From 4ec6b5ab8647f0baa2ea67a8b4c2e1a885e7134e Mon Sep 17 00:00:00 2001 From: v0 Date: Fri, 31 Jul 2026 18:11:29 +0000 Subject: [PATCH 1/3] =?UTF-8?q?=F0=9F=94=A7=20fix:=20restore=20pnpm=20buil?= =?UTF-8?q?d?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Add missing server/src/types/express.d.ts (Request.actor augmentation) - Cast hermes listSkills/syncSkills at the adapter-utils type boundary - Replace nonexistent lucide Taskcore icon with local TaskcoreIcon component - Un-ignore server/src/types/express.d.ts so clones can build --- .gitignore | 1 + server/src/adapters/registry.ts | 4 +-- server/src/types/express.d.ts | 36 +++++++++++++++++++++++++++ ui/src/components/CommentThread.tsx | 5 ++-- ui/src/components/CompanyRail.tsx | 5 ++-- ui/src/components/IssueChatThread.tsx | 5 ++-- ui/src/components/NewIssueDialog.tsx | 6 ++--- ui/src/components/TaskcoreIcon.tsx | 21 ++++++++++++++++ ui/src/pages/CompanySkills.tsx | 4 +-- ui/src/pages/IssueDetail.tsx | 4 +-- 10 files changed, 76 insertions(+), 15 deletions(-) create mode 100644 server/src/types/express.d.ts create mode 100644 ui/src/components/TaskcoreIcon.tsx diff --git a/.gitignore b/.gitignore index 0425a0f..507c082 100644 --- a/.gitignore +++ b/.gitignore @@ -29,6 +29,7 @@ cli/package.dev.json server/src/**/*.js server/src/**/*.js.map server/src/**/*.d.ts +!server/src/types/express.d.ts server/src/**/*.d.ts.map tmp/ feedback-export-* diff --git a/server/src/adapters/registry.ts b/server/src/adapters/registry.ts index 44bb576..8518b06 100644 --- a/server/src/adapters/registry.ts +++ b/server/src/adapters/registry.ts @@ -185,8 +185,8 @@ const hermesLocalAdapter: ServerAdapterModule = { execute: hermesExecute, testEnvironment: hermesTestEnvironment, sessionCodec: hermesSessionCodec, - listSkills: hermesListSkills, - syncSkills: hermesSyncSkills, + listSkills: hermesListSkills as unknown as ServerAdapterModule["listSkills"], + syncSkills: hermesSyncSkills as unknown as ServerAdapterModule["syncSkills"], models: hermesModels, supportsLocalAgentJwt: true, agentConfigurationDoc: hermesAgentConfigurationDoc, diff --git a/server/src/types/express.d.ts b/server/src/types/express.d.ts new file mode 100644 index 0000000..56a493e --- /dev/null +++ b/server/src/types/express.d.ts @@ -0,0 +1,36 @@ +// Express Request augmentation for the request actor resolved by +// `actorMiddleware` in `src/middleware/auth.ts`. +// +// The actor is attached to every request before route handlers run and is the +// single source of truth for "who is making this request" (board user, agent, +// or none). Company scoping and permission checks read this property. + +declare global { + namespace Express { + interface Request { + actor: RequestActor; + } + } +} + +type RequestActorSource = + | "local_implicit" + | "session" + | "board_key" + | "agent_jwt" + | "agent_key" + | "none"; + +type RequestActor = { + type: "board" | "agent" | "none"; + source: RequestActorSource; + userId?: string; + agentId?: string; + companyId?: string; + companyIds?: string[]; + isInstanceAdmin?: boolean; + keyId?: string; + runId?: string; +}; + +export {}; diff --git a/ui/src/components/CommentThread.tsx b/ui/src/components/CommentThread.tsx index db912f4..b88db80 100644 --- a/ui/src/components/CommentThread.tsx +++ b/ui/src/components/CommentThread.tsx @@ -9,7 +9,8 @@ import type { IssueComment, } from "@taskcore/shared"; import { Button } from "@/components/ui/button"; -import { ArrowRight, Check, Copy, Taskcore } from "lucide-react"; +import { ArrowRight, Check, Copy } from "lucide-react"; +import { TaskcoreIcon } from "./TaskcoreIcon"; import { Avatar, AvatarFallback } from "@/components/ui/avatar"; import { Identity } from "./Identity"; import { InlineEntitySelector, type InlineEntityOption } from "./InlineEntitySelector"; @@ -938,7 +939,7 @@ export function CommentThread({ disabled={attaching} title="Attach image" > - + )} diff --git a/ui/src/components/CompanyRail.tsx b/ui/src/components/CompanyRail.tsx index 6c04671..21a5cde 100644 --- a/ui/src/components/CompanyRail.tsx +++ b/ui/src/components/CompanyRail.tsx @@ -1,5 +1,6 @@ import { useCallback, useMemo } from "react"; -import { Taskcore, Plus } from "lucide-react"; +import { Plus } from "lucide-react"; +import { TaskcoreIcon } from "./TaskcoreIcon"; import { useQueries, useQuery } from "@tanstack/react-query"; import { DndContext, @@ -202,7 +203,7 @@ export function CompanyRail() {
{/* Taskcore icon - aligned with top sections (implied line, no visible border) */}
- +
{/* Company list */} diff --git a/ui/src/components/IssueChatThread.tsx b/ui/src/components/IssueChatThread.tsx index f147dbf..67d6c1f 100644 --- a/ui/src/components/IssueChatThread.tsx +++ b/ui/src/components/IssueChatThread.tsx @@ -88,7 +88,8 @@ import { cn, formatDateTime, formatShortDate } from "../lib/utils"; import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"; import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"; import { Textarea } from "@/components/ui/textarea"; -import { AlertTriangle, ArrowRight, Brain, Check, ChevronDown, Copy, Hammer, Loader2, MoreHorizontal, Taskcore, Search, Square, ThumbsDown, ThumbsUp } from "lucide-react"; +import { AlertTriangle, ArrowRight, Brain, Check, ChevronDown, Copy, Hammer, Loader2, MoreHorizontal, Search, Square, ThumbsDown, ThumbsUp } from "lucide-react"; +import { TaskcoreIcon } from "./TaskcoreIcon"; interface IssueChatMessageContext { feedbackVoteByTargetId: Map; @@ -1789,7 +1790,7 @@ const IssueChatComposer = forwardRef - +
) : null} diff --git a/ui/src/components/NewIssueDialog.tsx b/ui/src/components/NewIssueDialog.tsx index 7f3664c..4be2489 100644 --- a/ui/src/components/NewIssueDialog.tsx +++ b/ui/src/components/NewIssueDialog.tsx @@ -44,7 +44,6 @@ import { AlertTriangle, Tag, Calendar, - Taskcore, FileText, Loader2, ListTree, @@ -58,6 +57,7 @@ import { issueStatusText, issueStatusTextDefault, priorityColor, priorityColorDe import { MarkdownEditor, type MarkdownEditorRef, type MentionOption } from "./MarkdownEditor"; import { AgentIcon } from "./AgentIconPicker"; import { InlineEntitySelector, type InlineEntityOption } from "./InlineEntitySelector"; +import { TaskcoreIcon } from "./TaskcoreIcon"; const DRAFT_KEY = "taskcore:issue-draft"; const DEBOUNCE_MS = 800; @@ -1525,7 +1525,7 @@ export function NewIssueDialog() {
- + {file.file.name}
@@ -1632,7 +1632,7 @@ export function NewIssueDialog() { onClick={() => stageFileInputRef.current?.click()} disabled={createIssue.isPending} > - + Upload diff --git a/ui/src/components/TaskcoreIcon.tsx b/ui/src/components/TaskcoreIcon.tsx new file mode 100644 index 0000000..91079cd --- /dev/null +++ b/ui/src/components/TaskcoreIcon.tsx @@ -0,0 +1,21 @@ +import { cn } from "../lib/utils"; + +interface TaskcoreIconProps { + className?: string; +} + +export function TaskcoreIcon({ className }: TaskcoreIconProps) { + return ( + + + + ); +} diff --git a/ui/src/pages/CompanySkills.tsx b/ui/src/pages/CompanySkills.tsx index 4af4bcb..780482a 100644 --- a/ui/src/pages/CompanySkills.tsx +++ b/ui/src/pages/CompanySkills.tsx @@ -46,7 +46,6 @@ import { Github, Link2, ExternalLink, - Taskcore, Pencil, Plus, RefreshCw, @@ -54,6 +53,7 @@ import { Search, Trash2, } from "lucide-react"; +import { TaskcoreIcon } from "../components/TaskcoreIcon"; type SkillTreeNode = { name: string; @@ -160,7 +160,7 @@ function sourceMeta(sourceBadge: CompanySkillSourceBadge, sourceLabel: string | case "local": return { icon: Folder, label: sourceLabel ?? "Folder", managedLabel: "Folder managed" }; case "taskcore": - return { icon: Taskcore, label: sourceLabel ?? "Taskcore", managedLabel: "Taskcore managed" }; + return { icon: TaskcoreIcon, label: sourceLabel ?? "Taskcore", managedLabel: "Taskcore managed" }; default: return { icon: Boxes, label: sourceLabel ?? "Catalog", managedLabel: "Catalog managed" }; } diff --git a/ui/src/pages/IssueDetail.tsx b/ui/src/pages/IssueDetail.tsx index a4909c1..7d49f35 100644 --- a/ui/src/pages/IssueDetail.tsx +++ b/ui/src/pages/IssueDetail.tsx @@ -91,12 +91,12 @@ import { MessageSquare, MoreHorizontal, MoreVertical, - Taskcore, Plus, Repeat, SlidersHorizontal, Trash2, } from "lucide-react"; +import { TaskcoreIcon } from "../components/TaskcoreIcon"; import { getClosedIsolatedExecutionWorkspaceMessage, isClosedIsolatedExecutionWorkspace, @@ -2094,7 +2094,7 @@ export function IssueDetail() { attachmentDragActive && "border-primary bg-primary/5", )} > - + {uploadAttachment.isPending || importMarkdownDocument.isPending ? "Uploading..." : ( <> Upload attachment From b3ea18a445c82ce8fa7cc3f55f48f25bc7892525 Mon Sep 17 00:00:00 2001 From: v0 Date: Fri, 31 Jul 2026 18:46:00 +0000 Subject: [PATCH 2/3] =?UTF-8?q?=F0=9F=9A=80=20feat:=20add=20Vercel=20serve?= =?UTF-8?q?rless=20deployment=20support?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - add serverless entry (server/src/vercel.ts) with Vercel runtime defaults and config guards - bundle server into a single ESM function via scripts/build-vercel-function.mjs - support Vercel Postgres/RDS env conventions (POSTGRES_URL, PGHOST/...) - stdout-only logging and disable plugins/background jobs in serverless runtime - allow overriding DB pool options (max, prepare) for bounded serverless connections --- api/index.js | 220289 ++++++++++++++++++++++ packages/db/src/client.ts | 12 +- packages/db/src/runtime-config.ts | 3 +- packages/shared/src/index.ts | 1 + packages/shared/src/vercel-postgres.ts | 38 + scripts/build-vercel-function.mjs | 69 + server/src/app.ts | 35 +- server/src/config.ts | 3 +- server/src/middleware/logger.ts | 47 +- server/src/vercel.ts | 164 + server/src/version.ts | 15 +- 11 files changed, 220634 insertions(+), 42 deletions(-) create mode 100644 api/index.js create mode 100644 packages/shared/src/vercel-postgres.ts create mode 100644 scripts/build-vercel-function.mjs create mode 100644 server/src/vercel.ts diff --git a/api/index.js b/api/index.js new file mode 100644 index 0000000..4bdd72c --- /dev/null +++ b/api/index.js @@ -0,0 +1,220289 @@ +/* Taskcore Vercel serverless bundle. Generated by scripts/build-vercel-function.mjs - do not edit. */ +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __require = /* @__PURE__ */ ((x5) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x5, { + get: (a5, b6) => (typeof require !== "undefined" ? require : a5)[b6] +}) : x5)(function(x5) { + if (typeof require !== "undefined") return require.apply(this, arguments); + throw Error('Dynamic require of "' + x5 + '" is not supported'); +}); +var __esm = (fn, res) => function __init() { + return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res; +}; +var __commonJS = (cb, mod) => function __require2() { + return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; +}; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except2, desc3) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except2) + __defProp(to, key, { get: () => from[key], enumerable: !(desc3 = __getOwnPropDesc(from, key)) || desc3.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// node_modules/.pnpm/postgres@3.4.9/node_modules/postgres/src/query.js +function cachedError(xs) { + if (originCache.has(xs)) + return originCache.get(xs); + const x5 = Error.stackTraceLimit; + Error.stackTraceLimit = 4; + originCache.set(xs, new Error()); + Error.stackTraceLimit = x5; + return originCache.get(xs); +} +var originCache, originStackCache, originError, CLOSE, Query; +var init_query = __esm({ + "node_modules/.pnpm/postgres@3.4.9/node_modules/postgres/src/query.js"() { + originCache = /* @__PURE__ */ new Map(); + originStackCache = /* @__PURE__ */ new Map(); + originError = /* @__PURE__ */ Symbol("OriginError"); + CLOSE = {}; + Query = class extends Promise { + constructor(strings, args, handler, canceller, options = {}) { + let resolve4, reject; + super((a5, b6) => { + resolve4 = a5; + reject = b6; + }); + this.tagged = Array.isArray(strings.raw); + this.strings = strings; + this.args = args; + this.handler = handler; + this.canceller = canceller; + this.options = options; + this.state = null; + this.statement = null; + this.resolve = (x5) => (this.active = false, resolve4(x5)); + this.reject = (x5) => (this.active = false, reject(x5)); + this.active = false; + this.cancelled = null; + this.executed = false; + this.signature = ""; + this[originError] = this.handler.debug ? new Error() : this.tagged && cachedError(this.strings); + } + get origin() { + return (this.handler.debug ? this[originError].stack : this.tagged && originStackCache.has(this.strings) ? originStackCache.get(this.strings) : originStackCache.set(this.strings, this[originError].stack).get(this.strings)) || ""; + } + static get [Symbol.species]() { + return Promise; + } + cancel() { + return this.canceller && (this.canceller(this), this.canceller = null); + } + simple() { + this.options.simple = true; + this.options.prepare = false; + return this; + } + async readable() { + this.simple(); + this.streaming = true; + return this; + } + async writable() { + this.simple(); + this.streaming = true; + return this; + } + cursor(rows = 1, fn) { + this.options.simple = false; + if (typeof rows === "function") { + fn = rows; + rows = 1; + } + this.cursorRows = rows; + if (typeof fn === "function") + return this.cursorFn = fn, this; + let prev; + return { + [Symbol.asyncIterator]: () => ({ + next: () => { + if (this.executed && !this.active) + return { done: true }; + prev && prev(); + const promise2 = new Promise((resolve4, reject) => { + this.cursorFn = (value) => { + resolve4({ value, done: false }); + return new Promise((r5) => prev = r5); + }; + this.resolve = () => (this.active = false, resolve4({ done: true })); + this.reject = (x5) => (this.active = false, reject(x5)); + }); + this.execute(); + return promise2; + }, + return() { + prev && prev(CLOSE); + return { done: true }; + } + }) + }; + } + describe() { + this.options.simple = false; + this.onlyDescribe = this.options.prepare = true; + return this; + } + stream() { + throw new Error(".stream has been renamed to .forEach"); + } + forEach(fn) { + this.forEachFn = fn; + this.handle(); + return this; + } + raw() { + this.isRaw = true; + return this; + } + values() { + this.isRaw = "values"; + return this; + } + async handle() { + !this.executed && (this.executed = true) && await 1 && this.handler(this); + } + execute() { + this.handle(); + return this; + } + then() { + this.handle(); + return super.then.apply(this, arguments); + } + catch() { + this.handle(); + return super.catch.apply(this, arguments); + } + finally() { + this.handle(); + return super.finally.apply(this, arguments); + } + }; + } +}); + +// node_modules/.pnpm/postgres@3.4.9/node_modules/postgres/src/errors.js +function connection(x5, options, socket) { + const { host, port } = socket || options; + const error50 = Object.assign( + new Error("write " + x5 + " " + (options.path || host + ":" + port)), + { + code: x5, + errno: x5, + address: options.path || host + }, + options.path ? {} : { port } + ); + Error.captureStackTrace(error50, connection); + return error50; +} +function postgres(x5) { + const error50 = new PostgresError(x5); + Error.captureStackTrace(error50, postgres); + return error50; +} +function generic(code, message2) { + const error50 = Object.assign(new Error(code + ": " + message2), { code }); + Error.captureStackTrace(error50, generic); + return error50; +} +function notSupported(x5) { + const error50 = Object.assign( + new Error(x5 + " (B) is not supported"), + { + code: "MESSAGE_NOT_SUPPORTED", + name: x5 + } + ); + Error.captureStackTrace(error50, notSupported); + return error50; +} +var PostgresError, Errors; +var init_errors = __esm({ + "node_modules/.pnpm/postgres@3.4.9/node_modules/postgres/src/errors.js"() { + PostgresError = class extends Error { + constructor(x5) { + super(x5.message); + this.name = this.constructor.name; + Object.assign(this, x5); + } + }; + Errors = { + connection, + postgres, + generic, + notSupported + }; + } +}); + +// node_modules/.pnpm/postgres@3.4.9/node_modules/postgres/src/types.js +function handleValue(x5, parameters, types2, options) { + let value = x5 instanceof Parameter ? x5.value : x5; + if (value === void 0) { + x5 instanceof Parameter ? x5.value = options.transform.undefined : value = x5 = options.transform.undefined; + if (value === void 0) + throw Errors.generic("UNDEFINED_VALUE", "Undefined values are not allowed"); + } + return "$" + types2.push( + x5 instanceof Parameter ? (parameters.push(x5.value), x5.array ? x5.array[x5.type || inferType(x5.value)] || x5.type || firstIsString(x5.value) : x5.type) : (parameters.push(x5), inferType(x5)) + ); +} +function stringify(q5, string4, value, parameters, types2, options) { + for (let i5 = 1; i5 < q5.strings.length; i5++) { + string4 += stringifyValue(string4, value, parameters, types2, options) + q5.strings[i5]; + value = q5.args[i5]; + } + return string4; +} +function stringifyValue(string4, value, parameters, types2, o5) { + return value instanceof Builder ? value.build(string4, parameters, types2, o5) : value instanceof Query ? fragment(value, parameters, types2, o5) : value instanceof Identifier ? value.value : value && value[0] instanceof Query ? value.reduce((acc, x5) => acc + " " + fragment(x5, parameters, types2, o5), "") : handleValue(value, parameters, types2, o5); +} +function fragment(q5, parameters, types2, options) { + q5.fragment = true; + return stringify(q5, q5.strings[0], q5.args[0], parameters, types2, options); +} +function valuesBuilder(first, parameters, types2, columns, options) { + return first.map( + (row) => "(" + columns.map( + (column) => stringifyValue("values", row[column], parameters, types2, options) + ).join(",") + ")" + ).join(","); +} +function values(first, rest, parameters, types2, options) { + const multi = Array.isArray(first[0]); + const columns = rest.length ? rest.flat() : Object.keys(multi ? first[0] : first); + return valuesBuilder(multi ? first : [first], parameters, types2, columns, options); +} +function select(first, rest, parameters, types2, options) { + typeof first === "string" && (first = [first].concat(rest)); + if (Array.isArray(first)) + return escapeIdentifiers(first, options); + let value; + const columns = rest.length ? rest.flat() : Object.keys(first); + return columns.map((x5) => { + value = first[x5]; + return (value instanceof Query ? fragment(value, parameters, types2, options) : value instanceof Identifier ? value.value : handleValue(value, parameters, types2, options)) + " as " + escapeIdentifier(options.transform.column.to ? options.transform.column.to(x5) : x5); + }).join(","); +} +function notTagged() { + throw Errors.generic("NOT_TAGGED_CALL", "Query not called as a tagged template literal"); +} +function firstIsString(x5) { + if (Array.isArray(x5)) + return firstIsString(x5[0]); + return typeof x5 === "string" ? 1009 : 0; +} +function typeHandlers(types2) { + return Object.keys(types2).reduce((acc, k5) => { + types2[k5].from && [].concat(types2[k5].from).forEach((x5) => acc.parsers[x5] = types2[k5].parse); + if (types2[k5].serialize) { + acc.serializers[types2[k5].to] = types2[k5].serialize; + types2[k5].from && [].concat(types2[k5].from).forEach((x5) => acc.serializers[x5] = types2[k5].serialize); + } + return acc; + }, { parsers: {}, serializers: {} }); +} +function escapeIdentifiers(xs, { transform: { column } }) { + return xs.map((x5) => escapeIdentifier(column.to ? column.to(x5) : x5)).join(","); +} +function arrayEscape(x5) { + return x5.replace(escapeBackslash, "\\\\").replace(escapeQuote, '\\"'); +} +function arrayParserLoop(s5, x5, parser, typarray) { + const xs = []; + const delimiter = typarray === 1020 ? ";" : ","; + for (; s5.i < x5.length; s5.i++) { + s5.char = x5[s5.i]; + if (s5.quoted) { + if (s5.char === "\\") { + s5.str += x5[++s5.i]; + } else if (s5.char === '"') { + xs.push(parser ? parser(s5.str) : s5.str); + s5.str = ""; + s5.quoted = x5[s5.i + 1] === '"'; + s5.last = s5.i + 2; + } else { + s5.str += s5.char; + } + } else if (s5.char === '"') { + s5.quoted = true; + } else if (s5.char === "{") { + s5.last = ++s5.i; + xs.push(arrayParserLoop(s5, x5, parser, typarray)); + } else if (s5.char === "}") { + s5.quoted = false; + s5.last < s5.i && xs.push(parser ? parser(x5.slice(s5.last, s5.i)) : x5.slice(s5.last, s5.i)); + s5.last = s5.i + 1; + break; + } else if (s5.char === delimiter && s5.p !== "}" && s5.p !== '"') { + xs.push(parser ? parser(x5.slice(s5.last, s5.i)) : x5.slice(s5.last, s5.i)); + s5.last = s5.i + 1; + } + s5.p = s5.char; + } + s5.last < s5.i && xs.push(parser ? parser(x5.slice(s5.last, s5.i + 1)) : x5.slice(s5.last, s5.i + 1)); + return xs; +} +function createJsonTransform(fn) { + return function jsonTransform(x5, column) { + return typeof x5 === "object" && x5 !== null && (column.type === 114 || column.type === 3802) ? Array.isArray(x5) ? x5.map((x6) => jsonTransform(x6, column)) : Object.entries(x5).reduce((acc, [k5, v5]) => Object.assign(acc, { [fn(k5)]: jsonTransform(v5, column) }), {}) : x5; + }; +} +var types, NotTagged, Identifier, Parameter, Builder, defaultHandlers, builders, serializers, parsers, mergeUserTypes, escapeIdentifier, inferType, escapeBackslash, escapeQuote, arraySerializer, arrayParserState, arrayParser, toCamel, toPascal, toKebab, fromCamel, fromPascal, fromKebab, camel, pascal, kebab; +var init_types = __esm({ + "node_modules/.pnpm/postgres@3.4.9/node_modules/postgres/src/types.js"() { + init_query(); + init_errors(); + types = { + string: { + to: 25, + from: null, + // defaults to string + serialize: (x5) => "" + x5 + }, + number: { + to: 0, + from: [21, 23, 26, 700, 701], + serialize: (x5) => "" + x5, + parse: (x5) => +x5 + }, + json: { + to: 114, + from: [114, 3802], + serialize: (x5) => JSON.stringify(x5), + parse: (x5) => JSON.parse(x5) + }, + boolean: { + to: 16, + from: 16, + serialize: (x5) => x5 === true ? "t" : "f", + parse: (x5) => x5 === "t" + }, + date: { + to: 1184, + from: [1082, 1114, 1184], + serialize: (x5) => (x5 instanceof Date ? x5 : new Date(x5)).toISOString(), + parse: (x5) => new Date(x5) + }, + bytea: { + to: 17, + from: 17, + serialize: (x5) => "\\x" + Buffer.from(x5).toString("hex"), + parse: (x5) => Buffer.from(x5.slice(2), "hex") + } + }; + NotTagged = class { + then() { + notTagged(); + } + catch() { + notTagged(); + } + finally() { + notTagged(); + } + }; + Identifier = class extends NotTagged { + constructor(value) { + super(); + this.value = escapeIdentifier(value); + } + }; + Parameter = class extends NotTagged { + constructor(value, type, array2) { + super(); + this.value = value; + this.type = type; + this.array = array2; + } + }; + Builder = class extends NotTagged { + constructor(first, rest) { + super(); + this.first = first; + this.rest = rest; + } + build(before, parameters, types2, options) { + const keyword = builders.map(([x5, fn]) => ({ fn, i: before.search(x5) })).sort((a5, b6) => a5.i - b6.i).pop(); + return keyword.i === -1 ? escapeIdentifiers(this.first, options) : keyword.fn(this.first, this.rest, parameters, types2, options); + } + }; + defaultHandlers = typeHandlers(types); + builders = Object.entries({ + values, + in: (...xs) => { + const x5 = values(...xs); + return x5 === "()" ? "(null)" : x5; + }, + select, + as: select, + returning: select, + "\\(": select, + update(first, rest, parameters, types2, options) { + return (rest.length ? rest.flat() : Object.keys(first)).map( + (x5) => escapeIdentifier(options.transform.column.to ? options.transform.column.to(x5) : x5) + "=" + stringifyValue("values", first[x5], parameters, types2, options) + ); + }, + insert(first, rest, parameters, types2, options) { + const columns = rest.length ? rest.flat() : Object.keys(Array.isArray(first) ? first[0] : first); + return "(" + escapeIdentifiers(columns, options) + ")values" + valuesBuilder(Array.isArray(first) ? first : [first], parameters, types2, columns, options); + } + }).map(([x5, fn]) => [new RegExp("((?:^|[\\s(])" + x5 + "(?:$|[\\s(]))(?![\\s\\S]*\\1)", "i"), fn]); + serializers = defaultHandlers.serializers; + parsers = defaultHandlers.parsers; + mergeUserTypes = function(types2) { + const user = typeHandlers(types2 || {}); + return { + serializers: Object.assign({}, serializers, user.serializers), + parsers: Object.assign({}, parsers, user.parsers) + }; + }; + escapeIdentifier = function escape2(str) { + return '"' + str.replace(/"/g, '""').replace(/\./g, '"."') + '"'; + }; + inferType = function inferType2(x5) { + return x5 instanceof Parameter ? x5.type : x5 instanceof Date ? 1184 : x5 instanceof Uint8Array ? 17 : x5 === true || x5 === false ? 16 : typeof x5 === "bigint" ? 20 : Array.isArray(x5) ? inferType2(x5[0]) : 0; + }; + escapeBackslash = /\\/g; + escapeQuote = /"/g; + arraySerializer = function arraySerializer2(xs, serializer, options, typarray) { + if (Array.isArray(xs) === false) + return xs; + if (!xs.length) + return "{}"; + const first = xs[0]; + const delimiter = typarray === 1020 ? ";" : ","; + if (Array.isArray(first) && !first.type) + return "{" + xs.map((x5) => arraySerializer2(x5, serializer, options, typarray)).join(delimiter) + "}"; + return "{" + xs.map((x5) => { + if (x5 === void 0) { + x5 = options.transform.undefined; + if (x5 === void 0) + throw Errors.generic("UNDEFINED_VALUE", "Undefined values are not allowed"); + } + return x5 === null ? "null" : '"' + arrayEscape(serializer ? serializer(x5.type ? x5.value : x5) : "" + x5) + '"'; + }).join(delimiter) + "}"; + }; + arrayParserState = { + i: 0, + char: null, + str: "", + quoted: false, + last: 0 + }; + arrayParser = function arrayParser2(x5, parser, typarray) { + arrayParserState.i = arrayParserState.last = 0; + return arrayParserLoop(arrayParserState, x5, parser, typarray); + }; + toCamel = (x5) => { + let str = x5[0]; + for (let i5 = 1; i5 < x5.length; i5++) + str += x5[i5] === "_" ? x5[++i5].toUpperCase() : x5[i5]; + return str; + }; + toPascal = (x5) => { + let str = x5[0].toUpperCase(); + for (let i5 = 1; i5 < x5.length; i5++) + str += x5[i5] === "_" ? x5[++i5].toUpperCase() : x5[i5]; + return str; + }; + toKebab = (x5) => x5.replace(/_/g, "-"); + fromCamel = (x5) => x5.replace(/([A-Z])/g, "_$1").toLowerCase(); + fromPascal = (x5) => (x5.slice(0, 1) + x5.slice(1).replace(/([A-Z])/g, "_$1")).toLowerCase(); + fromKebab = (x5) => x5.replace(/-/g, "_"); + toCamel.column = { from: toCamel }; + toCamel.value = { from: createJsonTransform(toCamel) }; + fromCamel.column = { to: fromCamel }; + camel = { ...toCamel }; + camel.column.to = fromCamel; + toPascal.column = { from: toPascal }; + toPascal.value = { from: createJsonTransform(toPascal) }; + fromPascal.column = { to: fromPascal }; + pascal = { ...toPascal }; + pascal.column.to = fromPascal; + toKebab.column = { from: toKebab }; + toKebab.value = { from: createJsonTransform(toKebab) }; + fromKebab.column = { to: fromKebab }; + kebab = { ...toKebab }; + kebab.column.to = fromKebab; + } +}); + +// node_modules/.pnpm/postgres@3.4.9/node_modules/postgres/src/result.js +var Result; +var init_result = __esm({ + "node_modules/.pnpm/postgres@3.4.9/node_modules/postgres/src/result.js"() { + Result = class extends Array { + constructor() { + super(); + Object.defineProperties(this, { + count: { value: null, writable: true }, + state: { value: null, writable: true }, + command: { value: null, writable: true }, + columns: { value: null, writable: true }, + statement: { value: null, writable: true } + }); + } + static get [Symbol.species]() { + return Array; + } + }; + } +}); + +// node_modules/.pnpm/postgres@3.4.9/node_modules/postgres/src/queue.js +function Queue(initial = []) { + let xs = initial.slice(); + let index2 = 0; + return { + get length() { + return xs.length - index2; + }, + remove: (x5) => { + const index3 = xs.indexOf(x5); + return index3 === -1 ? null : (xs.splice(index3, 1), x5); + }, + push: (x5) => (xs.push(x5), x5), + shift: () => { + const out = xs[index2++]; + if (index2 === xs.length) { + index2 = 0; + xs = []; + } else { + xs[index2 - 1] = void 0; + } + return out; + } + }; +} +var queue_default; +var init_queue = __esm({ + "node_modules/.pnpm/postgres@3.4.9/node_modules/postgres/src/queue.js"() { + queue_default = Queue; + } +}); + +// node_modules/.pnpm/postgres@3.4.9/node_modules/postgres/src/bytes.js +function fit(x5) { + if (buffer.length - b.i < x5) { + const prev = buffer, length = prev.length; + buffer = Buffer.allocUnsafe(length + (length >> 1) + x5); + prev.copy(buffer); + } +} +function reset() { + b.i = 0; + return b; +} +var size, buffer, messages, b, bytes_default; +var init_bytes = __esm({ + "node_modules/.pnpm/postgres@3.4.9/node_modules/postgres/src/bytes.js"() { + size = 256; + buffer = Buffer.allocUnsafe(size); + messages = "BCcDdEFfHPpQSX".split("").reduce((acc, x5) => { + const v5 = x5.charCodeAt(0); + acc[x5] = () => { + buffer[0] = v5; + b.i = 5; + return b; + }; + return acc; + }, {}); + b = Object.assign(reset, messages, { + N: String.fromCharCode(0), + i: 0, + inc(x5) { + b.i += x5; + return b; + }, + str(x5) { + const length = Buffer.byteLength(x5); + fit(length); + b.i += buffer.write(x5, b.i, length, "utf8"); + return b; + }, + i16(x5) { + fit(2); + buffer.writeUInt16BE(x5, b.i); + b.i += 2; + return b; + }, + i32(x5, i5) { + if (i5 || i5 === 0) { + buffer.writeUInt32BE(x5, i5); + return b; + } + fit(4); + buffer.writeUInt32BE(x5, b.i); + b.i += 4; + return b; + }, + z(x5) { + fit(x5); + buffer.fill(0, b.i, b.i + x5); + b.i += x5; + return b; + }, + raw(x5) { + buffer = Buffer.concat([buffer.subarray(0, b.i), x5]); + b.i = buffer.length; + return b; + }, + end(at = 1) { + buffer.writeUInt32BE(b.i - at, at); + const out = buffer.subarray(0, b.i); + b.i = 0; + buffer = Buffer.allocUnsafe(size); + return out; + } + }); + bytes_default = b; + } +}); + +// node_modules/.pnpm/postgres@3.4.9/node_modules/postgres/src/connection.js +import net from "net"; +import tls from "tls"; +import crypto2 from "crypto"; +import Stream from "stream"; +import { performance as performance2 } from "perf_hooks"; +function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose = noop } = {}) { + const { + sslnegotiation, + ssl, + max, + user, + host, + port, + database, + parsers: parsers2, + transform: transform3, + onnotice, + onnotify, + onparameter, + max_pipeline, + keep_alive, + backoff: backoff2, + target_session_attrs + } = options; + const sent = queue_default(), id = uid++, backend = { pid: null, secret: null }, idleTimer = timer(end, options.idle_timeout), lifeTimer = timer(end, options.max_lifetime), connectTimer = timer(connectTimedOut, options.connect_timeout); + let socket = null, cancelMessage, errorResponse = null, result = new Result(), incoming = Buffer.alloc(0), needsTypes = options.fetch_types, backendParameters = {}, statements = {}, statementId = Math.random().toString(36).slice(2), statementCount = 1, closedTime = 0, remaining = 0, hostIndex = 0, retries = 0, length = 0, delay3 = 0, rows = 0, serverSignature = null, nextWriteTimer = null, terminated = false, incomings = null, results = null, initial = null, ending = null, stream = null, chunk = null, ended = null, nonce = null, query = null, final = null; + const connection2 = { + queue: queues.closed, + idleTimer, + connect(query2) { + initial = query2; + reconnect(); + }, + terminate, + execute: execute11, + cancel, + end, + count: 0, + id + }; + queues.closed && queues.closed.push(connection2); + return connection2; + async function createSocket() { + let x5; + try { + x5 = options.socket ? await Promise.resolve(options.socket(options)) : new net.Socket(); + } catch (e5) { + error50(e5); + return; + } + x5.on("error", error50); + x5.on("close", closed); + x5.on("drain", drain); + return x5; + } + async function cancel({ pid, secret }, resolve4, reject) { + try { + cancelMessage = bytes_default().i32(16).i32(80877102).i32(pid).i32(secret).end(16); + await connect(); + socket.once("error", reject); + socket.once("close", resolve4); + } catch (error51) { + reject(error51); + } + } + function execute11(q5) { + if (terminated) + return queryError(q5, Errors.connection("CONNECTION_DESTROYED", options)); + if (stream) + return queryError(q5, Errors.generic("COPY_IN_PROGRESS", "You cannot execute queries during copy")); + if (q5.cancelled) + return; + try { + q5.state = backend; + query ? sent.push(q5) : (query = q5, query.active = true); + build(q5); + return write(toBuffer(q5)) && !q5.describeFirst && !q5.cursorFn && sent.length < max_pipeline && (!q5.options.onexecute || q5.options.onexecute(connection2)); + } catch (error51) { + sent.length === 0 && write(Sync); + errored(error51); + return true; + } + } + function toBuffer(q5) { + if (q5.parameters.length >= 65534) + throw Errors.generic("MAX_PARAMETERS_EXCEEDED", "Max number of parameters (65534) exceeded"); + return q5.options.simple ? bytes_default().Q().str(q5.statement.string + bytes_default.N).end() : q5.describeFirst ? Buffer.concat([describe3(q5), Flush]) : q5.prepare ? q5.prepared ? prepared(q5) : Buffer.concat([describe3(q5), prepared(q5)]) : unnamed(q5); + } + function describe3(q5) { + return Buffer.concat([ + Parse(q5.statement.string, q5.parameters, q5.statement.types, q5.statement.name), + Describe("S", q5.statement.name) + ]); + } + function prepared(q5) { + return Buffer.concat([ + Bind(q5.parameters, q5.statement.types, q5.statement.name, q5.cursorName), + q5.cursorFn ? Execute("", q5.cursorRows) : ExecuteUnnamed + ]); + } + function unnamed(q5) { + return Buffer.concat([ + Parse(q5.statement.string, q5.parameters, q5.statement.types), + DescribeUnnamed, + prepared(q5) + ]); + } + function build(q5) { + const parameters = [], types2 = []; + const string4 = stringify(q5, q5.strings[0], q5.args[0], parameters, types2, options); + !q5.tagged && q5.args.forEach((x5) => handleValue(x5, parameters, types2, options)); + q5.prepare = options.prepare && ("prepare" in q5.options ? q5.options.prepare : true); + q5.string = string4; + q5.signature = q5.prepare && types2 + string4; + q5.onlyDescribe && delete statements[q5.signature]; + q5.parameters = q5.parameters || parameters; + q5.prepared = q5.prepare && q5.signature in statements; + q5.describeFirst = q5.onlyDescribe || parameters.length && !q5.prepared; + q5.statement = q5.prepared ? statements[q5.signature] : { string: string4, types: types2, name: q5.prepare ? statementId + statementCount++ : "" }; + typeof options.debug === "function" && options.debug(id, string4, parameters, types2); + } + function write(x5, fn) { + chunk = chunk ? Buffer.concat([chunk, x5]) : Buffer.from(x5); + if (fn || chunk.length >= 1024) + return nextWrite(fn); + nextWriteTimer === null && (nextWriteTimer = setImmediate(nextWrite)); + return true; + } + function nextWrite(fn) { + const x5 = socket.write(chunk, fn); + nextWriteTimer !== null && clearImmediate(nextWriteTimer); + chunk = nextWriteTimer = null; + return x5; + } + function connectTimedOut() { + errored(Errors.connection("CONNECT_TIMEOUT", options, socket)); + socket.destroy(); + } + async function secure() { + if (sslnegotiation !== "direct") { + write(SSLRequest); + const canSSL = await new Promise((r5) => socket.once("data", (x5) => r5(x5[0] === 83))); + if (!canSSL && ssl === "prefer") + return connected(); + } + const options2 = { + socket, + servername: net.isIP(socket.host) ? void 0 : socket.host + }; + if (sslnegotiation === "direct") + options2.ALPNProtocols = ["postgresql"]; + if (ssl === "require" || ssl === "allow" || ssl === "prefer") + options2.rejectUnauthorized = false; + else if (typeof ssl === "object") + Object.assign(options2, ssl); + socket.removeAllListeners(); + socket = tls.connect(options2); + socket.on("secureConnect", connected); + socket.on("error", error50); + socket.on("close", closed); + socket.on("drain", drain); + } + function drain() { + !query && onopen(connection2); + } + function data2(x5) { + if (incomings) { + incomings.push(x5); + remaining -= x5.length; + if (remaining > 0) + return; + } + incoming = incomings ? Buffer.concat(incomings, length - remaining) : incoming.length === 0 ? x5 : Buffer.concat([incoming, x5], incoming.length + x5.length); + while (incoming.length > 4) { + length = incoming.readUInt32BE(1); + if (length >= incoming.length) { + remaining = length - incoming.length; + incomings = [incoming]; + break; + } + try { + handle(incoming.subarray(0, length + 1)); + } catch (e5) { + query && (query.cursorFn || query.describeFirst) && write(Sync); + errored(e5); + } + incoming = incoming.subarray(length + 1); + remaining = 0; + incomings = null; + } + } + async function connect() { + terminated = false; + backendParameters = {}; + socket || (socket = await createSocket()); + if (!socket) + return; + connectTimer.start(); + if (options.socket) + return ssl ? secure() : connected(); + socket.on("connect", ssl ? secure : connected); + if (options.path) + return socket.connect(options.path); + socket.ssl = ssl; + socket.connect(port[hostIndex], host[hostIndex]); + socket.host = host[hostIndex]; + socket.port = port[hostIndex]; + hostIndex = (hostIndex + 1) % port.length; + } + function reconnect() { + setTimeout(connect, closedTime ? Math.max(0, closedTime + delay3 - performance2.now()) : 0); + } + function connected() { + try { + statements = {}; + needsTypes = options.fetch_types; + statementId = Math.random().toString(36).slice(2); + statementCount = 1; + lifeTimer.start(); + socket.on("data", data2); + keep_alive && socket.setKeepAlive && socket.setKeepAlive(true, 1e3 * keep_alive); + const s5 = StartupMessage(); + write(s5); + } catch (err) { + error50(err); + } + } + function error50(err) { + if (connection2.queue === queues.connecting && options.host[retries + 1]) + return; + errored(err); + while (sent.length) + queryError(sent.shift(), err); + } + function errored(err) { + stream && (stream.destroy(err), stream = null); + query && queryError(query, err); + initial && (queryError(initial, err), initial = null); + } + function queryError(query2, err) { + if (query2.reserve) + return query2.reject(err); + if (!err || typeof err !== "object") + err = new Error(err); + "query" in err || "parameters" in err || Object.defineProperties(err, { + stack: { value: err.stack + query2.origin.replace(/.*\n/, "\n"), enumerable: options.debug }, + query: { value: query2.string, enumerable: options.debug }, + parameters: { value: query2.parameters, enumerable: options.debug }, + args: { value: query2.args, enumerable: options.debug }, + types: { value: query2.statement && query2.statement.types, enumerable: options.debug } + }); + query2.reject(err); + } + function end() { + return ending || (!connection2.reserved && onend(connection2), !connection2.reserved && !initial && !query && sent.length === 0 ? (terminate(), new Promise((r5) => socket && socket.readyState !== "closed" ? socket.once("close", r5) : r5())) : ending = new Promise((r5) => ended = r5)); + } + function terminate() { + terminated = true; + if (stream || query || initial || sent.length) + error50(Errors.connection("CONNECTION_DESTROYED", options)); + clearImmediate(nextWriteTimer); + if (socket) { + socket.removeListener("data", data2); + socket.removeListener("connect", connected); + socket.readyState === "open" && socket.end(bytes_default().X().end()); + } + ended && (ended(), ending = ended = null); + } + async function closed(hadError) { + incoming = Buffer.alloc(0); + remaining = 0; + incomings = null; + clearImmediate(nextWriteTimer); + socket.removeListener("data", data2); + socket.removeListener("connect", connected); + idleTimer.cancel(); + lifeTimer.cancel(); + connectTimer.cancel(); + socket.removeAllListeners(); + socket = null; + if (initial) + return reconnect(); + !hadError && (query || sent.length) && error50(Errors.connection("CONNECTION_CLOSED", options, socket)); + closedTime = performance2.now(); + hadError && options.shared.retries++; + delay3 = (typeof backoff2 === "function" ? backoff2(options.shared.retries) : backoff2) * 1e3; + onclose(connection2, Errors.connection("CONNECTION_CLOSED", options, socket)); + } + function handle(xs, x5 = xs[0]) { + (x5 === 68 ? DataRow : ( + // D + x5 === 100 ? CopyData : ( + // d + x5 === 65 ? NotificationResponse : ( + // A + x5 === 83 ? ParameterStatus : ( + // S + x5 === 90 ? ReadyForQuery : ( + // Z + x5 === 67 ? CommandComplete : ( + // C + x5 === 50 ? BindComplete : ( + // 2 + x5 === 49 ? ParseComplete : ( + // 1 + x5 === 116 ? ParameterDescription : ( + // t + x5 === 84 ? RowDescription : ( + // T + x5 === 82 ? Authentication : ( + // R + x5 === 110 ? NoData : ( + // n + x5 === 75 ? BackendKeyData : ( + // K + x5 === 69 ? ErrorResponse : ( + // E + x5 === 115 ? PortalSuspended : ( + // s + x5 === 51 ? CloseComplete : ( + // 3 + x5 === 71 ? CopyInResponse : ( + // G + x5 === 78 ? NoticeResponse : ( + // N + x5 === 72 ? CopyOutResponse : ( + // H + x5 === 99 ? CopyDone : ( + // c + x5 === 73 ? EmptyQueryResponse : ( + // I + x5 === 86 ? FunctionCallResponse : ( + // V + x5 === 118 ? NegotiateProtocolVersion : ( + // v + x5 === 87 ? CopyBothResponse : ( + // W + /* c8 ignore next */ + UnknownMessage + ) + ) + ) + ) + ) + ) + ) + ) + ) + ) + ) + ) + ) + ) + ) + ) + ) + ) + ) + ) + ) + ) + ) + ))(xs); + } + function DataRow(x5) { + let index2 = 7; + let length2; + let column; + let value; + const row = query.isRaw ? new Array(query.statement.columns.length) : {}; + for (let i5 = 0; i5 < query.statement.columns.length; i5++) { + column = query.statement.columns[i5]; + length2 = x5.readInt32BE(index2); + index2 += 4; + value = length2 === -1 ? null : query.isRaw === true ? x5.subarray(index2, index2 += length2) : column.parser === void 0 ? x5.toString("utf8", index2, index2 += length2) : column.parser.array === true ? column.parser(x5.toString("utf8", index2 + 1, index2 += length2)) : column.parser(x5.toString("utf8", index2, index2 += length2)); + query.isRaw ? row[i5] = query.isRaw === true ? value : transform3.value.from ? transform3.value.from(value, column) : value : row[column.name] = transform3.value.from ? transform3.value.from(value, column) : value; + } + query.forEachFn ? query.forEachFn(transform3.row.from ? transform3.row.from(row) : row, result) : result[rows++] = transform3.row.from ? transform3.row.from(row) : row; + } + function ParameterStatus(x5) { + const [k5, v5] = x5.toString("utf8", 5, x5.length - 1).split(bytes_default.N); + backendParameters[k5] = v5; + if (options.parameters[k5] !== v5) { + options.parameters[k5] = v5; + onparameter && onparameter(k5, v5); + } + } + function ReadyForQuery(x5) { + if (query) { + if (errorResponse) { + query.retried ? errored(query.retried) : query.prepared && retryRoutines.has(errorResponse.routine) ? retry(query, errorResponse) : errored(errorResponse); + } else { + query.resolve(results || result); + } + } else if (errorResponse) { + errored(errorResponse); + } + query = results = errorResponse = null; + result = new Result(); + connectTimer.cancel(); + if (initial) { + if (target_session_attrs) { + if (!backendParameters.in_hot_standby || !backendParameters.default_transaction_read_only) + return fetchState(); + else if (tryNext(target_session_attrs, backendParameters)) + return terminate(); + } + if (needsTypes) { + initial.reserve && (initial = null); + return fetchArrayTypes(); + } + initial && !initial.reserve && execute11(initial); + options.shared.retries = retries = 0; + initial = null; + return; + } + while (sent.length && (query = sent.shift()) && (query.active = true, query.cancelled)) + Connection(options).cancel(query.state, query.cancelled.resolve, query.cancelled.reject); + if (query) + return; + connection2.reserved ? !connection2.reserved.release && x5[5] === 73 ? ending ? terminate() : (connection2.reserved = null, onopen(connection2)) : connection2.reserved() : ending ? terminate() : onopen(connection2); + } + function CommandComplete(x5) { + rows = 0; + for (let i5 = x5.length - 1; i5 > 0; i5--) { + if (x5[i5] === 32 && x5[i5 + 1] < 58 && result.count === null) + result.count = +x5.toString("utf8", i5 + 1, x5.length - 1); + if (x5[i5 - 1] >= 65) { + result.command = x5.toString("utf8", 5, i5); + result.state = backend; + break; + } + } + final && (final(), final = null); + if (result.command === "BEGIN" && max !== 1 && !connection2.reserved) + return errored(Errors.generic("UNSAFE_TRANSACTION", "Only use sql.begin, sql.reserved or max: 1")); + if (query.options.simple) + return BindComplete(); + if (query.cursorFn) { + result.count && query.cursorFn(result); + write(Sync); + } + } + function ParseComplete() { + query.parsing = false; + } + function BindComplete() { + !result.statement && (result.statement = query.statement); + result.columns = query.statement.columns; + } + function ParameterDescription(x5) { + const length2 = x5.readUInt16BE(5); + for (let i5 = 0; i5 < length2; ++i5) + !query.statement.types[i5] && (query.statement.types[i5] = x5.readUInt32BE(7 + i5 * 4)); + query.prepare && (statements[query.signature] = query.statement); + query.describeFirst && !query.onlyDescribe && (write(prepared(query)), query.describeFirst = false); + } + function RowDescription(x5) { + if (result.command) { + results = results || [result]; + results.push(result = new Result()); + result.count = null; + query.statement.columns = null; + } + const length2 = x5.readUInt16BE(5); + let index2 = 7; + let start; + query.statement.columns = Array(length2); + for (let i5 = 0; i5 < length2; ++i5) { + start = index2; + while (x5[index2++] !== 0) ; + const table = x5.readUInt32BE(index2); + const number4 = x5.readUInt16BE(index2 + 4); + const type = x5.readUInt32BE(index2 + 6); + query.statement.columns[i5] = { + name: transform3.column.from ? transform3.column.from(x5.toString("utf8", start, index2 - 1)) : x5.toString("utf8", start, index2 - 1), + parser: parsers2[type], + table, + number: number4, + type + }; + index2 += 18; + } + result.statement = query.statement; + if (query.onlyDescribe) + return query.resolve(query.statement), write(Sync); + } + async function Authentication(x5, type = x5.readUInt32BE(5)) { + (type === 3 ? AuthenticationCleartextPassword : type === 5 ? AuthenticationMD5Password : type === 10 ? SASL : type === 11 ? SASLContinue : type === 12 ? SASLFinal : type !== 0 ? UnknownAuth : noop)(x5, type); + } + async function AuthenticationCleartextPassword() { + const payload2 = await Pass(); + write( + bytes_default().p().str(payload2).z(1).end() + ); + } + async function AuthenticationMD5Password(x5) { + const payload2 = "md5" + await md5( + Buffer.concat([ + Buffer.from(await md5(await Pass() + user)), + x5.subarray(9) + ]) + ); + write( + bytes_default().p().str(payload2).z(1).end() + ); + } + async function SASL() { + nonce = (await crypto2.randomBytes(18)).toString("base64"); + bytes_default().p().str("SCRAM-SHA-256" + bytes_default.N); + const i5 = bytes_default.i; + write(bytes_default.inc(4).str("n,,n=*,r=" + nonce).i32(bytes_default.i - i5 - 4, i5).end()); + } + async function SASLContinue(x5) { + const res = x5.toString("utf8", 9).split(",").reduce((acc, x6) => (acc[x6[0]] = x6.slice(2), acc), {}); + const saltedPassword = await crypto2.pbkdf2Sync( + await Pass(), + Buffer.from(res.s, "base64"), + parseInt(res.i), + 32, + "sha256" + ); + const clientKey = await hmac(saltedPassword, "Client Key"); + const auth = "n=*,r=" + nonce + ",r=" + res.r + ",s=" + res.s + ",i=" + res.i + ",c=biws,r=" + res.r; + serverSignature = (await hmac(await hmac(saltedPassword, "Server Key"), auth)).toString("base64"); + const payload2 = "c=biws,r=" + res.r + ",p=" + xor( + clientKey, + Buffer.from(await hmac(await sha256(clientKey), auth)) + ).toString("base64"); + write( + bytes_default().p().str(payload2).end() + ); + } + function SASLFinal(x5) { + if (x5.toString("utf8", 9).split(bytes_default.N, 1)[0].slice(2) === serverSignature) + return; + errored(Errors.generic("SASL_SIGNATURE_MISMATCH", "The server did not return the correct signature")); + socket.destroy(); + } + function Pass() { + return Promise.resolve( + typeof options.pass === "function" ? options.pass() : options.pass + ); + } + function NoData() { + result.statement = query.statement; + result.statement.columns = []; + if (query.onlyDescribe) + return query.resolve(query.statement), write(Sync); + } + function BackendKeyData(x5) { + backend.pid = x5.readUInt32BE(5); + backend.secret = x5.readUInt32BE(9); + } + async function fetchArrayTypes() { + needsTypes = false; + const types2 = await new Query([` + select b.oid, b.typarray + from pg_catalog.pg_type a + left join pg_catalog.pg_type b on b.oid = a.typelem + where a.typcategory = 'A' + group by b.oid, b.typarray + order by b.oid + `], [], execute11); + types2.forEach(({ oid, typarray }) => addArrayType(oid, typarray)); + } + function addArrayType(oid, typarray) { + if (!!options.parsers[typarray] && !!options.serializers[typarray]) return; + const parser = options.parsers[oid]; + options.shared.typeArrayMap[oid] = typarray; + options.parsers[typarray] = (xs) => arrayParser(xs, parser, typarray); + options.parsers[typarray].array = true; + options.serializers[typarray] = (xs) => arraySerializer(xs, options.serializers[oid], options, typarray); + } + function tryNext(x5, xs) { + return x5 === "read-write" && xs.default_transaction_read_only === "on" || x5 === "read-only" && xs.default_transaction_read_only === "off" || x5 === "primary" && xs.in_hot_standby === "on" || x5 === "standby" && xs.in_hot_standby === "off" || x5 === "prefer-standby" && xs.in_hot_standby === "off" && options.host[retries]; + } + function fetchState() { + const query2 = new Query([` + show transaction_read_only; + select pg_catalog.pg_is_in_recovery() + `], [], execute11, null, { simple: true }); + query2.resolve = ([[a5], [b6]]) => { + backendParameters.default_transaction_read_only = a5.transaction_read_only; + backendParameters.in_hot_standby = b6.pg_is_in_recovery ? "on" : "off"; + }; + query2.execute(); + } + function ErrorResponse(x5) { + if (query) { + (query.cursorFn || query.describeFirst) && write(Sync); + errorResponse = Errors.postgres(parseError(x5)); + } else { + errored(Errors.postgres(parseError(x5))); + } + } + function retry(q5, error51) { + delete statements[q5.signature]; + q5.retried = error51; + execute11(q5); + } + function NotificationResponse(x5) { + if (!onnotify) + return; + let index2 = 9; + while (x5[index2++] !== 0) ; + onnotify( + x5.toString("utf8", 9, index2 - 1), + x5.toString("utf8", index2, x5.length - 1) + ); + } + async function PortalSuspended() { + try { + const x5 = await Promise.resolve(query.cursorFn(result)); + rows = 0; + x5 === CLOSE ? write(Close(query.portal)) : (result = new Result(), write(Execute("", query.cursorRows))); + } catch (err) { + write(Sync); + query.reject(err); + } + } + function CloseComplete() { + result.count && query.cursorFn(result); + query.resolve(result); + } + function CopyInResponse() { + stream = new Stream.Writable({ + autoDestroy: true, + write(chunk2, encoding, callback) { + socket.write(bytes_default().d().raw(chunk2).end(), callback); + }, + destroy(error51, callback) { + callback(error51); + socket.write(bytes_default().f().str(error51 + bytes_default.N).end()); + stream = null; + }, + final(callback) { + socket.write(bytes_default().c().end()); + final = callback; + stream = null; + } + }); + query.resolve(stream); + } + function CopyOutResponse() { + stream = new Stream.Readable({ + read() { + socket.resume(); + } + }); + query.resolve(stream); + } + function CopyBothResponse() { + stream = new Stream.Duplex({ + autoDestroy: true, + read() { + socket.resume(); + }, + /* c8 ignore next 11 */ + write(chunk2, encoding, callback) { + socket.write(bytes_default().d().raw(chunk2).end(), callback); + }, + destroy(error51, callback) { + callback(error51); + socket.write(bytes_default().f().str(error51 + bytes_default.N).end()); + stream = null; + }, + final(callback) { + socket.write(bytes_default().c().end()); + final = callback; + } + }); + query.resolve(stream); + } + function CopyData(x5) { + stream && (stream.push(x5.subarray(5)) || socket.pause()); + } + function CopyDone() { + stream && stream.push(null); + stream = null; + } + function NoticeResponse(x5) { + onnotice ? onnotice(parseError(x5)) : console.log(parseError(x5)); + } + function EmptyQueryResponse() { + } + function FunctionCallResponse() { + errored(Errors.notSupported("FunctionCallResponse")); + } + function NegotiateProtocolVersion() { + errored(Errors.notSupported("NegotiateProtocolVersion")); + } + function UnknownMessage(x5) { + console.error("Postgres.js : Unknown Message:", x5[0]); + } + function UnknownAuth(x5, type) { + console.error("Postgres.js : Unknown Auth:", type); + } + function Bind(parameters, types2, statement = "", portal = "") { + let prev, type; + bytes_default().B().str(portal + bytes_default.N).str(statement + bytes_default.N).i16(0).i16(parameters.length); + parameters.forEach((x5, i5) => { + if (x5 === null) + return bytes_default.i32(4294967295); + type = types2[i5]; + parameters[i5] = x5 = type in options.serializers ? options.serializers[type](x5) : "" + x5; + prev = bytes_default.i; + bytes_default.inc(4).str(x5).i32(bytes_default.i - prev - 4, prev); + }); + bytes_default.i16(0); + return bytes_default.end(); + } + function Parse(str, parameters, types2, name = "") { + bytes_default().P().str(name + bytes_default.N).str(str + bytes_default.N).i16(parameters.length); + parameters.forEach((x5, i5) => bytes_default.i32(types2[i5] || 0)); + return bytes_default.end(); + } + function Describe(x5, name = "") { + return bytes_default().D().str(x5).str(name + bytes_default.N).end(); + } + function Execute(portal = "", rows2 = 0) { + return Buffer.concat([ + bytes_default().E().str(portal + bytes_default.N).i32(rows2).end(), + Flush + ]); + } + function Close(portal = "") { + return Buffer.concat([ + bytes_default().C().str("P").str(portal + bytes_default.N).end(), + bytes_default().S().end() + ]); + } + function StartupMessage() { + return cancelMessage || bytes_default().inc(4).i16(3).z(2).str( + Object.entries(Object.assign( + { + user, + database, + client_encoding: "UTF8" + }, + options.connection + )).filter(([, v5]) => v5).map(([k5, v5]) => k5 + bytes_default.N + v5).join(bytes_default.N) + ).z(2).end(0); + } +} +function parseError(x5) { + const error50 = {}; + let start = 5; + for (let i5 = 5; i5 < x5.length - 1; i5++) { + if (x5[i5] === 0) { + error50[errorFields[x5[start]]] = x5.toString("utf8", start + 1, i5); + start = i5 + 1; + } + } + return error50; +} +function md5(x5) { + return crypto2.createHash("md5").update(x5).digest("hex"); +} +function hmac(key, x5) { + return crypto2.createHmac("sha256", key).update(x5).digest(); +} +function sha256(x5) { + return crypto2.createHash("sha256").update(x5).digest(); +} +function xor(a5, b6) { + const length = Math.max(a5.length, b6.length); + const buffer2 = Buffer.allocUnsafe(length); + for (let i5 = 0; i5 < length; i5++) + buffer2[i5] = a5[i5] ^ b6[i5]; + return buffer2; +} +function timer(fn, seconds) { + seconds = typeof seconds === "function" ? seconds() : seconds; + if (!seconds) + return { cancel: noop, start: noop }; + let timer2; + return { + cancel() { + timer2 && (clearTimeout(timer2), timer2 = null); + }, + start() { + timer2 && clearTimeout(timer2); + timer2 = setTimeout(done, seconds * 1e3, arguments); + } + }; + function done(args) { + fn.apply(null, args); + timer2 = null; + } +} +var connection_default, uid, Sync, Flush, SSLRequest, ExecuteUnnamed, DescribeUnnamed, noop, retryRoutines, errorFields; +var init_connection = __esm({ + "node_modules/.pnpm/postgres@3.4.9/node_modules/postgres/src/connection.js"() { + init_types(); + init_errors(); + init_result(); + init_queue(); + init_query(); + init_bytes(); + connection_default = Connection; + uid = 1; + Sync = bytes_default().S().end(); + Flush = bytes_default().H().end(); + SSLRequest = bytes_default().i32(8).i32(80877103).end(8); + ExecuteUnnamed = Buffer.concat([bytes_default().E().str(bytes_default.N).i32(0).end(), Sync]); + DescribeUnnamed = bytes_default().D().str("S").str(bytes_default.N).end(); + noop = () => { + }; + retryRoutines = /* @__PURE__ */ new Set([ + "FetchPreparedStatement", + "RevalidateCachedQuery", + "transformAssignedExpr" + ]); + errorFields = { + 83: "severity_local", + // S + 86: "severity", + // V + 67: "code", + // C + 77: "message", + // M + 68: "detail", + // D + 72: "hint", + // H + 80: "position", + // P + 112: "internal_position", + // p + 113: "internal_query", + // q + 87: "where", + // W + 115: "schema_name", + // s + 116: "table_name", + // t + 99: "column_name", + // c + 100: "data type_name", + // d + 110: "constraint_name", + // n + 70: "file", + // F + 76: "line", + // L + 82: "routine" + // R + }; + } +}); + +// node_modules/.pnpm/postgres@3.4.9/node_modules/postgres/src/subscribe.js +function Subscribe(postgres2, options) { + const subscribers = /* @__PURE__ */ new Map(), slot = "postgresjs_" + Math.random().toString(36).slice(2), state2 = {}; + let connection2, stream, ended = false; + const sql3 = subscribe.sql = postgres2({ + ...options, + transform: { column: {}, value: {}, row: {} }, + max: 1, + fetch_types: false, + idle_timeout: null, + max_lifetime: null, + connection: { + ...options.connection, + replication: "database" + }, + onclose: async function() { + if (ended) + return; + stream = null; + state2.pid = state2.secret = void 0; + connected(await init2(sql3, slot, options.publications)); + subscribers.forEach((event) => event.forEach(({ onsubscribe }) => onsubscribe())); + }, + no_subscribe: true + }); + const end = sql3.end, close = sql3.close; + sql3.end = async () => { + ended = true; + stream && await new Promise((r5) => (stream.once("close", r5), stream.end())); + return end(); + }; + sql3.close = async () => { + stream && await new Promise((r5) => (stream.once("close", r5), stream.end())); + return close(); + }; + return subscribe; + async function subscribe(event, fn, onsubscribe = noop2, onerror = noop2) { + event = parseEvent(event); + if (!connection2) + connection2 = init2(sql3, slot, options.publications); + const subscriber = { fn, onsubscribe }; + const fns = subscribers.has(event) ? subscribers.get(event).add(subscriber) : subscribers.set(event, /* @__PURE__ */ new Set([subscriber])).get(event); + const unsubscribe = () => { + fns.delete(subscriber); + fns.size === 0 && subscribers.delete(event); + }; + return connection2.then((x5) => { + connected(x5); + onsubscribe(); + stream && stream.on("error", onerror); + return { unsubscribe, state: state2, sql: sql3 }; + }); + } + function connected(x5) { + stream = x5.stream; + state2.pid = x5.state.pid; + state2.secret = x5.state.secret; + } + async function init2(sql4, slot2, publications) { + if (!publications) + throw new Error("Missing publication names"); + const xs = await sql4.unsafe( + `CREATE_REPLICATION_SLOT ${slot2} TEMPORARY LOGICAL pgoutput NOEXPORT_SNAPSHOT` + ); + const [x5] = xs; + const stream2 = await sql4.unsafe( + `START_REPLICATION SLOT ${slot2} LOGICAL ${x5.consistent_point} (proto_version '1', publication_names '${publications}')` + ).writable(); + const state3 = { + lsn: Buffer.concat(x5.consistent_point.split("/").map((x6) => Buffer.from(("00000000" + x6).slice(-8), "hex"))) + }; + stream2.on("data", data2); + stream2.on("error", error50); + stream2.on("close", sql4.close); + return { stream: stream2, state: xs.state }; + function error50(e5) { + console.error("Unexpected error during logical streaming - reconnecting", e5); + } + function data2(x6) { + if (x6[0] === 119) { + parse(x6.subarray(25), state3, sql4.options.parsers, handle, options.transform); + } else if (x6[0] === 107 && x6[17]) { + state3.lsn = x6.subarray(1, 9); + pong(); + } + } + function handle(a5, b6) { + const path53 = b6.relation.schema + "." + b6.relation.table; + call("*", a5, b6); + call("*:" + path53, a5, b6); + b6.relation.keys.length && call("*:" + path53 + "=" + b6.relation.keys.map((x6) => a5[x6.name]), a5, b6); + call(b6.command, a5, b6); + call(b6.command + ":" + path53, a5, b6); + b6.relation.keys.length && call(b6.command + ":" + path53 + "=" + b6.relation.keys.map((x6) => a5[x6.name]), a5, b6); + } + function pong() { + const x6 = Buffer.alloc(34); + x6[0] = "r".charCodeAt(0); + x6.fill(state3.lsn, 1); + x6.writeBigInt64BE(BigInt(Date.now() - Date.UTC(2e3, 0, 1)) * BigInt(1e3), 25); + stream2.write(x6); + } + } + function call(x5, a5, b6) { + subscribers.has(x5) && subscribers.get(x5).forEach(({ fn }) => fn(a5, b6, x5)); + } +} +function Time(x5) { + return new Date(Date.UTC(2e3, 0, 1) + Number(x5 / BigInt(1e3))); +} +function parse(x5, state2, parsers2, handle, transform3) { + const char2 = (acc, [k5, v5]) => (acc[k5.charCodeAt(0)] = v5, acc); + Object.entries({ + R: (x6) => { + let i5 = 1; + const r5 = state2[x6.readUInt32BE(i5)] = { + schema: x6.toString("utf8", i5 += 4, i5 = x6.indexOf(0, i5)) || "pg_catalog", + table: x6.toString("utf8", i5 + 1, i5 = x6.indexOf(0, i5 + 1)), + columns: Array(x6.readUInt16BE(i5 += 2)), + keys: [] + }; + i5 += 2; + let columnIndex = 0, column; + while (i5 < x6.length) { + column = r5.columns[columnIndex++] = { + key: x6[i5++], + name: transform3.column.from ? transform3.column.from(x6.toString("utf8", i5, i5 = x6.indexOf(0, i5))) : x6.toString("utf8", i5, i5 = x6.indexOf(0, i5)), + type: x6.readUInt32BE(i5 += 1), + parser: parsers2[x6.readUInt32BE(i5)], + atttypmod: x6.readUInt32BE(i5 += 4) + }; + column.key && r5.keys.push(column); + i5 += 4; + } + }, + Y: () => { + }, + // Type + O: () => { + }, + // Origin + B: (x6) => { + state2.date = Time(x6.readBigInt64BE(9)); + state2.lsn = x6.subarray(1, 9); + }, + I: (x6) => { + let i5 = 1; + const relation = state2[x6.readUInt32BE(i5)]; + const { row } = tuples(x6, relation.columns, i5 += 7, transform3); + handle(row, { + command: "insert", + relation + }); + }, + D: (x6) => { + let i5 = 1; + const relation = state2[x6.readUInt32BE(i5)]; + i5 += 4; + const key = x6[i5] === 75; + handle( + key || x6[i5] === 79 ? tuples(x6, relation.columns, i5 += 3, transform3).row : null, + { + command: "delete", + relation, + key + } + ); + }, + U: (x6) => { + let i5 = 1; + const relation = state2[x6.readUInt32BE(i5)]; + i5 += 4; + const key = x6[i5] === 75; + const xs = key || x6[i5] === 79 ? tuples(x6, relation.columns, i5 += 3, transform3) : null; + xs && (i5 = xs.i); + const { row } = tuples(x6, relation.columns, i5 + 3, transform3); + handle(row, { + command: "update", + relation, + key, + old: xs && xs.row + }); + }, + T: () => { + }, + // Truncate, + C: () => { + } + // Commit + }).reduce(char2, {})[x5[0]](x5); +} +function tuples(x5, columns, xi, transform3) { + let type, column, value; + const row = transform3.raw ? new Array(columns.length) : {}; + for (let i5 = 0; i5 < columns.length; i5++) { + type = x5[xi++]; + column = columns[i5]; + value = type === 110 ? null : type === 117 ? void 0 : column.parser === void 0 ? x5.toString("utf8", xi + 4, xi += 4 + x5.readUInt32BE(xi)) : column.parser.array === true ? column.parser(x5.toString("utf8", xi + 5, xi += 4 + x5.readUInt32BE(xi))) : column.parser(x5.toString("utf8", xi + 4, xi += 4 + x5.readUInt32BE(xi))); + transform3.raw ? row[i5] = transform3.raw === true ? value : transform3.value.from ? transform3.value.from(value, column) : value : row[column.name] = transform3.value.from ? transform3.value.from(value, column) : value; + } + return { i: xi, row: transform3.row.from ? transform3.row.from(row) : row }; +} +function parseEvent(x5) { + const xs = x5.match(/^(\*|insert|update|delete)?:?([^.]+?\.?[^=]+)?=?(.+)?/i) || []; + if (!xs) + throw new Error("Malformed subscribe pattern: " + x5); + const [, command, path53, key] = xs; + return (command || "*") + (path53 ? ":" + (path53.indexOf(".") === -1 ? "public." + path53 : path53) : "") + (key ? "=" + key : ""); +} +var noop2; +var init_subscribe = __esm({ + "node_modules/.pnpm/postgres@3.4.9/node_modules/postgres/src/subscribe.js"() { + noop2 = () => { + }; + } +}); + +// node_modules/.pnpm/postgres@3.4.9/node_modules/postgres/src/large.js +import Stream2 from "stream"; +function largeObject(sql3, oid, mode = 131072 | 262144) { + return new Promise(async (resolve4, reject) => { + await sql3.begin(async (sql4) => { + let finish; + !oid && ([{ oid }] = await sql4`select lo_creat(-1) as oid`); + const [{ fd }] = await sql4`select lo_open(${oid}, ${mode}) as fd`; + const lo = { + writable, + readable, + close: () => sql4`select lo_close(${fd})`.then(finish), + tell: () => sql4`select lo_tell64(${fd})`, + read: (x5) => sql4`select loread(${fd}, ${x5}) as data`, + write: (x5) => sql4`select lowrite(${fd}, ${x5})`, + truncate: (x5) => sql4`select lo_truncate64(${fd}, ${x5})`, + seek: (x5, whence = 0) => sql4`select lo_lseek64(${fd}, ${x5}, ${whence})`, + size: () => sql4` + select + lo_lseek64(${fd}, location, 0) as position, + seek.size + from ( + select + lo_lseek64($1, 0, 2) as size, + tell.location + from (select lo_tell64($1) as location) tell + ) seek + ` + }; + resolve4(lo); + return new Promise(async (r5) => finish = r5); + async function readable({ + highWaterMark = 2048 * 8, + start = 0, + end = Infinity + } = {}) { + let max = end - start; + start && await lo.seek(start); + return new Stream2.Readable({ + highWaterMark, + async read(size2) { + const l5 = size2 > max ? size2 - max : size2; + max -= size2; + const [{ data: data2 }] = await lo.read(l5); + this.push(data2); + if (data2.length < size2) + this.push(null); + } + }); + } + async function writable({ + highWaterMark = 2048 * 8, + start = 0 + } = {}) { + start && await lo.seek(start); + return new Stream2.Writable({ + highWaterMark, + write(chunk, encoding, callback) { + lo.write(chunk).then(() => callback(), callback); + } + }); + } + }).catch(reject); + }); +} +var init_large = __esm({ + "node_modules/.pnpm/postgres@3.4.9/node_modules/postgres/src/large.js"() { + } +}); + +// node_modules/.pnpm/postgres@3.4.9/node_modules/postgres/src/index.js +import os from "os"; +import fs from "fs"; +function Postgres(a5, b6) { + const options = parseOptions(a5, b6), subscribe = options.no_subscribe || Subscribe(Postgres, { ...options }); + let ending = false; + const queries = queue_default(), connecting = queue_default(), reserved = queue_default(), closed = queue_default(), ended = queue_default(), open2 = queue_default(), busy = queue_default(), full = queue_default(), queues = { connecting, reserved, closed, ended, open: open2, busy, full }; + const connections = [...Array(options.max)].map(() => connection_default(options, queues, { onopen, onend, onclose })); + const sql3 = Sql(handler); + Object.assign(sql3, { + get parameters() { + return options.parameters; + }, + largeObject: largeObject.bind(null, sql3), + subscribe, + CLOSE, + END: CLOSE, + PostgresError, + options, + reserve, + listen, + begin, + close, + end + }); + return sql3; + function Sql(handler2) { + handler2.debug = options.debug; + Object.entries(options.types).reduce((acc, [name, type]) => { + acc[name] = (x5) => new Parameter(x5, type.to); + return acc; + }, typed); + Object.assign(sql4, { + types: typed, + typed, + unsafe, + notify, + array: array2, + json: json3, + file: file2 + }); + return sql4; + function typed(value, type) { + return new Parameter(value, type); + } + function sql4(strings, ...args) { + const query = strings && Array.isArray(strings.raw) ? new Query(strings, args, handler2, cancel) : typeof strings === "string" && !args.length ? new Identifier(options.transform.column.to ? options.transform.column.to(strings) : strings) : new Builder(strings, args); + return query; + } + function unsafe(string4, args = [], options2 = {}) { + arguments.length === 2 && !Array.isArray(args) && (options2 = args, args = []); + const query = new Query([string4], args, handler2, cancel, { + prepare: false, + ...options2, + simple: "simple" in options2 ? options2.simple : args.length === 0 + }); + return query; + } + function file2(path53, args = [], options2 = {}) { + arguments.length === 2 && !Array.isArray(args) && (options2 = args, args = []); + const query = new Query([], args, (query2) => { + fs.readFile(path53, "utf8", (err, string4) => { + if (err) + return query2.reject(err); + query2.strings = [string4]; + handler2(query2); + }); + }, cancel, { + ...options2, + simple: "simple" in options2 ? options2.simple : args.length === 0 + }); + return query; + } + } + async function listen(name, fn, onlisten) { + const listener = { fn, onlisten }; + const sql4 = listen.sql || (listen.sql = Postgres({ + ...options, + max: 1, + idle_timeout: null, + max_lifetime: null, + fetch_types: false, + onclose() { + Object.entries(listen.channels).forEach(([name2, { listeners }]) => { + delete listen.channels[name2]; + Promise.all(listeners.map((l5) => listen(name2, l5.fn, l5.onlisten).catch(() => { + }))); + }); + }, + onnotify(c5, x5) { + c5 in listen.channels && listen.channels[c5].listeners.forEach((l5) => l5.fn(x5)); + } + })); + const channels = listen.channels || (listen.channels = {}), exists2 = name in channels; + if (exists2) { + channels[name].listeners.push(listener); + const result2 = await channels[name].result; + listener.onlisten && listener.onlisten(); + return { state: result2.state, unlisten }; + } + channels[name] = { result: sql4`listen ${sql4.unsafe('"' + name.replace(/"/g, '""') + '"')}`, listeners: [listener] }; + const result = await channels[name].result; + listener.onlisten && listener.onlisten(); + return { state: result.state, unlisten }; + async function unlisten() { + if (name in channels === false) + return; + channels[name].listeners = channels[name].listeners.filter((x5) => x5 !== listener); + if (channels[name].listeners.length) + return; + delete channels[name]; + return sql4`unlisten ${sql4.unsafe('"' + name.replace(/"/g, '""') + '"')}`; + } + } + async function notify(channel, payload2) { + return await sql3`select pg_notify(${channel}, ${"" + payload2})`; + } + async function reserve() { + const queue = queue_default(); + const c5 = open2.length ? open2.shift() : await new Promise((resolve4, reject) => { + const query = { reserve: resolve4, reject }; + queries.push(query); + closed.length && connect(closed.shift(), query); + }); + move(c5, reserved); + c5.reserved = () => queue.length ? c5.execute(queue.shift()) : move(c5, reserved); + c5.reserved.release = true; + const sql4 = Sql(handler2); + sql4.release = () => { + c5.reserved = null; + onopen(c5); + }; + return sql4; + function handler2(q5) { + c5.queue === full ? queue.push(q5) : c5.execute(q5) || move(c5, full); + } + } + async function begin(options2, fn) { + !fn && (fn = options2, options2 = ""); + const queries2 = queue_default(); + let savepoints = 0, connection2, prepare = null; + try { + await sql3.unsafe("begin " + options2.replace(/[^a-z ]/ig, ""), [], { onexecute }).execute(); + return await Promise.race([ + scope(connection2, fn), + new Promise((_, reject) => connection2.onclose = reject) + ]); + } catch (error50) { + throw error50; + } + async function scope(c5, fn2, name) { + const sql4 = Sql(handler2); + sql4.savepoint = savepoint; + sql4.prepare = (x5) => prepare = x5.replace(/[^a-z0-9$-_. ]/gi); + let uncaughtError, result; + name && await sql4`savepoint ${sql4(name)}`; + try { + result = await new Promise((resolve4, reject) => { + const x5 = fn2(sql4); + Promise.resolve(Array.isArray(x5) ? Promise.all(x5) : x5).then(resolve4, reject); + }); + if (uncaughtError) + throw uncaughtError; + } catch (e5) { + await (name ? sql4`rollback to ${sql4(name)}` : sql4`rollback`); + throw e5 instanceof PostgresError && e5.code === "25P02" && uncaughtError || e5; + } + if (!name) { + prepare ? await sql4`prepare transaction '${sql4.unsafe(prepare)}'` : await sql4`commit`; + } + return result; + function savepoint(name2, fn3) { + if (name2 && Array.isArray(name2.raw)) + return savepoint((sql5) => sql5.apply(sql5, arguments)); + arguments.length === 1 && (fn3 = name2, name2 = null); + return scope(c5, fn3, "s" + savepoints++ + (name2 ? "_" + name2 : "")); + } + function handler2(q5) { + q5.catch((e5) => uncaughtError || (uncaughtError = e5)); + c5.queue === full ? queries2.push(q5) : c5.execute(q5) || move(c5, full); + } + } + function onexecute(c5) { + connection2 = c5; + move(c5, reserved); + c5.reserved = () => queries2.length ? c5.execute(queries2.shift()) : move(c5, reserved); + } + } + function move(c5, queue) { + c5.queue.remove(c5); + queue.push(c5); + c5.queue = queue; + queue === open2 ? c5.idleTimer.start() : c5.idleTimer.cancel(); + return c5; + } + function json3(x5) { + return new Parameter(x5, 3802); + } + function array2(x5, type) { + if (!Array.isArray(x5)) + return array2(Array.from(arguments)); + return new Parameter(x5, type || (x5.length ? inferType(x5) || 25 : 0), options.shared.typeArrayMap); + } + function handler(query) { + if (ending) + return query.reject(Errors.connection("CONNECTION_ENDED", options, options)); + if (open2.length) + return go(open2.shift(), query); + if (closed.length) + return connect(closed.shift(), query); + busy.length ? go(busy.shift(), query) : queries.push(query); + } + function go(c5, query) { + return c5.execute(query) ? move(c5, busy) : move(c5, full); + } + function cancel(query) { + return new Promise((resolve4, reject) => { + query.state ? query.active ? connection_default(options).cancel(query.state, resolve4, reject) : query.cancelled = { resolve: resolve4, reject } : (queries.remove(query), query.cancelled = true, query.reject(Errors.generic("57014", "canceling statement due to user request")), resolve4()); + }); + } + async function end({ timeout = null } = {}) { + if (ending) + return ending; + await 1; + let timer2; + return ending = Promise.race([ + new Promise((r5) => timeout !== null && (timer2 = setTimeout(destroy, timeout * 1e3, r5))), + Promise.all(connections.map((c5) => c5.end()).concat( + listen.sql ? listen.sql.end({ timeout: 0 }) : [], + subscribe.sql ? subscribe.sql.end({ timeout: 0 }) : [] + )) + ]).then(() => clearTimeout(timer2)); + } + async function close() { + await Promise.all(connections.map((c5) => c5.end())); + } + async function destroy(resolve4) { + await Promise.all(connections.map((c5) => c5.terminate())); + while (queries.length) + queries.shift().reject(Errors.connection("CONNECTION_DESTROYED", options)); + resolve4(); + } + function connect(c5, query) { + move(c5, connecting); + c5.connect(query); + return c5; + } + function onend(c5) { + move(c5, ended); + } + function onopen(c5) { + if (queries.length === 0) + return move(c5, open2); + let max = Math.ceil(queries.length / (connecting.length + 1)), ready = true; + while (ready && queries.length && max-- > 0) { + const query = queries.shift(); + if (query.reserve) + return query.reserve(c5); + ready = c5.execute(query); + } + ready ? move(c5, busy) : move(c5, full); + } + function onclose(c5, e5) { + move(c5, closed); + c5.reserved = null; + c5.onclose && (c5.onclose(e5), c5.onclose = null); + options.onclose && options.onclose(c5.id); + queries.length && connect(c5, queries.shift()); + } +} +function parseOptions(a5, b6) { + if (a5 && a5.shared) + return a5; + const env2 = process.env, o5 = (!a5 || typeof a5 === "string" ? b6 : a5) || {}, { url: url2, multihost } = parseUrl(a5), query = [...url2.searchParams].reduce((a6, [b7, c5]) => (a6[b7] = c5, a6), {}), host = o5.hostname || o5.host || multihost || url2.hostname || env2.PGHOST || "localhost", port = o5.port || url2.port || env2.PGPORT || 5432, user = o5.user || o5.username || url2.username || env2.PGUSERNAME || env2.PGUSER || osUsername(); + o5.no_prepare && (o5.prepare = false); + query.sslmode && (query.ssl = query.sslmode, delete query.sslmode); + "timeout" in o5 && (console.log("The timeout option is deprecated, use idle_timeout instead"), o5.idle_timeout = o5.timeout); + query.sslrootcert === "system" && (query.ssl = "verify-full"); + const ints = ["idle_timeout", "connect_timeout", "max_lifetime", "max_pipeline", "backoff", "keep_alive"]; + const defaults = { + max: globalThis.Cloudflare ? 3 : 10, + ssl: false, + sslnegotiation: null, + idle_timeout: null, + connect_timeout: 30, + max_lifetime, + max_pipeline: 100, + backoff, + keep_alive: 60, + prepare: true, + debug: false, + fetch_types: true, + publications: "alltables", + target_session_attrs: null + }; + return { + host: Array.isArray(host) ? host : host.split(",").map((x5) => x5.split(":")[0]), + port: Array.isArray(port) ? port : host.split(",").map((x5) => parseInt(x5.split(":")[1] || port)), + path: o5.path || host.indexOf("/") > -1 && host + "/.s.PGSQL." + port, + database: o5.database || o5.db || (url2.pathname || "").slice(1) || env2.PGDATABASE || user, + user, + pass: o5.pass || o5.password || url2.password || env2.PGPASSWORD || "", + ...Object.entries(defaults).reduce( + (acc, [k5, d5]) => { + const value = k5 in o5 ? o5[k5] : k5 in query ? query[k5] === "disable" || query[k5] === "false" ? false : query[k5] : env2["PG" + k5.toUpperCase()] || d5; + acc[k5] = typeof value === "string" && ints.includes(k5) ? +value : value; + return acc; + }, + {} + ), + connection: { + application_name: env2.PGAPPNAME || "postgres.js", + ...o5.connection, + ...Object.entries(query).reduce((acc, [k5, v5]) => (k5 in defaults || (acc[k5] = v5), acc), {}) + }, + types: o5.types || {}, + target_session_attrs: tsa(o5, url2, env2), + onnotice: o5.onnotice, + onnotify: o5.onnotify, + onclose: o5.onclose, + onparameter: o5.onparameter, + socket: o5.socket, + transform: parseTransform(o5.transform || { undefined: void 0 }), + parameters: {}, + shared: { retries: 0, typeArrayMap: {} }, + ...mergeUserTypes(o5.types) + }; +} +function tsa(o5, url2, env2) { + const x5 = o5.target_session_attrs || url2.searchParams.get("target_session_attrs") || env2.PGTARGETSESSIONATTRS; + if (!x5 || ["read-write", "read-only", "primary", "standby", "prefer-standby"].includes(x5)) + return x5; + throw new Error("target_session_attrs " + x5 + " is not supported"); +} +function backoff(retries) { + return (0.5 + Math.random() / 2) * Math.min(3 ** retries / 100, 20); +} +function max_lifetime() { + return 60 * (30 + Math.random() * 30); +} +function parseTransform(x5) { + return { + undefined: x5.undefined, + column: { + from: typeof x5.column === "function" ? x5.column : x5.column && x5.column.from, + to: x5.column && x5.column.to + }, + value: { + from: typeof x5.value === "function" ? x5.value : x5.value && x5.value.from, + to: x5.value && x5.value.to + }, + row: { + from: typeof x5.row === "function" ? x5.row : x5.row && x5.row.from, + to: x5.row && x5.row.to + } + }; +} +function parseUrl(url2) { + if (!url2 || typeof url2 !== "string") + return { url: { searchParams: /* @__PURE__ */ new Map() } }; + let host = url2; + host = host.slice(host.indexOf("://") + 3).split(/[?/]/)[0]; + host = decodeURIComponent(host.slice(host.indexOf("@") + 1)); + const urlObj = new URL(url2.replace(host, host.split(",")[0])); + return { + url: { + username: decodeURIComponent(urlObj.username), + password: decodeURIComponent(urlObj.password), + host: urlObj.host, + hostname: urlObj.hostname, + port: urlObj.port, + pathname: urlObj.pathname, + searchParams: urlObj.searchParams + }, + multihost: host.indexOf(",") > -1 && host + }; +} +function osUsername() { + try { + return os.userInfo().username; + } catch (_) { + return process.env.USERNAME || process.env.USER || process.env.LOGNAME; + } +} +var src_default; +var init_src = __esm({ + "node_modules/.pnpm/postgres@3.4.9/node_modules/postgres/src/index.js"() { + init_types(); + init_connection(); + init_query(); + init_queue(); + init_errors(); + init_subscribe(); + init_large(); + Object.assign(Postgres, { + PostgresError, + toPascal, + pascal, + toCamel, + camel, + toKebab, + kebab, + fromPascal, + fromCamel, + fromKebab, + BigInt: { + to: 20, + from: [20], + parse: (x5) => BigInt(x5), + // eslint-disable-line + serialize: (x5) => x5.toString() + } + }); + src_default = Postgres; + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/entity.js +function is(value, type) { + if (!value || typeof value !== "object") { + return false; + } + if (value instanceof type) { + return true; + } + if (!Object.prototype.hasOwnProperty.call(type, entityKind)) { + throw new Error( + `Class "${type.name ?? ""}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.` + ); + } + let cls = Object.getPrototypeOf(value).constructor; + if (cls) { + while (cls) { + if (entityKind in cls && cls[entityKind] === type[entityKind]) { + return true; + } + cls = Object.getPrototypeOf(cls); + } + } + return false; +} +var entityKind; +var init_entity = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/entity.js"() { + entityKind = /* @__PURE__ */ Symbol.for("drizzle:entityKind"); + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/logger.js +var ConsoleLogWriter, DefaultLogger, NoopLogger; +var init_logger = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/logger.js"() { + init_entity(); + ConsoleLogWriter = class { + static [entityKind] = "ConsoleLogWriter"; + write(message2) { + console.log(message2); + } + }; + DefaultLogger = class { + static [entityKind] = "DefaultLogger"; + writer; + constructor(config3) { + this.writer = config3?.writer ?? new ConsoleLogWriter(); + } + logQuery(query, params) { + const stringifiedParams = params.map((p5) => { + try { + return JSON.stringify(p5); + } catch { + return String(p5); + } + }); + const paramsStr = stringifiedParams.length ? ` -- params: [${stringifiedParams.join(", ")}]` : ""; + this.writer.write(`Query: ${query}${paramsStr}`); + } + }; + NoopLogger = class { + static [entityKind] = "NoopLogger"; + logQuery() { + } + }; + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/query-promise.js +var QueryPromise; +var init_query_promise = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/query-promise.js"() { + init_entity(); + QueryPromise = class { + static [entityKind] = "QueryPromise"; + [Symbol.toStringTag] = "QueryPromise"; + catch(onRejected) { + return this.then(void 0, onRejected); + } + finally(onFinally) { + return this.then( + (value) => { + onFinally?.(); + return value; + }, + (reason) => { + onFinally?.(); + throw reason; + } + ); + } + then(onFulfilled, onRejected) { + return this.execute().then(onFulfilled, onRejected); + } + }; + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/table.utils.js +var TableName; +var init_table_utils = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/table.utils.js"() { + TableName = /* @__PURE__ */ Symbol.for("drizzle:Name"); + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/table.js +function getTableName(table) { + return table[TableName]; +} +function getTableUniqueName(table) { + return `${table[Schema] ?? "public"}.${table[TableName]}`; +} +var Schema, Columns, ExtraConfigColumns, OriginalName, BaseName, IsAlias, ExtraConfigBuilder, IsDrizzleTable, Table; +var init_table = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/table.js"() { + init_entity(); + init_table_utils(); + Schema = /* @__PURE__ */ Symbol.for("drizzle:Schema"); + Columns = /* @__PURE__ */ Symbol.for("drizzle:Columns"); + ExtraConfigColumns = /* @__PURE__ */ Symbol.for("drizzle:ExtraConfigColumns"); + OriginalName = /* @__PURE__ */ Symbol.for("drizzle:OriginalName"); + BaseName = /* @__PURE__ */ Symbol.for("drizzle:BaseName"); + IsAlias = /* @__PURE__ */ Symbol.for("drizzle:IsAlias"); + ExtraConfigBuilder = /* @__PURE__ */ Symbol.for("drizzle:ExtraConfigBuilder"); + IsDrizzleTable = /* @__PURE__ */ Symbol.for("drizzle:IsDrizzleTable"); + Table = class { + static [entityKind] = "Table"; + /** @internal */ + static Symbol = { + Name: TableName, + Schema, + OriginalName, + Columns, + ExtraConfigColumns, + BaseName, + IsAlias, + ExtraConfigBuilder + }; + /** + * @internal + * Can be changed if the table is aliased. + */ + [TableName]; + /** + * @internal + * Used to store the original name of the table, before any aliasing. + */ + [OriginalName]; + /** @internal */ + [Schema]; + /** @internal */ + [Columns]; + /** @internal */ + [ExtraConfigColumns]; + /** + * @internal + * Used to store the table name before the transformation via the `tableCreator` functions. + */ + [BaseName]; + /** @internal */ + [IsAlias] = false; + /** @internal */ + [IsDrizzleTable] = true; + /** @internal */ + [ExtraConfigBuilder] = void 0; + constructor(name, schema2, baseName) { + this[TableName] = this[OriginalName] = name; + this[Schema] = schema2; + this[BaseName] = baseName; + } + }; + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/tracing-utils.js +function iife(fn, ...args) { + return fn(...args); +} +var init_tracing_utils = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/tracing-utils.js"() { + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/version.js +var version; +var init_version = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/version.js"() { + version = "0.38.4"; + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/tracing.js +var otel, rawTracer, tracer; +var init_tracing = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/tracing.js"() { + init_tracing_utils(); + init_version(); + tracer = { + startActiveSpan(name, fn) { + if (!otel) { + return fn(); + } + if (!rawTracer) { + rawTracer = otel.trace.getTracer("drizzle-orm", version); + } + return iife( + (otel2, rawTracer2) => rawTracer2.startActiveSpan( + name, + (span) => { + try { + return fn(span); + } catch (e5) { + span.setStatus({ + code: otel2.SpanStatusCode.ERROR, + message: e5 instanceof Error ? e5.message : "Unknown error" + // eslint-disable-line no-instanceof/no-instanceof + }); + throw e5; + } finally { + span.end(); + } + } + ), + otel, + rawTracer + ); + } + }; + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/column.js +var Column; +var init_column = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/column.js"() { + init_entity(); + Column = class { + constructor(table, config3) { + this.table = table; + this.config = config3; + this.name = config3.name; + this.keyAsName = config3.keyAsName; + this.notNull = config3.notNull; + this.default = config3.default; + this.defaultFn = config3.defaultFn; + this.onUpdateFn = config3.onUpdateFn; + this.hasDefault = config3.hasDefault; + this.primary = config3.primaryKey; + this.isUnique = config3.isUnique; + this.uniqueName = config3.uniqueName; + this.uniqueType = config3.uniqueType; + this.dataType = config3.dataType; + this.columnType = config3.columnType; + this.generated = config3.generated; + this.generatedIdentity = config3.generatedIdentity; + } + static [entityKind] = "Column"; + name; + keyAsName; + primary; + notNull; + default; + defaultFn; + onUpdateFn; + hasDefault; + isUnique; + uniqueName; + uniqueType; + dataType; + columnType; + enumValues = void 0; + generated = void 0; + generatedIdentity = void 0; + config; + mapFromDriverValue(value) { + return value; + } + mapToDriverValue(value) { + return value; + } + // ** @internal */ + shouldDisableInsert() { + return this.config.generated !== void 0 && this.config.generated.type !== "byDefault"; + } + }; + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/column-builder.js +var ColumnBuilder; +var init_column_builder = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/column-builder.js"() { + init_entity(); + ColumnBuilder = class { + static [entityKind] = "ColumnBuilder"; + config; + constructor(name, dataType, columnType) { + this.config = { + name, + keyAsName: name === "", + notNull: false, + default: void 0, + hasDefault: false, + primaryKey: false, + isUnique: false, + uniqueName: void 0, + uniqueType: void 0, + dataType, + columnType, + generated: void 0 + }; + } + /** + * Changes the data type of the column. Commonly used with `json` columns. Also, useful for branded types. + * + * @example + * ```ts + * const users = pgTable('users', { + * id: integer('id').$type().primaryKey(), + * details: json('details').$type().notNull(), + * }); + * ``` + */ + $type() { + return this; + } + /** + * Adds a `not null` clause to the column definition. + * + * Affects the `select` model of the table - columns *without* `not null` will be nullable on select. + */ + notNull() { + this.config.notNull = true; + return this; + } + /** + * Adds a `default ` clause to the column definition. + * + * Affects the `insert` model of the table - columns *with* `default` are optional on insert. + * + * If you need to set a dynamic default value, use {@link $defaultFn} instead. + */ + default(value) { + this.config.default = value; + this.config.hasDefault = true; + return this; + } + /** + * Adds a dynamic default value to the column. + * The function will be called when the row is inserted, and the returned value will be used as the column value. + * + * **Note:** This value does not affect the `drizzle-kit` behavior, it is only used at runtime in `drizzle-orm`. + */ + $defaultFn(fn) { + this.config.defaultFn = fn; + this.config.hasDefault = true; + return this; + } + /** + * Alias for {@link $defaultFn}. + */ + $default = this.$defaultFn; + /** + * Adds a dynamic update value to the column. + * The function will be called when the row is updated, and the returned value will be used as the column value if none is provided. + * If no `default` (or `$defaultFn`) value is provided, the function will be called when the row is inserted as well, and the returned value will be used as the column value. + * + * **Note:** This value does not affect the `drizzle-kit` behavior, it is only used at runtime in `drizzle-orm`. + */ + $onUpdateFn(fn) { + this.config.onUpdateFn = fn; + this.config.hasDefault = true; + return this; + } + /** + * Alias for {@link $onUpdateFn}. + */ + $onUpdate = this.$onUpdateFn; + /** + * Adds a `primary key` clause to the column definition. This implicitly makes the column `not null`. + * + * In SQLite, `integer primary key` implicitly makes the column auto-incrementing. + */ + primaryKey() { + this.config.primaryKey = true; + this.config.notNull = true; + return this; + } + /** @internal Sets the name of the column to the key within the table definition if a name was not given. */ + setName(name) { + if (this.config.name !== "") + return; + this.config.name = name; + } + }; + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/foreign-keys.js +var ForeignKeyBuilder, ForeignKey; +var init_foreign_keys = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/foreign-keys.js"() { + init_entity(); + init_table_utils(); + ForeignKeyBuilder = class { + static [entityKind] = "PgForeignKeyBuilder"; + /** @internal */ + reference; + /** @internal */ + _onUpdate = "no action"; + /** @internal */ + _onDelete = "no action"; + constructor(config3, actions) { + this.reference = () => { + const { name, columns, foreignColumns } = config3(); + return { name, columns, foreignTable: foreignColumns[0].table, foreignColumns }; + }; + if (actions) { + this._onUpdate = actions.onUpdate; + this._onDelete = actions.onDelete; + } + } + onUpdate(action) { + this._onUpdate = action === void 0 ? "no action" : action; + return this; + } + onDelete(action) { + this._onDelete = action === void 0 ? "no action" : action; + return this; + } + /** @internal */ + build(table) { + return new ForeignKey(table, this); + } + }; + ForeignKey = class { + constructor(table, builder) { + this.table = table; + this.reference = builder.reference; + this.onUpdate = builder._onUpdate; + this.onDelete = builder._onDelete; + } + static [entityKind] = "PgForeignKey"; + reference; + onUpdate; + onDelete; + getName() { + const { name, columns, foreignColumns } = this.reference(); + const columnNames = columns.map((column) => column.name); + const foreignColumnNames = foreignColumns.map((column) => column.name); + const chunks = [ + this.table[TableName], + ...columnNames, + foreignColumns[0].table[TableName], + ...foreignColumnNames + ]; + return name ?? `${chunks.join("_")}_fk`; + } + }; + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/unique-constraint.js +function unique(name) { + return new UniqueOnConstraintBuilder(name); +} +function uniqueKeyName(table, columns) { + return `${table[TableName]}_${columns.join("_")}_unique`; +} +var UniqueConstraintBuilder, UniqueOnConstraintBuilder, UniqueConstraint; +var init_unique_constraint = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/unique-constraint.js"() { + init_entity(); + init_table_utils(); + UniqueConstraintBuilder = class { + constructor(columns, name) { + this.name = name; + this.columns = columns; + } + static [entityKind] = "PgUniqueConstraintBuilder"; + /** @internal */ + columns; + /** @internal */ + nullsNotDistinctConfig = false; + nullsNotDistinct() { + this.nullsNotDistinctConfig = true; + return this; + } + /** @internal */ + build(table) { + return new UniqueConstraint(table, this.columns, this.nullsNotDistinctConfig, this.name); + } + }; + UniqueOnConstraintBuilder = class { + static [entityKind] = "PgUniqueOnConstraintBuilder"; + /** @internal */ + name; + constructor(name) { + this.name = name; + } + on(...columns) { + return new UniqueConstraintBuilder(columns, this.name); + } + }; + UniqueConstraint = class { + constructor(table, columns, nullsNotDistinct, name) { + this.table = table; + this.columns = columns; + this.name = name ?? uniqueKeyName(this.table, this.columns.map((column) => column.name)); + this.nullsNotDistinct = nullsNotDistinct; + } + static [entityKind] = "PgUniqueConstraint"; + columns; + name; + nullsNotDistinct = false; + getName() { + return this.name; + } + }; + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/utils/array.js +function parsePgArrayValue(arrayString, startFrom, inQuotes) { + for (let i5 = startFrom; i5 < arrayString.length; i5++) { + const char2 = arrayString[i5]; + if (char2 === "\\") { + i5++; + continue; + } + if (char2 === '"') { + return [arrayString.slice(startFrom, i5).replace(/\\/g, ""), i5 + 1]; + } + if (inQuotes) { + continue; + } + if (char2 === "," || char2 === "}") { + return [arrayString.slice(startFrom, i5).replace(/\\/g, ""), i5]; + } + } + return [arrayString.slice(startFrom).replace(/\\/g, ""), arrayString.length]; +} +function parsePgNestedArray(arrayString, startFrom = 0) { + const result = []; + let i5 = startFrom; + let lastCharIsComma = false; + while (i5 < arrayString.length) { + const char2 = arrayString[i5]; + if (char2 === ",") { + if (lastCharIsComma || i5 === startFrom) { + result.push(""); + } + lastCharIsComma = true; + i5++; + continue; + } + lastCharIsComma = false; + if (char2 === "\\") { + i5 += 2; + continue; + } + if (char2 === '"') { + const [value2, startFrom2] = parsePgArrayValue(arrayString, i5 + 1, true); + result.push(value2); + i5 = startFrom2; + continue; + } + if (char2 === "}") { + return [result, i5 + 1]; + } + if (char2 === "{") { + const [value2, startFrom2] = parsePgNestedArray(arrayString, i5 + 1); + result.push(value2); + i5 = startFrom2; + continue; + } + const [value, newStartFrom] = parsePgArrayValue(arrayString, i5, false); + result.push(value); + i5 = newStartFrom; + } + return [result, i5]; +} +function parsePgArray(arrayString) { + const [result] = parsePgNestedArray(arrayString, 1); + return result; +} +function makePgArray(array2) { + return `{${array2.map((item) => { + if (Array.isArray(item)) { + return makePgArray(item); + } + if (typeof item === "string") { + return `"${item.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`; + } + return `${item}`; + }).join(",")}}`; +} +var init_array = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/utils/array.js"() { + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/common.js +var PgColumnBuilder, PgColumn, ExtraConfigColumn, IndexedColumn, PgArrayBuilder, PgArray; +var init_common = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/common.js"() { + init_column_builder(); + init_column(); + init_entity(); + init_foreign_keys(); + init_tracing_utils(); + init_unique_constraint(); + init_array(); + PgColumnBuilder = class extends ColumnBuilder { + foreignKeyConfigs = []; + static [entityKind] = "PgColumnBuilder"; + array(size2) { + return new PgArrayBuilder(this.config.name, this, size2); + } + references(ref, actions = {}) { + this.foreignKeyConfigs.push({ ref, actions }); + return this; + } + unique(name, config3) { + this.config.isUnique = true; + this.config.uniqueName = name; + this.config.uniqueType = config3?.nulls; + return this; + } + generatedAlwaysAs(as) { + this.config.generated = { + as, + type: "always", + mode: "stored" + }; + return this; + } + /** @internal */ + buildForeignKeys(column, table) { + return this.foreignKeyConfigs.map(({ ref, actions }) => { + return iife( + (ref2, actions2) => { + const builder = new ForeignKeyBuilder(() => { + const foreignColumn = ref2(); + return { columns: [column], foreignColumns: [foreignColumn] }; + }); + if (actions2.onUpdate) { + builder.onUpdate(actions2.onUpdate); + } + if (actions2.onDelete) { + builder.onDelete(actions2.onDelete); + } + return builder.build(table); + }, + ref, + actions + ); + }); + } + /** @internal */ + buildExtraConfigColumn(table) { + return new ExtraConfigColumn(table, this.config); + } + }; + PgColumn = class extends Column { + constructor(table, config3) { + if (!config3.uniqueName) { + config3.uniqueName = uniqueKeyName(table, [config3.name]); + } + super(table, config3); + this.table = table; + } + static [entityKind] = "PgColumn"; + }; + ExtraConfigColumn = class extends PgColumn { + static [entityKind] = "ExtraConfigColumn"; + getSQLType() { + return this.getSQLType(); + } + indexConfig = { + order: this.config.order ?? "asc", + nulls: this.config.nulls ?? "last", + opClass: this.config.opClass + }; + defaultConfig = { + order: "asc", + nulls: "last", + opClass: void 0 + }; + asc() { + this.indexConfig.order = "asc"; + return this; + } + desc() { + this.indexConfig.order = "desc"; + return this; + } + nullsFirst() { + this.indexConfig.nulls = "first"; + return this; + } + nullsLast() { + this.indexConfig.nulls = "last"; + return this; + } + /** + * ### PostgreSQL documentation quote + * + * > An operator class with optional parameters can be specified for each column of an index. + * The operator class identifies the operators to be used by the index for that column. + * For example, a B-tree index on four-byte integers would use the int4_ops class; + * this operator class includes comparison functions for four-byte integers. + * In practice the default operator class for the column's data type is usually sufficient. + * The main point of having operator classes is that for some data types, there could be more than one meaningful ordering. + * For example, we might want to sort a complex-number data type either by absolute value or by real part. + * We could do this by defining two operator classes for the data type and then selecting the proper class when creating an index. + * More information about operator classes check: + * + * ### Useful links + * https://www.postgresql.org/docs/current/sql-createindex.html + * + * https://www.postgresql.org/docs/current/indexes-opclass.html + * + * https://www.postgresql.org/docs/current/xindex.html + * + * ### Additional types + * If you have the `pg_vector` extension installed in your database, you can use the + * `vector_l2_ops`, `vector_ip_ops`, `vector_cosine_ops`, `vector_l1_ops`, `bit_hamming_ops`, `bit_jaccard_ops`, `halfvec_l2_ops`, `sparsevec_l2_ops` options, which are predefined types. + * + * **You can always specify any string you want in the operator class, in case Drizzle doesn't have it natively in its types** + * + * @param opClass + * @returns + */ + op(opClass) { + this.indexConfig.opClass = opClass; + return this; + } + }; + IndexedColumn = class { + static [entityKind] = "IndexedColumn"; + constructor(name, keyAsName, type, indexConfig) { + this.name = name; + this.keyAsName = keyAsName; + this.type = type; + this.indexConfig = indexConfig; + } + name; + keyAsName; + type; + indexConfig; + }; + PgArrayBuilder = class extends PgColumnBuilder { + static [entityKind] = "PgArrayBuilder"; + constructor(name, baseBuilder, size2) { + super(name, "array", "PgArray"); + this.config.baseBuilder = baseBuilder; + this.config.size = size2; + } + /** @internal */ + build(table) { + const baseColumn = this.config.baseBuilder.build(table); + return new PgArray( + table, + this.config, + baseColumn + ); + } + }; + PgArray = class _PgArray extends PgColumn { + constructor(table, config3, baseColumn, range2) { + super(table, config3); + this.baseColumn = baseColumn; + this.range = range2; + this.size = config3.size; + } + size; + static [entityKind] = "PgArray"; + getSQLType() { + return `${this.baseColumn.getSQLType()}[${typeof this.size === "number" ? this.size : ""}]`; + } + mapFromDriverValue(value) { + if (typeof value === "string") { + value = parsePgArray(value); + } + return value.map((v5) => this.baseColumn.mapFromDriverValue(v5)); + } + mapToDriverValue(value, isNestedArray = false) { + const a5 = value.map( + (v5) => v5 === null ? null : is(this.baseColumn, _PgArray) ? this.baseColumn.mapToDriverValue(v5, true) : this.baseColumn.mapToDriverValue(v5) + ); + if (isNestedArray) + return a5; + return makePgArray(a5); + } + }; + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/enum.js +function isPgEnum(obj) { + return !!obj && typeof obj === "function" && isPgEnumSym in obj && obj[isPgEnumSym] === true; +} +function pgEnumWithSchema(enumName, values2, schema2) { + const enumInstance = Object.assign( + (name) => new PgEnumColumnBuilder(name ?? "", enumInstance), + { + enumName, + enumValues: values2, + schema: schema2, + [isPgEnumSym]: true + } + ); + return enumInstance; +} +var isPgEnumSym, PgEnumColumnBuilder, PgEnumColumn; +var init_enum = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/enum.js"() { + init_entity(); + init_common(); + isPgEnumSym = /* @__PURE__ */ Symbol.for("drizzle:isPgEnum"); + PgEnumColumnBuilder = class extends PgColumnBuilder { + static [entityKind] = "PgEnumColumnBuilder"; + constructor(name, enumInstance) { + super(name, "string", "PgEnumColumn"); + this.config.enum = enumInstance; + } + /** @internal */ + build(table) { + return new PgEnumColumn( + table, + this.config + ); + } + }; + PgEnumColumn = class extends PgColumn { + static [entityKind] = "PgEnumColumn"; + enum = this.config.enum; + enumValues = this.config.enum.enumValues; + constructor(table, config3) { + super(table, config3); + this.enum = config3.enum; + } + getSQLType() { + return this.enum.enumName; + } + }; + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/subquery.js +var Subquery, WithSubquery; +var init_subquery = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/subquery.js"() { + init_entity(); + Subquery = class { + static [entityKind] = "Subquery"; + constructor(sql3, selection, alias, isWith = false) { + this._ = { + brand: "Subquery", + sql: sql3, + selectedFields: selection, + alias, + isWith + }; + } + // getSQL(): SQL { + // return new SQL([this]); + // } + }; + WithSubquery = class extends Subquery { + static [entityKind] = "WithSubquery"; + }; + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/view-common.js +var ViewBaseConfig; +var init_view_common = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/view-common.js"() { + ViewBaseConfig = /* @__PURE__ */ Symbol.for("drizzle:ViewBaseConfig"); + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/sql/sql.js +function isSQLWrapper(value) { + return value !== null && value !== void 0 && typeof value.getSQL === "function"; +} +function mergeQueries(queries) { + const result = { sql: "", params: [] }; + for (const query of queries) { + result.sql += query.sql; + result.params.push(...query.params); + if (query.typings?.length) { + if (!result.typings) { + result.typings = []; + } + result.typings.push(...query.typings); + } + } + return result; +} +function isDriverValueEncoder(value) { + return typeof value === "object" && value !== null && "mapToDriverValue" in value && typeof value.mapToDriverValue === "function"; +} +function sql(strings, ...params) { + const queryChunks = []; + if (params.length > 0 || strings.length > 0 && strings[0] !== "") { + queryChunks.push(new StringChunk(strings[0])); + } + for (const [paramIndex, param2] of params.entries()) { + queryChunks.push(param2, new StringChunk(strings[paramIndex + 1])); + } + return new SQL(queryChunks); +} +function fillPlaceholders(params, values2) { + return params.map((p5) => { + if (is(p5, Placeholder)) { + if (!(p5.name in values2)) { + throw new Error(`No value for placeholder "${p5.name}" was provided`); + } + return values2[p5.name]; + } + if (is(p5, Param) && is(p5.value, Placeholder)) { + if (!(p5.value.name in values2)) { + throw new Error(`No value for placeholder "${p5.value.name}" was provided`); + } + return p5.encoder.mapToDriverValue(values2[p5.value.name]); + } + return p5; + }); +} +var FakePrimitiveParam, StringChunk, SQL, Name, noopDecoder, noopEncoder, noopMapper, Param, Placeholder, IsDrizzleView, View; +var init_sql = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/sql/sql.js"() { + init_entity(); + init_enum(); + init_subquery(); + init_tracing(); + init_view_common(); + init_column(); + init_table(); + FakePrimitiveParam = class { + static [entityKind] = "FakePrimitiveParam"; + }; + StringChunk = class { + static [entityKind] = "StringChunk"; + value; + constructor(value) { + this.value = Array.isArray(value) ? value : [value]; + } + getSQL() { + return new SQL([this]); + } + }; + SQL = class _SQL { + constructor(queryChunks) { + this.queryChunks = queryChunks; + } + static [entityKind] = "SQL"; + /** @internal */ + decoder = noopDecoder; + shouldInlineParams = false; + append(query) { + this.queryChunks.push(...query.queryChunks); + return this; + } + toQuery(config3) { + return tracer.startActiveSpan("drizzle.buildSQL", (span) => { + const query = this.buildQueryFromSourceParams(this.queryChunks, config3); + span?.setAttributes({ + "drizzle.query.text": query.sql, + "drizzle.query.params": JSON.stringify(query.params) + }); + return query; + }); + } + buildQueryFromSourceParams(chunks, _config) { + const config3 = Object.assign({}, _config, { + inlineParams: _config.inlineParams || this.shouldInlineParams, + paramStartIndex: _config.paramStartIndex || { value: 0 } + }); + const { + casing, + escapeName, + escapeParam, + prepareTyping, + inlineParams, + paramStartIndex + } = config3; + return mergeQueries(chunks.map((chunk) => { + if (is(chunk, StringChunk)) { + return { sql: chunk.value.join(""), params: [] }; + } + if (is(chunk, Name)) { + return { sql: escapeName(chunk.value), params: [] }; + } + if (chunk === void 0) { + return { sql: "", params: [] }; + } + if (Array.isArray(chunk)) { + const result = [new StringChunk("(")]; + for (const [i5, p5] of chunk.entries()) { + result.push(p5); + if (i5 < chunk.length - 1) { + result.push(new StringChunk(", ")); + } + } + result.push(new StringChunk(")")); + return this.buildQueryFromSourceParams(result, config3); + } + if (is(chunk, _SQL)) { + return this.buildQueryFromSourceParams(chunk.queryChunks, { + ...config3, + inlineParams: inlineParams || chunk.shouldInlineParams + }); + } + if (is(chunk, Table)) { + const schemaName = chunk[Table.Symbol.Schema]; + const tableName = chunk[Table.Symbol.Name]; + return { + sql: schemaName === void 0 ? escapeName(tableName) : escapeName(schemaName) + "." + escapeName(tableName), + params: [] + }; + } + if (is(chunk, Column)) { + const columnName = casing.getColumnCasing(chunk); + if (_config.invokeSource === "indexes") { + return { sql: escapeName(columnName), params: [] }; + } + const schemaName = chunk.table[Table.Symbol.Schema]; + return { + sql: chunk.table[IsAlias] || schemaName === void 0 ? escapeName(chunk.table[Table.Symbol.Name]) + "." + escapeName(columnName) : escapeName(schemaName) + "." + escapeName(chunk.table[Table.Symbol.Name]) + "." + escapeName(columnName), + params: [] + }; + } + if (is(chunk, View)) { + const schemaName = chunk[ViewBaseConfig].schema; + const viewName = chunk[ViewBaseConfig].name; + return { + sql: schemaName === void 0 ? escapeName(viewName) : escapeName(schemaName) + "." + escapeName(viewName), + params: [] + }; + } + if (is(chunk, Param)) { + if (is(chunk.value, Placeholder)) { + return { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: ["none"] }; + } + const mappedValue = chunk.value === null ? null : chunk.encoder.mapToDriverValue(chunk.value); + if (is(mappedValue, _SQL)) { + return this.buildQueryFromSourceParams([mappedValue], config3); + } + if (inlineParams) { + return { sql: this.mapInlineParam(mappedValue, config3), params: [] }; + } + let typings = ["none"]; + if (prepareTyping) { + typings = [prepareTyping(chunk.encoder)]; + } + return { sql: escapeParam(paramStartIndex.value++, mappedValue), params: [mappedValue], typings }; + } + if (is(chunk, Placeholder)) { + return { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: ["none"] }; + } + if (is(chunk, _SQL.Aliased) && chunk.fieldAlias !== void 0) { + return { sql: escapeName(chunk.fieldAlias), params: [] }; + } + if (is(chunk, Subquery)) { + if (chunk._.isWith) { + return { sql: escapeName(chunk._.alias), params: [] }; + } + return this.buildQueryFromSourceParams([ + new StringChunk("("), + chunk._.sql, + new StringChunk(") "), + new Name(chunk._.alias) + ], config3); + } + if (isPgEnum(chunk)) { + if (chunk.schema) { + return { sql: escapeName(chunk.schema) + "." + escapeName(chunk.enumName), params: [] }; + } + return { sql: escapeName(chunk.enumName), params: [] }; + } + if (isSQLWrapper(chunk)) { + if (chunk.shouldOmitSQLParens?.()) { + return this.buildQueryFromSourceParams([chunk.getSQL()], config3); + } + return this.buildQueryFromSourceParams([ + new StringChunk("("), + chunk.getSQL(), + new StringChunk(")") + ], config3); + } + if (inlineParams) { + return { sql: this.mapInlineParam(chunk, config3), params: [] }; + } + return { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: ["none"] }; + })); + } + mapInlineParam(chunk, { escapeString }) { + if (chunk === null) { + return "null"; + } + if (typeof chunk === "number" || typeof chunk === "boolean") { + return chunk.toString(); + } + if (typeof chunk === "string") { + return escapeString(chunk); + } + if (typeof chunk === "object") { + const mappedValueAsString = chunk.toString(); + if (mappedValueAsString === "[object Object]") { + return escapeString(JSON.stringify(chunk)); + } + return escapeString(mappedValueAsString); + } + throw new Error("Unexpected param value: " + chunk); + } + getSQL() { + return this; + } + as(alias) { + if (alias === void 0) { + return this; + } + return new _SQL.Aliased(this, alias); + } + mapWith(decoder2) { + this.decoder = typeof decoder2 === "function" ? { mapFromDriverValue: decoder2 } : decoder2; + return this; + } + inlineParams() { + this.shouldInlineParams = true; + return this; + } + /** + * This method is used to conditionally include a part of the query. + * + * @param condition - Condition to check + * @returns itself if the condition is `true`, otherwise `undefined` + */ + if(condition) { + return condition ? this : void 0; + } + }; + Name = class { + constructor(value) { + this.value = value; + } + static [entityKind] = "Name"; + brand; + getSQL() { + return new SQL([this]); + } + }; + noopDecoder = { + mapFromDriverValue: (value) => value + }; + noopEncoder = { + mapToDriverValue: (value) => value + }; + noopMapper = { + ...noopDecoder, + ...noopEncoder + }; + Param = class { + /** + * @param value - Parameter value + * @param encoder - Encoder to convert the value to a driver parameter + */ + constructor(value, encoder3 = noopEncoder) { + this.value = value; + this.encoder = encoder3; + } + static [entityKind] = "Param"; + brand; + getSQL() { + return new SQL([this]); + } + }; + ((sql22) => { + function empty() { + return new SQL([]); + } + sql22.empty = empty; + function fromList(list2) { + return new SQL(list2); + } + sql22.fromList = fromList; + function raw(str) { + return new SQL([new StringChunk(str)]); + } + sql22.raw = raw; + function join4(chunks, separator) { + const result = []; + for (const [i5, chunk] of chunks.entries()) { + if (i5 > 0 && separator !== void 0) { + result.push(separator); + } + result.push(chunk); + } + return new SQL(result); + } + sql22.join = join4; + function identifier(value) { + return new Name(value); + } + sql22.identifier = identifier; + function placeholder2(name2) { + return new Placeholder(name2); + } + sql22.placeholder = placeholder2; + function param2(value, encoder3) { + return new Param(value, encoder3); + } + sql22.param = param2; + })(sql || (sql = {})); + ((SQL2) => { + class Aliased { + constructor(sql22, fieldAlias) { + this.sql = sql22; + this.fieldAlias = fieldAlias; + } + static [entityKind] = "SQL.Aliased"; + /** @internal */ + isSelectionField = false; + getSQL() { + return this.sql; + } + /** @internal */ + clone() { + return new Aliased(this.sql, this.fieldAlias); + } + } + SQL2.Aliased = Aliased; + })(SQL || (SQL = {})); + Placeholder = class { + constructor(name2) { + this.name = name2; + } + static [entityKind] = "Placeholder"; + getSQL() { + return new SQL([this]); + } + }; + IsDrizzleView = /* @__PURE__ */ Symbol.for("drizzle:IsDrizzleView"); + View = class { + static [entityKind] = "View"; + /** @internal */ + [ViewBaseConfig]; + /** @internal */ + [IsDrizzleView] = true; + constructor({ name: name2, schema: schema2, selectedFields, query }) { + this[ViewBaseConfig] = { + name: name2, + originalName: name2, + schema: schema2, + selectedFields, + query, + isExisting: !query, + isAlias: false + }; + } + getSQL() { + return new SQL([this]); + } + }; + Column.prototype.getSQL = function() { + return new SQL([this]); + }; + Table.prototype.getSQL = function() { + return new SQL([this]); + }; + Subquery.prototype.getSQL = function() { + return new SQL([this]); + }; + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/utils.js +function mapResultRow(columns, row, joinsNotNullableMap) { + const nullifyMap = {}; + const result = columns.reduce( + (result2, { path: path53, field }, columnIndex) => { + let decoder2; + if (is(field, Column)) { + decoder2 = field; + } else if (is(field, SQL)) { + decoder2 = field.decoder; + } else { + decoder2 = field.sql.decoder; + } + let node = result2; + for (const [pathChunkIndex, pathChunk] of path53.entries()) { + if (pathChunkIndex < path53.length - 1) { + if (!(pathChunk in node)) { + node[pathChunk] = {}; + } + node = node[pathChunk]; + } else { + const rawValue = row[columnIndex]; + const value = node[pathChunk] = rawValue === null ? null : decoder2.mapFromDriverValue(rawValue); + if (joinsNotNullableMap && is(field, Column) && path53.length === 2) { + const objectName = path53[0]; + if (!(objectName in nullifyMap)) { + nullifyMap[objectName] = value === null ? getTableName(field.table) : false; + } else if (typeof nullifyMap[objectName] === "string" && nullifyMap[objectName] !== getTableName(field.table)) { + nullifyMap[objectName] = false; + } + } + } + } + return result2; + }, + {} + ); + if (joinsNotNullableMap && Object.keys(nullifyMap).length > 0) { + for (const [objectName, tableName] of Object.entries(nullifyMap)) { + if (typeof tableName === "string" && !joinsNotNullableMap[tableName]) { + result[objectName] = null; + } + } + } + return result; +} +function orderSelectedFields(fields, pathPrefix) { + return Object.entries(fields).reduce((result, [name, field]) => { + if (typeof name !== "string") { + return result; + } + const newPath = pathPrefix ? [...pathPrefix, name] : [name]; + if (is(field, Column) || is(field, SQL) || is(field, SQL.Aliased)) { + result.push({ path: newPath, field }); + } else if (is(field, Table)) { + result.push(...orderSelectedFields(field[Table.Symbol.Columns], newPath)); + } else { + result.push(...orderSelectedFields(field, newPath)); + } + return result; + }, []); +} +function haveSameKeys(left, right) { + const leftKeys = Object.keys(left); + const rightKeys = Object.keys(right); + if (leftKeys.length !== rightKeys.length) { + return false; + } + for (const [index2, key] of leftKeys.entries()) { + if (key !== rightKeys[index2]) { + return false; + } + } + return true; +} +function mapUpdateSet(table, values2) { + const entries2 = Object.entries(values2).filter(([, value]) => value !== void 0).map(([key, value]) => { + if (is(value, SQL) || is(value, Column)) { + return [key, value]; + } else { + return [key, new Param(value, table[Table.Symbol.Columns][key])]; + } + }); + if (entries2.length === 0) { + throw new Error("No values to set"); + } + return Object.fromEntries(entries2); +} +function applyMixins(baseClass, extendedClasses) { + for (const extendedClass of extendedClasses) { + for (const name of Object.getOwnPropertyNames(extendedClass.prototype)) { + if (name === "constructor") + continue; + Object.defineProperty( + baseClass.prototype, + name, + Object.getOwnPropertyDescriptor(extendedClass.prototype, name) || /* @__PURE__ */ Object.create(null) + ); + } + } +} +function getTableColumns(table) { + return table[Table.Symbol.Columns]; +} +function getTableLikeName(table) { + return is(table, Subquery) ? table._.alias : is(table, View) ? table[ViewBaseConfig].name : is(table, SQL) ? void 0 : table[Table.Symbol.IsAlias] ? table[Table.Symbol.Name] : table[Table.Symbol.BaseName]; +} +function getColumnNameAndConfig(a5, b6) { + return { + name: typeof a5 === "string" && a5.length > 0 ? a5 : "", + config: typeof a5 === "object" ? a5 : b6 + }; +} +function isConfig(data2) { + if (typeof data2 !== "object" || data2 === null) + return false; + if (data2.constructor.name !== "Object") + return false; + if ("logger" in data2) { + const type = typeof data2["logger"]; + if (type !== "boolean" && (type !== "object" || typeof data2["logger"]["logQuery"] !== "function") && type !== "undefined") + return false; + return true; + } + if ("schema" in data2) { + const type = typeof data2["logger"]; + if (type !== "object" && type !== "undefined") + return false; + return true; + } + if ("casing" in data2) { + const type = typeof data2["logger"]; + if (type !== "string" && type !== "undefined") + return false; + return true; + } + if ("mode" in data2) { + if (data2["mode"] !== "default" || data2["mode"] !== "planetscale" || data2["mode"] !== void 0) + return false; + return true; + } + if ("connection" in data2) { + const type = typeof data2["connection"]; + if (type !== "string" && type !== "object" && type !== "undefined") + return false; + return true; + } + if ("client" in data2) { + const type = typeof data2["client"]; + if (type !== "object" && type !== "function" && type !== "undefined") + return false; + return true; + } + if (Object.keys(data2).length === 0) + return true; + return false; +} +var init_utils = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/utils.js"() { + init_column(); + init_entity(); + init_sql(); + init_subquery(); + init_table(); + init_view_common(); + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/query-builders/delete.js +var PgDeleteBase; +var init_delete = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/query-builders/delete.js"() { + init_entity(); + init_query_promise(); + init_table(); + init_tracing(); + init_utils(); + PgDeleteBase = class extends QueryPromise { + constructor(table, session, dialect, withList) { + super(); + this.session = session; + this.dialect = dialect; + this.config = { table, withList }; + } + static [entityKind] = "PgDelete"; + config; + /** + * Adds a `where` clause to the query. + * + * Calling this method will delete only those rows that fulfill a specified condition. + * + * See docs: {@link https://orm.drizzle.team/docs/delete} + * + * @param where the `where` clause. + * + * @example + * You can use conditional operators and `sql function` to filter the rows to be deleted. + * + * ```ts + * // Delete all cars with green color + * await db.delete(cars).where(eq(cars.color, 'green')); + * // or + * await db.delete(cars).where(sql`${cars.color} = 'green'`) + * ``` + * + * You can logically combine conditional operators with `and()` and `or()` operators: + * + * ```ts + * // Delete all BMW cars with a green color + * await db.delete(cars).where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW'))); + * + * // Delete all cars with the green or blue color + * await db.delete(cars).where(or(eq(cars.color, 'green'), eq(cars.color, 'blue'))); + * ``` + */ + where(where) { + this.config.where = where; + return this; + } + returning(fields = this.config.table[Table.Symbol.Columns]) { + this.config.returning = orderSelectedFields(fields); + return this; + } + /** @internal */ + getSQL() { + return this.dialect.buildDeleteQuery(this.config); + } + toSQL() { + const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL()); + return rest; + } + /** @internal */ + _prepare(name) { + return tracer.startActiveSpan("drizzle.prepareQuery", () => { + return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), this.config.returning, name, true); + }); + } + prepare(name) { + return this._prepare(name); + } + authToken; + /** @internal */ + setToken(token) { + this.authToken = token; + return this; + } + execute = (placeholderValues) => { + return tracer.startActiveSpan("drizzle.operation", () => { + return this._prepare().execute(placeholderValues, this.authToken); + }); + }; + $dynamic() { + return this; + } + }; + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/alias.js +function aliasedTable(table, tableAlias) { + return new Proxy(table, new TableAliasProxyHandler(tableAlias, false)); +} +function aliasedTableColumn(column, tableAlias) { + return new Proxy( + column, + new ColumnAliasProxyHandler(new Proxy(column.table, new TableAliasProxyHandler(tableAlias, false))) + ); +} +function mapColumnsInAliasedSQLToAlias(query, alias) { + return new SQL.Aliased(mapColumnsInSQLToAlias(query.sql, alias), query.fieldAlias); +} +function mapColumnsInSQLToAlias(query, alias) { + return sql.join(query.queryChunks.map((c5) => { + if (is(c5, Column)) { + return aliasedTableColumn(c5, alias); + } + if (is(c5, SQL)) { + return mapColumnsInSQLToAlias(c5, alias); + } + if (is(c5, SQL.Aliased)) { + return mapColumnsInAliasedSQLToAlias(c5, alias); + } + return c5; + })); +} +var ColumnAliasProxyHandler, TableAliasProxyHandler, RelationTableAliasProxyHandler; +var init_alias = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/alias.js"() { + init_column(); + init_entity(); + init_sql(); + init_table(); + init_view_common(); + ColumnAliasProxyHandler = class { + constructor(table) { + this.table = table; + } + static [entityKind] = "ColumnAliasProxyHandler"; + get(columnObj, prop) { + if (prop === "table") { + return this.table; + } + return columnObj[prop]; + } + }; + TableAliasProxyHandler = class { + constructor(alias, replaceOriginalName) { + this.alias = alias; + this.replaceOriginalName = replaceOriginalName; + } + static [entityKind] = "TableAliasProxyHandler"; + get(target, prop) { + if (prop === Table.Symbol.IsAlias) { + return true; + } + if (prop === Table.Symbol.Name) { + return this.alias; + } + if (this.replaceOriginalName && prop === Table.Symbol.OriginalName) { + return this.alias; + } + if (prop === ViewBaseConfig) { + return { + ...target[ViewBaseConfig], + name: this.alias, + isAlias: true + }; + } + if (prop === Table.Symbol.Columns) { + const columns = target[Table.Symbol.Columns]; + if (!columns) { + return columns; + } + const proxiedColumns = {}; + Object.keys(columns).map((key) => { + proxiedColumns[key] = new Proxy( + columns[key], + new ColumnAliasProxyHandler(new Proxy(target, this)) + ); + }); + return proxiedColumns; + } + const value = target[prop]; + if (is(value, Column)) { + return new Proxy(value, new ColumnAliasProxyHandler(new Proxy(target, this))); + } + return value; + } + }; + RelationTableAliasProxyHandler = class { + constructor(alias) { + this.alias = alias; + } + static [entityKind] = "RelationTableAliasProxyHandler"; + get(target, prop) { + if (prop === "sourceTable") { + return aliasedTable(target.sourceTable, this.alias); + } + return target[prop]; + } + }; + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/casing.js +function toSnakeCase(input) { + const words = input.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? []; + return words.map((word) => word.toLowerCase()).join("_"); +} +function toCamelCase(input) { + const words = input.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? []; + return words.reduce((acc, word, i5) => { + const formattedWord = i5 === 0 ? word.toLowerCase() : `${word[0].toUpperCase()}${word.slice(1)}`; + return acc + formattedWord; + }, ""); +} +function noopCase(input) { + return input; +} +var CasingCache; +var init_casing = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/casing.js"() { + init_entity(); + init_table(); + CasingCache = class { + static [entityKind] = "CasingCache"; + /** @internal */ + cache = {}; + cachedTables = {}; + convert; + constructor(casing) { + this.convert = casing === "snake_case" ? toSnakeCase : casing === "camelCase" ? toCamelCase : noopCase; + } + getColumnCasing(column) { + if (!column.keyAsName) + return column.name; + const schema2 = column.table[Table.Symbol.Schema] ?? "public"; + const tableName = column.table[Table.Symbol.OriginalName]; + const key = `${schema2}.${tableName}.${column.name}`; + if (!this.cache[key]) { + this.cacheTable(column.table); + } + return this.cache[key]; + } + cacheTable(table) { + const schema2 = table[Table.Symbol.Schema] ?? "public"; + const tableName = table[Table.Symbol.OriginalName]; + const tableKey = `${schema2}.${tableName}`; + if (!this.cachedTables[tableKey]) { + for (const column of Object.values(table[Table.Symbol.Columns])) { + const columnKey = `${tableKey}.${column.name}`; + this.cache[columnKey] = this.convert(column.name); + } + this.cachedTables[tableKey] = true; + } + } + clearCache() { + this.cache = {}; + this.cachedTables = {}; + } + }; + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/errors.js +var DrizzleError, TransactionRollbackError; +var init_errors2 = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/errors.js"() { + init_entity(); + DrizzleError = class extends Error { + static [entityKind] = "DrizzleError"; + constructor({ message: message2, cause }) { + super(message2); + this.name = "DrizzleError"; + this.cause = cause; + } + }; + TransactionRollbackError = class extends DrizzleError { + static [entityKind] = "TransactionRollbackError"; + constructor() { + super({ message: "Rollback" }); + } + }; + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/int.common.js +var PgIntColumnBaseBuilder; +var init_int_common = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/int.common.js"() { + init_entity(); + init_common(); + PgIntColumnBaseBuilder = class extends PgColumnBuilder { + static [entityKind] = "PgIntColumnBaseBuilder"; + generatedAlwaysAsIdentity(sequence) { + if (sequence) { + const { name, ...options } = sequence; + this.config.generatedIdentity = { + type: "always", + sequenceName: name, + sequenceOptions: options + }; + } else { + this.config.generatedIdentity = { + type: "always" + }; + } + this.config.hasDefault = true; + this.config.notNull = true; + return this; + } + generatedByDefaultAsIdentity(sequence) { + if (sequence) { + const { name, ...options } = sequence; + this.config.generatedIdentity = { + type: "byDefault", + sequenceName: name, + sequenceOptions: options + }; + } else { + this.config.generatedIdentity = { + type: "byDefault" + }; + } + this.config.hasDefault = true; + this.config.notNull = true; + return this; + } + }; + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/bigint.js +function bigint(a5, b6) { + const { name, config: config3 } = getColumnNameAndConfig(a5, b6); + if (config3.mode === "number") { + return new PgBigInt53Builder(name); + } + return new PgBigInt64Builder(name); +} +var PgBigInt53Builder, PgBigInt53, PgBigInt64Builder, PgBigInt64; +var init_bigint = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/bigint.js"() { + init_entity(); + init_utils(); + init_common(); + init_int_common(); + PgBigInt53Builder = class extends PgIntColumnBaseBuilder { + static [entityKind] = "PgBigInt53Builder"; + constructor(name) { + super(name, "number", "PgBigInt53"); + } + /** @internal */ + build(table) { + return new PgBigInt53(table, this.config); + } + }; + PgBigInt53 = class extends PgColumn { + static [entityKind] = "PgBigInt53"; + getSQLType() { + return "bigint"; + } + mapFromDriverValue(value) { + if (typeof value === "number") { + return value; + } + return Number(value); + } + }; + PgBigInt64Builder = class extends PgIntColumnBaseBuilder { + static [entityKind] = "PgBigInt64Builder"; + constructor(name) { + super(name, "bigint", "PgBigInt64"); + } + /** @internal */ + build(table) { + return new PgBigInt64( + table, + this.config + ); + } + }; + PgBigInt64 = class extends PgColumn { + static [entityKind] = "PgBigInt64"; + getSQLType() { + return "bigint"; + } + // eslint-disable-next-line unicorn/prefer-native-coercion-functions + mapFromDriverValue(value) { + return BigInt(value); + } + }; + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/bigserial.js +function bigserial(a5, b6) { + const { name, config: config3 } = getColumnNameAndConfig(a5, b6); + if (config3.mode === "number") { + return new PgBigSerial53Builder(name); + } + return new PgBigSerial64Builder(name); +} +var PgBigSerial53Builder, PgBigSerial53, PgBigSerial64Builder, PgBigSerial64; +var init_bigserial = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/bigserial.js"() { + init_entity(); + init_utils(); + init_common(); + PgBigSerial53Builder = class extends PgColumnBuilder { + static [entityKind] = "PgBigSerial53Builder"; + constructor(name) { + super(name, "number", "PgBigSerial53"); + this.config.hasDefault = true; + this.config.notNull = true; + } + /** @internal */ + build(table) { + return new PgBigSerial53( + table, + this.config + ); + } + }; + PgBigSerial53 = class extends PgColumn { + static [entityKind] = "PgBigSerial53"; + getSQLType() { + return "bigserial"; + } + mapFromDriverValue(value) { + if (typeof value === "number") { + return value; + } + return Number(value); + } + }; + PgBigSerial64Builder = class extends PgColumnBuilder { + static [entityKind] = "PgBigSerial64Builder"; + constructor(name) { + super(name, "bigint", "PgBigSerial64"); + this.config.hasDefault = true; + } + /** @internal */ + build(table) { + return new PgBigSerial64( + table, + this.config + ); + } + }; + PgBigSerial64 = class extends PgColumn { + static [entityKind] = "PgBigSerial64"; + getSQLType() { + return "bigserial"; + } + // eslint-disable-next-line unicorn/prefer-native-coercion-functions + mapFromDriverValue(value) { + return BigInt(value); + } + }; + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/boolean.js +function boolean(name) { + return new PgBooleanBuilder(name ?? ""); +} +var PgBooleanBuilder, PgBoolean; +var init_boolean = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/boolean.js"() { + init_entity(); + init_common(); + PgBooleanBuilder = class extends PgColumnBuilder { + static [entityKind] = "PgBooleanBuilder"; + constructor(name) { + super(name, "boolean", "PgBoolean"); + } + /** @internal */ + build(table) { + return new PgBoolean(table, this.config); + } + }; + PgBoolean = class extends PgColumn { + static [entityKind] = "PgBoolean"; + getSQLType() { + return "boolean"; + } + }; + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/char.js +function char(a5, b6 = {}) { + const { name, config: config3 } = getColumnNameAndConfig(a5, b6); + return new PgCharBuilder(name, config3); +} +var PgCharBuilder, PgChar; +var init_char = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/char.js"() { + init_entity(); + init_utils(); + init_common(); + PgCharBuilder = class extends PgColumnBuilder { + static [entityKind] = "PgCharBuilder"; + constructor(name, config3) { + super(name, "string", "PgChar"); + this.config.length = config3.length; + this.config.enumValues = config3.enum; + } + /** @internal */ + build(table) { + return new PgChar( + table, + this.config + ); + } + }; + PgChar = class extends PgColumn { + static [entityKind] = "PgChar"; + length = this.config.length; + enumValues = this.config.enumValues; + getSQLType() { + return this.length === void 0 ? `char` : `char(${this.length})`; + } + }; + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/cidr.js +function cidr(name) { + return new PgCidrBuilder(name ?? ""); +} +var PgCidrBuilder, PgCidr; +var init_cidr = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/cidr.js"() { + init_entity(); + init_common(); + PgCidrBuilder = class extends PgColumnBuilder { + static [entityKind] = "PgCidrBuilder"; + constructor(name) { + super(name, "string", "PgCidr"); + } + /** @internal */ + build(table) { + return new PgCidr(table, this.config); + } + }; + PgCidr = class extends PgColumn { + static [entityKind] = "PgCidr"; + getSQLType() { + return "cidr"; + } + }; + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/custom.js +function customType(customTypeParams) { + return (a5, b6) => { + const { name, config: config3 } = getColumnNameAndConfig(a5, b6); + return new PgCustomColumnBuilder(name, config3, customTypeParams); + }; +} +var PgCustomColumnBuilder, PgCustomColumn; +var init_custom = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/custom.js"() { + init_entity(); + init_utils(); + init_common(); + PgCustomColumnBuilder = class extends PgColumnBuilder { + static [entityKind] = "PgCustomColumnBuilder"; + constructor(name, fieldConfig, customTypeParams) { + super(name, "custom", "PgCustomColumn"); + this.config.fieldConfig = fieldConfig; + this.config.customTypeParams = customTypeParams; + } + /** @internal */ + build(table) { + return new PgCustomColumn( + table, + this.config + ); + } + }; + PgCustomColumn = class extends PgColumn { + static [entityKind] = "PgCustomColumn"; + sqlName; + mapTo; + mapFrom; + constructor(table, config3) { + super(table, config3); + this.sqlName = config3.customTypeParams.dataType(config3.fieldConfig); + this.mapTo = config3.customTypeParams.toDriver; + this.mapFrom = config3.customTypeParams.fromDriver; + } + getSQLType() { + return this.sqlName; + } + mapFromDriverValue(value) { + return typeof this.mapFrom === "function" ? this.mapFrom(value) : value; + } + mapToDriverValue(value) { + return typeof this.mapTo === "function" ? this.mapTo(value) : value; + } + }; + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/date.common.js +var PgDateColumnBaseBuilder; +var init_date_common = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/date.common.js"() { + init_entity(); + init_sql(); + init_common(); + PgDateColumnBaseBuilder = class extends PgColumnBuilder { + static [entityKind] = "PgDateColumnBaseBuilder"; + defaultNow() { + return this.default(sql`now()`); + } + }; + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/date.js +function date(a5, b6) { + const { name, config: config3 } = getColumnNameAndConfig(a5, b6); + if (config3?.mode === "date") { + return new PgDateBuilder(name); + } + return new PgDateStringBuilder(name); +} +var PgDateBuilder, PgDate, PgDateStringBuilder, PgDateString; +var init_date = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/date.js"() { + init_entity(); + init_utils(); + init_common(); + init_date_common(); + PgDateBuilder = class extends PgDateColumnBaseBuilder { + static [entityKind] = "PgDateBuilder"; + constructor(name) { + super(name, "date", "PgDate"); + } + /** @internal */ + build(table) { + return new PgDate(table, this.config); + } + }; + PgDate = class extends PgColumn { + static [entityKind] = "PgDate"; + getSQLType() { + return "date"; + } + mapFromDriverValue(value) { + return new Date(value); + } + mapToDriverValue(value) { + return value.toISOString(); + } + }; + PgDateStringBuilder = class extends PgDateColumnBaseBuilder { + static [entityKind] = "PgDateStringBuilder"; + constructor(name) { + super(name, "string", "PgDateString"); + } + /** @internal */ + build(table) { + return new PgDateString( + table, + this.config + ); + } + }; + PgDateString = class extends PgColumn { + static [entityKind] = "PgDateString"; + getSQLType() { + return "date"; + } + }; + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/double-precision.js +function doublePrecision(name) { + return new PgDoublePrecisionBuilder(name ?? ""); +} +var PgDoublePrecisionBuilder, PgDoublePrecision; +var init_double_precision = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/double-precision.js"() { + init_entity(); + init_common(); + PgDoublePrecisionBuilder = class extends PgColumnBuilder { + static [entityKind] = "PgDoublePrecisionBuilder"; + constructor(name) { + super(name, "number", "PgDoublePrecision"); + } + /** @internal */ + build(table) { + return new PgDoublePrecision( + table, + this.config + ); + } + }; + PgDoublePrecision = class extends PgColumn { + static [entityKind] = "PgDoublePrecision"; + getSQLType() { + return "double precision"; + } + mapFromDriverValue(value) { + if (typeof value === "string") { + return Number.parseFloat(value); + } + return value; + } + }; + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/inet.js +function inet(name) { + return new PgInetBuilder(name ?? ""); +} +var PgInetBuilder, PgInet; +var init_inet = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/inet.js"() { + init_entity(); + init_common(); + PgInetBuilder = class extends PgColumnBuilder { + static [entityKind] = "PgInetBuilder"; + constructor(name) { + super(name, "string", "PgInet"); + } + /** @internal */ + build(table) { + return new PgInet(table, this.config); + } + }; + PgInet = class extends PgColumn { + static [entityKind] = "PgInet"; + getSQLType() { + return "inet"; + } + }; + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/integer.js +function integer(name) { + return new PgIntegerBuilder(name ?? ""); +} +var PgIntegerBuilder, PgInteger; +var init_integer = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/integer.js"() { + init_entity(); + init_common(); + init_int_common(); + PgIntegerBuilder = class extends PgIntColumnBaseBuilder { + static [entityKind] = "PgIntegerBuilder"; + constructor(name) { + super(name, "number", "PgInteger"); + } + /** @internal */ + build(table) { + return new PgInteger(table, this.config); + } + }; + PgInteger = class extends PgColumn { + static [entityKind] = "PgInteger"; + getSQLType() { + return "integer"; + } + mapFromDriverValue(value) { + if (typeof value === "string") { + return Number.parseInt(value); + } + return value; + } + }; + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/interval.js +function interval(a5, b6 = {}) { + const { name, config: config3 } = getColumnNameAndConfig(a5, b6); + return new PgIntervalBuilder(name, config3); +} +var PgIntervalBuilder, PgInterval; +var init_interval = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/interval.js"() { + init_entity(); + init_utils(); + init_common(); + PgIntervalBuilder = class extends PgColumnBuilder { + static [entityKind] = "PgIntervalBuilder"; + constructor(name, intervalConfig) { + super(name, "string", "PgInterval"); + this.config.intervalConfig = intervalConfig; + } + /** @internal */ + build(table) { + return new PgInterval(table, this.config); + } + }; + PgInterval = class extends PgColumn { + static [entityKind] = "PgInterval"; + fields = this.config.intervalConfig.fields; + precision = this.config.intervalConfig.precision; + getSQLType() { + const fields = this.fields ? ` ${this.fields}` : ""; + const precision = this.precision ? `(${this.precision})` : ""; + return `interval${fields}${precision}`; + } + }; + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/json.js +function json(name) { + return new PgJsonBuilder(name ?? ""); +} +var PgJsonBuilder, PgJson; +var init_json = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/json.js"() { + init_entity(); + init_common(); + PgJsonBuilder = class extends PgColumnBuilder { + static [entityKind] = "PgJsonBuilder"; + constructor(name) { + super(name, "json", "PgJson"); + } + /** @internal */ + build(table) { + return new PgJson(table, this.config); + } + }; + PgJson = class extends PgColumn { + static [entityKind] = "PgJson"; + constructor(table, config3) { + super(table, config3); + } + getSQLType() { + return "json"; + } + mapToDriverValue(value) { + return JSON.stringify(value); + } + mapFromDriverValue(value) { + if (typeof value === "string") { + try { + return JSON.parse(value); + } catch { + return value; + } + } + return value; + } + }; + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/jsonb.js +function jsonb(name) { + return new PgJsonbBuilder(name ?? ""); +} +var PgJsonbBuilder, PgJsonb; +var init_jsonb = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/jsonb.js"() { + init_entity(); + init_common(); + PgJsonbBuilder = class extends PgColumnBuilder { + static [entityKind] = "PgJsonbBuilder"; + constructor(name) { + super(name, "json", "PgJsonb"); + } + /** @internal */ + build(table) { + return new PgJsonb(table, this.config); + } + }; + PgJsonb = class extends PgColumn { + static [entityKind] = "PgJsonb"; + constructor(table, config3) { + super(table, config3); + } + getSQLType() { + return "jsonb"; + } + mapToDriverValue(value) { + return JSON.stringify(value); + } + mapFromDriverValue(value) { + if (typeof value === "string") { + try { + return JSON.parse(value); + } catch { + return value; + } + } + return value; + } + }; + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/line.js +function line(a5, b6) { + const { name, config: config3 } = getColumnNameAndConfig(a5, b6); + if (!config3?.mode || config3.mode === "tuple") { + return new PgLineBuilder(name); + } + return new PgLineABCBuilder(name); +} +var PgLineBuilder, PgLineTuple, PgLineABCBuilder, PgLineABC; +var init_line = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/line.js"() { + init_entity(); + init_utils(); + init_common(); + PgLineBuilder = class extends PgColumnBuilder { + static [entityKind] = "PgLineBuilder"; + constructor(name) { + super(name, "array", "PgLine"); + } + /** @internal */ + build(table) { + return new PgLineTuple( + table, + this.config + ); + } + }; + PgLineTuple = class extends PgColumn { + static [entityKind] = "PgLine"; + getSQLType() { + return "line"; + } + mapFromDriverValue(value) { + const [a5, b6, c5] = value.slice(1, -1).split(","); + return [Number.parseFloat(a5), Number.parseFloat(b6), Number.parseFloat(c5)]; + } + mapToDriverValue(value) { + return `{${value[0]},${value[1]},${value[2]}}`; + } + }; + PgLineABCBuilder = class extends PgColumnBuilder { + static [entityKind] = "PgLineABCBuilder"; + constructor(name) { + super(name, "json", "PgLineABC"); + } + /** @internal */ + build(table) { + return new PgLineABC( + table, + this.config + ); + } + }; + PgLineABC = class extends PgColumn { + static [entityKind] = "PgLineABC"; + getSQLType() { + return "line"; + } + mapFromDriverValue(value) { + const [a5, b6, c5] = value.slice(1, -1).split(","); + return { a: Number.parseFloat(a5), b: Number.parseFloat(b6), c: Number.parseFloat(c5) }; + } + mapToDriverValue(value) { + return `{${value.a},${value.b},${value.c}}`; + } + }; + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/macaddr.js +function macaddr(name) { + return new PgMacaddrBuilder(name ?? ""); +} +var PgMacaddrBuilder, PgMacaddr; +var init_macaddr = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/macaddr.js"() { + init_entity(); + init_common(); + PgMacaddrBuilder = class extends PgColumnBuilder { + static [entityKind] = "PgMacaddrBuilder"; + constructor(name) { + super(name, "string", "PgMacaddr"); + } + /** @internal */ + build(table) { + return new PgMacaddr(table, this.config); + } + }; + PgMacaddr = class extends PgColumn { + static [entityKind] = "PgMacaddr"; + getSQLType() { + return "macaddr"; + } + }; + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/macaddr8.js +function macaddr8(name) { + return new PgMacaddr8Builder(name ?? ""); +} +var PgMacaddr8Builder, PgMacaddr8; +var init_macaddr8 = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/macaddr8.js"() { + init_entity(); + init_common(); + PgMacaddr8Builder = class extends PgColumnBuilder { + static [entityKind] = "PgMacaddr8Builder"; + constructor(name) { + super(name, "string", "PgMacaddr8"); + } + /** @internal */ + build(table) { + return new PgMacaddr8(table, this.config); + } + }; + PgMacaddr8 = class extends PgColumn { + static [entityKind] = "PgMacaddr8"; + getSQLType() { + return "macaddr8"; + } + }; + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/numeric.js +function numeric(a5, b6) { + const { name, config: config3 } = getColumnNameAndConfig(a5, b6); + return new PgNumericBuilder(name, config3?.precision, config3?.scale); +} +var PgNumericBuilder, PgNumeric; +var init_numeric = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/numeric.js"() { + init_entity(); + init_utils(); + init_common(); + PgNumericBuilder = class extends PgColumnBuilder { + static [entityKind] = "PgNumericBuilder"; + constructor(name, precision, scale) { + super(name, "string", "PgNumeric"); + this.config.precision = precision; + this.config.scale = scale; + } + /** @internal */ + build(table) { + return new PgNumeric(table, this.config); + } + }; + PgNumeric = class extends PgColumn { + static [entityKind] = "PgNumeric"; + precision; + scale; + constructor(table, config3) { + super(table, config3); + this.precision = config3.precision; + this.scale = config3.scale; + } + getSQLType() { + if (this.precision !== void 0 && this.scale !== void 0) { + return `numeric(${this.precision}, ${this.scale})`; + } else if (this.precision === void 0) { + return "numeric"; + } else { + return `numeric(${this.precision})`; + } + } + }; + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/point.js +function point(a5, b6) { + const { name, config: config3 } = getColumnNameAndConfig(a5, b6); + if (!config3?.mode || config3.mode === "tuple") { + return new PgPointTupleBuilder(name); + } + return new PgPointObjectBuilder(name); +} +var PgPointTupleBuilder, PgPointTuple, PgPointObjectBuilder, PgPointObject; +var init_point = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/point.js"() { + init_entity(); + init_utils(); + init_common(); + PgPointTupleBuilder = class extends PgColumnBuilder { + static [entityKind] = "PgPointTupleBuilder"; + constructor(name) { + super(name, "array", "PgPointTuple"); + } + /** @internal */ + build(table) { + return new PgPointTuple( + table, + this.config + ); + } + }; + PgPointTuple = class extends PgColumn { + static [entityKind] = "PgPointTuple"; + getSQLType() { + return "point"; + } + mapFromDriverValue(value) { + if (typeof value === "string") { + const [x5, y2] = value.slice(1, -1).split(","); + return [Number.parseFloat(x5), Number.parseFloat(y2)]; + } + return [value.x, value.y]; + } + mapToDriverValue(value) { + return `(${value[0]},${value[1]})`; + } + }; + PgPointObjectBuilder = class extends PgColumnBuilder { + static [entityKind] = "PgPointObjectBuilder"; + constructor(name) { + super(name, "json", "PgPointObject"); + } + /** @internal */ + build(table) { + return new PgPointObject( + table, + this.config + ); + } + }; + PgPointObject = class extends PgColumn { + static [entityKind] = "PgPointObject"; + getSQLType() { + return "point"; + } + mapFromDriverValue(value) { + if (typeof value === "string") { + const [x5, y2] = value.slice(1, -1).split(","); + return { x: Number.parseFloat(x5), y: Number.parseFloat(y2) }; + } + return value; + } + mapToDriverValue(value) { + return `(${value.x},${value.y})`; + } + }; + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/postgis_extension/utils.js +function hexToBytes(hex4) { + const bytes = []; + for (let c5 = 0; c5 < hex4.length; c5 += 2) { + bytes.push(Number.parseInt(hex4.slice(c5, c5 + 2), 16)); + } + return new Uint8Array(bytes); +} +function bytesToFloat64(bytes, offset) { + const buffer2 = new ArrayBuffer(8); + const view = new DataView(buffer2); + for (let i5 = 0; i5 < 8; i5++) { + view.setUint8(i5, bytes[offset + i5]); + } + return view.getFloat64(0, true); +} +function parseEWKB(hex4) { + const bytes = hexToBytes(hex4); + let offset = 0; + const byteOrder = bytes[offset]; + offset += 1; + const view = new DataView(bytes.buffer); + const geomType = view.getUint32(offset, byteOrder === 1); + offset += 4; + let _srid; + if (geomType & 536870912) { + _srid = view.getUint32(offset, byteOrder === 1); + offset += 4; + } + if ((geomType & 65535) === 1) { + const x5 = bytesToFloat64(bytes, offset); + offset += 8; + const y2 = bytesToFloat64(bytes, offset); + offset += 8; + return [x5, y2]; + } + throw new Error("Unsupported geometry type"); +} +var init_utils2 = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/postgis_extension/utils.js"() { + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/postgis_extension/geometry.js +function geometry(a5, b6) { + const { name, config: config3 } = getColumnNameAndConfig(a5, b6); + if (!config3?.mode || config3.mode === "tuple") { + return new PgGeometryBuilder(name); + } + return new PgGeometryObjectBuilder(name); +} +var PgGeometryBuilder, PgGeometry, PgGeometryObjectBuilder, PgGeometryObject; +var init_geometry = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/postgis_extension/geometry.js"() { + init_entity(); + init_utils(); + init_common(); + init_utils2(); + PgGeometryBuilder = class extends PgColumnBuilder { + static [entityKind] = "PgGeometryBuilder"; + constructor(name) { + super(name, "array", "PgGeometry"); + } + /** @internal */ + build(table) { + return new PgGeometry( + table, + this.config + ); + } + }; + PgGeometry = class extends PgColumn { + static [entityKind] = "PgGeometry"; + getSQLType() { + return "geometry(point)"; + } + mapFromDriverValue(value) { + return parseEWKB(value); + } + mapToDriverValue(value) { + return `point(${value[0]} ${value[1]})`; + } + }; + PgGeometryObjectBuilder = class extends PgColumnBuilder { + static [entityKind] = "PgGeometryObjectBuilder"; + constructor(name) { + super(name, "json", "PgGeometryObject"); + } + /** @internal */ + build(table) { + return new PgGeometryObject( + table, + this.config + ); + } + }; + PgGeometryObject = class extends PgColumn { + static [entityKind] = "PgGeometryObject"; + getSQLType() { + return "geometry(point)"; + } + mapFromDriverValue(value) { + const parsed = parseEWKB(value); + return { x: parsed[0], y: parsed[1] }; + } + mapToDriverValue(value) { + return `point(${value.x} ${value.y})`; + } + }; + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/real.js +function real(name) { + return new PgRealBuilder(name ?? ""); +} +var PgRealBuilder, PgReal; +var init_real = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/real.js"() { + init_entity(); + init_common(); + PgRealBuilder = class extends PgColumnBuilder { + static [entityKind] = "PgRealBuilder"; + constructor(name, length) { + super(name, "number", "PgReal"); + this.config.length = length; + } + /** @internal */ + build(table) { + return new PgReal(table, this.config); + } + }; + PgReal = class extends PgColumn { + static [entityKind] = "PgReal"; + constructor(table, config3) { + super(table, config3); + } + getSQLType() { + return "real"; + } + mapFromDriverValue = (value) => { + if (typeof value === "string") { + return Number.parseFloat(value); + } + return value; + }; + }; + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/serial.js +function serial(name) { + return new PgSerialBuilder(name ?? ""); +} +var PgSerialBuilder, PgSerial; +var init_serial = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/serial.js"() { + init_entity(); + init_common(); + PgSerialBuilder = class extends PgColumnBuilder { + static [entityKind] = "PgSerialBuilder"; + constructor(name) { + super(name, "number", "PgSerial"); + this.config.hasDefault = true; + this.config.notNull = true; + } + /** @internal */ + build(table) { + return new PgSerial(table, this.config); + } + }; + PgSerial = class extends PgColumn { + static [entityKind] = "PgSerial"; + getSQLType() { + return "serial"; + } + }; + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/smallint.js +function smallint(name) { + return new PgSmallIntBuilder(name ?? ""); +} +var PgSmallIntBuilder, PgSmallInt; +var init_smallint = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/smallint.js"() { + init_entity(); + init_common(); + init_int_common(); + PgSmallIntBuilder = class extends PgIntColumnBaseBuilder { + static [entityKind] = "PgSmallIntBuilder"; + constructor(name) { + super(name, "number", "PgSmallInt"); + } + /** @internal */ + build(table) { + return new PgSmallInt(table, this.config); + } + }; + PgSmallInt = class extends PgColumn { + static [entityKind] = "PgSmallInt"; + getSQLType() { + return "smallint"; + } + mapFromDriverValue = (value) => { + if (typeof value === "string") { + return Number(value); + } + return value; + }; + }; + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/smallserial.js +function smallserial(name) { + return new PgSmallSerialBuilder(name ?? ""); +} +var PgSmallSerialBuilder, PgSmallSerial; +var init_smallserial = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/smallserial.js"() { + init_entity(); + init_common(); + PgSmallSerialBuilder = class extends PgColumnBuilder { + static [entityKind] = "PgSmallSerialBuilder"; + constructor(name) { + super(name, "number", "PgSmallSerial"); + this.config.hasDefault = true; + this.config.notNull = true; + } + /** @internal */ + build(table) { + return new PgSmallSerial( + table, + this.config + ); + } + }; + PgSmallSerial = class extends PgColumn { + static [entityKind] = "PgSmallSerial"; + getSQLType() { + return "smallserial"; + } + }; + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/text.js +function text(a5, b6 = {}) { + const { name, config: config3 } = getColumnNameAndConfig(a5, b6); + return new PgTextBuilder(name, config3); +} +var PgTextBuilder, PgText; +var init_text = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/text.js"() { + init_entity(); + init_utils(); + init_common(); + PgTextBuilder = class extends PgColumnBuilder { + static [entityKind] = "PgTextBuilder"; + constructor(name, config3) { + super(name, "string", "PgText"); + this.config.enumValues = config3.enum; + } + /** @internal */ + build(table) { + return new PgText(table, this.config); + } + }; + PgText = class extends PgColumn { + static [entityKind] = "PgText"; + enumValues = this.config.enumValues; + getSQLType() { + return "text"; + } + }; + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/time.js +function time(a5, b6 = {}) { + const { name, config: config3 } = getColumnNameAndConfig(a5, b6); + return new PgTimeBuilder(name, config3.withTimezone ?? false, config3.precision); +} +var PgTimeBuilder, PgTime; +var init_time = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/time.js"() { + init_entity(); + init_utils(); + init_common(); + init_date_common(); + PgTimeBuilder = class extends PgDateColumnBaseBuilder { + constructor(name, withTimezone, precision) { + super(name, "string", "PgTime"); + this.withTimezone = withTimezone; + this.precision = precision; + this.config.withTimezone = withTimezone; + this.config.precision = precision; + } + static [entityKind] = "PgTimeBuilder"; + /** @internal */ + build(table) { + return new PgTime(table, this.config); + } + }; + PgTime = class extends PgColumn { + static [entityKind] = "PgTime"; + withTimezone; + precision; + constructor(table, config3) { + super(table, config3); + this.withTimezone = config3.withTimezone; + this.precision = config3.precision; + } + getSQLType() { + const precision = this.precision === void 0 ? "" : `(${this.precision})`; + return `time${precision}${this.withTimezone ? " with time zone" : ""}`; + } + }; + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/timestamp.js +function timestamp(a5, b6 = {}) { + const { name, config: config3 } = getColumnNameAndConfig(a5, b6); + if (config3?.mode === "string") { + return new PgTimestampStringBuilder(name, config3.withTimezone ?? false, config3.precision); + } + return new PgTimestampBuilder(name, config3?.withTimezone ?? false, config3?.precision); +} +var PgTimestampBuilder, PgTimestamp, PgTimestampStringBuilder, PgTimestampString; +var init_timestamp = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/timestamp.js"() { + init_entity(); + init_utils(); + init_common(); + init_date_common(); + PgTimestampBuilder = class extends PgDateColumnBaseBuilder { + static [entityKind] = "PgTimestampBuilder"; + constructor(name, withTimezone, precision) { + super(name, "date", "PgTimestamp"); + this.config.withTimezone = withTimezone; + this.config.precision = precision; + } + /** @internal */ + build(table) { + return new PgTimestamp(table, this.config); + } + }; + PgTimestamp = class extends PgColumn { + static [entityKind] = "PgTimestamp"; + withTimezone; + precision; + constructor(table, config3) { + super(table, config3); + this.withTimezone = config3.withTimezone; + this.precision = config3.precision; + } + getSQLType() { + const precision = this.precision === void 0 ? "" : ` (${this.precision})`; + return `timestamp${precision}${this.withTimezone ? " with time zone" : ""}`; + } + mapFromDriverValue = (value) => { + return new Date(this.withTimezone ? value : value + "+0000"); + }; + mapToDriverValue = (value) => { + return value.toISOString(); + }; + }; + PgTimestampStringBuilder = class extends PgDateColumnBaseBuilder { + static [entityKind] = "PgTimestampStringBuilder"; + constructor(name, withTimezone, precision) { + super(name, "string", "PgTimestampString"); + this.config.withTimezone = withTimezone; + this.config.precision = precision; + } + /** @internal */ + build(table) { + return new PgTimestampString( + table, + this.config + ); + } + }; + PgTimestampString = class extends PgColumn { + static [entityKind] = "PgTimestampString"; + withTimezone; + precision; + constructor(table, config3) { + super(table, config3); + this.withTimezone = config3.withTimezone; + this.precision = config3.precision; + } + getSQLType() { + const precision = this.precision === void 0 ? "" : `(${this.precision})`; + return `timestamp${precision}${this.withTimezone ? " with time zone" : ""}`; + } + }; + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/uuid.js +function uuid(name) { + return new PgUUIDBuilder(name ?? ""); +} +var PgUUIDBuilder, PgUUID; +var init_uuid = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/uuid.js"() { + init_entity(); + init_sql(); + init_common(); + PgUUIDBuilder = class extends PgColumnBuilder { + static [entityKind] = "PgUUIDBuilder"; + constructor(name) { + super(name, "string", "PgUUID"); + } + /** + * Adds `default gen_random_uuid()` to the column definition. + */ + defaultRandom() { + return this.default(sql`gen_random_uuid()`); + } + /** @internal */ + build(table) { + return new PgUUID(table, this.config); + } + }; + PgUUID = class extends PgColumn { + static [entityKind] = "PgUUID"; + getSQLType() { + return "uuid"; + } + }; + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/varchar.js +function varchar(a5, b6 = {}) { + const { name, config: config3 } = getColumnNameAndConfig(a5, b6); + return new PgVarcharBuilder(name, config3); +} +var PgVarcharBuilder, PgVarchar; +var init_varchar = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/varchar.js"() { + init_entity(); + init_utils(); + init_common(); + PgVarcharBuilder = class extends PgColumnBuilder { + static [entityKind] = "PgVarcharBuilder"; + constructor(name, config3) { + super(name, "string", "PgVarchar"); + this.config.length = config3.length; + this.config.enumValues = config3.enum; + } + /** @internal */ + build(table) { + return new PgVarchar( + table, + this.config + ); + } + }; + PgVarchar = class extends PgColumn { + static [entityKind] = "PgVarchar"; + length = this.config.length; + enumValues = this.config.enumValues; + getSQLType() { + return this.length === void 0 ? `varchar` : `varchar(${this.length})`; + } + }; + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/vector_extension/bit.js +function bit(a5, b6) { + const { name, config: config3 } = getColumnNameAndConfig(a5, b6); + return new PgBinaryVectorBuilder(name, config3); +} +var PgBinaryVectorBuilder, PgBinaryVector; +var init_bit = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/vector_extension/bit.js"() { + init_entity(); + init_utils(); + init_common(); + PgBinaryVectorBuilder = class extends PgColumnBuilder { + static [entityKind] = "PgBinaryVectorBuilder"; + constructor(name, config3) { + super(name, "string", "PgBinaryVector"); + this.config.dimensions = config3.dimensions; + } + /** @internal */ + build(table) { + return new PgBinaryVector( + table, + this.config + ); + } + }; + PgBinaryVector = class extends PgColumn { + static [entityKind] = "PgBinaryVector"; + dimensions = this.config.dimensions; + getSQLType() { + return `bit(${this.dimensions})`; + } + }; + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/vector_extension/halfvec.js +function halfvec(a5, b6) { + const { name, config: config3 } = getColumnNameAndConfig(a5, b6); + return new PgHalfVectorBuilder(name, config3); +} +var PgHalfVectorBuilder, PgHalfVector; +var init_halfvec = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/vector_extension/halfvec.js"() { + init_entity(); + init_utils(); + init_common(); + PgHalfVectorBuilder = class extends PgColumnBuilder { + static [entityKind] = "PgHalfVectorBuilder"; + constructor(name, config3) { + super(name, "array", "PgHalfVector"); + this.config.dimensions = config3.dimensions; + } + /** @internal */ + build(table) { + return new PgHalfVector( + table, + this.config + ); + } + }; + PgHalfVector = class extends PgColumn { + static [entityKind] = "PgHalfVector"; + dimensions = this.config.dimensions; + getSQLType() { + return `halfvec(${this.dimensions})`; + } + mapToDriverValue(value) { + return JSON.stringify(value); + } + mapFromDriverValue(value) { + return value.slice(1, -1).split(",").map((v5) => Number.parseFloat(v5)); + } + }; + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/vector_extension/sparsevec.js +function sparsevec(a5, b6) { + const { name, config: config3 } = getColumnNameAndConfig(a5, b6); + return new PgSparseVectorBuilder(name, config3); +} +var PgSparseVectorBuilder, PgSparseVector; +var init_sparsevec = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/vector_extension/sparsevec.js"() { + init_entity(); + init_utils(); + init_common(); + PgSparseVectorBuilder = class extends PgColumnBuilder { + static [entityKind] = "PgSparseVectorBuilder"; + constructor(name, config3) { + super(name, "string", "PgSparseVector"); + this.config.dimensions = config3.dimensions; + } + /** @internal */ + build(table) { + return new PgSparseVector( + table, + this.config + ); + } + }; + PgSparseVector = class extends PgColumn { + static [entityKind] = "PgSparseVector"; + dimensions = this.config.dimensions; + getSQLType() { + return `sparsevec(${this.dimensions})`; + } + }; + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/vector_extension/vector.js +function vector(a5, b6) { + const { name, config: config3 } = getColumnNameAndConfig(a5, b6); + return new PgVectorBuilder(name, config3); +} +var PgVectorBuilder, PgVector; +var init_vector = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/vector_extension/vector.js"() { + init_entity(); + init_utils(); + init_common(); + PgVectorBuilder = class extends PgColumnBuilder { + static [entityKind] = "PgVectorBuilder"; + constructor(name, config3) { + super(name, "array", "PgVector"); + this.config.dimensions = config3.dimensions; + } + /** @internal */ + build(table) { + return new PgVector( + table, + this.config + ); + } + }; + PgVector = class extends PgColumn { + static [entityKind] = "PgVector"; + dimensions = this.config.dimensions; + getSQLType() { + return `vector(${this.dimensions})`; + } + mapToDriverValue(value) { + return JSON.stringify(value); + } + mapFromDriverValue(value) { + return value.slice(1, -1).split(",").map((v5) => Number.parseFloat(v5)); + } + }; + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/index.js +var init_columns = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/index.js"() { + init_bigint(); + init_bigserial(); + init_boolean(); + init_char(); + init_cidr(); + init_common(); + init_custom(); + init_date(); + init_double_precision(); + init_enum(); + init_inet(); + init_int_common(); + init_integer(); + init_interval(); + init_json(); + init_jsonb(); + init_line(); + init_macaddr(); + init_macaddr8(); + init_numeric(); + init_point(); + init_geometry(); + init_real(); + init_serial(); + init_smallint(); + init_smallserial(); + init_text(); + init_time(); + init_timestamp(); + init_uuid(); + init_varchar(); + init_bit(); + init_halfvec(); + init_sparsevec(); + init_vector(); + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/all.js +function getPgColumnBuilders() { + return { + bigint, + bigserial, + boolean, + char, + cidr, + customType, + date, + doublePrecision, + inet, + integer, + interval, + json, + jsonb, + line, + macaddr, + macaddr8, + numeric, + point, + geometry, + real, + serial, + smallint, + smallserial, + text, + time, + timestamp, + uuid, + varchar, + bit, + halfvec, + sparsevec, + vector + }; +} +var init_all = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/all.js"() { + init_bigint(); + init_bigserial(); + init_boolean(); + init_char(); + init_cidr(); + init_custom(); + init_date(); + init_double_precision(); + init_inet(); + init_integer(); + init_interval(); + init_json(); + init_jsonb(); + init_line(); + init_macaddr(); + init_macaddr8(); + init_numeric(); + init_point(); + init_geometry(); + init_real(); + init_serial(); + init_smallint(); + init_smallserial(); + init_text(); + init_time(); + init_timestamp(); + init_uuid(); + init_varchar(); + init_bit(); + init_halfvec(); + init_sparsevec(); + init_vector(); + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/table.js +function pgTableWithSchema(name, columns, extraConfig, schema2, baseName = name) { + const rawTable = new PgTable(name, schema2, baseName); + const parsedColumns = typeof columns === "function" ? columns(getPgColumnBuilders()) : columns; + const builtColumns = Object.fromEntries( + Object.entries(parsedColumns).map(([name2, colBuilderBase]) => { + const colBuilder = colBuilderBase; + colBuilder.setName(name2); + const column = colBuilder.build(rawTable); + rawTable[InlineForeignKeys].push(...colBuilder.buildForeignKeys(column, rawTable)); + return [name2, column]; + }) + ); + const builtColumnsForExtraConfig = Object.fromEntries( + Object.entries(parsedColumns).map(([name2, colBuilderBase]) => { + const colBuilder = colBuilderBase; + colBuilder.setName(name2); + const column = colBuilder.buildExtraConfigColumn(rawTable); + return [name2, column]; + }) + ); + const table = Object.assign(rawTable, builtColumns); + table[Table.Symbol.Columns] = builtColumns; + table[Table.Symbol.ExtraConfigColumns] = builtColumnsForExtraConfig; + if (extraConfig) { + table[PgTable.Symbol.ExtraConfigBuilder] = extraConfig; + } + return Object.assign(table, { + enableRLS: () => { + table[PgTable.Symbol.EnableRLS] = true; + return table; + } + }); +} +var InlineForeignKeys, EnableRLS, PgTable, pgTable; +var init_table2 = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/table.js"() { + init_entity(); + init_table(); + init_all(); + InlineForeignKeys = /* @__PURE__ */ Symbol.for("drizzle:PgInlineForeignKeys"); + EnableRLS = /* @__PURE__ */ Symbol.for("drizzle:EnableRLS"); + PgTable = class extends Table { + static [entityKind] = "PgTable"; + /** @internal */ + static Symbol = Object.assign({}, Table.Symbol, { + InlineForeignKeys, + EnableRLS + }); + /**@internal */ + [InlineForeignKeys] = []; + /** @internal */ + [EnableRLS] = false; + /** @internal */ + [Table.Symbol.ExtraConfigBuilder] = void 0; + }; + pgTable = (name, columns, extraConfig) => { + return pgTableWithSchema(name, columns, extraConfig, void 0); + }; + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/primary-keys.js +function primaryKey(...config3) { + if (config3[0].columns) { + return new PrimaryKeyBuilder(config3[0].columns, config3[0].name); + } + return new PrimaryKeyBuilder(config3); +} +var PrimaryKeyBuilder, PrimaryKey; +var init_primary_keys = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/primary-keys.js"() { + init_entity(); + init_table2(); + PrimaryKeyBuilder = class { + static [entityKind] = "PgPrimaryKeyBuilder"; + /** @internal */ + columns; + /** @internal */ + name; + constructor(columns, name) { + this.columns = columns; + this.name = name; + } + /** @internal */ + build(table) { + return new PrimaryKey(table, this.columns, this.name); + } + }; + PrimaryKey = class { + constructor(table, columns, name) { + this.table = table; + this.columns = columns; + this.name = name; + } + static [entityKind] = "PgPrimaryKey"; + columns; + name; + getName() { + return this.name ?? `${this.table[PgTable.Symbol.Name]}_${this.columns.map((column) => column.name).join("_")}_pk`; + } + }; + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/sql/expressions/conditions.js +function bindIfParam(value, column) { + if (isDriverValueEncoder(column) && !isSQLWrapper(value) && !is(value, Param) && !is(value, Placeholder) && !is(value, Column) && !is(value, Table) && !is(value, View)) { + return new Param(value, column); + } + return value; +} +function and(...unfilteredConditions) { + const conditions = unfilteredConditions.filter( + (c5) => c5 !== void 0 + ); + if (conditions.length === 0) { + return void 0; + } + if (conditions.length === 1) { + return new SQL(conditions); + } + return new SQL([ + new StringChunk("("), + sql.join(conditions, new StringChunk(" and ")), + new StringChunk(")") + ]); +} +function or(...unfilteredConditions) { + const conditions = unfilteredConditions.filter( + (c5) => c5 !== void 0 + ); + if (conditions.length === 0) { + return void 0; + } + if (conditions.length === 1) { + return new SQL(conditions); + } + return new SQL([ + new StringChunk("("), + sql.join(conditions, new StringChunk(" or ")), + new StringChunk(")") + ]); +} +function not(condition) { + return sql`not ${condition}`; +} +function inArray(column, values2) { + if (Array.isArray(values2)) { + if (values2.length === 0) { + return sql`false`; + } + return sql`${column} in ${values2.map((v5) => bindIfParam(v5, column))}`; + } + return sql`${column} in ${bindIfParam(values2, column)}`; +} +function notInArray(column, values2) { + if (Array.isArray(values2)) { + if (values2.length === 0) { + return sql`true`; + } + return sql`${column} not in ${values2.map((v5) => bindIfParam(v5, column))}`; + } + return sql`${column} not in ${bindIfParam(values2, column)}`; +} +function isNull(value) { + return sql`${value} is null`; +} +function isNotNull(value) { + return sql`${value} is not null`; +} +function exists(subquery) { + return sql`exists ${subquery}`; +} +function notExists(subquery) { + return sql`not exists ${subquery}`; +} +function between(column, min, max) { + return sql`${column} between ${bindIfParam(min, column)} and ${bindIfParam( + max, + column + )}`; +} +function notBetween(column, min, max) { + return sql`${column} not between ${bindIfParam( + min, + column + )} and ${bindIfParam(max, column)}`; +} +function like(column, value) { + return sql`${column} like ${value}`; +} +function notLike(column, value) { + return sql`${column} not like ${value}`; +} +function ilike(column, value) { + return sql`${column} ilike ${value}`; +} +function notIlike(column, value) { + return sql`${column} not ilike ${value}`; +} +var eq, ne, gt, gte, lt, lte; +var init_conditions = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/sql/expressions/conditions.js"() { + init_column(); + init_entity(); + init_table(); + init_sql(); + eq = (left, right) => { + return sql`${left} = ${bindIfParam(right, left)}`; + }; + ne = (left, right) => { + return sql`${left} <> ${bindIfParam(right, left)}`; + }; + gt = (left, right) => { + return sql`${left} > ${bindIfParam(right, left)}`; + }; + gte = (left, right) => { + return sql`${left} >= ${bindIfParam(right, left)}`; + }; + lt = (left, right) => { + return sql`${left} < ${bindIfParam(right, left)}`; + }; + lte = (left, right) => { + return sql`${left} <= ${bindIfParam(right, left)}`; + }; + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/sql/expressions/select.js +function asc(column) { + return sql`${column} asc`; +} +function desc(column) { + return sql`${column} desc`; +} +var init_select = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/sql/expressions/select.js"() { + init_sql(); + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/sql/expressions/index.js +var init_expressions = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/sql/expressions/index.js"() { + init_conditions(); + init_select(); + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/relations.js +function getOperators() { + return { + and, + between, + eq, + exists, + gt, + gte, + ilike, + inArray, + isNull, + isNotNull, + like, + lt, + lte, + ne, + not, + notBetween, + notExists, + notLike, + notIlike, + notInArray, + or, + sql + }; +} +function getOrderByOperators() { + return { + sql, + asc, + desc + }; +} +function extractTablesRelationalConfig(schema2, configHelpers) { + if (Object.keys(schema2).length === 1 && "default" in schema2 && !is(schema2["default"], Table)) { + schema2 = schema2["default"]; + } + const tableNamesMap = {}; + const relationsBuffer = {}; + const tablesConfig = {}; + for (const [key, value] of Object.entries(schema2)) { + if (is(value, Table)) { + const dbName = getTableUniqueName(value); + const bufferedRelations = relationsBuffer[dbName]; + tableNamesMap[dbName] = key; + tablesConfig[key] = { + tsName: key, + dbName: value[Table.Symbol.Name], + schema: value[Table.Symbol.Schema], + columns: value[Table.Symbol.Columns], + relations: bufferedRelations?.relations ?? {}, + primaryKey: bufferedRelations?.primaryKey ?? [] + }; + for (const column of Object.values( + value[Table.Symbol.Columns] + )) { + if (column.primary) { + tablesConfig[key].primaryKey.push(column); + } + } + const extraConfig = value[Table.Symbol.ExtraConfigBuilder]?.(value[Table.Symbol.ExtraConfigColumns]); + if (extraConfig) { + for (const configEntry of Object.values(extraConfig)) { + if (is(configEntry, PrimaryKeyBuilder)) { + tablesConfig[key].primaryKey.push(...configEntry.columns); + } + } + } + } else if (is(value, Relations)) { + const dbName = getTableUniqueName(value.table); + const tableName = tableNamesMap[dbName]; + const relations2 = value.config( + configHelpers(value.table) + ); + let primaryKey2; + for (const [relationName, relation] of Object.entries(relations2)) { + if (tableName) { + const tableConfig = tablesConfig[tableName]; + tableConfig.relations[relationName] = relation; + if (primaryKey2) { + tableConfig.primaryKey.push(...primaryKey2); + } + } else { + if (!(dbName in relationsBuffer)) { + relationsBuffer[dbName] = { + relations: {}, + primaryKey: primaryKey2 + }; + } + relationsBuffer[dbName].relations[relationName] = relation; + } + } + } + } + return { tables: tablesConfig, tableNamesMap }; +} +function createOne(sourceTable) { + return function one(table, config3) { + return new One( + sourceTable, + table, + config3, + config3?.fields.reduce((res, f5) => res && f5.notNull, true) ?? false + ); + }; +} +function createMany(sourceTable) { + return function many(referencedTable, config3) { + return new Many(sourceTable, referencedTable, config3); + }; +} +function normalizeRelation(schema2, tableNamesMap, relation) { + if (is(relation, One) && relation.config) { + return { + fields: relation.config.fields, + references: relation.config.references + }; + } + const referencedTableTsName = tableNamesMap[getTableUniqueName(relation.referencedTable)]; + if (!referencedTableTsName) { + throw new Error( + `Table "${relation.referencedTable[Table.Symbol.Name]}" not found in schema` + ); + } + const referencedTableConfig = schema2[referencedTableTsName]; + if (!referencedTableConfig) { + throw new Error(`Table "${referencedTableTsName}" not found in schema`); + } + const sourceTable = relation.sourceTable; + const sourceTableTsName = tableNamesMap[getTableUniqueName(sourceTable)]; + if (!sourceTableTsName) { + throw new Error( + `Table "${sourceTable[Table.Symbol.Name]}" not found in schema` + ); + } + const reverseRelations = []; + for (const referencedTableRelation of Object.values( + referencedTableConfig.relations + )) { + if (relation.relationName && relation !== referencedTableRelation && referencedTableRelation.relationName === relation.relationName || !relation.relationName && referencedTableRelation.referencedTable === relation.sourceTable) { + reverseRelations.push(referencedTableRelation); + } + } + if (reverseRelations.length > 1) { + throw relation.relationName ? new Error( + `There are multiple relations with name "${relation.relationName}" in table "${referencedTableTsName}"` + ) : new Error( + `There are multiple relations between "${referencedTableTsName}" and "${relation.sourceTable[Table.Symbol.Name]}". Please specify relation name` + ); + } + if (reverseRelations[0] && is(reverseRelations[0], One) && reverseRelations[0].config) { + return { + fields: reverseRelations[0].config.references, + references: reverseRelations[0].config.fields + }; + } + throw new Error( + `There is not enough information to infer relation "${sourceTableTsName}.${relation.fieldName}"` + ); +} +function createTableRelationsHelpers(sourceTable) { + return { + one: createOne(sourceTable), + many: createMany(sourceTable) + }; +} +function mapRelationalRow(tablesConfig, tableConfig, row, buildQueryResultSelection, mapColumnValue = (value) => value) { + const result = {}; + for (const [ + selectionItemIndex, + selectionItem + ] of buildQueryResultSelection.entries()) { + if (selectionItem.isJson) { + const relation = tableConfig.relations[selectionItem.tsKey]; + const rawSubRows = row[selectionItemIndex]; + const subRows = typeof rawSubRows === "string" ? JSON.parse(rawSubRows) : rawSubRows; + result[selectionItem.tsKey] = is(relation, One) ? subRows && mapRelationalRow( + tablesConfig, + tablesConfig[selectionItem.relationTableTsKey], + subRows, + selectionItem.selection, + mapColumnValue + ) : subRows.map( + (subRow) => mapRelationalRow( + tablesConfig, + tablesConfig[selectionItem.relationTableTsKey], + subRow, + selectionItem.selection, + mapColumnValue + ) + ); + } else { + const value = mapColumnValue(row[selectionItemIndex]); + const field = selectionItem.field; + let decoder2; + if (is(field, Column)) { + decoder2 = field; + } else if (is(field, SQL)) { + decoder2 = field.decoder; + } else { + decoder2 = field.sql.decoder; + } + result[selectionItem.tsKey] = value === null ? null : decoder2.mapFromDriverValue(value); + } + } + return result; +} +var Relation, Relations, One, Many; +var init_relations = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/relations.js"() { + init_table(); + init_column(); + init_entity(); + init_primary_keys(); + init_expressions(); + init_sql(); + Relation = class { + constructor(sourceTable, referencedTable, relationName) { + this.sourceTable = sourceTable; + this.referencedTable = referencedTable; + this.relationName = relationName; + this.referencedTableName = referencedTable[Table.Symbol.Name]; + } + static [entityKind] = "Relation"; + referencedTableName; + fieldName; + }; + Relations = class { + constructor(table, config3) { + this.table = table; + this.config = config3; + } + static [entityKind] = "Relations"; + }; + One = class _One extends Relation { + constructor(sourceTable, referencedTable, config3, isNullable) { + super(sourceTable, referencedTable, config3?.relationName); + this.config = config3; + this.isNullable = isNullable; + } + static [entityKind] = "One"; + withFieldName(fieldName) { + const relation = new _One( + this.sourceTable, + this.referencedTable, + this.config, + this.isNullable + ); + relation.fieldName = fieldName; + return relation; + } + }; + Many = class _Many extends Relation { + constructor(sourceTable, referencedTable, config3) { + super(sourceTable, referencedTable, config3?.relationName); + this.config = config3; + } + static [entityKind] = "Many"; + withFieldName(fieldName) { + const relation = new _Many( + this.sourceTable, + this.referencedTable, + this.config + ); + relation.fieldName = fieldName; + return relation; + } + }; + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/sql/functions/aggregate.js +function count(expression) { + return sql`count(${expression || sql.raw("*")})`.mapWith(Number); +} +var init_aggregate = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/sql/functions/aggregate.js"() { + init_sql(); + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/sql/functions/vector.js +var init_vector2 = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/sql/functions/vector.js"() { + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/sql/functions/index.js +var init_functions = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/sql/functions/index.js"() { + init_aggregate(); + init_vector2(); + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/sql/index.js +var init_sql2 = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/sql/index.js"() { + init_expressions(); + init_functions(); + init_sql(); + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/view-base.js +var PgViewBase; +var init_view_base = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/view-base.js"() { + init_entity(); + init_sql(); + PgViewBase = class extends View { + static [entityKind] = "PgViewBase"; + }; + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/dialect.js +var PgDialect; +var init_dialect = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/dialect.js"() { + init_alias(); + init_casing(); + init_column(); + init_entity(); + init_errors2(); + init_columns(); + init_table2(); + init_relations(); + init_sql2(); + init_sql(); + init_subquery(); + init_table(); + init_utils(); + init_view_common(); + init_view_base(); + PgDialect = class { + static [entityKind] = "PgDialect"; + /** @internal */ + casing; + constructor(config3) { + this.casing = new CasingCache(config3?.casing); + } + async migrate(migrations, session, config3) { + const migrationsTable = typeof config3 === "string" ? "__drizzle_migrations" : config3.migrationsTable ?? "__drizzle_migrations"; + const migrationsSchema = typeof config3 === "string" ? "drizzle" : config3.migrationsSchema ?? "drizzle"; + const migrationTableCreate = sql` + CREATE TABLE IF NOT EXISTS ${sql.identifier(migrationsSchema)}.${sql.identifier(migrationsTable)} ( + id SERIAL PRIMARY KEY, + hash text NOT NULL, + created_at bigint + ) + `; + await session.execute(sql`CREATE SCHEMA IF NOT EXISTS ${sql.identifier(migrationsSchema)}`); + await session.execute(migrationTableCreate); + const dbMigrations = await session.all( + sql`select id, hash, created_at from ${sql.identifier(migrationsSchema)}.${sql.identifier(migrationsTable)} order by created_at desc limit 1` + ); + const lastDbMigration = dbMigrations[0]; + await session.transaction(async (tx) => { + for await (const migration of migrations) { + if (!lastDbMigration || Number(lastDbMigration.created_at) < migration.folderMillis) { + for (const stmt of migration.sql) { + await tx.execute(sql.raw(stmt)); + } + await tx.execute( + sql`insert into ${sql.identifier(migrationsSchema)}.${sql.identifier(migrationsTable)} ("hash", "created_at") values(${migration.hash}, ${migration.folderMillis})` + ); + } + } + }); + } + escapeName(name) { + return `"${name}"`; + } + escapeParam(num) { + return `$${num + 1}`; + } + escapeString(str) { + return `'${str.replace(/'/g, "''")}'`; + } + buildWithCTE(queries) { + if (!queries?.length) + return void 0; + const withSqlChunks = [sql`with `]; + for (const [i5, w5] of queries.entries()) { + withSqlChunks.push(sql`${sql.identifier(w5._.alias)} as (${w5._.sql})`); + if (i5 < queries.length - 1) { + withSqlChunks.push(sql`, `); + } + } + withSqlChunks.push(sql` `); + return sql.join(withSqlChunks); + } + buildDeleteQuery({ table, where, returning, withList }) { + const withSql = this.buildWithCTE(withList); + const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : void 0; + const whereSql = where ? sql` where ${where}` : void 0; + return sql`${withSql}delete from ${table}${whereSql}${returningSql}`; + } + buildUpdateSet(table, set2) { + const tableColumns = table[Table.Symbol.Columns]; + const columnNames = Object.keys(tableColumns).filter( + (colName) => set2[colName] !== void 0 || tableColumns[colName]?.onUpdateFn !== void 0 + ); + const setSize = columnNames.length; + return sql.join(columnNames.flatMap((colName, i5) => { + const col = tableColumns[colName]; + const value = set2[colName] ?? sql.param(col.onUpdateFn(), col); + const res = sql`${sql.identifier(this.casing.getColumnCasing(col))} = ${value}`; + if (i5 < setSize - 1) { + return [res, sql.raw(", ")]; + } + return [res]; + })); + } + buildUpdateQuery({ table, set: set2, where, returning, withList, from, joins }) { + const withSql = this.buildWithCTE(withList); + const tableName = table[PgTable.Symbol.Name]; + const tableSchema = table[PgTable.Symbol.Schema]; + const origTableName = table[PgTable.Symbol.OriginalName]; + const alias = tableName === origTableName ? void 0 : tableName; + const tableSql = sql`${tableSchema ? sql`${sql.identifier(tableSchema)}.` : void 0}${sql.identifier(origTableName)}${alias && sql` ${sql.identifier(alias)}`}`; + const setSql = this.buildUpdateSet(table, set2); + const fromSql = from && sql.join([sql.raw(" from "), this.buildFromTable(from)]); + const joinsSql = this.buildJoins(joins); + const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: !from })}` : void 0; + const whereSql = where ? sql` where ${where}` : void 0; + return sql`${withSql}update ${tableSql} set ${setSql}${fromSql}${joinsSql}${whereSql}${returningSql}`; + } + /** + * Builds selection SQL with provided fields/expressions + * + * Examples: + * + * `select from` + * + * `insert ... returning ` + * + * If `isSingleTable` is true, then columns won't be prefixed with table name + */ + buildSelection(fields, { isSingleTable = false } = {}) { + const columnsLen = fields.length; + const chunks = fields.flatMap(({ field }, i5) => { + const chunk = []; + if (is(field, SQL.Aliased) && field.isSelectionField) { + chunk.push(sql.identifier(field.fieldAlias)); + } else if (is(field, SQL.Aliased) || is(field, SQL)) { + const query = is(field, SQL.Aliased) ? field.sql : field; + if (isSingleTable) { + chunk.push( + new SQL( + query.queryChunks.map((c5) => { + if (is(c5, PgColumn)) { + return sql.identifier(this.casing.getColumnCasing(c5)); + } + return c5; + }) + ) + ); + } else { + chunk.push(query); + } + if (is(field, SQL.Aliased)) { + chunk.push(sql` as ${sql.identifier(field.fieldAlias)}`); + } + } else if (is(field, Column)) { + if (isSingleTable) { + chunk.push(sql.identifier(this.casing.getColumnCasing(field))); + } else { + chunk.push(field); + } + } + if (i5 < columnsLen - 1) { + chunk.push(sql`, `); + } + return chunk; + }); + return sql.join(chunks); + } + buildJoins(joins) { + if (!joins || joins.length === 0) { + return void 0; + } + const joinsArray = []; + for (const [index2, joinMeta] of joins.entries()) { + if (index2 === 0) { + joinsArray.push(sql` `); + } + const table = joinMeta.table; + const lateralSql = joinMeta.lateral ? sql` lateral` : void 0; + if (is(table, PgTable)) { + const tableName = table[PgTable.Symbol.Name]; + const tableSchema = table[PgTable.Symbol.Schema]; + const origTableName = table[PgTable.Symbol.OriginalName]; + const alias = tableName === origTableName ? void 0 : joinMeta.alias; + joinsArray.push( + sql`${sql.raw(joinMeta.joinType)} join${lateralSql} ${tableSchema ? sql`${sql.identifier(tableSchema)}.` : void 0}${sql.identifier(origTableName)}${alias && sql` ${sql.identifier(alias)}`} on ${joinMeta.on}` + ); + } else if (is(table, View)) { + const viewName = table[ViewBaseConfig].name; + const viewSchema = table[ViewBaseConfig].schema; + const origViewName = table[ViewBaseConfig].originalName; + const alias = viewName === origViewName ? void 0 : joinMeta.alias; + joinsArray.push( + sql`${sql.raw(joinMeta.joinType)} join${lateralSql} ${viewSchema ? sql`${sql.identifier(viewSchema)}.` : void 0}${sql.identifier(origViewName)}${alias && sql` ${sql.identifier(alias)}`} on ${joinMeta.on}` + ); + } else { + joinsArray.push( + sql`${sql.raw(joinMeta.joinType)} join${lateralSql} ${table} on ${joinMeta.on}` + ); + } + if (index2 < joins.length - 1) { + joinsArray.push(sql` `); + } + } + return sql.join(joinsArray); + } + buildFromTable(table) { + if (is(table, Table) && table[Table.Symbol.OriginalName] !== table[Table.Symbol.Name]) { + let fullName = sql`${sql.identifier(table[Table.Symbol.OriginalName])}`; + if (table[Table.Symbol.Schema]) { + fullName = sql`${sql.identifier(table[Table.Symbol.Schema])}.${fullName}`; + } + return sql`${fullName} ${sql.identifier(table[Table.Symbol.Name])}`; + } + return table; + } + buildSelectQuery({ + withList, + fields, + fieldsFlat, + where, + having, + table, + joins, + orderBy, + groupBy, + limit, + offset, + lockingClause, + distinct, + setOperators + }) { + const fieldsList = fieldsFlat ?? orderSelectedFields(fields); + for (const f5 of fieldsList) { + if (is(f5.field, Column) && getTableName(f5.field.table) !== (is(table, Subquery) ? table._.alias : is(table, PgViewBase) ? table[ViewBaseConfig].name : is(table, SQL) ? void 0 : getTableName(table)) && !((table2) => joins?.some( + ({ alias }) => alias === (table2[Table.Symbol.IsAlias] ? getTableName(table2) : table2[Table.Symbol.BaseName]) + ))(f5.field.table)) { + const tableName = getTableName(f5.field.table); + throw new Error( + `Your "${f5.path.join("->")}" field references a column "${tableName}"."${f5.field.name}", but the table "${tableName}" is not part of the query! Did you forget to join it?` + ); + } + } + const isSingleTable = !joins || joins.length === 0; + const withSql = this.buildWithCTE(withList); + let distinctSql; + if (distinct) { + distinctSql = distinct === true ? sql` distinct` : sql` distinct on (${sql.join(distinct.on, sql`, `)})`; + } + const selection = this.buildSelection(fieldsList, { isSingleTable }); + const tableSql = this.buildFromTable(table); + const joinsSql = this.buildJoins(joins); + const whereSql = where ? sql` where ${where}` : void 0; + const havingSql = having ? sql` having ${having}` : void 0; + let orderBySql; + if (orderBy && orderBy.length > 0) { + orderBySql = sql` order by ${sql.join(orderBy, sql`, `)}`; + } + let groupBySql; + if (groupBy && groupBy.length > 0) { + groupBySql = sql` group by ${sql.join(groupBy, sql`, `)}`; + } + const limitSql = typeof limit === "object" || typeof limit === "number" && limit >= 0 ? sql` limit ${limit}` : void 0; + const offsetSql = offset ? sql` offset ${offset}` : void 0; + const lockingClauseSql = sql.empty(); + if (lockingClause) { + const clauseSql = sql` for ${sql.raw(lockingClause.strength)}`; + if (lockingClause.config.of) { + clauseSql.append( + sql` of ${sql.join( + Array.isArray(lockingClause.config.of) ? lockingClause.config.of : [lockingClause.config.of], + sql`, ` + )}` + ); + } + if (lockingClause.config.noWait) { + clauseSql.append(sql` no wait`); + } else if (lockingClause.config.skipLocked) { + clauseSql.append(sql` skip locked`); + } + lockingClauseSql.append(clauseSql); + } + const finalQuery = sql`${withSql}select${distinctSql} ${selection} from ${tableSql}${joinsSql}${whereSql}${groupBySql}${havingSql}${orderBySql}${limitSql}${offsetSql}${lockingClauseSql}`; + if (setOperators.length > 0) { + return this.buildSetOperations(finalQuery, setOperators); + } + return finalQuery; + } + buildSetOperations(leftSelect, setOperators) { + const [setOperator, ...rest] = setOperators; + if (!setOperator) { + throw new Error("Cannot pass undefined values to any set operator"); + } + if (rest.length === 0) { + return this.buildSetOperationQuery({ leftSelect, setOperator }); + } + return this.buildSetOperations( + this.buildSetOperationQuery({ leftSelect, setOperator }), + rest + ); + } + buildSetOperationQuery({ + leftSelect, + setOperator: { type, isAll, rightSelect, limit, orderBy, offset } + }) { + const leftChunk = sql`(${leftSelect.getSQL()}) `; + const rightChunk = sql`(${rightSelect.getSQL()})`; + let orderBySql; + if (orderBy && orderBy.length > 0) { + const orderByValues = []; + for (const singleOrderBy of orderBy) { + if (is(singleOrderBy, PgColumn)) { + orderByValues.push(sql.identifier(singleOrderBy.name)); + } else if (is(singleOrderBy, SQL)) { + for (let i5 = 0; i5 < singleOrderBy.queryChunks.length; i5++) { + const chunk = singleOrderBy.queryChunks[i5]; + if (is(chunk, PgColumn)) { + singleOrderBy.queryChunks[i5] = sql.identifier(chunk.name); + } + } + orderByValues.push(sql`${singleOrderBy}`); + } else { + orderByValues.push(sql`${singleOrderBy}`); + } + } + orderBySql = sql` order by ${sql.join(orderByValues, sql`, `)} `; + } + const limitSql = typeof limit === "object" || typeof limit === "number" && limit >= 0 ? sql` limit ${limit}` : void 0; + const operatorChunk = sql.raw(`${type} ${isAll ? "all " : ""}`); + const offsetSql = offset ? sql` offset ${offset}` : void 0; + return sql`${leftChunk}${operatorChunk}${rightChunk}${orderBySql}${limitSql}${offsetSql}`; + } + buildInsertQuery({ table, values: valuesOrSelect, onConflict, returning, withList, select: select2, overridingSystemValue_ }) { + const valuesSqlList = []; + const columns = table[Table.Symbol.Columns]; + const colEntries = Object.entries(columns).filter(([_, col]) => !col.shouldDisableInsert()); + const insertOrder = colEntries.map( + ([, column]) => sql.identifier(this.casing.getColumnCasing(column)) + ); + if (select2) { + const select22 = valuesOrSelect; + if (is(select22, SQL)) { + valuesSqlList.push(select22); + } else { + valuesSqlList.push(select22.getSQL()); + } + } else { + const values2 = valuesOrSelect; + valuesSqlList.push(sql.raw("values ")); + for (const [valueIndex, value] of values2.entries()) { + const valueList = []; + for (const [fieldName, col] of colEntries) { + const colValue = value[fieldName]; + if (colValue === void 0 || is(colValue, Param) && colValue.value === void 0) { + if (col.defaultFn !== void 0) { + const defaultFnResult = col.defaultFn(); + const defaultValue = is(defaultFnResult, SQL) ? defaultFnResult : sql.param(defaultFnResult, col); + valueList.push(defaultValue); + } else if (!col.default && col.onUpdateFn !== void 0) { + const onUpdateFnResult = col.onUpdateFn(); + const newValue = is(onUpdateFnResult, SQL) ? onUpdateFnResult : sql.param(onUpdateFnResult, col); + valueList.push(newValue); + } else { + valueList.push(sql`default`); + } + } else { + valueList.push(colValue); + } + } + valuesSqlList.push(valueList); + if (valueIndex < values2.length - 1) { + valuesSqlList.push(sql`, `); + } + } + } + const withSql = this.buildWithCTE(withList); + const valuesSql = sql.join(valuesSqlList); + const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : void 0; + const onConflictSql = onConflict ? sql` on conflict ${onConflict}` : void 0; + const overridingSql = overridingSystemValue_ === true ? sql`overriding system value ` : void 0; + return sql`${withSql}insert into ${table} ${insertOrder} ${overridingSql}${valuesSql}${onConflictSql}${returningSql}`; + } + buildRefreshMaterializedViewQuery({ view, concurrently, withNoData }) { + const concurrentlySql = concurrently ? sql` concurrently` : void 0; + const withNoDataSql = withNoData ? sql` with no data` : void 0; + return sql`refresh materialized view${concurrentlySql} ${view}${withNoDataSql}`; + } + prepareTyping(encoder3) { + if (is(encoder3, PgJsonb) || is(encoder3, PgJson)) { + return "json"; + } else if (is(encoder3, PgNumeric)) { + return "decimal"; + } else if (is(encoder3, PgTime)) { + return "time"; + } else if (is(encoder3, PgTimestamp) || is(encoder3, PgTimestampString)) { + return "timestamp"; + } else if (is(encoder3, PgDate) || is(encoder3, PgDateString)) { + return "date"; + } else if (is(encoder3, PgUUID)) { + return "uuid"; + } else { + return "none"; + } + } + sqlToQuery(sql22, invokeSource) { + return sql22.toQuery({ + casing: this.casing, + escapeName: this.escapeName, + escapeParam: this.escapeParam, + escapeString: this.escapeString, + prepareTyping: this.prepareTyping, + invokeSource + }); + } + // buildRelationalQueryWithPK({ + // fullSchema, + // schema, + // tableNamesMap, + // table, + // tableConfig, + // queryConfig: config, + // tableAlias, + // isRoot = false, + // joinOn, + // }: { + // fullSchema: Record; + // schema: TablesRelationalConfig; + // tableNamesMap: Record; + // table: PgTable; + // tableConfig: TableRelationalConfig; + // queryConfig: true | DBQueryConfig<'many', true>; + // tableAlias: string; + // isRoot?: boolean; + // joinOn?: SQL; + // }): BuildRelationalQueryResult { + // // For { "": true }, return a table with selection of all columns + // if (config === true) { + // const selectionEntries = Object.entries(tableConfig.columns); + // const selection: BuildRelationalQueryResult['selection'] = selectionEntries.map(( + // [key, value], + // ) => ({ + // dbKey: value.name, + // tsKey: key, + // field: value as PgColumn, + // relationTableTsKey: undefined, + // isJson: false, + // selection: [], + // })); + // return { + // tableTsKey: tableConfig.tsName, + // sql: table, + // selection, + // }; + // } + // // let selection: BuildRelationalQueryResult['selection'] = []; + // // let selectionForBuild = selection; + // const aliasedColumns = Object.fromEntries( + // Object.entries(tableConfig.columns).map(([key, value]) => [key, aliasedTableColumn(value, tableAlias)]), + // ); + // const aliasedRelations = Object.fromEntries( + // Object.entries(tableConfig.relations).map(([key, value]) => [key, aliasedRelation(value, tableAlias)]), + // ); + // const aliasedFields = Object.assign({}, aliasedColumns, aliasedRelations); + // let where, hasUserDefinedWhere; + // if (config.where) { + // const whereSql = typeof config.where === 'function' ? config.where(aliasedFields, operators) : config.where; + // where = whereSql && mapColumnsInSQLToAlias(whereSql, tableAlias); + // hasUserDefinedWhere = !!where; + // } + // where = and(joinOn, where); + // // const fieldsSelection: { tsKey: string; value: PgColumn | SQL.Aliased; isExtra?: boolean }[] = []; + // let joins: Join[] = []; + // let selectedColumns: string[] = []; + // // Figure out which columns to select + // if (config.columns) { + // let isIncludeMode = false; + // for (const [field, value] of Object.entries(config.columns)) { + // if (value === undefined) { + // continue; + // } + // if (field in tableConfig.columns) { + // if (!isIncludeMode && value === true) { + // isIncludeMode = true; + // } + // selectedColumns.push(field); + // } + // } + // if (selectedColumns.length > 0) { + // selectedColumns = isIncludeMode + // ? selectedColumns.filter((c) => config.columns?.[c] === true) + // : Object.keys(tableConfig.columns).filter((key) => !selectedColumns.includes(key)); + // } + // } else { + // // Select all columns if selection is not specified + // selectedColumns = Object.keys(tableConfig.columns); + // } + // // for (const field of selectedColumns) { + // // const column = tableConfig.columns[field]! as PgColumn; + // // fieldsSelection.push({ tsKey: field, value: column }); + // // } + // let initiallySelectedRelations: { + // tsKey: string; + // queryConfig: true | DBQueryConfig<'many', false>; + // relation: Relation; + // }[] = []; + // // let selectedRelations: BuildRelationalQueryResult['selection'] = []; + // // Figure out which relations to select + // if (config.with) { + // initiallySelectedRelations = Object.entries(config.with) + // .filter((entry): entry is [typeof entry[0], NonNullable] => !!entry[1]) + // .map(([tsKey, queryConfig]) => ({ tsKey, queryConfig, relation: tableConfig.relations[tsKey]! })); + // } + // const manyRelations = initiallySelectedRelations.filter((r) => + // is(r.relation, Many) + // && (schema[tableNamesMap[r.relation.referencedTable[Table.Symbol.Name]]!]?.primaryKey.length ?? 0) > 0 + // ); + // // If this is the last Many relation (or there are no Many relations), we are on the innermost subquery level + // const isInnermostQuery = manyRelations.length < 2; + // const selectedExtras: { + // tsKey: string; + // value: SQL.Aliased; + // }[] = []; + // // Figure out which extras to select + // if (isInnermostQuery && config.extras) { + // const extras = typeof config.extras === 'function' + // ? config.extras(aliasedFields, { sql }) + // : config.extras; + // for (const [tsKey, value] of Object.entries(extras)) { + // selectedExtras.push({ + // tsKey, + // value: mapColumnsInAliasedSQLToAlias(value, tableAlias), + // }); + // } + // } + // // Transform `fieldsSelection` into `selection` + // // `fieldsSelection` shouldn't be used after this point + // // for (const { tsKey, value, isExtra } of fieldsSelection) { + // // selection.push({ + // // dbKey: is(value, SQL.Aliased) ? value.fieldAlias : tableConfig.columns[tsKey]!.name, + // // tsKey, + // // field: is(value, Column) ? aliasedTableColumn(value, tableAlias) : value, + // // relationTableTsKey: undefined, + // // isJson: false, + // // isExtra, + // // selection: [], + // // }); + // // } + // let orderByOrig = typeof config.orderBy === 'function' + // ? config.orderBy(aliasedFields, orderByOperators) + // : config.orderBy ?? []; + // if (!Array.isArray(orderByOrig)) { + // orderByOrig = [orderByOrig]; + // } + // const orderBy = orderByOrig.map((orderByValue) => { + // if (is(orderByValue, Column)) { + // return aliasedTableColumn(orderByValue, tableAlias) as PgColumn; + // } + // return mapColumnsInSQLToAlias(orderByValue, tableAlias); + // }); + // const limit = isInnermostQuery ? config.limit : undefined; + // const offset = isInnermostQuery ? config.offset : undefined; + // // For non-root queries without additional config except columns, return a table with selection + // if ( + // !isRoot + // && initiallySelectedRelations.length === 0 + // && selectedExtras.length === 0 + // && !where + // && orderBy.length === 0 + // && limit === undefined + // && offset === undefined + // ) { + // return { + // tableTsKey: tableConfig.tsName, + // sql: table, + // selection: selectedColumns.map((key) => ({ + // dbKey: tableConfig.columns[key]!.name, + // tsKey: key, + // field: tableConfig.columns[key] as PgColumn, + // relationTableTsKey: undefined, + // isJson: false, + // selection: [], + // })), + // }; + // } + // const selectedRelationsWithoutPK: + // // Process all relations without primary keys, because they need to be joined differently and will all be on the same query level + // for ( + // const { + // tsKey: selectedRelationTsKey, + // queryConfig: selectedRelationConfigValue, + // relation, + // } of initiallySelectedRelations + // ) { + // const normalizedRelation = normalizeRelation(schema, tableNamesMap, relation); + // const relationTableName = relation.referencedTable[Table.Symbol.Name]; + // const relationTableTsName = tableNamesMap[relationTableName]!; + // const relationTable = schema[relationTableTsName]!; + // if (relationTable.primaryKey.length > 0) { + // continue; + // } + // const relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`; + // const joinOn = and( + // ...normalizedRelation.fields.map((field, i) => + // eq( + // aliasedTableColumn(normalizedRelation.references[i]!, relationTableAlias), + // aliasedTableColumn(field, tableAlias), + // ) + // ), + // ); + // const builtRelation = this.buildRelationalQueryWithoutPK({ + // fullSchema, + // schema, + // tableNamesMap, + // table: fullSchema[relationTableTsName] as PgTable, + // tableConfig: schema[relationTableTsName]!, + // queryConfig: selectedRelationConfigValue, + // tableAlias: relationTableAlias, + // joinOn, + // nestedQueryRelation: relation, + // }); + // const field = sql`${sql.identifier(relationTableAlias)}.${sql.identifier('data')}`.as(selectedRelationTsKey); + // joins.push({ + // on: sql`true`, + // table: new Subquery(builtRelation.sql as SQL, {}, relationTableAlias), + // alias: relationTableAlias, + // joinType: 'left', + // lateral: true, + // }); + // selectedRelations.push({ + // dbKey: selectedRelationTsKey, + // tsKey: selectedRelationTsKey, + // field, + // relationTableTsKey: relationTableTsName, + // isJson: true, + // selection: builtRelation.selection, + // }); + // } + // const oneRelations = initiallySelectedRelations.filter((r): r is typeof r & { relation: One } => + // is(r.relation, One) + // ); + // // Process all One relations with PKs, because they can all be joined on the same level + // for ( + // const { + // tsKey: selectedRelationTsKey, + // queryConfig: selectedRelationConfigValue, + // relation, + // } of oneRelations + // ) { + // const normalizedRelation = normalizeRelation(schema, tableNamesMap, relation); + // const relationTableName = relation.referencedTable[Table.Symbol.Name]; + // const relationTableTsName = tableNamesMap[relationTableName]!; + // const relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`; + // const relationTable = schema[relationTableTsName]!; + // if (relationTable.primaryKey.length === 0) { + // continue; + // } + // const joinOn = and( + // ...normalizedRelation.fields.map((field, i) => + // eq( + // aliasedTableColumn(normalizedRelation.references[i]!, relationTableAlias), + // aliasedTableColumn(field, tableAlias), + // ) + // ), + // ); + // const builtRelation = this.buildRelationalQueryWithPK({ + // fullSchema, + // schema, + // tableNamesMap, + // table: fullSchema[relationTableTsName] as PgTable, + // tableConfig: schema[relationTableTsName]!, + // queryConfig: selectedRelationConfigValue, + // tableAlias: relationTableAlias, + // joinOn, + // }); + // const field = sql`case when ${sql.identifier(relationTableAlias)} is null then null else json_build_array(${ + // sql.join( + // builtRelation.selection.map(({ field }) => + // is(field, SQL.Aliased) + // ? sql`${sql.identifier(relationTableAlias)}.${sql.identifier(field.fieldAlias)}` + // : is(field, Column) + // ? aliasedTableColumn(field, relationTableAlias) + // : field + // ), + // sql`, `, + // ) + // }) end`.as(selectedRelationTsKey); + // const isLateralJoin = is(builtRelation.sql, SQL); + // joins.push({ + // on: isLateralJoin ? sql`true` : joinOn, + // table: is(builtRelation.sql, SQL) + // ? new Subquery(builtRelation.sql, {}, relationTableAlias) + // : aliasedTable(builtRelation.sql, relationTableAlias), + // alias: relationTableAlias, + // joinType: 'left', + // lateral: is(builtRelation.sql, SQL), + // }); + // selectedRelations.push({ + // dbKey: selectedRelationTsKey, + // tsKey: selectedRelationTsKey, + // field, + // relationTableTsKey: relationTableTsName, + // isJson: true, + // selection: builtRelation.selection, + // }); + // } + // let distinct: PgSelectConfig['distinct']; + // let tableFrom: PgTable | Subquery = table; + // // Process first Many relation - each one requires a nested subquery + // const manyRelation = manyRelations[0]; + // if (manyRelation) { + // const { + // tsKey: selectedRelationTsKey, + // queryConfig: selectedRelationQueryConfig, + // relation, + // } = manyRelation; + // distinct = { + // on: tableConfig.primaryKey.map((c) => aliasedTableColumn(c as PgColumn, tableAlias)), + // }; + // const normalizedRelation = normalizeRelation(schema, tableNamesMap, relation); + // const relationTableName = relation.referencedTable[Table.Symbol.Name]; + // const relationTableTsName = tableNamesMap[relationTableName]!; + // const relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`; + // const joinOn = and( + // ...normalizedRelation.fields.map((field, i) => + // eq( + // aliasedTableColumn(normalizedRelation.references[i]!, relationTableAlias), + // aliasedTableColumn(field, tableAlias), + // ) + // ), + // ); + // const builtRelationJoin = this.buildRelationalQueryWithPK({ + // fullSchema, + // schema, + // tableNamesMap, + // table: fullSchema[relationTableTsName] as PgTable, + // tableConfig: schema[relationTableTsName]!, + // queryConfig: selectedRelationQueryConfig, + // tableAlias: relationTableAlias, + // joinOn, + // }); + // const builtRelationSelectionField = sql`case when ${ + // sql.identifier(relationTableAlias) + // } is null then '[]' else json_agg(json_build_array(${ + // sql.join( + // builtRelationJoin.selection.map(({ field }) => + // is(field, SQL.Aliased) + // ? sql`${sql.identifier(relationTableAlias)}.${sql.identifier(field.fieldAlias)}` + // : is(field, Column) + // ? aliasedTableColumn(field, relationTableAlias) + // : field + // ), + // sql`, `, + // ) + // })) over (partition by ${sql.join(distinct.on, sql`, `)}) end`.as(selectedRelationTsKey); + // const isLateralJoin = is(builtRelationJoin.sql, SQL); + // joins.push({ + // on: isLateralJoin ? sql`true` : joinOn, + // table: isLateralJoin + // ? new Subquery(builtRelationJoin.sql as SQL, {}, relationTableAlias) + // : aliasedTable(builtRelationJoin.sql as PgTable, relationTableAlias), + // alias: relationTableAlias, + // joinType: 'left', + // lateral: isLateralJoin, + // }); + // // Build the "from" subquery with the remaining Many relations + // const builtTableFrom = this.buildRelationalQueryWithPK({ + // fullSchema, + // schema, + // tableNamesMap, + // table, + // tableConfig, + // queryConfig: { + // ...config, + // where: undefined, + // orderBy: undefined, + // limit: undefined, + // offset: undefined, + // with: manyRelations.slice(1).reduce>( + // (result, { tsKey, queryConfig: configValue }) => { + // result[tsKey] = configValue; + // return result; + // }, + // {}, + // ), + // }, + // tableAlias, + // }); + // selectedRelations.push({ + // dbKey: selectedRelationTsKey, + // tsKey: selectedRelationTsKey, + // field: builtRelationSelectionField, + // relationTableTsKey: relationTableTsName, + // isJson: true, + // selection: builtRelationJoin.selection, + // }); + // // selection = builtTableFrom.selection.map((item) => + // // is(item.field, SQL.Aliased) + // // ? { ...item, field: sql`${sql.identifier(tableAlias)}.${sql.identifier(item.field.fieldAlias)}` } + // // : item + // // ); + // // selectionForBuild = [{ + // // dbKey: '*', + // // tsKey: '*', + // // field: sql`${sql.identifier(tableAlias)}.*`, + // // selection: [], + // // isJson: false, + // // relationTableTsKey: undefined, + // // }]; + // // const newSelectionItem: (typeof selection)[number] = { + // // dbKey: selectedRelationTsKey, + // // tsKey: selectedRelationTsKey, + // // field, + // // relationTableTsKey: relationTableTsName, + // // isJson: true, + // // selection: builtRelationJoin.selection, + // // }; + // // selection.push(newSelectionItem); + // // selectionForBuild.push(newSelectionItem); + // tableFrom = is(builtTableFrom.sql, PgTable) + // ? builtTableFrom.sql + // : new Subquery(builtTableFrom.sql, {}, tableAlias); + // } + // if (selectedColumns.length === 0 && selectedRelations.length === 0 && selectedExtras.length === 0) { + // throw new DrizzleError(`No fields selected for table "${tableConfig.tsName}" ("${tableAlias}")`); + // } + // let selection: BuildRelationalQueryResult['selection']; + // function prepareSelectedColumns() { + // return selectedColumns.map((key) => ({ + // dbKey: tableConfig.columns[key]!.name, + // tsKey: key, + // field: tableConfig.columns[key] as PgColumn, + // relationTableTsKey: undefined, + // isJson: false, + // selection: [], + // })); + // } + // function prepareSelectedExtras() { + // return selectedExtras.map((item) => ({ + // dbKey: item.value.fieldAlias, + // tsKey: item.tsKey, + // field: item.value, + // relationTableTsKey: undefined, + // isJson: false, + // selection: [], + // })); + // } + // if (isRoot) { + // selection = [ + // ...prepareSelectedColumns(), + // ...prepareSelectedExtras(), + // ]; + // } + // if (hasUserDefinedWhere || orderBy.length > 0) { + // tableFrom = new Subquery( + // this.buildSelectQuery({ + // table: is(tableFrom, PgTable) ? aliasedTable(tableFrom, tableAlias) : tableFrom, + // fields: {}, + // fieldsFlat: selectionForBuild.map(({ field }) => ({ + // path: [], + // field: is(field, Column) ? aliasedTableColumn(field, tableAlias) : field, + // })), + // joins, + // distinct, + // }), + // {}, + // tableAlias, + // ); + // selectionForBuild = selection.map((item) => + // is(item.field, SQL.Aliased) + // ? { ...item, field: sql`${sql.identifier(tableAlias)}.${sql.identifier(item.field.fieldAlias)}` } + // : item + // ); + // joins = []; + // distinct = undefined; + // } + // const result = this.buildSelectQuery({ + // table: is(tableFrom, PgTable) ? aliasedTable(tableFrom, tableAlias) : tableFrom, + // fields: {}, + // fieldsFlat: selectionForBuild.map(({ field }) => ({ + // path: [], + // field: is(field, Column) ? aliasedTableColumn(field, tableAlias) : field, + // })), + // where, + // limit, + // offset, + // joins, + // orderBy, + // distinct, + // }); + // return { + // tableTsKey: tableConfig.tsName, + // sql: result, + // selection, + // }; + // } + buildRelationalQueryWithoutPK({ + fullSchema, + schema: schema2, + tableNamesMap, + table, + tableConfig, + queryConfig: config3, + tableAlias, + nestedQueryRelation, + joinOn + }) { + let selection = []; + let limit, offset, orderBy = [], where; + const joins = []; + if (config3 === true) { + const selectionEntries = Object.entries(tableConfig.columns); + selection = selectionEntries.map(([key, value]) => ({ + dbKey: value.name, + tsKey: key, + field: aliasedTableColumn(value, tableAlias), + relationTableTsKey: void 0, + isJson: false, + selection: [] + })); + } else { + const aliasedColumns = Object.fromEntries( + Object.entries(tableConfig.columns).map(([key, value]) => [key, aliasedTableColumn(value, tableAlias)]) + ); + if (config3.where) { + const whereSql = typeof config3.where === "function" ? config3.where(aliasedColumns, getOperators()) : config3.where; + where = whereSql && mapColumnsInSQLToAlias(whereSql, tableAlias); + } + const fieldsSelection = []; + let selectedColumns = []; + if (config3.columns) { + let isIncludeMode = false; + for (const [field, value] of Object.entries(config3.columns)) { + if (value === void 0) { + continue; + } + if (field in tableConfig.columns) { + if (!isIncludeMode && value === true) { + isIncludeMode = true; + } + selectedColumns.push(field); + } + } + if (selectedColumns.length > 0) { + selectedColumns = isIncludeMode ? selectedColumns.filter((c5) => config3.columns?.[c5] === true) : Object.keys(tableConfig.columns).filter((key) => !selectedColumns.includes(key)); + } + } else { + selectedColumns = Object.keys(tableConfig.columns); + } + for (const field of selectedColumns) { + const column = tableConfig.columns[field]; + fieldsSelection.push({ tsKey: field, value: column }); + } + let selectedRelations = []; + if (config3.with) { + selectedRelations = Object.entries(config3.with).filter((entry) => !!entry[1]).map(([tsKey, queryConfig]) => ({ tsKey, queryConfig, relation: tableConfig.relations[tsKey] })); + } + let extras; + if (config3.extras) { + extras = typeof config3.extras === "function" ? config3.extras(aliasedColumns, { sql }) : config3.extras; + for (const [tsKey, value] of Object.entries(extras)) { + fieldsSelection.push({ + tsKey, + value: mapColumnsInAliasedSQLToAlias(value, tableAlias) + }); + } + } + for (const { tsKey, value } of fieldsSelection) { + selection.push({ + dbKey: is(value, SQL.Aliased) ? value.fieldAlias : tableConfig.columns[tsKey].name, + tsKey, + field: is(value, Column) ? aliasedTableColumn(value, tableAlias) : value, + relationTableTsKey: void 0, + isJson: false, + selection: [] + }); + } + let orderByOrig = typeof config3.orderBy === "function" ? config3.orderBy(aliasedColumns, getOrderByOperators()) : config3.orderBy ?? []; + if (!Array.isArray(orderByOrig)) { + orderByOrig = [orderByOrig]; + } + orderBy = orderByOrig.map((orderByValue) => { + if (is(orderByValue, Column)) { + return aliasedTableColumn(orderByValue, tableAlias); + } + return mapColumnsInSQLToAlias(orderByValue, tableAlias); + }); + limit = config3.limit; + offset = config3.offset; + for (const { + tsKey: selectedRelationTsKey, + queryConfig: selectedRelationConfigValue, + relation + } of selectedRelations) { + const normalizedRelation = normalizeRelation(schema2, tableNamesMap, relation); + const relationTableName = getTableUniqueName(relation.referencedTable); + const relationTableTsName = tableNamesMap[relationTableName]; + const relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`; + const joinOn2 = and( + ...normalizedRelation.fields.map( + (field2, i5) => eq( + aliasedTableColumn(normalizedRelation.references[i5], relationTableAlias), + aliasedTableColumn(field2, tableAlias) + ) + ) + ); + const builtRelation = this.buildRelationalQueryWithoutPK({ + fullSchema, + schema: schema2, + tableNamesMap, + table: fullSchema[relationTableTsName], + tableConfig: schema2[relationTableTsName], + queryConfig: is(relation, One) ? selectedRelationConfigValue === true ? { limit: 1 } : { ...selectedRelationConfigValue, limit: 1 } : selectedRelationConfigValue, + tableAlias: relationTableAlias, + joinOn: joinOn2, + nestedQueryRelation: relation + }); + const field = sql`${sql.identifier(relationTableAlias)}.${sql.identifier("data")}`.as(selectedRelationTsKey); + joins.push({ + on: sql`true`, + table: new Subquery(builtRelation.sql, {}, relationTableAlias), + alias: relationTableAlias, + joinType: "left", + lateral: true + }); + selection.push({ + dbKey: selectedRelationTsKey, + tsKey: selectedRelationTsKey, + field, + relationTableTsKey: relationTableTsName, + isJson: true, + selection: builtRelation.selection + }); + } + } + if (selection.length === 0) { + throw new DrizzleError({ message: `No fields selected for table "${tableConfig.tsName}" ("${tableAlias}")` }); + } + let result; + where = and(joinOn, where); + if (nestedQueryRelation) { + let field = sql`json_build_array(${sql.join( + selection.map( + ({ field: field2, tsKey, isJson }) => isJson ? sql`${sql.identifier(`${tableAlias}_${tsKey}`)}.${sql.identifier("data")}` : is(field2, SQL.Aliased) ? field2.sql : field2 + ), + sql`, ` + )})`; + if (is(nestedQueryRelation, Many)) { + field = sql`coalesce(json_agg(${field}${orderBy.length > 0 ? sql` order by ${sql.join(orderBy, sql`, `)}` : void 0}), '[]'::json)`; + } + const nestedSelection = [{ + dbKey: "data", + tsKey: "data", + field: field.as("data"), + isJson: true, + relationTableTsKey: tableConfig.tsName, + selection + }]; + const needsSubquery = limit !== void 0 || offset !== void 0 || orderBy.length > 0; + if (needsSubquery) { + result = this.buildSelectQuery({ + table: aliasedTable(table, tableAlias), + fields: {}, + fieldsFlat: [{ + path: [], + field: sql.raw("*") + }], + where, + limit, + offset, + orderBy, + setOperators: [] + }); + where = void 0; + limit = void 0; + offset = void 0; + orderBy = []; + } else { + result = aliasedTable(table, tableAlias); + } + result = this.buildSelectQuery({ + table: is(result, PgTable) ? result : new Subquery(result, {}, tableAlias), + fields: {}, + fieldsFlat: nestedSelection.map(({ field: field2 }) => ({ + path: [], + field: is(field2, Column) ? aliasedTableColumn(field2, tableAlias) : field2 + })), + joins, + where, + limit, + offset, + orderBy, + setOperators: [] + }); + } else { + result = this.buildSelectQuery({ + table: aliasedTable(table, tableAlias), + fields: {}, + fieldsFlat: selection.map(({ field }) => ({ + path: [], + field: is(field, Column) ? aliasedTableColumn(field, tableAlias) : field + })), + joins, + where, + limit, + offset, + orderBy, + setOperators: [] + }); + } + return { + tableTsKey: tableConfig.tsName, + sql: result, + selection + }; + } + }; + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/selection-proxy.js +var SelectionProxyHandler; +var init_selection_proxy = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/selection-proxy.js"() { + init_alias(); + init_column(); + init_entity(); + init_sql(); + init_subquery(); + init_view_common(); + SelectionProxyHandler = class _SelectionProxyHandler { + static [entityKind] = "SelectionProxyHandler"; + config; + constructor(config3) { + this.config = { ...config3 }; + } + get(subquery, prop) { + if (prop === "_") { + return { + ...subquery["_"], + selectedFields: new Proxy( + subquery._.selectedFields, + this + ) + }; + } + if (prop === ViewBaseConfig) { + return { + ...subquery[ViewBaseConfig], + selectedFields: new Proxy( + subquery[ViewBaseConfig].selectedFields, + this + ) + }; + } + if (typeof prop === "symbol") { + return subquery[prop]; + } + const columns = is(subquery, Subquery) ? subquery._.selectedFields : is(subquery, View) ? subquery[ViewBaseConfig].selectedFields : subquery; + const value = columns[prop]; + if (is(value, SQL.Aliased)) { + if (this.config.sqlAliasedBehavior === "sql" && !value.isSelectionField) { + return value.sql; + } + const newValue = value.clone(); + newValue.isSelectionField = true; + return newValue; + } + if (is(value, SQL)) { + if (this.config.sqlBehavior === "sql") { + return value; + } + throw new Error( + `You tried to reference "${prop}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.` + ); + } + if (is(value, Column)) { + if (this.config.alias) { + return new Proxy( + value, + new ColumnAliasProxyHandler( + new Proxy( + value.table, + new TableAliasProxyHandler(this.config.alias, this.config.replaceOriginalName ?? false) + ) + ) + ); + } + return value; + } + if (typeof value !== "object" || value === null) { + return value; + } + return new Proxy(value, new _SelectionProxyHandler(this.config)); + } + }; + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/query-builders/query-builder.js +var TypedQueryBuilder; +var init_query_builder = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/query-builders/query-builder.js"() { + init_entity(); + TypedQueryBuilder = class { + static [entityKind] = "TypedQueryBuilder"; + /** @internal */ + getSelectedFields() { + return this._.selectedFields; + } + }; + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/query-builders/select.js +function createSetOperator(type, isAll) { + return (leftSelect, rightSelect, ...restSelects) => { + const setOperators = [rightSelect, ...restSelects].map((select2) => ({ + type, + isAll, + rightSelect: select2 + })); + for (const setOperator of setOperators) { + if (!haveSameKeys(leftSelect.getSelectedFields(), setOperator.rightSelect.getSelectedFields())) { + throw new Error( + "Set operator error (union / intersect / except): selected fields are not the same or are in a different order" + ); + } + } + return leftSelect.addSetOperators(setOperators); + }; +} +var PgSelectBuilder, PgSelectQueryBuilderBase, PgSelectBase, getPgSetOperators, union, unionAll, intersect, intersectAll, except, exceptAll; +var init_select2 = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/query-builders/select.js"() { + init_entity(); + init_view_base(); + init_query_builder(); + init_query_promise(); + init_selection_proxy(); + init_sql(); + init_subquery(); + init_table(); + init_tracing(); + init_utils(); + init_utils(); + init_view_common(); + PgSelectBuilder = class { + static [entityKind] = "PgSelectBuilder"; + fields; + session; + dialect; + withList = []; + distinct; + constructor(config3) { + this.fields = config3.fields; + this.session = config3.session; + this.dialect = config3.dialect; + if (config3.withList) { + this.withList = config3.withList; + } + this.distinct = config3.distinct; + } + authToken; + /** @internal */ + setToken(token) { + this.authToken = token; + return this; + } + /** + * Specify the table, subquery, or other target that you're + * building a select query against. + * + * {@link https://www.postgresql.org/docs/current/sql-select.html#SQL-FROM | Postgres from documentation} + */ + from(source) { + const isPartialSelect = !!this.fields; + let fields; + if (this.fields) { + fields = this.fields; + } else if (is(source, Subquery)) { + fields = Object.fromEntries( + Object.keys(source._.selectedFields).map((key) => [key, source[key]]) + ); + } else if (is(source, PgViewBase)) { + fields = source[ViewBaseConfig].selectedFields; + } else if (is(source, SQL)) { + fields = {}; + } else { + fields = getTableColumns(source); + } + return new PgSelectBase({ + table: source, + fields, + isPartialSelect, + session: this.session, + dialect: this.dialect, + withList: this.withList, + distinct: this.distinct + }).setToken(this.authToken); + } + }; + PgSelectQueryBuilderBase = class extends TypedQueryBuilder { + static [entityKind] = "PgSelectQueryBuilder"; + _; + config; + joinsNotNullableMap; + tableName; + isPartialSelect; + session; + dialect; + constructor({ table, fields, isPartialSelect, session, dialect, withList, distinct }) { + super(); + this.config = { + withList, + table, + fields: { ...fields }, + distinct, + setOperators: [] + }; + this.isPartialSelect = isPartialSelect; + this.session = session; + this.dialect = dialect; + this._ = { + selectedFields: fields + }; + this.tableName = getTableLikeName(table); + this.joinsNotNullableMap = typeof this.tableName === "string" ? { [this.tableName]: true } : {}; + } + createJoin(joinType) { + return (table, on) => { + const baseTableName = this.tableName; + const tableName = getTableLikeName(table); + if (typeof tableName === "string" && this.config.joins?.some((join4) => join4.alias === tableName)) { + throw new Error(`Alias "${tableName}" is already used in this query`); + } + if (!this.isPartialSelect) { + if (Object.keys(this.joinsNotNullableMap).length === 1 && typeof baseTableName === "string") { + this.config.fields = { + [baseTableName]: this.config.fields + }; + } + if (typeof tableName === "string" && !is(table, SQL)) { + const selection = is(table, Subquery) ? table._.selectedFields : is(table, View) ? table[ViewBaseConfig].selectedFields : table[Table.Symbol.Columns]; + this.config.fields[tableName] = selection; + } + } + if (typeof on === "function") { + on = on( + new Proxy( + this.config.fields, + new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" }) + ) + ); + } + if (!this.config.joins) { + this.config.joins = []; + } + this.config.joins.push({ on, table, joinType, alias: tableName }); + if (typeof tableName === "string") { + switch (joinType) { + case "left": { + this.joinsNotNullableMap[tableName] = false; + break; + } + case "right": { + this.joinsNotNullableMap = Object.fromEntries( + Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false]) + ); + this.joinsNotNullableMap[tableName] = true; + break; + } + case "inner": { + this.joinsNotNullableMap[tableName] = true; + break; + } + case "full": { + this.joinsNotNullableMap = Object.fromEntries( + Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false]) + ); + this.joinsNotNullableMap[tableName] = false; + break; + } + } + } + return this; + }; + } + /** + * Executes a `left join` operation by adding another table to the current query. + * + * Calling this method associates each row of the table with the corresponding row from the joined table, if a match is found. If no matching row exists, it sets all columns of the joined table to null. + * + * See docs: {@link https://orm.drizzle.team/docs/joins#left-join} + * + * @param table the table to join. + * @param on the `on` clause. + * + * @example + * + * ```ts + * // Select all users and their pets + * const usersWithPets: { user: User; pets: Pet | null }[] = await db.select() + * .from(users) + * .leftJoin(pets, eq(users.id, pets.ownerId)) + * + * // Select userId and petId + * const usersIdsAndPetIds: { userId: number; petId: number | null }[] = await db.select({ + * userId: users.id, + * petId: pets.id, + * }) + * .from(users) + * .leftJoin(pets, eq(users.id, pets.ownerId)) + * ``` + */ + leftJoin = this.createJoin("left"); + /** + * Executes a `right join` operation by adding another table to the current query. + * + * Calling this method associates each row of the joined table with the corresponding row from the main table, if a match is found. If no matching row exists, it sets all columns of the main table to null. + * + * See docs: {@link https://orm.drizzle.team/docs/joins#right-join} + * + * @param table the table to join. + * @param on the `on` clause. + * + * @example + * + * ```ts + * // Select all users and their pets + * const usersWithPets: { user: User | null; pets: Pet }[] = await db.select() + * .from(users) + * .rightJoin(pets, eq(users.id, pets.ownerId)) + * + * // Select userId and petId + * const usersIdsAndPetIds: { userId: number | null; petId: number }[] = await db.select({ + * userId: users.id, + * petId: pets.id, + * }) + * .from(users) + * .rightJoin(pets, eq(users.id, pets.ownerId)) + * ``` + */ + rightJoin = this.createJoin("right"); + /** + * Executes an `inner join` operation, creating a new table by combining rows from two tables that have matching values. + * + * Calling this method retrieves rows that have corresponding entries in both joined tables. Rows without matching entries in either table are excluded, resulting in a table that includes only matching pairs. + * + * See docs: {@link https://orm.drizzle.team/docs/joins#inner-join} + * + * @param table the table to join. + * @param on the `on` clause. + * + * @example + * + * ```ts + * // Select all users and their pets + * const usersWithPets: { user: User; pets: Pet }[] = await db.select() + * .from(users) + * .innerJoin(pets, eq(users.id, pets.ownerId)) + * + * // Select userId and petId + * const usersIdsAndPetIds: { userId: number; petId: number }[] = await db.select({ + * userId: users.id, + * petId: pets.id, + * }) + * .from(users) + * .innerJoin(pets, eq(users.id, pets.ownerId)) + * ``` + */ + innerJoin = this.createJoin("inner"); + /** + * Executes a `full join` operation by combining rows from two tables into a new table. + * + * Calling this method retrieves all rows from both main and joined tables, merging rows with matching values and filling in `null` for non-matching columns. + * + * See docs: {@link https://orm.drizzle.team/docs/joins#full-join} + * + * @param table the table to join. + * @param on the `on` clause. + * + * @example + * + * ```ts + * // Select all users and their pets + * const usersWithPets: { user: User | null; pets: Pet | null }[] = await db.select() + * .from(users) + * .fullJoin(pets, eq(users.id, pets.ownerId)) + * + * // Select userId and petId + * const usersIdsAndPetIds: { userId: number | null; petId: number | null }[] = await db.select({ + * userId: users.id, + * petId: pets.id, + * }) + * .from(users) + * .fullJoin(pets, eq(users.id, pets.ownerId)) + * ``` + */ + fullJoin = this.createJoin("full"); + createSetOperator(type, isAll) { + return (rightSelection) => { + const rightSelect = typeof rightSelection === "function" ? rightSelection(getPgSetOperators()) : rightSelection; + if (!haveSameKeys(this.getSelectedFields(), rightSelect.getSelectedFields())) { + throw new Error( + "Set operator error (union / intersect / except): selected fields are not the same or are in a different order" + ); + } + this.config.setOperators.push({ type, isAll, rightSelect }); + return this; + }; + } + /** + * Adds `union` set operator to the query. + * + * Calling this method will combine the result sets of the `select` statements and remove any duplicate rows that appear across them. + * + * See docs: {@link https://orm.drizzle.team/docs/set-operations#union} + * + * @example + * + * ```ts + * // Select all unique names from customers and users tables + * await db.select({ name: users.name }) + * .from(users) + * .union( + * db.select({ name: customers.name }).from(customers) + * ); + * // or + * import { union } from 'drizzle-orm/pg-core' + * + * await union( + * db.select({ name: users.name }).from(users), + * db.select({ name: customers.name }).from(customers) + * ); + * ``` + */ + union = this.createSetOperator("union", false); + /** + * Adds `union all` set operator to the query. + * + * Calling this method will combine the result-set of the `select` statements and keep all duplicate rows that appear across them. + * + * See docs: {@link https://orm.drizzle.team/docs/set-operations#union-all} + * + * @example + * + * ```ts + * // Select all transaction ids from both online and in-store sales + * await db.select({ transaction: onlineSales.transactionId }) + * .from(onlineSales) + * .unionAll( + * db.select({ transaction: inStoreSales.transactionId }).from(inStoreSales) + * ); + * // or + * import { unionAll } from 'drizzle-orm/pg-core' + * + * await unionAll( + * db.select({ transaction: onlineSales.transactionId }).from(onlineSales), + * db.select({ transaction: inStoreSales.transactionId }).from(inStoreSales) + * ); + * ``` + */ + unionAll = this.createSetOperator("union", true); + /** + * Adds `intersect` set operator to the query. + * + * Calling this method will retain only the rows that are present in both result sets and eliminate duplicates. + * + * See docs: {@link https://orm.drizzle.team/docs/set-operations#intersect} + * + * @example + * + * ```ts + * // Select course names that are offered in both departments A and B + * await db.select({ courseName: depA.courseName }) + * .from(depA) + * .intersect( + * db.select({ courseName: depB.courseName }).from(depB) + * ); + * // or + * import { intersect } from 'drizzle-orm/pg-core' + * + * await intersect( + * db.select({ courseName: depA.courseName }).from(depA), + * db.select({ courseName: depB.courseName }).from(depB) + * ); + * ``` + */ + intersect = this.createSetOperator("intersect", false); + /** + * Adds `intersect all` set operator to the query. + * + * Calling this method will retain only the rows that are present in both result sets including all duplicates. + * + * See docs: {@link https://orm.drizzle.team/docs/set-operations#intersect-all} + * + * @example + * + * ```ts + * // Select all products and quantities that are ordered by both regular and VIP customers + * await db.select({ + * productId: regularCustomerOrders.productId, + * quantityOrdered: regularCustomerOrders.quantityOrdered + * }) + * .from(regularCustomerOrders) + * .intersectAll( + * db.select({ + * productId: vipCustomerOrders.productId, + * quantityOrdered: vipCustomerOrders.quantityOrdered + * }) + * .from(vipCustomerOrders) + * ); + * // or + * import { intersectAll } from 'drizzle-orm/pg-core' + * + * await intersectAll( + * db.select({ + * productId: regularCustomerOrders.productId, + * quantityOrdered: regularCustomerOrders.quantityOrdered + * }) + * .from(regularCustomerOrders), + * db.select({ + * productId: vipCustomerOrders.productId, + * quantityOrdered: vipCustomerOrders.quantityOrdered + * }) + * .from(vipCustomerOrders) + * ); + * ``` + */ + intersectAll = this.createSetOperator("intersect", true); + /** + * Adds `except` set operator to the query. + * + * Calling this method will retrieve all unique rows from the left query, except for the rows that are present in the result set of the right query. + * + * See docs: {@link https://orm.drizzle.team/docs/set-operations#except} + * + * @example + * + * ```ts + * // Select all courses offered in department A but not in department B + * await db.select({ courseName: depA.courseName }) + * .from(depA) + * .except( + * db.select({ courseName: depB.courseName }).from(depB) + * ); + * // or + * import { except } from 'drizzle-orm/pg-core' + * + * await except( + * db.select({ courseName: depA.courseName }).from(depA), + * db.select({ courseName: depB.courseName }).from(depB) + * ); + * ``` + */ + except = this.createSetOperator("except", false); + /** + * Adds `except all` set operator to the query. + * + * Calling this method will retrieve all rows from the left query, except for the rows that are present in the result set of the right query. + * + * See docs: {@link https://orm.drizzle.team/docs/set-operations#except-all} + * + * @example + * + * ```ts + * // Select all products that are ordered by regular customers but not by VIP customers + * await db.select({ + * productId: regularCustomerOrders.productId, + * quantityOrdered: regularCustomerOrders.quantityOrdered, + * }) + * .from(regularCustomerOrders) + * .exceptAll( + * db.select({ + * productId: vipCustomerOrders.productId, + * quantityOrdered: vipCustomerOrders.quantityOrdered, + * }) + * .from(vipCustomerOrders) + * ); + * // or + * import { exceptAll } from 'drizzle-orm/pg-core' + * + * await exceptAll( + * db.select({ + * productId: regularCustomerOrders.productId, + * quantityOrdered: regularCustomerOrders.quantityOrdered + * }) + * .from(regularCustomerOrders), + * db.select({ + * productId: vipCustomerOrders.productId, + * quantityOrdered: vipCustomerOrders.quantityOrdered + * }) + * .from(vipCustomerOrders) + * ); + * ``` + */ + exceptAll = this.createSetOperator("except", true); + /** @internal */ + addSetOperators(setOperators) { + this.config.setOperators.push(...setOperators); + return this; + } + /** + * Adds a `where` clause to the query. + * + * Calling this method will select only those rows that fulfill a specified condition. + * + * See docs: {@link https://orm.drizzle.team/docs/select#filtering} + * + * @param where the `where` clause. + * + * @example + * You can use conditional operators and `sql function` to filter the rows to be selected. + * + * ```ts + * // Select all cars with green color + * await db.select().from(cars).where(eq(cars.color, 'green')); + * // or + * await db.select().from(cars).where(sql`${cars.color} = 'green'`) + * ``` + * + * You can logically combine conditional operators with `and()` and `or()` operators: + * + * ```ts + * // Select all BMW cars with a green color + * await db.select().from(cars).where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW'))); + * + * // Select all cars with the green or blue color + * await db.select().from(cars).where(or(eq(cars.color, 'green'), eq(cars.color, 'blue'))); + * ``` + */ + where(where) { + if (typeof where === "function") { + where = where( + new Proxy( + this.config.fields, + new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" }) + ) + ); + } + this.config.where = where; + return this; + } + /** + * Adds a `having` clause to the query. + * + * Calling this method will select only those rows that fulfill a specified condition. It is typically used with aggregate functions to filter the aggregated data based on a specified condition. + * + * See docs: {@link https://orm.drizzle.team/docs/select#aggregations} + * + * @param having the `having` clause. + * + * @example + * + * ```ts + * // Select all brands with more than one car + * await db.select({ + * brand: cars.brand, + * count: sql`cast(count(${cars.id}) as int)`, + * }) + * .from(cars) + * .groupBy(cars.brand) + * .having(({ count }) => gt(count, 1)); + * ``` + */ + having(having) { + if (typeof having === "function") { + having = having( + new Proxy( + this.config.fields, + new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" }) + ) + ); + } + this.config.having = having; + return this; + } + groupBy(...columns) { + if (typeof columns[0] === "function") { + const groupBy = columns[0]( + new Proxy( + this.config.fields, + new SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" }) + ) + ); + this.config.groupBy = Array.isArray(groupBy) ? groupBy : [groupBy]; + } else { + this.config.groupBy = columns; + } + return this; + } + orderBy(...columns) { + if (typeof columns[0] === "function") { + const orderBy = columns[0]( + new Proxy( + this.config.fields, + new SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" }) + ) + ); + const orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy]; + if (this.config.setOperators.length > 0) { + this.config.setOperators.at(-1).orderBy = orderByArray; + } else { + this.config.orderBy = orderByArray; + } + } else { + const orderByArray = columns; + if (this.config.setOperators.length > 0) { + this.config.setOperators.at(-1).orderBy = orderByArray; + } else { + this.config.orderBy = orderByArray; + } + } + return this; + } + /** + * Adds a `limit` clause to the query. + * + * Calling this method will set the maximum number of rows that will be returned by this query. + * + * See docs: {@link https://orm.drizzle.team/docs/select#limit--offset} + * + * @param limit the `limit` clause. + * + * @example + * + * ```ts + * // Get the first 10 people from this query. + * await db.select().from(people).limit(10); + * ``` + */ + limit(limit) { + if (this.config.setOperators.length > 0) { + this.config.setOperators.at(-1).limit = limit; + } else { + this.config.limit = limit; + } + return this; + } + /** + * Adds an `offset` clause to the query. + * + * Calling this method will skip a number of rows when returning results from this query. + * + * See docs: {@link https://orm.drizzle.team/docs/select#limit--offset} + * + * @param offset the `offset` clause. + * + * @example + * + * ```ts + * // Get the 10th-20th people from this query. + * await db.select().from(people).offset(10).limit(10); + * ``` + */ + offset(offset) { + if (this.config.setOperators.length > 0) { + this.config.setOperators.at(-1).offset = offset; + } else { + this.config.offset = offset; + } + return this; + } + /** + * Adds a `for` clause to the query. + * + * Calling this method will specify a lock strength for this query that controls how strictly it acquires exclusive access to the rows being queried. + * + * See docs: {@link https://www.postgresql.org/docs/current/sql-select.html#SQL-FOR-UPDATE-SHARE} + * + * @param strength the lock strength. + * @param config the lock configuration. + */ + for(strength, config3 = {}) { + this.config.lockingClause = { strength, config: config3 }; + return this; + } + /** @internal */ + getSQL() { + return this.dialect.buildSelectQuery(this.config); + } + toSQL() { + const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL()); + return rest; + } + as(alias) { + return new Proxy( + new Subquery(this.getSQL(), this.config.fields, alias), + new SelectionProxyHandler({ alias, sqlAliasedBehavior: "alias", sqlBehavior: "error" }) + ); + } + /** @internal */ + getSelectedFields() { + return new Proxy( + this.config.fields, + new SelectionProxyHandler({ alias: this.tableName, sqlAliasedBehavior: "alias", sqlBehavior: "error" }) + ); + } + $dynamic() { + return this; + } + }; + PgSelectBase = class extends PgSelectQueryBuilderBase { + static [entityKind] = "PgSelect"; + /** @internal */ + _prepare(name) { + const { session, config: config3, dialect, joinsNotNullableMap, authToken } = this; + if (!session) { + throw new Error("Cannot execute a query on a query builder. Please use a database instance instead."); + } + return tracer.startActiveSpan("drizzle.prepareQuery", () => { + const fieldsList = orderSelectedFields(config3.fields); + const query = session.prepareQuery(dialect.sqlToQuery(this.getSQL()), fieldsList, name, true); + query.joinsNotNullableMap = joinsNotNullableMap; + return query.setToken(authToken); + }); + } + /** + * Create a prepared statement for this query. This allows + * the database to remember this query for the given session + * and call it by name, rather than specifying the full query. + * + * {@link https://www.postgresql.org/docs/current/sql-prepare.html | Postgres prepare documentation} + */ + prepare(name) { + return this._prepare(name); + } + authToken; + /** @internal */ + setToken(token) { + this.authToken = token; + return this; + } + execute = (placeholderValues) => { + return tracer.startActiveSpan("drizzle.operation", () => { + return this._prepare().execute(placeholderValues, this.authToken); + }); + }; + }; + applyMixins(PgSelectBase, [QueryPromise]); + getPgSetOperators = () => ({ + union, + unionAll, + intersect, + intersectAll, + except, + exceptAll + }); + union = createSetOperator("union", false); + unionAll = createSetOperator("union", true); + intersect = createSetOperator("intersect", false); + intersectAll = createSetOperator("intersect", true); + except = createSetOperator("except", false); + exceptAll = createSetOperator("except", true); + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/query-builders/query-builder.js +var QueryBuilder; +var init_query_builder2 = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/query-builders/query-builder.js"() { + init_entity(); + init_dialect(); + init_selection_proxy(); + init_subquery(); + init_select2(); + QueryBuilder = class { + static [entityKind] = "PgQueryBuilder"; + dialect; + dialectConfig; + constructor(dialect) { + this.dialect = is(dialect, PgDialect) ? dialect : void 0; + this.dialectConfig = is(dialect, PgDialect) ? void 0 : dialect; + } + $with(alias) { + const queryBuilder = this; + return { + as(qb) { + if (typeof qb === "function") { + qb = qb(queryBuilder); + } + return new Proxy( + new WithSubquery(qb.getSQL(), qb.getSelectedFields(), alias, true), + new SelectionProxyHandler({ alias, sqlAliasedBehavior: "alias", sqlBehavior: "error" }) + ); + } + }; + } + with(...queries) { + const self2 = this; + function select2(fields) { + return new PgSelectBuilder({ + fields: fields ?? void 0, + session: void 0, + dialect: self2.getDialect(), + withList: queries + }); + } + function selectDistinct(fields) { + return new PgSelectBuilder({ + fields: fields ?? void 0, + session: void 0, + dialect: self2.getDialect(), + distinct: true + }); + } + function selectDistinctOn(on, fields) { + return new PgSelectBuilder({ + fields: fields ?? void 0, + session: void 0, + dialect: self2.getDialect(), + distinct: { on } + }); + } + return { select: select2, selectDistinct, selectDistinctOn }; + } + select(fields) { + return new PgSelectBuilder({ + fields: fields ?? void 0, + session: void 0, + dialect: this.getDialect() + }); + } + selectDistinct(fields) { + return new PgSelectBuilder({ + fields: fields ?? void 0, + session: void 0, + dialect: this.getDialect(), + distinct: true + }); + } + selectDistinctOn(on, fields) { + return new PgSelectBuilder({ + fields: fields ?? void 0, + session: void 0, + dialect: this.getDialect(), + distinct: { on } + }); + } + // Lazy load dialect to avoid circular dependency + getDialect() { + if (!this.dialect) { + this.dialect = new PgDialect(this.dialectConfig); + } + return this.dialect; + } + }; + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/query-builders/insert.js +var PgInsertBuilder, PgInsertBase; +var init_insert = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/query-builders/insert.js"() { + init_entity(); + init_query_promise(); + init_sql(); + init_table(); + init_tracing(); + init_utils(); + init_query_builder2(); + PgInsertBuilder = class { + constructor(table, session, dialect, withList, overridingSystemValue_) { + this.table = table; + this.session = session; + this.dialect = dialect; + this.withList = withList; + this.overridingSystemValue_ = overridingSystemValue_; + } + static [entityKind] = "PgInsertBuilder"; + authToken; + /** @internal */ + setToken(token) { + this.authToken = token; + return this; + } + overridingSystemValue() { + this.overridingSystemValue_ = true; + return this; + } + values(values2) { + values2 = Array.isArray(values2) ? values2 : [values2]; + if (values2.length === 0) { + throw new Error("values() must be called with at least one value"); + } + const mappedValues = values2.map((entry) => { + const result = {}; + const cols = this.table[Table.Symbol.Columns]; + for (const colKey of Object.keys(entry)) { + const colValue = entry[colKey]; + result[colKey] = is(colValue, SQL) ? colValue : new Param(colValue, cols[colKey]); + } + return result; + }); + return new PgInsertBase( + this.table, + mappedValues, + this.session, + this.dialect, + this.withList, + false, + this.overridingSystemValue_ + ).setToken(this.authToken); + } + select(selectQuery) { + const select2 = typeof selectQuery === "function" ? selectQuery(new QueryBuilder()) : selectQuery; + if (!is(select2, SQL) && !haveSameKeys(this.table[Columns], select2._.selectedFields)) { + throw new Error( + "Insert select error: selected fields are not the same or are in a different order compared to the table definition" + ); + } + return new PgInsertBase(this.table, select2, this.session, this.dialect, this.withList, true); + } + }; + PgInsertBase = class extends QueryPromise { + constructor(table, values2, session, dialect, withList, select2, overridingSystemValue_) { + super(); + this.session = session; + this.dialect = dialect; + this.config = { table, values: values2, withList, select: select2, overridingSystemValue_ }; + } + static [entityKind] = "PgInsert"; + config; + returning(fields = this.config.table[Table.Symbol.Columns]) { + this.config.returning = orderSelectedFields(fields); + return this; + } + /** + * Adds an `on conflict do nothing` clause to the query. + * + * Calling this method simply avoids inserting a row as its alternative action. + * + * See docs: {@link https://orm.drizzle.team/docs/insert#on-conflict-do-nothing} + * + * @param config The `target` and `where` clauses. + * + * @example + * ```ts + * // Insert one row and cancel the insert if there's a conflict + * await db.insert(cars) + * .values({ id: 1, brand: 'BMW' }) + * .onConflictDoNothing(); + * + * // Explicitly specify conflict target + * await db.insert(cars) + * .values({ id: 1, brand: 'BMW' }) + * .onConflictDoNothing({ target: cars.id }); + * ``` + */ + onConflictDoNothing(config3 = {}) { + if (config3.target === void 0) { + this.config.onConflict = sql`do nothing`; + } else { + let targetColumn = ""; + targetColumn = Array.isArray(config3.target) ? config3.target.map((it) => this.dialect.escapeName(this.dialect.casing.getColumnCasing(it))).join(",") : this.dialect.escapeName(this.dialect.casing.getColumnCasing(config3.target)); + const whereSql = config3.where ? sql` where ${config3.where}` : void 0; + this.config.onConflict = sql`(${sql.raw(targetColumn)})${whereSql} do nothing`; + } + return this; + } + /** + * Adds an `on conflict do update` clause to the query. + * + * Calling this method will update the existing row that conflicts with the row proposed for insertion as its alternative action. + * + * See docs: {@link https://orm.drizzle.team/docs/insert#upserts-and-conflicts} + * + * @param config The `target`, `set` and `where` clauses. + * + * @example + * ```ts + * // Update the row if there's a conflict + * await db.insert(cars) + * .values({ id: 1, brand: 'BMW' }) + * .onConflictDoUpdate({ + * target: cars.id, + * set: { brand: 'Porsche' } + * }); + * + * // Upsert with 'where' clause + * await db.insert(cars) + * .values({ id: 1, brand: 'BMW' }) + * .onConflictDoUpdate({ + * target: cars.id, + * set: { brand: 'newBMW' }, + * targetWhere: sql`${cars.createdAt} > '2023-01-01'::date`, + * }); + * ``` + */ + onConflictDoUpdate(config3) { + if (config3.where && (config3.targetWhere || config3.setWhere)) { + throw new Error( + 'You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.' + ); + } + const whereSql = config3.where ? sql` where ${config3.where}` : void 0; + const targetWhereSql = config3.targetWhere ? sql` where ${config3.targetWhere}` : void 0; + const setWhereSql = config3.setWhere ? sql` where ${config3.setWhere}` : void 0; + const setSql = this.dialect.buildUpdateSet(this.config.table, mapUpdateSet(this.config.table, config3.set)); + let targetColumn = ""; + targetColumn = Array.isArray(config3.target) ? config3.target.map((it) => this.dialect.escapeName(this.dialect.casing.getColumnCasing(it))).join(",") : this.dialect.escapeName(this.dialect.casing.getColumnCasing(config3.target)); + this.config.onConflict = sql`(${sql.raw(targetColumn)})${targetWhereSql} do update set ${setSql}${whereSql}${setWhereSql}`; + return this; + } + /** @internal */ + getSQL() { + return this.dialect.buildInsertQuery(this.config); + } + toSQL() { + const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL()); + return rest; + } + /** @internal */ + _prepare(name) { + return tracer.startActiveSpan("drizzle.prepareQuery", () => { + return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), this.config.returning, name, true); + }); + } + prepare(name) { + return this._prepare(name); + } + authToken; + /** @internal */ + setToken(token) { + this.authToken = token; + return this; + } + execute = (placeholderValues) => { + return tracer.startActiveSpan("drizzle.operation", () => { + return this._prepare().execute(placeholderValues, this.authToken); + }); + }; + $dynamic() { + return this; + } + }; + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/query-builders/refresh-materialized-view.js +var PgRefreshMaterializedView; +var init_refresh_materialized_view = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/query-builders/refresh-materialized-view.js"() { + init_entity(); + init_query_promise(); + init_tracing(); + PgRefreshMaterializedView = class extends QueryPromise { + constructor(view, session, dialect) { + super(); + this.session = session; + this.dialect = dialect; + this.config = { view }; + } + static [entityKind] = "PgRefreshMaterializedView"; + config; + concurrently() { + if (this.config.withNoData !== void 0) { + throw new Error("Cannot use concurrently and withNoData together"); + } + this.config.concurrently = true; + return this; + } + withNoData() { + if (this.config.concurrently !== void 0) { + throw new Error("Cannot use concurrently and withNoData together"); + } + this.config.withNoData = true; + return this; + } + /** @internal */ + getSQL() { + return this.dialect.buildRefreshMaterializedViewQuery(this.config); + } + toSQL() { + const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL()); + return rest; + } + /** @internal */ + _prepare(name) { + return tracer.startActiveSpan("drizzle.prepareQuery", () => { + return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), void 0, name, true); + }); + } + prepare(name) { + return this._prepare(name); + } + authToken; + /** @internal */ + setToken(token) { + this.authToken = token; + return this; + } + execute = (placeholderValues) => { + return tracer.startActiveSpan("drizzle.operation", () => { + return this._prepare().execute(placeholderValues, this.authToken); + }); + }; + }; + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/query-builders/select.types.js +var init_select_types = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/query-builders/select.types.js"() { + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/query-builders/update.js +var PgUpdateBuilder, PgUpdateBase; +var init_update = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/query-builders/update.js"() { + init_entity(); + init_table2(); + init_query_promise(); + init_selection_proxy(); + init_sql(); + init_subquery(); + init_table(); + init_utils(); + init_view_common(); + PgUpdateBuilder = class { + constructor(table, session, dialect, withList) { + this.table = table; + this.session = session; + this.dialect = dialect; + this.withList = withList; + } + static [entityKind] = "PgUpdateBuilder"; + authToken; + setToken(token) { + this.authToken = token; + return this; + } + set(values2) { + return new PgUpdateBase( + this.table, + mapUpdateSet(this.table, values2), + this.session, + this.dialect, + this.withList + ).setToken(this.authToken); + } + }; + PgUpdateBase = class extends QueryPromise { + constructor(table, set2, session, dialect, withList) { + super(); + this.session = session; + this.dialect = dialect; + this.config = { set: set2, table, withList, joins: [] }; + this.tableName = getTableLikeName(table); + this.joinsNotNullableMap = typeof this.tableName === "string" ? { [this.tableName]: true } : {}; + } + static [entityKind] = "PgUpdate"; + config; + tableName; + joinsNotNullableMap; + from(source) { + const tableName = getTableLikeName(source); + if (typeof tableName === "string") { + this.joinsNotNullableMap[tableName] = true; + } + this.config.from = source; + return this; + } + getTableLikeFields(table) { + if (is(table, PgTable)) { + return table[Table.Symbol.Columns]; + } else if (is(table, Subquery)) { + return table._.selectedFields; + } + return table[ViewBaseConfig].selectedFields; + } + createJoin(joinType) { + return (table, on) => { + const tableName = getTableLikeName(table); + if (typeof tableName === "string" && this.config.joins.some((join4) => join4.alias === tableName)) { + throw new Error(`Alias "${tableName}" is already used in this query`); + } + if (typeof on === "function") { + const from = this.config.from && !is(this.config.from, SQL) ? this.getTableLikeFields(this.config.from) : void 0; + on = on( + new Proxy( + this.config.table[Table.Symbol.Columns], + new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" }) + ), + from && new Proxy( + from, + new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" }) + ) + ); + } + this.config.joins.push({ on, table, joinType, alias: tableName }); + if (typeof tableName === "string") { + switch (joinType) { + case "left": { + this.joinsNotNullableMap[tableName] = false; + break; + } + case "right": { + this.joinsNotNullableMap = Object.fromEntries( + Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false]) + ); + this.joinsNotNullableMap[tableName] = true; + break; + } + case "inner": { + this.joinsNotNullableMap[tableName] = true; + break; + } + case "full": { + this.joinsNotNullableMap = Object.fromEntries( + Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false]) + ); + this.joinsNotNullableMap[tableName] = false; + break; + } + } + } + return this; + }; + } + leftJoin = this.createJoin("left"); + rightJoin = this.createJoin("right"); + innerJoin = this.createJoin("inner"); + fullJoin = this.createJoin("full"); + /** + * Adds a 'where' clause to the query. + * + * Calling this method will update only those rows that fulfill a specified condition. + * + * See docs: {@link https://orm.drizzle.team/docs/update} + * + * @param where the 'where' clause. + * + * @example + * You can use conditional operators and `sql function` to filter the rows to be updated. + * + * ```ts + * // Update all cars with green color + * await db.update(cars).set({ color: 'red' }) + * .where(eq(cars.color, 'green')); + * // or + * await db.update(cars).set({ color: 'red' }) + * .where(sql`${cars.color} = 'green'`) + * ``` + * + * You can logically combine conditional operators with `and()` and `or()` operators: + * + * ```ts + * // Update all BMW cars with a green color + * await db.update(cars).set({ color: 'red' }) + * .where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW'))); + * + * // Update all cars with the green or blue color + * await db.update(cars).set({ color: 'red' }) + * .where(or(eq(cars.color, 'green'), eq(cars.color, 'blue'))); + * ``` + */ + where(where) { + this.config.where = where; + return this; + } + returning(fields) { + if (!fields) { + fields = Object.assign({}, this.config.table[Table.Symbol.Columns]); + if (this.config.from) { + const tableName = getTableLikeName(this.config.from); + if (typeof tableName === "string" && this.config.from && !is(this.config.from, SQL)) { + const fromFields = this.getTableLikeFields(this.config.from); + fields[tableName] = fromFields; + } + for (const join4 of this.config.joins) { + const tableName2 = getTableLikeName(join4.table); + if (typeof tableName2 === "string" && !is(join4.table, SQL)) { + const fromFields = this.getTableLikeFields(join4.table); + fields[tableName2] = fromFields; + } + } + } + } + this.config.returning = orderSelectedFields(fields); + return this; + } + /** @internal */ + getSQL() { + return this.dialect.buildUpdateQuery(this.config); + } + toSQL() { + const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL()); + return rest; + } + /** @internal */ + _prepare(name) { + const query = this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), this.config.returning, name, true); + query.joinsNotNullableMap = this.joinsNotNullableMap; + return query; + } + prepare(name) { + return this._prepare(name); + } + authToken; + /** @internal */ + setToken(token) { + this.authToken = token; + return this; + } + execute = (placeholderValues) => { + return this._prepare().execute(placeholderValues, this.authToken); + }; + $dynamic() { + return this; + } + }; + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/query-builders/index.js +var init_query_builders = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/query-builders/index.js"() { + init_delete(); + init_insert(); + init_query_builder2(); + init_refresh_materialized_view(); + init_select2(); + init_select_types(); + init_update(); + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/query-builders/count.js +var PgCountBuilder; +var init_count = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/query-builders/count.js"() { + init_entity(); + init_sql(); + PgCountBuilder = class _PgCountBuilder extends SQL { + constructor(params) { + super(_PgCountBuilder.buildEmbeddedCount(params.source, params.filters).queryChunks); + this.params = params; + this.mapWith(Number); + this.session = params.session; + this.sql = _PgCountBuilder.buildCount( + params.source, + params.filters + ); + } + sql; + token; + static [entityKind] = "PgCountBuilder"; + [Symbol.toStringTag] = "PgCountBuilder"; + session; + static buildEmbeddedCount(source, filters) { + return sql`(select count(*) from ${source}${sql.raw(" where ").if(filters)}${filters})`; + } + static buildCount(source, filters) { + return sql`select count(*) as count from ${source}${sql.raw(" where ").if(filters)}${filters};`; + } + /** @intrnal */ + setToken(token) { + this.token = token; + return this; + } + then(onfulfilled, onrejected) { + return Promise.resolve(this.session.count(this.sql, this.token)).then( + onfulfilled, + onrejected + ); + } + catch(onRejected) { + return this.then(void 0, onRejected); + } + finally(onFinally) { + return this.then( + (value) => { + onFinally?.(); + return value; + }, + (reason) => { + onFinally?.(); + throw reason; + } + ); + } + }; + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/query-builders/query.js +var RelationalQueryBuilder, PgRelationalQuery; +var init_query2 = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/query-builders/query.js"() { + init_entity(); + init_query_promise(); + init_relations(); + init_tracing(); + RelationalQueryBuilder = class { + constructor(fullSchema, schema2, tableNamesMap, table, tableConfig, dialect, session) { + this.fullSchema = fullSchema; + this.schema = schema2; + this.tableNamesMap = tableNamesMap; + this.table = table; + this.tableConfig = tableConfig; + this.dialect = dialect; + this.session = session; + } + static [entityKind] = "PgRelationalQueryBuilder"; + findMany(config3) { + return new PgRelationalQuery( + this.fullSchema, + this.schema, + this.tableNamesMap, + this.table, + this.tableConfig, + this.dialect, + this.session, + config3 ? config3 : {}, + "many" + ); + } + findFirst(config3) { + return new PgRelationalQuery( + this.fullSchema, + this.schema, + this.tableNamesMap, + this.table, + this.tableConfig, + this.dialect, + this.session, + config3 ? { ...config3, limit: 1 } : { limit: 1 }, + "first" + ); + } + }; + PgRelationalQuery = class extends QueryPromise { + constructor(fullSchema, schema2, tableNamesMap, table, tableConfig, dialect, session, config3, mode) { + super(); + this.fullSchema = fullSchema; + this.schema = schema2; + this.tableNamesMap = tableNamesMap; + this.table = table; + this.tableConfig = tableConfig; + this.dialect = dialect; + this.session = session; + this.config = config3; + this.mode = mode; + } + static [entityKind] = "PgRelationalQuery"; + /** @internal */ + _prepare(name) { + return tracer.startActiveSpan("drizzle.prepareQuery", () => { + const { query, builtQuery } = this._toSQL(); + return this.session.prepareQuery( + builtQuery, + void 0, + name, + true, + (rawRows, mapColumnValue) => { + const rows = rawRows.map( + (row) => mapRelationalRow(this.schema, this.tableConfig, row, query.selection, mapColumnValue) + ); + if (this.mode === "first") { + return rows[0]; + } + return rows; + } + ); + }); + } + prepare(name) { + return this._prepare(name); + } + _getQuery() { + return this.dialect.buildRelationalQueryWithoutPK({ + fullSchema: this.fullSchema, + schema: this.schema, + tableNamesMap: this.tableNamesMap, + table: this.table, + tableConfig: this.tableConfig, + queryConfig: this.config, + tableAlias: this.tableConfig.tsName + }); + } + /** @internal */ + getSQL() { + return this._getQuery().sql; + } + _toSQL() { + const query = this._getQuery(); + const builtQuery = this.dialect.sqlToQuery(query.sql); + return { query, builtQuery }; + } + toSQL() { + return this._toSQL().builtQuery; + } + authToken; + /** @internal */ + setToken(token) { + this.authToken = token; + return this; + } + execute() { + return tracer.startActiveSpan("drizzle.operation", () => { + return this._prepare().execute(void 0, this.authToken); + }); + } + }; + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/query-builders/raw.js +var PgRaw; +var init_raw = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/query-builders/raw.js"() { + init_entity(); + init_query_promise(); + PgRaw = class extends QueryPromise { + constructor(execute11, sql3, query, mapBatchResult) { + super(); + this.execute = execute11; + this.sql = sql3; + this.query = query; + this.mapBatchResult = mapBatchResult; + } + static [entityKind] = "PgRaw"; + /** @internal */ + getSQL() { + return this.sql; + } + getQuery() { + return this.query; + } + mapResult(result, isFromBatch) { + return isFromBatch ? this.mapBatchResult(result) : result; + } + _prepare() { + return this; + } + /** @internal */ + isResponseInArrayMode() { + return false; + } + }; + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/db.js +var PgDatabase; +var init_db = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/db.js"() { + init_entity(); + init_query_builders(); + init_selection_proxy(); + init_sql(); + init_subquery(); + init_count(); + init_query2(); + init_raw(); + init_refresh_materialized_view(); + PgDatabase = class { + constructor(dialect, session, schema2) { + this.dialect = dialect; + this.session = session; + this._ = schema2 ? { + schema: schema2.schema, + fullSchema: schema2.fullSchema, + tableNamesMap: schema2.tableNamesMap, + session + } : { + schema: void 0, + fullSchema: {}, + tableNamesMap: {}, + session + }; + this.query = {}; + if (this._.schema) { + for (const [tableName, columns] of Object.entries(this._.schema)) { + this.query[tableName] = new RelationalQueryBuilder( + schema2.fullSchema, + this._.schema, + this._.tableNamesMap, + schema2.fullSchema[tableName], + columns, + dialect, + session + ); + } + } + } + static [entityKind] = "PgDatabase"; + query; + /** + * Creates a subquery that defines a temporary named result set as a CTE. + * + * It is useful for breaking down complex queries into simpler parts and for reusing the result set in subsequent parts of the query. + * + * See docs: {@link https://orm.drizzle.team/docs/select#with-clause} + * + * @param alias The alias for the subquery. + * + * Failure to provide an alias will result in a DrizzleTypeError, preventing the subquery from being referenced in other queries. + * + * @example + * + * ```ts + * // Create a subquery with alias 'sq' and use it in the select query + * const sq = db.$with('sq').as(db.select().from(users).where(eq(users.id, 42))); + * + * const result = await db.with(sq).select().from(sq); + * ``` + * + * To select arbitrary SQL values as fields in a CTE and reference them in other CTEs or in the main query, you need to add aliases to them: + * + * ```ts + * // Select an arbitrary SQL value as a field in a CTE and reference it in the main query + * const sq = db.$with('sq').as(db.select({ + * name: sql`upper(${users.name})`.as('name'), + * }) + * .from(users)); + * + * const result = await db.with(sq).select({ name: sq.name }).from(sq); + * ``` + */ + $with(alias) { + const self2 = this; + return { + as(qb) { + if (typeof qb === "function") { + qb = qb(new QueryBuilder(self2.dialect)); + } + return new Proxy( + new WithSubquery(qb.getSQL(), qb.getSelectedFields(), alias, true), + new SelectionProxyHandler({ alias, sqlAliasedBehavior: "alias", sqlBehavior: "error" }) + ); + } + }; + } + $count(source, filters) { + return new PgCountBuilder({ source, filters, session: this.session }); + } + /** + * Incorporates a previously defined CTE (using `$with`) into the main query. + * + * This method allows the main query to reference a temporary named result set. + * + * See docs: {@link https://orm.drizzle.team/docs/select#with-clause} + * + * @param queries The CTEs to incorporate into the main query. + * + * @example + * + * ```ts + * // Define a subquery 'sq' as a CTE using $with + * const sq = db.$with('sq').as(db.select().from(users).where(eq(users.id, 42))); + * + * // Incorporate the CTE 'sq' into the main query and select from it + * const result = await db.with(sq).select().from(sq); + * ``` + */ + with(...queries) { + const self2 = this; + function select2(fields) { + return new PgSelectBuilder({ + fields: fields ?? void 0, + session: self2.session, + dialect: self2.dialect, + withList: queries + }); + } + function selectDistinct(fields) { + return new PgSelectBuilder({ + fields: fields ?? void 0, + session: self2.session, + dialect: self2.dialect, + withList: queries, + distinct: true + }); + } + function selectDistinctOn(on, fields) { + return new PgSelectBuilder({ + fields: fields ?? void 0, + session: self2.session, + dialect: self2.dialect, + withList: queries, + distinct: { on } + }); + } + function update(table) { + return new PgUpdateBuilder(table, self2.session, self2.dialect, queries); + } + function insert(table) { + return new PgInsertBuilder(table, self2.session, self2.dialect, queries); + } + function delete_(table) { + return new PgDeleteBase(table, self2.session, self2.dialect, queries); + } + return { select: select2, selectDistinct, selectDistinctOn, update, insert, delete: delete_ }; + } + select(fields) { + return new PgSelectBuilder({ + fields: fields ?? void 0, + session: this.session, + dialect: this.dialect + }); + } + selectDistinct(fields) { + return new PgSelectBuilder({ + fields: fields ?? void 0, + session: this.session, + dialect: this.dialect, + distinct: true + }); + } + selectDistinctOn(on, fields) { + return new PgSelectBuilder({ + fields: fields ?? void 0, + session: this.session, + dialect: this.dialect, + distinct: { on } + }); + } + /** + * Creates an update query. + * + * Calling this method without `.where()` clause will update all rows in a table. The `.where()` clause specifies which rows should be updated. + * + * Use `.set()` method to specify which values to update. + * + * See docs: {@link https://orm.drizzle.team/docs/update} + * + * @param table The table to update. + * + * @example + * + * ```ts + * // Update all rows in the 'cars' table + * await db.update(cars).set({ color: 'red' }); + * + * // Update rows with filters and conditions + * await db.update(cars).set({ color: 'red' }).where(eq(cars.brand, 'BMW')); + * + * // Update with returning clause + * const updatedCar: Car[] = await db.update(cars) + * .set({ color: 'red' }) + * .where(eq(cars.id, 1)) + * .returning(); + * ``` + */ + update(table) { + return new PgUpdateBuilder(table, this.session, this.dialect); + } + /** + * Creates an insert query. + * + * Calling this method will create new rows in a table. Use `.values()` method to specify which values to insert. + * + * See docs: {@link https://orm.drizzle.team/docs/insert} + * + * @param table The table to insert into. + * + * @example + * + * ```ts + * // Insert one row + * await db.insert(cars).values({ brand: 'BMW' }); + * + * // Insert multiple rows + * await db.insert(cars).values([{ brand: 'BMW' }, { brand: 'Porsche' }]); + * + * // Insert with returning clause + * const insertedCar: Car[] = await db.insert(cars) + * .values({ brand: 'BMW' }) + * .returning(); + * ``` + */ + insert(table) { + return new PgInsertBuilder(table, this.session, this.dialect); + } + /** + * Creates a delete query. + * + * Calling this method without `.where()` clause will delete all rows in a table. The `.where()` clause specifies which rows should be deleted. + * + * See docs: {@link https://orm.drizzle.team/docs/delete} + * + * @param table The table to delete from. + * + * @example + * + * ```ts + * // Delete all rows in the 'cars' table + * await db.delete(cars); + * + * // Delete rows with filters and conditions + * await db.delete(cars).where(eq(cars.color, 'green')); + * + * // Delete with returning clause + * const deletedCar: Car[] = await db.delete(cars) + * .where(eq(cars.id, 1)) + * .returning(); + * ``` + */ + delete(table) { + return new PgDeleteBase(table, this.session, this.dialect); + } + refreshMaterializedView(view) { + return new PgRefreshMaterializedView(view, this.session, this.dialect); + } + authToken; + execute(query) { + const sequel = typeof query === "string" ? sql.raw(query) : query.getSQL(); + const builtQuery = this.dialect.sqlToQuery(sequel); + const prepared = this.session.prepareQuery( + builtQuery, + void 0, + void 0, + false + ); + return new PgRaw( + () => prepared.execute(void 0, this.authToken), + sequel, + builtQuery, + (result) => prepared.mapResult(result, true) + ); + } + transaction(transaction, config3) { + return this.session.transaction(transaction, config3); + } + }; + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/alias.js +var init_alias2 = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/alias.js"() { + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/checks.js +var CheckBuilder, Check; +var init_checks = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/checks.js"() { + init_entity(); + CheckBuilder = class { + constructor(name, value) { + this.name = name; + this.value = value; + } + static [entityKind] = "PgCheckBuilder"; + brand; + /** @internal */ + build(table) { + return new Check(table, this); + } + }; + Check = class { + constructor(table, builder) { + this.table = table; + this.name = builder.name; + this.value = builder.value; + } + static [entityKind] = "PgCheck"; + name; + value; + }; + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/indexes.js +function index(name) { + return new IndexBuilderOn(false, name); +} +function uniqueIndex(name) { + return new IndexBuilderOn(true, name); +} +var IndexBuilderOn, IndexBuilder, Index; +var init_indexes = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/indexes.js"() { + init_sql(); + init_entity(); + init_columns(); + IndexBuilderOn = class { + constructor(unique2, name) { + this.unique = unique2; + this.name = name; + } + static [entityKind] = "PgIndexBuilderOn"; + on(...columns) { + return new IndexBuilder( + columns.map((it) => { + if (is(it, SQL)) { + return it; + } + it = it; + const clonedIndexedColumn = new IndexedColumn(it.name, !!it.keyAsName, it.columnType, it.indexConfig); + it.indexConfig = JSON.parse(JSON.stringify(it.defaultConfig)); + return clonedIndexedColumn; + }), + this.unique, + false, + this.name + ); + } + onOnly(...columns) { + return new IndexBuilder( + columns.map((it) => { + if (is(it, SQL)) { + return it; + } + it = it; + const clonedIndexedColumn = new IndexedColumn(it.name, !!it.keyAsName, it.columnType, it.indexConfig); + it.indexConfig = it.defaultConfig; + return clonedIndexedColumn; + }), + this.unique, + true, + this.name + ); + } + /** + * Specify what index method to use. Choices are `btree`, `hash`, `gist`, `spgist`, `gin`, `brin`, or user-installed access methods like `bloom`. The default method is `btree. + * + * If you have the `pg_vector` extension installed in your database, you can use the `hnsw` and `ivfflat` options, which are predefined types. + * + * **You can always specify any string you want in the method, in case Drizzle doesn't have it natively in its types** + * + * @param method The name of the index method to be used + * @param columns + * @returns + */ + using(method, ...columns) { + return new IndexBuilder( + columns.map((it) => { + if (is(it, SQL)) { + return it; + } + it = it; + const clonedIndexedColumn = new IndexedColumn(it.name, !!it.keyAsName, it.columnType, it.indexConfig); + it.indexConfig = JSON.parse(JSON.stringify(it.defaultConfig)); + return clonedIndexedColumn; + }), + this.unique, + true, + this.name, + method + ); + } + }; + IndexBuilder = class { + static [entityKind] = "PgIndexBuilder"; + /** @internal */ + config; + constructor(columns, unique2, only, name, method = "btree") { + this.config = { + name, + columns, + unique: unique2, + only, + method + }; + } + concurrently() { + this.config.concurrently = true; + return this; + } + with(obj) { + this.config.with = obj; + return this; + } + where(condition) { + this.config.where = condition; + return this; + } + /** @internal */ + build(table) { + return new Index(this.config, table); + } + }; + Index = class { + static [entityKind] = "PgIndex"; + config; + constructor(config3, table) { + this.config = { ...config3, table }; + } + }; + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/policies.js +var PgPolicy; +var init_policies = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/policies.js"() { + init_entity(); + PgPolicy = class { + constructor(name, config3) { + this.name = name; + if (config3) { + this.as = config3.as; + this.for = config3.for; + this.to = config3.to; + this.using = config3.using; + this.withCheck = config3.withCheck; + } + } + static [entityKind] = "PgPolicy"; + as; + for; + to; + using; + withCheck; + /** @internal */ + _linkedTable; + link(table) { + this._linkedTable = table; + return this; + } + }; + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/roles.js +var PgRole; +var init_roles = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/roles.js"() { + init_entity(); + PgRole = class { + constructor(name, config3) { + this.name = name; + if (config3) { + this.createDb = config3.createDb; + this.createRole = config3.createRole; + this.inherit = config3.inherit; + } + } + static [entityKind] = "PgRole"; + /** @internal */ + _existing; + /** @internal */ + createDb; + /** @internal */ + createRole; + /** @internal */ + inherit; + existing() { + this._existing = true; + return this; + } + }; + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/sequence.js +function pgSequenceWithSchema(name, options, schema2) { + return new PgSequence(name, options, schema2); +} +var PgSequence; +var init_sequence = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/sequence.js"() { + init_entity(); + PgSequence = class { + constructor(seqName, seqOptions, schema2) { + this.seqName = seqName; + this.seqOptions = seqOptions; + this.schema = schema2; + } + static [entityKind] = "PgSequence"; + }; + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/view-common.js +var PgViewConfig; +var init_view_common2 = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/view-common.js"() { + PgViewConfig = /* @__PURE__ */ Symbol.for("drizzle:PgViewConfig"); + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/view.js +function pgViewWithSchema(name, selection, schema2) { + if (selection) { + return new ManualViewBuilder(name, selection, schema2); + } + return new ViewBuilder(name, schema2); +} +function pgMaterializedViewWithSchema(name, selection, schema2) { + if (selection) { + return new ManualMaterializedViewBuilder(name, selection, schema2); + } + return new MaterializedViewBuilder(name, schema2); +} +var DefaultViewBuilderCore, ViewBuilder, ManualViewBuilder, MaterializedViewBuilderCore, MaterializedViewBuilder, ManualMaterializedViewBuilder, PgView, PgMaterializedViewConfig, PgMaterializedView; +var init_view = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/view.js"() { + init_entity(); + init_selection_proxy(); + init_utils(); + init_query_builder2(); + init_table2(); + init_view_base(); + init_view_common2(); + DefaultViewBuilderCore = class { + constructor(name, schema2) { + this.name = name; + this.schema = schema2; + } + static [entityKind] = "PgDefaultViewBuilderCore"; + config = {}; + with(config3) { + this.config.with = config3; + return this; + } + }; + ViewBuilder = class extends DefaultViewBuilderCore { + static [entityKind] = "PgViewBuilder"; + as(qb) { + if (typeof qb === "function") { + qb = qb(new QueryBuilder()); + } + const selectionProxy = new SelectionProxyHandler({ + alias: this.name, + sqlBehavior: "error", + sqlAliasedBehavior: "alias", + replaceOriginalName: true + }); + const aliasedSelection = new Proxy(qb.getSelectedFields(), selectionProxy); + return new Proxy( + new PgView({ + pgConfig: this.config, + config: { + name: this.name, + schema: this.schema, + selectedFields: aliasedSelection, + query: qb.getSQL().inlineParams() + } + }), + selectionProxy + ); + } + }; + ManualViewBuilder = class extends DefaultViewBuilderCore { + static [entityKind] = "PgManualViewBuilder"; + columns; + constructor(name, columns, schema2) { + super(name, schema2); + this.columns = getTableColumns(pgTable(name, columns)); + } + existing() { + return new Proxy( + new PgView({ + pgConfig: void 0, + config: { + name: this.name, + schema: this.schema, + selectedFields: this.columns, + query: void 0 + } + }), + new SelectionProxyHandler({ + alias: this.name, + sqlBehavior: "error", + sqlAliasedBehavior: "alias", + replaceOriginalName: true + }) + ); + } + as(query) { + return new Proxy( + new PgView({ + pgConfig: this.config, + config: { + name: this.name, + schema: this.schema, + selectedFields: this.columns, + query: query.inlineParams() + } + }), + new SelectionProxyHandler({ + alias: this.name, + sqlBehavior: "error", + sqlAliasedBehavior: "alias", + replaceOriginalName: true + }) + ); + } + }; + MaterializedViewBuilderCore = class { + constructor(name, schema2) { + this.name = name; + this.schema = schema2; + } + static [entityKind] = "PgMaterializedViewBuilderCore"; + config = {}; + using(using) { + this.config.using = using; + return this; + } + with(config3) { + this.config.with = config3; + return this; + } + tablespace(tablespace) { + this.config.tablespace = tablespace; + return this; + } + withNoData() { + this.config.withNoData = true; + return this; + } + }; + MaterializedViewBuilder = class extends MaterializedViewBuilderCore { + static [entityKind] = "PgMaterializedViewBuilder"; + as(qb) { + if (typeof qb === "function") { + qb = qb(new QueryBuilder()); + } + const selectionProxy = new SelectionProxyHandler({ + alias: this.name, + sqlBehavior: "error", + sqlAliasedBehavior: "alias", + replaceOriginalName: true + }); + const aliasedSelection = new Proxy(qb.getSelectedFields(), selectionProxy); + return new Proxy( + new PgMaterializedView({ + pgConfig: { + with: this.config.with, + using: this.config.using, + tablespace: this.config.tablespace, + withNoData: this.config.withNoData + }, + config: { + name: this.name, + schema: this.schema, + selectedFields: aliasedSelection, + query: qb.getSQL().inlineParams() + } + }), + selectionProxy + ); + } + }; + ManualMaterializedViewBuilder = class extends MaterializedViewBuilderCore { + static [entityKind] = "PgManualMaterializedViewBuilder"; + columns; + constructor(name, columns, schema2) { + super(name, schema2); + this.columns = getTableColumns(pgTable(name, columns)); + } + existing() { + return new Proxy( + new PgMaterializedView({ + pgConfig: { + tablespace: this.config.tablespace, + using: this.config.using, + with: this.config.with, + withNoData: this.config.withNoData + }, + config: { + name: this.name, + schema: this.schema, + selectedFields: this.columns, + query: void 0 + } + }), + new SelectionProxyHandler({ + alias: this.name, + sqlBehavior: "error", + sqlAliasedBehavior: "alias", + replaceOriginalName: true + }) + ); + } + as(query) { + return new Proxy( + new PgMaterializedView({ + pgConfig: { + tablespace: this.config.tablespace, + using: this.config.using, + with: this.config.with, + withNoData: this.config.withNoData + }, + config: { + name: this.name, + schema: this.schema, + selectedFields: this.columns, + query: query.inlineParams() + } + }), + new SelectionProxyHandler({ + alias: this.name, + sqlBehavior: "error", + sqlAliasedBehavior: "alias", + replaceOriginalName: true + }) + ); + } + }; + PgView = class extends PgViewBase { + static [entityKind] = "PgView"; + [PgViewConfig]; + constructor({ pgConfig, config: config3 }) { + super(config3); + if (pgConfig) { + this[PgViewConfig] = { + with: pgConfig.with + }; + } + } + }; + PgMaterializedViewConfig = /* @__PURE__ */ Symbol.for("drizzle:PgMaterializedViewConfig"); + PgMaterializedView = class extends PgViewBase { + static [entityKind] = "PgMaterializedView"; + [PgMaterializedViewConfig]; + constructor({ pgConfig, config: config3 }) { + super(config3); + this[PgMaterializedViewConfig] = { + with: pgConfig?.with, + using: pgConfig?.using, + tablespace: pgConfig?.tablespace, + withNoData: pgConfig?.withNoData + }; + } + }; + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/schema.js +var PgSchema; +var init_schema = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/schema.js"() { + init_entity(); + init_sql(); + init_enum(); + init_sequence(); + init_table2(); + init_view(); + PgSchema = class { + constructor(schemaName) { + this.schemaName = schemaName; + } + static [entityKind] = "PgSchema"; + table = (name, columns, extraConfig) => { + return pgTableWithSchema(name, columns, extraConfig, this.schemaName); + }; + view = (name, columns) => { + return pgViewWithSchema(name, columns, this.schemaName); + }; + materializedView = (name, columns) => { + return pgMaterializedViewWithSchema(name, columns, this.schemaName); + }; + enum = (name, values2) => { + return pgEnumWithSchema(name, values2, this.schemaName); + }; + sequence = (name, options) => { + return pgSequenceWithSchema(name, options, this.schemaName); + }; + getSQL() { + return new SQL([sql.identifier(this.schemaName)]); + } + shouldOmitSQLParens() { + return true; + } + }; + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/session.js +var PgPreparedQuery, PgSession, PgTransaction; +var init_session = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/session.js"() { + init_entity(); + init_errors2(); + init_sql2(); + init_tracing(); + init_db(); + PgPreparedQuery = class { + constructor(query) { + this.query = query; + } + authToken; + getQuery() { + return this.query; + } + mapResult(response, _isFromBatch) { + return response; + } + /** @internal */ + setToken(token) { + this.authToken = token; + return this; + } + static [entityKind] = "PgPreparedQuery"; + /** @internal */ + joinsNotNullableMap; + }; + PgSession = class { + constructor(dialect) { + this.dialect = dialect; + } + static [entityKind] = "PgSession"; + /** @internal */ + execute(query, token) { + return tracer.startActiveSpan("drizzle.operation", () => { + const prepared = tracer.startActiveSpan("drizzle.prepareQuery", () => { + return this.prepareQuery( + this.dialect.sqlToQuery(query), + void 0, + void 0, + false + ); + }); + return prepared.setToken(token).execute(void 0, token); + }); + } + all(query) { + return this.prepareQuery( + this.dialect.sqlToQuery(query), + void 0, + void 0, + false + ).all(); + } + /** @internal */ + async count(sql22, token) { + const res = await this.execute(sql22, token); + return Number( + res[0]["count"] + ); + } + }; + PgTransaction = class extends PgDatabase { + constructor(dialect, session, schema2, nestedIndex = 0) { + super(dialect, session, schema2); + this.schema = schema2; + this.nestedIndex = nestedIndex; + } + static [entityKind] = "PgTransaction"; + rollback() { + throw new TransactionRollbackError(); + } + /** @internal */ + getTransactionConfigSQL(config3) { + const chunks = []; + if (config3.isolationLevel) { + chunks.push(`isolation level ${config3.isolationLevel}`); + } + if (config3.accessMode) { + chunks.push(config3.accessMode); + } + if (typeof config3.deferrable === "boolean") { + chunks.push(config3.deferrable ? "deferrable" : "not deferrable"); + } + return sql.raw(chunks.join(" ")); + } + setTransaction(config3) { + return this.session.execute(sql`set transaction ${this.getTransactionConfigSQL(config3)}`); + } + }; + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/subquery.js +var init_subquery2 = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/subquery.js"() { + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/utils.js +var init_utils3 = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/utils.js"() { + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/utils/index.js +var init_utils4 = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/utils/index.js"() { + init_array(); + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/index.js +var init_pg_core = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/index.js"() { + init_alias2(); + init_checks(); + init_columns(); + init_db(); + init_dialect(); + init_foreign_keys(); + init_indexes(); + init_policies(); + init_primary_keys(); + init_query_builders(); + init_roles(); + init_schema(); + init_sequence(); + init_session(); + init_subquery2(); + init_table2(); + init_unique_constraint(); + init_utils3(); + init_utils4(); + init_view_common2(); + init_view(); + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/postgres-js/session.js +var PostgresJsPreparedQuery, PostgresJsSession, PostgresJsTransaction; +var init_session2 = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/postgres-js/session.js"() { + init_entity(); + init_logger(); + init_pg_core(); + init_session(); + init_sql(); + init_tracing(); + init_utils(); + PostgresJsPreparedQuery = class extends PgPreparedQuery { + constructor(client2, queryString, params, logger4, fields, _isResponseInArrayMode, customResultMapper) { + super({ sql: queryString, params }); + this.client = client2; + this.queryString = queryString; + this.params = params; + this.logger = logger4; + this.fields = fields; + this._isResponseInArrayMode = _isResponseInArrayMode; + this.customResultMapper = customResultMapper; + } + static [entityKind] = "PostgresJsPreparedQuery"; + async execute(placeholderValues = {}) { + return tracer.startActiveSpan("drizzle.execute", async (span) => { + const params = fillPlaceholders(this.params, placeholderValues); + span?.setAttributes({ + "drizzle.query.text": this.queryString, + "drizzle.query.params": JSON.stringify(params) + }); + this.logger.logQuery(this.queryString, params); + const { fields, queryString: query, client: client2, joinsNotNullableMap, customResultMapper } = this; + if (!fields && !customResultMapper) { + return tracer.startActiveSpan("drizzle.driver.execute", () => { + return client2.unsafe(query, params); + }); + } + const rows = await tracer.startActiveSpan("drizzle.driver.execute", () => { + span?.setAttributes({ + "drizzle.query.text": query, + "drizzle.query.params": JSON.stringify(params) + }); + return client2.unsafe(query, params).values(); + }); + return tracer.startActiveSpan("drizzle.mapResponse", () => { + return customResultMapper ? customResultMapper(rows) : rows.map((row) => mapResultRow(fields, row, joinsNotNullableMap)); + }); + }); + } + all(placeholderValues = {}) { + return tracer.startActiveSpan("drizzle.execute", async (span) => { + const params = fillPlaceholders(this.params, placeholderValues); + span?.setAttributes({ + "drizzle.query.text": this.queryString, + "drizzle.query.params": JSON.stringify(params) + }); + this.logger.logQuery(this.queryString, params); + return tracer.startActiveSpan("drizzle.driver.execute", () => { + span?.setAttributes({ + "drizzle.query.text": this.queryString, + "drizzle.query.params": JSON.stringify(params) + }); + return this.client.unsafe(this.queryString, params); + }); + }); + } + /** @internal */ + isResponseInArrayMode() { + return this._isResponseInArrayMode; + } + }; + PostgresJsSession = class _PostgresJsSession extends PgSession { + constructor(client2, dialect, schema2, options = {}) { + super(dialect); + this.client = client2; + this.schema = schema2; + this.options = options; + this.logger = options.logger ?? new NoopLogger(); + } + static [entityKind] = "PostgresJsSession"; + logger; + prepareQuery(query, fields, name, isResponseInArrayMode, customResultMapper) { + return new PostgresJsPreparedQuery( + this.client, + query.sql, + query.params, + this.logger, + fields, + isResponseInArrayMode, + customResultMapper + ); + } + query(query, params) { + this.logger.logQuery(query, params); + return this.client.unsafe(query, params).values(); + } + queryObjects(query, params) { + return this.client.unsafe(query, params); + } + transaction(transaction, config3) { + return this.client.begin(async (client2) => { + const session = new _PostgresJsSession( + client2, + this.dialect, + this.schema, + this.options + ); + const tx = new PostgresJsTransaction(this.dialect, session, this.schema); + if (config3) { + await tx.setTransaction(config3); + } + return transaction(tx); + }); + } + }; + PostgresJsTransaction = class _PostgresJsTransaction extends PgTransaction { + constructor(dialect, session, schema2, nestedIndex = 0) { + super(dialect, session, schema2, nestedIndex); + this.session = session; + } + static [entityKind] = "PostgresJsTransaction"; + transaction(transaction) { + return this.session.client.savepoint((client2) => { + const session = new PostgresJsSession( + client2, + this.dialect, + this.schema, + this.session.options + ); + const tx = new _PostgresJsTransaction(this.dialect, session, this.schema); + return transaction(tx); + }); + } + }; + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/postgres-js/driver.js +function construct(client2, config3 = {}) { + const transparentParser = (val) => val; + for (const type of ["1184", "1082", "1083", "1114"]) { + client2.options.parsers[type] = transparentParser; + client2.options.serializers[type] = transparentParser; + } + client2.options.serializers["114"] = transparentParser; + client2.options.serializers["3802"] = transparentParser; + const dialect = new PgDialect({ casing: config3.casing }); + let logger4; + if (config3.logger === true) { + logger4 = new DefaultLogger(); + } else if (config3.logger !== false) { + logger4 = config3.logger; + } + let schema2; + if (config3.schema) { + const tablesConfig = extractTablesRelationalConfig( + config3.schema, + createTableRelationsHelpers + ); + schema2 = { + fullSchema: config3.schema, + schema: tablesConfig.tables, + tableNamesMap: tablesConfig.tableNamesMap + }; + } + const session = new PostgresJsSession(client2, dialect, schema2, { logger: logger4 }); + const db = new PostgresJsDatabase(dialect, session, schema2); + db.$client = client2; + return db; +} +function drizzle(...params) { + if (typeof params[0] === "string") { + const instance = src_default(params[0]); + return construct(instance, params[1]); + } + if (isConfig(params[0])) { + const { connection: connection2, client: client2, ...drizzleConfig } = params[0]; + if (client2) + return construct(client2, drizzleConfig); + if (typeof connection2 === "object" && connection2.url !== void 0) { + const { url: url2, ...config3 } = connection2; + const instance2 = src_default(url2, config3); + return construct(instance2, drizzleConfig); + } + const instance = src_default(connection2); + return construct(instance, drizzleConfig); + } + return construct(params[0], params[1]); +} +var PostgresJsDatabase; +var init_driver = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/postgres-js/driver.js"() { + init_src(); + init_entity(); + init_logger(); + init_db(); + init_dialect(); + init_relations(); + init_utils(); + init_session2(); + PostgresJsDatabase = class extends PgDatabase { + static [entityKind] = "PostgresJsDatabase"; + }; + ((drizzle2) => { + function mock(config3) { + return construct({ + options: { + parsers: {}, + serializers: {} + } + }, config3); + } + drizzle2.mock = mock; + })(drizzle || (drizzle = {})); + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/postgres-js/index.js +var init_postgres_js = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/postgres-js/index.js"() { + init_driver(); + init_session2(); + } +}); + +// packages/db/src/schema/companies.ts +var companies; +var init_companies = __esm({ + "packages/db/src/schema/companies.ts"() { + "use strict"; + init_pg_core(); + companies = pgTable( + "companies", + { + id: uuid("id").primaryKey().defaultRandom(), + name: text("name").notNull(), + description: text("description"), + status: text("status").notNull().default("active"), + pauseReason: text("pause_reason"), + pausedAt: timestamp("paused_at", { withTimezone: true }), + issuePrefix: text("issue_prefix").notNull().default("PAP"), + issueCounter: integer("issue_counter").notNull().default(0), + budgetMonthlyCents: integer("budget_monthly_cents").notNull().default(0), + spentMonthlyCents: integer("spent_monthly_cents").notNull().default(0), + requireBoardApprovalForNewAgents: boolean("require_board_approval_for_new_agents").notNull().default(true), + feedbackDataSharingEnabled: boolean("feedback_data_sharing_enabled").notNull().default(false), + feedbackDataSharingConsentAt: timestamp("feedback_data_sharing_consent_at", { withTimezone: true }), + feedbackDataSharingConsentByUserId: text("feedback_data_sharing_consent_by_user_id"), + feedbackDataSharingTermsVersion: text("feedback_data_sharing_terms_version"), + brandColor: text("brand_color"), + createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), + updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() + }, + (table) => ({ + issuePrefixUniqueIdx: uniqueIndex("companies_issue_prefix_idx").on(table.issuePrefix) + }) + ); + } +}); + +// packages/db/src/schema/agents.ts +var agents; +var init_agents = __esm({ + "packages/db/src/schema/agents.ts"() { + "use strict"; + init_pg_core(); + init_companies(); + agents = pgTable( + "agents", + { + id: uuid("id").primaryKey().defaultRandom(), + companyId: uuid("company_id").notNull().references(() => companies.id), + name: text("name").notNull(), + role: text("role").notNull().default("general"), + title: text("title"), + icon: text("icon"), + status: text("status").notNull().default("idle"), + reportsTo: uuid("reports_to").references(() => agents.id), + capabilities: text("capabilities"), + adapterType: text("adapter_type").notNull().default("process"), + adapterConfig: jsonb("adapter_config").$type().notNull().default({}), + runtimeConfig: jsonb("runtime_config").$type().notNull().default({}), + budgetMonthlyCents: integer("budget_monthly_cents").notNull().default(0), + spentMonthlyCents: integer("spent_monthly_cents").notNull().default(0), + pauseReason: text("pause_reason"), + pausedAt: timestamp("paused_at", { withTimezone: true }), + permissions: jsonb("permissions").$type().notNull().default({}), + lastHeartbeatAt: timestamp("last_heartbeat_at", { withTimezone: true }), + metadata: jsonb("metadata").$type(), + createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), + updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() + }, + (table) => ({ + companyStatusIdx: index("agents_company_status_idx").on(table.companyId, table.status), + companyReportsToIdx: index("agents_company_reports_to_idx").on(table.companyId, table.reportsTo) + }) + ); + } +}); + +// packages/db/src/schema/assets.ts +var assets; +var init_assets = __esm({ + "packages/db/src/schema/assets.ts"() { + "use strict"; + init_pg_core(); + init_companies(); + init_agents(); + assets = pgTable( + "assets", + { + id: uuid("id").primaryKey().defaultRandom(), + companyId: uuid("company_id").notNull().references(() => companies.id), + provider: text("provider").notNull(), + objectKey: text("object_key").notNull(), + contentType: text("content_type").notNull(), + byteSize: integer("byte_size").notNull(), + sha256: text("sha256").notNull(), + originalFilename: text("original_filename"), + createdByAgentId: uuid("created_by_agent_id").references(() => agents.id), + createdByUserId: text("created_by_user_id"), + createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), + updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() + }, + (table) => ({ + companyCreatedIdx: index("assets_company_created_idx").on(table.companyId, table.createdAt), + companyProviderIdx: index("assets_company_provider_idx").on(table.companyId, table.provider), + companyObjectKeyUq: uniqueIndex("assets_company_object_key_uq").on(table.companyId, table.objectKey) + }) + ); + } +}); + +// packages/db/src/schema/company_logos.ts +var companyLogos; +var init_company_logos = __esm({ + "packages/db/src/schema/company_logos.ts"() { + "use strict"; + init_pg_core(); + init_companies(); + init_assets(); + companyLogos = pgTable( + "company_logos", + { + id: uuid("id").primaryKey().defaultRandom(), + companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }), + assetId: uuid("asset_id").notNull().references(() => assets.id, { onDelete: "cascade" }), + createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), + updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() + }, + (table) => ({ + companyUq: uniqueIndex("company_logos_company_uq").on(table.companyId), + assetUq: uniqueIndex("company_logos_asset_uq").on(table.assetId) + }) + ); + } +}); + +// packages/db/src/schema/auth.ts +var authUsers, authSessions, authAccounts, authVerifications; +var init_auth = __esm({ + "packages/db/src/schema/auth.ts"() { + "use strict"; + init_pg_core(); + authUsers = pgTable("user", { + id: text("id").primaryKey(), + name: text("name").notNull(), + email: text("email").notNull(), + emailVerified: boolean("email_verified").notNull().default(false), + image: text("image"), + createdAt: timestamp("created_at", { withTimezone: true }).notNull(), + updatedAt: timestamp("updated_at", { withTimezone: true }).notNull() + }); + authSessions = pgTable("session", { + id: text("id").primaryKey(), + expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(), + token: text("token").notNull(), + createdAt: timestamp("created_at", { withTimezone: true }).notNull(), + updatedAt: timestamp("updated_at", { withTimezone: true }).notNull(), + ipAddress: text("ip_address"), + userAgent: text("user_agent"), + userId: text("user_id").notNull().references(() => authUsers.id, { onDelete: "cascade" }) + }); + authAccounts = pgTable("account", { + id: text("id").primaryKey(), + accountId: text("account_id").notNull(), + providerId: text("provider_id").notNull(), + userId: text("user_id").notNull().references(() => authUsers.id, { onDelete: "cascade" }), + accessToken: text("access_token"), + refreshToken: text("refresh_token"), + idToken: text("id_token"), + accessTokenExpiresAt: timestamp("access_token_expires_at", { withTimezone: true }), + refreshTokenExpiresAt: timestamp("refresh_token_expires_at", { withTimezone: true }), + scope: text("scope"), + password: text("password"), + createdAt: timestamp("created_at", { withTimezone: true }).notNull(), + updatedAt: timestamp("updated_at", { withTimezone: true }).notNull() + }); + authVerifications = pgTable("verification", { + id: text("id").primaryKey(), + identifier: text("identifier").notNull(), + value: text("value").notNull(), + expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(), + createdAt: timestamp("created_at", { withTimezone: true }), + updatedAt: timestamp("updated_at", { withTimezone: true }) + }); + } +}); + +// packages/db/src/schema/instance_settings.ts +var instanceSettings; +var init_instance_settings = __esm({ + "packages/db/src/schema/instance_settings.ts"() { + "use strict"; + init_pg_core(); + instanceSettings = pgTable( + "instance_settings", + { + id: uuid("id").primaryKey().defaultRandom(), + singletonKey: text("singleton_key").notNull().default("default"), + general: jsonb("general").$type().notNull().default({}), + experimental: jsonb("experimental").$type().notNull().default({}), + createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), + updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() + }, + (table) => ({ + singletonKeyIdx: uniqueIndex("instance_settings_singleton_key_idx").on(table.singletonKey) + }) + ); + } +}); + +// packages/db/src/schema/instance_user_roles.ts +var instanceUserRoles; +var init_instance_user_roles = __esm({ + "packages/db/src/schema/instance_user_roles.ts"() { + "use strict"; + init_pg_core(); + instanceUserRoles = pgTable( + "instance_user_roles", + { + id: uuid("id").primaryKey().defaultRandom(), + userId: text("user_id").notNull(), + role: text("role").notNull().default("instance_admin"), + createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), + updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() + }, + (table) => ({ + userRoleUniqueIdx: uniqueIndex("instance_user_roles_user_role_unique_idx").on(table.userId, table.role), + roleIdx: index("instance_user_roles_role_idx").on(table.role) + }) + ); + } +}); + +// packages/db/src/schema/user_sidebar_preferences.ts +var userSidebarPreferences; +var init_user_sidebar_preferences = __esm({ + "packages/db/src/schema/user_sidebar_preferences.ts"() { + "use strict"; + init_pg_core(); + userSidebarPreferences = pgTable( + "user_sidebar_preferences", + { + id: uuid("id").primaryKey().defaultRandom(), + userId: text("user_id").notNull(), + companyOrder: jsonb("company_order").$type().notNull().default([]), + createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), + updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() + }, + (table) => ({ + userUq: uniqueIndex("user_sidebar_preferences_user_uq").on(table.userId) + }) + ); + } +}); + +// packages/db/src/schema/board_api_keys.ts +var boardApiKeys; +var init_board_api_keys = __esm({ + "packages/db/src/schema/board_api_keys.ts"() { + "use strict"; + init_pg_core(); + init_auth(); + boardApiKeys = pgTable( + "board_api_keys", + { + id: uuid("id").primaryKey().defaultRandom(), + userId: text("user_id").notNull().references(() => authUsers.id, { onDelete: "cascade" }), + name: text("name").notNull(), + keyHash: text("key_hash").notNull(), + lastUsedAt: timestamp("last_used_at", { withTimezone: true }), + revokedAt: timestamp("revoked_at", { withTimezone: true }), + expiresAt: timestamp("expires_at", { withTimezone: true }), + createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow() + }, + (table) => ({ + keyHashIdx: uniqueIndex("board_api_keys_key_hash_idx").on(table.keyHash), + userIdx: index("board_api_keys_user_idx").on(table.userId) + }) + ); + } +}); + +// packages/db/src/schema/cli_auth_challenges.ts +var cliAuthChallenges; +var init_cli_auth_challenges = __esm({ + "packages/db/src/schema/cli_auth_challenges.ts"() { + "use strict"; + init_pg_core(); + init_auth(); + init_companies(); + init_board_api_keys(); + cliAuthChallenges = pgTable( + "cli_auth_challenges", + { + id: uuid("id").primaryKey().defaultRandom(), + secretHash: text("secret_hash").notNull(), + command: text("command").notNull(), + clientName: text("client_name"), + requestedAccess: text("requested_access").notNull().default("board"), + requestedCompanyId: uuid("requested_company_id").references(() => companies.id, { onDelete: "set null" }), + pendingKeyHash: text("pending_key_hash").notNull(), + pendingKeyName: text("pending_key_name").notNull(), + approvedByUserId: text("approved_by_user_id").references(() => authUsers.id, { onDelete: "set null" }), + boardApiKeyId: uuid("board_api_key_id").references(() => boardApiKeys.id, { onDelete: "set null" }), + approvedAt: timestamp("approved_at", { withTimezone: true }), + cancelledAt: timestamp("cancelled_at", { withTimezone: true }), + expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(), + createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), + updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() + }, + (table) => ({ + secretHashIdx: index("cli_auth_challenges_secret_hash_idx").on(table.secretHash), + approvedByIdx: index("cli_auth_challenges_approved_by_idx").on(table.approvedByUserId), + requestedCompanyIdx: index("cli_auth_challenges_requested_company_idx").on(table.requestedCompanyId) + }) + ); + } +}); + +// packages/db/src/schema/company_memberships.ts +var companyMemberships; +var init_company_memberships = __esm({ + "packages/db/src/schema/company_memberships.ts"() { + "use strict"; + init_pg_core(); + init_companies(); + companyMemberships = pgTable( + "company_memberships", + { + id: uuid("id").primaryKey().defaultRandom(), + companyId: uuid("company_id").notNull().references(() => companies.id), + principalType: text("principal_type").notNull(), + principalId: text("principal_id").notNull(), + status: text("status").notNull().default("active"), + membershipRole: text("membership_role"), + createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), + updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() + }, + (table) => ({ + companyPrincipalUniqueIdx: uniqueIndex("company_memberships_company_principal_unique_idx").on( + table.companyId, + table.principalType, + table.principalId + ), + principalStatusIdx: index("company_memberships_principal_status_idx").on( + table.principalType, + table.principalId, + table.status + ), + companyStatusIdx: index("company_memberships_company_status_idx").on(table.companyId, table.status) + }) + ); + } +}); + +// packages/db/src/schema/company_user_sidebar_preferences.ts +var companyUserSidebarPreferences; +var init_company_user_sidebar_preferences = __esm({ + "packages/db/src/schema/company_user_sidebar_preferences.ts"() { + "use strict"; + init_pg_core(); + init_companies(); + companyUserSidebarPreferences = pgTable( + "company_user_sidebar_preferences", + { + id: uuid("id").primaryKey().defaultRandom(), + companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }), + userId: text("user_id").notNull(), + projectOrder: jsonb("project_order").$type().notNull().default([]), + createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), + updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() + }, + (table) => ({ + companyIdx: index("company_user_sidebar_preferences_company_idx").on(table.companyId), + userIdx: index("company_user_sidebar_preferences_user_idx").on(table.userId), + companyUserUq: uniqueIndex("company_user_sidebar_preferences_company_user_uq").on( + table.companyId, + table.userId + ) + }) + ); + } +}); + +// packages/db/src/schema/principal_permission_grants.ts +var principalPermissionGrants; +var init_principal_permission_grants = __esm({ + "packages/db/src/schema/principal_permission_grants.ts"() { + "use strict"; + init_pg_core(); + init_companies(); + principalPermissionGrants = pgTable( + "principal_permission_grants", + { + id: uuid("id").primaryKey().defaultRandom(), + companyId: uuid("company_id").notNull().references(() => companies.id), + principalType: text("principal_type").notNull(), + principalId: text("principal_id").notNull(), + permissionKey: text("permission_key").notNull(), + scope: jsonb("scope").$type(), + grantedByUserId: text("granted_by_user_id"), + createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), + updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() + }, + (table) => ({ + uniqueGrantIdx: uniqueIndex("principal_permission_grants_unique_idx").on( + table.companyId, + table.principalType, + table.principalId, + table.permissionKey + ), + companyPermissionIdx: index("principal_permission_grants_company_permission_idx").on( + table.companyId, + table.permissionKey + ) + }) + ); + } +}); + +// packages/db/src/schema/invites.ts +var invites; +var init_invites = __esm({ + "packages/db/src/schema/invites.ts"() { + "use strict"; + init_pg_core(); + init_companies(); + invites = pgTable( + "invites", + { + id: uuid("id").primaryKey().defaultRandom(), + companyId: uuid("company_id").references(() => companies.id), + inviteType: text("invite_type").notNull().default("company_join"), + tokenHash: text("token_hash").notNull(), + allowedJoinTypes: text("allowed_join_types").notNull().default("both"), + defaultsPayload: jsonb("defaults_payload").$type(), + expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(), + invitedByUserId: text("invited_by_user_id"), + revokedAt: timestamp("revoked_at", { withTimezone: true }), + acceptedAt: timestamp("accepted_at", { withTimezone: true }), + createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), + updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() + }, + (table) => ({ + tokenHashUniqueIdx: uniqueIndex("invites_token_hash_unique_idx").on(table.tokenHash), + companyInviteStateIdx: index("invites_company_invite_state_idx").on( + table.companyId, + table.inviteType, + table.revokedAt, + table.expiresAt + ) + }) + ); + } +}); + +// packages/db/src/schema/join_requests.ts +var joinRequests; +var init_join_requests = __esm({ + "packages/db/src/schema/join_requests.ts"() { + "use strict"; + init_pg_core(); + init_companies(); + init_invites(); + init_agents(); + joinRequests = pgTable( + "join_requests", + { + id: uuid("id").primaryKey().defaultRandom(), + inviteId: uuid("invite_id").notNull().references(() => invites.id), + companyId: uuid("company_id").notNull().references(() => companies.id), + requestType: text("request_type").notNull(), + status: text("status").notNull().default("pending_approval"), + requestIp: text("request_ip").notNull(), + requestingUserId: text("requesting_user_id"), + requestEmailSnapshot: text("request_email_snapshot"), + agentName: text("agent_name"), + adapterType: text("adapter_type"), + capabilities: text("capabilities"), + agentDefaultsPayload: jsonb("agent_defaults_payload").$type(), + claimSecretHash: text("claim_secret_hash"), + claimSecretExpiresAt: timestamp("claim_secret_expires_at", { withTimezone: true }), + claimSecretConsumedAt: timestamp("claim_secret_consumed_at", { withTimezone: true }), + createdAgentId: uuid("created_agent_id").references(() => agents.id), + approvedByUserId: text("approved_by_user_id"), + approvedAt: timestamp("approved_at", { withTimezone: true }), + rejectedByUserId: text("rejected_by_user_id"), + rejectedAt: timestamp("rejected_at", { withTimezone: true }), + createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), + updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() + }, + (table) => ({ + inviteUniqueIdx: uniqueIndex("join_requests_invite_unique_idx").on(table.inviteId), + companyStatusTypeCreatedIdx: index("join_requests_company_status_type_created_idx").on( + table.companyId, + table.status, + table.requestType, + table.createdAt + ) + }) + ); + } +}); + +// packages/db/src/schema/budget_policies.ts +var budgetPolicies; +var init_budget_policies = __esm({ + "packages/db/src/schema/budget_policies.ts"() { + "use strict"; + init_pg_core(); + init_companies(); + budgetPolicies = pgTable( + "budget_policies", + { + id: uuid("id").primaryKey().defaultRandom(), + companyId: uuid("company_id").notNull().references(() => companies.id), + scopeType: text("scope_type").notNull(), + scopeId: uuid("scope_id").notNull(), + metric: text("metric").notNull().default("billed_cents"), + windowKind: text("window_kind").notNull(), + amount: integer("amount").notNull().default(0), + warnPercent: integer("warn_percent").notNull().default(80), + hardStopEnabled: boolean("hard_stop_enabled").notNull().default(true), + notifyEnabled: boolean("notify_enabled").notNull().default(true), + isActive: boolean("is_active").notNull().default(true), + createdByUserId: text("created_by_user_id"), + updatedByUserId: text("updated_by_user_id"), + createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), + updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() + }, + (table) => ({ + companyScopeActiveIdx: index("budget_policies_company_scope_active_idx").on( + table.companyId, + table.scopeType, + table.scopeId, + table.isActive + ), + companyWindowIdx: index("budget_policies_company_window_idx").on( + table.companyId, + table.windowKind, + table.metric + ), + companyScopeMetricUniqueIdx: uniqueIndex("budget_policies_company_scope_metric_unique_idx").on( + table.companyId, + table.scopeType, + table.scopeId, + table.metric, + table.windowKind + ) + }) + ); + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/expressions.js +var init_expressions2 = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/expressions.js"() { + init_expressions(); + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/operations.js +var init_operations = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/operations.js"() { + } +}); + +// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/index.js +var init_drizzle_orm = __esm({ + "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/index.js"() { + init_alias(); + init_column_builder(); + init_column(); + init_entity(); + init_errors2(); + init_expressions2(); + init_logger(); + init_operations(); + init_query_promise(); + init_relations(); + init_sql2(); + init_subquery(); + init_table(); + init_utils(); + init_view_common(); + } +}); + +// packages/db/src/schema/approvals.ts +var approvals; +var init_approvals = __esm({ + "packages/db/src/schema/approvals.ts"() { + "use strict"; + init_pg_core(); + init_companies(); + init_agents(); + approvals = pgTable( + "approvals", + { + id: uuid("id").primaryKey().defaultRandom(), + companyId: uuid("company_id").notNull().references(() => companies.id), + type: text("type").notNull(), + requestedByAgentId: uuid("requested_by_agent_id").references(() => agents.id), + requestedByUserId: text("requested_by_user_id"), + status: text("status").notNull().default("pending"), + payload: jsonb("payload").$type().notNull(), + decisionNote: text("decision_note"), + decidedByUserId: text("decided_by_user_id"), + decidedAt: timestamp("decided_at", { withTimezone: true }), + createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), + updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() + }, + (table) => ({ + companyStatusTypeIdx: index("approvals_company_status_type_idx").on( + table.companyId, + table.status, + table.type + ) + }) + ); + } +}); + +// packages/db/src/schema/budget_incidents.ts +var budgetIncidents; +var init_budget_incidents = __esm({ + "packages/db/src/schema/budget_incidents.ts"() { + "use strict"; + init_drizzle_orm(); + init_pg_core(); + init_approvals(); + init_budget_policies(); + init_companies(); + budgetIncidents = pgTable( + "budget_incidents", + { + id: uuid("id").primaryKey().defaultRandom(), + companyId: uuid("company_id").notNull().references(() => companies.id), + policyId: uuid("policy_id").notNull().references(() => budgetPolicies.id), + scopeType: text("scope_type").notNull(), + scopeId: uuid("scope_id").notNull(), + metric: text("metric").notNull(), + windowKind: text("window_kind").notNull(), + windowStart: timestamp("window_start", { withTimezone: true }).notNull(), + windowEnd: timestamp("window_end", { withTimezone: true }).notNull(), + thresholdType: text("threshold_type").notNull(), + amountLimit: integer("amount_limit").notNull(), + amountObserved: integer("amount_observed").notNull(), + status: text("status").notNull().default("open"), + approvalId: uuid("approval_id").references(() => approvals.id), + resolvedAt: timestamp("resolved_at", { withTimezone: true }), + createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), + updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() + }, + (table) => ({ + companyStatusIdx: index("budget_incidents_company_status_idx").on(table.companyId, table.status), + companyScopeIdx: index("budget_incidents_company_scope_idx").on( + table.companyId, + table.scopeType, + table.scopeId, + table.status + ), + policyWindowIdx: uniqueIndex("budget_incidents_policy_window_threshold_idx").on( + table.policyId, + table.windowStart, + table.thresholdType + ).where(sql`${table.status} <> 'dismissed'`) + }) + ); + } +}); + +// packages/db/src/schema/agent_config_revisions.ts +var agentConfigRevisions; +var init_agent_config_revisions = __esm({ + "packages/db/src/schema/agent_config_revisions.ts"() { + "use strict"; + init_pg_core(); + init_companies(); + init_agents(); + agentConfigRevisions = pgTable( + "agent_config_revisions", + { + id: uuid("id").primaryKey().defaultRandom(), + companyId: uuid("company_id").notNull().references(() => companies.id), + agentId: uuid("agent_id").notNull().references(() => agents.id, { onDelete: "cascade" }), + createdByAgentId: uuid("created_by_agent_id").references(() => agents.id, { onDelete: "set null" }), + createdByUserId: text("created_by_user_id"), + source: text("source").notNull().default("patch"), + rolledBackFromRevisionId: uuid("rolled_back_from_revision_id"), + changedKeys: jsonb("changed_keys").$type().notNull().default([]), + beforeConfig: jsonb("before_config").$type().notNull(), + afterConfig: jsonb("after_config").$type().notNull(), + createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow() + }, + (table) => ({ + companyAgentCreatedIdx: index("agent_config_revisions_company_agent_created_idx").on( + table.companyId, + table.agentId, + table.createdAt + ), + agentCreatedIdx: index("agent_config_revisions_agent_created_idx").on(table.agentId, table.createdAt) + }) + ); + } +}); + +// packages/db/src/schema/agent_api_keys.ts +var agentApiKeys; +var init_agent_api_keys = __esm({ + "packages/db/src/schema/agent_api_keys.ts"() { + "use strict"; + init_pg_core(); + init_agents(); + init_companies(); + agentApiKeys = pgTable( + "agent_api_keys", + { + id: uuid("id").primaryKey().defaultRandom(), + agentId: uuid("agent_id").notNull().references(() => agents.id), + companyId: uuid("company_id").notNull().references(() => companies.id), + name: text("name").notNull(), + keyHash: text("key_hash").notNull(), + lastUsedAt: timestamp("last_used_at", { withTimezone: true }), + revokedAt: timestamp("revoked_at", { withTimezone: true }), + createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow() + }, + (table) => ({ + keyHashIdx: index("agent_api_keys_key_hash_idx").on(table.keyHash), + companyAgentIdx: index("agent_api_keys_company_agent_idx").on(table.companyId, table.agentId) + }) + ); + } +}); + +// packages/db/src/schema/agent_runtime_state.ts +var agentRuntimeState; +var init_agent_runtime_state = __esm({ + "packages/db/src/schema/agent_runtime_state.ts"() { + "use strict"; + init_pg_core(); + init_agents(); + init_companies(); + agentRuntimeState = pgTable( + "agent_runtime_state", + { + agentId: uuid("agent_id").primaryKey().references(() => agents.id), + companyId: uuid("company_id").notNull().references(() => companies.id), + adapterType: text("adapter_type").notNull(), + sessionId: text("session_id"), + stateJson: jsonb("state_json").$type().notNull().default({}), + lastRunId: uuid("last_run_id"), + lastRunStatus: text("last_run_status"), + totalInputTokens: bigint("total_input_tokens", { mode: "number" }).notNull().default(0), + totalOutputTokens: bigint("total_output_tokens", { mode: "number" }).notNull().default(0), + totalCachedInputTokens: bigint("total_cached_input_tokens", { mode: "number" }).notNull().default(0), + totalCostCents: bigint("total_cost_cents", { mode: "number" }).notNull().default(0), + lastError: text("last_error"), + createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), + updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() + }, + (table) => ({ + companyAgentIdx: index("agent_runtime_state_company_agent_idx").on(table.companyId, table.agentId), + companyUpdatedIdx: index("agent_runtime_state_company_updated_idx").on(table.companyId, table.updatedAt) + }) + ); + } +}); + +// packages/db/src/schema/agent_wakeup_requests.ts +var agentWakeupRequests; +var init_agent_wakeup_requests = __esm({ + "packages/db/src/schema/agent_wakeup_requests.ts"() { + "use strict"; + init_pg_core(); + init_companies(); + init_agents(); + agentWakeupRequests = pgTable( + "agent_wakeup_requests", + { + id: uuid("id").primaryKey().defaultRandom(), + companyId: uuid("company_id").notNull().references(() => companies.id), + agentId: uuid("agent_id").notNull().references(() => agents.id), + source: text("source").notNull(), + triggerDetail: text("trigger_detail"), + reason: text("reason"), + payload: jsonb("payload").$type(), + status: text("status").notNull().default("queued"), + coalescedCount: integer("coalesced_count").notNull().default(0), + requestedByActorType: text("requested_by_actor_type"), + requestedByActorId: text("requested_by_actor_id"), + idempotencyKey: text("idempotency_key"), + runId: uuid("run_id"), + requestedAt: timestamp("requested_at", { withTimezone: true }).notNull().defaultNow(), + claimedAt: timestamp("claimed_at", { withTimezone: true }), + finishedAt: timestamp("finished_at", { withTimezone: true }), + error: text("error"), + createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), + updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() + }, + (table) => ({ + companyAgentStatusIdx: index("agent_wakeup_requests_company_agent_status_idx").on( + table.companyId, + table.agentId, + table.status + ), + companyRequestedIdx: index("agent_wakeup_requests_company_requested_idx").on( + table.companyId, + table.requestedAt + ), + agentRequestedIdx: index("agent_wakeup_requests_agent_requested_idx").on(table.agentId, table.requestedAt) + }) + ); + } +}); + +// packages/db/src/schema/heartbeat_runs.ts +var heartbeatRuns; +var init_heartbeat_runs = __esm({ + "packages/db/src/schema/heartbeat_runs.ts"() { + "use strict"; + init_pg_core(); + init_companies(); + init_agents(); + init_agent_wakeup_requests(); + heartbeatRuns = pgTable( + "heartbeat_runs", + { + id: uuid("id").primaryKey().defaultRandom(), + companyId: uuid("company_id").notNull().references(() => companies.id), + agentId: uuid("agent_id").notNull().references(() => agents.id), + invocationSource: text("invocation_source").notNull().default("on_demand"), + triggerDetail: text("trigger_detail"), + status: text("status").notNull().default("queued"), + startedAt: timestamp("started_at", { withTimezone: true }), + finishedAt: timestamp("finished_at", { withTimezone: true }), + error: text("error"), + wakeupRequestId: uuid("wakeup_request_id").references(() => agentWakeupRequests.id), + exitCode: integer("exit_code"), + signal: text("signal"), + usageJson: jsonb("usage_json").$type(), + resultJson: jsonb("result_json").$type(), + sessionIdBefore: text("session_id_before"), + sessionIdAfter: text("session_id_after"), + logStore: text("log_store"), + logRef: text("log_ref"), + logBytes: bigint("log_bytes", { mode: "number" }), + logSha256: text("log_sha256"), + logCompressed: boolean("log_compressed").notNull().default(false), + stdoutExcerpt: text("stdout_excerpt"), + stderrExcerpt: text("stderr_excerpt"), + errorCode: text("error_code"), + externalRunId: text("external_run_id"), + processPid: integer("process_pid"), + processGroupId: integer("process_group_id"), + processStartedAt: timestamp("process_started_at", { withTimezone: true }), + retryOfRunId: uuid("retry_of_run_id").references(() => heartbeatRuns.id, { + onDelete: "set null" + }), + processLossRetryCount: integer("process_loss_retry_count").notNull().default(0), + issueCommentStatus: text("issue_comment_status").notNull().default("not_applicable"), + issueCommentSatisfiedByCommentId: uuid("issue_comment_satisfied_by_comment_id"), + issueCommentRetryQueuedAt: timestamp("issue_comment_retry_queued_at", { withTimezone: true }), + contextSnapshot: jsonb("context_snapshot").$type(), + createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), + updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() + }, + (table) => ({ + companyAgentStartedIdx: index("heartbeat_runs_company_agent_started_idx").on( + table.companyId, + table.agentId, + table.startedAt + ) + }) + ); + } +}); + +// packages/db/src/schema/agent_task_sessions.ts +var agentTaskSessions; +var init_agent_task_sessions = __esm({ + "packages/db/src/schema/agent_task_sessions.ts"() { + "use strict"; + init_pg_core(); + init_companies(); + init_agents(); + init_heartbeat_runs(); + agentTaskSessions = pgTable( + "agent_task_sessions", + { + id: uuid("id").primaryKey().defaultRandom(), + companyId: uuid("company_id").notNull().references(() => companies.id), + agentId: uuid("agent_id").notNull().references(() => agents.id), + adapterType: text("adapter_type").notNull(), + taskKey: text("task_key").notNull(), + sessionParamsJson: jsonb("session_params_json").$type(), + sessionDisplayId: text("session_display_id"), + lastRunId: uuid("last_run_id").references(() => heartbeatRuns.id), + lastError: text("last_error"), + createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), + updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() + }, + (table) => ({ + companyAgentTaskUniqueIdx: uniqueIndex("agent_task_sessions_company_agent_adapter_task_uniq").on( + table.companyId, + table.agentId, + table.adapterType, + table.taskKey + ), + companyAgentUpdatedIdx: index("agent_task_sessions_company_agent_updated_idx").on( + table.companyId, + table.agentId, + table.updatedAt + ), + companyTaskUpdatedIdx: index("agent_task_sessions_company_task_updated_idx").on( + table.companyId, + table.taskKey, + table.updatedAt + ) + }) + ); + } +}); + +// packages/db/src/schema/goals.ts +var goals; +var init_goals = __esm({ + "packages/db/src/schema/goals.ts"() { + "use strict"; + init_pg_core(); + init_agents(); + init_companies(); + goals = pgTable( + "goals", + { + id: uuid("id").primaryKey().defaultRandom(), + companyId: uuid("company_id").notNull().references(() => companies.id), + title: text("title").notNull(), + description: text("description"), + level: text("level").notNull().default("task"), + status: text("status").notNull().default("planned"), + parentId: uuid("parent_id").references(() => goals.id), + ownerAgentId: uuid("owner_agent_id").references(() => agents.id), + createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), + updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() + }, + (table) => ({ + companyIdx: index("goals_company_idx").on(table.companyId) + }) + ); + } +}); + +// packages/db/src/schema/projects.ts +var projects; +var init_projects = __esm({ + "packages/db/src/schema/projects.ts"() { + "use strict"; + init_pg_core(); + init_companies(); + init_goals(); + init_agents(); + projects = pgTable( + "projects", + { + id: uuid("id").primaryKey().defaultRandom(), + companyId: uuid("company_id").notNull().references(() => companies.id), + goalId: uuid("goal_id").references(() => goals.id), + name: text("name").notNull(), + description: text("description"), + status: text("status").notNull().default("backlog"), + leadAgentId: uuid("lead_agent_id").references(() => agents.id), + targetDate: date("target_date"), + color: text("color"), + env: jsonb("env").$type(), + pauseReason: text("pause_reason"), + pausedAt: timestamp("paused_at", { withTimezone: true }), + executionWorkspacePolicy: jsonb("execution_workspace_policy").$type(), + archivedAt: timestamp("archived_at", { withTimezone: true }), + createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), + updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() + }, + (table) => ({ + companyIdx: index("projects_company_idx").on(table.companyId) + }) + ); + } +}); + +// packages/db/src/schema/project_workspaces.ts +var projectWorkspaces; +var init_project_workspaces = __esm({ + "packages/db/src/schema/project_workspaces.ts"() { + "use strict"; + init_pg_core(); + init_companies(); + init_projects(); + projectWorkspaces = pgTable( + "project_workspaces", + { + id: uuid("id").primaryKey().defaultRandom(), + companyId: uuid("company_id").notNull().references(() => companies.id), + projectId: uuid("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }), + name: text("name").notNull(), + sourceType: text("source_type").notNull().default("local_path"), + cwd: text("cwd"), + repoUrl: text("repo_url"), + repoRef: text("repo_ref"), + defaultRef: text("default_ref"), + visibility: text("visibility").notNull().default("default"), + setupCommand: text("setup_command"), + cleanupCommand: text("cleanup_command"), + remoteProvider: text("remote_provider"), + remoteWorkspaceRef: text("remote_workspace_ref"), + sharedWorkspaceKey: text("shared_workspace_key"), + metadata: jsonb("metadata").$type(), + isPrimary: boolean("is_primary").notNull().default(false), + createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), + updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() + }, + (table) => ({ + companyProjectIdx: index("project_workspaces_company_project_idx").on(table.companyId, table.projectId), + projectPrimaryIdx: index("project_workspaces_project_primary_idx").on(table.projectId, table.isPrimary), + projectSourceTypeIdx: index("project_workspaces_project_source_type_idx").on(table.projectId, table.sourceType), + companySharedKeyIdx: index("project_workspaces_company_shared_key_idx").on(table.companyId, table.sharedWorkspaceKey), + projectRemoteRefIdx: uniqueIndex("project_workspaces_project_remote_ref_idx").on(table.projectId, table.remoteProvider, table.remoteWorkspaceRef) + }) + ); + } +}); + +// packages/db/src/schema/issues.ts +var issues; +var init_issues = __esm({ + "packages/db/src/schema/issues.ts"() { + "use strict"; + init_drizzle_orm(); + init_pg_core(); + init_agents(); + init_projects(); + init_goals(); + init_companies(); + init_heartbeat_runs(); + init_project_workspaces(); + init_execution_workspaces(); + issues = pgTable( + "issues", + { + id: uuid("id").primaryKey().defaultRandom(), + companyId: uuid("company_id").notNull().references(() => companies.id), + projectId: uuid("project_id").references(() => projects.id), + projectWorkspaceId: uuid("project_workspace_id").references(() => projectWorkspaces.id, { onDelete: "set null" }), + goalId: uuid("goal_id").references(() => goals.id), + parentId: uuid("parent_id").references(() => issues.id), + title: text("title").notNull(), + description: text("description"), + status: text("status").notNull().default("backlog"), + priority: text("priority").notNull().default("medium"), + assigneeAgentId: uuid("assignee_agent_id").references(() => agents.id), + assigneeUserId: text("assignee_user_id"), + checkoutRunId: uuid("checkout_run_id").references(() => heartbeatRuns.id, { onDelete: "set null" }), + executionRunId: uuid("execution_run_id").references(() => heartbeatRuns.id, { onDelete: "set null" }), + executionAgentNameKey: text("execution_agent_name_key"), + executionLockedAt: timestamp("execution_locked_at", { withTimezone: true }), + createdByAgentId: uuid("created_by_agent_id").references(() => agents.id), + createdByUserId: text("created_by_user_id"), + issueNumber: integer("issue_number"), + identifier: text("identifier"), + originKind: text("origin_kind").notNull().default("manual"), + originId: text("origin_id"), + originRunId: text("origin_run_id"), + requestDepth: integer("request_depth").notNull().default(0), + billingCode: text("billing_code"), + assigneeAdapterOverrides: jsonb("assignee_adapter_overrides").$type(), + executionPolicy: jsonb("execution_policy").$type(), + executionState: jsonb("execution_state").$type(), + executionWorkspaceId: uuid("execution_workspace_id").references(() => executionWorkspaces.id, { onDelete: "set null" }), + executionWorkspacePreference: text("execution_workspace_preference"), + executionWorkspaceSettings: jsonb("execution_workspace_settings").$type(), + startedAt: timestamp("started_at", { withTimezone: true }), + completedAt: timestamp("completed_at", { withTimezone: true }), + cancelledAt: timestamp("cancelled_at", { withTimezone: true }), + hiddenAt: timestamp("hidden_at", { withTimezone: true }), + createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), + updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() + }, + (table) => ({ + companyStatusIdx: index("issues_company_status_idx").on(table.companyId, table.status), + assigneeStatusIdx: index("issues_company_assignee_status_idx").on( + table.companyId, + table.assigneeAgentId, + table.status + ), + assigneeUserStatusIdx: index("issues_company_assignee_user_status_idx").on( + table.companyId, + table.assigneeUserId, + table.status + ), + parentIdx: index("issues_company_parent_idx").on(table.companyId, table.parentId), + projectIdx: index("issues_company_project_idx").on(table.companyId, table.projectId), + originIdx: index("issues_company_origin_idx").on(table.companyId, table.originKind, table.originId), + projectWorkspaceIdx: index("issues_company_project_workspace_idx").on(table.companyId, table.projectWorkspaceId), + executionWorkspaceIdx: index("issues_company_execution_workspace_idx").on(table.companyId, table.executionWorkspaceId), + identifierIdx: uniqueIndex("issues_identifier_idx").on(table.identifier), + titleSearchIdx: index("issues_title_search_idx").using("gin", table.title.op("gin_trgm_ops")), + identifierSearchIdx: index("issues_identifier_search_idx").using("gin", table.identifier.op("gin_trgm_ops")), + descriptionSearchIdx: index("issues_description_search_idx").using("gin", table.description.op("gin_trgm_ops")), + openRoutineExecutionIdx: uniqueIndex("issues_open_routine_execution_uq").on(table.companyId, table.originKind, table.originId).where( + sql`${table.originKind} = 'routine_execution' + and ${table.originId} is not null + and ${table.hiddenAt} is null + and ${table.executionRunId} is not null + and ${table.status} in ('backlog', 'todo', 'in_progress', 'in_review', 'blocked')` + ) + }) + ); + } +}); + +// packages/db/src/schema/execution_workspaces.ts +var executionWorkspaces; +var init_execution_workspaces = __esm({ + "packages/db/src/schema/execution_workspaces.ts"() { + "use strict"; + init_pg_core(); + init_companies(); + init_issues(); + init_project_workspaces(); + init_projects(); + executionWorkspaces = pgTable( + "execution_workspaces", + { + id: uuid("id").primaryKey().defaultRandom(), + companyId: uuid("company_id").notNull().references(() => companies.id), + projectId: uuid("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }), + projectWorkspaceId: uuid("project_workspace_id").references(() => projectWorkspaces.id, { onDelete: "set null" }), + sourceIssueId: uuid("source_issue_id").references(() => issues.id, { onDelete: "set null" }), + mode: text("mode").notNull(), + strategyType: text("strategy_type").notNull(), + name: text("name").notNull(), + status: text("status").notNull().default("active"), + cwd: text("cwd"), + repoUrl: text("repo_url"), + baseRef: text("base_ref"), + branchName: text("branch_name"), + providerType: text("provider_type").notNull().default("local_fs"), + providerRef: text("provider_ref"), + derivedFromExecutionWorkspaceId: uuid("derived_from_execution_workspace_id").references(() => executionWorkspaces.id, { onDelete: "set null" }), + lastUsedAt: timestamp("last_used_at", { withTimezone: true }).notNull().defaultNow(), + openedAt: timestamp("opened_at", { withTimezone: true }).notNull().defaultNow(), + closedAt: timestamp("closed_at", { withTimezone: true }), + cleanupEligibleAt: timestamp("cleanup_eligible_at", { withTimezone: true }), + cleanupReason: text("cleanup_reason"), + metadata: jsonb("metadata").$type(), + createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), + updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() + }, + (table) => ({ + companyProjectStatusIdx: index("execution_workspaces_company_project_status_idx").on( + table.companyId, + table.projectId, + table.status + ), + companyProjectWorkspaceStatusIdx: index("execution_workspaces_company_project_workspace_status_idx").on( + table.companyId, + table.projectWorkspaceId, + table.status + ), + companySourceIssueIdx: index("execution_workspaces_company_source_issue_idx").on( + table.companyId, + table.sourceIssueId + ), + companyLastUsedIdx: index("execution_workspaces_company_last_used_idx").on( + table.companyId, + table.lastUsedAt + ), + companyBranchIdx: index("execution_workspaces_company_branch_idx").on( + table.companyId, + table.branchName + ) + }) + ); + } +}); + +// packages/db/src/schema/workspace_operations.ts +var workspaceOperations; +var init_workspace_operations = __esm({ + "packages/db/src/schema/workspace_operations.ts"() { + "use strict"; + init_pg_core(); + init_companies(); + init_execution_workspaces(); + init_heartbeat_runs(); + workspaceOperations = pgTable( + "workspace_operations", + { + id: uuid("id").primaryKey().defaultRandom(), + companyId: uuid("company_id").notNull().references(() => companies.id), + executionWorkspaceId: uuid("execution_workspace_id").references(() => executionWorkspaces.id, { + onDelete: "set null" + }), + heartbeatRunId: uuid("heartbeat_run_id").references(() => heartbeatRuns.id, { + onDelete: "set null" + }), + phase: text("phase").notNull(), + command: text("command"), + cwd: text("cwd"), + status: text("status").notNull().default("running"), + exitCode: integer("exit_code"), + logStore: text("log_store"), + logRef: text("log_ref"), + logBytes: bigint("log_bytes", { mode: "number" }), + logSha256: text("log_sha256"), + logCompressed: boolean("log_compressed").notNull().default(false), + stdoutExcerpt: text("stdout_excerpt"), + stderrExcerpt: text("stderr_excerpt"), + metadata: jsonb("metadata").$type(), + startedAt: timestamp("started_at", { withTimezone: true }).notNull().defaultNow(), + finishedAt: timestamp("finished_at", { withTimezone: true }), + createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), + updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() + }, + (table) => ({ + companyRunStartedIdx: index("workspace_operations_company_run_started_idx").on( + table.companyId, + table.heartbeatRunId, + table.startedAt + ), + companyWorkspaceStartedIdx: index("workspace_operations_company_workspace_started_idx").on( + table.companyId, + table.executionWorkspaceId, + table.startedAt + ) + }) + ); + } +}); + +// packages/db/src/schema/workspace_runtime_services.ts +var workspaceRuntimeServices; +var init_workspace_runtime_services = __esm({ + "packages/db/src/schema/workspace_runtime_services.ts"() { + "use strict"; + init_pg_core(); + init_companies(); + init_projects(); + init_project_workspaces(); + init_execution_workspaces(); + init_issues(); + init_agents(); + init_heartbeat_runs(); + workspaceRuntimeServices = pgTable( + "workspace_runtime_services", + { + id: uuid("id").primaryKey(), + companyId: uuid("company_id").notNull().references(() => companies.id), + projectId: uuid("project_id").references(() => projects.id, { onDelete: "set null" }), + projectWorkspaceId: uuid("project_workspace_id").references(() => projectWorkspaces.id, { onDelete: "set null" }), + executionWorkspaceId: uuid("execution_workspace_id").references(() => executionWorkspaces.id, { onDelete: "set null" }), + issueId: uuid("issue_id").references(() => issues.id, { onDelete: "set null" }), + scopeType: text("scope_type").notNull(), + scopeId: text("scope_id"), + serviceName: text("service_name").notNull(), + status: text("status").notNull(), + lifecycle: text("lifecycle").notNull(), + reuseKey: text("reuse_key"), + command: text("command"), + cwd: text("cwd"), + port: integer("port"), + url: text("url"), + provider: text("provider").notNull(), + providerRef: text("provider_ref"), + ownerAgentId: uuid("owner_agent_id").references(() => agents.id, { onDelete: "set null" }), + startedByRunId: uuid("started_by_run_id").references(() => heartbeatRuns.id, { onDelete: "set null" }), + lastUsedAt: timestamp("last_used_at", { withTimezone: true }).notNull().defaultNow(), + startedAt: timestamp("started_at", { withTimezone: true }).notNull().defaultNow(), + stoppedAt: timestamp("stopped_at", { withTimezone: true }), + stopPolicy: jsonb("stop_policy").$type(), + healthStatus: text("health_status").notNull().default("unknown"), + createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), + updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() + }, + (table) => ({ + companyWorkspaceStatusIdx: index("workspace_runtime_services_company_workspace_status_idx").on( + table.companyId, + table.projectWorkspaceId, + table.status + ), + companyExecutionWorkspaceStatusIdx: index("workspace_runtime_services_company_execution_workspace_status_idx").on( + table.companyId, + table.executionWorkspaceId, + table.status + ), + companyProjectStatusIdx: index("workspace_runtime_services_company_project_status_idx").on( + table.companyId, + table.projectId, + table.status + ), + runIdx: index("workspace_runtime_services_run_idx").on(table.startedByRunId), + companyUpdatedIdx: index("workspace_runtime_services_company_updated_idx").on( + table.companyId, + table.updatedAt + ) + }) + ); + } +}); + +// packages/db/src/schema/project_goals.ts +var projectGoals; +var init_project_goals = __esm({ + "packages/db/src/schema/project_goals.ts"() { + "use strict"; + init_pg_core(); + init_companies(); + init_projects(); + init_goals(); + projectGoals = pgTable( + "project_goals", + { + projectId: uuid("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }), + goalId: uuid("goal_id").notNull().references(() => goals.id, { onDelete: "cascade" }), + companyId: uuid("company_id").notNull().references(() => companies.id), + createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), + updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() + }, + (table) => ({ + pk: primaryKey({ columns: [table.projectId, table.goalId] }), + projectIdx: index("project_goals_project_idx").on(table.projectId), + goalIdx: index("project_goals_goal_idx").on(table.goalId), + companyIdx: index("project_goals_company_idx").on(table.companyId) + }) + ); + } +}); + +// packages/db/src/schema/issue_relations.ts +var issueRelations; +var init_issue_relations = __esm({ + "packages/db/src/schema/issue_relations.ts"() { + "use strict"; + init_pg_core(); + init_agents(); + init_companies(); + init_issues(); + issueRelations = pgTable( + "issue_relations", + { + id: uuid("id").primaryKey().defaultRandom(), + companyId: uuid("company_id").notNull().references(() => companies.id), + issueId: uuid("issue_id").notNull().references(() => issues.id, { onDelete: "cascade" }), + relatedIssueId: uuid("related_issue_id").notNull().references(() => issues.id, { onDelete: "cascade" }), + type: text("type").$type().notNull(), + createdByAgentId: uuid("created_by_agent_id").references(() => agents.id, { onDelete: "set null" }), + createdByUserId: text("created_by_user_id"), + createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), + updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() + }, + (table) => ({ + companyIssueIdx: index("issue_relations_company_issue_idx").on(table.companyId, table.issueId), + companyRelatedIssueIdx: index("issue_relations_company_related_issue_idx").on(table.companyId, table.relatedIssueId), + companyTypeIdx: index("issue_relations_company_type_idx").on(table.companyId, table.type), + companyEdgeUq: uniqueIndex("issue_relations_company_edge_uq").on( + table.companyId, + table.issueId, + table.relatedIssueId, + table.type + ) + }) + ); + } +}); + +// packages/db/src/schema/company_secrets.ts +var companySecrets; +var init_company_secrets = __esm({ + "packages/db/src/schema/company_secrets.ts"() { + "use strict"; + init_pg_core(); + init_companies(); + init_agents(); + companySecrets = pgTable( + "company_secrets", + { + id: uuid("id").primaryKey().defaultRandom(), + companyId: uuid("company_id").notNull().references(() => companies.id), + name: text("name").notNull(), + provider: text("provider").notNull().default("local_encrypted"), + externalRef: text("external_ref"), + latestVersion: integer("latest_version").notNull().default(1), + description: text("description"), + createdByAgentId: uuid("created_by_agent_id").references(() => agents.id, { onDelete: "set null" }), + createdByUserId: text("created_by_user_id"), + createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), + updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() + }, + (table) => ({ + companyIdx: index("company_secrets_company_idx").on(table.companyId), + companyProviderIdx: index("company_secrets_company_provider_idx").on(table.companyId, table.provider), + companyNameUq: uniqueIndex("company_secrets_company_name_uq").on(table.companyId, table.name) + }) + ); + } +}); + +// packages/db/src/schema/routines.ts +var routines, routineTriggers, routineRuns; +var init_routines = __esm({ + "packages/db/src/schema/routines.ts"() { + "use strict"; + init_pg_core(); + init_agents(); + init_companies(); + init_company_secrets(); + init_issues(); + init_projects(); + init_goals(); + routines = pgTable( + "routines", + { + id: uuid("id").primaryKey().defaultRandom(), + companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }), + projectId: uuid("project_id").references(() => projects.id, { onDelete: "cascade" }), + goalId: uuid("goal_id").references(() => goals.id, { onDelete: "set null" }), + parentIssueId: uuid("parent_issue_id").references(() => issues.id, { onDelete: "set null" }), + title: text("title").notNull(), + description: text("description"), + assigneeAgentId: uuid("assignee_agent_id").references(() => agents.id), + priority: text("priority").notNull().default("medium"), + status: text("status").notNull().default("active"), + concurrencyPolicy: text("concurrency_policy").notNull().default("coalesce_if_active"), + catchUpPolicy: text("catch_up_policy").notNull().default("skip_missed"), + variables: jsonb("variables").$type().notNull().default([]), + createdByAgentId: uuid("created_by_agent_id").references(() => agents.id, { onDelete: "set null" }), + createdByUserId: text("created_by_user_id"), + updatedByAgentId: uuid("updated_by_agent_id").references(() => agents.id, { onDelete: "set null" }), + updatedByUserId: text("updated_by_user_id"), + lastTriggeredAt: timestamp("last_triggered_at", { withTimezone: true }), + lastEnqueuedAt: timestamp("last_enqueued_at", { withTimezone: true }), + createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), + updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() + }, + (table) => ({ + companyStatusIdx: index("routines_company_status_idx").on(table.companyId, table.status), + companyAssigneeIdx: index("routines_company_assignee_idx").on(table.companyId, table.assigneeAgentId), + companyProjectIdx: index("routines_company_project_idx").on(table.companyId, table.projectId) + }) + ); + routineTriggers = pgTable( + "routine_triggers", + { + id: uuid("id").primaryKey().defaultRandom(), + companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }), + routineId: uuid("routine_id").notNull().references(() => routines.id, { onDelete: "cascade" }), + kind: text("kind").notNull(), + label: text("label"), + enabled: boolean("enabled").notNull().default(true), + cronExpression: text("cron_expression"), + timezone: text("timezone"), + nextRunAt: timestamp("next_run_at", { withTimezone: true }), + lastFiredAt: timestamp("last_fired_at", { withTimezone: true }), + publicId: text("public_id"), + secretId: uuid("secret_id").references(() => companySecrets.id, { onDelete: "set null" }), + signingMode: text("signing_mode"), + replayWindowSec: integer("replay_window_sec"), + lastRotatedAt: timestamp("last_rotated_at", { withTimezone: true }), + lastResult: text("last_result"), + createdByAgentId: uuid("created_by_agent_id").references(() => agents.id, { onDelete: "set null" }), + createdByUserId: text("created_by_user_id"), + updatedByAgentId: uuid("updated_by_agent_id").references(() => agents.id, { onDelete: "set null" }), + updatedByUserId: text("updated_by_user_id"), + createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), + updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() + }, + (table) => ({ + companyRoutineIdx: index("routine_triggers_company_routine_idx").on(table.companyId, table.routineId), + companyKindIdx: index("routine_triggers_company_kind_idx").on(table.companyId, table.kind), + nextRunIdx: index("routine_triggers_next_run_idx").on(table.nextRunAt), + publicIdIdx: index("routine_triggers_public_id_idx").on(table.publicId), + publicIdUq: uniqueIndex("routine_triggers_public_id_uq").on(table.publicId) + }) + ); + routineRuns = pgTable( + "routine_runs", + { + id: uuid("id").primaryKey().defaultRandom(), + companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }), + routineId: uuid("routine_id").notNull().references(() => routines.id, { onDelete: "cascade" }), + triggerId: uuid("trigger_id").references(() => routineTriggers.id, { onDelete: "set null" }), + source: text("source").notNull(), + status: text("status").notNull().default("received"), + triggeredAt: timestamp("triggered_at", { withTimezone: true }).notNull().defaultNow(), + idempotencyKey: text("idempotency_key"), + triggerPayload: jsonb("trigger_payload").$type(), + linkedIssueId: uuid("linked_issue_id").references(() => issues.id, { onDelete: "set null" }), + coalescedIntoRunId: uuid("coalesced_into_run_id"), + failureReason: text("failure_reason"), + completedAt: timestamp("completed_at", { withTimezone: true }), + createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), + updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() + }, + (table) => ({ + companyRoutineIdx: index("routine_runs_company_routine_idx").on(table.companyId, table.routineId, table.createdAt), + triggerIdx: index("routine_runs_trigger_idx").on(table.triggerId, table.createdAt), + linkedIssueIdx: index("routine_runs_linked_issue_idx").on(table.linkedIssueId), + idempotencyIdx: index("routine_runs_trigger_idempotency_idx").on(table.triggerId, table.idempotencyKey) + }) + ); + } +}); + +// packages/db/src/schema/issue_work_products.ts +var issueWorkProducts; +var init_issue_work_products = __esm({ + "packages/db/src/schema/issue_work_products.ts"() { + "use strict"; + init_pg_core(); + init_companies(); + init_execution_workspaces(); + init_heartbeat_runs(); + init_issues(); + init_projects(); + init_workspace_runtime_services(); + issueWorkProducts = pgTable( + "issue_work_products", + { + id: uuid("id").primaryKey().defaultRandom(), + companyId: uuid("company_id").notNull().references(() => companies.id), + projectId: uuid("project_id").references(() => projects.id, { onDelete: "set null" }), + issueId: uuid("issue_id").notNull().references(() => issues.id, { onDelete: "cascade" }), + executionWorkspaceId: uuid("execution_workspace_id").references(() => executionWorkspaces.id, { onDelete: "set null" }), + runtimeServiceId: uuid("runtime_service_id").references(() => workspaceRuntimeServices.id, { onDelete: "set null" }), + type: text("type").notNull(), + provider: text("provider").notNull(), + externalId: text("external_id"), + title: text("title").notNull(), + url: text("url"), + status: text("status").notNull(), + reviewState: text("review_state").notNull().default("none"), + isPrimary: boolean("is_primary").notNull().default(false), + healthStatus: text("health_status").notNull().default("unknown"), + summary: text("summary"), + metadata: jsonb("metadata").$type(), + createdByRunId: uuid("created_by_run_id").references(() => heartbeatRuns.id, { onDelete: "set null" }), + createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), + updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() + }, + (table) => ({ + companyIssueTypeIdx: index("issue_work_products_company_issue_type_idx").on( + table.companyId, + table.issueId, + table.type + ), + companyExecutionWorkspaceTypeIdx: index("issue_work_products_company_execution_workspace_type_idx").on( + table.companyId, + table.executionWorkspaceId, + table.type + ), + companyProviderExternalIdIdx: index("issue_work_products_company_provider_external_id_idx").on( + table.companyId, + table.provider, + table.externalId + ), + companyUpdatedIdx: index("issue_work_products_company_updated_idx").on( + table.companyId, + table.updatedAt + ) + }) + ); + } +}); + +// packages/db/src/schema/labels.ts +var labels; +var init_labels = __esm({ + "packages/db/src/schema/labels.ts"() { + "use strict"; + init_pg_core(); + init_companies(); + labels = pgTable( + "labels", + { + id: uuid("id").primaryKey().defaultRandom(), + companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }), + name: text("name").notNull(), + color: text("color").notNull(), + createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), + updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() + }, + (table) => ({ + companyIdx: index("labels_company_idx").on(table.companyId), + companyNameIdx: uniqueIndex("labels_company_name_idx").on(table.companyId, table.name) + }) + ); + } +}); + +// packages/db/src/schema/issue_labels.ts +var issueLabels; +var init_issue_labels = __esm({ + "packages/db/src/schema/issue_labels.ts"() { + "use strict"; + init_pg_core(); + init_companies(); + init_issues(); + init_labels(); + issueLabels = pgTable( + "issue_labels", + { + issueId: uuid("issue_id").notNull().references(() => issues.id, { onDelete: "cascade" }), + labelId: uuid("label_id").notNull().references(() => labels.id, { onDelete: "cascade" }), + companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }), + createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow() + }, + (table) => ({ + pk: primaryKey({ columns: [table.issueId, table.labelId], name: "issue_labels_pk" }), + issueIdx: index("issue_labels_issue_idx").on(table.issueId), + labelIdx: index("issue_labels_label_idx").on(table.labelId), + companyIdx: index("issue_labels_company_idx").on(table.companyId) + }) + ); + } +}); + +// packages/db/src/schema/issue_approvals.ts +var issueApprovals; +var init_issue_approvals = __esm({ + "packages/db/src/schema/issue_approvals.ts"() { + "use strict"; + init_pg_core(); + init_companies(); + init_issues(); + init_approvals(); + init_agents(); + issueApprovals = pgTable( + "issue_approvals", + { + companyId: uuid("company_id").notNull().references(() => companies.id), + issueId: uuid("issue_id").notNull().references(() => issues.id, { onDelete: "cascade" }), + approvalId: uuid("approval_id").notNull().references(() => approvals.id, { onDelete: "cascade" }), + linkedByAgentId: uuid("linked_by_agent_id").references(() => agents.id, { onDelete: "set null" }), + linkedByUserId: text("linked_by_user_id"), + createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow() + }, + (table) => ({ + pk: primaryKey({ columns: [table.issueId, table.approvalId], name: "issue_approvals_pk" }), + issueIdx: index("issue_approvals_issue_idx").on(table.issueId), + approvalIdx: index("issue_approvals_approval_idx").on(table.approvalId), + companyIdx: index("issue_approvals_company_idx").on(table.companyId) + }) + ); + } +}); + +// packages/db/src/schema/issue_comments.ts +var issueComments; +var init_issue_comments = __esm({ + "packages/db/src/schema/issue_comments.ts"() { + "use strict"; + init_pg_core(); + init_companies(); + init_issues(); + init_agents(); + init_heartbeat_runs(); + issueComments = pgTable( + "issue_comments", + { + id: uuid("id").primaryKey().defaultRandom(), + companyId: uuid("company_id").notNull().references(() => companies.id), + issueId: uuid("issue_id").notNull().references(() => issues.id), + authorAgentId: uuid("author_agent_id").references(() => agents.id), + authorUserId: text("author_user_id"), + createdByRunId: uuid("created_by_run_id").references(() => heartbeatRuns.id, { onDelete: "set null" }), + body: text("body").notNull(), + createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), + updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() + }, + (table) => ({ + issueIdx: index("issue_comments_issue_idx").on(table.issueId), + companyIdx: index("issue_comments_company_idx").on(table.companyId), + companyIssueCreatedAtIdx: index("issue_comments_company_issue_created_at_idx").on( + table.companyId, + table.issueId, + table.createdAt + ), + companyAuthorIssueCreatedAtIdx: index("issue_comments_company_author_issue_created_at_idx").on( + table.companyId, + table.authorUserId, + table.issueId, + table.createdAt + ), + bodySearchIdx: index("issue_comments_body_search_idx").using("gin", table.body.op("gin_trgm_ops")) + }) + ); + } +}); + +// packages/db/src/schema/issue_execution_decisions.ts +var issueExecutionDecisions; +var init_issue_execution_decisions = __esm({ + "packages/db/src/schema/issue_execution_decisions.ts"() { + "use strict"; + init_pg_core(); + init_companies(); + init_issues(); + init_agents(); + init_heartbeat_runs(); + issueExecutionDecisions = pgTable( + "issue_execution_decisions", + { + id: uuid("id").primaryKey().defaultRandom(), + companyId: uuid("company_id").notNull().references(() => companies.id), + issueId: uuid("issue_id").notNull().references(() => issues.id, { onDelete: "cascade" }), + stageId: uuid("stage_id").notNull(), + stageType: text("stage_type").notNull(), + actorAgentId: uuid("actor_agent_id").references(() => agents.id), + actorUserId: text("actor_user_id"), + outcome: text("outcome").notNull(), + body: text("body").notNull(), + createdByRunId: uuid("created_by_run_id").references(() => heartbeatRuns.id, { onDelete: "set null" }), + createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), + updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() + }, + (table) => ({ + companyIssueIdx: index("issue_execution_decisions_company_issue_idx").on(table.companyId, table.issueId), + stageIdx: index("issue_execution_decisions_stage_idx").on(table.issueId, table.stageId, table.createdAt) + }) + ); + } +}); + +// packages/db/src/schema/issue_inbox_archives.ts +var issueInboxArchives; +var init_issue_inbox_archives = __esm({ + "packages/db/src/schema/issue_inbox_archives.ts"() { + "use strict"; + init_pg_core(); + init_companies(); + init_issues(); + issueInboxArchives = pgTable( + "issue_inbox_archives", + { + id: uuid("id").primaryKey().defaultRandom(), + companyId: uuid("company_id").notNull().references(() => companies.id), + issueId: uuid("issue_id").notNull().references(() => issues.id), + userId: text("user_id").notNull(), + archivedAt: timestamp("archived_at", { withTimezone: true }).notNull().defaultNow(), + createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), + updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() + }, + (table) => ({ + companyIssueIdx: index("issue_inbox_archives_company_issue_idx").on(table.companyId, table.issueId), + companyUserIdx: index("issue_inbox_archives_company_user_idx").on(table.companyId, table.userId), + companyIssueUserUnique: uniqueIndex("issue_inbox_archives_company_issue_user_idx").on( + table.companyId, + table.issueId, + table.userId + ) + }) + ); + } +}); + +// packages/db/src/schema/inbox_dismissals.ts +var inboxDismissals; +var init_inbox_dismissals = __esm({ + "packages/db/src/schema/inbox_dismissals.ts"() { + "use strict"; + init_pg_core(); + init_companies(); + inboxDismissals = pgTable( + "inbox_dismissals", + { + id: uuid("id").primaryKey().defaultRandom(), + companyId: uuid("company_id").notNull().references(() => companies.id), + userId: text("user_id").notNull(), + itemKey: text("item_key").notNull(), + dismissedAt: timestamp("dismissed_at", { withTimezone: true }).notNull().defaultNow(), + createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), + updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() + }, + (table) => ({ + companyUserIdx: index("inbox_dismissals_company_user_idx").on(table.companyId, table.userId), + companyItemIdx: index("inbox_dismissals_company_item_idx").on(table.companyId, table.itemKey), + companyUserItemUnique: uniqueIndex("inbox_dismissals_company_user_item_idx").on( + table.companyId, + table.userId, + table.itemKey + ) + }) + ); + } +}); + +// packages/db/src/schema/feedback_votes.ts +var feedbackVotes; +var init_feedback_votes = __esm({ + "packages/db/src/schema/feedback_votes.ts"() { + "use strict"; + init_pg_core(); + init_companies(); + init_issues(); + feedbackVotes = pgTable( + "feedback_votes", + { + id: uuid("id").primaryKey().defaultRandom(), + companyId: uuid("company_id").notNull().references(() => companies.id), + issueId: uuid("issue_id").notNull().references(() => issues.id), + targetType: text("target_type").notNull(), + targetId: text("target_id").notNull(), + authorUserId: text("author_user_id").notNull(), + vote: text("vote").notNull(), + reason: text("reason"), + sharedWithLabs: boolean("shared_with_labs").notNull().default(false), + sharedAt: timestamp("shared_at", { withTimezone: true }), + consentVersion: text("consent_version"), + redactionSummary: jsonb("redaction_summary"), + createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), + updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() + }, + (table) => ({ + companyIssueIdx: index("feedback_votes_company_issue_idx").on(table.companyId, table.issueId), + issueTargetIdx: index("feedback_votes_issue_target_idx").on(table.issueId, table.targetType, table.targetId), + authorIdx: index("feedback_votes_author_idx").on(table.authorUserId, table.createdAt), + companyTargetAuthorUniqueIdx: uniqueIndex("feedback_votes_company_target_author_idx").on( + table.companyId, + table.targetType, + table.targetId, + table.authorUserId + ) + }) + ); + } +}); + +// packages/db/src/schema/feedback_exports.ts +var feedbackExports; +var init_feedback_exports = __esm({ + "packages/db/src/schema/feedback_exports.ts"() { + "use strict"; + init_pg_core(); + init_companies(); + init_feedback_votes(); + init_issues(); + init_projects(); + feedbackExports = pgTable( + "feedback_exports", + { + id: uuid("id").primaryKey().defaultRandom(), + companyId: uuid("company_id").notNull().references(() => companies.id), + feedbackVoteId: uuid("feedback_vote_id").notNull().references(() => feedbackVotes.id, { onDelete: "cascade" }), + issueId: uuid("issue_id").notNull().references(() => issues.id, { onDelete: "cascade" }), + projectId: uuid("project_id").references(() => projects.id, { onDelete: "set null" }), + authorUserId: text("author_user_id").notNull(), + targetType: text("target_type").notNull(), + targetId: text("target_id").notNull(), + vote: text("vote").notNull(), + status: text("status").notNull().default("local_only"), + destination: text("destination"), + exportId: text("export_id"), + consentVersion: text("consent_version"), + schemaVersion: text("schema_version").notNull().default("taskcore-feedback-envelope-v2"), + bundleVersion: text("bundle_version").notNull().default("taskcore-feedback-bundle-v2"), + payloadVersion: text("payload_version").notNull().default("taskcore-feedback-v1"), + payloadDigest: text("payload_digest"), + payloadSnapshot: jsonb("payload_snapshot"), + targetSummary: jsonb("target_summary").notNull(), + redactionSummary: jsonb("redaction_summary"), + attemptCount: integer("attempt_count").notNull().default(0), + lastAttemptedAt: timestamp("last_attempted_at", { withTimezone: true }), + exportedAt: timestamp("exported_at", { withTimezone: true }), + failureReason: text("failure_reason"), + createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), + updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() + }, + (table) => ({ + voteUniqueIdx: uniqueIndex("feedback_exports_feedback_vote_idx").on(table.feedbackVoteId), + companyCreatedIdx: index("feedback_exports_company_created_idx").on(table.companyId, table.createdAt), + companyStatusIdx: index("feedback_exports_company_status_idx").on(table.companyId, table.status, table.createdAt), + companyIssueIdx: index("feedback_exports_company_issue_idx").on(table.companyId, table.issueId, table.createdAt), + companyProjectIdx: index("feedback_exports_company_project_idx").on(table.companyId, table.projectId, table.createdAt), + companyAuthorIdx: index("feedback_exports_company_author_idx").on(table.companyId, table.authorUserId, table.createdAt) + }) + ); + } +}); + +// packages/db/src/schema/issue_read_states.ts +var issueReadStates; +var init_issue_read_states = __esm({ + "packages/db/src/schema/issue_read_states.ts"() { + "use strict"; + init_pg_core(); + init_companies(); + init_issues(); + issueReadStates = pgTable( + "issue_read_states", + { + id: uuid("id").primaryKey().defaultRandom(), + companyId: uuid("company_id").notNull().references(() => companies.id), + issueId: uuid("issue_id").notNull().references(() => issues.id), + userId: text("user_id").notNull(), + lastReadAt: timestamp("last_read_at", { withTimezone: true }).notNull().defaultNow(), + createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), + updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() + }, + (table) => ({ + companyIssueIdx: index("issue_read_states_company_issue_idx").on(table.companyId, table.issueId), + companyUserIdx: index("issue_read_states_company_user_idx").on(table.companyId, table.userId), + companyIssueUserUnique: uniqueIndex("issue_read_states_company_issue_user_idx").on( + table.companyId, + table.issueId, + table.userId + ) + }) + ); + } +}); + +// packages/db/src/schema/issue_attachments.ts +var issueAttachments; +var init_issue_attachments = __esm({ + "packages/db/src/schema/issue_attachments.ts"() { + "use strict"; + init_pg_core(); + init_companies(); + init_issues(); + init_assets(); + init_issue_comments(); + issueAttachments = pgTable( + "issue_attachments", + { + id: uuid("id").primaryKey().defaultRandom(), + companyId: uuid("company_id").notNull().references(() => companies.id), + issueId: uuid("issue_id").notNull().references(() => issues.id, { onDelete: "cascade" }), + assetId: uuid("asset_id").notNull().references(() => assets.id, { onDelete: "cascade" }), + issueCommentId: uuid("issue_comment_id").references(() => issueComments.id, { onDelete: "set null" }), + createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), + updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() + }, + (table) => ({ + companyIssueIdx: index("issue_attachments_company_issue_idx").on(table.companyId, table.issueId), + issueCommentIdx: index("issue_attachments_issue_comment_idx").on(table.issueCommentId), + assetUq: uniqueIndex("issue_attachments_asset_uq").on(table.assetId) + }) + ); + } +}); + +// packages/db/src/schema/documents.ts +var documents; +var init_documents = __esm({ + "packages/db/src/schema/documents.ts"() { + "use strict"; + init_pg_core(); + init_companies(); + init_agents(); + documents = pgTable( + "documents", + { + id: uuid("id").primaryKey().defaultRandom(), + companyId: uuid("company_id").notNull().references(() => companies.id), + title: text("title"), + format: text("format").notNull().default("markdown"), + latestBody: text("latest_body").notNull(), + latestRevisionId: uuid("latest_revision_id"), + latestRevisionNumber: integer("latest_revision_number").notNull().default(1), + createdByAgentId: uuid("created_by_agent_id").references(() => agents.id, { onDelete: "set null" }), + createdByUserId: text("created_by_user_id"), + updatedByAgentId: uuid("updated_by_agent_id").references(() => agents.id, { onDelete: "set null" }), + updatedByUserId: text("updated_by_user_id"), + createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), + updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() + }, + (table) => ({ + companyUpdatedIdx: index("documents_company_updated_idx").on(table.companyId, table.updatedAt), + companyCreatedIdx: index("documents_company_created_idx").on(table.companyId, table.createdAt) + }) + ); + } +}); + +// packages/db/src/schema/document_revisions.ts +var documentRevisions; +var init_document_revisions = __esm({ + "packages/db/src/schema/document_revisions.ts"() { + "use strict"; + init_pg_core(); + init_companies(); + init_agents(); + init_documents(); + init_heartbeat_runs(); + documentRevisions = pgTable( + "document_revisions", + { + id: uuid("id").primaryKey().defaultRandom(), + companyId: uuid("company_id").notNull().references(() => companies.id), + documentId: uuid("document_id").notNull().references(() => documents.id, { onDelete: "cascade" }), + revisionNumber: integer("revision_number").notNull(), + title: text("title"), + format: text("format").notNull().default("markdown"), + body: text("body").notNull(), + changeSummary: text("change_summary"), + createdByAgentId: uuid("created_by_agent_id").references(() => agents.id, { onDelete: "set null" }), + createdByUserId: text("created_by_user_id"), + createdByRunId: uuid("created_by_run_id").references(() => heartbeatRuns.id, { onDelete: "set null" }), + createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow() + }, + (table) => ({ + documentRevisionUq: uniqueIndex("document_revisions_document_revision_uq").on( + table.documentId, + table.revisionNumber + ), + companyDocumentCreatedIdx: index("document_revisions_company_document_created_idx").on( + table.companyId, + table.documentId, + table.createdAt + ) + }) + ); + } +}); + +// packages/db/src/schema/issue_documents.ts +var issueDocuments; +var init_issue_documents = __esm({ + "packages/db/src/schema/issue_documents.ts"() { + "use strict"; + init_pg_core(); + init_companies(); + init_issues(); + init_documents(); + issueDocuments = pgTable( + "issue_documents", + { + id: uuid("id").primaryKey().defaultRandom(), + companyId: uuid("company_id").notNull().references(() => companies.id), + issueId: uuid("issue_id").notNull().references(() => issues.id, { onDelete: "cascade" }), + documentId: uuid("document_id").notNull().references(() => documents.id, { onDelete: "cascade" }), + key: text("key").notNull(), + createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), + updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() + }, + (table) => ({ + companyIssueKeyUq: uniqueIndex("issue_documents_company_issue_key_uq").on( + table.companyId, + table.issueId, + table.key + ), + documentUq: uniqueIndex("issue_documents_document_uq").on(table.documentId), + companyIssueUpdatedIdx: index("issue_documents_company_issue_updated_idx").on( + table.companyId, + table.issueId, + table.updatedAt + ) + }) + ); + } +}); + +// packages/db/src/schema/heartbeat_run_events.ts +var heartbeatRunEvents; +var init_heartbeat_run_events = __esm({ + "packages/db/src/schema/heartbeat_run_events.ts"() { + "use strict"; + init_pg_core(); + init_companies(); + init_agents(); + init_heartbeat_runs(); + heartbeatRunEvents = pgTable( + "heartbeat_run_events", + { + id: bigserial("id", { mode: "number" }).primaryKey(), + companyId: uuid("company_id").notNull().references(() => companies.id), + runId: uuid("run_id").notNull().references(() => heartbeatRuns.id), + agentId: uuid("agent_id").notNull().references(() => agents.id), + seq: integer("seq").notNull(), + eventType: text("event_type").notNull(), + stream: text("stream"), + level: text("level"), + color: text("color"), + message: text("message"), + payload: jsonb("payload").$type(), + createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow() + }, + (table) => ({ + runSeqIdx: index("heartbeat_run_events_run_seq_idx").on(table.runId, table.seq), + companyRunIdx: index("heartbeat_run_events_company_run_idx").on(table.companyId, table.runId), + companyCreatedIdx: index("heartbeat_run_events_company_created_idx").on(table.companyId, table.createdAt) + }) + ); + } +}); + +// packages/db/src/schema/cost_events.ts +var costEvents; +var init_cost_events = __esm({ + "packages/db/src/schema/cost_events.ts"() { + "use strict"; + init_pg_core(); + init_companies(); + init_agents(); + init_issues(); + init_projects(); + init_goals(); + init_heartbeat_runs(); + costEvents = pgTable( + "cost_events", + { + id: uuid("id").primaryKey().defaultRandom(), + companyId: uuid("company_id").notNull().references(() => companies.id), + agentId: uuid("agent_id").notNull().references(() => agents.id), + issueId: uuid("issue_id").references(() => issues.id), + projectId: uuid("project_id").references(() => projects.id), + goalId: uuid("goal_id").references(() => goals.id), + heartbeatRunId: uuid("heartbeat_run_id").references(() => heartbeatRuns.id), + billingCode: text("billing_code"), + provider: text("provider").notNull(), + biller: text("biller").notNull().default("unknown"), + billingType: text("billing_type").notNull().default("unknown"), + model: text("model").notNull(), + inputTokens: integer("input_tokens").notNull().default(0), + cachedInputTokens: integer("cached_input_tokens").notNull().default(0), + outputTokens: integer("output_tokens").notNull().default(0), + costCents: integer("cost_cents").notNull(), + occurredAt: timestamp("occurred_at", { withTimezone: true }).notNull(), + createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow() + }, + (table) => ({ + companyOccurredIdx: index("cost_events_company_occurred_idx").on(table.companyId, table.occurredAt), + companyAgentOccurredIdx: index("cost_events_company_agent_occurred_idx").on( + table.companyId, + table.agentId, + table.occurredAt + ), + companyProviderOccurredIdx: index("cost_events_company_provider_occurred_idx").on( + table.companyId, + table.provider, + table.occurredAt + ), + companyBillerOccurredIdx: index("cost_events_company_biller_occurred_idx").on( + table.companyId, + table.biller, + table.occurredAt + ), + companyHeartbeatRunIdx: index("cost_events_company_heartbeat_run_idx").on( + table.companyId, + table.heartbeatRunId + ) + }) + ); + } +}); + +// packages/db/src/schema/finance_events.ts +var financeEvents; +var init_finance_events = __esm({ + "packages/db/src/schema/finance_events.ts"() { + "use strict"; + init_pg_core(); + init_companies(); + init_agents(); + init_issues(); + init_projects(); + init_goals(); + init_heartbeat_runs(); + init_cost_events(); + financeEvents = pgTable( + "finance_events", + { + id: uuid("id").primaryKey().defaultRandom(), + companyId: uuid("company_id").notNull().references(() => companies.id), + agentId: uuid("agent_id").references(() => agents.id), + issueId: uuid("issue_id").references(() => issues.id), + projectId: uuid("project_id").references(() => projects.id), + goalId: uuid("goal_id").references(() => goals.id), + heartbeatRunId: uuid("heartbeat_run_id").references(() => heartbeatRuns.id), + costEventId: uuid("cost_event_id").references(() => costEvents.id), + billingCode: text("billing_code"), + description: text("description"), + eventKind: text("event_kind").notNull(), + direction: text("direction").notNull().default("debit"), + biller: text("biller").notNull(), + provider: text("provider"), + executionAdapterType: text("execution_adapter_type"), + pricingTier: text("pricing_tier"), + region: text("region"), + model: text("model"), + quantity: integer("quantity"), + unit: text("unit"), + amountCents: integer("amount_cents").notNull(), + currency: text("currency").notNull().default("USD"), + estimated: boolean("estimated").notNull().default(false), + externalInvoiceId: text("external_invoice_id"), + metadataJson: jsonb("metadata_json").$type(), + occurredAt: timestamp("occurred_at", { withTimezone: true }).notNull(), + createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow() + }, + (table) => ({ + companyOccurredIdx: index("finance_events_company_occurred_idx").on(table.companyId, table.occurredAt), + companyBillerOccurredIdx: index("finance_events_company_biller_occurred_idx").on( + table.companyId, + table.biller, + table.occurredAt + ), + companyKindOccurredIdx: index("finance_events_company_kind_occurred_idx").on( + table.companyId, + table.eventKind, + table.occurredAt + ), + companyDirectionOccurredIdx: index("finance_events_company_direction_occurred_idx").on( + table.companyId, + table.direction, + table.occurredAt + ), + companyHeartbeatRunIdx: index("finance_events_company_heartbeat_run_idx").on( + table.companyId, + table.heartbeatRunId + ), + companyCostEventIdx: index("finance_events_company_cost_event_idx").on( + table.companyId, + table.costEventId + ) + }) + ); + } +}); + +// packages/db/src/schema/approval_comments.ts +var approvalComments; +var init_approval_comments = __esm({ + "packages/db/src/schema/approval_comments.ts"() { + "use strict"; + init_pg_core(); + init_companies(); + init_approvals(); + init_agents(); + approvalComments = pgTable( + "approval_comments", + { + id: uuid("id").primaryKey().defaultRandom(), + companyId: uuid("company_id").notNull().references(() => companies.id), + approvalId: uuid("approval_id").notNull().references(() => approvals.id), + authorAgentId: uuid("author_agent_id").references(() => agents.id), + authorUserId: text("author_user_id"), + body: text("body").notNull(), + createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), + updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() + }, + (table) => ({ + companyIdx: index("approval_comments_company_idx").on(table.companyId), + approvalIdx: index("approval_comments_approval_idx").on(table.approvalId), + approvalCreatedIdx: index("approval_comments_approval_created_idx").on( + table.approvalId, + table.createdAt + ) + }) + ); + } +}); + +// packages/db/src/schema/activity_log.ts +var activityLog; +var init_activity_log = __esm({ + "packages/db/src/schema/activity_log.ts"() { + "use strict"; + init_pg_core(); + init_companies(); + init_agents(); + init_heartbeat_runs(); + activityLog = pgTable( + "activity_log", + { + id: uuid("id").primaryKey().defaultRandom(), + companyId: uuid("company_id").notNull().references(() => companies.id), + actorType: text("actor_type").notNull().default("system"), + actorId: text("actor_id").notNull(), + action: text("action").notNull(), + entityType: text("entity_type").notNull(), + entityId: text("entity_id").notNull(), + agentId: uuid("agent_id").references(() => agents.id), + runId: uuid("run_id").references(() => heartbeatRuns.id), + details: jsonb("details").$type(), + createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow() + }, + (table) => ({ + companyCreatedIdx: index("activity_log_company_created_idx").on(table.companyId, table.createdAt), + runIdIdx: index("activity_log_run_id_idx").on(table.runId), + entityIdx: index("activity_log_entity_type_id_idx").on(table.entityType, table.entityId) + }) + ); + } +}); + +// packages/db/src/schema/company_secret_versions.ts +var companySecretVersions; +var init_company_secret_versions = __esm({ + "packages/db/src/schema/company_secret_versions.ts"() { + "use strict"; + init_pg_core(); + init_agents(); + init_company_secrets(); + companySecretVersions = pgTable( + "company_secret_versions", + { + id: uuid("id").primaryKey().defaultRandom(), + secretId: uuid("secret_id").notNull().references(() => companySecrets.id, { onDelete: "cascade" }), + version: integer("version").notNull(), + material: jsonb("material").$type().notNull(), + valueSha256: text("value_sha256").notNull(), + createdByAgentId: uuid("created_by_agent_id").references(() => agents.id, { onDelete: "set null" }), + createdByUserId: text("created_by_user_id"), + createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), + revokedAt: timestamp("revoked_at", { withTimezone: true }) + }, + (table) => ({ + secretIdx: index("company_secret_versions_secret_idx").on(table.secretId, table.createdAt), + valueHashIdx: index("company_secret_versions_value_sha256_idx").on(table.valueSha256), + secretVersionUq: uniqueIndex("company_secret_versions_secret_version_uq").on(table.secretId, table.version) + }) + ); + } +}); + +// packages/db/src/schema/company_skills.ts +var companySkills; +var init_company_skills = __esm({ + "packages/db/src/schema/company_skills.ts"() { + "use strict"; + init_pg_core(); + init_companies(); + companySkills = pgTable( + "company_skills", + { + id: uuid("id").primaryKey().defaultRandom(), + companyId: uuid("company_id").notNull().references(() => companies.id), + key: text("key").notNull(), + slug: text("slug").notNull(), + name: text("name").notNull(), + description: text("description"), + markdown: text("markdown").notNull(), + sourceType: text("source_type").notNull().default("local_path"), + sourceLocator: text("source_locator"), + sourceRef: text("source_ref"), + trustLevel: text("trust_level").notNull().default("markdown_only"), + compatibility: text("compatibility").notNull().default("compatible"), + fileInventory: jsonb("file_inventory").$type().notNull().default([]), + metadata: jsonb("metadata").$type(), + createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), + updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() + }, + (table) => ({ + companyKeyUniqueIdx: uniqueIndex("company_skills_company_key_idx").on(table.companyId, table.key), + companyNameIdx: index("company_skills_company_name_idx").on(table.companyId, table.name) + }) + ); + } +}); + +// packages/db/src/schema/plugins.ts +var plugins; +var init_plugins = __esm({ + "packages/db/src/schema/plugins.ts"() { + "use strict"; + init_pg_core(); + plugins = pgTable( + "plugins", + { + id: uuid("id").primaryKey().defaultRandom(), + pluginKey: text("plugin_key").notNull(), + packageName: text("package_name").notNull(), + version: text("version").notNull(), + apiVersion: integer("api_version").notNull().default(1), + categories: jsonb("categories").$type().notNull().default([]), + manifestJson: jsonb("manifest_json").$type().notNull(), + status: text("status").$type().notNull().default("installed"), + installOrder: integer("install_order"), + /** Resolved package path for local-path installs; used to find worker entrypoint. */ + packagePath: text("package_path"), + lastError: text("last_error"), + installedAt: timestamp("installed_at", { withTimezone: true }).notNull().defaultNow(), + updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() + }, + (table) => ({ + pluginKeyIdx: uniqueIndex("plugins_plugin_key_idx").on(table.pluginKey), + statusIdx: index("plugins_status_idx").on(table.status) + }) + ); + } +}); + +// packages/db/src/schema/plugin_config.ts +var pluginConfig; +var init_plugin_config = __esm({ + "packages/db/src/schema/plugin_config.ts"() { + "use strict"; + init_pg_core(); + init_plugins(); + pluginConfig = pgTable( + "plugin_config", + { + id: uuid("id").primaryKey().defaultRandom(), + pluginId: uuid("plugin_id").notNull().references(() => plugins.id, { onDelete: "cascade" }), + configJson: jsonb("config_json").$type().notNull().default({}), + lastError: text("last_error"), + createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), + updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() + }, + (table) => ({ + pluginIdIdx: uniqueIndex("plugin_config_plugin_id_idx").on(table.pluginId) + }) + ); + } +}); + +// packages/db/src/schema/plugin_company_settings.ts +var pluginCompanySettings; +var init_plugin_company_settings = __esm({ + "packages/db/src/schema/plugin_company_settings.ts"() { + "use strict"; + init_pg_core(); + init_companies(); + init_plugins(); + pluginCompanySettings = pgTable( + "plugin_company_settings", + { + id: uuid("id").primaryKey().defaultRandom(), + companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }), + pluginId: uuid("plugin_id").notNull().references(() => plugins.id, { onDelete: "cascade" }), + enabled: boolean("enabled").notNull().default(true), + settingsJson: jsonb("settings_json").$type().notNull().default({}), + lastError: text("last_error"), + createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), + updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() + }, + (table) => ({ + companyIdx: index("plugin_company_settings_company_idx").on(table.companyId), + pluginIdx: index("plugin_company_settings_plugin_idx").on(table.pluginId), + companyPluginUq: uniqueIndex("plugin_company_settings_company_plugin_uq").on( + table.companyId, + table.pluginId + ) + }) + ); + } +}); + +// packages/db/src/schema/plugin_state.ts +var pluginState; +var init_plugin_state = __esm({ + "packages/db/src/schema/plugin_state.ts"() { + "use strict"; + init_pg_core(); + init_plugins(); + pluginState = pgTable( + "plugin_state", + { + id: uuid("id").primaryKey().defaultRandom(), + /** FK to the owning plugin. Cascades on delete. */ + pluginId: uuid("plugin_id").notNull().references(() => plugins.id, { onDelete: "cascade" }), + /** Granularity of the scope (e.g. `"instance"`, `"project"`, `"issue"`). */ + scopeKind: text("scope_kind").$type().notNull(), + /** + * UUID or text identifier for the scoped object. + * Null for `instance` scope (which has no associated entity). + */ + scopeId: text("scope_id"), + /** + * Sub-namespace to avoid key collisions within a scope. + * Defaults to `"default"` if the plugin does not specify one. + */ + namespace: text("namespace").notNull().default("default"), + /** The key identifying this state entry within the namespace. */ + stateKey: text("state_key").notNull(), + /** JSON-serializable value stored by the plugin. */ + valueJson: jsonb("value_json").notNull(), + /** Timestamp of the most recent write. */ + updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() + }, + (table) => ({ + /** + * Unique constraint enforces that there is at most one value per + * (plugin, scope kind, scope id, namespace, key) tuple. + * + * `nullsNotDistinct()` is required so that `scope_id IS NULL` entries + * (used by `instance` scope) are treated as equal by PostgreSQL rather + * than as distinct nulls — otherwise the upsert target in `set()` would + * fail to match existing rows and create duplicates. + * + * Requires PostgreSQL 15+. + */ + uniqueEntry: unique("plugin_state_unique_entry_idx").on( + table.pluginId, + table.scopeKind, + table.scopeId, + table.namespace, + table.stateKey + ).nullsNotDistinct(), + /** Speed up lookups by plugin + scope kind (most common access pattern). */ + pluginScopeIdx: index("plugin_state_plugin_scope_idx").on( + table.pluginId, + table.scopeKind + ) + }) + ); + } +}); + +// packages/db/src/schema/plugin_entities.ts +var pluginEntities; +var init_plugin_entities = __esm({ + "packages/db/src/schema/plugin_entities.ts"() { + "use strict"; + init_pg_core(); + init_plugins(); + pluginEntities = pgTable( + "plugin_entities", + { + id: uuid("id").primaryKey().defaultRandom(), + pluginId: uuid("plugin_id").notNull().references(() => plugins.id, { onDelete: "cascade" }), + entityType: text("entity_type").notNull(), + scopeKind: text("scope_kind").$type().notNull(), + scopeId: text("scope_id"), + // NULL for global scope (text to match plugin_state.scope_id) + externalId: text("external_id"), + // ID in the external system + title: text("title"), + status: text("status"), + data: jsonb("data").$type().notNull().default({}), + createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), + updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() + }, + (table) => ({ + pluginIdx: index("plugin_entities_plugin_idx").on(table.pluginId), + typeIdx: index("plugin_entities_type_idx").on(table.entityType), + scopeIdx: index("plugin_entities_scope_idx").on(table.scopeKind, table.scopeId), + externalIdx: uniqueIndex("plugin_entities_external_idx").on( + table.pluginId, + table.entityType, + table.externalId + ) + }) + ); + } +}); + +// packages/db/src/schema/plugin_jobs.ts +var pluginJobs, pluginJobRuns; +var init_plugin_jobs = __esm({ + "packages/db/src/schema/plugin_jobs.ts"() { + "use strict"; + init_pg_core(); + init_plugins(); + pluginJobs = pgTable( + "plugin_jobs", + { + id: uuid("id").primaryKey().defaultRandom(), + /** FK to the owning plugin. Cascades on delete. */ + pluginId: uuid("plugin_id").notNull().references(() => plugins.id, { onDelete: "cascade" }), + /** Identifier matching the key in the plugin manifest's `jobs` array. */ + jobKey: text("job_key").notNull(), + /** Cron expression (e.g. `"0 * * * *"`) or interval string. */ + schedule: text("schedule").notNull(), + /** Current scheduling state. */ + status: text("status").$type().notNull().default("active"), + /** Timestamp of the most recent successful execution. */ + lastRunAt: timestamp("last_run_at", { withTimezone: true }), + /** Pre-computed timestamp of the next scheduled execution. */ + nextRunAt: timestamp("next_run_at", { withTimezone: true }), + createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), + updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() + }, + (table) => ({ + pluginIdx: index("plugin_jobs_plugin_idx").on(table.pluginId), + nextRunIdx: index("plugin_jobs_next_run_idx").on(table.nextRunAt), + uniqueJobIdx: uniqueIndex("plugin_jobs_unique_idx").on(table.pluginId, table.jobKey) + }) + ); + pluginJobRuns = pgTable( + "plugin_job_runs", + { + id: uuid("id").primaryKey().defaultRandom(), + /** FK to the parent job definition. Cascades on delete. */ + jobId: uuid("job_id").notNull().references(() => pluginJobs.id, { onDelete: "cascade" }), + /** Denormalized FK to the owning plugin for efficient querying. Cascades on delete. */ + pluginId: uuid("plugin_id").notNull().references(() => plugins.id, { onDelete: "cascade" }), + /** What caused this run to start (`"scheduled"` or `"manual"`). */ + trigger: text("trigger").$type().notNull(), + /** Current lifecycle state of this run. */ + status: text("status").$type().notNull().default("pending"), + /** Wall-clock duration in milliseconds. Null until the run finishes. */ + durationMs: integer("duration_ms"), + /** Error message if `status === "failed"`. */ + error: text("error"), + /** Ordered list of log lines emitted during this run. */ + logs: jsonb("logs").$type().notNull().default([]), + startedAt: timestamp("started_at", { withTimezone: true }), + finishedAt: timestamp("finished_at", { withTimezone: true }), + createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow() + }, + (table) => ({ + jobIdx: index("plugin_job_runs_job_idx").on(table.jobId), + pluginIdx: index("plugin_job_runs_plugin_idx").on(table.pluginId), + statusIdx: index("plugin_job_runs_status_idx").on(table.status) + }) + ); + } +}); + +// packages/db/src/schema/plugin_webhooks.ts +var pluginWebhookDeliveries; +var init_plugin_webhooks = __esm({ + "packages/db/src/schema/plugin_webhooks.ts"() { + "use strict"; + init_pg_core(); + init_plugins(); + pluginWebhookDeliveries = pgTable( + "plugin_webhook_deliveries", + { + id: uuid("id").primaryKey().defaultRandom(), + /** FK to the owning plugin. Cascades on delete. */ + pluginId: uuid("plugin_id").notNull().references(() => plugins.id, { onDelete: "cascade" }), + /** Identifier matching the key in the plugin manifest's `webhooks` array. */ + webhookKey: text("webhook_key").notNull(), + /** Optional de-duplication ID provided by the external system. */ + externalId: text("external_id"), + /** Current delivery state. */ + status: text("status").$type().notNull().default("pending"), + /** Wall-clock processing duration in milliseconds. Null until delivery finishes. */ + durationMs: integer("duration_ms"), + /** Error message if `status === "failed"`. */ + error: text("error"), + /** Raw JSON body of the inbound HTTP request. */ + payload: jsonb("payload").$type().notNull(), + /** Relevant HTTP headers from the inbound request (e.g. signature headers). */ + headers: jsonb("headers").$type().notNull().default({}), + startedAt: timestamp("started_at", { withTimezone: true }), + finishedAt: timestamp("finished_at", { withTimezone: true }), + createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow() + }, + (table) => ({ + pluginIdx: index("plugin_webhook_deliveries_plugin_idx").on(table.pluginId), + statusIdx: index("plugin_webhook_deliveries_status_idx").on(table.status), + keyIdx: index("plugin_webhook_deliveries_key_idx").on(table.webhookKey) + }) + ); + } +}); + +// packages/db/src/schema/plugin_logs.ts +var pluginLogs; +var init_plugin_logs = __esm({ + "packages/db/src/schema/plugin_logs.ts"() { + "use strict"; + init_pg_core(); + init_plugins(); + pluginLogs = pgTable( + "plugin_logs", + { + id: uuid("id").primaryKey().defaultRandom(), + pluginId: uuid("plugin_id").notNull().references(() => plugins.id, { onDelete: "cascade" }), + level: text("level").notNull().default("info"), + message: text("message").notNull(), + meta: jsonb("meta").$type(), + createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow() + }, + (table) => ({ + pluginTimeIdx: index("plugin_logs_plugin_time_idx").on( + table.pluginId, + table.createdAt + ), + levelIdx: index("plugin_logs_level_idx").on(table.level) + }) + ); + } +}); + +// packages/db/src/schema/index.ts +var schema_exports = {}; +__export(schema_exports, { + activityLog: () => activityLog, + agentApiKeys: () => agentApiKeys, + agentConfigRevisions: () => agentConfigRevisions, + agentRuntimeState: () => agentRuntimeState, + agentTaskSessions: () => agentTaskSessions, + agentWakeupRequests: () => agentWakeupRequests, + agents: () => agents, + approvalComments: () => approvalComments, + approvals: () => approvals, + assets: () => assets, + authAccounts: () => authAccounts, + authSessions: () => authSessions, + authUsers: () => authUsers, + authVerifications: () => authVerifications, + boardApiKeys: () => boardApiKeys, + budgetIncidents: () => budgetIncidents, + budgetPolicies: () => budgetPolicies, + cliAuthChallenges: () => cliAuthChallenges, + companies: () => companies, + companyLogos: () => companyLogos, + companyMemberships: () => companyMemberships, + companySecretVersions: () => companySecretVersions, + companySecrets: () => companySecrets, + companySkills: () => companySkills, + companyUserSidebarPreferences: () => companyUserSidebarPreferences, + costEvents: () => costEvents, + documentRevisions: () => documentRevisions, + documents: () => documents, + executionWorkspaces: () => executionWorkspaces, + feedbackExports: () => feedbackExports, + feedbackVotes: () => feedbackVotes, + financeEvents: () => financeEvents, + goals: () => goals, + heartbeatRunEvents: () => heartbeatRunEvents, + heartbeatRuns: () => heartbeatRuns, + inboxDismissals: () => inboxDismissals, + instanceSettings: () => instanceSettings, + instanceUserRoles: () => instanceUserRoles, + invites: () => invites, + issueApprovals: () => issueApprovals, + issueAttachments: () => issueAttachments, + issueComments: () => issueComments, + issueDocuments: () => issueDocuments, + issueExecutionDecisions: () => issueExecutionDecisions, + issueInboxArchives: () => issueInboxArchives, + issueLabels: () => issueLabels, + issueReadStates: () => issueReadStates, + issueRelations: () => issueRelations, + issueWorkProducts: () => issueWorkProducts, + issues: () => issues, + joinRequests: () => joinRequests, + labels: () => labels, + pluginCompanySettings: () => pluginCompanySettings, + pluginConfig: () => pluginConfig, + pluginEntities: () => pluginEntities, + pluginJobRuns: () => pluginJobRuns, + pluginJobs: () => pluginJobs, + pluginLogs: () => pluginLogs, + pluginState: () => pluginState, + pluginWebhookDeliveries: () => pluginWebhookDeliveries, + plugins: () => plugins, + principalPermissionGrants: () => principalPermissionGrants, + projectGoals: () => projectGoals, + projectWorkspaces: () => projectWorkspaces, + projects: () => projects, + routineRuns: () => routineRuns, + routineTriggers: () => routineTriggers, + routines: () => routines, + userSidebarPreferences: () => userSidebarPreferences, + workspaceOperations: () => workspaceOperations, + workspaceRuntimeServices: () => workspaceRuntimeServices +}); +var init_schema2 = __esm({ + "packages/db/src/schema/index.ts"() { + "use strict"; + init_companies(); + init_company_logos(); + init_auth(); + init_instance_settings(); + init_instance_user_roles(); + init_user_sidebar_preferences(); + init_agents(); + init_board_api_keys(); + init_cli_auth_challenges(); + init_company_memberships(); + init_company_user_sidebar_preferences(); + init_principal_permission_grants(); + init_invites(); + init_join_requests(); + init_budget_policies(); + init_budget_incidents(); + init_agent_config_revisions(); + init_agent_api_keys(); + init_agent_runtime_state(); + init_agent_task_sessions(); + init_agent_wakeup_requests(); + init_projects(); + init_project_workspaces(); + init_execution_workspaces(); + init_workspace_operations(); + init_workspace_runtime_services(); + init_project_goals(); + init_goals(); + init_issues(); + init_issue_relations(); + init_routines(); + init_issue_work_products(); + init_labels(); + init_issue_labels(); + init_issue_approvals(); + init_issue_comments(); + init_issue_execution_decisions(); + init_issue_inbox_archives(); + init_inbox_dismissals(); + init_feedback_votes(); + init_feedback_exports(); + init_issue_read_states(); + init_assets(); + init_issue_attachments(); + init_documents(); + init_document_revisions(); + init_issue_documents(); + init_heartbeat_runs(); + init_heartbeat_run_events(); + init_cost_events(); + init_finance_events(); + init_approvals(); + init_approval_comments(); + init_activity_log(); + init_company_secrets(); + init_company_secret_versions(); + init_company_skills(); + init_plugins(); + init_plugin_config(); + init_plugin_company_settings(); + init_plugin_state(); + init_plugin_entities(); + init_plugin_jobs(); + init_plugin_webhooks(); + init_plugin_logs(); + } +}); + +// packages/db/src/client.ts +import { fileURLToPath } from "node:url"; +function createDb(url2, options) { + const opts = {}; + if (options?.max !== void 0) opts.max = options.max; + if (options?.prepare !== void 0) opts.prepare = options.prepare; + const sql3 = src_default(url2, opts); + return drizzle(sql3, { schema: schema_exports }); +} +var MIGRATIONS_FOLDER, MIGRATIONS_JOURNAL_JSON; +var init_client = __esm({ + "packages/db/src/client.ts"() { + "use strict"; + init_postgres_js(); + init_src(); + init_schema2(); + MIGRATIONS_FOLDER = fileURLToPath(new URL("./migrations", import.meta.url)); + MIGRATIONS_JOURNAL_JSON = fileURLToPath(new URL("./migrations/meta/_journal.json", import.meta.url)); + } +}); + +// packages/db/src/test-embedded-postgres.ts +var init_test_embedded_postgres = __esm({ + "packages/db/src/test-embedded-postgres.ts"() { + "use strict"; + init_client(); + } +}); + +// packages/db/src/backup-lib.ts +var DEFAULT_BACKUP_WRITE_BUFFER_BYTES; +var init_backup_lib = __esm({ + "packages/db/src/backup-lib.ts"() { + "use strict"; + init_src(); + DEFAULT_BACKUP_WRITE_BUFFER_BYTES = 1024 * 1024; + } +}); + +// packages/db/src/embedded-postgres-error.ts +var init_embedded_postgres_error = __esm({ + "packages/db/src/embedded-postgres-error.ts"() { + "use strict"; + } +}); + +// packages/db/src/index.ts +var init_src2 = __esm({ + "packages/db/src/index.ts"() { + "use strict"; + init_client(); + init_test_embedded_postgres(); + init_backup_lib(); + init_embedded_postgres_error(); + init_issue_relations(); + init_schema2(); + } +}); + +// node_modules/.pnpm/ms@2.1.3/node_modules/ms/index.js +var require_ms = __commonJS({ + "node_modules/.pnpm/ms@2.1.3/node_modules/ms/index.js"(exports, module) { + var s5 = 1e3; + var m5 = s5 * 60; + var h5 = m5 * 60; + var d5 = h5 * 24; + var w5 = d5 * 7; + var y2 = d5 * 365.25; + module.exports = function(val, options) { + options = options || {}; + var type = typeof val; + if (type === "string" && val.length > 0) { + return parse5(val); + } else if (type === "number" && isFinite(val)) { + return options.long ? fmtLong(val) : fmtShort(val); + } + throw new Error( + "val is not a non-empty string or a valid number. val=" + JSON.stringify(val) + ); + }; + function parse5(str) { + str = String(str); + if (str.length > 100) { + return; + } + var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( + str + ); + if (!match) { + return; + } + var n5 = parseFloat(match[1]); + var type = (match[2] || "ms").toLowerCase(); + switch (type) { + case "years": + case "year": + case "yrs": + case "yr": + case "y": + return n5 * y2; + case "weeks": + case "week": + case "w": + return n5 * w5; + case "days": + case "day": + case "d": + return n5 * d5; + case "hours": + case "hour": + case "hrs": + case "hr": + case "h": + return n5 * h5; + case "minutes": + case "minute": + case "mins": + case "min": + case "m": + return n5 * m5; + case "seconds": + case "second": + case "secs": + case "sec": + case "s": + return n5 * s5; + case "milliseconds": + case "millisecond": + case "msecs": + case "msec": + case "ms": + return n5; + default: + return void 0; + } + } + function fmtShort(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d5) { + return Math.round(ms / d5) + "d"; + } + if (msAbs >= h5) { + return Math.round(ms / h5) + "h"; + } + if (msAbs >= m5) { + return Math.round(ms / m5) + "m"; + } + if (msAbs >= s5) { + return Math.round(ms / s5) + "s"; + } + return ms + "ms"; + } + function fmtLong(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d5) { + return plural(ms, msAbs, d5, "day"); + } + if (msAbs >= h5) { + return plural(ms, msAbs, h5, "hour"); + } + if (msAbs >= m5) { + return plural(ms, msAbs, m5, "minute"); + } + if (msAbs >= s5) { + return plural(ms, msAbs, s5, "second"); + } + return ms + " ms"; + } + function plural(ms, msAbs, n5, name) { + var isPlural = msAbs >= n5 * 1.5; + return Math.round(ms / n5) + " " + name + (isPlural ? "s" : ""); + } + } +}); + +// node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/common.js +var require_common = __commonJS({ + "node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/common.js"(exports, module) { + function setup(env2) { + createDebug.debug = createDebug; + createDebug.default = createDebug; + createDebug.coerce = coerce2; + createDebug.disable = disable; + createDebug.enable = enable; + createDebug.enabled = enabled; + createDebug.humanize = require_ms(); + createDebug.destroy = destroy; + Object.keys(env2).forEach((key) => { + createDebug[key] = env2[key]; + }); + createDebug.names = []; + createDebug.skips = []; + createDebug.formatters = {}; + function selectColor(namespace) { + let hash2 = 0; + for (let i5 = 0; i5 < namespace.length; i5++) { + hash2 = (hash2 << 5) - hash2 + namespace.charCodeAt(i5); + hash2 |= 0; + } + return createDebug.colors[Math.abs(hash2) % createDebug.colors.length]; + } + createDebug.selectColor = selectColor; + function createDebug(namespace) { + let prevTime; + let enableOverride = null; + let namespacesCache; + let enabledCache; + function debug(...args) { + if (!debug.enabled) { + return; + } + const self2 = debug; + const curr = Number(/* @__PURE__ */ new Date()); + const ms = curr - (prevTime || curr); + self2.diff = ms; + self2.prev = prevTime; + self2.curr = curr; + prevTime = curr; + args[0] = createDebug.coerce(args[0]); + if (typeof args[0] !== "string") { + args.unshift("%O"); + } + let index2 = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format2) => { + if (match === "%%") { + return "%"; + } + index2++; + const formatter = createDebug.formatters[format2]; + if (typeof formatter === "function") { + const val = args[index2]; + match = formatter.call(self2, val); + args.splice(index2, 1); + index2--; + } + return match; + }); + createDebug.formatArgs.call(self2, args); + const logFn = self2.log || createDebug.log; + logFn.apply(self2, args); + } + debug.namespace = namespace; + debug.useColors = createDebug.useColors(); + debug.color = createDebug.selectColor(namespace); + debug.extend = extend2; + debug.destroy = createDebug.destroy; + Object.defineProperty(debug, "enabled", { + enumerable: true, + configurable: false, + get: () => { + if (enableOverride !== null) { + return enableOverride; + } + if (namespacesCache !== createDebug.namespaces) { + namespacesCache = createDebug.namespaces; + enabledCache = createDebug.enabled(namespace); + } + return enabledCache; + }, + set: (v5) => { + enableOverride = v5; + } + }); + if (typeof createDebug.init === "function") { + createDebug.init(debug); + } + return debug; + } + function extend2(namespace, delimiter) { + const newDebug = createDebug(this.namespace + (typeof delimiter === "undefined" ? ":" : delimiter) + namespace); + newDebug.log = this.log; + return newDebug; + } + function enable(namespaces) { + createDebug.save(namespaces); + createDebug.namespaces = namespaces; + createDebug.names = []; + createDebug.skips = []; + const split = (typeof namespaces === "string" ? namespaces : "").trim().replace(/\s+/g, ",").split(",").filter(Boolean); + for (const ns of split) { + if (ns[0] === "-") { + createDebug.skips.push(ns.slice(1)); + } else { + createDebug.names.push(ns); + } + } + } + function matchesTemplate(search, template) { + let searchIndex = 0; + let templateIndex = 0; + let starIndex = -1; + let matchIndex = 0; + while (searchIndex < search.length) { + if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === "*")) { + if (template[templateIndex] === "*") { + starIndex = templateIndex; + matchIndex = searchIndex; + templateIndex++; + } else { + searchIndex++; + templateIndex++; + } + } else if (starIndex !== -1) { + templateIndex = starIndex + 1; + matchIndex++; + searchIndex = matchIndex; + } else { + return false; + } + } + while (templateIndex < template.length && template[templateIndex] === "*") { + templateIndex++; + } + return templateIndex === template.length; + } + function disable() { + const namespaces = [ + ...createDebug.names, + ...createDebug.skips.map((namespace) => "-" + namespace) + ].join(","); + createDebug.enable(""); + return namespaces; + } + function enabled(name) { + for (const skip of createDebug.skips) { + if (matchesTemplate(name, skip)) { + return false; + } + } + for (const ns of createDebug.names) { + if (matchesTemplate(name, ns)) { + return true; + } + } + return false; + } + function coerce2(val) { + if (val instanceof Error) { + return val.stack || val.message; + } + return val; + } + function destroy() { + console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."); + } + createDebug.enable(createDebug.load()); + return createDebug; + } + module.exports = setup; + } +}); + +// node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/browser.js +var require_browser = __commonJS({ + "node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/browser.js"(exports, module) { + exports.formatArgs = formatArgs; + exports.save = save; + exports.load = load; + exports.useColors = useColors; + exports.storage = localstorage(); + exports.destroy = /* @__PURE__ */ (() => { + let warned = false; + return () => { + if (!warned) { + warned = true; + console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."); + } + }; + })(); + exports.colors = [ + "#0000CC", + "#0000FF", + "#0033CC", + "#0033FF", + "#0066CC", + "#0066FF", + "#0099CC", + "#0099FF", + "#00CC00", + "#00CC33", + "#00CC66", + "#00CC99", + "#00CCCC", + "#00CCFF", + "#3300CC", + "#3300FF", + "#3333CC", + "#3333FF", + "#3366CC", + "#3366FF", + "#3399CC", + "#3399FF", + "#33CC00", + "#33CC33", + "#33CC66", + "#33CC99", + "#33CCCC", + "#33CCFF", + "#6600CC", + "#6600FF", + "#6633CC", + "#6633FF", + "#66CC00", + "#66CC33", + "#9900CC", + "#9900FF", + "#9933CC", + "#9933FF", + "#99CC00", + "#99CC33", + "#CC0000", + "#CC0033", + "#CC0066", + "#CC0099", + "#CC00CC", + "#CC00FF", + "#CC3300", + "#CC3333", + "#CC3366", + "#CC3399", + "#CC33CC", + "#CC33FF", + "#CC6600", + "#CC6633", + "#CC9900", + "#CC9933", + "#CCCC00", + "#CCCC33", + "#FF0000", + "#FF0033", + "#FF0066", + "#FF0099", + "#FF00CC", + "#FF00FF", + "#FF3300", + "#FF3333", + "#FF3366", + "#FF3399", + "#FF33CC", + "#FF33FF", + "#FF6600", + "#FF6633", + "#FF9900", + "#FF9933", + "#FFCC00", + "#FFCC33" + ]; + function useColors() { + if (typeof window !== "undefined" && window.process && (window.process.type === "renderer" || window.process.__nwjs)) { + return true; + } + if (typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { + return false; + } + let m5; + return typeof document !== "undefined" && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773 + typeof window !== "undefined" && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + typeof navigator !== "undefined" && navigator.userAgent && (m5 = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m5[1], 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker + typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/); + } + function formatArgs(args) { + args[0] = (this.useColors ? "%c" : "") + this.namespace + (this.useColors ? " %c" : " ") + args[0] + (this.useColors ? "%c " : " ") + "+" + module.exports.humanize(this.diff); + if (!this.useColors) { + return; + } + const c5 = "color: " + this.color; + args.splice(1, 0, c5, "color: inherit"); + let index2 = 0; + let lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, (match) => { + if (match === "%%") { + return; + } + index2++; + if (match === "%c") { + lastC = index2; + } + }); + args.splice(lastC, 0, c5); + } + exports.log = console.debug || console.log || (() => { + }); + function save(namespaces) { + try { + if (namespaces) { + exports.storage.setItem("debug", namespaces); + } else { + exports.storage.removeItem("debug"); + } + } catch (error50) { + } + } + function load() { + let r5; + try { + r5 = exports.storage.getItem("debug") || exports.storage.getItem("DEBUG"); + } catch (error50) { + } + if (!r5 && typeof process !== "undefined" && "env" in process) { + r5 = process.env.DEBUG; + } + return r5; + } + function localstorage() { + try { + return localStorage; + } catch (error50) { + } + } + module.exports = require_common()(exports); + var { formatters } = module.exports; + formatters.j = function(v5) { + try { + return JSON.stringify(v5); + } catch (error50) { + return "[UnexpectedJSONParseError]: " + error50.message; + } + }; + } +}); + +// node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/node.js +var require_node = __commonJS({ + "node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/node.js"(exports, module) { + var tty = __require("tty"); + var util2 = __require("util"); + exports.init = init2; + exports.log = log2; + exports.formatArgs = formatArgs; + exports.save = save; + exports.load = load; + exports.useColors = useColors; + exports.destroy = util2.deprecate( + () => { + }, + "Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`." + ); + exports.colors = [6, 2, 3, 4, 5, 1]; + try { + const supportsColor = __require("supports-color"); + if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { + exports.colors = [ + 20, + 21, + 26, + 27, + 32, + 33, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 56, + 57, + 62, + 63, + 68, + 69, + 74, + 75, + 76, + 77, + 78, + 79, + 80, + 81, + 92, + 93, + 98, + 99, + 112, + 113, + 128, + 129, + 134, + 135, + 148, + 149, + 160, + 161, + 162, + 163, + 164, + 165, + 166, + 167, + 168, + 169, + 170, + 171, + 172, + 173, + 178, + 179, + 184, + 185, + 196, + 197, + 198, + 199, + 200, + 201, + 202, + 203, + 204, + 205, + 206, + 207, + 208, + 209, + 214, + 215, + 220, + 221 + ]; + } + } catch (error50) { + } + exports.inspectOpts = Object.keys(process.env).filter((key) => { + return /^debug_/i.test(key); + }).reduce((obj, key) => { + const prop = key.substring(6).toLowerCase().replace(/_([a-z])/g, (_, k5) => { + return k5.toUpperCase(); + }); + let val = process.env[key]; + if (/^(yes|on|true|enabled)$/i.test(val)) { + val = true; + } else if (/^(no|off|false|disabled)$/i.test(val)) { + val = false; + } else if (val === "null") { + val = null; + } else { + val = Number(val); + } + obj[prop] = val; + return obj; + }, {}); + function useColors() { + return "colors" in exports.inspectOpts ? Boolean(exports.inspectOpts.colors) : tty.isatty(process.stderr.fd); + } + function formatArgs(args) { + const { namespace: name, useColors: useColors2 } = this; + if (useColors2) { + const c5 = this.color; + const colorCode = "\x1B[3" + (c5 < 8 ? c5 : "8;5;" + c5); + const prefix = ` ${colorCode};1m${name} \x1B[0m`; + args[0] = prefix + args[0].split("\n").join("\n" + prefix); + args.push(colorCode + "m+" + module.exports.humanize(this.diff) + "\x1B[0m"); + } else { + args[0] = getDate2() + name + " " + args[0]; + } + } + function getDate2() { + if (exports.inspectOpts.hideDate) { + return ""; + } + return (/* @__PURE__ */ new Date()).toISOString() + " "; + } + function log2(...args) { + return process.stderr.write(util2.formatWithOptions(exports.inspectOpts, ...args) + "\n"); + } + function save(namespaces) { + if (namespaces) { + process.env.DEBUG = namespaces; + } else { + delete process.env.DEBUG; + } + } + function load() { + return process.env.DEBUG; + } + function init2(debug) { + debug.inspectOpts = {}; + const keys = Object.keys(exports.inspectOpts); + for (let i5 = 0; i5 < keys.length; i5++) { + debug.inspectOpts[keys[i5]] = exports.inspectOpts[keys[i5]]; + } + } + module.exports = require_common()(exports); + var { formatters } = module.exports; + formatters.o = function(v5) { + this.inspectOpts.colors = this.useColors; + return util2.inspect(v5, this.inspectOpts).split("\n").map((str) => str.trim()).join(" "); + }; + formatters.O = function(v5) { + this.inspectOpts.colors = this.useColors; + return util2.inspect(v5, this.inspectOpts); + }; + } +}); + +// node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/index.js +var require_src = __commonJS({ + "node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/index.js"(exports, module) { + if (typeof process === "undefined" || process.type === "renderer" || process.browser === true || process.__nwjs) { + module.exports = require_browser(); + } else { + module.exports = require_node(); + } + } +}); + +// node_modules/.pnpm/depd@2.0.0/node_modules/depd/index.js +var require_depd = __commonJS({ + "node_modules/.pnpm/depd@2.0.0/node_modules/depd/index.js"(exports, module) { + var relative3 = __require("path").relative; + module.exports = depd; + var basePath = process.cwd(); + function containsNamespace(str, namespace) { + var vals = str.split(/[ ,]+/); + var ns = String(namespace).toLowerCase(); + for (var i5 = 0; i5 < vals.length; i5++) { + var val = vals[i5]; + if (val && (val === "*" || val.toLowerCase() === ns)) { + return true; + } + } + return false; + } + function convertDataDescriptorToAccessor(obj, prop, message2) { + var descriptor = Object.getOwnPropertyDescriptor(obj, prop); + var value = descriptor.value; + descriptor.get = function getter() { + return value; + }; + if (descriptor.writable) { + descriptor.set = function setter(val) { + return value = val; + }; + } + delete descriptor.value; + delete descriptor.writable; + Object.defineProperty(obj, prop, descriptor); + return descriptor; + } + function createArgumentsString(arity) { + var str = ""; + for (var i5 = 0; i5 < arity; i5++) { + str += ", arg" + i5; + } + return str.substr(2); + } + function createStackString(stack) { + var str = this.name + ": " + this.namespace; + if (this.message) { + str += " deprecated " + this.message; + } + for (var i5 = 0; i5 < stack.length; i5++) { + str += "\n at " + stack[i5].toString(); + } + return str; + } + function depd(namespace) { + if (!namespace) { + throw new TypeError("argument namespace is required"); + } + var stack = getStack(); + var site = callSiteLocation(stack[1]); + var file2 = site[0]; + function deprecate2(message2) { + log2.call(deprecate2, message2); + } + deprecate2._file = file2; + deprecate2._ignored = isignored(namespace); + deprecate2._namespace = namespace; + deprecate2._traced = istraced(namespace); + deprecate2._warned = /* @__PURE__ */ Object.create(null); + deprecate2.function = wrapfunction; + deprecate2.property = wrapproperty; + return deprecate2; + } + function eehaslisteners(emitter2, type) { + var count2 = typeof emitter2.listenerCount !== "function" ? emitter2.listeners(type).length : emitter2.listenerCount(type); + return count2 > 0; + } + function isignored(namespace) { + if (process.noDeprecation) { + return true; + } + var str = process.env.NO_DEPRECATION || ""; + return containsNamespace(str, namespace); + } + function istraced(namespace) { + if (process.traceDeprecation) { + return true; + } + var str = process.env.TRACE_DEPRECATION || ""; + return containsNamespace(str, namespace); + } + function log2(message2, site) { + var haslisteners = eehaslisteners(process, "deprecation"); + if (!haslisteners && this._ignored) { + return; + } + var caller; + var callFile; + var callSite; + var depSite; + var i5 = 0; + var seen = false; + var stack = getStack(); + var file2 = this._file; + if (site) { + depSite = site; + callSite = callSiteLocation(stack[1]); + callSite.name = depSite.name; + file2 = callSite[0]; + } else { + i5 = 2; + depSite = callSiteLocation(stack[i5]); + callSite = depSite; + } + for (; i5 < stack.length; i5++) { + caller = callSiteLocation(stack[i5]); + callFile = caller[0]; + if (callFile === file2) { + seen = true; + } else if (callFile === this._file) { + file2 = this._file; + } else if (seen) { + break; + } + } + var key = caller ? depSite.join(":") + "__" + caller.join(":") : void 0; + if (key !== void 0 && key in this._warned) { + return; + } + this._warned[key] = true; + var msg = message2; + if (!msg) { + msg = callSite === depSite || !callSite.name ? defaultMessage(depSite) : defaultMessage(callSite); + } + if (haslisteners) { + var err = DeprecationError(this._namespace, msg, stack.slice(i5)); + process.emit("deprecation", err); + return; + } + var format2 = process.stderr.isTTY ? formatColor : formatPlain; + var output = format2.call(this, msg, caller, stack.slice(i5)); + process.stderr.write(output + "\n", "utf8"); + } + function callSiteLocation(callSite) { + var file2 = callSite.getFileName() || ""; + var line3 = callSite.getLineNumber(); + var colm = callSite.getColumnNumber(); + if (callSite.isEval()) { + file2 = callSite.getEvalOrigin() + ", " + file2; + } + var site = [file2, line3, colm]; + site.callSite = callSite; + site.name = callSite.getFunctionName(); + return site; + } + function defaultMessage(site) { + var callSite = site.callSite; + var funcName = site.name; + if (!funcName) { + funcName = ""; + } + var context = callSite.getThis(); + var typeName = context && callSite.getTypeName(); + if (typeName === "Object") { + typeName = void 0; + } + if (typeName === "Function") { + typeName = context.name || typeName; + } + return typeName && callSite.getMethodName() ? typeName + "." + funcName : funcName; + } + function formatPlain(msg, caller, stack) { + var timestamp2 = (/* @__PURE__ */ new Date()).toUTCString(); + var formatted = timestamp2 + " " + this._namespace + " deprecated " + msg; + if (this._traced) { + for (var i5 = 0; i5 < stack.length; i5++) { + formatted += "\n at " + stack[i5].toString(); + } + return formatted; + } + if (caller) { + formatted += " at " + formatLocation(caller); + } + return formatted; + } + function formatColor(msg, caller, stack) { + var formatted = "\x1B[36;1m" + this._namespace + "\x1B[22;39m \x1B[33;1mdeprecated\x1B[22;39m \x1B[0m" + msg + "\x1B[39m"; + if (this._traced) { + for (var i5 = 0; i5 < stack.length; i5++) { + formatted += "\n \x1B[36mat " + stack[i5].toString() + "\x1B[39m"; + } + return formatted; + } + if (caller) { + formatted += " \x1B[36m" + formatLocation(caller) + "\x1B[39m"; + } + return formatted; + } + function formatLocation(callSite) { + return relative3(basePath, callSite[0]) + ":" + callSite[1] + ":" + callSite[2]; + } + function getStack() { + var limit = Error.stackTraceLimit; + var obj = {}; + var prep = Error.prepareStackTrace; + Error.prepareStackTrace = prepareObjectStackTrace; + Error.stackTraceLimit = Math.max(10, limit); + Error.captureStackTrace(obj); + var stack = obj.stack.slice(1); + Error.prepareStackTrace = prep; + Error.stackTraceLimit = limit; + return stack; + } + function prepareObjectStackTrace(obj, stack) { + return stack; + } + function wrapfunction(fn, message2) { + if (typeof fn !== "function") { + throw new TypeError("argument fn must be a function"); + } + var args = createArgumentsString(fn.length); + var stack = getStack(); + var site = callSiteLocation(stack[1]); + site.name = fn.name; + var deprecatedfn = new Function( + "fn", + "log", + "deprecate", + "message", + "site", + '"use strict"\nreturn function (' + args + ") {log.call(deprecate, message, site)\nreturn fn.apply(this, arguments)\n}" + )(fn, log2, this, message2, site); + return deprecatedfn; + } + function wrapproperty(obj, prop, message2) { + if (!obj || typeof obj !== "object" && typeof obj !== "function") { + throw new TypeError("argument obj must be object"); + } + var descriptor = Object.getOwnPropertyDescriptor(obj, prop); + if (!descriptor) { + throw new TypeError("must call property on owner object"); + } + if (!descriptor.configurable) { + throw new TypeError("property must be configurable"); + } + var deprecate2 = this; + var stack = getStack(); + var site = callSiteLocation(stack[1]); + site.name = prop; + if ("value" in descriptor) { + descriptor = convertDataDescriptorToAccessor(obj, prop, message2); + } + var get2 = descriptor.get; + var set2 = descriptor.set; + if (typeof get2 === "function") { + descriptor.get = function getter() { + log2.call(deprecate2, message2, site); + return get2.apply(this, arguments); + }; + } + if (typeof set2 === "function") { + descriptor.set = function setter() { + log2.call(deprecate2, message2, site); + return set2.apply(this, arguments); + }; + } + Object.defineProperty(obj, prop, descriptor); + } + function DeprecationError(namespace, message2, stack) { + var error50 = new Error(); + var stackString; + Object.defineProperty(error50, "constructor", { + value: DeprecationError + }); + Object.defineProperty(error50, "message", { + configurable: true, + enumerable: false, + value: message2, + writable: true + }); + Object.defineProperty(error50, "name", { + enumerable: false, + configurable: true, + value: "DeprecationError", + writable: true + }); + Object.defineProperty(error50, "namespace", { + configurable: true, + enumerable: false, + value: namespace, + writable: true + }); + Object.defineProperty(error50, "stack", { + configurable: true, + enumerable: false, + get: function() { + if (stackString !== void 0) { + return stackString; + } + return stackString = createStackString.call(this, stack); + }, + set: function setter(val) { + stackString = val; + } + }); + return error50; + } + } +}); + +// node_modules/.pnpm/setprototypeof@1.2.0/node_modules/setprototypeof/index.js +var require_setprototypeof = __commonJS({ + "node_modules/.pnpm/setprototypeof@1.2.0/node_modules/setprototypeof/index.js"(exports, module) { + "use strict"; + module.exports = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array ? setProtoOf : mixinProperties); + function setProtoOf(obj, proto) { + obj.__proto__ = proto; + return obj; + } + function mixinProperties(obj, proto) { + for (var prop in proto) { + if (!Object.prototype.hasOwnProperty.call(obj, prop)) { + obj[prop] = proto[prop]; + } + } + return obj; + } + } +}); + +// node_modules/.pnpm/statuses@2.0.2/node_modules/statuses/codes.json +var require_codes = __commonJS({ + "node_modules/.pnpm/statuses@2.0.2/node_modules/statuses/codes.json"(exports, module) { + module.exports = { + "100": "Continue", + "101": "Switching Protocols", + "102": "Processing", + "103": "Early Hints", + "200": "OK", + "201": "Created", + "202": "Accepted", + "203": "Non-Authoritative Information", + "204": "No Content", + "205": "Reset Content", + "206": "Partial Content", + "207": "Multi-Status", + "208": "Already Reported", + "226": "IM Used", + "300": "Multiple Choices", + "301": "Moved Permanently", + "302": "Found", + "303": "See Other", + "304": "Not Modified", + "305": "Use Proxy", + "307": "Temporary Redirect", + "308": "Permanent Redirect", + "400": "Bad Request", + "401": "Unauthorized", + "402": "Payment Required", + "403": "Forbidden", + "404": "Not Found", + "405": "Method Not Allowed", + "406": "Not Acceptable", + "407": "Proxy Authentication Required", + "408": "Request Timeout", + "409": "Conflict", + "410": "Gone", + "411": "Length Required", + "412": "Precondition Failed", + "413": "Payload Too Large", + "414": "URI Too Long", + "415": "Unsupported Media Type", + "416": "Range Not Satisfiable", + "417": "Expectation Failed", + "418": "I'm a Teapot", + "421": "Misdirected Request", + "422": "Unprocessable Entity", + "423": "Locked", + "424": "Failed Dependency", + "425": "Too Early", + "426": "Upgrade Required", + "428": "Precondition Required", + "429": "Too Many Requests", + "431": "Request Header Fields Too Large", + "451": "Unavailable For Legal Reasons", + "500": "Internal Server Error", + "501": "Not Implemented", + "502": "Bad Gateway", + "503": "Service Unavailable", + "504": "Gateway Timeout", + "505": "HTTP Version Not Supported", + "506": "Variant Also Negotiates", + "507": "Insufficient Storage", + "508": "Loop Detected", + "509": "Bandwidth Limit Exceeded", + "510": "Not Extended", + "511": "Network Authentication Required" + }; + } +}); + +// node_modules/.pnpm/statuses@2.0.2/node_modules/statuses/index.js +var require_statuses = __commonJS({ + "node_modules/.pnpm/statuses@2.0.2/node_modules/statuses/index.js"(exports, module) { + "use strict"; + var codes = require_codes(); + module.exports = status; + status.message = codes; + status.code = createMessageToStatusCodeMap(codes); + status.codes = createStatusCodeList(codes); + status.redirect = { + 300: true, + 301: true, + 302: true, + 303: true, + 305: true, + 307: true, + 308: true + }; + status.empty = { + 204: true, + 205: true, + 304: true + }; + status.retry = { + 502: true, + 503: true, + 504: true + }; + function createMessageToStatusCodeMap(codes2) { + var map4 = {}; + Object.keys(codes2).forEach(function forEachCode(code) { + var message2 = codes2[code]; + var status2 = Number(code); + map4[message2.toLowerCase()] = status2; + }); + return map4; + } + function createStatusCodeList(codes2) { + return Object.keys(codes2).map(function mapCode(code) { + return Number(code); + }); + } + function getStatusCode(message2) { + var msg = message2.toLowerCase(); + if (!Object.prototype.hasOwnProperty.call(status.code, msg)) { + throw new Error('invalid status message: "' + message2 + '"'); + } + return status.code[msg]; + } + function getStatusMessage(code) { + if (!Object.prototype.hasOwnProperty.call(status.message, code)) { + throw new Error("invalid status code: " + code); + } + return status.message[code]; + } + function status(code) { + if (typeof code === "number") { + return getStatusMessage(code); + } + if (typeof code !== "string") { + throw new TypeError("code must be a number or string"); + } + var n5 = parseInt(code, 10); + if (!isNaN(n5)) { + return getStatusMessage(n5); + } + return getStatusCode(code); + } + } +}); + +// node_modules/.pnpm/inherits@2.0.4/node_modules/inherits/inherits_browser.js +var require_inherits_browser = __commonJS({ + "node_modules/.pnpm/inherits@2.0.4/node_modules/inherits/inherits_browser.js"(exports, module) { + if (typeof Object.create === "function") { + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor; + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + } + }; + } else { + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor; + var TempCtor = function() { + }; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + } + }; + } + } +}); + +// node_modules/.pnpm/inherits@2.0.4/node_modules/inherits/inherits.js +var require_inherits = __commonJS({ + "node_modules/.pnpm/inherits@2.0.4/node_modules/inherits/inherits.js"(exports, module) { + try { + util2 = __require("util"); + if (typeof util2.inherits !== "function") throw ""; + module.exports = util2.inherits; + } catch (e5) { + module.exports = require_inherits_browser(); + } + var util2; + } +}); + +// node_modules/.pnpm/toidentifier@1.0.1/node_modules/toidentifier/index.js +var require_toidentifier = __commonJS({ + "node_modules/.pnpm/toidentifier@1.0.1/node_modules/toidentifier/index.js"(exports, module) { + "use strict"; + module.exports = toIdentifier; + function toIdentifier(str) { + return str.split(" ").map(function(token) { + return token.slice(0, 1).toUpperCase() + token.slice(1); + }).join("").replace(/[^ _0-9a-z]/gi, ""); + } + } +}); + +// node_modules/.pnpm/http-errors@2.0.1/node_modules/http-errors/index.js +var require_http_errors = __commonJS({ + "node_modules/.pnpm/http-errors@2.0.1/node_modules/http-errors/index.js"(exports, module) { + "use strict"; + var deprecate2 = require_depd()("http-errors"); + var setPrototypeOf2 = require_setprototypeof(); + var statuses = require_statuses(); + var inherits = require_inherits(); + var toIdentifier = require_toidentifier(); + module.exports = createError; + module.exports.HttpError = createHttpErrorConstructor(); + module.exports.isHttpError = createIsHttpErrorFunction(module.exports.HttpError); + populateConstructorExports(module.exports, statuses.codes, module.exports.HttpError); + function codeClass(status) { + return Number(String(status).charAt(0) + "00"); + } + function createError() { + var err; + var msg; + var status = 500; + var props = {}; + for (var i5 = 0; i5 < arguments.length; i5++) { + var arg = arguments[i5]; + var type = typeof arg; + if (type === "object" && arg instanceof Error) { + err = arg; + status = err.status || err.statusCode || status; + } else if (type === "number" && i5 === 0) { + status = arg; + } else if (type === "string") { + msg = arg; + } else if (type === "object") { + props = arg; + } else { + throw new TypeError("argument #" + (i5 + 1) + " unsupported type " + type); + } + } + if (typeof status === "number" && (status < 400 || status >= 600)) { + deprecate2("non-error status code; use only 4xx or 5xx status codes"); + } + if (typeof status !== "number" || !statuses.message[status] && (status < 400 || status >= 600)) { + status = 500; + } + var HttpError2 = createError[status] || createError[codeClass(status)]; + if (!err) { + err = HttpError2 ? new HttpError2(msg) : new Error(msg || statuses.message[status]); + Error.captureStackTrace(err, createError); + } + if (!HttpError2 || !(err instanceof HttpError2) || err.status !== status) { + err.expose = status < 500; + err.status = err.statusCode = status; + } + for (var key in props) { + if (key !== "status" && key !== "statusCode") { + err[key] = props[key]; + } + } + return err; + } + function createHttpErrorConstructor() { + function HttpError2() { + throw new TypeError("cannot construct abstract class"); + } + inherits(HttpError2, Error); + return HttpError2; + } + function createClientErrorConstructor(HttpError2, name, code) { + var className = toClassName(name); + function ClientError(message2) { + var msg = message2 != null ? message2 : statuses.message[code]; + var err = new Error(msg); + Error.captureStackTrace(err, ClientError); + setPrototypeOf2(err, ClientError.prototype); + Object.defineProperty(err, "message", { + enumerable: true, + configurable: true, + value: msg, + writable: true + }); + Object.defineProperty(err, "name", { + enumerable: false, + configurable: true, + value: className, + writable: true + }); + return err; + } + inherits(ClientError, HttpError2); + nameFunc(ClientError, className); + ClientError.prototype.status = code; + ClientError.prototype.statusCode = code; + ClientError.prototype.expose = true; + return ClientError; + } + function createIsHttpErrorFunction(HttpError2) { + return function isHttpError(val) { + if (!val || typeof val !== "object") { + return false; + } + if (val instanceof HttpError2) { + return true; + } + return val instanceof Error && typeof val.expose === "boolean" && typeof val.statusCode === "number" && val.status === val.statusCode; + }; + } + function createServerErrorConstructor(HttpError2, name, code) { + var className = toClassName(name); + function ServerError(message2) { + var msg = message2 != null ? message2 : statuses.message[code]; + var err = new Error(msg); + Error.captureStackTrace(err, ServerError); + setPrototypeOf2(err, ServerError.prototype); + Object.defineProperty(err, "message", { + enumerable: true, + configurable: true, + value: msg, + writable: true + }); + Object.defineProperty(err, "name", { + enumerable: false, + configurable: true, + value: className, + writable: true + }); + return err; + } + inherits(ServerError, HttpError2); + nameFunc(ServerError, className); + ServerError.prototype.status = code; + ServerError.prototype.statusCode = code; + ServerError.prototype.expose = false; + return ServerError; + } + function nameFunc(func, name) { + var desc3 = Object.getOwnPropertyDescriptor(func, "name"); + if (desc3 && desc3.configurable) { + desc3.value = name; + Object.defineProperty(func, "name", desc3); + } + } + function populateConstructorExports(exports2, codes, HttpError2) { + codes.forEach(function forEachCode(code) { + var CodeError; + var name = toIdentifier(statuses.message[code]); + switch (codeClass(code)) { + case 400: + CodeError = createClientErrorConstructor(HttpError2, name, code); + break; + case 500: + CodeError = createServerErrorConstructor(HttpError2, name, code); + break; + } + if (CodeError) { + exports2[code] = CodeError; + exports2[name] = CodeError; + } + }); + } + function toClassName(name) { + return name.slice(-5) === "Error" ? name : name + "Error"; + } + } +}); + +// node_modules/.pnpm/bytes@3.1.2/node_modules/bytes/index.js +var require_bytes = __commonJS({ + "node_modules/.pnpm/bytes@3.1.2/node_modules/bytes/index.js"(exports, module) { + "use strict"; + module.exports = bytes; + module.exports.format = format2; + module.exports.parse = parse5; + var formatThousandsRegExp = /\B(?=(\d{3})+(?!\d))/g; + var formatDecimalsRegExp = /(?:\.0*|(\.[^0]+)0+)$/; + var map4 = { + b: 1, + kb: 1 << 10, + mb: 1 << 20, + gb: 1 << 30, + tb: Math.pow(1024, 4), + pb: Math.pow(1024, 5) + }; + var parseRegExp = /^((-|\+)?(\d+(?:\.\d+)?)) *(kb|mb|gb|tb|pb)$/i; + function bytes(value, options) { + if (typeof value === "string") { + return parse5(value); + } + if (typeof value === "number") { + return format2(value, options); + } + return null; + } + function format2(value, options) { + if (!Number.isFinite(value)) { + return null; + } + var mag = Math.abs(value); + var thousandsSeparator = options && options.thousandsSeparator || ""; + var unitSeparator = options && options.unitSeparator || ""; + var decimalPlaces = options && options.decimalPlaces !== void 0 ? options.decimalPlaces : 2; + var fixedDecimals = Boolean(options && options.fixedDecimals); + var unit = options && options.unit || ""; + if (!unit || !map4[unit.toLowerCase()]) { + if (mag >= map4.pb) { + unit = "PB"; + } else if (mag >= map4.tb) { + unit = "TB"; + } else if (mag >= map4.gb) { + unit = "GB"; + } else if (mag >= map4.mb) { + unit = "MB"; + } else if (mag >= map4.kb) { + unit = "KB"; + } else { + unit = "B"; + } + } + var val = value / map4[unit.toLowerCase()]; + var str = val.toFixed(decimalPlaces); + if (!fixedDecimals) { + str = str.replace(formatDecimalsRegExp, "$1"); + } + if (thousandsSeparator) { + str = str.split(".").map(function(s5, i5) { + return i5 === 0 ? s5.replace(formatThousandsRegExp, thousandsSeparator) : s5; + }).join("."); + } + return str + unitSeparator + unit; + } + function parse5(val) { + if (typeof val === "number" && !isNaN(val)) { + return val; + } + if (typeof val !== "string") { + return null; + } + var results = parseRegExp.exec(val); + var floatValue; + var unit = "b"; + if (!results) { + floatValue = parseInt(val, 10); + unit = "b"; + } else { + floatValue = parseFloat(results[1]); + unit = results[4].toLowerCase(); + } + if (isNaN(floatValue)) { + return null; + } + return Math.floor(map4[unit] * floatValue); + } + } +}); + +// node_modules/.pnpm/safer-buffer@2.1.2/node_modules/safer-buffer/safer.js +var require_safer = __commonJS({ + "node_modules/.pnpm/safer-buffer@2.1.2/node_modules/safer-buffer/safer.js"(exports, module) { + "use strict"; + var buffer2 = __require("buffer"); + var Buffer2 = buffer2.Buffer; + var safer = {}; + var key; + for (key in buffer2) { + if (!buffer2.hasOwnProperty(key)) continue; + if (key === "SlowBuffer" || key === "Buffer") continue; + safer[key] = buffer2[key]; + } + var Safer = safer.Buffer = {}; + for (key in Buffer2) { + if (!Buffer2.hasOwnProperty(key)) continue; + if (key === "allocUnsafe" || key === "allocUnsafeSlow") continue; + Safer[key] = Buffer2[key]; + } + safer.Buffer.prototype = Buffer2.prototype; + if (!Safer.from || Safer.from === Uint8Array.from) { + Safer.from = function(value, encodingOrOffset, length) { + if (typeof value === "number") { + throw new TypeError('The "value" argument must not be of type number. Received type ' + typeof value); + } + if (value && typeof value.length === "undefined") { + throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value); + } + return Buffer2(value, encodingOrOffset, length); + }; + } + if (!Safer.alloc) { + Safer.alloc = function(size2, fill, encoding) { + if (typeof size2 !== "number") { + throw new TypeError('The "size" argument must be of type number. Received type ' + typeof size2); + } + if (size2 < 0 || size2 >= 2 * (1 << 30)) { + throw new RangeError('The value "' + size2 + '" is invalid for option "size"'); + } + var buf = Buffer2(size2); + if (!fill || fill.length === 0) { + buf.fill(0); + } else if (typeof encoding === "string") { + buf.fill(fill, encoding); + } else { + buf.fill(fill); + } + return buf; + }; + } + if (!safer.kStringMaxLength) { + try { + safer.kStringMaxLength = process.binding("buffer").kStringMaxLength; + } catch (e5) { + } + } + if (!safer.constants) { + safer.constants = { + MAX_LENGTH: safer.kMaxLength + }; + if (safer.kStringMaxLength) { + safer.constants.MAX_STRING_LENGTH = safer.kStringMaxLength; + } + } + module.exports = safer; + } +}); + +// node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/lib/bom-handling.js +var require_bom_handling = __commonJS({ + "node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/lib/bom-handling.js"(exports) { + "use strict"; + var BOMChar = "\uFEFF"; + exports.PrependBOM = PrependBOMWrapper; + function PrependBOMWrapper(encoder3, options) { + this.encoder = encoder3; + this.addBOM = true; + } + PrependBOMWrapper.prototype.write = function(str) { + if (this.addBOM) { + str = BOMChar + str; + this.addBOM = false; + } + return this.encoder.write(str); + }; + PrependBOMWrapper.prototype.end = function() { + return this.encoder.end(); + }; + exports.StripBOM = StripBOMWrapper; + function StripBOMWrapper(decoder2, options) { + this.decoder = decoder2; + this.pass = false; + this.options = options || {}; + } + StripBOMWrapper.prototype.write = function(buf) { + var res = this.decoder.write(buf); + if (this.pass || !res) { + return res; + } + if (res[0] === BOMChar) { + res = res.slice(1); + if (typeof this.options.stripBOM === "function") { + this.options.stripBOM(); + } + } + this.pass = true; + return res; + }; + StripBOMWrapper.prototype.end = function() { + return this.decoder.end(); + }; + } +}); + +// node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/lib/helpers/merge-exports.js +var require_merge_exports = __commonJS({ + "node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/lib/helpers/merge-exports.js"(exports, module) { + "use strict"; + var hasOwn = typeof Object.hasOwn === "undefined" ? Function.call.bind(Object.prototype.hasOwnProperty) : Object.hasOwn; + function mergeModules(target, module2) { + for (var key in module2) { + if (hasOwn(module2, key)) { + target[key] = module2[key]; + } + } + } + module.exports = mergeModules; + } +}); + +// node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/encodings/internal.js +var require_internal = __commonJS({ + "node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/encodings/internal.js"(exports, module) { + "use strict"; + var Buffer2 = require_safer().Buffer; + module.exports = { + // Encodings + utf8: { type: "_internal", bomAware: true }, + cesu8: { type: "_internal", bomAware: true }, + unicode11utf8: "utf8", + ucs2: { type: "_internal", bomAware: true }, + utf16le: "ucs2", + binary: { type: "_internal" }, + base64: { type: "_internal" }, + hex: { type: "_internal" }, + // Codec. + _internal: InternalCodec + }; + function InternalCodec(codecOptions, iconv) { + this.enc = codecOptions.encodingName; + this.bomAware = codecOptions.bomAware; + if (this.enc === "base64") { + this.encoder = InternalEncoderBase64; + } else if (this.enc === "utf8") { + this.encoder = InternalEncoderUtf8; + } else if (this.enc === "cesu8") { + this.enc = "utf8"; + this.encoder = InternalEncoderCesu8; + if (Buffer2.from("eda0bdedb2a9", "hex").toString() !== "\u{1F4A9}") { + this.decoder = InternalDecoderCesu8; + this.defaultCharUnicode = iconv.defaultCharUnicode; + } + } + } + InternalCodec.prototype.encoder = InternalEncoder; + InternalCodec.prototype.decoder = InternalDecoder; + var StringDecoder = __require("string_decoder").StringDecoder; + function InternalDecoder(options, codec2) { + this.decoder = new StringDecoder(codec2.enc); + } + InternalDecoder.prototype.write = function(buf) { + if (!Buffer2.isBuffer(buf)) { + buf = Buffer2.from(buf); + } + return this.decoder.write(buf); + }; + InternalDecoder.prototype.end = function() { + return this.decoder.end(); + }; + function InternalEncoder(options, codec2) { + this.enc = codec2.enc; + } + InternalEncoder.prototype.write = function(str) { + return Buffer2.from(str, this.enc); + }; + InternalEncoder.prototype.end = function() { + }; + function InternalEncoderBase64(options, codec2) { + this.prevStr = ""; + } + InternalEncoderBase64.prototype.write = function(str) { + str = this.prevStr + str; + var completeQuads = str.length - str.length % 4; + this.prevStr = str.slice(completeQuads); + str = str.slice(0, completeQuads); + return Buffer2.from(str, "base64"); + }; + InternalEncoderBase64.prototype.end = function() { + return Buffer2.from(this.prevStr, "base64"); + }; + function InternalEncoderCesu8(options, codec2) { + } + InternalEncoderCesu8.prototype.write = function(str) { + var buf = Buffer2.alloc(str.length * 3); + var bufIdx = 0; + for (var i5 = 0; i5 < str.length; i5++) { + var charCode = str.charCodeAt(i5); + if (charCode < 128) { + buf[bufIdx++] = charCode; + } else if (charCode < 2048) { + buf[bufIdx++] = 192 + (charCode >>> 6); + buf[bufIdx++] = 128 + (charCode & 63); + } else { + buf[bufIdx++] = 224 + (charCode >>> 12); + buf[bufIdx++] = 128 + (charCode >>> 6 & 63); + buf[bufIdx++] = 128 + (charCode & 63); + } + } + return buf.slice(0, bufIdx); + }; + InternalEncoderCesu8.prototype.end = function() { + }; + function InternalDecoderCesu8(options, codec2) { + this.acc = 0; + this.contBytes = 0; + this.accBytes = 0; + this.defaultCharUnicode = codec2.defaultCharUnicode; + } + InternalDecoderCesu8.prototype.write = function(buf) { + var acc = this.acc; + var contBytes = this.contBytes; + var accBytes = this.accBytes; + var res = ""; + for (var i5 = 0; i5 < buf.length; i5++) { + var curByte = buf[i5]; + if ((curByte & 192) !== 128) { + if (contBytes > 0) { + res += this.defaultCharUnicode; + contBytes = 0; + } + if (curByte < 128) { + res += String.fromCharCode(curByte); + } else if (curByte < 224) { + acc = curByte & 31; + contBytes = 1; + accBytes = 1; + } else if (curByte < 240) { + acc = curByte & 15; + contBytes = 2; + accBytes = 1; + } else { + res += this.defaultCharUnicode; + } + } else { + if (contBytes > 0) { + acc = acc << 6 | curByte & 63; + contBytes--; + accBytes++; + if (contBytes === 0) { + if (accBytes === 2 && acc < 128 && acc > 0) { + res += this.defaultCharUnicode; + } else if (accBytes === 3 && acc < 2048) { + res += this.defaultCharUnicode; + } else { + res += String.fromCharCode(acc); + } + } + } else { + res += this.defaultCharUnicode; + } + } + } + this.acc = acc; + this.contBytes = contBytes; + this.accBytes = accBytes; + return res; + }; + InternalDecoderCesu8.prototype.end = function() { + var res = 0; + if (this.contBytes > 0) { + res += this.defaultCharUnicode; + } + return res; + }; + function InternalEncoderUtf8(options, codec2) { + this.highSurrogate = ""; + } + InternalEncoderUtf8.prototype.write = function(str) { + if (this.highSurrogate) { + str = this.highSurrogate + str; + this.highSurrogate = ""; + } + if (str.length > 0) { + var charCode = str.charCodeAt(str.length - 1); + if (charCode >= 55296 && charCode < 56320) { + this.highSurrogate = str[str.length - 1]; + str = str.slice(0, str.length - 1); + } + } + return Buffer2.from(str, this.enc); + }; + InternalEncoderUtf8.prototype.end = function() { + if (this.highSurrogate) { + var str = this.highSurrogate; + this.highSurrogate = ""; + return Buffer2.from(str, this.enc); + } + }; + } +}); + +// node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/encodings/utf32.js +var require_utf32 = __commonJS({ + "node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/encodings/utf32.js"(exports) { + "use strict"; + var Buffer2 = require_safer().Buffer; + exports._utf32 = Utf32Codec; + function Utf32Codec(codecOptions, iconv) { + this.iconv = iconv; + this.bomAware = true; + this.isLE = codecOptions.isLE; + } + exports.utf32le = { type: "_utf32", isLE: true }; + exports.utf32be = { type: "_utf32", isLE: false }; + exports.ucs4le = "utf32le"; + exports.ucs4be = "utf32be"; + Utf32Codec.prototype.encoder = Utf32Encoder; + Utf32Codec.prototype.decoder = Utf32Decoder; + function Utf32Encoder(options, codec2) { + this.isLE = codec2.isLE; + this.highSurrogate = 0; + } + Utf32Encoder.prototype.write = function(str) { + var src = Buffer2.from(str, "ucs2"); + var dst = Buffer2.alloc(src.length * 2); + var write32 = this.isLE ? dst.writeUInt32LE : dst.writeUInt32BE; + var offset = 0; + for (var i5 = 0; i5 < src.length; i5 += 2) { + var code = src.readUInt16LE(i5); + var isHighSurrogate = code >= 55296 && code < 56320; + var isLowSurrogate = code >= 56320 && code < 57344; + if (this.highSurrogate) { + if (isHighSurrogate || !isLowSurrogate) { + write32.call(dst, this.highSurrogate, offset); + offset += 4; + } else { + var codepoint = (this.highSurrogate - 55296 << 10 | code - 56320) + 65536; + write32.call(dst, codepoint, offset); + offset += 4; + this.highSurrogate = 0; + continue; + } + } + if (isHighSurrogate) { + this.highSurrogate = code; + } else { + write32.call(dst, code, offset); + offset += 4; + this.highSurrogate = 0; + } + } + if (offset < dst.length) { + dst = dst.slice(0, offset); + } + return dst; + }; + Utf32Encoder.prototype.end = function() { + if (!this.highSurrogate) { + return; + } + var buf = Buffer2.alloc(4); + if (this.isLE) { + buf.writeUInt32LE(this.highSurrogate, 0); + } else { + buf.writeUInt32BE(this.highSurrogate, 0); + } + this.highSurrogate = 0; + return buf; + }; + function Utf32Decoder(options, codec2) { + this.isLE = codec2.isLE; + this.badChar = codec2.iconv.defaultCharUnicode.charCodeAt(0); + this.overflow = []; + } + Utf32Decoder.prototype.write = function(src) { + if (src.length === 0) { + return ""; + } + var i5 = 0; + var codepoint = 0; + var dst = Buffer2.alloc(src.length + 4); + var offset = 0; + var isLE3 = this.isLE; + var overflow = this.overflow; + var badChar = this.badChar; + if (overflow.length > 0) { + for (; i5 < src.length && overflow.length < 4; i5++) { + overflow.push(src[i5]); + } + if (overflow.length === 4) { + if (isLE3) { + codepoint = overflow[i5] | overflow[i5 + 1] << 8 | overflow[i5 + 2] << 16 | overflow[i5 + 3] << 24; + } else { + codepoint = overflow[i5 + 3] | overflow[i5 + 2] << 8 | overflow[i5 + 1] << 16 | overflow[i5] << 24; + } + overflow.length = 0; + offset = _writeCodepoint(dst, offset, codepoint, badChar); + } + } + for (; i5 < src.length - 3; i5 += 4) { + if (isLE3) { + codepoint = src[i5] | src[i5 + 1] << 8 | src[i5 + 2] << 16 | src[i5 + 3] << 24; + } else { + codepoint = src[i5 + 3] | src[i5 + 2] << 8 | src[i5 + 1] << 16 | src[i5] << 24; + } + offset = _writeCodepoint(dst, offset, codepoint, badChar); + } + for (; i5 < src.length; i5++) { + overflow.push(src[i5]); + } + return dst.slice(0, offset).toString("ucs2"); + }; + function _writeCodepoint(dst, offset, codepoint, badChar) { + if (codepoint < 0 || codepoint > 1114111) { + codepoint = badChar; + } + if (codepoint >= 65536) { + codepoint -= 65536; + var high = 55296 | codepoint >> 10; + dst[offset++] = high & 255; + dst[offset++] = high >> 8; + var codepoint = 56320 | codepoint & 1023; + } + dst[offset++] = codepoint & 255; + dst[offset++] = codepoint >> 8; + return offset; + } + Utf32Decoder.prototype.end = function() { + this.overflow.length = 0; + }; + exports.utf32 = Utf32AutoCodec; + exports.ucs4 = "utf32"; + function Utf32AutoCodec(options, iconv) { + this.iconv = iconv; + } + Utf32AutoCodec.prototype.encoder = Utf32AutoEncoder; + Utf32AutoCodec.prototype.decoder = Utf32AutoDecoder; + function Utf32AutoEncoder(options, codec2) { + options = options || {}; + if (options.addBOM === void 0) { + options.addBOM = true; + } + this.encoder = codec2.iconv.getEncoder(options.defaultEncoding || "utf-32le", options); + } + Utf32AutoEncoder.prototype.write = function(str) { + return this.encoder.write(str); + }; + Utf32AutoEncoder.prototype.end = function() { + return this.encoder.end(); + }; + function Utf32AutoDecoder(options, codec2) { + this.decoder = null; + this.initialBufs = []; + this.initialBufsLen = 0; + this.options = options || {}; + this.iconv = codec2.iconv; + } + Utf32AutoDecoder.prototype.write = function(buf) { + if (!this.decoder) { + this.initialBufs.push(buf); + this.initialBufsLen += buf.length; + if (this.initialBufsLen < 32) { + return ""; + } + var encoding = detectEncoding(this.initialBufs, this.options.defaultEncoding); + this.decoder = this.iconv.getDecoder(encoding, this.options); + var resStr = ""; + for (var i5 = 0; i5 < this.initialBufs.length; i5++) { + resStr += this.decoder.write(this.initialBufs[i5]); + } + this.initialBufs.length = this.initialBufsLen = 0; + return resStr; + } + return this.decoder.write(buf); + }; + Utf32AutoDecoder.prototype.end = function() { + if (!this.decoder) { + var encoding = detectEncoding(this.initialBufs, this.options.defaultEncoding); + this.decoder = this.iconv.getDecoder(encoding, this.options); + var resStr = ""; + for (var i5 = 0; i5 < this.initialBufs.length; i5++) { + resStr += this.decoder.write(this.initialBufs[i5]); + } + var trail = this.decoder.end(); + if (trail) { + resStr += trail; + } + this.initialBufs.length = this.initialBufsLen = 0; + return resStr; + } + return this.decoder.end(); + }; + function detectEncoding(bufs, defaultEncoding) { + var b6 = []; + var charsProcessed = 0; + var invalidLE = 0; + var invalidBE = 0; + var bmpCharsLE = 0; + var bmpCharsBE = 0; + outerLoop: + for (var i5 = 0; i5 < bufs.length; i5++) { + var buf = bufs[i5]; + for (var j5 = 0; j5 < buf.length; j5++) { + b6.push(buf[j5]); + if (b6.length === 4) { + if (charsProcessed === 0) { + if (b6[0] === 255 && b6[1] === 254 && b6[2] === 0 && b6[3] === 0) { + return "utf-32le"; + } + if (b6[0] === 0 && b6[1] === 0 && b6[2] === 254 && b6[3] === 255) { + return "utf-32be"; + } + } + if (b6[0] !== 0 || b6[1] > 16) invalidBE++; + if (b6[3] !== 0 || b6[2] > 16) invalidLE++; + if (b6[0] === 0 && b6[1] === 0 && (b6[2] !== 0 || b6[3] !== 0)) bmpCharsBE++; + if ((b6[0] !== 0 || b6[1] !== 0) && b6[2] === 0 && b6[3] === 0) bmpCharsLE++; + b6.length = 0; + charsProcessed++; + if (charsProcessed >= 100) { + break outerLoop; + } + } + } + } + if (bmpCharsBE - invalidBE > bmpCharsLE - invalidLE) return "utf-32be"; + if (bmpCharsBE - invalidBE < bmpCharsLE - invalidLE) return "utf-32le"; + return defaultEncoding || "utf-32le"; + } + } +}); + +// node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/encodings/utf16.js +var require_utf16 = __commonJS({ + "node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/encodings/utf16.js"(exports) { + "use strict"; + var Buffer2 = require_safer().Buffer; + exports.utf16be = Utf16BECodec; + function Utf16BECodec() { + } + Utf16BECodec.prototype.encoder = Utf16BEEncoder; + Utf16BECodec.prototype.decoder = Utf16BEDecoder; + Utf16BECodec.prototype.bomAware = true; + function Utf16BEEncoder() { + } + Utf16BEEncoder.prototype.write = function(str) { + var buf = Buffer2.from(str, "ucs2"); + for (var i5 = 0; i5 < buf.length; i5 += 2) { + var tmp = buf[i5]; + buf[i5] = buf[i5 + 1]; + buf[i5 + 1] = tmp; + } + return buf; + }; + Utf16BEEncoder.prototype.end = function() { + }; + function Utf16BEDecoder() { + this.overflowByte = -1; + } + Utf16BEDecoder.prototype.write = function(buf) { + if (buf.length == 0) { + return ""; + } + var buf2 = Buffer2.alloc(buf.length + 1); + var i5 = 0; + var j5 = 0; + if (this.overflowByte !== -1) { + buf2[0] = buf[0]; + buf2[1] = this.overflowByte; + i5 = 1; + j5 = 2; + } + for (; i5 < buf.length - 1; i5 += 2, j5 += 2) { + buf2[j5] = buf[i5 + 1]; + buf2[j5 + 1] = buf[i5]; + } + this.overflowByte = i5 == buf.length - 1 ? buf[buf.length - 1] : -1; + return buf2.slice(0, j5).toString("ucs2"); + }; + Utf16BEDecoder.prototype.end = function() { + this.overflowByte = -1; + }; + exports.utf16 = Utf16Codec; + function Utf16Codec(codecOptions, iconv) { + this.iconv = iconv; + } + Utf16Codec.prototype.encoder = Utf16Encoder; + Utf16Codec.prototype.decoder = Utf16Decoder; + function Utf16Encoder(options, codec2) { + options = options || {}; + if (options.addBOM === void 0) { + options.addBOM = true; + } + this.encoder = codec2.iconv.getEncoder("utf-16le", options); + } + Utf16Encoder.prototype.write = function(str) { + return this.encoder.write(str); + }; + Utf16Encoder.prototype.end = function() { + return this.encoder.end(); + }; + function Utf16Decoder(options, codec2) { + this.decoder = null; + this.initialBufs = []; + this.initialBufsLen = 0; + this.options = options || {}; + this.iconv = codec2.iconv; + } + Utf16Decoder.prototype.write = function(buf) { + if (!this.decoder) { + this.initialBufs.push(buf); + this.initialBufsLen += buf.length; + if (this.initialBufsLen < 16) { + return ""; + } + var encoding = detectEncoding(this.initialBufs, this.options.defaultEncoding); + this.decoder = this.iconv.getDecoder(encoding, this.options); + var resStr = ""; + for (var i5 = 0; i5 < this.initialBufs.length; i5++) { + resStr += this.decoder.write(this.initialBufs[i5]); + } + this.initialBufs.length = this.initialBufsLen = 0; + return resStr; + } + return this.decoder.write(buf); + }; + Utf16Decoder.prototype.end = function() { + if (!this.decoder) { + var encoding = detectEncoding(this.initialBufs, this.options.defaultEncoding); + this.decoder = this.iconv.getDecoder(encoding, this.options); + var resStr = ""; + for (var i5 = 0; i5 < this.initialBufs.length; i5++) { + resStr += this.decoder.write(this.initialBufs[i5]); + } + var trail = this.decoder.end(); + if (trail) { + resStr += trail; + } + this.initialBufs.length = this.initialBufsLen = 0; + return resStr; + } + return this.decoder.end(); + }; + function detectEncoding(bufs, defaultEncoding) { + var b6 = []; + var charsProcessed = 0; + var asciiCharsLE = 0; + var asciiCharsBE = 0; + outerLoop: + for (var i5 = 0; i5 < bufs.length; i5++) { + var buf = bufs[i5]; + for (var j5 = 0; j5 < buf.length; j5++) { + b6.push(buf[j5]); + if (b6.length === 2) { + if (charsProcessed === 0) { + if (b6[0] === 255 && b6[1] === 254) return "utf-16le"; + if (b6[0] === 254 && b6[1] === 255) return "utf-16be"; + } + if (b6[0] === 0 && b6[1] !== 0) asciiCharsBE++; + if (b6[0] !== 0 && b6[1] === 0) asciiCharsLE++; + b6.length = 0; + charsProcessed++; + if (charsProcessed >= 100) { + break outerLoop; + } + } + } + } + if (asciiCharsBE > asciiCharsLE) return "utf-16be"; + if (asciiCharsBE < asciiCharsLE) return "utf-16le"; + return defaultEncoding || "utf-16le"; + } + } +}); + +// node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/encodings/utf7.js +var require_utf7 = __commonJS({ + "node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/encodings/utf7.js"(exports) { + "use strict"; + var Buffer2 = require_safer().Buffer; + exports.utf7 = Utf7Codec; + exports.unicode11utf7 = "utf7"; + function Utf7Codec(codecOptions, iconv) { + this.iconv = iconv; + } + Utf7Codec.prototype.encoder = Utf7Encoder; + Utf7Codec.prototype.decoder = Utf7Decoder; + Utf7Codec.prototype.bomAware = true; + var nonDirectChars = /[^A-Za-z0-9'\(\),-\.\/:\? \n\r\t]+/g; + function Utf7Encoder(options, codec2) { + this.iconv = codec2.iconv; + } + Utf7Encoder.prototype.write = function(str) { + return Buffer2.from(str.replace(nonDirectChars, function(chunk) { + return "+" + (chunk === "+" ? "" : this.iconv.encode(chunk, "utf16-be").toString("base64").replace(/=+$/, "")) + "-"; + }.bind(this))); + }; + Utf7Encoder.prototype.end = function() { + }; + function Utf7Decoder(options, codec2) { + this.iconv = codec2.iconv; + this.inBase64 = false; + this.base64Accum = ""; + } + var base64Regex2 = /[A-Za-z0-9\/+]/; + var base64Chars = []; + for (i5 = 0; i5 < 256; i5++) { + base64Chars[i5] = base64Regex2.test(String.fromCharCode(i5)); + } + var i5; + var plusChar = "+".charCodeAt(0); + var minusChar = "-".charCodeAt(0); + var andChar = "&".charCodeAt(0); + Utf7Decoder.prototype.write = function(buf) { + var res = ""; + var lastI = 0; + var inBase64 = this.inBase64; + var base64Accum = this.base64Accum; + for (var i6 = 0; i6 < buf.length; i6++) { + if (!inBase64) { + if (buf[i6] == plusChar) { + res += this.iconv.decode(buf.slice(lastI, i6), "ascii"); + lastI = i6 + 1; + inBase64 = true; + } + } else { + if (!base64Chars[buf[i6]]) { + if (i6 == lastI && buf[i6] == minusChar) { + res += "+"; + } else { + var b64str = base64Accum + this.iconv.decode(buf.slice(lastI, i6), "ascii"); + res += this.iconv.decode(Buffer2.from(b64str, "base64"), "utf16-be"); + } + if (buf[i6] != minusChar) { + i6--; + } + lastI = i6 + 1; + inBase64 = false; + base64Accum = ""; + } + } + } + if (!inBase64) { + res += this.iconv.decode(buf.slice(lastI), "ascii"); + } else { + var b64str = base64Accum + this.iconv.decode(buf.slice(lastI), "ascii"); + var canBeDecoded = b64str.length - b64str.length % 8; + base64Accum = b64str.slice(canBeDecoded); + b64str = b64str.slice(0, canBeDecoded); + res += this.iconv.decode(Buffer2.from(b64str, "base64"), "utf16-be"); + } + this.inBase64 = inBase64; + this.base64Accum = base64Accum; + return res; + }; + Utf7Decoder.prototype.end = function() { + var res = ""; + if (this.inBase64 && this.base64Accum.length > 0) { + res = this.iconv.decode(Buffer2.from(this.base64Accum, "base64"), "utf16-be"); + } + this.inBase64 = false; + this.base64Accum = ""; + return res; + }; + exports.utf7imap = Utf7IMAPCodec; + function Utf7IMAPCodec(codecOptions, iconv) { + this.iconv = iconv; + } + Utf7IMAPCodec.prototype.encoder = Utf7IMAPEncoder; + Utf7IMAPCodec.prototype.decoder = Utf7IMAPDecoder; + Utf7IMAPCodec.prototype.bomAware = true; + function Utf7IMAPEncoder(options, codec2) { + this.iconv = codec2.iconv; + this.inBase64 = false; + this.base64Accum = Buffer2.alloc(6); + this.base64AccumIdx = 0; + } + Utf7IMAPEncoder.prototype.write = function(str) { + var inBase64 = this.inBase64; + var base64Accum = this.base64Accum; + var base64AccumIdx = this.base64AccumIdx; + var buf = Buffer2.alloc(str.length * 5 + 10); + var bufIdx = 0; + for (var i6 = 0; i6 < str.length; i6++) { + var uChar = str.charCodeAt(i6); + if (uChar >= 32 && uChar <= 126) { + if (inBase64) { + if (base64AccumIdx > 0) { + bufIdx += buf.write(base64Accum.slice(0, base64AccumIdx).toString("base64").replace(/\//g, ",").replace(/=+$/, ""), bufIdx); + base64AccumIdx = 0; + } + buf[bufIdx++] = minusChar; + inBase64 = false; + } + if (!inBase64) { + buf[bufIdx++] = uChar; + if (uChar === andChar) { + buf[bufIdx++] = minusChar; + } + } + } else { + if (!inBase64) { + buf[bufIdx++] = andChar; + inBase64 = true; + } + if (inBase64) { + base64Accum[base64AccumIdx++] = uChar >> 8; + base64Accum[base64AccumIdx++] = uChar & 255; + if (base64AccumIdx == base64Accum.length) { + bufIdx += buf.write(base64Accum.toString("base64").replace(/\//g, ","), bufIdx); + base64AccumIdx = 0; + } + } + } + } + this.inBase64 = inBase64; + this.base64AccumIdx = base64AccumIdx; + return buf.slice(0, bufIdx); + }; + Utf7IMAPEncoder.prototype.end = function() { + var buf = Buffer2.alloc(10); + var bufIdx = 0; + if (this.inBase64) { + if (this.base64AccumIdx > 0) { + bufIdx += buf.write(this.base64Accum.slice(0, this.base64AccumIdx).toString("base64").replace(/\//g, ",").replace(/=+$/, ""), bufIdx); + this.base64AccumIdx = 0; + } + buf[bufIdx++] = minusChar; + this.inBase64 = false; + } + return buf.slice(0, bufIdx); + }; + function Utf7IMAPDecoder(options, codec2) { + this.iconv = codec2.iconv; + this.inBase64 = false; + this.base64Accum = ""; + } + var base64IMAPChars = base64Chars.slice(); + base64IMAPChars[",".charCodeAt(0)] = true; + Utf7IMAPDecoder.prototype.write = function(buf) { + var res = ""; + var lastI = 0; + var inBase64 = this.inBase64; + var base64Accum = this.base64Accum; + for (var i6 = 0; i6 < buf.length; i6++) { + if (!inBase64) { + if (buf[i6] == andChar) { + res += this.iconv.decode(buf.slice(lastI, i6), "ascii"); + lastI = i6 + 1; + inBase64 = true; + } + } else { + if (!base64IMAPChars[buf[i6]]) { + if (i6 == lastI && buf[i6] == minusChar) { + res += "&"; + } else { + var b64str = base64Accum + this.iconv.decode(buf.slice(lastI, i6), "ascii").replace(/,/g, "/"); + res += this.iconv.decode(Buffer2.from(b64str, "base64"), "utf16-be"); + } + if (buf[i6] != minusChar) { + i6--; + } + lastI = i6 + 1; + inBase64 = false; + base64Accum = ""; + } + } + } + if (!inBase64) { + res += this.iconv.decode(buf.slice(lastI), "ascii"); + } else { + var b64str = base64Accum + this.iconv.decode(buf.slice(lastI), "ascii").replace(/,/g, "/"); + var canBeDecoded = b64str.length - b64str.length % 8; + base64Accum = b64str.slice(canBeDecoded); + b64str = b64str.slice(0, canBeDecoded); + res += this.iconv.decode(Buffer2.from(b64str, "base64"), "utf16-be"); + } + this.inBase64 = inBase64; + this.base64Accum = base64Accum; + return res; + }; + Utf7IMAPDecoder.prototype.end = function() { + var res = ""; + if (this.inBase64 && this.base64Accum.length > 0) { + res = this.iconv.decode(Buffer2.from(this.base64Accum, "base64"), "utf16-be"); + } + this.inBase64 = false; + this.base64Accum = ""; + return res; + }; + } +}); + +// node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/encodings/sbcs-codec.js +var require_sbcs_codec = __commonJS({ + "node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/encodings/sbcs-codec.js"(exports) { + "use strict"; + var Buffer2 = require_safer().Buffer; + exports._sbcs = SBCSCodec; + function SBCSCodec(codecOptions, iconv) { + if (!codecOptions) { + throw new Error("SBCS codec is called without the data."); + } + if (!codecOptions.chars || codecOptions.chars.length !== 128 && codecOptions.chars.length !== 256) { + throw new Error("Encoding '" + codecOptions.type + "' has incorrect 'chars' (must be of len 128 or 256)"); + } + if (codecOptions.chars.length === 128) { + var asciiString = ""; + for (var i5 = 0; i5 < 128; i5++) { + asciiString += String.fromCharCode(i5); + } + codecOptions.chars = asciiString + codecOptions.chars; + } + this.decodeBuf = Buffer2.from(codecOptions.chars, "ucs2"); + var encodeBuf = Buffer2.alloc(65536, iconv.defaultCharSingleByte.charCodeAt(0)); + for (var i5 = 0; i5 < codecOptions.chars.length; i5++) { + encodeBuf[codecOptions.chars.charCodeAt(i5)] = i5; + } + this.encodeBuf = encodeBuf; + } + SBCSCodec.prototype.encoder = SBCSEncoder; + SBCSCodec.prototype.decoder = SBCSDecoder; + function SBCSEncoder(options, codec2) { + this.encodeBuf = codec2.encodeBuf; + } + SBCSEncoder.prototype.write = function(str) { + var buf = Buffer2.alloc(str.length); + for (var i5 = 0; i5 < str.length; i5++) { + buf[i5] = this.encodeBuf[str.charCodeAt(i5)]; + } + return buf; + }; + SBCSEncoder.prototype.end = function() { + }; + function SBCSDecoder(options, codec2) { + this.decodeBuf = codec2.decodeBuf; + } + SBCSDecoder.prototype.write = function(buf) { + var decodeBuf = this.decodeBuf; + var newBuf = Buffer2.alloc(buf.length * 2); + var idx1 = 0; + var idx2 = 0; + for (var i5 = 0; i5 < buf.length; i5++) { + idx1 = buf[i5] * 2; + idx2 = i5 * 2; + newBuf[idx2] = decodeBuf[idx1]; + newBuf[idx2 + 1] = decodeBuf[idx1 + 1]; + } + return newBuf.toString("ucs2"); + }; + SBCSDecoder.prototype.end = function() { + }; + } +}); + +// node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/encodings/sbcs-data.js +var require_sbcs_data = __commonJS({ + "node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/encodings/sbcs-data.js"(exports, module) { + "use strict"; + module.exports = { + // Not supported by iconv, not sure why. + 10029: "maccenteuro", + maccenteuro: { + type: "_sbcs", + chars: "\xC4\u0100\u0101\xC9\u0104\xD6\xDC\xE1\u0105\u010C\xE4\u010D\u0106\u0107\xE9\u0179\u017A\u010E\xED\u010F\u0112\u0113\u0116\xF3\u0117\xF4\xF6\xF5\xFA\u011A\u011B\xFC\u2020\xB0\u0118\xA3\xA7\u2022\xB6\xDF\xAE\xA9\u2122\u0119\xA8\u2260\u0123\u012E\u012F\u012A\u2264\u2265\u012B\u0136\u2202\u2211\u0142\u013B\u013C\u013D\u013E\u0139\u013A\u0145\u0146\u0143\xAC\u221A\u0144\u0147\u2206\xAB\xBB\u2026\xA0\u0148\u0150\xD5\u0151\u014C\u2013\u2014\u201C\u201D\u2018\u2019\xF7\u25CA\u014D\u0154\u0155\u0158\u2039\u203A\u0159\u0156\u0157\u0160\u201A\u201E\u0161\u015A\u015B\xC1\u0164\u0165\xCD\u017D\u017E\u016A\xD3\xD4\u016B\u016E\xDA\u016F\u0170\u0171\u0172\u0173\xDD\xFD\u0137\u017B\u0141\u017C\u0122\u02C7" + }, + 808: "cp808", + ibm808: "cp808", + cp808: { + type: "_sbcs", + chars: "\u0410\u0411\u0412\u0413\u0414\u0415\u0416\u0417\u0418\u0419\u041A\u041B\u041C\u041D\u041E\u041F\u0420\u0421\u0422\u0423\u0424\u0425\u0426\u0427\u0428\u0429\u042A\u042B\u042C\u042D\u042E\u042F\u0430\u0431\u0432\u0433\u0434\u0435\u0436\u0437\u0438\u0439\u043A\u043B\u043C\u043D\u043E\u043F\u2591\u2592\u2593\u2502\u2524\u2561\u2562\u2556\u2555\u2563\u2551\u2557\u255D\u255C\u255B\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u255E\u255F\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u2567\u2568\u2564\u2565\u2559\u2558\u2552\u2553\u256B\u256A\u2518\u250C\u2588\u2584\u258C\u2590\u2580\u0440\u0441\u0442\u0443\u0444\u0445\u0446\u0447\u0448\u0449\u044A\u044B\u044C\u044D\u044E\u044F\u0401\u0451\u0404\u0454\u0407\u0457\u040E\u045E\xB0\u2219\xB7\u221A\u2116\u20AC\u25A0\xA0" + }, + mik: { + type: "_sbcs", + chars: "\u0410\u0411\u0412\u0413\u0414\u0415\u0416\u0417\u0418\u0419\u041A\u041B\u041C\u041D\u041E\u041F\u0420\u0421\u0422\u0423\u0424\u0425\u0426\u0427\u0428\u0429\u042A\u042B\u042C\u042D\u042E\u042F\u0430\u0431\u0432\u0433\u0434\u0435\u0436\u0437\u0438\u0439\u043A\u043B\u043C\u043D\u043E\u043F\u0440\u0441\u0442\u0443\u0444\u0445\u0446\u0447\u0448\u0449\u044A\u044B\u044C\u044D\u044E\u044F\u2514\u2534\u252C\u251C\u2500\u253C\u2563\u2551\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u2510\u2591\u2592\u2593\u2502\u2524\u2116\xA7\u2557\u255D\u2518\u250C\u2588\u2584\u258C\u2590\u2580\u03B1\xDF\u0393\u03C0\u03A3\u03C3\xB5\u03C4\u03A6\u0398\u03A9\u03B4\u221E\u03C6\u03B5\u2229\u2261\xB1\u2265\u2264\u2320\u2321\xF7\u2248\xB0\u2219\xB7\u221A\u207F\xB2\u25A0\xA0" + }, + cp720: { + type: "_sbcs", + chars: "\x80\x81\xE9\xE2\x84\xE0\x86\xE7\xEA\xEB\xE8\xEF\xEE\x8D\x8E\x8F\x90\u0651\u0652\xF4\xA4\u0640\xFB\xF9\u0621\u0622\u0623\u0624\xA3\u0625\u0626\u0627\u0628\u0629\u062A\u062B\u062C\u062D\u062E\u062F\u0630\u0631\u0632\u0633\u0634\u0635\xAB\xBB\u2591\u2592\u2593\u2502\u2524\u2561\u2562\u2556\u2555\u2563\u2551\u2557\u255D\u255C\u255B\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u255E\u255F\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u2567\u2568\u2564\u2565\u2559\u2558\u2552\u2553\u256B\u256A\u2518\u250C\u2588\u2584\u258C\u2590\u2580\u0636\u0637\u0638\u0639\u063A\u0641\xB5\u0642\u0643\u0644\u0645\u0646\u0647\u0648\u0649\u064A\u2261\u064B\u064C\u064D\u064E\u064F\u0650\u2248\xB0\u2219\xB7\u221A\u207F\xB2\u25A0\xA0" + }, + // Aliases of generated encodings. + ascii8bit: "ascii", + usascii: "ascii", + ansix34: "ascii", + ansix341968: "ascii", + ansix341986: "ascii", + csascii: "ascii", + cp367: "ascii", + ibm367: "ascii", + isoir6: "ascii", + iso646us: "ascii", + iso646irv: "ascii", + us: "ascii", + latin1: "iso88591", + latin2: "iso88592", + latin3: "iso88593", + latin4: "iso88594", + latin5: "iso88599", + latin6: "iso885910", + latin7: "iso885913", + latin8: "iso885914", + latin9: "iso885915", + latin10: "iso885916", + csisolatin1: "iso88591", + csisolatin2: "iso88592", + csisolatin3: "iso88593", + csisolatin4: "iso88594", + csisolatincyrillic: "iso88595", + csisolatinarabic: "iso88596", + csisolatingreek: "iso88597", + csisolatinhebrew: "iso88598", + csisolatin5: "iso88599", + csisolatin6: "iso885910", + l1: "iso88591", + l2: "iso88592", + l3: "iso88593", + l4: "iso88594", + l5: "iso88599", + l6: "iso885910", + l7: "iso885913", + l8: "iso885914", + l9: "iso885915", + l10: "iso885916", + isoir14: "iso646jp", + isoir57: "iso646cn", + isoir100: "iso88591", + isoir101: "iso88592", + isoir109: "iso88593", + isoir110: "iso88594", + isoir144: "iso88595", + isoir127: "iso88596", + isoir126: "iso88597", + isoir138: "iso88598", + isoir148: "iso88599", + isoir157: "iso885910", + isoir166: "tis620", + isoir179: "iso885913", + isoir199: "iso885914", + isoir203: "iso885915", + isoir226: "iso885916", + cp819: "iso88591", + ibm819: "iso88591", + cyrillic: "iso88595", + arabic: "iso88596", + arabic8: "iso88596", + ecma114: "iso88596", + asmo708: "iso88596", + greek: "iso88597", + greek8: "iso88597", + ecma118: "iso88597", + elot928: "iso88597", + hebrew: "iso88598", + hebrew8: "iso88598", + turkish: "iso88599", + turkish8: "iso88599", + thai: "iso885911", + thai8: "iso885911", + celtic: "iso885914", + celtic8: "iso885914", + isoceltic: "iso885914", + tis6200: "tis620", + tis62025291: "tis620", + tis62025330: "tis620", + 1e4: "macroman", + 10006: "macgreek", + 10007: "maccyrillic", + 10079: "maciceland", + 10081: "macturkish", + cspc8codepage437: "cp437", + cspc775baltic: "cp775", + cspc850multilingual: "cp850", + cspcp852: "cp852", + cspc862latinhebrew: "cp862", + cpgr: "cp869", + msee: "cp1250", + mscyrl: "cp1251", + msansi: "cp1252", + msgreek: "cp1253", + msturk: "cp1254", + mshebr: "cp1255", + msarab: "cp1256", + winbaltrim: "cp1257", + cp20866: "koi8r", + 20866: "koi8r", + ibm878: "koi8r", + cskoi8r: "koi8r", + cp21866: "koi8u", + 21866: "koi8u", + ibm1168: "koi8u", + strk10482002: "rk1048", + tcvn5712: "tcvn", + tcvn57121: "tcvn", + gb198880: "iso646cn", + cn: "iso646cn", + csiso14jisc6220ro: "iso646jp", + jisc62201969ro: "iso646jp", + jp: "iso646jp", + cshproman8: "hproman8", + r8: "hproman8", + roman8: "hproman8", + xroman8: "hproman8", + ibm1051: "hproman8", + mac: "macintosh", + csmacintosh: "macintosh" + }; + } +}); + +// node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/encodings/sbcs-data-generated.js +var require_sbcs_data_generated = __commonJS({ + "node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/encodings/sbcs-data-generated.js"(exports, module) { + "use strict"; + module.exports = { + "437": "cp437", + "737": "cp737", + "775": "cp775", + "850": "cp850", + "852": "cp852", + "855": "cp855", + "856": "cp856", + "857": "cp857", + "858": "cp858", + "860": "cp860", + "861": "cp861", + "862": "cp862", + "863": "cp863", + "864": "cp864", + "865": "cp865", + "866": "cp866", + "869": "cp869", + "874": "windows874", + "922": "cp922", + "1046": "cp1046", + "1124": "cp1124", + "1125": "cp1125", + "1129": "cp1129", + "1133": "cp1133", + "1161": "cp1161", + "1162": "cp1162", + "1163": "cp1163", + "1250": "windows1250", + "1251": "windows1251", + "1252": "windows1252", + "1253": "windows1253", + "1254": "windows1254", + "1255": "windows1255", + "1256": "windows1256", + "1257": "windows1257", + "1258": "windows1258", + "28591": "iso88591", + "28592": "iso88592", + "28593": "iso88593", + "28594": "iso88594", + "28595": "iso88595", + "28596": "iso88596", + "28597": "iso88597", + "28598": "iso88598", + "28599": "iso88599", + "28600": "iso885910", + "28601": "iso885911", + "28603": "iso885913", + "28604": "iso885914", + "28605": "iso885915", + "28606": "iso885916", + "windows874": { + "type": "_sbcs", + "chars": "\u20AC\uFFFD\uFFFD\uFFFD\uFFFD\u2026\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u2018\u2019\u201C\u201D\u2022\u2013\u2014\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\xA0\u0E01\u0E02\u0E03\u0E04\u0E05\u0E06\u0E07\u0E08\u0E09\u0E0A\u0E0B\u0E0C\u0E0D\u0E0E\u0E0F\u0E10\u0E11\u0E12\u0E13\u0E14\u0E15\u0E16\u0E17\u0E18\u0E19\u0E1A\u0E1B\u0E1C\u0E1D\u0E1E\u0E1F\u0E20\u0E21\u0E22\u0E23\u0E24\u0E25\u0E26\u0E27\u0E28\u0E29\u0E2A\u0E2B\u0E2C\u0E2D\u0E2E\u0E2F\u0E30\u0E31\u0E32\u0E33\u0E34\u0E35\u0E36\u0E37\u0E38\u0E39\u0E3A\uFFFD\uFFFD\uFFFD\uFFFD\u0E3F\u0E40\u0E41\u0E42\u0E43\u0E44\u0E45\u0E46\u0E47\u0E48\u0E49\u0E4A\u0E4B\u0E4C\u0E4D\u0E4E\u0E4F\u0E50\u0E51\u0E52\u0E53\u0E54\u0E55\u0E56\u0E57\u0E58\u0E59\u0E5A\u0E5B\uFFFD\uFFFD\uFFFD\uFFFD" + }, + "win874": "windows874", + "cp874": "windows874", + "windows1250": { + "type": "_sbcs", + "chars": "\u20AC\uFFFD\u201A\uFFFD\u201E\u2026\u2020\u2021\uFFFD\u2030\u0160\u2039\u015A\u0164\u017D\u0179\uFFFD\u2018\u2019\u201C\u201D\u2022\u2013\u2014\uFFFD\u2122\u0161\u203A\u015B\u0165\u017E\u017A\xA0\u02C7\u02D8\u0141\xA4\u0104\xA6\xA7\xA8\xA9\u015E\xAB\xAC\xAD\xAE\u017B\xB0\xB1\u02DB\u0142\xB4\xB5\xB6\xB7\xB8\u0105\u015F\xBB\u013D\u02DD\u013E\u017C\u0154\xC1\xC2\u0102\xC4\u0139\u0106\xC7\u010C\xC9\u0118\xCB\u011A\xCD\xCE\u010E\u0110\u0143\u0147\xD3\xD4\u0150\xD6\xD7\u0158\u016E\xDA\u0170\xDC\xDD\u0162\xDF\u0155\xE1\xE2\u0103\xE4\u013A\u0107\xE7\u010D\xE9\u0119\xEB\u011B\xED\xEE\u010F\u0111\u0144\u0148\xF3\xF4\u0151\xF6\xF7\u0159\u016F\xFA\u0171\xFC\xFD\u0163\u02D9" + }, + "win1250": "windows1250", + "cp1250": "windows1250", + "windows1251": { + "type": "_sbcs", + "chars": "\u0402\u0403\u201A\u0453\u201E\u2026\u2020\u2021\u20AC\u2030\u0409\u2039\u040A\u040C\u040B\u040F\u0452\u2018\u2019\u201C\u201D\u2022\u2013\u2014\uFFFD\u2122\u0459\u203A\u045A\u045C\u045B\u045F\xA0\u040E\u045E\u0408\xA4\u0490\xA6\xA7\u0401\xA9\u0404\xAB\xAC\xAD\xAE\u0407\xB0\xB1\u0406\u0456\u0491\xB5\xB6\xB7\u0451\u2116\u0454\xBB\u0458\u0405\u0455\u0457\u0410\u0411\u0412\u0413\u0414\u0415\u0416\u0417\u0418\u0419\u041A\u041B\u041C\u041D\u041E\u041F\u0420\u0421\u0422\u0423\u0424\u0425\u0426\u0427\u0428\u0429\u042A\u042B\u042C\u042D\u042E\u042F\u0430\u0431\u0432\u0433\u0434\u0435\u0436\u0437\u0438\u0439\u043A\u043B\u043C\u043D\u043E\u043F\u0440\u0441\u0442\u0443\u0444\u0445\u0446\u0447\u0448\u0449\u044A\u044B\u044C\u044D\u044E\u044F" + }, + "win1251": "windows1251", + "cp1251": "windows1251", + "windows1252": { + "type": "_sbcs", + "chars": "\u20AC\uFFFD\u201A\u0192\u201E\u2026\u2020\u2021\u02C6\u2030\u0160\u2039\u0152\uFFFD\u017D\uFFFD\uFFFD\u2018\u2019\u201C\u201D\u2022\u2013\u2014\u02DC\u2122\u0161\u203A\u0153\uFFFD\u017E\u0178\xA0\xA1\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xAA\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xBA\xBB\xBC\xBD\xBE\xBF\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1\xD2\xD3\xD4\xD5\xD6\xD7\xD8\xD9\xDA\xDB\xDC\xDD\xDE\xDF\xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\xFA\xFB\xFC\xFD\xFE\xFF" + }, + "win1252": "windows1252", + "cp1252": "windows1252", + "windows1253": { + "type": "_sbcs", + "chars": "\u20AC\uFFFD\u201A\u0192\u201E\u2026\u2020\u2021\uFFFD\u2030\uFFFD\u2039\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u2018\u2019\u201C\u201D\u2022\u2013\u2014\uFFFD\u2122\uFFFD\u203A\uFFFD\uFFFD\uFFFD\uFFFD\xA0\u0385\u0386\xA3\xA4\xA5\xA6\xA7\xA8\xA9\uFFFD\xAB\xAC\xAD\xAE\u2015\xB0\xB1\xB2\xB3\u0384\xB5\xB6\xB7\u0388\u0389\u038A\xBB\u038C\xBD\u038E\u038F\u0390\u0391\u0392\u0393\u0394\u0395\u0396\u0397\u0398\u0399\u039A\u039B\u039C\u039D\u039E\u039F\u03A0\u03A1\uFFFD\u03A3\u03A4\u03A5\u03A6\u03A7\u03A8\u03A9\u03AA\u03AB\u03AC\u03AD\u03AE\u03AF\u03B0\u03B1\u03B2\u03B3\u03B4\u03B5\u03B6\u03B7\u03B8\u03B9\u03BA\u03BB\u03BC\u03BD\u03BE\u03BF\u03C0\u03C1\u03C2\u03C3\u03C4\u03C5\u03C6\u03C7\u03C8\u03C9\u03CA\u03CB\u03CC\u03CD\u03CE\uFFFD" + }, + "win1253": "windows1253", + "cp1253": "windows1253", + "windows1254": { + "type": "_sbcs", + "chars": "\u20AC\uFFFD\u201A\u0192\u201E\u2026\u2020\u2021\u02C6\u2030\u0160\u2039\u0152\uFFFD\uFFFD\uFFFD\uFFFD\u2018\u2019\u201C\u201D\u2022\u2013\u2014\u02DC\u2122\u0161\u203A\u0153\uFFFD\uFFFD\u0178\xA0\xA1\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xAA\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xBA\xBB\xBC\xBD\xBE\xBF\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\u011E\xD1\xD2\xD3\xD4\xD5\xD6\xD7\xD8\xD9\xDA\xDB\xDC\u0130\u015E\xDF\xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\u011F\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\xFA\xFB\xFC\u0131\u015F\xFF" + }, + "win1254": "windows1254", + "cp1254": "windows1254", + "windows1255": { + "type": "_sbcs", + "chars": "\u20AC\uFFFD\u201A\u0192\u201E\u2026\u2020\u2021\u02C6\u2030\uFFFD\u2039\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u2018\u2019\u201C\u201D\u2022\u2013\u2014\u02DC\u2122\uFFFD\u203A\uFFFD\uFFFD\uFFFD\uFFFD\xA0\xA1\xA2\xA3\u20AA\xA5\xA6\xA7\xA8\xA9\xD7\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xF7\xBB\xBC\xBD\xBE\xBF\u05B0\u05B1\u05B2\u05B3\u05B4\u05B5\u05B6\u05B7\u05B8\u05B9\u05BA\u05BB\u05BC\u05BD\u05BE\u05BF\u05C0\u05C1\u05C2\u05C3\u05F0\u05F1\u05F2\u05F3\u05F4\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u05D0\u05D1\u05D2\u05D3\u05D4\u05D5\u05D6\u05D7\u05D8\u05D9\u05DA\u05DB\u05DC\u05DD\u05DE\u05DF\u05E0\u05E1\u05E2\u05E3\u05E4\u05E5\u05E6\u05E7\u05E8\u05E9\u05EA\uFFFD\uFFFD\u200E\u200F\uFFFD" + }, + "win1255": "windows1255", + "cp1255": "windows1255", + "windows1256": { + "type": "_sbcs", + "chars": "\u20AC\u067E\u201A\u0192\u201E\u2026\u2020\u2021\u02C6\u2030\u0679\u2039\u0152\u0686\u0698\u0688\u06AF\u2018\u2019\u201C\u201D\u2022\u2013\u2014\u06A9\u2122\u0691\u203A\u0153\u200C\u200D\u06BA\xA0\u060C\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\u06BE\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\u061B\xBB\xBC\xBD\xBE\u061F\u06C1\u0621\u0622\u0623\u0624\u0625\u0626\u0627\u0628\u0629\u062A\u062B\u062C\u062D\u062E\u062F\u0630\u0631\u0632\u0633\u0634\u0635\u0636\xD7\u0637\u0638\u0639\u063A\u0640\u0641\u0642\u0643\xE0\u0644\xE2\u0645\u0646\u0647\u0648\xE7\xE8\xE9\xEA\xEB\u0649\u064A\xEE\xEF\u064B\u064C\u064D\u064E\xF4\u064F\u0650\xF7\u0651\xF9\u0652\xFB\xFC\u200E\u200F\u06D2" + }, + "win1256": "windows1256", + "cp1256": "windows1256", + "windows1257": { + "type": "_sbcs", + "chars": "\u20AC\uFFFD\u201A\uFFFD\u201E\u2026\u2020\u2021\uFFFD\u2030\uFFFD\u2039\uFFFD\xA8\u02C7\xB8\uFFFD\u2018\u2019\u201C\u201D\u2022\u2013\u2014\uFFFD\u2122\uFFFD\u203A\uFFFD\xAF\u02DB\uFFFD\xA0\uFFFD\xA2\xA3\xA4\uFFFD\xA6\xA7\xD8\xA9\u0156\xAB\xAC\xAD\xAE\xC6\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xF8\xB9\u0157\xBB\xBC\xBD\xBE\xE6\u0104\u012E\u0100\u0106\xC4\xC5\u0118\u0112\u010C\xC9\u0179\u0116\u0122\u0136\u012A\u013B\u0160\u0143\u0145\xD3\u014C\xD5\xD6\xD7\u0172\u0141\u015A\u016A\xDC\u017B\u017D\xDF\u0105\u012F\u0101\u0107\xE4\xE5\u0119\u0113\u010D\xE9\u017A\u0117\u0123\u0137\u012B\u013C\u0161\u0144\u0146\xF3\u014D\xF5\xF6\xF7\u0173\u0142\u015B\u016B\xFC\u017C\u017E\u02D9" + }, + "win1257": "windows1257", + "cp1257": "windows1257", + "windows1258": { + "type": "_sbcs", + "chars": "\u20AC\uFFFD\u201A\u0192\u201E\u2026\u2020\u2021\u02C6\u2030\uFFFD\u2039\u0152\uFFFD\uFFFD\uFFFD\uFFFD\u2018\u2019\u201C\u201D\u2022\u2013\u2014\u02DC\u2122\uFFFD\u203A\u0153\uFFFD\uFFFD\u0178\xA0\xA1\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xAA\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xBA\xBB\xBC\xBD\xBE\xBF\xC0\xC1\xC2\u0102\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\u0300\xCD\xCE\xCF\u0110\xD1\u0309\xD3\xD4\u01A0\xD6\xD7\xD8\xD9\xDA\xDB\xDC\u01AF\u0303\xDF\xE0\xE1\xE2\u0103\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\u0301\xED\xEE\xEF\u0111\xF1\u0323\xF3\xF4\u01A1\xF6\xF7\xF8\xF9\xFA\xFB\xFC\u01B0\u20AB\xFF" + }, + "win1258": "windows1258", + "cp1258": "windows1258", + "iso88591": { + "type": "_sbcs", + "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\xA1\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xAA\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xBA\xBB\xBC\xBD\xBE\xBF\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1\xD2\xD3\xD4\xD5\xD6\xD7\xD8\xD9\xDA\xDB\xDC\xDD\xDE\xDF\xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\xFA\xFB\xFC\xFD\xFE\xFF" + }, + "cp28591": "iso88591", + "iso88592": { + "type": "_sbcs", + "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\u0104\u02D8\u0141\xA4\u013D\u015A\xA7\xA8\u0160\u015E\u0164\u0179\xAD\u017D\u017B\xB0\u0105\u02DB\u0142\xB4\u013E\u015B\u02C7\xB8\u0161\u015F\u0165\u017A\u02DD\u017E\u017C\u0154\xC1\xC2\u0102\xC4\u0139\u0106\xC7\u010C\xC9\u0118\xCB\u011A\xCD\xCE\u010E\u0110\u0143\u0147\xD3\xD4\u0150\xD6\xD7\u0158\u016E\xDA\u0170\xDC\xDD\u0162\xDF\u0155\xE1\xE2\u0103\xE4\u013A\u0107\xE7\u010D\xE9\u0119\xEB\u011B\xED\xEE\u010F\u0111\u0144\u0148\xF3\xF4\u0151\xF6\xF7\u0159\u016F\xFA\u0171\xFC\xFD\u0163\u02D9" + }, + "cp28592": "iso88592", + "iso88593": { + "type": "_sbcs", + "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\u0126\u02D8\xA3\xA4\uFFFD\u0124\xA7\xA8\u0130\u015E\u011E\u0134\xAD\uFFFD\u017B\xB0\u0127\xB2\xB3\xB4\xB5\u0125\xB7\xB8\u0131\u015F\u011F\u0135\xBD\uFFFD\u017C\xC0\xC1\xC2\uFFFD\xC4\u010A\u0108\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\uFFFD\xD1\xD2\xD3\xD4\u0120\xD6\xD7\u011C\xD9\xDA\xDB\xDC\u016C\u015C\xDF\xE0\xE1\xE2\uFFFD\xE4\u010B\u0109\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\uFFFD\xF1\xF2\xF3\xF4\u0121\xF6\xF7\u011D\xF9\xFA\xFB\xFC\u016D\u015D\u02D9" + }, + "cp28593": "iso88593", + "iso88594": { + "type": "_sbcs", + "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\u0104\u0138\u0156\xA4\u0128\u013B\xA7\xA8\u0160\u0112\u0122\u0166\xAD\u017D\xAF\xB0\u0105\u02DB\u0157\xB4\u0129\u013C\u02C7\xB8\u0161\u0113\u0123\u0167\u014A\u017E\u014B\u0100\xC1\xC2\xC3\xC4\xC5\xC6\u012E\u010C\xC9\u0118\xCB\u0116\xCD\xCE\u012A\u0110\u0145\u014C\u0136\xD4\xD5\xD6\xD7\xD8\u0172\xDA\xDB\xDC\u0168\u016A\xDF\u0101\xE1\xE2\xE3\xE4\xE5\xE6\u012F\u010D\xE9\u0119\xEB\u0117\xED\xEE\u012B\u0111\u0146\u014D\u0137\xF4\xF5\xF6\xF7\xF8\u0173\xFA\xFB\xFC\u0169\u016B\u02D9" + }, + "cp28594": "iso88594", + "iso88595": { + "type": "_sbcs", + "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\u0401\u0402\u0403\u0404\u0405\u0406\u0407\u0408\u0409\u040A\u040B\u040C\xAD\u040E\u040F\u0410\u0411\u0412\u0413\u0414\u0415\u0416\u0417\u0418\u0419\u041A\u041B\u041C\u041D\u041E\u041F\u0420\u0421\u0422\u0423\u0424\u0425\u0426\u0427\u0428\u0429\u042A\u042B\u042C\u042D\u042E\u042F\u0430\u0431\u0432\u0433\u0434\u0435\u0436\u0437\u0438\u0439\u043A\u043B\u043C\u043D\u043E\u043F\u0440\u0441\u0442\u0443\u0444\u0445\u0446\u0447\u0448\u0449\u044A\u044B\u044C\u044D\u044E\u044F\u2116\u0451\u0452\u0453\u0454\u0455\u0456\u0457\u0458\u0459\u045A\u045B\u045C\xA7\u045E\u045F" + }, + "cp28595": "iso88595", + "iso88596": { + "type": "_sbcs", + "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\uFFFD\uFFFD\uFFFD\xA4\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u060C\xAD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u061B\uFFFD\uFFFD\uFFFD\u061F\uFFFD\u0621\u0622\u0623\u0624\u0625\u0626\u0627\u0628\u0629\u062A\u062B\u062C\u062D\u062E\u062F\u0630\u0631\u0632\u0633\u0634\u0635\u0636\u0637\u0638\u0639\u063A\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u0640\u0641\u0642\u0643\u0644\u0645\u0646\u0647\u0648\u0649\u064A\u064B\u064C\u064D\u064E\u064F\u0650\u0651\u0652\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD" + }, + "cp28596": "iso88596", + "iso88597": { + "type": "_sbcs", + "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\u2018\u2019\xA3\u20AC\u20AF\xA6\xA7\xA8\xA9\u037A\xAB\xAC\xAD\uFFFD\u2015\xB0\xB1\xB2\xB3\u0384\u0385\u0386\xB7\u0388\u0389\u038A\xBB\u038C\xBD\u038E\u038F\u0390\u0391\u0392\u0393\u0394\u0395\u0396\u0397\u0398\u0399\u039A\u039B\u039C\u039D\u039E\u039F\u03A0\u03A1\uFFFD\u03A3\u03A4\u03A5\u03A6\u03A7\u03A8\u03A9\u03AA\u03AB\u03AC\u03AD\u03AE\u03AF\u03B0\u03B1\u03B2\u03B3\u03B4\u03B5\u03B6\u03B7\u03B8\u03B9\u03BA\u03BB\u03BC\u03BD\u03BE\u03BF\u03C0\u03C1\u03C2\u03C3\u03C4\u03C5\u03C6\u03C7\u03C8\u03C9\u03CA\u03CB\u03CC\u03CD\u03CE\uFFFD" + }, + "cp28597": "iso88597", + "iso88598": { + "type": "_sbcs", + "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\uFFFD\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xD7\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xF7\xBB\xBC\xBD\xBE\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u2017\u05D0\u05D1\u05D2\u05D3\u05D4\u05D5\u05D6\u05D7\u05D8\u05D9\u05DA\u05DB\u05DC\u05DD\u05DE\u05DF\u05E0\u05E1\u05E2\u05E3\u05E4\u05E5\u05E6\u05E7\u05E8\u05E9\u05EA\uFFFD\uFFFD\u200E\u200F\uFFFD" + }, + "cp28598": "iso88598", + "iso88599": { + "type": "_sbcs", + "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\xA1\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xAA\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xBA\xBB\xBC\xBD\xBE\xBF\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\u011E\xD1\xD2\xD3\xD4\xD5\xD6\xD7\xD8\xD9\xDA\xDB\xDC\u0130\u015E\xDF\xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\u011F\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\xFA\xFB\xFC\u0131\u015F\xFF" + }, + "cp28599": "iso88599", + "iso885910": { + "type": "_sbcs", + "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\u0104\u0112\u0122\u012A\u0128\u0136\xA7\u013B\u0110\u0160\u0166\u017D\xAD\u016A\u014A\xB0\u0105\u0113\u0123\u012B\u0129\u0137\xB7\u013C\u0111\u0161\u0167\u017E\u2015\u016B\u014B\u0100\xC1\xC2\xC3\xC4\xC5\xC6\u012E\u010C\xC9\u0118\xCB\u0116\xCD\xCE\xCF\xD0\u0145\u014C\xD3\xD4\xD5\xD6\u0168\xD8\u0172\xDA\xDB\xDC\xDD\xDE\xDF\u0101\xE1\xE2\xE3\xE4\xE5\xE6\u012F\u010D\xE9\u0119\xEB\u0117\xED\xEE\xEF\xF0\u0146\u014D\xF3\xF4\xF5\xF6\u0169\xF8\u0173\xFA\xFB\xFC\xFD\xFE\u0138" + }, + "cp28600": "iso885910", + "iso885911": { + "type": "_sbcs", + "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\u0E01\u0E02\u0E03\u0E04\u0E05\u0E06\u0E07\u0E08\u0E09\u0E0A\u0E0B\u0E0C\u0E0D\u0E0E\u0E0F\u0E10\u0E11\u0E12\u0E13\u0E14\u0E15\u0E16\u0E17\u0E18\u0E19\u0E1A\u0E1B\u0E1C\u0E1D\u0E1E\u0E1F\u0E20\u0E21\u0E22\u0E23\u0E24\u0E25\u0E26\u0E27\u0E28\u0E29\u0E2A\u0E2B\u0E2C\u0E2D\u0E2E\u0E2F\u0E30\u0E31\u0E32\u0E33\u0E34\u0E35\u0E36\u0E37\u0E38\u0E39\u0E3A\uFFFD\uFFFD\uFFFD\uFFFD\u0E3F\u0E40\u0E41\u0E42\u0E43\u0E44\u0E45\u0E46\u0E47\u0E48\u0E49\u0E4A\u0E4B\u0E4C\u0E4D\u0E4E\u0E4F\u0E50\u0E51\u0E52\u0E53\u0E54\u0E55\u0E56\u0E57\u0E58\u0E59\u0E5A\u0E5B\uFFFD\uFFFD\uFFFD\uFFFD" + }, + "cp28601": "iso885911", + "iso885913": { + "type": "_sbcs", + "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\u201D\xA2\xA3\xA4\u201E\xA6\xA7\xD8\xA9\u0156\xAB\xAC\xAD\xAE\xC6\xB0\xB1\xB2\xB3\u201C\xB5\xB6\xB7\xF8\xB9\u0157\xBB\xBC\xBD\xBE\xE6\u0104\u012E\u0100\u0106\xC4\xC5\u0118\u0112\u010C\xC9\u0179\u0116\u0122\u0136\u012A\u013B\u0160\u0143\u0145\xD3\u014C\xD5\xD6\xD7\u0172\u0141\u015A\u016A\xDC\u017B\u017D\xDF\u0105\u012F\u0101\u0107\xE4\xE5\u0119\u0113\u010D\xE9\u017A\u0117\u0123\u0137\u012B\u013C\u0161\u0144\u0146\xF3\u014D\xF5\xF6\xF7\u0173\u0142\u015B\u016B\xFC\u017C\u017E\u2019" + }, + "cp28603": "iso885913", + "iso885914": { + "type": "_sbcs", + "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\u1E02\u1E03\xA3\u010A\u010B\u1E0A\xA7\u1E80\xA9\u1E82\u1E0B\u1EF2\xAD\xAE\u0178\u1E1E\u1E1F\u0120\u0121\u1E40\u1E41\xB6\u1E56\u1E81\u1E57\u1E83\u1E60\u1EF3\u1E84\u1E85\u1E61\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\u0174\xD1\xD2\xD3\xD4\xD5\xD6\u1E6A\xD8\xD9\xDA\xDB\xDC\xDD\u0176\xDF\xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\u0175\xF1\xF2\xF3\xF4\xF5\xF6\u1E6B\xF8\xF9\xFA\xFB\xFC\xFD\u0177\xFF" + }, + "cp28604": "iso885914", + "iso885915": { + "type": "_sbcs", + "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\xA1\xA2\xA3\u20AC\xA5\u0160\xA7\u0161\xA9\xAA\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\u017D\xB5\xB6\xB7\u017E\xB9\xBA\xBB\u0152\u0153\u0178\xBF\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1\xD2\xD3\xD4\xD5\xD6\xD7\xD8\xD9\xDA\xDB\xDC\xDD\xDE\xDF\xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\xFA\xFB\xFC\xFD\xFE\xFF" + }, + "cp28605": "iso885915", + "iso885916": { + "type": "_sbcs", + "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\u0104\u0105\u0141\u20AC\u201E\u0160\xA7\u0161\xA9\u0218\xAB\u0179\xAD\u017A\u017B\xB0\xB1\u010C\u0142\u017D\u201D\xB6\xB7\u017E\u010D\u0219\xBB\u0152\u0153\u0178\u017C\xC0\xC1\xC2\u0102\xC4\u0106\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\u0110\u0143\xD2\xD3\xD4\u0150\xD6\u015A\u0170\xD9\xDA\xDB\xDC\u0118\u021A\xDF\xE0\xE1\xE2\u0103\xE4\u0107\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\u0111\u0144\xF2\xF3\xF4\u0151\xF6\u015B\u0171\xF9\xFA\xFB\xFC\u0119\u021B\xFF" + }, + "cp28606": "iso885916", + "cp437": { + "type": "_sbcs", + "chars": "\xC7\xFC\xE9\xE2\xE4\xE0\xE5\xE7\xEA\xEB\xE8\xEF\xEE\xEC\xC4\xC5\xC9\xE6\xC6\xF4\xF6\xF2\xFB\xF9\xFF\xD6\xDC\xA2\xA3\xA5\u20A7\u0192\xE1\xED\xF3\xFA\xF1\xD1\xAA\xBA\xBF\u2310\xAC\xBD\xBC\xA1\xAB\xBB\u2591\u2592\u2593\u2502\u2524\u2561\u2562\u2556\u2555\u2563\u2551\u2557\u255D\u255C\u255B\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u255E\u255F\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u2567\u2568\u2564\u2565\u2559\u2558\u2552\u2553\u256B\u256A\u2518\u250C\u2588\u2584\u258C\u2590\u2580\u03B1\xDF\u0393\u03C0\u03A3\u03C3\xB5\u03C4\u03A6\u0398\u03A9\u03B4\u221E\u03C6\u03B5\u2229\u2261\xB1\u2265\u2264\u2320\u2321\xF7\u2248\xB0\u2219\xB7\u221A\u207F\xB2\u25A0\xA0" + }, + "ibm437": "cp437", + "csibm437": "cp437", + "cp737": { + "type": "_sbcs", + "chars": "\u0391\u0392\u0393\u0394\u0395\u0396\u0397\u0398\u0399\u039A\u039B\u039C\u039D\u039E\u039F\u03A0\u03A1\u03A3\u03A4\u03A5\u03A6\u03A7\u03A8\u03A9\u03B1\u03B2\u03B3\u03B4\u03B5\u03B6\u03B7\u03B8\u03B9\u03BA\u03BB\u03BC\u03BD\u03BE\u03BF\u03C0\u03C1\u03C3\u03C2\u03C4\u03C5\u03C6\u03C7\u03C8\u2591\u2592\u2593\u2502\u2524\u2561\u2562\u2556\u2555\u2563\u2551\u2557\u255D\u255C\u255B\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u255E\u255F\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u2567\u2568\u2564\u2565\u2559\u2558\u2552\u2553\u256B\u256A\u2518\u250C\u2588\u2584\u258C\u2590\u2580\u03C9\u03AC\u03AD\u03AE\u03CA\u03AF\u03CC\u03CD\u03CB\u03CE\u0386\u0388\u0389\u038A\u038C\u038E\u038F\xB1\u2265\u2264\u03AA\u03AB\xF7\u2248\xB0\u2219\xB7\u221A\u207F\xB2\u25A0\xA0" + }, + "ibm737": "cp737", + "csibm737": "cp737", + "cp775": { + "type": "_sbcs", + "chars": "\u0106\xFC\xE9\u0101\xE4\u0123\xE5\u0107\u0142\u0113\u0156\u0157\u012B\u0179\xC4\xC5\xC9\xE6\xC6\u014D\xF6\u0122\xA2\u015A\u015B\xD6\xDC\xF8\xA3\xD8\xD7\xA4\u0100\u012A\xF3\u017B\u017C\u017A\u201D\xA6\xA9\xAE\xAC\xBD\xBC\u0141\xAB\xBB\u2591\u2592\u2593\u2502\u2524\u0104\u010C\u0118\u0116\u2563\u2551\u2557\u255D\u012E\u0160\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u0172\u016A\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u017D\u0105\u010D\u0119\u0117\u012F\u0161\u0173\u016B\u017E\u2518\u250C\u2588\u2584\u258C\u2590\u2580\xD3\xDF\u014C\u0143\xF5\xD5\xB5\u0144\u0136\u0137\u013B\u013C\u0146\u0112\u0145\u2019\xAD\xB1\u201C\xBE\xB6\xA7\xF7\u201E\xB0\u2219\xB7\xB9\xB3\xB2\u25A0\xA0" + }, + "ibm775": "cp775", + "csibm775": "cp775", + "cp850": { + "type": "_sbcs", + "chars": "\xC7\xFC\xE9\xE2\xE4\xE0\xE5\xE7\xEA\xEB\xE8\xEF\xEE\xEC\xC4\xC5\xC9\xE6\xC6\xF4\xF6\xF2\xFB\xF9\xFF\xD6\xDC\xF8\xA3\xD8\xD7\u0192\xE1\xED\xF3\xFA\xF1\xD1\xAA\xBA\xBF\xAE\xAC\xBD\xBC\xA1\xAB\xBB\u2591\u2592\u2593\u2502\u2524\xC1\xC2\xC0\xA9\u2563\u2551\u2557\u255D\xA2\xA5\u2510\u2514\u2534\u252C\u251C\u2500\u253C\xE3\xC3\u255A\u2554\u2569\u2566\u2560\u2550\u256C\xA4\xF0\xD0\xCA\xCB\xC8\u0131\xCD\xCE\xCF\u2518\u250C\u2588\u2584\xA6\xCC\u2580\xD3\xDF\xD4\xD2\xF5\xD5\xB5\xFE\xDE\xDA\xDB\xD9\xFD\xDD\xAF\xB4\xAD\xB1\u2017\xBE\xB6\xA7\xF7\xB8\xB0\xA8\xB7\xB9\xB3\xB2\u25A0\xA0" + }, + "ibm850": "cp850", + "csibm850": "cp850", + "cp852": { + "type": "_sbcs", + "chars": "\xC7\xFC\xE9\xE2\xE4\u016F\u0107\xE7\u0142\xEB\u0150\u0151\xEE\u0179\xC4\u0106\xC9\u0139\u013A\xF4\xF6\u013D\u013E\u015A\u015B\xD6\xDC\u0164\u0165\u0141\xD7\u010D\xE1\xED\xF3\xFA\u0104\u0105\u017D\u017E\u0118\u0119\xAC\u017A\u010C\u015F\xAB\xBB\u2591\u2592\u2593\u2502\u2524\xC1\xC2\u011A\u015E\u2563\u2551\u2557\u255D\u017B\u017C\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u0102\u0103\u255A\u2554\u2569\u2566\u2560\u2550\u256C\xA4\u0111\u0110\u010E\xCB\u010F\u0147\xCD\xCE\u011B\u2518\u250C\u2588\u2584\u0162\u016E\u2580\xD3\xDF\xD4\u0143\u0144\u0148\u0160\u0161\u0154\xDA\u0155\u0170\xFD\xDD\u0163\xB4\xAD\u02DD\u02DB\u02C7\u02D8\xA7\xF7\xB8\xB0\xA8\u02D9\u0171\u0158\u0159\u25A0\xA0" + }, + "ibm852": "cp852", + "csibm852": "cp852", + "cp855": { + "type": "_sbcs", + "chars": "\u0452\u0402\u0453\u0403\u0451\u0401\u0454\u0404\u0455\u0405\u0456\u0406\u0457\u0407\u0458\u0408\u0459\u0409\u045A\u040A\u045B\u040B\u045C\u040C\u045E\u040E\u045F\u040F\u044E\u042E\u044A\u042A\u0430\u0410\u0431\u0411\u0446\u0426\u0434\u0414\u0435\u0415\u0444\u0424\u0433\u0413\xAB\xBB\u2591\u2592\u2593\u2502\u2524\u0445\u0425\u0438\u0418\u2563\u2551\u2557\u255D\u0439\u0419\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u043A\u041A\u255A\u2554\u2569\u2566\u2560\u2550\u256C\xA4\u043B\u041B\u043C\u041C\u043D\u041D\u043E\u041E\u043F\u2518\u250C\u2588\u2584\u041F\u044F\u2580\u042F\u0440\u0420\u0441\u0421\u0442\u0422\u0443\u0423\u0436\u0416\u0432\u0412\u044C\u042C\u2116\xAD\u044B\u042B\u0437\u0417\u0448\u0428\u044D\u042D\u0449\u0429\u0447\u0427\xA7\u25A0\xA0" + }, + "ibm855": "cp855", + "csibm855": "cp855", + "cp856": { + "type": "_sbcs", + "chars": "\u05D0\u05D1\u05D2\u05D3\u05D4\u05D5\u05D6\u05D7\u05D8\u05D9\u05DA\u05DB\u05DC\u05DD\u05DE\u05DF\u05E0\u05E1\u05E2\u05E3\u05E4\u05E5\u05E6\u05E7\u05E8\u05E9\u05EA\uFFFD\xA3\uFFFD\xD7\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\xAE\xAC\xBD\xBC\uFFFD\xAB\xBB\u2591\u2592\u2593\u2502\u2524\uFFFD\uFFFD\uFFFD\xA9\u2563\u2551\u2557\u255D\xA2\xA5\u2510\u2514\u2534\u252C\u251C\u2500\u253C\uFFFD\uFFFD\u255A\u2554\u2569\u2566\u2560\u2550\u256C\xA4\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u2518\u250C\u2588\u2584\xA6\uFFFD\u2580\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\xB5\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\xAF\xB4\xAD\xB1\u2017\xBE\xB6\xA7\xF7\xB8\xB0\xA8\xB7\xB9\xB3\xB2\u25A0\xA0" + }, + "ibm856": "cp856", + "csibm856": "cp856", + "cp857": { + "type": "_sbcs", + "chars": "\xC7\xFC\xE9\xE2\xE4\xE0\xE5\xE7\xEA\xEB\xE8\xEF\xEE\u0131\xC4\xC5\xC9\xE6\xC6\xF4\xF6\xF2\xFB\xF9\u0130\xD6\xDC\xF8\xA3\xD8\u015E\u015F\xE1\xED\xF3\xFA\xF1\xD1\u011E\u011F\xBF\xAE\xAC\xBD\xBC\xA1\xAB\xBB\u2591\u2592\u2593\u2502\u2524\xC1\xC2\xC0\xA9\u2563\u2551\u2557\u255D\xA2\xA5\u2510\u2514\u2534\u252C\u251C\u2500\u253C\xE3\xC3\u255A\u2554\u2569\u2566\u2560\u2550\u256C\xA4\xBA\xAA\xCA\xCB\xC8\uFFFD\xCD\xCE\xCF\u2518\u250C\u2588\u2584\xA6\xCC\u2580\xD3\xDF\xD4\xD2\xF5\xD5\xB5\uFFFD\xD7\xDA\xDB\xD9\xEC\xFF\xAF\xB4\xAD\xB1\uFFFD\xBE\xB6\xA7\xF7\xB8\xB0\xA8\xB7\xB9\xB3\xB2\u25A0\xA0" + }, + "ibm857": "cp857", + "csibm857": "cp857", + "cp858": { + "type": "_sbcs", + "chars": "\xC7\xFC\xE9\xE2\xE4\xE0\xE5\xE7\xEA\xEB\xE8\xEF\xEE\xEC\xC4\xC5\xC9\xE6\xC6\xF4\xF6\xF2\xFB\xF9\xFF\xD6\xDC\xF8\xA3\xD8\xD7\u0192\xE1\xED\xF3\xFA\xF1\xD1\xAA\xBA\xBF\xAE\xAC\xBD\xBC\xA1\xAB\xBB\u2591\u2592\u2593\u2502\u2524\xC1\xC2\xC0\xA9\u2563\u2551\u2557\u255D\xA2\xA5\u2510\u2514\u2534\u252C\u251C\u2500\u253C\xE3\xC3\u255A\u2554\u2569\u2566\u2560\u2550\u256C\xA4\xF0\xD0\xCA\xCB\xC8\u20AC\xCD\xCE\xCF\u2518\u250C\u2588\u2584\xA6\xCC\u2580\xD3\xDF\xD4\xD2\xF5\xD5\xB5\xFE\xDE\xDA\xDB\xD9\xFD\xDD\xAF\xB4\xAD\xB1\u2017\xBE\xB6\xA7\xF7\xB8\xB0\xA8\xB7\xB9\xB3\xB2\u25A0\xA0" + }, + "ibm858": "cp858", + "csibm858": "cp858", + "cp860": { + "type": "_sbcs", + "chars": "\xC7\xFC\xE9\xE2\xE3\xE0\xC1\xE7\xEA\xCA\xE8\xCD\xD4\xEC\xC3\xC2\xC9\xC0\xC8\xF4\xF5\xF2\xDA\xF9\xCC\xD5\xDC\xA2\xA3\xD9\u20A7\xD3\xE1\xED\xF3\xFA\xF1\xD1\xAA\xBA\xBF\xD2\xAC\xBD\xBC\xA1\xAB\xBB\u2591\u2592\u2593\u2502\u2524\u2561\u2562\u2556\u2555\u2563\u2551\u2557\u255D\u255C\u255B\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u255E\u255F\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u2567\u2568\u2564\u2565\u2559\u2558\u2552\u2553\u256B\u256A\u2518\u250C\u2588\u2584\u258C\u2590\u2580\u03B1\xDF\u0393\u03C0\u03A3\u03C3\xB5\u03C4\u03A6\u0398\u03A9\u03B4\u221E\u03C6\u03B5\u2229\u2261\xB1\u2265\u2264\u2320\u2321\xF7\u2248\xB0\u2219\xB7\u221A\u207F\xB2\u25A0\xA0" + }, + "ibm860": "cp860", + "csibm860": "cp860", + "cp861": { + "type": "_sbcs", + "chars": "\xC7\xFC\xE9\xE2\xE4\xE0\xE5\xE7\xEA\xEB\xE8\xD0\xF0\xDE\xC4\xC5\xC9\xE6\xC6\xF4\xF6\xFE\xFB\xDD\xFD\xD6\xDC\xF8\xA3\xD8\u20A7\u0192\xE1\xED\xF3\xFA\xC1\xCD\xD3\xDA\xBF\u2310\xAC\xBD\xBC\xA1\xAB\xBB\u2591\u2592\u2593\u2502\u2524\u2561\u2562\u2556\u2555\u2563\u2551\u2557\u255D\u255C\u255B\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u255E\u255F\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u2567\u2568\u2564\u2565\u2559\u2558\u2552\u2553\u256B\u256A\u2518\u250C\u2588\u2584\u258C\u2590\u2580\u03B1\xDF\u0393\u03C0\u03A3\u03C3\xB5\u03C4\u03A6\u0398\u03A9\u03B4\u221E\u03C6\u03B5\u2229\u2261\xB1\u2265\u2264\u2320\u2321\xF7\u2248\xB0\u2219\xB7\u221A\u207F\xB2\u25A0\xA0" + }, + "ibm861": "cp861", + "csibm861": "cp861", + "cp862": { + "type": "_sbcs", + "chars": "\u05D0\u05D1\u05D2\u05D3\u05D4\u05D5\u05D6\u05D7\u05D8\u05D9\u05DA\u05DB\u05DC\u05DD\u05DE\u05DF\u05E0\u05E1\u05E2\u05E3\u05E4\u05E5\u05E6\u05E7\u05E8\u05E9\u05EA\xA2\xA3\xA5\u20A7\u0192\xE1\xED\xF3\xFA\xF1\xD1\xAA\xBA\xBF\u2310\xAC\xBD\xBC\xA1\xAB\xBB\u2591\u2592\u2593\u2502\u2524\u2561\u2562\u2556\u2555\u2563\u2551\u2557\u255D\u255C\u255B\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u255E\u255F\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u2567\u2568\u2564\u2565\u2559\u2558\u2552\u2553\u256B\u256A\u2518\u250C\u2588\u2584\u258C\u2590\u2580\u03B1\xDF\u0393\u03C0\u03A3\u03C3\xB5\u03C4\u03A6\u0398\u03A9\u03B4\u221E\u03C6\u03B5\u2229\u2261\xB1\u2265\u2264\u2320\u2321\xF7\u2248\xB0\u2219\xB7\u221A\u207F\xB2\u25A0\xA0" + }, + "ibm862": "cp862", + "csibm862": "cp862", + "cp863": { + "type": "_sbcs", + "chars": "\xC7\xFC\xE9\xE2\xC2\xE0\xB6\xE7\xEA\xEB\xE8\xEF\xEE\u2017\xC0\xA7\xC9\xC8\xCA\xF4\xCB\xCF\xFB\xF9\xA4\xD4\xDC\xA2\xA3\xD9\xDB\u0192\xA6\xB4\xF3\xFA\xA8\xB8\xB3\xAF\xCE\u2310\xAC\xBD\xBC\xBE\xAB\xBB\u2591\u2592\u2593\u2502\u2524\u2561\u2562\u2556\u2555\u2563\u2551\u2557\u255D\u255C\u255B\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u255E\u255F\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u2567\u2568\u2564\u2565\u2559\u2558\u2552\u2553\u256B\u256A\u2518\u250C\u2588\u2584\u258C\u2590\u2580\u03B1\xDF\u0393\u03C0\u03A3\u03C3\xB5\u03C4\u03A6\u0398\u03A9\u03B4\u221E\u03C6\u03B5\u2229\u2261\xB1\u2265\u2264\u2320\u2321\xF7\u2248\xB0\u2219\xB7\u221A\u207F\xB2\u25A0\xA0" + }, + "ibm863": "cp863", + "csibm863": "cp863", + "cp864": { + "type": "_sbcs", + "chars": "\0\x07\b \n\v\f\r\x1B !\"#$\u066A&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7F\xB0\xB7\u2219\u221A\u2592\u2500\u2502\u253C\u2524\u252C\u251C\u2534\u2510\u250C\u2514\u2518\u03B2\u221E\u03C6\xB1\xBD\xBC\u2248\xAB\xBB\uFEF7\uFEF8\uFFFD\uFFFD\uFEFB\uFEFC\uFFFD\xA0\xAD\uFE82\xA3\xA4\uFE84\uFFFD\uFFFD\uFE8E\uFE8F\uFE95\uFE99\u060C\uFE9D\uFEA1\uFEA5\u0660\u0661\u0662\u0663\u0664\u0665\u0666\u0667\u0668\u0669\uFED1\u061B\uFEB1\uFEB5\uFEB9\u061F\xA2\uFE80\uFE81\uFE83\uFE85\uFECA\uFE8B\uFE8D\uFE91\uFE93\uFE97\uFE9B\uFE9F\uFEA3\uFEA7\uFEA9\uFEAB\uFEAD\uFEAF\uFEB3\uFEB7\uFEBB\uFEBF\uFEC1\uFEC5\uFECB\uFECF\xA6\xAC\xF7\xD7\uFEC9\u0640\uFED3\uFED7\uFEDB\uFEDF\uFEE3\uFEE7\uFEEB\uFEED\uFEEF\uFEF3\uFEBD\uFECC\uFECE\uFECD\uFEE1\uFE7D\u0651\uFEE5\uFEE9\uFEEC\uFEF0\uFEF2\uFED0\uFED5\uFEF5\uFEF6\uFEDD\uFED9\uFEF1\u25A0\uFFFD" + }, + "ibm864": "cp864", + "csibm864": "cp864", + "cp865": { + "type": "_sbcs", + "chars": "\xC7\xFC\xE9\xE2\xE4\xE0\xE5\xE7\xEA\xEB\xE8\xEF\xEE\xEC\xC4\xC5\xC9\xE6\xC6\xF4\xF6\xF2\xFB\xF9\xFF\xD6\xDC\xF8\xA3\xD8\u20A7\u0192\xE1\xED\xF3\xFA\xF1\xD1\xAA\xBA\xBF\u2310\xAC\xBD\xBC\xA1\xAB\xA4\u2591\u2592\u2593\u2502\u2524\u2561\u2562\u2556\u2555\u2563\u2551\u2557\u255D\u255C\u255B\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u255E\u255F\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u2567\u2568\u2564\u2565\u2559\u2558\u2552\u2553\u256B\u256A\u2518\u250C\u2588\u2584\u258C\u2590\u2580\u03B1\xDF\u0393\u03C0\u03A3\u03C3\xB5\u03C4\u03A6\u0398\u03A9\u03B4\u221E\u03C6\u03B5\u2229\u2261\xB1\u2265\u2264\u2320\u2321\xF7\u2248\xB0\u2219\xB7\u221A\u207F\xB2\u25A0\xA0" + }, + "ibm865": "cp865", + "csibm865": "cp865", + "cp866": { + "type": "_sbcs", + "chars": "\u0410\u0411\u0412\u0413\u0414\u0415\u0416\u0417\u0418\u0419\u041A\u041B\u041C\u041D\u041E\u041F\u0420\u0421\u0422\u0423\u0424\u0425\u0426\u0427\u0428\u0429\u042A\u042B\u042C\u042D\u042E\u042F\u0430\u0431\u0432\u0433\u0434\u0435\u0436\u0437\u0438\u0439\u043A\u043B\u043C\u043D\u043E\u043F\u2591\u2592\u2593\u2502\u2524\u2561\u2562\u2556\u2555\u2563\u2551\u2557\u255D\u255C\u255B\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u255E\u255F\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u2567\u2568\u2564\u2565\u2559\u2558\u2552\u2553\u256B\u256A\u2518\u250C\u2588\u2584\u258C\u2590\u2580\u0440\u0441\u0442\u0443\u0444\u0445\u0446\u0447\u0448\u0449\u044A\u044B\u044C\u044D\u044E\u044F\u0401\u0451\u0404\u0454\u0407\u0457\u040E\u045E\xB0\u2219\xB7\u221A\u2116\xA4\u25A0\xA0" + }, + "ibm866": "cp866", + "csibm866": "cp866", + "cp869": { + "type": "_sbcs", + "chars": "\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u0386\uFFFD\xB7\xAC\xA6\u2018\u2019\u0388\u2015\u0389\u038A\u03AA\u038C\uFFFD\uFFFD\u038E\u03AB\xA9\u038F\xB2\xB3\u03AC\xA3\u03AD\u03AE\u03AF\u03CA\u0390\u03CC\u03CD\u0391\u0392\u0393\u0394\u0395\u0396\u0397\xBD\u0398\u0399\xAB\xBB\u2591\u2592\u2593\u2502\u2524\u039A\u039B\u039C\u039D\u2563\u2551\u2557\u255D\u039E\u039F\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u03A0\u03A1\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u03A3\u03A4\u03A5\u03A6\u03A7\u03A8\u03A9\u03B1\u03B2\u03B3\u2518\u250C\u2588\u2584\u03B4\u03B5\u2580\u03B6\u03B7\u03B8\u03B9\u03BA\u03BB\u03BC\u03BD\u03BE\u03BF\u03C0\u03C1\u03C3\u03C2\u03C4\u0384\xAD\xB1\u03C5\u03C6\u03C7\xA7\u03C8\u0385\xB0\xA8\u03C9\u03CB\u03B0\u03CE\u25A0\xA0" + }, + "ibm869": "cp869", + "csibm869": "cp869", + "cp922": { + "type": "_sbcs", + "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\xA1\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xAA\xAB\xAC\xAD\xAE\u203E\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xBA\xBB\xBC\xBD\xBE\xBF\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\u0160\xD1\xD2\xD3\xD4\xD5\xD6\xD7\xD8\xD9\xDA\xDB\xDC\xDD\u017D\xDF\xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\u0161\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\xFA\xFB\xFC\xFD\u017E\xFF" + }, + "ibm922": "cp922", + "csibm922": "cp922", + "cp1046": { + "type": "_sbcs", + "chars": "\uFE88\xD7\xF7\uF8F6\uF8F5\uF8F4\uF8F7\uFE71\x88\u25A0\u2502\u2500\u2510\u250C\u2514\u2518\uFE79\uFE7B\uFE7D\uFE7F\uFE77\uFE8A\uFEF0\uFEF3\uFEF2\uFECE\uFECF\uFED0\uFEF6\uFEF8\uFEFA\uFEFC\xA0\uF8FA\uF8F9\uF8F8\xA4\uF8FB\uFE8B\uFE91\uFE97\uFE9B\uFE9F\uFEA3\u060C\xAD\uFEA7\uFEB3\u0660\u0661\u0662\u0663\u0664\u0665\u0666\u0667\u0668\u0669\uFEB7\u061B\uFEBB\uFEBF\uFECA\u061F\uFECB\u0621\u0622\u0623\u0624\u0625\u0626\u0627\u0628\u0629\u062A\u062B\u062C\u062D\u062E\u062F\u0630\u0631\u0632\u0633\u0634\u0635\u0636\u0637\uFEC7\u0639\u063A\uFECC\uFE82\uFE84\uFE8E\uFED3\u0640\u0641\u0642\u0643\u0644\u0645\u0646\u0647\u0648\u0649\u064A\u064B\u064C\u064D\u064E\u064F\u0650\u0651\u0652\uFED7\uFEDB\uFEDF\uF8FC\uFEF5\uFEF7\uFEF9\uFEFB\uFEE3\uFEE7\uFEEC\uFEE9\uFFFD" + }, + "ibm1046": "cp1046", + "csibm1046": "cp1046", + "cp1124": { + "type": "_sbcs", + "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\u0401\u0402\u0490\u0404\u0405\u0406\u0407\u0408\u0409\u040A\u040B\u040C\xAD\u040E\u040F\u0410\u0411\u0412\u0413\u0414\u0415\u0416\u0417\u0418\u0419\u041A\u041B\u041C\u041D\u041E\u041F\u0420\u0421\u0422\u0423\u0424\u0425\u0426\u0427\u0428\u0429\u042A\u042B\u042C\u042D\u042E\u042F\u0430\u0431\u0432\u0433\u0434\u0435\u0436\u0437\u0438\u0439\u043A\u043B\u043C\u043D\u043E\u043F\u0440\u0441\u0442\u0443\u0444\u0445\u0446\u0447\u0448\u0449\u044A\u044B\u044C\u044D\u044E\u044F\u2116\u0451\u0452\u0491\u0454\u0455\u0456\u0457\u0458\u0459\u045A\u045B\u045C\xA7\u045E\u045F" + }, + "ibm1124": "cp1124", + "csibm1124": "cp1124", + "cp1125": { + "type": "_sbcs", + "chars": "\u0410\u0411\u0412\u0413\u0414\u0415\u0416\u0417\u0418\u0419\u041A\u041B\u041C\u041D\u041E\u041F\u0420\u0421\u0422\u0423\u0424\u0425\u0426\u0427\u0428\u0429\u042A\u042B\u042C\u042D\u042E\u042F\u0430\u0431\u0432\u0433\u0434\u0435\u0436\u0437\u0438\u0439\u043A\u043B\u043C\u043D\u043E\u043F\u2591\u2592\u2593\u2502\u2524\u2561\u2562\u2556\u2555\u2563\u2551\u2557\u255D\u255C\u255B\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u255E\u255F\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u2567\u2568\u2564\u2565\u2559\u2558\u2552\u2553\u256B\u256A\u2518\u250C\u2588\u2584\u258C\u2590\u2580\u0440\u0441\u0442\u0443\u0444\u0445\u0446\u0447\u0448\u0449\u044A\u044B\u044C\u044D\u044E\u044F\u0401\u0451\u0490\u0491\u0404\u0454\u0406\u0456\u0407\u0457\xB7\u221A\u2116\xA4\u25A0\xA0" + }, + "ibm1125": "cp1125", + "csibm1125": "cp1125", + "cp1129": { + "type": "_sbcs", + "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\xA1\xA2\xA3\xA4\xA5\xA6\xA7\u0153\xA9\xAA\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\u0178\xB5\xB6\xB7\u0152\xB9\xBA\xBB\xBC\xBD\xBE\xBF\xC0\xC1\xC2\u0102\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\u0300\xCD\xCE\xCF\u0110\xD1\u0309\xD3\xD4\u01A0\xD6\xD7\xD8\xD9\xDA\xDB\xDC\u01AF\u0303\xDF\xE0\xE1\xE2\u0103\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\u0301\xED\xEE\xEF\u0111\xF1\u0323\xF3\xF4\u01A1\xF6\xF7\xF8\xF9\xFA\xFB\xFC\u01B0\u20AB\xFF" + }, + "ibm1129": "cp1129", + "csibm1129": "cp1129", + "cp1133": { + "type": "_sbcs", + "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\u0E81\u0E82\u0E84\u0E87\u0E88\u0EAA\u0E8A\u0E8D\u0E94\u0E95\u0E96\u0E97\u0E99\u0E9A\u0E9B\u0E9C\u0E9D\u0E9E\u0E9F\u0EA1\u0EA2\u0EA3\u0EA5\u0EA7\u0EAB\u0EAD\u0EAE\uFFFD\uFFFD\uFFFD\u0EAF\u0EB0\u0EB2\u0EB3\u0EB4\u0EB5\u0EB6\u0EB7\u0EB8\u0EB9\u0EBC\u0EB1\u0EBB\u0EBD\uFFFD\uFFFD\uFFFD\u0EC0\u0EC1\u0EC2\u0EC3\u0EC4\u0EC8\u0EC9\u0ECA\u0ECB\u0ECC\u0ECD\u0EC6\uFFFD\u0EDC\u0EDD\u20AD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u0ED0\u0ED1\u0ED2\u0ED3\u0ED4\u0ED5\u0ED6\u0ED7\u0ED8\u0ED9\uFFFD\uFFFD\xA2\xAC\xA6\uFFFD" + }, + "ibm1133": "cp1133", + "csibm1133": "cp1133", + "cp1161": { + "type": "_sbcs", + "chars": "\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u0E48\u0E01\u0E02\u0E03\u0E04\u0E05\u0E06\u0E07\u0E08\u0E09\u0E0A\u0E0B\u0E0C\u0E0D\u0E0E\u0E0F\u0E10\u0E11\u0E12\u0E13\u0E14\u0E15\u0E16\u0E17\u0E18\u0E19\u0E1A\u0E1B\u0E1C\u0E1D\u0E1E\u0E1F\u0E20\u0E21\u0E22\u0E23\u0E24\u0E25\u0E26\u0E27\u0E28\u0E29\u0E2A\u0E2B\u0E2C\u0E2D\u0E2E\u0E2F\u0E30\u0E31\u0E32\u0E33\u0E34\u0E35\u0E36\u0E37\u0E38\u0E39\u0E3A\u0E49\u0E4A\u0E4B\u20AC\u0E3F\u0E40\u0E41\u0E42\u0E43\u0E44\u0E45\u0E46\u0E47\u0E48\u0E49\u0E4A\u0E4B\u0E4C\u0E4D\u0E4E\u0E4F\u0E50\u0E51\u0E52\u0E53\u0E54\u0E55\u0E56\u0E57\u0E58\u0E59\u0E5A\u0E5B\xA2\xAC\xA6\xA0" + }, + "ibm1161": "cp1161", + "csibm1161": "cp1161", + "cp1162": { + "type": "_sbcs", + "chars": "\u20AC\x81\x82\x83\x84\u2026\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\u2018\u2019\u201C\u201D\u2022\u2013\u2014\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\u0E01\u0E02\u0E03\u0E04\u0E05\u0E06\u0E07\u0E08\u0E09\u0E0A\u0E0B\u0E0C\u0E0D\u0E0E\u0E0F\u0E10\u0E11\u0E12\u0E13\u0E14\u0E15\u0E16\u0E17\u0E18\u0E19\u0E1A\u0E1B\u0E1C\u0E1D\u0E1E\u0E1F\u0E20\u0E21\u0E22\u0E23\u0E24\u0E25\u0E26\u0E27\u0E28\u0E29\u0E2A\u0E2B\u0E2C\u0E2D\u0E2E\u0E2F\u0E30\u0E31\u0E32\u0E33\u0E34\u0E35\u0E36\u0E37\u0E38\u0E39\u0E3A\uFFFD\uFFFD\uFFFD\uFFFD\u0E3F\u0E40\u0E41\u0E42\u0E43\u0E44\u0E45\u0E46\u0E47\u0E48\u0E49\u0E4A\u0E4B\u0E4C\u0E4D\u0E4E\u0E4F\u0E50\u0E51\u0E52\u0E53\u0E54\u0E55\u0E56\u0E57\u0E58\u0E59\u0E5A\u0E5B\uFFFD\uFFFD\uFFFD\uFFFD" + }, + "ibm1162": "cp1162", + "csibm1162": "cp1162", + "cp1163": { + "type": "_sbcs", + "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\xA1\xA2\xA3\u20AC\xA5\xA6\xA7\u0153\xA9\xAA\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\u0178\xB5\xB6\xB7\u0152\xB9\xBA\xBB\xBC\xBD\xBE\xBF\xC0\xC1\xC2\u0102\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\u0300\xCD\xCE\xCF\u0110\xD1\u0309\xD3\xD4\u01A0\xD6\xD7\xD8\xD9\xDA\xDB\xDC\u01AF\u0303\xDF\xE0\xE1\xE2\u0103\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\u0301\xED\xEE\xEF\u0111\xF1\u0323\xF3\xF4\u01A1\xF6\xF7\xF8\xF9\xFA\xFB\xFC\u01B0\u20AB\xFF" + }, + "ibm1163": "cp1163", + "csibm1163": "cp1163", + "maccroatian": { + "type": "_sbcs", + "chars": "\xC4\xC5\xC7\xC9\xD1\xD6\xDC\xE1\xE0\xE2\xE4\xE3\xE5\xE7\xE9\xE8\xEA\xEB\xED\xEC\xEE\xEF\xF1\xF3\xF2\xF4\xF6\xF5\xFA\xF9\xFB\xFC\u2020\xB0\xA2\xA3\xA7\u2022\xB6\xDF\xAE\u0160\u2122\xB4\xA8\u2260\u017D\xD8\u221E\xB1\u2264\u2265\u2206\xB5\u2202\u2211\u220F\u0161\u222B\xAA\xBA\u2126\u017E\xF8\xBF\xA1\xAC\u221A\u0192\u2248\u0106\xAB\u010C\u2026\xA0\xC0\xC3\xD5\u0152\u0153\u0110\u2014\u201C\u201D\u2018\u2019\xF7\u25CA\uFFFD\xA9\u2044\xA4\u2039\u203A\xC6\xBB\u2013\xB7\u201A\u201E\u2030\xC2\u0107\xC1\u010D\xC8\xCD\xCE\xCF\xCC\xD3\xD4\u0111\xD2\xDA\xDB\xD9\u0131\u02C6\u02DC\xAF\u03C0\xCB\u02DA\xB8\xCA\xE6\u02C7" + }, + "maccyrillic": { + "type": "_sbcs", + "chars": "\u0410\u0411\u0412\u0413\u0414\u0415\u0416\u0417\u0418\u0419\u041A\u041B\u041C\u041D\u041E\u041F\u0420\u0421\u0422\u0423\u0424\u0425\u0426\u0427\u0428\u0429\u042A\u042B\u042C\u042D\u042E\u042F\u2020\xB0\xA2\xA3\xA7\u2022\xB6\u0406\xAE\xA9\u2122\u0402\u0452\u2260\u0403\u0453\u221E\xB1\u2264\u2265\u0456\xB5\u2202\u0408\u0404\u0454\u0407\u0457\u0409\u0459\u040A\u045A\u0458\u0405\xAC\u221A\u0192\u2248\u2206\xAB\xBB\u2026\xA0\u040B\u045B\u040C\u045C\u0455\u2013\u2014\u201C\u201D\u2018\u2019\xF7\u201E\u040E\u045E\u040F\u045F\u2116\u0401\u0451\u044F\u0430\u0431\u0432\u0433\u0434\u0435\u0436\u0437\u0438\u0439\u043A\u043B\u043C\u043D\u043E\u043F\u0440\u0441\u0442\u0443\u0444\u0445\u0446\u0447\u0448\u0449\u044A\u044B\u044C\u044D\u044E\xA4" + }, + "macgreek": { + "type": "_sbcs", + "chars": "\xC4\xB9\xB2\xC9\xB3\xD6\xDC\u0385\xE0\xE2\xE4\u0384\xA8\xE7\xE9\xE8\xEA\xEB\xA3\u2122\xEE\xEF\u2022\xBD\u2030\xF4\xF6\xA6\xAD\xF9\xFB\xFC\u2020\u0393\u0394\u0398\u039B\u039E\u03A0\xDF\xAE\xA9\u03A3\u03AA\xA7\u2260\xB0\u0387\u0391\xB1\u2264\u2265\xA5\u0392\u0395\u0396\u0397\u0399\u039A\u039C\u03A6\u03AB\u03A8\u03A9\u03AC\u039D\xAC\u039F\u03A1\u2248\u03A4\xAB\xBB\u2026\xA0\u03A5\u03A7\u0386\u0388\u0153\u2013\u2015\u201C\u201D\u2018\u2019\xF7\u0389\u038A\u038C\u038E\u03AD\u03AE\u03AF\u03CC\u038F\u03CD\u03B1\u03B2\u03C8\u03B4\u03B5\u03C6\u03B3\u03B7\u03B9\u03BE\u03BA\u03BB\u03BC\u03BD\u03BF\u03C0\u03CE\u03C1\u03C3\u03C4\u03B8\u03C9\u03C2\u03C7\u03C5\u03B6\u03CA\u03CB\u0390\u03B0\uFFFD" + }, + "maciceland": { + "type": "_sbcs", + "chars": "\xC4\xC5\xC7\xC9\xD1\xD6\xDC\xE1\xE0\xE2\xE4\xE3\xE5\xE7\xE9\xE8\xEA\xEB\xED\xEC\xEE\xEF\xF1\xF3\xF2\xF4\xF6\xF5\xFA\xF9\xFB\xFC\xDD\xB0\xA2\xA3\xA7\u2022\xB6\xDF\xAE\xA9\u2122\xB4\xA8\u2260\xC6\xD8\u221E\xB1\u2264\u2265\xA5\xB5\u2202\u2211\u220F\u03C0\u222B\xAA\xBA\u2126\xE6\xF8\xBF\xA1\xAC\u221A\u0192\u2248\u2206\xAB\xBB\u2026\xA0\xC0\xC3\xD5\u0152\u0153\u2013\u2014\u201C\u201D\u2018\u2019\xF7\u25CA\xFF\u0178\u2044\xA4\xD0\xF0\xDE\xFE\xFD\xB7\u201A\u201E\u2030\xC2\xCA\xC1\xCB\xC8\xCD\xCE\xCF\xCC\xD3\xD4\uFFFD\xD2\xDA\xDB\xD9\u0131\u02C6\u02DC\xAF\u02D8\u02D9\u02DA\xB8\u02DD\u02DB\u02C7" + }, + "macroman": { + "type": "_sbcs", + "chars": "\xC4\xC5\xC7\xC9\xD1\xD6\xDC\xE1\xE0\xE2\xE4\xE3\xE5\xE7\xE9\xE8\xEA\xEB\xED\xEC\xEE\xEF\xF1\xF3\xF2\xF4\xF6\xF5\xFA\xF9\xFB\xFC\u2020\xB0\xA2\xA3\xA7\u2022\xB6\xDF\xAE\xA9\u2122\xB4\xA8\u2260\xC6\xD8\u221E\xB1\u2264\u2265\xA5\xB5\u2202\u2211\u220F\u03C0\u222B\xAA\xBA\u2126\xE6\xF8\xBF\xA1\xAC\u221A\u0192\u2248\u2206\xAB\xBB\u2026\xA0\xC0\xC3\xD5\u0152\u0153\u2013\u2014\u201C\u201D\u2018\u2019\xF7\u25CA\xFF\u0178\u2044\xA4\u2039\u203A\uFB01\uFB02\u2021\xB7\u201A\u201E\u2030\xC2\xCA\xC1\xCB\xC8\xCD\xCE\xCF\xCC\xD3\xD4\uFFFD\xD2\xDA\xDB\xD9\u0131\u02C6\u02DC\xAF\u02D8\u02D9\u02DA\xB8\u02DD\u02DB\u02C7" + }, + "macromania": { + "type": "_sbcs", + "chars": "\xC4\xC5\xC7\xC9\xD1\xD6\xDC\xE1\xE0\xE2\xE4\xE3\xE5\xE7\xE9\xE8\xEA\xEB\xED\xEC\xEE\xEF\xF1\xF3\xF2\xF4\xF6\xF5\xFA\xF9\xFB\xFC\u2020\xB0\xA2\xA3\xA7\u2022\xB6\xDF\xAE\xA9\u2122\xB4\xA8\u2260\u0102\u015E\u221E\xB1\u2264\u2265\xA5\xB5\u2202\u2211\u220F\u03C0\u222B\xAA\xBA\u2126\u0103\u015F\xBF\xA1\xAC\u221A\u0192\u2248\u2206\xAB\xBB\u2026\xA0\xC0\xC3\xD5\u0152\u0153\u2013\u2014\u201C\u201D\u2018\u2019\xF7\u25CA\xFF\u0178\u2044\xA4\u2039\u203A\u0162\u0163\u2021\xB7\u201A\u201E\u2030\xC2\xCA\xC1\xCB\xC8\xCD\xCE\xCF\xCC\xD3\xD4\uFFFD\xD2\xDA\xDB\xD9\u0131\u02C6\u02DC\xAF\u02D8\u02D9\u02DA\xB8\u02DD\u02DB\u02C7" + }, + "macthai": { + "type": "_sbcs", + "chars": "\xAB\xBB\u2026\uF88C\uF88F\uF892\uF895\uF898\uF88B\uF88E\uF891\uF894\uF897\u201C\u201D\uF899\uFFFD\u2022\uF884\uF889\uF885\uF886\uF887\uF888\uF88A\uF88D\uF890\uF893\uF896\u2018\u2019\uFFFD\xA0\u0E01\u0E02\u0E03\u0E04\u0E05\u0E06\u0E07\u0E08\u0E09\u0E0A\u0E0B\u0E0C\u0E0D\u0E0E\u0E0F\u0E10\u0E11\u0E12\u0E13\u0E14\u0E15\u0E16\u0E17\u0E18\u0E19\u0E1A\u0E1B\u0E1C\u0E1D\u0E1E\u0E1F\u0E20\u0E21\u0E22\u0E23\u0E24\u0E25\u0E26\u0E27\u0E28\u0E29\u0E2A\u0E2B\u0E2C\u0E2D\u0E2E\u0E2F\u0E30\u0E31\u0E32\u0E33\u0E34\u0E35\u0E36\u0E37\u0E38\u0E39\u0E3A\uFEFF\u200B\u2013\u2014\u0E3F\u0E40\u0E41\u0E42\u0E43\u0E44\u0E45\u0E46\u0E47\u0E48\u0E49\u0E4A\u0E4B\u0E4C\u0E4D\u2122\u0E4F\u0E50\u0E51\u0E52\u0E53\u0E54\u0E55\u0E56\u0E57\u0E58\u0E59\xAE\xA9\uFFFD\uFFFD\uFFFD\uFFFD" + }, + "macturkish": { + "type": "_sbcs", + "chars": "\xC4\xC5\xC7\xC9\xD1\xD6\xDC\xE1\xE0\xE2\xE4\xE3\xE5\xE7\xE9\xE8\xEA\xEB\xED\xEC\xEE\xEF\xF1\xF3\xF2\xF4\xF6\xF5\xFA\xF9\xFB\xFC\u2020\xB0\xA2\xA3\xA7\u2022\xB6\xDF\xAE\xA9\u2122\xB4\xA8\u2260\xC6\xD8\u221E\xB1\u2264\u2265\xA5\xB5\u2202\u2211\u220F\u03C0\u222B\xAA\xBA\u2126\xE6\xF8\xBF\xA1\xAC\u221A\u0192\u2248\u2206\xAB\xBB\u2026\xA0\xC0\xC3\xD5\u0152\u0153\u2013\u2014\u201C\u201D\u2018\u2019\xF7\u25CA\xFF\u0178\u011E\u011F\u0130\u0131\u015E\u015F\u2021\xB7\u201A\u201E\u2030\xC2\xCA\xC1\xCB\xC8\xCD\xCE\xCF\xCC\xD3\xD4\uFFFD\xD2\xDA\xDB\xD9\uFFFD\u02C6\u02DC\xAF\u02D8\u02D9\u02DA\xB8\u02DD\u02DB\u02C7" + }, + "macukraine": { + "type": "_sbcs", + "chars": "\u0410\u0411\u0412\u0413\u0414\u0415\u0416\u0417\u0418\u0419\u041A\u041B\u041C\u041D\u041E\u041F\u0420\u0421\u0422\u0423\u0424\u0425\u0426\u0427\u0428\u0429\u042A\u042B\u042C\u042D\u042E\u042F\u2020\xB0\u0490\xA3\xA7\u2022\xB6\u0406\xAE\xA9\u2122\u0402\u0452\u2260\u0403\u0453\u221E\xB1\u2264\u2265\u0456\xB5\u0491\u0408\u0404\u0454\u0407\u0457\u0409\u0459\u040A\u045A\u0458\u0405\xAC\u221A\u0192\u2248\u2206\xAB\xBB\u2026\xA0\u040B\u045B\u040C\u045C\u0455\u2013\u2014\u201C\u201D\u2018\u2019\xF7\u201E\u040E\u045E\u040F\u045F\u2116\u0401\u0451\u044F\u0430\u0431\u0432\u0433\u0434\u0435\u0436\u0437\u0438\u0439\u043A\u043B\u043C\u043D\u043E\u043F\u0440\u0441\u0442\u0443\u0444\u0445\u0446\u0447\u0448\u0449\u044A\u044B\u044C\u044D\u044E\xA4" + }, + "koi8r": { + "type": "_sbcs", + "chars": "\u2500\u2502\u250C\u2510\u2514\u2518\u251C\u2524\u252C\u2534\u253C\u2580\u2584\u2588\u258C\u2590\u2591\u2592\u2593\u2320\u25A0\u2219\u221A\u2248\u2264\u2265\xA0\u2321\xB0\xB2\xB7\xF7\u2550\u2551\u2552\u0451\u2553\u2554\u2555\u2556\u2557\u2558\u2559\u255A\u255B\u255C\u255D\u255E\u255F\u2560\u2561\u0401\u2562\u2563\u2564\u2565\u2566\u2567\u2568\u2569\u256A\u256B\u256C\xA9\u044E\u0430\u0431\u0446\u0434\u0435\u0444\u0433\u0445\u0438\u0439\u043A\u043B\u043C\u043D\u043E\u043F\u044F\u0440\u0441\u0442\u0443\u0436\u0432\u044C\u044B\u0437\u0448\u044D\u0449\u0447\u044A\u042E\u0410\u0411\u0426\u0414\u0415\u0424\u0413\u0425\u0418\u0419\u041A\u041B\u041C\u041D\u041E\u041F\u042F\u0420\u0421\u0422\u0423\u0416\u0412\u042C\u042B\u0417\u0428\u042D\u0429\u0427\u042A" + }, + "koi8u": { + "type": "_sbcs", + "chars": "\u2500\u2502\u250C\u2510\u2514\u2518\u251C\u2524\u252C\u2534\u253C\u2580\u2584\u2588\u258C\u2590\u2591\u2592\u2593\u2320\u25A0\u2219\u221A\u2248\u2264\u2265\xA0\u2321\xB0\xB2\xB7\xF7\u2550\u2551\u2552\u0451\u0454\u2554\u0456\u0457\u2557\u2558\u2559\u255A\u255B\u0491\u255D\u255E\u255F\u2560\u2561\u0401\u0404\u2563\u0406\u0407\u2566\u2567\u2568\u2569\u256A\u0490\u256C\xA9\u044E\u0430\u0431\u0446\u0434\u0435\u0444\u0433\u0445\u0438\u0439\u043A\u043B\u043C\u043D\u043E\u043F\u044F\u0440\u0441\u0442\u0443\u0436\u0432\u044C\u044B\u0437\u0448\u044D\u0449\u0447\u044A\u042E\u0410\u0411\u0426\u0414\u0415\u0424\u0413\u0425\u0418\u0419\u041A\u041B\u041C\u041D\u041E\u041F\u042F\u0420\u0421\u0422\u0423\u0416\u0412\u042C\u042B\u0417\u0428\u042D\u0429\u0427\u042A" + }, + "koi8ru": { + "type": "_sbcs", + "chars": "\u2500\u2502\u250C\u2510\u2514\u2518\u251C\u2524\u252C\u2534\u253C\u2580\u2584\u2588\u258C\u2590\u2591\u2592\u2593\u2320\u25A0\u2219\u221A\u2248\u2264\u2265\xA0\u2321\xB0\xB2\xB7\xF7\u2550\u2551\u2552\u0451\u0454\u2554\u0456\u0457\u2557\u2558\u2559\u255A\u255B\u0491\u045E\u255E\u255F\u2560\u2561\u0401\u0404\u2563\u0406\u0407\u2566\u2567\u2568\u2569\u256A\u0490\u040E\xA9\u044E\u0430\u0431\u0446\u0434\u0435\u0444\u0433\u0445\u0438\u0439\u043A\u043B\u043C\u043D\u043E\u043F\u044F\u0440\u0441\u0442\u0443\u0436\u0432\u044C\u044B\u0437\u0448\u044D\u0449\u0447\u044A\u042E\u0410\u0411\u0426\u0414\u0415\u0424\u0413\u0425\u0418\u0419\u041A\u041B\u041C\u041D\u041E\u041F\u042F\u0420\u0421\u0422\u0423\u0416\u0412\u042C\u042B\u0417\u0428\u042D\u0429\u0427\u042A" + }, + "koi8t": { + "type": "_sbcs", + "chars": "\u049B\u0493\u201A\u0492\u201E\u2026\u2020\u2021\uFFFD\u2030\u04B3\u2039\u04B2\u04B7\u04B6\uFFFD\u049A\u2018\u2019\u201C\u201D\u2022\u2013\u2014\uFFFD\u2122\uFFFD\u203A\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u04EF\u04EE\u0451\xA4\u04E3\xA6\xA7\uFFFD\uFFFD\uFFFD\xAB\xAC\xAD\xAE\uFFFD\xB0\xB1\xB2\u0401\uFFFD\u04E2\xB6\xB7\uFFFD\u2116\uFFFD\xBB\uFFFD\uFFFD\uFFFD\xA9\u044E\u0430\u0431\u0446\u0434\u0435\u0444\u0433\u0445\u0438\u0439\u043A\u043B\u043C\u043D\u043E\u043F\u044F\u0440\u0441\u0442\u0443\u0436\u0432\u044C\u044B\u0437\u0448\u044D\u0449\u0447\u044A\u042E\u0410\u0411\u0426\u0414\u0415\u0424\u0413\u0425\u0418\u0419\u041A\u041B\u041C\u041D\u041E\u041F\u042F\u0420\u0421\u0422\u0423\u0416\u0412\u042C\u042B\u0417\u0428\u042D\u0429\u0427\u042A" + }, + "armscii8": { + "type": "_sbcs", + "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\uFFFD\u0587\u0589)(\xBB\xAB\u2014.\u055D,-\u058A\u2026\u055C\u055B\u055E\u0531\u0561\u0532\u0562\u0533\u0563\u0534\u0564\u0535\u0565\u0536\u0566\u0537\u0567\u0538\u0568\u0539\u0569\u053A\u056A\u053B\u056B\u053C\u056C\u053D\u056D\u053E\u056E\u053F\u056F\u0540\u0570\u0541\u0571\u0542\u0572\u0543\u0573\u0544\u0574\u0545\u0575\u0546\u0576\u0547\u0577\u0548\u0578\u0549\u0579\u054A\u057A\u054B\u057B\u054C\u057C\u054D\u057D\u054E\u057E\u054F\u057F\u0550\u0580\u0551\u0581\u0552\u0582\u0553\u0583\u0554\u0584\u0555\u0585\u0556\u0586\u055A\uFFFD" + }, + "rk1048": { + "type": "_sbcs", + "chars": "\u0402\u0403\u201A\u0453\u201E\u2026\u2020\u2021\u20AC\u2030\u0409\u2039\u040A\u049A\u04BA\u040F\u0452\u2018\u2019\u201C\u201D\u2022\u2013\u2014\uFFFD\u2122\u0459\u203A\u045A\u049B\u04BB\u045F\xA0\u04B0\u04B1\u04D8\xA4\u04E8\xA6\xA7\u0401\xA9\u0492\xAB\xAC\xAD\xAE\u04AE\xB0\xB1\u0406\u0456\u04E9\xB5\xB6\xB7\u0451\u2116\u0493\xBB\u04D9\u04A2\u04A3\u04AF\u0410\u0411\u0412\u0413\u0414\u0415\u0416\u0417\u0418\u0419\u041A\u041B\u041C\u041D\u041E\u041F\u0420\u0421\u0422\u0423\u0424\u0425\u0426\u0427\u0428\u0429\u042A\u042B\u042C\u042D\u042E\u042F\u0430\u0431\u0432\u0433\u0434\u0435\u0436\u0437\u0438\u0439\u043A\u043B\u043C\u043D\u043E\u043F\u0440\u0441\u0442\u0443\u0444\u0445\u0446\u0447\u0448\u0449\u044A\u044B\u044C\u044D\u044E\u044F" + }, + "tcvn": { + "type": "_sbcs", + "chars": "\0\xDA\u1EE4\u1EEA\u1EEC\u1EEE\x07\b \n\v\f\r\u1EE8\u1EF0\u1EF2\u1EF6\u1EF8\xDD\u1EF4\x1B !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7F\xC0\u1EA2\xC3\xC1\u1EA0\u1EB6\u1EAC\xC8\u1EBA\u1EBC\xC9\u1EB8\u1EC6\xCC\u1EC8\u0128\xCD\u1ECA\xD2\u1ECE\xD5\xD3\u1ECC\u1ED8\u1EDC\u1EDE\u1EE0\u1EDA\u1EE2\xD9\u1EE6\u0168\xA0\u0102\xC2\xCA\xD4\u01A0\u01AF\u0110\u0103\xE2\xEA\xF4\u01A1\u01B0\u0111\u1EB0\u0300\u0309\u0303\u0301\u0323\xE0\u1EA3\xE3\xE1\u1EA1\u1EB2\u1EB1\u1EB3\u1EB5\u1EAF\u1EB4\u1EAE\u1EA6\u1EA8\u1EAA\u1EA4\u1EC0\u1EB7\u1EA7\u1EA9\u1EAB\u1EA5\u1EAD\xE8\u1EC2\u1EBB\u1EBD\xE9\u1EB9\u1EC1\u1EC3\u1EC5\u1EBF\u1EC7\xEC\u1EC9\u1EC4\u1EBE\u1ED2\u0129\xED\u1ECB\xF2\u1ED4\u1ECF\xF5\xF3\u1ECD\u1ED3\u1ED5\u1ED7\u1ED1\u1ED9\u1EDD\u1EDF\u1EE1\u1EDB\u1EE3\xF9\u1ED6\u1EE7\u0169\xFA\u1EE5\u1EEB\u1EED\u1EEF\u1EE9\u1EF1\u1EF3\u1EF7\u1EF9\xFD\u1EF5\u1ED0" + }, + "georgianacademy": { + "type": "_sbcs", + "chars": "\x80\x81\u201A\u0192\u201E\u2026\u2020\u2021\u02C6\u2030\u0160\u2039\u0152\x8D\x8E\x8F\x90\u2018\u2019\u201C\u201D\u2022\u2013\u2014\u02DC\u2122\u0161\u203A\u0153\x9D\x9E\u0178\xA0\xA1\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xAA\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xBA\xBB\xBC\xBD\xBE\xBF\u10D0\u10D1\u10D2\u10D3\u10D4\u10D5\u10D6\u10D7\u10D8\u10D9\u10DA\u10DB\u10DC\u10DD\u10DE\u10DF\u10E0\u10E1\u10E2\u10E3\u10E4\u10E5\u10E6\u10E7\u10E8\u10E9\u10EA\u10EB\u10EC\u10ED\u10EE\u10EF\u10F0\u10F1\u10F2\u10F3\u10F4\u10F5\u10F6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\xFA\xFB\xFC\xFD\xFE\xFF" + }, + "georgianps": { + "type": "_sbcs", + "chars": "\x80\x81\u201A\u0192\u201E\u2026\u2020\u2021\u02C6\u2030\u0160\u2039\u0152\x8D\x8E\x8F\x90\u2018\u2019\u201C\u201D\u2022\u2013\u2014\u02DC\u2122\u0161\u203A\u0153\x9D\x9E\u0178\xA0\xA1\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xAA\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xBA\xBB\xBC\xBD\xBE\xBF\u10D0\u10D1\u10D2\u10D3\u10D4\u10D5\u10D6\u10F1\u10D7\u10D8\u10D9\u10DA\u10DB\u10DC\u10F2\u10DD\u10DE\u10DF\u10E0\u10E1\u10E2\u10F3\u10E3\u10E4\u10E5\u10E6\u10E7\u10E8\u10E9\u10EA\u10EB\u10EC\u10ED\u10EE\u10F4\u10EF\u10F0\u10F5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\xFA\xFB\xFC\xFD\xFE\xFF" + }, + "pt154": { + "type": "_sbcs", + "chars": "\u0496\u0492\u04EE\u0493\u201E\u2026\u04B6\u04AE\u04B2\u04AF\u04A0\u04E2\u04A2\u049A\u04BA\u04B8\u0497\u2018\u2019\u201C\u201D\u2022\u2013\u2014\u04B3\u04B7\u04A1\u04E3\u04A3\u049B\u04BB\u04B9\xA0\u040E\u045E\u0408\u04E8\u0498\u04B0\xA7\u0401\xA9\u04D8\xAB\xAC\u04EF\xAE\u049C\xB0\u04B1\u0406\u0456\u0499\u04E9\xB6\xB7\u0451\u2116\u04D9\xBB\u0458\u04AA\u04AB\u049D\u0410\u0411\u0412\u0413\u0414\u0415\u0416\u0417\u0418\u0419\u041A\u041B\u041C\u041D\u041E\u041F\u0420\u0421\u0422\u0423\u0424\u0425\u0426\u0427\u0428\u0429\u042A\u042B\u042C\u042D\u042E\u042F\u0430\u0431\u0432\u0433\u0434\u0435\u0436\u0437\u0438\u0439\u043A\u043B\u043C\u043D\u043E\u043F\u0440\u0441\u0442\u0443\u0444\u0445\u0446\u0447\u0448\u0449\u044A\u044B\u044C\u044D\u044E\u044F" + }, + "viscii": { + "type": "_sbcs", + "chars": "\0\u1EB2\u1EB4\u1EAA\x07\b \n\v\f\r\u1EF6\u1EF8\x1B\u1EF4 !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7F\u1EA0\u1EAE\u1EB0\u1EB6\u1EA4\u1EA6\u1EA8\u1EAC\u1EBC\u1EB8\u1EBE\u1EC0\u1EC2\u1EC4\u1EC6\u1ED0\u1ED2\u1ED4\u1ED6\u1ED8\u1EE2\u1EDA\u1EDC\u1EDE\u1ECA\u1ECE\u1ECC\u1EC8\u1EE6\u0168\u1EE4\u1EF2\xD5\u1EAF\u1EB1\u1EB7\u1EA5\u1EA7\u1EA9\u1EAD\u1EBD\u1EB9\u1EBF\u1EC1\u1EC3\u1EC5\u1EC7\u1ED1\u1ED3\u1ED5\u1ED7\u1EE0\u01A0\u1ED9\u1EDD\u1EDF\u1ECB\u1EF0\u1EE8\u1EEA\u1EEC\u01A1\u1EDB\u01AF\xC0\xC1\xC2\xC3\u1EA2\u0102\u1EB3\u1EB5\xC8\xC9\xCA\u1EBA\xCC\xCD\u0128\u1EF3\u0110\u1EE9\xD2\xD3\xD4\u1EA1\u1EF7\u1EEB\u1EED\xD9\xDA\u1EF9\u1EF5\xDD\u1EE1\u01B0\xE0\xE1\xE2\xE3\u1EA3\u0103\u1EEF\u1EAB\xE8\xE9\xEA\u1EBB\xEC\xED\u0129\u1EC9\u0111\u1EF1\xF2\xF3\xF4\xF5\u1ECF\u1ECD\u1EE5\xF9\xFA\u0169\u1EE7\xFD\u1EE3\u1EEE" + }, + "iso646cn": { + "type": "_sbcs", + "chars": "\0\x07\b \n\v\f\r\x1B !\"#\xA5%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}\u203E\x7F\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD" + }, + "iso646jp": { + "type": "_sbcs", + "chars": "\0\x07\b \n\v\f\r\x1B !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\xA5]^_`abcdefghijklmnopqrstuvwxyz{|}\u203E\x7F\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD" + }, + "hproman8": { + "type": "_sbcs", + "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\xC0\xC2\xC8\xCA\xCB\xCE\xCF\xB4\u02CB\u02C6\xA8\u02DC\xD9\xDB\u20A4\xAF\xDD\xFD\xB0\xC7\xE7\xD1\xF1\xA1\xBF\xA4\xA3\xA5\xA7\u0192\xA2\xE2\xEA\xF4\xFB\xE1\xE9\xF3\xFA\xE0\xE8\xF2\xF9\xE4\xEB\xF6\xFC\xC5\xEE\xD8\xC6\xE5\xED\xF8\xE6\xC4\xEC\xD6\xDC\xC9\xEF\xDF\xD4\xC1\xC3\xE3\xD0\xF0\xCD\xCC\xD3\xD2\xD5\xF5\u0160\u0161\xDA\u0178\xFF\xDE\xFE\xB7\xB5\xB6\xBE\u2014\xBC\xBD\xAA\xBA\xAB\u25A0\xBB\xB1\uFFFD" + }, + "macintosh": { + "type": "_sbcs", + "chars": "\xC4\xC5\xC7\xC9\xD1\xD6\xDC\xE1\xE0\xE2\xE4\xE3\xE5\xE7\xE9\xE8\xEA\xEB\xED\xEC\xEE\xEF\xF1\xF3\xF2\xF4\xF6\xF5\xFA\xF9\xFB\xFC\u2020\xB0\xA2\xA3\xA7\u2022\xB6\xDF\xAE\xA9\u2122\xB4\xA8\u2260\xC6\xD8\u221E\xB1\u2264\u2265\xA5\xB5\u2202\u2211\u220F\u03C0\u222B\xAA\xBA\u2126\xE6\xF8\xBF\xA1\xAC\u221A\u0192\u2248\u2206\xAB\xBB\u2026\xA0\xC0\xC3\xD5\u0152\u0153\u2013\u2014\u201C\u201D\u2018\u2019\xF7\u25CA\xFF\u0178\u2044\xA4\u2039\u203A\uFB01\uFB02\u2021\xB7\u201A\u201E\u2030\xC2\xCA\xC1\xCB\xC8\xCD\xCE\xCF\xCC\xD3\xD4\uFFFD\xD2\xDA\xDB\xD9\u0131\u02C6\u02DC\xAF\u02D8\u02D9\u02DA\xB8\u02DD\u02DB\u02C7" + }, + "ascii": { + "type": "_sbcs", + "chars": "\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD" + }, + "tis620": { + "type": "_sbcs", + "chars": "\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u0E01\u0E02\u0E03\u0E04\u0E05\u0E06\u0E07\u0E08\u0E09\u0E0A\u0E0B\u0E0C\u0E0D\u0E0E\u0E0F\u0E10\u0E11\u0E12\u0E13\u0E14\u0E15\u0E16\u0E17\u0E18\u0E19\u0E1A\u0E1B\u0E1C\u0E1D\u0E1E\u0E1F\u0E20\u0E21\u0E22\u0E23\u0E24\u0E25\u0E26\u0E27\u0E28\u0E29\u0E2A\u0E2B\u0E2C\u0E2D\u0E2E\u0E2F\u0E30\u0E31\u0E32\u0E33\u0E34\u0E35\u0E36\u0E37\u0E38\u0E39\u0E3A\uFFFD\uFFFD\uFFFD\uFFFD\u0E3F\u0E40\u0E41\u0E42\u0E43\u0E44\u0E45\u0E46\u0E47\u0E48\u0E49\u0E4A\u0E4B\u0E4C\u0E4D\u0E4E\u0E4F\u0E50\u0E51\u0E52\u0E53\u0E54\u0E55\u0E56\u0E57\u0E58\u0E59\u0E5A\u0E5B\uFFFD\uFFFD\uFFFD\uFFFD" + } + }; + } +}); + +// node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/encodings/dbcs-codec.js +var require_dbcs_codec = __commonJS({ + "node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/encodings/dbcs-codec.js"(exports) { + "use strict"; + var Buffer2 = require_safer().Buffer; + exports._dbcs = DBCSCodec; + var UNASSIGNED = -1; + var GB18030_CODE = -2; + var SEQ_START = -10; + var NODE_START = -1e3; + var UNASSIGNED_NODE = new Array(256); + var DEF_CHAR = -1; + for (i5 = 0; i5 < 256; i5++) { + UNASSIGNED_NODE[i5] = UNASSIGNED; + } + var i5; + function DBCSCodec(codecOptions, iconv) { + this.encodingName = codecOptions.encodingName; + if (!codecOptions) { + throw new Error("DBCS codec is called without the data."); + } + if (!codecOptions.table) { + throw new Error("Encoding '" + this.encodingName + "' has no data."); + } + var mappingTable = codecOptions.table(); + this.decodeTables = []; + this.decodeTables[0] = UNASSIGNED_NODE.slice(0); + this.decodeTableSeq = []; + for (var i6 = 0; i6 < mappingTable.length; i6++) { + this._addDecodeChunk(mappingTable[i6]); + } + if (typeof codecOptions.gb18030 === "function") { + this.gb18030 = codecOptions.gb18030(); + var commonThirdByteNodeIdx = this.decodeTables.length; + this.decodeTables.push(UNASSIGNED_NODE.slice(0)); + var commonFourthByteNodeIdx = this.decodeTables.length; + this.decodeTables.push(UNASSIGNED_NODE.slice(0)); + var firstByteNode = this.decodeTables[0]; + for (var i6 = 129; i6 <= 254; i6++) { + var secondByteNode = this.decodeTables[NODE_START - firstByteNode[i6]]; + for (var j5 = 48; j5 <= 57; j5++) { + if (secondByteNode[j5] === UNASSIGNED) { + secondByteNode[j5] = NODE_START - commonThirdByteNodeIdx; + } else if (secondByteNode[j5] > NODE_START) { + throw new Error("gb18030 decode tables conflict at byte 2"); + } + var thirdByteNode = this.decodeTables[NODE_START - secondByteNode[j5]]; + for (var k5 = 129; k5 <= 254; k5++) { + if (thirdByteNode[k5] === UNASSIGNED) { + thirdByteNode[k5] = NODE_START - commonFourthByteNodeIdx; + } else if (thirdByteNode[k5] === NODE_START - commonFourthByteNodeIdx) { + continue; + } else if (thirdByteNode[k5] > NODE_START) { + throw new Error("gb18030 decode tables conflict at byte 3"); + } + var fourthByteNode = this.decodeTables[NODE_START - thirdByteNode[k5]]; + for (var l5 = 48; l5 <= 57; l5++) { + if (fourthByteNode[l5] === UNASSIGNED) { + fourthByteNode[l5] = GB18030_CODE; + } + } + } + } + } + } + this.defaultCharUnicode = iconv.defaultCharUnicode; + this.encodeTable = []; + this.encodeTableSeq = []; + var skipEncodeChars = {}; + if (codecOptions.encodeSkipVals) { + for (var i6 = 0; i6 < codecOptions.encodeSkipVals.length; i6++) { + var val = codecOptions.encodeSkipVals[i6]; + if (typeof val === "number") { + skipEncodeChars[val] = true; + } else { + for (var j5 = val.from; j5 <= val.to; j5++) { + skipEncodeChars[j5] = true; + } + } + } + } + this._fillEncodeTable(0, 0, skipEncodeChars); + if (codecOptions.encodeAdd) { + for (var uChar in codecOptions.encodeAdd) { + if (Object.prototype.hasOwnProperty.call(codecOptions.encodeAdd, uChar)) { + this._setEncodeChar(uChar.charCodeAt(0), codecOptions.encodeAdd[uChar]); + } + } + } + this.defCharSB = this.encodeTable[0][iconv.defaultCharSingleByte.charCodeAt(0)]; + if (this.defCharSB === UNASSIGNED) this.defCharSB = this.encodeTable[0]["?"]; + if (this.defCharSB === UNASSIGNED) this.defCharSB = "?".charCodeAt(0); + } + DBCSCodec.prototype.encoder = DBCSEncoder; + DBCSCodec.prototype.decoder = DBCSDecoder; + DBCSCodec.prototype._getDecodeTrieNode = function(addr) { + var bytes = []; + for (; addr > 0; addr >>>= 8) { + bytes.push(addr & 255); + } + if (bytes.length == 0) { + bytes.push(0); + } + var node = this.decodeTables[0]; + for (var i6 = bytes.length - 1; i6 > 0; i6--) { + var val = node[bytes[i6]]; + if (val == UNASSIGNED) { + node[bytes[i6]] = NODE_START - this.decodeTables.length; + this.decodeTables.push(node = UNASSIGNED_NODE.slice(0)); + } else if (val <= NODE_START) { + node = this.decodeTables[NODE_START - val]; + } else { + throw new Error("Overwrite byte in " + this.encodingName + ", addr: " + addr.toString(16)); + } + } + return node; + }; + DBCSCodec.prototype._addDecodeChunk = function(chunk) { + var curAddr = parseInt(chunk[0], 16); + var writeTable = this._getDecodeTrieNode(curAddr); + curAddr = curAddr & 255; + for (var k5 = 1; k5 < chunk.length; k5++) { + var part = chunk[k5]; + if (typeof part === "string") { + for (var l5 = 0; l5 < part.length; ) { + var code = part.charCodeAt(l5++); + if (code >= 55296 && code < 56320) { + var codeTrail = part.charCodeAt(l5++); + if (codeTrail >= 56320 && codeTrail < 57344) { + writeTable[curAddr++] = 65536 + (code - 55296) * 1024 + (codeTrail - 56320); + } else { + throw new Error("Incorrect surrogate pair in " + this.encodingName + " at chunk " + chunk[0]); + } + } else if (code > 4080 && code <= 4095) { + var len = 4095 - code + 2; + var seq = []; + for (var m5 = 0; m5 < len; m5++) { + seq.push(part.charCodeAt(l5++)); + } + writeTable[curAddr++] = SEQ_START - this.decodeTableSeq.length; + this.decodeTableSeq.push(seq); + } else { + writeTable[curAddr++] = code; + } + } + } else if (typeof part === "number") { + var charCode = writeTable[curAddr - 1] + 1; + for (var l5 = 0; l5 < part; l5++) { + writeTable[curAddr++] = charCode++; + } + } else { + throw new Error("Incorrect type '" + typeof part + "' given in " + this.encodingName + " at chunk " + chunk[0]); + } + } + if (curAddr > 255) { + throw new Error("Incorrect chunk in " + this.encodingName + " at addr " + chunk[0] + ": too long" + curAddr); + } + }; + DBCSCodec.prototype._getEncodeBucket = function(uCode) { + var high = uCode >> 8; + if (this.encodeTable[high] === void 0) { + this.encodeTable[high] = UNASSIGNED_NODE.slice(0); + } + return this.encodeTable[high]; + }; + DBCSCodec.prototype._setEncodeChar = function(uCode, dbcsCode) { + var bucket = this._getEncodeBucket(uCode); + var low = uCode & 255; + if (bucket[low] <= SEQ_START) { + this.encodeTableSeq[SEQ_START - bucket[low]][DEF_CHAR] = dbcsCode; + } else if (bucket[low] == UNASSIGNED) { + bucket[low] = dbcsCode; + } + }; + DBCSCodec.prototype._setEncodeSequence = function(seq, dbcsCode) { + var uCode = seq[0]; + var bucket = this._getEncodeBucket(uCode); + var low = uCode & 255; + var node; + if (bucket[low] <= SEQ_START) { + node = this.encodeTableSeq[SEQ_START - bucket[low]]; + } else { + node = {}; + if (bucket[low] !== UNASSIGNED) node[DEF_CHAR] = bucket[low]; + bucket[low] = SEQ_START - this.encodeTableSeq.length; + this.encodeTableSeq.push(node); + } + for (var j5 = 1; j5 < seq.length - 1; j5++) { + var oldVal = node[uCode]; + if (typeof oldVal === "object") { + node = oldVal; + } else { + node = node[uCode] = {}; + if (oldVal !== void 0) { + node[DEF_CHAR] = oldVal; + } + } + } + uCode = seq[seq.length - 1]; + node[uCode] = dbcsCode; + }; + DBCSCodec.prototype._fillEncodeTable = function(nodeIdx, prefix, skipEncodeChars) { + var node = this.decodeTables[nodeIdx]; + var hasValues = false; + var subNodeEmpty = {}; + for (var i6 = 0; i6 < 256; i6++) { + var uCode = node[i6]; + var mbCode = prefix + i6; + if (skipEncodeChars[mbCode]) { + continue; + } + if (uCode >= 0) { + this._setEncodeChar(uCode, mbCode); + hasValues = true; + } else if (uCode <= NODE_START) { + var subNodeIdx = NODE_START - uCode; + if (!subNodeEmpty[subNodeIdx]) { + var newPrefix = mbCode << 8 >>> 0; + if (this._fillEncodeTable(subNodeIdx, newPrefix, skipEncodeChars)) { + hasValues = true; + } else { + subNodeEmpty[subNodeIdx] = true; + } + } + } else if (uCode <= SEQ_START) { + this._setEncodeSequence(this.decodeTableSeq[SEQ_START - uCode], mbCode); + hasValues = true; + } + } + return hasValues; + }; + function DBCSEncoder(options, codec2) { + this.leadSurrogate = -1; + this.seqObj = void 0; + this.encodeTable = codec2.encodeTable; + this.encodeTableSeq = codec2.encodeTableSeq; + this.defaultCharSingleByte = codec2.defCharSB; + this.gb18030 = codec2.gb18030; + } + DBCSEncoder.prototype.write = function(str) { + var newBuf = Buffer2.alloc(str.length * (this.gb18030 ? 4 : 3)); + var leadSurrogate = this.leadSurrogate; + var seqObj = this.seqObj; + var nextChar = -1; + var i6 = 0; + var j5 = 0; + while (true) { + if (nextChar === -1) { + if (i6 == str.length) break; + var uCode = str.charCodeAt(i6++); + } else { + var uCode = nextChar; + nextChar = -1; + } + if (uCode >= 55296 && uCode < 57344) { + if (uCode < 56320) { + if (leadSurrogate === -1) { + leadSurrogate = uCode; + continue; + } else { + leadSurrogate = uCode; + uCode = UNASSIGNED; + } + } else { + if (leadSurrogate !== -1) { + uCode = 65536 + (leadSurrogate - 55296) * 1024 + (uCode - 56320); + leadSurrogate = -1; + } else { + uCode = UNASSIGNED; + } + } + } else if (leadSurrogate !== -1) { + nextChar = uCode; + uCode = UNASSIGNED; + leadSurrogate = -1; + } + var dbcsCode = UNASSIGNED; + if (seqObj !== void 0 && uCode != UNASSIGNED) { + var resCode = seqObj[uCode]; + if (typeof resCode === "object") { + seqObj = resCode; + continue; + } else if (typeof resCode === "number") { + dbcsCode = resCode; + } else if (resCode == void 0) { + resCode = seqObj[DEF_CHAR]; + if (resCode !== void 0) { + dbcsCode = resCode; + nextChar = uCode; + } else { + } + } + seqObj = void 0; + } else if (uCode >= 0) { + var subtable = this.encodeTable[uCode >> 8]; + if (subtable !== void 0) { + dbcsCode = subtable[uCode & 255]; + } + if (dbcsCode <= SEQ_START) { + seqObj = this.encodeTableSeq[SEQ_START - dbcsCode]; + continue; + } + if (dbcsCode == UNASSIGNED && this.gb18030) { + var idx = findIdx(this.gb18030.uChars, uCode); + if (idx != -1) { + var dbcsCode = this.gb18030.gbChars[idx] + (uCode - this.gb18030.uChars[idx]); + newBuf[j5++] = 129 + Math.floor(dbcsCode / 12600); + dbcsCode = dbcsCode % 12600; + newBuf[j5++] = 48 + Math.floor(dbcsCode / 1260); + dbcsCode = dbcsCode % 1260; + newBuf[j5++] = 129 + Math.floor(dbcsCode / 10); + dbcsCode = dbcsCode % 10; + newBuf[j5++] = 48 + dbcsCode; + continue; + } + } + } + if (dbcsCode === UNASSIGNED) { + dbcsCode = this.defaultCharSingleByte; + } + if (dbcsCode < 256) { + newBuf[j5++] = dbcsCode; + } else if (dbcsCode < 65536) { + newBuf[j5++] = dbcsCode >> 8; + newBuf[j5++] = dbcsCode & 255; + } else if (dbcsCode < 16777216) { + newBuf[j5++] = dbcsCode >> 16; + newBuf[j5++] = dbcsCode >> 8 & 255; + newBuf[j5++] = dbcsCode & 255; + } else { + newBuf[j5++] = dbcsCode >>> 24; + newBuf[j5++] = dbcsCode >>> 16 & 255; + newBuf[j5++] = dbcsCode >>> 8 & 255; + newBuf[j5++] = dbcsCode & 255; + } + } + this.seqObj = seqObj; + this.leadSurrogate = leadSurrogate; + return newBuf.slice(0, j5); + }; + DBCSEncoder.prototype.end = function() { + if (this.leadSurrogate === -1 && this.seqObj === void 0) { + return; + } + var newBuf = Buffer2.alloc(10); + var j5 = 0; + if (this.seqObj) { + var dbcsCode = this.seqObj[DEF_CHAR]; + if (dbcsCode !== void 0) { + if (dbcsCode < 256) { + newBuf[j5++] = dbcsCode; + } else { + newBuf[j5++] = dbcsCode >> 8; + newBuf[j5++] = dbcsCode & 255; + } + } else { + } + this.seqObj = void 0; + } + if (this.leadSurrogate !== -1) { + newBuf[j5++] = this.defaultCharSingleByte; + this.leadSurrogate = -1; + } + return newBuf.slice(0, j5); + }; + DBCSEncoder.prototype.findIdx = findIdx; + function DBCSDecoder(options, codec2) { + this.nodeIdx = 0; + this.prevBytes = []; + this.decodeTables = codec2.decodeTables; + this.decodeTableSeq = codec2.decodeTableSeq; + this.defaultCharUnicode = codec2.defaultCharUnicode; + this.gb18030 = codec2.gb18030; + } + DBCSDecoder.prototype.write = function(buf) { + var newBuf = Buffer2.alloc(buf.length * 2); + var nodeIdx = this.nodeIdx; + var prevBytes = this.prevBytes; + var prevOffset = this.prevBytes.length; + var seqStart = -this.prevBytes.length; + var uCode; + for (var i6 = 0, j5 = 0; i6 < buf.length; i6++) { + var curByte = i6 >= 0 ? buf[i6] : prevBytes[i6 + prevOffset]; + var uCode = this.decodeTables[nodeIdx][curByte]; + if (uCode >= 0) { + } else if (uCode === UNASSIGNED) { + uCode = this.defaultCharUnicode.charCodeAt(0); + i6 = seqStart; + } else if (uCode === GB18030_CODE) { + if (i6 >= 3) { + var ptr = (buf[i6 - 3] - 129) * 12600 + (buf[i6 - 2] - 48) * 1260 + (buf[i6 - 1] - 129) * 10 + (curByte - 48); + } else { + var ptr = (prevBytes[i6 - 3 + prevOffset] - 129) * 12600 + ((i6 - 2 >= 0 ? buf[i6 - 2] : prevBytes[i6 - 2 + prevOffset]) - 48) * 1260 + ((i6 - 1 >= 0 ? buf[i6 - 1] : prevBytes[i6 - 1 + prevOffset]) - 129) * 10 + (curByte - 48); + } + var idx = findIdx(this.gb18030.gbChars, ptr); + uCode = this.gb18030.uChars[idx] + ptr - this.gb18030.gbChars[idx]; + } else if (uCode <= NODE_START) { + nodeIdx = NODE_START - uCode; + continue; + } else if (uCode <= SEQ_START) { + var seq = this.decodeTableSeq[SEQ_START - uCode]; + for (var k5 = 0; k5 < seq.length - 1; k5++) { + uCode = seq[k5]; + newBuf[j5++] = uCode & 255; + newBuf[j5++] = uCode >> 8; + } + uCode = seq[seq.length - 1]; + } else { + throw new Error("iconv-lite internal error: invalid decoding table value " + uCode + " at " + nodeIdx + "/" + curByte); + } + if (uCode >= 65536) { + uCode -= 65536; + var uCodeLead = 55296 | uCode >> 10; + newBuf[j5++] = uCodeLead & 255; + newBuf[j5++] = uCodeLead >> 8; + uCode = 56320 | uCode & 1023; + } + newBuf[j5++] = uCode & 255; + newBuf[j5++] = uCode >> 8; + nodeIdx = 0; + seqStart = i6 + 1; + } + this.nodeIdx = nodeIdx; + this.prevBytes = seqStart >= 0 ? Array.prototype.slice.call(buf, seqStart) : prevBytes.slice(seqStart + prevOffset).concat(Array.prototype.slice.call(buf)); + return newBuf.slice(0, j5).toString("ucs2"); + }; + DBCSDecoder.prototype.end = function() { + var ret = ""; + while (this.prevBytes.length > 0) { + ret += this.defaultCharUnicode; + var bytesArr = this.prevBytes.slice(1); + this.prevBytes = []; + this.nodeIdx = 0; + if (bytesArr.length > 0) { + ret += this.write(bytesArr); + } + } + this.prevBytes = []; + this.nodeIdx = 0; + return ret; + }; + function findIdx(table, val) { + if (table[0] > val) { + return -1; + } + var l5 = 0; + var r5 = table.length; + while (l5 < r5 - 1) { + var mid = l5 + (r5 - l5 + 1 >> 1); + if (table[mid] <= val) { + l5 = mid; + } else { + r5 = mid; + } + } + return l5; + } + } +}); + +// node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/encodings/tables/shiftjis.json +var require_shiftjis = __commonJS({ + "node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/encodings/tables/shiftjis.json"(exports, module) { + module.exports = [ + ["0", "\0", 128], + ["a1", "\uFF61", 62], + ["8140", "\u3000\u3001\u3002\uFF0C\uFF0E\u30FB\uFF1A\uFF1B\uFF1F\uFF01\u309B\u309C\xB4\uFF40\xA8\uFF3E\uFFE3\uFF3F\u30FD\u30FE\u309D\u309E\u3003\u4EDD\u3005\u3006\u3007\u30FC\u2015\u2010\uFF0F\uFF3C\uFF5E\u2225\uFF5C\u2026\u2025\u2018\u2019\u201C\u201D\uFF08\uFF09\u3014\u3015\uFF3B\uFF3D\uFF5B\uFF5D\u3008", 9, "\uFF0B\uFF0D\xB1\xD7"], + ["8180", "\xF7\uFF1D\u2260\uFF1C\uFF1E\u2266\u2267\u221E\u2234\u2642\u2640\xB0\u2032\u2033\u2103\uFFE5\uFF04\uFFE0\uFFE1\uFF05\uFF03\uFF06\uFF0A\uFF20\xA7\u2606\u2605\u25CB\u25CF\u25CE\u25C7\u25C6\u25A1\u25A0\u25B3\u25B2\u25BD\u25BC\u203B\u3012\u2192\u2190\u2191\u2193\u3013"], + ["81b8", "\u2208\u220B\u2286\u2287\u2282\u2283\u222A\u2229"], + ["81c8", "\u2227\u2228\uFFE2\u21D2\u21D4\u2200\u2203"], + ["81da", "\u2220\u22A5\u2312\u2202\u2207\u2261\u2252\u226A\u226B\u221A\u223D\u221D\u2235\u222B\u222C"], + ["81f0", "\u212B\u2030\u266F\u266D\u266A\u2020\u2021\xB6"], + ["81fc", "\u25EF"], + ["824f", "\uFF10", 9], + ["8260", "\uFF21", 25], + ["8281", "\uFF41", 25], + ["829f", "\u3041", 82], + ["8340", "\u30A1", 62], + ["8380", "\u30E0", 22], + ["839f", "\u0391", 16, "\u03A3", 6], + ["83bf", "\u03B1", 16, "\u03C3", 6], + ["8440", "\u0410", 5, "\u0401\u0416", 25], + ["8470", "\u0430", 5, "\u0451\u0436", 7], + ["8480", "\u043E", 17], + ["849f", "\u2500\u2502\u250C\u2510\u2518\u2514\u251C\u252C\u2524\u2534\u253C\u2501\u2503\u250F\u2513\u251B\u2517\u2523\u2533\u252B\u253B\u254B\u2520\u252F\u2528\u2537\u253F\u251D\u2530\u2525\u2538\u2542"], + ["8740", "\u2460", 19, "\u2160", 9], + ["875f", "\u3349\u3314\u3322\u334D\u3318\u3327\u3303\u3336\u3351\u3357\u330D\u3326\u3323\u332B\u334A\u333B\u339C\u339D\u339E\u338E\u338F\u33C4\u33A1"], + ["877e", "\u337B"], + ["8780", "\u301D\u301F\u2116\u33CD\u2121\u32A4", 4, "\u3231\u3232\u3239\u337E\u337D\u337C\u2252\u2261\u222B\u222E\u2211\u221A\u22A5\u2220\u221F\u22BF\u2235\u2229\u222A"], + ["889f", "\u4E9C\u5516\u5A03\u963F\u54C0\u611B\u6328\u59F6\u9022\u8475\u831C\u7A50\u60AA\u63E1\u6E25\u65ED\u8466\u82A6\u9BF5\u6893\u5727\u65A1\u6271\u5B9B\u59D0\u867B\u98F4\u7D62\u7DBE\u9B8E\u6216\u7C9F\u88B7\u5B89\u5EB5\u6309\u6697\u6848\u95C7\u978D\u674F\u4EE5\u4F0A\u4F4D\u4F9D\u5049\u56F2\u5937\u59D4\u5A01\u5C09\u60DF\u610F\u6170\u6613\u6905\u70BA\u754F\u7570\u79FB\u7DAD\u7DEF\u80C3\u840E\u8863\u8B02\u9055\u907A\u533B\u4E95\u4EA5\u57DF\u80B2\u90C1\u78EF\u4E00\u58F1\u6EA2\u9038\u7A32\u8328\u828B\u9C2F\u5141\u5370\u54BD\u54E1\u56E0\u59FB\u5F15\u98F2\u6DEB\u80E4\u852D"], + ["8940", "\u9662\u9670\u96A0\u97FB\u540B\u53F3\u5B87\u70CF\u7FBD\u8FC2\u96E8\u536F\u9D5C\u7ABA\u4E11\u7893\u81FC\u6E26\u5618\u5504\u6B1D\u851A\u9C3B\u59E5\u53A9\u6D66\u74DC\u958F\u5642\u4E91\u904B\u96F2\u834F\u990C\u53E1\u55B6\u5B30\u5F71\u6620\u66F3\u6804\u6C38\u6CF3\u6D29\u745B\u76C8\u7A4E\u9834\u82F1\u885B\u8A60\u92ED\u6DB2\u75AB\u76CA\u99C5\u60A6\u8B01\u8D8A\u95B2\u698E\u53AD\u5186"], + ["8980", "\u5712\u5830\u5944\u5BB4\u5EF6\u6028\u63A9\u63F4\u6CBF\u6F14\u708E\u7114\u7159\u71D5\u733F\u7E01\u8276\u82D1\u8597\u9060\u925B\u9D1B\u5869\u65BC\u6C5A\u7525\u51F9\u592E\u5965\u5F80\u5FDC\u62BC\u65FA\u6A2A\u6B27\u6BB4\u738B\u7FC1\u8956\u9D2C\u9D0E\u9EC4\u5CA1\u6C96\u837B\u5104\u5C4B\u61B6\u81C6\u6876\u7261\u4E59\u4FFA\u5378\u6069\u6E29\u7A4F\u97F3\u4E0B\u5316\u4EEE\u4F55\u4F3D\u4FA1\u4F73\u52A0\u53EF\u5609\u590F\u5AC1\u5BB6\u5BE1\u79D1\u6687\u679C\u67B6\u6B4C\u6CB3\u706B\u73C2\u798D\u79BE\u7A3C\u7B87\u82B1\u82DB\u8304\u8377\u83EF\u83D3\u8766\u8AB2\u5629\u8CA8\u8FE6\u904E\u971E\u868A\u4FC4\u5CE8\u6211\u7259\u753B\u81E5\u82BD\u86FE\u8CC0\u96C5\u9913\u99D5\u4ECB\u4F1A\u89E3\u56DE\u584A\u58CA\u5EFB\u5FEB\u602A\u6094\u6062\u61D0\u6212\u62D0\u6539"], + ["8a40", "\u9B41\u6666\u68B0\u6D77\u7070\u754C\u7686\u7D75\u82A5\u87F9\u958B\u968E\u8C9D\u51F1\u52BE\u5916\u54B3\u5BB3\u5D16\u6168\u6982\u6DAF\u788D\u84CB\u8857\u8A72\u93A7\u9AB8\u6D6C\u99A8\u86D9\u57A3\u67FF\u86CE\u920E\u5283\u5687\u5404\u5ED3\u62E1\u64B9\u683C\u6838\u6BBB\u7372\u78BA\u7A6B\u899A\u89D2\u8D6B\u8F03\u90ED\u95A3\u9694\u9769\u5B66\u5CB3\u697D\u984D\u984E\u639B\u7B20\u6A2B"], + ["8a80", "\u6A7F\u68B6\u9C0D\u6F5F\u5272\u559D\u6070\u62EC\u6D3B\u6E07\u6ED1\u845B\u8910\u8F44\u4E14\u9C39\u53F6\u691B\u6A3A\u9784\u682A\u515C\u7AC3\u84B2\u91DC\u938C\u565B\u9D28\u6822\u8305\u8431\u7CA5\u5208\u82C5\u74E6\u4E7E\u4F83\u51A0\u5BD2\u520A\u52D8\u52E7\u5DFB\u559A\u582A\u59E6\u5B8C\u5B98\u5BDB\u5E72\u5E79\u60A3\u611F\u6163\u61BE\u63DB\u6562\u67D1\u6853\u68FA\u6B3E\u6B53\u6C57\u6F22\u6F97\u6F45\u74B0\u7518\u76E3\u770B\u7AFF\u7BA1\u7C21\u7DE9\u7F36\u7FF0\u809D\u8266\u839E\u89B3\u8ACC\u8CAB\u9084\u9451\u9593\u9591\u95A2\u9665\u97D3\u9928\u8218\u4E38\u542B\u5CB8\u5DCC\u73A9\u764C\u773C\u5CA9\u7FEB\u8D0B\u96C1\u9811\u9854\u9858\u4F01\u4F0E\u5371\u559C\u5668\u57FA\u5947\u5B09\u5BC4\u5C90\u5E0C\u5E7E\u5FCC\u63EE\u673A\u65D7\u65E2\u671F\u68CB\u68C4"], + ["8b40", "\u6A5F\u5E30\u6BC5\u6C17\u6C7D\u757F\u7948\u5B63\u7A00\u7D00\u5FBD\u898F\u8A18\u8CB4\u8D77\u8ECC\u8F1D\u98E2\u9A0E\u9B3C\u4E80\u507D\u5100\u5993\u5B9C\u622F\u6280\u64EC\u6B3A\u72A0\u7591\u7947\u7FA9\u87FB\u8ABC\u8B70\u63AC\u83CA\u97A0\u5409\u5403\u55AB\u6854\u6A58\u8A70\u7827\u6775\u9ECD\u5374\u5BA2\u811A\u8650\u9006\u4E18\u4E45\u4EC7\u4F11\u53CA\u5438\u5BAE\u5F13\u6025\u6551"], + ["8b80", "\u673D\u6C42\u6C72\u6CE3\u7078\u7403\u7A76\u7AAE\u7B08\u7D1A\u7CFE\u7D66\u65E7\u725B\u53BB\u5C45\u5DE8\u62D2\u62E0\u6319\u6E20\u865A\u8A31\u8DDD\u92F8\u6F01\u79A6\u9B5A\u4EA8\u4EAB\u4EAC\u4F9B\u4FA0\u50D1\u5147\u7AF6\u5171\u51F6\u5354\u5321\u537F\u53EB\u55AC\u5883\u5CE1\u5F37\u5F4A\u602F\u6050\u606D\u631F\u6559\u6A4B\u6CC1\u72C2\u72ED\u77EF\u80F8\u8105\u8208\u854E\u90F7\u93E1\u97FF\u9957\u9A5A\u4EF0\u51DD\u5C2D\u6681\u696D\u5C40\u66F2\u6975\u7389\u6850\u7C81\u50C5\u52E4\u5747\u5DFE\u9326\u65A4\u6B23\u6B3D\u7434\u7981\u79BD\u7B4B\u7DCA\u82B9\u83CC\u887F\u895F\u8B39\u8FD1\u91D1\u541F\u9280\u4E5D\u5036\u53E5\u533A\u72D7\u7396\u77E9\u82E6\u8EAF\u99C6\u99C8\u99D2\u5177\u611A\u865E\u55B0\u7A7A\u5076\u5BD3\u9047\u9685\u4E32\u6ADB\u91E7\u5C51\u5C48"], + ["8c40", "\u6398\u7A9F\u6C93\u9774\u8F61\u7AAA\u718A\u9688\u7C82\u6817\u7E70\u6851\u936C\u52F2\u541B\u85AB\u8A13\u7FA4\u8ECD\u90E1\u5366\u8888\u7941\u4FC2\u50BE\u5211\u5144\u5553\u572D\u73EA\u578B\u5951\u5F62\u5F84\u6075\u6176\u6167\u61A9\u63B2\u643A\u656C\u666F\u6842\u6E13\u7566\u7A3D\u7CFB\u7D4C\u7D99\u7E4B\u7F6B\u830E\u834A\u86CD\u8A08\u8A63\u8B66\u8EFD\u981A\u9D8F\u82B8\u8FCE\u9BE8"], + ["8c80", "\u5287\u621F\u6483\u6FC0\u9699\u6841\u5091\u6B20\u6C7A\u6F54\u7A74\u7D50\u8840\u8A23\u6708\u4EF6\u5039\u5026\u5065\u517C\u5238\u5263\u55A7\u570F\u5805\u5ACC\u5EFA\u61B2\u61F8\u62F3\u6372\u691C\u6A29\u727D\u72AC\u732E\u7814\u786F\u7D79\u770C\u80A9\u898B\u8B19\u8CE2\u8ED2\u9063\u9375\u967A\u9855\u9A13\u9E78\u5143\u539F\u53B3\u5E7B\u5F26\u6E1B\u6E90\u7384\u73FE\u7D43\u8237\u8A00\u8AFA\u9650\u4E4E\u500B\u53E4\u547C\u56FA\u59D1\u5B64\u5DF1\u5EAB\u5F27\u6238\u6545\u67AF\u6E56\u72D0\u7CCA\u88B4\u80A1\u80E1\u83F0\u864E\u8A87\u8DE8\u9237\u96C7\u9867\u9F13\u4E94\u4E92\u4F0D\u5348\u5449\u543E\u5A2F\u5F8C\u5FA1\u609F\u68A7\u6A8E\u745A\u7881\u8A9E\u8AA4\u8B77\u9190\u4E5E\u9BC9\u4EA4\u4F7C\u4FAF\u5019\u5016\u5149\u516C\u529F\u52B9\u52FE\u539A\u53E3\u5411"], + ["8d40", "\u540E\u5589\u5751\u57A2\u597D\u5B54\u5B5D\u5B8F\u5DE5\u5DE7\u5DF7\u5E78\u5E83\u5E9A\u5EB7\u5F18\u6052\u614C\u6297\u62D8\u63A7\u653B\u6602\u6643\u66F4\u676D\u6821\u6897\u69CB\u6C5F\u6D2A\u6D69\u6E2F\u6E9D\u7532\u7687\u786C\u7A3F\u7CE0\u7D05\u7D18\u7D5E\u7DB1\u8015\u8003\u80AF\u80B1\u8154\u818F\u822A\u8352\u884C\u8861\u8B1B\u8CA2\u8CFC\u90CA\u9175\u9271\u783F\u92FC\u95A4\u964D"], + ["8d80", "\u9805\u9999\u9AD8\u9D3B\u525B\u52AB\u53F7\u5408\u58D5\u62F7\u6FE0\u8C6A\u8F5F\u9EB9\u514B\u523B\u544A\u56FD\u7A40\u9177\u9D60\u9ED2\u7344\u6F09\u8170\u7511\u5FFD\u60DA\u9AA8\u72DB\u8FBC\u6B64\u9803\u4ECA\u56F0\u5764\u58BE\u5A5A\u6068\u61C7\u660F\u6606\u6839\u68B1\u6DF7\u75D5\u7D3A\u826E\u9B42\u4E9B\u4F50\u53C9\u5506\u5D6F\u5DE6\u5DEE\u67FB\u6C99\u7473\u7802\u8A50\u9396\u88DF\u5750\u5EA7\u632B\u50B5\u50AC\u518D\u6700\u54C9\u585E\u59BB\u5BB0\u5F69\u624D\u63A1\u683D\u6B73\u6E08\u707D\u91C7\u7280\u7815\u7826\u796D\u658E\u7D30\u83DC\u88C1\u8F09\u969B\u5264\u5728\u6750\u7F6A\u8CA1\u51B4\u5742\u962A\u583A\u698A\u80B4\u54B2\u5D0E\u57FC\u7895\u9DFA\u4F5C\u524A\u548B\u643E\u6628\u6714\u67F5\u7A84\u7B56\u7D22\u932F\u685C\u9BAD\u7B39\u5319\u518A\u5237"], + ["8e40", "\u5BDF\u62F6\u64AE\u64E6\u672D\u6BBA\u85A9\u96D1\u7690\u9BD6\u634C\u9306\u9BAB\u76BF\u6652\u4E09\u5098\u53C2\u5C71\u60E8\u6492\u6563\u685F\u71E6\u73CA\u7523\u7B97\u7E82\u8695\u8B83\u8CDB\u9178\u9910\u65AC\u66AB\u6B8B\u4ED5\u4ED4\u4F3A\u4F7F\u523A\u53F8\u53F2\u55E3\u56DB\u58EB\u59CB\u59C9\u59FF\u5B50\u5C4D\u5E02\u5E2B\u5FD7\u601D\u6307\u652F\u5B5C\u65AF\u65BD\u65E8\u679D\u6B62"], + ["8e80", "\u6B7B\u6C0F\u7345\u7949\u79C1\u7CF8\u7D19\u7D2B\u80A2\u8102\u81F3\u8996\u8A5E\u8A69\u8A66\u8A8C\u8AEE\u8CC7\u8CDC\u96CC\u98FC\u6B6F\u4E8B\u4F3C\u4F8D\u5150\u5B57\u5BFA\u6148\u6301\u6642\u6B21\u6ECB\u6CBB\u723E\u74BD\u75D4\u78C1\u793A\u800C\u8033\u81EA\u8494\u8F9E\u6C50\u9E7F\u5F0F\u8B58\u9D2B\u7AFA\u8EF8\u5B8D\u96EB\u4E03\u53F1\u57F7\u5931\u5AC9\u5BA4\u6089\u6E7F\u6F06\u75BE\u8CEA\u5B9F\u8500\u7BE0\u5072\u67F4\u829D\u5C61\u854A\u7E1E\u820E\u5199\u5C04\u6368\u8D66\u659C\u716E\u793E\u7D17\u8005\u8B1D\u8ECA\u906E\u86C7\u90AA\u501F\u52FA\u5C3A\u6753\u707C\u7235\u914C\u91C8\u932B\u82E5\u5BC2\u5F31\u60F9\u4E3B\u53D6\u5B88\u624B\u6731\u6B8A\u72E9\u73E0\u7A2E\u816B\u8DA3\u9152\u9996\u5112\u53D7\u546A\u5BFF\u6388\u6A39\u7DAC\u9700\u56DA\u53CE\u5468"], + ["8f40", "\u5B97\u5C31\u5DDE\u4FEE\u6101\u62FE\u6D32\u79C0\u79CB\u7D42\u7E4D\u7FD2\u81ED\u821F\u8490\u8846\u8972\u8B90\u8E74\u8F2F\u9031\u914B\u916C\u96C6\u919C\u4EC0\u4F4F\u5145\u5341\u5F93\u620E\u67D4\u6C41\u6E0B\u7363\u7E26\u91CD\u9283\u53D4\u5919\u5BBF\u6DD1\u795D\u7E2E\u7C9B\u587E\u719F\u51FA\u8853\u8FF0\u4FCA\u5CFB\u6625\u77AC\u7AE3\u821C\u99FF\u51C6\u5FAA\u65EC\u696F\u6B89\u6DF3"], + ["8f80", "\u6E96\u6F64\u76FE\u7D14\u5DE1\u9075\u9187\u9806\u51E6\u521D\u6240\u6691\u66D9\u6E1A\u5EB6\u7DD2\u7F72\u66F8\u85AF\u85F7\u8AF8\u52A9\u53D9\u5973\u5E8F\u5F90\u6055\u92E4\u9664\u50B7\u511F\u52DD\u5320\u5347\u53EC\u54E8\u5546\u5531\u5617\u5968\u59BE\u5A3C\u5BB5\u5C06\u5C0F\u5C11\u5C1A\u5E84\u5E8A\u5EE0\u5F70\u627F\u6284\u62DB\u638C\u6377\u6607\u660C\u662D\u6676\u677E\u68A2\u6A1F\u6A35\u6CBC\u6D88\u6E09\u6E58\u713C\u7126\u7167\u75C7\u7701\u785D\u7901\u7965\u79F0\u7AE0\u7B11\u7CA7\u7D39\u8096\u83D6\u848B\u8549\u885D\u88F3\u8A1F\u8A3C\u8A54\u8A73\u8C61\u8CDE\u91A4\u9266\u937E\u9418\u969C\u9798\u4E0A\u4E08\u4E1E\u4E57\u5197\u5270\u57CE\u5834\u58CC\u5B22\u5E38\u60C5\u64FE\u6761\u6756\u6D44\u72B6\u7573\u7A63\u84B8\u8B72\u91B8\u9320\u5631\u57F4\u98FE"], + ["9040", "\u62ED\u690D\u6B96\u71ED\u7E54\u8077\u8272\u89E6\u98DF\u8755\u8FB1\u5C3B\u4F38\u4FE1\u4FB5\u5507\u5A20\u5BDD\u5BE9\u5FC3\u614E\u632F\u65B0\u664B\u68EE\u699B\u6D78\u6DF1\u7533\u75B9\u771F\u795E\u79E6\u7D33\u81E3\u82AF\u85AA\u89AA\u8A3A\u8EAB\u8F9B\u9032\u91DD\u9707\u4EBA\u4EC1\u5203\u5875\u58EC\u5C0B\u751A\u5C3D\u814E\u8A0A\u8FC5\u9663\u976D\u7B25\u8ACF\u9808\u9162\u56F3\u53A8"], + ["9080", "\u9017\u5439\u5782\u5E25\u63A8\u6C34\u708A\u7761\u7C8B\u7FE0\u8870\u9042\u9154\u9310\u9318\u968F\u745E\u9AC4\u5D07\u5D69\u6570\u67A2\u8DA8\u96DB\u636E\u6749\u6919\u83C5\u9817\u96C0\u88FE\u6F84\u647A\u5BF8\u4E16\u702C\u755D\u662F\u51C4\u5236\u52E2\u59D3\u5F81\u6027\u6210\u653F\u6574\u661F\u6674\u68F2\u6816\u6B63\u6E05\u7272\u751F\u76DB\u7CBE\u8056\u58F0\u88FD\u897F\u8AA0\u8A93\u8ACB\u901D\u9192\u9752\u9759\u6589\u7A0E\u8106\u96BB\u5E2D\u60DC\u621A\u65A5\u6614\u6790\u77F3\u7A4D\u7C4D\u7E3E\u810A\u8CAC\u8D64\u8DE1\u8E5F\u78A9\u5207\u62D9\u63A5\u6442\u6298\u8A2D\u7A83\u7BC0\u8AAC\u96EA\u7D76\u820C\u8749\u4ED9\u5148\u5343\u5360\u5BA3\u5C02\u5C16\u5DDD\u6226\u6247\u64B0\u6813\u6834\u6CC9\u6D45\u6D17\u67D3\u6F5C\u714E\u717D\u65CB\u7A7F\u7BAD\u7DDA"], + ["9140", "\u7E4A\u7FA8\u817A\u821B\u8239\u85A6\u8A6E\u8CCE\u8DF5\u9078\u9077\u92AD\u9291\u9583\u9BAE\u524D\u5584\u6F38\u7136\u5168\u7985\u7E55\u81B3\u7CCE\u564C\u5851\u5CA8\u63AA\u66FE\u66FD\u695A\u72D9\u758F\u758E\u790E\u7956\u79DF\u7C97\u7D20\u7D44\u8607\u8A34\u963B\u9061\u9F20\u50E7\u5275\u53CC\u53E2\u5009\u55AA\u58EE\u594F\u723D\u5B8B\u5C64\u531D\u60E3\u60F3\u635C\u6383\u633F\u63BB"], + ["9180", "\u64CD\u65E9\u66F9\u5DE3\u69CD\u69FD\u6F15\u71E5\u4E89\u75E9\u76F8\u7A93\u7CDF\u7DCF\u7D9C\u8061\u8349\u8358\u846C\u84BC\u85FB\u88C5\u8D70\u9001\u906D\u9397\u971C\u9A12\u50CF\u5897\u618E\u81D3\u8535\u8D08\u9020\u4FC3\u5074\u5247\u5373\u606F\u6349\u675F\u6E2C\u8DB3\u901F\u4FD7\u5C5E\u8CCA\u65CF\u7D9A\u5352\u8896\u5176\u63C3\u5B58\u5B6B\u5C0A\u640D\u6751\u905C\u4ED6\u591A\u592A\u6C70\u8A51\u553E\u5815\u59A5\u60F0\u6253\u67C1\u8235\u6955\u9640\u99C4\u9A28\u4F53\u5806\u5BFE\u8010\u5CB1\u5E2F\u5F85\u6020\u614B\u6234\u66FF\u6CF0\u6EDE\u80CE\u817F\u82D4\u888B\u8CB8\u9000\u902E\u968A\u9EDB\u9BDB\u4EE3\u53F0\u5927\u7B2C\u918D\u984C\u9DF9\u6EDD\u7027\u5353\u5544\u5B85\u6258\u629E\u62D3\u6CA2\u6FEF\u7422\u8A17\u9438\u6FC1\u8AFE\u8338\u51E7\u86F8\u53EA"], + ["9240", "\u53E9\u4F46\u9054\u8FB0\u596A\u8131\u5DFD\u7AEA\u8FBF\u68DA\u8C37\u72F8\u9C48\u6A3D\u8AB0\u4E39\u5358\u5606\u5766\u62C5\u63A2\u65E6\u6B4E\u6DE1\u6E5B\u70AD\u77ED\u7AEF\u7BAA\u7DBB\u803D\u80C6\u86CB\u8A95\u935B\u56E3\u58C7\u5F3E\u65AD\u6696\u6A80\u6BB5\u7537\u8AC7\u5024\u77E5\u5730\u5F1B\u6065\u667A\u6C60\u75F4\u7A1A\u7F6E\u81F4\u8718\u9045\u99B3\u7BC9\u755C\u7AF9\u7B51\u84C4"], + ["9280", "\u9010\u79E9\u7A92\u8336\u5AE1\u7740\u4E2D\u4EF2\u5B99\u5FE0\u62BD\u663C\u67F1\u6CE8\u866B\u8877\u8A3B\u914E\u92F3\u99D0\u6A17\u7026\u732A\u82E7\u8457\u8CAF\u4E01\u5146\u51CB\u558B\u5BF5\u5E16\u5E33\u5E81\u5F14\u5F35\u5F6B\u5FB4\u61F2\u6311\u66A2\u671D\u6F6E\u7252\u753A\u773A\u8074\u8139\u8178\u8776\u8ABF\u8ADC\u8D85\u8DF3\u929A\u9577\u9802\u9CE5\u52C5\u6357\u76F4\u6715\u6C88\u73CD\u8CC3\u93AE\u9673\u6D25\u589C\u690E\u69CC\u8FFD\u939A\u75DB\u901A\u585A\u6802\u63B4\u69FB\u4F43\u6F2C\u67D8\u8FBB\u8526\u7DB4\u9354\u693F\u6F70\u576A\u58F7\u5B2C\u7D2C\u722A\u540A\u91E3\u9DB4\u4EAD\u4F4E\u505C\u5075\u5243\u8C9E\u5448\u5824\u5B9A\u5E1D\u5E95\u5EAD\u5EF7\u5F1F\u608C\u62B5\u633A\u63D0\u68AF\u6C40\u7887\u798E\u7A0B\u7DE0\u8247\u8A02\u8AE6\u8E44\u9013"], + ["9340", "\u90B8\u912D\u91D8\u9F0E\u6CE5\u6458\u64E2\u6575\u6EF4\u7684\u7B1B\u9069\u93D1\u6EBA\u54F2\u5FB9\u64A4\u8F4D\u8FED\u9244\u5178\u586B\u5929\u5C55\u5E97\u6DFB\u7E8F\u751C\u8CBC\u8EE2\u985B\u70B9\u4F1D\u6BBF\u6FB1\u7530\u96FB\u514E\u5410\u5835\u5857\u59AC\u5C60\u5F92\u6597\u675C\u6E21\u767B\u83DF\u8CED\u9014\u90FD\u934D\u7825\u783A\u52AA\u5EA6\u571F\u5974\u6012\u5012\u515A\u51AC"], + ["9380", "\u51CD\u5200\u5510\u5854\u5858\u5957\u5B95\u5CF6\u5D8B\u60BC\u6295\u642D\u6771\u6843\u68BC\u68DF\u76D7\u6DD8\u6E6F\u6D9B\u706F\u71C8\u5F53\u75D8\u7977\u7B49\u7B54\u7B52\u7CD6\u7D71\u5230\u8463\u8569\u85E4\u8A0E\u8B04\u8C46\u8E0F\u9003\u900F\u9419\u9676\u982D\u9A30\u95D8\u50CD\u52D5\u540C\u5802\u5C0E\u61A7\u649E\u6D1E\u77B3\u7AE5\u80F4\u8404\u9053\u9285\u5CE0\u9D07\u533F\u5F97\u5FB3\u6D9C\u7279\u7763\u79BF\u7BE4\u6BD2\u72EC\u8AAD\u6803\u6A61\u51F8\u7A81\u6934\u5C4A\u9CF6\u82EB\u5BC5\u9149\u701E\u5678\u5C6F\u60C7\u6566\u6C8C\u8C5A\u9041\u9813\u5451\u66C7\u920D\u5948\u90A3\u5185\u4E4D\u51EA\u8599\u8B0E\u7058\u637A\u934B\u6962\u99B4\u7E04\u7577\u5357\u6960\u8EDF\u96E3\u6C5D\u4E8C\u5C3C\u5F10\u8FE9\u5302\u8CD1\u8089\u8679\u5EFF\u65E5\u4E73\u5165"], + ["9440", "\u5982\u5C3F\u97EE\u4EFB\u598A\u5FCD\u8A8D\u6FE1\u79B0\u7962\u5BE7\u8471\u732B\u71B1\u5E74\u5FF5\u637B\u649A\u71C3\u7C98\u4E43\u5EFC\u4E4B\u57DC\u56A2\u60A9\u6FC3\u7D0D\u80FD\u8133\u81BF\u8FB2\u8997\u86A4\u5DF4\u628A\u64AD\u8987\u6777\u6CE2\u6D3E\u7436\u7834\u5A46\u7F75\u82AD\u99AC\u4FF3\u5EC3\u62DD\u6392\u6557\u676F\u76C3\u724C\u80CC\u80BA\u8F29\u914D\u500D\u57F9\u5A92\u6885"], + ["9480", "\u6973\u7164\u72FD\u8CB7\u58F2\u8CE0\u966A\u9019\u877F\u79E4\u77E7\u8429\u4F2F\u5265\u535A\u62CD\u67CF\u6CCA\u767D\u7B94\u7C95\u8236\u8584\u8FEB\u66DD\u6F20\u7206\u7E1B\u83AB\u99C1\u9EA6\u51FD\u7BB1\u7872\u7BB8\u8087\u7B48\u6AE8\u5E61\u808C\u7551\u7560\u516B\u9262\u6E8C\u767A\u9197\u9AEA\u4F10\u7F70\u629C\u7B4F\u95A5\u9CE9\u567A\u5859\u86E4\u96BC\u4F34\u5224\u534A\u53CD\u53DB\u5E06\u642C\u6591\u677F\u6C3E\u6C4E\u7248\u72AF\u73ED\u7554\u7E41\u822C\u85E9\u8CA9\u7BC4\u91C6\u7169\u9812\u98EF\u633D\u6669\u756A\u76E4\u78D0\u8543\u86EE\u532A\u5351\u5426\u5983\u5E87\u5F7C\u60B2\u6249\u6279\u62AB\u6590\u6BD4\u6CCC\u75B2\u76AE\u7891\u79D8\u7DCB\u7F77\u80A5\u88AB\u8AB9\u8CBB\u907F\u975E\u98DB\u6A0B\u7C38\u5099\u5C3E\u5FAE\u6787\u6BD8\u7435\u7709\u7F8E"], + ["9540", "\u9F3B\u67CA\u7A17\u5339\u758B\u9AED\u5F66\u819D\u83F1\u8098\u5F3C\u5FC5\u7562\u7B46\u903C\u6867\u59EB\u5A9B\u7D10\u767E\u8B2C\u4FF5\u5F6A\u6A19\u6C37\u6F02\u74E2\u7968\u8868\u8A55\u8C79\u5EDF\u63CF\u75C5\u79D2\u82D7\u9328\u92F2\u849C\u86ED\u9C2D\u54C1\u5F6C\u658C\u6D5C\u7015\u8CA7\u8CD3\u983B\u654F\u74F6\u4E0D\u4ED8\u57E0\u592B\u5A66\u5BCC\u51A8\u5E03\u5E9C\u6016\u6276\u6577"], + ["9580", "\u65A7\u666E\u6D6E\u7236\u7B26\u8150\u819A\u8299\u8B5C\u8CA0\u8CE6\u8D74\u961C\u9644\u4FAE\u64AB\u6B66\u821E\u8461\u856A\u90E8\u5C01\u6953\u98A8\u847A\u8557\u4F0F\u526F\u5FA9\u5E45\u670D\u798F\u8179\u8907\u8986\u6DF5\u5F17\u6255\u6CB8\u4ECF\u7269\u9B92\u5206\u543B\u5674\u58B3\u61A4\u626E\u711A\u596E\u7C89\u7CDE\u7D1B\u96F0\u6587\u805E\u4E19\u4F75\u5175\u5840\u5E63\u5E73\u5F0A\u67C4\u4E26\u853D\u9589\u965B\u7C73\u9801\u50FB\u58C1\u7656\u78A7\u5225\u77A5\u8511\u7B86\u504F\u5909\u7247\u7BC7\u7DE8\u8FBA\u8FD4\u904D\u4FBF\u52C9\u5A29\u5F01\u97AD\u4FDD\u8217\u92EA\u5703\u6355\u6B69\u752B\u88DC\u8F14\u7A42\u52DF\u5893\u6155\u620A\u66AE\u6BCD\u7C3F\u83E9\u5023\u4FF8\u5305\u5446\u5831\u5949\u5B9D\u5CF0\u5CEF\u5D29\u5E96\u62B1\u6367\u653E\u65B9\u670B"], + ["9640", "\u6CD5\u6CE1\u70F9\u7832\u7E2B\u80DE\u82B3\u840C\u84EC\u8702\u8912\u8A2A\u8C4A\u90A6\u92D2\u98FD\u9CF3\u9D6C\u4E4F\u4EA1\u508D\u5256\u574A\u59A8\u5E3D\u5FD8\u5FD9\u623F\u66B4\u671B\u67D0\u68D2\u5192\u7D21\u80AA\u81A8\u8B00\u8C8C\u8CBF\u927E\u9632\u5420\u982C\u5317\u50D5\u535C\u58A8\u64B2\u6734\u7267\u7766\u7A46\u91E6\u52C3\u6CA1\u6B86\u5800\u5E4C\u5954\u672C\u7FFB\u51E1\u76C6"], + ["9680", "\u6469\u78E8\u9B54\u9EBB\u57CB\u59B9\u6627\u679A\u6BCE\u54E9\u69D9\u5E55\u819C\u6795\u9BAA\u67FE\u9C52\u685D\u4EA6\u4FE3\u53C8\u62B9\u672B\u6CAB\u8FC4\u4FAD\u7E6D\u9EBF\u4E07\u6162\u6E80\u6F2B\u8513\u5473\u672A\u9B45\u5DF3\u7B95\u5CAC\u5BC6\u871C\u6E4A\u84D1\u7A14\u8108\u5999\u7C8D\u6C11\u7720\u52D9\u5922\u7121\u725F\u77DB\u9727\u9D61\u690B\u5A7F\u5A18\u51A5\u540D\u547D\u660E\u76DF\u8FF7\u9298\u9CF4\u59EA\u725D\u6EC5\u514D\u68C9\u7DBF\u7DEC\u9762\u9EBA\u6478\u6A21\u8302\u5984\u5B5F\u6BDB\u731B\u76F2\u7DB2\u8017\u8499\u5132\u6728\u9ED9\u76EE\u6762\u52FF\u9905\u5C24\u623B\u7C7E\u8CB0\u554F\u60B6\u7D0B\u9580\u5301\u4E5F\u51B6\u591C\u723A\u8036\u91CE\u5F25\u77E2\u5384\u5F79\u7D04\u85AC\u8A33\u8E8D\u9756\u67F3\u85AE\u9453\u6109\u6108\u6CB9\u7652"], + ["9740", "\u8AED\u8F38\u552F\u4F51\u512A\u52C7\u53CB\u5BA5\u5E7D\u60A0\u6182\u63D6\u6709\u67DA\u6E67\u6D8C\u7336\u7337\u7531\u7950\u88D5\u8A98\u904A\u9091\u90F5\u96C4\u878D\u5915\u4E88\u4F59\u4E0E\u8A89\u8F3F\u9810\u50AD\u5E7C\u5996\u5BB9\u5EB8\u63DA\u63FA\u64C1\u66DC\u694A\u69D8\u6D0B\u6EB6\u7194\u7528\u7AAF\u7F8A\u8000\u8449\u84C9\u8981\u8B21\u8E0A\u9065\u967D\u990A\u617E\u6291\u6B32"], + ["9780", "\u6C83\u6D74\u7FCC\u7FFC\u6DC0\u7F85\u87BA\u88F8\u6765\u83B1\u983C\u96F7\u6D1B\u7D61\u843D\u916A\u4E71\u5375\u5D50\u6B04\u6FEB\u85CD\u862D\u89A7\u5229\u540F\u5C65\u674E\u68A8\u7406\u7483\u75E2\u88CF\u88E1\u91CC\u96E2\u9678\u5F8B\u7387\u7ACB\u844E\u63A0\u7565\u5289\u6D41\u6E9C\u7409\u7559\u786B\u7C92\u9686\u7ADC\u9F8D\u4FB6\u616E\u65C5\u865C\u4E86\u4EAE\u50DA\u4E21\u51CC\u5BEE\u6599\u6881\u6DBC\u731F\u7642\u77AD\u7A1C\u7CE7\u826F\u8AD2\u907C\u91CF\u9675\u9818\u529B\u7DD1\u502B\u5398\u6797\u6DCB\u71D0\u7433\u81E8\u8F2A\u96A3\u9C57\u9E9F\u7460\u5841\u6D99\u7D2F\u985E\u4EE4\u4F36\u4F8B\u51B7\u52B1\u5DBA\u601C\u73B2\u793C\u82D3\u9234\u96B7\u96F6\u970A\u9E97\u9F62\u66A6\u6B74\u5217\u52A3\u70C8\u88C2\u5EC9\u604B\u6190\u6F23\u7149\u7C3E\u7DF4\u806F"], + ["9840", "\u84EE\u9023\u932C\u5442\u9B6F\u6AD3\u7089\u8CC2\u8DEF\u9732\u52B4\u5A41\u5ECA\u5F04\u6717\u697C\u6994\u6D6A\u6F0F\u7262\u72FC\u7BED\u8001\u807E\u874B\u90CE\u516D\u9E93\u7984\u808B\u9332\u8AD6\u502D\u548C\u8A71\u6B6A\u8CC4\u8107\u60D1\u67A0\u9DF2\u4E99\u4E98\u9C10\u8A6B\u85C1\u8568\u6900\u6E7E\u7897\u8155"], + ["989f", "\u5F0C\u4E10\u4E15\u4E2A\u4E31\u4E36\u4E3C\u4E3F\u4E42\u4E56\u4E58\u4E82\u4E85\u8C6B\u4E8A\u8212\u5F0D\u4E8E\u4E9E\u4E9F\u4EA0\u4EA2\u4EB0\u4EB3\u4EB6\u4ECE\u4ECD\u4EC4\u4EC6\u4EC2\u4ED7\u4EDE\u4EED\u4EDF\u4EF7\u4F09\u4F5A\u4F30\u4F5B\u4F5D\u4F57\u4F47\u4F76\u4F88\u4F8F\u4F98\u4F7B\u4F69\u4F70\u4F91\u4F6F\u4F86\u4F96\u5118\u4FD4\u4FDF\u4FCE\u4FD8\u4FDB\u4FD1\u4FDA\u4FD0\u4FE4\u4FE5\u501A\u5028\u5014\u502A\u5025\u5005\u4F1C\u4FF6\u5021\u5029\u502C\u4FFE\u4FEF\u5011\u5006\u5043\u5047\u6703\u5055\u5050\u5048\u505A\u5056\u506C\u5078\u5080\u509A\u5085\u50B4\u50B2"], + ["9940", "\u50C9\u50CA\u50B3\u50C2\u50D6\u50DE\u50E5\u50ED\u50E3\u50EE\u50F9\u50F5\u5109\u5101\u5102\u5116\u5115\u5114\u511A\u5121\u513A\u5137\u513C\u513B\u513F\u5140\u5152\u514C\u5154\u5162\u7AF8\u5169\u516A\u516E\u5180\u5182\u56D8\u518C\u5189\u518F\u5191\u5193\u5195\u5196\u51A4\u51A6\u51A2\u51A9\u51AA\u51AB\u51B3\u51B1\u51B2\u51B0\u51B5\u51BD\u51C5\u51C9\u51DB\u51E0\u8655\u51E9\u51ED"], + ["9980", "\u51F0\u51F5\u51FE\u5204\u520B\u5214\u520E\u5227\u522A\u522E\u5233\u5239\u524F\u5244\u524B\u524C\u525E\u5254\u526A\u5274\u5269\u5273\u527F\u527D\u528D\u5294\u5292\u5271\u5288\u5291\u8FA8\u8FA7\u52AC\u52AD\u52BC\u52B5\u52C1\u52CD\u52D7\u52DE\u52E3\u52E6\u98ED\u52E0\u52F3\u52F5\u52F8\u52F9\u5306\u5308\u7538\u530D\u5310\u530F\u5315\u531A\u5323\u532F\u5331\u5333\u5338\u5340\u5346\u5345\u4E17\u5349\u534D\u51D6\u535E\u5369\u536E\u5918\u537B\u5377\u5382\u5396\u53A0\u53A6\u53A5\u53AE\u53B0\u53B6\u53C3\u7C12\u96D9\u53DF\u66FC\u71EE\u53EE\u53E8\u53ED\u53FA\u5401\u543D\u5440\u542C\u542D\u543C\u542E\u5436\u5429\u541D\u544E\u548F\u5475\u548E\u545F\u5471\u5477\u5470\u5492\u547B\u5480\u5476\u5484\u5490\u5486\u54C7\u54A2\u54B8\u54A5\u54AC\u54C4\u54C8\u54A8"], + ["9a40", "\u54AB\u54C2\u54A4\u54BE\u54BC\u54D8\u54E5\u54E6\u550F\u5514\u54FD\u54EE\u54ED\u54FA\u54E2\u5539\u5540\u5563\u554C\u552E\u555C\u5545\u5556\u5557\u5538\u5533\u555D\u5599\u5580\u54AF\u558A\u559F\u557B\u557E\u5598\u559E\u55AE\u557C\u5583\u55A9\u5587\u55A8\u55DA\u55C5\u55DF\u55C4\u55DC\u55E4\u55D4\u5614\u55F7\u5616\u55FE\u55FD\u561B\u55F9\u564E\u5650\u71DF\u5634\u5636\u5632\u5638"], + ["9a80", "\u566B\u5664\u562F\u566C\u566A\u5686\u5680\u568A\u56A0\u5694\u568F\u56A5\u56AE\u56B6\u56B4\u56C2\u56BC\u56C1\u56C3\u56C0\u56C8\u56CE\u56D1\u56D3\u56D7\u56EE\u56F9\u5700\u56FF\u5704\u5709\u5708\u570B\u570D\u5713\u5718\u5716\u55C7\u571C\u5726\u5737\u5738\u574E\u573B\u5740\u574F\u5769\u57C0\u5788\u5761\u577F\u5789\u5793\u57A0\u57B3\u57A4\u57AA\u57B0\u57C3\u57C6\u57D4\u57D2\u57D3\u580A\u57D6\u57E3\u580B\u5819\u581D\u5872\u5821\u5862\u584B\u5870\u6BC0\u5852\u583D\u5879\u5885\u58B9\u589F\u58AB\u58BA\u58DE\u58BB\u58B8\u58AE\u58C5\u58D3\u58D1\u58D7\u58D9\u58D8\u58E5\u58DC\u58E4\u58DF\u58EF\u58FA\u58F9\u58FB\u58FC\u58FD\u5902\u590A\u5910\u591B\u68A6\u5925\u592C\u592D\u5932\u5938\u593E\u7AD2\u5955\u5950\u594E\u595A\u5958\u5962\u5960\u5967\u596C\u5969"], + ["9b40", "\u5978\u5981\u599D\u4F5E\u4FAB\u59A3\u59B2\u59C6\u59E8\u59DC\u598D\u59D9\u59DA\u5A25\u5A1F\u5A11\u5A1C\u5A09\u5A1A\u5A40\u5A6C\u5A49\u5A35\u5A36\u5A62\u5A6A\u5A9A\u5ABC\u5ABE\u5ACB\u5AC2\u5ABD\u5AE3\u5AD7\u5AE6\u5AE9\u5AD6\u5AFA\u5AFB\u5B0C\u5B0B\u5B16\u5B32\u5AD0\u5B2A\u5B36\u5B3E\u5B43\u5B45\u5B40\u5B51\u5B55\u5B5A\u5B5B\u5B65\u5B69\u5B70\u5B73\u5B75\u5B78\u6588\u5B7A\u5B80"], + ["9b80", "\u5B83\u5BA6\u5BB8\u5BC3\u5BC7\u5BC9\u5BD4\u5BD0\u5BE4\u5BE6\u5BE2\u5BDE\u5BE5\u5BEB\u5BF0\u5BF6\u5BF3\u5C05\u5C07\u5C08\u5C0D\u5C13\u5C20\u5C22\u5C28\u5C38\u5C39\u5C41\u5C46\u5C4E\u5C53\u5C50\u5C4F\u5B71\u5C6C\u5C6E\u4E62\u5C76\u5C79\u5C8C\u5C91\u5C94\u599B\u5CAB\u5CBB\u5CB6\u5CBC\u5CB7\u5CC5\u5CBE\u5CC7\u5CD9\u5CE9\u5CFD\u5CFA\u5CED\u5D8C\u5CEA\u5D0B\u5D15\u5D17\u5D5C\u5D1F\u5D1B\u5D11\u5D14\u5D22\u5D1A\u5D19\u5D18\u5D4C\u5D52\u5D4E\u5D4B\u5D6C\u5D73\u5D76\u5D87\u5D84\u5D82\u5DA2\u5D9D\u5DAC\u5DAE\u5DBD\u5D90\u5DB7\u5DBC\u5DC9\u5DCD\u5DD3\u5DD2\u5DD6\u5DDB\u5DEB\u5DF2\u5DF5\u5E0B\u5E1A\u5E19\u5E11\u5E1B\u5E36\u5E37\u5E44\u5E43\u5E40\u5E4E\u5E57\u5E54\u5E5F\u5E62\u5E64\u5E47\u5E75\u5E76\u5E7A\u9EBC\u5E7F\u5EA0\u5EC1\u5EC2\u5EC8\u5ED0\u5ECF"], + ["9c40", "\u5ED6\u5EE3\u5EDD\u5EDA\u5EDB\u5EE2\u5EE1\u5EE8\u5EE9\u5EEC\u5EF1\u5EF3\u5EF0\u5EF4\u5EF8\u5EFE\u5F03\u5F09\u5F5D\u5F5C\u5F0B\u5F11\u5F16\u5F29\u5F2D\u5F38\u5F41\u5F48\u5F4C\u5F4E\u5F2F\u5F51\u5F56\u5F57\u5F59\u5F61\u5F6D\u5F73\u5F77\u5F83\u5F82\u5F7F\u5F8A\u5F88\u5F91\u5F87\u5F9E\u5F99\u5F98\u5FA0\u5FA8\u5FAD\u5FBC\u5FD6\u5FFB\u5FE4\u5FF8\u5FF1\u5FDD\u60B3\u5FFF\u6021\u6060"], + ["9c80", "\u6019\u6010\u6029\u600E\u6031\u601B\u6015\u602B\u6026\u600F\u603A\u605A\u6041\u606A\u6077\u605F\u604A\u6046\u604D\u6063\u6043\u6064\u6042\u606C\u606B\u6059\u6081\u608D\u60E7\u6083\u609A\u6084\u609B\u6096\u6097\u6092\u60A7\u608B\u60E1\u60B8\u60E0\u60D3\u60B4\u5FF0\u60BD\u60C6\u60B5\u60D8\u614D\u6115\u6106\u60F6\u60F7\u6100\u60F4\u60FA\u6103\u6121\u60FB\u60F1\u610D\u610E\u6147\u613E\u6128\u6127\u614A\u613F\u613C\u612C\u6134\u613D\u6142\u6144\u6173\u6177\u6158\u6159\u615A\u616B\u6174\u616F\u6165\u6171\u615F\u615D\u6153\u6175\u6199\u6196\u6187\u61AC\u6194\u619A\u618A\u6191\u61AB\u61AE\u61CC\u61CA\u61C9\u61F7\u61C8\u61C3\u61C6\u61BA\u61CB\u7F79\u61CD\u61E6\u61E3\u61F6\u61FA\u61F4\u61FF\u61FD\u61FC\u61FE\u6200\u6208\u6209\u620D\u620C\u6214\u621B"], + ["9d40", "\u621E\u6221\u622A\u622E\u6230\u6232\u6233\u6241\u624E\u625E\u6263\u625B\u6260\u6268\u627C\u6282\u6289\u627E\u6292\u6293\u6296\u62D4\u6283\u6294\u62D7\u62D1\u62BB\u62CF\u62FF\u62C6\u64D4\u62C8\u62DC\u62CC\u62CA\u62C2\u62C7\u629B\u62C9\u630C\u62EE\u62F1\u6327\u6302\u6308\u62EF\u62F5\u6350\u633E\u634D\u641C\u634F\u6396\u638E\u6380\u63AB\u6376\u63A3\u638F\u6389\u639F\u63B5\u636B"], + ["9d80", "\u6369\u63BE\u63E9\u63C0\u63C6\u63E3\u63C9\u63D2\u63F6\u63C4\u6416\u6434\u6406\u6413\u6426\u6436\u651D\u6417\u6428\u640F\u6467\u646F\u6476\u644E\u652A\u6495\u6493\u64A5\u64A9\u6488\u64BC\u64DA\u64D2\u64C5\u64C7\u64BB\u64D8\u64C2\u64F1\u64E7\u8209\u64E0\u64E1\u62AC\u64E3\u64EF\u652C\u64F6\u64F4\u64F2\u64FA\u6500\u64FD\u6518\u651C\u6505\u6524\u6523\u652B\u6534\u6535\u6537\u6536\u6538\u754B\u6548\u6556\u6555\u654D\u6558\u655E\u655D\u6572\u6578\u6582\u6583\u8B8A\u659B\u659F\u65AB\u65B7\u65C3\u65C6\u65C1\u65C4\u65CC\u65D2\u65DB\u65D9\u65E0\u65E1\u65F1\u6772\u660A\u6603\u65FB\u6773\u6635\u6636\u6634\u661C\u664F\u6644\u6649\u6641\u665E\u665D\u6664\u6667\u6668\u665F\u6662\u6670\u6683\u6688\u668E\u6689\u6684\u6698\u669D\u66C1\u66B9\u66C9\u66BE\u66BC"], + ["9e40", "\u66C4\u66B8\u66D6\u66DA\u66E0\u663F\u66E6\u66E9\u66F0\u66F5\u66F7\u670F\u6716\u671E\u6726\u6727\u9738\u672E\u673F\u6736\u6741\u6738\u6737\u6746\u675E\u6760\u6759\u6763\u6764\u6789\u6770\u67A9\u677C\u676A\u678C\u678B\u67A6\u67A1\u6785\u67B7\u67EF\u67B4\u67EC\u67B3\u67E9\u67B8\u67E4\u67DE\u67DD\u67E2\u67EE\u67B9\u67CE\u67C6\u67E7\u6A9C\u681E\u6846\u6829\u6840\u684D\u6832\u684E"], + ["9e80", "\u68B3\u682B\u6859\u6863\u6877\u687F\u689F\u688F\u68AD\u6894\u689D\u689B\u6883\u6AAE\u68B9\u6874\u68B5\u68A0\u68BA\u690F\u688D\u687E\u6901\u68CA\u6908\u68D8\u6922\u6926\u68E1\u690C\u68CD\u68D4\u68E7\u68D5\u6936\u6912\u6904\u68D7\u68E3\u6925\u68F9\u68E0\u68EF\u6928\u692A\u691A\u6923\u6921\u68C6\u6979\u6977\u695C\u6978\u696B\u6954\u697E\u696E\u6939\u6974\u693D\u6959\u6930\u6961\u695E\u695D\u6981\u696A\u69B2\u69AE\u69D0\u69BF\u69C1\u69D3\u69BE\u69CE\u5BE8\u69CA\u69DD\u69BB\u69C3\u69A7\u6A2E\u6991\u69A0\u699C\u6995\u69B4\u69DE\u69E8\u6A02\u6A1B\u69FF\u6B0A\u69F9\u69F2\u69E7\u6A05\u69B1\u6A1E\u69ED\u6A14\u69EB\u6A0A\u6A12\u6AC1\u6A23\u6A13\u6A44\u6A0C\u6A72\u6A36\u6A78\u6A47\u6A62\u6A59\u6A66\u6A48\u6A38\u6A22\u6A90\u6A8D\u6AA0\u6A84\u6AA2\u6AA3"], + ["9f40", "\u6A97\u8617\u6ABB\u6AC3\u6AC2\u6AB8\u6AB3\u6AAC\u6ADE\u6AD1\u6ADF\u6AAA\u6ADA\u6AEA\u6AFB\u6B05\u8616\u6AFA\u6B12\u6B16\u9B31\u6B1F\u6B38\u6B37\u76DC\u6B39\u98EE\u6B47\u6B43\u6B49\u6B50\u6B59\u6B54\u6B5B\u6B5F\u6B61\u6B78\u6B79\u6B7F\u6B80\u6B84\u6B83\u6B8D\u6B98\u6B95\u6B9E\u6BA4\u6BAA\u6BAB\u6BAF\u6BB2\u6BB1\u6BB3\u6BB7\u6BBC\u6BC6\u6BCB\u6BD3\u6BDF\u6BEC\u6BEB\u6BF3\u6BEF"], + ["9f80", "\u9EBE\u6C08\u6C13\u6C14\u6C1B\u6C24\u6C23\u6C5E\u6C55\u6C62\u6C6A\u6C82\u6C8D\u6C9A\u6C81\u6C9B\u6C7E\u6C68\u6C73\u6C92\u6C90\u6CC4\u6CF1\u6CD3\u6CBD\u6CD7\u6CC5\u6CDD\u6CAE\u6CB1\u6CBE\u6CBA\u6CDB\u6CEF\u6CD9\u6CEA\u6D1F\u884D\u6D36\u6D2B\u6D3D\u6D38\u6D19\u6D35\u6D33\u6D12\u6D0C\u6D63\u6D93\u6D64\u6D5A\u6D79\u6D59\u6D8E\u6D95\u6FE4\u6D85\u6DF9\u6E15\u6E0A\u6DB5\u6DC7\u6DE6\u6DB8\u6DC6\u6DEC\u6DDE\u6DCC\u6DE8\u6DD2\u6DC5\u6DFA\u6DD9\u6DE4\u6DD5\u6DEA\u6DEE\u6E2D\u6E6E\u6E2E\u6E19\u6E72\u6E5F\u6E3E\u6E23\u6E6B\u6E2B\u6E76\u6E4D\u6E1F\u6E43\u6E3A\u6E4E\u6E24\u6EFF\u6E1D\u6E38\u6E82\u6EAA\u6E98\u6EC9\u6EB7\u6ED3\u6EBD\u6EAF\u6EC4\u6EB2\u6ED4\u6ED5\u6E8F\u6EA5\u6EC2\u6E9F\u6F41\u6F11\u704C\u6EEC\u6EF8\u6EFE\u6F3F\u6EF2\u6F31\u6EEF\u6F32\u6ECC"], + ["e040", "\u6F3E\u6F13\u6EF7\u6F86\u6F7A\u6F78\u6F81\u6F80\u6F6F\u6F5B\u6FF3\u6F6D\u6F82\u6F7C\u6F58\u6F8E\u6F91\u6FC2\u6F66\u6FB3\u6FA3\u6FA1\u6FA4\u6FB9\u6FC6\u6FAA\u6FDF\u6FD5\u6FEC\u6FD4\u6FD8\u6FF1\u6FEE\u6FDB\u7009\u700B\u6FFA\u7011\u7001\u700F\u6FFE\u701B\u701A\u6F74\u701D\u7018\u701F\u7030\u703E\u7032\u7051\u7063\u7099\u7092\u70AF\u70F1\u70AC\u70B8\u70B3\u70AE\u70DF\u70CB\u70DD"], + ["e080", "\u70D9\u7109\u70FD\u711C\u7119\u7165\u7155\u7188\u7166\u7162\u714C\u7156\u716C\u718F\u71FB\u7184\u7195\u71A8\u71AC\u71D7\u71B9\u71BE\u71D2\u71C9\u71D4\u71CE\u71E0\u71EC\u71E7\u71F5\u71FC\u71F9\u71FF\u720D\u7210\u721B\u7228\u722D\u722C\u7230\u7232\u723B\u723C\u723F\u7240\u7246\u724B\u7258\u7274\u727E\u7282\u7281\u7287\u7292\u7296\u72A2\u72A7\u72B9\u72B2\u72C3\u72C6\u72C4\u72CE\u72D2\u72E2\u72E0\u72E1\u72F9\u72F7\u500F\u7317\u730A\u731C\u7316\u731D\u7334\u732F\u7329\u7325\u733E\u734E\u734F\u9ED8\u7357\u736A\u7368\u7370\u7378\u7375\u737B\u737A\u73C8\u73B3\u73CE\u73BB\u73C0\u73E5\u73EE\u73DE\u74A2\u7405\u746F\u7425\u73F8\u7432\u743A\u7455\u743F\u745F\u7459\u7441\u745C\u7469\u7470\u7463\u746A\u7476\u747E\u748B\u749E\u74A7\u74CA\u74CF\u74D4\u73F1"], + ["e140", "\u74E0\u74E3\u74E7\u74E9\u74EE\u74F2\u74F0\u74F1\u74F8\u74F7\u7504\u7503\u7505\u750C\u750E\u750D\u7515\u7513\u751E\u7526\u752C\u753C\u7544\u754D\u754A\u7549\u755B\u7546\u755A\u7569\u7564\u7567\u756B\u756D\u7578\u7576\u7586\u7587\u7574\u758A\u7589\u7582\u7594\u759A\u759D\u75A5\u75A3\u75C2\u75B3\u75C3\u75B5\u75BD\u75B8\u75BC\u75B1\u75CD\u75CA\u75D2\u75D9\u75E3\u75DE\u75FE\u75FF"], + ["e180", "\u75FC\u7601\u75F0\u75FA\u75F2\u75F3\u760B\u760D\u7609\u761F\u7627\u7620\u7621\u7622\u7624\u7634\u7630\u763B\u7647\u7648\u7646\u765C\u7658\u7661\u7662\u7668\u7669\u766A\u7667\u766C\u7670\u7672\u7676\u7678\u767C\u7680\u7683\u7688\u768B\u768E\u7696\u7693\u7699\u769A\u76B0\u76B4\u76B8\u76B9\u76BA\u76C2\u76CD\u76D6\u76D2\u76DE\u76E1\u76E5\u76E7\u76EA\u862F\u76FB\u7708\u7707\u7704\u7729\u7724\u771E\u7725\u7726\u771B\u7737\u7738\u7747\u775A\u7768\u776B\u775B\u7765\u777F\u777E\u7779\u778E\u778B\u7791\u77A0\u779E\u77B0\u77B6\u77B9\u77BF\u77BC\u77BD\u77BB\u77C7\u77CD\u77D7\u77DA\u77DC\u77E3\u77EE\u77FC\u780C\u7812\u7926\u7820\u792A\u7845\u788E\u7874\u7886\u787C\u789A\u788C\u78A3\u78B5\u78AA\u78AF\u78D1\u78C6\u78CB\u78D4\u78BE\u78BC\u78C5\u78CA\u78EC"], + ["e240", "\u78E7\u78DA\u78FD\u78F4\u7907\u7912\u7911\u7919\u792C\u792B\u7940\u7960\u7957\u795F\u795A\u7955\u7953\u797A\u797F\u798A\u799D\u79A7\u9F4B\u79AA\u79AE\u79B3\u79B9\u79BA\u79C9\u79D5\u79E7\u79EC\u79E1\u79E3\u7A08\u7A0D\u7A18\u7A19\u7A20\u7A1F\u7980\u7A31\u7A3B\u7A3E\u7A37\u7A43\u7A57\u7A49\u7A61\u7A62\u7A69\u9F9D\u7A70\u7A79\u7A7D\u7A88\u7A97\u7A95\u7A98\u7A96\u7AA9\u7AC8\u7AB0"], + ["e280", "\u7AB6\u7AC5\u7AC4\u7ABF\u9083\u7AC7\u7ACA\u7ACD\u7ACF\u7AD5\u7AD3\u7AD9\u7ADA\u7ADD\u7AE1\u7AE2\u7AE6\u7AED\u7AF0\u7B02\u7B0F\u7B0A\u7B06\u7B33\u7B18\u7B19\u7B1E\u7B35\u7B28\u7B36\u7B50\u7B7A\u7B04\u7B4D\u7B0B\u7B4C\u7B45\u7B75\u7B65\u7B74\u7B67\u7B70\u7B71\u7B6C\u7B6E\u7B9D\u7B98\u7B9F\u7B8D\u7B9C\u7B9A\u7B8B\u7B92\u7B8F\u7B5D\u7B99\u7BCB\u7BC1\u7BCC\u7BCF\u7BB4\u7BC6\u7BDD\u7BE9\u7C11\u7C14\u7BE6\u7BE5\u7C60\u7C00\u7C07\u7C13\u7BF3\u7BF7\u7C17\u7C0D\u7BF6\u7C23\u7C27\u7C2A\u7C1F\u7C37\u7C2B\u7C3D\u7C4C\u7C43\u7C54\u7C4F\u7C40\u7C50\u7C58\u7C5F\u7C64\u7C56\u7C65\u7C6C\u7C75\u7C83\u7C90\u7CA4\u7CAD\u7CA2\u7CAB\u7CA1\u7CA8\u7CB3\u7CB2\u7CB1\u7CAE\u7CB9\u7CBD\u7CC0\u7CC5\u7CC2\u7CD8\u7CD2\u7CDC\u7CE2\u9B3B\u7CEF\u7CF2\u7CF4\u7CF6\u7CFA\u7D06"], + ["e340", "\u7D02\u7D1C\u7D15\u7D0A\u7D45\u7D4B\u7D2E\u7D32\u7D3F\u7D35\u7D46\u7D73\u7D56\u7D4E\u7D72\u7D68\u7D6E\u7D4F\u7D63\u7D93\u7D89\u7D5B\u7D8F\u7D7D\u7D9B\u7DBA\u7DAE\u7DA3\u7DB5\u7DC7\u7DBD\u7DAB\u7E3D\u7DA2\u7DAF\u7DDC\u7DB8\u7D9F\u7DB0\u7DD8\u7DDD\u7DE4\u7DDE\u7DFB\u7DF2\u7DE1\u7E05\u7E0A\u7E23\u7E21\u7E12\u7E31\u7E1F\u7E09\u7E0B\u7E22\u7E46\u7E66\u7E3B\u7E35\u7E39\u7E43\u7E37"], + ["e380", "\u7E32\u7E3A\u7E67\u7E5D\u7E56\u7E5E\u7E59\u7E5A\u7E79\u7E6A\u7E69\u7E7C\u7E7B\u7E83\u7DD5\u7E7D\u8FAE\u7E7F\u7E88\u7E89\u7E8C\u7E92\u7E90\u7E93\u7E94\u7E96\u7E8E\u7E9B\u7E9C\u7F38\u7F3A\u7F45\u7F4C\u7F4D\u7F4E\u7F50\u7F51\u7F55\u7F54\u7F58\u7F5F\u7F60\u7F68\u7F69\u7F67\u7F78\u7F82\u7F86\u7F83\u7F88\u7F87\u7F8C\u7F94\u7F9E\u7F9D\u7F9A\u7FA3\u7FAF\u7FB2\u7FB9\u7FAE\u7FB6\u7FB8\u8B71\u7FC5\u7FC6\u7FCA\u7FD5\u7FD4\u7FE1\u7FE6\u7FE9\u7FF3\u7FF9\u98DC\u8006\u8004\u800B\u8012\u8018\u8019\u801C\u8021\u8028\u803F\u803B\u804A\u8046\u8052\u8058\u805A\u805F\u8062\u8068\u8073\u8072\u8070\u8076\u8079\u807D\u807F\u8084\u8086\u8085\u809B\u8093\u809A\u80AD\u5190\u80AC\u80DB\u80E5\u80D9\u80DD\u80C4\u80DA\u80D6\u8109\u80EF\u80F1\u811B\u8129\u8123\u812F\u814B"], + ["e440", "\u968B\u8146\u813E\u8153\u8151\u80FC\u8171\u816E\u8165\u8166\u8174\u8183\u8188\u818A\u8180\u8182\u81A0\u8195\u81A4\u81A3\u815F\u8193\u81A9\u81B0\u81B5\u81BE\u81B8\u81BD\u81C0\u81C2\u81BA\u81C9\u81CD\u81D1\u81D9\u81D8\u81C8\u81DA\u81DF\u81E0\u81E7\u81FA\u81FB\u81FE\u8201\u8202\u8205\u8207\u820A\u820D\u8210\u8216\u8229\u822B\u8238\u8233\u8240\u8259\u8258\u825D\u825A\u825F\u8264"], + ["e480", "\u8262\u8268\u826A\u826B\u822E\u8271\u8277\u8278\u827E\u828D\u8292\u82AB\u829F\u82BB\u82AC\u82E1\u82E3\u82DF\u82D2\u82F4\u82F3\u82FA\u8393\u8303\u82FB\u82F9\u82DE\u8306\u82DC\u8309\u82D9\u8335\u8334\u8316\u8332\u8331\u8340\u8339\u8350\u8345\u832F\u832B\u8317\u8318\u8385\u839A\u83AA\u839F\u83A2\u8396\u8323\u838E\u8387\u838A\u837C\u83B5\u8373\u8375\u83A0\u8389\u83A8\u83F4\u8413\u83EB\u83CE\u83FD\u8403\u83D8\u840B\u83C1\u83F7\u8407\u83E0\u83F2\u840D\u8422\u8420\u83BD\u8438\u8506\u83FB\u846D\u842A\u843C\u855A\u8484\u8477\u846B\u84AD\u846E\u8482\u8469\u8446\u842C\u846F\u8479\u8435\u84CA\u8462\u84B9\u84BF\u849F\u84D9\u84CD\u84BB\u84DA\u84D0\u84C1\u84C6\u84D6\u84A1\u8521\u84FF\u84F4\u8517\u8518\u852C\u851F\u8515\u8514\u84FC\u8540\u8563\u8558\u8548"], + ["e540", "\u8541\u8602\u854B\u8555\u8580\u85A4\u8588\u8591\u858A\u85A8\u856D\u8594\u859B\u85EA\u8587\u859C\u8577\u857E\u8590\u85C9\u85BA\u85CF\u85B9\u85D0\u85D5\u85DD\u85E5\u85DC\u85F9\u860A\u8613\u860B\u85FE\u85FA\u8606\u8622\u861A\u8630\u863F\u864D\u4E55\u8654\u865F\u8667\u8671\u8693\u86A3\u86A9\u86AA\u868B\u868C\u86B6\u86AF\u86C4\u86C6\u86B0\u86C9\u8823\u86AB\u86D4\u86DE\u86E9\u86EC"], + ["e580", "\u86DF\u86DB\u86EF\u8712\u8706\u8708\u8700\u8703\u86FB\u8711\u8709\u870D\u86F9\u870A\u8734\u873F\u8737\u873B\u8725\u8729\u871A\u8760\u875F\u8778\u874C\u874E\u8774\u8757\u8768\u876E\u8759\u8753\u8763\u876A\u8805\u87A2\u879F\u8782\u87AF\u87CB\u87BD\u87C0\u87D0\u96D6\u87AB\u87C4\u87B3\u87C7\u87C6\u87BB\u87EF\u87F2\u87E0\u880F\u880D\u87FE\u87F6\u87F7\u880E\u87D2\u8811\u8816\u8815\u8822\u8821\u8831\u8836\u8839\u8827\u883B\u8844\u8842\u8852\u8859\u885E\u8862\u886B\u8881\u887E\u889E\u8875\u887D\u88B5\u8872\u8882\u8897\u8892\u88AE\u8899\u88A2\u888D\u88A4\u88B0\u88BF\u88B1\u88C3\u88C4\u88D4\u88D8\u88D9\u88DD\u88F9\u8902\u88FC\u88F4\u88E8\u88F2\u8904\u890C\u890A\u8913\u8943\u891E\u8925\u892A\u892B\u8941\u8944\u893B\u8936\u8938\u894C\u891D\u8960\u895E"], + ["e640", "\u8966\u8964\u896D\u896A\u896F\u8974\u8977\u897E\u8983\u8988\u898A\u8993\u8998\u89A1\u89A9\u89A6\u89AC\u89AF\u89B2\u89BA\u89BD\u89BF\u89C0\u89DA\u89DC\u89DD\u89E7\u89F4\u89F8\u8A03\u8A16\u8A10\u8A0C\u8A1B\u8A1D\u8A25\u8A36\u8A41\u8A5B\u8A52\u8A46\u8A48\u8A7C\u8A6D\u8A6C\u8A62\u8A85\u8A82\u8A84\u8AA8\u8AA1\u8A91\u8AA5\u8AA6\u8A9A\u8AA3\u8AC4\u8ACD\u8AC2\u8ADA\u8AEB\u8AF3\u8AE7"], + ["e680", "\u8AE4\u8AF1\u8B14\u8AE0\u8AE2\u8AF7\u8ADE\u8ADB\u8B0C\u8B07\u8B1A\u8AE1\u8B16\u8B10\u8B17\u8B20\u8B33\u97AB\u8B26\u8B2B\u8B3E\u8B28\u8B41\u8B4C\u8B4F\u8B4E\u8B49\u8B56\u8B5B\u8B5A\u8B6B\u8B5F\u8B6C\u8B6F\u8B74\u8B7D\u8B80\u8B8C\u8B8E\u8B92\u8B93\u8B96\u8B99\u8B9A\u8C3A\u8C41\u8C3F\u8C48\u8C4C\u8C4E\u8C50\u8C55\u8C62\u8C6C\u8C78\u8C7A\u8C82\u8C89\u8C85\u8C8A\u8C8D\u8C8E\u8C94\u8C7C\u8C98\u621D\u8CAD\u8CAA\u8CBD\u8CB2\u8CB3\u8CAE\u8CB6\u8CC8\u8CC1\u8CE4\u8CE3\u8CDA\u8CFD\u8CFA\u8CFB\u8D04\u8D05\u8D0A\u8D07\u8D0F\u8D0D\u8D10\u9F4E\u8D13\u8CCD\u8D14\u8D16\u8D67\u8D6D\u8D71\u8D73\u8D81\u8D99\u8DC2\u8DBE\u8DBA\u8DCF\u8DDA\u8DD6\u8DCC\u8DDB\u8DCB\u8DEA\u8DEB\u8DDF\u8DE3\u8DFC\u8E08\u8E09\u8DFF\u8E1D\u8E1E\u8E10\u8E1F\u8E42\u8E35\u8E30\u8E34\u8E4A"], + ["e740", "\u8E47\u8E49\u8E4C\u8E50\u8E48\u8E59\u8E64\u8E60\u8E2A\u8E63\u8E55\u8E76\u8E72\u8E7C\u8E81\u8E87\u8E85\u8E84\u8E8B\u8E8A\u8E93\u8E91\u8E94\u8E99\u8EAA\u8EA1\u8EAC\u8EB0\u8EC6\u8EB1\u8EBE\u8EC5\u8EC8\u8ECB\u8EDB\u8EE3\u8EFC\u8EFB\u8EEB\u8EFE\u8F0A\u8F05\u8F15\u8F12\u8F19\u8F13\u8F1C\u8F1F\u8F1B\u8F0C\u8F26\u8F33\u8F3B\u8F39\u8F45\u8F42\u8F3E\u8F4C\u8F49\u8F46\u8F4E\u8F57\u8F5C"], + ["e780", "\u8F62\u8F63\u8F64\u8F9C\u8F9F\u8FA3\u8FAD\u8FAF\u8FB7\u8FDA\u8FE5\u8FE2\u8FEA\u8FEF\u9087\u8FF4\u9005\u8FF9\u8FFA\u9011\u9015\u9021\u900D\u901E\u9016\u900B\u9027\u9036\u9035\u9039\u8FF8\u904F\u9050\u9051\u9052\u900E\u9049\u903E\u9056\u9058\u905E\u9068\u906F\u9076\u96A8\u9072\u9082\u907D\u9081\u9080\u908A\u9089\u908F\u90A8\u90AF\u90B1\u90B5\u90E2\u90E4\u6248\u90DB\u9102\u9112\u9119\u9132\u9130\u914A\u9156\u9158\u9163\u9165\u9169\u9173\u9172\u918B\u9189\u9182\u91A2\u91AB\u91AF\u91AA\u91B5\u91B4\u91BA\u91C0\u91C1\u91C9\u91CB\u91D0\u91D6\u91DF\u91E1\u91DB\u91FC\u91F5\u91F6\u921E\u91FF\u9214\u922C\u9215\u9211\u925E\u9257\u9245\u9249\u9264\u9248\u9295\u923F\u924B\u9250\u929C\u9296\u9293\u929B\u925A\u92CF\u92B9\u92B7\u92E9\u930F\u92FA\u9344\u932E"], + ["e840", "\u9319\u9322\u931A\u9323\u933A\u9335\u933B\u935C\u9360\u937C\u936E\u9356\u93B0\u93AC\u93AD\u9394\u93B9\u93D6\u93D7\u93E8\u93E5\u93D8\u93C3\u93DD\u93D0\u93C8\u93E4\u941A\u9414\u9413\u9403\u9407\u9410\u9436\u942B\u9435\u9421\u943A\u9441\u9452\u9444\u945B\u9460\u9462\u945E\u946A\u9229\u9470\u9475\u9477\u947D\u945A\u947C\u947E\u9481\u947F\u9582\u9587\u958A\u9594\u9596\u9598\u9599"], + ["e880", "\u95A0\u95A8\u95A7\u95AD\u95BC\u95BB\u95B9\u95BE\u95CA\u6FF6\u95C3\u95CD\u95CC\u95D5\u95D4\u95D6\u95DC\u95E1\u95E5\u95E2\u9621\u9628\u962E\u962F\u9642\u964C\u964F\u964B\u9677\u965C\u965E\u965D\u965F\u9666\u9672\u966C\u968D\u9698\u9695\u9697\u96AA\u96A7\u96B1\u96B2\u96B0\u96B4\u96B6\u96B8\u96B9\u96CE\u96CB\u96C9\u96CD\u894D\u96DC\u970D\u96D5\u96F9\u9704\u9706\u9708\u9713\u970E\u9711\u970F\u9716\u9719\u9724\u972A\u9730\u9739\u973D\u973E\u9744\u9746\u9748\u9742\u9749\u975C\u9760\u9764\u9766\u9768\u52D2\u976B\u9771\u9779\u9785\u977C\u9781\u977A\u9786\u978B\u978F\u9790\u979C\u97A8\u97A6\u97A3\u97B3\u97B4\u97C3\u97C6\u97C8\u97CB\u97DC\u97ED\u9F4F\u97F2\u7ADF\u97F6\u97F5\u980F\u980C\u9838\u9824\u9821\u9837\u983D\u9846\u984F\u984B\u986B\u986F\u9870"], + ["e940", "\u9871\u9874\u9873\u98AA\u98AF\u98B1\u98B6\u98C4\u98C3\u98C6\u98E9\u98EB\u9903\u9909\u9912\u9914\u9918\u9921\u991D\u991E\u9924\u9920\u992C\u992E\u993D\u993E\u9942\u9949\u9945\u9950\u994B\u9951\u9952\u994C\u9955\u9997\u9998\u99A5\u99AD\u99AE\u99BC\u99DF\u99DB\u99DD\u99D8\u99D1\u99ED\u99EE\u99F1\u99F2\u99FB\u99F8\u9A01\u9A0F\u9A05\u99E2\u9A19\u9A2B\u9A37\u9A45\u9A42\u9A40\u9A43"], + ["e980", "\u9A3E\u9A55\u9A4D\u9A5B\u9A57\u9A5F\u9A62\u9A65\u9A64\u9A69\u9A6B\u9A6A\u9AAD\u9AB0\u9ABC\u9AC0\u9ACF\u9AD1\u9AD3\u9AD4\u9ADE\u9ADF\u9AE2\u9AE3\u9AE6\u9AEF\u9AEB\u9AEE\u9AF4\u9AF1\u9AF7\u9AFB\u9B06\u9B18\u9B1A\u9B1F\u9B22\u9B23\u9B25\u9B27\u9B28\u9B29\u9B2A\u9B2E\u9B2F\u9B32\u9B44\u9B43\u9B4F\u9B4D\u9B4E\u9B51\u9B58\u9B74\u9B93\u9B83\u9B91\u9B96\u9B97\u9B9F\u9BA0\u9BA8\u9BB4\u9BC0\u9BCA\u9BB9\u9BC6\u9BCF\u9BD1\u9BD2\u9BE3\u9BE2\u9BE4\u9BD4\u9BE1\u9C3A\u9BF2\u9BF1\u9BF0\u9C15\u9C14\u9C09\u9C13\u9C0C\u9C06\u9C08\u9C12\u9C0A\u9C04\u9C2E\u9C1B\u9C25\u9C24\u9C21\u9C30\u9C47\u9C32\u9C46\u9C3E\u9C5A\u9C60\u9C67\u9C76\u9C78\u9CE7\u9CEC\u9CF0\u9D09\u9D08\u9CEB\u9D03\u9D06\u9D2A\u9D26\u9DAF\u9D23\u9D1F\u9D44\u9D15\u9D12\u9D41\u9D3F\u9D3E\u9D46\u9D48"], + ["ea40", "\u9D5D\u9D5E\u9D64\u9D51\u9D50\u9D59\u9D72\u9D89\u9D87\u9DAB\u9D6F\u9D7A\u9D9A\u9DA4\u9DA9\u9DB2\u9DC4\u9DC1\u9DBB\u9DB8\u9DBA\u9DC6\u9DCF\u9DC2\u9DD9\u9DD3\u9DF8\u9DE6\u9DED\u9DEF\u9DFD\u9E1A\u9E1B\u9E1E\u9E75\u9E79\u9E7D\u9E81\u9E88\u9E8B\u9E8C\u9E92\u9E95\u9E91\u9E9D\u9EA5\u9EA9\u9EB8\u9EAA\u9EAD\u9761\u9ECC\u9ECE\u9ECF\u9ED0\u9ED4\u9EDC\u9EDE\u9EDD\u9EE0\u9EE5\u9EE8\u9EEF"], + ["ea80", "\u9EF4\u9EF6\u9EF7\u9EF9\u9EFB\u9EFC\u9EFD\u9F07\u9F08\u76B7\u9F15\u9F21\u9F2C\u9F3E\u9F4A\u9F52\u9F54\u9F63\u9F5F\u9F60\u9F61\u9F66\u9F67\u9F6C\u9F6A\u9F77\u9F72\u9F76\u9F95\u9F9C\u9FA0\u582F\u69C7\u9059\u7464\u51DC\u7199"], + ["ed40", "\u7E8A\u891C\u9348\u9288\u84DC\u4FC9\u70BB\u6631\u68C8\u92F9\u66FB\u5F45\u4E28\u4EE1\u4EFC\u4F00\u4F03\u4F39\u4F56\u4F92\u4F8A\u4F9A\u4F94\u4FCD\u5040\u5022\u4FFF\u501E\u5046\u5070\u5042\u5094\u50F4\u50D8\u514A\u5164\u519D\u51BE\u51EC\u5215\u529C\u52A6\u52C0\u52DB\u5300\u5307\u5324\u5372\u5393\u53B2\u53DD\uFA0E\u549C\u548A\u54A9\u54FF\u5586\u5759\u5765\u57AC\u57C8\u57C7\uFA0F"], + ["ed80", "\uFA10\u589E\u58B2\u590B\u5953\u595B\u595D\u5963\u59A4\u59BA\u5B56\u5BC0\u752F\u5BD8\u5BEC\u5C1E\u5CA6\u5CBA\u5CF5\u5D27\u5D53\uFA11\u5D42\u5D6D\u5DB8\u5DB9\u5DD0\u5F21\u5F34\u5F67\u5FB7\u5FDE\u605D\u6085\u608A\u60DE\u60D5\u6120\u60F2\u6111\u6137\u6130\u6198\u6213\u62A6\u63F5\u6460\u649D\u64CE\u654E\u6600\u6615\u663B\u6609\u662E\u661E\u6624\u6665\u6657\u6659\uFA12\u6673\u6699\u66A0\u66B2\u66BF\u66FA\u670E\uF929\u6766\u67BB\u6852\u67C0\u6801\u6844\u68CF\uFA13\u6968\uFA14\u6998\u69E2\u6A30\u6A6B\u6A46\u6A73\u6A7E\u6AE2\u6AE4\u6BD6\u6C3F\u6C5C\u6C86\u6C6F\u6CDA\u6D04\u6D87\u6D6F\u6D96\u6DAC\u6DCF\u6DF8\u6DF2\u6DFC\u6E39\u6E5C\u6E27\u6E3C\u6EBF\u6F88\u6FB5\u6FF5\u7005\u7007\u7028\u7085\u70AB\u710F\u7104\u715C\u7146\u7147\uFA15\u71C1\u71FE\u72B1"], + ["ee40", "\u72BE\u7324\uFA16\u7377\u73BD\u73C9\u73D6\u73E3\u73D2\u7407\u73F5\u7426\u742A\u7429\u742E\u7462\u7489\u749F\u7501\u756F\u7682\u769C\u769E\u769B\u76A6\uFA17\u7746\u52AF\u7821\u784E\u7864\u787A\u7930\uFA18\uFA19\uFA1A\u7994\uFA1B\u799B\u7AD1\u7AE7\uFA1C\u7AEB\u7B9E\uFA1D\u7D48\u7D5C\u7DB7\u7DA0\u7DD6\u7E52\u7F47\u7FA1\uFA1E\u8301\u8362\u837F\u83C7\u83F6\u8448\u84B4\u8553\u8559"], + ["ee80", "\u856B\uFA1F\u85B0\uFA20\uFA21\u8807\u88F5\u8A12\u8A37\u8A79\u8AA7\u8ABE\u8ADF\uFA22\u8AF6\u8B53\u8B7F\u8CF0\u8CF4\u8D12\u8D76\uFA23\u8ECF\uFA24\uFA25\u9067\u90DE\uFA26\u9115\u9127\u91DA\u91D7\u91DE\u91ED\u91EE\u91E4\u91E5\u9206\u9210\u920A\u923A\u9240\u923C\u924E\u9259\u9251\u9239\u9267\u92A7\u9277\u9278\u92E7\u92D7\u92D9\u92D0\uFA27\u92D5\u92E0\u92D3\u9325\u9321\u92FB\uFA28\u931E\u92FF\u931D\u9302\u9370\u9357\u93A4\u93C6\u93DE\u93F8\u9431\u9445\u9448\u9592\uF9DC\uFA29\u969D\u96AF\u9733\u973B\u9743\u974D\u974F\u9751\u9755\u9857\u9865\uFA2A\uFA2B\u9927\uFA2C\u999E\u9A4E\u9AD9\u9ADC\u9B75\u9B72\u9B8F\u9BB1\u9BBB\u9C00\u9D70\u9D6B\uFA2D\u9E19\u9ED1"], + ["eeef", "\u2170", 9, "\uFFE2\uFFE4\uFF07\uFF02"], + ["f040", "\uE000", 62], + ["f080", "\uE03F", 124], + ["f140", "\uE0BC", 62], + ["f180", "\uE0FB", 124], + ["f240", "\uE178", 62], + ["f280", "\uE1B7", 124], + ["f340", "\uE234", 62], + ["f380", "\uE273", 124], + ["f440", "\uE2F0", 62], + ["f480", "\uE32F", 124], + ["f540", "\uE3AC", 62], + ["f580", "\uE3EB", 124], + ["f640", "\uE468", 62], + ["f680", "\uE4A7", 124], + ["f740", "\uE524", 62], + ["f780", "\uE563", 124], + ["f840", "\uE5E0", 62], + ["f880", "\uE61F", 124], + ["f940", "\uE69C"], + ["fa40", "\u2170", 9, "\u2160", 9, "\uFFE2\uFFE4\uFF07\uFF02\u3231\u2116\u2121\u2235\u7E8A\u891C\u9348\u9288\u84DC\u4FC9\u70BB\u6631\u68C8\u92F9\u66FB\u5F45\u4E28\u4EE1\u4EFC\u4F00\u4F03\u4F39\u4F56\u4F92\u4F8A\u4F9A\u4F94\u4FCD\u5040\u5022\u4FFF\u501E\u5046\u5070\u5042\u5094\u50F4\u50D8\u514A"], + ["fa80", "\u5164\u519D\u51BE\u51EC\u5215\u529C\u52A6\u52C0\u52DB\u5300\u5307\u5324\u5372\u5393\u53B2\u53DD\uFA0E\u549C\u548A\u54A9\u54FF\u5586\u5759\u5765\u57AC\u57C8\u57C7\uFA0F\uFA10\u589E\u58B2\u590B\u5953\u595B\u595D\u5963\u59A4\u59BA\u5B56\u5BC0\u752F\u5BD8\u5BEC\u5C1E\u5CA6\u5CBA\u5CF5\u5D27\u5D53\uFA11\u5D42\u5D6D\u5DB8\u5DB9\u5DD0\u5F21\u5F34\u5F67\u5FB7\u5FDE\u605D\u6085\u608A\u60DE\u60D5\u6120\u60F2\u6111\u6137\u6130\u6198\u6213\u62A6\u63F5\u6460\u649D\u64CE\u654E\u6600\u6615\u663B\u6609\u662E\u661E\u6624\u6665\u6657\u6659\uFA12\u6673\u6699\u66A0\u66B2\u66BF\u66FA\u670E\uF929\u6766\u67BB\u6852\u67C0\u6801\u6844\u68CF\uFA13\u6968\uFA14\u6998\u69E2\u6A30\u6A6B\u6A46\u6A73\u6A7E\u6AE2\u6AE4\u6BD6\u6C3F\u6C5C\u6C86\u6C6F\u6CDA\u6D04\u6D87\u6D6F"], + ["fb40", "\u6D96\u6DAC\u6DCF\u6DF8\u6DF2\u6DFC\u6E39\u6E5C\u6E27\u6E3C\u6EBF\u6F88\u6FB5\u6FF5\u7005\u7007\u7028\u7085\u70AB\u710F\u7104\u715C\u7146\u7147\uFA15\u71C1\u71FE\u72B1\u72BE\u7324\uFA16\u7377\u73BD\u73C9\u73D6\u73E3\u73D2\u7407\u73F5\u7426\u742A\u7429\u742E\u7462\u7489\u749F\u7501\u756F\u7682\u769C\u769E\u769B\u76A6\uFA17\u7746\u52AF\u7821\u784E\u7864\u787A\u7930\uFA18\uFA19"], + ["fb80", "\uFA1A\u7994\uFA1B\u799B\u7AD1\u7AE7\uFA1C\u7AEB\u7B9E\uFA1D\u7D48\u7D5C\u7DB7\u7DA0\u7DD6\u7E52\u7F47\u7FA1\uFA1E\u8301\u8362\u837F\u83C7\u83F6\u8448\u84B4\u8553\u8559\u856B\uFA1F\u85B0\uFA20\uFA21\u8807\u88F5\u8A12\u8A37\u8A79\u8AA7\u8ABE\u8ADF\uFA22\u8AF6\u8B53\u8B7F\u8CF0\u8CF4\u8D12\u8D76\uFA23\u8ECF\uFA24\uFA25\u9067\u90DE\uFA26\u9115\u9127\u91DA\u91D7\u91DE\u91ED\u91EE\u91E4\u91E5\u9206\u9210\u920A\u923A\u9240\u923C\u924E\u9259\u9251\u9239\u9267\u92A7\u9277\u9278\u92E7\u92D7\u92D9\u92D0\uFA27\u92D5\u92E0\u92D3\u9325\u9321\u92FB\uFA28\u931E\u92FF\u931D\u9302\u9370\u9357\u93A4\u93C6\u93DE\u93F8\u9431\u9445\u9448\u9592\uF9DC\uFA29\u969D\u96AF\u9733\u973B\u9743\u974D\u974F\u9751\u9755\u9857\u9865\uFA2A\uFA2B\u9927\uFA2C\u999E\u9A4E\u9AD9"], + ["fc40", "\u9ADC\u9B75\u9B72\u9B8F\u9BB1\u9BBB\u9C00\u9D70\u9D6B\uFA2D\u9E19\u9ED1"] + ]; + } +}); + +// node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/encodings/tables/eucjp.json +var require_eucjp = __commonJS({ + "node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/encodings/tables/eucjp.json"(exports, module) { + module.exports = [ + ["0", "\0", 127], + ["8ea1", "\uFF61", 62], + ["a1a1", "\u3000\u3001\u3002\uFF0C\uFF0E\u30FB\uFF1A\uFF1B\uFF1F\uFF01\u309B\u309C\xB4\uFF40\xA8\uFF3E\uFFE3\uFF3F\u30FD\u30FE\u309D\u309E\u3003\u4EDD\u3005\u3006\u3007\u30FC\u2015\u2010\uFF0F\uFF3C\uFF5E\u2225\uFF5C\u2026\u2025\u2018\u2019\u201C\u201D\uFF08\uFF09\u3014\u3015\uFF3B\uFF3D\uFF5B\uFF5D\u3008", 9, "\uFF0B\uFF0D\xB1\xD7\xF7\uFF1D\u2260\uFF1C\uFF1E\u2266\u2267\u221E\u2234\u2642\u2640\xB0\u2032\u2033\u2103\uFFE5\uFF04\uFFE0\uFFE1\uFF05\uFF03\uFF06\uFF0A\uFF20\xA7\u2606\u2605\u25CB\u25CF\u25CE\u25C7"], + ["a2a1", "\u25C6\u25A1\u25A0\u25B3\u25B2\u25BD\u25BC\u203B\u3012\u2192\u2190\u2191\u2193\u3013"], + ["a2ba", "\u2208\u220B\u2286\u2287\u2282\u2283\u222A\u2229"], + ["a2ca", "\u2227\u2228\uFFE2\u21D2\u21D4\u2200\u2203"], + ["a2dc", "\u2220\u22A5\u2312\u2202\u2207\u2261\u2252\u226A\u226B\u221A\u223D\u221D\u2235\u222B\u222C"], + ["a2f2", "\u212B\u2030\u266F\u266D\u266A\u2020\u2021\xB6"], + ["a2fe", "\u25EF"], + ["a3b0", "\uFF10", 9], + ["a3c1", "\uFF21", 25], + ["a3e1", "\uFF41", 25], + ["a4a1", "\u3041", 82], + ["a5a1", "\u30A1", 85], + ["a6a1", "\u0391", 16, "\u03A3", 6], + ["a6c1", "\u03B1", 16, "\u03C3", 6], + ["a7a1", "\u0410", 5, "\u0401\u0416", 25], + ["a7d1", "\u0430", 5, "\u0451\u0436", 25], + ["a8a1", "\u2500\u2502\u250C\u2510\u2518\u2514\u251C\u252C\u2524\u2534\u253C\u2501\u2503\u250F\u2513\u251B\u2517\u2523\u2533\u252B\u253B\u254B\u2520\u252F\u2528\u2537\u253F\u251D\u2530\u2525\u2538\u2542"], + ["ada1", "\u2460", 19, "\u2160", 9], + ["adc0", "\u3349\u3314\u3322\u334D\u3318\u3327\u3303\u3336\u3351\u3357\u330D\u3326\u3323\u332B\u334A\u333B\u339C\u339D\u339E\u338E\u338F\u33C4\u33A1"], + ["addf", "\u337B\u301D\u301F\u2116\u33CD\u2121\u32A4", 4, "\u3231\u3232\u3239\u337E\u337D\u337C\u2252\u2261\u222B\u222E\u2211\u221A\u22A5\u2220\u221F\u22BF\u2235\u2229\u222A"], + ["b0a1", "\u4E9C\u5516\u5A03\u963F\u54C0\u611B\u6328\u59F6\u9022\u8475\u831C\u7A50\u60AA\u63E1\u6E25\u65ED\u8466\u82A6\u9BF5\u6893\u5727\u65A1\u6271\u5B9B\u59D0\u867B\u98F4\u7D62\u7DBE\u9B8E\u6216\u7C9F\u88B7\u5B89\u5EB5\u6309\u6697\u6848\u95C7\u978D\u674F\u4EE5\u4F0A\u4F4D\u4F9D\u5049\u56F2\u5937\u59D4\u5A01\u5C09\u60DF\u610F\u6170\u6613\u6905\u70BA\u754F\u7570\u79FB\u7DAD\u7DEF\u80C3\u840E\u8863\u8B02\u9055\u907A\u533B\u4E95\u4EA5\u57DF\u80B2\u90C1\u78EF\u4E00\u58F1\u6EA2\u9038\u7A32\u8328\u828B\u9C2F\u5141\u5370\u54BD\u54E1\u56E0\u59FB\u5F15\u98F2\u6DEB\u80E4\u852D"], + ["b1a1", "\u9662\u9670\u96A0\u97FB\u540B\u53F3\u5B87\u70CF\u7FBD\u8FC2\u96E8\u536F\u9D5C\u7ABA\u4E11\u7893\u81FC\u6E26\u5618\u5504\u6B1D\u851A\u9C3B\u59E5\u53A9\u6D66\u74DC\u958F\u5642\u4E91\u904B\u96F2\u834F\u990C\u53E1\u55B6\u5B30\u5F71\u6620\u66F3\u6804\u6C38\u6CF3\u6D29\u745B\u76C8\u7A4E\u9834\u82F1\u885B\u8A60\u92ED\u6DB2\u75AB\u76CA\u99C5\u60A6\u8B01\u8D8A\u95B2\u698E\u53AD\u5186\u5712\u5830\u5944\u5BB4\u5EF6\u6028\u63A9\u63F4\u6CBF\u6F14\u708E\u7114\u7159\u71D5\u733F\u7E01\u8276\u82D1\u8597\u9060\u925B\u9D1B\u5869\u65BC\u6C5A\u7525\u51F9\u592E\u5965\u5F80\u5FDC"], + ["b2a1", "\u62BC\u65FA\u6A2A\u6B27\u6BB4\u738B\u7FC1\u8956\u9D2C\u9D0E\u9EC4\u5CA1\u6C96\u837B\u5104\u5C4B\u61B6\u81C6\u6876\u7261\u4E59\u4FFA\u5378\u6069\u6E29\u7A4F\u97F3\u4E0B\u5316\u4EEE\u4F55\u4F3D\u4FA1\u4F73\u52A0\u53EF\u5609\u590F\u5AC1\u5BB6\u5BE1\u79D1\u6687\u679C\u67B6\u6B4C\u6CB3\u706B\u73C2\u798D\u79BE\u7A3C\u7B87\u82B1\u82DB\u8304\u8377\u83EF\u83D3\u8766\u8AB2\u5629\u8CA8\u8FE6\u904E\u971E\u868A\u4FC4\u5CE8\u6211\u7259\u753B\u81E5\u82BD\u86FE\u8CC0\u96C5\u9913\u99D5\u4ECB\u4F1A\u89E3\u56DE\u584A\u58CA\u5EFB\u5FEB\u602A\u6094\u6062\u61D0\u6212\u62D0\u6539"], + ["b3a1", "\u9B41\u6666\u68B0\u6D77\u7070\u754C\u7686\u7D75\u82A5\u87F9\u958B\u968E\u8C9D\u51F1\u52BE\u5916\u54B3\u5BB3\u5D16\u6168\u6982\u6DAF\u788D\u84CB\u8857\u8A72\u93A7\u9AB8\u6D6C\u99A8\u86D9\u57A3\u67FF\u86CE\u920E\u5283\u5687\u5404\u5ED3\u62E1\u64B9\u683C\u6838\u6BBB\u7372\u78BA\u7A6B\u899A\u89D2\u8D6B\u8F03\u90ED\u95A3\u9694\u9769\u5B66\u5CB3\u697D\u984D\u984E\u639B\u7B20\u6A2B\u6A7F\u68B6\u9C0D\u6F5F\u5272\u559D\u6070\u62EC\u6D3B\u6E07\u6ED1\u845B\u8910\u8F44\u4E14\u9C39\u53F6\u691B\u6A3A\u9784\u682A\u515C\u7AC3\u84B2\u91DC\u938C\u565B\u9D28\u6822\u8305\u8431"], + ["b4a1", "\u7CA5\u5208\u82C5\u74E6\u4E7E\u4F83\u51A0\u5BD2\u520A\u52D8\u52E7\u5DFB\u559A\u582A\u59E6\u5B8C\u5B98\u5BDB\u5E72\u5E79\u60A3\u611F\u6163\u61BE\u63DB\u6562\u67D1\u6853\u68FA\u6B3E\u6B53\u6C57\u6F22\u6F97\u6F45\u74B0\u7518\u76E3\u770B\u7AFF\u7BA1\u7C21\u7DE9\u7F36\u7FF0\u809D\u8266\u839E\u89B3\u8ACC\u8CAB\u9084\u9451\u9593\u9591\u95A2\u9665\u97D3\u9928\u8218\u4E38\u542B\u5CB8\u5DCC\u73A9\u764C\u773C\u5CA9\u7FEB\u8D0B\u96C1\u9811\u9854\u9858\u4F01\u4F0E\u5371\u559C\u5668\u57FA\u5947\u5B09\u5BC4\u5C90\u5E0C\u5E7E\u5FCC\u63EE\u673A\u65D7\u65E2\u671F\u68CB\u68C4"], + ["b5a1", "\u6A5F\u5E30\u6BC5\u6C17\u6C7D\u757F\u7948\u5B63\u7A00\u7D00\u5FBD\u898F\u8A18\u8CB4\u8D77\u8ECC\u8F1D\u98E2\u9A0E\u9B3C\u4E80\u507D\u5100\u5993\u5B9C\u622F\u6280\u64EC\u6B3A\u72A0\u7591\u7947\u7FA9\u87FB\u8ABC\u8B70\u63AC\u83CA\u97A0\u5409\u5403\u55AB\u6854\u6A58\u8A70\u7827\u6775\u9ECD\u5374\u5BA2\u811A\u8650\u9006\u4E18\u4E45\u4EC7\u4F11\u53CA\u5438\u5BAE\u5F13\u6025\u6551\u673D\u6C42\u6C72\u6CE3\u7078\u7403\u7A76\u7AAE\u7B08\u7D1A\u7CFE\u7D66\u65E7\u725B\u53BB\u5C45\u5DE8\u62D2\u62E0\u6319\u6E20\u865A\u8A31\u8DDD\u92F8\u6F01\u79A6\u9B5A\u4EA8\u4EAB\u4EAC"], + ["b6a1", "\u4F9B\u4FA0\u50D1\u5147\u7AF6\u5171\u51F6\u5354\u5321\u537F\u53EB\u55AC\u5883\u5CE1\u5F37\u5F4A\u602F\u6050\u606D\u631F\u6559\u6A4B\u6CC1\u72C2\u72ED\u77EF\u80F8\u8105\u8208\u854E\u90F7\u93E1\u97FF\u9957\u9A5A\u4EF0\u51DD\u5C2D\u6681\u696D\u5C40\u66F2\u6975\u7389\u6850\u7C81\u50C5\u52E4\u5747\u5DFE\u9326\u65A4\u6B23\u6B3D\u7434\u7981\u79BD\u7B4B\u7DCA\u82B9\u83CC\u887F\u895F\u8B39\u8FD1\u91D1\u541F\u9280\u4E5D\u5036\u53E5\u533A\u72D7\u7396\u77E9\u82E6\u8EAF\u99C6\u99C8\u99D2\u5177\u611A\u865E\u55B0\u7A7A\u5076\u5BD3\u9047\u9685\u4E32\u6ADB\u91E7\u5C51\u5C48"], + ["b7a1", "\u6398\u7A9F\u6C93\u9774\u8F61\u7AAA\u718A\u9688\u7C82\u6817\u7E70\u6851\u936C\u52F2\u541B\u85AB\u8A13\u7FA4\u8ECD\u90E1\u5366\u8888\u7941\u4FC2\u50BE\u5211\u5144\u5553\u572D\u73EA\u578B\u5951\u5F62\u5F84\u6075\u6176\u6167\u61A9\u63B2\u643A\u656C\u666F\u6842\u6E13\u7566\u7A3D\u7CFB\u7D4C\u7D99\u7E4B\u7F6B\u830E\u834A\u86CD\u8A08\u8A63\u8B66\u8EFD\u981A\u9D8F\u82B8\u8FCE\u9BE8\u5287\u621F\u6483\u6FC0\u9699\u6841\u5091\u6B20\u6C7A\u6F54\u7A74\u7D50\u8840\u8A23\u6708\u4EF6\u5039\u5026\u5065\u517C\u5238\u5263\u55A7\u570F\u5805\u5ACC\u5EFA\u61B2\u61F8\u62F3\u6372"], + ["b8a1", "\u691C\u6A29\u727D\u72AC\u732E\u7814\u786F\u7D79\u770C\u80A9\u898B\u8B19\u8CE2\u8ED2\u9063\u9375\u967A\u9855\u9A13\u9E78\u5143\u539F\u53B3\u5E7B\u5F26\u6E1B\u6E90\u7384\u73FE\u7D43\u8237\u8A00\u8AFA\u9650\u4E4E\u500B\u53E4\u547C\u56FA\u59D1\u5B64\u5DF1\u5EAB\u5F27\u6238\u6545\u67AF\u6E56\u72D0\u7CCA\u88B4\u80A1\u80E1\u83F0\u864E\u8A87\u8DE8\u9237\u96C7\u9867\u9F13\u4E94\u4E92\u4F0D\u5348\u5449\u543E\u5A2F\u5F8C\u5FA1\u609F\u68A7\u6A8E\u745A\u7881\u8A9E\u8AA4\u8B77\u9190\u4E5E\u9BC9\u4EA4\u4F7C\u4FAF\u5019\u5016\u5149\u516C\u529F\u52B9\u52FE\u539A\u53E3\u5411"], + ["b9a1", "\u540E\u5589\u5751\u57A2\u597D\u5B54\u5B5D\u5B8F\u5DE5\u5DE7\u5DF7\u5E78\u5E83\u5E9A\u5EB7\u5F18\u6052\u614C\u6297\u62D8\u63A7\u653B\u6602\u6643\u66F4\u676D\u6821\u6897\u69CB\u6C5F\u6D2A\u6D69\u6E2F\u6E9D\u7532\u7687\u786C\u7A3F\u7CE0\u7D05\u7D18\u7D5E\u7DB1\u8015\u8003\u80AF\u80B1\u8154\u818F\u822A\u8352\u884C\u8861\u8B1B\u8CA2\u8CFC\u90CA\u9175\u9271\u783F\u92FC\u95A4\u964D\u9805\u9999\u9AD8\u9D3B\u525B\u52AB\u53F7\u5408\u58D5\u62F7\u6FE0\u8C6A\u8F5F\u9EB9\u514B\u523B\u544A\u56FD\u7A40\u9177\u9D60\u9ED2\u7344\u6F09\u8170\u7511\u5FFD\u60DA\u9AA8\u72DB\u8FBC"], + ["baa1", "\u6B64\u9803\u4ECA\u56F0\u5764\u58BE\u5A5A\u6068\u61C7\u660F\u6606\u6839\u68B1\u6DF7\u75D5\u7D3A\u826E\u9B42\u4E9B\u4F50\u53C9\u5506\u5D6F\u5DE6\u5DEE\u67FB\u6C99\u7473\u7802\u8A50\u9396\u88DF\u5750\u5EA7\u632B\u50B5\u50AC\u518D\u6700\u54C9\u585E\u59BB\u5BB0\u5F69\u624D\u63A1\u683D\u6B73\u6E08\u707D\u91C7\u7280\u7815\u7826\u796D\u658E\u7D30\u83DC\u88C1\u8F09\u969B\u5264\u5728\u6750\u7F6A\u8CA1\u51B4\u5742\u962A\u583A\u698A\u80B4\u54B2\u5D0E\u57FC\u7895\u9DFA\u4F5C\u524A\u548B\u643E\u6628\u6714\u67F5\u7A84\u7B56\u7D22\u932F\u685C\u9BAD\u7B39\u5319\u518A\u5237"], + ["bba1", "\u5BDF\u62F6\u64AE\u64E6\u672D\u6BBA\u85A9\u96D1\u7690\u9BD6\u634C\u9306\u9BAB\u76BF\u6652\u4E09\u5098\u53C2\u5C71\u60E8\u6492\u6563\u685F\u71E6\u73CA\u7523\u7B97\u7E82\u8695\u8B83\u8CDB\u9178\u9910\u65AC\u66AB\u6B8B\u4ED5\u4ED4\u4F3A\u4F7F\u523A\u53F8\u53F2\u55E3\u56DB\u58EB\u59CB\u59C9\u59FF\u5B50\u5C4D\u5E02\u5E2B\u5FD7\u601D\u6307\u652F\u5B5C\u65AF\u65BD\u65E8\u679D\u6B62\u6B7B\u6C0F\u7345\u7949\u79C1\u7CF8\u7D19\u7D2B\u80A2\u8102\u81F3\u8996\u8A5E\u8A69\u8A66\u8A8C\u8AEE\u8CC7\u8CDC\u96CC\u98FC\u6B6F\u4E8B\u4F3C\u4F8D\u5150\u5B57\u5BFA\u6148\u6301\u6642"], + ["bca1", "\u6B21\u6ECB\u6CBB\u723E\u74BD\u75D4\u78C1\u793A\u800C\u8033\u81EA\u8494\u8F9E\u6C50\u9E7F\u5F0F\u8B58\u9D2B\u7AFA\u8EF8\u5B8D\u96EB\u4E03\u53F1\u57F7\u5931\u5AC9\u5BA4\u6089\u6E7F\u6F06\u75BE\u8CEA\u5B9F\u8500\u7BE0\u5072\u67F4\u829D\u5C61\u854A\u7E1E\u820E\u5199\u5C04\u6368\u8D66\u659C\u716E\u793E\u7D17\u8005\u8B1D\u8ECA\u906E\u86C7\u90AA\u501F\u52FA\u5C3A\u6753\u707C\u7235\u914C\u91C8\u932B\u82E5\u5BC2\u5F31\u60F9\u4E3B\u53D6\u5B88\u624B\u6731\u6B8A\u72E9\u73E0\u7A2E\u816B\u8DA3\u9152\u9996\u5112\u53D7\u546A\u5BFF\u6388\u6A39\u7DAC\u9700\u56DA\u53CE\u5468"], + ["bda1", "\u5B97\u5C31\u5DDE\u4FEE\u6101\u62FE\u6D32\u79C0\u79CB\u7D42\u7E4D\u7FD2\u81ED\u821F\u8490\u8846\u8972\u8B90\u8E74\u8F2F\u9031\u914B\u916C\u96C6\u919C\u4EC0\u4F4F\u5145\u5341\u5F93\u620E\u67D4\u6C41\u6E0B\u7363\u7E26\u91CD\u9283\u53D4\u5919\u5BBF\u6DD1\u795D\u7E2E\u7C9B\u587E\u719F\u51FA\u8853\u8FF0\u4FCA\u5CFB\u6625\u77AC\u7AE3\u821C\u99FF\u51C6\u5FAA\u65EC\u696F\u6B89\u6DF3\u6E96\u6F64\u76FE\u7D14\u5DE1\u9075\u9187\u9806\u51E6\u521D\u6240\u6691\u66D9\u6E1A\u5EB6\u7DD2\u7F72\u66F8\u85AF\u85F7\u8AF8\u52A9\u53D9\u5973\u5E8F\u5F90\u6055\u92E4\u9664\u50B7\u511F"], + ["bea1", "\u52DD\u5320\u5347\u53EC\u54E8\u5546\u5531\u5617\u5968\u59BE\u5A3C\u5BB5\u5C06\u5C0F\u5C11\u5C1A\u5E84\u5E8A\u5EE0\u5F70\u627F\u6284\u62DB\u638C\u6377\u6607\u660C\u662D\u6676\u677E\u68A2\u6A1F\u6A35\u6CBC\u6D88\u6E09\u6E58\u713C\u7126\u7167\u75C7\u7701\u785D\u7901\u7965\u79F0\u7AE0\u7B11\u7CA7\u7D39\u8096\u83D6\u848B\u8549\u885D\u88F3\u8A1F\u8A3C\u8A54\u8A73\u8C61\u8CDE\u91A4\u9266\u937E\u9418\u969C\u9798\u4E0A\u4E08\u4E1E\u4E57\u5197\u5270\u57CE\u5834\u58CC\u5B22\u5E38\u60C5\u64FE\u6761\u6756\u6D44\u72B6\u7573\u7A63\u84B8\u8B72\u91B8\u9320\u5631\u57F4\u98FE"], + ["bfa1", "\u62ED\u690D\u6B96\u71ED\u7E54\u8077\u8272\u89E6\u98DF\u8755\u8FB1\u5C3B\u4F38\u4FE1\u4FB5\u5507\u5A20\u5BDD\u5BE9\u5FC3\u614E\u632F\u65B0\u664B\u68EE\u699B\u6D78\u6DF1\u7533\u75B9\u771F\u795E\u79E6\u7D33\u81E3\u82AF\u85AA\u89AA\u8A3A\u8EAB\u8F9B\u9032\u91DD\u9707\u4EBA\u4EC1\u5203\u5875\u58EC\u5C0B\u751A\u5C3D\u814E\u8A0A\u8FC5\u9663\u976D\u7B25\u8ACF\u9808\u9162\u56F3\u53A8\u9017\u5439\u5782\u5E25\u63A8\u6C34\u708A\u7761\u7C8B\u7FE0\u8870\u9042\u9154\u9310\u9318\u968F\u745E\u9AC4\u5D07\u5D69\u6570\u67A2\u8DA8\u96DB\u636E\u6749\u6919\u83C5\u9817\u96C0\u88FE"], + ["c0a1", "\u6F84\u647A\u5BF8\u4E16\u702C\u755D\u662F\u51C4\u5236\u52E2\u59D3\u5F81\u6027\u6210\u653F\u6574\u661F\u6674\u68F2\u6816\u6B63\u6E05\u7272\u751F\u76DB\u7CBE\u8056\u58F0\u88FD\u897F\u8AA0\u8A93\u8ACB\u901D\u9192\u9752\u9759\u6589\u7A0E\u8106\u96BB\u5E2D\u60DC\u621A\u65A5\u6614\u6790\u77F3\u7A4D\u7C4D\u7E3E\u810A\u8CAC\u8D64\u8DE1\u8E5F\u78A9\u5207\u62D9\u63A5\u6442\u6298\u8A2D\u7A83\u7BC0\u8AAC\u96EA\u7D76\u820C\u8749\u4ED9\u5148\u5343\u5360\u5BA3\u5C02\u5C16\u5DDD\u6226\u6247\u64B0\u6813\u6834\u6CC9\u6D45\u6D17\u67D3\u6F5C\u714E\u717D\u65CB\u7A7F\u7BAD\u7DDA"], + ["c1a1", "\u7E4A\u7FA8\u817A\u821B\u8239\u85A6\u8A6E\u8CCE\u8DF5\u9078\u9077\u92AD\u9291\u9583\u9BAE\u524D\u5584\u6F38\u7136\u5168\u7985\u7E55\u81B3\u7CCE\u564C\u5851\u5CA8\u63AA\u66FE\u66FD\u695A\u72D9\u758F\u758E\u790E\u7956\u79DF\u7C97\u7D20\u7D44\u8607\u8A34\u963B\u9061\u9F20\u50E7\u5275\u53CC\u53E2\u5009\u55AA\u58EE\u594F\u723D\u5B8B\u5C64\u531D\u60E3\u60F3\u635C\u6383\u633F\u63BB\u64CD\u65E9\u66F9\u5DE3\u69CD\u69FD\u6F15\u71E5\u4E89\u75E9\u76F8\u7A93\u7CDF\u7DCF\u7D9C\u8061\u8349\u8358\u846C\u84BC\u85FB\u88C5\u8D70\u9001\u906D\u9397\u971C\u9A12\u50CF\u5897\u618E"], + ["c2a1", "\u81D3\u8535\u8D08\u9020\u4FC3\u5074\u5247\u5373\u606F\u6349\u675F\u6E2C\u8DB3\u901F\u4FD7\u5C5E\u8CCA\u65CF\u7D9A\u5352\u8896\u5176\u63C3\u5B58\u5B6B\u5C0A\u640D\u6751\u905C\u4ED6\u591A\u592A\u6C70\u8A51\u553E\u5815\u59A5\u60F0\u6253\u67C1\u8235\u6955\u9640\u99C4\u9A28\u4F53\u5806\u5BFE\u8010\u5CB1\u5E2F\u5F85\u6020\u614B\u6234\u66FF\u6CF0\u6EDE\u80CE\u817F\u82D4\u888B\u8CB8\u9000\u902E\u968A\u9EDB\u9BDB\u4EE3\u53F0\u5927\u7B2C\u918D\u984C\u9DF9\u6EDD\u7027\u5353\u5544\u5B85\u6258\u629E\u62D3\u6CA2\u6FEF\u7422\u8A17\u9438\u6FC1\u8AFE\u8338\u51E7\u86F8\u53EA"], + ["c3a1", "\u53E9\u4F46\u9054\u8FB0\u596A\u8131\u5DFD\u7AEA\u8FBF\u68DA\u8C37\u72F8\u9C48\u6A3D\u8AB0\u4E39\u5358\u5606\u5766\u62C5\u63A2\u65E6\u6B4E\u6DE1\u6E5B\u70AD\u77ED\u7AEF\u7BAA\u7DBB\u803D\u80C6\u86CB\u8A95\u935B\u56E3\u58C7\u5F3E\u65AD\u6696\u6A80\u6BB5\u7537\u8AC7\u5024\u77E5\u5730\u5F1B\u6065\u667A\u6C60\u75F4\u7A1A\u7F6E\u81F4\u8718\u9045\u99B3\u7BC9\u755C\u7AF9\u7B51\u84C4\u9010\u79E9\u7A92\u8336\u5AE1\u7740\u4E2D\u4EF2\u5B99\u5FE0\u62BD\u663C\u67F1\u6CE8\u866B\u8877\u8A3B\u914E\u92F3\u99D0\u6A17\u7026\u732A\u82E7\u8457\u8CAF\u4E01\u5146\u51CB\u558B\u5BF5"], + ["c4a1", "\u5E16\u5E33\u5E81\u5F14\u5F35\u5F6B\u5FB4\u61F2\u6311\u66A2\u671D\u6F6E\u7252\u753A\u773A\u8074\u8139\u8178\u8776\u8ABF\u8ADC\u8D85\u8DF3\u929A\u9577\u9802\u9CE5\u52C5\u6357\u76F4\u6715\u6C88\u73CD\u8CC3\u93AE\u9673\u6D25\u589C\u690E\u69CC\u8FFD\u939A\u75DB\u901A\u585A\u6802\u63B4\u69FB\u4F43\u6F2C\u67D8\u8FBB\u8526\u7DB4\u9354\u693F\u6F70\u576A\u58F7\u5B2C\u7D2C\u722A\u540A\u91E3\u9DB4\u4EAD\u4F4E\u505C\u5075\u5243\u8C9E\u5448\u5824\u5B9A\u5E1D\u5E95\u5EAD\u5EF7\u5F1F\u608C\u62B5\u633A\u63D0\u68AF\u6C40\u7887\u798E\u7A0B\u7DE0\u8247\u8A02\u8AE6\u8E44\u9013"], + ["c5a1", "\u90B8\u912D\u91D8\u9F0E\u6CE5\u6458\u64E2\u6575\u6EF4\u7684\u7B1B\u9069\u93D1\u6EBA\u54F2\u5FB9\u64A4\u8F4D\u8FED\u9244\u5178\u586B\u5929\u5C55\u5E97\u6DFB\u7E8F\u751C\u8CBC\u8EE2\u985B\u70B9\u4F1D\u6BBF\u6FB1\u7530\u96FB\u514E\u5410\u5835\u5857\u59AC\u5C60\u5F92\u6597\u675C\u6E21\u767B\u83DF\u8CED\u9014\u90FD\u934D\u7825\u783A\u52AA\u5EA6\u571F\u5974\u6012\u5012\u515A\u51AC\u51CD\u5200\u5510\u5854\u5858\u5957\u5B95\u5CF6\u5D8B\u60BC\u6295\u642D\u6771\u6843\u68BC\u68DF\u76D7\u6DD8\u6E6F\u6D9B\u706F\u71C8\u5F53\u75D8\u7977\u7B49\u7B54\u7B52\u7CD6\u7D71\u5230"], + ["c6a1", "\u8463\u8569\u85E4\u8A0E\u8B04\u8C46\u8E0F\u9003\u900F\u9419\u9676\u982D\u9A30\u95D8\u50CD\u52D5\u540C\u5802\u5C0E\u61A7\u649E\u6D1E\u77B3\u7AE5\u80F4\u8404\u9053\u9285\u5CE0\u9D07\u533F\u5F97\u5FB3\u6D9C\u7279\u7763\u79BF\u7BE4\u6BD2\u72EC\u8AAD\u6803\u6A61\u51F8\u7A81\u6934\u5C4A\u9CF6\u82EB\u5BC5\u9149\u701E\u5678\u5C6F\u60C7\u6566\u6C8C\u8C5A\u9041\u9813\u5451\u66C7\u920D\u5948\u90A3\u5185\u4E4D\u51EA\u8599\u8B0E\u7058\u637A\u934B\u6962\u99B4\u7E04\u7577\u5357\u6960\u8EDF\u96E3\u6C5D\u4E8C\u5C3C\u5F10\u8FE9\u5302\u8CD1\u8089\u8679\u5EFF\u65E5\u4E73\u5165"], + ["c7a1", "\u5982\u5C3F\u97EE\u4EFB\u598A\u5FCD\u8A8D\u6FE1\u79B0\u7962\u5BE7\u8471\u732B\u71B1\u5E74\u5FF5\u637B\u649A\u71C3\u7C98\u4E43\u5EFC\u4E4B\u57DC\u56A2\u60A9\u6FC3\u7D0D\u80FD\u8133\u81BF\u8FB2\u8997\u86A4\u5DF4\u628A\u64AD\u8987\u6777\u6CE2\u6D3E\u7436\u7834\u5A46\u7F75\u82AD\u99AC\u4FF3\u5EC3\u62DD\u6392\u6557\u676F\u76C3\u724C\u80CC\u80BA\u8F29\u914D\u500D\u57F9\u5A92\u6885\u6973\u7164\u72FD\u8CB7\u58F2\u8CE0\u966A\u9019\u877F\u79E4\u77E7\u8429\u4F2F\u5265\u535A\u62CD\u67CF\u6CCA\u767D\u7B94\u7C95\u8236\u8584\u8FEB\u66DD\u6F20\u7206\u7E1B\u83AB\u99C1\u9EA6"], + ["c8a1", "\u51FD\u7BB1\u7872\u7BB8\u8087\u7B48\u6AE8\u5E61\u808C\u7551\u7560\u516B\u9262\u6E8C\u767A\u9197\u9AEA\u4F10\u7F70\u629C\u7B4F\u95A5\u9CE9\u567A\u5859\u86E4\u96BC\u4F34\u5224\u534A\u53CD\u53DB\u5E06\u642C\u6591\u677F\u6C3E\u6C4E\u7248\u72AF\u73ED\u7554\u7E41\u822C\u85E9\u8CA9\u7BC4\u91C6\u7169\u9812\u98EF\u633D\u6669\u756A\u76E4\u78D0\u8543\u86EE\u532A\u5351\u5426\u5983\u5E87\u5F7C\u60B2\u6249\u6279\u62AB\u6590\u6BD4\u6CCC\u75B2\u76AE\u7891\u79D8\u7DCB\u7F77\u80A5\u88AB\u8AB9\u8CBB\u907F\u975E\u98DB\u6A0B\u7C38\u5099\u5C3E\u5FAE\u6787\u6BD8\u7435\u7709\u7F8E"], + ["c9a1", "\u9F3B\u67CA\u7A17\u5339\u758B\u9AED\u5F66\u819D\u83F1\u8098\u5F3C\u5FC5\u7562\u7B46\u903C\u6867\u59EB\u5A9B\u7D10\u767E\u8B2C\u4FF5\u5F6A\u6A19\u6C37\u6F02\u74E2\u7968\u8868\u8A55\u8C79\u5EDF\u63CF\u75C5\u79D2\u82D7\u9328\u92F2\u849C\u86ED\u9C2D\u54C1\u5F6C\u658C\u6D5C\u7015\u8CA7\u8CD3\u983B\u654F\u74F6\u4E0D\u4ED8\u57E0\u592B\u5A66\u5BCC\u51A8\u5E03\u5E9C\u6016\u6276\u6577\u65A7\u666E\u6D6E\u7236\u7B26\u8150\u819A\u8299\u8B5C\u8CA0\u8CE6\u8D74\u961C\u9644\u4FAE\u64AB\u6B66\u821E\u8461\u856A\u90E8\u5C01\u6953\u98A8\u847A\u8557\u4F0F\u526F\u5FA9\u5E45\u670D"], + ["caa1", "\u798F\u8179\u8907\u8986\u6DF5\u5F17\u6255\u6CB8\u4ECF\u7269\u9B92\u5206\u543B\u5674\u58B3\u61A4\u626E\u711A\u596E\u7C89\u7CDE\u7D1B\u96F0\u6587\u805E\u4E19\u4F75\u5175\u5840\u5E63\u5E73\u5F0A\u67C4\u4E26\u853D\u9589\u965B\u7C73\u9801\u50FB\u58C1\u7656\u78A7\u5225\u77A5\u8511\u7B86\u504F\u5909\u7247\u7BC7\u7DE8\u8FBA\u8FD4\u904D\u4FBF\u52C9\u5A29\u5F01\u97AD\u4FDD\u8217\u92EA\u5703\u6355\u6B69\u752B\u88DC\u8F14\u7A42\u52DF\u5893\u6155\u620A\u66AE\u6BCD\u7C3F\u83E9\u5023\u4FF8\u5305\u5446\u5831\u5949\u5B9D\u5CF0\u5CEF\u5D29\u5E96\u62B1\u6367\u653E\u65B9\u670B"], + ["cba1", "\u6CD5\u6CE1\u70F9\u7832\u7E2B\u80DE\u82B3\u840C\u84EC\u8702\u8912\u8A2A\u8C4A\u90A6\u92D2\u98FD\u9CF3\u9D6C\u4E4F\u4EA1\u508D\u5256\u574A\u59A8\u5E3D\u5FD8\u5FD9\u623F\u66B4\u671B\u67D0\u68D2\u5192\u7D21\u80AA\u81A8\u8B00\u8C8C\u8CBF\u927E\u9632\u5420\u982C\u5317\u50D5\u535C\u58A8\u64B2\u6734\u7267\u7766\u7A46\u91E6\u52C3\u6CA1\u6B86\u5800\u5E4C\u5954\u672C\u7FFB\u51E1\u76C6\u6469\u78E8\u9B54\u9EBB\u57CB\u59B9\u6627\u679A\u6BCE\u54E9\u69D9\u5E55\u819C\u6795\u9BAA\u67FE\u9C52\u685D\u4EA6\u4FE3\u53C8\u62B9\u672B\u6CAB\u8FC4\u4FAD\u7E6D\u9EBF\u4E07\u6162\u6E80"], + ["cca1", "\u6F2B\u8513\u5473\u672A\u9B45\u5DF3\u7B95\u5CAC\u5BC6\u871C\u6E4A\u84D1\u7A14\u8108\u5999\u7C8D\u6C11\u7720\u52D9\u5922\u7121\u725F\u77DB\u9727\u9D61\u690B\u5A7F\u5A18\u51A5\u540D\u547D\u660E\u76DF\u8FF7\u9298\u9CF4\u59EA\u725D\u6EC5\u514D\u68C9\u7DBF\u7DEC\u9762\u9EBA\u6478\u6A21\u8302\u5984\u5B5F\u6BDB\u731B\u76F2\u7DB2\u8017\u8499\u5132\u6728\u9ED9\u76EE\u6762\u52FF\u9905\u5C24\u623B\u7C7E\u8CB0\u554F\u60B6\u7D0B\u9580\u5301\u4E5F\u51B6\u591C\u723A\u8036\u91CE\u5F25\u77E2\u5384\u5F79\u7D04\u85AC\u8A33\u8E8D\u9756\u67F3\u85AE\u9453\u6109\u6108\u6CB9\u7652"], + ["cda1", "\u8AED\u8F38\u552F\u4F51\u512A\u52C7\u53CB\u5BA5\u5E7D\u60A0\u6182\u63D6\u6709\u67DA\u6E67\u6D8C\u7336\u7337\u7531\u7950\u88D5\u8A98\u904A\u9091\u90F5\u96C4\u878D\u5915\u4E88\u4F59\u4E0E\u8A89\u8F3F\u9810\u50AD\u5E7C\u5996\u5BB9\u5EB8\u63DA\u63FA\u64C1\u66DC\u694A\u69D8\u6D0B\u6EB6\u7194\u7528\u7AAF\u7F8A\u8000\u8449\u84C9\u8981\u8B21\u8E0A\u9065\u967D\u990A\u617E\u6291\u6B32\u6C83\u6D74\u7FCC\u7FFC\u6DC0\u7F85\u87BA\u88F8\u6765\u83B1\u983C\u96F7\u6D1B\u7D61\u843D\u916A\u4E71\u5375\u5D50\u6B04\u6FEB\u85CD\u862D\u89A7\u5229\u540F\u5C65\u674E\u68A8\u7406\u7483"], + ["cea1", "\u75E2\u88CF\u88E1\u91CC\u96E2\u9678\u5F8B\u7387\u7ACB\u844E\u63A0\u7565\u5289\u6D41\u6E9C\u7409\u7559\u786B\u7C92\u9686\u7ADC\u9F8D\u4FB6\u616E\u65C5\u865C\u4E86\u4EAE\u50DA\u4E21\u51CC\u5BEE\u6599\u6881\u6DBC\u731F\u7642\u77AD\u7A1C\u7CE7\u826F\u8AD2\u907C\u91CF\u9675\u9818\u529B\u7DD1\u502B\u5398\u6797\u6DCB\u71D0\u7433\u81E8\u8F2A\u96A3\u9C57\u9E9F\u7460\u5841\u6D99\u7D2F\u985E\u4EE4\u4F36\u4F8B\u51B7\u52B1\u5DBA\u601C\u73B2\u793C\u82D3\u9234\u96B7\u96F6\u970A\u9E97\u9F62\u66A6\u6B74\u5217\u52A3\u70C8\u88C2\u5EC9\u604B\u6190\u6F23\u7149\u7C3E\u7DF4\u806F"], + ["cfa1", "\u84EE\u9023\u932C\u5442\u9B6F\u6AD3\u7089\u8CC2\u8DEF\u9732\u52B4\u5A41\u5ECA\u5F04\u6717\u697C\u6994\u6D6A\u6F0F\u7262\u72FC\u7BED\u8001\u807E\u874B\u90CE\u516D\u9E93\u7984\u808B\u9332\u8AD6\u502D\u548C\u8A71\u6B6A\u8CC4\u8107\u60D1\u67A0\u9DF2\u4E99\u4E98\u9C10\u8A6B\u85C1\u8568\u6900\u6E7E\u7897\u8155"], + ["d0a1", "\u5F0C\u4E10\u4E15\u4E2A\u4E31\u4E36\u4E3C\u4E3F\u4E42\u4E56\u4E58\u4E82\u4E85\u8C6B\u4E8A\u8212\u5F0D\u4E8E\u4E9E\u4E9F\u4EA0\u4EA2\u4EB0\u4EB3\u4EB6\u4ECE\u4ECD\u4EC4\u4EC6\u4EC2\u4ED7\u4EDE\u4EED\u4EDF\u4EF7\u4F09\u4F5A\u4F30\u4F5B\u4F5D\u4F57\u4F47\u4F76\u4F88\u4F8F\u4F98\u4F7B\u4F69\u4F70\u4F91\u4F6F\u4F86\u4F96\u5118\u4FD4\u4FDF\u4FCE\u4FD8\u4FDB\u4FD1\u4FDA\u4FD0\u4FE4\u4FE5\u501A\u5028\u5014\u502A\u5025\u5005\u4F1C\u4FF6\u5021\u5029\u502C\u4FFE\u4FEF\u5011\u5006\u5043\u5047\u6703\u5055\u5050\u5048\u505A\u5056\u506C\u5078\u5080\u509A\u5085\u50B4\u50B2"], + ["d1a1", "\u50C9\u50CA\u50B3\u50C2\u50D6\u50DE\u50E5\u50ED\u50E3\u50EE\u50F9\u50F5\u5109\u5101\u5102\u5116\u5115\u5114\u511A\u5121\u513A\u5137\u513C\u513B\u513F\u5140\u5152\u514C\u5154\u5162\u7AF8\u5169\u516A\u516E\u5180\u5182\u56D8\u518C\u5189\u518F\u5191\u5193\u5195\u5196\u51A4\u51A6\u51A2\u51A9\u51AA\u51AB\u51B3\u51B1\u51B2\u51B0\u51B5\u51BD\u51C5\u51C9\u51DB\u51E0\u8655\u51E9\u51ED\u51F0\u51F5\u51FE\u5204\u520B\u5214\u520E\u5227\u522A\u522E\u5233\u5239\u524F\u5244\u524B\u524C\u525E\u5254\u526A\u5274\u5269\u5273\u527F\u527D\u528D\u5294\u5292\u5271\u5288\u5291\u8FA8"], + ["d2a1", "\u8FA7\u52AC\u52AD\u52BC\u52B5\u52C1\u52CD\u52D7\u52DE\u52E3\u52E6\u98ED\u52E0\u52F3\u52F5\u52F8\u52F9\u5306\u5308\u7538\u530D\u5310\u530F\u5315\u531A\u5323\u532F\u5331\u5333\u5338\u5340\u5346\u5345\u4E17\u5349\u534D\u51D6\u535E\u5369\u536E\u5918\u537B\u5377\u5382\u5396\u53A0\u53A6\u53A5\u53AE\u53B0\u53B6\u53C3\u7C12\u96D9\u53DF\u66FC\u71EE\u53EE\u53E8\u53ED\u53FA\u5401\u543D\u5440\u542C\u542D\u543C\u542E\u5436\u5429\u541D\u544E\u548F\u5475\u548E\u545F\u5471\u5477\u5470\u5492\u547B\u5480\u5476\u5484\u5490\u5486\u54C7\u54A2\u54B8\u54A5\u54AC\u54C4\u54C8\u54A8"], + ["d3a1", "\u54AB\u54C2\u54A4\u54BE\u54BC\u54D8\u54E5\u54E6\u550F\u5514\u54FD\u54EE\u54ED\u54FA\u54E2\u5539\u5540\u5563\u554C\u552E\u555C\u5545\u5556\u5557\u5538\u5533\u555D\u5599\u5580\u54AF\u558A\u559F\u557B\u557E\u5598\u559E\u55AE\u557C\u5583\u55A9\u5587\u55A8\u55DA\u55C5\u55DF\u55C4\u55DC\u55E4\u55D4\u5614\u55F7\u5616\u55FE\u55FD\u561B\u55F9\u564E\u5650\u71DF\u5634\u5636\u5632\u5638\u566B\u5664\u562F\u566C\u566A\u5686\u5680\u568A\u56A0\u5694\u568F\u56A5\u56AE\u56B6\u56B4\u56C2\u56BC\u56C1\u56C3\u56C0\u56C8\u56CE\u56D1\u56D3\u56D7\u56EE\u56F9\u5700\u56FF\u5704\u5709"], + ["d4a1", "\u5708\u570B\u570D\u5713\u5718\u5716\u55C7\u571C\u5726\u5737\u5738\u574E\u573B\u5740\u574F\u5769\u57C0\u5788\u5761\u577F\u5789\u5793\u57A0\u57B3\u57A4\u57AA\u57B0\u57C3\u57C6\u57D4\u57D2\u57D3\u580A\u57D6\u57E3\u580B\u5819\u581D\u5872\u5821\u5862\u584B\u5870\u6BC0\u5852\u583D\u5879\u5885\u58B9\u589F\u58AB\u58BA\u58DE\u58BB\u58B8\u58AE\u58C5\u58D3\u58D1\u58D7\u58D9\u58D8\u58E5\u58DC\u58E4\u58DF\u58EF\u58FA\u58F9\u58FB\u58FC\u58FD\u5902\u590A\u5910\u591B\u68A6\u5925\u592C\u592D\u5932\u5938\u593E\u7AD2\u5955\u5950\u594E\u595A\u5958\u5962\u5960\u5967\u596C\u5969"], + ["d5a1", "\u5978\u5981\u599D\u4F5E\u4FAB\u59A3\u59B2\u59C6\u59E8\u59DC\u598D\u59D9\u59DA\u5A25\u5A1F\u5A11\u5A1C\u5A09\u5A1A\u5A40\u5A6C\u5A49\u5A35\u5A36\u5A62\u5A6A\u5A9A\u5ABC\u5ABE\u5ACB\u5AC2\u5ABD\u5AE3\u5AD7\u5AE6\u5AE9\u5AD6\u5AFA\u5AFB\u5B0C\u5B0B\u5B16\u5B32\u5AD0\u5B2A\u5B36\u5B3E\u5B43\u5B45\u5B40\u5B51\u5B55\u5B5A\u5B5B\u5B65\u5B69\u5B70\u5B73\u5B75\u5B78\u6588\u5B7A\u5B80\u5B83\u5BA6\u5BB8\u5BC3\u5BC7\u5BC9\u5BD4\u5BD0\u5BE4\u5BE6\u5BE2\u5BDE\u5BE5\u5BEB\u5BF0\u5BF6\u5BF3\u5C05\u5C07\u5C08\u5C0D\u5C13\u5C20\u5C22\u5C28\u5C38\u5C39\u5C41\u5C46\u5C4E\u5C53"], + ["d6a1", "\u5C50\u5C4F\u5B71\u5C6C\u5C6E\u4E62\u5C76\u5C79\u5C8C\u5C91\u5C94\u599B\u5CAB\u5CBB\u5CB6\u5CBC\u5CB7\u5CC5\u5CBE\u5CC7\u5CD9\u5CE9\u5CFD\u5CFA\u5CED\u5D8C\u5CEA\u5D0B\u5D15\u5D17\u5D5C\u5D1F\u5D1B\u5D11\u5D14\u5D22\u5D1A\u5D19\u5D18\u5D4C\u5D52\u5D4E\u5D4B\u5D6C\u5D73\u5D76\u5D87\u5D84\u5D82\u5DA2\u5D9D\u5DAC\u5DAE\u5DBD\u5D90\u5DB7\u5DBC\u5DC9\u5DCD\u5DD3\u5DD2\u5DD6\u5DDB\u5DEB\u5DF2\u5DF5\u5E0B\u5E1A\u5E19\u5E11\u5E1B\u5E36\u5E37\u5E44\u5E43\u5E40\u5E4E\u5E57\u5E54\u5E5F\u5E62\u5E64\u5E47\u5E75\u5E76\u5E7A\u9EBC\u5E7F\u5EA0\u5EC1\u5EC2\u5EC8\u5ED0\u5ECF"], + ["d7a1", "\u5ED6\u5EE3\u5EDD\u5EDA\u5EDB\u5EE2\u5EE1\u5EE8\u5EE9\u5EEC\u5EF1\u5EF3\u5EF0\u5EF4\u5EF8\u5EFE\u5F03\u5F09\u5F5D\u5F5C\u5F0B\u5F11\u5F16\u5F29\u5F2D\u5F38\u5F41\u5F48\u5F4C\u5F4E\u5F2F\u5F51\u5F56\u5F57\u5F59\u5F61\u5F6D\u5F73\u5F77\u5F83\u5F82\u5F7F\u5F8A\u5F88\u5F91\u5F87\u5F9E\u5F99\u5F98\u5FA0\u5FA8\u5FAD\u5FBC\u5FD6\u5FFB\u5FE4\u5FF8\u5FF1\u5FDD\u60B3\u5FFF\u6021\u6060\u6019\u6010\u6029\u600E\u6031\u601B\u6015\u602B\u6026\u600F\u603A\u605A\u6041\u606A\u6077\u605F\u604A\u6046\u604D\u6063\u6043\u6064\u6042\u606C\u606B\u6059\u6081\u608D\u60E7\u6083\u609A"], + ["d8a1", "\u6084\u609B\u6096\u6097\u6092\u60A7\u608B\u60E1\u60B8\u60E0\u60D3\u60B4\u5FF0\u60BD\u60C6\u60B5\u60D8\u614D\u6115\u6106\u60F6\u60F7\u6100\u60F4\u60FA\u6103\u6121\u60FB\u60F1\u610D\u610E\u6147\u613E\u6128\u6127\u614A\u613F\u613C\u612C\u6134\u613D\u6142\u6144\u6173\u6177\u6158\u6159\u615A\u616B\u6174\u616F\u6165\u6171\u615F\u615D\u6153\u6175\u6199\u6196\u6187\u61AC\u6194\u619A\u618A\u6191\u61AB\u61AE\u61CC\u61CA\u61C9\u61F7\u61C8\u61C3\u61C6\u61BA\u61CB\u7F79\u61CD\u61E6\u61E3\u61F6\u61FA\u61F4\u61FF\u61FD\u61FC\u61FE\u6200\u6208\u6209\u620D\u620C\u6214\u621B"], + ["d9a1", "\u621E\u6221\u622A\u622E\u6230\u6232\u6233\u6241\u624E\u625E\u6263\u625B\u6260\u6268\u627C\u6282\u6289\u627E\u6292\u6293\u6296\u62D4\u6283\u6294\u62D7\u62D1\u62BB\u62CF\u62FF\u62C6\u64D4\u62C8\u62DC\u62CC\u62CA\u62C2\u62C7\u629B\u62C9\u630C\u62EE\u62F1\u6327\u6302\u6308\u62EF\u62F5\u6350\u633E\u634D\u641C\u634F\u6396\u638E\u6380\u63AB\u6376\u63A3\u638F\u6389\u639F\u63B5\u636B\u6369\u63BE\u63E9\u63C0\u63C6\u63E3\u63C9\u63D2\u63F6\u63C4\u6416\u6434\u6406\u6413\u6426\u6436\u651D\u6417\u6428\u640F\u6467\u646F\u6476\u644E\u652A\u6495\u6493\u64A5\u64A9\u6488\u64BC"], + ["daa1", "\u64DA\u64D2\u64C5\u64C7\u64BB\u64D8\u64C2\u64F1\u64E7\u8209\u64E0\u64E1\u62AC\u64E3\u64EF\u652C\u64F6\u64F4\u64F2\u64FA\u6500\u64FD\u6518\u651C\u6505\u6524\u6523\u652B\u6534\u6535\u6537\u6536\u6538\u754B\u6548\u6556\u6555\u654D\u6558\u655E\u655D\u6572\u6578\u6582\u6583\u8B8A\u659B\u659F\u65AB\u65B7\u65C3\u65C6\u65C1\u65C4\u65CC\u65D2\u65DB\u65D9\u65E0\u65E1\u65F1\u6772\u660A\u6603\u65FB\u6773\u6635\u6636\u6634\u661C\u664F\u6644\u6649\u6641\u665E\u665D\u6664\u6667\u6668\u665F\u6662\u6670\u6683\u6688\u668E\u6689\u6684\u6698\u669D\u66C1\u66B9\u66C9\u66BE\u66BC"], + ["dba1", "\u66C4\u66B8\u66D6\u66DA\u66E0\u663F\u66E6\u66E9\u66F0\u66F5\u66F7\u670F\u6716\u671E\u6726\u6727\u9738\u672E\u673F\u6736\u6741\u6738\u6737\u6746\u675E\u6760\u6759\u6763\u6764\u6789\u6770\u67A9\u677C\u676A\u678C\u678B\u67A6\u67A1\u6785\u67B7\u67EF\u67B4\u67EC\u67B3\u67E9\u67B8\u67E4\u67DE\u67DD\u67E2\u67EE\u67B9\u67CE\u67C6\u67E7\u6A9C\u681E\u6846\u6829\u6840\u684D\u6832\u684E\u68B3\u682B\u6859\u6863\u6877\u687F\u689F\u688F\u68AD\u6894\u689D\u689B\u6883\u6AAE\u68B9\u6874\u68B5\u68A0\u68BA\u690F\u688D\u687E\u6901\u68CA\u6908\u68D8\u6922\u6926\u68E1\u690C\u68CD"], + ["dca1", "\u68D4\u68E7\u68D5\u6936\u6912\u6904\u68D7\u68E3\u6925\u68F9\u68E0\u68EF\u6928\u692A\u691A\u6923\u6921\u68C6\u6979\u6977\u695C\u6978\u696B\u6954\u697E\u696E\u6939\u6974\u693D\u6959\u6930\u6961\u695E\u695D\u6981\u696A\u69B2\u69AE\u69D0\u69BF\u69C1\u69D3\u69BE\u69CE\u5BE8\u69CA\u69DD\u69BB\u69C3\u69A7\u6A2E\u6991\u69A0\u699C\u6995\u69B4\u69DE\u69E8\u6A02\u6A1B\u69FF\u6B0A\u69F9\u69F2\u69E7\u6A05\u69B1\u6A1E\u69ED\u6A14\u69EB\u6A0A\u6A12\u6AC1\u6A23\u6A13\u6A44\u6A0C\u6A72\u6A36\u6A78\u6A47\u6A62\u6A59\u6A66\u6A48\u6A38\u6A22\u6A90\u6A8D\u6AA0\u6A84\u6AA2\u6AA3"], + ["dda1", "\u6A97\u8617\u6ABB\u6AC3\u6AC2\u6AB8\u6AB3\u6AAC\u6ADE\u6AD1\u6ADF\u6AAA\u6ADA\u6AEA\u6AFB\u6B05\u8616\u6AFA\u6B12\u6B16\u9B31\u6B1F\u6B38\u6B37\u76DC\u6B39\u98EE\u6B47\u6B43\u6B49\u6B50\u6B59\u6B54\u6B5B\u6B5F\u6B61\u6B78\u6B79\u6B7F\u6B80\u6B84\u6B83\u6B8D\u6B98\u6B95\u6B9E\u6BA4\u6BAA\u6BAB\u6BAF\u6BB2\u6BB1\u6BB3\u6BB7\u6BBC\u6BC6\u6BCB\u6BD3\u6BDF\u6BEC\u6BEB\u6BF3\u6BEF\u9EBE\u6C08\u6C13\u6C14\u6C1B\u6C24\u6C23\u6C5E\u6C55\u6C62\u6C6A\u6C82\u6C8D\u6C9A\u6C81\u6C9B\u6C7E\u6C68\u6C73\u6C92\u6C90\u6CC4\u6CF1\u6CD3\u6CBD\u6CD7\u6CC5\u6CDD\u6CAE\u6CB1\u6CBE"], + ["dea1", "\u6CBA\u6CDB\u6CEF\u6CD9\u6CEA\u6D1F\u884D\u6D36\u6D2B\u6D3D\u6D38\u6D19\u6D35\u6D33\u6D12\u6D0C\u6D63\u6D93\u6D64\u6D5A\u6D79\u6D59\u6D8E\u6D95\u6FE4\u6D85\u6DF9\u6E15\u6E0A\u6DB5\u6DC7\u6DE6\u6DB8\u6DC6\u6DEC\u6DDE\u6DCC\u6DE8\u6DD2\u6DC5\u6DFA\u6DD9\u6DE4\u6DD5\u6DEA\u6DEE\u6E2D\u6E6E\u6E2E\u6E19\u6E72\u6E5F\u6E3E\u6E23\u6E6B\u6E2B\u6E76\u6E4D\u6E1F\u6E43\u6E3A\u6E4E\u6E24\u6EFF\u6E1D\u6E38\u6E82\u6EAA\u6E98\u6EC9\u6EB7\u6ED3\u6EBD\u6EAF\u6EC4\u6EB2\u6ED4\u6ED5\u6E8F\u6EA5\u6EC2\u6E9F\u6F41\u6F11\u704C\u6EEC\u6EF8\u6EFE\u6F3F\u6EF2\u6F31\u6EEF\u6F32\u6ECC"], + ["dfa1", "\u6F3E\u6F13\u6EF7\u6F86\u6F7A\u6F78\u6F81\u6F80\u6F6F\u6F5B\u6FF3\u6F6D\u6F82\u6F7C\u6F58\u6F8E\u6F91\u6FC2\u6F66\u6FB3\u6FA3\u6FA1\u6FA4\u6FB9\u6FC6\u6FAA\u6FDF\u6FD5\u6FEC\u6FD4\u6FD8\u6FF1\u6FEE\u6FDB\u7009\u700B\u6FFA\u7011\u7001\u700F\u6FFE\u701B\u701A\u6F74\u701D\u7018\u701F\u7030\u703E\u7032\u7051\u7063\u7099\u7092\u70AF\u70F1\u70AC\u70B8\u70B3\u70AE\u70DF\u70CB\u70DD\u70D9\u7109\u70FD\u711C\u7119\u7165\u7155\u7188\u7166\u7162\u714C\u7156\u716C\u718F\u71FB\u7184\u7195\u71A8\u71AC\u71D7\u71B9\u71BE\u71D2\u71C9\u71D4\u71CE\u71E0\u71EC\u71E7\u71F5\u71FC"], + ["e0a1", "\u71F9\u71FF\u720D\u7210\u721B\u7228\u722D\u722C\u7230\u7232\u723B\u723C\u723F\u7240\u7246\u724B\u7258\u7274\u727E\u7282\u7281\u7287\u7292\u7296\u72A2\u72A7\u72B9\u72B2\u72C3\u72C6\u72C4\u72CE\u72D2\u72E2\u72E0\u72E1\u72F9\u72F7\u500F\u7317\u730A\u731C\u7316\u731D\u7334\u732F\u7329\u7325\u733E\u734E\u734F\u9ED8\u7357\u736A\u7368\u7370\u7378\u7375\u737B\u737A\u73C8\u73B3\u73CE\u73BB\u73C0\u73E5\u73EE\u73DE\u74A2\u7405\u746F\u7425\u73F8\u7432\u743A\u7455\u743F\u745F\u7459\u7441\u745C\u7469\u7470\u7463\u746A\u7476\u747E\u748B\u749E\u74A7\u74CA\u74CF\u74D4\u73F1"], + ["e1a1", "\u74E0\u74E3\u74E7\u74E9\u74EE\u74F2\u74F0\u74F1\u74F8\u74F7\u7504\u7503\u7505\u750C\u750E\u750D\u7515\u7513\u751E\u7526\u752C\u753C\u7544\u754D\u754A\u7549\u755B\u7546\u755A\u7569\u7564\u7567\u756B\u756D\u7578\u7576\u7586\u7587\u7574\u758A\u7589\u7582\u7594\u759A\u759D\u75A5\u75A3\u75C2\u75B3\u75C3\u75B5\u75BD\u75B8\u75BC\u75B1\u75CD\u75CA\u75D2\u75D9\u75E3\u75DE\u75FE\u75FF\u75FC\u7601\u75F0\u75FA\u75F2\u75F3\u760B\u760D\u7609\u761F\u7627\u7620\u7621\u7622\u7624\u7634\u7630\u763B\u7647\u7648\u7646\u765C\u7658\u7661\u7662\u7668\u7669\u766A\u7667\u766C\u7670"], + ["e2a1", "\u7672\u7676\u7678\u767C\u7680\u7683\u7688\u768B\u768E\u7696\u7693\u7699\u769A\u76B0\u76B4\u76B8\u76B9\u76BA\u76C2\u76CD\u76D6\u76D2\u76DE\u76E1\u76E5\u76E7\u76EA\u862F\u76FB\u7708\u7707\u7704\u7729\u7724\u771E\u7725\u7726\u771B\u7737\u7738\u7747\u775A\u7768\u776B\u775B\u7765\u777F\u777E\u7779\u778E\u778B\u7791\u77A0\u779E\u77B0\u77B6\u77B9\u77BF\u77BC\u77BD\u77BB\u77C7\u77CD\u77D7\u77DA\u77DC\u77E3\u77EE\u77FC\u780C\u7812\u7926\u7820\u792A\u7845\u788E\u7874\u7886\u787C\u789A\u788C\u78A3\u78B5\u78AA\u78AF\u78D1\u78C6\u78CB\u78D4\u78BE\u78BC\u78C5\u78CA\u78EC"], + ["e3a1", "\u78E7\u78DA\u78FD\u78F4\u7907\u7912\u7911\u7919\u792C\u792B\u7940\u7960\u7957\u795F\u795A\u7955\u7953\u797A\u797F\u798A\u799D\u79A7\u9F4B\u79AA\u79AE\u79B3\u79B9\u79BA\u79C9\u79D5\u79E7\u79EC\u79E1\u79E3\u7A08\u7A0D\u7A18\u7A19\u7A20\u7A1F\u7980\u7A31\u7A3B\u7A3E\u7A37\u7A43\u7A57\u7A49\u7A61\u7A62\u7A69\u9F9D\u7A70\u7A79\u7A7D\u7A88\u7A97\u7A95\u7A98\u7A96\u7AA9\u7AC8\u7AB0\u7AB6\u7AC5\u7AC4\u7ABF\u9083\u7AC7\u7ACA\u7ACD\u7ACF\u7AD5\u7AD3\u7AD9\u7ADA\u7ADD\u7AE1\u7AE2\u7AE6\u7AED\u7AF0\u7B02\u7B0F\u7B0A\u7B06\u7B33\u7B18\u7B19\u7B1E\u7B35\u7B28\u7B36\u7B50"], + ["e4a1", "\u7B7A\u7B04\u7B4D\u7B0B\u7B4C\u7B45\u7B75\u7B65\u7B74\u7B67\u7B70\u7B71\u7B6C\u7B6E\u7B9D\u7B98\u7B9F\u7B8D\u7B9C\u7B9A\u7B8B\u7B92\u7B8F\u7B5D\u7B99\u7BCB\u7BC1\u7BCC\u7BCF\u7BB4\u7BC6\u7BDD\u7BE9\u7C11\u7C14\u7BE6\u7BE5\u7C60\u7C00\u7C07\u7C13\u7BF3\u7BF7\u7C17\u7C0D\u7BF6\u7C23\u7C27\u7C2A\u7C1F\u7C37\u7C2B\u7C3D\u7C4C\u7C43\u7C54\u7C4F\u7C40\u7C50\u7C58\u7C5F\u7C64\u7C56\u7C65\u7C6C\u7C75\u7C83\u7C90\u7CA4\u7CAD\u7CA2\u7CAB\u7CA1\u7CA8\u7CB3\u7CB2\u7CB1\u7CAE\u7CB9\u7CBD\u7CC0\u7CC5\u7CC2\u7CD8\u7CD2\u7CDC\u7CE2\u9B3B\u7CEF\u7CF2\u7CF4\u7CF6\u7CFA\u7D06"], + ["e5a1", "\u7D02\u7D1C\u7D15\u7D0A\u7D45\u7D4B\u7D2E\u7D32\u7D3F\u7D35\u7D46\u7D73\u7D56\u7D4E\u7D72\u7D68\u7D6E\u7D4F\u7D63\u7D93\u7D89\u7D5B\u7D8F\u7D7D\u7D9B\u7DBA\u7DAE\u7DA3\u7DB5\u7DC7\u7DBD\u7DAB\u7E3D\u7DA2\u7DAF\u7DDC\u7DB8\u7D9F\u7DB0\u7DD8\u7DDD\u7DE4\u7DDE\u7DFB\u7DF2\u7DE1\u7E05\u7E0A\u7E23\u7E21\u7E12\u7E31\u7E1F\u7E09\u7E0B\u7E22\u7E46\u7E66\u7E3B\u7E35\u7E39\u7E43\u7E37\u7E32\u7E3A\u7E67\u7E5D\u7E56\u7E5E\u7E59\u7E5A\u7E79\u7E6A\u7E69\u7E7C\u7E7B\u7E83\u7DD5\u7E7D\u8FAE\u7E7F\u7E88\u7E89\u7E8C\u7E92\u7E90\u7E93\u7E94\u7E96\u7E8E\u7E9B\u7E9C\u7F38\u7F3A"], + ["e6a1", "\u7F45\u7F4C\u7F4D\u7F4E\u7F50\u7F51\u7F55\u7F54\u7F58\u7F5F\u7F60\u7F68\u7F69\u7F67\u7F78\u7F82\u7F86\u7F83\u7F88\u7F87\u7F8C\u7F94\u7F9E\u7F9D\u7F9A\u7FA3\u7FAF\u7FB2\u7FB9\u7FAE\u7FB6\u7FB8\u8B71\u7FC5\u7FC6\u7FCA\u7FD5\u7FD4\u7FE1\u7FE6\u7FE9\u7FF3\u7FF9\u98DC\u8006\u8004\u800B\u8012\u8018\u8019\u801C\u8021\u8028\u803F\u803B\u804A\u8046\u8052\u8058\u805A\u805F\u8062\u8068\u8073\u8072\u8070\u8076\u8079\u807D\u807F\u8084\u8086\u8085\u809B\u8093\u809A\u80AD\u5190\u80AC\u80DB\u80E5\u80D9\u80DD\u80C4\u80DA\u80D6\u8109\u80EF\u80F1\u811B\u8129\u8123\u812F\u814B"], + ["e7a1", "\u968B\u8146\u813E\u8153\u8151\u80FC\u8171\u816E\u8165\u8166\u8174\u8183\u8188\u818A\u8180\u8182\u81A0\u8195\u81A4\u81A3\u815F\u8193\u81A9\u81B0\u81B5\u81BE\u81B8\u81BD\u81C0\u81C2\u81BA\u81C9\u81CD\u81D1\u81D9\u81D8\u81C8\u81DA\u81DF\u81E0\u81E7\u81FA\u81FB\u81FE\u8201\u8202\u8205\u8207\u820A\u820D\u8210\u8216\u8229\u822B\u8238\u8233\u8240\u8259\u8258\u825D\u825A\u825F\u8264\u8262\u8268\u826A\u826B\u822E\u8271\u8277\u8278\u827E\u828D\u8292\u82AB\u829F\u82BB\u82AC\u82E1\u82E3\u82DF\u82D2\u82F4\u82F3\u82FA\u8393\u8303\u82FB\u82F9\u82DE\u8306\u82DC\u8309\u82D9"], + ["e8a1", "\u8335\u8334\u8316\u8332\u8331\u8340\u8339\u8350\u8345\u832F\u832B\u8317\u8318\u8385\u839A\u83AA\u839F\u83A2\u8396\u8323\u838E\u8387\u838A\u837C\u83B5\u8373\u8375\u83A0\u8389\u83A8\u83F4\u8413\u83EB\u83CE\u83FD\u8403\u83D8\u840B\u83C1\u83F7\u8407\u83E0\u83F2\u840D\u8422\u8420\u83BD\u8438\u8506\u83FB\u846D\u842A\u843C\u855A\u8484\u8477\u846B\u84AD\u846E\u8482\u8469\u8446\u842C\u846F\u8479\u8435\u84CA\u8462\u84B9\u84BF\u849F\u84D9\u84CD\u84BB\u84DA\u84D0\u84C1\u84C6\u84D6\u84A1\u8521\u84FF\u84F4\u8517\u8518\u852C\u851F\u8515\u8514\u84FC\u8540\u8563\u8558\u8548"], + ["e9a1", "\u8541\u8602\u854B\u8555\u8580\u85A4\u8588\u8591\u858A\u85A8\u856D\u8594\u859B\u85EA\u8587\u859C\u8577\u857E\u8590\u85C9\u85BA\u85CF\u85B9\u85D0\u85D5\u85DD\u85E5\u85DC\u85F9\u860A\u8613\u860B\u85FE\u85FA\u8606\u8622\u861A\u8630\u863F\u864D\u4E55\u8654\u865F\u8667\u8671\u8693\u86A3\u86A9\u86AA\u868B\u868C\u86B6\u86AF\u86C4\u86C6\u86B0\u86C9\u8823\u86AB\u86D4\u86DE\u86E9\u86EC\u86DF\u86DB\u86EF\u8712\u8706\u8708\u8700\u8703\u86FB\u8711\u8709\u870D\u86F9\u870A\u8734\u873F\u8737\u873B\u8725\u8729\u871A\u8760\u875F\u8778\u874C\u874E\u8774\u8757\u8768\u876E\u8759"], + ["eaa1", "\u8753\u8763\u876A\u8805\u87A2\u879F\u8782\u87AF\u87CB\u87BD\u87C0\u87D0\u96D6\u87AB\u87C4\u87B3\u87C7\u87C6\u87BB\u87EF\u87F2\u87E0\u880F\u880D\u87FE\u87F6\u87F7\u880E\u87D2\u8811\u8816\u8815\u8822\u8821\u8831\u8836\u8839\u8827\u883B\u8844\u8842\u8852\u8859\u885E\u8862\u886B\u8881\u887E\u889E\u8875\u887D\u88B5\u8872\u8882\u8897\u8892\u88AE\u8899\u88A2\u888D\u88A4\u88B0\u88BF\u88B1\u88C3\u88C4\u88D4\u88D8\u88D9\u88DD\u88F9\u8902\u88FC\u88F4\u88E8\u88F2\u8904\u890C\u890A\u8913\u8943\u891E\u8925\u892A\u892B\u8941\u8944\u893B\u8936\u8938\u894C\u891D\u8960\u895E"], + ["eba1", "\u8966\u8964\u896D\u896A\u896F\u8974\u8977\u897E\u8983\u8988\u898A\u8993\u8998\u89A1\u89A9\u89A6\u89AC\u89AF\u89B2\u89BA\u89BD\u89BF\u89C0\u89DA\u89DC\u89DD\u89E7\u89F4\u89F8\u8A03\u8A16\u8A10\u8A0C\u8A1B\u8A1D\u8A25\u8A36\u8A41\u8A5B\u8A52\u8A46\u8A48\u8A7C\u8A6D\u8A6C\u8A62\u8A85\u8A82\u8A84\u8AA8\u8AA1\u8A91\u8AA5\u8AA6\u8A9A\u8AA3\u8AC4\u8ACD\u8AC2\u8ADA\u8AEB\u8AF3\u8AE7\u8AE4\u8AF1\u8B14\u8AE0\u8AE2\u8AF7\u8ADE\u8ADB\u8B0C\u8B07\u8B1A\u8AE1\u8B16\u8B10\u8B17\u8B20\u8B33\u97AB\u8B26\u8B2B\u8B3E\u8B28\u8B41\u8B4C\u8B4F\u8B4E\u8B49\u8B56\u8B5B\u8B5A\u8B6B"], + ["eca1", "\u8B5F\u8B6C\u8B6F\u8B74\u8B7D\u8B80\u8B8C\u8B8E\u8B92\u8B93\u8B96\u8B99\u8B9A\u8C3A\u8C41\u8C3F\u8C48\u8C4C\u8C4E\u8C50\u8C55\u8C62\u8C6C\u8C78\u8C7A\u8C82\u8C89\u8C85\u8C8A\u8C8D\u8C8E\u8C94\u8C7C\u8C98\u621D\u8CAD\u8CAA\u8CBD\u8CB2\u8CB3\u8CAE\u8CB6\u8CC8\u8CC1\u8CE4\u8CE3\u8CDA\u8CFD\u8CFA\u8CFB\u8D04\u8D05\u8D0A\u8D07\u8D0F\u8D0D\u8D10\u9F4E\u8D13\u8CCD\u8D14\u8D16\u8D67\u8D6D\u8D71\u8D73\u8D81\u8D99\u8DC2\u8DBE\u8DBA\u8DCF\u8DDA\u8DD6\u8DCC\u8DDB\u8DCB\u8DEA\u8DEB\u8DDF\u8DE3\u8DFC\u8E08\u8E09\u8DFF\u8E1D\u8E1E\u8E10\u8E1F\u8E42\u8E35\u8E30\u8E34\u8E4A"], + ["eda1", "\u8E47\u8E49\u8E4C\u8E50\u8E48\u8E59\u8E64\u8E60\u8E2A\u8E63\u8E55\u8E76\u8E72\u8E7C\u8E81\u8E87\u8E85\u8E84\u8E8B\u8E8A\u8E93\u8E91\u8E94\u8E99\u8EAA\u8EA1\u8EAC\u8EB0\u8EC6\u8EB1\u8EBE\u8EC5\u8EC8\u8ECB\u8EDB\u8EE3\u8EFC\u8EFB\u8EEB\u8EFE\u8F0A\u8F05\u8F15\u8F12\u8F19\u8F13\u8F1C\u8F1F\u8F1B\u8F0C\u8F26\u8F33\u8F3B\u8F39\u8F45\u8F42\u8F3E\u8F4C\u8F49\u8F46\u8F4E\u8F57\u8F5C\u8F62\u8F63\u8F64\u8F9C\u8F9F\u8FA3\u8FAD\u8FAF\u8FB7\u8FDA\u8FE5\u8FE2\u8FEA\u8FEF\u9087\u8FF4\u9005\u8FF9\u8FFA\u9011\u9015\u9021\u900D\u901E\u9016\u900B\u9027\u9036\u9035\u9039\u8FF8"], + ["eea1", "\u904F\u9050\u9051\u9052\u900E\u9049\u903E\u9056\u9058\u905E\u9068\u906F\u9076\u96A8\u9072\u9082\u907D\u9081\u9080\u908A\u9089\u908F\u90A8\u90AF\u90B1\u90B5\u90E2\u90E4\u6248\u90DB\u9102\u9112\u9119\u9132\u9130\u914A\u9156\u9158\u9163\u9165\u9169\u9173\u9172\u918B\u9189\u9182\u91A2\u91AB\u91AF\u91AA\u91B5\u91B4\u91BA\u91C0\u91C1\u91C9\u91CB\u91D0\u91D6\u91DF\u91E1\u91DB\u91FC\u91F5\u91F6\u921E\u91FF\u9214\u922C\u9215\u9211\u925E\u9257\u9245\u9249\u9264\u9248\u9295\u923F\u924B\u9250\u929C\u9296\u9293\u929B\u925A\u92CF\u92B9\u92B7\u92E9\u930F\u92FA\u9344\u932E"], + ["efa1", "\u9319\u9322\u931A\u9323\u933A\u9335\u933B\u935C\u9360\u937C\u936E\u9356\u93B0\u93AC\u93AD\u9394\u93B9\u93D6\u93D7\u93E8\u93E5\u93D8\u93C3\u93DD\u93D0\u93C8\u93E4\u941A\u9414\u9413\u9403\u9407\u9410\u9436\u942B\u9435\u9421\u943A\u9441\u9452\u9444\u945B\u9460\u9462\u945E\u946A\u9229\u9470\u9475\u9477\u947D\u945A\u947C\u947E\u9481\u947F\u9582\u9587\u958A\u9594\u9596\u9598\u9599\u95A0\u95A8\u95A7\u95AD\u95BC\u95BB\u95B9\u95BE\u95CA\u6FF6\u95C3\u95CD\u95CC\u95D5\u95D4\u95D6\u95DC\u95E1\u95E5\u95E2\u9621\u9628\u962E\u962F\u9642\u964C\u964F\u964B\u9677\u965C\u965E"], + ["f0a1", "\u965D\u965F\u9666\u9672\u966C\u968D\u9698\u9695\u9697\u96AA\u96A7\u96B1\u96B2\u96B0\u96B4\u96B6\u96B8\u96B9\u96CE\u96CB\u96C9\u96CD\u894D\u96DC\u970D\u96D5\u96F9\u9704\u9706\u9708\u9713\u970E\u9711\u970F\u9716\u9719\u9724\u972A\u9730\u9739\u973D\u973E\u9744\u9746\u9748\u9742\u9749\u975C\u9760\u9764\u9766\u9768\u52D2\u976B\u9771\u9779\u9785\u977C\u9781\u977A\u9786\u978B\u978F\u9790\u979C\u97A8\u97A6\u97A3\u97B3\u97B4\u97C3\u97C6\u97C8\u97CB\u97DC\u97ED\u9F4F\u97F2\u7ADF\u97F6\u97F5\u980F\u980C\u9838\u9824\u9821\u9837\u983D\u9846\u984F\u984B\u986B\u986F\u9870"], + ["f1a1", "\u9871\u9874\u9873\u98AA\u98AF\u98B1\u98B6\u98C4\u98C3\u98C6\u98E9\u98EB\u9903\u9909\u9912\u9914\u9918\u9921\u991D\u991E\u9924\u9920\u992C\u992E\u993D\u993E\u9942\u9949\u9945\u9950\u994B\u9951\u9952\u994C\u9955\u9997\u9998\u99A5\u99AD\u99AE\u99BC\u99DF\u99DB\u99DD\u99D8\u99D1\u99ED\u99EE\u99F1\u99F2\u99FB\u99F8\u9A01\u9A0F\u9A05\u99E2\u9A19\u9A2B\u9A37\u9A45\u9A42\u9A40\u9A43\u9A3E\u9A55\u9A4D\u9A5B\u9A57\u9A5F\u9A62\u9A65\u9A64\u9A69\u9A6B\u9A6A\u9AAD\u9AB0\u9ABC\u9AC0\u9ACF\u9AD1\u9AD3\u9AD4\u9ADE\u9ADF\u9AE2\u9AE3\u9AE6\u9AEF\u9AEB\u9AEE\u9AF4\u9AF1\u9AF7"], + ["f2a1", "\u9AFB\u9B06\u9B18\u9B1A\u9B1F\u9B22\u9B23\u9B25\u9B27\u9B28\u9B29\u9B2A\u9B2E\u9B2F\u9B32\u9B44\u9B43\u9B4F\u9B4D\u9B4E\u9B51\u9B58\u9B74\u9B93\u9B83\u9B91\u9B96\u9B97\u9B9F\u9BA0\u9BA8\u9BB4\u9BC0\u9BCA\u9BB9\u9BC6\u9BCF\u9BD1\u9BD2\u9BE3\u9BE2\u9BE4\u9BD4\u9BE1\u9C3A\u9BF2\u9BF1\u9BF0\u9C15\u9C14\u9C09\u9C13\u9C0C\u9C06\u9C08\u9C12\u9C0A\u9C04\u9C2E\u9C1B\u9C25\u9C24\u9C21\u9C30\u9C47\u9C32\u9C46\u9C3E\u9C5A\u9C60\u9C67\u9C76\u9C78\u9CE7\u9CEC\u9CF0\u9D09\u9D08\u9CEB\u9D03\u9D06\u9D2A\u9D26\u9DAF\u9D23\u9D1F\u9D44\u9D15\u9D12\u9D41\u9D3F\u9D3E\u9D46\u9D48"], + ["f3a1", "\u9D5D\u9D5E\u9D64\u9D51\u9D50\u9D59\u9D72\u9D89\u9D87\u9DAB\u9D6F\u9D7A\u9D9A\u9DA4\u9DA9\u9DB2\u9DC4\u9DC1\u9DBB\u9DB8\u9DBA\u9DC6\u9DCF\u9DC2\u9DD9\u9DD3\u9DF8\u9DE6\u9DED\u9DEF\u9DFD\u9E1A\u9E1B\u9E1E\u9E75\u9E79\u9E7D\u9E81\u9E88\u9E8B\u9E8C\u9E92\u9E95\u9E91\u9E9D\u9EA5\u9EA9\u9EB8\u9EAA\u9EAD\u9761\u9ECC\u9ECE\u9ECF\u9ED0\u9ED4\u9EDC\u9EDE\u9EDD\u9EE0\u9EE5\u9EE8\u9EEF\u9EF4\u9EF6\u9EF7\u9EF9\u9EFB\u9EFC\u9EFD\u9F07\u9F08\u76B7\u9F15\u9F21\u9F2C\u9F3E\u9F4A\u9F52\u9F54\u9F63\u9F5F\u9F60\u9F61\u9F66\u9F67\u9F6C\u9F6A\u9F77\u9F72\u9F76\u9F95\u9F9C\u9FA0"], + ["f4a1", "\u582F\u69C7\u9059\u7464\u51DC\u7199"], + ["f9a1", "\u7E8A\u891C\u9348\u9288\u84DC\u4FC9\u70BB\u6631\u68C8\u92F9\u66FB\u5F45\u4E28\u4EE1\u4EFC\u4F00\u4F03\u4F39\u4F56\u4F92\u4F8A\u4F9A\u4F94\u4FCD\u5040\u5022\u4FFF\u501E\u5046\u5070\u5042\u5094\u50F4\u50D8\u514A\u5164\u519D\u51BE\u51EC\u5215\u529C\u52A6\u52C0\u52DB\u5300\u5307\u5324\u5372\u5393\u53B2\u53DD\uFA0E\u549C\u548A\u54A9\u54FF\u5586\u5759\u5765\u57AC\u57C8\u57C7\uFA0F\uFA10\u589E\u58B2\u590B\u5953\u595B\u595D\u5963\u59A4\u59BA\u5B56\u5BC0\u752F\u5BD8\u5BEC\u5C1E\u5CA6\u5CBA\u5CF5\u5D27\u5D53\uFA11\u5D42\u5D6D\u5DB8\u5DB9\u5DD0\u5F21\u5F34\u5F67\u5FB7"], + ["faa1", "\u5FDE\u605D\u6085\u608A\u60DE\u60D5\u6120\u60F2\u6111\u6137\u6130\u6198\u6213\u62A6\u63F5\u6460\u649D\u64CE\u654E\u6600\u6615\u663B\u6609\u662E\u661E\u6624\u6665\u6657\u6659\uFA12\u6673\u6699\u66A0\u66B2\u66BF\u66FA\u670E\uF929\u6766\u67BB\u6852\u67C0\u6801\u6844\u68CF\uFA13\u6968\uFA14\u6998\u69E2\u6A30\u6A6B\u6A46\u6A73\u6A7E\u6AE2\u6AE4\u6BD6\u6C3F\u6C5C\u6C86\u6C6F\u6CDA\u6D04\u6D87\u6D6F\u6D96\u6DAC\u6DCF\u6DF8\u6DF2\u6DFC\u6E39\u6E5C\u6E27\u6E3C\u6EBF\u6F88\u6FB5\u6FF5\u7005\u7007\u7028\u7085\u70AB\u710F\u7104\u715C\u7146\u7147\uFA15\u71C1\u71FE\u72B1"], + ["fba1", "\u72BE\u7324\uFA16\u7377\u73BD\u73C9\u73D6\u73E3\u73D2\u7407\u73F5\u7426\u742A\u7429\u742E\u7462\u7489\u749F\u7501\u756F\u7682\u769C\u769E\u769B\u76A6\uFA17\u7746\u52AF\u7821\u784E\u7864\u787A\u7930\uFA18\uFA19\uFA1A\u7994\uFA1B\u799B\u7AD1\u7AE7\uFA1C\u7AEB\u7B9E\uFA1D\u7D48\u7D5C\u7DB7\u7DA0\u7DD6\u7E52\u7F47\u7FA1\uFA1E\u8301\u8362\u837F\u83C7\u83F6\u8448\u84B4\u8553\u8559\u856B\uFA1F\u85B0\uFA20\uFA21\u8807\u88F5\u8A12\u8A37\u8A79\u8AA7\u8ABE\u8ADF\uFA22\u8AF6\u8B53\u8B7F\u8CF0\u8CF4\u8D12\u8D76\uFA23\u8ECF\uFA24\uFA25\u9067\u90DE\uFA26\u9115\u9127\u91DA"], + ["fca1", "\u91D7\u91DE\u91ED\u91EE\u91E4\u91E5\u9206\u9210\u920A\u923A\u9240\u923C\u924E\u9259\u9251\u9239\u9267\u92A7\u9277\u9278\u92E7\u92D7\u92D9\u92D0\uFA27\u92D5\u92E0\u92D3\u9325\u9321\u92FB\uFA28\u931E\u92FF\u931D\u9302\u9370\u9357\u93A4\u93C6\u93DE\u93F8\u9431\u9445\u9448\u9592\uF9DC\uFA29\u969D\u96AF\u9733\u973B\u9743\u974D\u974F\u9751\u9755\u9857\u9865\uFA2A\uFA2B\u9927\uFA2C\u999E\u9A4E\u9AD9\u9ADC\u9B75\u9B72\u9B8F\u9BB1\u9BBB\u9C00\u9D70\u9D6B\uFA2D\u9E19\u9ED1"], + ["fcf1", "\u2170", 9, "\uFFE2\uFFE4\uFF07\uFF02"], + ["8fa2af", "\u02D8\u02C7\xB8\u02D9\u02DD\xAF\u02DB\u02DA\uFF5E\u0384\u0385"], + ["8fa2c2", "\xA1\xA6\xBF"], + ["8fa2eb", "\xBA\xAA\xA9\xAE\u2122\xA4\u2116"], + ["8fa6e1", "\u0386\u0388\u0389\u038A\u03AA"], + ["8fa6e7", "\u038C"], + ["8fa6e9", "\u038E\u03AB"], + ["8fa6ec", "\u038F"], + ["8fa6f1", "\u03AC\u03AD\u03AE\u03AF\u03CA\u0390\u03CC\u03C2\u03CD\u03CB\u03B0\u03CE"], + ["8fa7c2", "\u0402", 10, "\u040E\u040F"], + ["8fa7f2", "\u0452", 10, "\u045E\u045F"], + ["8fa9a1", "\xC6\u0110"], + ["8fa9a4", "\u0126"], + ["8fa9a6", "\u0132"], + ["8fa9a8", "\u0141\u013F"], + ["8fa9ab", "\u014A\xD8\u0152"], + ["8fa9af", "\u0166\xDE"], + ["8fa9c1", "\xE6\u0111\xF0\u0127\u0131\u0133\u0138\u0142\u0140\u0149\u014B\xF8\u0153\xDF\u0167\xFE"], + ["8faaa1", "\xC1\xC0\xC4\xC2\u0102\u01CD\u0100\u0104\xC5\xC3\u0106\u0108\u010C\xC7\u010A\u010E\xC9\xC8\xCB\xCA\u011A\u0116\u0112\u0118"], + ["8faaba", "\u011C\u011E\u0122\u0120\u0124\xCD\xCC\xCF\xCE\u01CF\u0130\u012A\u012E\u0128\u0134\u0136\u0139\u013D\u013B\u0143\u0147\u0145\xD1\xD3\xD2\xD6\xD4\u01D1\u0150\u014C\xD5\u0154\u0158\u0156\u015A\u015C\u0160\u015E\u0164\u0162\xDA\xD9\xDC\xDB\u016C\u01D3\u0170\u016A\u0172\u016E\u0168\u01D7\u01DB\u01D9\u01D5\u0174\xDD\u0178\u0176\u0179\u017D\u017B"], + ["8faba1", "\xE1\xE0\xE4\xE2\u0103\u01CE\u0101\u0105\xE5\xE3\u0107\u0109\u010D\xE7\u010B\u010F\xE9\xE8\xEB\xEA\u011B\u0117\u0113\u0119\u01F5\u011D\u011F"], + ["8fabbd", "\u0121\u0125\xED\xEC\xEF\xEE\u01D0"], + ["8fabc5", "\u012B\u012F\u0129\u0135\u0137\u013A\u013E\u013C\u0144\u0148\u0146\xF1\xF3\xF2\xF6\xF4\u01D2\u0151\u014D\xF5\u0155\u0159\u0157\u015B\u015D\u0161\u015F\u0165\u0163\xFA\xF9\xFC\xFB\u016D\u01D4\u0171\u016B\u0173\u016F\u0169\u01D8\u01DC\u01DA\u01D6\u0175\xFD\xFF\u0177\u017A\u017E\u017C"], + ["8fb0a1", "\u4E02\u4E04\u4E05\u4E0C\u4E12\u4E1F\u4E23\u4E24\u4E28\u4E2B\u4E2E\u4E2F\u4E30\u4E35\u4E40\u4E41\u4E44\u4E47\u4E51\u4E5A\u4E5C\u4E63\u4E68\u4E69\u4E74\u4E75\u4E79\u4E7F\u4E8D\u4E96\u4E97\u4E9D\u4EAF\u4EB9\u4EC3\u4ED0\u4EDA\u4EDB\u4EE0\u4EE1\u4EE2\u4EE8\u4EEF\u4EF1\u4EF3\u4EF5\u4EFD\u4EFE\u4EFF\u4F00\u4F02\u4F03\u4F08\u4F0B\u4F0C\u4F12\u4F15\u4F16\u4F17\u4F19\u4F2E\u4F31\u4F60\u4F33\u4F35\u4F37\u4F39\u4F3B\u4F3E\u4F40\u4F42\u4F48\u4F49\u4F4B\u4F4C\u4F52\u4F54\u4F56\u4F58\u4F5F\u4F63\u4F6A\u4F6C\u4F6E\u4F71\u4F77\u4F78\u4F79\u4F7A\u4F7D\u4F7E\u4F81\u4F82\u4F84"], + ["8fb1a1", "\u4F85\u4F89\u4F8A\u4F8C\u4F8E\u4F90\u4F92\u4F93\u4F94\u4F97\u4F99\u4F9A\u4F9E\u4F9F\u4FB2\u4FB7\u4FB9\u4FBB\u4FBC\u4FBD\u4FBE\u4FC0\u4FC1\u4FC5\u4FC6\u4FC8\u4FC9\u4FCB\u4FCC\u4FCD\u4FCF\u4FD2\u4FDC\u4FE0\u4FE2\u4FF0\u4FF2\u4FFC\u4FFD\u4FFF\u5000\u5001\u5004\u5007\u500A\u500C\u500E\u5010\u5013\u5017\u5018\u501B\u501C\u501D\u501E\u5022\u5027\u502E\u5030\u5032\u5033\u5035\u5040\u5041\u5042\u5045\u5046\u504A\u504C\u504E\u5051\u5052\u5053\u5057\u5059\u505F\u5060\u5062\u5063\u5066\u5067\u506A\u506D\u5070\u5071\u503B\u5081\u5083\u5084\u5086\u508A\u508E\u508F\u5090"], + ["8fb2a1", "\u5092\u5093\u5094\u5096\u509B\u509C\u509E", 4, "\u50AA\u50AF\u50B0\u50B9\u50BA\u50BD\u50C0\u50C3\u50C4\u50C7\u50CC\u50CE\u50D0\u50D3\u50D4\u50D8\u50DC\u50DD\u50DF\u50E2\u50E4\u50E6\u50E8\u50E9\u50EF\u50F1\u50F6\u50FA\u50FE\u5103\u5106\u5107\u5108\u510B\u510C\u510D\u510E\u50F2\u5110\u5117\u5119\u511B\u511C\u511D\u511E\u5123\u5127\u5128\u512C\u512D\u512F\u5131\u5133\u5134\u5135\u5138\u5139\u5142\u514A\u514F\u5153\u5155\u5157\u5158\u515F\u5164\u5166\u517E\u5183\u5184\u518B\u518E\u5198\u519D\u51A1\u51A3\u51AD\u51B8\u51BA\u51BC\u51BE\u51BF\u51C2"], + ["8fb3a1", "\u51C8\u51CF\u51D1\u51D2\u51D3\u51D5\u51D8\u51DE\u51E2\u51E5\u51EE\u51F2\u51F3\u51F4\u51F7\u5201\u5202\u5205\u5212\u5213\u5215\u5216\u5218\u5222\u5228\u5231\u5232\u5235\u523C\u5245\u5249\u5255\u5257\u5258\u525A\u525C\u525F\u5260\u5261\u5266\u526E\u5277\u5278\u5279\u5280\u5282\u5285\u528A\u528C\u5293\u5295\u5296\u5297\u5298\u529A\u529C\u52A4\u52A5\u52A6\u52A7\u52AF\u52B0\u52B6\u52B7\u52B8\u52BA\u52BB\u52BD\u52C0\u52C4\u52C6\u52C8\u52CC\u52CF\u52D1\u52D4\u52D6\u52DB\u52DC\u52E1\u52E5\u52E8\u52E9\u52EA\u52EC\u52F0\u52F1\u52F4\u52F6\u52F7\u5300\u5303\u530A\u530B"], + ["8fb4a1", "\u530C\u5311\u5313\u5318\u531B\u531C\u531E\u531F\u5325\u5327\u5328\u5329\u532B\u532C\u532D\u5330\u5332\u5335\u533C\u533D\u533E\u5342\u534C\u534B\u5359\u535B\u5361\u5363\u5365\u536C\u536D\u5372\u5379\u537E\u5383\u5387\u5388\u538E\u5393\u5394\u5399\u539D\u53A1\u53A4\u53AA\u53AB\u53AF\u53B2\u53B4\u53B5\u53B7\u53B8\u53BA\u53BD\u53C0\u53C5\u53CF\u53D2\u53D3\u53D5\u53DA\u53DD\u53DE\u53E0\u53E6\u53E7\u53F5\u5402\u5413\u541A\u5421\u5427\u5428\u542A\u542F\u5431\u5434\u5435\u5443\u5444\u5447\u544D\u544F\u545E\u5462\u5464\u5466\u5467\u5469\u546B\u546D\u546E\u5474\u547F"], + ["8fb5a1", "\u5481\u5483\u5485\u5488\u5489\u548D\u5491\u5495\u5496\u549C\u549F\u54A1\u54A6\u54A7\u54A9\u54AA\u54AD\u54AE\u54B1\u54B7\u54B9\u54BA\u54BB\u54BF\u54C6\u54CA\u54CD\u54CE\u54E0\u54EA\u54EC\u54EF\u54F6\u54FC\u54FE\u54FF\u5500\u5501\u5505\u5508\u5509\u550C\u550D\u550E\u5515\u552A\u552B\u5532\u5535\u5536\u553B\u553C\u553D\u5541\u5547\u5549\u554A\u554D\u5550\u5551\u5558\u555A\u555B\u555E\u5560\u5561\u5564\u5566\u557F\u5581\u5582\u5586\u5588\u558E\u558F\u5591\u5592\u5593\u5594\u5597\u55A3\u55A4\u55AD\u55B2\u55BF\u55C1\u55C3\u55C6\u55C9\u55CB\u55CC\u55CE\u55D1\u55D2"], + ["8fb6a1", "\u55D3\u55D7\u55D8\u55DB\u55DE\u55E2\u55E9\u55F6\u55FF\u5605\u5608\u560A\u560D", 5, "\u5619\u562C\u5630\u5633\u5635\u5637\u5639\u563B\u563C\u563D\u563F\u5640\u5641\u5643\u5644\u5646\u5649\u564B\u564D\u564F\u5654\u565E\u5660\u5661\u5662\u5663\u5666\u5669\u566D\u566F\u5671\u5672\u5675\u5684\u5685\u5688\u568B\u568C\u5695\u5699\u569A\u569D\u569E\u569F\u56A6\u56A7\u56A8\u56A9\u56AB\u56AC\u56AD\u56B1\u56B3\u56B7\u56BE\u56C5\u56C9\u56CA\u56CB\u56CF\u56D0\u56CC\u56CD\u56D9\u56DC\u56DD\u56DF\u56E1\u56E4", 4, "\u56F1\u56EB\u56ED"], + ["8fb7a1", "\u56F6\u56F7\u5701\u5702\u5707\u570A\u570C\u5711\u5715\u571A\u571B\u571D\u5720\u5722\u5723\u5724\u5725\u5729\u572A\u572C\u572E\u572F\u5733\u5734\u573D\u573E\u573F\u5745\u5746\u574C\u574D\u5752\u5762\u5765\u5767\u5768\u576B\u576D", 4, "\u5773\u5774\u5775\u5777\u5779\u577A\u577B\u577C\u577E\u5781\u5783\u578C\u5794\u5797\u5799\u579A\u579C\u579D\u579E\u579F\u57A1\u5795\u57A7\u57A8\u57A9\u57AC\u57B8\u57BD\u57C7\u57C8\u57CC\u57CF\u57D5\u57DD\u57DE\u57E4\u57E6\u57E7\u57E9\u57ED\u57F0\u57F5\u57F6\u57F8\u57FD\u57FE\u57FF\u5803\u5804\u5808\u5809\u57E1"], + ["8fb8a1", "\u580C\u580D\u581B\u581E\u581F\u5820\u5826\u5827\u582D\u5832\u5839\u583F\u5849\u584C\u584D\u584F\u5850\u5855\u585F\u5861\u5864\u5867\u5868\u5878\u587C\u587F\u5880\u5881\u5887\u5888\u5889\u588A\u588C\u588D\u588F\u5890\u5894\u5896\u589D\u58A0\u58A1\u58A2\u58A6\u58A9\u58B1\u58B2\u58C4\u58BC\u58C2\u58C8\u58CD\u58CE\u58D0\u58D2\u58D4\u58D6\u58DA\u58DD\u58E1\u58E2\u58E9\u58F3\u5905\u5906\u590B\u590C\u5912\u5913\u5914\u8641\u591D\u5921\u5923\u5924\u5928\u592F\u5930\u5933\u5935\u5936\u593F\u5943\u5946\u5952\u5953\u5959\u595B\u595D\u595E\u595F\u5961\u5963\u596B\u596D"], + ["8fb9a1", "\u596F\u5972\u5975\u5976\u5979\u597B\u597C\u598B\u598C\u598E\u5992\u5995\u5997\u599F\u59A4\u59A7\u59AD\u59AE\u59AF\u59B0\u59B3\u59B7\u59BA\u59BC\u59C1\u59C3\u59C4\u59C8\u59CA\u59CD\u59D2\u59DD\u59DE\u59DF\u59E3\u59E4\u59E7\u59EE\u59EF\u59F1\u59F2\u59F4\u59F7\u5A00\u5A04\u5A0C\u5A0D\u5A0E\u5A12\u5A13\u5A1E\u5A23\u5A24\u5A27\u5A28\u5A2A\u5A2D\u5A30\u5A44\u5A45\u5A47\u5A48\u5A4C\u5A50\u5A55\u5A5E\u5A63\u5A65\u5A67\u5A6D\u5A77\u5A7A\u5A7B\u5A7E\u5A8B\u5A90\u5A93\u5A96\u5A99\u5A9C\u5A9E\u5A9F\u5AA0\u5AA2\u5AA7\u5AAC\u5AB1\u5AB2\u5AB3\u5AB5\u5AB8\u5ABA\u5ABB\u5ABF"], + ["8fbaa1", "\u5AC4\u5AC6\u5AC8\u5ACF\u5ADA\u5ADC\u5AE0\u5AE5\u5AEA\u5AEE\u5AF5\u5AF6\u5AFD\u5B00\u5B01\u5B08\u5B17\u5B34\u5B19\u5B1B\u5B1D\u5B21\u5B25\u5B2D\u5B38\u5B41\u5B4B\u5B4C\u5B52\u5B56\u5B5E\u5B68\u5B6E\u5B6F\u5B7C\u5B7D\u5B7E\u5B7F\u5B81\u5B84\u5B86\u5B8A\u5B8E\u5B90\u5B91\u5B93\u5B94\u5B96\u5BA8\u5BA9\u5BAC\u5BAD\u5BAF\u5BB1\u5BB2\u5BB7\u5BBA\u5BBC\u5BC0\u5BC1\u5BCD\u5BCF\u5BD6", 4, "\u5BE0\u5BEF\u5BF1\u5BF4\u5BFD\u5C0C\u5C17\u5C1E\u5C1F\u5C23\u5C26\u5C29\u5C2B\u5C2C\u5C2E\u5C30\u5C32\u5C35\u5C36\u5C59\u5C5A\u5C5C\u5C62\u5C63\u5C67\u5C68\u5C69"], + ["8fbba1", "\u5C6D\u5C70\u5C74\u5C75\u5C7A\u5C7B\u5C7C\u5C7D\u5C87\u5C88\u5C8A\u5C8F\u5C92\u5C9D\u5C9F\u5CA0\u5CA2\u5CA3\u5CA6\u5CAA\u5CB2\u5CB4\u5CB5\u5CBA\u5CC9\u5CCB\u5CD2\u5CDD\u5CD7\u5CEE\u5CF1\u5CF2\u5CF4\u5D01\u5D06\u5D0D\u5D12\u5D2B\u5D23\u5D24\u5D26\u5D27\u5D31\u5D34\u5D39\u5D3D\u5D3F\u5D42\u5D43\u5D46\u5D48\u5D55\u5D51\u5D59\u5D4A\u5D5F\u5D60\u5D61\u5D62\u5D64\u5D6A\u5D6D\u5D70\u5D79\u5D7A\u5D7E\u5D7F\u5D81\u5D83\u5D88\u5D8A\u5D92\u5D93\u5D94\u5D95\u5D99\u5D9B\u5D9F\u5DA0\u5DA7\u5DAB\u5DB0\u5DB4\u5DB8\u5DB9\u5DC3\u5DC7\u5DCB\u5DD0\u5DCE\u5DD8\u5DD9\u5DE0\u5DE4"], + ["8fbca1", "\u5DE9\u5DF8\u5DF9\u5E00\u5E07\u5E0D\u5E12\u5E14\u5E15\u5E18\u5E1F\u5E20\u5E2E\u5E28\u5E32\u5E35\u5E3E\u5E4B\u5E50\u5E49\u5E51\u5E56\u5E58\u5E5B\u5E5C\u5E5E\u5E68\u5E6A", 4, "\u5E70\u5E80\u5E8B\u5E8E\u5EA2\u5EA4\u5EA5\u5EA8\u5EAA\u5EAC\u5EB1\u5EB3\u5EBD\u5EBE\u5EBF\u5EC6\u5ECC\u5ECB\u5ECE\u5ED1\u5ED2\u5ED4\u5ED5\u5EDC\u5EDE\u5EE5\u5EEB\u5F02\u5F06\u5F07\u5F08\u5F0E\u5F19\u5F1C\u5F1D\u5F21\u5F22\u5F23\u5F24\u5F28\u5F2B\u5F2C\u5F2E\u5F30\u5F34\u5F36\u5F3B\u5F3D\u5F3F\u5F40\u5F44\u5F45\u5F47\u5F4D\u5F50\u5F54\u5F58\u5F5B\u5F60\u5F63\u5F64\u5F67"], + ["8fbda1", "\u5F6F\u5F72\u5F74\u5F75\u5F78\u5F7A\u5F7D\u5F7E\u5F89\u5F8D\u5F8F\u5F96\u5F9C\u5F9D\u5FA2\u5FA7\u5FAB\u5FA4\u5FAC\u5FAF\u5FB0\u5FB1\u5FB8\u5FC4\u5FC7\u5FC8\u5FC9\u5FCB\u5FD0", 4, "\u5FDE\u5FE1\u5FE2\u5FE8\u5FE9\u5FEA\u5FEC\u5FED\u5FEE\u5FEF\u5FF2\u5FF3\u5FF6\u5FFA\u5FFC\u6007\u600A\u600D\u6013\u6014\u6017\u6018\u601A\u601F\u6024\u602D\u6033\u6035\u6040\u6047\u6048\u6049\u604C\u6051\u6054\u6056\u6057\u605D\u6061\u6067\u6071\u607E\u607F\u6082\u6086\u6088\u608A\u608E\u6091\u6093\u6095\u6098\u609D\u609E\u60A2\u60A4\u60A5\u60A8\u60B0\u60B1\u60B7"], + ["8fbea1", "\u60BB\u60BE\u60C2\u60C4\u60C8\u60C9\u60CA\u60CB\u60CE\u60CF\u60D4\u60D5\u60D9\u60DB\u60DD\u60DE\u60E2\u60E5\u60F2\u60F5\u60F8\u60FC\u60FD\u6102\u6107\u610A\u610C\u6110", 4, "\u6116\u6117\u6119\u611C\u611E\u6122\u612A\u612B\u6130\u6131\u6135\u6136\u6137\u6139\u6141\u6145\u6146\u6149\u615E\u6160\u616C\u6172\u6178\u617B\u617C\u617F\u6180\u6181\u6183\u6184\u618B\u618D\u6192\u6193\u6197\u6198\u619C\u619D\u619F\u61A0\u61A5\u61A8\u61AA\u61AD\u61B8\u61B9\u61BC\u61C0\u61C1\u61C2\u61CE\u61CF\u61D5\u61DC\u61DD\u61DE\u61DF\u61E1\u61E2\u61E7\u61E9\u61E5"], + ["8fbfa1", "\u61EC\u61ED\u61EF\u6201\u6203\u6204\u6207\u6213\u6215\u621C\u6220\u6222\u6223\u6227\u6229\u622B\u6239\u623D\u6242\u6243\u6244\u6246\u624C\u6250\u6251\u6252\u6254\u6256\u625A\u625C\u6264\u626D\u626F\u6273\u627A\u627D\u628D\u628E\u628F\u6290\u62A6\u62A8\u62B3\u62B6\u62B7\u62BA\u62BE\u62BF\u62C4\u62CE\u62D5\u62D6\u62DA\u62EA\u62F2\u62F4\u62FC\u62FD\u6303\u6304\u630A\u630B\u630D\u6310\u6313\u6316\u6318\u6329\u632A\u632D\u6335\u6336\u6339\u633C\u6341\u6342\u6343\u6344\u6346\u634A\u634B\u634E\u6352\u6353\u6354\u6358\u635B\u6365\u6366\u636C\u636D\u6371\u6374\u6375"], + ["8fc0a1", "\u6378\u637C\u637D\u637F\u6382\u6384\u6387\u638A\u6390\u6394\u6395\u6399\u639A\u639E\u63A4\u63A6\u63AD\u63AE\u63AF\u63BD\u63C1\u63C5\u63C8\u63CE\u63D1\u63D3\u63D4\u63D5\u63DC\u63E0\u63E5\u63EA\u63EC\u63F2\u63F3\u63F5\u63F8\u63F9\u6409\u640A\u6410\u6412\u6414\u6418\u641E\u6420\u6422\u6424\u6425\u6429\u642A\u642F\u6430\u6435\u643D\u643F\u644B\u644F\u6451\u6452\u6453\u6454\u645A\u645B\u645C\u645D\u645F\u6460\u6461\u6463\u646D\u6473\u6474\u647B\u647D\u6485\u6487\u648F\u6490\u6491\u6498\u6499\u649B\u649D\u649F\u64A1\u64A3\u64A6\u64A8\u64AC\u64B3\u64BD\u64BE\u64BF"], + ["8fc1a1", "\u64C4\u64C9\u64CA\u64CB\u64CC\u64CE\u64D0\u64D1\u64D5\u64D7\u64E4\u64E5\u64E9\u64EA\u64ED\u64F0\u64F5\u64F7\u64FB\u64FF\u6501\u6504\u6508\u6509\u650A\u650F\u6513\u6514\u6516\u6519\u651B\u651E\u651F\u6522\u6526\u6529\u652E\u6531\u653A\u653C\u653D\u6543\u6547\u6549\u6550\u6552\u6554\u655F\u6560\u6567\u656B\u657A\u657D\u6581\u6585\u658A\u6592\u6595\u6598\u659D\u65A0\u65A3\u65A6\u65AE\u65B2\u65B3\u65B4\u65BF\u65C2\u65C8\u65C9\u65CE\u65D0\u65D4\u65D6\u65D8\u65DF\u65F0\u65F2\u65F4\u65F5\u65F9\u65FE\u65FF\u6600\u6604\u6608\u6609\u660D\u6611\u6612\u6615\u6616\u661D"], + ["8fc2a1", "\u661E\u6621\u6622\u6623\u6624\u6626\u6629\u662A\u662B\u662C\u662E\u6630\u6631\u6633\u6639\u6637\u6640\u6645\u6646\u664A\u664C\u6651\u664E\u6657\u6658\u6659\u665B\u665C\u6660\u6661\u66FB\u666A\u666B\u666C\u667E\u6673\u6675\u667F\u6677\u6678\u6679\u667B\u6680\u667C\u668B\u668C\u668D\u6690\u6692\u6699\u669A\u669B\u669C\u669F\u66A0\u66A4\u66AD\u66B1\u66B2\u66B5\u66BB\u66BF\u66C0\u66C2\u66C3\u66C8\u66CC\u66CE\u66CF\u66D4\u66DB\u66DF\u66E8\u66EB\u66EC\u66EE\u66FA\u6705\u6707\u670E\u6713\u6719\u671C\u6720\u6722\u6733\u673E\u6745\u6747\u6748\u674C\u6754\u6755\u675D"], + ["8fc3a1", "\u6766\u676C\u676E\u6774\u6776\u677B\u6781\u6784\u678E\u678F\u6791\u6793\u6796\u6798\u6799\u679B\u67B0\u67B1\u67B2\u67B5\u67BB\u67BC\u67BD\u67F9\u67C0\u67C2\u67C3\u67C5\u67C8\u67C9\u67D2\u67D7\u67D9\u67DC\u67E1\u67E6\u67F0\u67F2\u67F6\u67F7\u6852\u6814\u6819\u681D\u681F\u6828\u6827\u682C\u682D\u682F\u6830\u6831\u6833\u683B\u683F\u6844\u6845\u684A\u684C\u6855\u6857\u6858\u685B\u686B\u686E", 4, "\u6875\u6879\u687A\u687B\u687C\u6882\u6884\u6886\u6888\u6896\u6898\u689A\u689C\u68A1\u68A3\u68A5\u68A9\u68AA\u68AE\u68B2\u68BB\u68C5\u68C8\u68CC\u68CF"], + ["8fc4a1", "\u68D0\u68D1\u68D3\u68D6\u68D9\u68DC\u68DD\u68E5\u68E8\u68EA\u68EB\u68EC\u68ED\u68F0\u68F1\u68F5\u68F6\u68FB\u68FC\u68FD\u6906\u6909\u690A\u6910\u6911\u6913\u6916\u6917\u6931\u6933\u6935\u6938\u693B\u6942\u6945\u6949\u694E\u6957\u695B\u6963\u6964\u6965\u6966\u6968\u6969\u696C\u6970\u6971\u6972\u697A\u697B\u697F\u6980\u698D\u6992\u6996\u6998\u69A1\u69A5\u69A6\u69A8\u69AB\u69AD\u69AF\u69B7\u69B8\u69BA\u69BC\u69C5\u69C8\u69D1\u69D6\u69D7\u69E2\u69E5\u69EE\u69EF\u69F1\u69F3\u69F5\u69FE\u6A00\u6A01\u6A03\u6A0F\u6A11\u6A15\u6A1A\u6A1D\u6A20\u6A24\u6A28\u6A30\u6A32"], + ["8fc5a1", "\u6A34\u6A37\u6A3B\u6A3E\u6A3F\u6A45\u6A46\u6A49\u6A4A\u6A4E\u6A50\u6A51\u6A52\u6A55\u6A56\u6A5B\u6A64\u6A67\u6A6A\u6A71\u6A73\u6A7E\u6A81\u6A83\u6A86\u6A87\u6A89\u6A8B\u6A91\u6A9B\u6A9D\u6A9E\u6A9F\u6AA5\u6AAB\u6AAF\u6AB0\u6AB1\u6AB4\u6ABD\u6ABE\u6ABF\u6AC6\u6AC9\u6AC8\u6ACC\u6AD0\u6AD4\u6AD5\u6AD6\u6ADC\u6ADD\u6AE4\u6AE7\u6AEC\u6AF0\u6AF1\u6AF2\u6AFC\u6AFD\u6B02\u6B03\u6B06\u6B07\u6B09\u6B0F\u6B10\u6B11\u6B17\u6B1B\u6B1E\u6B24\u6B28\u6B2B\u6B2C\u6B2F\u6B35\u6B36\u6B3B\u6B3F\u6B46\u6B4A\u6B4D\u6B52\u6B56\u6B58\u6B5D\u6B60\u6B67\u6B6B\u6B6E\u6B70\u6B75\u6B7D"], + ["8fc6a1", "\u6B7E\u6B82\u6B85\u6B97\u6B9B\u6B9F\u6BA0\u6BA2\u6BA3\u6BA8\u6BA9\u6BAC\u6BAD\u6BAE\u6BB0\u6BB8\u6BB9\u6BBD\u6BBE\u6BC3\u6BC4\u6BC9\u6BCC\u6BD6\u6BDA\u6BE1\u6BE3\u6BE6\u6BE7\u6BEE\u6BF1\u6BF7\u6BF9\u6BFF\u6C02\u6C04\u6C05\u6C09\u6C0D\u6C0E\u6C10\u6C12\u6C19\u6C1F\u6C26\u6C27\u6C28\u6C2C\u6C2E\u6C33\u6C35\u6C36\u6C3A\u6C3B\u6C3F\u6C4A\u6C4B\u6C4D\u6C4F\u6C52\u6C54\u6C59\u6C5B\u6C5C\u6C6B\u6C6D\u6C6F\u6C74\u6C76\u6C78\u6C79\u6C7B\u6C85\u6C86\u6C87\u6C89\u6C94\u6C95\u6C97\u6C98\u6C9C\u6C9F\u6CB0\u6CB2\u6CB4\u6CC2\u6CC6\u6CCD\u6CCF\u6CD0\u6CD1\u6CD2\u6CD4\u6CD6"], + ["8fc7a1", "\u6CDA\u6CDC\u6CE0\u6CE7\u6CE9\u6CEB\u6CEC\u6CEE\u6CF2\u6CF4\u6D04\u6D07\u6D0A\u6D0E\u6D0F\u6D11\u6D13\u6D1A\u6D26\u6D27\u6D28\u6C67\u6D2E\u6D2F\u6D31\u6D39\u6D3C\u6D3F\u6D57\u6D5E\u6D5F\u6D61\u6D65\u6D67\u6D6F\u6D70\u6D7C\u6D82\u6D87\u6D91\u6D92\u6D94\u6D96\u6D97\u6D98\u6DAA\u6DAC\u6DB4\u6DB7\u6DB9\u6DBD\u6DBF\u6DC4\u6DC8\u6DCA\u6DCE\u6DCF\u6DD6\u6DDB\u6DDD\u6DDF\u6DE0\u6DE2\u6DE5\u6DE9\u6DEF\u6DF0\u6DF4\u6DF6\u6DFC\u6E00\u6E04\u6E1E\u6E22\u6E27\u6E32\u6E36\u6E39\u6E3B\u6E3C\u6E44\u6E45\u6E48\u6E49\u6E4B\u6E4F\u6E51\u6E52\u6E53\u6E54\u6E57\u6E5C\u6E5D\u6E5E"], + ["8fc8a1", "\u6E62\u6E63\u6E68\u6E73\u6E7B\u6E7D\u6E8D\u6E93\u6E99\u6EA0\u6EA7\u6EAD\u6EAE\u6EB1\u6EB3\u6EBB\u6EBF\u6EC0\u6EC1\u6EC3\u6EC7\u6EC8\u6ECA\u6ECD\u6ECE\u6ECF\u6EEB\u6EED\u6EEE\u6EF9\u6EFB\u6EFD\u6F04\u6F08\u6F0A\u6F0C\u6F0D\u6F16\u6F18\u6F1A\u6F1B\u6F26\u6F29\u6F2A\u6F2F\u6F30\u6F33\u6F36\u6F3B\u6F3C\u6F2D\u6F4F\u6F51\u6F52\u6F53\u6F57\u6F59\u6F5A\u6F5D\u6F5E\u6F61\u6F62\u6F68\u6F6C\u6F7D\u6F7E\u6F83\u6F87\u6F88\u6F8B\u6F8C\u6F8D\u6F90\u6F92\u6F93\u6F94\u6F96\u6F9A\u6F9F\u6FA0\u6FA5\u6FA6\u6FA7\u6FA8\u6FAE\u6FAF\u6FB0\u6FB5\u6FB6\u6FBC\u6FC5\u6FC7\u6FC8\u6FCA"], + ["8fc9a1", "\u6FDA\u6FDE\u6FE8\u6FE9\u6FF0\u6FF5\u6FF9\u6FFC\u6FFD\u7000\u7005\u7006\u7007\u700D\u7017\u7020\u7023\u702F\u7034\u7037\u7039\u703C\u7043\u7044\u7048\u7049\u704A\u704B\u7054\u7055\u705D\u705E\u704E\u7064\u7065\u706C\u706E\u7075\u7076\u707E\u7081\u7085\u7086\u7094", 4, "\u709B\u70A4\u70AB\u70B0\u70B1\u70B4\u70B7\u70CA\u70D1\u70D3\u70D4\u70D5\u70D6\u70D8\u70DC\u70E4\u70FA\u7103", 4, "\u710B\u710C\u710F\u711E\u7120\u712B\u712D\u712F\u7130\u7131\u7138\u7141\u7145\u7146\u7147\u714A\u714B\u7150\u7152\u7157\u715A\u715C\u715E\u7160"], + ["8fcaa1", "\u7168\u7179\u7180\u7185\u7187\u718C\u7192\u719A\u719B\u71A0\u71A2\u71AF\u71B0\u71B2\u71B3\u71BA\u71BF\u71C0\u71C1\u71C4\u71CB\u71CC\u71D3\u71D6\u71D9\u71DA\u71DC\u71F8\u71FE\u7200\u7207\u7208\u7209\u7213\u7217\u721A\u721D\u721F\u7224\u722B\u722F\u7234\u7238\u7239\u7241\u7242\u7243\u7245\u724E\u724F\u7250\u7253\u7255\u7256\u725A\u725C\u725E\u7260\u7263\u7268\u726B\u726E\u726F\u7271\u7277\u7278\u727B\u727C\u727F\u7284\u7289\u728D\u728E\u7293\u729B\u72A8\u72AD\u72AE\u72B1\u72B4\u72BE\u72C1\u72C7\u72C9\u72CC\u72D5\u72D6\u72D8\u72DF\u72E5\u72F3\u72F4\u72FA\u72FB"], + ["8fcba1", "\u72FE\u7302\u7304\u7305\u7307\u730B\u730D\u7312\u7313\u7318\u7319\u731E\u7322\u7324\u7327\u7328\u732C\u7331\u7332\u7335\u733A\u733B\u733D\u7343\u734D\u7350\u7352\u7356\u7358\u735D\u735E\u735F\u7360\u7366\u7367\u7369\u736B\u736C\u736E\u736F\u7371\u7377\u7379\u737C\u7380\u7381\u7383\u7385\u7386\u738E\u7390\u7393\u7395\u7397\u7398\u739C\u739E\u739F\u73A0\u73A2\u73A5\u73A6\u73AA\u73AB\u73AD\u73B5\u73B7\u73B9\u73BC\u73BD\u73BF\u73C5\u73C6\u73C9\u73CB\u73CC\u73CF\u73D2\u73D3\u73D6\u73D9\u73DD\u73E1\u73E3\u73E6\u73E7\u73E9\u73F4\u73F5\u73F7\u73F9\u73FA\u73FB\u73FD"], + ["8fcca1", "\u73FF\u7400\u7401\u7404\u7407\u740A\u7411\u741A\u741B\u7424\u7426\u7428", 9, "\u7439\u7440\u7443\u7444\u7446\u7447\u744B\u744D\u7451\u7452\u7457\u745D\u7462\u7466\u7467\u7468\u746B\u746D\u746E\u7471\u7472\u7480\u7481\u7485\u7486\u7487\u7489\u748F\u7490\u7491\u7492\u7498\u7499\u749A\u749C\u749F\u74A0\u74A1\u74A3\u74A6\u74A8\u74A9\u74AA\u74AB\u74AE\u74AF\u74B1\u74B2\u74B5\u74B9\u74BB\u74BF\u74C8\u74C9\u74CC\u74D0\u74D3\u74D8\u74DA\u74DB\u74DE\u74DF\u74E4\u74E8\u74EA\u74EB\u74EF\u74F4\u74FA\u74FB\u74FC\u74FF\u7506"], + ["8fcda1", "\u7512\u7516\u7517\u7520\u7521\u7524\u7527\u7529\u752A\u752F\u7536\u7539\u753D\u753E\u753F\u7540\u7543\u7547\u7548\u754E\u7550\u7552\u7557\u755E\u755F\u7561\u756F\u7571\u7579", 5, "\u7581\u7585\u7590\u7592\u7593\u7595\u7599\u759C\u75A2\u75A4\u75B4\u75BA\u75BF\u75C0\u75C1\u75C4\u75C6\u75CC\u75CE\u75CF\u75D7\u75DC\u75DF\u75E0\u75E1\u75E4\u75E7\u75EC\u75EE\u75EF\u75F1\u75F9\u7600\u7602\u7603\u7604\u7607\u7608\u760A\u760C\u760F\u7612\u7613\u7615\u7616\u7619\u761B\u761C\u761D\u761E\u7623\u7625\u7626\u7629\u762D\u7632\u7633\u7635\u7638\u7639"], + ["8fcea1", "\u763A\u763C\u764A\u7640\u7641\u7643\u7644\u7645\u7649\u764B\u7655\u7659\u765F\u7664\u7665\u766D\u766E\u766F\u7671\u7674\u7681\u7685\u768C\u768D\u7695\u769B\u769C\u769D\u769F\u76A0\u76A2", 6, "\u76AA\u76AD\u76BD\u76C1\u76C5\u76C9\u76CB\u76CC\u76CE\u76D4\u76D9\u76E0\u76E6\u76E8\u76EC\u76F0\u76F1\u76F6\u76F9\u76FC\u7700\u7706\u770A\u770E\u7712\u7714\u7715\u7717\u7719\u771A\u771C\u7722\u7728\u772D\u772E\u772F\u7734\u7735\u7736\u7739\u773D\u773E\u7742\u7745\u7746\u774A\u774D\u774E\u774F\u7752\u7756\u7757\u775C\u775E\u775F\u7760\u7762"], + ["8fcfa1", "\u7764\u7767\u776A\u776C\u7770\u7772\u7773\u7774\u777A\u777D\u7780\u7784\u778C\u778D\u7794\u7795\u7796\u779A\u779F\u77A2\u77A7\u77AA\u77AE\u77AF\u77B1\u77B5\u77BE\u77C3\u77C9\u77D1\u77D2\u77D5\u77D9\u77DE\u77DF\u77E0\u77E4\u77E6\u77EA\u77EC\u77F0\u77F1\u77F4\u77F8\u77FB\u7805\u7806\u7809\u780D\u780E\u7811\u781D\u7821\u7822\u7823\u782D\u782E\u7830\u7835\u7837\u7843\u7844\u7847\u7848\u784C\u784E\u7852\u785C\u785E\u7860\u7861\u7863\u7864\u7868\u786A\u786E\u787A\u787E\u788A\u788F\u7894\u7898\u78A1\u789D\u789E\u789F\u78A4\u78A8\u78AC\u78AD\u78B0\u78B1\u78B2\u78B3"], + ["8fd0a1", "\u78BB\u78BD\u78BF\u78C7\u78C8\u78C9\u78CC\u78CE\u78D2\u78D3\u78D5\u78D6\u78E4\u78DB\u78DF\u78E0\u78E1\u78E6\u78EA\u78F2\u78F3\u7900\u78F6\u78F7\u78FA\u78FB\u78FF\u7906\u790C\u7910\u791A\u791C\u791E\u791F\u7920\u7925\u7927\u7929\u792D\u7931\u7934\u7935\u793B\u793D\u793F\u7944\u7945\u7946\u794A\u794B\u794F\u7951\u7954\u7958\u795B\u795C\u7967\u7969\u796B\u7972\u7979\u797B\u797C\u797E\u798B\u798C\u7991\u7993\u7994\u7995\u7996\u7998\u799B\u799C\u79A1\u79A8\u79A9\u79AB\u79AF\u79B1\u79B4\u79B8\u79BB\u79C2\u79C4\u79C7\u79C8\u79CA\u79CF\u79D4\u79D6\u79DA\u79DD\u79DE"], + ["8fd1a1", "\u79E0\u79E2\u79E5\u79EA\u79EB\u79ED\u79F1\u79F8\u79FC\u7A02\u7A03\u7A07\u7A09\u7A0A\u7A0C\u7A11\u7A15\u7A1B\u7A1E\u7A21\u7A27\u7A2B\u7A2D\u7A2F\u7A30\u7A34\u7A35\u7A38\u7A39\u7A3A\u7A44\u7A45\u7A47\u7A48\u7A4C\u7A55\u7A56\u7A59\u7A5C\u7A5D\u7A5F\u7A60\u7A65\u7A67\u7A6A\u7A6D\u7A75\u7A78\u7A7E\u7A80\u7A82\u7A85\u7A86\u7A8A\u7A8B\u7A90\u7A91\u7A94\u7A9E\u7AA0\u7AA3\u7AAC\u7AB3\u7AB5\u7AB9\u7ABB\u7ABC\u7AC6\u7AC9\u7ACC\u7ACE\u7AD1\u7ADB\u7AE8\u7AE9\u7AEB\u7AEC\u7AF1\u7AF4\u7AFB\u7AFD\u7AFE\u7B07\u7B14\u7B1F\u7B23\u7B27\u7B29\u7B2A\u7B2B\u7B2D\u7B2E\u7B2F\u7B30"], + ["8fd2a1", "\u7B31\u7B34\u7B3D\u7B3F\u7B40\u7B41\u7B47\u7B4E\u7B55\u7B60\u7B64\u7B66\u7B69\u7B6A\u7B6D\u7B6F\u7B72\u7B73\u7B77\u7B84\u7B89\u7B8E\u7B90\u7B91\u7B96\u7B9B\u7B9E\u7BA0\u7BA5\u7BAC\u7BAF\u7BB0\u7BB2\u7BB5\u7BB6\u7BBA\u7BBB\u7BBC\u7BBD\u7BC2\u7BC5\u7BC8\u7BCA\u7BD4\u7BD6\u7BD7\u7BD9\u7BDA\u7BDB\u7BE8\u7BEA\u7BF2\u7BF4\u7BF5\u7BF8\u7BF9\u7BFA\u7BFC\u7BFE\u7C01\u7C02\u7C03\u7C04\u7C06\u7C09\u7C0B\u7C0C\u7C0E\u7C0F\u7C19\u7C1B\u7C20\u7C25\u7C26\u7C28\u7C2C\u7C31\u7C33\u7C34\u7C36\u7C39\u7C3A\u7C46\u7C4A\u7C55\u7C51\u7C52\u7C53\u7C59", 5], + ["8fd3a1", "\u7C61\u7C63\u7C67\u7C69\u7C6D\u7C6E\u7C70\u7C72\u7C79\u7C7C\u7C7D\u7C86\u7C87\u7C8F\u7C94\u7C9E\u7CA0\u7CA6\u7CB0\u7CB6\u7CB7\u7CBA\u7CBB\u7CBC\u7CBF\u7CC4\u7CC7\u7CC8\u7CC9\u7CCD\u7CCF\u7CD3\u7CD4\u7CD5\u7CD7\u7CD9\u7CDA\u7CDD\u7CE6\u7CE9\u7CEB\u7CF5\u7D03\u7D07\u7D08\u7D09\u7D0F\u7D11\u7D12\u7D13\u7D16\u7D1D\u7D1E\u7D23\u7D26\u7D2A\u7D2D\u7D31\u7D3C\u7D3D\u7D3E\u7D40\u7D41\u7D47\u7D48\u7D4D\u7D51\u7D53\u7D57\u7D59\u7D5A\u7D5C\u7D5D\u7D65\u7D67\u7D6A\u7D70\u7D78\u7D7A\u7D7B\u7D7F\u7D81\u7D82\u7D83\u7D85\u7D86\u7D88\u7D8B\u7D8C\u7D8D\u7D91\u7D96\u7D97\u7D9D"], + ["8fd4a1", "\u7D9E\u7DA6\u7DA7\u7DAA\u7DB3\u7DB6\u7DB7\u7DB9\u7DC2", 4, "\u7DCC\u7DCD\u7DCE\u7DD7\u7DD9\u7E00\u7DE2\u7DE5\u7DE6\u7DEA\u7DEB\u7DED\u7DF1\u7DF5\u7DF6\u7DF9\u7DFA\u7E08\u7E10\u7E11\u7E15\u7E17\u7E1C\u7E1D\u7E20\u7E27\u7E28\u7E2C\u7E2D\u7E2F\u7E33\u7E36\u7E3F\u7E44\u7E45\u7E47\u7E4E\u7E50\u7E52\u7E58\u7E5F\u7E61\u7E62\u7E65\u7E6B\u7E6E\u7E6F\u7E73\u7E78\u7E7E\u7E81\u7E86\u7E87\u7E8A\u7E8D\u7E91\u7E95\u7E98\u7E9A\u7E9D\u7E9E\u7F3C\u7F3B\u7F3D\u7F3E\u7F3F\u7F43\u7F44\u7F47\u7F4F\u7F52\u7F53\u7F5B\u7F5C\u7F5D\u7F61\u7F63\u7F64\u7F65\u7F66\u7F6D"], + ["8fd5a1", "\u7F71\u7F7D\u7F7E\u7F7F\u7F80\u7F8B\u7F8D\u7F8F\u7F90\u7F91\u7F96\u7F97\u7F9C\u7FA1\u7FA2\u7FA6\u7FAA\u7FAD\u7FB4\u7FBC\u7FBF\u7FC0\u7FC3\u7FC8\u7FCE\u7FCF\u7FDB\u7FDF\u7FE3\u7FE5\u7FE8\u7FEC\u7FEE\u7FEF\u7FF2\u7FFA\u7FFD\u7FFE\u7FFF\u8007\u8008\u800A\u800D\u800E\u800F\u8011\u8013\u8014\u8016\u801D\u801E\u801F\u8020\u8024\u8026\u802C\u802E\u8030\u8034\u8035\u8037\u8039\u803A\u803C\u803E\u8040\u8044\u8060\u8064\u8066\u806D\u8071\u8075\u8081\u8088\u808E\u809C\u809E\u80A6\u80A7\u80AB\u80B8\u80B9\u80C8\u80CD\u80CF\u80D2\u80D4\u80D5\u80D7\u80D8\u80E0\u80ED\u80EE"], + ["8fd6a1", "\u80F0\u80F2\u80F3\u80F6\u80F9\u80FA\u80FE\u8103\u810B\u8116\u8117\u8118\u811C\u811E\u8120\u8124\u8127\u812C\u8130\u8135\u813A\u813C\u8145\u8147\u814A\u814C\u8152\u8157\u8160\u8161\u8167\u8168\u8169\u816D\u816F\u8177\u8181\u8190\u8184\u8185\u8186\u818B\u818E\u8196\u8198\u819B\u819E\u81A2\u81AE\u81B2\u81B4\u81BB\u81CB\u81C3\u81C5\u81CA\u81CE\u81CF\u81D5\u81D7\u81DB\u81DD\u81DE\u81E1\u81E4\u81EB\u81EC\u81F0\u81F1\u81F2\u81F5\u81F6\u81F8\u81F9\u81FD\u81FF\u8200\u8203\u820F\u8213\u8214\u8219\u821A\u821D\u8221\u8222\u8228\u8232\u8234\u823A\u8243\u8244\u8245\u8246"], + ["8fd7a1", "\u824B\u824E\u824F\u8251\u8256\u825C\u8260\u8263\u8267\u826D\u8274\u827B\u827D\u827F\u8280\u8281\u8283\u8284\u8287\u8289\u828A\u828E\u8291\u8294\u8296\u8298\u829A\u829B\u82A0\u82A1\u82A3\u82A4\u82A7\u82A8\u82A9\u82AA\u82AE\u82B0\u82B2\u82B4\u82B7\u82BA\u82BC\u82BE\u82BF\u82C6\u82D0\u82D5\u82DA\u82E0\u82E2\u82E4\u82E8\u82EA\u82ED\u82EF\u82F6\u82F7\u82FD\u82FE\u8300\u8301\u8307\u8308\u830A\u830B\u8354\u831B\u831D\u831E\u831F\u8321\u8322\u832C\u832D\u832E\u8330\u8333\u8337\u833A\u833C\u833D\u8342\u8343\u8344\u8347\u834D\u834E\u8351\u8355\u8356\u8357\u8370\u8378"], + ["8fd8a1", "\u837D\u837F\u8380\u8382\u8384\u8386\u838D\u8392\u8394\u8395\u8398\u8399\u839B\u839C\u839D\u83A6\u83A7\u83A9\u83AC\u83BE\u83BF\u83C0\u83C7\u83C9\u83CF\u83D0\u83D1\u83D4\u83DD\u8353\u83E8\u83EA\u83F6\u83F8\u83F9\u83FC\u8401\u8406\u840A\u840F\u8411\u8415\u8419\u83AD\u842F\u8439\u8445\u8447\u8448\u844A\u844D\u844F\u8451\u8452\u8456\u8458\u8459\u845A\u845C\u8460\u8464\u8465\u8467\u846A\u8470\u8473\u8474\u8476\u8478\u847C\u847D\u8481\u8485\u8492\u8493\u8495\u849E\u84A6\u84A8\u84A9\u84AA\u84AF\u84B1\u84B4\u84BA\u84BD\u84BE\u84C0\u84C2\u84C7\u84C8\u84CC\u84CF\u84D3"], + ["8fd9a1", "\u84DC\u84E7\u84EA\u84EF\u84F0\u84F1\u84F2\u84F7\u8532\u84FA\u84FB\u84FD\u8502\u8503\u8507\u850C\u850E\u8510\u851C\u851E\u8522\u8523\u8524\u8525\u8527\u852A\u852B\u852F\u8533\u8534\u8536\u853F\u8546\u854F", 4, "\u8556\u8559\u855C", 6, "\u8564\u856B\u856F\u8579\u857A\u857B\u857D\u857F\u8581\u8585\u8586\u8589\u858B\u858C\u858F\u8593\u8598\u859D\u859F\u85A0\u85A2\u85A5\u85A7\u85B4\u85B6\u85B7\u85B8\u85BC\u85BD\u85BE\u85BF\u85C2\u85C7\u85CA\u85CB\u85CE\u85AD\u85D8\u85DA\u85DF\u85E0\u85E6\u85E8\u85ED\u85F3\u85F6\u85FC"], + ["8fdaa1", "\u85FF\u8600\u8604\u8605\u860D\u860E\u8610\u8611\u8612\u8618\u8619\u861B\u861E\u8621\u8627\u8629\u8636\u8638\u863A\u863C\u863D\u8640\u8642\u8646\u8652\u8653\u8656\u8657\u8658\u8659\u865D\u8660", 4, "\u8669\u866C\u866F\u8675\u8676\u8677\u867A\u868D\u8691\u8696\u8698\u869A\u869C\u86A1\u86A6\u86A7\u86A8\u86AD\u86B1\u86B3\u86B4\u86B5\u86B7\u86B8\u86B9\u86BF\u86C0\u86C1\u86C3\u86C5\u86D1\u86D2\u86D5\u86D7\u86DA\u86DC\u86E0\u86E3\u86E5\u86E7\u8688\u86FA\u86FC\u86FD\u8704\u8705\u8707\u870B\u870E\u870F\u8710\u8713\u8714\u8719\u871E\u871F\u8721\u8723"], + ["8fdba1", "\u8728\u872E\u872F\u8731\u8732\u8739\u873A\u873C\u873D\u873E\u8740\u8743\u8745\u874D\u8758\u875D\u8761\u8764\u8765\u876F\u8771\u8772\u877B\u8783", 6, "\u878B\u878C\u8790\u8793\u8795\u8797\u8798\u8799\u879E\u87A0\u87A3\u87A7\u87AC\u87AD\u87AE\u87B1\u87B5\u87BE\u87BF\u87C1\u87C8\u87C9\u87CA\u87CE\u87D5\u87D6\u87D9\u87DA\u87DC\u87DF\u87E2\u87E3\u87E4\u87EA\u87EB\u87ED\u87F1\u87F3\u87F8\u87FA\u87FF\u8801\u8803\u8806\u8809\u880A\u880B\u8810\u8819\u8812\u8813\u8814\u8818\u881A\u881B\u881C\u881E\u881F\u8828\u882D\u882E\u8830\u8832\u8835"], + ["8fdca1", "\u883A\u883C\u8841\u8843\u8845\u8848\u8849\u884A\u884B\u884E\u8851\u8855\u8856\u8858\u885A\u885C\u885F\u8860\u8864\u8869\u8871\u8879\u887B\u8880\u8898\u889A\u889B\u889C\u889F\u88A0\u88A8\u88AA\u88BA\u88BD\u88BE\u88C0\u88CA", 4, "\u88D1\u88D2\u88D3\u88DB\u88DE\u88E7\u88EF\u88F0\u88F1\u88F5\u88F7\u8901\u8906\u890D\u890E\u890F\u8915\u8916\u8918\u8919\u891A\u891C\u8920\u8926\u8927\u8928\u8930\u8931\u8932\u8935\u8939\u893A\u893E\u8940\u8942\u8945\u8946\u8949\u894F\u8952\u8957\u895A\u895B\u895C\u8961\u8962\u8963\u896B\u896E\u8970\u8973\u8975\u897A"], + ["8fdda1", "\u897B\u897C\u897D\u8989\u898D\u8990\u8994\u8995\u899B\u899C\u899F\u89A0\u89A5\u89B0\u89B4\u89B5\u89B6\u89B7\u89BC\u89D4", 4, "\u89E5\u89E9\u89EB\u89ED\u89F1\u89F3\u89F6\u89F9\u89FD\u89FF\u8A04\u8A05\u8A07\u8A0F\u8A11\u8A12\u8A14\u8A15\u8A1E\u8A20\u8A22\u8A24\u8A26\u8A2B\u8A2C\u8A2F\u8A35\u8A37\u8A3D\u8A3E\u8A40\u8A43\u8A45\u8A47\u8A49\u8A4D\u8A4E\u8A53\u8A56\u8A57\u8A58\u8A5C\u8A5D\u8A61\u8A65\u8A67\u8A75\u8A76\u8A77\u8A79\u8A7A\u8A7B\u8A7E\u8A7F\u8A80\u8A83\u8A86\u8A8B\u8A8F\u8A90\u8A92\u8A96\u8A97\u8A99\u8A9F\u8AA7\u8AA9\u8AAE\u8AAF\u8AB3"], + ["8fdea1", "\u8AB6\u8AB7\u8ABB\u8ABE\u8AC3\u8AC6\u8AC8\u8AC9\u8ACA\u8AD1\u8AD3\u8AD4\u8AD5\u8AD7\u8ADD\u8ADF\u8AEC\u8AF0\u8AF4\u8AF5\u8AF6\u8AFC\u8AFF\u8B05\u8B06\u8B0B\u8B11\u8B1C\u8B1E\u8B1F\u8B0A\u8B2D\u8B30\u8B37\u8B3C\u8B42", 4, "\u8B48\u8B52\u8B53\u8B54\u8B59\u8B4D\u8B5E\u8B63\u8B6D\u8B76\u8B78\u8B79\u8B7C\u8B7E\u8B81\u8B84\u8B85\u8B8B\u8B8D\u8B8F\u8B94\u8B95\u8B9C\u8B9E\u8B9F\u8C38\u8C39\u8C3D\u8C3E\u8C45\u8C47\u8C49\u8C4B\u8C4F\u8C51\u8C53\u8C54\u8C57\u8C58\u8C5B\u8C5D\u8C59\u8C63\u8C64\u8C66\u8C68\u8C69\u8C6D\u8C73\u8C75\u8C76\u8C7B\u8C7E\u8C86"], + ["8fdfa1", "\u8C87\u8C8B\u8C90\u8C92\u8C93\u8C99\u8C9B\u8C9C\u8CA4\u8CB9\u8CBA\u8CC5\u8CC6\u8CC9\u8CCB\u8CCF\u8CD6\u8CD5\u8CD9\u8CDD\u8CE1\u8CE8\u8CEC\u8CEF\u8CF0\u8CF2\u8CF5\u8CF7\u8CF8\u8CFE\u8CFF\u8D01\u8D03\u8D09\u8D12\u8D17\u8D1B\u8D65\u8D69\u8D6C\u8D6E\u8D7F\u8D82\u8D84\u8D88\u8D8D\u8D90\u8D91\u8D95\u8D9E\u8D9F\u8DA0\u8DA6\u8DAB\u8DAC\u8DAF\u8DB2\u8DB5\u8DB7\u8DB9\u8DBB\u8DC0\u8DC5\u8DC6\u8DC7\u8DC8\u8DCA\u8DCE\u8DD1\u8DD4\u8DD5\u8DD7\u8DD9\u8DE4\u8DE5\u8DE7\u8DEC\u8DF0\u8DBC\u8DF1\u8DF2\u8DF4\u8DFD\u8E01\u8E04\u8E05\u8E06\u8E0B\u8E11\u8E14\u8E16\u8E20\u8E21\u8E22"], + ["8fe0a1", "\u8E23\u8E26\u8E27\u8E31\u8E33\u8E36\u8E37\u8E38\u8E39\u8E3D\u8E40\u8E41\u8E4B\u8E4D\u8E4E\u8E4F\u8E54\u8E5B\u8E5C\u8E5D\u8E5E\u8E61\u8E62\u8E69\u8E6C\u8E6D\u8E6F\u8E70\u8E71\u8E79\u8E7A\u8E7B\u8E82\u8E83\u8E89\u8E90\u8E92\u8E95\u8E9A\u8E9B\u8E9D\u8E9E\u8EA2\u8EA7\u8EA9\u8EAD\u8EAE\u8EB3\u8EB5\u8EBA\u8EBB\u8EC0\u8EC1\u8EC3\u8EC4\u8EC7\u8ECF\u8ED1\u8ED4\u8EDC\u8EE8\u8EEE\u8EF0\u8EF1\u8EF7\u8EF9\u8EFA\u8EED\u8F00\u8F02\u8F07\u8F08\u8F0F\u8F10\u8F16\u8F17\u8F18\u8F1E\u8F20\u8F21\u8F23\u8F25\u8F27\u8F28\u8F2C\u8F2D\u8F2E\u8F34\u8F35\u8F36\u8F37\u8F3A\u8F40\u8F41"], + ["8fe1a1", "\u8F43\u8F47\u8F4F\u8F51", 4, "\u8F58\u8F5D\u8F5E\u8F65\u8F9D\u8FA0\u8FA1\u8FA4\u8FA5\u8FA6\u8FB5\u8FB6\u8FB8\u8FBE\u8FC0\u8FC1\u8FC6\u8FCA\u8FCB\u8FCD\u8FD0\u8FD2\u8FD3\u8FD5\u8FE0\u8FE3\u8FE4\u8FE8\u8FEE\u8FF1\u8FF5\u8FF6\u8FFB\u8FFE\u9002\u9004\u9008\u900C\u9018\u901B\u9028\u9029\u902F\u902A\u902C\u902D\u9033\u9034\u9037\u903F\u9043\u9044\u904C\u905B\u905D\u9062\u9066\u9067\u906C\u9070\u9074\u9079\u9085\u9088\u908B\u908C\u908E\u9090\u9095\u9097\u9098\u9099\u909B\u90A0\u90A1\u90A2\u90A5\u90B0\u90B2\u90B3\u90B4\u90B6\u90BD\u90CC\u90BE\u90C3"], + ["8fe2a1", "\u90C4\u90C5\u90C7\u90C8\u90D5\u90D7\u90D8\u90D9\u90DC\u90DD\u90DF\u90E5\u90D2\u90F6\u90EB\u90EF\u90F0\u90F4\u90FE\u90FF\u9100\u9104\u9105\u9106\u9108\u910D\u9110\u9114\u9116\u9117\u9118\u911A\u911C\u911E\u9120\u9125\u9122\u9123\u9127\u9129\u912E\u912F\u9131\u9134\u9136\u9137\u9139\u913A\u913C\u913D\u9143\u9147\u9148\u914F\u9153\u9157\u9159\u915A\u915B\u9161\u9164\u9167\u916D\u9174\u9179\u917A\u917B\u9181\u9183\u9185\u9186\u918A\u918E\u9191\u9193\u9194\u9195\u9198\u919E\u91A1\u91A6\u91A8\u91AC\u91AD\u91AE\u91B0\u91B1\u91B2\u91B3\u91B6\u91BB\u91BC\u91BD\u91BF"], + ["8fe3a1", "\u91C2\u91C3\u91C5\u91D3\u91D4\u91D7\u91D9\u91DA\u91DE\u91E4\u91E5\u91E9\u91EA\u91EC", 5, "\u91F7\u91F9\u91FB\u91FD\u9200\u9201\u9204\u9205\u9206\u9207\u9209\u920A\u920C\u9210\u9212\u9213\u9216\u9218\u921C\u921D\u9223\u9224\u9225\u9226\u9228\u922E\u922F\u9230\u9233\u9235\u9236\u9238\u9239\u923A\u923C\u923E\u9240\u9242\u9243\u9246\u9247\u924A\u924D\u924E\u924F\u9251\u9258\u9259\u925C\u925D\u9260\u9261\u9265\u9267\u9268\u9269\u926E\u926F\u9270\u9275", 4, "\u927B\u927C\u927D\u927F\u9288\u9289\u928A\u928D\u928E\u9292\u9297"], + ["8fe4a1", "\u9299\u929F\u92A0\u92A4\u92A5\u92A7\u92A8\u92AB\u92AF\u92B2\u92B6\u92B8\u92BA\u92BB\u92BC\u92BD\u92BF", 4, "\u92C5\u92C6\u92C7\u92C8\u92CB\u92CC\u92CD\u92CE\u92D0\u92D3\u92D5\u92D7\u92D8\u92D9\u92DC\u92DD\u92DF\u92E0\u92E1\u92E3\u92E5\u92E7\u92E8\u92EC\u92EE\u92F0\u92F9\u92FB\u92FF\u9300\u9302\u9308\u930D\u9311\u9314\u9315\u931C\u931D\u931E\u931F\u9321\u9324\u9325\u9327\u9329\u932A\u9333\u9334\u9336\u9337\u9347\u9348\u9349\u9350\u9351\u9352\u9355\u9357\u9358\u935A\u935E\u9364\u9365\u9367\u9369\u936A\u936D\u936F\u9370\u9371\u9373\u9374\u9376"], + ["8fe5a1", "\u937A\u937D\u937F\u9380\u9381\u9382\u9388\u938A\u938B\u938D\u938F\u9392\u9395\u9398\u939B\u939E\u93A1\u93A3\u93A4\u93A6\u93A8\u93AB\u93B4\u93B5\u93B6\u93BA\u93A9\u93C1\u93C4\u93C5\u93C6\u93C7\u93C9", 4, "\u93D3\u93D9\u93DC\u93DE\u93DF\u93E2\u93E6\u93E7\u93F9\u93F7\u93F8\u93FA\u93FB\u93FD\u9401\u9402\u9404\u9408\u9409\u940D\u940E\u940F\u9415\u9416\u9417\u941F\u942E\u942F\u9431\u9432\u9433\u9434\u943B\u943F\u943D\u9443\u9445\u9448\u944A\u944C\u9455\u9459\u945C\u945F\u9461\u9463\u9468\u946B\u946D\u946E\u946F\u9471\u9472\u9484\u9483\u9578\u9579"], + ["8fe6a1", "\u957E\u9584\u9588\u958C\u958D\u958E\u959D\u959E\u959F\u95A1\u95A6\u95A9\u95AB\u95AC\u95B4\u95B6\u95BA\u95BD\u95BF\u95C6\u95C8\u95C9\u95CB\u95D0\u95D1\u95D2\u95D3\u95D9\u95DA\u95DD\u95DE\u95DF\u95E0\u95E4\u95E6\u961D\u961E\u9622\u9624\u9625\u9626\u962C\u9631\u9633\u9637\u9638\u9639\u963A\u963C\u963D\u9641\u9652\u9654\u9656\u9657\u9658\u9661\u966E\u9674\u967B\u967C\u967E\u967F\u9681\u9682\u9683\u9684\u9689\u9691\u9696\u969A\u969D\u969F\u96A4\u96A5\u96A6\u96A9\u96AE\u96AF\u96B3\u96BA\u96CA\u96D2\u5DB2\u96D8\u96DA\u96DD\u96DE\u96DF\u96E9\u96EF\u96F1\u96FA\u9702"], + ["8fe7a1", "\u9703\u9705\u9709\u971A\u971B\u971D\u9721\u9722\u9723\u9728\u9731\u9733\u9741\u9743\u974A\u974E\u974F\u9755\u9757\u9758\u975A\u975B\u9763\u9767\u976A\u976E\u9773\u9776\u9777\u9778\u977B\u977D\u977F\u9780\u9789\u9795\u9796\u9797\u9799\u979A\u979E\u979F\u97A2\u97AC\u97AE\u97B1\u97B2\u97B5\u97B6\u97B8\u97B9\u97BA\u97BC\u97BE\u97BF\u97C1\u97C4\u97C5\u97C7\u97C9\u97CA\u97CC\u97CD\u97CE\u97D0\u97D1\u97D4\u97D7\u97D8\u97D9\u97DD\u97DE\u97E0\u97DB\u97E1\u97E4\u97EF\u97F1\u97F4\u97F7\u97F8\u97FA\u9807\u980A\u9819\u980D\u980E\u9814\u9816\u981C\u981E\u9820\u9823\u9826"], + ["8fe8a1", "\u982B\u982E\u982F\u9830\u9832\u9833\u9835\u9825\u983E\u9844\u9847\u984A\u9851\u9852\u9853\u9856\u9857\u9859\u985A\u9862\u9863\u9865\u9866\u986A\u986C\u98AB\u98AD\u98AE\u98B0\u98B4\u98B7\u98B8\u98BA\u98BB\u98BF\u98C2\u98C5\u98C8\u98CC\u98E1\u98E3\u98E5\u98E6\u98E7\u98EA\u98F3\u98F6\u9902\u9907\u9908\u9911\u9915\u9916\u9917\u991A\u991B\u991C\u991F\u9922\u9926\u9927\u992B\u9931", 4, "\u9939\u993A\u993B\u993C\u9940\u9941\u9946\u9947\u9948\u994D\u994E\u9954\u9958\u9959\u995B\u995C\u995E\u995F\u9960\u999B\u999D\u999F\u99A6\u99B0\u99B1\u99B2\u99B5"], + ["8fe9a1", "\u99B9\u99BA\u99BD\u99BF\u99C3\u99C9\u99D3\u99D4\u99D9\u99DA\u99DC\u99DE\u99E7\u99EA\u99EB\u99EC\u99F0\u99F4\u99F5\u99F9\u99FD\u99FE\u9A02\u9A03\u9A04\u9A0B\u9A0C\u9A10\u9A11\u9A16\u9A1E\u9A20\u9A22\u9A23\u9A24\u9A27\u9A2D\u9A2E\u9A33\u9A35\u9A36\u9A38\u9A47\u9A41\u9A44\u9A4A\u9A4B\u9A4C\u9A4E\u9A51\u9A54\u9A56\u9A5D\u9AAA\u9AAC\u9AAE\u9AAF\u9AB2\u9AB4\u9AB5\u9AB6\u9AB9\u9ABB\u9ABE\u9ABF\u9AC1\u9AC3\u9AC6\u9AC8\u9ACE\u9AD0\u9AD2\u9AD5\u9AD6\u9AD7\u9ADB\u9ADC\u9AE0\u9AE4\u9AE5\u9AE7\u9AE9\u9AEC\u9AF2\u9AF3\u9AF5\u9AF9\u9AFA\u9AFD\u9AFF", 4], + ["8feaa1", "\u9B04\u9B05\u9B08\u9B09\u9B0B\u9B0C\u9B0D\u9B0E\u9B10\u9B12\u9B16\u9B19\u9B1B\u9B1C\u9B20\u9B26\u9B2B\u9B2D\u9B33\u9B34\u9B35\u9B37\u9B39\u9B3A\u9B3D\u9B48\u9B4B\u9B4C\u9B55\u9B56\u9B57\u9B5B\u9B5E\u9B61\u9B63\u9B65\u9B66\u9B68\u9B6A", 4, "\u9B73\u9B75\u9B77\u9B78\u9B79\u9B7F\u9B80\u9B84\u9B85\u9B86\u9B87\u9B89\u9B8A\u9B8B\u9B8D\u9B8F\u9B90\u9B94\u9B9A\u9B9D\u9B9E\u9BA6\u9BA7\u9BA9\u9BAC\u9BB0\u9BB1\u9BB2\u9BB7\u9BB8\u9BBB\u9BBC\u9BBE\u9BBF\u9BC1\u9BC7\u9BC8\u9BCE\u9BD0\u9BD7\u9BD8\u9BDD\u9BDF\u9BE5\u9BE7\u9BEA\u9BEB\u9BEF\u9BF3\u9BF7\u9BF8"], + ["8feba1", "\u9BF9\u9BFA\u9BFD\u9BFF\u9C00\u9C02\u9C0B\u9C0F\u9C11\u9C16\u9C18\u9C19\u9C1A\u9C1C\u9C1E\u9C22\u9C23\u9C26", 4, "\u9C31\u9C35\u9C36\u9C37\u9C3D\u9C41\u9C43\u9C44\u9C45\u9C49\u9C4A\u9C4E\u9C4F\u9C50\u9C53\u9C54\u9C56\u9C58\u9C5B\u9C5D\u9C5E\u9C5F\u9C63\u9C69\u9C6A\u9C5C\u9C6B\u9C68\u9C6E\u9C70\u9C72\u9C75\u9C77\u9C7B\u9CE6\u9CF2\u9CF7\u9CF9\u9D0B\u9D02\u9D11\u9D17\u9D18\u9D1C\u9D1D\u9D1E\u9D2F\u9D30\u9D32\u9D33\u9D34\u9D3A\u9D3C\u9D45\u9D3D\u9D42\u9D43\u9D47\u9D4A\u9D53\u9D54\u9D5F\u9D63\u9D62\u9D65\u9D69\u9D6A\u9D6B\u9D70\u9D76\u9D77\u9D7B"], + ["8feca1", "\u9D7C\u9D7E\u9D83\u9D84\u9D86\u9D8A\u9D8D\u9D8E\u9D92\u9D93\u9D95\u9D96\u9D97\u9D98\u9DA1\u9DAA\u9DAC\u9DAE\u9DB1\u9DB5\u9DB9\u9DBC\u9DBF\u9DC3\u9DC7\u9DC9\u9DCA\u9DD4\u9DD5\u9DD6\u9DD7\u9DDA\u9DDE\u9DDF\u9DE0\u9DE5\u9DE7\u9DE9\u9DEB\u9DEE\u9DF0\u9DF3\u9DF4\u9DFE\u9E0A\u9E02\u9E07\u9E0E\u9E10\u9E11\u9E12\u9E15\u9E16\u9E19\u9E1C\u9E1D\u9E7A\u9E7B\u9E7C\u9E80\u9E82\u9E83\u9E84\u9E85\u9E87\u9E8E\u9E8F\u9E96\u9E98\u9E9B\u9E9E\u9EA4\u9EA8\u9EAC\u9EAE\u9EAF\u9EB0\u9EB3\u9EB4\u9EB5\u9EC6\u9EC8\u9ECB\u9ED5\u9EDF\u9EE4\u9EE7\u9EEC\u9EED\u9EEE\u9EF0\u9EF1\u9EF2\u9EF5"], + ["8feda1", "\u9EF8\u9EFF\u9F02\u9F03\u9F09\u9F0F\u9F10\u9F11\u9F12\u9F14\u9F16\u9F17\u9F19\u9F1A\u9F1B\u9F1F\u9F22\u9F26\u9F2A\u9F2B\u9F2F\u9F31\u9F32\u9F34\u9F37\u9F39\u9F3A\u9F3C\u9F3D\u9F3F\u9F41\u9F43", 4, "\u9F53\u9F55\u9F56\u9F57\u9F58\u9F5A\u9F5D\u9F5E\u9F68\u9F69\u9F6D", 4, "\u9F73\u9F75\u9F7A\u9F7D\u9F8F\u9F90\u9F91\u9F92\u9F94\u9F96\u9F97\u9F9E\u9FA1\u9FA2\u9FA3\u9FA5"] + ]; + } +}); + +// node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/encodings/tables/cp936.json +var require_cp936 = __commonJS({ + "node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/encodings/tables/cp936.json"(exports, module) { + module.exports = [ + ["0", "\0", 127, "\u20AC"], + ["8140", "\u4E02\u4E04\u4E05\u4E06\u4E0F\u4E12\u4E17\u4E1F\u4E20\u4E21\u4E23\u4E26\u4E29\u4E2E\u4E2F\u4E31\u4E33\u4E35\u4E37\u4E3C\u4E40\u4E41\u4E42\u4E44\u4E46\u4E4A\u4E51\u4E55\u4E57\u4E5A\u4E5B\u4E62\u4E63\u4E64\u4E65\u4E67\u4E68\u4E6A", 5, "\u4E72\u4E74", 9, "\u4E7F", 6, "\u4E87\u4E8A"], + ["8180", "\u4E90\u4E96\u4E97\u4E99\u4E9C\u4E9D\u4E9E\u4EA3\u4EAA\u4EAF\u4EB0\u4EB1\u4EB4\u4EB6\u4EB7\u4EB8\u4EB9\u4EBC\u4EBD\u4EBE\u4EC8\u4ECC\u4ECF\u4ED0\u4ED2\u4EDA\u4EDB\u4EDC\u4EE0\u4EE2\u4EE6\u4EE7\u4EE9\u4EED\u4EEE\u4EEF\u4EF1\u4EF4\u4EF8\u4EF9\u4EFA\u4EFC\u4EFE\u4F00\u4F02", 6, "\u4F0B\u4F0C\u4F12", 4, "\u4F1C\u4F1D\u4F21\u4F23\u4F28\u4F29\u4F2C\u4F2D\u4F2E\u4F31\u4F33\u4F35\u4F37\u4F39\u4F3B\u4F3E", 4, "\u4F44\u4F45\u4F47", 5, "\u4F52\u4F54\u4F56\u4F61\u4F62\u4F66\u4F68\u4F6A\u4F6B\u4F6D\u4F6E\u4F71\u4F72\u4F75\u4F77\u4F78\u4F79\u4F7A\u4F7D\u4F80\u4F81\u4F82\u4F85\u4F86\u4F87\u4F8A\u4F8C\u4F8E\u4F90\u4F92\u4F93\u4F95\u4F96\u4F98\u4F99\u4F9A\u4F9C\u4F9E\u4F9F\u4FA1\u4FA2"], + ["8240", "\u4FA4\u4FAB\u4FAD\u4FB0", 4, "\u4FB6", 8, "\u4FC0\u4FC1\u4FC2\u4FC6\u4FC7\u4FC8\u4FC9\u4FCB\u4FCC\u4FCD\u4FD2", 4, "\u4FD9\u4FDB\u4FE0\u4FE2\u4FE4\u4FE5\u4FE7\u4FEB\u4FEC\u4FF0\u4FF2\u4FF4\u4FF5\u4FF6\u4FF7\u4FF9\u4FFB\u4FFC\u4FFD\u4FFF", 11], + ["8280", "\u500B\u500E\u5010\u5011\u5013\u5015\u5016\u5017\u501B\u501D\u501E\u5020\u5022\u5023\u5024\u5027\u502B\u502F", 10, "\u503B\u503D\u503F\u5040\u5041\u5042\u5044\u5045\u5046\u5049\u504A\u504B\u504D\u5050", 4, "\u5056\u5057\u5058\u5059\u505B\u505D", 7, "\u5066", 5, "\u506D", 8, "\u5078\u5079\u507A\u507C\u507D\u5081\u5082\u5083\u5084\u5086\u5087\u5089\u508A\u508B\u508C\u508E", 20, "\u50A4\u50A6\u50AA\u50AB\u50AD", 4, "\u50B3", 6, "\u50BC"], + ["8340", "\u50BD", 17, "\u50D0", 5, "\u50D7\u50D8\u50D9\u50DB", 10, "\u50E8\u50E9\u50EA\u50EB\u50EF\u50F0\u50F1\u50F2\u50F4\u50F6", 4, "\u50FC", 9, "\u5108"], + ["8380", "\u5109\u510A\u510C", 5, "\u5113", 13, "\u5122", 28, "\u5142\u5147\u514A\u514C\u514E\u514F\u5150\u5152\u5153\u5157\u5158\u5159\u515B\u515D", 4, "\u5163\u5164\u5166\u5167\u5169\u516A\u516F\u5172\u517A\u517E\u517F\u5183\u5184\u5186\u5187\u518A\u518B\u518E\u518F\u5190\u5191\u5193\u5194\u5198\u519A\u519D\u519E\u519F\u51A1\u51A3\u51A6", 4, "\u51AD\u51AE\u51B4\u51B8\u51B9\u51BA\u51BE\u51BF\u51C1\u51C2\u51C3\u51C5\u51C8\u51CA\u51CD\u51CE\u51D0\u51D2", 5], + ["8440", "\u51D8\u51D9\u51DA\u51DC\u51DE\u51DF\u51E2\u51E3\u51E5", 5, "\u51EC\u51EE\u51F1\u51F2\u51F4\u51F7\u51FE\u5204\u5205\u5209\u520B\u520C\u520F\u5210\u5213\u5214\u5215\u521C\u521E\u521F\u5221\u5222\u5223\u5225\u5226\u5227\u522A\u522C\u522F\u5231\u5232\u5234\u5235\u523C\u523E\u5244", 5, "\u524B\u524E\u524F\u5252\u5253\u5255\u5257\u5258"], + ["8480", "\u5259\u525A\u525B\u525D\u525F\u5260\u5262\u5263\u5264\u5266\u5268\u526B\u526C\u526D\u526E\u5270\u5271\u5273", 9, "\u527E\u5280\u5283", 4, "\u5289", 6, "\u5291\u5292\u5294", 6, "\u529C\u52A4\u52A5\u52A6\u52A7\u52AE\u52AF\u52B0\u52B4", 9, "\u52C0\u52C1\u52C2\u52C4\u52C5\u52C6\u52C8\u52CA\u52CC\u52CD\u52CE\u52CF\u52D1\u52D3\u52D4\u52D5\u52D7\u52D9", 5, "\u52E0\u52E1\u52E2\u52E3\u52E5", 10, "\u52F1", 7, "\u52FB\u52FC\u52FD\u5301\u5302\u5303\u5304\u5307\u5309\u530A\u530B\u530C\u530E"], + ["8540", "\u5311\u5312\u5313\u5314\u5318\u531B\u531C\u531E\u531F\u5322\u5324\u5325\u5327\u5328\u5329\u532B\u532C\u532D\u532F", 9, "\u533C\u533D\u5340\u5342\u5344\u5346\u534B\u534C\u534D\u5350\u5354\u5358\u5359\u535B\u535D\u5365\u5368\u536A\u536C\u536D\u5372\u5376\u5379\u537B\u537C\u537D\u537E\u5380\u5381\u5383\u5387\u5388\u538A\u538E\u538F"], + ["8580", "\u5390", 4, "\u5396\u5397\u5399\u539B\u539C\u539E\u53A0\u53A1\u53A4\u53A7\u53AA\u53AB\u53AC\u53AD\u53AF", 6, "\u53B7\u53B8\u53B9\u53BA\u53BC\u53BD\u53BE\u53C0\u53C3", 4, "\u53CE\u53CF\u53D0\u53D2\u53D3\u53D5\u53DA\u53DC\u53DD\u53DE\u53E1\u53E2\u53E7\u53F4\u53FA\u53FE\u53FF\u5400\u5402\u5405\u5407\u540B\u5414\u5418\u5419\u541A\u541C\u5422\u5424\u5425\u542A\u5430\u5433\u5436\u5437\u543A\u543D\u543F\u5441\u5442\u5444\u5445\u5447\u5449\u544C\u544D\u544E\u544F\u5451\u545A\u545D", 4, "\u5463\u5465\u5467\u5469", 7, "\u5474\u5479\u547A\u547E\u547F\u5481\u5483\u5485\u5487\u5488\u5489\u548A\u548D\u5491\u5493\u5497\u5498\u549C\u549E\u549F\u54A0\u54A1"], + ["8640", "\u54A2\u54A5\u54AE\u54B0\u54B2\u54B5\u54B6\u54B7\u54B9\u54BA\u54BC\u54BE\u54C3\u54C5\u54CA\u54CB\u54D6\u54D8\u54DB\u54E0", 4, "\u54EB\u54EC\u54EF\u54F0\u54F1\u54F4", 5, "\u54FB\u54FE\u5500\u5502\u5503\u5504\u5505\u5508\u550A", 4, "\u5512\u5513\u5515", 5, "\u551C\u551D\u551E\u551F\u5521\u5525\u5526"], + ["8680", "\u5528\u5529\u552B\u552D\u5532\u5534\u5535\u5536\u5538\u5539\u553A\u553B\u553D\u5540\u5542\u5545\u5547\u5548\u554B", 4, "\u5551\u5552\u5553\u5554\u5557", 4, "\u555D\u555E\u555F\u5560\u5562\u5563\u5568\u5569\u556B\u556F", 5, "\u5579\u557A\u557D\u557F\u5585\u5586\u558C\u558D\u558E\u5590\u5592\u5593\u5595\u5596\u5597\u559A\u559B\u559E\u55A0", 6, "\u55A8", 8, "\u55B2\u55B4\u55B6\u55B8\u55BA\u55BC\u55BF", 4, "\u55C6\u55C7\u55C8\u55CA\u55CB\u55CE\u55CF\u55D0\u55D5\u55D7", 4, "\u55DE\u55E0\u55E2\u55E7\u55E9\u55ED\u55EE\u55F0\u55F1\u55F4\u55F6\u55F8", 4, "\u55FF\u5602\u5603\u5604\u5605"], + ["8740", "\u5606\u5607\u560A\u560B\u560D\u5610", 7, "\u5619\u561A\u561C\u561D\u5620\u5621\u5622\u5625\u5626\u5628\u5629\u562A\u562B\u562E\u562F\u5630\u5633\u5635\u5637\u5638\u563A\u563C\u563D\u563E\u5640", 11, "\u564F", 4, "\u5655\u5656\u565A\u565B\u565D", 4], + ["8780", "\u5663\u5665\u5666\u5667\u566D\u566E\u566F\u5670\u5672\u5673\u5674\u5675\u5677\u5678\u5679\u567A\u567D", 7, "\u5687", 6, "\u5690\u5691\u5692\u5694", 14, "\u56A4", 10, "\u56B0", 6, "\u56B8\u56B9\u56BA\u56BB\u56BD", 12, "\u56CB", 8, "\u56D5\u56D6\u56D8\u56D9\u56DC\u56E3\u56E5", 5, "\u56EC\u56EE\u56EF\u56F2\u56F3\u56F6\u56F7\u56F8\u56FB\u56FC\u5700\u5701\u5702\u5705\u5707\u570B", 6], + ["8840", "\u5712", 9, "\u571D\u571E\u5720\u5721\u5722\u5724\u5725\u5726\u5727\u572B\u5731\u5732\u5734", 4, "\u573C\u573D\u573F\u5741\u5743\u5744\u5745\u5746\u5748\u5749\u574B\u5752", 4, "\u5758\u5759\u5762\u5763\u5765\u5767\u576C\u576E\u5770\u5771\u5772\u5774\u5775\u5778\u5779\u577A\u577D\u577E\u577F\u5780"], + ["8880", "\u5781\u5787\u5788\u5789\u578A\u578D", 4, "\u5794", 6, "\u579C\u579D\u579E\u579F\u57A5\u57A8\u57AA\u57AC\u57AF\u57B0\u57B1\u57B3\u57B5\u57B6\u57B7\u57B9", 8, "\u57C4", 6, "\u57CC\u57CD\u57D0\u57D1\u57D3\u57D6\u57D7\u57DB\u57DC\u57DE\u57E1\u57E2\u57E3\u57E5", 7, "\u57EE\u57F0\u57F1\u57F2\u57F3\u57F5\u57F6\u57F7\u57FB\u57FC\u57FE\u57FF\u5801\u5803\u5804\u5805\u5808\u5809\u580A\u580C\u580E\u580F\u5810\u5812\u5813\u5814\u5816\u5817\u5818\u581A\u581B\u581C\u581D\u581F\u5822\u5823\u5825", 4, "\u582B", 4, "\u5831\u5832\u5833\u5834\u5836", 7], + ["8940", "\u583E", 5, "\u5845", 6, "\u584E\u584F\u5850\u5852\u5853\u5855\u5856\u5857\u5859", 4, "\u585F", 5, "\u5866", 4, "\u586D", 16, "\u587F\u5882\u5884\u5886\u5887\u5888\u588A\u588B\u588C"], + ["8980", "\u588D", 4, "\u5894", 4, "\u589B\u589C\u589D\u58A0", 7, "\u58AA", 17, "\u58BD\u58BE\u58BF\u58C0\u58C2\u58C3\u58C4\u58C6", 10, "\u58D2\u58D3\u58D4\u58D6", 13, "\u58E5", 5, "\u58ED\u58EF\u58F1\u58F2\u58F4\u58F5\u58F7\u58F8\u58FA", 7, "\u5903\u5905\u5906\u5908", 4, "\u590E\u5910\u5911\u5912\u5913\u5917\u5918\u591B\u591D\u591E\u5920\u5921\u5922\u5923\u5926\u5928\u592C\u5930\u5932\u5933\u5935\u5936\u593B"], + ["8a40", "\u593D\u593E\u593F\u5940\u5943\u5945\u5946\u594A\u594C\u594D\u5950\u5952\u5953\u5959\u595B", 4, "\u5961\u5963\u5964\u5966", 12, "\u5975\u5977\u597A\u597B\u597C\u597E\u597F\u5980\u5985\u5989\u598B\u598C\u598E\u598F\u5990\u5991\u5994\u5995\u5998\u599A\u599B\u599C\u599D\u599F\u59A0\u59A1\u59A2\u59A6"], + ["8a80", "\u59A7\u59AC\u59AD\u59B0\u59B1\u59B3", 5, "\u59BA\u59BC\u59BD\u59BF", 6, "\u59C7\u59C8\u59C9\u59CC\u59CD\u59CE\u59CF\u59D5\u59D6\u59D9\u59DB\u59DE", 4, "\u59E4\u59E6\u59E7\u59E9\u59EA\u59EB\u59ED", 11, "\u59FA\u59FC\u59FD\u59FE\u5A00\u5A02\u5A0A\u5A0B\u5A0D\u5A0E\u5A0F\u5A10\u5A12\u5A14\u5A15\u5A16\u5A17\u5A19\u5A1A\u5A1B\u5A1D\u5A1E\u5A21\u5A22\u5A24\u5A26\u5A27\u5A28\u5A2A", 6, "\u5A33\u5A35\u5A37", 4, "\u5A3D\u5A3E\u5A3F\u5A41", 4, "\u5A47\u5A48\u5A4B", 9, "\u5A56\u5A57\u5A58\u5A59\u5A5B", 5], + ["8b40", "\u5A61\u5A63\u5A64\u5A65\u5A66\u5A68\u5A69\u5A6B", 8, "\u5A78\u5A79\u5A7B\u5A7C\u5A7D\u5A7E\u5A80", 17, "\u5A93", 6, "\u5A9C", 13, "\u5AAB\u5AAC"], + ["8b80", "\u5AAD", 4, "\u5AB4\u5AB6\u5AB7\u5AB9", 4, "\u5ABF\u5AC0\u5AC3", 5, "\u5ACA\u5ACB\u5ACD", 4, "\u5AD3\u5AD5\u5AD7\u5AD9\u5ADA\u5ADB\u5ADD\u5ADE\u5ADF\u5AE2\u5AE4\u5AE5\u5AE7\u5AE8\u5AEA\u5AEC", 4, "\u5AF2", 22, "\u5B0A", 11, "\u5B18", 25, "\u5B33\u5B35\u5B36\u5B38", 7, "\u5B41", 6], + ["8c40", "\u5B48", 7, "\u5B52\u5B56\u5B5E\u5B60\u5B61\u5B67\u5B68\u5B6B\u5B6D\u5B6E\u5B6F\u5B72\u5B74\u5B76\u5B77\u5B78\u5B79\u5B7B\u5B7C\u5B7E\u5B7F\u5B82\u5B86\u5B8A\u5B8D\u5B8E\u5B90\u5B91\u5B92\u5B94\u5B96\u5B9F\u5BA7\u5BA8\u5BA9\u5BAC\u5BAD\u5BAE\u5BAF\u5BB1\u5BB2\u5BB7\u5BBA\u5BBB\u5BBC\u5BC0\u5BC1\u5BC3\u5BC8\u5BC9\u5BCA\u5BCB\u5BCD\u5BCE\u5BCF"], + ["8c80", "\u5BD1\u5BD4", 8, "\u5BE0\u5BE2\u5BE3\u5BE6\u5BE7\u5BE9", 4, "\u5BEF\u5BF1", 6, "\u5BFD\u5BFE\u5C00\u5C02\u5C03\u5C05\u5C07\u5C08\u5C0B\u5C0C\u5C0D\u5C0E\u5C10\u5C12\u5C13\u5C17\u5C19\u5C1B\u5C1E\u5C1F\u5C20\u5C21\u5C23\u5C26\u5C28\u5C29\u5C2A\u5C2B\u5C2D\u5C2E\u5C2F\u5C30\u5C32\u5C33\u5C35\u5C36\u5C37\u5C43\u5C44\u5C46\u5C47\u5C4C\u5C4D\u5C52\u5C53\u5C54\u5C56\u5C57\u5C58\u5C5A\u5C5B\u5C5C\u5C5D\u5C5F\u5C62\u5C64\u5C67", 6, "\u5C70\u5C72", 6, "\u5C7B\u5C7C\u5C7D\u5C7E\u5C80\u5C83", 4, "\u5C89\u5C8A\u5C8B\u5C8E\u5C8F\u5C92\u5C93\u5C95\u5C9D", 4, "\u5CA4", 4], + ["8d40", "\u5CAA\u5CAE\u5CAF\u5CB0\u5CB2\u5CB4\u5CB6\u5CB9\u5CBA\u5CBB\u5CBC\u5CBE\u5CC0\u5CC2\u5CC3\u5CC5", 5, "\u5CCC", 5, "\u5CD3", 5, "\u5CDA", 6, "\u5CE2\u5CE3\u5CE7\u5CE9\u5CEB\u5CEC\u5CEE\u5CEF\u5CF1", 9, "\u5CFC", 4], + ["8d80", "\u5D01\u5D04\u5D05\u5D08", 5, "\u5D0F", 4, "\u5D15\u5D17\u5D18\u5D19\u5D1A\u5D1C\u5D1D\u5D1F", 4, "\u5D25\u5D28\u5D2A\u5D2B\u5D2C\u5D2F", 4, "\u5D35", 7, "\u5D3F", 7, "\u5D48\u5D49\u5D4D", 10, "\u5D59\u5D5A\u5D5C\u5D5E", 10, "\u5D6A\u5D6D\u5D6E\u5D70\u5D71\u5D72\u5D73\u5D75", 12, "\u5D83", 21, "\u5D9A\u5D9B\u5D9C\u5D9E\u5D9F\u5DA0"], + ["8e40", "\u5DA1", 21, "\u5DB8", 12, "\u5DC6", 6, "\u5DCE", 12, "\u5DDC\u5DDF\u5DE0\u5DE3\u5DE4\u5DEA\u5DEC\u5DED"], + ["8e80", "\u5DF0\u5DF5\u5DF6\u5DF8", 4, "\u5DFF\u5E00\u5E04\u5E07\u5E09\u5E0A\u5E0B\u5E0D\u5E0E\u5E12\u5E13\u5E17\u5E1E", 7, "\u5E28", 4, "\u5E2F\u5E30\u5E32", 4, "\u5E39\u5E3A\u5E3E\u5E3F\u5E40\u5E41\u5E43\u5E46", 5, "\u5E4D", 6, "\u5E56", 4, "\u5E5C\u5E5D\u5E5F\u5E60\u5E63", 14, "\u5E75\u5E77\u5E79\u5E7E\u5E81\u5E82\u5E83\u5E85\u5E88\u5E89\u5E8C\u5E8D\u5E8E\u5E92\u5E98\u5E9B\u5E9D\u5EA1\u5EA2\u5EA3\u5EA4\u5EA8", 4, "\u5EAE", 4, "\u5EB4\u5EBA\u5EBB\u5EBC\u5EBD\u5EBF", 6], + ["8f40", "\u5EC6\u5EC7\u5EC8\u5ECB", 5, "\u5ED4\u5ED5\u5ED7\u5ED8\u5ED9\u5EDA\u5EDC", 11, "\u5EE9\u5EEB", 8, "\u5EF5\u5EF8\u5EF9\u5EFB\u5EFC\u5EFD\u5F05\u5F06\u5F07\u5F09\u5F0C\u5F0D\u5F0E\u5F10\u5F12\u5F14\u5F16\u5F19\u5F1A\u5F1C\u5F1D\u5F1E\u5F21\u5F22\u5F23\u5F24"], + ["8f80", "\u5F28\u5F2B\u5F2C\u5F2E\u5F30\u5F32", 6, "\u5F3B\u5F3D\u5F3E\u5F3F\u5F41", 14, "\u5F51\u5F54\u5F59\u5F5A\u5F5B\u5F5C\u5F5E\u5F5F\u5F60\u5F63\u5F65\u5F67\u5F68\u5F6B\u5F6E\u5F6F\u5F72\u5F74\u5F75\u5F76\u5F78\u5F7A\u5F7D\u5F7E\u5F7F\u5F83\u5F86\u5F8D\u5F8E\u5F8F\u5F91\u5F93\u5F94\u5F96\u5F9A\u5F9B\u5F9D\u5F9E\u5F9F\u5FA0\u5FA2", 5, "\u5FA9\u5FAB\u5FAC\u5FAF", 5, "\u5FB6\u5FB8\u5FB9\u5FBA\u5FBB\u5FBE", 4, "\u5FC7\u5FC8\u5FCA\u5FCB\u5FCE\u5FD3\u5FD4\u5FD5\u5FDA\u5FDB\u5FDC\u5FDE\u5FDF\u5FE2\u5FE3\u5FE5\u5FE6\u5FE8\u5FE9\u5FEC\u5FEF\u5FF0\u5FF2\u5FF3\u5FF4\u5FF6\u5FF7\u5FF9\u5FFA\u5FFC\u6007"], + ["9040", "\u6008\u6009\u600B\u600C\u6010\u6011\u6013\u6017\u6018\u601A\u601E\u601F\u6022\u6023\u6024\u602C\u602D\u602E\u6030", 4, "\u6036", 4, "\u603D\u603E\u6040\u6044", 6, "\u604C\u604E\u604F\u6051\u6053\u6054\u6056\u6057\u6058\u605B\u605C\u605E\u605F\u6060\u6061\u6065\u6066\u606E\u6071\u6072\u6074\u6075\u6077\u607E\u6080"], + ["9080", "\u6081\u6082\u6085\u6086\u6087\u6088\u608A\u608B\u608E\u608F\u6090\u6091\u6093\u6095\u6097\u6098\u6099\u609C\u609E\u60A1\u60A2\u60A4\u60A5\u60A7\u60A9\u60AA\u60AE\u60B0\u60B3\u60B5\u60B6\u60B7\u60B9\u60BA\u60BD", 7, "\u60C7\u60C8\u60C9\u60CC", 4, "\u60D2\u60D3\u60D4\u60D6\u60D7\u60D9\u60DB\u60DE\u60E1", 4, "\u60EA\u60F1\u60F2\u60F5\u60F7\u60F8\u60FB", 4, "\u6102\u6103\u6104\u6105\u6107\u610A\u610B\u610C\u6110", 4, "\u6116\u6117\u6118\u6119\u611B\u611C\u611D\u611E\u6121\u6122\u6125\u6128\u6129\u612A\u612C", 18, "\u6140", 6], + ["9140", "\u6147\u6149\u614B\u614D\u614F\u6150\u6152\u6153\u6154\u6156", 6, "\u615E\u615F\u6160\u6161\u6163\u6164\u6165\u6166\u6169", 6, "\u6171\u6172\u6173\u6174\u6176\u6178", 18, "\u618C\u618D\u618F", 4, "\u6195"], + ["9180", "\u6196", 6, "\u619E", 8, "\u61AA\u61AB\u61AD", 9, "\u61B8", 5, "\u61BF\u61C0\u61C1\u61C3", 4, "\u61C9\u61CC", 4, "\u61D3\u61D5", 16, "\u61E7", 13, "\u61F6", 8, "\u6200", 5, "\u6207\u6209\u6213\u6214\u6219\u621C\u621D\u621E\u6220\u6223\u6226\u6227\u6228\u6229\u622B\u622D\u622F\u6230\u6231\u6232\u6235\u6236\u6238", 4, "\u6242\u6244\u6245\u6246\u624A"], + ["9240", "\u624F\u6250\u6255\u6256\u6257\u6259\u625A\u625C", 6, "\u6264\u6265\u6268\u6271\u6272\u6274\u6275\u6277\u6278\u627A\u627B\u627D\u6281\u6282\u6283\u6285\u6286\u6287\u6288\u628B", 5, "\u6294\u6299\u629C\u629D\u629E\u62A3\u62A6\u62A7\u62A9\u62AA\u62AD\u62AE\u62AF\u62B0\u62B2\u62B3\u62B4\u62B6\u62B7\u62B8\u62BA\u62BE\u62C0\u62C1"], + ["9280", "\u62C3\u62CB\u62CF\u62D1\u62D5\u62DD\u62DE\u62E0\u62E1\u62E4\u62EA\u62EB\u62F0\u62F2\u62F5\u62F8\u62F9\u62FA\u62FB\u6300\u6303\u6304\u6305\u6306\u630A\u630B\u630C\u630D\u630F\u6310\u6312\u6313\u6314\u6315\u6317\u6318\u6319\u631C\u6326\u6327\u6329\u632C\u632D\u632E\u6330\u6331\u6333", 5, "\u633B\u633C\u633E\u633F\u6340\u6341\u6344\u6347\u6348\u634A\u6351\u6352\u6353\u6354\u6356", 7, "\u6360\u6364\u6365\u6366\u6368\u636A\u636B\u636C\u636F\u6370\u6372\u6373\u6374\u6375\u6378\u6379\u637C\u637D\u637E\u637F\u6381\u6383\u6384\u6385\u6386\u638B\u638D\u6391\u6393\u6394\u6395\u6397\u6399", 6, "\u63A1\u63A4\u63A6\u63AB\u63AF\u63B1\u63B2\u63B5\u63B6\u63B9\u63BB\u63BD\u63BF\u63C0"], + ["9340", "\u63C1\u63C2\u63C3\u63C5\u63C7\u63C8\u63CA\u63CB\u63CC\u63D1\u63D3\u63D4\u63D5\u63D7", 6, "\u63DF\u63E2\u63E4", 4, "\u63EB\u63EC\u63EE\u63EF\u63F0\u63F1\u63F3\u63F5\u63F7\u63F9\u63FA\u63FB\u63FC\u63FE\u6403\u6404\u6406", 4, "\u640D\u640E\u6411\u6412\u6415", 5, "\u641D\u641F\u6422\u6423\u6424"], + ["9380", "\u6425\u6427\u6428\u6429\u642B\u642E", 5, "\u6435", 4, "\u643B\u643C\u643E\u6440\u6442\u6443\u6449\u644B", 6, "\u6453\u6455\u6456\u6457\u6459", 4, "\u645F", 7, "\u6468\u646A\u646B\u646C\u646E", 9, "\u647B", 6, "\u6483\u6486\u6488", 8, "\u6493\u6494\u6497\u6498\u649A\u649B\u649C\u649D\u649F", 4, "\u64A5\u64A6\u64A7\u64A8\u64AA\u64AB\u64AF\u64B1\u64B2\u64B3\u64B4\u64B6\u64B9\u64BB\u64BD\u64BE\u64BF\u64C1\u64C3\u64C4\u64C6", 6, "\u64CF\u64D1\u64D3\u64D4\u64D5\u64D6\u64D9\u64DA"], + ["9440", "\u64DB\u64DC\u64DD\u64DF\u64E0\u64E1\u64E3\u64E5\u64E7", 24, "\u6501", 7, "\u650A", 7, "\u6513", 4, "\u6519", 8], + ["9480", "\u6522\u6523\u6524\u6526", 4, "\u652C\u652D\u6530\u6531\u6532\u6533\u6537\u653A\u653C\u653D\u6540", 4, "\u6546\u6547\u654A\u654B\u654D\u654E\u6550\u6552\u6553\u6554\u6557\u6558\u655A\u655C\u655F\u6560\u6561\u6564\u6565\u6567\u6568\u6569\u656A\u656D\u656E\u656F\u6571\u6573\u6575\u6576\u6578", 14, "\u6588\u6589\u658A\u658D\u658E\u658F\u6592\u6594\u6595\u6596\u6598\u659A\u659D\u659E\u65A0\u65A2\u65A3\u65A6\u65A8\u65AA\u65AC\u65AE\u65B1", 7, "\u65BA\u65BB\u65BE\u65BF\u65C0\u65C2\u65C7\u65C8\u65C9\u65CA\u65CD\u65D0\u65D1\u65D3\u65D4\u65D5\u65D8", 7, "\u65E1\u65E3\u65E4\u65EA\u65EB"], + ["9540", "\u65F2\u65F3\u65F4\u65F5\u65F8\u65F9\u65FB", 4, "\u6601\u6604\u6605\u6607\u6608\u6609\u660B\u660D\u6610\u6611\u6612\u6616\u6617\u6618\u661A\u661B\u661C\u661E\u6621\u6622\u6623\u6624\u6626\u6629\u662A\u662B\u662C\u662E\u6630\u6632\u6633\u6637", 4, "\u663D\u663F\u6640\u6642\u6644", 6, "\u664D\u664E\u6650\u6651\u6658"], + ["9580", "\u6659\u665B\u665C\u665D\u665E\u6660\u6662\u6663\u6665\u6667\u6669", 4, "\u6671\u6672\u6673\u6675\u6678\u6679\u667B\u667C\u667D\u667F\u6680\u6681\u6683\u6685\u6686\u6688\u6689\u668A\u668B\u668D\u668E\u668F\u6690\u6692\u6693\u6694\u6695\u6698", 4, "\u669E", 8, "\u66A9", 4, "\u66AF", 4, "\u66B5\u66B6\u66B7\u66B8\u66BA\u66BB\u66BC\u66BD\u66BF", 25, "\u66DA\u66DE", 7, "\u66E7\u66E8\u66EA", 5, "\u66F1\u66F5\u66F6\u66F8\u66FA\u66FB\u66FD\u6701\u6702\u6703"], + ["9640", "\u6704\u6705\u6706\u6707\u670C\u670E\u670F\u6711\u6712\u6713\u6716\u6718\u6719\u671A\u671C\u671E\u6720", 5, "\u6727\u6729\u672E\u6730\u6732\u6733\u6736\u6737\u6738\u6739\u673B\u673C\u673E\u673F\u6741\u6744\u6745\u6747\u674A\u674B\u674D\u6752\u6754\u6755\u6757", 4, "\u675D\u6762\u6763\u6764\u6766\u6767\u676B\u676C\u676E\u6771\u6774\u6776"], + ["9680", "\u6778\u6779\u677A\u677B\u677D\u6780\u6782\u6783\u6785\u6786\u6788\u678A\u678C\u678D\u678E\u678F\u6791\u6792\u6793\u6794\u6796\u6799\u679B\u679F\u67A0\u67A1\u67A4\u67A6\u67A9\u67AC\u67AE\u67B1\u67B2\u67B4\u67B9", 7, "\u67C2\u67C5", 9, "\u67D5\u67D6\u67D7\u67DB\u67DF\u67E1\u67E3\u67E4\u67E6\u67E7\u67E8\u67EA\u67EB\u67ED\u67EE\u67F2\u67F5", 7, "\u67FE\u6801\u6802\u6803\u6804\u6806\u680D\u6810\u6812\u6814\u6815\u6818", 4, "\u681E\u681F\u6820\u6822", 6, "\u682B", 6, "\u6834\u6835\u6836\u683A\u683B\u683F\u6847\u684B\u684D\u684F\u6852\u6856", 5], + ["9740", "\u685C\u685D\u685E\u685F\u686A\u686C", 7, "\u6875\u6878", 8, "\u6882\u6884\u6887", 7, "\u6890\u6891\u6892\u6894\u6895\u6896\u6898", 9, "\u68A3\u68A4\u68A5\u68A9\u68AA\u68AB\u68AC\u68AE\u68B1\u68B2\u68B4\u68B6\u68B7\u68B8"], + ["9780", "\u68B9", 6, "\u68C1\u68C3", 5, "\u68CA\u68CC\u68CE\u68CF\u68D0\u68D1\u68D3\u68D4\u68D6\u68D7\u68D9\u68DB", 4, "\u68E1\u68E2\u68E4", 9, "\u68EF\u68F2\u68F3\u68F4\u68F6\u68F7\u68F8\u68FB\u68FD\u68FE\u68FF\u6900\u6902\u6903\u6904\u6906", 4, "\u690C\u690F\u6911\u6913", 11, "\u6921\u6922\u6923\u6925", 7, "\u692E\u692F\u6931\u6932\u6933\u6935\u6936\u6937\u6938\u693A\u693B\u693C\u693E\u6940\u6941\u6943", 16, "\u6955\u6956\u6958\u6959\u695B\u695C\u695F"], + ["9840", "\u6961\u6962\u6964\u6965\u6967\u6968\u6969\u696A\u696C\u696D\u696F\u6970\u6972", 4, "\u697A\u697B\u697D\u697E\u697F\u6981\u6983\u6985\u698A\u698B\u698C\u698E", 5, "\u6996\u6997\u6999\u699A\u699D", 9, "\u69A9\u69AA\u69AC\u69AE\u69AF\u69B0\u69B2\u69B3\u69B5\u69B6\u69B8\u69B9\u69BA\u69BC\u69BD"], + ["9880", "\u69BE\u69BF\u69C0\u69C2", 7, "\u69CB\u69CD\u69CF\u69D1\u69D2\u69D3\u69D5", 5, "\u69DC\u69DD\u69DE\u69E1", 11, "\u69EE\u69EF\u69F0\u69F1\u69F3", 9, "\u69FE\u6A00", 9, "\u6A0B", 11, "\u6A19", 5, "\u6A20\u6A22", 5, "\u6A29\u6A2B\u6A2C\u6A2D\u6A2E\u6A30\u6A32\u6A33\u6A34\u6A36", 6, "\u6A3F", 4, "\u6A45\u6A46\u6A48", 7, "\u6A51", 6, "\u6A5A"], + ["9940", "\u6A5C", 4, "\u6A62\u6A63\u6A64\u6A66", 10, "\u6A72", 6, "\u6A7A\u6A7B\u6A7D\u6A7E\u6A7F\u6A81\u6A82\u6A83\u6A85", 8, "\u6A8F\u6A92", 4, "\u6A98", 7, "\u6AA1", 5], + ["9980", "\u6AA7\u6AA8\u6AAA\u6AAD", 114, "\u6B25\u6B26\u6B28", 6], + ["9a40", "\u6B2F\u6B30\u6B31\u6B33\u6B34\u6B35\u6B36\u6B38\u6B3B\u6B3C\u6B3D\u6B3F\u6B40\u6B41\u6B42\u6B44\u6B45\u6B48\u6B4A\u6B4B\u6B4D", 11, "\u6B5A", 7, "\u6B68\u6B69\u6B6B", 13, "\u6B7A\u6B7D\u6B7E\u6B7F\u6B80\u6B85\u6B88"], + ["9a80", "\u6B8C\u6B8E\u6B8F\u6B90\u6B91\u6B94\u6B95\u6B97\u6B98\u6B99\u6B9C", 4, "\u6BA2", 7, "\u6BAB", 7, "\u6BB6\u6BB8", 6, "\u6BC0\u6BC3\u6BC4\u6BC6", 4, "\u6BCC\u6BCE\u6BD0\u6BD1\u6BD8\u6BDA\u6BDC", 4, "\u6BE2", 7, "\u6BEC\u6BED\u6BEE\u6BF0\u6BF1\u6BF2\u6BF4\u6BF6\u6BF7\u6BF8\u6BFA\u6BFB\u6BFC\u6BFE", 6, "\u6C08", 4, "\u6C0E\u6C12\u6C17\u6C1C\u6C1D\u6C1E\u6C20\u6C23\u6C25\u6C2B\u6C2C\u6C2D\u6C31\u6C33\u6C36\u6C37\u6C39\u6C3A\u6C3B\u6C3C\u6C3E\u6C3F\u6C43\u6C44\u6C45\u6C48\u6C4B", 4, "\u6C51\u6C52\u6C53\u6C56\u6C58"], + ["9b40", "\u6C59\u6C5A\u6C62\u6C63\u6C65\u6C66\u6C67\u6C6B", 4, "\u6C71\u6C73\u6C75\u6C77\u6C78\u6C7A\u6C7B\u6C7C\u6C7F\u6C80\u6C84\u6C87\u6C8A\u6C8B\u6C8D\u6C8E\u6C91\u6C92\u6C95\u6C96\u6C97\u6C98\u6C9A\u6C9C\u6C9D\u6C9E\u6CA0\u6CA2\u6CA8\u6CAC\u6CAF\u6CB0\u6CB4\u6CB5\u6CB6\u6CB7\u6CBA\u6CC0\u6CC1\u6CC2\u6CC3\u6CC6\u6CC7\u6CC8\u6CCB\u6CCD\u6CCE\u6CCF\u6CD1\u6CD2\u6CD8"], + ["9b80", "\u6CD9\u6CDA\u6CDC\u6CDD\u6CDF\u6CE4\u6CE6\u6CE7\u6CE9\u6CEC\u6CED\u6CF2\u6CF4\u6CF9\u6CFF\u6D00\u6D02\u6D03\u6D05\u6D06\u6D08\u6D09\u6D0A\u6D0D\u6D0F\u6D10\u6D11\u6D13\u6D14\u6D15\u6D16\u6D18\u6D1C\u6D1D\u6D1F", 5, "\u6D26\u6D28\u6D29\u6D2C\u6D2D\u6D2F\u6D30\u6D34\u6D36\u6D37\u6D38\u6D3A\u6D3F\u6D40\u6D42\u6D44\u6D49\u6D4C\u6D50\u6D55\u6D56\u6D57\u6D58\u6D5B\u6D5D\u6D5F\u6D61\u6D62\u6D64\u6D65\u6D67\u6D68\u6D6B\u6D6C\u6D6D\u6D70\u6D71\u6D72\u6D73\u6D75\u6D76\u6D79\u6D7A\u6D7B\u6D7D", 4, "\u6D83\u6D84\u6D86\u6D87\u6D8A\u6D8B\u6D8D\u6D8F\u6D90\u6D92\u6D96", 4, "\u6D9C\u6DA2\u6DA5\u6DAC\u6DAD\u6DB0\u6DB1\u6DB3\u6DB4\u6DB6\u6DB7\u6DB9", 5, "\u6DC1\u6DC2\u6DC3\u6DC8\u6DC9\u6DCA"], + ["9c40", "\u6DCD\u6DCE\u6DCF\u6DD0\u6DD2\u6DD3\u6DD4\u6DD5\u6DD7\u6DDA\u6DDB\u6DDC\u6DDF\u6DE2\u6DE3\u6DE5\u6DE7\u6DE8\u6DE9\u6DEA\u6DED\u6DEF\u6DF0\u6DF2\u6DF4\u6DF5\u6DF6\u6DF8\u6DFA\u6DFD", 7, "\u6E06\u6E07\u6E08\u6E09\u6E0B\u6E0F\u6E12\u6E13\u6E15\u6E18\u6E19\u6E1B\u6E1C\u6E1E\u6E1F\u6E22\u6E26\u6E27\u6E28\u6E2A\u6E2C\u6E2E\u6E30\u6E31\u6E33\u6E35"], + ["9c80", "\u6E36\u6E37\u6E39\u6E3B", 7, "\u6E45", 7, "\u6E4F\u6E50\u6E51\u6E52\u6E55\u6E57\u6E59\u6E5A\u6E5C\u6E5D\u6E5E\u6E60", 10, "\u6E6C\u6E6D\u6E6F", 14, "\u6E80\u6E81\u6E82\u6E84\u6E87\u6E88\u6E8A", 4, "\u6E91", 6, "\u6E99\u6E9A\u6E9B\u6E9D\u6E9E\u6EA0\u6EA1\u6EA3\u6EA4\u6EA6\u6EA8\u6EA9\u6EAB\u6EAC\u6EAD\u6EAE\u6EB0\u6EB3\u6EB5\u6EB8\u6EB9\u6EBC\u6EBE\u6EBF\u6EC0\u6EC3\u6EC4\u6EC5\u6EC6\u6EC8\u6EC9\u6ECA\u6ECC\u6ECD\u6ECE\u6ED0\u6ED2\u6ED6\u6ED8\u6ED9\u6EDB\u6EDC\u6EDD\u6EE3\u6EE7\u6EEA", 5], + ["9d40", "\u6EF0\u6EF1\u6EF2\u6EF3\u6EF5\u6EF6\u6EF7\u6EF8\u6EFA", 7, "\u6F03\u6F04\u6F05\u6F07\u6F08\u6F0A", 4, "\u6F10\u6F11\u6F12\u6F16", 9, "\u6F21\u6F22\u6F23\u6F25\u6F26\u6F27\u6F28\u6F2C\u6F2E\u6F30\u6F32\u6F34\u6F35\u6F37", 6, "\u6F3F\u6F40\u6F41\u6F42"], + ["9d80", "\u6F43\u6F44\u6F45\u6F48\u6F49\u6F4A\u6F4C\u6F4E", 9, "\u6F59\u6F5A\u6F5B\u6F5D\u6F5F\u6F60\u6F61\u6F63\u6F64\u6F65\u6F67", 5, "\u6F6F\u6F70\u6F71\u6F73\u6F75\u6F76\u6F77\u6F79\u6F7B\u6F7D", 6, "\u6F85\u6F86\u6F87\u6F8A\u6F8B\u6F8F", 12, "\u6F9D\u6F9E\u6F9F\u6FA0\u6FA2", 4, "\u6FA8", 10, "\u6FB4\u6FB5\u6FB7\u6FB8\u6FBA", 5, "\u6FC1\u6FC3", 5, "\u6FCA", 6, "\u6FD3", 10, "\u6FDF\u6FE2\u6FE3\u6FE4\u6FE5"], + ["9e40", "\u6FE6", 7, "\u6FF0", 32, "\u7012", 7, "\u701C", 6, "\u7024", 6], + ["9e80", "\u702B", 9, "\u7036\u7037\u7038\u703A", 17, "\u704D\u704E\u7050", 13, "\u705F", 11, "\u706E\u7071\u7072\u7073\u7074\u7077\u7079\u707A\u707B\u707D\u7081\u7082\u7083\u7084\u7086\u7087\u7088\u708B\u708C\u708D\u708F\u7090\u7091\u7093\u7097\u7098\u709A\u709B\u709E", 12, "\u70B0\u70B2\u70B4\u70B5\u70B6\u70BA\u70BE\u70BF\u70C4\u70C5\u70C6\u70C7\u70C9\u70CB", 12, "\u70DA"], + ["9f40", "\u70DC\u70DD\u70DE\u70E0\u70E1\u70E2\u70E3\u70E5\u70EA\u70EE\u70F0", 6, "\u70F8\u70FA\u70FB\u70FC\u70FE", 10, "\u710B", 4, "\u7111\u7112\u7114\u7117\u711B", 10, "\u7127", 7, "\u7132\u7133\u7134"], + ["9f80", "\u7135\u7137", 13, "\u7146\u7147\u7148\u7149\u714B\u714D\u714F", 12, "\u715D\u715F", 4, "\u7165\u7169", 4, "\u716F\u7170\u7171\u7174\u7175\u7176\u7177\u7179\u717B\u717C\u717E", 5, "\u7185", 4, "\u718B\u718C\u718D\u718E\u7190\u7191\u7192\u7193\u7195\u7196\u7197\u719A", 4, "\u71A1", 6, "\u71A9\u71AA\u71AB\u71AD", 5, "\u71B4\u71B6\u71B7\u71B8\u71BA", 8, "\u71C4", 9, "\u71CF", 4], + ["a040", "\u71D6", 9, "\u71E1\u71E2\u71E3\u71E4\u71E6\u71E8", 5, "\u71EF", 9, "\u71FA", 11, "\u7207", 19], + ["a080", "\u721B\u721C\u721E", 9, "\u7229\u722B\u722D\u722E\u722F\u7232\u7233\u7234\u723A\u723C\u723E\u7240", 6, "\u7249\u724A\u724B\u724E\u724F\u7250\u7251\u7253\u7254\u7255\u7257\u7258\u725A\u725C\u725E\u7260\u7263\u7264\u7265\u7268\u726A\u726B\u726C\u726D\u7270\u7271\u7273\u7274\u7276\u7277\u7278\u727B\u727C\u727D\u7282\u7283\u7285", 4, "\u728C\u728E\u7290\u7291\u7293", 11, "\u72A0", 11, "\u72AE\u72B1\u72B2\u72B3\u72B5\u72BA", 6, "\u72C5\u72C6\u72C7\u72C9\u72CA\u72CB\u72CC\u72CF\u72D1\u72D3\u72D4\u72D5\u72D6\u72D8\u72DA\u72DB"], + ["a1a1", "\u3000\u3001\u3002\xB7\u02C9\u02C7\xA8\u3003\u3005\u2014\uFF5E\u2016\u2026\u2018\u2019\u201C\u201D\u3014\u3015\u3008", 7, "\u3016\u3017\u3010\u3011\xB1\xD7\xF7\u2236\u2227\u2228\u2211\u220F\u222A\u2229\u2208\u2237\u221A\u22A5\u2225\u2220\u2312\u2299\u222B\u222E\u2261\u224C\u2248\u223D\u221D\u2260\u226E\u226F\u2264\u2265\u221E\u2235\u2234\u2642\u2640\xB0\u2032\u2033\u2103\uFF04\xA4\uFFE0\uFFE1\u2030\xA7\u2116\u2606\u2605\u25CB\u25CF\u25CE\u25C7\u25C6\u25A1\u25A0\u25B3\u25B2\u203B\u2192\u2190\u2191\u2193\u3013"], + ["a2a1", "\u2170", 9], + ["a2b1", "\u2488", 19, "\u2474", 19, "\u2460", 9], + ["a2e5", "\u3220", 9], + ["a2f1", "\u2160", 11], + ["a3a1", "\uFF01\uFF02\uFF03\uFFE5\uFF05", 88, "\uFFE3"], + ["a4a1", "\u3041", 82], + ["a5a1", "\u30A1", 85], + ["a6a1", "\u0391", 16, "\u03A3", 6], + ["a6c1", "\u03B1", 16, "\u03C3", 6], + ["a6e0", "\uFE35\uFE36\uFE39\uFE3A\uFE3F\uFE40\uFE3D\uFE3E\uFE41\uFE42\uFE43\uFE44"], + ["a6ee", "\uFE3B\uFE3C\uFE37\uFE38\uFE31"], + ["a6f4", "\uFE33\uFE34"], + ["a7a1", "\u0410", 5, "\u0401\u0416", 25], + ["a7d1", "\u0430", 5, "\u0451\u0436", 25], + ["a840", "\u02CA\u02CB\u02D9\u2013\u2015\u2025\u2035\u2105\u2109\u2196\u2197\u2198\u2199\u2215\u221F\u2223\u2252\u2266\u2267\u22BF\u2550", 35, "\u2581", 6], + ["a880", "\u2588", 7, "\u2593\u2594\u2595\u25BC\u25BD\u25E2\u25E3\u25E4\u25E5\u2609\u2295\u3012\u301D\u301E"], + ["a8a1", "\u0101\xE1\u01CE\xE0\u0113\xE9\u011B\xE8\u012B\xED\u01D0\xEC\u014D\xF3\u01D2\xF2\u016B\xFA\u01D4\xF9\u01D6\u01D8\u01DA\u01DC\xFC\xEA\u0251"], + ["a8bd", "\u0144\u0148"], + ["a8c0", "\u0261"], + ["a8c5", "\u3105", 36], + ["a940", "\u3021", 8, "\u32A3\u338E\u338F\u339C\u339D\u339E\u33A1\u33C4\u33CE\u33D1\u33D2\u33D5\uFE30\uFFE2\uFFE4"], + ["a959", "\u2121\u3231"], + ["a95c", "\u2010"], + ["a960", "\u30FC\u309B\u309C\u30FD\u30FE\u3006\u309D\u309E\uFE49", 9, "\uFE54\uFE55\uFE56\uFE57\uFE59", 8], + ["a980", "\uFE62", 4, "\uFE68\uFE69\uFE6A\uFE6B"], + ["a996", "\u3007"], + ["a9a4", "\u2500", 75], + ["aa40", "\u72DC\u72DD\u72DF\u72E2", 5, "\u72EA\u72EB\u72F5\u72F6\u72F9\u72FD\u72FE\u72FF\u7300\u7302\u7304", 5, "\u730B\u730C\u730D\u730F\u7310\u7311\u7312\u7314\u7318\u7319\u731A\u731F\u7320\u7323\u7324\u7326\u7327\u7328\u732D\u732F\u7330\u7332\u7333\u7335\u7336\u733A\u733B\u733C\u733D\u7340", 8], + ["aa80", "\u7349\u734A\u734B\u734C\u734E\u734F\u7351\u7353\u7354\u7355\u7356\u7358", 7, "\u7361", 10, "\u736E\u7370\u7371"], + ["ab40", "\u7372", 11, "\u737F", 4, "\u7385\u7386\u7388\u738A\u738C\u738D\u738F\u7390\u7392\u7393\u7394\u7395\u7397\u7398\u7399\u739A\u739C\u739D\u739E\u73A0\u73A1\u73A3", 5, "\u73AA\u73AC\u73AD\u73B1\u73B4\u73B5\u73B6\u73B8\u73B9\u73BC\u73BD\u73BE\u73BF\u73C1\u73C3", 4], + ["ab80", "\u73CB\u73CC\u73CE\u73D2", 6, "\u73DA\u73DB\u73DC\u73DD\u73DF\u73E1\u73E2\u73E3\u73E4\u73E6\u73E8\u73EA\u73EB\u73EC\u73EE\u73EF\u73F0\u73F1\u73F3", 4], + ["ac40", "\u73F8", 10, "\u7404\u7407\u7408\u740B\u740C\u740D\u740E\u7411", 8, "\u741C", 5, "\u7423\u7424\u7427\u7429\u742B\u742D\u742F\u7431\u7432\u7437", 4, "\u743D\u743E\u743F\u7440\u7442", 11], + ["ac80", "\u744E", 6, "\u7456\u7458\u745D\u7460", 12, "\u746E\u746F\u7471", 4, "\u7478\u7479\u747A"], + ["ad40", "\u747B\u747C\u747D\u747F\u7482\u7484\u7485\u7486\u7488\u7489\u748A\u748C\u748D\u748F\u7491", 10, "\u749D\u749F", 7, "\u74AA", 15, "\u74BB", 12], + ["ad80", "\u74C8", 9, "\u74D3", 8, "\u74DD\u74DF\u74E1\u74E5\u74E7", 6, "\u74F0\u74F1\u74F2"], + ["ae40", "\u74F3\u74F5\u74F8", 6, "\u7500\u7501\u7502\u7503\u7505", 7, "\u750E\u7510\u7512\u7514\u7515\u7516\u7517\u751B\u751D\u751E\u7520", 4, "\u7526\u7527\u752A\u752E\u7534\u7536\u7539\u753C\u753D\u753F\u7541\u7542\u7543\u7544\u7546\u7547\u7549\u754A\u754D\u7550\u7551\u7552\u7553\u7555\u7556\u7557\u7558"], + ["ae80", "\u755D", 7, "\u7567\u7568\u7569\u756B", 6, "\u7573\u7575\u7576\u7577\u757A", 4, "\u7580\u7581\u7582\u7584\u7585\u7587"], + ["af40", "\u7588\u7589\u758A\u758C\u758D\u758E\u7590\u7593\u7595\u7598\u759B\u759C\u759E\u75A2\u75A6", 4, "\u75AD\u75B6\u75B7\u75BA\u75BB\u75BF\u75C0\u75C1\u75C6\u75CB\u75CC\u75CE\u75CF\u75D0\u75D1\u75D3\u75D7\u75D9\u75DA\u75DC\u75DD\u75DF\u75E0\u75E1\u75E5\u75E9\u75EC\u75ED\u75EE\u75EF\u75F2\u75F3\u75F5\u75F6\u75F7\u75F8\u75FA\u75FB\u75FD\u75FE\u7602\u7604\u7606\u7607"], + ["af80", "\u7608\u7609\u760B\u760D\u760E\u760F\u7611\u7612\u7613\u7614\u7616\u761A\u761C\u761D\u761E\u7621\u7623\u7627\u7628\u762C\u762E\u762F\u7631\u7632\u7636\u7637\u7639\u763A\u763B\u763D\u7641\u7642\u7644"], + ["b040", "\u7645", 6, "\u764E", 5, "\u7655\u7657", 4, "\u765D\u765F\u7660\u7661\u7662\u7664", 6, "\u766C\u766D\u766E\u7670", 7, "\u7679\u767A\u767C\u767F\u7680\u7681\u7683\u7685\u7689\u768A\u768C\u768D\u768F\u7690\u7692\u7694\u7695\u7697\u7698\u769A\u769B"], + ["b080", "\u769C", 7, "\u76A5", 8, "\u76AF\u76B0\u76B3\u76B5", 9, "\u76C0\u76C1\u76C3\u554A\u963F\u57C3\u6328\u54CE\u5509\u54C0\u7691\u764C\u853C\u77EE\u827E\u788D\u7231\u9698\u978D\u6C28\u5B89\u4FFA\u6309\u6697\u5CB8\u80FA\u6848\u80AE\u6602\u76CE\u51F9\u6556\u71AC\u7FF1\u8884\u50B2\u5965\u61CA\u6FB3\u82AD\u634C\u6252\u53ED\u5427\u7B06\u516B\u75A4\u5DF4\u62D4\u8DCB\u9776\u628A\u8019\u575D\u9738\u7F62\u7238\u767D\u67CF\u767E\u6446\u4F70\u8D25\u62DC\u7A17\u6591\u73ED\u642C\u6273\u822C\u9881\u677F\u7248\u626E\u62CC\u4F34\u74E3\u534A\u529E\u7ECA\u90A6\u5E2E\u6886\u699C\u8180\u7ED1\u68D2\u78C5\u868C\u9551\u508D\u8C24\u82DE\u80DE\u5305\u8912\u5265"], + ["b140", "\u76C4\u76C7\u76C9\u76CB\u76CC\u76D3\u76D5\u76D9\u76DA\u76DC\u76DD\u76DE\u76E0", 4, "\u76E6", 7, "\u76F0\u76F3\u76F5\u76F6\u76F7\u76FA\u76FB\u76FD\u76FF\u7700\u7702\u7703\u7705\u7706\u770A\u770C\u770E", 10, "\u771B\u771C\u771D\u771E\u7721\u7723\u7724\u7725\u7727\u772A\u772B"], + ["b180", "\u772C\u772E\u7730", 4, "\u7739\u773B\u773D\u773E\u773F\u7742\u7744\u7745\u7746\u7748", 7, "\u7752", 7, "\u775C\u8584\u96F9\u4FDD\u5821\u9971\u5B9D\u62B1\u62A5\u66B4\u8C79\u9C8D\u7206\u676F\u7891\u60B2\u5351\u5317\u8F88\u80CC\u8D1D\u94A1\u500D\u72C8\u5907\u60EB\u7119\u88AB\u5954\u82EF\u672C\u7B28\u5D29\u7EF7\u752D\u6CF5\u8E66\u8FF8\u903C\u9F3B\u6BD4\u9119\u7B14\u5F7C\u78A7\u84D6\u853D\u6BD5\u6BD9\u6BD6\u5E01\u5E87\u75F9\u95ED\u655D\u5F0A\u5FC5\u8F9F\u58C1\u81C2\u907F\u965B\u97AD\u8FB9\u7F16\u8D2C\u6241\u4FBF\u53D8\u535E\u8FA8\u8FA9\u8FAB\u904D\u6807\u5F6A\u8198\u8868\u9CD6\u618B\u522B\u762A\u5F6C\u658C\u6FD2\u6EE8\u5BBE\u6448\u5175\u51B0\u67C4\u4E19\u79C9\u997C\u70B3"], + ["b240", "\u775D\u775E\u775F\u7760\u7764\u7767\u7769\u776A\u776D", 11, "\u777A\u777B\u777C\u7781\u7782\u7783\u7786", 5, "\u778F\u7790\u7793", 11, "\u77A1\u77A3\u77A4\u77A6\u77A8\u77AB\u77AD\u77AE\u77AF\u77B1\u77B2\u77B4\u77B6", 4], + ["b280", "\u77BC\u77BE\u77C0", 12, "\u77CE", 8, "\u77D8\u77D9\u77DA\u77DD", 4, "\u77E4\u75C5\u5E76\u73BB\u83E0\u64AD\u62E8\u94B5\u6CE2\u535A\u52C3\u640F\u94C2\u7B94\u4F2F\u5E1B\u8236\u8116\u818A\u6E24\u6CCA\u9A73\u6355\u535C\u54FA\u8865\u57E0\u4E0D\u5E03\u6B65\u7C3F\u90E8\u6016\u64E6\u731C\u88C1\u6750\u624D\u8D22\u776C\u8E29\u91C7\u5F69\u83DC\u8521\u9910\u53C2\u8695\u6B8B\u60ED\u60E8\u707F\u82CD\u8231\u4ED3\u6CA7\u85CF\u64CD\u7CD9\u69FD\u66F9\u8349\u5395\u7B56\u4FA7\u518C\u6D4B\u5C42\u8E6D\u63D2\u53C9\u832C\u8336\u67E5\u78B4\u643D\u5BDF\u5C94\u5DEE\u8BE7\u62C6\u67F4\u8C7A\u6400\u63BA\u8749\u998B\u8C17\u7F20\u94F2\u4EA7\u9610\u98A4\u660C\u7316"], + ["b340", "\u77E6\u77E8\u77EA\u77EF\u77F0\u77F1\u77F2\u77F4\u77F5\u77F7\u77F9\u77FA\u77FB\u77FC\u7803", 5, "\u780A\u780B\u780E\u780F\u7810\u7813\u7815\u7819\u781B\u781E\u7820\u7821\u7822\u7824\u7828\u782A\u782B\u782E\u782F\u7831\u7832\u7833\u7835\u7836\u783D\u783F\u7841\u7842\u7843\u7844\u7846\u7848\u7849\u784A\u784B\u784D\u784F\u7851\u7853\u7854\u7858\u7859\u785A"], + ["b380", "\u785B\u785C\u785E", 11, "\u786F", 7, "\u7878\u7879\u787A\u787B\u787D", 6, "\u573A\u5C1D\u5E38\u957F\u507F\u80A0\u5382\u655E\u7545\u5531\u5021\u8D85\u6284\u949E\u671D\u5632\u6F6E\u5DE2\u5435\u7092\u8F66\u626F\u64A4\u63A3\u5F7B\u6F88\u90F4\u81E3\u8FB0\u5C18\u6668\u5FF1\u6C89\u9648\u8D81\u886C\u6491\u79F0\u57CE\u6A59\u6210\u5448\u4E58\u7A0B\u60E9\u6F84\u8BDA\u627F\u901E\u9A8B\u79E4\u5403\u75F4\u6301\u5319\u6C60\u8FDF\u5F1B\u9A70\u803B\u9F7F\u4F88\u5C3A\u8D64\u7FC5\u65A5\u70BD\u5145\u51B2\u866B\u5D07\u5BA0\u62BD\u916C\u7574\u8E0C\u7A20\u6101\u7B79\u4EC7\u7EF8\u7785\u4E11\u81ED\u521D\u51FA\u6A71\u53A8\u8E87\u9504\u96CF\u6EC1\u9664\u695A"], + ["b440", "\u7884\u7885\u7886\u7888\u788A\u788B\u788F\u7890\u7892\u7894\u7895\u7896\u7899\u789D\u789E\u78A0\u78A2\u78A4\u78A6\u78A8", 7, "\u78B5\u78B6\u78B7\u78B8\u78BA\u78BB\u78BC\u78BD\u78BF\u78C0\u78C2\u78C3\u78C4\u78C6\u78C7\u78C8\u78CC\u78CD\u78CE\u78CF\u78D1\u78D2\u78D3\u78D6\u78D7\u78D8\u78DA", 9], + ["b480", "\u78E4\u78E5\u78E6\u78E7\u78E9\u78EA\u78EB\u78ED", 4, "\u78F3\u78F5\u78F6\u78F8\u78F9\u78FB", 5, "\u7902\u7903\u7904\u7906", 6, "\u7840\u50A8\u77D7\u6410\u89E6\u5904\u63E3\u5DDD\u7A7F\u693D\u4F20\u8239\u5598\u4E32\u75AE\u7A97\u5E62\u5E8A\u95EF\u521B\u5439\u708A\u6376\u9524\u5782\u6625\u693F\u9187\u5507\u6DF3\u7EAF\u8822\u6233\u7EF0\u75B5\u8328\u78C1\u96CC\u8F9E\u6148\u74F7\u8BCD\u6B64\u523A\u8D50\u6B21\u806A\u8471\u56F1\u5306\u4ECE\u4E1B\u51D1\u7C97\u918B\u7C07\u4FC3\u8E7F\u7BE1\u7A9C\u6467\u5D14\u50AC\u8106\u7601\u7CB9\u6DEC\u7FE0\u6751\u5B58\u5BF8\u78CB\u64AE\u6413\u63AA\u632B\u9519\u642D\u8FBE\u7B54\u7629\u6253\u5927\u5446\u6B79\u50A3\u6234\u5E26\u6B86\u4EE3\u8D37\u888B\u5F85\u902E"], + ["b540", "\u790D", 5, "\u7914", 9, "\u791F", 4, "\u7925", 14, "\u7935", 4, "\u793D\u793F\u7942\u7943\u7944\u7945\u7947\u794A", 8, "\u7954\u7955\u7958\u7959\u7961\u7963"], + ["b580", "\u7964\u7966\u7969\u796A\u796B\u796C\u796E\u7970", 6, "\u7979\u797B", 4, "\u7982\u7983\u7986\u7987\u7988\u7989\u798B\u798C\u798D\u798E\u7990\u7991\u7992\u6020\u803D\u62C5\u4E39\u5355\u90F8\u63B8\u80C6\u65E6\u6C2E\u4F46\u60EE\u6DE1\u8BDE\u5F39\u86CB\u5F53\u6321\u515A\u8361\u6863\u5200\u6363\u8E48\u5012\u5C9B\u7977\u5BFC\u5230\u7A3B\u60BC\u9053\u76D7\u5FB7\u5F97\u7684\u8E6C\u706F\u767B\u7B49\u77AA\u51F3\u9093\u5824\u4F4E\u6EF4\u8FEA\u654C\u7B1B\u72C4\u6DA4\u7FDF\u5AE1\u62B5\u5E95\u5730\u8482\u7B2C\u5E1D\u5F1F\u9012\u7F14\u98A0\u6382\u6EC7\u7898\u70B9\u5178\u975B\u57AB\u7535\u4F43\u7538\u5E97\u60E6\u5960\u6DC0\u6BBF\u7889\u53FC\u96D5\u51CB\u5201\u6389\u540A\u9493\u8C03\u8DCC\u7239\u789F\u8776\u8FED\u8C0D\u53E0"], + ["b640", "\u7993", 6, "\u799B", 11, "\u79A8", 10, "\u79B4", 4, "\u79BC\u79BF\u79C2\u79C4\u79C5\u79C7\u79C8\u79CA\u79CC\u79CE\u79CF\u79D0\u79D3\u79D4\u79D6\u79D7\u79D9", 5, "\u79E0\u79E1\u79E2\u79E5\u79E8\u79EA"], + ["b680", "\u79EC\u79EE\u79F1", 6, "\u79F9\u79FA\u79FC\u79FE\u79FF\u7A01\u7A04\u7A05\u7A07\u7A08\u7A09\u7A0A\u7A0C\u7A0F", 4, "\u7A15\u7A16\u7A18\u7A19\u7A1B\u7A1C\u4E01\u76EF\u53EE\u9489\u9876\u9F0E\u952D\u5B9A\u8BA2\u4E22\u4E1C\u51AC\u8463\u61C2\u52A8\u680B\u4F97\u606B\u51BB\u6D1E\u515C\u6296\u6597\u9661\u8C46\u9017\u75D8\u90FD\u7763\u6BD2\u728A\u72EC\u8BFB\u5835\u7779\u8D4C\u675C\u9540\u809A\u5EA6\u6E21\u5992\u7AEF\u77ED\u953B\u6BB5\u65AD\u7F0E\u5806\u5151\u961F\u5BF9\u58A9\u5428\u8E72\u6566\u987F\u56E4\u949D\u76FE\u9041\u6387\u54C6\u591A\u593A\u579B\u8EB2\u6735\u8DFA\u8235\u5241\u60F0\u5815\u86FE\u5CE8\u9E45\u4FC4\u989D\u8BB9\u5A25\u6076\u5384\u627C\u904F\u9102\u997F\u6069\u800C\u513F\u8033\u5C14\u9975\u6D31\u4E8C"], + ["b740", "\u7A1D\u7A1F\u7A21\u7A22\u7A24", 14, "\u7A34\u7A35\u7A36\u7A38\u7A3A\u7A3E\u7A40", 5, "\u7A47", 9, "\u7A52", 4, "\u7A58", 16], + ["b780", "\u7A69", 6, "\u7A71\u7A72\u7A73\u7A75\u7A7B\u7A7C\u7A7D\u7A7E\u7A82\u7A85\u7A87\u7A89\u7A8A\u7A8B\u7A8C\u7A8E\u7A8F\u7A90\u7A93\u7A94\u7A99\u7A9A\u7A9B\u7A9E\u7AA1\u7AA2\u8D30\u53D1\u7F5A\u7B4F\u4F10\u4E4F\u9600\u6CD5\u73D0\u85E9\u5E06\u756A\u7FFB\u6A0A\u77FE\u9492\u7E41\u51E1\u70E6\u53CD\u8FD4\u8303\u8D29\u72AF\u996D\u6CDB\u574A\u82B3\u65B9\u80AA\u623F\u9632\u59A8\u4EFF\u8BBF\u7EBA\u653E\u83F2\u975E\u5561\u98DE\u80A5\u532A\u8BFD\u5420\u80BA\u5E9F\u6CB8\u8D39\u82AC\u915A\u5429\u6C1B\u5206\u7EB7\u575F\u711A\u6C7E\u7C89\u594B\u4EFD\u5FFF\u6124\u7CAA\u4E30\u5C01\u67AB\u8702\u5CF0\u950B\u98CE\u75AF\u70FD\u9022\u51AF\u7F1D\u8BBD\u5949\u51E4\u4F5B\u5426\u592B\u6577\u80A4\u5B75\u6276\u62C2\u8F90\u5E45\u6C1F\u7B26\u4F0F\u4FD8\u670D"], + ["b840", "\u7AA3\u7AA4\u7AA7\u7AA9\u7AAA\u7AAB\u7AAE", 4, "\u7AB4", 10, "\u7AC0", 10, "\u7ACC", 9, "\u7AD7\u7AD8\u7ADA\u7ADB\u7ADC\u7ADD\u7AE1\u7AE2\u7AE4\u7AE7", 5, "\u7AEE\u7AF0\u7AF1\u7AF2\u7AF3"], + ["b880", "\u7AF4", 4, "\u7AFB\u7AFC\u7AFE\u7B00\u7B01\u7B02\u7B05\u7B07\u7B09\u7B0C\u7B0D\u7B0E\u7B10\u7B12\u7B13\u7B16\u7B17\u7B18\u7B1A\u7B1C\u7B1D\u7B1F\u7B21\u7B22\u7B23\u7B27\u7B29\u7B2D\u6D6E\u6DAA\u798F\u88B1\u5F17\u752B\u629A\u8F85\u4FEF\u91DC\u65A7\u812F\u8151\u5E9C\u8150\u8D74\u526F\u8986\u8D4B\u590D\u5085\u4ED8\u961C\u7236\u8179\u8D1F\u5BCC\u8BA3\u9644\u5987\u7F1A\u5490\u5676\u560E\u8BE5\u6539\u6982\u9499\u76D6\u6E89\u5E72\u7518\u6746\u67D1\u7AFF\u809D\u8D76\u611F\u79C6\u6562\u8D63\u5188\u521A\u94A2\u7F38\u809B\u7EB2\u5C97\u6E2F\u6760\u7BD9\u768B\u9AD8\u818F\u7F94\u7CD5\u641E\u9550\u7A3F\u544A\u54E5\u6B4C\u6401\u6208\u9E3D\u80F3\u7599\u5272\u9769\u845B\u683C\u86E4\u9601\u9694\u94EC\u4E2A\u5404\u7ED9\u6839\u8DDF\u8015\u66F4\u5E9A\u7FB9"], + ["b940", "\u7B2F\u7B30\u7B32\u7B34\u7B35\u7B36\u7B37\u7B39\u7B3B\u7B3D\u7B3F", 5, "\u7B46\u7B48\u7B4A\u7B4D\u7B4E\u7B53\u7B55\u7B57\u7B59\u7B5C\u7B5E\u7B5F\u7B61\u7B63", 10, "\u7B6F\u7B70\u7B73\u7B74\u7B76\u7B78\u7B7A\u7B7C\u7B7D\u7B7F\u7B81\u7B82\u7B83\u7B84\u7B86", 6, "\u7B8E\u7B8F"], + ["b980", "\u7B91\u7B92\u7B93\u7B96\u7B98\u7B99\u7B9A\u7B9B\u7B9E\u7B9F\u7BA0\u7BA3\u7BA4\u7BA5\u7BAE\u7BAF\u7BB0\u7BB2\u7BB3\u7BB5\u7BB6\u7BB7\u7BB9", 7, "\u7BC2\u7BC3\u7BC4\u57C2\u803F\u6897\u5DE5\u653B\u529F\u606D\u9F9A\u4F9B\u8EAC\u516C\u5BAB\u5F13\u5DE9\u6C5E\u62F1\u8D21\u5171\u94A9\u52FE\u6C9F\u82DF\u72D7\u57A2\u6784\u8D2D\u591F\u8F9C\u83C7\u5495\u7B8D\u4F30\u6CBD\u5B64\u59D1\u9F13\u53E4\u86CA\u9AA8\u8C37\u80A1\u6545\u987E\u56FA\u96C7\u522E\u74DC\u5250\u5BE1\u6302\u8902\u4E56\u62D0\u602A\u68FA\u5173\u5B98\u51A0\u89C2\u7BA1\u9986\u7F50\u60EF\u704C\u8D2F\u5149\u5E7F\u901B\u7470\u89C4\u572D\u7845\u5F52\u9F9F\u95FA\u8F68\u9B3C\u8BE1\u7678\u6842\u67DC\u8DEA\u8D35\u523D\u8F8A\u6EDA\u68CD\u9505\u90ED\u56FD\u679C\u88F9\u8FC7\u54C8"], + ["ba40", "\u7BC5\u7BC8\u7BC9\u7BCA\u7BCB\u7BCD\u7BCE\u7BCF\u7BD0\u7BD2\u7BD4", 4, "\u7BDB\u7BDC\u7BDE\u7BDF\u7BE0\u7BE2\u7BE3\u7BE4\u7BE7\u7BE8\u7BE9\u7BEB\u7BEC\u7BED\u7BEF\u7BF0\u7BF2", 4, "\u7BF8\u7BF9\u7BFA\u7BFB\u7BFD\u7BFF", 7, "\u7C08\u7C09\u7C0A\u7C0D\u7C0E\u7C10", 5, "\u7C17\u7C18\u7C19"], + ["ba80", "\u7C1A", 4, "\u7C20", 5, "\u7C28\u7C29\u7C2B", 12, "\u7C39", 5, "\u7C42\u9AB8\u5B69\u6D77\u6C26\u4EA5\u5BB3\u9A87\u9163\u61A8\u90AF\u97E9\u542B\u6DB5\u5BD2\u51FD\u558A\u7F55\u7FF0\u64BC\u634D\u65F1\u61BE\u608D\u710A\u6C57\u6C49\u592F\u676D\u822A\u58D5\u568E\u8C6A\u6BEB\u90DD\u597D\u8017\u53F7\u6D69\u5475\u559D\u8377\u83CF\u6838\u79BE\u548C\u4F55\u5408\u76D2\u8C89\u9602\u6CB3\u6DB8\u8D6B\u8910\u9E64\u8D3A\u563F\u9ED1\u75D5\u5F88\u72E0\u6068\u54FC\u4EA8\u6A2A\u8861\u6052\u8F70\u54C4\u70D8\u8679\u9E3F\u6D2A\u5B8F\u5F18\u7EA2\u5589\u4FAF\u7334\u543C\u539A\u5019\u540E\u547C\u4E4E\u5FFD\u745A\u58F6\u846B\u80E1\u8774\u72D0\u7CCA\u6E56"], + ["bb40", "\u7C43", 9, "\u7C4E", 36, "\u7C75", 5, "\u7C7E", 9], + ["bb80", "\u7C88\u7C8A", 6, "\u7C93\u7C94\u7C96\u7C99\u7C9A\u7C9B\u7CA0\u7CA1\u7CA3\u7CA6\u7CA7\u7CA8\u7CA9\u7CAB\u7CAC\u7CAD\u7CAF\u7CB0\u7CB4", 4, "\u7CBA\u7CBB\u5F27\u864E\u552C\u62A4\u4E92\u6CAA\u6237\u82B1\u54D7\u534E\u733E\u6ED1\u753B\u5212\u5316\u8BDD\u69D0\u5F8A\u6000\u6DEE\u574F\u6B22\u73AF\u6853\u8FD8\u7F13\u6362\u60A3\u5524\u75EA\u8C62\u7115\u6DA3\u5BA6\u5E7B\u8352\u614C\u9EC4\u78FA\u8757\u7C27\u7687\u51F0\u60F6\u714C\u6643\u5E4C\u604D\u8C0E\u7070\u6325\u8F89\u5FBD\u6062\u86D4\u56DE\u6BC1\u6094\u6167\u5349\u60E0\u6666\u8D3F\u79FD\u4F1A\u70E9\u6C47\u8BB3\u8BF2\u7ED8\u8364\u660F\u5A5A\u9B42\u6D51\u6DF7\u8C41\u6D3B\u4F19\u706B\u83B7\u6216\u60D1\u970D\u8D27\u7978\u51FB\u573E\u57FA\u673A\u7578\u7A3D\u79EF\u7B95"], + ["bc40", "\u7CBF\u7CC0\u7CC2\u7CC3\u7CC4\u7CC6\u7CC9\u7CCB\u7CCE", 6, "\u7CD8\u7CDA\u7CDB\u7CDD\u7CDE\u7CE1", 6, "\u7CE9", 5, "\u7CF0", 7, "\u7CF9\u7CFA\u7CFC", 13, "\u7D0B", 5], + ["bc80", "\u7D11", 14, "\u7D21\u7D23\u7D24\u7D25\u7D26\u7D28\u7D29\u7D2A\u7D2C\u7D2D\u7D2E\u7D30", 6, "\u808C\u9965\u8FF9\u6FC0\u8BA5\u9E21\u59EC\u7EE9\u7F09\u5409\u6781\u68D8\u8F91\u7C4D\u96C6\u53CA\u6025\u75BE\u6C72\u5373\u5AC9\u7EA7\u6324\u51E0\u810A\u5DF1\u84DF\u6280\u5180\u5B63\u4F0E\u796D\u5242\u60B8\u6D4E\u5BC4\u5BC2\u8BA1\u8BB0\u65E2\u5FCC\u9645\u5993\u7EE7\u7EAA\u5609\u67B7\u5939\u4F73\u5BB6\u52A0\u835A\u988A\u8D3E\u7532\u94BE\u5047\u7A3C\u4EF7\u67B6\u9A7E\u5AC1\u6B7C\u76D1\u575A\u5C16\u7B3A\u95F4\u714E\u517C\u80A9\u8270\u5978\u7F04\u8327\u68C0\u67EC\u78B1\u7877\u62E3\u6361\u7B80\u4FED\u526A\u51CF\u8350\u69DB\u9274\u8DF5\u8D31\u89C1\u952E\u7BAD\u4EF6"], + ["bd40", "\u7D37", 54, "\u7D6F", 7], + ["bd80", "\u7D78", 32, "\u5065\u8230\u5251\u996F\u6E10\u6E85\u6DA7\u5EFA\u50F5\u59DC\u5C06\u6D46\u6C5F\u7586\u848B\u6868\u5956\u8BB2\u5320\u9171\u964D\u8549\u6912\u7901\u7126\u80F6\u4EA4\u90CA\u6D47\u9A84\u5A07\u56BC\u6405\u94F0\u77EB\u4FA5\u811A\u72E1\u89D2\u997A\u7F34\u7EDE\u527F\u6559\u9175\u8F7F\u8F83\u53EB\u7A96\u63ED\u63A5\u7686\u79F8\u8857\u9636\u622A\u52AB\u8282\u6854\u6770\u6377\u776B\u7AED\u6D01\u7ED3\u89E3\u59D0\u6212\u85C9\u82A5\u754C\u501F\u4ECB\u75A5\u8BEB\u5C4A\u5DFE\u7B4B\u65A4\u91D1\u4ECA\u6D25\u895F\u7D27\u9526\u4EC5\u8C28\u8FDB\u9773\u664B\u7981\u8FD1\u70EC\u6D78"], + ["be40", "\u7D99", 12, "\u7DA7", 6, "\u7DAF", 42], + ["be80", "\u7DDA", 32, "\u5C3D\u52B2\u8346\u5162\u830E\u775B\u6676\u9CB8\u4EAC\u60CA\u7CBE\u7CB3\u7ECF\u4E95\u8B66\u666F\u9888\u9759\u5883\u656C\u955C\u5F84\u75C9\u9756\u7ADF\u7ADE\u51C0\u70AF\u7A98\u63EA\u7A76\u7EA0\u7396\u97ED\u4E45\u7078\u4E5D\u9152\u53A9\u6551\u65E7\u81FC\u8205\u548E\u5C31\u759A\u97A0\u62D8\u72D9\u75BD\u5C45\u9A79\u83CA\u5C40\u5480\u77E9\u4E3E\u6CAE\u805A\u62D2\u636E\u5DE8\u5177\u8DDD\u8E1E\u952F\u4FF1\u53E5\u60E7\u70AC\u5267\u6350\u9E43\u5A1F\u5026\u7737\u5377\u7EE2\u6485\u652B\u6289\u6398\u5014\u7235\u89C9\u51B3\u8BC0\u7EDD\u5747\u83CC\u94A7\u519B\u541B\u5CFB"], + ["bf40", "\u7DFB", 62], + ["bf80", "\u7E3A\u7E3C", 4, "\u7E42", 4, "\u7E48", 21, "\u4FCA\u7AE3\u6D5A\u90E1\u9A8F\u5580\u5496\u5361\u54AF\u5F00\u63E9\u6977\u51EF\u6168\u520A\u582A\u52D8\u574E\u780D\u770B\u5EB7\u6177\u7CE0\u625B\u6297\u4EA2\u7095\u8003\u62F7\u70E4\u9760\u5777\u82DB\u67EF\u68F5\u78D5\u9897\u79D1\u58F3\u54B3\u53EF\u6E34\u514B\u523B\u5BA2\u8BFE\u80AF\u5543\u57A6\u6073\u5751\u542D\u7A7A\u6050\u5B54\u63A7\u62A0\u53E3\u6263\u5BC7\u67AF\u54ED\u7A9F\u82E6\u9177\u5E93\u88E4\u5938\u57AE\u630E\u8DE8\u80EF\u5757\u7B77\u4FA9\u5FEB\u5BBD\u6B3E\u5321\u7B50\u72C2\u6846\u77FF\u7736\u65F7\u51B5\u4E8F\u76D4\u5CBF\u7AA5\u8475\u594E\u9B41\u5080"], + ["c040", "\u7E5E", 35, "\u7E83", 23, "\u7E9C\u7E9D\u7E9E"], + ["c080", "\u7EAE\u7EB4\u7EBB\u7EBC\u7ED6\u7EE4\u7EEC\u7EF9\u7F0A\u7F10\u7F1E\u7F37\u7F39\u7F3B", 6, "\u7F43\u7F46", 9, "\u7F52\u7F53\u9988\u6127\u6E83\u5764\u6606\u6346\u56F0\u62EC\u6269\u5ED3\u9614\u5783\u62C9\u5587\u8721\u814A\u8FA3\u5566\u83B1\u6765\u8D56\u84DD\u5A6A\u680F\u62E6\u7BEE\u9611\u5170\u6F9C\u8C30\u63FD\u89C8\u61D2\u7F06\u70C2\u6EE5\u7405\u6994\u72FC\u5ECA\u90CE\u6717\u6D6A\u635E\u52B3\u7262\u8001\u4F6C\u59E5\u916A\u70D9\u6D9D\u52D2\u4E50\u96F7\u956D\u857E\u78CA\u7D2F\u5121\u5792\u64C2\u808B\u7C7B\u6CEA\u68F1\u695E\u51B7\u5398\u68A8\u7281\u9ECE\u7BF1\u72F8\u79BB\u6F13\u7406\u674E\u91CC\u9CA4\u793C\u8389\u8354\u540F\u6817\u4E3D\u5389\u52B1\u783E\u5386\u5229\u5088\u4F8B\u4FD0"], + ["c140", "\u7F56\u7F59\u7F5B\u7F5C\u7F5D\u7F5E\u7F60\u7F63", 4, "\u7F6B\u7F6C\u7F6D\u7F6F\u7F70\u7F73\u7F75\u7F76\u7F77\u7F78\u7F7A\u7F7B\u7F7C\u7F7D\u7F7F\u7F80\u7F82", 7, "\u7F8B\u7F8D\u7F8F", 4, "\u7F95", 4, "\u7F9B\u7F9C\u7FA0\u7FA2\u7FA3\u7FA5\u7FA6\u7FA8", 6, "\u7FB1"], + ["c180", "\u7FB3", 4, "\u7FBA\u7FBB\u7FBE\u7FC0\u7FC2\u7FC3\u7FC4\u7FC6\u7FC7\u7FC8\u7FC9\u7FCB\u7FCD\u7FCF", 4, "\u7FD6\u7FD7\u7FD9", 5, "\u7FE2\u7FE3\u75E2\u7ACB\u7C92\u6CA5\u96B6\u529B\u7483\u54E9\u4FE9\u8054\u83B2\u8FDE\u9570\u5EC9\u601C\u6D9F\u5E18\u655B\u8138\u94FE\u604B\u70BC\u7EC3\u7CAE\u51C9\u6881\u7CB1\u826F\u4E24\u8F86\u91CF\u667E\u4EAE\u8C05\u64A9\u804A\u50DA\u7597\u71CE\u5BE5\u8FBD\u6F66\u4E86\u6482\u9563\u5ED6\u6599\u5217\u88C2\u70C8\u52A3\u730E\u7433\u6797\u78F7\u9716\u4E34\u90BB\u9CDE\u6DCB\u51DB\u8D41\u541D\u62CE\u73B2\u83F1\u96F6\u9F84\u94C3\u4F36\u7F9A\u51CC\u7075\u9675\u5CAD\u9886\u53E6\u4EE4\u6E9C\u7409\u69B4\u786B\u998F\u7559\u5218\u7624\u6D41\u67F3\u516D\u9F99\u804B\u5499\u7B3C\u7ABF"], + ["c240", "\u7FE4\u7FE7\u7FE8\u7FEA\u7FEB\u7FEC\u7FED\u7FEF\u7FF2\u7FF4", 6, "\u7FFD\u7FFE\u7FFF\u8002\u8007\u8008\u8009\u800A\u800E\u800F\u8011\u8013\u801A\u801B\u801D\u801E\u801F\u8021\u8023\u8024\u802B", 5, "\u8032\u8034\u8039\u803A\u803C\u803E\u8040\u8041\u8044\u8045\u8047\u8048\u8049\u804E\u804F\u8050\u8051\u8053\u8055\u8056\u8057"], + ["c280", "\u8059\u805B", 13, "\u806B", 5, "\u8072", 11, "\u9686\u5784\u62E2\u9647\u697C\u5A04\u6402\u7BD3\u6F0F\u964B\u82A6\u5362\u9885\u5E90\u7089\u63B3\u5364\u864F\u9C81\u9E93\u788C\u9732\u8DEF\u8D42\u9E7F\u6F5E\u7984\u5F55\u9646\u622E\u9A74\u5415\u94DD\u4FA3\u65C5\u5C65\u5C61\u7F15\u8651\u6C2F\u5F8B\u7387\u6EE4\u7EFF\u5CE6\u631B\u5B6A\u6EE6\u5375\u4E71\u63A0\u7565\u62A1\u8F6E\u4F26\u4ED1\u6CA6\u7EB6\u8BBA\u841D\u87BA\u7F57\u903B\u9523\u7BA9\u9AA1\u88F8\u843D\u6D1B\u9A86\u7EDC\u5988\u9EBB\u739B\u7801\u8682\u9A6C\u9A82\u561B\u5417\u57CB\u4E70\u9EA6\u5356\u8FC8\u8109\u7792\u9992\u86EE\u6EE1\u8513\u66FC\u6162\u6F2B"], + ["c340", "\u807E\u8081\u8082\u8085\u8088\u808A\u808D", 5, "\u8094\u8095\u8097\u8099\u809E\u80A3\u80A6\u80A7\u80A8\u80AC\u80B0\u80B3\u80B5\u80B6\u80B8\u80B9\u80BB\u80C5\u80C7", 4, "\u80CF", 6, "\u80D8\u80DF\u80E0\u80E2\u80E3\u80E6\u80EE\u80F5\u80F7\u80F9\u80FB\u80FE\u80FF\u8100\u8101\u8103\u8104\u8105\u8107\u8108\u810B"], + ["c380", "\u810C\u8115\u8117\u8119\u811B\u811C\u811D\u811F", 12, "\u812D\u812E\u8130\u8133\u8134\u8135\u8137\u8139", 4, "\u813F\u8C29\u8292\u832B\u76F2\u6C13\u5FD9\u83BD\u732B\u8305\u951A\u6BDB\u77DB\u94C6\u536F\u8302\u5192\u5E3D\u8C8C\u8D38\u4E48\u73AB\u679A\u6885\u9176\u9709\u7164\u6CA1\u7709\u5A92\u9541\u6BCF\u7F8E\u6627\u5BD0\u59B9\u5A9A\u95E8\u95F7\u4EEC\u840C\u8499\u6AAC\u76DF\u9530\u731B\u68A6\u5B5F\u772F\u919A\u9761\u7CDC\u8FF7\u8C1C\u5F25\u7C73\u79D8\u89C5\u6CCC\u871C\u5BC6\u5E42\u68C9\u7720\u7EF5\u5195\u514D\u52C9\u5A29\u7F05\u9762\u82D7\u63CF\u7784\u85D0\u79D2\u6E3A\u5E99\u5999\u8511\u706D\u6C11\u62BF\u76BF\u654F\u60AF\u95FD\u660E\u879F\u9E23\u94ED\u540D\u547D\u8C2C\u6478"], + ["c440", "\u8140", 5, "\u8147\u8149\u814D\u814E\u814F\u8152\u8156\u8157\u8158\u815B", 4, "\u8161\u8162\u8163\u8164\u8166\u8168\u816A\u816B\u816C\u816F\u8172\u8173\u8175\u8176\u8177\u8178\u8181\u8183", 4, "\u8189\u818B\u818C\u818D\u818E\u8190\u8192", 5, "\u8199\u819A\u819E", 4, "\u81A4\u81A5"], + ["c480", "\u81A7\u81A9\u81AB", 7, "\u81B4", 5, "\u81BC\u81BD\u81BE\u81BF\u81C4\u81C5\u81C7\u81C8\u81C9\u81CB\u81CD", 6, "\u6479\u8611\u6A21\u819C\u78E8\u6469\u9B54\u62B9\u672B\u83AB\u58A8\u9ED8\u6CAB\u6F20\u5BDE\u964C\u8C0B\u725F\u67D0\u62C7\u7261\u4EA9\u59C6\u6BCD\u5893\u66AE\u5E55\u52DF\u6155\u6728\u76EE\u7766\u7267\u7A46\u62FF\u54EA\u5450\u94A0\u90A3\u5A1C\u7EB3\u6C16\u4E43\u5976\u8010\u5948\u5357\u7537\u96BE\u56CA\u6320\u8111\u607C\u95F9\u6DD6\u5462\u9981\u5185\u5AE9\u80FD\u59AE\u9713\u502A\u6CE5\u5C3C\u62DF\u4F60\u533F\u817B\u9006\u6EBA\u852B\u62C8\u5E74\u78BE\u64B5\u637B\u5FF5\u5A18\u917F\u9E1F\u5C3F\u634F\u8042\u5B7D\u556E\u954A\u954D\u6D85\u60A8\u67E0\u72DE\u51DD\u5B81"], + ["c540", "\u81D4", 14, "\u81E4\u81E5\u81E6\u81E8\u81E9\u81EB\u81EE", 4, "\u81F5", 5, "\u81FD\u81FF\u8203\u8207", 4, "\u820E\u820F\u8211\u8213\u8215", 5, "\u821D\u8220\u8224\u8225\u8226\u8227\u8229\u822E\u8232\u823A\u823C\u823D\u823F"], + ["c580", "\u8240\u8241\u8242\u8243\u8245\u8246\u8248\u824A\u824C\u824D\u824E\u8250", 7, "\u8259\u825B\u825C\u825D\u825E\u8260", 7, "\u8269\u62E7\u6CDE\u725B\u626D\u94AE\u7EBD\u8113\u6D53\u519C\u5F04\u5974\u52AA\u6012\u5973\u6696\u8650\u759F\u632A\u61E6\u7CEF\u8BFA\u54E6\u6B27\u9E25\u6BB4\u85D5\u5455\u5076\u6CA4\u556A\u8DB4\u722C\u5E15\u6015\u7436\u62CD\u6392\u724C\u5F98\u6E43\u6D3E\u6500\u6F58\u76D8\u78D0\u76FC\u7554\u5224\u53DB\u4E53\u5E9E\u65C1\u802A\u80D6\u629B\u5486\u5228\u70AE\u888D\u8DD1\u6CE1\u5478\u80DA\u57F9\u88F4\u8D54\u966A\u914D\u4F69\u6C9B\u55B7\u76C6\u7830\u62A8\u70F9\u6F8E\u5F6D\u84EC\u68DA\u787C\u7BF7\u81A8\u670B\u9E4F\u6367\u78B0\u576F\u7812\u9739\u6279\u62AB\u5288\u7435\u6BD7"], + ["c640", "\u826A\u826B\u826C\u826D\u8271\u8275\u8276\u8277\u8278\u827B\u827C\u8280\u8281\u8283\u8285\u8286\u8287\u8289\u828C\u8290\u8293\u8294\u8295\u8296\u829A\u829B\u829E\u82A0\u82A2\u82A3\u82A7\u82B2\u82B5\u82B6\u82BA\u82BB\u82BC\u82BF\u82C0\u82C2\u82C3\u82C5\u82C6\u82C9\u82D0\u82D6\u82D9\u82DA\u82DD\u82E2\u82E7\u82E8\u82E9\u82EA\u82EC\u82ED\u82EE\u82F0\u82F2\u82F3\u82F5\u82F6\u82F8"], + ["c680", "\u82FA\u82FC", 4, "\u830A\u830B\u830D\u8310\u8312\u8313\u8316\u8318\u8319\u831D", 9, "\u8329\u832A\u832E\u8330\u8332\u8337\u833B\u833D\u5564\u813E\u75B2\u76AE\u5339\u75DE\u50FB\u5C41\u8B6C\u7BC7\u504F\u7247\u9A97\u98D8\u6F02\u74E2\u7968\u6487\u77A5\u62FC\u9891\u8D2B\u54C1\u8058\u4E52\u576A\u82F9\u840D\u5E73\u51ED\u74F6\u8BC4\u5C4F\u5761\u6CFC\u9887\u5A46\u7834\u9B44\u8FEB\u7C95\u5256\u6251\u94FA\u4EC6\u8386\u8461\u83E9\u84B2\u57D4\u6734\u5703\u666E\u6D66\u8C31\u66DD\u7011\u671F\u6B3A\u6816\u621A\u59BB\u4E03\u51C4\u6F06\u67D2\u6C8F\u5176\u68CB\u5947\u6B67\u7566\u5D0E\u8110\u9F50\u65D7\u7948\u7941\u9A91\u8D77\u5C82\u4E5E\u4F01\u542F\u5951\u780C\u5668\u6C14\u8FC4\u5F03\u6C7D\u6CE3\u8BAB\u6390"], + ["c740", "\u833E\u833F\u8341\u8342\u8344\u8345\u8348\u834A", 4, "\u8353\u8355", 4, "\u835D\u8362\u8370", 6, "\u8379\u837A\u837E", 6, "\u8387\u8388\u838A\u838B\u838C\u838D\u838F\u8390\u8391\u8394\u8395\u8396\u8397\u8399\u839A\u839D\u839F\u83A1", 6, "\u83AC\u83AD\u83AE"], + ["c780", "\u83AF\u83B5\u83BB\u83BE\u83BF\u83C2\u83C3\u83C4\u83C6\u83C8\u83C9\u83CB\u83CD\u83CE\u83D0\u83D1\u83D2\u83D3\u83D5\u83D7\u83D9\u83DA\u83DB\u83DE\u83E2\u83E3\u83E4\u83E6\u83E7\u83E8\u83EB\u83EC\u83ED\u6070\u6D3D\u7275\u6266\u948E\u94C5\u5343\u8FC1\u7B7E\u4EDF\u8C26\u4E7E\u9ED4\u94B1\u94B3\u524D\u6F5C\u9063\u6D45\u8C34\u5811\u5D4C\u6B20\u6B49\u67AA\u545B\u8154\u7F8C\u5899\u8537\u5F3A\u62A2\u6A47\u9539\u6572\u6084\u6865\u77A7\u4E54\u4FA8\u5DE7\u9798\u64AC\u7FD8\u5CED\u4FCF\u7A8D\u5207\u8304\u4E14\u602F\u7A83\u94A6\u4FB5\u4EB2\u79E6\u7434\u52E4\u82B9\u64D2\u79BD\u5BDD\u6C81\u9752\u8F7B\u6C22\u503E\u537F\u6E05\u64CE\u6674\u6C30\u60C5\u9877\u8BF7\u5E86\u743C\u7A77\u79CB\u4E18\u90B1\u7403\u6C42\u56DA\u914B\u6CC5\u8D8B\u533A\u86C6\u66F2\u8EAF\u5C48\u9A71\u6E20"], + ["c840", "\u83EE\u83EF\u83F3", 4, "\u83FA\u83FB\u83FC\u83FE\u83FF\u8400\u8402\u8405\u8407\u8408\u8409\u840A\u8410\u8412", 5, "\u8419\u841A\u841B\u841E", 5, "\u8429", 7, "\u8432", 5, "\u8439\u843A\u843B\u843E", 7, "\u8447\u8448\u8449"], + ["c880", "\u844A", 6, "\u8452", 4, "\u8458\u845D\u845E\u845F\u8460\u8462\u8464", 4, "\u846A\u846E\u846F\u8470\u8472\u8474\u8477\u8479\u847B\u847C\u53D6\u5A36\u9F8B\u8DA3\u53BB\u5708\u98A7\u6743\u919B\u6CC9\u5168\u75CA\u62F3\u72AC\u5238\u529D\u7F3A\u7094\u7638\u5374\u9E4A\u69B7\u786E\u96C0\u88D9\u7FA4\u7136\u71C3\u5189\u67D3\u74E4\u58E4\u6518\u56B7\u8BA9\u9976\u6270\u7ED5\u60F9\u70ED\u58EC\u4EC1\u4EBA\u5FCD\u97E7\u4EFB\u8BA4\u5203\u598A\u7EAB\u6254\u4ECD\u65E5\u620E\u8338\u84C9\u8363\u878D\u7194\u6EB6\u5BB9\u7ED2\u5197\u63C9\u67D4\u8089\u8339\u8815\u5112\u5B7A\u5982\u8FB1\u4E73\u6C5D\u5165\u8925\u8F6F\u962E\u854A\u745E\u9510\u95F0\u6DA6\u82E5\u5F31\u6492\u6D12\u8428\u816E\u9CC3\u585E\u8D5B\u4E09\u53C1"], + ["c940", "\u847D", 4, "\u8483\u8484\u8485\u8486\u848A\u848D\u848F", 7, "\u8498\u849A\u849B\u849D\u849E\u849F\u84A0\u84A2", 12, "\u84B0\u84B1\u84B3\u84B5\u84B6\u84B7\u84BB\u84BC\u84BE\u84C0\u84C2\u84C3\u84C5\u84C6\u84C7\u84C8\u84CB\u84CC\u84CE\u84CF\u84D2\u84D4\u84D5\u84D7"], + ["c980", "\u84D8", 4, "\u84DE\u84E1\u84E2\u84E4\u84E7", 4, "\u84ED\u84EE\u84EF\u84F1", 10, "\u84FD\u84FE\u8500\u8501\u8502\u4F1E\u6563\u6851\u55D3\u4E27\u6414\u9A9A\u626B\u5AC2\u745F\u8272\u6DA9\u68EE\u50E7\u838E\u7802\u6740\u5239\u6C99\u7EB1\u50BB\u5565\u715E\u7B5B\u6652\u73CA\u82EB\u6749\u5C71\u5220\u717D\u886B\u95EA\u9655\u64C5\u8D61\u81B3\u5584\u6C55\u6247\u7F2E\u5892\u4F24\u5546\u8D4F\u664C\u4E0A\u5C1A\u88F3\u68A2\u634E\u7A0D\u70E7\u828D\u52FA\u97F6\u5C11\u54E8\u90B5\u7ECD\u5962\u8D4A\u86C7\u820C\u820D\u8D66\u6444\u5C04\u6151\u6D89\u793E\u8BBE\u7837\u7533\u547B\u4F38\u8EAB\u6DF1\u5A20\u7EC5\u795E\u6C88\u5BA1\u5A76\u751A\u80BE\u614E\u6E17\u58F0\u751F\u7525\u7272\u5347\u7EF3"], + ["ca40", "\u8503", 8, "\u850D\u850E\u850F\u8510\u8512\u8514\u8515\u8516\u8518\u8519\u851B\u851C\u851D\u851E\u8520\u8522", 8, "\u852D", 9, "\u853E", 4, "\u8544\u8545\u8546\u8547\u854B", 10], + ["ca80", "\u8557\u8558\u855A\u855B\u855C\u855D\u855F", 4, "\u8565\u8566\u8567\u8569", 8, "\u8573\u8575\u8576\u8577\u8578\u857C\u857D\u857F\u8580\u8581\u7701\u76DB\u5269\u80DC\u5723\u5E08\u5931\u72EE\u65BD\u6E7F\u8BD7\u5C38\u8671\u5341\u77F3\u62FE\u65F6\u4EC0\u98DF\u8680\u5B9E\u8BC6\u53F2\u77E2\u4F7F\u5C4E\u9A76\u59CB\u5F0F\u793A\u58EB\u4E16\u67FF\u4E8B\u62ED\u8A93\u901D\u52BF\u662F\u55DC\u566C\u9002\u4ED5\u4F8D\u91CA\u9970\u6C0F\u5E02\u6043\u5BA4\u89C6\u8BD5\u6536\u624B\u9996\u5B88\u5BFF\u6388\u552E\u53D7\u7626\u517D\u852C\u67A2\u68B3\u6B8A\u6292\u8F93\u53D4\u8212\u6DD1\u758F\u4E66\u8D4E\u5B70\u719F\u85AF\u6691\u66D9\u7F72\u8700\u9ECD\u9F20\u5C5E\u672F\u8FF0\u6811\u675F\u620D\u7AD6\u5885\u5EB6\u6570\u6F31"], + ["cb40", "\u8582\u8583\u8586\u8588", 6, "\u8590", 10, "\u859D", 6, "\u85A5\u85A6\u85A7\u85A9\u85AB\u85AC\u85AD\u85B1", 5, "\u85B8\u85BA", 6, "\u85C2", 6, "\u85CA", 4, "\u85D1\u85D2"], + ["cb80", "\u85D4\u85D6", 5, "\u85DD", 6, "\u85E5\u85E6\u85E7\u85E8\u85EA", 14, "\u6055\u5237\u800D\u6454\u8870\u7529\u5E05\u6813\u62F4\u971C\u53CC\u723D\u8C01\u6C34\u7761\u7A0E\u542E\u77AC\u987A\u821C\u8BF4\u7855\u6714\u70C1\u65AF\u6495\u5636\u601D\u79C1\u53F8\u4E1D\u6B7B\u8086\u5BFA\u55E3\u56DB\u4F3A\u4F3C\u9972\u5DF3\u677E\u8038\u6002\u9882\u9001\u5B8B\u8BBC\u8BF5\u641C\u8258\u64DE\u55FD\u82CF\u9165\u4FD7\u7D20\u901F\u7C9F\u50F3\u5851\u6EAF\u5BBF\u8BC9\u8083\u9178\u849C\u7B97\u867D\u968B\u968F\u7EE5\u9AD3\u788E\u5C81\u7A57\u9042\u96A7\u795F\u5B59\u635F\u7B0B\u84D1\u68AD\u5506\u7F29\u7410\u7D22\u9501\u6240\u584C\u4ED6\u5B83\u5979\u5854"], + ["cc40", "\u85F9\u85FA\u85FC\u85FD\u85FE\u8600", 4, "\u8606", 10, "\u8612\u8613\u8614\u8615\u8617", 15, "\u8628\u862A", 13, "\u8639\u863A\u863B\u863D\u863E\u863F\u8640"], + ["cc80", "\u8641", 11, "\u8652\u8653\u8655", 4, "\u865B\u865C\u865D\u865F\u8660\u8661\u8663", 7, "\u736D\u631E\u8E4B\u8E0F\u80CE\u82D4\u62AC\u53F0\u6CF0\u915E\u592A\u6001\u6C70\u574D\u644A\u8D2A\u762B\u6EE9\u575B\u6A80\u75F0\u6F6D\u8C2D\u8C08\u5766\u6BEF\u8892\u78B3\u63A2\u53F9\u70AD\u6C64\u5858\u642A\u5802\u68E0\u819B\u5510\u7CD6\u5018\u8EBA\u6DCC\u8D9F\u70EB\u638F\u6D9B\u6ED4\u7EE6\u8404\u6843\u9003\u6DD8\u9676\u8BA8\u5957\u7279\u85E4\u817E\u75BC\u8A8A\u68AF\u5254\u8E22\u9511\u63D0\u9898\u8E44\u557C\u4F53\u66FF\u568F\u60D5\u6D95\u5243\u5C49\u5929\u6DFB\u586B\u7530\u751C\u606C\u8214\u8146\u6311\u6761\u8FE2\u773A\u8DF3\u8D34\u94C1\u5E16\u5385\u542C\u70C3"], + ["cd40", "\u866D\u866F\u8670\u8672", 6, "\u8683", 6, "\u868E", 4, "\u8694\u8696", 5, "\u869E", 4, "\u86A5\u86A6\u86AB\u86AD\u86AE\u86B2\u86B3\u86B7\u86B8\u86B9\u86BB", 4, "\u86C1\u86C2\u86C3\u86C5\u86C8\u86CC\u86CD\u86D2\u86D3\u86D5\u86D6\u86D7\u86DA\u86DC"], + ["cd80", "\u86DD\u86E0\u86E1\u86E2\u86E3\u86E5\u86E6\u86E7\u86E8\u86EA\u86EB\u86EC\u86EF\u86F5\u86F6\u86F7\u86FA\u86FB\u86FC\u86FD\u86FF\u8701\u8704\u8705\u8706\u870B\u870C\u870E\u870F\u8710\u8711\u8714\u8716\u6C40\u5EF7\u505C\u4EAD\u5EAD\u633A\u8247\u901A\u6850\u916E\u77B3\u540C\u94DC\u5F64\u7AE5\u6876\u6345\u7B52\u7EDF\u75DB\u5077\u6295\u5934\u900F\u51F8\u79C3\u7A81\u56FE\u5F92\u9014\u6D82\u5C60\u571F\u5410\u5154\u6E4D\u56E2\u63A8\u9893\u817F\u8715\u892A\u9000\u541E\u5C6F\u81C0\u62D6\u6258\u8131\u9E35\u9640\u9A6E\u9A7C\u692D\u59A5\u62D3\u553E\u6316\u54C7\u86D9\u6D3C\u5A03\u74E6\u889C\u6B6A\u5916\u8C4C\u5F2F\u6E7E\u73A9\u987D\u4E38\u70F7\u5B8C\u7897\u633D\u665A\u7696\u60CB\u5B9B\u5A49\u4E07\u8155\u6C6A\u738B\u4EA1\u6789\u7F51\u5F80\u65FA\u671B\u5FD8\u5984\u5A01"], + ["ce40", "\u8719\u871B\u871D\u871F\u8720\u8724\u8726\u8727\u8728\u872A\u872B\u872C\u872D\u872F\u8730\u8732\u8733\u8735\u8736\u8738\u8739\u873A\u873C\u873D\u8740", 6, "\u874A\u874B\u874D\u874F\u8750\u8751\u8752\u8754\u8755\u8756\u8758\u875A", 5, "\u8761\u8762\u8766", 7, "\u876F\u8771\u8772\u8773\u8775"], + ["ce80", "\u8777\u8778\u8779\u877A\u877F\u8780\u8781\u8784\u8786\u8787\u8789\u878A\u878C\u878E", 4, "\u8794\u8795\u8796\u8798", 6, "\u87A0", 4, "\u5DCD\u5FAE\u5371\u97E6\u8FDD\u6845\u56F4\u552F\u60DF\u4E3A\u6F4D\u7EF4\u82C7\u840E\u59D4\u4F1F\u4F2A\u5C3E\u7EAC\u672A\u851A\u5473\u754F\u80C3\u5582\u9B4F\u4F4D\u6E2D\u8C13\u5C09\u6170\u536B\u761F\u6E29\u868A\u6587\u95FB\u7EB9\u543B\u7A33\u7D0A\u95EE\u55E1\u7FC1\u74EE\u631D\u8717\u6DA1\u7A9D\u6211\u65A1\u5367\u63E1\u6C83\u5DEB\u545C\u94A8\u4E4C\u6C61\u8BEC\u5C4B\u65E0\u829C\u68A7\u543E\u5434\u6BCB\u6B66\u4E94\u6342\u5348\u821E\u4F0D\u4FAE\u575E\u620A\u96FE\u6664\u7269\u52FF\u52A1\u609F\u8BEF\u6614\u7199\u6790\u897F\u7852\u77FD\u6670\u563B\u5438\u9521\u727A"], + ["cf40", "\u87A5\u87A6\u87A7\u87A9\u87AA\u87AE\u87B0\u87B1\u87B2\u87B4\u87B6\u87B7\u87B8\u87B9\u87BB\u87BC\u87BE\u87BF\u87C1", 4, "\u87C7\u87C8\u87C9\u87CC", 4, "\u87D4", 6, "\u87DC\u87DD\u87DE\u87DF\u87E1\u87E2\u87E3\u87E4\u87E6\u87E7\u87E8\u87E9\u87EB\u87EC\u87ED\u87EF", 9], + ["cf80", "\u87FA\u87FB\u87FC\u87FD\u87FF\u8800\u8801\u8802\u8804", 5, "\u880B", 7, "\u8814\u8817\u8818\u8819\u881A\u881C", 4, "\u8823\u7A00\u606F\u5E0C\u6089\u819D\u5915\u60DC\u7184\u70EF\u6EAA\u6C50\u7280\u6A84\u88AD\u5E2D\u4E60\u5AB3\u559C\u94E3\u6D17\u7CFB\u9699\u620F\u7EC6\u778E\u867E\u5323\u971E\u8F96\u6687\u5CE1\u4FA0\u72ED\u4E0B\u53A6\u590F\u5413\u6380\u9528\u5148\u4ED9\u9C9C\u7EA4\u54B8\u8D24\u8854\u8237\u95F2\u6D8E\u5F26\u5ACC\u663E\u9669\u73B0\u732E\u53BF\u817A\u9985\u7FA1\u5BAA\u9677\u9650\u7EBF\u76F8\u53A2\u9576\u9999\u7BB1\u8944\u6E58\u4E61\u7FD4\u7965\u8BE6\u60F3\u54CD\u4EAB\u9879\u5DF7\u6A61\u50CF\u5411\u8C61\u8427\u785D\u9704\u524A\u54EE\u56A3\u9500\u6D88\u5BB5\u6DC6\u6653"], + ["d040", "\u8824", 13, "\u8833", 5, "\u883A\u883B\u883D\u883E\u883F\u8841\u8842\u8843\u8846", 5, "\u884E", 5, "\u8855\u8856\u8858\u885A", 6, "\u8866\u8867\u886A\u886D\u886F\u8871\u8873\u8874\u8875\u8876\u8878\u8879\u887A"], + ["d080", "\u887B\u887C\u8880\u8883\u8886\u8887\u8889\u888A\u888C\u888E\u888F\u8890\u8891\u8893\u8894\u8895\u8897", 4, "\u889D", 4, "\u88A3\u88A5", 5, "\u5C0F\u5B5D\u6821\u8096\u5578\u7B11\u6548\u6954\u4E9B\u6B47\u874E\u978B\u534F\u631F\u643A\u90AA\u659C\u80C1\u8C10\u5199\u68B0\u5378\u87F9\u61C8\u6CC4\u6CFB\u8C22\u5C51\u85AA\u82AF\u950C\u6B23\u8F9B\u65B0\u5FFB\u5FC3\u4FE1\u8845\u661F\u8165\u7329\u60FA\u5174\u5211\u578B\u5F62\u90A2\u884C\u9192\u5E78\u674F\u6027\u59D3\u5144\u51F6\u80F8\u5308\u6C79\u96C4\u718A\u4F11\u4FEE\u7F9E\u673D\u55C5\u9508\u79C0\u8896\u7EE3\u589F\u620C\u9700\u865A\u5618\u987B\u5F90\u8BB8\u84C4\u9157\u53D9\u65ED\u5E8F\u755C\u6064\u7D6E\u5A7F\u7EEA\u7EED\u8F69\u55A7\u5BA3\u60AC\u65CB\u7384"], + ["d140", "\u88AC\u88AE\u88AF\u88B0\u88B2", 4, "\u88B8\u88B9\u88BA\u88BB\u88BD\u88BE\u88BF\u88C0\u88C3\u88C4\u88C7\u88C8\u88CA\u88CB\u88CC\u88CD\u88CF\u88D0\u88D1\u88D3\u88D6\u88D7\u88DA", 4, "\u88E0\u88E1\u88E6\u88E7\u88E9", 6, "\u88F2\u88F5\u88F6\u88F7\u88FA\u88FB\u88FD\u88FF\u8900\u8901\u8903", 5], + ["d180", "\u8909\u890B", 4, "\u8911\u8914", 4, "\u891C", 4, "\u8922\u8923\u8924\u8926\u8927\u8928\u8929\u892C\u892D\u892E\u892F\u8931\u8932\u8933\u8935\u8937\u9009\u7663\u7729\u7EDA\u9774\u859B\u5B66\u7A74\u96EA\u8840\u52CB\u718F\u5FAA\u65EC\u8BE2\u5BFB\u9A6F\u5DE1\u6B89\u6C5B\u8BAD\u8BAF\u900A\u8FC5\u538B\u62BC\u9E26\u9E2D\u5440\u4E2B\u82BD\u7259\u869C\u5D16\u8859\u6DAF\u96C5\u54D1\u4E9A\u8BB6\u7109\u54BD\u9609\u70DF\u6DF9\u76D0\u4E25\u7814\u8712\u5CA9\u5EF6\u8A00\u989C\u960E\u708E\u6CBF\u5944\u63A9\u773C\u884D\u6F14\u8273\u5830\u71D5\u538C\u781A\u96C1\u5501\u5F66\u7130\u5BB4\u8C1A\u9A8C\u6B83\u592E\u9E2F\u79E7\u6768\u626C\u4F6F\u75A1\u7F8A\u6D0B\u9633\u6C27\u4EF0\u75D2\u517B\u6837\u6F3E\u9080\u8170\u5996\u7476"], + ["d240", "\u8938", 8, "\u8942\u8943\u8945", 24, "\u8960", 5, "\u8967", 19, "\u897C"], + ["d280", "\u897D\u897E\u8980\u8982\u8984\u8985\u8987", 26, "\u6447\u5C27\u9065\u7A91\u8C23\u59DA\u54AC\u8200\u836F\u8981\u8000\u6930\u564E\u8036\u7237\u91CE\u51B6\u4E5F\u9875\u6396\u4E1A\u53F6\u66F3\u814B\u591C\u6DB2\u4E00\u58F9\u533B\u63D6\u94F1\u4F9D\u4F0A\u8863\u9890\u5937\u9057\u79FB\u4EEA\u80F0\u7591\u6C82\u5B9C\u59E8\u5F5D\u6905\u8681\u501A\u5DF2\u4E59\u77E3\u4EE5\u827A\u6291\u6613\u9091\u5C79\u4EBF\u5F79\u81C6\u9038\u8084\u75AB\u4EA6\u88D4\u610F\u6BC5\u5FC6\u4E49\u76CA\u6EA2\u8BE3\u8BAE\u8C0A\u8BD1\u5F02\u7FFC\u7FCC\u7ECE\u8335\u836B\u56E0\u6BB7\u97F3\u9634\u59FB\u541F\u94F6\u6DEB\u5BC5\u996E\u5C39\u5F15\u9690"], + ["d340", "\u89A2", 30, "\u89C3\u89CD\u89D3\u89D4\u89D5\u89D7\u89D8\u89D9\u89DB\u89DD\u89DF\u89E0\u89E1\u89E2\u89E4\u89E7\u89E8\u89E9\u89EA\u89EC\u89ED\u89EE\u89F0\u89F1\u89F2\u89F4", 6], + ["d380", "\u89FB", 4, "\u8A01", 5, "\u8A08", 21, "\u5370\u82F1\u6A31\u5A74\u9E70\u5E94\u7F28\u83B9\u8424\u8425\u8367\u8747\u8FCE\u8D62\u76C8\u5F71\u9896\u786C\u6620\u54DF\u62E5\u4F63\u81C3\u75C8\u5EB8\u96CD\u8E0A\u86F9\u548F\u6CF3\u6D8C\u6C38\u607F\u52C7\u7528\u5E7D\u4F18\u60A0\u5FE7\u5C24\u7531\u90AE\u94C0\u72B9\u6CB9\u6E38\u9149\u6709\u53CB\u53F3\u4F51\u91C9\u8BF1\u53C8\u5E7C\u8FC2\u6DE4\u4E8E\u76C2\u6986\u865E\u611A\u8206\u4F59\u4FDE\u903E\u9C7C\u6109\u6E1D\u6E14\u9685\u4E88\u5A31\u96E8\u4E0E\u5C7F\u79B9\u5B87\u8BED\u7FBD\u7389\u57DF\u828B\u90C1\u5401\u9047\u55BB\u5CEA\u5FA1\u6108\u6B32\u72F1\u80B2\u8A89"], + ["d440", "\u8A1E", 31, "\u8A3F", 8, "\u8A49", 21], + ["d480", "\u8A5F", 25, "\u8A7A", 6, "\u6D74\u5BD3\u88D5\u9884\u8C6B\u9A6D\u9E33\u6E0A\u51A4\u5143\u57A3\u8881\u539F\u63F4\u8F95\u56ED\u5458\u5706\u733F\u6E90\u7F18\u8FDC\u82D1\u613F\u6028\u9662\u66F0\u7EA6\u8D8A\u8DC3\u94A5\u5CB3\u7CA4\u6708\u60A6\u9605\u8018\u4E91\u90E7\u5300\u9668\u5141\u8FD0\u8574\u915D\u6655\u97F5\u5B55\u531D\u7838\u6742\u683D\u54C9\u707E\u5BB0\u8F7D\u518D\u5728\u54B1\u6512\u6682\u8D5E\u8D43\u810F\u846C\u906D\u7CDF\u51FF\u85FB\u67A3\u65E9\u6FA1\u86A4\u8E81\u566A\u9020\u7682\u7076\u71E5\u8D23\u62E9\u5219\u6CFD\u8D3C\u600E\u589E\u618E\u66FE\u8D60\u624E\u55B3\u6E23\u672D\u8F67"], + ["d540", "\u8A81", 7, "\u8A8B", 7, "\u8A94", 46], + ["d580", "\u8AC3", 32, "\u94E1\u95F8\u7728\u6805\u69A8\u548B\u4E4D\u70B8\u8BC8\u6458\u658B\u5B85\u7A84\u503A\u5BE8\u77BB\u6BE1\u8A79\u7C98\u6CBE\u76CF\u65A9\u8F97\u5D2D\u5C55\u8638\u6808\u5360\u6218\u7AD9\u6E5B\u7EFD\u6A1F\u7AE0\u5F70\u6F33\u5F20\u638C\u6DA8\u6756\u4E08\u5E10\u8D26\u4ED7\u80C0\u7634\u969C\u62DB\u662D\u627E\u6CBC\u8D75\u7167\u7F69\u5146\u8087\u53EC\u906E\u6298\u54F2\u86F0\u8F99\u8005\u9517\u8517\u8FD9\u6D59\u73CD\u659F\u771F\u7504\u7827\u81FB\u8D1E\u9488\u4FA6\u6795\u75B9\u8BCA\u9707\u632F\u9547\u9635\u84B8\u6323\u7741\u5F81\u72F0\u4E89\u6014\u6574\u62EF\u6B63\u653F"], + ["d640", "\u8AE4", 34, "\u8B08", 27], + ["d680", "\u8B24\u8B25\u8B27", 30, "\u5E27\u75C7\u90D1\u8BC1\u829D\u679D\u652F\u5431\u8718\u77E5\u80A2\u8102\u6C41\u4E4B\u7EC7\u804C\u76F4\u690D\u6B96\u6267\u503C\u4F84\u5740\u6307\u6B62\u8DBE\u53EA\u65E8\u7EB8\u5FD7\u631A\u63B7\u81F3\u81F4\u7F6E\u5E1C\u5CD9\u5236\u667A\u79E9\u7A1A\u8D28\u7099\u75D4\u6EDE\u6CBB\u7A92\u4E2D\u76C5\u5FE0\u949F\u8877\u7EC8\u79CD\u80BF\u91CD\u4EF2\u4F17\u821F\u5468\u5DDE\u6D32\u8BCC\u7CA5\u8F74\u8098\u5E1A\u5492\u76B1\u5B99\u663C\u9AA4\u73E0\u682A\u86DB\u6731\u732A\u8BF8\u8BDB\u9010\u7AF9\u70DB\u716E\u62C4\u77A9\u5631\u4E3B\u8457\u67F1\u52A9\u86C0\u8D2E\u94F8\u7B51"], + ["d740", "\u8B46", 31, "\u8B67", 4, "\u8B6D", 25], + ["d780", "\u8B87", 24, "\u8BAC\u8BB1\u8BBB\u8BC7\u8BD0\u8BEA\u8C09\u8C1E\u4F4F\u6CE8\u795D\u9A7B\u6293\u722A\u62FD\u4E13\u7816\u8F6C\u64B0\u8D5A\u7BC6\u6869\u5E84\u88C5\u5986\u649E\u58EE\u72B6\u690E\u9525\u8FFD\u8D58\u5760\u7F00\u8C06\u51C6\u6349\u62D9\u5353\u684C\u7422\u8301\u914C\u5544\u7740\u707C\u6D4A\u5179\u54A8\u8D44\u59FF\u6ECB\u6DC4\u5B5C\u7D2B\u4ED4\u7C7D\u6ED3\u5B50\u81EA\u6E0D\u5B57\u9B03\u68D5\u8E2A\u5B97\u7EFC\u603B\u7EB5\u90B9\u8D70\u594F\u63CD\u79DF\u8DB3\u5352\u65CF\u7956\u8BC5\u963B\u7EC4\u94BB\u7E82\u5634\u9189\u6700\u7F6A\u5C0A\u9075\u6628\u5DE6\u4F50\u67DE\u505A\u4F5C\u5750\u5EA7"], + ["d840", "\u8C38", 8, "\u8C42\u8C43\u8C44\u8C45\u8C48\u8C4A\u8C4B\u8C4D", 7, "\u8C56\u8C57\u8C58\u8C59\u8C5B", 5, "\u8C63", 6, "\u8C6C", 6, "\u8C74\u8C75\u8C76\u8C77\u8C7B", 6, "\u8C83\u8C84\u8C86\u8C87"], + ["d880", "\u8C88\u8C8B\u8C8D", 6, "\u8C95\u8C96\u8C97\u8C99", 20, "\u4E8D\u4E0C\u5140\u4E10\u5EFF\u5345\u4E15\u4E98\u4E1E\u9B32\u5B6C\u5669\u4E28\u79BA\u4E3F\u5315\u4E47\u592D\u723B\u536E\u6C10\u56DF\u80E4\u9997\u6BD3\u777E\u9F17\u4E36\u4E9F\u9F10\u4E5C\u4E69\u4E93\u8288\u5B5B\u556C\u560F\u4EC4\u538D\u539D\u53A3\u53A5\u53AE\u9765\u8D5D\u531A\u53F5\u5326\u532E\u533E\u8D5C\u5366\u5363\u5202\u5208\u520E\u522D\u5233\u523F\u5240\u524C\u525E\u5261\u525C\u84AF\u527D\u5282\u5281\u5290\u5293\u5182\u7F54\u4EBB\u4EC3\u4EC9\u4EC2\u4EE8\u4EE1\u4EEB\u4EDE\u4F1B\u4EF3\u4F22\u4F64\u4EF5\u4F25\u4F27\u4F09\u4F2B\u4F5E\u4F67\u6538\u4F5A\u4F5D"], + ["d940", "\u8CAE", 62], + ["d980", "\u8CED", 32, "\u4F5F\u4F57\u4F32\u4F3D\u4F76\u4F74\u4F91\u4F89\u4F83\u4F8F\u4F7E\u4F7B\u4FAA\u4F7C\u4FAC\u4F94\u4FE6\u4FE8\u4FEA\u4FC5\u4FDA\u4FE3\u4FDC\u4FD1\u4FDF\u4FF8\u5029\u504C\u4FF3\u502C\u500F\u502E\u502D\u4FFE\u501C\u500C\u5025\u5028\u507E\u5043\u5055\u5048\u504E\u506C\u507B\u50A5\u50A7\u50A9\u50BA\u50D6\u5106\u50ED\u50EC\u50E6\u50EE\u5107\u510B\u4EDD\u6C3D\u4F58\u4F65\u4FCE\u9FA0\u6C46\u7C74\u516E\u5DFD\u9EC9\u9998\u5181\u5914\u52F9\u530D\u8A07\u5310\u51EB\u5919\u5155\u4EA0\u5156\u4EB3\u886E\u88A4\u4EB5\u8114\u88D2\u7980\u5B34\u8803\u7FB8\u51AB\u51B1\u51BD\u51BC"], + ["da40", "\u8D0E", 14, "\u8D20\u8D51\u8D52\u8D57\u8D5F\u8D65\u8D68\u8D69\u8D6A\u8D6C\u8D6E\u8D6F\u8D71\u8D72\u8D78", 8, "\u8D82\u8D83\u8D86\u8D87\u8D88\u8D89\u8D8C", 4, "\u8D92\u8D93\u8D95", 9, "\u8DA0\u8DA1"], + ["da80", "\u8DA2\u8DA4", 12, "\u8DB2\u8DB6\u8DB7\u8DB9\u8DBB\u8DBD\u8DC0\u8DC1\u8DC2\u8DC5\u8DC7\u8DC8\u8DC9\u8DCA\u8DCD\u8DD0\u8DD2\u8DD3\u8DD4\u51C7\u5196\u51A2\u51A5\u8BA0\u8BA6\u8BA7\u8BAA\u8BB4\u8BB5\u8BB7\u8BC2\u8BC3\u8BCB\u8BCF\u8BCE\u8BD2\u8BD3\u8BD4\u8BD6\u8BD8\u8BD9\u8BDC\u8BDF\u8BE0\u8BE4\u8BE8\u8BE9\u8BEE\u8BF0\u8BF3\u8BF6\u8BF9\u8BFC\u8BFF\u8C00\u8C02\u8C04\u8C07\u8C0C\u8C0F\u8C11\u8C12\u8C14\u8C15\u8C16\u8C19\u8C1B\u8C18\u8C1D\u8C1F\u8C20\u8C21\u8C25\u8C27\u8C2A\u8C2B\u8C2E\u8C2F\u8C32\u8C33\u8C35\u8C36\u5369\u537A\u961D\u9622\u9621\u9631\u962A\u963D\u963C\u9642\u9649\u9654\u965F\u9667\u966C\u9672\u9674\u9688\u968D\u9697\u96B0\u9097\u909B\u909D\u9099\u90AC\u90A1\u90B4\u90B3\u90B6\u90BA"], + ["db40", "\u8DD5\u8DD8\u8DD9\u8DDC\u8DE0\u8DE1\u8DE2\u8DE5\u8DE6\u8DE7\u8DE9\u8DED\u8DEE\u8DF0\u8DF1\u8DF2\u8DF4\u8DF6\u8DFC\u8DFE", 6, "\u8E06\u8E07\u8E08\u8E0B\u8E0D\u8E0E\u8E10\u8E11\u8E12\u8E13\u8E15", 7, "\u8E20\u8E21\u8E24", 4, "\u8E2B\u8E2D\u8E30\u8E32\u8E33\u8E34\u8E36\u8E37\u8E38\u8E3B\u8E3C\u8E3E"], + ["db80", "\u8E3F\u8E43\u8E45\u8E46\u8E4C", 4, "\u8E53", 5, "\u8E5A", 11, "\u8E67\u8E68\u8E6A\u8E6B\u8E6E\u8E71\u90B8\u90B0\u90CF\u90C5\u90BE\u90D0\u90C4\u90C7\u90D3\u90E6\u90E2\u90DC\u90D7\u90DB\u90EB\u90EF\u90FE\u9104\u9122\u911E\u9123\u9131\u912F\u9139\u9143\u9146\u520D\u5942\u52A2\u52AC\u52AD\u52BE\u54FF\u52D0\u52D6\u52F0\u53DF\u71EE\u77CD\u5EF4\u51F5\u51FC\u9B2F\u53B6\u5F01\u755A\u5DEF\u574C\u57A9\u57A1\u587E\u58BC\u58C5\u58D1\u5729\u572C\u572A\u5733\u5739\u572E\u572F\u575C\u573B\u5742\u5769\u5785\u576B\u5786\u577C\u577B\u5768\u576D\u5776\u5773\u57AD\u57A4\u578C\u57B2\u57CF\u57A7\u57B4\u5793\u57A0\u57D5\u57D8\u57DA\u57D9\u57D2\u57B8\u57F4\u57EF\u57F8\u57E4\u57DD"], + ["dc40", "\u8E73\u8E75\u8E77", 4, "\u8E7D\u8E7E\u8E80\u8E82\u8E83\u8E84\u8E86\u8E88", 6, "\u8E91\u8E92\u8E93\u8E95", 6, "\u8E9D\u8E9F", 11, "\u8EAD\u8EAE\u8EB0\u8EB1\u8EB3", 6, "\u8EBB", 7], + ["dc80", "\u8EC3", 10, "\u8ECF", 21, "\u580B\u580D\u57FD\u57ED\u5800\u581E\u5819\u5844\u5820\u5865\u586C\u5881\u5889\u589A\u5880\u99A8\u9F19\u61FF\u8279\u827D\u827F\u828F\u828A\u82A8\u8284\u828E\u8291\u8297\u8299\u82AB\u82B8\u82BE\u82B0\u82C8\u82CA\u82E3\u8298\u82B7\u82AE\u82CB\u82CC\u82C1\u82A9\u82B4\u82A1\u82AA\u829F\u82C4\u82CE\u82A4\u82E1\u8309\u82F7\u82E4\u830F\u8307\u82DC\u82F4\u82D2\u82D8\u830C\u82FB\u82D3\u8311\u831A\u8306\u8314\u8315\u82E0\u82D5\u831C\u8351\u835B\u835C\u8308\u8392\u833C\u8334\u8331\u839B\u835E\u832F\u834F\u8347\u8343\u835F\u8340\u8317\u8360\u832D\u833A\u8333\u8366\u8365"], + ["dd40", "\u8EE5", 62], + ["dd80", "\u8F24", 32, "\u8368\u831B\u8369\u836C\u836A\u836D\u836E\u83B0\u8378\u83B3\u83B4\u83A0\u83AA\u8393\u839C\u8385\u837C\u83B6\u83A9\u837D\u83B8\u837B\u8398\u839E\u83A8\u83BA\u83BC\u83C1\u8401\u83E5\u83D8\u5807\u8418\u840B\u83DD\u83FD\u83D6\u841C\u8438\u8411\u8406\u83D4\u83DF\u840F\u8403\u83F8\u83F9\u83EA\u83C5\u83C0\u8426\u83F0\u83E1\u845C\u8451\u845A\u8459\u8473\u8487\u8488\u847A\u8489\u8478\u843C\u8446\u8469\u8476\u848C\u848E\u8431\u846D\u84C1\u84CD\u84D0\u84E6\u84BD\u84D3\u84CA\u84BF\u84BA\u84E0\u84A1\u84B9\u84B4\u8497\u84E5\u84E3\u850C\u750D\u8538\u84F0\u8539\u851F\u853A"], + ["de40", "\u8F45", 32, "\u8F6A\u8F80\u8F8C\u8F92\u8F9D\u8FA0\u8FA1\u8FA2\u8FA4\u8FA5\u8FA6\u8FA7\u8FAA\u8FAC\u8FAD\u8FAE\u8FAF\u8FB2\u8FB3\u8FB4\u8FB5\u8FB7\u8FB8\u8FBA\u8FBB\u8FBC\u8FBF\u8FC0\u8FC3\u8FC6"], + ["de80", "\u8FC9", 4, "\u8FCF\u8FD2\u8FD6\u8FD7\u8FDA\u8FE0\u8FE1\u8FE3\u8FE7\u8FEC\u8FEF\u8FF1\u8FF2\u8FF4\u8FF5\u8FF6\u8FFA\u8FFB\u8FFC\u8FFE\u8FFF\u9007\u9008\u900C\u900E\u9013\u9015\u9018\u8556\u853B\u84FF\u84FC\u8559\u8548\u8568\u8564\u855E\u857A\u77A2\u8543\u8572\u857B\u85A4\u85A8\u8587\u858F\u8579\u85AE\u859C\u8585\u85B9\u85B7\u85B0\u85D3\u85C1\u85DC\u85FF\u8627\u8605\u8629\u8616\u863C\u5EFE\u5F08\u593C\u5941\u8037\u5955\u595A\u5958\u530F\u5C22\u5C25\u5C2C\u5C34\u624C\u626A\u629F\u62BB\u62CA\u62DA\u62D7\u62EE\u6322\u62F6\u6339\u634B\u6343\u63AD\u63F6\u6371\u637A\u638E\u63B4\u636D\u63AC\u638A\u6369\u63AE\u63BC\u63F2\u63F8\u63E0\u63FF\u63C4\u63DE\u63CE\u6452\u63C6\u63BE\u6445\u6441\u640B\u641B\u6420\u640C\u6426\u6421\u645E\u6484\u646D\u6496"], + ["df40", "\u9019\u901C\u9023\u9024\u9025\u9027", 5, "\u9030", 4, "\u9037\u9039\u903A\u903D\u903F\u9040\u9043\u9045\u9046\u9048", 4, "\u904E\u9054\u9055\u9056\u9059\u905A\u905C", 5, "\u9064\u9066\u9067\u9069\u906A\u906B\u906C\u906F", 4, "\u9076", 6, "\u907E\u9081"], + ["df80", "\u9084\u9085\u9086\u9087\u9089\u908A\u908C", 4, "\u9092\u9094\u9096\u9098\u909A\u909C\u909E\u909F\u90A0\u90A4\u90A5\u90A7\u90A8\u90A9\u90AB\u90AD\u90B2\u90B7\u90BC\u90BD\u90BF\u90C0\u647A\u64B7\u64B8\u6499\u64BA\u64C0\u64D0\u64D7\u64E4\u64E2\u6509\u6525\u652E\u5F0B\u5FD2\u7519\u5F11\u535F\u53F1\u53FD\u53E9\u53E8\u53FB\u5412\u5416\u5406\u544B\u5452\u5453\u5454\u5456\u5443\u5421\u5457\u5459\u5423\u5432\u5482\u5494\u5477\u5471\u5464\u549A\u549B\u5484\u5476\u5466\u549D\u54D0\u54AD\u54C2\u54B4\u54D2\u54A7\u54A6\u54D3\u54D4\u5472\u54A3\u54D5\u54BB\u54BF\u54CC\u54D9\u54DA\u54DC\u54A9\u54AA\u54A4\u54DD\u54CF\u54DE\u551B\u54E7\u5520\u54FD\u5514\u54F3\u5522\u5523\u550F\u5511\u5527\u552A\u5567\u558F\u55B5\u5549\u556D\u5541\u5555\u553F\u5550\u553C"], + ["e040", "\u90C2\u90C3\u90C6\u90C8\u90C9\u90CB\u90CC\u90CD\u90D2\u90D4\u90D5\u90D6\u90D8\u90D9\u90DA\u90DE\u90DF\u90E0\u90E3\u90E4\u90E5\u90E9\u90EA\u90EC\u90EE\u90F0\u90F1\u90F2\u90F3\u90F5\u90F6\u90F7\u90F9\u90FA\u90FB\u90FC\u90FF\u9100\u9101\u9103\u9105", 19, "\u911A\u911B\u911C"], + ["e080", "\u911D\u911F\u9120\u9121\u9124", 10, "\u9130\u9132", 6, "\u913A", 8, "\u9144\u5537\u5556\u5575\u5576\u5577\u5533\u5530\u555C\u558B\u55D2\u5583\u55B1\u55B9\u5588\u5581\u559F\u557E\u55D6\u5591\u557B\u55DF\u55BD\u55BE\u5594\u5599\u55EA\u55F7\u55C9\u561F\u55D1\u55EB\u55EC\u55D4\u55E6\u55DD\u55C4\u55EF\u55E5\u55F2\u55F3\u55CC\u55CD\u55E8\u55F5\u55E4\u8F94\u561E\u5608\u560C\u5601\u5624\u5623\u55FE\u5600\u5627\u562D\u5658\u5639\u5657\u562C\u564D\u5662\u5659\u565C\u564C\u5654\u5686\u5664\u5671\u566B\u567B\u567C\u5685\u5693\u56AF\u56D4\u56D7\u56DD\u56E1\u56F5\u56EB\u56F9\u56FF\u5704\u570A\u5709\u571C\u5E0F\u5E19\u5E14\u5E11\u5E31\u5E3B\u5E3C"], + ["e140", "\u9145\u9147\u9148\u9151\u9153\u9154\u9155\u9156\u9158\u9159\u915B\u915C\u915F\u9160\u9166\u9167\u9168\u916B\u916D\u9173\u917A\u917B\u917C\u9180", 4, "\u9186\u9188\u918A\u918E\u918F\u9193", 6, "\u919C", 5, "\u91A4", 5, "\u91AB\u91AC\u91B0\u91B1\u91B2\u91B3\u91B6\u91B7\u91B8\u91B9\u91BB"], + ["e180", "\u91BC", 10, "\u91C8\u91CB\u91D0\u91D2", 9, "\u91DD", 8, "\u5E37\u5E44\u5E54\u5E5B\u5E5E\u5E61\u5C8C\u5C7A\u5C8D\u5C90\u5C96\u5C88\u5C98\u5C99\u5C91\u5C9A\u5C9C\u5CB5\u5CA2\u5CBD\u5CAC\u5CAB\u5CB1\u5CA3\u5CC1\u5CB7\u5CC4\u5CD2\u5CE4\u5CCB\u5CE5\u5D02\u5D03\u5D27\u5D26\u5D2E\u5D24\u5D1E\u5D06\u5D1B\u5D58\u5D3E\u5D34\u5D3D\u5D6C\u5D5B\u5D6F\u5D5D\u5D6B\u5D4B\u5D4A\u5D69\u5D74\u5D82\u5D99\u5D9D\u8C73\u5DB7\u5DC5\u5F73\u5F77\u5F82\u5F87\u5F89\u5F8C\u5F95\u5F99\u5F9C\u5FA8\u5FAD\u5FB5\u5FBC\u8862\u5F61\u72AD\u72B0\u72B4\u72B7\u72B8\u72C3\u72C1\u72CE\u72CD\u72D2\u72E8\u72EF\u72E9\u72F2\u72F4\u72F7\u7301\u72F3\u7303\u72FA"], + ["e240", "\u91E6", 62], + ["e280", "\u9225", 32, "\u72FB\u7317\u7313\u7321\u730A\u731E\u731D\u7315\u7322\u7339\u7325\u732C\u7338\u7331\u7350\u734D\u7357\u7360\u736C\u736F\u737E\u821B\u5925\u98E7\u5924\u5902\u9963\u9967", 5, "\u9974\u9977\u997D\u9980\u9984\u9987\u998A\u998D\u9990\u9991\u9993\u9994\u9995\u5E80\u5E91\u5E8B\u5E96\u5EA5\u5EA0\u5EB9\u5EB5\u5EBE\u5EB3\u8D53\u5ED2\u5ED1\u5EDB\u5EE8\u5EEA\u81BA\u5FC4\u5FC9\u5FD6\u5FCF\u6003\u5FEE\u6004\u5FE1\u5FE4\u5FFE\u6005\u6006\u5FEA\u5FED\u5FF8\u6019\u6035\u6026\u601B\u600F\u600D\u6029\u602B\u600A\u603F\u6021\u6078\u6079\u607B\u607A\u6042"], + ["e340", "\u9246", 45, "\u9275", 16], + ["e380", "\u9286", 7, "\u928F", 24, "\u606A\u607D\u6096\u609A\u60AD\u609D\u6083\u6092\u608C\u609B\u60EC\u60BB\u60B1\u60DD\u60D8\u60C6\u60DA\u60B4\u6120\u6126\u6115\u6123\u60F4\u6100\u610E\u612B\u614A\u6175\u61AC\u6194\u61A7\u61B7\u61D4\u61F5\u5FDD\u96B3\u95E9\u95EB\u95F1\u95F3\u95F5\u95F6\u95FC\u95FE\u9603\u9604\u9606\u9608\u960A\u960B\u960C\u960D\u960F\u9612\u9615\u9616\u9617\u9619\u961A\u4E2C\u723F\u6215\u6C35\u6C54\u6C5C\u6C4A\u6CA3\u6C85\u6C90\u6C94\u6C8C\u6C68\u6C69\u6C74\u6C76\u6C86\u6CA9\u6CD0\u6CD4\u6CAD\u6CF7\u6CF8\u6CF1\u6CD7\u6CB2\u6CE0\u6CD6\u6CFA\u6CEB\u6CEE\u6CB1\u6CD3\u6CEF\u6CFE"], + ["e440", "\u92A8", 5, "\u92AF", 24, "\u92C9", 31], + ["e480", "\u92E9", 32, "\u6D39\u6D27\u6D0C\u6D43\u6D48\u6D07\u6D04\u6D19\u6D0E\u6D2B\u6D4D\u6D2E\u6D35\u6D1A\u6D4F\u6D52\u6D54\u6D33\u6D91\u6D6F\u6D9E\u6DA0\u6D5E\u6D93\u6D94\u6D5C\u6D60\u6D7C\u6D63\u6E1A\u6DC7\u6DC5\u6DDE\u6E0E\u6DBF\u6DE0\u6E11\u6DE6\u6DDD\u6DD9\u6E16\u6DAB\u6E0C\u6DAE\u6E2B\u6E6E\u6E4E\u6E6B\u6EB2\u6E5F\u6E86\u6E53\u6E54\u6E32\u6E25\u6E44\u6EDF\u6EB1\u6E98\u6EE0\u6F2D\u6EE2\u6EA5\u6EA7\u6EBD\u6EBB\u6EB7\u6ED7\u6EB4\u6ECF\u6E8F\u6EC2\u6E9F\u6F62\u6F46\u6F47\u6F24\u6F15\u6EF9\u6F2F\u6F36\u6F4B\u6F74\u6F2A\u6F09\u6F29\u6F89\u6F8D\u6F8C\u6F78\u6F72\u6F7C\u6F7A\u6FD1"], + ["e540", "\u930A", 51, "\u933F", 10], + ["e580", "\u934A", 31, "\u936B\u6FC9\u6FA7\u6FB9\u6FB6\u6FC2\u6FE1\u6FEE\u6FDE\u6FE0\u6FEF\u701A\u7023\u701B\u7039\u7035\u704F\u705E\u5B80\u5B84\u5B95\u5B93\u5BA5\u5BB8\u752F\u9A9E\u6434\u5BE4\u5BEE\u8930\u5BF0\u8E47\u8B07\u8FB6\u8FD3\u8FD5\u8FE5\u8FEE\u8FE4\u8FE9\u8FE6\u8FF3\u8FE8\u9005\u9004\u900B\u9026\u9011\u900D\u9016\u9021\u9035\u9036\u902D\u902F\u9044\u9051\u9052\u9050\u9068\u9058\u9062\u905B\u66B9\u9074\u907D\u9082\u9088\u9083\u908B\u5F50\u5F57\u5F56\u5F58\u5C3B\u54AB\u5C50\u5C59\u5B71\u5C63\u5C66\u7FBC\u5F2A\u5F29\u5F2D\u8274\u5F3C\u9B3B\u5C6E\u5981\u5983\u598D\u59A9\u59AA\u59A3"], + ["e640", "\u936C", 34, "\u9390", 27], + ["e680", "\u93AC", 29, "\u93CB\u93CC\u93CD\u5997\u59CA\u59AB\u599E\u59A4\u59D2\u59B2\u59AF\u59D7\u59BE\u5A05\u5A06\u59DD\u5A08\u59E3\u59D8\u59F9\u5A0C\u5A09\u5A32\u5A34\u5A11\u5A23\u5A13\u5A40\u5A67\u5A4A\u5A55\u5A3C\u5A62\u5A75\u80EC\u5AAA\u5A9B\u5A77\u5A7A\u5ABE\u5AEB\u5AB2\u5AD2\u5AD4\u5AB8\u5AE0\u5AE3\u5AF1\u5AD6\u5AE6\u5AD8\u5ADC\u5B09\u5B17\u5B16\u5B32\u5B37\u5B40\u5C15\u5C1C\u5B5A\u5B65\u5B73\u5B51\u5B53\u5B62\u9A75\u9A77\u9A78\u9A7A\u9A7F\u9A7D\u9A80\u9A81\u9A85\u9A88\u9A8A\u9A90\u9A92\u9A93\u9A96\u9A98\u9A9B\u9A9C\u9A9D\u9A9F\u9AA0\u9AA2\u9AA3\u9AA5\u9AA7\u7E9F\u7EA1\u7EA3\u7EA5\u7EA8\u7EA9"], + ["e740", "\u93CE", 7, "\u93D7", 54], + ["e780", "\u940E", 32, "\u7EAD\u7EB0\u7EBE\u7EC0\u7EC1\u7EC2\u7EC9\u7ECB\u7ECC\u7ED0\u7ED4\u7ED7\u7EDB\u7EE0\u7EE1\u7EE8\u7EEB\u7EEE\u7EEF\u7EF1\u7EF2\u7F0D\u7EF6\u7EFA\u7EFB\u7EFE\u7F01\u7F02\u7F03\u7F07\u7F08\u7F0B\u7F0C\u7F0F\u7F11\u7F12\u7F17\u7F19\u7F1C\u7F1B\u7F1F\u7F21", 6, "\u7F2A\u7F2B\u7F2C\u7F2D\u7F2F", 4, "\u7F35\u5E7A\u757F\u5DDB\u753E\u9095\u738E\u7391\u73AE\u73A2\u739F\u73CF\u73C2\u73D1\u73B7\u73B3\u73C0\u73C9\u73C8\u73E5\u73D9\u987C\u740A\u73E9\u73E7\u73DE\u73BA\u73F2\u740F\u742A\u745B\u7426\u7425\u7428\u7430\u742E\u742C"], + ["e840", "\u942F", 14, "\u943F", 43, "\u946C\u946D\u946E\u946F"], + ["e880", "\u9470", 20, "\u9491\u9496\u9498\u94C7\u94CF\u94D3\u94D4\u94DA\u94E6\u94FB\u951C\u9520\u741B\u741A\u7441\u745C\u7457\u7455\u7459\u7477\u746D\u747E\u749C\u748E\u7480\u7481\u7487\u748B\u749E\u74A8\u74A9\u7490\u74A7\u74D2\u74BA\u97EA\u97EB\u97EC\u674C\u6753\u675E\u6748\u6769\u67A5\u6787\u676A\u6773\u6798\u67A7\u6775\u67A8\u679E\u67AD\u678B\u6777\u677C\u67F0\u6809\u67D8\u680A\u67E9\u67B0\u680C\u67D9\u67B5\u67DA\u67B3\u67DD\u6800\u67C3\u67B8\u67E2\u680E\u67C1\u67FD\u6832\u6833\u6860\u6861\u684E\u6862\u6844\u6864\u6883\u681D\u6855\u6866\u6841\u6867\u6840\u683E\u684A\u6849\u6829\u68B5\u688F\u6874\u6877\u6893\u686B\u68C2\u696E\u68FC\u691F\u6920\u68F9"], + ["e940", "\u9527\u9533\u953D\u9543\u9548\u954B\u9555\u955A\u9560\u956E\u9574\u9575\u9577", 7, "\u9580", 42], + ["e980", "\u95AB", 32, "\u6924\u68F0\u690B\u6901\u6957\u68E3\u6910\u6971\u6939\u6960\u6942\u695D\u6984\u696B\u6980\u6998\u6978\u6934\u69CC\u6987\u6988\u69CE\u6989\u6966\u6963\u6979\u699B\u69A7\u69BB\u69AB\u69AD\u69D4\u69B1\u69C1\u69CA\u69DF\u6995\u69E0\u698D\u69FF\u6A2F\u69ED\u6A17\u6A18\u6A65\u69F2\u6A44\u6A3E\u6AA0\u6A50\u6A5B\u6A35\u6A8E\u6A79\u6A3D\u6A28\u6A58\u6A7C\u6A91\u6A90\u6AA9\u6A97\u6AAB\u7337\u7352\u6B81\u6B82\u6B87\u6B84\u6B92\u6B93\u6B8D\u6B9A\u6B9B\u6BA1\u6BAA\u8F6B\u8F6D\u8F71\u8F72\u8F73\u8F75\u8F76\u8F78\u8F77\u8F79\u8F7A\u8F7C\u8F7E\u8F81\u8F82\u8F84\u8F87\u8F8B"], + ["ea40", "\u95CC", 27, "\u95EC\u95FF\u9607\u9613\u9618\u961B\u961E\u9620\u9623", 6, "\u962B\u962C\u962D\u962F\u9630\u9637\u9638\u9639\u963A\u963E\u9641\u9643\u964A\u964E\u964F\u9651\u9652\u9653\u9656\u9657"], + ["ea80", "\u9658\u9659\u965A\u965C\u965D\u965E\u9660\u9663\u9665\u9666\u966B\u966D", 4, "\u9673\u9678", 12, "\u9687\u9689\u968A\u8F8D\u8F8E\u8F8F\u8F98\u8F9A\u8ECE\u620B\u6217\u621B\u621F\u6222\u6221\u6225\u6224\u622C\u81E7\u74EF\u74F4\u74FF\u750F\u7511\u7513\u6534\u65EE\u65EF\u65F0\u660A\u6619\u6772\u6603\u6615\u6600\u7085\u66F7\u661D\u6634\u6631\u6636\u6635\u8006\u665F\u6654\u6641\u664F\u6656\u6661\u6657\u6677\u6684\u668C\u66A7\u669D\u66BE\u66DB\u66DC\u66E6\u66E9\u8D32\u8D33\u8D36\u8D3B\u8D3D\u8D40\u8D45\u8D46\u8D48\u8D49\u8D47\u8D4D\u8D55\u8D59\u89C7\u89CA\u89CB\u89CC\u89CE\u89CF\u89D0\u89D1\u726E\u729F\u725D\u7266\u726F\u727E\u727F\u7284\u728B\u728D\u728F\u7292\u6308\u6332\u63B0"], + ["eb40", "\u968C\u968E\u9691\u9692\u9693\u9695\u9696\u969A\u969B\u969D", 9, "\u96A8", 7, "\u96B1\u96B2\u96B4\u96B5\u96B7\u96B8\u96BA\u96BB\u96BF\u96C2\u96C3\u96C8\u96CA\u96CB\u96D0\u96D1\u96D3\u96D4\u96D6", 9, "\u96E1", 6, "\u96EB"], + ["eb80", "\u96EC\u96ED\u96EE\u96F0\u96F1\u96F2\u96F4\u96F5\u96F8\u96FA\u96FB\u96FC\u96FD\u96FF\u9702\u9703\u9705\u970A\u970B\u970C\u9710\u9711\u9712\u9714\u9715\u9717", 4, "\u971D\u971F\u9720\u643F\u64D8\u8004\u6BEA\u6BF3\u6BFD\u6BF5\u6BF9\u6C05\u6C07\u6C06\u6C0D\u6C15\u6C18\u6C19\u6C1A\u6C21\u6C29\u6C24\u6C2A\u6C32\u6535\u6555\u656B\u724D\u7252\u7256\u7230\u8662\u5216\u809F\u809C\u8093\u80BC\u670A\u80BD\u80B1\u80AB\u80AD\u80B4\u80B7\u80E7\u80E8\u80E9\u80EA\u80DB\u80C2\u80C4\u80D9\u80CD\u80D7\u6710\u80DD\u80EB\u80F1\u80F4\u80ED\u810D\u810E\u80F2\u80FC\u6715\u8112\u8C5A\u8136\u811E\u812C\u8118\u8132\u8148\u814C\u8153\u8174\u8159\u815A\u8171\u8160\u8169\u817C\u817D\u816D\u8167\u584D\u5AB5\u8188\u8182\u8191\u6ED5\u81A3\u81AA\u81CC\u6726\u81CA\u81BB"], + ["ec40", "\u9721", 8, "\u972B\u972C\u972E\u972F\u9731\u9733", 4, "\u973A\u973B\u973C\u973D\u973F", 18, "\u9754\u9755\u9757\u9758\u975A\u975C\u975D\u975F\u9763\u9764\u9766\u9767\u9768\u976A", 7], + ["ec80", "\u9772\u9775\u9777", 4, "\u977D", 7, "\u9786", 4, "\u978C\u978E\u978F\u9790\u9793\u9795\u9796\u9797\u9799", 4, "\u81C1\u81A6\u6B24\u6B37\u6B39\u6B43\u6B46\u6B59\u98D1\u98D2\u98D3\u98D5\u98D9\u98DA\u6BB3\u5F40\u6BC2\u89F3\u6590\u9F51\u6593\u65BC\u65C6\u65C4\u65C3\u65CC\u65CE\u65D2\u65D6\u7080\u709C\u7096\u709D\u70BB\u70C0\u70B7\u70AB\u70B1\u70E8\u70CA\u7110\u7113\u7116\u712F\u7131\u7173\u715C\u7168\u7145\u7172\u714A\u7178\u717A\u7198\u71B3\u71B5\u71A8\u71A0\u71E0\u71D4\u71E7\u71F9\u721D\u7228\u706C\u7118\u7166\u71B9\u623E\u623D\u6243\u6248\u6249\u793B\u7940\u7946\u7949\u795B\u795C\u7953\u795A\u7962\u7957\u7960\u796F\u7967\u797A\u7985\u798A\u799A\u79A7\u79B3\u5FD1\u5FD0"], + ["ed40", "\u979E\u979F\u97A1\u97A2\u97A4", 6, "\u97AC\u97AE\u97B0\u97B1\u97B3\u97B5", 46], + ["ed80", "\u97E4\u97E5\u97E8\u97EE", 4, "\u97F4\u97F7", 23, "\u603C\u605D\u605A\u6067\u6041\u6059\u6063\u60AB\u6106\u610D\u615D\u61A9\u619D\u61CB\u61D1\u6206\u8080\u807F\u6C93\u6CF6\u6DFC\u77F6\u77F8\u7800\u7809\u7817\u7818\u7811\u65AB\u782D\u781C\u781D\u7839\u783A\u783B\u781F\u783C\u7825\u782C\u7823\u7829\u784E\u786D\u7856\u7857\u7826\u7850\u7847\u784C\u786A\u789B\u7893\u789A\u7887\u789C\u78A1\u78A3\u78B2\u78B9\u78A5\u78D4\u78D9\u78C9\u78EC\u78F2\u7905\u78F4\u7913\u7924\u791E\u7934\u9F9B\u9EF9\u9EFB\u9EFC\u76F1\u7704\u770D\u76F9\u7707\u7708\u771A\u7722\u7719\u772D\u7726\u7735\u7738\u7750\u7751\u7747\u7743\u775A\u7768"], + ["ee40", "\u980F", 62], + ["ee80", "\u984E", 32, "\u7762\u7765\u777F\u778D\u777D\u7780\u778C\u7791\u779F\u77A0\u77B0\u77B5\u77BD\u753A\u7540\u754E\u754B\u7548\u755B\u7572\u7579\u7583\u7F58\u7F61\u7F5F\u8A48\u7F68\u7F74\u7F71\u7F79\u7F81\u7F7E\u76CD\u76E5\u8832\u9485\u9486\u9487\u948B\u948A\u948C\u948D\u948F\u9490\u9494\u9497\u9495\u949A\u949B\u949C\u94A3\u94A4\u94AB\u94AA\u94AD\u94AC\u94AF\u94B0\u94B2\u94B4\u94B6", 4, "\u94BC\u94BD\u94BF\u94C4\u94C8", 6, "\u94D0\u94D1\u94D2\u94D5\u94D6\u94D7\u94D9\u94D8\u94DB\u94DE\u94DF\u94E0\u94E2\u94E4\u94E5\u94E7\u94E8\u94EA"], + ["ef40", "\u986F", 5, "\u988B\u988E\u9892\u9895\u9899\u98A3\u98A8", 37, "\u98CF\u98D0\u98D4\u98D6\u98D7\u98DB\u98DC\u98DD\u98E0", 4], + ["ef80", "\u98E5\u98E6\u98E9", 30, "\u94E9\u94EB\u94EE\u94EF\u94F3\u94F4\u94F5\u94F7\u94F9\u94FC\u94FD\u94FF\u9503\u9502\u9506\u9507\u9509\u950A\u950D\u950E\u950F\u9512", 4, "\u9518\u951B\u951D\u951E\u951F\u9522\u952A\u952B\u9529\u952C\u9531\u9532\u9534\u9536\u9537\u9538\u953C\u953E\u953F\u9542\u9535\u9544\u9545\u9546\u9549\u954C\u954E\u954F\u9552\u9553\u9554\u9556\u9557\u9558\u9559\u955B\u955E\u955F\u955D\u9561\u9562\u9564", 8, "\u956F\u9571\u9572\u9573\u953A\u77E7\u77EC\u96C9\u79D5\u79ED\u79E3\u79EB\u7A06\u5D47\u7A03\u7A02\u7A1E\u7A14"], + ["f040", "\u9908", 4, "\u990E\u990F\u9911", 28, "\u992F", 26], + ["f080", "\u994A", 9, "\u9956", 12, "\u9964\u9966\u9973\u9978\u9979\u997B\u997E\u9982\u9983\u9989\u7A39\u7A37\u7A51\u9ECF\u99A5\u7A70\u7688\u768E\u7693\u7699\u76A4\u74DE\u74E0\u752C\u9E20\u9E22\u9E28", 4, "\u9E32\u9E31\u9E36\u9E38\u9E37\u9E39\u9E3A\u9E3E\u9E41\u9E42\u9E44\u9E46\u9E47\u9E48\u9E49\u9E4B\u9E4C\u9E4E\u9E51\u9E55\u9E57\u9E5A\u9E5B\u9E5C\u9E5E\u9E63\u9E66", 6, "\u9E71\u9E6D\u9E73\u7592\u7594\u7596\u75A0\u759D\u75AC\u75A3\u75B3\u75B4\u75B8\u75C4\u75B1\u75B0\u75C3\u75C2\u75D6\u75CD\u75E3\u75E8\u75E6\u75E4\u75EB\u75E7\u7603\u75F1\u75FC\u75FF\u7610\u7600\u7605\u760C\u7617\u760A\u7625\u7618\u7615\u7619"], + ["f140", "\u998C\u998E\u999A", 10, "\u99A6\u99A7\u99A9", 47], + ["f180", "\u99D9", 32, "\u761B\u763C\u7622\u7620\u7640\u762D\u7630\u763F\u7635\u7643\u763E\u7633\u764D\u765E\u7654\u765C\u7656\u766B\u766F\u7FCA\u7AE6\u7A78\u7A79\u7A80\u7A86\u7A88\u7A95\u7AA6\u7AA0\u7AAC\u7AA8\u7AAD\u7AB3\u8864\u8869\u8872\u887D\u887F\u8882\u88A2\u88C6\u88B7\u88BC\u88C9\u88E2\u88CE\u88E3\u88E5\u88F1\u891A\u88FC\u88E8\u88FE\u88F0\u8921\u8919\u8913\u891B\u890A\u8934\u892B\u8936\u8941\u8966\u897B\u758B\u80E5\u76B2\u76B4\u77DC\u8012\u8014\u8016\u801C\u8020\u8022\u8025\u8026\u8027\u8029\u8028\u8031\u800B\u8035\u8043\u8046\u804D\u8052\u8069\u8071\u8983\u9878\u9880\u9883"], + ["f240", "\u99FA", 62], + ["f280", "\u9A39", 32, "\u9889\u988C\u988D\u988F\u9894\u989A\u989B\u989E\u989F\u98A1\u98A2\u98A5\u98A6\u864D\u8654\u866C\u866E\u867F\u867A\u867C\u867B\u86A8\u868D\u868B\u86AC\u869D\u86A7\u86A3\u86AA\u8693\u86A9\u86B6\u86C4\u86B5\u86CE\u86B0\u86BA\u86B1\u86AF\u86C9\u86CF\u86B4\u86E9\u86F1\u86F2\u86ED\u86F3\u86D0\u8713\u86DE\u86F4\u86DF\u86D8\u86D1\u8703\u8707\u86F8\u8708\u870A\u870D\u8709\u8723\u873B\u871E\u8725\u872E\u871A\u873E\u8748\u8734\u8731\u8729\u8737\u873F\u8782\u8722\u877D\u877E\u877B\u8760\u8770\u874C\u876E\u878B\u8753\u8763\u877C\u8764\u8759\u8765\u8793\u87AF\u87A8\u87D2"], + ["f340", "\u9A5A", 17, "\u9A72\u9A83\u9A89\u9A8D\u9A8E\u9A94\u9A95\u9A99\u9AA6\u9AA9", 6, "\u9AB2\u9AB3\u9AB4\u9AB5\u9AB9\u9ABB\u9ABD\u9ABE\u9ABF\u9AC3\u9AC4\u9AC6", 4, "\u9ACD\u9ACE\u9ACF\u9AD0\u9AD2\u9AD4\u9AD5\u9AD6\u9AD7\u9AD9\u9ADA\u9ADB\u9ADC"], + ["f380", "\u9ADD\u9ADE\u9AE0\u9AE2\u9AE3\u9AE4\u9AE5\u9AE7\u9AE8\u9AE9\u9AEA\u9AEC\u9AEE\u9AF0", 8, "\u9AFA\u9AFC", 6, "\u9B04\u9B05\u9B06\u87C6\u8788\u8785\u87AD\u8797\u8783\u87AB\u87E5\u87AC\u87B5\u87B3\u87CB\u87D3\u87BD\u87D1\u87C0\u87CA\u87DB\u87EA\u87E0\u87EE\u8816\u8813\u87FE\u880A\u881B\u8821\u8839\u883C\u7F36\u7F42\u7F44\u7F45\u8210\u7AFA\u7AFD\u7B08\u7B03\u7B04\u7B15\u7B0A\u7B2B\u7B0F\u7B47\u7B38\u7B2A\u7B19\u7B2E\u7B31\u7B20\u7B25\u7B24\u7B33\u7B3E\u7B1E\u7B58\u7B5A\u7B45\u7B75\u7B4C\u7B5D\u7B60\u7B6E\u7B7B\u7B62\u7B72\u7B71\u7B90\u7BA6\u7BA7\u7BB8\u7BAC\u7B9D\u7BA8\u7B85\u7BAA\u7B9C\u7BA2\u7BAB\u7BB4\u7BD1\u7BC1\u7BCC\u7BDD\u7BDA\u7BE5\u7BE6\u7BEA\u7C0C\u7BFE\u7BFC\u7C0F\u7C16\u7C0B"], + ["f440", "\u9B07\u9B09", 5, "\u9B10\u9B11\u9B12\u9B14", 10, "\u9B20\u9B21\u9B22\u9B24", 10, "\u9B30\u9B31\u9B33", 7, "\u9B3D\u9B3E\u9B3F\u9B40\u9B46\u9B4A\u9B4B\u9B4C\u9B4E\u9B50\u9B52\u9B53\u9B55", 5], + ["f480", "\u9B5B", 32, "\u7C1F\u7C2A\u7C26\u7C38\u7C41\u7C40\u81FE\u8201\u8202\u8204\u81EC\u8844\u8221\u8222\u8223\u822D\u822F\u8228\u822B\u8238\u823B\u8233\u8234\u823E\u8244\u8249\u824B\u824F\u825A\u825F\u8268\u887E\u8885\u8888\u88D8\u88DF\u895E\u7F9D\u7F9F\u7FA7\u7FAF\u7FB0\u7FB2\u7C7C\u6549\u7C91\u7C9D\u7C9C\u7C9E\u7CA2\u7CB2\u7CBC\u7CBD\u7CC1\u7CC7\u7CCC\u7CCD\u7CC8\u7CC5\u7CD7\u7CE8\u826E\u66A8\u7FBF\u7FCE\u7FD5\u7FE5\u7FE1\u7FE6\u7FE9\u7FEE\u7FF3\u7CF8\u7D77\u7DA6\u7DAE\u7E47\u7E9B\u9EB8\u9EB4\u8D73\u8D84\u8D94\u8D91\u8DB1\u8D67\u8D6D\u8C47\u8C49\u914A\u9150\u914E\u914F\u9164"], + ["f540", "\u9B7C", 62], + ["f580", "\u9BBB", 32, "\u9162\u9161\u9170\u9169\u916F\u917D\u917E\u9172\u9174\u9179\u918C\u9185\u9190\u918D\u9191\u91A2\u91A3\u91AA\u91AD\u91AE\u91AF\u91B5\u91B4\u91BA\u8C55\u9E7E\u8DB8\u8DEB\u8E05\u8E59\u8E69\u8DB5\u8DBF\u8DBC\u8DBA\u8DC4\u8DD6\u8DD7\u8DDA\u8DDE\u8DCE\u8DCF\u8DDB\u8DC6\u8DEC\u8DF7\u8DF8\u8DE3\u8DF9\u8DFB\u8DE4\u8E09\u8DFD\u8E14\u8E1D\u8E1F\u8E2C\u8E2E\u8E23\u8E2F\u8E3A\u8E40\u8E39\u8E35\u8E3D\u8E31\u8E49\u8E41\u8E42\u8E51\u8E52\u8E4A\u8E70\u8E76\u8E7C\u8E6F\u8E74\u8E85\u8E8F\u8E94\u8E90\u8E9C\u8E9E\u8C78\u8C82\u8C8A\u8C85\u8C98\u8C94\u659B\u89D6\u89DE\u89DA\u89DC"], + ["f640", "\u9BDC", 62], + ["f680", "\u9C1B", 32, "\u89E5\u89EB\u89EF\u8A3E\u8B26\u9753\u96E9\u96F3\u96EF\u9706\u9701\u9708\u970F\u970E\u972A\u972D\u9730\u973E\u9F80\u9F83\u9F85", 5, "\u9F8C\u9EFE\u9F0B\u9F0D\u96B9\u96BC\u96BD\u96CE\u96D2\u77BF\u96E0\u928E\u92AE\u92C8\u933E\u936A\u93CA\u938F\u943E\u946B\u9C7F\u9C82\u9C85\u9C86\u9C87\u9C88\u7A23\u9C8B\u9C8E\u9C90\u9C91\u9C92\u9C94\u9C95\u9C9A\u9C9B\u9C9E", 5, "\u9CA5", 4, "\u9CAB\u9CAD\u9CAE\u9CB0", 7, "\u9CBA\u9CBB\u9CBC\u9CBD\u9CC4\u9CC5\u9CC6\u9CC7\u9CCA\u9CCB"], + ["f740", "\u9C3C", 62], + ["f780", "\u9C7B\u9C7D\u9C7E\u9C80\u9C83\u9C84\u9C89\u9C8A\u9C8C\u9C8F\u9C93\u9C96\u9C97\u9C98\u9C99\u9C9D\u9CAA\u9CAC\u9CAF\u9CB9\u9CBE", 4, "\u9CC8\u9CC9\u9CD1\u9CD2\u9CDA\u9CDB\u9CE0\u9CE1\u9CCC", 4, "\u9CD3\u9CD4\u9CD5\u9CD7\u9CD8\u9CD9\u9CDC\u9CDD\u9CDF\u9CE2\u977C\u9785\u9791\u9792\u9794\u97AF\u97AB\u97A3\u97B2\u97B4\u9AB1\u9AB0\u9AB7\u9E58\u9AB6\u9ABA\u9ABC\u9AC1\u9AC0\u9AC5\u9AC2\u9ACB\u9ACC\u9AD1\u9B45\u9B43\u9B47\u9B49\u9B48\u9B4D\u9B51\u98E8\u990D\u992E\u9955\u9954\u9ADF\u9AE1\u9AE6\u9AEF\u9AEB\u9AFB\u9AED\u9AF9\u9B08\u9B0F\u9B13\u9B1F\u9B23\u9EBD\u9EBE\u7E3B\u9E82\u9E87\u9E88\u9E8B\u9E92\u93D6\u9E9D\u9E9F\u9EDB\u9EDC\u9EDD\u9EE0\u9EDF\u9EE2\u9EE9\u9EE7\u9EE5\u9EEA\u9EEF\u9F22\u9F2C\u9F2F\u9F39\u9F37\u9F3D\u9F3E\u9F44"], + ["f840", "\u9CE3", 62], + ["f880", "\u9D22", 32], + ["f940", "\u9D43", 62], + ["f980", "\u9D82", 32], + ["fa40", "\u9DA3", 62], + ["fa80", "\u9DE2", 32], + ["fb40", "\u9E03", 27, "\u9E24\u9E27\u9E2E\u9E30\u9E34\u9E3B\u9E3C\u9E40\u9E4D\u9E50\u9E52\u9E53\u9E54\u9E56\u9E59\u9E5D\u9E5F\u9E60\u9E61\u9E62\u9E65\u9E6E\u9E6F\u9E72\u9E74", 9, "\u9E80"], + ["fb80", "\u9E81\u9E83\u9E84\u9E85\u9E86\u9E89\u9E8A\u9E8C", 5, "\u9E94", 8, "\u9E9E\u9EA0", 5, "\u9EA7\u9EA8\u9EA9\u9EAA"], + ["fc40", "\u9EAB", 8, "\u9EB5\u9EB6\u9EB7\u9EB9\u9EBA\u9EBC\u9EBF", 4, "\u9EC5\u9EC6\u9EC7\u9EC8\u9ECA\u9ECB\u9ECC\u9ED0\u9ED2\u9ED3\u9ED5\u9ED6\u9ED7\u9ED9\u9EDA\u9EDE\u9EE1\u9EE3\u9EE4\u9EE6\u9EE8\u9EEB\u9EEC\u9EED\u9EEE\u9EF0", 8, "\u9EFA\u9EFD\u9EFF", 6], + ["fc80", "\u9F06", 4, "\u9F0C\u9F0F\u9F11\u9F12\u9F14\u9F15\u9F16\u9F18\u9F1A", 5, "\u9F21\u9F23", 8, "\u9F2D\u9F2E\u9F30\u9F31"], + ["fd40", "\u9F32", 4, "\u9F38\u9F3A\u9F3C\u9F3F", 4, "\u9F45", 10, "\u9F52", 38], + ["fd80", "\u9F79", 5, "\u9F81\u9F82\u9F8D", 11, "\u9F9C\u9F9D\u9F9E\u9FA1", 4, "\uF92C\uF979\uF995\uF9E7\uF9F1"], + ["fe40", "\uFA0C\uFA0D\uFA0E\uFA0F\uFA11\uFA13\uFA14\uFA18\uFA1F\uFA20\uFA21\uFA23\uFA24\uFA27\uFA28\uFA29"] + ]; + } +}); + +// node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/encodings/tables/gbk-added.json +var require_gbk_added = __commonJS({ + "node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/encodings/tables/gbk-added.json"(exports, module) { + module.exports = [ + ["a140", "\uE4C6", 62], + ["a180", "\uE505", 32], + ["a240", "\uE526", 62], + ["a280", "\uE565", 32], + ["a2ab", "\uE766", 5], + ["a2e3", "\u20AC\uE76D"], + ["a2ef", "\uE76E\uE76F"], + ["a2fd", "\uE770\uE771"], + ["a340", "\uE586", 62], + ["a380", "\uE5C5", 31, "\u3000"], + ["a440", "\uE5E6", 62], + ["a480", "\uE625", 32], + ["a4f4", "\uE772", 10], + ["a540", "\uE646", 62], + ["a580", "\uE685", 32], + ["a5f7", "\uE77D", 7], + ["a640", "\uE6A6", 62], + ["a680", "\uE6E5", 32], + ["a6b9", "\uE785", 7], + ["a6d9", "\uE78D", 6], + ["a6ec", "\uE794\uE795"], + ["a6f3", "\uE796"], + ["a6f6", "\uE797", 8], + ["a740", "\uE706", 62], + ["a780", "\uE745", 32], + ["a7c2", "\uE7A0", 14], + ["a7f2", "\uE7AF", 12], + ["a896", "\uE7BC", 10], + ["a8bc", "\u1E3F"], + ["a8bf", "\u01F9"], + ["a8c1", "\uE7C9\uE7CA\uE7CB\uE7CC"], + ["a8ea", "\uE7CD", 20], + ["a958", "\uE7E2"], + ["a95b", "\uE7E3"], + ["a95d", "\uE7E4\uE7E5\uE7E6"], + ["a989", "\u303E\u2FF0", 11], + ["a997", "\uE7F4", 12], + ["a9f0", "\uE801", 14], + ["aaa1", "\uE000", 93], + ["aba1", "\uE05E", 93], + ["aca1", "\uE0BC", 93], + ["ada1", "\uE11A", 93], + ["aea1", "\uE178", 93], + ["afa1", "\uE1D6", 93], + ["d7fa", "\uE810", 4], + ["f8a1", "\uE234", 93], + ["f9a1", "\uE292", 93], + ["faa1", "\uE2F0", 93], + ["fba1", "\uE34E", 93], + ["fca1", "\uE3AC", 93], + ["fda1", "\uE40A", 93], + ["fe50", "\u2E81\uE816\uE817\uE818\u2E84\u3473\u3447\u2E88\u2E8B\uE81E\u359E\u361A\u360E\u2E8C\u2E97\u396E\u3918\uE826\u39CF\u39DF\u3A73\u39D0\uE82B\uE82C\u3B4E\u3C6E\u3CE0\u2EA7\uE831\uE832\u2EAA\u4056\u415F\u2EAE\u4337\u2EB3\u2EB6\u2EB7\uE83B\u43B1\u43AC\u2EBB\u43DD\u44D6\u4661\u464C\uE843"], + ["fe80", "\u4723\u4729\u477C\u478D\u2ECA\u4947\u497A\u497D\u4982\u4983\u4985\u4986\u499F\u499B\u49B7\u49B6\uE854\uE855\u4CA3\u4C9F\u4CA0\u4CA1\u4C77\u4CA2\u4D13", 6, "\u4DAE\uE864\uE468", 93], + ["8135f437", "\uE7C7"] + ]; + } +}); + +// node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/encodings/tables/gb18030-ranges.json +var require_gb18030_ranges = __commonJS({ + "node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/encodings/tables/gb18030-ranges.json"(exports, module) { + module.exports = { uChars: [128, 165, 169, 178, 184, 216, 226, 235, 238, 244, 248, 251, 253, 258, 276, 284, 300, 325, 329, 334, 364, 463, 465, 467, 469, 471, 473, 475, 477, 506, 594, 610, 712, 716, 730, 930, 938, 962, 970, 1026, 1104, 1106, 8209, 8215, 8218, 8222, 8231, 8241, 8244, 8246, 8252, 8365, 8452, 8454, 8458, 8471, 8482, 8556, 8570, 8596, 8602, 8713, 8720, 8722, 8726, 8731, 8737, 8740, 8742, 8748, 8751, 8760, 8766, 8777, 8781, 8787, 8802, 8808, 8816, 8854, 8858, 8870, 8896, 8979, 9322, 9372, 9548, 9588, 9616, 9622, 9634, 9652, 9662, 9672, 9676, 9680, 9702, 9735, 9738, 9793, 9795, 11906, 11909, 11913, 11917, 11928, 11944, 11947, 11951, 11956, 11960, 11964, 11979, 12284, 12292, 12312, 12319, 12330, 12351, 12436, 12447, 12535, 12543, 12586, 12842, 12850, 12964, 13200, 13215, 13218, 13253, 13263, 13267, 13270, 13384, 13428, 13727, 13839, 13851, 14617, 14703, 14801, 14816, 14964, 15183, 15471, 15585, 16471, 16736, 17208, 17325, 17330, 17374, 17623, 17997, 18018, 18212, 18218, 18301, 18318, 18760, 18811, 18814, 18820, 18823, 18844, 18848, 18872, 19576, 19620, 19738, 19887, 40870, 59244, 59336, 59367, 59413, 59417, 59423, 59431, 59437, 59443, 59452, 59460, 59478, 59493, 63789, 63866, 63894, 63976, 63986, 64016, 64018, 64021, 64025, 64034, 64037, 64042, 65074, 65093, 65107, 65112, 65127, 65132, 65375, 65510, 65536], gbChars: [0, 36, 38, 45, 50, 81, 89, 95, 96, 100, 103, 104, 105, 109, 126, 133, 148, 172, 175, 179, 208, 306, 307, 308, 309, 310, 311, 312, 313, 341, 428, 443, 544, 545, 558, 741, 742, 749, 750, 805, 819, 820, 7922, 7924, 7925, 7927, 7934, 7943, 7944, 7945, 7950, 8062, 8148, 8149, 8152, 8164, 8174, 8236, 8240, 8262, 8264, 8374, 8380, 8381, 8384, 8388, 8390, 8392, 8393, 8394, 8396, 8401, 8406, 8416, 8419, 8424, 8437, 8439, 8445, 8482, 8485, 8496, 8521, 8603, 8936, 8946, 9046, 9050, 9063, 9066, 9076, 9092, 9100, 9108, 9111, 9113, 9131, 9162, 9164, 9218, 9219, 11329, 11331, 11334, 11336, 11346, 11361, 11363, 11366, 11370, 11372, 11375, 11389, 11682, 11686, 11687, 11692, 11694, 11714, 11716, 11723, 11725, 11730, 11736, 11982, 11989, 12102, 12336, 12348, 12350, 12384, 12393, 12395, 12397, 12510, 12553, 12851, 12962, 12973, 13738, 13823, 13919, 13933, 14080, 14298, 14585, 14698, 15583, 15847, 16318, 16434, 16438, 16481, 16729, 17102, 17122, 17315, 17320, 17402, 17418, 17859, 17909, 17911, 17915, 17916, 17936, 17939, 17961, 18664, 18703, 18814, 18962, 19043, 33469, 33470, 33471, 33484, 33485, 33490, 33497, 33501, 33505, 33513, 33520, 33536, 33550, 37845, 37921, 37948, 38029, 38038, 38064, 38065, 38066, 38069, 38075, 38076, 38078, 39108, 39109, 39113, 39114, 39115, 39116, 39265, 39394, 189e3] }; + } +}); + +// node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/encodings/tables/cp949.json +var require_cp949 = __commonJS({ + "node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/encodings/tables/cp949.json"(exports, module) { + module.exports = [ + ["0", "\0", 127], + ["8141", "\uAC02\uAC03\uAC05\uAC06\uAC0B", 4, "\uAC18\uAC1E\uAC1F\uAC21\uAC22\uAC23\uAC25", 6, "\uAC2E\uAC32\uAC33\uAC34"], + ["8161", "\uAC35\uAC36\uAC37\uAC3A\uAC3B\uAC3D\uAC3E\uAC3F\uAC41", 9, "\uAC4C\uAC4E", 5, "\uAC55"], + ["8181", "\uAC56\uAC57\uAC59\uAC5A\uAC5B\uAC5D", 18, "\uAC72\uAC73\uAC75\uAC76\uAC79\uAC7B", 4, "\uAC82\uAC87\uAC88\uAC8D\uAC8E\uAC8F\uAC91\uAC92\uAC93\uAC95", 6, "\uAC9E\uACA2", 5, "\uACAB\uACAD\uACAE\uACB1", 6, "\uACBA\uACBE\uACBF\uACC0\uACC2\uACC3\uACC5\uACC6\uACC7\uACC9\uACCA\uACCB\uACCD", 7, "\uACD6\uACD8", 7, "\uACE2\uACE3\uACE5\uACE6\uACE9\uACEB\uACED\uACEE\uACF2\uACF4\uACF7", 4, "\uACFE\uACFF\uAD01\uAD02\uAD03\uAD05\uAD07", 4, "\uAD0E\uAD10\uAD12\uAD13"], + ["8241", "\uAD14\uAD15\uAD16\uAD17\uAD19\uAD1A\uAD1B\uAD1D\uAD1E\uAD1F\uAD21", 7, "\uAD2A\uAD2B\uAD2E", 5], + ["8261", "\uAD36\uAD37\uAD39\uAD3A\uAD3B\uAD3D", 6, "\uAD46\uAD48\uAD4A", 5, "\uAD51\uAD52\uAD53\uAD55\uAD56\uAD57"], + ["8281", "\uAD59", 7, "\uAD62\uAD64", 7, "\uAD6E\uAD6F\uAD71\uAD72\uAD77\uAD78\uAD79\uAD7A\uAD7E\uAD80\uAD83", 4, "\uAD8A\uAD8B\uAD8D\uAD8E\uAD8F\uAD91", 10, "\uAD9E", 5, "\uADA5", 17, "\uADB8", 7, "\uADC2\uADC3\uADC5\uADC6\uADC7\uADC9", 6, "\uADD2\uADD4", 7, "\uADDD\uADDE\uADDF\uADE1\uADE2\uADE3\uADE5", 18], + ["8341", "\uADFA\uADFB\uADFD\uADFE\uAE02", 5, "\uAE0A\uAE0C\uAE0E", 5, "\uAE15", 7], + ["8361", "\uAE1D", 18, "\uAE32\uAE33\uAE35\uAE36\uAE39\uAE3B\uAE3C"], + ["8381", "\uAE3D\uAE3E\uAE3F\uAE42\uAE44\uAE47\uAE48\uAE49\uAE4B\uAE4F\uAE51\uAE52\uAE53\uAE55\uAE57", 4, "\uAE5E\uAE62\uAE63\uAE64\uAE66\uAE67\uAE6A\uAE6B\uAE6D\uAE6E\uAE6F\uAE71", 6, "\uAE7A\uAE7E", 5, "\uAE86", 5, "\uAE8D", 46, "\uAEBF\uAEC1\uAEC2\uAEC3\uAEC5", 6, "\uAECE\uAED2", 5, "\uAEDA\uAEDB\uAEDD", 8], + ["8441", "\uAEE6\uAEE7\uAEE9\uAEEA\uAEEC\uAEEE", 5, "\uAEF5\uAEF6\uAEF7\uAEF9\uAEFA\uAEFB\uAEFD", 8], + ["8461", "\uAF06\uAF09\uAF0A\uAF0B\uAF0C\uAF0E\uAF0F\uAF11", 18], + ["8481", "\uAF24", 7, "\uAF2E\uAF2F\uAF31\uAF33\uAF35", 6, "\uAF3E\uAF40\uAF44\uAF45\uAF46\uAF47\uAF4A", 5, "\uAF51", 10, "\uAF5E", 5, "\uAF66", 18, "\uAF7A", 5, "\uAF81\uAF82\uAF83\uAF85\uAF86\uAF87\uAF89", 6, "\uAF92\uAF93\uAF94\uAF96", 5, "\uAF9D", 26, "\uAFBA\uAFBB\uAFBD\uAFBE"], + ["8541", "\uAFBF\uAFC1", 5, "\uAFCA\uAFCC\uAFCF", 4, "\uAFD5", 6, "\uAFDD", 4], + ["8561", "\uAFE2", 5, "\uAFEA", 5, "\uAFF2\uAFF3\uAFF5\uAFF6\uAFF7\uAFF9", 6, "\uB002\uB003"], + ["8581", "\uB005", 6, "\uB00D\uB00E\uB00F\uB011\uB012\uB013\uB015", 6, "\uB01E", 9, "\uB029", 26, "\uB046\uB047\uB049\uB04B\uB04D\uB04F\uB050\uB051\uB052\uB056\uB058\uB05A\uB05B\uB05C\uB05E", 29, "\uB07E\uB07F\uB081\uB082\uB083\uB085", 6, "\uB08E\uB090\uB092", 5, "\uB09B\uB09D\uB09E\uB0A3\uB0A4"], + ["8641", "\uB0A5\uB0A6\uB0A7\uB0AA\uB0B0\uB0B2\uB0B6\uB0B7\uB0B9\uB0BA\uB0BB\uB0BD", 6, "\uB0C6\uB0CA", 5, "\uB0D2"], + ["8661", "\uB0D3\uB0D5\uB0D6\uB0D7\uB0D9", 6, "\uB0E1\uB0E2\uB0E3\uB0E4\uB0E6", 10], + ["8681", "\uB0F1", 22, "\uB10A\uB10D\uB10E\uB10F\uB111\uB114\uB115\uB116\uB117\uB11A\uB11E", 4, "\uB126\uB127\uB129\uB12A\uB12B\uB12D", 6, "\uB136\uB13A", 5, "\uB142\uB143\uB145\uB146\uB147\uB149", 6, "\uB152\uB153\uB156\uB157\uB159\uB15A\uB15B\uB15D\uB15E\uB15F\uB161", 22, "\uB17A\uB17B\uB17D\uB17E\uB17F\uB181\uB183", 4, "\uB18A\uB18C\uB18E\uB18F\uB190\uB191\uB195\uB196\uB197\uB199\uB19A\uB19B\uB19D"], + ["8741", "\uB19E", 9, "\uB1A9", 15], + ["8761", "\uB1B9", 18, "\uB1CD\uB1CE\uB1CF\uB1D1\uB1D2\uB1D3\uB1D5"], + ["8781", "\uB1D6", 5, "\uB1DE\uB1E0", 7, "\uB1EA\uB1EB\uB1ED\uB1EE\uB1EF\uB1F1", 7, "\uB1FA\uB1FC\uB1FE", 5, "\uB206\uB207\uB209\uB20A\uB20D", 6, "\uB216\uB218\uB21A", 5, "\uB221", 18, "\uB235", 6, "\uB23D", 26, "\uB259\uB25A\uB25B\uB25D\uB25E\uB25F\uB261", 6, "\uB26A", 4], + ["8841", "\uB26F", 4, "\uB276", 5, "\uB27D", 6, "\uB286\uB287\uB288\uB28A", 4], + ["8861", "\uB28F\uB292\uB293\uB295\uB296\uB297\uB29B", 4, "\uB2A2\uB2A4\uB2A7\uB2A8\uB2A9\uB2AB\uB2AD\uB2AE\uB2AF\uB2B1\uB2B2\uB2B3\uB2B5\uB2B6\uB2B7"], + ["8881", "\uB2B8", 15, "\uB2CA\uB2CB\uB2CD\uB2CE\uB2CF\uB2D1\uB2D3", 4, "\uB2DA\uB2DC\uB2DE\uB2DF\uB2E0\uB2E1\uB2E3\uB2E7\uB2E9\uB2EA\uB2F0\uB2F1\uB2F2\uB2F6\uB2FC\uB2FD\uB2FE\uB302\uB303\uB305\uB306\uB307\uB309", 6, "\uB312\uB316", 5, "\uB31D", 54, "\uB357\uB359\uB35A\uB35D\uB360\uB361\uB362\uB363"], + ["8941", "\uB366\uB368\uB36A\uB36C\uB36D\uB36F\uB372\uB373\uB375\uB376\uB377\uB379", 6, "\uB382\uB386", 5, "\uB38D"], + ["8961", "\uB38E\uB38F\uB391\uB392\uB393\uB395", 10, "\uB3A2", 5, "\uB3A9\uB3AA\uB3AB\uB3AD"], + ["8981", "\uB3AE", 21, "\uB3C6\uB3C7\uB3C9\uB3CA\uB3CD\uB3CF\uB3D1\uB3D2\uB3D3\uB3D6\uB3D8\uB3DA\uB3DC\uB3DE\uB3DF\uB3E1\uB3E2\uB3E3\uB3E5\uB3E6\uB3E7\uB3E9", 18, "\uB3FD", 18, "\uB411", 6, "\uB419\uB41A\uB41B\uB41D\uB41E\uB41F\uB421", 6, "\uB42A\uB42C", 7, "\uB435", 15], + ["8a41", "\uB445", 10, "\uB452\uB453\uB455\uB456\uB457\uB459", 6, "\uB462\uB464\uB466"], + ["8a61", "\uB467", 4, "\uB46D", 18, "\uB481\uB482"], + ["8a81", "\uB483", 4, "\uB489", 19, "\uB49E", 5, "\uB4A5\uB4A6\uB4A7\uB4A9\uB4AA\uB4AB\uB4AD", 7, "\uB4B6\uB4B8\uB4BA", 5, "\uB4C1\uB4C2\uB4C3\uB4C5\uB4C6\uB4C7\uB4C9", 6, "\uB4D1\uB4D2\uB4D3\uB4D4\uB4D6", 5, "\uB4DE\uB4DF\uB4E1\uB4E2\uB4E5\uB4E7", 4, "\uB4EE\uB4F0\uB4F2", 5, "\uB4F9", 26, "\uB516\uB517\uB519\uB51A\uB51D"], + ["8b41", "\uB51E", 5, "\uB526\uB52B", 4, "\uB532\uB533\uB535\uB536\uB537\uB539", 6, "\uB542\uB546"], + ["8b61", "\uB547\uB548\uB549\uB54A\uB54E\uB54F\uB551\uB552\uB553\uB555", 6, "\uB55E\uB562", 8], + ["8b81", "\uB56B", 52, "\uB5A2\uB5A3\uB5A5\uB5A6\uB5A7\uB5A9\uB5AC\uB5AD\uB5AE\uB5AF\uB5B2\uB5B6", 4, "\uB5BE\uB5BF\uB5C1\uB5C2\uB5C3\uB5C5", 6, "\uB5CE\uB5D2", 5, "\uB5D9", 18, "\uB5ED", 18], + ["8c41", "\uB600", 15, "\uB612\uB613\uB615\uB616\uB617\uB619", 4], + ["8c61", "\uB61E", 6, "\uB626", 5, "\uB62D", 6, "\uB635", 5], + ["8c81", "\uB63B", 12, "\uB649", 26, "\uB665\uB666\uB667\uB669", 50, "\uB69E\uB69F\uB6A1\uB6A2\uB6A3\uB6A5", 5, "\uB6AD\uB6AE\uB6AF\uB6B0\uB6B2", 16], + ["8d41", "\uB6C3", 16, "\uB6D5", 8], + ["8d61", "\uB6DE", 17, "\uB6F1\uB6F2\uB6F3\uB6F5\uB6F6\uB6F7\uB6F9\uB6FA"], + ["8d81", "\uB6FB", 4, "\uB702\uB703\uB704\uB706", 33, "\uB72A\uB72B\uB72D\uB72E\uB731", 6, "\uB73A\uB73C", 7, "\uB745\uB746\uB747\uB749\uB74A\uB74B\uB74D", 6, "\uB756", 9, "\uB761\uB762\uB763\uB765\uB766\uB767\uB769", 6, "\uB772\uB774\uB776", 5, "\uB77E\uB77F\uB781\uB782\uB783\uB785", 6, "\uB78E\uB793\uB794\uB795\uB79A\uB79B\uB79D\uB79E"], + ["8e41", "\uB79F\uB7A1", 6, "\uB7AA\uB7AE", 5, "\uB7B6\uB7B7\uB7B9", 8], + ["8e61", "\uB7C2", 4, "\uB7C8\uB7CA", 19], + ["8e81", "\uB7DE", 13, "\uB7EE\uB7EF\uB7F1\uB7F2\uB7F3\uB7F5", 6, "\uB7FE\uB802", 4, "\uB80A\uB80B\uB80D\uB80E\uB80F\uB811", 6, "\uB81A\uB81C\uB81E", 5, "\uB826\uB827\uB829\uB82A\uB82B\uB82D", 6, "\uB836\uB83A", 5, "\uB841\uB842\uB843\uB845", 11, "\uB852\uB854", 7, "\uB85E\uB85F\uB861\uB862\uB863\uB865", 6, "\uB86E\uB870\uB872", 5, "\uB879\uB87A\uB87B\uB87D", 7], + ["8f41", "\uB885", 7, "\uB88E", 17], + ["8f61", "\uB8A0", 7, "\uB8A9", 6, "\uB8B1\uB8B2\uB8B3\uB8B5\uB8B6\uB8B7\uB8B9", 4], + ["8f81", "\uB8BE\uB8BF\uB8C2\uB8C4\uB8C6", 5, "\uB8CD\uB8CE\uB8CF\uB8D1\uB8D2\uB8D3\uB8D5", 7, "\uB8DE\uB8E0\uB8E2", 5, "\uB8EA\uB8EB\uB8ED\uB8EE\uB8EF\uB8F1", 6, "\uB8FA\uB8FC\uB8FE", 5, "\uB905", 18, "\uB919", 6, "\uB921", 26, "\uB93E\uB93F\uB941\uB942\uB943\uB945", 6, "\uB94D\uB94E\uB950\uB952", 5], + ["9041", "\uB95A\uB95B\uB95D\uB95E\uB95F\uB961", 6, "\uB96A\uB96C\uB96E", 5, "\uB976\uB977\uB979\uB97A\uB97B\uB97D"], + ["9061", "\uB97E", 5, "\uB986\uB988\uB98B\uB98C\uB98F", 15], + ["9081", "\uB99F", 12, "\uB9AE\uB9AF\uB9B1\uB9B2\uB9B3\uB9B5", 6, "\uB9BE\uB9C0\uB9C2", 5, "\uB9CA\uB9CB\uB9CD\uB9D3", 4, "\uB9DA\uB9DC\uB9DF\uB9E0\uB9E2\uB9E6\uB9E7\uB9E9\uB9EA\uB9EB\uB9ED", 6, "\uB9F6\uB9FB", 4, "\uBA02", 5, "\uBA09", 11, "\uBA16", 33, "\uBA3A\uBA3B\uBA3D\uBA3E\uBA3F\uBA41\uBA43\uBA44\uBA45\uBA46"], + ["9141", "\uBA47\uBA4A\uBA4C\uBA4F\uBA50\uBA51\uBA52\uBA56\uBA57\uBA59\uBA5A\uBA5B\uBA5D", 6, "\uBA66\uBA6A", 5], + ["9161", "\uBA72\uBA73\uBA75\uBA76\uBA77\uBA79", 9, "\uBA86\uBA88\uBA89\uBA8A\uBA8B\uBA8D", 5], + ["9181", "\uBA93", 20, "\uBAAA\uBAAD\uBAAE\uBAAF\uBAB1\uBAB3", 4, "\uBABA\uBABC\uBABE", 5, "\uBAC5\uBAC6\uBAC7\uBAC9", 14, "\uBADA", 33, "\uBAFD\uBAFE\uBAFF\uBB01\uBB02\uBB03\uBB05", 7, "\uBB0E\uBB10\uBB12", 5, "\uBB19\uBB1A\uBB1B\uBB1D\uBB1E\uBB1F\uBB21", 6], + ["9241", "\uBB28\uBB2A\uBB2C", 7, "\uBB37\uBB39\uBB3A\uBB3F", 4, "\uBB46\uBB48\uBB4A\uBB4B\uBB4C\uBB4E\uBB51\uBB52"], + ["9261", "\uBB53\uBB55\uBB56\uBB57\uBB59", 7, "\uBB62\uBB64", 7, "\uBB6D", 4], + ["9281", "\uBB72", 21, "\uBB89\uBB8A\uBB8B\uBB8D\uBB8E\uBB8F\uBB91", 18, "\uBBA5\uBBA6\uBBA7\uBBA9\uBBAA\uBBAB\uBBAD", 6, "\uBBB5\uBBB6\uBBB8", 7, "\uBBC1\uBBC2\uBBC3\uBBC5\uBBC6\uBBC7\uBBC9", 6, "\uBBD1\uBBD2\uBBD4", 35, "\uBBFA\uBBFB\uBBFD\uBBFE\uBC01"], + ["9341", "\uBC03", 4, "\uBC0A\uBC0E\uBC10\uBC12\uBC13\uBC19\uBC1A\uBC20\uBC21\uBC22\uBC23\uBC26\uBC28\uBC2A\uBC2B\uBC2C\uBC2E\uBC2F\uBC32\uBC33\uBC35"], + ["9361", "\uBC36\uBC37\uBC39", 6, "\uBC42\uBC46\uBC47\uBC48\uBC4A\uBC4B\uBC4E\uBC4F\uBC51", 8], + ["9381", "\uBC5A\uBC5B\uBC5C\uBC5E", 37, "\uBC86\uBC87\uBC89\uBC8A\uBC8D\uBC8F", 4, "\uBC96\uBC98\uBC9B", 4, "\uBCA2\uBCA3\uBCA5\uBCA6\uBCA9", 6, "\uBCB2\uBCB6", 5, "\uBCBE\uBCBF\uBCC1\uBCC2\uBCC3\uBCC5", 7, "\uBCCE\uBCD2\uBCD3\uBCD4\uBCD6\uBCD7\uBCD9\uBCDA\uBCDB\uBCDD", 22, "\uBCF7\uBCF9\uBCFA\uBCFB\uBCFD"], + ["9441", "\uBCFE", 5, "\uBD06\uBD08\uBD0A", 5, "\uBD11\uBD12\uBD13\uBD15", 8], + ["9461", "\uBD1E", 5, "\uBD25", 6, "\uBD2D", 12], + ["9481", "\uBD3A", 5, "\uBD41", 6, "\uBD4A\uBD4B\uBD4D\uBD4E\uBD4F\uBD51", 6, "\uBD5A", 9, "\uBD65\uBD66\uBD67\uBD69", 22, "\uBD82\uBD83\uBD85\uBD86\uBD8B", 4, "\uBD92\uBD94\uBD96\uBD97\uBD98\uBD9B\uBD9D", 6, "\uBDA5", 10, "\uBDB1", 6, "\uBDB9", 24], + ["9541", "\uBDD2\uBDD3\uBDD6\uBDD7\uBDD9\uBDDA\uBDDB\uBDDD", 11, "\uBDEA", 5, "\uBDF1"], + ["9561", "\uBDF2\uBDF3\uBDF5\uBDF6\uBDF7\uBDF9", 6, "\uBE01\uBE02\uBE04\uBE06", 5, "\uBE0E\uBE0F\uBE11\uBE12\uBE13"], + ["9581", "\uBE15", 6, "\uBE1E\uBE20", 35, "\uBE46\uBE47\uBE49\uBE4A\uBE4B\uBE4D\uBE4F", 4, "\uBE56\uBE58\uBE5C\uBE5D\uBE5E\uBE5F\uBE62\uBE63\uBE65\uBE66\uBE67\uBE69\uBE6B", 4, "\uBE72\uBE76", 4, "\uBE7E\uBE7F\uBE81\uBE82\uBE83\uBE85", 6, "\uBE8E\uBE92", 5, "\uBE9A", 13, "\uBEA9", 14], + ["9641", "\uBEB8", 23, "\uBED2\uBED3"], + ["9661", "\uBED5\uBED6\uBED9", 6, "\uBEE1\uBEE2\uBEE6", 5, "\uBEED", 8], + ["9681", "\uBEF6", 10, "\uBF02", 5, "\uBF0A", 13, "\uBF1A\uBF1E", 33, "\uBF42\uBF43\uBF45\uBF46\uBF47\uBF49", 6, "\uBF52\uBF53\uBF54\uBF56", 44], + ["9741", "\uBF83", 16, "\uBF95", 8], + ["9761", "\uBF9E", 17, "\uBFB1", 7], + ["9781", "\uBFB9", 11, "\uBFC6", 5, "\uBFCE\uBFCF\uBFD1\uBFD2\uBFD3\uBFD5", 6, "\uBFDD\uBFDE\uBFE0\uBFE2", 89, "\uC03D\uC03E\uC03F"], + ["9841", "\uC040", 16, "\uC052", 5, "\uC059\uC05A\uC05B"], + ["9861", "\uC05D\uC05E\uC05F\uC061", 6, "\uC06A", 15], + ["9881", "\uC07A", 21, "\uC092\uC093\uC095\uC096\uC097\uC099", 6, "\uC0A2\uC0A4\uC0A6", 5, "\uC0AE\uC0B1\uC0B2\uC0B7", 4, "\uC0BE\uC0C2\uC0C3\uC0C4\uC0C6\uC0C7\uC0CA\uC0CB\uC0CD\uC0CE\uC0CF\uC0D1", 6, "\uC0DA\uC0DE", 5, "\uC0E6\uC0E7\uC0E9\uC0EA\uC0EB\uC0ED", 6, "\uC0F6\uC0F8\uC0FA", 5, "\uC101\uC102\uC103\uC105\uC106\uC107\uC109", 6, "\uC111\uC112\uC113\uC114\uC116", 5, "\uC121\uC122\uC125\uC128\uC129\uC12A\uC12B\uC12E"], + ["9941", "\uC132\uC133\uC134\uC135\uC137\uC13A\uC13B\uC13D\uC13E\uC13F\uC141", 6, "\uC14A\uC14E", 5, "\uC156\uC157"], + ["9961", "\uC159\uC15A\uC15B\uC15D", 6, "\uC166\uC16A", 5, "\uC171\uC172\uC173\uC175\uC176\uC177\uC179\uC17A\uC17B"], + ["9981", "\uC17C", 8, "\uC186", 5, "\uC18F\uC191\uC192\uC193\uC195\uC197", 4, "\uC19E\uC1A0\uC1A2\uC1A3\uC1A4\uC1A6\uC1A7\uC1AA\uC1AB\uC1AD\uC1AE\uC1AF\uC1B1", 11, "\uC1BE", 5, "\uC1C5\uC1C6\uC1C7\uC1C9\uC1CA\uC1CB\uC1CD", 6, "\uC1D5\uC1D6\uC1D9", 6, "\uC1E1\uC1E2\uC1E3\uC1E5\uC1E6\uC1E7\uC1E9", 6, "\uC1F2\uC1F4", 7, "\uC1FE\uC1FF\uC201\uC202\uC203\uC205", 6, "\uC20E\uC210\uC212", 5, "\uC21A\uC21B\uC21D\uC21E\uC221\uC222\uC223"], + ["9a41", "\uC224\uC225\uC226\uC227\uC22A\uC22C\uC22E\uC230\uC233\uC235", 16], + ["9a61", "\uC246\uC247\uC249", 6, "\uC252\uC253\uC255\uC256\uC257\uC259", 6, "\uC261\uC262\uC263\uC264\uC266"], + ["9a81", "\uC267", 4, "\uC26E\uC26F\uC271\uC272\uC273\uC275", 6, "\uC27E\uC280\uC282", 5, "\uC28A", 5, "\uC291", 6, "\uC299\uC29A\uC29C\uC29E", 5, "\uC2A6\uC2A7\uC2A9\uC2AA\uC2AB\uC2AE", 5, "\uC2B6\uC2B8\uC2BA", 33, "\uC2DE\uC2DF\uC2E1\uC2E2\uC2E5", 5, "\uC2EE\uC2F0\uC2F2\uC2F3\uC2F4\uC2F5\uC2F7\uC2FA\uC2FD\uC2FE\uC2FF\uC301", 6, "\uC30A\uC30B\uC30E\uC30F"], + ["9b41", "\uC310\uC311\uC312\uC316\uC317\uC319\uC31A\uC31B\uC31D", 6, "\uC326\uC327\uC32A", 8], + ["9b61", "\uC333", 17, "\uC346", 7], + ["9b81", "\uC34E", 25, "\uC36A\uC36B\uC36D\uC36E\uC36F\uC371\uC373", 4, "\uC37A\uC37B\uC37E", 5, "\uC385\uC386\uC387\uC389\uC38A\uC38B\uC38D", 50, "\uC3C1", 22, "\uC3DA"], + ["9c41", "\uC3DB\uC3DD\uC3DE\uC3E1\uC3E3", 4, "\uC3EA\uC3EB\uC3EC\uC3EE", 5, "\uC3F6\uC3F7\uC3F9", 5], + ["9c61", "\uC3FF", 8, "\uC409", 6, "\uC411", 9], + ["9c81", "\uC41B", 8, "\uC425", 6, "\uC42D\uC42E\uC42F\uC431\uC432\uC433\uC435", 6, "\uC43E", 9, "\uC449", 26, "\uC466\uC467\uC469\uC46A\uC46B\uC46D", 6, "\uC476\uC477\uC478\uC47A", 5, "\uC481", 18, "\uC495", 6, "\uC49D", 12], + ["9d41", "\uC4AA", 13, "\uC4B9\uC4BA\uC4BB\uC4BD", 8], + ["9d61", "\uC4C6", 25], + ["9d81", "\uC4E0", 8, "\uC4EA", 5, "\uC4F2\uC4F3\uC4F5\uC4F6\uC4F7\uC4F9\uC4FB\uC4FC\uC4FD\uC4FE\uC502", 9, "\uC50D\uC50E\uC50F\uC511\uC512\uC513\uC515", 6, "\uC51D", 10, "\uC52A\uC52B\uC52D\uC52E\uC52F\uC531", 6, "\uC53A\uC53C\uC53E", 5, "\uC546\uC547\uC54B\uC54F\uC550\uC551\uC552\uC556\uC55A\uC55B\uC55C\uC55F\uC562\uC563\uC565\uC566\uC567\uC569", 6, "\uC572\uC576", 5, "\uC57E\uC57F\uC581\uC582\uC583\uC585\uC586\uC588\uC589\uC58A\uC58B\uC58E\uC590\uC592\uC593\uC594"], + ["9e41", "\uC596\uC599\uC59A\uC59B\uC59D\uC59E\uC59F\uC5A1", 7, "\uC5AA", 9, "\uC5B6"], + ["9e61", "\uC5B7\uC5BA\uC5BF", 4, "\uC5CB\uC5CD\uC5CF\uC5D2\uC5D3\uC5D5\uC5D6\uC5D7\uC5D9", 6, "\uC5E2\uC5E4\uC5E6\uC5E7"], + ["9e81", "\uC5E8\uC5E9\uC5EA\uC5EB\uC5EF\uC5F1\uC5F2\uC5F3\uC5F5\uC5F8\uC5F9\uC5FA\uC5FB\uC602\uC603\uC604\uC609\uC60A\uC60B\uC60D\uC60E\uC60F\uC611", 6, "\uC61A\uC61D", 6, "\uC626\uC627\uC629\uC62A\uC62B\uC62F\uC631\uC632\uC636\uC638\uC63A\uC63C\uC63D\uC63E\uC63F\uC642\uC643\uC645\uC646\uC647\uC649", 6, "\uC652\uC656", 5, "\uC65E\uC65F\uC661", 10, "\uC66D\uC66E\uC670\uC672", 5, "\uC67A\uC67B\uC67D\uC67E\uC67F\uC681", 6, "\uC68A\uC68C\uC68E", 5, "\uC696\uC697\uC699\uC69A\uC69B\uC69D", 6, "\uC6A6"], + ["9f41", "\uC6A8\uC6AA", 5, "\uC6B2\uC6B3\uC6B5\uC6B6\uC6B7\uC6BB", 4, "\uC6C2\uC6C4\uC6C6", 5, "\uC6CE"], + ["9f61", "\uC6CF\uC6D1\uC6D2\uC6D3\uC6D5", 6, "\uC6DE\uC6DF\uC6E2", 5, "\uC6EA\uC6EB\uC6ED\uC6EE\uC6EF\uC6F1\uC6F2"], + ["9f81", "\uC6F3", 4, "\uC6FA\uC6FB\uC6FC\uC6FE", 5, "\uC706\uC707\uC709\uC70A\uC70B\uC70D", 6, "\uC716\uC718\uC71A", 5, "\uC722\uC723\uC725\uC726\uC727\uC729", 6, "\uC732\uC734\uC736\uC738\uC739\uC73A\uC73B\uC73E\uC73F\uC741\uC742\uC743\uC745", 4, "\uC74B\uC74E\uC750\uC759\uC75A\uC75B\uC75D\uC75E\uC75F\uC761", 6, "\uC769\uC76A\uC76C", 7, "\uC776\uC777\uC779\uC77A\uC77B\uC77F\uC780\uC781\uC782\uC786\uC78B\uC78C\uC78D\uC78F\uC792\uC793\uC795\uC799\uC79B", 4, "\uC7A2\uC7A7", 4, "\uC7AE\uC7AF\uC7B1\uC7B2\uC7B3\uC7B5\uC7B6\uC7B7"], + ["a041", "\uC7B8\uC7B9\uC7BA\uC7BB\uC7BE\uC7C2", 5, "\uC7CA\uC7CB\uC7CD\uC7CF\uC7D1", 6, "\uC7D9\uC7DA\uC7DB\uC7DC"], + ["a061", "\uC7DE", 5, "\uC7E5\uC7E6\uC7E7\uC7E9\uC7EA\uC7EB\uC7ED", 13], + ["a081", "\uC7FB", 4, "\uC802\uC803\uC805\uC806\uC807\uC809\uC80B", 4, "\uC812\uC814\uC817", 4, "\uC81E\uC81F\uC821\uC822\uC823\uC825", 6, "\uC82E\uC830\uC832", 5, "\uC839\uC83A\uC83B\uC83D\uC83E\uC83F\uC841", 6, "\uC84A\uC84B\uC84E", 5, "\uC855", 26, "\uC872\uC873\uC875\uC876\uC877\uC879\uC87B", 4, "\uC882\uC884\uC888\uC889\uC88A\uC88E", 5, "\uC895", 7, "\uC89E\uC8A0\uC8A2\uC8A3\uC8A4"], + ["a141", "\uC8A5\uC8A6\uC8A7\uC8A9", 18, "\uC8BE\uC8BF\uC8C0\uC8C1"], + ["a161", "\uC8C2\uC8C3\uC8C5\uC8C6\uC8C7\uC8C9\uC8CA\uC8CB\uC8CD", 6, "\uC8D6\uC8D8\uC8DA", 5, "\uC8E2\uC8E3\uC8E5"], + ["a181", "\uC8E6", 14, "\uC8F6", 5, "\uC8FE\uC8FF\uC901\uC902\uC903\uC907", 4, "\uC90E\u3000\u3001\u3002\xB7\u2025\u2026\xA8\u3003\xAD\u2015\u2225\uFF3C\u223C\u2018\u2019\u201C\u201D\u3014\u3015\u3008", 9, "\xB1\xD7\xF7\u2260\u2264\u2265\u221E\u2234\xB0\u2032\u2033\u2103\u212B\uFFE0\uFFE1\uFFE5\u2642\u2640\u2220\u22A5\u2312\u2202\u2207\u2261\u2252\xA7\u203B\u2606\u2605\u25CB\u25CF\u25CE\u25C7\u25C6\u25A1\u25A0\u25B3\u25B2\u25BD\u25BC\u2192\u2190\u2191\u2193\u2194\u3013\u226A\u226B\u221A\u223D\u221D\u2235\u222B\u222C\u2208\u220B\u2286\u2287\u2282\u2283\u222A\u2229\u2227\u2228\uFFE2"], + ["a241", "\uC910\uC912", 5, "\uC919", 18], + ["a261", "\uC92D", 6, "\uC935", 18], + ["a281", "\uC948", 7, "\uC952\uC953\uC955\uC956\uC957\uC959", 6, "\uC962\uC964", 7, "\uC96D\uC96E\uC96F\u21D2\u21D4\u2200\u2203\xB4\uFF5E\u02C7\u02D8\u02DD\u02DA\u02D9\xB8\u02DB\xA1\xBF\u02D0\u222E\u2211\u220F\xA4\u2109\u2030\u25C1\u25C0\u25B7\u25B6\u2664\u2660\u2661\u2665\u2667\u2663\u2299\u25C8\u25A3\u25D0\u25D1\u2592\u25A4\u25A5\u25A8\u25A7\u25A6\u25A9\u2668\u260F\u260E\u261C\u261E\xB6\u2020\u2021\u2195\u2197\u2199\u2196\u2198\u266D\u2669\u266A\u266C\u327F\u321C\u2116\u33C7\u2122\u33C2\u33D8\u2121\u20AC\xAE"], + ["a341", "\uC971\uC972\uC973\uC975", 6, "\uC97D", 10, "\uC98A\uC98B\uC98D\uC98E\uC98F"], + ["a361", "\uC991", 6, "\uC99A\uC99C\uC99E", 16], + ["a381", "\uC9AF", 16, "\uC9C2\uC9C3\uC9C5\uC9C6\uC9C9\uC9CB", 4, "\uC9D2\uC9D4\uC9D7\uC9D8\uC9DB\uFF01", 58, "\uFFE6\uFF3D", 32, "\uFFE3"], + ["a441", "\uC9DE\uC9DF\uC9E1\uC9E3\uC9E5\uC9E6\uC9E8\uC9E9\uC9EA\uC9EB\uC9EE\uC9F2", 5, "\uC9FA\uC9FB\uC9FD\uC9FE\uC9FF\uCA01\uCA02\uCA03\uCA04"], + ["a461", "\uCA05\uCA06\uCA07\uCA0A\uCA0E", 5, "\uCA15\uCA16\uCA17\uCA19", 12], + ["a481", "\uCA26\uCA27\uCA28\uCA2A", 28, "\u3131", 93], + ["a541", "\uCA47", 4, "\uCA4E\uCA4F\uCA51\uCA52\uCA53\uCA55", 6, "\uCA5E\uCA62", 5, "\uCA69\uCA6A"], + ["a561", "\uCA6B", 17, "\uCA7E", 5, "\uCA85\uCA86"], + ["a581", "\uCA87", 16, "\uCA99", 14, "\u2170", 9], + ["a5b0", "\u2160", 9], + ["a5c1", "\u0391", 16, "\u03A3", 6], + ["a5e1", "\u03B1", 16, "\u03C3", 6], + ["a641", "\uCAA8", 19, "\uCABE\uCABF\uCAC1\uCAC2\uCAC3\uCAC5"], + ["a661", "\uCAC6", 5, "\uCACE\uCAD0\uCAD2\uCAD4\uCAD5\uCAD6\uCAD7\uCADA", 5, "\uCAE1", 6], + ["a681", "\uCAE8\uCAE9\uCAEA\uCAEB\uCAED", 6, "\uCAF5", 18, "\uCB09\uCB0A\u2500\u2502\u250C\u2510\u2518\u2514\u251C\u252C\u2524\u2534\u253C\u2501\u2503\u250F\u2513\u251B\u2517\u2523\u2533\u252B\u253B\u254B\u2520\u252F\u2528\u2537\u253F\u251D\u2530\u2525\u2538\u2542\u2512\u2511\u251A\u2519\u2516\u2515\u250E\u250D\u251E\u251F\u2521\u2522\u2526\u2527\u2529\u252A\u252D\u252E\u2531\u2532\u2535\u2536\u2539\u253A\u253D\u253E\u2540\u2541\u2543", 7], + ["a741", "\uCB0B", 4, "\uCB11\uCB12\uCB13\uCB15\uCB16\uCB17\uCB19", 6, "\uCB22", 7], + ["a761", "\uCB2A", 22, "\uCB42\uCB43\uCB44"], + ["a781", "\uCB45\uCB46\uCB47\uCB4A\uCB4B\uCB4D\uCB4E\uCB4F\uCB51", 6, "\uCB5A\uCB5B\uCB5C\uCB5E", 5, "\uCB65", 7, "\u3395\u3396\u3397\u2113\u3398\u33C4\u33A3\u33A4\u33A5\u33A6\u3399", 9, "\u33CA\u338D\u338E\u338F\u33CF\u3388\u3389\u33C8\u33A7\u33A8\u33B0", 9, "\u3380", 4, "\u33BA", 5, "\u3390", 4, "\u2126\u33C0\u33C1\u338A\u338B\u338C\u33D6\u33C5\u33AD\u33AE\u33AF\u33DB\u33A9\u33AA\u33AB\u33AC\u33DD\u33D0\u33D3\u33C3\u33C9\u33DC\u33C6"], + ["a841", "\uCB6D", 10, "\uCB7A", 14], + ["a861", "\uCB89", 18, "\uCB9D", 6], + ["a881", "\uCBA4", 19, "\uCBB9", 11, "\xC6\xD0\xAA\u0126"], + ["a8a6", "\u0132"], + ["a8a8", "\u013F\u0141\xD8\u0152\xBA\xDE\u0166\u014A"], + ["a8b1", "\u3260", 27, "\u24D0", 25, "\u2460", 14, "\xBD\u2153\u2154\xBC\xBE\u215B\u215C\u215D\u215E"], + ["a941", "\uCBC5", 14, "\uCBD5", 10], + ["a961", "\uCBE0\uCBE1\uCBE2\uCBE3\uCBE5\uCBE6\uCBE8\uCBEA", 18], + ["a981", "\uCBFD", 14, "\uCC0E\uCC0F\uCC11\uCC12\uCC13\uCC15", 6, "\uCC1E\uCC1F\uCC20\uCC23\uCC24\xE6\u0111\xF0\u0127\u0131\u0133\u0138\u0140\u0142\xF8\u0153\xDF\xFE\u0167\u014B\u0149\u3200", 27, "\u249C", 25, "\u2474", 14, "\xB9\xB2\xB3\u2074\u207F\u2081\u2082\u2083\u2084"], + ["aa41", "\uCC25\uCC26\uCC2A\uCC2B\uCC2D\uCC2F\uCC31", 6, "\uCC3A\uCC3F", 4, "\uCC46\uCC47\uCC49\uCC4A\uCC4B\uCC4D\uCC4E"], + ["aa61", "\uCC4F", 4, "\uCC56\uCC5A", 5, "\uCC61\uCC62\uCC63\uCC65\uCC67\uCC69", 6, "\uCC71\uCC72"], + ["aa81", "\uCC73\uCC74\uCC76", 29, "\u3041", 82], + ["ab41", "\uCC94\uCC95\uCC96\uCC97\uCC9A\uCC9B\uCC9D\uCC9E\uCC9F\uCCA1", 6, "\uCCAA\uCCAE", 5, "\uCCB6\uCCB7\uCCB9"], + ["ab61", "\uCCBA\uCCBB\uCCBD", 6, "\uCCC6\uCCC8\uCCCA", 5, "\uCCD1\uCCD2\uCCD3\uCCD5", 5], + ["ab81", "\uCCDB", 8, "\uCCE5", 6, "\uCCED\uCCEE\uCCEF\uCCF1", 12, "\u30A1", 85], + ["ac41", "\uCCFE\uCCFF\uCD00\uCD02", 5, "\uCD0A\uCD0B\uCD0D\uCD0E\uCD0F\uCD11", 6, "\uCD1A\uCD1C\uCD1E\uCD1F\uCD20"], + ["ac61", "\uCD21\uCD22\uCD23\uCD25\uCD26\uCD27\uCD29\uCD2A\uCD2B\uCD2D", 11, "\uCD3A", 4], + ["ac81", "\uCD3F", 28, "\uCD5D\uCD5E\uCD5F\u0410", 5, "\u0401\u0416", 25], + ["acd1", "\u0430", 5, "\u0451\u0436", 25], + ["ad41", "\uCD61\uCD62\uCD63\uCD65", 6, "\uCD6E\uCD70\uCD72", 5, "\uCD79", 7], + ["ad61", "\uCD81", 6, "\uCD89", 10, "\uCD96\uCD97\uCD99\uCD9A\uCD9B\uCD9D\uCD9E\uCD9F"], + ["ad81", "\uCDA0\uCDA1\uCDA2\uCDA3\uCDA6\uCDA8\uCDAA", 5, "\uCDB1", 18, "\uCDC5"], + ["ae41", "\uCDC6", 5, "\uCDCD\uCDCE\uCDCF\uCDD1", 16], + ["ae61", "\uCDE2", 5, "\uCDE9\uCDEA\uCDEB\uCDED\uCDEE\uCDEF\uCDF1", 6, "\uCDFA\uCDFC\uCDFE", 4], + ["ae81", "\uCE03\uCE05\uCE06\uCE07\uCE09\uCE0A\uCE0B\uCE0D", 6, "\uCE15\uCE16\uCE17\uCE18\uCE1A", 5, "\uCE22\uCE23\uCE25\uCE26\uCE27\uCE29\uCE2A\uCE2B"], + ["af41", "\uCE2C\uCE2D\uCE2E\uCE2F\uCE32\uCE34\uCE36", 19], + ["af61", "\uCE4A", 13, "\uCE5A\uCE5B\uCE5D\uCE5E\uCE62", 5, "\uCE6A\uCE6C"], + ["af81", "\uCE6E", 5, "\uCE76\uCE77\uCE79\uCE7A\uCE7B\uCE7D", 6, "\uCE86\uCE88\uCE8A", 5, "\uCE92\uCE93\uCE95\uCE96\uCE97\uCE99"], + ["b041", "\uCE9A", 5, "\uCEA2\uCEA6", 5, "\uCEAE", 12], + ["b061", "\uCEBB", 5, "\uCEC2", 19], + ["b081", "\uCED6", 13, "\uCEE6\uCEE7\uCEE9\uCEEA\uCEED", 6, "\uCEF6\uCEFA", 5, "\uAC00\uAC01\uAC04\uAC07\uAC08\uAC09\uAC0A\uAC10", 7, "\uAC19", 4, "\uAC20\uAC24\uAC2C\uAC2D\uAC2F\uAC30\uAC31\uAC38\uAC39\uAC3C\uAC40\uAC4B\uAC4D\uAC54\uAC58\uAC5C\uAC70\uAC71\uAC74\uAC77\uAC78\uAC7A\uAC80\uAC81\uAC83\uAC84\uAC85\uAC86\uAC89\uAC8A\uAC8B\uAC8C\uAC90\uAC94\uAC9C\uAC9D\uAC9F\uACA0\uACA1\uACA8\uACA9\uACAA\uACAC\uACAF\uACB0\uACB8\uACB9\uACBB\uACBC\uACBD\uACC1\uACC4\uACC8\uACCC\uACD5\uACD7\uACE0\uACE1\uACE4\uACE7\uACE8\uACEA\uACEC\uACEF\uACF0\uACF1\uACF3\uACF5\uACF6\uACFC\uACFD\uAD00\uAD04\uAD06"], + ["b141", "\uCF02\uCF03\uCF05\uCF06\uCF07\uCF09", 6, "\uCF12\uCF14\uCF16", 5, "\uCF1D\uCF1E\uCF1F\uCF21\uCF22\uCF23"], + ["b161", "\uCF25", 6, "\uCF2E\uCF32", 5, "\uCF39", 11], + ["b181", "\uCF45", 14, "\uCF56\uCF57\uCF59\uCF5A\uCF5B\uCF5D", 6, "\uCF66\uCF68\uCF6A\uCF6B\uCF6C\uAD0C\uAD0D\uAD0F\uAD11\uAD18\uAD1C\uAD20\uAD29\uAD2C\uAD2D\uAD34\uAD35\uAD38\uAD3C\uAD44\uAD45\uAD47\uAD49\uAD50\uAD54\uAD58\uAD61\uAD63\uAD6C\uAD6D\uAD70\uAD73\uAD74\uAD75\uAD76\uAD7B\uAD7C\uAD7D\uAD7F\uAD81\uAD82\uAD88\uAD89\uAD8C\uAD90\uAD9C\uAD9D\uADA4\uADB7\uADC0\uADC1\uADC4\uADC8\uADD0\uADD1\uADD3\uADDC\uADE0\uADE4\uADF8\uADF9\uADFC\uADFF\uAE00\uAE01\uAE08\uAE09\uAE0B\uAE0D\uAE14\uAE30\uAE31\uAE34\uAE37\uAE38\uAE3A\uAE40\uAE41\uAE43\uAE45\uAE46\uAE4A\uAE4C\uAE4D\uAE4E\uAE50\uAE54\uAE56\uAE5C\uAE5D\uAE5F\uAE60\uAE61\uAE65\uAE68\uAE69\uAE6C\uAE70\uAE78"], + ["b241", "\uCF6D\uCF6E\uCF6F\uCF72\uCF73\uCF75\uCF76\uCF77\uCF79", 6, "\uCF81\uCF82\uCF83\uCF84\uCF86", 5, "\uCF8D"], + ["b261", "\uCF8E", 18, "\uCFA2", 5, "\uCFA9"], + ["b281", "\uCFAA", 5, "\uCFB1", 18, "\uCFC5", 6, "\uAE79\uAE7B\uAE7C\uAE7D\uAE84\uAE85\uAE8C\uAEBC\uAEBD\uAEBE\uAEC0\uAEC4\uAECC\uAECD\uAECF\uAED0\uAED1\uAED8\uAED9\uAEDC\uAEE8\uAEEB\uAEED\uAEF4\uAEF8\uAEFC\uAF07\uAF08\uAF0D\uAF10\uAF2C\uAF2D\uAF30\uAF32\uAF34\uAF3C\uAF3D\uAF3F\uAF41\uAF42\uAF43\uAF48\uAF49\uAF50\uAF5C\uAF5D\uAF64\uAF65\uAF79\uAF80\uAF84\uAF88\uAF90\uAF91\uAF95\uAF9C\uAFB8\uAFB9\uAFBC\uAFC0\uAFC7\uAFC8\uAFC9\uAFCB\uAFCD\uAFCE\uAFD4\uAFDC\uAFE8\uAFE9\uAFF0\uAFF1\uAFF4\uAFF8\uB000\uB001\uB004\uB00C\uB010\uB014\uB01C\uB01D\uB028\uB044\uB045\uB048\uB04A\uB04C\uB04E\uB053\uB054\uB055\uB057\uB059"], + ["b341", "\uCFCC", 19, "\uCFE2\uCFE3\uCFE5\uCFE6\uCFE7\uCFE9"], + ["b361", "\uCFEA", 5, "\uCFF2\uCFF4\uCFF6", 5, "\uCFFD\uCFFE\uCFFF\uD001\uD002\uD003\uD005", 5], + ["b381", "\uD00B", 5, "\uD012", 5, "\uD019", 19, "\uB05D\uB07C\uB07D\uB080\uB084\uB08C\uB08D\uB08F\uB091\uB098\uB099\uB09A\uB09C\uB09F\uB0A0\uB0A1\uB0A2\uB0A8\uB0A9\uB0AB", 4, "\uB0B1\uB0B3\uB0B4\uB0B5\uB0B8\uB0BC\uB0C4\uB0C5\uB0C7\uB0C8\uB0C9\uB0D0\uB0D1\uB0D4\uB0D8\uB0E0\uB0E5\uB108\uB109\uB10B\uB10C\uB110\uB112\uB113\uB118\uB119\uB11B\uB11C\uB11D\uB123\uB124\uB125\uB128\uB12C\uB134\uB135\uB137\uB138\uB139\uB140\uB141\uB144\uB148\uB150\uB151\uB154\uB155\uB158\uB15C\uB160\uB178\uB179\uB17C\uB180\uB182\uB188\uB189\uB18B\uB18D\uB192\uB193\uB194\uB198\uB19C\uB1A8\uB1CC\uB1D0\uB1D4\uB1DC\uB1DD"], + ["b441", "\uD02E", 5, "\uD036\uD037\uD039\uD03A\uD03B\uD03D", 6, "\uD046\uD048\uD04A", 5], + ["b461", "\uD051\uD052\uD053\uD055\uD056\uD057\uD059", 6, "\uD061", 10, "\uD06E\uD06F"], + ["b481", "\uD071\uD072\uD073\uD075", 6, "\uD07E\uD07F\uD080\uD082", 18, "\uB1DF\uB1E8\uB1E9\uB1EC\uB1F0\uB1F9\uB1FB\uB1FD\uB204\uB205\uB208\uB20B\uB20C\uB214\uB215\uB217\uB219\uB220\uB234\uB23C\uB258\uB25C\uB260\uB268\uB269\uB274\uB275\uB27C\uB284\uB285\uB289\uB290\uB291\uB294\uB298\uB299\uB29A\uB2A0\uB2A1\uB2A3\uB2A5\uB2A6\uB2AA\uB2AC\uB2B0\uB2B4\uB2C8\uB2C9\uB2CC\uB2D0\uB2D2\uB2D8\uB2D9\uB2DB\uB2DD\uB2E2\uB2E4\uB2E5\uB2E6\uB2E8\uB2EB", 4, "\uB2F3\uB2F4\uB2F5\uB2F7", 4, "\uB2FF\uB300\uB301\uB304\uB308\uB310\uB311\uB313\uB314\uB315\uB31C\uB354\uB355\uB356\uB358\uB35B\uB35C\uB35E\uB35F\uB364\uB365"], + ["b541", "\uD095", 14, "\uD0A6\uD0A7\uD0A9\uD0AA\uD0AB\uD0AD", 5], + ["b561", "\uD0B3\uD0B6\uD0B8\uD0BA", 5, "\uD0C2\uD0C3\uD0C5\uD0C6\uD0C7\uD0CA", 5, "\uD0D2\uD0D6", 4], + ["b581", "\uD0DB\uD0DE\uD0DF\uD0E1\uD0E2\uD0E3\uD0E5", 6, "\uD0EE\uD0F2", 5, "\uD0F9", 11, "\uB367\uB369\uB36B\uB36E\uB370\uB371\uB374\uB378\uB380\uB381\uB383\uB384\uB385\uB38C\uB390\uB394\uB3A0\uB3A1\uB3A8\uB3AC\uB3C4\uB3C5\uB3C8\uB3CB\uB3CC\uB3CE\uB3D0\uB3D4\uB3D5\uB3D7\uB3D9\uB3DB\uB3DD\uB3E0\uB3E4\uB3E8\uB3FC\uB410\uB418\uB41C\uB420\uB428\uB429\uB42B\uB434\uB450\uB451\uB454\uB458\uB460\uB461\uB463\uB465\uB46C\uB480\uB488\uB49D\uB4A4\uB4A8\uB4AC\uB4B5\uB4B7\uB4B9\uB4C0\uB4C4\uB4C8\uB4D0\uB4D5\uB4DC\uB4DD\uB4E0\uB4E3\uB4E4\uB4E6\uB4EC\uB4ED\uB4EF\uB4F1\uB4F8\uB514\uB515\uB518\uB51B\uB51C\uB524\uB525\uB527\uB528\uB529\uB52A\uB530\uB531\uB534\uB538"], + ["b641", "\uD105", 7, "\uD10E", 17], + ["b661", "\uD120", 15, "\uD132\uD133\uD135\uD136\uD137\uD139\uD13B\uD13C\uD13D\uD13E"], + ["b681", "\uD13F\uD142\uD146", 5, "\uD14E\uD14F\uD151\uD152\uD153\uD155", 6, "\uD15E\uD160\uD162", 5, "\uD169\uD16A\uD16B\uD16D\uB540\uB541\uB543\uB544\uB545\uB54B\uB54C\uB54D\uB550\uB554\uB55C\uB55D\uB55F\uB560\uB561\uB5A0\uB5A1\uB5A4\uB5A8\uB5AA\uB5AB\uB5B0\uB5B1\uB5B3\uB5B4\uB5B5\uB5BB\uB5BC\uB5BD\uB5C0\uB5C4\uB5CC\uB5CD\uB5CF\uB5D0\uB5D1\uB5D8\uB5EC\uB610\uB611\uB614\uB618\uB625\uB62C\uB634\uB648\uB664\uB668\uB69C\uB69D\uB6A0\uB6A4\uB6AB\uB6AC\uB6B1\uB6D4\uB6F0\uB6F4\uB6F8\uB700\uB701\uB705\uB728\uB729\uB72C\uB72F\uB730\uB738\uB739\uB73B\uB744\uB748\uB74C\uB754\uB755\uB760\uB764\uB768\uB770\uB771\uB773\uB775\uB77C\uB77D\uB780\uB784\uB78C\uB78D\uB78F\uB790\uB791\uB792\uB796\uB797"], + ["b741", "\uD16E", 13, "\uD17D", 6, "\uD185\uD186\uD187\uD189\uD18A"], + ["b761", "\uD18B", 20, "\uD1A2\uD1A3\uD1A5\uD1A6\uD1A7"], + ["b781", "\uD1A9", 6, "\uD1B2\uD1B4\uD1B6\uD1B7\uD1B8\uD1B9\uD1BB\uD1BD\uD1BE\uD1BF\uD1C1", 14, "\uB798\uB799\uB79C\uB7A0\uB7A8\uB7A9\uB7AB\uB7AC\uB7AD\uB7B4\uB7B5\uB7B8\uB7C7\uB7C9\uB7EC\uB7ED\uB7F0\uB7F4\uB7FC\uB7FD\uB7FF\uB800\uB801\uB807\uB808\uB809\uB80C\uB810\uB818\uB819\uB81B\uB81D\uB824\uB825\uB828\uB82C\uB834\uB835\uB837\uB838\uB839\uB840\uB844\uB851\uB853\uB85C\uB85D\uB860\uB864\uB86C\uB86D\uB86F\uB871\uB878\uB87C\uB88D\uB8A8\uB8B0\uB8B4\uB8B8\uB8C0\uB8C1\uB8C3\uB8C5\uB8CC\uB8D0\uB8D4\uB8DD\uB8DF\uB8E1\uB8E8\uB8E9\uB8EC\uB8F0\uB8F8\uB8F9\uB8FB\uB8FD\uB904\uB918\uB920\uB93C\uB93D\uB940\uB944\uB94C\uB94F\uB951\uB958\uB959\uB95C\uB960\uB968\uB969"], + ["b841", "\uD1D0", 7, "\uD1D9", 17], + ["b861", "\uD1EB", 8, "\uD1F5\uD1F6\uD1F7\uD1F9", 13], + ["b881", "\uD208\uD20A", 5, "\uD211", 24, "\uB96B\uB96D\uB974\uB975\uB978\uB97C\uB984\uB985\uB987\uB989\uB98A\uB98D\uB98E\uB9AC\uB9AD\uB9B0\uB9B4\uB9BC\uB9BD\uB9BF\uB9C1\uB9C8\uB9C9\uB9CC\uB9CE", 4, "\uB9D8\uB9D9\uB9DB\uB9DD\uB9DE\uB9E1\uB9E3\uB9E4\uB9E5\uB9E8\uB9EC\uB9F4\uB9F5\uB9F7\uB9F8\uB9F9\uB9FA\uBA00\uBA01\uBA08\uBA15\uBA38\uBA39\uBA3C\uBA40\uBA42\uBA48\uBA49\uBA4B\uBA4D\uBA4E\uBA53\uBA54\uBA55\uBA58\uBA5C\uBA64\uBA65\uBA67\uBA68\uBA69\uBA70\uBA71\uBA74\uBA78\uBA83\uBA84\uBA85\uBA87\uBA8C\uBAA8\uBAA9\uBAAB\uBAAC\uBAB0\uBAB2\uBAB8\uBAB9\uBABB\uBABD\uBAC4\uBAC8\uBAD8\uBAD9\uBAFC"], + ["b941", "\uD22A\uD22B\uD22E\uD22F\uD231\uD232\uD233\uD235", 6, "\uD23E\uD240\uD242", 5, "\uD249\uD24A\uD24B\uD24C"], + ["b961", "\uD24D", 14, "\uD25D", 6, "\uD265\uD266\uD267\uD268"], + ["b981", "\uD269", 22, "\uD282\uD283\uD285\uD286\uD287\uD289\uD28A\uD28B\uD28C\uBB00\uBB04\uBB0D\uBB0F\uBB11\uBB18\uBB1C\uBB20\uBB29\uBB2B\uBB34\uBB35\uBB36\uBB38\uBB3B\uBB3C\uBB3D\uBB3E\uBB44\uBB45\uBB47\uBB49\uBB4D\uBB4F\uBB50\uBB54\uBB58\uBB61\uBB63\uBB6C\uBB88\uBB8C\uBB90\uBBA4\uBBA8\uBBAC\uBBB4\uBBB7\uBBC0\uBBC4\uBBC8\uBBD0\uBBD3\uBBF8\uBBF9\uBBFC\uBBFF\uBC00\uBC02\uBC08\uBC09\uBC0B\uBC0C\uBC0D\uBC0F\uBC11\uBC14", 4, "\uBC1B", 4, "\uBC24\uBC25\uBC27\uBC29\uBC2D\uBC30\uBC31\uBC34\uBC38\uBC40\uBC41\uBC43\uBC44\uBC45\uBC49\uBC4C\uBC4D\uBC50\uBC5D\uBC84\uBC85\uBC88\uBC8B\uBC8C\uBC8E\uBC94\uBC95\uBC97"], + ["ba41", "\uD28D\uD28E\uD28F\uD292\uD293\uD294\uD296", 5, "\uD29D\uD29E\uD29F\uD2A1\uD2A2\uD2A3\uD2A5", 6, "\uD2AD"], + ["ba61", "\uD2AE\uD2AF\uD2B0\uD2B2", 5, "\uD2BA\uD2BB\uD2BD\uD2BE\uD2C1\uD2C3", 4, "\uD2CA\uD2CC", 5], + ["ba81", "\uD2D2\uD2D3\uD2D5\uD2D6\uD2D7\uD2D9\uD2DA\uD2DB\uD2DD", 6, "\uD2E6", 9, "\uD2F2\uD2F3\uD2F5\uD2F6\uD2F7\uD2F9\uD2FA\uBC99\uBC9A\uBCA0\uBCA1\uBCA4\uBCA7\uBCA8\uBCB0\uBCB1\uBCB3\uBCB4\uBCB5\uBCBC\uBCBD\uBCC0\uBCC4\uBCCD\uBCCF\uBCD0\uBCD1\uBCD5\uBCD8\uBCDC\uBCF4\uBCF5\uBCF6\uBCF8\uBCFC\uBD04\uBD05\uBD07\uBD09\uBD10\uBD14\uBD24\uBD2C\uBD40\uBD48\uBD49\uBD4C\uBD50\uBD58\uBD59\uBD64\uBD68\uBD80\uBD81\uBD84\uBD87\uBD88\uBD89\uBD8A\uBD90\uBD91\uBD93\uBD95\uBD99\uBD9A\uBD9C\uBDA4\uBDB0\uBDB8\uBDD4\uBDD5\uBDD8\uBDDC\uBDE9\uBDF0\uBDF4\uBDF8\uBE00\uBE03\uBE05\uBE0C\uBE0D\uBE10\uBE14\uBE1C\uBE1D\uBE1F\uBE44\uBE45\uBE48\uBE4C\uBE4E\uBE54\uBE55\uBE57\uBE59\uBE5A\uBE5B\uBE60\uBE61\uBE64"], + ["bb41", "\uD2FB", 4, "\uD302\uD304\uD306", 5, "\uD30F\uD311\uD312\uD313\uD315\uD317", 4, "\uD31E\uD322\uD323"], + ["bb61", "\uD324\uD326\uD327\uD32A\uD32B\uD32D\uD32E\uD32F\uD331", 6, "\uD33A\uD33E", 5, "\uD346\uD347\uD348\uD349"], + ["bb81", "\uD34A", 31, "\uBE68\uBE6A\uBE70\uBE71\uBE73\uBE74\uBE75\uBE7B\uBE7C\uBE7D\uBE80\uBE84\uBE8C\uBE8D\uBE8F\uBE90\uBE91\uBE98\uBE99\uBEA8\uBED0\uBED1\uBED4\uBED7\uBED8\uBEE0\uBEE3\uBEE4\uBEE5\uBEEC\uBF01\uBF08\uBF09\uBF18\uBF19\uBF1B\uBF1C\uBF1D\uBF40\uBF41\uBF44\uBF48\uBF50\uBF51\uBF55\uBF94\uBFB0\uBFC5\uBFCC\uBFCD\uBFD0\uBFD4\uBFDC\uBFDF\uBFE1\uC03C\uC051\uC058\uC05C\uC060\uC068\uC069\uC090\uC091\uC094\uC098\uC0A0\uC0A1\uC0A3\uC0A5\uC0AC\uC0AD\uC0AF\uC0B0\uC0B3\uC0B4\uC0B5\uC0B6\uC0BC\uC0BD\uC0BF\uC0C0\uC0C1\uC0C5\uC0C8\uC0C9\uC0CC\uC0D0\uC0D8\uC0D9\uC0DB\uC0DC\uC0DD\uC0E4"], + ["bc41", "\uD36A", 17, "\uD37E\uD37F\uD381\uD382\uD383\uD385\uD386\uD387"], + ["bc61", "\uD388\uD389\uD38A\uD38B\uD38E\uD392", 5, "\uD39A\uD39B\uD39D\uD39E\uD39F\uD3A1", 6, "\uD3AA\uD3AC\uD3AE"], + ["bc81", "\uD3AF", 4, "\uD3B5\uD3B6\uD3B7\uD3B9\uD3BA\uD3BB\uD3BD", 6, "\uD3C6\uD3C7\uD3CA", 5, "\uD3D1", 5, "\uC0E5\uC0E8\uC0EC\uC0F4\uC0F5\uC0F7\uC0F9\uC100\uC104\uC108\uC110\uC115\uC11C", 4, "\uC123\uC124\uC126\uC127\uC12C\uC12D\uC12F\uC130\uC131\uC136\uC138\uC139\uC13C\uC140\uC148\uC149\uC14B\uC14C\uC14D\uC154\uC155\uC158\uC15C\uC164\uC165\uC167\uC168\uC169\uC170\uC174\uC178\uC185\uC18C\uC18D\uC18E\uC190\uC194\uC196\uC19C\uC19D\uC19F\uC1A1\uC1A5\uC1A8\uC1A9\uC1AC\uC1B0\uC1BD\uC1C4\uC1C8\uC1CC\uC1D4\uC1D7\uC1D8\uC1E0\uC1E4\uC1E8\uC1F0\uC1F1\uC1F3\uC1FC\uC1FD\uC200\uC204\uC20C\uC20D\uC20F\uC211\uC218\uC219\uC21C\uC21F\uC220\uC228\uC229\uC22B\uC22D"], + ["bd41", "\uD3D7\uD3D9", 7, "\uD3E2\uD3E4", 7, "\uD3EE\uD3EF\uD3F1\uD3F2\uD3F3\uD3F5\uD3F6\uD3F7"], + ["bd61", "\uD3F8\uD3F9\uD3FA\uD3FB\uD3FE\uD400\uD402", 5, "\uD409", 13], + ["bd81", "\uD417", 5, "\uD41E", 25, "\uC22F\uC231\uC232\uC234\uC248\uC250\uC251\uC254\uC258\uC260\uC265\uC26C\uC26D\uC270\uC274\uC27C\uC27D\uC27F\uC281\uC288\uC289\uC290\uC298\uC29B\uC29D\uC2A4\uC2A5\uC2A8\uC2AC\uC2AD\uC2B4\uC2B5\uC2B7\uC2B9\uC2DC\uC2DD\uC2E0\uC2E3\uC2E4\uC2EB\uC2EC\uC2ED\uC2EF\uC2F1\uC2F6\uC2F8\uC2F9\uC2FB\uC2FC\uC300\uC308\uC309\uC30C\uC30D\uC313\uC314\uC315\uC318\uC31C\uC324\uC325\uC328\uC329\uC345\uC368\uC369\uC36C\uC370\uC372\uC378\uC379\uC37C\uC37D\uC384\uC388\uC38C\uC3C0\uC3D8\uC3D9\uC3DC\uC3DF\uC3E0\uC3E2\uC3E8\uC3E9\uC3ED\uC3F4\uC3F5\uC3F8\uC408\uC410\uC424\uC42C\uC430"], + ["be41", "\uD438", 7, "\uD441\uD442\uD443\uD445", 14], + ["be61", "\uD454", 7, "\uD45D\uD45E\uD45F\uD461\uD462\uD463\uD465", 7, "\uD46E\uD470\uD471\uD472"], + ["be81", "\uD473", 4, "\uD47A\uD47B\uD47D\uD47E\uD481\uD483", 4, "\uD48A\uD48C\uD48E", 5, "\uD495", 8, "\uC434\uC43C\uC43D\uC448\uC464\uC465\uC468\uC46C\uC474\uC475\uC479\uC480\uC494\uC49C\uC4B8\uC4BC\uC4E9\uC4F0\uC4F1\uC4F4\uC4F8\uC4FA\uC4FF\uC500\uC501\uC50C\uC510\uC514\uC51C\uC528\uC529\uC52C\uC530\uC538\uC539\uC53B\uC53D\uC544\uC545\uC548\uC549\uC54A\uC54C\uC54D\uC54E\uC553\uC554\uC555\uC557\uC558\uC559\uC55D\uC55E\uC560\uC561\uC564\uC568\uC570\uC571\uC573\uC574\uC575\uC57C\uC57D\uC580\uC584\uC587\uC58C\uC58D\uC58F\uC591\uC595\uC597\uC598\uC59C\uC5A0\uC5A9\uC5B4\uC5B5\uC5B8\uC5B9\uC5BB\uC5BC\uC5BD\uC5BE\uC5C4", 6, "\uC5CC\uC5CE"], + ["bf41", "\uD49E", 10, "\uD4AA", 14], + ["bf61", "\uD4B9", 18, "\uD4CD\uD4CE\uD4CF\uD4D1\uD4D2\uD4D3\uD4D5"], + ["bf81", "\uD4D6", 5, "\uD4DD\uD4DE\uD4E0", 7, "\uD4E9\uD4EA\uD4EB\uD4ED\uD4EE\uD4EF\uD4F1", 6, "\uD4F9\uD4FA\uD4FC\uC5D0\uC5D1\uC5D4\uC5D8\uC5E0\uC5E1\uC5E3\uC5E5\uC5EC\uC5ED\uC5EE\uC5F0\uC5F4\uC5F6\uC5F7\uC5FC", 5, "\uC605\uC606\uC607\uC608\uC60C\uC610\uC618\uC619\uC61B\uC61C\uC624\uC625\uC628\uC62C\uC62D\uC62E\uC630\uC633\uC634\uC635\uC637\uC639\uC63B\uC640\uC641\uC644\uC648\uC650\uC651\uC653\uC654\uC655\uC65C\uC65D\uC660\uC66C\uC66F\uC671\uC678\uC679\uC67C\uC680\uC688\uC689\uC68B\uC68D\uC694\uC695\uC698\uC69C\uC6A4\uC6A5\uC6A7\uC6A9\uC6B0\uC6B1\uC6B4\uC6B8\uC6B9\uC6BA\uC6C0\uC6C1\uC6C3\uC6C5\uC6CC\uC6CD\uC6D0\uC6D4\uC6DC\uC6DD\uC6E0\uC6E1\uC6E8"], + ["c041", "\uD4FE", 5, "\uD505\uD506\uD507\uD509\uD50A\uD50B\uD50D", 6, "\uD516\uD518", 5], + ["c061", "\uD51E", 25], + ["c081", "\uD538\uD539\uD53A\uD53B\uD53E\uD53F\uD541\uD542\uD543\uD545", 6, "\uD54E\uD550\uD552", 5, "\uD55A\uD55B\uD55D\uD55E\uD55F\uD561\uD562\uD563\uC6E9\uC6EC\uC6F0\uC6F8\uC6F9\uC6FD\uC704\uC705\uC708\uC70C\uC714\uC715\uC717\uC719\uC720\uC721\uC724\uC728\uC730\uC731\uC733\uC735\uC737\uC73C\uC73D\uC740\uC744\uC74A\uC74C\uC74D\uC74F\uC751", 7, "\uC75C\uC760\uC768\uC76B\uC774\uC775\uC778\uC77C\uC77D\uC77E\uC783\uC784\uC785\uC787\uC788\uC789\uC78A\uC78E\uC790\uC791\uC794\uC796\uC797\uC798\uC79A\uC7A0\uC7A1\uC7A3\uC7A4\uC7A5\uC7A6\uC7AC\uC7AD\uC7B0\uC7B4\uC7BC\uC7BD\uC7BF\uC7C0\uC7C1\uC7C8\uC7C9\uC7CC\uC7CE\uC7D0\uC7D8\uC7DD\uC7E4\uC7E8\uC7EC\uC800\uC801\uC804\uC808\uC80A"], + ["c141", "\uD564\uD566\uD567\uD56A\uD56C\uD56E", 5, "\uD576\uD577\uD579\uD57A\uD57B\uD57D", 6, "\uD586\uD58A\uD58B"], + ["c161", "\uD58C\uD58D\uD58E\uD58F\uD591", 19, "\uD5A6\uD5A7"], + ["c181", "\uD5A8", 31, "\uC810\uC811\uC813\uC815\uC816\uC81C\uC81D\uC820\uC824\uC82C\uC82D\uC82F\uC831\uC838\uC83C\uC840\uC848\uC849\uC84C\uC84D\uC854\uC870\uC871\uC874\uC878\uC87A\uC880\uC881\uC883\uC885\uC886\uC887\uC88B\uC88C\uC88D\uC894\uC89D\uC89F\uC8A1\uC8A8\uC8BC\uC8BD\uC8C4\uC8C8\uC8CC\uC8D4\uC8D5\uC8D7\uC8D9\uC8E0\uC8E1\uC8E4\uC8F5\uC8FC\uC8FD\uC900\uC904\uC905\uC906\uC90C\uC90D\uC90F\uC911\uC918\uC92C\uC934\uC950\uC951\uC954\uC958\uC960\uC961\uC963\uC96C\uC970\uC974\uC97C\uC988\uC989\uC98C\uC990\uC998\uC999\uC99B\uC99D\uC9C0\uC9C1\uC9C4\uC9C7\uC9C8\uC9CA\uC9D0\uC9D1\uC9D3"], + ["c241", "\uD5CA\uD5CB\uD5CD\uD5CE\uD5CF\uD5D1\uD5D3", 4, "\uD5DA\uD5DC\uD5DE", 5, "\uD5E6\uD5E7\uD5E9\uD5EA\uD5EB\uD5ED\uD5EE"], + ["c261", "\uD5EF", 4, "\uD5F6\uD5F8\uD5FA", 5, "\uD602\uD603\uD605\uD606\uD607\uD609", 6, "\uD612"], + ["c281", "\uD616", 5, "\uD61D\uD61E\uD61F\uD621\uD622\uD623\uD625", 7, "\uD62E", 9, "\uD63A\uD63B\uC9D5\uC9D6\uC9D9\uC9DA\uC9DC\uC9DD\uC9E0\uC9E2\uC9E4\uC9E7\uC9EC\uC9ED\uC9EF\uC9F0\uC9F1\uC9F8\uC9F9\uC9FC\uCA00\uCA08\uCA09\uCA0B\uCA0C\uCA0D\uCA14\uCA18\uCA29\uCA4C\uCA4D\uCA50\uCA54\uCA5C\uCA5D\uCA5F\uCA60\uCA61\uCA68\uCA7D\uCA84\uCA98\uCABC\uCABD\uCAC0\uCAC4\uCACC\uCACD\uCACF\uCAD1\uCAD3\uCAD8\uCAD9\uCAE0\uCAEC\uCAF4\uCB08\uCB10\uCB14\uCB18\uCB20\uCB21\uCB41\uCB48\uCB49\uCB4C\uCB50\uCB58\uCB59\uCB5D\uCB64\uCB78\uCB79\uCB9C\uCBB8\uCBD4\uCBE4\uCBE7\uCBE9\uCC0C\uCC0D\uCC10\uCC14\uCC1C\uCC1D\uCC21\uCC22\uCC27\uCC28\uCC29\uCC2C\uCC2E\uCC30\uCC38\uCC39\uCC3B"], + ["c341", "\uD63D\uD63E\uD63F\uD641\uD642\uD643\uD644\uD646\uD647\uD64A\uD64C\uD64E\uD64F\uD650\uD652\uD653\uD656\uD657\uD659\uD65A\uD65B\uD65D", 4], + ["c361", "\uD662", 4, "\uD668\uD66A", 5, "\uD672\uD673\uD675", 11], + ["c381", "\uD681\uD682\uD684\uD686", 5, "\uD68E\uD68F\uD691\uD692\uD693\uD695", 7, "\uD69E\uD6A0\uD6A2", 5, "\uD6A9\uD6AA\uCC3C\uCC3D\uCC3E\uCC44\uCC45\uCC48\uCC4C\uCC54\uCC55\uCC57\uCC58\uCC59\uCC60\uCC64\uCC66\uCC68\uCC70\uCC75\uCC98\uCC99\uCC9C\uCCA0\uCCA8\uCCA9\uCCAB\uCCAC\uCCAD\uCCB4\uCCB5\uCCB8\uCCBC\uCCC4\uCCC5\uCCC7\uCCC9\uCCD0\uCCD4\uCCE4\uCCEC\uCCF0\uCD01\uCD08\uCD09\uCD0C\uCD10\uCD18\uCD19\uCD1B\uCD1D\uCD24\uCD28\uCD2C\uCD39\uCD5C\uCD60\uCD64\uCD6C\uCD6D\uCD6F\uCD71\uCD78\uCD88\uCD94\uCD95\uCD98\uCD9C\uCDA4\uCDA5\uCDA7\uCDA9\uCDB0\uCDC4\uCDCC\uCDD0\uCDE8\uCDEC\uCDF0\uCDF8\uCDF9\uCDFB\uCDFD\uCE04\uCE08\uCE0C\uCE14\uCE19\uCE20\uCE21\uCE24\uCE28\uCE30\uCE31\uCE33\uCE35"], + ["c441", "\uD6AB\uD6AD\uD6AE\uD6AF\uD6B1", 7, "\uD6BA\uD6BC", 7, "\uD6C6\uD6C7\uD6C9\uD6CA\uD6CB"], + ["c461", "\uD6CD\uD6CE\uD6CF\uD6D0\uD6D2\uD6D3\uD6D5\uD6D6\uD6D8\uD6DA", 5, "\uD6E1\uD6E2\uD6E3\uD6E5\uD6E6\uD6E7\uD6E9", 4], + ["c481", "\uD6EE\uD6EF\uD6F1\uD6F2\uD6F3\uD6F4\uD6F6", 5, "\uD6FE\uD6FF\uD701\uD702\uD703\uD705", 11, "\uD712\uD713\uD714\uCE58\uCE59\uCE5C\uCE5F\uCE60\uCE61\uCE68\uCE69\uCE6B\uCE6D\uCE74\uCE75\uCE78\uCE7C\uCE84\uCE85\uCE87\uCE89\uCE90\uCE91\uCE94\uCE98\uCEA0\uCEA1\uCEA3\uCEA4\uCEA5\uCEAC\uCEAD\uCEC1\uCEE4\uCEE5\uCEE8\uCEEB\uCEEC\uCEF4\uCEF5\uCEF7\uCEF8\uCEF9\uCF00\uCF01\uCF04\uCF08\uCF10\uCF11\uCF13\uCF15\uCF1C\uCF20\uCF24\uCF2C\uCF2D\uCF2F\uCF30\uCF31\uCF38\uCF54\uCF55\uCF58\uCF5C\uCF64\uCF65\uCF67\uCF69\uCF70\uCF71\uCF74\uCF78\uCF80\uCF85\uCF8C\uCFA1\uCFA8\uCFB0\uCFC4\uCFE0\uCFE1\uCFE4\uCFE8\uCFF0\uCFF1\uCFF3\uCFF5\uCFFC\uD000\uD004\uD011\uD018\uD02D\uD034\uD035\uD038\uD03C"], + ["c541", "\uD715\uD716\uD717\uD71A\uD71B\uD71D\uD71E\uD71F\uD721", 6, "\uD72A\uD72C\uD72E", 5, "\uD736\uD737\uD739"], + ["c561", "\uD73A\uD73B\uD73D", 6, "\uD745\uD746\uD748\uD74A", 5, "\uD752\uD753\uD755\uD75A", 4], + ["c581", "\uD75F\uD762\uD764\uD766\uD767\uD768\uD76A\uD76B\uD76D\uD76E\uD76F\uD771\uD772\uD773\uD775", 6, "\uD77E\uD77F\uD780\uD782", 5, "\uD78A\uD78B\uD044\uD045\uD047\uD049\uD050\uD054\uD058\uD060\uD06C\uD06D\uD070\uD074\uD07C\uD07D\uD081\uD0A4\uD0A5\uD0A8\uD0AC\uD0B4\uD0B5\uD0B7\uD0B9\uD0C0\uD0C1\uD0C4\uD0C8\uD0C9\uD0D0\uD0D1\uD0D3\uD0D4\uD0D5\uD0DC\uD0DD\uD0E0\uD0E4\uD0EC\uD0ED\uD0EF\uD0F0\uD0F1\uD0F8\uD10D\uD130\uD131\uD134\uD138\uD13A\uD140\uD141\uD143\uD144\uD145\uD14C\uD14D\uD150\uD154\uD15C\uD15D\uD15F\uD161\uD168\uD16C\uD17C\uD184\uD188\uD1A0\uD1A1\uD1A4\uD1A8\uD1B0\uD1B1\uD1B3\uD1B5\uD1BA\uD1BC\uD1C0\uD1D8\uD1F4\uD1F8\uD207\uD209\uD210\uD22C\uD22D\uD230\uD234\uD23C\uD23D\uD23F\uD241\uD248\uD25C"], + ["c641", "\uD78D\uD78E\uD78F\uD791", 6, "\uD79A\uD79C\uD79E", 5], + ["c6a1", "\uD264\uD280\uD281\uD284\uD288\uD290\uD291\uD295\uD29C\uD2A0\uD2A4\uD2AC\uD2B1\uD2B8\uD2B9\uD2BC\uD2BF\uD2C0\uD2C2\uD2C8\uD2C9\uD2CB\uD2D4\uD2D8\uD2DC\uD2E4\uD2E5\uD2F0\uD2F1\uD2F4\uD2F8\uD300\uD301\uD303\uD305\uD30C\uD30D\uD30E\uD310\uD314\uD316\uD31C\uD31D\uD31F\uD320\uD321\uD325\uD328\uD329\uD32C\uD330\uD338\uD339\uD33B\uD33C\uD33D\uD344\uD345\uD37C\uD37D\uD380\uD384\uD38C\uD38D\uD38F\uD390\uD391\uD398\uD399\uD39C\uD3A0\uD3A8\uD3A9\uD3AB\uD3AD\uD3B4\uD3B8\uD3BC\uD3C4\uD3C5\uD3C8\uD3C9\uD3D0\uD3D8\uD3E1\uD3E3\uD3EC\uD3ED\uD3F0\uD3F4\uD3FC\uD3FD\uD3FF\uD401"], + ["c7a1", "\uD408\uD41D\uD440\uD444\uD45C\uD460\uD464\uD46D\uD46F\uD478\uD479\uD47C\uD47F\uD480\uD482\uD488\uD489\uD48B\uD48D\uD494\uD4A9\uD4CC\uD4D0\uD4D4\uD4DC\uD4DF\uD4E8\uD4EC\uD4F0\uD4F8\uD4FB\uD4FD\uD504\uD508\uD50C\uD514\uD515\uD517\uD53C\uD53D\uD540\uD544\uD54C\uD54D\uD54F\uD551\uD558\uD559\uD55C\uD560\uD565\uD568\uD569\uD56B\uD56D\uD574\uD575\uD578\uD57C\uD584\uD585\uD587\uD588\uD589\uD590\uD5A5\uD5C8\uD5C9\uD5CC\uD5D0\uD5D2\uD5D8\uD5D9\uD5DB\uD5DD\uD5E4\uD5E5\uD5E8\uD5EC\uD5F4\uD5F5\uD5F7\uD5F9\uD600\uD601\uD604\uD608\uD610\uD611\uD613\uD614\uD615\uD61C\uD620"], + ["c8a1", "\uD624\uD62D\uD638\uD639\uD63C\uD640\uD645\uD648\uD649\uD64B\uD64D\uD651\uD654\uD655\uD658\uD65C\uD667\uD669\uD670\uD671\uD674\uD683\uD685\uD68C\uD68D\uD690\uD694\uD69D\uD69F\uD6A1\uD6A8\uD6AC\uD6B0\uD6B9\uD6BB\uD6C4\uD6C5\uD6C8\uD6CC\uD6D1\uD6D4\uD6D7\uD6D9\uD6E0\uD6E4\uD6E8\uD6F0\uD6F5\uD6FC\uD6FD\uD700\uD704\uD711\uD718\uD719\uD71C\uD720\uD728\uD729\uD72B\uD72D\uD734\uD735\uD738\uD73C\uD744\uD747\uD749\uD750\uD751\uD754\uD756\uD757\uD758\uD759\uD760\uD761\uD763\uD765\uD769\uD76C\uD770\uD774\uD77C\uD77D\uD781\uD788\uD789\uD78C\uD790\uD798\uD799\uD79B\uD79D"], + ["caa1", "\u4F3D\u4F73\u5047\u50F9\u52A0\u53EF\u5475\u54E5\u5609\u5AC1\u5BB6\u6687\u67B6\u67B7\u67EF\u6B4C\u73C2\u75C2\u7A3C\u82DB\u8304\u8857\u8888\u8A36\u8CC8\u8DCF\u8EFB\u8FE6\u99D5\u523B\u5374\u5404\u606A\u6164\u6BBC\u73CF\u811A\u89BA\u89D2\u95A3\u4F83\u520A\u58BE\u5978\u59E6\u5E72\u5E79\u61C7\u63C0\u6746\u67EC\u687F\u6F97\u764E\u770B\u78F5\u7A08\u7AFF\u7C21\u809D\u826E\u8271\u8AEB\u9593\u4E6B\u559D\u66F7\u6E34\u78A3\u7AED\u845B\u8910\u874E\u97A8\u52D8\u574E\u582A\u5D4C\u611F\u61BE\u6221\u6562\u67D1\u6A44\u6E1B\u7518\u75B3\u76E3\u77B0\u7D3A\u90AF\u9451\u9452\u9F95"], + ["cba1", "\u5323\u5CAC\u7532\u80DB\u9240\u9598\u525B\u5808\u59DC\u5CA1\u5D17\u5EB7\u5F3A\u5F4A\u6177\u6C5F\u757A\u7586\u7CE0\u7D73\u7DB1\u7F8C\u8154\u8221\u8591\u8941\u8B1B\u92FC\u964D\u9C47\u4ECB\u4EF7\u500B\u51F1\u584F\u6137\u613E\u6168\u6539\u69EA\u6F11\u75A5\u7686\u76D6\u7B87\u82A5\u84CB\uF900\u93A7\u958B\u5580\u5BA2\u5751\uF901\u7CB3\u7FB9\u91B5\u5028\u53BB\u5C45\u5DE8\u62D2\u636E\u64DA\u64E7\u6E20\u70AC\u795B\u8DDD\u8E1E\uF902\u907D\u9245\u92F8\u4E7E\u4EF6\u5065\u5DFE\u5EFA\u6106\u6957\u8171\u8654\u8E47\u9375\u9A2B\u4E5E\u5091\u6770\u6840\u5109\u528D\u5292\u6AA2"], + ["cca1", "\u77BC\u9210\u9ED4\u52AB\u602F\u8FF2\u5048\u61A9\u63ED\u64CA\u683C\u6A84\u6FC0\u8188\u89A1\u9694\u5805\u727D\u72AC\u7504\u7D79\u7E6D\u80A9\u898B\u8B74\u9063\u9D51\u6289\u6C7A\u6F54\u7D50\u7F3A\u8A23\u517C\u614A\u7B9D\u8B19\u9257\u938C\u4EAC\u4FD3\u501E\u50BE\u5106\u52C1\u52CD\u537F\u5770\u5883\u5E9A\u5F91\u6176\u61AC\u64CE\u656C\u666F\u66BB\u66F4\u6897\u6D87\u7085\u70F1\u749F\u74A5\u74CA\u75D9\u786C\u78EC\u7ADF\u7AF6\u7D45\u7D93\u8015\u803F\u811B\u8396\u8B66\u8F15\u9015\u93E1\u9803\u9838\u9A5A\u9BE8\u4FC2\u5553\u583A\u5951\u5B63\u5C46\u60B8\u6212\u6842\u68B0"], + ["cda1", "\u68E8\u6EAA\u754C\u7678\u78CE\u7A3D\u7CFB\u7E6B\u7E7C\u8A08\u8AA1\u8C3F\u968E\u9DC4\u53E4\u53E9\u544A\u5471\u56FA\u59D1\u5B64\u5C3B\u5EAB\u62F7\u6537\u6545\u6572\u66A0\u67AF\u69C1\u6CBD\u75FC\u7690\u777E\u7A3F\u7F94\u8003\u80A1\u818F\u82E6\u82FD\u83F0\u85C1\u8831\u88B4\u8AA5\uF903\u8F9C\u932E\u96C7\u9867\u9AD8\u9F13\u54ED\u659B\u66F2\u688F\u7A40\u8C37\u9D60\u56F0\u5764\u5D11\u6606\u68B1\u68CD\u6EFE\u7428\u889E\u9BE4\u6C68\uF904\u9AA8\u4F9B\u516C\u5171\u529F\u5B54\u5DE5\u6050\u606D\u62F1\u63A7\u653B\u73D9\u7A7A\u86A3\u8CA2\u978F\u4E32\u5BE1\u6208\u679C\u74DC"], + ["cea1", "\u79D1\u83D3\u8A87\u8AB2\u8DE8\u904E\u934B\u9846\u5ED3\u69E8\u85FF\u90ED\uF905\u51A0\u5B98\u5BEC\u6163\u68FA\u6B3E\u704C\u742F\u74D8\u7BA1\u7F50\u83C5\u89C0\u8CAB\u95DC\u9928\u522E\u605D\u62EC\u9002\u4F8A\u5149\u5321\u58D9\u5EE3\u66E0\u6D38\u709A\u72C2\u73D6\u7B50\u80F1\u945B\u5366\u639B\u7F6B\u4E56\u5080\u584A\u58DE\u602A\u6127\u62D0\u69D0\u9B41\u5B8F\u7D18\u80B1\u8F5F\u4EA4\u50D1\u54AC\u55AC\u5B0C\u5DA0\u5DE7\u652A\u654E\u6821\u6A4B\u72E1\u768E\u77EF\u7D5E\u7FF9\u81A0\u854E\u86DF\u8F03\u8F4E\u90CA\u9903\u9A55\u9BAB\u4E18\u4E45\u4E5D\u4EC7\u4FF1\u5177\u52FE"], + ["cfa1", "\u5340\u53E3\u53E5\u548E\u5614\u5775\u57A2\u5BC7\u5D87\u5ED0\u61FC\u62D8\u6551\u67B8\u67E9\u69CB\u6B50\u6BC6\u6BEC\u6C42\u6E9D\u7078\u72D7\u7396\u7403\u77BF\u77E9\u7A76\u7D7F\u8009\u81FC\u8205\u820A\u82DF\u8862\u8B33\u8CFC\u8EC0\u9011\u90B1\u9264\u92B6\u99D2\u9A45\u9CE9\u9DD7\u9F9C\u570B\u5C40\u83CA\u97A0\u97AB\u9EB4\u541B\u7A98\u7FA4\u88D9\u8ECD\u90E1\u5800\u5C48\u6398\u7A9F\u5BAE\u5F13\u7A79\u7AAE\u828E\u8EAC\u5026\u5238\u52F8\u5377\u5708\u62F3\u6372\u6B0A\u6DC3\u7737\u53A5\u7357\u8568\u8E76\u95D5\u673A\u6AC3\u6F70\u8A6D\u8ECC\u994B\uF906\u6677\u6B78\u8CB4"], + ["d0a1", "\u9B3C\uF907\u53EB\u572D\u594E\u63C6\u69FB\u73EA\u7845\u7ABA\u7AC5\u7CFE\u8475\u898F\u8D73\u9035\u95A8\u52FB\u5747\u7547\u7B60\u83CC\u921E\uF908\u6A58\u514B\u524B\u5287\u621F\u68D8\u6975\u9699\u50C5\u52A4\u52E4\u61C3\u65A4\u6839\u69FF\u747E\u7B4B\u82B9\u83EB\u89B2\u8B39\u8FD1\u9949\uF909\u4ECA\u5997\u64D2\u6611\u6A8E\u7434\u7981\u79BD\u82A9\u887E\u887F\u895F\uF90A\u9326\u4F0B\u53CA\u6025\u6271\u6C72\u7D1A\u7D66\u4E98\u5162\u77DC\u80AF\u4F01\u4F0E\u5176\u5180\u55DC\u5668\u573B\u57FA\u57FC\u5914\u5947\u5993\u5BC4\u5C90\u5D0E\u5DF1\u5E7E\u5FCC\u6280\u65D7\u65E3"], + ["d1a1", "\u671E\u671F\u675E\u68CB\u68C4\u6A5F\u6B3A\u6C23\u6C7D\u6C82\u6DC7\u7398\u7426\u742A\u7482\u74A3\u7578\u757F\u7881\u78EF\u7941\u7947\u7948\u797A\u7B95\u7D00\u7DBA\u7F88\u8006\u802D\u808C\u8A18\u8B4F\u8C48\u8D77\u9321\u9324\u98E2\u9951\u9A0E\u9A0F\u9A65\u9E92\u7DCA\u4F76\u5409\u62EE\u6854\u91D1\u55AB\u513A\uF90B\uF90C\u5A1C\u61E6\uF90D\u62CF\u62FF\uF90E", 5, "\u90A3\uF914", 4, "\u8AFE\uF919\uF91A\uF91B\uF91C\u6696\uF91D\u7156\uF91E\uF91F\u96E3\uF920\u634F\u637A\u5357\uF921\u678F\u6960\u6E73\uF922\u7537\uF923\uF924\uF925"], + ["d2a1", "\u7D0D\uF926\uF927\u8872\u56CA\u5A18\uF928", 4, "\u4E43\uF92D\u5167\u5948\u67F0\u8010\uF92E\u5973\u5E74\u649A\u79CA\u5FF5\u606C\u62C8\u637B\u5BE7\u5BD7\u52AA\uF92F\u5974\u5F29\u6012\uF930\uF931\uF932\u7459\uF933", 5, "\u99D1\uF939", 10, "\u6FC3\uF944\uF945\u81BF\u8FB2\u60F1\uF946\uF947\u8166\uF948\uF949\u5C3F\uF94A", 7, "\u5AE9\u8A25\u677B\u7D10\uF952", 5, "\u80FD\uF958\uF959\u5C3C\u6CE5\u533F\u6EBA\u591A\u8336"], + ["d3a1", "\u4E39\u4EB6\u4F46\u55AE\u5718\u58C7\u5F56\u65B7\u65E6\u6A80\u6BB5\u6E4D\u77ED\u7AEF\u7C1E\u7DDE\u86CB\u8892\u9132\u935B\u64BB\u6FBE\u737A\u75B8\u9054\u5556\u574D\u61BA\u64D4\u66C7\u6DE1\u6E5B\u6F6D\u6FB9\u75F0\u8043\u81BD\u8541\u8983\u8AC7\u8B5A\u931F\u6C93\u7553\u7B54\u8E0F\u905D\u5510\u5802\u5858\u5E62\u6207\u649E\u68E0\u7576\u7CD6\u87B3\u9EE8\u4EE3\u5788\u576E\u5927\u5C0D\u5CB1\u5E36\u5F85\u6234\u64E1\u73B3\u81FA\u888B\u8CB8\u968A\u9EDB\u5B85\u5FB7\u60B3\u5012\u5200\u5230\u5716\u5835\u5857\u5C0E\u5C60\u5CF6\u5D8B\u5EA6\u5F92\u60BC\u6311\u6389\u6417\u6843"], + ["d4a1", "\u68F9\u6AC2\u6DD8\u6E21\u6ED4\u6FE4\u71FE\u76DC\u7779\u79B1\u7A3B\u8404\u89A9\u8CED\u8DF3\u8E48\u9003\u9014\u9053\u90FD\u934D\u9676\u97DC\u6BD2\u7006\u7258\u72A2\u7368\u7763\u79BF\u7BE4\u7E9B\u8B80\u58A9\u60C7\u6566\u65FD\u66BE\u6C8C\u711E\u71C9\u8C5A\u9813\u4E6D\u7A81\u4EDD\u51AC\u51CD\u52D5\u540C\u61A7\u6771\u6850\u68DF\u6D1E\u6F7C\u75BC\u77B3\u7AE5\u80F4\u8463\u9285\u515C\u6597\u675C\u6793\u75D8\u7AC7\u8373\uF95A\u8C46\u9017\u982D\u5C6F\u81C0\u829A\u9041\u906F\u920D\u5F97\u5D9D\u6A59\u71C8\u767B\u7B49\u85E4\u8B04\u9127\u9A30\u5587\u61F6\uF95B\u7669\u7F85"], + ["d5a1", "\u863F\u87BA\u88F8\u908F\uF95C\u6D1B\u70D9\u73DE\u7D61\u843D\uF95D\u916A\u99F1\uF95E\u4E82\u5375\u6B04\u6B12\u703E\u721B\u862D\u9E1E\u524C\u8FA3\u5D50\u64E5\u652C\u6B16\u6FEB\u7C43\u7E9C\u85CD\u8964\u89BD\u62C9\u81D8\u881F\u5ECA\u6717\u6D6A\u72FC\u7405\u746F\u8782\u90DE\u4F86\u5D0D\u5FA0\u840A\u51B7\u63A0\u7565\u4EAE\u5006\u5169\u51C9\u6881\u6A11\u7CAE\u7CB1\u7CE7\u826F\u8AD2\u8F1B\u91CF\u4FB6\u5137\u52F5\u5442\u5EEC\u616E\u623E\u65C5\u6ADA\u6FFE\u792A\u85DC\u8823\u95AD\u9A62\u9A6A\u9E97\u9ECE\u529B\u66C6\u6B77\u701D\u792B\u8F62\u9742\u6190\u6200\u6523\u6F23"], + ["d6a1", "\u7149\u7489\u7DF4\u806F\u84EE\u8F26\u9023\u934A\u51BD\u5217\u52A3\u6D0C\u70C8\u88C2\u5EC9\u6582\u6BAE\u6FC2\u7C3E\u7375\u4EE4\u4F36\u56F9\uF95F\u5CBA\u5DBA\u601C\u73B2\u7B2D\u7F9A\u7FCE\u8046\u901E\u9234\u96F6\u9748\u9818\u9F61\u4F8B\u6FA7\u79AE\u91B4\u96B7\u52DE\uF960\u6488\u64C4\u6AD3\u6F5E\u7018\u7210\u76E7\u8001\u8606\u865C\u8DEF\u8F05\u9732\u9B6F\u9DFA\u9E75\u788C\u797F\u7DA0\u83C9\u9304\u9E7F\u9E93\u8AD6\u58DF\u5F04\u6727\u7027\u74CF\u7C60\u807E\u5121\u7028\u7262\u78CA\u8CC2\u8CDA\u8CF4\u96F7\u4E86\u50DA\u5BEE\u5ED6\u6599\u71CE\u7642\u77AD\u804A\u84FC"], + ["d7a1", "\u907C\u9B27\u9F8D\u58D8\u5A41\u5C62\u6A13\u6DDA\u6F0F\u763B\u7D2F\u7E37\u851E\u8938\u93E4\u964B\u5289\u65D2\u67F3\u69B4\u6D41\u6E9C\u700F\u7409\u7460\u7559\u7624\u786B\u8B2C\u985E\u516D\u622E\u9678\u4F96\u502B\u5D19\u6DEA\u7DB8\u8F2A\u5F8B\u6144\u6817\uF961\u9686\u52D2\u808B\u51DC\u51CC\u695E\u7A1C\u7DBE\u83F1\u9675\u4FDA\u5229\u5398\u540F\u550E\u5C65\u60A7\u674E\u68A8\u6D6C\u7281\u72F8\u7406\u7483\uF962\u75E2\u7C6C\u7F79\u7FB8\u8389\u88CF\u88E1\u91CC\u91D0\u96E2\u9BC9\u541D\u6F7E\u71D0\u7498\u85FA\u8EAA\u96A3\u9C57\u9E9F\u6797\u6DCB\u7433\u81E8\u9716\u782C"], + ["d8a1", "\u7ACB\u7B20\u7C92\u6469\u746A\u75F2\u78BC\u78E8\u99AC\u9B54\u9EBB\u5BDE\u5E55\u6F20\u819C\u83AB\u9088\u4E07\u534D\u5A29\u5DD2\u5F4E\u6162\u633D\u6669\u66FC\u6EFF\u6F2B\u7063\u779E\u842C\u8513\u883B\u8F13\u9945\u9C3B\u551C\u62B9\u672B\u6CAB\u8309\u896A\u977A\u4EA1\u5984\u5FD8\u5FD9\u671B\u7DB2\u7F54\u8292\u832B\u83BD\u8F1E\u9099\u57CB\u59B9\u5A92\u5BD0\u6627\u679A\u6885\u6BCF\u7164\u7F75\u8CB7\u8CE3\u9081\u9B45\u8108\u8C8A\u964C\u9A40\u9EA5\u5B5F\u6C13\u731B\u76F2\u76DF\u840C\u51AA\u8993\u514D\u5195\u52C9\u68C9\u6C94\u7704\u7720\u7DBF\u7DEC\u9762\u9EB5\u6EC5"], + ["d9a1", "\u8511\u51A5\u540D\u547D\u660E\u669D\u6927\u6E9F\u76BF\u7791\u8317\u84C2\u879F\u9169\u9298\u9CF4\u8882\u4FAE\u5192\u52DF\u59C6\u5E3D\u6155\u6478\u6479\u66AE\u67D0\u6A21\u6BCD\u6BDB\u725F\u7261\u7441\u7738\u77DB\u8017\u82BC\u8305\u8B00\u8B28\u8C8C\u6728\u6C90\u7267\u76EE\u7766\u7A46\u9DA9\u6B7F\u6C92\u5922\u6726\u8499\u536F\u5893\u5999\u5EDF\u63CF\u6634\u6773\u6E3A\u732B\u7AD7\u82D7\u9328\u52D9\u5DEB\u61AE\u61CB\u620A\u62C7\u64AB\u65E0\u6959\u6B66\u6BCB\u7121\u73F7\u755D\u7E46\u821E\u8302\u856A\u8AA3\u8CBF\u9727\u9D61\u58A8\u9ED8\u5011\u520E\u543B\u554F\u6587"], + ["daa1", "\u6C76\u7D0A\u7D0B\u805E\u868A\u9580\u96EF\u52FF\u6C95\u7269\u5473\u5A9A\u5C3E\u5D4B\u5F4C\u5FAE\u672A\u68B6\u6963\u6E3C\u6E44\u7709\u7C73\u7F8E\u8587\u8B0E\u8FF7\u9761\u9EF4\u5CB7\u60B6\u610D\u61AB\u654F\u65FB\u65FC\u6C11\u6CEF\u739F\u73C9\u7DE1\u9594\u5BC6\u871C\u8B10\u525D\u535A\u62CD\u640F\u64B2\u6734\u6A38\u6CCA\u73C0\u749E\u7B94\u7C95\u7E1B\u818A\u8236\u8584\u8FEB\u96F9\u99C1\u4F34\u534A\u53CD\u53DB\u62CC\u642C\u6500\u6591\u69C3\u6CEE\u6F58\u73ED\u7554\u7622\u76E4\u76FC\u78D0\u78FB\u792C\u7D46\u822C\u87E0\u8FD4\u9812\u98EF\u52C3\u62D4\u64A5\u6E24\u6F51"], + ["dba1", "\u767C\u8DCB\u91B1\u9262\u9AEE\u9B43\u5023\u508D\u574A\u59A8\u5C28\u5E47\u5F77\u623F\u653E\u65B9\u65C1\u6609\u678B\u699C\u6EC2\u78C5\u7D21\u80AA\u8180\u822B\u82B3\u84A1\u868C\u8A2A\u8B17\u90A6\u9632\u9F90\u500D\u4FF3\uF963\u57F9\u5F98\u62DC\u6392\u676F\u6E43\u7119\u76C3\u80CC\u80DA\u88F4\u88F5\u8919\u8CE0\u8F29\u914D\u966A\u4F2F\u4F70\u5E1B\u67CF\u6822\u767D\u767E\u9B44\u5E61\u6A0A\u7169\u71D4\u756A\uF964\u7E41\u8543\u85E9\u98DC\u4F10\u7B4F\u7F70\u95A5\u51E1\u5E06\u68B5\u6C3E\u6C4E\u6CDB\u72AF\u7BC4\u8303\u6CD5\u743A\u50FB\u5288\u58C1\u64D8\u6A97\u74A7\u7656"], + ["dca1", "\u78A7\u8617\u95E2\u9739\uF965\u535E\u5F01\u8B8A\u8FA8\u8FAF\u908A\u5225\u77A5\u9C49\u9F08\u4E19\u5002\u5175\u5C5B\u5E77\u661E\u663A\u67C4\u68C5\u70B3\u7501\u75C5\u79C9\u7ADD\u8F27\u9920\u9A08\u4FDD\u5821\u5831\u5BF6\u666E\u6B65\u6D11\u6E7A\u6F7D\u73E4\u752B\u83E9\u88DC\u8913\u8B5C\u8F14\u4F0F\u50D5\u5310\u535C\u5B93\u5FA9\u670D\u798F\u8179\u832F\u8514\u8907\u8986\u8F39\u8F3B\u99A5\u9C12\u672C\u4E76\u4FF8\u5949\u5C01\u5CEF\u5CF0\u6367\u68D2\u70FD\u71A2\u742B\u7E2B\u84EC\u8702\u9022\u92D2\u9CF3\u4E0D\u4ED8\u4FEF\u5085\u5256\u526F\u5426\u5490\u57E0\u592B\u5A66"], + ["dda1", "\u5B5A\u5B75\u5BCC\u5E9C\uF966\u6276\u6577\u65A7\u6D6E\u6EA5\u7236\u7B26\u7C3F\u7F36\u8150\u8151\u819A\u8240\u8299\u83A9\u8A03\u8CA0\u8CE6\u8CFB\u8D74\u8DBA\u90E8\u91DC\u961C\u9644\u99D9\u9CE7\u5317\u5206\u5429\u5674\u58B3\u5954\u596E\u5FFF\u61A4\u626E\u6610\u6C7E\u711A\u76C6\u7C89\u7CDE\u7D1B\u82AC\u8CC1\u96F0\uF967\u4F5B\u5F17\u5F7F\u62C2\u5D29\u670B\u68DA\u787C\u7E43\u9D6C\u4E15\u5099\u5315\u532A\u5351\u5983\u5A62\u5E87\u60B2\u618A\u6249\u6279\u6590\u6787\u69A7\u6BD4\u6BD6\u6BD7\u6BD8\u6CB8\uF968\u7435\u75FA\u7812\u7891\u79D5\u79D8\u7C83\u7DCB\u7FE1\u80A5"], + ["dea1", "\u813E\u81C2\u83F2\u871A\u88E8\u8AB9\u8B6C\u8CBB\u9119\u975E\u98DB\u9F3B\u56AC\u5B2A\u5F6C\u658C\u6AB3\u6BAF\u6D5C\u6FF1\u7015\u725D\u73AD\u8CA7\u8CD3\u983B\u6191\u6C37\u8058\u9A01\u4E4D\u4E8B\u4E9B\u4ED5\u4F3A\u4F3C\u4F7F\u4FDF\u50FF\u53F2\u53F8\u5506\u55E3\u56DB\u58EB\u5962\u5A11\u5BEB\u5BFA\u5C04\u5DF3\u5E2B\u5F99\u601D\u6368\u659C\u65AF\u67F6\u67FB\u68AD\u6B7B\u6C99\u6CD7\u6E23\u7009\u7345\u7802\u793E\u7940\u7960\u79C1\u7BE9\u7D17\u7D72\u8086\u820D\u838E\u84D1\u86C7\u88DF\u8A50\u8A5E\u8B1D\u8CDC\u8D66\u8FAD\u90AA\u98FC\u99DF\u9E9D\u524A\uF969\u6714\uF96A"], + ["dfa1", "\u5098\u522A\u5C71\u6563\u6C55\u73CA\u7523\u759D\u7B97\u849C\u9178\u9730\u4E77\u6492\u6BBA\u715E\u85A9\u4E09\uF96B\u6749\u68EE\u6E17\u829F\u8518\u886B\u63F7\u6F81\u9212\u98AF\u4E0A\u50B7\u50CF\u511F\u5546\u55AA\u5617\u5B40\u5C19\u5CE0\u5E38\u5E8A\u5EA0\u5EC2\u60F3\u6851\u6A61\u6E58\u723D\u7240\u72C0\u76F8\u7965\u7BB1\u7FD4\u88F3\u89F4\u8A73\u8C61\u8CDE\u971C\u585E\u74BD\u8CFD\u55C7\uF96C\u7A61\u7D22\u8272\u7272\u751F\u7525\uF96D\u7B19\u5885\u58FB\u5DBC\u5E8F\u5EB6\u5F90\u6055\u6292\u637F\u654D\u6691\u66D9\u66F8\u6816\u68F2\u7280\u745E\u7B6E\u7D6E\u7DD6\u7F72"], + ["e0a1", "\u80E5\u8212\u85AF\u897F\u8A93\u901D\u92E4\u9ECD\u9F20\u5915\u596D\u5E2D\u60DC\u6614\u6673\u6790\u6C50\u6DC5\u6F5F\u77F3\u78A9\u84C6\u91CB\u932B\u4ED9\u50CA\u5148\u5584\u5B0B\u5BA3\u6247\u657E\u65CB\u6E32\u717D\u7401\u7444\u7487\u74BF\u766C\u79AA\u7DDA\u7E55\u7FA8\u817A\u81B3\u8239\u861A\u87EC\u8A75\u8DE3\u9078\u9291\u9425\u994D\u9BAE\u5368\u5C51\u6954\u6CC4\u6D29\u6E2B\u820C\u859B\u893B\u8A2D\u8AAA\u96EA\u9F67\u5261\u66B9\u6BB2\u7E96\u87FE\u8D0D\u9583\u965D\u651D\u6D89\u71EE\uF96E\u57CE\u59D3\u5BAC\u6027\u60FA\u6210\u661F\u665F\u7329\u73F9\u76DB\u7701\u7B6C"], + ["e1a1", "\u8056\u8072\u8165\u8AA0\u9192\u4E16\u52E2\u6B72\u6D17\u7A05\u7B39\u7D30\uF96F\u8CB0\u53EC\u562F\u5851\u5BB5\u5C0F\u5C11\u5DE2\u6240\u6383\u6414\u662D\u68B3\u6CBC\u6D88\u6EAF\u701F\u70A4\u71D2\u7526\u758F\u758E\u7619\u7B11\u7BE0\u7C2B\u7D20\u7D39\u852C\u856D\u8607\u8A34\u900D\u9061\u90B5\u92B7\u97F6\u9A37\u4FD7\u5C6C\u675F\u6D91\u7C9F\u7E8C\u8B16\u8D16\u901F\u5B6B\u5DFD\u640D\u84C0\u905C\u98E1\u7387\u5B8B\u609A\u677E\u6DDE\u8A1F\u8AA6\u9001\u980C\u5237\uF970\u7051\u788E\u9396\u8870\u91D7\u4FEE\u53D7\u55FD\u56DA\u5782\u58FD\u5AC2\u5B88\u5CAB\u5CC0\u5E25\u6101"], + ["e2a1", "\u620D\u624B\u6388\u641C\u6536\u6578\u6A39\u6B8A\u6C34\u6D19\u6F31\u71E7\u72E9\u7378\u7407\u74B2\u7626\u7761\u79C0\u7A57\u7AEA\u7CB9\u7D8F\u7DAC\u7E61\u7F9E\u8129\u8331\u8490\u84DA\u85EA\u8896\u8AB0\u8B90\u8F38\u9042\u9083\u916C\u9296\u92B9\u968B\u96A7\u96A8\u96D6\u9700\u9808\u9996\u9AD3\u9B1A\u53D4\u587E\u5919\u5B70\u5BBF\u6DD1\u6F5A\u719F\u7421\u74B9\u8085\u83FD\u5DE1\u5F87\u5FAA\u6042\u65EC\u6812\u696F\u6A53\u6B89\u6D35\u6DF3\u73E3\u76FE\u77AC\u7B4D\u7D14\u8123\u821C\u8340\u84F4\u8563\u8A62\u8AC4\u9187\u931E\u9806\u99B4\u620C\u8853\u8FF0\u9265\u5D07\u5D27"], + ["e3a1", "\u5D69\u745F\u819D\u8768\u6FD5\u62FE\u7FD2\u8936\u8972\u4E1E\u4E58\u50E7\u52DD\u5347\u627F\u6607\u7E69\u8805\u965E\u4F8D\u5319\u5636\u59CB\u5AA4\u5C38\u5C4E\u5C4D\u5E02\u5F11\u6043\u65BD\u662F\u6642\u67BE\u67F4\u731C\u77E2\u793A\u7FC5\u8494\u84CD\u8996\u8A66\u8A69\u8AE1\u8C55\u8C7A\u57F4\u5BD4\u5F0F\u606F\u62ED\u690D\u6B96\u6E5C\u7184\u7BD2\u8755\u8B58\u8EFE\u98DF\u98FE\u4F38\u4F81\u4FE1\u547B\u5A20\u5BB8\u613C\u65B0\u6668\u71FC\u7533\u795E\u7D33\u814E\u81E3\u8398\u85AA\u85CE\u8703\u8A0A\u8EAB\u8F9B\uF971\u8FC5\u5931\u5BA4\u5BE6\u6089\u5BE9\u5C0B\u5FC3\u6C81"], + ["e4a1", "\uF972\u6DF1\u700B\u751A\u82AF\u8AF6\u4EC0\u5341\uF973\u96D9\u6C0F\u4E9E\u4FC4\u5152\u555E\u5A25\u5CE8\u6211\u7259\u82BD\u83AA\u86FE\u8859\u8A1D\u963F\u96C5\u9913\u9D09\u9D5D\u580A\u5CB3\u5DBD\u5E44\u60E1\u6115\u63E1\u6A02\u6E25\u9102\u9354\u984E\u9C10\u9F77\u5B89\u5CB8\u6309\u664F\u6848\u773C\u96C1\u978D\u9854\u9B9F\u65A1\u8B01\u8ECB\u95BC\u5535\u5CA9\u5DD6\u5EB5\u6697\u764C\u83F4\u95C7\u58D3\u62BC\u72CE\u9D28\u4EF0\u592E\u600F\u663B\u6B83\u79E7\u9D26\u5393\u54C0\u57C3\u5D16\u611B\u66D6\u6DAF\u788D\u827E\u9698\u9744\u5384\u627C\u6396\u6DB2\u7E0A\u814B\u984D"], + ["e5a1", "\u6AFB\u7F4C\u9DAF\u9E1A\u4E5F\u503B\u51B6\u591C\u60F9\u63F6\u6930\u723A\u8036\uF974\u91CE\u5F31\uF975\uF976\u7D04\u82E5\u846F\u84BB\u85E5\u8E8D\uF977\u4F6F\uF978\uF979\u58E4\u5B43\u6059\u63DA\u6518\u656D\u6698\uF97A\u694A\u6A23\u6D0B\u7001\u716C\u75D2\u760D\u79B3\u7A70\uF97B\u7F8A\uF97C\u8944\uF97D\u8B93\u91C0\u967D\uF97E\u990A\u5704\u5FA1\u65BC\u6F01\u7600\u79A6\u8A9E\u99AD\u9B5A\u9F6C\u5104\u61B6\u6291\u6A8D\u81C6\u5043\u5830\u5F66\u7109\u8A00\u8AFA\u5B7C\u8616\u4FFA\u513C\u56B4\u5944\u63A9\u6DF9\u5DAA\u696D\u5186\u4E88\u4F59\uF97F\uF980\uF981\u5982\uF982"], + ["e6a1", "\uF983\u6B5F\u6C5D\uF984\u74B5\u7916\uF985\u8207\u8245\u8339\u8F3F\u8F5D\uF986\u9918\uF987\uF988\uF989\u4EA6\uF98A\u57DF\u5F79\u6613\uF98B\uF98C\u75AB\u7E79\u8B6F\uF98D\u9006\u9A5B\u56A5\u5827\u59F8\u5A1F\u5BB4\uF98E\u5EF6\uF98F\uF990\u6350\u633B\uF991\u693D\u6C87\u6CBF\u6D8E\u6D93\u6DF5\u6F14\uF992\u70DF\u7136\u7159\uF993\u71C3\u71D5\uF994\u784F\u786F\uF995\u7B75\u7DE3\uF996\u7E2F\uF997\u884D\u8EDF\uF998\uF999\uF99A\u925B\uF99B\u9CF6\uF99C\uF99D\uF99E\u6085\u6D85\uF99F\u71B1\uF9A0\uF9A1\u95B1\u53AD\uF9A2\uF9A3\uF9A4\u67D3\uF9A5\u708E\u7130\u7430\u8276\u82D2"], + ["e7a1", "\uF9A6\u95BB\u9AE5\u9E7D\u66C4\uF9A7\u71C1\u8449\uF9A8\uF9A9\u584B\uF9AA\uF9AB\u5DB8\u5F71\uF9AC\u6620\u668E\u6979\u69AE\u6C38\u6CF3\u6E36\u6F41\u6FDA\u701B\u702F\u7150\u71DF\u7370\uF9AD\u745B\uF9AE\u74D4\u76C8\u7A4E\u7E93\uF9AF\uF9B0\u82F1\u8A60\u8FCE\uF9B1\u9348\uF9B2\u9719\uF9B3\uF9B4\u4E42\u502A\uF9B5\u5208\u53E1\u66F3\u6C6D\u6FCA\u730A\u777F\u7A62\u82AE\u85DD\u8602\uF9B6\u88D4\u8A63\u8B7D\u8C6B\uF9B7\u92B3\uF9B8\u9713\u9810\u4E94\u4F0D\u4FC9\u50B2\u5348\u543E\u5433\u55DA\u5862\u58BA\u5967\u5A1B\u5BE4\u609F\uF9B9\u61CA\u6556\u65FF\u6664\u68A7\u6C5A\u6FB3"], + ["e8a1", "\u70CF\u71AC\u7352\u7B7D\u8708\u8AA4\u9C32\u9F07\u5C4B\u6C83\u7344\u7389\u923A\u6EAB\u7465\u761F\u7A69\u7E15\u860A\u5140\u58C5\u64C1\u74EE\u7515\u7670\u7FC1\u9095\u96CD\u9954\u6E26\u74E6\u7AA9\u7AAA\u81E5\u86D9\u8778\u8A1B\u5A49\u5B8C\u5B9B\u68A1\u6900\u6D63\u73A9\u7413\u742C\u7897\u7DE9\u7FEB\u8118\u8155\u839E\u8C4C\u962E\u9811\u66F0\u5F80\u65FA\u6789\u6C6A\u738B\u502D\u5A03\u6B6A\u77EE\u5916\u5D6C\u5DCD\u7325\u754F\uF9BA\uF9BB\u50E5\u51F9\u582F\u592D\u5996\u59DA\u5BE5\uF9BC\uF9BD\u5DA2\u62D7\u6416\u6493\u64FE\uF9BE\u66DC\uF9BF\u6A48\uF9C0\u71FF\u7464\uF9C1"], + ["e9a1", "\u7A88\u7AAF\u7E47\u7E5E\u8000\u8170\uF9C2\u87EF\u8981\u8B20\u9059\uF9C3\u9080\u9952\u617E\u6B32\u6D74\u7E1F\u8925\u8FB1\u4FD1\u50AD\u5197\u52C7\u57C7\u5889\u5BB9\u5EB8\u6142\u6995\u6D8C\u6E67\u6EB6\u7194\u7462\u7528\u752C\u8073\u8338\u84C9\u8E0A\u9394\u93DE\uF9C4\u4E8E\u4F51\u5076\u512A\u53C8\u53CB\u53F3\u5B87\u5BD3\u5C24\u611A\u6182\u65F4\u725B\u7397\u7440\u76C2\u7950\u7991\u79B9\u7D06\u7FBD\u828B\u85D5\u865E\u8FC2\u9047\u90F5\u91EA\u9685\u96E8\u96E9\u52D6\u5F67\u65ED\u6631\u682F\u715C\u7A36\u90C1\u980A\u4E91\uF9C5\u6A52\u6B9E\u6F90\u7189\u8018\u82B8\u8553"], + ["eaa1", "\u904B\u9695\u96F2\u97FB\u851A\u9B31\u4E90\u718A\u96C4\u5143\u539F\u54E1\u5713\u5712\u57A3\u5A9B\u5AC4\u5BC3\u6028\u613F\u63F4\u6C85\u6D39\u6E72\u6E90\u7230\u733F\u7457\u82D1\u8881\u8F45\u9060\uF9C6\u9662\u9858\u9D1B\u6708\u8D8A\u925E\u4F4D\u5049\u50DE\u5371\u570D\u59D4\u5A01\u5C09\u6170\u6690\u6E2D\u7232\u744B\u7DEF\u80C3\u840E\u8466\u853F\u875F\u885B\u8918\u8B02\u9055\u97CB\u9B4F\u4E73\u4F91\u5112\u516A\uF9C7\u552F\u55A9\u5B7A\u5BA5\u5E7C\u5E7D\u5EBE\u60A0\u60DF\u6108\u6109\u63C4\u6538\u6709\uF9C8\u67D4\u67DA\uF9C9\u6961\u6962\u6CB9\u6D27\uF9CA\u6E38\uF9CB"], + ["eba1", "\u6FE1\u7336\u7337\uF9CC\u745C\u7531\uF9CD\u7652\uF9CE\uF9CF\u7DAD\u81FE\u8438\u88D5\u8A98\u8ADB\u8AED\u8E30\u8E42\u904A\u903E\u907A\u9149\u91C9\u936E\uF9D0\uF9D1\u5809\uF9D2\u6BD3\u8089\u80B2\uF9D3\uF9D4\u5141\u596B\u5C39\uF9D5\uF9D6\u6F64\u73A7\u80E4\u8D07\uF9D7\u9217\u958F\uF9D8\uF9D9\uF9DA\uF9DB\u807F\u620E\u701C\u7D68\u878D\uF9DC\u57A0\u6069\u6147\u6BB7\u8ABE\u9280\u96B1\u4E59\u541F\u6DEB\u852D\u9670\u97F3\u98EE\u63D6\u6CE3\u9091\u51DD\u61C9\u81BA\u9DF9\u4F9D\u501A\u5100\u5B9C\u610F\u61FF\u64EC\u6905\u6BC5\u7591\u77E3\u7FA9\u8264\u858F\u87FB\u8863\u8ABC"], + ["eca1", "\u8B70\u91AB\u4E8C\u4EE5\u4F0A\uF9DD\uF9DE\u5937\u59E8\uF9DF\u5DF2\u5F1B\u5F5B\u6021\uF9E0\uF9E1\uF9E2\uF9E3\u723E\u73E5\uF9E4\u7570\u75CD\uF9E5\u79FB\uF9E6\u800C\u8033\u8084\u82E1\u8351\uF9E7\uF9E8\u8CBD\u8CB3\u9087\uF9E9\uF9EA\u98F4\u990C\uF9EB\uF9EC\u7037\u76CA\u7FCA\u7FCC\u7FFC\u8B1A\u4EBA\u4EC1\u5203\u5370\uF9ED\u54BD\u56E0\u59FB\u5BC5\u5F15\u5FCD\u6E6E\uF9EE\uF9EF\u7D6A\u8335\uF9F0\u8693\u8A8D\uF9F1\u976D\u9777\uF9F2\uF9F3\u4E00\u4F5A\u4F7E\u58F9\u65E5\u6EA2\u9038\u93B0\u99B9\u4EFB\u58EC\u598A\u59D9\u6041\uF9F4\uF9F5\u7A14\uF9F6\u834F\u8CC3\u5165\u5344"], + ["eda1", "\uF9F7\uF9F8\uF9F9\u4ECD\u5269\u5B55\u82BF\u4ED4\u523A\u54A8\u59C9\u59FF\u5B50\u5B57\u5B5C\u6063\u6148\u6ECB\u7099\u716E\u7386\u74F7\u75B5\u78C1\u7D2B\u8005\u81EA\u8328\u8517\u85C9\u8AEE\u8CC7\u96CC\u4F5C\u52FA\u56BC\u65AB\u6628\u707C\u70B8\u7235\u7DBD\u828D\u914C\u96C0\u9D72\u5B71\u68E7\u6B98\u6F7A\u76DE\u5C91\u66AB\u6F5B\u7BB4\u7C2A\u8836\u96DC\u4E08\u4ED7\u5320\u5834\u58BB\u58EF\u596C\u5C07\u5E33\u5E84\u5F35\u638C\u66B2\u6756\u6A1F\u6AA3\u6B0C\u6F3F\u7246\uF9FA\u7350\u748B\u7AE0\u7CA7\u8178\u81DF\u81E7\u838A\u846C\u8523\u8594\u85CF\u88DD\u8D13\u91AC\u9577"], + ["eea1", "\u969C\u518D\u54C9\u5728\u5BB0\u624D\u6750\u683D\u6893\u6E3D\u6ED3\u707D\u7E21\u88C1\u8CA1\u8F09\u9F4B\u9F4E\u722D\u7B8F\u8ACD\u931A\u4F47\u4F4E\u5132\u5480\u59D0\u5E95\u62B5\u6775\u696E\u6A17\u6CAE\u6E1A\u72D9\u732A\u75BD\u7BB8\u7D35\u82E7\u83F9\u8457\u85F7\u8A5B\u8CAF\u8E87\u9019\u90B8\u96CE\u9F5F\u52E3\u540A\u5AE1\u5BC2\u6458\u6575\u6EF4\u72C4\uF9FB\u7684\u7A4D\u7B1B\u7C4D\u7E3E\u7FDF\u837B\u8B2B\u8CCA\u8D64\u8DE1\u8E5F\u8FEA\u8FF9\u9069\u93D1\u4F43\u4F7A\u50B3\u5168\u5178\u524D\u526A\u5861\u587C\u5960\u5C08\u5C55\u5EDB\u609B\u6230\u6813\u6BBF\u6C08\u6FB1"], + ["efa1", "\u714E\u7420\u7530\u7538\u7551\u7672\u7B4C\u7B8B\u7BAD\u7BC6\u7E8F\u8A6E\u8F3E\u8F49\u923F\u9293\u9322\u942B\u96FB\u985A\u986B\u991E\u5207\u622A\u6298\u6D59\u7664\u7ACA\u7BC0\u7D76\u5360\u5CBE\u5E97\u6F38\u70B9\u7C98\u9711\u9B8E\u9EDE\u63A5\u647A\u8776\u4E01\u4E95\u4EAD\u505C\u5075\u5448\u59C3\u5B9A\u5E40\u5EAD\u5EF7\u5F81\u60C5\u633A\u653F\u6574\u65CC\u6676\u6678\u67FE\u6968\u6A89\u6B63\u6C40\u6DC0\u6DE8\u6E1F\u6E5E\u701E\u70A1\u738E\u73FD\u753A\u775B\u7887\u798E\u7A0B\u7A7D\u7CBE\u7D8E\u8247\u8A02\u8AEA\u8C9E\u912D\u914A\u91D8\u9266\u92CC\u9320\u9706\u9756"], + ["f0a1", "\u975C\u9802\u9F0E\u5236\u5291\u557C\u5824\u5E1D\u5F1F\u608C\u63D0\u68AF\u6FDF\u796D\u7B2C\u81CD\u85BA\u88FD\u8AF8\u8E44\u918D\u9664\u969B\u973D\u984C\u9F4A\u4FCE\u5146\u51CB\u52A9\u5632\u5F14\u5F6B\u63AA\u64CD\u65E9\u6641\u66FA\u66F9\u671D\u689D\u68D7\u69FD\u6F15\u6F6E\u7167\u71E5\u722A\u74AA\u773A\u7956\u795A\u79DF\u7A20\u7A95\u7C97\u7CDF\u7D44\u7E70\u8087\u85FB\u86A4\u8A54\u8ABF\u8D99\u8E81\u9020\u906D\u91E3\u963B\u96D5\u9CE5\u65CF\u7C07\u8DB3\u93C3\u5B58\u5C0A\u5352\u62D9\u731D\u5027\u5B97\u5F9E\u60B0\u616B\u68D5\u6DD9\u742E\u7A2E\u7D42\u7D9C\u7E31\u816B"], + ["f1a1", "\u8E2A\u8E35\u937E\u9418\u4F50\u5750\u5DE6\u5EA7\u632B\u7F6A\u4E3B\u4F4F\u4F8F\u505A\u59DD\u80C4\u546A\u5468\u55FE\u594F\u5B99\u5DDE\u5EDA\u665D\u6731\u67F1\u682A\u6CE8\u6D32\u6E4A\u6F8D\u70B7\u73E0\u7587\u7C4C\u7D02\u7D2C\u7DA2\u821F\u86DB\u8A3B\u8A85\u8D70\u8E8A\u8F33\u9031\u914E\u9152\u9444\u99D0\u7AF9\u7CA5\u4FCA\u5101\u51C6\u57C8\u5BEF\u5CFB\u6659\u6A3D\u6D5A\u6E96\u6FEC\u710C\u756F\u7AE3\u8822\u9021\u9075\u96CB\u99FF\u8301\u4E2D\u4EF2\u8846\u91CD\u537D\u6ADB\u696B\u6C41\u847A\u589E\u618E\u66FE\u62EF\u70DD\u7511\u75C7\u7E52\u84B8\u8B49\u8D08\u4E4B\u53EA"], + ["f2a1", "\u54AB\u5730\u5740\u5FD7\u6301\u6307\u646F\u652F\u65E8\u667A\u679D\u67B3\u6B62\u6C60\u6C9A\u6F2C\u77E5\u7825\u7949\u7957\u7D19\u80A2\u8102\u81F3\u829D\u82B7\u8718\u8A8C\uF9FC\u8D04\u8DBE\u9072\u76F4\u7A19\u7A37\u7E54\u8077\u5507\u55D4\u5875\u632F\u6422\u6649\u664B\u686D\u699B\u6B84\u6D25\u6EB1\u73CD\u7468\u74A1\u755B\u75B9\u76E1\u771E\u778B\u79E6\u7E09\u7E1D\u81FB\u852F\u8897\u8A3A\u8CD1\u8EEB\u8FB0\u9032\u93AD\u9663\u9673\u9707\u4F84\u53F1\u59EA\u5AC9\u5E19\u684E\u74C6\u75BE\u79E9\u7A92\u81A3\u86ED\u8CEA\u8DCC\u8FED\u659F\u6715\uF9FD\u57F7\u6F57\u7DDD\u8F2F"], + ["f3a1", "\u93F6\u96C6\u5FB5\u61F2\u6F84\u4E14\u4F98\u501F\u53C9\u55DF\u5D6F\u5DEE\u6B21\u6B64\u78CB\u7B9A\uF9FE\u8E49\u8ECA\u906E\u6349\u643E\u7740\u7A84\u932F\u947F\u9F6A\u64B0\u6FAF\u71E6\u74A8\u74DA\u7AC4\u7C12\u7E82\u7CB2\u7E98\u8B9A\u8D0A\u947D\u9910\u994C\u5239\u5BDF\u64E6\u672D\u7D2E\u50ED\u53C3\u5879\u6158\u6159\u61FA\u65AC\u7AD9\u8B92\u8B96\u5009\u5021\u5275\u5531\u5A3C\u5EE0\u5F70\u6134\u655E\u660C\u6636\u66A2\u69CD\u6EC4\u6F32\u7316\u7621\u7A93\u8139\u8259\u83D6\u84BC\u50B5\u57F0\u5BC0\u5BE8\u5F69\u63A1\u7826\u7DB5\u83DC\u8521\u91C7\u91F5\u518A\u67F5\u7B56"], + ["f4a1", "\u8CAC\u51C4\u59BB\u60BD\u8655\u501C\uF9FF\u5254\u5C3A\u617D\u621A\u62D3\u64F2\u65A5\u6ECC\u7620\u810A\u8E60\u965F\u96BB\u4EDF\u5343\u5598\u5929\u5DDD\u64C5\u6CC9\u6DFA\u7394\u7A7F\u821B\u85A6\u8CE4\u8E10\u9077\u91E7\u95E1\u9621\u97C6\u51F8\u54F2\u5586\u5FB9\u64A4\u6F88\u7DB4\u8F1F\u8F4D\u9435\u50C9\u5C16\u6CBE\u6DFB\u751B\u77BB\u7C3D\u7C64\u8A79\u8AC2\u581E\u59BE\u5E16\u6377\u7252\u758A\u776B\u8ADC\u8CBC\u8F12\u5EF3\u6674\u6DF8\u807D\u83C1\u8ACB\u9751\u9BD6\uFA00\u5243\u66FF\u6D95\u6EEF\u7DE0\u8AE6\u902E\u905E\u9AD4\u521D\u527F\u54E8\u6194\u6284\u62DB\u68A2"], + ["f5a1", "\u6912\u695A\u6A35\u7092\u7126\u785D\u7901\u790E\u79D2\u7A0D\u8096\u8278\u82D5\u8349\u8549\u8C82\u8D85\u9162\u918B\u91AE\u4FC3\u56D1\u71ED\u77D7\u8700\u89F8\u5BF8\u5FD6\u6751\u90A8\u53E2\u585A\u5BF5\u60A4\u6181\u6460\u7E3D\u8070\u8525\u9283\u64AE\u50AC\u5D14\u6700\u589C\u62BD\u63A8\u690E\u6978\u6A1E\u6E6B\u76BA\u79CB\u82BB\u8429\u8ACF\u8DA8\u8FFD\u9112\u914B\u919C\u9310\u9318\u939A\u96DB\u9A36\u9C0D\u4E11\u755C\u795D\u7AFA\u7B51\u7BC9\u7E2E\u84C4\u8E59\u8E74\u8EF8\u9010\u6625\u693F\u7443\u51FA\u672E\u9EDC\u5145\u5FE0\u6C96\u87F2\u885D\u8877\u60B4\u81B5\u8403"], + ["f6a1", "\u8D05\u53D6\u5439\u5634\u5A36\u5C31\u708A\u7FE0\u805A\u8106\u81ED\u8DA3\u9189\u9A5F\u9DF2\u5074\u4EC4\u53A0\u60FB\u6E2C\u5C64\u4F88\u5024\u55E4\u5CD9\u5E5F\u6065\u6894\u6CBB\u6DC4\u71BE\u75D4\u75F4\u7661\u7A1A\u7A49\u7DC7\u7DFB\u7F6E\u81F4\u86A9\u8F1C\u96C9\u99B3\u9F52\u5247\u52C5\u98ED\u89AA\u4E03\u67D2\u6F06\u4FB5\u5BE2\u6795\u6C88\u6D78\u741B\u7827\u91DD\u937C\u87C4\u79E4\u7A31\u5FEB\u4ED6\u54A4\u553E\u58AE\u59A5\u60F0\u6253\u62D6\u6736\u6955\u8235\u9640\u99B1\u99DD\u502C\u5353\u5544\u577C\uFA01\u6258\uFA02\u64E2\u666B\u67DD\u6FC1\u6FEF\u7422\u7438\u8A17"], + ["f7a1", "\u9438\u5451\u5606\u5766\u5F48\u619A\u6B4E\u7058\u70AD\u7DBB\u8A95\u596A\u812B\u63A2\u7708\u803D\u8CAA\u5854\u642D\u69BB\u5B95\u5E11\u6E6F\uFA03\u8569\u514C\u53F0\u592A\u6020\u614B\u6B86\u6C70\u6CF0\u7B1E\u80CE\u82D4\u8DC6\u90B0\u98B1\uFA04\u64C7\u6FA4\u6491\u6504\u514E\u5410\u571F\u8A0E\u615F\u6876\uFA05\u75DB\u7B52\u7D71\u901A\u5806\u69CC\u817F\u892A\u9000\u9839\u5078\u5957\u59AC\u6295\u900F\u9B2A\u615D\u7279\u95D6\u5761\u5A46\u5DF4\u628A\u64AD\u64FA\u6777\u6CE2\u6D3E\u722C\u7436\u7834\u7F77\u82AD\u8DDB\u9817\u5224\u5742\u677F\u7248\u74E3\u8CA9\u8FA6\u9211"], + ["f8a1", "\u962A\u516B\u53ED\u634C\u4F69\u5504\u6096\u6557\u6C9B\u6D7F\u724C\u72FD\u7A17\u8987\u8C9D\u5F6D\u6F8E\u70F9\u81A8\u610E\u4FBF\u504F\u6241\u7247\u7BC7\u7DE8\u7FE9\u904D\u97AD\u9A19\u8CB6\u576A\u5E73\u67B0\u840D\u8A55\u5420\u5B16\u5E63\u5EE2\u5F0A\u6583\u80BA\u853D\u9589\u965B\u4F48\u5305\u530D\u530F\u5486\u54FA\u5703\u5E03\u6016\u629B\u62B1\u6355\uFA06\u6CE1\u6D66\u75B1\u7832\u80DE\u812F\u82DE\u8461\u84B2\u888D\u8912\u900B\u92EA\u98FD\u9B91\u5E45\u66B4\u66DD\u7011\u7206\uFA07\u4FF5\u527D\u5F6A\u6153\u6753\u6A19\u6F02\u74E2\u7968\u8868\u8C79\u98C7\u98C4\u9A43"], + ["f9a1", "\u54C1\u7A1F\u6953\u8AF7\u8C4A\u98A8\u99AE\u5F7C\u62AB\u75B2\u76AE\u88AB\u907F\u9642\u5339\u5F3C\u5FC5\u6CCC\u73CC\u7562\u758B\u7B46\u82FE\u999D\u4E4F\u903C\u4E0B\u4F55\u53A6\u590F\u5EC8\u6630\u6CB3\u7455\u8377\u8766\u8CC0\u9050\u971E\u9C15\u58D1\u5B78\u8650\u8B14\u9DB4\u5BD2\u6068\u608D\u65F1\u6C57\u6F22\u6FA3\u701A\u7F55\u7FF0\u9591\u9592\u9650\u97D3\u5272\u8F44\u51FD\u542B\u54B8\u5563\u558A\u6ABB\u6DB5\u7DD8\u8266\u929C\u9677\u9E79\u5408\u54C8\u76D2\u86E4\u95A4\u95D4\u965C\u4EA2\u4F09\u59EE\u5AE6\u5DF7\u6052\u6297\u676D\u6841\u6C86\u6E2F\u7F38\u809B\u822A"], + ["faa1", "\uFA08\uFA09\u9805\u4EA5\u5055\u54B3\u5793\u595A\u5B69\u5BB3\u61C8\u6977\u6D77\u7023\u87F9\u89E3\u8A72\u8AE7\u9082\u99ED\u9AB8\u52BE\u6838\u5016\u5E78\u674F\u8347\u884C\u4EAB\u5411\u56AE\u73E6\u9115\u97FF\u9909\u9957\u9999\u5653\u589F\u865B\u8A31\u61B2\u6AF6\u737B\u8ED2\u6B47\u96AA\u9A57\u5955\u7200\u8D6B\u9769\u4FD4\u5CF4\u5F26\u61F8\u665B\u6CEB\u70AB\u7384\u73B9\u73FE\u7729\u774D\u7D43\u7D62\u7E23\u8237\u8852\uFA0A\u8CE2\u9249\u986F\u5B51\u7A74\u8840\u9801\u5ACC\u4FE0\u5354\u593E\u5CFD\u633E\u6D79\u72F9\u8105\u8107\u83A2\u92CF\u9830\u4EA8\u5144\u5211\u578B"], + ["fba1", "\u5F62\u6CC2\u6ECE\u7005\u7050\u70AF\u7192\u73E9\u7469\u834A\u87A2\u8861\u9008\u90A2\u93A3\u99A8\u516E\u5F57\u60E0\u6167\u66B3\u8559\u8E4A\u91AF\u978B\u4E4E\u4E92\u547C\u58D5\u58FA\u597D\u5CB5\u5F27\u6236\u6248\u660A\u6667\u6BEB\u6D69\u6DCF\u6E56\u6EF8\u6F94\u6FE0\u6FE9\u705D\u72D0\u7425\u745A\u74E0\u7693\u795C\u7CCA\u7E1E\u80E1\u82A6\u846B\u84BF\u864E\u865F\u8774\u8B77\u8C6A\u93AC\u9800\u9865\u60D1\u6216\u9177\u5A5A\u660F\u6DF7\u6E3E\u743F\u9B42\u5FFD\u60DA\u7B0F\u54C4\u5F18\u6C5E\u6CD3\u6D2A\u70D8\u7D05\u8679\u8A0C\u9D3B\u5316\u548C\u5B05\u6A3A\u706B\u7575"], + ["fca1", "\u798D\u79BE\u82B1\u83EF\u8A71\u8B41\u8CA8\u9774\uFA0B\u64F4\u652B\u78BA\u78BB\u7A6B\u4E38\u559A\u5950\u5BA6\u5E7B\u60A3\u63DB\u6B61\u6665\u6853\u6E19\u7165\u74B0\u7D08\u9084\u9A69\u9C25\u6D3B\u6ED1\u733E\u8C41\u95CA\u51F0\u5E4C\u5FA8\u604D\u60F6\u6130\u614C\u6643\u6644\u69A5\u6CC1\u6E5F\u6EC9\u6F62\u714C\u749C\u7687\u7BC1\u7C27\u8352\u8757\u9051\u968D\u9EC3\u532F\u56DE\u5EFB\u5F8A\u6062\u6094\u61F7\u6666\u6703\u6A9C\u6DEE\u6FAE\u7070\u736A\u7E6A\u81BE\u8334\u86D4\u8AA8\u8CC4\u5283\u7372\u5B96\u6A6B\u9404\u54EE\u5686\u5B5D\u6548\u6585\u66C9\u689F\u6D8D\u6DC6"], + ["fda1", "\u723B\u80B4\u9175\u9A4D\u4FAF\u5019\u539A\u540E\u543C\u5589\u55C5\u5E3F\u5F8C\u673D\u7166\u73DD\u9005\u52DB\u52F3\u5864\u58CE\u7104\u718F\u71FB\u85B0\u8A13\u6688\u85A8\u55A7\u6684\u714A\u8431\u5349\u5599\u6BC1\u5F59\u5FBD\u63EE\u6689\u7147\u8AF1\u8F1D\u9EBE\u4F11\u643A\u70CB\u7566\u8667\u6064\u8B4E\u9DF8\u5147\u51F6\u5308\u6D36\u80F8\u9ED1\u6615\u6B23\u7098\u75D5\u5403\u5C79\u7D07\u8A16\u6B20\u6B3D\u6B46\u5438\u6070\u6D3D\u7FD5\u8208\u50D6\u51DE\u559C\u566B\u56CD\u59EC\u5B09\u5E0C\u6199\u6198\u6231\u665E\u66E6\u7199\u71B9\u71BA\u72A7\u79A7\u7A00\u7FB2\u8A70"] + ]; + } +}); + +// node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/encodings/tables/cp950.json +var require_cp950 = __commonJS({ + "node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/encodings/tables/cp950.json"(exports, module) { + module.exports = [ + ["0", "\0", 127], + ["a140", "\u3000\uFF0C\u3001\u3002\uFF0E\u2027\uFF1B\uFF1A\uFF1F\uFF01\uFE30\u2026\u2025\uFE50\uFE51\uFE52\xB7\uFE54\uFE55\uFE56\uFE57\uFF5C\u2013\uFE31\u2014\uFE33\u2574\uFE34\uFE4F\uFF08\uFF09\uFE35\uFE36\uFF5B\uFF5D\uFE37\uFE38\u3014\u3015\uFE39\uFE3A\u3010\u3011\uFE3B\uFE3C\u300A\u300B\uFE3D\uFE3E\u3008\u3009\uFE3F\uFE40\u300C\u300D\uFE41\uFE42\u300E\u300F\uFE43\uFE44\uFE59\uFE5A"], + ["a1a1", "\uFE5B\uFE5C\uFE5D\uFE5E\u2018\u2019\u201C\u201D\u301D\u301E\u2035\u2032\uFF03\uFF06\uFF0A\u203B\xA7\u3003\u25CB\u25CF\u25B3\u25B2\u25CE\u2606\u2605\u25C7\u25C6\u25A1\u25A0\u25BD\u25BC\u32A3\u2105\xAF\uFFE3\uFF3F\u02CD\uFE49\uFE4A\uFE4D\uFE4E\uFE4B\uFE4C\uFE5F\uFE60\uFE61\uFF0B\uFF0D\xD7\xF7\xB1\u221A\uFF1C\uFF1E\uFF1D\u2266\u2267\u2260\u221E\u2252\u2261\uFE62", 4, "\uFF5E\u2229\u222A\u22A5\u2220\u221F\u22BF\u33D2\u33D1\u222B\u222E\u2235\u2234\u2640\u2642\u2295\u2299\u2191\u2193\u2190\u2192\u2196\u2197\u2199\u2198\u2225\u2223\uFF0F"], + ["a240", "\uFF3C\u2215\uFE68\uFF04\uFFE5\u3012\uFFE0\uFFE1\uFF05\uFF20\u2103\u2109\uFE69\uFE6A\uFE6B\u33D5\u339C\u339D\u339E\u33CE\u33A1\u338E\u338F\u33C4\xB0\u5159\u515B\u515E\u515D\u5161\u5163\u55E7\u74E9\u7CCE\u2581", 7, "\u258F\u258E\u258D\u258C\u258B\u258A\u2589\u253C\u2534\u252C\u2524\u251C\u2594\u2500\u2502\u2595\u250C\u2510\u2514\u2518\u256D"], + ["a2a1", "\u256E\u2570\u256F\u2550\u255E\u256A\u2561\u25E2\u25E3\u25E5\u25E4\u2571\u2572\u2573\uFF10", 9, "\u2160", 9, "\u3021", 8, "\u5341\u5344\u5345\uFF21", 25, "\uFF41", 21], + ["a340", "\uFF57\uFF58\uFF59\uFF5A\u0391", 16, "\u03A3", 6, "\u03B1", 16, "\u03C3", 6, "\u3105", 10], + ["a3a1", "\u3110", 25, "\u02D9\u02C9\u02CA\u02C7\u02CB"], + ["a3e1", "\u20AC"], + ["a440", "\u4E00\u4E59\u4E01\u4E03\u4E43\u4E5D\u4E86\u4E8C\u4EBA\u513F\u5165\u516B\u51E0\u5200\u5201\u529B\u5315\u5341\u535C\u53C8\u4E09\u4E0B\u4E08\u4E0A\u4E2B\u4E38\u51E1\u4E45\u4E48\u4E5F\u4E5E\u4E8E\u4EA1\u5140\u5203\u52FA\u5343\u53C9\u53E3\u571F\u58EB\u5915\u5927\u5973\u5B50\u5B51\u5B53\u5BF8\u5C0F\u5C22\u5C38\u5C71\u5DDD\u5DE5\u5DF1\u5DF2\u5DF3\u5DFE\u5E72\u5EFE\u5F0B\u5F13\u624D"], + ["a4a1", "\u4E11\u4E10\u4E0D\u4E2D\u4E30\u4E39\u4E4B\u5C39\u4E88\u4E91\u4E95\u4E92\u4E94\u4EA2\u4EC1\u4EC0\u4EC3\u4EC6\u4EC7\u4ECD\u4ECA\u4ECB\u4EC4\u5143\u5141\u5167\u516D\u516E\u516C\u5197\u51F6\u5206\u5207\u5208\u52FB\u52FE\u52FF\u5316\u5339\u5348\u5347\u5345\u535E\u5384\u53CB\u53CA\u53CD\u58EC\u5929\u592B\u592A\u592D\u5B54\u5C11\u5C24\u5C3A\u5C6F\u5DF4\u5E7B\u5EFF\u5F14\u5F15\u5FC3\u6208\u6236\u624B\u624E\u652F\u6587\u6597\u65A4\u65B9\u65E5\u66F0\u6708\u6728\u6B20\u6B62\u6B79\u6BCB\u6BD4\u6BDB\u6C0F\u6C34\u706B\u722A\u7236\u723B\u7247\u7259\u725B\u72AC\u738B\u4E19"], + ["a540", "\u4E16\u4E15\u4E14\u4E18\u4E3B\u4E4D\u4E4F\u4E4E\u4EE5\u4ED8\u4ED4\u4ED5\u4ED6\u4ED7\u4EE3\u4EE4\u4ED9\u4EDE\u5145\u5144\u5189\u518A\u51AC\u51F9\u51FA\u51F8\u520A\u52A0\u529F\u5305\u5306\u5317\u531D\u4EDF\u534A\u5349\u5361\u5360\u536F\u536E\u53BB\u53EF\u53E4\u53F3\u53EC\u53EE\u53E9\u53E8\u53FC\u53F8\u53F5\u53EB\u53E6\u53EA\u53F2\u53F1\u53F0\u53E5\u53ED\u53FB\u56DB\u56DA\u5916"], + ["a5a1", "\u592E\u5931\u5974\u5976\u5B55\u5B83\u5C3C\u5DE8\u5DE7\u5DE6\u5E02\u5E03\u5E73\u5E7C\u5F01\u5F18\u5F17\u5FC5\u620A\u6253\u6254\u6252\u6251\u65A5\u65E6\u672E\u672C\u672A\u672B\u672D\u6B63\u6BCD\u6C11\u6C10\u6C38\u6C41\u6C40\u6C3E\u72AF\u7384\u7389\u74DC\u74E6\u7518\u751F\u7528\u7529\u7530\u7531\u7532\u7533\u758B\u767D\u76AE\u76BF\u76EE\u77DB\u77E2\u77F3\u793A\u79BE\u7A74\u7ACB\u4E1E\u4E1F\u4E52\u4E53\u4E69\u4E99\u4EA4\u4EA6\u4EA5\u4EFF\u4F09\u4F19\u4F0A\u4F15\u4F0D\u4F10\u4F11\u4F0F\u4EF2\u4EF6\u4EFB\u4EF0\u4EF3\u4EFD\u4F01\u4F0B\u5149\u5147\u5146\u5148\u5168"], + ["a640", "\u5171\u518D\u51B0\u5217\u5211\u5212\u520E\u5216\u52A3\u5308\u5321\u5320\u5370\u5371\u5409\u540F\u540C\u540A\u5410\u5401\u540B\u5404\u5411\u540D\u5408\u5403\u540E\u5406\u5412\u56E0\u56DE\u56DD\u5733\u5730\u5728\u572D\u572C\u572F\u5729\u5919\u591A\u5937\u5938\u5984\u5978\u5983\u597D\u5979\u5982\u5981\u5B57\u5B58\u5B87\u5B88\u5B85\u5B89\u5BFA\u5C16\u5C79\u5DDE\u5E06\u5E76\u5E74"], + ["a6a1", "\u5F0F\u5F1B\u5FD9\u5FD6\u620E\u620C\u620D\u6210\u6263\u625B\u6258\u6536\u65E9\u65E8\u65EC\u65ED\u66F2\u66F3\u6709\u673D\u6734\u6731\u6735\u6B21\u6B64\u6B7B\u6C16\u6C5D\u6C57\u6C59\u6C5F\u6C60\u6C50\u6C55\u6C61\u6C5B\u6C4D\u6C4E\u7070\u725F\u725D\u767E\u7AF9\u7C73\u7CF8\u7F36\u7F8A\u7FBD\u8001\u8003\u800C\u8012\u8033\u807F\u8089\u808B\u808C\u81E3\u81EA\u81F3\u81FC\u820C\u821B\u821F\u826E\u8272\u827E\u866B\u8840\u884C\u8863\u897F\u9621\u4E32\u4EA8\u4F4D\u4F4F\u4F47\u4F57\u4F5E\u4F34\u4F5B\u4F55\u4F30\u4F50\u4F51\u4F3D\u4F3A\u4F38\u4F43\u4F54\u4F3C\u4F46\u4F63"], + ["a740", "\u4F5C\u4F60\u4F2F\u4F4E\u4F36\u4F59\u4F5D\u4F48\u4F5A\u514C\u514B\u514D\u5175\u51B6\u51B7\u5225\u5224\u5229\u522A\u5228\u52AB\u52A9\u52AA\u52AC\u5323\u5373\u5375\u541D\u542D\u541E\u543E\u5426\u544E\u5427\u5446\u5443\u5433\u5448\u5442\u541B\u5429\u544A\u5439\u543B\u5438\u542E\u5435\u5436\u5420\u543C\u5440\u5431\u542B\u541F\u542C\u56EA\u56F0\u56E4\u56EB\u574A\u5751\u5740\u574D"], + ["a7a1", "\u5747\u574E\u573E\u5750\u574F\u573B\u58EF\u593E\u599D\u5992\u59A8\u599E\u59A3\u5999\u5996\u598D\u59A4\u5993\u598A\u59A5\u5B5D\u5B5C\u5B5A\u5B5B\u5B8C\u5B8B\u5B8F\u5C2C\u5C40\u5C41\u5C3F\u5C3E\u5C90\u5C91\u5C94\u5C8C\u5DEB\u5E0C\u5E8F\u5E87\u5E8A\u5EF7\u5F04\u5F1F\u5F64\u5F62\u5F77\u5F79\u5FD8\u5FCC\u5FD7\u5FCD\u5FF1\u5FEB\u5FF8\u5FEA\u6212\u6211\u6284\u6297\u6296\u6280\u6276\u6289\u626D\u628A\u627C\u627E\u6279\u6273\u6292\u626F\u6298\u626E\u6295\u6293\u6291\u6286\u6539\u653B\u6538\u65F1\u66F4\u675F\u674E\u674F\u6750\u6751\u675C\u6756\u675E\u6749\u6746\u6760"], + ["a840", "\u6753\u6757\u6B65\u6BCF\u6C42\u6C5E\u6C99\u6C81\u6C88\u6C89\u6C85\u6C9B\u6C6A\u6C7A\u6C90\u6C70\u6C8C\u6C68\u6C96\u6C92\u6C7D\u6C83\u6C72\u6C7E\u6C74\u6C86\u6C76\u6C8D\u6C94\u6C98\u6C82\u7076\u707C\u707D\u7078\u7262\u7261\u7260\u72C4\u72C2\u7396\u752C\u752B\u7537\u7538\u7682\u76EF\u77E3\u79C1\u79C0\u79BF\u7A76\u7CFB\u7F55\u8096\u8093\u809D\u8098\u809B\u809A\u80B2\u826F\u8292"], + ["a8a1", "\u828B\u828D\u898B\u89D2\u8A00\u8C37\u8C46\u8C55\u8C9D\u8D64\u8D70\u8DB3\u8EAB\u8ECA\u8F9B\u8FB0\u8FC2\u8FC6\u8FC5\u8FC4\u5DE1\u9091\u90A2\u90AA\u90A6\u90A3\u9149\u91C6\u91CC\u9632\u962E\u9631\u962A\u962C\u4E26\u4E56\u4E73\u4E8B\u4E9B\u4E9E\u4EAB\u4EAC\u4F6F\u4F9D\u4F8D\u4F73\u4F7F\u4F6C\u4F9B\u4F8B\u4F86\u4F83\u4F70\u4F75\u4F88\u4F69\u4F7B\u4F96\u4F7E\u4F8F\u4F91\u4F7A\u5154\u5152\u5155\u5169\u5177\u5176\u5178\u51BD\u51FD\u523B\u5238\u5237\u523A\u5230\u522E\u5236\u5241\u52BE\u52BB\u5352\u5354\u5353\u5351\u5366\u5377\u5378\u5379\u53D6\u53D4\u53D7\u5473\u5475"], + ["a940", "\u5496\u5478\u5495\u5480\u547B\u5477\u5484\u5492\u5486\u547C\u5490\u5471\u5476\u548C\u549A\u5462\u5468\u548B\u547D\u548E\u56FA\u5783\u5777\u576A\u5769\u5761\u5766\u5764\u577C\u591C\u5949\u5947\u5948\u5944\u5954\u59BE\u59BB\u59D4\u59B9\u59AE\u59D1\u59C6\u59D0\u59CD\u59CB\u59D3\u59CA\u59AF\u59B3\u59D2\u59C5\u5B5F\u5B64\u5B63\u5B97\u5B9A\u5B98\u5B9C\u5B99\u5B9B\u5C1A\u5C48\u5C45"], + ["a9a1", "\u5C46\u5CB7\u5CA1\u5CB8\u5CA9\u5CAB\u5CB1\u5CB3\u5E18\u5E1A\u5E16\u5E15\u5E1B\u5E11\u5E78\u5E9A\u5E97\u5E9C\u5E95\u5E96\u5EF6\u5F26\u5F27\u5F29\u5F80\u5F81\u5F7F\u5F7C\u5FDD\u5FE0\u5FFD\u5FF5\u5FFF\u600F\u6014\u602F\u6035\u6016\u602A\u6015\u6021\u6027\u6029\u602B\u601B\u6216\u6215\u623F\u623E\u6240\u627F\u62C9\u62CC\u62C4\u62BF\u62C2\u62B9\u62D2\u62DB\u62AB\u62D3\u62D4\u62CB\u62C8\u62A8\u62BD\u62BC\u62D0\u62D9\u62C7\u62CD\u62B5\u62DA\u62B1\u62D8\u62D6\u62D7\u62C6\u62AC\u62CE\u653E\u65A7\u65BC\u65FA\u6614\u6613\u660C\u6606\u6602\u660E\u6600\u660F\u6615\u660A"], + ["aa40", "\u6607\u670D\u670B\u676D\u678B\u6795\u6771\u679C\u6773\u6777\u6787\u679D\u6797\u676F\u6770\u677F\u6789\u677E\u6790\u6775\u679A\u6793\u677C\u676A\u6772\u6B23\u6B66\u6B67\u6B7F\u6C13\u6C1B\u6CE3\u6CE8\u6CF3\u6CB1\u6CCC\u6CE5\u6CB3\u6CBD\u6CBE\u6CBC\u6CE2\u6CAB\u6CD5\u6CD3\u6CB8\u6CC4\u6CB9\u6CC1\u6CAE\u6CD7\u6CC5\u6CF1\u6CBF\u6CBB\u6CE1\u6CDB\u6CCA\u6CAC\u6CEF\u6CDC\u6CD6\u6CE0"], + ["aaa1", "\u7095\u708E\u7092\u708A\u7099\u722C\u722D\u7238\u7248\u7267\u7269\u72C0\u72CE\u72D9\u72D7\u72D0\u73A9\u73A8\u739F\u73AB\u73A5\u753D\u759D\u7599\u759A\u7684\u76C2\u76F2\u76F4\u77E5\u77FD\u793E\u7940\u7941\u79C9\u79C8\u7A7A\u7A79\u7AFA\u7CFE\u7F54\u7F8C\u7F8B\u8005\u80BA\u80A5\u80A2\u80B1\u80A1\u80AB\u80A9\u80B4\u80AA\u80AF\u81E5\u81FE\u820D\u82B3\u829D\u8299\u82AD\u82BD\u829F\u82B9\u82B1\u82AC\u82A5\u82AF\u82B8\u82A3\u82B0\u82BE\u82B7\u864E\u8671\u521D\u8868\u8ECB\u8FCE\u8FD4\u8FD1\u90B5\u90B8\u90B1\u90B6\u91C7\u91D1\u9577\u9580\u961C\u9640\u963F\u963B\u9644"], + ["ab40", "\u9642\u96B9\u96E8\u9752\u975E\u4E9F\u4EAD\u4EAE\u4FE1\u4FB5\u4FAF\u4FBF\u4FE0\u4FD1\u4FCF\u4FDD\u4FC3\u4FB6\u4FD8\u4FDF\u4FCA\u4FD7\u4FAE\u4FD0\u4FC4\u4FC2\u4FDA\u4FCE\u4FDE\u4FB7\u5157\u5192\u5191\u51A0\u524E\u5243\u524A\u524D\u524C\u524B\u5247\u52C7\u52C9\u52C3\u52C1\u530D\u5357\u537B\u539A\u53DB\u54AC\u54C0\u54A8\u54CE\u54C9\u54B8\u54A6\u54B3\u54C7\u54C2\u54BD\u54AA\u54C1"], + ["aba1", "\u54C4\u54C8\u54AF\u54AB\u54B1\u54BB\u54A9\u54A7\u54BF\u56FF\u5782\u578B\u57A0\u57A3\u57A2\u57CE\u57AE\u5793\u5955\u5951\u594F\u594E\u5950\u59DC\u59D8\u59FF\u59E3\u59E8\u5A03\u59E5\u59EA\u59DA\u59E6\u5A01\u59FB\u5B69\u5BA3\u5BA6\u5BA4\u5BA2\u5BA5\u5C01\u5C4E\u5C4F\u5C4D\u5C4B\u5CD9\u5CD2\u5DF7\u5E1D\u5E25\u5E1F\u5E7D\u5EA0\u5EA6\u5EFA\u5F08\u5F2D\u5F65\u5F88\u5F85\u5F8A\u5F8B\u5F87\u5F8C\u5F89\u6012\u601D\u6020\u6025\u600E\u6028\u604D\u6070\u6068\u6062\u6046\u6043\u606C\u606B\u606A\u6064\u6241\u62DC\u6316\u6309\u62FC\u62ED\u6301\u62EE\u62FD\u6307\u62F1\u62F7"], + ["ac40", "\u62EF\u62EC\u62FE\u62F4\u6311\u6302\u653F\u6545\u65AB\u65BD\u65E2\u6625\u662D\u6620\u6627\u662F\u661F\u6628\u6631\u6624\u66F7\u67FF\u67D3\u67F1\u67D4\u67D0\u67EC\u67B6\u67AF\u67F5\u67E9\u67EF\u67C4\u67D1\u67B4\u67DA\u67E5\u67B8\u67CF\u67DE\u67F3\u67B0\u67D9\u67E2\u67DD\u67D2\u6B6A\u6B83\u6B86\u6BB5\u6BD2\u6BD7\u6C1F\u6CC9\u6D0B\u6D32\u6D2A\u6D41\u6D25\u6D0C\u6D31\u6D1E\u6D17"], + ["aca1", "\u6D3B\u6D3D\u6D3E\u6D36\u6D1B\u6CF5\u6D39\u6D27\u6D38\u6D29\u6D2E\u6D35\u6D0E\u6D2B\u70AB\u70BA\u70B3\u70AC\u70AF\u70AD\u70B8\u70AE\u70A4\u7230\u7272\u726F\u7274\u72E9\u72E0\u72E1\u73B7\u73CA\u73BB\u73B2\u73CD\u73C0\u73B3\u751A\u752D\u754F\u754C\u754E\u754B\u75AB\u75A4\u75A5\u75A2\u75A3\u7678\u7686\u7687\u7688\u76C8\u76C6\u76C3\u76C5\u7701\u76F9\u76F8\u7709\u770B\u76FE\u76FC\u7707\u77DC\u7802\u7814\u780C\u780D\u7946\u7949\u7948\u7947\u79B9\u79BA\u79D1\u79D2\u79CB\u7A7F\u7A81\u7AFF\u7AFD\u7C7D\u7D02\u7D05\u7D00\u7D09\u7D07\u7D04\u7D06\u7F38\u7F8E\u7FBF\u8004"], + ["ad40", "\u8010\u800D\u8011\u8036\u80D6\u80E5\u80DA\u80C3\u80C4\u80CC\u80E1\u80DB\u80CE\u80DE\u80E4\u80DD\u81F4\u8222\u82E7\u8303\u8305\u82E3\u82DB\u82E6\u8304\u82E5\u8302\u8309\u82D2\u82D7\u82F1\u8301\u82DC\u82D4\u82D1\u82DE\u82D3\u82DF\u82EF\u8306\u8650\u8679\u867B\u867A\u884D\u886B\u8981\u89D4\u8A08\u8A02\u8A03\u8C9E\u8CA0\u8D74\u8D73\u8DB4\u8ECD\u8ECC\u8FF0\u8FE6\u8FE2\u8FEA\u8FE5"], + ["ada1", "\u8FED\u8FEB\u8FE4\u8FE8\u90CA\u90CE\u90C1\u90C3\u914B\u914A\u91CD\u9582\u9650\u964B\u964C\u964D\u9762\u9769\u97CB\u97ED\u97F3\u9801\u98A8\u98DB\u98DF\u9996\u9999\u4E58\u4EB3\u500C\u500D\u5023\u4FEF\u5026\u5025\u4FF8\u5029\u5016\u5006\u503C\u501F\u501A\u5012\u5011\u4FFA\u5000\u5014\u5028\u4FF1\u5021\u500B\u5019\u5018\u4FF3\u4FEE\u502D\u502A\u4FFE\u502B\u5009\u517C\u51A4\u51A5\u51A2\u51CD\u51CC\u51C6\u51CB\u5256\u525C\u5254\u525B\u525D\u532A\u537F\u539F\u539D\u53DF\u54E8\u5510\u5501\u5537\u54FC\u54E5\u54F2\u5506\u54FA\u5514\u54E9\u54ED\u54E1\u5509\u54EE\u54EA"], + ["ae40", "\u54E6\u5527\u5507\u54FD\u550F\u5703\u5704\u57C2\u57D4\u57CB\u57C3\u5809\u590F\u5957\u5958\u595A\u5A11\u5A18\u5A1C\u5A1F\u5A1B\u5A13\u59EC\u5A20\u5A23\u5A29\u5A25\u5A0C\u5A09\u5B6B\u5C58\u5BB0\u5BB3\u5BB6\u5BB4\u5BAE\u5BB5\u5BB9\u5BB8\u5C04\u5C51\u5C55\u5C50\u5CED\u5CFD\u5CFB\u5CEA\u5CE8\u5CF0\u5CF6\u5D01\u5CF4\u5DEE\u5E2D\u5E2B\u5EAB\u5EAD\u5EA7\u5F31\u5F92\u5F91\u5F90\u6059"], + ["aea1", "\u6063\u6065\u6050\u6055\u606D\u6069\u606F\u6084\u609F\u609A\u608D\u6094\u608C\u6085\u6096\u6247\u62F3\u6308\u62FF\u634E\u633E\u632F\u6355\u6342\u6346\u634F\u6349\u633A\u6350\u633D\u632A\u632B\u6328\u634D\u634C\u6548\u6549\u6599\u65C1\u65C5\u6642\u6649\u664F\u6643\u6652\u664C\u6645\u6641\u66F8\u6714\u6715\u6717\u6821\u6838\u6848\u6846\u6853\u6839\u6842\u6854\u6829\u68B3\u6817\u684C\u6851\u683D\u67F4\u6850\u6840\u683C\u6843\u682A\u6845\u6813\u6818\u6841\u6B8A\u6B89\u6BB7\u6C23\u6C27\u6C28\u6C26\u6C24\u6CF0\u6D6A\u6D95\u6D88\u6D87\u6D66\u6D78\u6D77\u6D59\u6D93"], + ["af40", "\u6D6C\u6D89\u6D6E\u6D5A\u6D74\u6D69\u6D8C\u6D8A\u6D79\u6D85\u6D65\u6D94\u70CA\u70D8\u70E4\u70D9\u70C8\u70CF\u7239\u7279\u72FC\u72F9\u72FD\u72F8\u72F7\u7386\u73ED\u7409\u73EE\u73E0\u73EA\u73DE\u7554\u755D\u755C\u755A\u7559\u75BE\u75C5\u75C7\u75B2\u75B3\u75BD\u75BC\u75B9\u75C2\u75B8\u768B\u76B0\u76CA\u76CD\u76CE\u7729\u771F\u7720\u7728\u77E9\u7830\u7827\u7838\u781D\u7834\u7837"], + ["afa1", "\u7825\u782D\u7820\u781F\u7832\u7955\u7950\u7960\u795F\u7956\u795E\u795D\u7957\u795A\u79E4\u79E3\u79E7\u79DF\u79E6\u79E9\u79D8\u7A84\u7A88\u7AD9\u7B06\u7B11\u7C89\u7D21\u7D17\u7D0B\u7D0A\u7D20\u7D22\u7D14\u7D10\u7D15\u7D1A\u7D1C\u7D0D\u7D19\u7D1B\u7F3A\u7F5F\u7F94\u7FC5\u7FC1\u8006\u8018\u8015\u8019\u8017\u803D\u803F\u80F1\u8102\u80F0\u8105\u80ED\u80F4\u8106\u80F8\u80F3\u8108\u80FD\u810A\u80FC\u80EF\u81ED\u81EC\u8200\u8210\u822A\u822B\u8228\u822C\u82BB\u832B\u8352\u8354\u834A\u8338\u8350\u8349\u8335\u8334\u834F\u8332\u8339\u8336\u8317\u8340\u8331\u8328\u8343"], + ["b040", "\u8654\u868A\u86AA\u8693\u86A4\u86A9\u868C\u86A3\u869C\u8870\u8877\u8881\u8882\u887D\u8879\u8A18\u8A10\u8A0E\u8A0C\u8A15\u8A0A\u8A17\u8A13\u8A16\u8A0F\u8A11\u8C48\u8C7A\u8C79\u8CA1\u8CA2\u8D77\u8EAC\u8ED2\u8ED4\u8ECF\u8FB1\u9001\u9006\u8FF7\u9000\u8FFA\u8FF4\u9003\u8FFD\u9005\u8FF8\u9095\u90E1\u90DD\u90E2\u9152\u914D\u914C\u91D8\u91DD\u91D7\u91DC\u91D9\u9583\u9662\u9663\u9661"], + ["b0a1", "\u965B\u965D\u9664\u9658\u965E\u96BB\u98E2\u99AC\u9AA8\u9AD8\u9B25\u9B32\u9B3C\u4E7E\u507A\u507D\u505C\u5047\u5043\u504C\u505A\u5049\u5065\u5076\u504E\u5055\u5075\u5074\u5077\u504F\u500F\u506F\u506D\u515C\u5195\u51F0\u526A\u526F\u52D2\u52D9\u52D8\u52D5\u5310\u530F\u5319\u533F\u5340\u533E\u53C3\u66FC\u5546\u556A\u5566\u5544\u555E\u5561\u5543\u554A\u5531\u5556\u554F\u5555\u552F\u5564\u5538\u552E\u555C\u552C\u5563\u5533\u5541\u5557\u5708\u570B\u5709\u57DF\u5805\u580A\u5806\u57E0\u57E4\u57FA\u5802\u5835\u57F7\u57F9\u5920\u5962\u5A36\u5A41\u5A49\u5A66\u5A6A\u5A40"], + ["b140", "\u5A3C\u5A62\u5A5A\u5A46\u5A4A\u5B70\u5BC7\u5BC5\u5BC4\u5BC2\u5BBF\u5BC6\u5C09\u5C08\u5C07\u5C60\u5C5C\u5C5D\u5D07\u5D06\u5D0E\u5D1B\u5D16\u5D22\u5D11\u5D29\u5D14\u5D19\u5D24\u5D27\u5D17\u5DE2\u5E38\u5E36\u5E33\u5E37\u5EB7\u5EB8\u5EB6\u5EB5\u5EBE\u5F35\u5F37\u5F57\u5F6C\u5F69\u5F6B\u5F97\u5F99\u5F9E\u5F98\u5FA1\u5FA0\u5F9C\u607F\u60A3\u6089\u60A0\u60A8\u60CB\u60B4\u60E6\u60BD"], + ["b1a1", "\u60C5\u60BB\u60B5\u60DC\u60BC\u60D8\u60D5\u60C6\u60DF\u60B8\u60DA\u60C7\u621A\u621B\u6248\u63A0\u63A7\u6372\u6396\u63A2\u63A5\u6377\u6367\u6398\u63AA\u6371\u63A9\u6389\u6383\u639B\u636B\u63A8\u6384\u6388\u6399\u63A1\u63AC\u6392\u638F\u6380\u637B\u6369\u6368\u637A\u655D\u6556\u6551\u6559\u6557\u555F\u654F\u6558\u6555\u6554\u659C\u659B\u65AC\u65CF\u65CB\u65CC\u65CE\u665D\u665A\u6664\u6668\u6666\u665E\u66F9\u52D7\u671B\u6881\u68AF\u68A2\u6893\u68B5\u687F\u6876\u68B1\u68A7\u6897\u68B0\u6883\u68C4\u68AD\u6886\u6885\u6894\u689D\u68A8\u689F\u68A1\u6882\u6B32\u6BBA"], + ["b240", "\u6BEB\u6BEC\u6C2B\u6D8E\u6DBC\u6DF3\u6DD9\u6DB2\u6DE1\u6DCC\u6DE4\u6DFB\u6DFA\u6E05\u6DC7\u6DCB\u6DAF\u6DD1\u6DAE\u6DDE\u6DF9\u6DB8\u6DF7\u6DF5\u6DC5\u6DD2\u6E1A\u6DB5\u6DDA\u6DEB\u6DD8\u6DEA\u6DF1\u6DEE\u6DE8\u6DC6\u6DC4\u6DAA\u6DEC\u6DBF\u6DE6\u70F9\u7109\u710A\u70FD\u70EF\u723D\u727D\u7281\u731C\u731B\u7316\u7313\u7319\u7387\u7405\u740A\u7403\u7406\u73FE\u740D\u74E0\u74F6"], + ["b2a1", "\u74F7\u751C\u7522\u7565\u7566\u7562\u7570\u758F\u75D4\u75D5\u75B5\u75CA\u75CD\u768E\u76D4\u76D2\u76DB\u7737\u773E\u773C\u7736\u7738\u773A\u786B\u7843\u784E\u7965\u7968\u796D\u79FB\u7A92\u7A95\u7B20\u7B28\u7B1B\u7B2C\u7B26\u7B19\u7B1E\u7B2E\u7C92\u7C97\u7C95\u7D46\u7D43\u7D71\u7D2E\u7D39\u7D3C\u7D40\u7D30\u7D33\u7D44\u7D2F\u7D42\u7D32\u7D31\u7F3D\u7F9E\u7F9A\u7FCC\u7FCE\u7FD2\u801C\u804A\u8046\u812F\u8116\u8123\u812B\u8129\u8130\u8124\u8202\u8235\u8237\u8236\u8239\u838E\u839E\u8398\u8378\u83A2\u8396\u83BD\u83AB\u8392\u838A\u8393\u8389\u83A0\u8377\u837B\u837C"], + ["b340", "\u8386\u83A7\u8655\u5F6A\u86C7\u86C0\u86B6\u86C4\u86B5\u86C6\u86CB\u86B1\u86AF\u86C9\u8853\u889E\u8888\u88AB\u8892\u8896\u888D\u888B\u8993\u898F\u8A2A\u8A1D\u8A23\u8A25\u8A31\u8A2D\u8A1F\u8A1B\u8A22\u8C49\u8C5A\u8CA9\u8CAC\u8CAB\u8CA8\u8CAA\u8CA7\u8D67\u8D66\u8DBE\u8DBA\u8EDB\u8EDF\u9019\u900D\u901A\u9017\u9023\u901F\u901D\u9010\u9015\u901E\u9020\u900F\u9022\u9016\u901B\u9014"], + ["b3a1", "\u90E8\u90ED\u90FD\u9157\u91CE\u91F5\u91E6\u91E3\u91E7\u91ED\u91E9\u9589\u966A\u9675\u9673\u9678\u9670\u9674\u9676\u9677\u966C\u96C0\u96EA\u96E9\u7AE0\u7ADF\u9802\u9803\u9B5A\u9CE5\u9E75\u9E7F\u9EA5\u9EBB\u50A2\u508D\u5085\u5099\u5091\u5080\u5096\u5098\u509A\u6700\u51F1\u5272\u5274\u5275\u5269\u52DE\u52DD\u52DB\u535A\u53A5\u557B\u5580\u55A7\u557C\u558A\u559D\u5598\u5582\u559C\u55AA\u5594\u5587\u558B\u5583\u55B3\u55AE\u559F\u553E\u55B2\u559A\u55BB\u55AC\u55B1\u557E\u5589\u55AB\u5599\u570D\u582F\u582A\u5834\u5824\u5830\u5831\u5821\u581D\u5820\u58F9\u58FA\u5960"], + ["b440", "\u5A77\u5A9A\u5A7F\u5A92\u5A9B\u5AA7\u5B73\u5B71\u5BD2\u5BCC\u5BD3\u5BD0\u5C0A\u5C0B\u5C31\u5D4C\u5D50\u5D34\u5D47\u5DFD\u5E45\u5E3D\u5E40\u5E43\u5E7E\u5ECA\u5EC1\u5EC2\u5EC4\u5F3C\u5F6D\u5FA9\u5FAA\u5FA8\u60D1\u60E1\u60B2\u60B6\u60E0\u611C\u6123\u60FA\u6115\u60F0\u60FB\u60F4\u6168\u60F1\u610E\u60F6\u6109\u6100\u6112\u621F\u6249\u63A3\u638C\u63CF\u63C0\u63E9\u63C9\u63C6\u63CD"], + ["b4a1", "\u63D2\u63E3\u63D0\u63E1\u63D6\u63ED\u63EE\u6376\u63F4\u63EA\u63DB\u6452\u63DA\u63F9\u655E\u6566\u6562\u6563\u6591\u6590\u65AF\u666E\u6670\u6674\u6676\u666F\u6691\u667A\u667E\u6677\u66FE\u66FF\u671F\u671D\u68FA\u68D5\u68E0\u68D8\u68D7\u6905\u68DF\u68F5\u68EE\u68E7\u68F9\u68D2\u68F2\u68E3\u68CB\u68CD\u690D\u6912\u690E\u68C9\u68DA\u696E\u68FB\u6B3E\u6B3A\u6B3D\u6B98\u6B96\u6BBC\u6BEF\u6C2E\u6C2F\u6C2C\u6E2F\u6E38\u6E54\u6E21\u6E32\u6E67\u6E4A\u6E20\u6E25\u6E23\u6E1B\u6E5B\u6E58\u6E24\u6E56\u6E6E\u6E2D\u6E26\u6E6F\u6E34\u6E4D\u6E3A\u6E2C\u6E43\u6E1D\u6E3E\u6ECB"], + ["b540", "\u6E89\u6E19\u6E4E\u6E63\u6E44\u6E72\u6E69\u6E5F\u7119\u711A\u7126\u7130\u7121\u7136\u716E\u711C\u724C\u7284\u7280\u7336\u7325\u7334\u7329\u743A\u742A\u7433\u7422\u7425\u7435\u7436\u7434\u742F\u741B\u7426\u7428\u7525\u7526\u756B\u756A\u75E2\u75DB\u75E3\u75D9\u75D8\u75DE\u75E0\u767B\u767C\u7696\u7693\u76B4\u76DC\u774F\u77ED\u785D\u786C\u786F\u7A0D\u7A08\u7A0B\u7A05\u7A00\u7A98"], + ["b5a1", "\u7A97\u7A96\u7AE5\u7AE3\u7B49\u7B56\u7B46\u7B50\u7B52\u7B54\u7B4D\u7B4B\u7B4F\u7B51\u7C9F\u7CA5\u7D5E\u7D50\u7D68\u7D55\u7D2B\u7D6E\u7D72\u7D61\u7D66\u7D62\u7D70\u7D73\u5584\u7FD4\u7FD5\u800B\u8052\u8085\u8155\u8154\u814B\u8151\u814E\u8139\u8146\u813E\u814C\u8153\u8174\u8212\u821C\u83E9\u8403\u83F8\u840D\u83E0\u83C5\u840B\u83C1\u83EF\u83F1\u83F4\u8457\u840A\u83F0\u840C\u83CC\u83FD\u83F2\u83CA\u8438\u840E\u8404\u83DC\u8407\u83D4\u83DF\u865B\u86DF\u86D9\u86ED\u86D4\u86DB\u86E4\u86D0\u86DE\u8857\u88C1\u88C2\u88B1\u8983\u8996\u8A3B\u8A60\u8A55\u8A5E\u8A3C\u8A41"], + ["b640", "\u8A54\u8A5B\u8A50\u8A46\u8A34\u8A3A\u8A36\u8A56\u8C61\u8C82\u8CAF\u8CBC\u8CB3\u8CBD\u8CC1\u8CBB\u8CC0\u8CB4\u8CB7\u8CB6\u8CBF\u8CB8\u8D8A\u8D85\u8D81\u8DCE\u8DDD\u8DCB\u8DDA\u8DD1\u8DCC\u8DDB\u8DC6\u8EFB\u8EF8\u8EFC\u8F9C\u902E\u9035\u9031\u9038\u9032\u9036\u9102\u90F5\u9109\u90FE\u9163\u9165\u91CF\u9214\u9215\u9223\u9209\u921E\u920D\u9210\u9207\u9211\u9594\u958F\u958B\u9591"], + ["b6a1", "\u9593\u9592\u958E\u968A\u968E\u968B\u967D\u9685\u9686\u968D\u9672\u9684\u96C1\u96C5\u96C4\u96C6\u96C7\u96EF\u96F2\u97CC\u9805\u9806\u9808\u98E7\u98EA\u98EF\u98E9\u98F2\u98ED\u99AE\u99AD\u9EC3\u9ECD\u9ED1\u4E82\u50AD\u50B5\u50B2\u50B3\u50C5\u50BE\u50AC\u50B7\u50BB\u50AF\u50C7\u527F\u5277\u527D\u52DF\u52E6\u52E4\u52E2\u52E3\u532F\u55DF\u55E8\u55D3\u55E6\u55CE\u55DC\u55C7\u55D1\u55E3\u55E4\u55EF\u55DA\u55E1\u55C5\u55C6\u55E5\u55C9\u5712\u5713\u585E\u5851\u5858\u5857\u585A\u5854\u586B\u584C\u586D\u584A\u5862\u5852\u584B\u5967\u5AC1\u5AC9\u5ACC\u5ABE\u5ABD\u5ABC"], + ["b740", "\u5AB3\u5AC2\u5AB2\u5D69\u5D6F\u5E4C\u5E79\u5EC9\u5EC8\u5F12\u5F59\u5FAC\u5FAE\u611A\u610F\u6148\u611F\u60F3\u611B\u60F9\u6101\u6108\u614E\u614C\u6144\u614D\u613E\u6134\u6127\u610D\u6106\u6137\u6221\u6222\u6413\u643E\u641E\u642A\u642D\u643D\u642C\u640F\u641C\u6414\u640D\u6436\u6416\u6417\u6406\u656C\u659F\u65B0\u6697\u6689\u6687\u6688\u6696\u6684\u6698\u668D\u6703\u6994\u696D"], + ["b7a1", "\u695A\u6977\u6960\u6954\u6975\u6930\u6982\u694A\u6968\u696B\u695E\u6953\u6979\u6986\u695D\u6963\u695B\u6B47\u6B72\u6BC0\u6BBF\u6BD3\u6BFD\u6EA2\u6EAF\u6ED3\u6EB6\u6EC2\u6E90\u6E9D\u6EC7\u6EC5\u6EA5\u6E98\u6EBC\u6EBA\u6EAB\u6ED1\u6E96\u6E9C\u6EC4\u6ED4\u6EAA\u6EA7\u6EB4\u714E\u7159\u7169\u7164\u7149\u7167\u715C\u716C\u7166\u714C\u7165\u715E\u7146\u7168\u7156\u723A\u7252\u7337\u7345\u733F\u733E\u746F\u745A\u7455\u745F\u745E\u7441\u743F\u7459\u745B\u745C\u7576\u7578\u7600\u75F0\u7601\u75F2\u75F1\u75FA\u75FF\u75F4\u75F3\u76DE\u76DF\u775B\u776B\u7766\u775E\u7763"], + ["b840", "\u7779\u776A\u776C\u775C\u7765\u7768\u7762\u77EE\u788E\u78B0\u7897\u7898\u788C\u7889\u787C\u7891\u7893\u787F\u797A\u797F\u7981\u842C\u79BD\u7A1C\u7A1A\u7A20\u7A14\u7A1F\u7A1E\u7A9F\u7AA0\u7B77\u7BC0\u7B60\u7B6E\u7B67\u7CB1\u7CB3\u7CB5\u7D93\u7D79\u7D91\u7D81\u7D8F\u7D5B\u7F6E\u7F69\u7F6A\u7F72\u7FA9\u7FA8\u7FA4\u8056\u8058\u8086\u8084\u8171\u8170\u8178\u8165\u816E\u8173\u816B"], + ["b8a1", "\u8179\u817A\u8166\u8205\u8247\u8482\u8477\u843D\u8431\u8475\u8466\u846B\u8449\u846C\u845B\u843C\u8435\u8461\u8463\u8469\u846D\u8446\u865E\u865C\u865F\u86F9\u8713\u8708\u8707\u8700\u86FE\u86FB\u8702\u8703\u8706\u870A\u8859\u88DF\u88D4\u88D9\u88DC\u88D8\u88DD\u88E1\u88CA\u88D5\u88D2\u899C\u89E3\u8A6B\u8A72\u8A73\u8A66\u8A69\u8A70\u8A87\u8A7C\u8A63\u8AA0\u8A71\u8A85\u8A6D\u8A62\u8A6E\u8A6C\u8A79\u8A7B\u8A3E\u8A68\u8C62\u8C8A\u8C89\u8CCA\u8CC7\u8CC8\u8CC4\u8CB2\u8CC3\u8CC2\u8CC5\u8DE1\u8DDF\u8DE8\u8DEF\u8DF3\u8DFA\u8DEA\u8DE4\u8DE6\u8EB2\u8F03\u8F09\u8EFE\u8F0A"], + ["b940", "\u8F9F\u8FB2\u904B\u904A\u9053\u9042\u9054\u903C\u9055\u9050\u9047\u904F\u904E\u904D\u9051\u903E\u9041\u9112\u9117\u916C\u916A\u9169\u91C9\u9237\u9257\u9238\u923D\u9240\u923E\u925B\u924B\u9264\u9251\u9234\u9249\u924D\u9245\u9239\u923F\u925A\u9598\u9698\u9694\u9695\u96CD\u96CB\u96C9\u96CA\u96F7\u96FB\u96F9\u96F6\u9756\u9774\u9776\u9810\u9811\u9813\u980A\u9812\u980C\u98FC\u98F4"], + ["b9a1", "\u98FD\u98FE\u99B3\u99B1\u99B4\u9AE1\u9CE9\u9E82\u9F0E\u9F13\u9F20\u50E7\u50EE\u50E5\u50D6\u50ED\u50DA\u50D5\u50CF\u50D1\u50F1\u50CE\u50E9\u5162\u51F3\u5283\u5282\u5331\u53AD\u55FE\u5600\u561B\u5617\u55FD\u5614\u5606\u5609\u560D\u560E\u55F7\u5616\u561F\u5608\u5610\u55F6\u5718\u5716\u5875\u587E\u5883\u5893\u588A\u5879\u5885\u587D\u58FD\u5925\u5922\u5924\u596A\u5969\u5AE1\u5AE6\u5AE9\u5AD7\u5AD6\u5AD8\u5AE3\u5B75\u5BDE\u5BE7\u5BE1\u5BE5\u5BE6\u5BE8\u5BE2\u5BE4\u5BDF\u5C0D\u5C62\u5D84\u5D87\u5E5B\u5E63\u5E55\u5E57\u5E54\u5ED3\u5ED6\u5F0A\u5F46\u5F70\u5FB9\u6147"], + ["ba40", "\u613F\u614B\u6177\u6162\u6163\u615F\u615A\u6158\u6175\u622A\u6487\u6458\u6454\u64A4\u6478\u645F\u647A\u6451\u6467\u6434\u646D\u647B\u6572\u65A1\u65D7\u65D6\u66A2\u66A8\u669D\u699C\u69A8\u6995\u69C1\u69AE\u69D3\u69CB\u699B\u69B7\u69BB\u69AB\u69B4\u69D0\u69CD\u69AD\u69CC\u69A6\u69C3\u69A3\u6B49\u6B4C\u6C33\u6F33\u6F14\u6EFE\u6F13\u6EF4\u6F29\u6F3E\u6F20\u6F2C\u6F0F\u6F02\u6F22"], + ["baa1", "\u6EFF\u6EEF\u6F06\u6F31\u6F38\u6F32\u6F23\u6F15\u6F2B\u6F2F\u6F88\u6F2A\u6EEC\u6F01\u6EF2\u6ECC\u6EF7\u7194\u7199\u717D\u718A\u7184\u7192\u723E\u7292\u7296\u7344\u7350\u7464\u7463\u746A\u7470\u746D\u7504\u7591\u7627\u760D\u760B\u7609\u7613\u76E1\u76E3\u7784\u777D\u777F\u7761\u78C1\u789F\u78A7\u78B3\u78A9\u78A3\u798E\u798F\u798D\u7A2E\u7A31\u7AAA\u7AA9\u7AED\u7AEF\u7BA1\u7B95\u7B8B\u7B75\u7B97\u7B9D\u7B94\u7B8F\u7BB8\u7B87\u7B84\u7CB9\u7CBD\u7CBE\u7DBB\u7DB0\u7D9C\u7DBD\u7DBE\u7DA0\u7DCA\u7DB4\u7DB2\u7DB1\u7DBA\u7DA2\u7DBF\u7DB5\u7DB8\u7DAD\u7DD2\u7DC7\u7DAC"], + ["bb40", "\u7F70\u7FE0\u7FE1\u7FDF\u805E\u805A\u8087\u8150\u8180\u818F\u8188\u818A\u817F\u8182\u81E7\u81FA\u8207\u8214\u821E\u824B\u84C9\u84BF\u84C6\u84C4\u8499\u849E\u84B2\u849C\u84CB\u84B8\u84C0\u84D3\u8490\u84BC\u84D1\u84CA\u873F\u871C\u873B\u8722\u8725\u8734\u8718\u8755\u8737\u8729\u88F3\u8902\u88F4\u88F9\u88F8\u88FD\u88E8\u891A\u88EF\u8AA6\u8A8C\u8A9E\u8AA3\u8A8D\u8AA1\u8A93\u8AA4"], + ["bba1", "\u8AAA\u8AA5\u8AA8\u8A98\u8A91\u8A9A\u8AA7\u8C6A\u8C8D\u8C8C\u8CD3\u8CD1\u8CD2\u8D6B\u8D99\u8D95\u8DFC\u8F14\u8F12\u8F15\u8F13\u8FA3\u9060\u9058\u905C\u9063\u9059\u905E\u9062\u905D\u905B\u9119\u9118\u911E\u9175\u9178\u9177\u9174\u9278\u9280\u9285\u9298\u9296\u927B\u9293\u929C\u92A8\u927C\u9291\u95A1\u95A8\u95A9\u95A3\u95A5\u95A4\u9699\u969C\u969B\u96CC\u96D2\u9700\u977C\u9785\u97F6\u9817\u9818\u98AF\u98B1\u9903\u9905\u990C\u9909\u99C1\u9AAF\u9AB0\u9AE6\u9B41\u9B42\u9CF4\u9CF6\u9CF3\u9EBC\u9F3B\u9F4A\u5104\u5100\u50FB\u50F5\u50F9\u5102\u5108\u5109\u5105\u51DC"], + ["bc40", "\u5287\u5288\u5289\u528D\u528A\u52F0\u53B2\u562E\u563B\u5639\u5632\u563F\u5634\u5629\u5653\u564E\u5657\u5674\u5636\u562F\u5630\u5880\u589F\u589E\u58B3\u589C\u58AE\u58A9\u58A6\u596D\u5B09\u5AFB\u5B0B\u5AF5\u5B0C\u5B08\u5BEE\u5BEC\u5BE9\u5BEB\u5C64\u5C65\u5D9D\u5D94\u5E62\u5E5F\u5E61\u5EE2\u5EDA\u5EDF\u5EDD\u5EE3\u5EE0\u5F48\u5F71\u5FB7\u5FB5\u6176\u6167\u616E\u615D\u6155\u6182"], + ["bca1", "\u617C\u6170\u616B\u617E\u61A7\u6190\u61AB\u618E\u61AC\u619A\u61A4\u6194\u61AE\u622E\u6469\u646F\u6479\u649E\u64B2\u6488\u6490\u64B0\u64A5\u6493\u6495\u64A9\u6492\u64AE\u64AD\u64AB\u649A\u64AC\u6499\u64A2\u64B3\u6575\u6577\u6578\u66AE\u66AB\u66B4\u66B1\u6A23\u6A1F\u69E8\u6A01\u6A1E\u6A19\u69FD\u6A21\u6A13\u6A0A\u69F3\u6A02\u6A05\u69ED\u6A11\u6B50\u6B4E\u6BA4\u6BC5\u6BC6\u6F3F\u6F7C\u6F84\u6F51\u6F66\u6F54\u6F86\u6F6D\u6F5B\u6F78\u6F6E\u6F8E\u6F7A\u6F70\u6F64\u6F97\u6F58\u6ED5\u6F6F\u6F60\u6F5F\u719F\u71AC\u71B1\u71A8\u7256\u729B\u734E\u7357\u7469\u748B\u7483"], + ["bd40", "\u747E\u7480\u757F\u7620\u7629\u761F\u7624\u7626\u7621\u7622\u769A\u76BA\u76E4\u778E\u7787\u778C\u7791\u778B\u78CB\u78C5\u78BA\u78CA\u78BE\u78D5\u78BC\u78D0\u7A3F\u7A3C\u7A40\u7A3D\u7A37\u7A3B\u7AAF\u7AAE\u7BAD\u7BB1\u7BC4\u7BB4\u7BC6\u7BC7\u7BC1\u7BA0\u7BCC\u7CCA\u7DE0\u7DF4\u7DEF\u7DFB\u7DD8\u7DEC\u7DDD\u7DE8\u7DE3\u7DDA\u7DDE\u7DE9\u7D9E\u7DD9\u7DF2\u7DF9\u7F75\u7F77\u7FAF"], + ["bda1", "\u7FE9\u8026\u819B\u819C\u819D\u81A0\u819A\u8198\u8517\u853D\u851A\u84EE\u852C\u852D\u8513\u8511\u8523\u8521\u8514\u84EC\u8525\u84FF\u8506\u8782\u8774\u8776\u8760\u8766\u8778\u8768\u8759\u8757\u874C\u8753\u885B\u885D\u8910\u8907\u8912\u8913\u8915\u890A\u8ABC\u8AD2\u8AC7\u8AC4\u8A95\u8ACB\u8AF8\u8AB2\u8AC9\u8AC2\u8ABF\u8AB0\u8AD6\u8ACD\u8AB6\u8AB9\u8ADB\u8C4C\u8C4E\u8C6C\u8CE0\u8CDE\u8CE6\u8CE4\u8CEC\u8CED\u8CE2\u8CE3\u8CDC\u8CEA\u8CE1\u8D6D\u8D9F\u8DA3\u8E2B\u8E10\u8E1D\u8E22\u8E0F\u8E29\u8E1F\u8E21\u8E1E\u8EBA\u8F1D\u8F1B\u8F1F\u8F29\u8F26\u8F2A\u8F1C\u8F1E"], + ["be40", "\u8F25\u9069\u906E\u9068\u906D\u9077\u9130\u912D\u9127\u9131\u9187\u9189\u918B\u9183\u92C5\u92BB\u92B7\u92EA\u92AC\u92E4\u92C1\u92B3\u92BC\u92D2\u92C7\u92F0\u92B2\u95AD\u95B1\u9704\u9706\u9707\u9709\u9760\u978D\u978B\u978F\u9821\u982B\u981C\u98B3\u990A\u9913\u9912\u9918\u99DD\u99D0\u99DF\u99DB\u99D1\u99D5\u99D2\u99D9\u9AB7\u9AEE\u9AEF\u9B27\u9B45\u9B44\u9B77\u9B6F\u9D06\u9D09"], + ["bea1", "\u9D03\u9EA9\u9EBE\u9ECE\u58A8\u9F52\u5112\u5118\u5114\u5110\u5115\u5180\u51AA\u51DD\u5291\u5293\u52F3\u5659\u566B\u5679\u5669\u5664\u5678\u566A\u5668\u5665\u5671\u566F\u566C\u5662\u5676\u58C1\u58BE\u58C7\u58C5\u596E\u5B1D\u5B34\u5B78\u5BF0\u5C0E\u5F4A\u61B2\u6191\u61A9\u618A\u61CD\u61B6\u61BE\u61CA\u61C8\u6230\u64C5\u64C1\u64CB\u64BB\u64BC\u64DA\u64C4\u64C7\u64C2\u64CD\u64BF\u64D2\u64D4\u64BE\u6574\u66C6\u66C9\u66B9\u66C4\u66C7\u66B8\u6A3D\u6A38\u6A3A\u6A59\u6A6B\u6A58\u6A39\u6A44\u6A62\u6A61\u6A4B\u6A47\u6A35\u6A5F\u6A48\u6B59\u6B77\u6C05\u6FC2\u6FB1\u6FA1"], + ["bf40", "\u6FC3\u6FA4\u6FC1\u6FA7\u6FB3\u6FC0\u6FB9\u6FB6\u6FA6\u6FA0\u6FB4\u71BE\u71C9\u71D0\u71D2\u71C8\u71D5\u71B9\u71CE\u71D9\u71DC\u71C3\u71C4\u7368\u749C\u74A3\u7498\u749F\u749E\u74E2\u750C\u750D\u7634\u7638\u763A\u76E7\u76E5\u77A0\u779E\u779F\u77A5\u78E8\u78DA\u78EC\u78E7\u79A6\u7A4D\u7A4E\u7A46\u7A4C\u7A4B\u7ABA\u7BD9\u7C11\u7BC9\u7BE4\u7BDB\u7BE1\u7BE9\u7BE6\u7CD5\u7CD6\u7E0A"], + ["bfa1", "\u7E11\u7E08\u7E1B\u7E23\u7E1E\u7E1D\u7E09\u7E10\u7F79\u7FB2\u7FF0\u7FF1\u7FEE\u8028\u81B3\u81A9\u81A8\u81FB\u8208\u8258\u8259\u854A\u8559\u8548\u8568\u8569\u8543\u8549\u856D\u856A\u855E\u8783\u879F\u879E\u87A2\u878D\u8861\u892A\u8932\u8925\u892B\u8921\u89AA\u89A6\u8AE6\u8AFA\u8AEB\u8AF1\u8B00\u8ADC\u8AE7\u8AEE\u8AFE\u8B01\u8B02\u8AF7\u8AED\u8AF3\u8AF6\u8AFC\u8C6B\u8C6D\u8C93\u8CF4\u8E44\u8E31\u8E34\u8E42\u8E39\u8E35\u8F3B\u8F2F\u8F38\u8F33\u8FA8\u8FA6\u9075\u9074\u9078\u9072\u907C\u907A\u9134\u9192\u9320\u9336\u92F8\u9333\u932F\u9322\u92FC\u932B\u9304\u931A"], + ["c040", "\u9310\u9326\u9321\u9315\u932E\u9319\u95BB\u96A7\u96A8\u96AA\u96D5\u970E\u9711\u9716\u970D\u9713\u970F\u975B\u975C\u9766\u9798\u9830\u9838\u983B\u9837\u982D\u9839\u9824\u9910\u9928\u991E\u991B\u9921\u991A\u99ED\u99E2\u99F1\u9AB8\u9ABC\u9AFB\u9AED\u9B28\u9B91\u9D15\u9D23\u9D26\u9D28\u9D12\u9D1B\u9ED8\u9ED4\u9F8D\u9F9C\u512A\u511F\u5121\u5132\u52F5\u568E\u5680\u5690\u5685\u5687"], + ["c0a1", "\u568F\u58D5\u58D3\u58D1\u58CE\u5B30\u5B2A\u5B24\u5B7A\u5C37\u5C68\u5DBC\u5DBA\u5DBD\u5DB8\u5E6B\u5F4C\u5FBD\u61C9\u61C2\u61C7\u61E6\u61CB\u6232\u6234\u64CE\u64CA\u64D8\u64E0\u64F0\u64E6\u64EC\u64F1\u64E2\u64ED\u6582\u6583\u66D9\u66D6\u6A80\u6A94\u6A84\u6AA2\u6A9C\u6ADB\u6AA3\u6A7E\u6A97\u6A90\u6AA0\u6B5C\u6BAE\u6BDA\u6C08\u6FD8\u6FF1\u6FDF\u6FE0\u6FDB\u6FE4\u6FEB\u6FEF\u6F80\u6FEC\u6FE1\u6FE9\u6FD5\u6FEE\u6FF0\u71E7\u71DF\u71EE\u71E6\u71E5\u71ED\u71EC\u71F4\u71E0\u7235\u7246\u7370\u7372\u74A9\u74B0\u74A6\u74A8\u7646\u7642\u764C\u76EA\u77B3\u77AA\u77B0\u77AC"], + ["c140", "\u77A7\u77AD\u77EF\u78F7\u78FA\u78F4\u78EF\u7901\u79A7\u79AA\u7A57\u7ABF\u7C07\u7C0D\u7BFE\u7BF7\u7C0C\u7BE0\u7CE0\u7CDC\u7CDE\u7CE2\u7CDF\u7CD9\u7CDD\u7E2E\u7E3E\u7E46\u7E37\u7E32\u7E43\u7E2B\u7E3D\u7E31\u7E45\u7E41\u7E34\u7E39\u7E48\u7E35\u7E3F\u7E2F\u7F44\u7FF3\u7FFC\u8071\u8072\u8070\u806F\u8073\u81C6\u81C3\u81BA\u81C2\u81C0\u81BF\u81BD\u81C9\u81BE\u81E8\u8209\u8271\u85AA"], + ["c1a1", "\u8584\u857E\u859C\u8591\u8594\u85AF\u859B\u8587\u85A8\u858A\u8667\u87C0\u87D1\u87B3\u87D2\u87C6\u87AB\u87BB\u87BA\u87C8\u87CB\u893B\u8936\u8944\u8938\u893D\u89AC\u8B0E\u8B17\u8B19\u8B1B\u8B0A\u8B20\u8B1D\u8B04\u8B10\u8C41\u8C3F\u8C73\u8CFA\u8CFD\u8CFC\u8CF8\u8CFB\u8DA8\u8E49\u8E4B\u8E48\u8E4A\u8F44\u8F3E\u8F42\u8F45\u8F3F\u907F\u907D\u9084\u9081\u9082\u9080\u9139\u91A3\u919E\u919C\u934D\u9382\u9328\u9375\u934A\u9365\u934B\u9318\u937E\u936C\u935B\u9370\u935A\u9354\u95CA\u95CB\u95CC\u95C8\u95C6\u96B1\u96B8\u96D6\u971C\u971E\u97A0\u97D3\u9846\u98B6\u9935\u9A01"], + ["c240", "\u99FF\u9BAE\u9BAB\u9BAA\u9BAD\u9D3B\u9D3F\u9E8B\u9ECF\u9EDE\u9EDC\u9EDD\u9EDB\u9F3E\u9F4B\u53E2\u5695\u56AE\u58D9\u58D8\u5B38\u5F5D\u61E3\u6233\u64F4\u64F2\u64FE\u6506\u64FA\u64FB\u64F7\u65B7\u66DC\u6726\u6AB3\u6AAC\u6AC3\u6ABB\u6AB8\u6AC2\u6AAE\u6AAF\u6B5F\u6B78\u6BAF\u7009\u700B\u6FFE\u7006\u6FFA\u7011\u700F\u71FB\u71FC\u71FE\u71F8\u7377\u7375\u74A7\u74BF\u7515\u7656\u7658"], + ["c2a1", "\u7652\u77BD\u77BF\u77BB\u77BC\u790E\u79AE\u7A61\u7A62\u7A60\u7AC4\u7AC5\u7C2B\u7C27\u7C2A\u7C1E\u7C23\u7C21\u7CE7\u7E54\u7E55\u7E5E\u7E5A\u7E61\u7E52\u7E59\u7F48\u7FF9\u7FFB\u8077\u8076\u81CD\u81CF\u820A\u85CF\u85A9\u85CD\u85D0\u85C9\u85B0\u85BA\u85B9\u85A6\u87EF\u87EC\u87F2\u87E0\u8986\u89B2\u89F4\u8B28\u8B39\u8B2C\u8B2B\u8C50\u8D05\u8E59\u8E63\u8E66\u8E64\u8E5F\u8E55\u8EC0\u8F49\u8F4D\u9087\u9083\u9088\u91AB\u91AC\u91D0\u9394\u938A\u9396\u93A2\u93B3\u93AE\u93AC\u93B0\u9398\u939A\u9397\u95D4\u95D6\u95D0\u95D5\u96E2\u96DC\u96D9\u96DB\u96DE\u9724\u97A3\u97A6"], + ["c340", "\u97AD\u97F9\u984D\u984F\u984C\u984E\u9853\u98BA\u993E\u993F\u993D\u992E\u99A5\u9A0E\u9AC1\u9B03\u9B06\u9B4F\u9B4E\u9B4D\u9BCA\u9BC9\u9BFD\u9BC8\u9BC0\u9D51\u9D5D\u9D60\u9EE0\u9F15\u9F2C\u5133\u56A5\u58DE\u58DF\u58E2\u5BF5\u9F90\u5EEC\u61F2\u61F7\u61F6\u61F5\u6500\u650F\u66E0\u66DD\u6AE5\u6ADD\u6ADA\u6AD3\u701B\u701F\u7028\u701A\u701D\u7015\u7018\u7206\u720D\u7258\u72A2\u7378"], + ["c3a1", "\u737A\u74BD\u74CA\u74E3\u7587\u7586\u765F\u7661\u77C7\u7919\u79B1\u7A6B\u7A69\u7C3E\u7C3F\u7C38\u7C3D\u7C37\u7C40\u7E6B\u7E6D\u7E79\u7E69\u7E6A\u7F85\u7E73\u7FB6\u7FB9\u7FB8\u81D8\u85E9\u85DD\u85EA\u85D5\u85E4\u85E5\u85F7\u87FB\u8805\u880D\u87F9\u87FE\u8960\u895F\u8956\u895E\u8B41\u8B5C\u8B58\u8B49\u8B5A\u8B4E\u8B4F\u8B46\u8B59\u8D08\u8D0A\u8E7C\u8E72\u8E87\u8E76\u8E6C\u8E7A\u8E74\u8F54\u8F4E\u8FAD\u908A\u908B\u91B1\u91AE\u93E1\u93D1\u93DF\u93C3\u93C8\u93DC\u93DD\u93D6\u93E2\u93CD\u93D8\u93E4\u93D7\u93E8\u95DC\u96B4\u96E3\u972A\u9727\u9761\u97DC\u97FB\u985E"], + ["c440", "\u9858\u985B\u98BC\u9945\u9949\u9A16\u9A19\u9B0D\u9BE8\u9BE7\u9BD6\u9BDB\u9D89\u9D61\u9D72\u9D6A\u9D6C\u9E92\u9E97\u9E93\u9EB4\u52F8\u56A8\u56B7\u56B6\u56B4\u56BC\u58E4\u5B40\u5B43\u5B7D\u5BF6\u5DC9\u61F8\u61FA\u6518\u6514\u6519\u66E6\u6727\u6AEC\u703E\u7030\u7032\u7210\u737B\u74CF\u7662\u7665\u7926\u792A\u792C\u792B\u7AC7\u7AF6\u7C4C\u7C43\u7C4D\u7CEF\u7CF0\u8FAE\u7E7D\u7E7C"], + ["c4a1", "\u7E82\u7F4C\u8000\u81DA\u8266\u85FB\u85F9\u8611\u85FA\u8606\u860B\u8607\u860A\u8814\u8815\u8964\u89BA\u89F8\u8B70\u8B6C\u8B66\u8B6F\u8B5F\u8B6B\u8D0F\u8D0D\u8E89\u8E81\u8E85\u8E82\u91B4\u91CB\u9418\u9403\u93FD\u95E1\u9730\u98C4\u9952\u9951\u99A8\u9A2B\u9A30\u9A37\u9A35\u9C13\u9C0D\u9E79\u9EB5\u9EE8\u9F2F\u9F5F\u9F63\u9F61\u5137\u5138\u56C1\u56C0\u56C2\u5914\u5C6C\u5DCD\u61FC\u61FE\u651D\u651C\u6595\u66E9\u6AFB\u6B04\u6AFA\u6BB2\u704C\u721B\u72A7\u74D6\u74D4\u7669\u77D3\u7C50\u7E8F\u7E8C\u7FBC\u8617\u862D\u861A\u8823\u8822\u8821\u881F\u896A\u896C\u89BD\u8B74"], + ["c540", "\u8B77\u8B7D\u8D13\u8E8A\u8E8D\u8E8B\u8F5F\u8FAF\u91BA\u942E\u9433\u9435\u943A\u9438\u9432\u942B\u95E2\u9738\u9739\u9732\u97FF\u9867\u9865\u9957\u9A45\u9A43\u9A40\u9A3E\u9ACF\u9B54\u9B51\u9C2D\u9C25\u9DAF\u9DB4\u9DC2\u9DB8\u9E9D\u9EEF\u9F19\u9F5C\u9F66\u9F67\u513C\u513B\u56C8\u56CA\u56C9\u5B7F\u5DD4\u5DD2\u5F4E\u61FF\u6524\u6B0A\u6B61\u7051\u7058\u7380\u74E4\u758A\u766E\u766C"], + ["c5a1", "\u79B3\u7C60\u7C5F\u807E\u807D\u81DF\u8972\u896F\u89FC\u8B80\u8D16\u8D17\u8E91\u8E93\u8F61\u9148\u9444\u9451\u9452\u973D\u973E\u97C3\u97C1\u986B\u9955\u9A55\u9A4D\u9AD2\u9B1A\u9C49\u9C31\u9C3E\u9C3B\u9DD3\u9DD7\u9F34\u9F6C\u9F6A\u9F94\u56CC\u5DD6\u6200\u6523\u652B\u652A\u66EC\u6B10\u74DA\u7ACA\u7C64\u7C63\u7C65\u7E93\u7E96\u7E94\u81E2\u8638\u863F\u8831\u8B8A\u9090\u908F\u9463\u9460\u9464\u9768\u986F\u995C\u9A5A\u9A5B\u9A57\u9AD3\u9AD4\u9AD1\u9C54\u9C57\u9C56\u9DE5\u9E9F\u9EF4\u56D1\u58E9\u652C\u705E\u7671\u7672\u77D7\u7F50\u7F88\u8836\u8839\u8862\u8B93\u8B92"], + ["c640", "\u8B96\u8277\u8D1B\u91C0\u946A\u9742\u9748\u9744\u97C6\u9870\u9A5F\u9B22\u9B58\u9C5F\u9DF9\u9DFA\u9E7C\u9E7D\u9F07\u9F77\u9F72\u5EF3\u6B16\u7063\u7C6C\u7C6E\u883B\u89C0\u8EA1\u91C1\u9472\u9470\u9871\u995E\u9AD6\u9B23\u9ECC\u7064\u77DA\u8B9A\u9477\u97C9\u9A62\u9A65\u7E9C\u8B9C\u8EAA\u91C5\u947D\u947E\u947C\u9C77\u9C78\u9EF7\u8C54\u947F\u9E1A\u7228\u9A6A\u9B31\u9E1B\u9E1E\u7C72"], + ["c940", "\u4E42\u4E5C\u51F5\u531A\u5382\u4E07\u4E0C\u4E47\u4E8D\u56D7\uFA0C\u5C6E\u5F73\u4E0F\u5187\u4E0E\u4E2E\u4E93\u4EC2\u4EC9\u4EC8\u5198\u52FC\u536C\u53B9\u5720\u5903\u592C\u5C10\u5DFF\u65E1\u6BB3\u6BCC\u6C14\u723F\u4E31\u4E3C\u4EE8\u4EDC\u4EE9\u4EE1\u4EDD\u4EDA\u520C\u531C\u534C\u5722\u5723\u5917\u592F\u5B81\u5B84\u5C12\u5C3B\u5C74\u5C73\u5E04\u5E80\u5E82\u5FC9\u6209\u6250\u6C15"], + ["c9a1", "\u6C36\u6C43\u6C3F\u6C3B\u72AE\u72B0\u738A\u79B8\u808A\u961E\u4F0E\u4F18\u4F2C\u4EF5\u4F14\u4EF1\u4F00\u4EF7\u4F08\u4F1D\u4F02\u4F05\u4F22\u4F13\u4F04\u4EF4\u4F12\u51B1\u5213\u5209\u5210\u52A6\u5322\u531F\u534D\u538A\u5407\u56E1\u56DF\u572E\u572A\u5734\u593C\u5980\u597C\u5985\u597B\u597E\u5977\u597F\u5B56\u5C15\u5C25\u5C7C\u5C7A\u5C7B\u5C7E\u5DDF\u5E75\u5E84\u5F02\u5F1A\u5F74\u5FD5\u5FD4\u5FCF\u625C\u625E\u6264\u6261\u6266\u6262\u6259\u6260\u625A\u6265\u65EF\u65EE\u673E\u6739\u6738\u673B\u673A\u673F\u673C\u6733\u6C18\u6C46\u6C52\u6C5C\u6C4F\u6C4A\u6C54\u6C4B"], + ["ca40", "\u6C4C\u7071\u725E\u72B4\u72B5\u738E\u752A\u767F\u7A75\u7F51\u8278\u827C\u8280\u827D\u827F\u864D\u897E\u9099\u9097\u9098\u909B\u9094\u9622\u9624\u9620\u9623\u4F56\u4F3B\u4F62\u4F49\u4F53\u4F64\u4F3E\u4F67\u4F52\u4F5F\u4F41\u4F58\u4F2D\u4F33\u4F3F\u4F61\u518F\u51B9\u521C\u521E\u5221\u52AD\u52AE\u5309\u5363\u5372\u538E\u538F\u5430\u5437\u542A\u5454\u5445\u5419\u541C\u5425\u5418"], + ["caa1", "\u543D\u544F\u5441\u5428\u5424\u5447\u56EE\u56E7\u56E5\u5741\u5745\u574C\u5749\u574B\u5752\u5906\u5940\u59A6\u5998\u59A0\u5997\u598E\u59A2\u5990\u598F\u59A7\u59A1\u5B8E\u5B92\u5C28\u5C2A\u5C8D\u5C8F\u5C88\u5C8B\u5C89\u5C92\u5C8A\u5C86\u5C93\u5C95\u5DE0\u5E0A\u5E0E\u5E8B\u5E89\u5E8C\u5E88\u5E8D\u5F05\u5F1D\u5F78\u5F76\u5FD2\u5FD1\u5FD0\u5FED\u5FE8\u5FEE\u5FF3\u5FE1\u5FE4\u5FE3\u5FFA\u5FEF\u5FF7\u5FFB\u6000\u5FF4\u623A\u6283\u628C\u628E\u628F\u6294\u6287\u6271\u627B\u627A\u6270\u6281\u6288\u6277\u627D\u6272\u6274\u6537\u65F0\u65F4\u65F3\u65F2\u65F5\u6745\u6747"], + ["cb40", "\u6759\u6755\u674C\u6748\u675D\u674D\u675A\u674B\u6BD0\u6C19\u6C1A\u6C78\u6C67\u6C6B\u6C84\u6C8B\u6C8F\u6C71\u6C6F\u6C69\u6C9A\u6C6D\u6C87\u6C95\u6C9C\u6C66\u6C73\u6C65\u6C7B\u6C8E\u7074\u707A\u7263\u72BF\u72BD\u72C3\u72C6\u72C1\u72BA\u72C5\u7395\u7397\u7393\u7394\u7392\u753A\u7539\u7594\u7595\u7681\u793D\u8034\u8095\u8099\u8090\u8092\u809C\u8290\u828F\u8285\u828E\u8291\u8293"], + ["cba1", "\u828A\u8283\u8284\u8C78\u8FC9\u8FBF\u909F\u90A1\u90A5\u909E\u90A7\u90A0\u9630\u9628\u962F\u962D\u4E33\u4F98\u4F7C\u4F85\u4F7D\u4F80\u4F87\u4F76\u4F74\u4F89\u4F84\u4F77\u4F4C\u4F97\u4F6A\u4F9A\u4F79\u4F81\u4F78\u4F90\u4F9C\u4F94\u4F9E\u4F92\u4F82\u4F95\u4F6B\u4F6E\u519E\u51BC\u51BE\u5235\u5232\u5233\u5246\u5231\u52BC\u530A\u530B\u533C\u5392\u5394\u5487\u547F\u5481\u5491\u5482\u5488\u546B\u547A\u547E\u5465\u546C\u5474\u5466\u548D\u546F\u5461\u5460\u5498\u5463\u5467\u5464\u56F7\u56F9\u576F\u5772\u576D\u576B\u5771\u5770\u5776\u5780\u5775\u577B\u5773\u5774\u5762"], + ["cc40", "\u5768\u577D\u590C\u5945\u59B5\u59BA\u59CF\u59CE\u59B2\u59CC\u59C1\u59B6\u59BC\u59C3\u59D6\u59B1\u59BD\u59C0\u59C8\u59B4\u59C7\u5B62\u5B65\u5B93\u5B95\u5C44\u5C47\u5CAE\u5CA4\u5CA0\u5CB5\u5CAF\u5CA8\u5CAC\u5C9F\u5CA3\u5CAD\u5CA2\u5CAA\u5CA7\u5C9D\u5CA5\u5CB6\u5CB0\u5CA6\u5E17\u5E14\u5E19\u5F28\u5F22\u5F23\u5F24\u5F54\u5F82\u5F7E\u5F7D\u5FDE\u5FE5\u602D\u6026\u6019\u6032\u600B"], + ["cca1", "\u6034\u600A\u6017\u6033\u601A\u601E\u602C\u6022\u600D\u6010\u602E\u6013\u6011\u600C\u6009\u601C\u6214\u623D\u62AD\u62B4\u62D1\u62BE\u62AA\u62B6\u62CA\u62AE\u62B3\u62AF\u62BB\u62A9\u62B0\u62B8\u653D\u65A8\u65BB\u6609\u65FC\u6604\u6612\u6608\u65FB\u6603\u660B\u660D\u6605\u65FD\u6611\u6610\u66F6\u670A\u6785\u676C\u678E\u6792\u6776\u677B\u6798\u6786\u6784\u6774\u678D\u678C\u677A\u679F\u6791\u6799\u6783\u677D\u6781\u6778\u6779\u6794\u6B25\u6B80\u6B7E\u6BDE\u6C1D\u6C93\u6CEC\u6CEB\u6CEE\u6CD9\u6CB6\u6CD4\u6CAD\u6CE7\u6CB7\u6CD0\u6CC2\u6CBA\u6CC3\u6CC6\u6CED\u6CF2"], + ["cd40", "\u6CD2\u6CDD\u6CB4\u6C8A\u6C9D\u6C80\u6CDE\u6CC0\u6D30\u6CCD\u6CC7\u6CB0\u6CF9\u6CCF\u6CE9\u6CD1\u7094\u7098\u7085\u7093\u7086\u7084\u7091\u7096\u7082\u709A\u7083\u726A\u72D6\u72CB\u72D8\u72C9\u72DC\u72D2\u72D4\u72DA\u72CC\u72D1\u73A4\u73A1\u73AD\u73A6\u73A2\u73A0\u73AC\u739D\u74DD\u74E8\u753F\u7540\u753E\u758C\u7598\u76AF\u76F3\u76F1\u76F0\u76F5\u77F8\u77FC\u77F9\u77FB\u77FA"], + ["cda1", "\u77F7\u7942\u793F\u79C5\u7A78\u7A7B\u7AFB\u7C75\u7CFD\u8035\u808F\u80AE\u80A3\u80B8\u80B5\u80AD\u8220\u82A0\u82C0\u82AB\u829A\u8298\u829B\u82B5\u82A7\u82AE\u82BC\u829E\u82BA\u82B4\u82A8\u82A1\u82A9\u82C2\u82A4\u82C3\u82B6\u82A2\u8670\u866F\u866D\u866E\u8C56\u8FD2\u8FCB\u8FD3\u8FCD\u8FD6\u8FD5\u8FD7\u90B2\u90B4\u90AF\u90B3\u90B0\u9639\u963D\u963C\u963A\u9643\u4FCD\u4FC5\u4FD3\u4FB2\u4FC9\u4FCB\u4FC1\u4FD4\u4FDC\u4FD9\u4FBB\u4FB3\u4FDB\u4FC7\u4FD6\u4FBA\u4FC0\u4FB9\u4FEC\u5244\u5249\u52C0\u52C2\u533D\u537C\u5397\u5396\u5399\u5398\u54BA\u54A1\u54AD\u54A5\u54CF"], + ["ce40", "\u54C3\u830D\u54B7\u54AE\u54D6\u54B6\u54C5\u54C6\u54A0\u5470\u54BC\u54A2\u54BE\u5472\u54DE\u54B0\u57B5\u579E\u579F\u57A4\u578C\u5797\u579D\u579B\u5794\u5798\u578F\u5799\u57A5\u579A\u5795\u58F4\u590D\u5953\u59E1\u59DE\u59EE\u5A00\u59F1\u59DD\u59FA\u59FD\u59FC\u59F6\u59E4\u59F2\u59F7\u59DB\u59E9\u59F3\u59F5\u59E0\u59FE\u59F4\u59ED\u5BA8\u5C4C\u5CD0\u5CD8\u5CCC\u5CD7\u5CCB\u5CDB"], + ["cea1", "\u5CDE\u5CDA\u5CC9\u5CC7\u5CCA\u5CD6\u5CD3\u5CD4\u5CCF\u5CC8\u5CC6\u5CCE\u5CDF\u5CF8\u5DF9\u5E21\u5E22\u5E23\u5E20\u5E24\u5EB0\u5EA4\u5EA2\u5E9B\u5EA3\u5EA5\u5F07\u5F2E\u5F56\u5F86\u6037\u6039\u6054\u6072\u605E\u6045\u6053\u6047\u6049\u605B\u604C\u6040\u6042\u605F\u6024\u6044\u6058\u6066\u606E\u6242\u6243\u62CF\u630D\u630B\u62F5\u630E\u6303\u62EB\u62F9\u630F\u630C\u62F8\u62F6\u6300\u6313\u6314\u62FA\u6315\u62FB\u62F0\u6541\u6543\u65AA\u65BF\u6636\u6621\u6632\u6635\u661C\u6626\u6622\u6633\u662B\u663A\u661D\u6634\u6639\u662E\u670F\u6710\u67C1\u67F2\u67C8\u67BA"], + ["cf40", "\u67DC\u67BB\u67F8\u67D8\u67C0\u67B7\u67C5\u67EB\u67E4\u67DF\u67B5\u67CD\u67B3\u67F7\u67F6\u67EE\u67E3\u67C2\u67B9\u67CE\u67E7\u67F0\u67B2\u67FC\u67C6\u67ED\u67CC\u67AE\u67E6\u67DB\u67FA\u67C9\u67CA\u67C3\u67EA\u67CB\u6B28\u6B82\u6B84\u6BB6\u6BD6\u6BD8\u6BE0\u6C20\u6C21\u6D28\u6D34\u6D2D\u6D1F\u6D3C\u6D3F\u6D12\u6D0A\u6CDA\u6D33\u6D04\u6D19\u6D3A\u6D1A\u6D11\u6D00\u6D1D\u6D42"], + ["cfa1", "\u6D01\u6D18\u6D37\u6D03\u6D0F\u6D40\u6D07\u6D20\u6D2C\u6D08\u6D22\u6D09\u6D10\u70B7\u709F\u70BE\u70B1\u70B0\u70A1\u70B4\u70B5\u70A9\u7241\u7249\u724A\u726C\u7270\u7273\u726E\u72CA\u72E4\u72E8\u72EB\u72DF\u72EA\u72E6\u72E3\u7385\u73CC\u73C2\u73C8\u73C5\u73B9\u73B6\u73B5\u73B4\u73EB\u73BF\u73C7\u73BE\u73C3\u73C6\u73B8\u73CB\u74EC\u74EE\u752E\u7547\u7548\u75A7\u75AA\u7679\u76C4\u7708\u7703\u7704\u7705\u770A\u76F7\u76FB\u76FA\u77E7\u77E8\u7806\u7811\u7812\u7805\u7810\u780F\u780E\u7809\u7803\u7813\u794A\u794C\u794B\u7945\u7944\u79D5\u79CD\u79CF\u79D6\u79CE\u7A80"], + ["d040", "\u7A7E\u7AD1\u7B00\u7B01\u7C7A\u7C78\u7C79\u7C7F\u7C80\u7C81\u7D03\u7D08\u7D01\u7F58\u7F91\u7F8D\u7FBE\u8007\u800E\u800F\u8014\u8037\u80D8\u80C7\u80E0\u80D1\u80C8\u80C2\u80D0\u80C5\u80E3\u80D9\u80DC\u80CA\u80D5\u80C9\u80CF\u80D7\u80E6\u80CD\u81FF\u8221\u8294\u82D9\u82FE\u82F9\u8307\u82E8\u8300\u82D5\u833A\u82EB\u82D6\u82F4\u82EC\u82E1\u82F2\u82F5\u830C\u82FB\u82F6\u82F0\u82EA"], + ["d0a1", "\u82E4\u82E0\u82FA\u82F3\u82ED\u8677\u8674\u867C\u8673\u8841\u884E\u8867\u886A\u8869\u89D3\u8A04\u8A07\u8D72\u8FE3\u8FE1\u8FEE\u8FE0\u90F1\u90BD\u90BF\u90D5\u90C5\u90BE\u90C7\u90CB\u90C8\u91D4\u91D3\u9654\u964F\u9651\u9653\u964A\u964E\u501E\u5005\u5007\u5013\u5022\u5030\u501B\u4FF5\u4FF4\u5033\u5037\u502C\u4FF6\u4FF7\u5017\u501C\u5020\u5027\u5035\u502F\u5031\u500E\u515A\u5194\u5193\u51CA\u51C4\u51C5\u51C8\u51CE\u5261\u525A\u5252\u525E\u525F\u5255\u5262\u52CD\u530E\u539E\u5526\u54E2\u5517\u5512\u54E7\u54F3\u54E4\u551A\u54FF\u5504\u5508\u54EB\u5511\u5505\u54F1"], + ["d140", "\u550A\u54FB\u54F7\u54F8\u54E0\u550E\u5503\u550B\u5701\u5702\u57CC\u5832\u57D5\u57D2\u57BA\u57C6\u57BD\u57BC\u57B8\u57B6\u57BF\u57C7\u57D0\u57B9\u57C1\u590E\u594A\u5A19\u5A16\u5A2D\u5A2E\u5A15\u5A0F\u5A17\u5A0A\u5A1E\u5A33\u5B6C\u5BA7\u5BAD\u5BAC\u5C03\u5C56\u5C54\u5CEC\u5CFF\u5CEE\u5CF1\u5CF7\u5D00\u5CF9\u5E29\u5E28\u5EA8\u5EAE\u5EAA\u5EAC\u5F33\u5F30\u5F67\u605D\u605A\u6067"], + ["d1a1", "\u6041\u60A2\u6088\u6080\u6092\u6081\u609D\u6083\u6095\u609B\u6097\u6087\u609C\u608E\u6219\u6246\u62F2\u6310\u6356\u632C\u6344\u6345\u6336\u6343\u63E4\u6339\u634B\u634A\u633C\u6329\u6341\u6334\u6358\u6354\u6359\u632D\u6347\u6333\u635A\u6351\u6338\u6357\u6340\u6348\u654A\u6546\u65C6\u65C3\u65C4\u65C2\u664A\u665F\u6647\u6651\u6712\u6713\u681F\u681A\u6849\u6832\u6833\u683B\u684B\u684F\u6816\u6831\u681C\u6835\u682B\u682D\u682F\u684E\u6844\u6834\u681D\u6812\u6814\u6826\u6828\u682E\u684D\u683A\u6825\u6820\u6B2C\u6B2F\u6B2D\u6B31\u6B34\u6B6D\u8082\u6B88\u6BE6\u6BE4"], + ["d240", "\u6BE8\u6BE3\u6BE2\u6BE7\u6C25\u6D7A\u6D63\u6D64\u6D76\u6D0D\u6D61\u6D92\u6D58\u6D62\u6D6D\u6D6F\u6D91\u6D8D\u6DEF\u6D7F\u6D86\u6D5E\u6D67\u6D60\u6D97\u6D70\u6D7C\u6D5F\u6D82\u6D98\u6D2F\u6D68\u6D8B\u6D7E\u6D80\u6D84\u6D16\u6D83\u6D7B\u6D7D\u6D75\u6D90\u70DC\u70D3\u70D1\u70DD\u70CB\u7F39\u70E2\u70D7\u70D2\u70DE\u70E0\u70D4\u70CD\u70C5\u70C6\u70C7\u70DA\u70CE\u70E1\u7242\u7278"], + ["d2a1", "\u7277\u7276\u7300\u72FA\u72F4\u72FE\u72F6\u72F3\u72FB\u7301\u73D3\u73D9\u73E5\u73D6\u73BC\u73E7\u73E3\u73E9\u73DC\u73D2\u73DB\u73D4\u73DD\u73DA\u73D7\u73D8\u73E8\u74DE\u74DF\u74F4\u74F5\u7521\u755B\u755F\u75B0\u75C1\u75BB\u75C4\u75C0\u75BF\u75B6\u75BA\u768A\u76C9\u771D\u771B\u7710\u7713\u7712\u7723\u7711\u7715\u7719\u771A\u7722\u7727\u7823\u782C\u7822\u7835\u782F\u7828\u782E\u782B\u7821\u7829\u7833\u782A\u7831\u7954\u795B\u794F\u795C\u7953\u7952\u7951\u79EB\u79EC\u79E0\u79EE\u79ED\u79EA\u79DC\u79DE\u79DD\u7A86\u7A89\u7A85\u7A8B\u7A8C\u7A8A\u7A87\u7AD8\u7B10"], + ["d340", "\u7B04\u7B13\u7B05\u7B0F\u7B08\u7B0A\u7B0E\u7B09\u7B12\u7C84\u7C91\u7C8A\u7C8C\u7C88\u7C8D\u7C85\u7D1E\u7D1D\u7D11\u7D0E\u7D18\u7D16\u7D13\u7D1F\u7D12\u7D0F\u7D0C\u7F5C\u7F61\u7F5E\u7F60\u7F5D\u7F5B\u7F96\u7F92\u7FC3\u7FC2\u7FC0\u8016\u803E\u8039\u80FA\u80F2\u80F9\u80F5\u8101\u80FB\u8100\u8201\u822F\u8225\u8333\u832D\u8344\u8319\u8351\u8325\u8356\u833F\u8341\u8326\u831C\u8322"], + ["d3a1", "\u8342\u834E\u831B\u832A\u8308\u833C\u834D\u8316\u8324\u8320\u8337\u832F\u8329\u8347\u8345\u834C\u8353\u831E\u832C\u834B\u8327\u8348\u8653\u8652\u86A2\u86A8\u8696\u868D\u8691\u869E\u8687\u8697\u8686\u868B\u869A\u8685\u86A5\u8699\u86A1\u86A7\u8695\u8698\u868E\u869D\u8690\u8694\u8843\u8844\u886D\u8875\u8876\u8872\u8880\u8871\u887F\u886F\u8883\u887E\u8874\u887C\u8A12\u8C47\u8C57\u8C7B\u8CA4\u8CA3\u8D76\u8D78\u8DB5\u8DB7\u8DB6\u8ED1\u8ED3\u8FFE\u8FF5\u9002\u8FFF\u8FFB\u9004\u8FFC\u8FF6\u90D6\u90E0\u90D9\u90DA\u90E3\u90DF\u90E5\u90D8\u90DB\u90D7\u90DC\u90E4\u9150"], + ["d440", "\u914E\u914F\u91D5\u91E2\u91DA\u965C\u965F\u96BC\u98E3\u9ADF\u9B2F\u4E7F\u5070\u506A\u5061\u505E\u5060\u5053\u504B\u505D\u5072\u5048\u504D\u5041\u505B\u504A\u5062\u5015\u5045\u505F\u5069\u506B\u5063\u5064\u5046\u5040\u506E\u5073\u5057\u5051\u51D0\u526B\u526D\u526C\u526E\u52D6\u52D3\u532D\u539C\u5575\u5576\u553C\u554D\u5550\u5534\u552A\u5551\u5562\u5536\u5535\u5530\u5552\u5545"], + ["d4a1", "\u550C\u5532\u5565\u554E\u5539\u5548\u552D\u553B\u5540\u554B\u570A\u5707\u57FB\u5814\u57E2\u57F6\u57DC\u57F4\u5800\u57ED\u57FD\u5808\u57F8\u580B\u57F3\u57CF\u5807\u57EE\u57E3\u57F2\u57E5\u57EC\u57E1\u580E\u57FC\u5810\u57E7\u5801\u580C\u57F1\u57E9\u57F0\u580D\u5804\u595C\u5A60\u5A58\u5A55\u5A67\u5A5E\u5A38\u5A35\u5A6D\u5A50\u5A5F\u5A65\u5A6C\u5A53\u5A64\u5A57\u5A43\u5A5D\u5A52\u5A44\u5A5B\u5A48\u5A8E\u5A3E\u5A4D\u5A39\u5A4C\u5A70\u5A69\u5A47\u5A51\u5A56\u5A42\u5A5C\u5B72\u5B6E\u5BC1\u5BC0\u5C59\u5D1E\u5D0B\u5D1D\u5D1A\u5D20\u5D0C\u5D28\u5D0D\u5D26\u5D25\u5D0F"], + ["d540", "\u5D30\u5D12\u5D23\u5D1F\u5D2E\u5E3E\u5E34\u5EB1\u5EB4\u5EB9\u5EB2\u5EB3\u5F36\u5F38\u5F9B\u5F96\u5F9F\u608A\u6090\u6086\u60BE\u60B0\u60BA\u60D3\u60D4\u60CF\u60E4\u60D9\u60DD\u60C8\u60B1\u60DB\u60B7\u60CA\u60BF\u60C3\u60CD\u60C0\u6332\u6365\u638A\u6382\u637D\u63BD\u639E\u63AD\u639D\u6397\u63AB\u638E\u636F\u6387\u6390\u636E\u63AF\u6375\u639C\u636D\u63AE\u637C\u63A4\u633B\u639F"], + ["d5a1", "\u6378\u6385\u6381\u6391\u638D\u6370\u6553\u65CD\u6665\u6661\u665B\u6659\u665C\u6662\u6718\u6879\u6887\u6890\u689C\u686D\u686E\u68AE\u68AB\u6956\u686F\u68A3\u68AC\u68A9\u6875\u6874\u68B2\u688F\u6877\u6892\u687C\u686B\u6872\u68AA\u6880\u6871\u687E\u689B\u6896\u688B\u68A0\u6889\u68A4\u6878\u687B\u6891\u688C\u688A\u687D\u6B36\u6B33\u6B37\u6B38\u6B91\u6B8F\u6B8D\u6B8E\u6B8C\u6C2A\u6DC0\u6DAB\u6DB4\u6DB3\u6E74\u6DAC\u6DE9\u6DE2\u6DB7\u6DF6\u6DD4\u6E00\u6DC8\u6DE0\u6DDF\u6DD6\u6DBE\u6DE5\u6DDC\u6DDD\u6DDB\u6DF4\u6DCA\u6DBD\u6DED\u6DF0\u6DBA\u6DD5\u6DC2\u6DCF\u6DC9"], + ["d640", "\u6DD0\u6DF2\u6DD3\u6DFD\u6DD7\u6DCD\u6DE3\u6DBB\u70FA\u710D\u70F7\u7117\u70F4\u710C\u70F0\u7104\u70F3\u7110\u70FC\u70FF\u7106\u7113\u7100\u70F8\u70F6\u710B\u7102\u710E\u727E\u727B\u727C\u727F\u731D\u7317\u7307\u7311\u7318\u730A\u7308\u72FF\u730F\u731E\u7388\u73F6\u73F8\u73F5\u7404\u7401\u73FD\u7407\u7400\u73FA\u73FC\u73FF\u740C\u740B\u73F4\u7408\u7564\u7563\u75CE\u75D2\u75CF"], + ["d6a1", "\u75CB\u75CC\u75D1\u75D0\u768F\u7689\u76D3\u7739\u772F\u772D\u7731\u7732\u7734\u7733\u773D\u7725\u773B\u7735\u7848\u7852\u7849\u784D\u784A\u784C\u7826\u7845\u7850\u7964\u7967\u7969\u796A\u7963\u796B\u7961\u79BB\u79FA\u79F8\u79F6\u79F7\u7A8F\u7A94\u7A90\u7B35\u7B47\u7B34\u7B25\u7B30\u7B22\u7B24\u7B33\u7B18\u7B2A\u7B1D\u7B31\u7B2B\u7B2D\u7B2F\u7B32\u7B38\u7B1A\u7B23\u7C94\u7C98\u7C96\u7CA3\u7D35\u7D3D\u7D38\u7D36\u7D3A\u7D45\u7D2C\u7D29\u7D41\u7D47\u7D3E\u7D3F\u7D4A\u7D3B\u7D28\u7F63\u7F95\u7F9C\u7F9D\u7F9B\u7FCA\u7FCB\u7FCD\u7FD0\u7FD1\u7FC7\u7FCF\u7FC9\u801F"], + ["d740", "\u801E\u801B\u8047\u8043\u8048\u8118\u8125\u8119\u811B\u812D\u811F\u812C\u811E\u8121\u8115\u8127\u811D\u8122\u8211\u8238\u8233\u823A\u8234\u8232\u8274\u8390\u83A3\u83A8\u838D\u837A\u8373\u83A4\u8374\u838F\u8381\u8395\u8399\u8375\u8394\u83A9\u837D\u8383\u838C\u839D\u839B\u83AA\u838B\u837E\u83A5\u83AF\u8388\u8397\u83B0\u837F\u83A6\u8387\u83AE\u8376\u839A\u8659\u8656\u86BF\u86B7"], + ["d7a1", "\u86C2\u86C1\u86C5\u86BA\u86B0\u86C8\u86B9\u86B3\u86B8\u86CC\u86B4\u86BB\u86BC\u86C3\u86BD\u86BE\u8852\u8889\u8895\u88A8\u88A2\u88AA\u889A\u8891\u88A1\u889F\u8898\u88A7\u8899\u889B\u8897\u88A4\u88AC\u888C\u8893\u888E\u8982\u89D6\u89D9\u89D5\u8A30\u8A27\u8A2C\u8A1E\u8C39\u8C3B\u8C5C\u8C5D\u8C7D\u8CA5\u8D7D\u8D7B\u8D79\u8DBC\u8DC2\u8DB9\u8DBF\u8DC1\u8ED8\u8EDE\u8EDD\u8EDC\u8ED7\u8EE0\u8EE1\u9024\u900B\u9011\u901C\u900C\u9021\u90EF\u90EA\u90F0\u90F4\u90F2\u90F3\u90D4\u90EB\u90EC\u90E9\u9156\u9158\u915A\u9153\u9155\u91EC\u91F4\u91F1\u91F3\u91F8\u91E4\u91F9\u91EA"], + ["d840", "\u91EB\u91F7\u91E8\u91EE\u957A\u9586\u9588\u967C\u966D\u966B\u9671\u966F\u96BF\u976A\u9804\u98E5\u9997\u509B\u5095\u5094\u509E\u508B\u50A3\u5083\u508C\u508E\u509D\u5068\u509C\u5092\u5082\u5087\u515F\u51D4\u5312\u5311\u53A4\u53A7\u5591\u55A8\u55A5\u55AD\u5577\u5645\u55A2\u5593\u5588\u558F\u55B5\u5581\u55A3\u5592\u55A4\u557D\u558C\u55A6\u557F\u5595\u55A1\u558E\u570C\u5829\u5837"], + ["d8a1", "\u5819\u581E\u5827\u5823\u5828\u57F5\u5848\u5825\u581C\u581B\u5833\u583F\u5836\u582E\u5839\u5838\u582D\u582C\u583B\u5961\u5AAF\u5A94\u5A9F\u5A7A\u5AA2\u5A9E\u5A78\u5AA6\u5A7C\u5AA5\u5AAC\u5A95\u5AAE\u5A37\u5A84\u5A8A\u5A97\u5A83\u5A8B\u5AA9\u5A7B\u5A7D\u5A8C\u5A9C\u5A8F\u5A93\u5A9D\u5BEA\u5BCD\u5BCB\u5BD4\u5BD1\u5BCA\u5BCE\u5C0C\u5C30\u5D37\u5D43\u5D6B\u5D41\u5D4B\u5D3F\u5D35\u5D51\u5D4E\u5D55\u5D33\u5D3A\u5D52\u5D3D\u5D31\u5D59\u5D42\u5D39\u5D49\u5D38\u5D3C\u5D32\u5D36\u5D40\u5D45\u5E44\u5E41\u5F58\u5FA6\u5FA5\u5FAB\u60C9\u60B9\u60CC\u60E2\u60CE\u60C4\u6114"], + ["d940", "\u60F2\u610A\u6116\u6105\u60F5\u6113\u60F8\u60FC\u60FE\u60C1\u6103\u6118\u611D\u6110\u60FF\u6104\u610B\u624A\u6394\u63B1\u63B0\u63CE\u63E5\u63E8\u63EF\u63C3\u649D\u63F3\u63CA\u63E0\u63F6\u63D5\u63F2\u63F5\u6461\u63DF\u63BE\u63DD\u63DC\u63C4\u63D8\u63D3\u63C2\u63C7\u63CC\u63CB\u63C8\u63F0\u63D7\u63D9\u6532\u6567\u656A\u6564\u655C\u6568\u6565\u658C\u659D\u659E\u65AE\u65D0\u65D2"], + ["d9a1", "\u667C\u666C\u667B\u6680\u6671\u6679\u666A\u6672\u6701\u690C\u68D3\u6904\u68DC\u692A\u68EC\u68EA\u68F1\u690F\u68D6\u68F7\u68EB\u68E4\u68F6\u6913\u6910\u68F3\u68E1\u6907\u68CC\u6908\u6970\u68B4\u6911\u68EF\u68C6\u6914\u68F8\u68D0\u68FD\u68FC\u68E8\u690B\u690A\u6917\u68CE\u68C8\u68DD\u68DE\u68E6\u68F4\u68D1\u6906\u68D4\u68E9\u6915\u6925\u68C7\u6B39\u6B3B\u6B3F\u6B3C\u6B94\u6B97\u6B99\u6B95\u6BBD\u6BF0\u6BF2\u6BF3\u6C30\u6DFC\u6E46\u6E47\u6E1F\u6E49\u6E88\u6E3C\u6E3D\u6E45\u6E62\u6E2B\u6E3F\u6E41\u6E5D\u6E73\u6E1C\u6E33\u6E4B\u6E40\u6E51\u6E3B\u6E03\u6E2E\u6E5E"], + ["da40", "\u6E68\u6E5C\u6E61\u6E31\u6E28\u6E60\u6E71\u6E6B\u6E39\u6E22\u6E30\u6E53\u6E65\u6E27\u6E78\u6E64\u6E77\u6E55\u6E79\u6E52\u6E66\u6E35\u6E36\u6E5A\u7120\u711E\u712F\u70FB\u712E\u7131\u7123\u7125\u7122\u7132\u711F\u7128\u713A\u711B\u724B\u725A\u7288\u7289\u7286\u7285\u728B\u7312\u730B\u7330\u7322\u7331\u7333\u7327\u7332\u732D\u7326\u7323\u7335\u730C\u742E\u742C\u7430\u742B\u7416"], + ["daa1", "\u741A\u7421\u742D\u7431\u7424\u7423\u741D\u7429\u7420\u7432\u74FB\u752F\u756F\u756C\u75E7\u75DA\u75E1\u75E6\u75DD\u75DF\u75E4\u75D7\u7695\u7692\u76DA\u7746\u7747\u7744\u774D\u7745\u774A\u774E\u774B\u774C\u77DE\u77EC\u7860\u7864\u7865\u785C\u786D\u7871\u786A\u786E\u7870\u7869\u7868\u785E\u7862\u7974\u7973\u7972\u7970\u7A02\u7A0A\u7A03\u7A0C\u7A04\u7A99\u7AE6\u7AE4\u7B4A\u7B3B\u7B44\u7B48\u7B4C\u7B4E\u7B40\u7B58\u7B45\u7CA2\u7C9E\u7CA8\u7CA1\u7D58\u7D6F\u7D63\u7D53\u7D56\u7D67\u7D6A\u7D4F\u7D6D\u7D5C\u7D6B\u7D52\u7D54\u7D69\u7D51\u7D5F\u7D4E\u7F3E\u7F3F\u7F65"], + ["db40", "\u7F66\u7FA2\u7FA0\u7FA1\u7FD7\u8051\u804F\u8050\u80FE\u80D4\u8143\u814A\u8152\u814F\u8147\u813D\u814D\u813A\u81E6\u81EE\u81F7\u81F8\u81F9\u8204\u823C\u823D\u823F\u8275\u833B\u83CF\u83F9\u8423\u83C0\u83E8\u8412\u83E7\u83E4\u83FC\u83F6\u8410\u83C6\u83C8\u83EB\u83E3\u83BF\u8401\u83DD\u83E5\u83D8\u83FF\u83E1\u83CB\u83CE\u83D6\u83F5\u83C9\u8409\u840F\u83DE\u8411\u8406\u83C2\u83F3"], + ["dba1", "\u83D5\u83FA\u83C7\u83D1\u83EA\u8413\u83C3\u83EC\u83EE\u83C4\u83FB\u83D7\u83E2\u841B\u83DB\u83FE\u86D8\u86E2\u86E6\u86D3\u86E3\u86DA\u86EA\u86DD\u86EB\u86DC\u86EC\u86E9\u86D7\u86E8\u86D1\u8848\u8856\u8855\u88BA\u88D7\u88B9\u88B8\u88C0\u88BE\u88B6\u88BC\u88B7\u88BD\u88B2\u8901\u88C9\u8995\u8998\u8997\u89DD\u89DA\u89DB\u8A4E\u8A4D\u8A39\u8A59\u8A40\u8A57\u8A58\u8A44\u8A45\u8A52\u8A48\u8A51\u8A4A\u8A4C\u8A4F\u8C5F\u8C81\u8C80\u8CBA\u8CBE\u8CB0\u8CB9\u8CB5\u8D84\u8D80\u8D89\u8DD8\u8DD3\u8DCD\u8DC7\u8DD6\u8DDC\u8DCF\u8DD5\u8DD9\u8DC8\u8DD7\u8DC5\u8EEF\u8EF7\u8EFA"], + ["dc40", "\u8EF9\u8EE6\u8EEE\u8EE5\u8EF5\u8EE7\u8EE8\u8EF6\u8EEB\u8EF1\u8EEC\u8EF4\u8EE9\u902D\u9034\u902F\u9106\u912C\u9104\u90FF\u90FC\u9108\u90F9\u90FB\u9101\u9100\u9107\u9105\u9103\u9161\u9164\u915F\u9162\u9160\u9201\u920A\u9225\u9203\u921A\u9226\u920F\u920C\u9200\u9212\u91FF\u91FD\u9206\u9204\u9227\u9202\u921C\u9224\u9219\u9217\u9205\u9216\u957B\u958D\u958C\u9590\u9687\u967E\u9688"], + ["dca1", "\u9689\u9683\u9680\u96C2\u96C8\u96C3\u96F1\u96F0\u976C\u9770\u976E\u9807\u98A9\u98EB\u9CE6\u9EF9\u4E83\u4E84\u4EB6\u50BD\u50BF\u50C6\u50AE\u50C4\u50CA\u50B4\u50C8\u50C2\u50B0\u50C1\u50BA\u50B1\u50CB\u50C9\u50B6\u50B8\u51D7\u527A\u5278\u527B\u527C\u55C3\u55DB\u55CC\u55D0\u55CB\u55CA\u55DD\u55C0\u55D4\u55C4\u55E9\u55BF\u55D2\u558D\u55CF\u55D5\u55E2\u55D6\u55C8\u55F2\u55CD\u55D9\u55C2\u5714\u5853\u5868\u5864\u584F\u584D\u5849\u586F\u5855\u584E\u585D\u5859\u5865\u585B\u583D\u5863\u5871\u58FC\u5AC7\u5AC4\u5ACB\u5ABA\u5AB8\u5AB1\u5AB5\u5AB0\u5ABF\u5AC8\u5ABB\u5AC6"], + ["dd40", "\u5AB7\u5AC0\u5ACA\u5AB4\u5AB6\u5ACD\u5AB9\u5A90\u5BD6\u5BD8\u5BD9\u5C1F\u5C33\u5D71\u5D63\u5D4A\u5D65\u5D72\u5D6C\u5D5E\u5D68\u5D67\u5D62\u5DF0\u5E4F\u5E4E\u5E4A\u5E4D\u5E4B\u5EC5\u5ECC\u5EC6\u5ECB\u5EC7\u5F40\u5FAF\u5FAD\u60F7\u6149\u614A\u612B\u6145\u6136\u6132\u612E\u6146\u612F\u614F\u6129\u6140\u6220\u9168\u6223\u6225\u6224\u63C5\u63F1\u63EB\u6410\u6412\u6409\u6420\u6424"], + ["dda1", "\u6433\u6443\u641F\u6415\u6418\u6439\u6437\u6422\u6423\u640C\u6426\u6430\u6428\u6441\u6435\u642F\u640A\u641A\u6440\u6425\u6427\u640B\u63E7\u641B\u642E\u6421\u640E\u656F\u6592\u65D3\u6686\u668C\u6695\u6690\u668B\u668A\u6699\u6694\u6678\u6720\u6966\u695F\u6938\u694E\u6962\u6971\u693F\u6945\u696A\u6939\u6942\u6957\u6959\u697A\u6948\u6949\u6935\u696C\u6933\u693D\u6965\u68F0\u6978\u6934\u6969\u6940\u696F\u6944\u6976\u6958\u6941\u6974\u694C\u693B\u694B\u6937\u695C\u694F\u6951\u6932\u6952\u692F\u697B\u693C\u6B46\u6B45\u6B43\u6B42\u6B48\u6B41\u6B9B\uFA0D\u6BFB\u6BFC"], + ["de40", "\u6BF9\u6BF7\u6BF8\u6E9B\u6ED6\u6EC8\u6E8F\u6EC0\u6E9F\u6E93\u6E94\u6EA0\u6EB1\u6EB9\u6EC6\u6ED2\u6EBD\u6EC1\u6E9E\u6EC9\u6EB7\u6EB0\u6ECD\u6EA6\u6ECF\u6EB2\u6EBE\u6EC3\u6EDC\u6ED8\u6E99\u6E92\u6E8E\u6E8D\u6EA4\u6EA1\u6EBF\u6EB3\u6ED0\u6ECA\u6E97\u6EAE\u6EA3\u7147\u7154\u7152\u7163\u7160\u7141\u715D\u7162\u7172\u7178\u716A\u7161\u7142\u7158\u7143\u714B\u7170\u715F\u7150\u7153"], + ["dea1", "\u7144\u714D\u715A\u724F\u728D\u728C\u7291\u7290\u728E\u733C\u7342\u733B\u733A\u7340\u734A\u7349\u7444\u744A\u744B\u7452\u7451\u7457\u7440\u744F\u7450\u744E\u7442\u7446\u744D\u7454\u74E1\u74FF\u74FE\u74FD\u751D\u7579\u7577\u6983\u75EF\u760F\u7603\u75F7\u75FE\u75FC\u75F9\u75F8\u7610\u75FB\u75F6\u75ED\u75F5\u75FD\u7699\u76B5\u76DD\u7755\u775F\u7760\u7752\u7756\u775A\u7769\u7767\u7754\u7759\u776D\u77E0\u7887\u789A\u7894\u788F\u7884\u7895\u7885\u7886\u78A1\u7883\u7879\u7899\u7880\u7896\u787B\u797C\u7982\u797D\u7979\u7A11\u7A18\u7A19\u7A12\u7A17\u7A15\u7A22\u7A13"], + ["df40", "\u7A1B\u7A10\u7AA3\u7AA2\u7A9E\u7AEB\u7B66\u7B64\u7B6D\u7B74\u7B69\u7B72\u7B65\u7B73\u7B71\u7B70\u7B61\u7B78\u7B76\u7B63\u7CB2\u7CB4\u7CAF\u7D88\u7D86\u7D80\u7D8D\u7D7F\u7D85\u7D7A\u7D8E\u7D7B\u7D83\u7D7C\u7D8C\u7D94\u7D84\u7D7D\u7D92\u7F6D\u7F6B\u7F67\u7F68\u7F6C\u7FA6\u7FA5\u7FA7\u7FDB\u7FDC\u8021\u8164\u8160\u8177\u815C\u8169\u815B\u8162\u8172\u6721\u815E\u8176\u8167\u816F"], + ["dfa1", "\u8144\u8161\u821D\u8249\u8244\u8240\u8242\u8245\u84F1\u843F\u8456\u8476\u8479\u848F\u848D\u8465\u8451\u8440\u8486\u8467\u8430\u844D\u847D\u845A\u8459\u8474\u8473\u845D\u8507\u845E\u8437\u843A\u8434\u847A\u8443\u8478\u8432\u8445\u8429\u83D9\u844B\u842F\u8442\u842D\u845F\u8470\u8439\u844E\u844C\u8452\u846F\u84C5\u848E\u843B\u8447\u8436\u8433\u8468\u847E\u8444\u842B\u8460\u8454\u846E\u8450\u870B\u8704\u86F7\u870C\u86FA\u86D6\u86F5\u874D\u86F8\u870E\u8709\u8701\u86F6\u870D\u8705\u88D6\u88CB\u88CD\u88CE\u88DE\u88DB\u88DA\u88CC\u88D0\u8985\u899B\u89DF\u89E5\u89E4"], + ["e040", "\u89E1\u89E0\u89E2\u89DC\u89E6\u8A76\u8A86\u8A7F\u8A61\u8A3F\u8A77\u8A82\u8A84\u8A75\u8A83\u8A81\u8A74\u8A7A\u8C3C\u8C4B\u8C4A\u8C65\u8C64\u8C66\u8C86\u8C84\u8C85\u8CCC\u8D68\u8D69\u8D91\u8D8C\u8D8E\u8D8F\u8D8D\u8D93\u8D94\u8D90\u8D92\u8DF0\u8DE0\u8DEC\u8DF1\u8DEE\u8DD0\u8DE9\u8DE3\u8DE2\u8DE7\u8DF2\u8DEB\u8DF4\u8F06\u8EFF\u8F01\u8F00\u8F05\u8F07\u8F08\u8F02\u8F0B\u9052\u903F"], + ["e0a1", "\u9044\u9049\u903D\u9110\u910D\u910F\u9111\u9116\u9114\u910B\u910E\u916E\u916F\u9248\u9252\u9230\u923A\u9266\u9233\u9265\u925E\u9283\u922E\u924A\u9246\u926D\u926C\u924F\u9260\u9267\u926F\u9236\u9261\u9270\u9231\u9254\u9263\u9250\u9272\u924E\u9253\u924C\u9256\u9232\u959F\u959C\u959E\u959B\u9692\u9693\u9691\u9697\u96CE\u96FA\u96FD\u96F8\u96F5\u9773\u9777\u9778\u9772\u980F\u980D\u980E\u98AC\u98F6\u98F9\u99AF\u99B2\u99B0\u99B5\u9AAD\u9AAB\u9B5B\u9CEA\u9CED\u9CE7\u9E80\u9EFD\u50E6\u50D4\u50D7\u50E8\u50F3\u50DB\u50EA\u50DD\u50E4\u50D3\u50EC\u50F0\u50EF\u50E3\u50E0"], + ["e140", "\u51D8\u5280\u5281\u52E9\u52EB\u5330\u53AC\u5627\u5615\u560C\u5612\u55FC\u560F\u561C\u5601\u5613\u5602\u55FA\u561D\u5604\u55FF\u55F9\u5889\u587C\u5890\u5898\u5886\u5881\u587F\u5874\u588B\u587A\u5887\u5891\u588E\u5876\u5882\u5888\u587B\u5894\u588F\u58FE\u596B\u5ADC\u5AEE\u5AE5\u5AD5\u5AEA\u5ADA\u5AED\u5AEB\u5AF3\u5AE2\u5AE0\u5ADB\u5AEC\u5ADE\u5ADD\u5AD9\u5AE8\u5ADF\u5B77\u5BE0"], + ["e1a1", "\u5BE3\u5C63\u5D82\u5D80\u5D7D\u5D86\u5D7A\u5D81\u5D77\u5D8A\u5D89\u5D88\u5D7E\u5D7C\u5D8D\u5D79\u5D7F\u5E58\u5E59\u5E53\u5ED8\u5ED1\u5ED7\u5ECE\u5EDC\u5ED5\u5ED9\u5ED2\u5ED4\u5F44\u5F43\u5F6F\u5FB6\u612C\u6128\u6141\u615E\u6171\u6173\u6152\u6153\u6172\u616C\u6180\u6174\u6154\u617A\u615B\u6165\u613B\u616A\u6161\u6156\u6229\u6227\u622B\u642B\u644D\u645B\u645D\u6474\u6476\u6472\u6473\u647D\u6475\u6466\u64A6\u644E\u6482\u645E\u645C\u644B\u6453\u6460\u6450\u647F\u643F\u646C\u646B\u6459\u6465\u6477\u6573\u65A0\u66A1\u66A0\u669F\u6705\u6704\u6722\u69B1\u69B6\u69C9"], + ["e240", "\u69A0\u69CE\u6996\u69B0\u69AC\u69BC\u6991\u6999\u698E\u69A7\u698D\u69A9\u69BE\u69AF\u69BF\u69C4\u69BD\u69A4\u69D4\u69B9\u69CA\u699A\u69CF\u69B3\u6993\u69AA\u69A1\u699E\u69D9\u6997\u6990\u69C2\u69B5\u69A5\u69C6\u6B4A\u6B4D\u6B4B\u6B9E\u6B9F\u6BA0\u6BC3\u6BC4\u6BFE\u6ECE\u6EF5\u6EF1\u6F03\u6F25\u6EF8\u6F37\u6EFB\u6F2E\u6F09\u6F4E\u6F19\u6F1A\u6F27\u6F18\u6F3B\u6F12\u6EED\u6F0A"], + ["e2a1", "\u6F36\u6F73\u6EF9\u6EEE\u6F2D\u6F40\u6F30\u6F3C\u6F35\u6EEB\u6F07\u6F0E\u6F43\u6F05\u6EFD\u6EF6\u6F39\u6F1C\u6EFC\u6F3A\u6F1F\u6F0D\u6F1E\u6F08\u6F21\u7187\u7190\u7189\u7180\u7185\u7182\u718F\u717B\u7186\u7181\u7197\u7244\u7253\u7297\u7295\u7293\u7343\u734D\u7351\u734C\u7462\u7473\u7471\u7475\u7472\u7467\u746E\u7500\u7502\u7503\u757D\u7590\u7616\u7608\u760C\u7615\u7611\u760A\u7614\u76B8\u7781\u777C\u7785\u7782\u776E\u7780\u776F\u777E\u7783\u78B2\u78AA\u78B4\u78AD\u78A8\u787E\u78AB\u789E\u78A5\u78A0\u78AC\u78A2\u78A4\u7998\u798A\u798B\u7996\u7995\u7994\u7993"], + ["e340", "\u7997\u7988\u7992\u7990\u7A2B\u7A4A\u7A30\u7A2F\u7A28\u7A26\u7AA8\u7AAB\u7AAC\u7AEE\u7B88\u7B9C\u7B8A\u7B91\u7B90\u7B96\u7B8D\u7B8C\u7B9B\u7B8E\u7B85\u7B98\u5284\u7B99\u7BA4\u7B82\u7CBB\u7CBF\u7CBC\u7CBA\u7DA7\u7DB7\u7DC2\u7DA3\u7DAA\u7DC1\u7DC0\u7DC5\u7D9D\u7DCE\u7DC4\u7DC6\u7DCB\u7DCC\u7DAF\u7DB9\u7D96\u7DBC\u7D9F\u7DA6\u7DAE\u7DA9\u7DA1\u7DC9\u7F73\u7FE2\u7FE3\u7FE5\u7FDE"], + ["e3a1", "\u8024\u805D\u805C\u8189\u8186\u8183\u8187\u818D\u818C\u818B\u8215\u8497\u84A4\u84A1\u849F\u84BA\u84CE\u84C2\u84AC\u84AE\u84AB\u84B9\u84B4\u84C1\u84CD\u84AA\u849A\u84B1\u84D0\u849D\u84A7\u84BB\u84A2\u8494\u84C7\u84CC\u849B\u84A9\u84AF\u84A8\u84D6\u8498\u84B6\u84CF\u84A0\u84D7\u84D4\u84D2\u84DB\u84B0\u8491\u8661\u8733\u8723\u8728\u876B\u8740\u872E\u871E\u8721\u8719\u871B\u8743\u872C\u8741\u873E\u8746\u8720\u8732\u872A\u872D\u873C\u8712\u873A\u8731\u8735\u8742\u8726\u8727\u8738\u8724\u871A\u8730\u8711\u88F7\u88E7\u88F1\u88F2\u88FA\u88FE\u88EE\u88FC\u88F6\u88FB"], + ["e440", "\u88F0\u88EC\u88EB\u899D\u89A1\u899F\u899E\u89E9\u89EB\u89E8\u8AAB\u8A99\u8A8B\u8A92\u8A8F\u8A96\u8C3D\u8C68\u8C69\u8CD5\u8CCF\u8CD7\u8D96\u8E09\u8E02\u8DFF\u8E0D\u8DFD\u8E0A\u8E03\u8E07\u8E06\u8E05\u8DFE\u8E00\u8E04\u8F10\u8F11\u8F0E\u8F0D\u9123\u911C\u9120\u9122\u911F\u911D\u911A\u9124\u9121\u911B\u917A\u9172\u9179\u9173\u92A5\u92A4\u9276\u929B\u927A\u92A0\u9294\u92AA\u928D"], + ["e4a1", "\u92A6\u929A\u92AB\u9279\u9297\u927F\u92A3\u92EE\u928E\u9282\u9295\u92A2\u927D\u9288\u92A1\u928A\u9286\u928C\u9299\u92A7\u927E\u9287\u92A9\u929D\u928B\u922D\u969E\u96A1\u96FF\u9758\u977D\u977A\u977E\u9783\u9780\u9782\u977B\u9784\u9781\u977F\u97CE\u97CD\u9816\u98AD\u98AE\u9902\u9900\u9907\u999D\u999C\u99C3\u99B9\u99BB\u99BA\u99C2\u99BD\u99C7\u9AB1\u9AE3\u9AE7\u9B3E\u9B3F\u9B60\u9B61\u9B5F\u9CF1\u9CF2\u9CF5\u9EA7\u50FF\u5103\u5130\u50F8\u5106\u5107\u50F6\u50FE\u510B\u510C\u50FD\u510A\u528B\u528C\u52F1\u52EF\u5648\u5642\u564C\u5635\u5641\u564A\u5649\u5646\u5658"], + ["e540", "\u565A\u5640\u5633\u563D\u562C\u563E\u5638\u562A\u563A\u571A\u58AB\u589D\u58B1\u58A0\u58A3\u58AF\u58AC\u58A5\u58A1\u58FF\u5AFF\u5AF4\u5AFD\u5AF7\u5AF6\u5B03\u5AF8\u5B02\u5AF9\u5B01\u5B07\u5B05\u5B0F\u5C67\u5D99\u5D97\u5D9F\u5D92\u5DA2\u5D93\u5D95\u5DA0\u5D9C\u5DA1\u5D9A\u5D9E\u5E69\u5E5D\u5E60\u5E5C\u7DF3\u5EDB\u5EDE\u5EE1\u5F49\u5FB2\u618B\u6183\u6179\u61B1\u61B0\u61A2\u6189"], + ["e5a1", "\u619B\u6193\u61AF\u61AD\u619F\u6192\u61AA\u61A1\u618D\u6166\u61B3\u622D\u646E\u6470\u6496\u64A0\u6485\u6497\u649C\u648F\u648B\u648A\u648C\u64A3\u649F\u6468\u64B1\u6498\u6576\u657A\u6579\u657B\u65B2\u65B3\u66B5\u66B0\u66A9\u66B2\u66B7\u66AA\u66AF\u6A00\u6A06\u6A17\u69E5\u69F8\u6A15\u69F1\u69E4\u6A20\u69FF\u69EC\u69E2\u6A1B\u6A1D\u69FE\u6A27\u69F2\u69EE\u6A14\u69F7\u69E7\u6A40\u6A08\u69E6\u69FB\u6A0D\u69FC\u69EB\u6A09\u6A04\u6A18\u6A25\u6A0F\u69F6\u6A26\u6A07\u69F4\u6A16\u6B51\u6BA5\u6BA3\u6BA2\u6BA6\u6C01\u6C00\u6BFF\u6C02\u6F41\u6F26\u6F7E\u6F87\u6FC6\u6F92"], + ["e640", "\u6F8D\u6F89\u6F8C\u6F62\u6F4F\u6F85\u6F5A\u6F96\u6F76\u6F6C\u6F82\u6F55\u6F72\u6F52\u6F50\u6F57\u6F94\u6F93\u6F5D\u6F00\u6F61\u6F6B\u6F7D\u6F67\u6F90\u6F53\u6F8B\u6F69\u6F7F\u6F95\u6F63\u6F77\u6F6A\u6F7B\u71B2\u71AF\u719B\u71B0\u71A0\u719A\u71A9\u71B5\u719D\u71A5\u719E\u71A4\u71A1\u71AA\u719C\u71A7\u71B3\u7298\u729A\u7358\u7352\u735E\u735F\u7360\u735D\u735B\u7361\u735A\u7359"], + ["e6a1", "\u7362\u7487\u7489\u748A\u7486\u7481\u747D\u7485\u7488\u747C\u7479\u7508\u7507\u757E\u7625\u761E\u7619\u761D\u761C\u7623\u761A\u7628\u761B\u769C\u769D\u769E\u769B\u778D\u778F\u7789\u7788\u78CD\u78BB\u78CF\u78CC\u78D1\u78CE\u78D4\u78C8\u78C3\u78C4\u78C9\u799A\u79A1\u79A0\u799C\u79A2\u799B\u6B76\u7A39\u7AB2\u7AB4\u7AB3\u7BB7\u7BCB\u7BBE\u7BAC\u7BCE\u7BAF\u7BB9\u7BCA\u7BB5\u7CC5\u7CC8\u7CCC\u7CCB\u7DF7\u7DDB\u7DEA\u7DE7\u7DD7\u7DE1\u7E03\u7DFA\u7DE6\u7DF6\u7DF1\u7DF0\u7DEE\u7DDF\u7F76\u7FAC\u7FB0\u7FAD\u7FED\u7FEB\u7FEA\u7FEC\u7FE6\u7FE8\u8064\u8067\u81A3\u819F"], + ["e740", "\u819E\u8195\u81A2\u8199\u8197\u8216\u824F\u8253\u8252\u8250\u824E\u8251\u8524\u853B\u850F\u8500\u8529\u850E\u8509\u850D\u851F\u850A\u8527\u851C\u84FB\u852B\u84FA\u8508\u850C\u84F4\u852A\u84F2\u8515\u84F7\u84EB\u84F3\u84FC\u8512\u84EA\u84E9\u8516\u84FE\u8528\u851D\u852E\u8502\u84FD\u851E\u84F6\u8531\u8526\u84E7\u84E8\u84F0\u84EF\u84F9\u8518\u8520\u8530\u850B\u8519\u852F\u8662"], + ["e7a1", "\u8756\u8763\u8764\u8777\u87E1\u8773\u8758\u8754\u875B\u8752\u8761\u875A\u8751\u875E\u876D\u876A\u8750\u874E\u875F\u875D\u876F\u876C\u877A\u876E\u875C\u8765\u874F\u877B\u8775\u8762\u8767\u8769\u885A\u8905\u890C\u8914\u890B\u8917\u8918\u8919\u8906\u8916\u8911\u890E\u8909\u89A2\u89A4\u89A3\u89ED\u89F0\u89EC\u8ACF\u8AC6\u8AB8\u8AD3\u8AD1\u8AD4\u8AD5\u8ABB\u8AD7\u8ABE\u8AC0\u8AC5\u8AD8\u8AC3\u8ABA\u8ABD\u8AD9\u8C3E\u8C4D\u8C8F\u8CE5\u8CDF\u8CD9\u8CE8\u8CDA\u8CDD\u8CE7\u8DA0\u8D9C\u8DA1\u8D9B\u8E20\u8E23\u8E25\u8E24\u8E2E\u8E15\u8E1B\u8E16\u8E11\u8E19\u8E26\u8E27"], + ["e840", "\u8E14\u8E12\u8E18\u8E13\u8E1C\u8E17\u8E1A\u8F2C\u8F24\u8F18\u8F1A\u8F20\u8F23\u8F16\u8F17\u9073\u9070\u906F\u9067\u906B\u912F\u912B\u9129\u912A\u9132\u9126\u912E\u9185\u9186\u918A\u9181\u9182\u9184\u9180\u92D0\u92C3\u92C4\u92C0\u92D9\u92B6\u92CF\u92F1\u92DF\u92D8\u92E9\u92D7\u92DD\u92CC\u92EF\u92C2\u92E8\u92CA\u92C8\u92CE\u92E6\u92CD\u92D5\u92C9\u92E0\u92DE\u92E7\u92D1\u92D3"], + ["e8a1", "\u92B5\u92E1\u92C6\u92B4\u957C\u95AC\u95AB\u95AE\u95B0\u96A4\u96A2\u96D3\u9705\u9708\u9702\u975A\u978A\u978E\u9788\u97D0\u97CF\u981E\u981D\u9826\u9829\u9828\u9820\u981B\u9827\u98B2\u9908\u98FA\u9911\u9914\u9916\u9917\u9915\u99DC\u99CD\u99CF\u99D3\u99D4\u99CE\u99C9\u99D6\u99D8\u99CB\u99D7\u99CC\u9AB3\u9AEC\u9AEB\u9AF3\u9AF2\u9AF1\u9B46\u9B43\u9B67\u9B74\u9B71\u9B66\u9B76\u9B75\u9B70\u9B68\u9B64\u9B6C\u9CFC\u9CFA\u9CFD\u9CFF\u9CF7\u9D07\u9D00\u9CF9\u9CFB\u9D08\u9D05\u9D04\u9E83\u9ED3\u9F0F\u9F10\u511C\u5113\u5117\u511A\u5111\u51DE\u5334\u53E1\u5670\u5660\u566E"], + ["e940", "\u5673\u5666\u5663\u566D\u5672\u565E\u5677\u571C\u571B\u58C8\u58BD\u58C9\u58BF\u58BA\u58C2\u58BC\u58C6\u5B17\u5B19\u5B1B\u5B21\u5B14\u5B13\u5B10\u5B16\u5B28\u5B1A\u5B20\u5B1E\u5BEF\u5DAC\u5DB1\u5DA9\u5DA7\u5DB5\u5DB0\u5DAE\u5DAA\u5DA8\u5DB2\u5DAD\u5DAF\u5DB4\u5E67\u5E68\u5E66\u5E6F\u5EE9\u5EE7\u5EE6\u5EE8\u5EE5\u5F4B\u5FBC\u619D\u61A8\u6196\u61C5\u61B4\u61C6\u61C1\u61CC\u61BA"], + ["e9a1", "\u61BF\u61B8\u618C\u64D7\u64D6\u64D0\u64CF\u64C9\u64BD\u6489\u64C3\u64DB\u64F3\u64D9\u6533\u657F\u657C\u65A2\u66C8\u66BE\u66C0\u66CA\u66CB\u66CF\u66BD\u66BB\u66BA\u66CC\u6723\u6A34\u6A66\u6A49\u6A67\u6A32\u6A68\u6A3E\u6A5D\u6A6D\u6A76\u6A5B\u6A51\u6A28\u6A5A\u6A3B\u6A3F\u6A41\u6A6A\u6A64\u6A50\u6A4F\u6A54\u6A6F\u6A69\u6A60\u6A3C\u6A5E\u6A56\u6A55\u6A4D\u6A4E\u6A46\u6B55\u6B54\u6B56\u6BA7\u6BAA\u6BAB\u6BC8\u6BC7\u6C04\u6C03\u6C06\u6FAD\u6FCB\u6FA3\u6FC7\u6FBC\u6FCE\u6FC8\u6F5E\u6FC4\u6FBD\u6F9E\u6FCA\u6FA8\u7004\u6FA5\u6FAE\u6FBA\u6FAC\u6FAA\u6FCF\u6FBF\u6FB8"], + ["ea40", "\u6FA2\u6FC9\u6FAB\u6FCD\u6FAF\u6FB2\u6FB0\u71C5\u71C2\u71BF\u71B8\u71D6\u71C0\u71C1\u71CB\u71D4\u71CA\u71C7\u71CF\u71BD\u71D8\u71BC\u71C6\u71DA\u71DB\u729D\u729E\u7369\u7366\u7367\u736C\u7365\u736B\u736A\u747F\u749A\u74A0\u7494\u7492\u7495\u74A1\u750B\u7580\u762F\u762D\u7631\u763D\u7633\u763C\u7635\u7632\u7630\u76BB\u76E6\u779A\u779D\u77A1\u779C\u779B\u77A2\u77A3\u7795\u7799"], + ["eaa1", "\u7797\u78DD\u78E9\u78E5\u78EA\u78DE\u78E3\u78DB\u78E1\u78E2\u78ED\u78DF\u78E0\u79A4\u7A44\u7A48\u7A47\u7AB6\u7AB8\u7AB5\u7AB1\u7AB7\u7BDE\u7BE3\u7BE7\u7BDD\u7BD5\u7BE5\u7BDA\u7BE8\u7BF9\u7BD4\u7BEA\u7BE2\u7BDC\u7BEB\u7BD8\u7BDF\u7CD2\u7CD4\u7CD7\u7CD0\u7CD1\u7E12\u7E21\u7E17\u7E0C\u7E1F\u7E20\u7E13\u7E0E\u7E1C\u7E15\u7E1A\u7E22\u7E0B\u7E0F\u7E16\u7E0D\u7E14\u7E25\u7E24\u7F43\u7F7B\u7F7C\u7F7A\u7FB1\u7FEF\u802A\u8029\u806C\u81B1\u81A6\u81AE\u81B9\u81B5\u81AB\u81B0\u81AC\u81B4\u81B2\u81B7\u81A7\u81F2\u8255\u8256\u8257\u8556\u8545\u856B\u854D\u8553\u8561\u8558"], + ["eb40", "\u8540\u8546\u8564\u8541\u8562\u8544\u8551\u8547\u8563\u853E\u855B\u8571\u854E\u856E\u8575\u8555\u8567\u8560\u858C\u8566\u855D\u8554\u8565\u856C\u8663\u8665\u8664\u879B\u878F\u8797\u8793\u8792\u8788\u8781\u8796\u8798\u8779\u8787\u87A3\u8785\u8790\u8791\u879D\u8784\u8794\u879C\u879A\u8789\u891E\u8926\u8930\u892D\u892E\u8927\u8931\u8922\u8929\u8923\u892F\u892C\u891F\u89F1\u8AE0"], + ["eba1", "\u8AE2\u8AF2\u8AF4\u8AF5\u8ADD\u8B14\u8AE4\u8ADF\u8AF0\u8AC8\u8ADE\u8AE1\u8AE8\u8AFF\u8AEF\u8AFB\u8C91\u8C92\u8C90\u8CF5\u8CEE\u8CF1\u8CF0\u8CF3\u8D6C\u8D6E\u8DA5\u8DA7\u8E33\u8E3E\u8E38\u8E40\u8E45\u8E36\u8E3C\u8E3D\u8E41\u8E30\u8E3F\u8EBD\u8F36\u8F2E\u8F35\u8F32\u8F39\u8F37\u8F34\u9076\u9079\u907B\u9086\u90FA\u9133\u9135\u9136\u9193\u9190\u9191\u918D\u918F\u9327\u931E\u9308\u931F\u9306\u930F\u937A\u9338\u933C\u931B\u9323\u9312\u9301\u9346\u932D\u930E\u930D\u92CB\u931D\u92FA\u9325\u9313\u92F9\u92F7\u9334\u9302\u9324\u92FF\u9329\u9339\u9335\u932A\u9314\u930C"], + ["ec40", "\u930B\u92FE\u9309\u9300\u92FB\u9316\u95BC\u95CD\u95BE\u95B9\u95BA\u95B6\u95BF\u95B5\u95BD\u96A9\u96D4\u970B\u9712\u9710\u9799\u9797\u9794\u97F0\u97F8\u9835\u982F\u9832\u9924\u991F\u9927\u9929\u999E\u99EE\u99EC\u99E5\u99E4\u99F0\u99E3\u99EA\u99E9\u99E7\u9AB9\u9ABF\u9AB4\u9ABB\u9AF6\u9AFA\u9AF9\u9AF7\u9B33\u9B80\u9B85\u9B87\u9B7C\u9B7E\u9B7B\u9B82\u9B93\u9B92\u9B90\u9B7A\u9B95"], + ["eca1", "\u9B7D\u9B88\u9D25\u9D17\u9D20\u9D1E\u9D14\u9D29\u9D1D\u9D18\u9D22\u9D10\u9D19\u9D1F\u9E88\u9E86\u9E87\u9EAE\u9EAD\u9ED5\u9ED6\u9EFA\u9F12\u9F3D\u5126\u5125\u5122\u5124\u5120\u5129\u52F4\u5693\u568C\u568D\u5686\u5684\u5683\u567E\u5682\u567F\u5681\u58D6\u58D4\u58CF\u58D2\u5B2D\u5B25\u5B32\u5B23\u5B2C\u5B27\u5B26\u5B2F\u5B2E\u5B7B\u5BF1\u5BF2\u5DB7\u5E6C\u5E6A\u5FBE\u5FBB\u61C3\u61B5\u61BC\u61E7\u61E0\u61E5\u61E4\u61E8\u61DE\u64EF\u64E9\u64E3\u64EB\u64E4\u64E8\u6581\u6580\u65B6\u65DA\u66D2\u6A8D\u6A96\u6A81\u6AA5\u6A89\u6A9F\u6A9B\u6AA1\u6A9E\u6A87\u6A93\u6A8E"], + ["ed40", "\u6A95\u6A83\u6AA8\u6AA4\u6A91\u6A7F\u6AA6\u6A9A\u6A85\u6A8C\u6A92\u6B5B\u6BAD\u6C09\u6FCC\u6FA9\u6FF4\u6FD4\u6FE3\u6FDC\u6FED\u6FE7\u6FE6\u6FDE\u6FF2\u6FDD\u6FE2\u6FE8\u71E1\u71F1\u71E8\u71F2\u71E4\u71F0\u71E2\u7373\u736E\u736F\u7497\u74B2\u74AB\u7490\u74AA\u74AD\u74B1\u74A5\u74AF\u7510\u7511\u7512\u750F\u7584\u7643\u7648\u7649\u7647\u76A4\u76E9\u77B5\u77AB\u77B2\u77B7\u77B6"], + ["eda1", "\u77B4\u77B1\u77A8\u77F0\u78F3\u78FD\u7902\u78FB\u78FC\u78F2\u7905\u78F9\u78FE\u7904\u79AB\u79A8\u7A5C\u7A5B\u7A56\u7A58\u7A54\u7A5A\u7ABE\u7AC0\u7AC1\u7C05\u7C0F\u7BF2\u7C00\u7BFF\u7BFB\u7C0E\u7BF4\u7C0B\u7BF3\u7C02\u7C09\u7C03\u7C01\u7BF8\u7BFD\u7C06\u7BF0\u7BF1\u7C10\u7C0A\u7CE8\u7E2D\u7E3C\u7E42\u7E33\u9848\u7E38\u7E2A\u7E49\u7E40\u7E47\u7E29\u7E4C\u7E30\u7E3B\u7E36\u7E44\u7E3A\u7F45\u7F7F\u7F7E\u7F7D\u7FF4\u7FF2\u802C\u81BB\u81C4\u81CC\u81CA\u81C5\u81C7\u81BC\u81E9\u825B\u825A\u825C\u8583\u8580\u858F\u85A7\u8595\u85A0\u858B\u85A3\u857B\u85A4\u859A\u859E"], + ["ee40", "\u8577\u857C\u8589\u85A1\u857A\u8578\u8557\u858E\u8596\u8586\u858D\u8599\u859D\u8581\u85A2\u8582\u8588\u8585\u8579\u8576\u8598\u8590\u859F\u8668\u87BE\u87AA\u87AD\u87C5\u87B0\u87AC\u87B9\u87B5\u87BC\u87AE\u87C9\u87C3\u87C2\u87CC\u87B7\u87AF\u87C4\u87CA\u87B4\u87B6\u87BF\u87B8\u87BD\u87DE\u87B2\u8935\u8933\u893C\u893E\u8941\u8952\u8937\u8942\u89AD\u89AF\u89AE\u89F2\u89F3\u8B1E"], + ["eea1", "\u8B18\u8B16\u8B11\u8B05\u8B0B\u8B22\u8B0F\u8B12\u8B15\u8B07\u8B0D\u8B08\u8B06\u8B1C\u8B13\u8B1A\u8C4F\u8C70\u8C72\u8C71\u8C6F\u8C95\u8C94\u8CF9\u8D6F\u8E4E\u8E4D\u8E53\u8E50\u8E4C\u8E47\u8F43\u8F40\u9085\u907E\u9138\u919A\u91A2\u919B\u9199\u919F\u91A1\u919D\u91A0\u93A1\u9383\u93AF\u9364\u9356\u9347\u937C\u9358\u935C\u9376\u9349\u9350\u9351\u9360\u936D\u938F\u934C\u936A\u9379\u9357\u9355\u9352\u934F\u9371\u9377\u937B\u9361\u935E\u9363\u9367\u9380\u934E\u9359\u95C7\u95C0\u95C9\u95C3\u95C5\u95B7\u96AE\u96B0\u96AC\u9720\u971F\u9718\u971D\u9719\u979A\u97A1\u979C"], + ["ef40", "\u979E\u979D\u97D5\u97D4\u97F1\u9841\u9844\u984A\u9849\u9845\u9843\u9925\u992B\u992C\u992A\u9933\u9932\u992F\u992D\u9931\u9930\u9998\u99A3\u99A1\u9A02\u99FA\u99F4\u99F7\u99F9\u99F8\u99F6\u99FB\u99FD\u99FE\u99FC\u9A03\u9ABE\u9AFE\u9AFD\u9B01\u9AFC\u9B48\u9B9A\u9BA8\u9B9E\u9B9B\u9BA6\u9BA1\u9BA5\u9BA4\u9B86\u9BA2\u9BA0\u9BAF\u9D33\u9D41\u9D67\u9D36\u9D2E\u9D2F\u9D31\u9D38\u9D30"], + ["efa1", "\u9D45\u9D42\u9D43\u9D3E\u9D37\u9D40\u9D3D\u7FF5\u9D2D\u9E8A\u9E89\u9E8D\u9EB0\u9EC8\u9EDA\u9EFB\u9EFF\u9F24\u9F23\u9F22\u9F54\u9FA0\u5131\u512D\u512E\u5698\u569C\u5697\u569A\u569D\u5699\u5970\u5B3C\u5C69\u5C6A\u5DC0\u5E6D\u5E6E\u61D8\u61DF\u61ED\u61EE\u61F1\u61EA\u61F0\u61EB\u61D6\u61E9\u64FF\u6504\u64FD\u64F8\u6501\u6503\u64FC\u6594\u65DB\u66DA\u66DB\u66D8\u6AC5\u6AB9\u6ABD\u6AE1\u6AC6\u6ABA\u6AB6\u6AB7\u6AC7\u6AB4\u6AAD\u6B5E\u6BC9\u6C0B\u7007\u700C\u700D\u7001\u7005\u7014\u700E\u6FFF\u7000\u6FFB\u7026\u6FFC\u6FF7\u700A\u7201\u71FF\u71F9\u7203\u71FD\u7376"], + ["f040", "\u74B8\u74C0\u74B5\u74C1\u74BE\u74B6\u74BB\u74C2\u7514\u7513\u765C\u7664\u7659\u7650\u7653\u7657\u765A\u76A6\u76BD\u76EC\u77C2\u77BA\u78FF\u790C\u7913\u7914\u7909\u7910\u7912\u7911\u79AD\u79AC\u7A5F\u7C1C\u7C29\u7C19\u7C20\u7C1F\u7C2D\u7C1D\u7C26\u7C28\u7C22\u7C25\u7C30\u7E5C\u7E50\u7E56\u7E63\u7E58\u7E62\u7E5F\u7E51\u7E60\u7E57\u7E53\u7FB5\u7FB3\u7FF7\u7FF8\u8075\u81D1\u81D2"], + ["f0a1", "\u81D0\u825F\u825E\u85B4\u85C6\u85C0\u85C3\u85C2\u85B3\u85B5\u85BD\u85C7\u85C4\u85BF\u85CB\u85CE\u85C8\u85C5\u85B1\u85B6\u85D2\u8624\u85B8\u85B7\u85BE\u8669\u87E7\u87E6\u87E2\u87DB\u87EB\u87EA\u87E5\u87DF\u87F3\u87E4\u87D4\u87DC\u87D3\u87ED\u87D8\u87E3\u87A4\u87D7\u87D9\u8801\u87F4\u87E8\u87DD\u8953\u894B\u894F\u894C\u8946\u8950\u8951\u8949\u8B2A\u8B27\u8B23\u8B33\u8B30\u8B35\u8B47\u8B2F\u8B3C\u8B3E\u8B31\u8B25\u8B37\u8B26\u8B36\u8B2E\u8B24\u8B3B\u8B3D\u8B3A\u8C42\u8C75\u8C99\u8C98\u8C97\u8CFE\u8D04\u8D02\u8D00\u8E5C\u8E62\u8E60\u8E57\u8E56\u8E5E\u8E65\u8E67"], + ["f140", "\u8E5B\u8E5A\u8E61\u8E5D\u8E69\u8E54\u8F46\u8F47\u8F48\u8F4B\u9128\u913A\u913B\u913E\u91A8\u91A5\u91A7\u91AF\u91AA\u93B5\u938C\u9392\u93B7\u939B\u939D\u9389\u93A7\u938E\u93AA\u939E\u93A6\u9395\u9388\u9399\u939F\u938D\u93B1\u9391\u93B2\u93A4\u93A8\u93B4\u93A3\u93A5\u95D2\u95D3\u95D1\u96B3\u96D7\u96DA\u5DC2\u96DF\u96D8\u96DD\u9723\u9722\u9725\u97AC\u97AE\u97A8\u97AB\u97A4\u97AA"], + ["f1a1", "\u97A2\u97A5\u97D7\u97D9\u97D6\u97D8\u97FA\u9850\u9851\u9852\u98B8\u9941\u993C\u993A\u9A0F\u9A0B\u9A09\u9A0D\u9A04\u9A11\u9A0A\u9A05\u9A07\u9A06\u9AC0\u9ADC\u9B08\u9B04\u9B05\u9B29\u9B35\u9B4A\u9B4C\u9B4B\u9BC7\u9BC6\u9BC3\u9BBF\u9BC1\u9BB5\u9BB8\u9BD3\u9BB6\u9BC4\u9BB9\u9BBD\u9D5C\u9D53\u9D4F\u9D4A\u9D5B\u9D4B\u9D59\u9D56\u9D4C\u9D57\u9D52\u9D54\u9D5F\u9D58\u9D5A\u9E8E\u9E8C\u9EDF\u9F01\u9F00\u9F16\u9F25\u9F2B\u9F2A\u9F29\u9F28\u9F4C\u9F55\u5134\u5135\u5296\u52F7\u53B4\u56AB\u56AD\u56A6\u56A7\u56AA\u56AC\u58DA\u58DD\u58DB\u5912\u5B3D\u5B3E\u5B3F\u5DC3\u5E70"], + ["f240", "\u5FBF\u61FB\u6507\u6510\u650D\u6509\u650C\u650E\u6584\u65DE\u65DD\u66DE\u6AE7\u6AE0\u6ACC\u6AD1\u6AD9\u6ACB\u6ADF\u6ADC\u6AD0\u6AEB\u6ACF\u6ACD\u6ADE\u6B60\u6BB0\u6C0C\u7019\u7027\u7020\u7016\u702B\u7021\u7022\u7023\u7029\u7017\u7024\u701C\u702A\u720C\u720A\u7207\u7202\u7205\u72A5\u72A6\u72A4\u72A3\u72A1\u74CB\u74C5\u74B7\u74C3\u7516\u7660\u77C9\u77CA\u77C4\u77F1\u791D\u791B"], + ["f2a1", "\u7921\u791C\u7917\u791E\u79B0\u7A67\u7A68\u7C33\u7C3C\u7C39\u7C2C\u7C3B\u7CEC\u7CEA\u7E76\u7E75\u7E78\u7E70\u7E77\u7E6F\u7E7A\u7E72\u7E74\u7E68\u7F4B\u7F4A\u7F83\u7F86\u7FB7\u7FFD\u7FFE\u8078\u81D7\u81D5\u8264\u8261\u8263\u85EB\u85F1\u85ED\u85D9\u85E1\u85E8\u85DA\u85D7\u85EC\u85F2\u85F8\u85D8\u85DF\u85E3\u85DC\u85D1\u85F0\u85E6\u85EF\u85DE\u85E2\u8800\u87FA\u8803\u87F6\u87F7\u8809\u880C\u880B\u8806\u87FC\u8808\u87FF\u880A\u8802\u8962\u895A\u895B\u8957\u8961\u895C\u8958\u895D\u8959\u8988\u89B7\u89B6\u89F6\u8B50\u8B48\u8B4A\u8B40\u8B53\u8B56\u8B54\u8B4B\u8B55"], + ["f340", "\u8B51\u8B42\u8B52\u8B57\u8C43\u8C77\u8C76\u8C9A\u8D06\u8D07\u8D09\u8DAC\u8DAA\u8DAD\u8DAB\u8E6D\u8E78\u8E73\u8E6A\u8E6F\u8E7B\u8EC2\u8F52\u8F51\u8F4F\u8F50\u8F53\u8FB4\u9140\u913F\u91B0\u91AD\u93DE\u93C7\u93CF\u93C2\u93DA\u93D0\u93F9\u93EC\u93CC\u93D9\u93A9\u93E6\u93CA\u93D4\u93EE\u93E3\u93D5\u93C4\u93CE\u93C0\u93D2\u93E7\u957D\u95DA\u95DB\u96E1\u9729\u972B\u972C\u9728\u9726"], + ["f3a1", "\u97B3\u97B7\u97B6\u97DD\u97DE\u97DF\u985C\u9859\u985D\u9857\u98BF\u98BD\u98BB\u98BE\u9948\u9947\u9943\u99A6\u99A7\u9A1A\u9A15\u9A25\u9A1D\u9A24\u9A1B\u9A22\u9A20\u9A27\u9A23\u9A1E\u9A1C\u9A14\u9AC2\u9B0B\u9B0A\u9B0E\u9B0C\u9B37\u9BEA\u9BEB\u9BE0\u9BDE\u9BE4\u9BE6\u9BE2\u9BF0\u9BD4\u9BD7\u9BEC\u9BDC\u9BD9\u9BE5\u9BD5\u9BE1\u9BDA\u9D77\u9D81\u9D8A\u9D84\u9D88\u9D71\u9D80\u9D78\u9D86\u9D8B\u9D8C\u9D7D\u9D6B\u9D74\u9D75\u9D70\u9D69\u9D85\u9D73\u9D7B\u9D82\u9D6F\u9D79\u9D7F\u9D87\u9D68\u9E94\u9E91\u9EC0\u9EFC\u9F2D\u9F40\u9F41\u9F4D\u9F56\u9F57\u9F58\u5337\u56B2"], + ["f440", "\u56B5\u56B3\u58E3\u5B45\u5DC6\u5DC7\u5EEE\u5EEF\u5FC0\u5FC1\u61F9\u6517\u6516\u6515\u6513\u65DF\u66E8\u66E3\u66E4\u6AF3\u6AF0\u6AEA\u6AE8\u6AF9\u6AF1\u6AEE\u6AEF\u703C\u7035\u702F\u7037\u7034\u7031\u7042\u7038\u703F\u703A\u7039\u7040\u703B\u7033\u7041\u7213\u7214\u72A8\u737D\u737C\u74BA\u76AB\u76AA\u76BE\u76ED\u77CC\u77CE\u77CF\u77CD\u77F2\u7925\u7923\u7927\u7928\u7924\u7929"], + ["f4a1", "\u79B2\u7A6E\u7A6C\u7A6D\u7AF7\u7C49\u7C48\u7C4A\u7C47\u7C45\u7CEE\u7E7B\u7E7E\u7E81\u7E80\u7FBA\u7FFF\u8079\u81DB\u81D9\u820B\u8268\u8269\u8622\u85FF\u8601\u85FE\u861B\u8600\u85F6\u8604\u8609\u8605\u860C\u85FD\u8819\u8810\u8811\u8817\u8813\u8816\u8963\u8966\u89B9\u89F7\u8B60\u8B6A\u8B5D\u8B68\u8B63\u8B65\u8B67\u8B6D\u8DAE\u8E86\u8E88\u8E84\u8F59\u8F56\u8F57\u8F55\u8F58\u8F5A\u908D\u9143\u9141\u91B7\u91B5\u91B2\u91B3\u940B\u9413\u93FB\u9420\u940F\u9414\u93FE\u9415\u9410\u9428\u9419\u940D\u93F5\u9400\u93F7\u9407\u940E\u9416\u9412\u93FA\u9409\u93F8\u940A\u93FF"], + ["f540", "\u93FC\u940C\u93F6\u9411\u9406\u95DE\u95E0\u95DF\u972E\u972F\u97B9\u97BB\u97FD\u97FE\u9860\u9862\u9863\u985F\u98C1\u98C2\u9950\u994E\u9959\u994C\u994B\u9953\u9A32\u9A34\u9A31\u9A2C\u9A2A\u9A36\u9A29\u9A2E\u9A38\u9A2D\u9AC7\u9ACA\u9AC6\u9B10\u9B12\u9B11\u9C0B\u9C08\u9BF7\u9C05\u9C12\u9BF8\u9C40\u9C07\u9C0E\u9C06\u9C17\u9C14\u9C09\u9D9F\u9D99\u9DA4\u9D9D\u9D92\u9D98\u9D90\u9D9B"], + ["f5a1", "\u9DA0\u9D94\u9D9C\u9DAA\u9D97\u9DA1\u9D9A\u9DA2\u9DA8\u9D9E\u9DA3\u9DBF\u9DA9\u9D96\u9DA6\u9DA7\u9E99\u9E9B\u9E9A\u9EE5\u9EE4\u9EE7\u9EE6\u9F30\u9F2E\u9F5B\u9F60\u9F5E\u9F5D\u9F59\u9F91\u513A\u5139\u5298\u5297\u56C3\u56BD\u56BE\u5B48\u5B47\u5DCB\u5DCF\u5EF1\u61FD\u651B\u6B02\u6AFC\u6B03\u6AF8\u6B00\u7043\u7044\u704A\u7048\u7049\u7045\u7046\u721D\u721A\u7219\u737E\u7517\u766A\u77D0\u792D\u7931\u792F\u7C54\u7C53\u7CF2\u7E8A\u7E87\u7E88\u7E8B\u7E86\u7E8D\u7F4D\u7FBB\u8030\u81DD\u8618\u862A\u8626\u861F\u8623\u861C\u8619\u8627\u862E\u8621\u8620\u8629\u861E\u8625"], + ["f640", "\u8829\u881D\u881B\u8820\u8824\u881C\u882B\u884A\u896D\u8969\u896E\u896B\u89FA\u8B79\u8B78\u8B45\u8B7A\u8B7B\u8D10\u8D14\u8DAF\u8E8E\u8E8C\u8F5E\u8F5B\u8F5D\u9146\u9144\u9145\u91B9\u943F\u943B\u9436\u9429\u943D\u943C\u9430\u9439\u942A\u9437\u942C\u9440\u9431\u95E5\u95E4\u95E3\u9735\u973A\u97BF\u97E1\u9864\u98C9\u98C6\u98C0\u9958\u9956\u9A39\u9A3D\u9A46\u9A44\u9A42\u9A41\u9A3A"], + ["f6a1", "\u9A3F\u9ACD\u9B15\u9B17\u9B18\u9B16\u9B3A\u9B52\u9C2B\u9C1D\u9C1C\u9C2C\u9C23\u9C28\u9C29\u9C24\u9C21\u9DB7\u9DB6\u9DBC\u9DC1\u9DC7\u9DCA\u9DCF\u9DBE\u9DC5\u9DC3\u9DBB\u9DB5\u9DCE\u9DB9\u9DBA\u9DAC\u9DC8\u9DB1\u9DAD\u9DCC\u9DB3\u9DCD\u9DB2\u9E7A\u9E9C\u9EEB\u9EEE\u9EED\u9F1B\u9F18\u9F1A\u9F31\u9F4E\u9F65\u9F64\u9F92\u4EB9\u56C6\u56C5\u56CB\u5971\u5B4B\u5B4C\u5DD5\u5DD1\u5EF2\u6521\u6520\u6526\u6522\u6B0B\u6B08\u6B09\u6C0D\u7055\u7056\u7057\u7052\u721E\u721F\u72A9\u737F\u74D8\u74D5\u74D9\u74D7\u766D\u76AD\u7935\u79B4\u7A70\u7A71\u7C57\u7C5C\u7C59\u7C5B\u7C5A"], + ["f740", "\u7CF4\u7CF1\u7E91\u7F4F\u7F87\u81DE\u826B\u8634\u8635\u8633\u862C\u8632\u8636\u882C\u8828\u8826\u882A\u8825\u8971\u89BF\u89BE\u89FB\u8B7E\u8B84\u8B82\u8B86\u8B85\u8B7F\u8D15\u8E95\u8E94\u8E9A\u8E92\u8E90\u8E96\u8E97\u8F60\u8F62\u9147\u944C\u9450\u944A\u944B\u944F\u9447\u9445\u9448\u9449\u9446\u973F\u97E3\u986A\u9869\u98CB\u9954\u995B\u9A4E\u9A53\u9A54\u9A4C\u9A4F\u9A48\u9A4A"], + ["f7a1", "\u9A49\u9A52\u9A50\u9AD0\u9B19\u9B2B\u9B3B\u9B56\u9B55\u9C46\u9C48\u9C3F\u9C44\u9C39\u9C33\u9C41\u9C3C\u9C37\u9C34\u9C32\u9C3D\u9C36\u9DDB\u9DD2\u9DDE\u9DDA\u9DCB\u9DD0\u9DDC\u9DD1\u9DDF\u9DE9\u9DD9\u9DD8\u9DD6\u9DF5\u9DD5\u9DDD\u9EB6\u9EF0\u9F35\u9F33\u9F32\u9F42\u9F6B\u9F95\u9FA2\u513D\u5299\u58E8\u58E7\u5972\u5B4D\u5DD8\u882F\u5F4F\u6201\u6203\u6204\u6529\u6525\u6596\u66EB\u6B11\u6B12\u6B0F\u6BCA\u705B\u705A\u7222\u7382\u7381\u7383\u7670\u77D4\u7C67\u7C66\u7E95\u826C\u863A\u8640\u8639\u863C\u8631\u863B\u863E\u8830\u8832\u882E\u8833\u8976\u8974\u8973\u89FE"], + ["f840", "\u8B8C\u8B8E\u8B8B\u8B88\u8C45\u8D19\u8E98\u8F64\u8F63\u91BC\u9462\u9455\u945D\u9457\u945E\u97C4\u97C5\u9800\u9A56\u9A59\u9B1E\u9B1F\u9B20\u9C52\u9C58\u9C50\u9C4A\u9C4D\u9C4B\u9C55\u9C59\u9C4C\u9C4E\u9DFB\u9DF7\u9DEF\u9DE3\u9DEB\u9DF8\u9DE4\u9DF6\u9DE1\u9DEE\u9DE6\u9DF2\u9DF0\u9DE2\u9DEC\u9DF4\u9DF3\u9DE8\u9DED\u9EC2\u9ED0\u9EF2\u9EF3\u9F06\u9F1C\u9F38\u9F37\u9F36\u9F43\u9F4F"], + ["f8a1", "\u9F71\u9F70\u9F6E\u9F6F\u56D3\u56CD\u5B4E\u5C6D\u652D\u66ED\u66EE\u6B13\u705F\u7061\u705D\u7060\u7223\u74DB\u74E5\u77D5\u7938\u79B7\u79B6\u7C6A\u7E97\u7F89\u826D\u8643\u8838\u8837\u8835\u884B\u8B94\u8B95\u8E9E\u8E9F\u8EA0\u8E9D\u91BE\u91BD\u91C2\u946B\u9468\u9469\u96E5\u9746\u9743\u9747\u97C7\u97E5\u9A5E\u9AD5\u9B59\u9C63\u9C67\u9C66\u9C62\u9C5E\u9C60\u9E02\u9DFE\u9E07\u9E03\u9E06\u9E05\u9E00\u9E01\u9E09\u9DFF\u9DFD\u9E04\u9EA0\u9F1E\u9F46\u9F74\u9F75\u9F76\u56D4\u652E\u65B8\u6B18\u6B19\u6B17\u6B1A\u7062\u7226\u72AA\u77D8\u77D9\u7939\u7C69\u7C6B\u7CF6\u7E9A"], + ["f940", "\u7E98\u7E9B\u7E99\u81E0\u81E1\u8646\u8647\u8648\u8979\u897A\u897C\u897B\u89FF\u8B98\u8B99\u8EA5\u8EA4\u8EA3\u946E\u946D\u946F\u9471\u9473\u9749\u9872\u995F\u9C68\u9C6E\u9C6D\u9E0B\u9E0D\u9E10\u9E0F\u9E12\u9E11\u9EA1\u9EF5\u9F09\u9F47\u9F78\u9F7B\u9F7A\u9F79\u571E\u7066\u7C6F\u883C\u8DB2\u8EA6\u91C3\u9474\u9478\u9476\u9475\u9A60\u9C74\u9C73\u9C71\u9C75\u9E14\u9E13\u9EF6\u9F0A"], + ["f9a1", "\u9FA4\u7068\u7065\u7CF7\u866A\u883E\u883D\u883F\u8B9E\u8C9C\u8EA9\u8EC9\u974B\u9873\u9874\u98CC\u9961\u99AB\u9A64\u9A66\u9A67\u9B24\u9E15\u9E17\u9F48\u6207\u6B1E\u7227\u864C\u8EA8\u9482\u9480\u9481\u9A69\u9A68\u9B2E\u9E19\u7229\u864B\u8B9F\u9483\u9C79\u9EB7\u7675\u9A6B\u9C7A\u9E1D\u7069\u706A\u9EA4\u9F7E\u9F49\u9F98\u7881\u92B9\u88CF\u58BB\u6052\u7CA7\u5AFA\u2554\u2566\u2557\u2560\u256C\u2563\u255A\u2569\u255D\u2552\u2564\u2555\u255E\u256A\u2561\u2558\u2567\u255B\u2553\u2565\u2556\u255F\u256B\u2562\u2559\u2568\u255C\u2551\u2550\u256D\u256E\u2570\u256F\u2593"] + ]; + } +}); + +// node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/encodings/tables/big5-added.json +var require_big5_added = __commonJS({ + "node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/encodings/tables/big5-added.json"(exports, module) { + module.exports = [ + ["8740", "\u43F0\u4C32\u4603\u45A6\u4578\u{27267}\u4D77\u45B3\u{27CB1}\u4CE2\u{27CC5}\u3B95\u4736\u4744\u4C47\u4C40\u{242BF}\u{23617}\u{27352}\u{26E8B}\u{270D2}\u4C57\u{2A351}\u474F\u45DA\u4C85\u{27C6C}\u4D07\u4AA4\u46A1\u{26B23}\u7225\u{25A54}\u{21A63}\u{23E06}\u{23F61}\u664D\u56FB"], + ["8767", "\u7D95\u591D\u{28BB9}\u3DF4\u9734\u{27BEF}\u5BDB\u{21D5E}\u5AA4\u3625\u{29EB0}\u5AD1\u5BB7\u5CFC\u676E\u8593\u{29945}\u7461\u749D\u3875\u{21D53}\u{2369E}\u{26021}\u3EEC"], + ["87a1", "\u{258DE}\u3AF5\u7AFC\u9F97\u{24161}\u{2890D}\u{231EA}\u{20A8A}\u{2325E}\u430A\u8484\u9F96\u942F\u4930\u8613\u5896\u974A\u9218\u79D0\u7A32\u6660\u6A29\u889D\u744C\u7BC5\u6782\u7A2C\u524F\u9046\u34E6\u73C4\u{25DB9}\u74C6\u9FC7\u57B3\u492F\u544C\u4131\u{2368E}\u5818\u7A72\u{27B65}\u8B8F\u46AE\u{26E88}\u4181\u{25D99}\u7BAE\u{224BC}\u9FC8\u{224C1}\u{224C9}\u{224CC}\u9FC9\u8504\u{235BB}\u40B4\u9FCA\u44E1\u{2ADFF}\u62C1\u706E\u9FCB"], + ["8840", "\u31C0", 4, "\u{2010C}\u31C5\u{200D1}\u{200CD}\u31C6\u31C7\u{200CB}\u{21FE8}\u31C8\u{200CA}\u31C9\u31CA\u31CB\u31CC\u{2010E}\u31CD\u31CE\u0100\xC1\u01CD\xC0\u0112\xC9\u011A\xC8\u014C\xD3\u01D1\xD2\u0FFF\xCA\u0304\u1EBE\u0FFF\xCA\u030C\u1EC0\xCA\u0101\xE1\u01CE\xE0\u0251\u0113\xE9\u011B\xE8\u012B\xED\u01D0\xEC\u014D\xF3\u01D2\xF2\u016B\xFA\u01D4\xF9\u01D6\u01D8\u01DA"], + ["88a1", "\u01DC\xFC\u0FFF\xEA\u0304\u1EBF\u0FFF\xEA\u030C\u1EC1\xEA\u0261\u23DA\u23DB"], + ["8940", "\u{2A3A9}\u{21145}"], + ["8943", "\u650A"], + ["8946", "\u4E3D\u6EDD\u9D4E\u91DF"], + ["894c", "\u{27735}\u6491\u4F1A\u4F28\u4FA8\u5156\u5174\u519C\u51E4\u52A1\u52A8\u533B\u534E\u53D1\u53D8\u56E2\u58F0\u5904\u5907\u5932\u5934\u5B66\u5B9E\u5B9F\u5C9A\u5E86\u603B\u6589\u67FE\u6804\u6865\u6D4E\u70BC\u7535\u7EA4\u7EAC\u7EBA\u7EC7\u7ECF\u7EDF\u7F06\u7F37\u827A\u82CF\u836F\u89C6\u8BBE\u8BE2\u8F66\u8F67\u8F6E"], + ["89a1", "\u7411\u7CFC\u7DCD\u6946\u7AC9\u5227"], + ["89ab", "\u918C\u78B8\u915E\u80BC"], + ["89b0", "\u8D0B\u80F6\u{209E7}"], + ["89b5", "\u809F\u9EC7\u4CCD\u9DC9\u9E0C\u4C3E\u{29DF6}\u{2700E}\u9E0A\u{2A133}\u35C1"], + ["89c1", "\u6E9A\u823E\u7519"], + ["89c5", "\u4911\u9A6C\u9A8F\u9F99\u7987\u{2846C}\u{21DCA}\u{205D0}\u{22AE6}\u4E24\u4E81\u4E80\u4E87\u4EBF\u4EEB\u4F37\u344C\u4FBD\u3E48\u5003\u5088\u347D\u3493\u34A5\u5186\u5905\u51DB\u51FC\u5205\u4E89\u5279\u5290\u5327\u35C7\u53A9\u3551\u53B0\u3553\u53C2\u5423\u356D\u3572\u3681\u5493\u54A3\u54B4\u54B9\u54D0\u54EF\u5518\u5523\u5528\u3598\u553F\u35A5\u35BF\u55D7\u35C5"], + ["8a40", "\u{27D84}\u5525"], + ["8a43", "\u{20C42}\u{20D15}\u{2512B}\u5590\u{22CC6}\u39EC\u{20341}\u8E46\u{24DB8}\u{294E5}\u4053\u{280BE}\u777A\u{22C38}\u3A34\u47D5\u{2815D}\u{269F2}\u{24DEA}\u64DD\u{20D7C}\u{20FB4}\u{20CD5}\u{210F4}\u648D\u8E7E\u{20E96}\u{20C0B}\u{20F64}\u{22CA9}\u{28256}\u{244D3}"], + ["8a64", "\u{20D46}\u{29A4D}\u{280E9}\u47F4\u{24EA7}\u{22CC2}\u9AB2\u3A67\u{295F4}\u3FED\u3506\u{252C7}\u{297D4}\u{278C8}\u{22D44}\u9D6E\u9815"], + ["8a76", "\u43D9\u{260A5}\u64B4\u54E3\u{22D4C}\u{22BCA}\u{21077}\u39FB\u{2106F}"], + ["8aa1", "\u{266DA}\u{26716}\u{279A0}\u64EA\u{25052}\u{20C43}\u8E68\u{221A1}\u{28B4C}\u{20731}"], + ["8aac", "\u480B\u{201A9}\u3FFA\u5873\u{22D8D}"], + ["8ab2", "\u{245C8}\u{204FC}\u{26097}\u{20F4C}\u{20D96}\u5579\u40BB\u43BA"], + ["8abb", "\u4AB4\u{22A66}\u{2109D}\u81AA\u98F5\u{20D9C}\u6379\u39FE\u{22775}\u8DC0\u56A1\u647C\u3E43"], + ["8ac9", "\u{2A601}\u{20E09}\u{22ACF}\u{22CC9}"], + ["8ace", "\u{210C8}\u{239C2}\u3992\u3A06\u{2829B}\u3578\u{25E49}\u{220C7}\u5652\u{20F31}\u{22CB2}\u{29720}\u34BC\u6C3D\u{24E3B}"], + ["8adf", "\u{27574}\u{22E8B}\u{22208}\u{2A65B}\u{28CCD}\u{20E7A}\u{20C34}\u{2681C}\u7F93\u{210CF}\u{22803}\u{22939}\u35FB\u{251E3}\u{20E8C}\u{20F8D}\u{20EAA}\u3F93\u{20F30}\u{20D47}\u{2114F}\u{20E4C}"], + ["8af6", "\u{20EAB}\u{20BA9}\u{20D48}\u{210C0}\u{2113D}\u3FF9\u{22696}\u6432\u{20FAD}"], + ["8b40", "\u{233F4}\u{27639}\u{22BCE}\u{20D7E}\u{20D7F}\u{22C51}\u{22C55}\u3A18\u{20E98}\u{210C7}\u{20F2E}\u{2A632}\u{26B50}\u{28CD2}\u{28D99}\u{28CCA}\u95AA\u54CC\u82C4\u55B9"], + ["8b55", "\u{29EC3}\u9C26\u9AB6\u{2775E}\u{22DEE}\u7140\u816D\u80EC\u5C1C\u{26572}\u8134\u3797\u535F\u{280BD}\u91B6\u{20EFA}\u{20E0F}\u{20E77}\u{20EFB}\u35DD\u{24DEB}\u3609\u{20CD6}\u56AF\u{227B5}\u{210C9}\u{20E10}\u{20E78}\u{21078}\u{21148}\u{28207}\u{21455}\u{20E79}\u{24E50}\u{22DA4}\u5A54\u{2101D}\u{2101E}\u{210F5}\u{210F6}\u579C\u{20E11}"], + ["8ba1", "\u{27694}\u{282CD}\u{20FB5}\u{20E7B}\u{2517E}\u3703\u{20FB6}\u{21180}\u{252D8}\u{2A2BD}\u{249DA}\u{2183A}\u{24177}\u{2827C}\u5899\u5268\u361A\u{2573D}\u7BB2\u5B68\u4800\u4B2C\u9F27\u49E7\u9C1F\u9B8D\u{25B74}\u{2313D}\u55FB\u35F2\u5689\u4E28\u5902\u{21BC1}\u{2F878}\u9751\u{20086}\u4E5B\u4EBB\u353E\u5C23\u5F51\u5FC4\u38FA\u624C\u6535\u6B7A\u6C35\u6C3A\u706C\u722B\u4E2C\u72AD\u{248E9}\u7F52\u793B\u7CF9\u7F53\u{2626A}\u34C1"], + ["8bde", "\u{2634B}\u8002\u8080\u{26612}\u{26951}\u535D\u8864\u89C1\u{278B2}\u8BA0\u8D1D\u9485\u9578\u957F\u95E8\u{28E0F}\u97E6\u9875\u98CE\u98DE\u9963\u{29810}\u9C7C\u9E1F\u9EC4\u6B6F\uF907\u4E37\u{20087}\u961D\u6237\u94A2"], + ["8c40", "\u503B\u6DFE\u{29C73}\u9FA6\u3DC9\u888F\u{2414E}\u7077\u5CF5\u4B20\u{251CD}\u3559\u{25D30}\u6122\u{28A32}\u8FA7\u91F6\u7191\u6719\u73BA\u{23281}\u{2A107}\u3C8B\u{21980}\u4B10\u78E4\u7402\u51AE\u{2870F}\u4009\u6A63\u{2A2BA}\u4223\u860F\u{20A6F}\u7A2A\u{29947}\u{28AEA}\u9755\u704D\u5324\u{2207E}\u93F4\u76D9\u{289E3}\u9FA7\u77DD\u4EA3\u4FF0\u50BC\u4E2F\u4F17\u9FA8\u5434\u7D8B\u5892\u58D0\u{21DB6}\u5E92\u5E99\u5FC2\u{22712}\u658B"], + ["8ca1", "\u{233F9}\u6919\u6A43\u{23C63}\u6CFF"], + ["8ca7", "\u7200\u{24505}\u738C\u3EDB\u{24A13}\u5B15\u74B9\u8B83\u{25CA4}\u{25695}\u7A93\u7BEC\u7CC3\u7E6C\u82F8\u8597\u9FA9\u8890\u9FAA\u8EB9\u9FAB\u8FCF\u855F\u99E0\u9221\u9FAC\u{28DB9}\u{2143F}\u4071\u42A2\u5A1A"], + ["8cc9", "\u9868\u676B\u4276\u573D"], + ["8cce", "\u85D6\u{2497B}\u82BF\u{2710D}\u4C81\u{26D74}\u5D7B\u{26B15}\u{26FBE}\u9FAD\u9FAE\u5B96\u9FAF\u66E7\u7E5B\u6E57\u79CA\u3D88\u44C3\u{23256}\u{22796}\u439A\u4536"], + ["8ce6", "\u5CD5\u{23B1A}\u8AF9\u5C78\u3D12\u{23551}\u5D78\u9FB2\u7157\u4558\u{240EC}\u{21E23}\u4C77\u3978\u344A\u{201A4}\u{26C41}\u8ACC\u4FB4\u{20239}\u59BF\u816C\u9856\u{298FA}\u5F3B"], + ["8d40", "\u{20B9F}"], + ["8d42", "\u{221C1}\u{2896D}\u4102\u46BB\u{29079}\u3F07\u9FB3\u{2A1B5}\u40F8\u37D6\u46F7\u{26C46}\u417C\u{286B2}\u{273FF}\u456D\u38D4\u{2549A}\u4561\u451B\u4D89\u4C7B\u4D76\u45EA\u3FC8\u{24B0F}\u3661\u44DE\u44BD\u41ED\u5D3E\u5D48\u5D56\u3DFC\u380F\u5DA4\u5DB9\u3820\u3838\u5E42\u5EBD\u5F25\u5F83\u3908\u3914\u393F\u394D\u60D7\u613D\u5CE5\u3989\u61B7\u61B9\u61CF\u39B8\u622C\u6290\u62E5\u6318\u39F8\u56B1"], + ["8da1", "\u3A03\u63E2\u63FB\u6407\u645A\u3A4B\u64C0\u5D15\u5621\u9F9F\u3A97\u6586\u3ABD\u65FF\u6653\u3AF2\u6692\u3B22\u6716\u3B42\u67A4\u6800\u3B58\u684A\u6884\u3B72\u3B71\u3B7B\u6909\u6943\u725C\u6964\u699F\u6985\u3BBC\u69D6\u3BDD\u6A65\u6A74\u6A71\u6A82\u3BEC\u6A99\u3BF2\u6AAB\u6AB5\u6AD4\u6AF6\u6B81\u6BC1\u6BEA\u6C75\u6CAA\u3CCB\u6D02\u6D06\u6D26\u6D81\u3CEF\u6DA4\u6DB1\u6E15\u6E18\u6E29\u6E86\u{289C0}\u6EBB\u6EE2\u6EDA\u9F7F\u6EE8\u6EE9\u6F24\u6F34\u3D46\u{23F41}\u6F81\u6FBE\u3D6A\u3D75\u71B7\u5C99\u3D8A\u702C\u3D91\u7050\u7054\u706F\u707F\u7089\u{20325}\u43C1\u35F1\u{20ED8}"], + ["8e40", "\u{23ED7}\u57BE\u{26ED3}\u713E\u{257E0}\u364E\u69A2\u{28BE9}\u5B74\u7A49\u{258E1}\u{294D9}\u7A65\u7A7D\u{259AC}\u7ABB\u7AB0\u7AC2\u7AC3\u71D1\u{2648D}\u41CA\u7ADA\u7ADD\u7AEA\u41EF\u54B2\u{25C01}\u7B0B\u7B55\u7B29\u{2530E}\u{25CFE}\u7BA2\u7B6F\u839C\u{25BB4}\u{26C7F}\u7BD0\u8421\u7B92\u7BB8\u{25D20}\u3DAD\u{25C65}\u8492\u7BFA\u7C06\u7C35\u{25CC1}\u7C44\u7C83\u{24882}\u7CA6\u667D\u{24578}\u7CC9\u7CC7\u7CE6\u7C74\u7CF3\u7CF5\u7CCE"], + ["8ea1", "\u7E67\u451D\u{26E44}\u7D5D\u{26ED6}\u748D\u7D89\u7DAB\u7135\u7DB3\u7DD2\u{24057}\u{26029}\u7DE4\u3D13\u7DF5\u{217F9}\u7DE5\u{2836D}\u7E1D\u{26121}\u{2615A}\u7E6E\u7E92\u432B\u946C\u7E27\u7F40\u7F41\u7F47\u7936\u{262D0}\u99E1\u7F97\u{26351}\u7FA3\u{21661}\u{20068}\u455C\u{23766}\u4503\u{2833A}\u7FFA\u{26489}\u8005\u8008\u801D\u8028\u802F\u{2A087}\u{26CC3}\u803B\u803C\u8061\u{22714}\u4989\u{26626}\u{23DE3}\u{266E8}\u6725\u80A7\u{28A48}\u8107\u811A\u58B0\u{226F6}\u6C7F\u{26498}\u{24FB8}\u64E7\u{2148A}\u8218\u{2185E}\u6A53\u{24A65}\u{24A95}\u447A\u8229\u{20B0D}\u{26A52}\u{23D7E}\u4FF9\u{214FD}\u84E2\u8362\u{26B0A}\u{249A7}\u{23530}\u{21773}\u{23DF8}\u82AA\u691B\u{2F994}\u41DB"], + ["8f40", "\u854B\u82D0\u831A\u{20E16}\u{217B4}\u36C1\u{2317D}\u{2355A}\u827B\u82E2\u8318\u{23E8B}\u{26DA3}\u{26B05}\u{26B97}\u{235CE}\u3DBF\u831D\u55EC\u8385\u450B\u{26DA5}\u83AC\u83C1\u83D3\u347E\u{26ED4}\u6A57\u855A\u3496\u{26E42}\u{22EEF}\u8458\u{25BE4}\u8471\u3DD3\u44E4\u6AA7\u844A\u{23CB5}\u7958\u84A8\u{26B96}\u{26E77}\u{26E43}\u84DE\u840F\u8391\u44A0\u8493\u84E4\u{25C91}\u4240\u{25CC0}\u4543\u8534\u5AF2\u{26E99}\u4527\u8573\u4516\u67BF\u8616"], + ["8fa1", "\u{28625}\u{2863B}\u85C1\u{27088}\u8602\u{21582}\u{270CD}\u{2F9B2}\u456A\u8628\u3648\u{218A2}\u53F7\u{2739A}\u867E\u8771\u{2A0F8}\u87EE\u{22C27}\u87B1\u87DA\u880F\u5661\u866C\u6856\u460F\u8845\u8846\u{275E0}\u{23DB9}\u{275E4}\u885E\u889C\u465B\u88B4\u88B5\u63C1\u88C5\u7777\u{2770F}\u8987\u898A\u89A6\u89A9\u89A7\u89BC\u{28A25}\u89E7\u{27924}\u{27ABD}\u8A9C\u7793\u91FE\u8A90\u{27A59}\u7AE9\u{27B3A}\u{23F8F}\u4713\u{27B38}\u717C\u8B0C\u8B1F\u{25430}\u{25565}\u8B3F\u8B4C\u8B4D\u8AA9\u{24A7A}\u8B90\u8B9B\u8AAF\u{216DF}\u4615\u884F\u8C9B\u{27D54}\u{27D8F}\u{2F9D4}\u3725\u{27D53}\u8CD6\u{27D98}\u{27DBD}\u8D12\u8D03\u{21910}\u8CDB\u705C\u8D11\u{24CC9}\u3ED0\u8D77"], + ["9040", "\u8DA9\u{28002}\u{21014}\u{2498A}\u3B7C\u{281BC}\u{2710C}\u7AE7\u8EAD\u8EB6\u8EC3\u92D4\u8F19\u8F2D\u{28365}\u{28412}\u8FA5\u9303\u{2A29F}\u{20A50}\u8FB3\u492A\u{289DE}\u{2853D}\u{23DBB}\u5EF8\u{23262}\u8FF9\u{2A014}\u{286BC}\u{28501}\u{22325}\u3980\u{26ED7}\u9037\u{2853C}\u{27ABE}\u9061\u{2856C}\u{2860B}\u90A8\u{28713}\u90C4\u{286E6}\u90AE\u90FD\u9167\u3AF0\u91A9\u91C4\u7CAC\u{28933}\u{21E89}\u920E\u6C9F\u9241\u9262\u{255B9}\u92B9\u{28AC6}\u{23C9B}\u{28B0C}\u{255DB}"], + ["90a1", "\u{20D31}\u932C\u936B\u{28AE1}\u{28BEB}\u708F\u5AC3\u{28AE2}\u{28AE5}\u4965\u9244\u{28BEC}\u{28C39}\u{28BFF}\u9373\u945B\u8EBC\u9585\u95A6\u9426\u95A0\u6FF6\u42B9\u{2267A}\u{286D8}\u{2127C}\u{23E2E}\u49DF\u6C1C\u967B\u9696\u416C\u96A3\u{26ED5}\u61DA\u96B6\u78F5\u{28AE0}\u96BD\u53CC\u49A1\u{26CB8}\u{20274}\u{26410}\u{290AF}\u{290E5}\u{24AD1}\u{21915}\u{2330A}\u9731\u8642\u9736\u4A0F\u453D\u4585\u{24AE9}\u7075\u5B41\u971B\u975C\u{291D5}\u9757\u5B4A\u{291EB}\u975F\u9425\u50D0\u{230B7}\u{230BC}\u9789\u979F\u97B1\u97BE\u97C0\u97D2\u97E0\u{2546C}\u97EE\u741C\u{29433}\u97FF\u97F5\u{2941D}\u{2797A}\u4AD1\u9834\u9833\u984B\u9866\u3B0E\u{27175}\u3D51\u{20630}\u{2415C}"], + ["9140", "\u{25706}\u98CA\u98B7\u98C8\u98C7\u4AFF\u{26D27}\u{216D3}\u55B0\u98E1\u98E6\u98EC\u9378\u9939\u{24A29}\u4B72\u{29857}\u{29905}\u99F5\u9A0C\u9A3B\u9A10\u9A58\u{25725}\u36C4\u{290B1}\u{29BD5}\u9AE0\u9AE2\u{29B05}\u9AF4\u4C0E\u9B14\u9B2D\u{28600}\u5034\u9B34\u{269A8}\u38C3\u{2307D}\u9B50\u9B40\u{29D3E}\u5A45\u{21863}\u9B8E\u{2424B}\u9C02\u9BFF\u9C0C\u{29E68}\u9DD4\u{29FB7}\u{2A192}\u{2A1AB}\u{2A0E1}\u{2A123}\u{2A1DF}\u9D7E\u9D83\u{2A134}\u9E0E\u6888"], + ["91a1", "\u9DC4\u{2215B}\u{2A193}\u{2A220}\u{2193B}\u{2A233}\u9D39\u{2A0B9}\u{2A2B4}\u9E90\u9E95\u9E9E\u9EA2\u4D34\u9EAA\u9EAF\u{24364}\u9EC1\u3B60\u39E5\u3D1D\u4F32\u37BE\u{28C2B}\u9F02\u9F08\u4B96\u9424\u{26DA2}\u9F17\u9F16\u9F39\u569F\u568A\u9F45\u99B8\u{2908B}\u97F2\u847F\u9F62\u9F69\u7ADC\u9F8E\u7216\u4BBE\u{24975}\u{249BB}\u7177\u{249F8}\u{24348}\u{24A51}\u739E\u{28BDA}\u{218FA}\u799F\u{2897E}\u{28E36}\u9369\u93F3\u{28A44}\u92EC\u9381\u93CB\u{2896C}\u{244B9}\u7217\u3EEB\u7772\u7A43\u70D0\u{24473}\u{243F8}\u717E\u{217EF}\u70A3\u{218BE}\u{23599}\u3EC7\u{21885}\u{2542F}\u{217F8}\u3722\u{216FB}\u{21839}\u36E1\u{21774}\u{218D1}\u{25F4B}\u3723\u{216C0}\u575B\u{24A25}\u{213FE}\u{212A8}"], + ["9240", "\u{213C6}\u{214B6}\u8503\u{236A6}\u8503\u8455\u{24994}\u{27165}\u{23E31}\u{2555C}\u{23EFB}\u{27052}\u44F4\u{236EE}\u{2999D}\u{26F26}\u67F9\u3733\u3C15\u3DE7\u586C\u{21922}\u6810\u4057\u{2373F}\u{240E1}\u{2408B}\u{2410F}\u{26C21}\u54CB\u569E\u{266B1}\u5692\u{20FDF}\u{20BA8}\u{20E0D}\u93C6\u{28B13}\u939C\u4EF8\u512B\u3819\u{24436}\u4EBC\u{20465}\u{2037F}\u4F4B\u4F8A\u{25651}\u5A68\u{201AB}\u{203CB}\u3999\u{2030A}\u{20414}\u3435\u4F29\u{202C0}\u{28EB3}\u{20275}\u8ADA\u{2020C}\u4E98"], + ["92a1", "\u50CD\u510D\u4FA2\u4F03\u{24A0E}\u{23E8A}\u4F42\u502E\u506C\u5081\u4FCC\u4FE5\u5058\u50FC\u5159\u515B\u515D\u515E\u6E76\u{23595}\u{23E39}\u{23EBF}\u6D72\u{21884}\u{23E89}\u51A8\u51C3\u{205E0}\u44DD\u{204A3}\u{20492}\u{20491}\u8D7A\u{28A9C}\u{2070E}\u5259\u52A4\u{20873}\u52E1\u936E\u467A\u718C\u{2438C}\u{20C20}\u{249AC}\u{210E4}\u69D1\u{20E1D}\u7479\u3EDE\u7499\u7414\u7456\u7398\u4B8E\u{24ABC}\u{2408D}\u53D0\u3584\u720F\u{240C9}\u55B4\u{20345}\u54CD\u{20BC6}\u571D\u925D\u96F4\u9366\u57DD\u578D\u577F\u363E\u58CB\u5A99\u{28A46}\u{216FA}\u{2176F}\u{21710}\u5A2C\u59B8\u928F\u5A7E\u5ACF\u5A12\u{25946}\u{219F3}\u{21861}\u{24295}\u36F5\u6D05\u7443\u5A21\u{25E83}"], + ["9340", "\u5A81\u{28BD7}\u{20413}\u93E0\u748C\u{21303}\u7105\u4972\u9408\u{289FB}\u93BD\u37A0\u5C1E\u5C9E\u5E5E\u5E48\u{21996}\u{2197C}\u{23AEE}\u5ECD\u5B4F\u{21903}\u{21904}\u3701\u{218A0}\u36DD\u{216FE}\u36D3\u812A\u{28A47}\u{21DBA}\u{23472}\u{289A8}\u5F0C\u5F0E\u{21927}\u{217AB}\u5A6B\u{2173B}\u5B44\u8614\u{275FD}\u8860\u607E\u{22860}\u{2262B}\u5FDB\u3EB8\u{225AF}\u{225BE}\u{29088}\u{26F73}\u61C0\u{2003E}\u{20046}\u{2261B}\u6199\u6198\u6075\u{22C9B}\u{22D07}\u{246D4}\u{2914D}"], + ["93a1", "\u6471\u{24665}\u{22B6A}\u3A29\u{22B22}\u{23450}\u{298EA}\u{22E78}\u6337\u{2A45B}\u64B6\u6331\u63D1\u{249E3}\u{22D67}\u62A4\u{22CA1}\u643B\u656B\u6972\u3BF4\u{2308E}\u{232AD}\u{24989}\u{232AB}\u550D\u{232E0}\u{218D9}\u{2943F}\u66CE\u{23289}\u{231B3}\u3AE0\u4190\u{25584}\u{28B22}\u{2558F}\u{216FC}\u{2555B}\u{25425}\u78EE\u{23103}\u{2182A}\u{23234}\u3464\u{2320F}\u{23182}\u{242C9}\u668E\u{26D24}\u666B\u4B93\u6630\u{27870}\u{21DEB}\u6663\u{232D2}\u{232E1}\u661E\u{25872}\u38D1\u{2383A}\u{237BC}\u3B99\u{237A2}\u{233FE}\u74D0\u3B96\u678F\u{2462A}\u68B6\u681E\u3BC4\u6ABE\u3863\u{237D5}\u{24487}\u6A33\u6A52\u6AC9\u6B05\u{21912}\u6511\u6898\u6A4C\u3BD7\u6A7A\u6B57\u{23FC0}\u{23C9A}\u93A0\u92F2\u{28BEA}\u{28ACB}"], + ["9440", "\u9289\u{2801E}\u{289DC}\u9467\u6DA5\u6F0B\u{249EC}\u6D67\u{23F7F}\u3D8F\u6E04\u{2403C}\u5A3D\u6E0A\u5847\u6D24\u7842\u713B\u{2431A}\u{24276}\u70F1\u7250\u7287\u7294\u{2478F}\u{24725}\u5179\u{24AA4}\u{205EB}\u747A\u{23EF8}\u{2365F}\u{24A4A}\u{24917}\u{25FE1}\u3F06\u3EB1\u{24ADF}\u{28C23}\u{23F35}\u60A7\u3EF3\u74CC\u743C\u9387\u7437\u449F\u{26DEA}\u4551\u7583\u3F63\u{24CD9}\u{24D06}\u3F58\u7555\u7673\u{2A5C6}\u3B19\u7468\u{28ACC}\u{249AB}\u{2498E}\u3AFB"], + ["94a1", "\u3DCD\u{24A4E}\u3EFF\u{249C5}\u{248F3}\u91FA\u5732\u9342\u{28AE3}\u{21864}\u50DF\u{25221}\u{251E7}\u7778\u{23232}\u770E\u770F\u777B\u{24697}\u{23781}\u3A5E\u{248F0}\u7438\u749B\u3EBF\u{24ABA}\u{24AC7}\u40C8\u{24A96}\u{261AE}\u9307\u{25581}\u781E\u788D\u7888\u78D2\u73D0\u7959\u{27741}\u{256E3}\u410E\u799B\u8496\u79A5\u6A2D\u{23EFA}\u7A3A\u79F4\u416E\u{216E6}\u4132\u9235\u79F1\u{20D4C}\u{2498C}\u{20299}\u{23DBA}\u{2176E}\u3597\u556B\u3570\u36AA\u{201D4}\u{20C0D}\u7AE2\u5A59\u{226F5}\u{25AAF}\u{25A9C}\u5A0D\u{2025B}\u78F0\u5A2A\u{25BC6}\u7AFE\u41F9\u7C5D\u7C6D\u4211\u{25BB3}\u{25EBC}\u{25EA6}\u7CCD\u{249F9}\u{217B0}\u7C8E\u7C7C\u7CAE\u6AB2\u7DDC\u7E07\u7DD3\u7F4E\u{26261}"], + ["9540", "\u{2615C}\u{27B48}\u7D97\u{25E82}\u426A\u{26B75}\u{20916}\u67D6\u{2004E}\u{235CF}\u57C4\u{26412}\u{263F8}\u{24962}\u7FDD\u7B27\u{2082C}\u{25AE9}\u{25D43}\u7B0C\u{25E0E}\u99E6\u8645\u9A63\u6A1C\u{2343F}\u39E2\u{249F7}\u{265AD}\u9A1F\u{265A0}\u8480\u{27127}\u{26CD1}\u44EA\u8137\u4402\u80C6\u8109\u8142\u{267B4}\u98C3\u{26A42}\u8262\u8265\u{26A51}\u8453\u{26DA7}\u8610\u{2721B}\u5A86\u417F\u{21840}\u5B2B\u{218A1}\u5AE4\u{218D8}\u86A0\u{2F9BC}\u{23D8F}\u882D\u{27422}\u5A02"], + ["95a1", "\u886E\u4F45\u8887\u88BF\u88E6\u8965\u894D\u{25683}\u8954\u{27785}\u{27784}\u{28BF5}\u{28BD9}\u{28B9C}\u{289F9}\u3EAD\u84A3\u46F5\u46CF\u37F2\u8A3D\u8A1C\u{29448}\u5F4D\u922B\u{24284}\u65D4\u7129\u70C4\u{21845}\u9D6D\u8C9F\u8CE9\u{27DDC}\u599A\u77C3\u59F0\u436E\u36D4\u8E2A\u8EA7\u{24C09}\u8F30\u8F4A\u42F4\u6C58\u6FBB\u{22321}\u489B\u6F79\u6E8B\u{217DA}\u9BE9\u36B5\u{2492F}\u90BB\u9097\u5571\u4906\u91BB\u9404\u{28A4B}\u4062\u{28AFC}\u9427\u{28C1D}\u{28C3B}\u84E5\u8A2B\u9599\u95A7\u9597\u9596\u{28D34}\u7445\u3EC2\u{248FF}\u{24A42}\u{243EA}\u3EE7\u{23225}\u968F\u{28EE7}\u{28E66}\u{28E65}\u3ECC\u{249ED}\u{24A78}\u{23FEE}\u7412\u746B\u3EFC\u9741\u{290B0}"], + ["9640", "\u6847\u4A1D\u{29093}\u{257DF}\u975D\u9368\u{28989}\u{28C26}\u{28B2F}\u{263BE}\u92BA\u5B11\u8B69\u493C\u73F9\u{2421B}\u979B\u9771\u9938\u{20F26}\u5DC1\u{28BC5}\u{24AB2}\u981F\u{294DA}\u92F6\u{295D7}\u91E5\u44C0\u{28B50}\u{24A67}\u{28B64}\u98DC\u{28A45}\u3F00\u922A\u4925\u8414\u993B\u994D\u{27B06}\u3DFD\u999B\u4B6F\u99AA\u9A5C\u{28B65}\u{258C8}\u6A8F\u9A21\u5AFE\u9A2F\u{298F1}\u4B90\u{29948}\u99BC\u4BBD\u4B97\u937D\u5872\u{21302}\u5822\u{249B8}"], + ["96a1", "\u{214E8}\u7844\u{2271F}\u{23DB8}\u68C5\u3D7D\u9458\u3927\u6150\u{22781}\u{2296B}\u6107\u9C4F\u9C53\u9C7B\u9C35\u9C10\u9B7F\u9BCF\u{29E2D}\u9B9F\u{2A1F5}\u{2A0FE}\u9D21\u4CAE\u{24104}\u9E18\u4CB0\u9D0C\u{2A1B4}\u{2A0ED}\u{2A0F3}\u{2992F}\u9DA5\u84BD\u{26E12}\u{26FDF}\u{26B82}\u85FC\u4533\u{26DA4}\u{26E84}\u{26DF0}\u8420\u85EE\u{26E00}\u{237D7}\u{26064}\u79E2\u{2359C}\u{23640}\u492D\u{249DE}\u3D62\u93DB\u92BE\u9348\u{202BF}\u78B9\u9277\u944D\u4FE4\u3440\u9064\u{2555D}\u783D\u7854\u78B6\u784B\u{21757}\u{231C9}\u{24941}\u369A\u4F72\u6FDA\u6FD9\u701E\u701E\u5414\u{241B5}\u57BB\u58F3\u578A\u9D16\u57D7\u7134\u34AF\u{241AC}\u71EB\u{26C40}\u{24F97}\u5B28\u{217B5}\u{28A49}"], + ["9740", "\u610C\u5ACE\u5A0B\u42BC\u{24488}\u372C\u4B7B\u{289FC}\u93BB\u93B8\u{218D6}\u{20F1D}\u8472\u{26CC0}\u{21413}\u{242FA}\u{22C26}\u{243C1}\u5994\u{23DB7}\u{26741}\u7DA8\u{2615B}\u{260A4}\u{249B9}\u{2498B}\u{289FA}\u92E5\u73E2\u3EE9\u74B4\u{28B63}\u{2189F}\u3EE1\u{24AB3}\u6AD8\u73F3\u73FB\u3ED6\u{24A3E}\u{24A94}\u{217D9}\u{24A66}\u{203A7}\u{21424}\u{249E5}\u7448\u{24916}\u70A5\u{24976}\u9284\u73E6\u935F\u{204FE}\u9331\u{28ACE}\u{28A16}\u9386\u{28BE7}\u{255D5}\u4935\u{28A82}\u716B"], + ["97a1", "\u{24943}\u{20CFF}\u56A4\u{2061A}\u{20BEB}\u{20CB8}\u5502\u79C4\u{217FA}\u7DFE\u{216C2}\u{24A50}\u{21852}\u452E\u9401\u370A\u{28AC0}\u{249AD}\u59B0\u{218BF}\u{21883}\u{27484}\u5AA1\u36E2\u{23D5B}\u36B0\u925F\u5A79\u{28A81}\u{21862}\u9374\u3CCD\u{20AB4}\u4A96\u398A\u50F4\u3D69\u3D4C\u{2139C}\u7175\u42FB\u{28218}\u6E0F\u{290E4}\u44EB\u6D57\u{27E4F}\u7067\u6CAF\u3CD6\u{23FED}\u{23E2D}\u6E02\u6F0C\u3D6F\u{203F5}\u7551\u36BC\u34C8\u4680\u3EDA\u4871\u59C4\u926E\u493E\u8F41\u{28C1C}\u{26BC0}\u5812\u57C8\u36D6\u{21452}\u70FE\u{24362}\u{24A71}\u{22FE3}\u{212B0}\u{223BD}\u68B9\u6967\u{21398}\u{234E5}\u{27BF4}\u{236DF}\u{28A83}\u{237D6}\u{233FA}\u{24C9F}\u6A1A\u{236AD}\u{26CB7}\u843E\u44DF\u44CE"], + ["9840", "\u{26D26}\u{26D51}\u{26C82}\u{26FDE}\u6F17\u{27109}\u833D\u{2173A}\u83ED\u{26C80}\u{27053}\u{217DB}\u5989\u5A82\u{217B3}\u5A61\u5A71\u{21905}\u{241FC}\u372D\u59EF\u{2173C}\u36C7\u718E\u9390\u669A\u{242A5}\u5A6E\u5A2B\u{24293}\u6A2B\u{23EF9}\u{27736}\u{2445B}\u{242CA}\u711D\u{24259}\u{289E1}\u4FB0\u{26D28}\u5CC2\u{244CE}\u{27E4D}\u{243BD}\u6A0C\u{24256}\u{21304}\u70A6\u7133\u{243E9}\u3DA5\u6CDF\u{2F825}\u{24A4F}\u7E65\u59EB\u5D2F\u3DF3\u5F5C\u{24A5D}\u{217DF}\u7DA4\u8426"], + ["98a1", "\u5485\u{23AFA}\u{23300}\u{20214}\u577E\u{208D5}\u{20619}\u3FE5\u{21F9E}\u{2A2B6}\u7003\u{2915B}\u5D70\u738F\u7CD3\u{28A59}\u{29420}\u4FC8\u7FE7\u72CD\u7310\u{27AF4}\u7338\u7339\u{256F6}\u7341\u7348\u3EA9\u{27B18}\u906C\u71F5\u{248F2}\u73E1\u81F6\u3ECA\u770C\u3ED1\u6CA2\u56FD\u7419\u741E\u741F\u3EE2\u3EF0\u3EF4\u3EFA\u74D3\u3F0E\u3F53\u7542\u756D\u7572\u758D\u3F7C\u75C8\u75DC\u3FC0\u764D\u3FD7\u7674\u3FDC\u767A\u{24F5C}\u7188\u5623\u8980\u5869\u401D\u7743\u4039\u6761\u4045\u35DB\u7798\u406A\u406F\u5C5E\u77BE\u77CB\u58F2\u7818\u70B9\u781C\u40A8\u7839\u7847\u7851\u7866\u8448\u{25535}\u7933\u6803\u7932\u4103"], + ["9940", "\u4109\u7991\u7999\u8FBB\u7A06\u8FBC\u4167\u7A91\u41B2\u7ABC\u8279\u41C4\u7ACF\u7ADB\u41CF\u4E21\u7B62\u7B6C\u7B7B\u7C12\u7C1B\u4260\u427A\u7C7B\u7C9C\u428C\u7CB8\u4294\u7CED\u8F93\u70C0\u{20CCF}\u7DCF\u7DD4\u7DD0\u7DFD\u7FAE\u7FB4\u729F\u4397\u8020\u8025\u7B39\u802E\u8031\u8054\u3DCC\u57B4\u70A0\u80B7\u80E9\u43ED\u810C\u732A\u810E\u8112\u7560\u8114\u4401\u3B39\u8156\u8159\u815A"], + ["99a1", "\u4413\u583A\u817C\u8184\u4425\u8193\u442D\u81A5\u57EF\u81C1\u81E4\u8254\u448F\u82A6\u8276\u82CA\u82D8\u82FF\u44B0\u8357\u9669\u698A\u8405\u70F5\u8464\u60E3\u8488\u4504\u84BE\u84E1\u84F8\u8510\u8538\u8552\u453B\u856F\u8570\u85E0\u4577\u8672\u8692\u86B2\u86EF\u9645\u878B\u4606\u4617\u88AE\u88FF\u8924\u8947\u8991\u{27967}\u8A29\u8A38\u8A94\u8AB4\u8C51\u8CD4\u8CF2\u8D1C\u4798\u585F\u8DC3\u47ED\u4EEE\u8E3A\u55D8\u5754\u8E71\u55F5\u8EB0\u4837\u8ECE\u8EE2\u8EE4\u8EED\u8EF2\u8FB7\u8FC1\u8FCA\u8FCC\u9033\u99C4\u48AD\u98E0\u9213\u491E\u9228\u9258\u926B\u92B1\u92AE\u92BF"], + ["9a40", "\u92E3\u92EB\u92F3\u92F4\u92FD\u9343\u9384\u93AD\u4945\u4951\u9EBF\u9417\u5301\u941D\u942D\u943E\u496A\u9454\u9479\u952D\u95A2\u49A7\u95F4\u9633\u49E5\u67A0\u4A24\u9740\u4A35\u97B2\u97C2\u5654\u4AE4\u60E8\u98B9\u4B19\u98F1\u5844\u990E\u9919\u51B4\u991C\u9937\u9942\u995D\u9962\u4B70\u99C5\u4B9D\u9A3C\u9B0F\u7A83\u9B69\u9B81\u9BDD\u9BF1\u9BF4\u4C6D\u9C20\u376F\u{21BC2}\u9D49\u9C3A"], + ["9aa1", "\u9EFE\u5650\u9D93\u9DBD\u9DC0\u9DFC\u94F6\u8FB6\u9E7B\u9EAC\u9EB1\u9EBD\u9EC6\u94DC\u9EE2\u9EF1\u9EF8\u7AC8\u9F44\u{20094}\u{202B7}\u{203A0}\u691A\u94C3\u59AC\u{204D7}\u5840\u94C1\u37B9\u{205D5}\u{20615}\u{20676}\u{216BA}\u5757\u7173\u{20AC2}\u{20ACD}\u{20BBF}\u546A\u{2F83B}\u{20BCB}\u549E\u{20BFB}\u{20C3B}\u{20C53}\u{20C65}\u{20C7C}\u60E7\u{20C8D}\u567A\u{20CB5}\u{20CDD}\u{20CED}\u{20D6F}\u{20DB2}\u{20DC8}\u6955\u9C2F\u87A5\u{20E04}\u{20E0E}\u{20ED7}\u{20F90}\u{20F2D}\u{20E73}\u5C20\u{20FBC}\u5E0B\u{2105C}\u{2104F}\u{21076}\u671E\u{2107B}\u{21088}\u{21096}\u3647\u{210BF}\u{210D3}\u{2112F}\u{2113B}\u5364\u84AD\u{212E3}\u{21375}\u{21336}\u8B81\u{21577}\u{21619}\u{217C3}\u{217C7}\u4E78\u70BB\u{2182D}\u{2196A}"], + ["9b40", "\u{21A2D}\u{21A45}\u{21C2A}\u{21C70}\u{21CAC}\u{21EC8}\u62C3\u{21ED5}\u{21F15}\u7198\u6855\u{22045}\u69E9\u36C8\u{2227C}\u{223D7}\u{223FA}\u{2272A}\u{22871}\u{2294F}\u82FD\u{22967}\u{22993}\u{22AD5}\u89A5\u{22AE8}\u8FA0\u{22B0E}\u97B8\u{22B3F}\u9847\u9ABD\u{22C4C}"], + ["9b62", "\u{22C88}\u{22CB7}\u{25BE8}\u{22D08}\u{22D12}\u{22DB7}\u{22D95}\u{22E42}\u{22F74}\u{22FCC}\u{23033}\u{23066}\u{2331F}\u{233DE}\u5FB1\u6648\u66BF\u{27A79}\u{23567}\u{235F3}\u7201\u{249BA}\u77D7\u{2361A}\u{23716}\u7E87\u{20346}\u58B5\u670E"], + ["9ba1", "\u6918\u{23AA7}\u{27657}\u{25FE2}\u{23E11}\u{23EB9}\u{275FE}\u{2209A}\u48D0\u4AB8\u{24119}\u{28A9A}\u{242EE}\u{2430D}\u{2403B}\u{24334}\u{24396}\u{24A45}\u{205CA}\u51D2\u{20611}\u599F\u{21EA8}\u3BBE\u{23CFF}\u{24404}\u{244D6}\u5788\u{24674}\u399B\u{2472F}\u{285E8}\u{299C9}\u3762\u{221C3}\u8B5E\u{28B4E}\u99D6\u{24812}\u{248FB}\u{24A15}\u7209\u{24AC0}\u{20C78}\u5965\u{24EA5}\u{24F86}\u{20779}\u8EDA\u{2502C}\u528F\u573F\u7171\u{25299}\u{25419}\u{23F4A}\u{24AA7}\u55BC\u{25446}\u{2546E}\u{26B52}\u91D4\u3473\u{2553F}\u{27632}\u{2555E}\u4718\u{25562}\u{25566}\u{257C7}\u{2493F}\u{2585D}\u5066\u34FB\u{233CC}\u60DE\u{25903}\u477C\u{28948}\u{25AAE}\u{25B89}\u{25C06}\u{21D90}\u57A1\u7151\u6FB6\u{26102}\u{27C12}\u9056\u{261B2}\u{24F9A}\u8B62\u{26402}\u{2644A}"], + ["9c40", "\u5D5B\u{26BF7}\u8F36\u{26484}\u{2191C}\u8AEA\u{249F6}\u{26488}\u{23FEF}\u{26512}\u4BC0\u{265BF}\u{266B5}\u{2271B}\u9465\u{257E1}\u6195\u5A27\u{2F8CD}\u4FBB\u56B9\u{24521}\u{266FC}\u4E6A\u{24934}\u9656\u6D8F\u{26CBD}\u3618\u8977\u{26799}\u{2686E}\u{26411}\u{2685E}\u71DF\u{268C7}\u7B42\u{290C0}\u{20A11}\u{26926}\u9104\u{26939}\u7A45\u9DF0\u{269FA}\u9A26\u{26A2D}\u365F\u{26469}\u{20021}\u7983\u{26A34}\u{26B5B}\u5D2C\u{23519}\u83CF\u{26B9D}\u46D0\u{26CA4}\u753B\u8865\u{26DAE}\u58B6"], + ["9ca1", "\u371C\u{2258D}\u{2704B}\u{271CD}\u3C54\u{27280}\u{27285}\u9281\u{2217A}\u{2728B}\u9330\u{272E6}\u{249D0}\u6C39\u949F\u{27450}\u{20EF8}\u8827\u88F5\u{22926}\u{28473}\u{217B1}\u6EB8\u{24A2A}\u{21820}\u39A4\u36B9\u5C10\u79E3\u453F\u66B6\u{29CAD}\u{298A4}\u8943\u{277CC}\u{27858}\u56D6\u40DF\u{2160A}\u39A1\u{2372F}\u{280E8}\u{213C5}\u71AD\u8366\u{279DD}\u{291A8}\u5A67\u4CB7\u{270AF}\u{289AB}\u{279FD}\u{27A0A}\u{27B0B}\u{27D66}\u{2417A}\u7B43\u797E\u{28009}\u6FB5\u{2A2DF}\u6A03\u{28318}\u53A2\u{26E07}\u93BF\u6836\u975D\u{2816F}\u{28023}\u{269B5}\u{213ED}\u{2322F}\u{28048}\u5D85\u{28C30}\u{28083}\u5715\u9823\u{28949}\u5DAB\u{24988}\u65BE\u69D5\u53D2\u{24AA5}\u{23F81}\u3C11\u6736\u{28090}\u{280F4}\u{2812E}\u{21FA1}\u{2814F}"], + ["9d40", "\u{28189}\u{281AF}\u{2821A}\u{28306}\u{2832F}\u{2838A}\u35CA\u{28468}\u{286AA}\u48FA\u63E6\u{28956}\u7808\u9255\u{289B8}\u43F2\u{289E7}\u43DF\u{289E8}\u{28B46}\u{28BD4}\u59F8\u{28C09}\u8F0B\u{28FC5}\u{290EC}\u7B51\u{29110}\u{2913C}\u3DF7\u{2915E}\u{24ACA}\u8FD0\u728F\u568B\u{294E7}\u{295E9}\u{295B0}\u{295B8}\u{29732}\u{298D1}\u{29949}\u{2996A}\u{299C3}\u{29A28}\u{29B0E}\u{29D5A}\u{29D9B}\u7E9F\u{29EF8}\u{29F23}\u4CA4\u9547\u{2A293}\u71A2\u{2A2FF}\u4D91\u9012\u{2A5CB}\u4D9C\u{20C9C}\u8FBE\u55C1"], + ["9da1", "\u8FBA\u{224B0}\u8FB9\u{24A93}\u4509\u7E7F\u6F56\u6AB1\u4EEA\u34E4\u{28B2C}\u{2789D}\u373A\u8E80\u{217F5}\u{28024}\u{28B6C}\u{28B99}\u{27A3E}\u{266AF}\u3DEB\u{27655}\u{23CB7}\u{25635}\u{25956}\u4E9A\u{25E81}\u{26258}\u56BF\u{20E6D}\u8E0E\u5B6D\u{23E88}\u{24C9E}\u63DE\u62D0\u{217F6}\u{2187B}\u6530\u562D\u{25C4A}\u541A\u{25311}\u3DC6\u{29D98}\u4C7D\u5622\u561E\u7F49\u{25ED8}\u5975\u{23D40}\u8770\u4E1C\u{20FEA}\u{20D49}\u{236BA}\u8117\u9D5E\u8D18\u763B\u9C45\u764E\u77B9\u9345\u5432\u8148\u82F7\u5625\u8132\u8418\u80BD\u55EA\u7962\u5643\u5416\u{20E9D}\u35CE\u5605\u55F1\u66F1\u{282E2}\u362D\u7534\u55F0\u55BA\u5497\u5572\u{20C41}\u{20C96}\u5ED0\u{25148}\u{20E76}\u{22C62}"], + ["9e40", "\u{20EA2}\u9EAB\u7D5A\u55DE\u{21075}\u629D\u976D\u5494\u8CCD\u71F6\u9176\u63FC\u63B9\u63FE\u5569\u{22B43}\u9C72\u{22EB3}\u519A\u34DF\u{20DA7}\u51A7\u544D\u551E\u5513\u7666\u8E2D\u{2688A}\u75B1\u80B6\u8804\u8786\u88C7\u81B6\u841C\u{210C1}\u44EC\u7304\u{24706}\u5B90\u830B\u{26893}\u567B\u{226F4}\u{27D2F}\u{241A3}\u{27D73}\u{26ED0}\u{272B6}\u9170\u{211D9}\u9208\u{23CFC}\u{2A6A9}\u{20EAC}\u{20EF9}\u7266\u{21CA2}\u474E\u{24FC2}\u{27FF9}\u{20FEB}\u40FA"], + ["9ea1", "\u9C5D\u651F\u{22DA0}\u48F3\u{247E0}\u{29D7C}\u{20FEC}\u{20E0A}\u6062\u{275A3}\u{20FED}"], + ["9ead", "\u{26048}\u{21187}\u71A3\u7E8E\u9D50\u4E1A\u4E04\u3577\u5B0D\u6CB2\u5367\u36AC\u39DC\u537D\u36A5\u{24618}\u589A\u{24B6E}\u822D\u544B\u57AA\u{25A95}\u{20979}"], + ["9ec5", "\u3A52\u{22465}\u7374\u{29EAC}\u4D09\u9BED\u{23CFE}\u{29F30}\u4C5B\u{24FA9}\u{2959E}\u{29FDE}\u845C\u{23DB6}\u{272B2}\u{267B3}\u{23720}\u632E\u7D25\u{23EF7}\u{23E2C}\u3A2A\u9008\u52CC\u3E74\u367A\u45E9\u{2048E}\u7640\u5AF0\u{20EB6}\u787A\u{27F2E}\u58A7\u40BF\u567C\u9B8B\u5D74\u7654\u{2A434}\u9E85\u4CE1\u75F9\u37FB\u6119\u{230DA}\u{243F2}"], + ["9ef5", "\u565D\u{212A9}\u57A7\u{24963}\u{29E06}\u5234\u{270AE}\u35AD\u6C4A\u9D7C"], + ["9f40", "\u7C56\u9B39\u57DE\u{2176C}\u5C53\u64D3\u{294D0}\u{26335}\u{27164}\u86AD\u{20D28}\u{26D22}\u{24AE2}\u{20D71}"], + ["9f4f", "\u51FE\u{21F0F}\u5D8E\u9703\u{21DD1}\u9E81\u904C\u7B1F\u9B02\u5CD1\u7BA3\u6268\u6335\u9AFF\u7BCF\u9B2A\u7C7E\u9B2E\u7C42\u7C86\u9C15\u7BFC\u9B09\u9F17\u9C1B\u{2493E}\u9F5A\u5573\u5BC3\u4FFD\u9E98\u4FF2\u5260\u3E06\u52D1\u5767\u5056\u59B7\u5E12\u97C8\u9DAB\u8F5C\u5469\u97B4\u9940\u97BA\u532C\u6130"], + ["9fa1", "\u692C\u53DA\u9C0A\u9D02\u4C3B\u9641\u6980\u50A6\u7546\u{2176D}\u99DA\u5273"], + ["9fae", "\u9159\u9681\u915C"], + ["9fb2", "\u9151\u{28E97}\u637F\u{26D23}\u6ACA\u5611\u918E\u757A\u6285\u{203FC}\u734F\u7C70\u{25C21}\u{23CFD}"], + ["9fc1", "\u{24919}\u76D6\u9B9D\u4E2A\u{20CD4}\u83BE\u8842"], + ["9fc9", "\u5C4A\u69C0\u50ED\u577A\u521F\u5DF5\u4ECE\u6C31\u{201F2}\u4F39\u549C\u54DA\u529A\u8D82\u35FE\u5F0C\u35F3"], + ["9fdb", "\u6B52\u917C\u9FA5\u9B97\u982E\u98B4\u9ABA\u9EA8\u9E84\u717A\u7B14"], + ["9fe7", "\u6BFA\u8818\u7F78"], + ["9feb", "\u5620\u{2A64A}\u8E77\u9F53"], + ["9ff0", "\u8DD4\u8E4F\u9E1C\u8E01\u6282\u{2837D}\u8E28\u8E75\u7AD3\u{24A77}\u7A3E\u78D8\u6CEA\u8A67\u7607"], + ["a040", "\u{28A5A}\u9F26\u6CCE\u87D6\u75C3\u{2A2B2}\u7853\u{2F840}\u8D0C\u72E2\u7371\u8B2D\u7302\u74F1\u8CEB\u{24ABB}\u862F\u5FBA\u88A0\u44B7"], + ["a055", "\u{2183B}\u{26E05}"], + ["a058", "\u8A7E\u{2251B}"], + ["a05b", "\u60FD\u7667\u9AD7\u9D44\u936E\u9B8F\u87F5"], + ["a063", "\u880F\u8CF7\u732C\u9721\u9BB0\u35D6\u72B2\u4C07\u7C51\u994A\u{26159}\u6159\u4C04\u9E96\u617D"], + ["a073", "\u575F\u616F\u62A6\u6239\u62CE\u3A5C\u61E2\u53AA\u{233F5}\u6364\u6802\u35D2"], + ["a0a1", "\u5D57\u{28BC2}\u8FDA\u{28E39}"], + ["a0a6", "\u50D9\u{21D46}\u7906\u5332\u9638\u{20F3B}\u4065"], + ["a0ae", "\u77FE"], + ["a0b0", "\u7CC2\u{25F1A}\u7CDA\u7A2D\u8066\u8063\u7D4D\u7505\u74F2\u8994\u821A\u670C\u8062\u{27486}\u805B\u74F0\u8103\u7724\u8989\u{267CC}\u7553\u{26ED1}\u87A9\u87CE\u81C8\u878C\u8A49\u8CAD\u8B43\u772B\u74F8\u84DA\u3635\u69B2\u8DA6"], + ["a0d4", "\u89A9\u7468\u6DB9\u87C1\u{24011}\u74E7\u3DDB\u7176\u60A4\u619C\u3CD1\u7162\u6077"], + ["a0e2", "\u7F71\u{28B2D}\u7250\u60E9\u4B7E\u5220\u3C18\u{23CC7}\u{25ED7}\u{27656}\u{25531}\u{21944}\u{212FE}\u{29903}\u{26DDC}\u{270AD}\u5CC1\u{261AD}\u{28A0F}\u{23677}\u{200EE}\u{26846}\u{24F0E}\u4562\u5B1F\u{2634C}\u9F50\u9EA6\u{2626B}"], + ["a3c0", "\u2400", 31, "\u2421"], + ["c6a1", "\u2460", 9, "\u2474", 9, "\u2170", 9, "\u4E36\u4E3F\u4E85\u4EA0\u5182\u5196\u51AB\u52F9\u5338\u5369\u53B6\u590A\u5B80\u5DDB\u2F33\u5E7F\u5EF4\u5F50\u5F61\u6534\u65E0\u7592\u7676\u8FB5\u96B6\xA8\u02C6\u30FD\u30FE\u309D\u309E\u3003\u4EDD\u3005\u3006\u3007\u30FC\uFF3B\uFF3D\u273D\u3041", 23], + ["c740", "\u3059", 58, "\u30A1\u30A2\u30A3\u30A4"], + ["c7a1", "\u30A5", 81, "\u0410", 5, "\u0401\u0416", 4], + ["c840", "\u041B", 26, "\u0451\u0436", 25, "\u21E7\u21B8\u21B9\u31CF\u{200CC}\u4E5A\u{2008A}\u5202\u4491"], + ["c8a1", "\u9FB0\u5188\u9FB1\u{27607}"], + ["c8cd", "\uFFE2\uFFE4\uFF07\uFF02\u3231\u2116\u2121\u309B\u309C\u2E80\u2E84\u2E86\u2E87\u2E88\u2E8A\u2E8C\u2E8D\u2E95\u2E9C\u2E9D\u2EA5\u2EA7\u2EAA\u2EAC\u2EAE\u2EB6\u2EBC\u2EBE\u2EC6\u2ECA\u2ECC\u2ECD\u2ECF\u2ED6\u2ED7\u2EDE\u2EE3"], + ["c8f5", "\u0283\u0250\u025B\u0254\u0275\u0153\xF8\u014B\u028A\u026A"], + ["f9fe", "\uFFED"], + ["fa40", "\u{20547}\u92DB\u{205DF}\u{23FC5}\u854C\u42B5\u73EF\u51B5\u3649\u{24942}\u{289E4}\u9344\u{219DB}\u82EE\u{23CC8}\u783C\u6744\u62DF\u{24933}\u{289AA}\u{202A0}\u{26BB3}\u{21305}\u4FAB\u{224ED}\u5008\u{26D29}\u{27A84}\u{23600}\u{24AB1}\u{22513}\u5029\u{2037E}\u5FA4\u{20380}\u{20347}\u6EDB\u{2041F}\u507D\u5101\u347A\u510E\u986C\u3743\u8416\u{249A4}\u{20487}\u5160\u{233B4}\u516A\u{20BFF}\u{220FC}\u{202E5}\u{22530}\u{2058E}\u{23233}\u{21983}\u5B82\u877D\u{205B3}\u{23C99}\u51B2\u51B8"], + ["faa1", "\u9D34\u51C9\u51CF\u51D1\u3CDC\u51D3\u{24AA6}\u51B3\u51E2\u5342\u51ED\u83CD\u693E\u{2372D}\u5F7B\u520B\u5226\u523C\u52B5\u5257\u5294\u52B9\u52C5\u7C15\u8542\u52E0\u860D\u{26B13}\u5305\u{28ADE}\u5549\u6ED9\u{23F80}\u{20954}\u{23FEC}\u5333\u5344\u{20BE2}\u6CCB\u{21726}\u681B\u73D5\u604A\u3EAA\u38CC\u{216E8}\u71DD\u44A2\u536D\u5374\u{286AB}\u537E\u537F\u{21596}\u{21613}\u77E6\u5393\u{28A9B}\u53A0\u53AB\u53AE\u73A7\u{25772}\u3F59\u739C\u53C1\u53C5\u6C49\u4E49\u57FE\u53D9\u3AAB\u{20B8F}\u53E0\u{23FEB}\u{22DA3}\u53F6\u{20C77}\u5413\u7079\u552B\u6657\u6D5B\u546D\u{26B53}\u{20D74}\u555D\u548F\u54A4\u47A6\u{2170D}\u{20EDD}\u3DB4\u{20D4D}"], + ["fb40", "\u{289BC}\u{22698}\u5547\u4CED\u542F\u7417\u5586\u55A9\u5605\u{218D7}\u{2403A}\u4552\u{24435}\u66B3\u{210B4}\u5637\u66CD\u{2328A}\u66A4\u66AD\u564D\u564F\u78F1\u56F1\u9787\u53FE\u5700\u56EF\u56ED\u{28B66}\u3623\u{2124F}\u5746\u{241A5}\u6C6E\u708B\u5742\u36B1\u{26C7E}\u57E6\u{21416}\u5803\u{21454}\u{24363}\u5826\u{24BF5}\u585C\u58AA\u3561\u58E0\u58DC\u{2123C}\u58FB\u5BFF\u5743\u{2A150}\u{24278}\u93D3\u35A1\u591F\u68A6\u36C3\u6E59"], + ["fba1", "\u{2163E}\u5A24\u5553\u{21692}\u8505\u59C9\u{20D4E}\u{26C81}\u{26D2A}\u{217DC}\u59D9\u{217FB}\u{217B2}\u{26DA6}\u6D71\u{21828}\u{216D5}\u59F9\u{26E45}\u5AAB\u5A63\u36E6\u{249A9}\u5A77\u3708\u5A96\u7465\u5AD3\u{26FA1}\u{22554}\u3D85\u{21911}\u3732\u{216B8}\u5E83\u52D0\u5B76\u6588\u5B7C\u{27A0E}\u4004\u485D\u{20204}\u5BD5\u6160\u{21A34}\u{259CC}\u{205A5}\u5BF3\u5B9D\u4D10\u5C05\u{21B44}\u5C13\u73CE\u5C14\u{21CA5}\u{26B28}\u5C49\u48DD\u5C85\u5CE9\u5CEF\u5D8B\u{21DF9}\u{21E37}\u5D10\u5D18\u5D46\u{21EA4}\u5CBA\u5DD7\u82FC\u382D\u{24901}\u{22049}\u{22173}\u8287\u3836\u3BC2\u5E2E\u6A8A\u5E75\u5E7A\u{244BC}\u{20CD3}\u53A6\u4EB7\u5ED0\u53A8\u{21771}\u5E09\u5EF4\u{28482}"], + ["fc40", "\u5EF9\u5EFB\u38A0\u5EFC\u683E\u941B\u5F0D\u{201C1}\u{2F894}\u3ADE\u48AE\u{2133A}\u5F3A\u{26888}\u{223D0}\u5F58\u{22471}\u5F63\u97BD\u{26E6E}\u5F72\u9340\u{28A36}\u5FA7\u5DB6\u3D5F\u{25250}\u{21F6A}\u{270F8}\u{22668}\u91D6\u{2029E}\u{28A29}\u6031\u6685\u{21877}\u3963\u3DC7\u3639\u5790\u{227B4}\u7971\u3E40\u609E\u60A4\u60B3\u{24982}\u{2498F}\u{27A53}\u74A4\u50E1\u5AA0\u6164\u8424\u6142\u{2F8A6}\u{26ED2}\u6181\u51F4\u{20656}\u6187\u5BAA\u{23FB7}"], + ["fca1", "\u{2285F}\u61D3\u{28B9D}\u{2995D}\u61D0\u3932\u{22980}\u{228C1}\u6023\u615C\u651E\u638B\u{20118}\u62C5\u{21770}\u62D5\u{22E0D}\u636C\u{249DF}\u3A17\u6438\u63F8\u{2138E}\u{217FC}\u6490\u6F8A\u{22E36}\u9814\u{2408C}\u{2571D}\u64E1\u64E5\u947B\u3A66\u643A\u3A57\u654D\u6F16\u{24A28}\u{24A23}\u6585\u656D\u655F\u{2307E}\u65B5\u{24940}\u4B37\u65D1\u40D8\u{21829}\u65E0\u65E3\u5FDF\u{23400}\u6618\u{231F7}\u{231F8}\u6644\u{231A4}\u{231A5}\u664B\u{20E75}\u6667\u{251E6}\u6673\u6674\u{21E3D}\u{23231}\u{285F4}\u{231C8}\u{25313}\u77C5\u{228F7}\u99A4\u6702\u{2439C}\u{24A21}\u3B2B\u69FA\u{237C2}\u675E\u6767\u6762\u{241CD}\u{290ED}\u67D7\u44E9\u6822\u6E50\u923C\u6801\u{233E6}\u{26DA0}\u685D"], + ["fd40", "\u{2346F}\u69E1\u6A0B\u{28ADF}\u6973\u68C3\u{235CD}\u6901\u6900\u3D32\u3A01\u{2363C}\u3B80\u67AC\u6961\u{28A4A}\u42FC\u6936\u6998\u3BA1\u{203C9}\u8363\u5090\u69F9\u{23659}\u{2212A}\u6A45\u{23703}\u6A9D\u3BF3\u67B1\u6AC8\u{2919C}\u3C0D\u6B1D\u{20923}\u60DE\u6B35\u6B74\u{227CD}\u6EB5\u{23ADB}\u{203B5}\u{21958}\u3740\u5421\u{23B5A}\u6BE1\u{23EFC}\u6BDC\u6C37\u{2248B}\u{248F1}\u{26B51}\u6C5A\u8226\u6C79\u{23DBC}\u44C5\u{23DBD}\u{241A4}\u{2490C}\u{24900}"], + ["fda1", "\u{23CC9}\u36E5\u3CEB\u{20D32}\u9B83\u{231F9}\u{22491}\u7F8F\u6837\u{26D25}\u{26DA1}\u{26DEB}\u6D96\u6D5C\u6E7C\u6F04\u{2497F}\u{24085}\u{26E72}\u8533\u{26F74}\u51C7\u6C9C\u6E1D\u842E\u{28B21}\u6E2F\u{23E2F}\u7453\u{23F82}\u79CC\u6E4F\u5A91\u{2304B}\u6FF8\u370D\u6F9D\u{23E30}\u6EFA\u{21497}\u{2403D}\u4555\u93F0\u6F44\u6F5C\u3D4E\u6F74\u{29170}\u3D3B\u6F9F\u{24144}\u6FD3\u{24091}\u{24155}\u{24039}\u{23FF0}\u{23FB4}\u{2413F}\u51DF\u{24156}\u{24157}\u{24140}\u{261DD}\u704B\u707E\u70A7\u7081\u70CC\u70D5\u70D6\u70DF\u4104\u3DE8\u71B4\u7196\u{24277}\u712B\u7145\u5A88\u714A\u716E\u5C9C\u{24365}\u714F\u9362\u{242C1}\u712C\u{2445A}\u{24A27}\u{24A22}\u71BA\u{28BE8}\u70BD\u720E"], + ["fe40", "\u9442\u7215\u5911\u9443\u7224\u9341\u{25605}\u722E\u7240\u{24974}\u68BD\u7255\u7257\u3E55\u{23044}\u680D\u6F3D\u7282\u732A\u732B\u{24823}\u{2882B}\u48ED\u{28804}\u7328\u732E\u73CF\u73AA\u{20C3A}\u{26A2E}\u73C9\u7449\u{241E2}\u{216E7}\u{24A24}\u6623\u36C5\u{249B7}\u{2498D}\u{249FB}\u73F7\u7415\u6903\u{24A26}\u7439\u{205C3}\u3ED7\u745C\u{228AD}\u7460\u{28EB2}\u7447\u73E4\u7476\u83B9\u746C\u3730\u7474\u93F1\u6A2C\u7482\u4953\u{24A8C}"], + ["fea1", "\u{2415F}\u{24A79}\u{28B8F}\u5B46\u{28C03}\u{2189E}\u74C8\u{21988}\u750E\u74E9\u751E\u{28ED9}\u{21A4B}\u5BD7\u{28EAC}\u9385\u754D\u754A\u7567\u756E\u{24F82}\u3F04\u{24D13}\u758E\u745D\u759E\u75B4\u7602\u762C\u7651\u764F\u766F\u7676\u{263F5}\u7690\u81EF\u37F8\u{26911}\u{2690E}\u76A1\u76A5\u76B7\u76CC\u{26F9F}\u8462\u{2509D}\u{2517D}\u{21E1C}\u771E\u7726\u7740\u64AF\u{25220}\u7758\u{232AC}\u77AF\u{28964}\u{28968}\u{216C1}\u77F4\u7809\u{21376}\u{24A12}\u68CA\u78AF\u78C7\u78D3\u96A5\u792E\u{255E0}\u78D7\u7934\u78B1\u{2760C}\u8FB8\u8884\u{28B2B}\u{26083}\u{2261C}\u7986\u8900\u6902\u7980\u{25857}\u799D\u{27B39}\u793C\u79A9\u6E2A\u{27126}\u3EA8\u79C6\u{2910D}\u79D4"] + ]; + } +}); + +// node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/encodings/dbcs-data.js +var require_dbcs_data = __commonJS({ + "node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/encodings/dbcs-data.js"(exports, module) { + "use strict"; + module.exports = { + // == Japanese/ShiftJIS ==================================================== + // All japanese encodings are based on JIS X set of standards: + // JIS X 0201 - Single-byte encoding of ASCII + ¥ + Kana chars at 0xA1-0xDF. + // JIS X 0208 - Main set of 6879 characters, placed in 94x94 plane, to be encoded by 2 bytes. + // Has several variations in 1978, 1983, 1990 and 1997. + // JIS X 0212 - Supplementary plane of 6067 chars in 94x94 plane. 1990. Effectively dead. + // JIS X 0213 - Extension and modern replacement of 0208 and 0212. Total chars: 11233. + // 2 planes, first is superset of 0208, second - revised 0212. + // Introduced in 2000, revised 2004. Some characters are in Unicode Plane 2 (0x2xxxx) + // Byte encodings are: + // * Shift_JIS: Compatible with 0201, uses not defined chars in top half as lead bytes for double-byte + // encoding of 0208. Lead byte ranges: 0x81-0x9F, 0xE0-0xEF; Trail byte ranges: 0x40-0x7E, 0x80-0x9E, 0x9F-0xFC. + // Windows CP932 is a superset of Shift_JIS. Some companies added more chars, notably KDDI. + // * EUC-JP: Up to 3 bytes per character. Used mostly on *nixes. + // 0x00-0x7F - lower part of 0201 + // 0x8E, 0xA1-0xDF - upper part of 0201 + // (0xA1-0xFE)x2 - 0208 plane (94x94). + // 0x8F, (0xA1-0xFE)x2 - 0212 plane (94x94). + // * JIS X 208: 7-bit, direct encoding of 0208. Byte ranges: 0x21-0x7E (94 values). Uncommon. + // Used as-is in ISO2022 family. + // * ISO2022-JP: Stateful encoding, with escape sequences to switch between ASCII, + // 0201-1976 Roman, 0208-1978, 0208-1983. + // * ISO2022-JP-1: Adds esc seq for 0212-1990. + // * ISO2022-JP-2: Adds esc seq for GB2313-1980, KSX1001-1992, ISO8859-1, ISO8859-7. + // * ISO2022-JP-3: Adds esc seq for 0201-1976 Kana set, 0213-2000 Planes 1, 2. + // * ISO2022-JP-2004: Adds 0213-2004 Plane 1. + // + // After JIS X 0213 appeared, Shift_JIS-2004, EUC-JISX0213 and ISO2022-JP-2004 followed, with just changing the planes. + // + // Overall, it seems that it's a mess :( http://www8.plala.or.jp/tkubota1/unicode-symbols-map2.html + shiftjis: { + type: "_dbcs", + table: function() { + return require_shiftjis(); + }, + encodeAdd: { "\xA5": 92, "\u203E": 126 }, + encodeSkipVals: [{ from: 60736, to: 63808 }] + }, + csshiftjis: "shiftjis", + mskanji: "shiftjis", + sjis: "shiftjis", + windows31j: "shiftjis", + ms31j: "shiftjis", + xsjis: "shiftjis", + windows932: "shiftjis", + ms932: "shiftjis", + 932: "shiftjis", + cp932: "shiftjis", + eucjp: { + type: "_dbcs", + table: function() { + return require_eucjp(); + }, + encodeAdd: { "\xA5": 92, "\u203E": 126 } + }, + // TODO: KDDI extension to Shift_JIS + // TODO: IBM CCSID 942 = CP932, but F0-F9 custom chars and other char changes. + // TODO: IBM CCSID 943 = Shift_JIS = CP932 with original Shift_JIS lower 128 chars. + // == Chinese/GBK ========================================================== + // http://en.wikipedia.org/wiki/GBK + // We mostly implement W3C recommendation: https://www.w3.org/TR/encoding/#gbk-encoder + // Oldest GB2312 (1981, ~7600 chars) is a subset of CP936 + gb2312: "cp936", + gb231280: "cp936", + gb23121980: "cp936", + csgb2312: "cp936", + csiso58gb231280: "cp936", + euccn: "cp936", + // Microsoft's CP936 is a subset and approximation of GBK. + windows936: "cp936", + ms936: "cp936", + 936: "cp936", + cp936: { + type: "_dbcs", + table: function() { + return require_cp936(); + } + }, + // GBK (~22000 chars) is an extension of CP936 that added user-mapped chars and some other. + gbk: { + type: "_dbcs", + table: function() { + return require_cp936().concat(require_gbk_added()); + } + }, + xgbk: "gbk", + isoir58: "gbk", + // GB18030 is an algorithmic extension of GBK. + // Main source: https://www.w3.org/TR/encoding/#gbk-encoder + // http://icu-project.org/docs/papers/gb18030.html + // http://source.icu-project.org/repos/icu/data/trunk/charset/data/xml/gb-18030-2000.xml + // http://www.khngai.com/chinese/charmap/tblgbk.php?page=0 + gb18030: { + type: "_dbcs", + table: function() { + return require_cp936().concat(require_gbk_added()); + }, + gb18030: function() { + return require_gb18030_ranges(); + }, + encodeSkipVals: [128], + encodeAdd: { "\u20AC": 41699 } + }, + chinese: "gb18030", + // == Korean =============================================================== + // EUC-KR, KS_C_5601 and KS X 1001 are exactly the same. + windows949: "cp949", + ms949: "cp949", + 949: "cp949", + cp949: { + type: "_dbcs", + table: function() { + return require_cp949(); + } + }, + cseuckr: "cp949", + csksc56011987: "cp949", + euckr: "cp949", + isoir149: "cp949", + korean: "cp949", + ksc56011987: "cp949", + ksc56011989: "cp949", + ksc5601: "cp949", + // == Big5/Taiwan/Hong Kong ================================================ + // There are lots of tables for Big5 and cp950. Please see the following links for history: + // http://moztw.org/docs/big5/ http://www.haible.de/bruno/charsets/conversion-tables/Big5.html + // Variations, in roughly number of defined chars: + // * Windows CP 950: Microsoft variant of Big5. Canonical: http://www.unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WINDOWS/CP950.TXT + // * Windows CP 951: Microsoft variant of Big5-HKSCS-2001. Seems to be never public. http://me.abelcheung.org/articles/research/what-is-cp951/ + // * Big5-2003 (Taiwan standard) almost superset of cp950. + // * Unicode-at-on (UAO) / Mozilla 1.8. Falling out of use on the Web. Not supported by other browsers. + // * Big5-HKSCS (-2001, -2004, -2008). Hong Kong standard. + // many unicode code points moved from PUA to Supplementary plane (U+2XXXX) over the years. + // Plus, it has 4 combining sequences. + // Seems that Mozilla refused to support it for 10 yrs. https://bugzilla.mozilla.org/show_bug.cgi?id=162431 https://bugzilla.mozilla.org/show_bug.cgi?id=310299 + // because big5-hkscs is the only encoding to include astral characters in non-algorithmic way. + // Implementations are not consistent within browsers; sometimes labeled as just big5. + // MS Internet Explorer switches from big5 to big5-hkscs when a patch applied. + // Great discussion & recap of what's going on https://bugzilla.mozilla.org/show_bug.cgi?id=912470#c31 + // In the encoder, it might make sense to support encoding old PUA mappings to Big5 bytes seq-s. + // Official spec: http://www.ogcio.gov.hk/en/business/tech_promotion/ccli/terms/doc/2003cmp_2008.txt + // http://www.ogcio.gov.hk/tc/business/tech_promotion/ccli/terms/doc/hkscs-2008-big5-iso.txt + // + // Current understanding of how to deal with Big5(-HKSCS) is in the Encoding Standard, http://encoding.spec.whatwg.org/#big5-encoder + // Unicode mapping (http://www.unicode.org/Public/MAPPINGS/OBSOLETE/EASTASIA/OTHER/BIG5.TXT) is said to be wrong. + windows950: "cp950", + ms950: "cp950", + 950: "cp950", + cp950: { + type: "_dbcs", + table: function() { + return require_cp950(); + } + }, + // Big5 has many variations and is an extension of cp950. We use Encoding Standard's as a consensus. + big5: "big5hkscs", + big5hkscs: { + type: "_dbcs", + table: function() { + return require_cp950().concat(require_big5_added()); + }, + encodeSkipVals: [ + // Although Encoding Standard says we should avoid encoding to HKSCS area (See Step 1 of + // https://encoding.spec.whatwg.org/#index-big5-pointer), we still do it to increase compatibility with ICU. + // But if a single unicode point can be encoded both as HKSCS and regular Big5, we prefer the latter. + 36457, + 36463, + 36478, + 36523, + 36532, + 36557, + 36560, + 36695, + 36713, + 36718, + 36811, + 36862, + 36973, + 36986, + 37060, + 37084, + 37105, + 37311, + 37551, + 37552, + 37553, + 37554, + 37585, + 37959, + 38090, + 38361, + 38652, + 39285, + 39798, + 39800, + 39803, + 39878, + 39902, + 39916, + 39926, + 40002, + 40019, + 40034, + 40040, + 40043, + 40055, + 40124, + 40125, + 40144, + 40279, + 40282, + 40388, + 40431, + 40443, + 40617, + 40687, + 40701, + 40800, + 40907, + 41079, + 41180, + 41183, + 36812, + 37576, + 38468, + 38637, + // Step 2 of https://encoding.spec.whatwg.org/#index-big5-pointer: Use last pointer for U+2550, U+255E, U+2561, U+256A, U+5341, or U+5345 + 41636, + 41637, + 41639, + 41638, + 41676, + 41678 + ] + }, + cnbig5: "big5hkscs", + csbig5: "big5hkscs", + xxbig5: "big5hkscs" + }; + } +}); + +// node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/encodings/index.js +var require_encodings = __commonJS({ + "node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/encodings/index.js"(exports, module) { + "use strict"; + var mergeModules = require_merge_exports(); + var modules = [ + require_internal(), + require_utf32(), + require_utf16(), + require_utf7(), + require_sbcs_codec(), + require_sbcs_data(), + require_sbcs_data_generated(), + require_dbcs_codec(), + require_dbcs_data() + ]; + for (i5 = 0; i5 < modules.length; i5++) { + module = modules[i5]; + mergeModules(exports, module); + } + var module; + var i5; + } +}); + +// node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/lib/streams.js +var require_streams = __commonJS({ + "node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/lib/streams.js"(exports, module) { + "use strict"; + var Buffer2 = require_safer().Buffer; + module.exports = function(streamModule) { + var Transform = streamModule.Transform; + function IconvLiteEncoderStream(conv, options) { + this.conv = conv; + options = options || {}; + options.decodeStrings = false; + Transform.call(this, options); + } + IconvLiteEncoderStream.prototype = Object.create(Transform.prototype, { + constructor: { value: IconvLiteEncoderStream } + }); + IconvLiteEncoderStream.prototype._transform = function(chunk, encoding, done) { + if (typeof chunk !== "string") { + return done(new Error("Iconv encoding stream needs strings as its input.")); + } + try { + var res = this.conv.write(chunk); + if (res && res.length) this.push(res); + done(); + } catch (e5) { + done(e5); + } + }; + IconvLiteEncoderStream.prototype._flush = function(done) { + try { + var res = this.conv.end(); + if (res && res.length) this.push(res); + done(); + } catch (e5) { + done(e5); + } + }; + IconvLiteEncoderStream.prototype.collect = function(cb) { + var chunks = []; + this.on("error", cb); + this.on("data", function(chunk) { + chunks.push(chunk); + }); + this.on("end", function() { + cb(null, Buffer2.concat(chunks)); + }); + return this; + }; + function IconvLiteDecoderStream(conv, options) { + this.conv = conv; + options = options || {}; + options.encoding = this.encoding = "utf8"; + Transform.call(this, options); + } + IconvLiteDecoderStream.prototype = Object.create(Transform.prototype, { + constructor: { value: IconvLiteDecoderStream } + }); + IconvLiteDecoderStream.prototype._transform = function(chunk, encoding, done) { + if (!Buffer2.isBuffer(chunk) && !(chunk instanceof Uint8Array)) { + return done(new Error("Iconv decoding stream needs buffers as its input.")); + } + try { + var res = this.conv.write(chunk); + if (res && res.length) this.push(res, this.encoding); + done(); + } catch (e5) { + done(e5); + } + }; + IconvLiteDecoderStream.prototype._flush = function(done) { + try { + var res = this.conv.end(); + if (res && res.length) this.push(res, this.encoding); + done(); + } catch (e5) { + done(e5); + } + }; + IconvLiteDecoderStream.prototype.collect = function(cb) { + var res = ""; + this.on("error", cb); + this.on("data", function(chunk) { + res += chunk; + }); + this.on("end", function() { + cb(null, res); + }); + return this; + }; + return { + IconvLiteEncoderStream, + IconvLiteDecoderStream + }; + }; + } +}); + +// node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/lib/index.js +var require_lib = __commonJS({ + "node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/lib/index.js"(exports, module) { + "use strict"; + var Buffer2 = require_safer().Buffer; + var bomHandling = require_bom_handling(); + var mergeModules = require_merge_exports(); + module.exports.encodings = null; + module.exports.defaultCharUnicode = "\uFFFD"; + module.exports.defaultCharSingleByte = "?"; + module.exports.encode = function encode6(str, encoding, options) { + str = "" + (str || ""); + var encoder3 = module.exports.getEncoder(encoding, options); + var res = encoder3.write(str); + var trail = encoder3.end(); + return trail && trail.length > 0 ? Buffer2.concat([res, trail]) : res; + }; + module.exports.decode = function decode5(buf, encoding, options) { + if (typeof buf === "string") { + if (!module.exports.skipDecodeWarning) { + console.error("Iconv-lite warning: decode()-ing strings is deprecated. Refer to https://github.com/ashtuchkin/iconv-lite/wiki/Use-Buffers-when-decoding"); + module.exports.skipDecodeWarning = true; + } + buf = Buffer2.from("" + (buf || ""), "binary"); + } + var decoder2 = module.exports.getDecoder(encoding, options); + var res = decoder2.write(buf); + var trail = decoder2.end(); + return trail ? res + trail : res; + }; + module.exports.encodingExists = function encodingExists(enc2) { + try { + module.exports.getCodec(enc2); + return true; + } catch (e5) { + return false; + } + }; + module.exports.toEncoding = module.exports.encode; + module.exports.fromEncoding = module.exports.decode; + module.exports._codecDataCache = { __proto__: null }; + module.exports.getCodec = function getCodec(encoding) { + if (!module.exports.encodings) { + var raw = require_encodings(); + module.exports.encodings = { __proto__: null }; + mergeModules(module.exports.encodings, raw); + } + var enc2 = module.exports._canonicalizeEncoding(encoding); + var codecOptions = {}; + while (true) { + var codec2 = module.exports._codecDataCache[enc2]; + if (codec2) { + return codec2; + } + var codecDef = module.exports.encodings[enc2]; + switch (typeof codecDef) { + case "string": + enc2 = codecDef; + break; + case "object": + for (var key in codecDef) { + codecOptions[key] = codecDef[key]; + } + if (!codecOptions.encodingName) { + codecOptions.encodingName = enc2; + } + enc2 = codecDef.type; + break; + case "function": + if (!codecOptions.encodingName) { + codecOptions.encodingName = enc2; + } + codec2 = new codecDef(codecOptions, module.exports); + module.exports._codecDataCache[codecOptions.encodingName] = codec2; + return codec2; + default: + throw new Error("Encoding not recognized: '" + encoding + "' (searched as: '" + enc2 + "')"); + } + } + }; + module.exports._canonicalizeEncoding = function(encoding) { + return ("" + encoding).toLowerCase().replace(/:\d{4}$|[^0-9a-z]/g, ""); + }; + module.exports.getEncoder = function getEncoder(encoding, options) { + var codec2 = module.exports.getCodec(encoding); + var encoder3 = new codec2.encoder(options, codec2); + if (codec2.bomAware && options && options.addBOM) { + encoder3 = new bomHandling.PrependBOM(encoder3, options); + } + return encoder3; + }; + module.exports.getDecoder = function getDecoder(encoding, options) { + var codec2 = module.exports.getCodec(encoding); + var decoder2 = new codec2.decoder(options, codec2); + if (codec2.bomAware && !(options && options.stripBOM === false)) { + decoder2 = new bomHandling.StripBOM(decoder2, options); + } + return decoder2; + }; + module.exports.enableStreamingAPI = function enableStreamingAPI(streamModule2) { + if (module.exports.supportsStreams) { + return; + } + var streams = require_streams()(streamModule2); + module.exports.IconvLiteEncoderStream = streams.IconvLiteEncoderStream; + module.exports.IconvLiteDecoderStream = streams.IconvLiteDecoderStream; + module.exports.encodeStream = function encodeStream(encoding, options) { + return new module.exports.IconvLiteEncoderStream(module.exports.getEncoder(encoding, options), options); + }; + module.exports.decodeStream = function decodeStream(encoding, options) { + return new module.exports.IconvLiteDecoderStream(module.exports.getDecoder(encoding, options), options); + }; + module.exports.supportsStreams = true; + }; + var streamModule; + try { + streamModule = __require("stream"); + } catch (e5) { + } + if (streamModule && streamModule.Transform) { + module.exports.enableStreamingAPI(streamModule); + } else { + module.exports.encodeStream = module.exports.decodeStream = function() { + throw new Error("iconv-lite Streaming API is not enabled. Use iconv.enableStreamingAPI(require('stream')); to enable it."); + }; + } + if (false) { + console.error("iconv-lite warning: js files use non-utf8 encoding. See https://github.com/ashtuchkin/iconv-lite/wiki/Javascript-source-file-encodings for more info."); + } + } +}); + +// node_modules/.pnpm/unpipe@1.0.0/node_modules/unpipe/index.js +var require_unpipe = __commonJS({ + "node_modules/.pnpm/unpipe@1.0.0/node_modules/unpipe/index.js"(exports, module) { + "use strict"; + module.exports = unpipe; + function hasPipeDataListeners(stream) { + var listeners = stream.listeners("data"); + for (var i5 = 0; i5 < listeners.length; i5++) { + if (listeners[i5].name === "ondata") { + return true; + } + } + return false; + } + function unpipe(stream) { + if (!stream) { + throw new TypeError("argument stream is required"); + } + if (typeof stream.unpipe === "function") { + stream.unpipe(); + return; + } + if (!hasPipeDataListeners(stream)) { + return; + } + var listener; + var listeners = stream.listeners("close"); + for (var i5 = 0; i5 < listeners.length; i5++) { + listener = listeners[i5]; + if (listener.name !== "cleanup" && listener.name !== "onclose") { + continue; + } + listener.call(stream); + } + } + } +}); + +// node_modules/.pnpm/raw-body@3.0.2/node_modules/raw-body/index.js +var require_raw_body = __commonJS({ + "node_modules/.pnpm/raw-body@3.0.2/node_modules/raw-body/index.js"(exports, module) { + "use strict"; + var asyncHooks = tryRequireAsyncHooks(); + var bytes = require_bytes(); + var createError = require_http_errors(); + var iconv = require_lib(); + var unpipe = require_unpipe(); + module.exports = getRawBody; + var ICONV_ENCODING_MESSAGE_REGEXP = /^Encoding not recognized: /; + function getDecoder(encoding) { + if (!encoding) return null; + try { + return iconv.getDecoder(encoding); + } catch (e5) { + if (!ICONV_ENCODING_MESSAGE_REGEXP.test(e5.message)) throw e5; + throw createError(415, "specified encoding unsupported", { + encoding, + type: "encoding.unsupported" + }); + } + } + function getRawBody(stream, options, callback) { + var done = callback; + var opts = options || {}; + if (stream === void 0) { + throw new TypeError("argument stream is required"); + } else if (typeof stream !== "object" || stream === null || typeof stream.on !== "function") { + throw new TypeError("argument stream must be a stream"); + } + if (options === true || typeof options === "string") { + opts = { + encoding: options + }; + } + if (typeof options === "function") { + done = options; + opts = {}; + } + if (done !== void 0 && typeof done !== "function") { + throw new TypeError("argument callback must be a function"); + } + if (!done && !global.Promise) { + throw new TypeError("argument callback is required"); + } + var encoding = opts.encoding !== true ? opts.encoding : "utf-8"; + var limit = bytes.parse(opts.limit); + var length = opts.length != null && !isNaN(opts.length) ? parseInt(opts.length, 10) : null; + if (done) { + return readStream(stream, encoding, length, limit, wrap4(done)); + } + return new Promise(function executor(resolve4, reject) { + readStream(stream, encoding, length, limit, function onRead(err, buf) { + if (err) return reject(err); + resolve4(buf); + }); + }); + } + function halt(stream) { + unpipe(stream); + if (typeof stream.pause === "function") { + stream.pause(); + } + } + function readStream(stream, encoding, length, limit, callback) { + var complete = false; + var sync = true; + if (limit !== null && length !== null && length > limit) { + return done(createError(413, "request entity too large", { + expected: length, + length, + limit, + type: "entity.too.large" + })); + } + var state2 = stream._readableState; + if (stream._decoder || state2 && (state2.encoding || state2.decoder)) { + return done(createError(500, "stream encoding should not be set", { + type: "stream.encoding.set" + })); + } + if (typeof stream.readable !== "undefined" && !stream.readable) { + return done(createError(500, "stream is not readable", { + type: "stream.not.readable" + })); + } + var received = 0; + var decoder2; + try { + decoder2 = getDecoder(encoding); + } catch (err) { + return done(err); + } + var buffer2 = decoder2 ? "" : []; + stream.on("aborted", onAborted); + stream.on("close", cleanup); + stream.on("data", onData); + stream.on("end", onEnd); + stream.on("error", onEnd); + sync = false; + function done() { + var args = new Array(arguments.length); + for (var i5 = 0; i5 < args.length; i5++) { + args[i5] = arguments[i5]; + } + complete = true; + if (sync) { + process.nextTick(invokeCallback); + } else { + invokeCallback(); + } + function invokeCallback() { + cleanup(); + if (args[0]) { + halt(stream); + } + callback.apply(null, args); + } + } + function onAborted() { + if (complete) return; + done(createError(400, "request aborted", { + code: "ECONNABORTED", + expected: length, + length, + received, + type: "request.aborted" + })); + } + function onData(chunk) { + if (complete) return; + received += chunk.length; + if (limit !== null && received > limit) { + done(createError(413, "request entity too large", { + limit, + received, + type: "entity.too.large" + })); + } else if (decoder2) { + buffer2 += decoder2.write(chunk); + } else { + buffer2.push(chunk); + } + } + function onEnd(err) { + if (complete) return; + if (err) return done(err); + if (length !== null && received !== length) { + done(createError(400, "request size did not match content length", { + expected: length, + length, + received, + type: "request.size.invalid" + })); + } else { + var string4 = decoder2 ? buffer2 + (decoder2.end() || "") : Buffer.concat(buffer2); + done(null, string4); + } + } + function cleanup() { + buffer2 = null; + stream.removeListener("aborted", onAborted); + stream.removeListener("data", onData); + stream.removeListener("end", onEnd); + stream.removeListener("error", onEnd); + stream.removeListener("close", cleanup); + } + } + function tryRequireAsyncHooks() { + try { + return __require("async_hooks"); + } catch (e5) { + return {}; + } + } + function wrap4(fn) { + var res; + if (asyncHooks.AsyncResource) { + res = new asyncHooks.AsyncResource(fn.name || "bound-anonymous-fn"); + } + if (!res || !res.runInAsyncScope) { + return fn; + } + return res.runInAsyncScope.bind(res, fn, null); + } + } +}); + +// node_modules/.pnpm/ee-first@1.1.1/node_modules/ee-first/index.js +var require_ee_first = __commonJS({ + "node_modules/.pnpm/ee-first@1.1.1/node_modules/ee-first/index.js"(exports, module) { + "use strict"; + module.exports = first; + function first(stuff, done) { + if (!Array.isArray(stuff)) + throw new TypeError("arg must be an array of [ee, events...] arrays"); + var cleanups = []; + for (var i5 = 0; i5 < stuff.length; i5++) { + var arr = stuff[i5]; + if (!Array.isArray(arr) || arr.length < 2) + throw new TypeError("each array member must be [ee, events...]"); + var ee = arr[0]; + for (var j5 = 1; j5 < arr.length; j5++) { + var event = arr[j5]; + var fn = listener(event, callback); + ee.on(event, fn); + cleanups.push({ + ee, + event, + fn + }); + } + } + function callback() { + cleanup(); + done.apply(null, arguments); + } + function cleanup() { + var x5; + for (var i6 = 0; i6 < cleanups.length; i6++) { + x5 = cleanups[i6]; + x5.ee.removeListener(x5.event, x5.fn); + } + } + function thunk(fn2) { + done = fn2; + } + thunk.cancel = cleanup; + return thunk; + } + function listener(event, done) { + return function onevent(arg1) { + var args = new Array(arguments.length); + var ee = this; + var err = event === "error" ? arg1 : null; + for (var i5 = 0; i5 < args.length; i5++) { + args[i5] = arguments[i5]; + } + done(err, ee, event, args); + }; + } + } +}); + +// node_modules/.pnpm/on-finished@2.4.1/node_modules/on-finished/index.js +var require_on_finished = __commonJS({ + "node_modules/.pnpm/on-finished@2.4.1/node_modules/on-finished/index.js"(exports, module) { + "use strict"; + module.exports = onFinished; + module.exports.isFinished = isFinished; + var asyncHooks = tryRequireAsyncHooks(); + var first = require_ee_first(); + var defer = typeof setImmediate === "function" ? setImmediate : function(fn) { + process.nextTick(fn.bind.apply(fn, arguments)); + }; + function onFinished(msg, listener) { + if (isFinished(msg) !== false) { + defer(listener, null, msg); + return msg; + } + attachListener(msg, wrap4(listener)); + return msg; + } + function isFinished(msg) { + var socket = msg.socket; + if (typeof msg.finished === "boolean") { + return Boolean(msg.finished || socket && !socket.writable); + } + if (typeof msg.complete === "boolean") { + return Boolean(msg.upgrade || !socket || !socket.readable || msg.complete && !msg.readable); + } + return void 0; + } + function attachFinishedListener(msg, callback) { + var eeMsg; + var eeSocket; + var finished = false; + function onFinish(error50) { + eeMsg.cancel(); + eeSocket.cancel(); + finished = true; + callback(error50); + } + eeMsg = eeSocket = first([[msg, "end", "finish"]], onFinish); + function onSocket(socket) { + msg.removeListener("socket", onSocket); + if (finished) return; + if (eeMsg !== eeSocket) return; + eeSocket = first([[socket, "error", "close"]], onFinish); + } + if (msg.socket) { + onSocket(msg.socket); + return; + } + msg.on("socket", onSocket); + if (msg.socket === void 0) { + patchAssignSocket(msg, onSocket); + } + } + function attachListener(msg, listener) { + var attached = msg.__onFinished; + if (!attached || !attached.queue) { + attached = msg.__onFinished = createListener(msg); + attachFinishedListener(msg, attached); + } + attached.queue.push(listener); + } + function createListener(msg) { + function listener(err) { + if (msg.__onFinished === listener) msg.__onFinished = null; + if (!listener.queue) return; + var queue = listener.queue; + listener.queue = null; + for (var i5 = 0; i5 < queue.length; i5++) { + queue[i5](err, msg); + } + } + listener.queue = []; + return listener; + } + function patchAssignSocket(res, callback) { + var assignSocket = res.assignSocket; + if (typeof assignSocket !== "function") return; + res.assignSocket = function _assignSocket(socket) { + assignSocket.call(this, socket); + callback(socket); + }; + } + function tryRequireAsyncHooks() { + try { + return __require("async_hooks"); + } catch (e5) { + return {}; + } + } + function wrap4(fn) { + var res; + if (asyncHooks.AsyncResource) { + res = new asyncHooks.AsyncResource(fn.name || "bound-anonymous-fn"); + } + if (!res || !res.runInAsyncScope) { + return fn; + } + return res.runInAsyncScope.bind(res, fn, null); + } + } +}); + +// node_modules/.pnpm/content-type@1.0.5/node_modules/content-type/index.js +var require_content_type = __commonJS({ + "node_modules/.pnpm/content-type@1.0.5/node_modules/content-type/index.js"(exports) { + "use strict"; + var PARAM_REGEXP = /; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g; + var TEXT_REGEXP = /^[\u000b\u0020-\u007e\u0080-\u00ff]+$/; + var TOKEN_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/; + var QESC_REGEXP = /\\([\u000b\u0020-\u00ff])/g; + var QUOTE_REGEXP = /([\\"])/g; + var TYPE_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/; + exports.format = format2; + exports.parse = parse5; + function format2(obj) { + if (!obj || typeof obj !== "object") { + throw new TypeError("argument obj is required"); + } + var parameters = obj.parameters; + var type = obj.type; + if (!type || !TYPE_REGEXP.test(type)) { + throw new TypeError("invalid type"); + } + var string4 = type; + if (parameters && typeof parameters === "object") { + var param; + var params = Object.keys(parameters).sort(); + for (var i5 = 0; i5 < params.length; i5++) { + param = params[i5]; + if (!TOKEN_REGEXP.test(param)) { + throw new TypeError("invalid parameter name"); + } + string4 += "; " + param + "=" + qstring(parameters[param]); + } + } + return string4; + } + function parse5(string4) { + if (!string4) { + throw new TypeError("argument string is required"); + } + var header = typeof string4 === "object" ? getcontenttype(string4) : string4; + if (typeof header !== "string") { + throw new TypeError("argument string is required to be a string"); + } + var index2 = header.indexOf(";"); + var type = index2 !== -1 ? header.slice(0, index2).trim() : header.trim(); + if (!TYPE_REGEXP.test(type)) { + throw new TypeError("invalid media type"); + } + var obj = new ContentType(type.toLowerCase()); + if (index2 !== -1) { + var key; + var match; + var value; + PARAM_REGEXP.lastIndex = index2; + while (match = PARAM_REGEXP.exec(header)) { + if (match.index !== index2) { + throw new TypeError("invalid parameter format"); + } + index2 += match[0].length; + key = match[1].toLowerCase(); + value = match[2]; + if (value.charCodeAt(0) === 34) { + value = value.slice(1, -1); + if (value.indexOf("\\") !== -1) { + value = value.replace(QESC_REGEXP, "$1"); + } + } + obj.parameters[key] = value; + } + if (index2 !== header.length) { + throw new TypeError("invalid parameter format"); + } + } + return obj; + } + function getcontenttype(obj) { + var header; + if (typeof obj.getHeader === "function") { + header = obj.getHeader("content-type"); + } else if (typeof obj.headers === "object") { + header = obj.headers && obj.headers["content-type"]; + } + if (typeof header !== "string") { + throw new TypeError("content-type header is missing from object"); + } + return header; + } + function qstring(val) { + var str = String(val); + if (TOKEN_REGEXP.test(str)) { + return str; + } + if (str.length > 0 && !TEXT_REGEXP.test(str)) { + throw new TypeError("invalid parameter value"); + } + return '"' + str.replace(QUOTE_REGEXP, "\\$1") + '"'; + } + function ContentType(type) { + this.parameters = /* @__PURE__ */ Object.create(null); + this.type = type; + } + } +}); + +// node_modules/.pnpm/mime-db@1.54.0/node_modules/mime-db/db.json +var require_db = __commonJS({ + "node_modules/.pnpm/mime-db@1.54.0/node_modules/mime-db/db.json"(exports, module) { + module.exports = { + "application/1d-interleaved-parityfec": { + source: "iana" + }, + "application/3gpdash-qoe-report+xml": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/3gpp-ims+xml": { + source: "iana", + compressible: true + }, + "application/3gpphal+json": { + source: "iana", + compressible: true + }, + "application/3gpphalforms+json": { + source: "iana", + compressible: true + }, + "application/a2l": { + source: "iana" + }, + "application/ace+cbor": { + source: "iana" + }, + "application/ace+json": { + source: "iana", + compressible: true + }, + "application/ace-groupcomm+cbor": { + source: "iana" + }, + "application/ace-trl+cbor": { + source: "iana" + }, + "application/activemessage": { + source: "iana" + }, + "application/activity+json": { + source: "iana", + compressible: true + }, + "application/aif+cbor": { + source: "iana" + }, + "application/aif+json": { + source: "iana", + compressible: true + }, + "application/alto-cdni+json": { + source: "iana", + compressible: true + }, + "application/alto-cdnifilter+json": { + source: "iana", + compressible: true + }, + "application/alto-costmap+json": { + source: "iana", + compressible: true + }, + "application/alto-costmapfilter+json": { + source: "iana", + compressible: true + }, + "application/alto-directory+json": { + source: "iana", + compressible: true + }, + "application/alto-endpointcost+json": { + source: "iana", + compressible: true + }, + "application/alto-endpointcostparams+json": { + source: "iana", + compressible: true + }, + "application/alto-endpointprop+json": { + source: "iana", + compressible: true + }, + "application/alto-endpointpropparams+json": { + source: "iana", + compressible: true + }, + "application/alto-error+json": { + source: "iana", + compressible: true + }, + "application/alto-networkmap+json": { + source: "iana", + compressible: true + }, + "application/alto-networkmapfilter+json": { + source: "iana", + compressible: true + }, + "application/alto-propmap+json": { + source: "iana", + compressible: true + }, + "application/alto-propmapparams+json": { + source: "iana", + compressible: true + }, + "application/alto-tips+json": { + source: "iana", + compressible: true + }, + "application/alto-tipsparams+json": { + source: "iana", + compressible: true + }, + "application/alto-updatestreamcontrol+json": { + source: "iana", + compressible: true + }, + "application/alto-updatestreamparams+json": { + source: "iana", + compressible: true + }, + "application/aml": { + source: "iana" + }, + "application/andrew-inset": { + source: "iana", + extensions: ["ez"] + }, + "application/appinstaller": { + compressible: false, + extensions: ["appinstaller"] + }, + "application/applefile": { + source: "iana" + }, + "application/applixware": { + source: "apache", + extensions: ["aw"] + }, + "application/appx": { + compressible: false, + extensions: ["appx"] + }, + "application/appxbundle": { + compressible: false, + extensions: ["appxbundle"] + }, + "application/at+jwt": { + source: "iana" + }, + "application/atf": { + source: "iana" + }, + "application/atfx": { + source: "iana" + }, + "application/atom+xml": { + source: "iana", + compressible: true, + extensions: ["atom"] + }, + "application/atomcat+xml": { + source: "iana", + compressible: true, + extensions: ["atomcat"] + }, + "application/atomdeleted+xml": { + source: "iana", + compressible: true, + extensions: ["atomdeleted"] + }, + "application/atomicmail": { + source: "iana" + }, + "application/atomsvc+xml": { + source: "iana", + compressible: true, + extensions: ["atomsvc"] + }, + "application/atsc-dwd+xml": { + source: "iana", + compressible: true, + extensions: ["dwd"] + }, + "application/atsc-dynamic-event-message": { + source: "iana" + }, + "application/atsc-held+xml": { + source: "iana", + compressible: true, + extensions: ["held"] + }, + "application/atsc-rdt+json": { + source: "iana", + compressible: true + }, + "application/atsc-rsat+xml": { + source: "iana", + compressible: true, + extensions: ["rsat"] + }, + "application/atxml": { + source: "iana" + }, + "application/auth-policy+xml": { + source: "iana", + compressible: true + }, + "application/automationml-aml+xml": { + source: "iana", + compressible: true, + extensions: ["aml"] + }, + "application/automationml-amlx+zip": { + source: "iana", + compressible: false, + extensions: ["amlx"] + }, + "application/bacnet-xdd+zip": { + source: "iana", + compressible: false + }, + "application/batch-smtp": { + source: "iana" + }, + "application/bdoc": { + compressible: false, + extensions: ["bdoc"] + }, + "application/beep+xml": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/bufr": { + source: "iana" + }, + "application/c2pa": { + source: "iana" + }, + "application/calendar+json": { + source: "iana", + compressible: true + }, + "application/calendar+xml": { + source: "iana", + compressible: true, + extensions: ["xcs"] + }, + "application/call-completion": { + source: "iana" + }, + "application/cals-1840": { + source: "iana" + }, + "application/captive+json": { + source: "iana", + compressible: true + }, + "application/cbor": { + source: "iana" + }, + "application/cbor-seq": { + source: "iana" + }, + "application/cccex": { + source: "iana" + }, + "application/ccmp+xml": { + source: "iana", + compressible: true + }, + "application/ccxml+xml": { + source: "iana", + compressible: true, + extensions: ["ccxml"] + }, + "application/cda+xml": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/cdfx+xml": { + source: "iana", + compressible: true, + extensions: ["cdfx"] + }, + "application/cdmi-capability": { + source: "iana", + extensions: ["cdmia"] + }, + "application/cdmi-container": { + source: "iana", + extensions: ["cdmic"] + }, + "application/cdmi-domain": { + source: "iana", + extensions: ["cdmid"] + }, + "application/cdmi-object": { + source: "iana", + extensions: ["cdmio"] + }, + "application/cdmi-queue": { + source: "iana", + extensions: ["cdmiq"] + }, + "application/cdni": { + source: "iana" + }, + "application/ce+cbor": { + source: "iana" + }, + "application/cea": { + source: "iana" + }, + "application/cea-2018+xml": { + source: "iana", + compressible: true + }, + "application/cellml+xml": { + source: "iana", + compressible: true + }, + "application/cfw": { + source: "iana" + }, + "application/cid-edhoc+cbor-seq": { + source: "iana" + }, + "application/city+json": { + source: "iana", + compressible: true + }, + "application/city+json-seq": { + source: "iana" + }, + "application/clr": { + source: "iana" + }, + "application/clue+xml": { + source: "iana", + compressible: true + }, + "application/clue_info+xml": { + source: "iana", + compressible: true + }, + "application/cms": { + source: "iana" + }, + "application/cnrp+xml": { + source: "iana", + compressible: true + }, + "application/coap-eap": { + source: "iana" + }, + "application/coap-group+json": { + source: "iana", + compressible: true + }, + "application/coap-payload": { + source: "iana" + }, + "application/commonground": { + source: "iana" + }, + "application/concise-problem-details+cbor": { + source: "iana" + }, + "application/conference-info+xml": { + source: "iana", + compressible: true + }, + "application/cose": { + source: "iana" + }, + "application/cose-key": { + source: "iana" + }, + "application/cose-key-set": { + source: "iana" + }, + "application/cose-x509": { + source: "iana" + }, + "application/cpl+xml": { + source: "iana", + compressible: true, + extensions: ["cpl"] + }, + "application/csrattrs": { + source: "iana" + }, + "application/csta+xml": { + source: "iana", + compressible: true + }, + "application/cstadata+xml": { + source: "iana", + compressible: true + }, + "application/csvm+json": { + source: "iana", + compressible: true + }, + "application/cu-seeme": { + source: "apache", + extensions: ["cu"] + }, + "application/cwl": { + source: "iana", + extensions: ["cwl"] + }, + "application/cwl+json": { + source: "iana", + compressible: true + }, + "application/cwl+yaml": { + source: "iana" + }, + "application/cwt": { + source: "iana" + }, + "application/cybercash": { + source: "iana" + }, + "application/dart": { + compressible: true + }, + "application/dash+xml": { + source: "iana", + compressible: true, + extensions: ["mpd"] + }, + "application/dash-patch+xml": { + source: "iana", + compressible: true, + extensions: ["mpp"] + }, + "application/dashdelta": { + source: "iana" + }, + "application/davmount+xml": { + source: "iana", + compressible: true, + extensions: ["davmount"] + }, + "application/dca-rft": { + source: "iana" + }, + "application/dcd": { + source: "iana" + }, + "application/dec-dx": { + source: "iana" + }, + "application/dialog-info+xml": { + source: "iana", + compressible: true + }, + "application/dicom": { + source: "iana", + extensions: ["dcm"] + }, + "application/dicom+json": { + source: "iana", + compressible: true + }, + "application/dicom+xml": { + source: "iana", + compressible: true + }, + "application/dii": { + source: "iana" + }, + "application/dit": { + source: "iana" + }, + "application/dns": { + source: "iana" + }, + "application/dns+json": { + source: "iana", + compressible: true + }, + "application/dns-message": { + source: "iana" + }, + "application/docbook+xml": { + source: "apache", + compressible: true, + extensions: ["dbk"] + }, + "application/dots+cbor": { + source: "iana" + }, + "application/dpop+jwt": { + source: "iana" + }, + "application/dskpp+xml": { + source: "iana", + compressible: true + }, + "application/dssc+der": { + source: "iana", + extensions: ["dssc"] + }, + "application/dssc+xml": { + source: "iana", + compressible: true, + extensions: ["xdssc"] + }, + "application/dvcs": { + source: "iana" + }, + "application/eat+cwt": { + source: "iana" + }, + "application/eat+jwt": { + source: "iana" + }, + "application/eat-bun+cbor": { + source: "iana" + }, + "application/eat-bun+json": { + source: "iana", + compressible: true + }, + "application/eat-ucs+cbor": { + source: "iana" + }, + "application/eat-ucs+json": { + source: "iana", + compressible: true + }, + "application/ecmascript": { + source: "apache", + compressible: true, + extensions: ["ecma"] + }, + "application/edhoc+cbor-seq": { + source: "iana" + }, + "application/edi-consent": { + source: "iana" + }, + "application/edi-x12": { + source: "iana", + compressible: false + }, + "application/edifact": { + source: "iana", + compressible: false + }, + "application/efi": { + source: "iana" + }, + "application/elm+json": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/elm+xml": { + source: "iana", + compressible: true + }, + "application/emergencycalldata.cap+xml": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/emergencycalldata.comment+xml": { + source: "iana", + compressible: true + }, + "application/emergencycalldata.control+xml": { + source: "iana", + compressible: true + }, + "application/emergencycalldata.deviceinfo+xml": { + source: "iana", + compressible: true + }, + "application/emergencycalldata.ecall.msd": { + source: "iana" + }, + "application/emergencycalldata.legacyesn+json": { + source: "iana", + compressible: true + }, + "application/emergencycalldata.providerinfo+xml": { + source: "iana", + compressible: true + }, + "application/emergencycalldata.serviceinfo+xml": { + source: "iana", + compressible: true + }, + "application/emergencycalldata.subscriberinfo+xml": { + source: "iana", + compressible: true + }, + "application/emergencycalldata.veds+xml": { + source: "iana", + compressible: true + }, + "application/emma+xml": { + source: "iana", + compressible: true, + extensions: ["emma"] + }, + "application/emotionml+xml": { + source: "iana", + compressible: true, + extensions: ["emotionml"] + }, + "application/encaprtp": { + source: "iana" + }, + "application/entity-statement+jwt": { + source: "iana" + }, + "application/epp+xml": { + source: "iana", + compressible: true + }, + "application/epub+zip": { + source: "iana", + compressible: false, + extensions: ["epub"] + }, + "application/eshop": { + source: "iana" + }, + "application/exi": { + source: "iana", + extensions: ["exi"] + }, + "application/expect-ct-report+json": { + source: "iana", + compressible: true + }, + "application/express": { + source: "iana", + extensions: ["exp"] + }, + "application/fastinfoset": { + source: "iana" + }, + "application/fastsoap": { + source: "iana" + }, + "application/fdf": { + source: "iana", + extensions: ["fdf"] + }, + "application/fdt+xml": { + source: "iana", + compressible: true, + extensions: ["fdt"] + }, + "application/fhir+json": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/fhir+xml": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/fido.trusted-apps+json": { + compressible: true + }, + "application/fits": { + source: "iana" + }, + "application/flexfec": { + source: "iana" + }, + "application/font-sfnt": { + source: "iana" + }, + "application/font-tdpfr": { + source: "iana", + extensions: ["pfr"] + }, + "application/font-woff": { + source: "iana", + compressible: false + }, + "application/framework-attributes+xml": { + source: "iana", + compressible: true + }, + "application/geo+json": { + source: "iana", + compressible: true, + extensions: ["geojson"] + }, + "application/geo+json-seq": { + source: "iana" + }, + "application/geopackage+sqlite3": { + source: "iana" + }, + "application/geopose+json": { + source: "iana", + compressible: true + }, + "application/geoxacml+json": { + source: "iana", + compressible: true + }, + "application/geoxacml+xml": { + source: "iana", + compressible: true + }, + "application/gltf-buffer": { + source: "iana" + }, + "application/gml+xml": { + source: "iana", + compressible: true, + extensions: ["gml"] + }, + "application/gnap-binding-jws": { + source: "iana" + }, + "application/gnap-binding-jwsd": { + source: "iana" + }, + "application/gnap-binding-rotation-jws": { + source: "iana" + }, + "application/gnap-binding-rotation-jwsd": { + source: "iana" + }, + "application/gpx+xml": { + source: "apache", + compressible: true, + extensions: ["gpx"] + }, + "application/grib": { + source: "iana" + }, + "application/gxf": { + source: "apache", + extensions: ["gxf"] + }, + "application/gzip": { + source: "iana", + compressible: false, + extensions: ["gz"] + }, + "application/h224": { + source: "iana" + }, + "application/held+xml": { + source: "iana", + compressible: true + }, + "application/hjson": { + extensions: ["hjson"] + }, + "application/hl7v2+xml": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/http": { + source: "iana" + }, + "application/hyperstudio": { + source: "iana", + extensions: ["stk"] + }, + "application/ibe-key-request+xml": { + source: "iana", + compressible: true + }, + "application/ibe-pkg-reply+xml": { + source: "iana", + compressible: true + }, + "application/ibe-pp-data": { + source: "iana" + }, + "application/iges": { + source: "iana" + }, + "application/im-iscomposing+xml": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/index": { + source: "iana" + }, + "application/index.cmd": { + source: "iana" + }, + "application/index.obj": { + source: "iana" + }, + "application/index.response": { + source: "iana" + }, + "application/index.vnd": { + source: "iana" + }, + "application/inkml+xml": { + source: "iana", + compressible: true, + extensions: ["ink", "inkml"] + }, + "application/iotp": { + source: "iana" + }, + "application/ipfix": { + source: "iana", + extensions: ["ipfix"] + }, + "application/ipp": { + source: "iana" + }, + "application/isup": { + source: "iana" + }, + "application/its+xml": { + source: "iana", + compressible: true, + extensions: ["its"] + }, + "application/java-archive": { + source: "iana", + compressible: false, + extensions: ["jar", "war", "ear"] + }, + "application/java-serialized-object": { + source: "apache", + compressible: false, + extensions: ["ser"] + }, + "application/java-vm": { + source: "apache", + compressible: false, + extensions: ["class"] + }, + "application/javascript": { + source: "apache", + charset: "UTF-8", + compressible: true, + extensions: ["js"] + }, + "application/jf2feed+json": { + source: "iana", + compressible: true + }, + "application/jose": { + source: "iana" + }, + "application/jose+json": { + source: "iana", + compressible: true + }, + "application/jrd+json": { + source: "iana", + compressible: true + }, + "application/jscalendar+json": { + source: "iana", + compressible: true + }, + "application/jscontact+json": { + source: "iana", + compressible: true + }, + "application/json": { + source: "iana", + charset: "UTF-8", + compressible: true, + extensions: ["json", "map"] + }, + "application/json-patch+json": { + source: "iana", + compressible: true + }, + "application/json-seq": { + source: "iana" + }, + "application/json5": { + extensions: ["json5"] + }, + "application/jsonml+json": { + source: "apache", + compressible: true, + extensions: ["jsonml"] + }, + "application/jsonpath": { + source: "iana" + }, + "application/jwk+json": { + source: "iana", + compressible: true + }, + "application/jwk-set+json": { + source: "iana", + compressible: true + }, + "application/jwk-set+jwt": { + source: "iana" + }, + "application/jwt": { + source: "iana" + }, + "application/kpml-request+xml": { + source: "iana", + compressible: true + }, + "application/kpml-response+xml": { + source: "iana", + compressible: true + }, + "application/ld+json": { + source: "iana", + compressible: true, + extensions: ["jsonld"] + }, + "application/lgr+xml": { + source: "iana", + compressible: true, + extensions: ["lgr"] + }, + "application/link-format": { + source: "iana" + }, + "application/linkset": { + source: "iana" + }, + "application/linkset+json": { + source: "iana", + compressible: true + }, + "application/load-control+xml": { + source: "iana", + compressible: true + }, + "application/logout+jwt": { + source: "iana" + }, + "application/lost+xml": { + source: "iana", + compressible: true, + extensions: ["lostxml"] + }, + "application/lostsync+xml": { + source: "iana", + compressible: true + }, + "application/lpf+zip": { + source: "iana", + compressible: false + }, + "application/lxf": { + source: "iana" + }, + "application/mac-binhex40": { + source: "iana", + extensions: ["hqx"] + }, + "application/mac-compactpro": { + source: "apache", + extensions: ["cpt"] + }, + "application/macwriteii": { + source: "iana" + }, + "application/mads+xml": { + source: "iana", + compressible: true, + extensions: ["mads"] + }, + "application/manifest+json": { + source: "iana", + charset: "UTF-8", + compressible: true, + extensions: ["webmanifest"] + }, + "application/marc": { + source: "iana", + extensions: ["mrc"] + }, + "application/marcxml+xml": { + source: "iana", + compressible: true, + extensions: ["mrcx"] + }, + "application/mathematica": { + source: "iana", + extensions: ["ma", "nb", "mb"] + }, + "application/mathml+xml": { + source: "iana", + compressible: true, + extensions: ["mathml"] + }, + "application/mathml-content+xml": { + source: "iana", + compressible: true + }, + "application/mathml-presentation+xml": { + source: "iana", + compressible: true + }, + "application/mbms-associated-procedure-description+xml": { + source: "iana", + compressible: true + }, + "application/mbms-deregister+xml": { + source: "iana", + compressible: true + }, + "application/mbms-envelope+xml": { + source: "iana", + compressible: true + }, + "application/mbms-msk+xml": { + source: "iana", + compressible: true + }, + "application/mbms-msk-response+xml": { + source: "iana", + compressible: true + }, + "application/mbms-protection-description+xml": { + source: "iana", + compressible: true + }, + "application/mbms-reception-report+xml": { + source: "iana", + compressible: true + }, + "application/mbms-register+xml": { + source: "iana", + compressible: true + }, + "application/mbms-register-response+xml": { + source: "iana", + compressible: true + }, + "application/mbms-schedule+xml": { + source: "iana", + compressible: true + }, + "application/mbms-user-service-description+xml": { + source: "iana", + compressible: true + }, + "application/mbox": { + source: "iana", + extensions: ["mbox"] + }, + "application/media-policy-dataset+xml": { + source: "iana", + compressible: true, + extensions: ["mpf"] + }, + "application/media_control+xml": { + source: "iana", + compressible: true + }, + "application/mediaservercontrol+xml": { + source: "iana", + compressible: true, + extensions: ["mscml"] + }, + "application/merge-patch+json": { + source: "iana", + compressible: true + }, + "application/metalink+xml": { + source: "apache", + compressible: true, + extensions: ["metalink"] + }, + "application/metalink4+xml": { + source: "iana", + compressible: true, + extensions: ["meta4"] + }, + "application/mets+xml": { + source: "iana", + compressible: true, + extensions: ["mets"] + }, + "application/mf4": { + source: "iana" + }, + "application/mikey": { + source: "iana" + }, + "application/mipc": { + source: "iana" + }, + "application/missing-blocks+cbor-seq": { + source: "iana" + }, + "application/mmt-aei+xml": { + source: "iana", + compressible: true, + extensions: ["maei"] + }, + "application/mmt-usd+xml": { + source: "iana", + compressible: true, + extensions: ["musd"] + }, + "application/mods+xml": { + source: "iana", + compressible: true, + extensions: ["mods"] + }, + "application/moss-keys": { + source: "iana" + }, + "application/moss-signature": { + source: "iana" + }, + "application/mosskey-data": { + source: "iana" + }, + "application/mosskey-request": { + source: "iana" + }, + "application/mp21": { + source: "iana", + extensions: ["m21", "mp21"] + }, + "application/mp4": { + source: "iana", + extensions: ["mp4", "mpg4", "mp4s", "m4p"] + }, + "application/mpeg4-generic": { + source: "iana" + }, + "application/mpeg4-iod": { + source: "iana" + }, + "application/mpeg4-iod-xmt": { + source: "iana" + }, + "application/mrb-consumer+xml": { + source: "iana", + compressible: true + }, + "application/mrb-publish+xml": { + source: "iana", + compressible: true + }, + "application/msc-ivr+xml": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/msc-mixer+xml": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/msix": { + compressible: false, + extensions: ["msix"] + }, + "application/msixbundle": { + compressible: false, + extensions: ["msixbundle"] + }, + "application/msword": { + source: "iana", + compressible: false, + extensions: ["doc", "dot"] + }, + "application/mud+json": { + source: "iana", + compressible: true + }, + "application/multipart-core": { + source: "iana" + }, + "application/mxf": { + source: "iana", + extensions: ["mxf"] + }, + "application/n-quads": { + source: "iana", + extensions: ["nq"] + }, + "application/n-triples": { + source: "iana", + extensions: ["nt"] + }, + "application/nasdata": { + source: "iana" + }, + "application/news-checkgroups": { + source: "iana", + charset: "US-ASCII" + }, + "application/news-groupinfo": { + source: "iana", + charset: "US-ASCII" + }, + "application/news-transmission": { + source: "iana" + }, + "application/nlsml+xml": { + source: "iana", + compressible: true + }, + "application/node": { + source: "iana", + extensions: ["cjs"] + }, + "application/nss": { + source: "iana" + }, + "application/oauth-authz-req+jwt": { + source: "iana" + }, + "application/oblivious-dns-message": { + source: "iana" + }, + "application/ocsp-request": { + source: "iana" + }, + "application/ocsp-response": { + source: "iana" + }, + "application/octet-stream": { + source: "iana", + compressible: true, + extensions: ["bin", "dms", "lrf", "mar", "so", "dist", "distz", "pkg", "bpk", "dump", "elc", "deploy", "exe", "dll", "deb", "dmg", "iso", "img", "msi", "msp", "msm", "buffer"] + }, + "application/oda": { + source: "iana", + extensions: ["oda"] + }, + "application/odm+xml": { + source: "iana", + compressible: true + }, + "application/odx": { + source: "iana" + }, + "application/oebps-package+xml": { + source: "iana", + compressible: true, + extensions: ["opf"] + }, + "application/ogg": { + source: "iana", + compressible: false, + extensions: ["ogx"] + }, + "application/ohttp-keys": { + source: "iana" + }, + "application/omdoc+xml": { + source: "apache", + compressible: true, + extensions: ["omdoc"] + }, + "application/onenote": { + source: "apache", + extensions: ["onetoc", "onetoc2", "onetmp", "onepkg", "one", "onea"] + }, + "application/opc-nodeset+xml": { + source: "iana", + compressible: true + }, + "application/oscore": { + source: "iana" + }, + "application/oxps": { + source: "iana", + extensions: ["oxps"] + }, + "application/p21": { + source: "iana" + }, + "application/p21+zip": { + source: "iana", + compressible: false + }, + "application/p2p-overlay+xml": { + source: "iana", + compressible: true, + extensions: ["relo"] + }, + "application/parityfec": { + source: "iana" + }, + "application/passport": { + source: "iana" + }, + "application/patch-ops-error+xml": { + source: "iana", + compressible: true, + extensions: ["xer"] + }, + "application/pdf": { + source: "iana", + compressible: false, + extensions: ["pdf"] + }, + "application/pdx": { + source: "iana" + }, + "application/pem-certificate-chain": { + source: "iana" + }, + "application/pgp-encrypted": { + source: "iana", + compressible: false, + extensions: ["pgp"] + }, + "application/pgp-keys": { + source: "iana", + extensions: ["asc"] + }, + "application/pgp-signature": { + source: "iana", + extensions: ["sig", "asc"] + }, + "application/pics-rules": { + source: "apache", + extensions: ["prf"] + }, + "application/pidf+xml": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/pidf-diff+xml": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/pkcs10": { + source: "iana", + extensions: ["p10"] + }, + "application/pkcs12": { + source: "iana" + }, + "application/pkcs7-mime": { + source: "iana", + extensions: ["p7m", "p7c"] + }, + "application/pkcs7-signature": { + source: "iana", + extensions: ["p7s"] + }, + "application/pkcs8": { + source: "iana", + extensions: ["p8"] + }, + "application/pkcs8-encrypted": { + source: "iana" + }, + "application/pkix-attr-cert": { + source: "iana", + extensions: ["ac"] + }, + "application/pkix-cert": { + source: "iana", + extensions: ["cer"] + }, + "application/pkix-crl": { + source: "iana", + extensions: ["crl"] + }, + "application/pkix-pkipath": { + source: "iana", + extensions: ["pkipath"] + }, + "application/pkixcmp": { + source: "iana", + extensions: ["pki"] + }, + "application/pls+xml": { + source: "iana", + compressible: true, + extensions: ["pls"] + }, + "application/poc-settings+xml": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/postscript": { + source: "iana", + compressible: true, + extensions: ["ai", "eps", "ps"] + }, + "application/ppsp-tracker+json": { + source: "iana", + compressible: true + }, + "application/private-token-issuer-directory": { + source: "iana" + }, + "application/private-token-request": { + source: "iana" + }, + "application/private-token-response": { + source: "iana" + }, + "application/problem+json": { + source: "iana", + compressible: true + }, + "application/problem+xml": { + source: "iana", + compressible: true + }, + "application/provenance+xml": { + source: "iana", + compressible: true, + extensions: ["provx"] + }, + "application/provided-claims+jwt": { + source: "iana" + }, + "application/prs.alvestrand.titrax-sheet": { + source: "iana" + }, + "application/prs.cww": { + source: "iana", + extensions: ["cww"] + }, + "application/prs.cyn": { + source: "iana", + charset: "7-BIT" + }, + "application/prs.hpub+zip": { + source: "iana", + compressible: false + }, + "application/prs.implied-document+xml": { + source: "iana", + compressible: true + }, + "application/prs.implied-executable": { + source: "iana" + }, + "application/prs.implied-object+json": { + source: "iana", + compressible: true + }, + "application/prs.implied-object+json-seq": { + source: "iana" + }, + "application/prs.implied-object+yaml": { + source: "iana" + }, + "application/prs.implied-structure": { + source: "iana" + }, + "application/prs.mayfile": { + source: "iana" + }, + "application/prs.nprend": { + source: "iana" + }, + "application/prs.plucker": { + source: "iana" + }, + "application/prs.rdf-xml-crypt": { + source: "iana" + }, + "application/prs.vcfbzip2": { + source: "iana" + }, + "application/prs.xsf+xml": { + source: "iana", + compressible: true, + extensions: ["xsf"] + }, + "application/pskc+xml": { + source: "iana", + compressible: true, + extensions: ["pskcxml"] + }, + "application/pvd+json": { + source: "iana", + compressible: true + }, + "application/qsig": { + source: "iana" + }, + "application/raml+yaml": { + compressible: true, + extensions: ["raml"] + }, + "application/raptorfec": { + source: "iana" + }, + "application/rdap+json": { + source: "iana", + compressible: true + }, + "application/rdf+xml": { + source: "iana", + compressible: true, + extensions: ["rdf", "owl"] + }, + "application/reginfo+xml": { + source: "iana", + compressible: true, + extensions: ["rif"] + }, + "application/relax-ng-compact-syntax": { + source: "iana", + extensions: ["rnc"] + }, + "application/remote-printing": { + source: "apache" + }, + "application/reputon+json": { + source: "iana", + compressible: true + }, + "application/resolve-response+jwt": { + source: "iana" + }, + "application/resource-lists+xml": { + source: "iana", + compressible: true, + extensions: ["rl"] + }, + "application/resource-lists-diff+xml": { + source: "iana", + compressible: true, + extensions: ["rld"] + }, + "application/rfc+xml": { + source: "iana", + compressible: true + }, + "application/riscos": { + source: "iana" + }, + "application/rlmi+xml": { + source: "iana", + compressible: true + }, + "application/rls-services+xml": { + source: "iana", + compressible: true, + extensions: ["rs"] + }, + "application/route-apd+xml": { + source: "iana", + compressible: true, + extensions: ["rapd"] + }, + "application/route-s-tsid+xml": { + source: "iana", + compressible: true, + extensions: ["sls"] + }, + "application/route-usd+xml": { + source: "iana", + compressible: true, + extensions: ["rusd"] + }, + "application/rpki-checklist": { + source: "iana" + }, + "application/rpki-ghostbusters": { + source: "iana", + extensions: ["gbr"] + }, + "application/rpki-manifest": { + source: "iana", + extensions: ["mft"] + }, + "application/rpki-publication": { + source: "iana" + }, + "application/rpki-roa": { + source: "iana", + extensions: ["roa"] + }, + "application/rpki-signed-tal": { + source: "iana" + }, + "application/rpki-updown": { + source: "iana" + }, + "application/rsd+xml": { + source: "apache", + compressible: true, + extensions: ["rsd"] + }, + "application/rss+xml": { + source: "apache", + compressible: true, + extensions: ["rss"] + }, + "application/rtf": { + source: "iana", + compressible: true, + extensions: ["rtf"] + }, + "application/rtploopback": { + source: "iana" + }, + "application/rtx": { + source: "iana" + }, + "application/samlassertion+xml": { + source: "iana", + compressible: true + }, + "application/samlmetadata+xml": { + source: "iana", + compressible: true + }, + "application/sarif+json": { + source: "iana", + compressible: true + }, + "application/sarif-external-properties+json": { + source: "iana", + compressible: true + }, + "application/sbe": { + source: "iana" + }, + "application/sbml+xml": { + source: "iana", + compressible: true, + extensions: ["sbml"] + }, + "application/scaip+xml": { + source: "iana", + compressible: true + }, + "application/scim+json": { + source: "iana", + compressible: true + }, + "application/scvp-cv-request": { + source: "iana", + extensions: ["scq"] + }, + "application/scvp-cv-response": { + source: "iana", + extensions: ["scs"] + }, + "application/scvp-vp-request": { + source: "iana", + extensions: ["spq"] + }, + "application/scvp-vp-response": { + source: "iana", + extensions: ["spp"] + }, + "application/sdp": { + source: "iana", + extensions: ["sdp"] + }, + "application/secevent+jwt": { + source: "iana" + }, + "application/senml+cbor": { + source: "iana" + }, + "application/senml+json": { + source: "iana", + compressible: true + }, + "application/senml+xml": { + source: "iana", + compressible: true, + extensions: ["senmlx"] + }, + "application/senml-etch+cbor": { + source: "iana" + }, + "application/senml-etch+json": { + source: "iana", + compressible: true + }, + "application/senml-exi": { + source: "iana" + }, + "application/sensml+cbor": { + source: "iana" + }, + "application/sensml+json": { + source: "iana", + compressible: true + }, + "application/sensml+xml": { + source: "iana", + compressible: true, + extensions: ["sensmlx"] + }, + "application/sensml-exi": { + source: "iana" + }, + "application/sep+xml": { + source: "iana", + compressible: true + }, + "application/sep-exi": { + source: "iana" + }, + "application/session-info": { + source: "iana" + }, + "application/set-payment": { + source: "iana" + }, + "application/set-payment-initiation": { + source: "iana", + extensions: ["setpay"] + }, + "application/set-registration": { + source: "iana" + }, + "application/set-registration-initiation": { + source: "iana", + extensions: ["setreg"] + }, + "application/sgml": { + source: "iana" + }, + "application/sgml-open-catalog": { + source: "iana" + }, + "application/shf+xml": { + source: "iana", + compressible: true, + extensions: ["shf"] + }, + "application/sieve": { + source: "iana", + extensions: ["siv", "sieve"] + }, + "application/simple-filter+xml": { + source: "iana", + compressible: true + }, + "application/simple-message-summary": { + source: "iana" + }, + "application/simplesymbolcontainer": { + source: "iana" + }, + "application/sipc": { + source: "iana" + }, + "application/slate": { + source: "iana" + }, + "application/smil": { + source: "apache" + }, + "application/smil+xml": { + source: "iana", + compressible: true, + extensions: ["smi", "smil"] + }, + "application/smpte336m": { + source: "iana" + }, + "application/soap+fastinfoset": { + source: "iana" + }, + "application/soap+xml": { + source: "iana", + compressible: true + }, + "application/sparql-query": { + source: "iana", + extensions: ["rq"] + }, + "application/sparql-results+xml": { + source: "iana", + compressible: true, + extensions: ["srx"] + }, + "application/spdx+json": { + source: "iana", + compressible: true + }, + "application/spirits-event+xml": { + source: "iana", + compressible: true + }, + "application/sql": { + source: "iana", + extensions: ["sql"] + }, + "application/srgs": { + source: "iana", + extensions: ["gram"] + }, + "application/srgs+xml": { + source: "iana", + compressible: true, + extensions: ["grxml"] + }, + "application/sru+xml": { + source: "iana", + compressible: true, + extensions: ["sru"] + }, + "application/ssdl+xml": { + source: "apache", + compressible: true, + extensions: ["ssdl"] + }, + "application/sslkeylogfile": { + source: "iana" + }, + "application/ssml+xml": { + source: "iana", + compressible: true, + extensions: ["ssml"] + }, + "application/st2110-41": { + source: "iana" + }, + "application/stix+json": { + source: "iana", + compressible: true + }, + "application/stratum": { + source: "iana" + }, + "application/swid+cbor": { + source: "iana" + }, + "application/swid+xml": { + source: "iana", + compressible: true, + extensions: ["swidtag"] + }, + "application/tamp-apex-update": { + source: "iana" + }, + "application/tamp-apex-update-confirm": { + source: "iana" + }, + "application/tamp-community-update": { + source: "iana" + }, + "application/tamp-community-update-confirm": { + source: "iana" + }, + "application/tamp-error": { + source: "iana" + }, + "application/tamp-sequence-adjust": { + source: "iana" + }, + "application/tamp-sequence-adjust-confirm": { + source: "iana" + }, + "application/tamp-status-query": { + source: "iana" + }, + "application/tamp-status-response": { + source: "iana" + }, + "application/tamp-update": { + source: "iana" + }, + "application/tamp-update-confirm": { + source: "iana" + }, + "application/tar": { + compressible: true + }, + "application/taxii+json": { + source: "iana", + compressible: true + }, + "application/td+json": { + source: "iana", + compressible: true + }, + "application/tei+xml": { + source: "iana", + compressible: true, + extensions: ["tei", "teicorpus"] + }, + "application/tetra_isi": { + source: "iana" + }, + "application/thraud+xml": { + source: "iana", + compressible: true, + extensions: ["tfi"] + }, + "application/timestamp-query": { + source: "iana" + }, + "application/timestamp-reply": { + source: "iana" + }, + "application/timestamped-data": { + source: "iana", + extensions: ["tsd"] + }, + "application/tlsrpt+gzip": { + source: "iana" + }, + "application/tlsrpt+json": { + source: "iana", + compressible: true + }, + "application/tm+json": { + source: "iana", + compressible: true + }, + "application/tnauthlist": { + source: "iana" + }, + "application/toc+cbor": { + source: "iana" + }, + "application/token-introspection+jwt": { + source: "iana" + }, + "application/toml": { + source: "iana", + compressible: true, + extensions: ["toml"] + }, + "application/trickle-ice-sdpfrag": { + source: "iana" + }, + "application/trig": { + source: "iana", + extensions: ["trig"] + }, + "application/trust-chain+json": { + source: "iana", + compressible: true + }, + "application/trust-mark+jwt": { + source: "iana" + }, + "application/trust-mark-delegation+jwt": { + source: "iana" + }, + "application/ttml+xml": { + source: "iana", + compressible: true, + extensions: ["ttml"] + }, + "application/tve-trigger": { + source: "iana" + }, + "application/tzif": { + source: "iana" + }, + "application/tzif-leap": { + source: "iana" + }, + "application/ubjson": { + compressible: false, + extensions: ["ubj"] + }, + "application/uccs+cbor": { + source: "iana" + }, + "application/ujcs+json": { + source: "iana", + compressible: true + }, + "application/ulpfec": { + source: "iana" + }, + "application/urc-grpsheet+xml": { + source: "iana", + compressible: true + }, + "application/urc-ressheet+xml": { + source: "iana", + compressible: true, + extensions: ["rsheet"] + }, + "application/urc-targetdesc+xml": { + source: "iana", + compressible: true, + extensions: ["td"] + }, + "application/urc-uisocketdesc+xml": { + source: "iana", + compressible: true + }, + "application/vc": { + source: "iana" + }, + "application/vc+cose": { + source: "iana" + }, + "application/vc+jwt": { + source: "iana" + }, + "application/vcard+json": { + source: "iana", + compressible: true + }, + "application/vcard+xml": { + source: "iana", + compressible: true + }, + "application/vemmi": { + source: "iana" + }, + "application/vividence.scriptfile": { + source: "apache" + }, + "application/vnd.1000minds.decision-model+xml": { + source: "iana", + compressible: true, + extensions: ["1km"] + }, + "application/vnd.1ob": { + source: "iana" + }, + "application/vnd.3gpp-prose+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp-prose-pc3a+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp-prose-pc3ach+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp-prose-pc3ch+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp-prose-pc8+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp-v2x-local-service-information": { + source: "iana" + }, + "application/vnd.3gpp.5gnas": { + source: "iana" + }, + "application/vnd.3gpp.5gsa2x": { + source: "iana" + }, + "application/vnd.3gpp.5gsa2x-local-service-information": { + source: "iana" + }, + "application/vnd.3gpp.5gsv2x": { + source: "iana" + }, + "application/vnd.3gpp.5gsv2x-local-service-information": { + source: "iana" + }, + "application/vnd.3gpp.access-transfer-events+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.bsf+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.crs+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.current-location-discovery+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.gmop+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.gtpc": { + source: "iana" + }, + "application/vnd.3gpp.interworking-data": { + source: "iana" + }, + "application/vnd.3gpp.lpp": { + source: "iana" + }, + "application/vnd.3gpp.mc-signalling-ear": { + source: "iana" + }, + "application/vnd.3gpp.mcdata-affiliation-command+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcdata-info+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcdata-msgstore-ctrl-request+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcdata-payload": { + source: "iana" + }, + "application/vnd.3gpp.mcdata-regroup+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcdata-service-config+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcdata-signalling": { + source: "iana" + }, + "application/vnd.3gpp.mcdata-ue-config+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcdata-user-profile+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcptt-affiliation-command+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcptt-floor-request+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcptt-info+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcptt-location-info+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcptt-mbms-usage-info+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcptt-regroup+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcptt-service-config+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcptt-signed+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcptt-ue-config+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcptt-ue-init-config+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcptt-user-profile+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcvideo-affiliation-command+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcvideo-info+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcvideo-location-info+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcvideo-mbms-usage-info+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcvideo-regroup+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcvideo-service-config+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcvideo-transmission-request+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcvideo-ue-config+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcvideo-user-profile+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mid-call+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.ngap": { + source: "iana" + }, + "application/vnd.3gpp.pfcp": { + source: "iana" + }, + "application/vnd.3gpp.pic-bw-large": { + source: "iana", + extensions: ["plb"] + }, + "application/vnd.3gpp.pic-bw-small": { + source: "iana", + extensions: ["psb"] + }, + "application/vnd.3gpp.pic-bw-var": { + source: "iana", + extensions: ["pvb"] + }, + "application/vnd.3gpp.pinapp-info+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.s1ap": { + source: "iana" + }, + "application/vnd.3gpp.seal-group-doc+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.seal-info+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.seal-location-info+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.seal-mbms-usage-info+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.seal-network-qos-management-info+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.seal-ue-config-info+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.seal-unicast-info+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.seal-user-profile-info+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.sms": { + source: "iana" + }, + "application/vnd.3gpp.sms+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.srvcc-ext+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.srvcc-info+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.state-and-event-info+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.ussd+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.v2x": { + source: "iana" + }, + "application/vnd.3gpp.vae-info+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp2.bcmcsinfo+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp2.sms": { + source: "iana" + }, + "application/vnd.3gpp2.tcap": { + source: "iana", + extensions: ["tcap"] + }, + "application/vnd.3lightssoftware.imagescal": { + source: "iana" + }, + "application/vnd.3m.post-it-notes": { + source: "iana", + extensions: ["pwn"] + }, + "application/vnd.accpac.simply.aso": { + source: "iana", + extensions: ["aso"] + }, + "application/vnd.accpac.simply.imp": { + source: "iana", + extensions: ["imp"] + }, + "application/vnd.acm.addressxfer+json": { + source: "iana", + compressible: true + }, + "application/vnd.acm.chatbot+json": { + source: "iana", + compressible: true + }, + "application/vnd.acucobol": { + source: "iana", + extensions: ["acu"] + }, + "application/vnd.acucorp": { + source: "iana", + extensions: ["atc", "acutc"] + }, + "application/vnd.adobe.air-application-installer-package+zip": { + source: "apache", + compressible: false, + extensions: ["air"] + }, + "application/vnd.adobe.flash.movie": { + source: "iana" + }, + "application/vnd.adobe.formscentral.fcdt": { + source: "iana", + extensions: ["fcdt"] + }, + "application/vnd.adobe.fxp": { + source: "iana", + extensions: ["fxp", "fxpl"] + }, + "application/vnd.adobe.partial-upload": { + source: "iana" + }, + "application/vnd.adobe.xdp+xml": { + source: "iana", + compressible: true, + extensions: ["xdp"] + }, + "application/vnd.adobe.xfdf": { + source: "apache", + extensions: ["xfdf"] + }, + "application/vnd.aether.imp": { + source: "iana" + }, + "application/vnd.afpc.afplinedata": { + source: "iana" + }, + "application/vnd.afpc.afplinedata-pagedef": { + source: "iana" + }, + "application/vnd.afpc.cmoca-cmresource": { + source: "iana" + }, + "application/vnd.afpc.foca-charset": { + source: "iana" + }, + "application/vnd.afpc.foca-codedfont": { + source: "iana" + }, + "application/vnd.afpc.foca-codepage": { + source: "iana" + }, + "application/vnd.afpc.modca": { + source: "iana" + }, + "application/vnd.afpc.modca-cmtable": { + source: "iana" + }, + "application/vnd.afpc.modca-formdef": { + source: "iana" + }, + "application/vnd.afpc.modca-mediummap": { + source: "iana" + }, + "application/vnd.afpc.modca-objectcontainer": { + source: "iana" + }, + "application/vnd.afpc.modca-overlay": { + source: "iana" + }, + "application/vnd.afpc.modca-pagesegment": { + source: "iana" + }, + "application/vnd.age": { + source: "iana", + extensions: ["age"] + }, + "application/vnd.ah-barcode": { + source: "apache" + }, + "application/vnd.ahead.space": { + source: "iana", + extensions: ["ahead"] + }, + "application/vnd.airzip.filesecure.azf": { + source: "iana", + extensions: ["azf"] + }, + "application/vnd.airzip.filesecure.azs": { + source: "iana", + extensions: ["azs"] + }, + "application/vnd.amadeus+json": { + source: "iana", + compressible: true + }, + "application/vnd.amazon.ebook": { + source: "apache", + extensions: ["azw"] + }, + "application/vnd.amazon.mobi8-ebook": { + source: "iana" + }, + "application/vnd.americandynamics.acc": { + source: "iana", + extensions: ["acc"] + }, + "application/vnd.amiga.ami": { + source: "iana", + extensions: ["ami"] + }, + "application/vnd.amundsen.maze+xml": { + source: "iana", + compressible: true + }, + "application/vnd.android.ota": { + source: "iana" + }, + "application/vnd.android.package-archive": { + source: "apache", + compressible: false, + extensions: ["apk"] + }, + "application/vnd.anki": { + source: "iana" + }, + "application/vnd.anser-web-certificate-issue-initiation": { + source: "iana", + extensions: ["cii"] + }, + "application/vnd.anser-web-funds-transfer-initiation": { + source: "apache", + extensions: ["fti"] + }, + "application/vnd.antix.game-component": { + source: "iana", + extensions: ["atx"] + }, + "application/vnd.apache.arrow.file": { + source: "iana" + }, + "application/vnd.apache.arrow.stream": { + source: "iana" + }, + "application/vnd.apache.parquet": { + source: "iana" + }, + "application/vnd.apache.thrift.binary": { + source: "iana" + }, + "application/vnd.apache.thrift.compact": { + source: "iana" + }, + "application/vnd.apache.thrift.json": { + source: "iana" + }, + "application/vnd.apexlang": { + source: "iana" + }, + "application/vnd.api+json": { + source: "iana", + compressible: true + }, + "application/vnd.aplextor.warrp+json": { + source: "iana", + compressible: true + }, + "application/vnd.apothekende.reservation+json": { + source: "iana", + compressible: true + }, + "application/vnd.apple.installer+xml": { + source: "iana", + compressible: true, + extensions: ["mpkg"] + }, + "application/vnd.apple.keynote": { + source: "iana", + extensions: ["key"] + }, + "application/vnd.apple.mpegurl": { + source: "iana", + extensions: ["m3u8"] + }, + "application/vnd.apple.numbers": { + source: "iana", + extensions: ["numbers"] + }, + "application/vnd.apple.pages": { + source: "iana", + extensions: ["pages"] + }, + "application/vnd.apple.pkpass": { + compressible: false, + extensions: ["pkpass"] + }, + "application/vnd.arastra.swi": { + source: "apache" + }, + "application/vnd.aristanetworks.swi": { + source: "iana", + extensions: ["swi"] + }, + "application/vnd.artisan+json": { + source: "iana", + compressible: true + }, + "application/vnd.artsquare": { + source: "iana" + }, + "application/vnd.astraea-software.iota": { + source: "iana", + extensions: ["iota"] + }, + "application/vnd.audiograph": { + source: "iana", + extensions: ["aep"] + }, + "application/vnd.autodesk.fbx": { + extensions: ["fbx"] + }, + "application/vnd.autopackage": { + source: "iana" + }, + "application/vnd.avalon+json": { + source: "iana", + compressible: true + }, + "application/vnd.avistar+xml": { + source: "iana", + compressible: true + }, + "application/vnd.balsamiq.bmml+xml": { + source: "iana", + compressible: true, + extensions: ["bmml"] + }, + "application/vnd.balsamiq.bmpr": { + source: "iana" + }, + "application/vnd.banana-accounting": { + source: "iana" + }, + "application/vnd.bbf.usp.error": { + source: "iana" + }, + "application/vnd.bbf.usp.msg": { + source: "iana" + }, + "application/vnd.bbf.usp.msg+json": { + source: "iana", + compressible: true + }, + "application/vnd.bekitzur-stech+json": { + source: "iana", + compressible: true + }, + "application/vnd.belightsoft.lhzd+zip": { + source: "iana", + compressible: false + }, + "application/vnd.belightsoft.lhzl+zip": { + source: "iana", + compressible: false + }, + "application/vnd.bint.med-content": { + source: "iana" + }, + "application/vnd.biopax.rdf+xml": { + source: "iana", + compressible: true + }, + "application/vnd.blink-idb-value-wrapper": { + source: "iana" + }, + "application/vnd.blueice.multipass": { + source: "iana", + extensions: ["mpm"] + }, + "application/vnd.bluetooth.ep.oob": { + source: "iana" + }, + "application/vnd.bluetooth.le.oob": { + source: "iana" + }, + "application/vnd.bmi": { + source: "iana", + extensions: ["bmi"] + }, + "application/vnd.bpf": { + source: "iana" + }, + "application/vnd.bpf3": { + source: "iana" + }, + "application/vnd.businessobjects": { + source: "iana", + extensions: ["rep"] + }, + "application/vnd.byu.uapi+json": { + source: "iana", + compressible: true + }, + "application/vnd.bzip3": { + source: "iana" + }, + "application/vnd.c3voc.schedule+xml": { + source: "iana", + compressible: true + }, + "application/vnd.cab-jscript": { + source: "iana" + }, + "application/vnd.canon-cpdl": { + source: "iana" + }, + "application/vnd.canon-lips": { + source: "iana" + }, + "application/vnd.capasystems-pg+json": { + source: "iana", + compressible: true + }, + "application/vnd.cendio.thinlinc.clientconf": { + source: "iana" + }, + "application/vnd.century-systems.tcp_stream": { + source: "iana" + }, + "application/vnd.chemdraw+xml": { + source: "iana", + compressible: true, + extensions: ["cdxml"] + }, + "application/vnd.chess-pgn": { + source: "iana" + }, + "application/vnd.chipnuts.karaoke-mmd": { + source: "iana", + extensions: ["mmd"] + }, + "application/vnd.ciedi": { + source: "iana" + }, + "application/vnd.cinderella": { + source: "iana", + extensions: ["cdy"] + }, + "application/vnd.cirpack.isdn-ext": { + source: "iana" + }, + "application/vnd.citationstyles.style+xml": { + source: "iana", + compressible: true, + extensions: ["csl"] + }, + "application/vnd.claymore": { + source: "iana", + extensions: ["cla"] + }, + "application/vnd.cloanto.rp9": { + source: "iana", + extensions: ["rp9"] + }, + "application/vnd.clonk.c4group": { + source: "iana", + extensions: ["c4g", "c4d", "c4f", "c4p", "c4u"] + }, + "application/vnd.cluetrust.cartomobile-config": { + source: "iana", + extensions: ["c11amc"] + }, + "application/vnd.cluetrust.cartomobile-config-pkg": { + source: "iana", + extensions: ["c11amz"] + }, + "application/vnd.cncf.helm.chart.content.v1.tar+gzip": { + source: "iana" + }, + "application/vnd.cncf.helm.chart.provenance.v1.prov": { + source: "iana" + }, + "application/vnd.cncf.helm.config.v1+json": { + source: "iana", + compressible: true + }, + "application/vnd.coffeescript": { + source: "iana" + }, + "application/vnd.collabio.xodocuments.document": { + source: "iana" + }, + "application/vnd.collabio.xodocuments.document-template": { + source: "iana" + }, + "application/vnd.collabio.xodocuments.presentation": { + source: "iana" + }, + "application/vnd.collabio.xodocuments.presentation-template": { + source: "iana" + }, + "application/vnd.collabio.xodocuments.spreadsheet": { + source: "iana" + }, + "application/vnd.collabio.xodocuments.spreadsheet-template": { + source: "iana" + }, + "application/vnd.collection+json": { + source: "iana", + compressible: true + }, + "application/vnd.collection.doc+json": { + source: "iana", + compressible: true + }, + "application/vnd.collection.next+json": { + source: "iana", + compressible: true + }, + "application/vnd.comicbook+zip": { + source: "iana", + compressible: false + }, + "application/vnd.comicbook-rar": { + source: "iana" + }, + "application/vnd.commerce-battelle": { + source: "iana" + }, + "application/vnd.commonspace": { + source: "iana", + extensions: ["csp"] + }, + "application/vnd.contact.cmsg": { + source: "iana", + extensions: ["cdbcmsg"] + }, + "application/vnd.coreos.ignition+json": { + source: "iana", + compressible: true + }, + "application/vnd.cosmocaller": { + source: "iana", + extensions: ["cmc"] + }, + "application/vnd.crick.clicker": { + source: "iana", + extensions: ["clkx"] + }, + "application/vnd.crick.clicker.keyboard": { + source: "iana", + extensions: ["clkk"] + }, + "application/vnd.crick.clicker.palette": { + source: "iana", + extensions: ["clkp"] + }, + "application/vnd.crick.clicker.template": { + source: "iana", + extensions: ["clkt"] + }, + "application/vnd.crick.clicker.wordbank": { + source: "iana", + extensions: ["clkw"] + }, + "application/vnd.criticaltools.wbs+xml": { + source: "iana", + compressible: true, + extensions: ["wbs"] + }, + "application/vnd.cryptii.pipe+json": { + source: "iana", + compressible: true + }, + "application/vnd.crypto-shade-file": { + source: "iana" + }, + "application/vnd.cryptomator.encrypted": { + source: "iana" + }, + "application/vnd.cryptomator.vault": { + source: "iana" + }, + "application/vnd.ctc-posml": { + source: "iana", + extensions: ["pml"] + }, + "application/vnd.ctct.ws+xml": { + source: "iana", + compressible: true + }, + "application/vnd.cups-pdf": { + source: "iana" + }, + "application/vnd.cups-postscript": { + source: "iana" + }, + "application/vnd.cups-ppd": { + source: "iana", + extensions: ["ppd"] + }, + "application/vnd.cups-raster": { + source: "iana" + }, + "application/vnd.cups-raw": { + source: "iana" + }, + "application/vnd.curl": { + source: "iana" + }, + "application/vnd.curl.car": { + source: "apache", + extensions: ["car"] + }, + "application/vnd.curl.pcurl": { + source: "apache", + extensions: ["pcurl"] + }, + "application/vnd.cyan.dean.root+xml": { + source: "iana", + compressible: true + }, + "application/vnd.cybank": { + source: "iana" + }, + "application/vnd.cyclonedx+json": { + source: "iana", + compressible: true + }, + "application/vnd.cyclonedx+xml": { + source: "iana", + compressible: true + }, + "application/vnd.d2l.coursepackage1p0+zip": { + source: "iana", + compressible: false + }, + "application/vnd.d3m-dataset": { + source: "iana" + }, + "application/vnd.d3m-problem": { + source: "iana" + }, + "application/vnd.dart": { + source: "iana", + compressible: true, + extensions: ["dart"] + }, + "application/vnd.data-vision.rdz": { + source: "iana", + extensions: ["rdz"] + }, + "application/vnd.datalog": { + source: "iana" + }, + "application/vnd.datapackage+json": { + source: "iana", + compressible: true + }, + "application/vnd.dataresource+json": { + source: "iana", + compressible: true + }, + "application/vnd.dbf": { + source: "iana", + extensions: ["dbf"] + }, + "application/vnd.dcmp+xml": { + source: "iana", + compressible: true, + extensions: ["dcmp"] + }, + "application/vnd.debian.binary-package": { + source: "iana" + }, + "application/vnd.dece.data": { + source: "iana", + extensions: ["uvf", "uvvf", "uvd", "uvvd"] + }, + "application/vnd.dece.ttml+xml": { + source: "iana", + compressible: true, + extensions: ["uvt", "uvvt"] + }, + "application/vnd.dece.unspecified": { + source: "iana", + extensions: ["uvx", "uvvx"] + }, + "application/vnd.dece.zip": { + source: "iana", + extensions: ["uvz", "uvvz"] + }, + "application/vnd.denovo.fcselayout-link": { + source: "iana", + extensions: ["fe_launch"] + }, + "application/vnd.desmume.movie": { + source: "iana" + }, + "application/vnd.dir-bi.plate-dl-nosuffix": { + source: "iana" + }, + "application/vnd.dm.delegation+xml": { + source: "iana", + compressible: true + }, + "application/vnd.dna": { + source: "iana", + extensions: ["dna"] + }, + "application/vnd.document+json": { + source: "iana", + compressible: true + }, + "application/vnd.dolby.mlp": { + source: "apache", + extensions: ["mlp"] + }, + "application/vnd.dolby.mobile.1": { + source: "iana" + }, + "application/vnd.dolby.mobile.2": { + source: "iana" + }, + "application/vnd.doremir.scorecloud-binary-document": { + source: "iana" + }, + "application/vnd.dpgraph": { + source: "iana", + extensions: ["dpg"] + }, + "application/vnd.dreamfactory": { + source: "iana", + extensions: ["dfac"] + }, + "application/vnd.drive+json": { + source: "iana", + compressible: true + }, + "application/vnd.ds-keypoint": { + source: "apache", + extensions: ["kpxx"] + }, + "application/vnd.dtg.local": { + source: "iana" + }, + "application/vnd.dtg.local.flash": { + source: "iana" + }, + "application/vnd.dtg.local.html": { + source: "iana" + }, + "application/vnd.dvb.ait": { + source: "iana", + extensions: ["ait"] + }, + "application/vnd.dvb.dvbisl+xml": { + source: "iana", + compressible: true + }, + "application/vnd.dvb.dvbj": { + source: "iana" + }, + "application/vnd.dvb.esgcontainer": { + source: "iana" + }, + "application/vnd.dvb.ipdcdftnotifaccess": { + source: "iana" + }, + "application/vnd.dvb.ipdcesgaccess": { + source: "iana" + }, + "application/vnd.dvb.ipdcesgaccess2": { + source: "iana" + }, + "application/vnd.dvb.ipdcesgpdd": { + source: "iana" + }, + "application/vnd.dvb.ipdcroaming": { + source: "iana" + }, + "application/vnd.dvb.iptv.alfec-base": { + source: "iana" + }, + "application/vnd.dvb.iptv.alfec-enhancement": { + source: "iana" + }, + "application/vnd.dvb.notif-aggregate-root+xml": { + source: "iana", + compressible: true + }, + "application/vnd.dvb.notif-container+xml": { + source: "iana", + compressible: true + }, + "application/vnd.dvb.notif-generic+xml": { + source: "iana", + compressible: true + }, + "application/vnd.dvb.notif-ia-msglist+xml": { + source: "iana", + compressible: true + }, + "application/vnd.dvb.notif-ia-registration-request+xml": { + source: "iana", + compressible: true + }, + "application/vnd.dvb.notif-ia-registration-response+xml": { + source: "iana", + compressible: true + }, + "application/vnd.dvb.notif-init+xml": { + source: "iana", + compressible: true + }, + "application/vnd.dvb.pfr": { + source: "iana" + }, + "application/vnd.dvb.service": { + source: "iana", + extensions: ["svc"] + }, + "application/vnd.dxr": { + source: "iana" + }, + "application/vnd.dynageo": { + source: "iana", + extensions: ["geo"] + }, + "application/vnd.dzr": { + source: "iana" + }, + "application/vnd.easykaraoke.cdgdownload": { + source: "iana" + }, + "application/vnd.ecdis-update": { + source: "iana" + }, + "application/vnd.ecip.rlp": { + source: "iana" + }, + "application/vnd.eclipse.ditto+json": { + source: "iana", + compressible: true + }, + "application/vnd.ecowin.chart": { + source: "iana", + extensions: ["mag"] + }, + "application/vnd.ecowin.filerequest": { + source: "iana" + }, + "application/vnd.ecowin.fileupdate": { + source: "iana" + }, + "application/vnd.ecowin.series": { + source: "iana" + }, + "application/vnd.ecowin.seriesrequest": { + source: "iana" + }, + "application/vnd.ecowin.seriesupdate": { + source: "iana" + }, + "application/vnd.efi.img": { + source: "iana" + }, + "application/vnd.efi.iso": { + source: "iana" + }, + "application/vnd.eln+zip": { + source: "iana", + compressible: false + }, + "application/vnd.emclient.accessrequest+xml": { + source: "iana", + compressible: true + }, + "application/vnd.enliven": { + source: "iana", + extensions: ["nml"] + }, + "application/vnd.enphase.envoy": { + source: "iana" + }, + "application/vnd.eprints.data+xml": { + source: "iana", + compressible: true + }, + "application/vnd.epson.esf": { + source: "iana", + extensions: ["esf"] + }, + "application/vnd.epson.msf": { + source: "iana", + extensions: ["msf"] + }, + "application/vnd.epson.quickanime": { + source: "iana", + extensions: ["qam"] + }, + "application/vnd.epson.salt": { + source: "iana", + extensions: ["slt"] + }, + "application/vnd.epson.ssf": { + source: "iana", + extensions: ["ssf"] + }, + "application/vnd.ericsson.quickcall": { + source: "iana" + }, + "application/vnd.erofs": { + source: "iana" + }, + "application/vnd.espass-espass+zip": { + source: "iana", + compressible: false + }, + "application/vnd.eszigno3+xml": { + source: "iana", + compressible: true, + extensions: ["es3", "et3"] + }, + "application/vnd.etsi.aoc+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.asic-e+zip": { + source: "iana", + compressible: false + }, + "application/vnd.etsi.asic-s+zip": { + source: "iana", + compressible: false + }, + "application/vnd.etsi.cug+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.iptvcommand+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.iptvdiscovery+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.iptvprofile+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.iptvsad-bc+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.iptvsad-cod+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.iptvsad-npvr+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.iptvservice+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.iptvsync+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.iptvueprofile+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.mcid+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.mheg5": { + source: "iana" + }, + "application/vnd.etsi.overload-control-policy-dataset+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.pstn+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.sci+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.simservs+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.timestamp-token": { + source: "iana" + }, + "application/vnd.etsi.tsl+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.tsl.der": { + source: "iana" + }, + "application/vnd.eu.kasparian.car+json": { + source: "iana", + compressible: true + }, + "application/vnd.eudora.data": { + source: "iana" + }, + "application/vnd.evolv.ecig.profile": { + source: "iana" + }, + "application/vnd.evolv.ecig.settings": { + source: "iana" + }, + "application/vnd.evolv.ecig.theme": { + source: "iana" + }, + "application/vnd.exstream-empower+zip": { + source: "iana", + compressible: false + }, + "application/vnd.exstream-package": { + source: "iana" + }, + "application/vnd.ezpix-album": { + source: "iana", + extensions: ["ez2"] + }, + "application/vnd.ezpix-package": { + source: "iana", + extensions: ["ez3"] + }, + "application/vnd.f-secure.mobile": { + source: "iana" + }, + "application/vnd.familysearch.gedcom+zip": { + source: "iana", + compressible: false + }, + "application/vnd.fastcopy-disk-image": { + source: "iana" + }, + "application/vnd.fdf": { + source: "apache", + extensions: ["fdf"] + }, + "application/vnd.fdsn.mseed": { + source: "iana", + extensions: ["mseed"] + }, + "application/vnd.fdsn.seed": { + source: "iana", + extensions: ["seed", "dataless"] + }, + "application/vnd.fdsn.stationxml+xml": { + source: "iana", + charset: "XML-BASED", + compressible: true + }, + "application/vnd.ffsns": { + source: "iana" + }, + "application/vnd.ficlab.flb+zip": { + source: "iana", + compressible: false + }, + "application/vnd.filmit.zfc": { + source: "iana" + }, + "application/vnd.fints": { + source: "iana" + }, + "application/vnd.firemonkeys.cloudcell": { + source: "iana" + }, + "application/vnd.flographit": { + source: "iana", + extensions: ["gph"] + }, + "application/vnd.fluxtime.clip": { + source: "iana", + extensions: ["ftc"] + }, + "application/vnd.font-fontforge-sfd": { + source: "iana" + }, + "application/vnd.framemaker": { + source: "iana", + extensions: ["fm", "frame", "maker", "book"] + }, + "application/vnd.freelog.comic": { + source: "iana" + }, + "application/vnd.frogans.fnc": { + source: "apache", + extensions: ["fnc"] + }, + "application/vnd.frogans.ltf": { + source: "apache", + extensions: ["ltf"] + }, + "application/vnd.fsc.weblaunch": { + source: "iana", + extensions: ["fsc"] + }, + "application/vnd.fujifilm.fb.docuworks": { + source: "iana" + }, + "application/vnd.fujifilm.fb.docuworks.binder": { + source: "iana" + }, + "application/vnd.fujifilm.fb.docuworks.container": { + source: "iana" + }, + "application/vnd.fujifilm.fb.jfi+xml": { + source: "iana", + compressible: true + }, + "application/vnd.fujitsu.oasys": { + source: "iana", + extensions: ["oas"] + }, + "application/vnd.fujitsu.oasys2": { + source: "iana", + extensions: ["oa2"] + }, + "application/vnd.fujitsu.oasys3": { + source: "iana", + extensions: ["oa3"] + }, + "application/vnd.fujitsu.oasysgp": { + source: "iana", + extensions: ["fg5"] + }, + "application/vnd.fujitsu.oasysprs": { + source: "iana", + extensions: ["bh2"] + }, + "application/vnd.fujixerox.art-ex": { + source: "iana" + }, + "application/vnd.fujixerox.art4": { + source: "iana" + }, + "application/vnd.fujixerox.ddd": { + source: "iana", + extensions: ["ddd"] + }, + "application/vnd.fujixerox.docuworks": { + source: "iana", + extensions: ["xdw"] + }, + "application/vnd.fujixerox.docuworks.binder": { + source: "iana", + extensions: ["xbd"] + }, + "application/vnd.fujixerox.docuworks.container": { + source: "iana" + }, + "application/vnd.fujixerox.hbpl": { + source: "iana" + }, + "application/vnd.fut-misnet": { + source: "iana" + }, + "application/vnd.futoin+cbor": { + source: "iana" + }, + "application/vnd.futoin+json": { + source: "iana", + compressible: true + }, + "application/vnd.fuzzysheet": { + source: "iana", + extensions: ["fzs"] + }, + "application/vnd.ga4gh.passport+jwt": { + source: "iana" + }, + "application/vnd.genomatix.tuxedo": { + source: "iana", + extensions: ["txd"] + }, + "application/vnd.genozip": { + source: "iana" + }, + "application/vnd.gentics.grd+json": { + source: "iana", + compressible: true + }, + "application/vnd.gentoo.catmetadata+xml": { + source: "iana", + compressible: true + }, + "application/vnd.gentoo.ebuild": { + source: "iana" + }, + "application/vnd.gentoo.eclass": { + source: "iana" + }, + "application/vnd.gentoo.gpkg": { + source: "iana" + }, + "application/vnd.gentoo.manifest": { + source: "iana" + }, + "application/vnd.gentoo.pkgmetadata+xml": { + source: "iana", + compressible: true + }, + "application/vnd.gentoo.xpak": { + source: "iana" + }, + "application/vnd.geo+json": { + source: "apache", + compressible: true + }, + "application/vnd.geocube+xml": { + source: "apache", + compressible: true + }, + "application/vnd.geogebra.file": { + source: "iana", + extensions: ["ggb"] + }, + "application/vnd.geogebra.pinboard": { + source: "iana" + }, + "application/vnd.geogebra.slides": { + source: "iana", + extensions: ["ggs"] + }, + "application/vnd.geogebra.tool": { + source: "iana", + extensions: ["ggt"] + }, + "application/vnd.geometry-explorer": { + source: "iana", + extensions: ["gex", "gre"] + }, + "application/vnd.geonext": { + source: "iana", + extensions: ["gxt"] + }, + "application/vnd.geoplan": { + source: "iana", + extensions: ["g2w"] + }, + "application/vnd.geospace": { + source: "iana", + extensions: ["g3w"] + }, + "application/vnd.gerber": { + source: "iana" + }, + "application/vnd.globalplatform.card-content-mgt": { + source: "iana" + }, + "application/vnd.globalplatform.card-content-mgt-response": { + source: "iana" + }, + "application/vnd.gmx": { + source: "iana", + extensions: ["gmx"] + }, + "application/vnd.gnu.taler.exchange+json": { + source: "iana", + compressible: true + }, + "application/vnd.gnu.taler.merchant+json": { + source: "iana", + compressible: true + }, + "application/vnd.google-apps.audio": {}, + "application/vnd.google-apps.document": { + compressible: false, + extensions: ["gdoc"] + }, + "application/vnd.google-apps.drawing": { + compressible: false, + extensions: ["gdraw"] + }, + "application/vnd.google-apps.drive-sdk": { + compressible: false + }, + "application/vnd.google-apps.file": {}, + "application/vnd.google-apps.folder": { + compressible: false + }, + "application/vnd.google-apps.form": { + compressible: false, + extensions: ["gform"] + }, + "application/vnd.google-apps.fusiontable": {}, + "application/vnd.google-apps.jam": { + compressible: false, + extensions: ["gjam"] + }, + "application/vnd.google-apps.mail-layout": {}, + "application/vnd.google-apps.map": { + compressible: false, + extensions: ["gmap"] + }, + "application/vnd.google-apps.photo": {}, + "application/vnd.google-apps.presentation": { + compressible: false, + extensions: ["gslides"] + }, + "application/vnd.google-apps.script": { + compressible: false, + extensions: ["gscript"] + }, + "application/vnd.google-apps.shortcut": {}, + "application/vnd.google-apps.site": { + compressible: false, + extensions: ["gsite"] + }, + "application/vnd.google-apps.spreadsheet": { + compressible: false, + extensions: ["gsheet"] + }, + "application/vnd.google-apps.unknown": {}, + "application/vnd.google-apps.video": {}, + "application/vnd.google-earth.kml+xml": { + source: "iana", + compressible: true, + extensions: ["kml"] + }, + "application/vnd.google-earth.kmz": { + source: "iana", + compressible: false, + extensions: ["kmz"] + }, + "application/vnd.gov.sk.e-form+xml": { + source: "apache", + compressible: true + }, + "application/vnd.gov.sk.e-form+zip": { + source: "iana", + compressible: false + }, + "application/vnd.gov.sk.xmldatacontainer+xml": { + source: "iana", + compressible: true, + extensions: ["xdcf"] + }, + "application/vnd.gpxsee.map+xml": { + source: "iana", + compressible: true + }, + "application/vnd.grafeq": { + source: "iana", + extensions: ["gqf", "gqs"] + }, + "application/vnd.gridmp": { + source: "iana" + }, + "application/vnd.groove-account": { + source: "iana", + extensions: ["gac"] + }, + "application/vnd.groove-help": { + source: "iana", + extensions: ["ghf"] + }, + "application/vnd.groove-identity-message": { + source: "iana", + extensions: ["gim"] + }, + "application/vnd.groove-injector": { + source: "iana", + extensions: ["grv"] + }, + "application/vnd.groove-tool-message": { + source: "iana", + extensions: ["gtm"] + }, + "application/vnd.groove-tool-template": { + source: "iana", + extensions: ["tpl"] + }, + "application/vnd.groove-vcard": { + source: "iana", + extensions: ["vcg"] + }, + "application/vnd.hal+json": { + source: "iana", + compressible: true + }, + "application/vnd.hal+xml": { + source: "iana", + compressible: true, + extensions: ["hal"] + }, + "application/vnd.handheld-entertainment+xml": { + source: "iana", + compressible: true, + extensions: ["zmm"] + }, + "application/vnd.hbci": { + source: "iana", + extensions: ["hbci"] + }, + "application/vnd.hc+json": { + source: "iana", + compressible: true + }, + "application/vnd.hcl-bireports": { + source: "iana" + }, + "application/vnd.hdt": { + source: "iana" + }, + "application/vnd.heroku+json": { + source: "iana", + compressible: true + }, + "application/vnd.hhe.lesson-player": { + source: "iana", + extensions: ["les"] + }, + "application/vnd.hp-hpgl": { + source: "iana", + extensions: ["hpgl"] + }, + "application/vnd.hp-hpid": { + source: "iana", + extensions: ["hpid"] + }, + "application/vnd.hp-hps": { + source: "iana", + extensions: ["hps"] + }, + "application/vnd.hp-jlyt": { + source: "iana", + extensions: ["jlt"] + }, + "application/vnd.hp-pcl": { + source: "iana", + extensions: ["pcl"] + }, + "application/vnd.hp-pclxl": { + source: "iana", + extensions: ["pclxl"] + }, + "application/vnd.hsl": { + source: "iana" + }, + "application/vnd.httphone": { + source: "iana" + }, + "application/vnd.hydrostatix.sof-data": { + source: "iana", + extensions: ["sfd-hdstx"] + }, + "application/vnd.hyper+json": { + source: "iana", + compressible: true + }, + "application/vnd.hyper-item+json": { + source: "iana", + compressible: true + }, + "application/vnd.hyperdrive+json": { + source: "iana", + compressible: true + }, + "application/vnd.hzn-3d-crossword": { + source: "iana" + }, + "application/vnd.ibm.afplinedata": { + source: "apache" + }, + "application/vnd.ibm.electronic-media": { + source: "iana" + }, + "application/vnd.ibm.minipay": { + source: "iana", + extensions: ["mpy"] + }, + "application/vnd.ibm.modcap": { + source: "apache", + extensions: ["afp", "listafp", "list3820"] + }, + "application/vnd.ibm.rights-management": { + source: "iana", + extensions: ["irm"] + }, + "application/vnd.ibm.secure-container": { + source: "iana", + extensions: ["sc"] + }, + "application/vnd.iccprofile": { + source: "iana", + extensions: ["icc", "icm"] + }, + "application/vnd.ieee.1905": { + source: "iana" + }, + "application/vnd.igloader": { + source: "iana", + extensions: ["igl"] + }, + "application/vnd.imagemeter.folder+zip": { + source: "iana", + compressible: false + }, + "application/vnd.imagemeter.image+zip": { + source: "iana", + compressible: false + }, + "application/vnd.immervision-ivp": { + source: "iana", + extensions: ["ivp"] + }, + "application/vnd.immervision-ivu": { + source: "iana", + extensions: ["ivu"] + }, + "application/vnd.ims.imsccv1p1": { + source: "iana" + }, + "application/vnd.ims.imsccv1p2": { + source: "iana" + }, + "application/vnd.ims.imsccv1p3": { + source: "iana" + }, + "application/vnd.ims.lis.v2.result+json": { + source: "iana", + compressible: true + }, + "application/vnd.ims.lti.v2.toolconsumerprofile+json": { + source: "iana", + compressible: true + }, + "application/vnd.ims.lti.v2.toolproxy+json": { + source: "iana", + compressible: true + }, + "application/vnd.ims.lti.v2.toolproxy.id+json": { + source: "iana", + compressible: true + }, + "application/vnd.ims.lti.v2.toolsettings+json": { + source: "iana", + compressible: true + }, + "application/vnd.ims.lti.v2.toolsettings.simple+json": { + source: "iana", + compressible: true + }, + "application/vnd.informedcontrol.rms+xml": { + source: "iana", + compressible: true + }, + "application/vnd.informix-visionary": { + source: "apache" + }, + "application/vnd.infotech.project": { + source: "iana" + }, + "application/vnd.infotech.project+xml": { + source: "iana", + compressible: true + }, + "application/vnd.innopath.wamp.notification": { + source: "iana" + }, + "application/vnd.insors.igm": { + source: "iana", + extensions: ["igm"] + }, + "application/vnd.intercon.formnet": { + source: "iana", + extensions: ["xpw", "xpx"] + }, + "application/vnd.intergeo": { + source: "iana", + extensions: ["i2g"] + }, + "application/vnd.intertrust.digibox": { + source: "iana" + }, + "application/vnd.intertrust.nncp": { + source: "iana" + }, + "application/vnd.intu.qbo": { + source: "iana", + extensions: ["qbo"] + }, + "application/vnd.intu.qfx": { + source: "iana", + extensions: ["qfx"] + }, + "application/vnd.ipfs.ipns-record": { + source: "iana" + }, + "application/vnd.ipld.car": { + source: "iana" + }, + "application/vnd.ipld.dag-cbor": { + source: "iana" + }, + "application/vnd.ipld.dag-json": { + source: "iana" + }, + "application/vnd.ipld.raw": { + source: "iana" + }, + "application/vnd.iptc.g2.catalogitem+xml": { + source: "iana", + compressible: true + }, + "application/vnd.iptc.g2.conceptitem+xml": { + source: "iana", + compressible: true + }, + "application/vnd.iptc.g2.knowledgeitem+xml": { + source: "iana", + compressible: true + }, + "application/vnd.iptc.g2.newsitem+xml": { + source: "iana", + compressible: true + }, + "application/vnd.iptc.g2.newsmessage+xml": { + source: "iana", + compressible: true + }, + "application/vnd.iptc.g2.packageitem+xml": { + source: "iana", + compressible: true + }, + "application/vnd.iptc.g2.planningitem+xml": { + source: "iana", + compressible: true + }, + "application/vnd.ipunplugged.rcprofile": { + source: "iana", + extensions: ["rcprofile"] + }, + "application/vnd.irepository.package+xml": { + source: "iana", + compressible: true, + extensions: ["irp"] + }, + "application/vnd.is-xpr": { + source: "iana", + extensions: ["xpr"] + }, + "application/vnd.isac.fcs": { + source: "iana", + extensions: ["fcs"] + }, + "application/vnd.iso11783-10+zip": { + source: "iana", + compressible: false + }, + "application/vnd.jam": { + source: "iana", + extensions: ["jam"] + }, + "application/vnd.japannet-directory-service": { + source: "iana" + }, + "application/vnd.japannet-jpnstore-wakeup": { + source: "iana" + }, + "application/vnd.japannet-payment-wakeup": { + source: "iana" + }, + "application/vnd.japannet-registration": { + source: "iana" + }, + "application/vnd.japannet-registration-wakeup": { + source: "iana" + }, + "application/vnd.japannet-setstore-wakeup": { + source: "iana" + }, + "application/vnd.japannet-verification": { + source: "iana" + }, + "application/vnd.japannet-verification-wakeup": { + source: "iana" + }, + "application/vnd.jcp.javame.midlet-rms": { + source: "iana", + extensions: ["rms"] + }, + "application/vnd.jisp": { + source: "iana", + extensions: ["jisp"] + }, + "application/vnd.joost.joda-archive": { + source: "iana", + extensions: ["joda"] + }, + "application/vnd.jsk.isdn-ngn": { + source: "iana" + }, + "application/vnd.kahootz": { + source: "iana", + extensions: ["ktz", "ktr"] + }, + "application/vnd.kde.karbon": { + source: "iana", + extensions: ["karbon"] + }, + "application/vnd.kde.kchart": { + source: "iana", + extensions: ["chrt"] + }, + "application/vnd.kde.kformula": { + source: "iana", + extensions: ["kfo"] + }, + "application/vnd.kde.kivio": { + source: "iana", + extensions: ["flw"] + }, + "application/vnd.kde.kontour": { + source: "iana", + extensions: ["kon"] + }, + "application/vnd.kde.kpresenter": { + source: "iana", + extensions: ["kpr", "kpt"] + }, + "application/vnd.kde.kspread": { + source: "iana", + extensions: ["ksp"] + }, + "application/vnd.kde.kword": { + source: "iana", + extensions: ["kwd", "kwt"] + }, + "application/vnd.kdl": { + source: "iana" + }, + "application/vnd.kenameaapp": { + source: "iana", + extensions: ["htke"] + }, + "application/vnd.keyman.kmp+zip": { + source: "iana", + compressible: false + }, + "application/vnd.keyman.kmx": { + source: "iana" + }, + "application/vnd.kidspiration": { + source: "iana", + extensions: ["kia"] + }, + "application/vnd.kinar": { + source: "iana", + extensions: ["kne", "knp"] + }, + "application/vnd.koan": { + source: "iana", + extensions: ["skp", "skd", "skt", "skm"] + }, + "application/vnd.kodak-descriptor": { + source: "iana", + extensions: ["sse"] + }, + "application/vnd.las": { + source: "iana" + }, + "application/vnd.las.las+json": { + source: "iana", + compressible: true + }, + "application/vnd.las.las+xml": { + source: "iana", + compressible: true, + extensions: ["lasxml"] + }, + "application/vnd.laszip": { + source: "iana" + }, + "application/vnd.ldev.productlicensing": { + source: "iana" + }, + "application/vnd.leap+json": { + source: "iana", + compressible: true + }, + "application/vnd.liberty-request+xml": { + source: "iana", + compressible: true + }, + "application/vnd.llamagraphics.life-balance.desktop": { + source: "iana", + extensions: ["lbd"] + }, + "application/vnd.llamagraphics.life-balance.exchange+xml": { + source: "iana", + compressible: true, + extensions: ["lbe"] + }, + "application/vnd.logipipe.circuit+zip": { + source: "iana", + compressible: false + }, + "application/vnd.loom": { + source: "iana" + }, + "application/vnd.lotus-1-2-3": { + source: "iana", + extensions: ["123"] + }, + "application/vnd.lotus-approach": { + source: "iana", + extensions: ["apr"] + }, + "application/vnd.lotus-freelance": { + source: "iana", + extensions: ["pre"] + }, + "application/vnd.lotus-notes": { + source: "iana", + extensions: ["nsf"] + }, + "application/vnd.lotus-organizer": { + source: "iana", + extensions: ["org"] + }, + "application/vnd.lotus-screencam": { + source: "iana", + extensions: ["scm"] + }, + "application/vnd.lotus-wordpro": { + source: "iana", + extensions: ["lwp"] + }, + "application/vnd.macports.portpkg": { + source: "iana", + extensions: ["portpkg"] + }, + "application/vnd.mapbox-vector-tile": { + source: "iana", + extensions: ["mvt"] + }, + "application/vnd.marlin.drm.actiontoken+xml": { + source: "iana", + compressible: true + }, + "application/vnd.marlin.drm.conftoken+xml": { + source: "iana", + compressible: true + }, + "application/vnd.marlin.drm.license+xml": { + source: "iana", + compressible: true + }, + "application/vnd.marlin.drm.mdcf": { + source: "iana" + }, + "application/vnd.mason+json": { + source: "iana", + compressible: true + }, + "application/vnd.maxar.archive.3tz+zip": { + source: "iana", + compressible: false + }, + "application/vnd.maxmind.maxmind-db": { + source: "iana" + }, + "application/vnd.mcd": { + source: "iana", + extensions: ["mcd"] + }, + "application/vnd.mdl": { + source: "iana" + }, + "application/vnd.mdl-mbsdf": { + source: "iana" + }, + "application/vnd.medcalcdata": { + source: "iana", + extensions: ["mc1"] + }, + "application/vnd.mediastation.cdkey": { + source: "iana", + extensions: ["cdkey"] + }, + "application/vnd.medicalholodeck.recordxr": { + source: "iana" + }, + "application/vnd.meridian-slingshot": { + source: "iana" + }, + "application/vnd.mermaid": { + source: "iana" + }, + "application/vnd.mfer": { + source: "iana", + extensions: ["mwf"] + }, + "application/vnd.mfmp": { + source: "iana", + extensions: ["mfm"] + }, + "application/vnd.micro+json": { + source: "iana", + compressible: true + }, + "application/vnd.micrografx.flo": { + source: "iana", + extensions: ["flo"] + }, + "application/vnd.micrografx.igx": { + source: "iana", + extensions: ["igx"] + }, + "application/vnd.microsoft.portable-executable": { + source: "iana" + }, + "application/vnd.microsoft.windows.thumbnail-cache": { + source: "iana" + }, + "application/vnd.miele+json": { + source: "iana", + compressible: true + }, + "application/vnd.mif": { + source: "iana", + extensions: ["mif"] + }, + "application/vnd.minisoft-hp3000-save": { + source: "iana" + }, + "application/vnd.mitsubishi.misty-guard.trustweb": { + source: "iana" + }, + "application/vnd.mobius.daf": { + source: "iana", + extensions: ["daf"] + }, + "application/vnd.mobius.dis": { + source: "iana", + extensions: ["dis"] + }, + "application/vnd.mobius.mbk": { + source: "iana", + extensions: ["mbk"] + }, + "application/vnd.mobius.mqy": { + source: "iana", + extensions: ["mqy"] + }, + "application/vnd.mobius.msl": { + source: "iana", + extensions: ["msl"] + }, + "application/vnd.mobius.plc": { + source: "iana", + extensions: ["plc"] + }, + "application/vnd.mobius.txf": { + source: "iana", + extensions: ["txf"] + }, + "application/vnd.modl": { + source: "iana" + }, + "application/vnd.mophun.application": { + source: "iana", + extensions: ["mpn"] + }, + "application/vnd.mophun.certificate": { + source: "iana", + extensions: ["mpc"] + }, + "application/vnd.motorola.flexsuite": { + source: "iana" + }, + "application/vnd.motorola.flexsuite.adsi": { + source: "iana" + }, + "application/vnd.motorola.flexsuite.fis": { + source: "iana" + }, + "application/vnd.motorola.flexsuite.gotap": { + source: "iana" + }, + "application/vnd.motorola.flexsuite.kmr": { + source: "iana" + }, + "application/vnd.motorola.flexsuite.ttc": { + source: "iana" + }, + "application/vnd.motorola.flexsuite.wem": { + source: "iana" + }, + "application/vnd.motorola.iprm": { + source: "iana" + }, + "application/vnd.mozilla.xul+xml": { + source: "iana", + compressible: true, + extensions: ["xul"] + }, + "application/vnd.ms-3mfdocument": { + source: "iana" + }, + "application/vnd.ms-artgalry": { + source: "iana", + extensions: ["cil"] + }, + "application/vnd.ms-asf": { + source: "iana" + }, + "application/vnd.ms-cab-compressed": { + source: "iana", + extensions: ["cab"] + }, + "application/vnd.ms-color.iccprofile": { + source: "apache" + }, + "application/vnd.ms-excel": { + source: "iana", + compressible: false, + extensions: ["xls", "xlm", "xla", "xlc", "xlt", "xlw"] + }, + "application/vnd.ms-excel.addin.macroenabled.12": { + source: "iana", + extensions: ["xlam"] + }, + "application/vnd.ms-excel.sheet.binary.macroenabled.12": { + source: "iana", + extensions: ["xlsb"] + }, + "application/vnd.ms-excel.sheet.macroenabled.12": { + source: "iana", + extensions: ["xlsm"] + }, + "application/vnd.ms-excel.template.macroenabled.12": { + source: "iana", + extensions: ["xltm"] + }, + "application/vnd.ms-fontobject": { + source: "iana", + compressible: true, + extensions: ["eot"] + }, + "application/vnd.ms-htmlhelp": { + source: "iana", + extensions: ["chm"] + }, + "application/vnd.ms-ims": { + source: "iana", + extensions: ["ims"] + }, + "application/vnd.ms-lrm": { + source: "iana", + extensions: ["lrm"] + }, + "application/vnd.ms-office.activex+xml": { + source: "iana", + compressible: true + }, + "application/vnd.ms-officetheme": { + source: "iana", + extensions: ["thmx"] + }, + "application/vnd.ms-opentype": { + source: "apache", + compressible: true + }, + "application/vnd.ms-outlook": { + compressible: false, + extensions: ["msg"] + }, + "application/vnd.ms-package.obfuscated-opentype": { + source: "apache" + }, + "application/vnd.ms-pki.seccat": { + source: "apache", + extensions: ["cat"] + }, + "application/vnd.ms-pki.stl": { + source: "apache", + extensions: ["stl"] + }, + "application/vnd.ms-playready.initiator+xml": { + source: "iana", + compressible: true + }, + "application/vnd.ms-powerpoint": { + source: "iana", + compressible: false, + extensions: ["ppt", "pps", "pot"] + }, + "application/vnd.ms-powerpoint.addin.macroenabled.12": { + source: "iana", + extensions: ["ppam"] + }, + "application/vnd.ms-powerpoint.presentation.macroenabled.12": { + source: "iana", + extensions: ["pptm"] + }, + "application/vnd.ms-powerpoint.slide.macroenabled.12": { + source: "iana", + extensions: ["sldm"] + }, + "application/vnd.ms-powerpoint.slideshow.macroenabled.12": { + source: "iana", + extensions: ["ppsm"] + }, + "application/vnd.ms-powerpoint.template.macroenabled.12": { + source: "iana", + extensions: ["potm"] + }, + "application/vnd.ms-printdevicecapabilities+xml": { + source: "iana", + compressible: true + }, + "application/vnd.ms-printing.printticket+xml": { + source: "apache", + compressible: true + }, + "application/vnd.ms-printschematicket+xml": { + source: "iana", + compressible: true + }, + "application/vnd.ms-project": { + source: "iana", + extensions: ["mpp", "mpt"] + }, + "application/vnd.ms-tnef": { + source: "iana" + }, + "application/vnd.ms-visio.viewer": { + extensions: ["vdx"] + }, + "application/vnd.ms-windows.devicepairing": { + source: "iana" + }, + "application/vnd.ms-windows.nwprinting.oob": { + source: "iana" + }, + "application/vnd.ms-windows.printerpairing": { + source: "iana" + }, + "application/vnd.ms-windows.wsd.oob": { + source: "iana" + }, + "application/vnd.ms-wmdrm.lic-chlg-req": { + source: "iana" + }, + "application/vnd.ms-wmdrm.lic-resp": { + source: "iana" + }, + "application/vnd.ms-wmdrm.meter-chlg-req": { + source: "iana" + }, + "application/vnd.ms-wmdrm.meter-resp": { + source: "iana" + }, + "application/vnd.ms-word.document.macroenabled.12": { + source: "iana", + extensions: ["docm"] + }, + "application/vnd.ms-word.template.macroenabled.12": { + source: "iana", + extensions: ["dotm"] + }, + "application/vnd.ms-works": { + source: "iana", + extensions: ["wps", "wks", "wcm", "wdb"] + }, + "application/vnd.ms-wpl": { + source: "iana", + extensions: ["wpl"] + }, + "application/vnd.ms-xpsdocument": { + source: "iana", + compressible: false, + extensions: ["xps"] + }, + "application/vnd.msa-disk-image": { + source: "iana" + }, + "application/vnd.mseq": { + source: "iana", + extensions: ["mseq"] + }, + "application/vnd.msgpack": { + source: "iana" + }, + "application/vnd.msign": { + source: "iana" + }, + "application/vnd.multiad.creator": { + source: "iana" + }, + "application/vnd.multiad.creator.cif": { + source: "iana" + }, + "application/vnd.music-niff": { + source: "iana" + }, + "application/vnd.musician": { + source: "iana", + extensions: ["mus"] + }, + "application/vnd.muvee.style": { + source: "iana", + extensions: ["msty"] + }, + "application/vnd.mynfc": { + source: "iana", + extensions: ["taglet"] + }, + "application/vnd.nacamar.ybrid+json": { + source: "iana", + compressible: true + }, + "application/vnd.nato.bindingdataobject+cbor": { + source: "iana" + }, + "application/vnd.nato.bindingdataobject+json": { + source: "iana", + compressible: true + }, + "application/vnd.nato.bindingdataobject+xml": { + source: "iana", + compressible: true, + extensions: ["bdo"] + }, + "application/vnd.nato.openxmlformats-package.iepd+zip": { + source: "iana", + compressible: false + }, + "application/vnd.ncd.control": { + source: "iana" + }, + "application/vnd.ncd.reference": { + source: "iana" + }, + "application/vnd.nearst.inv+json": { + source: "iana", + compressible: true + }, + "application/vnd.nebumind.line": { + source: "iana" + }, + "application/vnd.nervana": { + source: "iana" + }, + "application/vnd.netfpx": { + source: "iana" + }, + "application/vnd.neurolanguage.nlu": { + source: "iana", + extensions: ["nlu"] + }, + "application/vnd.nimn": { + source: "iana" + }, + "application/vnd.nintendo.nitro.rom": { + source: "iana" + }, + "application/vnd.nintendo.snes.rom": { + source: "iana" + }, + "application/vnd.nitf": { + source: "iana", + extensions: ["ntf", "nitf"] + }, + "application/vnd.noblenet-directory": { + source: "iana", + extensions: ["nnd"] + }, + "application/vnd.noblenet-sealer": { + source: "iana", + extensions: ["nns"] + }, + "application/vnd.noblenet-web": { + source: "iana", + extensions: ["nnw"] + }, + "application/vnd.nokia.catalogs": { + source: "iana" + }, + "application/vnd.nokia.conml+wbxml": { + source: "iana" + }, + "application/vnd.nokia.conml+xml": { + source: "iana", + compressible: true + }, + "application/vnd.nokia.iptv.config+xml": { + source: "iana", + compressible: true + }, + "application/vnd.nokia.isds-radio-presets": { + source: "iana" + }, + "application/vnd.nokia.landmark+wbxml": { + source: "iana" + }, + "application/vnd.nokia.landmark+xml": { + source: "iana", + compressible: true + }, + "application/vnd.nokia.landmarkcollection+xml": { + source: "iana", + compressible: true + }, + "application/vnd.nokia.n-gage.ac+xml": { + source: "iana", + compressible: true, + extensions: ["ac"] + }, + "application/vnd.nokia.n-gage.data": { + source: "iana", + extensions: ["ngdat"] + }, + "application/vnd.nokia.n-gage.symbian.install": { + source: "apache", + extensions: ["n-gage"] + }, + "application/vnd.nokia.ncd": { + source: "iana" + }, + "application/vnd.nokia.pcd+wbxml": { + source: "iana" + }, + "application/vnd.nokia.pcd+xml": { + source: "iana", + compressible: true + }, + "application/vnd.nokia.radio-preset": { + source: "iana", + extensions: ["rpst"] + }, + "application/vnd.nokia.radio-presets": { + source: "iana", + extensions: ["rpss"] + }, + "application/vnd.novadigm.edm": { + source: "iana", + extensions: ["edm"] + }, + "application/vnd.novadigm.edx": { + source: "iana", + extensions: ["edx"] + }, + "application/vnd.novadigm.ext": { + source: "iana", + extensions: ["ext"] + }, + "application/vnd.ntt-local.content-share": { + source: "iana" + }, + "application/vnd.ntt-local.file-transfer": { + source: "iana" + }, + "application/vnd.ntt-local.ogw_remote-access": { + source: "iana" + }, + "application/vnd.ntt-local.sip-ta_remote": { + source: "iana" + }, + "application/vnd.ntt-local.sip-ta_tcp_stream": { + source: "iana" + }, + "application/vnd.oai.workflows": { + source: "iana" + }, + "application/vnd.oai.workflows+json": { + source: "iana", + compressible: true + }, + "application/vnd.oai.workflows+yaml": { + source: "iana" + }, + "application/vnd.oasis.opendocument.base": { + source: "iana" + }, + "application/vnd.oasis.opendocument.chart": { + source: "iana", + extensions: ["odc"] + }, + "application/vnd.oasis.opendocument.chart-template": { + source: "iana", + extensions: ["otc"] + }, + "application/vnd.oasis.opendocument.database": { + source: "apache", + extensions: ["odb"] + }, + "application/vnd.oasis.opendocument.formula": { + source: "iana", + extensions: ["odf"] + }, + "application/vnd.oasis.opendocument.formula-template": { + source: "iana", + extensions: ["odft"] + }, + "application/vnd.oasis.opendocument.graphics": { + source: "iana", + compressible: false, + extensions: ["odg"] + }, + "application/vnd.oasis.opendocument.graphics-template": { + source: "iana", + extensions: ["otg"] + }, + "application/vnd.oasis.opendocument.image": { + source: "iana", + extensions: ["odi"] + }, + "application/vnd.oasis.opendocument.image-template": { + source: "iana", + extensions: ["oti"] + }, + "application/vnd.oasis.opendocument.presentation": { + source: "iana", + compressible: false, + extensions: ["odp"] + }, + "application/vnd.oasis.opendocument.presentation-template": { + source: "iana", + extensions: ["otp"] + }, + "application/vnd.oasis.opendocument.spreadsheet": { + source: "iana", + compressible: false, + extensions: ["ods"] + }, + "application/vnd.oasis.opendocument.spreadsheet-template": { + source: "iana", + extensions: ["ots"] + }, + "application/vnd.oasis.opendocument.text": { + source: "iana", + compressible: false, + extensions: ["odt"] + }, + "application/vnd.oasis.opendocument.text-master": { + source: "iana", + extensions: ["odm"] + }, + "application/vnd.oasis.opendocument.text-master-template": { + source: "iana" + }, + "application/vnd.oasis.opendocument.text-template": { + source: "iana", + extensions: ["ott"] + }, + "application/vnd.oasis.opendocument.text-web": { + source: "iana", + extensions: ["oth"] + }, + "application/vnd.obn": { + source: "iana" + }, + "application/vnd.ocf+cbor": { + source: "iana" + }, + "application/vnd.oci.image.manifest.v1+json": { + source: "iana", + compressible: true + }, + "application/vnd.oftn.l10n+json": { + source: "iana", + compressible: true + }, + "application/vnd.oipf.contentaccessdownload+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oipf.contentaccessstreaming+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oipf.cspg-hexbinary": { + source: "iana" + }, + "application/vnd.oipf.dae.svg+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oipf.dae.xhtml+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oipf.mippvcontrolmessage+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oipf.pae.gem": { + source: "iana" + }, + "application/vnd.oipf.spdiscovery+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oipf.spdlist+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oipf.ueprofile+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oipf.userprofile+xml": { + source: "iana", + compressible: true + }, + "application/vnd.olpc-sugar": { + source: "iana", + extensions: ["xo"] + }, + "application/vnd.oma-scws-config": { + source: "iana" + }, + "application/vnd.oma-scws-http-request": { + source: "iana" + }, + "application/vnd.oma-scws-http-response": { + source: "iana" + }, + "application/vnd.oma.bcast.associated-procedure-parameter+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.bcast.drm-trigger+xml": { + source: "apache", + compressible: true + }, + "application/vnd.oma.bcast.imd+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.bcast.ltkm": { + source: "iana" + }, + "application/vnd.oma.bcast.notification+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.bcast.provisioningtrigger": { + source: "iana" + }, + "application/vnd.oma.bcast.sgboot": { + source: "iana" + }, + "application/vnd.oma.bcast.sgdd+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.bcast.sgdu": { + source: "iana" + }, + "application/vnd.oma.bcast.simple-symbol-container": { + source: "iana" + }, + "application/vnd.oma.bcast.smartcard-trigger+xml": { + source: "apache", + compressible: true + }, + "application/vnd.oma.bcast.sprov+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.bcast.stkm": { + source: "iana" + }, + "application/vnd.oma.cab-address-book+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.cab-feature-handler+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.cab-pcc+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.cab-subs-invite+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.cab-user-prefs+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.dcd": { + source: "iana" + }, + "application/vnd.oma.dcdc": { + source: "iana" + }, + "application/vnd.oma.dd2+xml": { + source: "iana", + compressible: true, + extensions: ["dd2"] + }, + "application/vnd.oma.drm.risd+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.group-usage-list+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.lwm2m+cbor": { + source: "iana" + }, + "application/vnd.oma.lwm2m+json": { + source: "iana", + compressible: true + }, + "application/vnd.oma.lwm2m+tlv": { + source: "iana" + }, + "application/vnd.oma.pal+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.poc.detailed-progress-report+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.poc.final-report+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.poc.groups+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.poc.invocation-descriptor+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.poc.optimized-progress-report+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.push": { + source: "iana" + }, + "application/vnd.oma.scidm.messages+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.xcap-directory+xml": { + source: "iana", + compressible: true + }, + "application/vnd.omads-email+xml": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/vnd.omads-file+xml": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/vnd.omads-folder+xml": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/vnd.omaloc-supl-init": { + source: "iana" + }, + "application/vnd.onepager": { + source: "iana" + }, + "application/vnd.onepagertamp": { + source: "iana" + }, + "application/vnd.onepagertamx": { + source: "iana" + }, + "application/vnd.onepagertat": { + source: "iana" + }, + "application/vnd.onepagertatp": { + source: "iana" + }, + "application/vnd.onepagertatx": { + source: "iana" + }, + "application/vnd.onvif.metadata": { + source: "iana" + }, + "application/vnd.openblox.game+xml": { + source: "iana", + compressible: true, + extensions: ["obgx"] + }, + "application/vnd.openblox.game-binary": { + source: "iana" + }, + "application/vnd.openeye.oeb": { + source: "iana" + }, + "application/vnd.openofficeorg.extension": { + source: "apache", + extensions: ["oxt"] + }, + "application/vnd.openstreetmap.data+xml": { + source: "iana", + compressible: true, + extensions: ["osm"] + }, + "application/vnd.opentimestamps.ots": { + source: "iana" + }, + "application/vnd.openvpi.dspx+json": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.custom-properties+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.customxmlproperties+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.drawing+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.drawingml.chart+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramcolors+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramdata+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramlayout+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramstyle+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.extended-properties+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.presentationml.commentauthors+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.presentationml.comments+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.presentationml.handoutmaster+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.presentationml.notesmaster+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.presentationml.notesslide+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.presentationml.presentation": { + source: "iana", + compressible: false, + extensions: ["pptx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.presentationml.presprops+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slide": { + source: "iana", + extensions: ["sldx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.slide+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slidelayout+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slidemaster+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slideshow": { + source: "iana", + extensions: ["ppsx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slideupdateinfo+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.presentationml.tablestyles+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.presentationml.tags+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.presentationml.template": { + source: "iana", + extensions: ["potx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.template.main+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.presentationml.viewprops+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.calcchain+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.externallink+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcachedefinition+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcacherecords+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivottable+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.querytable+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionheaders+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionlog+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedstrings+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": { + source: "iana", + compressible: false, + extensions: ["xlsx"] + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheetmetadata+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.tablesinglecells+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.template": { + source: "iana", + extensions: ["xltx"] + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.usernames+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.volatiledependencies+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.theme+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.themeoverride+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.vmldrawing": { + source: "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document": { + source: "iana", + compressible: false, + extensions: ["docx"] + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.fonttable+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.template": { + source: "iana", + extensions: ["dotx"] + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.websettings+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-package.core-properties+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-package.relationships+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oracle.resource+json": { + source: "iana", + compressible: true + }, + "application/vnd.orange.indata": { + source: "iana" + }, + "application/vnd.osa.netdeploy": { + source: "iana" + }, + "application/vnd.osgeo.mapguide.package": { + source: "iana", + extensions: ["mgp"] + }, + "application/vnd.osgi.bundle": { + source: "iana" + }, + "application/vnd.osgi.dp": { + source: "iana", + extensions: ["dp"] + }, + "application/vnd.osgi.subsystem": { + source: "iana", + extensions: ["esa"] + }, + "application/vnd.otps.ct-kip+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oxli.countgraph": { + source: "iana" + }, + "application/vnd.pagerduty+json": { + source: "iana", + compressible: true + }, + "application/vnd.palm": { + source: "iana", + extensions: ["pdb", "pqa", "oprc"] + }, + "application/vnd.panoply": { + source: "iana" + }, + "application/vnd.paos.xml": { + source: "iana" + }, + "application/vnd.patentdive": { + source: "iana" + }, + "application/vnd.patientecommsdoc": { + source: "iana" + }, + "application/vnd.pawaafile": { + source: "iana", + extensions: ["paw"] + }, + "application/vnd.pcos": { + source: "iana" + }, + "application/vnd.pg.format": { + source: "iana", + extensions: ["str"] + }, + "application/vnd.pg.osasli": { + source: "iana", + extensions: ["ei6"] + }, + "application/vnd.piaccess.application-licence": { + source: "iana" + }, + "application/vnd.picsel": { + source: "iana", + extensions: ["efif"] + }, + "application/vnd.pmi.widget": { + source: "iana", + extensions: ["wg"] + }, + "application/vnd.poc.group-advertisement+xml": { + source: "iana", + compressible: true + }, + "application/vnd.pocketlearn": { + source: "iana", + extensions: ["plf"] + }, + "application/vnd.powerbuilder6": { + source: "iana", + extensions: ["pbd"] + }, + "application/vnd.powerbuilder6-s": { + source: "iana" + }, + "application/vnd.powerbuilder7": { + source: "iana" + }, + "application/vnd.powerbuilder7-s": { + source: "iana" + }, + "application/vnd.powerbuilder75": { + source: "iana" + }, + "application/vnd.powerbuilder75-s": { + source: "iana" + }, + "application/vnd.preminet": { + source: "iana" + }, + "application/vnd.previewsystems.box": { + source: "iana", + extensions: ["box"] + }, + "application/vnd.procrate.brushset": { + extensions: ["brushset"] + }, + "application/vnd.procreate.brush": { + extensions: ["brush"] + }, + "application/vnd.procreate.dream": { + extensions: ["drm"] + }, + "application/vnd.proteus.magazine": { + source: "iana", + extensions: ["mgz"] + }, + "application/vnd.psfs": { + source: "iana" + }, + "application/vnd.pt.mundusmundi": { + source: "iana" + }, + "application/vnd.publishare-delta-tree": { + source: "iana", + extensions: ["qps"] + }, + "application/vnd.pvi.ptid1": { + source: "iana", + extensions: ["ptid"] + }, + "application/vnd.pwg-multiplexed": { + source: "iana" + }, + "application/vnd.pwg-xhtml-print+xml": { + source: "iana", + compressible: true, + extensions: ["xhtm"] + }, + "application/vnd.qualcomm.brew-app-res": { + source: "iana" + }, + "application/vnd.quarantainenet": { + source: "iana" + }, + "application/vnd.quark.quarkxpress": { + source: "iana", + extensions: ["qxd", "qxt", "qwd", "qwt", "qxl", "qxb"] + }, + "application/vnd.quobject-quoxdocument": { + source: "iana" + }, + "application/vnd.radisys.moml+xml": { + source: "iana", + compressible: true + }, + "application/vnd.radisys.msml+xml": { + source: "iana", + compressible: true + }, + "application/vnd.radisys.msml-audit+xml": { + source: "iana", + compressible: true + }, + "application/vnd.radisys.msml-audit-conf+xml": { + source: "iana", + compressible: true + }, + "application/vnd.radisys.msml-audit-conn+xml": { + source: "iana", + compressible: true + }, + "application/vnd.radisys.msml-audit-dialog+xml": { + source: "iana", + compressible: true + }, + "application/vnd.radisys.msml-audit-stream+xml": { + source: "iana", + compressible: true + }, + "application/vnd.radisys.msml-conf+xml": { + source: "iana", + compressible: true + }, + "application/vnd.radisys.msml-dialog+xml": { + source: "iana", + compressible: true + }, + "application/vnd.radisys.msml-dialog-base+xml": { + source: "iana", + compressible: true + }, + "application/vnd.radisys.msml-dialog-fax-detect+xml": { + source: "iana", + compressible: true + }, + "application/vnd.radisys.msml-dialog-fax-sendrecv+xml": { + source: "iana", + compressible: true + }, + "application/vnd.radisys.msml-dialog-group+xml": { + source: "iana", + compressible: true + }, + "application/vnd.radisys.msml-dialog-speech+xml": { + source: "iana", + compressible: true + }, + "application/vnd.radisys.msml-dialog-transform+xml": { + source: "iana", + compressible: true + }, + "application/vnd.rainstor.data": { + source: "iana" + }, + "application/vnd.rapid": { + source: "iana" + }, + "application/vnd.rar": { + source: "iana", + extensions: ["rar"] + }, + "application/vnd.realvnc.bed": { + source: "iana", + extensions: ["bed"] + }, + "application/vnd.recordare.musicxml": { + source: "iana", + extensions: ["mxl"] + }, + "application/vnd.recordare.musicxml+xml": { + source: "iana", + compressible: true, + extensions: ["musicxml"] + }, + "application/vnd.relpipe": { + source: "iana" + }, + "application/vnd.renlearn.rlprint": { + source: "iana" + }, + "application/vnd.resilient.logic": { + source: "iana" + }, + "application/vnd.restful+json": { + source: "iana", + compressible: true + }, + "application/vnd.rig.cryptonote": { + source: "iana", + extensions: ["cryptonote"] + }, + "application/vnd.rim.cod": { + source: "apache", + extensions: ["cod"] + }, + "application/vnd.rn-realmedia": { + source: "apache", + extensions: ["rm"] + }, + "application/vnd.rn-realmedia-vbr": { + source: "apache", + extensions: ["rmvb"] + }, + "application/vnd.route66.link66+xml": { + source: "iana", + compressible: true, + extensions: ["link66"] + }, + "application/vnd.rs-274x": { + source: "iana" + }, + "application/vnd.ruckus.download": { + source: "iana" + }, + "application/vnd.s3sms": { + source: "iana" + }, + "application/vnd.sailingtracker.track": { + source: "iana", + extensions: ["st"] + }, + "application/vnd.sar": { + source: "iana" + }, + "application/vnd.sbm.cid": { + source: "iana" + }, + "application/vnd.sbm.mid2": { + source: "iana" + }, + "application/vnd.scribus": { + source: "iana" + }, + "application/vnd.sealed.3df": { + source: "iana" + }, + "application/vnd.sealed.csf": { + source: "iana" + }, + "application/vnd.sealed.doc": { + source: "iana" + }, + "application/vnd.sealed.eml": { + source: "iana" + }, + "application/vnd.sealed.mht": { + source: "iana" + }, + "application/vnd.sealed.net": { + source: "iana" + }, + "application/vnd.sealed.ppt": { + source: "iana" + }, + "application/vnd.sealed.tiff": { + source: "iana" + }, + "application/vnd.sealed.xls": { + source: "iana" + }, + "application/vnd.sealedmedia.softseal.html": { + source: "iana" + }, + "application/vnd.sealedmedia.softseal.pdf": { + source: "iana" + }, + "application/vnd.seemail": { + source: "iana", + extensions: ["see"] + }, + "application/vnd.seis+json": { + source: "iana", + compressible: true + }, + "application/vnd.sema": { + source: "iana", + extensions: ["sema"] + }, + "application/vnd.semd": { + source: "iana", + extensions: ["semd"] + }, + "application/vnd.semf": { + source: "iana", + extensions: ["semf"] + }, + "application/vnd.shade-save-file": { + source: "iana" + }, + "application/vnd.shana.informed.formdata": { + source: "iana", + extensions: ["ifm"] + }, + "application/vnd.shana.informed.formtemplate": { + source: "iana", + extensions: ["itp"] + }, + "application/vnd.shana.informed.interchange": { + source: "iana", + extensions: ["iif"] + }, + "application/vnd.shana.informed.package": { + source: "iana", + extensions: ["ipk"] + }, + "application/vnd.shootproof+json": { + source: "iana", + compressible: true + }, + "application/vnd.shopkick+json": { + source: "iana", + compressible: true + }, + "application/vnd.shp": { + source: "iana" + }, + "application/vnd.shx": { + source: "iana" + }, + "application/vnd.sigrok.session": { + source: "iana" + }, + "application/vnd.simtech-mindmapper": { + source: "iana", + extensions: ["twd", "twds"] + }, + "application/vnd.siren+json": { + source: "iana", + compressible: true + }, + "application/vnd.sketchometry": { + source: "iana" + }, + "application/vnd.smaf": { + source: "iana", + extensions: ["mmf"] + }, + "application/vnd.smart.notebook": { + source: "iana" + }, + "application/vnd.smart.teacher": { + source: "iana", + extensions: ["teacher"] + }, + "application/vnd.smintio.portals.archive": { + source: "iana" + }, + "application/vnd.snesdev-page-table": { + source: "iana" + }, + "application/vnd.software602.filler.form+xml": { + source: "iana", + compressible: true, + extensions: ["fo"] + }, + "application/vnd.software602.filler.form-xml-zip": { + source: "iana" + }, + "application/vnd.solent.sdkm+xml": { + source: "iana", + compressible: true, + extensions: ["sdkm", "sdkd"] + }, + "application/vnd.spotfire.dxp": { + source: "iana", + extensions: ["dxp"] + }, + "application/vnd.spotfire.sfs": { + source: "iana", + extensions: ["sfs"] + }, + "application/vnd.sqlite3": { + source: "iana" + }, + "application/vnd.sss-cod": { + source: "iana" + }, + "application/vnd.sss-dtf": { + source: "iana" + }, + "application/vnd.sss-ntf": { + source: "iana" + }, + "application/vnd.stardivision.calc": { + source: "apache", + extensions: ["sdc"] + }, + "application/vnd.stardivision.draw": { + source: "apache", + extensions: ["sda"] + }, + "application/vnd.stardivision.impress": { + source: "apache", + extensions: ["sdd"] + }, + "application/vnd.stardivision.math": { + source: "apache", + extensions: ["smf"] + }, + "application/vnd.stardivision.writer": { + source: "apache", + extensions: ["sdw", "vor"] + }, + "application/vnd.stardivision.writer-global": { + source: "apache", + extensions: ["sgl"] + }, + "application/vnd.stepmania.package": { + source: "iana", + extensions: ["smzip"] + }, + "application/vnd.stepmania.stepchart": { + source: "iana", + extensions: ["sm"] + }, + "application/vnd.street-stream": { + source: "iana" + }, + "application/vnd.sun.wadl+xml": { + source: "iana", + compressible: true, + extensions: ["wadl"] + }, + "application/vnd.sun.xml.calc": { + source: "apache", + extensions: ["sxc"] + }, + "application/vnd.sun.xml.calc.template": { + source: "apache", + extensions: ["stc"] + }, + "application/vnd.sun.xml.draw": { + source: "apache", + extensions: ["sxd"] + }, + "application/vnd.sun.xml.draw.template": { + source: "apache", + extensions: ["std"] + }, + "application/vnd.sun.xml.impress": { + source: "apache", + extensions: ["sxi"] + }, + "application/vnd.sun.xml.impress.template": { + source: "apache", + extensions: ["sti"] + }, + "application/vnd.sun.xml.math": { + source: "apache", + extensions: ["sxm"] + }, + "application/vnd.sun.xml.writer": { + source: "apache", + extensions: ["sxw"] + }, + "application/vnd.sun.xml.writer.global": { + source: "apache", + extensions: ["sxg"] + }, + "application/vnd.sun.xml.writer.template": { + source: "apache", + extensions: ["stw"] + }, + "application/vnd.sus-calendar": { + source: "iana", + extensions: ["sus", "susp"] + }, + "application/vnd.svd": { + source: "iana", + extensions: ["svd"] + }, + "application/vnd.swiftview-ics": { + source: "iana" + }, + "application/vnd.sybyl.mol2": { + source: "iana" + }, + "application/vnd.sycle+xml": { + source: "iana", + compressible: true + }, + "application/vnd.syft+json": { + source: "iana", + compressible: true + }, + "application/vnd.symbian.install": { + source: "apache", + extensions: ["sis", "sisx"] + }, + "application/vnd.syncml+xml": { + source: "iana", + charset: "UTF-8", + compressible: true, + extensions: ["xsm"] + }, + "application/vnd.syncml.dm+wbxml": { + source: "iana", + charset: "UTF-8", + extensions: ["bdm"] + }, + "application/vnd.syncml.dm+xml": { + source: "iana", + charset: "UTF-8", + compressible: true, + extensions: ["xdm"] + }, + "application/vnd.syncml.dm.notification": { + source: "iana" + }, + "application/vnd.syncml.dmddf+wbxml": { + source: "iana" + }, + "application/vnd.syncml.dmddf+xml": { + source: "iana", + charset: "UTF-8", + compressible: true, + extensions: ["ddf"] + }, + "application/vnd.syncml.dmtnds+wbxml": { + source: "iana" + }, + "application/vnd.syncml.dmtnds+xml": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/vnd.syncml.ds.notification": { + source: "iana" + }, + "application/vnd.tableschema+json": { + source: "iana", + compressible: true + }, + "application/vnd.tao.intent-module-archive": { + source: "iana", + extensions: ["tao"] + }, + "application/vnd.tcpdump.pcap": { + source: "iana", + extensions: ["pcap", "cap", "dmp"] + }, + "application/vnd.think-cell.ppttc+json": { + source: "iana", + compressible: true + }, + "application/vnd.tmd.mediaflex.api+xml": { + source: "iana", + compressible: true + }, + "application/vnd.tml": { + source: "iana" + }, + "application/vnd.tmobile-livetv": { + source: "iana", + extensions: ["tmo"] + }, + "application/vnd.tri.onesource": { + source: "iana" + }, + "application/vnd.trid.tpt": { + source: "iana", + extensions: ["tpt"] + }, + "application/vnd.triscape.mxs": { + source: "iana", + extensions: ["mxs"] + }, + "application/vnd.trueapp": { + source: "iana", + extensions: ["tra"] + }, + "application/vnd.truedoc": { + source: "iana" + }, + "application/vnd.ubisoft.webplayer": { + source: "iana" + }, + "application/vnd.ufdl": { + source: "iana", + extensions: ["ufd", "ufdl"] + }, + "application/vnd.uic.osdm+json": { + source: "iana", + compressible: true + }, + "application/vnd.uiq.theme": { + source: "iana", + extensions: ["utz"] + }, + "application/vnd.umajin": { + source: "iana", + extensions: ["umj"] + }, + "application/vnd.unity": { + source: "iana", + extensions: ["unityweb"] + }, + "application/vnd.uoml+xml": { + source: "iana", + compressible: true, + extensions: ["uoml", "uo"] + }, + "application/vnd.uplanet.alert": { + source: "iana" + }, + "application/vnd.uplanet.alert-wbxml": { + source: "iana" + }, + "application/vnd.uplanet.bearer-choice": { + source: "iana" + }, + "application/vnd.uplanet.bearer-choice-wbxml": { + source: "iana" + }, + "application/vnd.uplanet.cacheop": { + source: "iana" + }, + "application/vnd.uplanet.cacheop-wbxml": { + source: "iana" + }, + "application/vnd.uplanet.channel": { + source: "iana" + }, + "application/vnd.uplanet.channel-wbxml": { + source: "iana" + }, + "application/vnd.uplanet.list": { + source: "iana" + }, + "application/vnd.uplanet.list-wbxml": { + source: "iana" + }, + "application/vnd.uplanet.listcmd": { + source: "iana" + }, + "application/vnd.uplanet.listcmd-wbxml": { + source: "iana" + }, + "application/vnd.uplanet.signal": { + source: "iana" + }, + "application/vnd.uri-map": { + source: "iana" + }, + "application/vnd.valve.source.material": { + source: "iana" + }, + "application/vnd.vcx": { + source: "iana", + extensions: ["vcx"] + }, + "application/vnd.vd-study": { + source: "iana" + }, + "application/vnd.vectorworks": { + source: "iana" + }, + "application/vnd.vel+json": { + source: "iana", + compressible: true + }, + "application/vnd.veraison.tsm-report+cbor": { + source: "iana" + }, + "application/vnd.veraison.tsm-report+json": { + source: "iana", + compressible: true + }, + "application/vnd.verimatrix.vcas": { + source: "iana" + }, + "application/vnd.veritone.aion+json": { + source: "iana", + compressible: true + }, + "application/vnd.veryant.thin": { + source: "iana" + }, + "application/vnd.ves.encrypted": { + source: "iana" + }, + "application/vnd.vidsoft.vidconference": { + source: "iana" + }, + "application/vnd.visio": { + source: "iana", + extensions: ["vsd", "vst", "vss", "vsw", "vsdx", "vtx"] + }, + "application/vnd.visionary": { + source: "iana", + extensions: ["vis"] + }, + "application/vnd.vividence.scriptfile": { + source: "iana" + }, + "application/vnd.vocalshaper.vsp4": { + source: "iana" + }, + "application/vnd.vsf": { + source: "iana", + extensions: ["vsf"] + }, + "application/vnd.wap.sic": { + source: "iana" + }, + "application/vnd.wap.slc": { + source: "iana" + }, + "application/vnd.wap.wbxml": { + source: "iana", + charset: "UTF-8", + extensions: ["wbxml"] + }, + "application/vnd.wap.wmlc": { + source: "iana", + extensions: ["wmlc"] + }, + "application/vnd.wap.wmlscriptc": { + source: "iana", + extensions: ["wmlsc"] + }, + "application/vnd.wasmflow.wafl": { + source: "iana" + }, + "application/vnd.webturbo": { + source: "iana", + extensions: ["wtb"] + }, + "application/vnd.wfa.dpp": { + source: "iana" + }, + "application/vnd.wfa.p2p": { + source: "iana" + }, + "application/vnd.wfa.wsc": { + source: "iana" + }, + "application/vnd.windows.devicepairing": { + source: "iana" + }, + "application/vnd.wmc": { + source: "iana" + }, + "application/vnd.wmf.bootstrap": { + source: "iana" + }, + "application/vnd.wolfram.mathematica": { + source: "iana" + }, + "application/vnd.wolfram.mathematica.package": { + source: "iana" + }, + "application/vnd.wolfram.player": { + source: "iana", + extensions: ["nbp"] + }, + "application/vnd.wordlift": { + source: "iana" + }, + "application/vnd.wordperfect": { + source: "iana", + extensions: ["wpd"] + }, + "application/vnd.wqd": { + source: "iana", + extensions: ["wqd"] + }, + "application/vnd.wrq-hp3000-labelled": { + source: "iana" + }, + "application/vnd.wt.stf": { + source: "iana", + extensions: ["stf"] + }, + "application/vnd.wv.csp+wbxml": { + source: "iana" + }, + "application/vnd.wv.csp+xml": { + source: "iana", + compressible: true + }, + "application/vnd.wv.ssp+xml": { + source: "iana", + compressible: true + }, + "application/vnd.xacml+json": { + source: "iana", + compressible: true + }, + "application/vnd.xara": { + source: "iana", + extensions: ["xar"] + }, + "application/vnd.xarin.cpj": { + source: "iana" + }, + "application/vnd.xecrets-encrypted": { + source: "iana" + }, + "application/vnd.xfdl": { + source: "iana", + extensions: ["xfdl"] + }, + "application/vnd.xfdl.webform": { + source: "iana" + }, + "application/vnd.xmi+xml": { + source: "iana", + compressible: true + }, + "application/vnd.xmpie.cpkg": { + source: "iana" + }, + "application/vnd.xmpie.dpkg": { + source: "iana" + }, + "application/vnd.xmpie.plan": { + source: "iana" + }, + "application/vnd.xmpie.ppkg": { + source: "iana" + }, + "application/vnd.xmpie.xlim": { + source: "iana" + }, + "application/vnd.yamaha.hv-dic": { + source: "iana", + extensions: ["hvd"] + }, + "application/vnd.yamaha.hv-script": { + source: "iana", + extensions: ["hvs"] + }, + "application/vnd.yamaha.hv-voice": { + source: "iana", + extensions: ["hvp"] + }, + "application/vnd.yamaha.openscoreformat": { + source: "iana", + extensions: ["osf"] + }, + "application/vnd.yamaha.openscoreformat.osfpvg+xml": { + source: "iana", + compressible: true, + extensions: ["osfpvg"] + }, + "application/vnd.yamaha.remote-setup": { + source: "iana" + }, + "application/vnd.yamaha.smaf-audio": { + source: "iana", + extensions: ["saf"] + }, + "application/vnd.yamaha.smaf-phrase": { + source: "iana", + extensions: ["spf"] + }, + "application/vnd.yamaha.through-ngn": { + source: "iana" + }, + "application/vnd.yamaha.tunnel-udpencap": { + source: "iana" + }, + "application/vnd.yaoweme": { + source: "iana" + }, + "application/vnd.yellowriver-custom-menu": { + source: "iana", + extensions: ["cmp"] + }, + "application/vnd.zul": { + source: "iana", + extensions: ["zir", "zirz"] + }, + "application/vnd.zzazz.deck+xml": { + source: "iana", + compressible: true, + extensions: ["zaz"] + }, + "application/voicexml+xml": { + source: "iana", + compressible: true, + extensions: ["vxml"] + }, + "application/voucher-cms+json": { + source: "iana", + compressible: true + }, + "application/voucher-jws+json": { + source: "iana", + compressible: true + }, + "application/vp": { + source: "iana" + }, + "application/vp+cose": { + source: "iana" + }, + "application/vp+jwt": { + source: "iana" + }, + "application/vq-rtcpxr": { + source: "iana" + }, + "application/wasm": { + source: "iana", + compressible: true, + extensions: ["wasm"] + }, + "application/watcherinfo+xml": { + source: "iana", + compressible: true, + extensions: ["wif"] + }, + "application/webpush-options+json": { + source: "iana", + compressible: true + }, + "application/whoispp-query": { + source: "iana" + }, + "application/whoispp-response": { + source: "iana" + }, + "application/widget": { + source: "iana", + extensions: ["wgt"] + }, + "application/winhlp": { + source: "apache", + extensions: ["hlp"] + }, + "application/wita": { + source: "iana" + }, + "application/wordperfect5.1": { + source: "iana" + }, + "application/wsdl+xml": { + source: "iana", + compressible: true, + extensions: ["wsdl"] + }, + "application/wspolicy+xml": { + source: "iana", + compressible: true, + extensions: ["wspolicy"] + }, + "application/x-7z-compressed": { + source: "apache", + compressible: false, + extensions: ["7z"] + }, + "application/x-abiword": { + source: "apache", + extensions: ["abw"] + }, + "application/x-ace-compressed": { + source: "apache", + extensions: ["ace"] + }, + "application/x-amf": { + source: "apache" + }, + "application/x-apple-diskimage": { + source: "apache", + extensions: ["dmg"] + }, + "application/x-arj": { + compressible: false, + extensions: ["arj"] + }, + "application/x-authorware-bin": { + source: "apache", + extensions: ["aab", "x32", "u32", "vox"] + }, + "application/x-authorware-map": { + source: "apache", + extensions: ["aam"] + }, + "application/x-authorware-seg": { + source: "apache", + extensions: ["aas"] + }, + "application/x-bcpio": { + source: "apache", + extensions: ["bcpio"] + }, + "application/x-bdoc": { + compressible: false, + extensions: ["bdoc"] + }, + "application/x-bittorrent": { + source: "apache", + extensions: ["torrent"] + }, + "application/x-blender": { + extensions: ["blend"] + }, + "application/x-blorb": { + source: "apache", + extensions: ["blb", "blorb"] + }, + "application/x-bzip": { + source: "apache", + compressible: false, + extensions: ["bz"] + }, + "application/x-bzip2": { + source: "apache", + compressible: false, + extensions: ["bz2", "boz"] + }, + "application/x-cbr": { + source: "apache", + extensions: ["cbr", "cba", "cbt", "cbz", "cb7"] + }, + "application/x-cdlink": { + source: "apache", + extensions: ["vcd"] + }, + "application/x-cfs-compressed": { + source: "apache", + extensions: ["cfs"] + }, + "application/x-chat": { + source: "apache", + extensions: ["chat"] + }, + "application/x-chess-pgn": { + source: "apache", + extensions: ["pgn"] + }, + "application/x-chrome-extension": { + extensions: ["crx"] + }, + "application/x-cocoa": { + source: "nginx", + extensions: ["cco"] + }, + "application/x-compress": { + source: "apache" + }, + "application/x-compressed": { + extensions: ["rar"] + }, + "application/x-conference": { + source: "apache", + extensions: ["nsc"] + }, + "application/x-cpio": { + source: "apache", + extensions: ["cpio"] + }, + "application/x-csh": { + source: "apache", + extensions: ["csh"] + }, + "application/x-deb": { + compressible: false + }, + "application/x-debian-package": { + source: "apache", + extensions: ["deb", "udeb"] + }, + "application/x-dgc-compressed": { + source: "apache", + extensions: ["dgc"] + }, + "application/x-director": { + source: "apache", + extensions: ["dir", "dcr", "dxr", "cst", "cct", "cxt", "w3d", "fgd", "swa"] + }, + "application/x-doom": { + source: "apache", + extensions: ["wad"] + }, + "application/x-dtbncx+xml": { + source: "apache", + compressible: true, + extensions: ["ncx"] + }, + "application/x-dtbook+xml": { + source: "apache", + compressible: true, + extensions: ["dtb"] + }, + "application/x-dtbresource+xml": { + source: "apache", + compressible: true, + extensions: ["res"] + }, + "application/x-dvi": { + source: "apache", + compressible: false, + extensions: ["dvi"] + }, + "application/x-envoy": { + source: "apache", + extensions: ["evy"] + }, + "application/x-eva": { + source: "apache", + extensions: ["eva"] + }, + "application/x-font-bdf": { + source: "apache", + extensions: ["bdf"] + }, + "application/x-font-dos": { + source: "apache" + }, + "application/x-font-framemaker": { + source: "apache" + }, + "application/x-font-ghostscript": { + source: "apache", + extensions: ["gsf"] + }, + "application/x-font-libgrx": { + source: "apache" + }, + "application/x-font-linux-psf": { + source: "apache", + extensions: ["psf"] + }, + "application/x-font-pcf": { + source: "apache", + extensions: ["pcf"] + }, + "application/x-font-snf": { + source: "apache", + extensions: ["snf"] + }, + "application/x-font-speedo": { + source: "apache" + }, + "application/x-font-sunos-news": { + source: "apache" + }, + "application/x-font-type1": { + source: "apache", + extensions: ["pfa", "pfb", "pfm", "afm"] + }, + "application/x-font-vfont": { + source: "apache" + }, + "application/x-freearc": { + source: "apache", + extensions: ["arc"] + }, + "application/x-futuresplash": { + source: "apache", + extensions: ["spl"] + }, + "application/x-gca-compressed": { + source: "apache", + extensions: ["gca"] + }, + "application/x-glulx": { + source: "apache", + extensions: ["ulx"] + }, + "application/x-gnumeric": { + source: "apache", + extensions: ["gnumeric"] + }, + "application/x-gramps-xml": { + source: "apache", + extensions: ["gramps"] + }, + "application/x-gtar": { + source: "apache", + extensions: ["gtar"] + }, + "application/x-gzip": { + source: "apache" + }, + "application/x-hdf": { + source: "apache", + extensions: ["hdf"] + }, + "application/x-httpd-php": { + compressible: true, + extensions: ["php"] + }, + "application/x-install-instructions": { + source: "apache", + extensions: ["install"] + }, + "application/x-ipynb+json": { + compressible: true, + extensions: ["ipynb"] + }, + "application/x-iso9660-image": { + source: "apache", + extensions: ["iso"] + }, + "application/x-iwork-keynote-sffkey": { + extensions: ["key"] + }, + "application/x-iwork-numbers-sffnumbers": { + extensions: ["numbers"] + }, + "application/x-iwork-pages-sffpages": { + extensions: ["pages"] + }, + "application/x-java-archive-diff": { + source: "nginx", + extensions: ["jardiff"] + }, + "application/x-java-jnlp-file": { + source: "apache", + compressible: false, + extensions: ["jnlp"] + }, + "application/x-javascript": { + compressible: true + }, + "application/x-keepass2": { + extensions: ["kdbx"] + }, + "application/x-latex": { + source: "apache", + compressible: false, + extensions: ["latex"] + }, + "application/x-lua-bytecode": { + extensions: ["luac"] + }, + "application/x-lzh-compressed": { + source: "apache", + extensions: ["lzh", "lha"] + }, + "application/x-makeself": { + source: "nginx", + extensions: ["run"] + }, + "application/x-mie": { + source: "apache", + extensions: ["mie"] + }, + "application/x-mobipocket-ebook": { + source: "apache", + extensions: ["prc", "mobi"] + }, + "application/x-mpegurl": { + compressible: false + }, + "application/x-ms-application": { + source: "apache", + extensions: ["application"] + }, + "application/x-ms-shortcut": { + source: "apache", + extensions: ["lnk"] + }, + "application/x-ms-wmd": { + source: "apache", + extensions: ["wmd"] + }, + "application/x-ms-wmz": { + source: "apache", + extensions: ["wmz"] + }, + "application/x-ms-xbap": { + source: "apache", + extensions: ["xbap"] + }, + "application/x-msaccess": { + source: "apache", + extensions: ["mdb"] + }, + "application/x-msbinder": { + source: "apache", + extensions: ["obd"] + }, + "application/x-mscardfile": { + source: "apache", + extensions: ["crd"] + }, + "application/x-msclip": { + source: "apache", + extensions: ["clp"] + }, + "application/x-msdos-program": { + extensions: ["exe"] + }, + "application/x-msdownload": { + source: "apache", + extensions: ["exe", "dll", "com", "bat", "msi"] + }, + "application/x-msmediaview": { + source: "apache", + extensions: ["mvb", "m13", "m14"] + }, + "application/x-msmetafile": { + source: "apache", + extensions: ["wmf", "wmz", "emf", "emz"] + }, + "application/x-msmoney": { + source: "apache", + extensions: ["mny"] + }, + "application/x-mspublisher": { + source: "apache", + extensions: ["pub"] + }, + "application/x-msschedule": { + source: "apache", + extensions: ["scd"] + }, + "application/x-msterminal": { + source: "apache", + extensions: ["trm"] + }, + "application/x-mswrite": { + source: "apache", + extensions: ["wri"] + }, + "application/x-netcdf": { + source: "apache", + extensions: ["nc", "cdf"] + }, + "application/x-ns-proxy-autoconfig": { + compressible: true, + extensions: ["pac"] + }, + "application/x-nzb": { + source: "apache", + extensions: ["nzb"] + }, + "application/x-perl": { + source: "nginx", + extensions: ["pl", "pm"] + }, + "application/x-pilot": { + source: "nginx", + extensions: ["prc", "pdb"] + }, + "application/x-pkcs12": { + source: "apache", + compressible: false, + extensions: ["p12", "pfx"] + }, + "application/x-pkcs7-certificates": { + source: "apache", + extensions: ["p7b", "spc"] + }, + "application/x-pkcs7-certreqresp": { + source: "apache", + extensions: ["p7r"] + }, + "application/x-pki-message": { + source: "iana" + }, + "application/x-rar-compressed": { + source: "apache", + compressible: false, + extensions: ["rar"] + }, + "application/x-redhat-package-manager": { + source: "nginx", + extensions: ["rpm"] + }, + "application/x-research-info-systems": { + source: "apache", + extensions: ["ris"] + }, + "application/x-sea": { + source: "nginx", + extensions: ["sea"] + }, + "application/x-sh": { + source: "apache", + compressible: true, + extensions: ["sh"] + }, + "application/x-shar": { + source: "apache", + extensions: ["shar"] + }, + "application/x-shockwave-flash": { + source: "apache", + compressible: false, + extensions: ["swf"] + }, + "application/x-silverlight-app": { + source: "apache", + extensions: ["xap"] + }, + "application/x-sql": { + source: "apache", + extensions: ["sql"] + }, + "application/x-stuffit": { + source: "apache", + compressible: false, + extensions: ["sit"] + }, + "application/x-stuffitx": { + source: "apache", + extensions: ["sitx"] + }, + "application/x-subrip": { + source: "apache", + extensions: ["srt"] + }, + "application/x-sv4cpio": { + source: "apache", + extensions: ["sv4cpio"] + }, + "application/x-sv4crc": { + source: "apache", + extensions: ["sv4crc"] + }, + "application/x-t3vm-image": { + source: "apache", + extensions: ["t3"] + }, + "application/x-tads": { + source: "apache", + extensions: ["gam"] + }, + "application/x-tar": { + source: "apache", + compressible: true, + extensions: ["tar"] + }, + "application/x-tcl": { + source: "apache", + extensions: ["tcl", "tk"] + }, + "application/x-tex": { + source: "apache", + extensions: ["tex"] + }, + "application/x-tex-tfm": { + source: "apache", + extensions: ["tfm"] + }, + "application/x-texinfo": { + source: "apache", + extensions: ["texinfo", "texi"] + }, + "application/x-tgif": { + source: "apache", + extensions: ["obj"] + }, + "application/x-ustar": { + source: "apache", + extensions: ["ustar"] + }, + "application/x-virtualbox-hdd": { + compressible: true, + extensions: ["hdd"] + }, + "application/x-virtualbox-ova": { + compressible: true, + extensions: ["ova"] + }, + "application/x-virtualbox-ovf": { + compressible: true, + extensions: ["ovf"] + }, + "application/x-virtualbox-vbox": { + compressible: true, + extensions: ["vbox"] + }, + "application/x-virtualbox-vbox-extpack": { + compressible: false, + extensions: ["vbox-extpack"] + }, + "application/x-virtualbox-vdi": { + compressible: true, + extensions: ["vdi"] + }, + "application/x-virtualbox-vhd": { + compressible: true, + extensions: ["vhd"] + }, + "application/x-virtualbox-vmdk": { + compressible: true, + extensions: ["vmdk"] + }, + "application/x-wais-source": { + source: "apache", + extensions: ["src"] + }, + "application/x-web-app-manifest+json": { + compressible: true, + extensions: ["webapp"] + }, + "application/x-www-form-urlencoded": { + source: "iana", + compressible: true + }, + "application/x-x509-ca-cert": { + source: "iana", + extensions: ["der", "crt", "pem"] + }, + "application/x-x509-ca-ra-cert": { + source: "iana" + }, + "application/x-x509-next-ca-cert": { + source: "iana" + }, + "application/x-xfig": { + source: "apache", + extensions: ["fig"] + }, + "application/x-xliff+xml": { + source: "apache", + compressible: true, + extensions: ["xlf"] + }, + "application/x-xpinstall": { + source: "apache", + compressible: false, + extensions: ["xpi"] + }, + "application/x-xz": { + source: "apache", + extensions: ["xz"] + }, + "application/x-zip-compressed": { + extensions: ["zip"] + }, + "application/x-zmachine": { + source: "apache", + extensions: ["z1", "z2", "z3", "z4", "z5", "z6", "z7", "z8"] + }, + "application/x400-bp": { + source: "iana" + }, + "application/xacml+xml": { + source: "iana", + compressible: true + }, + "application/xaml+xml": { + source: "apache", + compressible: true, + extensions: ["xaml"] + }, + "application/xcap-att+xml": { + source: "iana", + compressible: true, + extensions: ["xav"] + }, + "application/xcap-caps+xml": { + source: "iana", + compressible: true, + extensions: ["xca"] + }, + "application/xcap-diff+xml": { + source: "iana", + compressible: true, + extensions: ["xdf"] + }, + "application/xcap-el+xml": { + source: "iana", + compressible: true, + extensions: ["xel"] + }, + "application/xcap-error+xml": { + source: "iana", + compressible: true + }, + "application/xcap-ns+xml": { + source: "iana", + compressible: true, + extensions: ["xns"] + }, + "application/xcon-conference-info+xml": { + source: "iana", + compressible: true + }, + "application/xcon-conference-info-diff+xml": { + source: "iana", + compressible: true + }, + "application/xenc+xml": { + source: "iana", + compressible: true, + extensions: ["xenc"] + }, + "application/xfdf": { + source: "iana", + extensions: ["xfdf"] + }, + "application/xhtml+xml": { + source: "iana", + compressible: true, + extensions: ["xhtml", "xht"] + }, + "application/xhtml-voice+xml": { + source: "apache", + compressible: true + }, + "application/xliff+xml": { + source: "iana", + compressible: true, + extensions: ["xlf"] + }, + "application/xml": { + source: "iana", + compressible: true, + extensions: ["xml", "xsl", "xsd", "rng"] + }, + "application/xml-dtd": { + source: "iana", + compressible: true, + extensions: ["dtd"] + }, + "application/xml-external-parsed-entity": { + source: "iana" + }, + "application/xml-patch+xml": { + source: "iana", + compressible: true + }, + "application/xmpp+xml": { + source: "iana", + compressible: true + }, + "application/xop+xml": { + source: "iana", + compressible: true, + extensions: ["xop"] + }, + "application/xproc+xml": { + source: "apache", + compressible: true, + extensions: ["xpl"] + }, + "application/xslt+xml": { + source: "iana", + compressible: true, + extensions: ["xsl", "xslt"] + }, + "application/xspf+xml": { + source: "apache", + compressible: true, + extensions: ["xspf"] + }, + "application/xv+xml": { + source: "iana", + compressible: true, + extensions: ["mxml", "xhvml", "xvml", "xvm"] + }, + "application/yaml": { + source: "iana" + }, + "application/yang": { + source: "iana", + extensions: ["yang"] + }, + "application/yang-data+cbor": { + source: "iana" + }, + "application/yang-data+json": { + source: "iana", + compressible: true + }, + "application/yang-data+xml": { + source: "iana", + compressible: true + }, + "application/yang-patch+json": { + source: "iana", + compressible: true + }, + "application/yang-patch+xml": { + source: "iana", + compressible: true + }, + "application/yang-sid+json": { + source: "iana", + compressible: true + }, + "application/yin+xml": { + source: "iana", + compressible: true, + extensions: ["yin"] + }, + "application/zip": { + source: "iana", + compressible: false, + extensions: ["zip"] + }, + "application/zip+dotlottie": { + extensions: ["lottie"] + }, + "application/zlib": { + source: "iana" + }, + "application/zstd": { + source: "iana" + }, + "audio/1d-interleaved-parityfec": { + source: "iana" + }, + "audio/32kadpcm": { + source: "iana" + }, + "audio/3gpp": { + source: "iana", + compressible: false, + extensions: ["3gpp"] + }, + "audio/3gpp2": { + source: "iana" + }, + "audio/aac": { + source: "iana", + extensions: ["adts", "aac"] + }, + "audio/ac3": { + source: "iana" + }, + "audio/adpcm": { + source: "apache", + extensions: ["adp"] + }, + "audio/amr": { + source: "iana", + extensions: ["amr"] + }, + "audio/amr-wb": { + source: "iana" + }, + "audio/amr-wb+": { + source: "iana" + }, + "audio/aptx": { + source: "iana" + }, + "audio/asc": { + source: "iana" + }, + "audio/atrac-advanced-lossless": { + source: "iana" + }, + "audio/atrac-x": { + source: "iana" + }, + "audio/atrac3": { + source: "iana" + }, + "audio/basic": { + source: "iana", + compressible: false, + extensions: ["au", "snd"] + }, + "audio/bv16": { + source: "iana" + }, + "audio/bv32": { + source: "iana" + }, + "audio/clearmode": { + source: "iana" + }, + "audio/cn": { + source: "iana" + }, + "audio/dat12": { + source: "iana" + }, + "audio/dls": { + source: "iana" + }, + "audio/dsr-es201108": { + source: "iana" + }, + "audio/dsr-es202050": { + source: "iana" + }, + "audio/dsr-es202211": { + source: "iana" + }, + "audio/dsr-es202212": { + source: "iana" + }, + "audio/dv": { + source: "iana" + }, + "audio/dvi4": { + source: "iana" + }, + "audio/eac3": { + source: "iana" + }, + "audio/encaprtp": { + source: "iana" + }, + "audio/evrc": { + source: "iana" + }, + "audio/evrc-qcp": { + source: "iana" + }, + "audio/evrc0": { + source: "iana" + }, + "audio/evrc1": { + source: "iana" + }, + "audio/evrcb": { + source: "iana" + }, + "audio/evrcb0": { + source: "iana" + }, + "audio/evrcb1": { + source: "iana" + }, + "audio/evrcnw": { + source: "iana" + }, + "audio/evrcnw0": { + source: "iana" + }, + "audio/evrcnw1": { + source: "iana" + }, + "audio/evrcwb": { + source: "iana" + }, + "audio/evrcwb0": { + source: "iana" + }, + "audio/evrcwb1": { + source: "iana" + }, + "audio/evs": { + source: "iana" + }, + "audio/flac": { + source: "iana" + }, + "audio/flexfec": { + source: "iana" + }, + "audio/fwdred": { + source: "iana" + }, + "audio/g711-0": { + source: "iana" + }, + "audio/g719": { + source: "iana" + }, + "audio/g722": { + source: "iana" + }, + "audio/g7221": { + source: "iana" + }, + "audio/g723": { + source: "iana" + }, + "audio/g726-16": { + source: "iana" + }, + "audio/g726-24": { + source: "iana" + }, + "audio/g726-32": { + source: "iana" + }, + "audio/g726-40": { + source: "iana" + }, + "audio/g728": { + source: "iana" + }, + "audio/g729": { + source: "iana" + }, + "audio/g7291": { + source: "iana" + }, + "audio/g729d": { + source: "iana" + }, + "audio/g729e": { + source: "iana" + }, + "audio/gsm": { + source: "iana" + }, + "audio/gsm-efr": { + source: "iana" + }, + "audio/gsm-hr-08": { + source: "iana" + }, + "audio/ilbc": { + source: "iana" + }, + "audio/ip-mr_v2.5": { + source: "iana" + }, + "audio/isac": { + source: "apache" + }, + "audio/l16": { + source: "iana" + }, + "audio/l20": { + source: "iana" + }, + "audio/l24": { + source: "iana", + compressible: false + }, + "audio/l8": { + source: "iana" + }, + "audio/lpc": { + source: "iana" + }, + "audio/matroska": { + source: "iana" + }, + "audio/melp": { + source: "iana" + }, + "audio/melp1200": { + source: "iana" + }, + "audio/melp2400": { + source: "iana" + }, + "audio/melp600": { + source: "iana" + }, + "audio/mhas": { + source: "iana" + }, + "audio/midi": { + source: "apache", + extensions: ["mid", "midi", "kar", "rmi"] + }, + "audio/midi-clip": { + source: "iana" + }, + "audio/mobile-xmf": { + source: "iana", + extensions: ["mxmf"] + }, + "audio/mp3": { + compressible: false, + extensions: ["mp3"] + }, + "audio/mp4": { + source: "iana", + compressible: false, + extensions: ["m4a", "mp4a", "m4b"] + }, + "audio/mp4a-latm": { + source: "iana" + }, + "audio/mpa": { + source: "iana" + }, + "audio/mpa-robust": { + source: "iana" + }, + "audio/mpeg": { + source: "iana", + compressible: false, + extensions: ["mpga", "mp2", "mp2a", "mp3", "m2a", "m3a"] + }, + "audio/mpeg4-generic": { + source: "iana" + }, + "audio/musepack": { + source: "apache" + }, + "audio/ogg": { + source: "iana", + compressible: false, + extensions: ["oga", "ogg", "spx", "opus"] + }, + "audio/opus": { + source: "iana" + }, + "audio/parityfec": { + source: "iana" + }, + "audio/pcma": { + source: "iana" + }, + "audio/pcma-wb": { + source: "iana" + }, + "audio/pcmu": { + source: "iana" + }, + "audio/pcmu-wb": { + source: "iana" + }, + "audio/prs.sid": { + source: "iana" + }, + "audio/qcelp": { + source: "iana" + }, + "audio/raptorfec": { + source: "iana" + }, + "audio/red": { + source: "iana" + }, + "audio/rtp-enc-aescm128": { + source: "iana" + }, + "audio/rtp-midi": { + source: "iana" + }, + "audio/rtploopback": { + source: "iana" + }, + "audio/rtx": { + source: "iana" + }, + "audio/s3m": { + source: "apache", + extensions: ["s3m"] + }, + "audio/scip": { + source: "iana" + }, + "audio/silk": { + source: "apache", + extensions: ["sil"] + }, + "audio/smv": { + source: "iana" + }, + "audio/smv-qcp": { + source: "iana" + }, + "audio/smv0": { + source: "iana" + }, + "audio/sofa": { + source: "iana" + }, + "audio/sp-midi": { + source: "iana" + }, + "audio/speex": { + source: "iana" + }, + "audio/t140c": { + source: "iana" + }, + "audio/t38": { + source: "iana" + }, + "audio/telephone-event": { + source: "iana" + }, + "audio/tetra_acelp": { + source: "iana" + }, + "audio/tetra_acelp_bb": { + source: "iana" + }, + "audio/tone": { + source: "iana" + }, + "audio/tsvcis": { + source: "iana" + }, + "audio/uemclip": { + source: "iana" + }, + "audio/ulpfec": { + source: "iana" + }, + "audio/usac": { + source: "iana" + }, + "audio/vdvi": { + source: "iana" + }, + "audio/vmr-wb": { + source: "iana" + }, + "audio/vnd.3gpp.iufp": { + source: "iana" + }, + "audio/vnd.4sb": { + source: "iana" + }, + "audio/vnd.audiokoz": { + source: "iana" + }, + "audio/vnd.celp": { + source: "iana" + }, + "audio/vnd.cisco.nse": { + source: "iana" + }, + "audio/vnd.cmles.radio-events": { + source: "iana" + }, + "audio/vnd.cns.anp1": { + source: "iana" + }, + "audio/vnd.cns.inf1": { + source: "iana" + }, + "audio/vnd.dece.audio": { + source: "iana", + extensions: ["uva", "uvva"] + }, + "audio/vnd.digital-winds": { + source: "iana", + extensions: ["eol"] + }, + "audio/vnd.dlna.adts": { + source: "iana" + }, + "audio/vnd.dolby.heaac.1": { + source: "iana" + }, + "audio/vnd.dolby.heaac.2": { + source: "iana" + }, + "audio/vnd.dolby.mlp": { + source: "iana" + }, + "audio/vnd.dolby.mps": { + source: "iana" + }, + "audio/vnd.dolby.pl2": { + source: "iana" + }, + "audio/vnd.dolby.pl2x": { + source: "iana" + }, + "audio/vnd.dolby.pl2z": { + source: "iana" + }, + "audio/vnd.dolby.pulse.1": { + source: "iana" + }, + "audio/vnd.dra": { + source: "iana", + extensions: ["dra"] + }, + "audio/vnd.dts": { + source: "iana", + extensions: ["dts"] + }, + "audio/vnd.dts.hd": { + source: "iana", + extensions: ["dtshd"] + }, + "audio/vnd.dts.uhd": { + source: "iana" + }, + "audio/vnd.dvb.file": { + source: "iana" + }, + "audio/vnd.everad.plj": { + source: "iana" + }, + "audio/vnd.hns.audio": { + source: "iana" + }, + "audio/vnd.lucent.voice": { + source: "iana", + extensions: ["lvp"] + }, + "audio/vnd.ms-playready.media.pya": { + source: "iana", + extensions: ["pya"] + }, + "audio/vnd.nokia.mobile-xmf": { + source: "iana" + }, + "audio/vnd.nortel.vbk": { + source: "iana" + }, + "audio/vnd.nuera.ecelp4800": { + source: "iana", + extensions: ["ecelp4800"] + }, + "audio/vnd.nuera.ecelp7470": { + source: "iana", + extensions: ["ecelp7470"] + }, + "audio/vnd.nuera.ecelp9600": { + source: "iana", + extensions: ["ecelp9600"] + }, + "audio/vnd.octel.sbc": { + source: "iana" + }, + "audio/vnd.presonus.multitrack": { + source: "iana" + }, + "audio/vnd.qcelp": { + source: "apache" + }, + "audio/vnd.rhetorex.32kadpcm": { + source: "iana" + }, + "audio/vnd.rip": { + source: "iana", + extensions: ["rip"] + }, + "audio/vnd.rn-realaudio": { + compressible: false + }, + "audio/vnd.sealedmedia.softseal.mpeg": { + source: "iana" + }, + "audio/vnd.vmx.cvsd": { + source: "iana" + }, + "audio/vnd.wave": { + compressible: false + }, + "audio/vorbis": { + source: "iana", + compressible: false + }, + "audio/vorbis-config": { + source: "iana" + }, + "audio/wav": { + compressible: false, + extensions: ["wav"] + }, + "audio/wave": { + compressible: false, + extensions: ["wav"] + }, + "audio/webm": { + source: "apache", + compressible: false, + extensions: ["weba"] + }, + "audio/x-aac": { + source: "apache", + compressible: false, + extensions: ["aac"] + }, + "audio/x-aiff": { + source: "apache", + extensions: ["aif", "aiff", "aifc"] + }, + "audio/x-caf": { + source: "apache", + compressible: false, + extensions: ["caf"] + }, + "audio/x-flac": { + source: "apache", + extensions: ["flac"] + }, + "audio/x-m4a": { + source: "nginx", + extensions: ["m4a"] + }, + "audio/x-matroska": { + source: "apache", + extensions: ["mka"] + }, + "audio/x-mpegurl": { + source: "apache", + extensions: ["m3u"] + }, + "audio/x-ms-wax": { + source: "apache", + extensions: ["wax"] + }, + "audio/x-ms-wma": { + source: "apache", + extensions: ["wma"] + }, + "audio/x-pn-realaudio": { + source: "apache", + extensions: ["ram", "ra"] + }, + "audio/x-pn-realaudio-plugin": { + source: "apache", + extensions: ["rmp"] + }, + "audio/x-realaudio": { + source: "nginx", + extensions: ["ra"] + }, + "audio/x-tta": { + source: "apache" + }, + "audio/x-wav": { + source: "apache", + extensions: ["wav"] + }, + "audio/xm": { + source: "apache", + extensions: ["xm"] + }, + "chemical/x-cdx": { + source: "apache", + extensions: ["cdx"] + }, + "chemical/x-cif": { + source: "apache", + extensions: ["cif"] + }, + "chemical/x-cmdf": { + source: "apache", + extensions: ["cmdf"] + }, + "chemical/x-cml": { + source: "apache", + extensions: ["cml"] + }, + "chemical/x-csml": { + source: "apache", + extensions: ["csml"] + }, + "chemical/x-pdb": { + source: "apache" + }, + "chemical/x-xyz": { + source: "apache", + extensions: ["xyz"] + }, + "font/collection": { + source: "iana", + extensions: ["ttc"] + }, + "font/otf": { + source: "iana", + compressible: true, + extensions: ["otf"] + }, + "font/sfnt": { + source: "iana" + }, + "font/ttf": { + source: "iana", + compressible: true, + extensions: ["ttf"] + }, + "font/woff": { + source: "iana", + extensions: ["woff"] + }, + "font/woff2": { + source: "iana", + extensions: ["woff2"] + }, + "image/aces": { + source: "iana", + extensions: ["exr"] + }, + "image/apng": { + source: "iana", + compressible: false, + extensions: ["apng"] + }, + "image/avci": { + source: "iana", + extensions: ["avci"] + }, + "image/avcs": { + source: "iana", + extensions: ["avcs"] + }, + "image/avif": { + source: "iana", + compressible: false, + extensions: ["avif"] + }, + "image/bmp": { + source: "iana", + compressible: true, + extensions: ["bmp", "dib"] + }, + "image/cgm": { + source: "iana", + extensions: ["cgm"] + }, + "image/dicom-rle": { + source: "iana", + extensions: ["drle"] + }, + "image/dpx": { + source: "iana", + extensions: ["dpx"] + }, + "image/emf": { + source: "iana", + extensions: ["emf"] + }, + "image/fits": { + source: "iana", + extensions: ["fits"] + }, + "image/g3fax": { + source: "iana", + extensions: ["g3"] + }, + "image/gif": { + source: "iana", + compressible: false, + extensions: ["gif"] + }, + "image/heic": { + source: "iana", + extensions: ["heic"] + }, + "image/heic-sequence": { + source: "iana", + extensions: ["heics"] + }, + "image/heif": { + source: "iana", + extensions: ["heif"] + }, + "image/heif-sequence": { + source: "iana", + extensions: ["heifs"] + }, + "image/hej2k": { + source: "iana", + extensions: ["hej2"] + }, + "image/ief": { + source: "iana", + extensions: ["ief"] + }, + "image/j2c": { + source: "iana" + }, + "image/jaii": { + source: "iana", + extensions: ["jaii"] + }, + "image/jais": { + source: "iana", + extensions: ["jais"] + }, + "image/jls": { + source: "iana", + extensions: ["jls"] + }, + "image/jp2": { + source: "iana", + compressible: false, + extensions: ["jp2", "jpg2"] + }, + "image/jpeg": { + source: "iana", + compressible: false, + extensions: ["jpg", "jpeg", "jpe"] + }, + "image/jph": { + source: "iana", + extensions: ["jph"] + }, + "image/jphc": { + source: "iana", + extensions: ["jhc"] + }, + "image/jpm": { + source: "iana", + compressible: false, + extensions: ["jpm", "jpgm"] + }, + "image/jpx": { + source: "iana", + compressible: false, + extensions: ["jpx", "jpf"] + }, + "image/jxl": { + source: "iana", + extensions: ["jxl"] + }, + "image/jxr": { + source: "iana", + extensions: ["jxr"] + }, + "image/jxra": { + source: "iana", + extensions: ["jxra"] + }, + "image/jxrs": { + source: "iana", + extensions: ["jxrs"] + }, + "image/jxs": { + source: "iana", + extensions: ["jxs"] + }, + "image/jxsc": { + source: "iana", + extensions: ["jxsc"] + }, + "image/jxsi": { + source: "iana", + extensions: ["jxsi"] + }, + "image/jxss": { + source: "iana", + extensions: ["jxss"] + }, + "image/ktx": { + source: "iana", + extensions: ["ktx"] + }, + "image/ktx2": { + source: "iana", + extensions: ["ktx2"] + }, + "image/naplps": { + source: "iana" + }, + "image/pjpeg": { + compressible: false, + extensions: ["jfif"] + }, + "image/png": { + source: "iana", + compressible: false, + extensions: ["png"] + }, + "image/prs.btif": { + source: "iana", + extensions: ["btif", "btf"] + }, + "image/prs.pti": { + source: "iana", + extensions: ["pti"] + }, + "image/pwg-raster": { + source: "iana" + }, + "image/sgi": { + source: "apache", + extensions: ["sgi"] + }, + "image/svg+xml": { + source: "iana", + compressible: true, + extensions: ["svg", "svgz"] + }, + "image/t38": { + source: "iana", + extensions: ["t38"] + }, + "image/tiff": { + source: "iana", + compressible: false, + extensions: ["tif", "tiff"] + }, + "image/tiff-fx": { + source: "iana", + extensions: ["tfx"] + }, + "image/vnd.adobe.photoshop": { + source: "iana", + compressible: true, + extensions: ["psd"] + }, + "image/vnd.airzip.accelerator.azv": { + source: "iana", + extensions: ["azv"] + }, + "image/vnd.clip": { + source: "iana" + }, + "image/vnd.cns.inf2": { + source: "iana" + }, + "image/vnd.dece.graphic": { + source: "iana", + extensions: ["uvi", "uvvi", "uvg", "uvvg"] + }, + "image/vnd.djvu": { + source: "iana", + extensions: ["djvu", "djv"] + }, + "image/vnd.dvb.subtitle": { + source: "iana", + extensions: ["sub"] + }, + "image/vnd.dwg": { + source: "iana", + extensions: ["dwg"] + }, + "image/vnd.dxf": { + source: "iana", + extensions: ["dxf"] + }, + "image/vnd.fastbidsheet": { + source: "iana", + extensions: ["fbs"] + }, + "image/vnd.fpx": { + source: "iana", + extensions: ["fpx"] + }, + "image/vnd.fst": { + source: "iana", + extensions: ["fst"] + }, + "image/vnd.fujixerox.edmics-mmr": { + source: "iana", + extensions: ["mmr"] + }, + "image/vnd.fujixerox.edmics-rlc": { + source: "iana", + extensions: ["rlc"] + }, + "image/vnd.globalgraphics.pgb": { + source: "iana" + }, + "image/vnd.microsoft.icon": { + source: "iana", + compressible: true, + extensions: ["ico"] + }, + "image/vnd.mix": { + source: "iana" + }, + "image/vnd.mozilla.apng": { + source: "iana" + }, + "image/vnd.ms-dds": { + compressible: true, + extensions: ["dds"] + }, + "image/vnd.ms-modi": { + source: "iana", + extensions: ["mdi"] + }, + "image/vnd.ms-photo": { + source: "apache", + extensions: ["wdp"] + }, + "image/vnd.net-fpx": { + source: "iana", + extensions: ["npx"] + }, + "image/vnd.pco.b16": { + source: "iana", + extensions: ["b16"] + }, + "image/vnd.radiance": { + source: "iana" + }, + "image/vnd.sealed.png": { + source: "iana" + }, + "image/vnd.sealedmedia.softseal.gif": { + source: "iana" + }, + "image/vnd.sealedmedia.softseal.jpg": { + source: "iana" + }, + "image/vnd.svf": { + source: "iana" + }, + "image/vnd.tencent.tap": { + source: "iana", + extensions: ["tap"] + }, + "image/vnd.valve.source.texture": { + source: "iana", + extensions: ["vtf"] + }, + "image/vnd.wap.wbmp": { + source: "iana", + extensions: ["wbmp"] + }, + "image/vnd.xiff": { + source: "iana", + extensions: ["xif"] + }, + "image/vnd.zbrush.pcx": { + source: "iana", + extensions: ["pcx"] + }, + "image/webp": { + source: "iana", + extensions: ["webp"] + }, + "image/wmf": { + source: "iana", + extensions: ["wmf"] + }, + "image/x-3ds": { + source: "apache", + extensions: ["3ds"] + }, + "image/x-adobe-dng": { + extensions: ["dng"] + }, + "image/x-cmu-raster": { + source: "apache", + extensions: ["ras"] + }, + "image/x-cmx": { + source: "apache", + extensions: ["cmx"] + }, + "image/x-emf": { + source: "iana" + }, + "image/x-freehand": { + source: "apache", + extensions: ["fh", "fhc", "fh4", "fh5", "fh7"] + }, + "image/x-icon": { + source: "apache", + compressible: true, + extensions: ["ico"] + }, + "image/x-jng": { + source: "nginx", + extensions: ["jng"] + }, + "image/x-mrsid-image": { + source: "apache", + extensions: ["sid"] + }, + "image/x-ms-bmp": { + source: "nginx", + compressible: true, + extensions: ["bmp"] + }, + "image/x-pcx": { + source: "apache", + extensions: ["pcx"] + }, + "image/x-pict": { + source: "apache", + extensions: ["pic", "pct"] + }, + "image/x-portable-anymap": { + source: "apache", + extensions: ["pnm"] + }, + "image/x-portable-bitmap": { + source: "apache", + extensions: ["pbm"] + }, + "image/x-portable-graymap": { + source: "apache", + extensions: ["pgm"] + }, + "image/x-portable-pixmap": { + source: "apache", + extensions: ["ppm"] + }, + "image/x-rgb": { + source: "apache", + extensions: ["rgb"] + }, + "image/x-tga": { + source: "apache", + extensions: ["tga"] + }, + "image/x-wmf": { + source: "iana" + }, + "image/x-xbitmap": { + source: "apache", + extensions: ["xbm"] + }, + "image/x-xcf": { + compressible: false + }, + "image/x-xpixmap": { + source: "apache", + extensions: ["xpm"] + }, + "image/x-xwindowdump": { + source: "apache", + extensions: ["xwd"] + }, + "message/bhttp": { + source: "iana" + }, + "message/cpim": { + source: "iana" + }, + "message/delivery-status": { + source: "iana" + }, + "message/disposition-notification": { + source: "iana", + extensions: [ + "disposition-notification" + ] + }, + "message/external-body": { + source: "iana" + }, + "message/feedback-report": { + source: "iana" + }, + "message/global": { + source: "iana", + extensions: ["u8msg"] + }, + "message/global-delivery-status": { + source: "iana", + extensions: ["u8dsn"] + }, + "message/global-disposition-notification": { + source: "iana", + extensions: ["u8mdn"] + }, + "message/global-headers": { + source: "iana", + extensions: ["u8hdr"] + }, + "message/http": { + source: "iana", + compressible: false + }, + "message/imdn+xml": { + source: "iana", + compressible: true + }, + "message/mls": { + source: "iana" + }, + "message/news": { + source: "apache" + }, + "message/ohttp-req": { + source: "iana" + }, + "message/ohttp-res": { + source: "iana" + }, + "message/partial": { + source: "iana", + compressible: false + }, + "message/rfc822": { + source: "iana", + compressible: true, + extensions: ["eml", "mime", "mht", "mhtml"] + }, + "message/s-http": { + source: "apache" + }, + "message/sip": { + source: "iana" + }, + "message/sipfrag": { + source: "iana" + }, + "message/tracking-status": { + source: "iana" + }, + "message/vnd.si.simp": { + source: "apache" + }, + "message/vnd.wfa.wsc": { + source: "iana", + extensions: ["wsc"] + }, + "model/3mf": { + source: "iana", + extensions: ["3mf"] + }, + "model/e57": { + source: "iana" + }, + "model/gltf+json": { + source: "iana", + compressible: true, + extensions: ["gltf"] + }, + "model/gltf-binary": { + source: "iana", + compressible: true, + extensions: ["glb"] + }, + "model/iges": { + source: "iana", + compressible: false, + extensions: ["igs", "iges"] + }, + "model/jt": { + source: "iana", + extensions: ["jt"] + }, + "model/mesh": { + source: "iana", + compressible: false, + extensions: ["msh", "mesh", "silo"] + }, + "model/mtl": { + source: "iana", + extensions: ["mtl"] + }, + "model/obj": { + source: "iana", + extensions: ["obj"] + }, + "model/prc": { + source: "iana", + extensions: ["prc"] + }, + "model/step": { + source: "iana", + extensions: ["step", "stp", "stpnc", "p21", "210"] + }, + "model/step+xml": { + source: "iana", + compressible: true, + extensions: ["stpx"] + }, + "model/step+zip": { + source: "iana", + compressible: false, + extensions: ["stpz"] + }, + "model/step-xml+zip": { + source: "iana", + compressible: false, + extensions: ["stpxz"] + }, + "model/stl": { + source: "iana", + extensions: ["stl"] + }, + "model/u3d": { + source: "iana", + extensions: ["u3d"] + }, + "model/vnd.bary": { + source: "iana", + extensions: ["bary"] + }, + "model/vnd.cld": { + source: "iana", + extensions: ["cld"] + }, + "model/vnd.collada+xml": { + source: "iana", + compressible: true, + extensions: ["dae"] + }, + "model/vnd.dwf": { + source: "iana", + extensions: ["dwf"] + }, + "model/vnd.flatland.3dml": { + source: "iana" + }, + "model/vnd.gdl": { + source: "iana", + extensions: ["gdl"] + }, + "model/vnd.gs-gdl": { + source: "apache" + }, + "model/vnd.gs.gdl": { + source: "iana" + }, + "model/vnd.gtw": { + source: "iana", + extensions: ["gtw"] + }, + "model/vnd.moml+xml": { + source: "iana", + compressible: true + }, + "model/vnd.mts": { + source: "iana", + extensions: ["mts"] + }, + "model/vnd.opengex": { + source: "iana", + extensions: ["ogex"] + }, + "model/vnd.parasolid.transmit.binary": { + source: "iana", + extensions: ["x_b"] + }, + "model/vnd.parasolid.transmit.text": { + source: "iana", + extensions: ["x_t"] + }, + "model/vnd.pytha.pyox": { + source: "iana", + extensions: ["pyo", "pyox"] + }, + "model/vnd.rosette.annotated-data-model": { + source: "iana" + }, + "model/vnd.sap.vds": { + source: "iana", + extensions: ["vds"] + }, + "model/vnd.usda": { + source: "iana", + extensions: ["usda"] + }, + "model/vnd.usdz+zip": { + source: "iana", + compressible: false, + extensions: ["usdz"] + }, + "model/vnd.valve.source.compiled-map": { + source: "iana", + extensions: ["bsp"] + }, + "model/vnd.vtu": { + source: "iana", + extensions: ["vtu"] + }, + "model/vrml": { + source: "iana", + compressible: false, + extensions: ["wrl", "vrml"] + }, + "model/x3d+binary": { + source: "apache", + compressible: false, + extensions: ["x3db", "x3dbz"] + }, + "model/x3d+fastinfoset": { + source: "iana", + extensions: ["x3db"] + }, + "model/x3d+vrml": { + source: "apache", + compressible: false, + extensions: ["x3dv", "x3dvz"] + }, + "model/x3d+xml": { + source: "iana", + compressible: true, + extensions: ["x3d", "x3dz"] + }, + "model/x3d-vrml": { + source: "iana", + extensions: ["x3dv"] + }, + "multipart/alternative": { + source: "iana", + compressible: false + }, + "multipart/appledouble": { + source: "iana" + }, + "multipart/byteranges": { + source: "iana" + }, + "multipart/digest": { + source: "iana" + }, + "multipart/encrypted": { + source: "iana", + compressible: false + }, + "multipart/form-data": { + source: "iana", + compressible: false + }, + "multipart/header-set": { + source: "iana" + }, + "multipart/mixed": { + source: "iana" + }, + "multipart/multilingual": { + source: "iana" + }, + "multipart/parallel": { + source: "iana" + }, + "multipart/related": { + source: "iana", + compressible: false + }, + "multipart/report": { + source: "iana" + }, + "multipart/signed": { + source: "iana", + compressible: false + }, + "multipart/vnd.bint.med-plus": { + source: "iana" + }, + "multipart/voice-message": { + source: "iana" + }, + "multipart/x-mixed-replace": { + source: "iana" + }, + "text/1d-interleaved-parityfec": { + source: "iana" + }, + "text/cache-manifest": { + source: "iana", + compressible: true, + extensions: ["appcache", "manifest"] + }, + "text/calendar": { + source: "iana", + extensions: ["ics", "ifb"] + }, + "text/calender": { + compressible: true + }, + "text/cmd": { + compressible: true + }, + "text/coffeescript": { + extensions: ["coffee", "litcoffee"] + }, + "text/cql": { + source: "iana" + }, + "text/cql-expression": { + source: "iana" + }, + "text/cql-identifier": { + source: "iana" + }, + "text/css": { + source: "iana", + charset: "UTF-8", + compressible: true, + extensions: ["css"] + }, + "text/csv": { + source: "iana", + compressible: true, + extensions: ["csv"] + }, + "text/csv-schema": { + source: "iana" + }, + "text/directory": { + source: "iana" + }, + "text/dns": { + source: "iana" + }, + "text/ecmascript": { + source: "apache" + }, + "text/encaprtp": { + source: "iana" + }, + "text/enriched": { + source: "iana" + }, + "text/fhirpath": { + source: "iana" + }, + "text/flexfec": { + source: "iana" + }, + "text/fwdred": { + source: "iana" + }, + "text/gff3": { + source: "iana" + }, + "text/grammar-ref-list": { + source: "iana" + }, + "text/hl7v2": { + source: "iana" + }, + "text/html": { + source: "iana", + compressible: true, + extensions: ["html", "htm", "shtml"] + }, + "text/jade": { + extensions: ["jade"] + }, + "text/javascript": { + source: "iana", + charset: "UTF-8", + compressible: true, + extensions: ["js", "mjs"] + }, + "text/jcr-cnd": { + source: "iana" + }, + "text/jsx": { + compressible: true, + extensions: ["jsx"] + }, + "text/less": { + compressible: true, + extensions: ["less"] + }, + "text/markdown": { + source: "iana", + compressible: true, + extensions: ["md", "markdown"] + }, + "text/mathml": { + source: "nginx", + extensions: ["mml"] + }, + "text/mdx": { + compressible: true, + extensions: ["mdx"] + }, + "text/mizar": { + source: "iana" + }, + "text/n3": { + source: "iana", + charset: "UTF-8", + compressible: true, + extensions: ["n3"] + }, + "text/parameters": { + source: "iana", + charset: "UTF-8" + }, + "text/parityfec": { + source: "iana" + }, + "text/plain": { + source: "iana", + compressible: true, + extensions: ["txt", "text", "conf", "def", "list", "log", "in", "ini"] + }, + "text/provenance-notation": { + source: "iana", + charset: "UTF-8" + }, + "text/prs.fallenstein.rst": { + source: "iana" + }, + "text/prs.lines.tag": { + source: "iana", + extensions: ["dsc"] + }, + "text/prs.prop.logic": { + source: "iana" + }, + "text/prs.texi": { + source: "iana" + }, + "text/raptorfec": { + source: "iana" + }, + "text/red": { + source: "iana" + }, + "text/rfc822-headers": { + source: "iana" + }, + "text/richtext": { + source: "iana", + compressible: true, + extensions: ["rtx"] + }, + "text/rtf": { + source: "iana", + compressible: true, + extensions: ["rtf"] + }, + "text/rtp-enc-aescm128": { + source: "iana" + }, + "text/rtploopback": { + source: "iana" + }, + "text/rtx": { + source: "iana" + }, + "text/sgml": { + source: "iana", + extensions: ["sgml", "sgm"] + }, + "text/shaclc": { + source: "iana" + }, + "text/shex": { + source: "iana", + extensions: ["shex"] + }, + "text/slim": { + extensions: ["slim", "slm"] + }, + "text/spdx": { + source: "iana", + extensions: ["spdx"] + }, + "text/strings": { + source: "iana" + }, + "text/stylus": { + extensions: ["stylus", "styl"] + }, + "text/t140": { + source: "iana" + }, + "text/tab-separated-values": { + source: "iana", + compressible: true, + extensions: ["tsv"] + }, + "text/troff": { + source: "iana", + extensions: ["t", "tr", "roff", "man", "me", "ms"] + }, + "text/turtle": { + source: "iana", + charset: "UTF-8", + extensions: ["ttl"] + }, + "text/ulpfec": { + source: "iana" + }, + "text/uri-list": { + source: "iana", + compressible: true, + extensions: ["uri", "uris", "urls"] + }, + "text/vcard": { + source: "iana", + compressible: true, + extensions: ["vcard"] + }, + "text/vnd.a": { + source: "iana" + }, + "text/vnd.abc": { + source: "iana" + }, + "text/vnd.ascii-art": { + source: "iana" + }, + "text/vnd.curl": { + source: "iana", + extensions: ["curl"] + }, + "text/vnd.curl.dcurl": { + source: "apache", + extensions: ["dcurl"] + }, + "text/vnd.curl.mcurl": { + source: "apache", + extensions: ["mcurl"] + }, + "text/vnd.curl.scurl": { + source: "apache", + extensions: ["scurl"] + }, + "text/vnd.debian.copyright": { + source: "iana", + charset: "UTF-8" + }, + "text/vnd.dmclientscript": { + source: "iana" + }, + "text/vnd.dvb.subtitle": { + source: "iana", + extensions: ["sub"] + }, + "text/vnd.esmertec.theme-descriptor": { + source: "iana", + charset: "UTF-8" + }, + "text/vnd.exchangeable": { + source: "iana" + }, + "text/vnd.familysearch.gedcom": { + source: "iana", + extensions: ["ged"] + }, + "text/vnd.ficlab.flt": { + source: "iana" + }, + "text/vnd.fly": { + source: "iana", + extensions: ["fly"] + }, + "text/vnd.fmi.flexstor": { + source: "iana", + extensions: ["flx"] + }, + "text/vnd.gml": { + source: "iana" + }, + "text/vnd.graphviz": { + source: "iana", + extensions: ["gv"] + }, + "text/vnd.hans": { + source: "iana" + }, + "text/vnd.hgl": { + source: "iana" + }, + "text/vnd.in3d.3dml": { + source: "iana", + extensions: ["3dml"] + }, + "text/vnd.in3d.spot": { + source: "iana", + extensions: ["spot"] + }, + "text/vnd.iptc.newsml": { + source: "iana" + }, + "text/vnd.iptc.nitf": { + source: "iana" + }, + "text/vnd.latex-z": { + source: "iana" + }, + "text/vnd.motorola.reflex": { + source: "iana" + }, + "text/vnd.ms-mediapackage": { + source: "iana" + }, + "text/vnd.net2phone.commcenter.command": { + source: "iana" + }, + "text/vnd.radisys.msml-basic-layout": { + source: "iana" + }, + "text/vnd.senx.warpscript": { + source: "iana" + }, + "text/vnd.si.uricatalogue": { + source: "apache" + }, + "text/vnd.sosi": { + source: "iana" + }, + "text/vnd.sun.j2me.app-descriptor": { + source: "iana", + charset: "UTF-8", + extensions: ["jad"] + }, + "text/vnd.trolltech.linguist": { + source: "iana", + charset: "UTF-8" + }, + "text/vnd.vcf": { + source: "iana" + }, + "text/vnd.wap.si": { + source: "iana" + }, + "text/vnd.wap.sl": { + source: "iana" + }, + "text/vnd.wap.wml": { + source: "iana", + extensions: ["wml"] + }, + "text/vnd.wap.wmlscript": { + source: "iana", + extensions: ["wmls"] + }, + "text/vnd.zoo.kcl": { + source: "iana" + }, + "text/vtt": { + source: "iana", + charset: "UTF-8", + compressible: true, + extensions: ["vtt"] + }, + "text/wgsl": { + source: "iana", + extensions: ["wgsl"] + }, + "text/x-asm": { + source: "apache", + extensions: ["s", "asm"] + }, + "text/x-c": { + source: "apache", + extensions: ["c", "cc", "cxx", "cpp", "h", "hh", "dic"] + }, + "text/x-component": { + source: "nginx", + extensions: ["htc"] + }, + "text/x-fortran": { + source: "apache", + extensions: ["f", "for", "f77", "f90"] + }, + "text/x-gwt-rpc": { + compressible: true + }, + "text/x-handlebars-template": { + extensions: ["hbs"] + }, + "text/x-java-source": { + source: "apache", + extensions: ["java"] + }, + "text/x-jquery-tmpl": { + compressible: true + }, + "text/x-lua": { + extensions: ["lua"] + }, + "text/x-markdown": { + compressible: true, + extensions: ["mkd"] + }, + "text/x-nfo": { + source: "apache", + extensions: ["nfo"] + }, + "text/x-opml": { + source: "apache", + extensions: ["opml"] + }, + "text/x-org": { + compressible: true, + extensions: ["org"] + }, + "text/x-pascal": { + source: "apache", + extensions: ["p", "pas"] + }, + "text/x-processing": { + compressible: true, + extensions: ["pde"] + }, + "text/x-sass": { + extensions: ["sass"] + }, + "text/x-scss": { + extensions: ["scss"] + }, + "text/x-setext": { + source: "apache", + extensions: ["etx"] + }, + "text/x-sfv": { + source: "apache", + extensions: ["sfv"] + }, + "text/x-suse-ymp": { + compressible: true, + extensions: ["ymp"] + }, + "text/x-uuencode": { + source: "apache", + extensions: ["uu"] + }, + "text/x-vcalendar": { + source: "apache", + extensions: ["vcs"] + }, + "text/x-vcard": { + source: "apache", + extensions: ["vcf"] + }, + "text/xml": { + source: "iana", + compressible: true, + extensions: ["xml"] + }, + "text/xml-external-parsed-entity": { + source: "iana" + }, + "text/yaml": { + compressible: true, + extensions: ["yaml", "yml"] + }, + "video/1d-interleaved-parityfec": { + source: "iana" + }, + "video/3gpp": { + source: "iana", + extensions: ["3gp", "3gpp"] + }, + "video/3gpp-tt": { + source: "iana" + }, + "video/3gpp2": { + source: "iana", + extensions: ["3g2"] + }, + "video/av1": { + source: "iana" + }, + "video/bmpeg": { + source: "iana" + }, + "video/bt656": { + source: "iana" + }, + "video/celb": { + source: "iana" + }, + "video/dv": { + source: "iana" + }, + "video/encaprtp": { + source: "iana" + }, + "video/evc": { + source: "iana" + }, + "video/ffv1": { + source: "iana" + }, + "video/flexfec": { + source: "iana" + }, + "video/h261": { + source: "iana", + extensions: ["h261"] + }, + "video/h263": { + source: "iana", + extensions: ["h263"] + }, + "video/h263-1998": { + source: "iana" + }, + "video/h263-2000": { + source: "iana" + }, + "video/h264": { + source: "iana", + extensions: ["h264"] + }, + "video/h264-rcdo": { + source: "iana" + }, + "video/h264-svc": { + source: "iana" + }, + "video/h265": { + source: "iana" + }, + "video/h266": { + source: "iana" + }, + "video/iso.segment": { + source: "iana", + extensions: ["m4s"] + }, + "video/jpeg": { + source: "iana", + extensions: ["jpgv"] + }, + "video/jpeg2000": { + source: "iana" + }, + "video/jpm": { + source: "apache", + extensions: ["jpm", "jpgm"] + }, + "video/jxsv": { + source: "iana" + }, + "video/lottie+json": { + source: "iana", + compressible: true + }, + "video/matroska": { + source: "iana" + }, + "video/matroska-3d": { + source: "iana" + }, + "video/mj2": { + source: "iana", + extensions: ["mj2", "mjp2"] + }, + "video/mp1s": { + source: "iana" + }, + "video/mp2p": { + source: "iana" + }, + "video/mp2t": { + source: "iana", + extensions: ["ts", "m2t", "m2ts", "mts"] + }, + "video/mp4": { + source: "iana", + compressible: false, + extensions: ["mp4", "mp4v", "mpg4"] + }, + "video/mp4v-es": { + source: "iana" + }, + "video/mpeg": { + source: "iana", + compressible: false, + extensions: ["mpeg", "mpg", "mpe", "m1v", "m2v"] + }, + "video/mpeg4-generic": { + source: "iana" + }, + "video/mpv": { + source: "iana" + }, + "video/nv": { + source: "iana" + }, + "video/ogg": { + source: "iana", + compressible: false, + extensions: ["ogv"] + }, + "video/parityfec": { + source: "iana" + }, + "video/pointer": { + source: "iana" + }, + "video/quicktime": { + source: "iana", + compressible: false, + extensions: ["qt", "mov"] + }, + "video/raptorfec": { + source: "iana" + }, + "video/raw": { + source: "iana" + }, + "video/rtp-enc-aescm128": { + source: "iana" + }, + "video/rtploopback": { + source: "iana" + }, + "video/rtx": { + source: "iana" + }, + "video/scip": { + source: "iana" + }, + "video/smpte291": { + source: "iana" + }, + "video/smpte292m": { + source: "iana" + }, + "video/ulpfec": { + source: "iana" + }, + "video/vc1": { + source: "iana" + }, + "video/vc2": { + source: "iana" + }, + "video/vnd.cctv": { + source: "iana" + }, + "video/vnd.dece.hd": { + source: "iana", + extensions: ["uvh", "uvvh"] + }, + "video/vnd.dece.mobile": { + source: "iana", + extensions: ["uvm", "uvvm"] + }, + "video/vnd.dece.mp4": { + source: "iana" + }, + "video/vnd.dece.pd": { + source: "iana", + extensions: ["uvp", "uvvp"] + }, + "video/vnd.dece.sd": { + source: "iana", + extensions: ["uvs", "uvvs"] + }, + "video/vnd.dece.video": { + source: "iana", + extensions: ["uvv", "uvvv"] + }, + "video/vnd.directv.mpeg": { + source: "iana" + }, + "video/vnd.directv.mpeg-tts": { + source: "iana" + }, + "video/vnd.dlna.mpeg-tts": { + source: "iana" + }, + "video/vnd.dvb.file": { + source: "iana", + extensions: ["dvb"] + }, + "video/vnd.fvt": { + source: "iana", + extensions: ["fvt"] + }, + "video/vnd.hns.video": { + source: "iana" + }, + "video/vnd.iptvforum.1dparityfec-1010": { + source: "iana" + }, + "video/vnd.iptvforum.1dparityfec-2005": { + source: "iana" + }, + "video/vnd.iptvforum.2dparityfec-1010": { + source: "iana" + }, + "video/vnd.iptvforum.2dparityfec-2005": { + source: "iana" + }, + "video/vnd.iptvforum.ttsavc": { + source: "iana" + }, + "video/vnd.iptvforum.ttsmpeg2": { + source: "iana" + }, + "video/vnd.motorola.video": { + source: "iana" + }, + "video/vnd.motorola.videop": { + source: "iana" + }, + "video/vnd.mpegurl": { + source: "iana", + extensions: ["mxu", "m4u"] + }, + "video/vnd.ms-playready.media.pyv": { + source: "iana", + extensions: ["pyv"] + }, + "video/vnd.nokia.interleaved-multimedia": { + source: "iana" + }, + "video/vnd.nokia.mp4vr": { + source: "iana" + }, + "video/vnd.nokia.videovoip": { + source: "iana" + }, + "video/vnd.objectvideo": { + source: "iana" + }, + "video/vnd.planar": { + source: "iana" + }, + "video/vnd.radgamettools.bink": { + source: "iana" + }, + "video/vnd.radgamettools.smacker": { + source: "apache" + }, + "video/vnd.sealed.mpeg1": { + source: "iana" + }, + "video/vnd.sealed.mpeg4": { + source: "iana" + }, + "video/vnd.sealed.swf": { + source: "iana" + }, + "video/vnd.sealedmedia.softseal.mov": { + source: "iana" + }, + "video/vnd.uvvu.mp4": { + source: "iana", + extensions: ["uvu", "uvvu"] + }, + "video/vnd.vivo": { + source: "iana", + extensions: ["viv"] + }, + "video/vnd.youtube.yt": { + source: "iana" + }, + "video/vp8": { + source: "iana" + }, + "video/vp9": { + source: "iana" + }, + "video/webm": { + source: "apache", + compressible: false, + extensions: ["webm"] + }, + "video/x-f4v": { + source: "apache", + extensions: ["f4v"] + }, + "video/x-fli": { + source: "apache", + extensions: ["fli"] + }, + "video/x-flv": { + source: "apache", + compressible: false, + extensions: ["flv"] + }, + "video/x-m4v": { + source: "apache", + extensions: ["m4v"] + }, + "video/x-matroska": { + source: "apache", + compressible: false, + extensions: ["mkv", "mk3d", "mks"] + }, + "video/x-mng": { + source: "apache", + extensions: ["mng"] + }, + "video/x-ms-asf": { + source: "apache", + extensions: ["asf", "asx"] + }, + "video/x-ms-vob": { + source: "apache", + extensions: ["vob"] + }, + "video/x-ms-wm": { + source: "apache", + extensions: ["wm"] + }, + "video/x-ms-wmv": { + source: "apache", + compressible: false, + extensions: ["wmv"] + }, + "video/x-ms-wmx": { + source: "apache", + extensions: ["wmx"] + }, + "video/x-ms-wvx": { + source: "apache", + extensions: ["wvx"] + }, + "video/x-msvideo": { + source: "apache", + extensions: ["avi"] + }, + "video/x-sgi-movie": { + source: "apache", + extensions: ["movie"] + }, + "video/x-smv": { + source: "apache", + extensions: ["smv"] + }, + "x-conference/x-cooltalk": { + source: "apache", + extensions: ["ice"] + }, + "x-shader/x-fragment": { + compressible: true + }, + "x-shader/x-vertex": { + compressible: true + } + }; + } +}); + +// node_modules/.pnpm/mime-db@1.54.0/node_modules/mime-db/index.js +var require_mime_db = __commonJS({ + "node_modules/.pnpm/mime-db@1.54.0/node_modules/mime-db/index.js"(exports, module) { + module.exports = require_db(); + } +}); + +// node_modules/.pnpm/mime-types@3.0.2/node_modules/mime-types/mimeScore.js +var require_mimeScore = __commonJS({ + "node_modules/.pnpm/mime-types@3.0.2/node_modules/mime-types/mimeScore.js"(exports, module) { + var FACET_SCORES = { + "prs.": 100, + "x-": 200, + "x.": 300, + "vnd.": 400, + default: 900 + }; + var SOURCE_SCORES = { + nginx: 10, + apache: 20, + iana: 40, + default: 30 + // definitions added by `jshttp/mime-db` project? + }; + var TYPE_SCORES = { + // prefer application/xml over text/xml + // prefer application/rtf over text/rtf + application: 1, + // prefer font/woff over application/font-woff + font: 2, + // prefer video/mp4 over audio/mp4 over application/mp4 + // See https://www.rfc-editor.org/rfc/rfc4337.html#section-2 + audio: 2, + video: 3, + default: 0 + }; + module.exports = function mimeScore(mimeType, source = "default") { + if (mimeType === "application/octet-stream") { + return 0; + } + const [type, subtype] = mimeType.split("/"); + const facet = subtype.replace(/(\.|x-).*/, "$1"); + const facetScore = FACET_SCORES[facet] || FACET_SCORES.default; + const sourceScore = SOURCE_SCORES[source] || SOURCE_SCORES.default; + const typeScore = TYPE_SCORES[type] || TYPE_SCORES.default; + const lengthScore = 1 - mimeType.length / 100; + return facetScore + sourceScore + typeScore + lengthScore; + }; + } +}); + +// node_modules/.pnpm/mime-types@3.0.2/node_modules/mime-types/index.js +var require_mime_types = __commonJS({ + "node_modules/.pnpm/mime-types@3.0.2/node_modules/mime-types/index.js"(exports) { + "use strict"; + var db = require_mime_db(); + var extname2 = __require("path").extname; + var mimeScore = require_mimeScore(); + var EXTRACT_TYPE_REGEXP = /^\s*([^;\s]*)(?:;|\s|$)/; + var TEXT_TYPE_REGEXP = /^text\//i; + exports.charset = charset; + exports.charsets = { lookup: charset }; + exports.contentType = contentType; + exports.extension = extension2; + exports.extensions = /* @__PURE__ */ Object.create(null); + exports.lookup = lookup; + exports.types = /* @__PURE__ */ Object.create(null); + exports._extensionConflicts = []; + populateMaps(exports.extensions, exports.types); + function charset(type) { + if (!type || typeof type !== "string") { + return false; + } + var match = EXTRACT_TYPE_REGEXP.exec(type); + var mime = match && db[match[1].toLowerCase()]; + if (mime && mime.charset) { + return mime.charset; + } + if (match && TEXT_TYPE_REGEXP.test(match[1])) { + return "UTF-8"; + } + return false; + } + function contentType(str) { + if (!str || typeof str !== "string") { + return false; + } + var mime = str.indexOf("/") === -1 ? exports.lookup(str) : str; + if (!mime) { + return false; + } + if (mime.indexOf("charset") === -1) { + var charset2 = exports.charset(mime); + if (charset2) mime += "; charset=" + charset2.toLowerCase(); + } + return mime; + } + function extension2(type) { + if (!type || typeof type !== "string") { + return false; + } + var match = EXTRACT_TYPE_REGEXP.exec(type); + var exts = match && exports.extensions[match[1].toLowerCase()]; + if (!exts || !exts.length) { + return false; + } + return exts[0]; + } + function lookup(path53) { + if (!path53 || typeof path53 !== "string") { + return false; + } + var extension3 = extname2("x." + path53).toLowerCase().slice(1); + if (!extension3) { + return false; + } + return exports.types[extension3] || false; + } + function populateMaps(extensions, types2) { + Object.keys(db).forEach(function forEachMimeType(type) { + var mime = db[type]; + var exts = mime.extensions; + if (!exts || !exts.length) { + return; + } + extensions[type] = exts; + for (var i5 = 0; i5 < exts.length; i5++) { + var extension3 = exts[i5]; + types2[extension3] = _preferredType(extension3, types2[extension3], type); + const legacyType = _preferredTypeLegacy( + extension3, + types2[extension3], + type + ); + if (legacyType !== types2[extension3]) { + exports._extensionConflicts.push([extension3, legacyType, types2[extension3]]); + } + } + }); + } + function _preferredType(ext, type0, type1) { + var score0 = type0 ? mimeScore(type0, db[type0].source) : 0; + var score1 = type1 ? mimeScore(type1, db[type1].source) : 0; + return score0 > score1 ? type0 : type1; + } + function _preferredTypeLegacy(ext, type0, type1) { + var SOURCE_RANK = ["nginx", "apache", void 0, "iana"]; + var score0 = type0 ? SOURCE_RANK.indexOf(db[type0].source) : 0; + var score1 = type1 ? SOURCE_RANK.indexOf(db[type1].source) : 0; + if (exports.types[extension2] !== "application/octet-stream" && (score0 > score1 || score0 === score1 && exports.types[extension2]?.slice(0, 12) === "application/")) { + return type0; + } + return score0 > score1 ? type0 : type1; + } + } +}); + +// node_modules/.pnpm/media-typer@1.1.0/node_modules/media-typer/index.js +var require_media_typer = __commonJS({ + "node_modules/.pnpm/media-typer@1.1.0/node_modules/media-typer/index.js"(exports) { + "use strict"; + var SUBTYPE_NAME_REGEXP = /^[A-Za-z0-9][A-Za-z0-9!#$&^_.-]{0,126}$/; + var TYPE_NAME_REGEXP = /^[A-Za-z0-9][A-Za-z0-9!#$&^_-]{0,126}$/; + var TYPE_REGEXP = /^ *([A-Za-z0-9][A-Za-z0-9!#$&^_-]{0,126})\/([A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}) *$/; + exports.format = format2; + exports.parse = parse5; + exports.test = test; + function format2(obj) { + if (!obj || typeof obj !== "object") { + throw new TypeError("argument obj is required"); + } + var subtype = obj.subtype; + var suffix = obj.suffix; + var type = obj.type; + if (!type || !TYPE_NAME_REGEXP.test(type)) { + throw new TypeError("invalid type"); + } + if (!subtype || !SUBTYPE_NAME_REGEXP.test(subtype)) { + throw new TypeError("invalid subtype"); + } + var string4 = type + "/" + subtype; + if (suffix) { + if (!TYPE_NAME_REGEXP.test(suffix)) { + throw new TypeError("invalid suffix"); + } + string4 += "+" + suffix; + } + return string4; + } + function test(string4) { + if (!string4) { + throw new TypeError("argument string is required"); + } + if (typeof string4 !== "string") { + throw new TypeError("argument string is required to be a string"); + } + return TYPE_REGEXP.test(string4.toLowerCase()); + } + function parse5(string4) { + if (!string4) { + throw new TypeError("argument string is required"); + } + if (typeof string4 !== "string") { + throw new TypeError("argument string is required to be a string"); + } + var match = TYPE_REGEXP.exec(string4.toLowerCase()); + if (!match) { + throw new TypeError("invalid media type"); + } + var type = match[1]; + var subtype = match[2]; + var suffix; + var index2 = subtype.lastIndexOf("+"); + if (index2 !== -1) { + suffix = subtype.substr(index2 + 1); + subtype = subtype.substr(0, index2); + } + return new MediaType(type, subtype, suffix); + } + function MediaType(type, subtype, suffix) { + this.type = type; + this.subtype = subtype; + this.suffix = suffix; + } + } +}); + +// node_modules/.pnpm/type-is@2.0.1/node_modules/type-is/index.js +var require_type_is = __commonJS({ + "node_modules/.pnpm/type-is@2.0.1/node_modules/type-is/index.js"(exports, module) { + "use strict"; + var contentType = require_content_type(); + var mime = require_mime_types(); + var typer = require_media_typer(); + module.exports = typeofrequest; + module.exports.is = typeis; + module.exports.hasBody = hasbody; + module.exports.normalize = normalize2; + module.exports.match = mimeMatch; + function typeis(value, types_) { + var i5; + var types2 = types_; + var val = tryNormalizeType(value); + if (!val) { + return false; + } + if (types2 && !Array.isArray(types2)) { + types2 = new Array(arguments.length - 1); + for (i5 = 0; i5 < types2.length; i5++) { + types2[i5] = arguments[i5 + 1]; + } + } + if (!types2 || !types2.length) { + return val; + } + var type; + for (i5 = 0; i5 < types2.length; i5++) { + if (mimeMatch(normalize2(type = types2[i5]), val)) { + return type[0] === "+" || type.indexOf("*") !== -1 ? val : type; + } + } + return false; + } + function hasbody(req) { + return req.headers["transfer-encoding"] !== void 0 || !isNaN(req.headers["content-length"]); + } + function typeofrequest(req, types_) { + if (!hasbody(req)) return null; + var types2 = arguments.length > 2 ? Array.prototype.slice.call(arguments, 1) : types_; + var value = req.headers["content-type"]; + return typeis(value, types2); + } + function normalize2(type) { + if (typeof type !== "string") { + return false; + } + switch (type) { + case "urlencoded": + return "application/x-www-form-urlencoded"; + case "multipart": + return "multipart/*"; + } + if (type[0] === "+") { + return "*/*" + type; + } + return type.indexOf("/") === -1 ? mime.lookup(type) : type; + } + function mimeMatch(expected, actual) { + if (expected === false) { + return false; + } + var actualParts = actual.split("/"); + var expectedParts = expected.split("/"); + if (actualParts.length !== 2 || expectedParts.length !== 2) { + return false; + } + if (expectedParts[0] !== "*" && expectedParts[0] !== actualParts[0]) { + return false; + } + if (expectedParts[1].slice(0, 2) === "*+") { + return expectedParts[1].length <= actualParts[1].length + 1 && expectedParts[1].slice(1) === actualParts[1].slice(1 - expectedParts[1].length); + } + if (expectedParts[1] !== "*" && expectedParts[1] !== actualParts[1]) { + return false; + } + return true; + } + function normalizeType(value) { + var type = contentType.parse(value).type; + return typer.test(type) ? type : null; + } + function tryNormalizeType(value) { + try { + return value ? normalizeType(value) : null; + } catch (err) { + return null; + } + } + } +}); + +// node_modules/.pnpm/body-parser@2.2.2/node_modules/body-parser/lib/utils.js +var require_utils = __commonJS({ + "node_modules/.pnpm/body-parser@2.2.2/node_modules/body-parser/lib/utils.js"(exports, module) { + "use strict"; + var bytes = require_bytes(); + var contentType = require_content_type(); + var typeis = require_type_is(); + module.exports = { + getCharset, + normalizeOptions, + passthrough + }; + function getCharset(req) { + try { + return (contentType.parse(req).parameters.charset || "").toLowerCase(); + } catch { + return void 0; + } + } + function typeChecker(type) { + return function checkType(req) { + return Boolean(typeis(req, type)); + }; + } + function normalizeOptions(options, defaultType) { + if (!defaultType) { + throw new TypeError("defaultType must be provided"); + } + var inflate = options?.inflate !== false; + var limit = typeof options?.limit !== "number" ? bytes.parse(options?.limit || "100kb") : options?.limit; + var type = options?.type || defaultType; + var verify2 = options?.verify || false; + var defaultCharset = options?.defaultCharset || "utf-8"; + if (verify2 !== false && typeof verify2 !== "function") { + throw new TypeError("option verify must be function"); + } + var shouldParse = typeof type !== "function" ? typeChecker(type) : type; + return { + inflate, + limit, + verify: verify2, + defaultCharset, + shouldParse + }; + } + function passthrough(value) { + return value; + } + } +}); + +// node_modules/.pnpm/body-parser@2.2.2/node_modules/body-parser/lib/read.js +var require_read = __commonJS({ + "node_modules/.pnpm/body-parser@2.2.2/node_modules/body-parser/lib/read.js"(exports, module) { + "use strict"; + var createError = require_http_errors(); + var getBody3 = require_raw_body(); + var iconv = require_lib(); + var onFinished = require_on_finished(); + var zlib = __require("node:zlib"); + var hasBody = require_type_is().hasBody; + var { getCharset } = require_utils(); + module.exports = read; + function read(req, res, next, parse5, debug, options) { + if (onFinished.isFinished(req)) { + debug("body already parsed"); + next(); + return; + } + if (!("body" in req)) { + req.body = void 0; + } + if (!hasBody(req)) { + debug("skip empty body"); + next(); + return; + } + debug("content-type %j", req.headers["content-type"]); + if (!options.shouldParse(req)) { + debug("skip parsing"); + next(); + return; + } + var encoding = null; + if (options?.skipCharset !== true) { + encoding = getCharset(req) || options.defaultCharset; + if (!!options?.isValidCharset && !options.isValidCharset(encoding)) { + debug("invalid charset"); + next(createError(415, 'unsupported charset "' + encoding.toUpperCase() + '"', { + charset: encoding, + type: "charset.unsupported" + })); + return; + } + } + var length; + var opts = options; + var stream; + var verify2 = opts.verify; + try { + stream = contentstream(req, debug, opts.inflate); + length = stream.length; + stream.length = void 0; + } catch (err) { + return next(err); + } + opts.length = length; + opts.encoding = verify2 ? null : encoding; + if (opts.encoding === null && encoding !== null && !iconv.encodingExists(encoding)) { + return next(createError(415, 'unsupported charset "' + encoding.toUpperCase() + '"', { + charset: encoding.toLowerCase(), + type: "charset.unsupported" + })); + } + debug("read body"); + getBody3(stream, opts, function(error50, body) { + if (error50) { + var _error; + if (error50.type === "encoding.unsupported") { + _error = createError(415, 'unsupported charset "' + encoding.toUpperCase() + '"', { + charset: encoding.toLowerCase(), + type: "charset.unsupported" + }); + } else { + _error = createError(400, error50); + } + if (stream !== req) { + req.unpipe(); + stream.destroy(); + } + dump(req, function onfinished() { + next(createError(400, _error)); + }); + return; + } + if (verify2) { + try { + debug("verify body"); + verify2(req, res, body, encoding); + } catch (err) { + next(createError(403, err, { + body, + type: err.type || "entity.verify.failed" + })); + return; + } + } + var str = body; + try { + debug("parse body"); + str = typeof body !== "string" && encoding !== null ? iconv.decode(body, encoding) : body; + req.body = parse5(str, encoding); + } catch (err) { + next(createError(400, err, { + body: str, + type: err.type || "entity.parse.failed" + })); + return; + } + next(); + }); + } + function contentstream(req, debug, inflate) { + var encoding = (req.headers["content-encoding"] || "identity").toLowerCase(); + var length = req.headers["content-length"]; + debug('content-encoding "%s"', encoding); + if (inflate === false && encoding !== "identity") { + throw createError(415, "content encoding unsupported", { + encoding, + type: "encoding.unsupported" + }); + } + if (encoding === "identity") { + req.length = length; + return req; + } + var stream = createDecompressionStream(encoding, debug); + req.pipe(stream); + return stream; + } + function createDecompressionStream(encoding, debug) { + switch (encoding) { + case "deflate": + debug("inflate body"); + return zlib.createInflate(); + case "gzip": + debug("gunzip body"); + return zlib.createGunzip(); + case "br": + debug("brotli decompress body"); + return zlib.createBrotliDecompress(); + default: + throw createError(415, 'unsupported content encoding "' + encoding + '"', { + encoding, + type: "encoding.unsupported" + }); + } + } + function dump(req, callback) { + if (onFinished.isFinished(req)) { + callback(null); + } else { + onFinished(req, callback); + req.resume(); + } + } + } +}); + +// node_modules/.pnpm/body-parser@2.2.2/node_modules/body-parser/lib/types/json.js +var require_json = __commonJS({ + "node_modules/.pnpm/body-parser@2.2.2/node_modules/body-parser/lib/types/json.js"(exports, module) { + "use strict"; + var debug = require_src()("body-parser:json"); + var read = require_read(); + var { normalizeOptions } = require_utils(); + module.exports = json3; + var FIRST_CHAR_REGEXP = /^[\x20\x09\x0a\x0d]*([^\x20\x09\x0a\x0d])/; + var JSON_SYNTAX_CHAR = "#"; + var JSON_SYNTAX_REGEXP = /#+/g; + function json3(options) { + const normalizedOptions = normalizeOptions(options, "application/json"); + var reviver = options?.reviver; + var strict = options?.strict !== false; + function parse5(body) { + if (body.length === 0) { + return {}; + } + if (strict) { + var first = firstchar(body); + if (first !== "{" && first !== "[") { + debug("strict violation"); + throw createStrictSyntaxError(body, first); + } + } + try { + debug("parse json"); + return JSON.parse(body, reviver); + } catch (e5) { + throw normalizeJsonSyntaxError(e5, { + message: e5.message, + stack: e5.stack + }); + } + } + const readOptions = { + ...normalizedOptions, + // assert charset per RFC 7159 sec 8.1 + isValidCharset: (charset) => charset.slice(0, 4) === "utf-" + }; + return function jsonParser(req, res, next) { + read(req, res, next, parse5, debug, readOptions); + }; + } + function createStrictSyntaxError(str, char2) { + var index2 = str.indexOf(char2); + var partial2 = ""; + if (index2 !== -1) { + partial2 = str.substring(0, index2) + JSON_SYNTAX_CHAR.repeat(str.length - index2); + } + try { + JSON.parse(partial2); + throw new SyntaxError("strict violation"); + } catch (e5) { + return normalizeJsonSyntaxError(e5, { + message: e5.message.replace(JSON_SYNTAX_REGEXP, function(placeholder) { + return str.substring(index2, index2 + placeholder.length); + }), + stack: e5.stack + }); + } + } + function firstchar(str) { + var match = FIRST_CHAR_REGEXP.exec(str); + return match ? match[1] : void 0; + } + function normalizeJsonSyntaxError(error50, obj) { + var keys = Object.getOwnPropertyNames(error50); + for (var i5 = 0; i5 < keys.length; i5++) { + var key = keys[i5]; + if (key !== "stack" && key !== "message") { + delete error50[key]; + } + } + error50.stack = obj.stack.replace(error50.message, obj.message); + error50.message = obj.message; + return error50; + } + } +}); + +// node_modules/.pnpm/body-parser@2.2.2/node_modules/body-parser/lib/types/raw.js +var require_raw = __commonJS({ + "node_modules/.pnpm/body-parser@2.2.2/node_modules/body-parser/lib/types/raw.js"(exports, module) { + "use strict"; + var debug = require_src()("body-parser:raw"); + var read = require_read(); + var { normalizeOptions, passthrough } = require_utils(); + module.exports = raw; + function raw(options) { + const normalizedOptions = normalizeOptions(options, "application/octet-stream"); + const readOptions = { + ...normalizedOptions, + // Skip charset validation and parse the body as is + skipCharset: true + }; + return function rawParser(req, res, next) { + read(req, res, next, passthrough, debug, readOptions); + }; + } + } +}); + +// node_modules/.pnpm/body-parser@2.2.2/node_modules/body-parser/lib/types/text.js +var require_text = __commonJS({ + "node_modules/.pnpm/body-parser@2.2.2/node_modules/body-parser/lib/types/text.js"(exports, module) { + "use strict"; + var debug = require_src()("body-parser:text"); + var read = require_read(); + var { normalizeOptions, passthrough } = require_utils(); + module.exports = text3; + function text3(options) { + const normalizedOptions = normalizeOptions(options, "text/plain"); + return function textParser(req, res, next) { + read(req, res, next, passthrough, debug, normalizedOptions); + }; + } + } +}); + +// node_modules/.pnpm/es-errors@1.3.0/node_modules/es-errors/type.js +var require_type = __commonJS({ + "node_modules/.pnpm/es-errors@1.3.0/node_modules/es-errors/type.js"(exports, module) { + "use strict"; + module.exports = TypeError; + } +}); + +// node_modules/.pnpm/object-inspect@1.13.4/node_modules/object-inspect/util.inspect.js +var require_util_inspect = __commonJS({ + "node_modules/.pnpm/object-inspect@1.13.4/node_modules/object-inspect/util.inspect.js"(exports, module) { + module.exports = __require("util").inspect; + } +}); + +// node_modules/.pnpm/object-inspect@1.13.4/node_modules/object-inspect/index.js +var require_object_inspect = __commonJS({ + "node_modules/.pnpm/object-inspect@1.13.4/node_modules/object-inspect/index.js"(exports, module) { + var hasMap = typeof Map === "function" && Map.prototype; + var mapSizeDescriptor = Object.getOwnPropertyDescriptor && hasMap ? Object.getOwnPropertyDescriptor(Map.prototype, "size") : null; + var mapSize = hasMap && mapSizeDescriptor && typeof mapSizeDescriptor.get === "function" ? mapSizeDescriptor.get : null; + var mapForEach = hasMap && Map.prototype.forEach; + var hasSet = typeof Set === "function" && Set.prototype; + var setSizeDescriptor = Object.getOwnPropertyDescriptor && hasSet ? Object.getOwnPropertyDescriptor(Set.prototype, "size") : null; + var setSize = hasSet && setSizeDescriptor && typeof setSizeDescriptor.get === "function" ? setSizeDescriptor.get : null; + var setForEach = hasSet && Set.prototype.forEach; + var hasWeakMap = typeof WeakMap === "function" && WeakMap.prototype; + var weakMapHas = hasWeakMap ? WeakMap.prototype.has : null; + var hasWeakSet = typeof WeakSet === "function" && WeakSet.prototype; + var weakSetHas = hasWeakSet ? WeakSet.prototype.has : null; + var hasWeakRef = typeof WeakRef === "function" && WeakRef.prototype; + var weakRefDeref = hasWeakRef ? WeakRef.prototype.deref : null; + var booleanValueOf = Boolean.prototype.valueOf; + var objectToString = Object.prototype.toString; + var functionToString = Function.prototype.toString; + var $match = String.prototype.match; + var $slice = String.prototype.slice; + var $replace = String.prototype.replace; + var $toUpperCase = String.prototype.toUpperCase; + var $toLowerCase = String.prototype.toLowerCase; + var $test = RegExp.prototype.test; + var $concat = Array.prototype.concat; + var $join = Array.prototype.join; + var $arrSlice = Array.prototype.slice; + var $floor = Math.floor; + var bigIntValueOf = typeof BigInt === "function" ? BigInt.prototype.valueOf : null; + var gOPS = Object.getOwnPropertySymbols; + var symToString = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? Symbol.prototype.toString : null; + var hasShammedSymbols = typeof Symbol === "function" && typeof Symbol.iterator === "object"; + var toStringTag = typeof Symbol === "function" && Symbol.toStringTag && (typeof Symbol.toStringTag === hasShammedSymbols ? "object" : "symbol") ? Symbol.toStringTag : null; + var isEnumerable = Object.prototype.propertyIsEnumerable; + var gPO = (typeof Reflect === "function" ? Reflect.getPrototypeOf : Object.getPrototypeOf) || ([].__proto__ === Array.prototype ? function(O) { + return O.__proto__; + } : null); + function addNumericSeparator(num, str) { + if (num === Infinity || num === -Infinity || num !== num || num && num > -1e3 && num < 1e3 || $test.call(/e/, str)) { + return str; + } + var sepRegex = /[0-9](?=(?:[0-9]{3})+(?![0-9]))/g; + if (typeof num === "number") { + var int2 = num < 0 ? -$floor(-num) : $floor(num); + if (int2 !== num) { + var intStr = String(int2); + var dec = $slice.call(str, intStr.length + 1); + return $replace.call(intStr, sepRegex, "$&_") + "." + $replace.call($replace.call(dec, /([0-9]{3})/g, "$&_"), /_$/, ""); + } + } + return $replace.call(str, sepRegex, "$&_"); + } + var utilInspect = require_util_inspect(); + var inspectCustom = utilInspect.custom; + var inspectSymbol = isSymbol(inspectCustom) ? inspectCustom : null; + var quotes = { + __proto__: null, + "double": '"', + single: "'" + }; + var quoteREs = { + __proto__: null, + "double": /(["\\])/g, + single: /(['\\])/g + }; + module.exports = function inspect_(obj, options, depth, seen) { + var opts = options || {}; + if (has(opts, "quoteStyle") && !has(quotes, opts.quoteStyle)) { + throw new TypeError('option "quoteStyle" must be "single" or "double"'); + } + if (has(opts, "maxStringLength") && (typeof opts.maxStringLength === "number" ? opts.maxStringLength < 0 && opts.maxStringLength !== Infinity : opts.maxStringLength !== null)) { + throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`'); + } + var customInspect = has(opts, "customInspect") ? opts.customInspect : true; + if (typeof customInspect !== "boolean" && customInspect !== "symbol") { + throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`"); + } + if (has(opts, "indent") && opts.indent !== null && opts.indent !== " " && !(parseInt(opts.indent, 10) === opts.indent && opts.indent > 0)) { + throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`'); + } + if (has(opts, "numericSeparator") && typeof opts.numericSeparator !== "boolean") { + throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`'); + } + var numericSeparator = opts.numericSeparator; + if (typeof obj === "undefined") { + return "undefined"; + } + if (obj === null) { + return "null"; + } + if (typeof obj === "boolean") { + return obj ? "true" : "false"; + } + if (typeof obj === "string") { + return inspectString(obj, opts); + } + if (typeof obj === "number") { + if (obj === 0) { + return Infinity / obj > 0 ? "0" : "-0"; + } + var str = String(obj); + return numericSeparator ? addNumericSeparator(obj, str) : str; + } + if (typeof obj === "bigint") { + var bigIntStr = String(obj) + "n"; + return numericSeparator ? addNumericSeparator(obj, bigIntStr) : bigIntStr; + } + var maxDepth = typeof opts.depth === "undefined" ? 5 : opts.depth; + if (typeof depth === "undefined") { + depth = 0; + } + if (depth >= maxDepth && maxDepth > 0 && typeof obj === "object") { + return isArray(obj) ? "[Array]" : "[Object]"; + } + var indent = getIndent(opts, depth); + if (typeof seen === "undefined") { + seen = []; + } else if (indexOf(seen, obj) >= 0) { + return "[Circular]"; + } + function inspect(value, from, noIndent) { + if (from) { + seen = $arrSlice.call(seen); + seen.push(from); + } + if (noIndent) { + var newOpts = { + depth: opts.depth + }; + if (has(opts, "quoteStyle")) { + newOpts.quoteStyle = opts.quoteStyle; + } + return inspect_(value, newOpts, depth + 1, seen); + } + return inspect_(value, opts, depth + 1, seen); + } + if (typeof obj === "function" && !isRegExp(obj)) { + var name = nameOf(obj); + var keys = arrObjKeys(obj, inspect); + return "[Function" + (name ? ": " + name : " (anonymous)") + "]" + (keys.length > 0 ? " { " + $join.call(keys, ", ") + " }" : ""); + } + if (isSymbol(obj)) { + var symString = hasShammedSymbols ? $replace.call(String(obj), /^(Symbol\(.*\))_[^)]*$/, "$1") : symToString.call(obj); + return typeof obj === "object" && !hasShammedSymbols ? markBoxed(symString) : symString; + } + if (isElement(obj)) { + var s5 = "<" + $toLowerCase.call(String(obj.nodeName)); + var attrs = obj.attributes || []; + for (var i5 = 0; i5 < attrs.length; i5++) { + s5 += " " + attrs[i5].name + "=" + wrapQuotes(quote(attrs[i5].value), "double", opts); + } + s5 += ">"; + if (obj.childNodes && obj.childNodes.length) { + s5 += "..."; + } + s5 += ""; + return s5; + } + if (isArray(obj)) { + if (obj.length === 0) { + return "[]"; + } + var xs = arrObjKeys(obj, inspect); + if (indent && !singleLineValues(xs)) { + return "[" + indentedJoin(xs, indent) + "]"; + } + return "[ " + $join.call(xs, ", ") + " ]"; + } + if (isError(obj)) { + var parts = arrObjKeys(obj, inspect); + if (!("cause" in Error.prototype) && "cause" in obj && !isEnumerable.call(obj, "cause")) { + return "{ [" + String(obj) + "] " + $join.call($concat.call("[cause]: " + inspect(obj.cause), parts), ", ") + " }"; + } + if (parts.length === 0) { + return "[" + String(obj) + "]"; + } + return "{ [" + String(obj) + "] " + $join.call(parts, ", ") + " }"; + } + if (typeof obj === "object" && customInspect) { + if (inspectSymbol && typeof obj[inspectSymbol] === "function" && utilInspect) { + return utilInspect(obj, { depth: maxDepth - depth }); + } else if (customInspect !== "symbol" && typeof obj.inspect === "function") { + return obj.inspect(); + } + } + if (isMap(obj)) { + var mapParts = []; + if (mapForEach) { + mapForEach.call(obj, function(value, key) { + mapParts.push(inspect(key, obj, true) + " => " + inspect(value, obj)); + }); + } + return collectionOf("Map", mapSize.call(obj), mapParts, indent); + } + if (isSet(obj)) { + var setParts = []; + if (setForEach) { + setForEach.call(obj, function(value) { + setParts.push(inspect(value, obj)); + }); + } + return collectionOf("Set", setSize.call(obj), setParts, indent); + } + if (isWeakMap(obj)) { + return weakCollectionOf("WeakMap"); + } + if (isWeakSet(obj)) { + return weakCollectionOf("WeakSet"); + } + if (isWeakRef(obj)) { + return weakCollectionOf("WeakRef"); + } + if (isNumber2(obj)) { + return markBoxed(inspect(Number(obj))); + } + if (isBigInt2(obj)) { + return markBoxed(inspect(bigIntValueOf.call(obj))); + } + if (isBoolean2(obj)) { + return markBoxed(booleanValueOf.call(obj)); + } + if (isString2(obj)) { + return markBoxed(inspect(String(obj))); + } + if (typeof window !== "undefined" && obj === window) { + return "{ [object Window] }"; + } + if (typeof globalThis !== "undefined" && obj === globalThis || typeof global !== "undefined" && obj === global) { + return "{ [object globalThis] }"; + } + if (!isDate2(obj) && !isRegExp(obj)) { + var ys = arrObjKeys(obj, inspect); + var isPlainObject7 = gPO ? gPO(obj) === Object.prototype : obj instanceof Object || obj.constructor === Object; + var protoTag = obj instanceof Object ? "" : "null prototype"; + var stringTag = !isPlainObject7 && toStringTag && Object(obj) === obj && toStringTag in obj ? $slice.call(toStr(obj), 8, -1) : protoTag ? "Object" : ""; + var constructorTag = isPlainObject7 || typeof obj.constructor !== "function" ? "" : obj.constructor.name ? obj.constructor.name + " " : ""; + var tag3 = constructorTag + (stringTag || protoTag ? "[" + $join.call($concat.call([], stringTag || [], protoTag || []), ": ") + "] " : ""); + if (ys.length === 0) { + return tag3 + "{}"; + } + if (indent) { + return tag3 + "{" + indentedJoin(ys, indent) + "}"; + } + return tag3 + "{ " + $join.call(ys, ", ") + " }"; + } + return String(obj); + }; + function wrapQuotes(s5, defaultStyle, opts) { + var style = opts.quoteStyle || defaultStyle; + var quoteChar = quotes[style]; + return quoteChar + s5 + quoteChar; + } + function quote(s5) { + return $replace.call(String(s5), /"/g, """); + } + function canTrustToString(obj) { + return !toStringTag || !(typeof obj === "object" && (toStringTag in obj || typeof obj[toStringTag] !== "undefined")); + } + function isArray(obj) { + return toStr(obj) === "[object Array]" && canTrustToString(obj); + } + function isDate2(obj) { + return toStr(obj) === "[object Date]" && canTrustToString(obj); + } + function isRegExp(obj) { + return toStr(obj) === "[object RegExp]" && canTrustToString(obj); + } + function isError(obj) { + return toStr(obj) === "[object Error]" && canTrustToString(obj); + } + function isString2(obj) { + return toStr(obj) === "[object String]" && canTrustToString(obj); + } + function isNumber2(obj) { + return toStr(obj) === "[object Number]" && canTrustToString(obj); + } + function isBoolean2(obj) { + return toStr(obj) === "[object Boolean]" && canTrustToString(obj); + } + function isSymbol(obj) { + if (hasShammedSymbols) { + return obj && typeof obj === "object" && obj instanceof Symbol; + } + if (typeof obj === "symbol") { + return true; + } + if (!obj || typeof obj !== "object" || !symToString) { + return false; + } + try { + symToString.call(obj); + return true; + } catch (e5) { + } + return false; + } + function isBigInt2(obj) { + if (!obj || typeof obj !== "object" || !bigIntValueOf) { + return false; + } + try { + bigIntValueOf.call(obj); + return true; + } catch (e5) { + } + return false; + } + var hasOwn = Object.prototype.hasOwnProperty || function(key) { + return key in this; + }; + function has(obj, key) { + return hasOwn.call(obj, key); + } + function toStr(obj) { + return objectToString.call(obj); + } + function nameOf(f5) { + if (f5.name) { + return f5.name; + } + var m5 = $match.call(functionToString.call(f5), /^function\s*([\w$]+)/); + if (m5) { + return m5[1]; + } + return null; + } + function indexOf(xs, x5) { + if (xs.indexOf) { + return xs.indexOf(x5); + } + for (var i5 = 0, l5 = xs.length; i5 < l5; i5++) { + if (xs[i5] === x5) { + return i5; + } + } + return -1; + } + function isMap(x5) { + if (!mapSize || !x5 || typeof x5 !== "object") { + return false; + } + try { + mapSize.call(x5); + try { + setSize.call(x5); + } catch (s5) { + return true; + } + return x5 instanceof Map; + } catch (e5) { + } + return false; + } + function isWeakMap(x5) { + if (!weakMapHas || !x5 || typeof x5 !== "object") { + return false; + } + try { + weakMapHas.call(x5, weakMapHas); + try { + weakSetHas.call(x5, weakSetHas); + } catch (s5) { + return true; + } + return x5 instanceof WeakMap; + } catch (e5) { + } + return false; + } + function isWeakRef(x5) { + if (!weakRefDeref || !x5 || typeof x5 !== "object") { + return false; + } + try { + weakRefDeref.call(x5); + return true; + } catch (e5) { + } + return false; + } + function isSet(x5) { + if (!setSize || !x5 || typeof x5 !== "object") { + return false; + } + try { + setSize.call(x5); + try { + mapSize.call(x5); + } catch (m5) { + return true; + } + return x5 instanceof Set; + } catch (e5) { + } + return false; + } + function isWeakSet(x5) { + if (!weakSetHas || !x5 || typeof x5 !== "object") { + return false; + } + try { + weakSetHas.call(x5, weakSetHas); + try { + weakMapHas.call(x5, weakMapHas); + } catch (s5) { + return true; + } + return x5 instanceof WeakSet; + } catch (e5) { + } + return false; + } + function isElement(x5) { + if (!x5 || typeof x5 !== "object") { + return false; + } + if (typeof HTMLElement !== "undefined" && x5 instanceof HTMLElement) { + return true; + } + return typeof x5.nodeName === "string" && typeof x5.getAttribute === "function"; + } + function inspectString(str, opts) { + if (str.length > opts.maxStringLength) { + var remaining = str.length - opts.maxStringLength; + var trailer = "... " + remaining + " more character" + (remaining > 1 ? "s" : ""); + return inspectString($slice.call(str, 0, opts.maxStringLength), opts) + trailer; + } + var quoteRE = quoteREs[opts.quoteStyle || "single"]; + quoteRE.lastIndex = 0; + var s5 = $replace.call($replace.call(str, quoteRE, "\\$1"), /[\x00-\x1f]/g, lowbyte); + return wrapQuotes(s5, "single", opts); + } + function lowbyte(c5) { + var n5 = c5.charCodeAt(0); + var x5 = { + 8: "b", + 9: "t", + 10: "n", + 12: "f", + 13: "r" + }[n5]; + if (x5) { + return "\\" + x5; + } + return "\\x" + (n5 < 16 ? "0" : "") + $toUpperCase.call(n5.toString(16)); + } + function markBoxed(str) { + return "Object(" + str + ")"; + } + function weakCollectionOf(type) { + return type + " { ? }"; + } + function collectionOf(type, size2, entries2, indent) { + var joinedEntries = indent ? indentedJoin(entries2, indent) : $join.call(entries2, ", "); + return type + " (" + size2 + ") {" + joinedEntries + "}"; + } + function singleLineValues(xs) { + for (var i5 = 0; i5 < xs.length; i5++) { + if (indexOf(xs[i5], "\n") >= 0) { + return false; + } + } + return true; + } + function getIndent(opts, depth) { + var baseIndent; + if (opts.indent === " ") { + baseIndent = " "; + } else if (typeof opts.indent === "number" && opts.indent > 0) { + baseIndent = $join.call(Array(opts.indent + 1), " "); + } else { + return null; + } + return { + base: baseIndent, + prev: $join.call(Array(depth + 1), baseIndent) + }; + } + function indentedJoin(xs, indent) { + if (xs.length === 0) { + return ""; + } + var lineJoiner = "\n" + indent.prev + indent.base; + return lineJoiner + $join.call(xs, "," + lineJoiner) + "\n" + indent.prev; + } + function arrObjKeys(obj, inspect) { + var isArr = isArray(obj); + var xs = []; + if (isArr) { + xs.length = obj.length; + for (var i5 = 0; i5 < obj.length; i5++) { + xs[i5] = has(obj, i5) ? inspect(obj[i5], obj) : ""; + } + } + var syms = typeof gOPS === "function" ? gOPS(obj) : []; + var symMap; + if (hasShammedSymbols) { + symMap = {}; + for (var k5 = 0; k5 < syms.length; k5++) { + symMap["$" + syms[k5]] = syms[k5]; + } + } + for (var key in obj) { + if (!has(obj, key)) { + continue; + } + if (isArr && String(Number(key)) === key && key < obj.length) { + continue; + } + if (hasShammedSymbols && symMap["$" + key] instanceof Symbol) { + continue; + } else if ($test.call(/[^\w$]/, key)) { + xs.push(inspect(key, obj) + ": " + inspect(obj[key], obj)); + } else { + xs.push(key + ": " + inspect(obj[key], obj)); + } + } + if (typeof gOPS === "function") { + for (var j5 = 0; j5 < syms.length; j5++) { + if (isEnumerable.call(obj, syms[j5])) { + xs.push("[" + inspect(syms[j5]) + "]: " + inspect(obj[syms[j5]], obj)); + } + } + } + return xs; + } + } +}); + +// node_modules/.pnpm/side-channel-list@1.0.1/node_modules/side-channel-list/index.js +var require_side_channel_list = __commonJS({ + "node_modules/.pnpm/side-channel-list@1.0.1/node_modules/side-channel-list/index.js"(exports, module) { + "use strict"; + var inspect = require_object_inspect(); + var $TypeError = require_type(); + var listGetNode = function(list2, key, isDelete) { + var prev = list2; + var curr; + for (; (curr = prev.next) != null; prev = curr) { + if (curr.key === key) { + prev.next = curr.next; + if (!isDelete) { + curr.next = /** @type {NonNullable} */ + list2.next; + list2.next = curr; + } + return curr; + } + } + }; + var listGet = function(objects, key) { + if (!objects) { + return void 0; + } + var node = listGetNode(objects, key); + return node && node.value; + }; + var listSet = function(objects, key, value) { + var node = listGetNode(objects, key); + if (node) { + node.value = value; + } else { + objects.next = /** @type {import('./list.d.ts').ListNode} */ + { + // eslint-disable-line no-param-reassign, no-extra-parens + key, + next: objects.next, + value + }; + } + }; + var listHas = function(objects, key) { + if (!objects) { + return false; + } + return !!listGetNode(objects, key); + }; + var listDelete = function(objects, key) { + if (objects) { + return listGetNode(objects, key, true); + } + }; + module.exports = function getSideChannelList() { + var $o; + var channel = { + assert: function(key) { + if (!channel.has(key)) { + throw new $TypeError("Side channel does not contain " + inspect(key)); + } + }, + "delete": function(key) { + var deletedNode = listDelete($o, key); + if (deletedNode && $o && !$o.next) { + $o = void 0; + } + return !!deletedNode; + }, + get: function(key) { + return listGet($o, key); + }, + has: function(key) { + return listHas($o, key); + }, + set: function(key, value) { + if (!$o) { + $o = { + next: void 0 + }; + } + listSet( + /** @type {NonNullable} */ + $o, + key, + value + ); + } + }; + return channel; + }; + } +}); + +// node_modules/.pnpm/es-object-atoms@1.1.1/node_modules/es-object-atoms/index.js +var require_es_object_atoms = __commonJS({ + "node_modules/.pnpm/es-object-atoms@1.1.1/node_modules/es-object-atoms/index.js"(exports, module) { + "use strict"; + module.exports = Object; + } +}); + +// node_modules/.pnpm/es-errors@1.3.0/node_modules/es-errors/index.js +var require_es_errors = __commonJS({ + "node_modules/.pnpm/es-errors@1.3.0/node_modules/es-errors/index.js"(exports, module) { + "use strict"; + module.exports = Error; + } +}); + +// node_modules/.pnpm/es-errors@1.3.0/node_modules/es-errors/eval.js +var require_eval = __commonJS({ + "node_modules/.pnpm/es-errors@1.3.0/node_modules/es-errors/eval.js"(exports, module) { + "use strict"; + module.exports = EvalError; + } +}); + +// node_modules/.pnpm/es-errors@1.3.0/node_modules/es-errors/range.js +var require_range = __commonJS({ + "node_modules/.pnpm/es-errors@1.3.0/node_modules/es-errors/range.js"(exports, module) { + "use strict"; + module.exports = RangeError; + } +}); + +// node_modules/.pnpm/es-errors@1.3.0/node_modules/es-errors/ref.js +var require_ref = __commonJS({ + "node_modules/.pnpm/es-errors@1.3.0/node_modules/es-errors/ref.js"(exports, module) { + "use strict"; + module.exports = ReferenceError; + } +}); + +// node_modules/.pnpm/es-errors@1.3.0/node_modules/es-errors/syntax.js +var require_syntax = __commonJS({ + "node_modules/.pnpm/es-errors@1.3.0/node_modules/es-errors/syntax.js"(exports, module) { + "use strict"; + module.exports = SyntaxError; + } +}); + +// node_modules/.pnpm/es-errors@1.3.0/node_modules/es-errors/uri.js +var require_uri = __commonJS({ + "node_modules/.pnpm/es-errors@1.3.0/node_modules/es-errors/uri.js"(exports, module) { + "use strict"; + module.exports = URIError; + } +}); + +// node_modules/.pnpm/math-intrinsics@1.1.0/node_modules/math-intrinsics/abs.js +var require_abs = __commonJS({ + "node_modules/.pnpm/math-intrinsics@1.1.0/node_modules/math-intrinsics/abs.js"(exports, module) { + "use strict"; + module.exports = Math.abs; + } +}); + +// node_modules/.pnpm/math-intrinsics@1.1.0/node_modules/math-intrinsics/floor.js +var require_floor = __commonJS({ + "node_modules/.pnpm/math-intrinsics@1.1.0/node_modules/math-intrinsics/floor.js"(exports, module) { + "use strict"; + module.exports = Math.floor; + } +}); + +// node_modules/.pnpm/math-intrinsics@1.1.0/node_modules/math-intrinsics/max.js +var require_max = __commonJS({ + "node_modules/.pnpm/math-intrinsics@1.1.0/node_modules/math-intrinsics/max.js"(exports, module) { + "use strict"; + module.exports = Math.max; + } +}); + +// node_modules/.pnpm/math-intrinsics@1.1.0/node_modules/math-intrinsics/min.js +var require_min = __commonJS({ + "node_modules/.pnpm/math-intrinsics@1.1.0/node_modules/math-intrinsics/min.js"(exports, module) { + "use strict"; + module.exports = Math.min; + } +}); + +// node_modules/.pnpm/math-intrinsics@1.1.0/node_modules/math-intrinsics/pow.js +var require_pow = __commonJS({ + "node_modules/.pnpm/math-intrinsics@1.1.0/node_modules/math-intrinsics/pow.js"(exports, module) { + "use strict"; + module.exports = Math.pow; + } +}); + +// node_modules/.pnpm/math-intrinsics@1.1.0/node_modules/math-intrinsics/round.js +var require_round = __commonJS({ + "node_modules/.pnpm/math-intrinsics@1.1.0/node_modules/math-intrinsics/round.js"(exports, module) { + "use strict"; + module.exports = Math.round; + } +}); + +// node_modules/.pnpm/math-intrinsics@1.1.0/node_modules/math-intrinsics/isNaN.js +var require_isNaN = __commonJS({ + "node_modules/.pnpm/math-intrinsics@1.1.0/node_modules/math-intrinsics/isNaN.js"(exports, module) { + "use strict"; + module.exports = Number.isNaN || function isNaN2(a5) { + return a5 !== a5; + }; + } +}); + +// node_modules/.pnpm/math-intrinsics@1.1.0/node_modules/math-intrinsics/sign.js +var require_sign = __commonJS({ + "node_modules/.pnpm/math-intrinsics@1.1.0/node_modules/math-intrinsics/sign.js"(exports, module) { + "use strict"; + var $isNaN = require_isNaN(); + module.exports = function sign2(number4) { + if ($isNaN(number4) || number4 === 0) { + return number4; + } + return number4 < 0 ? -1 : 1; + }; + } +}); + +// node_modules/.pnpm/gopd@1.2.0/node_modules/gopd/gOPD.js +var require_gOPD = __commonJS({ + "node_modules/.pnpm/gopd@1.2.0/node_modules/gopd/gOPD.js"(exports, module) { + "use strict"; + module.exports = Object.getOwnPropertyDescriptor; + } +}); + +// node_modules/.pnpm/gopd@1.2.0/node_modules/gopd/index.js +var require_gopd = __commonJS({ + "node_modules/.pnpm/gopd@1.2.0/node_modules/gopd/index.js"(exports, module) { + "use strict"; + var $gOPD = require_gOPD(); + if ($gOPD) { + try { + $gOPD([], "length"); + } catch (e5) { + $gOPD = null; + } + } + module.exports = $gOPD; + } +}); + +// node_modules/.pnpm/es-define-property@1.0.1/node_modules/es-define-property/index.js +var require_es_define_property = __commonJS({ + "node_modules/.pnpm/es-define-property@1.0.1/node_modules/es-define-property/index.js"(exports, module) { + "use strict"; + var $defineProperty = Object.defineProperty || false; + if ($defineProperty) { + try { + $defineProperty({}, "a", { value: 1 }); + } catch (e5) { + $defineProperty = false; + } + } + module.exports = $defineProperty; + } +}); + +// node_modules/.pnpm/has-symbols@1.1.0/node_modules/has-symbols/shams.js +var require_shams = __commonJS({ + "node_modules/.pnpm/has-symbols@1.1.0/node_modules/has-symbols/shams.js"(exports, module) { + "use strict"; + module.exports = function hasSymbols() { + if (typeof Symbol !== "function" || typeof Object.getOwnPropertySymbols !== "function") { + return false; + } + if (typeof Symbol.iterator === "symbol") { + return true; + } + var obj = {}; + var sym = /* @__PURE__ */ Symbol("test"); + var symObj = Object(sym); + if (typeof sym === "string") { + return false; + } + if (Object.prototype.toString.call(sym) !== "[object Symbol]") { + return false; + } + if (Object.prototype.toString.call(symObj) !== "[object Symbol]") { + return false; + } + var symVal = 42; + obj[sym] = symVal; + for (var _ in obj) { + return false; + } + if (typeof Object.keys === "function" && Object.keys(obj).length !== 0) { + return false; + } + if (typeof Object.getOwnPropertyNames === "function" && Object.getOwnPropertyNames(obj).length !== 0) { + return false; + } + var syms = Object.getOwnPropertySymbols(obj); + if (syms.length !== 1 || syms[0] !== sym) { + return false; + } + if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { + return false; + } + if (typeof Object.getOwnPropertyDescriptor === "function") { + var descriptor = ( + /** @type {PropertyDescriptor} */ + Object.getOwnPropertyDescriptor(obj, sym) + ); + if (descriptor.value !== symVal || descriptor.enumerable !== true) { + return false; + } + } + return true; + }; + } +}); + +// node_modules/.pnpm/has-symbols@1.1.0/node_modules/has-symbols/index.js +var require_has_symbols = __commonJS({ + "node_modules/.pnpm/has-symbols@1.1.0/node_modules/has-symbols/index.js"(exports, module) { + "use strict"; + var origSymbol = typeof Symbol !== "undefined" && Symbol; + var hasSymbolSham = require_shams(); + module.exports = function hasNativeSymbols() { + if (typeof origSymbol !== "function") { + return false; + } + if (typeof Symbol !== "function") { + return false; + } + if (typeof origSymbol("foo") !== "symbol") { + return false; + } + if (typeof /* @__PURE__ */ Symbol("bar") !== "symbol") { + return false; + } + return hasSymbolSham(); + }; + } +}); + +// node_modules/.pnpm/get-proto@1.0.1/node_modules/get-proto/Reflect.getPrototypeOf.js +var require_Reflect_getPrototypeOf = __commonJS({ + "node_modules/.pnpm/get-proto@1.0.1/node_modules/get-proto/Reflect.getPrototypeOf.js"(exports, module) { + "use strict"; + module.exports = typeof Reflect !== "undefined" && Reflect.getPrototypeOf || null; + } +}); + +// node_modules/.pnpm/get-proto@1.0.1/node_modules/get-proto/Object.getPrototypeOf.js +var require_Object_getPrototypeOf = __commonJS({ + "node_modules/.pnpm/get-proto@1.0.1/node_modules/get-proto/Object.getPrototypeOf.js"(exports, module) { + "use strict"; + var $Object = require_es_object_atoms(); + module.exports = $Object.getPrototypeOf || null; + } +}); + +// node_modules/.pnpm/function-bind@1.1.2/node_modules/function-bind/implementation.js +var require_implementation = __commonJS({ + "node_modules/.pnpm/function-bind@1.1.2/node_modules/function-bind/implementation.js"(exports, module) { + "use strict"; + var ERROR_MESSAGE = "Function.prototype.bind called on incompatible "; + var toStr = Object.prototype.toString; + var max = Math.max; + var funcType = "[object Function]"; + var concatty = function concatty2(a5, b6) { + var arr = []; + for (var i5 = 0; i5 < a5.length; i5 += 1) { + arr[i5] = a5[i5]; + } + for (var j5 = 0; j5 < b6.length; j5 += 1) { + arr[j5 + a5.length] = b6[j5]; + } + return arr; + }; + var slicy = function slicy2(arrLike, offset) { + var arr = []; + for (var i5 = offset || 0, j5 = 0; i5 < arrLike.length; i5 += 1, j5 += 1) { + arr[j5] = arrLike[i5]; + } + return arr; + }; + var joiny = function(arr, joiner) { + var str = ""; + for (var i5 = 0; i5 < arr.length; i5 += 1) { + str += arr[i5]; + if (i5 + 1 < arr.length) { + str += joiner; + } + } + return str; + }; + module.exports = function bind2(that) { + var target = this; + if (typeof target !== "function" || toStr.apply(target) !== funcType) { + throw new TypeError(ERROR_MESSAGE + target); + } + var args = slicy(arguments, 1); + var bound; + var binder = function() { + if (this instanceof bound) { + var result = target.apply( + this, + concatty(args, arguments) + ); + if (Object(result) === result) { + return result; + } + return this; + } + return target.apply( + that, + concatty(args, arguments) + ); + }; + var boundLength = max(0, target.length - args.length); + var boundArgs = []; + for (var i5 = 0; i5 < boundLength; i5++) { + boundArgs[i5] = "$" + i5; + } + bound = Function("binder", "return function (" + joiny(boundArgs, ",") + "){ return binder.apply(this,arguments); }")(binder); + if (target.prototype) { + var Empty = function Empty2() { + }; + Empty.prototype = target.prototype; + bound.prototype = new Empty(); + Empty.prototype = null; + } + return bound; + }; + } +}); + +// node_modules/.pnpm/function-bind@1.1.2/node_modules/function-bind/index.js +var require_function_bind = __commonJS({ + "node_modules/.pnpm/function-bind@1.1.2/node_modules/function-bind/index.js"(exports, module) { + "use strict"; + var implementation = require_implementation(); + module.exports = Function.prototype.bind || implementation; + } +}); + +// node_modules/.pnpm/call-bind-apply-helpers@1.0.2/node_modules/call-bind-apply-helpers/functionCall.js +var require_functionCall = __commonJS({ + "node_modules/.pnpm/call-bind-apply-helpers@1.0.2/node_modules/call-bind-apply-helpers/functionCall.js"(exports, module) { + "use strict"; + module.exports = Function.prototype.call; + } +}); + +// node_modules/.pnpm/call-bind-apply-helpers@1.0.2/node_modules/call-bind-apply-helpers/functionApply.js +var require_functionApply = __commonJS({ + "node_modules/.pnpm/call-bind-apply-helpers@1.0.2/node_modules/call-bind-apply-helpers/functionApply.js"(exports, module) { + "use strict"; + module.exports = Function.prototype.apply; + } +}); + +// node_modules/.pnpm/call-bind-apply-helpers@1.0.2/node_modules/call-bind-apply-helpers/reflectApply.js +var require_reflectApply = __commonJS({ + "node_modules/.pnpm/call-bind-apply-helpers@1.0.2/node_modules/call-bind-apply-helpers/reflectApply.js"(exports, module) { + "use strict"; + module.exports = typeof Reflect !== "undefined" && Reflect && Reflect.apply; + } +}); + +// node_modules/.pnpm/call-bind-apply-helpers@1.0.2/node_modules/call-bind-apply-helpers/actualApply.js +var require_actualApply = __commonJS({ + "node_modules/.pnpm/call-bind-apply-helpers@1.0.2/node_modules/call-bind-apply-helpers/actualApply.js"(exports, module) { + "use strict"; + var bind2 = require_function_bind(); + var $apply = require_functionApply(); + var $call = require_functionCall(); + var $reflectApply = require_reflectApply(); + module.exports = $reflectApply || bind2.call($call, $apply); + } +}); + +// node_modules/.pnpm/call-bind-apply-helpers@1.0.2/node_modules/call-bind-apply-helpers/index.js +var require_call_bind_apply_helpers = __commonJS({ + "node_modules/.pnpm/call-bind-apply-helpers@1.0.2/node_modules/call-bind-apply-helpers/index.js"(exports, module) { + "use strict"; + var bind2 = require_function_bind(); + var $TypeError = require_type(); + var $call = require_functionCall(); + var $actualApply = require_actualApply(); + module.exports = function callBindBasic(args) { + if (args.length < 1 || typeof args[0] !== "function") { + throw new $TypeError("a function is required"); + } + return $actualApply(bind2, $call, args); + }; + } +}); + +// node_modules/.pnpm/dunder-proto@1.0.1/node_modules/dunder-proto/get.js +var require_get = __commonJS({ + "node_modules/.pnpm/dunder-proto@1.0.1/node_modules/dunder-proto/get.js"(exports, module) { + "use strict"; + var callBind = require_call_bind_apply_helpers(); + var gOPD = require_gopd(); + var hasProtoAccessor; + try { + hasProtoAccessor = /** @type {{ __proto__?: typeof Array.prototype }} */ + [].__proto__ === Array.prototype; + } catch (e5) { + if (!e5 || typeof e5 !== "object" || !("code" in e5) || e5.code !== "ERR_PROTO_ACCESS") { + throw e5; + } + } + var desc3 = !!hasProtoAccessor && gOPD && gOPD( + Object.prototype, + /** @type {keyof typeof Object.prototype} */ + "__proto__" + ); + var $Object = Object; + var $getPrototypeOf = $Object.getPrototypeOf; + module.exports = desc3 && typeof desc3.get === "function" ? callBind([desc3.get]) : typeof $getPrototypeOf === "function" ? ( + /** @type {import('./get')} */ + function getDunder(value) { + return $getPrototypeOf(value == null ? value : $Object(value)); + } + ) : false; + } +}); + +// node_modules/.pnpm/get-proto@1.0.1/node_modules/get-proto/index.js +var require_get_proto = __commonJS({ + "node_modules/.pnpm/get-proto@1.0.1/node_modules/get-proto/index.js"(exports, module) { + "use strict"; + var reflectGetProto = require_Reflect_getPrototypeOf(); + var originalGetProto = require_Object_getPrototypeOf(); + var getDunderProto = require_get(); + module.exports = reflectGetProto ? function getProto(O) { + return reflectGetProto(O); + } : originalGetProto ? function getProto(O) { + if (!O || typeof O !== "object" && typeof O !== "function") { + throw new TypeError("getProto: not an object"); + } + return originalGetProto(O); + } : getDunderProto ? function getProto(O) { + return getDunderProto(O); + } : null; + } +}); + +// node_modules/.pnpm/hasown@2.0.2/node_modules/hasown/index.js +var require_hasown = __commonJS({ + "node_modules/.pnpm/hasown@2.0.2/node_modules/hasown/index.js"(exports, module) { + "use strict"; + var call = Function.prototype.call; + var $hasOwn = Object.prototype.hasOwnProperty; + var bind2 = require_function_bind(); + module.exports = bind2.call(call, $hasOwn); + } +}); + +// node_modules/.pnpm/get-intrinsic@1.3.0/node_modules/get-intrinsic/index.js +var require_get_intrinsic = __commonJS({ + "node_modules/.pnpm/get-intrinsic@1.3.0/node_modules/get-intrinsic/index.js"(exports, module) { + "use strict"; + var undefined2; + var $Object = require_es_object_atoms(); + var $Error = require_es_errors(); + var $EvalError = require_eval(); + var $RangeError = require_range(); + var $ReferenceError = require_ref(); + var $SyntaxError = require_syntax(); + var $TypeError = require_type(); + var $URIError = require_uri(); + var abs = require_abs(); + var floor = require_floor(); + var max = require_max(); + var min = require_min(); + var pow = require_pow(); + var round = require_round(); + var sign2 = require_sign(); + var $Function = Function; + var getEvalledConstructor = function(expressionSyntax) { + try { + return $Function('"use strict"; return (' + expressionSyntax + ").constructor;")(); + } catch (e5) { + } + }; + var $gOPD = require_gopd(); + var $defineProperty = require_es_define_property(); + var throwTypeError = function() { + throw new $TypeError(); + }; + var ThrowTypeError = $gOPD ? (function() { + try { + arguments.callee; + return throwTypeError; + } catch (calleeThrows) { + try { + return $gOPD(arguments, "callee").get; + } catch (gOPDthrows) { + return throwTypeError; + } + } + })() : throwTypeError; + var hasSymbols = require_has_symbols()(); + var getProto = require_get_proto(); + var $ObjectGPO = require_Object_getPrototypeOf(); + var $ReflectGPO = require_Reflect_getPrototypeOf(); + var $apply = require_functionApply(); + var $call = require_functionCall(); + var needsEval = {}; + var TypedArray = typeof Uint8Array === "undefined" || !getProto ? undefined2 : getProto(Uint8Array); + var INTRINSICS = { + __proto__: null, + "%AggregateError%": typeof AggregateError === "undefined" ? undefined2 : AggregateError, + "%Array%": Array, + "%ArrayBuffer%": typeof ArrayBuffer === "undefined" ? undefined2 : ArrayBuffer, + "%ArrayIteratorPrototype%": hasSymbols && getProto ? getProto([][Symbol.iterator]()) : undefined2, + "%AsyncFromSyncIteratorPrototype%": undefined2, + "%AsyncFunction%": needsEval, + "%AsyncGenerator%": needsEval, + "%AsyncGeneratorFunction%": needsEval, + "%AsyncIteratorPrototype%": needsEval, + "%Atomics%": typeof Atomics === "undefined" ? undefined2 : Atomics, + "%BigInt%": typeof BigInt === "undefined" ? undefined2 : BigInt, + "%BigInt64Array%": typeof BigInt64Array === "undefined" ? undefined2 : BigInt64Array, + "%BigUint64Array%": typeof BigUint64Array === "undefined" ? undefined2 : BigUint64Array, + "%Boolean%": Boolean, + "%DataView%": typeof DataView === "undefined" ? undefined2 : DataView, + "%Date%": Date, + "%decodeURI%": decodeURI, + "%decodeURIComponent%": decodeURIComponent, + "%encodeURI%": encodeURI, + "%encodeURIComponent%": encodeURIComponent, + "%Error%": $Error, + "%eval%": eval, + // eslint-disable-line no-eval + "%EvalError%": $EvalError, + "%Float16Array%": typeof Float16Array === "undefined" ? undefined2 : Float16Array, + "%Float32Array%": typeof Float32Array === "undefined" ? undefined2 : Float32Array, + "%Float64Array%": typeof Float64Array === "undefined" ? undefined2 : Float64Array, + "%FinalizationRegistry%": typeof FinalizationRegistry === "undefined" ? undefined2 : FinalizationRegistry, + "%Function%": $Function, + "%GeneratorFunction%": needsEval, + "%Int8Array%": typeof Int8Array === "undefined" ? undefined2 : Int8Array, + "%Int16Array%": typeof Int16Array === "undefined" ? undefined2 : Int16Array, + "%Int32Array%": typeof Int32Array === "undefined" ? undefined2 : Int32Array, + "%isFinite%": isFinite, + "%isNaN%": isNaN, + "%IteratorPrototype%": hasSymbols && getProto ? getProto(getProto([][Symbol.iterator]())) : undefined2, + "%JSON%": typeof JSON === "object" ? JSON : undefined2, + "%Map%": typeof Map === "undefined" ? undefined2 : Map, + "%MapIteratorPrototype%": typeof Map === "undefined" || !hasSymbols || !getProto ? undefined2 : getProto((/* @__PURE__ */ new Map())[Symbol.iterator]()), + "%Math%": Math, + "%Number%": Number, + "%Object%": $Object, + "%Object.getOwnPropertyDescriptor%": $gOPD, + "%parseFloat%": parseFloat, + "%parseInt%": parseInt, + "%Promise%": typeof Promise === "undefined" ? undefined2 : Promise, + "%Proxy%": typeof Proxy === "undefined" ? undefined2 : Proxy, + "%RangeError%": $RangeError, + "%ReferenceError%": $ReferenceError, + "%Reflect%": typeof Reflect === "undefined" ? undefined2 : Reflect, + "%RegExp%": RegExp, + "%Set%": typeof Set === "undefined" ? undefined2 : Set, + "%SetIteratorPrototype%": typeof Set === "undefined" || !hasSymbols || !getProto ? undefined2 : getProto((/* @__PURE__ */ new Set())[Symbol.iterator]()), + "%SharedArrayBuffer%": typeof SharedArrayBuffer === "undefined" ? undefined2 : SharedArrayBuffer, + "%String%": String, + "%StringIteratorPrototype%": hasSymbols && getProto ? getProto(""[Symbol.iterator]()) : undefined2, + "%Symbol%": hasSymbols ? Symbol : undefined2, + "%SyntaxError%": $SyntaxError, + "%ThrowTypeError%": ThrowTypeError, + "%TypedArray%": TypedArray, + "%TypeError%": $TypeError, + "%Uint8Array%": typeof Uint8Array === "undefined" ? undefined2 : Uint8Array, + "%Uint8ClampedArray%": typeof Uint8ClampedArray === "undefined" ? undefined2 : Uint8ClampedArray, + "%Uint16Array%": typeof Uint16Array === "undefined" ? undefined2 : Uint16Array, + "%Uint32Array%": typeof Uint32Array === "undefined" ? undefined2 : Uint32Array, + "%URIError%": $URIError, + "%WeakMap%": typeof WeakMap === "undefined" ? undefined2 : WeakMap, + "%WeakRef%": typeof WeakRef === "undefined" ? undefined2 : WeakRef, + "%WeakSet%": typeof WeakSet === "undefined" ? undefined2 : WeakSet, + "%Function.prototype.call%": $call, + "%Function.prototype.apply%": $apply, + "%Object.defineProperty%": $defineProperty, + "%Object.getPrototypeOf%": $ObjectGPO, + "%Math.abs%": abs, + "%Math.floor%": floor, + "%Math.max%": max, + "%Math.min%": min, + "%Math.pow%": pow, + "%Math.round%": round, + "%Math.sign%": sign2, + "%Reflect.getPrototypeOf%": $ReflectGPO + }; + if (getProto) { + try { + null.error; + } catch (e5) { + errorProto = getProto(getProto(e5)); + INTRINSICS["%Error.prototype%"] = errorProto; + } + } + var errorProto; + var doEval = function doEval2(name) { + var value; + if (name === "%AsyncFunction%") { + value = getEvalledConstructor("async function () {}"); + } else if (name === "%GeneratorFunction%") { + value = getEvalledConstructor("function* () {}"); + } else if (name === "%AsyncGeneratorFunction%") { + value = getEvalledConstructor("async function* () {}"); + } else if (name === "%AsyncGenerator%") { + var fn = doEval2("%AsyncGeneratorFunction%"); + if (fn) { + value = fn.prototype; + } + } else if (name === "%AsyncIteratorPrototype%") { + var gen = doEval2("%AsyncGenerator%"); + if (gen && getProto) { + value = getProto(gen.prototype); + } + } + INTRINSICS[name] = value; + return value; + }; + var LEGACY_ALIASES = { + __proto__: null, + "%ArrayBufferPrototype%": ["ArrayBuffer", "prototype"], + "%ArrayPrototype%": ["Array", "prototype"], + "%ArrayProto_entries%": ["Array", "prototype", "entries"], + "%ArrayProto_forEach%": ["Array", "prototype", "forEach"], + "%ArrayProto_keys%": ["Array", "prototype", "keys"], + "%ArrayProto_values%": ["Array", "prototype", "values"], + "%AsyncFunctionPrototype%": ["AsyncFunction", "prototype"], + "%AsyncGenerator%": ["AsyncGeneratorFunction", "prototype"], + "%AsyncGeneratorPrototype%": ["AsyncGeneratorFunction", "prototype", "prototype"], + "%BooleanPrototype%": ["Boolean", "prototype"], + "%DataViewPrototype%": ["DataView", "prototype"], + "%DatePrototype%": ["Date", "prototype"], + "%ErrorPrototype%": ["Error", "prototype"], + "%EvalErrorPrototype%": ["EvalError", "prototype"], + "%Float32ArrayPrototype%": ["Float32Array", "prototype"], + "%Float64ArrayPrototype%": ["Float64Array", "prototype"], + "%FunctionPrototype%": ["Function", "prototype"], + "%Generator%": ["GeneratorFunction", "prototype"], + "%GeneratorPrototype%": ["GeneratorFunction", "prototype", "prototype"], + "%Int8ArrayPrototype%": ["Int8Array", "prototype"], + "%Int16ArrayPrototype%": ["Int16Array", "prototype"], + "%Int32ArrayPrototype%": ["Int32Array", "prototype"], + "%JSONParse%": ["JSON", "parse"], + "%JSONStringify%": ["JSON", "stringify"], + "%MapPrototype%": ["Map", "prototype"], + "%NumberPrototype%": ["Number", "prototype"], + "%ObjectPrototype%": ["Object", "prototype"], + "%ObjProto_toString%": ["Object", "prototype", "toString"], + "%ObjProto_valueOf%": ["Object", "prototype", "valueOf"], + "%PromisePrototype%": ["Promise", "prototype"], + "%PromiseProto_then%": ["Promise", "prototype", "then"], + "%Promise_all%": ["Promise", "all"], + "%Promise_reject%": ["Promise", "reject"], + "%Promise_resolve%": ["Promise", "resolve"], + "%RangeErrorPrototype%": ["RangeError", "prototype"], + "%ReferenceErrorPrototype%": ["ReferenceError", "prototype"], + "%RegExpPrototype%": ["RegExp", "prototype"], + "%SetPrototype%": ["Set", "prototype"], + "%SharedArrayBufferPrototype%": ["SharedArrayBuffer", "prototype"], + "%StringPrototype%": ["String", "prototype"], + "%SymbolPrototype%": ["Symbol", "prototype"], + "%SyntaxErrorPrototype%": ["SyntaxError", "prototype"], + "%TypedArrayPrototype%": ["TypedArray", "prototype"], + "%TypeErrorPrototype%": ["TypeError", "prototype"], + "%Uint8ArrayPrototype%": ["Uint8Array", "prototype"], + "%Uint8ClampedArrayPrototype%": ["Uint8ClampedArray", "prototype"], + "%Uint16ArrayPrototype%": ["Uint16Array", "prototype"], + "%Uint32ArrayPrototype%": ["Uint32Array", "prototype"], + "%URIErrorPrototype%": ["URIError", "prototype"], + "%WeakMapPrototype%": ["WeakMap", "prototype"], + "%WeakSetPrototype%": ["WeakSet", "prototype"] + }; + var bind2 = require_function_bind(); + var hasOwn = require_hasown(); + var $concat = bind2.call($call, Array.prototype.concat); + var $spliceApply = bind2.call($apply, Array.prototype.splice); + var $replace = bind2.call($call, String.prototype.replace); + var $strSlice = bind2.call($call, String.prototype.slice); + var $exec = bind2.call($call, RegExp.prototype.exec); + var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g; + var reEscapeChar = /\\(\\)?/g; + var stringToPath = function stringToPath2(string4) { + var first = $strSlice(string4, 0, 1); + var last = $strSlice(string4, -1); + if (first === "%" && last !== "%") { + throw new $SyntaxError("invalid intrinsic syntax, expected closing `%`"); + } else if (last === "%" && first !== "%") { + throw new $SyntaxError("invalid intrinsic syntax, expected opening `%`"); + } + var result = []; + $replace(string4, rePropName, function(match, number4, quote, subString) { + result[result.length] = quote ? $replace(subString, reEscapeChar, "$1") : number4 || match; + }); + return result; + }; + var getBaseIntrinsic = function getBaseIntrinsic2(name, allowMissing) { + var intrinsicName = name; + var alias; + if (hasOwn(LEGACY_ALIASES, intrinsicName)) { + alias = LEGACY_ALIASES[intrinsicName]; + intrinsicName = "%" + alias[0] + "%"; + } + if (hasOwn(INTRINSICS, intrinsicName)) { + var value = INTRINSICS[intrinsicName]; + if (value === needsEval) { + value = doEval(intrinsicName); + } + if (typeof value === "undefined" && !allowMissing) { + throw new $TypeError("intrinsic " + name + " exists, but is not available. Please file an issue!"); + } + return { + alias, + name: intrinsicName, + value + }; + } + throw new $SyntaxError("intrinsic " + name + " does not exist!"); + }; + module.exports = function GetIntrinsic(name, allowMissing) { + if (typeof name !== "string" || name.length === 0) { + throw new $TypeError("intrinsic name must be a non-empty string"); + } + if (arguments.length > 1 && typeof allowMissing !== "boolean") { + throw new $TypeError('"allowMissing" argument must be a boolean'); + } + if ($exec(/^%?[^%]*%?$/, name) === null) { + throw new $SyntaxError("`%` may not be present anywhere but at the beginning and end of the intrinsic name"); + } + var parts = stringToPath(name); + var intrinsicBaseName = parts.length > 0 ? parts[0] : ""; + var intrinsic = getBaseIntrinsic("%" + intrinsicBaseName + "%", allowMissing); + var intrinsicRealName = intrinsic.name; + var value = intrinsic.value; + var skipFurtherCaching = false; + var alias = intrinsic.alias; + if (alias) { + intrinsicBaseName = alias[0]; + $spliceApply(parts, $concat([0, 1], alias)); + } + for (var i5 = 1, isOwn = true; i5 < parts.length; i5 += 1) { + var part = parts[i5]; + var first = $strSlice(part, 0, 1); + var last = $strSlice(part, -1); + if ((first === '"' || first === "'" || first === "`" || (last === '"' || last === "'" || last === "`")) && first !== last) { + throw new $SyntaxError("property names with quotes must have matching quotes"); + } + if (part === "constructor" || !isOwn) { + skipFurtherCaching = true; + } + intrinsicBaseName += "." + part; + intrinsicRealName = "%" + intrinsicBaseName + "%"; + if (hasOwn(INTRINSICS, intrinsicRealName)) { + value = INTRINSICS[intrinsicRealName]; + } else if (value != null) { + if (!(part in value)) { + if (!allowMissing) { + throw new $TypeError("base intrinsic for " + name + " exists, but the property is not available."); + } + return void undefined2; + } + if ($gOPD && i5 + 1 >= parts.length) { + var desc3 = $gOPD(value, part); + isOwn = !!desc3; + if (isOwn && "get" in desc3 && !("originalValue" in desc3.get)) { + value = desc3.get; + } else { + value = value[part]; + } + } else { + isOwn = hasOwn(value, part); + value = value[part]; + } + if (isOwn && !skipFurtherCaching) { + INTRINSICS[intrinsicRealName] = value; + } + } + } + return value; + }; + } +}); + +// node_modules/.pnpm/call-bound@1.0.4/node_modules/call-bound/index.js +var require_call_bound = __commonJS({ + "node_modules/.pnpm/call-bound@1.0.4/node_modules/call-bound/index.js"(exports, module) { + "use strict"; + var GetIntrinsic = require_get_intrinsic(); + var callBindBasic = require_call_bind_apply_helpers(); + var $indexOf = callBindBasic([GetIntrinsic("%String.prototype.indexOf%")]); + module.exports = function callBoundIntrinsic(name, allowMissing) { + var intrinsic = ( + /** @type {(this: unknown, ...args: unknown[]) => unknown} */ + GetIntrinsic(name, !!allowMissing) + ); + if (typeof intrinsic === "function" && $indexOf(name, ".prototype.") > -1) { + return callBindBasic( + /** @type {const} */ + [intrinsic] + ); + } + return intrinsic; + }; + } +}); + +// node_modules/.pnpm/side-channel-map@1.0.1/node_modules/side-channel-map/index.js +var require_side_channel_map = __commonJS({ + "node_modules/.pnpm/side-channel-map@1.0.1/node_modules/side-channel-map/index.js"(exports, module) { + "use strict"; + var GetIntrinsic = require_get_intrinsic(); + var callBound = require_call_bound(); + var inspect = require_object_inspect(); + var $TypeError = require_type(); + var $Map = GetIntrinsic("%Map%", true); + var $mapGet = callBound("Map.prototype.get", true); + var $mapSet = callBound("Map.prototype.set", true); + var $mapHas = callBound("Map.prototype.has", true); + var $mapDelete = callBound("Map.prototype.delete", true); + var $mapSize = callBound("Map.prototype.size", true); + module.exports = !!$Map && /** @type {Exclude} */ + function getSideChannelMap() { + var $m; + var channel = { + assert: function(key) { + if (!channel.has(key)) { + throw new $TypeError("Side channel does not contain " + inspect(key)); + } + }, + "delete": function(key) { + if ($m) { + var result = $mapDelete($m, key); + if ($mapSize($m) === 0) { + $m = void 0; + } + return result; + } + return false; + }, + get: function(key) { + if ($m) { + return $mapGet($m, key); + } + }, + has: function(key) { + if ($m) { + return $mapHas($m, key); + } + return false; + }, + set: function(key, value) { + if (!$m) { + $m = new $Map(); + } + $mapSet($m, key, value); + } + }; + return channel; + }; + } +}); + +// node_modules/.pnpm/side-channel-weakmap@1.0.2/node_modules/side-channel-weakmap/index.js +var require_side_channel_weakmap = __commonJS({ + "node_modules/.pnpm/side-channel-weakmap@1.0.2/node_modules/side-channel-weakmap/index.js"(exports, module) { + "use strict"; + var GetIntrinsic = require_get_intrinsic(); + var callBound = require_call_bound(); + var inspect = require_object_inspect(); + var getSideChannelMap = require_side_channel_map(); + var $TypeError = require_type(); + var $WeakMap = GetIntrinsic("%WeakMap%", true); + var $weakMapGet = callBound("WeakMap.prototype.get", true); + var $weakMapSet = callBound("WeakMap.prototype.set", true); + var $weakMapHas = callBound("WeakMap.prototype.has", true); + var $weakMapDelete = callBound("WeakMap.prototype.delete", true); + module.exports = $WeakMap ? ( + /** @type {Exclude} */ + function getSideChannelWeakMap() { + var $wm; + var $m; + var channel = { + assert: function(key) { + if (!channel.has(key)) { + throw new $TypeError("Side channel does not contain " + inspect(key)); + } + }, + "delete": function(key) { + if ($WeakMap && key && (typeof key === "object" || typeof key === "function")) { + if ($wm) { + return $weakMapDelete($wm, key); + } + } else if (getSideChannelMap) { + if ($m) { + return $m["delete"](key); + } + } + return false; + }, + get: function(key) { + if ($WeakMap && key && (typeof key === "object" || typeof key === "function")) { + if ($wm) { + return $weakMapGet($wm, key); + } + } + return $m && $m.get(key); + }, + has: function(key) { + if ($WeakMap && key && (typeof key === "object" || typeof key === "function")) { + if ($wm) { + return $weakMapHas($wm, key); + } + } + return !!$m && $m.has(key); + }, + set: function(key, value) { + if ($WeakMap && key && (typeof key === "object" || typeof key === "function")) { + if (!$wm) { + $wm = new $WeakMap(); + } + $weakMapSet($wm, key, value); + } else if (getSideChannelMap) { + if (!$m) { + $m = getSideChannelMap(); + } + $m.set(key, value); + } + } + }; + return channel; + } + ) : getSideChannelMap; + } +}); + +// node_modules/.pnpm/side-channel@1.1.0/node_modules/side-channel/index.js +var require_side_channel = __commonJS({ + "node_modules/.pnpm/side-channel@1.1.0/node_modules/side-channel/index.js"(exports, module) { + "use strict"; + var $TypeError = require_type(); + var inspect = require_object_inspect(); + var getSideChannelList = require_side_channel_list(); + var getSideChannelMap = require_side_channel_map(); + var getSideChannelWeakMap = require_side_channel_weakmap(); + var makeChannel = getSideChannelWeakMap || getSideChannelMap || getSideChannelList; + module.exports = function getSideChannel() { + var $channelData; + var channel = { + assert: function(key) { + if (!channel.has(key)) { + throw new $TypeError("Side channel does not contain " + inspect(key)); + } + }, + "delete": function(key) { + return !!$channelData && $channelData["delete"](key); + }, + get: function(key) { + return $channelData && $channelData.get(key); + }, + has: function(key) { + return !!$channelData && $channelData.has(key); + }, + set: function(key, value) { + if (!$channelData) { + $channelData = makeChannel(); + } + $channelData.set(key, value); + } + }; + return channel; + }; + } +}); + +// node_modules/.pnpm/qs@6.15.1/node_modules/qs/lib/formats.js +var require_formats = __commonJS({ + "node_modules/.pnpm/qs@6.15.1/node_modules/qs/lib/formats.js"(exports, module) { + "use strict"; + var replace = String.prototype.replace; + var percentTwenties = /%20/g; + var Format = { + RFC1738: "RFC1738", + RFC3986: "RFC3986" + }; + module.exports = { + "default": Format.RFC3986, + formatters: { + RFC1738: function(value) { + return replace.call(value, percentTwenties, "+"); + }, + RFC3986: function(value) { + return String(value); + } + }, + RFC1738: Format.RFC1738, + RFC3986: Format.RFC3986 + }; + } +}); + +// node_modules/.pnpm/qs@6.15.1/node_modules/qs/lib/utils.js +var require_utils2 = __commonJS({ + "node_modules/.pnpm/qs@6.15.1/node_modules/qs/lib/utils.js"(exports, module) { + "use strict"; + var formats = require_formats(); + var getSideChannel = require_side_channel(); + var has = Object.prototype.hasOwnProperty; + var isArray = Array.isArray; + var overflowChannel = getSideChannel(); + var markOverflow = function markOverflow2(obj, maxIndex) { + overflowChannel.set(obj, maxIndex); + return obj; + }; + var isOverflow = function isOverflow2(obj) { + return overflowChannel.has(obj); + }; + var getMaxIndex = function getMaxIndex2(obj) { + return overflowChannel.get(obj); + }; + var setMaxIndex = function setMaxIndex2(obj, maxIndex) { + overflowChannel.set(obj, maxIndex); + }; + var hexTable = (function() { + var array2 = []; + for (var i5 = 0; i5 < 256; ++i5) { + array2[array2.length] = "%" + ((i5 < 16 ? "0" : "") + i5.toString(16)).toUpperCase(); + } + return array2; + })(); + var compactQueue = function compactQueue2(queue) { + while (queue.length > 1) { + var item = queue.pop(); + var obj = item.obj[item.prop]; + if (isArray(obj)) { + var compacted = []; + for (var j5 = 0; j5 < obj.length; ++j5) { + if (typeof obj[j5] !== "undefined") { + compacted[compacted.length] = obj[j5]; + } + } + item.obj[item.prop] = compacted; + } + } + }; + var arrayToObject = function arrayToObject2(source, options) { + var obj = options && options.plainObjects ? { __proto__: null } : {}; + for (var i5 = 0; i5 < source.length; ++i5) { + if (typeof source[i5] !== "undefined") { + obj[i5] = source[i5]; + } + } + return obj; + }; + var merge2 = function merge3(target, source, options) { + if (!source) { + return target; + } + if (typeof source !== "object" && typeof source !== "function") { + if (isArray(target)) { + var nextIndex = target.length; + if (options && typeof options.arrayLimit === "number" && nextIndex > options.arrayLimit) { + return markOverflow(arrayToObject(target.concat(source), options), nextIndex); + } + target[nextIndex] = source; + } else if (target && typeof target === "object") { + if (isOverflow(target)) { + var newIndex = getMaxIndex(target) + 1; + target[newIndex] = source; + setMaxIndex(target, newIndex); + } else if (options && options.strictMerge) { + return [target, source]; + } else if (options && (options.plainObjects || options.allowPrototypes) || !has.call(Object.prototype, source)) { + target[source] = true; + } + } else { + return [target, source]; + } + return target; + } + if (!target || typeof target !== "object") { + if (isOverflow(source)) { + var sourceKeys = Object.keys(source); + var result = options && options.plainObjects ? { __proto__: null, 0: target } : { 0: target }; + for (var m5 = 0; m5 < sourceKeys.length; m5++) { + var oldKey = parseInt(sourceKeys[m5], 10); + result[oldKey + 1] = source[sourceKeys[m5]]; + } + return markOverflow(result, getMaxIndex(source) + 1); + } + var combined = [target].concat(source); + if (options && typeof options.arrayLimit === "number" && combined.length > options.arrayLimit) { + return markOverflow(arrayToObject(combined, options), combined.length - 1); + } + return combined; + } + var mergeTarget = target; + if (isArray(target) && !isArray(source)) { + mergeTarget = arrayToObject(target, options); + } + if (isArray(target) && isArray(source)) { + source.forEach(function(item, i5) { + if (has.call(target, i5)) { + var targetItem = target[i5]; + if (targetItem && typeof targetItem === "object" && item && typeof item === "object") { + target[i5] = merge3(targetItem, item, options); + } else { + target[target.length] = item; + } + } else { + target[i5] = item; + } + }); + return target; + } + return Object.keys(source).reduce(function(acc, key) { + var value = source[key]; + if (has.call(acc, key)) { + acc[key] = merge3(acc[key], value, options); + } else { + acc[key] = value; + } + if (isOverflow(source) && !isOverflow(acc)) { + markOverflow(acc, getMaxIndex(source)); + } + if (isOverflow(acc)) { + var keyNum = parseInt(key, 10); + if (String(keyNum) === key && keyNum >= 0 && keyNum > getMaxIndex(acc)) { + setMaxIndex(acc, keyNum); + } + } + return acc; + }, mergeTarget); + }; + var assign = function assignSingleSource(target, source) { + return Object.keys(source).reduce(function(acc, key) { + acc[key] = source[key]; + return acc; + }, target); + }; + var decode5 = function(str, defaultDecoder, charset) { + var strWithoutPlus = str.replace(/\+/g, " "); + if (charset === "iso-8859-1") { + return strWithoutPlus.replace(/%[0-9a-f]{2}/gi, unescape); + } + try { + return decodeURIComponent(strWithoutPlus); + } catch (e5) { + return strWithoutPlus; + } + }; + var limit = 1024; + var encode6 = function encode7(str, defaultEncoder, charset, kind, format2) { + if (str.length === 0) { + return str; + } + var string4 = str; + if (typeof str === "symbol") { + string4 = Symbol.prototype.toString.call(str); + } else if (typeof str !== "string") { + string4 = String(str); + } + if (charset === "iso-8859-1") { + return escape(string4).replace(/%u[0-9a-f]{4}/gi, function($0) { + return "%26%23" + parseInt($0.slice(2), 16) + "%3B"; + }); + } + var out = ""; + for (var j5 = 0; j5 < string4.length; j5 += limit) { + var segment = string4.length >= limit ? string4.slice(j5, j5 + limit) : string4; + var arr = []; + for (var i5 = 0; i5 < segment.length; ++i5) { + var c5 = segment.charCodeAt(i5); + if (c5 === 45 || c5 === 46 || c5 === 95 || c5 === 126 || c5 >= 48 && c5 <= 57 || c5 >= 65 && c5 <= 90 || c5 >= 97 && c5 <= 122 || format2 === formats.RFC1738 && (c5 === 40 || c5 === 41)) { + arr[arr.length] = segment.charAt(i5); + continue; + } + if (c5 < 128) { + arr[arr.length] = hexTable[c5]; + continue; + } + if (c5 < 2048) { + arr[arr.length] = hexTable[192 | c5 >> 6] + hexTable[128 | c5 & 63]; + continue; + } + if (c5 < 55296 || c5 >= 57344) { + arr[arr.length] = hexTable[224 | c5 >> 12] + hexTable[128 | c5 >> 6 & 63] + hexTable[128 | c5 & 63]; + continue; + } + i5 += 1; + c5 = 65536 + ((c5 & 1023) << 10 | segment.charCodeAt(i5) & 1023); + arr[arr.length] = hexTable[240 | c5 >> 18] + hexTable[128 | c5 >> 12 & 63] + hexTable[128 | c5 >> 6 & 63] + hexTable[128 | c5 & 63]; + } + out += arr.join(""); + } + return out; + }; + var compact = function compact2(value) { + var queue = [{ obj: { o: value }, prop: "o" }]; + var refs = []; + for (var i5 = 0; i5 < queue.length; ++i5) { + var item = queue[i5]; + var obj = item.obj[item.prop]; + var keys = Object.keys(obj); + for (var j5 = 0; j5 < keys.length; ++j5) { + var key = keys[j5]; + var val = obj[key]; + if (typeof val === "object" && val !== null && refs.indexOf(val) === -1) { + queue[queue.length] = { obj, prop: key }; + refs[refs.length] = val; + } + } + } + compactQueue(queue); + return value; + }; + var isRegExp = function isRegExp2(obj) { + return Object.prototype.toString.call(obj) === "[object RegExp]"; + }; + var isBuffer2 = function isBuffer3(obj) { + if (!obj || typeof obj !== "object") { + return false; + } + return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); + }; + var combine = function combine2(a5, b6, arrayLimit, plainObjects) { + if (isOverflow(a5)) { + var newIndex = getMaxIndex(a5) + 1; + a5[newIndex] = b6; + setMaxIndex(a5, newIndex); + return a5; + } + var result = [].concat(a5, b6); + if (result.length > arrayLimit) { + return markOverflow(arrayToObject(result, { plainObjects }), result.length - 1); + } + return result; + }; + var maybeMap = function maybeMap2(val, fn) { + if (isArray(val)) { + var mapped = []; + for (var i5 = 0; i5 < val.length; i5 += 1) { + mapped[mapped.length] = fn(val[i5]); + } + return mapped; + } + return fn(val); + }; + module.exports = { + arrayToObject, + assign, + combine, + compact, + decode: decode5, + encode: encode6, + isBuffer: isBuffer2, + isOverflow, + isRegExp, + markOverflow, + maybeMap, + merge: merge2 + }; + } +}); + +// node_modules/.pnpm/qs@6.15.1/node_modules/qs/lib/stringify.js +var require_stringify = __commonJS({ + "node_modules/.pnpm/qs@6.15.1/node_modules/qs/lib/stringify.js"(exports, module) { + "use strict"; + var getSideChannel = require_side_channel(); + var utils = require_utils2(); + var formats = require_formats(); + var has = Object.prototype.hasOwnProperty; + var arrayPrefixGenerators = { + brackets: function brackets(prefix) { + return prefix + "[]"; + }, + comma: "comma", + indices: function indices(prefix, key) { + return prefix + "[" + key + "]"; + }, + repeat: function repeat(prefix) { + return prefix; + } + }; + var isArray = Array.isArray; + var push = Array.prototype.push; + var pushToArray = function(arr, valueOrArray) { + push.apply(arr, isArray(valueOrArray) ? valueOrArray : [valueOrArray]); + }; + var toISO = Date.prototype.toISOString; + var defaultFormat = formats["default"]; + var defaults = { + addQueryPrefix: false, + allowDots: false, + allowEmptyArrays: false, + arrayFormat: "indices", + charset: "utf-8", + charsetSentinel: false, + commaRoundTrip: false, + delimiter: "&", + encode: true, + encodeDotInKeys: false, + encoder: utils.encode, + encodeValuesOnly: false, + filter: void 0, + format: defaultFormat, + formatter: formats.formatters[defaultFormat], + // deprecated + indices: false, + serializeDate: function serializeDate(date7) { + return toISO.call(date7); + }, + skipNulls: false, + strictNullHandling: false + }; + var isNonNullishPrimitive = function isNonNullishPrimitive2(v5) { + return typeof v5 === "string" || typeof v5 === "number" || typeof v5 === "boolean" || typeof v5 === "symbol" || typeof v5 === "bigint"; + }; + var sentinel = {}; + var stringify2 = function stringify3(object2, prefix, generateArrayPrefix, commaRoundTrip, allowEmptyArrays, strictNullHandling, skipNulls, encodeDotInKeys, encoder3, filter, sort, allowDots, serializeDate, format2, formatter, encodeValuesOnly, charset, sideChannel) { + var obj = object2; + var tmpSc = sideChannel; + var step = 0; + var findFlag = false; + while ((tmpSc = tmpSc.get(sentinel)) !== void 0 && !findFlag) { + var pos = tmpSc.get(object2); + step += 1; + if (typeof pos !== "undefined") { + if (pos === step) { + throw new RangeError("Cyclic object value"); + } else { + findFlag = true; + } + } + if (typeof tmpSc.get(sentinel) === "undefined") { + step = 0; + } + } + if (typeof filter === "function") { + obj = filter(prefix, obj); + } else if (obj instanceof Date) { + obj = serializeDate(obj); + } else if (generateArrayPrefix === "comma" && isArray(obj)) { + obj = utils.maybeMap(obj, function(value2) { + if (value2 instanceof Date) { + return serializeDate(value2); + } + return value2; + }); + } + if (obj === null) { + if (strictNullHandling) { + return encoder3 && !encodeValuesOnly ? encoder3(prefix, defaults.encoder, charset, "key", format2) : prefix; + } + obj = ""; + } + if (isNonNullishPrimitive(obj) || utils.isBuffer(obj)) { + if (encoder3) { + var keyValue = encodeValuesOnly ? prefix : encoder3(prefix, defaults.encoder, charset, "key", format2); + return [formatter(keyValue) + "=" + formatter(encoder3(obj, defaults.encoder, charset, "value", format2))]; + } + return [formatter(prefix) + "=" + formatter(String(obj))]; + } + var values2 = []; + if (typeof obj === "undefined") { + return values2; + } + var objKeys; + if (generateArrayPrefix === "comma" && isArray(obj)) { + if (encodeValuesOnly && encoder3) { + obj = utils.maybeMap(obj, encoder3); + } + objKeys = [{ value: obj.length > 0 ? obj.join(",") || null : void 0 }]; + } else if (isArray(filter)) { + objKeys = filter; + } else { + var keys = Object.keys(obj); + objKeys = sort ? keys.sort(sort) : keys; + } + var encodedPrefix = encodeDotInKeys ? String(prefix).replace(/\./g, "%2E") : String(prefix); + var adjustedPrefix = commaRoundTrip && isArray(obj) && obj.length === 1 ? encodedPrefix + "[]" : encodedPrefix; + if (allowEmptyArrays && isArray(obj) && obj.length === 0) { + return adjustedPrefix + "[]"; + } + for (var j5 = 0; j5 < objKeys.length; ++j5) { + var key = objKeys[j5]; + var value = typeof key === "object" && key && typeof key.value !== "undefined" ? key.value : obj[key]; + if (skipNulls && value === null) { + continue; + } + var encodedKey = allowDots && encodeDotInKeys ? String(key).replace(/\./g, "%2E") : String(key); + var keyPrefix = isArray(obj) ? typeof generateArrayPrefix === "function" ? generateArrayPrefix(adjustedPrefix, encodedKey) : adjustedPrefix : adjustedPrefix + (allowDots ? "." + encodedKey : "[" + encodedKey + "]"); + sideChannel.set(object2, step); + var valueSideChannel = getSideChannel(); + valueSideChannel.set(sentinel, sideChannel); + pushToArray(values2, stringify3( + value, + keyPrefix, + generateArrayPrefix, + commaRoundTrip, + allowEmptyArrays, + strictNullHandling, + skipNulls, + encodeDotInKeys, + generateArrayPrefix === "comma" && encodeValuesOnly && isArray(obj) ? null : encoder3, + filter, + sort, + allowDots, + serializeDate, + format2, + formatter, + encodeValuesOnly, + charset, + valueSideChannel + )); + } + return values2; + }; + var normalizeStringifyOptions = function normalizeStringifyOptions2(opts) { + if (!opts) { + return defaults; + } + if (typeof opts.allowEmptyArrays !== "undefined" && typeof opts.allowEmptyArrays !== "boolean") { + throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided"); + } + if (typeof opts.encodeDotInKeys !== "undefined" && typeof opts.encodeDotInKeys !== "boolean") { + throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided"); + } + if (opts.encoder !== null && typeof opts.encoder !== "undefined" && typeof opts.encoder !== "function") { + throw new TypeError("Encoder has to be a function."); + } + var charset = opts.charset || defaults.charset; + if (typeof opts.charset !== "undefined" && opts.charset !== "utf-8" && opts.charset !== "iso-8859-1") { + throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined"); + } + var format2 = formats["default"]; + if (typeof opts.format !== "undefined") { + if (!has.call(formats.formatters, opts.format)) { + throw new TypeError("Unknown format option provided."); + } + format2 = opts.format; + } + var formatter = formats.formatters[format2]; + var filter = defaults.filter; + if (typeof opts.filter === "function" || isArray(opts.filter)) { + filter = opts.filter; + } + var arrayFormat; + if (opts.arrayFormat in arrayPrefixGenerators) { + arrayFormat = opts.arrayFormat; + } else if ("indices" in opts) { + arrayFormat = opts.indices ? "indices" : "repeat"; + } else { + arrayFormat = defaults.arrayFormat; + } + if ("commaRoundTrip" in opts && typeof opts.commaRoundTrip !== "boolean") { + throw new TypeError("`commaRoundTrip` must be a boolean, or absent"); + } + var allowDots = typeof opts.allowDots === "undefined" ? opts.encodeDotInKeys === true ? true : defaults.allowDots : !!opts.allowDots; + return { + addQueryPrefix: typeof opts.addQueryPrefix === "boolean" ? opts.addQueryPrefix : defaults.addQueryPrefix, + allowDots, + allowEmptyArrays: typeof opts.allowEmptyArrays === "boolean" ? !!opts.allowEmptyArrays : defaults.allowEmptyArrays, + arrayFormat, + charset, + charsetSentinel: typeof opts.charsetSentinel === "boolean" ? opts.charsetSentinel : defaults.charsetSentinel, + commaRoundTrip: !!opts.commaRoundTrip, + delimiter: typeof opts.delimiter === "undefined" ? defaults.delimiter : opts.delimiter, + encode: typeof opts.encode === "boolean" ? opts.encode : defaults.encode, + encodeDotInKeys: typeof opts.encodeDotInKeys === "boolean" ? opts.encodeDotInKeys : defaults.encodeDotInKeys, + encoder: typeof opts.encoder === "function" ? opts.encoder : defaults.encoder, + encodeValuesOnly: typeof opts.encodeValuesOnly === "boolean" ? opts.encodeValuesOnly : defaults.encodeValuesOnly, + filter, + format: format2, + formatter, + serializeDate: typeof opts.serializeDate === "function" ? opts.serializeDate : defaults.serializeDate, + skipNulls: typeof opts.skipNulls === "boolean" ? opts.skipNulls : defaults.skipNulls, + sort: typeof opts.sort === "function" ? opts.sort : null, + strictNullHandling: typeof opts.strictNullHandling === "boolean" ? opts.strictNullHandling : defaults.strictNullHandling + }; + }; + module.exports = function(object2, opts) { + var obj = object2; + var options = normalizeStringifyOptions(opts); + var objKeys; + var filter; + if (typeof options.filter === "function") { + filter = options.filter; + obj = filter("", obj); + } else if (isArray(options.filter)) { + filter = options.filter; + objKeys = filter; + } + var keys = []; + if (typeof obj !== "object" || obj === null) { + return ""; + } + var generateArrayPrefix = arrayPrefixGenerators[options.arrayFormat]; + var commaRoundTrip = generateArrayPrefix === "comma" && options.commaRoundTrip; + if (!objKeys) { + objKeys = Object.keys(obj); + } + if (options.sort) { + objKeys.sort(options.sort); + } + var sideChannel = getSideChannel(); + for (var i5 = 0; i5 < objKeys.length; ++i5) { + var key = objKeys[i5]; + var value = obj[key]; + if (options.skipNulls && value === null) { + continue; + } + pushToArray(keys, stringify2( + value, + key, + generateArrayPrefix, + commaRoundTrip, + options.allowEmptyArrays, + options.strictNullHandling, + options.skipNulls, + options.encodeDotInKeys, + options.encode ? options.encoder : null, + options.filter, + options.sort, + options.allowDots, + options.serializeDate, + options.format, + options.formatter, + options.encodeValuesOnly, + options.charset, + sideChannel + )); + } + var joined = keys.join(options.delimiter); + var prefix = options.addQueryPrefix === true ? "?" : ""; + if (options.charsetSentinel) { + if (options.charset === "iso-8859-1") { + prefix += "utf8=%26%2310003%3B&"; + } else { + prefix += "utf8=%E2%9C%93&"; + } + } + return joined.length > 0 ? prefix + joined : ""; + }; + } +}); + +// node_modules/.pnpm/qs@6.15.1/node_modules/qs/lib/parse.js +var require_parse = __commonJS({ + "node_modules/.pnpm/qs@6.15.1/node_modules/qs/lib/parse.js"(exports, module) { + "use strict"; + var utils = require_utils2(); + var has = Object.prototype.hasOwnProperty; + var isArray = Array.isArray; + var defaults = { + allowDots: false, + allowEmptyArrays: false, + allowPrototypes: false, + allowSparse: false, + arrayLimit: 20, + charset: "utf-8", + charsetSentinel: false, + comma: false, + decodeDotInKeys: false, + decoder: utils.decode, + delimiter: "&", + depth: 5, + duplicates: "combine", + ignoreQueryPrefix: false, + interpretNumericEntities: false, + parameterLimit: 1e3, + parseArrays: true, + plainObjects: false, + strictDepth: false, + strictMerge: true, + strictNullHandling: false, + throwOnLimitExceeded: false + }; + var interpretNumericEntities = function(str) { + return str.replace(/&#(\d+);/g, function($0, numberStr) { + return String.fromCharCode(parseInt(numberStr, 10)); + }); + }; + var parseArrayValue = function(val, options, currentArrayLength) { + if (val && typeof val === "string" && options.comma && val.indexOf(",") > -1) { + return val.split(","); + } + if (options.throwOnLimitExceeded && currentArrayLength >= options.arrayLimit) { + throw new RangeError("Array limit exceeded. Only " + options.arrayLimit + " element" + (options.arrayLimit === 1 ? "" : "s") + " allowed in an array."); + } + return val; + }; + var isoSentinel = "utf8=%26%2310003%3B"; + var charsetSentinel = "utf8=%E2%9C%93"; + var parseValues = function parseQueryStringValues(str, options) { + var obj = { __proto__: null }; + var cleanStr = options.ignoreQueryPrefix ? str.replace(/^\?/, "") : str; + cleanStr = cleanStr.replace(/%5B/gi, "[").replace(/%5D/gi, "]"); + var limit = options.parameterLimit === Infinity ? void 0 : options.parameterLimit; + var parts = cleanStr.split( + options.delimiter, + options.throwOnLimitExceeded && typeof limit !== "undefined" ? limit + 1 : limit + ); + if (options.throwOnLimitExceeded && typeof limit !== "undefined" && parts.length > limit) { + throw new RangeError("Parameter limit exceeded. Only " + limit + " parameter" + (limit === 1 ? "" : "s") + " allowed."); + } + var skipIndex = -1; + var i5; + var charset = options.charset; + if (options.charsetSentinel) { + for (i5 = 0; i5 < parts.length; ++i5) { + if (parts[i5].indexOf("utf8=") === 0) { + if (parts[i5] === charsetSentinel) { + charset = "utf-8"; + } else if (parts[i5] === isoSentinel) { + charset = "iso-8859-1"; + } + skipIndex = i5; + i5 = parts.length; + } + } + } + for (i5 = 0; i5 < parts.length; ++i5) { + if (i5 === skipIndex) { + continue; + } + var part = parts[i5]; + var bracketEqualsPos = part.indexOf("]="); + var pos = bracketEqualsPos === -1 ? part.indexOf("=") : bracketEqualsPos + 1; + var key; + var val; + if (pos === -1) { + key = options.decoder(part, defaults.decoder, charset, "key"); + val = options.strictNullHandling ? null : ""; + } else { + key = options.decoder(part.slice(0, pos), defaults.decoder, charset, "key"); + if (key !== null) { + val = utils.maybeMap( + parseArrayValue( + part.slice(pos + 1), + options, + isArray(obj[key]) ? obj[key].length : 0 + ), + function(encodedVal) { + return options.decoder(encodedVal, defaults.decoder, charset, "value"); + } + ); + } + } + if (val && options.interpretNumericEntities && charset === "iso-8859-1") { + val = interpretNumericEntities(String(val)); + } + if (part.indexOf("[]=") > -1) { + val = isArray(val) ? [val] : val; + } + if (options.comma && isArray(val) && val.length > options.arrayLimit) { + if (options.throwOnLimitExceeded) { + throw new RangeError("Array limit exceeded. Only " + options.arrayLimit + " element" + (options.arrayLimit === 1 ? "" : "s") + " allowed in an array."); + } + val = utils.combine([], val, options.arrayLimit, options.plainObjects); + } + if (key !== null) { + var existing = has.call(obj, key); + if (existing && (options.duplicates === "combine" || part.indexOf("[]=") > -1)) { + obj[key] = utils.combine( + obj[key], + val, + options.arrayLimit, + options.plainObjects + ); + } else if (!existing || options.duplicates === "last") { + obj[key] = val; + } + } + } + return obj; + }; + var parseObject5 = function(chain, val, options, valuesParsed) { + var currentArrayLength = 0; + if (chain.length > 0 && chain[chain.length - 1] === "[]") { + var parentKey = chain.slice(0, -1).join(""); + currentArrayLength = Array.isArray(val) && val[parentKey] ? val[parentKey].length : 0; + } + var leaf = valuesParsed ? val : parseArrayValue(val, options, currentArrayLength); + for (var i5 = chain.length - 1; i5 >= 0; --i5) { + var obj; + var root = chain[i5]; + if (root === "[]" && options.parseArrays) { + if (utils.isOverflow(leaf)) { + obj = leaf; + } else { + obj = options.allowEmptyArrays && (leaf === "" || options.strictNullHandling && leaf === null) ? [] : utils.combine( + [], + leaf, + options.arrayLimit, + options.plainObjects + ); + } + } else { + obj = options.plainObjects ? { __proto__: null } : {}; + var cleanRoot = root.charAt(0) === "[" && root.charAt(root.length - 1) === "]" ? root.slice(1, -1) : root; + var decodedRoot = options.decodeDotInKeys ? cleanRoot.replace(/%2E/g, ".") : cleanRoot; + var index2 = parseInt(decodedRoot, 10); + var isValidArrayIndex = !isNaN(index2) && root !== decodedRoot && String(index2) === decodedRoot && index2 >= 0 && options.parseArrays; + if (!options.parseArrays && decodedRoot === "") { + obj = { 0: leaf }; + } else if (isValidArrayIndex && index2 < options.arrayLimit) { + obj = []; + obj[index2] = leaf; + } else if (isValidArrayIndex && options.throwOnLimitExceeded) { + throw new RangeError("Array limit exceeded. Only " + options.arrayLimit + " element" + (options.arrayLimit === 1 ? "" : "s") + " allowed in an array."); + } else if (isValidArrayIndex) { + obj[index2] = leaf; + utils.markOverflow(obj, index2); + } else if (decodedRoot !== "__proto__") { + obj[decodedRoot] = leaf; + } + } + leaf = obj; + } + return leaf; + }; + var splitKeyIntoSegments = function splitKeyIntoSegments2(givenKey, options) { + var key = options.allowDots ? givenKey.replace(/\.([^.[]+)/g, "[$1]") : givenKey; + if (options.depth <= 0) { + if (!options.plainObjects && has.call(Object.prototype, key)) { + if (!options.allowPrototypes) { + return; + } + } + return [key]; + } + var brackets = /(\[[^[\]]*])/; + var child = /(\[[^[\]]*])/g; + var segment = brackets.exec(key); + var parent = segment ? key.slice(0, segment.index) : key; + var keys = []; + if (parent) { + if (!options.plainObjects && has.call(Object.prototype, parent)) { + if (!options.allowPrototypes) { + return; + } + } + keys[keys.length] = parent; + } + var i5 = 0; + while ((segment = child.exec(key)) !== null && i5 < options.depth) { + i5 += 1; + var segmentContent = segment[1].slice(1, -1); + if (!options.plainObjects && has.call(Object.prototype, segmentContent)) { + if (!options.allowPrototypes) { + return; + } + } + keys[keys.length] = segment[1]; + } + if (segment) { + if (options.strictDepth === true) { + throw new RangeError("Input depth exceeded depth option of " + options.depth + " and strictDepth is true"); + } + keys[keys.length] = "[" + key.slice(segment.index) + "]"; + } + return keys; + }; + var parseKeys = function parseQueryStringKeys(givenKey, val, options, valuesParsed) { + if (!givenKey) { + return; + } + var keys = splitKeyIntoSegments(givenKey, options); + if (!keys) { + return; + } + return parseObject5(keys, val, options, valuesParsed); + }; + var normalizeParseOptions = function normalizeParseOptions2(opts) { + if (!opts) { + return defaults; + } + if (typeof opts.allowEmptyArrays !== "undefined" && typeof opts.allowEmptyArrays !== "boolean") { + throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided"); + } + if (typeof opts.decodeDotInKeys !== "undefined" && typeof opts.decodeDotInKeys !== "boolean") { + throw new TypeError("`decodeDotInKeys` option can only be `true` or `false`, when provided"); + } + if (opts.decoder !== null && typeof opts.decoder !== "undefined" && typeof opts.decoder !== "function") { + throw new TypeError("Decoder has to be a function."); + } + if (typeof opts.charset !== "undefined" && opts.charset !== "utf-8" && opts.charset !== "iso-8859-1") { + throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined"); + } + if (typeof opts.throwOnLimitExceeded !== "undefined" && typeof opts.throwOnLimitExceeded !== "boolean") { + throw new TypeError("`throwOnLimitExceeded` option must be a boolean"); + } + var charset = typeof opts.charset === "undefined" ? defaults.charset : opts.charset; + var duplicates = typeof opts.duplicates === "undefined" ? defaults.duplicates : opts.duplicates; + if (duplicates !== "combine" && duplicates !== "first" && duplicates !== "last") { + throw new TypeError("The duplicates option must be either combine, first, or last"); + } + var allowDots = typeof opts.allowDots === "undefined" ? opts.decodeDotInKeys === true ? true : defaults.allowDots : !!opts.allowDots; + return { + allowDots, + allowEmptyArrays: typeof opts.allowEmptyArrays === "boolean" ? !!opts.allowEmptyArrays : defaults.allowEmptyArrays, + allowPrototypes: typeof opts.allowPrototypes === "boolean" ? opts.allowPrototypes : defaults.allowPrototypes, + allowSparse: typeof opts.allowSparse === "boolean" ? opts.allowSparse : defaults.allowSparse, + arrayLimit: typeof opts.arrayLimit === "number" ? opts.arrayLimit : defaults.arrayLimit, + charset, + charsetSentinel: typeof opts.charsetSentinel === "boolean" ? opts.charsetSentinel : defaults.charsetSentinel, + comma: typeof opts.comma === "boolean" ? opts.comma : defaults.comma, + decodeDotInKeys: typeof opts.decodeDotInKeys === "boolean" ? opts.decodeDotInKeys : defaults.decodeDotInKeys, + decoder: typeof opts.decoder === "function" ? opts.decoder : defaults.decoder, + delimiter: typeof opts.delimiter === "string" || utils.isRegExp(opts.delimiter) ? opts.delimiter : defaults.delimiter, + // eslint-disable-next-line no-implicit-coercion, no-extra-parens + depth: typeof opts.depth === "number" || opts.depth === false ? +opts.depth : defaults.depth, + duplicates, + ignoreQueryPrefix: opts.ignoreQueryPrefix === true, + interpretNumericEntities: typeof opts.interpretNumericEntities === "boolean" ? opts.interpretNumericEntities : defaults.interpretNumericEntities, + parameterLimit: typeof opts.parameterLimit === "number" ? opts.parameterLimit : defaults.parameterLimit, + parseArrays: opts.parseArrays !== false, + plainObjects: typeof opts.plainObjects === "boolean" ? opts.plainObjects : defaults.plainObjects, + strictDepth: typeof opts.strictDepth === "boolean" ? !!opts.strictDepth : defaults.strictDepth, + strictMerge: typeof opts.strictMerge === "boolean" ? !!opts.strictMerge : defaults.strictMerge, + strictNullHandling: typeof opts.strictNullHandling === "boolean" ? opts.strictNullHandling : defaults.strictNullHandling, + throwOnLimitExceeded: typeof opts.throwOnLimitExceeded === "boolean" ? opts.throwOnLimitExceeded : false + }; + }; + module.exports = function(str, opts) { + var options = normalizeParseOptions(opts); + if (str === "" || str === null || typeof str === "undefined") { + return options.plainObjects ? { __proto__: null } : {}; + } + var tempObj = typeof str === "string" ? parseValues(str, options) : str; + var obj = options.plainObjects ? { __proto__: null } : {}; + var keys = Object.keys(tempObj); + for (var i5 = 0; i5 < keys.length; ++i5) { + var key = keys[i5]; + var newObj = parseKeys(key, tempObj[key], options, typeof str === "string"); + obj = utils.merge(obj, newObj, options); + } + if (options.allowSparse === true) { + return obj; + } + return utils.compact(obj); + }; + } +}); + +// node_modules/.pnpm/qs@6.15.1/node_modules/qs/lib/index.js +var require_lib2 = __commonJS({ + "node_modules/.pnpm/qs@6.15.1/node_modules/qs/lib/index.js"(exports, module) { + "use strict"; + var stringify2 = require_stringify(); + var parse5 = require_parse(); + var formats = require_formats(); + module.exports = { + formats, + parse: parse5, + stringify: stringify2 + }; + } +}); + +// node_modules/.pnpm/body-parser@2.2.2/node_modules/body-parser/lib/types/urlencoded.js +var require_urlencoded = __commonJS({ + "node_modules/.pnpm/body-parser@2.2.2/node_modules/body-parser/lib/types/urlencoded.js"(exports, module) { + "use strict"; + var createError = require_http_errors(); + var debug = require_src()("body-parser:urlencoded"); + var read = require_read(); + var qs = require_lib2(); + var { normalizeOptions } = require_utils(); + module.exports = urlencoded; + function urlencoded(options) { + const normalizedOptions = normalizeOptions(options, "application/x-www-form-urlencoded"); + if (normalizedOptions.defaultCharset !== "utf-8" && normalizedOptions.defaultCharset !== "iso-8859-1") { + throw new TypeError("option defaultCharset must be either utf-8 or iso-8859-1"); + } + var queryparse = createQueryParser(options); + function parse5(body, encoding) { + return body.length ? queryparse(body, encoding) : {}; + } + const readOptions = { + ...normalizedOptions, + // assert charset + isValidCharset: (charset) => charset === "utf-8" || charset === "iso-8859-1" + }; + return function urlencodedParser(req, res, next) { + read(req, res, next, parse5, debug, readOptions); + }; + } + function createQueryParser(options) { + var extended = Boolean(options?.extended); + var parameterLimit = options?.parameterLimit !== void 0 ? options?.parameterLimit : 1e3; + var charsetSentinel = options?.charsetSentinel; + var interpretNumericEntities = options?.interpretNumericEntities; + var depth = extended ? options?.depth !== void 0 ? options?.depth : 32 : 0; + if (isNaN(parameterLimit) || parameterLimit < 1) { + throw new TypeError("option parameterLimit must be a positive number"); + } + if (isNaN(depth) || depth < 0) { + throw new TypeError("option depth must be a zero or a positive number"); + } + if (isFinite(parameterLimit)) { + parameterLimit = parameterLimit | 0; + } + return function queryparse(body, encoding) { + var paramCount = parameterCount(body, parameterLimit); + if (paramCount === void 0) { + debug("too many parameters"); + throw createError(413, "too many parameters", { + type: "parameters.too.many" + }); + } + var arrayLimit = extended ? Math.max(100, paramCount) : paramCount; + debug("parse " + (extended ? "extended " : "") + "urlencoding"); + try { + return qs.parse(body, { + allowPrototypes: true, + arrayLimit, + depth, + charsetSentinel, + interpretNumericEntities, + charset: encoding, + parameterLimit, + strictDepth: true + }); + } catch (err) { + if (err instanceof RangeError) { + throw createError(400, "The input exceeded the depth", { + type: "querystring.parse.rangeError" + }); + } else { + throw err; + } + } + }; + } + function parameterCount(body, limit) { + let count2 = 0; + let index2 = -1; + do { + count2++; + if (count2 > limit) return void 0; + index2 = body.indexOf("&", index2 + 1); + } while (index2 !== -1); + return count2; + } + } +}); + +// node_modules/.pnpm/body-parser@2.2.2/node_modules/body-parser/index.js +var require_body_parser = __commonJS({ + "node_modules/.pnpm/body-parser@2.2.2/node_modules/body-parser/index.js"(exports, module) { + "use strict"; + exports = module.exports = bodyParser; + Object.defineProperty(exports, "json", { + configurable: true, + enumerable: true, + get: () => require_json() + }); + Object.defineProperty(exports, "raw", { + configurable: true, + enumerable: true, + get: () => require_raw() + }); + Object.defineProperty(exports, "text", { + configurable: true, + enumerable: true, + get: () => require_text() + }); + Object.defineProperty(exports, "urlencoded", { + configurable: true, + enumerable: true, + get: () => require_urlencoded() + }); + function bodyParser() { + throw new Error("The bodyParser() generic has been split into individual middleware to use instead."); + } + } +}); + +// node_modules/.pnpm/merge-descriptors@2.0.0/node_modules/merge-descriptors/index.js +var require_merge_descriptors = __commonJS({ + "node_modules/.pnpm/merge-descriptors@2.0.0/node_modules/merge-descriptors/index.js"(exports, module) { + "use strict"; + function mergeDescriptors(destination, source, overwrite = true) { + if (!destination) { + throw new TypeError("The `destination` argument is required."); + } + if (!source) { + throw new TypeError("The `source` argument is required."); + } + for (const name of Object.getOwnPropertyNames(source)) { + if (!overwrite && Object.hasOwn(destination, name)) { + continue; + } + const descriptor = Object.getOwnPropertyDescriptor(source, name); + Object.defineProperty(destination, name, descriptor); + } + return destination; + } + module.exports = mergeDescriptors; + } +}); + +// node_modules/.pnpm/encodeurl@2.0.0/node_modules/encodeurl/index.js +var require_encodeurl = __commonJS({ + "node_modules/.pnpm/encodeurl@2.0.0/node_modules/encodeurl/index.js"(exports, module) { + "use strict"; + module.exports = encodeUrl; + var ENCODE_CHARS_REGEXP = /(?:[^\x21\x23-\x3B\x3D\x3F-\x5F\x61-\x7A\x7C\x7E]|%(?:[^0-9A-Fa-f]|[0-9A-Fa-f][^0-9A-Fa-f]|$))+/g; + var UNMATCHED_SURROGATE_PAIR_REGEXP = /(^|[^\uD800-\uDBFF])[\uDC00-\uDFFF]|[\uD800-\uDBFF]([^\uDC00-\uDFFF]|$)/g; + var UNMATCHED_SURROGATE_PAIR_REPLACE = "$1\uFFFD$2"; + function encodeUrl(url2) { + return String(url2).replace(UNMATCHED_SURROGATE_PAIR_REGEXP, UNMATCHED_SURROGATE_PAIR_REPLACE).replace(ENCODE_CHARS_REGEXP, encodeURI); + } + } +}); + +// node_modules/.pnpm/escape-html@1.0.3/node_modules/escape-html/index.js +var require_escape_html = __commonJS({ + "node_modules/.pnpm/escape-html@1.0.3/node_modules/escape-html/index.js"(exports, module) { + "use strict"; + var matchHtmlRegExp = /["'&<>]/; + module.exports = escapeHtml; + function escapeHtml(string4) { + var str = "" + string4; + var match = matchHtmlRegExp.exec(str); + if (!match) { + return str; + } + var escape3; + var html3 = ""; + var index2 = 0; + var lastIndex = 0; + for (index2 = match.index; index2 < str.length; index2++) { + switch (str.charCodeAt(index2)) { + case 34: + escape3 = """; + break; + case 38: + escape3 = "&"; + break; + case 39: + escape3 = "'"; + break; + case 60: + escape3 = "<"; + break; + case 62: + escape3 = ">"; + break; + default: + continue; + } + if (lastIndex !== index2) { + html3 += str.substring(lastIndex, index2); + } + lastIndex = index2 + 1; + html3 += escape3; + } + return lastIndex !== index2 ? html3 + str.substring(lastIndex, index2) : html3; + } + } +}); + +// node_modules/.pnpm/parseurl@1.3.3/node_modules/parseurl/index.js +var require_parseurl = __commonJS({ + "node_modules/.pnpm/parseurl@1.3.3/node_modules/parseurl/index.js"(exports, module) { + "use strict"; + var url2 = __require("url"); + var parse5 = url2.parse; + var Url = url2.Url; + module.exports = parseurl; + module.exports.original = originalurl; + function parseurl(req) { + var url3 = req.url; + if (url3 === void 0) { + return void 0; + } + var parsed = req._parsedUrl; + if (fresh(url3, parsed)) { + return parsed; + } + parsed = fastparse(url3); + parsed._raw = url3; + return req._parsedUrl = parsed; + } + function originalurl(req) { + var url3 = req.originalUrl; + if (typeof url3 !== "string") { + return parseurl(req); + } + var parsed = req._parsedOriginalUrl; + if (fresh(url3, parsed)) { + return parsed; + } + parsed = fastparse(url3); + parsed._raw = url3; + return req._parsedOriginalUrl = parsed; + } + function fastparse(str) { + if (typeof str !== "string" || str.charCodeAt(0) !== 47) { + return parse5(str); + } + var pathname = str; + var query = null; + var search = null; + for (var i5 = 1; i5 < str.length; i5++) { + switch (str.charCodeAt(i5)) { + case 63: + if (search === null) { + pathname = str.substring(0, i5); + query = str.substring(i5 + 1); + search = str.substring(i5); + } + break; + case 9: + /* \t */ + case 10: + /* \n */ + case 12: + /* \f */ + case 13: + /* \r */ + case 32: + /* */ + case 35: + /* # */ + case 160: + case 65279: + return parse5(str); + } + } + var url3 = Url !== void 0 ? new Url() : {}; + url3.path = str; + url3.href = str; + url3.pathname = pathname; + if (search !== null) { + url3.query = query; + url3.search = search; + } + return url3; + } + function fresh(url3, parsedUrl) { + return typeof parsedUrl === "object" && parsedUrl !== null && (Url === void 0 || parsedUrl instanceof Url) && parsedUrl._raw === url3; + } + } +}); + +// node_modules/.pnpm/finalhandler@2.1.1/node_modules/finalhandler/index.js +var require_finalhandler = __commonJS({ + "node_modules/.pnpm/finalhandler@2.1.1/node_modules/finalhandler/index.js"(exports, module) { + "use strict"; + var debug = require_src()("finalhandler"); + var encodeUrl = require_encodeurl(); + var escapeHtml = require_escape_html(); + var onFinished = require_on_finished(); + var parseUrl7 = require_parseurl(); + var statuses = require_statuses(); + var isFinished = onFinished.isFinished; + function createHtmlDocument(message2) { + var body = escapeHtml(message2).replaceAll("\n", "
").replaceAll(" ", "  "); + return '\n\n\n\nError\n\n\n
' + body + "
\n\n\n"; + } + module.exports = finalhandler; + function finalhandler(req, res, options) { + var opts = options || {}; + var env2 = opts.env || "production"; + var onerror = opts.onerror; + return function(err) { + var headers; + var msg; + var status; + if (!err && res.headersSent) { + debug("cannot 404 after headers sent"); + return; + } + if (err) { + status = getErrorStatusCode(err); + if (status === void 0) { + status = getResponseStatusCode(res); + } else { + headers = getErrorHeaders(err); + } + msg = getErrorMessage(err, status, env2); + } else { + status = 404; + msg = "Cannot " + req.method + " " + encodeUrl(getResourceName(req)); + } + debug("default %s", status); + if (err && onerror) { + setImmediate(onerror, err, req, res); + } + if (res.headersSent) { + debug("cannot %d after headers sent", status); + if (req.socket) { + req.socket.destroy(); + } + return; + } + send(req, res, status, headers, msg); + }; + } + function getErrorHeaders(err) { + if (!err.headers || typeof err.headers !== "object") { + return void 0; + } + return { ...err.headers }; + } + function getErrorMessage(err, status, env2) { + var msg; + if (env2 !== "production") { + msg = err.stack; + if (!msg && typeof err.toString === "function") { + msg = err.toString(); + } + } + return msg || statuses.message[status]; + } + function getErrorStatusCode(err) { + if (typeof err.status === "number" && err.status >= 400 && err.status < 600) { + return err.status; + } + if (typeof err.statusCode === "number" && err.statusCode >= 400 && err.statusCode < 600) { + return err.statusCode; + } + return void 0; + } + function getResourceName(req) { + try { + return parseUrl7.original(req).pathname; + } catch (e5) { + return "resource"; + } + } + function getResponseStatusCode(res) { + var status = res.statusCode; + if (typeof status !== "number" || status < 400 || status > 599) { + status = 500; + } + return status; + } + function send(req, res, status, headers, message2) { + function write() { + var body = createHtmlDocument(message2); + res.statusCode = status; + if (req.httpVersionMajor < 2) { + res.statusMessage = statuses.message[status]; + } + res.removeHeader("Content-Encoding"); + res.removeHeader("Content-Language"); + res.removeHeader("Content-Range"); + for (const [key, value] of Object.entries(headers ?? {})) { + res.setHeader(key, value); + } + res.setHeader("Content-Security-Policy", "default-src 'none'"); + res.setHeader("X-Content-Type-Options", "nosniff"); + res.setHeader("Content-Type", "text/html; charset=utf-8"); + res.setHeader("Content-Length", Buffer.byteLength(body, "utf8")); + if (req.method === "HEAD") { + res.end(); + return; + } + res.end(body, "utf8"); + } + if (isFinished(req)) { + write(); + return; + } + req.unpipe(); + onFinished(req, write); + req.resume(); + } + } +}); + +// node_modules/.pnpm/express@5.2.1/node_modules/express/lib/view.js +var require_view = __commonJS({ + "node_modules/.pnpm/express@5.2.1/node_modules/express/lib/view.js"(exports, module) { + "use strict"; + var debug = require_src()("express:view"); + var path53 = __require("node:path"); + var fs41 = __require("node:fs"); + var dirname3 = path53.dirname; + var basename3 = path53.basename; + var extname2 = path53.extname; + var join4 = path53.join; + var resolve4 = path53.resolve; + module.exports = View2; + function View2(name, options) { + var opts = options || {}; + this.defaultEngine = opts.defaultEngine; + this.ext = extname2(name); + this.name = name; + this.root = opts.root; + if (!this.ext && !this.defaultEngine) { + throw new Error("No default engine was specified and no extension was provided."); + } + var fileName = name; + if (!this.ext) { + this.ext = this.defaultEngine[0] !== "." ? "." + this.defaultEngine : this.defaultEngine; + fileName += this.ext; + } + if (!opts.engines[this.ext]) { + var mod = this.ext.slice(1); + debug('require "%s"', mod); + var fn = __require(mod).__express; + if (typeof fn !== "function") { + throw new Error('Module "' + mod + '" does not provide a view engine.'); + } + opts.engines[this.ext] = fn; + } + this.engine = opts.engines[this.ext]; + this.path = this.lookup(fileName); + } + View2.prototype.lookup = function lookup(name) { + var path54; + var roots = [].concat(this.root); + debug('lookup "%s"', name); + for (var i5 = 0; i5 < roots.length && !path54; i5++) { + var root = roots[i5]; + var loc = resolve4(root, name); + var dir = dirname3(loc); + var file2 = basename3(loc); + path54 = this.resolve(dir, file2); + } + return path54; + }; + View2.prototype.render = function render(options, callback) { + var sync = true; + debug('render "%s"', this.path); + this.engine(this.path, options, function onRender() { + if (!sync) { + return callback.apply(this, arguments); + } + var args = new Array(arguments.length); + var cntx = this; + for (var i5 = 0; i5 < arguments.length; i5++) { + args[i5] = arguments[i5]; + } + return process.nextTick(function renderTick() { + return callback.apply(cntx, args); + }); + }); + sync = false; + }; + View2.prototype.resolve = function resolve5(dir, file2) { + var ext = this.ext; + var path54 = join4(dir, file2); + var stat5 = tryStat(path54); + if (stat5 && stat5.isFile()) { + return path54; + } + path54 = join4(dir, basename3(file2, ext), "index" + ext); + stat5 = tryStat(path54); + if (stat5 && stat5.isFile()) { + return path54; + } + }; + function tryStat(path54) { + debug('stat "%s"', path54); + try { + return fs41.statSync(path54); + } catch (e5) { + return void 0; + } + } + } +}); + +// node_modules/.pnpm/etag@1.8.1/node_modules/etag/index.js +var require_etag = __commonJS({ + "node_modules/.pnpm/etag@1.8.1/node_modules/etag/index.js"(exports, module) { + "use strict"; + module.exports = etag; + var crypto6 = __require("crypto"); + var Stats = __require("fs").Stats; + var toString = Object.prototype.toString; + function entitytag(entity) { + if (entity.length === 0) { + return '"0-2jmj7l5rSw0yVb/vlWAYkK/YBwk"'; + } + var hash2 = crypto6.createHash("sha1").update(entity, "utf8").digest("base64").substring(0, 27); + var len = typeof entity === "string" ? Buffer.byteLength(entity, "utf8") : entity.length; + return '"' + len.toString(16) + "-" + hash2 + '"'; + } + function etag(entity, options) { + if (entity == null) { + throw new TypeError("argument entity is required"); + } + var isStats = isstats(entity); + var weak = options && typeof options.weak === "boolean" ? options.weak : isStats; + if (!isStats && typeof entity !== "string" && !Buffer.isBuffer(entity)) { + throw new TypeError("argument entity must be string, Buffer, or fs.Stats"); + } + var tag3 = isStats ? stattag(entity) : entitytag(entity); + return weak ? "W/" + tag3 : tag3; + } + function isstats(obj) { + if (typeof Stats === "function" && obj instanceof Stats) { + return true; + } + return obj && typeof obj === "object" && "ctime" in obj && toString.call(obj.ctime) === "[object Date]" && "mtime" in obj && toString.call(obj.mtime) === "[object Date]" && "ino" in obj && typeof obj.ino === "number" && "size" in obj && typeof obj.size === "number"; + } + function stattag(stat5) { + var mtime = stat5.mtime.getTime().toString(16); + var size2 = stat5.size.toString(16); + return '"' + size2 + "-" + mtime + '"'; + } + } +}); + +// node_modules/.pnpm/forwarded@0.2.0/node_modules/forwarded/index.js +var require_forwarded = __commonJS({ + "node_modules/.pnpm/forwarded@0.2.0/node_modules/forwarded/index.js"(exports, module) { + "use strict"; + module.exports = forwarded; + function forwarded(req) { + if (!req) { + throw new TypeError("argument req is required"); + } + var proxyAddrs = parse5(req.headers["x-forwarded-for"] || ""); + var socketAddr = getSocketAddr(req); + var addrs = [socketAddr].concat(proxyAddrs); + return addrs; + } + function getSocketAddr(req) { + return req.socket ? req.socket.remoteAddress : req.connection.remoteAddress; + } + function parse5(header) { + var end = header.length; + var list2 = []; + var start = header.length; + for (var i5 = header.length - 1; i5 >= 0; i5--) { + switch (header.charCodeAt(i5)) { + case 32: + if (start === end) { + start = end = i5; + } + break; + case 44: + if (start !== end) { + list2.push(header.substring(start, end)); + } + start = end = i5; + break; + default: + start = i5; + break; + } + } + if (start !== end) { + list2.push(header.substring(start, end)); + } + return list2; + } + } +}); + +// node_modules/.pnpm/ipaddr.js@1.9.1/node_modules/ipaddr.js/lib/ipaddr.js +var require_ipaddr = __commonJS({ + "node_modules/.pnpm/ipaddr.js@1.9.1/node_modules/ipaddr.js/lib/ipaddr.js"(exports, module) { + (function() { + var expandIPv62, ipaddr, ipv4Part, ipv4Regexes, ipv6Part, ipv6Regexes, matchCIDR, root, zoneIndex; + ipaddr = {}; + root = this; + if (typeof module !== "undefined" && module !== null && module.exports) { + module.exports = ipaddr; + } else { + root["ipaddr"] = ipaddr; + } + matchCIDR = function(first, second, partSize, cidrBits) { + var part, shift; + if (first.length !== second.length) { + throw new Error("ipaddr: cannot match CIDR for objects with different lengths"); + } + part = 0; + while (cidrBits > 0) { + shift = partSize - cidrBits; + if (shift < 0) { + shift = 0; + } + if (first[part] >> shift !== second[part] >> shift) { + return false; + } + cidrBits -= partSize; + part += 1; + } + return true; + }; + ipaddr.subnetMatch = function(address, rangeList, defaultName) { + var k5, len, rangeName, rangeSubnets, subnet; + if (defaultName == null) { + defaultName = "unicast"; + } + for (rangeName in rangeList) { + rangeSubnets = rangeList[rangeName]; + if (rangeSubnets[0] && !(rangeSubnets[0] instanceof Array)) { + rangeSubnets = [rangeSubnets]; + } + for (k5 = 0, len = rangeSubnets.length; k5 < len; k5++) { + subnet = rangeSubnets[k5]; + if (address.kind() === subnet[0].kind()) { + if (address.match.apply(address, subnet)) { + return rangeName; + } + } + } + } + return defaultName; + }; + ipaddr.IPv4 = (function() { + function IPv4(octets) { + var k5, len, octet; + if (octets.length !== 4) { + throw new Error("ipaddr: ipv4 octet count should be 4"); + } + for (k5 = 0, len = octets.length; k5 < len; k5++) { + octet = octets[k5]; + if (!(0 <= octet && octet <= 255)) { + throw new Error("ipaddr: ipv4 octet should fit in 8 bits"); + } + } + this.octets = octets; + } + IPv4.prototype.kind = function() { + return "ipv4"; + }; + IPv4.prototype.toString = function() { + return this.octets.join("."); + }; + IPv4.prototype.toNormalizedString = function() { + return this.toString(); + }; + IPv4.prototype.toByteArray = function() { + return this.octets.slice(0); + }; + IPv4.prototype.match = function(other, cidrRange) { + var ref; + if (cidrRange === void 0) { + ref = other, other = ref[0], cidrRange = ref[1]; + } + if (other.kind() !== "ipv4") { + throw new Error("ipaddr: cannot match ipv4 address with non-ipv4 one"); + } + return matchCIDR(this.octets, other.octets, 8, cidrRange); + }; + IPv4.prototype.SpecialRanges = { + unspecified: [[new IPv4([0, 0, 0, 0]), 8]], + broadcast: [[new IPv4([255, 255, 255, 255]), 32]], + multicast: [[new IPv4([224, 0, 0, 0]), 4]], + linkLocal: [[new IPv4([169, 254, 0, 0]), 16]], + loopback: [[new IPv4([127, 0, 0, 0]), 8]], + carrierGradeNat: [[new IPv4([100, 64, 0, 0]), 10]], + "private": [[new IPv4([10, 0, 0, 0]), 8], [new IPv4([172, 16, 0, 0]), 12], [new IPv4([192, 168, 0, 0]), 16]], + reserved: [[new IPv4([192, 0, 0, 0]), 24], [new IPv4([192, 0, 2, 0]), 24], [new IPv4([192, 88, 99, 0]), 24], [new IPv4([198, 51, 100, 0]), 24], [new IPv4([203, 0, 113, 0]), 24], [new IPv4([240, 0, 0, 0]), 4]] + }; + IPv4.prototype.range = function() { + return ipaddr.subnetMatch(this, this.SpecialRanges); + }; + IPv4.prototype.toIPv4MappedAddress = function() { + return ipaddr.IPv6.parse("::ffff:" + this.toString()); + }; + IPv4.prototype.prefixLengthFromSubnetMask = function() { + var cidr2, i5, k5, octet, stop, zeros, zerotable; + zerotable = { + 0: 8, + 128: 7, + 192: 6, + 224: 5, + 240: 4, + 248: 3, + 252: 2, + 254: 1, + 255: 0 + }; + cidr2 = 0; + stop = false; + for (i5 = k5 = 3; k5 >= 0; i5 = k5 += -1) { + octet = this.octets[i5]; + if (octet in zerotable) { + zeros = zerotable[octet]; + if (stop && zeros !== 0) { + return null; + } + if (zeros !== 8) { + stop = true; + } + cidr2 += zeros; + } else { + return null; + } + } + return 32 - cidr2; + }; + return IPv4; + })(); + ipv4Part = "(0?\\d+|0x[a-f0-9]+)"; + ipv4Regexes = { + fourOctet: new RegExp("^" + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "$", "i"), + longValue: new RegExp("^" + ipv4Part + "$", "i") + }; + ipaddr.IPv4.parser = function(string4) { + var match, parseIntAuto, part, shift, value; + parseIntAuto = function(string5) { + if (string5[0] === "0" && string5[1] !== "x") { + return parseInt(string5, 8); + } else { + return parseInt(string5); + } + }; + if (match = string4.match(ipv4Regexes.fourOctet)) { + return (function() { + var k5, len, ref, results; + ref = match.slice(1, 6); + results = []; + for (k5 = 0, len = ref.length; k5 < len; k5++) { + part = ref[k5]; + results.push(parseIntAuto(part)); + } + return results; + })(); + } else if (match = string4.match(ipv4Regexes.longValue)) { + value = parseIntAuto(match[1]); + if (value > 4294967295 || value < 0) { + throw new Error("ipaddr: address outside defined range"); + } + return (function() { + var k5, results; + results = []; + for (shift = k5 = 0; k5 <= 24; shift = k5 += 8) { + results.push(value >> shift & 255); + } + return results; + })().reverse(); + } else { + return null; + } + }; + ipaddr.IPv6 = (function() { + function IPv6(parts, zoneId) { + var i5, k5, l5, len, part, ref; + if (parts.length === 16) { + this.parts = []; + for (i5 = k5 = 0; k5 <= 14; i5 = k5 += 2) { + this.parts.push(parts[i5] << 8 | parts[i5 + 1]); + } + } else if (parts.length === 8) { + this.parts = parts; + } else { + throw new Error("ipaddr: ipv6 part count should be 8 or 16"); + } + ref = this.parts; + for (l5 = 0, len = ref.length; l5 < len; l5++) { + part = ref[l5]; + if (!(0 <= part && part <= 65535)) { + throw new Error("ipaddr: ipv6 part should fit in 16 bits"); + } + } + if (zoneId) { + this.zoneId = zoneId; + } + } + IPv6.prototype.kind = function() { + return "ipv6"; + }; + IPv6.prototype.toString = function() { + return this.toNormalizedString().replace(/((^|:)(0(:|$))+)/, "::"); + }; + IPv6.prototype.toRFC5952String = function() { + var bestMatchIndex, bestMatchLength, match, regex, string4; + regex = /((^|:)(0(:|$)){2,})/g; + string4 = this.toNormalizedString(); + bestMatchIndex = 0; + bestMatchLength = -1; + while (match = regex.exec(string4)) { + if (match[0].length > bestMatchLength) { + bestMatchIndex = match.index; + bestMatchLength = match[0].length; + } + } + if (bestMatchLength < 0) { + return string4; + } + return string4.substring(0, bestMatchIndex) + "::" + string4.substring(bestMatchIndex + bestMatchLength); + }; + IPv6.prototype.toByteArray = function() { + var bytes, k5, len, part, ref; + bytes = []; + ref = this.parts; + for (k5 = 0, len = ref.length; k5 < len; k5++) { + part = ref[k5]; + bytes.push(part >> 8); + bytes.push(part & 255); + } + return bytes; + }; + IPv6.prototype.toNormalizedString = function() { + var addr, part, suffix; + addr = (function() { + var k5, len, ref, results; + ref = this.parts; + results = []; + for (k5 = 0, len = ref.length; k5 < len; k5++) { + part = ref[k5]; + results.push(part.toString(16)); + } + return results; + }).call(this).join(":"); + suffix = ""; + if (this.zoneId) { + suffix = "%" + this.zoneId; + } + return addr + suffix; + }; + IPv6.prototype.toFixedLengthString = function() { + var addr, part, suffix; + addr = (function() { + var k5, len, ref, results; + ref = this.parts; + results = []; + for (k5 = 0, len = ref.length; k5 < len; k5++) { + part = ref[k5]; + results.push(part.toString(16).padStart(4, "0")); + } + return results; + }).call(this).join(":"); + suffix = ""; + if (this.zoneId) { + suffix = "%" + this.zoneId; + } + return addr + suffix; + }; + IPv6.prototype.match = function(other, cidrRange) { + var ref; + if (cidrRange === void 0) { + ref = other, other = ref[0], cidrRange = ref[1]; + } + if (other.kind() !== "ipv6") { + throw new Error("ipaddr: cannot match ipv6 address with non-ipv6 one"); + } + return matchCIDR(this.parts, other.parts, 16, cidrRange); + }; + IPv6.prototype.SpecialRanges = { + unspecified: [new IPv6([0, 0, 0, 0, 0, 0, 0, 0]), 128], + linkLocal: [new IPv6([65152, 0, 0, 0, 0, 0, 0, 0]), 10], + multicast: [new IPv6([65280, 0, 0, 0, 0, 0, 0, 0]), 8], + loopback: [new IPv6([0, 0, 0, 0, 0, 0, 0, 1]), 128], + uniqueLocal: [new IPv6([64512, 0, 0, 0, 0, 0, 0, 0]), 7], + ipv4Mapped: [new IPv6([0, 0, 0, 0, 0, 65535, 0, 0]), 96], + rfc6145: [new IPv6([0, 0, 0, 0, 65535, 0, 0, 0]), 96], + rfc6052: [new IPv6([100, 65435, 0, 0, 0, 0, 0, 0]), 96], + "6to4": [new IPv6([8194, 0, 0, 0, 0, 0, 0, 0]), 16], + teredo: [new IPv6([8193, 0, 0, 0, 0, 0, 0, 0]), 32], + reserved: [[new IPv6([8193, 3512, 0, 0, 0, 0, 0, 0]), 32]] + }; + IPv6.prototype.range = function() { + return ipaddr.subnetMatch(this, this.SpecialRanges); + }; + IPv6.prototype.isIPv4MappedAddress = function() { + return this.range() === "ipv4Mapped"; + }; + IPv6.prototype.toIPv4Address = function() { + var high, low, ref; + if (!this.isIPv4MappedAddress()) { + throw new Error("ipaddr: trying to convert a generic ipv6 address to ipv4"); + } + ref = this.parts.slice(-2), high = ref[0], low = ref[1]; + return new ipaddr.IPv4([high >> 8, high & 255, low >> 8, low & 255]); + }; + IPv6.prototype.prefixLengthFromSubnetMask = function() { + var cidr2, i5, k5, part, stop, zeros, zerotable; + zerotable = { + 0: 16, + 32768: 15, + 49152: 14, + 57344: 13, + 61440: 12, + 63488: 11, + 64512: 10, + 65024: 9, + 65280: 8, + 65408: 7, + 65472: 6, + 65504: 5, + 65520: 4, + 65528: 3, + 65532: 2, + 65534: 1, + 65535: 0 + }; + cidr2 = 0; + stop = false; + for (i5 = k5 = 7; k5 >= 0; i5 = k5 += -1) { + part = this.parts[i5]; + if (part in zerotable) { + zeros = zerotable[part]; + if (stop && zeros !== 0) { + return null; + } + if (zeros !== 16) { + stop = true; + } + cidr2 += zeros; + } else { + return null; + } + } + return 128 - cidr2; + }; + return IPv6; + })(); + ipv6Part = "(?:[0-9a-f]+::?)+"; + zoneIndex = "%[0-9a-z]{1,}"; + ipv6Regexes = { + zoneIndex: new RegExp(zoneIndex, "i"), + "native": new RegExp("^(::)?(" + ipv6Part + ")?([0-9a-f]+)?(::)?(" + zoneIndex + ")?$", "i"), + transitional: new RegExp("^((?:" + ipv6Part + ")|(?:::)(?:" + ipv6Part + ")?)" + (ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part) + ("(" + zoneIndex + ")?$"), "i") + }; + expandIPv62 = function(string4, parts) { + var colonCount, lastColon, part, replacement, replacementCount, zoneId; + if (string4.indexOf("::") !== string4.lastIndexOf("::")) { + return null; + } + zoneId = (string4.match(ipv6Regexes["zoneIndex"]) || [])[0]; + if (zoneId) { + zoneId = zoneId.substring(1); + string4 = string4.replace(/%.+$/, ""); + } + colonCount = 0; + lastColon = -1; + while ((lastColon = string4.indexOf(":", lastColon + 1)) >= 0) { + colonCount++; + } + if (string4.substr(0, 2) === "::") { + colonCount--; + } + if (string4.substr(-2, 2) === "::") { + colonCount--; + } + if (colonCount > parts) { + return null; + } + replacementCount = parts - colonCount; + replacement = ":"; + while (replacementCount--) { + replacement += "0:"; + } + string4 = string4.replace("::", replacement); + if (string4[0] === ":") { + string4 = string4.slice(1); + } + if (string4[string4.length - 1] === ":") { + string4 = string4.slice(0, -1); + } + parts = (function() { + var k5, len, ref, results; + ref = string4.split(":"); + results = []; + for (k5 = 0, len = ref.length; k5 < len; k5++) { + part = ref[k5]; + results.push(parseInt(part, 16)); + } + return results; + })(); + return { + parts, + zoneId + }; + }; + ipaddr.IPv6.parser = function(string4) { + var addr, k5, len, match, octet, octets, zoneId; + if (ipv6Regexes["native"].test(string4)) { + return expandIPv62(string4, 8); + } else if (match = string4.match(ipv6Regexes["transitional"])) { + zoneId = match[6] || ""; + addr = expandIPv62(match[1].slice(0, -1) + zoneId, 6); + if (addr.parts) { + octets = [parseInt(match[2]), parseInt(match[3]), parseInt(match[4]), parseInt(match[5])]; + for (k5 = 0, len = octets.length; k5 < len; k5++) { + octet = octets[k5]; + if (!(0 <= octet && octet <= 255)) { + return null; + } + } + addr.parts.push(octets[0] << 8 | octets[1]); + addr.parts.push(octets[2] << 8 | octets[3]); + return { + parts: addr.parts, + zoneId: addr.zoneId + }; + } + } + return null; + }; + ipaddr.IPv4.isIPv4 = ipaddr.IPv6.isIPv6 = function(string4) { + return this.parser(string4) !== null; + }; + ipaddr.IPv4.isValid = function(string4) { + var e5; + try { + new this(this.parser(string4)); + return true; + } catch (error1) { + e5 = error1; + return false; + } + }; + ipaddr.IPv4.isValidFourPartDecimal = function(string4) { + if (ipaddr.IPv4.isValid(string4) && string4.match(/^(0|[1-9]\d*)(\.(0|[1-9]\d*)){3}$/)) { + return true; + } else { + return false; + } + }; + ipaddr.IPv6.isValid = function(string4) { + var addr, e5; + if (typeof string4 === "string" && string4.indexOf(":") === -1) { + return false; + } + try { + addr = this.parser(string4); + new this(addr.parts, addr.zoneId); + return true; + } catch (error1) { + e5 = error1; + return false; + } + }; + ipaddr.IPv4.parse = function(string4) { + var parts; + parts = this.parser(string4); + if (parts === null) { + throw new Error("ipaddr: string is not formatted like ip address"); + } + return new this(parts); + }; + ipaddr.IPv6.parse = function(string4) { + var addr; + addr = this.parser(string4); + if (addr.parts === null) { + throw new Error("ipaddr: string is not formatted like ip address"); + } + return new this(addr.parts, addr.zoneId); + }; + ipaddr.IPv4.parseCIDR = function(string4) { + var maskLength, match, parsed; + if (match = string4.match(/^(.+)\/(\d+)$/)) { + maskLength = parseInt(match[2]); + if (maskLength >= 0 && maskLength <= 32) { + parsed = [this.parse(match[1]), maskLength]; + Object.defineProperty(parsed, "toString", { + value: function() { + return this.join("/"); + } + }); + return parsed; + } + } + throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range"); + }; + ipaddr.IPv4.subnetMaskFromPrefixLength = function(prefix) { + var filledOctetCount, j5, octets; + prefix = parseInt(prefix); + if (prefix < 0 || prefix > 32) { + throw new Error("ipaddr: invalid IPv4 prefix length"); + } + octets = [0, 0, 0, 0]; + j5 = 0; + filledOctetCount = Math.floor(prefix / 8); + while (j5 < filledOctetCount) { + octets[j5] = 255; + j5++; + } + if (filledOctetCount < 4) { + octets[filledOctetCount] = Math.pow(2, prefix % 8) - 1 << 8 - prefix % 8; + } + return new this(octets); + }; + ipaddr.IPv4.broadcastAddressFromCIDR = function(string4) { + var cidr2, error50, i5, ipInterfaceOctets, octets, subnetMaskOctets; + try { + cidr2 = this.parseCIDR(string4); + ipInterfaceOctets = cidr2[0].toByteArray(); + subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr2[1]).toByteArray(); + octets = []; + i5 = 0; + while (i5 < 4) { + octets.push(parseInt(ipInterfaceOctets[i5], 10) | parseInt(subnetMaskOctets[i5], 10) ^ 255); + i5++; + } + return new this(octets); + } catch (error1) { + error50 = error1; + throw new Error("ipaddr: the address does not have IPv4 CIDR format"); + } + }; + ipaddr.IPv4.networkAddressFromCIDR = function(string4) { + var cidr2, error50, i5, ipInterfaceOctets, octets, subnetMaskOctets; + try { + cidr2 = this.parseCIDR(string4); + ipInterfaceOctets = cidr2[0].toByteArray(); + subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr2[1]).toByteArray(); + octets = []; + i5 = 0; + while (i5 < 4) { + octets.push(parseInt(ipInterfaceOctets[i5], 10) & parseInt(subnetMaskOctets[i5], 10)); + i5++; + } + return new this(octets); + } catch (error1) { + error50 = error1; + throw new Error("ipaddr: the address does not have IPv4 CIDR format"); + } + }; + ipaddr.IPv6.parseCIDR = function(string4) { + var maskLength, match, parsed; + if (match = string4.match(/^(.+)\/(\d+)$/)) { + maskLength = parseInt(match[2]); + if (maskLength >= 0 && maskLength <= 128) { + parsed = [this.parse(match[1]), maskLength]; + Object.defineProperty(parsed, "toString", { + value: function() { + return this.join("/"); + } + }); + return parsed; + } + } + throw new Error("ipaddr: string is not formatted like an IPv6 CIDR range"); + }; + ipaddr.isValid = function(string4) { + return ipaddr.IPv6.isValid(string4) || ipaddr.IPv4.isValid(string4); + }; + ipaddr.parse = function(string4) { + if (ipaddr.IPv6.isValid(string4)) { + return ipaddr.IPv6.parse(string4); + } else if (ipaddr.IPv4.isValid(string4)) { + return ipaddr.IPv4.parse(string4); + } else { + throw new Error("ipaddr: the address has neither IPv6 nor IPv4 format"); + } + }; + ipaddr.parseCIDR = function(string4) { + var e5; + try { + return ipaddr.IPv6.parseCIDR(string4); + } catch (error1) { + e5 = error1; + try { + return ipaddr.IPv4.parseCIDR(string4); + } catch (error110) { + e5 = error110; + throw new Error("ipaddr: the address has neither IPv6 nor IPv4 CIDR format"); + } + } + }; + ipaddr.fromByteArray = function(bytes) { + var length; + length = bytes.length; + if (length === 4) { + return new ipaddr.IPv4(bytes); + } else if (length === 16) { + return new ipaddr.IPv6(bytes); + } else { + throw new Error("ipaddr: the binary input is neither an IPv6 nor IPv4 address"); + } + }; + ipaddr.process = function(string4) { + var addr; + addr = this.parse(string4); + if (addr.kind() === "ipv6" && addr.isIPv4MappedAddress()) { + return addr.toIPv4Address(); + } else { + return addr; + } + }; + }).call(exports); + } +}); + +// node_modules/.pnpm/proxy-addr@2.0.7/node_modules/proxy-addr/index.js +var require_proxy_addr = __commonJS({ + "node_modules/.pnpm/proxy-addr@2.0.7/node_modules/proxy-addr/index.js"(exports, module) { + "use strict"; + module.exports = proxyaddr; + module.exports.all = alladdrs; + module.exports.compile = compile; + var forwarded = require_forwarded(); + var ipaddr = require_ipaddr(); + var DIGIT_REGEXP = /^[0-9]+$/; + var isip = ipaddr.isValid; + var parseip = ipaddr.parse; + var IP_RANGES = { + linklocal: ["169.254.0.0/16", "fe80::/10"], + loopback: ["127.0.0.1/8", "::1/128"], + uniquelocal: ["10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "fc00::/7"] + }; + function alladdrs(req, trust) { + var addrs = forwarded(req); + if (!trust) { + return addrs; + } + if (typeof trust !== "function") { + trust = compile(trust); + } + for (var i5 = 0; i5 < addrs.length - 1; i5++) { + if (trust(addrs[i5], i5)) continue; + addrs.length = i5 + 1; + } + return addrs; + } + function compile(val) { + if (!val) { + throw new TypeError("argument is required"); + } + var trust; + if (typeof val === "string") { + trust = [val]; + } else if (Array.isArray(val)) { + trust = val.slice(); + } else { + throw new TypeError("unsupported trust argument"); + } + for (var i5 = 0; i5 < trust.length; i5++) { + val = trust[i5]; + if (!Object.prototype.hasOwnProperty.call(IP_RANGES, val)) { + continue; + } + val = IP_RANGES[val]; + trust.splice.apply(trust, [i5, 1].concat(val)); + i5 += val.length - 1; + } + return compileTrust(compileRangeSubnets(trust)); + } + function compileRangeSubnets(arr) { + var rangeSubnets = new Array(arr.length); + for (var i5 = 0; i5 < arr.length; i5++) { + rangeSubnets[i5] = parseipNotation(arr[i5]); + } + return rangeSubnets; + } + function compileTrust(rangeSubnets) { + var len = rangeSubnets.length; + return len === 0 ? trustNone : len === 1 ? trustSingle(rangeSubnets[0]) : trustMulti(rangeSubnets); + } + function parseipNotation(note) { + var pos = note.lastIndexOf("/"); + var str = pos !== -1 ? note.substring(0, pos) : note; + if (!isip(str)) { + throw new TypeError("invalid IP address: " + str); + } + var ip = parseip(str); + if (pos === -1 && ip.kind() === "ipv6" && ip.isIPv4MappedAddress()) { + ip = ip.toIPv4Address(); + } + var max = ip.kind() === "ipv6" ? 128 : 32; + var range2 = pos !== -1 ? note.substring(pos + 1, note.length) : null; + if (range2 === null) { + range2 = max; + } else if (DIGIT_REGEXP.test(range2)) { + range2 = parseInt(range2, 10); + } else if (ip.kind() === "ipv4" && isip(range2)) { + range2 = parseNetmask(range2); + } else { + range2 = null; + } + if (range2 <= 0 || range2 > max) { + throw new TypeError("invalid range on address: " + note); + } + return [ip, range2]; + } + function parseNetmask(netmask) { + var ip = parseip(netmask); + var kind = ip.kind(); + return kind === "ipv4" ? ip.prefixLengthFromSubnetMask() : null; + } + function proxyaddr(req, trust) { + if (!req) { + throw new TypeError("req argument is required"); + } + if (!trust) { + throw new TypeError("trust argument is required"); + } + var addrs = alladdrs(req, trust); + var addr = addrs[addrs.length - 1]; + return addr; + } + function trustNone() { + return false; + } + function trustMulti(subnets) { + return function trust(addr) { + if (!isip(addr)) return false; + var ip = parseip(addr); + var ipconv; + var kind = ip.kind(); + for (var i5 = 0; i5 < subnets.length; i5++) { + var subnet = subnets[i5]; + var subnetip = subnet[0]; + var subnetkind = subnetip.kind(); + var subnetrange = subnet[1]; + var trusted = ip; + if (kind !== subnetkind) { + if (subnetkind === "ipv4" && !ip.isIPv4MappedAddress()) { + continue; + } + if (!ipconv) { + ipconv = subnetkind === "ipv4" ? ip.toIPv4Address() : ip.toIPv4MappedAddress(); + } + trusted = ipconv; + } + if (trusted.match(subnetip, subnetrange)) { + return true; + } + } + return false; + }; + } + function trustSingle(subnet) { + var subnetip = subnet[0]; + var subnetkind = subnetip.kind(); + var subnetisipv4 = subnetkind === "ipv4"; + var subnetrange = subnet[1]; + return function trust(addr) { + if (!isip(addr)) return false; + var ip = parseip(addr); + var kind = ip.kind(); + if (kind !== subnetkind) { + if (subnetisipv4 && !ip.isIPv4MappedAddress()) { + return false; + } + ip = subnetisipv4 ? ip.toIPv4Address() : ip.toIPv4MappedAddress(); + } + return ip.match(subnetip, subnetrange); + }; + } + } +}); + +// node_modules/.pnpm/express@5.2.1/node_modules/express/lib/utils.js +var require_utils3 = __commonJS({ + "node_modules/.pnpm/express@5.2.1/node_modules/express/lib/utils.js"(exports) { + "use strict"; + var { METHODS } = __require("node:http"); + var contentType = require_content_type(); + var etag = require_etag(); + var mime = require_mime_types(); + var proxyaddr = require_proxy_addr(); + var qs = require_lib2(); + var querystring = __require("node:querystring"); + var { Buffer: Buffer2 } = __require("node:buffer"); + exports.methods = METHODS.map((method) => method.toLowerCase()); + exports.etag = createETagGenerator({ weak: false }); + exports.wetag = createETagGenerator({ weak: true }); + exports.normalizeType = function(type) { + return ~type.indexOf("/") ? acceptParams(type) : { value: mime.lookup(type) || "application/octet-stream", params: {} }; + }; + exports.normalizeTypes = function(types2) { + return types2.map(exports.normalizeType); + }; + function acceptParams(str) { + var length = str.length; + var colonIndex = str.indexOf(";"); + var index2 = colonIndex === -1 ? length : colonIndex; + var ret = { value: str.slice(0, index2).trim(), quality: 1, params: {} }; + while (index2 < length) { + var splitIndex = str.indexOf("=", index2); + if (splitIndex === -1) break; + var colonIndex = str.indexOf(";", index2); + var endIndex = colonIndex === -1 ? length : colonIndex; + if (splitIndex > endIndex) { + index2 = str.lastIndexOf(";", splitIndex - 1) + 1; + continue; + } + var key = str.slice(index2, splitIndex).trim(); + var value = str.slice(splitIndex + 1, endIndex).trim(); + if (key === "q") { + ret.quality = parseFloat(value); + } else { + ret.params[key] = value; + } + index2 = endIndex + 1; + } + return ret; + } + exports.compileETag = function(val) { + var fn; + if (typeof val === "function") { + return val; + } + switch (val) { + case true: + case "weak": + fn = exports.wetag; + break; + case false: + break; + case "strong": + fn = exports.etag; + break; + default: + throw new TypeError("unknown value for etag function: " + val); + } + return fn; + }; + exports.compileQueryParser = function compileQueryParser(val) { + var fn; + if (typeof val === "function") { + return val; + } + switch (val) { + case true: + case "simple": + fn = querystring.parse; + break; + case false: + break; + case "extended": + fn = parseExtendedQueryString; + break; + default: + throw new TypeError("unknown value for query parser function: " + val); + } + return fn; + }; + exports.compileTrust = function(val) { + if (typeof val === "function") return val; + if (val === true) { + return function() { + return true; + }; + } + if (typeof val === "number") { + return function(a5, i5) { + return i5 < val; + }; + } + if (typeof val === "string") { + val = val.split(",").map(function(v5) { + return v5.trim(); + }); + } + return proxyaddr.compile(val || []); + }; + exports.setCharset = function setCharset(type, charset) { + if (!type || !charset) { + return type; + } + var parsed = contentType.parse(type); + parsed.parameters.charset = charset; + return contentType.format(parsed); + }; + function createETagGenerator(options) { + return function generateETag(body, encoding) { + var buf = !Buffer2.isBuffer(body) ? Buffer2.from(body, encoding) : body; + return etag(buf, options); + }; + } + function parseExtendedQueryString(str) { + return qs.parse(str, { + allowPrototypes: true + }); + } + } +}); + +// node_modules/.pnpm/wrappy@1.0.2/node_modules/wrappy/wrappy.js +var require_wrappy = __commonJS({ + "node_modules/.pnpm/wrappy@1.0.2/node_modules/wrappy/wrappy.js"(exports, module) { + module.exports = wrappy; + function wrappy(fn, cb) { + if (fn && cb) return wrappy(fn)(cb); + if (typeof fn !== "function") + throw new TypeError("need wrapper function"); + Object.keys(fn).forEach(function(k5) { + wrapper[k5] = fn[k5]; + }); + return wrapper; + function wrapper() { + var args = new Array(arguments.length); + for (var i5 = 0; i5 < args.length; i5++) { + args[i5] = arguments[i5]; + } + var ret = fn.apply(this, args); + var cb2 = args[args.length - 1]; + if (typeof ret === "function" && ret !== cb2) { + Object.keys(cb2).forEach(function(k5) { + ret[k5] = cb2[k5]; + }); + } + return ret; + } + } + } +}); + +// node_modules/.pnpm/once@1.4.0/node_modules/once/once.js +var require_once = __commonJS({ + "node_modules/.pnpm/once@1.4.0/node_modules/once/once.js"(exports, module) { + var wrappy = require_wrappy(); + module.exports = wrappy(once); + module.exports.strict = wrappy(onceStrict); + once.proto = once(function() { + Object.defineProperty(Function.prototype, "once", { + value: function() { + return once(this); + }, + configurable: true + }); + Object.defineProperty(Function.prototype, "onceStrict", { + value: function() { + return onceStrict(this); + }, + configurable: true + }); + }); + function once(fn) { + var f5 = function() { + if (f5.called) return f5.value; + f5.called = true; + return f5.value = fn.apply(this, arguments); + }; + f5.called = false; + return f5; + } + function onceStrict(fn) { + var f5 = function() { + if (f5.called) + throw new Error(f5.onceError); + f5.called = true; + return f5.value = fn.apply(this, arguments); + }; + var name = fn.name || "Function wrapped with `once`"; + f5.onceError = name + " shouldn't be called more than once"; + f5.called = false; + return f5; + } + } +}); + +// node_modules/.pnpm/is-promise@4.0.0/node_modules/is-promise/index.js +var require_is_promise = __commonJS({ + "node_modules/.pnpm/is-promise@4.0.0/node_modules/is-promise/index.js"(exports, module) { + module.exports = isPromise2; + module.exports.default = isPromise2; + function isPromise2(obj) { + return !!obj && (typeof obj === "object" || typeof obj === "function") && typeof obj.then === "function"; + } + } +}); + +// node_modules/.pnpm/path-to-regexp@8.4.2/node_modules/path-to-regexp/dist/index.js +var require_dist = __commonJS({ + "node_modules/.pnpm/path-to-regexp@8.4.2/node_modules/path-to-regexp/dist/index.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.PathError = exports.TokenData = void 0; + exports.parse = parse5; + exports.compile = compile; + exports.match = match; + exports.pathToRegexp = pathToRegexp; + exports.stringify = stringify2; + var DEFAULT_DELIMITER = "/"; + var NOOP_VALUE = (value) => value; + var ID_START = /^[$_\p{ID_Start}]$/u; + var ID_CONTINUE = /^[$\u200c\u200d\p{ID_Continue}]$/u; + var ID = /^[$_\p{ID_Start}][$\u200c\u200d\p{ID_Continue}]*$/u; + function escapeText(str) { + return str.replace(/[{}()\[\]+?!:*\\]/g, "\\$&"); + } + function escape3(str) { + return str.replace(/[.+*?^${}()[\]|/\\]/g, "\\$&"); + } + var TokenData = class { + constructor(tokens, originalPath) { + this.tokens = tokens; + this.originalPath = originalPath; + } + }; + exports.TokenData = TokenData; + var PathError = class extends TypeError { + constructor(message2, originalPath) { + let text3 = message2; + if (originalPath) + text3 += `: ${originalPath}`; + text3 += `; visit https://git.new/pathToRegexpError for info`; + super(text3); + this.originalPath = originalPath; + } + }; + exports.PathError = PathError; + function parse5(str, options = {}) { + const { encodePath = NOOP_VALUE } = options; + const chars = [...str]; + let index2 = 0; + function consumeUntil(end) { + const output = []; + let path53 = ""; + function writePath() { + if (!path53) + return; + output.push({ + type: "text", + value: encodePath(path53) + }); + path53 = ""; + } + while (index2 < chars.length) { + const value = chars[index2++]; + if (value === end) { + writePath(); + return output; + } + if (value === "\\") { + if (index2 === chars.length) { + throw new PathError(`Unexpected end after \\ at index ${index2}`, str); + } + path53 += chars[index2++]; + continue; + } + if (value === ":" || value === "*") { + const type = value === ":" ? "param" : "wildcard"; + let name = ""; + if (ID_START.test(chars[index2])) { + do { + name += chars[index2++]; + } while (ID_CONTINUE.test(chars[index2])); + } else if (chars[index2] === '"') { + let quoteStart = index2; + while (index2 < chars.length) { + if (chars[++index2] === '"') { + index2++; + quoteStart = 0; + break; + } + if (chars[index2] === "\\") + index2++; + name += chars[index2]; + } + if (quoteStart) { + throw new PathError(`Unterminated quote at index ${quoteStart}`, str); + } + } + if (!name) { + throw new PathError(`Missing parameter name at index ${index2}`, str); + } + writePath(); + output.push({ type, name }); + continue; + } + if (value === "{") { + writePath(); + output.push({ + type: "group", + tokens: consumeUntil("}") + }); + continue; + } + if (value === "}" || value === "(" || value === ")" || value === "[" || value === "]" || value === "+" || value === "?" || value === "!") { + throw new PathError(`Unexpected ${value} at index ${index2 - 1}`, str); + } + path53 += value; + } + if (end) { + throw new PathError(`Unexpected end at index ${index2}, expected ${end}`, str); + } + writePath(); + return output; + } + return new TokenData(consumeUntil(""), str); + } + function compile(path53, options = {}) { + const { encode: encode6 = encodeURIComponent, delimiter = DEFAULT_DELIMITER } = options; + const data2 = typeof path53 === "object" ? path53 : parse5(path53, options); + const fn = tokensToFunction(data2.tokens, delimiter, encode6); + return function path54(params = {}) { + const missing = []; + const path55 = fn(params, missing); + if (missing.length) { + throw new TypeError(`Missing parameters: ${missing.join(", ")}`); + } + return path55; + }; + } + function tokensToFunction(tokens, delimiter, encode6) { + const encoders = tokens.map((token) => tokenToFunction(token, delimiter, encode6)); + return (data2, missing) => { + let result = ""; + for (const encoder3 of encoders) { + result += encoder3(data2, missing); + } + return result; + }; + } + function tokenToFunction(token, delimiter, encode6) { + if (token.type === "text") + return () => token.value; + if (token.type === "group") { + const fn = tokensToFunction(token.tokens, delimiter, encode6); + return (data2, missing) => { + const len = missing.length; + const value = fn(data2, missing); + if (missing.length === len) + return value; + missing.length = len; + return ""; + }; + } + const encodeValue = encode6 || NOOP_VALUE; + if (token.type === "wildcard" && encode6 !== false) { + return (data2, missing) => { + const value = data2[token.name]; + if (value == null) { + missing.push(token.name); + return ""; + } + if (!Array.isArray(value) || value.length === 0) { + throw new TypeError(`Expected "${token.name}" to be a non-empty array`); + } + let result = ""; + for (let i5 = 0; i5 < value.length; i5++) { + if (typeof value[i5] !== "string") { + throw new TypeError(`Expected "${token.name}/${i5}" to be a string`); + } + if (i5 > 0) + result += delimiter; + result += encodeValue(value[i5]); + } + return result; + }; + } + return (data2, missing) => { + const value = data2[token.name]; + if (value == null) { + missing.push(token.name); + return ""; + } + if (typeof value !== "string") { + throw new TypeError(`Expected "${token.name}" to be a string`); + } + return encodeValue(value); + }; + } + function match(path53, options = {}) { + const { decode: decode5 = decodeURIComponent, delimiter = DEFAULT_DELIMITER } = options; + const { regexp, keys } = pathToRegexp(path53, options); + const decoders2 = keys.map((key) => { + if (decode5 === false) + return NOOP_VALUE; + if (key.type === "param") + return decode5; + return (value) => value.split(delimiter).map(decode5); + }); + return function match2(input) { + const m5 = regexp.exec(input); + if (!m5) + return false; + const path54 = m5[0]; + const params = /* @__PURE__ */ Object.create(null); + for (let i5 = 1; i5 < m5.length; i5++) { + if (m5[i5] === void 0) + continue; + const key = keys[i5 - 1]; + const decoder2 = decoders2[i5 - 1]; + params[key.name] = decoder2(m5[i5]); + } + return { path: path54, params }; + }; + } + function pathToRegexp(path53, options = {}) { + const { delimiter = DEFAULT_DELIMITER, end = true, sensitive = false, trailing = true } = options; + const keys = []; + let source = ""; + let combinations = 0; + function process3(path54) { + if (Array.isArray(path54)) { + for (const p5 of path54) + process3(p5); + return; + } + const data2 = typeof path54 === "object" ? path54 : parse5(path54, options); + flatten(data2.tokens, 0, [], (tokens) => { + if (combinations >= 256) { + throw new PathError("Too many path combinations", data2.originalPath); + } + if (combinations > 0) + source += "|"; + source += toRegExpSource(tokens, delimiter, keys, data2.originalPath); + combinations++; + }); + } + process3(path53); + let pattern = `^(?:${source})`; + if (trailing) + pattern += "(?:" + escape3(delimiter) + "$)?"; + pattern += end ? "$" : "(?=" + escape3(delimiter) + "|$)"; + return { regexp: new RegExp(pattern, sensitive ? "" : "i"), keys }; + } + function flatten(tokens, index2, result, callback) { + while (index2 < tokens.length) { + const token = tokens[index2++]; + if (token.type === "group") { + const len = result.length; + flatten(token.tokens, 0, result, (seq) => flatten(tokens, index2, seq, callback)); + result.length = len; + continue; + } + result.push(token); + } + callback(result); + } + function toRegExpSource(tokens, delimiter, keys, originalPath) { + let result = ""; + let backtrack = ""; + let wildcardBacktrack = ""; + let prevCaptureType = 0; + let hasSegmentCapture = 0; + let index2 = 0; + function hasInSegment(index3, type) { + while (index3 < tokens.length) { + const token = tokens[index3++]; + if (token.type === type) + return true; + if (token.type === "text") { + if (token.value.includes(delimiter)) + break; + } + } + return false; + } + function peekText(index3) { + let result2 = ""; + while (index3 < tokens.length) { + const token = tokens[index3++]; + if (token.type !== "text") + break; + result2 += token.value; + } + return result2; + } + while (index2 < tokens.length) { + const token = tokens[index2++]; + if (token.type === "text") { + result += escape3(token.value); + backtrack += token.value; + if (prevCaptureType === 2) + wildcardBacktrack += token.value; + if (token.value.includes(delimiter)) + hasSegmentCapture = 0; + continue; + } + if (token.type === "param" || token.type === "wildcard") { + if (prevCaptureType && !backtrack) { + throw new PathError(`Missing text before "${token.name}" ${token.type}`, originalPath); + } + if (token.type === "param") { + result += hasSegmentCapture & 2 ? `(${negate(delimiter, backtrack)}+)` : hasInSegment(index2, "wildcard") ? `(${negate(delimiter, peekText(index2))}+)` : hasSegmentCapture & 1 ? `(${negate(delimiter, backtrack)}+|${escape3(backtrack)})` : `(${negate(delimiter, "")}+)`; + hasSegmentCapture |= prevCaptureType = 1; + } else { + result += hasSegmentCapture & 2 ? `(${negate(backtrack, "")}+)` : wildcardBacktrack ? `(${negate(wildcardBacktrack, "")}+|${negate(delimiter, "")}+)` : `([^]+)`; + wildcardBacktrack = ""; + hasSegmentCapture |= prevCaptureType = 2; + } + keys.push(token); + backtrack = ""; + continue; + } + throw new TypeError(`Unknown token type: ${token.type}`); + } + return result; + } + function negate(a5, b6) { + if (b6.length > a5.length) + return negate(b6, a5); + if (a5 === b6) + b6 = ""; + if (b6.length > 1) + return `(?:(?!${escape3(a5)}|${escape3(b6)})[^])`; + if (a5.length > 1) + return `(?:(?!${escape3(a5)})[^${escape3(b6)}])`; + return `[^${escape3(a5 + b6)}]`; + } + function stringifyTokens(tokens, index2) { + let value = ""; + while (index2 < tokens.length) { + const token = tokens[index2++]; + if (token.type === "text") { + value += escapeText(token.value); + continue; + } + if (token.type === "group") { + value += "{" + stringifyTokens(token.tokens, 0) + "}"; + continue; + } + if (token.type === "param") { + value += ":" + stringifyName(token.name, tokens[index2]); + continue; + } + if (token.type === "wildcard") { + value += "*" + stringifyName(token.name, tokens[index2]); + continue; + } + throw new TypeError(`Unknown token type: ${token.type}`); + } + return value; + } + function stringify2(data2) { + return stringifyTokens(data2.tokens, 0); + } + function stringifyName(name, next) { + if (!ID.test(name)) + return JSON.stringify(name); + if ((next === null || next === void 0 ? void 0 : next.type) === "text" && ID_CONTINUE.test(next.value[0])) { + return JSON.stringify(name); + } + return name; + } + } +}); + +// node_modules/.pnpm/router@2.2.0/node_modules/router/lib/layer.js +var require_layer = __commonJS({ + "node_modules/.pnpm/router@2.2.0/node_modules/router/lib/layer.js"(exports, module) { + "use strict"; + var isPromise2 = require_is_promise(); + var pathRegexp = require_dist(); + var debug = require_src()("router:layer"); + var deprecate2 = require_depd()("router"); + var TRAILING_SLASH_REGEXP = /\/+$/; + var MATCHING_GROUP_REGEXP = /\((?:\?<(.*?)>)?(?!\?)/g; + module.exports = Layer; + function Layer(path53, options, fn) { + if (!(this instanceof Layer)) { + return new Layer(path53, options, fn); + } + debug("new %o", path53); + const opts = options || {}; + this.handle = fn; + this.keys = []; + this.name = fn.name || ""; + this.params = void 0; + this.path = void 0; + this.slash = path53 === "/" && opts.end === false; + function matcher(_path) { + if (_path instanceof RegExp) { + const keys = []; + let name = 0; + let m5; + while (m5 = MATCHING_GROUP_REGEXP.exec(_path.source)) { + keys.push({ + name: m5[1] || name++, + offset: m5.index + }); + } + return function regexpMatcher(p5) { + const match = _path.exec(p5); + if (!match) { + return false; + } + const params = {}; + for (let i5 = 1; i5 < match.length; i5++) { + const key = keys[i5 - 1]; + const prop = key.name; + const val = decodeParam(match[i5]); + if (val !== void 0) { + params[prop] = val; + } + } + return { + params, + path: match[0] + }; + }; + } + return pathRegexp.match(opts.strict ? _path : loosen(_path), { + sensitive: opts.sensitive, + end: opts.end, + trailing: !opts.strict, + decode: decodeParam + }); + } + this.matchers = Array.isArray(path53) ? path53.map(matcher) : [matcher(path53)]; + } + Layer.prototype.handleError = function handleError(error50, req, res, next) { + const fn = this.handle; + if (fn.length !== 4) { + return next(error50); + } + try { + const ret = fn(error50, req, res, next); + if (isPromise2(ret)) { + if (!(ret instanceof Promise)) { + deprecate2("handlers that are Promise-like are deprecated, use a native Promise instead"); + } + ret.then(null, function(error51) { + next(error51 || new Error("Rejected promise")); + }); + } + } catch (err) { + next(err); + } + }; + Layer.prototype.handleRequest = function handleRequest(req, res, next) { + const fn = this.handle; + if (fn.length > 3) { + return next(); + } + try { + const ret = fn(req, res, next); + if (isPromise2(ret)) { + if (!(ret instanceof Promise)) { + deprecate2("handlers that are Promise-like are deprecated, use a native Promise instead"); + } + ret.then(null, function(error50) { + next(error50 || new Error("Rejected promise")); + }); + } + } catch (err) { + next(err); + } + }; + Layer.prototype.match = function match(path53) { + let match2; + if (path53 != null) { + if (this.slash) { + this.params = {}; + this.path = ""; + return true; + } + let i5 = 0; + while (!match2 && i5 < this.matchers.length) { + match2 = this.matchers[i5](path53); + i5++; + } + } + if (!match2) { + this.params = void 0; + this.path = void 0; + return false; + } + this.params = match2.params; + this.path = match2.path; + this.keys = Object.keys(match2.params); + return true; + }; + function decodeParam(val) { + if (typeof val !== "string" || val.length === 0) { + return val; + } + try { + return decodeURIComponent(val); + } catch (err) { + if (err instanceof URIError) { + err.message = "Failed to decode param '" + val + "'"; + err.status = 400; + } + throw err; + } + } + function loosen(path53) { + if (path53 instanceof RegExp || path53 === "/") { + return path53; + } + return Array.isArray(path53) ? path53.map(function(p5) { + return loosen(p5); + }) : String(path53).replace(TRAILING_SLASH_REGEXP, ""); + } + } +}); + +// node_modules/.pnpm/router@2.2.0/node_modules/router/lib/route.js +var require_route = __commonJS({ + "node_modules/.pnpm/router@2.2.0/node_modules/router/lib/route.js"(exports, module) { + "use strict"; + var debug = require_src()("router:route"); + var Layer = require_layer(); + var { METHODS } = __require("node:http"); + var slice = Array.prototype.slice; + var flatten = Array.prototype.flat; + var methods2 = METHODS.map((method) => method.toLowerCase()); + module.exports = Route; + function Route(path53) { + debug("new %o", path53); + this.path = path53; + this.stack = []; + this.methods = /* @__PURE__ */ Object.create(null); + } + Route.prototype._handlesMethod = function _handlesMethod(method) { + if (this.methods._all) { + return true; + } + let name = typeof method === "string" ? method.toLowerCase() : method; + if (name === "head" && !this.methods.head) { + name = "get"; + } + return Boolean(this.methods[name]); + }; + Route.prototype._methods = function _methods() { + const methods3 = Object.keys(this.methods); + if (this.methods.get && !this.methods.head) { + methods3.push("head"); + } + for (let i5 = 0; i5 < methods3.length; i5++) { + methods3[i5] = methods3[i5].toUpperCase(); + } + return methods3; + }; + Route.prototype.dispatch = function dispatch(req, res, done) { + let idx = 0; + const stack = this.stack; + let sync = 0; + if (stack.length === 0) { + return done(); + } + let method = typeof req.method === "string" ? req.method.toLowerCase() : req.method; + if (method === "head" && !this.methods.head) { + method = "get"; + } + req.route = this; + next(); + function next(err) { + if (err && err === "route") { + return done(); + } + if (err && err === "router") { + return done(err); + } + if (idx >= stack.length) { + return done(err); + } + if (++sync > 100) { + return setImmediate(next, err); + } + let layer; + let match; + while (match !== true && idx < stack.length) { + layer = stack[idx++]; + match = !layer.method || layer.method === method; + } + if (match !== true) { + return done(err); + } + if (err) { + layer.handleError(err, req, res, next); + } else { + layer.handleRequest(req, res, next); + } + sync = 0; + } + }; + Route.prototype.all = function all(handler) { + const callbacks = flatten.call(slice.call(arguments), Infinity); + if (callbacks.length === 0) { + throw new TypeError("argument handler is required"); + } + for (let i5 = 0; i5 < callbacks.length; i5++) { + const fn = callbacks[i5]; + if (typeof fn !== "function") { + throw new TypeError("argument handler must be a function"); + } + const layer = Layer("/", {}, fn); + layer.method = void 0; + this.methods._all = true; + this.stack.push(layer); + } + return this; + }; + methods2.forEach(function(method) { + Route.prototype[method] = function(handler) { + const callbacks = flatten.call(slice.call(arguments), Infinity); + if (callbacks.length === 0) { + throw new TypeError("argument handler is required"); + } + for (let i5 = 0; i5 < callbacks.length; i5++) { + const fn = callbacks[i5]; + if (typeof fn !== "function") { + throw new TypeError("argument handler must be a function"); + } + debug("%s %s", method, this.path); + const layer = Layer("/", {}, fn); + layer.method = method; + this.methods[method] = true; + this.stack.push(layer); + } + return this; + }; + }); + } +}); + +// node_modules/.pnpm/router@2.2.0/node_modules/router/index.js +var require_router = __commonJS({ + "node_modules/.pnpm/router@2.2.0/node_modules/router/index.js"(exports, module) { + "use strict"; + var isPromise2 = require_is_promise(); + var Layer = require_layer(); + var { METHODS } = __require("node:http"); + var parseUrl7 = require_parseurl(); + var Route = require_route(); + var debug = require_src()("router"); + var deprecate2 = require_depd()("router"); + var slice = Array.prototype.slice; + var flatten = Array.prototype.flat; + var methods2 = METHODS.map((method) => method.toLowerCase()); + module.exports = Router26; + module.exports.Route = Route; + function Router26(options) { + if (!(this instanceof Router26)) { + return new Router26(options); + } + const opts = options || {}; + function router2(req, res, next) { + router2.handle(req, res, next); + } + Object.setPrototypeOf(router2, this); + router2.caseSensitive = opts.caseSensitive; + router2.mergeParams = opts.mergeParams; + router2.params = {}; + router2.strict = opts.strict; + router2.stack = []; + return router2; + } + Router26.prototype = function() { + }; + Router26.prototype.param = function param(name, fn) { + if (!name) { + throw new TypeError("argument name is required"); + } + if (typeof name !== "string") { + throw new TypeError("argument name must be a string"); + } + if (!fn) { + throw new TypeError("argument fn is required"); + } + if (typeof fn !== "function") { + throw new TypeError("argument fn must be a function"); + } + let params = this.params[name]; + if (!params) { + params = this.params[name] = []; + } + params.push(fn); + return this; + }; + Router26.prototype.handle = function handle(req, res, callback) { + if (!callback) { + throw new TypeError("argument callback is required"); + } + debug("dispatching %s %s", req.method, req.url); + let idx = 0; + let methods3; + const protohost = getProtohost(req.url) || ""; + let removed = ""; + const self2 = this; + let slashAdded = false; + let sync = 0; + const paramcalled = {}; + const stack = this.stack; + const parentParams = req.params; + const parentUrl = req.baseUrl || ""; + let done = restore(callback, req, "baseUrl", "next", "params"); + req.next = next; + if (req.method === "OPTIONS") { + methods3 = []; + done = wrap4(done, generateOptionsResponder(res, methods3)); + } + req.baseUrl = parentUrl; + req.originalUrl = req.originalUrl || req.url; + next(); + function next(err) { + let layerError = err === "route" ? null : err; + if (slashAdded) { + req.url = req.url.slice(1); + slashAdded = false; + } + if (removed.length !== 0) { + req.baseUrl = parentUrl; + req.url = protohost + removed + req.url.slice(protohost.length); + removed = ""; + } + if (layerError === "router") { + setImmediate(done, null); + return; + } + if (idx >= stack.length) { + setImmediate(done, layerError); + return; + } + if (++sync > 100) { + return setImmediate(next, err); + } + const path53 = getPathname(req); + if (path53 == null) { + return done(layerError); + } + let layer; + let match; + let route; + while (match !== true && idx < stack.length) { + layer = stack[idx++]; + match = matchLayer(layer, path53); + route = layer.route; + if (typeof match !== "boolean") { + layerError = layerError || match; + } + if (match !== true) { + continue; + } + if (!route) { + continue; + } + if (layerError) { + match = false; + continue; + } + const method = req.method; + const hasMethod = route._handlesMethod(method); + if (!hasMethod && method === "OPTIONS" && methods3) { + methods3.push.apply(methods3, route._methods()); + } + if (!hasMethod && method !== "HEAD") { + match = false; + } + } + if (match !== true) { + return done(layerError); + } + if (route) { + req.route = route; + } + req.params = self2.mergeParams ? mergeParams(layer.params, parentParams) : layer.params; + const layerPath = layer.path; + processParams(self2.params, layer, paramcalled, req, res, function(err2) { + if (err2) { + next(layerError || err2); + } else if (route) { + layer.handleRequest(req, res, next); + } else { + trimPrefix(layer, layerError, layerPath, path53); + } + sync = 0; + }); + } + function trimPrefix(layer, layerError, layerPath, path53) { + if (layerPath.length !== 0) { + if (layerPath !== path53.substring(0, layerPath.length)) { + next(layerError); + return; + } + const c5 = path53[layerPath.length]; + if (c5 && c5 !== "/") { + next(layerError); + return; + } + debug("trim prefix (%s) from url %s", layerPath, req.url); + removed = layerPath; + req.url = protohost + req.url.slice(protohost.length + removed.length); + if (!protohost && req.url[0] !== "/") { + req.url = "/" + req.url; + slashAdded = true; + } + req.baseUrl = parentUrl + (removed[removed.length - 1] === "/" ? removed.substring(0, removed.length - 1) : removed); + } + debug("%s %s : %s", layer.name, layerPath, req.originalUrl); + if (layerError) { + layer.handleError(layerError, req, res, next); + } else { + layer.handleRequest(req, res, next); + } + } + }; + Router26.prototype.use = function use2(handler) { + let offset = 0; + let path53 = "/"; + if (typeof handler !== "function") { + let arg = handler; + while (Array.isArray(arg) && arg.length !== 0) { + arg = arg[0]; + } + if (typeof arg !== "function") { + offset = 1; + path53 = handler; + } + } + const callbacks = flatten.call(slice.call(arguments, offset), Infinity); + if (callbacks.length === 0) { + throw new TypeError("argument handler is required"); + } + for (let i5 = 0; i5 < callbacks.length; i5++) { + const fn = callbacks[i5]; + if (typeof fn !== "function") { + throw new TypeError("argument handler must be a function"); + } + debug("use %o %s", path53, fn.name || ""); + const layer = new Layer(path53, { + sensitive: this.caseSensitive, + strict: false, + end: false + }, fn); + layer.route = void 0; + this.stack.push(layer); + } + return this; + }; + Router26.prototype.route = function route(path53) { + const route2 = new Route(path53); + const layer = new Layer(path53, { + sensitive: this.caseSensitive, + strict: this.strict, + end: true + }, handle); + function handle(req, res, next) { + route2.dispatch(req, res, next); + } + layer.route = route2; + this.stack.push(layer); + return route2; + }; + methods2.concat("all").forEach(function(method) { + Router26.prototype[method] = function(path53) { + const route = this.route(path53); + route[method].apply(route, slice.call(arguments, 1)); + return this; + }; + }); + function generateOptionsResponder(res, methods3) { + return function onDone(fn, err) { + if (err || methods3.length === 0) { + return fn(err); + } + trySendOptionsResponse(res, methods3, fn); + }; + } + function getPathname(req) { + try { + return parseUrl7(req).pathname; + } catch (err) { + return void 0; + } + } + function getProtohost(url2) { + if (typeof url2 !== "string" || url2.length === 0 || url2[0] === "/") { + return void 0; + } + const searchIndex = url2.indexOf("?"); + const pathLength = searchIndex !== -1 ? searchIndex : url2.length; + const fqdnIndex = url2.substring(0, pathLength).indexOf("://"); + return fqdnIndex !== -1 ? url2.substring(0, url2.indexOf("/", 3 + fqdnIndex)) : void 0; + } + function matchLayer(layer, path53) { + try { + return layer.match(path53); + } catch (err) { + return err; + } + } + function mergeParams(params, parent) { + if (typeof parent !== "object" || !parent) { + return params; + } + const obj = Object.assign({}, parent); + if (!(0 in params) || !(0 in parent)) { + return Object.assign(obj, params); + } + let i5 = 0; + let o5 = 0; + while (i5 in params) { + i5++; + } + while (o5 in parent) { + o5++; + } + for (i5--; i5 >= 0; i5--) { + params[i5 + o5] = params[i5]; + if (i5 < o5) { + delete params[i5]; + } + } + return Object.assign(obj, params); + } + function processParams(params, layer, called, req, res, done) { + const keys = layer.keys; + if (!keys || keys.length === 0) { + return done(); + } + let i5 = 0; + let paramIndex = 0; + let key; + let paramVal; + let paramCallbacks; + let paramCalled; + function param(err) { + if (err) { + return done(err); + } + if (i5 >= keys.length) { + return done(); + } + paramIndex = 0; + key = keys[i5++]; + paramVal = req.params[key]; + paramCallbacks = params[key]; + paramCalled = called[key]; + if (paramVal === void 0 || !paramCallbacks) { + return param(); + } + if (paramCalled && (paramCalled.match === paramVal || paramCalled.error && paramCalled.error !== "route")) { + req.params[key] = paramCalled.value; + return param(paramCalled.error); + } + called[key] = paramCalled = { + error: null, + match: paramVal, + value: paramVal + }; + paramCallback(); + } + function paramCallback(err) { + const fn = paramCallbacks[paramIndex++]; + paramCalled.value = req.params[key]; + if (err) { + paramCalled.error = err; + param(err); + return; + } + if (!fn) return param(); + try { + const ret = fn(req, res, paramCallback, paramVal, key); + if (isPromise2(ret)) { + if (!(ret instanceof Promise)) { + deprecate2("parameters that are Promise-like are deprecated, use a native Promise instead"); + } + ret.then(null, function(error50) { + paramCallback(error50 || new Error("Rejected promise")); + }); + } + } catch (e5) { + paramCallback(e5); + } + } + param(); + } + function restore(fn, obj) { + const props = new Array(arguments.length - 2); + const vals = new Array(arguments.length - 2); + for (let i5 = 0; i5 < props.length; i5++) { + props[i5] = arguments[i5 + 2]; + vals[i5] = obj[props[i5]]; + } + return function() { + for (let i5 = 0; i5 < props.length; i5++) { + obj[props[i5]] = vals[i5]; + } + return fn.apply(this, arguments); + }; + } + function sendOptionsResponse(res, methods3) { + const options = /* @__PURE__ */ Object.create(null); + for (let i5 = 0; i5 < methods3.length; i5++) { + options[methods3[i5]] = true; + } + const allow = Object.keys(options).sort().join(", "); + res.setHeader("Allow", allow); + res.setHeader("Content-Length", Buffer.byteLength(allow)); + res.setHeader("Content-Type", "text/plain"); + res.setHeader("X-Content-Type-Options", "nosniff"); + res.end(allow); + } + function trySendOptionsResponse(res, methods3, next) { + try { + sendOptionsResponse(res, methods3); + } catch (err) { + next(err); + } + } + function wrap4(old, fn) { + return function proxy() { + const args = new Array(arguments.length + 1); + args[0] = old; + for (let i5 = 0, len = arguments.length; i5 < len; i5++) { + args[i5 + 1] = arguments[i5]; + } + fn.apply(this, args); + }; + } + } +}); + +// node_modules/.pnpm/express@5.2.1/node_modules/express/lib/application.js +var require_application = __commonJS({ + "node_modules/.pnpm/express@5.2.1/node_modules/express/lib/application.js"(exports, module) { + "use strict"; + var finalhandler = require_finalhandler(); + var debug = require_src()("express:application"); + var View2 = require_view(); + var http = __require("node:http"); + var methods2 = require_utils3().methods; + var compileETag = require_utils3().compileETag; + var compileQueryParser = require_utils3().compileQueryParser; + var compileTrust = require_utils3().compileTrust; + var resolve4 = __require("node:path").resolve; + var once = require_once(); + var Router26 = require_router(); + var slice = Array.prototype.slice; + var flatten = Array.prototype.flat; + var app = exports = module.exports = {}; + var trustProxyDefaultSymbol = "@@symbol:trust_proxy_default"; + app.init = function init2() { + var router2 = null; + this.cache = /* @__PURE__ */ Object.create(null); + this.engines = /* @__PURE__ */ Object.create(null); + this.settings = /* @__PURE__ */ Object.create(null); + this.defaultConfiguration(); + Object.defineProperty(this, "router", { + configurable: true, + enumerable: true, + get: function getrouter() { + if (router2 === null) { + router2 = new Router26({ + caseSensitive: this.enabled("case sensitive routing"), + strict: this.enabled("strict routing") + }); + } + return router2; + } + }); + }; + app.defaultConfiguration = function defaultConfiguration() { + var env2 = "production"; + this.enable("x-powered-by"); + this.set("etag", "weak"); + this.set("env", env2); + this.set("query parser", "simple"); + this.set("subdomain offset", 2); + this.set("trust proxy", false); + Object.defineProperty(this.settings, trustProxyDefaultSymbol, { + configurable: true, + value: true + }); + debug("booting in %s mode", env2); + this.on("mount", function onmount(parent) { + if (this.settings[trustProxyDefaultSymbol] === true && typeof parent.settings["trust proxy fn"] === "function") { + delete this.settings["trust proxy"]; + delete this.settings["trust proxy fn"]; + } + Object.setPrototypeOf(this.request, parent.request); + Object.setPrototypeOf(this.response, parent.response); + Object.setPrototypeOf(this.engines, parent.engines); + Object.setPrototypeOf(this.settings, parent.settings); + }); + this.locals = /* @__PURE__ */ Object.create(null); + this.mountpath = "/"; + this.locals.settings = this.settings; + this.set("view", View2); + this.set("views", resolve4("views")); + this.set("jsonp callback name", "callback"); + if (env2 === "production") { + this.enable("view cache"); + } + }; + app.handle = function handle(req, res, callback) { + var done = callback || finalhandler(req, res, { + env: this.get("env"), + onerror: logerror.bind(this) + }); + if (this.enabled("x-powered-by")) { + res.setHeader("X-Powered-By", "Express"); + } + req.res = res; + res.req = req; + Object.setPrototypeOf(req, this.request); + Object.setPrototypeOf(res, this.response); + if (!res.locals) { + res.locals = /* @__PURE__ */ Object.create(null); + } + this.router.handle(req, res, done); + }; + app.use = function use2(fn) { + var offset = 0; + var path53 = "/"; + if (typeof fn !== "function") { + var arg = fn; + while (Array.isArray(arg) && arg.length !== 0) { + arg = arg[0]; + } + if (typeof arg !== "function") { + offset = 1; + path53 = fn; + } + } + var fns = flatten.call(slice.call(arguments, offset), Infinity); + if (fns.length === 0) { + throw new TypeError("app.use() requires a middleware function"); + } + var router2 = this.router; + fns.forEach(function(fn2) { + if (!fn2 || !fn2.handle || !fn2.set) { + return router2.use(path53, fn2); + } + debug(".use app under %s", path53); + fn2.mountpath = path53; + fn2.parent = this; + router2.use(path53, function mounted_app(req, res, next) { + var orig = req.app; + fn2.handle(req, res, function(err) { + Object.setPrototypeOf(req, orig.request); + Object.setPrototypeOf(res, orig.response); + next(err); + }); + }); + fn2.emit("mount", this); + }, this); + return this; + }; + app.route = function route(path53) { + return this.router.route(path53); + }; + app.engine = function engine(ext, fn) { + if (typeof fn !== "function") { + throw new Error("callback function required"); + } + var extension2 = ext[0] !== "." ? "." + ext : ext; + this.engines[extension2] = fn; + return this; + }; + app.param = function param(name, fn) { + if (Array.isArray(name)) { + for (var i5 = 0; i5 < name.length; i5++) { + this.param(name[i5], fn); + } + return this; + } + this.router.param(name, fn); + return this; + }; + app.set = function set2(setting, val) { + if (arguments.length === 1) { + return this.settings[setting]; + } + debug('set "%s" to %o', setting, val); + this.settings[setting] = val; + switch (setting) { + case "etag": + this.set("etag fn", compileETag(val)); + break; + case "query parser": + this.set("query parser fn", compileQueryParser(val)); + break; + case "trust proxy": + this.set("trust proxy fn", compileTrust(val)); + Object.defineProperty(this.settings, trustProxyDefaultSymbol, { + configurable: true, + value: false + }); + break; + } + return this; + }; + app.path = function path53() { + return this.parent ? this.parent.path() + this.mountpath : ""; + }; + app.enabled = function enabled(setting) { + return Boolean(this.set(setting)); + }; + app.disabled = function disabled(setting) { + return !this.set(setting); + }; + app.enable = function enable(setting) { + return this.set(setting, true); + }; + app.disable = function disable(setting) { + return this.set(setting, false); + }; + methods2.forEach(function(method) { + app[method] = function(path53) { + if (method === "get" && arguments.length === 1) { + return this.set(path53); + } + var route = this.route(path53); + route[method].apply(route, slice.call(arguments, 1)); + return this; + }; + }); + app.all = function all(path53) { + var route = this.route(path53); + var args = slice.call(arguments, 1); + for (var i5 = 0; i5 < methods2.length; i5++) { + route[methods2[i5]].apply(route, args); + } + return this; + }; + app.render = function render(name, options, callback) { + var cache7 = this.cache; + var done = callback; + var engines = this.engines; + var opts = options; + var view; + if (typeof options === "function") { + done = options; + opts = {}; + } + var renderOptions = { ...this.locals, ...opts._locals, ...opts }; + if (renderOptions.cache == null) { + renderOptions.cache = this.enabled("view cache"); + } + if (renderOptions.cache) { + view = cache7[name]; + } + if (!view) { + var View3 = this.get("view"); + view = new View3(name, { + defaultEngine: this.get("view engine"), + root: this.get("views"), + engines + }); + if (!view.path) { + var dirs = Array.isArray(view.root) && view.root.length > 1 ? 'directories "' + view.root.slice(0, -1).join('", "') + '" or "' + view.root[view.root.length - 1] + '"' : 'directory "' + view.root + '"'; + var err = new Error('Failed to lookup view "' + name + '" in views ' + dirs); + err.view = view; + return done(err); + } + if (renderOptions.cache) { + cache7[name] = view; + } + } + tryRender(view, renderOptions, done); + }; + app.listen = function listen() { + var server = http.createServer(this); + var args = slice.call(arguments); + if (typeof args[args.length - 1] === "function") { + var done = args[args.length - 1] = once(args[args.length - 1]); + server.once("error", done); + } + return server.listen.apply(server, args); + }; + function logerror(err) { + if (this.get("env") !== "test") console.error(err.stack || err.toString()); + } + function tryRender(view, options, callback) { + try { + view.render(options, callback); + } catch (err) { + callback(err); + } + } + } +}); + +// node_modules/.pnpm/negotiator@1.0.0/node_modules/negotiator/lib/charset.js +var require_charset = __commonJS({ + "node_modules/.pnpm/negotiator@1.0.0/node_modules/negotiator/lib/charset.js"(exports, module) { + "use strict"; + module.exports = preferredCharsets; + module.exports.preferredCharsets = preferredCharsets; + var simpleCharsetRegExp = /^\s*([^\s;]+)\s*(?:;(.*))?$/; + function parseAcceptCharset(accept) { + var accepts = accept.split(","); + for (var i5 = 0, j5 = 0; i5 < accepts.length; i5++) { + var charset = parseCharset(accepts[i5].trim(), i5); + if (charset) { + accepts[j5++] = charset; + } + } + accepts.length = j5; + return accepts; + } + function parseCharset(str, i5) { + var match = simpleCharsetRegExp.exec(str); + if (!match) return null; + var charset = match[1]; + var q5 = 1; + if (match[2]) { + var params = match[2].split(";"); + for (var j5 = 0; j5 < params.length; j5++) { + var p5 = params[j5].trim().split("="); + if (p5[0] === "q") { + q5 = parseFloat(p5[1]); + break; + } + } + } + return { + charset, + q: q5, + i: i5 + }; + } + function getCharsetPriority(charset, accepted, index2) { + var priority = { o: -1, q: 0, s: 0 }; + for (var i5 = 0; i5 < accepted.length; i5++) { + var spec = specify(charset, accepted[i5], index2); + if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { + priority = spec; + } + } + return priority; + } + function specify(charset, spec, index2) { + var s5 = 0; + if (spec.charset.toLowerCase() === charset.toLowerCase()) { + s5 |= 1; + } else if (spec.charset !== "*") { + return null; + } + return { + i: index2, + o: spec.i, + q: spec.q, + s: s5 + }; + } + function preferredCharsets(accept, provided) { + var accepts = parseAcceptCharset(accept === void 0 ? "*" : accept || ""); + if (!provided) { + return accepts.filter(isQuality).sort(compareSpecs).map(getFullCharset); + } + var priorities = provided.map(function getPriority(type, index2) { + return getCharsetPriority(type, accepts, index2); + }); + return priorities.filter(isQuality).sort(compareSpecs).map(function getCharset(priority) { + return provided[priorities.indexOf(priority)]; + }); + } + function compareSpecs(a5, b6) { + return b6.q - a5.q || b6.s - a5.s || a5.o - b6.o || a5.i - b6.i || 0; + } + function getFullCharset(spec) { + return spec.charset; + } + function isQuality(spec) { + return spec.q > 0; + } + } +}); + +// node_modules/.pnpm/negotiator@1.0.0/node_modules/negotiator/lib/encoding.js +var require_encoding = __commonJS({ + "node_modules/.pnpm/negotiator@1.0.0/node_modules/negotiator/lib/encoding.js"(exports, module) { + "use strict"; + module.exports = preferredEncodings; + module.exports.preferredEncodings = preferredEncodings; + var simpleEncodingRegExp = /^\s*([^\s;]+)\s*(?:;(.*))?$/; + function parseAcceptEncoding(accept) { + var accepts = accept.split(","); + var hasIdentity = false; + var minQuality = 1; + for (var i5 = 0, j5 = 0; i5 < accepts.length; i5++) { + var encoding = parseEncoding(accepts[i5].trim(), i5); + if (encoding) { + accepts[j5++] = encoding; + hasIdentity = hasIdentity || specify("identity", encoding); + minQuality = Math.min(minQuality, encoding.q || 1); + } + } + if (!hasIdentity) { + accepts[j5++] = { + encoding: "identity", + q: minQuality, + i: i5 + }; + } + accepts.length = j5; + return accepts; + } + function parseEncoding(str, i5) { + var match = simpleEncodingRegExp.exec(str); + if (!match) return null; + var encoding = match[1]; + var q5 = 1; + if (match[2]) { + var params = match[2].split(";"); + for (var j5 = 0; j5 < params.length; j5++) { + var p5 = params[j5].trim().split("="); + if (p5[0] === "q") { + q5 = parseFloat(p5[1]); + break; + } + } + } + return { + encoding, + q: q5, + i: i5 + }; + } + function getEncodingPriority(encoding, accepted, index2) { + var priority = { encoding, o: -1, q: 0, s: 0 }; + for (var i5 = 0; i5 < accepted.length; i5++) { + var spec = specify(encoding, accepted[i5], index2); + if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { + priority = spec; + } + } + return priority; + } + function specify(encoding, spec, index2) { + var s5 = 0; + if (spec.encoding.toLowerCase() === encoding.toLowerCase()) { + s5 |= 1; + } else if (spec.encoding !== "*") { + return null; + } + return { + encoding, + i: index2, + o: spec.i, + q: spec.q, + s: s5 + }; + } + function preferredEncodings(accept, provided, preferred) { + var accepts = parseAcceptEncoding(accept || ""); + var comparator = preferred ? function comparator2(a5, b6) { + if (a5.q !== b6.q) { + return b6.q - a5.q; + } + var aPreferred = preferred.indexOf(a5.encoding); + var bPreferred = preferred.indexOf(b6.encoding); + if (aPreferred === -1 && bPreferred === -1) { + return b6.s - a5.s || a5.o - b6.o || a5.i - b6.i; + } + if (aPreferred !== -1 && bPreferred !== -1) { + return aPreferred - bPreferred; + } + return aPreferred === -1 ? 1 : -1; + } : compareSpecs; + if (!provided) { + return accepts.filter(isQuality).sort(comparator).map(getFullEncoding); + } + var priorities = provided.map(function getPriority(type, index2) { + return getEncodingPriority(type, accepts, index2); + }); + return priorities.filter(isQuality).sort(comparator).map(function getEncoding(priority) { + return provided[priorities.indexOf(priority)]; + }); + } + function compareSpecs(a5, b6) { + return b6.q - a5.q || b6.s - a5.s || a5.o - b6.o || a5.i - b6.i; + } + function getFullEncoding(spec) { + return spec.encoding; + } + function isQuality(spec) { + return spec.q > 0; + } + } +}); + +// node_modules/.pnpm/negotiator@1.0.0/node_modules/negotiator/lib/language.js +var require_language = __commonJS({ + "node_modules/.pnpm/negotiator@1.0.0/node_modules/negotiator/lib/language.js"(exports, module) { + "use strict"; + module.exports = preferredLanguages; + module.exports.preferredLanguages = preferredLanguages; + var simpleLanguageRegExp = /^\s*([^\s\-;]+)(?:-([^\s;]+))?\s*(?:;(.*))?$/; + function parseAcceptLanguage(accept) { + var accepts = accept.split(","); + for (var i5 = 0, j5 = 0; i5 < accepts.length; i5++) { + var language = parseLanguage(accepts[i5].trim(), i5); + if (language) { + accepts[j5++] = language; + } + } + accepts.length = j5; + return accepts; + } + function parseLanguage(str, i5) { + var match = simpleLanguageRegExp.exec(str); + if (!match) return null; + var prefix = match[1]; + var suffix = match[2]; + var full = prefix; + if (suffix) full += "-" + suffix; + var q5 = 1; + if (match[3]) { + var params = match[3].split(";"); + for (var j5 = 0; j5 < params.length; j5++) { + var p5 = params[j5].split("="); + if (p5[0] === "q") q5 = parseFloat(p5[1]); + } + } + return { + prefix, + suffix, + q: q5, + i: i5, + full + }; + } + function getLanguagePriority(language, accepted, index2) { + var priority = { o: -1, q: 0, s: 0 }; + for (var i5 = 0; i5 < accepted.length; i5++) { + var spec = specify(language, accepted[i5], index2); + if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { + priority = spec; + } + } + return priority; + } + function specify(language, spec, index2) { + var p5 = parseLanguage(language); + if (!p5) return null; + var s5 = 0; + if (spec.full.toLowerCase() === p5.full.toLowerCase()) { + s5 |= 4; + } else if (spec.prefix.toLowerCase() === p5.full.toLowerCase()) { + s5 |= 2; + } else if (spec.full.toLowerCase() === p5.prefix.toLowerCase()) { + s5 |= 1; + } else if (spec.full !== "*") { + return null; + } + return { + i: index2, + o: spec.i, + q: spec.q, + s: s5 + }; + } + function preferredLanguages(accept, provided) { + var accepts = parseAcceptLanguage(accept === void 0 ? "*" : accept || ""); + if (!provided) { + return accepts.filter(isQuality).sort(compareSpecs).map(getFullLanguage); + } + var priorities = provided.map(function getPriority(type, index2) { + return getLanguagePriority(type, accepts, index2); + }); + return priorities.filter(isQuality).sort(compareSpecs).map(function getLanguage(priority) { + return provided[priorities.indexOf(priority)]; + }); + } + function compareSpecs(a5, b6) { + return b6.q - a5.q || b6.s - a5.s || a5.o - b6.o || a5.i - b6.i || 0; + } + function getFullLanguage(spec) { + return spec.full; + } + function isQuality(spec) { + return spec.q > 0; + } + } +}); + +// node_modules/.pnpm/negotiator@1.0.0/node_modules/negotiator/lib/mediaType.js +var require_mediaType = __commonJS({ + "node_modules/.pnpm/negotiator@1.0.0/node_modules/negotiator/lib/mediaType.js"(exports, module) { + "use strict"; + module.exports = preferredMediaTypes; + module.exports.preferredMediaTypes = preferredMediaTypes; + var simpleMediaTypeRegExp = /^\s*([^\s\/;]+)\/([^;\s]+)\s*(?:;(.*))?$/; + function parseAccept(accept) { + var accepts = splitMediaTypes(accept); + for (var i5 = 0, j5 = 0; i5 < accepts.length; i5++) { + var mediaType = parseMediaType(accepts[i5].trim(), i5); + if (mediaType) { + accepts[j5++] = mediaType; + } + } + accepts.length = j5; + return accepts; + } + function parseMediaType(str, i5) { + var match = simpleMediaTypeRegExp.exec(str); + if (!match) return null; + var params = /* @__PURE__ */ Object.create(null); + var q5 = 1; + var subtype = match[2]; + var type = match[1]; + if (match[3]) { + var kvps = splitParameters(match[3]).map(splitKeyValuePair); + for (var j5 = 0; j5 < kvps.length; j5++) { + var pair = kvps[j5]; + var key = pair[0].toLowerCase(); + var val = pair[1]; + var value = val && val[0] === '"' && val[val.length - 1] === '"' ? val.slice(1, -1) : val; + if (key === "q") { + q5 = parseFloat(value); + break; + } + params[key] = value; + } + } + return { + type, + subtype, + params, + q: q5, + i: i5 + }; + } + function getMediaTypePriority(type, accepted, index2) { + var priority = { o: -1, q: 0, s: 0 }; + for (var i5 = 0; i5 < accepted.length; i5++) { + var spec = specify(type, accepted[i5], index2); + if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { + priority = spec; + } + } + return priority; + } + function specify(type, spec, index2) { + var p5 = parseMediaType(type); + var s5 = 0; + if (!p5) { + return null; + } + if (spec.type.toLowerCase() == p5.type.toLowerCase()) { + s5 |= 4; + } else if (spec.type != "*") { + return null; + } + if (spec.subtype.toLowerCase() == p5.subtype.toLowerCase()) { + s5 |= 2; + } else if (spec.subtype != "*") { + return null; + } + var keys = Object.keys(spec.params); + if (keys.length > 0) { + if (keys.every(function(k5) { + return spec.params[k5] == "*" || (spec.params[k5] || "").toLowerCase() == (p5.params[k5] || "").toLowerCase(); + })) { + s5 |= 1; + } else { + return null; + } + } + return { + i: index2, + o: spec.i, + q: spec.q, + s: s5 + }; + } + function preferredMediaTypes(accept, provided) { + var accepts = parseAccept(accept === void 0 ? "*/*" : accept || ""); + if (!provided) { + return accepts.filter(isQuality).sort(compareSpecs).map(getFullType); + } + var priorities = provided.map(function getPriority(type, index2) { + return getMediaTypePriority(type, accepts, index2); + }); + return priorities.filter(isQuality).sort(compareSpecs).map(function getType(priority) { + return provided[priorities.indexOf(priority)]; + }); + } + function compareSpecs(a5, b6) { + return b6.q - a5.q || b6.s - a5.s || a5.o - b6.o || a5.i - b6.i || 0; + } + function getFullType(spec) { + return spec.type + "/" + spec.subtype; + } + function isQuality(spec) { + return spec.q > 0; + } + function quoteCount(string4) { + var count2 = 0; + var index2 = 0; + while ((index2 = string4.indexOf('"', index2)) !== -1) { + count2++; + index2++; + } + return count2; + } + function splitKeyValuePair(str) { + var index2 = str.indexOf("="); + var key; + var val; + if (index2 === -1) { + key = str; + } else { + key = str.slice(0, index2); + val = str.slice(index2 + 1); + } + return [key, val]; + } + function splitMediaTypes(accept) { + var accepts = accept.split(","); + for (var i5 = 1, j5 = 0; i5 < accepts.length; i5++) { + if (quoteCount(accepts[j5]) % 2 == 0) { + accepts[++j5] = accepts[i5]; + } else { + accepts[j5] += "," + accepts[i5]; + } + } + accepts.length = j5 + 1; + return accepts; + } + function splitParameters(str) { + var parameters = str.split(";"); + for (var i5 = 1, j5 = 0; i5 < parameters.length; i5++) { + if (quoteCount(parameters[j5]) % 2 == 0) { + parameters[++j5] = parameters[i5]; + } else { + parameters[j5] += ";" + parameters[i5]; + } + } + parameters.length = j5 + 1; + for (var i5 = 0; i5 < parameters.length; i5++) { + parameters[i5] = parameters[i5].trim(); + } + return parameters; + } + } +}); + +// node_modules/.pnpm/negotiator@1.0.0/node_modules/negotiator/index.js +var require_negotiator = __commonJS({ + "node_modules/.pnpm/negotiator@1.0.0/node_modules/negotiator/index.js"(exports, module) { + "use strict"; + var preferredCharsets = require_charset(); + var preferredEncodings = require_encoding(); + var preferredLanguages = require_language(); + var preferredMediaTypes = require_mediaType(); + module.exports = Negotiator; + module.exports.Negotiator = Negotiator; + function Negotiator(request) { + if (!(this instanceof Negotiator)) { + return new Negotiator(request); + } + this.request = request; + } + Negotiator.prototype.charset = function charset(available) { + var set2 = this.charsets(available); + return set2 && set2[0]; + }; + Negotiator.prototype.charsets = function charsets(available) { + return preferredCharsets(this.request.headers["accept-charset"], available); + }; + Negotiator.prototype.encoding = function encoding(available, opts) { + var set2 = this.encodings(available, opts); + return set2 && set2[0]; + }; + Negotiator.prototype.encodings = function encodings(available, options) { + var opts = options || {}; + return preferredEncodings(this.request.headers["accept-encoding"], available, opts.preferred); + }; + Negotiator.prototype.language = function language(available) { + var set2 = this.languages(available); + return set2 && set2[0]; + }; + Negotiator.prototype.languages = function languages(available) { + return preferredLanguages(this.request.headers["accept-language"], available); + }; + Negotiator.prototype.mediaType = function mediaType(available) { + var set2 = this.mediaTypes(available); + return set2 && set2[0]; + }; + Negotiator.prototype.mediaTypes = function mediaTypes(available) { + return preferredMediaTypes(this.request.headers.accept, available); + }; + Negotiator.prototype.preferredCharset = Negotiator.prototype.charset; + Negotiator.prototype.preferredCharsets = Negotiator.prototype.charsets; + Negotiator.prototype.preferredEncoding = Negotiator.prototype.encoding; + Negotiator.prototype.preferredEncodings = Negotiator.prototype.encodings; + Negotiator.prototype.preferredLanguage = Negotiator.prototype.language; + Negotiator.prototype.preferredLanguages = Negotiator.prototype.languages; + Negotiator.prototype.preferredMediaType = Negotiator.prototype.mediaType; + Negotiator.prototype.preferredMediaTypes = Negotiator.prototype.mediaTypes; + } +}); + +// node_modules/.pnpm/accepts@2.0.0/node_modules/accepts/index.js +var require_accepts = __commonJS({ + "node_modules/.pnpm/accepts@2.0.0/node_modules/accepts/index.js"(exports, module) { + "use strict"; + var Negotiator = require_negotiator(); + var mime = require_mime_types(); + module.exports = Accepts; + function Accepts(req) { + if (!(this instanceof Accepts)) { + return new Accepts(req); + } + this.headers = req.headers; + this.negotiator = new Negotiator(req); + } + Accepts.prototype.type = Accepts.prototype.types = function(types_) { + var types2 = types_; + if (types2 && !Array.isArray(types2)) { + types2 = new Array(arguments.length); + for (var i5 = 0; i5 < types2.length; i5++) { + types2[i5] = arguments[i5]; + } + } + if (!types2 || types2.length === 0) { + return this.negotiator.mediaTypes(); + } + if (!this.headers.accept) { + return types2[0]; + } + var mimes = types2.map(extToMime); + var accepts = this.negotiator.mediaTypes(mimes.filter(validMime)); + var first = accepts[0]; + return first ? types2[mimes.indexOf(first)] : false; + }; + Accepts.prototype.encoding = Accepts.prototype.encodings = function(encodings_) { + var encodings = encodings_; + if (encodings && !Array.isArray(encodings)) { + encodings = new Array(arguments.length); + for (var i5 = 0; i5 < encodings.length; i5++) { + encodings[i5] = arguments[i5]; + } + } + if (!encodings || encodings.length === 0) { + return this.negotiator.encodings(); + } + return this.negotiator.encodings(encodings)[0] || false; + }; + Accepts.prototype.charset = Accepts.prototype.charsets = function(charsets_) { + var charsets = charsets_; + if (charsets && !Array.isArray(charsets)) { + charsets = new Array(arguments.length); + for (var i5 = 0; i5 < charsets.length; i5++) { + charsets[i5] = arguments[i5]; + } + } + if (!charsets || charsets.length === 0) { + return this.negotiator.charsets(); + } + return this.negotiator.charsets(charsets)[0] || false; + }; + Accepts.prototype.lang = Accepts.prototype.langs = Accepts.prototype.language = Accepts.prototype.languages = function(languages_) { + var languages = languages_; + if (languages && !Array.isArray(languages)) { + languages = new Array(arguments.length); + for (var i5 = 0; i5 < languages.length; i5++) { + languages[i5] = arguments[i5]; + } + } + if (!languages || languages.length === 0) { + return this.negotiator.languages(); + } + return this.negotiator.languages(languages)[0] || false; + }; + function extToMime(type) { + return type.indexOf("/") === -1 ? mime.lookup(type) : type; + } + function validMime(type) { + return typeof type === "string"; + } + } +}); + +// node_modules/.pnpm/fresh@2.0.0/node_modules/fresh/index.js +var require_fresh = __commonJS({ + "node_modules/.pnpm/fresh@2.0.0/node_modules/fresh/index.js"(exports, module) { + "use strict"; + var CACHE_CONTROL_NO_CACHE_REGEXP = /(?:^|,)\s*?no-cache\s*?(?:,|$)/; + module.exports = fresh; + function fresh(reqHeaders, resHeaders) { + var modifiedSince = reqHeaders["if-modified-since"]; + var noneMatch = reqHeaders["if-none-match"]; + if (!modifiedSince && !noneMatch) { + return false; + } + var cacheControl = reqHeaders["cache-control"]; + if (cacheControl && CACHE_CONTROL_NO_CACHE_REGEXP.test(cacheControl)) { + return false; + } + if (noneMatch) { + if (noneMatch === "*") { + return true; + } + var etag = resHeaders.etag; + if (!etag) { + return false; + } + var matches = parseTokenList(noneMatch); + for (var i5 = 0; i5 < matches.length; i5++) { + var match = matches[i5]; + if (match === etag || match === "W/" + etag || "W/" + match === etag) { + return true; + } + } + return false; + } + if (modifiedSince) { + var lastModified = resHeaders["last-modified"]; + var modifiedStale = !lastModified || !(parseHttpDate(lastModified) <= parseHttpDate(modifiedSince)); + if (modifiedStale) { + return false; + } + } + return true; + } + function parseHttpDate(date7) { + var timestamp2 = date7 && Date.parse(date7); + return typeof timestamp2 === "number" ? timestamp2 : NaN; + } + function parseTokenList(str) { + var end = 0; + var list2 = []; + var start = 0; + for (var i5 = 0, len = str.length; i5 < len; i5++) { + switch (str.charCodeAt(i5)) { + case 32: + if (start === end) { + start = end = i5 + 1; + } + break; + case 44: + list2.push(str.substring(start, end)); + start = end = i5 + 1; + break; + default: + end = i5 + 1; + break; + } + } + list2.push(str.substring(start, end)); + return list2; + } + } +}); + +// node_modules/.pnpm/range-parser@1.2.1/node_modules/range-parser/index.js +var require_range_parser = __commonJS({ + "node_modules/.pnpm/range-parser@1.2.1/node_modules/range-parser/index.js"(exports, module) { + "use strict"; + module.exports = rangeParser; + function rangeParser(size2, str, options) { + if (typeof str !== "string") { + throw new TypeError("argument str must be a string"); + } + var index2 = str.indexOf("="); + if (index2 === -1) { + return -2; + } + var arr = str.slice(index2 + 1).split(","); + var ranges = []; + ranges.type = str.slice(0, index2); + for (var i5 = 0; i5 < arr.length; i5++) { + var range2 = arr[i5].split("-"); + var start = parseInt(range2[0], 10); + var end = parseInt(range2[1], 10); + if (isNaN(start)) { + start = size2 - end; + end = size2 - 1; + } else if (isNaN(end)) { + end = size2 - 1; + } + if (end > size2 - 1) { + end = size2 - 1; + } + if (isNaN(start) || isNaN(end) || start > end || start < 0) { + continue; + } + ranges.push({ + start, + end + }); + } + if (ranges.length < 1) { + return -1; + } + return options && options.combine ? combineRanges(ranges) : ranges; + } + function combineRanges(ranges) { + var ordered = ranges.map(mapWithIndex).sort(sortByRangeStart); + for (var j5 = 0, i5 = 1; i5 < ordered.length; i5++) { + var range2 = ordered[i5]; + var current = ordered[j5]; + if (range2.start > current.end + 1) { + ordered[++j5] = range2; + } else if (range2.end > current.end) { + current.end = range2.end; + current.index = Math.min(current.index, range2.index); + } + } + ordered.length = j5 + 1; + var combined = ordered.sort(sortByRangeIndex).map(mapWithoutIndex); + combined.type = ranges.type; + return combined; + } + function mapWithIndex(range2, index2) { + return { + start: range2.start, + end: range2.end, + index: index2 + }; + } + function mapWithoutIndex(range2) { + return { + start: range2.start, + end: range2.end + }; + } + function sortByRangeIndex(a5, b6) { + return a5.index - b6.index; + } + function sortByRangeStart(a5, b6) { + return a5.start - b6.start; + } + } +}); + +// node_modules/.pnpm/express@5.2.1/node_modules/express/lib/request.js +var require_request = __commonJS({ + "node_modules/.pnpm/express@5.2.1/node_modules/express/lib/request.js"(exports, module) { + "use strict"; + var accepts = require_accepts(); + var isIP2 = __require("node:net").isIP; + var typeis = require_type_is(); + var http = __require("node:http"); + var fresh = require_fresh(); + var parseRange = require_range_parser(); + var parse5 = require_parseurl(); + var proxyaddr = require_proxy_addr(); + var req = Object.create(http.IncomingMessage.prototype); + module.exports = req; + req.get = req.header = function header(name) { + if (!name) { + throw new TypeError("name argument is required to req.get"); + } + if (typeof name !== "string") { + throw new TypeError("name must be a string to req.get"); + } + var lc = name.toLowerCase(); + switch (lc) { + case "referer": + case "referrer": + return this.headers.referrer || this.headers.referer; + default: + return this.headers[lc]; + } + }; + req.accepts = function() { + var accept = accepts(this); + return accept.types.apply(accept, arguments); + }; + req.acceptsEncodings = function() { + var accept = accepts(this); + return accept.encodings.apply(accept, arguments); + }; + req.acceptsCharsets = function() { + var accept = accepts(this); + return accept.charsets.apply(accept, arguments); + }; + req.acceptsLanguages = function(...languages) { + return accepts(this).languages(...languages); + }; + req.range = function range2(size2, options) { + var range3 = this.get("Range"); + if (!range3) return; + return parseRange(size2, range3, options); + }; + defineGetter(req, "query", function query() { + var queryparse = this.app.get("query parser fn"); + if (!queryparse) { + return /* @__PURE__ */ Object.create(null); + } + var querystring = parse5(this).query; + return queryparse(querystring); + }); + req.is = function is2(types2) { + var arr = types2; + if (!Array.isArray(types2)) { + arr = new Array(arguments.length); + for (var i5 = 0; i5 < arr.length; i5++) { + arr[i5] = arguments[i5]; + } + } + return typeis(this, arr); + }; + defineGetter(req, "protocol", function protocol() { + var proto = this.socket.encrypted ? "https" : "http"; + var trust = this.app.get("trust proxy fn"); + if (!trust(this.socket.remoteAddress, 0)) { + return proto; + } + var header = this.get("X-Forwarded-Proto") || proto; + var index2 = header.indexOf(","); + return index2 !== -1 ? header.substring(0, index2).trim() : header.trim(); + }); + defineGetter(req, "secure", function secure() { + return this.protocol === "https"; + }); + defineGetter(req, "ip", function ip() { + var trust = this.app.get("trust proxy fn"); + return proxyaddr(this, trust); + }); + defineGetter(req, "ips", function ips() { + var trust = this.app.get("trust proxy fn"); + var addrs = proxyaddr.all(this, trust); + addrs.reverse().pop(); + return addrs; + }); + defineGetter(req, "subdomains", function subdomains() { + var hostname3 = this.hostname; + if (!hostname3) return []; + var offset = this.app.get("subdomain offset"); + var subdomains2 = !isIP2(hostname3) ? hostname3.split(".").reverse() : [hostname3]; + return subdomains2.slice(offset); + }); + defineGetter(req, "path", function path53() { + return parse5(this).pathname; + }); + defineGetter(req, "host", function host() { + var trust = this.app.get("trust proxy fn"); + var val = this.get("X-Forwarded-Host"); + if (!val || !trust(this.socket.remoteAddress, 0)) { + val = this.get("Host"); + } else if (val.indexOf(",") !== -1) { + val = val.substring(0, val.indexOf(",")).trimRight(); + } + return val || void 0; + }); + defineGetter(req, "hostname", function hostname3() { + var host = this.host; + if (!host) return; + var offset = host[0] === "[" ? host.indexOf("]") + 1 : 0; + var index2 = host.indexOf(":", offset); + return index2 !== -1 ? host.substring(0, index2) : host; + }); + defineGetter(req, "fresh", function() { + var method = this.method; + var res = this.res; + var status = res.statusCode; + if ("GET" !== method && "HEAD" !== method) return false; + if (status >= 200 && status < 300 || 304 === status) { + return fresh(this.headers, { + "etag": res.get("ETag"), + "last-modified": res.get("Last-Modified") + }); + } + return false; + }); + defineGetter(req, "stale", function stale() { + return !this.fresh; + }); + defineGetter(req, "xhr", function xhr() { + var val = this.get("X-Requested-With") || ""; + return val.toLowerCase() === "xmlhttprequest"; + }); + function defineGetter(obj, name, getter) { + Object.defineProperty(obj, name, { + configurable: true, + enumerable: true, + get: getter + }); + } + } +}); + +// node_modules/.pnpm/content-disposition@1.1.0/node_modules/content-disposition/index.js +var require_content_disposition = __commonJS({ + "node_modules/.pnpm/content-disposition@1.1.0/node_modules/content-disposition/index.js"(exports, module) { + "use strict"; + module.exports = contentDisposition; + module.exports.parse = parse5; + var utf8Decoder = new TextDecoder("utf-8"); + var ENCODE_URL_ATTR_CHAR_REGEXP = /[\x00-\x20"'()*,/:;<=>?@[\\\]{}\x7f]/g; + var NON_LATIN1_REGEXP = /[^\x20-\x7e\xa0-\xff]/g; + var QESC_REGEXP = /\\([\u0000-\u007f])/g; + var QUOTE_REGEXP = /([\\"])/g; + var PARAM_REGEXP = /;[\x09\x20]*([!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*=[\x09\x20]*("(?:[\x20!\x23-\x5b\x5d-\x7e\x80-\xff]|\\[\x20-\x7e])*"|[!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*/g; + var TEXT_REGEXP = /^[\x20-\x7e\x80-\xff]+$/; + var TOKEN_REGEXP = /^[!#$%&'*+.0-9A-Z^_`a-z|~-]+$/; + var EXT_VALUE_REGEXP = /^([A-Za-z0-9!#$%&+\-^_`{}~]+)'(?:[A-Za-z]{2,3}(?:-[A-Za-z]{3}){0,3}|[A-Za-z]{4,8}|)'((?:%[0-9A-Fa-f]{2}|[A-Za-z0-9!#$&+.^_`|~-])+)$/; + var DISPOSITION_TYPE_REGEXP = /^([!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*(?:$|;)/; + function contentDisposition(filename, options) { + var opts = options || {}; + var type = opts.type || "attachment"; + var params = createparams(filename, opts.fallback); + return format2(new ContentDisposition(type, params)); + } + function createparams(filename, fallback) { + if (filename === void 0) { + return; + } + var params = {}; + if (typeof filename !== "string") { + throw new TypeError("filename must be a string"); + } + if (fallback === void 0) { + fallback = true; + } + if (typeof fallback !== "string" && typeof fallback !== "boolean") { + throw new TypeError("fallback must be a string or boolean"); + } + if (typeof fallback === "string" && NON_LATIN1_REGEXP.test(fallback)) { + throw new TypeError("fallback must be ISO-8859-1 string"); + } + var name = basename3(filename); + var isQuotedString = TEXT_REGEXP.test(name); + var fallbackName = typeof fallback !== "string" ? fallback && getlatin1(name) : basename3(fallback); + var hasFallback = typeof fallbackName === "string" && fallbackName !== name; + if (hasFallback || !isQuotedString || hasHexEscape(name)) { + params["filename*"] = name; + } + if (isQuotedString || hasFallback) { + params.filename = hasFallback ? fallbackName : name; + } + return params; + } + function format2(obj) { + var parameters = obj.parameters; + var type = obj.type; + if (!type || typeof type !== "string" || !TOKEN_REGEXP.test(type)) { + throw new TypeError("invalid type"); + } + var string4 = String(type).toLowerCase(); + if (parameters && typeof parameters === "object") { + var param; + var params = Object.keys(parameters).sort(); + for (var i5 = 0; i5 < params.length; i5++) { + param = params[i5]; + var val = param.slice(-1) === "*" ? ustring(parameters[param]) : qstring(parameters[param]); + string4 += "; " + param + "=" + val; + } + } + return string4; + } + function decodefield(str) { + const match = EXT_VALUE_REGEXP.exec(str); + if (!match) { + throw new TypeError("invalid extended field value"); + } + const charset = match[1].toLowerCase(); + const encoded = match[2]; + switch (charset) { + case "iso-8859-1": { + const binary2 = decodeHexEscapes(encoded); + return getlatin1(binary2); + } + case "utf-8": + case "utf8": { + try { + return decodeURIComponent(encoded); + } catch { + const binary2 = decodeHexEscapes(encoded); + const bytes = new Uint8Array(binary2.length); + for (let idx = 0; idx < binary2.length; idx++) { + bytes[idx] = binary2.charCodeAt(idx); + } + return utf8Decoder.decode(bytes); + } + } + } + throw new TypeError("unsupported charset in extended field"); + } + function getlatin1(val) { + return String(val).replace(NON_LATIN1_REGEXP, "?"); + } + function parse5(string4) { + if (!string4 || typeof string4 !== "string") { + throw new TypeError("argument string is required"); + } + var match = DISPOSITION_TYPE_REGEXP.exec(string4); + if (!match) { + throw new TypeError("invalid type format"); + } + var index2 = match[0].length; + var type = match[1].toLowerCase(); + var key; + var names = []; + var params = {}; + var value; + index2 = PARAM_REGEXP.lastIndex = match[0].slice(-1) === ";" ? index2 - 1 : index2; + while (match = PARAM_REGEXP.exec(string4)) { + if (match.index !== index2) { + throw new TypeError("invalid parameter format"); + } + index2 += match[0].length; + key = match[1].toLowerCase(); + value = match[2]; + if (names.indexOf(key) !== -1) { + throw new TypeError("invalid duplicate parameter"); + } + names.push(key); + if (key.indexOf("*") + 1 === key.length) { + key = key.slice(0, -1); + value = decodefield(value); + params[key] = value; + continue; + } + if (typeof params[key] === "string") { + continue; + } + if (value[0] === '"') { + value = value.slice(1, -1).replace(QESC_REGEXP, "$1"); + } + params[key] = value; + } + if (index2 !== -1 && index2 !== string4.length) { + throw new TypeError("invalid parameter format"); + } + return new ContentDisposition(type, params); + } + function pencode(char2) { + return "%" + String(char2).charCodeAt(0).toString(16).toUpperCase(); + } + function qstring(val) { + var str = String(val); + return '"' + str.replace(QUOTE_REGEXP, "\\$1") + '"'; + } + function ustring(val) { + var str = String(val); + var encoded = encodeURIComponent(str).replace(ENCODE_URL_ATTR_CHAR_REGEXP, pencode); + return "UTF-8''" + encoded; + } + function ContentDisposition(type, parameters) { + this.type = type; + this.parameters = parameters; + } + function basename3(path53) { + const normalized = path53.replaceAll("\\", "/"); + let end = normalized.length; + while (end > 0 && normalized[end - 1] === "/") { + end--; + } + if (end === 0) { + return ""; + } + let start = end - 1; + while (start >= 0 && normalized[start] !== "/") { + start--; + } + return normalized.slice(start + 1, end); + } + function isHexDigit(char2) { + const code = char2.charCodeAt(0); + return code >= 48 && code <= 57 || // 0-9 + code >= 65 && code <= 70 || // A-F + code >= 97 && code <= 102; + } + function hasHexEscape(str) { + const maxIndex = str.length - 3; + let lastIndex = -1; + while ((lastIndex = str.indexOf("%", lastIndex + 1)) !== -1 && lastIndex <= maxIndex) { + if (isHexDigit(str[lastIndex + 1]) && isHexDigit(str[lastIndex + 2])) { + return true; + } + } + return false; + } + function decodeHexEscapes(str) { + const firstEscape = str.indexOf("%"); + if (firstEscape === -1) return str; + let result = str.slice(0, firstEscape); + for (let idx = firstEscape; idx < str.length; idx++) { + if (str[idx] === "%" && idx + 2 < str.length && isHexDigit(str[idx + 1]) && isHexDigit(str[idx + 2])) { + result += String.fromCharCode(Number.parseInt(str[idx + 1] + str[idx + 2], 16)); + idx += 2; + } else { + result += str[idx]; + } + } + return result; + } + } +}); + +// node_modules/.pnpm/cookie-signature@1.2.2/node_modules/cookie-signature/index.js +var require_cookie_signature = __commonJS({ + "node_modules/.pnpm/cookie-signature@1.2.2/node_modules/cookie-signature/index.js"(exports) { + var crypto6 = __require("crypto"); + exports.sign = function(val, secret) { + if ("string" != typeof val) throw new TypeError("Cookie value must be provided as a string."); + if (null == secret) throw new TypeError("Secret key must be provided."); + return val + "." + crypto6.createHmac("sha256", secret).update(val).digest("base64").replace(/\=+$/, ""); + }; + exports.unsign = function(input, secret) { + if ("string" != typeof input) throw new TypeError("Signed cookie string must be provided."); + if (null == secret) throw new TypeError("Secret key must be provided."); + var tentativeValue = input.slice(0, input.lastIndexOf(".")), expectedInput = exports.sign(tentativeValue, secret), expectedBuffer = Buffer.from(expectedInput), inputBuffer = Buffer.from(input); + return expectedBuffer.length === inputBuffer.length && crypto6.timingSafeEqual(expectedBuffer, inputBuffer) ? tentativeValue : false; + }; + } +}); + +// node_modules/.pnpm/cookie@0.7.2/node_modules/cookie/index.js +var require_cookie = __commonJS({ + "node_modules/.pnpm/cookie@0.7.2/node_modules/cookie/index.js"(exports) { + "use strict"; + exports.parse = parse5; + exports.serialize = serialize; + var __toString = Object.prototype.toString; + var __hasOwnProperty = Object.prototype.hasOwnProperty; + var cookieNameRegExp = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/; + var cookieValueRegExp = /^("?)[\u0021\u0023-\u002B\u002D-\u003A\u003C-\u005B\u005D-\u007E]*\1$/; + var domainValueRegExp = /^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i; + var pathValueRegExp = /^[\u0020-\u003A\u003D-\u007E]*$/; + function parse5(str, opt) { + if (typeof str !== "string") { + throw new TypeError("argument str must be a string"); + } + var obj = {}; + var len = str.length; + if (len < 2) return obj; + var dec = opt && opt.decode || decode5; + var index2 = 0; + var eqIdx = 0; + var endIdx = 0; + do { + eqIdx = str.indexOf("=", index2); + if (eqIdx === -1) break; + endIdx = str.indexOf(";", index2); + if (endIdx === -1) { + endIdx = len; + } else if (eqIdx > endIdx) { + index2 = str.lastIndexOf(";", eqIdx - 1) + 1; + continue; + } + var keyStartIdx = startIndex(str, index2, eqIdx); + var keyEndIdx = endIndex(str, eqIdx, keyStartIdx); + var key = str.slice(keyStartIdx, keyEndIdx); + if (!__hasOwnProperty.call(obj, key)) { + var valStartIdx = startIndex(str, eqIdx + 1, endIdx); + var valEndIdx = endIndex(str, endIdx, valStartIdx); + if (str.charCodeAt(valStartIdx) === 34 && str.charCodeAt(valEndIdx - 1) === 34) { + valStartIdx++; + valEndIdx--; + } + var val = str.slice(valStartIdx, valEndIdx); + obj[key] = tryDecode2(val, dec); + } + index2 = endIdx + 1; + } while (index2 < len); + return obj; + } + function startIndex(str, index2, max) { + do { + var code = str.charCodeAt(index2); + if (code !== 32 && code !== 9) return index2; + } while (++index2 < max); + return max; + } + function endIndex(str, index2, min) { + while (index2 > min) { + var code = str.charCodeAt(--index2); + if (code !== 32 && code !== 9) return index2 + 1; + } + return min; + } + function serialize(name, val, opt) { + var enc2 = opt && opt.encode || encodeURIComponent; + if (typeof enc2 !== "function") { + throw new TypeError("option encode is invalid"); + } + if (!cookieNameRegExp.test(name)) { + throw new TypeError("argument name is invalid"); + } + var value = enc2(val); + if (!cookieValueRegExp.test(value)) { + throw new TypeError("argument val is invalid"); + } + var str = name + "=" + value; + if (!opt) return str; + if (null != opt.maxAge) { + var maxAge = Math.floor(opt.maxAge); + if (!isFinite(maxAge)) { + throw new TypeError("option maxAge is invalid"); + } + str += "; Max-Age=" + maxAge; + } + if (opt.domain) { + if (!domainValueRegExp.test(opt.domain)) { + throw new TypeError("option domain is invalid"); + } + str += "; Domain=" + opt.domain; + } + if (opt.path) { + if (!pathValueRegExp.test(opt.path)) { + throw new TypeError("option path is invalid"); + } + str += "; Path=" + opt.path; + } + if (opt.expires) { + var expires = opt.expires; + if (!isDate2(expires) || isNaN(expires.valueOf())) { + throw new TypeError("option expires is invalid"); + } + str += "; Expires=" + expires.toUTCString(); + } + if (opt.httpOnly) { + str += "; HttpOnly"; + } + if (opt.secure) { + str += "; Secure"; + } + if (opt.partitioned) { + str += "; Partitioned"; + } + if (opt.priority) { + var priority = typeof opt.priority === "string" ? opt.priority.toLowerCase() : opt.priority; + switch (priority) { + case "low": + str += "; Priority=Low"; + break; + case "medium": + str += "; Priority=Medium"; + break; + case "high": + str += "; Priority=High"; + break; + default: + throw new TypeError("option priority is invalid"); + } + } + if (opt.sameSite) { + var sameSite = typeof opt.sameSite === "string" ? opt.sameSite.toLowerCase() : opt.sameSite; + switch (sameSite) { + case true: + str += "; SameSite=Strict"; + break; + case "lax": + str += "; SameSite=Lax"; + break; + case "strict": + str += "; SameSite=Strict"; + break; + case "none": + str += "; SameSite=None"; + break; + default: + throw new TypeError("option sameSite is invalid"); + } + } + return str; + } + function decode5(str) { + return str.indexOf("%") !== -1 ? decodeURIComponent(str) : str; + } + function isDate2(val) { + return __toString.call(val) === "[object Date]"; + } + function tryDecode2(str, decode6) { + try { + return decode6(str); + } catch (e5) { + return str; + } + } + } +}); + +// node_modules/.pnpm/send@1.2.1/node_modules/send/index.js +var require_send = __commonJS({ + "node_modules/.pnpm/send@1.2.1/node_modules/send/index.js"(exports, module) { + "use strict"; + var createError = require_http_errors(); + var debug = require_src()("send"); + var encodeUrl = require_encodeurl(); + var escapeHtml = require_escape_html(); + var etag = require_etag(); + var fresh = require_fresh(); + var fs41 = __require("fs"); + var mime = require_mime_types(); + var ms = require_ms(); + var onFinished = require_on_finished(); + var parseRange = require_range_parser(); + var path53 = __require("path"); + var statuses = require_statuses(); + var Stream3 = __require("stream"); + var util2 = __require("util"); + var extname2 = path53.extname; + var join4 = path53.join; + var normalize2 = path53.normalize; + var resolve4 = path53.resolve; + var sep = path53.sep; + var BYTES_RANGE_REGEXP = /^ *bytes=/; + var MAX_MAXAGE = 60 * 60 * 24 * 365 * 1e3; + var UP_PATH_REGEXP = /(?:^|[\\/])\.\.(?:[\\/]|$)/; + module.exports = send; + function send(req, path54, options) { + return new SendStream(req, path54, options); + } + function SendStream(req, path54, options) { + Stream3.call(this); + var opts = options || {}; + this.options = opts; + this.path = path54; + this.req = req; + this._acceptRanges = opts.acceptRanges !== void 0 ? Boolean(opts.acceptRanges) : true; + this._cacheControl = opts.cacheControl !== void 0 ? Boolean(opts.cacheControl) : true; + this._etag = opts.etag !== void 0 ? Boolean(opts.etag) : true; + this._dotfiles = opts.dotfiles !== void 0 ? opts.dotfiles : "ignore"; + if (this._dotfiles !== "ignore" && this._dotfiles !== "allow" && this._dotfiles !== "deny") { + throw new TypeError('dotfiles option must be "allow", "deny", or "ignore"'); + } + this._extensions = opts.extensions !== void 0 ? normalizeList(opts.extensions, "extensions option") : []; + this._immutable = opts.immutable !== void 0 ? Boolean(opts.immutable) : false; + this._index = opts.index !== void 0 ? normalizeList(opts.index, "index option") : ["index.html"]; + this._lastModified = opts.lastModified !== void 0 ? Boolean(opts.lastModified) : true; + this._maxage = opts.maxAge || opts.maxage; + this._maxage = typeof this._maxage === "string" ? ms(this._maxage) : Number(this._maxage); + this._maxage = !isNaN(this._maxage) ? Math.min(Math.max(0, this._maxage), MAX_MAXAGE) : 0; + this._root = opts.root ? resolve4(opts.root) : null; + } + util2.inherits(SendStream, Stream3); + SendStream.prototype.error = function error50(status, err) { + if (hasListeners(this, "error")) { + return this.emit("error", createHttpError(status, err)); + } + var res = this.res; + var msg = statuses.message[status] || String(status); + var doc = createHtmlDocument("Error", escapeHtml(msg)); + clearHeaders(res); + if (err && err.headers) { + setHeaders(res, err.headers); + } + res.statusCode = status; + res.setHeader("Content-Type", "text/html; charset=UTF-8"); + res.setHeader("Content-Length", Buffer.byteLength(doc)); + res.setHeader("Content-Security-Policy", "default-src 'none'"); + res.setHeader("X-Content-Type-Options", "nosniff"); + res.end(doc); + }; + SendStream.prototype.hasTrailingSlash = function hasTrailingSlash() { + return this.path[this.path.length - 1] === "/"; + }; + SendStream.prototype.isConditionalGET = function isConditionalGET() { + return this.req.headers["if-match"] || this.req.headers["if-unmodified-since"] || this.req.headers["if-none-match"] || this.req.headers["if-modified-since"]; + }; + SendStream.prototype.isPreconditionFailure = function isPreconditionFailure() { + var req = this.req; + var res = this.res; + var match = req.headers["if-match"]; + if (match) { + var etag2 = res.getHeader("ETag"); + return !etag2 || match !== "*" && parseTokenList(match).every(function(match2) { + return match2 !== etag2 && match2 !== "W/" + etag2 && "W/" + match2 !== etag2; + }); + } + var unmodifiedSince = parseHttpDate(req.headers["if-unmodified-since"]); + if (!isNaN(unmodifiedSince)) { + var lastModified = parseHttpDate(res.getHeader("Last-Modified")); + return isNaN(lastModified) || lastModified > unmodifiedSince; + } + return false; + }; + SendStream.prototype.removeContentHeaderFields = function removeContentHeaderFields() { + var res = this.res; + res.removeHeader("Content-Encoding"); + res.removeHeader("Content-Language"); + res.removeHeader("Content-Length"); + res.removeHeader("Content-Range"); + res.removeHeader("Content-Type"); + }; + SendStream.prototype.notModified = function notModified() { + var res = this.res; + debug("not modified"); + this.removeContentHeaderFields(); + res.statusCode = 304; + res.end(); + }; + SendStream.prototype.headersAlreadySent = function headersAlreadySent() { + var err = new Error("Can't set headers after they are sent."); + debug("headers already sent"); + this.error(500, err); + }; + SendStream.prototype.isCachable = function isCachable() { + var statusCode = this.res.statusCode; + return statusCode >= 200 && statusCode < 300 || statusCode === 304; + }; + SendStream.prototype.onStatError = function onStatError(error50) { + switch (error50.code) { + case "ENAMETOOLONG": + case "ENOENT": + case "ENOTDIR": + this.error(404, error50); + break; + default: + this.error(500, error50); + break; + } + }; + SendStream.prototype.isFresh = function isFresh() { + return fresh(this.req.headers, { + etag: this.res.getHeader("ETag"), + "last-modified": this.res.getHeader("Last-Modified") + }); + }; + SendStream.prototype.isRangeFresh = function isRangeFresh() { + var ifRange = this.req.headers["if-range"]; + if (!ifRange) { + return true; + } + if (ifRange.indexOf('"') !== -1) { + var etag2 = this.res.getHeader("ETag"); + return Boolean(etag2 && ifRange.indexOf(etag2) !== -1); + } + var lastModified = this.res.getHeader("Last-Modified"); + return parseHttpDate(lastModified) <= parseHttpDate(ifRange); + }; + SendStream.prototype.redirect = function redirect(path54) { + var res = this.res; + if (hasListeners(this, "directory")) { + this.emit("directory", res, path54); + return; + } + if (this.hasTrailingSlash()) { + this.error(403); + return; + } + var loc = encodeUrl(collapseLeadingSlashes(this.path + "/")); + var doc = createHtmlDocument("Redirecting", "Redirecting to " + escapeHtml(loc)); + res.statusCode = 301; + res.setHeader("Content-Type", "text/html; charset=UTF-8"); + res.setHeader("Content-Length", Buffer.byteLength(doc)); + res.setHeader("Content-Security-Policy", "default-src 'none'"); + res.setHeader("X-Content-Type-Options", "nosniff"); + res.setHeader("Location", loc); + res.end(doc); + }; + SendStream.prototype.pipe = function pipe2(res) { + var root = this._root; + this.res = res; + var path54 = decode5(this.path); + if (path54 === -1) { + this.error(400); + return res; + } + if (~path54.indexOf("\0")) { + this.error(400); + return res; + } + var parts; + if (root !== null) { + if (path54) { + path54 = normalize2("." + sep + path54); + } + if (UP_PATH_REGEXP.test(path54)) { + debug('malicious path "%s"', path54); + this.error(403); + return res; + } + parts = path54.split(sep); + path54 = normalize2(join4(root, path54)); + } else { + if (UP_PATH_REGEXP.test(path54)) { + debug('malicious path "%s"', path54); + this.error(403); + return res; + } + parts = normalize2(path54).split(sep); + path54 = resolve4(path54); + } + if (containsDotFile(parts)) { + debug('%s dotfile "%s"', this._dotfiles, path54); + switch (this._dotfiles) { + case "allow": + break; + case "deny": + this.error(403); + return res; + case "ignore": + default: + this.error(404); + return res; + } + } + if (this._index.length && this.hasTrailingSlash()) { + this.sendIndex(path54); + return res; + } + this.sendFile(path54); + return res; + }; + SendStream.prototype.send = function send2(path54, stat5) { + var len = stat5.size; + var options = this.options; + var opts = {}; + var res = this.res; + var req = this.req; + var ranges = req.headers.range; + var offset = options.start || 0; + if (res.headersSent) { + this.headersAlreadySent(); + return; + } + debug('pipe "%s"', path54); + this.setHeader(path54, stat5); + this.type(path54); + if (this.isConditionalGET()) { + if (this.isPreconditionFailure()) { + this.error(412); + return; + } + if (this.isCachable() && this.isFresh()) { + this.notModified(); + return; + } + } + len = Math.max(0, len - offset); + if (options.end !== void 0) { + var bytes = options.end - offset + 1; + if (len > bytes) len = bytes; + } + if (this._acceptRanges && BYTES_RANGE_REGEXP.test(ranges)) { + ranges = parseRange(len, ranges, { + combine: true + }); + if (!this.isRangeFresh()) { + debug("range stale"); + ranges = -2; + } + if (ranges === -1) { + debug("range unsatisfiable"); + res.setHeader("Content-Range", contentRange("bytes", len)); + return this.error(416, { + headers: { "Content-Range": res.getHeader("Content-Range") } + }); + } + if (ranges !== -2 && ranges.length === 1) { + debug("range %j", ranges); + res.statusCode = 206; + res.setHeader("Content-Range", contentRange("bytes", len, ranges[0])); + offset += ranges[0].start; + len = ranges[0].end - ranges[0].start + 1; + } + } + for (var prop in options) { + opts[prop] = options[prop]; + } + opts.start = offset; + opts.end = Math.max(offset, offset + len - 1); + res.setHeader("Content-Length", len); + if (req.method === "HEAD") { + res.end(); + return; + } + this.stream(path54, opts); + }; + SendStream.prototype.sendFile = function sendFile(path54) { + var i5 = 0; + var self2 = this; + debug('stat "%s"', path54); + fs41.stat(path54, function onstat(err, stat5) { + var pathEndsWithSep = path54[path54.length - 1] === sep; + if (err && err.code === "ENOENT" && !extname2(path54) && !pathEndsWithSep) { + return next(err); + } + if (err) return self2.onStatError(err); + if (stat5.isDirectory()) return self2.redirect(path54); + if (pathEndsWithSep) return self2.error(404); + self2.emit("file", path54, stat5); + self2.send(path54, stat5); + }); + function next(err) { + if (self2._extensions.length <= i5) { + return err ? self2.onStatError(err) : self2.error(404); + } + var p5 = path54 + "." + self2._extensions[i5++]; + debug('stat "%s"', p5); + fs41.stat(p5, function(err2, stat5) { + if (err2) return next(err2); + if (stat5.isDirectory()) return next(); + self2.emit("file", p5, stat5); + self2.send(p5, stat5); + }); + } + }; + SendStream.prototype.sendIndex = function sendIndex(path54) { + var i5 = -1; + var self2 = this; + function next(err) { + if (++i5 >= self2._index.length) { + if (err) return self2.onStatError(err); + return self2.error(404); + } + var p5 = join4(path54, self2._index[i5]); + debug('stat "%s"', p5); + fs41.stat(p5, function(err2, stat5) { + if (err2) return next(err2); + if (stat5.isDirectory()) return next(); + self2.emit("file", p5, stat5); + self2.send(p5, stat5); + }); + } + next(); + }; + SendStream.prototype.stream = function stream(path54, options) { + var self2 = this; + var res = this.res; + var stream2 = fs41.createReadStream(path54, options); + this.emit("stream", stream2); + stream2.pipe(res); + function cleanup() { + stream2.destroy(); + } + onFinished(res, cleanup); + stream2.on("error", function onerror(err) { + cleanup(); + self2.onStatError(err); + }); + stream2.on("end", function onend() { + self2.emit("end"); + }); + }; + SendStream.prototype.type = function type(path54) { + var res = this.res; + if (res.getHeader("Content-Type")) return; + var ext = extname2(path54); + var type2 = mime.contentType(ext) || "application/octet-stream"; + debug("content-type %s", type2); + res.setHeader("Content-Type", type2); + }; + SendStream.prototype.setHeader = function setHeader(path54, stat5) { + var res = this.res; + this.emit("headers", res, path54, stat5); + if (this._acceptRanges && !res.getHeader("Accept-Ranges")) { + debug("accept ranges"); + res.setHeader("Accept-Ranges", "bytes"); + } + if (this._cacheControl && !res.getHeader("Cache-Control")) { + var cacheControl = "public, max-age=" + Math.floor(this._maxage / 1e3); + if (this._immutable) { + cacheControl += ", immutable"; + } + debug("cache-control %s", cacheControl); + res.setHeader("Cache-Control", cacheControl); + } + if (this._lastModified && !res.getHeader("Last-Modified")) { + var modified = stat5.mtime.toUTCString(); + debug("modified %s", modified); + res.setHeader("Last-Modified", modified); + } + if (this._etag && !res.getHeader("ETag")) { + var val = etag(stat5); + debug("etag %s", val); + res.setHeader("ETag", val); + } + }; + function clearHeaders(res) { + for (const header of res.getHeaderNames()) { + res.removeHeader(header); + } + } + function collapseLeadingSlashes(str) { + for (var i5 = 0; i5 < str.length; i5++) { + if (str[i5] !== "/") { + break; + } + } + return i5 > 1 ? "/" + str.substr(i5) : str; + } + function containsDotFile(parts) { + for (var i5 = 0; i5 < parts.length; i5++) { + var part = parts[i5]; + if (part.length > 1 && part[0] === ".") { + return true; + } + } + return false; + } + function contentRange(type, size2, range2) { + return type + " " + (range2 ? range2.start + "-" + range2.end : "*") + "/" + size2; + } + function createHtmlDocument(title, body) { + return '\n\n\n\n' + title + "\n\n\n
" + body + "
\n\n\n"; + } + function createHttpError(status, err) { + if (!err) { + return createError(status); + } + return err instanceof Error ? createError(status, err, { expose: false }) : createError(status, err); + } + function decode5(path54) { + try { + return decodeURIComponent(path54); + } catch (err) { + return -1; + } + } + function hasListeners(emitter2, type) { + var count2 = typeof emitter2.listenerCount !== "function" ? emitter2.listeners(type).length : emitter2.listenerCount(type); + return count2 > 0; + } + function normalizeList(val, name) { + var list2 = [].concat(val || []); + for (var i5 = 0; i5 < list2.length; i5++) { + if (typeof list2[i5] !== "string") { + throw new TypeError(name + " must be array of strings or false"); + } + } + return list2; + } + function parseHttpDate(date7) { + var timestamp2 = date7 && Date.parse(date7); + return typeof timestamp2 === "number" ? timestamp2 : NaN; + } + function parseTokenList(str) { + var end = 0; + var list2 = []; + var start = 0; + for (var i5 = 0, len = str.length; i5 < len; i5++) { + switch (str.charCodeAt(i5)) { + case 32: + if (start === end) { + start = end = i5 + 1; + } + break; + case 44: + if (start !== end) { + list2.push(str.substring(start, end)); + } + start = end = i5 + 1; + break; + default: + end = i5 + 1; + break; + } + } + if (start !== end) { + list2.push(str.substring(start, end)); + } + return list2; + } + function setHeaders(res, headers) { + var keys = Object.keys(headers); + for (var i5 = 0; i5 < keys.length; i5++) { + var key = keys[i5]; + res.setHeader(key, headers[key]); + } + } + } +}); + +// node_modules/.pnpm/vary@1.1.2/node_modules/vary/index.js +var require_vary = __commonJS({ + "node_modules/.pnpm/vary@1.1.2/node_modules/vary/index.js"(exports, module) { + "use strict"; + module.exports = vary; + module.exports.append = append; + var FIELD_NAME_REGEXP = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/; + function append(header, field) { + if (typeof header !== "string") { + throw new TypeError("header argument is required"); + } + if (!field) { + throw new TypeError("field argument is required"); + } + var fields = !Array.isArray(field) ? parse5(String(field)) : field; + for (var j5 = 0; j5 < fields.length; j5++) { + if (!FIELD_NAME_REGEXP.test(fields[j5])) { + throw new TypeError("field argument contains an invalid header name"); + } + } + if (header === "*") { + return header; + } + var val = header; + var vals = parse5(header.toLowerCase()); + if (fields.indexOf("*") !== -1 || vals.indexOf("*") !== -1) { + return "*"; + } + for (var i5 = 0; i5 < fields.length; i5++) { + var fld = fields[i5].toLowerCase(); + if (vals.indexOf(fld) === -1) { + vals.push(fld); + val = val ? val + ", " + fields[i5] : fields[i5]; + } + } + return val; + } + function parse5(header) { + var end = 0; + var list2 = []; + var start = 0; + for (var i5 = 0, len = header.length; i5 < len; i5++) { + switch (header.charCodeAt(i5)) { + case 32: + if (start === end) { + start = end = i5 + 1; + } + break; + case 44: + list2.push(header.substring(start, end)); + start = end = i5 + 1; + break; + default: + end = i5 + 1; + break; + } + } + list2.push(header.substring(start, end)); + return list2; + } + function vary(res, field) { + if (!res || !res.getHeader || !res.setHeader) { + throw new TypeError("res argument is required"); + } + var val = res.getHeader("Vary") || ""; + var header = Array.isArray(val) ? val.join(", ") : String(val); + if (val = append(header, field)) { + res.setHeader("Vary", val); + } + } + } +}); + +// node_modules/.pnpm/express@5.2.1/node_modules/express/lib/response.js +var require_response = __commonJS({ + "node_modules/.pnpm/express@5.2.1/node_modules/express/lib/response.js"(exports, module) { + "use strict"; + var contentDisposition = require_content_disposition(); + var createError = require_http_errors(); + var deprecate2 = require_depd()("express"); + var encodeUrl = require_encodeurl(); + var escapeHtml = require_escape_html(); + var http = __require("node:http"); + var onFinished = require_on_finished(); + var mime = require_mime_types(); + var path53 = __require("node:path"); + var pathIsAbsolute = __require("node:path").isAbsolute; + var statuses = require_statuses(); + var sign2 = require_cookie_signature().sign; + var normalizeType = require_utils3().normalizeType; + var normalizeTypes = require_utils3().normalizeTypes; + var setCharset = require_utils3().setCharset; + var cookie = require_cookie(); + var send = require_send(); + var extname2 = path53.extname; + var resolve4 = path53.resolve; + var vary = require_vary(); + var { Buffer: Buffer2 } = __require("node:buffer"); + var res = Object.create(http.ServerResponse.prototype); + module.exports = res; + res.status = function status(code) { + if (!Number.isInteger(code)) { + throw new TypeError(`Invalid status code: ${JSON.stringify(code)}. Status code must be an integer.`); + } + if (code < 100 || code > 999) { + throw new RangeError(`Invalid status code: ${JSON.stringify(code)}. Status code must be greater than 99 and less than 1000.`); + } + this.statusCode = code; + return this; + }; + res.links = function(links) { + var link = this.get("Link") || ""; + if (link) link += ", "; + return this.set("Link", link + Object.keys(links).map(function(rel) { + if (Array.isArray(links[rel])) { + return links[rel].map(function(singleLink) { + return `<${singleLink}>; rel="${rel}"`; + }).join(", "); + } else { + return `<${links[rel]}>; rel="${rel}"`; + } + }).join(", ")); + }; + res.send = function send2(body) { + var chunk = body; + var encoding; + var req = this.req; + var type; + var app = this.app; + switch (typeof chunk) { + // string defaulting to html + case "string": + if (!this.get("Content-Type")) { + this.type("html"); + } + break; + case "boolean": + case "number": + case "object": + if (chunk === null) { + chunk = ""; + } else if (ArrayBuffer.isView(chunk)) { + if (!this.get("Content-Type")) { + this.type("bin"); + } + } else { + return this.json(chunk); + } + break; + } + if (typeof chunk === "string") { + encoding = "utf8"; + type = this.get("Content-Type"); + if (typeof type === "string") { + this.set("Content-Type", setCharset(type, "utf-8")); + } + } + var etagFn = app.get("etag fn"); + var generateETag = !this.get("ETag") && typeof etagFn === "function"; + var len; + if (chunk !== void 0) { + if (Buffer2.isBuffer(chunk)) { + len = chunk.length; + } else if (!generateETag && chunk.length < 1e3) { + len = Buffer2.byteLength(chunk, encoding); + } else { + chunk = Buffer2.from(chunk, encoding); + encoding = void 0; + len = chunk.length; + } + this.set("Content-Length", len); + } + var etag; + if (generateETag && len !== void 0) { + if (etag = etagFn(chunk, encoding)) { + this.set("ETag", etag); + } + } + if (req.fresh) this.status(304); + if (204 === this.statusCode || 304 === this.statusCode) { + this.removeHeader("Content-Type"); + this.removeHeader("Content-Length"); + this.removeHeader("Transfer-Encoding"); + chunk = ""; + } + if (this.statusCode === 205) { + this.set("Content-Length", "0"); + this.removeHeader("Transfer-Encoding"); + chunk = ""; + } + if (req.method === "HEAD") { + this.end(); + } else { + this.end(chunk, encoding); + } + return this; + }; + res.json = function json3(obj) { + var app = this.app; + var escape3 = app.get("json escape"); + var replacer = app.get("json replacer"); + var spaces = app.get("json spaces"); + var body = stringify2(obj, replacer, spaces, escape3); + if (!this.get("Content-Type")) { + this.set("Content-Type", "application/json"); + } + return this.send(body); + }; + res.jsonp = function jsonp(obj) { + var app = this.app; + var escape3 = app.get("json escape"); + var replacer = app.get("json replacer"); + var spaces = app.get("json spaces"); + var body = stringify2(obj, replacer, spaces, escape3); + var callback = this.req.query[app.get("jsonp callback name")]; + if (!this.get("Content-Type")) { + this.set("X-Content-Type-Options", "nosniff"); + this.set("Content-Type", "application/json"); + } + if (Array.isArray(callback)) { + callback = callback[0]; + } + if (typeof callback === "string" && callback.length !== 0) { + this.set("X-Content-Type-Options", "nosniff"); + this.set("Content-Type", "text/javascript"); + callback = callback.replace(/[^\[\]\w$.]/g, ""); + if (body === void 0) { + body = ""; + } else if (typeof body === "string") { + body = body.replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029"); + } + body = "/**/ typeof " + callback + " === 'function' && " + callback + "(" + body + ");"; + } + return this.send(body); + }; + res.sendStatus = function sendStatus(statusCode) { + var body = statuses.message[statusCode] || String(statusCode); + this.status(statusCode); + this.type("txt"); + return this.send(body); + }; + res.sendFile = function sendFile(path54, options, callback) { + var done = callback; + var req = this.req; + var res2 = this; + var next = req.next; + var opts = options || {}; + if (!path54) { + throw new TypeError("path argument is required to res.sendFile"); + } + if (typeof path54 !== "string") { + throw new TypeError("path must be a string to res.sendFile"); + } + if (typeof options === "function") { + done = options; + opts = {}; + } + if (!opts.root && !pathIsAbsolute(path54)) { + throw new TypeError("path must be absolute or specify root to res.sendFile"); + } + var pathname = encodeURI(path54); + opts.etag = this.app.enabled("etag"); + var file2 = send(req, pathname, opts); + sendfile(res2, file2, opts, function(err) { + if (done) return done(err); + if (err && err.code === "EISDIR") return next(); + if (err && err.code !== "ECONNABORTED" && err.syscall !== "write") { + next(err); + } + }); + }; + res.download = function download(path54, filename, options, callback) { + var done = callback; + var name = filename; + var opts = options || null; + if (typeof filename === "function") { + done = filename; + name = null; + opts = null; + } else if (typeof options === "function") { + done = options; + opts = null; + } + if (typeof filename === "object" && (typeof options === "function" || options === void 0)) { + name = null; + opts = filename; + } + var headers = { + "Content-Disposition": contentDisposition(name || path54) + }; + if (opts && opts.headers) { + var keys = Object.keys(opts.headers); + for (var i5 = 0; i5 < keys.length; i5++) { + var key = keys[i5]; + if (key.toLowerCase() !== "content-disposition") { + headers[key] = opts.headers[key]; + } + } + } + opts = Object.create(opts); + opts.headers = headers; + var fullPath = !opts.root ? resolve4(path54) : path54; + return this.sendFile(fullPath, opts, done); + }; + res.contentType = res.type = function contentType(type) { + var ct = type.indexOf("/") === -1 ? mime.contentType(type) || "application/octet-stream" : type; + return this.set("Content-Type", ct); + }; + res.format = function(obj) { + var req = this.req; + var next = req.next; + var keys = Object.keys(obj).filter(function(v5) { + return v5 !== "default"; + }); + var key = keys.length > 0 ? req.accepts(keys) : false; + this.vary("Accept"); + if (key) { + this.set("Content-Type", normalizeType(key).value); + obj[key](req, this, next); + } else if (obj.default) { + obj.default(req, this, next); + } else { + next(createError(406, { + types: normalizeTypes(keys).map(function(o5) { + return o5.value; + }) + })); + } + return this; + }; + res.attachment = function attachment(filename) { + if (filename) { + this.type(extname2(filename)); + } + this.set("Content-Disposition", contentDisposition(filename)); + return this; + }; + res.append = function append(field, val) { + var prev = this.get(field); + var value = val; + if (prev) { + value = Array.isArray(prev) ? prev.concat(val) : Array.isArray(val) ? [prev].concat(val) : [prev, val]; + } + return this.set(field, value); + }; + res.set = res.header = function header(field, val) { + if (arguments.length === 2) { + var value = Array.isArray(val) ? val.map(String) : String(val); + if (field.toLowerCase() === "content-type") { + if (Array.isArray(value)) { + throw new TypeError("Content-Type cannot be set to an Array"); + } + value = mime.contentType(value); + } + this.setHeader(field, value); + } else { + for (var key in field) { + this.set(key, field[key]); + } + } + return this; + }; + res.get = function(field) { + return this.getHeader(field); + }; + res.clearCookie = function clearCookie(name, options) { + const opts = { path: "/", ...options, expires: /* @__PURE__ */ new Date(1) }; + delete opts.maxAge; + return this.cookie(name, "", opts); + }; + res.cookie = function(name, value, options) { + var opts = { ...options }; + var secret = this.req.secret; + var signed = opts.signed; + if (signed && !secret) { + throw new Error('cookieParser("secret") required for signed cookies'); + } + var val = typeof value === "object" ? "j:" + JSON.stringify(value) : String(value); + if (signed) { + val = "s:" + sign2(val, secret); + } + if (opts.maxAge != null) { + var maxAge = opts.maxAge - 0; + if (!isNaN(maxAge)) { + opts.expires = new Date(Date.now() + maxAge); + opts.maxAge = Math.floor(maxAge / 1e3); + } + } + if (opts.path == null) { + opts.path = "/"; + } + this.append("Set-Cookie", cookie.serialize(name, String(val), opts)); + return this; + }; + res.location = function location(url2) { + return this.set("Location", encodeUrl(url2)); + }; + res.redirect = function redirect(url2) { + var address = url2; + var body; + var status = 302; + if (arguments.length === 2) { + status = arguments[0]; + address = arguments[1]; + } + if (!address) { + deprecate2("Provide a url argument"); + } + if (typeof address !== "string") { + deprecate2("Url must be a string"); + } + if (typeof status !== "number") { + deprecate2("Status must be a number"); + } + address = this.location(address).get("Location"); + this.format({ + text: function() { + body = statuses.message[status] + ". Redirecting to " + address; + }, + html: function() { + var u5 = escapeHtml(address); + body = "

" + statuses.message[status] + ". Redirecting to " + u5 + "

"; + }, + default: function() { + body = ""; + } + }); + this.status(status); + this.set("Content-Length", Buffer2.byteLength(body)); + if (this.req.method === "HEAD") { + this.end(); + } else { + this.end(body); + } + }; + res.vary = function(field) { + vary(this, field); + return this; + }; + res.render = function render(view, options, callback) { + var app = this.req.app; + var done = callback; + var opts = options || {}; + var req = this.req; + var self2 = this; + if (typeof options === "function") { + done = options; + opts = {}; + } + opts._locals = self2.locals; + done = done || function(err, str) { + if (err) return req.next(err); + self2.send(str); + }; + app.render(view, opts, done); + }; + function sendfile(res2, file2, options, callback) { + var done = false; + var streaming; + function onaborted() { + if (done) return; + done = true; + var err = new Error("Request aborted"); + err.code = "ECONNABORTED"; + callback(err); + } + function ondirectory() { + if (done) return; + done = true; + var err = new Error("EISDIR, read"); + err.code = "EISDIR"; + callback(err); + } + function onerror(err) { + if (done) return; + done = true; + callback(err); + } + function onend() { + if (done) return; + done = true; + callback(); + } + function onfile() { + streaming = false; + } + function onfinish(err) { + if (err && err.code === "ECONNRESET") return onaborted(); + if (err) return onerror(err); + if (done) return; + setImmediate(function() { + if (streaming !== false && !done) { + onaborted(); + return; + } + if (done) return; + done = true; + callback(); + }); + } + function onstream() { + streaming = true; + } + file2.on("directory", ondirectory); + file2.on("end", onend); + file2.on("error", onerror); + file2.on("file", onfile); + file2.on("stream", onstream); + onFinished(res2, onfinish); + if (options.headers) { + file2.on("headers", function headers(res3) { + var obj = options.headers; + var keys = Object.keys(obj); + for (var i5 = 0; i5 < keys.length; i5++) { + var k5 = keys[i5]; + res3.setHeader(k5, obj[k5]); + } + }); + } + file2.pipe(res2); + } + function stringify2(value, replacer, spaces, escape3) { + var json3 = replacer || spaces ? JSON.stringify(value, replacer, spaces) : JSON.stringify(value); + if (escape3 && typeof json3 === "string") { + json3 = json3.replace(/[<>&]/g, function(c5) { + switch (c5.charCodeAt(0)) { + case 60: + return "\\u003c"; + case 62: + return "\\u003e"; + case 38: + return "\\u0026"; + /* istanbul ignore next: unreachable default */ + default: + return c5; + } + }); + } + return json3; + } + } +}); + +// node_modules/.pnpm/serve-static@2.2.1/node_modules/serve-static/index.js +var require_serve_static = __commonJS({ + "node_modules/.pnpm/serve-static@2.2.1/node_modules/serve-static/index.js"(exports, module) { + "use strict"; + var encodeUrl = require_encodeurl(); + var escapeHtml = require_escape_html(); + var parseUrl7 = require_parseurl(); + var resolve4 = __require("path").resolve; + var send = require_send(); + var url2 = __require("url"); + module.exports = serveStatic; + function serveStatic(root, options) { + if (!root) { + throw new TypeError("root path required"); + } + if (typeof root !== "string") { + throw new TypeError("root path must be a string"); + } + var opts = Object.create(options || null); + var fallthrough = opts.fallthrough !== false; + var redirect = opts.redirect !== false; + var setHeaders = opts.setHeaders; + if (setHeaders && typeof setHeaders !== "function") { + throw new TypeError("option setHeaders must be function"); + } + opts.maxage = opts.maxage || opts.maxAge || 0; + opts.root = resolve4(root); + var onDirectory = redirect ? createRedirectDirectoryListener() : createNotFoundDirectoryListener(); + return function serveStatic2(req, res, next) { + if (req.method !== "GET" && req.method !== "HEAD") { + if (fallthrough) { + return next(); + } + res.statusCode = 405; + res.setHeader("Allow", "GET, HEAD"); + res.setHeader("Content-Length", "0"); + res.end(); + return; + } + var forwardError = !fallthrough; + var originalUrl = parseUrl7.original(req); + var path53 = parseUrl7(req).pathname; + if (path53 === "/" && originalUrl.pathname.substr(-1) !== "/") { + path53 = ""; + } + var stream = send(req, path53, opts); + stream.on("directory", onDirectory); + if (setHeaders) { + stream.on("headers", setHeaders); + } + if (fallthrough) { + stream.on("file", function onFile() { + forwardError = true; + }); + } + stream.on("error", function error50(err) { + if (forwardError || !(err.statusCode < 500)) { + next(err); + return; + } + next(); + }); + stream.pipe(res); + }; + } + function collapseLeadingSlashes(str) { + for (var i5 = 0; i5 < str.length; i5++) { + if (str.charCodeAt(i5) !== 47) { + break; + } + } + return i5 > 1 ? "/" + str.substr(i5) : str; + } + function createHtmlDocument(title, body) { + return '\n\n\n\n' + title + "\n\n\n
" + body + "
\n\n\n"; + } + function createNotFoundDirectoryListener() { + return function notFound2() { + this.error(404); + }; + } + function createRedirectDirectoryListener() { + return function redirect(res) { + if (this.hasTrailingSlash()) { + this.error(404); + return; + } + var originalUrl = parseUrl7.original(this.req); + originalUrl.path = null; + originalUrl.pathname = collapseLeadingSlashes(originalUrl.pathname + "/"); + var loc = encodeUrl(url2.format(originalUrl)); + var doc = createHtmlDocument("Redirecting", "Redirecting to " + escapeHtml(loc)); + res.statusCode = 301; + res.setHeader("Content-Type", "text/html; charset=UTF-8"); + res.setHeader("Content-Length", Buffer.byteLength(doc)); + res.setHeader("Content-Security-Policy", "default-src 'none'"); + res.setHeader("X-Content-Type-Options", "nosniff"); + res.setHeader("Location", loc); + res.end(doc); + }; + } + } +}); + +// node_modules/.pnpm/express@5.2.1/node_modules/express/lib/express.js +var require_express = __commonJS({ + "node_modules/.pnpm/express@5.2.1/node_modules/express/lib/express.js"(exports, module) { + "use strict"; + var bodyParser = require_body_parser(); + var EventEmitter5 = __require("node:events").EventEmitter; + var mixin = require_merge_descriptors(); + var proto = require_application(); + var Router26 = require_router(); + var req = require_request(); + var res = require_response(); + exports = module.exports = createApplication; + function createApplication() { + var app = function(req2, res2, next) { + app.handle(req2, res2, next); + }; + mixin(app, EventEmitter5.prototype, false); + mixin(app, proto, false); + app.request = Object.create(req, { + app: { configurable: true, enumerable: true, writable: true, value: app } + }); + app.response = Object.create(res, { + app: { configurable: true, enumerable: true, writable: true, value: app } + }); + app.init(); + return app; + } + exports.application = proto; + exports.request = req; + exports.response = res; + exports.Route = Router26.Route; + exports.Router = Router26; + exports.json = bodyParser.json; + exports.raw = bodyParser.raw; + exports.static = require_serve_static(); + exports.text = bodyParser.text; + exports.urlencoded = bodyParser.urlencoded; + } +}); + +// node_modules/.pnpm/express@5.2.1/node_modules/express/index.js +var require_express2 = __commonJS({ + "node_modules/.pnpm/express@5.2.1/node_modules/express/index.js"(exports, module) { + "use strict"; + module.exports = require_express(); + } +}); + +// node_modules/.pnpm/pino-std-serializers@7.1.0/node_modules/pino-std-serializers/lib/err-helpers.js +var require_err_helpers = __commonJS({ + "node_modules/.pnpm/pino-std-serializers@7.1.0/node_modules/pino-std-serializers/lib/err-helpers.js"(exports, module) { + "use strict"; + var isErrorLike = (err) => { + return err && typeof err.message === "string"; + }; + var getErrorCause = (err) => { + if (!err) return; + const cause = err.cause; + if (typeof cause === "function") { + const causeResult = err.cause(); + return isErrorLike(causeResult) ? causeResult : void 0; + } else { + return isErrorLike(cause) ? cause : void 0; + } + }; + var _stackWithCauses = (err, seen) => { + if (!isErrorLike(err)) return ""; + const stack = err.stack || ""; + if (seen.has(err)) { + return stack + "\ncauses have become circular..."; + } + const cause = getErrorCause(err); + if (cause) { + seen.add(err); + return stack + "\ncaused by: " + _stackWithCauses(cause, seen); + } else { + return stack; + } + }; + var stackWithCauses = (err) => _stackWithCauses(err, /* @__PURE__ */ new Set()); + var _messageWithCauses = (err, seen, skip) => { + if (!isErrorLike(err)) return ""; + const message2 = skip ? "" : err.message || ""; + if (seen.has(err)) { + return message2 + ": ..."; + } + const cause = getErrorCause(err); + if (cause) { + seen.add(err); + const skipIfVErrorStyleCause = typeof err.cause === "function"; + return message2 + (skipIfVErrorStyleCause ? "" : ": ") + _messageWithCauses(cause, seen, skipIfVErrorStyleCause); + } else { + return message2; + } + }; + var messageWithCauses = (err) => _messageWithCauses(err, /* @__PURE__ */ new Set()); + module.exports = { + isErrorLike, + getErrorCause, + stackWithCauses, + messageWithCauses + }; + } +}); + +// node_modules/.pnpm/pino-std-serializers@7.1.0/node_modules/pino-std-serializers/lib/err-proto.js +var require_err_proto = __commonJS({ + "node_modules/.pnpm/pino-std-serializers@7.1.0/node_modules/pino-std-serializers/lib/err-proto.js"(exports, module) { + "use strict"; + var seen = /* @__PURE__ */ Symbol("circular-ref-tag"); + var rawSymbol = /* @__PURE__ */ Symbol("pino-raw-err-ref"); + var pinoErrProto = Object.create({}, { + type: { + enumerable: true, + writable: true, + value: void 0 + }, + message: { + enumerable: true, + writable: true, + value: void 0 + }, + stack: { + enumerable: true, + writable: true, + value: void 0 + }, + aggregateErrors: { + enumerable: true, + writable: true, + value: void 0 + }, + raw: { + enumerable: false, + get: function() { + return this[rawSymbol]; + }, + set: function(val) { + this[rawSymbol] = val; + } + } + }); + Object.defineProperty(pinoErrProto, rawSymbol, { + writable: true, + value: {} + }); + module.exports = { + pinoErrProto, + pinoErrorSymbols: { + seen, + rawSymbol + } + }; + } +}); + +// node_modules/.pnpm/pino-std-serializers@7.1.0/node_modules/pino-std-serializers/lib/err.js +var require_err = __commonJS({ + "node_modules/.pnpm/pino-std-serializers@7.1.0/node_modules/pino-std-serializers/lib/err.js"(exports, module) { + "use strict"; + module.exports = errSerializer; + var { messageWithCauses, stackWithCauses, isErrorLike } = require_err_helpers(); + var { pinoErrProto, pinoErrorSymbols } = require_err_proto(); + var { seen } = pinoErrorSymbols; + var { toString } = Object.prototype; + function errSerializer(err) { + if (!isErrorLike(err)) { + return err; + } + err[seen] = void 0; + const _err = Object.create(pinoErrProto); + _err.type = toString.call(err.constructor) === "[object Function]" ? err.constructor.name : err.name; + _err.message = messageWithCauses(err); + _err.stack = stackWithCauses(err); + if (Array.isArray(err.errors)) { + _err.aggregateErrors = err.errors.map((err2) => errSerializer(err2)); + } + for (const key in err) { + if (_err[key] === void 0) { + const val = err[key]; + if (isErrorLike(val)) { + if (key !== "cause" && !Object.prototype.hasOwnProperty.call(val, seen)) { + _err[key] = errSerializer(val); + } + } else { + _err[key] = val; + } + } + } + delete err[seen]; + _err.raw = err; + return _err; + } + } +}); + +// node_modules/.pnpm/pino-std-serializers@7.1.0/node_modules/pino-std-serializers/lib/err-with-cause.js +var require_err_with_cause = __commonJS({ + "node_modules/.pnpm/pino-std-serializers@7.1.0/node_modules/pino-std-serializers/lib/err-with-cause.js"(exports, module) { + "use strict"; + module.exports = errWithCauseSerializer; + var { isErrorLike } = require_err_helpers(); + var { pinoErrProto, pinoErrorSymbols } = require_err_proto(); + var { seen } = pinoErrorSymbols; + var { toString } = Object.prototype; + function errWithCauseSerializer(err) { + if (!isErrorLike(err)) { + return err; + } + err[seen] = void 0; + const _err = Object.create(pinoErrProto); + _err.type = toString.call(err.constructor) === "[object Function]" ? err.constructor.name : err.name; + _err.message = err.message; + _err.stack = err.stack; + if (Array.isArray(err.errors)) { + _err.aggregateErrors = err.errors.map((err2) => errWithCauseSerializer(err2)); + } + if (isErrorLike(err.cause) && !Object.prototype.hasOwnProperty.call(err.cause, seen)) { + _err.cause = errWithCauseSerializer(err.cause); + } + for (const key in err) { + if (_err[key] === void 0) { + const val = err[key]; + if (isErrorLike(val)) { + if (!Object.prototype.hasOwnProperty.call(val, seen)) { + _err[key] = errWithCauseSerializer(val); + } + } else { + _err[key] = val; + } + } + } + delete err[seen]; + _err.raw = err; + return _err; + } + } +}); + +// node_modules/.pnpm/pino-std-serializers@7.1.0/node_modules/pino-std-serializers/lib/req.js +var require_req = __commonJS({ + "node_modules/.pnpm/pino-std-serializers@7.1.0/node_modules/pino-std-serializers/lib/req.js"(exports, module) { + "use strict"; + module.exports = { + mapHttpRequest, + reqSerializer + }; + var rawSymbol = /* @__PURE__ */ Symbol("pino-raw-req-ref"); + var pinoReqProto = Object.create({}, { + id: { + enumerable: true, + writable: true, + value: "" + }, + method: { + enumerable: true, + writable: true, + value: "" + }, + url: { + enumerable: true, + writable: true, + value: "" + }, + query: { + enumerable: true, + writable: true, + value: "" + }, + params: { + enumerable: true, + writable: true, + value: "" + }, + headers: { + enumerable: true, + writable: true, + value: {} + }, + remoteAddress: { + enumerable: true, + writable: true, + value: "" + }, + remotePort: { + enumerable: true, + writable: true, + value: "" + }, + raw: { + enumerable: false, + get: function() { + return this[rawSymbol]; + }, + set: function(val) { + this[rawSymbol] = val; + } + } + }); + Object.defineProperty(pinoReqProto, rawSymbol, { + writable: true, + value: {} + }); + function reqSerializer(req) { + const connection2 = req.info || req.socket; + const _req = Object.create(pinoReqProto); + _req.id = typeof req.id === "function" ? req.id() : req.id || (req.info ? req.info.id : void 0); + _req.method = req.method; + if (req.originalUrl) { + _req.url = req.originalUrl; + } else { + const path53 = req.path; + _req.url = typeof path53 === "string" ? path53 : req.url ? req.url.path || req.url : void 0; + } + if (req.query) { + _req.query = req.query; + } + if (req.params) { + _req.params = req.params; + } + _req.headers = req.headers; + _req.remoteAddress = connection2 && connection2.remoteAddress; + _req.remotePort = connection2 && connection2.remotePort; + _req.raw = req.raw || req; + return _req; + } + function mapHttpRequest(req) { + return { + req: reqSerializer(req) + }; + } + } +}); + +// node_modules/.pnpm/pino-std-serializers@7.1.0/node_modules/pino-std-serializers/lib/res.js +var require_res = __commonJS({ + "node_modules/.pnpm/pino-std-serializers@7.1.0/node_modules/pino-std-serializers/lib/res.js"(exports, module) { + "use strict"; + module.exports = { + mapHttpResponse, + resSerializer + }; + var rawSymbol = /* @__PURE__ */ Symbol("pino-raw-res-ref"); + var pinoResProto = Object.create({}, { + statusCode: { + enumerable: true, + writable: true, + value: 0 + }, + headers: { + enumerable: true, + writable: true, + value: "" + }, + raw: { + enumerable: false, + get: function() { + return this[rawSymbol]; + }, + set: function(val) { + this[rawSymbol] = val; + } + } + }); + Object.defineProperty(pinoResProto, rawSymbol, { + writable: true, + value: {} + }); + function resSerializer(res) { + const _res = Object.create(pinoResProto); + _res.statusCode = res.headersSent ? res.statusCode : null; + _res.headers = res.getHeaders ? res.getHeaders() : res._headers; + _res.raw = res; + return _res; + } + function mapHttpResponse(res) { + return { + res: resSerializer(res) + }; + } + } +}); + +// node_modules/.pnpm/pino-std-serializers@7.1.0/node_modules/pino-std-serializers/index.js +var require_pino_std_serializers = __commonJS({ + "node_modules/.pnpm/pino-std-serializers@7.1.0/node_modules/pino-std-serializers/index.js"(exports, module) { + "use strict"; + var errSerializer = require_err(); + var errWithCauseSerializer = require_err_with_cause(); + var reqSerializers = require_req(); + var resSerializers = require_res(); + module.exports = { + err: errSerializer, + errWithCause: errWithCauseSerializer, + mapHttpRequest: reqSerializers.mapHttpRequest, + mapHttpResponse: resSerializers.mapHttpResponse, + req: reqSerializers.reqSerializer, + res: resSerializers.resSerializer, + wrapErrorSerializer: function wrapErrorSerializer(customSerializer) { + if (customSerializer === errSerializer) return customSerializer; + return function wrapErrSerializer(err) { + return customSerializer(errSerializer(err)); + }; + }, + wrapRequestSerializer: function wrapRequestSerializer(customSerializer) { + if (customSerializer === reqSerializers.reqSerializer) return customSerializer; + return function wrappedReqSerializer(req) { + return customSerializer(reqSerializers.reqSerializer(req)); + }; + }, + wrapResponseSerializer: function wrapResponseSerializer(customSerializer) { + if (customSerializer === resSerializers.resSerializer) return customSerializer; + return function wrappedResSerializer(res) { + return customSerializer(resSerializers.resSerializer(res)); + }; + } + }; + } +}); + +// node_modules/.pnpm/pino@9.14.0/node_modules/pino/lib/caller.js +var require_caller = __commonJS({ + "node_modules/.pnpm/pino@9.14.0/node_modules/pino/lib/caller.js"(exports, module) { + "use strict"; + function noOpPrepareStackTrace(_, stack) { + return stack; + } + module.exports = function getCallers() { + const originalPrepare = Error.prepareStackTrace; + Error.prepareStackTrace = noOpPrepareStackTrace; + const stack = new Error().stack; + Error.prepareStackTrace = originalPrepare; + if (!Array.isArray(stack)) { + return void 0; + } + const entries2 = stack.slice(2); + const fileNames = []; + for (const entry of entries2) { + if (!entry) { + continue; + } + fileNames.push(entry.getFileName()); + } + return fileNames; + }; + } +}); + +// node_modules/.pnpm/@pinojs+redact@0.4.0/node_modules/@pinojs/redact/index.js +var require_redact = __commonJS({ + "node_modules/.pnpm/@pinojs+redact@0.4.0/node_modules/@pinojs/redact/index.js"(exports, module) { + "use strict"; + function deepClone(obj) { + if (obj === null || typeof obj !== "object") { + return obj; + } + if (obj instanceof Date) { + return new Date(obj.getTime()); + } + if (obj instanceof Array) { + const cloned = []; + for (let i5 = 0; i5 < obj.length; i5++) { + cloned[i5] = deepClone(obj[i5]); + } + return cloned; + } + if (typeof obj === "object") { + const cloned = Object.create(Object.getPrototypeOf(obj)); + for (const key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + cloned[key] = deepClone(obj[key]); + } + } + return cloned; + } + return obj; + } + function parsePath(path53) { + const parts = []; + let current = ""; + let inBrackets = false; + let inQuotes = false; + let quoteChar = ""; + for (let i5 = 0; i5 < path53.length; i5++) { + const char2 = path53[i5]; + if (!inBrackets && char2 === ".") { + if (current) { + parts.push(current); + current = ""; + } + } else if (char2 === "[") { + if (current) { + parts.push(current); + current = ""; + } + inBrackets = true; + } else if (char2 === "]" && inBrackets) { + parts.push(current); + current = ""; + inBrackets = false; + inQuotes = false; + } else if ((char2 === '"' || char2 === "'") && inBrackets) { + if (!inQuotes) { + inQuotes = true; + quoteChar = char2; + } else if (char2 === quoteChar) { + inQuotes = false; + quoteChar = ""; + } else { + current += char2; + } + } else { + current += char2; + } + } + if (current) { + parts.push(current); + } + return parts; + } + function setValue(obj, parts, value) { + let current = obj; + for (let i5 = 0; i5 < parts.length - 1; i5++) { + const key = parts[i5]; + if (typeof current !== "object" || current === null || !(key in current)) { + return false; + } + if (typeof current[key] !== "object" || current[key] === null) { + return false; + } + current = current[key]; + } + const lastKey = parts[parts.length - 1]; + if (lastKey === "*") { + if (Array.isArray(current)) { + for (let i5 = 0; i5 < current.length; i5++) { + current[i5] = value; + } + } else if (typeof current === "object" && current !== null) { + for (const key in current) { + if (Object.prototype.hasOwnProperty.call(current, key)) { + current[key] = value; + } + } + } + } else { + if (typeof current === "object" && current !== null && lastKey in current && Object.prototype.hasOwnProperty.call(current, lastKey)) { + current[lastKey] = value; + } + } + return true; + } + function removeKey(obj, parts) { + let current = obj; + for (let i5 = 0; i5 < parts.length - 1; i5++) { + const key = parts[i5]; + if (typeof current !== "object" || current === null || !(key in current)) { + return false; + } + if (typeof current[key] !== "object" || current[key] === null) { + return false; + } + current = current[key]; + } + const lastKey = parts[parts.length - 1]; + if (lastKey === "*") { + if (Array.isArray(current)) { + for (let i5 = 0; i5 < current.length; i5++) { + current[i5] = void 0; + } + } else if (typeof current === "object" && current !== null) { + for (const key in current) { + if (Object.prototype.hasOwnProperty.call(current, key)) { + delete current[key]; + } + } + } + } else { + if (typeof current === "object" && current !== null && lastKey in current && Object.prototype.hasOwnProperty.call(current, lastKey)) { + delete current[lastKey]; + } + } + return true; + } + var PATH_NOT_FOUND = /* @__PURE__ */ Symbol("PATH_NOT_FOUND"); + function getValueIfExists(obj, parts) { + let current = obj; + for (const part of parts) { + if (current === null || current === void 0) { + return PATH_NOT_FOUND; + } + if (typeof current !== "object" || current === null) { + return PATH_NOT_FOUND; + } + if (!(part in current)) { + return PATH_NOT_FOUND; + } + current = current[part]; + } + return current; + } + function getValue(obj, parts) { + let current = obj; + for (const part of parts) { + if (current === null || current === void 0) { + return void 0; + } + if (typeof current !== "object" || current === null) { + return void 0; + } + current = current[part]; + } + return current; + } + function redactPaths(obj, paths2, censor, remove = false) { + for (const path53 of paths2) { + const parts = parsePath(path53); + if (parts.includes("*")) { + redactWildcardPath(obj, parts, censor, path53, remove); + } else { + if (remove) { + removeKey(obj, parts); + } else { + const value = getValueIfExists(obj, parts); + if (value === PATH_NOT_FOUND) { + continue; + } + const actualCensor = typeof censor === "function" ? censor(value, parts) : censor; + setValue(obj, parts, actualCensor); + } + } + } + } + function redactWildcardPath(obj, parts, censor, originalPath, remove = false) { + const wildcardIndex = parts.indexOf("*"); + if (wildcardIndex === parts.length - 1) { + const parentParts = parts.slice(0, -1); + let current = obj; + for (const part of parentParts) { + if (current === null || current === void 0) return; + if (typeof current !== "object" || current === null) return; + current = current[part]; + } + if (Array.isArray(current)) { + if (remove) { + for (let i5 = 0; i5 < current.length; i5++) { + current[i5] = void 0; + } + } else { + for (let i5 = 0; i5 < current.length; i5++) { + const indexPath = [...parentParts, i5.toString()]; + const actualCensor = typeof censor === "function" ? censor(current[i5], indexPath) : censor; + current[i5] = actualCensor; + } + } + } else if (typeof current === "object" && current !== null) { + if (remove) { + const keysToDelete = []; + for (const key in current) { + if (Object.prototype.hasOwnProperty.call(current, key)) { + keysToDelete.push(key); + } + } + for (const key of keysToDelete) { + delete current[key]; + } + } else { + for (const key in current) { + const keyPath = [...parentParts, key]; + const actualCensor = typeof censor === "function" ? censor(current[key], keyPath) : censor; + current[key] = actualCensor; + } + } + } + } else { + redactIntermediateWildcard(obj, parts, censor, wildcardIndex, originalPath, remove); + } + } + function redactIntermediateWildcard(obj, parts, censor, wildcardIndex, originalPath, remove = false) { + const beforeWildcard = parts.slice(0, wildcardIndex); + const afterWildcard = parts.slice(wildcardIndex + 1); + const pathArray = []; + function traverse(current, pathLength) { + if (pathLength === beforeWildcard.length) { + if (Array.isArray(current)) { + for (let i5 = 0; i5 < current.length; i5++) { + pathArray[pathLength] = i5.toString(); + traverse(current[i5], pathLength + 1); + } + } else if (typeof current === "object" && current !== null) { + for (const key in current) { + pathArray[pathLength] = key; + traverse(current[key], pathLength + 1); + } + } + } else if (pathLength < beforeWildcard.length) { + const nextKey = beforeWildcard[pathLength]; + if (current && typeof current === "object" && current !== null && nextKey in current) { + pathArray[pathLength] = nextKey; + traverse(current[nextKey], pathLength + 1); + } + } else { + if (afterWildcard.includes("*")) { + const wrappedCensor = typeof censor === "function" ? (value, path53) => { + const fullPath = [...pathArray.slice(0, pathLength), ...path53]; + return censor(value, fullPath); + } : censor; + redactWildcardPath(current, afterWildcard, wrappedCensor, originalPath, remove); + } else { + if (remove) { + removeKey(current, afterWildcard); + } else { + const actualCensor = typeof censor === "function" ? censor(getValue(current, afterWildcard), [...pathArray.slice(0, pathLength), ...afterWildcard]) : censor; + setValue(current, afterWildcard, actualCensor); + } + } + } + } + if (beforeWildcard.length === 0) { + traverse(obj, 0); + } else { + let current = obj; + for (let i5 = 0; i5 < beforeWildcard.length; i5++) { + const part = beforeWildcard[i5]; + if (current === null || current === void 0) return; + if (typeof current !== "object" || current === null) return; + current = current[part]; + pathArray[i5] = part; + } + if (current !== null && current !== void 0) { + traverse(current, beforeWildcard.length); + } + } + } + function buildPathStructure(pathsToClone) { + if (pathsToClone.length === 0) { + return null; + } + const pathStructure = /* @__PURE__ */ new Map(); + for (const path53 of pathsToClone) { + const parts = parsePath(path53); + let current = pathStructure; + for (let i5 = 0; i5 < parts.length; i5++) { + const part = parts[i5]; + if (!current.has(part)) { + current.set(part, /* @__PURE__ */ new Map()); + } + current = current.get(part); + } + } + return pathStructure; + } + function selectiveClone(obj, pathStructure) { + if (!pathStructure) { + return obj; + } + function cloneSelectively(source, pathMap, depth = 0) { + if (!pathMap || pathMap.size === 0) { + return source; + } + if (source === null || typeof source !== "object") { + return source; + } + if (source instanceof Date) { + return new Date(source.getTime()); + } + if (Array.isArray(source)) { + const cloned2 = []; + for (let i5 = 0; i5 < source.length; i5++) { + const indexStr = i5.toString(); + if (pathMap.has(indexStr) || pathMap.has("*")) { + cloned2[i5] = cloneSelectively(source[i5], pathMap.get(indexStr) || pathMap.get("*")); + } else { + cloned2[i5] = source[i5]; + } + } + return cloned2; + } + const cloned = Object.create(Object.getPrototypeOf(source)); + for (const key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + if (pathMap.has(key) || pathMap.has("*")) { + cloned[key] = cloneSelectively(source[key], pathMap.get(key) || pathMap.get("*")); + } else { + cloned[key] = source[key]; + } + } + } + return cloned; + } + return cloneSelectively(obj, pathStructure); + } + function validatePath(path53) { + if (typeof path53 !== "string") { + throw new Error("Paths must be (non-empty) strings"); + } + if (path53 === "") { + throw new Error("Invalid redaction path ()"); + } + if (path53.includes("..")) { + throw new Error(`Invalid redaction path (${path53})`); + } + if (path53.includes(",")) { + throw new Error(`Invalid redaction path (${path53})`); + } + let bracketCount = 0; + let inQuotes = false; + let quoteChar = ""; + for (let i5 = 0; i5 < path53.length; i5++) { + const char2 = path53[i5]; + if ((char2 === '"' || char2 === "'") && bracketCount > 0) { + if (!inQuotes) { + inQuotes = true; + quoteChar = char2; + } else if (char2 === quoteChar) { + inQuotes = false; + quoteChar = ""; + } + } else if (char2 === "[" && !inQuotes) { + bracketCount++; + } else if (char2 === "]" && !inQuotes) { + bracketCount--; + if (bracketCount < 0) { + throw new Error(`Invalid redaction path (${path53})`); + } + } + } + if (bracketCount !== 0) { + throw new Error(`Invalid redaction path (${path53})`); + } + } + function validatePaths(paths2) { + if (!Array.isArray(paths2)) { + throw new TypeError("paths must be an array"); + } + for (const path53 of paths2) { + validatePath(path53); + } + } + function slowRedact(options = {}) { + const { + paths: paths2 = [], + censor = "[REDACTED]", + serialize = JSON.stringify, + strict = true, + remove = false + } = options; + validatePaths(paths2); + const pathStructure = buildPathStructure(paths2); + return function redact(obj) { + if (strict && (obj === null || typeof obj !== "object")) { + if (obj === null || obj === void 0) { + return serialize ? serialize(obj) : obj; + } + if (typeof obj !== "object") { + return serialize ? serialize(obj) : obj; + } + } + const cloned = selectiveClone(obj, pathStructure); + const original = obj; + let actualCensor = censor; + if (typeof censor === "function") { + actualCensor = censor; + } + redactPaths(cloned, paths2, actualCensor, remove); + if (serialize === false) { + cloned.restore = function() { + return deepClone(original); + }; + return cloned; + } + if (typeof serialize === "function") { + return serialize(cloned); + } + return JSON.stringify(cloned); + }; + } + module.exports = slowRedact; + } +}); + +// node_modules/.pnpm/pino@9.14.0/node_modules/pino/lib/symbols.js +var require_symbols = __commonJS({ + "node_modules/.pnpm/pino@9.14.0/node_modules/pino/lib/symbols.js"(exports, module) { + "use strict"; + var setLevelSym = /* @__PURE__ */ Symbol("pino.setLevel"); + var getLevelSym = /* @__PURE__ */ Symbol("pino.getLevel"); + var levelValSym = /* @__PURE__ */ Symbol("pino.levelVal"); + var levelCompSym = /* @__PURE__ */ Symbol("pino.levelComp"); + var useLevelLabelsSym = /* @__PURE__ */ Symbol("pino.useLevelLabels"); + var useOnlyCustomLevelsSym = /* @__PURE__ */ Symbol("pino.useOnlyCustomLevels"); + var mixinSym = /* @__PURE__ */ Symbol("pino.mixin"); + var lsCacheSym = /* @__PURE__ */ Symbol("pino.lsCache"); + var chindingsSym = /* @__PURE__ */ Symbol("pino.chindings"); + var asJsonSym = /* @__PURE__ */ Symbol("pino.asJson"); + var writeSym = /* @__PURE__ */ Symbol("pino.write"); + var redactFmtSym = /* @__PURE__ */ Symbol("pino.redactFmt"); + var timeSym = /* @__PURE__ */ Symbol("pino.time"); + var timeSliceIndexSym = /* @__PURE__ */ Symbol("pino.timeSliceIndex"); + var streamSym = /* @__PURE__ */ Symbol("pino.stream"); + var stringifySym = /* @__PURE__ */ Symbol("pino.stringify"); + var stringifySafeSym = /* @__PURE__ */ Symbol("pino.stringifySafe"); + var stringifiersSym = /* @__PURE__ */ Symbol("pino.stringifiers"); + var endSym = /* @__PURE__ */ Symbol("pino.end"); + var formatOptsSym = /* @__PURE__ */ Symbol("pino.formatOpts"); + var messageKeySym = /* @__PURE__ */ Symbol("pino.messageKey"); + var errorKeySym = /* @__PURE__ */ Symbol("pino.errorKey"); + var nestedKeySym = /* @__PURE__ */ Symbol("pino.nestedKey"); + var nestedKeyStrSym = /* @__PURE__ */ Symbol("pino.nestedKeyStr"); + var mixinMergeStrategySym = /* @__PURE__ */ Symbol("pino.mixinMergeStrategy"); + var msgPrefixSym = /* @__PURE__ */ Symbol("pino.msgPrefix"); + var wildcardFirstSym = /* @__PURE__ */ Symbol("pino.wildcardFirst"); + var serializersSym = /* @__PURE__ */ Symbol.for("pino.serializers"); + var formattersSym = /* @__PURE__ */ Symbol.for("pino.formatters"); + var hooksSym = /* @__PURE__ */ Symbol.for("pino.hooks"); + var needsMetadataGsym = /* @__PURE__ */ Symbol.for("pino.metadata"); + module.exports = { + setLevelSym, + getLevelSym, + levelValSym, + levelCompSym, + useLevelLabelsSym, + mixinSym, + lsCacheSym, + chindingsSym, + asJsonSym, + writeSym, + serializersSym, + redactFmtSym, + timeSym, + timeSliceIndexSym, + streamSym, + stringifySym, + stringifySafeSym, + stringifiersSym, + endSym, + formatOptsSym, + messageKeySym, + errorKeySym, + nestedKeySym, + wildcardFirstSym, + needsMetadataGsym, + useOnlyCustomLevelsSym, + formattersSym, + hooksSym, + nestedKeyStrSym, + mixinMergeStrategySym, + msgPrefixSym + }; + } +}); + +// node_modules/.pnpm/pino@9.14.0/node_modules/pino/lib/redaction.js +var require_redaction = __commonJS({ + "node_modules/.pnpm/pino@9.14.0/node_modules/pino/lib/redaction.js"(exports, module) { + "use strict"; + var Redact = require_redact(); + var { redactFmtSym, wildcardFirstSym } = require_symbols(); + var rx = /[^.[\]]+|\[([^[\]]*?)\]/g; + var CENSOR = "[Redacted]"; + var strict = false; + function redaction(opts, serialize) { + const { paths: paths2, censor, remove } = handle(opts); + const shape = paths2.reduce((o5, str) => { + rx.lastIndex = 0; + const first = rx.exec(str); + const next = rx.exec(str); + let ns = first[1] !== void 0 ? first[1].replace(/^(?:"|'|`)(.*)(?:"|'|`)$/, "$1") : first[0]; + if (ns === "*") { + ns = wildcardFirstSym; + } + if (next === null) { + o5[ns] = null; + return o5; + } + if (o5[ns] === null) { + return o5; + } + const { index: index2 } = next; + const nextPath = `${str.substr(index2, str.length - 1)}`; + o5[ns] = o5[ns] || []; + if (ns !== wildcardFirstSym && o5[ns].length === 0) { + o5[ns].push(...o5[wildcardFirstSym] || []); + } + if (ns === wildcardFirstSym) { + Object.keys(o5).forEach(function(k5) { + if (o5[k5]) { + o5[k5].push(nextPath); + } + }); + } + o5[ns].push(nextPath); + return o5; + }, {}); + const result = { + [redactFmtSym]: Redact({ paths: paths2, censor, serialize, strict, remove }) + }; + const topCensor = (...args) => { + return typeof censor === "function" ? serialize(censor(...args)) : serialize(censor); + }; + return [...Object.keys(shape), ...Object.getOwnPropertySymbols(shape)].reduce((o5, k5) => { + if (shape[k5] === null) { + o5[k5] = (value) => topCensor(value, [k5]); + } else { + const wrappedCensor = typeof censor === "function" ? (value, path53) => { + return censor(value, [k5, ...path53]); + } : censor; + o5[k5] = Redact({ + paths: shape[k5], + censor: wrappedCensor, + serialize, + strict, + remove + }); + } + return o5; + }, result); + } + function handle(opts) { + if (Array.isArray(opts)) { + opts = { paths: opts, censor: CENSOR }; + return opts; + } + let { paths: paths2, censor = CENSOR, remove } = opts; + if (Array.isArray(paths2) === false) { + throw Error("pino \u2013 redact must contain an array of strings"); + } + if (remove === true) censor = void 0; + return { paths: paths2, censor, remove }; + } + module.exports = redaction; + } +}); + +// node_modules/.pnpm/pino@9.14.0/node_modules/pino/lib/time.js +var require_time = __commonJS({ + "node_modules/.pnpm/pino@9.14.0/node_modules/pino/lib/time.js"(exports, module) { + "use strict"; + var nullTime = () => ""; + var epochTime = () => `,"time":${Date.now()}`; + var unixTime = () => `,"time":${Math.round(Date.now() / 1e3)}`; + var isoTime = () => `,"time":"${new Date(Date.now()).toISOString()}"`; + var NS_PER_MS = 1000000n; + var NS_PER_SEC = 1000000000n; + var startWallTimeNs = BigInt(Date.now()) * NS_PER_MS; + var startHrTime = process.hrtime.bigint(); + var isoTimeNano = () => { + const elapsedNs = process.hrtime.bigint() - startHrTime; + const currentTimeNs = startWallTimeNs + elapsedNs; + const secondsSinceEpoch = currentTimeNs / NS_PER_SEC; + const nanosWithinSecond = currentTimeNs % NS_PER_SEC; + const msSinceEpoch = Number(secondsSinceEpoch * 1000n + nanosWithinSecond / 1000000n); + const date7 = new Date(msSinceEpoch); + const year3 = date7.getUTCFullYear(); + const month = (date7.getUTCMonth() + 1).toString().padStart(2, "0"); + const day2 = date7.getUTCDate().toString().padStart(2, "0"); + const hours = date7.getUTCHours().toString().padStart(2, "0"); + const minutes = date7.getUTCMinutes().toString().padStart(2, "0"); + const seconds = date7.getUTCSeconds().toString().padStart(2, "0"); + return `,"time":"${year3}-${month}-${day2}T${hours}:${minutes}:${seconds}.${nanosWithinSecond.toString().padStart(9, "0")}Z"`; + }; + module.exports = { nullTime, epochTime, unixTime, isoTime, isoTimeNano }; + } +}); + +// node_modules/.pnpm/quick-format-unescaped@4.0.4/node_modules/quick-format-unescaped/index.js +var require_quick_format_unescaped = __commonJS({ + "node_modules/.pnpm/quick-format-unescaped@4.0.4/node_modules/quick-format-unescaped/index.js"(exports, module) { + "use strict"; + function tryStringify(o5) { + try { + return JSON.stringify(o5); + } catch (e5) { + return '"[Circular]"'; + } + } + module.exports = format2; + function format2(f5, args, opts) { + var ss = opts && opts.stringify || tryStringify; + var offset = 1; + if (typeof f5 === "object" && f5 !== null) { + var len = args.length + offset; + if (len === 1) return f5; + var objects = new Array(len); + objects[0] = ss(f5); + for (var index2 = 1; index2 < len; index2++) { + objects[index2] = ss(args[index2]); + } + return objects.join(" "); + } + if (typeof f5 !== "string") { + return f5; + } + var argLen = args.length; + if (argLen === 0) return f5; + var str = ""; + var a5 = 1 - offset; + var lastPos = -1; + var flen = f5 && f5.length || 0; + for (var i5 = 0; i5 < flen; ) { + if (f5.charCodeAt(i5) === 37 && i5 + 1 < flen) { + lastPos = lastPos > -1 ? lastPos : 0; + switch (f5.charCodeAt(i5 + 1)) { + case 100: + // 'd' + case 102: + if (a5 >= argLen) + break; + if (args[a5] == null) break; + if (lastPos < i5) + str += f5.slice(lastPos, i5); + str += Number(args[a5]); + lastPos = i5 + 2; + i5++; + break; + case 105: + if (a5 >= argLen) + break; + if (args[a5] == null) break; + if (lastPos < i5) + str += f5.slice(lastPos, i5); + str += Math.floor(Number(args[a5])); + lastPos = i5 + 2; + i5++; + break; + case 79: + // 'O' + case 111: + // 'o' + case 106: + if (a5 >= argLen) + break; + if (args[a5] === void 0) break; + if (lastPos < i5) + str += f5.slice(lastPos, i5); + var type = typeof args[a5]; + if (type === "string") { + str += "'" + args[a5] + "'"; + lastPos = i5 + 2; + i5++; + break; + } + if (type === "function") { + str += args[a5].name || ""; + lastPos = i5 + 2; + i5++; + break; + } + str += ss(args[a5]); + lastPos = i5 + 2; + i5++; + break; + case 115: + if (a5 >= argLen) + break; + if (lastPos < i5) + str += f5.slice(lastPos, i5); + str += String(args[a5]); + lastPos = i5 + 2; + i5++; + break; + case 37: + if (lastPos < i5) + str += f5.slice(lastPos, i5); + str += "%"; + lastPos = i5 + 2; + i5++; + a5--; + break; + } + ++a5; + } + ++i5; + } + if (lastPos === -1) + return f5; + else if (lastPos < flen) { + str += f5.slice(lastPos); + } + return str; + } + } +}); + +// node_modules/.pnpm/atomic-sleep@1.0.0/node_modules/atomic-sleep/index.js +var require_atomic_sleep = __commonJS({ + "node_modules/.pnpm/atomic-sleep@1.0.0/node_modules/atomic-sleep/index.js"(exports, module) { + "use strict"; + if (typeof SharedArrayBuffer !== "undefined" && typeof Atomics !== "undefined") { + let sleep = function(ms) { + const valid = ms > 0 && ms < Infinity; + if (valid === false) { + if (typeof ms !== "number" && typeof ms !== "bigint") { + throw TypeError("sleep: ms must be a number"); + } + throw RangeError("sleep: ms must be a number that is greater than 0 but less than Infinity"); + } + Atomics.wait(nil, 0, 0, Number(ms)); + }; + const nil = new Int32Array(new SharedArrayBuffer(4)); + module.exports = sleep; + } else { + let sleep = function(ms) { + const valid = ms > 0 && ms < Infinity; + if (valid === false) { + if (typeof ms !== "number" && typeof ms !== "bigint") { + throw TypeError("sleep: ms must be a number"); + } + throw RangeError("sleep: ms must be a number that is greater than 0 but less than Infinity"); + } + const target = Date.now() + Number(ms); + while (target > Date.now()) { + } + }; + module.exports = sleep; + } + } +}); + +// node_modules/.pnpm/sonic-boom@4.2.1/node_modules/sonic-boom/index.js +var require_sonic_boom = __commonJS({ + "node_modules/.pnpm/sonic-boom@4.2.1/node_modules/sonic-boom/index.js"(exports, module) { + "use strict"; + var fs41 = __require("fs"); + var EventEmitter5 = __require("events"); + var inherits = __require("util").inherits; + var path53 = __require("path"); + var sleep = require_atomic_sleep(); + var assert2 = __require("assert"); + var BUSY_WRITE_TIMEOUT = 100; + var kEmptyBuffer = Buffer.allocUnsafe(0); + var MAX_WRITE = 16 * 1024; + var kContentModeBuffer = "buffer"; + var kContentModeUtf8 = "utf8"; + var [major, minor] = (process.versions.node || "0.0").split(".").map(Number); + var kCopyBuffer = major >= 22 && minor >= 7; + function openFile(file2, sonic) { + sonic._opening = true; + sonic._writing = true; + sonic._asyncDrainScheduled = false; + function fileOpened(err, fd) { + if (err) { + sonic._reopening = false; + sonic._writing = false; + sonic._opening = false; + if (sonic.sync) { + process.nextTick(() => { + if (sonic.listenerCount("error") > 0) { + sonic.emit("error", err); + } + }); + } else { + sonic.emit("error", err); + } + return; + } + const reopening = sonic._reopening; + sonic.fd = fd; + sonic.file = file2; + sonic._reopening = false; + sonic._opening = false; + sonic._writing = false; + if (sonic.sync) { + process.nextTick(() => sonic.emit("ready")); + } else { + sonic.emit("ready"); + } + if (sonic.destroyed) { + return; + } + if (!sonic._writing && sonic._len > sonic.minLength || sonic._flushPending) { + sonic._actualWrite(); + } else if (reopening) { + process.nextTick(() => sonic.emit("drain")); + } + } + const flags = sonic.append ? "a" : "w"; + const mode = sonic.mode; + if (sonic.sync) { + try { + if (sonic.mkdir) fs41.mkdirSync(path53.dirname(file2), { recursive: true }); + const fd = fs41.openSync(file2, flags, mode); + fileOpened(null, fd); + } catch (err) { + fileOpened(err); + throw err; + } + } else if (sonic.mkdir) { + fs41.mkdir(path53.dirname(file2), { recursive: true }, (err) => { + if (err) return fileOpened(err); + fs41.open(file2, flags, mode, fileOpened); + }); + } else { + fs41.open(file2, flags, mode, fileOpened); + } + } + function SonicBoom(opts) { + if (!(this instanceof SonicBoom)) { + return new SonicBoom(opts); + } + let { fd, dest, minLength, maxLength, maxWrite, periodicFlush, sync, append = true, mkdir, retryEAGAIN, fsync, contentMode, mode } = opts || {}; + fd = fd || dest; + this._len = 0; + this.fd = -1; + this._bufs = []; + this._lens = []; + this._writing = false; + this._ending = false; + this._reopening = false; + this._asyncDrainScheduled = false; + this._flushPending = false; + this._hwm = Math.max(minLength || 0, 16387); + this.file = null; + this.destroyed = false; + this.minLength = minLength || 0; + this.maxLength = maxLength || 0; + this.maxWrite = maxWrite || MAX_WRITE; + this._periodicFlush = periodicFlush || 0; + this._periodicFlushTimer = void 0; + this.sync = sync || false; + this.writable = true; + this._fsync = fsync || false; + this.append = append || false; + this.mode = mode; + this.retryEAGAIN = retryEAGAIN || (() => true); + this.mkdir = mkdir || false; + let fsWriteSync; + let fsWrite; + if (contentMode === kContentModeBuffer) { + this._writingBuf = kEmptyBuffer; + this.write = writeBuffer; + this.flush = flushBuffer; + this.flushSync = flushBufferSync; + this._actualWrite = actualWriteBuffer; + fsWriteSync = () => fs41.writeSync(this.fd, this._writingBuf); + fsWrite = () => fs41.write(this.fd, this._writingBuf, this.release); + } else if (contentMode === void 0 || contentMode === kContentModeUtf8) { + this._writingBuf = ""; + this.write = write; + this.flush = flush; + this.flushSync = flushSync; + this._actualWrite = actualWrite; + fsWriteSync = () => { + if (Buffer.isBuffer(this._writingBuf)) { + return fs41.writeSync(this.fd, this._writingBuf); + } + return fs41.writeSync(this.fd, this._writingBuf, "utf8"); + }; + fsWrite = () => { + if (Buffer.isBuffer(this._writingBuf)) { + return fs41.write(this.fd, this._writingBuf, this.release); + } + return fs41.write(this.fd, this._writingBuf, "utf8", this.release); + }; + } else { + throw new Error(`SonicBoom supports "${kContentModeUtf8}" and "${kContentModeBuffer}", but passed ${contentMode}`); + } + if (typeof fd === "number") { + this.fd = fd; + process.nextTick(() => this.emit("ready")); + } else if (typeof fd === "string") { + openFile(fd, this); + } else { + throw new Error("SonicBoom supports only file descriptors and files"); + } + if (this.minLength >= this.maxWrite) { + throw new Error(`minLength should be smaller than maxWrite (${this.maxWrite})`); + } + this.release = (err, n5) => { + if (err) { + if ((err.code === "EAGAIN" || err.code === "EBUSY") && this.retryEAGAIN(err, this._writingBuf.length, this._len - this._writingBuf.length)) { + if (this.sync) { + try { + sleep(BUSY_WRITE_TIMEOUT); + this.release(void 0, 0); + } catch (err2) { + this.release(err2); + } + } else { + setTimeout(fsWrite, BUSY_WRITE_TIMEOUT); + } + } else { + this._writing = false; + this.emit("error", err); + } + return; + } + this.emit("write", n5); + const releasedBufObj = releaseWritingBuf(this._writingBuf, this._len, n5); + this._len = releasedBufObj.len; + this._writingBuf = releasedBufObj.writingBuf; + if (this._writingBuf.length) { + if (!this.sync) { + fsWrite(); + return; + } + try { + do { + const n6 = fsWriteSync(); + const releasedBufObj2 = releaseWritingBuf(this._writingBuf, this._len, n6); + this._len = releasedBufObj2.len; + this._writingBuf = releasedBufObj2.writingBuf; + } while (this._writingBuf.length); + } catch (err2) { + this.release(err2); + return; + } + } + if (this._fsync) { + fs41.fsyncSync(this.fd); + } + const len = this._len; + if (this._reopening) { + this._writing = false; + this._reopening = false; + this.reopen(); + } else if (len > this.minLength) { + this._actualWrite(); + } else if (this._ending) { + if (len > 0) { + this._actualWrite(); + } else { + this._writing = false; + actualClose(this); + } + } else { + this._writing = false; + if (this.sync) { + if (!this._asyncDrainScheduled) { + this._asyncDrainScheduled = true; + process.nextTick(emitDrain, this); + } + } else { + this.emit("drain"); + } + } + }; + this.on("newListener", function(name) { + if (name === "drain") { + this._asyncDrainScheduled = false; + } + }); + if (this._periodicFlush !== 0) { + this._periodicFlushTimer = setInterval(() => this.flush(null), this._periodicFlush); + this._periodicFlushTimer.unref(); + } + } + function releaseWritingBuf(writingBuf, len, n5) { + if (typeof writingBuf === "string") { + writingBuf = Buffer.from(writingBuf); + } + len = Math.max(len - n5, 0); + writingBuf = writingBuf.subarray(n5); + return { writingBuf, len }; + } + function emitDrain(sonic) { + const hasListeners = sonic.listenerCount("drain") > 0; + if (!hasListeners) return; + sonic._asyncDrainScheduled = false; + sonic.emit("drain"); + } + inherits(SonicBoom, EventEmitter5); + function mergeBuf(bufs, len) { + if (bufs.length === 0) { + return kEmptyBuffer; + } + if (bufs.length === 1) { + return bufs[0]; + } + return Buffer.concat(bufs, len); + } + function write(data2) { + if (this.destroyed) { + throw new Error("SonicBoom destroyed"); + } + data2 = "" + data2; + const dataLen = Buffer.byteLength(data2); + const len = this._len + dataLen; + const bufs = this._bufs; + if (this.maxLength && len > this.maxLength) { + this.emit("drop", data2); + return this._len < this._hwm; + } + if (bufs.length === 0 || Buffer.byteLength(bufs[bufs.length - 1]) + dataLen > this.maxWrite) { + bufs.push(data2); + } else { + bufs[bufs.length - 1] += data2; + } + this._len = len; + if (!this._writing && this._len >= this.minLength) { + this._actualWrite(); + } + return this._len < this._hwm; + } + function writeBuffer(data2) { + if (this.destroyed) { + throw new Error("SonicBoom destroyed"); + } + const len = this._len + data2.length; + const bufs = this._bufs; + const lens = this._lens; + if (this.maxLength && len > this.maxLength) { + this.emit("drop", data2); + return this._len < this._hwm; + } + if (bufs.length === 0 || lens[lens.length - 1] + data2.length > this.maxWrite) { + bufs.push([data2]); + lens.push(data2.length); + } else { + bufs[bufs.length - 1].push(data2); + lens[lens.length - 1] += data2.length; + } + this._len = len; + if (!this._writing && this._len >= this.minLength) { + this._actualWrite(); + } + return this._len < this._hwm; + } + function callFlushCallbackOnDrain(cb) { + this._flushPending = true; + const onDrain = () => { + if (!this._fsync) { + try { + fs41.fsync(this.fd, (err) => { + this._flushPending = false; + cb(err); + }); + } catch (err) { + cb(err); + } + } else { + this._flushPending = false; + cb(); + } + this.off("error", onError); + }; + const onError = (err) => { + this._flushPending = false; + cb(err); + this.off("drain", onDrain); + }; + this.once("drain", onDrain); + this.once("error", onError); + } + function flush(cb) { + if (cb != null && typeof cb !== "function") { + throw new Error("flush cb must be a function"); + } + if (this.destroyed) { + const error50 = new Error("SonicBoom destroyed"); + if (cb) { + cb(error50); + return; + } + throw error50; + } + if (this.minLength <= 0) { + cb?.(); + return; + } + if (cb) { + callFlushCallbackOnDrain.call(this, cb); + } + if (this._writing) { + return; + } + if (this._bufs.length === 0) { + this._bufs.push(""); + } + this._actualWrite(); + } + function flushBuffer(cb) { + if (cb != null && typeof cb !== "function") { + throw new Error("flush cb must be a function"); + } + if (this.destroyed) { + const error50 = new Error("SonicBoom destroyed"); + if (cb) { + cb(error50); + return; + } + throw error50; + } + if (this.minLength <= 0) { + cb?.(); + return; + } + if (cb) { + callFlushCallbackOnDrain.call(this, cb); + } + if (this._writing) { + return; + } + if (this._bufs.length === 0) { + this._bufs.push([]); + this._lens.push(0); + } + this._actualWrite(); + } + SonicBoom.prototype.reopen = function(file2) { + if (this.destroyed) { + throw new Error("SonicBoom destroyed"); + } + if (this._opening) { + this.once("ready", () => { + this.reopen(file2); + }); + return; + } + if (this._ending) { + return; + } + if (!this.file) { + throw new Error("Unable to reopen a file descriptor, you must pass a file to SonicBoom"); + } + if (file2) { + this.file = file2; + } + this._reopening = true; + if (this._writing) { + return; + } + const fd = this.fd; + this.once("ready", () => { + if (fd !== this.fd) { + fs41.close(fd, (err) => { + if (err) { + return this.emit("error", err); + } + }); + } + }); + openFile(this.file, this); + }; + SonicBoom.prototype.end = function() { + if (this.destroyed) { + throw new Error("SonicBoom destroyed"); + } + if (this._opening) { + this.once("ready", () => { + this.end(); + }); + return; + } + if (this._ending) { + return; + } + this._ending = true; + if (this._writing) { + return; + } + if (this._len > 0 && this.fd >= 0) { + this._actualWrite(); + } else { + actualClose(this); + } + }; + function flushSync() { + if (this.destroyed) { + throw new Error("SonicBoom destroyed"); + } + if (this.fd < 0) { + throw new Error("sonic boom is not ready yet"); + } + if (!this._writing && this._writingBuf.length > 0) { + this._bufs.unshift(this._writingBuf); + this._writingBuf = ""; + } + let buf = ""; + while (this._bufs.length || buf.length) { + if (buf.length <= 0) { + buf = this._bufs[0]; + } + try { + const n5 = Buffer.isBuffer(buf) ? fs41.writeSync(this.fd, buf) : fs41.writeSync(this.fd, buf, "utf8"); + const releasedBufObj = releaseWritingBuf(buf, this._len, n5); + buf = releasedBufObj.writingBuf; + this._len = releasedBufObj.len; + if (buf.length <= 0) { + this._bufs.shift(); + } + } catch (err) { + const shouldRetry = err.code === "EAGAIN" || err.code === "EBUSY"; + if (shouldRetry && !this.retryEAGAIN(err, buf.length, this._len - buf.length)) { + throw err; + } + sleep(BUSY_WRITE_TIMEOUT); + } + } + try { + fs41.fsyncSync(this.fd); + } catch { + } + } + function flushBufferSync() { + if (this.destroyed) { + throw new Error("SonicBoom destroyed"); + } + if (this.fd < 0) { + throw new Error("sonic boom is not ready yet"); + } + if (!this._writing && this._writingBuf.length > 0) { + this._bufs.unshift([this._writingBuf]); + this._writingBuf = kEmptyBuffer; + } + let buf = kEmptyBuffer; + while (this._bufs.length || buf.length) { + if (buf.length <= 0) { + buf = mergeBuf(this._bufs[0], this._lens[0]); + } + try { + const n5 = fs41.writeSync(this.fd, buf); + buf = buf.subarray(n5); + this._len = Math.max(this._len - n5, 0); + if (buf.length <= 0) { + this._bufs.shift(); + this._lens.shift(); + } + } catch (err) { + const shouldRetry = err.code === "EAGAIN" || err.code === "EBUSY"; + if (shouldRetry && !this.retryEAGAIN(err, buf.length, this._len - buf.length)) { + throw err; + } + sleep(BUSY_WRITE_TIMEOUT); + } + } + } + SonicBoom.prototype.destroy = function() { + if (this.destroyed) { + return; + } + actualClose(this); + }; + function actualWrite() { + const release = this.release; + this._writing = true; + this._writingBuf = this._writingBuf.length ? this._writingBuf : this._bufs.shift() || ""; + if (this.sync) { + try { + const written = Buffer.isBuffer(this._writingBuf) ? fs41.writeSync(this.fd, this._writingBuf) : fs41.writeSync(this.fd, this._writingBuf, "utf8"); + release(null, written); + } catch (err) { + release(err); + } + } else { + fs41.write(this.fd, this._writingBuf, release); + } + } + function actualWriteBuffer() { + const release = this.release; + this._writing = true; + this._writingBuf = this._writingBuf.length ? this._writingBuf : mergeBuf(this._bufs.shift(), this._lens.shift()); + if (this.sync) { + try { + const written = fs41.writeSync(this.fd, this._writingBuf); + release(null, written); + } catch (err) { + release(err); + } + } else { + if (kCopyBuffer) { + this._writingBuf = Buffer.from(this._writingBuf); + } + fs41.write(this.fd, this._writingBuf, release); + } + } + function actualClose(sonic) { + if (sonic.fd === -1) { + sonic.once("ready", actualClose.bind(null, sonic)); + return; + } + if (sonic._periodicFlushTimer !== void 0) { + clearInterval(sonic._periodicFlushTimer); + } + sonic.destroyed = true; + sonic._bufs = []; + sonic._lens = []; + assert2(typeof sonic.fd === "number", `sonic.fd must be a number, got ${typeof sonic.fd}`); + try { + fs41.fsync(sonic.fd, closeWrapped); + } catch { + } + function closeWrapped() { + if (sonic.fd !== 1 && sonic.fd !== 2) { + fs41.close(sonic.fd, done); + } else { + done(); + } + } + function done(err) { + if (err) { + sonic.emit("error", err); + return; + } + if (sonic._ending && !sonic._writing) { + sonic.emit("finish"); + } + sonic.emit("close"); + } + } + SonicBoom.SonicBoom = SonicBoom; + SonicBoom.default = SonicBoom; + module.exports = SonicBoom; + } +}); + +// node_modules/.pnpm/on-exit-leak-free@2.1.2/node_modules/on-exit-leak-free/index.js +var require_on_exit_leak_free = __commonJS({ + "node_modules/.pnpm/on-exit-leak-free@2.1.2/node_modules/on-exit-leak-free/index.js"(exports, module) { + "use strict"; + var refs = { + exit: [], + beforeExit: [] + }; + var functions = { + exit: onExit, + beforeExit: onBeforeExit + }; + var registry2; + function ensureRegistry() { + if (registry2 === void 0) { + registry2 = new FinalizationRegistry(clear); + } + } + function install(event) { + if (refs[event].length > 0) { + return; + } + process.on(event, functions[event]); + } + function uninstall(event) { + if (refs[event].length > 0) { + return; + } + process.removeListener(event, functions[event]); + if (refs.exit.length === 0 && refs.beforeExit.length === 0) { + registry2 = void 0; + } + } + function onExit() { + callRefs("exit"); + } + function onBeforeExit() { + callRefs("beforeExit"); + } + function callRefs(event) { + for (const ref of refs[event]) { + const obj = ref.deref(); + const fn = ref.fn; + if (obj !== void 0) { + fn(obj, event); + } + } + refs[event] = []; + } + function clear(ref) { + for (const event of ["exit", "beforeExit"]) { + const index2 = refs[event].indexOf(ref); + refs[event].splice(index2, index2 + 1); + uninstall(event); + } + } + function _register(event, obj, fn) { + if (obj === void 0) { + throw new Error("the object can't be undefined"); + } + install(event); + const ref = new WeakRef(obj); + ref.fn = fn; + ensureRegistry(); + registry2.register(obj, ref); + refs[event].push(ref); + } + function register(obj, fn) { + _register("exit", obj, fn); + } + function registerBeforeExit(obj, fn) { + _register("beforeExit", obj, fn); + } + function unregister(obj) { + if (registry2 === void 0) { + return; + } + registry2.unregister(obj); + for (const event of ["exit", "beforeExit"]) { + refs[event] = refs[event].filter((ref) => { + const _obj = ref.deref(); + return _obj && _obj !== obj; + }); + uninstall(event); + } + } + module.exports = { + register, + registerBeforeExit, + unregister + }; + } +}); + +// node_modules/.pnpm/thread-stream@3.1.0/node_modules/thread-stream/package.json +var require_package = __commonJS({ + "node_modules/.pnpm/thread-stream@3.1.0/node_modules/thread-stream/package.json"(exports, module) { + module.exports = { + name: "thread-stream", + version: "3.1.0", + description: "A streaming way to send data to a Node.js Worker Thread", + main: "index.js", + types: "index.d.ts", + dependencies: { + "real-require": "^0.2.0" + }, + devDependencies: { + "@types/node": "^20.1.0", + "@types/tap": "^15.0.0", + "@yao-pkg/pkg": "^5.11.5", + desm: "^1.3.0", + fastbench: "^1.0.1", + husky: "^9.0.6", + "pino-elasticsearch": "^8.0.0", + "sonic-boom": "^4.0.1", + standard: "^17.0.0", + tap: "^16.2.0", + "ts-node": "^10.8.0", + typescript: "^5.3.2", + "why-is-node-running": "^2.2.2" + }, + scripts: { + build: "tsc --noEmit", + test: 'standard && npm run build && npm run transpile && tap "test/**/*.test.*js" && tap --ts test/*.test.*ts', + "test:ci": "standard && npm run transpile && npm run test:ci:js && npm run test:ci:ts", + "test:ci:js": 'tap --no-check-coverage --timeout=120 --coverage-report=lcovonly "test/**/*.test.*js"', + "test:ci:ts": 'tap --ts --no-check-coverage --coverage-report=lcovonly "test/**/*.test.*ts"', + "test:yarn": 'npm run transpile && tap "test/**/*.test.js" --no-check-coverage', + transpile: "sh ./test/ts/transpile.sh", + prepare: "husky install" + }, + standard: { + ignore: [ + "test/ts/**/*", + "test/syntax-error.mjs" + ] + }, + repository: { + type: "git", + url: "git+https://github.com/mcollina/thread-stream.git" + }, + keywords: [ + "worker", + "thread", + "threads", + "stream" + ], + author: "Matteo Collina ", + license: "MIT", + bugs: { + url: "https://github.com/mcollina/thread-stream/issues" + }, + homepage: "https://github.com/mcollina/thread-stream#readme" + }; + } +}); + +// node_modules/.pnpm/thread-stream@3.1.0/node_modules/thread-stream/lib/wait.js +var require_wait = __commonJS({ + "node_modules/.pnpm/thread-stream@3.1.0/node_modules/thread-stream/lib/wait.js"(exports, module) { + "use strict"; + var MAX_TIMEOUT = 1e3; + function wait(state2, index2, expected, timeout, done) { + const max = Date.now() + timeout; + let current = Atomics.load(state2, index2); + if (current === expected) { + done(null, "ok"); + return; + } + let prior = current; + const check3 = (backoff2) => { + if (Date.now() > max) { + done(null, "timed-out"); + } else { + setTimeout(() => { + prior = current; + current = Atomics.load(state2, index2); + if (current === prior) { + check3(backoff2 >= MAX_TIMEOUT ? MAX_TIMEOUT : backoff2 * 2); + } else { + if (current === expected) done(null, "ok"); + else done(null, "not-equal"); + } + }, backoff2); + } + }; + check3(1); + } + function waitDiff(state2, index2, expected, timeout, done) { + const max = Date.now() + timeout; + let current = Atomics.load(state2, index2); + if (current !== expected) { + done(null, "ok"); + return; + } + const check3 = (backoff2) => { + if (Date.now() > max) { + done(null, "timed-out"); + } else { + setTimeout(() => { + current = Atomics.load(state2, index2); + if (current !== expected) { + done(null, "ok"); + } else { + check3(backoff2 >= MAX_TIMEOUT ? MAX_TIMEOUT : backoff2 * 2); + } + }, backoff2); + } + }; + check3(1); + } + module.exports = { wait, waitDiff }; + } +}); + +// node_modules/.pnpm/thread-stream@3.1.0/node_modules/thread-stream/lib/indexes.js +var require_indexes = __commonJS({ + "node_modules/.pnpm/thread-stream@3.1.0/node_modules/thread-stream/lib/indexes.js"(exports, module) { + "use strict"; + var WRITE_INDEX = 4; + var READ_INDEX = 8; + module.exports = { + WRITE_INDEX, + READ_INDEX + }; + } +}); + +// node_modules/.pnpm/thread-stream@3.1.0/node_modules/thread-stream/index.js +var require_thread_stream = __commonJS({ + "node_modules/.pnpm/thread-stream@3.1.0/node_modules/thread-stream/index.js"(exports, module) { + "use strict"; + var { version: version3 } = require_package(); + var { EventEmitter: EventEmitter5 } = __require("events"); + var { Worker } = __require("worker_threads"); + var { join: join4 } = __require("path"); + var { pathToFileURL } = __require("url"); + var { wait } = require_wait(); + var { + WRITE_INDEX, + READ_INDEX + } = require_indexes(); + var buffer2 = __require("buffer"); + var assert2 = __require("assert"); + var kImpl = /* @__PURE__ */ Symbol("kImpl"); + var MAX_STRING = buffer2.constants.MAX_STRING_LENGTH; + var FakeWeakRef = class { + constructor(value) { + this._value = value; + } + deref() { + return this._value; + } + }; + var FakeFinalizationRegistry = class { + register() { + } + unregister() { + } + }; + var FinalizationRegistry2 = process.env.NODE_V8_COVERAGE ? FakeFinalizationRegistry : global.FinalizationRegistry || FakeFinalizationRegistry; + var WeakRef2 = process.env.NODE_V8_COVERAGE ? FakeWeakRef : global.WeakRef || FakeWeakRef; + var registry2 = new FinalizationRegistry2((worker) => { + if (worker.exited) { + return; + } + worker.terminate(); + }); + function createWorker(stream, opts) { + const { filename, workerData } = opts; + const bundlerOverrides = "__bundlerPathsOverrides" in globalThis ? globalThis.__bundlerPathsOverrides : {}; + const toExecute = bundlerOverrides["thread-stream-worker"] || join4(__dirname, "lib", "worker.js"); + const worker = new Worker(toExecute, { + ...opts.workerOpts, + trackUnmanagedFds: false, + workerData: { + filename: filename.indexOf("file://") === 0 ? filename : pathToFileURL(filename).href, + dataBuf: stream[kImpl].dataBuf, + stateBuf: stream[kImpl].stateBuf, + workerData: { + $context: { + threadStreamVersion: version3 + }, + ...workerData + } + } + }); + worker.stream = new FakeWeakRef(stream); + worker.on("message", onWorkerMessage); + worker.on("exit", onWorkerExit); + registry2.register(stream, worker); + return worker; + } + function drain(stream) { + assert2(!stream[kImpl].sync); + if (stream[kImpl].needDrain) { + stream[kImpl].needDrain = false; + stream.emit("drain"); + } + } + function nextFlush(stream) { + const writeIndex = Atomics.load(stream[kImpl].state, WRITE_INDEX); + let leftover = stream[kImpl].data.length - writeIndex; + if (leftover > 0) { + if (stream[kImpl].buf.length === 0) { + stream[kImpl].flushing = false; + if (stream[kImpl].ending) { + end(stream); + } else if (stream[kImpl].needDrain) { + process.nextTick(drain, stream); + } + return; + } + let toWrite = stream[kImpl].buf.slice(0, leftover); + let toWriteBytes = Buffer.byteLength(toWrite); + if (toWriteBytes <= leftover) { + stream[kImpl].buf = stream[kImpl].buf.slice(leftover); + write(stream, toWrite, nextFlush.bind(null, stream)); + } else { + stream.flush(() => { + if (stream.destroyed) { + return; + } + Atomics.store(stream[kImpl].state, READ_INDEX, 0); + Atomics.store(stream[kImpl].state, WRITE_INDEX, 0); + while (toWriteBytes > stream[kImpl].data.length) { + leftover = leftover / 2; + toWrite = stream[kImpl].buf.slice(0, leftover); + toWriteBytes = Buffer.byteLength(toWrite); + } + stream[kImpl].buf = stream[kImpl].buf.slice(leftover); + write(stream, toWrite, nextFlush.bind(null, stream)); + }); + } + } else if (leftover === 0) { + if (writeIndex === 0 && stream[kImpl].buf.length === 0) { + return; + } + stream.flush(() => { + Atomics.store(stream[kImpl].state, READ_INDEX, 0); + Atomics.store(stream[kImpl].state, WRITE_INDEX, 0); + nextFlush(stream); + }); + } else { + destroy(stream, new Error("overwritten")); + } + } + function onWorkerMessage(msg) { + const stream = this.stream.deref(); + if (stream === void 0) { + this.exited = true; + this.terminate(); + return; + } + switch (msg.code) { + case "READY": + this.stream = new WeakRef2(stream); + stream.flush(() => { + stream[kImpl].ready = true; + stream.emit("ready"); + }); + break; + case "ERROR": + destroy(stream, msg.err); + break; + case "EVENT": + if (Array.isArray(msg.args)) { + stream.emit(msg.name, ...msg.args); + } else { + stream.emit(msg.name, msg.args); + } + break; + case "WARNING": + process.emitWarning(msg.err); + break; + default: + destroy(stream, new Error("this should not happen: " + msg.code)); + } + } + function onWorkerExit(code) { + const stream = this.stream.deref(); + if (stream === void 0) { + return; + } + registry2.unregister(stream); + stream.worker.exited = true; + stream.worker.off("exit", onWorkerExit); + destroy(stream, code !== 0 ? new Error("the worker thread exited") : null); + } + var ThreadStream = class extends EventEmitter5 { + constructor(opts = {}) { + super(); + if (opts.bufferSize < 4) { + throw new Error("bufferSize must at least fit a 4-byte utf-8 char"); + } + this[kImpl] = {}; + this[kImpl].stateBuf = new SharedArrayBuffer(128); + this[kImpl].state = new Int32Array(this[kImpl].stateBuf); + this[kImpl].dataBuf = new SharedArrayBuffer(opts.bufferSize || 4 * 1024 * 1024); + this[kImpl].data = Buffer.from(this[kImpl].dataBuf); + this[kImpl].sync = opts.sync || false; + this[kImpl].ending = false; + this[kImpl].ended = false; + this[kImpl].needDrain = false; + this[kImpl].destroyed = false; + this[kImpl].flushing = false; + this[kImpl].ready = false; + this[kImpl].finished = false; + this[kImpl].errored = null; + this[kImpl].closed = false; + this[kImpl].buf = ""; + this.worker = createWorker(this, opts); + this.on("message", (message2, transferList) => { + this.worker.postMessage(message2, transferList); + }); + } + write(data2) { + if (this[kImpl].destroyed) { + error50(this, new Error("the worker has exited")); + return false; + } + if (this[kImpl].ending) { + error50(this, new Error("the worker is ending")); + return false; + } + if (this[kImpl].flushing && this[kImpl].buf.length + data2.length >= MAX_STRING) { + try { + writeSync(this); + this[kImpl].flushing = true; + } catch (err) { + destroy(this, err); + return false; + } + } + this[kImpl].buf += data2; + if (this[kImpl].sync) { + try { + writeSync(this); + return true; + } catch (err) { + destroy(this, err); + return false; + } + } + if (!this[kImpl].flushing) { + this[kImpl].flushing = true; + setImmediate(nextFlush, this); + } + this[kImpl].needDrain = this[kImpl].data.length - this[kImpl].buf.length - Atomics.load(this[kImpl].state, WRITE_INDEX) <= 0; + return !this[kImpl].needDrain; + } + end() { + if (this[kImpl].destroyed) { + return; + } + this[kImpl].ending = true; + end(this); + } + flush(cb) { + if (this[kImpl].destroyed) { + if (typeof cb === "function") { + process.nextTick(cb, new Error("the worker has exited")); + } + return; + } + const writeIndex = Atomics.load(this[kImpl].state, WRITE_INDEX); + wait(this[kImpl].state, READ_INDEX, writeIndex, Infinity, (err, res) => { + if (err) { + destroy(this, err); + process.nextTick(cb, err); + return; + } + if (res === "not-equal") { + this.flush(cb); + return; + } + process.nextTick(cb); + }); + } + flushSync() { + if (this[kImpl].destroyed) { + return; + } + writeSync(this); + flushSync(this); + } + unref() { + this.worker.unref(); + } + ref() { + this.worker.ref(); + } + get ready() { + return this[kImpl].ready; + } + get destroyed() { + return this[kImpl].destroyed; + } + get closed() { + return this[kImpl].closed; + } + get writable() { + return !this[kImpl].destroyed && !this[kImpl].ending; + } + get writableEnded() { + return this[kImpl].ending; + } + get writableFinished() { + return this[kImpl].finished; + } + get writableNeedDrain() { + return this[kImpl].needDrain; + } + get writableObjectMode() { + return false; + } + get writableErrored() { + return this[kImpl].errored; + } + }; + function error50(stream, err) { + setImmediate(() => { + stream.emit("error", err); + }); + } + function destroy(stream, err) { + if (stream[kImpl].destroyed) { + return; + } + stream[kImpl].destroyed = true; + if (err) { + stream[kImpl].errored = err; + error50(stream, err); + } + if (!stream.worker.exited) { + stream.worker.terminate().catch(() => { + }).then(() => { + stream[kImpl].closed = true; + stream.emit("close"); + }); + } else { + setImmediate(() => { + stream[kImpl].closed = true; + stream.emit("close"); + }); + } + } + function write(stream, data2, cb) { + const current = Atomics.load(stream[kImpl].state, WRITE_INDEX); + const length = Buffer.byteLength(data2); + stream[kImpl].data.write(data2, current); + Atomics.store(stream[kImpl].state, WRITE_INDEX, current + length); + Atomics.notify(stream[kImpl].state, WRITE_INDEX); + cb(); + return true; + } + function end(stream) { + if (stream[kImpl].ended || !stream[kImpl].ending || stream[kImpl].flushing) { + return; + } + stream[kImpl].ended = true; + try { + stream.flushSync(); + let readIndex = Atomics.load(stream[kImpl].state, READ_INDEX); + Atomics.store(stream[kImpl].state, WRITE_INDEX, -1); + Atomics.notify(stream[kImpl].state, WRITE_INDEX); + let spins = 0; + while (readIndex !== -1) { + Atomics.wait(stream[kImpl].state, READ_INDEX, readIndex, 1e3); + readIndex = Atomics.load(stream[kImpl].state, READ_INDEX); + if (readIndex === -2) { + destroy(stream, new Error("end() failed")); + return; + } + if (++spins === 10) { + destroy(stream, new Error("end() took too long (10s)")); + return; + } + } + process.nextTick(() => { + stream[kImpl].finished = true; + stream.emit("finish"); + }); + } catch (err) { + destroy(stream, err); + } + } + function writeSync(stream) { + const cb = () => { + if (stream[kImpl].ending) { + end(stream); + } else if (stream[kImpl].needDrain) { + process.nextTick(drain, stream); + } + }; + stream[kImpl].flushing = false; + while (stream[kImpl].buf.length !== 0) { + const writeIndex = Atomics.load(stream[kImpl].state, WRITE_INDEX); + let leftover = stream[kImpl].data.length - writeIndex; + if (leftover === 0) { + flushSync(stream); + Atomics.store(stream[kImpl].state, READ_INDEX, 0); + Atomics.store(stream[kImpl].state, WRITE_INDEX, 0); + continue; + } else if (leftover < 0) { + throw new Error("overwritten"); + } + let toWrite = stream[kImpl].buf.slice(0, leftover); + let toWriteBytes = Buffer.byteLength(toWrite); + if (toWriteBytes <= leftover) { + stream[kImpl].buf = stream[kImpl].buf.slice(leftover); + write(stream, toWrite, cb); + } else { + flushSync(stream); + Atomics.store(stream[kImpl].state, READ_INDEX, 0); + Atomics.store(stream[kImpl].state, WRITE_INDEX, 0); + while (toWriteBytes > stream[kImpl].buf.length) { + leftover = leftover / 2; + toWrite = stream[kImpl].buf.slice(0, leftover); + toWriteBytes = Buffer.byteLength(toWrite); + } + stream[kImpl].buf = stream[kImpl].buf.slice(leftover); + write(stream, toWrite, cb); + } + } + } + function flushSync(stream) { + if (stream[kImpl].flushing) { + throw new Error("unable to flush while flushing"); + } + const writeIndex = Atomics.load(stream[kImpl].state, WRITE_INDEX); + let spins = 0; + while (true) { + const readIndex = Atomics.load(stream[kImpl].state, READ_INDEX); + if (readIndex === -2) { + throw Error("_flushSync failed"); + } + if (readIndex !== writeIndex) { + Atomics.wait(stream[kImpl].state, READ_INDEX, readIndex, 1e3); + } else { + break; + } + if (++spins === 10) { + throw new Error("_flushSync took too long (10s)"); + } + } + } + module.exports = ThreadStream; + } +}); + +// node_modules/.pnpm/pino@9.14.0/node_modules/pino/lib/transport.js +var require_transport = __commonJS({ + "node_modules/.pnpm/pino@9.14.0/node_modules/pino/lib/transport.js"(exports, module) { + "use strict"; + var { createRequire: createRequire2 } = __require("module"); + var getCallers = require_caller(); + var { join: join4, isAbsolute: isAbsolute2, sep } = __require("node:path"); + var sleep = require_atomic_sleep(); + var onExit = require_on_exit_leak_free(); + var ThreadStream = require_thread_stream(); + function setupOnExit(stream) { + onExit.register(stream, autoEnd); + onExit.registerBeforeExit(stream, flush); + stream.on("close", function() { + onExit.unregister(stream); + }); + } + function buildStream(filename, workerData, workerOpts, sync) { + const stream = new ThreadStream({ + filename, + workerData, + workerOpts, + sync + }); + stream.on("ready", onReady); + stream.on("close", function() { + process.removeListener("exit", onExit2); + }); + process.on("exit", onExit2); + function onReady() { + process.removeListener("exit", onExit2); + stream.unref(); + if (workerOpts.autoEnd !== false) { + setupOnExit(stream); + } + } + function onExit2() { + if (stream.closed) { + return; + } + stream.flushSync(); + sleep(100); + stream.end(); + } + return stream; + } + function autoEnd(stream) { + stream.ref(); + stream.flushSync(); + stream.end(); + stream.once("close", function() { + stream.unref(); + }); + } + function flush(stream) { + stream.flushSync(); + } + function transport(fullOptions) { + const { pipeline, targets, levels: levels2, dedupe, worker = {}, caller = getCallers(), sync = false } = fullOptions; + const options = { + ...fullOptions.options + }; + const callers = typeof caller === "string" ? [caller] : caller; + const bundlerOverrides = "__bundlerPathsOverrides" in globalThis ? globalThis.__bundlerPathsOverrides : {}; + let target = fullOptions.target; + if (target && targets) { + throw new Error("only one of target or targets can be specified"); + } + if (targets) { + target = bundlerOverrides["pino-worker"] || join4(__dirname, "worker.js"); + options.targets = targets.filter((dest) => dest.target).map((dest) => { + return { + ...dest, + target: fixTarget(dest.target) + }; + }); + options.pipelines = targets.filter((dest) => dest.pipeline).map((dest) => { + return dest.pipeline.map((t5) => { + return { + ...t5, + level: dest.level, + // duplicate the pipeline `level` property defined in the upper level + target: fixTarget(t5.target) + }; + }); + }); + } else if (pipeline) { + target = bundlerOverrides["pino-worker"] || join4(__dirname, "worker.js"); + options.pipelines = [pipeline.map((dest) => { + return { + ...dest, + target: fixTarget(dest.target) + }; + })]; + } + if (levels2) { + options.levels = levels2; + } + if (dedupe) { + options.dedupe = dedupe; + } + options.pinoWillSendConfig = true; + return buildStream(fixTarget(target), options, worker, sync); + function fixTarget(origin) { + origin = bundlerOverrides[origin] || origin; + if (isAbsolute2(origin) || origin.indexOf("file://") === 0) { + return origin; + } + if (origin === "pino/file") { + return join4(__dirname, "..", "file.js"); + } + let fixTarget2; + for (const filePath of callers) { + try { + const context = filePath === "node:repl" ? process.cwd() + sep : filePath; + fixTarget2 = createRequire2(context).resolve(origin); + break; + } catch (err) { + continue; + } + } + if (!fixTarget2) { + throw new Error(`unable to determine transport target for "${origin}"`); + } + return fixTarget2; + } + } + module.exports = transport; + } +}); + +// node_modules/.pnpm/pino@9.14.0/node_modules/pino/lib/tools.js +var require_tools = __commonJS({ + "node_modules/.pnpm/pino@9.14.0/node_modules/pino/lib/tools.js"(exports, module) { + "use strict"; + var diagChan = __require("node:diagnostics_channel"); + var format2 = require_quick_format_unescaped(); + var { mapHttpRequest, mapHttpResponse } = require_pino_std_serializers(); + var SonicBoom = require_sonic_boom(); + var onExit = require_on_exit_leak_free(); + var { + lsCacheSym, + chindingsSym, + writeSym, + serializersSym, + formatOptsSym, + endSym, + stringifiersSym, + stringifySym, + stringifySafeSym, + wildcardFirstSym, + nestedKeySym, + formattersSym, + messageKeySym, + errorKeySym, + nestedKeyStrSym, + msgPrefixSym + } = require_symbols(); + var { isMainThread } = __require("worker_threads"); + var transport = require_transport(); + var asJsonChan; + if (typeof diagChan.tracingChannel === "function") { + asJsonChan = diagChan.tracingChannel("pino_asJson"); + } else { + asJsonChan = { + hasSubscribers: false, + traceSync(fn, store, thisArg, ...args) { + return fn.call(thisArg, ...args); + } + }; + } + function noop5() { + } + function genLog(level, hook) { + if (!hook) return LOG; + return function hookWrappedLog(...args) { + hook.call(this, args, LOG, level); + }; + function LOG(o5, ...n5) { + if (typeof o5 === "object") { + let msg = o5; + if (o5 !== null) { + if (o5.method && o5.headers && o5.socket) { + o5 = mapHttpRequest(o5); + } else if (typeof o5.setHeader === "function") { + o5 = mapHttpResponse(o5); + } + } + let formatParams; + if (msg === null && n5.length === 0) { + formatParams = [null]; + } else { + msg = n5.shift(); + formatParams = n5; + } + if (typeof this[msgPrefixSym] === "string" && msg !== void 0 && msg !== null) { + msg = this[msgPrefixSym] + msg; + } + this[writeSym](o5, format2(msg, formatParams, this[formatOptsSym]), level); + } else { + let msg = o5 === void 0 ? n5.shift() : o5; + if (typeof this[msgPrefixSym] === "string" && msg !== void 0 && msg !== null) { + msg = this[msgPrefixSym] + msg; + } + this[writeSym](null, format2(msg, n5, this[formatOptsSym]), level); + } + } + } + function asString15(str) { + let result = ""; + let last = 0; + let found = false; + let point2 = 255; + const l5 = str.length; + if (l5 > 100) { + return JSON.stringify(str); + } + for (var i5 = 0; i5 < l5 && point2 >= 32; i5++) { + point2 = str.charCodeAt(i5); + if (point2 === 34 || point2 === 92) { + result += str.slice(last, i5) + "\\"; + last = i5; + found = true; + } + } + if (!found) { + result = str; + } else { + result += str.slice(last); + } + return point2 < 32 ? JSON.stringify(str) : '"' + result + '"'; + } + function asJson(obj, msg, num, time5) { + if (asJsonChan.hasSubscribers === false) { + return _asJson.call(this, obj, msg, num, time5); + } + const store = { instance: this, arguments }; + return asJsonChan.traceSync(_asJson, store, this, obj, msg, num, time5); + } + function _asJson(obj, msg, num, time5) { + const stringify3 = this[stringifySym]; + const stringifySafe = this[stringifySafeSym]; + const stringifiers = this[stringifiersSym]; + const end = this[endSym]; + const chindings = this[chindingsSym]; + const serializers2 = this[serializersSym]; + const formatters = this[formattersSym]; + const messageKey = this[messageKeySym]; + const errorKey = this[errorKeySym]; + let data2 = this[lsCacheSym][num] + time5; + data2 = data2 + chindings; + let value; + if (formatters.log) { + obj = formatters.log(obj); + } + const wildcardStringifier = stringifiers[wildcardFirstSym]; + let propStr = ""; + for (const key in obj) { + value = obj[key]; + if (Object.prototype.hasOwnProperty.call(obj, key) && value !== void 0) { + if (serializers2[key]) { + value = serializers2[key](value); + } else if (key === errorKey && serializers2.err) { + value = serializers2.err(value); + } + const stringifier = stringifiers[key] || wildcardStringifier; + switch (typeof value) { + case "undefined": + case "function": + continue; + case "number": + if (Number.isFinite(value) === false) { + value = null; + } + // this case explicitly falls through to the next one + case "boolean": + if (stringifier) value = stringifier(value); + break; + case "string": + value = (stringifier || asString15)(value); + break; + default: + value = (stringifier || stringify3)(value, stringifySafe); + } + if (value === void 0) continue; + const strKey = asString15(key); + propStr += "," + strKey + ":" + value; + } + } + let msgStr = ""; + if (msg !== void 0) { + value = serializers2[messageKey] ? serializers2[messageKey](msg) : msg; + const stringifier = stringifiers[messageKey] || wildcardStringifier; + switch (typeof value) { + case "function": + break; + case "number": + if (Number.isFinite(value) === false) { + value = null; + } + // this case explicitly falls through to the next one + case "boolean": + if (stringifier) value = stringifier(value); + msgStr = ',"' + messageKey + '":' + value; + break; + case "string": + value = (stringifier || asString15)(value); + msgStr = ',"' + messageKey + '":' + value; + break; + default: + value = (stringifier || stringify3)(value, stringifySafe); + msgStr = ',"' + messageKey + '":' + value; + } + } + if (this[nestedKeySym] && propStr) { + return data2 + this[nestedKeyStrSym] + propStr.slice(1) + "}" + msgStr + end; + } else { + return data2 + propStr + msgStr + end; + } + } + function asChindings(instance, bindings) { + let value; + let data2 = instance[chindingsSym]; + const stringify3 = instance[stringifySym]; + const stringifySafe = instance[stringifySafeSym]; + const stringifiers = instance[stringifiersSym]; + const wildcardStringifier = stringifiers[wildcardFirstSym]; + const serializers2 = instance[serializersSym]; + const formatter = instance[formattersSym].bindings; + bindings = formatter(bindings); + for (const key in bindings) { + value = bindings[key]; + const valid = (key.length < 5 || key !== "level" && key !== "serializers" && key !== "formatters" && key !== "customLevels") && bindings.hasOwnProperty(key) && value !== void 0; + if (valid === true) { + value = serializers2[key] ? serializers2[key](value) : value; + value = (stringifiers[key] || wildcardStringifier || stringify3)(value, stringifySafe); + if (value === void 0) continue; + data2 += ',"' + key + '":' + value; + } + } + return data2; + } + function hasBeenTampered(stream) { + return stream.write !== stream.constructor.prototype.write; + } + function buildSafeSonicBoom(opts) { + const stream = new SonicBoom(opts); + stream.on("error", filterBrokenPipe); + if (!opts.sync && isMainThread) { + onExit.register(stream, autoEnd); + stream.on("close", function() { + onExit.unregister(stream); + }); + } + return stream; + function filterBrokenPipe(err) { + if (err.code === "EPIPE") { + stream.write = noop5; + stream.end = noop5; + stream.flushSync = noop5; + stream.destroy = noop5; + return; + } + stream.removeListener("error", filterBrokenPipe); + stream.emit("error", err); + } + } + function autoEnd(stream, eventName) { + if (stream.destroyed) { + return; + } + if (eventName === "beforeExit") { + stream.flush(); + stream.on("drain", function() { + stream.end(); + }); + } else { + stream.flushSync(); + } + } + function createArgsNormalizer(defaultOptions2) { + return function normalizeArgs(instance, caller, opts = {}, stream) { + if (typeof opts === "string") { + stream = buildSafeSonicBoom({ dest: opts }); + opts = {}; + } else if (typeof stream === "string") { + if (opts && opts.transport) { + throw Error("only one of option.transport or stream can be specified"); + } + stream = buildSafeSonicBoom({ dest: stream }); + } else if (opts instanceof SonicBoom || opts.writable || opts._writableState) { + stream = opts; + opts = {}; + } else if (opts.transport) { + if (opts.transport instanceof SonicBoom || opts.transport.writable || opts.transport._writableState) { + throw Error("option.transport do not allow stream, please pass to option directly. e.g. pino(transport)"); + } + if (opts.transport.targets && opts.transport.targets.length && opts.formatters && typeof opts.formatters.level === "function") { + throw Error("option.transport.targets do not allow custom level formatters"); + } + let customLevels; + if (opts.customLevels) { + customLevels = opts.useOnlyCustomLevels ? opts.customLevels : Object.assign({}, opts.levels, opts.customLevels); + } + stream = transport({ caller, ...opts.transport, levels: customLevels }); + } + opts = Object.assign({}, defaultOptions2, opts); + opts.serializers = Object.assign({}, defaultOptions2.serializers, opts.serializers); + opts.formatters = Object.assign({}, defaultOptions2.formatters, opts.formatters); + if (opts.prettyPrint) { + throw new Error("prettyPrint option is no longer supported, see the pino-pretty package (https://github.com/pinojs/pino-pretty)"); + } + const { enabled, onChild } = opts; + if (enabled === false) opts.level = "silent"; + if (!onChild) opts.onChild = noop5; + if (!stream) { + if (!hasBeenTampered(process.stdout)) { + stream = buildSafeSonicBoom({ fd: process.stdout.fd || 1 }); + } else { + stream = process.stdout; + } + } + return { opts, stream }; + }; + } + function stringify2(obj, stringifySafeFn) { + try { + return JSON.stringify(obj); + } catch (_) { + try { + const stringify3 = stringifySafeFn || this[stringifySafeSym]; + return stringify3(obj); + } catch (_2) { + return '"[unable to serialize, circular reference is too complex to analyze]"'; + } + } + } + function buildFormatters(level, bindings, log2) { + return { + level, + bindings, + log: log2 + }; + } + function normalizeDestFileDescriptor(destination) { + const fd = Number(destination); + if (typeof destination === "string" && Number.isFinite(fd)) { + return fd; + } + if (destination === void 0) { + return 1; + } + return destination; + } + module.exports = { + noop: noop5, + buildSafeSonicBoom, + asChindings, + asJson, + genLog, + createArgsNormalizer, + stringify: stringify2, + buildFormatters, + normalizeDestFileDescriptor + }; + } +}); + +// node_modules/.pnpm/pino@9.14.0/node_modules/pino/lib/constants.js +var require_constants = __commonJS({ + "node_modules/.pnpm/pino@9.14.0/node_modules/pino/lib/constants.js"(exports, module) { + var DEFAULT_LEVELS = { + trace: 10, + debug: 20, + info: 30, + warn: 40, + error: 50, + fatal: 60 + }; + var SORTING_ORDER = { + ASC: "ASC", + DESC: "DESC" + }; + module.exports = { + DEFAULT_LEVELS, + SORTING_ORDER + }; + } +}); + +// node_modules/.pnpm/pino@9.14.0/node_modules/pino/lib/levels.js +var require_levels = __commonJS({ + "node_modules/.pnpm/pino@9.14.0/node_modules/pino/lib/levels.js"(exports, module) { + "use strict"; + var { + lsCacheSym, + levelValSym, + useOnlyCustomLevelsSym, + streamSym, + formattersSym, + hooksSym, + levelCompSym + } = require_symbols(); + var { noop: noop5, genLog } = require_tools(); + var { DEFAULT_LEVELS, SORTING_ORDER } = require_constants(); + var levelMethods = { + fatal: (hook) => { + const logFatal = genLog(DEFAULT_LEVELS.fatal, hook); + return function(...args) { + const stream = this[streamSym]; + logFatal.call(this, ...args); + if (typeof stream.flushSync === "function") { + try { + stream.flushSync(); + } catch (e5) { + } + } + }; + }, + error: (hook) => genLog(DEFAULT_LEVELS.error, hook), + warn: (hook) => genLog(DEFAULT_LEVELS.warn, hook), + info: (hook) => genLog(DEFAULT_LEVELS.info, hook), + debug: (hook) => genLog(DEFAULT_LEVELS.debug, hook), + trace: (hook) => genLog(DEFAULT_LEVELS.trace, hook) + }; + var nums = Object.keys(DEFAULT_LEVELS).reduce((o5, k5) => { + o5[DEFAULT_LEVELS[k5]] = k5; + return o5; + }, {}); + var initialLsCache = Object.keys(nums).reduce((o5, k5) => { + o5[k5] = '{"level":' + Number(k5); + return o5; + }, {}); + function genLsCache(instance) { + const formatter = instance[formattersSym].level; + const { labels: labels2 } = instance.levels; + const cache7 = {}; + for (const label in labels2) { + const level = formatter(labels2[label], Number(label)); + cache7[label] = JSON.stringify(level).slice(0, -1); + } + instance[lsCacheSym] = cache7; + return instance; + } + function isStandardLevel(level, useOnlyCustomLevels) { + if (useOnlyCustomLevels) { + return false; + } + switch (level) { + case "fatal": + case "error": + case "warn": + case "info": + case "debug": + case "trace": + return true; + default: + return false; + } + } + function setLevel(level) { + const { labels: labels2, values: values2 } = this.levels; + if (typeof level === "number") { + if (labels2[level] === void 0) throw Error("unknown level value" + level); + level = labels2[level]; + } + if (values2[level] === void 0) throw Error("unknown level " + level); + const preLevelVal = this[levelValSym]; + const levelVal = this[levelValSym] = values2[level]; + const useOnlyCustomLevelsVal = this[useOnlyCustomLevelsSym]; + const levelComparison = this[levelCompSym]; + const hook = this[hooksSym].logMethod; + for (const key in values2) { + if (levelComparison(values2[key], levelVal) === false) { + this[key] = noop5; + continue; + } + this[key] = isStandardLevel(key, useOnlyCustomLevelsVal) ? levelMethods[key](hook) : genLog(values2[key], hook); + } + this.emit( + "level-change", + level, + levelVal, + labels2[preLevelVal], + preLevelVal, + this + ); + } + function getLevel(level) { + const { levels: levels2, levelVal } = this; + return levels2 && levels2.labels ? levels2.labels[levelVal] : ""; + } + function isLevelEnabled(logLevel) { + const { values: values2 } = this.levels; + const logLevelVal = values2[logLevel]; + return logLevelVal !== void 0 && this[levelCompSym](logLevelVal, this[levelValSym]); + } + function compareLevel(direction, current, expected) { + if (direction === SORTING_ORDER.DESC) { + return current <= expected; + } + return current >= expected; + } + function genLevelComparison(levelComparison) { + if (typeof levelComparison === "string") { + return compareLevel.bind(null, levelComparison); + } + return levelComparison; + } + function mappings(customLevels = null, useOnlyCustomLevels = false) { + const customNums = customLevels ? Object.keys(customLevels).reduce((o5, k5) => { + o5[customLevels[k5]] = k5; + return o5; + }, {}) : null; + const labels2 = Object.assign( + Object.create(Object.prototype, { Infinity: { value: "silent" } }), + useOnlyCustomLevels ? null : nums, + customNums + ); + const values2 = Object.assign( + Object.create(Object.prototype, { silent: { value: Infinity } }), + useOnlyCustomLevels ? null : DEFAULT_LEVELS, + customLevels + ); + return { labels: labels2, values: values2 }; + } + function assertDefaultLevelFound(defaultLevel, customLevels, useOnlyCustomLevels) { + if (typeof defaultLevel === "number") { + const values2 = [].concat( + Object.keys(customLevels || {}).map((key) => customLevels[key]), + useOnlyCustomLevels ? [] : Object.keys(nums).map((level) => +level), + Infinity + ); + if (!values2.includes(defaultLevel)) { + throw Error(`default level:${defaultLevel} must be included in custom levels`); + } + return; + } + const labels2 = Object.assign( + Object.create(Object.prototype, { silent: { value: Infinity } }), + useOnlyCustomLevels ? null : DEFAULT_LEVELS, + customLevels + ); + if (!(defaultLevel in labels2)) { + throw Error(`default level:${defaultLevel} must be included in custom levels`); + } + } + function assertNoLevelCollisions(levels2, customLevels) { + const { labels: labels2, values: values2 } = levels2; + for (const k5 in customLevels) { + if (k5 in values2) { + throw Error("levels cannot be overridden"); + } + if (customLevels[k5] in labels2) { + throw Error("pre-existing level values cannot be used for new levels"); + } + } + } + function assertLevelComparison(levelComparison) { + if (typeof levelComparison === "function") { + return; + } + if (typeof levelComparison === "string" && Object.values(SORTING_ORDER).includes(levelComparison)) { + return; + } + throw new Error('Levels comparison should be one of "ASC", "DESC" or "function" type'); + } + module.exports = { + initialLsCache, + genLsCache, + levelMethods, + getLevel, + setLevel, + isLevelEnabled, + mappings, + assertNoLevelCollisions, + assertDefaultLevelFound, + genLevelComparison, + assertLevelComparison + }; + } +}); + +// node_modules/.pnpm/pino@9.14.0/node_modules/pino/lib/meta.js +var require_meta = __commonJS({ + "node_modules/.pnpm/pino@9.14.0/node_modules/pino/lib/meta.js"(exports, module) { + "use strict"; + module.exports = { version: "9.14.0" }; + } +}); + +// node_modules/.pnpm/pino@9.14.0/node_modules/pino/lib/proto.js +var require_proto = __commonJS({ + "node_modules/.pnpm/pino@9.14.0/node_modules/pino/lib/proto.js"(exports, module) { + "use strict"; + var { EventEmitter: EventEmitter5 } = __require("node:events"); + var { + lsCacheSym, + levelValSym, + setLevelSym, + getLevelSym, + chindingsSym, + parsedChindingsSym, + mixinSym, + asJsonSym, + writeSym, + mixinMergeStrategySym, + timeSym, + timeSliceIndexSym, + streamSym, + serializersSym, + formattersSym, + errorKeySym, + messageKeySym, + useOnlyCustomLevelsSym, + needsMetadataGsym, + redactFmtSym, + stringifySym, + formatOptsSym, + stringifiersSym, + msgPrefixSym, + hooksSym + } = require_symbols(); + var { + getLevel, + setLevel, + isLevelEnabled, + mappings, + initialLsCache, + genLsCache, + assertNoLevelCollisions + } = require_levels(); + var { + asChindings, + asJson, + buildFormatters, + stringify: stringify2, + noop: noop5 + } = require_tools(); + var { + version: version3 + } = require_meta(); + var redaction = require_redaction(); + var constructor = class Pino { + }; + var prototype = { + constructor, + child, + bindings, + setBindings, + flush, + isLevelEnabled, + version: version3, + get level() { + return this[getLevelSym](); + }, + set level(lvl) { + this[setLevelSym](lvl); + }, + get levelVal() { + return this[levelValSym]; + }, + set levelVal(n5) { + throw Error("levelVal is read-only"); + }, + get msgPrefix() { + return this[msgPrefixSym]; + }, + get [Symbol.toStringTag]() { + return "Pino"; + }, + [lsCacheSym]: initialLsCache, + [writeSym]: write, + [asJsonSym]: asJson, + [getLevelSym]: getLevel, + [setLevelSym]: setLevel + }; + Object.setPrototypeOf(prototype, EventEmitter5.prototype); + module.exports = function() { + return Object.create(prototype); + }; + var resetChildingsFormatter = (bindings2) => bindings2; + function child(bindings2, options) { + if (!bindings2) { + throw Error("missing bindings for child Pino"); + } + const serializers2 = this[serializersSym]; + const formatters = this[formattersSym]; + const instance = Object.create(this); + if (options == null) { + if (instance[formattersSym].bindings !== resetChildingsFormatter) { + instance[formattersSym] = buildFormatters( + formatters.level, + resetChildingsFormatter, + formatters.log + ); + } + instance[chindingsSym] = asChindings(instance, bindings2); + instance[setLevelSym](this.level); + if (this.onChild !== noop5) { + this.onChild(instance); + } + return instance; + } + if (options.hasOwnProperty("serializers") === true) { + instance[serializersSym] = /* @__PURE__ */ Object.create(null); + for (const k5 in serializers2) { + instance[serializersSym][k5] = serializers2[k5]; + } + const parentSymbols = Object.getOwnPropertySymbols(serializers2); + for (var i5 = 0; i5 < parentSymbols.length; i5++) { + const ks = parentSymbols[i5]; + instance[serializersSym][ks] = serializers2[ks]; + } + for (const bk in options.serializers) { + instance[serializersSym][bk] = options.serializers[bk]; + } + const bindingsSymbols = Object.getOwnPropertySymbols(options.serializers); + for (var bi = 0; bi < bindingsSymbols.length; bi++) { + const bks = bindingsSymbols[bi]; + instance[serializersSym][bks] = options.serializers[bks]; + } + } else instance[serializersSym] = serializers2; + if (options.hasOwnProperty("formatters")) { + const { level, bindings: chindings, log: log2 } = options.formatters; + instance[formattersSym] = buildFormatters( + level || formatters.level, + chindings || resetChildingsFormatter, + log2 || formatters.log + ); + } else { + instance[formattersSym] = buildFormatters( + formatters.level, + resetChildingsFormatter, + formatters.log + ); + } + if (options.hasOwnProperty("customLevels") === true) { + assertNoLevelCollisions(this.levels, options.customLevels); + instance.levels = mappings(options.customLevels, instance[useOnlyCustomLevelsSym]); + genLsCache(instance); + } + if (typeof options.redact === "object" && options.redact !== null || Array.isArray(options.redact)) { + instance.redact = options.redact; + const stringifiers = redaction(instance.redact, stringify2); + const formatOpts = { stringify: stringifiers[redactFmtSym] }; + instance[stringifySym] = stringify2; + instance[stringifiersSym] = stringifiers; + instance[formatOptsSym] = formatOpts; + } + if (typeof options.msgPrefix === "string") { + instance[msgPrefixSym] = (this[msgPrefixSym] || "") + options.msgPrefix; + } + instance[chindingsSym] = asChindings(instance, bindings2); + const childLevel = options.level || this.level; + instance[setLevelSym](childLevel); + this.onChild(instance); + return instance; + } + function bindings() { + const chindings = this[chindingsSym]; + const chindingsJson = `{${chindings.substr(1)}}`; + const bindingsFromJson = JSON.parse(chindingsJson); + delete bindingsFromJson.pid; + delete bindingsFromJson.hostname; + return bindingsFromJson; + } + function setBindings(newBindings) { + const chindings = asChindings(this, newBindings); + this[chindingsSym] = chindings; + delete this[parsedChindingsSym]; + } + function defaultMixinMergeStrategy(mergeObject, mixinObject) { + return Object.assign(mixinObject, mergeObject); + } + function write(_obj, msg, num) { + const t5 = this[timeSym](); + const mixin = this[mixinSym]; + const errorKey = this[errorKeySym]; + const messageKey = this[messageKeySym]; + const mixinMergeStrategy = this[mixinMergeStrategySym] || defaultMixinMergeStrategy; + let obj; + const streamWriteHook = this[hooksSym].streamWrite; + if (_obj === void 0 || _obj === null) { + obj = {}; + } else if (_obj instanceof Error) { + obj = { [errorKey]: _obj }; + if (msg === void 0) { + msg = _obj.message; + } + } else { + obj = _obj; + if (msg === void 0 && _obj[messageKey] === void 0 && _obj[errorKey]) { + msg = _obj[errorKey].message; + } + } + if (mixin) { + obj = mixinMergeStrategy(obj, mixin(obj, num, this)); + } + const s5 = this[asJsonSym](obj, msg, num, t5); + const stream = this[streamSym]; + if (stream[needsMetadataGsym] === true) { + stream.lastLevel = num; + stream.lastObj = obj; + stream.lastMsg = msg; + stream.lastTime = t5.slice(this[timeSliceIndexSym]); + stream.lastLogger = this; + } + stream.write(streamWriteHook ? streamWriteHook(s5) : s5); + } + function flush(cb) { + if (cb != null && typeof cb !== "function") { + throw Error("callback must be a function"); + } + const stream = this[streamSym]; + if (typeof stream.flush === "function") { + stream.flush(cb || noop5); + } else if (cb) cb(); + } + } +}); + +// node_modules/.pnpm/safe-stable-stringify@2.5.0/node_modules/safe-stable-stringify/index.js +var require_safe_stable_stringify = __commonJS({ + "node_modules/.pnpm/safe-stable-stringify@2.5.0/node_modules/safe-stable-stringify/index.js"(exports, module) { + "use strict"; + var { hasOwnProperty } = Object.prototype; + var stringify2 = configure(); + stringify2.configure = configure; + stringify2.stringify = stringify2; + stringify2.default = stringify2; + exports.stringify = stringify2; + exports.configure = configure; + module.exports = stringify2; + var strEscapeSequencesRegExp = /[\u0000-\u001f\u0022\u005c\ud800-\udfff]/; + function strEscape(str) { + if (str.length < 5e3 && !strEscapeSequencesRegExp.test(str)) { + return `"${str}"`; + } + return JSON.stringify(str); + } + function sort(array2, comparator) { + if (array2.length > 200 || comparator) { + return array2.sort(comparator); + } + for (let i5 = 1; i5 < array2.length; i5++) { + const currentValue = array2[i5]; + let position = i5; + while (position !== 0 && array2[position - 1] > currentValue) { + array2[position] = array2[position - 1]; + position--; + } + array2[position] = currentValue; + } + return array2; + } + var typedArrayPrototypeGetSymbolToStringTag = Object.getOwnPropertyDescriptor( + Object.getPrototypeOf( + Object.getPrototypeOf( + new Int8Array() + ) + ), + Symbol.toStringTag + ).get; + function isTypedArrayWithEntries(value) { + return typedArrayPrototypeGetSymbolToStringTag.call(value) !== void 0 && value.length !== 0; + } + function stringifyTypedArray(array2, separator, maximumBreadth) { + if (array2.length < maximumBreadth) { + maximumBreadth = array2.length; + } + const whitespace = separator === "," ? "" : " "; + let res = `"0":${whitespace}${array2[0]}`; + for (let i5 = 1; i5 < maximumBreadth; i5++) { + res += `${separator}"${i5}":${whitespace}${array2[i5]}`; + } + return res; + } + function getCircularValueOption(options) { + if (hasOwnProperty.call(options, "circularValue")) { + const circularValue = options.circularValue; + if (typeof circularValue === "string") { + return `"${circularValue}"`; + } + if (circularValue == null) { + return circularValue; + } + if (circularValue === Error || circularValue === TypeError) { + return { + toString() { + throw new TypeError("Converting circular structure to JSON"); + } + }; + } + throw new TypeError('The "circularValue" argument must be of type string or the value null or undefined'); + } + return '"[Circular]"'; + } + function getDeterministicOption(options) { + let value; + if (hasOwnProperty.call(options, "deterministic")) { + value = options.deterministic; + if (typeof value !== "boolean" && typeof value !== "function") { + throw new TypeError('The "deterministic" argument must be of type boolean or comparator function'); + } + } + return value === void 0 ? true : value; + } + function getBooleanOption(options, key) { + let value; + if (hasOwnProperty.call(options, key)) { + value = options[key]; + if (typeof value !== "boolean") { + throw new TypeError(`The "${key}" argument must be of type boolean`); + } + } + return value === void 0 ? true : value; + } + function getPositiveIntegerOption(options, key) { + let value; + if (hasOwnProperty.call(options, key)) { + value = options[key]; + if (typeof value !== "number") { + throw new TypeError(`The "${key}" argument must be of type number`); + } + if (!Number.isInteger(value)) { + throw new TypeError(`The "${key}" argument must be an integer`); + } + if (value < 1) { + throw new RangeError(`The "${key}" argument must be >= 1`); + } + } + return value === void 0 ? Infinity : value; + } + function getItemCount(number4) { + if (number4 === 1) { + return "1 item"; + } + return `${number4} items`; + } + function getUniqueReplacerSet(replacerArray) { + const replacerSet = /* @__PURE__ */ new Set(); + for (const value of replacerArray) { + if (typeof value === "string" || typeof value === "number") { + replacerSet.add(String(value)); + } + } + return replacerSet; + } + function getStrictOption(options) { + if (hasOwnProperty.call(options, "strict")) { + const value = options.strict; + if (typeof value !== "boolean") { + throw new TypeError('The "strict" argument must be of type boolean'); + } + if (value) { + return (value2) => { + let message2 = `Object can not safely be stringified. Received type ${typeof value2}`; + if (typeof value2 !== "function") message2 += ` (${value2.toString()})`; + throw new Error(message2); + }; + } + } + } + function configure(options) { + options = { ...options }; + const fail = getStrictOption(options); + if (fail) { + if (options.bigint === void 0) { + options.bigint = false; + } + if (!("circularValue" in options)) { + options.circularValue = Error; + } + } + const circularValue = getCircularValueOption(options); + const bigint5 = getBooleanOption(options, "bigint"); + const deterministic = getDeterministicOption(options); + const comparator = typeof deterministic === "function" ? deterministic : void 0; + const maximumDepth = getPositiveIntegerOption(options, "maximumDepth"); + const maximumBreadth = getPositiveIntegerOption(options, "maximumBreadth"); + function stringifyFnReplacer(key, parent, stack, replacer, spacer, indentation) { + let value = parent[key]; + if (typeof value === "object" && value !== null && typeof value.toJSON === "function") { + value = value.toJSON(key); + } + value = replacer.call(parent, key, value); + switch (typeof value) { + case "string": + return strEscape(value); + case "object": { + if (value === null) { + return "null"; + } + if (stack.indexOf(value) !== -1) { + return circularValue; + } + let res = ""; + let join4 = ","; + const originalIndentation = indentation; + if (Array.isArray(value)) { + if (value.length === 0) { + return "[]"; + } + if (maximumDepth < stack.length + 1) { + return '"[Array]"'; + } + stack.push(value); + if (spacer !== "") { + indentation += spacer; + res += ` +${indentation}`; + join4 = `, +${indentation}`; + } + const maximumValuesToStringify = Math.min(value.length, maximumBreadth); + let i5 = 0; + for (; i5 < maximumValuesToStringify - 1; i5++) { + const tmp2 = stringifyFnReplacer(String(i5), value, stack, replacer, spacer, indentation); + res += tmp2 !== void 0 ? tmp2 : "null"; + res += join4; + } + const tmp = stringifyFnReplacer(String(i5), value, stack, replacer, spacer, indentation); + res += tmp !== void 0 ? tmp : "null"; + if (value.length - 1 > maximumBreadth) { + const removedKeys = value.length - maximumBreadth - 1; + res += `${join4}"... ${getItemCount(removedKeys)} not stringified"`; + } + if (spacer !== "") { + res += ` +${originalIndentation}`; + } + stack.pop(); + return `[${res}]`; + } + let keys = Object.keys(value); + const keyLength = keys.length; + if (keyLength === 0) { + return "{}"; + } + if (maximumDepth < stack.length + 1) { + return '"[Object]"'; + } + let whitespace = ""; + let separator = ""; + if (spacer !== "") { + indentation += spacer; + join4 = `, +${indentation}`; + whitespace = " "; + } + const maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth); + if (deterministic && !isTypedArrayWithEntries(value)) { + keys = sort(keys, comparator); + } + stack.push(value); + for (let i5 = 0; i5 < maximumPropertiesToStringify; i5++) { + const key2 = keys[i5]; + const tmp = stringifyFnReplacer(key2, value, stack, replacer, spacer, indentation); + if (tmp !== void 0) { + res += `${separator}${strEscape(key2)}:${whitespace}${tmp}`; + separator = join4; + } + } + if (keyLength > maximumBreadth) { + const removedKeys = keyLength - maximumBreadth; + res += `${separator}"...":${whitespace}"${getItemCount(removedKeys)} not stringified"`; + separator = join4; + } + if (spacer !== "" && separator.length > 1) { + res = ` +${indentation}${res} +${originalIndentation}`; + } + stack.pop(); + return `{${res}}`; + } + case "number": + return isFinite(value) ? String(value) : fail ? fail(value) : "null"; + case "boolean": + return value === true ? "true" : "false"; + case "undefined": + return void 0; + case "bigint": + if (bigint5) { + return String(value); + } + // fallthrough + default: + return fail ? fail(value) : void 0; + } + } + function stringifyArrayReplacer(key, value, stack, replacer, spacer, indentation) { + if (typeof value === "object" && value !== null && typeof value.toJSON === "function") { + value = value.toJSON(key); + } + switch (typeof value) { + case "string": + return strEscape(value); + case "object": { + if (value === null) { + return "null"; + } + if (stack.indexOf(value) !== -1) { + return circularValue; + } + const originalIndentation = indentation; + let res = ""; + let join4 = ","; + if (Array.isArray(value)) { + if (value.length === 0) { + return "[]"; + } + if (maximumDepth < stack.length + 1) { + return '"[Array]"'; + } + stack.push(value); + if (spacer !== "") { + indentation += spacer; + res += ` +${indentation}`; + join4 = `, +${indentation}`; + } + const maximumValuesToStringify = Math.min(value.length, maximumBreadth); + let i5 = 0; + for (; i5 < maximumValuesToStringify - 1; i5++) { + const tmp2 = stringifyArrayReplacer(String(i5), value[i5], stack, replacer, spacer, indentation); + res += tmp2 !== void 0 ? tmp2 : "null"; + res += join4; + } + const tmp = stringifyArrayReplacer(String(i5), value[i5], stack, replacer, spacer, indentation); + res += tmp !== void 0 ? tmp : "null"; + if (value.length - 1 > maximumBreadth) { + const removedKeys = value.length - maximumBreadth - 1; + res += `${join4}"... ${getItemCount(removedKeys)} not stringified"`; + } + if (spacer !== "") { + res += ` +${originalIndentation}`; + } + stack.pop(); + return `[${res}]`; + } + stack.push(value); + let whitespace = ""; + if (spacer !== "") { + indentation += spacer; + join4 = `, +${indentation}`; + whitespace = " "; + } + let separator = ""; + for (const key2 of replacer) { + const tmp = stringifyArrayReplacer(key2, value[key2], stack, replacer, spacer, indentation); + if (tmp !== void 0) { + res += `${separator}${strEscape(key2)}:${whitespace}${tmp}`; + separator = join4; + } + } + if (spacer !== "" && separator.length > 1) { + res = ` +${indentation}${res} +${originalIndentation}`; + } + stack.pop(); + return `{${res}}`; + } + case "number": + return isFinite(value) ? String(value) : fail ? fail(value) : "null"; + case "boolean": + return value === true ? "true" : "false"; + case "undefined": + return void 0; + case "bigint": + if (bigint5) { + return String(value); + } + // fallthrough + default: + return fail ? fail(value) : void 0; + } + } + function stringifyIndent(key, value, stack, spacer, indentation) { + switch (typeof value) { + case "string": + return strEscape(value); + case "object": { + if (value === null) { + return "null"; + } + if (typeof value.toJSON === "function") { + value = value.toJSON(key); + if (typeof value !== "object") { + return stringifyIndent(key, value, stack, spacer, indentation); + } + if (value === null) { + return "null"; + } + } + if (stack.indexOf(value) !== -1) { + return circularValue; + } + const originalIndentation = indentation; + if (Array.isArray(value)) { + if (value.length === 0) { + return "[]"; + } + if (maximumDepth < stack.length + 1) { + return '"[Array]"'; + } + stack.push(value); + indentation += spacer; + let res2 = ` +${indentation}`; + const join5 = `, +${indentation}`; + const maximumValuesToStringify = Math.min(value.length, maximumBreadth); + let i5 = 0; + for (; i5 < maximumValuesToStringify - 1; i5++) { + const tmp2 = stringifyIndent(String(i5), value[i5], stack, spacer, indentation); + res2 += tmp2 !== void 0 ? tmp2 : "null"; + res2 += join5; + } + const tmp = stringifyIndent(String(i5), value[i5], stack, spacer, indentation); + res2 += tmp !== void 0 ? tmp : "null"; + if (value.length - 1 > maximumBreadth) { + const removedKeys = value.length - maximumBreadth - 1; + res2 += `${join5}"... ${getItemCount(removedKeys)} not stringified"`; + } + res2 += ` +${originalIndentation}`; + stack.pop(); + return `[${res2}]`; + } + let keys = Object.keys(value); + const keyLength = keys.length; + if (keyLength === 0) { + return "{}"; + } + if (maximumDepth < stack.length + 1) { + return '"[Object]"'; + } + indentation += spacer; + const join4 = `, +${indentation}`; + let res = ""; + let separator = ""; + let maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth); + if (isTypedArrayWithEntries(value)) { + res += stringifyTypedArray(value, join4, maximumBreadth); + keys = keys.slice(value.length); + maximumPropertiesToStringify -= value.length; + separator = join4; + } + if (deterministic) { + keys = sort(keys, comparator); + } + stack.push(value); + for (let i5 = 0; i5 < maximumPropertiesToStringify; i5++) { + const key2 = keys[i5]; + const tmp = stringifyIndent(key2, value[key2], stack, spacer, indentation); + if (tmp !== void 0) { + res += `${separator}${strEscape(key2)}: ${tmp}`; + separator = join4; + } + } + if (keyLength > maximumBreadth) { + const removedKeys = keyLength - maximumBreadth; + res += `${separator}"...": "${getItemCount(removedKeys)} not stringified"`; + separator = join4; + } + if (separator !== "") { + res = ` +${indentation}${res} +${originalIndentation}`; + } + stack.pop(); + return `{${res}}`; + } + case "number": + return isFinite(value) ? String(value) : fail ? fail(value) : "null"; + case "boolean": + return value === true ? "true" : "false"; + case "undefined": + return void 0; + case "bigint": + if (bigint5) { + return String(value); + } + // fallthrough + default: + return fail ? fail(value) : void 0; + } + } + function stringifySimple(key, value, stack) { + switch (typeof value) { + case "string": + return strEscape(value); + case "object": { + if (value === null) { + return "null"; + } + if (typeof value.toJSON === "function") { + value = value.toJSON(key); + if (typeof value !== "object") { + return stringifySimple(key, value, stack); + } + if (value === null) { + return "null"; + } + } + if (stack.indexOf(value) !== -1) { + return circularValue; + } + let res = ""; + const hasLength = value.length !== void 0; + if (hasLength && Array.isArray(value)) { + if (value.length === 0) { + return "[]"; + } + if (maximumDepth < stack.length + 1) { + return '"[Array]"'; + } + stack.push(value); + const maximumValuesToStringify = Math.min(value.length, maximumBreadth); + let i5 = 0; + for (; i5 < maximumValuesToStringify - 1; i5++) { + const tmp2 = stringifySimple(String(i5), value[i5], stack); + res += tmp2 !== void 0 ? tmp2 : "null"; + res += ","; + } + const tmp = stringifySimple(String(i5), value[i5], stack); + res += tmp !== void 0 ? tmp : "null"; + if (value.length - 1 > maximumBreadth) { + const removedKeys = value.length - maximumBreadth - 1; + res += `,"... ${getItemCount(removedKeys)} not stringified"`; + } + stack.pop(); + return `[${res}]`; + } + let keys = Object.keys(value); + const keyLength = keys.length; + if (keyLength === 0) { + return "{}"; + } + if (maximumDepth < stack.length + 1) { + return '"[Object]"'; + } + let separator = ""; + let maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth); + if (hasLength && isTypedArrayWithEntries(value)) { + res += stringifyTypedArray(value, ",", maximumBreadth); + keys = keys.slice(value.length); + maximumPropertiesToStringify -= value.length; + separator = ","; + } + if (deterministic) { + keys = sort(keys, comparator); + } + stack.push(value); + for (let i5 = 0; i5 < maximumPropertiesToStringify; i5++) { + const key2 = keys[i5]; + const tmp = stringifySimple(key2, value[key2], stack); + if (tmp !== void 0) { + res += `${separator}${strEscape(key2)}:${tmp}`; + separator = ","; + } + } + if (keyLength > maximumBreadth) { + const removedKeys = keyLength - maximumBreadth; + res += `${separator}"...":"${getItemCount(removedKeys)} not stringified"`; + } + stack.pop(); + return `{${res}}`; + } + case "number": + return isFinite(value) ? String(value) : fail ? fail(value) : "null"; + case "boolean": + return value === true ? "true" : "false"; + case "undefined": + return void 0; + case "bigint": + if (bigint5) { + return String(value); + } + // fallthrough + default: + return fail ? fail(value) : void 0; + } + } + function stringify3(value, replacer, space) { + if (arguments.length > 1) { + let spacer = ""; + if (typeof space === "number") { + spacer = " ".repeat(Math.min(space, 10)); + } else if (typeof space === "string") { + spacer = space.slice(0, 10); + } + if (replacer != null) { + if (typeof replacer === "function") { + return stringifyFnReplacer("", { "": value }, [], replacer, spacer, ""); + } + if (Array.isArray(replacer)) { + return stringifyArrayReplacer("", value, [], getUniqueReplacerSet(replacer), spacer, ""); + } + } + if (spacer.length !== 0) { + return stringifyIndent("", value, [], spacer, ""); + } + } + return stringifySimple("", value, []); + } + return stringify3; + } + } +}); + +// node_modules/.pnpm/pino@9.14.0/node_modules/pino/lib/multistream.js +var require_multistream = __commonJS({ + "node_modules/.pnpm/pino@9.14.0/node_modules/pino/lib/multistream.js"(exports, module) { + "use strict"; + var metadata = /* @__PURE__ */ Symbol.for("pino.metadata"); + var { DEFAULT_LEVELS } = require_constants(); + var DEFAULT_INFO_LEVEL = DEFAULT_LEVELS.info; + function multistream(streamsArray, opts) { + streamsArray = streamsArray || []; + opts = opts || { dedupe: false }; + const streamLevels = Object.create(DEFAULT_LEVELS); + streamLevels.silent = Infinity; + if (opts.levels && typeof opts.levels === "object") { + Object.keys(opts.levels).forEach((i5) => { + streamLevels[i5] = opts.levels[i5]; + }); + } + const res = { + write, + add, + remove, + emit, + flushSync, + end, + minLevel: 0, + lastId: 0, + streams: [], + clone: clone3, + [metadata]: true, + streamLevels + }; + if (Array.isArray(streamsArray)) { + streamsArray.forEach(add, res); + } else { + add.call(res, streamsArray); + } + streamsArray = null; + return res; + function write(data2) { + let dest; + const level = this.lastLevel; + const { streams } = this; + let recordedLevel = 0; + let stream; + for (let i5 = initLoopVar(streams.length, opts.dedupe); checkLoopVar(i5, streams.length, opts.dedupe); i5 = adjustLoopVar(i5, opts.dedupe)) { + dest = streams[i5]; + if (dest.level <= level) { + if (recordedLevel !== 0 && recordedLevel !== dest.level) { + break; + } + stream = dest.stream; + if (stream[metadata]) { + const { lastTime, lastMsg, lastObj, lastLogger } = this; + stream.lastLevel = level; + stream.lastTime = lastTime; + stream.lastMsg = lastMsg; + stream.lastObj = lastObj; + stream.lastLogger = lastLogger; + } + stream.write(data2); + if (opts.dedupe) { + recordedLevel = dest.level; + } + } else if (!opts.dedupe) { + break; + } + } + } + function emit(...args) { + for (const { stream } of this.streams) { + if (typeof stream.emit === "function") { + stream.emit(...args); + } + } + } + function flushSync() { + for (const { stream } of this.streams) { + if (typeof stream.flushSync === "function") { + stream.flushSync(); + } + } + } + function add(dest) { + if (!dest) { + return res; + } + const isStream = typeof dest.write === "function" || dest.stream; + const stream_ = dest.write ? dest : dest.stream; + if (!isStream) { + throw Error("stream object needs to implement either StreamEntry or DestinationStream interface"); + } + const { streams, streamLevels: streamLevels2 } = this; + let level; + if (typeof dest.levelVal === "number") { + level = dest.levelVal; + } else if (typeof dest.level === "string") { + level = streamLevels2[dest.level]; + } else if (typeof dest.level === "number") { + level = dest.level; + } else { + level = DEFAULT_INFO_LEVEL; + } + const dest_ = { + stream: stream_, + level, + levelVal: void 0, + id: ++res.lastId + }; + streams.unshift(dest_); + streams.sort(compareByLevel); + this.minLevel = streams[0].level; + return res; + } + function remove(id) { + const { streams } = this; + const index2 = streams.findIndex((s5) => s5.id === id); + if (index2 >= 0) { + streams.splice(index2, 1); + streams.sort(compareByLevel); + this.minLevel = streams.length > 0 ? streams[0].level : -1; + } + return res; + } + function end() { + for (const { stream } of this.streams) { + if (typeof stream.flushSync === "function") { + stream.flushSync(); + } + stream.end(); + } + } + function clone3(level) { + const streams = new Array(this.streams.length); + for (let i5 = 0; i5 < streams.length; i5++) { + streams[i5] = { + level, + stream: this.streams[i5].stream + }; + } + return { + write, + add, + remove, + minLevel: level, + streams, + clone: clone3, + emit, + flushSync, + [metadata]: true + }; + } + } + function compareByLevel(a5, b6) { + return a5.level - b6.level; + } + function initLoopVar(length, dedupe) { + return dedupe ? length - 1 : 0; + } + function adjustLoopVar(i5, dedupe) { + return dedupe ? i5 - 1 : i5 + 1; + } + function checkLoopVar(i5, length, dedupe) { + return dedupe ? i5 >= 0 : i5 < length; + } + module.exports = multistream; + } +}); + +// node_modules/.pnpm/pino@9.14.0/node_modules/pino/pino.js +var require_pino = __commonJS({ + "node_modules/.pnpm/pino@9.14.0/node_modules/pino/pino.js"(exports, module) { + "use strict"; + var os24 = __require("node:os"); + var stdSerializers = require_pino_std_serializers(); + var caller = require_caller(); + var redaction = require_redaction(); + var time5 = require_time(); + var proto = require_proto(); + var symbols = require_symbols(); + var { configure } = require_safe_stable_stringify(); + var { assertDefaultLevelFound, mappings, genLsCache, genLevelComparison, assertLevelComparison } = require_levels(); + var { DEFAULT_LEVELS, SORTING_ORDER } = require_constants(); + var { + createArgsNormalizer, + asChindings, + buildSafeSonicBoom, + buildFormatters, + stringify: stringify2, + normalizeDestFileDescriptor, + noop: noop5 + } = require_tools(); + var { version: version3 } = require_meta(); + var { + chindingsSym, + redactFmtSym, + serializersSym, + timeSym, + timeSliceIndexSym, + streamSym, + stringifySym, + stringifySafeSym, + stringifiersSym, + setLevelSym, + endSym, + formatOptsSym, + messageKeySym, + errorKeySym, + nestedKeySym, + mixinSym, + levelCompSym, + useOnlyCustomLevelsSym, + formattersSym, + hooksSym, + nestedKeyStrSym, + mixinMergeStrategySym, + msgPrefixSym + } = symbols; + var { epochTime, nullTime } = time5; + var { pid } = process; + var hostname3 = os24.hostname(); + var defaultErrorSerializer = stdSerializers.err; + var defaultOptions2 = { + level: "info", + levelComparison: SORTING_ORDER.ASC, + levels: DEFAULT_LEVELS, + messageKey: "msg", + errorKey: "err", + nestedKey: null, + enabled: true, + base: { pid, hostname: hostname3 }, + serializers: Object.assign(/* @__PURE__ */ Object.create(null), { + err: defaultErrorSerializer + }), + formatters: Object.assign(/* @__PURE__ */ Object.create(null), { + bindings(bindings) { + return bindings; + }, + level(label, number4) { + return { level: number4 }; + } + }), + hooks: { + logMethod: void 0, + streamWrite: void 0 + }, + timestamp: epochTime, + name: void 0, + redact: null, + customLevels: null, + useOnlyCustomLevels: false, + depthLimit: 5, + edgeLimit: 100 + }; + var normalize2 = createArgsNormalizer(defaultOptions2); + var serializers2 = Object.assign(/* @__PURE__ */ Object.create(null), stdSerializers); + function pino2(...args) { + const instance = {}; + const { opts, stream } = normalize2(instance, caller(), ...args); + if (opts.level && typeof opts.level === "string" && DEFAULT_LEVELS[opts.level.toLowerCase()] !== void 0) opts.level = opts.level.toLowerCase(); + const { + redact, + crlf, + serializers: serializers3, + timestamp: timestamp2, + messageKey, + errorKey, + nestedKey, + base, + name, + level, + customLevels, + levelComparison, + mixin, + mixinMergeStrategy, + useOnlyCustomLevels, + formatters, + hooks, + depthLimit, + edgeLimit, + onChild, + msgPrefix + } = opts; + const stringifySafe = configure({ + maximumDepth: depthLimit, + maximumBreadth: edgeLimit + }); + const allFormatters = buildFormatters( + formatters.level, + formatters.bindings, + formatters.log + ); + const stringifyFn = stringify2.bind({ + [stringifySafeSym]: stringifySafe + }); + const stringifiers = redact ? redaction(redact, stringifyFn) : {}; + const formatOpts = redact ? { stringify: stringifiers[redactFmtSym] } : { stringify: stringifyFn }; + const end = "}" + (crlf ? "\r\n" : "\n"); + const coreChindings = asChindings.bind(null, { + [chindingsSym]: "", + [serializersSym]: serializers3, + [stringifiersSym]: stringifiers, + [stringifySym]: stringify2, + [stringifySafeSym]: stringifySafe, + [formattersSym]: allFormatters + }); + let chindings = ""; + if (base !== null) { + if (name === void 0) { + chindings = coreChindings(base); + } else { + chindings = coreChindings(Object.assign({}, base, { name })); + } + } + const time6 = timestamp2 instanceof Function ? timestamp2 : timestamp2 ? epochTime : nullTime; + const timeSliceIndex = time6().indexOf(":") + 1; + if (useOnlyCustomLevels && !customLevels) throw Error("customLevels is required if useOnlyCustomLevels is set true"); + if (mixin && typeof mixin !== "function") throw Error(`Unknown mixin type "${typeof mixin}" - expected "function"`); + if (msgPrefix && typeof msgPrefix !== "string") throw Error(`Unknown msgPrefix type "${typeof msgPrefix}" - expected "string"`); + assertDefaultLevelFound(level, customLevels, useOnlyCustomLevels); + const levels2 = mappings(customLevels, useOnlyCustomLevels); + if (typeof stream.emit === "function") { + stream.emit("message", { code: "PINO_CONFIG", config: { levels: levels2, messageKey, errorKey } }); + } + assertLevelComparison(levelComparison); + const levelCompFunc = genLevelComparison(levelComparison); + Object.assign(instance, { + levels: levels2, + [levelCompSym]: levelCompFunc, + [useOnlyCustomLevelsSym]: useOnlyCustomLevels, + [streamSym]: stream, + [timeSym]: time6, + [timeSliceIndexSym]: timeSliceIndex, + [stringifySym]: stringify2, + [stringifySafeSym]: stringifySafe, + [stringifiersSym]: stringifiers, + [endSym]: end, + [formatOptsSym]: formatOpts, + [messageKeySym]: messageKey, + [errorKeySym]: errorKey, + [nestedKeySym]: nestedKey, + // protect against injection + [nestedKeyStrSym]: nestedKey ? `,${JSON.stringify(nestedKey)}:{` : "", + [serializersSym]: serializers3, + [mixinSym]: mixin, + [mixinMergeStrategySym]: mixinMergeStrategy, + [chindingsSym]: chindings, + [formattersSym]: allFormatters, + [hooksSym]: hooks, + silent: noop5, + onChild, + [msgPrefixSym]: msgPrefix + }); + Object.setPrototypeOf(instance, proto()); + genLsCache(instance); + instance[setLevelSym](level); + return instance; + } + module.exports = pino2; + module.exports.destination = (dest = process.stdout.fd) => { + if (typeof dest === "object") { + dest.dest = normalizeDestFileDescriptor(dest.dest || process.stdout.fd); + return buildSafeSonicBoom(dest); + } else { + return buildSafeSonicBoom({ dest: normalizeDestFileDescriptor(dest), minLength: 0 }); + } + }; + module.exports.transport = require_transport(); + module.exports.multistream = require_multistream(); + module.exports.levels = mappings(); + module.exports.stdSerializers = serializers2; + module.exports.stdTimeFunctions = Object.assign({}, time5); + module.exports.symbols = symbols; + module.exports.version = version3; + module.exports.default = pino2; + module.exports.pino = pino2; + } +}); + +// node_modules/.pnpm/get-caller-file@2.0.5/node_modules/get-caller-file/index.js +var require_get_caller_file = __commonJS({ + "node_modules/.pnpm/get-caller-file@2.0.5/node_modules/get-caller-file/index.js"(exports, module) { + "use strict"; + module.exports = function getCallerFile(position) { + if (position === void 0) { + position = 2; + } + if (position >= Error.stackTraceLimit) { + throw new TypeError("getCallerFile(position) requires position be less then Error.stackTraceLimit but position was: `" + position + "` and Error.stackTraceLimit was: `" + Error.stackTraceLimit + "`"); + } + var oldPrepareStackTrace = Error.prepareStackTrace; + Error.prepareStackTrace = function(_, stack2) { + return stack2; + }; + var stack = new Error().stack; + Error.prepareStackTrace = oldPrepareStackTrace; + if (stack !== null && typeof stack === "object") { + return stack[position] ? stack[position].getFileName() : void 0; + } + }; + } +}); + +// node_modules/.pnpm/pino-http@10.5.0/node_modules/pino-http/logger.js +var require_logger = __commonJS({ + "node_modules/.pnpm/pino-http@10.5.0/node_modules/pino-http/logger.js"(exports, module) { + "use strict"; + var { pino: pino2, symbols: { stringifySym, chindingsSym } } = require_pino(); + var serializers2 = require_pino_std_serializers(); + var getCallerFile = require_get_caller_file(); + var startTime = /* @__PURE__ */ Symbol("startTime"); + var reqObject = /* @__PURE__ */ Symbol("reqObject"); + function pinoLogger(opts, stream) { + if (opts && opts._writableState) { + stream = opts; + opts = null; + } + opts = Object.assign({}, opts); + opts.customAttributeKeys = opts.customAttributeKeys || {}; + const reqKey = opts.customAttributeKeys.req || "req"; + const resKey = opts.customAttributeKeys.res || "res"; + const errKey = opts.customAttributeKeys.err || "err"; + const requestIdKey = opts.customAttributeKeys.reqId || "reqId"; + const responseTimeKey = opts.customAttributeKeys.responseTime || "responseTime"; + delete opts.customAttributeKeys; + const customProps = opts.customProps || void 0; + opts.wrapSerializers = "wrapSerializers" in opts ? opts.wrapSerializers : true; + if (opts.wrapSerializers) { + opts.serializers = Object.assign({}, opts.serializers); + const requestSerializer = opts.serializers[reqKey] || opts.serializers.req || serializers2.req; + const responseSerializer = opts.serializers[resKey] || opts.serializers.res || serializers2.res; + const errorSerializer = opts.serializers[errKey] || opts.serializers.err || serializers2.err; + opts.serializers[reqKey] = serializers2.wrapRequestSerializer(requestSerializer); + opts.serializers[resKey] = serializers2.wrapResponseSerializer(responseSerializer); + opts.serializers[errKey] = serializers2.wrapErrorSerializer(errorSerializer); + } + delete opts.wrapSerializers; + if (opts.useLevel && opts.customLogLevel) { + throw new Error("You can't pass 'useLevel' and 'customLogLevel' together"); + } + function getValidLogLevel(level, defaultValue = "info") { + if (level && typeof level === "string") { + const logLevel = level.trim(); + if (validLogLevels.includes(logLevel) === true) { + return logLevel; + } + } + return defaultValue; + } + function getLogLevelFromCustomLogLevel(customLogLevel2, useLevel2, res, err, req) { + return customLogLevel2 ? getValidLogLevel(customLogLevel2(req, res, err), useLevel2) : useLevel2; + } + const customLogLevel = opts.customLogLevel; + delete opts.customLogLevel; + const theStream = opts.stream || stream; + delete opts.stream; + const autoLogging = opts.autoLogging !== false; + const autoLoggingIgnore = opts.autoLogging && opts.autoLogging.ignore ? opts.autoLogging.ignore : null; + delete opts.autoLogging; + const onRequestReceivedObject = getFunctionOrDefault(opts.customReceivedObject, void 0); + const receivedMessage = getFunctionOrDefault(opts.customReceivedMessage, void 0); + const onRequestSuccessObject = getFunctionOrDefault(opts.customSuccessObject, defaultSuccessfulRequestObjectProvider); + const successMessage = getFunctionOrDefault(opts.customSuccessMessage, defaultSuccessfulRequestMessageProvider); + const onRequestErrorObject = getFunctionOrDefault(opts.customErrorObject, defaultFailedRequestObjectProvider); + const errorMessage = getFunctionOrDefault(opts.customErrorMessage, defaultFailedRequestMessageProvider); + delete opts.customSuccessfulMessage; + delete opts.customErroredMessage; + const quietReqLogger = !!opts.quietReqLogger; + const quietResLogger = !!opts.quietResLogger; + const logger4 = wrapChild(opts, theStream); + const validLogLevels = Object.keys(logger4.levels.values).concat("silent"); + const useLevel = getValidLogLevel(opts.useLevel); + delete opts.useLevel; + const genReqId = reqIdGenFactory(opts.genReqId); + const result = (req, res, next) => { + return loggingMiddleware(logger4, req, res, next); + }; + result.logger = logger4; + return result; + function onResFinished(res, logger5, err) { + let log2 = logger5; + const responseTime = Date.now() - res[startTime]; + const req = res[reqObject]; + const level = getLogLevelFromCustomLogLevel(customLogLevel, useLevel, res, err, req); + if (level === "silent") { + return; + } + const customPropBindings = typeof customProps === "function" ? customProps(req, res) : customProps; + if (customPropBindings) { + const customPropBindingStr = logger5[stringifySym](customPropBindings).replace(/[{}]/g, ""); + const customPropBindingsStr = logger5[chindingsSym]; + if (!customPropBindingsStr.includes(customPropBindingStr)) { + log2 = logger5.child(customPropBindings); + } + } + if (err || res.err || res.statusCode >= 500) { + const error50 = err || res.err || new Error("failed with status code " + res.statusCode); + log2[level]( + onRequestErrorObject(req, res, error50, { + [resKey]: res, + [errKey]: error50, + [responseTimeKey]: responseTime + }), + errorMessage(req, res, error50, responseTime) + ); + return; + } + log2[level]( + onRequestSuccessObject(req, res, { + [resKey]: res, + [responseTimeKey]: responseTime + }), + successMessage(req, res, responseTime) + ); + } + function loggingMiddleware(logger5, req, res, next) { + let shouldLogSuccess = true; + req.id = req.id || genReqId(req, res); + const log2 = quietReqLogger ? logger5.child({ [requestIdKey]: req.id }) : logger5; + let fullReqLogger = log2.child({ [reqKey]: req }); + const customPropBindings = typeof customProps === "function" ? customProps(req, res) : customProps; + if (customPropBindings) { + fullReqLogger = fullReqLogger.child(customPropBindings); + } + const responseLogger = quietResLogger ? log2 : fullReqLogger; + const requestLogger = quietReqLogger ? log2 : fullReqLogger; + if (!res.log) { + res.log = responseLogger; + } + if (Array.isArray(res.allLogs) === false) { + res.allLogs = []; + } + res.allLogs.push(responseLogger); + if (!req.log) { + req.log = requestLogger; + } + if (!req.allLogs) { + req.allLogs = []; + } + req.allLogs.push(requestLogger); + res[startTime] = res[startTime] || Date.now(); + res[reqObject] = req; + const onResponseComplete = (err) => { + res.removeListener("close", onResponseComplete); + res.removeListener("finish", onResponseComplete); + res.removeListener("error", onResponseComplete); + return onResFinished(res, responseLogger, err); + }; + if (autoLogging) { + if (autoLoggingIgnore !== null && shouldLogSuccess === true) { + const isIgnored = autoLoggingIgnore(req); + shouldLogSuccess = !isIgnored; + } + if (shouldLogSuccess) { + const shouldLogReceived = receivedMessage !== void 0 || onRequestReceivedObject !== void 0; + if (shouldLogReceived) { + const level = getLogLevelFromCustomLogLevel(customLogLevel, useLevel, res, void 0, req); + const receivedObjectResult = onRequestReceivedObject !== void 0 ? onRequestReceivedObject(req, res, void 0) : {}; + const receivedStringResult = receivedMessage !== void 0 ? receivedMessage(req, res) : void 0; + requestLogger[level](receivedObjectResult, receivedStringResult); + } + res.on("close", onResponseComplete); + res.on("finish", onResponseComplete); + } + res.on("error", onResponseComplete); + } + if (next) { + next(); + } + } + } + function wrapChild(opts, stream) { + const prevLogger = opts.logger; + const prevGenReqId = opts.genReqId; + let logger4 = null; + if (prevLogger) { + opts.logger = void 0; + opts.genReqId = void 0; + logger4 = prevLogger.child({}, opts); + opts.logger = prevLogger; + opts.genReqId = prevGenReqId; + } else { + if (opts.transport && !opts.transport.caller) { + opts.transport.caller = getCallerFile(); + } + logger4 = pino2(opts, stream); + } + return logger4; + } + function reqIdGenFactory(func) { + if (typeof func === "function") return func; + const maxInt = 2147483647; + let nextReqId = 0; + return function genReqId(req, res) { + return req.id || (nextReqId = nextReqId + 1 & maxInt); + }; + } + function getFunctionOrDefault(value, defaultValue) { + if (value && typeof value === "function") { + return value; + } + return defaultValue; + } + function defaultSuccessfulRequestObjectProvider(req, res, successObject) { + return successObject; + } + function defaultFailedRequestObjectProvider(req, res, error50, errorObject) { + return errorObject; + } + function defaultFailedRequestMessageProvider() { + return "request errored"; + } + function defaultSuccessfulRequestMessageProvider(req, res) { + return !req.readableAborted && res.writableEnded ? "request completed" : "request aborted"; + } + module.exports = pinoLogger; + module.exports.stdSerializers = { + err: serializers2.err, + req: serializers2.req, + res: serializers2.res + }; + module.exports.startTime = startTime; + module.exports.default = pinoLogger; + module.exports.pinoHttp = pinoLogger; + } +}); + +// node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/constants.js +var require_constants2 = __commonJS({ + "node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/constants.js"(exports, module) { + "use strict"; + var BINARY_TYPES = ["nodebuffer", "arraybuffer", "fragments"]; + var hasBlob = typeof Blob !== "undefined"; + if (hasBlob) BINARY_TYPES.push("blob"); + module.exports = { + BINARY_TYPES, + CLOSE_TIMEOUT: 3e4, + EMPTY_BUFFER: Buffer.alloc(0), + GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11", + hasBlob, + kForOnEventAttribute: /* @__PURE__ */ Symbol("kIsForOnEventAttribute"), + kListener: /* @__PURE__ */ Symbol("kListener"), + kStatusCode: /* @__PURE__ */ Symbol("status-code"), + kWebSocket: /* @__PURE__ */ Symbol("websocket"), + NOOP: () => { + } + }; + } +}); + +// node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/buffer-util.js +var require_buffer_util = __commonJS({ + "node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/buffer-util.js"(exports, module) { + "use strict"; + var { EMPTY_BUFFER: EMPTY_BUFFER2 } = require_constants2(); + var FastBuffer = Buffer[Symbol.species]; + function concat2(list2, totalLength) { + if (list2.length === 0) return EMPTY_BUFFER2; + if (list2.length === 1) return list2[0]; + const target = Buffer.allocUnsafe(totalLength); + let offset = 0; + for (let i5 = 0; i5 < list2.length; i5++) { + const buf = list2[i5]; + target.set(buf, offset); + offset += buf.length; + } + if (offset < totalLength) { + return new FastBuffer(target.buffer, target.byteOffset, offset); + } + return target; + } + function _mask(source, mask, output, offset, length) { + for (let i5 = 0; i5 < length; i5++) { + output[offset + i5] = source[i5] ^ mask[i5 & 3]; + } + } + function _unmask(buffer2, mask) { + for (let i5 = 0; i5 < buffer2.length; i5++) { + buffer2[i5] ^= mask[i5 & 3]; + } + } + function toArrayBuffer(buf) { + if (buf.length === buf.buffer.byteLength) { + return buf.buffer; + } + return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length); + } + function toBuffer(data2) { + toBuffer.readOnly = true; + if (Buffer.isBuffer(data2)) return data2; + let buf; + if (data2 instanceof ArrayBuffer) { + buf = new FastBuffer(data2); + } else if (ArrayBuffer.isView(data2)) { + buf = new FastBuffer(data2.buffer, data2.byteOffset, data2.byteLength); + } else { + buf = Buffer.from(data2); + toBuffer.readOnly = false; + } + return buf; + } + module.exports = { + concat: concat2, + mask: _mask, + toArrayBuffer, + toBuffer, + unmask: _unmask + }; + if (!process.env.WS_NO_BUFFER_UTIL) { + try { + const bufferUtil = __require("bufferutil"); + module.exports.mask = function(source, mask, output, offset, length) { + if (length < 48) _mask(source, mask, output, offset, length); + else bufferUtil.mask(source, mask, output, offset, length); + }; + module.exports.unmask = function(buffer2, mask) { + if (buffer2.length < 32) _unmask(buffer2, mask); + else bufferUtil.unmask(buffer2, mask); + }; + } catch (e5) { + } + } + } +}); + +// node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/limiter.js +var require_limiter = __commonJS({ + "node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/limiter.js"(exports, module) { + "use strict"; + var kDone = /* @__PURE__ */ Symbol("kDone"); + var kRun = /* @__PURE__ */ Symbol("kRun"); + var Limiter = class { + /** + * Creates a new `Limiter`. + * + * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed + * to run concurrently + */ + constructor(concurrency) { + this[kDone] = () => { + this.pending--; + this[kRun](); + }; + this.concurrency = concurrency || Infinity; + this.jobs = []; + this.pending = 0; + } + /** + * Adds a job to the queue. + * + * @param {Function} job The job to run + * @public + */ + add(job) { + this.jobs.push(job); + this[kRun](); + } + /** + * Removes a job from the queue and runs it if possible. + * + * @private + */ + [kRun]() { + if (this.pending === this.concurrency) return; + if (this.jobs.length) { + const job = this.jobs.shift(); + this.pending++; + job(this[kDone]); + } + } + }; + module.exports = Limiter; + } +}); + +// node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/permessage-deflate.js +var require_permessage_deflate = __commonJS({ + "node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/permessage-deflate.js"(exports, module) { + "use strict"; + var zlib = __require("zlib"); + var bufferUtil = require_buffer_util(); + var Limiter = require_limiter(); + var { kStatusCode } = require_constants2(); + var FastBuffer = Buffer[Symbol.species]; + var TRAILER = Buffer.from([0, 0, 255, 255]); + var kPerMessageDeflate = /* @__PURE__ */ Symbol("permessage-deflate"); + var kTotalLength = /* @__PURE__ */ Symbol("total-length"); + var kCallback = /* @__PURE__ */ Symbol("callback"); + var kBuffers = /* @__PURE__ */ Symbol("buffers"); + var kError = /* @__PURE__ */ Symbol("error"); + var zlibLimiter; + var PerMessageDeflate2 = class { + /** + * Creates a PerMessageDeflate instance. + * + * @param {Object} [options] Configuration options + * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support + * for, or request, a custom client window size + * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/ + * acknowledge disabling of client context takeover + * @param {Number} [options.concurrencyLimit=10] The number of concurrent + * calls to zlib + * @param {Boolean} [options.isServer=false] Create the instance in either + * server or client mode + * @param {Number} [options.maxPayload=0] The maximum allowed message length + * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the + * use of a custom server window size + * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept + * disabling of server context takeover + * @param {Number} [options.threshold=1024] Size (in bytes) below which + * messages should not be compressed if context takeover is disabled + * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on + * deflate + * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on + * inflate + */ + constructor(options) { + this._options = options || {}; + this._threshold = this._options.threshold !== void 0 ? this._options.threshold : 1024; + this._maxPayload = this._options.maxPayload | 0; + this._isServer = !!this._options.isServer; + this._deflate = null; + this._inflate = null; + this.params = null; + if (!zlibLimiter) { + const concurrency = this._options.concurrencyLimit !== void 0 ? this._options.concurrencyLimit : 10; + zlibLimiter = new Limiter(concurrency); + } + } + /** + * @type {String} + */ + static get extensionName() { + return "permessage-deflate"; + } + /** + * Create an extension negotiation offer. + * + * @return {Object} Extension parameters + * @public + */ + offer() { + const params = {}; + if (this._options.serverNoContextTakeover) { + params.server_no_context_takeover = true; + } + if (this._options.clientNoContextTakeover) { + params.client_no_context_takeover = true; + } + if (this._options.serverMaxWindowBits) { + params.server_max_window_bits = this._options.serverMaxWindowBits; + } + if (this._options.clientMaxWindowBits) { + params.client_max_window_bits = this._options.clientMaxWindowBits; + } else if (this._options.clientMaxWindowBits == null) { + params.client_max_window_bits = true; + } + return params; + } + /** + * Accept an extension negotiation offer/response. + * + * @param {Array} configurations The extension negotiation offers/reponse + * @return {Object} Accepted configuration + * @public + */ + accept(configurations) { + configurations = this.normalizeParams(configurations); + this.params = this._isServer ? this.acceptAsServer(configurations) : this.acceptAsClient(configurations); + return this.params; + } + /** + * Releases all resources used by the extension. + * + * @public + */ + cleanup() { + if (this._inflate) { + this._inflate.close(); + this._inflate = null; + } + if (this._deflate) { + const callback = this._deflate[kCallback]; + this._deflate.close(); + this._deflate = null; + if (callback) { + callback( + new Error( + "The deflate stream was closed while data was being processed" + ) + ); + } + } + } + /** + * Accept an extension negotiation offer. + * + * @param {Array} offers The extension negotiation offers + * @return {Object} Accepted configuration + * @private + */ + acceptAsServer(offers) { + const opts = this._options; + const accepted = offers.find((params) => { + if (opts.serverNoContextTakeover === false && params.server_no_context_takeover || params.server_max_window_bits && (opts.serverMaxWindowBits === false || typeof opts.serverMaxWindowBits === "number" && opts.serverMaxWindowBits > params.server_max_window_bits) || typeof opts.clientMaxWindowBits === "number" && !params.client_max_window_bits) { + return false; + } + return true; + }); + if (!accepted) { + throw new Error("None of the extension offers can be accepted"); + } + if (opts.serverNoContextTakeover) { + accepted.server_no_context_takeover = true; + } + if (opts.clientNoContextTakeover) { + accepted.client_no_context_takeover = true; + } + if (typeof opts.serverMaxWindowBits === "number") { + accepted.server_max_window_bits = opts.serverMaxWindowBits; + } + if (typeof opts.clientMaxWindowBits === "number") { + accepted.client_max_window_bits = opts.clientMaxWindowBits; + } else if (accepted.client_max_window_bits === true || opts.clientMaxWindowBits === false) { + delete accepted.client_max_window_bits; + } + return accepted; + } + /** + * Accept the extension negotiation response. + * + * @param {Array} response The extension negotiation response + * @return {Object} Accepted configuration + * @private + */ + acceptAsClient(response) { + const params = response[0]; + if (this._options.clientNoContextTakeover === false && params.client_no_context_takeover) { + throw new Error('Unexpected parameter "client_no_context_takeover"'); + } + if (!params.client_max_window_bits) { + if (typeof this._options.clientMaxWindowBits === "number") { + params.client_max_window_bits = this._options.clientMaxWindowBits; + } + } else if (this._options.clientMaxWindowBits === false || typeof this._options.clientMaxWindowBits === "number" && params.client_max_window_bits > this._options.clientMaxWindowBits) { + throw new Error( + 'Unexpected or invalid parameter "client_max_window_bits"' + ); + } + return params; + } + /** + * Normalize parameters. + * + * @param {Array} configurations The extension negotiation offers/reponse + * @return {Array} The offers/response with normalized parameters + * @private + */ + normalizeParams(configurations) { + configurations.forEach((params) => { + Object.keys(params).forEach((key) => { + let value = params[key]; + if (value.length > 1) { + throw new Error(`Parameter "${key}" must have only a single value`); + } + value = value[0]; + if (key === "client_max_window_bits") { + if (value !== true) { + const num = +value; + if (!Number.isInteger(num) || num < 8 || num > 15) { + throw new TypeError( + `Invalid value for parameter "${key}": ${value}` + ); + } + value = num; + } else if (!this._isServer) { + throw new TypeError( + `Invalid value for parameter "${key}": ${value}` + ); + } + } else if (key === "server_max_window_bits") { + const num = +value; + if (!Number.isInteger(num) || num < 8 || num > 15) { + throw new TypeError( + `Invalid value for parameter "${key}": ${value}` + ); + } + value = num; + } else if (key === "client_no_context_takeover" || key === "server_no_context_takeover") { + if (value !== true) { + throw new TypeError( + `Invalid value for parameter "${key}": ${value}` + ); + } + } else { + throw new Error(`Unknown parameter "${key}"`); + } + params[key] = value; + }); + }); + return configurations; + } + /** + * Decompress data. Concurrency limited. + * + * @param {Buffer} data Compressed data + * @param {Boolean} fin Specifies whether or not this is the last fragment + * @param {Function} callback Callback + * @public + */ + decompress(data2, fin, callback) { + zlibLimiter.add((done) => { + this._decompress(data2, fin, (err, result) => { + done(); + callback(err, result); + }); + }); + } + /** + * Compress data. Concurrency limited. + * + * @param {(Buffer|String)} data Data to compress + * @param {Boolean} fin Specifies whether or not this is the last fragment + * @param {Function} callback Callback + * @public + */ + compress(data2, fin, callback) { + zlibLimiter.add((done) => { + this._compress(data2, fin, (err, result) => { + done(); + callback(err, result); + }); + }); + } + /** + * Decompress data. + * + * @param {Buffer} data Compressed data + * @param {Boolean} fin Specifies whether or not this is the last fragment + * @param {Function} callback Callback + * @private + */ + _decompress(data2, fin, callback) { + const endpoint = this._isServer ? "client" : "server"; + if (!this._inflate) { + const key = `${endpoint}_max_window_bits`; + const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key]; + this._inflate = zlib.createInflateRaw({ + ...this._options.zlibInflateOptions, + windowBits + }); + this._inflate[kPerMessageDeflate] = this; + this._inflate[kTotalLength] = 0; + this._inflate[kBuffers] = []; + this._inflate.on("error", inflateOnError); + this._inflate.on("data", inflateOnData); + } + this._inflate[kCallback] = callback; + this._inflate.write(data2); + if (fin) this._inflate.write(TRAILER); + this._inflate.flush(() => { + const err = this._inflate[kError]; + if (err) { + this._inflate.close(); + this._inflate = null; + callback(err); + return; + } + const data3 = bufferUtil.concat( + this._inflate[kBuffers], + this._inflate[kTotalLength] + ); + if (this._inflate._readableState.endEmitted) { + this._inflate.close(); + this._inflate = null; + } else { + this._inflate[kTotalLength] = 0; + this._inflate[kBuffers] = []; + if (fin && this.params[`${endpoint}_no_context_takeover`]) { + this._inflate.reset(); + } + } + callback(null, data3); + }); + } + /** + * Compress data. + * + * @param {(Buffer|String)} data Data to compress + * @param {Boolean} fin Specifies whether or not this is the last fragment + * @param {Function} callback Callback + * @private + */ + _compress(data2, fin, callback) { + const endpoint = this._isServer ? "server" : "client"; + if (!this._deflate) { + const key = `${endpoint}_max_window_bits`; + const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key]; + this._deflate = zlib.createDeflateRaw({ + ...this._options.zlibDeflateOptions, + windowBits + }); + this._deflate[kTotalLength] = 0; + this._deflate[kBuffers] = []; + this._deflate.on("data", deflateOnData); + } + this._deflate[kCallback] = callback; + this._deflate.write(data2); + this._deflate.flush(zlib.Z_SYNC_FLUSH, () => { + if (!this._deflate) { + return; + } + let data3 = bufferUtil.concat( + this._deflate[kBuffers], + this._deflate[kTotalLength] + ); + if (fin) { + data3 = new FastBuffer(data3.buffer, data3.byteOffset, data3.length - 4); + } + this._deflate[kCallback] = null; + this._deflate[kTotalLength] = 0; + this._deflate[kBuffers] = []; + if (fin && this.params[`${endpoint}_no_context_takeover`]) { + this._deflate.reset(); + } + callback(null, data3); + }); + } + }; + module.exports = PerMessageDeflate2; + function deflateOnData(chunk) { + this[kBuffers].push(chunk); + this[kTotalLength] += chunk.length; + } + function inflateOnData(chunk) { + this[kTotalLength] += chunk.length; + if (this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload) { + this[kBuffers].push(chunk); + return; + } + this[kError] = new RangeError("Max payload size exceeded"); + this[kError].code = "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"; + this[kError][kStatusCode] = 1009; + this.removeListener("data", inflateOnData); + this.reset(); + } + function inflateOnError(err) { + this[kPerMessageDeflate]._inflate = null; + if (this[kError]) { + this[kCallback](this[kError]); + return; + } + err[kStatusCode] = 1007; + this[kCallback](err); + } + } +}); + +// node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/validation.js +var require_validation = __commonJS({ + "node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/validation.js"(exports, module) { + "use strict"; + var { isUtf8 } = __require("buffer"); + var { hasBlob } = require_constants2(); + var tokenChars = [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + // 0 - 15 + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + // 16 - 31 + 0, + 1, + 0, + 1, + 1, + 1, + 1, + 1, + 0, + 0, + 1, + 1, + 0, + 1, + 1, + 0, + // 32 - 47 + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + // 48 - 63 + 0, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + // 64 - 79 + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 0, + 0, + 0, + 1, + 1, + // 80 - 95 + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + // 96 - 111 + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 0, + 1, + 0, + 1, + 0 + // 112 - 127 + ]; + function isValidStatusCode(code) { + return code >= 1e3 && code <= 1014 && code !== 1004 && code !== 1005 && code !== 1006 || code >= 3e3 && code <= 4999; + } + function _isValidUTF8(buf) { + const len = buf.length; + let i5 = 0; + while (i5 < len) { + if ((buf[i5] & 128) === 0) { + i5++; + } else if ((buf[i5] & 224) === 192) { + if (i5 + 1 === len || (buf[i5 + 1] & 192) !== 128 || (buf[i5] & 254) === 192) { + return false; + } + i5 += 2; + } else if ((buf[i5] & 240) === 224) { + if (i5 + 2 >= len || (buf[i5 + 1] & 192) !== 128 || (buf[i5 + 2] & 192) !== 128 || buf[i5] === 224 && (buf[i5 + 1] & 224) === 128 || // Overlong + buf[i5] === 237 && (buf[i5 + 1] & 224) === 160) { + return false; + } + i5 += 3; + } else if ((buf[i5] & 248) === 240) { + if (i5 + 3 >= len || (buf[i5 + 1] & 192) !== 128 || (buf[i5 + 2] & 192) !== 128 || (buf[i5 + 3] & 192) !== 128 || buf[i5] === 240 && (buf[i5 + 1] & 240) === 128 || // Overlong + buf[i5] === 244 && buf[i5 + 1] > 143 || buf[i5] > 244) { + return false; + } + i5 += 4; + } else { + return false; + } + } + return true; + } + function isBlob(value) { + return hasBlob && typeof value === "object" && typeof value.arrayBuffer === "function" && typeof value.type === "string" && typeof value.stream === "function" && (value[Symbol.toStringTag] === "Blob" || value[Symbol.toStringTag] === "File"); + } + module.exports = { + isBlob, + isValidStatusCode, + isValidUTF8: _isValidUTF8, + tokenChars + }; + if (isUtf8) { + module.exports.isValidUTF8 = function(buf) { + return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf); + }; + } else if (!process.env.WS_NO_UTF_8_VALIDATE) { + try { + const isValidUTF8 = __require("utf-8-validate"); + module.exports.isValidUTF8 = function(buf) { + return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf); + }; + } catch (e5) { + } + } + } +}); + +// node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/receiver.js +var require_receiver = __commonJS({ + "node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/receiver.js"(exports, module) { + "use strict"; + var { Writable } = __require("stream"); + var PerMessageDeflate2 = require_permessage_deflate(); + var { + BINARY_TYPES, + EMPTY_BUFFER: EMPTY_BUFFER2, + kStatusCode, + kWebSocket + } = require_constants2(); + var { concat: concat2, toArrayBuffer, unmask } = require_buffer_util(); + var { isValidStatusCode, isValidUTF8 } = require_validation(); + var FastBuffer = Buffer[Symbol.species]; + var GET_INFO = 0; + var GET_PAYLOAD_LENGTH_16 = 1; + var GET_PAYLOAD_LENGTH_64 = 2; + var GET_MASK = 3; + var GET_DATA = 4; + var INFLATING = 5; + var DEFER_EVENT = 6; + var Receiver2 = class extends Writable { + /** + * Creates a Receiver instance. + * + * @param {Object} [options] Options object + * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether + * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted + * multiple times in the same tick + * @param {String} [options.binaryType=nodebuffer] The type for binary data + * @param {Object} [options.extensions] An object containing the negotiated + * extensions + * @param {Boolean} [options.isServer=false] Specifies whether to operate in + * client or server mode + * @param {Number} [options.maxPayload=0] The maximum allowed message length + * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or + * not to skip UTF-8 validation for text and close messages + */ + constructor(options = {}) { + super(); + this._allowSynchronousEvents = options.allowSynchronousEvents !== void 0 ? options.allowSynchronousEvents : true; + this._binaryType = options.binaryType || BINARY_TYPES[0]; + this._extensions = options.extensions || {}; + this._isServer = !!options.isServer; + this._maxPayload = options.maxPayload | 0; + this._skipUTF8Validation = !!options.skipUTF8Validation; + this[kWebSocket] = void 0; + this._bufferedBytes = 0; + this._buffers = []; + this._compressed = false; + this._payloadLength = 0; + this._mask = void 0; + this._fragmented = 0; + this._masked = false; + this._fin = false; + this._opcode = 0; + this._totalPayloadLength = 0; + this._messageLength = 0; + this._fragments = []; + this._errored = false; + this._loop = false; + this._state = GET_INFO; + } + /** + * Implements `Writable.prototype._write()`. + * + * @param {Buffer} chunk The chunk of data to write + * @param {String} encoding The character encoding of `chunk` + * @param {Function} cb Callback + * @private + */ + _write(chunk, encoding, cb) { + if (this._opcode === 8 && this._state == GET_INFO) return cb(); + this._bufferedBytes += chunk.length; + this._buffers.push(chunk); + this.startLoop(cb); + } + /** + * Consumes `n` bytes from the buffered data. + * + * @param {Number} n The number of bytes to consume + * @return {Buffer} The consumed bytes + * @private + */ + consume(n5) { + this._bufferedBytes -= n5; + if (n5 === this._buffers[0].length) return this._buffers.shift(); + if (n5 < this._buffers[0].length) { + const buf = this._buffers[0]; + this._buffers[0] = new FastBuffer( + buf.buffer, + buf.byteOffset + n5, + buf.length - n5 + ); + return new FastBuffer(buf.buffer, buf.byteOffset, n5); + } + const dst = Buffer.allocUnsafe(n5); + do { + const buf = this._buffers[0]; + const offset = dst.length - n5; + if (n5 >= buf.length) { + dst.set(this._buffers.shift(), offset); + } else { + dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n5), offset); + this._buffers[0] = new FastBuffer( + buf.buffer, + buf.byteOffset + n5, + buf.length - n5 + ); + } + n5 -= buf.length; + } while (n5 > 0); + return dst; + } + /** + * Starts the parsing loop. + * + * @param {Function} cb Callback + * @private + */ + startLoop(cb) { + this._loop = true; + do { + switch (this._state) { + case GET_INFO: + this.getInfo(cb); + break; + case GET_PAYLOAD_LENGTH_16: + this.getPayloadLength16(cb); + break; + case GET_PAYLOAD_LENGTH_64: + this.getPayloadLength64(cb); + break; + case GET_MASK: + this.getMask(); + break; + case GET_DATA: + this.getData(cb); + break; + case INFLATING: + case DEFER_EVENT: + this._loop = false; + return; + } + } while (this._loop); + if (!this._errored) cb(); + } + /** + * Reads the first two bytes of a frame. + * + * @param {Function} cb Callback + * @private + */ + getInfo(cb) { + if (this._bufferedBytes < 2) { + this._loop = false; + return; + } + const buf = this.consume(2); + if ((buf[0] & 48) !== 0) { + const error50 = this.createError( + RangeError, + "RSV2 and RSV3 must be clear", + true, + 1002, + "WS_ERR_UNEXPECTED_RSV_2_3" + ); + cb(error50); + return; + } + const compressed = (buf[0] & 64) === 64; + if (compressed && !this._extensions[PerMessageDeflate2.extensionName]) { + const error50 = this.createError( + RangeError, + "RSV1 must be clear", + true, + 1002, + "WS_ERR_UNEXPECTED_RSV_1" + ); + cb(error50); + return; + } + this._fin = (buf[0] & 128) === 128; + this._opcode = buf[0] & 15; + this._payloadLength = buf[1] & 127; + if (this._opcode === 0) { + if (compressed) { + const error50 = this.createError( + RangeError, + "RSV1 must be clear", + true, + 1002, + "WS_ERR_UNEXPECTED_RSV_1" + ); + cb(error50); + return; + } + if (!this._fragmented) { + const error50 = this.createError( + RangeError, + "invalid opcode 0", + true, + 1002, + "WS_ERR_INVALID_OPCODE" + ); + cb(error50); + return; + } + this._opcode = this._fragmented; + } else if (this._opcode === 1 || this._opcode === 2) { + if (this._fragmented) { + const error50 = this.createError( + RangeError, + `invalid opcode ${this._opcode}`, + true, + 1002, + "WS_ERR_INVALID_OPCODE" + ); + cb(error50); + return; + } + this._compressed = compressed; + } else if (this._opcode > 7 && this._opcode < 11) { + if (!this._fin) { + const error50 = this.createError( + RangeError, + "FIN must be set", + true, + 1002, + "WS_ERR_EXPECTED_FIN" + ); + cb(error50); + return; + } + if (compressed) { + const error50 = this.createError( + RangeError, + "RSV1 must be clear", + true, + 1002, + "WS_ERR_UNEXPECTED_RSV_1" + ); + cb(error50); + return; + } + if (this._payloadLength > 125 || this._opcode === 8 && this._payloadLength === 1) { + const error50 = this.createError( + RangeError, + `invalid payload length ${this._payloadLength}`, + true, + 1002, + "WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH" + ); + cb(error50); + return; + } + } else { + const error50 = this.createError( + RangeError, + `invalid opcode ${this._opcode}`, + true, + 1002, + "WS_ERR_INVALID_OPCODE" + ); + cb(error50); + return; + } + if (!this._fin && !this._fragmented) this._fragmented = this._opcode; + this._masked = (buf[1] & 128) === 128; + if (this._isServer) { + if (!this._masked) { + const error50 = this.createError( + RangeError, + "MASK must be set", + true, + 1002, + "WS_ERR_EXPECTED_MASK" + ); + cb(error50); + return; + } + } else if (this._masked) { + const error50 = this.createError( + RangeError, + "MASK must be clear", + true, + 1002, + "WS_ERR_UNEXPECTED_MASK" + ); + cb(error50); + return; + } + if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16; + else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64; + else this.haveLength(cb); + } + /** + * Gets extended payload length (7+16). + * + * @param {Function} cb Callback + * @private + */ + getPayloadLength16(cb) { + if (this._bufferedBytes < 2) { + this._loop = false; + return; + } + this._payloadLength = this.consume(2).readUInt16BE(0); + this.haveLength(cb); + } + /** + * Gets extended payload length (7+64). + * + * @param {Function} cb Callback + * @private + */ + getPayloadLength64(cb) { + if (this._bufferedBytes < 8) { + this._loop = false; + return; + } + const buf = this.consume(8); + const num = buf.readUInt32BE(0); + if (num > Math.pow(2, 53 - 32) - 1) { + const error50 = this.createError( + RangeError, + "Unsupported WebSocket frame: payload length > 2^53 - 1", + false, + 1009, + "WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH" + ); + cb(error50); + return; + } + this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4); + this.haveLength(cb); + } + /** + * Payload length has been read. + * + * @param {Function} cb Callback + * @private + */ + haveLength(cb) { + if (this._payloadLength && this._opcode < 8) { + this._totalPayloadLength += this._payloadLength; + if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) { + const error50 = this.createError( + RangeError, + "Max payload size exceeded", + false, + 1009, + "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH" + ); + cb(error50); + return; + } + } + if (this._masked) this._state = GET_MASK; + else this._state = GET_DATA; + } + /** + * Reads mask bytes. + * + * @private + */ + getMask() { + if (this._bufferedBytes < 4) { + this._loop = false; + return; + } + this._mask = this.consume(4); + this._state = GET_DATA; + } + /** + * Reads data bytes. + * + * @param {Function} cb Callback + * @private + */ + getData(cb) { + let data2 = EMPTY_BUFFER2; + if (this._payloadLength) { + if (this._bufferedBytes < this._payloadLength) { + this._loop = false; + return; + } + data2 = this.consume(this._payloadLength); + if (this._masked && (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0) { + unmask(data2, this._mask); + } + } + if (this._opcode > 7) { + this.controlMessage(data2, cb); + return; + } + if (this._compressed) { + this._state = INFLATING; + this.decompress(data2, cb); + return; + } + if (data2.length) { + this._messageLength = this._totalPayloadLength; + this._fragments.push(data2); + } + this.dataMessage(cb); + } + /** + * Decompresses data. + * + * @param {Buffer} data Compressed data + * @param {Function} cb Callback + * @private + */ + decompress(data2, cb) { + const perMessageDeflate = this._extensions[PerMessageDeflate2.extensionName]; + perMessageDeflate.decompress(data2, this._fin, (err, buf) => { + if (err) return cb(err); + if (buf.length) { + this._messageLength += buf.length; + if (this._messageLength > this._maxPayload && this._maxPayload > 0) { + const error50 = this.createError( + RangeError, + "Max payload size exceeded", + false, + 1009, + "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH" + ); + cb(error50); + return; + } + this._fragments.push(buf); + } + this.dataMessage(cb); + if (this._state === GET_INFO) this.startLoop(cb); + }); + } + /** + * Handles a data message. + * + * @param {Function} cb Callback + * @private + */ + dataMessage(cb) { + if (!this._fin) { + this._state = GET_INFO; + return; + } + const messageLength = this._messageLength; + const fragments = this._fragments; + this._totalPayloadLength = 0; + this._messageLength = 0; + this._fragmented = 0; + this._fragments = []; + if (this._opcode === 2) { + let data2; + if (this._binaryType === "nodebuffer") { + data2 = concat2(fragments, messageLength); + } else if (this._binaryType === "arraybuffer") { + data2 = toArrayBuffer(concat2(fragments, messageLength)); + } else if (this._binaryType === "blob") { + data2 = new Blob(fragments); + } else { + data2 = fragments; + } + if (this._allowSynchronousEvents) { + this.emit("message", data2, true); + this._state = GET_INFO; + } else { + this._state = DEFER_EVENT; + setImmediate(() => { + this.emit("message", data2, true); + this._state = GET_INFO; + this.startLoop(cb); + }); + } + } else { + const buf = concat2(fragments, messageLength); + if (!this._skipUTF8Validation && !isValidUTF8(buf)) { + const error50 = this.createError( + Error, + "invalid UTF-8 sequence", + true, + 1007, + "WS_ERR_INVALID_UTF8" + ); + cb(error50); + return; + } + if (this._state === INFLATING || this._allowSynchronousEvents) { + this.emit("message", buf, false); + this._state = GET_INFO; + } else { + this._state = DEFER_EVENT; + setImmediate(() => { + this.emit("message", buf, false); + this._state = GET_INFO; + this.startLoop(cb); + }); + } + } + } + /** + * Handles a control message. + * + * @param {Buffer} data Data to handle + * @return {(Error|RangeError|undefined)} A possible error + * @private + */ + controlMessage(data2, cb) { + if (this._opcode === 8) { + if (data2.length === 0) { + this._loop = false; + this.emit("conclude", 1005, EMPTY_BUFFER2); + this.end(); + } else { + const code = data2.readUInt16BE(0); + if (!isValidStatusCode(code)) { + const error50 = this.createError( + RangeError, + `invalid status code ${code}`, + true, + 1002, + "WS_ERR_INVALID_CLOSE_CODE" + ); + cb(error50); + return; + } + const buf = new FastBuffer( + data2.buffer, + data2.byteOffset + 2, + data2.length - 2 + ); + if (!this._skipUTF8Validation && !isValidUTF8(buf)) { + const error50 = this.createError( + Error, + "invalid UTF-8 sequence", + true, + 1007, + "WS_ERR_INVALID_UTF8" + ); + cb(error50); + return; + } + this._loop = false; + this.emit("conclude", code, buf); + this.end(); + } + this._state = GET_INFO; + return; + } + if (this._allowSynchronousEvents) { + this.emit(this._opcode === 9 ? "ping" : "pong", data2); + this._state = GET_INFO; + } else { + this._state = DEFER_EVENT; + setImmediate(() => { + this.emit(this._opcode === 9 ? "ping" : "pong", data2); + this._state = GET_INFO; + this.startLoop(cb); + }); + } + } + /** + * Builds an error object. + * + * @param {function(new:Error|RangeError)} ErrorCtor The error constructor + * @param {String} message The error message + * @param {Boolean} prefix Specifies whether or not to add a default prefix to + * `message` + * @param {Number} statusCode The status code + * @param {String} errorCode The exposed error code + * @return {(Error|RangeError)} The error + * @private + */ + createError(ErrorCtor, message2, prefix, statusCode, errorCode) { + this._loop = false; + this._errored = true; + const err = new ErrorCtor( + prefix ? `Invalid WebSocket frame: ${message2}` : message2 + ); + Error.captureStackTrace(err, this.createError); + err.code = errorCode; + err[kStatusCode] = statusCode; + return err; + } + }; + module.exports = Receiver2; + } +}); + +// node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/sender.js +var require_sender = __commonJS({ + "node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/sender.js"(exports, module) { + "use strict"; + var { Duplex } = __require("stream"); + var { randomFillSync } = __require("crypto"); + var PerMessageDeflate2 = require_permessage_deflate(); + var { EMPTY_BUFFER: EMPTY_BUFFER2, kWebSocket, NOOP } = require_constants2(); + var { isBlob, isValidStatusCode } = require_validation(); + var { mask: applyMask, toBuffer } = require_buffer_util(); + var kByteLength = /* @__PURE__ */ Symbol("kByteLength"); + var maskBuffer = Buffer.alloc(4); + var RANDOM_POOL_SIZE = 8 * 1024; + var randomPool; + var randomPoolPointer = RANDOM_POOL_SIZE; + var DEFAULT = 0; + var DEFLATING = 1; + var GET_BLOB_DATA = 2; + var Sender2 = class _Sender { + /** + * Creates a Sender instance. + * + * @param {Duplex} socket The connection socket + * @param {Object} [extensions] An object containing the negotiated extensions + * @param {Function} [generateMask] The function used to generate the masking + * key + */ + constructor(socket, extensions, generateMask) { + this._extensions = extensions || {}; + if (generateMask) { + this._generateMask = generateMask; + this._maskBuffer = Buffer.alloc(4); + } + this._socket = socket; + this._firstFragment = true; + this._compress = false; + this._bufferedBytes = 0; + this._queue = []; + this._state = DEFAULT; + this.onerror = NOOP; + this[kWebSocket] = void 0; + } + /** + * Frames a piece of data according to the HyBi WebSocket protocol. + * + * @param {(Buffer|String)} data The data to frame + * @param {Object} options Options object + * @param {Boolean} [options.fin=false] Specifies whether or not to set the + * FIN bit + * @param {Function} [options.generateMask] The function used to generate the + * masking key + * @param {Boolean} [options.mask=false] Specifies whether or not to mask + * `data` + * @param {Buffer} [options.maskBuffer] The buffer used to store the masking + * key + * @param {Number} options.opcode The opcode + * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be + * modified + * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the + * RSV1 bit + * @return {(Buffer|String)[]} The framed data + * @public + */ + static frame(data2, options) { + let mask; + let merge2 = false; + let offset = 2; + let skipMasking = false; + if (options.mask) { + mask = options.maskBuffer || maskBuffer; + if (options.generateMask) { + options.generateMask(mask); + } else { + if (randomPoolPointer === RANDOM_POOL_SIZE) { + if (randomPool === void 0) { + randomPool = Buffer.alloc(RANDOM_POOL_SIZE); + } + randomFillSync(randomPool, 0, RANDOM_POOL_SIZE); + randomPoolPointer = 0; + } + mask[0] = randomPool[randomPoolPointer++]; + mask[1] = randomPool[randomPoolPointer++]; + mask[2] = randomPool[randomPoolPointer++]; + mask[3] = randomPool[randomPoolPointer++]; + } + skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0; + offset = 6; + } + let dataLength; + if (typeof data2 === "string") { + if ((!options.mask || skipMasking) && options[kByteLength] !== void 0) { + dataLength = options[kByteLength]; + } else { + data2 = Buffer.from(data2); + dataLength = data2.length; + } + } else { + dataLength = data2.length; + merge2 = options.mask && options.readOnly && !skipMasking; + } + let payloadLength = dataLength; + if (dataLength >= 65536) { + offset += 8; + payloadLength = 127; + } else if (dataLength > 125) { + offset += 2; + payloadLength = 126; + } + const target = Buffer.allocUnsafe(merge2 ? dataLength + offset : offset); + target[0] = options.fin ? options.opcode | 128 : options.opcode; + if (options.rsv1) target[0] |= 64; + target[1] = payloadLength; + if (payloadLength === 126) { + target.writeUInt16BE(dataLength, 2); + } else if (payloadLength === 127) { + target[2] = target[3] = 0; + target.writeUIntBE(dataLength, 4, 6); + } + if (!options.mask) return [target, data2]; + target[1] |= 128; + target[offset - 4] = mask[0]; + target[offset - 3] = mask[1]; + target[offset - 2] = mask[2]; + target[offset - 1] = mask[3]; + if (skipMasking) return [target, data2]; + if (merge2) { + applyMask(data2, mask, target, offset, dataLength); + return [target]; + } + applyMask(data2, mask, data2, 0, dataLength); + return [target, data2]; + } + /** + * Sends a close message to the other peer. + * + * @param {Number} [code] The status code component of the body + * @param {(String|Buffer)} [data] The message component of the body + * @param {Boolean} [mask=false] Specifies whether or not to mask the message + * @param {Function} [cb] Callback + * @public + */ + close(code, data2, mask, cb) { + let buf; + if (code === void 0) { + buf = EMPTY_BUFFER2; + } else if (typeof code !== "number" || !isValidStatusCode(code)) { + throw new TypeError("First argument must be a valid error code number"); + } else if (data2 === void 0 || !data2.length) { + buf = Buffer.allocUnsafe(2); + buf.writeUInt16BE(code, 0); + } else { + const length = Buffer.byteLength(data2); + if (length > 123) { + throw new RangeError("The message must not be greater than 123 bytes"); + } + buf = Buffer.allocUnsafe(2 + length); + buf.writeUInt16BE(code, 0); + if (typeof data2 === "string") { + buf.write(data2, 2); + } else { + buf.set(data2, 2); + } + } + const options = { + [kByteLength]: buf.length, + fin: true, + generateMask: this._generateMask, + mask, + maskBuffer: this._maskBuffer, + opcode: 8, + readOnly: false, + rsv1: false + }; + if (this._state !== DEFAULT) { + this.enqueue([this.dispatch, buf, false, options, cb]); + } else { + this.sendFrame(_Sender.frame(buf, options), cb); + } + } + /** + * Sends a ping message to the other peer. + * + * @param {*} data The message to send + * @param {Boolean} [mask=false] Specifies whether or not to mask `data` + * @param {Function} [cb] Callback + * @public + */ + ping(data2, mask, cb) { + let byteLength; + let readOnly; + if (typeof data2 === "string") { + byteLength = Buffer.byteLength(data2); + readOnly = false; + } else if (isBlob(data2)) { + byteLength = data2.size; + readOnly = false; + } else { + data2 = toBuffer(data2); + byteLength = data2.length; + readOnly = toBuffer.readOnly; + } + if (byteLength > 125) { + throw new RangeError("The data size must not be greater than 125 bytes"); + } + const options = { + [kByteLength]: byteLength, + fin: true, + generateMask: this._generateMask, + mask, + maskBuffer: this._maskBuffer, + opcode: 9, + readOnly, + rsv1: false + }; + if (isBlob(data2)) { + if (this._state !== DEFAULT) { + this.enqueue([this.getBlobData, data2, false, options, cb]); + } else { + this.getBlobData(data2, false, options, cb); + } + } else if (this._state !== DEFAULT) { + this.enqueue([this.dispatch, data2, false, options, cb]); + } else { + this.sendFrame(_Sender.frame(data2, options), cb); + } + } + /** + * Sends a pong message to the other peer. + * + * @param {*} data The message to send + * @param {Boolean} [mask=false] Specifies whether or not to mask `data` + * @param {Function} [cb] Callback + * @public + */ + pong(data2, mask, cb) { + let byteLength; + let readOnly; + if (typeof data2 === "string") { + byteLength = Buffer.byteLength(data2); + readOnly = false; + } else if (isBlob(data2)) { + byteLength = data2.size; + readOnly = false; + } else { + data2 = toBuffer(data2); + byteLength = data2.length; + readOnly = toBuffer.readOnly; + } + if (byteLength > 125) { + throw new RangeError("The data size must not be greater than 125 bytes"); + } + const options = { + [kByteLength]: byteLength, + fin: true, + generateMask: this._generateMask, + mask, + maskBuffer: this._maskBuffer, + opcode: 10, + readOnly, + rsv1: false + }; + if (isBlob(data2)) { + if (this._state !== DEFAULT) { + this.enqueue([this.getBlobData, data2, false, options, cb]); + } else { + this.getBlobData(data2, false, options, cb); + } + } else if (this._state !== DEFAULT) { + this.enqueue([this.dispatch, data2, false, options, cb]); + } else { + this.sendFrame(_Sender.frame(data2, options), cb); + } + } + /** + * Sends a data message to the other peer. + * + * @param {*} data The message to send + * @param {Object} options Options object + * @param {Boolean} [options.binary=false] Specifies whether `data` is binary + * or text + * @param {Boolean} [options.compress=false] Specifies whether or not to + * compress `data` + * @param {Boolean} [options.fin=false] Specifies whether the fragment is the + * last one + * @param {Boolean} [options.mask=false] Specifies whether or not to mask + * `data` + * @param {Function} [cb] Callback + * @public + */ + send(data2, options, cb) { + const perMessageDeflate = this._extensions[PerMessageDeflate2.extensionName]; + let opcode = options.binary ? 2 : 1; + let rsv1 = options.compress; + let byteLength; + let readOnly; + if (typeof data2 === "string") { + byteLength = Buffer.byteLength(data2); + readOnly = false; + } else if (isBlob(data2)) { + byteLength = data2.size; + readOnly = false; + } else { + data2 = toBuffer(data2); + byteLength = data2.length; + readOnly = toBuffer.readOnly; + } + if (this._firstFragment) { + this._firstFragment = false; + if (rsv1 && perMessageDeflate && perMessageDeflate.params[perMessageDeflate._isServer ? "server_no_context_takeover" : "client_no_context_takeover"]) { + rsv1 = byteLength >= perMessageDeflate._threshold; + } + this._compress = rsv1; + } else { + rsv1 = false; + opcode = 0; + } + if (options.fin) this._firstFragment = true; + const opts = { + [kByteLength]: byteLength, + fin: options.fin, + generateMask: this._generateMask, + mask: options.mask, + maskBuffer: this._maskBuffer, + opcode, + readOnly, + rsv1 + }; + if (isBlob(data2)) { + if (this._state !== DEFAULT) { + this.enqueue([this.getBlobData, data2, this._compress, opts, cb]); + } else { + this.getBlobData(data2, this._compress, opts, cb); + } + } else if (this._state !== DEFAULT) { + this.enqueue([this.dispatch, data2, this._compress, opts, cb]); + } else { + this.dispatch(data2, this._compress, opts, cb); + } + } + /** + * Gets the contents of a blob as binary data. + * + * @param {Blob} blob The blob + * @param {Boolean} [compress=false] Specifies whether or not to compress + * the data + * @param {Object} options Options object + * @param {Boolean} [options.fin=false] Specifies whether or not to set the + * FIN bit + * @param {Function} [options.generateMask] The function used to generate the + * masking key + * @param {Boolean} [options.mask=false] Specifies whether or not to mask + * `data` + * @param {Buffer} [options.maskBuffer] The buffer used to store the masking + * key + * @param {Number} options.opcode The opcode + * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be + * modified + * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the + * RSV1 bit + * @param {Function} [cb] Callback + * @private + */ + getBlobData(blob, compress2, options, cb) { + this._bufferedBytes += options[kByteLength]; + this._state = GET_BLOB_DATA; + blob.arrayBuffer().then((arrayBuffer) => { + if (this._socket.destroyed) { + const err = new Error( + "The socket was closed while the blob was being read" + ); + process.nextTick(callCallbacks, this, err, cb); + return; + } + this._bufferedBytes -= options[kByteLength]; + const data2 = toBuffer(arrayBuffer); + if (!compress2) { + this._state = DEFAULT; + this.sendFrame(_Sender.frame(data2, options), cb); + this.dequeue(); + } else { + this.dispatch(data2, compress2, options, cb); + } + }).catch((err) => { + process.nextTick(onError, this, err, cb); + }); + } + /** + * Dispatches a message. + * + * @param {(Buffer|String)} data The message to send + * @param {Boolean} [compress=false] Specifies whether or not to compress + * `data` + * @param {Object} options Options object + * @param {Boolean} [options.fin=false] Specifies whether or not to set the + * FIN bit + * @param {Function} [options.generateMask] The function used to generate the + * masking key + * @param {Boolean} [options.mask=false] Specifies whether or not to mask + * `data` + * @param {Buffer} [options.maskBuffer] The buffer used to store the masking + * key + * @param {Number} options.opcode The opcode + * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be + * modified + * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the + * RSV1 bit + * @param {Function} [cb] Callback + * @private + */ + dispatch(data2, compress2, options, cb) { + if (!compress2) { + this.sendFrame(_Sender.frame(data2, options), cb); + return; + } + const perMessageDeflate = this._extensions[PerMessageDeflate2.extensionName]; + this._bufferedBytes += options[kByteLength]; + this._state = DEFLATING; + perMessageDeflate.compress(data2, options.fin, (_, buf) => { + if (this._socket.destroyed) { + const err = new Error( + "The socket was closed while data was being compressed" + ); + callCallbacks(this, err, cb); + return; + } + this._bufferedBytes -= options[kByteLength]; + this._state = DEFAULT; + options.readOnly = false; + this.sendFrame(_Sender.frame(buf, options), cb); + this.dequeue(); + }); + } + /** + * Executes queued send operations. + * + * @private + */ + dequeue() { + while (this._state === DEFAULT && this._queue.length) { + const params = this._queue.shift(); + this._bufferedBytes -= params[3][kByteLength]; + Reflect.apply(params[0], this, params.slice(1)); + } + } + /** + * Enqueues a send operation. + * + * @param {Array} params Send operation parameters. + * @private + */ + enqueue(params) { + this._bufferedBytes += params[3][kByteLength]; + this._queue.push(params); + } + /** + * Sends a frame. + * + * @param {(Buffer | String)[]} list The frame to send + * @param {Function} [cb] Callback + * @private + */ + sendFrame(list2, cb) { + if (list2.length === 2) { + this._socket.cork(); + this._socket.write(list2[0]); + this._socket.write(list2[1], cb); + this._socket.uncork(); + } else { + this._socket.write(list2[0], cb); + } + } + }; + module.exports = Sender2; + function callCallbacks(sender, err, cb) { + if (typeof cb === "function") cb(err); + for (let i5 = 0; i5 < sender._queue.length; i5++) { + const params = sender._queue[i5]; + const callback = params[params.length - 1]; + if (typeof callback === "function") callback(err); + } + } + function onError(sender, err, cb) { + callCallbacks(sender, err, cb); + sender.onerror(err); + } + } +}); + +// node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/event-target.js +var require_event_target = __commonJS({ + "node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/event-target.js"(exports, module) { + "use strict"; + var { kForOnEventAttribute, kListener } = require_constants2(); + var kCode = /* @__PURE__ */ Symbol("kCode"); + var kData = /* @__PURE__ */ Symbol("kData"); + var kError = /* @__PURE__ */ Symbol("kError"); + var kMessage = /* @__PURE__ */ Symbol("kMessage"); + var kReason = /* @__PURE__ */ Symbol("kReason"); + var kTarget = /* @__PURE__ */ Symbol("kTarget"); + var kType = /* @__PURE__ */ Symbol("kType"); + var kWasClean = /* @__PURE__ */ Symbol("kWasClean"); + var Event = class { + /** + * Create a new `Event`. + * + * @param {String} type The name of the event + * @throws {TypeError} If the `type` argument is not specified + */ + constructor(type) { + this[kTarget] = null; + this[kType] = type; + } + /** + * @type {*} + */ + get target() { + return this[kTarget]; + } + /** + * @type {String} + */ + get type() { + return this[kType]; + } + }; + Object.defineProperty(Event.prototype, "target", { enumerable: true }); + Object.defineProperty(Event.prototype, "type", { enumerable: true }); + var CloseEvent = class extends Event { + /** + * Create a new `CloseEvent`. + * + * @param {String} type The name of the event + * @param {Object} [options] A dictionary object that allows for setting + * attributes via object members of the same name + * @param {Number} [options.code=0] The status code explaining why the + * connection was closed + * @param {String} [options.reason=''] A human-readable string explaining why + * the connection was closed + * @param {Boolean} [options.wasClean=false] Indicates whether or not the + * connection was cleanly closed + */ + constructor(type, options = {}) { + super(type); + this[kCode] = options.code === void 0 ? 0 : options.code; + this[kReason] = options.reason === void 0 ? "" : options.reason; + this[kWasClean] = options.wasClean === void 0 ? false : options.wasClean; + } + /** + * @type {Number} + */ + get code() { + return this[kCode]; + } + /** + * @type {String} + */ + get reason() { + return this[kReason]; + } + /** + * @type {Boolean} + */ + get wasClean() { + return this[kWasClean]; + } + }; + Object.defineProperty(CloseEvent.prototype, "code", { enumerable: true }); + Object.defineProperty(CloseEvent.prototype, "reason", { enumerable: true }); + Object.defineProperty(CloseEvent.prototype, "wasClean", { enumerable: true }); + var ErrorEvent = class extends Event { + /** + * Create a new `ErrorEvent`. + * + * @param {String} type The name of the event + * @param {Object} [options] A dictionary object that allows for setting + * attributes via object members of the same name + * @param {*} [options.error=null] The error that generated this event + * @param {String} [options.message=''] The error message + */ + constructor(type, options = {}) { + super(type); + this[kError] = options.error === void 0 ? null : options.error; + this[kMessage] = options.message === void 0 ? "" : options.message; + } + /** + * @type {*} + */ + get error() { + return this[kError]; + } + /** + * @type {String} + */ + get message() { + return this[kMessage]; + } + }; + Object.defineProperty(ErrorEvent.prototype, "error", { enumerable: true }); + Object.defineProperty(ErrorEvent.prototype, "message", { enumerable: true }); + var MessageEvent = class extends Event { + /** + * Create a new `MessageEvent`. + * + * @param {String} type The name of the event + * @param {Object} [options] A dictionary object that allows for setting + * attributes via object members of the same name + * @param {*} [options.data=null] The message content + */ + constructor(type, options = {}) { + super(type); + this[kData] = options.data === void 0 ? null : options.data; + } + /** + * @type {*} + */ + get data() { + return this[kData]; + } + }; + Object.defineProperty(MessageEvent.prototype, "data", { enumerable: true }); + var EventTarget = { + /** + * Register an event listener. + * + * @param {String} type A string representing the event type to listen for + * @param {(Function|Object)} handler The listener to add + * @param {Object} [options] An options object specifies characteristics about + * the event listener + * @param {Boolean} [options.once=false] A `Boolean` indicating that the + * listener should be invoked at most once after being added. If `true`, + * the listener would be automatically removed when invoked. + * @public + */ + addEventListener(type, handler, options = {}) { + for (const listener of this.listeners(type)) { + if (!options[kForOnEventAttribute] && listener[kListener] === handler && !listener[kForOnEventAttribute]) { + return; + } + } + let wrapper; + if (type === "message") { + wrapper = function onMessage(data2, isBinary) { + const event = new MessageEvent("message", { + data: isBinary ? data2 : data2.toString() + }); + event[kTarget] = this; + callListener(handler, this, event); + }; + } else if (type === "close") { + wrapper = function onClose(code, message2) { + const event = new CloseEvent("close", { + code, + reason: message2.toString(), + wasClean: this._closeFrameReceived && this._closeFrameSent + }); + event[kTarget] = this; + callListener(handler, this, event); + }; + } else if (type === "error") { + wrapper = function onError(error50) { + const event = new ErrorEvent("error", { + error: error50, + message: error50.message + }); + event[kTarget] = this; + callListener(handler, this, event); + }; + } else if (type === "open") { + wrapper = function onOpen() { + const event = new Event("open"); + event[kTarget] = this; + callListener(handler, this, event); + }; + } else { + return; + } + wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute]; + wrapper[kListener] = handler; + if (options.once) { + this.once(type, wrapper); + } else { + this.on(type, wrapper); + } + }, + /** + * Remove an event listener. + * + * @param {String} type A string representing the event type to remove + * @param {(Function|Object)} handler The listener to remove + * @public + */ + removeEventListener(type, handler) { + for (const listener of this.listeners(type)) { + if (listener[kListener] === handler && !listener[kForOnEventAttribute]) { + this.removeListener(type, listener); + break; + } + } + } + }; + module.exports = { + CloseEvent, + ErrorEvent, + Event, + EventTarget, + MessageEvent + }; + function callListener(listener, thisArg, event) { + if (typeof listener === "object" && listener.handleEvent) { + listener.handleEvent.call(listener, event); + } else { + listener.call(thisArg, event); + } + } + } +}); + +// node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/extension.js +var require_extension = __commonJS({ + "node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/extension.js"(exports, module) { + "use strict"; + var { tokenChars } = require_validation(); + function push(dest, name, elem) { + if (dest[name] === void 0) dest[name] = [elem]; + else dest[name].push(elem); + } + function parse5(header) { + const offers = /* @__PURE__ */ Object.create(null); + let params = /* @__PURE__ */ Object.create(null); + let mustUnescape = false; + let isEscaping = false; + let inQuotes = false; + let extensionName; + let paramName; + let start = -1; + let code = -1; + let end = -1; + let i5 = 0; + for (; i5 < header.length; i5++) { + code = header.charCodeAt(i5); + if (extensionName === void 0) { + if (end === -1 && tokenChars[code] === 1) { + if (start === -1) start = i5; + } else if (i5 !== 0 && (code === 32 || code === 9)) { + if (end === -1 && start !== -1) end = i5; + } else if (code === 59 || code === 44) { + if (start === -1) { + throw new SyntaxError(`Unexpected character at index ${i5}`); + } + if (end === -1) end = i5; + const name = header.slice(start, end); + if (code === 44) { + push(offers, name, params); + params = /* @__PURE__ */ Object.create(null); + } else { + extensionName = name; + } + start = end = -1; + } else { + throw new SyntaxError(`Unexpected character at index ${i5}`); + } + } else if (paramName === void 0) { + if (end === -1 && tokenChars[code] === 1) { + if (start === -1) start = i5; + } else if (code === 32 || code === 9) { + if (end === -1 && start !== -1) end = i5; + } else if (code === 59 || code === 44) { + if (start === -1) { + throw new SyntaxError(`Unexpected character at index ${i5}`); + } + if (end === -1) end = i5; + push(params, header.slice(start, end), true); + if (code === 44) { + push(offers, extensionName, params); + params = /* @__PURE__ */ Object.create(null); + extensionName = void 0; + } + start = end = -1; + } else if (code === 61 && start !== -1 && end === -1) { + paramName = header.slice(start, i5); + start = end = -1; + } else { + throw new SyntaxError(`Unexpected character at index ${i5}`); + } + } else { + if (isEscaping) { + if (tokenChars[code] !== 1) { + throw new SyntaxError(`Unexpected character at index ${i5}`); + } + if (start === -1) start = i5; + else if (!mustUnescape) mustUnescape = true; + isEscaping = false; + } else if (inQuotes) { + if (tokenChars[code] === 1) { + if (start === -1) start = i5; + } else if (code === 34 && start !== -1) { + inQuotes = false; + end = i5; + } else if (code === 92) { + isEscaping = true; + } else { + throw new SyntaxError(`Unexpected character at index ${i5}`); + } + } else if (code === 34 && header.charCodeAt(i5 - 1) === 61) { + inQuotes = true; + } else if (end === -1 && tokenChars[code] === 1) { + if (start === -1) start = i5; + } else if (start !== -1 && (code === 32 || code === 9)) { + if (end === -1) end = i5; + } else if (code === 59 || code === 44) { + if (start === -1) { + throw new SyntaxError(`Unexpected character at index ${i5}`); + } + if (end === -1) end = i5; + let value = header.slice(start, end); + if (mustUnescape) { + value = value.replace(/\\/g, ""); + mustUnescape = false; + } + push(params, paramName, value); + if (code === 44) { + push(offers, extensionName, params); + params = /* @__PURE__ */ Object.create(null); + extensionName = void 0; + } + paramName = void 0; + start = end = -1; + } else { + throw new SyntaxError(`Unexpected character at index ${i5}`); + } + } + } + if (start === -1 || inQuotes || code === 32 || code === 9) { + throw new SyntaxError("Unexpected end of input"); + } + if (end === -1) end = i5; + const token = header.slice(start, end); + if (extensionName === void 0) { + push(offers, token, params); + } else { + if (paramName === void 0) { + push(params, token, true); + } else if (mustUnescape) { + push(params, paramName, token.replace(/\\/g, "")); + } else { + push(params, paramName, token); + } + push(offers, extensionName, params); + } + return offers; + } + function format2(extensions) { + return Object.keys(extensions).map((extension2) => { + let configurations = extensions[extension2]; + if (!Array.isArray(configurations)) configurations = [configurations]; + return configurations.map((params) => { + return [extension2].concat( + Object.keys(params).map((k5) => { + let values2 = params[k5]; + if (!Array.isArray(values2)) values2 = [values2]; + return values2.map((v5) => v5 === true ? k5 : `${k5}=${v5}`).join("; "); + }) + ).join("; "); + }).join(", "); + }).join(", "); + } + module.exports = { format: format2, parse: parse5 }; + } +}); + +// node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/websocket.js +var require_websocket = __commonJS({ + "node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/websocket.js"(exports, module) { + "use strict"; + var EventEmitter5 = __require("events"); + var https = __require("https"); + var http = __require("http"); + var net3 = __require("net"); + var tls2 = __require("tls"); + var { randomBytes: randomBytes7, createHash: createHash18 } = __require("crypto"); + var { Duplex, Readable: Readable3 } = __require("stream"); + var { URL: URL2 } = __require("url"); + var PerMessageDeflate2 = require_permessage_deflate(); + var Receiver2 = require_receiver(); + var Sender2 = require_sender(); + var { isBlob } = require_validation(); + var { + BINARY_TYPES, + CLOSE_TIMEOUT, + EMPTY_BUFFER: EMPTY_BUFFER2, + GUID, + kForOnEventAttribute, + kListener, + kStatusCode, + kWebSocket, + NOOP + } = require_constants2(); + var { + EventTarget: { addEventListener, removeEventListener } + } = require_event_target(); + var { format: format2, parse: parse5 } = require_extension(); + var { toBuffer } = require_buffer_util(); + var kAborted = /* @__PURE__ */ Symbol("kAborted"); + var protocolVersions = [8, 13]; + var readyStates = ["CONNECTING", "OPEN", "CLOSING", "CLOSED"]; + var subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/; + var WebSocket2 = class _WebSocket extends EventEmitter5 { + /** + * Create a new `WebSocket`. + * + * @param {(String|URL)} address The URL to which to connect + * @param {(String|String[])} [protocols] The subprotocols + * @param {Object} [options] Connection options + */ + constructor(address, protocols, options) { + super(); + this._binaryType = BINARY_TYPES[0]; + this._closeCode = 1006; + this._closeFrameReceived = false; + this._closeFrameSent = false; + this._closeMessage = EMPTY_BUFFER2; + this._closeTimer = null; + this._errorEmitted = false; + this._extensions = {}; + this._paused = false; + this._protocol = ""; + this._readyState = _WebSocket.CONNECTING; + this._receiver = null; + this._sender = null; + this._socket = null; + if (address !== null) { + this._bufferedAmount = 0; + this._isServer = false; + this._redirects = 0; + if (protocols === void 0) { + protocols = []; + } else if (!Array.isArray(protocols)) { + if (typeof protocols === "object" && protocols !== null) { + options = protocols; + protocols = []; + } else { + protocols = [protocols]; + } + } + initAsClient(this, address, protocols, options); + } else { + this._autoPong = options.autoPong; + this._closeTimeout = options.closeTimeout; + this._isServer = true; + } + } + /** + * For historical reasons, the custom "nodebuffer" type is used by the default + * instead of "blob". + * + * @type {String} + */ + get binaryType() { + return this._binaryType; + } + set binaryType(type) { + if (!BINARY_TYPES.includes(type)) return; + this._binaryType = type; + if (this._receiver) this._receiver._binaryType = type; + } + /** + * @type {Number} + */ + get bufferedAmount() { + if (!this._socket) return this._bufferedAmount; + return this._socket._writableState.length + this._sender._bufferedBytes; + } + /** + * @type {String} + */ + get extensions() { + return Object.keys(this._extensions).join(); + } + /** + * @type {Boolean} + */ + get isPaused() { + return this._paused; + } + /** + * @type {Function} + */ + /* istanbul ignore next */ + get onclose() { + return null; + } + /** + * @type {Function} + */ + /* istanbul ignore next */ + get onerror() { + return null; + } + /** + * @type {Function} + */ + /* istanbul ignore next */ + get onopen() { + return null; + } + /** + * @type {Function} + */ + /* istanbul ignore next */ + get onmessage() { + return null; + } + /** + * @type {String} + */ + get protocol() { + return this._protocol; + } + /** + * @type {Number} + */ + get readyState() { + return this._readyState; + } + /** + * @type {String} + */ + get url() { + return this._url; + } + /** + * Set up the socket and the internal resources. + * + * @param {Duplex} socket The network socket between the server and client + * @param {Buffer} head The first packet of the upgraded stream + * @param {Object} options Options object + * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether + * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted + * multiple times in the same tick + * @param {Function} [options.generateMask] The function used to generate the + * masking key + * @param {Number} [options.maxPayload=0] The maximum allowed message size + * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or + * not to skip UTF-8 validation for text and close messages + * @private + */ + setSocket(socket, head, options) { + const receiver = new Receiver2({ + allowSynchronousEvents: options.allowSynchronousEvents, + binaryType: this.binaryType, + extensions: this._extensions, + isServer: this._isServer, + maxPayload: options.maxPayload, + skipUTF8Validation: options.skipUTF8Validation + }); + const sender = new Sender2(socket, this._extensions, options.generateMask); + this._receiver = receiver; + this._sender = sender; + this._socket = socket; + receiver[kWebSocket] = this; + sender[kWebSocket] = this; + socket[kWebSocket] = this; + receiver.on("conclude", receiverOnConclude); + receiver.on("drain", receiverOnDrain); + receiver.on("error", receiverOnError); + receiver.on("message", receiverOnMessage); + receiver.on("ping", receiverOnPing); + receiver.on("pong", receiverOnPong); + sender.onerror = senderOnError; + if (socket.setTimeout) socket.setTimeout(0); + if (socket.setNoDelay) socket.setNoDelay(); + if (head.length > 0) socket.unshift(head); + socket.on("close", socketOnClose); + socket.on("data", socketOnData); + socket.on("end", socketOnEnd); + socket.on("error", socketOnError); + this._readyState = _WebSocket.OPEN; + this.emit("open"); + } + /** + * Emit the `'close'` event. + * + * @private + */ + emitClose() { + if (!this._socket) { + this._readyState = _WebSocket.CLOSED; + this.emit("close", this._closeCode, this._closeMessage); + return; + } + if (this._extensions[PerMessageDeflate2.extensionName]) { + this._extensions[PerMessageDeflate2.extensionName].cleanup(); + } + this._receiver.removeAllListeners(); + this._readyState = _WebSocket.CLOSED; + this.emit("close", this._closeCode, this._closeMessage); + } + /** + * Start a closing handshake. + * + * +----------+ +-----------+ +----------+ + * - - -|ws.close()|-->|close frame|-->|ws.close()|- - - + * | +----------+ +-----------+ +----------+ | + * +----------+ +-----------+ | + * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING + * +----------+ +-----------+ | + * | | | +---+ | + * +------------------------+-->|fin| - - - - + * | +---+ | +---+ + * - - - - -|fin|<---------------------+ + * +---+ + * + * @param {Number} [code] Status code explaining why the connection is closing + * @param {(String|Buffer)} [data] The reason why the connection is + * closing + * @public + */ + close(code, data2) { + if (this.readyState === _WebSocket.CLOSED) return; + if (this.readyState === _WebSocket.CONNECTING) { + const msg = "WebSocket was closed before the connection was established"; + abortHandshake(this, this._req, msg); + return; + } + if (this.readyState === _WebSocket.CLOSING) { + if (this._closeFrameSent && (this._closeFrameReceived || this._receiver._writableState.errorEmitted)) { + this._socket.end(); + } + return; + } + this._readyState = _WebSocket.CLOSING; + this._sender.close(code, data2, !this._isServer, (err) => { + if (err) return; + this._closeFrameSent = true; + if (this._closeFrameReceived || this._receiver._writableState.errorEmitted) { + this._socket.end(); + } + }); + setCloseTimer(this); + } + /** + * Pause the socket. + * + * @public + */ + pause() { + if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) { + return; + } + this._paused = true; + this._socket.pause(); + } + /** + * Send a ping. + * + * @param {*} [data] The data to send + * @param {Boolean} [mask] Indicates whether or not to mask `data` + * @param {Function} [cb] Callback which is executed when the ping is sent + * @public + */ + ping(data2, mask, cb) { + if (this.readyState === _WebSocket.CONNECTING) { + throw new Error("WebSocket is not open: readyState 0 (CONNECTING)"); + } + if (typeof data2 === "function") { + cb = data2; + data2 = mask = void 0; + } else if (typeof mask === "function") { + cb = mask; + mask = void 0; + } + if (typeof data2 === "number") data2 = data2.toString(); + if (this.readyState !== _WebSocket.OPEN) { + sendAfterClose(this, data2, cb); + return; + } + if (mask === void 0) mask = !this._isServer; + this._sender.ping(data2 || EMPTY_BUFFER2, mask, cb); + } + /** + * Send a pong. + * + * @param {*} [data] The data to send + * @param {Boolean} [mask] Indicates whether or not to mask `data` + * @param {Function} [cb] Callback which is executed when the pong is sent + * @public + */ + pong(data2, mask, cb) { + if (this.readyState === _WebSocket.CONNECTING) { + throw new Error("WebSocket is not open: readyState 0 (CONNECTING)"); + } + if (typeof data2 === "function") { + cb = data2; + data2 = mask = void 0; + } else if (typeof mask === "function") { + cb = mask; + mask = void 0; + } + if (typeof data2 === "number") data2 = data2.toString(); + if (this.readyState !== _WebSocket.OPEN) { + sendAfterClose(this, data2, cb); + return; + } + if (mask === void 0) mask = !this._isServer; + this._sender.pong(data2 || EMPTY_BUFFER2, mask, cb); + } + /** + * Resume the socket. + * + * @public + */ + resume() { + if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) { + return; + } + this._paused = false; + if (!this._receiver._writableState.needDrain) this._socket.resume(); + } + /** + * Send a data message. + * + * @param {*} data The message to send + * @param {Object} [options] Options object + * @param {Boolean} [options.binary] Specifies whether `data` is binary or + * text + * @param {Boolean} [options.compress] Specifies whether or not to compress + * `data` + * @param {Boolean} [options.fin=true] Specifies whether the fragment is the + * last one + * @param {Boolean} [options.mask] Specifies whether or not to mask `data` + * @param {Function} [cb] Callback which is executed when data is written out + * @public + */ + send(data2, options, cb) { + if (this.readyState === _WebSocket.CONNECTING) { + throw new Error("WebSocket is not open: readyState 0 (CONNECTING)"); + } + if (typeof options === "function") { + cb = options; + options = {}; + } + if (typeof data2 === "number") data2 = data2.toString(); + if (this.readyState !== _WebSocket.OPEN) { + sendAfterClose(this, data2, cb); + return; + } + const opts = { + binary: typeof data2 !== "string", + mask: !this._isServer, + compress: true, + fin: true, + ...options + }; + if (!this._extensions[PerMessageDeflate2.extensionName]) { + opts.compress = false; + } + this._sender.send(data2 || EMPTY_BUFFER2, opts, cb); + } + /** + * Forcibly close the connection. + * + * @public + */ + terminate() { + if (this.readyState === _WebSocket.CLOSED) return; + if (this.readyState === _WebSocket.CONNECTING) { + const msg = "WebSocket was closed before the connection was established"; + abortHandshake(this, this._req, msg); + return; + } + if (this._socket) { + this._readyState = _WebSocket.CLOSING; + this._socket.destroy(); + } + } + }; + Object.defineProperty(WebSocket2, "CONNECTING", { + enumerable: true, + value: readyStates.indexOf("CONNECTING") + }); + Object.defineProperty(WebSocket2.prototype, "CONNECTING", { + enumerable: true, + value: readyStates.indexOf("CONNECTING") + }); + Object.defineProperty(WebSocket2, "OPEN", { + enumerable: true, + value: readyStates.indexOf("OPEN") + }); + Object.defineProperty(WebSocket2.prototype, "OPEN", { + enumerable: true, + value: readyStates.indexOf("OPEN") + }); + Object.defineProperty(WebSocket2, "CLOSING", { + enumerable: true, + value: readyStates.indexOf("CLOSING") + }); + Object.defineProperty(WebSocket2.prototype, "CLOSING", { + enumerable: true, + value: readyStates.indexOf("CLOSING") + }); + Object.defineProperty(WebSocket2, "CLOSED", { + enumerable: true, + value: readyStates.indexOf("CLOSED") + }); + Object.defineProperty(WebSocket2.prototype, "CLOSED", { + enumerable: true, + value: readyStates.indexOf("CLOSED") + }); + [ + "binaryType", + "bufferedAmount", + "extensions", + "isPaused", + "protocol", + "readyState", + "url" + ].forEach((property) => { + Object.defineProperty(WebSocket2.prototype, property, { enumerable: true }); + }); + ["open", "error", "close", "message"].forEach((method) => { + Object.defineProperty(WebSocket2.prototype, `on${method}`, { + enumerable: true, + get() { + for (const listener of this.listeners(method)) { + if (listener[kForOnEventAttribute]) return listener[kListener]; + } + return null; + }, + set(handler) { + for (const listener of this.listeners(method)) { + if (listener[kForOnEventAttribute]) { + this.removeListener(method, listener); + break; + } + } + if (typeof handler !== "function") return; + this.addEventListener(method, handler, { + [kForOnEventAttribute]: true + }); + } + }); + }); + WebSocket2.prototype.addEventListener = addEventListener; + WebSocket2.prototype.removeEventListener = removeEventListener; + module.exports = WebSocket2; + function initAsClient(websocket, address, protocols, options) { + const opts = { + allowSynchronousEvents: true, + autoPong: true, + closeTimeout: CLOSE_TIMEOUT, + protocolVersion: protocolVersions[1], + maxPayload: 100 * 1024 * 1024, + skipUTF8Validation: false, + perMessageDeflate: true, + followRedirects: false, + maxRedirects: 10, + ...options, + socketPath: void 0, + hostname: void 0, + protocol: void 0, + timeout: void 0, + method: "GET", + host: void 0, + path: void 0, + port: void 0 + }; + websocket._autoPong = opts.autoPong; + websocket._closeTimeout = opts.closeTimeout; + if (!protocolVersions.includes(opts.protocolVersion)) { + throw new RangeError( + `Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})` + ); + } + let parsedUrl; + if (address instanceof URL2) { + parsedUrl = address; + } else { + try { + parsedUrl = new URL2(address); + } catch { + throw new SyntaxError(`Invalid URL: ${address}`); + } + } + if (parsedUrl.protocol === "http:") { + parsedUrl.protocol = "ws:"; + } else if (parsedUrl.protocol === "https:") { + parsedUrl.protocol = "wss:"; + } + websocket._url = parsedUrl.href; + const isSecure = parsedUrl.protocol === "wss:"; + const isIpcUrl = parsedUrl.protocol === "ws+unix:"; + let invalidUrlMessage; + if (parsedUrl.protocol !== "ws:" && !isSecure && !isIpcUrl) { + invalidUrlMessage = `The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`; + } else if (isIpcUrl && !parsedUrl.pathname) { + invalidUrlMessage = "The URL's pathname is empty"; + } else if (parsedUrl.hash) { + invalidUrlMessage = "The URL contains a fragment identifier"; + } + if (invalidUrlMessage) { + const err = new SyntaxError(invalidUrlMessage); + if (websocket._redirects === 0) { + throw err; + } else { + emitErrorAndClose(websocket, err); + return; + } + } + const defaultPort = isSecure ? 443 : 80; + const key = randomBytes7(16).toString("base64"); + const request = isSecure ? https.request : http.request; + const protocolSet = /* @__PURE__ */ new Set(); + let perMessageDeflate; + opts.createConnection = opts.createConnection || (isSecure ? tlsConnect : netConnect); + opts.defaultPort = opts.defaultPort || defaultPort; + opts.port = parsedUrl.port || defaultPort; + opts.host = parsedUrl.hostname.startsWith("[") ? parsedUrl.hostname.slice(1, -1) : parsedUrl.hostname; + opts.headers = { + ...opts.headers, + "Sec-WebSocket-Version": opts.protocolVersion, + "Sec-WebSocket-Key": key, + Connection: "Upgrade", + Upgrade: "websocket" + }; + opts.path = parsedUrl.pathname + parsedUrl.search; + opts.timeout = opts.handshakeTimeout; + if (opts.perMessageDeflate) { + perMessageDeflate = new PerMessageDeflate2({ + ...opts.perMessageDeflate, + isServer: false, + maxPayload: opts.maxPayload + }); + opts.headers["Sec-WebSocket-Extensions"] = format2({ + [PerMessageDeflate2.extensionName]: perMessageDeflate.offer() + }); + } + if (protocols.length) { + for (const protocol of protocols) { + if (typeof protocol !== "string" || !subprotocolRegex.test(protocol) || protocolSet.has(protocol)) { + throw new SyntaxError( + "An invalid or duplicated subprotocol was specified" + ); + } + protocolSet.add(protocol); + } + opts.headers["Sec-WebSocket-Protocol"] = protocols.join(","); + } + if (opts.origin) { + if (opts.protocolVersion < 13) { + opts.headers["Sec-WebSocket-Origin"] = opts.origin; + } else { + opts.headers.Origin = opts.origin; + } + } + if (parsedUrl.username || parsedUrl.password) { + opts.auth = `${parsedUrl.username}:${parsedUrl.password}`; + } + if (isIpcUrl) { + const parts = opts.path.split(":"); + opts.socketPath = parts[0]; + opts.path = parts[1]; + } + let req; + if (opts.followRedirects) { + if (websocket._redirects === 0) { + websocket._originalIpc = isIpcUrl; + websocket._originalSecure = isSecure; + websocket._originalHostOrSocketPath = isIpcUrl ? opts.socketPath : parsedUrl.host; + const headers = options && options.headers; + options = { ...options, headers: {} }; + if (headers) { + for (const [key2, value] of Object.entries(headers)) { + options.headers[key2.toLowerCase()] = value; + } + } + } else if (websocket.listenerCount("redirect") === 0) { + const isSameHost = isIpcUrl ? websocket._originalIpc ? opts.socketPath === websocket._originalHostOrSocketPath : false : websocket._originalIpc ? false : parsedUrl.host === websocket._originalHostOrSocketPath; + if (!isSameHost || websocket._originalSecure && !isSecure) { + delete opts.headers.authorization; + delete opts.headers.cookie; + if (!isSameHost) delete opts.headers.host; + opts.auth = void 0; + } + } + if (opts.auth && !options.headers.authorization) { + options.headers.authorization = "Basic " + Buffer.from(opts.auth).toString("base64"); + } + req = websocket._req = request(opts); + if (websocket._redirects) { + websocket.emit("redirect", websocket.url, req); + } + } else { + req = websocket._req = request(opts); + } + if (opts.timeout) { + req.on("timeout", () => { + abortHandshake(websocket, req, "Opening handshake has timed out"); + }); + } + req.on("error", (err) => { + if (req === null || req[kAborted]) return; + req = websocket._req = null; + emitErrorAndClose(websocket, err); + }); + req.on("response", (res) => { + const location = res.headers.location; + const statusCode = res.statusCode; + if (location && opts.followRedirects && statusCode >= 300 && statusCode < 400) { + if (++websocket._redirects > opts.maxRedirects) { + abortHandshake(websocket, req, "Maximum redirects exceeded"); + return; + } + req.abort(); + let addr; + try { + addr = new URL2(location, address); + } catch (e5) { + const err = new SyntaxError(`Invalid URL: ${location}`); + emitErrorAndClose(websocket, err); + return; + } + initAsClient(websocket, addr, protocols, options); + } else if (!websocket.emit("unexpected-response", req, res)) { + abortHandshake( + websocket, + req, + `Unexpected server response: ${res.statusCode}` + ); + } + }); + req.on("upgrade", (res, socket, head) => { + websocket.emit("upgrade", res); + if (websocket.readyState !== WebSocket2.CONNECTING) return; + req = websocket._req = null; + const upgrade = res.headers.upgrade; + if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") { + abortHandshake(websocket, socket, "Invalid Upgrade header"); + return; + } + const digest2 = createHash18("sha1").update(key + GUID).digest("base64"); + if (res.headers["sec-websocket-accept"] !== digest2) { + abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header"); + return; + } + const serverProt = res.headers["sec-websocket-protocol"]; + let protError; + if (serverProt !== void 0) { + if (!protocolSet.size) { + protError = "Server sent a subprotocol but none was requested"; + } else if (!protocolSet.has(serverProt)) { + protError = "Server sent an invalid subprotocol"; + } + } else if (protocolSet.size) { + protError = "Server sent no subprotocol"; + } + if (protError) { + abortHandshake(websocket, socket, protError); + return; + } + if (serverProt) websocket._protocol = serverProt; + const secWebSocketExtensions = res.headers["sec-websocket-extensions"]; + if (secWebSocketExtensions !== void 0) { + if (!perMessageDeflate) { + const message2 = "Server sent a Sec-WebSocket-Extensions header but no extension was requested"; + abortHandshake(websocket, socket, message2); + return; + } + let extensions; + try { + extensions = parse5(secWebSocketExtensions); + } catch (err) { + const message2 = "Invalid Sec-WebSocket-Extensions header"; + abortHandshake(websocket, socket, message2); + return; + } + const extensionNames = Object.keys(extensions); + if (extensionNames.length !== 1 || extensionNames[0] !== PerMessageDeflate2.extensionName) { + const message2 = "Server indicated an extension that was not requested"; + abortHandshake(websocket, socket, message2); + return; + } + try { + perMessageDeflate.accept(extensions[PerMessageDeflate2.extensionName]); + } catch (err) { + const message2 = "Invalid Sec-WebSocket-Extensions header"; + abortHandshake(websocket, socket, message2); + return; + } + websocket._extensions[PerMessageDeflate2.extensionName] = perMessageDeflate; + } + websocket.setSocket(socket, head, { + allowSynchronousEvents: opts.allowSynchronousEvents, + generateMask: opts.generateMask, + maxPayload: opts.maxPayload, + skipUTF8Validation: opts.skipUTF8Validation + }); + }); + if (opts.finishRequest) { + opts.finishRequest(req, websocket); + } else { + req.end(); + } + } + function emitErrorAndClose(websocket, err) { + websocket._readyState = WebSocket2.CLOSING; + websocket._errorEmitted = true; + websocket.emit("error", err); + websocket.emitClose(); + } + function netConnect(options) { + options.path = options.socketPath; + return net3.connect(options); + } + function tlsConnect(options) { + options.path = void 0; + if (!options.servername && options.servername !== "") { + options.servername = net3.isIP(options.host) ? "" : options.host; + } + return tls2.connect(options); + } + function abortHandshake(websocket, stream, message2) { + websocket._readyState = WebSocket2.CLOSING; + const err = new Error(message2); + Error.captureStackTrace(err, abortHandshake); + if (stream.setHeader) { + stream[kAborted] = true; + stream.abort(); + if (stream.socket && !stream.socket.destroyed) { + stream.socket.destroy(); + } + process.nextTick(emitErrorAndClose, websocket, err); + } else { + stream.destroy(err); + stream.once("error", websocket.emit.bind(websocket, "error")); + stream.once("close", websocket.emitClose.bind(websocket)); + } + } + function sendAfterClose(websocket, data2, cb) { + if (data2) { + const length = isBlob(data2) ? data2.size : toBuffer(data2).length; + if (websocket._socket) websocket._sender._bufferedBytes += length; + else websocket._bufferedAmount += length; + } + if (cb) { + const err = new Error( + `WebSocket is not open: readyState ${websocket.readyState} (${readyStates[websocket.readyState]})` + ); + process.nextTick(cb, err); + } + } + function receiverOnConclude(code, reason) { + const websocket = this[kWebSocket]; + websocket._closeFrameReceived = true; + websocket._closeMessage = reason; + websocket._closeCode = code; + if (websocket._socket[kWebSocket] === void 0) return; + websocket._socket.removeListener("data", socketOnData); + process.nextTick(resume, websocket._socket); + if (code === 1005) websocket.close(); + else websocket.close(code, reason); + } + function receiverOnDrain() { + const websocket = this[kWebSocket]; + if (!websocket.isPaused) websocket._socket.resume(); + } + function receiverOnError(err) { + const websocket = this[kWebSocket]; + if (websocket._socket[kWebSocket] !== void 0) { + websocket._socket.removeListener("data", socketOnData); + process.nextTick(resume, websocket._socket); + websocket.close(err[kStatusCode]); + } + if (!websocket._errorEmitted) { + websocket._errorEmitted = true; + websocket.emit("error", err); + } + } + function receiverOnFinish() { + this[kWebSocket].emitClose(); + } + function receiverOnMessage(data2, isBinary) { + this[kWebSocket].emit("message", data2, isBinary); + } + function receiverOnPing(data2) { + const websocket = this[kWebSocket]; + if (websocket._autoPong) websocket.pong(data2, !this._isServer, NOOP); + websocket.emit("ping", data2); + } + function receiverOnPong(data2) { + this[kWebSocket].emit("pong", data2); + } + function resume(stream) { + stream.resume(); + } + function senderOnError(err) { + const websocket = this[kWebSocket]; + if (websocket.readyState === WebSocket2.CLOSED) return; + if (websocket.readyState === WebSocket2.OPEN) { + websocket._readyState = WebSocket2.CLOSING; + setCloseTimer(websocket); + } + this._socket.end(); + if (!websocket._errorEmitted) { + websocket._errorEmitted = true; + websocket.emit("error", err); + } + } + function setCloseTimer(websocket) { + websocket._closeTimer = setTimeout( + websocket._socket.destroy.bind(websocket._socket), + websocket._closeTimeout + ); + } + function socketOnClose() { + const websocket = this[kWebSocket]; + this.removeListener("close", socketOnClose); + this.removeListener("data", socketOnData); + this.removeListener("end", socketOnEnd); + websocket._readyState = WebSocket2.CLOSING; + if (!this._readableState.endEmitted && !websocket._closeFrameReceived && !websocket._receiver._writableState.errorEmitted && this._readableState.length !== 0) { + const chunk = this.read(this._readableState.length); + websocket._receiver.write(chunk); + } + websocket._receiver.end(); + this[kWebSocket] = void 0; + clearTimeout(websocket._closeTimer); + if (websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted) { + websocket.emitClose(); + } else { + websocket._receiver.on("error", receiverOnFinish); + websocket._receiver.on("finish", receiverOnFinish); + } + } + function socketOnData(chunk) { + if (!this[kWebSocket]._receiver.write(chunk)) { + this.pause(); + } + } + function socketOnEnd() { + const websocket = this[kWebSocket]; + websocket._readyState = WebSocket2.CLOSING; + websocket._receiver.end(); + this.end(); + } + function socketOnError() { + const websocket = this[kWebSocket]; + this.removeListener("error", socketOnError); + this.on("error", NOOP); + if (websocket) { + websocket._readyState = WebSocket2.CLOSING; + this.destroy(); + } + } + } +}); + +// node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/stream.js +var require_stream = __commonJS({ + "node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/stream.js"(exports, module) { + "use strict"; + var WebSocket2 = require_websocket(); + var { Duplex } = __require("stream"); + function emitClose(stream) { + stream.emit("close"); + } + function duplexOnEnd() { + if (!this.destroyed && this._writableState.finished) { + this.destroy(); + } + } + function duplexOnError(err) { + this.removeListener("error", duplexOnError); + this.destroy(); + if (this.listenerCount("error") === 0) { + this.emit("error", err); + } + } + function createWebSocketStream2(ws, options) { + let terminateOnDestroy = true; + const duplex = new Duplex({ + ...options, + autoDestroy: false, + emitClose: false, + objectMode: false, + writableObjectMode: false + }); + ws.on("message", function message2(msg, isBinary) { + const data2 = !isBinary && duplex._readableState.objectMode ? msg.toString() : msg; + if (!duplex.push(data2)) ws.pause(); + }); + ws.once("error", function error50(err) { + if (duplex.destroyed) return; + terminateOnDestroy = false; + duplex.destroy(err); + }); + ws.once("close", function close() { + if (duplex.destroyed) return; + duplex.push(null); + }); + duplex._destroy = function(err, callback) { + if (ws.readyState === ws.CLOSED) { + callback(err); + process.nextTick(emitClose, duplex); + return; + } + let called = false; + ws.once("error", function error50(err2) { + called = true; + callback(err2); + }); + ws.once("close", function close() { + if (!called) callback(err); + process.nextTick(emitClose, duplex); + }); + if (terminateOnDestroy) ws.terminate(); + }; + duplex._final = function(callback) { + if (ws.readyState === ws.CONNECTING) { + ws.once("open", function open2() { + duplex._final(callback); + }); + return; + } + if (ws._socket === null) return; + if (ws._socket._writableState.finished) { + callback(); + if (duplex._readableState.endEmitted) duplex.destroy(); + } else { + ws._socket.once("finish", function finish() { + callback(); + }); + ws.close(); + } + }; + duplex._read = function() { + if (ws.isPaused) ws.resume(); + }; + duplex._write = function(chunk, encoding, callback) { + if (ws.readyState === ws.CONNECTING) { + ws.once("open", function open2() { + duplex._write(chunk, encoding, callback); + }); + return; + } + ws.send(chunk, callback); + }; + duplex.on("end", duplexOnEnd); + duplex.on("error", duplexOnError); + return duplex; + } + module.exports = createWebSocketStream2; + } +}); + +// node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/subprotocol.js +var require_subprotocol = __commonJS({ + "node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/subprotocol.js"(exports, module) { + "use strict"; + var { tokenChars } = require_validation(); + function parse5(header) { + const protocols = /* @__PURE__ */ new Set(); + let start = -1; + let end = -1; + let i5 = 0; + for (i5; i5 < header.length; i5++) { + const code = header.charCodeAt(i5); + if (end === -1 && tokenChars[code] === 1) { + if (start === -1) start = i5; + } else if (i5 !== 0 && (code === 32 || code === 9)) { + if (end === -1 && start !== -1) end = i5; + } else if (code === 44) { + if (start === -1) { + throw new SyntaxError(`Unexpected character at index ${i5}`); + } + if (end === -1) end = i5; + const protocol2 = header.slice(start, end); + if (protocols.has(protocol2)) { + throw new SyntaxError(`The "${protocol2}" subprotocol is duplicated`); + } + protocols.add(protocol2); + start = end = -1; + } else { + throw new SyntaxError(`Unexpected character at index ${i5}`); + } + } + if (start === -1 || end !== -1) { + throw new SyntaxError("Unexpected end of input"); + } + const protocol = header.slice(start, i5); + if (protocols.has(protocol)) { + throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`); + } + protocols.add(protocol); + return protocols; + } + module.exports = { parse: parse5 }; + } +}); + +// node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/websocket-server.js +var require_websocket_server = __commonJS({ + "node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/websocket-server.js"(exports, module) { + "use strict"; + var EventEmitter5 = __require("events"); + var http = __require("http"); + var { Duplex } = __require("stream"); + var { createHash: createHash18 } = __require("crypto"); + var extension2 = require_extension(); + var PerMessageDeflate2 = require_permessage_deflate(); + var subprotocol2 = require_subprotocol(); + var WebSocket2 = require_websocket(); + var { CLOSE_TIMEOUT, GUID, kWebSocket } = require_constants2(); + var keyRegex = /^[+/0-9A-Za-z]{22}==$/; + var RUNNING = 0; + var CLOSING = 1; + var CLOSED = 2; + var WebSocketServer2 = class extends EventEmitter5 { + /** + * Create a `WebSocketServer` instance. + * + * @param {Object} options Configuration options + * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether + * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted + * multiple times in the same tick + * @param {Boolean} [options.autoPong=true] Specifies whether or not to + * automatically send a pong in response to a ping + * @param {Number} [options.backlog=511] The maximum length of the queue of + * pending connections + * @param {Boolean} [options.clientTracking=true] Specifies whether or not to + * track clients + * @param {Number} [options.closeTimeout=30000] Duration in milliseconds to + * wait for the closing handshake to finish after `websocket.close()` is + * called + * @param {Function} [options.handleProtocols] A hook to handle protocols + * @param {String} [options.host] The hostname where to bind the server + * @param {Number} [options.maxPayload=104857600] The maximum allowed message + * size + * @param {Boolean} [options.noServer=false] Enable no server mode + * @param {String} [options.path] Accept only connections matching this path + * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable + * permessage-deflate + * @param {Number} [options.port] The port where to bind the server + * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S + * server to use + * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or + * not to skip UTF-8 validation for text and close messages + * @param {Function} [options.verifyClient] A hook to reject connections + * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket` + * class to use. It must be the `WebSocket` class or class that extends it + * @param {Function} [callback] A listener for the `listening` event + */ + constructor(options, callback) { + super(); + options = { + allowSynchronousEvents: true, + autoPong: true, + maxPayload: 100 * 1024 * 1024, + skipUTF8Validation: false, + perMessageDeflate: false, + handleProtocols: null, + clientTracking: true, + closeTimeout: CLOSE_TIMEOUT, + verifyClient: null, + noServer: false, + backlog: null, + // use default (511 as implemented in net.js) + server: null, + host: null, + path: null, + port: null, + WebSocket: WebSocket2, + ...options + }; + if (options.port == null && !options.server && !options.noServer || options.port != null && (options.server || options.noServer) || options.server && options.noServer) { + throw new TypeError( + 'One and only one of the "port", "server", or "noServer" options must be specified' + ); + } + if (options.port != null) { + this._server = http.createServer((req, res) => { + const body = http.STATUS_CODES[426]; + res.writeHead(426, { + "Content-Length": body.length, + "Content-Type": "text/plain" + }); + res.end(body); + }); + this._server.listen( + options.port, + options.host, + options.backlog, + callback + ); + } else if (options.server) { + this._server = options.server; + } + if (this._server) { + const emitConnection = this.emit.bind(this, "connection"); + this._removeListeners = addListeners(this._server, { + listening: this.emit.bind(this, "listening"), + error: this.emit.bind(this, "error"), + upgrade: (req, socket, head) => { + this.handleUpgrade(req, socket, head, emitConnection); + } + }); + } + if (options.perMessageDeflate === true) options.perMessageDeflate = {}; + if (options.clientTracking) { + this.clients = /* @__PURE__ */ new Set(); + this._shouldEmitClose = false; + } + this.options = options; + this._state = RUNNING; + } + /** + * Returns the bound address, the address family name, and port of the server + * as reported by the operating system if listening on an IP socket. + * If the server is listening on a pipe or UNIX domain socket, the name is + * returned as a string. + * + * @return {(Object|String|null)} The address of the server + * @public + */ + address() { + if (this.options.noServer) { + throw new Error('The server is operating in "noServer" mode'); + } + if (!this._server) return null; + return this._server.address(); + } + /** + * Stop the server from accepting new connections and emit the `'close'` event + * when all existing connections are closed. + * + * @param {Function} [cb] A one-time listener for the `'close'` event + * @public + */ + close(cb) { + if (this._state === CLOSED) { + if (cb) { + this.once("close", () => { + cb(new Error("The server is not running")); + }); + } + process.nextTick(emitClose, this); + return; + } + if (cb) this.once("close", cb); + if (this._state === CLOSING) return; + this._state = CLOSING; + if (this.options.noServer || this.options.server) { + if (this._server) { + this._removeListeners(); + this._removeListeners = this._server = null; + } + if (this.clients) { + if (!this.clients.size) { + process.nextTick(emitClose, this); + } else { + this._shouldEmitClose = true; + } + } else { + process.nextTick(emitClose, this); + } + } else { + const server = this._server; + this._removeListeners(); + this._removeListeners = this._server = null; + server.close(() => { + emitClose(this); + }); + } + } + /** + * See if a given request should be handled by this server instance. + * + * @param {http.IncomingMessage} req Request object to inspect + * @return {Boolean} `true` if the request is valid, else `false` + * @public + */ + shouldHandle(req) { + if (this.options.path) { + const index2 = req.url.indexOf("?"); + const pathname = index2 !== -1 ? req.url.slice(0, index2) : req.url; + if (pathname !== this.options.path) return false; + } + return true; + } + /** + * Handle a HTTP Upgrade request. + * + * @param {http.IncomingMessage} req The request object + * @param {Duplex} socket The network socket between the server and client + * @param {Buffer} head The first packet of the upgraded stream + * @param {Function} cb Callback + * @public + */ + handleUpgrade(req, socket, head, cb) { + socket.on("error", socketOnError); + const key = req.headers["sec-websocket-key"]; + const upgrade = req.headers.upgrade; + const version3 = +req.headers["sec-websocket-version"]; + if (req.method !== "GET") { + const message2 = "Invalid HTTP method"; + abortHandshakeOrEmitwsClientError(this, req, socket, 405, message2); + return; + } + if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") { + const message2 = "Invalid Upgrade header"; + abortHandshakeOrEmitwsClientError(this, req, socket, 400, message2); + return; + } + if (key === void 0 || !keyRegex.test(key)) { + const message2 = "Missing or invalid Sec-WebSocket-Key header"; + abortHandshakeOrEmitwsClientError(this, req, socket, 400, message2); + return; + } + if (version3 !== 13 && version3 !== 8) { + const message2 = "Missing or invalid Sec-WebSocket-Version header"; + abortHandshakeOrEmitwsClientError(this, req, socket, 400, message2, { + "Sec-WebSocket-Version": "13, 8" + }); + return; + } + if (!this.shouldHandle(req)) { + abortHandshake(socket, 400); + return; + } + const secWebSocketProtocol = req.headers["sec-websocket-protocol"]; + let protocols = /* @__PURE__ */ new Set(); + if (secWebSocketProtocol !== void 0) { + try { + protocols = subprotocol2.parse(secWebSocketProtocol); + } catch (err) { + const message2 = "Invalid Sec-WebSocket-Protocol header"; + abortHandshakeOrEmitwsClientError(this, req, socket, 400, message2); + return; + } + } + const secWebSocketExtensions = req.headers["sec-websocket-extensions"]; + const extensions = {}; + if (this.options.perMessageDeflate && secWebSocketExtensions !== void 0) { + const perMessageDeflate = new PerMessageDeflate2({ + ...this.options.perMessageDeflate, + isServer: true, + maxPayload: this.options.maxPayload + }); + try { + const offers = extension2.parse(secWebSocketExtensions); + if (offers[PerMessageDeflate2.extensionName]) { + perMessageDeflate.accept(offers[PerMessageDeflate2.extensionName]); + extensions[PerMessageDeflate2.extensionName] = perMessageDeflate; + } + } catch (err) { + const message2 = "Invalid or unacceptable Sec-WebSocket-Extensions header"; + abortHandshakeOrEmitwsClientError(this, req, socket, 400, message2); + return; + } + } + if (this.options.verifyClient) { + const info2 = { + origin: req.headers[`${version3 === 8 ? "sec-websocket-origin" : "origin"}`], + secure: !!(req.socket.authorized || req.socket.encrypted), + req + }; + if (this.options.verifyClient.length === 2) { + this.options.verifyClient(info2, (verified, code, message2, headers) => { + if (!verified) { + return abortHandshake(socket, code || 401, message2, headers); + } + this.completeUpgrade( + extensions, + key, + protocols, + req, + socket, + head, + cb + ); + }); + return; + } + if (!this.options.verifyClient(info2)) return abortHandshake(socket, 401); + } + this.completeUpgrade(extensions, key, protocols, req, socket, head, cb); + } + /** + * Upgrade the connection to WebSocket. + * + * @param {Object} extensions The accepted extensions + * @param {String} key The value of the `Sec-WebSocket-Key` header + * @param {Set} protocols The subprotocols + * @param {http.IncomingMessage} req The request object + * @param {Duplex} socket The network socket between the server and client + * @param {Buffer} head The first packet of the upgraded stream + * @param {Function} cb Callback + * @throws {Error} If called more than once with the same socket + * @private + */ + completeUpgrade(extensions, key, protocols, req, socket, head, cb) { + if (!socket.readable || !socket.writable) return socket.destroy(); + if (socket[kWebSocket]) { + throw new Error( + "server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration" + ); + } + if (this._state > RUNNING) return abortHandshake(socket, 503); + const digest2 = createHash18("sha1").update(key + GUID).digest("base64"); + const headers = [ + "HTTP/1.1 101 Switching Protocols", + "Upgrade: websocket", + "Connection: Upgrade", + `Sec-WebSocket-Accept: ${digest2}` + ]; + const ws = new this.options.WebSocket(null, void 0, this.options); + if (protocols.size) { + const protocol = this.options.handleProtocols ? this.options.handleProtocols(protocols, req) : protocols.values().next().value; + if (protocol) { + headers.push(`Sec-WebSocket-Protocol: ${protocol}`); + ws._protocol = protocol; + } + } + if (extensions[PerMessageDeflate2.extensionName]) { + const params = extensions[PerMessageDeflate2.extensionName].params; + const value = extension2.format({ + [PerMessageDeflate2.extensionName]: [params] + }); + headers.push(`Sec-WebSocket-Extensions: ${value}`); + ws._extensions = extensions; + } + this.emit("headers", headers, req); + socket.write(headers.concat("\r\n").join("\r\n")); + socket.removeListener("error", socketOnError); + ws.setSocket(socket, head, { + allowSynchronousEvents: this.options.allowSynchronousEvents, + maxPayload: this.options.maxPayload, + skipUTF8Validation: this.options.skipUTF8Validation + }); + if (this.clients) { + this.clients.add(ws); + ws.on("close", () => { + this.clients.delete(ws); + if (this._shouldEmitClose && !this.clients.size) { + process.nextTick(emitClose, this); + } + }); + } + cb(ws, req); + } + }; + module.exports = WebSocketServer2; + function addListeners(server, map4) { + for (const event of Object.keys(map4)) server.on(event, map4[event]); + return function removeListeners() { + for (const event of Object.keys(map4)) { + server.removeListener(event, map4[event]); + } + }; + } + function emitClose(server) { + server._state = CLOSED; + server.emit("close"); + } + function socketOnError() { + this.destroy(); + } + function abortHandshake(socket, code, message2, headers) { + message2 = message2 || http.STATUS_CODES[code]; + headers = { + Connection: "close", + "Content-Type": "text/html", + "Content-Length": Buffer.byteLength(message2), + ...headers + }; + socket.once("finish", socket.destroy); + socket.end( + `HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r +` + Object.keys(headers).map((h5) => `${h5}: ${headers[h5]}`).join("\r\n") + "\r\n\r\n" + message2 + ); + } + function abortHandshakeOrEmitwsClientError(server, req, socket, code, message2, headers) { + if (server.listenerCount("wsClientError")) { + const err = new Error(message2); + Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError); + server.emit("wsClientError", err, socket, req); + } else { + abortHandshake(socket, code, message2, headers); + } + } + } +}); + +// node_modules/.pnpm/dotenv@17.4.2/node_modules/dotenv/lib/main.js +var require_main = __commonJS({ + "node_modules/.pnpm/dotenv@17.4.2/node_modules/dotenv/lib/main.js"(exports, module) { + var fs41 = __require("fs"); + var path53 = __require("path"); + var os24 = __require("os"); + var crypto6 = __require("crypto"); + var TIPS = [ + "\u25C8 encrypted .env [www.dotenvx.com]", + "\u25C8 secrets for agents [www.dotenvx.com]", + "\u2301 auth for agents [www.vestauth.com]", + "\u2318 custom filepath { path: '/custom/path/.env' }", + "\u2318 enable debugging { debug: true }", + "\u2318 override existing { override: true }", + "\u2318 suppress logs { quiet: true }", + "\u2318 multiple files { path: ['.env.local', '.env'] }" + ]; + function _getRandomTip() { + return TIPS[Math.floor(Math.random() * TIPS.length)]; + } + function parseBoolean3(value) { + if (typeof value === "string") { + return !["false", "0", "no", "off", ""].includes(value.toLowerCase()); + } + return Boolean(value); + } + function supportsAnsi() { + return process.stdout.isTTY; + } + function dim(text3) { + return supportsAnsi() ? `\x1B[2m${text3}\x1B[0m` : text3; + } + var LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg; + function parse5(src) { + const obj = {}; + let lines = src.toString(); + lines = lines.replace(/\r\n?/mg, "\n"); + let match; + while ((match = LINE.exec(lines)) != null) { + const key = match[1]; + let value = match[2] || ""; + value = value.trim(); + const maybeQuote = value[0]; + value = value.replace(/^(['"`])([\s\S]*)\1$/mg, "$2"); + if (maybeQuote === '"') { + value = value.replace(/\\n/g, "\n"); + value = value.replace(/\\r/g, "\r"); + } + obj[key] = value; + } + return obj; + } + function _parseVault(options) { + options = options || {}; + const vaultPath = _vaultPath(options); + options.path = vaultPath; + const result = DotenvModule.configDotenv(options); + if (!result.parsed) { + const err = new Error(`MISSING_DATA: Cannot parse ${vaultPath} for an unknown reason`); + err.code = "MISSING_DATA"; + throw err; + } + const keys = _dotenvKey(options).split(","); + const length = keys.length; + let decrypted; + for (let i5 = 0; i5 < length; i5++) { + try { + const key = keys[i5].trim(); + const attrs = _instructions(result, key); + decrypted = DotenvModule.decrypt(attrs.ciphertext, attrs.key); + break; + } catch (error50) { + if (i5 + 1 >= length) { + throw error50; + } + } + } + return DotenvModule.parse(decrypted); + } + function _warn(message2) { + console.error(`\u26A0 ${message2}`); + } + function _debug(message2) { + console.log(`\u2506 ${message2}`); + } + function _log(message2) { + console.log(`\u25C7 ${message2}`); + } + function _dotenvKey(options) { + if (options && options.DOTENV_KEY && options.DOTENV_KEY.length > 0) { + return options.DOTENV_KEY; + } + if (process.env.DOTENV_KEY && process.env.DOTENV_KEY.length > 0) { + return process.env.DOTENV_KEY; + } + return ""; + } + function _instructions(result, dotenvKey) { + let uri; + try { + uri = new URL(dotenvKey); + } catch (error50) { + if (error50.code === "ERR_INVALID_URL") { + const err = new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development"); + err.code = "INVALID_DOTENV_KEY"; + throw err; + } + throw error50; + } + const key = uri.password; + if (!key) { + const err = new Error("INVALID_DOTENV_KEY: Missing key part"); + err.code = "INVALID_DOTENV_KEY"; + throw err; + } + const environment = uri.searchParams.get("environment"); + if (!environment) { + const err = new Error("INVALID_DOTENV_KEY: Missing environment part"); + err.code = "INVALID_DOTENV_KEY"; + throw err; + } + const environmentKey = `DOTENV_VAULT_${environment.toUpperCase()}`; + const ciphertext = result.parsed[environmentKey]; + if (!ciphertext) { + const err = new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${environmentKey} in your .env.vault file.`); + err.code = "NOT_FOUND_DOTENV_ENVIRONMENT"; + throw err; + } + return { ciphertext, key }; + } + function _vaultPath(options) { + let possibleVaultPath = null; + if (options && options.path && options.path.length > 0) { + if (Array.isArray(options.path)) { + for (const filepath of options.path) { + if (fs41.existsSync(filepath)) { + possibleVaultPath = filepath.endsWith(".vault") ? filepath : `${filepath}.vault`; + } + } + } else { + possibleVaultPath = options.path.endsWith(".vault") ? options.path : `${options.path}.vault`; + } + } else { + possibleVaultPath = path53.resolve(process.cwd(), ".env.vault"); + } + if (fs41.existsSync(possibleVaultPath)) { + return possibleVaultPath; + } + return null; + } + function _resolveHome(envPath) { + return envPath[0] === "~" ? path53.join(os24.homedir(), envPath.slice(1)) : envPath; + } + function _configVault(options) { + const debug = parseBoolean3(process.env.DOTENV_CONFIG_DEBUG || options && options.debug); + const quiet = parseBoolean3(process.env.DOTENV_CONFIG_QUIET || options && options.quiet); + if (debug || !quiet) { + _log("loading env from encrypted .env.vault"); + } + const parsed = DotenvModule._parseVault(options); + let processEnv = process.env; + if (options && options.processEnv != null) { + processEnv = options.processEnv; + } + DotenvModule.populate(processEnv, parsed, options); + return { parsed }; + } + function configDotenv(options) { + const dotenvPath = path53.resolve(process.cwd(), ".env"); + let encoding = "utf8"; + let processEnv = process.env; + if (options && options.processEnv != null) { + processEnv = options.processEnv; + } + let debug = parseBoolean3(processEnv.DOTENV_CONFIG_DEBUG || options && options.debug); + let quiet = parseBoolean3(processEnv.DOTENV_CONFIG_QUIET || options && options.quiet); + if (options && options.encoding) { + encoding = options.encoding; + } else { + if (debug) { + _debug("no encoding is specified (UTF-8 is used by default)"); + } + } + let optionPaths = [dotenvPath]; + if (options && options.path) { + if (!Array.isArray(options.path)) { + optionPaths = [_resolveHome(options.path)]; + } else { + optionPaths = []; + for (const filepath of options.path) { + optionPaths.push(_resolveHome(filepath)); + } + } + } + let lastError; + const parsedAll = {}; + for (const path54 of optionPaths) { + try { + const parsed = DotenvModule.parse(fs41.readFileSync(path54, { encoding })); + DotenvModule.populate(parsedAll, parsed, options); + } catch (e5) { + if (debug) { + _debug(`failed to load ${path54} ${e5.message}`); + } + lastError = e5; + } + } + const populated = DotenvModule.populate(processEnv, parsedAll, options); + debug = parseBoolean3(processEnv.DOTENV_CONFIG_DEBUG || debug); + quiet = parseBoolean3(processEnv.DOTENV_CONFIG_QUIET || quiet); + if (debug || !quiet) { + const keysCount = Object.keys(populated).length; + const shortPaths = []; + for (const filePath of optionPaths) { + try { + const relative3 = path53.relative(process.cwd(), filePath); + shortPaths.push(relative3); + } catch (e5) { + if (debug) { + _debug(`failed to load ${filePath} ${e5.message}`); + } + lastError = e5; + } + } + _log(`injected env (${keysCount}) from ${shortPaths.join(",")} ${dim(`// tip: ${_getRandomTip()}`)}`); + } + if (lastError) { + return { parsed: parsedAll, error: lastError }; + } else { + return { parsed: parsedAll }; + } + } + function config3(options) { + if (_dotenvKey(options).length === 0) { + return DotenvModule.configDotenv(options); + } + const vaultPath = _vaultPath(options); + if (!vaultPath) { + _warn(`you set DOTENV_KEY but you are missing a .env.vault file at ${vaultPath}`); + return DotenvModule.configDotenv(options); + } + return DotenvModule._configVault(options); + } + function decrypt3(encrypted, keyStr) { + const key = Buffer.from(keyStr.slice(-64), "hex"); + let ciphertext = Buffer.from(encrypted, "base64"); + const nonce = ciphertext.subarray(0, 12); + const authTag = ciphertext.subarray(-16); + ciphertext = ciphertext.subarray(12, -16); + try { + const aesgcm = crypto6.createDecipheriv("aes-256-gcm", key, nonce); + aesgcm.setAuthTag(authTag); + return `${aesgcm.update(ciphertext)}${aesgcm.final()}`; + } catch (error50) { + const isRange = error50 instanceof RangeError; + const invalidKeyLength = error50.message === "Invalid key length"; + const decryptionFailed = error50.message === "Unsupported state or unable to authenticate data"; + if (isRange || invalidKeyLength) { + const err = new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)"); + err.code = "INVALID_DOTENV_KEY"; + throw err; + } else if (decryptionFailed) { + const err = new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY"); + err.code = "DECRYPTION_FAILED"; + throw err; + } else { + throw error50; + } + } + } + function populate(processEnv, parsed, options = {}) { + const debug = Boolean(options && options.debug); + const override = Boolean(options && options.override); + const populated = {}; + if (typeof parsed !== "object") { + const err = new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate"); + err.code = "OBJECT_REQUIRED"; + throw err; + } + for (const key of Object.keys(parsed)) { + if (Object.prototype.hasOwnProperty.call(processEnv, key)) { + if (override === true) { + processEnv[key] = parsed[key]; + populated[key] = parsed[key]; + } + if (debug) { + if (override === true) { + _debug(`"${key}" is already defined and WAS overwritten`); + } else { + _debug(`"${key}" is already defined and was NOT overwritten`); + } + } + } else { + processEnv[key] = parsed[key]; + populated[key] = parsed[key]; + } + } + return populated; + } + var DotenvModule = { + configDotenv, + _configVault, + _parseVault, + config: config3, + decrypt: decrypt3, + parse: parse5, + populate + }; + module.exports.configDotenv = DotenvModule.configDotenv; + module.exports._configVault = DotenvModule._configVault; + module.exports._parseVault = DotenvModule._parseVault; + module.exports.config = DotenvModule.config; + module.exports.decrypt = DotenvModule.decrypt; + module.exports.parse = DotenvModule.parse; + module.exports.populate = DotenvModule.populate; + module.exports = DotenvModule; + } +}); + +// node_modules/.pnpm/@smithy+types@4.14.0/node_modules/@smithy/types/dist-cjs/index.js +var require_dist_cjs = __commonJS({ + "node_modules/.pnpm/@smithy+types@4.14.0/node_modules/@smithy/types/dist-cjs/index.js"(exports) { + "use strict"; + exports.HttpAuthLocation = void 0; + (function(HttpAuthLocation) { + HttpAuthLocation["HEADER"] = "header"; + HttpAuthLocation["QUERY"] = "query"; + })(exports.HttpAuthLocation || (exports.HttpAuthLocation = {})); + exports.HttpApiKeyAuthLocation = void 0; + (function(HttpApiKeyAuthLocation2) { + HttpApiKeyAuthLocation2["HEADER"] = "header"; + HttpApiKeyAuthLocation2["QUERY"] = "query"; + })(exports.HttpApiKeyAuthLocation || (exports.HttpApiKeyAuthLocation = {})); + exports.EndpointURLScheme = void 0; + (function(EndpointURLScheme) { + EndpointURLScheme["HTTP"] = "http"; + EndpointURLScheme["HTTPS"] = "https"; + })(exports.EndpointURLScheme || (exports.EndpointURLScheme = {})); + exports.AlgorithmId = void 0; + (function(AlgorithmId) { + AlgorithmId["MD5"] = "md5"; + AlgorithmId["CRC32"] = "crc32"; + AlgorithmId["CRC32C"] = "crc32c"; + AlgorithmId["SHA1"] = "sha1"; + AlgorithmId["SHA256"] = "sha256"; + })(exports.AlgorithmId || (exports.AlgorithmId = {})); + var getChecksumConfiguration = (runtimeConfig) => { + const checksumAlgorithms = []; + if (runtimeConfig.sha256 !== void 0) { + checksumAlgorithms.push({ + algorithmId: () => exports.AlgorithmId.SHA256, + checksumConstructor: () => runtimeConfig.sha256 + }); + } + if (runtimeConfig.md5 != void 0) { + checksumAlgorithms.push({ + algorithmId: () => exports.AlgorithmId.MD5, + checksumConstructor: () => runtimeConfig.md5 + }); + } + return { + addChecksumAlgorithm(algo) { + checksumAlgorithms.push(algo); + }, + checksumAlgorithms() { + return checksumAlgorithms; + } + }; + }; + var resolveChecksumRuntimeConfig = (clientConfig) => { + const runtimeConfig = {}; + clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { + runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); + }); + return runtimeConfig; + }; + var getDefaultClientConfiguration = (runtimeConfig) => { + return getChecksumConfiguration(runtimeConfig); + }; + var resolveDefaultRuntimeConfig5 = (config3) => { + return resolveChecksumRuntimeConfig(config3); + }; + exports.FieldPosition = void 0; + (function(FieldPosition) { + FieldPosition[FieldPosition["HEADER"] = 0] = "HEADER"; + FieldPosition[FieldPosition["TRAILER"] = 1] = "TRAILER"; + })(exports.FieldPosition || (exports.FieldPosition = {})); + var SMITHY_CONTEXT_KEY2 = "__smithy_context"; + exports.IniSectionType = void 0; + (function(IniSectionType) { + IniSectionType["PROFILE"] = "profile"; + IniSectionType["SSO_SESSION"] = "sso-session"; + IniSectionType["SERVICES"] = "services"; + })(exports.IniSectionType || (exports.IniSectionType = {})); + exports.RequestHandlerProtocol = void 0; + (function(RequestHandlerProtocol) { + RequestHandlerProtocol["HTTP_0_9"] = "http/0.9"; + RequestHandlerProtocol["HTTP_1_0"] = "http/1.0"; + RequestHandlerProtocol["TDS_8_0"] = "tds/8.0"; + })(exports.RequestHandlerProtocol || (exports.RequestHandlerProtocol = {})); + exports.SMITHY_CONTEXT_KEY = SMITHY_CONTEXT_KEY2; + exports.getDefaultClientConfiguration = getDefaultClientConfiguration; + exports.resolveDefaultRuntimeConfig = resolveDefaultRuntimeConfig5; + } +}); + +// node_modules/.pnpm/@smithy+protocol-http@5.3.13/node_modules/@smithy/protocol-http/dist-cjs/index.js +var require_dist_cjs2 = __commonJS({ + "node_modules/.pnpm/@smithy+protocol-http@5.3.13/node_modules/@smithy/protocol-http/dist-cjs/index.js"(exports) { + "use strict"; + var types2 = require_dist_cjs(); + var getHttpHandlerExtensionConfiguration5 = (runtimeConfig) => { + return { + setHttpHandler(handler) { + runtimeConfig.httpHandler = handler; + }, + httpHandler() { + return runtimeConfig.httpHandler; + }, + updateHttpClientConfig(key, value) { + runtimeConfig.httpHandler?.updateHttpClientConfig(key, value); + }, + httpHandlerConfigs() { + return runtimeConfig.httpHandler.httpHandlerConfigs(); + } + }; + }; + var resolveHttpHandlerRuntimeConfig5 = (httpHandlerExtensionConfiguration) => { + return { + httpHandler: httpHandlerExtensionConfiguration.httpHandler() + }; + }; + var Field = class { + name; + kind; + values; + constructor({ name, kind = types2.FieldPosition.HEADER, values: values2 = [] }) { + this.name = name; + this.kind = kind; + this.values = values2; + } + add(value) { + this.values.push(value); + } + set(values2) { + this.values = values2; + } + remove(value) { + this.values = this.values.filter((v5) => v5 !== value); + } + toString() { + return this.values.map((v5) => v5.includes(",") || v5.includes(" ") ? `"${v5}"` : v5).join(", "); + } + get() { + return this.values; + } + }; + var Fields = class { + entries = {}; + encoding; + constructor({ fields = [], encoding = "utf-8" }) { + fields.forEach(this.setField.bind(this)); + this.encoding = encoding; + } + setField(field) { + this.entries[field.name.toLowerCase()] = field; + } + getField(name) { + return this.entries[name.toLowerCase()]; + } + removeField(name) { + delete this.entries[name.toLowerCase()]; + } + getByType(kind) { + return Object.values(this.entries).filter((field) => field.kind === kind); + } + }; + var HttpRequest10 = class _HttpRequest { + method; + protocol; + hostname; + port; + path; + query; + headers; + username; + password; + fragment; + body; + constructor(options) { + this.method = options.method || "GET"; + this.hostname = options.hostname || "localhost"; + this.port = options.port; + this.query = options.query || {}; + this.headers = options.headers || {}; + this.body = options.body; + this.protocol = options.protocol ? options.protocol.slice(-1) !== ":" ? `${options.protocol}:` : options.protocol : "https:"; + this.path = options.path ? options.path.charAt(0) !== "/" ? `/${options.path}` : options.path : "/"; + this.username = options.username; + this.password = options.password; + this.fragment = options.fragment; + } + static clone(request) { + const cloned = new _HttpRequest({ + ...request, + headers: { ...request.headers } + }); + if (cloned.query) { + cloned.query = cloneQuery(cloned.query); + } + return cloned; + } + static isInstance(request) { + if (!request) { + return false; + } + const req = request; + return "method" in req && "protocol" in req && "hostname" in req && "path" in req && typeof req["query"] === "object" && typeof req["headers"] === "object"; + } + clone() { + return _HttpRequest.clone(this); + } + }; + function cloneQuery(query) { + return Object.keys(query).reduce((carry, paramName) => { + const param = query[paramName]; + return { + ...carry, + [paramName]: Array.isArray(param) ? [...param] : param + }; + }, {}); + } + var HttpResponse4 = class { + statusCode; + reason; + headers; + body; + constructor(options) { + this.statusCode = options.statusCode; + this.reason = options.reason; + this.headers = options.headers || {}; + this.body = options.body; + } + static isInstance(response) { + if (!response) + return false; + const resp = response; + return typeof resp.statusCode === "number" && typeof resp.headers === "object"; + } + }; + function isValidHostname(hostname3) { + const hostPattern = /^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/; + return hostPattern.test(hostname3); + } + exports.Field = Field; + exports.Fields = Fields; + exports.HttpRequest = HttpRequest10; + exports.HttpResponse = HttpResponse4; + exports.getHttpHandlerExtensionConfiguration = getHttpHandlerExtensionConfiguration5; + exports.isValidHostname = isValidHostname; + exports.resolveHttpHandlerRuntimeConfig = resolveHttpHandlerRuntimeConfig5; + } +}); + +// node_modules/.pnpm/@aws-sdk+middleware-expect-continue@3.972.9/node_modules/@aws-sdk/middleware-expect-continue/dist-cjs/index.js +var require_dist_cjs3 = __commonJS({ + "node_modules/.pnpm/@aws-sdk+middleware-expect-continue@3.972.9/node_modules/@aws-sdk/middleware-expect-continue/dist-cjs/index.js"(exports) { + "use strict"; + var protocolHttp = require_dist_cjs2(); + function addExpectContinueMiddleware(options) { + return (next) => async (args) => { + const { request } = args; + if (options.expectContinueHeader !== false && protocolHttp.HttpRequest.isInstance(request) && request.body && options.runtime === "node" && options.requestHandler?.constructor?.name !== "FetchHttpHandler") { + let sendHeader = true; + if (typeof options.expectContinueHeader === "number") { + try { + const bodyLength = Number(request.headers?.["content-length"]) ?? options.bodyLengthChecker?.(request.body) ?? Infinity; + sendHeader = bodyLength >= options.expectContinueHeader; + } catch (e5) { + } + } else { + sendHeader = !!options.expectContinueHeader; + } + if (sendHeader) { + request.headers.Expect = "100-continue"; + } + } + return next({ + ...args, + request + }); + }; + } + var addExpectContinueMiddlewareOptions = { + step: "build", + tags: ["SET_EXPECT_HEADER", "EXPECT_HEADER"], + name: "addExpectContinueMiddleware", + override: true + }; + var getAddExpectContinuePlugin = (options) => ({ + applyToStack: (clientStack) => { + clientStack.add(addExpectContinueMiddleware(options), addExpectContinueMiddlewareOptions); + } + }); + exports.addExpectContinueMiddleware = addExpectContinueMiddleware; + exports.addExpectContinueMiddlewareOptions = addExpectContinueMiddlewareOptions; + exports.getAddExpectContinuePlugin = getAddExpectContinuePlugin; + } +}); + +// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/client/emitWarningIfUnsupportedVersion.js +var state, emitWarningIfUnsupportedVersion; +var init_emitWarningIfUnsupportedVersion = __esm({ + "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/client/emitWarningIfUnsupportedVersion.js"() { + state = { + warningEmitted: false + }; + emitWarningIfUnsupportedVersion = (version3) => { + if (version3 && !state.warningEmitted && parseInt(version3.substring(1, version3.indexOf("."))) < 20) { + state.warningEmitted = true; + process.emitWarning(`NodeDeprecationWarning: The AWS SDK for JavaScript (v3) will +no longer support Node.js ${version3} in January 2026. + +To continue receiving updates to AWS services, bug fixes, and security +updates please upgrade to a supported Node.js LTS version. + +More information can be found at: https://a.co/c895JFp`); + } + }; + } +}); + +// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/client/longPollMiddleware.js +var longPollMiddleware, longPollMiddlewareOptions, getLongPollPlugin; +var init_longPollMiddleware = __esm({ + "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/client/longPollMiddleware.js"() { + longPollMiddleware = () => (next, context) => async (args) => { + context.__retryLongPoll = true; + return next(args); + }; + longPollMiddlewareOptions = { + name: "longPollMiddleware", + tags: ["RETRY"], + step: "initialize", + override: true + }; + getLongPollPlugin = (options) => ({ + applyToStack: (clientStack) => { + clientStack.add(longPollMiddleware(), longPollMiddlewareOptions); + } + }); + } +}); + +// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/client/setCredentialFeature.js +function setCredentialFeature(credentials, feature, value) { + if (!credentials.$source) { + credentials.$source = {}; + } + credentials.$source[feature] = value; + return credentials; +} +var init_setCredentialFeature = __esm({ + "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/client/setCredentialFeature.js"() { + } +}); + +// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/client/setFeature.js +function setFeature(context, feature, value) { + if (!context.__aws_sdk_context) { + context.__aws_sdk_context = { + features: {} + }; + } else if (!context.__aws_sdk_context.features) { + context.__aws_sdk_context.features = {}; + } + context.__aws_sdk_context.features[feature] = value; +} +var init_setFeature = __esm({ + "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/client/setFeature.js"() { + } +}); + +// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/client/setTokenFeature.js +function setTokenFeature(token, feature, value) { + if (!token.$source) { + token.$source = {}; + } + token.$source[feature] = value; + return token; +} +var init_setTokenFeature = __esm({ + "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/client/setTokenFeature.js"() { + } +}); + +// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/client/index.js +var client_exports = {}; +__export(client_exports, { + emitWarningIfUnsupportedVersion: () => emitWarningIfUnsupportedVersion, + getLongPollPlugin: () => getLongPollPlugin, + setCredentialFeature: () => setCredentialFeature, + setFeature: () => setFeature, + setTokenFeature: () => setTokenFeature, + state: () => state +}); +var init_client2 = __esm({ + "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/client/index.js"() { + init_emitWarningIfUnsupportedVersion(); + init_longPollMiddleware(); + init_setCredentialFeature(); + init_setFeature(); + init_setTokenFeature(); + } +}); + +// node_modules/.pnpm/@smithy+is-array-buffer@4.2.2/node_modules/@smithy/is-array-buffer/dist-cjs/index.js +var require_dist_cjs4 = __commonJS({ + "node_modules/.pnpm/@smithy+is-array-buffer@4.2.2/node_modules/@smithy/is-array-buffer/dist-cjs/index.js"(exports) { + "use strict"; + var isArrayBuffer = (arg) => typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer || Object.prototype.toString.call(arg) === "[object ArrayBuffer]"; + exports.isArrayBuffer = isArrayBuffer; + } +}); + +// node_modules/.pnpm/@smithy+util-buffer-from@4.2.2/node_modules/@smithy/util-buffer-from/dist-cjs/index.js +var require_dist_cjs5 = __commonJS({ + "node_modules/.pnpm/@smithy+util-buffer-from@4.2.2/node_modules/@smithy/util-buffer-from/dist-cjs/index.js"(exports) { + "use strict"; + var isArrayBuffer = require_dist_cjs4(); + var buffer2 = __require("buffer"); + var fromArrayBuffer = (input, offset = 0, length = input.byteLength - offset) => { + if (!isArrayBuffer.isArrayBuffer(input)) { + throw new TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof input} (${input})`); + } + return buffer2.Buffer.from(input, offset, length); + }; + var fromString = (input, encoding) => { + if (typeof input !== "string") { + throw new TypeError(`The "input" argument must be of type string. Received type ${typeof input} (${input})`); + } + return encoding ? buffer2.Buffer.from(input, encoding) : buffer2.Buffer.from(input); + }; + exports.fromArrayBuffer = fromArrayBuffer; + exports.fromString = fromString; + } +}); + +// node_modules/.pnpm/@smithy+util-base64@4.3.2/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js +var require_fromBase64 = __commonJS({ + "node_modules/.pnpm/@smithy+util-base64@4.3.2/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.fromBase64 = void 0; + var util_buffer_from_1 = require_dist_cjs5(); + var BASE64_REGEX = /^[A-Za-z0-9+/]*={0,2}$/; + var fromBase649 = (input) => { + if (input.length * 3 % 4 !== 0) { + throw new TypeError(`Incorrect padding on base64 string.`); + } + if (!BASE64_REGEX.exec(input)) { + throw new TypeError(`Invalid base64 string.`); + } + const buffer2 = (0, util_buffer_from_1.fromString)(input, "base64"); + return new Uint8Array(buffer2.buffer, buffer2.byteOffset, buffer2.byteLength); + }; + exports.fromBase64 = fromBase649; + } +}); + +// node_modules/.pnpm/@smithy+util-utf8@4.2.2/node_modules/@smithy/util-utf8/dist-cjs/index.js +var require_dist_cjs6 = __commonJS({ + "node_modules/.pnpm/@smithy+util-utf8@4.2.2/node_modules/@smithy/util-utf8/dist-cjs/index.js"(exports) { + "use strict"; + var utilBufferFrom = require_dist_cjs5(); + var fromUtf88 = (input) => { + const buf = utilBufferFrom.fromString(input, "utf8"); + return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength / Uint8Array.BYTES_PER_ELEMENT); + }; + var toUint8Array2 = (data2) => { + if (typeof data2 === "string") { + return fromUtf88(data2); + } + if (ArrayBuffer.isView(data2)) { + return new Uint8Array(data2.buffer, data2.byteOffset, data2.byteLength / Uint8Array.BYTES_PER_ELEMENT); + } + return new Uint8Array(data2); + }; + var toUtf811 = (input) => { + if (typeof input === "string") { + return input; + } + if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") { + throw new Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array."); + } + return utilBufferFrom.fromArrayBuffer(input.buffer, input.byteOffset, input.byteLength).toString("utf8"); + }; + exports.fromUtf8 = fromUtf88; + exports.toUint8Array = toUint8Array2; + exports.toUtf8 = toUtf811; + } +}); + +// node_modules/.pnpm/@smithy+util-base64@4.3.2/node_modules/@smithy/util-base64/dist-cjs/toBase64.js +var require_toBase64 = __commonJS({ + "node_modules/.pnpm/@smithy+util-base64@4.3.2/node_modules/@smithy/util-base64/dist-cjs/toBase64.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.toBase64 = void 0; + var util_buffer_from_1 = require_dist_cjs5(); + var util_utf8_1 = require_dist_cjs6(); + var toBase649 = (_input) => { + let input; + if (typeof _input === "string") { + input = (0, util_utf8_1.fromUtf8)(_input); + } else { + input = _input; + } + if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") { + throw new Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array."); + } + return (0, util_buffer_from_1.fromArrayBuffer)(input.buffer, input.byteOffset, input.byteLength).toString("base64"); + }; + exports.toBase64 = toBase649; + } +}); + +// node_modules/.pnpm/@smithy+util-base64@4.3.2/node_modules/@smithy/util-base64/dist-cjs/index.js +var require_dist_cjs7 = __commonJS({ + "node_modules/.pnpm/@smithy+util-base64@4.3.2/node_modules/@smithy/util-base64/dist-cjs/index.js"(exports) { + "use strict"; + var fromBase649 = require_fromBase64(); + var toBase649 = require_toBase64(); + Object.prototype.hasOwnProperty.call(fromBase649, "__proto__") && !Object.prototype.hasOwnProperty.call(exports, "__proto__") && Object.defineProperty(exports, "__proto__", { + enumerable: true, + value: fromBase649["__proto__"] + }); + Object.keys(fromBase649).forEach(function(k5) { + if (k5 !== "default" && !Object.prototype.hasOwnProperty.call(exports, k5)) exports[k5] = fromBase649[k5]; + }); + Object.prototype.hasOwnProperty.call(toBase649, "__proto__") && !Object.prototype.hasOwnProperty.call(exports, "__proto__") && Object.defineProperty(exports, "__proto__", { + enumerable: true, + value: toBase649["__proto__"] + }); + Object.keys(toBase649).forEach(function(k5) { + if (k5 !== "default" && !Object.prototype.hasOwnProperty.call(exports, k5)) exports[k5] = toBase649[k5]; + }); + } +}); + +// node_modules/.pnpm/@smithy+util-stream@4.5.22/node_modules/@smithy/util-stream/dist-cjs/checksum/ChecksumStream.js +var require_ChecksumStream = __commonJS({ + "node_modules/.pnpm/@smithy+util-stream@4.5.22/node_modules/@smithy/util-stream/dist-cjs/checksum/ChecksumStream.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ChecksumStream = void 0; + var util_base64_1 = require_dist_cjs7(); + var stream_1 = __require("stream"); + var ChecksumStream = class extends stream_1.Duplex { + expectedChecksum; + checksumSourceLocation; + checksum; + source; + base64Encoder; + pendingCallback = null; + constructor({ expectedChecksum, checksum, source, checksumSourceLocation, base64Encoder }) { + super(); + if (typeof source.pipe === "function") { + this.source = source; + } else { + throw new Error(`@smithy/util-stream: unsupported source type ${source?.constructor?.name ?? source} in ChecksumStream.`); + } + this.base64Encoder = base64Encoder ?? util_base64_1.toBase64; + this.expectedChecksum = expectedChecksum; + this.checksum = checksum; + this.checksumSourceLocation = checksumSourceLocation; + this.source.pipe(this); + } + _read(size2) { + if (this.pendingCallback) { + const callback = this.pendingCallback; + this.pendingCallback = null; + callback(); + } + } + _write(chunk, encoding, callback) { + try { + this.checksum.update(chunk); + const canPushMore = this.push(chunk); + if (!canPushMore) { + this.pendingCallback = callback; + return; + } + } catch (e5) { + return callback(e5); + } + return callback(); + } + async _final(callback) { + try { + const digest2 = await this.checksum.digest(); + const received = this.base64Encoder(digest2); + if (this.expectedChecksum !== received) { + return callback(new Error(`Checksum mismatch: expected "${this.expectedChecksum}" but received "${received}" in response header "${this.checksumSourceLocation}".`)); + } + } catch (e5) { + return callback(e5); + } + this.push(null); + return callback(); + } + }; + exports.ChecksumStream = ChecksumStream; + } +}); + +// node_modules/.pnpm/@smithy+util-stream@4.5.22/node_modules/@smithy/util-stream/dist-cjs/stream-type-check.js +var require_stream_type_check = __commonJS({ + "node_modules/.pnpm/@smithy+util-stream@4.5.22/node_modules/@smithy/util-stream/dist-cjs/stream-type-check.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.isBlob = exports.isReadableStream = void 0; + var isReadableStream = (stream) => typeof ReadableStream === "function" && (stream?.constructor?.name === ReadableStream.name || stream instanceof ReadableStream); + exports.isReadableStream = isReadableStream; + var isBlob = (blob) => { + return typeof Blob === "function" && (blob?.constructor?.name === Blob.name || blob instanceof Blob); + }; + exports.isBlob = isBlob; + } +}); + +// node_modules/.pnpm/@smithy+util-stream@4.5.22/node_modules/@smithy/util-stream/dist-cjs/checksum/ChecksumStream.browser.js +var require_ChecksumStream_browser = __commonJS({ + "node_modules/.pnpm/@smithy+util-stream@4.5.22/node_modules/@smithy/util-stream/dist-cjs/checksum/ChecksumStream.browser.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ChecksumStream = void 0; + var ReadableStreamRef = typeof ReadableStream === "function" ? ReadableStream : function() { + }; + var ChecksumStream = class extends ReadableStreamRef { + }; + exports.ChecksumStream = ChecksumStream; + } +}); + +// node_modules/.pnpm/@smithy+util-stream@4.5.22/node_modules/@smithy/util-stream/dist-cjs/checksum/createChecksumStream.browser.js +var require_createChecksumStream_browser = __commonJS({ + "node_modules/.pnpm/@smithy+util-stream@4.5.22/node_modules/@smithy/util-stream/dist-cjs/checksum/createChecksumStream.browser.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.createChecksumStream = void 0; + var util_base64_1 = require_dist_cjs7(); + var stream_type_check_1 = require_stream_type_check(); + var ChecksumStream_browser_1 = require_ChecksumStream_browser(); + var createChecksumStream = ({ expectedChecksum, checksum, source, checksumSourceLocation, base64Encoder }) => { + if (!(0, stream_type_check_1.isReadableStream)(source)) { + throw new Error(`@smithy/util-stream: unsupported source type ${source?.constructor?.name ?? source} in ChecksumStream.`); + } + const encoder3 = base64Encoder ?? util_base64_1.toBase64; + if (typeof TransformStream !== "function") { + throw new Error("@smithy/util-stream: unable to instantiate ChecksumStream because API unavailable: ReadableStream/TransformStream."); + } + const transform3 = new TransformStream({ + start() { + }, + async transform(chunk, controller) { + checksum.update(chunk); + controller.enqueue(chunk); + }, + async flush(controller) { + const digest2 = await checksum.digest(); + const received = encoder3(digest2); + if (expectedChecksum !== received) { + const error50 = new Error(`Checksum mismatch: expected "${expectedChecksum}" but received "${received}" in response header "${checksumSourceLocation}".`); + controller.error(error50); + } else { + controller.terminate(); + } + } + }); + source.pipeThrough(transform3); + const readable = transform3.readable; + Object.setPrototypeOf(readable, ChecksumStream_browser_1.ChecksumStream.prototype); + return readable; + }; + exports.createChecksumStream = createChecksumStream; + } +}); + +// node_modules/.pnpm/@smithy+util-stream@4.5.22/node_modules/@smithy/util-stream/dist-cjs/checksum/createChecksumStream.js +var require_createChecksumStream = __commonJS({ + "node_modules/.pnpm/@smithy+util-stream@4.5.22/node_modules/@smithy/util-stream/dist-cjs/checksum/createChecksumStream.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.createChecksumStream = createChecksumStream; + var stream_type_check_1 = require_stream_type_check(); + var ChecksumStream_1 = require_ChecksumStream(); + var createChecksumStream_browser_1 = require_createChecksumStream_browser(); + function createChecksumStream(init2) { + if (typeof ReadableStream === "function" && (0, stream_type_check_1.isReadableStream)(init2.source)) { + return (0, createChecksumStream_browser_1.createChecksumStream)(init2); + } + return new ChecksumStream_1.ChecksumStream(init2); + } + } +}); + +// node_modules/.pnpm/@smithy+util-stream@4.5.22/node_modules/@smithy/util-stream/dist-cjs/ByteArrayCollector.js +var require_ByteArrayCollector = __commonJS({ + "node_modules/.pnpm/@smithy+util-stream@4.5.22/node_modules/@smithy/util-stream/dist-cjs/ByteArrayCollector.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ByteArrayCollector = void 0; + var ByteArrayCollector = class { + allocByteArray; + byteLength = 0; + byteArrays = []; + constructor(allocByteArray) { + this.allocByteArray = allocByteArray; + } + push(byteArray) { + this.byteArrays.push(byteArray); + this.byteLength += byteArray.byteLength; + } + flush() { + if (this.byteArrays.length === 1) { + const bytes = this.byteArrays[0]; + this.reset(); + return bytes; + } + const aggregation = this.allocByteArray(this.byteLength); + let cursor2 = 0; + for (let i5 = 0; i5 < this.byteArrays.length; ++i5) { + const bytes = this.byteArrays[i5]; + aggregation.set(bytes, cursor2); + cursor2 += bytes.byteLength; + } + this.reset(); + return aggregation; + } + reset() { + this.byteArrays = []; + this.byteLength = 0; + } + }; + exports.ByteArrayCollector = ByteArrayCollector; + } +}); + +// node_modules/.pnpm/@smithy+util-stream@4.5.22/node_modules/@smithy/util-stream/dist-cjs/createBufferedReadableStream.js +var require_createBufferedReadableStream = __commonJS({ + "node_modules/.pnpm/@smithy+util-stream@4.5.22/node_modules/@smithy/util-stream/dist-cjs/createBufferedReadableStream.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.createBufferedReadable = void 0; + exports.createBufferedReadableStream = createBufferedReadableStream; + exports.merge = merge2; + exports.flush = flush; + exports.sizeOf = sizeOf; + exports.modeOf = modeOf; + var ByteArrayCollector_1 = require_ByteArrayCollector(); + function createBufferedReadableStream(upstream, size2, logger4) { + const reader = upstream.getReader(); + let streamBufferingLoggedWarning = false; + let bytesSeen = 0; + const buffers = ["", new ByteArrayCollector_1.ByteArrayCollector((size3) => new Uint8Array(size3))]; + let mode = -1; + const pull = async (controller) => { + const { value, done } = await reader.read(); + const chunk = value; + if (done) { + if (mode !== -1) { + const remainder = flush(buffers, mode); + if (sizeOf(remainder) > 0) { + controller.enqueue(remainder); + } + } + controller.close(); + } else { + const chunkMode = modeOf(chunk, false); + if (mode !== chunkMode) { + if (mode >= 0) { + controller.enqueue(flush(buffers, mode)); + } + mode = chunkMode; + } + if (mode === -1) { + controller.enqueue(chunk); + return; + } + const chunkSize = sizeOf(chunk); + bytesSeen += chunkSize; + const bufferSize = sizeOf(buffers[mode]); + if (chunkSize >= size2 && bufferSize === 0) { + controller.enqueue(chunk); + } else { + const newSize = merge2(buffers, mode, chunk); + if (!streamBufferingLoggedWarning && bytesSeen > size2 * 2) { + streamBufferingLoggedWarning = true; + logger4?.warn(`@smithy/util-stream - stream chunk size ${chunkSize} is below threshold of ${size2}, automatically buffering.`); + } + if (newSize >= size2) { + controller.enqueue(flush(buffers, mode)); + } else { + await pull(controller); + } + } + } + }; + return new ReadableStream({ + pull + }); + } + exports.createBufferedReadable = createBufferedReadableStream; + function merge2(buffers, mode, chunk) { + switch (mode) { + case 0: + buffers[0] += chunk; + return sizeOf(buffers[0]); + case 1: + case 2: + buffers[mode].push(chunk); + return sizeOf(buffers[mode]); + } + } + function flush(buffers, mode) { + switch (mode) { + case 0: + const s5 = buffers[0]; + buffers[0] = ""; + return s5; + case 1: + case 2: + return buffers[mode].flush(); + } + throw new Error(`@smithy/util-stream - invalid index ${mode} given to flush()`); + } + function sizeOf(chunk) { + return chunk?.byteLength ?? chunk?.length ?? 0; + } + function modeOf(chunk, allowBuffer = true) { + if (allowBuffer && typeof Buffer !== "undefined" && chunk instanceof Buffer) { + return 2; + } + if (chunk instanceof Uint8Array) { + return 1; + } + if (typeof chunk === "string") { + return 0; + } + return -1; + } + } +}); + +// node_modules/.pnpm/@smithy+util-stream@4.5.22/node_modules/@smithy/util-stream/dist-cjs/createBufferedReadable.js +var require_createBufferedReadable = __commonJS({ + "node_modules/.pnpm/@smithy+util-stream@4.5.22/node_modules/@smithy/util-stream/dist-cjs/createBufferedReadable.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.createBufferedReadable = createBufferedReadable; + var node_stream_1 = __require("node:stream"); + var ByteArrayCollector_1 = require_ByteArrayCollector(); + var createBufferedReadableStream_1 = require_createBufferedReadableStream(); + var stream_type_check_1 = require_stream_type_check(); + function createBufferedReadable(upstream, size2, logger4) { + if ((0, stream_type_check_1.isReadableStream)(upstream)) { + return (0, createBufferedReadableStream_1.createBufferedReadableStream)(upstream, size2, logger4); + } + const downstream = new node_stream_1.Readable({ read() { + } }); + let streamBufferingLoggedWarning = false; + let bytesSeen = 0; + const buffers = [ + "", + new ByteArrayCollector_1.ByteArrayCollector((size3) => new Uint8Array(size3)), + new ByteArrayCollector_1.ByteArrayCollector((size3) => Buffer.from(new Uint8Array(size3))) + ]; + let mode = -1; + upstream.on("data", (chunk) => { + const chunkMode = (0, createBufferedReadableStream_1.modeOf)(chunk, true); + if (mode !== chunkMode) { + if (mode >= 0) { + downstream.push((0, createBufferedReadableStream_1.flush)(buffers, mode)); + } + mode = chunkMode; + } + if (mode === -1) { + downstream.push(chunk); + return; + } + const chunkSize = (0, createBufferedReadableStream_1.sizeOf)(chunk); + bytesSeen += chunkSize; + const bufferSize = (0, createBufferedReadableStream_1.sizeOf)(buffers[mode]); + if (chunkSize >= size2 && bufferSize === 0) { + downstream.push(chunk); + } else { + const newSize = (0, createBufferedReadableStream_1.merge)(buffers, mode, chunk); + if (!streamBufferingLoggedWarning && bytesSeen > size2 * 2) { + streamBufferingLoggedWarning = true; + logger4?.warn(`@smithy/util-stream - stream chunk size ${chunkSize} is below threshold of ${size2}, automatically buffering.`); + } + if (newSize >= size2) { + downstream.push((0, createBufferedReadableStream_1.flush)(buffers, mode)); + } + } + }); + upstream.on("end", () => { + if (mode !== -1) { + const remainder = (0, createBufferedReadableStream_1.flush)(buffers, mode); + if ((0, createBufferedReadableStream_1.sizeOf)(remainder) > 0) { + downstream.push(remainder); + } + } + downstream.push(null); + }); + return downstream; + } + } +}); + +// node_modules/.pnpm/@smithy+util-stream@4.5.22/node_modules/@smithy/util-stream/dist-cjs/getAwsChunkedEncodingStream.browser.js +var require_getAwsChunkedEncodingStream_browser = __commonJS({ + "node_modules/.pnpm/@smithy+util-stream@4.5.22/node_modules/@smithy/util-stream/dist-cjs/getAwsChunkedEncodingStream.browser.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getAwsChunkedEncodingStream = void 0; + var getAwsChunkedEncodingStream = (readableStream, options) => { + const { base64Encoder, bodyLengthChecker, checksumAlgorithmFn, checksumLocationName, streamHasher } = options; + const checksumRequired = base64Encoder !== void 0 && bodyLengthChecker !== void 0 && checksumAlgorithmFn !== void 0 && checksumLocationName !== void 0 && streamHasher !== void 0; + const digest2 = checksumRequired ? streamHasher(checksumAlgorithmFn, readableStream) : void 0; + const reader = readableStream.getReader(); + return new ReadableStream({ + async pull(controller) { + const { value, done } = await reader.read(); + if (done) { + controller.enqueue(`0\r +`); + if (checksumRequired) { + const checksum = base64Encoder(await digest2); + controller.enqueue(`${checksumLocationName}:${checksum}\r +`); + controller.enqueue(`\r +`); + } + controller.close(); + } else { + controller.enqueue(`${(bodyLengthChecker(value) || 0).toString(16)}\r +${value}\r +`); + } + } + }); + }; + exports.getAwsChunkedEncodingStream = getAwsChunkedEncodingStream; + } +}); + +// node_modules/.pnpm/@smithy+util-stream@4.5.22/node_modules/@smithy/util-stream/dist-cjs/getAwsChunkedEncodingStream.js +var require_getAwsChunkedEncodingStream = __commonJS({ + "node_modules/.pnpm/@smithy+util-stream@4.5.22/node_modules/@smithy/util-stream/dist-cjs/getAwsChunkedEncodingStream.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getAwsChunkedEncodingStream = getAwsChunkedEncodingStream; + var node_stream_1 = __require("node:stream"); + var getAwsChunkedEncodingStream_browser_1 = require_getAwsChunkedEncodingStream_browser(); + var stream_type_check_1 = require_stream_type_check(); + function getAwsChunkedEncodingStream(stream, options) { + const readable = stream; + const readableStream = stream; + if ((0, stream_type_check_1.isReadableStream)(readableStream)) { + return (0, getAwsChunkedEncodingStream_browser_1.getAwsChunkedEncodingStream)(readableStream, options); + } + const { base64Encoder, bodyLengthChecker, checksumAlgorithmFn, checksumLocationName, streamHasher } = options; + const checksumRequired = base64Encoder !== void 0 && checksumAlgorithmFn !== void 0 && checksumLocationName !== void 0 && streamHasher !== void 0; + const digest2 = checksumRequired ? streamHasher(checksumAlgorithmFn, readable) : void 0; + const awsChunkedEncodingStream = new node_stream_1.Readable({ + read: () => { + } + }); + readable.on("data", (data2) => { + const length = bodyLengthChecker(data2) || 0; + if (length === 0) { + return; + } + awsChunkedEncodingStream.push(`${length.toString(16)}\r +`); + awsChunkedEncodingStream.push(data2); + awsChunkedEncodingStream.push("\r\n"); + }); + readable.on("end", async () => { + awsChunkedEncodingStream.push(`0\r +`); + if (checksumRequired) { + const checksum = base64Encoder(await digest2); + awsChunkedEncodingStream.push(`${checksumLocationName}:${checksum}\r +`); + awsChunkedEncodingStream.push(`\r +`); + } + awsChunkedEncodingStream.push(null); + }); + return awsChunkedEncodingStream; + } + } +}); + +// node_modules/.pnpm/@smithy+util-stream@4.5.22/node_modules/@smithy/util-stream/dist-cjs/headStream.browser.js +var require_headStream_browser = __commonJS({ + "node_modules/.pnpm/@smithy+util-stream@4.5.22/node_modules/@smithy/util-stream/dist-cjs/headStream.browser.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.headStream = headStream; + async function headStream(stream, bytes) { + let byteLengthCounter = 0; + const chunks = []; + const reader = stream.getReader(); + let isDone = false; + while (!isDone) { + const { done, value } = await reader.read(); + if (value) { + chunks.push(value); + byteLengthCounter += value?.byteLength ?? 0; + } + if (byteLengthCounter >= bytes) { + break; + } + isDone = done; + } + reader.releaseLock(); + const collected = new Uint8Array(Math.min(bytes, byteLengthCounter)); + let offset = 0; + for (const chunk of chunks) { + if (chunk.byteLength > collected.byteLength - offset) { + collected.set(chunk.subarray(0, collected.byteLength - offset), offset); + break; + } else { + collected.set(chunk, offset); + } + offset += chunk.length; + } + return collected; + } + } +}); + +// node_modules/.pnpm/@smithy+util-stream@4.5.22/node_modules/@smithy/util-stream/dist-cjs/headStream.js +var require_headStream = __commonJS({ + "node_modules/.pnpm/@smithy+util-stream@4.5.22/node_modules/@smithy/util-stream/dist-cjs/headStream.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.headStream = void 0; + var stream_1 = __require("stream"); + var headStream_browser_1 = require_headStream_browser(); + var stream_type_check_1 = require_stream_type_check(); + var headStream = (stream, bytes) => { + if ((0, stream_type_check_1.isReadableStream)(stream)) { + return (0, headStream_browser_1.headStream)(stream, bytes); + } + return new Promise((resolve4, reject) => { + const collector = new Collector(); + collector.limit = bytes; + stream.pipe(collector); + stream.on("error", (err) => { + collector.end(); + reject(err); + }); + collector.on("error", reject); + collector.on("finish", function() { + const bytes2 = new Uint8Array(Buffer.concat(this.buffers)); + resolve4(bytes2); + }); + }); + }; + exports.headStream = headStream; + var Collector = class extends stream_1.Writable { + buffers = []; + limit = Infinity; + bytesBuffered = 0; + _write(chunk, encoding, callback) { + this.buffers.push(chunk); + this.bytesBuffered += chunk.byteLength ?? 0; + if (this.bytesBuffered >= this.limit) { + const excess = this.bytesBuffered - this.limit; + const tailBuffer = this.buffers[this.buffers.length - 1]; + this.buffers[this.buffers.length - 1] = tailBuffer.subarray(0, tailBuffer.byteLength - excess); + this.emit("finish"); + } + callback(); + } + }; + } +}); + +// node_modules/.pnpm/@smithy+util-uri-escape@4.2.2/node_modules/@smithy/util-uri-escape/dist-cjs/index.js +var require_dist_cjs8 = __commonJS({ + "node_modules/.pnpm/@smithy+util-uri-escape@4.2.2/node_modules/@smithy/util-uri-escape/dist-cjs/index.js"(exports) { + "use strict"; + var escapeUri = (uri) => encodeURIComponent(uri).replace(/[!'()*]/g, hexEncode); + var hexEncode = (c5) => `%${c5.charCodeAt(0).toString(16).toUpperCase()}`; + var escapeUriPath = (uri) => uri.split("/").map(escapeUri).join("/"); + exports.escapeUri = escapeUri; + exports.escapeUriPath = escapeUriPath; + } +}); + +// node_modules/.pnpm/@smithy+querystring-builder@4.2.13/node_modules/@smithy/querystring-builder/dist-cjs/index.js +var require_dist_cjs9 = __commonJS({ + "node_modules/.pnpm/@smithy+querystring-builder@4.2.13/node_modules/@smithy/querystring-builder/dist-cjs/index.js"(exports) { + "use strict"; + var utilUriEscape = require_dist_cjs8(); + function buildQueryString(query) { + const parts = []; + for (let key of Object.keys(query).sort()) { + const value = query[key]; + key = utilUriEscape.escapeUri(key); + if (Array.isArray(value)) { + for (let i5 = 0, iLen = value.length; i5 < iLen; i5++) { + parts.push(`${key}=${utilUriEscape.escapeUri(value[i5])}`); + } + } else { + let qsEntry = key; + if (value || typeof value === "string") { + qsEntry += `=${utilUriEscape.escapeUri(value)}`; + } + parts.push(qsEntry); + } + } + return parts.join("&"); + } + exports.buildQueryString = buildQueryString; + } +}); + +// node_modules/.pnpm/@smithy+node-http-handler@4.5.2/node_modules/@smithy/node-http-handler/dist-cjs/index.js +var require_dist_cjs10 = __commonJS({ + "node_modules/.pnpm/@smithy+node-http-handler@4.5.2/node_modules/@smithy/node-http-handler/dist-cjs/index.js"(exports) { + "use strict"; + var protocolHttp = require_dist_cjs2(); + var querystringBuilder = require_dist_cjs9(); + var node_https = __require("node:https"); + var node_stream = __require("node:stream"); + var http2 = __require("node:http2"); + function buildAbortError(abortSignal) { + const reason = abortSignal && typeof abortSignal === "object" && "reason" in abortSignal ? abortSignal.reason : void 0; + if (reason) { + if (reason instanceof Error) { + const abortError3 = new Error("Request aborted"); + abortError3.name = "AbortError"; + abortError3.cause = reason; + return abortError3; + } + const abortError2 = new Error(String(reason)); + abortError2.name = "AbortError"; + return abortError2; + } + const abortError = new Error("Request aborted"); + abortError.name = "AbortError"; + return abortError; + } + var NODEJS_TIMEOUT_ERROR_CODES = ["ECONNRESET", "EPIPE", "ETIMEDOUT"]; + var getTransformedHeaders = (headers) => { + const transformedHeaders = {}; + for (const name of Object.keys(headers)) { + const headerValues = headers[name]; + transformedHeaders[name] = Array.isArray(headerValues) ? headerValues.join(",") : headerValues; + } + return transformedHeaders; + }; + var timing = { + setTimeout: (cb, ms) => setTimeout(cb, ms), + clearTimeout: (timeoutId) => clearTimeout(timeoutId) + }; + var DEFER_EVENT_LISTENER_TIME$2 = 1e3; + var setConnectionTimeout = (request, reject, timeoutInMs = 0) => { + if (!timeoutInMs) { + return -1; + } + const registerTimeout = (offset) => { + const timeoutId = timing.setTimeout(() => { + request.destroy(); + reject(Object.assign(new Error(`@smithy/node-http-handler - the request socket did not establish a connection with the server within the configured timeout of ${timeoutInMs} ms.`), { + name: "TimeoutError" + })); + }, timeoutInMs - offset); + const doWithSocket = (socket) => { + if (socket?.connecting) { + socket.on("connect", () => { + timing.clearTimeout(timeoutId); + }); + } else { + timing.clearTimeout(timeoutId); + } + }; + if (request.socket) { + doWithSocket(request.socket); + } else { + request.on("socket", doWithSocket); + } + }; + if (timeoutInMs < 2e3) { + registerTimeout(0); + return 0; + } + return timing.setTimeout(registerTimeout.bind(null, DEFER_EVENT_LISTENER_TIME$2), DEFER_EVENT_LISTENER_TIME$2); + }; + var setRequestTimeout = (req, reject, timeoutInMs = 0, throwOnRequestTimeout, logger4) => { + if (timeoutInMs) { + return timing.setTimeout(() => { + let msg = `@smithy/node-http-handler - [${throwOnRequestTimeout ? "ERROR" : "WARN"}] a request has exceeded the configured ${timeoutInMs} ms requestTimeout.`; + if (throwOnRequestTimeout) { + const error50 = Object.assign(new Error(msg), { + name: "TimeoutError", + code: "ETIMEDOUT" + }); + req.destroy(error50); + reject(error50); + } else { + msg += ` Init client requestHandler with throwOnRequestTimeout=true to turn this into an error.`; + logger4?.warn?.(msg); + } + }, timeoutInMs); + } + return -1; + }; + var DEFER_EVENT_LISTENER_TIME$1 = 3e3; + var setSocketKeepAlive = (request, { keepAlive, keepAliveMsecs }, deferTimeMs = DEFER_EVENT_LISTENER_TIME$1) => { + if (keepAlive !== true) { + return -1; + } + const registerListener = () => { + if (request.socket) { + request.socket.setKeepAlive(keepAlive, keepAliveMsecs || 0); + } else { + request.on("socket", (socket) => { + socket.setKeepAlive(keepAlive, keepAliveMsecs || 0); + }); + } + }; + if (deferTimeMs === 0) { + registerListener(); + return 0; + } + return timing.setTimeout(registerListener, deferTimeMs); + }; + var DEFER_EVENT_LISTENER_TIME = 3e3; + var setSocketTimeout = (request, reject, timeoutInMs = 0) => { + const registerTimeout = (offset) => { + const timeout = timeoutInMs - offset; + const onTimeout = () => { + request.destroy(); + reject(Object.assign(new Error(`@smithy/node-http-handler - the request socket timed out after ${timeoutInMs} ms of inactivity (configured by client requestHandler).`), { name: "TimeoutError" })); + }; + if (request.socket) { + request.socket.setTimeout(timeout, onTimeout); + request.on("close", () => request.socket?.removeListener("timeout", onTimeout)); + } else { + request.setTimeout(timeout, onTimeout); + } + }; + if (0 < timeoutInMs && timeoutInMs < 6e3) { + registerTimeout(0); + return 0; + } + return timing.setTimeout(registerTimeout.bind(null, timeoutInMs === 0 ? 0 : DEFER_EVENT_LISTENER_TIME), DEFER_EVENT_LISTENER_TIME); + }; + var MIN_WAIT_TIME = 6e3; + async function writeRequestBody(httpRequest2, request, maxContinueTimeoutMs = MIN_WAIT_TIME, externalAgent = false) { + const headers = request.headers ?? {}; + const expect = headers.Expect || headers.expect; + let timeoutId = -1; + let sendBody = true; + if (!externalAgent && expect === "100-continue") { + sendBody = await Promise.race([ + new Promise((resolve4) => { + timeoutId = Number(timing.setTimeout(() => resolve4(true), Math.max(MIN_WAIT_TIME, maxContinueTimeoutMs))); + }), + new Promise((resolve4) => { + httpRequest2.on("continue", () => { + timing.clearTimeout(timeoutId); + resolve4(true); + }); + httpRequest2.on("response", () => { + timing.clearTimeout(timeoutId); + resolve4(false); + }); + httpRequest2.on("error", () => { + timing.clearTimeout(timeoutId); + resolve4(false); + }); + }) + ]); + } + if (sendBody) { + writeBody(httpRequest2, request.body); + } + } + function writeBody(httpRequest2, body) { + if (body instanceof node_stream.Readable) { + body.pipe(httpRequest2); + return; + } + if (body) { + const isBuffer2 = Buffer.isBuffer(body); + const isString2 = typeof body === "string"; + if (isBuffer2 || isString2) { + if (isBuffer2 && body.byteLength === 0) { + httpRequest2.end(); + } else { + httpRequest2.end(body); + } + return; + } + const uint8 = body; + if (typeof uint8 === "object" && uint8.buffer && typeof uint8.byteOffset === "number" && typeof uint8.byteLength === "number") { + httpRequest2.end(Buffer.from(uint8.buffer, uint8.byteOffset, uint8.byteLength)); + return; + } + httpRequest2.end(Buffer.from(body)); + return; + } + httpRequest2.end(); + } + var DEFAULT_REQUEST_TIMEOUT = 0; + var hAgent = void 0; + var hRequest = void 0; + var NodeHttpHandler = class _NodeHttpHandler { + config; + configProvider; + socketWarningTimestamp = 0; + externalAgent = false; + metadata = { handlerProtocol: "http/1.1" }; + static create(instanceOrOptions) { + if (typeof instanceOrOptions?.handle === "function") { + return instanceOrOptions; + } + return new _NodeHttpHandler(instanceOrOptions); + } + static checkSocketUsage(agent, socketWarningTimestamp, logger4 = console) { + const { sockets, requests, maxSockets } = agent; + if (typeof maxSockets !== "number" || maxSockets === Infinity) { + return socketWarningTimestamp; + } + const interval2 = 15e3; + if (Date.now() - interval2 < socketWarningTimestamp) { + return socketWarningTimestamp; + } + if (sockets && requests) { + for (const origin in sockets) { + const socketsInUse = sockets[origin]?.length ?? 0; + const requestsEnqueued = requests[origin]?.length ?? 0; + if (socketsInUse >= maxSockets && requestsEnqueued >= 2 * maxSockets) { + logger4?.warn?.(`@smithy/node-http-handler:WARN - socket usage at capacity=${socketsInUse} and ${requestsEnqueued} additional requests are enqueued. +See https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/node-configuring-maxsockets.html +or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler config.`); + return Date.now(); + } + } + } + return socketWarningTimestamp; + } + constructor(options) { + this.configProvider = new Promise((resolve4, reject) => { + if (typeof options === "function") { + options().then((_options) => { + resolve4(this.resolveDefaultConfig(_options)); + }).catch(reject); + } else { + resolve4(this.resolveDefaultConfig(options)); + } + }); + } + destroy() { + this.config?.httpAgent?.destroy(); + this.config?.httpsAgent?.destroy(); + } + async handle(request, { abortSignal, requestTimeout } = {}) { + if (!this.config) { + this.config = await this.configProvider; + } + const config3 = this.config; + const isSSL = request.protocol === "https:"; + if (!isSSL && !this.config.httpAgent) { + this.config.httpAgent = await this.config.httpAgentProvider(); + } + return new Promise((_resolve, _reject) => { + let writeRequestBodyPromise = void 0; + const timeouts = []; + const resolve4 = async (arg) => { + await writeRequestBodyPromise; + timeouts.forEach(timing.clearTimeout); + _resolve(arg); + }; + const reject = async (arg) => { + await writeRequestBodyPromise; + timeouts.forEach(timing.clearTimeout); + _reject(arg); + }; + if (abortSignal?.aborted) { + const abortError = buildAbortError(abortSignal); + reject(abortError); + return; + } + const headers = request.headers ?? {}; + const expectContinue = (headers.Expect ?? headers.expect) === "100-continue"; + let agent = isSSL ? config3.httpsAgent : config3.httpAgent; + if (expectContinue && !this.externalAgent) { + agent = new (isSSL ? node_https.Agent : hAgent)({ + keepAlive: false, + maxSockets: Infinity + }); + } + timeouts.push(timing.setTimeout(() => { + this.socketWarningTimestamp = _NodeHttpHandler.checkSocketUsage(agent, this.socketWarningTimestamp, config3.logger); + }, config3.socketAcquisitionWarningTimeout ?? (config3.requestTimeout ?? 2e3) + (config3.connectionTimeout ?? 1e3))); + const queryString = querystringBuilder.buildQueryString(request.query || {}); + let auth = void 0; + if (request.username != null || request.password != null) { + const username = request.username ?? ""; + const password = request.password ?? ""; + auth = `${username}:${password}`; + } + let path53 = request.path; + if (queryString) { + path53 += `?${queryString}`; + } + if (request.fragment) { + path53 += `#${request.fragment}`; + } + let hostname3 = request.hostname ?? ""; + if (hostname3[0] === "[" && hostname3.endsWith("]")) { + hostname3 = request.hostname.slice(1, -1); + } else { + hostname3 = request.hostname; + } + const nodeHttpsOptions = { + headers: request.headers, + host: hostname3, + method: request.method, + path: path53, + port: request.port, + agent, + auth + }; + const requestFunc = isSSL ? node_https.request : hRequest; + const req = requestFunc(nodeHttpsOptions, (res) => { + const httpResponse = new protocolHttp.HttpResponse({ + statusCode: res.statusCode || -1, + reason: res.statusMessage, + headers: getTransformedHeaders(res.headers), + body: res + }); + resolve4({ response: httpResponse }); + }); + req.on("error", (err) => { + if (NODEJS_TIMEOUT_ERROR_CODES.includes(err.code)) { + reject(Object.assign(err, { name: "TimeoutError" })); + } else { + reject(err); + } + }); + if (abortSignal) { + const onAbort = () => { + req.destroy(); + const abortError = buildAbortError(abortSignal); + reject(abortError); + }; + if (typeof abortSignal.addEventListener === "function") { + const signal = abortSignal; + signal.addEventListener("abort", onAbort, { once: true }); + req.once("close", () => signal.removeEventListener("abort", onAbort)); + } else { + abortSignal.onabort = onAbort; + } + } + const effectiveRequestTimeout = requestTimeout ?? config3.requestTimeout; + timeouts.push(setConnectionTimeout(req, reject, config3.connectionTimeout)); + timeouts.push(setRequestTimeout(req, reject, effectiveRequestTimeout, config3.throwOnRequestTimeout, config3.logger ?? console)); + timeouts.push(setSocketTimeout(req, reject, config3.socketTimeout)); + const httpAgent = nodeHttpsOptions.agent; + if (typeof httpAgent === "object" && "keepAlive" in httpAgent) { + timeouts.push(setSocketKeepAlive(req, { + keepAlive: httpAgent.keepAlive, + keepAliveMsecs: httpAgent.keepAliveMsecs + })); + } + writeRequestBodyPromise = writeRequestBody(req, request, effectiveRequestTimeout, this.externalAgent).catch((e5) => { + timeouts.forEach(timing.clearTimeout); + return _reject(e5); + }); + }); + } + updateHttpClientConfig(key, value) { + this.config = void 0; + this.configProvider = this.configProvider.then((config3) => { + return { + ...config3, + [key]: value + }; + }); + } + httpHandlerConfigs() { + return this.config ?? {}; + } + resolveDefaultConfig(options) { + const { requestTimeout, connectionTimeout, socketTimeout, socketAcquisitionWarningTimeout, httpAgent, httpsAgent, throwOnRequestTimeout, logger: logger4 } = options || {}; + const keepAlive = true; + const maxSockets = 50; + return { + connectionTimeout, + requestTimeout, + socketTimeout, + socketAcquisitionWarningTimeout, + throwOnRequestTimeout, + httpAgentProvider: async () => { + const { Agent, request } = await import("node:http"); + hRequest = request; + hAgent = Agent; + if (httpAgent instanceof hAgent || typeof httpAgent?.destroy === "function") { + this.externalAgent = true; + return httpAgent; + } + return new hAgent({ keepAlive, maxSockets, ...httpAgent }); + }, + httpsAgent: (() => { + if (httpsAgent instanceof node_https.Agent || typeof httpsAgent?.destroy === "function") { + this.externalAgent = true; + return httpsAgent; + } + return new node_https.Agent({ keepAlive, maxSockets, ...httpsAgent }); + })(), + logger: logger4 + }; + } + }; + var NodeHttp2ConnectionPool = class { + sessions = []; + constructor(sessions) { + this.sessions = sessions ?? []; + } + poll() { + if (this.sessions.length > 0) { + return this.sessions.shift(); + } + } + offerLast(session) { + this.sessions.push(session); + } + contains(session) { + return this.sessions.includes(session); + } + remove(session) { + this.sessions = this.sessions.filter((s5) => s5 !== session); + } + [Symbol.iterator]() { + return this.sessions[Symbol.iterator](); + } + destroy(connection2) { + for (const session of this.sessions) { + if (session === connection2) { + if (!session.destroyed) { + session.destroy(); + } + } + } + } + }; + var NodeHttp2ConnectionManager = class { + constructor(config3) { + this.config = config3; + if (this.config.maxConcurrency && this.config.maxConcurrency <= 0) { + throw new RangeError("maxConcurrency must be greater than zero."); + } + } + config; + sessionCache = /* @__PURE__ */ new Map(); + lease(requestContext, connectionConfiguration) { + const url2 = this.getUrlString(requestContext); + const existingPool = this.sessionCache.get(url2); + if (existingPool) { + const existingSession = existingPool.poll(); + if (existingSession && !this.config.disableConcurrency) { + return existingSession; + } + } + const session = http2.connect(url2); + if (this.config.maxConcurrency) { + session.settings({ maxConcurrentStreams: this.config.maxConcurrency }, (err) => { + if (err) { + throw new Error("Fail to set maxConcurrentStreams to " + this.config.maxConcurrency + "when creating new session for " + requestContext.destination.toString()); + } + }); + } + session.unref(); + const destroySessionCb = () => { + session.destroy(); + this.deleteSession(url2, session); + }; + session.on("goaway", destroySessionCb); + session.on("error", destroySessionCb); + session.on("frameError", destroySessionCb); + session.on("close", () => this.deleteSession(url2, session)); + if (connectionConfiguration.requestTimeout) { + session.setTimeout(connectionConfiguration.requestTimeout, destroySessionCb); + } + const connectionPool = this.sessionCache.get(url2) || new NodeHttp2ConnectionPool(); + connectionPool.offerLast(session); + this.sessionCache.set(url2, connectionPool); + return session; + } + deleteSession(authority, session) { + const existingConnectionPool = this.sessionCache.get(authority); + if (!existingConnectionPool) { + return; + } + if (!existingConnectionPool.contains(session)) { + return; + } + existingConnectionPool.remove(session); + this.sessionCache.set(authority, existingConnectionPool); + } + release(requestContext, session) { + const cacheKey = this.getUrlString(requestContext); + this.sessionCache.get(cacheKey)?.offerLast(session); + } + destroy() { + for (const [key, connectionPool] of this.sessionCache) { + for (const session of connectionPool) { + if (!session.destroyed) { + session.destroy(); + } + connectionPool.remove(session); + } + this.sessionCache.delete(key); + } + } + setMaxConcurrentStreams(maxConcurrentStreams) { + if (maxConcurrentStreams && maxConcurrentStreams <= 0) { + throw new RangeError("maxConcurrentStreams must be greater than zero."); + } + this.config.maxConcurrency = maxConcurrentStreams; + } + setDisableConcurrentStreams(disableConcurrentStreams) { + this.config.disableConcurrency = disableConcurrentStreams; + } + getUrlString(request) { + return request.destination.toString(); + } + }; + var NodeHttp2Handler = class _NodeHttp2Handler { + config; + configProvider; + metadata = { handlerProtocol: "h2" }; + connectionManager = new NodeHttp2ConnectionManager({}); + static create(instanceOrOptions) { + if (typeof instanceOrOptions?.handle === "function") { + return instanceOrOptions; + } + return new _NodeHttp2Handler(instanceOrOptions); + } + constructor(options) { + this.configProvider = new Promise((resolve4, reject) => { + if (typeof options === "function") { + options().then((opts) => { + resolve4(opts || {}); + }).catch(reject); + } else { + resolve4(options || {}); + } + }); + } + destroy() { + this.connectionManager.destroy(); + } + async handle(request, { abortSignal, requestTimeout } = {}) { + if (!this.config) { + this.config = await this.configProvider; + this.connectionManager.setDisableConcurrentStreams(this.config.disableConcurrentStreams || false); + if (this.config.maxConcurrentStreams) { + this.connectionManager.setMaxConcurrentStreams(this.config.maxConcurrentStreams); + } + } + const { requestTimeout: configRequestTimeout, disableConcurrentStreams } = this.config; + const effectiveRequestTimeout = requestTimeout ?? configRequestTimeout; + return new Promise((_resolve, _reject) => { + let fulfilled = false; + let writeRequestBodyPromise = void 0; + const resolve4 = async (arg) => { + await writeRequestBodyPromise; + _resolve(arg); + }; + const reject = async (arg) => { + await writeRequestBodyPromise; + _reject(arg); + }; + if (abortSignal?.aborted) { + fulfilled = true; + const abortError = buildAbortError(abortSignal); + reject(abortError); + return; + } + const { hostname: hostname3, method, port, protocol, query } = request; + let auth = ""; + if (request.username != null || request.password != null) { + const username = request.username ?? ""; + const password = request.password ?? ""; + auth = `${username}:${password}@`; + } + const authority = `${protocol}//${auth}${hostname3}${port ? `:${port}` : ""}`; + const requestContext = { destination: new URL(authority) }; + const session = this.connectionManager.lease(requestContext, { + requestTimeout: this.config?.sessionTimeout, + disableConcurrentStreams: disableConcurrentStreams || false + }); + const rejectWithDestroy = (err) => { + if (disableConcurrentStreams) { + this.destroySession(session); + } + fulfilled = true; + reject(err); + }; + const queryString = querystringBuilder.buildQueryString(query || {}); + let path53 = request.path; + if (queryString) { + path53 += `?${queryString}`; + } + if (request.fragment) { + path53 += `#${request.fragment}`; + } + const req = session.request({ + ...request.headers, + [http2.constants.HTTP2_HEADER_PATH]: path53, + [http2.constants.HTTP2_HEADER_METHOD]: method + }); + session.ref(); + req.on("response", (headers) => { + const httpResponse = new protocolHttp.HttpResponse({ + statusCode: headers[":status"] || -1, + headers: getTransformedHeaders(headers), + body: req + }); + fulfilled = true; + resolve4({ response: httpResponse }); + if (disableConcurrentStreams) { + session.close(); + this.connectionManager.deleteSession(authority, session); + } + }); + if (effectiveRequestTimeout) { + req.setTimeout(effectiveRequestTimeout, () => { + req.close(); + const timeoutError = new Error(`Stream timed out because of no activity for ${effectiveRequestTimeout} ms`); + timeoutError.name = "TimeoutError"; + rejectWithDestroy(timeoutError); + }); + } + if (abortSignal) { + const onAbort = () => { + req.close(); + const abortError = buildAbortError(abortSignal); + rejectWithDestroy(abortError); + }; + if (typeof abortSignal.addEventListener === "function") { + const signal = abortSignal; + signal.addEventListener("abort", onAbort, { once: true }); + req.once("close", () => signal.removeEventListener("abort", onAbort)); + } else { + abortSignal.onabort = onAbort; + } + } + req.on("frameError", (type, code, id) => { + rejectWithDestroy(new Error(`Frame type id ${type} in stream id ${id} has failed with code ${code}.`)); + }); + req.on("error", rejectWithDestroy); + req.on("aborted", () => { + rejectWithDestroy(new Error(`HTTP/2 stream is abnormally aborted in mid-communication with result code ${req.rstCode}.`)); + }); + req.on("close", () => { + session.unref(); + if (disableConcurrentStreams) { + session.destroy(); + } + if (!fulfilled) { + rejectWithDestroy(new Error("Unexpected error: http2 request did not get a response")); + } + }); + writeRequestBodyPromise = writeRequestBody(req, request, effectiveRequestTimeout); + }); + } + updateHttpClientConfig(key, value) { + this.config = void 0; + this.configProvider = this.configProvider.then((config3) => { + return { + ...config3, + [key]: value + }; + }); + } + httpHandlerConfigs() { + return this.config ?? {}; + } + destroySession(session) { + if (!session.destroyed) { + session.destroy(); + } + } + }; + var Collector = class extends node_stream.Writable { + bufferedBytes = []; + _write(chunk, encoding, callback) { + this.bufferedBytes.push(chunk); + callback(); + } + }; + var streamCollector5 = (stream) => { + if (isReadableStreamInstance(stream)) { + return collectReadableStream(stream); + } + return new Promise((resolve4, reject) => { + const collector = new Collector(); + stream.pipe(collector); + stream.on("error", (err) => { + collector.end(); + reject(err); + }); + collector.on("error", reject); + collector.on("finish", function() { + const bytes = new Uint8Array(Buffer.concat(this.bufferedBytes)); + resolve4(bytes); + }); + }); + }; + var isReadableStreamInstance = (stream) => typeof ReadableStream === "function" && stream instanceof ReadableStream; + async function collectReadableStream(stream) { + const chunks = []; + const reader = stream.getReader(); + let isDone = false; + let length = 0; + while (!isDone) { + const { done, value } = await reader.read(); + if (value) { + chunks.push(value); + length += value.length; + } + isDone = done; + } + const collected = new Uint8Array(length); + let offset = 0; + for (const chunk of chunks) { + collected.set(chunk, offset); + offset += chunk.length; + } + return collected; + } + exports.DEFAULT_REQUEST_TIMEOUT = DEFAULT_REQUEST_TIMEOUT; + exports.NodeHttp2Handler = NodeHttp2Handler; + exports.NodeHttpHandler = NodeHttpHandler; + exports.streamCollector = streamCollector5; + } +}); + +// node_modules/.pnpm/@smithy+fetch-http-handler@5.3.16/node_modules/@smithy/fetch-http-handler/dist-cjs/index.js +var require_dist_cjs11 = __commonJS({ + "node_modules/.pnpm/@smithy+fetch-http-handler@5.3.16/node_modules/@smithy/fetch-http-handler/dist-cjs/index.js"(exports) { + "use strict"; + var protocolHttp = require_dist_cjs2(); + var querystringBuilder = require_dist_cjs9(); + var utilBase64 = require_dist_cjs7(); + function createRequest2(url2, requestOptions) { + return new Request(url2, requestOptions); + } + function requestTimeout(timeoutInMs = 0) { + return new Promise((resolve4, reject) => { + if (timeoutInMs) { + setTimeout(() => { + const timeoutError = new Error(`Request did not complete within ${timeoutInMs} ms`); + timeoutError.name = "TimeoutError"; + reject(timeoutError); + }, timeoutInMs); + } + }); + } + var keepAliveSupport = { + supported: void 0 + }; + var FetchHttpHandler = class _FetchHttpHandler { + config; + configProvider; + static create(instanceOrOptions) { + if (typeof instanceOrOptions?.handle === "function") { + return instanceOrOptions; + } + return new _FetchHttpHandler(instanceOrOptions); + } + constructor(options) { + if (typeof options === "function") { + this.configProvider = options().then((opts) => opts || {}); + } else { + this.config = options ?? {}; + this.configProvider = Promise.resolve(this.config); + } + if (keepAliveSupport.supported === void 0) { + keepAliveSupport.supported = Boolean(typeof Request !== "undefined" && "keepalive" in createRequest2("https://[::1]")); + } + } + destroy() { + } + async handle(request, { abortSignal, requestTimeout: requestTimeout$1 } = {}) { + if (!this.config) { + this.config = await this.configProvider; + } + const requestTimeoutInMs = requestTimeout$1 ?? this.config.requestTimeout; + const keepAlive = this.config.keepAlive === true; + const credentials = this.config.credentials; + if (abortSignal?.aborted) { + const abortError = buildAbortError(abortSignal); + return Promise.reject(abortError); + } + let path53 = request.path; + const queryString = querystringBuilder.buildQueryString(request.query || {}); + if (queryString) { + path53 += `?${queryString}`; + } + if (request.fragment) { + path53 += `#${request.fragment}`; + } + let auth = ""; + if (request.username != null || request.password != null) { + const username = request.username ?? ""; + const password = request.password ?? ""; + auth = `${username}:${password}@`; + } + const { port, method } = request; + const url2 = `${request.protocol}//${auth}${request.hostname}${port ? `:${port}` : ""}${path53}`; + const body = method === "GET" || method === "HEAD" ? void 0 : request.body; + const requestOptions = { + body, + headers: new Headers(request.headers), + method, + credentials + }; + if (this.config?.cache) { + requestOptions.cache = this.config.cache; + } + if (body) { + requestOptions.duplex = "half"; + } + if (typeof AbortController !== "undefined") { + requestOptions.signal = abortSignal; + } + if (keepAliveSupport.supported) { + requestOptions.keepalive = keepAlive; + } + if (typeof this.config.requestInit === "function") { + Object.assign(requestOptions, this.config.requestInit(request)); + } + let removeSignalEventListener = () => { + }; + const fetchRequest = createRequest2(url2, requestOptions); + const raceOfPromises = [ + fetch(fetchRequest).then((response) => { + const fetchHeaders = response.headers; + const transformedHeaders = {}; + for (const pair of fetchHeaders.entries()) { + transformedHeaders[pair[0]] = pair[1]; + } + const hasReadableStream = response.body != void 0; + if (!hasReadableStream) { + return response.blob().then((body2) => ({ + response: new protocolHttp.HttpResponse({ + headers: transformedHeaders, + reason: response.statusText, + statusCode: response.status, + body: body2 + }) + })); + } + return { + response: new protocolHttp.HttpResponse({ + headers: transformedHeaders, + reason: response.statusText, + statusCode: response.status, + body: response.body + }) + }; + }), + requestTimeout(requestTimeoutInMs) + ]; + if (abortSignal) { + raceOfPromises.push(new Promise((resolve4, reject) => { + const onAbort = () => { + const abortError = buildAbortError(abortSignal); + reject(abortError); + }; + if (typeof abortSignal.addEventListener === "function") { + const signal = abortSignal; + signal.addEventListener("abort", onAbort, { once: true }); + removeSignalEventListener = () => signal.removeEventListener("abort", onAbort); + } else { + abortSignal.onabort = onAbort; + } + })); + } + return Promise.race(raceOfPromises).finally(removeSignalEventListener); + } + updateHttpClientConfig(key, value) { + this.config = void 0; + this.configProvider = this.configProvider.then((config3) => { + config3[key] = value; + return config3; + }); + } + httpHandlerConfigs() { + return this.config ?? {}; + } + }; + function buildAbortError(abortSignal) { + const reason = abortSignal && typeof abortSignal === "object" && "reason" in abortSignal ? abortSignal.reason : void 0; + if (reason) { + if (reason instanceof Error) { + const abortError3 = new Error("Request aborted"); + abortError3.name = "AbortError"; + abortError3.cause = reason; + return abortError3; + } + const abortError2 = new Error(String(reason)); + abortError2.name = "AbortError"; + return abortError2; + } + const abortError = new Error("Request aborted"); + abortError.name = "AbortError"; + return abortError; + } + var streamCollector5 = async (stream) => { + if (typeof Blob === "function" && stream instanceof Blob || stream.constructor?.name === "Blob") { + if (Blob.prototype.arrayBuffer !== void 0) { + return new Uint8Array(await stream.arrayBuffer()); + } + return collectBlob(stream); + } + return collectStream(stream); + }; + async function collectBlob(blob) { + const base644 = await readToBase64(blob); + const arrayBuffer = utilBase64.fromBase64(base644); + return new Uint8Array(arrayBuffer); + } + async function collectStream(stream) { + const chunks = []; + const reader = stream.getReader(); + let isDone = false; + let length = 0; + while (!isDone) { + const { done, value } = await reader.read(); + if (value) { + chunks.push(value); + length += value.length; + } + isDone = done; + } + const collected = new Uint8Array(length); + let offset = 0; + for (const chunk of chunks) { + collected.set(chunk, offset); + offset += chunk.length; + } + return collected; + } + function readToBase64(blob) { + return new Promise((resolve4, reject) => { + const reader = new FileReader(); + reader.onloadend = () => { + if (reader.readyState !== 2) { + return reject(new Error("Reader aborted too early")); + } + const result = reader.result ?? ""; + const commaIndex = result.indexOf(","); + const dataOffset = commaIndex > -1 ? commaIndex + 1 : result.length; + resolve4(result.substring(dataOffset)); + }; + reader.onabort = () => reject(new Error("Read aborted")); + reader.onerror = () => reject(reader.error); + reader.readAsDataURL(blob); + }); + } + exports.FetchHttpHandler = FetchHttpHandler; + exports.keepAliveSupport = keepAliveSupport; + exports.streamCollector = streamCollector5; + } +}); + +// node_modules/.pnpm/@smithy+util-hex-encoding@4.2.2/node_modules/@smithy/util-hex-encoding/dist-cjs/index.js +var require_dist_cjs12 = __commonJS({ + "node_modules/.pnpm/@smithy+util-hex-encoding@4.2.2/node_modules/@smithy/util-hex-encoding/dist-cjs/index.js"(exports) { + "use strict"; + var SHORT_TO_HEX = {}; + var HEX_TO_SHORT = {}; + for (let i5 = 0; i5 < 256; i5++) { + let encodedByte = i5.toString(16).toLowerCase(); + if (encodedByte.length === 1) { + encodedByte = `0${encodedByte}`; + } + SHORT_TO_HEX[i5] = encodedByte; + HEX_TO_SHORT[encodedByte] = i5; + } + function fromHex(encoded) { + if (encoded.length % 2 !== 0) { + throw new Error("Hex encoded strings must have an even number length"); + } + const out = new Uint8Array(encoded.length / 2); + for (let i5 = 0; i5 < encoded.length; i5 += 2) { + const encodedByte = encoded.slice(i5, i5 + 2).toLowerCase(); + if (encodedByte in HEX_TO_SHORT) { + out[i5 / 2] = HEX_TO_SHORT[encodedByte]; + } else { + throw new Error(`Cannot decode unrecognized sequence ${encodedByte} as hexadecimal`); + } + } + return out; + } + function toHex(bytes) { + let out = ""; + for (let i5 = 0; i5 < bytes.byteLength; i5++) { + out += SHORT_TO_HEX[bytes[i5]]; + } + return out; + } + exports.fromHex = fromHex; + exports.toHex = toHex; + } +}); + +// node_modules/.pnpm/@smithy+util-stream@4.5.22/node_modules/@smithy/util-stream/dist-cjs/sdk-stream-mixin.browser.js +var require_sdk_stream_mixin_browser = __commonJS({ + "node_modules/.pnpm/@smithy+util-stream@4.5.22/node_modules/@smithy/util-stream/dist-cjs/sdk-stream-mixin.browser.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.sdkStreamMixin = void 0; + var fetch_http_handler_1 = require_dist_cjs11(); + var util_base64_1 = require_dist_cjs7(); + var util_hex_encoding_1 = require_dist_cjs12(); + var util_utf8_1 = require_dist_cjs6(); + var stream_type_check_1 = require_stream_type_check(); + var ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED = "The stream has already been transformed."; + var sdkStreamMixin2 = (stream) => { + if (!isBlobInstance(stream) && !(0, stream_type_check_1.isReadableStream)(stream)) { + const name = stream?.__proto__?.constructor?.name || stream; + throw new Error(`Unexpected stream implementation, expect Blob or ReadableStream, got ${name}`); + } + let transformed = false; + const transformToByteArray = async () => { + if (transformed) { + throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); + } + transformed = true; + return await (0, fetch_http_handler_1.streamCollector)(stream); + }; + const blobToWebStream = (blob) => { + if (typeof blob.stream !== "function") { + throw new Error("Cannot transform payload Blob to web stream. Please make sure the Blob.stream() is polyfilled.\nIf you are using React Native, this API is not yet supported, see: https://react-native.canny.io/feature-requests/p/fetch-streaming-body"); + } + return blob.stream(); + }; + return Object.assign(stream, { + transformToByteArray, + transformToString: async (encoding) => { + const buf = await transformToByteArray(); + if (encoding === "base64") { + return (0, util_base64_1.toBase64)(buf); + } else if (encoding === "hex") { + return (0, util_hex_encoding_1.toHex)(buf); + } else if (encoding === void 0 || encoding === "utf8" || encoding === "utf-8") { + return (0, util_utf8_1.toUtf8)(buf); + } else if (typeof TextDecoder === "function") { + return new TextDecoder(encoding).decode(buf); + } else { + throw new Error("TextDecoder is not available, please make sure polyfill is provided."); + } + }, + transformToWebStream: () => { + if (transformed) { + throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); + } + transformed = true; + if (isBlobInstance(stream)) { + return blobToWebStream(stream); + } else if ((0, stream_type_check_1.isReadableStream)(stream)) { + return stream; + } else { + throw new Error(`Cannot transform payload to web stream, got ${stream}`); + } + } + }); + }; + exports.sdkStreamMixin = sdkStreamMixin2; + var isBlobInstance = (stream) => typeof Blob === "function" && stream instanceof Blob; + } +}); + +// node_modules/.pnpm/@smithy+util-stream@4.5.22/node_modules/@smithy/util-stream/dist-cjs/sdk-stream-mixin.js +var require_sdk_stream_mixin = __commonJS({ + "node_modules/.pnpm/@smithy+util-stream@4.5.22/node_modules/@smithy/util-stream/dist-cjs/sdk-stream-mixin.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.sdkStreamMixin = void 0; + var node_http_handler_1 = require_dist_cjs10(); + var util_buffer_from_1 = require_dist_cjs5(); + var stream_1 = __require("stream"); + var sdk_stream_mixin_browser_1 = require_sdk_stream_mixin_browser(); + var ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED = "The stream has already been transformed."; + var sdkStreamMixin2 = (stream) => { + if (!(stream instanceof stream_1.Readable)) { + try { + return (0, sdk_stream_mixin_browser_1.sdkStreamMixin)(stream); + } catch (e5) { + const name = stream?.__proto__?.constructor?.name || stream; + throw new Error(`Unexpected stream implementation, expect Stream.Readable instance, got ${name}`); + } + } + let transformed = false; + const transformToByteArray = async () => { + if (transformed) { + throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); + } + transformed = true; + return await (0, node_http_handler_1.streamCollector)(stream); + }; + return Object.assign(stream, { + transformToByteArray, + transformToString: async (encoding) => { + const buf = await transformToByteArray(); + if (encoding === void 0 || Buffer.isEncoding(encoding)) { + return (0, util_buffer_from_1.fromArrayBuffer)(buf.buffer, buf.byteOffset, buf.byteLength).toString(encoding); + } else { + const decoder2 = new TextDecoder(encoding); + return decoder2.decode(buf); + } + }, + transformToWebStream: () => { + if (transformed) { + throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); + } + if (stream.readableFlowing !== null) { + throw new Error("The stream has been consumed by other callbacks."); + } + if (typeof stream_1.Readable.toWeb !== "function") { + throw new Error("Readable.toWeb() is not supported. Please ensure a polyfill is available."); + } + transformed = true; + return stream_1.Readable.toWeb(stream); + } + }); + }; + exports.sdkStreamMixin = sdkStreamMixin2; + } +}); + +// node_modules/.pnpm/@smithy+util-stream@4.5.22/node_modules/@smithy/util-stream/dist-cjs/splitStream.browser.js +var require_splitStream_browser = __commonJS({ + "node_modules/.pnpm/@smithy+util-stream@4.5.22/node_modules/@smithy/util-stream/dist-cjs/splitStream.browser.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.splitStream = splitStream; + async function splitStream(stream) { + if (typeof stream.stream === "function") { + stream = stream.stream(); + } + const readableStream = stream; + return readableStream.tee(); + } + } +}); + +// node_modules/.pnpm/@smithy+util-stream@4.5.22/node_modules/@smithy/util-stream/dist-cjs/splitStream.js +var require_splitStream = __commonJS({ + "node_modules/.pnpm/@smithy+util-stream@4.5.22/node_modules/@smithy/util-stream/dist-cjs/splitStream.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.splitStream = splitStream; + var stream_1 = __require("stream"); + var splitStream_browser_1 = require_splitStream_browser(); + var stream_type_check_1 = require_stream_type_check(); + async function splitStream(stream) { + if ((0, stream_type_check_1.isReadableStream)(stream) || (0, stream_type_check_1.isBlob)(stream)) { + return (0, splitStream_browser_1.splitStream)(stream); + } + const stream1 = new stream_1.PassThrough(); + const stream2 = new stream_1.PassThrough(); + stream.pipe(stream1); + stream.pipe(stream2); + return [stream1, stream2]; + } + } +}); + +// node_modules/.pnpm/@smithy+util-stream@4.5.22/node_modules/@smithy/util-stream/dist-cjs/index.js +var require_dist_cjs13 = __commonJS({ + "node_modules/.pnpm/@smithy+util-stream@4.5.22/node_modules/@smithy/util-stream/dist-cjs/index.js"(exports) { + "use strict"; + var utilBase64 = require_dist_cjs7(); + var utilUtf8 = require_dist_cjs6(); + var ChecksumStream = require_ChecksumStream(); + var createChecksumStream = require_createChecksumStream(); + var createBufferedReadable = require_createBufferedReadable(); + var getAwsChunkedEncodingStream = require_getAwsChunkedEncodingStream(); + var headStream = require_headStream(); + var sdkStreamMixin2 = require_sdk_stream_mixin(); + var splitStream = require_splitStream(); + var streamTypeCheck = require_stream_type_check(); + var Uint8ArrayBlobAdapter2 = class _Uint8ArrayBlobAdapter extends Uint8Array { + static fromString(source, encoding = "utf-8") { + if (typeof source === "string") { + if (encoding === "base64") { + return _Uint8ArrayBlobAdapter.mutate(utilBase64.fromBase64(source)); + } + return _Uint8ArrayBlobAdapter.mutate(utilUtf8.fromUtf8(source)); + } + throw new Error(`Unsupported conversion from ${typeof source} to Uint8ArrayBlobAdapter.`); + } + static mutate(source) { + Object.setPrototypeOf(source, _Uint8ArrayBlobAdapter.prototype); + return source; + } + transformToString(encoding = "utf-8") { + if (encoding === "base64") { + return utilBase64.toBase64(this); + } + return utilUtf8.toUtf8(this); + } + }; + exports.isBlob = streamTypeCheck.isBlob; + exports.isReadableStream = streamTypeCheck.isReadableStream; + exports.Uint8ArrayBlobAdapter = Uint8ArrayBlobAdapter2; + Object.prototype.hasOwnProperty.call(ChecksumStream, "__proto__") && !Object.prototype.hasOwnProperty.call(exports, "__proto__") && Object.defineProperty(exports, "__proto__", { + enumerable: true, + value: ChecksumStream["__proto__"] + }); + Object.keys(ChecksumStream).forEach(function(k5) { + if (k5 !== "default" && !Object.prototype.hasOwnProperty.call(exports, k5)) exports[k5] = ChecksumStream[k5]; + }); + Object.prototype.hasOwnProperty.call(createChecksumStream, "__proto__") && !Object.prototype.hasOwnProperty.call(exports, "__proto__") && Object.defineProperty(exports, "__proto__", { + enumerable: true, + value: createChecksumStream["__proto__"] + }); + Object.keys(createChecksumStream).forEach(function(k5) { + if (k5 !== "default" && !Object.prototype.hasOwnProperty.call(exports, k5)) exports[k5] = createChecksumStream[k5]; + }); + Object.prototype.hasOwnProperty.call(createBufferedReadable, "__proto__") && !Object.prototype.hasOwnProperty.call(exports, "__proto__") && Object.defineProperty(exports, "__proto__", { + enumerable: true, + value: createBufferedReadable["__proto__"] + }); + Object.keys(createBufferedReadable).forEach(function(k5) { + if (k5 !== "default" && !Object.prototype.hasOwnProperty.call(exports, k5)) exports[k5] = createBufferedReadable[k5]; + }); + Object.prototype.hasOwnProperty.call(getAwsChunkedEncodingStream, "__proto__") && !Object.prototype.hasOwnProperty.call(exports, "__proto__") && Object.defineProperty(exports, "__proto__", { + enumerable: true, + value: getAwsChunkedEncodingStream["__proto__"] + }); + Object.keys(getAwsChunkedEncodingStream).forEach(function(k5) { + if (k5 !== "default" && !Object.prototype.hasOwnProperty.call(exports, k5)) exports[k5] = getAwsChunkedEncodingStream[k5]; + }); + Object.prototype.hasOwnProperty.call(headStream, "__proto__") && !Object.prototype.hasOwnProperty.call(exports, "__proto__") && Object.defineProperty(exports, "__proto__", { + enumerable: true, + value: headStream["__proto__"] + }); + Object.keys(headStream).forEach(function(k5) { + if (k5 !== "default" && !Object.prototype.hasOwnProperty.call(exports, k5)) exports[k5] = headStream[k5]; + }); + Object.prototype.hasOwnProperty.call(sdkStreamMixin2, "__proto__") && !Object.prototype.hasOwnProperty.call(exports, "__proto__") && Object.defineProperty(exports, "__proto__", { + enumerable: true, + value: sdkStreamMixin2["__proto__"] + }); + Object.keys(sdkStreamMixin2).forEach(function(k5) { + if (k5 !== "default" && !Object.prototype.hasOwnProperty.call(exports, k5)) exports[k5] = sdkStreamMixin2[k5]; + }); + Object.prototype.hasOwnProperty.call(splitStream, "__proto__") && !Object.prototype.hasOwnProperty.call(exports, "__proto__") && Object.defineProperty(exports, "__proto__", { + enumerable: true, + value: splitStream["__proto__"] + }); + Object.keys(splitStream).forEach(function(k5) { + if (k5 !== "default" && !Object.prototype.hasOwnProperty.call(exports, k5)) exports[k5] = splitStream[k5]; + }); + } +}); + +// node_modules/.pnpm/tslib@2.8.1/node_modules/tslib/tslib.es6.mjs +var tslib_es6_exports = {}; +__export(tslib_es6_exports, { + __addDisposableResource: () => __addDisposableResource, + __assign: () => __assign, + __asyncDelegator: () => __asyncDelegator, + __asyncGenerator: () => __asyncGenerator, + __asyncValues: () => __asyncValues, + __await: () => __await, + __awaiter: () => __awaiter, + __classPrivateFieldGet: () => __classPrivateFieldGet, + __classPrivateFieldIn: () => __classPrivateFieldIn, + __classPrivateFieldSet: () => __classPrivateFieldSet, + __createBinding: () => __createBinding, + __decorate: () => __decorate, + __disposeResources: () => __disposeResources, + __esDecorate: () => __esDecorate, + __exportStar: () => __exportStar, + __extends: () => __extends, + __generator: () => __generator, + __importDefault: () => __importDefault, + __importStar: () => __importStar, + __makeTemplateObject: () => __makeTemplateObject, + __metadata: () => __metadata, + __param: () => __param, + __propKey: () => __propKey, + __read: () => __read, + __rest: () => __rest, + __rewriteRelativeImportExtension: () => __rewriteRelativeImportExtension, + __runInitializers: () => __runInitializers, + __setFunctionName: () => __setFunctionName, + __spread: () => __spread, + __spreadArray: () => __spreadArray, + __spreadArrays: () => __spreadArrays, + __values: () => __values, + default: () => tslib_es6_default +}); +function __extends(d5, b6) { + if (typeof b6 !== "function" && b6 !== null) + throw new TypeError("Class extends value " + String(b6) + " is not a constructor or null"); + extendStatics(d5, b6); + function __() { + this.constructor = d5; + } + d5.prototype = b6 === null ? Object.create(b6) : (__.prototype = b6.prototype, new __()); +} +function __rest(s5, e5) { + var t5 = {}; + for (var p5 in s5) if (Object.prototype.hasOwnProperty.call(s5, p5) && e5.indexOf(p5) < 0) + t5[p5] = s5[p5]; + if (s5 != null && typeof Object.getOwnPropertySymbols === "function") + for (var i5 = 0, p5 = Object.getOwnPropertySymbols(s5); i5 < p5.length; i5++) { + if (e5.indexOf(p5[i5]) < 0 && Object.prototype.propertyIsEnumerable.call(s5, p5[i5])) + t5[p5[i5]] = s5[p5[i5]]; + } + return t5; +} +function __decorate(decorators, target, key, desc3) { + var c5 = arguments.length, r5 = c5 < 3 ? target : desc3 === null ? desc3 = Object.getOwnPropertyDescriptor(target, key) : desc3, d5; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r5 = Reflect.decorate(decorators, target, key, desc3); + else for (var i5 = decorators.length - 1; i5 >= 0; i5--) if (d5 = decorators[i5]) r5 = (c5 < 3 ? d5(r5) : c5 > 3 ? d5(target, key, r5) : d5(target, key)) || r5; + return c5 > 3 && r5 && Object.defineProperty(target, key, r5), r5; +} +function __param(paramIndex, decorator) { + return function(target, key) { + decorator(target, key, paramIndex); + }; +} +function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { + function accept(f5) { + if (f5 !== void 0 && typeof f5 !== "function") throw new TypeError("Function expected"); + return f5; + } + var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; + var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; + var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); + var _, done = false; + for (var i5 = decorators.length - 1; i5 >= 0; i5--) { + var context = {}; + for (var p5 in contextIn) context[p5] = p5 === "access" ? {} : contextIn[p5]; + for (var p5 in contextIn.access) context.access[p5] = contextIn.access[p5]; + context.addInitializer = function(f5) { + if (done) throw new TypeError("Cannot add initializers after decoration has completed"); + extraInitializers.push(accept(f5 || null)); + }; + var result = (0, decorators[i5])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context); + if (kind === "accessor") { + if (result === void 0) continue; + if (result === null || typeof result !== "object") throw new TypeError("Object expected"); + if (_ = accept(result.get)) descriptor.get = _; + if (_ = accept(result.set)) descriptor.set = _; + if (_ = accept(result.init)) initializers.unshift(_); + } else if (_ = accept(result)) { + if (kind === "field") initializers.unshift(_); + else descriptor[key] = _; + } + } + if (target) Object.defineProperty(target, contextIn.name, descriptor); + done = true; +} +function __runInitializers(thisArg, initializers, value) { + var useValue = arguments.length > 2; + for (var i5 = 0; i5 < initializers.length; i5++) { + value = useValue ? initializers[i5].call(thisArg, value) : initializers[i5].call(thisArg); + } + return useValue ? value : void 0; +} +function __propKey(x5) { + return typeof x5 === "symbol" ? x5 : "".concat(x5); +} +function __setFunctionName(f5, name, prefix) { + if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : ""; + return Object.defineProperty(f5, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name }); +} +function __metadata(metadataKey, metadataValue) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); +} +function __awaiter(thisArg, _arguments, P, generator2) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve4) { + resolve4(value); + }); + } + return new (P || (P = Promise))(function(resolve4, reject) { + function fulfilled(value) { + try { + step(generator2.next(value)); + } catch (e5) { + reject(e5); + } + } + function rejected(value) { + try { + step(generator2["throw"](value)); + } catch (e5) { + reject(e5); + } + } + function step(result) { + result.done ? resolve4(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator2 = generator2.apply(thisArg, _arguments || [])).next()); + }); +} +function __generator(thisArg, body) { + var _ = { label: 0, sent: function() { + if (t5[0] & 1) throw t5[1]; + return t5[1]; + }, trys: [], ops: [] }, f5, y2, t5, g5 = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype); + return g5.next = verb(0), g5["throw"] = verb(1), g5["return"] = verb(2), typeof Symbol === "function" && (g5[Symbol.iterator] = function() { + return this; + }), g5; + function verb(n5) { + return function(v5) { + return step([n5, v5]); + }; + } + function step(op2) { + if (f5) throw new TypeError("Generator is already executing."); + while (g5 && (g5 = 0, op2[0] && (_ = 0)), _) try { + if (f5 = 1, y2 && (t5 = op2[0] & 2 ? y2["return"] : op2[0] ? y2["throw"] || ((t5 = y2["return"]) && t5.call(y2), 0) : y2.next) && !(t5 = t5.call(y2, op2[1])).done) return t5; + if (y2 = 0, t5) op2 = [op2[0] & 2, t5.value]; + switch (op2[0]) { + case 0: + case 1: + t5 = op2; + break; + case 4: + _.label++; + return { value: op2[1], done: false }; + case 5: + _.label++; + y2 = op2[1]; + op2 = [0]; + continue; + case 7: + op2 = _.ops.pop(); + _.trys.pop(); + continue; + default: + if (!(t5 = _.trys, t5 = t5.length > 0 && t5[t5.length - 1]) && (op2[0] === 6 || op2[0] === 2)) { + _ = 0; + continue; + } + if (op2[0] === 3 && (!t5 || op2[1] > t5[0] && op2[1] < t5[3])) { + _.label = op2[1]; + break; + } + if (op2[0] === 6 && _.label < t5[1]) { + _.label = t5[1]; + t5 = op2; + break; + } + if (t5 && _.label < t5[2]) { + _.label = t5[2]; + _.ops.push(op2); + break; + } + if (t5[2]) _.ops.pop(); + _.trys.pop(); + continue; + } + op2 = body.call(thisArg, _); + } catch (e5) { + op2 = [6, e5]; + y2 = 0; + } finally { + f5 = t5 = 0; + } + if (op2[0] & 5) throw op2[1]; + return { value: op2[0] ? op2[1] : void 0, done: true }; + } +} +function __exportStar(m5, o5) { + for (var p5 in m5) if (p5 !== "default" && !Object.prototype.hasOwnProperty.call(o5, p5)) __createBinding(o5, m5, p5); +} +function __values(o5) { + var s5 = typeof Symbol === "function" && Symbol.iterator, m5 = s5 && o5[s5], i5 = 0; + if (m5) return m5.call(o5); + if (o5 && typeof o5.length === "number") return { + next: function() { + if (o5 && i5 >= o5.length) o5 = void 0; + return { value: o5 && o5[i5++], done: !o5 }; + } + }; + throw new TypeError(s5 ? "Object is not iterable." : "Symbol.iterator is not defined."); +} +function __read(o5, n5) { + var m5 = typeof Symbol === "function" && o5[Symbol.iterator]; + if (!m5) return o5; + var i5 = m5.call(o5), r5, ar = [], e5; + try { + while ((n5 === void 0 || n5-- > 0) && !(r5 = i5.next()).done) ar.push(r5.value); + } catch (error50) { + e5 = { error: error50 }; + } finally { + try { + if (r5 && !r5.done && (m5 = i5["return"])) m5.call(i5); + } finally { + if (e5) throw e5.error; + } + } + return ar; +} +function __spread() { + for (var ar = [], i5 = 0; i5 < arguments.length; i5++) + ar = ar.concat(__read(arguments[i5])); + return ar; +} +function __spreadArrays() { + for (var s5 = 0, i5 = 0, il = arguments.length; i5 < il; i5++) s5 += arguments[i5].length; + for (var r5 = Array(s5), k5 = 0, i5 = 0; i5 < il; i5++) + for (var a5 = arguments[i5], j5 = 0, jl = a5.length; j5 < jl; j5++, k5++) + r5[k5] = a5[j5]; + return r5; +} +function __spreadArray(to, from, pack) { + if (pack || arguments.length === 2) for (var i5 = 0, l5 = from.length, ar; i5 < l5; i5++) { + if (ar || !(i5 in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i5); + ar[i5] = from[i5]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); +} +function __await(v5) { + return this instanceof __await ? (this.v = v5, this) : new __await(v5); +} +function __asyncGenerator(thisArg, _arguments, generator2) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g5 = generator2.apply(thisArg, _arguments || []), i5, q5 = []; + return i5 = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i5[Symbol.asyncIterator] = function() { + return this; + }, i5; + function awaitReturn(f5) { + return function(v5) { + return Promise.resolve(v5).then(f5, reject); + }; + } + function verb(n5, f5) { + if (g5[n5]) { + i5[n5] = function(v5) { + return new Promise(function(a5, b6) { + q5.push([n5, v5, a5, b6]) > 1 || resume(n5, v5); + }); + }; + if (f5) i5[n5] = f5(i5[n5]); + } + } + function resume(n5, v5) { + try { + step(g5[n5](v5)); + } catch (e5) { + settle(q5[0][3], e5); + } + } + function step(r5) { + r5.value instanceof __await ? Promise.resolve(r5.value.v).then(fulfill, reject) : settle(q5[0][2], r5); + } + function fulfill(value) { + resume("next", value); + } + function reject(value) { + resume("throw", value); + } + function settle(f5, v5) { + if (f5(v5), q5.shift(), q5.length) resume(q5[0][0], q5[0][1]); + } +} +function __asyncDelegator(o5) { + var i5, p5; + return i5 = {}, verb("next"), verb("throw", function(e5) { + throw e5; + }), verb("return"), i5[Symbol.iterator] = function() { + return this; + }, i5; + function verb(n5, f5) { + i5[n5] = o5[n5] ? function(v5) { + return (p5 = !p5) ? { value: __await(o5[n5](v5)), done: false } : f5 ? f5(v5) : v5; + } : f5; + } +} +function __asyncValues(o5) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m5 = o5[Symbol.asyncIterator], i5; + return m5 ? m5.call(o5) : (o5 = typeof __values === "function" ? __values(o5) : o5[Symbol.iterator](), i5 = {}, verb("next"), verb("throw"), verb("return"), i5[Symbol.asyncIterator] = function() { + return this; + }, i5); + function verb(n5) { + i5[n5] = o5[n5] && function(v5) { + return new Promise(function(resolve4, reject) { + v5 = o5[n5](v5), settle(resolve4, reject, v5.done, v5.value); + }); + }; + } + function settle(resolve4, reject, d5, v5) { + Promise.resolve(v5).then(function(v6) { + resolve4({ value: v6, done: d5 }); + }, reject); + } +} +function __makeTemplateObject(cooked, raw) { + if (Object.defineProperty) { + Object.defineProperty(cooked, "raw", { value: raw }); + } else { + cooked.raw = raw; + } + return cooked; +} +function __importStar(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k5 = ownKeys(mod), i5 = 0; i5 < k5.length; i5++) if (k5[i5] !== "default") __createBinding(result, mod, k5[i5]); + } + __setModuleDefault(result, mod); + return result; +} +function __importDefault(mod) { + return mod && mod.__esModule ? mod : { default: mod }; +} +function __classPrivateFieldGet(receiver, state2, kind, f5) { + if (kind === "a" && !f5) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state2 === "function" ? receiver !== state2 || !f5 : !state2.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f5 : kind === "a" ? f5.call(receiver) : f5 ? f5.value : state2.get(receiver); +} +function __classPrivateFieldSet(receiver, state2, value, kind, f5) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f5) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state2 === "function" ? receiver !== state2 || !f5 : !state2.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return kind === "a" ? f5.call(receiver, value) : f5 ? f5.value = value : state2.set(receiver, value), value; +} +function __classPrivateFieldIn(state2, receiver) { + if (receiver === null || typeof receiver !== "object" && typeof receiver !== "function") throw new TypeError("Cannot use 'in' operator on non-object"); + return typeof state2 === "function" ? receiver === state2 : state2.has(receiver); +} +function __addDisposableResource(env2, value, async) { + if (value !== null && value !== void 0) { + if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected."); + var dispose, inner; + if (async) { + if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); + dispose = value[Symbol.asyncDispose]; + } + if (dispose === void 0) { + if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); + dispose = value[Symbol.dispose]; + if (async) inner = dispose; + } + if (typeof dispose !== "function") throw new TypeError("Object not disposable."); + if (inner) dispose = function() { + try { + inner.call(this); + } catch (e5) { + return Promise.reject(e5); + } + }; + env2.stack.push({ value, dispose, async }); + } else if (async) { + env2.stack.push({ async: true }); + } + return value; +} +function __disposeResources(env2) { + function fail(e5) { + env2.error = env2.hasError ? new _SuppressedError(e5, env2.error, "An error was suppressed during disposal.") : e5; + env2.hasError = true; + } + var r5, s5 = 0; + function next() { + while (r5 = env2.stack.pop()) { + try { + if (!r5.async && s5 === 1) return s5 = 0, env2.stack.push(r5), Promise.resolve().then(next); + if (r5.dispose) { + var result = r5.dispose.call(r5.value); + if (r5.async) return s5 |= 2, Promise.resolve(result).then(next, function(e5) { + fail(e5); + return next(); + }); + } else s5 |= 1; + } catch (e5) { + fail(e5); + } + } + if (s5 === 1) return env2.hasError ? Promise.reject(env2.error) : Promise.resolve(); + if (env2.hasError) throw env2.error; + } + return next(); +} +function __rewriteRelativeImportExtension(path53, preserveJsx) { + if (typeof path53 === "string" && /^\.\.?\//.test(path53)) { + return path53.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function(m5, tsx, d5, ext, cm) { + return tsx ? preserveJsx ? ".jsx" : ".js" : d5 && (!ext || !cm) ? m5 : d5 + ext + "." + cm.toLowerCase() + "js"; + }); + } + return path53; +} +var extendStatics, __assign, __createBinding, __setModuleDefault, ownKeys, _SuppressedError, tslib_es6_default; +var init_tslib_es6 = __esm({ + "node_modules/.pnpm/tslib@2.8.1/node_modules/tslib/tslib.es6.mjs"() { + extendStatics = function(d5, b6) { + extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d6, b7) { + d6.__proto__ = b7; + } || function(d6, b7) { + for (var p5 in b7) if (Object.prototype.hasOwnProperty.call(b7, p5)) d6[p5] = b7[p5]; + }; + return extendStatics(d5, b6); + }; + __assign = function() { + __assign = Object.assign || function __assign2(t5) { + for (var s5, i5 = 1, n5 = arguments.length; i5 < n5; i5++) { + s5 = arguments[i5]; + for (var p5 in s5) if (Object.prototype.hasOwnProperty.call(s5, p5)) t5[p5] = s5[p5]; + } + return t5; + }; + return __assign.apply(this, arguments); + }; + __createBinding = Object.create ? (function(o5, m5, k5, k22) { + if (k22 === void 0) k22 = k5; + var desc3 = Object.getOwnPropertyDescriptor(m5, k5); + if (!desc3 || ("get" in desc3 ? !m5.__esModule : desc3.writable || desc3.configurable)) { + desc3 = { enumerable: true, get: function() { + return m5[k5]; + } }; + } + Object.defineProperty(o5, k22, desc3); + }) : (function(o5, m5, k5, k22) { + if (k22 === void 0) k22 = k5; + o5[k22] = m5[k5]; + }); + __setModuleDefault = Object.create ? (function(o5, v5) { + Object.defineProperty(o5, "default", { enumerable: true, value: v5 }); + }) : function(o5, v5) { + o5["default"] = v5; + }; + ownKeys = function(o5) { + ownKeys = Object.getOwnPropertyNames || function(o6) { + var ar = []; + for (var k5 in o6) if (Object.prototype.hasOwnProperty.call(o6, k5)) ar[ar.length] = k5; + return ar; + }; + return ownKeys(o5); + }; + _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function(error50, suppressed, message2) { + var e5 = new Error(message2); + return e5.name = "SuppressedError", e5.error = error50, e5.suppressed = suppressed, e5; + }; + tslib_es6_default = { + __extends, + __assign, + __rest, + __decorate, + __param, + __esDecorate, + __runInitializers, + __propKey, + __setFunctionName, + __metadata, + __awaiter, + __generator, + __createBinding, + __exportStar, + __values, + __read, + __spread, + __spreadArrays, + __spreadArray, + __await, + __asyncGenerator, + __asyncDelegator, + __asyncValues, + __makeTemplateObject, + __importStar, + __importDefault, + __classPrivateFieldGet, + __classPrivateFieldSet, + __classPrivateFieldIn, + __addDisposableResource, + __disposeResources, + __rewriteRelativeImportExtension + }; + } +}); + +// node_modules/.pnpm/@smithy+is-array-buffer@2.2.0/node_modules/@smithy/is-array-buffer/dist-cjs/index.js +var require_dist_cjs14 = __commonJS({ + "node_modules/.pnpm/@smithy+is-array-buffer@2.2.0/node_modules/@smithy/is-array-buffer/dist-cjs/index.js"(exports, module) { + var __defProp4 = Object.defineProperty; + var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp4 = Object.prototype.hasOwnProperty; + var __name = (target, value) => __defProp4(target, "name", { value, configurable: true }); + var __export3 = (target, all) => { + for (var name in all) + __defProp4(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps3 = (to, from, except2, desc3) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp4.call(to, key) && key !== except2) + __defProp4(to, key, { get: () => from[key], enumerable: !(desc3 = __getOwnPropDesc3(from, key)) || desc3.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps3(__defProp4({}, "__esModule", { value: true }), mod); + var src_exports = {}; + __export3(src_exports, { + isArrayBuffer: () => isArrayBuffer + }); + module.exports = __toCommonJS2(src_exports); + var isArrayBuffer = /* @__PURE__ */ __name((arg) => typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer || Object.prototype.toString.call(arg) === "[object ArrayBuffer]", "isArrayBuffer"); + } +}); + +// node_modules/.pnpm/@smithy+util-buffer-from@2.2.0/node_modules/@smithy/util-buffer-from/dist-cjs/index.js +var require_dist_cjs15 = __commonJS({ + "node_modules/.pnpm/@smithy+util-buffer-from@2.2.0/node_modules/@smithy/util-buffer-from/dist-cjs/index.js"(exports, module) { + var __defProp4 = Object.defineProperty; + var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp4 = Object.prototype.hasOwnProperty; + var __name = (target, value) => __defProp4(target, "name", { value, configurable: true }); + var __export3 = (target, all) => { + for (var name in all) + __defProp4(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps3 = (to, from, except2, desc3) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp4.call(to, key) && key !== except2) + __defProp4(to, key, { get: () => from[key], enumerable: !(desc3 = __getOwnPropDesc3(from, key)) || desc3.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps3(__defProp4({}, "__esModule", { value: true }), mod); + var src_exports = {}; + __export3(src_exports, { + fromArrayBuffer: () => fromArrayBuffer, + fromString: () => fromString + }); + module.exports = __toCommonJS2(src_exports); + var import_is_array_buffer = require_dist_cjs14(); + var import_buffer3 = __require("buffer"); + var fromArrayBuffer = /* @__PURE__ */ __name((input, offset = 0, length = input.byteLength - offset) => { + if (!(0, import_is_array_buffer.isArrayBuffer)(input)) { + throw new TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof input} (${input})`); + } + return import_buffer3.Buffer.from(input, offset, length); + }, "fromArrayBuffer"); + var fromString = /* @__PURE__ */ __name((input, encoding) => { + if (typeof input !== "string") { + throw new TypeError(`The "input" argument must be of type string. Received type ${typeof input} (${input})`); + } + return encoding ? import_buffer3.Buffer.from(input, encoding) : import_buffer3.Buffer.from(input); + }, "fromString"); + } +}); + +// node_modules/.pnpm/@smithy+util-utf8@2.3.0/node_modules/@smithy/util-utf8/dist-cjs/index.js +var require_dist_cjs16 = __commonJS({ + "node_modules/.pnpm/@smithy+util-utf8@2.3.0/node_modules/@smithy/util-utf8/dist-cjs/index.js"(exports, module) { + var __defProp4 = Object.defineProperty; + var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor; + var __getOwnPropNames3 = Object.getOwnPropertyNames; + var __hasOwnProp4 = Object.prototype.hasOwnProperty; + var __name = (target, value) => __defProp4(target, "name", { value, configurable: true }); + var __export3 = (target, all) => { + for (var name in all) + __defProp4(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps3 = (to, from, except2, desc3) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames3(from)) + if (!__hasOwnProp4.call(to, key) && key !== except2) + __defProp4(to, key, { get: () => from[key], enumerable: !(desc3 = __getOwnPropDesc3(from, key)) || desc3.enumerable }); + } + return to; + }; + var __toCommonJS2 = (mod) => __copyProps3(__defProp4({}, "__esModule", { value: true }), mod); + var src_exports = {}; + __export3(src_exports, { + fromUtf8: () => fromUtf88, + toUint8Array: () => toUint8Array2, + toUtf8: () => toUtf811 + }); + module.exports = __toCommonJS2(src_exports); + var import_util_buffer_from = require_dist_cjs15(); + var fromUtf88 = /* @__PURE__ */ __name((input) => { + const buf = (0, import_util_buffer_from.fromString)(input, "utf8"); + return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength / Uint8Array.BYTES_PER_ELEMENT); + }, "fromUtf8"); + var toUint8Array2 = /* @__PURE__ */ __name((data2) => { + if (typeof data2 === "string") { + return fromUtf88(data2); + } + if (ArrayBuffer.isView(data2)) { + return new Uint8Array(data2.buffer, data2.byteOffset, data2.byteLength / Uint8Array.BYTES_PER_ELEMENT); + } + return new Uint8Array(data2); + }, "toUint8Array"); + var toUtf811 = /* @__PURE__ */ __name((input) => { + if (typeof input === "string") { + return input; + } + if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") { + throw new Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array."); + } + return (0, import_util_buffer_from.fromArrayBuffer)(input.buffer, input.byteOffset, input.byteLength).toString("utf8"); + }, "toUtf8"); + } +}); + +// node_modules/.pnpm/@aws-crypto+util@5.2.0/node_modules/@aws-crypto/util/build/main/convertToBuffer.js +var require_convertToBuffer = __commonJS({ + "node_modules/.pnpm/@aws-crypto+util@5.2.0/node_modules/@aws-crypto/util/build/main/convertToBuffer.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.convertToBuffer = void 0; + var util_utf8_1 = require_dist_cjs16(); + var fromUtf88 = typeof Buffer !== "undefined" && Buffer.from ? function(input) { + return Buffer.from(input, "utf8"); + } : util_utf8_1.fromUtf8; + function convertToBuffer(data2) { + if (data2 instanceof Uint8Array) + return data2; + if (typeof data2 === "string") { + return fromUtf88(data2); + } + if (ArrayBuffer.isView(data2)) { + return new Uint8Array(data2.buffer, data2.byteOffset, data2.byteLength / Uint8Array.BYTES_PER_ELEMENT); + } + return new Uint8Array(data2); + } + exports.convertToBuffer = convertToBuffer; + } +}); + +// node_modules/.pnpm/@aws-crypto+util@5.2.0/node_modules/@aws-crypto/util/build/main/isEmptyData.js +var require_isEmptyData = __commonJS({ + "node_modules/.pnpm/@aws-crypto+util@5.2.0/node_modules/@aws-crypto/util/build/main/isEmptyData.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.isEmptyData = void 0; + function isEmptyData(data2) { + if (typeof data2 === "string") { + return data2.length === 0; + } + return data2.byteLength === 0; + } + exports.isEmptyData = isEmptyData; + } +}); + +// node_modules/.pnpm/@aws-crypto+util@5.2.0/node_modules/@aws-crypto/util/build/main/numToUint8.js +var require_numToUint8 = __commonJS({ + "node_modules/.pnpm/@aws-crypto+util@5.2.0/node_modules/@aws-crypto/util/build/main/numToUint8.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.numToUint8 = void 0; + function numToUint8(num) { + return new Uint8Array([ + (num & 4278190080) >> 24, + (num & 16711680) >> 16, + (num & 65280) >> 8, + num & 255 + ]); + } + exports.numToUint8 = numToUint8; + } +}); + +// node_modules/.pnpm/@aws-crypto+util@5.2.0/node_modules/@aws-crypto/util/build/main/uint32ArrayFrom.js +var require_uint32ArrayFrom = __commonJS({ + "node_modules/.pnpm/@aws-crypto+util@5.2.0/node_modules/@aws-crypto/util/build/main/uint32ArrayFrom.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.uint32ArrayFrom = void 0; + function uint32ArrayFrom(a_lookUpTable) { + if (!Uint32Array.from) { + var return_array = new Uint32Array(a_lookUpTable.length); + var a_index = 0; + while (a_index < a_lookUpTable.length) { + return_array[a_index] = a_lookUpTable[a_index]; + a_index += 1; + } + return return_array; + } + return Uint32Array.from(a_lookUpTable); + } + exports.uint32ArrayFrom = uint32ArrayFrom; + } +}); + +// node_modules/.pnpm/@aws-crypto+util@5.2.0/node_modules/@aws-crypto/util/build/main/index.js +var require_main2 = __commonJS({ + "node_modules/.pnpm/@aws-crypto+util@5.2.0/node_modules/@aws-crypto/util/build/main/index.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.uint32ArrayFrom = exports.numToUint8 = exports.isEmptyData = exports.convertToBuffer = void 0; + var convertToBuffer_1 = require_convertToBuffer(); + Object.defineProperty(exports, "convertToBuffer", { enumerable: true, get: function() { + return convertToBuffer_1.convertToBuffer; + } }); + var isEmptyData_1 = require_isEmptyData(); + Object.defineProperty(exports, "isEmptyData", { enumerable: true, get: function() { + return isEmptyData_1.isEmptyData; + } }); + var numToUint8_1 = require_numToUint8(); + Object.defineProperty(exports, "numToUint8", { enumerable: true, get: function() { + return numToUint8_1.numToUint8; + } }); + var uint32ArrayFrom_1 = require_uint32ArrayFrom(); + Object.defineProperty(exports, "uint32ArrayFrom", { enumerable: true, get: function() { + return uint32ArrayFrom_1.uint32ArrayFrom; + } }); + } +}); + +// node_modules/.pnpm/@aws-crypto+crc32c@5.2.0/node_modules/@aws-crypto/crc32c/build/main/aws_crc32c.js +var require_aws_crc32c = __commonJS({ + "node_modules/.pnpm/@aws-crypto+crc32c@5.2.0/node_modules/@aws-crypto/crc32c/build/main/aws_crc32c.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AwsCrc32c = void 0; + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var util_1 = require_main2(); + var index_1 = require_main3(); + var AwsCrc32c = ( + /** @class */ + (function() { + function AwsCrc32c2() { + this.crc32c = new index_1.Crc32c(); + } + AwsCrc32c2.prototype.update = function(toHash) { + if ((0, util_1.isEmptyData)(toHash)) + return; + this.crc32c.update((0, util_1.convertToBuffer)(toHash)); + }; + AwsCrc32c2.prototype.digest = function() { + return tslib_1.__awaiter(this, void 0, void 0, function() { + return tslib_1.__generator(this, function(_a6) { + return [2, (0, util_1.numToUint8)(this.crc32c.digest())]; + }); + }); + }; + AwsCrc32c2.prototype.reset = function() { + this.crc32c = new index_1.Crc32c(); + }; + return AwsCrc32c2; + })() + ); + exports.AwsCrc32c = AwsCrc32c; + } +}); + +// node_modules/.pnpm/@aws-crypto+crc32c@5.2.0/node_modules/@aws-crypto/crc32c/build/main/index.js +var require_main3 = __commonJS({ + "node_modules/.pnpm/@aws-crypto+crc32c@5.2.0/node_modules/@aws-crypto/crc32c/build/main/index.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AwsCrc32c = exports.Crc32c = exports.crc32c = void 0; + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var util_1 = require_main2(); + function crc32c(data2) { + return new Crc32c().update(data2).digest(); + } + exports.crc32c = crc32c; + var Crc32c = ( + /** @class */ + (function() { + function Crc32c2() { + this.checksum = 4294967295; + } + Crc32c2.prototype.update = function(data2) { + var e_1, _a6; + try { + for (var data_1 = tslib_1.__values(data2), data_1_1 = data_1.next(); !data_1_1.done; data_1_1 = data_1.next()) { + var byte = data_1_1.value; + this.checksum = this.checksum >>> 8 ^ lookupTable[(this.checksum ^ byte) & 255]; + } + } catch (e_1_1) { + e_1 = { error: e_1_1 }; + } finally { + try { + if (data_1_1 && !data_1_1.done && (_a6 = data_1.return)) _a6.call(data_1); + } finally { + if (e_1) throw e_1.error; + } + } + return this; + }; + Crc32c2.prototype.digest = function() { + return (this.checksum ^ 4294967295) >>> 0; + }; + return Crc32c2; + })() + ); + exports.Crc32c = Crc32c; + var a_lookupTable = [ + 0, + 4067132163, + 3778769143, + 324072436, + 3348797215, + 904991772, + 648144872, + 3570033899, + 2329499855, + 2024987596, + 1809983544, + 2575936315, + 1296289744, + 3207089363, + 2893594407, + 1578318884, + 274646895, + 3795141740, + 4049975192, + 51262619, + 3619967088, + 632279923, + 922689671, + 3298075524, + 2592579488, + 1760304291, + 2075979607, + 2312596564, + 1562183871, + 2943781820, + 3156637768, + 1313733451, + 549293790, + 3537243613, + 3246849577, + 871202090, + 3878099393, + 357341890, + 102525238, + 4101499445, + 2858735121, + 1477399826, + 1264559846, + 3107202533, + 1845379342, + 2677391885, + 2361733625, + 2125378298, + 820201905, + 3263744690, + 3520608582, + 598981189, + 4151959214, + 85089709, + 373468761, + 3827903834, + 3124367742, + 1213305469, + 1526817161, + 2842354314, + 2107672161, + 2412447074, + 2627466902, + 1861252501, + 1098587580, + 3004210879, + 2688576843, + 1378610760, + 2262928035, + 1955203488, + 1742404180, + 2511436119, + 3416409459, + 969524848, + 714683780, + 3639785095, + 205050476, + 4266873199, + 3976438427, + 526918040, + 1361435347, + 2739821008, + 2954799652, + 1114974503, + 2529119692, + 1691668175, + 2005155131, + 2247081528, + 3690758684, + 697762079, + 986182379, + 3366744552, + 476452099, + 3993867776, + 4250756596, + 255256311, + 1640403810, + 2477592673, + 2164122517, + 1922457750, + 2791048317, + 1412925310, + 1197962378, + 3037525897, + 3944729517, + 427051182, + 170179418, + 4165941337, + 746937522, + 3740196785, + 3451792453, + 1070968646, + 1905808397, + 2213795598, + 2426610938, + 1657317369, + 3053634322, + 1147748369, + 1463399397, + 2773627110, + 4215344322, + 153784257, + 444234805, + 3893493558, + 1021025245, + 3467647198, + 3722505002, + 797665321, + 2197175160, + 1889384571, + 1674398607, + 2443626636, + 1164749927, + 3070701412, + 2757221520, + 1446797203, + 137323447, + 4198817972, + 3910406976, + 461344835, + 3484808360, + 1037989803, + 781091935, + 3705997148, + 2460548119, + 1623424788, + 1939049696, + 2180517859, + 1429367560, + 2807687179, + 3020495871, + 1180866812, + 410100952, + 3927582683, + 4182430767, + 186734380, + 3756733383, + 763408580, + 1053836080, + 3434856499, + 2722870694, + 1344288421, + 1131464017, + 2971354706, + 1708204729, + 2545590714, + 2229949006, + 1988219213, + 680717673, + 3673779818, + 3383336350, + 1002577565, + 4010310262, + 493091189, + 238226049, + 4233660802, + 2987750089, + 1082061258, + 1395524158, + 2705686845, + 1972364758, + 2279892693, + 2494862625, + 1725896226, + 952904198, + 3399985413, + 3656866545, + 731699698, + 4283874585, + 222117402, + 510512622, + 3959836397, + 3280807620, + 837199303, + 582374963, + 3504198960, + 68661723, + 4135334616, + 3844915500, + 390545967, + 1230274059, + 3141532936, + 2825850620, + 1510247935, + 2395924756, + 2091215383, + 1878366691, + 2644384480, + 3553878443, + 565732008, + 854102364, + 3229815391, + 340358836, + 3861050807, + 4117890627, + 119113024, + 1493875044, + 2875275879, + 3090270611, + 1247431312, + 2660249211, + 1828433272, + 2141937292, + 2378227087, + 3811616794, + 291187481, + 34330861, + 4032846830, + 615137029, + 3603020806, + 3314634738, + 939183345, + 1776939221, + 2609017814, + 2295496738, + 2058945313, + 2926798794, + 1545135305, + 1330124605, + 3173225534, + 4084100981, + 17165430, + 307568514, + 3762199681, + 888469610, + 3332340585, + 3587147933, + 665062302, + 2042050490, + 2346497209, + 2559330125, + 1793573966, + 3190661285, + 1279665062, + 1595330642, + 2910671697 + ]; + var lookupTable = (0, util_1.uint32ArrayFrom)(a_lookupTable); + var aws_crc32c_1 = require_aws_crc32c(); + Object.defineProperty(exports, "AwsCrc32c", { enumerable: true, get: function() { + return aws_crc32c_1.AwsCrc32c; + } }); + } +}); + +// node_modules/.pnpm/@aws-sdk+crc64-nvme@3.972.6/node_modules/@aws-sdk/crc64-nvme/dist-cjs/index.js +var require_dist_cjs17 = __commonJS({ + "node_modules/.pnpm/@aws-sdk+crc64-nvme@3.972.6/node_modules/@aws-sdk/crc64-nvme/dist-cjs/index.js"(exports) { + "use strict"; + var generateCRC64NVMETable = () => { + const sliceLength = 8; + const tables = new Array(sliceLength); + for (let slice = 0; slice < sliceLength; slice++) { + const table = new Array(512); + for (let i5 = 0; i5 < 256; i5++) { + let crc = BigInt(i5); + for (let j5 = 0; j5 < 8 * (slice + 1); j5++) { + if (crc & 1n) { + crc = crc >> 1n ^ 0x9a6c9329ac4bc9b5n; + } else { + crc = crc >> 1n; + } + } + table[i5 * 2] = Number(crc >> 32n & 0xffffffffn); + table[i5 * 2 + 1] = Number(crc & 0xffffffffn); + } + tables[slice] = new Uint32Array(table); + } + return tables; + }; + var CRC64_NVME_REVERSED_TABLE; + var t0; + var t1; + var t22; + var t32; + var t42; + var t5; + var t6; + var t7; + var ensureTablesInitialized = () => { + if (!CRC64_NVME_REVERSED_TABLE) { + CRC64_NVME_REVERSED_TABLE = generateCRC64NVMETable(); + [t0, t1, t22, t32, t42, t5, t6, t7] = CRC64_NVME_REVERSED_TABLE; + } + }; + var Crc64Nvme = class { + c1 = 0; + c2 = 0; + constructor() { + ensureTablesInitialized(); + this.reset(); + } + update(data2) { + const len = data2.length; + let i5 = 0; + let crc1 = this.c1; + let crc2 = this.c2; + while (i5 + 8 <= len) { + const idx0 = ((crc2 ^ data2[i5++]) & 255) << 1; + const idx1 = ((crc2 >>> 8 ^ data2[i5++]) & 255) << 1; + const idx2 = ((crc2 >>> 16 ^ data2[i5++]) & 255) << 1; + const idx3 = ((crc2 >>> 24 ^ data2[i5++]) & 255) << 1; + const idx4 = ((crc1 ^ data2[i5++]) & 255) << 1; + const idx5 = ((crc1 >>> 8 ^ data2[i5++]) & 255) << 1; + const idx6 = ((crc1 >>> 16 ^ data2[i5++]) & 255) << 1; + const idx7 = ((crc1 >>> 24 ^ data2[i5++]) & 255) << 1; + crc1 = t7[idx0] ^ t6[idx1] ^ t5[idx2] ^ t42[idx3] ^ t32[idx4] ^ t22[idx5] ^ t1[idx6] ^ t0[idx7]; + crc2 = t7[idx0 + 1] ^ t6[idx1 + 1] ^ t5[idx2 + 1] ^ t42[idx3 + 1] ^ t32[idx4 + 1] ^ t22[idx5 + 1] ^ t1[idx6 + 1] ^ t0[idx7 + 1]; + } + while (i5 < len) { + const idx = ((crc2 ^ data2[i5]) & 255) << 1; + crc2 = (crc2 >>> 8 | (crc1 & 255) << 24) >>> 0; + crc1 = crc1 >>> 8 ^ t0[idx]; + crc2 ^= t0[idx + 1]; + i5++; + } + this.c1 = crc1; + this.c2 = crc2; + } + async digest() { + const c1 = this.c1 ^ 4294967295; + const c22 = this.c2 ^ 4294967295; + return new Uint8Array([ + c1 >>> 24, + c1 >>> 16 & 255, + c1 >>> 8 & 255, + c1 & 255, + c22 >>> 24, + c22 >>> 16 & 255, + c22 >>> 8 & 255, + c22 & 255 + ]); + } + reset() { + this.c1 = 4294967295; + this.c2 = 4294967295; + } + }; + var crc64NvmeCrtContainer = { + CrtCrc64Nvme: null + }; + exports.Crc64Nvme = Crc64Nvme; + exports.crc64NvmeCrtContainer = crc64NvmeCrtContainer; + } +}); + +// node_modules/.pnpm/@aws-crypto+crc32@5.2.0/node_modules/@aws-crypto/crc32/build/main/aws_crc32.js +var require_aws_crc32 = __commonJS({ + "node_modules/.pnpm/@aws-crypto+crc32@5.2.0/node_modules/@aws-crypto/crc32/build/main/aws_crc32.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AwsCrc32 = void 0; + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var util_1 = require_main2(); + var index_1 = require_main4(); + var AwsCrc32 = ( + /** @class */ + (function() { + function AwsCrc322() { + this.crc32 = new index_1.Crc32(); + } + AwsCrc322.prototype.update = function(toHash) { + if ((0, util_1.isEmptyData)(toHash)) + return; + this.crc32.update((0, util_1.convertToBuffer)(toHash)); + }; + AwsCrc322.prototype.digest = function() { + return tslib_1.__awaiter(this, void 0, void 0, function() { + return tslib_1.__generator(this, function(_a6) { + return [2, (0, util_1.numToUint8)(this.crc32.digest())]; + }); + }); + }; + AwsCrc322.prototype.reset = function() { + this.crc32 = new index_1.Crc32(); + }; + return AwsCrc322; + })() + ); + exports.AwsCrc32 = AwsCrc32; + } +}); + +// node_modules/.pnpm/@aws-crypto+crc32@5.2.0/node_modules/@aws-crypto/crc32/build/main/index.js +var require_main4 = __commonJS({ + "node_modules/.pnpm/@aws-crypto+crc32@5.2.0/node_modules/@aws-crypto/crc32/build/main/index.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AwsCrc32 = exports.Crc32 = exports.crc32 = void 0; + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var util_1 = require_main2(); + function crc32(data2) { + return new Crc32().update(data2).digest(); + } + exports.crc32 = crc32; + var Crc32 = ( + /** @class */ + (function() { + function Crc322() { + this.checksum = 4294967295; + } + Crc322.prototype.update = function(data2) { + var e_1, _a6; + try { + for (var data_1 = tslib_1.__values(data2), data_1_1 = data_1.next(); !data_1_1.done; data_1_1 = data_1.next()) { + var byte = data_1_1.value; + this.checksum = this.checksum >>> 8 ^ lookupTable[(this.checksum ^ byte) & 255]; + } + } catch (e_1_1) { + e_1 = { error: e_1_1 }; + } finally { + try { + if (data_1_1 && !data_1_1.done && (_a6 = data_1.return)) _a6.call(data_1); + } finally { + if (e_1) throw e_1.error; + } + } + return this; + }; + Crc322.prototype.digest = function() { + return (this.checksum ^ 4294967295) >>> 0; + }; + return Crc322; + })() + ); + exports.Crc32 = Crc32; + var a_lookUpTable = [ + 0, + 1996959894, + 3993919788, + 2567524794, + 124634137, + 1886057615, + 3915621685, + 2657392035, + 249268274, + 2044508324, + 3772115230, + 2547177864, + 162941995, + 2125561021, + 3887607047, + 2428444049, + 498536548, + 1789927666, + 4089016648, + 2227061214, + 450548861, + 1843258603, + 4107580753, + 2211677639, + 325883990, + 1684777152, + 4251122042, + 2321926636, + 335633487, + 1661365465, + 4195302755, + 2366115317, + 997073096, + 1281953886, + 3579855332, + 2724688242, + 1006888145, + 1258607687, + 3524101629, + 2768942443, + 901097722, + 1119000684, + 3686517206, + 2898065728, + 853044451, + 1172266101, + 3705015759, + 2882616665, + 651767980, + 1373503546, + 3369554304, + 3218104598, + 565507253, + 1454621731, + 3485111705, + 3099436303, + 671266974, + 1594198024, + 3322730930, + 2970347812, + 795835527, + 1483230225, + 3244367275, + 3060149565, + 1994146192, + 31158534, + 2563907772, + 4023717930, + 1907459465, + 112637215, + 2680153253, + 3904427059, + 2013776290, + 251722036, + 2517215374, + 3775830040, + 2137656763, + 141376813, + 2439277719, + 3865271297, + 1802195444, + 476864866, + 2238001368, + 4066508878, + 1812370925, + 453092731, + 2181625025, + 4111451223, + 1706088902, + 314042704, + 2344532202, + 4240017532, + 1658658271, + 366619977, + 2362670323, + 4224994405, + 1303535960, + 984961486, + 2747007092, + 3569037538, + 1256170817, + 1037604311, + 2765210733, + 3554079995, + 1131014506, + 879679996, + 2909243462, + 3663771856, + 1141124467, + 855842277, + 2852801631, + 3708648649, + 1342533948, + 654459306, + 3188396048, + 3373015174, + 1466479909, + 544179635, + 3110523913, + 3462522015, + 1591671054, + 702138776, + 2966460450, + 3352799412, + 1504918807, + 783551873, + 3082640443, + 3233442989, + 3988292384, + 2596254646, + 62317068, + 1957810842, + 3939845945, + 2647816111, + 81470997, + 1943803523, + 3814918930, + 2489596804, + 225274430, + 2053790376, + 3826175755, + 2466906013, + 167816743, + 2097651377, + 4027552580, + 2265490386, + 503444072, + 1762050814, + 4150417245, + 2154129355, + 426522225, + 1852507879, + 4275313526, + 2312317920, + 282753626, + 1742555852, + 4189708143, + 2394877945, + 397917763, + 1622183637, + 3604390888, + 2714866558, + 953729732, + 1340076626, + 3518719985, + 2797360999, + 1068828381, + 1219638859, + 3624741850, + 2936675148, + 906185462, + 1090812512, + 3747672003, + 2825379669, + 829329135, + 1181335161, + 3412177804, + 3160834842, + 628085408, + 1382605366, + 3423369109, + 3138078467, + 570562233, + 1426400815, + 3317316542, + 2998733608, + 733239954, + 1555261956, + 3268935591, + 3050360625, + 752459403, + 1541320221, + 2607071920, + 3965973030, + 1969922972, + 40735498, + 2617837225, + 3943577151, + 1913087877, + 83908371, + 2512341634, + 3803740692, + 2075208622, + 213261112, + 2463272603, + 3855990285, + 2094854071, + 198958881, + 2262029012, + 4057260610, + 1759359992, + 534414190, + 2176718541, + 4139329115, + 1873836001, + 414664567, + 2282248934, + 4279200368, + 1711684554, + 285281116, + 2405801727, + 4167216745, + 1634467795, + 376229701, + 2685067896, + 3608007406, + 1308918612, + 956543938, + 2808555105, + 3495958263, + 1231636301, + 1047427035, + 2932959818, + 3654703836, + 1088359270, + 936918e3, + 2847714899, + 3736837829, + 1202900863, + 817233897, + 3183342108, + 3401237130, + 1404277552, + 615818150, + 3134207493, + 3453421203, + 1423857449, + 601450431, + 3009837614, + 3294710456, + 1567103746, + 711928724, + 3020668471, + 3272380065, + 1510334235, + 755167117 + ]; + var lookupTable = (0, util_1.uint32ArrayFrom)(a_lookUpTable); + var aws_crc32_1 = require_aws_crc32(); + Object.defineProperty(exports, "AwsCrc32", { enumerable: true, get: function() { + return aws_crc32_1.AwsCrc32; + } }); + } +}); + +// node_modules/.pnpm/@aws-sdk+middleware-flexible-checksums@3.974.7/node_modules/@aws-sdk/middleware-flexible-checksums/dist-cjs/getCrc32ChecksumAlgorithmFunction.js +var require_getCrc32ChecksumAlgorithmFunction = __commonJS({ + "node_modules/.pnpm/@aws-sdk+middleware-flexible-checksums@3.974.7/node_modules/@aws-sdk/middleware-flexible-checksums/dist-cjs/getCrc32ChecksumAlgorithmFunction.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getCrc32ChecksumAlgorithmFunction = void 0; + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var crc32_1 = require_main4(); + var util_1 = require_main2(); + var zlib = tslib_1.__importStar(__require("node:zlib")); + var NodeCrc32 = class { + checksum = 0; + update(data2) { + this.checksum = zlib.crc32(data2, this.checksum); + } + async digest() { + return (0, util_1.numToUint8)(this.checksum); + } + reset() { + this.checksum = 0; + } + }; + var getCrc32ChecksumAlgorithmFunction = () => { + if (typeof zlib.crc32 === "undefined") { + return crc32_1.AwsCrc32; + } + return NodeCrc32; + }; + exports.getCrc32ChecksumAlgorithmFunction = getCrc32ChecksumAlgorithmFunction; + } +}); + +// node_modules/.pnpm/@smithy+util-middleware@4.2.13/node_modules/@smithy/util-middleware/dist-cjs/index.js +var require_dist_cjs18 = __commonJS({ + "node_modules/.pnpm/@smithy+util-middleware@4.2.13/node_modules/@smithy/util-middleware/dist-cjs/index.js"(exports) { + "use strict"; + var types2 = require_dist_cjs(); + var getSmithyContext11 = (context) => context[types2.SMITHY_CONTEXT_KEY] || (context[types2.SMITHY_CONTEXT_KEY] = {}); + var normalizeProvider6 = (input) => { + if (typeof input === "function") + return input; + const promisified = Promise.resolve(input); + return () => promisified; + }; + exports.getSmithyContext = getSmithyContext11; + exports.normalizeProvider = normalizeProvider6; + } +}); + +// node_modules/.pnpm/@aws-sdk+middleware-flexible-checksums@3.974.7/node_modules/@aws-sdk/middleware-flexible-checksums/dist-cjs/index.js +var require_dist_cjs19 = __commonJS({ + "node_modules/.pnpm/@aws-sdk+middleware-flexible-checksums@3.974.7/node_modules/@aws-sdk/middleware-flexible-checksums/dist-cjs/index.js"(exports) { + "use strict"; + var client2 = (init_client2(), __toCommonJS(client_exports)); + var protocolHttp = require_dist_cjs2(); + var utilStream = require_dist_cjs13(); + var isArrayBuffer = require_dist_cjs4(); + var crc32c = require_main3(); + var crc64Nvme = require_dist_cjs17(); + var getCrc32ChecksumAlgorithmFunction = require_getCrc32ChecksumAlgorithmFunction(); + var utilUtf8 = require_dist_cjs6(); + var utilMiddleware = require_dist_cjs18(); + var RequestChecksumCalculation = { + WHEN_SUPPORTED: "WHEN_SUPPORTED", + WHEN_REQUIRED: "WHEN_REQUIRED" + }; + var DEFAULT_REQUEST_CHECKSUM_CALCULATION = RequestChecksumCalculation.WHEN_SUPPORTED; + var ResponseChecksumValidation = { + WHEN_SUPPORTED: "WHEN_SUPPORTED", + WHEN_REQUIRED: "WHEN_REQUIRED" + }; + var DEFAULT_RESPONSE_CHECKSUM_VALIDATION = RequestChecksumCalculation.WHEN_SUPPORTED; + exports.ChecksumAlgorithm = void 0; + (function(ChecksumAlgorithm) { + ChecksumAlgorithm["MD5"] = "MD5"; + ChecksumAlgorithm["CRC32"] = "CRC32"; + ChecksumAlgorithm["CRC32C"] = "CRC32C"; + ChecksumAlgorithm["CRC64NVME"] = "CRC64NVME"; + ChecksumAlgorithm["SHA1"] = "SHA1"; + ChecksumAlgorithm["SHA256"] = "SHA256"; + })(exports.ChecksumAlgorithm || (exports.ChecksumAlgorithm = {})); + exports.ChecksumLocation = void 0; + (function(ChecksumLocation) { + ChecksumLocation["HEADER"] = "header"; + ChecksumLocation["TRAILER"] = "trailer"; + })(exports.ChecksumLocation || (exports.ChecksumLocation = {})); + var DEFAULT_CHECKSUM_ALGORITHM = exports.ChecksumAlgorithm.CRC32; + var SelectorType; + (function(SelectorType2) { + SelectorType2["ENV"] = "env"; + SelectorType2["CONFIG"] = "shared config entry"; + })(SelectorType || (SelectorType = {})); + var stringUnionSelector = (obj, key, union3, type) => { + if (!(key in obj)) + return void 0; + const value = obj[key].toUpperCase(); + if (!Object.values(union3).includes(value)) { + throw new TypeError(`Cannot load ${type} '${key}'. Expected one of ${Object.values(union3)}, got '${obj[key]}'.`); + } + return value; + }; + var ENV_REQUEST_CHECKSUM_CALCULATION = "AWS_REQUEST_CHECKSUM_CALCULATION"; + var CONFIG_REQUEST_CHECKSUM_CALCULATION = "request_checksum_calculation"; + var NODE_REQUEST_CHECKSUM_CALCULATION_CONFIG_OPTIONS = { + environmentVariableSelector: (env2) => stringUnionSelector(env2, ENV_REQUEST_CHECKSUM_CALCULATION, RequestChecksumCalculation, SelectorType.ENV), + configFileSelector: (profile) => stringUnionSelector(profile, CONFIG_REQUEST_CHECKSUM_CALCULATION, RequestChecksumCalculation, SelectorType.CONFIG), + default: DEFAULT_REQUEST_CHECKSUM_CALCULATION + }; + var ENV_RESPONSE_CHECKSUM_VALIDATION = "AWS_RESPONSE_CHECKSUM_VALIDATION"; + var CONFIG_RESPONSE_CHECKSUM_VALIDATION = "response_checksum_validation"; + var NODE_RESPONSE_CHECKSUM_VALIDATION_CONFIG_OPTIONS = { + environmentVariableSelector: (env2) => stringUnionSelector(env2, ENV_RESPONSE_CHECKSUM_VALIDATION, ResponseChecksumValidation, SelectorType.ENV), + configFileSelector: (profile) => stringUnionSelector(profile, CONFIG_RESPONSE_CHECKSUM_VALIDATION, ResponseChecksumValidation, SelectorType.CONFIG), + default: DEFAULT_RESPONSE_CHECKSUM_VALIDATION + }; + var getChecksumAlgorithmForRequest = (input, { requestChecksumRequired, requestAlgorithmMember, requestChecksumCalculation }) => { + if (!requestAlgorithmMember) { + return requestChecksumCalculation === RequestChecksumCalculation.WHEN_SUPPORTED || requestChecksumRequired ? DEFAULT_CHECKSUM_ALGORITHM : void 0; + } + if (!input[requestAlgorithmMember]) { + return void 0; + } + const checksumAlgorithm = input[requestAlgorithmMember]; + return checksumAlgorithm; + }; + var getChecksumLocationName = (algorithm2) => algorithm2 === exports.ChecksumAlgorithm.MD5 ? "content-md5" : `x-amz-checksum-${algorithm2.toLowerCase()}`; + var hasHeader = (header, headers) => { + const soughtHeader = header.toLowerCase(); + for (const headerName of Object.keys(headers)) { + if (soughtHeader === headerName.toLowerCase()) { + return true; + } + } + return false; + }; + var hasHeaderWithPrefix = (headerPrefix, headers) => { + const soughtHeaderPrefix = headerPrefix.toLowerCase(); + for (const headerName of Object.keys(headers)) { + if (headerName.toLowerCase().startsWith(soughtHeaderPrefix)) { + return true; + } + } + return false; + }; + var isStreaming = (body) => body !== void 0 && typeof body !== "string" && !ArrayBuffer.isView(body) && !isArrayBuffer.isArrayBuffer(body); + var CLIENT_SUPPORTED_ALGORITHMS = [ + exports.ChecksumAlgorithm.CRC32, + exports.ChecksumAlgorithm.CRC32C, + exports.ChecksumAlgorithm.CRC64NVME, + exports.ChecksumAlgorithm.SHA1, + exports.ChecksumAlgorithm.SHA256 + ]; + var PRIORITY_ORDER_ALGORITHMS = [ + exports.ChecksumAlgorithm.SHA256, + exports.ChecksumAlgorithm.SHA1, + exports.ChecksumAlgorithm.CRC32, + exports.ChecksumAlgorithm.CRC32C, + exports.ChecksumAlgorithm.CRC64NVME + ]; + var selectChecksumAlgorithmFunction = (checksumAlgorithm, config3) => { + const { checksumAlgorithms = {} } = config3; + switch (checksumAlgorithm) { + case exports.ChecksumAlgorithm.MD5: + return checksumAlgorithms?.MD5 ?? config3.md5; + case exports.ChecksumAlgorithm.CRC32: + return checksumAlgorithms?.CRC32 ?? getCrc32ChecksumAlgorithmFunction.getCrc32ChecksumAlgorithmFunction(); + case exports.ChecksumAlgorithm.CRC32C: + return checksumAlgorithms?.CRC32C ?? crc32c.AwsCrc32c; + case exports.ChecksumAlgorithm.CRC64NVME: + if (typeof crc64Nvme.crc64NvmeCrtContainer.CrtCrc64Nvme !== "function") { + return checksumAlgorithms?.CRC64NVME ?? crc64Nvme.Crc64Nvme; + } + return checksumAlgorithms?.CRC64NVME ?? crc64Nvme.crc64NvmeCrtContainer.CrtCrc64Nvme; + case exports.ChecksumAlgorithm.SHA1: + return checksumAlgorithms?.SHA1 ?? config3.sha1; + case exports.ChecksumAlgorithm.SHA256: + return checksumAlgorithms?.SHA256 ?? config3.sha256; + default: + if (checksumAlgorithms?.[checksumAlgorithm]) { + return checksumAlgorithms[checksumAlgorithm]; + } + throw new Error(`The checksum algorithm "${checksumAlgorithm}" is not supported by the client. Select one of ${CLIENT_SUPPORTED_ALGORITHMS}, or provide an implementation to the client constructor checksums field.`); + } + }; + var stringHasher = (checksumAlgorithmFn, body) => { + const hash2 = new checksumAlgorithmFn(); + hash2.update(utilUtf8.toUint8Array(body || "")); + return hash2.digest(); + }; + var flexibleChecksumsMiddlewareOptions = { + name: "flexibleChecksumsMiddleware", + step: "build", + tags: ["BODY_CHECKSUM"], + override: true + }; + var flexibleChecksumsMiddleware = (config3, middlewareConfig) => (next, context) => async (args) => { + if (!protocolHttp.HttpRequest.isInstance(args.request)) { + return next(args); + } + if (hasHeaderWithPrefix("x-amz-checksum-", args.request.headers)) { + return next(args); + } + const { request, input } = args; + const { body: requestBody, headers } = request; + const { base64Encoder, streamHasher } = config3; + const { requestChecksumRequired, requestAlgorithmMember } = middlewareConfig; + const requestChecksumCalculation = await config3.requestChecksumCalculation(); + const requestAlgorithmMemberName = requestAlgorithmMember?.name; + const requestAlgorithmMemberHttpHeader = requestAlgorithmMember?.httpHeader; + if (requestAlgorithmMemberName && !input[requestAlgorithmMemberName]) { + if (requestChecksumCalculation === RequestChecksumCalculation.WHEN_SUPPORTED || requestChecksumRequired) { + input[requestAlgorithmMemberName] = DEFAULT_CHECKSUM_ALGORITHM; + if (requestAlgorithmMemberHttpHeader) { + headers[requestAlgorithmMemberHttpHeader] = DEFAULT_CHECKSUM_ALGORITHM; + } + } + } + const checksumAlgorithm = getChecksumAlgorithmForRequest(input, { + requestChecksumRequired, + requestAlgorithmMember: requestAlgorithmMember?.name, + requestChecksumCalculation + }); + let updatedBody = requestBody; + let updatedHeaders = headers; + if (checksumAlgorithm) { + switch (checksumAlgorithm) { + case exports.ChecksumAlgorithm.CRC32: + client2.setFeature(context, "FLEXIBLE_CHECKSUMS_REQ_CRC32", "U"); + break; + case exports.ChecksumAlgorithm.CRC32C: + client2.setFeature(context, "FLEXIBLE_CHECKSUMS_REQ_CRC32C", "V"); + break; + case exports.ChecksumAlgorithm.CRC64NVME: + client2.setFeature(context, "FLEXIBLE_CHECKSUMS_REQ_CRC64", "W"); + break; + case exports.ChecksumAlgorithm.SHA1: + client2.setFeature(context, "FLEXIBLE_CHECKSUMS_REQ_SHA1", "X"); + break; + case exports.ChecksumAlgorithm.SHA256: + client2.setFeature(context, "FLEXIBLE_CHECKSUMS_REQ_SHA256", "Y"); + break; + } + const checksumLocationName = getChecksumLocationName(checksumAlgorithm); + const checksumAlgorithmFn = selectChecksumAlgorithmFunction(checksumAlgorithm, config3); + if (isStreaming(requestBody)) { + const { getAwsChunkedEncodingStream, bodyLengthChecker } = config3; + updatedBody = getAwsChunkedEncodingStream(typeof config3.requestStreamBufferSize === "number" && config3.requestStreamBufferSize >= 8 * 1024 ? utilStream.createBufferedReadable(requestBody, config3.requestStreamBufferSize, context.logger) : requestBody, { + base64Encoder, + bodyLengthChecker, + checksumLocationName, + checksumAlgorithmFn, + streamHasher + }); + updatedHeaders = { + ...headers, + "content-encoding": headers["content-encoding"] ? `${headers["content-encoding"]},aws-chunked` : "aws-chunked", + "transfer-encoding": "chunked", + "x-amz-decoded-content-length": headers["content-length"], + "x-amz-content-sha256": "STREAMING-UNSIGNED-PAYLOAD-TRAILER", + "x-amz-trailer": checksumLocationName + }; + delete updatedHeaders["content-length"]; + } else if (!hasHeader(checksumLocationName, headers)) { + const rawChecksum = await stringHasher(checksumAlgorithmFn, requestBody); + updatedHeaders = { + ...headers, + [checksumLocationName]: base64Encoder(rawChecksum) + }; + } + } + try { + const result = await next({ + ...args, + request: { + ...request, + headers: updatedHeaders, + body: updatedBody + } + }); + return result; + } catch (e5) { + if (e5 instanceof Error && e5.name === "InvalidChunkSizeError") { + try { + if (!e5.message.endsWith(".")) { + e5.message += "."; + } + e5.message += " Set [requestStreamBufferSize=number e.g. 65_536] in client constructor to instruct AWS SDK to buffer your input stream."; + } catch (ignored) { + } + } + throw e5; + } + }; + var flexibleChecksumsInputMiddlewareOptions = { + name: "flexibleChecksumsInputMiddleware", + toMiddleware: "serializerMiddleware", + relation: "before", + tags: ["BODY_CHECKSUM"], + override: true + }; + var flexibleChecksumsInputMiddleware = (config3, middlewareConfig) => (next, context) => async (args) => { + const input = args.input; + const { requestValidationModeMember } = middlewareConfig; + const requestChecksumCalculation = await config3.requestChecksumCalculation(); + const responseChecksumValidation = await config3.responseChecksumValidation(); + switch (requestChecksumCalculation) { + case RequestChecksumCalculation.WHEN_REQUIRED: + client2.setFeature(context, "FLEXIBLE_CHECKSUMS_REQ_WHEN_REQUIRED", "a"); + break; + case RequestChecksumCalculation.WHEN_SUPPORTED: + client2.setFeature(context, "FLEXIBLE_CHECKSUMS_REQ_WHEN_SUPPORTED", "Z"); + break; + } + switch (responseChecksumValidation) { + case ResponseChecksumValidation.WHEN_REQUIRED: + client2.setFeature(context, "FLEXIBLE_CHECKSUMS_RES_WHEN_REQUIRED", "c"); + break; + case ResponseChecksumValidation.WHEN_SUPPORTED: + client2.setFeature(context, "FLEXIBLE_CHECKSUMS_RES_WHEN_SUPPORTED", "b"); + break; + } + if (requestValidationModeMember && !input[requestValidationModeMember]) { + if (responseChecksumValidation === ResponseChecksumValidation.WHEN_SUPPORTED) { + input[requestValidationModeMember] = "ENABLED"; + } + } + return next(args); + }; + var getChecksumAlgorithmListForResponse = (responseAlgorithms = []) => { + const validChecksumAlgorithms = []; + let i5 = PRIORITY_ORDER_ALGORITHMS.length; + for (const algorithm2 of responseAlgorithms) { + const priority = PRIORITY_ORDER_ALGORITHMS.indexOf(algorithm2); + if (priority !== -1) { + validChecksumAlgorithms[priority] = algorithm2; + } else { + validChecksumAlgorithms[i5++] = algorithm2; + } + } + return validChecksumAlgorithms.filter(Boolean); + }; + var isChecksumWithPartNumber = (checksum) => { + const lastHyphenIndex = checksum.lastIndexOf("-"); + if (lastHyphenIndex !== -1) { + const numberPart = checksum.slice(lastHyphenIndex + 1); + if (!numberPart.startsWith("0")) { + const number4 = parseInt(numberPart, 10); + if (!isNaN(number4) && number4 >= 1 && number4 <= 1e4) { + return true; + } + } + } + return false; + }; + var getChecksum = async (body, { checksumAlgorithmFn, base64Encoder }) => base64Encoder(await stringHasher(checksumAlgorithmFn, body)); + var validateChecksumFromResponse = async (response, { config: config3, responseAlgorithms, logger: logger4 }) => { + const checksumAlgorithms = getChecksumAlgorithmListForResponse(responseAlgorithms); + const { body: responseBody, headers: responseHeaders } = response; + for (const algorithm2 of checksumAlgorithms) { + const responseHeader = getChecksumLocationName(algorithm2); + const checksumFromResponse = responseHeaders[responseHeader]; + if (checksumFromResponse) { + let checksumAlgorithmFn; + try { + checksumAlgorithmFn = selectChecksumAlgorithmFunction(algorithm2, config3); + } catch (error50) { + if (algorithm2 === exports.ChecksumAlgorithm.CRC64NVME) { + logger4?.warn(`Skipping ${exports.ChecksumAlgorithm.CRC64NVME} checksum validation: ${error50.message}`); + continue; + } + throw error50; + } + const { base64Encoder } = config3; + if (isStreaming(responseBody)) { + response.body = utilStream.createChecksumStream({ + expectedChecksum: checksumFromResponse, + checksumSourceLocation: responseHeader, + checksum: new checksumAlgorithmFn(), + source: responseBody, + base64Encoder + }); + return; + } + const checksum = await getChecksum(responseBody, { checksumAlgorithmFn, base64Encoder }); + if (checksum === checksumFromResponse) { + break; + } + throw new Error(`Checksum mismatch: expected "${checksum}" but received "${checksumFromResponse}" in response header "${responseHeader}".`); + } + } + }; + var flexibleChecksumsResponseMiddlewareOptions = { + name: "flexibleChecksumsResponseMiddleware", + toMiddleware: "deserializerMiddleware", + relation: "after", + tags: ["BODY_CHECKSUM"], + override: true + }; + var flexibleChecksumsResponseMiddleware = (config3, middlewareConfig) => (next, context) => async (args) => { + if (!protocolHttp.HttpRequest.isInstance(args.request)) { + return next(args); + } + const input = args.input; + const result = await next(args); + const response = result.response; + const { requestValidationModeMember, responseAlgorithms } = middlewareConfig; + if (requestValidationModeMember && input[requestValidationModeMember] === "ENABLED") { + const { clientName, commandName } = context; + const customChecksumAlgorithms = Object.keys(config3.checksumAlgorithms ?? {}).filter((algorithm2) => { + const responseHeader = getChecksumLocationName(algorithm2); + return response.headers[responseHeader] !== void 0; + }); + const algoList = getChecksumAlgorithmListForResponse([ + ...responseAlgorithms ?? [], + ...customChecksumAlgorithms + ]); + const isS3WholeObjectMultipartGetResponseChecksum = clientName === "S3Client" && commandName === "GetObjectCommand" && algoList.every((algorithm2) => { + const responseHeader = getChecksumLocationName(algorithm2); + const checksumFromResponse = response.headers[responseHeader]; + return !checksumFromResponse || isChecksumWithPartNumber(checksumFromResponse); + }); + if (isS3WholeObjectMultipartGetResponseChecksum) { + return result; + } + await validateChecksumFromResponse(response, { + config: config3, + responseAlgorithms: algoList, + logger: context.logger + }); + } + return result; + }; + var getFlexibleChecksumsPlugin = (config3, middlewareConfig) => ({ + applyToStack: (clientStack) => { + clientStack.add(flexibleChecksumsMiddleware(config3, middlewareConfig), flexibleChecksumsMiddlewareOptions); + clientStack.addRelativeTo(flexibleChecksumsInputMiddleware(config3, middlewareConfig), flexibleChecksumsInputMiddlewareOptions); + clientStack.addRelativeTo(flexibleChecksumsResponseMiddleware(config3, middlewareConfig), flexibleChecksumsResponseMiddlewareOptions); + } + }); + var resolveFlexibleChecksumsConfig = (input) => { + const { requestChecksumCalculation, responseChecksumValidation, requestStreamBufferSize } = input; + return Object.assign(input, { + requestChecksumCalculation: utilMiddleware.normalizeProvider(requestChecksumCalculation ?? DEFAULT_REQUEST_CHECKSUM_CALCULATION), + responseChecksumValidation: utilMiddleware.normalizeProvider(responseChecksumValidation ?? DEFAULT_RESPONSE_CHECKSUM_VALIDATION), + requestStreamBufferSize: Number(requestStreamBufferSize ?? 0), + checksumAlgorithms: input.checksumAlgorithms ?? {} + }); + }; + exports.CONFIG_REQUEST_CHECKSUM_CALCULATION = CONFIG_REQUEST_CHECKSUM_CALCULATION; + exports.CONFIG_RESPONSE_CHECKSUM_VALIDATION = CONFIG_RESPONSE_CHECKSUM_VALIDATION; + exports.DEFAULT_CHECKSUM_ALGORITHM = DEFAULT_CHECKSUM_ALGORITHM; + exports.DEFAULT_REQUEST_CHECKSUM_CALCULATION = DEFAULT_REQUEST_CHECKSUM_CALCULATION; + exports.DEFAULT_RESPONSE_CHECKSUM_VALIDATION = DEFAULT_RESPONSE_CHECKSUM_VALIDATION; + exports.ENV_REQUEST_CHECKSUM_CALCULATION = ENV_REQUEST_CHECKSUM_CALCULATION; + exports.ENV_RESPONSE_CHECKSUM_VALIDATION = ENV_RESPONSE_CHECKSUM_VALIDATION; + exports.NODE_REQUEST_CHECKSUM_CALCULATION_CONFIG_OPTIONS = NODE_REQUEST_CHECKSUM_CALCULATION_CONFIG_OPTIONS; + exports.NODE_RESPONSE_CHECKSUM_VALIDATION_CONFIG_OPTIONS = NODE_RESPONSE_CHECKSUM_VALIDATION_CONFIG_OPTIONS; + exports.RequestChecksumCalculation = RequestChecksumCalculation; + exports.ResponseChecksumValidation = ResponseChecksumValidation; + exports.flexibleChecksumsMiddleware = flexibleChecksumsMiddleware; + exports.flexibleChecksumsMiddlewareOptions = flexibleChecksumsMiddlewareOptions; + exports.getFlexibleChecksumsPlugin = getFlexibleChecksumsPlugin; + exports.resolveFlexibleChecksumsConfig = resolveFlexibleChecksumsConfig; + } +}); + +// node_modules/.pnpm/@aws-sdk+middleware-host-header@3.972.9/node_modules/@aws-sdk/middleware-host-header/dist-cjs/index.js +var require_dist_cjs20 = __commonJS({ + "node_modules/.pnpm/@aws-sdk+middleware-host-header@3.972.9/node_modules/@aws-sdk/middleware-host-header/dist-cjs/index.js"(exports) { + "use strict"; + var protocolHttp = require_dist_cjs2(); + function resolveHostHeaderConfig5(input) { + return input; + } + var hostHeaderMiddleware = (options) => (next) => async (args) => { + if (!protocolHttp.HttpRequest.isInstance(args.request)) + return next(args); + const { request } = args; + const { handlerProtocol = "" } = options.requestHandler.metadata || {}; + if (handlerProtocol.indexOf("h2") >= 0 && !request.headers[":authority"]) { + delete request.headers["host"]; + request.headers[":authority"] = request.hostname + (request.port ? ":" + request.port : ""); + } else if (!request.headers["host"]) { + let host = request.hostname; + if (request.port != null) + host += `:${request.port}`; + request.headers["host"] = host; + } + return next(args); + }; + var hostHeaderMiddlewareOptions = { + name: "hostHeaderMiddleware", + step: "build", + priority: "low", + tags: ["HOST"], + override: true + }; + var getHostHeaderPlugin5 = (options) => ({ + applyToStack: (clientStack) => { + clientStack.add(hostHeaderMiddleware(options), hostHeaderMiddlewareOptions); + } + }); + exports.getHostHeaderPlugin = getHostHeaderPlugin5; + exports.hostHeaderMiddleware = hostHeaderMiddleware; + exports.hostHeaderMiddlewareOptions = hostHeaderMiddlewareOptions; + exports.resolveHostHeaderConfig = resolveHostHeaderConfig5; + } +}); + +// node_modules/.pnpm/@aws-sdk+middleware-logger@3.972.9/node_modules/@aws-sdk/middleware-logger/dist-cjs/index.js +var require_dist_cjs21 = __commonJS({ + "node_modules/.pnpm/@aws-sdk+middleware-logger@3.972.9/node_modules/@aws-sdk/middleware-logger/dist-cjs/index.js"(exports) { + "use strict"; + var loggerMiddleware = () => (next, context) => async (args) => { + try { + const response = await next(args); + const { clientName, commandName, logger: logger4, dynamoDbDocumentClientOptions = {} } = context; + const { overrideInputFilterSensitiveLog, overrideOutputFilterSensitiveLog } = dynamoDbDocumentClientOptions; + const inputFilterSensitiveLog = overrideInputFilterSensitiveLog ?? context.inputFilterSensitiveLog; + const outputFilterSensitiveLog = overrideOutputFilterSensitiveLog ?? context.outputFilterSensitiveLog; + const { $metadata, ...outputWithoutMetadata } = response.output; + logger4?.info?.({ + clientName, + commandName, + input: inputFilterSensitiveLog(args.input), + output: outputFilterSensitiveLog(outputWithoutMetadata), + metadata: $metadata + }); + return response; + } catch (error50) { + const { clientName, commandName, logger: logger4, dynamoDbDocumentClientOptions = {} } = context; + const { overrideInputFilterSensitiveLog } = dynamoDbDocumentClientOptions; + const inputFilterSensitiveLog = overrideInputFilterSensitiveLog ?? context.inputFilterSensitiveLog; + logger4?.error?.({ + clientName, + commandName, + input: inputFilterSensitiveLog(args.input), + error: error50, + metadata: error50.$metadata + }); + throw error50; + } + }; + var loggerMiddlewareOptions = { + name: "loggerMiddleware", + tags: ["LOGGER"], + step: "initialize", + override: true + }; + var getLoggerPlugin5 = (options) => ({ + applyToStack: (clientStack) => { + clientStack.add(loggerMiddleware(), loggerMiddlewareOptions); + } + }); + exports.getLoggerPlugin = getLoggerPlugin5; + exports.loggerMiddleware = loggerMiddleware; + exports.loggerMiddlewareOptions = loggerMiddlewareOptions; + } +}); + +// node_modules/.pnpm/@aws+lambda-invoke-store@0.2.4/node_modules/@aws/lambda-invoke-store/dist-es/invoke-store.js +var invoke_store_exports = {}; +__export(invoke_store_exports, { + InvokeStore: () => InvokeStore, + InvokeStoreBase: () => InvokeStoreBase +}); +var PROTECTED_KEYS, NO_GLOBAL_AWS_LAMBDA, InvokeStoreBase, InvokeStoreSingle, InvokeStoreMulti, InvokeStore; +var init_invoke_store = __esm({ + "node_modules/.pnpm/@aws+lambda-invoke-store@0.2.4/node_modules/@aws/lambda-invoke-store/dist-es/invoke-store.js"() { + PROTECTED_KEYS = { + REQUEST_ID: /* @__PURE__ */ Symbol.for("_AWS_LAMBDA_REQUEST_ID"), + X_RAY_TRACE_ID: /* @__PURE__ */ Symbol.for("_AWS_LAMBDA_X_RAY_TRACE_ID"), + TENANT_ID: /* @__PURE__ */ Symbol.for("_AWS_LAMBDA_TENANT_ID") + }; + NO_GLOBAL_AWS_LAMBDA = ["true", "1"].includes(process.env?.AWS_LAMBDA_NODEJS_NO_GLOBAL_AWSLAMBDA ?? ""); + if (!NO_GLOBAL_AWS_LAMBDA) { + globalThis.awslambda = globalThis.awslambda || {}; + } + InvokeStoreBase = class { + static PROTECTED_KEYS = PROTECTED_KEYS; + isProtectedKey(key) { + return Object.values(PROTECTED_KEYS).includes(key); + } + getRequestId() { + return this.get(PROTECTED_KEYS.REQUEST_ID) ?? "-"; + } + getXRayTraceId() { + return this.get(PROTECTED_KEYS.X_RAY_TRACE_ID); + } + getTenantId() { + return this.get(PROTECTED_KEYS.TENANT_ID); + } + }; + InvokeStoreSingle = class extends InvokeStoreBase { + currentContext; + getContext() { + return this.currentContext; + } + hasContext() { + return this.currentContext !== void 0; + } + get(key) { + return this.currentContext?.[key]; + } + set(key, value) { + if (this.isProtectedKey(key)) { + throw new Error(`Cannot modify protected Lambda context field: ${String(key)}`); + } + this.currentContext = this.currentContext || {}; + this.currentContext[key] = value; + } + run(context, fn) { + this.currentContext = context; + return fn(); + } + }; + InvokeStoreMulti = class _InvokeStoreMulti extends InvokeStoreBase { + als; + static async create() { + const instance = new _InvokeStoreMulti(); + const asyncHooks = await import("node:async_hooks"); + instance.als = new asyncHooks.AsyncLocalStorage(); + return instance; + } + getContext() { + return this.als.getStore(); + } + hasContext() { + return this.als.getStore() !== void 0; + } + get(key) { + return this.als.getStore()?.[key]; + } + set(key, value) { + if (this.isProtectedKey(key)) { + throw new Error(`Cannot modify protected Lambda context field: ${String(key)}`); + } + const store = this.als.getStore(); + if (!store) { + throw new Error("No context available"); + } + store[key] = value; + } + run(context, fn) { + return this.als.run(context, fn); + } + }; + (function(InvokeStore2) { + let instance = null; + async function getInstanceAsync(forceInvokeStoreMulti) { + if (!instance) { + instance = (async () => { + const isMulti = forceInvokeStoreMulti === true || "AWS_LAMBDA_MAX_CONCURRENCY" in process.env; + const newInstance = isMulti ? await InvokeStoreMulti.create() : new InvokeStoreSingle(); + if (!NO_GLOBAL_AWS_LAMBDA && globalThis.awslambda?.InvokeStore) { + return globalThis.awslambda.InvokeStore; + } else if (!NO_GLOBAL_AWS_LAMBDA && globalThis.awslambda) { + globalThis.awslambda.InvokeStore = newInstance; + return newInstance; + } else { + return newInstance; + } + })(); + } + return instance; + } + InvokeStore2.getInstanceAsync = getInstanceAsync; + InvokeStore2._testing = process.env.AWS_LAMBDA_BENCHMARK_MODE === "1" ? { + reset: () => { + instance = null; + if (globalThis.awslambda?.InvokeStore) { + delete globalThis.awslambda.InvokeStore; + } + globalThis.awslambda = { InvokeStore: void 0 }; + } + } : void 0; + })(InvokeStore || (InvokeStore = {})); + } +}); + +// node_modules/.pnpm/@aws-sdk+middleware-recursion-detection@3.972.10/node_modules/@aws-sdk/middleware-recursion-detection/dist-cjs/recursionDetectionMiddleware.js +var require_recursionDetectionMiddleware = __commonJS({ + "node_modules/.pnpm/@aws-sdk+middleware-recursion-detection@3.972.10/node_modules/@aws-sdk/middleware-recursion-detection/dist-cjs/recursionDetectionMiddleware.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.recursionDetectionMiddleware = void 0; + var lambda_invoke_store_1 = (init_invoke_store(), __toCommonJS(invoke_store_exports)); + var protocol_http_1 = require_dist_cjs2(); + var TRACE_ID_HEADER_NAME = "X-Amzn-Trace-Id"; + var ENV_LAMBDA_FUNCTION_NAME = "AWS_LAMBDA_FUNCTION_NAME"; + var ENV_TRACE_ID = "_X_AMZN_TRACE_ID"; + var recursionDetectionMiddleware = () => (next) => async (args) => { + const { request } = args; + if (!protocol_http_1.HttpRequest.isInstance(request)) { + return next(args); + } + const traceIdHeader = Object.keys(request.headers ?? {}).find((h5) => h5.toLowerCase() === TRACE_ID_HEADER_NAME.toLowerCase()) ?? TRACE_ID_HEADER_NAME; + if (request.headers.hasOwnProperty(traceIdHeader)) { + return next(args); + } + const functionName = process.env[ENV_LAMBDA_FUNCTION_NAME]; + const traceIdFromEnv = process.env[ENV_TRACE_ID]; + const invokeStore = await lambda_invoke_store_1.InvokeStore.getInstanceAsync(); + const traceIdFromInvokeStore = invokeStore?.getXRayTraceId(); + const traceId = traceIdFromInvokeStore ?? traceIdFromEnv; + const nonEmptyString = (str) => typeof str === "string" && str.length > 0; + if (nonEmptyString(functionName) && nonEmptyString(traceId)) { + request.headers[TRACE_ID_HEADER_NAME] = traceId; + } + return next({ + ...args, + request + }); + }; + exports.recursionDetectionMiddleware = recursionDetectionMiddleware; + } +}); + +// node_modules/.pnpm/@aws-sdk+middleware-recursion-detection@3.972.10/node_modules/@aws-sdk/middleware-recursion-detection/dist-cjs/index.js +var require_dist_cjs22 = __commonJS({ + "node_modules/.pnpm/@aws-sdk+middleware-recursion-detection@3.972.10/node_modules/@aws-sdk/middleware-recursion-detection/dist-cjs/index.js"(exports) { + "use strict"; + var recursionDetectionMiddleware = require_recursionDetectionMiddleware(); + var recursionDetectionMiddlewareOptions = { + step: "build", + tags: ["RECURSION_DETECTION"], + name: "recursionDetectionMiddleware", + override: true, + priority: "low" + }; + var getRecursionDetectionPlugin5 = (options) => ({ + applyToStack: (clientStack) => { + clientStack.add(recursionDetectionMiddleware.recursionDetectionMiddleware(), recursionDetectionMiddlewareOptions); + } + }); + exports.getRecursionDetectionPlugin = getRecursionDetectionPlugin5; + Object.prototype.hasOwnProperty.call(recursionDetectionMiddleware, "__proto__") && !Object.prototype.hasOwnProperty.call(exports, "__proto__") && Object.defineProperty(exports, "__proto__", { + enumerable: true, + value: recursionDetectionMiddleware["__proto__"] + }); + Object.keys(recursionDetectionMiddleware).forEach(function(k5) { + if (k5 !== "default" && !Object.prototype.hasOwnProperty.call(exports, k5)) exports[k5] = recursionDetectionMiddleware[k5]; + }); + } +}); + +// node_modules/.pnpm/@smithy+middleware-stack@4.2.13/node_modules/@smithy/middleware-stack/dist-cjs/index.js +var require_dist_cjs23 = __commonJS({ + "node_modules/.pnpm/@smithy+middleware-stack@4.2.13/node_modules/@smithy/middleware-stack/dist-cjs/index.js"(exports) { + "use strict"; + var getAllAliases = (name, aliases) => { + const _aliases = []; + if (name) { + _aliases.push(name); + } + if (aliases) { + for (const alias of aliases) { + _aliases.push(alias); + } + } + return _aliases; + }; + var getMiddlewareNameWithAliases = (name, aliases) => { + return `${name || "anonymous"}${aliases && aliases.length > 0 ? ` (a.k.a. ${aliases.join(",")})` : ""}`; + }; + var constructStack = () => { + let absoluteEntries = []; + let relativeEntries = []; + let identifyOnResolve = false; + const entriesNameSet = /* @__PURE__ */ new Set(); + const sort = (entries2) => entries2.sort((a5, b6) => stepWeights[b6.step] - stepWeights[a5.step] || priorityWeights[b6.priority || "normal"] - priorityWeights[a5.priority || "normal"]); + const removeByName = (toRemove) => { + let isRemoved = false; + const filterCb = (entry) => { + const aliases = getAllAliases(entry.name, entry.aliases); + if (aliases.includes(toRemove)) { + isRemoved = true; + for (const alias of aliases) { + entriesNameSet.delete(alias); + } + return false; + } + return true; + }; + absoluteEntries = absoluteEntries.filter(filterCb); + relativeEntries = relativeEntries.filter(filterCb); + return isRemoved; + }; + const removeByReference = (toRemove) => { + let isRemoved = false; + const filterCb = (entry) => { + if (entry.middleware === toRemove) { + isRemoved = true; + for (const alias of getAllAliases(entry.name, entry.aliases)) { + entriesNameSet.delete(alias); + } + return false; + } + return true; + }; + absoluteEntries = absoluteEntries.filter(filterCb); + relativeEntries = relativeEntries.filter(filterCb); + return isRemoved; + }; + const cloneTo = (toStack) => { + absoluteEntries.forEach((entry) => { + toStack.add(entry.middleware, { ...entry }); + }); + relativeEntries.forEach((entry) => { + toStack.addRelativeTo(entry.middleware, { ...entry }); + }); + toStack.identifyOnResolve?.(stack.identifyOnResolve()); + return toStack; + }; + const expandRelativeMiddlewareList = (from) => { + const expandedMiddlewareList = []; + from.before.forEach((entry) => { + if (entry.before.length === 0 && entry.after.length === 0) { + expandedMiddlewareList.push(entry); + } else { + expandedMiddlewareList.push(...expandRelativeMiddlewareList(entry)); + } + }); + expandedMiddlewareList.push(from); + from.after.reverse().forEach((entry) => { + if (entry.before.length === 0 && entry.after.length === 0) { + expandedMiddlewareList.push(entry); + } else { + expandedMiddlewareList.push(...expandRelativeMiddlewareList(entry)); + } + }); + return expandedMiddlewareList; + }; + const getMiddlewareList = (debug = false) => { + const normalizedAbsoluteEntries = []; + const normalizedRelativeEntries = []; + const normalizedEntriesNameMap = {}; + absoluteEntries.forEach((entry) => { + const normalizedEntry = { + ...entry, + before: [], + after: [] + }; + for (const alias of getAllAliases(normalizedEntry.name, normalizedEntry.aliases)) { + normalizedEntriesNameMap[alias] = normalizedEntry; + } + normalizedAbsoluteEntries.push(normalizedEntry); + }); + relativeEntries.forEach((entry) => { + const normalizedEntry = { + ...entry, + before: [], + after: [] + }; + for (const alias of getAllAliases(normalizedEntry.name, normalizedEntry.aliases)) { + normalizedEntriesNameMap[alias] = normalizedEntry; + } + normalizedRelativeEntries.push(normalizedEntry); + }); + normalizedRelativeEntries.forEach((entry) => { + if (entry.toMiddleware) { + const toMiddleware = normalizedEntriesNameMap[entry.toMiddleware]; + if (toMiddleware === void 0) { + if (debug) { + return; + } + throw new Error(`${entry.toMiddleware} is not found when adding ${getMiddlewareNameWithAliases(entry.name, entry.aliases)} middleware ${entry.relation} ${entry.toMiddleware}`); + } + if (entry.relation === "after") { + toMiddleware.after.push(entry); + } + if (entry.relation === "before") { + toMiddleware.before.push(entry); + } + } + }); + const mainChain = sort(normalizedAbsoluteEntries).map(expandRelativeMiddlewareList).reduce((wholeList, expandedMiddlewareList) => { + wholeList.push(...expandedMiddlewareList); + return wholeList; + }, []); + return mainChain; + }; + const stack = { + add: (middleware, options = {}) => { + const { name, override, aliases: _aliases } = options; + const entry = { + step: "initialize", + priority: "normal", + middleware, + ...options + }; + const aliases = getAllAliases(name, _aliases); + if (aliases.length > 0) { + if (aliases.some((alias) => entriesNameSet.has(alias))) { + if (!override) + throw new Error(`Duplicate middleware name '${getMiddlewareNameWithAliases(name, _aliases)}'`); + for (const alias of aliases) { + const toOverrideIndex = absoluteEntries.findIndex((entry2) => entry2.name === alias || entry2.aliases?.some((a5) => a5 === alias)); + if (toOverrideIndex === -1) { + continue; + } + const toOverride = absoluteEntries[toOverrideIndex]; + if (toOverride.step !== entry.step || entry.priority !== toOverride.priority) { + throw new Error(`"${getMiddlewareNameWithAliases(toOverride.name, toOverride.aliases)}" middleware with ${toOverride.priority} priority in ${toOverride.step} step cannot be overridden by "${getMiddlewareNameWithAliases(name, _aliases)}" middleware with ${entry.priority} priority in ${entry.step} step.`); + } + absoluteEntries.splice(toOverrideIndex, 1); + } + } + for (const alias of aliases) { + entriesNameSet.add(alias); + } + } + absoluteEntries.push(entry); + }, + addRelativeTo: (middleware, options) => { + const { name, override, aliases: _aliases } = options; + const entry = { + middleware, + ...options + }; + const aliases = getAllAliases(name, _aliases); + if (aliases.length > 0) { + if (aliases.some((alias) => entriesNameSet.has(alias))) { + if (!override) + throw new Error(`Duplicate middleware name '${getMiddlewareNameWithAliases(name, _aliases)}'`); + for (const alias of aliases) { + const toOverrideIndex = relativeEntries.findIndex((entry2) => entry2.name === alias || entry2.aliases?.some((a5) => a5 === alias)); + if (toOverrideIndex === -1) { + continue; + } + const toOverride = relativeEntries[toOverrideIndex]; + if (toOverride.toMiddleware !== entry.toMiddleware || toOverride.relation !== entry.relation) { + throw new Error(`"${getMiddlewareNameWithAliases(toOverride.name, toOverride.aliases)}" middleware ${toOverride.relation} "${toOverride.toMiddleware}" middleware cannot be overridden by "${getMiddlewareNameWithAliases(name, _aliases)}" middleware ${entry.relation} "${entry.toMiddleware}" middleware.`); + } + relativeEntries.splice(toOverrideIndex, 1); + } + } + for (const alias of aliases) { + entriesNameSet.add(alias); + } + } + relativeEntries.push(entry); + }, + clone: () => cloneTo(constructStack()), + use: (plugin) => { + plugin.applyToStack(stack); + }, + remove: (toRemove) => { + if (typeof toRemove === "string") + return removeByName(toRemove); + else + return removeByReference(toRemove); + }, + removeByTag: (toRemove) => { + let isRemoved = false; + const filterCb = (entry) => { + const { tags, name, aliases: _aliases } = entry; + if (tags && tags.includes(toRemove)) { + const aliases = getAllAliases(name, _aliases); + for (const alias of aliases) { + entriesNameSet.delete(alias); + } + isRemoved = true; + return false; + } + return true; + }; + absoluteEntries = absoluteEntries.filter(filterCb); + relativeEntries = relativeEntries.filter(filterCb); + return isRemoved; + }, + concat: (from) => { + const cloned = cloneTo(constructStack()); + cloned.use(from); + cloned.identifyOnResolve(identifyOnResolve || cloned.identifyOnResolve() || (from.identifyOnResolve?.() ?? false)); + return cloned; + }, + applyToStack: cloneTo, + identify: () => { + return getMiddlewareList(true).map((mw) => { + const step = mw.step ?? mw.relation + " " + mw.toMiddleware; + return getMiddlewareNameWithAliases(mw.name, mw.aliases) + " - " + step; + }); + }, + identifyOnResolve(toggle) { + if (typeof toggle === "boolean") + identifyOnResolve = toggle; + return identifyOnResolve; + }, + resolve: (handler, context) => { + for (const middleware of getMiddlewareList().map((entry) => entry.middleware).reverse()) { + handler = middleware(handler, context); + } + if (identifyOnResolve) { + console.log(stack.identify()); + } + return handler; + } + }; + return stack; + }; + var stepWeights = { + initialize: 5, + serialize: 4, + build: 3, + finalizeRequest: 2, + deserialize: 1 + }; + var priorityWeights = { + high: 3, + normal: 2, + low: 1 + }; + exports.constructStack = constructStack; + } +}); + +// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/schema/deref.js +var deref; +var init_deref = __esm({ + "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/schema/deref.js"() { + deref = (schemaRef) => { + if (typeof schemaRef === "function") { + return schemaRef(); + } + return schemaRef; + }; + } +}); + +// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/schema/schemas/operation.js +var operation; +var init_operation = __esm({ + "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/schema/schemas/operation.js"() { + operation = (namespace, name, traits, input, output) => ({ + name, + namespace, + traits, + input, + output + }); + } +}); + +// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/schema/middleware/schemaDeserializationMiddleware.js +var import_protocol_http, import_util_middleware, schemaDeserializationMiddleware, findHeader; +var init_schemaDeserializationMiddleware = __esm({ + "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/schema/middleware/schemaDeserializationMiddleware.js"() { + import_protocol_http = __toESM(require_dist_cjs2()); + import_util_middleware = __toESM(require_dist_cjs18()); + init_operation(); + schemaDeserializationMiddleware = (config3) => (next, context) => async (args) => { + const { response } = await next(args); + const { operationSchema } = (0, import_util_middleware.getSmithyContext)(context); + const [, ns, n5, t5, i5, o5] = operationSchema ?? []; + try { + const parsed = await config3.protocol.deserializeResponse(operation(ns, n5, t5, i5, o5), { + ...config3, + ...context + }, response); + return { + response, + output: parsed + }; + } catch (error50) { + Object.defineProperty(error50, "$response", { + value: response, + enumerable: false, + writable: false, + configurable: false + }); + if (!("$metadata" in error50)) { + const hint = `Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`; + try { + error50.message += "\n " + hint; + } catch (e5) { + if (!context.logger || context.logger?.constructor?.name === "NoOpLogger") { + console.warn(hint); + } else { + context.logger?.warn?.(hint); + } + } + if (typeof error50.$responseBodyText !== "undefined") { + if (error50.$response) { + error50.$response.body = error50.$responseBodyText; + } + } + try { + if (import_protocol_http.HttpResponse.isInstance(response)) { + const { headers = {} } = response; + const headerEntries = Object.entries(headers); + error50.$metadata = { + httpStatusCode: response.statusCode, + requestId: findHeader(/^x-[\w-]+-request-?id$/, headerEntries), + extendedRequestId: findHeader(/^x-[\w-]+-id-2$/, headerEntries), + cfId: findHeader(/^x-[\w-]+-cf-id$/, headerEntries) + }; + } + } catch (e5) { + } + } + throw error50; + } + }; + findHeader = (pattern, headers) => { + return (headers.find(([k5]) => { + return k5.match(pattern); + }) || [void 0, void 0])[1]; + }; + } +}); + +// node_modules/.pnpm/@smithy+querystring-parser@4.2.13/node_modules/@smithy/querystring-parser/dist-cjs/index.js +var require_dist_cjs24 = __commonJS({ + "node_modules/.pnpm/@smithy+querystring-parser@4.2.13/node_modules/@smithy/querystring-parser/dist-cjs/index.js"(exports) { + "use strict"; + function parseQueryString(querystring) { + const query = {}; + querystring = querystring.replace(/^\?/, ""); + if (querystring) { + for (const pair of querystring.split("&")) { + let [key, value = null] = pair.split("="); + key = decodeURIComponent(key); + if (value) { + value = decodeURIComponent(value); + } + if (!(key in query)) { + query[key] = value; + } else if (Array.isArray(query[key])) { + query[key].push(value); + } else { + query[key] = [query[key], value]; + } + } + } + return query; + } + exports.parseQueryString = parseQueryString; + } +}); + +// node_modules/.pnpm/@smithy+url-parser@4.2.13/node_modules/@smithy/url-parser/dist-cjs/index.js +var require_dist_cjs25 = __commonJS({ + "node_modules/.pnpm/@smithy+url-parser@4.2.13/node_modules/@smithy/url-parser/dist-cjs/index.js"(exports) { + "use strict"; + var querystringParser = require_dist_cjs24(); + var parseUrl7 = (url2) => { + if (typeof url2 === "string") { + return parseUrl7(new URL(url2)); + } + const { hostname: hostname3, pathname, port, protocol, search } = url2; + let query; + if (search) { + query = querystringParser.parseQueryString(search); + } + return { + hostname: hostname3, + port: port ? parseInt(port) : void 0, + protocol, + path: pathname, + query + }; + }; + exports.parseUrl = parseUrl7; + } +}); + +// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/endpoints/toEndpointV1.js +var import_url_parser, toEndpointV1; +var init_toEndpointV1 = __esm({ + "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/endpoints/toEndpointV1.js"() { + import_url_parser = __toESM(require_dist_cjs25()); + toEndpointV1 = (endpoint) => { + if (typeof endpoint === "object") { + if ("url" in endpoint) { + const v1Endpoint = (0, import_url_parser.parseUrl)(endpoint.url); + if (endpoint.headers) { + v1Endpoint.headers = {}; + for (const [name, values2] of Object.entries(endpoint.headers)) { + v1Endpoint.headers[name.toLowerCase()] = values2.join(", "); + } + } + return v1Endpoint; + } + return endpoint; + } + return (0, import_url_parser.parseUrl)(endpoint); + }; + } +}); + +// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/endpoints/index.js +var endpoints_exports = {}; +__export(endpoints_exports, { + toEndpointV1: () => toEndpointV1 +}); +var init_endpoints = __esm({ + "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/endpoints/index.js"() { + init_toEndpointV1(); + } +}); + +// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/schema/middleware/schemaSerializationMiddleware.js +var import_util_middleware2, schemaSerializationMiddleware; +var init_schemaSerializationMiddleware = __esm({ + "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/schema/middleware/schemaSerializationMiddleware.js"() { + init_endpoints(); + import_util_middleware2 = __toESM(require_dist_cjs18()); + init_operation(); + schemaSerializationMiddleware = (config3) => (next, context) => async (args) => { + const { operationSchema } = (0, import_util_middleware2.getSmithyContext)(context); + const [, ns, n5, t5, i5, o5] = operationSchema ?? []; + const endpoint = context.endpointV2 ? async () => toEndpointV1(context.endpointV2) : config3.endpoint; + const request = await config3.protocol.serializeRequest(operation(ns, n5, t5, i5, o5), args.input, { + ...config3, + ...context, + endpoint + }); + return next({ + ...args, + request + }); + }; + } +}); + +// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/schema/middleware/getSchemaSerdePlugin.js +function getSchemaSerdePlugin(config3) { + return { + applyToStack: (commandStack) => { + commandStack.add(schemaSerializationMiddleware(config3), serializerMiddlewareOption); + commandStack.add(schemaDeserializationMiddleware(config3), deserializerMiddlewareOption); + config3.protocol.setSerdeContext(config3); + } + }; +} +var deserializerMiddlewareOption, serializerMiddlewareOption; +var init_getSchemaSerdePlugin = __esm({ + "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/schema/middleware/getSchemaSerdePlugin.js"() { + init_schemaDeserializationMiddleware(); + init_schemaSerializationMiddleware(); + deserializerMiddlewareOption = { + name: "deserializerMiddleware", + step: "deserialize", + tags: ["DESERIALIZER"], + override: true + }; + serializerMiddlewareOption = { + name: "serializerMiddleware", + step: "serialize", + tags: ["SERIALIZER"], + override: true + }; + } +}); + +// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/schema/schemas/Schema.js +var Schema2; +var init_Schema = __esm({ + "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/schema/schemas/Schema.js"() { + Schema2 = class { + name; + namespace; + traits; + static assign(instance, values2) { + const schema2 = Object.assign(instance, values2); + return schema2; + } + static [Symbol.hasInstance](lhs) { + const isPrototype = this.prototype.isPrototypeOf(lhs); + if (!isPrototype && typeof lhs === "object" && lhs !== null) { + const list2 = lhs; + return list2.symbol === this.symbol; + } + return isPrototype; + } + getName() { + return this.namespace + "#" + this.name; + } + }; + } +}); + +// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/schema/schemas/ListSchema.js +var ListSchema, list; +var init_ListSchema = __esm({ + "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/schema/schemas/ListSchema.js"() { + init_Schema(); + ListSchema = class _ListSchema extends Schema2 { + static symbol = /* @__PURE__ */ Symbol.for("@smithy/lis"); + name; + traits; + valueSchema; + symbol = _ListSchema.symbol; + }; + list = (namespace, name, traits, valueSchema) => Schema2.assign(new ListSchema(), { + name, + namespace, + traits, + valueSchema + }); + } +}); + +// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/schema/schemas/MapSchema.js +var MapSchema, map; +var init_MapSchema = __esm({ + "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/schema/schemas/MapSchema.js"() { + init_Schema(); + MapSchema = class _MapSchema extends Schema2 { + static symbol = /* @__PURE__ */ Symbol.for("@smithy/map"); + name; + traits; + keySchema; + valueSchema; + symbol = _MapSchema.symbol; + }; + map = (namespace, name, traits, keySchema, valueSchema) => Schema2.assign(new MapSchema(), { + name, + namespace, + traits, + keySchema, + valueSchema + }); + } +}); + +// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/schema/schemas/OperationSchema.js +var OperationSchema, op; +var init_OperationSchema = __esm({ + "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/schema/schemas/OperationSchema.js"() { + init_Schema(); + OperationSchema = class _OperationSchema extends Schema2 { + static symbol = /* @__PURE__ */ Symbol.for("@smithy/ope"); + name; + traits; + input; + output; + symbol = _OperationSchema.symbol; + }; + op = (namespace, name, traits, input, output) => Schema2.assign(new OperationSchema(), { + name, + namespace, + traits, + input, + output + }); + } +}); + +// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/schema/schemas/StructureSchema.js +var StructureSchema, struct; +var init_StructureSchema = __esm({ + "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/schema/schemas/StructureSchema.js"() { + init_Schema(); + StructureSchema = class _StructureSchema extends Schema2 { + static symbol = /* @__PURE__ */ Symbol.for("@smithy/str"); + name; + traits; + memberNames; + memberList; + symbol = _StructureSchema.symbol; + }; + struct = (namespace, name, traits, memberNames, memberList) => Schema2.assign(new StructureSchema(), { + name, + namespace, + traits, + memberNames, + memberList + }); + } +}); + +// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/schema/schemas/ErrorSchema.js +var ErrorSchema, error; +var init_ErrorSchema = __esm({ + "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/schema/schemas/ErrorSchema.js"() { + init_Schema(); + init_StructureSchema(); + ErrorSchema = class _ErrorSchema extends StructureSchema { + static symbol = /* @__PURE__ */ Symbol.for("@smithy/err"); + ctor; + symbol = _ErrorSchema.symbol; + }; + error = (namespace, name, traits, memberNames, memberList, ctor) => Schema2.assign(new ErrorSchema(), { + name, + namespace, + traits, + memberNames, + memberList, + ctor: null + }); + } +}); + +// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/schema/schemas/translateTraits.js +function translateTraits(indicator) { + if (typeof indicator === "object") { + return indicator; + } + indicator = indicator | 0; + if (traitsCache[indicator]) { + return traitsCache[indicator]; + } + const traits = {}; + let i5 = 0; + for (const trait of [ + "httpLabel", + "idempotent", + "idempotencyToken", + "sensitive", + "httpPayload", + "httpResponseCode", + "httpQueryParams" + ]) { + if ((indicator >> i5++ & 1) === 1) { + traits[trait] = 1; + } + } + return traitsCache[indicator] = traits; +} +var traitsCache; +var init_translateTraits = __esm({ + "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/schema/schemas/translateTraits.js"() { + traitsCache = []; + } +}); + +// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/schema/schemas/NormalizedSchema.js +function member(memberSchema, memberName) { + if (memberSchema instanceof NormalizedSchema) { + return Object.assign(memberSchema, { + memberName, + _isMemberSchema: true + }); + } + const internalCtorAccess = NormalizedSchema; + return new internalCtorAccess(memberSchema, memberName); +} +var anno, simpleSchemaCacheN, simpleSchemaCacheS, NormalizedSchema, isMemberSchema, isStaticSchema; +var init_NormalizedSchema = __esm({ + "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/schema/schemas/NormalizedSchema.js"() { + init_deref(); + init_translateTraits(); + anno = { + it: /* @__PURE__ */ Symbol.for("@smithy/nor-struct-it"), + ns: /* @__PURE__ */ Symbol.for("@smithy/ns") + }; + simpleSchemaCacheN = []; + simpleSchemaCacheS = {}; + NormalizedSchema = class _NormalizedSchema { + ref; + memberName; + static symbol = /* @__PURE__ */ Symbol.for("@smithy/nor"); + symbol = _NormalizedSchema.symbol; + name; + schema; + _isMemberSchema; + traits; + memberTraits; + normalizedTraits; + constructor(ref, memberName) { + this.ref = ref; + this.memberName = memberName; + const traitStack = []; + let _ref = ref; + let schema2 = ref; + this._isMemberSchema = false; + while (isMemberSchema(_ref)) { + traitStack.push(_ref[1]); + _ref = _ref[0]; + schema2 = deref(_ref); + this._isMemberSchema = true; + } + if (traitStack.length > 0) { + this.memberTraits = {}; + for (let i5 = traitStack.length - 1; i5 >= 0; --i5) { + const traitSet = traitStack[i5]; + Object.assign(this.memberTraits, translateTraits(traitSet)); + } + } else { + this.memberTraits = 0; + } + if (schema2 instanceof _NormalizedSchema) { + const computedMemberTraits = this.memberTraits; + Object.assign(this, schema2); + this.memberTraits = Object.assign({}, computedMemberTraits, schema2.getMemberTraits(), this.getMemberTraits()); + this.normalizedTraits = void 0; + this.memberName = memberName ?? schema2.memberName; + return; + } + this.schema = deref(schema2); + if (isStaticSchema(this.schema)) { + this.name = `${this.schema[1]}#${this.schema[2]}`; + this.traits = this.schema[3]; + } else { + this.name = this.memberName ?? String(schema2); + this.traits = 0; + } + if (this._isMemberSchema && !memberName) { + throw new Error(`@smithy/core/schema - NormalizedSchema member init ${this.getName(true)} missing member name.`); + } + } + static [Symbol.hasInstance](lhs) { + const isPrototype = this.prototype.isPrototypeOf(lhs); + if (!isPrototype && typeof lhs === "object" && lhs !== null) { + const ns = lhs; + return ns.symbol === this.symbol; + } + return isPrototype; + } + static of(ref) { + const keyAble = typeof ref === "function" || typeof ref === "object" && ref !== null; + if (typeof ref === "number") { + if (simpleSchemaCacheN[ref]) { + return simpleSchemaCacheN[ref]; + } + } else if (typeof ref === "string") { + if (simpleSchemaCacheS[ref]) { + return simpleSchemaCacheS[ref]; + } + } else if (keyAble) { + if (ref[anno.ns]) { + return ref[anno.ns]; + } + } + const sc = deref(ref); + if (sc instanceof _NormalizedSchema) { + return sc; + } + if (isMemberSchema(sc)) { + const [ns2, traits] = sc; + if (ns2 instanceof _NormalizedSchema) { + Object.assign(ns2.getMergedTraits(), translateTraits(traits)); + return ns2; + } + throw new Error(`@smithy/core/schema - may not init unwrapped member schema=${JSON.stringify(ref, null, 2)}.`); + } + const ns = new _NormalizedSchema(sc); + if (keyAble) { + return ref[anno.ns] = ns; + } + if (typeof sc === "string") { + return simpleSchemaCacheS[sc] = ns; + } + if (typeof sc === "number") { + return simpleSchemaCacheN[sc] = ns; + } + return ns; + } + getSchema() { + const sc = this.schema; + if (Array.isArray(sc) && sc[0] === 0) { + return sc[4]; + } + return sc; + } + getName(withNamespace = false) { + const { name } = this; + const short = !withNamespace && name && name.includes("#"); + return short ? name.split("#")[1] : name || void 0; + } + getMemberName() { + return this.memberName; + } + isMemberSchema() { + return this._isMemberSchema; + } + isListSchema() { + const sc = this.getSchema(); + return typeof sc === "number" ? sc >= 64 && sc < 128 : sc[0] === 1; + } + isMapSchema() { + const sc = this.getSchema(); + return typeof sc === "number" ? sc >= 128 && sc <= 255 : sc[0] === 2; + } + isStructSchema() { + const sc = this.getSchema(); + if (typeof sc !== "object") { + return false; + } + const id = sc[0]; + return id === 3 || id === -3 || id === 4; + } + isUnionSchema() { + const sc = this.getSchema(); + if (typeof sc !== "object") { + return false; + } + return sc[0] === 4; + } + isBlobSchema() { + const sc = this.getSchema(); + return sc === 21 || sc === 42; + } + isTimestampSchema() { + const sc = this.getSchema(); + return typeof sc === "number" && sc >= 4 && sc <= 7; + } + isUnitSchema() { + return this.getSchema() === "unit"; + } + isDocumentSchema() { + return this.getSchema() === 15; + } + isStringSchema() { + return this.getSchema() === 0; + } + isBooleanSchema() { + return this.getSchema() === 2; + } + isNumericSchema() { + return this.getSchema() === 1; + } + isBigIntegerSchema() { + return this.getSchema() === 17; + } + isBigDecimalSchema() { + return this.getSchema() === 19; + } + isStreaming() { + const { streaming } = this.getMergedTraits(); + return !!streaming || this.getSchema() === 42; + } + isIdempotencyToken() { + return !!this.getMergedTraits().idempotencyToken; + } + getMergedTraits() { + return this.normalizedTraits ?? (this.normalizedTraits = { + ...this.getOwnTraits(), + ...this.getMemberTraits() + }); + } + getMemberTraits() { + return translateTraits(this.memberTraits); + } + getOwnTraits() { + return translateTraits(this.traits); + } + getKeySchema() { + const [isDoc, isMap] = [this.isDocumentSchema(), this.isMapSchema()]; + if (!isDoc && !isMap) { + throw new Error(`@smithy/core/schema - cannot get key for non-map: ${this.getName(true)}`); + } + const schema2 = this.getSchema(); + const memberSchema = isDoc ? 15 : schema2[4] ?? 0; + return member([memberSchema, 0], "key"); + } + getValueSchema() { + const sc = this.getSchema(); + const [isDoc, isMap, isList] = [this.isDocumentSchema(), this.isMapSchema(), this.isListSchema()]; + const memberSchema = typeof sc === "number" ? 63 & sc : sc && typeof sc === "object" && (isMap || isList) ? sc[3 + sc[0]] : isDoc ? 15 : void 0; + if (memberSchema != null) { + return member([memberSchema, 0], isMap ? "value" : "member"); + } + throw new Error(`@smithy/core/schema - ${this.getName(true)} has no value member.`); + } + getMemberSchema(memberName) { + const struct2 = this.getSchema(); + if (this.isStructSchema() && struct2[4].includes(memberName)) { + const i5 = struct2[4].indexOf(memberName); + const memberSchema = struct2[5][i5]; + return member(isMemberSchema(memberSchema) ? memberSchema : [memberSchema, 0], memberName); + } + if (this.isDocumentSchema()) { + return member([15, 0], memberName); + } + throw new Error(`@smithy/core/schema - ${this.getName(true)} has no member=${memberName}.`); + } + getMemberSchemas() { + const buffer2 = {}; + try { + for (const [k5, v5] of this.structIterator()) { + buffer2[k5] = v5; + } + } catch (ignored) { + } + return buffer2; + } + getEventStreamMember() { + if (this.isStructSchema()) { + for (const [memberName, memberSchema] of this.structIterator()) { + if (memberSchema.isStreaming() && memberSchema.isStructSchema()) { + return memberName; + } + } + } + return ""; + } + *structIterator() { + if (this.isUnitSchema()) { + return; + } + if (!this.isStructSchema()) { + throw new Error("@smithy/core/schema - cannot iterate non-struct schema."); + } + const struct2 = this.getSchema(); + const z3 = struct2[4].length; + let it = struct2[anno.it]; + if (it && z3 === it.length) { + yield* it; + return; + } + it = Array(z3); + for (let i5 = 0; i5 < z3; ++i5) { + const k5 = struct2[4][i5]; + const v5 = member([struct2[5][i5], 0], k5); + yield it[i5] = [k5, v5]; + } + struct2[anno.it] = it; + } + }; + isMemberSchema = (sc) => Array.isArray(sc) && sc.length === 2; + isStaticSchema = (sc) => Array.isArray(sc) && sc.length >= 5; + } +}); + +// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/schema/schemas/SimpleSchema.js +var SimpleSchema, sim, simAdapter; +var init_SimpleSchema = __esm({ + "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/schema/schemas/SimpleSchema.js"() { + init_Schema(); + SimpleSchema = class _SimpleSchema extends Schema2 { + static symbol = /* @__PURE__ */ Symbol.for("@smithy/sim"); + name; + schemaRef; + traits; + symbol = _SimpleSchema.symbol; + }; + sim = (namespace, name, schemaRef, traits) => Schema2.assign(new SimpleSchema(), { + name, + namespace, + traits, + schemaRef + }); + simAdapter = (namespace, name, traits, schemaRef) => Schema2.assign(new SimpleSchema(), { + name, + namespace, + traits, + schemaRef + }); + } +}); + +// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/schema/schemas/sentinels.js +var SCHEMA; +var init_sentinels = __esm({ + "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/schema/schemas/sentinels.js"() { + SCHEMA = { + BLOB: 21, + STREAMING_BLOB: 42, + BOOLEAN: 2, + STRING: 0, + NUMERIC: 1, + BIG_INTEGER: 17, + BIG_DECIMAL: 19, + DOCUMENT: 15, + TIMESTAMP_DEFAULT: 4, + TIMESTAMP_DATE_TIME: 5, + TIMESTAMP_HTTP_DATE: 6, + TIMESTAMP_EPOCH_SECONDS: 7, + LIST_MODIFIER: 64, + MAP_MODIFIER: 128 + }; + } +}); + +// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/schema/TypeRegistry.js +var TypeRegistry; +var init_TypeRegistry = __esm({ + "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/schema/TypeRegistry.js"() { + TypeRegistry = class _TypeRegistry { + namespace; + schemas; + exceptions; + static registries = /* @__PURE__ */ new Map(); + constructor(namespace, schemas = /* @__PURE__ */ new Map(), exceptions = /* @__PURE__ */ new Map()) { + this.namespace = namespace; + this.schemas = schemas; + this.exceptions = exceptions; + } + static for(namespace) { + if (!_TypeRegistry.registries.has(namespace)) { + _TypeRegistry.registries.set(namespace, new _TypeRegistry(namespace)); + } + return _TypeRegistry.registries.get(namespace); + } + copyFrom(other) { + const { schemas, exceptions } = this; + for (const [k5, v5] of other.schemas) { + if (!schemas.has(k5)) { + schemas.set(k5, v5); + } + } + for (const [k5, v5] of other.exceptions) { + if (!exceptions.has(k5)) { + exceptions.set(k5, v5); + } + } + } + register(shapeId, schema2) { + const qualifiedName = this.normalizeShapeId(shapeId); + for (const r5 of [this, _TypeRegistry.for(qualifiedName.split("#")[0])]) { + r5.schemas.set(qualifiedName, schema2); + } + } + getSchema(shapeId) { + const id = this.normalizeShapeId(shapeId); + if (!this.schemas.has(id)) { + throw new Error(`@smithy/core/schema - schema not found for ${id}`); + } + return this.schemas.get(id); + } + registerError(es, ctor) { + const $error = es; + const ns = $error[1]; + for (const r5 of [this, _TypeRegistry.for(ns)]) { + r5.schemas.set(ns + "#" + $error[2], $error); + r5.exceptions.set($error, ctor); + } + } + getErrorCtor(es) { + const $error = es; + if (this.exceptions.has($error)) { + return this.exceptions.get($error); + } + const registry2 = _TypeRegistry.for($error[1]); + return registry2.exceptions.get($error); + } + getBaseException() { + for (const exceptionKey of this.exceptions.keys()) { + if (Array.isArray(exceptionKey)) { + const [, ns, name] = exceptionKey; + const id = ns + "#" + name; + if (id.startsWith("smithy.ts.sdk.synthetic.") && id.endsWith("ServiceException")) { + return exceptionKey; + } + } + } + return void 0; + } + find(predicate) { + return [...this.schemas.values()].find(predicate); + } + clear() { + this.schemas.clear(); + this.exceptions.clear(); + } + normalizeShapeId(shapeId) { + if (shapeId.includes("#")) { + return shapeId; + } + return this.namespace + "#" + shapeId; + } + }; + } +}); + +// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/schema/index.js +var schema_exports2 = {}; +__export(schema_exports2, { + ErrorSchema: () => ErrorSchema, + ListSchema: () => ListSchema, + MapSchema: () => MapSchema, + NormalizedSchema: () => NormalizedSchema, + OperationSchema: () => OperationSchema, + SCHEMA: () => SCHEMA, + Schema: () => Schema2, + SimpleSchema: () => SimpleSchema, + StructureSchema: () => StructureSchema, + TypeRegistry: () => TypeRegistry, + deref: () => deref, + deserializerMiddlewareOption: () => deserializerMiddlewareOption, + error: () => error, + getSchemaSerdePlugin: () => getSchemaSerdePlugin, + isStaticSchema: () => isStaticSchema, + list: () => list, + map: () => map, + op: () => op, + operation: () => operation, + serializerMiddlewareOption: () => serializerMiddlewareOption, + sim: () => sim, + simAdapter: () => simAdapter, + simpleSchemaCacheN: () => simpleSchemaCacheN, + simpleSchemaCacheS: () => simpleSchemaCacheS, + struct: () => struct, + traitsCache: () => traitsCache, + translateTraits: () => translateTraits +}); +var init_schema3 = __esm({ + "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/schema/index.js"() { + init_deref(); + init_getSchemaSerdePlugin(); + init_ListSchema(); + init_MapSchema(); + init_OperationSchema(); + init_operation(); + init_ErrorSchema(); + init_NormalizedSchema(); + init_Schema(); + init_SimpleSchema(); + init_StructureSchema(); + init_sentinels(); + init_translateTraits(); + init_TypeRegistry(); + } +}); + +// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/serde/copyDocumentWithTransform.js +var copyDocumentWithTransform; +var init_copyDocumentWithTransform = __esm({ + "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/serde/copyDocumentWithTransform.js"() { + copyDocumentWithTransform = (source, schemaRef, transform3 = (_) => _) => source; + } +}); + +// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/serde/parse-utils.js +var parseBoolean2, expectBoolean, expectNumber, MAX_FLOAT, expectFloat32, expectLong, expectInt, expectInt32, expectShort, expectByte, expectSizedInt, castInt, expectNonNull, expectObject, expectString, expectUnion, strictParseDouble, strictParseFloat, strictParseFloat32, NUMBER_REGEX, parseNumber2, limitedParseDouble, handleFloat, limitedParseFloat, limitedParseFloat32, parseFloatString, strictParseLong, strictParseInt, strictParseInt32, strictParseShort, strictParseByte, stackTraceWarning, logger2; +var init_parse_utils = __esm({ + "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/serde/parse-utils.js"() { + parseBoolean2 = (value) => { + switch (value) { + case "true": + return true; + case "false": + return false; + default: + throw new Error(`Unable to parse boolean value "${value}"`); + } + }; + expectBoolean = (value) => { + if (value === null || value === void 0) { + return void 0; + } + if (typeof value === "number") { + if (value === 0 || value === 1) { + logger2.warn(stackTraceWarning(`Expected boolean, got ${typeof value}: ${value}`)); + } + if (value === 0) { + return false; + } + if (value === 1) { + return true; + } + } + if (typeof value === "string") { + const lower = value.toLowerCase(); + if (lower === "false" || lower === "true") { + logger2.warn(stackTraceWarning(`Expected boolean, got ${typeof value}: ${value}`)); + } + if (lower === "false") { + return false; + } + if (lower === "true") { + return true; + } + } + if (typeof value === "boolean") { + return value; + } + throw new TypeError(`Expected boolean, got ${typeof value}: ${value}`); + }; + expectNumber = (value) => { + if (value === null || value === void 0) { + return void 0; + } + if (typeof value === "string") { + const parsed = parseFloat(value); + if (!Number.isNaN(parsed)) { + if (String(parsed) !== String(value)) { + logger2.warn(stackTraceWarning(`Expected number but observed string: ${value}`)); + } + return parsed; + } + } + if (typeof value === "number") { + return value; + } + throw new TypeError(`Expected number, got ${typeof value}: ${value}`); + }; + MAX_FLOAT = Math.ceil(2 ** 127 * (2 - 2 ** -23)); + expectFloat32 = (value) => { + const expected = expectNumber(value); + if (expected !== void 0 && !Number.isNaN(expected) && expected !== Infinity && expected !== -Infinity) { + if (Math.abs(expected) > MAX_FLOAT) { + throw new TypeError(`Expected 32-bit float, got ${value}`); + } + } + return expected; + }; + expectLong = (value) => { + if (value === null || value === void 0) { + return void 0; + } + if (Number.isInteger(value) && !Number.isNaN(value)) { + return value; + } + throw new TypeError(`Expected integer, got ${typeof value}: ${value}`); + }; + expectInt = expectLong; + expectInt32 = (value) => expectSizedInt(value, 32); + expectShort = (value) => expectSizedInt(value, 16); + expectByte = (value) => expectSizedInt(value, 8); + expectSizedInt = (value, size2) => { + const expected = expectLong(value); + if (expected !== void 0 && castInt(expected, size2) !== expected) { + throw new TypeError(`Expected ${size2}-bit integer, got ${value}`); + } + return expected; + }; + castInt = (value, size2) => { + switch (size2) { + case 32: + return Int32Array.of(value)[0]; + case 16: + return Int16Array.of(value)[0]; + case 8: + return Int8Array.of(value)[0]; + } + }; + expectNonNull = (value, location) => { + if (value === null || value === void 0) { + if (location) { + throw new TypeError(`Expected a non-null value for ${location}`); + } + throw new TypeError("Expected a non-null value"); + } + return value; + }; + expectObject = (value) => { + if (value === null || value === void 0) { + return void 0; + } + if (typeof value === "object" && !Array.isArray(value)) { + return value; + } + const receivedType = Array.isArray(value) ? "array" : typeof value; + throw new TypeError(`Expected object, got ${receivedType}: ${value}`); + }; + expectString = (value) => { + if (value === null || value === void 0) { + return void 0; + } + if (typeof value === "string") { + return value; + } + if (["boolean", "number", "bigint"].includes(typeof value)) { + logger2.warn(stackTraceWarning(`Expected string, got ${typeof value}: ${value}`)); + return String(value); + } + throw new TypeError(`Expected string, got ${typeof value}: ${value}`); + }; + expectUnion = (value) => { + if (value === null || value === void 0) { + return void 0; + } + const asObject = expectObject(value); + const setKeys = Object.entries(asObject).filter(([, v5]) => v5 != null).map(([k5]) => k5); + if (setKeys.length === 0) { + throw new TypeError(`Unions must have exactly one non-null member. None were found.`); + } + if (setKeys.length > 1) { + throw new TypeError(`Unions must have exactly one non-null member. Keys ${setKeys} were not null.`); + } + return asObject; + }; + strictParseDouble = (value) => { + if (typeof value == "string") { + return expectNumber(parseNumber2(value)); + } + return expectNumber(value); + }; + strictParseFloat = strictParseDouble; + strictParseFloat32 = (value) => { + if (typeof value == "string") { + return expectFloat32(parseNumber2(value)); + } + return expectFloat32(value); + }; + NUMBER_REGEX = /(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)|(-?Infinity)|(NaN)/g; + parseNumber2 = (value) => { + const matches = value.match(NUMBER_REGEX); + if (matches === null || matches[0].length !== value.length) { + throw new TypeError(`Expected real number, got implicit NaN`); + } + return parseFloat(value); + }; + limitedParseDouble = (value) => { + if (typeof value == "string") { + return parseFloatString(value); + } + return expectNumber(value); + }; + handleFloat = limitedParseDouble; + limitedParseFloat = limitedParseDouble; + limitedParseFloat32 = (value) => { + if (typeof value == "string") { + return parseFloatString(value); + } + return expectFloat32(value); + }; + parseFloatString = (value) => { + switch (value) { + case "NaN": + return NaN; + case "Infinity": + return Infinity; + case "-Infinity": + return -Infinity; + default: + throw new Error(`Unable to parse float value: ${value}`); + } + }; + strictParseLong = (value) => { + if (typeof value === "string") { + return expectLong(parseNumber2(value)); + } + return expectLong(value); + }; + strictParseInt = strictParseLong; + strictParseInt32 = (value) => { + if (typeof value === "string") { + return expectInt32(parseNumber2(value)); + } + return expectInt32(value); + }; + strictParseShort = (value) => { + if (typeof value === "string") { + return expectShort(parseNumber2(value)); + } + return expectShort(value); + }; + strictParseByte = (value) => { + if (typeof value === "string") { + return expectByte(parseNumber2(value)); + } + return expectByte(value); + }; + stackTraceWarning = (message2) => { + return String(new TypeError(message2).stack || message2).split("\n").slice(0, 5).filter((s5) => !s5.includes("stackTraceWarning")).join("\n"); + }; + logger2 = { + warn: console.warn + }; + } +}); + +// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/serde/date-utils.js +function dateToUtcString(date7) { + const year3 = date7.getUTCFullYear(); + const month = date7.getUTCMonth(); + const dayOfWeek = date7.getUTCDay(); + const dayOfMonthInt = date7.getUTCDate(); + const hoursInt = date7.getUTCHours(); + const minutesInt = date7.getUTCMinutes(); + const secondsInt = date7.getUTCSeconds(); + const dayOfMonthString = dayOfMonthInt < 10 ? `0${dayOfMonthInt}` : `${dayOfMonthInt}`; + const hoursString = hoursInt < 10 ? `0${hoursInt}` : `${hoursInt}`; + const minutesString = minutesInt < 10 ? `0${minutesInt}` : `${minutesInt}`; + const secondsString = secondsInt < 10 ? `0${secondsInt}` : `${secondsInt}`; + return `${DAYS[dayOfWeek]}, ${dayOfMonthString} ${MONTHS[month]} ${year3} ${hoursString}:${minutesString}:${secondsString} GMT`; +} +var DAYS, MONTHS, RFC3339, parseRfc3339DateTime, RFC3339_WITH_OFFSET, parseRfc3339DateTimeWithOffset, IMF_FIXDATE, RFC_850_DATE, ASC_TIME, parseRfc7231DateTime, parseEpochTimestamp, buildDate, parseTwoDigitYear, FIFTY_YEARS_IN_MILLIS, adjustRfc850Year, parseMonthByShortName, DAYS_IN_MONTH, validateDayOfMonth, isLeapYear, parseDateValue, parseMilliseconds, parseOffsetToMilliseconds, stripLeadingZeroes; +var init_date_utils = __esm({ + "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/serde/date-utils.js"() { + init_parse_utils(); + DAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; + MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; + RFC3339 = new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?[zZ]$/); + parseRfc3339DateTime = (value) => { + if (value === null || value === void 0) { + return void 0; + } + if (typeof value !== "string") { + throw new TypeError("RFC-3339 date-times must be expressed as strings"); + } + const match = RFC3339.exec(value); + if (!match) { + throw new TypeError("Invalid RFC-3339 date-time value"); + } + const [_, yearStr, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds] = match; + const year3 = strictParseShort(stripLeadingZeroes(yearStr)); + const month = parseDateValue(monthStr, "month", 1, 12); + const day2 = parseDateValue(dayStr, "day", 1, 31); + return buildDate(year3, month, day2, { hours, minutes, seconds, fractionalMilliseconds }); + }; + RFC3339_WITH_OFFSET = new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}\:\d{2})|[zZ])$/); + parseRfc3339DateTimeWithOffset = (value) => { + if (value === null || value === void 0) { + return void 0; + } + if (typeof value !== "string") { + throw new TypeError("RFC-3339 date-times must be expressed as strings"); + } + const match = RFC3339_WITH_OFFSET.exec(value); + if (!match) { + throw new TypeError("Invalid RFC-3339 date-time value"); + } + const [_, yearStr, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds, offsetStr] = match; + const year3 = strictParseShort(stripLeadingZeroes(yearStr)); + const month = parseDateValue(monthStr, "month", 1, 12); + const day2 = parseDateValue(dayStr, "day", 1, 31); + const date7 = buildDate(year3, month, day2, { hours, minutes, seconds, fractionalMilliseconds }); + if (offsetStr.toUpperCase() != "Z") { + date7.setTime(date7.getTime() - parseOffsetToMilliseconds(offsetStr)); + } + return date7; + }; + IMF_FIXDATE = new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/); + RFC_850_DATE = new RegExp(/^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/); + ASC_TIME = new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( [1-9]|\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? (\d{4})$/); + parseRfc7231DateTime = (value) => { + if (value === null || value === void 0) { + return void 0; + } + if (typeof value !== "string") { + throw new TypeError("RFC-7231 date-times must be expressed as strings"); + } + let match = IMF_FIXDATE.exec(value); + if (match) { + const [_, dayStr, monthStr, yearStr, hours, minutes, seconds, fractionalMilliseconds] = match; + return buildDate(strictParseShort(stripLeadingZeroes(yearStr)), parseMonthByShortName(monthStr), parseDateValue(dayStr, "day", 1, 31), { hours, minutes, seconds, fractionalMilliseconds }); + } + match = RFC_850_DATE.exec(value); + if (match) { + const [_, dayStr, monthStr, yearStr, hours, minutes, seconds, fractionalMilliseconds] = match; + return adjustRfc850Year(buildDate(parseTwoDigitYear(yearStr), parseMonthByShortName(monthStr), parseDateValue(dayStr, "day", 1, 31), { + hours, + minutes, + seconds, + fractionalMilliseconds + })); + } + match = ASC_TIME.exec(value); + if (match) { + const [_, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds, yearStr] = match; + return buildDate(strictParseShort(stripLeadingZeroes(yearStr)), parseMonthByShortName(monthStr), parseDateValue(dayStr.trimLeft(), "day", 1, 31), { hours, minutes, seconds, fractionalMilliseconds }); + } + throw new TypeError("Invalid RFC-7231 date-time value"); + }; + parseEpochTimestamp = (value) => { + if (value === null || value === void 0) { + return void 0; + } + let valueAsDouble; + if (typeof value === "number") { + valueAsDouble = value; + } else if (typeof value === "string") { + valueAsDouble = strictParseDouble(value); + } else if (typeof value === "object" && value.tag === 1) { + valueAsDouble = value.value; + } else { + throw new TypeError("Epoch timestamps must be expressed as floating point numbers or their string representation"); + } + if (Number.isNaN(valueAsDouble) || valueAsDouble === Infinity || valueAsDouble === -Infinity) { + throw new TypeError("Epoch timestamps must be valid, non-Infinite, non-NaN numerics"); + } + return new Date(Math.round(valueAsDouble * 1e3)); + }; + buildDate = (year3, month, day2, time5) => { + const adjustedMonth = month - 1; + validateDayOfMonth(year3, adjustedMonth, day2); + return new Date(Date.UTC(year3, adjustedMonth, day2, parseDateValue(time5.hours, "hour", 0, 23), parseDateValue(time5.minutes, "minute", 0, 59), parseDateValue(time5.seconds, "seconds", 0, 60), parseMilliseconds(time5.fractionalMilliseconds))); + }; + parseTwoDigitYear = (value) => { + const thisYear = (/* @__PURE__ */ new Date()).getUTCFullYear(); + const valueInThisCentury = Math.floor(thisYear / 100) * 100 + strictParseShort(stripLeadingZeroes(value)); + if (valueInThisCentury < thisYear) { + return valueInThisCentury + 100; + } + return valueInThisCentury; + }; + FIFTY_YEARS_IN_MILLIS = 50 * 365 * 24 * 60 * 60 * 1e3; + adjustRfc850Year = (input) => { + if (input.getTime() - (/* @__PURE__ */ new Date()).getTime() > FIFTY_YEARS_IN_MILLIS) { + return new Date(Date.UTC(input.getUTCFullYear() - 100, input.getUTCMonth(), input.getUTCDate(), input.getUTCHours(), input.getUTCMinutes(), input.getUTCSeconds(), input.getUTCMilliseconds())); + } + return input; + }; + parseMonthByShortName = (value) => { + const monthIdx = MONTHS.indexOf(value); + if (monthIdx < 0) { + throw new TypeError(`Invalid month: ${value}`); + } + return monthIdx + 1; + }; + DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; + validateDayOfMonth = (year3, month, day2) => { + let maxDays = DAYS_IN_MONTH[month]; + if (month === 1 && isLeapYear(year3)) { + maxDays = 29; + } + if (day2 > maxDays) { + throw new TypeError(`Invalid day for ${MONTHS[month]} in ${year3}: ${day2}`); + } + }; + isLeapYear = (year3) => { + return year3 % 4 === 0 && (year3 % 100 !== 0 || year3 % 400 === 0); + }; + parseDateValue = (value, type, lower, upper) => { + const dateVal = strictParseByte(stripLeadingZeroes(value)); + if (dateVal < lower || dateVal > upper) { + throw new TypeError(`${type} must be between ${lower} and ${upper}, inclusive`); + } + return dateVal; + }; + parseMilliseconds = (value) => { + if (value === null || value === void 0) { + return 0; + } + return strictParseFloat32("0." + value) * 1e3; + }; + parseOffsetToMilliseconds = (value) => { + const directionStr = value[0]; + let direction = 1; + if (directionStr == "+") { + direction = 1; + } else if (directionStr == "-") { + direction = -1; + } else { + throw new TypeError(`Offset direction, ${directionStr}, must be "+" or "-"`); + } + const hour2 = Number(value.substring(1, 3)); + const minute2 = Number(value.substring(4, 6)); + return direction * (hour2 * 60 + minute2) * 60 * 1e3; + }; + stripLeadingZeroes = (value) => { + let idx = 0; + while (idx < value.length - 1 && value.charAt(idx) === "0") { + idx++; + } + if (idx === 0) { + return value; + } + return value.slice(idx); + }; + } +}); + +// node_modules/.pnpm/@smithy+uuid@1.1.2/node_modules/@smithy/uuid/dist-cjs/randomUUID.js +var require_randomUUID = __commonJS({ + "node_modules/.pnpm/@smithy+uuid@1.1.2/node_modules/@smithy/uuid/dist-cjs/randomUUID.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.randomUUID = void 0; + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var crypto_1 = tslib_1.__importDefault(__require("crypto")); + exports.randomUUID = crypto_1.default.randomUUID.bind(crypto_1.default); + } +}); + +// node_modules/.pnpm/@smithy+uuid@1.1.2/node_modules/@smithy/uuid/dist-cjs/index.js +var require_dist_cjs26 = __commonJS({ + "node_modules/.pnpm/@smithy+uuid@1.1.2/node_modules/@smithy/uuid/dist-cjs/index.js"(exports) { + "use strict"; + var randomUUID12 = require_randomUUID(); + var decimalToHex = Array.from({ length: 256 }, (_, i5) => i5.toString(16).padStart(2, "0")); + var v42 = () => { + if (randomUUID12.randomUUID) { + return randomUUID12.randomUUID(); + } + const rnds = new Uint8Array(16); + crypto.getRandomValues(rnds); + rnds[6] = rnds[6] & 15 | 64; + rnds[8] = rnds[8] & 63 | 128; + return decimalToHex[rnds[0]] + decimalToHex[rnds[1]] + decimalToHex[rnds[2]] + decimalToHex[rnds[3]] + "-" + decimalToHex[rnds[4]] + decimalToHex[rnds[5]] + "-" + decimalToHex[rnds[6]] + decimalToHex[rnds[7]] + "-" + decimalToHex[rnds[8]] + decimalToHex[rnds[9]] + "-" + decimalToHex[rnds[10]] + decimalToHex[rnds[11]] + decimalToHex[rnds[12]] + decimalToHex[rnds[13]] + decimalToHex[rnds[14]] + decimalToHex[rnds[15]]; + }; + exports.v4 = v42; + } +}); + +// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/serde/generateIdempotencyToken.js +var import_uuid2; +var init_generateIdempotencyToken = __esm({ + "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/serde/generateIdempotencyToken.js"() { + import_uuid2 = __toESM(require_dist_cjs26()); + } +}); + +// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/serde/lazy-json.js +var LazyJsonString; +var init_lazy_json = __esm({ + "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/serde/lazy-json.js"() { + LazyJsonString = function LazyJsonString2(val) { + const str = Object.assign(new String(val), { + deserializeJSON() { + return JSON.parse(String(val)); + }, + toString() { + return String(val); + }, + toJSON() { + return String(val); + } + }); + return str; + }; + LazyJsonString.from = (object2) => { + if (object2 && typeof object2 === "object" && (object2 instanceof LazyJsonString || "deserializeJSON" in object2)) { + return object2; + } else if (typeof object2 === "string" || Object.getPrototypeOf(object2) === String.prototype) { + return LazyJsonString(String(object2)); + } + return LazyJsonString(JSON.stringify(object2)); + }; + LazyJsonString.fromObject = LazyJsonString.from; + } +}); + +// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/serde/quote-header.js +function quoteHeader(part) { + if (part.includes(",") || part.includes('"')) { + part = `"${part.replace(/"/g, '\\"')}"`; + } + return part; +} +var init_quote_header = __esm({ + "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/serde/quote-header.js"() { + } +}); + +// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/serde/schema-serde-lib/schema-date-utils.js +function range(v5, min, max) { + const _v = Number(v5); + if (_v < min || _v > max) { + throw new Error(`Value ${_v} out of range [${min}, ${max}]`); + } +} +var ddd, mmm, time2, date2, year, RFC3339_WITH_OFFSET2, IMF_FIXDATE2, RFC_850_DATE2, ASC_TIME2, months, _parseEpochTimestamp, _parseRfc3339DateTimeWithOffset, _parseRfc7231DateTime; +var init_schema_date_utils = __esm({ + "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/serde/schema-serde-lib/schema-date-utils.js"() { + ddd = `(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)(?:[ne|u?r]?s?day)?`; + mmm = `(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)`; + time2 = `(\\d?\\d):(\\d{2}):(\\d{2})(?:\\.(\\d+))?`; + date2 = `(\\d?\\d)`; + year = `(\\d{4})`; + RFC3339_WITH_OFFSET2 = new RegExp(/^(\d{4})-(\d\d)-(\d\d)[tT](\d\d):(\d\d):(\d\d)(\.(\d+))?(([-+]\d\d:\d\d)|[zZ])$/); + IMF_FIXDATE2 = new RegExp(`^${ddd}, ${date2} ${mmm} ${year} ${time2} GMT$`); + RFC_850_DATE2 = new RegExp(`^${ddd}, ${date2}-${mmm}-(\\d\\d) ${time2} GMT$`); + ASC_TIME2 = new RegExp(`^${ddd} ${mmm} ( [1-9]|\\d\\d) ${time2} ${year}$`); + months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; + _parseEpochTimestamp = (value) => { + if (value == null) { + return void 0; + } + let num = NaN; + if (typeof value === "number") { + num = value; + } else if (typeof value === "string") { + if (!/^-?\d*\.?\d+$/.test(value)) { + throw new TypeError(`parseEpochTimestamp - numeric string invalid.`); + } + num = Number.parseFloat(value); + } else if (typeof value === "object" && value.tag === 1) { + num = value.value; + } + if (isNaN(num) || Math.abs(num) === Infinity) { + throw new TypeError("Epoch timestamps must be valid finite numbers."); + } + return new Date(Math.round(num * 1e3)); + }; + _parseRfc3339DateTimeWithOffset = (value) => { + if (value == null) { + return void 0; + } + if (typeof value !== "string") { + throw new TypeError("RFC3339 timestamps must be strings"); + } + const matches = RFC3339_WITH_OFFSET2.exec(value); + if (!matches) { + throw new TypeError(`Invalid RFC3339 timestamp format ${value}`); + } + const [, yearStr, monthStr, dayStr, hours, minutes, seconds, , ms, offsetStr] = matches; + range(monthStr, 1, 12); + range(dayStr, 1, 31); + range(hours, 0, 23); + range(minutes, 0, 59); + range(seconds, 0, 60); + const date7 = new Date(Date.UTC(Number(yearStr), Number(monthStr) - 1, Number(dayStr), Number(hours), Number(minutes), Number(seconds), Number(ms) ? Math.round(parseFloat(`0.${ms}`) * 1e3) : 0)); + date7.setUTCFullYear(Number(yearStr)); + if (offsetStr.toUpperCase() != "Z") { + const [, sign2, offsetH, offsetM] = /([+-])(\d\d):(\d\d)/.exec(offsetStr) || [void 0, "+", 0, 0]; + const scalar = sign2 === "-" ? 1 : -1; + date7.setTime(date7.getTime() + scalar * (Number(offsetH) * 60 * 60 * 1e3 + Number(offsetM) * 60 * 1e3)); + } + return date7; + }; + _parseRfc7231DateTime = (value) => { + if (value == null) { + return void 0; + } + if (typeof value !== "string") { + throw new TypeError("RFC7231 timestamps must be strings."); + } + let day2; + let month; + let year3; + let hour2; + let minute2; + let second; + let fraction; + let matches; + if (matches = IMF_FIXDATE2.exec(value)) { + [, day2, month, year3, hour2, minute2, second, fraction] = matches; + } else if (matches = RFC_850_DATE2.exec(value)) { + [, day2, month, year3, hour2, minute2, second, fraction] = matches; + year3 = (Number(year3) + 1900).toString(); + } else if (matches = ASC_TIME2.exec(value)) { + [, month, day2, hour2, minute2, second, fraction, year3] = matches; + } + if (year3 && second) { + const timestamp2 = Date.UTC(Number(year3), months.indexOf(month), Number(day2), Number(hour2), Number(minute2), Number(second), fraction ? Math.round(parseFloat(`0.${fraction}`) * 1e3) : 0); + range(day2, 1, 31); + range(hour2, 0, 23); + range(minute2, 0, 59); + range(second, 0, 60); + const date7 = new Date(timestamp2); + date7.setUTCFullYear(Number(year3)); + return date7; + } + throw new TypeError(`Invalid RFC7231 date-time value ${value}.`); + }; + } +}); + +// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/serde/split-every.js +function splitEvery(value, delimiter, numDelimiters) { + if (numDelimiters <= 0 || !Number.isInteger(numDelimiters)) { + throw new Error("Invalid number of delimiters (" + numDelimiters + ") for splitEvery."); + } + const segments = value.split(delimiter); + if (numDelimiters === 1) { + return segments; + } + const compoundSegments = []; + let currentSegment = ""; + for (let i5 = 0; i5 < segments.length; i5++) { + if (currentSegment === "") { + currentSegment = segments[i5]; + } else { + currentSegment += delimiter + segments[i5]; + } + if ((i5 + 1) % numDelimiters === 0) { + compoundSegments.push(currentSegment); + currentSegment = ""; + } + } + if (currentSegment !== "") { + compoundSegments.push(currentSegment); + } + return compoundSegments; +} +var init_split_every = __esm({ + "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/serde/split-every.js"() { + } +}); + +// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/serde/split-header.js +var splitHeader; +var init_split_header = __esm({ + "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/serde/split-header.js"() { + splitHeader = (value) => { + const z3 = value.length; + const values2 = []; + let withinQuotes = false; + let prevChar = void 0; + let anchor = 0; + for (let i5 = 0; i5 < z3; ++i5) { + const char2 = value[i5]; + switch (char2) { + case `"`: + if (prevChar !== "\\") { + withinQuotes = !withinQuotes; + } + break; + case ",": + if (!withinQuotes) { + values2.push(value.slice(anchor, i5)); + anchor = i5 + 1; + } + break; + default: + } + prevChar = char2; + } + values2.push(value.slice(anchor)); + return values2.map((v5) => { + v5 = v5.trim(); + const z4 = v5.length; + if (z4 < 2) { + return v5; + } + if (v5[0] === `"` && v5[z4 - 1] === `"`) { + v5 = v5.slice(1, z4 - 1); + } + return v5.replace(/\\"/g, '"'); + }); + }; + } +}); + +// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/serde/value/NumericValue.js +function nv(input) { + return new NumericValue(String(input), "bigDecimal"); +} +var format, NumericValue; +var init_NumericValue = __esm({ + "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/serde/value/NumericValue.js"() { + format = /^-?\d*(\.\d+)?$/; + NumericValue = class _NumericValue { + string; + type; + constructor(string4, type) { + this.string = string4; + this.type = type; + if (!format.test(string4)) { + throw new Error(`@smithy/core/serde - NumericValue must only contain [0-9], at most one decimal point ".", and an optional negation prefix "-".`); + } + } + toString() { + return this.string; + } + static [Symbol.hasInstance](object2) { + if (!object2 || typeof object2 !== "object") { + return false; + } + const _nv = object2; + return _NumericValue.prototype.isPrototypeOf(object2) || _nv.type === "bigDecimal" && format.test(_nv.string); + } + }; + } +}); + +// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/serde/index.js +var serde_exports = {}; +__export(serde_exports, { + LazyJsonString: () => LazyJsonString, + NumericValue: () => NumericValue, + _parseEpochTimestamp: () => _parseEpochTimestamp, + _parseRfc3339DateTimeWithOffset: () => _parseRfc3339DateTimeWithOffset, + _parseRfc7231DateTime: () => _parseRfc7231DateTime, + copyDocumentWithTransform: () => copyDocumentWithTransform, + dateToUtcString: () => dateToUtcString, + expectBoolean: () => expectBoolean, + expectByte: () => expectByte, + expectFloat32: () => expectFloat32, + expectInt: () => expectInt, + expectInt32: () => expectInt32, + expectLong: () => expectLong, + expectNonNull: () => expectNonNull, + expectNumber: () => expectNumber, + expectObject: () => expectObject, + expectShort: () => expectShort, + expectString: () => expectString, + expectUnion: () => expectUnion, + generateIdempotencyToken: () => import_uuid2.v4, + handleFloat: () => handleFloat, + limitedParseDouble: () => limitedParseDouble, + limitedParseFloat: () => limitedParseFloat, + limitedParseFloat32: () => limitedParseFloat32, + logger: () => logger2, + nv: () => nv, + parseBoolean: () => parseBoolean2, + parseEpochTimestamp: () => parseEpochTimestamp, + parseRfc3339DateTime: () => parseRfc3339DateTime, + parseRfc3339DateTimeWithOffset: () => parseRfc3339DateTimeWithOffset, + parseRfc7231DateTime: () => parseRfc7231DateTime, + quoteHeader: () => quoteHeader, + splitEvery: () => splitEvery, + splitHeader: () => splitHeader, + strictParseByte: () => strictParseByte, + strictParseDouble: () => strictParseDouble, + strictParseFloat: () => strictParseFloat, + strictParseFloat32: () => strictParseFloat32, + strictParseInt: () => strictParseInt, + strictParseInt32: () => strictParseInt32, + strictParseLong: () => strictParseLong, + strictParseShort: () => strictParseShort +}); +var init_serde = __esm({ + "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/serde/index.js"() { + init_copyDocumentWithTransform(); + init_date_utils(); + init_generateIdempotencyToken(); + init_lazy_json(); + init_parse_utils(); + init_quote_header(); + init_schema_date_utils(); + init_split_every(); + init_split_header(); + init_NumericValue(); + } +}); + +// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/protocols/collect-stream-body.js +var import_util_stream, collectBody; +var init_collect_stream_body = __esm({ + "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/protocols/collect-stream-body.js"() { + import_util_stream = __toESM(require_dist_cjs13()); + collectBody = async (streamBody = new Uint8Array(), context) => { + if (streamBody instanceof Uint8Array) { + return import_util_stream.Uint8ArrayBlobAdapter.mutate(streamBody); + } + if (!streamBody) { + return import_util_stream.Uint8ArrayBlobAdapter.mutate(new Uint8Array()); + } + const fromContext = context.streamCollector(streamBody); + return import_util_stream.Uint8ArrayBlobAdapter.mutate(await fromContext); + }; + } +}); + +// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/protocols/extended-encode-uri-component.js +function extendedEncodeURIComponent(str) { + return encodeURIComponent(str).replace(/[!'()*]/g, function(c5) { + return "%" + c5.charCodeAt(0).toString(16).toUpperCase(); + }); +} +var init_extended_encode_uri_component = __esm({ + "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/protocols/extended-encode-uri-component.js"() { + } +}); + +// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/protocols/SerdeContext.js +var SerdeContext; +var init_SerdeContext = __esm({ + "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/protocols/SerdeContext.js"() { + SerdeContext = class { + serdeContext; + setSerdeContext(serdeContext) { + this.serdeContext = serdeContext; + } + }; + } +}); + +// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/event-streams/EventStreamSerde.js +var import_util_utf8, EventStreamSerde; +var init_EventStreamSerde = __esm({ + "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/event-streams/EventStreamSerde.js"() { + import_util_utf8 = __toESM(require_dist_cjs6()); + EventStreamSerde = class { + marshaller; + serializer; + deserializer; + serdeContext; + defaultContentType; + constructor({ marshaller, serializer, deserializer, serdeContext, defaultContentType }) { + this.marshaller = marshaller; + this.serializer = serializer; + this.deserializer = deserializer; + this.serdeContext = serdeContext; + this.defaultContentType = defaultContentType; + } + async serializeEventStream({ eventStream, requestSchema, initialRequest }) { + const marshaller = this.marshaller; + const eventStreamMember = requestSchema.getEventStreamMember(); + const unionSchema = requestSchema.getMemberSchema(eventStreamMember); + const serializer = this.serializer; + const defaultContentType = this.defaultContentType; + const initialRequestMarker = /* @__PURE__ */ Symbol("initialRequestMarker"); + const eventStreamIterable = { + async *[Symbol.asyncIterator]() { + if (initialRequest) { + const headers = { + ":event-type": { type: "string", value: "initial-request" }, + ":message-type": { type: "string", value: "event" }, + ":content-type": { type: "string", value: defaultContentType } + }; + serializer.write(requestSchema, initialRequest); + const body = serializer.flush(); + yield { + [initialRequestMarker]: true, + headers, + body + }; + } + for await (const page of eventStream) { + yield page; + } + } + }; + return marshaller.serialize(eventStreamIterable, (event) => { + if (event[initialRequestMarker]) { + return { + headers: event.headers, + body: event.body + }; + } + const unionMember = Object.keys(event).find((key) => { + return key !== "__type"; + }) ?? ""; + const { additionalHeaders, body, eventType, explicitPayloadContentType } = this.writeEventBody(unionMember, unionSchema, event); + const headers = { + ":event-type": { type: "string", value: eventType }, + ":message-type": { type: "string", value: "event" }, + ":content-type": { type: "string", value: explicitPayloadContentType ?? defaultContentType }, + ...additionalHeaders + }; + return { + headers, + body + }; + }); + } + async deserializeEventStream({ response, responseSchema, initialResponseContainer }) { + const marshaller = this.marshaller; + const eventStreamMember = responseSchema.getEventStreamMember(); + const unionSchema = responseSchema.getMemberSchema(eventStreamMember); + const memberSchemas = unionSchema.getMemberSchemas(); + const initialResponseMarker = /* @__PURE__ */ Symbol("initialResponseMarker"); + const asyncIterable = marshaller.deserialize(response.body, async (event) => { + const unionMember = Object.keys(event).find((key) => { + return key !== "__type"; + }) ?? ""; + const body = event[unionMember].body; + if (unionMember === "initial-response") { + const dataObject = await this.deserializer.read(responseSchema, body); + delete dataObject[eventStreamMember]; + return { + [initialResponseMarker]: true, + ...dataObject + }; + } else if (unionMember in memberSchemas) { + const eventStreamSchema = memberSchemas[unionMember]; + if (eventStreamSchema.isStructSchema()) { + const out = {}; + let hasBindings = false; + for (const [name, member2] of eventStreamSchema.structIterator()) { + const { eventHeader, eventPayload } = member2.getMergedTraits(); + hasBindings = hasBindings || Boolean(eventHeader || eventPayload); + if (eventPayload) { + if (member2.isBlobSchema()) { + out[name] = body; + } else if (member2.isStringSchema()) { + out[name] = (this.serdeContext?.utf8Encoder ?? import_util_utf8.toUtf8)(body); + } else if (member2.isStructSchema()) { + out[name] = await this.deserializer.read(member2, body); + } + } else if (eventHeader) { + const value = event[unionMember].headers[name]?.value; + if (value != null) { + if (member2.isNumericSchema()) { + if (value && typeof value === "object" && "bytes" in value) { + out[name] = BigInt(value.toString()); + } else { + out[name] = Number(value); + } + } else { + out[name] = value; + } + } + } + } + if (hasBindings) { + return { + [unionMember]: out + }; + } + if (body.byteLength === 0) { + return { + [unionMember]: {} + }; + } + } + return { + [unionMember]: await this.deserializer.read(eventStreamSchema, body) + }; + } else { + return { + $unknown: event + }; + } + }); + const asyncIterator = asyncIterable[Symbol.asyncIterator](); + const firstEvent = await asyncIterator.next(); + if (firstEvent.done) { + return asyncIterable; + } + if (firstEvent.value?.[initialResponseMarker]) { + if (!responseSchema) { + throw new Error("@smithy::core/protocols - initial-response event encountered in event stream but no response schema given."); + } + for (const [key, value] of Object.entries(firstEvent.value)) { + initialResponseContainer[key] = value; + } + } + return { + async *[Symbol.asyncIterator]() { + if (!firstEvent?.value?.[initialResponseMarker]) { + yield firstEvent.value; + } + while (true) { + const { done, value } = await asyncIterator.next(); + if (done) { + break; + } + yield value; + } + } + }; + } + writeEventBody(unionMember, unionSchema, event) { + const serializer = this.serializer; + let eventType = unionMember; + let explicitPayloadMember = null; + let explicitPayloadContentType; + const isKnownSchema = (() => { + const struct2 = unionSchema.getSchema(); + return struct2[4].includes(unionMember); + })(); + const additionalHeaders = {}; + if (!isKnownSchema) { + const [type, value] = event[unionMember]; + eventType = type; + serializer.write(15, value); + } else { + const eventSchema = unionSchema.getMemberSchema(unionMember); + if (eventSchema.isStructSchema()) { + for (const [memberName, memberSchema] of eventSchema.structIterator()) { + const { eventHeader, eventPayload } = memberSchema.getMergedTraits(); + if (eventPayload) { + explicitPayloadMember = memberName; + } else if (eventHeader) { + const value = event[unionMember][memberName]; + let type = "binary"; + if (memberSchema.isNumericSchema()) { + if ((-2) ** 31 <= value && value <= 2 ** 31 - 1) { + type = "integer"; + } else { + type = "long"; + } + } else if (memberSchema.isTimestampSchema()) { + type = "timestamp"; + } else if (memberSchema.isStringSchema()) { + type = "string"; + } else if (memberSchema.isBooleanSchema()) { + type = "boolean"; + } + if (value != null) { + additionalHeaders[memberName] = { + type, + value + }; + delete event[unionMember][memberName]; + } + } + } + if (explicitPayloadMember !== null) { + const payloadSchema = eventSchema.getMemberSchema(explicitPayloadMember); + if (payloadSchema.isBlobSchema()) { + explicitPayloadContentType = "application/octet-stream"; + } else if (payloadSchema.isStringSchema()) { + explicitPayloadContentType = "text/plain"; + } + serializer.write(payloadSchema, event[unionMember][explicitPayloadMember]); + } else { + serializer.write(eventSchema, event[unionMember]); + } + } else if (eventSchema.isUnitSchema()) { + serializer.write(eventSchema, {}); + } else { + throw new Error("@smithy/core/event-streams - non-struct member not supported in event stream union."); + } + } + const messageSerialization = serializer.flush() ?? new Uint8Array(); + const body = typeof messageSerialization === "string" ? (this.serdeContext?.utf8Decoder ?? import_util_utf8.fromUtf8)(messageSerialization) : messageSerialization; + return { + body, + eventType, + explicitPayloadContentType, + additionalHeaders + }; + } + }; + } +}); + +// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/event-streams/index.js +var event_streams_exports = {}; +__export(event_streams_exports, { + EventStreamSerde: () => EventStreamSerde +}); +var init_event_streams = __esm({ + "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/event-streams/index.js"() { + init_EventStreamSerde(); + } +}); + +// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/protocols/HttpProtocol.js +var import_protocol_http2, HttpProtocol; +var init_HttpProtocol = __esm({ + "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/protocols/HttpProtocol.js"() { + init_schema3(); + import_protocol_http2 = __toESM(require_dist_cjs2()); + init_SerdeContext(); + HttpProtocol = class extends SerdeContext { + options; + compositeErrorRegistry; + constructor(options) { + super(); + this.options = options; + this.compositeErrorRegistry = TypeRegistry.for(options.defaultNamespace); + for (const etr of options.errorTypeRegistries ?? []) { + this.compositeErrorRegistry.copyFrom(etr); + } + } + getRequestType() { + return import_protocol_http2.HttpRequest; + } + getResponseType() { + return import_protocol_http2.HttpResponse; + } + setSerdeContext(serdeContext) { + this.serdeContext = serdeContext; + this.serializer.setSerdeContext(serdeContext); + this.deserializer.setSerdeContext(serdeContext); + if (this.getPayloadCodec()) { + this.getPayloadCodec().setSerdeContext(serdeContext); + } + } + updateServiceEndpoint(request, endpoint) { + if ("url" in endpoint) { + request.protocol = endpoint.url.protocol; + request.hostname = endpoint.url.hostname; + request.port = endpoint.url.port ? Number(endpoint.url.port) : void 0; + request.path = endpoint.url.pathname; + request.fragment = endpoint.url.hash || void 0; + request.username = endpoint.url.username || void 0; + request.password = endpoint.url.password || void 0; + if (!request.query) { + request.query = {}; + } + for (const [k5, v5] of endpoint.url.searchParams.entries()) { + request.query[k5] = v5; + } + if (endpoint.headers) { + for (const [name, values2] of Object.entries(endpoint.headers)) { + request.headers[name] = values2.join(", "); + } + } + return request; + } else { + request.protocol = endpoint.protocol; + request.hostname = endpoint.hostname; + request.port = endpoint.port ? Number(endpoint.port) : void 0; + request.path = endpoint.path; + request.query = { + ...endpoint.query + }; + if (endpoint.headers) { + for (const [name, value] of Object.entries(endpoint.headers)) { + request.headers[name] = value; + } + } + return request; + } + } + setHostPrefix(request, operationSchema, input) { + if (this.serdeContext?.disableHostPrefix) { + return; + } + const inputNs = NormalizedSchema.of(operationSchema.input); + const opTraits = translateTraits(operationSchema.traits ?? {}); + if (opTraits.endpoint) { + let hostPrefix = opTraits.endpoint?.[0]; + if (typeof hostPrefix === "string") { + const hostLabelInputs = [...inputNs.structIterator()].filter(([, member2]) => member2.getMergedTraits().hostLabel); + for (const [name] of hostLabelInputs) { + const replacement = input[name]; + if (typeof replacement !== "string") { + throw new Error(`@smithy/core/schema - ${name} in input must be a string as hostLabel.`); + } + hostPrefix = hostPrefix.replace(`{${name}}`, replacement); + } + request.hostname = hostPrefix + request.hostname; + } + } + } + deserializeMetadata(output) { + return { + httpStatusCode: output.statusCode, + requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"], + extendedRequestId: output.headers["x-amz-id-2"], + cfId: output.headers["x-amz-cf-id"] + }; + } + async serializeEventStream({ eventStream, requestSchema, initialRequest }) { + const eventStreamSerde = await this.loadEventStreamCapability(); + return eventStreamSerde.serializeEventStream({ + eventStream, + requestSchema, + initialRequest + }); + } + async deserializeEventStream({ response, responseSchema, initialResponseContainer }) { + const eventStreamSerde = await this.loadEventStreamCapability(); + return eventStreamSerde.deserializeEventStream({ + response, + responseSchema, + initialResponseContainer + }); + } + async loadEventStreamCapability() { + const { EventStreamSerde: EventStreamSerde2 } = await Promise.resolve().then(() => (init_event_streams(), event_streams_exports)); + return new EventStreamSerde2({ + marshaller: this.getEventStreamMarshaller(), + serializer: this.serializer, + deserializer: this.deserializer, + serdeContext: this.serdeContext, + defaultContentType: this.getDefaultContentType() + }); + } + getDefaultContentType() { + throw new Error(`@smithy/core/protocols - ${this.constructor.name} getDefaultContentType() implementation missing.`); + } + async deserializeHttpMessage(schema2, context, response, arg4, arg5) { + void schema2; + void context; + void response; + void arg4; + void arg5; + return []; + } + getEventStreamMarshaller() { + const context = this.serdeContext; + if (!context.eventStreamMarshaller) { + throw new Error("@smithy/core - HttpProtocol: eventStreamMarshaller missing in serdeContext."); + } + return context.eventStreamMarshaller; + } + }; + } +}); + +// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/protocols/HttpBindingProtocol.js +var import_protocol_http3, import_util_stream2, HttpBindingProtocol; +var init_HttpBindingProtocol = __esm({ + "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/protocols/HttpBindingProtocol.js"() { + init_schema3(); + init_serde(); + import_protocol_http3 = __toESM(require_dist_cjs2()); + import_util_stream2 = __toESM(require_dist_cjs13()); + init_collect_stream_body(); + init_extended_encode_uri_component(); + init_HttpProtocol(); + HttpBindingProtocol = class extends HttpProtocol { + async serializeRequest(operationSchema, _input, context) { + const input = _input && typeof _input === "object" ? _input : {}; + const serializer = this.serializer; + const query = {}; + const headers = {}; + const endpoint = await context.endpoint(); + const ns = NormalizedSchema.of(operationSchema?.input); + const payloadMemberNames = []; + const payloadMemberSchemas = []; + let hasNonHttpBindingMember = false; + let payload2; + const request = new import_protocol_http3.HttpRequest({ + protocol: "", + hostname: "", + port: void 0, + path: "", + fragment: void 0, + query, + headers, + body: void 0 + }); + if (endpoint) { + this.updateServiceEndpoint(request, endpoint); + this.setHostPrefix(request, operationSchema, input); + const opTraits = translateTraits(operationSchema.traits); + if (opTraits.http) { + request.method = opTraits.http[0]; + const [path53, search] = opTraits.http[1].split("?"); + if (request.path == "/") { + request.path = path53; + } else { + request.path += path53; + } + const traitSearchParams = new URLSearchParams(search ?? ""); + Object.assign(query, Object.fromEntries(traitSearchParams)); + } + } + for (const [memberName, memberNs] of ns.structIterator()) { + const memberTraits = memberNs.getMergedTraits() ?? {}; + const inputMemberValue = input[memberName]; + if (inputMemberValue == null && !memberNs.isIdempotencyToken()) { + if (memberTraits.httpLabel) { + if (request.path.includes(`{${memberName}+}`) || request.path.includes(`{${memberName}}`)) { + throw new Error(`No value provided for input HTTP label: ${memberName}.`); + } + } + continue; + } + if (memberTraits.httpPayload) { + const isStreaming = memberNs.isStreaming(); + if (isStreaming) { + const isEventStream = memberNs.isStructSchema(); + if (isEventStream) { + if (input[memberName]) { + payload2 = await this.serializeEventStream({ + eventStream: input[memberName], + requestSchema: ns + }); + } + } else { + payload2 = inputMemberValue; + } + } else { + serializer.write(memberNs, inputMemberValue); + payload2 = serializer.flush(); + } + } else if (memberTraits.httpLabel) { + serializer.write(memberNs, inputMemberValue); + const replacement = serializer.flush(); + if (request.path.includes(`{${memberName}+}`)) { + request.path = request.path.replace(`{${memberName}+}`, replacement.split("/").map(extendedEncodeURIComponent).join("/")); + } else if (request.path.includes(`{${memberName}}`)) { + request.path = request.path.replace(`{${memberName}}`, extendedEncodeURIComponent(replacement)); + } + } else if (memberTraits.httpHeader) { + serializer.write(memberNs, inputMemberValue); + headers[memberTraits.httpHeader.toLowerCase()] = String(serializer.flush()); + } else if (typeof memberTraits.httpPrefixHeaders === "string") { + for (const [key, val] of Object.entries(inputMemberValue)) { + const amalgam = memberTraits.httpPrefixHeaders + key; + serializer.write([memberNs.getValueSchema(), { httpHeader: amalgam }], val); + headers[amalgam.toLowerCase()] = serializer.flush(); + } + } else if (memberTraits.httpQuery || memberTraits.httpQueryParams) { + this.serializeQuery(memberNs, inputMemberValue, query); + } else { + hasNonHttpBindingMember = true; + payloadMemberNames.push(memberName); + payloadMemberSchemas.push(memberNs); + } + } + if (hasNonHttpBindingMember && input) { + const [namespace, name] = (ns.getName(true) ?? "#Unknown").split("#"); + const requiredMembers = ns.getSchema()[6]; + const payloadSchema = [ + 3, + namespace, + name, + ns.getMergedTraits(), + payloadMemberNames, + payloadMemberSchemas, + void 0 + ]; + if (requiredMembers) { + payloadSchema[6] = requiredMembers; + } else { + payloadSchema.pop(); + } + serializer.write(payloadSchema, input); + payload2 = serializer.flush(); + } + request.headers = headers; + request.query = query; + request.body = payload2; + return request; + } + serializeQuery(ns, data2, query) { + const serializer = this.serializer; + const traits = ns.getMergedTraits(); + if (traits.httpQueryParams) { + for (const [key, val] of Object.entries(data2)) { + if (!(key in query)) { + const valueSchema = ns.getValueSchema(); + Object.assign(valueSchema.getMergedTraits(), { + ...traits, + httpQuery: key, + httpQueryParams: void 0 + }); + this.serializeQuery(valueSchema, val, query); + } + } + return; + } + if (ns.isListSchema()) { + const sparse = !!ns.getMergedTraits().sparse; + const buffer2 = []; + for (const item of data2) { + serializer.write([ns.getValueSchema(), traits], item); + const serializable = serializer.flush(); + if (sparse || serializable !== void 0) { + buffer2.push(serializable); + } + } + query[traits.httpQuery] = buffer2; + } else { + serializer.write([ns, traits], data2); + query[traits.httpQuery] = serializer.flush(); + } + } + async deserializeResponse(operationSchema, context, response) { + const deserializer = this.deserializer; + const ns = NormalizedSchema.of(operationSchema.output); + const dataObject = {}; + if (response.statusCode >= 300) { + const bytes = await collectBody(response.body, context); + if (bytes.byteLength > 0) { + Object.assign(dataObject, await deserializer.read(15, bytes)); + } + await this.handleError(operationSchema, context, response, dataObject, this.deserializeMetadata(response)); + throw new Error("@smithy/core/protocols - HTTP Protocol error handler failed to throw."); + } + for (const header in response.headers) { + const value = response.headers[header]; + delete response.headers[header]; + response.headers[header.toLowerCase()] = value; + } + const nonHttpBindingMembers = await this.deserializeHttpMessage(ns, context, response, dataObject); + if (nonHttpBindingMembers.length) { + const bytes = await collectBody(response.body, context); + if (bytes.byteLength > 0) { + const dataFromBody = await deserializer.read(ns, bytes); + for (const member2 of nonHttpBindingMembers) { + if (dataFromBody[member2] != null) { + dataObject[member2] = dataFromBody[member2]; + } + } + } + } else if (nonHttpBindingMembers.discardResponseBody) { + await collectBody(response.body, context); + } + dataObject.$metadata = this.deserializeMetadata(response); + return dataObject; + } + async deserializeHttpMessage(schema2, context, response, arg4, arg5) { + let dataObject; + if (arg4 instanceof Set) { + dataObject = arg5; + } else { + dataObject = arg4; + } + let discardResponseBody = true; + const deserializer = this.deserializer; + const ns = NormalizedSchema.of(schema2); + const nonHttpBindingMembers = []; + for (const [memberName, memberSchema] of ns.structIterator()) { + const memberTraits = memberSchema.getMemberTraits(); + if (memberTraits.httpPayload) { + discardResponseBody = false; + const isStreaming = memberSchema.isStreaming(); + if (isStreaming) { + const isEventStream = memberSchema.isStructSchema(); + if (isEventStream) { + dataObject[memberName] = await this.deserializeEventStream({ + response, + responseSchema: ns + }); + } else { + dataObject[memberName] = (0, import_util_stream2.sdkStreamMixin)(response.body); + } + } else if (response.body) { + const bytes = await collectBody(response.body, context); + if (bytes.byteLength > 0) { + dataObject[memberName] = await deserializer.read(memberSchema, bytes); + } + } + } else if (memberTraits.httpHeader) { + const key = String(memberTraits.httpHeader).toLowerCase(); + const value = response.headers[key]; + if (null != value) { + if (memberSchema.isListSchema()) { + const headerListValueSchema = memberSchema.getValueSchema(); + headerListValueSchema.getMergedTraits().httpHeader = key; + let sections; + if (headerListValueSchema.isTimestampSchema() && headerListValueSchema.getSchema() === 4) { + sections = splitEvery(value, ",", 2); + } else { + sections = splitHeader(value); + } + const list2 = []; + for (const section of sections) { + list2.push(await deserializer.read(headerListValueSchema, section.trim())); + } + dataObject[memberName] = list2; + } else { + dataObject[memberName] = await deserializer.read(memberSchema, value); + } + } + } else if (memberTraits.httpPrefixHeaders !== void 0) { + dataObject[memberName] = {}; + for (const [header, value] of Object.entries(response.headers)) { + if (header.startsWith(memberTraits.httpPrefixHeaders)) { + const valueSchema = memberSchema.getValueSchema(); + valueSchema.getMergedTraits().httpHeader = header; + dataObject[memberName][header.slice(memberTraits.httpPrefixHeaders.length)] = await deserializer.read(valueSchema, value); + } + } + } else if (memberTraits.httpResponseCode) { + dataObject[memberName] = response.statusCode; + } else { + nonHttpBindingMembers.push(memberName); + } + } + nonHttpBindingMembers.discardResponseBody = discardResponseBody; + return nonHttpBindingMembers; + } + }; + } +}); + +// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/protocols/RpcProtocol.js +var import_protocol_http4, RpcProtocol; +var init_RpcProtocol = __esm({ + "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/protocols/RpcProtocol.js"() { + init_schema3(); + import_protocol_http4 = __toESM(require_dist_cjs2()); + init_collect_stream_body(); + init_HttpProtocol(); + RpcProtocol = class extends HttpProtocol { + async serializeRequest(operationSchema, _input, context) { + const serializer = this.serializer; + const query = {}; + const headers = {}; + const endpoint = await context.endpoint(); + const ns = NormalizedSchema.of(operationSchema?.input); + const schema2 = ns.getSchema(); + let payload2; + const input = _input && typeof _input === "object" ? _input : {}; + const request = new import_protocol_http4.HttpRequest({ + protocol: "", + hostname: "", + port: void 0, + path: "/", + fragment: void 0, + query, + headers, + body: void 0 + }); + if (endpoint) { + this.updateServiceEndpoint(request, endpoint); + this.setHostPrefix(request, operationSchema, input); + } + if (input) { + const eventStreamMember = ns.getEventStreamMember(); + if (eventStreamMember) { + if (input[eventStreamMember]) { + const initialRequest = {}; + for (const [memberName, memberSchema] of ns.structIterator()) { + if (memberName !== eventStreamMember && input[memberName]) { + serializer.write(memberSchema, input[memberName]); + initialRequest[memberName] = serializer.flush(); + } + } + payload2 = await this.serializeEventStream({ + eventStream: input[eventStreamMember], + requestSchema: ns, + initialRequest + }); + } + } else { + serializer.write(schema2, input); + payload2 = serializer.flush(); + } + } + request.headers = Object.assign(request.headers, headers); + request.query = query; + request.body = payload2; + request.method = "POST"; + return request; + } + async deserializeResponse(operationSchema, context, response) { + const deserializer = this.deserializer; + const ns = NormalizedSchema.of(operationSchema.output); + const dataObject = {}; + if (response.statusCode >= 300) { + const bytes = await collectBody(response.body, context); + if (bytes.byteLength > 0) { + Object.assign(dataObject, await deserializer.read(15, bytes)); + } + await this.handleError(operationSchema, context, response, dataObject, this.deserializeMetadata(response)); + throw new Error("@smithy/core/protocols - RPC Protocol error handler failed to throw."); + } + for (const header in response.headers) { + const value = response.headers[header]; + delete response.headers[header]; + response.headers[header.toLowerCase()] = value; + } + const eventStreamMember = ns.getEventStreamMember(); + if (eventStreamMember) { + dataObject[eventStreamMember] = await this.deserializeEventStream({ + response, + responseSchema: ns, + initialResponseContainer: dataObject + }); + } else { + const bytes = await collectBody(response.body, context); + if (bytes.byteLength > 0) { + Object.assign(dataObject, await deserializer.read(ns, bytes)); + } + } + dataObject.$metadata = this.deserializeMetadata(response); + return dataObject; + } + }; + } +}); + +// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/protocols/resolve-path.js +var resolvedPath; +var init_resolve_path = __esm({ + "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/protocols/resolve-path.js"() { + init_extended_encode_uri_component(); + resolvedPath = (resolvedPath2, input, memberName, labelValueProvider, uriLabel, isGreedyLabel) => { + if (input != null && input[memberName] !== void 0) { + const labelValue = labelValueProvider(); + if (labelValue == null || labelValue.length <= 0) { + throw new Error("Empty value provided for input HTTP label: " + memberName + "."); + } + resolvedPath2 = resolvedPath2.replace(uriLabel, isGreedyLabel ? labelValue.split("/").map((segment) => extendedEncodeURIComponent(segment)).join("/") : extendedEncodeURIComponent(labelValue)); + } else { + throw new Error("No value provided for input HTTP label: " + memberName + "."); + } + return resolvedPath2; + }; + } +}); + +// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/protocols/requestBuilder.js +function requestBuilder(input, context) { + return new RequestBuilder(input, context); +} +var import_protocol_http5, RequestBuilder; +var init_requestBuilder = __esm({ + "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/protocols/requestBuilder.js"() { + import_protocol_http5 = __toESM(require_dist_cjs2()); + init_resolve_path(); + RequestBuilder = class { + input; + context; + query = {}; + method = ""; + headers = {}; + path = ""; + body = null; + hostname = ""; + resolvePathStack = []; + constructor(input, context) { + this.input = input; + this.context = context; + } + async build() { + const { hostname: hostname3, protocol = "https", port, path: basePath } = await this.context.endpoint(); + this.path = basePath; + for (const resolvePath of this.resolvePathStack) { + resolvePath(this.path); + } + return new import_protocol_http5.HttpRequest({ + protocol, + hostname: this.hostname || hostname3, + port, + method: this.method, + path: this.path, + query: this.query, + body: this.body, + headers: this.headers + }); + } + hn(hostname3) { + this.hostname = hostname3; + return this; + } + bp(uriLabel) { + this.resolvePathStack.push((basePath) => { + this.path = `${basePath?.endsWith("/") ? basePath.slice(0, -1) : basePath || ""}` + uriLabel; + }); + return this; + } + p(memberName, labelValueProvider, uriLabel, isGreedyLabel) { + this.resolvePathStack.push((path53) => { + this.path = resolvedPath(path53, this.input, memberName, labelValueProvider, uriLabel, isGreedyLabel); + }); + return this; + } + h(headers) { + this.headers = headers; + return this; + } + q(query) { + this.query = query; + return this; + } + b(body) { + this.body = body; + return this; + } + m(method) { + this.method = method; + return this; + } + }; + } +}); + +// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/protocols/serde/determineTimestampFormat.js +function determineTimestampFormat(ns, settings) { + if (settings.timestampFormat.useTrait) { + if (ns.isTimestampSchema() && (ns.getSchema() === 5 || ns.getSchema() === 6 || ns.getSchema() === 7)) { + return ns.getSchema(); + } + } + const { httpLabel, httpPrefixHeaders, httpHeader, httpQuery } = ns.getMergedTraits(); + const bindingFormat = settings.httpBindings ? typeof httpPrefixHeaders === "string" || Boolean(httpHeader) ? 6 : Boolean(httpQuery) || Boolean(httpLabel) ? 5 : void 0 : void 0; + return bindingFormat ?? settings.timestampFormat.default; +} +var init_determineTimestampFormat = __esm({ + "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/protocols/serde/determineTimestampFormat.js"() { + } +}); + +// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/protocols/serde/FromStringShapeDeserializer.js +var import_util_base64, import_util_utf82, FromStringShapeDeserializer; +var init_FromStringShapeDeserializer = __esm({ + "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/protocols/serde/FromStringShapeDeserializer.js"() { + init_schema3(); + init_serde(); + import_util_base64 = __toESM(require_dist_cjs7()); + import_util_utf82 = __toESM(require_dist_cjs6()); + init_SerdeContext(); + init_determineTimestampFormat(); + FromStringShapeDeserializer = class extends SerdeContext { + settings; + constructor(settings) { + super(); + this.settings = settings; + } + read(_schema, data2) { + const ns = NormalizedSchema.of(_schema); + if (ns.isListSchema()) { + return splitHeader(data2).map((item) => this.read(ns.getValueSchema(), item)); + } + if (ns.isBlobSchema()) { + return (this.serdeContext?.base64Decoder ?? import_util_base64.fromBase64)(data2); + } + if (ns.isTimestampSchema()) { + const format2 = determineTimestampFormat(ns, this.settings); + switch (format2) { + case 5: + return _parseRfc3339DateTimeWithOffset(data2); + case 6: + return _parseRfc7231DateTime(data2); + case 7: + return _parseEpochTimestamp(data2); + default: + console.warn("Missing timestamp format, parsing value with Date constructor:", data2); + return new Date(data2); + } + } + if (ns.isStringSchema()) { + const mediaType = ns.getMergedTraits().mediaType; + let intermediateValue = data2; + if (mediaType) { + if (ns.getMergedTraits().httpHeader) { + intermediateValue = this.base64ToUtf8(intermediateValue); + } + const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); + if (isJson) { + intermediateValue = LazyJsonString.from(intermediateValue); + } + return intermediateValue; + } + } + if (ns.isNumericSchema()) { + return Number(data2); + } + if (ns.isBigIntegerSchema()) { + return BigInt(data2); + } + if (ns.isBigDecimalSchema()) { + return new NumericValue(data2, "bigDecimal"); + } + if (ns.isBooleanSchema()) { + return String(data2).toLowerCase() === "true"; + } + return data2; + } + base64ToUtf8(base64String) { + return (this.serdeContext?.utf8Encoder ?? import_util_utf82.toUtf8)((this.serdeContext?.base64Decoder ?? import_util_base64.fromBase64)(base64String)); + } + }; + } +}); + +// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/protocols/serde/HttpInterceptingShapeDeserializer.js +var import_util_utf83, HttpInterceptingShapeDeserializer; +var init_HttpInterceptingShapeDeserializer = __esm({ + "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/protocols/serde/HttpInterceptingShapeDeserializer.js"() { + init_schema3(); + import_util_utf83 = __toESM(require_dist_cjs6()); + init_SerdeContext(); + init_FromStringShapeDeserializer(); + HttpInterceptingShapeDeserializer = class extends SerdeContext { + codecDeserializer; + stringDeserializer; + constructor(codecDeserializer, codecSettings) { + super(); + this.codecDeserializer = codecDeserializer; + this.stringDeserializer = new FromStringShapeDeserializer(codecSettings); + } + setSerdeContext(serdeContext) { + this.stringDeserializer.setSerdeContext(serdeContext); + this.codecDeserializer.setSerdeContext(serdeContext); + this.serdeContext = serdeContext; + } + read(schema2, data2) { + const ns = NormalizedSchema.of(schema2); + const traits = ns.getMergedTraits(); + const toString = this.serdeContext?.utf8Encoder ?? import_util_utf83.toUtf8; + if (traits.httpHeader || traits.httpResponseCode) { + return this.stringDeserializer.read(ns, toString(data2)); + } + if (traits.httpPayload) { + if (ns.isBlobSchema()) { + const toBytes = this.serdeContext?.utf8Decoder ?? import_util_utf83.fromUtf8; + if (typeof data2 === "string") { + return toBytes(data2); + } + return data2; + } else if (ns.isStringSchema()) { + if ("byteLength" in data2) { + return toString(data2); + } + return data2; + } + } + return this.codecDeserializer.read(ns, data2); + } + }; + } +}); + +// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/protocols/serde/ToStringShapeSerializer.js +var import_util_base642, ToStringShapeSerializer; +var init_ToStringShapeSerializer = __esm({ + "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/protocols/serde/ToStringShapeSerializer.js"() { + init_schema3(); + init_serde(); + import_util_base642 = __toESM(require_dist_cjs7()); + init_SerdeContext(); + init_determineTimestampFormat(); + ToStringShapeSerializer = class extends SerdeContext { + settings; + stringBuffer = ""; + constructor(settings) { + super(); + this.settings = settings; + } + write(schema2, value) { + const ns = NormalizedSchema.of(schema2); + switch (typeof value) { + case "object": + if (value === null) { + this.stringBuffer = "null"; + return; + } + if (ns.isTimestampSchema()) { + if (!(value instanceof Date)) { + throw new Error(`@smithy/core/protocols - received non-Date value ${value} when schema expected Date in ${ns.getName(true)}`); + } + const format2 = determineTimestampFormat(ns, this.settings); + switch (format2) { + case 5: + this.stringBuffer = value.toISOString().replace(".000Z", "Z"); + break; + case 6: + this.stringBuffer = dateToUtcString(value); + break; + case 7: + this.stringBuffer = String(value.getTime() / 1e3); + break; + default: + console.warn("Missing timestamp format, using epoch seconds", value); + this.stringBuffer = String(value.getTime() / 1e3); + } + return; + } + if (ns.isBlobSchema() && "byteLength" in value) { + this.stringBuffer = (this.serdeContext?.base64Encoder ?? import_util_base642.toBase64)(value); + return; + } + if (ns.isListSchema() && Array.isArray(value)) { + let buffer2 = ""; + for (const item of value) { + this.write([ns.getValueSchema(), ns.getMergedTraits()], item); + const headerItem = this.flush(); + const serialized = ns.getValueSchema().isTimestampSchema() ? headerItem : quoteHeader(headerItem); + if (buffer2 !== "") { + buffer2 += ", "; + } + buffer2 += serialized; + } + this.stringBuffer = buffer2; + return; + } + this.stringBuffer = JSON.stringify(value, null, 2); + break; + case "string": + const mediaType = ns.getMergedTraits().mediaType; + let intermediateValue = value; + if (mediaType) { + const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); + if (isJson) { + intermediateValue = LazyJsonString.from(intermediateValue); + } + if (ns.getMergedTraits().httpHeader) { + this.stringBuffer = (this.serdeContext?.base64Encoder ?? import_util_base642.toBase64)(intermediateValue.toString()); + return; + } + } + this.stringBuffer = value; + break; + default: + if (ns.isIdempotencyToken()) { + this.stringBuffer = (0, import_uuid2.v4)(); + } else { + this.stringBuffer = String(value); + } + } + } + flush() { + const buffer2 = this.stringBuffer; + this.stringBuffer = ""; + return buffer2; + } + }; + } +}); + +// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/protocols/serde/HttpInterceptingShapeSerializer.js +var HttpInterceptingShapeSerializer; +var init_HttpInterceptingShapeSerializer = __esm({ + "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/protocols/serde/HttpInterceptingShapeSerializer.js"() { + init_schema3(); + init_ToStringShapeSerializer(); + HttpInterceptingShapeSerializer = class { + codecSerializer; + stringSerializer; + buffer; + constructor(codecSerializer, codecSettings, stringSerializer = new ToStringShapeSerializer(codecSettings)) { + this.codecSerializer = codecSerializer; + this.stringSerializer = stringSerializer; + } + setSerdeContext(serdeContext) { + this.codecSerializer.setSerdeContext(serdeContext); + this.stringSerializer.setSerdeContext(serdeContext); + } + write(schema2, value) { + const ns = NormalizedSchema.of(schema2); + const traits = ns.getMergedTraits(); + if (traits.httpHeader || traits.httpLabel || traits.httpQuery) { + this.stringSerializer.write(ns, value); + this.buffer = this.stringSerializer.flush(); + return; + } + return this.codecSerializer.write(ns, value); + } + flush() { + if (this.buffer !== void 0) { + const buffer2 = this.buffer; + this.buffer = void 0; + return buffer2; + } + return this.codecSerializer.flush(); + } + }; + } +}); + +// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/protocols/index.js +var protocols_exports = {}; +__export(protocols_exports, { + FromStringShapeDeserializer: () => FromStringShapeDeserializer, + HttpBindingProtocol: () => HttpBindingProtocol, + HttpInterceptingShapeDeserializer: () => HttpInterceptingShapeDeserializer, + HttpInterceptingShapeSerializer: () => HttpInterceptingShapeSerializer, + HttpProtocol: () => HttpProtocol, + RequestBuilder: () => RequestBuilder, + RpcProtocol: () => RpcProtocol, + SerdeContext: () => SerdeContext, + ToStringShapeSerializer: () => ToStringShapeSerializer, + collectBody: () => collectBody, + determineTimestampFormat: () => determineTimestampFormat, + extendedEncodeURIComponent: () => extendedEncodeURIComponent, + requestBuilder: () => requestBuilder, + resolvedPath: () => resolvedPath +}); +var init_protocols = __esm({ + "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/protocols/index.js"() { + init_collect_stream_body(); + init_extended_encode_uri_component(); + init_HttpBindingProtocol(); + init_HttpProtocol(); + init_RpcProtocol(); + init_requestBuilder(); + init_resolve_path(); + init_FromStringShapeDeserializer(); + init_HttpInterceptingShapeDeserializer(); + init_HttpInterceptingShapeSerializer(); + init_ToStringShapeSerializer(); + init_determineTimestampFormat(); + init_SerdeContext(); + } +}); + +// node_modules/.pnpm/@smithy+smithy-client@4.12.9/node_modules/@smithy/smithy-client/dist-cjs/index.js +var require_dist_cjs27 = __commonJS({ + "node_modules/.pnpm/@smithy+smithy-client@4.12.9/node_modules/@smithy/smithy-client/dist-cjs/index.js"(exports) { + "use strict"; + var middlewareStack = require_dist_cjs23(); + var types2 = require_dist_cjs(); + var schema2 = (init_schema3(), __toCommonJS(schema_exports2)); + var serde = (init_serde(), __toCommonJS(serde_exports)); + var protocols = (init_protocols(), __toCommonJS(protocols_exports)); + var Client = class { + config; + middlewareStack = middlewareStack.constructStack(); + initConfig; + handlers; + constructor(config3) { + this.config = config3; + const { protocol, protocolSettings } = config3; + if (protocolSettings) { + if (typeof protocol === "function") { + config3.protocol = new protocol(protocolSettings); + } + } + } + send(command, optionsOrCb, cb) { + const options = typeof optionsOrCb !== "function" ? optionsOrCb : void 0; + const callback = typeof optionsOrCb === "function" ? optionsOrCb : cb; + const useHandlerCache = options === void 0 && this.config.cacheMiddleware === true; + let handler; + if (useHandlerCache) { + if (!this.handlers) { + this.handlers = /* @__PURE__ */ new WeakMap(); + } + const handlers = this.handlers; + if (handlers.has(command.constructor)) { + handler = handlers.get(command.constructor); + } else { + handler = command.resolveMiddleware(this.middlewareStack, this.config, options); + handlers.set(command.constructor, handler); + } + } else { + delete this.handlers; + handler = command.resolveMiddleware(this.middlewareStack, this.config, options); + } + if (callback) { + handler(command).then((result) => callback(null, result.output), (err) => callback(err)).catch(() => { + }); + } else { + return handler(command).then((result) => result.output); + } + } + destroy() { + this.config?.requestHandler?.destroy?.(); + delete this.handlers; + } + }; + var SENSITIVE_STRING$1 = "***SensitiveInformation***"; + function schemaLogFilter(schema$1, data2) { + if (data2 == null) { + return data2; + } + const ns = schema2.NormalizedSchema.of(schema$1); + if (ns.getMergedTraits().sensitive) { + return SENSITIVE_STRING$1; + } + if (ns.isListSchema()) { + const isSensitive = !!ns.getValueSchema().getMergedTraits().sensitive; + if (isSensitive) { + return SENSITIVE_STRING$1; + } + } else if (ns.isMapSchema()) { + const isSensitive = !!ns.getKeySchema().getMergedTraits().sensitive || !!ns.getValueSchema().getMergedTraits().sensitive; + if (isSensitive) { + return SENSITIVE_STRING$1; + } + } else if (ns.isStructSchema() && typeof data2 === "object") { + const object2 = data2; + const newObject = {}; + for (const [member2, memberNs] of ns.structIterator()) { + if (object2[member2] != null) { + newObject[member2] = schemaLogFilter(memberNs, object2[member2]); + } + } + return newObject; + } + return data2; + } + var Command2 = class { + middlewareStack = middlewareStack.constructStack(); + schema; + static classBuilder() { + return new ClassBuilder(); + } + resolveMiddlewareWithContext(clientStack, configuration, options, { middlewareFn, clientName, commandName, inputFilterSensitiveLog, outputFilterSensitiveLog, smithyContext, additionalContext, CommandCtor }) { + for (const mw of middlewareFn.bind(this)(CommandCtor, clientStack, configuration, options)) { + this.middlewareStack.use(mw); + } + const stack = clientStack.concat(this.middlewareStack); + const { logger: logger4 } = configuration; + const handlerExecutionContext = { + logger: logger4, + clientName, + commandName, + inputFilterSensitiveLog, + outputFilterSensitiveLog, + [types2.SMITHY_CONTEXT_KEY]: { + commandInstance: this, + ...smithyContext + }, + ...additionalContext + }; + const { requestHandler } = configuration; + return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); + } + }; + var ClassBuilder = class { + _init = () => { + }; + _ep = {}; + _middlewareFn = () => []; + _commandName = ""; + _clientName = ""; + _additionalContext = {}; + _smithyContext = {}; + _inputFilterSensitiveLog = void 0; + _outputFilterSensitiveLog = void 0; + _serializer = null; + _deserializer = null; + _operationSchema; + init(cb) { + this._init = cb; + } + ep(endpointParameterInstructions) { + this._ep = endpointParameterInstructions; + return this; + } + m(middlewareSupplier) { + this._middlewareFn = middlewareSupplier; + return this; + } + s(service, operation2, smithyContext = {}) { + this._smithyContext = { + service, + operation: operation2, + ...smithyContext + }; + return this; + } + c(additionalContext = {}) { + this._additionalContext = additionalContext; + return this; + } + n(clientName, commandName) { + this._clientName = clientName; + this._commandName = commandName; + return this; + } + f(inputFilter = (_) => _, outputFilter = (_) => _) { + this._inputFilterSensitiveLog = inputFilter; + this._outputFilterSensitiveLog = outputFilter; + return this; + } + ser(serializer) { + this._serializer = serializer; + return this; + } + de(deserializer) { + this._deserializer = deserializer; + return this; + } + sc(operation2) { + this._operationSchema = operation2; + this._smithyContext.operationSchema = operation2; + return this; + } + build() { + const closure = this; + let CommandRef; + return CommandRef = class extends Command2 { + input; + static getEndpointParameterInstructions() { + return closure._ep; + } + constructor(...[input]) { + super(); + this.input = input ?? {}; + closure._init(this); + this.schema = closure._operationSchema; + } + resolveMiddleware(stack, configuration, options) { + const op2 = closure._operationSchema; + const input = op2?.[4] ?? op2?.input; + const output = op2?.[5] ?? op2?.output; + return this.resolveMiddlewareWithContext(stack, configuration, options, { + CommandCtor: CommandRef, + middlewareFn: closure._middlewareFn, + clientName: closure._clientName, + commandName: closure._commandName, + inputFilterSensitiveLog: closure._inputFilterSensitiveLog ?? (op2 ? schemaLogFilter.bind(null, input) : (_) => _), + outputFilterSensitiveLog: closure._outputFilterSensitiveLog ?? (op2 ? schemaLogFilter.bind(null, output) : (_) => _), + smithyContext: closure._smithyContext, + additionalContext: closure._additionalContext + }); + } + serialize = closure._serializer; + deserialize = closure._deserializer; + }; + } + }; + var SENSITIVE_STRING = "***SensitiveInformation***"; + var createAggregatedClient5 = (commands5, Client2, options) => { + for (const [command, CommandCtor] of Object.entries(commands5)) { + const methodImpl = async function(args, optionsOrCb, cb) { + const command2 = new CommandCtor(args); + if (typeof optionsOrCb === "function") { + this.send(command2, optionsOrCb); + } else if (typeof cb === "function") { + if (typeof optionsOrCb !== "object") + throw new Error(`Expected http options but got ${typeof optionsOrCb}`); + this.send(command2, optionsOrCb || {}, cb); + } else { + return this.send(command2, optionsOrCb); + } + }; + const methodName = (command[0].toLowerCase() + command.slice(1)).replace(/Command$/, ""); + Client2.prototype[methodName] = methodImpl; + } + const { paginators = {}, waiters = {} } = options ?? {}; + for (const [paginatorName, paginatorFn] of Object.entries(paginators)) { + if (Client2.prototype[paginatorName] === void 0) { + Client2.prototype[paginatorName] = function(commandInput = {}, paginationConfiguration, ...rest) { + return paginatorFn({ + ...paginationConfiguration, + client: this + }, commandInput, ...rest); + }; + } + } + for (const [waiterName, waiterFn] of Object.entries(waiters)) { + if (Client2.prototype[waiterName] === void 0) { + Client2.prototype[waiterName] = async function(commandInput = {}, waiterConfiguration, ...rest) { + let config3 = waiterConfiguration; + if (typeof waiterConfiguration === "number") { + config3 = { + maxWaitTime: waiterConfiguration + }; + } + return waiterFn({ + ...config3, + client: this + }, commandInput, ...rest); + }; + } + } + }; + var ServiceException = class _ServiceException extends Error { + $fault; + $response; + $retryable; + $metadata; + constructor(options) { + super(options.message); + Object.setPrototypeOf(this, Object.getPrototypeOf(this).constructor.prototype); + this.name = options.name; + this.$fault = options.$fault; + this.$metadata = options.$metadata; + } + static isInstance(value) { + if (!value) + return false; + const candidate = value; + return _ServiceException.prototype.isPrototypeOf(candidate) || Boolean(candidate.$fault) && Boolean(candidate.$metadata) && (candidate.$fault === "client" || candidate.$fault === "server"); + } + static [Symbol.hasInstance](instance) { + if (!instance) + return false; + const candidate = instance; + if (this === _ServiceException) { + return _ServiceException.isInstance(instance); + } + if (_ServiceException.isInstance(instance)) { + if (candidate.name && this.name) { + return this.prototype.isPrototypeOf(instance) || candidate.name === this.name; + } + return this.prototype.isPrototypeOf(instance); + } + return false; + } + }; + var decorateServiceException2 = (exception, additions = {}) => { + Object.entries(additions).filter(([, v5]) => v5 !== void 0).forEach(([k5, v5]) => { + if (exception[k5] == void 0 || exception[k5] === "") { + exception[k5] = v5; + } + }); + const message2 = exception.message || exception.Message || "UnknownError"; + exception.message = message2; + delete exception.Message; + return exception; + }; + var throwDefaultError = ({ output, parsedBody, exceptionCtor, errorCode }) => { + const $metadata = deserializeMetadata(output); + const statusCode = $metadata.httpStatusCode ? $metadata.httpStatusCode + "" : void 0; + const response = new exceptionCtor({ + name: parsedBody?.code || parsedBody?.Code || errorCode || statusCode || "UnknownError", + $fault: "client", + $metadata + }); + throw decorateServiceException2(response, parsedBody); + }; + var withBaseException = (ExceptionCtor) => { + return ({ output, parsedBody, errorCode }) => { + throwDefaultError({ output, parsedBody, exceptionCtor: ExceptionCtor, errorCode }); + }; + }; + var deserializeMetadata = (output) => ({ + httpStatusCode: output.statusCode, + requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"], + extendedRequestId: output.headers["x-amz-id-2"], + cfId: output.headers["x-amz-cf-id"] + }); + var loadConfigsForDefaultMode5 = (mode) => { + switch (mode) { + case "standard": + return { + retryMode: "standard", + connectionTimeout: 3100 + }; + case "in-region": + return { + retryMode: "standard", + connectionTimeout: 1100 + }; + case "cross-region": + return { + retryMode: "standard", + connectionTimeout: 3100 + }; + case "mobile": + return { + retryMode: "standard", + connectionTimeout: 3e4 + }; + default: + return {}; + } + }; + var warningEmitted = false; + var emitWarningIfUnsupportedVersion6 = (version3) => { + if (version3 && !warningEmitted && parseInt(version3.substring(1, version3.indexOf("."))) < 16) { + warningEmitted = true; + } + }; + var knownAlgorithms = Object.values(types2.AlgorithmId); + var getChecksumConfiguration = (runtimeConfig) => { + const checksumAlgorithms = []; + for (const id in types2.AlgorithmId) { + const algorithmId = types2.AlgorithmId[id]; + if (runtimeConfig[algorithmId] === void 0) { + continue; + } + checksumAlgorithms.push({ + algorithmId: () => algorithmId, + checksumConstructor: () => runtimeConfig[algorithmId] + }); + } + for (const [id, ChecksumCtor] of Object.entries(runtimeConfig.checksumAlgorithms ?? {})) { + checksumAlgorithms.push({ + algorithmId: () => id, + checksumConstructor: () => ChecksumCtor + }); + } + return { + addChecksumAlgorithm(algo) { + runtimeConfig.checksumAlgorithms = runtimeConfig.checksumAlgorithms ?? {}; + const id = algo.algorithmId(); + const ctor = algo.checksumConstructor(); + if (knownAlgorithms.includes(id)) { + runtimeConfig.checksumAlgorithms[id.toUpperCase()] = ctor; + } else { + runtimeConfig.checksumAlgorithms[id] = ctor; + } + checksumAlgorithms.push(algo); + }, + checksumAlgorithms() { + return checksumAlgorithms; + } + }; + }; + var resolveChecksumRuntimeConfig = (clientConfig) => { + const runtimeConfig = {}; + clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { + const id = checksumAlgorithm.algorithmId(); + if (knownAlgorithms.includes(id)) { + runtimeConfig[id] = checksumAlgorithm.checksumConstructor(); + } + }); + return runtimeConfig; + }; + var getRetryConfiguration = (runtimeConfig) => { + return { + setRetryStrategy(retryStrategy) { + runtimeConfig.retryStrategy = retryStrategy; + }, + retryStrategy() { + return runtimeConfig.retryStrategy; + } + }; + }; + var resolveRetryRuntimeConfig = (retryStrategyConfiguration) => { + const runtimeConfig = {}; + runtimeConfig.retryStrategy = retryStrategyConfiguration.retryStrategy(); + return runtimeConfig; + }; + var getDefaultExtensionConfiguration5 = (runtimeConfig) => { + return Object.assign(getChecksumConfiguration(runtimeConfig), getRetryConfiguration(runtimeConfig)); + }; + var getDefaultClientConfiguration = getDefaultExtensionConfiguration5; + var resolveDefaultRuntimeConfig5 = (config3) => { + return Object.assign(resolveChecksumRuntimeConfig(config3), resolveRetryRuntimeConfig(config3)); + }; + var getArrayIfSingleItem = (mayBeArray) => Array.isArray(mayBeArray) ? mayBeArray : [mayBeArray]; + var getValueFromTextNode3 = (obj) => { + const textNodeName = "#text"; + for (const key in obj) { + if (obj.hasOwnProperty(key) && obj[key][textNodeName] !== void 0) { + obj[key] = obj[key][textNodeName]; + } else if (typeof obj[key] === "object" && obj[key] !== null) { + obj[key] = getValueFromTextNode3(obj[key]); + } + } + return obj; + }; + var isSerializableHeaderValue = (value) => { + return value != null; + }; + var NoOpLogger5 = class { + trace() { + } + debug() { + } + info() { + } + warn() { + } + error() { + } + }; + function map4(arg0, arg1, arg2) { + let target; + let filter; + let instructions; + if (typeof arg1 === "undefined" && typeof arg2 === "undefined") { + target = {}; + instructions = arg0; + } else { + target = arg0; + if (typeof arg1 === "function") { + filter = arg1; + instructions = arg2; + return mapWithFilter(target, filter, instructions); + } else { + instructions = arg1; + } + } + for (const key of Object.keys(instructions)) { + if (!Array.isArray(instructions[key])) { + target[key] = instructions[key]; + continue; + } + applyInstruction(target, null, instructions, key); + } + return target; + } + var convertMap = (target) => { + const output = {}; + for (const [k5, v5] of Object.entries(target || {})) { + output[k5] = [, v5]; + } + return output; + }; + var take = (source, instructions) => { + const out = {}; + for (const key in instructions) { + applyInstruction(out, source, instructions, key); + } + return out; + }; + var mapWithFilter = (target, filter, instructions) => { + return map4(target, Object.entries(instructions).reduce((_instructions, [key, value]) => { + if (Array.isArray(value)) { + _instructions[key] = value; + } else { + if (typeof value === "function") { + _instructions[key] = [filter, value()]; + } else { + _instructions[key] = [filter, value]; + } + } + return _instructions; + }, {})); + }; + var applyInstruction = (target, source, instructions, targetKey) => { + if (source !== null) { + let instruction = instructions[targetKey]; + if (typeof instruction === "function") { + instruction = [, instruction]; + } + const [filter2 = nonNullish, valueFn = pass, sourceKey = targetKey] = instruction; + if (typeof filter2 === "function" && filter2(source[sourceKey]) || typeof filter2 !== "function" && !!filter2) { + target[targetKey] = valueFn(source[sourceKey]); + } + return; + } + let [filter, value] = instructions[targetKey]; + if (typeof value === "function") { + let _value; + const defaultFilterPassed = filter === void 0 && (_value = value()) != null; + const customFilterPassed = typeof filter === "function" && !!filter(void 0) || typeof filter !== "function" && !!filter; + if (defaultFilterPassed) { + target[targetKey] = _value; + } else if (customFilterPassed) { + target[targetKey] = value(); + } + } else { + const defaultFilterPassed = filter === void 0 && value != null; + const customFilterPassed = typeof filter === "function" && !!filter(value) || typeof filter !== "function" && !!filter; + if (defaultFilterPassed || customFilterPassed) { + target[targetKey] = value; + } + } + }; + var nonNullish = (_) => _ != null; + var pass = (_) => _; + var serializeFloat = (value) => { + if (value !== value) { + return "NaN"; + } + switch (value) { + case Infinity: + return "Infinity"; + case -Infinity: + return "-Infinity"; + default: + return value; + } + }; + var serializeDateTime = (date7) => date7.toISOString().replace(".000Z", "Z"); + var _json = (obj) => { + if (obj == null) { + return {}; + } + if (Array.isArray(obj)) { + return obj.filter((_) => _ != null).map(_json); + } + if (typeof obj === "object") { + const target = {}; + for (const key of Object.keys(obj)) { + if (obj[key] == null) { + continue; + } + target[key] = _json(obj[key]); + } + return target; + } + return obj; + }; + exports.collectBody = protocols.collectBody; + exports.extendedEncodeURIComponent = protocols.extendedEncodeURIComponent; + exports.resolvedPath = protocols.resolvedPath; + exports.Client = Client; + exports.Command = Command2; + exports.NoOpLogger = NoOpLogger5; + exports.SENSITIVE_STRING = SENSITIVE_STRING; + exports.ServiceException = ServiceException; + exports._json = _json; + exports.convertMap = convertMap; + exports.createAggregatedClient = createAggregatedClient5; + exports.decorateServiceException = decorateServiceException2; + exports.emitWarningIfUnsupportedVersion = emitWarningIfUnsupportedVersion6; + exports.getArrayIfSingleItem = getArrayIfSingleItem; + exports.getDefaultClientConfiguration = getDefaultClientConfiguration; + exports.getDefaultExtensionConfiguration = getDefaultExtensionConfiguration5; + exports.getValueFromTextNode = getValueFromTextNode3; + exports.isSerializableHeaderValue = isSerializableHeaderValue; + exports.loadConfigsForDefaultMode = loadConfigsForDefaultMode5; + exports.map = map4; + exports.resolveDefaultRuntimeConfig = resolveDefaultRuntimeConfig5; + exports.serializeDateTime = serializeDateTime; + exports.serializeFloat = serializeFloat; + exports.take = take; + exports.throwDefaultError = throwDefaultError; + exports.withBaseException = withBaseException; + Object.prototype.hasOwnProperty.call(serde, "__proto__") && !Object.prototype.hasOwnProperty.call(exports, "__proto__") && Object.defineProperty(exports, "__proto__", { + enumerable: true, + value: serde["__proto__"] + }); + Object.keys(serde).forEach(function(k5) { + if (k5 !== "default" && !Object.prototype.hasOwnProperty.call(exports, k5)) exports[k5] = serde[k5]; + }); + } +}); + +// node_modules/.pnpm/@aws-sdk+util-arn-parser@3.972.3/node_modules/@aws-sdk/util-arn-parser/dist-cjs/index.js +var require_dist_cjs28 = __commonJS({ + "node_modules/.pnpm/@aws-sdk+util-arn-parser@3.972.3/node_modules/@aws-sdk/util-arn-parser/dist-cjs/index.js"(exports) { + "use strict"; + var validate2 = (str) => typeof str === "string" && str.indexOf("arn:") === 0 && str.split(":").length >= 6; + var parse5 = (arn) => { + const segments = arn.split(":"); + if (segments.length < 6 || segments[0] !== "arn") + throw new Error("Malformed ARN"); + const [, partition, service, region, accountId, ...resource] = segments; + return { + partition, + service, + region, + accountId, + resource: resource.join(":") + }; + }; + var build = (arnObject) => { + const { partition = "aws", service, region, accountId, resource } = arnObject; + if ([service, region, accountId, resource].some((segment) => typeof segment !== "string")) { + throw new Error("Input ARN object is invalid"); + } + return `arn:${partition}:${service}:${region}:${accountId}:${resource}`; + }; + exports.build = build; + exports.parse = parse5; + exports.validate = validate2; + } +}); + +// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/cbor/cbor-types.js +function alloc(size2) { + return typeof Buffer !== "undefined" ? Buffer.alloc(size2) : new Uint8Array(size2); +} +function tag(data2) { + data2[tagSymbol] = true; + return data2; +} +var majorUint64, majorNegativeInt64, majorUnstructuredByteString, majorUtf8String, majorList, majorMap, majorTag, majorSpecial, specialFalse, specialTrue, specialNull, specialUndefined, extendedOneByte, extendedFloat16, extendedFloat32, extendedFloat64, minorIndefinite, tagSymbol; +var init_cbor_types = __esm({ + "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/cbor/cbor-types.js"() { + majorUint64 = 0; + majorNegativeInt64 = 1; + majorUnstructuredByteString = 2; + majorUtf8String = 3; + majorList = 4; + majorMap = 5; + majorTag = 6; + majorSpecial = 7; + specialFalse = 20; + specialTrue = 21; + specialNull = 22; + specialUndefined = 23; + extendedOneByte = 24; + extendedFloat16 = 25; + extendedFloat32 = 26; + extendedFloat64 = 27; + minorIndefinite = 31; + tagSymbol = /* @__PURE__ */ Symbol("@smithy/core/cbor::tagSymbol"); + } +}); + +// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/cbor/cbor-decode.js +function setPayload(bytes) { + payload = bytes; + dataView = new DataView(payload.buffer, payload.byteOffset, payload.byteLength); +} +function decode(at, to) { + if (at >= to) { + throw new Error("unexpected end of (decode) payload."); + } + const major = (payload[at] & 224) >> 5; + const minor = payload[at] & 31; + switch (major) { + case majorUint64: + case majorNegativeInt64: + case majorTag: + let unsignedInt; + let offset; + if (minor < 24) { + unsignedInt = minor; + offset = 1; + } else { + switch (minor) { + case extendedOneByte: + case extendedFloat16: + case extendedFloat32: + case extendedFloat64: + const countLength = minorValueToArgumentLength[minor]; + const countOffset = countLength + 1; + offset = countOffset; + if (to - at < countOffset) { + throw new Error(`countLength ${countLength} greater than remaining buf len.`); + } + const countIndex = at + 1; + if (countLength === 1) { + unsignedInt = payload[countIndex]; + } else if (countLength === 2) { + unsignedInt = dataView.getUint16(countIndex); + } else if (countLength === 4) { + unsignedInt = dataView.getUint32(countIndex); + } else { + unsignedInt = dataView.getBigUint64(countIndex); + } + break; + default: + throw new Error(`unexpected minor value ${minor}.`); + } + } + if (major === majorUint64) { + _offset = offset; + return castBigInt(unsignedInt); + } else if (major === majorNegativeInt64) { + let negativeInt; + if (typeof unsignedInt === "bigint") { + negativeInt = BigInt(-1) - unsignedInt; + } else { + negativeInt = -1 - unsignedInt; + } + _offset = offset; + return castBigInt(negativeInt); + } else { + if (minor === 2 || minor === 3) { + const length = decodeCount(at + offset, to); + let b6 = BigInt(0); + const start = at + offset + _offset; + for (let i5 = start; i5 < start + length; ++i5) { + b6 = b6 << BigInt(8) | BigInt(payload[i5]); + } + _offset = offset + _offset + length; + return minor === 3 ? -b6 - BigInt(1) : b6; + } else if (minor === 4) { + const decimalFraction = decode(at + offset, to); + const [exponent, mantissa] = decimalFraction; + const normalizer = mantissa < 0 ? -1 : 1; + const mantissaStr = "0".repeat(Math.abs(exponent) + 1) + String(BigInt(normalizer) * BigInt(mantissa)); + let numericString; + const sign2 = mantissa < 0 ? "-" : ""; + numericString = exponent === 0 ? mantissaStr : mantissaStr.slice(0, mantissaStr.length + exponent) + "." + mantissaStr.slice(exponent); + numericString = numericString.replace(/^0+/g, ""); + if (numericString === "") { + numericString = "0"; + } + if (numericString[0] === ".") { + numericString = "0" + numericString; + } + numericString = sign2 + numericString; + _offset = offset + _offset; + return nv(numericString); + } else { + const value = decode(at + offset, to); + const valueOffset = _offset; + _offset = offset + valueOffset; + return tag({ tag: castBigInt(unsignedInt), value }); + } + } + case majorUtf8String: + case majorMap: + case majorList: + case majorUnstructuredByteString: + if (minor === minorIndefinite) { + switch (major) { + case majorUtf8String: + return decodeUtf8StringIndefinite(at, to); + case majorMap: + return decodeMapIndefinite(at, to); + case majorList: + return decodeListIndefinite(at, to); + case majorUnstructuredByteString: + return decodeUnstructuredByteStringIndefinite(at, to); + } + } else { + switch (major) { + case majorUtf8String: + return decodeUtf8String(at, to); + case majorMap: + return decodeMap(at, to); + case majorList: + return decodeList(at, to); + case majorUnstructuredByteString: + return decodeUnstructuredByteString(at, to); + } + } + default: + return decodeSpecial(at, to); + } +} +function bytesToUtf8(bytes, at, to) { + if (USE_BUFFER && bytes.constructor?.name === "Buffer") { + return bytes.toString("utf-8", at, to); + } + if (textDecoder) { + return textDecoder.decode(bytes.subarray(at, to)); + } + return (0, import_util_utf84.toUtf8)(bytes.subarray(at, to)); +} +function demote(bigInteger) { + const num = Number(bigInteger); + if (num < Number.MIN_SAFE_INTEGER || Number.MAX_SAFE_INTEGER < num) { + console.warn(new Error(`@smithy/core/cbor - truncating BigInt(${bigInteger}) to ${num} with loss of precision.`)); + } + return num; +} +function bytesToFloat16(a5, b6) { + const sign2 = a5 >> 7; + const exponent = (a5 & 124) >> 2; + const fraction = (a5 & 3) << 8 | b6; + const scalar = sign2 === 0 ? 1 : -1; + let exponentComponent; + let summation; + if (exponent === 0) { + if (fraction === 0) { + return 0; + } else { + exponentComponent = Math.pow(2, 1 - 15); + summation = 0; + } + } else if (exponent === 31) { + if (fraction === 0) { + return scalar * Infinity; + } else { + return NaN; + } + } else { + exponentComponent = Math.pow(2, exponent - 15); + summation = 1; + } + summation += fraction / 1024; + return scalar * (exponentComponent * summation); +} +function decodeCount(at, to) { + const minor = payload[at] & 31; + if (minor < 24) { + _offset = 1; + return minor; + } + if (minor === extendedOneByte || minor === extendedFloat16 || minor === extendedFloat32 || minor === extendedFloat64) { + const countLength = minorValueToArgumentLength[minor]; + _offset = countLength + 1; + if (to - at < _offset) { + throw new Error(`countLength ${countLength} greater than remaining buf len.`); + } + const countIndex = at + 1; + if (countLength === 1) { + return payload[countIndex]; + } else if (countLength === 2) { + return dataView.getUint16(countIndex); + } else if (countLength === 4) { + return dataView.getUint32(countIndex); + } + return demote(dataView.getBigUint64(countIndex)); + } + throw new Error(`unexpected minor value ${minor}.`); +} +function decodeUtf8String(at, to) { + const length = decodeCount(at, to); + const offset = _offset; + at += offset; + if (to - at < length) { + throw new Error(`string len ${length} greater than remaining buf len.`); + } + const value = bytesToUtf8(payload, at, at + length); + _offset = offset + length; + return value; +} +function decodeUtf8StringIndefinite(at, to) { + at += 1; + const vector2 = []; + for (const base = at; at < to; ) { + if (payload[at] === 255) { + const data2 = alloc(vector2.length); + data2.set(vector2, 0); + _offset = at - base + 2; + return bytesToUtf8(data2, 0, data2.length); + } + const major = (payload[at] & 224) >> 5; + const minor = payload[at] & 31; + if (major !== majorUtf8String) { + throw new Error(`unexpected major type ${major} in indefinite string.`); + } + if (minor === minorIndefinite) { + throw new Error("nested indefinite string."); + } + const bytes = decodeUnstructuredByteString(at, to); + const length = _offset; + at += length; + for (let i5 = 0; i5 < bytes.length; ++i5) { + vector2.push(bytes[i5]); + } + } + throw new Error("expected break marker."); +} +function decodeUnstructuredByteString(at, to) { + const length = decodeCount(at, to); + const offset = _offset; + at += offset; + if (to - at < length) { + throw new Error(`unstructured byte string len ${length} greater than remaining buf len.`); + } + const value = payload.subarray(at, at + length); + _offset = offset + length; + return value; +} +function decodeUnstructuredByteStringIndefinite(at, to) { + at += 1; + const vector2 = []; + for (const base = at; at < to; ) { + if (payload[at] === 255) { + const data2 = alloc(vector2.length); + data2.set(vector2, 0); + _offset = at - base + 2; + return data2; + } + const major = (payload[at] & 224) >> 5; + const minor = payload[at] & 31; + if (major !== majorUnstructuredByteString) { + throw new Error(`unexpected major type ${major} in indefinite string.`); + } + if (minor === minorIndefinite) { + throw new Error("nested indefinite string."); + } + const bytes = decodeUnstructuredByteString(at, to); + const length = _offset; + at += length; + for (let i5 = 0; i5 < bytes.length; ++i5) { + vector2.push(bytes[i5]); + } + } + throw new Error("expected break marker."); +} +function decodeList(at, to) { + const listDataLength = decodeCount(at, to); + const offset = _offset; + at += offset; + const base = at; + const list2 = Array(listDataLength); + for (let i5 = 0; i5 < listDataLength; ++i5) { + const item = decode(at, to); + const itemOffset = _offset; + list2[i5] = item; + at += itemOffset; + } + _offset = offset + (at - base); + return list2; +} +function decodeListIndefinite(at, to) { + at += 1; + const list2 = []; + for (const base = at; at < to; ) { + if (payload[at] === 255) { + _offset = at - base + 2; + return list2; + } + const item = decode(at, to); + const n5 = _offset; + at += n5; + list2.push(item); + } + throw new Error("expected break marker."); +} +function decodeMap(at, to) { + const mapDataLength = decodeCount(at, to); + const offset = _offset; + at += offset; + const base = at; + const map4 = {}; + for (let i5 = 0; i5 < mapDataLength; ++i5) { + if (at >= to) { + throw new Error("unexpected end of map payload."); + } + const major = (payload[at] & 224) >> 5; + if (major !== majorUtf8String) { + throw new Error(`unexpected major type ${major} for map key at index ${at}.`); + } + const key = decode(at, to); + at += _offset; + const value = decode(at, to); + at += _offset; + map4[key] = value; + } + _offset = offset + (at - base); + return map4; +} +function decodeMapIndefinite(at, to) { + at += 1; + const base = at; + const map4 = {}; + for (; at < to; ) { + if (at >= to) { + throw new Error("unexpected end of map payload."); + } + if (payload[at] === 255) { + _offset = at - base + 2; + return map4; + } + const major = (payload[at] & 224) >> 5; + if (major !== majorUtf8String) { + throw new Error(`unexpected major type ${major} for map key.`); + } + const key = decode(at, to); + at += _offset; + const value = decode(at, to); + at += _offset; + map4[key] = value; + } + throw new Error("expected break marker."); +} +function decodeSpecial(at, to) { + const minor = payload[at] & 31; + switch (minor) { + case specialTrue: + case specialFalse: + _offset = 1; + return minor === specialTrue; + case specialNull: + _offset = 1; + return null; + case specialUndefined: + _offset = 1; + return null; + case extendedFloat16: + if (to - at < 3) { + throw new Error("incomplete float16 at end of buf."); + } + _offset = 3; + return bytesToFloat16(payload[at + 1], payload[at + 2]); + case extendedFloat32: + if (to - at < 5) { + throw new Error("incomplete float32 at end of buf."); + } + _offset = 5; + return dataView.getFloat32(at + 1); + case extendedFloat64: + if (to - at < 9) { + throw new Error("incomplete float64 at end of buf."); + } + _offset = 9; + return dataView.getFloat64(at + 1); + default: + throw new Error(`unexpected minor value ${minor}.`); + } +} +function castBigInt(bigInt) { + if (typeof bigInt === "number") { + return bigInt; + } + const num = Number(bigInt); + if (Number.MIN_SAFE_INTEGER <= num && num <= Number.MAX_SAFE_INTEGER) { + return num; + } + return bigInt; +} +var import_util_utf84, USE_TEXT_DECODER, USE_BUFFER, payload, dataView, textDecoder, _offset, minorValueToArgumentLength; +var init_cbor_decode = __esm({ + "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/cbor/cbor-decode.js"() { + init_serde(); + import_util_utf84 = __toESM(require_dist_cjs6()); + init_cbor_types(); + USE_TEXT_DECODER = typeof TextDecoder !== "undefined"; + USE_BUFFER = typeof Buffer !== "undefined"; + payload = alloc(0); + dataView = new DataView(payload.buffer, payload.byteOffset, payload.byteLength); + textDecoder = USE_TEXT_DECODER ? new TextDecoder() : null; + _offset = 0; + minorValueToArgumentLength = { + [extendedOneByte]: 1, + [extendedFloat16]: 2, + [extendedFloat32]: 4, + [extendedFloat64]: 8 + }; + } +}); + +// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/cbor/cbor-encode.js +function ensureSpace(bytes) { + const remaining = data.byteLength - cursor; + if (remaining < bytes) { + if (cursor < 16e6) { + resize(Math.max(data.byteLength * 4, data.byteLength + bytes)); + } else { + resize(data.byteLength + bytes + 16e6); + } + } +} +function toUint8Array() { + const out = alloc(cursor); + out.set(data.subarray(0, cursor), 0); + cursor = 0; + return out; +} +function resize(size2) { + const old = data; + data = alloc(size2); + if (old) { + if (old.copy) { + old.copy(data, 0, 0, old.byteLength); + } else { + data.set(old, 0); + } + } + dataView2 = new DataView(data.buffer, data.byteOffset, data.byteLength); +} +function encodeHeader(major, value) { + if (value < 24) { + data[cursor++] = major << 5 | value; + } else if (value < 1 << 8) { + data[cursor++] = major << 5 | 24; + data[cursor++] = value; + } else if (value < 1 << 16) { + data[cursor++] = major << 5 | extendedFloat16; + dataView2.setUint16(cursor, value); + cursor += 2; + } else if (value < 2 ** 32) { + data[cursor++] = major << 5 | extendedFloat32; + dataView2.setUint32(cursor, value); + cursor += 4; + } else { + data[cursor++] = major << 5 | extendedFloat64; + dataView2.setBigUint64(cursor, typeof value === "bigint" ? value : BigInt(value)); + cursor += 8; + } +} +function encode(_input) { + const encodeStack = [_input]; + while (encodeStack.length) { + const input = encodeStack.pop(); + ensureSpace(typeof input === "string" ? input.length * 4 : 64); + if (typeof input === "string") { + if (USE_BUFFER2) { + encodeHeader(majorUtf8String, Buffer.byteLength(input)); + cursor += data.write(input, cursor); + } else { + const bytes = (0, import_util_utf85.fromUtf8)(input); + encodeHeader(majorUtf8String, bytes.byteLength); + data.set(bytes, cursor); + cursor += bytes.byteLength; + } + continue; + } else if (typeof input === "number") { + if (Number.isInteger(input)) { + const nonNegative = input >= 0; + const major = nonNegative ? majorUint64 : majorNegativeInt64; + const value = nonNegative ? input : -input - 1; + if (value < 24) { + data[cursor++] = major << 5 | value; + } else if (value < 256) { + data[cursor++] = major << 5 | 24; + data[cursor++] = value; + } else if (value < 65536) { + data[cursor++] = major << 5 | extendedFloat16; + data[cursor++] = value >> 8; + data[cursor++] = value; + } else if (value < 4294967296) { + data[cursor++] = major << 5 | extendedFloat32; + dataView2.setUint32(cursor, value); + cursor += 4; + } else { + data[cursor++] = major << 5 | extendedFloat64; + dataView2.setBigUint64(cursor, BigInt(value)); + cursor += 8; + } + continue; + } + data[cursor++] = majorSpecial << 5 | extendedFloat64; + dataView2.setFloat64(cursor, input); + cursor += 8; + continue; + } else if (typeof input === "bigint") { + const nonNegative = input >= 0; + const major = nonNegative ? majorUint64 : majorNegativeInt64; + const value = nonNegative ? input : -input - BigInt(1); + const n5 = Number(value); + if (n5 < 24) { + data[cursor++] = major << 5 | n5; + } else if (n5 < 256) { + data[cursor++] = major << 5 | 24; + data[cursor++] = n5; + } else if (n5 < 65536) { + data[cursor++] = major << 5 | extendedFloat16; + data[cursor++] = n5 >> 8; + data[cursor++] = n5 & 255; + } else if (n5 < 4294967296) { + data[cursor++] = major << 5 | extendedFloat32; + dataView2.setUint32(cursor, n5); + cursor += 4; + } else if (value < BigInt("18446744073709551616")) { + data[cursor++] = major << 5 | extendedFloat64; + dataView2.setBigUint64(cursor, value); + cursor += 8; + } else { + const binaryBigInt = value.toString(2); + const bigIntBytes = new Uint8Array(Math.ceil(binaryBigInt.length / 8)); + let b6 = value; + let i5 = 0; + while (bigIntBytes.byteLength - ++i5 >= 0) { + bigIntBytes[bigIntBytes.byteLength - i5] = Number(b6 & BigInt(255)); + b6 >>= BigInt(8); + } + ensureSpace(bigIntBytes.byteLength * 2); + data[cursor++] = nonNegative ? 194 : 195; + if (USE_BUFFER2) { + encodeHeader(majorUnstructuredByteString, Buffer.byteLength(bigIntBytes)); + } else { + encodeHeader(majorUnstructuredByteString, bigIntBytes.byteLength); + } + data.set(bigIntBytes, cursor); + cursor += bigIntBytes.byteLength; + } + continue; + } else if (input === null) { + data[cursor++] = majorSpecial << 5 | specialNull; + continue; + } else if (typeof input === "boolean") { + data[cursor++] = majorSpecial << 5 | (input ? specialTrue : specialFalse); + continue; + } else if (typeof input === "undefined") { + throw new Error("@smithy/core/cbor: client may not serialize undefined value."); + } else if (Array.isArray(input)) { + for (let i5 = input.length - 1; i5 >= 0; --i5) { + encodeStack.push(input[i5]); + } + encodeHeader(majorList, input.length); + continue; + } else if (typeof input.byteLength === "number") { + ensureSpace(input.length * 2); + encodeHeader(majorUnstructuredByteString, input.length); + data.set(input, cursor); + cursor += input.byteLength; + continue; + } else if (typeof input === "object") { + if (input instanceof NumericValue) { + const decimalIndex = input.string.indexOf("."); + const exponent = decimalIndex === -1 ? 0 : decimalIndex - input.string.length + 1; + const mantissa = BigInt(input.string.replace(".", "")); + data[cursor++] = 196; + encodeStack.push(mantissa); + encodeStack.push(exponent); + encodeHeader(majorList, 2); + continue; + } + if (input[tagSymbol]) { + if ("tag" in input && "value" in input) { + encodeStack.push(input.value); + encodeHeader(majorTag, input.tag); + continue; + } else { + throw new Error("tag encountered with missing fields, need 'tag' and 'value', found: " + JSON.stringify(input)); + } + } + const keys = Object.keys(input); + for (let i5 = keys.length - 1; i5 >= 0; --i5) { + const key = keys[i5]; + encodeStack.push(input[key]); + encodeStack.push(key); + } + encodeHeader(majorMap, keys.length); + continue; + } + throw new Error(`data type ${input?.constructor?.name ?? typeof input} not compatible for encoding.`); + } +} +var import_util_utf85, USE_BUFFER2, initialSize, data, dataView2, cursor; +var init_cbor_encode = __esm({ + "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/cbor/cbor-encode.js"() { + init_serde(); + import_util_utf85 = __toESM(require_dist_cjs6()); + init_cbor_types(); + USE_BUFFER2 = typeof Buffer !== "undefined"; + initialSize = 2048; + data = alloc(initialSize); + dataView2 = new DataView(data.buffer, data.byteOffset, data.byteLength); + cursor = 0; + } +}); + +// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/cbor/cbor.js +var cbor; +var init_cbor = __esm({ + "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/cbor/cbor.js"() { + init_cbor_decode(); + init_cbor_encode(); + cbor = { + deserialize(payload2) { + setPayload(payload2); + return decode(0, payload2.length); + }, + serialize(input) { + try { + encode(input); + return toUint8Array(); + } catch (e5) { + toUint8Array(); + throw e5; + } + }, + resizeEncodingBuffer(size2) { + resize(size2); + } + }; + } +}); + +// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/cbor/parseCborBody.js +var dateToTag, loadSmithyRpcV2CborErrorCode; +var init_parseCborBody = __esm({ + "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/cbor/parseCborBody.js"() { + init_cbor_types(); + dateToTag = (date7) => { + return tag({ + tag: 1, + value: date7.getTime() / 1e3 + }); + }; + loadSmithyRpcV2CborErrorCode = (output, data2) => { + const sanitizeErrorCode = (rawValue) => { + let cleanValue = rawValue; + if (typeof cleanValue === "number") { + cleanValue = cleanValue.toString(); + } + if (cleanValue.indexOf(",") >= 0) { + cleanValue = cleanValue.split(",")[0]; + } + if (cleanValue.indexOf(":") >= 0) { + cleanValue = cleanValue.split(":")[0]; + } + if (cleanValue.indexOf("#") >= 0) { + cleanValue = cleanValue.split("#")[1]; + } + return cleanValue; + }; + if (data2["__type"] !== void 0) { + return sanitizeErrorCode(data2["__type"]); + } + const codeKey = Object.keys(data2).find((key) => key.toLowerCase() === "code"); + if (codeKey && data2[codeKey] !== void 0) { + return sanitizeErrorCode(data2[codeKey]); + } + }; + } +}); + +// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/cbor/CborCodec.js +var import_util_base643, CborCodec, CborShapeSerializer, CborShapeDeserializer; +var init_CborCodec = __esm({ + "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/cbor/CborCodec.js"() { + init_protocols(); + init_schema3(); + init_serde(); + init_serde(); + import_util_base643 = __toESM(require_dist_cjs7()); + init_cbor(); + init_parseCborBody(); + CborCodec = class extends SerdeContext { + createSerializer() { + const serializer = new CborShapeSerializer(); + serializer.setSerdeContext(this.serdeContext); + return serializer; + } + createDeserializer() { + const deserializer = new CborShapeDeserializer(); + deserializer.setSerdeContext(this.serdeContext); + return deserializer; + } + }; + CborShapeSerializer = class extends SerdeContext { + value; + write(schema2, value) { + this.value = this.serialize(schema2, value); + } + serialize(schema2, source) { + const ns = NormalizedSchema.of(schema2); + if (source == null) { + if (ns.isIdempotencyToken()) { + return (0, import_uuid2.v4)(); + } + return source; + } + if (ns.isBlobSchema()) { + if (typeof source === "string") { + return (this.serdeContext?.base64Decoder ?? import_util_base643.fromBase64)(source); + } + return source; + } + if (ns.isTimestampSchema()) { + if (typeof source === "number" || typeof source === "bigint") { + return dateToTag(new Date(Number(source) / 1e3 | 0)); + } + return dateToTag(source); + } + if (typeof source === "function" || typeof source === "object") { + const sourceObject = source; + if (ns.isListSchema() && Array.isArray(sourceObject)) { + const sparse = !!ns.getMergedTraits().sparse; + const newArray = []; + let i5 = 0; + for (const item of sourceObject) { + const value = this.serialize(ns.getValueSchema(), item); + if (value != null || sparse) { + newArray[i5++] = value; + } + } + return newArray; + } + if (sourceObject instanceof Date) { + return dateToTag(sourceObject); + } + const newObject = {}; + if (ns.isMapSchema()) { + const sparse = !!ns.getMergedTraits().sparse; + for (const key of Object.keys(sourceObject)) { + const value = this.serialize(ns.getValueSchema(), sourceObject[key]); + if (value != null || sparse) { + newObject[key] = value; + } + } + } else if (ns.isStructSchema()) { + for (const [key, memberSchema] of ns.structIterator()) { + const value = this.serialize(memberSchema, sourceObject[key]); + if (value != null) { + newObject[key] = value; + } + } + const isUnion = ns.isUnionSchema(); + if (isUnion && Array.isArray(sourceObject.$unknown)) { + const [k5, v5] = sourceObject.$unknown; + newObject[k5] = v5; + } else if (typeof sourceObject.__type === "string") { + for (const [k5, v5] of Object.entries(sourceObject)) { + if (!(k5 in newObject)) { + newObject[k5] = this.serialize(15, v5); + } + } + } + } else if (ns.isDocumentSchema()) { + for (const key of Object.keys(sourceObject)) { + newObject[key] = this.serialize(ns.getValueSchema(), sourceObject[key]); + } + } else if (ns.isBigDecimalSchema()) { + return sourceObject; + } + return newObject; + } + return source; + } + flush() { + const buffer2 = cbor.serialize(this.value); + this.value = void 0; + return buffer2; + } + }; + CborShapeDeserializer = class extends SerdeContext { + read(schema2, bytes) { + const data2 = cbor.deserialize(bytes); + return this.readValue(schema2, data2); + } + readValue(_schema, value) { + const ns = NormalizedSchema.of(_schema); + if (ns.isTimestampSchema()) { + if (typeof value === "number") { + return _parseEpochTimestamp(value); + } + if (typeof value === "object") { + if (value.tag === 1 && "value" in value) { + return _parseEpochTimestamp(value.value); + } + } + } + if (ns.isBlobSchema()) { + if (typeof value === "string") { + return (this.serdeContext?.base64Decoder ?? import_util_base643.fromBase64)(value); + } + return value; + } + if (typeof value === "undefined" || typeof value === "boolean" || typeof value === "number" || typeof value === "string" || typeof value === "bigint" || typeof value === "symbol") { + return value; + } else if (typeof value === "object") { + if (value === null) { + return null; + } + if ("byteLength" in value) { + return value; + } + if (value instanceof Date) { + return value; + } + if (ns.isDocumentSchema()) { + return value; + } + if (ns.isListSchema()) { + const newArray = []; + const memberSchema = ns.getValueSchema(); + for (const item of value) { + const itemValue = this.readValue(memberSchema, item); + newArray.push(itemValue); + } + return newArray; + } + const newObject = {}; + if (ns.isMapSchema()) { + const targetSchema = ns.getValueSchema(); + for (const key of Object.keys(value)) { + const itemValue = this.readValue(targetSchema, value[key]); + newObject[key] = itemValue; + } + } else if (ns.isStructSchema()) { + const isUnion = ns.isUnionSchema(); + let keys; + if (isUnion) { + keys = new Set(Object.keys(value).filter((k5) => k5 !== "__type")); + } + for (const [key, memberSchema] of ns.structIterator()) { + if (isUnion) { + keys.delete(key); + } + if (value[key] != null) { + newObject[key] = this.readValue(memberSchema, value[key]); + } + } + if (isUnion && keys?.size === 1 && Object.keys(newObject).length === 0) { + const k5 = keys.values().next().value; + newObject.$unknown = [k5, value[k5]]; + } else if (typeof value.__type === "string") { + for (const [k5, v5] of Object.entries(value)) { + if (!(k5 in newObject)) { + newObject[k5] = v5; + } + } + } + } else if (value instanceof NumericValue) { + return value; + } + return newObject; + } else { + return value; + } + } + }; + } +}); + +// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/cbor/SmithyRpcV2CborProtocol.js +var import_util_middleware3, SmithyRpcV2CborProtocol; +var init_SmithyRpcV2CborProtocol = __esm({ + "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/cbor/SmithyRpcV2CborProtocol.js"() { + init_protocols(); + init_schema3(); + init_schema3(); + import_util_middleware3 = __toESM(require_dist_cjs18()); + init_CborCodec(); + init_parseCborBody(); + SmithyRpcV2CborProtocol = class extends RpcProtocol { + codec = new CborCodec(); + serializer = this.codec.createSerializer(); + deserializer = this.codec.createDeserializer(); + constructor({ defaultNamespace, errorTypeRegistries: errorTypeRegistries5 }) { + super({ defaultNamespace, errorTypeRegistries: errorTypeRegistries5 }); + } + getShapeId() { + return "smithy.protocols#rpcv2Cbor"; + } + getPayloadCodec() { + return this.codec; + } + async serializeRequest(operationSchema, input, context) { + const request = await super.serializeRequest(operationSchema, input, context); + Object.assign(request.headers, { + "content-type": this.getDefaultContentType(), + "smithy-protocol": "rpc-v2-cbor", + accept: this.getDefaultContentType() + }); + if (deref(operationSchema.input) === "unit") { + delete request.body; + delete request.headers["content-type"]; + } else { + if (!request.body) { + this.serializer.write(15, {}); + request.body = this.serializer.flush(); + } + try { + request.headers["content-length"] = String(request.body.byteLength); + } catch (e5) { + } + } + const { service, operation: operation2 } = (0, import_util_middleware3.getSmithyContext)(context); + const path53 = `/service/${service}/operation/${operation2}`; + if (request.path.endsWith("/")) { + request.path += path53.slice(1); + } else { + request.path += path53; + } + return request; + } + async deserializeResponse(operationSchema, context, response) { + return super.deserializeResponse(operationSchema, context, response); + } + async handleError(operationSchema, context, response, dataObject, metadata) { + const errorName = loadSmithyRpcV2CborErrorCode(response, dataObject) ?? "Unknown"; + const errorMetadata = { + $metadata: metadata, + $fault: response.statusCode <= 500 ? "client" : "server" + }; + let namespace = this.options.defaultNamespace; + if (errorName.includes("#")) { + [namespace] = errorName.split("#"); + } + const registry2 = this.compositeErrorRegistry; + const nsRegistry = TypeRegistry.for(namespace); + registry2.copyFrom(nsRegistry); + let errorSchema; + try { + errorSchema = registry2.getSchema(errorName); + } catch (e5) { + if (dataObject.Message) { + dataObject.message = dataObject.Message; + } + const syntheticRegistry = TypeRegistry.for("smithy.ts.sdk.synthetic." + namespace); + registry2.copyFrom(syntheticRegistry); + const baseExceptionSchema = registry2.getBaseException(); + if (baseExceptionSchema) { + const ErrorCtor2 = registry2.getErrorCtor(baseExceptionSchema); + throw Object.assign(new ErrorCtor2({ name: errorName }), errorMetadata, dataObject); + } + throw Object.assign(new Error(errorName), errorMetadata, dataObject); + } + const ns = NormalizedSchema.of(errorSchema); + const ErrorCtor = registry2.getErrorCtor(errorSchema); + const message2 = dataObject.message ?? dataObject.Message ?? "Unknown"; + const exception = new ErrorCtor(message2); + const output = {}; + for (const [name, member2] of ns.structIterator()) { + output[name] = this.deserializer.readValue(member2, dataObject[name]); + } + throw Object.assign(exception, errorMetadata, { + $fault: ns.getMergedTraits().error, + message: message2 + }, output); + } + getDefaultContentType() { + return "application/cbor"; + } + }; + } +}); + +// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/cbor/index.js +var init_cbor2 = __esm({ + "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/cbor/index.js"() { + init_parseCborBody(); + init_SmithyRpcV2CborProtocol(); + init_CborCodec(); + } +}); + +// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/ProtocolLib.js +var import_smithy_client, ProtocolLib; +var init_ProtocolLib = __esm({ + "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/ProtocolLib.js"() { + init_schema3(); + import_smithy_client = __toESM(require_dist_cjs27()); + ProtocolLib = class { + queryCompat; + errorRegistry; + constructor(queryCompat = false) { + this.queryCompat = queryCompat; + } + resolveRestContentType(defaultContentType, inputSchema) { + const members = inputSchema.getMemberSchemas(); + const httpPayloadMember = Object.values(members).find((m5) => { + return !!m5.getMergedTraits().httpPayload; + }); + if (httpPayloadMember) { + const mediaType = httpPayloadMember.getMergedTraits().mediaType; + if (mediaType) { + return mediaType; + } else if (httpPayloadMember.isStringSchema()) { + return "text/plain"; + } else if (httpPayloadMember.isBlobSchema()) { + return "application/octet-stream"; + } else { + return defaultContentType; + } + } else if (!inputSchema.isUnitSchema()) { + const hasBody = Object.values(members).find((m5) => { + const { httpQuery, httpQueryParams, httpHeader, httpLabel, httpPrefixHeaders } = m5.getMergedTraits(); + const noPrefixHeaders = httpPrefixHeaders === void 0; + return !httpQuery && !httpQueryParams && !httpHeader && !httpLabel && noPrefixHeaders; + }); + if (hasBody) { + return defaultContentType; + } + } + } + async getErrorSchemaOrThrowBaseException(errorIdentifier, defaultNamespace, response, dataObject, metadata, getErrorSchema) { + let errorName = errorIdentifier; + if (errorIdentifier.includes("#")) { + [, errorName] = errorIdentifier.split("#"); + } + const errorMetadata = { + $metadata: metadata, + $fault: response.statusCode < 500 ? "client" : "server" + }; + if (!this.errorRegistry) { + throw new Error("@aws-sdk/core/protocols - error handler not initialized."); + } + try { + const errorSchema = getErrorSchema?.(this.errorRegistry, errorName) ?? this.errorRegistry.getSchema(errorIdentifier); + return { errorSchema, errorMetadata }; + } catch (e5) { + dataObject.message = dataObject.message ?? dataObject.Message ?? "UnknownError"; + const synthetic = this.errorRegistry; + const baseExceptionSchema = synthetic.getBaseException(); + if (baseExceptionSchema) { + const ErrorCtor = synthetic.getErrorCtor(baseExceptionSchema) ?? Error; + throw this.decorateServiceException(Object.assign(new ErrorCtor({ name: errorName }), errorMetadata), dataObject); + } + const d5 = dataObject; + const message2 = d5?.message ?? d5?.Message ?? d5?.Error?.Message ?? d5?.Error?.message; + throw this.decorateServiceException(Object.assign(new Error(message2), { + name: errorName + }, errorMetadata), dataObject); + } + } + compose(composite, errorIdentifier, defaultNamespace) { + let namespace = defaultNamespace; + if (errorIdentifier.includes("#")) { + [namespace] = errorIdentifier.split("#"); + } + const staticRegistry = TypeRegistry.for(namespace); + const defaultSyntheticRegistry = TypeRegistry.for("smithy.ts.sdk.synthetic." + defaultNamespace); + composite.copyFrom(staticRegistry); + composite.copyFrom(defaultSyntheticRegistry); + this.errorRegistry = composite; + } + decorateServiceException(exception, additions = {}) { + if (this.queryCompat) { + const msg = exception.Message ?? additions.Message; + const error50 = (0, import_smithy_client.decorateServiceException)(exception, additions); + if (msg) { + error50.message = msg; + } + error50.Error = { + ...error50.Error, + Type: error50.Error?.Type, + Code: error50.Error?.Code, + Message: error50.Error?.message ?? error50.Error?.Message ?? msg + }; + const reqId = error50.$metadata.requestId; + if (reqId) { + error50.RequestId = reqId; + } + return error50; + } + return (0, import_smithy_client.decorateServiceException)(exception, additions); + } + setQueryCompatError(output, response) { + const queryErrorHeader = response.headers?.["x-amzn-query-error"]; + if (output !== void 0 && queryErrorHeader != null) { + const [Code, Type] = queryErrorHeader.split(";"); + const entries2 = Object.entries(output); + const Error2 = { + Code, + Type + }; + Object.assign(output, Error2); + for (const [k5, v5] of entries2) { + Error2[k5 === "message" ? "Message" : k5] = v5; + } + delete Error2.__type; + output.Error = Error2; + } + } + queryCompatOutput(queryCompatErrorData, errorData) { + if (queryCompatErrorData.Error) { + errorData.Error = queryCompatErrorData.Error; + } + if (queryCompatErrorData.Type) { + errorData.Type = queryCompatErrorData.Type; + } + if (queryCompatErrorData.Code) { + errorData.Code = queryCompatErrorData.Code; + } + } + findQueryCompatibleError(registry2, errorName) { + try { + return registry2.getSchema(errorName); + } catch (e5) { + return registry2.find((schema2) => NormalizedSchema.of(schema2).getMergedTraits().awsQueryError?.[0] === errorName); + } + } + }; + } +}); + +// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/cbor/AwsSmithyRpcV2CborProtocol.js +var AwsSmithyRpcV2CborProtocol; +var init_AwsSmithyRpcV2CborProtocol = __esm({ + "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/cbor/AwsSmithyRpcV2CborProtocol.js"() { + init_cbor2(); + init_schema3(); + init_ProtocolLib(); + AwsSmithyRpcV2CborProtocol = class extends SmithyRpcV2CborProtocol { + awsQueryCompatible; + mixin; + constructor({ defaultNamespace, errorTypeRegistries: errorTypeRegistries5, awsQueryCompatible }) { + super({ defaultNamespace, errorTypeRegistries: errorTypeRegistries5 }); + this.awsQueryCompatible = !!awsQueryCompatible; + this.mixin = new ProtocolLib(this.awsQueryCompatible); + } + async serializeRequest(operationSchema, input, context) { + const request = await super.serializeRequest(operationSchema, input, context); + if (this.awsQueryCompatible) { + request.headers["x-amzn-query-mode"] = "true"; + } + return request; + } + async handleError(operationSchema, context, response, dataObject, metadata) { + if (this.awsQueryCompatible) { + this.mixin.setQueryCompatError(dataObject, response); + } + const errorName = (() => { + const compatHeader = response.headers["x-amzn-query-error"]; + if (compatHeader && this.awsQueryCompatible) { + return compatHeader.split(";")[0]; + } + return loadSmithyRpcV2CborErrorCode(response, dataObject) ?? "Unknown"; + })(); + this.mixin.compose(this.compositeErrorRegistry, errorName, this.options.defaultNamespace); + const { errorSchema, errorMetadata } = await this.mixin.getErrorSchemaOrThrowBaseException(errorName, this.options.defaultNamespace, response, dataObject, metadata, this.awsQueryCompatible ? this.mixin.findQueryCompatibleError : void 0); + const ns = NormalizedSchema.of(errorSchema); + const message2 = dataObject.message ?? dataObject.Message ?? "UnknownError"; + const ErrorCtor = this.compositeErrorRegistry.getErrorCtor(errorSchema) ?? Error; + const exception = new ErrorCtor(message2); + const output = {}; + for (const [name, member2] of ns.structIterator()) { + if (dataObject[name] != null) { + output[name] = this.deserializer.readValue(member2, dataObject[name]); + } + } + if (this.awsQueryCompatible) { + this.mixin.queryCompatOutput(dataObject, output); + } + throw this.mixin.decorateServiceException(Object.assign(exception, errorMetadata, { + $fault: ns.getMergedTraits().error, + message: message2 + }, output), dataObject); + } + }; + } +}); + +// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/coercing-serializers.js +var _toStr, _toBool, _toNum; +var init_coercing_serializers = __esm({ + "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/coercing-serializers.js"() { + _toStr = (val) => { + if (val == null) { + return val; + } + if (typeof val === "number" || typeof val === "bigint") { + const warning = new Error(`Received number ${val} where a string was expected.`); + warning.name = "Warning"; + console.warn(warning); + return String(val); + } + if (typeof val === "boolean") { + const warning = new Error(`Received boolean ${val} where a string was expected.`); + warning.name = "Warning"; + console.warn(warning); + return String(val); + } + return val; + }; + _toBool = (val) => { + if (val == null) { + return val; + } + if (typeof val === "number") { + } + if (typeof val === "string") { + const lowercase2 = val.toLowerCase(); + if (val !== "" && lowercase2 !== "false" && lowercase2 !== "true") { + const warning = new Error(`Received string "${val}" where a boolean was expected.`); + warning.name = "Warning"; + console.warn(warning); + } + return val !== "" && lowercase2 !== "false"; + } + return val; + }; + _toNum = (val) => { + if (val == null) { + return val; + } + if (typeof val === "boolean") { + } + if (typeof val === "string") { + const num = Number(val); + if (num.toString() !== val) { + const warning = new Error(`Received string "${val}" where a number was expected.`); + warning.name = "Warning"; + console.warn(warning); + return val; + } + return num; + } + return val; + }; + } +}); + +// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/ConfigurableSerdeContext.js +var SerdeContextConfig; +var init_ConfigurableSerdeContext = __esm({ + "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/ConfigurableSerdeContext.js"() { + SerdeContextConfig = class { + serdeContext; + setSerdeContext(serdeContext) { + this.serdeContext = serdeContext; + } + }; + } +}); + +// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/UnionSerde.js +var UnionSerde; +var init_UnionSerde = __esm({ + "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/UnionSerde.js"() { + UnionSerde = class { + from; + to; + keys; + constructor(from, to) { + this.from = from; + this.to = to; + this.keys = new Set(Object.keys(this.from).filter((k5) => k5 !== "__type")); + } + mark(key) { + this.keys.delete(key); + } + hasUnknown() { + return this.keys.size === 1 && Object.keys(this.to).length === 0; + } + writeUnknown() { + if (this.hasUnknown()) { + const k5 = this.keys.values().next().value; + const v5 = this.from[k5]; + this.to.$unknown = [k5, v5]; + } + } + }; + } +}); + +// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/jsonReviver.js +function jsonReviver(key, value, context) { + if (context?.source) { + const numericString = context.source; + if (typeof value === "number") { + if (value > Number.MAX_SAFE_INTEGER || value < Number.MIN_SAFE_INTEGER || numericString !== String(value)) { + const isFractional = numericString.includes("."); + if (isFractional) { + return new NumericValue(numericString, "bigDecimal"); + } else { + return BigInt(numericString); + } + } + } + } + return value; +} +var init_jsonReviver = __esm({ + "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/jsonReviver.js"() { + init_serde(); + } +}); + +// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/common.js +var import_smithy_client2, import_util_utf86, collectBodyString; +var init_common2 = __esm({ + "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/common.js"() { + import_smithy_client2 = __toESM(require_dist_cjs27()); + import_util_utf86 = __toESM(require_dist_cjs6()); + collectBodyString = (streamBody, context) => (0, import_smithy_client2.collectBody)(streamBody, context).then((body) => (context?.utf8Encoder ?? import_util_utf86.toUtf8)(body)); + } +}); + +// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/parseJsonBody.js +var parseJsonBody, parseJsonErrorBody, loadRestJsonErrorCode; +var init_parseJsonBody = __esm({ + "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/parseJsonBody.js"() { + init_common2(); + parseJsonBody = (streamBody, context) => collectBodyString(streamBody, context).then((encoded) => { + if (encoded.length) { + try { + return JSON.parse(encoded); + } catch (e5) { + if (e5?.name === "SyntaxError") { + Object.defineProperty(e5, "$responseBodyText", { + value: encoded + }); + } + throw e5; + } + } + return {}; + }); + parseJsonErrorBody = async (errorBody, context) => { + const value = await parseJsonBody(errorBody, context); + value.message = value.message ?? value.Message; + return value; + }; + loadRestJsonErrorCode = (output, data2) => { + const findKey = (object2, key) => Object.keys(object2).find((k5) => k5.toLowerCase() === key.toLowerCase()); + const sanitizeErrorCode = (rawValue) => { + let cleanValue = rawValue; + if (typeof cleanValue === "number") { + cleanValue = cleanValue.toString(); + } + if (cleanValue.indexOf(",") >= 0) { + cleanValue = cleanValue.split(",")[0]; + } + if (cleanValue.indexOf(":") >= 0) { + cleanValue = cleanValue.split(":")[0]; + } + if (cleanValue.indexOf("#") >= 0) { + cleanValue = cleanValue.split("#")[1]; + } + return cleanValue; + }; + const headerKey = findKey(output.headers, "x-amzn-errortype"); + if (headerKey !== void 0) { + return sanitizeErrorCode(output.headers[headerKey]); + } + if (data2 && typeof data2 === "object") { + const codeKey = findKey(data2, "code"); + if (codeKey && data2[codeKey] !== void 0) { + return sanitizeErrorCode(data2[codeKey]); + } + if (data2["__type"] !== void 0) { + return sanitizeErrorCode(data2["__type"]); + } + } + }; + } +}); + +// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/JsonShapeDeserializer.js +var import_util_base644, JsonShapeDeserializer; +var init_JsonShapeDeserializer = __esm({ + "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/JsonShapeDeserializer.js"() { + init_protocols(); + init_schema3(); + init_serde(); + import_util_base644 = __toESM(require_dist_cjs7()); + init_ConfigurableSerdeContext(); + init_UnionSerde(); + init_jsonReviver(); + init_parseJsonBody(); + JsonShapeDeserializer = class extends SerdeContextConfig { + settings; + constructor(settings) { + super(); + this.settings = settings; + } + async read(schema2, data2) { + return this._read(schema2, typeof data2 === "string" ? JSON.parse(data2, jsonReviver) : await parseJsonBody(data2, this.serdeContext)); + } + readObject(schema2, data2) { + return this._read(schema2, data2); + } + _read(schema2, value) { + const isObject4 = value !== null && typeof value === "object"; + const ns = NormalizedSchema.of(schema2); + if (isObject4) { + if (ns.isStructSchema()) { + const record2 = value; + const union3 = ns.isUnionSchema(); + const out = {}; + let nameMap = void 0; + const { jsonName } = this.settings; + if (jsonName) { + nameMap = {}; + } + let unionSerde; + if (union3) { + unionSerde = new UnionSerde(record2, out); + } + for (const [memberName, memberSchema] of ns.structIterator()) { + let fromKey = memberName; + if (jsonName) { + fromKey = memberSchema.getMergedTraits().jsonName ?? fromKey; + nameMap[fromKey] = memberName; + } + if (union3) { + unionSerde.mark(fromKey); + } + if (record2[fromKey] != null) { + out[memberName] = this._read(memberSchema, record2[fromKey]); + } + } + if (union3) { + unionSerde.writeUnknown(); + } else if (typeof record2.__type === "string") { + for (const [k5, v5] of Object.entries(record2)) { + const t5 = jsonName ? nameMap[k5] ?? k5 : k5; + if (!(t5 in out)) { + out[t5] = v5; + } + } + } + return out; + } + if (Array.isArray(value) && ns.isListSchema()) { + const listMember = ns.getValueSchema(); + const out = []; + for (const item of value) { + out.push(this._read(listMember, item)); + } + return out; + } + if (ns.isMapSchema()) { + const mapMember = ns.getValueSchema(); + const out = {}; + for (const [_k, _v] of Object.entries(value)) { + out[_k] = this._read(mapMember, _v); + } + return out; + } + } + if (ns.isBlobSchema() && typeof value === "string") { + return (0, import_util_base644.fromBase64)(value); + } + const mediaType = ns.getMergedTraits().mediaType; + if (ns.isStringSchema() && typeof value === "string" && mediaType) { + const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); + if (isJson) { + return LazyJsonString.from(value); + } + return value; + } + if (ns.isTimestampSchema() && value != null) { + const format2 = determineTimestampFormat(ns, this.settings); + switch (format2) { + case 5: + return parseRfc3339DateTimeWithOffset(value); + case 6: + return parseRfc7231DateTime(value); + case 7: + return parseEpochTimestamp(value); + default: + console.warn("Missing timestamp format, parsing value with Date constructor:", value); + return new Date(value); + } + } + if (ns.isBigIntegerSchema() && (typeof value === "number" || typeof value === "string")) { + return BigInt(value); + } + if (ns.isBigDecimalSchema() && value != void 0) { + if (value instanceof NumericValue) { + return value; + } + const untyped = value; + if (untyped.type === "bigDecimal" && "string" in untyped) { + return new NumericValue(untyped.string, untyped.type); + } + return new NumericValue(String(value), "bigDecimal"); + } + if (ns.isNumericSchema() && typeof value === "string") { + switch (value) { + case "Infinity": + return Infinity; + case "-Infinity": + return -Infinity; + case "NaN": + return NaN; + } + return value; + } + if (ns.isDocumentSchema()) { + if (isObject4) { + const out = Array.isArray(value) ? [] : {}; + for (const [k5, v5] of Object.entries(value)) { + if (v5 instanceof NumericValue) { + out[k5] = v5; + } else { + out[k5] = this._read(ns, v5); + } + } + return out; + } else { + return structuredClone(value); + } + } + return value; + } + }; + } +}); + +// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/jsonReplacer.js +var NUMERIC_CONTROL_CHAR, JsonReplacer; +var init_jsonReplacer = __esm({ + "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/jsonReplacer.js"() { + init_serde(); + NUMERIC_CONTROL_CHAR = String.fromCharCode(925); + JsonReplacer = class { + values = /* @__PURE__ */ new Map(); + counter = 0; + stage = 0; + createReplacer() { + if (this.stage === 1) { + throw new Error("@aws-sdk/core/protocols - JsonReplacer already created."); + } + if (this.stage === 2) { + throw new Error("@aws-sdk/core/protocols - JsonReplacer exhausted."); + } + this.stage = 1; + return (key, value) => { + if (value instanceof NumericValue) { + const v5 = `${NUMERIC_CONTROL_CHAR + "nv" + this.counter++}_` + value.string; + this.values.set(`"${v5}"`, value.string); + return v5; + } + if (typeof value === "bigint") { + const s5 = value.toString(); + const v5 = `${NUMERIC_CONTROL_CHAR + "b" + this.counter++}_` + s5; + this.values.set(`"${v5}"`, s5); + return v5; + } + return value; + }; + } + replaceInJson(json3) { + if (this.stage === 0) { + throw new Error("@aws-sdk/core/protocols - JsonReplacer not created yet."); + } + if (this.stage === 2) { + throw new Error("@aws-sdk/core/protocols - JsonReplacer exhausted."); + } + this.stage = 2; + if (this.counter === 0) { + return json3; + } + for (const [key, value] of this.values) { + json3 = json3.replace(key, value); + } + return json3; + } + }; + } +}); + +// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/JsonShapeSerializer.js +var import_util_base645, JsonShapeSerializer; +var init_JsonShapeSerializer = __esm({ + "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/JsonShapeSerializer.js"() { + init_protocols(); + init_schema3(); + init_serde(); + import_util_base645 = __toESM(require_dist_cjs7()); + init_ConfigurableSerdeContext(); + init_jsonReplacer(); + JsonShapeSerializer = class extends SerdeContextConfig { + settings; + buffer; + useReplacer = false; + rootSchema; + constructor(settings) { + super(); + this.settings = settings; + } + write(schema2, value) { + this.rootSchema = NormalizedSchema.of(schema2); + this.buffer = this._write(this.rootSchema, value); + } + writeDiscriminatedDocument(schema2, value) { + this.write(schema2, value); + if (typeof this.buffer === "object") { + this.buffer.__type = NormalizedSchema.of(schema2).getName(true); + } + } + flush() { + const { rootSchema, useReplacer } = this; + this.rootSchema = void 0; + this.useReplacer = false; + if (rootSchema?.isStructSchema() || rootSchema?.isDocumentSchema()) { + if (!useReplacer) { + return JSON.stringify(this.buffer); + } + const replacer = new JsonReplacer(); + return replacer.replaceInJson(JSON.stringify(this.buffer, replacer.createReplacer(), 0)); + } + return this.buffer; + } + _write(schema2, value, container) { + const isObject4 = value !== null && typeof value === "object"; + const ns = NormalizedSchema.of(schema2); + if (isObject4) { + if (ns.isStructSchema()) { + const record2 = value; + const out = {}; + const { jsonName } = this.settings; + let nameMap = void 0; + if (jsonName) { + nameMap = {}; + } + for (const [memberName, memberSchema] of ns.structIterator()) { + const serializableValue = this._write(memberSchema, record2[memberName], ns); + if (serializableValue !== void 0) { + let targetKey = memberName; + if (jsonName) { + targetKey = memberSchema.getMergedTraits().jsonName ?? memberName; + nameMap[memberName] = targetKey; + } + out[targetKey] = serializableValue; + } + } + if (ns.isUnionSchema() && Object.keys(out).length === 0) { + const { $unknown } = record2; + if (Array.isArray($unknown)) { + const [k5, v5] = $unknown; + out[k5] = this._write(15, v5); + } + } else if (typeof record2.__type === "string") { + for (const [k5, v5] of Object.entries(record2)) { + const targetKey = jsonName ? nameMap[k5] ?? k5 : k5; + if (!(targetKey in out)) { + out[targetKey] = this._write(15, v5); + } + } + } + return out; + } + if (Array.isArray(value) && ns.isListSchema()) { + const listMember = ns.getValueSchema(); + const out = []; + const sparse = !!ns.getMergedTraits().sparse; + for (const item of value) { + if (sparse || item != null) { + out.push(this._write(listMember, item)); + } + } + return out; + } + if (ns.isMapSchema()) { + const mapMember = ns.getValueSchema(); + const out = {}; + const sparse = !!ns.getMergedTraits().sparse; + for (const [_k, _v] of Object.entries(value)) { + if (sparse || _v != null) { + out[_k] = this._write(mapMember, _v); + } + } + return out; + } + if (value instanceof Uint8Array && (ns.isBlobSchema() || ns.isDocumentSchema())) { + if (ns === this.rootSchema) { + return value; + } + return (this.serdeContext?.base64Encoder ?? import_util_base645.toBase64)(value); + } + if (value instanceof Date && (ns.isTimestampSchema() || ns.isDocumentSchema())) { + const format2 = determineTimestampFormat(ns, this.settings); + switch (format2) { + case 5: + return value.toISOString().replace(".000Z", "Z"); + case 6: + return dateToUtcString(value); + case 7: + return value.getTime() / 1e3; + default: + console.warn("Missing timestamp format, using epoch seconds", value); + return value.getTime() / 1e3; + } + } + if (value instanceof NumericValue) { + this.useReplacer = true; + } + } + if (value === null && container?.isStructSchema()) { + return void 0; + } + if (ns.isStringSchema()) { + if (typeof value === "undefined" && ns.isIdempotencyToken()) { + return (0, import_uuid2.v4)(); + } + const mediaType = ns.getMergedTraits().mediaType; + if (value != null && mediaType) { + const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); + if (isJson) { + return LazyJsonString.from(value); + } + } + return value; + } + if (typeof value === "number" && ns.isNumericSchema()) { + if (Math.abs(value) === Infinity || isNaN(value)) { + return String(value); + } + return value; + } + if (typeof value === "string" && ns.isBlobSchema()) { + if (ns === this.rootSchema) { + return value; + } + return (this.serdeContext?.base64Encoder ?? import_util_base645.toBase64)(value); + } + if (typeof value === "bigint") { + this.useReplacer = true; + } + if (ns.isDocumentSchema()) { + if (isObject4) { + const out = Array.isArray(value) ? [] : {}; + for (const [k5, v5] of Object.entries(value)) { + if (v5 instanceof NumericValue) { + this.useReplacer = true; + out[k5] = v5; + } else { + out[k5] = this._write(ns, v5); + } + } + return out; + } else { + return structuredClone(value); + } + } + return value; + } + }; + } +}); + +// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/JsonCodec.js +var JsonCodec; +var init_JsonCodec = __esm({ + "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/JsonCodec.js"() { + init_ConfigurableSerdeContext(); + init_JsonShapeDeserializer(); + init_JsonShapeSerializer(); + JsonCodec = class extends SerdeContextConfig { + settings; + constructor(settings) { + super(); + this.settings = settings; + } + createSerializer() { + const serializer = new JsonShapeSerializer(this.settings); + serializer.setSerdeContext(this.serdeContext); + return serializer; + } + createDeserializer() { + const deserializer = new JsonShapeDeserializer(this.settings); + deserializer.setSerdeContext(this.serdeContext); + return deserializer; + } + }; + } +}); + +// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/AwsJsonRpcProtocol.js +var AwsJsonRpcProtocol; +var init_AwsJsonRpcProtocol = __esm({ + "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/AwsJsonRpcProtocol.js"() { + init_protocols(); + init_schema3(); + init_ProtocolLib(); + init_JsonCodec(); + init_parseJsonBody(); + AwsJsonRpcProtocol = class extends RpcProtocol { + serializer; + deserializer; + serviceTarget; + codec; + mixin; + awsQueryCompatible; + constructor({ defaultNamespace, errorTypeRegistries: errorTypeRegistries5, serviceTarget, awsQueryCompatible, jsonCodec }) { + super({ + defaultNamespace, + errorTypeRegistries: errorTypeRegistries5 + }); + this.serviceTarget = serviceTarget; + this.codec = jsonCodec ?? new JsonCodec({ + timestampFormat: { + useTrait: true, + default: 7 + }, + jsonName: false + }); + this.serializer = this.codec.createSerializer(); + this.deserializer = this.codec.createDeserializer(); + this.awsQueryCompatible = !!awsQueryCompatible; + this.mixin = new ProtocolLib(this.awsQueryCompatible); + } + async serializeRequest(operationSchema, input, context) { + const request = await super.serializeRequest(operationSchema, input, context); + if (!request.path.endsWith("/")) { + request.path += "/"; + } + Object.assign(request.headers, { + "content-type": `application/x-amz-json-${this.getJsonRpcVersion()}`, + "x-amz-target": `${this.serviceTarget}.${operationSchema.name}` + }); + if (this.awsQueryCompatible) { + request.headers["x-amzn-query-mode"] = "true"; + } + if (deref(operationSchema.input) === "unit" || !request.body) { + request.body = "{}"; + } + return request; + } + getPayloadCodec() { + return this.codec; + } + async handleError(operationSchema, context, response, dataObject, metadata) { + if (this.awsQueryCompatible) { + this.mixin.setQueryCompatError(dataObject, response); + } + const errorIdentifier = loadRestJsonErrorCode(response, dataObject) ?? "Unknown"; + this.mixin.compose(this.compositeErrorRegistry, errorIdentifier, this.options.defaultNamespace); + const { errorSchema, errorMetadata } = await this.mixin.getErrorSchemaOrThrowBaseException(errorIdentifier, this.options.defaultNamespace, response, dataObject, metadata, this.awsQueryCompatible ? this.mixin.findQueryCompatibleError : void 0); + const ns = NormalizedSchema.of(errorSchema); + const message2 = dataObject.message ?? dataObject.Message ?? "UnknownError"; + const ErrorCtor = this.compositeErrorRegistry.getErrorCtor(errorSchema) ?? Error; + const exception = new ErrorCtor(message2); + const output = {}; + for (const [name, member2] of ns.structIterator()) { + if (dataObject[name] != null) { + output[name] = this.codec.createDeserializer().readObject(member2, dataObject[name]); + } + } + if (this.awsQueryCompatible) { + this.mixin.queryCompatOutput(dataObject, output); + } + throw this.mixin.decorateServiceException(Object.assign(exception, errorMetadata, { + $fault: ns.getMergedTraits().error, + message: message2 + }, output), dataObject); + } + }; + } +}); + +// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/AwsJson1_0Protocol.js +var AwsJson1_0Protocol; +var init_AwsJson1_0Protocol = __esm({ + "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/AwsJson1_0Protocol.js"() { + init_AwsJsonRpcProtocol(); + AwsJson1_0Protocol = class extends AwsJsonRpcProtocol { + constructor({ defaultNamespace, errorTypeRegistries: errorTypeRegistries5, serviceTarget, awsQueryCompatible, jsonCodec }) { + super({ + defaultNamespace, + errorTypeRegistries: errorTypeRegistries5, + serviceTarget, + awsQueryCompatible, + jsonCodec + }); + } + getShapeId() { + return "aws.protocols#awsJson1_0"; + } + getJsonRpcVersion() { + return "1.0"; + } + getDefaultContentType() { + return "application/x-amz-json-1.0"; + } + }; + } +}); + +// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/AwsJson1_1Protocol.js +var AwsJson1_1Protocol; +var init_AwsJson1_1Protocol = __esm({ + "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/AwsJson1_1Protocol.js"() { + init_AwsJsonRpcProtocol(); + AwsJson1_1Protocol = class extends AwsJsonRpcProtocol { + constructor({ defaultNamespace, errorTypeRegistries: errorTypeRegistries5, serviceTarget, awsQueryCompatible, jsonCodec }) { + super({ + defaultNamespace, + errorTypeRegistries: errorTypeRegistries5, + serviceTarget, + awsQueryCompatible, + jsonCodec + }); + } + getShapeId() { + return "aws.protocols#awsJson1_1"; + } + getJsonRpcVersion() { + return "1.1"; + } + getDefaultContentType() { + return "application/x-amz-json-1.1"; + } + }; + } +}); + +// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/AwsRestJsonProtocol.js +var AwsRestJsonProtocol; +var init_AwsRestJsonProtocol = __esm({ + "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/AwsRestJsonProtocol.js"() { + init_protocols(); + init_schema3(); + init_ProtocolLib(); + init_JsonCodec(); + init_parseJsonBody(); + AwsRestJsonProtocol = class extends HttpBindingProtocol { + serializer; + deserializer; + codec; + mixin = new ProtocolLib(); + constructor({ defaultNamespace, errorTypeRegistries: errorTypeRegistries5 }) { + super({ + defaultNamespace, + errorTypeRegistries: errorTypeRegistries5 + }); + const settings = { + timestampFormat: { + useTrait: true, + default: 7 + }, + httpBindings: true, + jsonName: true + }; + this.codec = new JsonCodec(settings); + this.serializer = new HttpInterceptingShapeSerializer(this.codec.createSerializer(), settings); + this.deserializer = new HttpInterceptingShapeDeserializer(this.codec.createDeserializer(), settings); + } + getShapeId() { + return "aws.protocols#restJson1"; + } + getPayloadCodec() { + return this.codec; + } + setSerdeContext(serdeContext) { + this.codec.setSerdeContext(serdeContext); + super.setSerdeContext(serdeContext); + } + async serializeRequest(operationSchema, input, context) { + const request = await super.serializeRequest(operationSchema, input, context); + const inputSchema = NormalizedSchema.of(operationSchema.input); + if (!request.headers["content-type"]) { + const contentType = this.mixin.resolveRestContentType(this.getDefaultContentType(), inputSchema); + if (contentType) { + request.headers["content-type"] = contentType; + } + } + if (request.body == null && request.headers["content-type"] === this.getDefaultContentType()) { + request.body = "{}"; + } + return request; + } + async deserializeResponse(operationSchema, context, response) { + const output = await super.deserializeResponse(operationSchema, context, response); + const outputSchema = NormalizedSchema.of(operationSchema.output); + for (const [name, member2] of outputSchema.structIterator()) { + if (member2.getMemberTraits().httpPayload && !(name in output)) { + output[name] = null; + } + } + return output; + } + async handleError(operationSchema, context, response, dataObject, metadata) { + const errorIdentifier = loadRestJsonErrorCode(response, dataObject) ?? "Unknown"; + this.mixin.compose(this.compositeErrorRegistry, errorIdentifier, this.options.defaultNamespace); + const { errorSchema, errorMetadata } = await this.mixin.getErrorSchemaOrThrowBaseException(errorIdentifier, this.options.defaultNamespace, response, dataObject, metadata); + const ns = NormalizedSchema.of(errorSchema); + const message2 = dataObject.message ?? dataObject.Message ?? "UnknownError"; + const ErrorCtor = this.compositeErrorRegistry.getErrorCtor(errorSchema) ?? Error; + const exception = new ErrorCtor(message2); + await this.deserializeHttpMessage(errorSchema, context, response, dataObject); + const output = {}; + for (const [name, member2] of ns.structIterator()) { + const target = member2.getMergedTraits().jsonName ?? name; + output[name] = this.codec.createDeserializer().readObject(member2, dataObject[target]); + } + throw this.mixin.decorateServiceException(Object.assign(exception, errorMetadata, { + $fault: ns.getMergedTraits().error, + message: message2 + }, output), dataObject); + } + getDefaultContentType() { + return "application/json"; + } + }; + } +}); + +// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/awsExpectUnion.js +var import_smithy_client3, awsExpectUnion; +var init_awsExpectUnion = __esm({ + "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/awsExpectUnion.js"() { + import_smithy_client3 = __toESM(require_dist_cjs27()); + awsExpectUnion = (value) => { + if (value == null) { + return void 0; + } + if (typeof value === "object" && "__type" in value) { + delete value.__type; + } + return (0, import_smithy_client3.expectUnion)(value); + }; + } +}); + +// node_modules/.pnpm/fast-xml-parser@5.5.8/node_modules/fast-xml-parser/lib/fxp.cjs +var require_fxp = __commonJS({ + "node_modules/.pnpm/fast-xml-parser@5.5.8/node_modules/fast-xml-parser/lib/fxp.cjs"(exports, module) { + (() => { + "use strict"; + var t5 = { d: (e6, i6) => { + for (var n6 in i6) t5.o(i6, n6) && !t5.o(e6, n6) && Object.defineProperty(e6, n6, { enumerable: true, get: i6[n6] }); + }, o: (t6, e6) => Object.prototype.hasOwnProperty.call(t6, e6), r: (t6) => { + "undefined" != typeof Symbol && Symbol.toStringTag && Object.defineProperty(t6, Symbol.toStringTag, { value: "Module" }), Object.defineProperty(t6, "__esModule", { value: true }); + } }, e5 = {}; + t5.r(e5), t5.d(e5, { XMLBuilder: () => $t, XMLParser: () => gt2, XMLValidator: () => It }); + const i5 = ":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD", n5 = new RegExp("^[" + i5 + "][" + i5 + "\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*$"); + function s5(t6, e6) { + const i6 = []; + let n6 = e6.exec(t6); + for (; n6; ) { + const s6 = []; + s6.startIndex = e6.lastIndex - n6[0].length; + const r6 = n6.length; + for (let t7 = 0; t7 < r6; t7++) s6.push(n6[t7]); + i6.push(s6), n6 = e6.exec(t6); + } + return i6; + } + const r5 = function(t6) { + return !(null == n5.exec(t6)); + }, o5 = ["hasOwnProperty", "toString", "valueOf", "__defineGetter__", "__defineSetter__", "__lookupGetter__", "__lookupSetter__"], a5 = ["__proto__", "constructor", "prototype"], h5 = { allowBooleanAttributes: false, unpairedTags: [] }; + function l5(t6, e6) { + e6 = Object.assign({}, h5, e6); + const i6 = []; + let n6 = false, s6 = false; + "\uFEFF" === t6[0] && (t6 = t6.substr(1)); + for (let r6 = 0; r6 < t6.length; r6++) if ("<" === t6[r6] && "?" === t6[r6 + 1]) { + if (r6 += 2, r6 = u5(t6, r6), r6.err) return r6; + } else { + if ("<" !== t6[r6]) { + if (p5(t6[r6])) continue; + return b6("InvalidChar", "char '" + t6[r6] + "' is not expected.", w5(t6, r6)); + } + { + let o6 = r6; + if (r6++, "!" === t6[r6]) { + r6 = c5(t6, r6); + continue; + } + { + let a6 = false; + "/" === t6[r6] && (a6 = true, r6++); + let h6 = ""; + for (; r6 < t6.length && ">" !== t6[r6] && " " !== t6[r6] && " " !== t6[r6] && "\n" !== t6[r6] && "\r" !== t6[r6]; r6++) h6 += t6[r6]; + if (h6 = h6.trim(), "/" === h6[h6.length - 1] && (h6 = h6.substring(0, h6.length - 1), r6--), !y2(h6)) { + let e7; + return e7 = 0 === h6.trim().length ? "Invalid space after '<'." : "Tag '" + h6 + "' is an invalid name.", b6("InvalidTag", e7, w5(t6, r6)); + } + const l6 = g5(t6, r6); + if (false === l6) return b6("InvalidAttr", "Attributes for '" + h6 + "' have open quote.", w5(t6, r6)); + let d6 = l6.value; + if (r6 = l6.index, "/" === d6[d6.length - 1]) { + const i7 = r6 - d6.length; + d6 = d6.substring(0, d6.length - 1); + const s7 = x5(d6, e6); + if (true !== s7) return b6(s7.err.code, s7.err.msg, w5(t6, i7 + s7.err.line)); + n6 = true; + } else if (a6) { + if (!l6.tagClosed) return b6("InvalidTag", "Closing tag '" + h6 + "' doesn't have proper closing.", w5(t6, r6)); + if (d6.trim().length > 0) return b6("InvalidTag", "Closing tag '" + h6 + "' can't have attributes or invalid starting.", w5(t6, o6)); + if (0 === i6.length) return b6("InvalidTag", "Closing tag '" + h6 + "' has not been opened.", w5(t6, o6)); + { + const e7 = i6.pop(); + if (h6 !== e7.tagName) { + let i7 = w5(t6, e7.tagStartPos); + return b6("InvalidTag", "Expected closing tag '" + e7.tagName + "' (opened in line " + i7.line + ", col " + i7.col + ") instead of closing tag '" + h6 + "'.", w5(t6, o6)); + } + 0 == i6.length && (s6 = true); + } + } else { + const a7 = x5(d6, e6); + if (true !== a7) return b6(a7.err.code, a7.err.msg, w5(t6, r6 - d6.length + a7.err.line)); + if (true === s6) return b6("InvalidXml", "Multiple possible root nodes found.", w5(t6, r6)); + -1 !== e6.unpairedTags.indexOf(h6) || i6.push({ tagName: h6, tagStartPos: o6 }), n6 = true; + } + for (r6++; r6 < t6.length; r6++) if ("<" === t6[r6]) { + if ("!" === t6[r6 + 1]) { + r6++, r6 = c5(t6, r6); + continue; + } + if ("?" !== t6[r6 + 1]) break; + if (r6 = u5(t6, ++r6), r6.err) return r6; + } else if ("&" === t6[r6]) { + const e7 = N(t6, r6); + if (-1 == e7) return b6("InvalidChar", "char '&' is not expected.", w5(t6, r6)); + r6 = e7; + } else if (true === s6 && !p5(t6[r6])) return b6("InvalidXml", "Extra text at the end", w5(t6, r6)); + "<" === t6[r6] && r6--; + } + } + } + return n6 ? 1 == i6.length ? b6("InvalidTag", "Unclosed tag '" + i6[0].tagName + "'.", w5(t6, i6[0].tagStartPos)) : !(i6.length > 0) || b6("InvalidXml", "Invalid '" + JSON.stringify(i6.map((t7) => t7.tagName), null, 4).replace(/\r?\n/g, "") + "' found.", { line: 1, col: 1 }) : b6("InvalidXml", "Start tag expected.", 1); + } + function p5(t6) { + return " " === t6 || " " === t6 || "\n" === t6 || "\r" === t6; + } + function u5(t6, e6) { + const i6 = e6; + for (; e6 < t6.length; e6++) if ("?" == t6[e6] || " " == t6[e6]) { + const n6 = t6.substr(i6, e6 - i6); + if (e6 > 5 && "xml" === n6) return b6("InvalidXml", "XML declaration allowed only at the start of the document.", w5(t6, e6)); + if ("?" == t6[e6] && ">" == t6[e6 + 1]) { + e6++; + break; + } + continue; + } + return e6; + } + function c5(t6, e6) { + if (t6.length > e6 + 5 && "-" === t6[e6 + 1] && "-" === t6[e6 + 2]) { + for (e6 += 3; e6 < t6.length; e6++) if ("-" === t6[e6] && "-" === t6[e6 + 1] && ">" === t6[e6 + 2]) { + e6 += 2; + break; + } + } else if (t6.length > e6 + 8 && "D" === t6[e6 + 1] && "O" === t6[e6 + 2] && "C" === t6[e6 + 3] && "T" === t6[e6 + 4] && "Y" === t6[e6 + 5] && "P" === t6[e6 + 6] && "E" === t6[e6 + 7]) { + let i6 = 1; + for (e6 += 8; e6 < t6.length; e6++) if ("<" === t6[e6]) i6++; + else if (">" === t6[e6] && (i6--, 0 === i6)) break; + } else if (t6.length > e6 + 9 && "[" === t6[e6 + 1] && "C" === t6[e6 + 2] && "D" === t6[e6 + 3] && "A" === t6[e6 + 4] && "T" === t6[e6 + 5] && "A" === t6[e6 + 6] && "[" === t6[e6 + 7]) { + for (e6 += 8; e6 < t6.length; e6++) if ("]" === t6[e6] && "]" === t6[e6 + 1] && ">" === t6[e6 + 2]) { + e6 += 2; + break; + } + } + return e6; + } + const d5 = '"', f5 = "'"; + function g5(t6, e6) { + let i6 = "", n6 = "", s6 = false; + for (; e6 < t6.length; e6++) { + if (t6[e6] === d5 || t6[e6] === f5) "" === n6 ? n6 = t6[e6] : n6 !== t6[e6] || (n6 = ""); + else if (">" === t6[e6] && "" === n6) { + s6 = true; + break; + } + i6 += t6[e6]; + } + return "" === n6 && { value: i6, index: e6, tagClosed: s6 }; + } + const m5 = new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`, "g"); + function x5(t6, e6) { + const i6 = s5(t6, m5), n6 = {}; + for (let t7 = 0; t7 < i6.length; t7++) { + if (0 === i6[t7][1].length) return b6("InvalidAttr", "Attribute '" + i6[t7][2] + "' has no space in starting.", v5(i6[t7])); + if (void 0 !== i6[t7][3] && void 0 === i6[t7][4]) return b6("InvalidAttr", "Attribute '" + i6[t7][2] + "' is without value.", v5(i6[t7])); + if (void 0 === i6[t7][3] && !e6.allowBooleanAttributes) return b6("InvalidAttr", "boolean attribute '" + i6[t7][2] + "' is not allowed.", v5(i6[t7])); + const s6 = i6[t7][2]; + if (!E2(s6)) return b6("InvalidAttr", "Attribute '" + s6 + "' is an invalid name.", v5(i6[t7])); + if (Object.prototype.hasOwnProperty.call(n6, s6)) return b6("InvalidAttr", "Attribute '" + s6 + "' is repeated.", v5(i6[t7])); + n6[s6] = 1; + } + return true; + } + function N(t6, e6) { + if (";" === t6[++e6]) return -1; + if ("#" === t6[e6]) return (function(t7, e7) { + let i7 = /\d/; + for ("x" === t7[e7] && (e7++, i7 = /[\da-fA-F]/); e7 < t7.length; e7++) { + if (";" === t7[e7]) return e7; + if (!t7[e7].match(i7)) break; + } + return -1; + })(t6, ++e6); + let i6 = 0; + for (; e6 < t6.length; e6++, i6++) if (!(t6[e6].match(/\w/) && i6 < 20)) { + if (";" === t6[e6]) break; + return -1; + } + return e6; + } + function b6(t6, e6, i6) { + return { err: { code: t6, msg: e6, line: i6.line || i6, col: i6.col } }; + } + function E2(t6) { + return r5(t6); + } + function y2(t6) { + return r5(t6); + } + function w5(t6, e6) { + const i6 = t6.substring(0, e6).split(/\r?\n/); + return { line: i6.length, col: i6[i6.length - 1].length + 1 }; + } + function v5(t6) { + return t6.startIndex + t6[1].length; + } + const T = (t6) => o5.includes(t6) ? "__" + t6 : t6, P = { preserveOrder: false, attributeNamePrefix: "@_", attributesGroupName: false, textNodeName: "#text", ignoreAttributes: true, removeNSPrefix: false, allowBooleanAttributes: false, parseTagValue: true, parseAttributeValue: false, trimValues: true, cdataPropName: false, numberParseOptions: { hex: true, leadingZeros: true, eNotation: true }, tagValueProcessor: function(t6, e6) { + return e6; + }, attributeValueProcessor: function(t6, e6) { + return e6; + }, stopNodes: [], alwaysCreateTextNode: false, isArray: () => false, commentPropName: false, unpairedTags: [], processEntities: true, htmlEntities: false, ignoreDeclaration: false, ignorePiTags: false, transformTagName: false, transformAttributeName: false, updateTag: function(t6, e6, i6) { + return t6; + }, captureMetaData: false, maxNestedTags: 100, strictReservedNames: true, jPath: true, onDangerousProperty: T }; + function S(t6, e6) { + if ("string" != typeof t6) return; + const i6 = t6.toLowerCase(); + if (o5.some((t7) => i6 === t7.toLowerCase())) throw new Error(`[SECURITY] Invalid ${e6}: "${t6}" is a reserved JavaScript keyword that could cause prototype pollution`); + if (a5.some((t7) => i6 === t7.toLowerCase())) throw new Error(`[SECURITY] Invalid ${e6}: "${t6}" is a reserved JavaScript keyword that could cause prototype pollution`); + } + function A2(t6) { + return "boolean" == typeof t6 ? { enabled: t6, maxEntitySize: 1e4, maxExpansionDepth: 10, maxTotalExpansions: 1e3, maxExpandedLength: 1e5, maxEntityCount: 100, allowedTags: null, tagFilter: null } : "object" == typeof t6 && null !== t6 ? { enabled: false !== t6.enabled, maxEntitySize: Math.max(1, t6.maxEntitySize ?? 1e4), maxExpansionDepth: Math.max(1, t6.maxExpansionDepth ?? 10), maxTotalExpansions: Math.max(1, t6.maxTotalExpansions ?? 1e3), maxExpandedLength: Math.max(1, t6.maxExpandedLength ?? 1e5), maxEntityCount: Math.max(1, t6.maxEntityCount ?? 100), allowedTags: t6.allowedTags ?? null, tagFilter: t6.tagFilter ?? null } : A2(true); + } + const O = function(t6) { + const e6 = Object.assign({}, P, t6), i6 = [{ value: e6.attributeNamePrefix, name: "attributeNamePrefix" }, { value: e6.attributesGroupName, name: "attributesGroupName" }, { value: e6.textNodeName, name: "textNodeName" }, { value: e6.cdataPropName, name: "cdataPropName" }, { value: e6.commentPropName, name: "commentPropName" }]; + for (const { value: t7, name: e7 } of i6) t7 && S(t7, e7); + return null === e6.onDangerousProperty && (e6.onDangerousProperty = T), e6.processEntities = A2(e6.processEntities), e6.stopNodes && Array.isArray(e6.stopNodes) && (e6.stopNodes = e6.stopNodes.map((t7) => "string" == typeof t7 && t7.startsWith("*.") ? ".." + t7.substring(2) : t7)), e6; + }; + let C2; + C2 = "function" != typeof Symbol ? "@@xmlMetadata" : /* @__PURE__ */ Symbol("XML Node Metadata"); + class $ { + constructor(t6) { + this.tagname = t6, this.child = [], this[":@"] = /* @__PURE__ */ Object.create(null); + } + add(t6, e6) { + "__proto__" === t6 && (t6 = "#__proto__"), this.child.push({ [t6]: e6 }); + } + addChild(t6, e6) { + "__proto__" === t6.tagname && (t6.tagname = "#__proto__"), t6[":@"] && Object.keys(t6[":@"]).length > 0 ? this.child.push({ [t6.tagname]: t6.child, ":@": t6[":@"] }) : this.child.push({ [t6.tagname]: t6.child }), void 0 !== e6 && (this.child[this.child.length - 1][C2] = { startIndex: e6 }); + } + static getMetaDataSymbol() { + return C2; + } + } + class I2 { + constructor(t6) { + this.suppressValidationErr = !t6, this.options = t6; + } + readDocType(t6, e6) { + const i6 = /* @__PURE__ */ Object.create(null); + let n6 = 0; + if ("O" !== t6[e6 + 3] || "C" !== t6[e6 + 4] || "T" !== t6[e6 + 5] || "Y" !== t6[e6 + 6] || "P" !== t6[e6 + 7] || "E" !== t6[e6 + 8]) throw new Error("Invalid Tag instead of DOCTYPE"); + { + e6 += 9; + let s6 = 1, r6 = false, o6 = false, a6 = ""; + for (; e6 < t6.length; e6++) if ("<" !== t6[e6] || o6) if (">" === t6[e6]) { + if (o6 ? "-" === t6[e6 - 1] && "-" === t6[e6 - 2] && (o6 = false, s6--) : s6--, 0 === s6) break; + } else "[" === t6[e6] ? r6 = true : a6 += t6[e6]; + else { + if (r6 && M(t6, "!ENTITY", e6)) { + let s7, r7; + if (e6 += 7, [s7, r7, e6] = this.readEntityExp(t6, e6 + 1, this.suppressValidationErr), -1 === r7.indexOf("&")) { + if (false !== this.options.enabled && null != this.options.maxEntityCount && n6 >= this.options.maxEntityCount) throw new Error(`Entity count (${n6 + 1}) exceeds maximum allowed (${this.options.maxEntityCount})`); + const t7 = s7.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + i6[s7] = { regx: RegExp(`&${t7};`, "g"), val: r7 }, n6++; + } + } else if (r6 && M(t6, "!ELEMENT", e6)) { + e6 += 8; + const { index: i7 } = this.readElementExp(t6, e6 + 1); + e6 = i7; + } else if (r6 && M(t6, "!ATTLIST", e6)) e6 += 8; + else if (r6 && M(t6, "!NOTATION", e6)) { + e6 += 9; + const { index: i7 } = this.readNotationExp(t6, e6 + 1, this.suppressValidationErr); + e6 = i7; + } else { + if (!M(t6, "!--", e6)) throw new Error("Invalid DOCTYPE"); + o6 = true; + } + s6++, a6 = ""; + } + if (0 !== s6) throw new Error("Unclosed DOCTYPE"); + } + return { entities: i6, i: e6 }; + } + readEntityExp(t6, e6) { + const i6 = e6 = j5(t6, e6); + for (; e6 < t6.length && !/\s/.test(t6[e6]) && '"' !== t6[e6] && "'" !== t6[e6]; ) e6++; + let n6 = t6.substring(i6, e6); + if (_(n6), e6 = j5(t6, e6), !this.suppressValidationErr) { + if ("SYSTEM" === t6.substring(e6, e6 + 6).toUpperCase()) throw new Error("External entities are not supported"); + if ("%" === t6[e6]) throw new Error("Parameter entities are not supported"); + } + let s6 = ""; + if ([e6, s6] = this.readIdentifierVal(t6, e6, "entity"), false !== this.options.enabled && null != this.options.maxEntitySize && s6.length > this.options.maxEntitySize) throw new Error(`Entity "${n6}" size (${s6.length}) exceeds maximum allowed size (${this.options.maxEntitySize})`); + return [n6, s6, --e6]; + } + readNotationExp(t6, e6) { + const i6 = e6 = j5(t6, e6); + for (; e6 < t6.length && !/\s/.test(t6[e6]); ) e6++; + let n6 = t6.substring(i6, e6); + !this.suppressValidationErr && _(n6), e6 = j5(t6, e6); + const s6 = t6.substring(e6, e6 + 6).toUpperCase(); + if (!this.suppressValidationErr && "SYSTEM" !== s6 && "PUBLIC" !== s6) throw new Error(`Expected SYSTEM or PUBLIC, found "${s6}"`); + e6 += s6.length, e6 = j5(t6, e6); + let r6 = null, o6 = null; + if ("PUBLIC" === s6) [e6, r6] = this.readIdentifierVal(t6, e6, "publicIdentifier"), '"' !== t6[e6 = j5(t6, e6)] && "'" !== t6[e6] || ([e6, o6] = this.readIdentifierVal(t6, e6, "systemIdentifier")); + else if ("SYSTEM" === s6 && ([e6, o6] = this.readIdentifierVal(t6, e6, "systemIdentifier"), !this.suppressValidationErr && !o6)) throw new Error("Missing mandatory system identifier for SYSTEM notation"); + return { notationName: n6, publicIdentifier: r6, systemIdentifier: o6, index: --e6 }; + } + readIdentifierVal(t6, e6, i6) { + let n6 = ""; + const s6 = t6[e6]; + if ('"' !== s6 && "'" !== s6) throw new Error(`Expected quoted string, found "${s6}"`); + const r6 = ++e6; + for (; e6 < t6.length && t6[e6] !== s6; ) e6++; + if (n6 = t6.substring(r6, e6), t6[e6] !== s6) throw new Error(`Unterminated ${i6} value`); + return [++e6, n6]; + } + readElementExp(t6, e6) { + const i6 = e6 = j5(t6, e6); + for (; e6 < t6.length && !/\s/.test(t6[e6]); ) e6++; + let n6 = t6.substring(i6, e6); + if (!this.suppressValidationErr && !r5(n6)) throw new Error(`Invalid element name: "${n6}"`); + let s6 = ""; + if ("E" === t6[e6 = j5(t6, e6)] && M(t6, "MPTY", e6)) e6 += 4; + else if ("A" === t6[e6] && M(t6, "NY", e6)) e6 += 2; + else if ("(" === t6[e6]) { + const i7 = ++e6; + for (; e6 < t6.length && ")" !== t6[e6]; ) e6++; + if (s6 = t6.substring(i7, e6), ")" !== t6[e6]) throw new Error("Unterminated content model"); + } else if (!this.suppressValidationErr) throw new Error(`Invalid Element Expression, found "${t6[e6]}"`); + return { elementName: n6, contentModel: s6.trim(), index: e6 }; + } + readAttlistExp(t6, e6) { + let i6 = e6 = j5(t6, e6); + for (; e6 < t6.length && !/\s/.test(t6[e6]); ) e6++; + let n6 = t6.substring(i6, e6); + for (_(n6), i6 = e6 = j5(t6, e6); e6 < t6.length && !/\s/.test(t6[e6]); ) e6++; + let s6 = t6.substring(i6, e6); + if (!_(s6)) throw new Error(`Invalid attribute name: "${s6}"`); + e6 = j5(t6, e6); + let r6 = ""; + if ("NOTATION" === t6.substring(e6, e6 + 8).toUpperCase()) { + if (r6 = "NOTATION", "(" !== t6[e6 = j5(t6, e6 += 8)]) throw new Error(`Expected '(', found "${t6[e6]}"`); + e6++; + let i7 = []; + for (; e6 < t6.length && ")" !== t6[e6]; ) { + const n7 = e6; + for (; e6 < t6.length && "|" !== t6[e6] && ")" !== t6[e6]; ) e6++; + let s7 = t6.substring(n7, e6); + if (s7 = s7.trim(), !_(s7)) throw new Error(`Invalid notation name: "${s7}"`); + i7.push(s7), "|" === t6[e6] && (e6++, e6 = j5(t6, e6)); + } + if (")" !== t6[e6]) throw new Error("Unterminated list of notations"); + e6++, r6 += " (" + i7.join("|") + ")"; + } else { + const i7 = e6; + for (; e6 < t6.length && !/\s/.test(t6[e6]); ) e6++; + r6 += t6.substring(i7, e6); + const n7 = ["CDATA", "ID", "IDREF", "IDREFS", "ENTITY", "ENTITIES", "NMTOKEN", "NMTOKENS"]; + if (!this.suppressValidationErr && !n7.includes(r6.toUpperCase())) throw new Error(`Invalid attribute type: "${r6}"`); + } + e6 = j5(t6, e6); + let o6 = ""; + return "#REQUIRED" === t6.substring(e6, e6 + 8).toUpperCase() ? (o6 = "#REQUIRED", e6 += 8) : "#IMPLIED" === t6.substring(e6, e6 + 7).toUpperCase() ? (o6 = "#IMPLIED", e6 += 7) : [e6, o6] = this.readIdentifierVal(t6, e6, "ATTLIST"), { elementName: n6, attributeName: s6, attributeType: r6, defaultValue: o6, index: e6 }; + } + } + const j5 = (t6, e6) => { + for (; e6 < t6.length && /\s/.test(t6[e6]); ) e6++; + return e6; + }; + function M(t6, e6, i6) { + for (let n6 = 0; n6 < e6.length; n6++) if (e6[n6] !== t6[i6 + n6 + 1]) return false; + return true; + } + function _(t6) { + if (r5(t6)) return t6; + throw new Error(`Invalid entity name ${t6}`); + } + const D2 = /^[-+]?0x[a-fA-F0-9]+$/, V = /^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/, k5 = { hex: true, leadingZeros: true, decimalPoint: ".", eNotation: true, infinity: "original" }; + const F2 = /^([-+])?(0*)(\d*(\.\d*)?[eE][-\+]?\d+)$/, L = /* @__PURE__ */ new Set(["push", "pop", "reset", "updateCurrent", "restore"]); + class G2 { + constructor(t6 = {}) { + this.separator = t6.separator || ".", this.path = [], this.siblingStacks = []; + } + push(t6, e6 = null, i6 = null) { + this.path.length > 0 && (this.path[this.path.length - 1].values = void 0); + const n6 = this.path.length; + this.siblingStacks[n6] || (this.siblingStacks[n6] = /* @__PURE__ */ new Map()); + const s6 = this.siblingStacks[n6], r6 = i6 ? `${i6}:${t6}` : t6, o6 = s6.get(r6) || 0; + let a6 = 0; + for (const t7 of s6.values()) a6 += t7; + s6.set(r6, o6 + 1); + const h6 = { tag: t6, position: a6, counter: o6 }; + null != i6 && (h6.namespace = i6), null != e6 && (h6.values = e6), this.path.push(h6); + } + pop() { + if (0 === this.path.length) return; + const t6 = this.path.pop(); + return this.siblingStacks.length > this.path.length + 1 && (this.siblingStacks.length = this.path.length + 1), t6; + } + updateCurrent(t6) { + if (this.path.length > 0) { + const e6 = this.path[this.path.length - 1]; + null != t6 && (e6.values = t6); + } + } + getCurrentTag() { + return this.path.length > 0 ? this.path[this.path.length - 1].tag : void 0; + } + getCurrentNamespace() { + return this.path.length > 0 ? this.path[this.path.length - 1].namespace : void 0; + } + getAttrValue(t6) { + if (0 === this.path.length) return; + const e6 = this.path[this.path.length - 1]; + return e6.values?.[t6]; + } + hasAttr(t6) { + if (0 === this.path.length) return false; + const e6 = this.path[this.path.length - 1]; + return void 0 !== e6.values && t6 in e6.values; + } + getPosition() { + return 0 === this.path.length ? -1 : this.path[this.path.length - 1].position ?? 0; + } + getCounter() { + return 0 === this.path.length ? -1 : this.path[this.path.length - 1].counter ?? 0; + } + getIndex() { + return this.getPosition(); + } + getDepth() { + return this.path.length; + } + toString(t6, e6 = true) { + const i6 = t6 || this.separator; + return this.path.map((t7) => e6 && t7.namespace ? `${t7.namespace}:${t7.tag}` : t7.tag).join(i6); + } + toArray() { + return this.path.map((t6) => t6.tag); + } + reset() { + this.path = [], this.siblingStacks = []; + } + matches(t6) { + const e6 = t6.segments; + return 0 !== e6.length && (t6.hasDeepWildcard() ? this._matchWithDeepWildcard(e6) : this._matchSimple(e6)); + } + _matchSimple(t6) { + if (this.path.length !== t6.length) return false; + for (let e6 = 0; e6 < t6.length; e6++) { + const i6 = t6[e6], n6 = this.path[e6], s6 = e6 === this.path.length - 1; + if (!this._matchSegment(i6, n6, s6)) return false; + } + return true; + } + _matchWithDeepWildcard(t6) { + let e6 = this.path.length - 1, i6 = t6.length - 1; + for (; i6 >= 0 && e6 >= 0; ) { + const n6 = t6[i6]; + if ("deep-wildcard" === n6.type) { + if (i6--, i6 < 0) return true; + const n7 = t6[i6]; + let s6 = false; + for (let t7 = e6; t7 >= 0; t7--) { + const r6 = t7 === this.path.length - 1; + if (this._matchSegment(n7, this.path[t7], r6)) { + e6 = t7 - 1, i6--, s6 = true; + break; + } + } + if (!s6) return false; + } else { + const t7 = e6 === this.path.length - 1; + if (!this._matchSegment(n6, this.path[e6], t7)) return false; + e6--, i6--; + } + } + return i6 < 0; + } + _matchSegment(t6, e6, i6) { + if ("*" !== t6.tag && t6.tag !== e6.tag) return false; + if (void 0 !== t6.namespace && "*" !== t6.namespace && t6.namespace !== e6.namespace) return false; + if (void 0 !== t6.attrName) { + if (!i6) return false; + if (!e6.values || !(t6.attrName in e6.values)) return false; + if (void 0 !== t6.attrValue) { + const i7 = e6.values[t6.attrName]; + if (String(i7) !== String(t6.attrValue)) return false; + } + } + if (void 0 !== t6.position) { + if (!i6) return false; + const n6 = e6.counter ?? 0; + if ("first" === t6.position && 0 !== n6) return false; + if ("odd" === t6.position && n6 % 2 != 1) return false; + if ("even" === t6.position && n6 % 2 != 0) return false; + if ("nth" === t6.position && n6 !== t6.positionValue) return false; + } + return true; + } + snapshot() { + return { path: this.path.map((t6) => ({ ...t6 })), siblingStacks: this.siblingStacks.map((t6) => new Map(t6)) }; + } + restore(t6) { + this.path = t6.path.map((t7) => ({ ...t7 })), this.siblingStacks = t6.siblingStacks.map((t7) => new Map(t7)); + } + readOnly() { + return new Proxy(this, { get(t6, e6, i6) { + if (L.has(e6)) return () => { + throw new TypeError(`Cannot call '${e6}' on a read-only Matcher. Obtain a writable instance to mutate state.`); + }; + const n6 = Reflect.get(t6, e6, i6); + return "path" === e6 || "siblingStacks" === e6 ? Object.freeze(Array.isArray(n6) ? n6.map((t7) => t7 instanceof Map ? Object.freeze(new Map(t7)) : Object.freeze({ ...t7 })) : n6) : "function" == typeof n6 ? n6.bind(t6) : n6; + }, set(t6, e6) { + throw new TypeError(`Cannot set property '${String(e6)}' on a read-only Matcher.`); + }, deleteProperty(t6, e6) { + throw new TypeError(`Cannot delete property '${String(e6)}' from a read-only Matcher.`); + } }); + } + } + class R { + constructor(t6, e6 = {}) { + this.pattern = t6, this.separator = e6.separator || ".", this.segments = this._parse(t6), this._hasDeepWildcard = this.segments.some((t7) => "deep-wildcard" === t7.type), this._hasAttributeCondition = this.segments.some((t7) => void 0 !== t7.attrName), this._hasPositionSelector = this.segments.some((t7) => void 0 !== t7.position); + } + _parse(t6) { + const e6 = []; + let i6 = 0, n6 = ""; + for (; i6 < t6.length; ) t6[i6] === this.separator ? i6 + 1 < t6.length && t6[i6 + 1] === this.separator ? (n6.trim() && (e6.push(this._parseSegment(n6.trim())), n6 = ""), e6.push({ type: "deep-wildcard" }), i6 += 2) : (n6.trim() && e6.push(this._parseSegment(n6.trim())), n6 = "", i6++) : (n6 += t6[i6], i6++); + return n6.trim() && e6.push(this._parseSegment(n6.trim())), e6; + } + _parseSegment(t6) { + const e6 = { type: "tag" }; + let i6 = null, n6 = t6; + const s6 = t6.match(/^([^\[]+)(\[[^\]]*\])(.*)$/); + if (s6 && (n6 = s6[1] + s6[3], s6[2])) { + const t7 = s6[2].slice(1, -1); + t7 && (i6 = t7); + } + let r6, o6, a6 = n6; + if (n6.includes("::")) { + const e7 = n6.indexOf("::"); + if (r6 = n6.substring(0, e7).trim(), a6 = n6.substring(e7 + 2).trim(), !r6) throw new Error(`Invalid namespace in pattern: ${t6}`); + } + let h6 = null; + if (a6.includes(":")) { + const t7 = a6.lastIndexOf(":"), e7 = a6.substring(0, t7).trim(), i7 = a6.substring(t7 + 1).trim(); + ["first", "last", "odd", "even"].includes(i7) || /^nth\(\d+\)$/.test(i7) ? (o6 = e7, h6 = i7) : o6 = a6; + } else o6 = a6; + if (!o6) throw new Error(`Invalid segment pattern: ${t6}`); + if (e6.tag = o6, r6 && (e6.namespace = r6), i6) if (i6.includes("=")) { + const t7 = i6.indexOf("="); + e6.attrName = i6.substring(0, t7).trim(), e6.attrValue = i6.substring(t7 + 1).trim(); + } else e6.attrName = i6.trim(); + if (h6) { + const t7 = h6.match(/^nth\((\d+)\)$/); + t7 ? (e6.position = "nth", e6.positionValue = parseInt(t7[1], 10)) : e6.position = h6; + } + return e6; + } + get length() { + return this.segments.length; + } + hasDeepWildcard() { + return this._hasDeepWildcard; + } + hasAttributeCondition() { + return this._hasAttributeCondition; + } + hasPositionSelector() { + return this._hasPositionSelector; + } + toString() { + return this.pattern; + } + } + function U(t6, e6) { + if (!t6) return {}; + const i6 = e6.attributesGroupName ? t6[e6.attributesGroupName] : t6; + if (!i6) return {}; + const n6 = {}; + for (const t7 in i6) t7.startsWith(e6.attributeNamePrefix) ? n6[t7.substring(e6.attributeNamePrefix.length)] = i6[t7] : n6[t7] = i6[t7]; + return n6; + } + function B2(t6) { + if (!t6 || "string" != typeof t6) return; + const e6 = t6.indexOf(":"); + if (-1 !== e6 && e6 > 0) { + const i6 = t6.substring(0, e6); + if ("xmlns" !== i6) return i6; + } + } + class W { + constructor(t6) { + var e6; + if (this.options = t6, this.currentNode = null, this.tagsNodeStack = [], this.docTypeEntities = {}, this.lastEntities = { apos: { regex: /&(apos|#39|#x27);/g, val: "'" }, gt: { regex: /&(gt|#62|#x3E);/g, val: ">" }, lt: { regex: /&(lt|#60|#x3C);/g, val: "<" }, quot: { regex: /&(quot|#34|#x22);/g, val: '"' } }, this.ampEntity = { regex: /&(amp|#38|#x26);/g, val: "&" }, this.htmlEntities = { space: { regex: /&(nbsp|#160);/g, val: " " }, cent: { regex: /&(cent|#162);/g, val: "\xA2" }, pound: { regex: /&(pound|#163);/g, val: "\xA3" }, yen: { regex: /&(yen|#165);/g, val: "\xA5" }, euro: { regex: /&(euro|#8364);/g, val: "\u20AC" }, copyright: { regex: /&(copy|#169);/g, val: "\xA9" }, reg: { regex: /&(reg|#174);/g, val: "\xAE" }, inr: { regex: /&(inr|#8377);/g, val: "\u20B9" }, num_dec: { regex: /&#([0-9]{1,7});/g, val: (t7, e7) => rt(e7, 10, "&#") }, num_hex: { regex: /&#x([0-9a-fA-F]{1,6});/g, val: (t7, e7) => rt(e7, 16, "&#x") } }, this.addExternalEntities = Y, this.parseXml = J2, this.parseTextData = z3, this.resolveNameSpace = X, this.buildAttributesMap = Z, this.isItStopNode = tt, this.replaceEntitiesValue = Q, this.readStopNodeData = nt, this.saveTextToParentTag = H2, this.addChild = K, this.ignoreAttributesFn = "function" == typeof (e6 = this.options.ignoreAttributes) ? e6 : Array.isArray(e6) ? (t7) => { + for (const i6 of e6) { + if ("string" == typeof i6 && t7 === i6) return true; + if (i6 instanceof RegExp && i6.test(t7)) return true; + } + } : () => false, this.entityExpansionCount = 0, this.currentExpandedLength = 0, this.matcher = new G2(), this.readonlyMatcher = this.matcher.readOnly(), this.isCurrentNodeStopNode = false, this.options.stopNodes && this.options.stopNodes.length > 0) { + this.stopNodeExpressions = []; + for (let t7 = 0; t7 < this.options.stopNodes.length; t7++) { + const e7 = this.options.stopNodes[t7]; + "string" == typeof e7 ? this.stopNodeExpressions.push(new R(e7)) : e7 instanceof R && this.stopNodeExpressions.push(e7); + } + } + } + } + function Y(t6) { + const e6 = Object.keys(t6); + for (let i6 = 0; i6 < e6.length; i6++) { + const n6 = e6[i6], s6 = n6.replace(/[.\-+*:]/g, "\\."); + this.lastEntities[n6] = { regex: new RegExp("&" + s6 + ";", "g"), val: t6[n6] }; + } + } + function z3(t6, e6, i6, n6, s6, r6, o6) { + if (void 0 !== t6 && (this.options.trimValues && !n6 && (t6 = t6.trim()), t6.length > 0)) { + o6 || (t6 = this.replaceEntitiesValue(t6, e6, i6)); + const n7 = this.options.jPath ? i6.toString() : i6, a6 = this.options.tagValueProcessor(e6, t6, n7, s6, r6); + return null == a6 ? t6 : typeof a6 != typeof t6 || a6 !== t6 ? a6 : this.options.trimValues || t6.trim() === t6 ? st(t6, this.options.parseTagValue, this.options.numberParseOptions) : t6; + } + } + function X(t6) { + if (this.options.removeNSPrefix) { + const e6 = t6.split(":"), i6 = "/" === t6.charAt(0) ? "/" : ""; + if ("xmlns" === e6[0]) return ""; + 2 === e6.length && (t6 = i6 + e6[1]); + } + return t6; + } + const q5 = new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`, "gm"); + function Z(t6, e6, i6) { + if (true !== this.options.ignoreAttributes && "string" == typeof t6) { + const n6 = s5(t6, q5), r6 = n6.length, o6 = {}, a6 = {}; + for (let t7 = 0; t7 < r6; t7++) { + const e7 = this.resolveNameSpace(n6[t7][1]), s6 = n6[t7][4]; + if (e7.length && void 0 !== s6) { + let t8 = s6; + this.options.trimValues && (t8 = t8.trim()), t8 = this.replaceEntitiesValue(t8, i6, this.readonlyMatcher), a6[e7] = t8; + } + } + Object.keys(a6).length > 0 && "object" == typeof e6 && e6.updateCurrent && e6.updateCurrent(a6); + for (let t7 = 0; t7 < r6; t7++) { + const s6 = this.resolveNameSpace(n6[t7][1]), r7 = this.options.jPath ? e6.toString() : this.readonlyMatcher; + if (this.ignoreAttributesFn(s6, r7)) continue; + let a7 = n6[t7][4], h6 = this.options.attributeNamePrefix + s6; + if (s6.length) if (this.options.transformAttributeName && (h6 = this.options.transformAttributeName(h6)), h6 = at(h6, this.options), void 0 !== a7) { + this.options.trimValues && (a7 = a7.trim()), a7 = this.replaceEntitiesValue(a7, i6, this.readonlyMatcher); + const t8 = this.options.jPath ? e6.toString() : this.readonlyMatcher, n7 = this.options.attributeValueProcessor(s6, a7, t8); + o6[h6] = null == n7 ? a7 : typeof n7 != typeof a7 || n7 !== a7 ? n7 : st(a7, this.options.parseAttributeValue, this.options.numberParseOptions); + } else this.options.allowBooleanAttributes && (o6[h6] = true); + } + if (!Object.keys(o6).length) return; + if (this.options.attributesGroupName) { + const t7 = {}; + return t7[this.options.attributesGroupName] = o6, t7; + } + return o6; + } + } + const J2 = function(t6) { + t6 = t6.replace(/\r\n?/g, "\n"); + const e6 = new $("!xml"); + let i6 = e6, n6 = ""; + this.matcher.reset(), this.entityExpansionCount = 0, this.currentExpandedLength = 0; + const s6 = new I2(this.options.processEntities); + for (let r6 = 0; r6 < t6.length; r6++) if ("<" === t6[r6]) if ("/" === t6[r6 + 1]) { + const e7 = et(t6, ">", r6, "Closing Tag is not closed."); + let s7 = t6.substring(r6 + 2, e7).trim(); + if (this.options.removeNSPrefix) { + const t7 = s7.indexOf(":"); + -1 !== t7 && (s7 = s7.substr(t7 + 1)); + } + s7 = ot(this.options.transformTagName, s7, "", this.options).tagName, i6 && (n6 = this.saveTextToParentTag(n6, i6, this.readonlyMatcher)); + const o6 = this.matcher.getCurrentTag(); + if (s7 && -1 !== this.options.unpairedTags.indexOf(s7)) throw new Error(`Unpaired tag can not be used as closing tag: `); + o6 && -1 !== this.options.unpairedTags.indexOf(o6) && (this.matcher.pop(), this.tagsNodeStack.pop()), this.matcher.pop(), this.isCurrentNodeStopNode = false, i6 = this.tagsNodeStack.pop(), n6 = "", r6 = e7; + } else if ("?" === t6[r6 + 1]) { + let e7 = it(t6, r6, false, "?>"); + if (!e7) throw new Error("Pi Tag is not closed."); + if (n6 = this.saveTextToParentTag(n6, i6, this.readonlyMatcher), this.options.ignoreDeclaration && "?xml" === e7.tagName || this.options.ignorePiTags) ; + else { + const t7 = new $(e7.tagName); + t7.add(this.options.textNodeName, ""), e7.tagName !== e7.tagExp && e7.attrExpPresent && (t7[":@"] = this.buildAttributesMap(e7.tagExp, this.matcher, e7.tagName)), this.addChild(i6, t7, this.readonlyMatcher, r6); + } + r6 = e7.closeIndex + 1; + } else if ("!--" === t6.substr(r6 + 1, 3)) { + const e7 = et(t6, "-->", r6 + 4, "Comment is not closed."); + if (this.options.commentPropName) { + const s7 = t6.substring(r6 + 4, e7 - 2); + n6 = this.saveTextToParentTag(n6, i6, this.readonlyMatcher), i6.add(this.options.commentPropName, [{ [this.options.textNodeName]: s7 }]); + } + r6 = e7; + } else if ("!D" === t6.substr(r6 + 1, 2)) { + const e7 = s6.readDocType(t6, r6); + this.docTypeEntities = e7.entities, r6 = e7.i; + } else if ("![" === t6.substr(r6 + 1, 2)) { + const e7 = et(t6, "]]>", r6, "CDATA is not closed.") - 2, s7 = t6.substring(r6 + 9, e7); + n6 = this.saveTextToParentTag(n6, i6, this.readonlyMatcher); + let o6 = this.parseTextData(s7, i6.tagname, this.readonlyMatcher, true, false, true, true); + null == o6 && (o6 = ""), this.options.cdataPropName ? i6.add(this.options.cdataPropName, [{ [this.options.textNodeName]: s7 }]) : i6.add(this.options.textNodeName, o6), r6 = e7 + 2; + } else { + let s7 = it(t6, r6, this.options.removeNSPrefix); + if (!s7) { + const e7 = t6.substring(Math.max(0, r6 - 50), Math.min(t6.length, r6 + 50)); + throw new Error(`readTagExp returned undefined at position ${r6}. Context: "${e7}"`); + } + let o6 = s7.tagName; + const a6 = s7.rawTagName; + let h6 = s7.tagExp, l6 = s7.attrExpPresent, p6 = s7.closeIndex; + if ({ tagName: o6, tagExp: h6 } = ot(this.options.transformTagName, o6, h6, this.options), this.options.strictReservedNames && (o6 === this.options.commentPropName || o6 === this.options.cdataPropName || o6 === this.options.textNodeName || o6 === this.options.attributesGroupName)) throw new Error(`Invalid tag name: ${o6}`); + i6 && n6 && "!xml" !== i6.tagname && (n6 = this.saveTextToParentTag(n6, i6, this.readonlyMatcher, false)); + const u6 = i6; + u6 && -1 !== this.options.unpairedTags.indexOf(u6.tagname) && (i6 = this.tagsNodeStack.pop(), this.matcher.pop()); + let c6 = false; + h6.length > 0 && h6.lastIndexOf("/") === h6.length - 1 && (c6 = true, "/" === o6[o6.length - 1] ? (o6 = o6.substr(0, o6.length - 1), h6 = o6) : h6 = h6.substr(0, h6.length - 1), l6 = o6 !== h6); + let d6, f6 = null, g6 = {}; + d6 = B2(a6), o6 !== e6.tagname && this.matcher.push(o6, {}, d6), o6 !== h6 && l6 && (f6 = this.buildAttributesMap(h6, this.matcher, o6), f6 && (g6 = U(f6, this.options))), o6 !== e6.tagname && (this.isCurrentNodeStopNode = this.isItStopNode(this.stopNodeExpressions, this.matcher)); + const m6 = r6; + if (this.isCurrentNodeStopNode) { + let e7 = ""; + if (c6) r6 = s7.closeIndex; + else if (-1 !== this.options.unpairedTags.indexOf(o6)) r6 = s7.closeIndex; + else { + const i7 = this.readStopNodeData(t6, a6, p6 + 1); + if (!i7) throw new Error(`Unexpected end of ${a6}`); + r6 = i7.i, e7 = i7.tagContent; + } + const n7 = new $(o6); + f6 && (n7[":@"] = f6), n7.add(this.options.textNodeName, e7), this.matcher.pop(), this.isCurrentNodeStopNode = false, this.addChild(i6, n7, this.readonlyMatcher, m6); + } else { + if (c6) { + ({ tagName: o6, tagExp: h6 } = ot(this.options.transformTagName, o6, h6, this.options)); + const t7 = new $(o6); + f6 && (t7[":@"] = f6), this.addChild(i6, t7, this.readonlyMatcher, m6), this.matcher.pop(), this.isCurrentNodeStopNode = false; + } else { + if (-1 !== this.options.unpairedTags.indexOf(o6)) { + const t7 = new $(o6); + f6 && (t7[":@"] = f6), this.addChild(i6, t7, this.readonlyMatcher, m6), this.matcher.pop(), this.isCurrentNodeStopNode = false, r6 = s7.closeIndex; + continue; + } + { + const t7 = new $(o6); + if (this.tagsNodeStack.length > this.options.maxNestedTags) throw new Error("Maximum nested tags exceeded"); + this.tagsNodeStack.push(i6), f6 && (t7[":@"] = f6), this.addChild(i6, t7, this.readonlyMatcher, m6), i6 = t7; + } + } + n6 = "", r6 = p6; + } + } + else n6 += t6[r6]; + return e6.child; + }; + function K(t6, e6, i6, n6) { + this.options.captureMetaData || (n6 = void 0); + const s6 = this.options.jPath ? i6.toString() : i6, r6 = this.options.updateTag(e6.tagname, s6, e6[":@"]); + false === r6 || ("string" == typeof r6 ? (e6.tagname = r6, t6.addChild(e6, n6)) : t6.addChild(e6, n6)); + } + function Q(t6, e6, i6) { + const n6 = this.options.processEntities; + if (!n6 || !n6.enabled) return t6; + if (n6.allowedTags) { + const s6 = this.options.jPath ? i6.toString() : i6; + if (!(Array.isArray(n6.allowedTags) ? n6.allowedTags.includes(e6) : n6.allowedTags(e6, s6))) return t6; + } + if (n6.tagFilter) { + const s6 = this.options.jPath ? i6.toString() : i6; + if (!n6.tagFilter(e6, s6)) return t6; + } + for (const e7 of Object.keys(this.docTypeEntities)) { + const i7 = this.docTypeEntities[e7], s6 = t6.match(i7.regx); + if (s6) { + if (this.entityExpansionCount += s6.length, n6.maxTotalExpansions && this.entityExpansionCount > n6.maxTotalExpansions) throw new Error(`Entity expansion limit exceeded: ${this.entityExpansionCount} > ${n6.maxTotalExpansions}`); + const e8 = t6.length; + if (t6 = t6.replace(i7.regx, i7.val), n6.maxExpandedLength && (this.currentExpandedLength += t6.length - e8, this.currentExpandedLength > n6.maxExpandedLength)) throw new Error(`Total expanded content size exceeded: ${this.currentExpandedLength} > ${n6.maxExpandedLength}`); + } + } + for (const e7 of Object.keys(this.lastEntities)) { + const i7 = this.lastEntities[e7], s6 = t6.match(i7.regex); + if (s6 && (this.entityExpansionCount += s6.length, n6.maxTotalExpansions && this.entityExpansionCount > n6.maxTotalExpansions)) throw new Error(`Entity expansion limit exceeded: ${this.entityExpansionCount} > ${n6.maxTotalExpansions}`); + t6 = t6.replace(i7.regex, i7.val); + } + if (-1 === t6.indexOf("&")) return t6; + if (this.options.htmlEntities) for (const e7 of Object.keys(this.htmlEntities)) { + const i7 = this.htmlEntities[e7], s6 = t6.match(i7.regex); + if (s6 && (this.entityExpansionCount += s6.length, n6.maxTotalExpansions && this.entityExpansionCount > n6.maxTotalExpansions)) throw new Error(`Entity expansion limit exceeded: ${this.entityExpansionCount} > ${n6.maxTotalExpansions}`); + t6 = t6.replace(i7.regex, i7.val); + } + return t6.replace(this.ampEntity.regex, this.ampEntity.val); + } + function H2(t6, e6, i6, n6) { + return t6 && (void 0 === n6 && (n6 = 0 === e6.child.length), void 0 !== (t6 = this.parseTextData(t6, e6.tagname, i6, false, !!e6[":@"] && 0 !== Object.keys(e6[":@"]).length, n6)) && "" !== t6 && e6.add(this.options.textNodeName, t6), t6 = ""), t6; + } + function tt(t6, e6) { + if (!t6 || 0 === t6.length) return false; + for (let i6 = 0; i6 < t6.length; i6++) if (e6.matches(t6[i6])) return true; + return false; + } + function et(t6, e6, i6, n6) { + const s6 = t6.indexOf(e6, i6); + if (-1 === s6) throw new Error(n6); + return s6 + e6.length - 1; + } + function it(t6, e6, i6, n6 = ">") { + const s6 = (function(t7, e7, i7 = ">") { + let n7, s7 = ""; + for (let r7 = e7; r7 < t7.length; r7++) { + let e8 = t7[r7]; + if (n7) e8 === n7 && (n7 = ""); + else if ('"' === e8 || "'" === e8) n7 = e8; + else if (e8 === i7[0]) { + if (!i7[1]) return { data: s7, index: r7 }; + if (t7[r7 + 1] === i7[1]) return { data: s7, index: r7 }; + } else " " === e8 && (e8 = " "); + s7 += e8; + } + })(t6, e6 + 1, n6); + if (!s6) return; + let r6 = s6.data; + const o6 = s6.index, a6 = r6.search(/\s/); + let h6 = r6, l6 = true; + -1 !== a6 && (h6 = r6.substring(0, a6), r6 = r6.substring(a6 + 1).trimStart()); + const p6 = h6; + if (i6) { + const t7 = h6.indexOf(":"); + -1 !== t7 && (h6 = h6.substr(t7 + 1), l6 = h6 !== s6.data.substr(t7 + 1)); + } + return { tagName: h6, tagExp: r6, closeIndex: o6, attrExpPresent: l6, rawTagName: p6 }; + } + function nt(t6, e6, i6) { + const n6 = i6; + let s6 = 1; + for (; i6 < t6.length; i6++) if ("<" === t6[i6]) if ("/" === t6[i6 + 1]) { + const r6 = et(t6, ">", i6, `${e6} is not closed`); + if (t6.substring(i6 + 2, r6).trim() === e6 && (s6--, 0 === s6)) return { tagContent: t6.substring(n6, i6), i: r6 }; + i6 = r6; + } else if ("?" === t6[i6 + 1]) i6 = et(t6, "?>", i6 + 1, "StopNode is not closed."); + else if ("!--" === t6.substr(i6 + 1, 3)) i6 = et(t6, "-->", i6 + 3, "StopNode is not closed."); + else if ("![" === t6.substr(i6 + 1, 2)) i6 = et(t6, "]]>", i6, "StopNode is not closed.") - 2; + else { + const n7 = it(t6, i6, ">"); + n7 && ((n7 && n7.tagName) === e6 && "/" !== n7.tagExp[n7.tagExp.length - 1] && s6++, i6 = n7.closeIndex); + } + } + function st(t6, e6, i6) { + if (e6 && "string" == typeof t6) { + const e7 = t6.trim(); + return "true" === e7 || "false" !== e7 && (function(t7, e8 = {}) { + if (e8 = Object.assign({}, k5, e8), !t7 || "string" != typeof t7) return t7; + let i7 = t7.trim(); + if (void 0 !== e8.skipLike && e8.skipLike.test(i7)) return t7; + if ("0" === t7) return 0; + if (e8.hex && D2.test(i7)) return (function(t8) { + if (parseInt) return parseInt(t8, 16); + if (Number.parseInt) return Number.parseInt(t8, 16); + if (window && window.parseInt) return window.parseInt(t8, 16); + throw new Error("parseInt, Number.parseInt, window.parseInt are not supported"); + })(i7); + if (isFinite(i7)) { + if (i7.includes("e") || i7.includes("E")) return (function(t8, e9, i8) { + if (!i8.eNotation) return t8; + const n7 = e9.match(F2); + if (n7) { + let s6 = n7[1] || ""; + const r6 = -1 === n7[3].indexOf("e") ? "E" : "e", o6 = n7[2], a6 = s6 ? t8[o6.length + 1] === r6 : t8[o6.length] === r6; + return o6.length > 1 && a6 ? t8 : (1 !== o6.length || !n7[3].startsWith(`.${r6}`) && n7[3][0] !== r6) && o6.length > 0 ? i8.leadingZeros && !a6 ? (e9 = (n7[1] || "") + n7[3], Number(e9)) : t8 : Number(e9); + } + return t8; + })(t7, i7, e8); + { + const s6 = V.exec(i7); + if (s6) { + const r6 = s6[1] || "", o6 = s6[2]; + let a6 = (n6 = s6[3]) && -1 !== n6.indexOf(".") ? ("." === (n6 = n6.replace(/0+$/, "")) ? n6 = "0" : "." === n6[0] ? n6 = "0" + n6 : "." === n6[n6.length - 1] && (n6 = n6.substring(0, n6.length - 1)), n6) : n6; + const h6 = r6 ? "." === t7[o6.length + 1] : "." === t7[o6.length]; + if (!e8.leadingZeros && (o6.length > 1 || 1 === o6.length && !h6)) return t7; + { + const n7 = Number(i7), s7 = String(n7); + if (0 === n7) return n7; + if (-1 !== s7.search(/[eE]/)) return e8.eNotation ? n7 : t7; + if (-1 !== i7.indexOf(".")) return "0" === s7 || s7 === a6 || s7 === `${r6}${a6}` ? n7 : t7; + let h7 = o6 ? a6 : i7; + return o6 ? h7 === s7 || r6 + h7 === s7 ? n7 : t7 : h7 === s7 || h7 === r6 + s7 ? n7 : t7; + } + } + return t7; + } + } + var n6; + return (function(t8, e9, i8) { + const n7 = e9 === 1 / 0; + switch (i8.infinity.toLowerCase()) { + case "null": + return null; + case "infinity": + return e9; + case "string": + return n7 ? "Infinity" : "-Infinity"; + default: + return t8; + } + })(t7, Number(i7), e8); + })(t6, i6); + } + return void 0 !== t6 ? t6 : ""; + } + function rt(t6, e6, i6) { + const n6 = Number.parseInt(t6, e6); + return n6 >= 0 && n6 <= 1114111 ? String.fromCodePoint(n6) : i6 + t6 + ";"; + } + function ot(t6, e6, i6, n6) { + if (t6) { + const n7 = t6(e6); + i6 === e6 && (i6 = n7), e6 = n7; + } + return { tagName: e6 = at(e6, n6), tagExp: i6 }; + } + function at(t6, e6) { + if (a5.includes(t6)) throw new Error(`[SECURITY] Invalid name: "${t6}" is a reserved JavaScript keyword that could cause prototype pollution`); + return o5.includes(t6) ? e6.onDangerousProperty(t6) : t6; + } + const ht = $.getMetaDataSymbol(); + function lt2(t6, e6) { + if (!t6 || "object" != typeof t6) return {}; + if (!e6) return t6; + const i6 = {}; + for (const n6 in t6) n6.startsWith(e6) ? i6[n6.substring(e6.length)] = t6[n6] : i6[n6] = t6[n6]; + return i6; + } + function pt(t6, e6, i6, n6) { + return ut(t6, e6, i6, n6); + } + function ut(t6, e6, i6, n6) { + let s6; + const r6 = {}; + for (let o6 = 0; o6 < t6.length; o6++) { + const a6 = t6[o6], h6 = ct(a6); + if (void 0 !== h6 && h6 !== e6.textNodeName) { + const t7 = lt2(a6[":@"] || {}, e6.attributeNamePrefix); + i6.push(h6, t7); + } + if (h6 === e6.textNodeName) void 0 === s6 ? s6 = a6[h6] : s6 += "" + a6[h6]; + else { + if (void 0 === h6) continue; + if (a6[h6]) { + let t7 = ut(a6[h6], e6, i6, n6); + const s7 = ft(t7, e6); + if (a6[":@"] ? dt(t7, a6[":@"], n6, e6) : 1 !== Object.keys(t7).length || void 0 === t7[e6.textNodeName] || e6.alwaysCreateTextNode ? 0 === Object.keys(t7).length && (e6.alwaysCreateTextNode ? t7[e6.textNodeName] = "" : t7 = "") : t7 = t7[e6.textNodeName], void 0 !== a6[ht] && "object" == typeof t7 && null !== t7 && (t7[ht] = a6[ht]), void 0 !== r6[h6] && Object.prototype.hasOwnProperty.call(r6, h6)) Array.isArray(r6[h6]) || (r6[h6] = [r6[h6]]), r6[h6].push(t7); + else { + const i7 = e6.jPath ? n6.toString() : n6; + e6.isArray(h6, i7, s7) ? r6[h6] = [t7] : r6[h6] = t7; + } + void 0 !== h6 && h6 !== e6.textNodeName && i6.pop(); + } + } + } + return "string" == typeof s6 ? s6.length > 0 && (r6[e6.textNodeName] = s6) : void 0 !== s6 && (r6[e6.textNodeName] = s6), r6; + } + function ct(t6) { + const e6 = Object.keys(t6); + for (let t7 = 0; t7 < e6.length; t7++) { + const i6 = e6[t7]; + if (":@" !== i6) return i6; + } + } + function dt(t6, e6, i6, n6) { + if (e6) { + const s6 = Object.keys(e6), r6 = s6.length; + for (let o6 = 0; o6 < r6; o6++) { + const r7 = s6[o6], a6 = r7.startsWith(n6.attributeNamePrefix) ? r7.substring(n6.attributeNamePrefix.length) : r7, h6 = n6.jPath ? i6.toString() + "." + a6 : i6; + n6.isArray(r7, h6, true, true) ? t6[r7] = [e6[r7]] : t6[r7] = e6[r7]; + } + } + } + function ft(t6, e6) { + const { textNodeName: i6 } = e6, n6 = Object.keys(t6).length; + return 0 === n6 || !(1 !== n6 || !t6[i6] && "boolean" != typeof t6[i6] && 0 !== t6[i6]); + } + class gt2 { + constructor(t6) { + this.externalEntities = {}, this.options = O(t6); + } + parse(t6, e6) { + if ("string" != typeof t6 && t6.toString) t6 = t6.toString(); + else if ("string" != typeof t6) throw new Error("XML data is accepted in String or Bytes[] form."); + if (e6) { + true === e6 && (e6 = {}); + const i7 = l5(t6, e6); + if (true !== i7) throw Error(`${i7.err.msg}:${i7.err.line}:${i7.err.col}`); + } + const i6 = new W(this.options); + i6.addExternalEntities(this.externalEntities); + const n6 = i6.parseXml(t6); + return this.options.preserveOrder || void 0 === n6 ? n6 : pt(n6, this.options, i6.matcher, i6.readonlyMatcher); + } + addEntity(t6, e6) { + if (-1 !== e6.indexOf("&")) throw new Error("Entity value can't have '&'"); + if (-1 !== t6.indexOf("&") || -1 !== t6.indexOf(";")) throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for ' '"); + if ("&" === e6) throw new Error("An entity with value '&' is not permitted"); + this.externalEntities[t6] = e6; + } + static getMetaDataSymbol() { + return $.getMetaDataSymbol(); + } + } + function mt(t6, e6) { + let i6 = ""; + e6.format && e6.indentBy.length > 0 && (i6 = "\n"); + const n6 = []; + if (e6.stopNodes && Array.isArray(e6.stopNodes)) for (let t7 = 0; t7 < e6.stopNodes.length; t7++) { + const i7 = e6.stopNodes[t7]; + "string" == typeof i7 ? n6.push(new R(i7)) : i7 instanceof R && n6.push(i7); + } + return xt(t6, e6, i6, new G2(), n6); + } + function xt(t6, e6, i6, n6, s6) { + let r6 = "", o6 = false; + if (e6.maxNestedTags && n6.getDepth() > e6.maxNestedTags) throw new Error("Maximum nested tags exceeded"); + if (!Array.isArray(t6)) { + if (null != t6) { + let i7 = t6.toString(); + return i7 = Tt(i7, e6), i7; + } + return ""; + } + for (let a6 = 0; a6 < t6.length; a6++) { + const h6 = t6[a6], l6 = yt(h6); + if (void 0 === l6) continue; + const p6 = Nt(h6[":@"], e6); + n6.push(l6, p6); + const u6 = vt(n6, s6); + if (l6 === e6.textNodeName) { + let t7 = h6[l6]; + u6 || (t7 = e6.tagValueProcessor(l6, t7), t7 = Tt(t7, e6)), o6 && (r6 += i6), r6 += t7, o6 = false, n6.pop(); + continue; + } + if (l6 === e6.cdataPropName) { + o6 && (r6 += i6), r6 += ``, o6 = false, n6.pop(); + continue; + } + if (l6 === e6.commentPropName) { + r6 += i6 + ``, o6 = true, n6.pop(); + continue; + } + if ("?" === l6[0]) { + const t7 = wt(h6[":@"], e6, u6), s7 = "?xml" === l6 ? "" : i6; + let a7 = h6[l6][0][e6.textNodeName]; + a7 = 0 !== a7.length ? " " + a7 : "", r6 += s7 + `<${l6}${a7}${t7}?>`, o6 = true, n6.pop(); + continue; + } + let c6 = i6; + "" !== c6 && (c6 += e6.indentBy); + const d6 = i6 + `<${l6}${wt(h6[":@"], e6, u6)}`; + let f6; + f6 = u6 ? bt(h6[l6], e6) : xt(h6[l6], e6, c6, n6, s6), -1 !== e6.unpairedTags.indexOf(l6) ? e6.suppressUnpairedNode ? r6 += d6 + ">" : r6 += d6 + "/>" : f6 && 0 !== f6.length || !e6.suppressEmptyNode ? f6 && f6.endsWith(">") ? r6 += d6 + `>${f6}${i6}` : (r6 += d6 + ">", f6 && "" !== i6 && (f6.includes("/>") || f6.includes("`) : r6 += d6 + "/>", o6 = true, n6.pop(); + } + return r6; + } + function Nt(t6, e6) { + if (!t6 || e6.ignoreAttributes) return null; + const i6 = {}; + let n6 = false; + for (let s6 in t6) Object.prototype.hasOwnProperty.call(t6, s6) && (i6[s6.startsWith(e6.attributeNamePrefix) ? s6.substr(e6.attributeNamePrefix.length) : s6] = t6[s6], n6 = true); + return n6 ? i6 : null; + } + function bt(t6, e6) { + if (!Array.isArray(t6)) return null != t6 ? t6.toString() : ""; + let i6 = ""; + for (let n6 = 0; n6 < t6.length; n6++) { + const s6 = t6[n6], r6 = yt(s6); + if (r6 === e6.textNodeName) i6 += s6[r6]; + else if (r6 === e6.cdataPropName) i6 += s6[r6][0][e6.textNodeName]; + else if (r6 === e6.commentPropName) i6 += s6[r6][0][e6.textNodeName]; + else { + if (r6 && "?" === r6[0]) continue; + if (r6) { + const t7 = Et(s6[":@"], e6), n7 = bt(s6[r6], e6); + n7 && 0 !== n7.length ? i6 += `<${r6}${t7}>${n7}` : i6 += `<${r6}${t7}/>`; + } + } + } + return i6; + } + function Et(t6, e6) { + let i6 = ""; + if (t6 && !e6.ignoreAttributes) for (let n6 in t6) { + if (!Object.prototype.hasOwnProperty.call(t6, n6)) continue; + let s6 = t6[n6]; + true === s6 && e6.suppressBooleanAttributes ? i6 += ` ${n6.substr(e6.attributeNamePrefix.length)}` : i6 += ` ${n6.substr(e6.attributeNamePrefix.length)}="${s6}"`; + } + return i6; + } + function yt(t6) { + const e6 = Object.keys(t6); + for (let i6 = 0; i6 < e6.length; i6++) { + const n6 = e6[i6]; + if (Object.prototype.hasOwnProperty.call(t6, n6) && ":@" !== n6) return n6; + } + } + function wt(t6, e6, i6) { + let n6 = ""; + if (t6 && !e6.ignoreAttributes) for (let s6 in t6) { + if (!Object.prototype.hasOwnProperty.call(t6, s6)) continue; + let r6; + i6 ? r6 = t6[s6] : (r6 = e6.attributeValueProcessor(s6, t6[s6]), r6 = Tt(r6, e6)), true === r6 && e6.suppressBooleanAttributes ? n6 += ` ${s6.substr(e6.attributeNamePrefix.length)}` : n6 += ` ${s6.substr(e6.attributeNamePrefix.length)}="${r6}"`; + } + return n6; + } + function vt(t6, e6) { + if (!e6 || 0 === e6.length) return false; + for (let i6 = 0; i6 < e6.length; i6++) if (t6.matches(e6[i6])) return true; + return false; + } + function Tt(t6, e6) { + if (t6 && t6.length > 0 && e6.processEntities) for (let i6 = 0; i6 < e6.entities.length; i6++) { + const n6 = e6.entities[i6]; + t6 = t6.replace(n6.regex, n6.val); + } + return t6; + } + const Pt = { attributeNamePrefix: "@_", attributesGroupName: false, textNodeName: "#text", ignoreAttributes: true, cdataPropName: false, format: false, indentBy: " ", suppressEmptyNode: false, suppressUnpairedNode: true, suppressBooleanAttributes: true, tagValueProcessor: function(t6, e6) { + return e6; + }, attributeValueProcessor: function(t6, e6) { + return e6; + }, preserveOrder: false, commentPropName: false, unpairedTags: [], entities: [{ regex: new RegExp("&", "g"), val: "&" }, { regex: new RegExp(">", "g"), val: ">" }, { regex: new RegExp("<", "g"), val: "<" }, { regex: new RegExp("'", "g"), val: "'" }, { regex: new RegExp('"', "g"), val: """ }], processEntities: true, stopNodes: [], oneListGroup: false, maxNestedTags: 100, jPath: true }; + function St(t6) { + if (this.options = Object.assign({}, Pt, t6), this.options.stopNodes && Array.isArray(this.options.stopNodes) && (this.options.stopNodes = this.options.stopNodes.map((t7) => "string" == typeof t7 && t7.startsWith("*.") ? ".." + t7.substring(2) : t7)), this.stopNodeExpressions = [], this.options.stopNodes && Array.isArray(this.options.stopNodes)) for (let t7 = 0; t7 < this.options.stopNodes.length; t7++) { + const e7 = this.options.stopNodes[t7]; + "string" == typeof e7 ? this.stopNodeExpressions.push(new R(e7)) : e7 instanceof R && this.stopNodeExpressions.push(e7); + } + var e6; + true === this.options.ignoreAttributes || this.options.attributesGroupName ? this.isAttribute = function() { + return false; + } : (this.ignoreAttributesFn = "function" == typeof (e6 = this.options.ignoreAttributes) ? e6 : Array.isArray(e6) ? (t7) => { + for (const i6 of e6) { + if ("string" == typeof i6 && t7 === i6) return true; + if (i6 instanceof RegExp && i6.test(t7)) return true; + } + } : () => false, this.attrPrefixLen = this.options.attributeNamePrefix.length, this.isAttribute = Ct), this.processTextOrObjNode = At, this.options.format ? (this.indentate = Ot, this.tagEndChar = ">\n", this.newLine = "\n") : (this.indentate = function() { + return ""; + }, this.tagEndChar = ">", this.newLine = ""); + } + function At(t6, e6, i6, n6) { + const s6 = this.extractAttributes(t6); + if (n6.push(e6, s6), this.checkStopNode(n6)) { + const s7 = this.buildRawContent(t6), r7 = this.buildAttributesForStopNode(t6); + return n6.pop(), this.buildObjectNode(s7, e6, r7, i6); + } + const r6 = this.j2x(t6, i6 + 1, n6); + return n6.pop(), void 0 !== t6[this.options.textNodeName] && 1 === Object.keys(t6).length ? this.buildTextValNode(t6[this.options.textNodeName], e6, r6.attrStr, i6, n6) : this.buildObjectNode(r6.val, e6, r6.attrStr, i6); + } + function Ot(t6) { + return this.options.indentBy.repeat(t6); + } + function Ct(t6) { + return !(!t6.startsWith(this.options.attributeNamePrefix) || t6 === this.options.textNodeName) && t6.substr(this.attrPrefixLen); + } + St.prototype.build = function(t6) { + if (this.options.preserveOrder) return mt(t6, this.options); + { + Array.isArray(t6) && this.options.arrayNodeName && this.options.arrayNodeName.length > 1 && (t6 = { [this.options.arrayNodeName]: t6 }); + const e6 = new G2(); + return this.j2x(t6, 0, e6).val; + } + }, St.prototype.j2x = function(t6, e6, i6) { + let n6 = "", s6 = ""; + if (this.options.maxNestedTags && i6.getDepth() >= this.options.maxNestedTags) throw new Error("Maximum nested tags exceeded"); + const r6 = this.options.jPath ? i6.toString() : i6, o6 = this.checkStopNode(i6); + for (let a6 in t6) if (Object.prototype.hasOwnProperty.call(t6, a6)) if (void 0 === t6[a6]) this.isAttribute(a6) && (s6 += ""); + else if (null === t6[a6]) this.isAttribute(a6) || a6 === this.options.cdataPropName ? s6 += "" : "?" === a6[0] ? s6 += this.indentate(e6) + "<" + a6 + "?" + this.tagEndChar : s6 += this.indentate(e6) + "<" + a6 + "/" + this.tagEndChar; + else if (t6[a6] instanceof Date) s6 += this.buildTextValNode(t6[a6], a6, "", e6, i6); + else if ("object" != typeof t6[a6]) { + const h6 = this.isAttribute(a6); + if (h6 && !this.ignoreAttributesFn(h6, r6)) n6 += this.buildAttrPairStr(h6, "" + t6[a6], o6); + else if (!h6) if (a6 === this.options.textNodeName) { + let e7 = this.options.tagValueProcessor(a6, "" + t6[a6]); + s6 += this.replaceEntitiesValue(e7); + } else { + i6.push(a6); + const n7 = this.checkStopNode(i6); + if (i6.pop(), n7) { + const i7 = "" + t6[a6]; + s6 += "" === i7 ? this.indentate(e6) + "<" + a6 + this.closeTag(a6) + this.tagEndChar : this.indentate(e6) + "<" + a6 + ">" + i7 + "" + t8 + "${t7}`; + else if ("object" == typeof t7 && null !== t7) { + const n7 = this.buildRawContent(t7), s6 = this.buildAttributesForStopNode(t7); + e6 += "" === n7 ? `<${i6}${s6}/>` : `<${i6}${s6}>${n7}`; + } + } else if ("object" == typeof n6 && null !== n6) { + const t7 = this.buildRawContent(n6), s6 = this.buildAttributesForStopNode(n6); + e6 += "" === t7 ? `<${i6}${s6}/>` : `<${i6}${s6}>${t7}`; + } else e6 += `<${i6}>${n6}`; + } + return e6; + }, St.prototype.buildAttributesForStopNode = function(t6) { + if (!t6 || "object" != typeof t6) return ""; + let e6 = ""; + if (this.options.attributesGroupName && t6[this.options.attributesGroupName]) { + const i6 = t6[this.options.attributesGroupName]; + for (let t7 in i6) { + if (!Object.prototype.hasOwnProperty.call(i6, t7)) continue; + const n6 = t7.startsWith(this.options.attributeNamePrefix) ? t7.substring(this.options.attributeNamePrefix.length) : t7, s6 = i6[t7]; + true === s6 && this.options.suppressBooleanAttributes ? e6 += " " + n6 : e6 += " " + n6 + '="' + s6 + '"'; + } + } else for (let i6 in t6) { + if (!Object.prototype.hasOwnProperty.call(t6, i6)) continue; + const n6 = this.isAttribute(i6); + if (n6) { + const s6 = t6[i6]; + true === s6 && this.options.suppressBooleanAttributes ? e6 += " " + n6 : e6 += " " + n6 + '="' + s6 + '"'; + } + } + return e6; + }, St.prototype.buildObjectNode = function(t6, e6, i6, n6) { + if ("" === t6) return "?" === e6[0] ? this.indentate(n6) + "<" + e6 + i6 + "?" + this.tagEndChar : this.indentate(n6) + "<" + e6 + i6 + this.closeTag(e6) + this.tagEndChar; + { + let s6 = "` + this.newLine : this.indentate(n6) + "<" + e6 + i6 + r6 + this.tagEndChar + t6 + this.indentate(n6) + s6 : this.indentate(n6) + "<" + e6 + i6 + r6 + ">" + t6 + s6; + } + }, St.prototype.closeTag = function(t6) { + let e6 = ""; + return -1 !== this.options.unpairedTags.indexOf(t6) ? this.options.suppressUnpairedNode || (e6 = "/") : e6 = this.options.suppressEmptyNode ? "/" : `>` + this.newLine; + if (false !== this.options.commentPropName && e6 === this.options.commentPropName) return this.indentate(n6) + `` + this.newLine; + if ("?" === e6[0]) return this.indentate(n6) + "<" + e6 + i6 + "?" + this.tagEndChar; + { + let s7 = this.options.tagValueProcessor(e6, t6); + return s7 = this.replaceEntitiesValue(s7), "" === s7 ? this.indentate(n6) + "<" + e6 + i6 + this.closeTag(e6) + this.tagEndChar : this.indentate(n6) + "<" + e6 + i6 + ">" + s7 + " 0 && this.options.processEntities) for (let e6 = 0; e6 < this.options.entities.length; e6++) { + const i6 = this.options.entities[e6]; + t6 = t6.replace(i6.regex, i6.val); + } + return t6; + }; + const $t = St, It = { validate: l5 }; + module.exports = e5; + })(); + } +}); + +// node_modules/.pnpm/@aws-sdk+xml-builder@3.972.17/node_modules/@aws-sdk/xml-builder/dist-cjs/xml-parser.js +var require_xml_parser = __commonJS({ + "node_modules/.pnpm/@aws-sdk+xml-builder@3.972.17/node_modules/@aws-sdk/xml-builder/dist-cjs/xml-parser.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.parseXML = parseXML3; + var fast_xml_parser_1 = require_fxp(); + var parser = new fast_xml_parser_1.XMLParser({ + attributeNamePrefix: "", + processEntities: { + enabled: true, + maxTotalExpansions: Infinity + }, + htmlEntities: true, + ignoreAttributes: false, + ignoreDeclaration: true, + parseTagValue: false, + trimValues: false, + tagValueProcessor: (_, val) => val.trim() === "" && val.includes("\n") ? "" : void 0, + maxNestedTags: Infinity + }); + parser.addEntity("#xD", "\r"); + parser.addEntity("#10", "\n"); + function parseXML3(xmlString) { + return parser.parse(xmlString, true); + } + } +}); + +// node_modules/.pnpm/@aws-sdk+xml-builder@3.972.17/node_modules/@aws-sdk/xml-builder/dist-cjs/index.js +var require_dist_cjs29 = __commonJS({ + "node_modules/.pnpm/@aws-sdk+xml-builder@3.972.17/node_modules/@aws-sdk/xml-builder/dist-cjs/index.js"(exports) { + "use strict"; + var xmlParser = require_xml_parser(); + var ATTR_ESCAPE_RE = /[&<>"]/g; + var ATTR_ESCAPE_MAP = { + "&": "&", + "<": "<", + ">": ">", + '"': """ + }; + function escapeAttribute(value) { + return value.replace(ATTR_ESCAPE_RE, (ch) => ATTR_ESCAPE_MAP[ch]); + } + var ELEMENT_ESCAPE_RE = /[&"'<>\r\n\u0085\u2028]/g; + var ELEMENT_ESCAPE_MAP = { + "&": "&", + '"': """, + "'": "'", + "<": "<", + ">": ">", + "\r": " ", + "\n": " ", + "\x85": "…", + "\u2028": "
" + }; + function escapeElement(value) { + return value.replace(ELEMENT_ESCAPE_RE, (ch) => ELEMENT_ESCAPE_MAP[ch]); + } + var XmlText2 = class { + value; + constructor(value) { + this.value = value; + } + toString() { + return escapeElement("" + this.value); + } + }; + var XmlNode2 = class _XmlNode { + name; + children; + attributes = {}; + static of(name, childText, withName) { + const node = new _XmlNode(name); + if (childText !== void 0) { + node.addChildNode(new XmlText2(childText)); + } + if (withName !== void 0) { + node.withName(withName); + } + return node; + } + constructor(name, children = []) { + this.name = name; + this.children = children; + } + withName(name) { + this.name = name; + return this; + } + addAttribute(name, value) { + this.attributes[name] = value; + return this; + } + addChildNode(child) { + this.children.push(child); + return this; + } + removeAttribute(name) { + delete this.attributes[name]; + return this; + } + n(name) { + this.name = name; + return this; + } + c(child) { + this.children.push(child); + return this; + } + a(name, value) { + if (value != null) { + this.attributes[name] = value; + } + return this; + } + cc(input, field, withName = field) { + if (input[field] != null) { + const node = _XmlNode.of(field, input[field]).withName(withName); + this.c(node); + } + } + l(input, listName, memberName, valueProvider) { + if (input[listName] != null) { + const nodes = valueProvider(); + nodes.map((node) => { + node.withName(memberName); + this.c(node); + }); + } + } + lc(input, listName, memberName, valueProvider) { + if (input[listName] != null) { + const nodes = valueProvider(); + const containerNode = new _XmlNode(memberName); + nodes.map((node) => { + containerNode.c(node); + }); + this.c(containerNode); + } + } + toString() { + const hasChildren = Boolean(this.children.length); + let xmlText = `<${this.name}`; + const attributes = this.attributes; + for (const attributeName of Object.keys(attributes)) { + const attribute = attributes[attributeName]; + if (attribute != null) { + xmlText += ` ${attributeName}="${escapeAttribute("" + attribute)}"`; + } + } + return xmlText += !hasChildren ? "/>" : `>${this.children.map((c5) => c5.toString()).join("")}`; + } + }; + exports.parseXML = xmlParser.parseXML; + exports.XmlNode = XmlNode2; + exports.XmlText = XmlText2; + } +}); + +// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/xml/XmlShapeDeserializer.js +var import_xml_builder, import_smithy_client4, import_util_utf87, XmlShapeDeserializer; +var init_XmlShapeDeserializer = __esm({ + "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/xml/XmlShapeDeserializer.js"() { + import_xml_builder = __toESM(require_dist_cjs29()); + init_protocols(); + init_schema3(); + import_smithy_client4 = __toESM(require_dist_cjs27()); + import_util_utf87 = __toESM(require_dist_cjs6()); + init_ConfigurableSerdeContext(); + init_UnionSerde(); + XmlShapeDeserializer = class extends SerdeContextConfig { + settings; + stringDeserializer; + constructor(settings) { + super(); + this.settings = settings; + this.stringDeserializer = new FromStringShapeDeserializer(settings); + } + setSerdeContext(serdeContext) { + this.serdeContext = serdeContext; + this.stringDeserializer.setSerdeContext(serdeContext); + } + read(schema2, bytes, key) { + const ns = NormalizedSchema.of(schema2); + const memberSchemas = ns.getMemberSchemas(); + const isEventPayload = ns.isStructSchema() && ns.isMemberSchema() && !!Object.values(memberSchemas).find((memberNs) => { + return !!memberNs.getMemberTraits().eventPayload; + }); + if (isEventPayload) { + const output = {}; + const memberName = Object.keys(memberSchemas)[0]; + const eventMemberSchema = memberSchemas[memberName]; + if (eventMemberSchema.isBlobSchema()) { + output[memberName] = bytes; + } else { + output[memberName] = this.read(memberSchemas[memberName], bytes); + } + return output; + } + const xmlString = (this.serdeContext?.utf8Encoder ?? import_util_utf87.toUtf8)(bytes); + const parsedObject = this.parseXml(xmlString); + return this.readSchema(schema2, key ? parsedObject[key] : parsedObject); + } + readSchema(_schema, value) { + const ns = NormalizedSchema.of(_schema); + if (ns.isUnitSchema()) { + return; + } + const traits = ns.getMergedTraits(); + if (ns.isListSchema() && !Array.isArray(value)) { + return this.readSchema(ns, [value]); + } + if (value == null) { + return value; + } + if (typeof value === "object") { + const flat = !!traits.xmlFlattened; + if (ns.isListSchema()) { + const listValue = ns.getValueSchema(); + const buffer3 = []; + const sourceKey = listValue.getMergedTraits().xmlName ?? "member"; + const source = flat ? value : (value[0] ?? value)[sourceKey]; + if (source == null) { + return buffer3; + } + const sourceArray = Array.isArray(source) ? source : [source]; + for (const v5 of sourceArray) { + buffer3.push(this.readSchema(listValue, v5)); + } + return buffer3; + } + const buffer2 = {}; + if (ns.isMapSchema()) { + const keyNs = ns.getKeySchema(); + const memberNs = ns.getValueSchema(); + let entries2; + if (flat) { + entries2 = Array.isArray(value) ? value : [value]; + } else { + entries2 = Array.isArray(value.entry) ? value.entry : [value.entry]; + } + const keyProperty = keyNs.getMergedTraits().xmlName ?? "key"; + const valueProperty = memberNs.getMergedTraits().xmlName ?? "value"; + for (const entry of entries2) { + const key = entry[keyProperty]; + const value2 = entry[valueProperty]; + buffer2[key] = this.readSchema(memberNs, value2); + } + return buffer2; + } + if (ns.isStructSchema()) { + const union3 = ns.isUnionSchema(); + let unionSerde; + if (union3) { + unionSerde = new UnionSerde(value, buffer2); + } + for (const [memberName, memberSchema] of ns.structIterator()) { + const memberTraits = memberSchema.getMergedTraits(); + const xmlObjectKey = !memberTraits.httpPayload ? memberSchema.getMemberTraits().xmlName ?? memberName : memberTraits.xmlName ?? memberSchema.getName(); + if (union3) { + unionSerde.mark(xmlObjectKey); + } + if (value[xmlObjectKey] != null) { + buffer2[memberName] = this.readSchema(memberSchema, value[xmlObjectKey]); + } + } + if (union3) { + unionSerde.writeUnknown(); + } + return buffer2; + } + if (ns.isDocumentSchema()) { + return value; + } + throw new Error(`@aws-sdk/core/protocols - xml deserializer unhandled schema type for ${ns.getName(true)}`); + } + if (ns.isListSchema()) { + return []; + } + if (ns.isMapSchema() || ns.isStructSchema()) { + return {}; + } + return this.stringDeserializer.read(ns, value); + } + parseXml(xml2) { + if (xml2.length) { + let parsedObj; + try { + parsedObj = (0, import_xml_builder.parseXML)(xml2); + } catch (e5) { + if (e5 && typeof e5 === "object") { + Object.defineProperty(e5, "$responseBodyText", { + value: xml2 + }); + } + throw e5; + } + const textNodeName = "#text"; + const key = Object.keys(parsedObj)[0]; + const parsedObjToReturn = parsedObj[key]; + if (parsedObjToReturn[textNodeName]) { + parsedObjToReturn[key] = parsedObjToReturn[textNodeName]; + delete parsedObjToReturn[textNodeName]; + } + return (0, import_smithy_client4.getValueFromTextNode)(parsedObjToReturn); + } + return {}; + } + }; + } +}); + +// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/query/QueryShapeSerializer.js +var import_smithy_client5, import_util_base646, QueryShapeSerializer; +var init_QueryShapeSerializer = __esm({ + "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/query/QueryShapeSerializer.js"() { + init_protocols(); + init_schema3(); + init_serde(); + import_smithy_client5 = __toESM(require_dist_cjs27()); + import_util_base646 = __toESM(require_dist_cjs7()); + init_ConfigurableSerdeContext(); + QueryShapeSerializer = class extends SerdeContextConfig { + settings; + buffer; + constructor(settings) { + super(); + this.settings = settings; + } + write(schema2, value, prefix = "") { + if (this.buffer === void 0) { + this.buffer = ""; + } + const ns = NormalizedSchema.of(schema2); + if (prefix && !prefix.endsWith(".")) { + prefix += "."; + } + if (ns.isBlobSchema()) { + if (typeof value === "string" || value instanceof Uint8Array) { + this.writeKey(prefix); + this.writeValue((this.serdeContext?.base64Encoder ?? import_util_base646.toBase64)(value)); + } + } else if (ns.isBooleanSchema() || ns.isNumericSchema() || ns.isStringSchema()) { + if (value != null) { + this.writeKey(prefix); + this.writeValue(String(value)); + } else if (ns.isIdempotencyToken()) { + this.writeKey(prefix); + this.writeValue((0, import_uuid2.v4)()); + } + } else if (ns.isBigIntegerSchema()) { + if (value != null) { + this.writeKey(prefix); + this.writeValue(String(value)); + } + } else if (ns.isBigDecimalSchema()) { + if (value != null) { + this.writeKey(prefix); + this.writeValue(value instanceof NumericValue ? value.string : String(value)); + } + } else if (ns.isTimestampSchema()) { + if (value instanceof Date) { + this.writeKey(prefix); + const format2 = determineTimestampFormat(ns, this.settings); + switch (format2) { + case 5: + this.writeValue(value.toISOString().replace(".000Z", "Z")); + break; + case 6: + this.writeValue((0, import_smithy_client5.dateToUtcString)(value)); + break; + case 7: + this.writeValue(String(value.getTime() / 1e3)); + break; + } + } + } else if (ns.isDocumentSchema()) { + if (Array.isArray(value)) { + this.write(64 | 15, value, prefix); + } else if (value instanceof Date) { + this.write(4, value, prefix); + } else if (value instanceof Uint8Array) { + this.write(21, value, prefix); + } else if (value && typeof value === "object") { + this.write(128 | 15, value, prefix); + } else { + this.writeKey(prefix); + this.writeValue(String(value)); + } + } else if (ns.isListSchema()) { + if (Array.isArray(value)) { + if (value.length === 0) { + if (this.settings.serializeEmptyLists) { + this.writeKey(prefix); + this.writeValue(""); + } + } else { + const member2 = ns.getValueSchema(); + const flat = this.settings.flattenLists || ns.getMergedTraits().xmlFlattened; + let i5 = 1; + for (const item of value) { + if (item == null) { + continue; + } + const traits = member2.getMergedTraits(); + const suffix = this.getKey("member", traits.xmlName, traits.ec2QueryName); + const key = flat ? `${prefix}${i5}` : `${prefix}${suffix}.${i5}`; + this.write(member2, item, key); + ++i5; + } + } + } + } else if (ns.isMapSchema()) { + if (value && typeof value === "object") { + const keySchema = ns.getKeySchema(); + const memberSchema = ns.getValueSchema(); + const flat = ns.getMergedTraits().xmlFlattened; + let i5 = 1; + for (const [k5, v5] of Object.entries(value)) { + if (v5 == null) { + continue; + } + const keyTraits = keySchema.getMergedTraits(); + const keySuffix = this.getKey("key", keyTraits.xmlName, keyTraits.ec2QueryName); + const key = flat ? `${prefix}${i5}.${keySuffix}` : `${prefix}entry.${i5}.${keySuffix}`; + const valTraits = memberSchema.getMergedTraits(); + const valueSuffix = this.getKey("value", valTraits.xmlName, valTraits.ec2QueryName); + const valueKey = flat ? `${prefix}${i5}.${valueSuffix}` : `${prefix}entry.${i5}.${valueSuffix}`; + this.write(keySchema, k5, key); + this.write(memberSchema, v5, valueKey); + ++i5; + } + } + } else if (ns.isStructSchema()) { + if (value && typeof value === "object") { + let didWriteMember = false; + for (const [memberName, member2] of ns.structIterator()) { + if (value[memberName] == null && !member2.isIdempotencyToken()) { + continue; + } + const traits = member2.getMergedTraits(); + const suffix = this.getKey(memberName, traits.xmlName, traits.ec2QueryName, "struct"); + const key = `${prefix}${suffix}`; + this.write(member2, value[memberName], key); + didWriteMember = true; + } + if (!didWriteMember && ns.isUnionSchema()) { + const { $unknown } = value; + if (Array.isArray($unknown)) { + const [k5, v5] = $unknown; + const key = `${prefix}${k5}`; + this.write(15, v5, key); + } + } + } + } else if (ns.isUnitSchema()) { + } else { + throw new Error(`@aws-sdk/core/protocols - QuerySerializer unrecognized schema type ${ns.getName(true)}`); + } + } + flush() { + if (this.buffer === void 0) { + throw new Error("@aws-sdk/core/protocols - QuerySerializer cannot flush with nothing written to buffer."); + } + const str = this.buffer; + delete this.buffer; + return str; + } + getKey(memberName, xmlName, ec2QueryName, keySource) { + const { ec2, capitalizeKeys } = this.settings; + if (ec2 && ec2QueryName) { + return ec2QueryName; + } + const key = xmlName ?? memberName; + if (capitalizeKeys && keySource === "struct") { + return key[0].toUpperCase() + key.slice(1); + } + return key; + } + writeKey(key) { + if (key.endsWith(".")) { + key = key.slice(0, key.length - 1); + } + this.buffer += `&${extendedEncodeURIComponent(key)}=`; + } + writeValue(value) { + this.buffer += extendedEncodeURIComponent(value); + } + }; + } +}); + +// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/query/AwsQueryProtocol.js +var AwsQueryProtocol; +var init_AwsQueryProtocol = __esm({ + "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/query/AwsQueryProtocol.js"() { + init_protocols(); + init_schema3(); + init_ProtocolLib(); + init_XmlShapeDeserializer(); + init_QueryShapeSerializer(); + AwsQueryProtocol = class extends RpcProtocol { + options; + serializer; + deserializer; + mixin = new ProtocolLib(); + constructor(options) { + super({ + defaultNamespace: options.defaultNamespace, + errorTypeRegistries: options.errorTypeRegistries + }); + this.options = options; + const settings = { + timestampFormat: { + useTrait: true, + default: 5 + }, + httpBindings: false, + xmlNamespace: options.xmlNamespace, + serviceNamespace: options.defaultNamespace, + serializeEmptyLists: true + }; + this.serializer = new QueryShapeSerializer(settings); + this.deserializer = new XmlShapeDeserializer(settings); + } + getShapeId() { + return "aws.protocols#awsQuery"; + } + setSerdeContext(serdeContext) { + this.serializer.setSerdeContext(serdeContext); + this.deserializer.setSerdeContext(serdeContext); + } + getPayloadCodec() { + throw new Error("AWSQuery protocol has no payload codec."); + } + async serializeRequest(operationSchema, input, context) { + const request = await super.serializeRequest(operationSchema, input, context); + if (!request.path.endsWith("/")) { + request.path += "/"; + } + Object.assign(request.headers, { + "content-type": `application/x-www-form-urlencoded` + }); + if (deref(operationSchema.input) === "unit" || !request.body) { + request.body = ""; + } + const action = operationSchema.name.split("#")[1] ?? operationSchema.name; + request.body = `Action=${action}&Version=${this.options.version}` + request.body; + if (request.body.endsWith("&")) { + request.body = request.body.slice(-1); + } + return request; + } + async deserializeResponse(operationSchema, context, response) { + const deserializer = this.deserializer; + const ns = NormalizedSchema.of(operationSchema.output); + const dataObject = {}; + if (response.statusCode >= 300) { + const bytes2 = await collectBody(response.body, context); + if (bytes2.byteLength > 0) { + Object.assign(dataObject, await deserializer.read(15, bytes2)); + } + await this.handleError(operationSchema, context, response, dataObject, this.deserializeMetadata(response)); + } + for (const header in response.headers) { + const value = response.headers[header]; + delete response.headers[header]; + response.headers[header.toLowerCase()] = value; + } + const shortName = operationSchema.name.split("#")[1] ?? operationSchema.name; + const awsQueryResultKey = ns.isStructSchema() && this.useNestedResult() ? shortName + "Result" : void 0; + const bytes = await collectBody(response.body, context); + if (bytes.byteLength > 0) { + Object.assign(dataObject, await deserializer.read(ns, bytes, awsQueryResultKey)); + } + const output = { + $metadata: this.deserializeMetadata(response), + ...dataObject + }; + return output; + } + useNestedResult() { + return true; + } + async handleError(operationSchema, context, response, dataObject, metadata) { + const errorIdentifier = this.loadQueryErrorCode(response, dataObject) ?? "Unknown"; + this.mixin.compose(this.compositeErrorRegistry, errorIdentifier, this.options.defaultNamespace); + const errorData = this.loadQueryError(dataObject) ?? {}; + const message2 = this.loadQueryErrorMessage(dataObject); + errorData.message = message2; + errorData.Error = { + Type: errorData.Type, + Code: errorData.Code, + Message: message2 + }; + const { errorSchema, errorMetadata } = await this.mixin.getErrorSchemaOrThrowBaseException(errorIdentifier, this.options.defaultNamespace, response, errorData, metadata, this.mixin.findQueryCompatibleError); + const ns = NormalizedSchema.of(errorSchema); + const ErrorCtor = this.compositeErrorRegistry.getErrorCtor(errorSchema) ?? Error; + const exception = new ErrorCtor(message2); + const output = { + Type: errorData.Error.Type, + Code: errorData.Error.Code, + Error: errorData.Error + }; + for (const [name, member2] of ns.structIterator()) { + const target = member2.getMergedTraits().xmlName ?? name; + const value = errorData[target] ?? dataObject[target]; + output[name] = this.deserializer.readSchema(member2, value); + } + throw this.mixin.decorateServiceException(Object.assign(exception, errorMetadata, { + $fault: ns.getMergedTraits().error, + message: message2 + }, output), dataObject); + } + loadQueryErrorCode(output, data2) { + const code = (data2.Errors?.[0]?.Error ?? data2.Errors?.Error ?? data2.Error)?.Code; + if (code !== void 0) { + return code; + } + if (output.statusCode == 404) { + return "NotFound"; + } + } + loadQueryError(data2) { + return data2.Errors?.[0]?.Error ?? data2.Errors?.Error ?? data2.Error; + } + loadQueryErrorMessage(data2) { + const errorData = this.loadQueryError(data2); + return errorData?.message ?? errorData?.Message ?? data2.message ?? data2.Message ?? "Unknown"; + } + getDefaultContentType() { + return "application/x-www-form-urlencoded"; + } + }; + } +}); + +// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/query/AwsEc2QueryProtocol.js +var AwsEc2QueryProtocol; +var init_AwsEc2QueryProtocol = __esm({ + "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/query/AwsEc2QueryProtocol.js"() { + init_AwsQueryProtocol(); + AwsEc2QueryProtocol = class extends AwsQueryProtocol { + options; + constructor(options) { + super(options); + this.options = options; + const ec2Settings = { + capitalizeKeys: true, + flattenLists: true, + serializeEmptyLists: false, + ec2: true + }; + Object.assign(this.serializer.settings, ec2Settings); + } + getShapeId() { + return "aws.protocols#ec2Query"; + } + useNestedResult() { + return false; + } + }; + } +}); + +// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/query/QuerySerializerSettings.js +var init_QuerySerializerSettings = __esm({ + "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/query/QuerySerializerSettings.js"() { + } +}); + +// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/xml/parseXmlBody.js +var import_xml_builder2, import_smithy_client6, parseXmlBody, parseXmlErrorBody, loadRestXmlErrorCode; +var init_parseXmlBody = __esm({ + "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/xml/parseXmlBody.js"() { + import_xml_builder2 = __toESM(require_dist_cjs29()); + import_smithy_client6 = __toESM(require_dist_cjs27()); + init_common2(); + parseXmlBody = (streamBody, context) => collectBodyString(streamBody, context).then((encoded) => { + if (encoded.length) { + let parsedObj; + try { + parsedObj = (0, import_xml_builder2.parseXML)(encoded); + } catch (e5) { + if (e5 && typeof e5 === "object") { + Object.defineProperty(e5, "$responseBodyText", { + value: encoded + }); + } + throw e5; + } + const textNodeName = "#text"; + const key = Object.keys(parsedObj)[0]; + const parsedObjToReturn = parsedObj[key]; + if (parsedObjToReturn[textNodeName]) { + parsedObjToReturn[key] = parsedObjToReturn[textNodeName]; + delete parsedObjToReturn[textNodeName]; + } + return (0, import_smithy_client6.getValueFromTextNode)(parsedObjToReturn); + } + return {}; + }); + parseXmlErrorBody = async (errorBody, context) => { + const value = await parseXmlBody(errorBody, context); + if (value.Error) { + value.Error.message = value.Error.message ?? value.Error.Message; + } + return value; + }; + loadRestXmlErrorCode = (output, data2) => { + if (data2?.Error?.Code !== void 0) { + return data2.Error.Code; + } + if (data2?.Code !== void 0) { + return data2.Code; + } + if (output.statusCode == 404) { + return "NotFound"; + } + }; + } +}); + +// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/xml/XmlShapeSerializer.js +var import_xml_builder3, import_smithy_client7, import_util_base647, XmlShapeSerializer; +var init_XmlShapeSerializer = __esm({ + "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/xml/XmlShapeSerializer.js"() { + import_xml_builder3 = __toESM(require_dist_cjs29()); + init_protocols(); + init_schema3(); + init_serde(); + import_smithy_client7 = __toESM(require_dist_cjs27()); + import_util_base647 = __toESM(require_dist_cjs7()); + init_ConfigurableSerdeContext(); + XmlShapeSerializer = class extends SerdeContextConfig { + settings; + stringBuffer; + byteBuffer; + buffer; + constructor(settings) { + super(); + this.settings = settings; + } + write(schema2, value) { + const ns = NormalizedSchema.of(schema2); + if (ns.isStringSchema() && typeof value === "string") { + this.stringBuffer = value; + } else if (ns.isBlobSchema()) { + this.byteBuffer = "byteLength" in value ? value : (this.serdeContext?.base64Decoder ?? import_util_base647.fromBase64)(value); + } else { + this.buffer = this.writeStruct(ns, value, void 0); + const traits = ns.getMergedTraits(); + if (traits.httpPayload && !traits.xmlName) { + this.buffer.withName(ns.getName()); + } + } + } + flush() { + if (this.byteBuffer !== void 0) { + const bytes = this.byteBuffer; + delete this.byteBuffer; + return bytes; + } + if (this.stringBuffer !== void 0) { + const str = this.stringBuffer; + delete this.stringBuffer; + return str; + } + const buffer2 = this.buffer; + if (this.settings.xmlNamespace) { + if (!buffer2?.attributes?.["xmlns"]) { + buffer2.addAttribute("xmlns", this.settings.xmlNamespace); + } + } + delete this.buffer; + return buffer2.toString(); + } + writeStruct(ns, value, parentXmlns) { + const traits = ns.getMergedTraits(); + const name = ns.isMemberSchema() && !traits.httpPayload ? ns.getMemberTraits().xmlName ?? ns.getMemberName() : traits.xmlName ?? ns.getName(); + if (!name || !ns.isStructSchema()) { + throw new Error(`@aws-sdk/core/protocols - xml serializer, cannot write struct with empty name or non-struct, schema=${ns.getName(true)}.`); + } + const structXmlNode = import_xml_builder3.XmlNode.of(name); + const [xmlnsAttr, xmlns] = this.getXmlnsAttribute(ns, parentXmlns); + for (const [memberName, memberSchema] of ns.structIterator()) { + const val = value[memberName]; + if (val != null || memberSchema.isIdempotencyToken()) { + if (memberSchema.getMergedTraits().xmlAttribute) { + structXmlNode.addAttribute(memberSchema.getMergedTraits().xmlName ?? memberName, this.writeSimple(memberSchema, val)); + continue; + } + if (memberSchema.isListSchema()) { + this.writeList(memberSchema, val, structXmlNode, xmlns); + } else if (memberSchema.isMapSchema()) { + this.writeMap(memberSchema, val, structXmlNode, xmlns); + } else if (memberSchema.isStructSchema()) { + structXmlNode.addChildNode(this.writeStruct(memberSchema, val, xmlns)); + } else { + const memberNode = import_xml_builder3.XmlNode.of(memberSchema.getMergedTraits().xmlName ?? memberSchema.getMemberName()); + this.writeSimpleInto(memberSchema, val, memberNode, xmlns); + structXmlNode.addChildNode(memberNode); + } + } + } + const { $unknown } = value; + if ($unknown && ns.isUnionSchema() && Array.isArray($unknown) && Object.keys(value).length === 1) { + const [k5, v5] = $unknown; + const node = import_xml_builder3.XmlNode.of(k5); + if (typeof v5 !== "string") { + if (value instanceof import_xml_builder3.XmlNode || value instanceof import_xml_builder3.XmlText) { + structXmlNode.addChildNode(value); + } else { + throw new Error(`@aws-sdk - $unknown union member in XML requires value of type string, @aws-sdk/xml-builder::XmlNode or XmlText.`); + } + } + this.writeSimpleInto(0, v5, node, xmlns); + structXmlNode.addChildNode(node); + } + if (xmlns) { + structXmlNode.addAttribute(xmlnsAttr, xmlns); + } + return structXmlNode; + } + writeList(listMember, array2, container, parentXmlns) { + if (!listMember.isMemberSchema()) { + throw new Error(`@aws-sdk/core/protocols - xml serializer, cannot write non-member list: ${listMember.getName(true)}`); + } + const listTraits = listMember.getMergedTraits(); + const listValueSchema = listMember.getValueSchema(); + const listValueTraits = listValueSchema.getMergedTraits(); + const sparse = !!listValueTraits.sparse; + const flat = !!listTraits.xmlFlattened; + const [xmlnsAttr, xmlns] = this.getXmlnsAttribute(listMember, parentXmlns); + const writeItem = (container2, value) => { + if (listValueSchema.isListSchema()) { + this.writeList(listValueSchema, Array.isArray(value) ? value : [value], container2, xmlns); + } else if (listValueSchema.isMapSchema()) { + this.writeMap(listValueSchema, value, container2, xmlns); + } else if (listValueSchema.isStructSchema()) { + const struct2 = this.writeStruct(listValueSchema, value, xmlns); + container2.addChildNode(struct2.withName(flat ? listTraits.xmlName ?? listMember.getMemberName() : listValueTraits.xmlName ?? "member")); + } else { + const listItemNode = import_xml_builder3.XmlNode.of(flat ? listTraits.xmlName ?? listMember.getMemberName() : listValueTraits.xmlName ?? "member"); + this.writeSimpleInto(listValueSchema, value, listItemNode, xmlns); + container2.addChildNode(listItemNode); + } + }; + if (flat) { + for (const value of array2) { + if (sparse || value != null) { + writeItem(container, value); + } + } + } else { + const listNode = import_xml_builder3.XmlNode.of(listTraits.xmlName ?? listMember.getMemberName()); + if (xmlns) { + listNode.addAttribute(xmlnsAttr, xmlns); + } + for (const value of array2) { + if (sparse || value != null) { + writeItem(listNode, value); + } + } + container.addChildNode(listNode); + } + } + writeMap(mapMember, map4, container, parentXmlns, containerIsMap = false) { + if (!mapMember.isMemberSchema()) { + throw new Error(`@aws-sdk/core/protocols - xml serializer, cannot write non-member map: ${mapMember.getName(true)}`); + } + const mapTraits = mapMember.getMergedTraits(); + const mapKeySchema = mapMember.getKeySchema(); + const mapKeyTraits = mapKeySchema.getMergedTraits(); + const keyTag = mapKeyTraits.xmlName ?? "key"; + const mapValueSchema = mapMember.getValueSchema(); + const mapValueTraits = mapValueSchema.getMergedTraits(); + const valueTag = mapValueTraits.xmlName ?? "value"; + const sparse = !!mapValueTraits.sparse; + const flat = !!mapTraits.xmlFlattened; + const [xmlnsAttr, xmlns] = this.getXmlnsAttribute(mapMember, parentXmlns); + const addKeyValue = (entry, key, val) => { + const keyNode = import_xml_builder3.XmlNode.of(keyTag, key); + const [keyXmlnsAttr, keyXmlns] = this.getXmlnsAttribute(mapKeySchema, xmlns); + if (keyXmlns) { + keyNode.addAttribute(keyXmlnsAttr, keyXmlns); + } + entry.addChildNode(keyNode); + let valueNode = import_xml_builder3.XmlNode.of(valueTag); + if (mapValueSchema.isListSchema()) { + this.writeList(mapValueSchema, val, valueNode, xmlns); + } else if (mapValueSchema.isMapSchema()) { + this.writeMap(mapValueSchema, val, valueNode, xmlns, true); + } else if (mapValueSchema.isStructSchema()) { + valueNode = this.writeStruct(mapValueSchema, val, xmlns); + } else { + this.writeSimpleInto(mapValueSchema, val, valueNode, xmlns); + } + entry.addChildNode(valueNode); + }; + if (flat) { + for (const [key, val] of Object.entries(map4)) { + if (sparse || val != null) { + const entry = import_xml_builder3.XmlNode.of(mapTraits.xmlName ?? mapMember.getMemberName()); + addKeyValue(entry, key, val); + container.addChildNode(entry); + } + } + } else { + let mapNode; + if (!containerIsMap) { + mapNode = import_xml_builder3.XmlNode.of(mapTraits.xmlName ?? mapMember.getMemberName()); + if (xmlns) { + mapNode.addAttribute(xmlnsAttr, xmlns); + } + container.addChildNode(mapNode); + } + for (const [key, val] of Object.entries(map4)) { + if (sparse || val != null) { + const entry = import_xml_builder3.XmlNode.of("entry"); + addKeyValue(entry, key, val); + (containerIsMap ? container : mapNode).addChildNode(entry); + } + } + } + } + writeSimple(_schema, value) { + if (null === value) { + throw new Error("@aws-sdk/core/protocols - (XML serializer) cannot write null value."); + } + const ns = NormalizedSchema.of(_schema); + let nodeContents = null; + if (value && typeof value === "object") { + if (ns.isBlobSchema()) { + nodeContents = (this.serdeContext?.base64Encoder ?? import_util_base647.toBase64)(value); + } else if (ns.isTimestampSchema() && value instanceof Date) { + const format2 = determineTimestampFormat(ns, this.settings); + switch (format2) { + case 5: + nodeContents = value.toISOString().replace(".000Z", "Z"); + break; + case 6: + nodeContents = (0, import_smithy_client7.dateToUtcString)(value); + break; + case 7: + nodeContents = String(value.getTime() / 1e3); + break; + default: + console.warn("Missing timestamp format, using http date", value); + nodeContents = (0, import_smithy_client7.dateToUtcString)(value); + break; + } + } else if (ns.isBigDecimalSchema() && value) { + if (value instanceof NumericValue) { + return value.string; + } + return String(value); + } else if (ns.isMapSchema() || ns.isListSchema()) { + throw new Error("@aws-sdk/core/protocols - xml serializer, cannot call _write() on List/Map schema, call writeList or writeMap() instead."); + } else { + throw new Error(`@aws-sdk/core/protocols - xml serializer, unhandled schema type for object value and schema: ${ns.getName(true)}`); + } + } + if (ns.isBooleanSchema() || ns.isNumericSchema() || ns.isBigIntegerSchema() || ns.isBigDecimalSchema()) { + nodeContents = String(value); + } + if (ns.isStringSchema()) { + if (value === void 0 && ns.isIdempotencyToken()) { + nodeContents = (0, import_uuid2.v4)(); + } else { + nodeContents = String(value); + } + } + if (nodeContents === null) { + throw new Error(`Unhandled schema-value pair ${ns.getName(true)}=${value}`); + } + return nodeContents; + } + writeSimpleInto(_schema, value, into, parentXmlns) { + const nodeContents = this.writeSimple(_schema, value); + const ns = NormalizedSchema.of(_schema); + const content = new import_xml_builder3.XmlText(nodeContents); + const [xmlnsAttr, xmlns] = this.getXmlnsAttribute(ns, parentXmlns); + if (xmlns) { + into.addAttribute(xmlnsAttr, xmlns); + } + into.addChildNode(content); + } + getXmlnsAttribute(ns, parentXmlns) { + const traits = ns.getMergedTraits(); + const [prefix, xmlns] = traits.xmlNamespace ?? []; + if (xmlns && xmlns !== parentXmlns) { + return [prefix ? `xmlns:${prefix}` : "xmlns", xmlns]; + } + return [void 0, void 0]; + } + }; + } +}); + +// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/xml/XmlCodec.js +var XmlCodec; +var init_XmlCodec = __esm({ + "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/xml/XmlCodec.js"() { + init_ConfigurableSerdeContext(); + init_XmlShapeDeserializer(); + init_XmlShapeSerializer(); + XmlCodec = class extends SerdeContextConfig { + settings; + constructor(settings) { + super(); + this.settings = settings; + } + createSerializer() { + const serializer = new XmlShapeSerializer(this.settings); + serializer.setSerdeContext(this.serdeContext); + return serializer; + } + createDeserializer() { + const deserializer = new XmlShapeDeserializer(this.settings); + deserializer.setSerdeContext(this.serdeContext); + return deserializer; + } + }; + } +}); + +// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/xml/AwsRestXmlProtocol.js +var AwsRestXmlProtocol; +var init_AwsRestXmlProtocol = __esm({ + "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/xml/AwsRestXmlProtocol.js"() { + init_protocols(); + init_schema3(); + init_ProtocolLib(); + init_parseXmlBody(); + init_XmlCodec(); + AwsRestXmlProtocol = class extends HttpBindingProtocol { + codec; + serializer; + deserializer; + mixin = new ProtocolLib(); + constructor(options) { + super(options); + const settings = { + timestampFormat: { + useTrait: true, + default: 5 + }, + httpBindings: true, + xmlNamespace: options.xmlNamespace, + serviceNamespace: options.defaultNamespace + }; + this.codec = new XmlCodec(settings); + this.serializer = new HttpInterceptingShapeSerializer(this.codec.createSerializer(), settings); + this.deserializer = new HttpInterceptingShapeDeserializer(this.codec.createDeserializer(), settings); + this.compositeErrorRegistry; + } + getPayloadCodec() { + return this.codec; + } + getShapeId() { + return "aws.protocols#restXml"; + } + async serializeRequest(operationSchema, input, context) { + const request = await super.serializeRequest(operationSchema, input, context); + const inputSchema = NormalizedSchema.of(operationSchema.input); + if (!request.headers["content-type"]) { + const contentType = this.mixin.resolveRestContentType(this.getDefaultContentType(), inputSchema); + if (contentType) { + request.headers["content-type"] = contentType; + } + } + if (typeof request.body === "string" && request.headers["content-type"] === this.getDefaultContentType() && !request.body.startsWith("' + request.body; + } + return request; + } + async deserializeResponse(operationSchema, context, response) { + return super.deserializeResponse(operationSchema, context, response); + } + async handleError(operationSchema, context, response, dataObject, metadata) { + const errorIdentifier = loadRestXmlErrorCode(response, dataObject) ?? "Unknown"; + this.mixin.compose(this.compositeErrorRegistry, errorIdentifier, this.options.defaultNamespace); + if (dataObject.Error && typeof dataObject.Error === "object") { + for (const key of Object.keys(dataObject.Error)) { + dataObject[key] = dataObject.Error[key]; + if (key.toLowerCase() === "message") { + dataObject.message = dataObject.Error[key]; + } + } + } + if (dataObject.RequestId && !metadata.requestId) { + metadata.requestId = dataObject.RequestId; + } + const { errorSchema, errorMetadata } = await this.mixin.getErrorSchemaOrThrowBaseException(errorIdentifier, this.options.defaultNamespace, response, dataObject, metadata); + const ns = NormalizedSchema.of(errorSchema); + const message2 = dataObject.Error?.message ?? dataObject.Error?.Message ?? dataObject.message ?? dataObject.Message ?? "UnknownError"; + const ErrorCtor = this.compositeErrorRegistry.getErrorCtor(errorSchema) ?? Error; + const exception = new ErrorCtor(message2); + await this.deserializeHttpMessage(errorSchema, context, response, dataObject); + const output = {}; + for (const [name, member2] of ns.structIterator()) { + const target = member2.getMergedTraits().xmlName ?? name; + const value = dataObject.Error?.[target] ?? dataObject[target]; + output[name] = this.codec.createDeserializer().readSchema(member2, value); + } + throw this.mixin.decorateServiceException(Object.assign(exception, errorMetadata, { + $fault: ns.getMergedTraits().error, + message: message2 + }, output), dataObject); + } + getDefaultContentType() { + return "application/xml"; + } + hasUnstructuredPayloadBinding(ns) { + for (const [, member2] of ns.structIterator()) { + if (member2.getMergedTraits().httpPayload) { + return !(member2.isStructSchema() || member2.isMapSchema() || member2.isListSchema()); + } + } + return false; + } + }; + } +}); + +// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/index.js +var protocols_exports2 = {}; +__export(protocols_exports2, { + AwsEc2QueryProtocol: () => AwsEc2QueryProtocol, + AwsJson1_0Protocol: () => AwsJson1_0Protocol, + AwsJson1_1Protocol: () => AwsJson1_1Protocol, + AwsJsonRpcProtocol: () => AwsJsonRpcProtocol, + AwsQueryProtocol: () => AwsQueryProtocol, + AwsRestJsonProtocol: () => AwsRestJsonProtocol, + AwsRestXmlProtocol: () => AwsRestXmlProtocol, + AwsSmithyRpcV2CborProtocol: () => AwsSmithyRpcV2CborProtocol, + JsonCodec: () => JsonCodec, + JsonShapeDeserializer: () => JsonShapeDeserializer, + JsonShapeSerializer: () => JsonShapeSerializer, + QueryShapeSerializer: () => QueryShapeSerializer, + XmlCodec: () => XmlCodec, + XmlShapeDeserializer: () => XmlShapeDeserializer, + XmlShapeSerializer: () => XmlShapeSerializer, + _toBool: () => _toBool, + _toNum: () => _toNum, + _toStr: () => _toStr, + awsExpectUnion: () => awsExpectUnion, + loadRestJsonErrorCode: () => loadRestJsonErrorCode, + loadRestXmlErrorCode: () => loadRestXmlErrorCode, + parseJsonBody: () => parseJsonBody, + parseJsonErrorBody: () => parseJsonErrorBody, + parseXmlBody: () => parseXmlBody, + parseXmlErrorBody: () => parseXmlErrorBody +}); +var init_protocols2 = __esm({ + "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/index.js"() { + init_AwsSmithyRpcV2CborProtocol(); + init_coercing_serializers(); + init_AwsJson1_0Protocol(); + init_AwsJson1_1Protocol(); + init_AwsJsonRpcProtocol(); + init_AwsRestJsonProtocol(); + init_JsonCodec(); + init_JsonShapeDeserializer(); + init_JsonShapeSerializer(); + init_awsExpectUnion(); + init_parseJsonBody(); + init_AwsEc2QueryProtocol(); + init_AwsQueryProtocol(); + init_QuerySerializerSettings(); + init_QueryShapeSerializer(); + init_AwsRestXmlProtocol(); + init_XmlCodec(); + init_XmlShapeDeserializer(); + init_XmlShapeSerializer(); + init_parseXmlBody(); + } +}); + +// node_modules/.pnpm/@smithy+signature-v4@5.3.13/node_modules/@smithy/signature-v4/dist-cjs/index.js +var require_dist_cjs30 = __commonJS({ + "node_modules/.pnpm/@smithy+signature-v4@5.3.13/node_modules/@smithy/signature-v4/dist-cjs/index.js"(exports) { + "use strict"; + var utilHexEncoding = require_dist_cjs12(); + var utilUtf8 = require_dist_cjs6(); + var isArrayBuffer = require_dist_cjs4(); + var protocolHttp = require_dist_cjs2(); + var utilMiddleware = require_dist_cjs18(); + var utilUriEscape = require_dist_cjs8(); + var ALGORITHM_QUERY_PARAM = "X-Amz-Algorithm"; + var CREDENTIAL_QUERY_PARAM = "X-Amz-Credential"; + var AMZ_DATE_QUERY_PARAM = "X-Amz-Date"; + var SIGNED_HEADERS_QUERY_PARAM = "X-Amz-SignedHeaders"; + var EXPIRES_QUERY_PARAM = "X-Amz-Expires"; + var SIGNATURE_QUERY_PARAM = "X-Amz-Signature"; + var TOKEN_QUERY_PARAM = "X-Amz-Security-Token"; + var REGION_SET_PARAM = "X-Amz-Region-Set"; + var AUTH_HEADER = "authorization"; + var AMZ_DATE_HEADER = AMZ_DATE_QUERY_PARAM.toLowerCase(); + var DATE_HEADER = "date"; + var GENERATED_HEADERS = [AUTH_HEADER, AMZ_DATE_HEADER, DATE_HEADER]; + var SIGNATURE_HEADER = SIGNATURE_QUERY_PARAM.toLowerCase(); + var SHA256_HEADER = "x-amz-content-sha256"; + var TOKEN_HEADER = TOKEN_QUERY_PARAM.toLowerCase(); + var HOST_HEADER = "host"; + var ALWAYS_UNSIGNABLE_HEADERS = { + authorization: true, + "cache-control": true, + connection: true, + expect: true, + from: true, + "keep-alive": true, + "max-forwards": true, + pragma: true, + referer: true, + te: true, + trailer: true, + "transfer-encoding": true, + upgrade: true, + "user-agent": true, + "x-amzn-trace-id": true + }; + var PROXY_HEADER_PATTERN = /^proxy-/; + var SEC_HEADER_PATTERN = /^sec-/; + var UNSIGNABLE_PATTERNS = [/^proxy-/i, /^sec-/i]; + var ALGORITHM_IDENTIFIER = "AWS4-HMAC-SHA256"; + var ALGORITHM_IDENTIFIER_V4A = "AWS4-ECDSA-P256-SHA256"; + var EVENT_ALGORITHM_IDENTIFIER = "AWS4-HMAC-SHA256-PAYLOAD"; + var UNSIGNED_PAYLOAD = "UNSIGNED-PAYLOAD"; + var MAX_CACHE_SIZE = 50; + var KEY_TYPE_IDENTIFIER = "aws4_request"; + var MAX_PRESIGNED_TTL = 60 * 60 * 24 * 7; + var signingKeyCache = {}; + var cacheQueue = []; + var createScope = (shortDate, region, service) => `${shortDate}/${region}/${service}/${KEY_TYPE_IDENTIFIER}`; + var getSigningKey = async (sha256Constructor, credentials, shortDate, region, service) => { + const credsHash = await hmac3(sha256Constructor, credentials.secretAccessKey, credentials.accessKeyId); + const cacheKey = `${shortDate}:${region}:${service}:${utilHexEncoding.toHex(credsHash)}:${credentials.sessionToken}`; + if (cacheKey in signingKeyCache) { + return signingKeyCache[cacheKey]; + } + cacheQueue.push(cacheKey); + while (cacheQueue.length > MAX_CACHE_SIZE) { + delete signingKeyCache[cacheQueue.shift()]; + } + let key = `AWS4${credentials.secretAccessKey}`; + for (const signable of [shortDate, region, service, KEY_TYPE_IDENTIFIER]) { + key = await hmac3(sha256Constructor, key, signable); + } + return signingKeyCache[cacheKey] = key; + }; + var clearCredentialCache = () => { + cacheQueue.length = 0; + Object.keys(signingKeyCache).forEach((cacheKey) => { + delete signingKeyCache[cacheKey]; + }); + }; + var hmac3 = (ctor, secret, data2) => { + const hash2 = new ctor(secret); + hash2.update(utilUtf8.toUint8Array(data2)); + return hash2.digest(); + }; + var getCanonicalHeaders = ({ headers }, unsignableHeaders, signableHeaders) => { + const canonical = {}; + for (const headerName of Object.keys(headers).sort()) { + if (headers[headerName] == void 0) { + continue; + } + const canonicalHeaderName = headerName.toLowerCase(); + if (canonicalHeaderName in ALWAYS_UNSIGNABLE_HEADERS || unsignableHeaders?.has(canonicalHeaderName) || PROXY_HEADER_PATTERN.test(canonicalHeaderName) || SEC_HEADER_PATTERN.test(canonicalHeaderName)) { + if (!signableHeaders || signableHeaders && !signableHeaders.has(canonicalHeaderName)) { + continue; + } + } + canonical[canonicalHeaderName] = headers[headerName].trim().replace(/\s+/g, " "); + } + return canonical; + }; + var getPayloadHash = async ({ headers, body }, hashConstructor) => { + for (const headerName of Object.keys(headers)) { + if (headerName.toLowerCase() === SHA256_HEADER) { + return headers[headerName]; + } + } + if (body == void 0) { + return "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"; + } else if (typeof body === "string" || ArrayBuffer.isView(body) || isArrayBuffer.isArrayBuffer(body)) { + const hashCtor = new hashConstructor(); + hashCtor.update(utilUtf8.toUint8Array(body)); + return utilHexEncoding.toHex(await hashCtor.digest()); + } + return UNSIGNED_PAYLOAD; + }; + var HeaderFormatter = class { + format(headers) { + const chunks = []; + for (const headerName of Object.keys(headers)) { + const bytes = utilUtf8.fromUtf8(headerName); + chunks.push(Uint8Array.from([bytes.byteLength]), bytes, this.formatHeaderValue(headers[headerName])); + } + const out = new Uint8Array(chunks.reduce((carry, bytes) => carry + bytes.byteLength, 0)); + let position = 0; + for (const chunk of chunks) { + out.set(chunk, position); + position += chunk.byteLength; + } + return out; + } + formatHeaderValue(header) { + switch (header.type) { + case "boolean": + return Uint8Array.from([header.value ? 0 : 1]); + case "byte": + return Uint8Array.from([2, header.value]); + case "short": + const shortView = new DataView(new ArrayBuffer(3)); + shortView.setUint8(0, 3); + shortView.setInt16(1, header.value, false); + return new Uint8Array(shortView.buffer); + case "integer": + const intView = new DataView(new ArrayBuffer(5)); + intView.setUint8(0, 4); + intView.setInt32(1, header.value, false); + return new Uint8Array(intView.buffer); + case "long": + const longBytes = new Uint8Array(9); + longBytes[0] = 5; + longBytes.set(header.value.bytes, 1); + return longBytes; + case "binary": + const binView = new DataView(new ArrayBuffer(3 + header.value.byteLength)); + binView.setUint8(0, 6); + binView.setUint16(1, header.value.byteLength, false); + const binBytes = new Uint8Array(binView.buffer); + binBytes.set(header.value, 3); + return binBytes; + case "string": + const utf8Bytes = utilUtf8.fromUtf8(header.value); + const strView = new DataView(new ArrayBuffer(3 + utf8Bytes.byteLength)); + strView.setUint8(0, 7); + strView.setUint16(1, utf8Bytes.byteLength, false); + const strBytes = new Uint8Array(strView.buffer); + strBytes.set(utf8Bytes, 3); + return strBytes; + case "timestamp": + const tsBytes = new Uint8Array(9); + tsBytes[0] = 8; + tsBytes.set(Int64.fromNumber(header.value.valueOf()).bytes, 1); + return tsBytes; + case "uuid": + if (!UUID_PATTERN2.test(header.value)) { + throw new Error(`Invalid UUID received: ${header.value}`); + } + const uuidBytes = new Uint8Array(17); + uuidBytes[0] = 9; + uuidBytes.set(utilHexEncoding.fromHex(header.value.replace(/\-/g, "")), 1); + return uuidBytes; + } + } + }; + var HEADER_VALUE_TYPE; + (function(HEADER_VALUE_TYPE2) { + HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["boolTrue"] = 0] = "boolTrue"; + HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["boolFalse"] = 1] = "boolFalse"; + HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["byte"] = 2] = "byte"; + HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["short"] = 3] = "short"; + HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["integer"] = 4] = "integer"; + HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["long"] = 5] = "long"; + HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["byteArray"] = 6] = "byteArray"; + HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["string"] = 7] = "string"; + HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["timestamp"] = 8] = "timestamp"; + HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["uuid"] = 9] = "uuid"; + })(HEADER_VALUE_TYPE || (HEADER_VALUE_TYPE = {})); + var UUID_PATTERN2 = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/; + var Int64 = class _Int64 { + bytes; + constructor(bytes) { + this.bytes = bytes; + if (bytes.byteLength !== 8) { + throw new Error("Int64 buffers must be exactly 8 bytes"); + } + } + static fromNumber(number4) { + if (number4 > 9223372036854776e3 || number4 < -9223372036854776e3) { + throw new Error(`${number4} is too large (or, if negative, too small) to represent as an Int64`); + } + const bytes = new Uint8Array(8); + for (let i5 = 7, remaining = Math.abs(Math.round(number4)); i5 > -1 && remaining > 0; i5--, remaining /= 256) { + bytes[i5] = remaining; + } + if (number4 < 0) { + negate(bytes); + } + return new _Int64(bytes); + } + valueOf() { + const bytes = this.bytes.slice(0); + const negative = bytes[0] & 128; + if (negative) { + negate(bytes); + } + return parseInt(utilHexEncoding.toHex(bytes), 16) * (negative ? -1 : 1); + } + toString() { + return String(this.valueOf()); + } + }; + function negate(bytes) { + for (let i5 = 0; i5 < 8; i5++) { + bytes[i5] ^= 255; + } + for (let i5 = 7; i5 > -1; i5--) { + bytes[i5]++; + if (bytes[i5] !== 0) + break; + } + } + var hasHeader = (soughtHeader, headers) => { + soughtHeader = soughtHeader.toLowerCase(); + for (const headerName of Object.keys(headers)) { + if (soughtHeader === headerName.toLowerCase()) { + return true; + } + } + return false; + }; + var moveHeadersToQuery = (request, options = {}) => { + const { headers, query = {} } = protocolHttp.HttpRequest.clone(request); + for (const name of Object.keys(headers)) { + const lname = name.toLowerCase(); + if (lname.slice(0, 6) === "x-amz-" && !options.unhoistableHeaders?.has(lname) || options.hoistableHeaders?.has(lname)) { + query[name] = headers[name]; + delete headers[name]; + } + } + return { + ...request, + headers, + query + }; + }; + var prepareRequest = (request) => { + request = protocolHttp.HttpRequest.clone(request); + for (const headerName of Object.keys(request.headers)) { + if (GENERATED_HEADERS.indexOf(headerName.toLowerCase()) > -1) { + delete request.headers[headerName]; + } + } + return request; + }; + var getCanonicalQuery = ({ query = {} }) => { + const keys = []; + const serialized = {}; + for (const key of Object.keys(query)) { + if (key.toLowerCase() === SIGNATURE_HEADER) { + continue; + } + const encodedKey = utilUriEscape.escapeUri(key); + keys.push(encodedKey); + const value = query[key]; + if (typeof value === "string") { + serialized[encodedKey] = `${encodedKey}=${utilUriEscape.escapeUri(value)}`; + } else if (Array.isArray(value)) { + serialized[encodedKey] = value.slice(0).reduce((encoded, value2) => encoded.concat([`${encodedKey}=${utilUriEscape.escapeUri(value2)}`]), []).sort().join("&"); + } + } + return keys.sort().map((key) => serialized[key]).filter((serialized2) => serialized2).join("&"); + }; + var iso8601 = (time5) => toDate2(time5).toISOString().replace(/\.\d{3}Z$/, "Z"); + var toDate2 = (time5) => { + if (typeof time5 === "number") { + return new Date(time5 * 1e3); + } + if (typeof time5 === "string") { + if (Number(time5)) { + return new Date(Number(time5) * 1e3); + } + return new Date(time5); + } + return time5; + }; + var SignatureV4Base = class { + service; + regionProvider; + credentialProvider; + sha256; + uriEscapePath; + applyChecksum; + constructor({ applyChecksum, credentials, region, service, sha256: sha2563, uriEscapePath = true }) { + this.service = service; + this.sha256 = sha2563; + this.uriEscapePath = uriEscapePath; + this.applyChecksum = typeof applyChecksum === "boolean" ? applyChecksum : true; + this.regionProvider = utilMiddleware.normalizeProvider(region); + this.credentialProvider = utilMiddleware.normalizeProvider(credentials); + } + createCanonicalRequest(request, canonicalHeaders, payloadHash) { + const sortedHeaders = Object.keys(canonicalHeaders).sort(); + return `${request.method} +${this.getCanonicalPath(request)} +${getCanonicalQuery(request)} +${sortedHeaders.map((name) => `${name}:${canonicalHeaders[name]}`).join("\n")} + +${sortedHeaders.join(";")} +${payloadHash}`; + } + async createStringToSign(longDate, credentialScope, canonicalRequest, algorithmIdentifier) { + const hash2 = new this.sha256(); + hash2.update(utilUtf8.toUint8Array(canonicalRequest)); + const hashedRequest = await hash2.digest(); + return `${algorithmIdentifier} +${longDate} +${credentialScope} +${utilHexEncoding.toHex(hashedRequest)}`; + } + getCanonicalPath({ path: path53 }) { + if (this.uriEscapePath) { + const normalizedPathSegments = []; + for (const pathSegment of path53.split("/")) { + if (pathSegment?.length === 0) + continue; + if (pathSegment === ".") + continue; + if (pathSegment === "..") { + normalizedPathSegments.pop(); + } else { + normalizedPathSegments.push(pathSegment); + } + } + const normalizedPath = `${path53?.startsWith("/") ? "/" : ""}${normalizedPathSegments.join("/")}${normalizedPathSegments.length > 0 && path53?.endsWith("/") ? "/" : ""}`; + const doubleEncoded = utilUriEscape.escapeUri(normalizedPath); + return doubleEncoded.replace(/%2F/g, "/"); + } + return path53; + } + validateResolvedCredentials(credentials) { + if (typeof credentials !== "object" || typeof credentials.accessKeyId !== "string" || typeof credentials.secretAccessKey !== "string") { + throw new Error("Resolved credential object is not valid"); + } + } + formatDate(now2) { + const longDate = iso8601(now2).replace(/[\-:]/g, ""); + return { + longDate, + shortDate: longDate.slice(0, 8) + }; + } + getCanonicalHeaderList(headers) { + return Object.keys(headers).sort().join(";"); + } + }; + var SignatureV42 = class extends SignatureV4Base { + headerFormatter = new HeaderFormatter(); + constructor({ applyChecksum, credentials, region, service, sha256: sha2563, uriEscapePath = true }) { + super({ + applyChecksum, + credentials, + region, + service, + sha256: sha2563, + uriEscapePath + }); + } + async presign(originalRequest, options = {}) { + const { signingDate = /* @__PURE__ */ new Date(), expiresIn = 3600, unsignableHeaders, unhoistableHeaders, signableHeaders, hoistableHeaders, signingRegion, signingService } = options; + const credentials = await this.credentialProvider(); + this.validateResolvedCredentials(credentials); + const region = signingRegion ?? await this.regionProvider(); + const { longDate, shortDate } = this.formatDate(signingDate); + if (expiresIn > MAX_PRESIGNED_TTL) { + return Promise.reject("Signature version 4 presigned URLs must have an expiration date less than one week in the future"); + } + const scope = createScope(shortDate, region, signingService ?? this.service); + const request = moveHeadersToQuery(prepareRequest(originalRequest), { unhoistableHeaders, hoistableHeaders }); + if (credentials.sessionToken) { + request.query[TOKEN_QUERY_PARAM] = credentials.sessionToken; + } + request.query[ALGORITHM_QUERY_PARAM] = ALGORITHM_IDENTIFIER; + request.query[CREDENTIAL_QUERY_PARAM] = `${credentials.accessKeyId}/${scope}`; + request.query[AMZ_DATE_QUERY_PARAM] = longDate; + request.query[EXPIRES_QUERY_PARAM] = expiresIn.toString(10); + const canonicalHeaders = getCanonicalHeaders(request, unsignableHeaders, signableHeaders); + request.query[SIGNED_HEADERS_QUERY_PARAM] = this.getCanonicalHeaderList(canonicalHeaders); + request.query[SIGNATURE_QUERY_PARAM] = await this.getSignature(longDate, scope, this.getSigningKey(credentials, region, shortDate, signingService), this.createCanonicalRequest(request, canonicalHeaders, await getPayloadHash(originalRequest, this.sha256))); + return request; + } + async sign(toSign, options) { + if (typeof toSign === "string") { + return this.signString(toSign, options); + } else if (toSign.headers && toSign.payload) { + return this.signEvent(toSign, options); + } else if (toSign.message) { + return this.signMessage(toSign, options); + } else { + return this.signRequest(toSign, options); + } + } + async signEvent({ headers, payload: payload2 }, { signingDate = /* @__PURE__ */ new Date(), priorSignature, signingRegion, signingService }) { + const region = signingRegion ?? await this.regionProvider(); + const { shortDate, longDate } = this.formatDate(signingDate); + const scope = createScope(shortDate, region, signingService ?? this.service); + const hashedPayload = await getPayloadHash({ headers: {}, body: payload2 }, this.sha256); + const hash2 = new this.sha256(); + hash2.update(headers); + const hashedHeaders = utilHexEncoding.toHex(await hash2.digest()); + const stringToSign = [ + EVENT_ALGORITHM_IDENTIFIER, + longDate, + scope, + priorSignature, + hashedHeaders, + hashedPayload + ].join("\n"); + return this.signString(stringToSign, { signingDate, signingRegion: region, signingService }); + } + async signMessage(signableMessage, { signingDate = /* @__PURE__ */ new Date(), signingRegion, signingService }) { + const promise2 = this.signEvent({ + headers: this.headerFormatter.format(signableMessage.message.headers), + payload: signableMessage.message.body + }, { + signingDate, + signingRegion, + signingService, + priorSignature: signableMessage.priorSignature + }); + return promise2.then((signature) => { + return { message: signableMessage.message, signature }; + }); + } + async signString(stringToSign, { signingDate = /* @__PURE__ */ new Date(), signingRegion, signingService } = {}) { + const credentials = await this.credentialProvider(); + this.validateResolvedCredentials(credentials); + const region = signingRegion ?? await this.regionProvider(); + const { shortDate } = this.formatDate(signingDate); + const hash2 = new this.sha256(await this.getSigningKey(credentials, region, shortDate, signingService)); + hash2.update(utilUtf8.toUint8Array(stringToSign)); + return utilHexEncoding.toHex(await hash2.digest()); + } + async signRequest(requestToSign, { signingDate = /* @__PURE__ */ new Date(), signableHeaders, unsignableHeaders, signingRegion, signingService } = {}) { + const credentials = await this.credentialProvider(); + this.validateResolvedCredentials(credentials); + const region = signingRegion ?? await this.regionProvider(); + const request = prepareRequest(requestToSign); + const { longDate, shortDate } = this.formatDate(signingDate); + const scope = createScope(shortDate, region, signingService ?? this.service); + request.headers[AMZ_DATE_HEADER] = longDate; + if (credentials.sessionToken) { + request.headers[TOKEN_HEADER] = credentials.sessionToken; + } + const payloadHash = await getPayloadHash(request, this.sha256); + if (!hasHeader(SHA256_HEADER, request.headers) && this.applyChecksum) { + request.headers[SHA256_HEADER] = payloadHash; + } + const canonicalHeaders = getCanonicalHeaders(request, unsignableHeaders, signableHeaders); + const signature = await this.getSignature(longDate, scope, this.getSigningKey(credentials, region, shortDate, signingService), this.createCanonicalRequest(request, canonicalHeaders, payloadHash)); + request.headers[AUTH_HEADER] = `${ALGORITHM_IDENTIFIER} Credential=${credentials.accessKeyId}/${scope}, SignedHeaders=${this.getCanonicalHeaderList(canonicalHeaders)}, Signature=${signature}`; + return request; + } + async getSignature(longDate, credentialScope, keyPromise, canonicalRequest) { + const stringToSign = await this.createStringToSign(longDate, credentialScope, canonicalRequest, ALGORITHM_IDENTIFIER); + const hash2 = new this.sha256(await keyPromise); + hash2.update(utilUtf8.toUint8Array(stringToSign)); + return utilHexEncoding.toHex(await hash2.digest()); + } + getSigningKey(credentials, region, shortDate, service) { + return getSigningKey(this.sha256, credentials, shortDate, region, service || this.service); + } + }; + var signatureV4aContainer = { + SignatureV4a: null + }; + exports.ALGORITHM_IDENTIFIER = ALGORITHM_IDENTIFIER; + exports.ALGORITHM_IDENTIFIER_V4A = ALGORITHM_IDENTIFIER_V4A; + exports.ALGORITHM_QUERY_PARAM = ALGORITHM_QUERY_PARAM; + exports.ALWAYS_UNSIGNABLE_HEADERS = ALWAYS_UNSIGNABLE_HEADERS; + exports.AMZ_DATE_HEADER = AMZ_DATE_HEADER; + exports.AMZ_DATE_QUERY_PARAM = AMZ_DATE_QUERY_PARAM; + exports.AUTH_HEADER = AUTH_HEADER; + exports.CREDENTIAL_QUERY_PARAM = CREDENTIAL_QUERY_PARAM; + exports.DATE_HEADER = DATE_HEADER; + exports.EVENT_ALGORITHM_IDENTIFIER = EVENT_ALGORITHM_IDENTIFIER; + exports.EXPIRES_QUERY_PARAM = EXPIRES_QUERY_PARAM; + exports.GENERATED_HEADERS = GENERATED_HEADERS; + exports.HOST_HEADER = HOST_HEADER; + exports.KEY_TYPE_IDENTIFIER = KEY_TYPE_IDENTIFIER; + exports.MAX_CACHE_SIZE = MAX_CACHE_SIZE; + exports.MAX_PRESIGNED_TTL = MAX_PRESIGNED_TTL; + exports.PROXY_HEADER_PATTERN = PROXY_HEADER_PATTERN; + exports.REGION_SET_PARAM = REGION_SET_PARAM; + exports.SEC_HEADER_PATTERN = SEC_HEADER_PATTERN; + exports.SHA256_HEADER = SHA256_HEADER; + exports.SIGNATURE_HEADER = SIGNATURE_HEADER; + exports.SIGNATURE_QUERY_PARAM = SIGNATURE_QUERY_PARAM; + exports.SIGNED_HEADERS_QUERY_PARAM = SIGNED_HEADERS_QUERY_PARAM; + exports.SignatureV4 = SignatureV42; + exports.SignatureV4Base = SignatureV4Base; + exports.TOKEN_HEADER = TOKEN_HEADER; + exports.TOKEN_QUERY_PARAM = TOKEN_QUERY_PARAM; + exports.UNSIGNABLE_PATTERNS = UNSIGNABLE_PATTERNS; + exports.UNSIGNED_PAYLOAD = UNSIGNED_PAYLOAD; + exports.clearCredentialCache = clearCredentialCache; + exports.createScope = createScope; + exports.getCanonicalHeaders = getCanonicalHeaders; + exports.getCanonicalQuery = getCanonicalQuery; + exports.getPayloadHash = getPayloadHash; + exports.getSigningKey = getSigningKey; + exports.hasHeader = hasHeader; + exports.moveHeadersToQuery = moveHeadersToQuery; + exports.prepareRequest = prepareRequest; + exports.signatureV4aContainer = signatureV4aContainer; + } +}); + +// node_modules/.pnpm/@smithy+util-config-provider@4.2.2/node_modules/@smithy/util-config-provider/dist-cjs/index.js +var require_dist_cjs31 = __commonJS({ + "node_modules/.pnpm/@smithy+util-config-provider@4.2.2/node_modules/@smithy/util-config-provider/dist-cjs/index.js"(exports) { + "use strict"; + var booleanSelector = (obj, key, type) => { + if (!(key in obj)) + return void 0; + if (obj[key] === "true") + return true; + if (obj[key] === "false") + return false; + throw new Error(`Cannot load ${type} "${key}". Expected "true" or "false", got ${obj[key]}.`); + }; + var numberSelector = (obj, key, type) => { + if (!(key in obj)) + return void 0; + const numberValue = parseInt(obj[key], 10); + if (Number.isNaN(numberValue)) { + throw new TypeError(`Cannot load ${type} '${key}'. Expected number, got '${obj[key]}'.`); + } + return numberValue; + }; + exports.SelectorType = void 0; + (function(SelectorType) { + SelectorType["ENV"] = "env"; + SelectorType["CONFIG"] = "shared config entry"; + })(exports.SelectorType || (exports.SelectorType = {})); + exports.booleanSelector = booleanSelector; + exports.numberSelector = numberSelector; + } +}); + +// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/getSmithyContext.js +var import_types3, getSmithyContext4; +var init_getSmithyContext = __esm({ + "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/getSmithyContext.js"() { + import_types3 = __toESM(require_dist_cjs()); + getSmithyContext4 = (context) => context[import_types3.SMITHY_CONTEXT_KEY] || (context[import_types3.SMITHY_CONTEXT_KEY] = {}); + } +}); + +// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/resolveAuthOptions.js +var resolveAuthOptions; +var init_resolveAuthOptions = __esm({ + "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/resolveAuthOptions.js"() { + resolveAuthOptions = (candidateAuthOptions, authSchemePreference) => { + if (!authSchemePreference || authSchemePreference.length === 0) { + return candidateAuthOptions; + } + const preferredAuthOptions = []; + for (const preferredSchemeName of authSchemePreference) { + for (const candidateAuthOption of candidateAuthOptions) { + const candidateAuthSchemeName = candidateAuthOption.schemeId.split("#")[1]; + if (candidateAuthSchemeName === preferredSchemeName) { + preferredAuthOptions.push(candidateAuthOption); + } + } + } + for (const candidateAuthOption of candidateAuthOptions) { + if (!preferredAuthOptions.find(({ schemeId }) => schemeId === candidateAuthOption.schemeId)) { + preferredAuthOptions.push(candidateAuthOption); + } + } + return preferredAuthOptions; + }; + } +}); + +// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/httpAuthSchemeMiddleware.js +function convertHttpAuthSchemesToMap(httpAuthSchemes) { + const map4 = /* @__PURE__ */ new Map(); + for (const scheme of httpAuthSchemes) { + map4.set(scheme.schemeId, scheme); + } + return map4; +} +var import_util_middleware4, httpAuthSchemeMiddleware; +var init_httpAuthSchemeMiddleware = __esm({ + "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/httpAuthSchemeMiddleware.js"() { + import_util_middleware4 = __toESM(require_dist_cjs18()); + init_resolveAuthOptions(); + httpAuthSchemeMiddleware = (config3, mwOptions) => (next, context) => async (args) => { + const options = config3.httpAuthSchemeProvider(await mwOptions.httpAuthSchemeParametersProvider(config3, context, args.input)); + const authSchemePreference = config3.authSchemePreference ? await config3.authSchemePreference() : []; + const resolvedOptions = resolveAuthOptions(options, authSchemePreference); + const authSchemes = convertHttpAuthSchemesToMap(config3.httpAuthSchemes); + const smithyContext = (0, import_util_middleware4.getSmithyContext)(context); + const failureReasons = []; + for (const option of resolvedOptions) { + const scheme = authSchemes.get(option.schemeId); + if (!scheme) { + failureReasons.push(`HttpAuthScheme \`${option.schemeId}\` was not enabled for this service.`); + continue; + } + const identityProvider = scheme.identityProvider(await mwOptions.identityProviderConfigProvider(config3)); + if (!identityProvider) { + failureReasons.push(`HttpAuthScheme \`${option.schemeId}\` did not have an IdentityProvider configured.`); + continue; + } + const { identityProperties = {}, signingProperties = {} } = option.propertiesExtractor?.(config3, context) || {}; + option.identityProperties = Object.assign(option.identityProperties || {}, identityProperties); + option.signingProperties = Object.assign(option.signingProperties || {}, signingProperties); + smithyContext.selectedHttpAuthScheme = { + httpAuthOption: option, + identity: await identityProvider(option.identityProperties), + signer: scheme.signer + }; + break; + } + if (!smithyContext.selectedHttpAuthScheme) { + throw new Error(failureReasons.join("\n")); + } + return next(args); + }; + } +}); + +// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/getHttpAuthSchemeEndpointRuleSetPlugin.js +var httpAuthSchemeEndpointRuleSetMiddlewareOptions, getHttpAuthSchemeEndpointRuleSetPlugin; +var init_getHttpAuthSchemeEndpointRuleSetPlugin = __esm({ + "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/getHttpAuthSchemeEndpointRuleSetPlugin.js"() { + init_httpAuthSchemeMiddleware(); + httpAuthSchemeEndpointRuleSetMiddlewareOptions = { + step: "serialize", + tags: ["HTTP_AUTH_SCHEME"], + name: "httpAuthSchemeMiddleware", + override: true, + relation: "before", + toMiddleware: "endpointV2Middleware" + }; + getHttpAuthSchemeEndpointRuleSetPlugin = (config3, { httpAuthSchemeParametersProvider, identityProviderConfigProvider }) => ({ + applyToStack: (clientStack) => { + clientStack.addRelativeTo(httpAuthSchemeMiddleware(config3, { + httpAuthSchemeParametersProvider, + identityProviderConfigProvider + }), httpAuthSchemeEndpointRuleSetMiddlewareOptions); + } + }); + } +}); + +// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/getHttpAuthSchemePlugin.js +var httpAuthSchemeMiddlewareOptions, getHttpAuthSchemePlugin; +var init_getHttpAuthSchemePlugin = __esm({ + "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/getHttpAuthSchemePlugin.js"() { + init_httpAuthSchemeMiddleware(); + httpAuthSchemeMiddlewareOptions = { + step: "serialize", + tags: ["HTTP_AUTH_SCHEME"], + name: "httpAuthSchemeMiddleware", + override: true, + relation: "before", + toMiddleware: "serializerMiddleware" + }; + getHttpAuthSchemePlugin = (config3, { httpAuthSchemeParametersProvider, identityProviderConfigProvider }) => ({ + applyToStack: (clientStack) => { + clientStack.addRelativeTo(httpAuthSchemeMiddleware(config3, { + httpAuthSchemeParametersProvider, + identityProviderConfigProvider + }), httpAuthSchemeMiddlewareOptions); + } + }); + } +}); + +// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/index.js +var init_middleware_http_auth_scheme = __esm({ + "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/index.js"() { + init_httpAuthSchemeMiddleware(); + init_getHttpAuthSchemeEndpointRuleSetPlugin(); + init_getHttpAuthSchemePlugin(); + } +}); + +// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/middleware-http-signing/httpSigningMiddleware.js +var import_protocol_http6, import_util_middleware5, defaultErrorHandler, defaultSuccessHandler, httpSigningMiddleware; +var init_httpSigningMiddleware = __esm({ + "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/middleware-http-signing/httpSigningMiddleware.js"() { + import_protocol_http6 = __toESM(require_dist_cjs2()); + import_util_middleware5 = __toESM(require_dist_cjs18()); + defaultErrorHandler = (signingProperties) => (error50) => { + throw error50; + }; + defaultSuccessHandler = (httpResponse, signingProperties) => { + }; + httpSigningMiddleware = (config3) => (next, context) => async (args) => { + if (!import_protocol_http6.HttpRequest.isInstance(args.request)) { + return next(args); + } + const smithyContext = (0, import_util_middleware5.getSmithyContext)(context); + const scheme = smithyContext.selectedHttpAuthScheme; + if (!scheme) { + throw new Error(`No HttpAuthScheme was selected: unable to sign request`); + } + const { httpAuthOption: { signingProperties = {} }, identity, signer } = scheme; + const output = await next({ + ...args, + request: await signer.sign(args.request, identity, signingProperties) + }).catch((signer.errorHandler || defaultErrorHandler)(signingProperties)); + (signer.successHandler || defaultSuccessHandler)(output.response, signingProperties); + return output; + }; + } +}); + +// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/middleware-http-signing/getHttpSigningMiddleware.js +var httpSigningMiddlewareOptions, getHttpSigningPlugin; +var init_getHttpSigningMiddleware = __esm({ + "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/middleware-http-signing/getHttpSigningMiddleware.js"() { + init_httpSigningMiddleware(); + httpSigningMiddlewareOptions = { + step: "finalizeRequest", + tags: ["HTTP_SIGNING"], + name: "httpSigningMiddleware", + aliases: ["apiKeyMiddleware", "tokenMiddleware", "awsAuthMiddleware"], + override: true, + relation: "after", + toMiddleware: "retryMiddleware" + }; + getHttpSigningPlugin = (config3) => ({ + applyToStack: (clientStack) => { + clientStack.addRelativeTo(httpSigningMiddleware(config3), httpSigningMiddlewareOptions); + } + }); + } +}); + +// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/middleware-http-signing/index.js +var init_middleware_http_signing = __esm({ + "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/middleware-http-signing/index.js"() { + init_httpSigningMiddleware(); + init_getHttpSigningMiddleware(); + } +}); + +// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/normalizeProvider.js +var normalizeProvider; +var init_normalizeProvider = __esm({ + "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/normalizeProvider.js"() { + normalizeProvider = (input) => { + if (typeof input === "function") + return input; + const promisified = Promise.resolve(input); + return () => promisified; + }; + } +}); + +// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/pagination/createPaginator.js +function createPaginator(ClientCtor, CommandCtor, inputTokenName, outputTokenName, pageSizeTokenName) { + return async function* paginateOperation(config3, input, ...additionalArguments) { + const _input = input; + let token = config3.startingToken ?? _input[inputTokenName]; + let hasNext = true; + let page; + while (hasNext) { + _input[inputTokenName] = token; + if (pageSizeTokenName) { + _input[pageSizeTokenName] = _input[pageSizeTokenName] ?? config3.pageSize; + } + if (config3.client instanceof ClientCtor) { + page = await makePagedClientRequest(CommandCtor, config3.client, input, config3.withCommand, ...additionalArguments); + } else { + throw new Error(`Invalid client, expected instance of ${ClientCtor.name}`); + } + yield page; + const prevToken = token; + token = get(page, outputTokenName); + hasNext = !!(token && (!config3.stopOnSameToken || token !== prevToken)); + } + return void 0; + }; +} +var makePagedClientRequest, get; +var init_createPaginator = __esm({ + "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/pagination/createPaginator.js"() { + makePagedClientRequest = async (CommandCtor, client2, input, withCommand = (_) => _, ...args) => { + let command = new CommandCtor(input); + command = withCommand(command) ?? command; + return await client2.send(command, ...args); + }; + get = (fromObject, path53) => { + let cursor2 = fromObject; + const pathComponents = path53.split("."); + for (const step of pathComponents) { + if (!cursor2 || typeof cursor2 !== "object") { + return void 0; + } + cursor2 = cursor2[step]; + } + return cursor2; + }; + } +}); + +// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/request-builder/requestBuilder.js +var init_requestBuilder2 = __esm({ + "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/request-builder/requestBuilder.js"() { + init_protocols(); + } +}); + +// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/setFeature.js +function setFeature2(context, feature, value) { + if (!context.__smithy_context) { + context.__smithy_context = { + features: {} + }; + } else if (!context.__smithy_context.features) { + context.__smithy_context.features = {}; + } + context.__smithy_context.features[feature] = value; +} +var init_setFeature2 = __esm({ + "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/setFeature.js"() { + } +}); + +// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/util-identity-and-auth/DefaultIdentityProviderConfig.js +var DefaultIdentityProviderConfig; +var init_DefaultIdentityProviderConfig = __esm({ + "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/util-identity-and-auth/DefaultIdentityProviderConfig.js"() { + DefaultIdentityProviderConfig = class { + authSchemes = /* @__PURE__ */ new Map(); + constructor(config3) { + for (const [key, value] of Object.entries(config3)) { + if (value !== void 0) { + this.authSchemes.set(key, value); + } + } + } + getIdentityProvider(schemeId) { + return this.authSchemes.get(schemeId); + } + }; + } +}); + +// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/httpApiKeyAuth.js +var import_protocol_http7, import_types4, HttpApiKeyAuthSigner; +var init_httpApiKeyAuth = __esm({ + "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/httpApiKeyAuth.js"() { + import_protocol_http7 = __toESM(require_dist_cjs2()); + import_types4 = __toESM(require_dist_cjs()); + HttpApiKeyAuthSigner = class { + async sign(httpRequest2, identity, signingProperties) { + if (!signingProperties) { + throw new Error("request could not be signed with `apiKey` since the `name` and `in` signer properties are missing"); + } + if (!signingProperties.name) { + throw new Error("request could not be signed with `apiKey` since the `name` signer property is missing"); + } + if (!signingProperties.in) { + throw new Error("request could not be signed with `apiKey` since the `in` signer property is missing"); + } + if (!identity.apiKey) { + throw new Error("request could not be signed with `apiKey` since the `apiKey` is not defined"); + } + const clonedRequest = import_protocol_http7.HttpRequest.clone(httpRequest2); + if (signingProperties.in === import_types4.HttpApiKeyAuthLocation.QUERY) { + clonedRequest.query[signingProperties.name] = identity.apiKey; + } else if (signingProperties.in === import_types4.HttpApiKeyAuthLocation.HEADER) { + clonedRequest.headers[signingProperties.name] = signingProperties.scheme ? `${signingProperties.scheme} ${identity.apiKey}` : identity.apiKey; + } else { + throw new Error("request can only be signed with `apiKey` locations `query` or `header`, but found: `" + signingProperties.in + "`"); + } + return clonedRequest; + } + }; + } +}); + +// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/httpBearerAuth.js +var import_protocol_http8, HttpBearerAuthSigner; +var init_httpBearerAuth = __esm({ + "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/httpBearerAuth.js"() { + import_protocol_http8 = __toESM(require_dist_cjs2()); + HttpBearerAuthSigner = class { + async sign(httpRequest2, identity, signingProperties) { + const clonedRequest = import_protocol_http8.HttpRequest.clone(httpRequest2); + if (!identity.token) { + throw new Error("request could not be signed with `token` since the `token` is not defined"); + } + clonedRequest.headers["Authorization"] = `Bearer ${identity.token}`; + return clonedRequest; + } + }; + } +}); + +// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/noAuth.js +var NoAuthSigner; +var init_noAuth = __esm({ + "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/noAuth.js"() { + NoAuthSigner = class { + async sign(httpRequest2, identity, signingProperties) { + return httpRequest2; + } + }; + } +}); + +// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/index.js +var init_httpAuthSchemes = __esm({ + "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/index.js"() { + init_httpApiKeyAuth(); + init_httpBearerAuth(); + init_noAuth(); + } +}); + +// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/util-identity-and-auth/memoizeIdentityProvider.js +var createIsIdentityExpiredFunction, EXPIRATION_MS, isIdentityExpired, doesIdentityRequireRefresh, memoizeIdentityProvider; +var init_memoizeIdentityProvider = __esm({ + "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/util-identity-and-auth/memoizeIdentityProvider.js"() { + createIsIdentityExpiredFunction = (expirationMs) => function isIdentityExpired2(identity) { + return doesIdentityRequireRefresh(identity) && identity.expiration.getTime() - Date.now() < expirationMs; + }; + EXPIRATION_MS = 3e5; + isIdentityExpired = createIsIdentityExpiredFunction(EXPIRATION_MS); + doesIdentityRequireRefresh = (identity) => identity.expiration !== void 0; + memoizeIdentityProvider = (provider, isExpired, requiresRefresh) => { + if (provider === void 0) { + return void 0; + } + const normalizedProvider = typeof provider !== "function" ? async () => Promise.resolve(provider) : provider; + let resolved; + let pending; + let hasResult; + let isConstant = false; + const coalesceProvider = async (options) => { + if (!pending) { + pending = normalizedProvider(options); + } + try { + resolved = await pending; + hasResult = true; + isConstant = false; + } finally { + pending = void 0; + } + return resolved; + }; + if (isExpired === void 0) { + return async (options) => { + if (!hasResult || options?.forceRefresh) { + resolved = await coalesceProvider(options); + } + return resolved; + }; + } + return async (options) => { + if (!hasResult || options?.forceRefresh) { + resolved = await coalesceProvider(options); + } + if (isConstant) { + return resolved; + } + if (!requiresRefresh(resolved)) { + isConstant = true; + return resolved; + } + if (isExpired(resolved)) { + await coalesceProvider(options); + return resolved; + } + return resolved; + }; + }; + } +}); + +// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/util-identity-and-auth/index.js +var init_util_identity_and_auth = __esm({ + "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/util-identity-and-auth/index.js"() { + init_DefaultIdentityProviderConfig(); + init_httpAuthSchemes(); + init_memoizeIdentityProvider(); + } +}); + +// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/index.js +var dist_es_exports = {}; +__export(dist_es_exports, { + DefaultIdentityProviderConfig: () => DefaultIdentityProviderConfig, + EXPIRATION_MS: () => EXPIRATION_MS, + HttpApiKeyAuthSigner: () => HttpApiKeyAuthSigner, + HttpBearerAuthSigner: () => HttpBearerAuthSigner, + NoAuthSigner: () => NoAuthSigner, + createIsIdentityExpiredFunction: () => createIsIdentityExpiredFunction, + createPaginator: () => createPaginator, + doesIdentityRequireRefresh: () => doesIdentityRequireRefresh, + getHttpAuthSchemeEndpointRuleSetPlugin: () => getHttpAuthSchemeEndpointRuleSetPlugin, + getHttpAuthSchemePlugin: () => getHttpAuthSchemePlugin, + getHttpSigningPlugin: () => getHttpSigningPlugin, + getSmithyContext: () => getSmithyContext4, + httpAuthSchemeEndpointRuleSetMiddlewareOptions: () => httpAuthSchemeEndpointRuleSetMiddlewareOptions, + httpAuthSchemeMiddleware: () => httpAuthSchemeMiddleware, + httpAuthSchemeMiddlewareOptions: () => httpAuthSchemeMiddlewareOptions, + httpSigningMiddleware: () => httpSigningMiddleware, + httpSigningMiddlewareOptions: () => httpSigningMiddlewareOptions, + isIdentityExpired: () => isIdentityExpired, + memoizeIdentityProvider: () => memoizeIdentityProvider, + normalizeProvider: () => normalizeProvider, + requestBuilder: () => requestBuilder, + setFeature: () => setFeature2 +}); +var init_dist_es = __esm({ + "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/index.js"() { + init_getSmithyContext(); + init_middleware_http_auth_scheme(); + init_middleware_http_signing(); + init_normalizeProvider(); + init_createPaginator(); + init_requestBuilder2(); + init_setFeature2(); + init_util_identity_and_auth(); + } +}); + +// node_modules/.pnpm/@aws-sdk+middleware-sdk-s3@3.972.28/node_modules/@aws-sdk/middleware-sdk-s3/dist-cjs/index.js +var require_dist_cjs32 = __commonJS({ + "node_modules/.pnpm/@aws-sdk+middleware-sdk-s3@3.972.28/node_modules/@aws-sdk/middleware-sdk-s3/dist-cjs/index.js"(exports) { + "use strict"; + var protocolHttp = require_dist_cjs2(); + var smithyClient = require_dist_cjs27(); + var utilStream = require_dist_cjs13(); + var utilArnParser = require_dist_cjs28(); + var protocols = (init_protocols2(), __toCommonJS(protocols_exports2)); + var schema2 = (init_schema3(), __toCommonJS(schema_exports2)); + var signatureV4 = require_dist_cjs30(); + var utilConfigProvider = require_dist_cjs31(); + var client2 = (init_client2(), __toCommonJS(client_exports)); + var core = (init_dist_es(), __toCommonJS(dist_es_exports)); + var utilMiddleware = require_dist_cjs18(); + var CONTENT_LENGTH_HEADER = "content-length"; + var DECODED_CONTENT_LENGTH_HEADER = "x-amz-decoded-content-length"; + function checkContentLengthHeader() { + return (next, context) => async (args) => { + const { request } = args; + if (protocolHttp.HttpRequest.isInstance(request)) { + if (!(CONTENT_LENGTH_HEADER in request.headers) && !(DECODED_CONTENT_LENGTH_HEADER in request.headers)) { + const message2 = `Are you using a Stream of unknown length as the Body of a PutObject request? Consider using Upload instead from @aws-sdk/lib-storage.`; + if (typeof context?.logger?.warn === "function" && !(context.logger instanceof smithyClient.NoOpLogger)) { + context.logger.warn(message2); + } else { + console.warn(message2); + } + } + } + return next({ ...args }); + }; + } + var checkContentLengthHeaderMiddlewareOptions = { + step: "finalizeRequest", + tags: ["CHECK_CONTENT_LENGTH_HEADER"], + name: "getCheckContentLengthHeaderPlugin", + override: true + }; + var getCheckContentLengthHeaderPlugin = (unused) => ({ + applyToStack: (clientStack) => { + clientStack.add(checkContentLengthHeader(), checkContentLengthHeaderMiddlewareOptions); + } + }); + var regionRedirectEndpointMiddleware = (config3) => { + return (next, context) => async (args) => { + const originalRegion = await config3.region(); + const regionProviderRef = config3.region; + let unlock = () => { + }; + if (context.__s3RegionRedirect) { + Object.defineProperty(config3, "region", { + writable: false, + value: async () => { + return context.__s3RegionRedirect; + } + }); + unlock = () => Object.defineProperty(config3, "region", { + writable: true, + value: regionProviderRef + }); + } + try { + const result = await next(args); + if (context.__s3RegionRedirect) { + unlock(); + const region = await config3.region(); + if (originalRegion !== region) { + throw new Error("Region was not restored following S3 region redirect."); + } + } + return result; + } catch (e5) { + unlock(); + throw e5; + } + }; + }; + var regionRedirectEndpointMiddlewareOptions = { + tags: ["REGION_REDIRECT", "S3"], + name: "regionRedirectEndpointMiddleware", + override: true, + relation: "before", + toMiddleware: "endpointV2Middleware" + }; + function regionRedirectMiddleware(clientConfig) { + return (next, context) => async (args) => { + try { + return await next(args); + } catch (err) { + if (clientConfig.followRegionRedirects) { + const statusCode = err?.$metadata?.httpStatusCode; + const isHeadBucket = context.commandName === "HeadBucketCommand"; + const bucketRegionHeader = err?.$response?.headers?.["x-amz-bucket-region"]; + if (bucketRegionHeader) { + if (statusCode === 301 || statusCode === 400 && (err?.name === "IllegalLocationConstraintException" || isHeadBucket)) { + try { + const actualRegion = bucketRegionHeader; + context.logger?.debug(`Redirecting from ${await clientConfig.region()} to ${actualRegion}`); + context.__s3RegionRedirect = actualRegion; + } catch (e5) { + throw new Error("Region redirect failed: " + e5); + } + return next(args); + } + } + } + throw err; + } + }; + } + var regionRedirectMiddlewareOptions = { + step: "initialize", + tags: ["REGION_REDIRECT", "S3"], + name: "regionRedirectMiddleware", + override: true + }; + var getRegionRedirectMiddlewarePlugin = (clientConfig) => ({ + applyToStack: (clientStack) => { + clientStack.add(regionRedirectMiddleware(clientConfig), regionRedirectMiddlewareOptions); + clientStack.addRelativeTo(regionRedirectEndpointMiddleware(clientConfig), regionRedirectEndpointMiddlewareOptions); + } + }); + var s3ExpiresMiddleware = (config3) => { + return (next, context) => async (args) => { + const result = await next(args); + const { response } = result; + if (protocolHttp.HttpResponse.isInstance(response)) { + if (response.headers.expires) { + response.headers.expiresstring = response.headers.expires; + try { + smithyClient.parseRfc7231DateTime(response.headers.expires); + } catch (e5) { + context.logger?.warn(`AWS SDK Warning for ${context.clientName}::${context.commandName} response parsing (${response.headers.expires}): ${e5}`); + delete response.headers.expires; + } + } + } + return result; + }; + }; + var s3ExpiresMiddlewareOptions = { + tags: ["S3"], + name: "s3ExpiresMiddleware", + override: true, + relation: "after", + toMiddleware: "deserializerMiddleware" + }; + var getS3ExpiresMiddlewarePlugin = (clientConfig) => ({ + applyToStack: (clientStack) => { + clientStack.addRelativeTo(s3ExpiresMiddleware(), s3ExpiresMiddlewareOptions); + } + }); + var S3ExpressIdentityCache = class _S3ExpressIdentityCache { + data; + lastPurgeTime = Date.now(); + static EXPIRED_CREDENTIAL_PURGE_INTERVAL_MS = 3e4; + constructor(data2 = {}) { + this.data = data2; + } + get(key) { + const entry = this.data[key]; + if (!entry) { + return; + } + return entry; + } + set(key, entry) { + this.data[key] = entry; + return entry; + } + delete(key) { + delete this.data[key]; + } + async purgeExpired() { + const now2 = Date.now(); + if (this.lastPurgeTime + _S3ExpressIdentityCache.EXPIRED_CREDENTIAL_PURGE_INTERVAL_MS > now2) { + return; + } + for (const key in this.data) { + const entry = this.data[key]; + if (!entry.isRefreshing) { + const credential = await entry.identity; + if (credential.expiration) { + if (credential.expiration.getTime() < now2) { + delete this.data[key]; + } + } + } + } + } + }; + var S3ExpressIdentityCacheEntry = class { + _identity; + isRefreshing; + accessed; + constructor(_identity, isRefreshing = false, accessed = Date.now()) { + this._identity = _identity; + this.isRefreshing = isRefreshing; + this.accessed = accessed; + } + get identity() { + this.accessed = Date.now(); + return this._identity; + } + }; + var S3ExpressIdentityProviderImpl = class _S3ExpressIdentityProviderImpl { + createSessionFn; + cache; + static REFRESH_WINDOW_MS = 6e4; + constructor(createSessionFn, cache7 = new S3ExpressIdentityCache()) { + this.createSessionFn = createSessionFn; + this.cache = cache7; + } + async getS3ExpressIdentity(awsIdentity, identityProperties) { + const key = identityProperties.Bucket; + const { cache: cache7 } = this; + const entry = cache7.get(key); + if (entry) { + return entry.identity.then((identity) => { + const isExpired = (identity.expiration?.getTime() ?? 0) < Date.now(); + if (isExpired) { + return cache7.set(key, new S3ExpressIdentityCacheEntry(this.getIdentity(key))).identity; + } + const isExpiringSoon = (identity.expiration?.getTime() ?? 0) < Date.now() + _S3ExpressIdentityProviderImpl.REFRESH_WINDOW_MS; + if (isExpiringSoon && !entry.isRefreshing) { + entry.isRefreshing = true; + this.getIdentity(key).then((id) => { + cache7.set(key, new S3ExpressIdentityCacheEntry(Promise.resolve(id))); + }); + } + return identity; + }); + } + return cache7.set(key, new S3ExpressIdentityCacheEntry(this.getIdentity(key))).identity; + } + async getIdentity(key) { + await this.cache.purgeExpired().catch((error50) => { + console.warn("Error while clearing expired entries in S3ExpressIdentityCache: \n" + error50); + }); + const session = await this.createSessionFn(key); + if (!session.Credentials?.AccessKeyId || !session.Credentials?.SecretAccessKey) { + throw new Error("s3#createSession response credential missing AccessKeyId or SecretAccessKey."); + } + const identity = { + accessKeyId: session.Credentials.AccessKeyId, + secretAccessKey: session.Credentials.SecretAccessKey, + sessionToken: session.Credentials.SessionToken, + expiration: session.Credentials.Expiration ? new Date(session.Credentials.Expiration) : void 0 + }; + return identity; + } + }; + var S3_EXPRESS_BUCKET_TYPE = "Directory"; + var S3_EXPRESS_BACKEND = "S3Express"; + var S3_EXPRESS_AUTH_SCHEME = "sigv4-s3express"; + var SESSION_TOKEN_QUERY_PARAM = "X-Amz-S3session-Token"; + var SESSION_TOKEN_HEADER = SESSION_TOKEN_QUERY_PARAM.toLowerCase(); + var NODE_DISABLE_S3_EXPRESS_SESSION_AUTH_ENV_NAME = "AWS_S3_DISABLE_EXPRESS_SESSION_AUTH"; + var NODE_DISABLE_S3_EXPRESS_SESSION_AUTH_INI_NAME = "s3_disable_express_session_auth"; + var NODE_DISABLE_S3_EXPRESS_SESSION_AUTH_OPTIONS = { + environmentVariableSelector: (env2) => utilConfigProvider.booleanSelector(env2, NODE_DISABLE_S3_EXPRESS_SESSION_AUTH_ENV_NAME, utilConfigProvider.SelectorType.ENV), + configFileSelector: (profile) => utilConfigProvider.booleanSelector(profile, NODE_DISABLE_S3_EXPRESS_SESSION_AUTH_INI_NAME, utilConfigProvider.SelectorType.CONFIG), + default: false + }; + var SignatureV4S3Express = class extends signatureV4.SignatureV4 { + async signWithCredentials(requestToSign, credentials, options) { + const credentialsWithoutSessionToken = getCredentialsWithoutSessionToken(credentials); + requestToSign.headers[SESSION_TOKEN_HEADER] = credentials.sessionToken; + const privateAccess = this; + setSingleOverride(privateAccess, credentialsWithoutSessionToken); + return privateAccess.signRequest(requestToSign, options ?? {}); + } + async presignWithCredentials(requestToSign, credentials, options) { + const credentialsWithoutSessionToken = getCredentialsWithoutSessionToken(credentials); + delete requestToSign.headers[SESSION_TOKEN_HEADER]; + requestToSign.headers[SESSION_TOKEN_QUERY_PARAM] = credentials.sessionToken; + requestToSign.query = requestToSign.query ?? {}; + requestToSign.query[SESSION_TOKEN_QUERY_PARAM] = credentials.sessionToken; + const privateAccess = this; + setSingleOverride(privateAccess, credentialsWithoutSessionToken); + return this.presign(requestToSign, options); + } + }; + function getCredentialsWithoutSessionToken(credentials) { + const credentialsWithoutSessionToken = { + accessKeyId: credentials.accessKeyId, + secretAccessKey: credentials.secretAccessKey, + expiration: credentials.expiration + }; + return credentialsWithoutSessionToken; + } + function setSingleOverride(privateAccess, credentialsWithoutSessionToken) { + const id = setTimeout(() => { + throw new Error("SignatureV4S3Express credential override was created but not called."); + }, 10); + const currentCredentialProvider = privateAccess.credentialProvider; + const overrideCredentialsProviderOnce = () => { + clearTimeout(id); + privateAccess.credentialProvider = currentCredentialProvider; + return Promise.resolve(credentialsWithoutSessionToken); + }; + privateAccess.credentialProvider = overrideCredentialsProviderOnce; + } + var s3ExpressMiddleware = (options) => { + return (next, context) => async (args) => { + if (context.endpointV2) { + const endpoint = context.endpointV2; + const isS3ExpressAuth = endpoint.properties?.authSchemes?.[0]?.name === S3_EXPRESS_AUTH_SCHEME; + const isS3ExpressBucket = endpoint.properties?.backend === S3_EXPRESS_BACKEND || endpoint.properties?.bucketType === S3_EXPRESS_BUCKET_TYPE; + if (isS3ExpressBucket) { + client2.setFeature(context, "S3_EXPRESS_BUCKET", "J"); + context.isS3ExpressBucket = true; + } + if (isS3ExpressAuth) { + const requestBucket = args.input.Bucket; + if (requestBucket) { + const s3ExpressIdentity = await options.s3ExpressIdentityProvider.getS3ExpressIdentity(await options.credentials(), { + Bucket: requestBucket + }); + context.s3ExpressIdentity = s3ExpressIdentity; + if (protocolHttp.HttpRequest.isInstance(args.request) && s3ExpressIdentity.sessionToken) { + args.request.headers[SESSION_TOKEN_HEADER] = s3ExpressIdentity.sessionToken; + } + } + } + } + return next(args); + }; + }; + var s3ExpressMiddlewareOptions = { + name: "s3ExpressMiddleware", + step: "build", + tags: ["S3", "S3_EXPRESS"], + override: true + }; + var getS3ExpressPlugin = (options) => ({ + applyToStack: (clientStack) => { + clientStack.add(s3ExpressMiddleware(options), s3ExpressMiddlewareOptions); + } + }); + var signS3Express = async (s3ExpressIdentity, signingOptions, request, sigV4MultiRegionSigner) => { + const signedRequest = await sigV4MultiRegionSigner.signWithCredentials(request, s3ExpressIdentity, {}); + if (signedRequest.headers["X-Amz-Security-Token"] || signedRequest.headers["x-amz-security-token"]) { + throw new Error("X-Amz-Security-Token must not be set for s3-express requests."); + } + return signedRequest; + }; + var defaultErrorHandler2 = (signingProperties) => (error50) => { + throw error50; + }; + var defaultSuccessHandler2 = (httpResponse, signingProperties) => { + }; + var s3ExpressHttpSigningMiddlewareOptions = core.httpSigningMiddlewareOptions; + var s3ExpressHttpSigningMiddleware = (config3) => (next, context) => async (args) => { + if (!protocolHttp.HttpRequest.isInstance(args.request)) { + return next(args); + } + const smithyContext = utilMiddleware.getSmithyContext(context); + const scheme = smithyContext.selectedHttpAuthScheme; + if (!scheme) { + throw new Error(`No HttpAuthScheme was selected: unable to sign request`); + } + const { httpAuthOption: { signingProperties = {} }, identity, signer } = scheme; + let request; + if (context.s3ExpressIdentity) { + request = await signS3Express(context.s3ExpressIdentity, signingProperties, args.request, await config3.signer()); + } else { + request = await signer.sign(args.request, identity, signingProperties); + } + const output = await next({ + ...args, + request + }).catch((signer.errorHandler || defaultErrorHandler2)(signingProperties)); + (signer.successHandler || defaultSuccessHandler2)(output.response, signingProperties); + return output; + }; + var getS3ExpressHttpSigningPlugin = (config3) => ({ + applyToStack: (clientStack) => { + clientStack.addRelativeTo(s3ExpressHttpSigningMiddleware(config3), core.httpSigningMiddlewareOptions); + } + }); + var resolveS3Config = (input, { session }) => { + const [s3ClientProvider, CreateSessionCommandCtor] = session; + const { forcePathStyle, useAccelerateEndpoint, disableMultiregionAccessPoints, followRegionRedirects, s3ExpressIdentityProvider, bucketEndpoint, expectContinueHeader } = input; + return Object.assign(input, { + forcePathStyle: forcePathStyle ?? false, + useAccelerateEndpoint: useAccelerateEndpoint ?? false, + disableMultiregionAccessPoints: disableMultiregionAccessPoints ?? false, + followRegionRedirects: followRegionRedirects ?? false, + s3ExpressIdentityProvider: s3ExpressIdentityProvider ?? new S3ExpressIdentityProviderImpl(async (key) => s3ClientProvider().send(new CreateSessionCommandCtor({ + Bucket: key + }))), + bucketEndpoint: bucketEndpoint ?? false, + expectContinueHeader: expectContinueHeader ?? 2097152 + }); + }; + var THROW_IF_EMPTY_BODY = { + CopyObjectCommand: true, + UploadPartCopyCommand: true, + CompleteMultipartUploadCommand: true + }; + var MAX_BYTES_TO_INSPECT = 3e3; + var throw200ExceptionsMiddleware = (config3) => (next, context) => async (args) => { + const result = await next(args); + const { response } = result; + if (!protocolHttp.HttpResponse.isInstance(response)) { + return result; + } + const { statusCode, body: sourceBody } = response; + if (statusCode < 200 || statusCode >= 300) { + return result; + } + const isSplittableStream = typeof sourceBody?.stream === "function" || typeof sourceBody?.pipe === "function" || typeof sourceBody?.tee === "function"; + if (!isSplittableStream) { + return result; + } + let bodyCopy = sourceBody; + let body = sourceBody; + if (sourceBody && typeof sourceBody === "object" && !(sourceBody instanceof Uint8Array)) { + [bodyCopy, body] = await utilStream.splitStream(sourceBody); + } + response.body = body; + const bodyBytes = await collectBody3(bodyCopy, { + streamCollector: async (stream) => { + return utilStream.headStream(stream, MAX_BYTES_TO_INSPECT); + } + }); + if (typeof bodyCopy?.destroy === "function") { + bodyCopy.destroy(); + } + const bodyStringTail = config3.utf8Encoder(bodyBytes.subarray(bodyBytes.length - 16)); + if (bodyBytes.length === 0 && THROW_IF_EMPTY_BODY[context.commandName]) { + const err = new Error("S3 aborted request"); + err.name = "InternalError"; + throw err; + } + if (bodyStringTail && bodyStringTail.endsWith("")) { + response.statusCode = 400; + } + return result; + }; + var collectBody3 = (streamBody = new Uint8Array(), context) => { + if (streamBody instanceof Uint8Array) { + return Promise.resolve(streamBody); + } + return context.streamCollector(streamBody) || Promise.resolve(new Uint8Array()); + }; + var throw200ExceptionsMiddlewareOptions = { + relation: "after", + toMiddleware: "deserializerMiddleware", + tags: ["THROW_200_EXCEPTIONS", "S3"], + name: "throw200ExceptionsMiddleware", + override: true + }; + var getThrow200ExceptionsPlugin = (config3) => ({ + applyToStack: (clientStack) => { + clientStack.addRelativeTo(throw200ExceptionsMiddleware(config3), throw200ExceptionsMiddlewareOptions); + } + }); + function bucketEndpointMiddleware(options) { + return (next, context) => async (args) => { + if (options.bucketEndpoint) { + const endpoint = context.endpointV2; + if (endpoint) { + const bucket = args.input.Bucket; + if (typeof bucket === "string") { + try { + const bucketEndpointUrl = new URL(bucket); + context.endpointV2 = { + ...endpoint, + url: bucketEndpointUrl + }; + } catch (e5) { + const warning = `@aws-sdk/middleware-sdk-s3: bucketEndpoint=true was set but Bucket=${bucket} could not be parsed as URL.`; + if (context.logger?.constructor?.name === "NoOpLogger") { + console.warn(warning); + } else { + context.logger?.warn?.(warning); + } + throw e5; + } + } + } + } + return next(args); + }; + } + var bucketEndpointMiddlewareOptions = { + name: "bucketEndpointMiddleware", + override: true, + relation: "after", + toMiddleware: "endpointV2Middleware" + }; + function validateBucketNameMiddleware({ bucketEndpoint }) { + return (next) => async (args) => { + const { input: { Bucket } } = args; + if (!bucketEndpoint && typeof Bucket === "string" && !utilArnParser.validate(Bucket) && Bucket.indexOf("/") >= 0) { + const err = new Error(`Bucket name shouldn't contain '/', received '${Bucket}'`); + err.name = "InvalidBucketName"; + throw err; + } + return next({ ...args }); + }; + } + var validateBucketNameMiddlewareOptions = { + step: "initialize", + tags: ["VALIDATE_BUCKET_NAME"], + name: "validateBucketNameMiddleware", + override: true + }; + var getValidateBucketNamePlugin = (options) => ({ + applyToStack: (clientStack) => { + clientStack.add(validateBucketNameMiddleware(options), validateBucketNameMiddlewareOptions); + clientStack.addRelativeTo(bucketEndpointMiddleware(options), bucketEndpointMiddlewareOptions); + } + }); + var S3RestXmlProtocol = class extends protocols.AwsRestXmlProtocol { + async serializeRequest(operationSchema, input, context) { + const request = await super.serializeRequest(operationSchema, input, context); + const ns = schema2.NormalizedSchema.of(operationSchema.input); + const staticStructureSchema = ns.getSchema(); + let bucketMemberIndex = 0; + const requiredMemberCount = staticStructureSchema[6] ?? 0; + if (input && typeof input === "object") { + for (const [memberName, memberNs] of ns.structIterator()) { + if (++bucketMemberIndex > requiredMemberCount) { + break; + } + if (memberName === "Bucket") { + if (!input.Bucket && memberNs.getMergedTraits().httpLabel) { + throw new Error(`No value provided for input HTTP label: Bucket.`); + } + break; + } + } + } + return request; + } + }; + exports.NODE_DISABLE_S3_EXPRESS_SESSION_AUTH_OPTIONS = NODE_DISABLE_S3_EXPRESS_SESSION_AUTH_OPTIONS; + exports.S3ExpressIdentityCache = S3ExpressIdentityCache; + exports.S3ExpressIdentityCacheEntry = S3ExpressIdentityCacheEntry; + exports.S3ExpressIdentityProviderImpl = S3ExpressIdentityProviderImpl; + exports.S3RestXmlProtocol = S3RestXmlProtocol; + exports.SignatureV4S3Express = SignatureV4S3Express; + exports.checkContentLengthHeader = checkContentLengthHeader; + exports.checkContentLengthHeaderMiddlewareOptions = checkContentLengthHeaderMiddlewareOptions; + exports.getCheckContentLengthHeaderPlugin = getCheckContentLengthHeaderPlugin; + exports.getRegionRedirectMiddlewarePlugin = getRegionRedirectMiddlewarePlugin; + exports.getS3ExpiresMiddlewarePlugin = getS3ExpiresMiddlewarePlugin; + exports.getS3ExpressHttpSigningPlugin = getS3ExpressHttpSigningPlugin; + exports.getS3ExpressPlugin = getS3ExpressPlugin; + exports.getThrow200ExceptionsPlugin = getThrow200ExceptionsPlugin; + exports.getValidateBucketNamePlugin = getValidateBucketNamePlugin; + exports.regionRedirectEndpointMiddleware = regionRedirectEndpointMiddleware; + exports.regionRedirectEndpointMiddlewareOptions = regionRedirectEndpointMiddlewareOptions; + exports.regionRedirectMiddleware = regionRedirectMiddleware; + exports.regionRedirectMiddlewareOptions = regionRedirectMiddlewareOptions; + exports.resolveS3Config = resolveS3Config; + exports.s3ExpiresMiddleware = s3ExpiresMiddleware; + exports.s3ExpiresMiddlewareOptions = s3ExpiresMiddlewareOptions; + exports.s3ExpressHttpSigningMiddleware = s3ExpressHttpSigningMiddleware; + exports.s3ExpressHttpSigningMiddlewareOptions = s3ExpressHttpSigningMiddlewareOptions; + exports.s3ExpressMiddleware = s3ExpressMiddleware; + exports.s3ExpressMiddlewareOptions = s3ExpressMiddlewareOptions; + exports.throw200ExceptionsMiddleware = throw200ExceptionsMiddleware; + exports.throw200ExceptionsMiddlewareOptions = throw200ExceptionsMiddlewareOptions; + exports.validateBucketNameMiddleware = validateBucketNameMiddleware; + exports.validateBucketNameMiddlewareOptions = validateBucketNameMiddlewareOptions; + } +}); + +// node_modules/.pnpm/@smithy+util-endpoints@3.4.0/node_modules/@smithy/util-endpoints/dist-cjs/index.js +var require_dist_cjs33 = __commonJS({ + "node_modules/.pnpm/@smithy+util-endpoints@3.4.0/node_modules/@smithy/util-endpoints/dist-cjs/index.js"(exports) { + "use strict"; + var types2 = require_dist_cjs(); + var BinaryDecisionDiagram = class _BinaryDecisionDiagram { + nodes; + root; + conditions; + results; + constructor(bdd, root, conditions, results) { + this.nodes = bdd; + this.root = root; + this.conditions = conditions; + this.results = results; + } + static from(bdd, root, conditions, results) { + return new _BinaryDecisionDiagram(bdd, root, conditions, results); + } + }; + var EndpointCache5 = class { + capacity; + data = /* @__PURE__ */ new Map(); + parameters = []; + constructor({ size: size2, params }) { + this.capacity = size2 ?? 50; + if (params) { + this.parameters = params; + } + } + get(endpointParams, resolver) { + const key = this.hash(endpointParams); + if (key === false) { + return resolver(); + } + if (!this.data.has(key)) { + if (this.data.size > this.capacity + 10) { + const keys = this.data.keys(); + let i5 = 0; + while (true) { + const { value, done } = keys.next(); + this.data.delete(value); + if (done || ++i5 > 10) { + break; + } + } + } + this.data.set(key, resolver()); + } + return this.data.get(key); + } + size() { + return this.data.size; + } + hash(endpointParams) { + let buffer2 = ""; + const { parameters } = this; + if (parameters.length === 0) { + return false; + } + for (const param of parameters) { + const val = String(endpointParams[param] ?? ""); + if (val.includes("|;")) { + return false; + } + buffer2 += val + "|;"; + } + return buffer2; + } + }; + var EndpointError = class extends Error { + constructor(message2) { + super(message2); + this.name = "EndpointError"; + } + }; + var debugId = "endpoints"; + function toDebugString(input) { + if (typeof input !== "object" || input == null) { + return input; + } + if ("ref" in input) { + return `$${toDebugString(input.ref)}`; + } + if ("fn" in input) { + return `${input.fn}(${(input.argv || []).map(toDebugString).join(", ")})`; + } + return JSON.stringify(input, null, 2); + } + var customEndpointFunctions5 = {}; + var booleanEquals = (value1, value2) => value1 === value2; + function coalesce(...args) { + for (const arg of args) { + if (arg != null) { + return arg; + } + } + return void 0; + } + var getAttrPathList = (path53) => { + const parts = path53.split("."); + const pathList = []; + for (const part of parts) { + const squareBracketIndex = part.indexOf("["); + if (squareBracketIndex !== -1) { + if (part.indexOf("]") !== part.length - 1) { + throw new EndpointError(`Path: '${path53}' does not end with ']'`); + } + const arrayIndex = part.slice(squareBracketIndex + 1, -1); + if (Number.isNaN(parseInt(arrayIndex))) { + throw new EndpointError(`Invalid array index: '${arrayIndex}' in path: '${path53}'`); + } + if (squareBracketIndex !== 0) { + pathList.push(part.slice(0, squareBracketIndex)); + } + pathList.push(arrayIndex); + } else { + pathList.push(part); + } + } + return pathList; + }; + var getAttr = (value, path53) => getAttrPathList(path53).reduce((acc, index2) => { + if (typeof acc !== "object") { + throw new EndpointError(`Index '${index2}' in '${path53}' not found in '${JSON.stringify(value)}'`); + } else if (Array.isArray(acc)) { + return acc[parseInt(index2)]; + } + return acc[index2]; + }, value); + var isSet = (value) => value != null; + var VALID_HOST_LABEL_REGEX = new RegExp(`^(?!.*-$)(?!-)[a-zA-Z0-9-]{1,63}$`); + var isValidHostLabel = (value, allowSubDomains = false) => { + if (!allowSubDomains) { + return VALID_HOST_LABEL_REGEX.test(value); + } + const labels2 = value.split("."); + for (const label of labels2) { + if (!isValidHostLabel(label)) { + return false; + } + } + return true; + }; + function ite(condition, trueValue, falseValue) { + return condition ? trueValue : falseValue; + } + var not2 = (value) => !value; + var IP_V4_REGEX = new RegExp(`^(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}$`); + var isIpAddress = (value) => IP_V4_REGEX.test(value) || value.startsWith("[") && value.endsWith("]"); + var DEFAULT_PORTS = { + [types2.EndpointURLScheme.HTTP]: 80, + [types2.EndpointURLScheme.HTTPS]: 443 + }; + var parseURL = (value) => { + const whatwgURL = (() => { + try { + if (value instanceof URL) { + return value; + } + if (typeof value === "object" && "hostname" in value) { + const { hostname: hostname4, port, protocol: protocol2 = "", path: path53 = "", query = {} } = value; + const url2 = new URL(`${protocol2}//${hostname4}${port ? `:${port}` : ""}${path53}`); + url2.search = Object.entries(query).map(([k5, v5]) => `${k5}=${v5}`).join("&"); + return url2; + } + return new URL(value); + } catch (error50) { + return null; + } + })(); + if (!whatwgURL) { + console.error(`Unable to parse ${JSON.stringify(value)} as a whatwg URL.`); + return null; + } + const urlString = whatwgURL.href; + const { host, hostname: hostname3, pathname, protocol, search } = whatwgURL; + if (search) { + return null; + } + const scheme = protocol.slice(0, -1); + if (!Object.values(types2.EndpointURLScheme).includes(scheme)) { + return null; + } + const isIp = isIpAddress(hostname3); + const inputContainsDefaultPort = urlString.includes(`${host}:${DEFAULT_PORTS[scheme]}`) || typeof value === "string" && value.includes(`${host}:${DEFAULT_PORTS[scheme]}`); + const authority = `${host}${inputContainsDefaultPort ? `:${DEFAULT_PORTS[scheme]}` : ``}`; + return { + scheme, + authority, + path: pathname, + normalizedPath: pathname.endsWith("/") ? pathname : `${pathname}/`, + isIp + }; + }; + function split(value, delimiter, limit) { + if (limit === 1) { + return [value]; + } + if (value === "") { + return [""]; + } + const parts = value.split(delimiter); + if (limit === 0) { + return parts; + } + return parts.slice(0, limit - 1).concat(parts.slice(1).join(delimiter)); + } + var stringEquals = (value1, value2) => value1 === value2; + var substring = (input, start, stop, reverse) => { + if (input == null || start >= stop || input.length < stop || /[^\u0000-\u007f]/.test(input)) { + return null; + } + if (!reverse) { + return input.substring(start, stop); + } + return input.substring(input.length - stop, input.length - start); + }; + var uriEncode = (value) => encodeURIComponent(value).replace(/[!*'()]/g, (c5) => `%${c5.charCodeAt(0).toString(16).toUpperCase()}`); + var endpointFunctions = { + booleanEquals, + coalesce, + getAttr, + isSet, + isValidHostLabel, + ite, + not: not2, + parseURL, + split, + stringEquals, + substring, + uriEncode + }; + var evaluateTemplate = (template, options) => { + const evaluatedTemplateArr = []; + const { referenceRecord, endpointParams } = options; + let currentIndex = 0; + while (currentIndex < template.length) { + const openingBraceIndex = template.indexOf("{", currentIndex); + if (openingBraceIndex === -1) { + evaluatedTemplateArr.push(template.slice(currentIndex)); + break; + } + evaluatedTemplateArr.push(template.slice(currentIndex, openingBraceIndex)); + const closingBraceIndex = template.indexOf("}", openingBraceIndex); + if (closingBraceIndex === -1) { + evaluatedTemplateArr.push(template.slice(openingBraceIndex)); + break; + } + if (template[openingBraceIndex + 1] === "{" && template[closingBraceIndex + 1] === "}") { + evaluatedTemplateArr.push(template.slice(openingBraceIndex + 1, closingBraceIndex)); + currentIndex = closingBraceIndex + 2; + } + const parameterName = template.substring(openingBraceIndex + 1, closingBraceIndex); + if (parameterName.includes("#")) { + const [refName, attrName] = parameterName.split("#"); + evaluatedTemplateArr.push(getAttr(referenceRecord[refName] ?? endpointParams[refName], attrName)); + } else { + evaluatedTemplateArr.push(referenceRecord[parameterName] ?? endpointParams[parameterName]); + } + currentIndex = closingBraceIndex + 1; + } + return evaluatedTemplateArr.join(""); + }; + var getReferenceValue = ({ ref }, options) => { + return options.referenceRecord[ref] ?? options.endpointParams[ref]; + }; + var evaluateExpression = (obj, keyName, options) => { + if (typeof obj === "string") { + return evaluateTemplate(obj, options); + } else if (obj["fn"]) { + return group$2.callFunction(obj, options); + } else if (obj["ref"]) { + return getReferenceValue(obj, options); + } + throw new EndpointError(`'${keyName}': ${String(obj)} is not a string, function or reference.`); + }; + var callFunction = ({ fn, argv }, options) => { + const evaluatedArgs = Array(argv.length); + for (let i5 = 0; i5 < evaluatedArgs.length; ++i5) { + const arg = argv[i5]; + if (typeof arg === "boolean" || typeof arg === "number") { + evaluatedArgs[i5] = arg; + } else { + evaluatedArgs[i5] = group$2.evaluateExpression(arg, "arg", options); + } + } + if (fn.includes(".")) { + const fnSegments = fn.split("."); + if (fnSegments[0] in customEndpointFunctions5 && fnSegments[1] != null) { + return customEndpointFunctions5[fnSegments[0]][fnSegments[1]](...evaluatedArgs); + } + } + if (typeof endpointFunctions[fn] !== "function") { + throw new Error(`function ${fn} not loaded in endpointFunctions.`); + } + const callable = endpointFunctions[fn]; + return callable(...evaluatedArgs); + }; + var group$2 = { + evaluateExpression, + callFunction + }; + var evaluateCondition = ({ assign, ...fnArgs }, options) => { + if (assign && assign in options.referenceRecord) { + throw new EndpointError(`'${assign}' is already defined in Reference Record.`); + } + const value = callFunction(fnArgs, options); + options.logger?.debug?.(`${debugId} evaluateCondition: ${toDebugString(fnArgs)} = ${toDebugString(value)}`); + return { + result: value === "" ? true : !!value, + ...assign != null && { toAssign: { name: assign, value } } + }; + }; + var getEndpointHeaders = (headers, options) => Object.entries(headers).reduce((acc, [headerKey, headerVal]) => ({ + ...acc, + [headerKey]: headerVal.map((headerValEntry) => { + const processedExpr = evaluateExpression(headerValEntry, "Header value entry", options); + if (typeof processedExpr !== "string") { + throw new EndpointError(`Header '${headerKey}' value '${processedExpr}' is not a string`); + } + return processedExpr; + }) + }), {}); + var getEndpointProperties = (properties, options) => Object.entries(properties).reduce((acc, [propertyKey, propertyVal]) => ({ + ...acc, + [propertyKey]: group$1.getEndpointProperty(propertyVal, options) + }), {}); + var getEndpointProperty = (property, options) => { + if (Array.isArray(property)) { + return property.map((propertyEntry) => getEndpointProperty(propertyEntry, options)); + } + switch (typeof property) { + case "string": + return evaluateTemplate(property, options); + case "object": + if (property === null) { + throw new EndpointError(`Unexpected endpoint property: ${property}`); + } + return group$1.getEndpointProperties(property, options); + case "boolean": + return property; + default: + throw new EndpointError(`Unexpected endpoint property type: ${typeof property}`); + } + }; + var group$1 = { + getEndpointProperty, + getEndpointProperties + }; + var getEndpointUrl = (endpointUrl, options) => { + const expression = evaluateExpression(endpointUrl, "Endpoint URL", options); + if (typeof expression === "string") { + try { + return new URL(expression); + } catch (error50) { + console.error(`Failed to construct URL with ${expression}`, error50); + throw error50; + } + } + throw new EndpointError(`Endpoint URL must be a string, got ${typeof expression}`); + }; + var RESULT = 1e8; + var decideEndpoint = (bdd, options) => { + const { nodes, root, results, conditions } = bdd; + let ref = root; + const referenceRecord = {}; + const closure = { + referenceRecord, + endpointParams: options.endpointParams, + logger: options.logger + }; + while (ref !== 1 && ref !== -1 && ref < RESULT) { + const node_i = 3 * (Math.abs(ref) - 1); + const [condition_i, highRef, lowRef] = [nodes[node_i], nodes[node_i + 1], nodes[node_i + 2]]; + const [fn, argv, assign] = conditions[condition_i]; + const evaluation = evaluateCondition({ fn, assign, argv }, closure); + if (evaluation.toAssign) { + const { name, value } = evaluation.toAssign; + referenceRecord[name] = value; + } + ref = ref >= 0 === evaluation.result ? highRef : lowRef; + } + if (ref >= RESULT) { + const result = results[ref - RESULT]; + if (result[0] === -1) { + const [, errorMessage] = result; + throw new EndpointError(errorMessage); + } + const [url2, properties, headers] = result; + return { + url: getEndpointUrl(url2, closure), + properties: getEndpointProperties(properties, closure), + headers: getEndpointHeaders(headers, closure) + }; + } + throw new EndpointError(`No matching endpoint.`); + }; + var evaluateConditions = (conditions = [], options) => { + const conditionsReferenceRecord = {}; + for (const condition of conditions) { + const { result, toAssign } = evaluateCondition(condition, { + ...options, + referenceRecord: { + ...options.referenceRecord, + ...conditionsReferenceRecord + } + }); + if (!result) { + return { result }; + } + if (toAssign) { + conditionsReferenceRecord[toAssign.name] = toAssign.value; + options.logger?.debug?.(`${debugId} assign: ${toAssign.name} := ${toDebugString(toAssign.value)}`); + } + } + return { result: true, referenceRecord: conditionsReferenceRecord }; + }; + var evaluateEndpointRule = (endpointRule, options) => { + const { conditions, endpoint } = endpointRule; + const { result, referenceRecord } = evaluateConditions(conditions, options); + if (!result) { + return; + } + const endpointRuleOptions = { + ...options, + referenceRecord: { ...options.referenceRecord, ...referenceRecord } + }; + const { url: url2, properties, headers } = endpoint; + options.logger?.debug?.(`${debugId} Resolving endpoint from template: ${toDebugString(endpoint)}`); + return { + ...headers != void 0 && { + headers: getEndpointHeaders(headers, endpointRuleOptions) + }, + ...properties != void 0 && { + properties: getEndpointProperties(properties, endpointRuleOptions) + }, + url: getEndpointUrl(url2, endpointRuleOptions) + }; + }; + var evaluateErrorRule = (errorRule, options) => { + const { conditions, error: error50 } = errorRule; + const { result, referenceRecord } = evaluateConditions(conditions, options); + if (!result) { + return; + } + throw new EndpointError(evaluateExpression(error50, "Error", { + ...options, + referenceRecord: { ...options.referenceRecord, ...referenceRecord } + })); + }; + var evaluateRules = (rules, options) => { + for (const rule of rules) { + if (rule.type === "endpoint") { + const endpointOrUndefined = evaluateEndpointRule(rule, options); + if (endpointOrUndefined) { + return endpointOrUndefined; + } + } else if (rule.type === "error") { + evaluateErrorRule(rule, options); + } else if (rule.type === "tree") { + const endpointOrUndefined = group.evaluateTreeRule(rule, options); + if (endpointOrUndefined) { + return endpointOrUndefined; + } + } else { + throw new EndpointError(`Unknown endpoint rule: ${rule}`); + } + } + throw new EndpointError(`Rules evaluation failed`); + }; + var evaluateTreeRule = (treeRule, options) => { + const { conditions, rules } = treeRule; + const { result, referenceRecord } = evaluateConditions(conditions, options); + if (!result) { + return; + } + return group.evaluateRules(rules, { + ...options, + referenceRecord: { ...options.referenceRecord, ...referenceRecord } + }); + }; + var group = { + evaluateRules, + evaluateTreeRule + }; + var resolveEndpoint5 = (ruleSetObject, options) => { + const { endpointParams, logger: logger4 } = options; + const { parameters, rules } = ruleSetObject; + options.logger?.debug?.(`${debugId} Initial EndpointParams: ${toDebugString(endpointParams)}`); + const paramsWithDefault = Object.entries(parameters).filter(([, v5]) => v5.default != null).map(([k5, v5]) => [k5, v5.default]); + if (paramsWithDefault.length > 0) { + for (const [paramKey, paramDefaultValue] of paramsWithDefault) { + endpointParams[paramKey] = endpointParams[paramKey] ?? paramDefaultValue; + } + } + const requiredParams = Object.entries(parameters).filter(([, v5]) => v5.required).map(([k5]) => k5); + for (const requiredParam of requiredParams) { + if (endpointParams[requiredParam] == null) { + throw new EndpointError(`Missing required parameter: '${requiredParam}'`); + } + } + const endpoint = evaluateRules(rules, { endpointParams, logger: logger4, referenceRecord: {} }); + options.logger?.debug?.(`${debugId} Resolved endpoint: ${toDebugString(endpoint)}`); + return endpoint; + }; + exports.BinaryDecisionDiagram = BinaryDecisionDiagram; + exports.EndpointCache = EndpointCache5; + exports.EndpointError = EndpointError; + exports.customEndpointFunctions = customEndpointFunctions5; + exports.decideEndpoint = decideEndpoint; + exports.isIpAddress = isIpAddress; + exports.isValidHostLabel = isValidHostLabel; + exports.resolveEndpoint = resolveEndpoint5; + } +}); + +// node_modules/.pnpm/@aws-sdk+util-endpoints@3.996.6/node_modules/@aws-sdk/util-endpoints/dist-cjs/index.js +var require_dist_cjs34 = __commonJS({ + "node_modules/.pnpm/@aws-sdk+util-endpoints@3.996.6/node_modules/@aws-sdk/util-endpoints/dist-cjs/index.js"(exports) { + "use strict"; + var utilEndpoints = require_dist_cjs33(); + var urlParser = require_dist_cjs25(); + var isVirtualHostableS3Bucket = (value, allowSubDomains = false) => { + if (allowSubDomains) { + for (const label of value.split(".")) { + if (!isVirtualHostableS3Bucket(label)) { + return false; + } + } + return true; + } + if (!utilEndpoints.isValidHostLabel(value)) { + return false; + } + if (value.length < 3 || value.length > 63) { + return false; + } + if (value !== value.toLowerCase()) { + return false; + } + if (utilEndpoints.isIpAddress(value)) { + return false; + } + return true; + }; + var ARN_DELIMITER = ":"; + var RESOURCE_DELIMITER = "/"; + var parseArn = (value) => { + const segments = value.split(ARN_DELIMITER); + if (segments.length < 6) + return null; + const [arn, partition2, service, region, accountId, ...resourcePath] = segments; + if (arn !== "arn" || partition2 === "" || service === "" || resourcePath.join(ARN_DELIMITER) === "") + return null; + const resourceId = resourcePath.map((resource) => resource.split(RESOURCE_DELIMITER)).flat(); + return { + partition: partition2, + service, + region, + accountId, + resourceId + }; + }; + var partitions = [ + { + id: "aws", + outputs: { + dnsSuffix: "amazonaws.com", + dualStackDnsSuffix: "api.aws", + implicitGlobalRegion: "us-east-1", + name: "aws", + supportsDualStack: true, + supportsFIPS: true + }, + regionRegex: "^(us|eu|ap|sa|ca|me|af|il|mx)\\-\\w+\\-\\d+$", + regions: { + "af-south-1": { + description: "Africa (Cape Town)" + }, + "ap-east-1": { + description: "Asia Pacific (Hong Kong)" + }, + "ap-east-2": { + description: "Asia Pacific (Taipei)" + }, + "ap-northeast-1": { + description: "Asia Pacific (Tokyo)" + }, + "ap-northeast-2": { + description: "Asia Pacific (Seoul)" + }, + "ap-northeast-3": { + description: "Asia Pacific (Osaka)" + }, + "ap-south-1": { + description: "Asia Pacific (Mumbai)" + }, + "ap-south-2": { + description: "Asia Pacific (Hyderabad)" + }, + "ap-southeast-1": { + description: "Asia Pacific (Singapore)" + }, + "ap-southeast-2": { + description: "Asia Pacific (Sydney)" + }, + "ap-southeast-3": { + description: "Asia Pacific (Jakarta)" + }, + "ap-southeast-4": { + description: "Asia Pacific (Melbourne)" + }, + "ap-southeast-5": { + description: "Asia Pacific (Malaysia)" + }, + "ap-southeast-6": { + description: "Asia Pacific (New Zealand)" + }, + "ap-southeast-7": { + description: "Asia Pacific (Thailand)" + }, + "aws-global": { + description: "aws global region" + }, + "ca-central-1": { + description: "Canada (Central)" + }, + "ca-west-1": { + description: "Canada West (Calgary)" + }, + "eu-central-1": { + description: "Europe (Frankfurt)" + }, + "eu-central-2": { + description: "Europe (Zurich)" + }, + "eu-north-1": { + description: "Europe (Stockholm)" + }, + "eu-south-1": { + description: "Europe (Milan)" + }, + "eu-south-2": { + description: "Europe (Spain)" + }, + "eu-west-1": { + description: "Europe (Ireland)" + }, + "eu-west-2": { + description: "Europe (London)" + }, + "eu-west-3": { + description: "Europe (Paris)" + }, + "il-central-1": { + description: "Israel (Tel Aviv)" + }, + "me-central-1": { + description: "Middle East (UAE)" + }, + "me-south-1": { + description: "Middle East (Bahrain)" + }, + "mx-central-1": { + description: "Mexico (Central)" + }, + "sa-east-1": { + description: "South America (Sao Paulo)" + }, + "us-east-1": { + description: "US East (N. Virginia)" + }, + "us-east-2": { + description: "US East (Ohio)" + }, + "us-west-1": { + description: "US West (N. California)" + }, + "us-west-2": { + description: "US West (Oregon)" + } + } + }, + { + id: "aws-cn", + outputs: { + dnsSuffix: "amazonaws.com.cn", + dualStackDnsSuffix: "api.amazonwebservices.com.cn", + implicitGlobalRegion: "cn-northwest-1", + name: "aws-cn", + supportsDualStack: true, + supportsFIPS: true + }, + regionRegex: "^cn\\-\\w+\\-\\d+$", + regions: { + "aws-cn-global": { + description: "aws-cn global region" + }, + "cn-north-1": { + description: "China (Beijing)" + }, + "cn-northwest-1": { + description: "China (Ningxia)" + } + } + }, + { + id: "aws-eusc", + outputs: { + dnsSuffix: "amazonaws.eu", + dualStackDnsSuffix: "api.amazonwebservices.eu", + implicitGlobalRegion: "eusc-de-east-1", + name: "aws-eusc", + supportsDualStack: true, + supportsFIPS: true + }, + regionRegex: "^eusc\\-(de)\\-\\w+\\-\\d+$", + regions: { + "eusc-de-east-1": { + description: "AWS European Sovereign Cloud (Germany)" + } + } + }, + { + id: "aws-iso", + outputs: { + dnsSuffix: "c2s.ic.gov", + dualStackDnsSuffix: "api.aws.ic.gov", + implicitGlobalRegion: "us-iso-east-1", + name: "aws-iso", + supportsDualStack: true, + supportsFIPS: true + }, + regionRegex: "^us\\-iso\\-\\w+\\-\\d+$", + regions: { + "aws-iso-global": { + description: "aws-iso global region" + }, + "us-iso-east-1": { + description: "US ISO East" + }, + "us-iso-west-1": { + description: "US ISO WEST" + } + } + }, + { + id: "aws-iso-b", + outputs: { + dnsSuffix: "sc2s.sgov.gov", + dualStackDnsSuffix: "api.aws.scloud", + implicitGlobalRegion: "us-isob-east-1", + name: "aws-iso-b", + supportsDualStack: true, + supportsFIPS: true + }, + regionRegex: "^us\\-isob\\-\\w+\\-\\d+$", + regions: { + "aws-iso-b-global": { + description: "aws-iso-b global region" + }, + "us-isob-east-1": { + description: "US ISOB East (Ohio)" + }, + "us-isob-west-1": { + description: "US ISOB West" + } + } + }, + { + id: "aws-iso-e", + outputs: { + dnsSuffix: "cloud.adc-e.uk", + dualStackDnsSuffix: "api.cloud-aws.adc-e.uk", + implicitGlobalRegion: "eu-isoe-west-1", + name: "aws-iso-e", + supportsDualStack: true, + supportsFIPS: true + }, + regionRegex: "^eu\\-isoe\\-\\w+\\-\\d+$", + regions: { + "aws-iso-e-global": { + description: "aws-iso-e global region" + }, + "eu-isoe-west-1": { + description: "EU ISOE West" + } + } + }, + { + id: "aws-iso-f", + outputs: { + dnsSuffix: "csp.hci.ic.gov", + dualStackDnsSuffix: "api.aws.hci.ic.gov", + implicitGlobalRegion: "us-isof-south-1", + name: "aws-iso-f", + supportsDualStack: true, + supportsFIPS: true + }, + regionRegex: "^us\\-isof\\-\\w+\\-\\d+$", + regions: { + "aws-iso-f-global": { + description: "aws-iso-f global region" + }, + "us-isof-east-1": { + description: "US ISOF EAST" + }, + "us-isof-south-1": { + description: "US ISOF SOUTH" + } + } + }, + { + id: "aws-us-gov", + outputs: { + dnsSuffix: "amazonaws.com", + dualStackDnsSuffix: "api.aws", + implicitGlobalRegion: "us-gov-west-1", + name: "aws-us-gov", + supportsDualStack: true, + supportsFIPS: true + }, + regionRegex: "^us\\-gov\\-\\w+\\-\\d+$", + regions: { + "aws-us-gov-global": { + description: "aws-us-gov global region" + }, + "us-gov-east-1": { + description: "AWS GovCloud (US-East)" + }, + "us-gov-west-1": { + description: "AWS GovCloud (US-West)" + } + } + } + ]; + var version3 = "1.1"; + var partitionsInfo = { + partitions, + version: version3 + }; + var selectedPartitionsInfo = partitionsInfo; + var selectedUserAgentPrefix = ""; + var partition = (value) => { + const { partitions: partitions2 } = selectedPartitionsInfo; + for (const partition2 of partitions2) { + const { regions, outputs } = partition2; + for (const [region, regionData] of Object.entries(regions)) { + if (region === value) { + return { + ...outputs, + ...regionData + }; + } + } + } + for (const partition2 of partitions2) { + const { regionRegex, outputs } = partition2; + if (new RegExp(regionRegex).test(value)) { + return { + ...outputs + }; + } + } + const DEFAULT_PARTITION = partitions2.find((partition2) => partition2.id === "aws"); + if (!DEFAULT_PARTITION) { + throw new Error("Provided region was not found in the partition array or regex, and default partition with id 'aws' doesn't exist."); + } + return { + ...DEFAULT_PARTITION.outputs + }; + }; + var setPartitionInfo = (partitionsInfo2, userAgentPrefix = "") => { + selectedPartitionsInfo = partitionsInfo2; + selectedUserAgentPrefix = userAgentPrefix; + }; + var useDefaultPartitionInfo = () => { + setPartitionInfo(partitionsInfo, ""); + }; + var getUserAgentPrefix = () => selectedUserAgentPrefix; + var awsEndpointFunctions5 = { + isVirtualHostableS3Bucket, + parseArn, + partition + }; + utilEndpoints.customEndpointFunctions.aws = awsEndpointFunctions5; + var resolveDefaultAwsRegionalEndpointsConfig = (input) => { + if (typeof input.endpointProvider !== "function") { + throw new Error("@aws-sdk/util-endpoint - endpointProvider and endpoint missing in config for this client."); + } + const { endpoint } = input; + if (endpoint === void 0) { + input.endpoint = async () => { + return toEndpointV12(input.endpointProvider({ + Region: typeof input.region === "function" ? await input.region() : input.region, + UseDualStack: typeof input.useDualstackEndpoint === "function" ? await input.useDualstackEndpoint() : input.useDualstackEndpoint, + UseFIPS: typeof input.useFipsEndpoint === "function" ? await input.useFipsEndpoint() : input.useFipsEndpoint, + Endpoint: void 0 + }, { logger: input.logger })); + }; + } + return input; + }; + var toEndpointV12 = (endpoint) => urlParser.parseUrl(endpoint.url); + exports.EndpointError = utilEndpoints.EndpointError; + exports.isIpAddress = utilEndpoints.isIpAddress; + exports.resolveEndpoint = utilEndpoints.resolveEndpoint; + exports.awsEndpointFunctions = awsEndpointFunctions5; + exports.getUserAgentPrefix = getUserAgentPrefix; + exports.partition = partition; + exports.resolveDefaultAwsRegionalEndpointsConfig = resolveDefaultAwsRegionalEndpointsConfig; + exports.setPartitionInfo = setPartitionInfo; + exports.toEndpointV1 = toEndpointV12; + exports.useDefaultPartitionInfo = useDefaultPartitionInfo; + } +}); + +// node_modules/.pnpm/@smithy+service-error-classification@4.2.13/node_modules/@smithy/service-error-classification/dist-cjs/index.js +var require_dist_cjs35 = __commonJS({ + "node_modules/.pnpm/@smithy+service-error-classification@4.2.13/node_modules/@smithy/service-error-classification/dist-cjs/index.js"(exports) { + "use strict"; + var CLOCK_SKEW_ERROR_CODES = [ + "AuthFailure", + "InvalidSignatureException", + "RequestExpired", + "RequestInTheFuture", + "RequestTimeTooSkewed", + "SignatureDoesNotMatch" + ]; + var THROTTLING_ERROR_CODES = [ + "BandwidthLimitExceeded", + "EC2ThrottledException", + "LimitExceededException", + "PriorRequestNotComplete", + "ProvisionedThroughputExceededException", + "RequestLimitExceeded", + "RequestThrottled", + "RequestThrottledException", + "SlowDown", + "ThrottledException", + "Throttling", + "ThrottlingException", + "TooManyRequestsException", + "TransactionInProgressException" + ]; + var TRANSIENT_ERROR_CODES = ["TimeoutError", "RequestTimeout", "RequestTimeoutException"]; + var TRANSIENT_ERROR_STATUS_CODES = [500, 502, 503, 504]; + var NODEJS_TIMEOUT_ERROR_CODES = ["ECONNRESET", "ECONNREFUSED", "EPIPE", "ETIMEDOUT"]; + var NODEJS_NETWORK_ERROR_CODES = ["EHOSTUNREACH", "ENETUNREACH", "ENOTFOUND"]; + var isRetryableByTrait = (error50) => error50?.$retryable !== void 0; + var isClockSkewError = (error50) => CLOCK_SKEW_ERROR_CODES.includes(error50.name); + var isClockSkewCorrectedError = (error50) => error50.$metadata?.clockSkewCorrected; + var isBrowserNetworkError = (error50) => { + const errorMessages = /* @__PURE__ */ new Set([ + "Failed to fetch", + "NetworkError when attempting to fetch resource", + "The Internet connection appears to be offline", + "Load failed", + "Network request failed" + ]); + const isValid2 = error50 && error50 instanceof TypeError; + if (!isValid2) { + return false; + } + return errorMessages.has(error50.message); + }; + var isThrottlingError = (error50) => error50.$metadata?.httpStatusCode === 429 || THROTTLING_ERROR_CODES.includes(error50.name) || error50.$retryable?.throttling == true; + var isTransientError = (error50, depth = 0) => isRetryableByTrait(error50) || isClockSkewCorrectedError(error50) || TRANSIENT_ERROR_CODES.includes(error50.name) || NODEJS_TIMEOUT_ERROR_CODES.includes(error50?.code || "") || NODEJS_NETWORK_ERROR_CODES.includes(error50?.code || "") || TRANSIENT_ERROR_STATUS_CODES.includes(error50.$metadata?.httpStatusCode || 0) || isBrowserNetworkError(error50) || error50.cause !== void 0 && depth <= 10 && isTransientError(error50.cause, depth + 1); + var isServerError = (error50) => { + if (error50.$metadata?.httpStatusCode !== void 0) { + const statusCode = error50.$metadata.httpStatusCode; + if (500 <= statusCode && statusCode <= 599 && !isTransientError(error50)) { + return true; + } + return false; + } + return false; + }; + exports.isBrowserNetworkError = isBrowserNetworkError; + exports.isClockSkewCorrectedError = isClockSkewCorrectedError; + exports.isClockSkewError = isClockSkewError; + exports.isRetryableByTrait = isRetryableByTrait; + exports.isServerError = isServerError; + exports.isThrottlingError = isThrottlingError; + exports.isTransientError = isTransientError; + } +}); + +// node_modules/.pnpm/@smithy+util-retry@4.3.1/node_modules/@smithy/util-retry/dist-cjs/index.js +var require_dist_cjs36 = __commonJS({ + "node_modules/.pnpm/@smithy+util-retry@4.3.1/node_modules/@smithy/util-retry/dist-cjs/index.js"(exports) { + "use strict"; + var serviceErrorClassification = require_dist_cjs35(); + exports.RETRY_MODES = void 0; + (function(RETRY_MODES) { + RETRY_MODES["STANDARD"] = "standard"; + RETRY_MODES["ADAPTIVE"] = "adaptive"; + })(exports.RETRY_MODES || (exports.RETRY_MODES = {})); + var DEFAULT_MAX_ATTEMPTS = 3; + var DEFAULT_RETRY_MODE5 = exports.RETRY_MODES.STANDARD; + var DefaultRateLimiter = class _DefaultRateLimiter { + static setTimeoutFn = setTimeout; + beta; + minCapacity; + minFillRate; + scaleConstant; + smooth; + enabled = false; + availableTokens = 0; + lastMaxRate = 0; + measuredTxRate = 0; + requestCount = 0; + fillRate; + lastThrottleTime; + lastTimestamp = 0; + lastTxRateBucket; + maxCapacity; + timeWindow = 0; + constructor(options) { + this.beta = options?.beta ?? 0.7; + this.minCapacity = options?.minCapacity ?? 1; + this.minFillRate = options?.minFillRate ?? 0.5; + this.scaleConstant = options?.scaleConstant ?? 0.4; + this.smooth = options?.smooth ?? 0.8; + this.lastThrottleTime = this.getCurrentTimeInSeconds(); + this.lastTxRateBucket = Math.floor(this.getCurrentTimeInSeconds()); + this.fillRate = this.minFillRate; + this.maxCapacity = this.minCapacity; + } + async getSendToken() { + return this.acquireTokenBucket(1); + } + updateClientSendingRate(response) { + let calculatedRate; + this.updateMeasuredRate(); + const retryErrorInfo = response; + const isThrottling = retryErrorInfo?.errorType === "THROTTLING" || serviceErrorClassification.isThrottlingError(retryErrorInfo?.error ?? response); + if (isThrottling) { + const rateToUse = !this.enabled ? this.measuredTxRate : Math.min(this.measuredTxRate, this.fillRate); + this.lastMaxRate = rateToUse; + this.calculateTimeWindow(); + this.lastThrottleTime = this.getCurrentTimeInSeconds(); + calculatedRate = this.cubicThrottle(rateToUse); + this.enableTokenBucket(); + } else { + this.calculateTimeWindow(); + calculatedRate = this.cubicSuccess(this.getCurrentTimeInSeconds()); + } + const newRate = Math.min(calculatedRate, 2 * this.measuredTxRate); + this.updateTokenBucketRate(newRate); + } + getCurrentTimeInSeconds() { + return Date.now() / 1e3; + } + async acquireTokenBucket(amount) { + if (!this.enabled) { + return; + } + this.refillTokenBucket(); + if (amount > this.availableTokens) { + const delay3 = (amount - this.availableTokens) / this.fillRate * 1e3; + await new Promise((resolve4) => _DefaultRateLimiter.setTimeoutFn(resolve4, delay3)); + } + this.availableTokens = this.availableTokens - amount; + } + refillTokenBucket() { + const timestamp2 = this.getCurrentTimeInSeconds(); + if (!this.lastTimestamp) { + this.lastTimestamp = timestamp2; + return; + } + const fillAmount = (timestamp2 - this.lastTimestamp) * this.fillRate; + this.availableTokens = Math.min(this.maxCapacity, this.availableTokens + fillAmount); + this.lastTimestamp = timestamp2; + } + calculateTimeWindow() { + this.timeWindow = this.getPrecise(Math.pow(this.lastMaxRate * (1 - this.beta) / this.scaleConstant, 1 / 3)); + } + cubicThrottle(rateToUse) { + return this.getPrecise(rateToUse * this.beta); + } + cubicSuccess(timestamp2) { + return this.getPrecise(this.scaleConstant * Math.pow(timestamp2 - this.lastThrottleTime - this.timeWindow, 3) + this.lastMaxRate); + } + enableTokenBucket() { + this.enabled = true; + } + updateTokenBucketRate(newRate) { + this.refillTokenBucket(); + this.fillRate = Math.max(newRate, this.minFillRate); + this.maxCapacity = Math.max(newRate, this.minCapacity); + this.availableTokens = Math.min(this.availableTokens, this.maxCapacity); + } + updateMeasuredRate() { + const t5 = this.getCurrentTimeInSeconds(); + const timeBucket = Math.floor(t5 * 2) / 2; + this.requestCount++; + if (timeBucket > this.lastTxRateBucket) { + const currentRate = this.requestCount / (timeBucket - this.lastTxRateBucket); + this.measuredTxRate = this.getPrecise(currentRate * this.smooth + this.measuredTxRate * (1 - this.smooth)); + this.requestCount = 0; + this.lastTxRateBucket = timeBucket; + } + } + getPrecise(num) { + return parseFloat(num.toFixed(8)); + } + }; + var DEFAULT_RETRY_DELAY_BASE = 100; + var MAXIMUM_RETRY_DELAY = 20 * 1e3; + var THROTTLING_RETRY_DELAY_BASE = 500; + var INITIAL_RETRY_TOKENS = 500; + var RETRY_COST = 5; + var TIMEOUT_RETRY_COST = 10; + var NO_RETRY_INCREMENT = 1; + var INVOCATION_ID_HEADER = "amz-sdk-invocation-id"; + var REQUEST_HEADER = "amz-sdk-request"; + var Retry = class _Retry { + static v2026 = typeof process !== "undefined" && process.env?.SMITHY_NEW_RETRIES_2026 === "true"; + static delay() { + return _Retry.v2026 ? 50 : 100; + } + static throttlingDelay() { + return _Retry.v2026 ? 1e3 : 500; + } + static cost() { + return _Retry.v2026 ? 14 : 5; + } + static throttlingCost() { + return _Retry.v2026 ? 5 : 10; + } + static modifiedCostType() { + return _Retry.v2026 ? "THROTTLING" : "TRANSIENT"; + } + }; + var DefaultRetryBackoffStrategy = class { + x = Retry.delay(); + computeNextBackoffDelay(i5) { + const b6 = Math.random(); + const r5 = 2; + const t_i = b6 * Math.min(this.x * r5 ** i5, MAXIMUM_RETRY_DELAY); + return Math.floor(t_i); + } + setDelayBase(delay3) { + this.x = delay3; + } + }; + var DefaultRetryToken = class { + delay; + count; + cost; + longPoll; + constructor(delay3, count2, cost, longPoll) { + this.delay = delay3; + this.count = count2; + this.cost = cost; + this.longPoll = longPoll; + } + getRetryCount() { + return this.count; + } + getRetryDelay() { + return Math.min(MAXIMUM_RETRY_DELAY, this.delay); + } + getRetryCost() { + return this.cost; + } + isLongPoll() { + return this.longPoll; + } + }; + var StandardRetryStrategy = class { + mode = exports.RETRY_MODES.STANDARD; + capacity = INITIAL_RETRY_TOKENS; + retryBackoffStrategy; + maxAttemptsProvider; + baseDelay; + constructor(arg1) { + if (typeof arg1 === "number") { + this.maxAttemptsProvider = async () => arg1; + } else if (typeof arg1 === "function") { + this.maxAttemptsProvider = arg1; + } else if (arg1 && typeof arg1 === "object") { + this.maxAttemptsProvider = async () => arg1.maxAttempts; + this.baseDelay = arg1.baseDelay; + this.retryBackoffStrategy = arg1.backoff; + } + this.maxAttemptsProvider ??= async () => DEFAULT_MAX_ATTEMPTS; + this.baseDelay ??= Retry.delay(); + this.retryBackoffStrategy ??= new DefaultRetryBackoffStrategy(); + } + async acquireInitialRetryToken(retryTokenScope) { + return new DefaultRetryToken(Retry.delay(), 0, void 0, Retry.v2026 && retryTokenScope.includes(":longpoll")); + } + async refreshRetryTokenForRetry(token, errorInfo) { + const maxAttempts = await this.getMaxAttempts(); + const shouldRetry = this.shouldRetry(token, errorInfo, maxAttempts); + if (shouldRetry || token.isLongPoll?.()) { + const errorType = errorInfo.errorType; + this.retryBackoffStrategy.setDelayBase(errorType === "THROTTLING" ? Retry.throttlingDelay() : this.baseDelay); + const delayFromErrorType = this.retryBackoffStrategy.computeNextBackoffDelay(token.getRetryCount()); + let retryDelay = delayFromErrorType; + if (errorInfo.retryAfterHint instanceof Date) { + retryDelay = Math.max(delayFromErrorType, Math.min(errorInfo.retryAfterHint.getTime() - Date.now(), delayFromErrorType + 5e3)); + } + if (!shouldRetry) { + throw Object.assign(new Error("No retry token available"), { $backoff: Retry.v2026 ? retryDelay : 0 }); + } else { + const capacityCost = this.getCapacityCost(errorType); + this.capacity -= capacityCost; + return new DefaultRetryToken(retryDelay, token.getRetryCount() + 1, capacityCost, token.isLongPoll?.() ?? false); + } + } + throw new Error("No retry token available"); + } + recordSuccess(token) { + this.capacity = Math.min(INITIAL_RETRY_TOKENS, this.capacity + (token.getRetryCost() ?? NO_RETRY_INCREMENT)); + } + getCapacity() { + return this.capacity; + } + async getMaxAttempts() { + try { + return await this.maxAttemptsProvider(); + } catch (error50) { + console.warn(`Max attempts provider could not resolve. Using default of ${DEFAULT_MAX_ATTEMPTS}`); + return DEFAULT_MAX_ATTEMPTS; + } + } + shouldRetry(tokenToRenew, errorInfo, maxAttempts) { + const attempts = tokenToRenew.getRetryCount() + 1; + return attempts < maxAttempts && this.capacity >= this.getCapacityCost(errorInfo.errorType) && this.isRetryableError(errorInfo.errorType); + } + getCapacityCost(errorType) { + return errorType === Retry.modifiedCostType() ? Retry.throttlingCost() : Retry.cost(); + } + isRetryableError(errorType) { + return errorType === "THROTTLING" || errorType === "TRANSIENT"; + } + async maxAttempts() { + return this.maxAttemptsProvider(); + } + }; + var AdaptiveRetryStrategy = class { + mode = exports.RETRY_MODES.ADAPTIVE; + rateLimiter; + standardRetryStrategy; + constructor(maxAttemptsProvider, options) { + const { rateLimiter } = options ?? {}; + this.rateLimiter = rateLimiter ?? new DefaultRateLimiter(); + this.standardRetryStrategy = options ? new StandardRetryStrategy({ + maxAttempts: typeof maxAttemptsProvider === "number" ? maxAttemptsProvider : 3, + ...options + }) : new StandardRetryStrategy(maxAttemptsProvider); + } + async acquireInitialRetryToken(retryTokenScope) { + await this.rateLimiter.getSendToken(); + return this.standardRetryStrategy.acquireInitialRetryToken(retryTokenScope); + } + async refreshRetryTokenForRetry(tokenToRenew, errorInfo) { + this.rateLimiter.updateClientSendingRate(errorInfo); + return this.standardRetryStrategy.refreshRetryTokenForRetry(tokenToRenew, errorInfo); + } + recordSuccess(token) { + this.rateLimiter.updateClientSendingRate({}); + this.standardRetryStrategy.recordSuccess(token); + } + async maxAttemptsProvider() { + return this.standardRetryStrategy.maxAttempts(); + } + }; + var ConfiguredRetryStrategy = class extends StandardRetryStrategy { + computeNextBackoffDelay; + constructor(maxAttempts, computeNextBackoffDelay = Retry.delay()) { + super(typeof maxAttempts === "function" ? maxAttempts : async () => maxAttempts); + if (typeof computeNextBackoffDelay === "number") { + this.computeNextBackoffDelay = () => computeNextBackoffDelay; + } else { + this.computeNextBackoffDelay = computeNextBackoffDelay; + } + } + async refreshRetryTokenForRetry(tokenToRenew, errorInfo) { + const token = await super.refreshRetryTokenForRetry(tokenToRenew, errorInfo); + token.getRetryDelay = () => this.computeNextBackoffDelay(token.getRetryCount()); + return token; + } + }; + exports.AdaptiveRetryStrategy = AdaptiveRetryStrategy; + exports.ConfiguredRetryStrategy = ConfiguredRetryStrategy; + exports.DEFAULT_MAX_ATTEMPTS = DEFAULT_MAX_ATTEMPTS; + exports.DEFAULT_RETRY_DELAY_BASE = DEFAULT_RETRY_DELAY_BASE; + exports.DEFAULT_RETRY_MODE = DEFAULT_RETRY_MODE5; + exports.DefaultRateLimiter = DefaultRateLimiter; + exports.INITIAL_RETRY_TOKENS = INITIAL_RETRY_TOKENS; + exports.INVOCATION_ID_HEADER = INVOCATION_ID_HEADER; + exports.MAXIMUM_RETRY_DELAY = MAXIMUM_RETRY_DELAY; + exports.NO_RETRY_INCREMENT = NO_RETRY_INCREMENT; + exports.REQUEST_HEADER = REQUEST_HEADER; + exports.RETRY_COST = RETRY_COST; + exports.Retry = Retry; + exports.StandardRetryStrategy = StandardRetryStrategy; + exports.THROTTLING_RETRY_DELAY_BASE = THROTTLING_RETRY_DELAY_BASE; + exports.TIMEOUT_RETRY_COST = TIMEOUT_RETRY_COST; + } +}); + +// node_modules/.pnpm/@aws-sdk+middleware-user-agent@3.972.29/node_modules/@aws-sdk/middleware-user-agent/dist-cjs/index.js +var require_dist_cjs37 = __commonJS({ + "node_modules/.pnpm/@aws-sdk+middleware-user-agent@3.972.29/node_modules/@aws-sdk/middleware-user-agent/dist-cjs/index.js"(exports) { + "use strict"; + var core = (init_dist_es(), __toCommonJS(dist_es_exports)); + var utilEndpoints = require_dist_cjs34(); + var protocolHttp = require_dist_cjs2(); + var client2 = (init_client2(), __toCommonJS(client_exports)); + var utilRetry = require_dist_cjs36(); + var DEFAULT_UA_APP_ID = void 0; + function isValidUserAgentAppId(appId) { + if (appId === void 0) { + return true; + } + return typeof appId === "string" && appId.length <= 50; + } + function resolveUserAgentConfig5(input) { + const normalizedAppIdProvider = core.normalizeProvider(input.userAgentAppId ?? DEFAULT_UA_APP_ID); + const { customUserAgent } = input; + return Object.assign(input, { + customUserAgent: typeof customUserAgent === "string" ? [[customUserAgent]] : customUserAgent, + userAgentAppId: async () => { + const appId = await normalizedAppIdProvider(); + if (!isValidUserAgentAppId(appId)) { + const logger4 = input.logger?.constructor?.name === "NoOpLogger" || !input.logger ? console : input.logger; + if (typeof appId !== "string") { + logger4?.warn("userAgentAppId must be a string or undefined."); + } else if (appId.length > 50) { + logger4?.warn("The provided userAgentAppId exceeds the maximum length of 50 characters."); + } + } + return appId; + } + }); + } + var ACCOUNT_ID_ENDPOINT_REGEX = /\d{12}\.ddb/; + async function checkFeatures(context, config3, args) { + const request = args.request; + if (request?.headers?.["smithy-protocol"] === "rpc-v2-cbor") { + client2.setFeature(context, "PROTOCOL_RPC_V2_CBOR", "M"); + } + if (typeof config3.retryStrategy === "function") { + const retryStrategy = await config3.retryStrategy(); + if (typeof retryStrategy.mode === "string") { + switch (retryStrategy.mode) { + case utilRetry.RETRY_MODES.ADAPTIVE: + client2.setFeature(context, "RETRY_MODE_ADAPTIVE", "F"); + break; + case utilRetry.RETRY_MODES.STANDARD: + client2.setFeature(context, "RETRY_MODE_STANDARD", "E"); + break; + } + } + } + if (typeof config3.accountIdEndpointMode === "function") { + const endpointV2 = context.endpointV2; + if (String(endpointV2?.url?.hostname).match(ACCOUNT_ID_ENDPOINT_REGEX)) { + client2.setFeature(context, "ACCOUNT_ID_ENDPOINT", "O"); + } + switch (await config3.accountIdEndpointMode?.()) { + case "disabled": + client2.setFeature(context, "ACCOUNT_ID_MODE_DISABLED", "Q"); + break; + case "preferred": + client2.setFeature(context, "ACCOUNT_ID_MODE_PREFERRED", "P"); + break; + case "required": + client2.setFeature(context, "ACCOUNT_ID_MODE_REQUIRED", "R"); + break; + } + } + const identity = context.__smithy_context?.selectedHttpAuthScheme?.identity; + if (identity?.$source) { + const credentials = identity; + if (credentials.accountId) { + client2.setFeature(context, "RESOLVED_ACCOUNT_ID", "T"); + } + for (const [key, value] of Object.entries(credentials.$source ?? {})) { + client2.setFeature(context, key, value); + } + } + } + var USER_AGENT2 = "user-agent"; + var X_AMZ_USER_AGENT = "x-amz-user-agent"; + var SPACE = " "; + var UA_NAME_SEPARATOR = "/"; + var UA_NAME_ESCAPE_REGEX = /[^!$%&'*+\-.^_`|~\w]/g; + var UA_VALUE_ESCAPE_REGEX = /[^!$%&'*+\-.^_`|~\w#]/g; + var UA_ESCAPE_CHAR = "-"; + var BYTE_LIMIT = 1024; + function encodeFeatures(features) { + let buffer2 = ""; + for (const key in features) { + const val = features[key]; + if (buffer2.length + val.length + 1 <= BYTE_LIMIT) { + if (buffer2.length) { + buffer2 += "," + val; + } else { + buffer2 += val; + } + continue; + } + break; + } + return buffer2; + } + var userAgentMiddleware = (options) => (next, context) => async (args) => { + const { request } = args; + if (!protocolHttp.HttpRequest.isInstance(request)) { + return next(args); + } + const { headers } = request; + const userAgent = context?.userAgent?.map(escapeUserAgent) || []; + const defaultUserAgent = (await options.defaultUserAgentProvider()).map(escapeUserAgent); + await checkFeatures(context, options, args); + const awsContext = context; + defaultUserAgent.push(`m/${encodeFeatures(Object.assign({}, context.__smithy_context?.features, awsContext.__aws_sdk_context?.features))}`); + const customUserAgent = options?.customUserAgent?.map(escapeUserAgent) || []; + const appId = await options.userAgentAppId(); + if (appId) { + defaultUserAgent.push(escapeUserAgent([`app`, `${appId}`])); + } + const prefix = utilEndpoints.getUserAgentPrefix(); + const sdkUserAgentValue = (prefix ? [prefix] : []).concat([...defaultUserAgent, ...userAgent, ...customUserAgent]).join(SPACE); + const normalUAValue = [ + ...defaultUserAgent.filter((section) => section.startsWith("aws-sdk-")), + ...customUserAgent + ].join(SPACE); + if (options.runtime !== "browser") { + if (normalUAValue) { + headers[X_AMZ_USER_AGENT] = headers[X_AMZ_USER_AGENT] ? `${headers[USER_AGENT2]} ${normalUAValue}` : normalUAValue; + } + headers[USER_AGENT2] = sdkUserAgentValue; + } else { + headers[X_AMZ_USER_AGENT] = sdkUserAgentValue; + } + return next({ + ...args, + request + }); + }; + var escapeUserAgent = (userAgentPair) => { + const name = userAgentPair[0].split(UA_NAME_SEPARATOR).map((part) => part.replace(UA_NAME_ESCAPE_REGEX, UA_ESCAPE_CHAR)).join(UA_NAME_SEPARATOR); + const version3 = userAgentPair[1]?.replace(UA_VALUE_ESCAPE_REGEX, UA_ESCAPE_CHAR); + const prefixSeparatorIndex = name.indexOf(UA_NAME_SEPARATOR); + const prefix = name.substring(0, prefixSeparatorIndex); + let uaName = name.substring(prefixSeparatorIndex + 1); + if (prefix === "api") { + uaName = uaName.toLowerCase(); + } + return [prefix, uaName, version3].filter((item) => item && item.length > 0).reduce((acc, item, index2) => { + switch (index2) { + case 0: + return item; + case 1: + return `${acc}/${item}`; + default: + return `${acc}#${item}`; + } + }, ""); + }; + var getUserAgentMiddlewareOptions = { + name: "getUserAgentMiddleware", + step: "build", + priority: "low", + tags: ["SET_USER_AGENT", "USER_AGENT"], + override: true + }; + var getUserAgentPlugin5 = (config3) => ({ + applyToStack: (clientStack) => { + clientStack.add(userAgentMiddleware(config3), getUserAgentMiddlewareOptions); + } + }); + exports.DEFAULT_UA_APP_ID = DEFAULT_UA_APP_ID; + exports.getUserAgentMiddlewareOptions = getUserAgentMiddlewareOptions; + exports.getUserAgentPlugin = getUserAgentPlugin5; + exports.resolveUserAgentConfig = resolveUserAgentConfig5; + exports.userAgentMiddleware = userAgentMiddleware; + } +}); + +// node_modules/.pnpm/@smithy+config-resolver@4.4.15/node_modules/@smithy/config-resolver/dist-cjs/index.js +var require_dist_cjs38 = __commonJS({ + "node_modules/.pnpm/@smithy+config-resolver@4.4.15/node_modules/@smithy/config-resolver/dist-cjs/index.js"(exports) { + "use strict"; + var utilConfigProvider = require_dist_cjs31(); + var utilMiddleware = require_dist_cjs18(); + var utilEndpoints = require_dist_cjs33(); + var ENV_USE_DUALSTACK_ENDPOINT = "AWS_USE_DUALSTACK_ENDPOINT"; + var CONFIG_USE_DUALSTACK_ENDPOINT = "use_dualstack_endpoint"; + var DEFAULT_USE_DUALSTACK_ENDPOINT = false; + var NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS5 = { + environmentVariableSelector: (env2) => utilConfigProvider.booleanSelector(env2, ENV_USE_DUALSTACK_ENDPOINT, utilConfigProvider.SelectorType.ENV), + configFileSelector: (profile) => utilConfigProvider.booleanSelector(profile, CONFIG_USE_DUALSTACK_ENDPOINT, utilConfigProvider.SelectorType.CONFIG), + default: false + }; + var nodeDualstackConfigSelectors = { + environmentVariableSelector: (env2) => utilConfigProvider.booleanSelector(env2, ENV_USE_DUALSTACK_ENDPOINT, utilConfigProvider.SelectorType.ENV), + configFileSelector: (profile) => utilConfigProvider.booleanSelector(profile, CONFIG_USE_DUALSTACK_ENDPOINT, utilConfigProvider.SelectorType.CONFIG), + default: void 0 + }; + var ENV_USE_FIPS_ENDPOINT = "AWS_USE_FIPS_ENDPOINT"; + var CONFIG_USE_FIPS_ENDPOINT = "use_fips_endpoint"; + var DEFAULT_USE_FIPS_ENDPOINT = false; + var NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS5 = { + environmentVariableSelector: (env2) => utilConfigProvider.booleanSelector(env2, ENV_USE_FIPS_ENDPOINT, utilConfigProvider.SelectorType.ENV), + configFileSelector: (profile) => utilConfigProvider.booleanSelector(profile, CONFIG_USE_FIPS_ENDPOINT, utilConfigProvider.SelectorType.CONFIG), + default: false + }; + var nodeFipsConfigSelectors = { + environmentVariableSelector: (env2) => utilConfigProvider.booleanSelector(env2, ENV_USE_FIPS_ENDPOINT, utilConfigProvider.SelectorType.ENV), + configFileSelector: (profile) => utilConfigProvider.booleanSelector(profile, CONFIG_USE_FIPS_ENDPOINT, utilConfigProvider.SelectorType.CONFIG), + default: void 0 + }; + var resolveCustomEndpointsConfig = (input) => { + const { tls: tls2, endpoint, urlParser, useDualstackEndpoint } = input; + return Object.assign(input, { + tls: tls2 ?? true, + endpoint: utilMiddleware.normalizeProvider(typeof endpoint === "string" ? urlParser(endpoint) : endpoint), + isCustomEndpoint: true, + useDualstackEndpoint: utilMiddleware.normalizeProvider(useDualstackEndpoint ?? false) + }); + }; + var getEndpointFromRegion = async (input) => { + const { tls: tls2 = true } = input; + const region = await input.region(); + const dnsHostRegex = new RegExp(/^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9])$/); + if (!dnsHostRegex.test(region)) { + throw new Error("Invalid region in client config"); + } + const useDualstackEndpoint = await input.useDualstackEndpoint(); + const useFipsEndpoint = await input.useFipsEndpoint(); + const { hostname: hostname3 } = await input.regionInfoProvider(region, { useDualstackEndpoint, useFipsEndpoint }) ?? {}; + if (!hostname3) { + throw new Error("Cannot resolve hostname from client config"); + } + return input.urlParser(`${tls2 ? "https:" : "http:"}//${hostname3}`); + }; + var resolveEndpointsConfig = (input) => { + const useDualstackEndpoint = utilMiddleware.normalizeProvider(input.useDualstackEndpoint ?? false); + const { endpoint, useFipsEndpoint, urlParser, tls: tls2 } = input; + return Object.assign(input, { + tls: tls2 ?? true, + endpoint: endpoint ? utilMiddleware.normalizeProvider(typeof endpoint === "string" ? urlParser(endpoint) : endpoint) : () => getEndpointFromRegion({ ...input, useDualstackEndpoint, useFipsEndpoint }), + isCustomEndpoint: !!endpoint, + useDualstackEndpoint + }); + }; + var REGION_ENV_NAME = "AWS_REGION"; + var REGION_INI_NAME = "region"; + var NODE_REGION_CONFIG_OPTIONS5 = { + environmentVariableSelector: (env2) => env2[REGION_ENV_NAME], + configFileSelector: (profile) => profile[REGION_INI_NAME], + default: () => { + throw new Error("Region is missing"); + } + }; + var NODE_REGION_CONFIG_FILE_OPTIONS5 = { + preferredFile: "credentials" + }; + var validRegions = /* @__PURE__ */ new Set(); + var checkRegion = (region, check3 = utilEndpoints.isValidHostLabel) => { + if (!validRegions.has(region) && !check3(region)) { + if (region === "*") { + console.warn(`@smithy/config-resolver WARN - Please use the caller region instead of "*". See "sigv4a" in https://github.com/aws/aws-sdk-js-v3/blob/main/supplemental-docs/CLIENTS.md.`); + } else { + throw new Error(`Region not accepted: region="${region}" is not a valid hostname component.`); + } + } else { + validRegions.add(region); + } + }; + var isFipsRegion = (region) => typeof region === "string" && (region.startsWith("fips-") || region.endsWith("-fips")); + var getRealRegion = (region) => isFipsRegion(region) ? ["fips-aws-global", "aws-fips"].includes(region) ? "us-east-1" : region.replace(/fips-(dkr-|prod-)?|-fips/, "") : region; + var resolveRegionConfig5 = (input) => { + const { region, useFipsEndpoint } = input; + if (!region) { + throw new Error("Region is missing"); + } + return Object.assign(input, { + region: async () => { + const providedRegion = typeof region === "function" ? await region() : region; + const realRegion = getRealRegion(providedRegion); + checkRegion(realRegion); + return realRegion; + }, + useFipsEndpoint: async () => { + const providedRegion = typeof region === "string" ? region : await region(); + if (isFipsRegion(providedRegion)) { + return true; + } + return typeof useFipsEndpoint !== "function" ? Promise.resolve(!!useFipsEndpoint) : useFipsEndpoint(); + } + }); + }; + var getHostnameFromVariants = (variants = [], { useFipsEndpoint, useDualstackEndpoint }) => variants.find(({ tags }) => useFipsEndpoint === tags.includes("fips") && useDualstackEndpoint === tags.includes("dualstack"))?.hostname; + var getResolvedHostname = (resolvedRegion, { regionHostname, partitionHostname }) => regionHostname ? regionHostname : partitionHostname ? partitionHostname.replace("{region}", resolvedRegion) : void 0; + var getResolvedPartition = (region, { partitionHash }) => Object.keys(partitionHash || {}).find((key) => partitionHash[key].regions.includes(region)) ?? "aws"; + var getResolvedSigningRegion = (hostname3, { signingRegion, regionRegex, useFipsEndpoint }) => { + if (signingRegion) { + return signingRegion; + } else if (useFipsEndpoint) { + const regionRegexJs = regionRegex.replace("\\\\", "\\").replace(/^\^/g, "\\.").replace(/\$$/g, "\\."); + const regionRegexmatchArray = hostname3.match(regionRegexJs); + if (regionRegexmatchArray) { + return regionRegexmatchArray[0].slice(1, -1); + } + } + }; + var getRegionInfo = (region, { useFipsEndpoint = false, useDualstackEndpoint = false, signingService, regionHash, partitionHash }) => { + const partition = getResolvedPartition(region, { partitionHash }); + const resolvedRegion = region in regionHash ? region : partitionHash[partition]?.endpoint ?? region; + const hostnameOptions = { useFipsEndpoint, useDualstackEndpoint }; + const regionHostname = getHostnameFromVariants(regionHash[resolvedRegion]?.variants, hostnameOptions); + const partitionHostname = getHostnameFromVariants(partitionHash[partition]?.variants, hostnameOptions); + const hostname3 = getResolvedHostname(resolvedRegion, { regionHostname, partitionHostname }); + if (hostname3 === void 0) { + throw new Error(`Endpoint resolution failed for: ${{ resolvedRegion, useFipsEndpoint, useDualstackEndpoint }}`); + } + const signingRegion = getResolvedSigningRegion(hostname3, { + signingRegion: regionHash[resolvedRegion]?.signingRegion, + regionRegex: partitionHash[partition].regionRegex, + useFipsEndpoint + }); + return { + partition, + signingService, + hostname: hostname3, + ...signingRegion && { signingRegion }, + ...regionHash[resolvedRegion]?.signingService && { + signingService: regionHash[resolvedRegion].signingService + } + }; + }; + exports.CONFIG_USE_DUALSTACK_ENDPOINT = CONFIG_USE_DUALSTACK_ENDPOINT; + exports.CONFIG_USE_FIPS_ENDPOINT = CONFIG_USE_FIPS_ENDPOINT; + exports.DEFAULT_USE_DUALSTACK_ENDPOINT = DEFAULT_USE_DUALSTACK_ENDPOINT; + exports.DEFAULT_USE_FIPS_ENDPOINT = DEFAULT_USE_FIPS_ENDPOINT; + exports.ENV_USE_DUALSTACK_ENDPOINT = ENV_USE_DUALSTACK_ENDPOINT; + exports.ENV_USE_FIPS_ENDPOINT = ENV_USE_FIPS_ENDPOINT; + exports.NODE_REGION_CONFIG_FILE_OPTIONS = NODE_REGION_CONFIG_FILE_OPTIONS5; + exports.NODE_REGION_CONFIG_OPTIONS = NODE_REGION_CONFIG_OPTIONS5; + exports.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS = NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS5; + exports.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS = NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS5; + exports.REGION_ENV_NAME = REGION_ENV_NAME; + exports.REGION_INI_NAME = REGION_INI_NAME; + exports.getRegionInfo = getRegionInfo; + exports.nodeDualstackConfigSelectors = nodeDualstackConfigSelectors; + exports.nodeFipsConfigSelectors = nodeFipsConfigSelectors; + exports.resolveCustomEndpointsConfig = resolveCustomEndpointsConfig; + exports.resolveEndpointsConfig = resolveEndpointsConfig; + exports.resolveRegionConfig = resolveRegionConfig5; + } +}); + +// node_modules/.pnpm/@smithy+eventstream-serde-config-resolver@4.3.13/node_modules/@smithy/eventstream-serde-config-resolver/dist-cjs/index.js +var require_dist_cjs39 = __commonJS({ + "node_modules/.pnpm/@smithy+eventstream-serde-config-resolver@4.3.13/node_modules/@smithy/eventstream-serde-config-resolver/dist-cjs/index.js"(exports) { + "use strict"; + var resolveEventStreamSerdeConfig = (input) => Object.assign(input, { + eventStreamMarshaller: input.eventStreamSerdeProvider(input) + }); + exports.resolveEventStreamSerdeConfig = resolveEventStreamSerdeConfig; + } +}); + +// node_modules/.pnpm/@smithy+middleware-content-length@4.2.13/node_modules/@smithy/middleware-content-length/dist-cjs/index.js +var require_dist_cjs40 = __commonJS({ + "node_modules/.pnpm/@smithy+middleware-content-length@4.2.13/node_modules/@smithy/middleware-content-length/dist-cjs/index.js"(exports) { + "use strict"; + var protocolHttp = require_dist_cjs2(); + var CONTENT_LENGTH_HEADER = "content-length"; + function contentLengthMiddleware(bodyLengthChecker) { + return (next) => async (args) => { + const request = args.request; + if (protocolHttp.HttpRequest.isInstance(request)) { + const { body, headers } = request; + if (body && Object.keys(headers).map((str) => str.toLowerCase()).indexOf(CONTENT_LENGTH_HEADER) === -1) { + try { + const length = bodyLengthChecker(body); + request.headers = { + ...request.headers, + [CONTENT_LENGTH_HEADER]: String(length) + }; + } catch (error50) { + } + } + } + return next({ + ...args, + request + }); + }; + } + var contentLengthMiddlewareOptions = { + step: "build", + tags: ["SET_CONTENT_LENGTH", "CONTENT_LENGTH"], + name: "contentLengthMiddleware", + override: true + }; + var getContentLengthPlugin5 = (options) => ({ + applyToStack: (clientStack) => { + clientStack.add(contentLengthMiddleware(options.bodyLengthChecker), contentLengthMiddlewareOptions); + } + }); + exports.contentLengthMiddleware = contentLengthMiddleware; + exports.contentLengthMiddlewareOptions = contentLengthMiddlewareOptions; + exports.getContentLengthPlugin = getContentLengthPlugin5; + } +}); + +// node_modules/.pnpm/@smithy+property-provider@4.2.13/node_modules/@smithy/property-provider/dist-cjs/index.js +var require_dist_cjs41 = __commonJS({ + "node_modules/.pnpm/@smithy+property-provider@4.2.13/node_modules/@smithy/property-provider/dist-cjs/index.js"(exports) { + "use strict"; + var ProviderError2 = class _ProviderError extends Error { + name = "ProviderError"; + tryNextLink; + constructor(message2, options = true) { + let logger4; + let tryNextLink = true; + if (typeof options === "boolean") { + logger4 = void 0; + tryNextLink = options; + } else if (options != null && typeof options === "object") { + logger4 = options.logger; + tryNextLink = options.tryNextLink ?? true; + } + super(message2); + this.tryNextLink = tryNextLink; + Object.setPrototypeOf(this, _ProviderError.prototype); + logger4?.debug?.(`@smithy/property-provider ${tryNextLink ? "->" : "(!)"} ${message2}`); + } + static from(error50, options = true) { + return Object.assign(new this(error50.message, options), error50); + } + }; + var CredentialsProviderError = class _CredentialsProviderError extends ProviderError2 { + name = "CredentialsProviderError"; + constructor(message2, options = true) { + super(message2, options); + Object.setPrototypeOf(this, _CredentialsProviderError.prototype); + } + }; + var TokenProviderError = class _TokenProviderError extends ProviderError2 { + name = "TokenProviderError"; + constructor(message2, options = true) { + super(message2, options); + Object.setPrototypeOf(this, _TokenProviderError.prototype); + } + }; + var chain = (...providers2) => async () => { + if (providers2.length === 0) { + throw new ProviderError2("No providers in chain"); + } + let lastProviderError; + for (const provider of providers2) { + try { + const credentials = await provider(); + return credentials; + } catch (err) { + lastProviderError = err; + if (err?.tryNextLink) { + continue; + } + throw err; + } + } + throw lastProviderError; + }; + var fromStatic = (staticValue) => () => Promise.resolve(staticValue); + var memoize = (provider, isExpired, requiresRefresh) => { + let resolved; + let pending; + let hasResult; + let isConstant = false; + const coalesceProvider = async () => { + if (!pending) { + pending = provider(); + } + try { + resolved = await pending; + hasResult = true; + isConstant = false; + } finally { + pending = void 0; + } + return resolved; + }; + if (isExpired === void 0) { + return async (options) => { + if (!hasResult || options?.forceRefresh) { + resolved = await coalesceProvider(); + } + return resolved; + }; + } + return async (options) => { + if (!hasResult || options?.forceRefresh) { + resolved = await coalesceProvider(); + } + if (isConstant) { + return resolved; + } + if (requiresRefresh && !requiresRefresh(resolved)) { + isConstant = true; + return resolved; + } + if (isExpired(resolved)) { + await coalesceProvider(); + return resolved; + } + return resolved; + }; + }; + exports.CredentialsProviderError = CredentialsProviderError; + exports.ProviderError = ProviderError2; + exports.TokenProviderError = TokenProviderError; + exports.chain = chain; + exports.fromStatic = fromStatic; + exports.memoize = memoize; + } +}); + +// node_modules/.pnpm/@smithy+shared-ini-file-loader@4.4.8/node_modules/@smithy/shared-ini-file-loader/dist-cjs/getHomeDir.js +var require_getHomeDir = __commonJS({ + "node_modules/.pnpm/@smithy+shared-ini-file-loader@4.4.8/node_modules/@smithy/shared-ini-file-loader/dist-cjs/getHomeDir.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getHomeDir = void 0; + var os_1 = __require("os"); + var path_1 = __require("path"); + var homeDirCache = {}; + var getHomeDirCacheKey = () => { + if (process && process.geteuid) { + return `${process.geteuid()}`; + } + return "DEFAULT"; + }; + var getHomeDir = () => { + const { HOME, USERPROFILE, HOMEPATH, HOMEDRIVE = `C:${path_1.sep}` } = process.env; + if (HOME) + return HOME; + if (USERPROFILE) + return USERPROFILE; + if (HOMEPATH) + return `${HOMEDRIVE}${HOMEPATH}`; + const homeDirCacheKey = getHomeDirCacheKey(); + if (!homeDirCache[homeDirCacheKey]) + homeDirCache[homeDirCacheKey] = (0, os_1.homedir)(); + return homeDirCache[homeDirCacheKey]; + }; + exports.getHomeDir = getHomeDir; + } +}); + +// node_modules/.pnpm/@smithy+shared-ini-file-loader@4.4.8/node_modules/@smithy/shared-ini-file-loader/dist-cjs/getSSOTokenFilepath.js +var require_getSSOTokenFilepath = __commonJS({ + "node_modules/.pnpm/@smithy+shared-ini-file-loader@4.4.8/node_modules/@smithy/shared-ini-file-loader/dist-cjs/getSSOTokenFilepath.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getSSOTokenFilepath = void 0; + var crypto_1 = __require("crypto"); + var path_1 = __require("path"); + var getHomeDir_1 = require_getHomeDir(); + var getSSOTokenFilepath = (id) => { + const hasher = (0, crypto_1.createHash)("sha1"); + const cacheName = hasher.update(id).digest("hex"); + return (0, path_1.join)((0, getHomeDir_1.getHomeDir)(), ".aws", "sso", "cache", `${cacheName}.json`); + }; + exports.getSSOTokenFilepath = getSSOTokenFilepath; + } +}); + +// node_modules/.pnpm/@smithy+shared-ini-file-loader@4.4.8/node_modules/@smithy/shared-ini-file-loader/dist-cjs/getSSOTokenFromFile.js +var require_getSSOTokenFromFile = __commonJS({ + "node_modules/.pnpm/@smithy+shared-ini-file-loader@4.4.8/node_modules/@smithy/shared-ini-file-loader/dist-cjs/getSSOTokenFromFile.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getSSOTokenFromFile = exports.tokenIntercept = void 0; + var promises_1 = __require("fs/promises"); + var getSSOTokenFilepath_1 = require_getSSOTokenFilepath(); + exports.tokenIntercept = {}; + var getSSOTokenFromFile = async (id) => { + if (exports.tokenIntercept[id]) { + return exports.tokenIntercept[id]; + } + const ssoTokenFilepath = (0, getSSOTokenFilepath_1.getSSOTokenFilepath)(id); + const ssoTokenText = await (0, promises_1.readFile)(ssoTokenFilepath, "utf8"); + return JSON.parse(ssoTokenText); + }; + exports.getSSOTokenFromFile = getSSOTokenFromFile; + } +}); + +// node_modules/.pnpm/@smithy+shared-ini-file-loader@4.4.8/node_modules/@smithy/shared-ini-file-loader/dist-cjs/readFile.js +var require_readFile = __commonJS({ + "node_modules/.pnpm/@smithy+shared-ini-file-loader@4.4.8/node_modules/@smithy/shared-ini-file-loader/dist-cjs/readFile.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.readFile = exports.fileIntercept = exports.filePromises = void 0; + var promises_1 = __require("node:fs/promises"); + exports.filePromises = {}; + exports.fileIntercept = {}; + var readFile5 = (path53, options) => { + if (exports.fileIntercept[path53] !== void 0) { + return exports.fileIntercept[path53]; + } + if (!exports.filePromises[path53] || options?.ignoreCache) { + exports.filePromises[path53] = (0, promises_1.readFile)(path53, "utf8"); + } + return exports.filePromises[path53]; + }; + exports.readFile = readFile5; + } +}); + +// node_modules/.pnpm/@smithy+shared-ini-file-loader@4.4.8/node_modules/@smithy/shared-ini-file-loader/dist-cjs/index.js +var require_dist_cjs42 = __commonJS({ + "node_modules/.pnpm/@smithy+shared-ini-file-loader@4.4.8/node_modules/@smithy/shared-ini-file-loader/dist-cjs/index.js"(exports) { + "use strict"; + var getHomeDir = require_getHomeDir(); + var getSSOTokenFilepath = require_getSSOTokenFilepath(); + var getSSOTokenFromFile = require_getSSOTokenFromFile(); + var path53 = __require("path"); + var types2 = require_dist_cjs(); + var readFile5 = require_readFile(); + var ENV_PROFILE = "AWS_PROFILE"; + var DEFAULT_PROFILE = "default"; + var getProfileName = (init2) => init2.profile || process.env[ENV_PROFILE] || DEFAULT_PROFILE; + var CONFIG_PREFIX_SEPARATOR = "."; + var getConfigData = (data2) => Object.entries(data2).filter(([key]) => { + const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR); + if (indexOfSeparator === -1) { + return false; + } + return Object.values(types2.IniSectionType).includes(key.substring(0, indexOfSeparator)); + }).reduce((acc, [key, value]) => { + const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR); + const updatedKey = key.substring(0, indexOfSeparator) === types2.IniSectionType.PROFILE ? key.substring(indexOfSeparator + 1) : key; + acc[updatedKey] = value; + return acc; + }, { + ...data2.default && { default: data2.default } + }); + var ENV_CONFIG_PATH = "AWS_CONFIG_FILE"; + var getConfigFilepath = () => process.env[ENV_CONFIG_PATH] || path53.join(getHomeDir.getHomeDir(), ".aws", "config"); + var ENV_CREDENTIALS_PATH = "AWS_SHARED_CREDENTIALS_FILE"; + var getCredentialsFilepath = () => process.env[ENV_CREDENTIALS_PATH] || path53.join(getHomeDir.getHomeDir(), ".aws", "credentials"); + var prefixKeyRegex = /^([\w-]+)\s(["'])?([\w-@\+\.%:/]+)\2$/; + var profileNameBlockList = ["__proto__", "profile __proto__"]; + var parseIni = (iniData) => { + const map4 = {}; + let currentSection; + let currentSubSection; + for (const iniLine of iniData.split(/\r?\n/)) { + const trimmedLine = iniLine.split(/(^|\s)[;#]/)[0].trim(); + const isSection = trimmedLine[0] === "[" && trimmedLine[trimmedLine.length - 1] === "]"; + if (isSection) { + currentSection = void 0; + currentSubSection = void 0; + const sectionName = trimmedLine.substring(1, trimmedLine.length - 1); + const matches = prefixKeyRegex.exec(sectionName); + if (matches) { + const [, prefix, , name] = matches; + if (Object.values(types2.IniSectionType).includes(prefix)) { + currentSection = [prefix, name].join(CONFIG_PREFIX_SEPARATOR); + } + } else { + currentSection = sectionName; + } + if (profileNameBlockList.includes(sectionName)) { + throw new Error(`Found invalid profile name "${sectionName}"`); + } + } else if (currentSection) { + const indexOfEqualsSign = trimmedLine.indexOf("="); + if (![0, -1].includes(indexOfEqualsSign)) { + const [name, value] = [ + trimmedLine.substring(0, indexOfEqualsSign).trim(), + trimmedLine.substring(indexOfEqualsSign + 1).trim() + ]; + if (value === "") { + currentSubSection = name; + } else { + if (currentSubSection && iniLine.trimStart() === iniLine) { + currentSubSection = void 0; + } + map4[currentSection] = map4[currentSection] || {}; + const key = currentSubSection ? [currentSubSection, name].join(CONFIG_PREFIX_SEPARATOR) : name; + map4[currentSection][key] = value; + } + } + } + } + return map4; + }; + var swallowError$1 = () => ({}); + var loadSharedConfigFiles = async (init2 = {}) => { + const { filepath = getCredentialsFilepath(), configFilepath = getConfigFilepath() } = init2; + const homeDir = getHomeDir.getHomeDir(); + const relativeHomeDirPrefix = "~/"; + let resolvedFilepath = filepath; + if (filepath.startsWith(relativeHomeDirPrefix)) { + resolvedFilepath = path53.join(homeDir, filepath.slice(2)); + } + let resolvedConfigFilepath = configFilepath; + if (configFilepath.startsWith(relativeHomeDirPrefix)) { + resolvedConfigFilepath = path53.join(homeDir, configFilepath.slice(2)); + } + const parsedFiles = await Promise.all([ + readFile5.readFile(resolvedConfigFilepath, { + ignoreCache: init2.ignoreCache + }).then(parseIni).then(getConfigData).catch(swallowError$1), + readFile5.readFile(resolvedFilepath, { + ignoreCache: init2.ignoreCache + }).then(parseIni).catch(swallowError$1) + ]); + return { + configFile: parsedFiles[0], + credentialsFile: parsedFiles[1] + }; + }; + var getSsoSessionData = (data2) => Object.entries(data2).filter(([key]) => key.startsWith(types2.IniSectionType.SSO_SESSION + CONFIG_PREFIX_SEPARATOR)).reduce((acc, [key, value]) => ({ ...acc, [key.substring(key.indexOf(CONFIG_PREFIX_SEPARATOR) + 1)]: value }), {}); + var swallowError = () => ({}); + var loadSsoSessionData = async (init2 = {}) => readFile5.readFile(init2.configFilepath ?? getConfigFilepath()).then(parseIni).then(getSsoSessionData).catch(swallowError); + var mergeConfigFiles = (...files) => { + const merged = {}; + for (const file2 of files) { + for (const [key, values2] of Object.entries(file2)) { + if (merged[key] !== void 0) { + Object.assign(merged[key], values2); + } else { + merged[key] = values2; + } + } + } + return merged; + }; + var parseKnownFiles = async (init2) => { + const parsedFiles = await loadSharedConfigFiles(init2); + return mergeConfigFiles(parsedFiles.configFile, parsedFiles.credentialsFile); + }; + var externalDataInterceptor = { + getFileRecord() { + return readFile5.fileIntercept; + }, + interceptFile(path54, contents) { + readFile5.fileIntercept[path54] = Promise.resolve(contents); + }, + getTokenRecord() { + return getSSOTokenFromFile.tokenIntercept; + }, + interceptToken(id, contents) { + getSSOTokenFromFile.tokenIntercept[id] = contents; + } + }; + exports.getSSOTokenFromFile = getSSOTokenFromFile.getSSOTokenFromFile; + exports.readFile = readFile5.readFile; + exports.CONFIG_PREFIX_SEPARATOR = CONFIG_PREFIX_SEPARATOR; + exports.DEFAULT_PROFILE = DEFAULT_PROFILE; + exports.ENV_PROFILE = ENV_PROFILE; + exports.externalDataInterceptor = externalDataInterceptor; + exports.getProfileName = getProfileName; + exports.loadSharedConfigFiles = loadSharedConfigFiles; + exports.loadSsoSessionData = loadSsoSessionData; + exports.parseKnownFiles = parseKnownFiles; + Object.prototype.hasOwnProperty.call(getHomeDir, "__proto__") && !Object.prototype.hasOwnProperty.call(exports, "__proto__") && Object.defineProperty(exports, "__proto__", { + enumerable: true, + value: getHomeDir["__proto__"] + }); + Object.keys(getHomeDir).forEach(function(k5) { + if (k5 !== "default" && !Object.prototype.hasOwnProperty.call(exports, k5)) exports[k5] = getHomeDir[k5]; + }); + Object.prototype.hasOwnProperty.call(getSSOTokenFilepath, "__proto__") && !Object.prototype.hasOwnProperty.call(exports, "__proto__") && Object.defineProperty(exports, "__proto__", { + enumerable: true, + value: getSSOTokenFilepath["__proto__"] + }); + Object.keys(getSSOTokenFilepath).forEach(function(k5) { + if (k5 !== "default" && !Object.prototype.hasOwnProperty.call(exports, k5)) exports[k5] = getSSOTokenFilepath[k5]; + }); + } +}); + +// node_modules/.pnpm/@smithy+node-config-provider@4.3.13/node_modules/@smithy/node-config-provider/dist-cjs/index.js +var require_dist_cjs43 = __commonJS({ + "node_modules/.pnpm/@smithy+node-config-provider@4.3.13/node_modules/@smithy/node-config-provider/dist-cjs/index.js"(exports) { + "use strict"; + var propertyProvider = require_dist_cjs41(); + var sharedIniFileLoader = require_dist_cjs42(); + function getSelectorName(functionString) { + try { + const constants = new Set(Array.from(functionString.match(/([A-Z_]){3,}/g) ?? [])); + constants.delete("CONFIG"); + constants.delete("CONFIG_PREFIX_SEPARATOR"); + constants.delete("ENV"); + return [...constants].join(", "); + } catch (e5) { + return functionString; + } + } + var fromEnv = (envVarSelector, options) => async () => { + try { + const config3 = envVarSelector(process.env, options); + if (config3 === void 0) { + throw new Error(); + } + return config3; + } catch (e5) { + throw new propertyProvider.CredentialsProviderError(e5.message || `Not found in ENV: ${getSelectorName(envVarSelector.toString())}`, { logger: options?.logger }); + } + }; + var fromSharedConfigFiles = (configSelector, { preferredFile = "config", ...init2 } = {}) => async () => { + const profile = sharedIniFileLoader.getProfileName(init2); + const { configFile, credentialsFile } = await sharedIniFileLoader.loadSharedConfigFiles(init2); + const profileFromCredentials = credentialsFile[profile] || {}; + const profileFromConfig = configFile[profile] || {}; + const mergedProfile = preferredFile === "config" ? { ...profileFromCredentials, ...profileFromConfig } : { ...profileFromConfig, ...profileFromCredentials }; + try { + const cfgFile = preferredFile === "config" ? configFile : credentialsFile; + const configValue = configSelector(mergedProfile, cfgFile); + if (configValue === void 0) { + throw new Error(); + } + return configValue; + } catch (e5) { + throw new propertyProvider.CredentialsProviderError(e5.message || `Not found in config files w/ profile [${profile}]: ${getSelectorName(configSelector.toString())}`, { logger: init2.logger }); + } + }; + var isFunction3 = (func) => typeof func === "function"; + var fromStatic = (defaultValue) => isFunction3(defaultValue) ? async () => await defaultValue() : propertyProvider.fromStatic(defaultValue); + var loadConfig2 = ({ environmentVariableSelector, configFileSelector, default: defaultValue }, configuration = {}) => { + const { signingName, logger: logger4 } = configuration; + const envOptions = { signingName, logger: logger4 }; + return propertyProvider.memoize(propertyProvider.chain(fromEnv(environmentVariableSelector, envOptions), fromSharedConfigFiles(configFileSelector, configuration), fromStatic(defaultValue))); + }; + exports.loadConfig = loadConfig2; + } +}); + +// node_modules/.pnpm/@smithy+middleware-endpoint@4.4.29/node_modules/@smithy/middleware-endpoint/dist-cjs/adaptors/getEndpointUrlConfig.js +var require_getEndpointUrlConfig = __commonJS({ + "node_modules/.pnpm/@smithy+middleware-endpoint@4.4.29/node_modules/@smithy/middleware-endpoint/dist-cjs/adaptors/getEndpointUrlConfig.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getEndpointUrlConfig = void 0; + var shared_ini_file_loader_1 = require_dist_cjs42(); + var ENV_ENDPOINT_URL = "AWS_ENDPOINT_URL"; + var CONFIG_ENDPOINT_URL = "endpoint_url"; + var getEndpointUrlConfig = (serviceId) => ({ + environmentVariableSelector: (env2) => { + const serviceSuffixParts = serviceId.split(" ").map((w5) => w5.toUpperCase()); + const serviceEndpointUrl = env2[[ENV_ENDPOINT_URL, ...serviceSuffixParts].join("_")]; + if (serviceEndpointUrl) + return serviceEndpointUrl; + const endpointUrl = env2[ENV_ENDPOINT_URL]; + if (endpointUrl) + return endpointUrl; + return void 0; + }, + configFileSelector: (profile, config3) => { + if (config3 && profile.services) { + const servicesSection = config3[["services", profile.services].join(shared_ini_file_loader_1.CONFIG_PREFIX_SEPARATOR)]; + if (servicesSection) { + const servicePrefixParts = serviceId.split(" ").map((w5) => w5.toLowerCase()); + const endpointUrl2 = servicesSection[[servicePrefixParts.join("_"), CONFIG_ENDPOINT_URL].join(shared_ini_file_loader_1.CONFIG_PREFIX_SEPARATOR)]; + if (endpointUrl2) + return endpointUrl2; + } + } + const endpointUrl = profile[CONFIG_ENDPOINT_URL]; + if (endpointUrl) + return endpointUrl; + return void 0; + }, + default: void 0 + }); + exports.getEndpointUrlConfig = getEndpointUrlConfig; + } +}); + +// node_modules/.pnpm/@smithy+middleware-endpoint@4.4.29/node_modules/@smithy/middleware-endpoint/dist-cjs/adaptors/getEndpointFromConfig.js +var require_getEndpointFromConfig = __commonJS({ + "node_modules/.pnpm/@smithy+middleware-endpoint@4.4.29/node_modules/@smithy/middleware-endpoint/dist-cjs/adaptors/getEndpointFromConfig.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getEndpointFromConfig = void 0; + var node_config_provider_1 = require_dist_cjs43(); + var getEndpointUrlConfig_1 = require_getEndpointUrlConfig(); + var getEndpointFromConfig = async (serviceId) => (0, node_config_provider_1.loadConfig)((0, getEndpointUrlConfig_1.getEndpointUrlConfig)(serviceId ?? ""))(); + exports.getEndpointFromConfig = getEndpointFromConfig; + } +}); + +// node_modules/.pnpm/@smithy+middleware-serde@4.2.17/node_modules/@smithy/middleware-serde/dist-cjs/index.js +var require_dist_cjs44 = __commonJS({ + "node_modules/.pnpm/@smithy+middleware-serde@4.2.17/node_modules/@smithy/middleware-serde/dist-cjs/index.js"(exports) { + "use strict"; + var protocolHttp = require_dist_cjs2(); + var endpoints = (init_endpoints(), __toCommonJS(endpoints_exports)); + var deserializerMiddleware = (options, deserializer) => (next, context) => async (args) => { + const { response } = await next(args); + try { + const parsed = await deserializer(response, options); + return { + response, + output: parsed + }; + } catch (error50) { + Object.defineProperty(error50, "$response", { + value: response, + enumerable: false, + writable: false, + configurable: false + }); + if (!("$metadata" in error50)) { + const hint = `Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`; + try { + error50.message += "\n " + hint; + } catch (e5) { + if (!context.logger || context.logger?.constructor?.name === "NoOpLogger") { + console.warn(hint); + } else { + context.logger?.warn?.(hint); + } + } + if (typeof error50.$responseBodyText !== "undefined") { + if (error50.$response) { + error50.$response.body = error50.$responseBodyText; + } + } + try { + if (protocolHttp.HttpResponse.isInstance(response)) { + const { headers = {} } = response; + const headerEntries = Object.entries(headers); + error50.$metadata = { + httpStatusCode: response.statusCode, + requestId: findHeader2(/^x-[\w-]+-request-?id$/, headerEntries), + extendedRequestId: findHeader2(/^x-[\w-]+-id-2$/, headerEntries), + cfId: findHeader2(/^x-[\w-]+-cf-id$/, headerEntries) + }; + } + } catch (e5) { + } + } + throw error50; + } + }; + var findHeader2 = (pattern, headers) => { + return (headers.find(([k5]) => { + return k5.match(pattern); + }) || [void 0, void 0])[1]; + }; + var serializerMiddleware = (options, serializer) => (next, context) => async (args) => { + const endpointConfig = options; + const endpoint = context.endpointV2 ? async () => endpoints.toEndpointV1(context.endpointV2) : endpointConfig.endpoint; + if (!endpoint) { + throw new Error("No valid endpoint provider available."); + } + const request = await serializer(args.input, { ...options, endpoint }); + return next({ + ...args, + request + }); + }; + var deserializerMiddlewareOption2 = { + name: "deserializerMiddleware", + step: "deserialize", + tags: ["DESERIALIZER"], + override: true + }; + var serializerMiddlewareOption2 = { + name: "serializerMiddleware", + step: "serialize", + tags: ["SERIALIZER"], + override: true + }; + function getSerdePlugin(config3, serializer, deserializer) { + return { + applyToStack: (commandStack) => { + commandStack.add(deserializerMiddleware(config3, deserializer), deserializerMiddlewareOption2); + commandStack.add(serializerMiddleware(config3, serializer), serializerMiddlewareOption2); + } + }; + } + exports.deserializerMiddleware = deserializerMiddleware; + exports.deserializerMiddlewareOption = deserializerMiddlewareOption2; + exports.getSerdePlugin = getSerdePlugin; + exports.serializerMiddleware = serializerMiddleware; + exports.serializerMiddlewareOption = serializerMiddlewareOption2; + } +}); + +// node_modules/.pnpm/@smithy+middleware-endpoint@4.4.29/node_modules/@smithy/middleware-endpoint/dist-cjs/index.js +var require_dist_cjs45 = __commonJS({ + "node_modules/.pnpm/@smithy+middleware-endpoint@4.4.29/node_modules/@smithy/middleware-endpoint/dist-cjs/index.js"(exports) { + "use strict"; + var core = (init_dist_es(), __toCommonJS(dist_es_exports)); + var utilMiddleware = require_dist_cjs18(); + var getEndpointFromConfig = require_getEndpointFromConfig(); + var urlParser = require_dist_cjs25(); + var middlewareSerde = require_dist_cjs44(); + var resolveParamsForS3 = async (endpointParams) => { + const bucket = endpointParams?.Bucket || ""; + if (typeof endpointParams.Bucket === "string") { + endpointParams.Bucket = bucket.replace(/#/g, encodeURIComponent("#")).replace(/\?/g, encodeURIComponent("?")); + } + if (isArnBucketName(bucket)) { + if (endpointParams.ForcePathStyle === true) { + throw new Error("Path-style addressing cannot be used with ARN buckets"); + } + } else if (!isDnsCompatibleBucketName(bucket) || bucket.indexOf(".") !== -1 && !String(endpointParams.Endpoint).startsWith("http:") || bucket.toLowerCase() !== bucket || bucket.length < 3) { + endpointParams.ForcePathStyle = true; + } + if (endpointParams.DisableMultiRegionAccessPoints) { + endpointParams.disableMultiRegionAccessPoints = true; + endpointParams.DisableMRAP = true; + } + return endpointParams; + }; + var DOMAIN_PATTERN = /^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$/; + var IP_ADDRESS_PATTERN = /(\d+\.){3}\d+/; + var DOTS_PATTERN = /\.\./; + var isDnsCompatibleBucketName = (bucketName) => DOMAIN_PATTERN.test(bucketName) && !IP_ADDRESS_PATTERN.test(bucketName) && !DOTS_PATTERN.test(bucketName); + var isArnBucketName = (bucketName) => { + const [arn, partition, service, , , bucket] = bucketName.split(":"); + const isArn = arn === "arn" && bucketName.split(":").length >= 6; + const isValidArn = Boolean(isArn && partition && service && bucket); + if (isArn && !isValidArn) { + throw new Error(`Invalid ARN: ${bucketName} was an invalid ARN.`); + } + return isValidArn; + }; + var createConfigValueProvider = (configKey, canonicalEndpointParamKey, config3, isClientContextParam = false) => { + const configProvider = async () => { + let configValue; + if (isClientContextParam) { + const clientContextParams = config3.clientContextParams; + const nestedValue = clientContextParams?.[configKey]; + configValue = nestedValue ?? config3[configKey] ?? config3[canonicalEndpointParamKey]; + } else { + configValue = config3[configKey] ?? config3[canonicalEndpointParamKey]; + } + if (typeof configValue === "function") { + return configValue(); + } + return configValue; + }; + if (configKey === "credentialScope" || canonicalEndpointParamKey === "CredentialScope") { + return async () => { + const credentials = typeof config3.credentials === "function" ? await config3.credentials() : config3.credentials; + const configValue = credentials?.credentialScope ?? credentials?.CredentialScope; + return configValue; + }; + } + if (configKey === "accountId" || canonicalEndpointParamKey === "AccountId") { + return async () => { + const credentials = typeof config3.credentials === "function" ? await config3.credentials() : config3.credentials; + const configValue = credentials?.accountId ?? credentials?.AccountId; + return configValue; + }; + } + if (configKey === "endpoint" || canonicalEndpointParamKey === "endpoint") { + return async () => { + if (config3.isCustomEndpoint === false) { + return void 0; + } + const endpoint = await configProvider(); + if (endpoint && typeof endpoint === "object") { + if ("url" in endpoint) { + return endpoint.url.href; + } + if ("hostname" in endpoint) { + const { protocol, hostname: hostname3, port, path: path53 } = endpoint; + return `${protocol}//${hostname3}${port ? ":" + port : ""}${path53}`; + } + } + return endpoint; + }; + } + return configProvider; + }; + var toEndpointV12 = (endpoint) => { + if (typeof endpoint === "object") { + if ("url" in endpoint) { + const v1Endpoint = urlParser.parseUrl(endpoint.url); + if (endpoint.headers) { + v1Endpoint.headers = {}; + for (const [name, values2] of Object.entries(endpoint.headers)) { + v1Endpoint.headers[name.toLowerCase()] = values2.join(", "); + } + } + return v1Endpoint; + } + return endpoint; + } + return urlParser.parseUrl(endpoint); + }; + var getEndpointFromInstructions = async (commandInput, instructionsSupplier, clientConfig, context) => { + if (!clientConfig.isCustomEndpoint) { + let endpointFromConfig; + if (clientConfig.serviceConfiguredEndpoint) { + endpointFromConfig = await clientConfig.serviceConfiguredEndpoint(); + } else { + endpointFromConfig = await getEndpointFromConfig.getEndpointFromConfig(clientConfig.serviceId); + } + if (endpointFromConfig) { + clientConfig.endpoint = () => Promise.resolve(toEndpointV12(endpointFromConfig)); + clientConfig.isCustomEndpoint = true; + } + } + const endpointParams = await resolveParams(commandInput, instructionsSupplier, clientConfig); + if (typeof clientConfig.endpointProvider !== "function") { + throw new Error("config.endpointProvider is not set."); + } + const endpoint = clientConfig.endpointProvider(endpointParams, context); + if (clientConfig.isCustomEndpoint && clientConfig.endpoint) { + const customEndpoint = await clientConfig.endpoint(); + if (customEndpoint?.headers) { + endpoint.headers ??= {}; + for (const [name, value] of Object.entries(customEndpoint.headers)) { + endpoint.headers[name] = Array.isArray(value) ? value : [value]; + } + } + } + return endpoint; + }; + var resolveParams = async (commandInput, instructionsSupplier, clientConfig) => { + const endpointParams = {}; + const instructions = instructionsSupplier?.getEndpointParameterInstructions?.() || {}; + for (const [name, instruction] of Object.entries(instructions)) { + switch (instruction.type) { + case "staticContextParams": + endpointParams[name] = instruction.value; + break; + case "contextParams": + endpointParams[name] = commandInput[instruction.name]; + break; + case "clientContextParams": + case "builtInParams": + endpointParams[name] = await createConfigValueProvider(instruction.name, name, clientConfig, instruction.type !== "builtInParams")(); + break; + case "operationContextParams": + endpointParams[name] = instruction.get(commandInput); + break; + default: + throw new Error("Unrecognized endpoint parameter instruction: " + JSON.stringify(instruction)); + } + } + if (Object.keys(instructions).length === 0) { + Object.assign(endpointParams, clientConfig); + } + if (String(clientConfig.serviceId).toLowerCase() === "s3") { + await resolveParamsForS3(endpointParams); + } + return endpointParams; + }; + var endpointMiddleware = ({ config: config3, instructions }) => { + return (next, context) => async (args) => { + if (config3.isCustomEndpoint) { + core.setFeature(context, "ENDPOINT_OVERRIDE", "N"); + } + const endpoint = await getEndpointFromInstructions(args.input, { + getEndpointParameterInstructions() { + return instructions; + } + }, { ...config3 }, context); + context.endpointV2 = endpoint; + context.authSchemes = endpoint.properties?.authSchemes; + const authScheme = context.authSchemes?.[0]; + if (authScheme) { + context["signing_region"] = authScheme.signingRegion; + context["signing_service"] = authScheme.signingName; + const smithyContext = utilMiddleware.getSmithyContext(context); + const httpAuthOption = smithyContext?.selectedHttpAuthScheme?.httpAuthOption; + if (httpAuthOption) { + httpAuthOption.signingProperties = Object.assign(httpAuthOption.signingProperties || {}, { + signing_region: authScheme.signingRegion, + signingRegion: authScheme.signingRegion, + signing_service: authScheme.signingName, + signingName: authScheme.signingName, + signingRegionSet: authScheme.signingRegionSet + }, authScheme.properties); + } + } + return next({ + ...args + }); + }; + }; + var endpointMiddlewareOptions = { + step: "serialize", + tags: ["ENDPOINT_PARAMETERS", "ENDPOINT_V2", "ENDPOINT"], + name: "endpointV2Middleware", + override: true, + relation: "before", + toMiddleware: middlewareSerde.serializerMiddlewareOption.name + }; + var getEndpointPlugin6 = (config3, instructions) => ({ + applyToStack: (clientStack) => { + clientStack.addRelativeTo(endpointMiddleware({ + config: config3, + instructions + }), endpointMiddlewareOptions); + } + }); + var resolveEndpointConfig5 = (input) => { + const tls2 = input.tls ?? true; + const { endpoint, useDualstackEndpoint, useFipsEndpoint } = input; + const customEndpointProvider = endpoint != null ? async () => toEndpointV12(await utilMiddleware.normalizeProvider(endpoint)()) : void 0; + const isCustomEndpoint = !!endpoint; + const resolvedConfig = Object.assign(input, { + endpoint: customEndpointProvider, + tls: tls2, + isCustomEndpoint, + useDualstackEndpoint: utilMiddleware.normalizeProvider(useDualstackEndpoint ?? false), + useFipsEndpoint: utilMiddleware.normalizeProvider(useFipsEndpoint ?? false) + }); + let configuredEndpointPromise = void 0; + resolvedConfig.serviceConfiguredEndpoint = async () => { + if (input.serviceId && !configuredEndpointPromise) { + configuredEndpointPromise = getEndpointFromConfig.getEndpointFromConfig(input.serviceId); + } + return configuredEndpointPromise; + }; + return resolvedConfig; + }; + var resolveEndpointRequiredConfig = (input) => { + const { endpoint } = input; + if (endpoint === void 0) { + input.endpoint = async () => { + throw new Error("@smithy/middleware-endpoint: (default endpointRuleSet) endpoint is not set - you must configure an endpoint."); + }; + } + return input; + }; + exports.endpointMiddleware = endpointMiddleware; + exports.endpointMiddlewareOptions = endpointMiddlewareOptions; + exports.getEndpointFromInstructions = getEndpointFromInstructions; + exports.getEndpointPlugin = getEndpointPlugin6; + exports.resolveEndpointConfig = resolveEndpointConfig5; + exports.resolveEndpointRequiredConfig = resolveEndpointRequiredConfig; + exports.resolveParams = resolveParams; + exports.toEndpointV1 = toEndpointV12; + } +}); + +// node_modules/.pnpm/@smithy+middleware-retry@4.5.1/node_modules/@smithy/middleware-retry/dist-cjs/isStreamingPayload/isStreamingPayload.js +var require_isStreamingPayload = __commonJS({ + "node_modules/.pnpm/@smithy+middleware-retry@4.5.1/node_modules/@smithy/middleware-retry/dist-cjs/isStreamingPayload/isStreamingPayload.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.isStreamingPayload = void 0; + var stream_1 = __require("stream"); + var isStreamingPayload = (request) => request?.body instanceof stream_1.Readable || typeof ReadableStream !== "undefined" && request?.body instanceof ReadableStream; + exports.isStreamingPayload = isStreamingPayload; + } +}); + +// node_modules/.pnpm/@smithy+middleware-retry@4.5.1/node_modules/@smithy/middleware-retry/dist-cjs/index.js +var require_dist_cjs46 = __commonJS({ + "node_modules/.pnpm/@smithy+middleware-retry@4.5.1/node_modules/@smithy/middleware-retry/dist-cjs/index.js"(exports) { + "use strict"; + var utilRetry = require_dist_cjs36(); + var protocolHttp = require_dist_cjs2(); + var serviceErrorClassification = require_dist_cjs35(); + var uuid5 = require_dist_cjs26(); + var utilMiddleware = require_dist_cjs18(); + var smithyClient = require_dist_cjs27(); + var isStreamingPayload = require_isStreamingPayload(); + var serde = (init_serde(), __toCommonJS(serde_exports)); + var asSdkError = (error50) => { + if (error50 instanceof Error) + return error50; + if (error50 instanceof Object) + return Object.assign(new Error(), error50); + if (typeof error50 === "string") + return new Error(error50); + return new Error(`AWS SDK error wrapper for ${error50}`); + }; + var getDefaultRetryQuota = (initialRetryTokens, options) => { + const MAX_CAPACITY = initialRetryTokens; + const noRetryIncrement = utilRetry.NO_RETRY_INCREMENT; + const retryCost = utilRetry.RETRY_COST; + const timeoutRetryCost = utilRetry.TIMEOUT_RETRY_COST; + let availableCapacity = initialRetryTokens; + const getCapacityAmount = (error50) => error50.name === "TimeoutError" ? timeoutRetryCost : retryCost; + const hasRetryTokens = (error50) => getCapacityAmount(error50) <= availableCapacity; + const retrieveRetryTokens = (error50) => { + if (!hasRetryTokens(error50)) { + throw new Error("No retry token available"); + } + const capacityAmount = getCapacityAmount(error50); + availableCapacity -= capacityAmount; + return capacityAmount; + }; + const releaseRetryTokens = (capacityReleaseAmount) => { + availableCapacity += capacityReleaseAmount ?? noRetryIncrement; + availableCapacity = Math.min(availableCapacity, MAX_CAPACITY); + }; + return Object.freeze({ + hasRetryTokens, + retrieveRetryTokens, + releaseRetryTokens + }); + }; + var defaultDelayDecider = (delayBase, attempts) => Math.floor(Math.min(utilRetry.MAXIMUM_RETRY_DELAY, Math.random() * 2 ** attempts * delayBase)); + var defaultRetryDecider = (error50) => { + if (!error50) { + return false; + } + return serviceErrorClassification.isRetryableByTrait(error50) || serviceErrorClassification.isClockSkewError(error50) || serviceErrorClassification.isThrottlingError(error50) || serviceErrorClassification.isTransientError(error50); + }; + var StandardRetryStrategy = class { + maxAttemptsProvider; + retryDecider; + delayDecider; + retryQuota; + mode = utilRetry.RETRY_MODES.STANDARD; + constructor(maxAttemptsProvider, options) { + this.maxAttemptsProvider = maxAttemptsProvider; + this.retryDecider = options?.retryDecider ?? defaultRetryDecider; + this.delayDecider = options?.delayDecider ?? defaultDelayDecider; + this.retryQuota = options?.retryQuota ?? getDefaultRetryQuota(utilRetry.INITIAL_RETRY_TOKENS); + } + shouldRetry(error50, attempts, maxAttempts) { + return attempts < maxAttempts && this.retryDecider(error50) && this.retryQuota.hasRetryTokens(error50); + } + async getMaxAttempts() { + let maxAttempts; + try { + maxAttempts = await this.maxAttemptsProvider(); + } catch (error50) { + maxAttempts = utilRetry.DEFAULT_MAX_ATTEMPTS; + } + return maxAttempts; + } + async retry(next, args, options) { + let retryTokenAmount; + let attempts = 0; + let totalDelay = 0; + const maxAttempts = await this.getMaxAttempts(); + const { request } = args; + if (protocolHttp.HttpRequest.isInstance(request)) { + request.headers[utilRetry.INVOCATION_ID_HEADER] = uuid5.v4(); + } + while (true) { + try { + if (protocolHttp.HttpRequest.isInstance(request)) { + request.headers[utilRetry.REQUEST_HEADER] = `attempt=${attempts + 1}; max=${maxAttempts}`; + } + if (options?.beforeRequest) { + await options.beforeRequest(); + } + const { response, output } = await next(args); + if (options?.afterRequest) { + options.afterRequest(response); + } + this.retryQuota.releaseRetryTokens(retryTokenAmount); + output.$metadata.attempts = attempts + 1; + output.$metadata.totalRetryDelay = totalDelay; + return { response, output }; + } catch (e5) { + const err = asSdkError(e5); + attempts++; + if (this.shouldRetry(err, attempts, maxAttempts)) { + retryTokenAmount = this.retryQuota.retrieveRetryTokens(err); + const delayFromDecider = this.delayDecider(serviceErrorClassification.isThrottlingError(err) ? utilRetry.THROTTLING_RETRY_DELAY_BASE : utilRetry.DEFAULT_RETRY_DELAY_BASE, attempts); + const delayFromResponse = getDelayFromRetryAfterHeader(err.$response); + const delay3 = Math.max(delayFromResponse || 0, delayFromDecider); + totalDelay += delay3; + await new Promise((resolve4) => setTimeout(resolve4, delay3)); + continue; + } + if (!err.$metadata) { + err.$metadata = {}; + } + err.$metadata.attempts = attempts; + err.$metadata.totalRetryDelay = totalDelay; + throw err; + } + } + } + }; + var getDelayFromRetryAfterHeader = (response) => { + if (!protocolHttp.HttpResponse.isInstance(response)) + return; + const retryAfterHeaderName = Object.keys(response.headers).find((key) => key.toLowerCase() === "retry-after"); + if (!retryAfterHeaderName) + return; + const retryAfter = response.headers[retryAfterHeaderName]; + const retryAfterSeconds = Number(retryAfter); + if (!Number.isNaN(retryAfterSeconds)) + return retryAfterSeconds * 1e3; + const retryAfterDate = new Date(retryAfter); + return retryAfterDate.getTime() - Date.now(); + }; + var AdaptiveRetryStrategy = class extends StandardRetryStrategy { + rateLimiter; + constructor(maxAttemptsProvider, options) { + const { rateLimiter, ...superOptions } = options ?? {}; + super(maxAttemptsProvider, superOptions); + this.rateLimiter = rateLimiter ?? new utilRetry.DefaultRateLimiter(); + this.mode = utilRetry.RETRY_MODES.ADAPTIVE; + } + async retry(next, args) { + return super.retry(next, args, { + beforeRequest: async () => { + return this.rateLimiter.getSendToken(); + }, + afterRequest: (response) => { + this.rateLimiter.updateClientSendingRate(response); + } + }); + } + }; + var ENV_MAX_ATTEMPTS = "AWS_MAX_ATTEMPTS"; + var CONFIG_MAX_ATTEMPTS = "max_attempts"; + var NODE_MAX_ATTEMPT_CONFIG_OPTIONS5 = { + environmentVariableSelector: (env2) => { + const value = env2[ENV_MAX_ATTEMPTS]; + if (!value) + return void 0; + const maxAttempt = parseInt(value); + if (Number.isNaN(maxAttempt)) { + throw new Error(`Environment variable ${ENV_MAX_ATTEMPTS} mast be a number, got "${value}"`); + } + return maxAttempt; + }, + configFileSelector: (profile) => { + const value = profile[CONFIG_MAX_ATTEMPTS]; + if (!value) + return void 0; + const maxAttempt = parseInt(value); + if (Number.isNaN(maxAttempt)) { + throw new Error(`Shared config file entry ${CONFIG_MAX_ATTEMPTS} mast be a number, got "${value}"`); + } + return maxAttempt; + }, + default: utilRetry.DEFAULT_MAX_ATTEMPTS + }; + var resolveRetryConfig5 = (input) => { + const { retryStrategy, retryMode } = input; + const maxAttempts = utilMiddleware.normalizeProvider(input.maxAttempts ?? utilRetry.DEFAULT_MAX_ATTEMPTS); + let controller = retryStrategy ? Promise.resolve(retryStrategy) : void 0; + const getDefault = async () => await utilMiddleware.normalizeProvider(retryMode)() === utilRetry.RETRY_MODES.ADAPTIVE ? new utilRetry.AdaptiveRetryStrategy(maxAttempts) : new utilRetry.StandardRetryStrategy(maxAttempts); + return Object.assign(input, { + maxAttempts, + retryStrategy: () => controller ??= getDefault() + }); + }; + var ENV_RETRY_MODE = "AWS_RETRY_MODE"; + var CONFIG_RETRY_MODE = "retry_mode"; + var NODE_RETRY_MODE_CONFIG_OPTIONS5 = { + environmentVariableSelector: (env2) => env2[ENV_RETRY_MODE], + configFileSelector: (profile) => profile[CONFIG_RETRY_MODE], + default: utilRetry.DEFAULT_RETRY_MODE + }; + var omitRetryHeadersMiddleware = () => (next) => async (args) => { + const { request } = args; + if (protocolHttp.HttpRequest.isInstance(request)) { + delete request.headers[utilRetry.INVOCATION_ID_HEADER]; + delete request.headers[utilRetry.REQUEST_HEADER]; + } + return next(args); + }; + var omitRetryHeadersMiddlewareOptions = { + name: "omitRetryHeadersMiddleware", + tags: ["RETRY", "HEADERS", "OMIT_RETRY_HEADERS"], + relation: "before", + toMiddleware: "awsAuthMiddleware", + override: true + }; + var getOmitRetryHeadersPlugin = (options) => ({ + applyToStack: (clientStack) => { + clientStack.addRelativeTo(omitRetryHeadersMiddleware(), omitRetryHeadersMiddlewareOptions); + } + }); + function parseRetryAfterHeader(response, logger4) { + if (!protocolHttp.HttpResponse.isInstance(response)) { + return; + } + for (const header of Object.keys(response.headers)) { + const h5 = header.toLowerCase(); + if (h5 === "retry-after") { + const retryAfter = response.headers[header]; + let retryAfterSeconds = NaN; + if (retryAfter.endsWith("GMT")) { + try { + const date7 = serde.parseRfc7231DateTime(retryAfter); + retryAfterSeconds = (date7.getTime() - Date.now()) / 1e3; + } catch (e5) { + logger4?.trace?.("Failed to parse retry-after header"); + logger4?.trace?.(e5); + } + } else if (retryAfter.match(/ GMT, ((\d+)|(\d+\.\d+))$/)) { + retryAfterSeconds = Number(retryAfter.match(/ GMT, ([\d.]+)$/)?.[1]); + } else if (retryAfter.match(/^((\d+)|(\d+\.\d+))$/)) { + retryAfterSeconds = Number(retryAfter); + } else if (Date.parse(retryAfter) >= Date.now()) { + retryAfterSeconds = (Date.parse(retryAfter) - Date.now()) / 1e3; + } + if (isNaN(retryAfterSeconds)) { + return; + } + return new Date(Date.now() + retryAfterSeconds * 1e3); + } else if (h5 === "x-amz-retry-after") { + const v5 = response.headers[header]; + const backoffMilliseconds = Number(v5); + if (isNaN(backoffMilliseconds)) { + logger4?.trace?.(`Failed to parse x-amz-retry-after=${v5}`); + return; + } + return new Date(Date.now() + backoffMilliseconds); + } + } + } + function getRetryAfterHint(response, logger4) { + return parseRetryAfterHeader(response, logger4); + } + var retryMiddleware = (options) => (next, context) => async (args) => { + let retryStrategy = await options.retryStrategy(); + const maxAttempts = await options.maxAttempts(); + if (isRetryStrategyV2(retryStrategy)) { + retryStrategy = retryStrategy; + let retryToken = await retryStrategy.acquireInitialRetryToken((context["partition_id"] ?? "") + (context.__retryLongPoll ? ":longpoll" : "")); + let lastError = new Error(); + let attempts = 0; + let totalRetryDelay = 0; + const { request } = args; + const isRequest2 = protocolHttp.HttpRequest.isInstance(request); + if (isRequest2) { + request.headers[utilRetry.INVOCATION_ID_HEADER] = uuid5.v4(); + } + while (true) { + try { + if (isRequest2) { + request.headers[utilRetry.REQUEST_HEADER] = `attempt=${attempts + 1}; max=${maxAttempts}`; + } + const { response, output } = await next(args); + retryStrategy.recordSuccess(retryToken); + output.$metadata.attempts = attempts + 1; + output.$metadata.totalRetryDelay = totalRetryDelay; + return { response, output }; + } catch (e5) { + const retryErrorInfo = getRetryErrorInfo(e5, options.logger); + lastError = asSdkError(e5); + if (isRequest2 && isStreamingPayload.isStreamingPayload(request)) { + (context.logger instanceof smithyClient.NoOpLogger ? console : context.logger)?.warn("An error was encountered in a non-retryable streaming request."); + throw lastError; + } + try { + retryToken = await retryStrategy.refreshRetryTokenForRetry(retryToken, retryErrorInfo); + } catch (refreshError) { + if (typeof refreshError.$backoff === "number") { + await cooldown(refreshError.$backoff); + } + if (!lastError.$metadata) { + lastError.$metadata = {}; + } + lastError.$metadata.attempts = attempts + 1; + lastError.$metadata.totalRetryDelay = totalRetryDelay; + throw lastError; + } + attempts = retryToken.getRetryCount(); + const delay3 = retryToken.getRetryDelay(); + totalRetryDelay += delay3; + await cooldown(delay3); + } + } + } else { + retryStrategy = retryStrategy; + if (retryStrategy?.mode) { + context.userAgent = [...context.userAgent || [], ["cfg/retry-mode", retryStrategy.mode]]; + } + return retryStrategy.retry(next, args); + } + }; + var cooldown = (ms) => new Promise((resolve4) => setTimeout(resolve4, ms)); + var isRetryStrategyV2 = (retryStrategy) => typeof retryStrategy.acquireInitialRetryToken !== "undefined" && typeof retryStrategy.refreshRetryTokenForRetry !== "undefined" && typeof retryStrategy.recordSuccess !== "undefined"; + var getRetryErrorInfo = (error50, logger4) => { + const errorInfo = { + error: error50, + errorType: getRetryErrorType(error50) + }; + const retryAfterHint = parseRetryAfterHeader(error50.$response, logger4); + if (retryAfterHint) { + errorInfo.retryAfterHint = retryAfterHint; + } + return errorInfo; + }; + var getRetryErrorType = (error50) => { + if (serviceErrorClassification.isThrottlingError(error50)) + return "THROTTLING"; + if (serviceErrorClassification.isTransientError(error50)) + return "TRANSIENT"; + if (serviceErrorClassification.isServerError(error50)) + return "SERVER_ERROR"; + return "CLIENT_ERROR"; + }; + var retryMiddlewareOptions = { + name: "retryMiddleware", + tags: ["RETRY"], + step: "finalizeRequest", + priority: "high", + override: true + }; + var getRetryPlugin5 = (options) => ({ + applyToStack: (clientStack) => { + clientStack.add(retryMiddleware(options), retryMiddlewareOptions); + } + }); + exports.AdaptiveRetryStrategy = AdaptiveRetryStrategy; + exports.CONFIG_MAX_ATTEMPTS = CONFIG_MAX_ATTEMPTS; + exports.CONFIG_RETRY_MODE = CONFIG_RETRY_MODE; + exports.ENV_MAX_ATTEMPTS = ENV_MAX_ATTEMPTS; + exports.ENV_RETRY_MODE = ENV_RETRY_MODE; + exports.NODE_MAX_ATTEMPT_CONFIG_OPTIONS = NODE_MAX_ATTEMPT_CONFIG_OPTIONS5; + exports.NODE_RETRY_MODE_CONFIG_OPTIONS = NODE_RETRY_MODE_CONFIG_OPTIONS5; + exports.StandardRetryStrategy = StandardRetryStrategy; + exports.defaultDelayDecider = defaultDelayDecider; + exports.defaultRetryDecider = defaultRetryDecider; + exports.getOmitRetryHeadersPlugin = getOmitRetryHeadersPlugin; + exports.getRetryAfterHint = getRetryAfterHint; + exports.getRetryPlugin = getRetryPlugin5; + exports.omitRetryHeadersMiddleware = omitRetryHeadersMiddleware; + exports.omitRetryHeadersMiddlewareOptions = omitRetryHeadersMiddlewareOptions; + exports.resolveRetryConfig = resolveRetryConfig5; + exports.retryMiddleware = retryMiddleware; + exports.retryMiddlewareOptions = retryMiddlewareOptions; + } +}); + +// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getDateHeader.js +var import_protocol_http9, getDateHeader; +var init_getDateHeader = __esm({ + "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getDateHeader.js"() { + import_protocol_http9 = __toESM(require_dist_cjs2()); + getDateHeader = (response) => import_protocol_http9.HttpResponse.isInstance(response) ? response.headers?.date ?? response.headers?.Date : void 0; + } +}); + +// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getSkewCorrectedDate.js +var getSkewCorrectedDate; +var init_getSkewCorrectedDate = __esm({ + "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getSkewCorrectedDate.js"() { + getSkewCorrectedDate = (systemClockOffset) => new Date(Date.now() + systemClockOffset); + } +}); + +// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/isClockSkewed.js +var isClockSkewed; +var init_isClockSkewed = __esm({ + "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/isClockSkewed.js"() { + init_getSkewCorrectedDate(); + isClockSkewed = (clockTime, systemClockOffset) => Math.abs(getSkewCorrectedDate(systemClockOffset).getTime() - clockTime) >= 3e5; + } +}); + +// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getUpdatedSystemClockOffset.js +var getUpdatedSystemClockOffset; +var init_getUpdatedSystemClockOffset = __esm({ + "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getUpdatedSystemClockOffset.js"() { + init_isClockSkewed(); + getUpdatedSystemClockOffset = (clockTime, currentSystemClockOffset) => { + const clockTimeInMs = Date.parse(clockTime); + if (isClockSkewed(clockTimeInMs, currentSystemClockOffset)) { + return clockTimeInMs - Date.now(); + } + return currentSystemClockOffset; + }; + } +}); + +// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/index.js +var init_utils5 = __esm({ + "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/index.js"() { + init_getDateHeader(); + init_getSkewCorrectedDate(); + init_getUpdatedSystemClockOffset(); + } +}); + +// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/AwsSdkSigV4Signer.js +var import_protocol_http10, throwSigningPropertyError, validateSigningProperties, AwsSdkSigV4Signer, AWSSDKSigV4Signer; +var init_AwsSdkSigV4Signer = __esm({ + "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/AwsSdkSigV4Signer.js"() { + import_protocol_http10 = __toESM(require_dist_cjs2()); + init_utils5(); + throwSigningPropertyError = (name, property) => { + if (!property) { + throw new Error(`Property \`${name}\` is not resolved for AWS SDK SigV4Auth`); + } + return property; + }; + validateSigningProperties = async (signingProperties) => { + const context = throwSigningPropertyError("context", signingProperties.context); + const config3 = throwSigningPropertyError("config", signingProperties.config); + const authScheme = context.endpointV2?.properties?.authSchemes?.[0]; + const signerFunction = throwSigningPropertyError("signer", config3.signer); + const signer = await signerFunction(authScheme); + const signingRegion = signingProperties?.signingRegion; + const signingRegionSet = signingProperties?.signingRegionSet; + const signingName = signingProperties?.signingName; + return { + config: config3, + signer, + signingRegion, + signingRegionSet, + signingName + }; + }; + AwsSdkSigV4Signer = class { + async sign(httpRequest2, identity, signingProperties) { + if (!import_protocol_http10.HttpRequest.isInstance(httpRequest2)) { + throw new Error("The request is not an instance of `HttpRequest` and cannot be signed"); + } + const validatedProps = await validateSigningProperties(signingProperties); + const { config: config3, signer } = validatedProps; + let { signingRegion, signingName } = validatedProps; + const handlerExecutionContext = signingProperties.context; + if (handlerExecutionContext?.authSchemes?.length ?? 0 > 1) { + const [first, second] = handlerExecutionContext.authSchemes; + if (first?.name === "sigv4a" && second?.name === "sigv4") { + signingRegion = second?.signingRegion ?? signingRegion; + signingName = second?.signingName ?? signingName; + } + } + const signedRequest = await signer.sign(httpRequest2, { + signingDate: getSkewCorrectedDate(config3.systemClockOffset), + signingRegion, + signingService: signingName + }); + return signedRequest; + } + errorHandler(signingProperties) { + return (error50) => { + const serverTime = error50.ServerTime ?? getDateHeader(error50.$response); + if (serverTime) { + const config3 = throwSigningPropertyError("config", signingProperties.config); + const initialSystemClockOffset = config3.systemClockOffset; + config3.systemClockOffset = getUpdatedSystemClockOffset(serverTime, config3.systemClockOffset); + const clockSkewCorrected = config3.systemClockOffset !== initialSystemClockOffset; + if (clockSkewCorrected && error50.$metadata) { + error50.$metadata.clockSkewCorrected = true; + } + } + throw error50; + }; + } + successHandler(httpResponse, signingProperties) { + const dateHeader = getDateHeader(httpResponse); + if (dateHeader) { + const config3 = throwSigningPropertyError("config", signingProperties.config); + config3.systemClockOffset = getUpdatedSystemClockOffset(dateHeader, config3.systemClockOffset); + } + } + }; + AWSSDKSigV4Signer = AwsSdkSigV4Signer; + } +}); + +// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/AwsSdkSigV4ASigner.js +var import_protocol_http11, AwsSdkSigV4ASigner; +var init_AwsSdkSigV4ASigner = __esm({ + "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/AwsSdkSigV4ASigner.js"() { + import_protocol_http11 = __toESM(require_dist_cjs2()); + init_utils5(); + init_AwsSdkSigV4Signer(); + AwsSdkSigV4ASigner = class extends AwsSdkSigV4Signer { + async sign(httpRequest2, identity, signingProperties) { + if (!import_protocol_http11.HttpRequest.isInstance(httpRequest2)) { + throw new Error("The request is not an instance of `HttpRequest` and cannot be signed"); + } + const { config: config3, signer, signingRegion, signingRegionSet, signingName } = await validateSigningProperties(signingProperties); + const configResolvedSigningRegionSet = await config3.sigv4aSigningRegionSet?.(); + const multiRegionOverride = (configResolvedSigningRegionSet ?? signingRegionSet ?? [signingRegion]).join(","); + const signedRequest = await signer.sign(httpRequest2, { + signingDate: getSkewCorrectedDate(config3.systemClockOffset), + signingRegion: multiRegionOverride, + signingService: signingName + }); + return signedRequest; + } + }; + } +}); + +// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getArrayForCommaSeparatedString.js +var getArrayForCommaSeparatedString; +var init_getArrayForCommaSeparatedString = __esm({ + "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getArrayForCommaSeparatedString.js"() { + getArrayForCommaSeparatedString = (str) => typeof str === "string" && str.length > 0 ? str.split(",").map((item) => item.trim()) : []; + } +}); + +// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getBearerTokenEnvKey.js +var getBearerTokenEnvKey; +var init_getBearerTokenEnvKey = __esm({ + "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getBearerTokenEnvKey.js"() { + getBearerTokenEnvKey = (signingName) => `AWS_BEARER_TOKEN_${signingName.replace(/[\s-]/g, "_").toUpperCase()}`; + } +}); + +// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/NODE_AUTH_SCHEME_PREFERENCE_OPTIONS.js +var NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY, NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY, NODE_AUTH_SCHEME_PREFERENCE_OPTIONS; +var init_NODE_AUTH_SCHEME_PREFERENCE_OPTIONS = __esm({ + "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/NODE_AUTH_SCHEME_PREFERENCE_OPTIONS.js"() { + init_getArrayForCommaSeparatedString(); + init_getBearerTokenEnvKey(); + NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY = "AWS_AUTH_SCHEME_PREFERENCE"; + NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY = "auth_scheme_preference"; + NODE_AUTH_SCHEME_PREFERENCE_OPTIONS = { + environmentVariableSelector: (env2, options) => { + if (options?.signingName) { + const bearerTokenKey = getBearerTokenEnvKey(options.signingName); + if (bearerTokenKey in env2) + return ["httpBearerAuth"]; + } + if (!(NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY in env2)) + return void 0; + return getArrayForCommaSeparatedString(env2[NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY]); + }, + configFileSelector: (profile) => { + if (!(NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY in profile)) + return void 0; + return getArrayForCommaSeparatedString(profile[NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY]); + }, + default: [] + }; + } +}); + +// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/resolveAwsSdkSigV4AConfig.js +var import_property_provider, resolveAwsSdkSigV4AConfig, NODE_SIGV4A_CONFIG_OPTIONS; +var init_resolveAwsSdkSigV4AConfig = __esm({ + "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/resolveAwsSdkSigV4AConfig.js"() { + init_dist_es(); + import_property_provider = __toESM(require_dist_cjs41()); + resolveAwsSdkSigV4AConfig = (config3) => { + config3.sigv4aSigningRegionSet = normalizeProvider(config3.sigv4aSigningRegionSet); + return config3; + }; + NODE_SIGV4A_CONFIG_OPTIONS = { + environmentVariableSelector(env2) { + if (env2.AWS_SIGV4A_SIGNING_REGION_SET) { + return env2.AWS_SIGV4A_SIGNING_REGION_SET.split(",").map((_) => _.trim()); + } + throw new import_property_provider.ProviderError("AWS_SIGV4A_SIGNING_REGION_SET not set in env.", { + tryNextLink: true + }); + }, + configFileSelector(profile) { + if (profile.sigv4a_signing_region_set) { + return (profile.sigv4a_signing_region_set ?? "").split(",").map((_) => _.trim()); + } + throw new import_property_provider.ProviderError("sigv4a_signing_region_set not set in profile.", { + tryNextLink: true + }); + }, + default: void 0 + }; + } +}); + +// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/resolveAwsSdkSigV4Config.js +function normalizeCredentialProvider(config3, { credentials, credentialDefaultProvider }) { + let credentialsProvider; + if (credentials) { + if (!credentials?.memoized) { + credentialsProvider = memoizeIdentityProvider(credentials, isIdentityExpired, doesIdentityRequireRefresh); + } else { + credentialsProvider = credentials; + } + } else { + if (credentialDefaultProvider) { + credentialsProvider = normalizeProvider(credentialDefaultProvider(Object.assign({}, config3, { + parentClientConfig: config3 + }))); + } else { + credentialsProvider = async () => { + throw new Error("@aws-sdk/core::resolveAwsSdkSigV4Config - `credentials` not provided and no credentialDefaultProvider was configured."); + }; + } + } + credentialsProvider.memoized = true; + return credentialsProvider; +} +function bindCallerConfig(config3, credentialsProvider) { + if (credentialsProvider.configBound) { + return credentialsProvider; + } + const fn = async (options) => credentialsProvider({ ...options, callerClientConfig: config3 }); + fn.memoized = credentialsProvider.memoized; + fn.configBound = true; + return fn; +} +var import_signature_v4, resolveAwsSdkSigV4Config, resolveAWSSDKSigV4Config; +var init_resolveAwsSdkSigV4Config = __esm({ + "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/resolveAwsSdkSigV4Config.js"() { + init_client2(); + init_dist_es(); + import_signature_v4 = __toESM(require_dist_cjs30()); + resolveAwsSdkSigV4Config = (config3) => { + let inputCredentials = config3.credentials; + let isUserSupplied = !!config3.credentials; + let resolvedCredentials = void 0; + Object.defineProperty(config3, "credentials", { + set(credentials) { + if (credentials && credentials !== inputCredentials && credentials !== resolvedCredentials) { + isUserSupplied = true; + } + inputCredentials = credentials; + const memoizedProvider = normalizeCredentialProvider(config3, { + credentials: inputCredentials, + credentialDefaultProvider: config3.credentialDefaultProvider + }); + const boundProvider = bindCallerConfig(config3, memoizedProvider); + if (isUserSupplied && !boundProvider.attributed) { + const isCredentialObject = typeof inputCredentials === "object" && inputCredentials !== null; + resolvedCredentials = async (options) => { + const creds = await boundProvider(options); + const attributedCreds = creds; + if (isCredentialObject && (!attributedCreds.$source || Object.keys(attributedCreds.$source).length === 0)) { + return setCredentialFeature(attributedCreds, "CREDENTIALS_CODE", "e"); + } + return attributedCreds; + }; + resolvedCredentials.memoized = boundProvider.memoized; + resolvedCredentials.configBound = boundProvider.configBound; + resolvedCredentials.attributed = true; + } else { + resolvedCredentials = boundProvider; + } + }, + get() { + return resolvedCredentials; + }, + enumerable: true, + configurable: true + }); + config3.credentials = inputCredentials; + const { signingEscapePath = true, systemClockOffset = config3.systemClockOffset || 0, sha256: sha2563 } = config3; + let signer; + if (config3.signer) { + signer = normalizeProvider(config3.signer); + } else if (config3.regionInfoProvider) { + signer = () => normalizeProvider(config3.region)().then(async (region) => [ + await config3.regionInfoProvider(region, { + useFipsEndpoint: await config3.useFipsEndpoint(), + useDualstackEndpoint: await config3.useDualstackEndpoint() + }) || {}, + region + ]).then(([regionInfo, region]) => { + const { signingRegion, signingService } = regionInfo; + config3.signingRegion = config3.signingRegion || signingRegion || region; + config3.signingName = config3.signingName || signingService || config3.serviceId; + const params = { + ...config3, + credentials: config3.credentials, + region: config3.signingRegion, + service: config3.signingName, + sha256: sha2563, + uriEscapePath: signingEscapePath + }; + const SignerCtor = config3.signerConstructor || import_signature_v4.SignatureV4; + return new SignerCtor(params); + }); + } else { + signer = async (authScheme) => { + authScheme = Object.assign({}, { + name: "sigv4", + signingName: config3.signingName || config3.defaultSigningName, + signingRegion: await normalizeProvider(config3.region)(), + properties: {} + }, authScheme); + const signingRegion = authScheme.signingRegion; + const signingService = authScheme.signingName; + config3.signingRegion = config3.signingRegion || signingRegion; + config3.signingName = config3.signingName || signingService || config3.serviceId; + const params = { + ...config3, + credentials: config3.credentials, + region: config3.signingRegion, + service: config3.signingName, + sha256: sha2563, + uriEscapePath: signingEscapePath + }; + const SignerCtor = config3.signerConstructor || import_signature_v4.SignatureV4; + return new SignerCtor(params); + }; + } + const resolvedConfig = Object.assign(config3, { + systemClockOffset, + signingEscapePath, + signer + }); + return resolvedConfig; + }; + resolveAWSSDKSigV4Config = resolveAwsSdkSigV4Config; + } +}); + +// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/index.js +var init_aws_sdk = __esm({ + "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/index.js"() { + init_AwsSdkSigV4Signer(); + init_AwsSdkSigV4ASigner(); + init_NODE_AUTH_SCHEME_PREFERENCE_OPTIONS(); + init_resolveAwsSdkSigV4AConfig(); + init_resolveAwsSdkSigV4Config(); + } +}); + +// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/index.js +var httpAuthSchemes_exports = {}; +__export(httpAuthSchemes_exports, { + AWSSDKSigV4Signer: () => AWSSDKSigV4Signer, + AwsSdkSigV4ASigner: () => AwsSdkSigV4ASigner, + AwsSdkSigV4Signer: () => AwsSdkSigV4Signer, + NODE_AUTH_SCHEME_PREFERENCE_OPTIONS: () => NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, + NODE_SIGV4A_CONFIG_OPTIONS: () => NODE_SIGV4A_CONFIG_OPTIONS, + getBearerTokenEnvKey: () => getBearerTokenEnvKey, + resolveAWSSDKSigV4Config: () => resolveAWSSDKSigV4Config, + resolveAwsSdkSigV4AConfig: () => resolveAwsSdkSigV4AConfig, + resolveAwsSdkSigV4Config: () => resolveAwsSdkSigV4Config, + validateSigningProperties: () => validateSigningProperties +}); +var init_httpAuthSchemes2 = __esm({ + "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/index.js"() { + init_aws_sdk(); + init_getBearerTokenEnvKey(); + } +}); + +// node_modules/.pnpm/@aws-sdk+signature-v4-multi-region@3.996.16/node_modules/@aws-sdk/signature-v4-multi-region/dist-cjs/index.js +var require_dist_cjs47 = __commonJS({ + "node_modules/.pnpm/@aws-sdk+signature-v4-multi-region@3.996.16/node_modules/@aws-sdk/signature-v4-multi-region/dist-cjs/index.js"(exports) { + "use strict"; + var middlewareSdkS3 = require_dist_cjs32(); + var signatureV4 = require_dist_cjs30(); + var signatureV4CrtContainer = { + CrtSignerV4: null + }; + var SignatureV4MultiRegion = class { + sigv4aSigner; + sigv4Signer; + signerOptions; + static sigv4aDependency() { + if (typeof signatureV4CrtContainer.CrtSignerV4 === "function") { + return "crt"; + } else if (typeof signatureV4.signatureV4aContainer.SignatureV4a === "function") { + return "js"; + } + return "none"; + } + constructor(options) { + this.sigv4Signer = new middlewareSdkS3.SignatureV4S3Express(options); + this.signerOptions = options; + } + async sign(requestToSign, options = {}) { + if (options.signingRegion === "*") { + return this.getSigv4aSigner().sign(requestToSign, options); + } + return this.sigv4Signer.sign(requestToSign, options); + } + async signWithCredentials(requestToSign, credentials, options = {}) { + if (options.signingRegion === "*") { + const signer = this.getSigv4aSigner(); + const CrtSignerV4 = signatureV4CrtContainer.CrtSignerV4; + if (CrtSignerV4 && signer instanceof CrtSignerV4) { + return signer.signWithCredentials(requestToSign, credentials, options); + } else { + throw new Error(`signWithCredentials with signingRegion '*' is only supported when using the CRT dependency @aws-sdk/signature-v4-crt. Please check whether you have installed the "@aws-sdk/signature-v4-crt" package explicitly. You must also register the package by calling [require("@aws-sdk/signature-v4-crt");] or an ESM equivalent such as [import "@aws-sdk/signature-v4-crt";]. For more information please go to https://github.com/aws/aws-sdk-js-v3#functionality-requiring-aws-common-runtime-crt`); + } + } + return this.sigv4Signer.signWithCredentials(requestToSign, credentials, options); + } + async presign(originalRequest, options = {}) { + if (options.signingRegion === "*") { + const signer = this.getSigv4aSigner(); + const CrtSignerV4 = signatureV4CrtContainer.CrtSignerV4; + if (CrtSignerV4 && signer instanceof CrtSignerV4) { + return signer.presign(originalRequest, options); + } else { + throw new Error(`presign with signingRegion '*' is only supported when using the CRT dependency @aws-sdk/signature-v4-crt. Please check whether you have installed the "@aws-sdk/signature-v4-crt" package explicitly. You must also register the package by calling [require("@aws-sdk/signature-v4-crt");] or an ESM equivalent such as [import "@aws-sdk/signature-v4-crt";]. For more information please go to https://github.com/aws/aws-sdk-js-v3#functionality-requiring-aws-common-runtime-crt`); + } + } + return this.sigv4Signer.presign(originalRequest, options); + } + async presignWithCredentials(originalRequest, credentials, options = {}) { + if (options.signingRegion === "*") { + throw new Error("Method presignWithCredentials is not supported for [signingRegion=*]."); + } + return this.sigv4Signer.presignWithCredentials(originalRequest, credentials, options); + } + getSigv4aSigner() { + if (!this.sigv4aSigner) { + const CrtSignerV4 = signatureV4CrtContainer.CrtSignerV4; + const JsSigV4aSigner = signatureV4.signatureV4aContainer.SignatureV4a; + if (this.signerOptions.runtime === "node") { + if (!CrtSignerV4 && !JsSigV4aSigner) { + throw new Error("Neither CRT nor JS SigV4a implementation is available. Please load either @aws-sdk/signature-v4-crt or @aws-sdk/signature-v4a. For more information please go to https://github.com/aws/aws-sdk-js-v3#functionality-requiring-aws-common-runtime-crt"); + } + if (CrtSignerV4 && typeof CrtSignerV4 === "function") { + this.sigv4aSigner = new CrtSignerV4({ + ...this.signerOptions, + signingAlgorithm: 1 + }); + } else if (JsSigV4aSigner && typeof JsSigV4aSigner === "function") { + this.sigv4aSigner = new JsSigV4aSigner({ + ...this.signerOptions + }); + } else { + throw new Error("Available SigV4a implementation is not a valid constructor. Please ensure you've properly imported @aws-sdk/signature-v4-crt or @aws-sdk/signature-v4a.For more information please go to https://github.com/aws/aws-sdk-js-v3#functionality-requiring-aws-common-runtime-crt"); + } + } else { + if (!JsSigV4aSigner || typeof JsSigV4aSigner !== "function") { + throw new Error("JS SigV4a implementation is not available or not a valid constructor. Please check whether you have installed the @aws-sdk/signature-v4a package explicitly. The CRT implementation is not available for browsers. You must also register the package by calling [require('@aws-sdk/signature-v4a');] or an ESM equivalent such as [import '@aws-sdk/signature-v4a';]. For more information please go to https://github.com/aws/aws-sdk-js-v3#using-javascript-non-crt-implementation-of-sigv4a"); + } + this.sigv4aSigner = new JsSigV4aSigner({ + ...this.signerOptions + }); + } + } + return this.sigv4aSigner; + } + }; + exports.SignatureV4MultiRegion = SignatureV4MultiRegion; + exports.signatureV4CrtContainer = signatureV4CrtContainer; + } +}); + +// node_modules/.pnpm/@aws-sdk+client-s3@3.1030.0/node_modules/@aws-sdk/client-s3/dist-cjs/endpoint/ruleset.js +var require_ruleset = __commonJS({ + "node_modules/.pnpm/@aws-sdk+client-s3@3.1030.0/node_modules/@aws-sdk/client-s3/dist-cjs/endpoint/ruleset.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ruleSet = void 0; + var cs = "required"; + var ct = "type"; + var cu = "rules"; + var cv = "conditions"; + var cw = "fn"; + var cx = "argv"; + var cy = "ref"; + var cz = "assign"; + var cA = "url"; + var cB = "properties"; + var cC = "backend"; + var cD = "authSchemes"; + var cE = "disableDoubleEncoding"; + var cF = "signingName"; + var cG = "signingRegion"; + var cH = "headers"; + var cI = "signingRegionSet"; + var a5 = 6; + var b6 = false; + var c5 = true; + var d5 = "isSet"; + var e5 = "booleanEquals"; + var f5 = "error"; + var g5 = "aws.partition"; + var h5 = "stringEquals"; + var i5 = "getAttr"; + var j5 = "name"; + var k5 = "substring"; + var l5 = "bucketSuffix"; + var m5 = "parseURL"; + var n5 = "endpoint"; + var o5 = "tree"; + var p5 = "aws.isVirtualHostableS3Bucket"; + var q5 = "{url#scheme}://{Bucket}.{url#authority}{url#path}"; + var r5 = "not"; + var s5 = "accessPointSuffix"; + var t5 = "{url#scheme}://{url#authority}{url#path}"; + var u5 = "hardwareType"; + var v5 = "regionPrefix"; + var w5 = "bucketAliasSuffix"; + var x5 = "outpostId"; + var y2 = "isValidHostLabel"; + var z3 = "sigv4a"; + var A2 = "s3-outposts"; + var B2 = "s3"; + var C2 = "{url#scheme}://{url#authority}{url#normalizedPath}{Bucket}"; + var D2 = "https://{Bucket}.s3-accelerate.{partitionResult#dnsSuffix}"; + var E2 = "https://{Bucket}.s3.{partitionResult#dnsSuffix}"; + var F2 = "aws.parseArn"; + var G2 = "bucketArn"; + var H2 = "arnType"; + var I2 = ""; + var J2 = "s3-object-lambda"; + var K = "accesspoint"; + var L = "accessPointName"; + var M = "{url#scheme}://{accessPointName}-{bucketArn#accountId}.{url#authority}{url#path}"; + var N = "mrapPartition"; + var O = "outpostType"; + var P = "arnPrefix"; + var Q = "{url#scheme}://{url#authority}{url#normalizedPath}{uri_encoded_bucket}"; + var R = "https://s3.{partitionResult#dnsSuffix}/{uri_encoded_bucket}"; + var S = "https://s3.{partitionResult#dnsSuffix}"; + var T = { [cs]: false, [ct]: "string" }; + var U = { [cs]: true, "default": false, [ct]: "boolean" }; + var V = { [cs]: false, [ct]: "boolean" }; + var W = { [cw]: e5, [cx]: [{ [cy]: "Accelerate" }, true] }; + var X = { [cw]: e5, [cx]: [{ [cy]: "UseFIPS" }, true] }; + var Y = { [cw]: e5, [cx]: [{ [cy]: "UseDualStack" }, true] }; + var Z = { [cw]: d5, [cx]: [{ [cy]: "Endpoint" }] }; + var aa = { [cw]: g5, [cx]: [{ [cy]: "Region" }], [cz]: "partitionResult" }; + var ab = { [cw]: h5, [cx]: [{ [cw]: i5, [cx]: [{ [cy]: "partitionResult" }, j5] }, "aws-cn"] }; + var ac = { [cw]: d5, [cx]: [{ [cy]: "Bucket" }] }; + var ad = { [cy]: "Bucket" }; + var ae = { [cv]: [W], [f5]: "S3Express does not support S3 Accelerate.", [ct]: f5 }; + var af = { [cv]: [Z, { [cw]: m5, [cx]: [{ [cy]: "Endpoint" }], [cz]: "url" }], [cu]: [{ [cv]: [{ [cw]: d5, [cx]: [{ [cy]: "DisableS3ExpressSessionAuth" }] }, { [cw]: e5, [cx]: [{ [cy]: "DisableS3ExpressSessionAuth" }, true] }], [cu]: [{ [cv]: [{ [cw]: e5, [cx]: [{ [cw]: i5, [cx]: [{ [cy]: "url" }, "isIp"] }, true] }], [cu]: [{ [cv]: [{ [cw]: "uriEncode", [cx]: [ad], [cz]: "uri_encoded_bucket" }], [cu]: [{ [n5]: { [cA]: "{url#scheme}://{url#authority}/{uri_encoded_bucket}{url#path}", [cB]: { [cC]: "S3Express", [cD]: [{ [cE]: true, [j5]: "sigv4", [cF]: "s3express", [cG]: "{Region}" }] }, [cH]: {} }, [ct]: n5 }], [ct]: o5 }], [ct]: o5 }, { [cv]: [{ [cw]: p5, [cx]: [ad, false] }], [cu]: [{ [n5]: { [cA]: q5, [cB]: { [cC]: "S3Express", [cD]: [{ [cE]: true, [j5]: "sigv4", [cF]: "s3express", [cG]: "{Region}" }] }, [cH]: {} }, [ct]: n5 }], [ct]: o5 }, { [f5]: "S3Express bucket name is not a valid virtual hostable name.", [ct]: f5 }], [ct]: o5 }, { [cv]: [{ [cw]: e5, [cx]: [{ [cw]: i5, [cx]: [{ [cy]: "url" }, "isIp"] }, true] }], [cu]: [{ [cv]: [{ [cw]: "uriEncode", [cx]: [ad], [cz]: "uri_encoded_bucket" }], [cu]: [{ [n5]: { [cA]: "{url#scheme}://{url#authority}/{uri_encoded_bucket}{url#path}", [cB]: { [cC]: "S3Express", [cD]: [{ [cE]: true, [j5]: "sigv4-s3express", [cF]: "s3express", [cG]: "{Region}" }] }, [cH]: {} }, [ct]: n5 }], [ct]: o5 }], [ct]: o5 }, { [cv]: [{ [cw]: p5, [cx]: [ad, false] }], [cu]: [{ [n5]: { [cA]: q5, [cB]: { [cC]: "S3Express", [cD]: [{ [cE]: true, [j5]: "sigv4-s3express", [cF]: "s3express", [cG]: "{Region}" }] }, [cH]: {} }, [ct]: n5 }], [ct]: o5 }, { [f5]: "S3Express bucket name is not a valid virtual hostable name.", [ct]: f5 }], [ct]: o5 }; + var ag = { [cw]: m5, [cx]: [{ [cy]: "Endpoint" }], [cz]: "url" }; + var ah = { [cw]: e5, [cx]: [{ [cw]: i5, [cx]: [{ [cy]: "url" }, "isIp"] }, true] }; + var ai = { [cy]: "url" }; + var aj = { [cw]: "uriEncode", [cx]: [ad], [cz]: "uri_encoded_bucket" }; + var ak = { [cC]: "S3Express", [cD]: [{ [cE]: true, [j5]: "sigv4", [cF]: "s3express", [cG]: "{Region}" }] }; + var al = {}; + var am = { [cw]: p5, [cx]: [ad, false] }; + var an = { [f5]: "S3Express bucket name is not a valid virtual hostable name.", [ct]: f5 }; + var ao = { [cw]: d5, [cx]: [{ [cy]: "UseS3ExpressControlEndpoint" }] }; + var ap = { [cw]: e5, [cx]: [{ [cy]: "UseS3ExpressControlEndpoint" }, true] }; + var aq = { [cw]: r5, [cx]: [Z] }; + var ar = { [cw]: e5, [cx]: [{ [cy]: "UseDualStack" }, false] }; + var as = { [cw]: e5, [cx]: [{ [cy]: "UseFIPS" }, false] }; + var at = { [f5]: "Unrecognized S3Express bucket name format.", [ct]: f5 }; + var au = { [cw]: r5, [cx]: [ac] }; + var av = { [cy]: u5 }; + var aw = { [cv]: [aq], [f5]: "Expected a endpoint to be specified but no endpoint was found", [ct]: f5 }; + var ax = { [cD]: [{ [cE]: true, [j5]: z3, [cF]: A2, [cI]: ["*"] }, { [cE]: true, [j5]: "sigv4", [cF]: A2, [cG]: "{Region}" }] }; + var ay = { [cw]: e5, [cx]: [{ [cy]: "ForcePathStyle" }, false] }; + var az = { [cy]: "ForcePathStyle" }; + var aA = { [cw]: e5, [cx]: [{ [cy]: "Accelerate" }, false] }; + var aB = { [cw]: h5, [cx]: [{ [cy]: "Region" }, "aws-global"] }; + var aC = { [cD]: [{ [cE]: true, [j5]: "sigv4", [cF]: B2, [cG]: "us-east-1" }] }; + var aD = { [cw]: r5, [cx]: [aB] }; + var aE = { [cw]: e5, [cx]: [{ [cy]: "UseGlobalEndpoint" }, true] }; + var aF = { [cA]: "https://{Bucket}.s3-fips.dualstack.{Region}.{partitionResult#dnsSuffix}", [cB]: { [cD]: [{ [cE]: true, [j5]: "sigv4", [cF]: B2, [cG]: "{Region}" }] }, [cH]: {} }; + var aG = { [cD]: [{ [cE]: true, [j5]: "sigv4", [cF]: B2, [cG]: "{Region}" }] }; + var aH = { [cw]: e5, [cx]: [{ [cy]: "UseGlobalEndpoint" }, false] }; + var aI = { [cA]: "https://{Bucket}.s3-fips.{Region}.{partitionResult#dnsSuffix}", [cB]: aG, [cH]: {} }; + var aJ = { [cA]: "https://{Bucket}.s3-accelerate.dualstack.{partitionResult#dnsSuffix}", [cB]: aG, [cH]: {} }; + var aK = { [cA]: "https://{Bucket}.s3.dualstack.{Region}.{partitionResult#dnsSuffix}", [cB]: aG, [cH]: {} }; + var aL = { [cw]: e5, [cx]: [{ [cw]: i5, [cx]: [ai, "isIp"] }, false] }; + var aM = { [cA]: C2, [cB]: aG, [cH]: {} }; + var aN = { [cA]: q5, [cB]: aG, [cH]: {} }; + var aO = { [n5]: aN, [ct]: n5 }; + var aP = { [cA]: D2, [cB]: aG, [cH]: {} }; + var aQ = { [cA]: "https://{Bucket}.s3.{Region}.{partitionResult#dnsSuffix}", [cB]: aG, [cH]: {} }; + var aR = { [f5]: "Invalid region: region was not a valid DNS name.", [ct]: f5 }; + var aS = { [cy]: G2 }; + var aT = { [cy]: H2 }; + var aU = { [cw]: i5, [cx]: [aS, "service"] }; + var aV = { [cy]: L }; + var aW = { [cv]: [Y], [f5]: "S3 Object Lambda does not support Dual-stack", [ct]: f5 }; + var aX = { [cv]: [W], [f5]: "S3 Object Lambda does not support S3 Accelerate", [ct]: f5 }; + var aY = { [cv]: [{ [cw]: d5, [cx]: [{ [cy]: "DisableAccessPoints" }] }, { [cw]: e5, [cx]: [{ [cy]: "DisableAccessPoints" }, true] }], [f5]: "Access points are not supported for this operation", [ct]: f5 }; + var aZ = { [cv]: [{ [cw]: d5, [cx]: [{ [cy]: "UseArnRegion" }] }, { [cw]: e5, [cx]: [{ [cy]: "UseArnRegion" }, false] }, { [cw]: r5, [cx]: [{ [cw]: h5, [cx]: [{ [cw]: i5, [cx]: [aS, "region"] }, "{Region}"] }] }], [f5]: "Invalid configuration: region from ARN `{bucketArn#region}` does not match client region `{Region}` and UseArnRegion is `false`", [ct]: f5 }; + var ba = { [cw]: i5, [cx]: [{ [cy]: "bucketPartition" }, j5] }; + var bb = { [cw]: i5, [cx]: [aS, "accountId"] }; + var bc = { [cD]: [{ [cE]: true, [j5]: "sigv4", [cF]: J2, [cG]: "{bucketArn#region}" }] }; + var bd = { [f5]: "Invalid ARN: The access point name may only contain a-z, A-Z, 0-9 and `-`. Found: `{accessPointName}`", [ct]: f5 }; + var be = { [f5]: "Invalid ARN: The account id may only contain a-z, A-Z, 0-9 and `-`. Found: `{bucketArn#accountId}`", [ct]: f5 }; + var bf = { [f5]: "Invalid region in ARN: `{bucketArn#region}` (invalid DNS name)", [ct]: f5 }; + var bg = { [f5]: "Client was configured for partition `{partitionResult#name}` but ARN (`{Bucket}`) has `{bucketPartition#name}`", [ct]: f5 }; + var bh = { [f5]: "Invalid ARN: The ARN may only contain a single resource component after `accesspoint`.", [ct]: f5 }; + var bi = { [f5]: "Invalid ARN: Expected a resource of the format `accesspoint:` but no name was provided", [ct]: f5 }; + var bj = { [cD]: [{ [cE]: true, [j5]: "sigv4", [cF]: B2, [cG]: "{bucketArn#region}" }] }; + var bk = { [cD]: [{ [cE]: true, [j5]: z3, [cF]: A2, [cI]: ["*"] }, { [cE]: true, [j5]: "sigv4", [cF]: A2, [cG]: "{bucketArn#region}" }] }; + var bl = { [cw]: F2, [cx]: [ad] }; + var bm = { [cA]: "https://s3-fips.dualstack.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}", [cB]: aG, [cH]: {} }; + var bn = { [cA]: "https://s3-fips.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}", [cB]: aG, [cH]: {} }; + var bo = { [cA]: "https://s3.dualstack.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}", [cB]: aG, [cH]: {} }; + var bp = { [cA]: Q, [cB]: aG, [cH]: {} }; + var bq = { [cA]: "https://s3.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}", [cB]: aG, [cH]: {} }; + var br = { [cy]: "UseObjectLambdaEndpoint" }; + var bs = { [cD]: [{ [cE]: true, [j5]: "sigv4", [cF]: J2, [cG]: "{Region}" }] }; + var bt = { [cA]: "https://s3-fips.dualstack.{Region}.{partitionResult#dnsSuffix}", [cB]: aG, [cH]: {} }; + var bu = { [cA]: "https://s3-fips.{Region}.{partitionResult#dnsSuffix}", [cB]: aG, [cH]: {} }; + var bv = { [cA]: "https://s3.dualstack.{Region}.{partitionResult#dnsSuffix}", [cB]: aG, [cH]: {} }; + var bw = { [cA]: t5, [cB]: aG, [cH]: {} }; + var bx = { [cA]: "https://s3.{Region}.{partitionResult#dnsSuffix}", [cB]: aG, [cH]: {} }; + var by = [{ [cy]: "Region" }]; + var bz = [{ [cy]: "Endpoint" }]; + var bA = [ad]; + var bB = [W]; + var bC = [Z, ag]; + var bD = [{ [cw]: d5, [cx]: [{ [cy]: "DisableS3ExpressSessionAuth" }] }, { [cw]: e5, [cx]: [{ [cy]: "DisableS3ExpressSessionAuth" }, true] }]; + var bE = [aj]; + var bF = [am]; + var bG = [aa]; + var bH = [X, Y]; + var bI = [X, ar]; + var bJ = [as, Y]; + var bK = [as, ar]; + var bL = [{ [cw]: k5, [cx]: [ad, 6, 14, true], [cz]: "s3expressAvailabilityZoneId" }, { [cw]: k5, [cx]: [ad, 14, 16, true], [cz]: "s3expressAvailabilityZoneDelim" }, { [cw]: h5, [cx]: [{ [cy]: "s3expressAvailabilityZoneDelim" }, "--"] }]; + var bM = [{ [cv]: [X, Y], [n5]: { [cA]: "https://{Bucket}.s3express-fips-{s3expressAvailabilityZoneId}.dualstack.{Region}.{partitionResult#dnsSuffix}", [cB]: ak, [cH]: {} }, [ct]: n5 }, { [cv]: bI, [n5]: { [cA]: "https://{Bucket}.s3express-fips-{s3expressAvailabilityZoneId}.{Region}.{partitionResult#dnsSuffix}", [cB]: ak, [cH]: {} }, [ct]: n5 }, { [cv]: bJ, [n5]: { [cA]: "https://{Bucket}.s3express-{s3expressAvailabilityZoneId}.dualstack.{Region}.{partitionResult#dnsSuffix}", [cB]: ak, [cH]: {} }, [ct]: n5 }, { [cv]: bK, [n5]: { [cA]: "https://{Bucket}.s3express-{s3expressAvailabilityZoneId}.{Region}.{partitionResult#dnsSuffix}", [cB]: ak, [cH]: {} }, [ct]: n5 }]; + var bN = [{ [cw]: k5, [cx]: [ad, 6, 15, true], [cz]: "s3expressAvailabilityZoneId" }, { [cw]: k5, [cx]: [ad, 15, 17, true], [cz]: "s3expressAvailabilityZoneDelim" }, { [cw]: h5, [cx]: [{ [cy]: "s3expressAvailabilityZoneDelim" }, "--"] }]; + var bO = [{ [cw]: k5, [cx]: [ad, 6, 19, true], [cz]: "s3expressAvailabilityZoneId" }, { [cw]: k5, [cx]: [ad, 19, 21, true], [cz]: "s3expressAvailabilityZoneDelim" }, { [cw]: h5, [cx]: [{ [cy]: "s3expressAvailabilityZoneDelim" }, "--"] }]; + var bP = [{ [cw]: k5, [cx]: [ad, 6, 20, true], [cz]: "s3expressAvailabilityZoneId" }, { [cw]: k5, [cx]: [ad, 20, 22, true], [cz]: "s3expressAvailabilityZoneDelim" }, { [cw]: h5, [cx]: [{ [cy]: "s3expressAvailabilityZoneDelim" }, "--"] }]; + var bQ = [{ [cw]: k5, [cx]: [ad, 6, 26, true], [cz]: "s3expressAvailabilityZoneId" }, { [cw]: k5, [cx]: [ad, 26, 28, true], [cz]: "s3expressAvailabilityZoneDelim" }, { [cw]: h5, [cx]: [{ [cy]: "s3expressAvailabilityZoneDelim" }, "--"] }]; + var bR = [{ [cv]: [X, Y], [n5]: { [cA]: "https://{Bucket}.s3express-fips-{s3expressAvailabilityZoneId}.dualstack.{Region}.{partitionResult#dnsSuffix}", [cB]: { [cC]: "S3Express", [cD]: [{ [cE]: true, [j5]: "sigv4-s3express", [cF]: "s3express", [cG]: "{Region}" }] }, [cH]: {} }, [ct]: n5 }, { [cv]: bI, [n5]: { [cA]: "https://{Bucket}.s3express-fips-{s3expressAvailabilityZoneId}.{Region}.{partitionResult#dnsSuffix}", [cB]: { [cC]: "S3Express", [cD]: [{ [cE]: true, [j5]: "sigv4-s3express", [cF]: "s3express", [cG]: "{Region}" }] }, [cH]: {} }, [ct]: n5 }, { [cv]: bJ, [n5]: { [cA]: "https://{Bucket}.s3express-{s3expressAvailabilityZoneId}.dualstack.{Region}.{partitionResult#dnsSuffix}", [cB]: { [cC]: "S3Express", [cD]: [{ [cE]: true, [j5]: "sigv4-s3express", [cF]: "s3express", [cG]: "{Region}" }] }, [cH]: {} }, [ct]: n5 }, { [cv]: bK, [n5]: { [cA]: "https://{Bucket}.s3express-{s3expressAvailabilityZoneId}.{Region}.{partitionResult#dnsSuffix}", [cB]: { [cC]: "S3Express", [cD]: [{ [cE]: true, [j5]: "sigv4-s3express", [cF]: "s3express", [cG]: "{Region}" }] }, [cH]: {} }, [ct]: n5 }]; + var bS = [ad, 0, 7, true]; + var bT = [{ [cw]: k5, [cx]: [ad, 7, 15, true], [cz]: "s3expressAvailabilityZoneId" }, { [cw]: k5, [cx]: [ad, 15, 17, true], [cz]: "s3expressAvailabilityZoneDelim" }, { [cw]: h5, [cx]: [{ [cy]: "s3expressAvailabilityZoneDelim" }, "--"] }]; + var bU = [{ [cw]: k5, [cx]: [ad, 7, 16, true], [cz]: "s3expressAvailabilityZoneId" }, { [cw]: k5, [cx]: [ad, 16, 18, true], [cz]: "s3expressAvailabilityZoneDelim" }, { [cw]: h5, [cx]: [{ [cy]: "s3expressAvailabilityZoneDelim" }, "--"] }]; + var bV = [{ [cw]: k5, [cx]: [ad, 7, 20, true], [cz]: "s3expressAvailabilityZoneId" }, { [cw]: k5, [cx]: [ad, 20, 22, true], [cz]: "s3expressAvailabilityZoneDelim" }, { [cw]: h5, [cx]: [{ [cy]: "s3expressAvailabilityZoneDelim" }, "--"] }]; + var bW = [{ [cw]: k5, [cx]: [ad, 7, 21, true], [cz]: "s3expressAvailabilityZoneId" }, { [cw]: k5, [cx]: [ad, 21, 23, true], [cz]: "s3expressAvailabilityZoneDelim" }, { [cw]: h5, [cx]: [{ [cy]: "s3expressAvailabilityZoneDelim" }, "--"] }]; + var bX = [{ [cw]: k5, [cx]: [ad, 7, 27, true], [cz]: "s3expressAvailabilityZoneId" }, { [cw]: k5, [cx]: [ad, 27, 29, true], [cz]: "s3expressAvailabilityZoneDelim" }, { [cw]: h5, [cx]: [{ [cy]: "s3expressAvailabilityZoneDelim" }, "--"] }]; + var bY = [ac]; + var bZ = [{ [cw]: y2, [cx]: [{ [cy]: x5 }, false] }]; + var ca = [{ [cw]: h5, [cx]: [{ [cy]: v5 }, "beta"] }]; + var cb = ["*"]; + var cc = [{ [cw]: y2, [cx]: [{ [cy]: "Region" }, false] }]; + var cd = [{ [cw]: h5, [cx]: [{ [cy]: "Region" }, "us-east-1"] }]; + var ce = [{ [cw]: h5, [cx]: [aT, K] }]; + var cf = [{ [cw]: i5, [cx]: [aS, "resourceId[1]"], [cz]: L }, { [cw]: r5, [cx]: [{ [cw]: h5, [cx]: [aV, I2] }] }]; + var cg = [aS, "resourceId[1]"]; + var ch = [Y]; + var ci = [{ [cw]: r5, [cx]: [{ [cw]: h5, [cx]: [{ [cw]: i5, [cx]: [aS, "region"] }, I2] }] }]; + var cj = [{ [cw]: r5, [cx]: [{ [cw]: d5, [cx]: [{ [cw]: i5, [cx]: [aS, "resourceId[2]"] }] }] }]; + var ck = [aS, "resourceId[2]"]; + var cl = [{ [cw]: g5, [cx]: [{ [cw]: i5, [cx]: [aS, "region"] }], [cz]: "bucketPartition" }]; + var cm = [{ [cw]: h5, [cx]: [ba, { [cw]: i5, [cx]: [{ [cy]: "partitionResult" }, j5] }] }]; + var cn = [{ [cw]: y2, [cx]: [{ [cw]: i5, [cx]: [aS, "region"] }, true] }]; + var co = [{ [cw]: y2, [cx]: [bb, false] }]; + var cp = [{ [cw]: y2, [cx]: [aV, false] }]; + var cq = [X]; + var cr = [{ [cw]: y2, [cx]: [{ [cy]: "Region" }, true] }]; + var _data5 = { version: "1.0", parameters: { Bucket: T, Region: T, UseFIPS: U, UseDualStack: U, Endpoint: T, ForcePathStyle: U, Accelerate: U, UseGlobalEndpoint: U, UseObjectLambdaEndpoint: V, Key: T, Prefix: T, CopySource: T, DisableAccessPoints: V, DisableMultiRegionAccessPoints: U, UseArnRegion: V, UseS3ExpressControlEndpoint: V, DisableS3ExpressSessionAuth: V }, [cu]: [{ [cv]: [{ [cw]: d5, [cx]: by }], [cu]: [{ [cv]: [W, X], error: "Accelerate cannot be used with FIPS", [ct]: f5 }, { [cv]: [Y, Z], error: "Cannot set dual-stack in combination with a custom endpoint.", [ct]: f5 }, { [cv]: [Z, X], error: "A custom endpoint cannot be combined with FIPS", [ct]: f5 }, { [cv]: [Z, W], error: "A custom endpoint cannot be combined with S3 Accelerate", [ct]: f5 }, { [cv]: [X, aa, ab], error: "Partition does not support FIPS", [ct]: f5 }, { [cv]: [ac, { [cw]: k5, [cx]: [ad, 0, a5, c5], [cz]: l5 }, { [cw]: h5, [cx]: [{ [cy]: l5 }, "--x-s3"] }], [cu]: [ae, af, { [cv]: [ao, ap], [cu]: [{ [cv]: bG, [cu]: [{ [cv]: [aj, aq], [cu]: [{ [cv]: bH, endpoint: { [cA]: "https://s3express-control-fips.dualstack.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}", [cB]: ak, [cH]: al }, [ct]: n5 }, { [cv]: bI, endpoint: { [cA]: "https://s3express-control-fips.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}", [cB]: ak, [cH]: al }, [ct]: n5 }, { [cv]: bJ, endpoint: { [cA]: "https://s3express-control.dualstack.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}", [cB]: ak, [cH]: al }, [ct]: n5 }, { [cv]: bK, endpoint: { [cA]: "https://s3express-control.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}", [cB]: ak, [cH]: al }, [ct]: n5 }], [ct]: o5 }], [ct]: o5 }], [ct]: o5 }, { [cv]: bF, [cu]: [{ [cv]: bG, [cu]: [{ [cv]: bD, [cu]: [{ [cv]: bL, [cu]: bM, [ct]: o5 }, { [cv]: bN, [cu]: bM, [ct]: o5 }, { [cv]: bO, [cu]: bM, [ct]: o5 }, { [cv]: bP, [cu]: bM, [ct]: o5 }, { [cv]: bQ, [cu]: bM, [ct]: o5 }, at], [ct]: o5 }, { [cv]: bL, [cu]: bR, [ct]: o5 }, { [cv]: bN, [cu]: bR, [ct]: o5 }, { [cv]: bO, [cu]: bR, [ct]: o5 }, { [cv]: bP, [cu]: bR, [ct]: o5 }, { [cv]: bQ, [cu]: bR, [ct]: o5 }, at], [ct]: o5 }], [ct]: o5 }, an], [ct]: o5 }, { [cv]: [ac, { [cw]: k5, [cx]: bS, [cz]: s5 }, { [cw]: h5, [cx]: [{ [cy]: s5 }, "--xa-s3"] }], [cu]: [ae, af, { [cv]: bF, [cu]: [{ [cv]: bG, [cu]: [{ [cv]: bD, [cu]: [{ [cv]: bT, [cu]: bM, [ct]: o5 }, { [cv]: bU, [cu]: bM, [ct]: o5 }, { [cv]: bV, [cu]: bM, [ct]: o5 }, { [cv]: bW, [cu]: bM, [ct]: o5 }, { [cv]: bX, [cu]: bM, [ct]: o5 }, at], [ct]: o5 }, { [cv]: bT, [cu]: bR, [ct]: o5 }, { [cv]: bU, [cu]: bR, [ct]: o5 }, { [cv]: bV, [cu]: bR, [ct]: o5 }, { [cv]: bW, [cu]: bR, [ct]: o5 }, { [cv]: bX, [cu]: bR, [ct]: o5 }, at], [ct]: o5 }], [ct]: o5 }, an], [ct]: o5 }, { [cv]: [au, ao, ap], [cu]: [{ [cv]: bG, [cu]: [{ [cv]: bC, endpoint: { [cA]: t5, [cB]: ak, [cH]: al }, [ct]: n5 }, { [cv]: bH, endpoint: { [cA]: "https://s3express-control-fips.dualstack.{Region}.{partitionResult#dnsSuffix}", [cB]: ak, [cH]: al }, [ct]: n5 }, { [cv]: bI, endpoint: { [cA]: "https://s3express-control-fips.{Region}.{partitionResult#dnsSuffix}", [cB]: ak, [cH]: al }, [ct]: n5 }, { [cv]: bJ, endpoint: { [cA]: "https://s3express-control.dualstack.{Region}.{partitionResult#dnsSuffix}", [cB]: ak, [cH]: al }, [ct]: n5 }, { [cv]: bK, endpoint: { [cA]: "https://s3express-control.{Region}.{partitionResult#dnsSuffix}", [cB]: ak, [cH]: al }, [ct]: n5 }], [ct]: o5 }], [ct]: o5 }, { [cv]: [ac, { [cw]: k5, [cx]: [ad, 49, 50, c5], [cz]: u5 }, { [cw]: k5, [cx]: [ad, 8, 12, c5], [cz]: v5 }, { [cw]: k5, [cx]: bS, [cz]: w5 }, { [cw]: k5, [cx]: [ad, 32, 49, c5], [cz]: x5 }, { [cw]: g5, [cx]: by, [cz]: "regionPartition" }, { [cw]: h5, [cx]: [{ [cy]: w5 }, "--op-s3"] }], [cu]: [{ [cv]: bZ, [cu]: [{ [cv]: bF, [cu]: [{ [cv]: [{ [cw]: h5, [cx]: [av, "e"] }], [cu]: [{ [cv]: ca, [cu]: [aw, { [cv]: bC, endpoint: { [cA]: "https://{Bucket}.ec2.{url#authority}", [cB]: ax, [cH]: al }, [ct]: n5 }], [ct]: o5 }, { endpoint: { [cA]: "https://{Bucket}.ec2.s3-outposts.{Region}.{regionPartition#dnsSuffix}", [cB]: ax, [cH]: al }, [ct]: n5 }], [ct]: o5 }, { [cv]: [{ [cw]: h5, [cx]: [av, "o"] }], [cu]: [{ [cv]: ca, [cu]: [aw, { [cv]: bC, endpoint: { [cA]: "https://{Bucket}.op-{outpostId}.{url#authority}", [cB]: ax, [cH]: al }, [ct]: n5 }], [ct]: o5 }, { endpoint: { [cA]: "https://{Bucket}.op-{outpostId}.s3-outposts.{Region}.{regionPartition#dnsSuffix}", [cB]: ax, [cH]: al }, [ct]: n5 }], [ct]: o5 }, { error: 'Unrecognized hardware type: "Expected hardware type o or e but got {hardwareType}"', [ct]: f5 }], [ct]: o5 }, { error: "Invalid Outposts Bucket alias - it must be a valid bucket name.", [ct]: f5 }], [ct]: o5 }, { error: "Invalid ARN: The outpost Id must only contain a-z, A-Z, 0-9 and `-`.", [ct]: f5 }], [ct]: o5 }, { [cv]: bY, [cu]: [{ [cv]: [Z, { [cw]: r5, [cx]: [{ [cw]: d5, [cx]: [{ [cw]: m5, [cx]: bz }] }] }], error: "Custom endpoint `{Endpoint}` was not a valid URI", [ct]: f5 }, { [cv]: [ay, am], [cu]: [{ [cv]: bG, [cu]: [{ [cv]: cc, [cu]: [{ [cv]: [W, ab], error: "S3 Accelerate cannot be used in this region", [ct]: f5 }, { [cv]: [Y, X, aA, aq, aB], endpoint: { [cA]: "https://{Bucket}.s3-fips.dualstack.us-east-1.{partitionResult#dnsSuffix}", [cB]: aC, [cH]: al }, [ct]: n5 }, { [cv]: [Y, X, aA, aq, aD, aE], [cu]: [{ endpoint: aF, [ct]: n5 }], [ct]: o5 }, { [cv]: [Y, X, aA, aq, aD, aH], endpoint: aF, [ct]: n5 }, { [cv]: [ar, X, aA, aq, aB], endpoint: { [cA]: "https://{Bucket}.s3-fips.us-east-1.{partitionResult#dnsSuffix}", [cB]: aC, [cH]: al }, [ct]: n5 }, { [cv]: [ar, X, aA, aq, aD, aE], [cu]: [{ endpoint: aI, [ct]: n5 }], [ct]: o5 }, { [cv]: [ar, X, aA, aq, aD, aH], endpoint: aI, [ct]: n5 }, { [cv]: [Y, as, W, aq, aB], endpoint: { [cA]: "https://{Bucket}.s3-accelerate.dualstack.us-east-1.{partitionResult#dnsSuffix}", [cB]: aC, [cH]: al }, [ct]: n5 }, { [cv]: [Y, as, W, aq, aD, aE], [cu]: [{ endpoint: aJ, [ct]: n5 }], [ct]: o5 }, { [cv]: [Y, as, W, aq, aD, aH], endpoint: aJ, [ct]: n5 }, { [cv]: [Y, as, aA, aq, aB], endpoint: { [cA]: "https://{Bucket}.s3.dualstack.us-east-1.{partitionResult#dnsSuffix}", [cB]: aC, [cH]: al }, [ct]: n5 }, { [cv]: [Y, as, aA, aq, aD, aE], [cu]: [{ endpoint: aK, [ct]: n5 }], [ct]: o5 }, { [cv]: [Y, as, aA, aq, aD, aH], endpoint: aK, [ct]: n5 }, { [cv]: [ar, as, aA, Z, ag, ah, aB], endpoint: { [cA]: C2, [cB]: aC, [cH]: al }, [ct]: n5 }, { [cv]: [ar, as, aA, Z, ag, aL, aB], endpoint: { [cA]: q5, [cB]: aC, [cH]: al }, [ct]: n5 }, { [cv]: [ar, as, aA, Z, ag, ah, aD, aE], [cu]: [{ [cv]: cd, endpoint: aM, [ct]: n5 }, { endpoint: aM, [ct]: n5 }], [ct]: o5 }, { [cv]: [ar, as, aA, Z, ag, aL, aD, aE], [cu]: [{ [cv]: cd, endpoint: aN, [ct]: n5 }, aO], [ct]: o5 }, { [cv]: [ar, as, aA, Z, ag, ah, aD, aH], endpoint: aM, [ct]: n5 }, { [cv]: [ar, as, aA, Z, ag, aL, aD, aH], endpoint: aN, [ct]: n5 }, { [cv]: [ar, as, W, aq, aB], endpoint: { [cA]: D2, [cB]: aC, [cH]: al }, [ct]: n5 }, { [cv]: [ar, as, W, aq, aD, aE], [cu]: [{ [cv]: cd, endpoint: aP, [ct]: n5 }, { endpoint: aP, [ct]: n5 }], [ct]: o5 }, { [cv]: [ar, as, W, aq, aD, aH], endpoint: aP, [ct]: n5 }, { [cv]: [ar, as, aA, aq, aB], endpoint: { [cA]: E2, [cB]: aC, [cH]: al }, [ct]: n5 }, { [cv]: [ar, as, aA, aq, aD, aE], [cu]: [{ [cv]: cd, endpoint: { [cA]: E2, [cB]: aG, [cH]: al }, [ct]: n5 }, { endpoint: aQ, [ct]: n5 }], [ct]: o5 }, { [cv]: [ar, as, aA, aq, aD, aH], endpoint: aQ, [ct]: n5 }], [ct]: o5 }, aR], [ct]: o5 }], [ct]: o5 }, { [cv]: [Z, ag, { [cw]: h5, [cx]: [{ [cw]: i5, [cx]: [ai, "scheme"] }, "http"] }, { [cw]: p5, [cx]: [ad, c5] }, ay, as, ar, aA], [cu]: [{ [cv]: bG, [cu]: [{ [cv]: cc, [cu]: [aO], [ct]: o5 }, aR], [ct]: o5 }], [ct]: o5 }, { [cv]: [ay, { [cw]: F2, [cx]: bA, [cz]: G2 }], [cu]: [{ [cv]: [{ [cw]: i5, [cx]: [aS, "resourceId[0]"], [cz]: H2 }, { [cw]: r5, [cx]: [{ [cw]: h5, [cx]: [aT, I2] }] }], [cu]: [{ [cv]: [{ [cw]: h5, [cx]: [aU, J2] }], [cu]: [{ [cv]: ce, [cu]: [{ [cv]: cf, [cu]: [aW, aX, { [cv]: ci, [cu]: [aY, { [cv]: cj, [cu]: [aZ, { [cv]: cl, [cu]: [{ [cv]: bG, [cu]: [{ [cv]: cm, [cu]: [{ [cv]: cn, [cu]: [{ [cv]: [{ [cw]: h5, [cx]: [bb, I2] }], error: "Invalid ARN: Missing account id", [ct]: f5 }, { [cv]: co, [cu]: [{ [cv]: cp, [cu]: [{ [cv]: bC, endpoint: { [cA]: M, [cB]: bc, [cH]: al }, [ct]: n5 }, { [cv]: cq, endpoint: { [cA]: "https://{accessPointName}-{bucketArn#accountId}.s3-object-lambda-fips.{bucketArn#region}.{bucketPartition#dnsSuffix}", [cB]: bc, [cH]: al }, [ct]: n5 }, { endpoint: { [cA]: "https://{accessPointName}-{bucketArn#accountId}.s3-object-lambda.{bucketArn#region}.{bucketPartition#dnsSuffix}", [cB]: bc, [cH]: al }, [ct]: n5 }], [ct]: o5 }, bd], [ct]: o5 }, be], [ct]: o5 }, bf], [ct]: o5 }, bg], [ct]: o5 }], [ct]: o5 }], [ct]: o5 }, bh], [ct]: o5 }, { error: "Invalid ARN: bucket ARN is missing a region", [ct]: f5 }], [ct]: o5 }, bi], [ct]: o5 }, { error: "Invalid ARN: Object Lambda ARNs only support `accesspoint` arn types, but found: `{arnType}`", [ct]: f5 }], [ct]: o5 }, { [cv]: ce, [cu]: [{ [cv]: cf, [cu]: [{ [cv]: ci, [cu]: [{ [cv]: ce, [cu]: [{ [cv]: ci, [cu]: [aY, { [cv]: cj, [cu]: [aZ, { [cv]: cl, [cu]: [{ [cv]: bG, [cu]: [{ [cv]: [{ [cw]: h5, [cx]: [ba, "{partitionResult#name}"] }], [cu]: [{ [cv]: cn, [cu]: [{ [cv]: [{ [cw]: h5, [cx]: [aU, B2] }], [cu]: [{ [cv]: co, [cu]: [{ [cv]: cp, [cu]: [{ [cv]: bB, error: "Access Points do not support S3 Accelerate", [ct]: f5 }, { [cv]: bH, endpoint: { [cA]: "https://{accessPointName}-{bucketArn#accountId}.s3-accesspoint-fips.dualstack.{bucketArn#region}.{bucketPartition#dnsSuffix}", [cB]: bj, [cH]: al }, [ct]: n5 }, { [cv]: bI, endpoint: { [cA]: "https://{accessPointName}-{bucketArn#accountId}.s3-accesspoint-fips.{bucketArn#region}.{bucketPartition#dnsSuffix}", [cB]: bj, [cH]: al }, [ct]: n5 }, { [cv]: bJ, endpoint: { [cA]: "https://{accessPointName}-{bucketArn#accountId}.s3-accesspoint.dualstack.{bucketArn#region}.{bucketPartition#dnsSuffix}", [cB]: bj, [cH]: al }, [ct]: n5 }, { [cv]: [as, ar, Z, ag], endpoint: { [cA]: M, [cB]: bj, [cH]: al }, [ct]: n5 }, { [cv]: bK, endpoint: { [cA]: "https://{accessPointName}-{bucketArn#accountId}.s3-accesspoint.{bucketArn#region}.{bucketPartition#dnsSuffix}", [cB]: bj, [cH]: al }, [ct]: n5 }], [ct]: o5 }, bd], [ct]: o5 }, be], [ct]: o5 }, { error: "Invalid ARN: The ARN was not for the S3 service, found: {bucketArn#service}", [ct]: f5 }], [ct]: o5 }, bf], [ct]: o5 }, bg], [ct]: o5 }], [ct]: o5 }], [ct]: o5 }, bh], [ct]: o5 }], [ct]: o5 }], [ct]: o5 }, { [cv]: [{ [cw]: y2, [cx]: [aV, c5] }], [cu]: [{ [cv]: ch, error: "S3 MRAP does not support dual-stack", [ct]: f5 }, { [cv]: cq, error: "S3 MRAP does not support FIPS", [ct]: f5 }, { [cv]: bB, error: "S3 MRAP does not support S3 Accelerate", [ct]: f5 }, { [cv]: [{ [cw]: e5, [cx]: [{ [cy]: "DisableMultiRegionAccessPoints" }, c5] }], error: "Invalid configuration: Multi-Region Access Point ARNs are disabled.", [ct]: f5 }, { [cv]: [{ [cw]: g5, [cx]: by, [cz]: N }], [cu]: [{ [cv]: [{ [cw]: h5, [cx]: [{ [cw]: i5, [cx]: [{ [cy]: N }, j5] }, { [cw]: i5, [cx]: [aS, "partition"] }] }], [cu]: [{ endpoint: { [cA]: "https://{accessPointName}.accesspoint.s3-global.{mrapPartition#dnsSuffix}", [cB]: { [cD]: [{ [cE]: c5, name: z3, [cF]: B2, [cI]: cb }] }, [cH]: al }, [ct]: n5 }], [ct]: o5 }, { error: "Client was configured for partition `{mrapPartition#name}` but bucket referred to partition `{bucketArn#partition}`", [ct]: f5 }], [ct]: o5 }], [ct]: o5 }, { error: "Invalid Access Point Name", [ct]: f5 }], [ct]: o5 }, bi], [ct]: o5 }, { [cv]: [{ [cw]: h5, [cx]: [aU, A2] }], [cu]: [{ [cv]: ch, error: "S3 Outposts does not support Dual-stack", [ct]: f5 }, { [cv]: cq, error: "S3 Outposts does not support FIPS", [ct]: f5 }, { [cv]: bB, error: "S3 Outposts does not support S3 Accelerate", [ct]: f5 }, { [cv]: [{ [cw]: d5, [cx]: [{ [cw]: i5, [cx]: [aS, "resourceId[4]"] }] }], error: "Invalid Arn: Outpost Access Point ARN contains sub resources", [ct]: f5 }, { [cv]: [{ [cw]: i5, [cx]: cg, [cz]: x5 }], [cu]: [{ [cv]: bZ, [cu]: [aZ, { [cv]: cl, [cu]: [{ [cv]: bG, [cu]: [{ [cv]: cm, [cu]: [{ [cv]: cn, [cu]: [{ [cv]: co, [cu]: [{ [cv]: [{ [cw]: i5, [cx]: ck, [cz]: O }], [cu]: [{ [cv]: [{ [cw]: i5, [cx]: [aS, "resourceId[3]"], [cz]: L }], [cu]: [{ [cv]: [{ [cw]: h5, [cx]: [{ [cy]: O }, K] }], [cu]: [{ [cv]: bC, endpoint: { [cA]: "https://{accessPointName}-{bucketArn#accountId}.{outpostId}.{url#authority}", [cB]: bk, [cH]: al }, [ct]: n5 }, { endpoint: { [cA]: "https://{accessPointName}-{bucketArn#accountId}.{outpostId}.s3-outposts.{bucketArn#region}.{bucketPartition#dnsSuffix}", [cB]: bk, [cH]: al }, [ct]: n5 }], [ct]: o5 }, { error: "Expected an outpost type `accesspoint`, found {outpostType}", [ct]: f5 }], [ct]: o5 }, { error: "Invalid ARN: expected an access point name", [ct]: f5 }], [ct]: o5 }, { error: "Invalid ARN: Expected a 4-component resource", [ct]: f5 }], [ct]: o5 }, be], [ct]: o5 }, bf], [ct]: o5 }, bg], [ct]: o5 }], [ct]: o5 }], [ct]: o5 }, { error: "Invalid ARN: The outpost Id may only contain a-z, A-Z, 0-9 and `-`. Found: `{outpostId}`", [ct]: f5 }], [ct]: o5 }, { error: "Invalid ARN: The Outpost Id was not set", [ct]: f5 }], [ct]: o5 }, { error: "Invalid ARN: Unrecognized format: {Bucket} (type: {arnType})", [ct]: f5 }], [ct]: o5 }, { error: "Invalid ARN: No ARN type specified", [ct]: f5 }], [ct]: o5 }, { [cv]: [{ [cw]: k5, [cx]: [ad, 0, 4, b6], [cz]: P }, { [cw]: h5, [cx]: [{ [cy]: P }, "arn:"] }, { [cw]: r5, [cx]: [{ [cw]: d5, [cx]: [bl] }] }], error: "Invalid ARN: `{Bucket}` was not a valid ARN", [ct]: f5 }, { [cv]: [{ [cw]: e5, [cx]: [az, c5] }, bl], error: "Path-style addressing cannot be used with ARN buckets", [ct]: f5 }, { [cv]: bE, [cu]: [{ [cv]: bG, [cu]: [{ [cv]: [aA], [cu]: [{ [cv]: [Y, aq, X, aB], endpoint: { [cA]: "https://s3-fips.dualstack.us-east-1.{partitionResult#dnsSuffix}/{uri_encoded_bucket}", [cB]: aC, [cH]: al }, [ct]: n5 }, { [cv]: [Y, aq, X, aD, aE], [cu]: [{ endpoint: bm, [ct]: n5 }], [ct]: o5 }, { [cv]: [Y, aq, X, aD, aH], endpoint: bm, [ct]: n5 }, { [cv]: [ar, aq, X, aB], endpoint: { [cA]: "https://s3-fips.us-east-1.{partitionResult#dnsSuffix}/{uri_encoded_bucket}", [cB]: aC, [cH]: al }, [ct]: n5 }, { [cv]: [ar, aq, X, aD, aE], [cu]: [{ endpoint: bn, [ct]: n5 }], [ct]: o5 }, { [cv]: [ar, aq, X, aD, aH], endpoint: bn, [ct]: n5 }, { [cv]: [Y, aq, as, aB], endpoint: { [cA]: "https://s3.dualstack.us-east-1.{partitionResult#dnsSuffix}/{uri_encoded_bucket}", [cB]: aC, [cH]: al }, [ct]: n5 }, { [cv]: [Y, aq, as, aD, aE], [cu]: [{ endpoint: bo, [ct]: n5 }], [ct]: o5 }, { [cv]: [Y, aq, as, aD, aH], endpoint: bo, [ct]: n5 }, { [cv]: [ar, Z, ag, as, aB], endpoint: { [cA]: Q, [cB]: aC, [cH]: al }, [ct]: n5 }, { [cv]: [ar, Z, ag, as, aD, aE], [cu]: [{ [cv]: cd, endpoint: bp, [ct]: n5 }, { endpoint: bp, [ct]: n5 }], [ct]: o5 }, { [cv]: [ar, Z, ag, as, aD, aH], endpoint: bp, [ct]: n5 }, { [cv]: [ar, aq, as, aB], endpoint: { [cA]: R, [cB]: aC, [cH]: al }, [ct]: n5 }, { [cv]: [ar, aq, as, aD, aE], [cu]: [{ [cv]: cd, endpoint: { [cA]: R, [cB]: aG, [cH]: al }, [ct]: n5 }, { endpoint: bq, [ct]: n5 }], [ct]: o5 }, { [cv]: [ar, aq, as, aD, aH], endpoint: bq, [ct]: n5 }], [ct]: o5 }, { error: "Path-style addressing cannot be used with S3 Accelerate", [ct]: f5 }], [ct]: o5 }], [ct]: o5 }], [ct]: o5 }, { [cv]: [{ [cw]: d5, [cx]: [br] }, { [cw]: e5, [cx]: [br, c5] }], [cu]: [{ [cv]: bG, [cu]: [{ [cv]: cr, [cu]: [aW, aX, { [cv]: bC, endpoint: { [cA]: t5, [cB]: bs, [cH]: al }, [ct]: n5 }, { [cv]: cq, endpoint: { [cA]: "https://s3-object-lambda-fips.{Region}.{partitionResult#dnsSuffix}", [cB]: bs, [cH]: al }, [ct]: n5 }, { endpoint: { [cA]: "https://s3-object-lambda.{Region}.{partitionResult#dnsSuffix}", [cB]: bs, [cH]: al }, [ct]: n5 }], [ct]: o5 }, aR], [ct]: o5 }], [ct]: o5 }, { [cv]: [au], [cu]: [{ [cv]: bG, [cu]: [{ [cv]: cr, [cu]: [{ [cv]: [X, Y, aq, aB], endpoint: { [cA]: "https://s3-fips.dualstack.us-east-1.{partitionResult#dnsSuffix}", [cB]: aC, [cH]: al }, [ct]: n5 }, { [cv]: [X, Y, aq, aD, aE], [cu]: [{ endpoint: bt, [ct]: n5 }], [ct]: o5 }, { [cv]: [X, Y, aq, aD, aH], endpoint: bt, [ct]: n5 }, { [cv]: [X, ar, aq, aB], endpoint: { [cA]: "https://s3-fips.us-east-1.{partitionResult#dnsSuffix}", [cB]: aC, [cH]: al }, [ct]: n5 }, { [cv]: [X, ar, aq, aD, aE], [cu]: [{ endpoint: bu, [ct]: n5 }], [ct]: o5 }, { [cv]: [X, ar, aq, aD, aH], endpoint: bu, [ct]: n5 }, { [cv]: [as, Y, aq, aB], endpoint: { [cA]: "https://s3.dualstack.us-east-1.{partitionResult#dnsSuffix}", [cB]: aC, [cH]: al }, [ct]: n5 }, { [cv]: [as, Y, aq, aD, aE], [cu]: [{ endpoint: bv, [ct]: n5 }], [ct]: o5 }, { [cv]: [as, Y, aq, aD, aH], endpoint: bv, [ct]: n5 }, { [cv]: [as, ar, Z, ag, aB], endpoint: { [cA]: t5, [cB]: aC, [cH]: al }, [ct]: n5 }, { [cv]: [as, ar, Z, ag, aD, aE], [cu]: [{ [cv]: cd, endpoint: bw, [ct]: n5 }, { endpoint: bw, [ct]: n5 }], [ct]: o5 }, { [cv]: [as, ar, Z, ag, aD, aH], endpoint: bw, [ct]: n5 }, { [cv]: [as, ar, aq, aB], endpoint: { [cA]: S, [cB]: aC, [cH]: al }, [ct]: n5 }, { [cv]: [as, ar, aq, aD, aE], [cu]: [{ [cv]: cd, endpoint: { [cA]: S, [cB]: aG, [cH]: al }, [ct]: n5 }, { endpoint: bx, [ct]: n5 }], [ct]: o5 }, { [cv]: [as, ar, aq, aD, aH], endpoint: bx, [ct]: n5 }], [ct]: o5 }, aR], [ct]: o5 }], [ct]: o5 }], [ct]: o5 }, { error: "A region must be set when sending requests to S3.", [ct]: f5 }] }; + exports.ruleSet = _data5; + } +}); + +// node_modules/.pnpm/@aws-sdk+client-s3@3.1030.0/node_modules/@aws-sdk/client-s3/dist-cjs/endpoint/endpointResolver.js +var require_endpointResolver = __commonJS({ + "node_modules/.pnpm/@aws-sdk+client-s3@3.1030.0/node_modules/@aws-sdk/client-s3/dist-cjs/endpoint/endpointResolver.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.defaultEndpointResolver = void 0; + var util_endpoints_1 = require_dist_cjs34(); + var util_endpoints_2 = require_dist_cjs33(); + var ruleset_1 = require_ruleset(); + var cache7 = new util_endpoints_2.EndpointCache({ + size: 50, + params: [ + "Accelerate", + "Bucket", + "DisableAccessPoints", + "DisableMultiRegionAccessPoints", + "DisableS3ExpressSessionAuth", + "Endpoint", + "ForcePathStyle", + "Region", + "UseArnRegion", + "UseDualStack", + "UseFIPS", + "UseGlobalEndpoint", + "UseObjectLambdaEndpoint", + "UseS3ExpressControlEndpoint" + ] + }); + var defaultEndpointResolver5 = (endpointParams, context = {}) => { + return cache7.get(endpointParams, () => (0, util_endpoints_2.resolveEndpoint)(ruleset_1.ruleSet, { + endpointParams, + logger: context.logger + })); + }; + exports.defaultEndpointResolver = defaultEndpointResolver5; + util_endpoints_2.customEndpointFunctions.aws = util_endpoints_1.awsEndpointFunctions; + } +}); + +// node_modules/.pnpm/@aws-sdk+client-s3@3.1030.0/node_modules/@aws-sdk/client-s3/dist-cjs/auth/httpAuthSchemeProvider.js +var require_httpAuthSchemeProvider = __commonJS({ + "node_modules/.pnpm/@aws-sdk+client-s3@3.1030.0/node_modules/@aws-sdk/client-s3/dist-cjs/auth/httpAuthSchemeProvider.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.resolveHttpAuthSchemeConfig = exports.defaultS3HttpAuthSchemeProvider = exports.defaultS3HttpAuthSchemeParametersProvider = void 0; + var httpAuthSchemes_1 = (init_httpAuthSchemes2(), __toCommonJS(httpAuthSchemes_exports)); + var signature_v4_multi_region_1 = require_dist_cjs47(); + var middleware_endpoint_1 = require_dist_cjs45(); + var util_middleware_1 = require_dist_cjs18(); + var endpointResolver_1 = require_endpointResolver(); + var createEndpointRuleSetHttpAuthSchemeParametersProvider = (defaultHttpAuthSchemeParametersProvider) => async (config3, context, input) => { + if (!input) { + throw new Error("Could not find `input` for `defaultEndpointRuleSetHttpAuthSchemeParametersProvider`"); + } + const defaultParameters = await defaultHttpAuthSchemeParametersProvider(config3, context, input); + const instructionsFn = (0, util_middleware_1.getSmithyContext)(context)?.commandInstance?.constructor?.getEndpointParameterInstructions; + if (!instructionsFn) { + throw new Error(`getEndpointParameterInstructions() is not defined on '${context.commandName}'`); + } + const endpointParameters = await (0, middleware_endpoint_1.resolveParams)(input, { getEndpointParameterInstructions: instructionsFn }, config3); + return Object.assign(defaultParameters, endpointParameters); + }; + var _defaultS3HttpAuthSchemeParametersProvider = async (config3, context, input) => { + return { + operation: (0, util_middleware_1.getSmithyContext)(context).operation, + region: await (0, util_middleware_1.normalizeProvider)(config3.region)() || (() => { + throw new Error("expected `region` to be configured for `aws.auth#sigv4`"); + })() + }; + }; + exports.defaultS3HttpAuthSchemeParametersProvider = createEndpointRuleSetHttpAuthSchemeParametersProvider(_defaultS3HttpAuthSchemeParametersProvider); + function createAwsAuthSigv4HttpAuthOption5(authParameters) { + return { + schemeId: "aws.auth#sigv4", + signingProperties: { + name: "s3", + region: authParameters.region + }, + propertiesExtractor: (config3, context) => ({ + signingProperties: { + config: config3, + context + } + }) + }; + } + function createAwsAuthSigv4aHttpAuthOption(authParameters) { + return { + schemeId: "aws.auth#sigv4a", + signingProperties: { + name: "s3", + region: authParameters.region + }, + propertiesExtractor: (config3, context) => ({ + signingProperties: { + config: config3, + context + } + }) + }; + } + var createEndpointRuleSetHttpAuthSchemeProvider = (defaultEndpointResolver5, defaultHttpAuthSchemeResolver, createHttpAuthOptionFunctions) => { + const endpointRuleSetHttpAuthSchemeProvider = (authParameters) => { + const endpoint = defaultEndpointResolver5(authParameters); + const authSchemes = endpoint.properties?.authSchemes; + if (!authSchemes) { + return defaultHttpAuthSchemeResolver(authParameters); + } + const options = []; + for (const scheme of authSchemes) { + const { name: resolvedName, properties = {}, ...rest } = scheme; + const name = resolvedName.toLowerCase(); + if (resolvedName !== name) { + console.warn(`HttpAuthScheme has been normalized with lowercasing: '${resolvedName}' to '${name}'`); + } + let schemeId; + if (name === "sigv4a") { + schemeId = "aws.auth#sigv4a"; + const sigv4Present = authSchemes.find((s5) => { + const name2 = s5.name.toLowerCase(); + return name2 !== "sigv4a" && name2.startsWith("sigv4"); + }); + if (signature_v4_multi_region_1.SignatureV4MultiRegion.sigv4aDependency() === "none" && sigv4Present) { + continue; + } + } else if (name.startsWith("sigv4")) { + schemeId = "aws.auth#sigv4"; + } else { + throw new Error(`Unknown HttpAuthScheme found in '@smithy.rules#endpointRuleSet': '${name}'`); + } + const createOption = createHttpAuthOptionFunctions[schemeId]; + if (!createOption) { + throw new Error(`Could not find HttpAuthOption create function for '${schemeId}'`); + } + const option = createOption(authParameters); + option.schemeId = schemeId; + option.signingProperties = { ...option.signingProperties || {}, ...rest, ...properties }; + options.push(option); + } + return options; + }; + return endpointRuleSetHttpAuthSchemeProvider; + }; + var _defaultS3HttpAuthSchemeProvider = (authParameters) => { + const options = []; + switch (authParameters.operation) { + default: { + options.push(createAwsAuthSigv4HttpAuthOption5(authParameters)); + options.push(createAwsAuthSigv4aHttpAuthOption(authParameters)); + } + } + return options; + }; + exports.defaultS3HttpAuthSchemeProvider = createEndpointRuleSetHttpAuthSchemeProvider(endpointResolver_1.defaultEndpointResolver, _defaultS3HttpAuthSchemeProvider, { + "aws.auth#sigv4": createAwsAuthSigv4HttpAuthOption5, + "aws.auth#sigv4a": createAwsAuthSigv4aHttpAuthOption + }); + var resolveHttpAuthSchemeConfig5 = (config3) => { + const config_0 = (0, httpAuthSchemes_1.resolveAwsSdkSigV4Config)(config3); + const config_1 = (0, httpAuthSchemes_1.resolveAwsSdkSigV4AConfig)(config_0); + return Object.assign(config_1, { + authSchemePreference: (0, util_middleware_1.normalizeProvider)(config3.authSchemePreference ?? []) + }); + }; + exports.resolveHttpAuthSchemeConfig = resolveHttpAuthSchemeConfig5; + } +}); + +// node_modules/.pnpm/@aws-sdk+client-s3@3.1030.0/node_modules/@aws-sdk/client-s3/dist-cjs/models/S3ServiceException.js +var require_S3ServiceException = __commonJS({ + "node_modules/.pnpm/@aws-sdk+client-s3@3.1030.0/node_modules/@aws-sdk/client-s3/dist-cjs/models/S3ServiceException.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.S3ServiceException = exports.__ServiceException = void 0; + var smithy_client_1 = require_dist_cjs27(); + Object.defineProperty(exports, "__ServiceException", { enumerable: true, get: function() { + return smithy_client_1.ServiceException; + } }); + var S3ServiceException = class _S3ServiceException extends smithy_client_1.ServiceException { + constructor(options) { + super(options); + Object.setPrototypeOf(this, _S3ServiceException.prototype); + } + }; + exports.S3ServiceException = S3ServiceException; + } +}); + +// node_modules/.pnpm/@aws-sdk+client-s3@3.1030.0/node_modules/@aws-sdk/client-s3/dist-cjs/models/errors.js +var require_errors = __commonJS({ + "node_modules/.pnpm/@aws-sdk+client-s3@3.1030.0/node_modules/@aws-sdk/client-s3/dist-cjs/models/errors.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ObjectAlreadyInActiveTierError = exports.IdempotencyParameterMismatch = exports.TooManyParts = exports.InvalidWriteOffset = exports.InvalidRequest = exports.EncryptionTypeMismatch = exports.NotFound = exports.NoSuchKey = exports.InvalidObjectState = exports.NoSuchBucket = exports.BucketAlreadyOwnedByYou = exports.BucketAlreadyExists = exports.ObjectNotInActiveTierError = exports.AccessDenied = exports.NoSuchUpload = void 0; + var S3ServiceException_1 = require_S3ServiceException(); + var NoSuchUpload = class _NoSuchUpload extends S3ServiceException_1.S3ServiceException { + name = "NoSuchUpload"; + $fault = "client"; + constructor(opts) { + super({ + name: "NoSuchUpload", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _NoSuchUpload.prototype); + } + }; + exports.NoSuchUpload = NoSuchUpload; + var AccessDenied = class _AccessDenied extends S3ServiceException_1.S3ServiceException { + name = "AccessDenied"; + $fault = "client"; + constructor(opts) { + super({ + name: "AccessDenied", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _AccessDenied.prototype); + } + }; + exports.AccessDenied = AccessDenied; + var ObjectNotInActiveTierError = class _ObjectNotInActiveTierError extends S3ServiceException_1.S3ServiceException { + name = "ObjectNotInActiveTierError"; + $fault = "client"; + constructor(opts) { + super({ + name: "ObjectNotInActiveTierError", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _ObjectNotInActiveTierError.prototype); + } + }; + exports.ObjectNotInActiveTierError = ObjectNotInActiveTierError; + var BucketAlreadyExists = class _BucketAlreadyExists extends S3ServiceException_1.S3ServiceException { + name = "BucketAlreadyExists"; + $fault = "client"; + constructor(opts) { + super({ + name: "BucketAlreadyExists", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _BucketAlreadyExists.prototype); + } + }; + exports.BucketAlreadyExists = BucketAlreadyExists; + var BucketAlreadyOwnedByYou = class _BucketAlreadyOwnedByYou extends S3ServiceException_1.S3ServiceException { + name = "BucketAlreadyOwnedByYou"; + $fault = "client"; + constructor(opts) { + super({ + name: "BucketAlreadyOwnedByYou", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _BucketAlreadyOwnedByYou.prototype); + } + }; + exports.BucketAlreadyOwnedByYou = BucketAlreadyOwnedByYou; + var NoSuchBucket = class _NoSuchBucket extends S3ServiceException_1.S3ServiceException { + name = "NoSuchBucket"; + $fault = "client"; + constructor(opts) { + super({ + name: "NoSuchBucket", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _NoSuchBucket.prototype); + } + }; + exports.NoSuchBucket = NoSuchBucket; + var InvalidObjectState = class _InvalidObjectState extends S3ServiceException_1.S3ServiceException { + name = "InvalidObjectState"; + $fault = "client"; + StorageClass; + AccessTier; + constructor(opts) { + super({ + name: "InvalidObjectState", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _InvalidObjectState.prototype); + this.StorageClass = opts.StorageClass; + this.AccessTier = opts.AccessTier; + } + }; + exports.InvalidObjectState = InvalidObjectState; + var NoSuchKey = class _NoSuchKey extends S3ServiceException_1.S3ServiceException { + name = "NoSuchKey"; + $fault = "client"; + constructor(opts) { + super({ + name: "NoSuchKey", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _NoSuchKey.prototype); + } + }; + exports.NoSuchKey = NoSuchKey; + var NotFound = class _NotFound extends S3ServiceException_1.S3ServiceException { + name = "NotFound"; + $fault = "client"; + constructor(opts) { + super({ + name: "NotFound", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _NotFound.prototype); + } + }; + exports.NotFound = NotFound; + var EncryptionTypeMismatch = class _EncryptionTypeMismatch extends S3ServiceException_1.S3ServiceException { + name = "EncryptionTypeMismatch"; + $fault = "client"; + constructor(opts) { + super({ + name: "EncryptionTypeMismatch", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _EncryptionTypeMismatch.prototype); + } + }; + exports.EncryptionTypeMismatch = EncryptionTypeMismatch; + var InvalidRequest = class _InvalidRequest extends S3ServiceException_1.S3ServiceException { + name = "InvalidRequest"; + $fault = "client"; + constructor(opts) { + super({ + name: "InvalidRequest", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _InvalidRequest.prototype); + } + }; + exports.InvalidRequest = InvalidRequest; + var InvalidWriteOffset = class _InvalidWriteOffset extends S3ServiceException_1.S3ServiceException { + name = "InvalidWriteOffset"; + $fault = "client"; + constructor(opts) { + super({ + name: "InvalidWriteOffset", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _InvalidWriteOffset.prototype); + } + }; + exports.InvalidWriteOffset = InvalidWriteOffset; + var TooManyParts = class _TooManyParts extends S3ServiceException_1.S3ServiceException { + name = "TooManyParts"; + $fault = "client"; + constructor(opts) { + super({ + name: "TooManyParts", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _TooManyParts.prototype); + } + }; + exports.TooManyParts = TooManyParts; + var IdempotencyParameterMismatch = class _IdempotencyParameterMismatch extends S3ServiceException_1.S3ServiceException { + name = "IdempotencyParameterMismatch"; + $fault = "client"; + constructor(opts) { + super({ + name: "IdempotencyParameterMismatch", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _IdempotencyParameterMismatch.prototype); + } + }; + exports.IdempotencyParameterMismatch = IdempotencyParameterMismatch; + var ObjectAlreadyInActiveTierError = class _ObjectAlreadyInActiveTierError extends S3ServiceException_1.S3ServiceException { + name = "ObjectAlreadyInActiveTierError"; + $fault = "client"; + constructor(opts) { + super({ + name: "ObjectAlreadyInActiveTierError", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _ObjectAlreadyInActiveTierError.prototype); + } + }; + exports.ObjectAlreadyInActiveTierError = ObjectAlreadyInActiveTierError; + } +}); + +// node_modules/.pnpm/@aws-sdk+client-s3@3.1030.0/node_modules/@aws-sdk/client-s3/dist-cjs/schemas/schemas_0.js +var require_schemas_0 = __commonJS({ + "node_modules/.pnpm/@aws-sdk+client-s3@3.1030.0/node_modules/@aws-sdk/client-s3/dist-cjs/schemas/schemas_0.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.CreateBucketMetadataTableConfigurationRequest$ = exports.CreateBucketMetadataConfigurationRequest$ = exports.CreateBucketConfiguration$ = exports.CORSRule$ = exports.CORSConfiguration$ = exports.CopyPartResult$ = exports.CopyObjectResult$ = exports.CopyObjectRequest$ = exports.CopyObjectOutput$ = exports.ContinuationEvent$ = exports.Condition$ = exports.CompleteMultipartUploadRequest$ = exports.CompleteMultipartUploadOutput$ = exports.CompletedPart$ = exports.CompletedMultipartUpload$ = exports.CommonPrefix$ = exports.Checksum$ = exports.BucketLoggingStatus$ = exports.BucketLifecycleConfiguration$ = exports.BucketInfo$ = exports.Bucket$ = exports.BlockedEncryptionTypes$ = exports.AnalyticsS3BucketDestination$ = exports.AnalyticsExportDestination$ = exports.AnalyticsConfiguration$ = exports.AnalyticsAndOperator$ = exports.AccessControlTranslation$ = exports.AccessControlPolicy$ = exports.AccelerateConfiguration$ = exports.AbortMultipartUploadRequest$ = exports.AbortMultipartUploadOutput$ = exports.AbortIncompleteMultipartUpload$ = exports.AbacStatus$ = exports.errorTypeRegistries = exports.TooManyParts$ = exports.ObjectNotInActiveTierError$ = exports.ObjectAlreadyInActiveTierError$ = exports.NotFound$ = exports.NoSuchUpload$ = exports.NoSuchKey$ = exports.NoSuchBucket$ = exports.InvalidWriteOffset$ = exports.InvalidRequest$ = exports.InvalidObjectState$ = exports.IdempotencyParameterMismatch$ = exports.EncryptionTypeMismatch$ = exports.BucketAlreadyOwnedByYou$ = exports.BucketAlreadyExists$ = exports.AccessDenied$ = exports.S3ServiceException$ = void 0; + exports.GetBucketAccelerateConfigurationRequest$ = exports.GetBucketAccelerateConfigurationOutput$ = exports.GetBucketAbacRequest$ = exports.GetBucketAbacOutput$ = exports.FilterRule$ = exports.ExistingObjectReplication$ = exports.EventBridgeConfiguration$ = exports.ErrorDocument$ = exports.ErrorDetails$ = exports._Error$ = exports.EndEvent$ = exports.EncryptionConfiguration$ = exports.Encryption$ = exports.DestinationResult$ = exports.Destination$ = exports.DeletePublicAccessBlockRequest$ = exports.DeleteObjectTaggingRequest$ = exports.DeleteObjectTaggingOutput$ = exports.DeleteObjectsRequest$ = exports.DeleteObjectsOutput$ = exports.DeleteObjectRequest$ = exports.DeleteObjectOutput$ = exports.DeleteMarkerReplication$ = exports.DeleteMarkerEntry$ = exports.DeletedObject$ = exports.DeleteBucketWebsiteRequest$ = exports.DeleteBucketTaggingRequest$ = exports.DeleteBucketRequest$ = exports.DeleteBucketReplicationRequest$ = exports.DeleteBucketPolicyRequest$ = exports.DeleteBucketOwnershipControlsRequest$ = exports.DeleteBucketMetricsConfigurationRequest$ = exports.DeleteBucketMetadataTableConfigurationRequest$ = exports.DeleteBucketMetadataConfigurationRequest$ = exports.DeleteBucketLifecycleRequest$ = exports.DeleteBucketInventoryConfigurationRequest$ = exports.DeleteBucketIntelligentTieringConfigurationRequest$ = exports.DeleteBucketEncryptionRequest$ = exports.DeleteBucketCorsRequest$ = exports.DeleteBucketAnalyticsConfigurationRequest$ = exports.Delete$ = exports.DefaultRetention$ = exports.CSVOutput$ = exports.CSVInput$ = exports.CreateSessionRequest$ = exports.CreateSessionOutput$ = exports.CreateMultipartUploadRequest$ = exports.CreateMultipartUploadOutput$ = exports.CreateBucketRequest$ = exports.CreateBucketOutput$ = void 0; + exports.GetObjectLegalHoldRequest$ = exports.GetObjectLegalHoldOutput$ = exports.GetObjectAttributesRequest$ = exports.GetObjectAttributesParts$ = exports.GetObjectAttributesOutput$ = exports.GetObjectAclRequest$ = exports.GetObjectAclOutput$ = exports.GetBucketWebsiteRequest$ = exports.GetBucketWebsiteOutput$ = exports.GetBucketVersioningRequest$ = exports.GetBucketVersioningOutput$ = exports.GetBucketTaggingRequest$ = exports.GetBucketTaggingOutput$ = exports.GetBucketRequestPaymentRequest$ = exports.GetBucketRequestPaymentOutput$ = exports.GetBucketReplicationRequest$ = exports.GetBucketReplicationOutput$ = exports.GetBucketPolicyStatusRequest$ = exports.GetBucketPolicyStatusOutput$ = exports.GetBucketPolicyRequest$ = exports.GetBucketPolicyOutput$ = exports.GetBucketOwnershipControlsRequest$ = exports.GetBucketOwnershipControlsOutput$ = exports.GetBucketNotificationConfigurationRequest$ = exports.GetBucketMetricsConfigurationRequest$ = exports.GetBucketMetricsConfigurationOutput$ = exports.GetBucketMetadataTableConfigurationResult$ = exports.GetBucketMetadataTableConfigurationRequest$ = exports.GetBucketMetadataTableConfigurationOutput$ = exports.GetBucketMetadataConfigurationResult$ = exports.GetBucketMetadataConfigurationRequest$ = exports.GetBucketMetadataConfigurationOutput$ = exports.GetBucketLoggingRequest$ = exports.GetBucketLoggingOutput$ = exports.GetBucketLocationRequest$ = exports.GetBucketLocationOutput$ = exports.GetBucketLifecycleConfigurationRequest$ = exports.GetBucketLifecycleConfigurationOutput$ = exports.GetBucketInventoryConfigurationRequest$ = exports.GetBucketInventoryConfigurationOutput$ = exports.GetBucketIntelligentTieringConfigurationRequest$ = exports.GetBucketIntelligentTieringConfigurationOutput$ = exports.GetBucketEncryptionRequest$ = exports.GetBucketEncryptionOutput$ = exports.GetBucketCorsRequest$ = exports.GetBucketCorsOutput$ = exports.GetBucketAnalyticsConfigurationRequest$ = exports.GetBucketAnalyticsConfigurationOutput$ = exports.GetBucketAclRequest$ = exports.GetBucketAclOutput$ = void 0; + exports.ListBucketInventoryConfigurationsRequest$ = exports.ListBucketInventoryConfigurationsOutput$ = exports.ListBucketIntelligentTieringConfigurationsRequest$ = exports.ListBucketIntelligentTieringConfigurationsOutput$ = exports.ListBucketAnalyticsConfigurationsRequest$ = exports.ListBucketAnalyticsConfigurationsOutput$ = exports.LifecycleRuleFilter$ = exports.LifecycleRuleAndOperator$ = exports.LifecycleRule$ = exports.LifecycleExpiration$ = exports.LambdaFunctionConfiguration$ = exports.JSONOutput$ = exports.JSONInput$ = exports.JournalTableConfigurationUpdates$ = exports.JournalTableConfigurationResult$ = exports.JournalTableConfiguration$ = exports.InventoryTableConfigurationUpdates$ = exports.InventoryTableConfigurationResult$ = exports.InventoryTableConfiguration$ = exports.InventorySchedule$ = exports.InventoryS3BucketDestination$ = exports.InventoryFilter$ = exports.InventoryEncryption$ = exports.InventoryDestination$ = exports.InventoryConfiguration$ = exports.IntelligentTieringFilter$ = exports.IntelligentTieringConfiguration$ = exports.IntelligentTieringAndOperator$ = exports.InputSerialization$ = exports.Initiator$ = exports.IndexDocument$ = exports.HeadObjectRequest$ = exports.HeadObjectOutput$ = exports.HeadBucketRequest$ = exports.HeadBucketOutput$ = exports.Grantee$ = exports.Grant$ = exports.GlacierJobParameters$ = exports.GetPublicAccessBlockRequest$ = exports.GetPublicAccessBlockOutput$ = exports.GetObjectTorrentRequest$ = exports.GetObjectTorrentOutput$ = exports.GetObjectTaggingRequest$ = exports.GetObjectTaggingOutput$ = exports.GetObjectRetentionRequest$ = exports.GetObjectRetentionOutput$ = exports.GetObjectRequest$ = exports.GetObjectOutput$ = exports.GetObjectLockConfigurationRequest$ = exports.GetObjectLockConfigurationOutput$ = void 0; + exports.Progress$ = exports.PolicyStatus$ = exports.PartitionedPrefix$ = exports.Part$ = exports.ParquetInput$ = exports.OwnershipControlsRule$ = exports.OwnershipControls$ = exports.Owner$ = exports.OutputSerialization$ = exports.OutputLocation$ = exports.ObjectVersion$ = exports.ObjectPart$ = exports.ObjectLockRule$ = exports.ObjectLockRetention$ = exports.ObjectLockLegalHold$ = exports.ObjectLockConfiguration$ = exports.ObjectIdentifier$ = exports._Object$ = exports.NotificationConfigurationFilter$ = exports.NotificationConfiguration$ = exports.NoncurrentVersionTransition$ = exports.NoncurrentVersionExpiration$ = exports.MultipartUpload$ = exports.MetricsConfiguration$ = exports.MetricsAndOperator$ = exports.Metrics$ = exports.MetadataTableEncryptionConfiguration$ = exports.MetadataTableConfigurationResult$ = exports.MetadataTableConfiguration$ = exports.MetadataEntry$ = exports.MetadataConfigurationResult$ = exports.MetadataConfiguration$ = exports.LoggingEnabled$ = exports.LocationInfo$ = exports.ListPartsRequest$ = exports.ListPartsOutput$ = exports.ListObjectVersionsRequest$ = exports.ListObjectVersionsOutput$ = exports.ListObjectsV2Request$ = exports.ListObjectsV2Output$ = exports.ListObjectsRequest$ = exports.ListObjectsOutput$ = exports.ListMultipartUploadsRequest$ = exports.ListMultipartUploadsOutput$ = exports.ListDirectoryBucketsRequest$ = exports.ListDirectoryBucketsOutput$ = exports.ListBucketsRequest$ = exports.ListBucketsOutput$ = exports.ListBucketMetricsConfigurationsRequest$ = exports.ListBucketMetricsConfigurationsOutput$ = void 0; + exports.RequestPaymentConfiguration$ = exports.ReplicationTimeValue$ = exports.ReplicationTime$ = exports.ReplicationRuleFilter$ = exports.ReplicationRuleAndOperator$ = exports.ReplicationRule$ = exports.ReplicationConfiguration$ = exports.ReplicaModifications$ = exports.RenameObjectRequest$ = exports.RenameObjectOutput$ = exports.RedirectAllRequestsTo$ = exports.Redirect$ = exports.RecordsEvent$ = exports.RecordExpiration$ = exports.QueueConfiguration$ = exports.PutPublicAccessBlockRequest$ = exports.PutObjectTaggingRequest$ = exports.PutObjectTaggingOutput$ = exports.PutObjectRetentionRequest$ = exports.PutObjectRetentionOutput$ = exports.PutObjectRequest$ = exports.PutObjectOutput$ = exports.PutObjectLockConfigurationRequest$ = exports.PutObjectLockConfigurationOutput$ = exports.PutObjectLegalHoldRequest$ = exports.PutObjectLegalHoldOutput$ = exports.PutObjectAclRequest$ = exports.PutObjectAclOutput$ = exports.PutBucketWebsiteRequest$ = exports.PutBucketVersioningRequest$ = exports.PutBucketTaggingRequest$ = exports.PutBucketRequestPaymentRequest$ = exports.PutBucketReplicationRequest$ = exports.PutBucketPolicyRequest$ = exports.PutBucketOwnershipControlsRequest$ = exports.PutBucketNotificationConfigurationRequest$ = exports.PutBucketMetricsConfigurationRequest$ = exports.PutBucketLoggingRequest$ = exports.PutBucketLifecycleConfigurationRequest$ = exports.PutBucketLifecycleConfigurationOutput$ = exports.PutBucketInventoryConfigurationRequest$ = exports.PutBucketIntelligentTieringConfigurationRequest$ = exports.PutBucketEncryptionRequest$ = exports.PutBucketCorsRequest$ = exports.PutBucketAnalyticsConfigurationRequest$ = exports.PutBucketAclRequest$ = exports.PutBucketAccelerateConfigurationRequest$ = exports.PutBucketAbacRequest$ = exports.PublicAccessBlockConfiguration$ = exports.ProgressEvent$ = void 0; + exports.SelectObjectContentEventStream$ = exports.ObjectEncryption$ = exports.MetricsFilter$ = exports.AnalyticsFilter$ = exports.WriteGetObjectResponseRequest$ = exports.WebsiteConfiguration$ = exports.VersioningConfiguration$ = exports.UploadPartRequest$ = exports.UploadPartOutput$ = exports.UploadPartCopyRequest$ = exports.UploadPartCopyOutput$ = exports.UpdateObjectEncryptionResponse$ = exports.UpdateObjectEncryptionRequest$ = exports.UpdateBucketMetadataJournalTableConfigurationRequest$ = exports.UpdateBucketMetadataInventoryTableConfigurationRequest$ = exports.Transition$ = exports.TopicConfiguration$ = exports.Tiering$ = exports.TargetObjectKeyFormat$ = exports.TargetGrant$ = exports.Tagging$ = exports.Tag$ = exports.StorageClassAnalysisDataExport$ = exports.StorageClassAnalysis$ = exports.StatsEvent$ = exports.Stats$ = exports.SSES3$ = exports.SSEKMSEncryption$ = exports.SseKmsEncryptedObjects$ = exports.SSEKMS$ = exports.SourceSelectionCriteria$ = exports.SimplePrefix$ = exports.SessionCredentials$ = exports.ServerSideEncryptionRule$ = exports.ServerSideEncryptionConfiguration$ = exports.ServerSideEncryptionByDefault$ = exports.SelectParameters$ = exports.SelectObjectContentRequest$ = exports.SelectObjectContentOutput$ = exports.ScanRange$ = exports.S3TablesDestinationResult$ = exports.S3TablesDestination$ = exports.S3Location$ = exports.S3KeyFilter$ = exports.RoutingRule$ = exports.RestoreStatus$ = exports.RestoreRequest$ = exports.RestoreObjectRequest$ = exports.RestoreObjectOutput$ = exports.RequestProgress$ = void 0; + exports.GetBucketWebsite$ = exports.GetBucketVersioning$ = exports.GetBucketTagging$ = exports.GetBucketRequestPayment$ = exports.GetBucketReplication$ = exports.GetBucketPolicyStatus$ = exports.GetBucketPolicy$ = exports.GetBucketOwnershipControls$ = exports.GetBucketNotificationConfiguration$ = exports.GetBucketMetricsConfiguration$ = exports.GetBucketMetadataTableConfiguration$ = exports.GetBucketMetadataConfiguration$ = exports.GetBucketLogging$ = exports.GetBucketLocation$ = exports.GetBucketLifecycleConfiguration$ = exports.GetBucketInventoryConfiguration$ = exports.GetBucketIntelligentTieringConfiguration$ = exports.GetBucketEncryption$ = exports.GetBucketCors$ = exports.GetBucketAnalyticsConfiguration$ = exports.GetBucketAcl$ = exports.GetBucketAccelerateConfiguration$ = exports.GetBucketAbac$ = exports.DeletePublicAccessBlock$ = exports.DeleteObjectTagging$ = exports.DeleteObjects$ = exports.DeleteObject$ = exports.DeleteBucketWebsite$ = exports.DeleteBucketTagging$ = exports.DeleteBucketReplication$ = exports.DeleteBucketPolicy$ = exports.DeleteBucketOwnershipControls$ = exports.DeleteBucketMetricsConfiguration$ = exports.DeleteBucketMetadataTableConfiguration$ = exports.DeleteBucketMetadataConfiguration$ = exports.DeleteBucketLifecycle$ = exports.DeleteBucketInventoryConfiguration$ = exports.DeleteBucketIntelligentTieringConfiguration$ = exports.DeleteBucketEncryption$ = exports.DeleteBucketCors$ = exports.DeleteBucketAnalyticsConfiguration$ = exports.DeleteBucket$ = exports.CreateSession$ = exports.CreateMultipartUpload$ = exports.CreateBucketMetadataTableConfiguration$ = exports.CreateBucketMetadataConfiguration$ = exports.CreateBucket$ = exports.CopyObject$ = exports.CompleteMultipartUpload$ = exports.AbortMultipartUpload$ = void 0; + exports.RestoreObject$ = exports.RenameObject$ = exports.PutPublicAccessBlock$ = exports.PutObjectTagging$ = exports.PutObjectRetention$ = exports.PutObjectLockConfiguration$ = exports.PutObjectLegalHold$ = exports.PutObjectAcl$ = exports.PutObject$ = exports.PutBucketWebsite$ = exports.PutBucketVersioning$ = exports.PutBucketTagging$ = exports.PutBucketRequestPayment$ = exports.PutBucketReplication$ = exports.PutBucketPolicy$ = exports.PutBucketOwnershipControls$ = exports.PutBucketNotificationConfiguration$ = exports.PutBucketMetricsConfiguration$ = exports.PutBucketLogging$ = exports.PutBucketLifecycleConfiguration$ = exports.PutBucketInventoryConfiguration$ = exports.PutBucketIntelligentTieringConfiguration$ = exports.PutBucketEncryption$ = exports.PutBucketCors$ = exports.PutBucketAnalyticsConfiguration$ = exports.PutBucketAcl$ = exports.PutBucketAccelerateConfiguration$ = exports.PutBucketAbac$ = exports.ListParts$ = exports.ListObjectVersions$ = exports.ListObjectsV2$ = exports.ListObjects$ = exports.ListMultipartUploads$ = exports.ListDirectoryBuckets$ = exports.ListBuckets$ = exports.ListBucketMetricsConfigurations$ = exports.ListBucketInventoryConfigurations$ = exports.ListBucketIntelligentTieringConfigurations$ = exports.ListBucketAnalyticsConfigurations$ = exports.HeadObject$ = exports.HeadBucket$ = exports.GetPublicAccessBlock$ = exports.GetObjectTorrent$ = exports.GetObjectTagging$ = exports.GetObjectRetention$ = exports.GetObjectLockConfiguration$ = exports.GetObjectLegalHold$ = exports.GetObjectAttributes$ = exports.GetObjectAcl$ = exports.GetObject$ = void 0; + exports.WriteGetObjectResponse$ = exports.UploadPartCopy$ = exports.UploadPart$ = exports.UpdateObjectEncryption$ = exports.UpdateBucketMetadataJournalTableConfiguration$ = exports.UpdateBucketMetadataInventoryTableConfiguration$ = exports.SelectObjectContent$ = void 0; + var _A2 = "Account"; + var _AAO = "AnalyticsAndOperator"; + var _AC = "AccelerateConfiguration"; + var _ACL = "AccessControlList"; + var _ACL_ = "ACL"; + var _ACLn = "AnalyticsConfigurationList"; + var _ACP = "AccessControlPolicy"; + var _ACT = "AccessControlTranslation"; + var _ACn = "AnalyticsConfiguration"; + var _AD = "AccessDenied"; + var _ADb = "AbortDate"; + var _AED = "AnalyticsExportDestination"; + var _AF = "AnalyticsFilter"; + var _AH = "AllowedHeaders"; + var _AHl = "AllowedHeader"; + var _AI = "AccountId"; + var _AIMU = "AbortIncompleteMultipartUpload"; + var _AKI2 = "AccessKeyId"; + var _AM = "AllowedMethods"; + var _AMU = "AbortMultipartUpload"; + var _AMUO = "AbortMultipartUploadOutput"; + var _AMUR = "AbortMultipartUploadRequest"; + var _AMl = "AllowedMethod"; + var _AO = "AllowedOrigins"; + var _AOl = "AllowedOrigin"; + var _APA = "AccessPointAlias"; + var _APAc = "AccessPointArn"; + var _AQRD = "AllowQuotedRecordDelimiter"; + var _AR2 = "AcceptRanges"; + var _ARI2 = "AbortRuleId"; + var _AS = "AbacStatus"; + var _ASBD = "AnalyticsS3BucketDestination"; + var _ASSEBD = "ApplyServerSideEncryptionByDefault"; + var _ASr = "ArchiveStatus"; + var _AT3 = "AccessTier"; + var _An = "And"; + var _B = "Bucket"; + var _BA = "BucketArn"; + var _BAE = "BucketAlreadyExists"; + var _BAI = "BucketAccountId"; + var _BAOBY = "BucketAlreadyOwnedByYou"; + var _BET = "BlockedEncryptionTypes"; + var _BGR = "BypassGovernanceRetention"; + var _BI = "BucketInfo"; + var _BKE = "BucketKeyEnabled"; + var _BLC = "BucketLifecycleConfiguration"; + var _BLN = "BucketLocationName"; + var _BLS = "BucketLoggingStatus"; + var _BLT = "BucketLocationType"; + var _BN = "BucketNamespace"; + var _BNu = "BucketName"; + var _BP = "BytesProcessed"; + var _BPA = "BlockPublicAcls"; + var _BPP = "BlockPublicPolicy"; + var _BR = "BucketRegion"; + var _BRy = "BytesReturned"; + var _BS = "BytesScanned"; + var _Bo = "Body"; + var _Bu = "Buckets"; + var _C2 = "Checksum"; + var _CA2 = "ChecksumAlgorithm"; + var _CACL = "CannedACL"; + var _CB = "CreateBucket"; + var _CBC = "CreateBucketConfiguration"; + var _CBMC = "CreateBucketMetadataConfiguration"; + var _CBMCR = "CreateBucketMetadataConfigurationRequest"; + var _CBMTC = "CreateBucketMetadataTableConfiguration"; + var _CBMTCR = "CreateBucketMetadataTableConfigurationRequest"; + var _CBO = "CreateBucketOutput"; + var _CBR = "CreateBucketRequest"; + var _CC = "CacheControl"; + var _CCRC = "ChecksumCRC32"; + var _CCRCC = "ChecksumCRC32C"; + var _CCRCNVME = "ChecksumCRC64NVME"; + var _CC_ = "Cache-Control"; + var _CD = "CreationDate"; + var _CD_ = "Content-Disposition"; + var _CDo = "ContentDisposition"; + var _CE = "ContinuationEvent"; + var _CE_ = "Content-Encoding"; + var _CEo = "ContentEncoding"; + var _CF = "CloudFunction"; + var _CFC = "CloudFunctionConfiguration"; + var _CL = "ContentLanguage"; + var _CL_ = "Content-Language"; + var _CL__ = "Content-Length"; + var _CLo = "ContentLength"; + var _CM = "Content-MD5"; + var _CMD = "ContentMD5"; + var _CMU = "CompletedMultipartUpload"; + var _CMUO = "CompleteMultipartUploadOutput"; + var _CMUOr = "CreateMultipartUploadOutput"; + var _CMUR = "CompleteMultipartUploadResult"; + var _CMURo = "CompleteMultipartUploadRequest"; + var _CMURr = "CreateMultipartUploadRequest"; + var _CMUo = "CompleteMultipartUpload"; + var _CMUr = "CreateMultipartUpload"; + var _CMh = "ChecksumMode"; + var _CO = "CopyObject"; + var _COO = "CopyObjectOutput"; + var _COR = "CopyObjectResult"; + var _CORSC = "CORSConfiguration"; + var _CORSR = "CORSRules"; + var _CORSRu = "CORSRule"; + var _CORo = "CopyObjectRequest"; + var _CP = "CommonPrefix"; + var _CPL = "CommonPrefixList"; + var _CPLo = "CompletedPartList"; + var _CPR = "CopyPartResult"; + var _CPo = "CompletedPart"; + var _CPom = "CommonPrefixes"; + var _CR = "ContentRange"; + var _CRSBA = "ConfirmRemoveSelfBucketAccess"; + var _CR_ = "Content-Range"; + var _CS2 = "CopySource"; + var _CSHA = "ChecksumSHA1"; + var _CSHAh = "ChecksumSHA256"; + var _CSIM = "CopySourceIfMatch"; + var _CSIMS = "CopySourceIfModifiedSince"; + var _CSINM = "CopySourceIfNoneMatch"; + var _CSIUS = "CopySourceIfUnmodifiedSince"; + var _CSO = "CreateSessionOutput"; + var _CSR = "CreateSessionResult"; + var _CSRo = "CopySourceRange"; + var _CSRr = "CreateSessionRequest"; + var _CSSSECA = "CopySourceSSECustomerAlgorithm"; + var _CSSSECK = "CopySourceSSECustomerKey"; + var _CSSSECKMD = "CopySourceSSECustomerKeyMD5"; + var _CSV = "CSV"; + var _CSVI = "CopySourceVersionId"; + var _CSVIn = "CSVInput"; + var _CSVO = "CSVOutput"; + var _CSo = "ConfigurationState"; + var _CSr = "CreateSession"; + var _CT2 = "ChecksumType"; + var _CT_ = "Content-Type"; + var _CTl = "ClientToken"; + var _CTo = "ContentType"; + var _CTom = "CompressionType"; + var _CTon = "ContinuationToken"; + var _Co = "Condition"; + var _Cod = "Code"; + var _Com = "Comments"; + var _Con = "Contents"; + var _Cont = "Cont"; + var _Cr = "Credentials"; + var _D = "Days"; + var _DAI = "DaysAfterInitiation"; + var _DB = "DeleteBucket"; + var _DBAC = "DeleteBucketAnalyticsConfiguration"; + var _DBACR = "DeleteBucketAnalyticsConfigurationRequest"; + var _DBC = "DeleteBucketCors"; + var _DBCR = "DeleteBucketCorsRequest"; + var _DBE = "DeleteBucketEncryption"; + var _DBER = "DeleteBucketEncryptionRequest"; + var _DBIC = "DeleteBucketInventoryConfiguration"; + var _DBICR = "DeleteBucketInventoryConfigurationRequest"; + var _DBITC = "DeleteBucketIntelligentTieringConfiguration"; + var _DBITCR = "DeleteBucketIntelligentTieringConfigurationRequest"; + var _DBL = "DeleteBucketLifecycle"; + var _DBLR = "DeleteBucketLifecycleRequest"; + var _DBMC = "DeleteBucketMetadataConfiguration"; + var _DBMCR = "DeleteBucketMetadataConfigurationRequest"; + var _DBMCRe = "DeleteBucketMetricsConfigurationRequest"; + var _DBMCe = "DeleteBucketMetricsConfiguration"; + var _DBMTC = "DeleteBucketMetadataTableConfiguration"; + var _DBMTCR = "DeleteBucketMetadataTableConfigurationRequest"; + var _DBOC = "DeleteBucketOwnershipControls"; + var _DBOCR = "DeleteBucketOwnershipControlsRequest"; + var _DBP = "DeleteBucketPolicy"; + var _DBPR = "DeleteBucketPolicyRequest"; + var _DBR = "DeleteBucketRequest"; + var _DBRR = "DeleteBucketReplicationRequest"; + var _DBRe = "DeleteBucketReplication"; + var _DBT = "DeleteBucketTagging"; + var _DBTR = "DeleteBucketTaggingRequest"; + var _DBW = "DeleteBucketWebsite"; + var _DBWR = "DeleteBucketWebsiteRequest"; + var _DE = "DataExport"; + var _DIM = "DestinationIfMatch"; + var _DIMS = "DestinationIfModifiedSince"; + var _DINM = "DestinationIfNoneMatch"; + var _DIUS = "DestinationIfUnmodifiedSince"; + var _DM = "DeleteMarker"; + var _DME = "DeleteMarkerEntry"; + var _DMR = "DeleteMarkerReplication"; + var _DMVI = "DeleteMarkerVersionId"; + var _DMe = "DeleteMarkers"; + var _DN = "DisplayName"; + var _DO = "DeletedObject"; + var _DOO = "DeleteObjectOutput"; + var _DOOe = "DeleteObjectsOutput"; + var _DOR = "DeleteObjectRequest"; + var _DORe = "DeleteObjectsRequest"; + var _DOT = "DeleteObjectTagging"; + var _DOTO = "DeleteObjectTaggingOutput"; + var _DOTR = "DeleteObjectTaggingRequest"; + var _DOe = "DeletedObjects"; + var _DOel = "DeleteObject"; + var _DOele = "DeleteObjects"; + var _DPAB = "DeletePublicAccessBlock"; + var _DPABR = "DeletePublicAccessBlockRequest"; + var _DR = "DataRedundancy"; + var _DRe = "DefaultRetention"; + var _DRel = "DeleteResult"; + var _DRes = "DestinationResult"; + var _Da = "Date"; + var _De = "Delete"; + var _Del = "Deleted"; + var _Deli = "Delimiter"; + var _Des = "Destination"; + var _Desc = "Description"; + var _Det = "Details"; + var _E2 = "Expiration"; + var _EA = "EmailAddress"; + var _EBC = "EventBridgeConfiguration"; + var _EBO = "ExpectedBucketOwner"; + var _EC = "EncryptionConfiguration"; + var _ECr = "ErrorCode"; + var _ED = "ErrorDetails"; + var _EDr = "ErrorDocument"; + var _EE = "EndEvent"; + var _EH = "ExposeHeaders"; + var _EHx = "ExposeHeader"; + var _EM = "ErrorMessage"; + var _EODM = "ExpiredObjectDeleteMarker"; + var _EOR = "ExistingObjectReplication"; + var _ES = "ExpiresString"; + var _ESBO = "ExpectedSourceBucketOwner"; + var _ET = "EncryptionType"; + var _ETL = "EncryptionTypeList"; + var _ETM = "EncryptionTypeMismatch"; + var _ETa = "ETag"; + var _ETn = "EncodingType"; + var _ETv = "EventThreshold"; + var _ETx = "ExpressionType"; + var _En = "Encryption"; + var _Ena = "Enabled"; + var _End = "End"; + var _Er = "Errors"; + var _Err = "Error"; + var _Ev = "Events"; + var _Eve = "Event"; + var _Ex = "Expires"; + var _Exp = "Expression"; + var _F = "Filter"; + var _FD = "FieldDelimiter"; + var _FHI = "FileHeaderInfo"; + var _FO = "FetchOwner"; + var _FR = "FilterRule"; + var _FRL = "FilterRuleList"; + var _FRi = "FilterRules"; + var _Fi = "Field"; + var _Fo = "Format"; + var _Fr = "Frequency"; + var _G = "Grants"; + var _GBA = "GetBucketAbac"; + var _GBAC = "GetBucketAccelerateConfiguration"; + var _GBACO = "GetBucketAccelerateConfigurationOutput"; + var _GBACOe = "GetBucketAnalyticsConfigurationOutput"; + var _GBACR = "GetBucketAccelerateConfigurationRequest"; + var _GBACRe = "GetBucketAnalyticsConfigurationRequest"; + var _GBACe = "GetBucketAnalyticsConfiguration"; + var _GBAO = "GetBucketAbacOutput"; + var _GBAOe = "GetBucketAclOutput"; + var _GBAR = "GetBucketAbacRequest"; + var _GBARe = "GetBucketAclRequest"; + var _GBAe = "GetBucketAcl"; + var _GBC = "GetBucketCors"; + var _GBCO = "GetBucketCorsOutput"; + var _GBCR = "GetBucketCorsRequest"; + var _GBE = "GetBucketEncryption"; + var _GBEO = "GetBucketEncryptionOutput"; + var _GBER = "GetBucketEncryptionRequest"; + var _GBIC = "GetBucketInventoryConfiguration"; + var _GBICO = "GetBucketInventoryConfigurationOutput"; + var _GBICR = "GetBucketInventoryConfigurationRequest"; + var _GBITC = "GetBucketIntelligentTieringConfiguration"; + var _GBITCO = "GetBucketIntelligentTieringConfigurationOutput"; + var _GBITCR = "GetBucketIntelligentTieringConfigurationRequest"; + var _GBL = "GetBucketLocation"; + var _GBLC = "GetBucketLifecycleConfiguration"; + var _GBLCO = "GetBucketLifecycleConfigurationOutput"; + var _GBLCR = "GetBucketLifecycleConfigurationRequest"; + var _GBLO = "GetBucketLocationOutput"; + var _GBLOe = "GetBucketLoggingOutput"; + var _GBLR = "GetBucketLocationRequest"; + var _GBLRe = "GetBucketLoggingRequest"; + var _GBLe = "GetBucketLogging"; + var _GBMC = "GetBucketMetadataConfiguration"; + var _GBMCO = "GetBucketMetadataConfigurationOutput"; + var _GBMCOe = "GetBucketMetricsConfigurationOutput"; + var _GBMCR = "GetBucketMetadataConfigurationResult"; + var _GBMCRe = "GetBucketMetadataConfigurationRequest"; + var _GBMCRet = "GetBucketMetricsConfigurationRequest"; + var _GBMCe = "GetBucketMetricsConfiguration"; + var _GBMTC = "GetBucketMetadataTableConfiguration"; + var _GBMTCO = "GetBucketMetadataTableConfigurationOutput"; + var _GBMTCR = "GetBucketMetadataTableConfigurationResult"; + var _GBMTCRe = "GetBucketMetadataTableConfigurationRequest"; + var _GBNC = "GetBucketNotificationConfiguration"; + var _GBNCR = "GetBucketNotificationConfigurationRequest"; + var _GBOC = "GetBucketOwnershipControls"; + var _GBOCO = "GetBucketOwnershipControlsOutput"; + var _GBOCR = "GetBucketOwnershipControlsRequest"; + var _GBP = "GetBucketPolicy"; + var _GBPO = "GetBucketPolicyOutput"; + var _GBPR = "GetBucketPolicyRequest"; + var _GBPS = "GetBucketPolicyStatus"; + var _GBPSO = "GetBucketPolicyStatusOutput"; + var _GBPSR = "GetBucketPolicyStatusRequest"; + var _GBR = "GetBucketReplication"; + var _GBRO = "GetBucketReplicationOutput"; + var _GBRP = "GetBucketRequestPayment"; + var _GBRPO = "GetBucketRequestPaymentOutput"; + var _GBRPR = "GetBucketRequestPaymentRequest"; + var _GBRR = "GetBucketReplicationRequest"; + var _GBT = "GetBucketTagging"; + var _GBTO = "GetBucketTaggingOutput"; + var _GBTR = "GetBucketTaggingRequest"; + var _GBV = "GetBucketVersioning"; + var _GBVO = "GetBucketVersioningOutput"; + var _GBVR = "GetBucketVersioningRequest"; + var _GBW = "GetBucketWebsite"; + var _GBWO = "GetBucketWebsiteOutput"; + var _GBWR = "GetBucketWebsiteRequest"; + var _GFC = "GrantFullControl"; + var _GJP = "GlacierJobParameters"; + var _GO = "GetObject"; + var _GOA = "GetObjectAcl"; + var _GOAO = "GetObjectAclOutput"; + var _GOAOe = "GetObjectAttributesOutput"; + var _GOAP = "GetObjectAttributesParts"; + var _GOAR = "GetObjectAclRequest"; + var _GOARe = "GetObjectAttributesResponse"; + var _GOARet = "GetObjectAttributesRequest"; + var _GOAe = "GetObjectAttributes"; + var _GOLC = "GetObjectLockConfiguration"; + var _GOLCO = "GetObjectLockConfigurationOutput"; + var _GOLCR = "GetObjectLockConfigurationRequest"; + var _GOLH = "GetObjectLegalHold"; + var _GOLHO = "GetObjectLegalHoldOutput"; + var _GOLHR = "GetObjectLegalHoldRequest"; + var _GOO = "GetObjectOutput"; + var _GOR = "GetObjectRequest"; + var _GORO = "GetObjectRetentionOutput"; + var _GORR = "GetObjectRetentionRequest"; + var _GORe = "GetObjectRetention"; + var _GOT = "GetObjectTagging"; + var _GOTO = "GetObjectTaggingOutput"; + var _GOTOe = "GetObjectTorrentOutput"; + var _GOTR = "GetObjectTaggingRequest"; + var _GOTRe = "GetObjectTorrentRequest"; + var _GOTe = "GetObjectTorrent"; + var _GPAB = "GetPublicAccessBlock"; + var _GPABO = "GetPublicAccessBlockOutput"; + var _GPABR = "GetPublicAccessBlockRequest"; + var _GR = "GrantRead"; + var _GRACP = "GrantReadACP"; + var _GW = "GrantWrite"; + var _GWACP = "GrantWriteACP"; + var _Gr = "Grant"; + var _Gra = "Grantee"; + var _HB = "HeadBucket"; + var _HBO = "HeadBucketOutput"; + var _HBR = "HeadBucketRequest"; + var _HECRE = "HttpErrorCodeReturnedEquals"; + var _HN = "HostName"; + var _HO = "HeadObject"; + var _HOO = "HeadObjectOutput"; + var _HOR = "HeadObjectRequest"; + var _HRC = "HttpRedirectCode"; + var _I = "Id"; + var _IC = "InventoryConfiguration"; + var _ICL = "InventoryConfigurationList"; + var _ID = "ID"; + var _IDn = "IndexDocument"; + var _IDnv = "InventoryDestination"; + var _IE = "IsEnabled"; + var _IEn = "InventoryEncryption"; + var _IF = "InventoryFilter"; + var _IL = "IsLatest"; + var _IM = "IfMatch"; + var _IMIT = "IfMatchInitiatedTime"; + var _IMLMT = "IfMatchLastModifiedTime"; + var _IMS = "IfMatchSize"; + var _IMS_ = "If-Modified-Since"; + var _IMSf = "IfModifiedSince"; + var _IMUR = "InitiateMultipartUploadResult"; + var _IM_ = "If-Match"; + var _INM = "IfNoneMatch"; + var _INM_ = "If-None-Match"; + var _IOF = "InventoryOptionalFields"; + var _IOS = "InvalidObjectState"; + var _IOV = "IncludedObjectVersions"; + var _IP = "IsPublic"; + var _IPA = "IgnorePublicAcls"; + var _IPM = "IdempotencyParameterMismatch"; + var _IR = "InvalidRequest"; + var _IRIP = "IsRestoreInProgress"; + var _IS = "InputSerialization"; + var _ISBD = "InventoryS3BucketDestination"; + var _ISn = "InventorySchedule"; + var _IT2 = "IsTruncated"; + var _ITAO = "IntelligentTieringAndOperator"; + var _ITC = "IntelligentTieringConfiguration"; + var _ITCL = "IntelligentTieringConfigurationList"; + var _ITCR = "InventoryTableConfigurationResult"; + var _ITCU = "InventoryTableConfigurationUpdates"; + var _ITCn = "InventoryTableConfiguration"; + var _ITF = "IntelligentTieringFilter"; + var _IUS = "IfUnmodifiedSince"; + var _IUS_ = "If-Unmodified-Since"; + var _IWO = "InvalidWriteOffset"; + var _In = "Initiator"; + var _Ini = "Initiated"; + var _JSON = "JSON"; + var _JSONI = "JSONInput"; + var _JSONO = "JSONOutput"; + var _JTC = "JournalTableConfiguration"; + var _JTCR = "JournalTableConfigurationResult"; + var _JTCU = "JournalTableConfigurationUpdates"; + var _K2 = "Key"; + var _KC = "KeyCount"; + var _KI = "KeyId"; + var _KKA = "KmsKeyArn"; + var _KM = "KeyMarker"; + var _KMSC = "KMSContext"; + var _KMSKA = "KMSKeyArn"; + var _KMSKI = "KMSKeyId"; + var _KMSMKID = "KMSMasterKeyID"; + var _KPE = "KeyPrefixEquals"; + var _L = "Location"; + var _LAMBR = "ListAllMyBucketsResult"; + var _LAMDBR = "ListAllMyDirectoryBucketsResult"; + var _LB = "ListBuckets"; + var _LBAC = "ListBucketAnalyticsConfigurations"; + var _LBACO = "ListBucketAnalyticsConfigurationsOutput"; + var _LBACR = "ListBucketAnalyticsConfigurationResult"; + var _LBACRi = "ListBucketAnalyticsConfigurationsRequest"; + var _LBIC = "ListBucketInventoryConfigurations"; + var _LBICO = "ListBucketInventoryConfigurationsOutput"; + var _LBICR = "ListBucketInventoryConfigurationsRequest"; + var _LBITC = "ListBucketIntelligentTieringConfigurations"; + var _LBITCO = "ListBucketIntelligentTieringConfigurationsOutput"; + var _LBITCR = "ListBucketIntelligentTieringConfigurationsRequest"; + var _LBMC = "ListBucketMetricsConfigurations"; + var _LBMCO = "ListBucketMetricsConfigurationsOutput"; + var _LBMCR = "ListBucketMetricsConfigurationsRequest"; + var _LBO = "ListBucketsOutput"; + var _LBR = "ListBucketsRequest"; + var _LBRi = "ListBucketResult"; + var _LC = "LocationConstraint"; + var _LCi = "LifecycleConfiguration"; + var _LDB = "ListDirectoryBuckets"; + var _LDBO = "ListDirectoryBucketsOutput"; + var _LDBR = "ListDirectoryBucketsRequest"; + var _LE = "LoggingEnabled"; + var _LEi = "LifecycleExpiration"; + var _LFA = "LambdaFunctionArn"; + var _LFC = "LambdaFunctionConfiguration"; + var _LFCL = "LambdaFunctionConfigurationList"; + var _LFCa = "LambdaFunctionConfigurations"; + var _LH = "LegalHold"; + var _LI = "LocationInfo"; + var _LICR = "ListInventoryConfigurationsResult"; + var _LM = "LastModified"; + var _LMCR = "ListMetricsConfigurationsResult"; + var _LMT = "LastModifiedTime"; + var _LMU = "ListMultipartUploads"; + var _LMUO = "ListMultipartUploadsOutput"; + var _LMUR = "ListMultipartUploadsResult"; + var _LMURi = "ListMultipartUploadsRequest"; + var _LM_ = "Last-Modified"; + var _LO = "ListObjects"; + var _LOO = "ListObjectsOutput"; + var _LOR = "ListObjectsRequest"; + var _LOV = "ListObjectsV2"; + var _LOVO = "ListObjectsV2Output"; + var _LOVOi = "ListObjectVersionsOutput"; + var _LOVR = "ListObjectsV2Request"; + var _LOVRi = "ListObjectVersionsRequest"; + var _LOVi = "ListObjectVersions"; + var _LP = "ListParts"; + var _LPO = "ListPartsOutput"; + var _LPR = "ListPartsResult"; + var _LPRi = "ListPartsRequest"; + var _LR = "LifecycleRule"; + var _LRAO = "LifecycleRuleAndOperator"; + var _LRF = "LifecycleRuleFilter"; + var _LRi = "LifecycleRules"; + var _LVR = "ListVersionsResult"; + var _M = "Metadata"; + var _MAO = "MetricsAndOperator"; + var _MAS = "MaxAgeSeconds"; + var _MB = "MaxBuckets"; + var _MC = "MetadataConfiguration"; + var _MCL = "MetricsConfigurationList"; + var _MCR = "MetadataConfigurationResult"; + var _MCe = "MetricsConfiguration"; + var _MD = "MetadataDirective"; + var _MDB = "MaxDirectoryBuckets"; + var _MDf = "MfaDelete"; + var _ME = "MetadataEntry"; + var _MF = "MetricsFilter"; + var _MFA = "MFA"; + var _MFAD = "MFADelete"; + var _MK = "MaxKeys"; + var _MM = "MissingMeta"; + var _MOS = "MpuObjectSize"; + var _MP = "MaxParts"; + var _MTC = "MetadataTableConfiguration"; + var _MTCR = "MetadataTableConfigurationResult"; + var _MTEC = "MetadataTableEncryptionConfiguration"; + var _MU = "MultipartUpload"; + var _MUL = "MultipartUploadList"; + var _MUa = "MaxUploads"; + var _Ma = "Marker"; + var _Me = "Metrics"; + var _Mes = "Message"; + var _Mi = "Minutes"; + var _Mo = "Mode"; + var _N = "Name"; + var _NC = "NotificationConfiguration"; + var _NCF = "NotificationConfigurationFilter"; + var _NCT = "NextContinuationToken"; + var _ND = "NoncurrentDays"; + var _NEKKAS = "NonEmptyKmsKeyArnString"; + var _NF = "NotFound"; + var _NKM = "NextKeyMarker"; + var _NM = "NextMarker"; + var _NNV = "NewerNoncurrentVersions"; + var _NPNM = "NextPartNumberMarker"; + var _NSB = "NoSuchBucket"; + var _NSK = "NoSuchKey"; + var _NSU = "NoSuchUpload"; + var _NUIM = "NextUploadIdMarker"; + var _NVE = "NoncurrentVersionExpiration"; + var _NVIM = "NextVersionIdMarker"; + var _NVT = "NoncurrentVersionTransitions"; + var _NVTL = "NoncurrentVersionTransitionList"; + var _NVTo = "NoncurrentVersionTransition"; + var _O = "Owner"; + var _OA = "ObjectAttributes"; + var _OAIATE = "ObjectAlreadyInActiveTierError"; + var _OC = "OwnershipControls"; + var _OCR = "OwnershipControlsRule"; + var _OCRw = "OwnershipControlsRules"; + var _OE = "ObjectEncryption"; + var _OF = "OptionalFields"; + var _OI = "ObjectIdentifier"; + var _OIL = "ObjectIdentifierList"; + var _OL = "OutputLocation"; + var _OLC = "ObjectLockConfiguration"; + var _OLE = "ObjectLockEnabled"; + var _OLEFB = "ObjectLockEnabledForBucket"; + var _OLLH = "ObjectLockLegalHold"; + var _OLLHS = "ObjectLockLegalHoldStatus"; + var _OLM = "ObjectLockMode"; + var _OLR = "ObjectLockRetention"; + var _OLRUD = "ObjectLockRetainUntilDate"; + var _OLRb = "ObjectLockRule"; + var _OLb = "ObjectList"; + var _ONIATE = "ObjectNotInActiveTierError"; + var _OO = "ObjectOwnership"; + var _OOA = "OptionalObjectAttributes"; + var _OP = "ObjectParts"; + var _OPb = "ObjectPart"; + var _OS = "ObjectSize"; + var _OSGT = "ObjectSizeGreaterThan"; + var _OSLT = "ObjectSizeLessThan"; + var _OSV = "OutputSchemaVersion"; + var _OSu = "OutputSerialization"; + var _OV = "ObjectVersion"; + var _OVL = "ObjectVersionList"; + var _Ob = "Objects"; + var _Obj = "Object"; + var _P2 = "Prefix"; + var _PABC = "PublicAccessBlockConfiguration"; + var _PBA = "PutBucketAbac"; + var _PBAC = "PutBucketAccelerateConfiguration"; + var _PBACR = "PutBucketAccelerateConfigurationRequest"; + var _PBACRu = "PutBucketAnalyticsConfigurationRequest"; + var _PBACu = "PutBucketAnalyticsConfiguration"; + var _PBAR = "PutBucketAbacRequest"; + var _PBARu = "PutBucketAclRequest"; + var _PBAu = "PutBucketAcl"; + var _PBC = "PutBucketCors"; + var _PBCR = "PutBucketCorsRequest"; + var _PBE = "PutBucketEncryption"; + var _PBER = "PutBucketEncryptionRequest"; + var _PBIC = "PutBucketInventoryConfiguration"; + var _PBICR = "PutBucketInventoryConfigurationRequest"; + var _PBITC = "PutBucketIntelligentTieringConfiguration"; + var _PBITCR = "PutBucketIntelligentTieringConfigurationRequest"; + var _PBL = "PutBucketLogging"; + var _PBLC = "PutBucketLifecycleConfiguration"; + var _PBLCO = "PutBucketLifecycleConfigurationOutput"; + var _PBLCR = "PutBucketLifecycleConfigurationRequest"; + var _PBLR = "PutBucketLoggingRequest"; + var _PBMC = "PutBucketMetricsConfiguration"; + var _PBMCR = "PutBucketMetricsConfigurationRequest"; + var _PBNC = "PutBucketNotificationConfiguration"; + var _PBNCR = "PutBucketNotificationConfigurationRequest"; + var _PBOC = "PutBucketOwnershipControls"; + var _PBOCR = "PutBucketOwnershipControlsRequest"; + var _PBP = "PutBucketPolicy"; + var _PBPR = "PutBucketPolicyRequest"; + var _PBR = "PutBucketReplication"; + var _PBRP = "PutBucketRequestPayment"; + var _PBRPR = "PutBucketRequestPaymentRequest"; + var _PBRR = "PutBucketReplicationRequest"; + var _PBT = "PutBucketTagging"; + var _PBTR = "PutBucketTaggingRequest"; + var _PBV = "PutBucketVersioning"; + var _PBVR = "PutBucketVersioningRequest"; + var _PBW = "PutBucketWebsite"; + var _PBWR = "PutBucketWebsiteRequest"; + var _PC2 = "PartsCount"; + var _PDS = "PartitionDateSource"; + var _PE = "ProgressEvent"; + var _PI2 = "ParquetInput"; + var _PL = "PartsList"; + var _PN = "PartNumber"; + var _PNM = "PartNumberMarker"; + var _PO = "PutObject"; + var _POA = "PutObjectAcl"; + var _POAO = "PutObjectAclOutput"; + var _POAR = "PutObjectAclRequest"; + var _POLC = "PutObjectLockConfiguration"; + var _POLCO = "PutObjectLockConfigurationOutput"; + var _POLCR = "PutObjectLockConfigurationRequest"; + var _POLH = "PutObjectLegalHold"; + var _POLHO = "PutObjectLegalHoldOutput"; + var _POLHR = "PutObjectLegalHoldRequest"; + var _POO = "PutObjectOutput"; + var _POR = "PutObjectRequest"; + var _PORO = "PutObjectRetentionOutput"; + var _PORR = "PutObjectRetentionRequest"; + var _PORu = "PutObjectRetention"; + var _POT = "PutObjectTagging"; + var _POTO = "PutObjectTaggingOutput"; + var _POTR = "PutObjectTaggingRequest"; + var _PP = "PartitionedPrefix"; + var _PPAB = "PutPublicAccessBlock"; + var _PPABR = "PutPublicAccessBlockRequest"; + var _PS = "PolicyStatus"; + var _Pa = "Parts"; + var _Par = "Part"; + var _Parq = "Parquet"; + var _Pay = "Payer"; + var _Payl = "Payload"; + var _Pe = "Permission"; + var _Po = "Policy"; + var _Pr2 = "Progress"; + var _Pri = "Priority"; + var _Pro = "Protocol"; + var _Q = "Quiet"; + var _QA = "QueueArn"; + var _QC = "QuoteCharacter"; + var _QCL = "QueueConfigurationList"; + var _QCu = "QueueConfigurations"; + var _QCue = "QueueConfiguration"; + var _QEC = "QuoteEscapeCharacter"; + var _QF = "QuoteFields"; + var _Qu = "Queue"; + var _R = "Rules"; + var _RART = "RedirectAllRequestsTo"; + var _RC2 = "RequestCharged"; + var _RCC = "ResponseCacheControl"; + var _RCD = "ResponseContentDisposition"; + var _RCE = "ResponseContentEncoding"; + var _RCL = "ResponseContentLanguage"; + var _RCT = "ResponseContentType"; + var _RCe = "ReplicationConfiguration"; + var _RD = "RecordDelimiter"; + var _RE = "ResponseExpires"; + var _RED = "RestoreExpiryDate"; + var _REe = "RecordExpiration"; + var _REec = "RecordsEvent"; + var _RKKID = "ReplicaKmsKeyID"; + var _RKPW = "ReplaceKeyPrefixWith"; + var _RKW = "ReplaceKeyWith"; + var _RM = "ReplicaModifications"; + var _RO = "RenameObject"; + var _ROO = "RenameObjectOutput"; + var _ROOe = "RestoreObjectOutput"; + var _ROP = "RestoreOutputPath"; + var _ROR = "RenameObjectRequest"; + var _RORe = "RestoreObjectRequest"; + var _ROe = "RestoreObject"; + var _RP = "RequestPayer"; + var _RPB = "RestrictPublicBuckets"; + var _RPC = "RequestPaymentConfiguration"; + var _RPe = "RequestProgress"; + var _RR = "RoutingRules"; + var _RRAO = "ReplicationRuleAndOperator"; + var _RRF = "ReplicationRuleFilter"; + var _RRe = "ReplicationRule"; + var _RRep = "ReplicationRules"; + var _RReq = "RequestRoute"; + var _RRes = "RestoreRequest"; + var _RRo = "RoutingRule"; + var _RS = "ReplicationStatus"; + var _RSe = "RestoreStatus"; + var _RSen = "RenameSource"; + var _RT3 = "ReplicationTime"; + var _RTV = "ReplicationTimeValue"; + var _RTe = "RequestToken"; + var _RUD = "RetainUntilDate"; + var _Ra = "Range"; + var _Re = "Restore"; + var _Rec = "Records"; + var _Red = "Redirect"; + var _Ret = "Retention"; + var _Ro = "Role"; + var _Ru = "Rule"; + var _S = "Status"; + var _SA = "StartAfter"; + var _SAK2 = "SecretAccessKey"; + var _SAs = "SseAlgorithm"; + var _SB = "StreamingBlob"; + var _SBD = "S3BucketDestination"; + var _SC = "StorageClass"; + var _SCA = "StorageClassAnalysis"; + var _SCADE = "StorageClassAnalysisDataExport"; + var _SCV = "SessionCredentialValue"; + var _SCe = "SessionCredentials"; + var _SCt = "StatusCode"; + var _SDV = "SkipDestinationValidation"; + var _SE = "StatsEvent"; + var _SIM = "SourceIfMatch"; + var _SIMS = "SourceIfModifiedSince"; + var _SINM = "SourceIfNoneMatch"; + var _SIUS = "SourceIfUnmodifiedSince"; + var _SK = "SSE-KMS"; + var _SKEO = "SseKmsEncryptedObjects"; + var _SKF = "S3KeyFilter"; + var _SKe = "S3Key"; + var _SL = "S3Location"; + var _SM = "SessionMode"; + var _SOC = "SelectObjectContent"; + var _SOCES = "SelectObjectContentEventStream"; + var _SOCO = "SelectObjectContentOutput"; + var _SOCR = "SelectObjectContentRequest"; + var _SP = "SelectParameters"; + var _SPi = "SimplePrefix"; + var _SR = "ScanRange"; + var _SS = "SSE-S3"; + var _SSC = "SourceSelectionCriteria"; + var _SSE = "ServerSideEncryption"; + var _SSEA = "SSEAlgorithm"; + var _SSEBD = "ServerSideEncryptionByDefault"; + var _SSEC = "ServerSideEncryptionConfiguration"; + var _SSECA = "SSECustomerAlgorithm"; + var _SSECK = "SSECustomerKey"; + var _SSECKMD = "SSECustomerKeyMD5"; + var _SSEKMS = "SSEKMS"; + var _SSEKMSE = "SSEKMSEncryption"; + var _SSEKMSEC = "SSEKMSEncryptionContext"; + var _SSEKMSKI = "SSEKMSKeyId"; + var _SSER = "ServerSideEncryptionRule"; + var _SSERe = "ServerSideEncryptionRules"; + var _SSES = "SSES3"; + var _ST2 = "SessionToken"; + var _STD = "S3TablesDestination"; + var _STDR = "S3TablesDestinationResult"; + var _S_ = "S3"; + var _Sc = "Schedule"; + var _Si = "Size"; + var _St = "Start"; + var _Sta = "Stats"; + var _Su = "Suffix"; + var _T2 = "Tags"; + var _TA = "TableArn"; + var _TAo = "TopicArn"; + var _TB = "TargetBucket"; + var _TBA = "TableBucketArn"; + var _TBT = "TableBucketType"; + var _TC2 = "TagCount"; + var _TCL = "TopicConfigurationList"; + var _TCo = "TopicConfigurations"; + var _TCop = "TopicConfiguration"; + var _TD = "TaggingDirective"; + var _TDMOS = "TransitionDefaultMinimumObjectSize"; + var _TG = "TargetGrants"; + var _TGa = "TargetGrant"; + var _TL = "TieringList"; + var _TLr = "TransitionList"; + var _TMP = "TooManyParts"; + var _TN = "TableNamespace"; + var _TNa = "TableName"; + var _TOKF = "TargetObjectKeyFormat"; + var _TP = "TargetPrefix"; + var _TPC = "TotalPartsCount"; + var _TS = "TagSet"; + var _TSa = "TableStatus"; + var _Ta2 = "Tag"; + var _Tag = "Tagging"; + var _Ti = "Tier"; + var _Tie = "Tierings"; + var _Tier = "Tiering"; + var _Tim = "Time"; + var _To = "Token"; + var _Top = "Topic"; + var _Tr = "Transitions"; + var _Tra = "Transition"; + var _Ty = "Type"; + var _U = "Uploads"; + var _UBMITC = "UpdateBucketMetadataInventoryTableConfiguration"; + var _UBMITCR = "UpdateBucketMetadataInventoryTableConfigurationRequest"; + var _UBMJTC = "UpdateBucketMetadataJournalTableConfiguration"; + var _UBMJTCR = "UpdateBucketMetadataJournalTableConfigurationRequest"; + var _UI = "UploadId"; + var _UIM = "UploadIdMarker"; + var _UM = "UserMetadata"; + var _UOE = "UpdateObjectEncryption"; + var _UOER = "UpdateObjectEncryptionRequest"; + var _UOERp = "UpdateObjectEncryptionResponse"; + var _UP = "UploadPart"; + var _UPC = "UploadPartCopy"; + var _UPCO = "UploadPartCopyOutput"; + var _UPCR = "UploadPartCopyRequest"; + var _UPO = "UploadPartOutput"; + var _UPR = "UploadPartRequest"; + var _URI = "URI"; + var _Up = "Upload"; + var _V2 = "Value"; + var _VC = "VersioningConfiguration"; + var _VI = "VersionId"; + var _VIM = "VersionIdMarker"; + var _Ve = "Versions"; + var _Ver = "Version"; + var _WC = "WebsiteConfiguration"; + var _WGOR = "WriteGetObjectResponse"; + var _WGORR = "WriteGetObjectResponseRequest"; + var _WOB = "WriteOffsetBytes"; + var _WRL = "WebsiteRedirectLocation"; + var _Y = "Years"; + var _ar = "accept-ranges"; + var _br = "bucket-region"; + var _c5 = "client"; + var _ct = "continuation-token"; + var _d = "delimiter"; + var _e5 = "error"; + var _eP = "eventPayload"; + var _en = "endpoint"; + var _et = "encoding-type"; + var _fo = "fetch-owner"; + var _h4 = "http"; + var _hC = "httpChecksum"; + var _hE5 = "httpError"; + var _hH2 = "httpHeader"; + var _hL = "hostLabel"; + var _hP = "httpPayload"; + var _hPH = "httpPrefixHeaders"; + var _hQ2 = "httpQuery"; + var _hi = "http://www.w3.org/2001/XMLSchema-instance"; + var _i = "id"; + var _iT3 = "idempotencyToken"; + var _km = "key-marker"; + var _m4 = "marker"; + var _mb = "max-buckets"; + var _mdb = "max-directory-buckets"; + var _mk = "max-keys"; + var _mp = "max-parts"; + var _mu = "max-uploads"; + var _p = "prefix"; + var _pN = "partNumber"; + var _pnm = "part-number-marker"; + var _rcc = "response-cache-control"; + var _rcd = "response-content-disposition"; + var _rce = "response-content-encoding"; + var _rcl = "response-content-language"; + var _rct = "response-content-type"; + var _re = "response-expires"; + var _s5 = "smithy.ts.sdk.synthetic.com.amazonaws.s3"; + var _sa = "start-after"; + var _st = "streaming"; + var _uI = "uploadId"; + var _uim = "upload-id-marker"; + var _vI = "versionId"; + var _vim = "version-id-marker"; + var _x = "xsi"; + var _xA = "xmlAttribute"; + var _xF = "xmlFlattened"; + var _xN = "xmlName"; + var _xNm = "xmlNamespace"; + var _xaa = "x-amz-acl"; + var _xaad = "x-amz-abort-date"; + var _xaapa = "x-amz-access-point-alias"; + var _xaari = "x-amz-abort-rule-id"; + var _xaas = "x-amz-archive-status"; + var _xaba = "x-amz-bucket-arn"; + var _xabgr = "x-amz-bypass-governance-retention"; + var _xabln = "x-amz-bucket-location-name"; + var _xablt = "x-amz-bucket-location-type"; + var _xabn = "x-amz-bucket-namespace"; + var _xabole = "x-amz-bucket-object-lock-enabled"; + var _xabolt = "x-amz-bucket-object-lock-token"; + var _xabr = "x-amz-bucket-region"; + var _xaca = "x-amz-checksum-algorithm"; + var _xacc = "x-amz-checksum-crc32"; + var _xacc_ = "x-amz-checksum-crc32c"; + var _xacc__ = "x-amz-checksum-crc64nvme"; + var _xacm = "x-amz-checksum-mode"; + var _xacrsba = "x-amz-confirm-remove-self-bucket-access"; + var _xacs = "x-amz-checksum-sha1"; + var _xacs_ = "x-amz-checksum-sha256"; + var _xacs__ = "x-amz-copy-source"; + var _xacsim = "x-amz-copy-source-if-match"; + var _xacsims = "x-amz-copy-source-if-modified-since"; + var _xacsinm = "x-amz-copy-source-if-none-match"; + var _xacsius = "x-amz-copy-source-if-unmodified-since"; + var _xacsm = "x-amz-create-session-mode"; + var _xacsr = "x-amz-copy-source-range"; + var _xacssseca = "x-amz-copy-source-server-side-encryption-customer-algorithm"; + var _xacssseck = "x-amz-copy-source-server-side-encryption-customer-key"; + var _xacssseckM = "x-amz-copy-source-server-side-encryption-customer-key-MD5"; + var _xacsvi = "x-amz-copy-source-version-id"; + var _xact = "x-amz-checksum-type"; + var _xact_ = "x-amz-client-token"; + var _xadm = "x-amz-delete-marker"; + var _xae = "x-amz-expiration"; + var _xaebo = "x-amz-expected-bucket-owner"; + var _xafec = "x-amz-fwd-error-code"; + var _xafem = "x-amz-fwd-error-message"; + var _xafhCC = "x-amz-fwd-header-Cache-Control"; + var _xafhCD = "x-amz-fwd-header-Content-Disposition"; + var _xafhCE = "x-amz-fwd-header-Content-Encoding"; + var _xafhCL = "x-amz-fwd-header-Content-Language"; + var _xafhCR = "x-amz-fwd-header-Content-Range"; + var _xafhCT = "x-amz-fwd-header-Content-Type"; + var _xafhE = "x-amz-fwd-header-ETag"; + var _xafhE_ = "x-amz-fwd-header-Expires"; + var _xafhLM = "x-amz-fwd-header-Last-Modified"; + var _xafhar = "x-amz-fwd-header-accept-ranges"; + var _xafhxacc = "x-amz-fwd-header-x-amz-checksum-crc32"; + var _xafhxacc_ = "x-amz-fwd-header-x-amz-checksum-crc32c"; + var _xafhxacc__ = "x-amz-fwd-header-x-amz-checksum-crc64nvme"; + var _xafhxacs = "x-amz-fwd-header-x-amz-checksum-sha1"; + var _xafhxacs_ = "x-amz-fwd-header-x-amz-checksum-sha256"; + var _xafhxadm = "x-amz-fwd-header-x-amz-delete-marker"; + var _xafhxae = "x-amz-fwd-header-x-amz-expiration"; + var _xafhxamm = "x-amz-fwd-header-x-amz-missing-meta"; + var _xafhxampc = "x-amz-fwd-header-x-amz-mp-parts-count"; + var _xafhxaollh = "x-amz-fwd-header-x-amz-object-lock-legal-hold"; + var _xafhxaolm = "x-amz-fwd-header-x-amz-object-lock-mode"; + var _xafhxaolrud = "x-amz-fwd-header-x-amz-object-lock-retain-until-date"; + var _xafhxar = "x-amz-fwd-header-x-amz-restore"; + var _xafhxarc = "x-amz-fwd-header-x-amz-request-charged"; + var _xafhxars = "x-amz-fwd-header-x-amz-replication-status"; + var _xafhxasc = "x-amz-fwd-header-x-amz-storage-class"; + var _xafhxasse = "x-amz-fwd-header-x-amz-server-side-encryption"; + var _xafhxasseakki = "x-amz-fwd-header-x-amz-server-side-encryption-aws-kms-key-id"; + var _xafhxassebke = "x-amz-fwd-header-x-amz-server-side-encryption-bucket-key-enabled"; + var _xafhxasseca = "x-amz-fwd-header-x-amz-server-side-encryption-customer-algorithm"; + var _xafhxasseckM = "x-amz-fwd-header-x-amz-server-side-encryption-customer-key-MD5"; + var _xafhxatc = "x-amz-fwd-header-x-amz-tagging-count"; + var _xafhxavi = "x-amz-fwd-header-x-amz-version-id"; + var _xafs = "x-amz-fwd-status"; + var _xagfc = "x-amz-grant-full-control"; + var _xagr = "x-amz-grant-read"; + var _xagra = "x-amz-grant-read-acp"; + var _xagw = "x-amz-grant-write"; + var _xagwa = "x-amz-grant-write-acp"; + var _xaimit = "x-amz-if-match-initiated-time"; + var _xaimlmt = "x-amz-if-match-last-modified-time"; + var _xaims = "x-amz-if-match-size"; + var _xam = "x-amz-meta-"; + var _xam_ = "x-amz-mfa"; + var _xamd = "x-amz-metadata-directive"; + var _xamm = "x-amz-missing-meta"; + var _xamos = "x-amz-mp-object-size"; + var _xamp = "x-amz-max-parts"; + var _xampc = "x-amz-mp-parts-count"; + var _xaoa = "x-amz-object-attributes"; + var _xaollh = "x-amz-object-lock-legal-hold"; + var _xaolm = "x-amz-object-lock-mode"; + var _xaolrud = "x-amz-object-lock-retain-until-date"; + var _xaoo = "x-amz-object-ownership"; + var _xaooa = "x-amz-optional-object-attributes"; + var _xaos = "x-amz-object-size"; + var _xapnm = "x-amz-part-number-marker"; + var _xar = "x-amz-restore"; + var _xarc = "x-amz-request-charged"; + var _xarop = "x-amz-restore-output-path"; + var _xarp = "x-amz-request-payer"; + var _xarr = "x-amz-request-route"; + var _xars = "x-amz-replication-status"; + var _xars_ = "x-amz-rename-source"; + var _xarsim = "x-amz-rename-source-if-match"; + var _xarsims = "x-amz-rename-source-if-modified-since"; + var _xarsinm = "x-amz-rename-source-if-none-match"; + var _xarsius = "x-amz-rename-source-if-unmodified-since"; + var _xart = "x-amz-request-token"; + var _xasc = "x-amz-storage-class"; + var _xasca = "x-amz-sdk-checksum-algorithm"; + var _xasdv = "x-amz-skip-destination-validation"; + var _xasebo = "x-amz-source-expected-bucket-owner"; + var _xasse = "x-amz-server-side-encryption"; + var _xasseakki = "x-amz-server-side-encryption-aws-kms-key-id"; + var _xassebke = "x-amz-server-side-encryption-bucket-key-enabled"; + var _xassec = "x-amz-server-side-encryption-context"; + var _xasseca = "x-amz-server-side-encryption-customer-algorithm"; + var _xasseck = "x-amz-server-side-encryption-customer-key"; + var _xasseckM = "x-amz-server-side-encryption-customer-key-MD5"; + var _xat = "x-amz-tagging"; + var _xatc = "x-amz-tagging-count"; + var _xatd = "x-amz-tagging-directive"; + var _xatdmos = "x-amz-transition-default-minimum-object-size"; + var _xavi = "x-amz-version-id"; + var _xawob = "x-amz-write-offset-bytes"; + var _xawrl = "x-amz-website-redirect-location"; + var _xs = "xsi:type"; + var n05 = "com.amazonaws.s3"; + var schema_1 = (init_schema3(), __toCommonJS(schema_exports2)); + var errors_1 = require_errors(); + var S3ServiceException_1 = require_S3ServiceException(); + var _s_registry5 = schema_1.TypeRegistry.for(_s5); + exports.S3ServiceException$ = [-3, _s5, "S3ServiceException", 0, [], []]; + _s_registry5.registerError(exports.S3ServiceException$, S3ServiceException_1.S3ServiceException); + var n0_registry5 = schema_1.TypeRegistry.for(n05); + exports.AccessDenied$ = [ + -3, + n05, + _AD, + { [_e5]: _c5, [_hE5]: 403 }, + [], + [] + ]; + n0_registry5.registerError(exports.AccessDenied$, errors_1.AccessDenied); + exports.BucketAlreadyExists$ = [ + -3, + n05, + _BAE, + { [_e5]: _c5, [_hE5]: 409 }, + [], + [] + ]; + n0_registry5.registerError(exports.BucketAlreadyExists$, errors_1.BucketAlreadyExists); + exports.BucketAlreadyOwnedByYou$ = [ + -3, + n05, + _BAOBY, + { [_e5]: _c5, [_hE5]: 409 }, + [], + [] + ]; + n0_registry5.registerError(exports.BucketAlreadyOwnedByYou$, errors_1.BucketAlreadyOwnedByYou); + exports.EncryptionTypeMismatch$ = [ + -3, + n05, + _ETM, + { [_e5]: _c5, [_hE5]: 400 }, + [], + [] + ]; + n0_registry5.registerError(exports.EncryptionTypeMismatch$, errors_1.EncryptionTypeMismatch); + exports.IdempotencyParameterMismatch$ = [ + -3, + n05, + _IPM, + { [_e5]: _c5, [_hE5]: 400 }, + [], + [] + ]; + n0_registry5.registerError(exports.IdempotencyParameterMismatch$, errors_1.IdempotencyParameterMismatch); + exports.InvalidObjectState$ = [ + -3, + n05, + _IOS, + { [_e5]: _c5, [_hE5]: 403 }, + [_SC, _AT3], + [0, 0] + ]; + n0_registry5.registerError(exports.InvalidObjectState$, errors_1.InvalidObjectState); + exports.InvalidRequest$ = [ + -3, + n05, + _IR, + { [_e5]: _c5, [_hE5]: 400 }, + [], + [] + ]; + n0_registry5.registerError(exports.InvalidRequest$, errors_1.InvalidRequest); + exports.InvalidWriteOffset$ = [ + -3, + n05, + _IWO, + { [_e5]: _c5, [_hE5]: 400 }, + [], + [] + ]; + n0_registry5.registerError(exports.InvalidWriteOffset$, errors_1.InvalidWriteOffset); + exports.NoSuchBucket$ = [ + -3, + n05, + _NSB, + { [_e5]: _c5, [_hE5]: 404 }, + [], + [] + ]; + n0_registry5.registerError(exports.NoSuchBucket$, errors_1.NoSuchBucket); + exports.NoSuchKey$ = [ + -3, + n05, + _NSK, + { [_e5]: _c5, [_hE5]: 404 }, + [], + [] + ]; + n0_registry5.registerError(exports.NoSuchKey$, errors_1.NoSuchKey); + exports.NoSuchUpload$ = [ + -3, + n05, + _NSU, + { [_e5]: _c5, [_hE5]: 404 }, + [], + [] + ]; + n0_registry5.registerError(exports.NoSuchUpload$, errors_1.NoSuchUpload); + exports.NotFound$ = [ + -3, + n05, + _NF, + { [_e5]: _c5 }, + [], + [] + ]; + n0_registry5.registerError(exports.NotFound$, errors_1.NotFound); + exports.ObjectAlreadyInActiveTierError$ = [ + -3, + n05, + _OAIATE, + { [_e5]: _c5, [_hE5]: 403 }, + [], + [] + ]; + n0_registry5.registerError(exports.ObjectAlreadyInActiveTierError$, errors_1.ObjectAlreadyInActiveTierError); + exports.ObjectNotInActiveTierError$ = [ + -3, + n05, + _ONIATE, + { [_e5]: _c5, [_hE5]: 403 }, + [], + [] + ]; + n0_registry5.registerError(exports.ObjectNotInActiveTierError$, errors_1.ObjectNotInActiveTierError); + exports.TooManyParts$ = [ + -3, + n05, + _TMP, + { [_e5]: _c5, [_hE5]: 400 }, + [], + [] + ]; + n0_registry5.registerError(exports.TooManyParts$, errors_1.TooManyParts); + exports.errorTypeRegistries = [ + _s_registry5, + n0_registry5 + ]; + var CopySourceSSECustomerKey = [0, n05, _CSSSECK, 8, 0]; + var NonEmptyKmsKeyArnString = [0, n05, _NEKKAS, 8, 0]; + var SessionCredentialValue = [0, n05, _SCV, 8, 0]; + var SSECustomerKey = [0, n05, _SSECK, 8, 0]; + var SSEKMSEncryptionContext = [0, n05, _SSEKMSEC, 8, 0]; + var SSEKMSKeyId = [0, n05, _SSEKMSKI, 8, 0]; + var StreamingBlob = [0, n05, _SB, { [_st]: 1 }, 42]; + exports.AbacStatus$ = [ + 3, + n05, + _AS, + 0, + [_S], + [0] + ]; + exports.AbortIncompleteMultipartUpload$ = [ + 3, + n05, + _AIMU, + 0, + [_DAI], + [1] + ]; + exports.AbortMultipartUploadOutput$ = [ + 3, + n05, + _AMUO, + 0, + [_RC2], + [[0, { [_hH2]: _xarc }]] + ]; + exports.AbortMultipartUploadRequest$ = [ + 3, + n05, + _AMUR, + 0, + [_B, _K2, _UI, _RP, _EBO, _IMIT], + [[0, 1], [0, 1], [0, { [_hQ2]: _uI }], [0, { [_hH2]: _xarp }], [0, { [_hH2]: _xaebo }], [6, { [_hH2]: _xaimit }]], + 3 + ]; + exports.AccelerateConfiguration$ = [ + 3, + n05, + _AC, + 0, + [_S], + [0] + ]; + exports.AccessControlPolicy$ = [ + 3, + n05, + _ACP, + 0, + [_G, _O], + [[() => Grants, { [_xN]: _ACL }], () => exports.Owner$] + ]; + exports.AccessControlTranslation$ = [ + 3, + n05, + _ACT, + 0, + [_O], + [0], + 1 + ]; + exports.AnalyticsAndOperator$ = [ + 3, + n05, + _AAO, + 0, + [_P2, _T2], + [0, [() => TagSet, { [_xF]: 1, [_xN]: _Ta2 }]] + ]; + exports.AnalyticsConfiguration$ = [ + 3, + n05, + _ACn, + 0, + [_I, _SCA, _F], + [0, () => exports.StorageClassAnalysis$, [() => exports.AnalyticsFilter$, 0]], + 2 + ]; + exports.AnalyticsExportDestination$ = [ + 3, + n05, + _AED, + 0, + [_SBD], + [() => exports.AnalyticsS3BucketDestination$], + 1 + ]; + exports.AnalyticsS3BucketDestination$ = [ + 3, + n05, + _ASBD, + 0, + [_Fo, _B, _BAI, _P2], + [0, 0, 0, 0], + 2 + ]; + exports.BlockedEncryptionTypes$ = [ + 3, + n05, + _BET, + 0, + [_ET], + [[() => EncryptionTypeList, { [_xF]: 1 }]] + ]; + exports.Bucket$ = [ + 3, + n05, + _B, + 0, + [_N, _CD, _BR, _BA], + [0, 4, 0, 0] + ]; + exports.BucketInfo$ = [ + 3, + n05, + _BI, + 0, + [_DR, _Ty], + [0, 0] + ]; + exports.BucketLifecycleConfiguration$ = [ + 3, + n05, + _BLC, + 0, + [_R], + [[() => LifecycleRules, { [_xF]: 1, [_xN]: _Ru }]], + 1 + ]; + exports.BucketLoggingStatus$ = [ + 3, + n05, + _BLS, + 0, + [_LE], + [[() => exports.LoggingEnabled$, 0]] + ]; + exports.Checksum$ = [ + 3, + n05, + _C2, + 0, + [_CCRC, _CCRCC, _CCRCNVME, _CSHA, _CSHAh, _CT2], + [0, 0, 0, 0, 0, 0] + ]; + exports.CommonPrefix$ = [ + 3, + n05, + _CP, + 0, + [_P2], + [0] + ]; + exports.CompletedMultipartUpload$ = [ + 3, + n05, + _CMU, + 0, + [_Pa], + [[() => CompletedPartList, { [_xF]: 1, [_xN]: _Par }]] + ]; + exports.CompletedPart$ = [ + 3, + n05, + _CPo, + 0, + [_ETa, _CCRC, _CCRCC, _CCRCNVME, _CSHA, _CSHAh, _PN], + [0, 0, 0, 0, 0, 0, 1] + ]; + exports.CompleteMultipartUploadOutput$ = [ + 3, + n05, + _CMUO, + { [_xN]: _CMUR }, + [_L, _B, _K2, _E2, _ETa, _CCRC, _CCRCC, _CCRCNVME, _CSHA, _CSHAh, _CT2, _SSE, _VI, _SSEKMSKI, _BKE, _RC2], + [0, 0, 0, [0, { [_hH2]: _xae }], 0, 0, 0, 0, 0, 0, 0, [0, { [_hH2]: _xasse }], [0, { [_hH2]: _xavi }], [() => SSEKMSKeyId, { [_hH2]: _xasseakki }], [2, { [_hH2]: _xassebke }], [0, { [_hH2]: _xarc }]] + ]; + exports.CompleteMultipartUploadRequest$ = [ + 3, + n05, + _CMURo, + 0, + [_B, _K2, _UI, _MU, _CCRC, _CCRCC, _CCRCNVME, _CSHA, _CSHAh, _CT2, _MOS, _RP, _EBO, _IM, _INM, _SSECA, _SSECK, _SSECKMD], + [[0, 1], [0, 1], [0, { [_hQ2]: _uI }], [() => exports.CompletedMultipartUpload$, { [_hP]: 1, [_xN]: _CMUo }], [0, { [_hH2]: _xacc }], [0, { [_hH2]: _xacc_ }], [0, { [_hH2]: _xacc__ }], [0, { [_hH2]: _xacs }], [0, { [_hH2]: _xacs_ }], [0, { [_hH2]: _xact }], [1, { [_hH2]: _xamos }], [0, { [_hH2]: _xarp }], [0, { [_hH2]: _xaebo }], [0, { [_hH2]: _IM_ }], [0, { [_hH2]: _INM_ }], [0, { [_hH2]: _xasseca }], [() => SSECustomerKey, { [_hH2]: _xasseck }], [0, { [_hH2]: _xasseckM }]], + 3 + ]; + exports.Condition$ = [ + 3, + n05, + _Co, + 0, + [_HECRE, _KPE], + [0, 0] + ]; + exports.ContinuationEvent$ = [ + 3, + n05, + _CE, + 0, + [], + [] + ]; + exports.CopyObjectOutput$ = [ + 3, + n05, + _COO, + 0, + [_COR, _E2, _CSVI, _VI, _SSE, _SSECA, _SSECKMD, _SSEKMSKI, _SSEKMSEC, _BKE, _RC2], + [[() => exports.CopyObjectResult$, 16], [0, { [_hH2]: _xae }], [0, { [_hH2]: _xacsvi }], [0, { [_hH2]: _xavi }], [0, { [_hH2]: _xasse }], [0, { [_hH2]: _xasseca }], [0, { [_hH2]: _xasseckM }], [() => SSEKMSKeyId, { [_hH2]: _xasseakki }], [() => SSEKMSEncryptionContext, { [_hH2]: _xassec }], [2, { [_hH2]: _xassebke }], [0, { [_hH2]: _xarc }]] + ]; + exports.CopyObjectRequest$ = [ + 3, + n05, + _CORo, + 0, + [_B, _CS2, _K2, _ACL_, _CC, _CA2, _CDo, _CEo, _CL, _CTo, _CSIM, _CSIMS, _CSINM, _CSIUS, _Ex, _GFC, _GR, _GRACP, _GWACP, _IM, _INM, _M, _MD, _TD, _SSE, _SC, _WRL, _SSECA, _SSECK, _SSECKMD, _SSEKMSKI, _SSEKMSEC, _BKE, _CSSSECA, _CSSSECK, _CSSSECKMD, _RP, _Tag, _OLM, _OLRUD, _OLLHS, _EBO, _ESBO], + [[0, 1], [0, { [_hH2]: _xacs__ }], [0, 1], [0, { [_hH2]: _xaa }], [0, { [_hH2]: _CC_ }], [0, { [_hH2]: _xaca }], [0, { [_hH2]: _CD_ }], [0, { [_hH2]: _CE_ }], [0, { [_hH2]: _CL_ }], [0, { [_hH2]: _CT_ }], [0, { [_hH2]: _xacsim }], [4, { [_hH2]: _xacsims }], [0, { [_hH2]: _xacsinm }], [4, { [_hH2]: _xacsius }], [4, { [_hH2]: _Ex }], [0, { [_hH2]: _xagfc }], [0, { [_hH2]: _xagr }], [0, { [_hH2]: _xagra }], [0, { [_hH2]: _xagwa }], [0, { [_hH2]: _IM_ }], [0, { [_hH2]: _INM_ }], [128 | 0, { [_hPH]: _xam }], [0, { [_hH2]: _xamd }], [0, { [_hH2]: _xatd }], [0, { [_hH2]: _xasse }], [0, { [_hH2]: _xasc }], [0, { [_hH2]: _xawrl }], [0, { [_hH2]: _xasseca }], [() => SSECustomerKey, { [_hH2]: _xasseck }], [0, { [_hH2]: _xasseckM }], [() => SSEKMSKeyId, { [_hH2]: _xasseakki }], [() => SSEKMSEncryptionContext, { [_hH2]: _xassec }], [2, { [_hH2]: _xassebke }], [0, { [_hH2]: _xacssseca }], [() => CopySourceSSECustomerKey, { [_hH2]: _xacssseck }], [0, { [_hH2]: _xacssseckM }], [0, { [_hH2]: _xarp }], [0, { [_hH2]: _xat }], [0, { [_hH2]: _xaolm }], [5, { [_hH2]: _xaolrud }], [0, { [_hH2]: _xaollh }], [0, { [_hH2]: _xaebo }], [0, { [_hH2]: _xasebo }]], + 3 + ]; + exports.CopyObjectResult$ = [ + 3, + n05, + _COR, + 0, + [_ETa, _LM, _CT2, _CCRC, _CCRCC, _CCRCNVME, _CSHA, _CSHAh], + [0, 4, 0, 0, 0, 0, 0, 0] + ]; + exports.CopyPartResult$ = [ + 3, + n05, + _CPR, + 0, + [_ETa, _LM, _CCRC, _CCRCC, _CCRCNVME, _CSHA, _CSHAh], + [0, 4, 0, 0, 0, 0, 0] + ]; + exports.CORSConfiguration$ = [ + 3, + n05, + _CORSC, + 0, + [_CORSR], + [[() => CORSRules, { [_xF]: 1, [_xN]: _CORSRu }]], + 1 + ]; + exports.CORSRule$ = [ + 3, + n05, + _CORSRu, + 0, + [_AM, _AO, _ID, _AH, _EH, _MAS], + [[64 | 0, { [_xF]: 1, [_xN]: _AMl }], [64 | 0, { [_xF]: 1, [_xN]: _AOl }], 0, [64 | 0, { [_xF]: 1, [_xN]: _AHl }], [64 | 0, { [_xF]: 1, [_xN]: _EHx }], 1], + 2 + ]; + exports.CreateBucketConfiguration$ = [ + 3, + n05, + _CBC, + 0, + [_LC, _L, _B, _T2], + [0, () => exports.LocationInfo$, () => exports.BucketInfo$, [() => TagSet, 0]] + ]; + exports.CreateBucketMetadataConfigurationRequest$ = [ + 3, + n05, + _CBMCR, + 0, + [_B, _MC, _CMD, _CA2, _EBO], + [[0, 1], [() => exports.MetadataConfiguration$, { [_hP]: 1, [_xN]: _MC }], [0, { [_hH2]: _CM }], [0, { [_hH2]: _xasca }], [0, { [_hH2]: _xaebo }]], + 2 + ]; + exports.CreateBucketMetadataTableConfigurationRequest$ = [ + 3, + n05, + _CBMTCR, + 0, + [_B, _MTC, _CMD, _CA2, _EBO], + [[0, 1], [() => exports.MetadataTableConfiguration$, { [_hP]: 1, [_xN]: _MTC }], [0, { [_hH2]: _CM }], [0, { [_hH2]: _xasca }], [0, { [_hH2]: _xaebo }]], + 2 + ]; + exports.CreateBucketOutput$ = [ + 3, + n05, + _CBO, + 0, + [_L, _BA], + [[0, { [_hH2]: _L }], [0, { [_hH2]: _xaba }]] + ]; + exports.CreateBucketRequest$ = [ + 3, + n05, + _CBR, + 0, + [_B, _ACL_, _CBC, _GFC, _GR, _GRACP, _GW, _GWACP, _OLEFB, _OO, _BN], + [[0, 1], [0, { [_hH2]: _xaa }], [() => exports.CreateBucketConfiguration$, { [_hP]: 1, [_xN]: _CBC }], [0, { [_hH2]: _xagfc }], [0, { [_hH2]: _xagr }], [0, { [_hH2]: _xagra }], [0, { [_hH2]: _xagw }], [0, { [_hH2]: _xagwa }], [2, { [_hH2]: _xabole }], [0, { [_hH2]: _xaoo }], [0, { [_hH2]: _xabn }]], + 1 + ]; + exports.CreateMultipartUploadOutput$ = [ + 3, + n05, + _CMUOr, + { [_xN]: _IMUR }, + [_ADb, _ARI2, _B, _K2, _UI, _SSE, _SSECA, _SSECKMD, _SSEKMSKI, _SSEKMSEC, _BKE, _RC2, _CA2, _CT2], + [[4, { [_hH2]: _xaad }], [0, { [_hH2]: _xaari }], [0, { [_xN]: _B }], 0, 0, [0, { [_hH2]: _xasse }], [0, { [_hH2]: _xasseca }], [0, { [_hH2]: _xasseckM }], [() => SSEKMSKeyId, { [_hH2]: _xasseakki }], [() => SSEKMSEncryptionContext, { [_hH2]: _xassec }], [2, { [_hH2]: _xassebke }], [0, { [_hH2]: _xarc }], [0, { [_hH2]: _xaca }], [0, { [_hH2]: _xact }]] + ]; + exports.CreateMultipartUploadRequest$ = [ + 3, + n05, + _CMURr, + 0, + [_B, _K2, _ACL_, _CC, _CDo, _CEo, _CL, _CTo, _Ex, _GFC, _GR, _GRACP, _GWACP, _M, _SSE, _SC, _WRL, _SSECA, _SSECK, _SSECKMD, _SSEKMSKI, _SSEKMSEC, _BKE, _RP, _Tag, _OLM, _OLRUD, _OLLHS, _EBO, _CA2, _CT2], + [[0, 1], [0, 1], [0, { [_hH2]: _xaa }], [0, { [_hH2]: _CC_ }], [0, { [_hH2]: _CD_ }], [0, { [_hH2]: _CE_ }], [0, { [_hH2]: _CL_ }], [0, { [_hH2]: _CT_ }], [4, { [_hH2]: _Ex }], [0, { [_hH2]: _xagfc }], [0, { [_hH2]: _xagr }], [0, { [_hH2]: _xagra }], [0, { [_hH2]: _xagwa }], [128 | 0, { [_hPH]: _xam }], [0, { [_hH2]: _xasse }], [0, { [_hH2]: _xasc }], [0, { [_hH2]: _xawrl }], [0, { [_hH2]: _xasseca }], [() => SSECustomerKey, { [_hH2]: _xasseck }], [0, { [_hH2]: _xasseckM }], [() => SSEKMSKeyId, { [_hH2]: _xasseakki }], [() => SSEKMSEncryptionContext, { [_hH2]: _xassec }], [2, { [_hH2]: _xassebke }], [0, { [_hH2]: _xarp }], [0, { [_hH2]: _xat }], [0, { [_hH2]: _xaolm }], [5, { [_hH2]: _xaolrud }], [0, { [_hH2]: _xaollh }], [0, { [_hH2]: _xaebo }], [0, { [_hH2]: _xaca }], [0, { [_hH2]: _xact }]], + 2 + ]; + exports.CreateSessionOutput$ = [ + 3, + n05, + _CSO, + { [_xN]: _CSR }, + [_Cr, _SSE, _SSEKMSKI, _SSEKMSEC, _BKE], + [[() => exports.SessionCredentials$, { [_xN]: _Cr }], [0, { [_hH2]: _xasse }], [() => SSEKMSKeyId, { [_hH2]: _xasseakki }], [() => SSEKMSEncryptionContext, { [_hH2]: _xassec }], [2, { [_hH2]: _xassebke }]], + 1 + ]; + exports.CreateSessionRequest$ = [ + 3, + n05, + _CSRr, + 0, + [_B, _SM, _SSE, _SSEKMSKI, _SSEKMSEC, _BKE], + [[0, 1], [0, { [_hH2]: _xacsm }], [0, { [_hH2]: _xasse }], [() => SSEKMSKeyId, { [_hH2]: _xasseakki }], [() => SSEKMSEncryptionContext, { [_hH2]: _xassec }], [2, { [_hH2]: _xassebke }]], + 1 + ]; + exports.CSVInput$ = [ + 3, + n05, + _CSVIn, + 0, + [_FHI, _Com, _QEC, _RD, _FD, _QC, _AQRD], + [0, 0, 0, 0, 0, 0, 2] + ]; + exports.CSVOutput$ = [ + 3, + n05, + _CSVO, + 0, + [_QF, _QEC, _RD, _FD, _QC], + [0, 0, 0, 0, 0] + ]; + exports.DefaultRetention$ = [ + 3, + n05, + _DRe, + 0, + [_Mo, _D, _Y], + [0, 1, 1] + ]; + exports.Delete$ = [ + 3, + n05, + _De, + 0, + [_Ob, _Q], + [[() => ObjectIdentifierList, { [_xF]: 1, [_xN]: _Obj }], 2], + 1 + ]; + exports.DeleteBucketAnalyticsConfigurationRequest$ = [ + 3, + n05, + _DBACR, + 0, + [_B, _I, _EBO], + [[0, 1], [0, { [_hQ2]: _i }], [0, { [_hH2]: _xaebo }]], + 2 + ]; + exports.DeleteBucketCorsRequest$ = [ + 3, + n05, + _DBCR, + 0, + [_B, _EBO], + [[0, 1], [0, { [_hH2]: _xaebo }]], + 1 + ]; + exports.DeleteBucketEncryptionRequest$ = [ + 3, + n05, + _DBER, + 0, + [_B, _EBO], + [[0, 1], [0, { [_hH2]: _xaebo }]], + 1 + ]; + exports.DeleteBucketIntelligentTieringConfigurationRequest$ = [ + 3, + n05, + _DBITCR, + 0, + [_B, _I, _EBO], + [[0, 1], [0, { [_hQ2]: _i }], [0, { [_hH2]: _xaebo }]], + 2 + ]; + exports.DeleteBucketInventoryConfigurationRequest$ = [ + 3, + n05, + _DBICR, + 0, + [_B, _I, _EBO], + [[0, 1], [0, { [_hQ2]: _i }], [0, { [_hH2]: _xaebo }]], + 2 + ]; + exports.DeleteBucketLifecycleRequest$ = [ + 3, + n05, + _DBLR, + 0, + [_B, _EBO], + [[0, 1], [0, { [_hH2]: _xaebo }]], + 1 + ]; + exports.DeleteBucketMetadataConfigurationRequest$ = [ + 3, + n05, + _DBMCR, + 0, + [_B, _EBO], + [[0, 1], [0, { [_hH2]: _xaebo }]], + 1 + ]; + exports.DeleteBucketMetadataTableConfigurationRequest$ = [ + 3, + n05, + _DBMTCR, + 0, + [_B, _EBO], + [[0, 1], [0, { [_hH2]: _xaebo }]], + 1 + ]; + exports.DeleteBucketMetricsConfigurationRequest$ = [ + 3, + n05, + _DBMCRe, + 0, + [_B, _I, _EBO], + [[0, 1], [0, { [_hQ2]: _i }], [0, { [_hH2]: _xaebo }]], + 2 + ]; + exports.DeleteBucketOwnershipControlsRequest$ = [ + 3, + n05, + _DBOCR, + 0, + [_B, _EBO], + [[0, 1], [0, { [_hH2]: _xaebo }]], + 1 + ]; + exports.DeleteBucketPolicyRequest$ = [ + 3, + n05, + _DBPR, + 0, + [_B, _EBO], + [[0, 1], [0, { [_hH2]: _xaebo }]], + 1 + ]; + exports.DeleteBucketReplicationRequest$ = [ + 3, + n05, + _DBRR, + 0, + [_B, _EBO], + [[0, 1], [0, { [_hH2]: _xaebo }]], + 1 + ]; + exports.DeleteBucketRequest$ = [ + 3, + n05, + _DBR, + 0, + [_B, _EBO], + [[0, 1], [0, { [_hH2]: _xaebo }]], + 1 + ]; + exports.DeleteBucketTaggingRequest$ = [ + 3, + n05, + _DBTR, + 0, + [_B, _EBO], + [[0, 1], [0, { [_hH2]: _xaebo }]], + 1 + ]; + exports.DeleteBucketWebsiteRequest$ = [ + 3, + n05, + _DBWR, + 0, + [_B, _EBO], + [[0, 1], [0, { [_hH2]: _xaebo }]], + 1 + ]; + exports.DeletedObject$ = [ + 3, + n05, + _DO, + 0, + [_K2, _VI, _DM, _DMVI], + [0, 0, 2, 0] + ]; + exports.DeleteMarkerEntry$ = [ + 3, + n05, + _DME, + 0, + [_O, _K2, _VI, _IL, _LM], + [() => exports.Owner$, 0, 0, 2, 4] + ]; + exports.DeleteMarkerReplication$ = [ + 3, + n05, + _DMR, + 0, + [_S], + [0] + ]; + exports.DeleteObjectOutput$ = [ + 3, + n05, + _DOO, + 0, + [_DM, _VI, _RC2], + [[2, { [_hH2]: _xadm }], [0, { [_hH2]: _xavi }], [0, { [_hH2]: _xarc }]] + ]; + exports.DeleteObjectRequest$ = [ + 3, + n05, + _DOR, + 0, + [_B, _K2, _MFA, _VI, _RP, _BGR, _EBO, _IM, _IMLMT, _IMS], + [[0, 1], [0, 1], [0, { [_hH2]: _xam_ }], [0, { [_hQ2]: _vI }], [0, { [_hH2]: _xarp }], [2, { [_hH2]: _xabgr }], [0, { [_hH2]: _xaebo }], [0, { [_hH2]: _IM_ }], [6, { [_hH2]: _xaimlmt }], [1, { [_hH2]: _xaims }]], + 2 + ]; + exports.DeleteObjectsOutput$ = [ + 3, + n05, + _DOOe, + { [_xN]: _DRel }, + [_Del, _RC2, _Er], + [[() => DeletedObjects, { [_xF]: 1 }], [0, { [_hH2]: _xarc }], [() => Errors2, { [_xF]: 1, [_xN]: _Err }]] + ]; + exports.DeleteObjectsRequest$ = [ + 3, + n05, + _DORe, + 0, + [_B, _De, _MFA, _RP, _BGR, _EBO, _CA2], + [[0, 1], [() => exports.Delete$, { [_hP]: 1, [_xN]: _De }], [0, { [_hH2]: _xam_ }], [0, { [_hH2]: _xarp }], [2, { [_hH2]: _xabgr }], [0, { [_hH2]: _xaebo }], [0, { [_hH2]: _xasca }]], + 2 + ]; + exports.DeleteObjectTaggingOutput$ = [ + 3, + n05, + _DOTO, + 0, + [_VI], + [[0, { [_hH2]: _xavi }]] + ]; + exports.DeleteObjectTaggingRequest$ = [ + 3, + n05, + _DOTR, + 0, + [_B, _K2, _VI, _EBO], + [[0, 1], [0, 1], [0, { [_hQ2]: _vI }], [0, { [_hH2]: _xaebo }]], + 2 + ]; + exports.DeletePublicAccessBlockRequest$ = [ + 3, + n05, + _DPABR, + 0, + [_B, _EBO], + [[0, 1], [0, { [_hH2]: _xaebo }]], + 1 + ]; + exports.Destination$ = [ + 3, + n05, + _Des, + 0, + [_B, _A2, _SC, _ACT, _EC, _RT3, _Me], + [0, 0, 0, () => exports.AccessControlTranslation$, () => exports.EncryptionConfiguration$, () => exports.ReplicationTime$, () => exports.Metrics$], + 1 + ]; + exports.DestinationResult$ = [ + 3, + n05, + _DRes, + 0, + [_TBT, _TBA, _TN], + [0, 0, 0] + ]; + exports.Encryption$ = [ + 3, + n05, + _En, + 0, + [_ET, _KMSKI, _KMSC], + [0, [() => SSEKMSKeyId, 0], 0], + 1 + ]; + exports.EncryptionConfiguration$ = [ + 3, + n05, + _EC, + 0, + [_RKKID], + [0] + ]; + exports.EndEvent$ = [ + 3, + n05, + _EE, + 0, + [], + [] + ]; + exports._Error$ = [ + 3, + n05, + _Err, + 0, + [_K2, _VI, _Cod, _Mes], + [0, 0, 0, 0] + ]; + exports.ErrorDetails$ = [ + 3, + n05, + _ED, + 0, + [_ECr, _EM], + [0, 0] + ]; + exports.ErrorDocument$ = [ + 3, + n05, + _EDr, + 0, + [_K2], + [0], + 1 + ]; + exports.EventBridgeConfiguration$ = [ + 3, + n05, + _EBC, + 0, + [], + [] + ]; + exports.ExistingObjectReplication$ = [ + 3, + n05, + _EOR, + 0, + [_S], + [0], + 1 + ]; + exports.FilterRule$ = [ + 3, + n05, + _FR, + 0, + [_N, _V2], + [0, 0] + ]; + exports.GetBucketAbacOutput$ = [ + 3, + n05, + _GBAO, + 0, + [_AS], + [[() => exports.AbacStatus$, 16]] + ]; + exports.GetBucketAbacRequest$ = [ + 3, + n05, + _GBAR, + 0, + [_B, _EBO], + [[0, 1], [0, { [_hH2]: _xaebo }]], + 1 + ]; + exports.GetBucketAccelerateConfigurationOutput$ = [ + 3, + n05, + _GBACO, + { [_xN]: _AC }, + [_S, _RC2], + [0, [0, { [_hH2]: _xarc }]] + ]; + exports.GetBucketAccelerateConfigurationRequest$ = [ + 3, + n05, + _GBACR, + 0, + [_B, _EBO, _RP], + [[0, 1], [0, { [_hH2]: _xaebo }], [0, { [_hH2]: _xarp }]], + 1 + ]; + exports.GetBucketAclOutput$ = [ + 3, + n05, + _GBAOe, + { [_xN]: _ACP }, + [_O, _G], + [() => exports.Owner$, [() => Grants, { [_xN]: _ACL }]] + ]; + exports.GetBucketAclRequest$ = [ + 3, + n05, + _GBARe, + 0, + [_B, _EBO], + [[0, 1], [0, { [_hH2]: _xaebo }]], + 1 + ]; + exports.GetBucketAnalyticsConfigurationOutput$ = [ + 3, + n05, + _GBACOe, + 0, + [_ACn], + [[() => exports.AnalyticsConfiguration$, 16]] + ]; + exports.GetBucketAnalyticsConfigurationRequest$ = [ + 3, + n05, + _GBACRe, + 0, + [_B, _I, _EBO], + [[0, 1], [0, { [_hQ2]: _i }], [0, { [_hH2]: _xaebo }]], + 2 + ]; + exports.GetBucketCorsOutput$ = [ + 3, + n05, + _GBCO, + { [_xN]: _CORSC }, + [_CORSR], + [[() => CORSRules, { [_xF]: 1, [_xN]: _CORSRu }]] + ]; + exports.GetBucketCorsRequest$ = [ + 3, + n05, + _GBCR, + 0, + [_B, _EBO], + [[0, 1], [0, { [_hH2]: _xaebo }]], + 1 + ]; + exports.GetBucketEncryptionOutput$ = [ + 3, + n05, + _GBEO, + 0, + [_SSEC], + [[() => exports.ServerSideEncryptionConfiguration$, 16]] + ]; + exports.GetBucketEncryptionRequest$ = [ + 3, + n05, + _GBER, + 0, + [_B, _EBO], + [[0, 1], [0, { [_hH2]: _xaebo }]], + 1 + ]; + exports.GetBucketIntelligentTieringConfigurationOutput$ = [ + 3, + n05, + _GBITCO, + 0, + [_ITC], + [[() => exports.IntelligentTieringConfiguration$, 16]] + ]; + exports.GetBucketIntelligentTieringConfigurationRequest$ = [ + 3, + n05, + _GBITCR, + 0, + [_B, _I, _EBO], + [[0, 1], [0, { [_hQ2]: _i }], [0, { [_hH2]: _xaebo }]], + 2 + ]; + exports.GetBucketInventoryConfigurationOutput$ = [ + 3, + n05, + _GBICO, + 0, + [_IC], + [[() => exports.InventoryConfiguration$, 16]] + ]; + exports.GetBucketInventoryConfigurationRequest$ = [ + 3, + n05, + _GBICR, + 0, + [_B, _I, _EBO], + [[0, 1], [0, { [_hQ2]: _i }], [0, { [_hH2]: _xaebo }]], + 2 + ]; + exports.GetBucketLifecycleConfigurationOutput$ = [ + 3, + n05, + _GBLCO, + { [_xN]: _LCi }, + [_R, _TDMOS], + [[() => LifecycleRules, { [_xF]: 1, [_xN]: _Ru }], [0, { [_hH2]: _xatdmos }]] + ]; + exports.GetBucketLifecycleConfigurationRequest$ = [ + 3, + n05, + _GBLCR, + 0, + [_B, _EBO], + [[0, 1], [0, { [_hH2]: _xaebo }]], + 1 + ]; + exports.GetBucketLocationOutput$ = [ + 3, + n05, + _GBLO, + { [_xN]: _LC }, + [_LC], + [0] + ]; + exports.GetBucketLocationRequest$ = [ + 3, + n05, + _GBLR, + 0, + [_B, _EBO], + [[0, 1], [0, { [_hH2]: _xaebo }]], + 1 + ]; + exports.GetBucketLoggingOutput$ = [ + 3, + n05, + _GBLOe, + { [_xN]: _BLS }, + [_LE], + [[() => exports.LoggingEnabled$, 0]] + ]; + exports.GetBucketLoggingRequest$ = [ + 3, + n05, + _GBLRe, + 0, + [_B, _EBO], + [[0, 1], [0, { [_hH2]: _xaebo }]], + 1 + ]; + exports.GetBucketMetadataConfigurationOutput$ = [ + 3, + n05, + _GBMCO, + 0, + [_GBMCR], + [[() => exports.GetBucketMetadataConfigurationResult$, 16]] + ]; + exports.GetBucketMetadataConfigurationRequest$ = [ + 3, + n05, + _GBMCRe, + 0, + [_B, _EBO], + [[0, 1], [0, { [_hH2]: _xaebo }]], + 1 + ]; + exports.GetBucketMetadataConfigurationResult$ = [ + 3, + n05, + _GBMCR, + 0, + [_MCR], + [() => exports.MetadataConfigurationResult$], + 1 + ]; + exports.GetBucketMetadataTableConfigurationOutput$ = [ + 3, + n05, + _GBMTCO, + 0, + [_GBMTCR], + [[() => exports.GetBucketMetadataTableConfigurationResult$, 16]] + ]; + exports.GetBucketMetadataTableConfigurationRequest$ = [ + 3, + n05, + _GBMTCRe, + 0, + [_B, _EBO], + [[0, 1], [0, { [_hH2]: _xaebo }]], + 1 + ]; + exports.GetBucketMetadataTableConfigurationResult$ = [ + 3, + n05, + _GBMTCR, + 0, + [_MTCR, _S, _Err], + [() => exports.MetadataTableConfigurationResult$, 0, () => exports.ErrorDetails$], + 2 + ]; + exports.GetBucketMetricsConfigurationOutput$ = [ + 3, + n05, + _GBMCOe, + 0, + [_MCe], + [[() => exports.MetricsConfiguration$, 16]] + ]; + exports.GetBucketMetricsConfigurationRequest$ = [ + 3, + n05, + _GBMCRet, + 0, + [_B, _I, _EBO], + [[0, 1], [0, { [_hQ2]: _i }], [0, { [_hH2]: _xaebo }]], + 2 + ]; + exports.GetBucketNotificationConfigurationRequest$ = [ + 3, + n05, + _GBNCR, + 0, + [_B, _EBO], + [[0, 1], [0, { [_hH2]: _xaebo }]], + 1 + ]; + exports.GetBucketOwnershipControlsOutput$ = [ + 3, + n05, + _GBOCO, + 0, + [_OC], + [[() => exports.OwnershipControls$, 16]] + ]; + exports.GetBucketOwnershipControlsRequest$ = [ + 3, + n05, + _GBOCR, + 0, + [_B, _EBO], + [[0, 1], [0, { [_hH2]: _xaebo }]], + 1 + ]; + exports.GetBucketPolicyOutput$ = [ + 3, + n05, + _GBPO, + 0, + [_Po], + [[0, 16]] + ]; + exports.GetBucketPolicyRequest$ = [ + 3, + n05, + _GBPR, + 0, + [_B, _EBO], + [[0, 1], [0, { [_hH2]: _xaebo }]], + 1 + ]; + exports.GetBucketPolicyStatusOutput$ = [ + 3, + n05, + _GBPSO, + 0, + [_PS], + [[() => exports.PolicyStatus$, 16]] + ]; + exports.GetBucketPolicyStatusRequest$ = [ + 3, + n05, + _GBPSR, + 0, + [_B, _EBO], + [[0, 1], [0, { [_hH2]: _xaebo }]], + 1 + ]; + exports.GetBucketReplicationOutput$ = [ + 3, + n05, + _GBRO, + 0, + [_RCe], + [[() => exports.ReplicationConfiguration$, 16]] + ]; + exports.GetBucketReplicationRequest$ = [ + 3, + n05, + _GBRR, + 0, + [_B, _EBO], + [[0, 1], [0, { [_hH2]: _xaebo }]], + 1 + ]; + exports.GetBucketRequestPaymentOutput$ = [ + 3, + n05, + _GBRPO, + { [_xN]: _RPC }, + [_Pay], + [0] + ]; + exports.GetBucketRequestPaymentRequest$ = [ + 3, + n05, + _GBRPR, + 0, + [_B, _EBO], + [[0, 1], [0, { [_hH2]: _xaebo }]], + 1 + ]; + exports.GetBucketTaggingOutput$ = [ + 3, + n05, + _GBTO, + { [_xN]: _Tag }, + [_TS], + [[() => TagSet, 0]], + 1 + ]; + exports.GetBucketTaggingRequest$ = [ + 3, + n05, + _GBTR, + 0, + [_B, _EBO], + [[0, 1], [0, { [_hH2]: _xaebo }]], + 1 + ]; + exports.GetBucketVersioningOutput$ = [ + 3, + n05, + _GBVO, + { [_xN]: _VC }, + [_S, _MFAD], + [0, [0, { [_xN]: _MDf }]] + ]; + exports.GetBucketVersioningRequest$ = [ + 3, + n05, + _GBVR, + 0, + [_B, _EBO], + [[0, 1], [0, { [_hH2]: _xaebo }]], + 1 + ]; + exports.GetBucketWebsiteOutput$ = [ + 3, + n05, + _GBWO, + { [_xN]: _WC }, + [_RART, _IDn, _EDr, _RR], + [() => exports.RedirectAllRequestsTo$, () => exports.IndexDocument$, () => exports.ErrorDocument$, [() => RoutingRules, 0]] + ]; + exports.GetBucketWebsiteRequest$ = [ + 3, + n05, + _GBWR, + 0, + [_B, _EBO], + [[0, 1], [0, { [_hH2]: _xaebo }]], + 1 + ]; + exports.GetObjectAclOutput$ = [ + 3, + n05, + _GOAO, + { [_xN]: _ACP }, + [_O, _G, _RC2], + [() => exports.Owner$, [() => Grants, { [_xN]: _ACL }], [0, { [_hH2]: _xarc }]] + ]; + exports.GetObjectAclRequest$ = [ + 3, + n05, + _GOAR, + 0, + [_B, _K2, _VI, _RP, _EBO], + [[0, 1], [0, 1], [0, { [_hQ2]: _vI }], [0, { [_hH2]: _xarp }], [0, { [_hH2]: _xaebo }]], + 2 + ]; + exports.GetObjectAttributesOutput$ = [ + 3, + n05, + _GOAOe, + { [_xN]: _GOARe }, + [_DM, _LM, _VI, _RC2, _ETa, _C2, _OP, _SC, _OS], + [[2, { [_hH2]: _xadm }], [4, { [_hH2]: _LM_ }], [0, { [_hH2]: _xavi }], [0, { [_hH2]: _xarc }], 0, () => exports.Checksum$, [() => exports.GetObjectAttributesParts$, 0], 0, 1] + ]; + exports.GetObjectAttributesParts$ = [ + 3, + n05, + _GOAP, + 0, + [_TPC, _PNM, _NPNM, _MP, _IT2, _Pa], + [[1, { [_xN]: _PC2 }], 0, 0, 1, 2, [() => PartsList, { [_xF]: 1, [_xN]: _Par }]] + ]; + exports.GetObjectAttributesRequest$ = [ + 3, + n05, + _GOARet, + 0, + [_B, _K2, _OA, _VI, _MP, _PNM, _SSECA, _SSECK, _SSECKMD, _RP, _EBO], + [[0, 1], [0, 1], [64 | 0, { [_hH2]: _xaoa }], [0, { [_hQ2]: _vI }], [1, { [_hH2]: _xamp }], [0, { [_hH2]: _xapnm }], [0, { [_hH2]: _xasseca }], [() => SSECustomerKey, { [_hH2]: _xasseck }], [0, { [_hH2]: _xasseckM }], [0, { [_hH2]: _xarp }], [0, { [_hH2]: _xaebo }]], + 3 + ]; + exports.GetObjectLegalHoldOutput$ = [ + 3, + n05, + _GOLHO, + 0, + [_LH], + [[() => exports.ObjectLockLegalHold$, { [_hP]: 1, [_xN]: _LH }]] + ]; + exports.GetObjectLegalHoldRequest$ = [ + 3, + n05, + _GOLHR, + 0, + [_B, _K2, _VI, _RP, _EBO], + [[0, 1], [0, 1], [0, { [_hQ2]: _vI }], [0, { [_hH2]: _xarp }], [0, { [_hH2]: _xaebo }]], + 2 + ]; + exports.GetObjectLockConfigurationOutput$ = [ + 3, + n05, + _GOLCO, + 0, + [_OLC], + [[() => exports.ObjectLockConfiguration$, 16]] + ]; + exports.GetObjectLockConfigurationRequest$ = [ + 3, + n05, + _GOLCR, + 0, + [_B, _EBO], + [[0, 1], [0, { [_hH2]: _xaebo }]], + 1 + ]; + exports.GetObjectOutput$ = [ + 3, + n05, + _GOO, + 0, + [_Bo, _DM, _AR2, _E2, _Re, _LM, _CLo, _ETa, _CCRC, _CCRCC, _CCRCNVME, _CSHA, _CSHAh, _CT2, _MM, _VI, _CC, _CDo, _CEo, _CL, _CR, _CTo, _Ex, _ES, _WRL, _SSE, _M, _SSECA, _SSECKMD, _SSEKMSKI, _BKE, _SC, _RC2, _RS, _PC2, _TC2, _OLM, _OLRUD, _OLLHS], + [[() => StreamingBlob, 16], [2, { [_hH2]: _xadm }], [0, { [_hH2]: _ar }], [0, { [_hH2]: _xae }], [0, { [_hH2]: _xar }], [4, { [_hH2]: _LM_ }], [1, { [_hH2]: _CL__ }], [0, { [_hH2]: _ETa }], [0, { [_hH2]: _xacc }], [0, { [_hH2]: _xacc_ }], [0, { [_hH2]: _xacc__ }], [0, { [_hH2]: _xacs }], [0, { [_hH2]: _xacs_ }], [0, { [_hH2]: _xact }], [1, { [_hH2]: _xamm }], [0, { [_hH2]: _xavi }], [0, { [_hH2]: _CC_ }], [0, { [_hH2]: _CD_ }], [0, { [_hH2]: _CE_ }], [0, { [_hH2]: _CL_ }], [0, { [_hH2]: _CR_ }], [0, { [_hH2]: _CT_ }], [4, { [_hH2]: _Ex }], [0, { [_hH2]: _ES }], [0, { [_hH2]: _xawrl }], [0, { [_hH2]: _xasse }], [128 | 0, { [_hPH]: _xam }], [0, { [_hH2]: _xasseca }], [0, { [_hH2]: _xasseckM }], [() => SSEKMSKeyId, { [_hH2]: _xasseakki }], [2, { [_hH2]: _xassebke }], [0, { [_hH2]: _xasc }], [0, { [_hH2]: _xarc }], [0, { [_hH2]: _xars }], [1, { [_hH2]: _xampc }], [1, { [_hH2]: _xatc }], [0, { [_hH2]: _xaolm }], [5, { [_hH2]: _xaolrud }], [0, { [_hH2]: _xaollh }]] + ]; + exports.GetObjectRequest$ = [ + 3, + n05, + _GOR, + 0, + [_B, _K2, _IM, _IMSf, _INM, _IUS, _Ra, _RCC, _RCD, _RCE, _RCL, _RCT, _RE, _VI, _SSECA, _SSECK, _SSECKMD, _RP, _PN, _EBO, _CMh], + [[0, 1], [0, 1], [0, { [_hH2]: _IM_ }], [4, { [_hH2]: _IMS_ }], [0, { [_hH2]: _INM_ }], [4, { [_hH2]: _IUS_ }], [0, { [_hH2]: _Ra }], [0, { [_hQ2]: _rcc }], [0, { [_hQ2]: _rcd }], [0, { [_hQ2]: _rce }], [0, { [_hQ2]: _rcl }], [0, { [_hQ2]: _rct }], [6, { [_hQ2]: _re }], [0, { [_hQ2]: _vI }], [0, { [_hH2]: _xasseca }], [() => SSECustomerKey, { [_hH2]: _xasseck }], [0, { [_hH2]: _xasseckM }], [0, { [_hH2]: _xarp }], [1, { [_hQ2]: _pN }], [0, { [_hH2]: _xaebo }], [0, { [_hH2]: _xacm }]], + 2 + ]; + exports.GetObjectRetentionOutput$ = [ + 3, + n05, + _GORO, + 0, + [_Ret], + [[() => exports.ObjectLockRetention$, { [_hP]: 1, [_xN]: _Ret }]] + ]; + exports.GetObjectRetentionRequest$ = [ + 3, + n05, + _GORR, + 0, + [_B, _K2, _VI, _RP, _EBO], + [[0, 1], [0, 1], [0, { [_hQ2]: _vI }], [0, { [_hH2]: _xarp }], [0, { [_hH2]: _xaebo }]], + 2 + ]; + exports.GetObjectTaggingOutput$ = [ + 3, + n05, + _GOTO, + { [_xN]: _Tag }, + [_TS, _VI], + [[() => TagSet, 0], [0, { [_hH2]: _xavi }]], + 1 + ]; + exports.GetObjectTaggingRequest$ = [ + 3, + n05, + _GOTR, + 0, + [_B, _K2, _VI, _EBO, _RP], + [[0, 1], [0, 1], [0, { [_hQ2]: _vI }], [0, { [_hH2]: _xaebo }], [0, { [_hH2]: _xarp }]], + 2 + ]; + exports.GetObjectTorrentOutput$ = [ + 3, + n05, + _GOTOe, + 0, + [_Bo, _RC2], + [[() => StreamingBlob, 16], [0, { [_hH2]: _xarc }]] + ]; + exports.GetObjectTorrentRequest$ = [ + 3, + n05, + _GOTRe, + 0, + [_B, _K2, _RP, _EBO], + [[0, 1], [0, 1], [0, { [_hH2]: _xarp }], [0, { [_hH2]: _xaebo }]], + 2 + ]; + exports.GetPublicAccessBlockOutput$ = [ + 3, + n05, + _GPABO, + 0, + [_PABC], + [[() => exports.PublicAccessBlockConfiguration$, 16]] + ]; + exports.GetPublicAccessBlockRequest$ = [ + 3, + n05, + _GPABR, + 0, + [_B, _EBO], + [[0, 1], [0, { [_hH2]: _xaebo }]], + 1 + ]; + exports.GlacierJobParameters$ = [ + 3, + n05, + _GJP, + 0, + [_Ti], + [0], + 1 + ]; + exports.Grant$ = [ + 3, + n05, + _Gr, + 0, + [_Gra, _Pe], + [[() => exports.Grantee$, { [_xNm]: [_x, _hi] }], 0] + ]; + exports.Grantee$ = [ + 3, + n05, + _Gra, + 0, + [_Ty, _DN, _EA, _ID, _URI], + [[0, { [_xA]: 1, [_xN]: _xs }], 0, 0, 0, 0], + 1 + ]; + exports.HeadBucketOutput$ = [ + 3, + n05, + _HBO, + 0, + [_BA, _BLT, _BLN, _BR, _APA], + [[0, { [_hH2]: _xaba }], [0, { [_hH2]: _xablt }], [0, { [_hH2]: _xabln }], [0, { [_hH2]: _xabr }], [2, { [_hH2]: _xaapa }]] + ]; + exports.HeadBucketRequest$ = [ + 3, + n05, + _HBR, + 0, + [_B, _EBO], + [[0, 1], [0, { [_hH2]: _xaebo }]], + 1 + ]; + exports.HeadObjectOutput$ = [ + 3, + n05, + _HOO, + 0, + [_DM, _AR2, _E2, _Re, _ASr, _LM, _CLo, _CCRC, _CCRCC, _CCRCNVME, _CSHA, _CSHAh, _CT2, _ETa, _MM, _VI, _CC, _CDo, _CEo, _CL, _CTo, _CR, _Ex, _ES, _WRL, _SSE, _M, _SSECA, _SSECKMD, _SSEKMSKI, _BKE, _SC, _RC2, _RS, _PC2, _TC2, _OLM, _OLRUD, _OLLHS], + [[2, { [_hH2]: _xadm }], [0, { [_hH2]: _ar }], [0, { [_hH2]: _xae }], [0, { [_hH2]: _xar }], [0, { [_hH2]: _xaas }], [4, { [_hH2]: _LM_ }], [1, { [_hH2]: _CL__ }], [0, { [_hH2]: _xacc }], [0, { [_hH2]: _xacc_ }], [0, { [_hH2]: _xacc__ }], [0, { [_hH2]: _xacs }], [0, { [_hH2]: _xacs_ }], [0, { [_hH2]: _xact }], [0, { [_hH2]: _ETa }], [1, { [_hH2]: _xamm }], [0, { [_hH2]: _xavi }], [0, { [_hH2]: _CC_ }], [0, { [_hH2]: _CD_ }], [0, { [_hH2]: _CE_ }], [0, { [_hH2]: _CL_ }], [0, { [_hH2]: _CT_ }], [0, { [_hH2]: _CR_ }], [4, { [_hH2]: _Ex }], [0, { [_hH2]: _ES }], [0, { [_hH2]: _xawrl }], [0, { [_hH2]: _xasse }], [128 | 0, { [_hPH]: _xam }], [0, { [_hH2]: _xasseca }], [0, { [_hH2]: _xasseckM }], [() => SSEKMSKeyId, { [_hH2]: _xasseakki }], [2, { [_hH2]: _xassebke }], [0, { [_hH2]: _xasc }], [0, { [_hH2]: _xarc }], [0, { [_hH2]: _xars }], [1, { [_hH2]: _xampc }], [1, { [_hH2]: _xatc }], [0, { [_hH2]: _xaolm }], [5, { [_hH2]: _xaolrud }], [0, { [_hH2]: _xaollh }]] + ]; + exports.HeadObjectRequest$ = [ + 3, + n05, + _HOR, + 0, + [_B, _K2, _IM, _IMSf, _INM, _IUS, _Ra, _RCC, _RCD, _RCE, _RCL, _RCT, _RE, _VI, _SSECA, _SSECK, _SSECKMD, _RP, _PN, _EBO, _CMh], + [[0, 1], [0, 1], [0, { [_hH2]: _IM_ }], [4, { [_hH2]: _IMS_ }], [0, { [_hH2]: _INM_ }], [4, { [_hH2]: _IUS_ }], [0, { [_hH2]: _Ra }], [0, { [_hQ2]: _rcc }], [0, { [_hQ2]: _rcd }], [0, { [_hQ2]: _rce }], [0, { [_hQ2]: _rcl }], [0, { [_hQ2]: _rct }], [6, { [_hQ2]: _re }], [0, { [_hQ2]: _vI }], [0, { [_hH2]: _xasseca }], [() => SSECustomerKey, { [_hH2]: _xasseck }], [0, { [_hH2]: _xasseckM }], [0, { [_hH2]: _xarp }], [1, { [_hQ2]: _pN }], [0, { [_hH2]: _xaebo }], [0, { [_hH2]: _xacm }]], + 2 + ]; + exports.IndexDocument$ = [ + 3, + n05, + _IDn, + 0, + [_Su], + [0], + 1 + ]; + exports.Initiator$ = [ + 3, + n05, + _In, + 0, + [_ID, _DN], + [0, 0] + ]; + exports.InputSerialization$ = [ + 3, + n05, + _IS, + 0, + [_CSV, _CTom, _JSON, _Parq], + [() => exports.CSVInput$, 0, () => exports.JSONInput$, () => exports.ParquetInput$] + ]; + exports.IntelligentTieringAndOperator$ = [ + 3, + n05, + _ITAO, + 0, + [_P2, _T2], + [0, [() => TagSet, { [_xF]: 1, [_xN]: _Ta2 }]] + ]; + exports.IntelligentTieringConfiguration$ = [ + 3, + n05, + _ITC, + 0, + [_I, _S, _Tie, _F], + [0, 0, [() => TieringList, { [_xF]: 1, [_xN]: _Tier }], [() => exports.IntelligentTieringFilter$, 0]], + 3 + ]; + exports.IntelligentTieringFilter$ = [ + 3, + n05, + _ITF, + 0, + [_P2, _Ta2, _An], + [0, () => exports.Tag$, [() => exports.IntelligentTieringAndOperator$, 0]] + ]; + exports.InventoryConfiguration$ = [ + 3, + n05, + _IC, + 0, + [_Des, _IE, _I, _IOV, _Sc, _F, _OF], + [[() => exports.InventoryDestination$, 0], 2, 0, 0, () => exports.InventorySchedule$, () => exports.InventoryFilter$, [() => InventoryOptionalFields, 0]], + 5 + ]; + exports.InventoryDestination$ = [ + 3, + n05, + _IDnv, + 0, + [_SBD], + [[() => exports.InventoryS3BucketDestination$, 0]], + 1 + ]; + exports.InventoryEncryption$ = [ + 3, + n05, + _IEn, + 0, + [_SSES, _SSEKMS], + [[() => exports.SSES3$, { [_xN]: _SS }], [() => exports.SSEKMS$, { [_xN]: _SK }]] + ]; + exports.InventoryFilter$ = [ + 3, + n05, + _IF, + 0, + [_P2], + [0], + 1 + ]; + exports.InventoryS3BucketDestination$ = [ + 3, + n05, + _ISBD, + 0, + [_B, _Fo, _AI, _P2, _En], + [0, 0, 0, 0, [() => exports.InventoryEncryption$, 0]], + 2 + ]; + exports.InventorySchedule$ = [ + 3, + n05, + _ISn, + 0, + [_Fr], + [0], + 1 + ]; + exports.InventoryTableConfiguration$ = [ + 3, + n05, + _ITCn, + 0, + [_CSo, _EC], + [0, () => exports.MetadataTableEncryptionConfiguration$], + 1 + ]; + exports.InventoryTableConfigurationResult$ = [ + 3, + n05, + _ITCR, + 0, + [_CSo, _TSa, _Err, _TNa, _TA], + [0, 0, () => exports.ErrorDetails$, 0, 0], + 1 + ]; + exports.InventoryTableConfigurationUpdates$ = [ + 3, + n05, + _ITCU, + 0, + [_CSo, _EC], + [0, () => exports.MetadataTableEncryptionConfiguration$], + 1 + ]; + exports.JournalTableConfiguration$ = [ + 3, + n05, + _JTC, + 0, + [_REe, _EC], + [() => exports.RecordExpiration$, () => exports.MetadataTableEncryptionConfiguration$], + 1 + ]; + exports.JournalTableConfigurationResult$ = [ + 3, + n05, + _JTCR, + 0, + [_TSa, _TNa, _REe, _Err, _TA], + [0, 0, () => exports.RecordExpiration$, () => exports.ErrorDetails$, 0], + 3 + ]; + exports.JournalTableConfigurationUpdates$ = [ + 3, + n05, + _JTCU, + 0, + [_REe], + [() => exports.RecordExpiration$], + 1 + ]; + exports.JSONInput$ = [ + 3, + n05, + _JSONI, + 0, + [_Ty], + [0] + ]; + exports.JSONOutput$ = [ + 3, + n05, + _JSONO, + 0, + [_RD], + [0] + ]; + exports.LambdaFunctionConfiguration$ = [ + 3, + n05, + _LFC, + 0, + [_LFA, _Ev, _I, _F], + [[0, { [_xN]: _CF }], [64 | 0, { [_xF]: 1, [_xN]: _Eve }], 0, [() => exports.NotificationConfigurationFilter$, 0]], + 2 + ]; + exports.LifecycleExpiration$ = [ + 3, + n05, + _LEi, + 0, + [_Da, _D, _EODM], + [5, 1, 2] + ]; + exports.LifecycleRule$ = [ + 3, + n05, + _LR, + 0, + [_S, _E2, _ID, _P2, _F, _Tr, _NVT, _NVE, _AIMU], + [0, () => exports.LifecycleExpiration$, 0, 0, [() => exports.LifecycleRuleFilter$, 0], [() => TransitionList, { [_xF]: 1, [_xN]: _Tra }], [() => NoncurrentVersionTransitionList, { [_xF]: 1, [_xN]: _NVTo }], () => exports.NoncurrentVersionExpiration$, () => exports.AbortIncompleteMultipartUpload$], + 1 + ]; + exports.LifecycleRuleAndOperator$ = [ + 3, + n05, + _LRAO, + 0, + [_P2, _T2, _OSGT, _OSLT], + [0, [() => TagSet, { [_xF]: 1, [_xN]: _Ta2 }], 1, 1] + ]; + exports.LifecycleRuleFilter$ = [ + 3, + n05, + _LRF, + 0, + [_P2, _Ta2, _OSGT, _OSLT, _An], + [0, () => exports.Tag$, 1, 1, [() => exports.LifecycleRuleAndOperator$, 0]] + ]; + exports.ListBucketAnalyticsConfigurationsOutput$ = [ + 3, + n05, + _LBACO, + { [_xN]: _LBACR }, + [_IT2, _CTon, _NCT, _ACLn], + [2, 0, 0, [() => AnalyticsConfigurationList, { [_xF]: 1, [_xN]: _ACn }]] + ]; + exports.ListBucketAnalyticsConfigurationsRequest$ = [ + 3, + n05, + _LBACRi, + 0, + [_B, _CTon, _EBO], + [[0, 1], [0, { [_hQ2]: _ct }], [0, { [_hH2]: _xaebo }]], + 1 + ]; + exports.ListBucketIntelligentTieringConfigurationsOutput$ = [ + 3, + n05, + _LBITCO, + 0, + [_IT2, _CTon, _NCT, _ITCL], + [2, 0, 0, [() => IntelligentTieringConfigurationList, { [_xF]: 1, [_xN]: _ITC }]] + ]; + exports.ListBucketIntelligentTieringConfigurationsRequest$ = [ + 3, + n05, + _LBITCR, + 0, + [_B, _CTon, _EBO], + [[0, 1], [0, { [_hQ2]: _ct }], [0, { [_hH2]: _xaebo }]], + 1 + ]; + exports.ListBucketInventoryConfigurationsOutput$ = [ + 3, + n05, + _LBICO, + { [_xN]: _LICR }, + [_CTon, _ICL, _IT2, _NCT], + [0, [() => InventoryConfigurationList, { [_xF]: 1, [_xN]: _IC }], 2, 0] + ]; + exports.ListBucketInventoryConfigurationsRequest$ = [ + 3, + n05, + _LBICR, + 0, + [_B, _CTon, _EBO], + [[0, 1], [0, { [_hQ2]: _ct }], [0, { [_hH2]: _xaebo }]], + 1 + ]; + exports.ListBucketMetricsConfigurationsOutput$ = [ + 3, + n05, + _LBMCO, + { [_xN]: _LMCR }, + [_IT2, _CTon, _NCT, _MCL], + [2, 0, 0, [() => MetricsConfigurationList, { [_xF]: 1, [_xN]: _MCe }]] + ]; + exports.ListBucketMetricsConfigurationsRequest$ = [ + 3, + n05, + _LBMCR, + 0, + [_B, _CTon, _EBO], + [[0, 1], [0, { [_hQ2]: _ct }], [0, { [_hH2]: _xaebo }]], + 1 + ]; + exports.ListBucketsOutput$ = [ + 3, + n05, + _LBO, + { [_xN]: _LAMBR }, + [_Bu, _O, _CTon, _P2], + [[() => Buckets, 0], () => exports.Owner$, 0, 0] + ]; + exports.ListBucketsRequest$ = [ + 3, + n05, + _LBR, + 0, + [_MB, _CTon, _P2, _BR], + [[1, { [_hQ2]: _mb }], [0, { [_hQ2]: _ct }], [0, { [_hQ2]: _p }], [0, { [_hQ2]: _br }]] + ]; + exports.ListDirectoryBucketsOutput$ = [ + 3, + n05, + _LDBO, + { [_xN]: _LAMDBR }, + [_Bu, _CTon], + [[() => Buckets, 0], 0] + ]; + exports.ListDirectoryBucketsRequest$ = [ + 3, + n05, + _LDBR, + 0, + [_CTon, _MDB], + [[0, { [_hQ2]: _ct }], [1, { [_hQ2]: _mdb }]] + ]; + exports.ListMultipartUploadsOutput$ = [ + 3, + n05, + _LMUO, + { [_xN]: _LMUR }, + [_B, _KM, _UIM, _NKM, _P2, _Deli, _NUIM, _MUa, _IT2, _U, _CPom, _ETn, _RC2], + [0, 0, 0, 0, 0, 0, 0, 1, 2, [() => MultipartUploadList, { [_xF]: 1, [_xN]: _Up }], [() => CommonPrefixList, { [_xF]: 1 }], 0, [0, { [_hH2]: _xarc }]] + ]; + exports.ListMultipartUploadsRequest$ = [ + 3, + n05, + _LMURi, + 0, + [_B, _Deli, _ETn, _KM, _MUa, _P2, _UIM, _EBO, _RP], + [[0, 1], [0, { [_hQ2]: _d }], [0, { [_hQ2]: _et }], [0, { [_hQ2]: _km }], [1, { [_hQ2]: _mu }], [0, { [_hQ2]: _p }], [0, { [_hQ2]: _uim }], [0, { [_hH2]: _xaebo }], [0, { [_hH2]: _xarp }]], + 1 + ]; + exports.ListObjectsOutput$ = [ + 3, + n05, + _LOO, + { [_xN]: _LBRi }, + [_IT2, _Ma, _NM, _Con, _N, _P2, _Deli, _MK, _CPom, _ETn, _RC2], + [2, 0, 0, [() => ObjectList, { [_xF]: 1 }], 0, 0, 0, 1, [() => CommonPrefixList, { [_xF]: 1 }], 0, [0, { [_hH2]: _xarc }]] + ]; + exports.ListObjectsRequest$ = [ + 3, + n05, + _LOR, + 0, + [_B, _Deli, _ETn, _Ma, _MK, _P2, _RP, _EBO, _OOA], + [[0, 1], [0, { [_hQ2]: _d }], [0, { [_hQ2]: _et }], [0, { [_hQ2]: _m4 }], [1, { [_hQ2]: _mk }], [0, { [_hQ2]: _p }], [0, { [_hH2]: _xarp }], [0, { [_hH2]: _xaebo }], [64 | 0, { [_hH2]: _xaooa }]], + 1 + ]; + exports.ListObjectsV2Output$ = [ + 3, + n05, + _LOVO, + { [_xN]: _LBRi }, + [_IT2, _Con, _N, _P2, _Deli, _MK, _CPom, _ETn, _KC, _CTon, _NCT, _SA, _RC2], + [2, [() => ObjectList, { [_xF]: 1 }], 0, 0, 0, 1, [() => CommonPrefixList, { [_xF]: 1 }], 0, 1, 0, 0, 0, [0, { [_hH2]: _xarc }]] + ]; + exports.ListObjectsV2Request$ = [ + 3, + n05, + _LOVR, + 0, + [_B, _Deli, _ETn, _MK, _P2, _CTon, _FO, _SA, _RP, _EBO, _OOA], + [[0, 1], [0, { [_hQ2]: _d }], [0, { [_hQ2]: _et }], [1, { [_hQ2]: _mk }], [0, { [_hQ2]: _p }], [0, { [_hQ2]: _ct }], [2, { [_hQ2]: _fo }], [0, { [_hQ2]: _sa }], [0, { [_hH2]: _xarp }], [0, { [_hH2]: _xaebo }], [64 | 0, { [_hH2]: _xaooa }]], + 1 + ]; + exports.ListObjectVersionsOutput$ = [ + 3, + n05, + _LOVOi, + { [_xN]: _LVR }, + [_IT2, _KM, _VIM, _NKM, _NVIM, _Ve, _DMe, _N, _P2, _Deli, _MK, _CPom, _ETn, _RC2], + [2, 0, 0, 0, 0, [() => ObjectVersionList, { [_xF]: 1, [_xN]: _Ver }], [() => DeleteMarkers, { [_xF]: 1, [_xN]: _DM }], 0, 0, 0, 1, [() => CommonPrefixList, { [_xF]: 1 }], 0, [0, { [_hH2]: _xarc }]] + ]; + exports.ListObjectVersionsRequest$ = [ + 3, + n05, + _LOVRi, + 0, + [_B, _Deli, _ETn, _KM, _MK, _P2, _VIM, _EBO, _RP, _OOA], + [[0, 1], [0, { [_hQ2]: _d }], [0, { [_hQ2]: _et }], [0, { [_hQ2]: _km }], [1, { [_hQ2]: _mk }], [0, { [_hQ2]: _p }], [0, { [_hQ2]: _vim }], [0, { [_hH2]: _xaebo }], [0, { [_hH2]: _xarp }], [64 | 0, { [_hH2]: _xaooa }]], + 1 + ]; + exports.ListPartsOutput$ = [ + 3, + n05, + _LPO, + { [_xN]: _LPR }, + [_ADb, _ARI2, _B, _K2, _UI, _PNM, _NPNM, _MP, _IT2, _Pa, _In, _O, _SC, _RC2, _CA2, _CT2], + [[4, { [_hH2]: _xaad }], [0, { [_hH2]: _xaari }], 0, 0, 0, 0, 0, 1, 2, [() => Parts, { [_xF]: 1, [_xN]: _Par }], () => exports.Initiator$, () => exports.Owner$, 0, [0, { [_hH2]: _xarc }], 0, 0] + ]; + exports.ListPartsRequest$ = [ + 3, + n05, + _LPRi, + 0, + [_B, _K2, _UI, _MP, _PNM, _RP, _EBO, _SSECA, _SSECK, _SSECKMD], + [[0, 1], [0, 1], [0, { [_hQ2]: _uI }], [1, { [_hQ2]: _mp }], [0, { [_hQ2]: _pnm }], [0, { [_hH2]: _xarp }], [0, { [_hH2]: _xaebo }], [0, { [_hH2]: _xasseca }], [() => SSECustomerKey, { [_hH2]: _xasseck }], [0, { [_hH2]: _xasseckM }]], + 3 + ]; + exports.LocationInfo$ = [ + 3, + n05, + _LI, + 0, + [_Ty, _N], + [0, 0] + ]; + exports.LoggingEnabled$ = [ + 3, + n05, + _LE, + 0, + [_TB, _TP, _TG, _TOKF], + [0, 0, [() => TargetGrants, 0], [() => exports.TargetObjectKeyFormat$, 0]], + 2 + ]; + exports.MetadataConfiguration$ = [ + 3, + n05, + _MC, + 0, + [_JTC, _ITCn], + [() => exports.JournalTableConfiguration$, () => exports.InventoryTableConfiguration$], + 1 + ]; + exports.MetadataConfigurationResult$ = [ + 3, + n05, + _MCR, + 0, + [_DRes, _JTCR, _ITCR], + [() => exports.DestinationResult$, () => exports.JournalTableConfigurationResult$, () => exports.InventoryTableConfigurationResult$], + 1 + ]; + exports.MetadataEntry$ = [ + 3, + n05, + _ME, + 0, + [_N, _V2], + [0, 0] + ]; + exports.MetadataTableConfiguration$ = [ + 3, + n05, + _MTC, + 0, + [_STD], + [() => exports.S3TablesDestination$], + 1 + ]; + exports.MetadataTableConfigurationResult$ = [ + 3, + n05, + _MTCR, + 0, + [_STDR], + [() => exports.S3TablesDestinationResult$], + 1 + ]; + exports.MetadataTableEncryptionConfiguration$ = [ + 3, + n05, + _MTEC, + 0, + [_SAs, _KKA], + [0, 0], + 1 + ]; + exports.Metrics$ = [ + 3, + n05, + _Me, + 0, + [_S, _ETv], + [0, () => exports.ReplicationTimeValue$], + 1 + ]; + exports.MetricsAndOperator$ = [ + 3, + n05, + _MAO, + 0, + [_P2, _T2, _APAc], + [0, [() => TagSet, { [_xF]: 1, [_xN]: _Ta2 }], 0] + ]; + exports.MetricsConfiguration$ = [ + 3, + n05, + _MCe, + 0, + [_I, _F], + [0, [() => exports.MetricsFilter$, 0]], + 1 + ]; + exports.MultipartUpload$ = [ + 3, + n05, + _MU, + 0, + [_UI, _K2, _Ini, _SC, _O, _In, _CA2, _CT2], + [0, 0, 4, 0, () => exports.Owner$, () => exports.Initiator$, 0, 0] + ]; + exports.NoncurrentVersionExpiration$ = [ + 3, + n05, + _NVE, + 0, + [_ND, _NNV], + [1, 1] + ]; + exports.NoncurrentVersionTransition$ = [ + 3, + n05, + _NVTo, + 0, + [_ND, _SC, _NNV], + [1, 0, 1] + ]; + exports.NotificationConfiguration$ = [ + 3, + n05, + _NC, + 0, + [_TCo, _QCu, _LFCa, _EBC], + [[() => TopicConfigurationList, { [_xF]: 1, [_xN]: _TCop }], [() => QueueConfigurationList, { [_xF]: 1, [_xN]: _QCue }], [() => LambdaFunctionConfigurationList, { [_xF]: 1, [_xN]: _CFC }], () => exports.EventBridgeConfiguration$] + ]; + exports.NotificationConfigurationFilter$ = [ + 3, + n05, + _NCF, + 0, + [_K2], + [[() => exports.S3KeyFilter$, { [_xN]: _SKe }]] + ]; + exports._Object$ = [ + 3, + n05, + _Obj, + 0, + [_K2, _LM, _ETa, _CA2, _CT2, _Si, _SC, _O, _RSe], + [0, 4, 0, [64 | 0, { [_xF]: 1 }], 0, 1, 0, () => exports.Owner$, () => exports.RestoreStatus$] + ]; + exports.ObjectIdentifier$ = [ + 3, + n05, + _OI, + 0, + [_K2, _VI, _ETa, _LMT, _Si], + [0, 0, 0, 6, 1], + 1 + ]; + exports.ObjectLockConfiguration$ = [ + 3, + n05, + _OLC, + 0, + [_OLE, _Ru], + [0, () => exports.ObjectLockRule$] + ]; + exports.ObjectLockLegalHold$ = [ + 3, + n05, + _OLLH, + 0, + [_S], + [0] + ]; + exports.ObjectLockRetention$ = [ + 3, + n05, + _OLR, + 0, + [_Mo, _RUD], + [0, 5] + ]; + exports.ObjectLockRule$ = [ + 3, + n05, + _OLRb, + 0, + [_DRe], + [() => exports.DefaultRetention$] + ]; + exports.ObjectPart$ = [ + 3, + n05, + _OPb, + 0, + [_PN, _Si, _CCRC, _CCRCC, _CCRCNVME, _CSHA, _CSHAh], + [1, 1, 0, 0, 0, 0, 0] + ]; + exports.ObjectVersion$ = [ + 3, + n05, + _OV, + 0, + [_ETa, _CA2, _CT2, _Si, _SC, _K2, _VI, _IL, _LM, _O, _RSe], + [0, [64 | 0, { [_xF]: 1 }], 0, 1, 0, 0, 0, 2, 4, () => exports.Owner$, () => exports.RestoreStatus$] + ]; + exports.OutputLocation$ = [ + 3, + n05, + _OL, + 0, + [_S_], + [[() => exports.S3Location$, 0]] + ]; + exports.OutputSerialization$ = [ + 3, + n05, + _OSu, + 0, + [_CSV, _JSON], + [() => exports.CSVOutput$, () => exports.JSONOutput$] + ]; + exports.Owner$ = [ + 3, + n05, + _O, + 0, + [_DN, _ID], + [0, 0] + ]; + exports.OwnershipControls$ = [ + 3, + n05, + _OC, + 0, + [_R], + [[() => OwnershipControlsRules, { [_xF]: 1, [_xN]: _Ru }]], + 1 + ]; + exports.OwnershipControlsRule$ = [ + 3, + n05, + _OCR, + 0, + [_OO], + [0], + 1 + ]; + exports.ParquetInput$ = [ + 3, + n05, + _PI2, + 0, + [], + [] + ]; + exports.Part$ = [ + 3, + n05, + _Par, + 0, + [_PN, _LM, _ETa, _Si, _CCRC, _CCRCC, _CCRCNVME, _CSHA, _CSHAh], + [1, 4, 0, 1, 0, 0, 0, 0, 0] + ]; + exports.PartitionedPrefix$ = [ + 3, + n05, + _PP, + { [_xN]: _PP }, + [_PDS], + [0] + ]; + exports.PolicyStatus$ = [ + 3, + n05, + _PS, + 0, + [_IP], + [[2, { [_xN]: _IP }]] + ]; + exports.Progress$ = [ + 3, + n05, + _Pr2, + 0, + [_BS, _BP, _BRy], + [1, 1, 1] + ]; + exports.ProgressEvent$ = [ + 3, + n05, + _PE, + 0, + [_Det], + [[() => exports.Progress$, { [_eP]: 1 }]] + ]; + exports.PublicAccessBlockConfiguration$ = [ + 3, + n05, + _PABC, + 0, + [_BPA, _IPA, _BPP, _RPB], + [[2, { [_xN]: _BPA }], [2, { [_xN]: _IPA }], [2, { [_xN]: _BPP }], [2, { [_xN]: _RPB }]] + ]; + exports.PutBucketAbacRequest$ = [ + 3, + n05, + _PBAR, + 0, + [_B, _AS, _CMD, _CA2, _EBO], + [[0, 1], [() => exports.AbacStatus$, { [_hP]: 1, [_xN]: _AS }], [0, { [_hH2]: _CM }], [0, { [_hH2]: _xasca }], [0, { [_hH2]: _xaebo }]], + 2 + ]; + exports.PutBucketAccelerateConfigurationRequest$ = [ + 3, + n05, + _PBACR, + 0, + [_B, _AC, _EBO, _CA2], + [[0, 1], [() => exports.AccelerateConfiguration$, { [_hP]: 1, [_xN]: _AC }], [0, { [_hH2]: _xaebo }], [0, { [_hH2]: _xasca }]], + 2 + ]; + exports.PutBucketAclRequest$ = [ + 3, + n05, + _PBARu, + 0, + [_B, _ACL_, _ACP, _CMD, _CA2, _GFC, _GR, _GRACP, _GW, _GWACP, _EBO], + [[0, 1], [0, { [_hH2]: _xaa }], [() => exports.AccessControlPolicy$, { [_hP]: 1, [_xN]: _ACP }], [0, { [_hH2]: _CM }], [0, { [_hH2]: _xasca }], [0, { [_hH2]: _xagfc }], [0, { [_hH2]: _xagr }], [0, { [_hH2]: _xagra }], [0, { [_hH2]: _xagw }], [0, { [_hH2]: _xagwa }], [0, { [_hH2]: _xaebo }]], + 1 + ]; + exports.PutBucketAnalyticsConfigurationRequest$ = [ + 3, + n05, + _PBACRu, + 0, + [_B, _I, _ACn, _EBO], + [[0, 1], [0, { [_hQ2]: _i }], [() => exports.AnalyticsConfiguration$, { [_hP]: 1, [_xN]: _ACn }], [0, { [_hH2]: _xaebo }]], + 3 + ]; + exports.PutBucketCorsRequest$ = [ + 3, + n05, + _PBCR, + 0, + [_B, _CORSC, _CMD, _CA2, _EBO], + [[0, 1], [() => exports.CORSConfiguration$, { [_hP]: 1, [_xN]: _CORSC }], [0, { [_hH2]: _CM }], [0, { [_hH2]: _xasca }], [0, { [_hH2]: _xaebo }]], + 2 + ]; + exports.PutBucketEncryptionRequest$ = [ + 3, + n05, + _PBER, + 0, + [_B, _SSEC, _CMD, _CA2, _EBO], + [[0, 1], [() => exports.ServerSideEncryptionConfiguration$, { [_hP]: 1, [_xN]: _SSEC }], [0, { [_hH2]: _CM }], [0, { [_hH2]: _xasca }], [0, { [_hH2]: _xaebo }]], + 2 + ]; + exports.PutBucketIntelligentTieringConfigurationRequest$ = [ + 3, + n05, + _PBITCR, + 0, + [_B, _I, _ITC, _EBO], + [[0, 1], [0, { [_hQ2]: _i }], [() => exports.IntelligentTieringConfiguration$, { [_hP]: 1, [_xN]: _ITC }], [0, { [_hH2]: _xaebo }]], + 3 + ]; + exports.PutBucketInventoryConfigurationRequest$ = [ + 3, + n05, + _PBICR, + 0, + [_B, _I, _IC, _EBO], + [[0, 1], [0, { [_hQ2]: _i }], [() => exports.InventoryConfiguration$, { [_hP]: 1, [_xN]: _IC }], [0, { [_hH2]: _xaebo }]], + 3 + ]; + exports.PutBucketLifecycleConfigurationOutput$ = [ + 3, + n05, + _PBLCO, + 0, + [_TDMOS], + [[0, { [_hH2]: _xatdmos }]] + ]; + exports.PutBucketLifecycleConfigurationRequest$ = [ + 3, + n05, + _PBLCR, + 0, + [_B, _CA2, _LCi, _EBO, _TDMOS], + [[0, 1], [0, { [_hH2]: _xasca }], [() => exports.BucketLifecycleConfiguration$, { [_hP]: 1, [_xN]: _LCi }], [0, { [_hH2]: _xaebo }], [0, { [_hH2]: _xatdmos }]], + 1 + ]; + exports.PutBucketLoggingRequest$ = [ + 3, + n05, + _PBLR, + 0, + [_B, _BLS, _CMD, _CA2, _EBO], + [[0, 1], [() => exports.BucketLoggingStatus$, { [_hP]: 1, [_xN]: _BLS }], [0, { [_hH2]: _CM }], [0, { [_hH2]: _xasca }], [0, { [_hH2]: _xaebo }]], + 2 + ]; + exports.PutBucketMetricsConfigurationRequest$ = [ + 3, + n05, + _PBMCR, + 0, + [_B, _I, _MCe, _EBO], + [[0, 1], [0, { [_hQ2]: _i }], [() => exports.MetricsConfiguration$, { [_hP]: 1, [_xN]: _MCe }], [0, { [_hH2]: _xaebo }]], + 3 + ]; + exports.PutBucketNotificationConfigurationRequest$ = [ + 3, + n05, + _PBNCR, + 0, + [_B, _NC, _EBO, _SDV], + [[0, 1], [() => exports.NotificationConfiguration$, { [_hP]: 1, [_xN]: _NC }], [0, { [_hH2]: _xaebo }], [2, { [_hH2]: _xasdv }]], + 2 + ]; + exports.PutBucketOwnershipControlsRequest$ = [ + 3, + n05, + _PBOCR, + 0, + [_B, _OC, _CMD, _EBO, _CA2], + [[0, 1], [() => exports.OwnershipControls$, { [_hP]: 1, [_xN]: _OC }], [0, { [_hH2]: _CM }], [0, { [_hH2]: _xaebo }], [0, { [_hH2]: _xasca }]], + 2 + ]; + exports.PutBucketPolicyRequest$ = [ + 3, + n05, + _PBPR, + 0, + [_B, _Po, _CMD, _CA2, _CRSBA, _EBO], + [[0, 1], [0, 16], [0, { [_hH2]: _CM }], [0, { [_hH2]: _xasca }], [2, { [_hH2]: _xacrsba }], [0, { [_hH2]: _xaebo }]], + 2 + ]; + exports.PutBucketReplicationRequest$ = [ + 3, + n05, + _PBRR, + 0, + [_B, _RCe, _CMD, _CA2, _To, _EBO], + [[0, 1], [() => exports.ReplicationConfiguration$, { [_hP]: 1, [_xN]: _RCe }], [0, { [_hH2]: _CM }], [0, { [_hH2]: _xasca }], [0, { [_hH2]: _xabolt }], [0, { [_hH2]: _xaebo }]], + 2 + ]; + exports.PutBucketRequestPaymentRequest$ = [ + 3, + n05, + _PBRPR, + 0, + [_B, _RPC, _CMD, _CA2, _EBO], + [[0, 1], [() => exports.RequestPaymentConfiguration$, { [_hP]: 1, [_xN]: _RPC }], [0, { [_hH2]: _CM }], [0, { [_hH2]: _xasca }], [0, { [_hH2]: _xaebo }]], + 2 + ]; + exports.PutBucketTaggingRequest$ = [ + 3, + n05, + _PBTR, + 0, + [_B, _Tag, _CMD, _CA2, _EBO], + [[0, 1], [() => exports.Tagging$, { [_hP]: 1, [_xN]: _Tag }], [0, { [_hH2]: _CM }], [0, { [_hH2]: _xasca }], [0, { [_hH2]: _xaebo }]], + 2 + ]; + exports.PutBucketVersioningRequest$ = [ + 3, + n05, + _PBVR, + 0, + [_B, _VC, _CMD, _CA2, _MFA, _EBO], + [[0, 1], [() => exports.VersioningConfiguration$, { [_hP]: 1, [_xN]: _VC }], [0, { [_hH2]: _CM }], [0, { [_hH2]: _xasca }], [0, { [_hH2]: _xam_ }], [0, { [_hH2]: _xaebo }]], + 2 + ]; + exports.PutBucketWebsiteRequest$ = [ + 3, + n05, + _PBWR, + 0, + [_B, _WC, _CMD, _CA2, _EBO], + [[0, 1], [() => exports.WebsiteConfiguration$, { [_hP]: 1, [_xN]: _WC }], [0, { [_hH2]: _CM }], [0, { [_hH2]: _xasca }], [0, { [_hH2]: _xaebo }]], + 2 + ]; + exports.PutObjectAclOutput$ = [ + 3, + n05, + _POAO, + 0, + [_RC2], + [[0, { [_hH2]: _xarc }]] + ]; + exports.PutObjectAclRequest$ = [ + 3, + n05, + _POAR, + 0, + [_B, _K2, _ACL_, _ACP, _CMD, _CA2, _GFC, _GR, _GRACP, _GW, _GWACP, _RP, _VI, _EBO], + [[0, 1], [0, 1], [0, { [_hH2]: _xaa }], [() => exports.AccessControlPolicy$, { [_hP]: 1, [_xN]: _ACP }], [0, { [_hH2]: _CM }], [0, { [_hH2]: _xasca }], [0, { [_hH2]: _xagfc }], [0, { [_hH2]: _xagr }], [0, { [_hH2]: _xagra }], [0, { [_hH2]: _xagw }], [0, { [_hH2]: _xagwa }], [0, { [_hH2]: _xarp }], [0, { [_hQ2]: _vI }], [0, { [_hH2]: _xaebo }]], + 2 + ]; + exports.PutObjectLegalHoldOutput$ = [ + 3, + n05, + _POLHO, + 0, + [_RC2], + [[0, { [_hH2]: _xarc }]] + ]; + exports.PutObjectLegalHoldRequest$ = [ + 3, + n05, + _POLHR, + 0, + [_B, _K2, _LH, _RP, _VI, _CMD, _CA2, _EBO], + [[0, 1], [0, 1], [() => exports.ObjectLockLegalHold$, { [_hP]: 1, [_xN]: _LH }], [0, { [_hH2]: _xarp }], [0, { [_hQ2]: _vI }], [0, { [_hH2]: _CM }], [0, { [_hH2]: _xasca }], [0, { [_hH2]: _xaebo }]], + 2 + ]; + exports.PutObjectLockConfigurationOutput$ = [ + 3, + n05, + _POLCO, + 0, + [_RC2], + [[0, { [_hH2]: _xarc }]] + ]; + exports.PutObjectLockConfigurationRequest$ = [ + 3, + n05, + _POLCR, + 0, + [_B, _OLC, _RP, _To, _CMD, _CA2, _EBO], + [[0, 1], [() => exports.ObjectLockConfiguration$, { [_hP]: 1, [_xN]: _OLC }], [0, { [_hH2]: _xarp }], [0, { [_hH2]: _xabolt }], [0, { [_hH2]: _CM }], [0, { [_hH2]: _xasca }], [0, { [_hH2]: _xaebo }]], + 1 + ]; + exports.PutObjectOutput$ = [ + 3, + n05, + _POO, + 0, + [_E2, _ETa, _CCRC, _CCRCC, _CCRCNVME, _CSHA, _CSHAh, _CT2, _SSE, _VI, _SSECA, _SSECKMD, _SSEKMSKI, _SSEKMSEC, _BKE, _Si, _RC2], + [[0, { [_hH2]: _xae }], [0, { [_hH2]: _ETa }], [0, { [_hH2]: _xacc }], [0, { [_hH2]: _xacc_ }], [0, { [_hH2]: _xacc__ }], [0, { [_hH2]: _xacs }], [0, { [_hH2]: _xacs_ }], [0, { [_hH2]: _xact }], [0, { [_hH2]: _xasse }], [0, { [_hH2]: _xavi }], [0, { [_hH2]: _xasseca }], [0, { [_hH2]: _xasseckM }], [() => SSEKMSKeyId, { [_hH2]: _xasseakki }], [() => SSEKMSEncryptionContext, { [_hH2]: _xassec }], [2, { [_hH2]: _xassebke }], [1, { [_hH2]: _xaos }], [0, { [_hH2]: _xarc }]] + ]; + exports.PutObjectRequest$ = [ + 3, + n05, + _POR, + 0, + [_B, _K2, _ACL_, _Bo, _CC, _CDo, _CEo, _CL, _CLo, _CMD, _CTo, _CA2, _CCRC, _CCRCC, _CCRCNVME, _CSHA, _CSHAh, _Ex, _IM, _INM, _GFC, _GR, _GRACP, _GWACP, _WOB, _M, _SSE, _SC, _WRL, _SSECA, _SSECK, _SSECKMD, _SSEKMSKI, _SSEKMSEC, _BKE, _RP, _Tag, _OLM, _OLRUD, _OLLHS, _EBO], + [[0, 1], [0, 1], [0, { [_hH2]: _xaa }], [() => StreamingBlob, 16], [0, { [_hH2]: _CC_ }], [0, { [_hH2]: _CD_ }], [0, { [_hH2]: _CE_ }], [0, { [_hH2]: _CL_ }], [1, { [_hH2]: _CL__ }], [0, { [_hH2]: _CM }], [0, { [_hH2]: _CT_ }], [0, { [_hH2]: _xasca }], [0, { [_hH2]: _xacc }], [0, { [_hH2]: _xacc_ }], [0, { [_hH2]: _xacc__ }], [0, { [_hH2]: _xacs }], [0, { [_hH2]: _xacs_ }], [4, { [_hH2]: _Ex }], [0, { [_hH2]: _IM_ }], [0, { [_hH2]: _INM_ }], [0, { [_hH2]: _xagfc }], [0, { [_hH2]: _xagr }], [0, { [_hH2]: _xagra }], [0, { [_hH2]: _xagwa }], [1, { [_hH2]: _xawob }], [128 | 0, { [_hPH]: _xam }], [0, { [_hH2]: _xasse }], [0, { [_hH2]: _xasc }], [0, { [_hH2]: _xawrl }], [0, { [_hH2]: _xasseca }], [() => SSECustomerKey, { [_hH2]: _xasseck }], [0, { [_hH2]: _xasseckM }], [() => SSEKMSKeyId, { [_hH2]: _xasseakki }], [() => SSEKMSEncryptionContext, { [_hH2]: _xassec }], [2, { [_hH2]: _xassebke }], [0, { [_hH2]: _xarp }], [0, { [_hH2]: _xat }], [0, { [_hH2]: _xaolm }], [5, { [_hH2]: _xaolrud }], [0, { [_hH2]: _xaollh }], [0, { [_hH2]: _xaebo }]], + 2 + ]; + exports.PutObjectRetentionOutput$ = [ + 3, + n05, + _PORO, + 0, + [_RC2], + [[0, { [_hH2]: _xarc }]] + ]; + exports.PutObjectRetentionRequest$ = [ + 3, + n05, + _PORR, + 0, + [_B, _K2, _Ret, _RP, _VI, _BGR, _CMD, _CA2, _EBO], + [[0, 1], [0, 1], [() => exports.ObjectLockRetention$, { [_hP]: 1, [_xN]: _Ret }], [0, { [_hH2]: _xarp }], [0, { [_hQ2]: _vI }], [2, { [_hH2]: _xabgr }], [0, { [_hH2]: _CM }], [0, { [_hH2]: _xasca }], [0, { [_hH2]: _xaebo }]], + 2 + ]; + exports.PutObjectTaggingOutput$ = [ + 3, + n05, + _POTO, + 0, + [_VI], + [[0, { [_hH2]: _xavi }]] + ]; + exports.PutObjectTaggingRequest$ = [ + 3, + n05, + _POTR, + 0, + [_B, _K2, _Tag, _VI, _CMD, _CA2, _EBO, _RP], + [[0, 1], [0, 1], [() => exports.Tagging$, { [_hP]: 1, [_xN]: _Tag }], [0, { [_hQ2]: _vI }], [0, { [_hH2]: _CM }], [0, { [_hH2]: _xasca }], [0, { [_hH2]: _xaebo }], [0, { [_hH2]: _xarp }]], + 3 + ]; + exports.PutPublicAccessBlockRequest$ = [ + 3, + n05, + _PPABR, + 0, + [_B, _PABC, _CMD, _CA2, _EBO], + [[0, 1], [() => exports.PublicAccessBlockConfiguration$, { [_hP]: 1, [_xN]: _PABC }], [0, { [_hH2]: _CM }], [0, { [_hH2]: _xasca }], [0, { [_hH2]: _xaebo }]], + 2 + ]; + exports.QueueConfiguration$ = [ + 3, + n05, + _QCue, + 0, + [_QA, _Ev, _I, _F], + [[0, { [_xN]: _Qu }], [64 | 0, { [_xF]: 1, [_xN]: _Eve }], 0, [() => exports.NotificationConfigurationFilter$, 0]], + 2 + ]; + exports.RecordExpiration$ = [ + 3, + n05, + _REe, + 0, + [_E2, _D], + [0, 1], + 1 + ]; + exports.RecordsEvent$ = [ + 3, + n05, + _REec, + 0, + [_Payl], + [[21, { [_eP]: 1 }]] + ]; + exports.Redirect$ = [ + 3, + n05, + _Red, + 0, + [_HN, _HRC, _Pro, _RKPW, _RKW], + [0, 0, 0, 0, 0] + ]; + exports.RedirectAllRequestsTo$ = [ + 3, + n05, + _RART, + 0, + [_HN, _Pro], + [0, 0], + 1 + ]; + exports.RenameObjectOutput$ = [ + 3, + n05, + _ROO, + 0, + [], + [] + ]; + exports.RenameObjectRequest$ = [ + 3, + n05, + _ROR, + 0, + [_B, _K2, _RSen, _DIM, _DINM, _DIMS, _DIUS, _SIM, _SINM, _SIMS, _SIUS, _CTl], + [[0, 1], [0, 1], [0, { [_hH2]: _xars_ }], [0, { [_hH2]: _IM_ }], [0, { [_hH2]: _INM_ }], [4, { [_hH2]: _IMS_ }], [4, { [_hH2]: _IUS_ }], [0, { [_hH2]: _xarsim }], [0, { [_hH2]: _xarsinm }], [6, { [_hH2]: _xarsims }], [6, { [_hH2]: _xarsius }], [0, { [_hH2]: _xact_, [_iT3]: 1 }]], + 3 + ]; + exports.ReplicaModifications$ = [ + 3, + n05, + _RM, + 0, + [_S], + [0], + 1 + ]; + exports.ReplicationConfiguration$ = [ + 3, + n05, + _RCe, + 0, + [_Ro, _R], + [0, [() => ReplicationRules, { [_xF]: 1, [_xN]: _Ru }]], + 2 + ]; + exports.ReplicationRule$ = [ + 3, + n05, + _RRe, + 0, + [_S, _Des, _ID, _Pri, _P2, _F, _SSC, _EOR, _DMR], + [0, () => exports.Destination$, 0, 1, 0, [() => exports.ReplicationRuleFilter$, 0], () => exports.SourceSelectionCriteria$, () => exports.ExistingObjectReplication$, () => exports.DeleteMarkerReplication$], + 2 + ]; + exports.ReplicationRuleAndOperator$ = [ + 3, + n05, + _RRAO, + 0, + [_P2, _T2], + [0, [() => TagSet, { [_xF]: 1, [_xN]: _Ta2 }]] + ]; + exports.ReplicationRuleFilter$ = [ + 3, + n05, + _RRF, + 0, + [_P2, _Ta2, _An], + [0, () => exports.Tag$, [() => exports.ReplicationRuleAndOperator$, 0]] + ]; + exports.ReplicationTime$ = [ + 3, + n05, + _RT3, + 0, + [_S, _Tim], + [0, () => exports.ReplicationTimeValue$], + 2 + ]; + exports.ReplicationTimeValue$ = [ + 3, + n05, + _RTV, + 0, + [_Mi], + [1] + ]; + exports.RequestPaymentConfiguration$ = [ + 3, + n05, + _RPC, + 0, + [_Pay], + [0], + 1 + ]; + exports.RequestProgress$ = [ + 3, + n05, + _RPe, + 0, + [_Ena], + [2] + ]; + exports.RestoreObjectOutput$ = [ + 3, + n05, + _ROOe, + 0, + [_RC2, _ROP], + [[0, { [_hH2]: _xarc }], [0, { [_hH2]: _xarop }]] + ]; + exports.RestoreObjectRequest$ = [ + 3, + n05, + _RORe, + 0, + [_B, _K2, _VI, _RRes, _RP, _CA2, _EBO], + [[0, 1], [0, 1], [0, { [_hQ2]: _vI }], [() => exports.RestoreRequest$, { [_hP]: 1, [_xN]: _RRes }], [0, { [_hH2]: _xarp }], [0, { [_hH2]: _xasca }], [0, { [_hH2]: _xaebo }]], + 2 + ]; + exports.RestoreRequest$ = [ + 3, + n05, + _RRes, + 0, + [_D, _GJP, _Ty, _Ti, _Desc, _SP, _OL], + [1, () => exports.GlacierJobParameters$, 0, 0, 0, () => exports.SelectParameters$, [() => exports.OutputLocation$, 0]] + ]; + exports.RestoreStatus$ = [ + 3, + n05, + _RSe, + 0, + [_IRIP, _RED], + [2, 4] + ]; + exports.RoutingRule$ = [ + 3, + n05, + _RRo, + 0, + [_Red, _Co], + [() => exports.Redirect$, () => exports.Condition$], + 1 + ]; + exports.S3KeyFilter$ = [ + 3, + n05, + _SKF, + 0, + [_FRi], + [[() => FilterRuleList, { [_xF]: 1, [_xN]: _FR }]] + ]; + exports.S3Location$ = [ + 3, + n05, + _SL, + 0, + [_BNu, _P2, _En, _CACL, _ACL, _Tag, _UM, _SC], + [0, 0, [() => exports.Encryption$, 0], 0, [() => Grants, 0], [() => exports.Tagging$, 0], [() => UserMetadata, 0], 0], + 2 + ]; + exports.S3TablesDestination$ = [ + 3, + n05, + _STD, + 0, + [_TBA, _TNa], + [0, 0], + 2 + ]; + exports.S3TablesDestinationResult$ = [ + 3, + n05, + _STDR, + 0, + [_TBA, _TNa, _TA, _TN], + [0, 0, 0, 0], + 4 + ]; + exports.ScanRange$ = [ + 3, + n05, + _SR, + 0, + [_St, _End], + [1, 1] + ]; + exports.SelectObjectContentOutput$ = [ + 3, + n05, + _SOCO, + 0, + [_Payl], + [[() => exports.SelectObjectContentEventStream$, 16]] + ]; + exports.SelectObjectContentRequest$ = [ + 3, + n05, + _SOCR, + 0, + [_B, _K2, _Exp, _ETx, _IS, _OSu, _SSECA, _SSECK, _SSECKMD, _RPe, _SR, _EBO], + [[0, 1], [0, 1], 0, 0, () => exports.InputSerialization$, () => exports.OutputSerialization$, [0, { [_hH2]: _xasseca }], [() => SSECustomerKey, { [_hH2]: _xasseck }], [0, { [_hH2]: _xasseckM }], () => exports.RequestProgress$, () => exports.ScanRange$, [0, { [_hH2]: _xaebo }]], + 6 + ]; + exports.SelectParameters$ = [ + 3, + n05, + _SP, + 0, + [_IS, _ETx, _Exp, _OSu], + [() => exports.InputSerialization$, 0, 0, () => exports.OutputSerialization$], + 4 + ]; + exports.ServerSideEncryptionByDefault$ = [ + 3, + n05, + _SSEBD, + 0, + [_SSEA, _KMSMKID], + [0, [() => SSEKMSKeyId, 0]], + 1 + ]; + exports.ServerSideEncryptionConfiguration$ = [ + 3, + n05, + _SSEC, + 0, + [_R], + [[() => ServerSideEncryptionRules, { [_xF]: 1, [_xN]: _Ru }]], + 1 + ]; + exports.ServerSideEncryptionRule$ = [ + 3, + n05, + _SSER, + 0, + [_ASSEBD, _BKE, _BET], + [[() => exports.ServerSideEncryptionByDefault$, 0], 2, [() => exports.BlockedEncryptionTypes$, 0]] + ]; + exports.SessionCredentials$ = [ + 3, + n05, + _SCe, + 0, + [_AKI2, _SAK2, _ST2, _E2], + [[0, { [_xN]: _AKI2 }], [() => SessionCredentialValue, { [_xN]: _SAK2 }], [() => SessionCredentialValue, { [_xN]: _ST2 }], [4, { [_xN]: _E2 }]], + 4 + ]; + exports.SimplePrefix$ = [ + 3, + n05, + _SPi, + { [_xN]: _SPi }, + [], + [] + ]; + exports.SourceSelectionCriteria$ = [ + 3, + n05, + _SSC, + 0, + [_SKEO, _RM], + [() => exports.SseKmsEncryptedObjects$, () => exports.ReplicaModifications$] + ]; + exports.SSEKMS$ = [ + 3, + n05, + _SSEKMS, + { [_xN]: _SK }, + [_KI], + [[() => SSEKMSKeyId, 0]], + 1 + ]; + exports.SseKmsEncryptedObjects$ = [ + 3, + n05, + _SKEO, + 0, + [_S], + [0], + 1 + ]; + exports.SSEKMSEncryption$ = [ + 3, + n05, + _SSEKMSE, + { [_xN]: _SK }, + [_KMSKA, _BKE], + [[() => NonEmptyKmsKeyArnString, 0], 2], + 1 + ]; + exports.SSES3$ = [ + 3, + n05, + _SSES, + { [_xN]: _SS }, + [], + [] + ]; + exports.Stats$ = [ + 3, + n05, + _Sta, + 0, + [_BS, _BP, _BRy], + [1, 1, 1] + ]; + exports.StatsEvent$ = [ + 3, + n05, + _SE, + 0, + [_Det], + [[() => exports.Stats$, { [_eP]: 1 }]] + ]; + exports.StorageClassAnalysis$ = [ + 3, + n05, + _SCA, + 0, + [_DE], + [() => exports.StorageClassAnalysisDataExport$] + ]; + exports.StorageClassAnalysisDataExport$ = [ + 3, + n05, + _SCADE, + 0, + [_OSV, _Des], + [0, () => exports.AnalyticsExportDestination$], + 2 + ]; + exports.Tag$ = [ + 3, + n05, + _Ta2, + 0, + [_K2, _V2], + [0, 0], + 2 + ]; + exports.Tagging$ = [ + 3, + n05, + _Tag, + 0, + [_TS], + [[() => TagSet, 0]], + 1 + ]; + exports.TargetGrant$ = [ + 3, + n05, + _TGa, + 0, + [_Gra, _Pe], + [[() => exports.Grantee$, { [_xNm]: [_x, _hi] }], 0] + ]; + exports.TargetObjectKeyFormat$ = [ + 3, + n05, + _TOKF, + 0, + [_SPi, _PP], + [[() => exports.SimplePrefix$, { [_xN]: _SPi }], [() => exports.PartitionedPrefix$, { [_xN]: _PP }]] + ]; + exports.Tiering$ = [ + 3, + n05, + _Tier, + 0, + [_D, _AT3], + [1, 0], + 2 + ]; + exports.TopicConfiguration$ = [ + 3, + n05, + _TCop, + 0, + [_TAo, _Ev, _I, _F], + [[0, { [_xN]: _Top }], [64 | 0, { [_xF]: 1, [_xN]: _Eve }], 0, [() => exports.NotificationConfigurationFilter$, 0]], + 2 + ]; + exports.Transition$ = [ + 3, + n05, + _Tra, + 0, + [_Da, _D, _SC], + [5, 1, 0] + ]; + exports.UpdateBucketMetadataInventoryTableConfigurationRequest$ = [ + 3, + n05, + _UBMITCR, + 0, + [_B, _ITCn, _CMD, _CA2, _EBO], + [[0, 1], [() => exports.InventoryTableConfigurationUpdates$, { [_hP]: 1, [_xN]: _ITCn }], [0, { [_hH2]: _CM }], [0, { [_hH2]: _xasca }], [0, { [_hH2]: _xaebo }]], + 2 + ]; + exports.UpdateBucketMetadataJournalTableConfigurationRequest$ = [ + 3, + n05, + _UBMJTCR, + 0, + [_B, _JTC, _CMD, _CA2, _EBO], + [[0, 1], [() => exports.JournalTableConfigurationUpdates$, { [_hP]: 1, [_xN]: _JTC }], [0, { [_hH2]: _CM }], [0, { [_hH2]: _xasca }], [0, { [_hH2]: _xaebo }]], + 2 + ]; + exports.UpdateObjectEncryptionRequest$ = [ + 3, + n05, + _UOER, + 0, + [_B, _K2, _OE, _VI, _RP, _EBO, _CMD, _CA2], + [[0, 1], [0, 1], [() => exports.ObjectEncryption$, 16], [0, { [_hQ2]: _vI }], [0, { [_hH2]: _xarp }], [0, { [_hH2]: _xaebo }], [0, { [_hH2]: _CM }], [0, { [_hH2]: _xasca }]], + 3 + ]; + exports.UpdateObjectEncryptionResponse$ = [ + 3, + n05, + _UOERp, + 0, + [_RC2], + [[0, { [_hH2]: _xarc }]] + ]; + exports.UploadPartCopyOutput$ = [ + 3, + n05, + _UPCO, + 0, + [_CSVI, _CPR, _SSE, _SSECA, _SSECKMD, _SSEKMSKI, _BKE, _RC2], + [[0, { [_hH2]: _xacsvi }], [() => exports.CopyPartResult$, 16], [0, { [_hH2]: _xasse }], [0, { [_hH2]: _xasseca }], [0, { [_hH2]: _xasseckM }], [() => SSEKMSKeyId, { [_hH2]: _xasseakki }], [2, { [_hH2]: _xassebke }], [0, { [_hH2]: _xarc }]] + ]; + exports.UploadPartCopyRequest$ = [ + 3, + n05, + _UPCR, + 0, + [_B, _CS2, _K2, _PN, _UI, _CSIM, _CSIMS, _CSINM, _CSIUS, _CSRo, _SSECA, _SSECK, _SSECKMD, _CSSSECA, _CSSSECK, _CSSSECKMD, _RP, _EBO, _ESBO], + [[0, 1], [0, { [_hH2]: _xacs__ }], [0, 1], [1, { [_hQ2]: _pN }], [0, { [_hQ2]: _uI }], [0, { [_hH2]: _xacsim }], [4, { [_hH2]: _xacsims }], [0, { [_hH2]: _xacsinm }], [4, { [_hH2]: _xacsius }], [0, { [_hH2]: _xacsr }], [0, { [_hH2]: _xasseca }], [() => SSECustomerKey, { [_hH2]: _xasseck }], [0, { [_hH2]: _xasseckM }], [0, { [_hH2]: _xacssseca }], [() => CopySourceSSECustomerKey, { [_hH2]: _xacssseck }], [0, { [_hH2]: _xacssseckM }], [0, { [_hH2]: _xarp }], [0, { [_hH2]: _xaebo }], [0, { [_hH2]: _xasebo }]], + 5 + ]; + exports.UploadPartOutput$ = [ + 3, + n05, + _UPO, + 0, + [_SSE, _ETa, _CCRC, _CCRCC, _CCRCNVME, _CSHA, _CSHAh, _SSECA, _SSECKMD, _SSEKMSKI, _BKE, _RC2], + [[0, { [_hH2]: _xasse }], [0, { [_hH2]: _ETa }], [0, { [_hH2]: _xacc }], [0, { [_hH2]: _xacc_ }], [0, { [_hH2]: _xacc__ }], [0, { [_hH2]: _xacs }], [0, { [_hH2]: _xacs_ }], [0, { [_hH2]: _xasseca }], [0, { [_hH2]: _xasseckM }], [() => SSEKMSKeyId, { [_hH2]: _xasseakki }], [2, { [_hH2]: _xassebke }], [0, { [_hH2]: _xarc }]] + ]; + exports.UploadPartRequest$ = [ + 3, + n05, + _UPR, + 0, + [_B, _K2, _PN, _UI, _Bo, _CLo, _CMD, _CA2, _CCRC, _CCRCC, _CCRCNVME, _CSHA, _CSHAh, _SSECA, _SSECK, _SSECKMD, _RP, _EBO], + [[0, 1], [0, 1], [1, { [_hQ2]: _pN }], [0, { [_hQ2]: _uI }], [() => StreamingBlob, 16], [1, { [_hH2]: _CL__ }], [0, { [_hH2]: _CM }], [0, { [_hH2]: _xasca }], [0, { [_hH2]: _xacc }], [0, { [_hH2]: _xacc_ }], [0, { [_hH2]: _xacc__ }], [0, { [_hH2]: _xacs }], [0, { [_hH2]: _xacs_ }], [0, { [_hH2]: _xasseca }], [() => SSECustomerKey, { [_hH2]: _xasseck }], [0, { [_hH2]: _xasseckM }], [0, { [_hH2]: _xarp }], [0, { [_hH2]: _xaebo }]], + 4 + ]; + exports.VersioningConfiguration$ = [ + 3, + n05, + _VC, + 0, + [_MFAD, _S], + [[0, { [_xN]: _MDf }], 0] + ]; + exports.WebsiteConfiguration$ = [ + 3, + n05, + _WC, + 0, + [_EDr, _IDn, _RART, _RR], + [() => exports.ErrorDocument$, () => exports.IndexDocument$, () => exports.RedirectAllRequestsTo$, [() => RoutingRules, 0]] + ]; + exports.WriteGetObjectResponseRequest$ = [ + 3, + n05, + _WGORR, + 0, + [_RReq, _RTe, _Bo, _SCt, _ECr, _EM, _AR2, _CC, _CDo, _CEo, _CL, _CLo, _CR, _CTo, _CCRC, _CCRCC, _CCRCNVME, _CSHA, _CSHAh, _DM, _ETa, _Ex, _E2, _LM, _MM, _M, _OLM, _OLLHS, _OLRUD, _PC2, _RS, _RC2, _Re, _SSE, _SSECA, _SSEKMSKI, _SSECKMD, _SC, _TC2, _VI, _BKE], + [[0, { [_hL]: 1, [_hH2]: _xarr }], [0, { [_hH2]: _xart }], [() => StreamingBlob, 16], [1, { [_hH2]: _xafs }], [0, { [_hH2]: _xafec }], [0, { [_hH2]: _xafem }], [0, { [_hH2]: _xafhar }], [0, { [_hH2]: _xafhCC }], [0, { [_hH2]: _xafhCD }], [0, { [_hH2]: _xafhCE }], [0, { [_hH2]: _xafhCL }], [1, { [_hH2]: _CL__ }], [0, { [_hH2]: _xafhCR }], [0, { [_hH2]: _xafhCT }], [0, { [_hH2]: _xafhxacc }], [0, { [_hH2]: _xafhxacc_ }], [0, { [_hH2]: _xafhxacc__ }], [0, { [_hH2]: _xafhxacs }], [0, { [_hH2]: _xafhxacs_ }], [2, { [_hH2]: _xafhxadm }], [0, { [_hH2]: _xafhE }], [4, { [_hH2]: _xafhE_ }], [0, { [_hH2]: _xafhxae }], [4, { [_hH2]: _xafhLM }], [1, { [_hH2]: _xafhxamm }], [128 | 0, { [_hPH]: _xam }], [0, { [_hH2]: _xafhxaolm }], [0, { [_hH2]: _xafhxaollh }], [5, { [_hH2]: _xafhxaolrud }], [1, { [_hH2]: _xafhxampc }], [0, { [_hH2]: _xafhxars }], [0, { [_hH2]: _xafhxarc }], [0, { [_hH2]: _xafhxar }], [0, { [_hH2]: _xafhxasse }], [0, { [_hH2]: _xafhxasseca }], [() => SSEKMSKeyId, { [_hH2]: _xafhxasseakki }], [0, { [_hH2]: _xafhxasseckM }], [0, { [_hH2]: _xafhxasc }], [1, { [_hH2]: _xafhxatc }], [0, { [_hH2]: _xafhxavi }], [2, { [_hH2]: _xafhxassebke }]], + 2 + ]; + var __Unit = "unit"; + var AllowedHeaders = 64 | 0; + var AllowedMethods = 64 | 0; + var AllowedOrigins = 64 | 0; + var AnalyticsConfigurationList = [ + 1, + n05, + _ACLn, + 0, + [ + () => exports.AnalyticsConfiguration$, + 0 + ] + ]; + var Buckets = [ + 1, + n05, + _Bu, + 0, + [ + () => exports.Bucket$, + { [_xN]: _B } + ] + ]; + var ChecksumAlgorithmList = 64 | 0; + var CommonPrefixList = [ + 1, + n05, + _CPL, + 0, + () => exports.CommonPrefix$ + ]; + var CompletedPartList = [ + 1, + n05, + _CPLo, + 0, + () => exports.CompletedPart$ + ]; + var CORSRules = [ + 1, + n05, + _CORSR, + 0, + [ + () => exports.CORSRule$, + 0 + ] + ]; + var DeletedObjects = [ + 1, + n05, + _DOe, + 0, + () => exports.DeletedObject$ + ]; + var DeleteMarkers = [ + 1, + n05, + _DMe, + 0, + () => exports.DeleteMarkerEntry$ + ]; + var EncryptionTypeList = [ + 1, + n05, + _ETL, + 0, + [ + 0, + { [_xN]: _ET } + ] + ]; + var Errors2 = [ + 1, + n05, + _Er, + 0, + () => exports._Error$ + ]; + var EventList = 64 | 0; + var ExposeHeaders = 64 | 0; + var FilterRuleList = [ + 1, + n05, + _FRL, + 0, + () => exports.FilterRule$ + ]; + var Grants = [ + 1, + n05, + _G, + 0, + [ + () => exports.Grant$, + { [_xN]: _Gr } + ] + ]; + var IntelligentTieringConfigurationList = [ + 1, + n05, + _ITCL, + 0, + [ + () => exports.IntelligentTieringConfiguration$, + 0 + ] + ]; + var InventoryConfigurationList = [ + 1, + n05, + _ICL, + 0, + [ + () => exports.InventoryConfiguration$, + 0 + ] + ]; + var InventoryOptionalFields = [ + 1, + n05, + _IOF, + 0, + [ + 0, + { [_xN]: _Fi } + ] + ]; + var LambdaFunctionConfigurationList = [ + 1, + n05, + _LFCL, + 0, + [ + () => exports.LambdaFunctionConfiguration$, + 0 + ] + ]; + var LifecycleRules = [ + 1, + n05, + _LRi, + 0, + [ + () => exports.LifecycleRule$, + 0 + ] + ]; + var MetricsConfigurationList = [ + 1, + n05, + _MCL, + 0, + [ + () => exports.MetricsConfiguration$, + 0 + ] + ]; + var MultipartUploadList = [ + 1, + n05, + _MUL, + 0, + () => exports.MultipartUpload$ + ]; + var NoncurrentVersionTransitionList = [ + 1, + n05, + _NVTL, + 0, + () => exports.NoncurrentVersionTransition$ + ]; + var ObjectAttributesList = 64 | 0; + var ObjectIdentifierList = [ + 1, + n05, + _OIL, + 0, + () => exports.ObjectIdentifier$ + ]; + var ObjectList = [ + 1, + n05, + _OLb, + 0, + [ + () => exports._Object$, + 0 + ] + ]; + var ObjectVersionList = [ + 1, + n05, + _OVL, + 0, + [ + () => exports.ObjectVersion$, + 0 + ] + ]; + var OptionalObjectAttributesList = 64 | 0; + var OwnershipControlsRules = [ + 1, + n05, + _OCRw, + 0, + () => exports.OwnershipControlsRule$ + ]; + var Parts = [ + 1, + n05, + _Pa, + 0, + () => exports.Part$ + ]; + var PartsList = [ + 1, + n05, + _PL, + 0, + () => exports.ObjectPart$ + ]; + var QueueConfigurationList = [ + 1, + n05, + _QCL, + 0, + [ + () => exports.QueueConfiguration$, + 0 + ] + ]; + var ReplicationRules = [ + 1, + n05, + _RRep, + 0, + [ + () => exports.ReplicationRule$, + 0 + ] + ]; + var RoutingRules = [ + 1, + n05, + _RR, + 0, + [ + () => exports.RoutingRule$, + { [_xN]: _RRo } + ] + ]; + var ServerSideEncryptionRules = [ + 1, + n05, + _SSERe, + 0, + [ + () => exports.ServerSideEncryptionRule$, + 0 + ] + ]; + var TagSet = [ + 1, + n05, + _TS, + 0, + [ + () => exports.Tag$, + { [_xN]: _Ta2 } + ] + ]; + var TargetGrants = [ + 1, + n05, + _TG, + 0, + [ + () => exports.TargetGrant$, + { [_xN]: _Gr } + ] + ]; + var TieringList = [ + 1, + n05, + _TL, + 0, + () => exports.Tiering$ + ]; + var TopicConfigurationList = [ + 1, + n05, + _TCL, + 0, + [ + () => exports.TopicConfiguration$, + 0 + ] + ]; + var TransitionList = [ + 1, + n05, + _TLr, + 0, + () => exports.Transition$ + ]; + var UserMetadata = [ + 1, + n05, + _UM, + 0, + [ + () => exports.MetadataEntry$, + { [_xN]: _ME } + ] + ]; + var Metadata = 128 | 0; + exports.AnalyticsFilter$ = [ + 4, + n05, + _AF, + 0, + [_P2, _Ta2, _An], + [0, () => exports.Tag$, [() => exports.AnalyticsAndOperator$, 0]] + ]; + exports.MetricsFilter$ = [ + 4, + n05, + _MF, + 0, + [_P2, _Ta2, _APAc, _An], + [0, () => exports.Tag$, 0, [() => exports.MetricsAndOperator$, 0]] + ]; + exports.ObjectEncryption$ = [ + 4, + n05, + _OE, + 0, + [_SSEKMS], + [[() => exports.SSEKMSEncryption$, { [_xN]: _SK }]] + ]; + exports.SelectObjectContentEventStream$ = [ + 4, + n05, + _SOCES, + { [_st]: 1 }, + [_Rec, _Sta, _Pr2, _Cont, _End], + [[() => exports.RecordsEvent$, 0], [() => exports.StatsEvent$, 0], [() => exports.ProgressEvent$, 0], () => exports.ContinuationEvent$, () => exports.EndEvent$] + ]; + exports.AbortMultipartUpload$ = [ + 9, + n05, + _AMU, + { [_h4]: ["DELETE", "/{Key+}?x-id=AbortMultipartUpload", 204] }, + () => exports.AbortMultipartUploadRequest$, + () => exports.AbortMultipartUploadOutput$ + ]; + exports.CompleteMultipartUpload$ = [ + 9, + n05, + _CMUo, + { [_h4]: ["POST", "/{Key+}", 200] }, + () => exports.CompleteMultipartUploadRequest$, + () => exports.CompleteMultipartUploadOutput$ + ]; + exports.CopyObject$ = [ + 9, + n05, + _CO, + { [_h4]: ["PUT", "/{Key+}?x-id=CopyObject", 200] }, + () => exports.CopyObjectRequest$, + () => exports.CopyObjectOutput$ + ]; + exports.CreateBucket$ = [ + 9, + n05, + _CB, + { [_h4]: ["PUT", "/", 200] }, + () => exports.CreateBucketRequest$, + () => exports.CreateBucketOutput$ + ]; + exports.CreateBucketMetadataConfiguration$ = [ + 9, + n05, + _CBMC, + { [_hC]: "-", [_h4]: ["POST", "/?metadataConfiguration", 200] }, + () => exports.CreateBucketMetadataConfigurationRequest$, + () => __Unit + ]; + exports.CreateBucketMetadataTableConfiguration$ = [ + 9, + n05, + _CBMTC, + { [_hC]: "-", [_h4]: ["POST", "/?metadataTable", 200] }, + () => exports.CreateBucketMetadataTableConfigurationRequest$, + () => __Unit + ]; + exports.CreateMultipartUpload$ = [ + 9, + n05, + _CMUr, + { [_h4]: ["POST", "/{Key+}?uploads", 200] }, + () => exports.CreateMultipartUploadRequest$, + () => exports.CreateMultipartUploadOutput$ + ]; + exports.CreateSession$ = [ + 9, + n05, + _CSr, + { [_h4]: ["GET", "/?session", 200] }, + () => exports.CreateSessionRequest$, + () => exports.CreateSessionOutput$ + ]; + exports.DeleteBucket$ = [ + 9, + n05, + _DB, + { [_h4]: ["DELETE", "/", 204] }, + () => exports.DeleteBucketRequest$, + () => __Unit + ]; + exports.DeleteBucketAnalyticsConfiguration$ = [ + 9, + n05, + _DBAC, + { [_h4]: ["DELETE", "/?analytics", 204] }, + () => exports.DeleteBucketAnalyticsConfigurationRequest$, + () => __Unit + ]; + exports.DeleteBucketCors$ = [ + 9, + n05, + _DBC, + { [_h4]: ["DELETE", "/?cors", 204] }, + () => exports.DeleteBucketCorsRequest$, + () => __Unit + ]; + exports.DeleteBucketEncryption$ = [ + 9, + n05, + _DBE, + { [_h4]: ["DELETE", "/?encryption", 204] }, + () => exports.DeleteBucketEncryptionRequest$, + () => __Unit + ]; + exports.DeleteBucketIntelligentTieringConfiguration$ = [ + 9, + n05, + _DBITC, + { [_h4]: ["DELETE", "/?intelligent-tiering", 204] }, + () => exports.DeleteBucketIntelligentTieringConfigurationRequest$, + () => __Unit + ]; + exports.DeleteBucketInventoryConfiguration$ = [ + 9, + n05, + _DBIC, + { [_h4]: ["DELETE", "/?inventory", 204] }, + () => exports.DeleteBucketInventoryConfigurationRequest$, + () => __Unit + ]; + exports.DeleteBucketLifecycle$ = [ + 9, + n05, + _DBL, + { [_h4]: ["DELETE", "/?lifecycle", 204] }, + () => exports.DeleteBucketLifecycleRequest$, + () => __Unit + ]; + exports.DeleteBucketMetadataConfiguration$ = [ + 9, + n05, + _DBMC, + { [_h4]: ["DELETE", "/?metadataConfiguration", 204] }, + () => exports.DeleteBucketMetadataConfigurationRequest$, + () => __Unit + ]; + exports.DeleteBucketMetadataTableConfiguration$ = [ + 9, + n05, + _DBMTC, + { [_h4]: ["DELETE", "/?metadataTable", 204] }, + () => exports.DeleteBucketMetadataTableConfigurationRequest$, + () => __Unit + ]; + exports.DeleteBucketMetricsConfiguration$ = [ + 9, + n05, + _DBMCe, + { [_h4]: ["DELETE", "/?metrics", 204] }, + () => exports.DeleteBucketMetricsConfigurationRequest$, + () => __Unit + ]; + exports.DeleteBucketOwnershipControls$ = [ + 9, + n05, + _DBOC, + { [_h4]: ["DELETE", "/?ownershipControls", 204] }, + () => exports.DeleteBucketOwnershipControlsRequest$, + () => __Unit + ]; + exports.DeleteBucketPolicy$ = [ + 9, + n05, + _DBP, + { [_h4]: ["DELETE", "/?policy", 204] }, + () => exports.DeleteBucketPolicyRequest$, + () => __Unit + ]; + exports.DeleteBucketReplication$ = [ + 9, + n05, + _DBRe, + { [_h4]: ["DELETE", "/?replication", 204] }, + () => exports.DeleteBucketReplicationRequest$, + () => __Unit + ]; + exports.DeleteBucketTagging$ = [ + 9, + n05, + _DBT, + { [_h4]: ["DELETE", "/?tagging", 204] }, + () => exports.DeleteBucketTaggingRequest$, + () => __Unit + ]; + exports.DeleteBucketWebsite$ = [ + 9, + n05, + _DBW, + { [_h4]: ["DELETE", "/?website", 204] }, + () => exports.DeleteBucketWebsiteRequest$, + () => __Unit + ]; + exports.DeleteObject$ = [ + 9, + n05, + _DOel, + { [_h4]: ["DELETE", "/{Key+}?x-id=DeleteObject", 204] }, + () => exports.DeleteObjectRequest$, + () => exports.DeleteObjectOutput$ + ]; + exports.DeleteObjects$ = [ + 9, + n05, + _DOele, + { [_hC]: "-", [_h4]: ["POST", "/?delete", 200] }, + () => exports.DeleteObjectsRequest$, + () => exports.DeleteObjectsOutput$ + ]; + exports.DeleteObjectTagging$ = [ + 9, + n05, + _DOT, + { [_h4]: ["DELETE", "/{Key+}?tagging", 204] }, + () => exports.DeleteObjectTaggingRequest$, + () => exports.DeleteObjectTaggingOutput$ + ]; + exports.DeletePublicAccessBlock$ = [ + 9, + n05, + _DPAB, + { [_h4]: ["DELETE", "/?publicAccessBlock", 204] }, + () => exports.DeletePublicAccessBlockRequest$, + () => __Unit + ]; + exports.GetBucketAbac$ = [ + 9, + n05, + _GBA, + { [_h4]: ["GET", "/?abac", 200] }, + () => exports.GetBucketAbacRequest$, + () => exports.GetBucketAbacOutput$ + ]; + exports.GetBucketAccelerateConfiguration$ = [ + 9, + n05, + _GBAC, + { [_h4]: ["GET", "/?accelerate", 200] }, + () => exports.GetBucketAccelerateConfigurationRequest$, + () => exports.GetBucketAccelerateConfigurationOutput$ + ]; + exports.GetBucketAcl$ = [ + 9, + n05, + _GBAe, + { [_h4]: ["GET", "/?acl", 200] }, + () => exports.GetBucketAclRequest$, + () => exports.GetBucketAclOutput$ + ]; + exports.GetBucketAnalyticsConfiguration$ = [ + 9, + n05, + _GBACe, + { [_h4]: ["GET", "/?analytics&x-id=GetBucketAnalyticsConfiguration", 200] }, + () => exports.GetBucketAnalyticsConfigurationRequest$, + () => exports.GetBucketAnalyticsConfigurationOutput$ + ]; + exports.GetBucketCors$ = [ + 9, + n05, + _GBC, + { [_h4]: ["GET", "/?cors", 200] }, + () => exports.GetBucketCorsRequest$, + () => exports.GetBucketCorsOutput$ + ]; + exports.GetBucketEncryption$ = [ + 9, + n05, + _GBE, + { [_h4]: ["GET", "/?encryption", 200] }, + () => exports.GetBucketEncryptionRequest$, + () => exports.GetBucketEncryptionOutput$ + ]; + exports.GetBucketIntelligentTieringConfiguration$ = [ + 9, + n05, + _GBITC, + { [_h4]: ["GET", "/?intelligent-tiering&x-id=GetBucketIntelligentTieringConfiguration", 200] }, + () => exports.GetBucketIntelligentTieringConfigurationRequest$, + () => exports.GetBucketIntelligentTieringConfigurationOutput$ + ]; + exports.GetBucketInventoryConfiguration$ = [ + 9, + n05, + _GBIC, + { [_h4]: ["GET", "/?inventory&x-id=GetBucketInventoryConfiguration", 200] }, + () => exports.GetBucketInventoryConfigurationRequest$, + () => exports.GetBucketInventoryConfigurationOutput$ + ]; + exports.GetBucketLifecycleConfiguration$ = [ + 9, + n05, + _GBLC, + { [_h4]: ["GET", "/?lifecycle", 200] }, + () => exports.GetBucketLifecycleConfigurationRequest$, + () => exports.GetBucketLifecycleConfigurationOutput$ + ]; + exports.GetBucketLocation$ = [ + 9, + n05, + _GBL, + { [_h4]: ["GET", "/?location", 200] }, + () => exports.GetBucketLocationRequest$, + () => exports.GetBucketLocationOutput$ + ]; + exports.GetBucketLogging$ = [ + 9, + n05, + _GBLe, + { [_h4]: ["GET", "/?logging", 200] }, + () => exports.GetBucketLoggingRequest$, + () => exports.GetBucketLoggingOutput$ + ]; + exports.GetBucketMetadataConfiguration$ = [ + 9, + n05, + _GBMC, + { [_h4]: ["GET", "/?metadataConfiguration", 200] }, + () => exports.GetBucketMetadataConfigurationRequest$, + () => exports.GetBucketMetadataConfigurationOutput$ + ]; + exports.GetBucketMetadataTableConfiguration$ = [ + 9, + n05, + _GBMTC, + { [_h4]: ["GET", "/?metadataTable", 200] }, + () => exports.GetBucketMetadataTableConfigurationRequest$, + () => exports.GetBucketMetadataTableConfigurationOutput$ + ]; + exports.GetBucketMetricsConfiguration$ = [ + 9, + n05, + _GBMCe, + { [_h4]: ["GET", "/?metrics&x-id=GetBucketMetricsConfiguration", 200] }, + () => exports.GetBucketMetricsConfigurationRequest$, + () => exports.GetBucketMetricsConfigurationOutput$ + ]; + exports.GetBucketNotificationConfiguration$ = [ + 9, + n05, + _GBNC, + { [_h4]: ["GET", "/?notification", 200] }, + () => exports.GetBucketNotificationConfigurationRequest$, + () => exports.NotificationConfiguration$ + ]; + exports.GetBucketOwnershipControls$ = [ + 9, + n05, + _GBOC, + { [_h4]: ["GET", "/?ownershipControls", 200] }, + () => exports.GetBucketOwnershipControlsRequest$, + () => exports.GetBucketOwnershipControlsOutput$ + ]; + exports.GetBucketPolicy$ = [ + 9, + n05, + _GBP, + { [_h4]: ["GET", "/?policy", 200] }, + () => exports.GetBucketPolicyRequest$, + () => exports.GetBucketPolicyOutput$ + ]; + exports.GetBucketPolicyStatus$ = [ + 9, + n05, + _GBPS, + { [_h4]: ["GET", "/?policyStatus", 200] }, + () => exports.GetBucketPolicyStatusRequest$, + () => exports.GetBucketPolicyStatusOutput$ + ]; + exports.GetBucketReplication$ = [ + 9, + n05, + _GBR, + { [_h4]: ["GET", "/?replication", 200] }, + () => exports.GetBucketReplicationRequest$, + () => exports.GetBucketReplicationOutput$ + ]; + exports.GetBucketRequestPayment$ = [ + 9, + n05, + _GBRP, + { [_h4]: ["GET", "/?requestPayment", 200] }, + () => exports.GetBucketRequestPaymentRequest$, + () => exports.GetBucketRequestPaymentOutput$ + ]; + exports.GetBucketTagging$ = [ + 9, + n05, + _GBT, + { [_h4]: ["GET", "/?tagging", 200] }, + () => exports.GetBucketTaggingRequest$, + () => exports.GetBucketTaggingOutput$ + ]; + exports.GetBucketVersioning$ = [ + 9, + n05, + _GBV, + { [_h4]: ["GET", "/?versioning", 200] }, + () => exports.GetBucketVersioningRequest$, + () => exports.GetBucketVersioningOutput$ + ]; + exports.GetBucketWebsite$ = [ + 9, + n05, + _GBW, + { [_h4]: ["GET", "/?website", 200] }, + () => exports.GetBucketWebsiteRequest$, + () => exports.GetBucketWebsiteOutput$ + ]; + exports.GetObject$ = [ + 9, + n05, + _GO, + { [_hC]: "-", [_h4]: ["GET", "/{Key+}?x-id=GetObject", 200] }, + () => exports.GetObjectRequest$, + () => exports.GetObjectOutput$ + ]; + exports.GetObjectAcl$ = [ + 9, + n05, + _GOA, + { [_h4]: ["GET", "/{Key+}?acl", 200] }, + () => exports.GetObjectAclRequest$, + () => exports.GetObjectAclOutput$ + ]; + exports.GetObjectAttributes$ = [ + 9, + n05, + _GOAe, + { [_h4]: ["GET", "/{Key+}?attributes", 200] }, + () => exports.GetObjectAttributesRequest$, + () => exports.GetObjectAttributesOutput$ + ]; + exports.GetObjectLegalHold$ = [ + 9, + n05, + _GOLH, + { [_h4]: ["GET", "/{Key+}?legal-hold", 200] }, + () => exports.GetObjectLegalHoldRequest$, + () => exports.GetObjectLegalHoldOutput$ + ]; + exports.GetObjectLockConfiguration$ = [ + 9, + n05, + _GOLC, + { [_h4]: ["GET", "/?object-lock", 200] }, + () => exports.GetObjectLockConfigurationRequest$, + () => exports.GetObjectLockConfigurationOutput$ + ]; + exports.GetObjectRetention$ = [ + 9, + n05, + _GORe, + { [_h4]: ["GET", "/{Key+}?retention", 200] }, + () => exports.GetObjectRetentionRequest$, + () => exports.GetObjectRetentionOutput$ + ]; + exports.GetObjectTagging$ = [ + 9, + n05, + _GOT, + { [_h4]: ["GET", "/{Key+}?tagging", 200] }, + () => exports.GetObjectTaggingRequest$, + () => exports.GetObjectTaggingOutput$ + ]; + exports.GetObjectTorrent$ = [ + 9, + n05, + _GOTe, + { [_h4]: ["GET", "/{Key+}?torrent", 200] }, + () => exports.GetObjectTorrentRequest$, + () => exports.GetObjectTorrentOutput$ + ]; + exports.GetPublicAccessBlock$ = [ + 9, + n05, + _GPAB, + { [_h4]: ["GET", "/?publicAccessBlock", 200] }, + () => exports.GetPublicAccessBlockRequest$, + () => exports.GetPublicAccessBlockOutput$ + ]; + exports.HeadBucket$ = [ + 9, + n05, + _HB, + { [_h4]: ["HEAD", "/", 200] }, + () => exports.HeadBucketRequest$, + () => exports.HeadBucketOutput$ + ]; + exports.HeadObject$ = [ + 9, + n05, + _HO, + { [_h4]: ["HEAD", "/{Key+}", 200] }, + () => exports.HeadObjectRequest$, + () => exports.HeadObjectOutput$ + ]; + exports.ListBucketAnalyticsConfigurations$ = [ + 9, + n05, + _LBAC, + { [_h4]: ["GET", "/?analytics&x-id=ListBucketAnalyticsConfigurations", 200] }, + () => exports.ListBucketAnalyticsConfigurationsRequest$, + () => exports.ListBucketAnalyticsConfigurationsOutput$ + ]; + exports.ListBucketIntelligentTieringConfigurations$ = [ + 9, + n05, + _LBITC, + { [_h4]: ["GET", "/?intelligent-tiering&x-id=ListBucketIntelligentTieringConfigurations", 200] }, + () => exports.ListBucketIntelligentTieringConfigurationsRequest$, + () => exports.ListBucketIntelligentTieringConfigurationsOutput$ + ]; + exports.ListBucketInventoryConfigurations$ = [ + 9, + n05, + _LBIC, + { [_h4]: ["GET", "/?inventory&x-id=ListBucketInventoryConfigurations", 200] }, + () => exports.ListBucketInventoryConfigurationsRequest$, + () => exports.ListBucketInventoryConfigurationsOutput$ + ]; + exports.ListBucketMetricsConfigurations$ = [ + 9, + n05, + _LBMC, + { [_h4]: ["GET", "/?metrics&x-id=ListBucketMetricsConfigurations", 200] }, + () => exports.ListBucketMetricsConfigurationsRequest$, + () => exports.ListBucketMetricsConfigurationsOutput$ + ]; + exports.ListBuckets$ = [ + 9, + n05, + _LB, + { [_h4]: ["GET", "/?x-id=ListBuckets", 200] }, + () => exports.ListBucketsRequest$, + () => exports.ListBucketsOutput$ + ]; + exports.ListDirectoryBuckets$ = [ + 9, + n05, + _LDB, + { [_h4]: ["GET", "/?x-id=ListDirectoryBuckets", 200] }, + () => exports.ListDirectoryBucketsRequest$, + () => exports.ListDirectoryBucketsOutput$ + ]; + exports.ListMultipartUploads$ = [ + 9, + n05, + _LMU, + { [_h4]: ["GET", "/?uploads", 200] }, + () => exports.ListMultipartUploadsRequest$, + () => exports.ListMultipartUploadsOutput$ + ]; + exports.ListObjects$ = [ + 9, + n05, + _LO, + { [_h4]: ["GET", "/", 200] }, + () => exports.ListObjectsRequest$, + () => exports.ListObjectsOutput$ + ]; + exports.ListObjectsV2$ = [ + 9, + n05, + _LOV, + { [_h4]: ["GET", "/?list-type=2", 200] }, + () => exports.ListObjectsV2Request$, + () => exports.ListObjectsV2Output$ + ]; + exports.ListObjectVersions$ = [ + 9, + n05, + _LOVi, + { [_h4]: ["GET", "/?versions", 200] }, + () => exports.ListObjectVersionsRequest$, + () => exports.ListObjectVersionsOutput$ + ]; + exports.ListParts$ = [ + 9, + n05, + _LP, + { [_h4]: ["GET", "/{Key+}?x-id=ListParts", 200] }, + () => exports.ListPartsRequest$, + () => exports.ListPartsOutput$ + ]; + exports.PutBucketAbac$ = [ + 9, + n05, + _PBA, + { [_hC]: "-", [_h4]: ["PUT", "/?abac", 200] }, + () => exports.PutBucketAbacRequest$, + () => __Unit + ]; + exports.PutBucketAccelerateConfiguration$ = [ + 9, + n05, + _PBAC, + { [_hC]: "-", [_h4]: ["PUT", "/?accelerate", 200] }, + () => exports.PutBucketAccelerateConfigurationRequest$, + () => __Unit + ]; + exports.PutBucketAcl$ = [ + 9, + n05, + _PBAu, + { [_hC]: "-", [_h4]: ["PUT", "/?acl", 200] }, + () => exports.PutBucketAclRequest$, + () => __Unit + ]; + exports.PutBucketAnalyticsConfiguration$ = [ + 9, + n05, + _PBACu, + { [_h4]: ["PUT", "/?analytics", 200] }, + () => exports.PutBucketAnalyticsConfigurationRequest$, + () => __Unit + ]; + exports.PutBucketCors$ = [ + 9, + n05, + _PBC, + { [_hC]: "-", [_h4]: ["PUT", "/?cors", 200] }, + () => exports.PutBucketCorsRequest$, + () => __Unit + ]; + exports.PutBucketEncryption$ = [ + 9, + n05, + _PBE, + { [_hC]: "-", [_h4]: ["PUT", "/?encryption", 200] }, + () => exports.PutBucketEncryptionRequest$, + () => __Unit + ]; + exports.PutBucketIntelligentTieringConfiguration$ = [ + 9, + n05, + _PBITC, + { [_h4]: ["PUT", "/?intelligent-tiering", 200] }, + () => exports.PutBucketIntelligentTieringConfigurationRequest$, + () => __Unit + ]; + exports.PutBucketInventoryConfiguration$ = [ + 9, + n05, + _PBIC, + { [_h4]: ["PUT", "/?inventory", 200] }, + () => exports.PutBucketInventoryConfigurationRequest$, + () => __Unit + ]; + exports.PutBucketLifecycleConfiguration$ = [ + 9, + n05, + _PBLC, + { [_hC]: "-", [_h4]: ["PUT", "/?lifecycle", 200] }, + () => exports.PutBucketLifecycleConfigurationRequest$, + () => exports.PutBucketLifecycleConfigurationOutput$ + ]; + exports.PutBucketLogging$ = [ + 9, + n05, + _PBL, + { [_hC]: "-", [_h4]: ["PUT", "/?logging", 200] }, + () => exports.PutBucketLoggingRequest$, + () => __Unit + ]; + exports.PutBucketMetricsConfiguration$ = [ + 9, + n05, + _PBMC, + { [_h4]: ["PUT", "/?metrics", 200] }, + () => exports.PutBucketMetricsConfigurationRequest$, + () => __Unit + ]; + exports.PutBucketNotificationConfiguration$ = [ + 9, + n05, + _PBNC, + { [_h4]: ["PUT", "/?notification", 200] }, + () => exports.PutBucketNotificationConfigurationRequest$, + () => __Unit + ]; + exports.PutBucketOwnershipControls$ = [ + 9, + n05, + _PBOC, + { [_hC]: "-", [_h4]: ["PUT", "/?ownershipControls", 200] }, + () => exports.PutBucketOwnershipControlsRequest$, + () => __Unit + ]; + exports.PutBucketPolicy$ = [ + 9, + n05, + _PBP, + { [_hC]: "-", [_h4]: ["PUT", "/?policy", 200] }, + () => exports.PutBucketPolicyRequest$, + () => __Unit + ]; + exports.PutBucketReplication$ = [ + 9, + n05, + _PBR, + { [_hC]: "-", [_h4]: ["PUT", "/?replication", 200] }, + () => exports.PutBucketReplicationRequest$, + () => __Unit + ]; + exports.PutBucketRequestPayment$ = [ + 9, + n05, + _PBRP, + { [_hC]: "-", [_h4]: ["PUT", "/?requestPayment", 200] }, + () => exports.PutBucketRequestPaymentRequest$, + () => __Unit + ]; + exports.PutBucketTagging$ = [ + 9, + n05, + _PBT, + { [_hC]: "-", [_h4]: ["PUT", "/?tagging", 200] }, + () => exports.PutBucketTaggingRequest$, + () => __Unit + ]; + exports.PutBucketVersioning$ = [ + 9, + n05, + _PBV, + { [_hC]: "-", [_h4]: ["PUT", "/?versioning", 200] }, + () => exports.PutBucketVersioningRequest$, + () => __Unit + ]; + exports.PutBucketWebsite$ = [ + 9, + n05, + _PBW, + { [_hC]: "-", [_h4]: ["PUT", "/?website", 200] }, + () => exports.PutBucketWebsiteRequest$, + () => __Unit + ]; + exports.PutObject$ = [ + 9, + n05, + _PO, + { [_hC]: "-", [_h4]: ["PUT", "/{Key+}?x-id=PutObject", 200] }, + () => exports.PutObjectRequest$, + () => exports.PutObjectOutput$ + ]; + exports.PutObjectAcl$ = [ + 9, + n05, + _POA, + { [_hC]: "-", [_h4]: ["PUT", "/{Key+}?acl", 200] }, + () => exports.PutObjectAclRequest$, + () => exports.PutObjectAclOutput$ + ]; + exports.PutObjectLegalHold$ = [ + 9, + n05, + _POLH, + { [_hC]: "-", [_h4]: ["PUT", "/{Key+}?legal-hold", 200] }, + () => exports.PutObjectLegalHoldRequest$, + () => exports.PutObjectLegalHoldOutput$ + ]; + exports.PutObjectLockConfiguration$ = [ + 9, + n05, + _POLC, + { [_hC]: "-", [_h4]: ["PUT", "/?object-lock", 200] }, + () => exports.PutObjectLockConfigurationRequest$, + () => exports.PutObjectLockConfigurationOutput$ + ]; + exports.PutObjectRetention$ = [ + 9, + n05, + _PORu, + { [_hC]: "-", [_h4]: ["PUT", "/{Key+}?retention", 200] }, + () => exports.PutObjectRetentionRequest$, + () => exports.PutObjectRetentionOutput$ + ]; + exports.PutObjectTagging$ = [ + 9, + n05, + _POT, + { [_hC]: "-", [_h4]: ["PUT", "/{Key+}?tagging", 200] }, + () => exports.PutObjectTaggingRequest$, + () => exports.PutObjectTaggingOutput$ + ]; + exports.PutPublicAccessBlock$ = [ + 9, + n05, + _PPAB, + { [_hC]: "-", [_h4]: ["PUT", "/?publicAccessBlock", 200] }, + () => exports.PutPublicAccessBlockRequest$, + () => __Unit + ]; + exports.RenameObject$ = [ + 9, + n05, + _RO, + { [_h4]: ["PUT", "/{Key+}?renameObject", 200] }, + () => exports.RenameObjectRequest$, + () => exports.RenameObjectOutput$ + ]; + exports.RestoreObject$ = [ + 9, + n05, + _ROe, + { [_hC]: "-", [_h4]: ["POST", "/{Key+}?restore", 200] }, + () => exports.RestoreObjectRequest$, + () => exports.RestoreObjectOutput$ + ]; + exports.SelectObjectContent$ = [ + 9, + n05, + _SOC, + { [_h4]: ["POST", "/{Key+}?select&select-type=2", 200] }, + () => exports.SelectObjectContentRequest$, + () => exports.SelectObjectContentOutput$ + ]; + exports.UpdateBucketMetadataInventoryTableConfiguration$ = [ + 9, + n05, + _UBMITC, + { [_hC]: "-", [_h4]: ["PUT", "/?metadataInventoryTable", 200] }, + () => exports.UpdateBucketMetadataInventoryTableConfigurationRequest$, + () => __Unit + ]; + exports.UpdateBucketMetadataJournalTableConfiguration$ = [ + 9, + n05, + _UBMJTC, + { [_hC]: "-", [_h4]: ["PUT", "/?metadataJournalTable", 200] }, + () => exports.UpdateBucketMetadataJournalTableConfigurationRequest$, + () => __Unit + ]; + exports.UpdateObjectEncryption$ = [ + 9, + n05, + _UOE, + { [_hC]: "-", [_h4]: ["PUT", "/{Key+}?encryption", 200] }, + () => exports.UpdateObjectEncryptionRequest$, + () => exports.UpdateObjectEncryptionResponse$ + ]; + exports.UploadPart$ = [ + 9, + n05, + _UP, + { [_hC]: "-", [_h4]: ["PUT", "/{Key+}?x-id=UploadPart", 200] }, + () => exports.UploadPartRequest$, + () => exports.UploadPartOutput$ + ]; + exports.UploadPartCopy$ = [ + 9, + n05, + _UPC, + { [_h4]: ["PUT", "/{Key+}?x-id=UploadPartCopy", 200] }, + () => exports.UploadPartCopyRequest$, + () => exports.UploadPartCopyOutput$ + ]; + exports.WriteGetObjectResponse$ = [ + 9, + n05, + _WGOR, + { [_en]: ["{RequestRoute}."], [_h4]: ["POST", "/WriteGetObjectResponse", 200] }, + () => exports.WriteGetObjectResponseRequest$, + () => __Unit + ]; + } +}); + +// node_modules/.pnpm/@aws-sdk+client-s3@3.1030.0/node_modules/@aws-sdk/client-s3/package.json +var require_package2 = __commonJS({ + "node_modules/.pnpm/@aws-sdk+client-s3@3.1030.0/node_modules/@aws-sdk/client-s3/package.json"(exports, module) { + module.exports = { + name: "@aws-sdk/client-s3", + description: "AWS SDK for JavaScript S3 Client for Node.js, Browser and React Native", + version: "3.1030.0", + scripts: { + build: "concurrently 'yarn:build:types' 'yarn:build:es' && yarn build:cjs", + "build:cjs": "node ../../scripts/compilation/inline client-s3", + "build:es": "tsc -p tsconfig.es.json", + "build:include:deps": 'yarn g:turbo run build -F="$npm_package_name"', + "build:types": "tsc -p tsconfig.types.json", + "build:types:downlevel": "downlevel-dts dist-types dist-types/ts3.4", + clean: "premove dist-cjs dist-es dist-types tsconfig.cjs.tsbuildinfo tsconfig.es.tsbuildinfo tsconfig.types.tsbuildinfo", + "extract:docs": "api-extractor run --local", + "generate:client": "node ../../scripts/generate-clients/single-service --solo s3", + test: "yarn g:vitest run", + "test:browser": "node ./test/browser-build/esbuild && yarn g:vitest run -c vitest.config.browser.mts", + "test:browser:watch": "node ./test/browser-build/esbuild && yarn g:vitest watch -c vitest.config.browser.mts", + "test:e2e": "yarn g:vitest run -c vitest.config.e2e.mts && yarn test:browser", + "test:e2e:watch": "yarn g:vitest watch -c vitest.config.e2e.mts", + "test:index": "tsc --noEmit ./test/index-types.ts && node ./test/index-objects.spec.mjs", + "test:integration": "yarn g:vitest run -c vitest.config.integ.mts", + "test:integration:watch": "yarn g:vitest watch -c vitest.config.integ.mts", + "test:watch": "yarn g:vitest watch" + }, + main: "./dist-cjs/index.js", + types: "./dist-types/index.d.ts", + module: "./dist-es/index.js", + sideEffects: false, + dependencies: { + "@aws-crypto/sha1-browser": "5.2.0", + "@aws-crypto/sha256-browser": "5.2.0", + "@aws-crypto/sha256-js": "5.2.0", + "@aws-sdk/core": "^3.973.27", + "@aws-sdk/credential-provider-node": "^3.972.30", + "@aws-sdk/middleware-bucket-endpoint": "^3.972.9", + "@aws-sdk/middleware-expect-continue": "^3.972.9", + "@aws-sdk/middleware-flexible-checksums": "^3.974.7", + "@aws-sdk/middleware-host-header": "^3.972.9", + "@aws-sdk/middleware-location-constraint": "^3.972.9", + "@aws-sdk/middleware-logger": "^3.972.9", + "@aws-sdk/middleware-recursion-detection": "^3.972.10", + "@aws-sdk/middleware-sdk-s3": "^3.972.28", + "@aws-sdk/middleware-ssec": "^3.972.9", + "@aws-sdk/middleware-user-agent": "^3.972.29", + "@aws-sdk/region-config-resolver": "^3.972.11", + "@aws-sdk/signature-v4-multi-region": "^3.996.16", + "@aws-sdk/types": "^3.973.7", + "@aws-sdk/util-endpoints": "^3.996.6", + "@aws-sdk/util-user-agent-browser": "^3.972.9", + "@aws-sdk/util-user-agent-node": "^3.973.15", + "@smithy/config-resolver": "^4.4.14", + "@smithy/core": "^3.23.14", + "@smithy/eventstream-serde-browser": "^4.2.13", + "@smithy/eventstream-serde-config-resolver": "^4.3.13", + "@smithy/eventstream-serde-node": "^4.2.13", + "@smithy/fetch-http-handler": "^5.3.16", + "@smithy/hash-blob-browser": "^4.2.14", + "@smithy/hash-node": "^4.2.13", + "@smithy/hash-stream-node": "^4.2.13", + "@smithy/invalid-dependency": "^4.2.13", + "@smithy/md5-js": "^4.2.13", + "@smithy/middleware-content-length": "^4.2.13", + "@smithy/middleware-endpoint": "^4.4.29", + "@smithy/middleware-retry": "^4.5.0", + "@smithy/middleware-serde": "^4.2.17", + "@smithy/middleware-stack": "^4.2.13", + "@smithy/node-config-provider": "^4.3.13", + "@smithy/node-http-handler": "^4.5.2", + "@smithy/protocol-http": "^5.3.13", + "@smithy/smithy-client": "^4.12.9", + "@smithy/types": "^4.14.0", + "@smithy/url-parser": "^4.2.13", + "@smithy/util-base64": "^4.3.2", + "@smithy/util-body-length-browser": "^4.2.2", + "@smithy/util-body-length-node": "^4.2.3", + "@smithy/util-defaults-mode-browser": "^4.3.45", + "@smithy/util-defaults-mode-node": "^4.2.49", + "@smithy/util-endpoints": "^3.3.4", + "@smithy/util-middleware": "^4.2.13", + "@smithy/util-retry": "^4.3.0", + "@smithy/util-stream": "^4.5.22", + "@smithy/util-utf8": "^4.2.2", + "@smithy/util-waiter": "^4.2.15", + tslib: "^2.6.2" + }, + devDependencies: { + "@aws-sdk/signature-v4-crt": "3.1030.0", + "@smithy/snapshot-testing": "^2.0.5", + "@tsconfig/node20": "20.1.8", + "@types/node": "^20.14.8", + concurrently: "7.0.0", + "downlevel-dts": "0.10.1", + premove: "4.0.0", + typescript: "~5.8.3", + vitest: "^4.0.17" + }, + engines: { + node: ">=20.0.0" + }, + typesVersions: { + "<4.5": { + "dist-types/*": [ + "dist-types/ts3.4/*" + ] + } + }, + files: [ + "dist-*/**" + ], + author: { + name: "AWS SDK for JavaScript Team", + url: "https://aws.amazon.com/javascript/" + }, + license: "Apache-2.0", + browser: { + "./dist-es/runtimeConfig": "./dist-es/runtimeConfig.browser" + }, + "react-native": { + "./dist-es/runtimeConfig": "./dist-es/runtimeConfig.native" + }, + homepage: "https://github.com/aws/aws-sdk-js-v3/tree/main/clients/client-s3", + repository: { + type: "git", + url: "https://github.com/aws/aws-sdk-js-v3.git", + directory: "clients/client-s3" + } + }; + } +}); + +// node_modules/.pnpm/@aws-sdk+credential-provider-env@3.972.25/node_modules/@aws-sdk/credential-provider-env/dist-cjs/index.js +var require_dist_cjs48 = __commonJS({ + "node_modules/.pnpm/@aws-sdk+credential-provider-env@3.972.25/node_modules/@aws-sdk/credential-provider-env/dist-cjs/index.js"(exports) { + "use strict"; + var client2 = (init_client2(), __toCommonJS(client_exports)); + var propertyProvider = require_dist_cjs41(); + var ENV_KEY = "AWS_ACCESS_KEY_ID"; + var ENV_SECRET = "AWS_SECRET_ACCESS_KEY"; + var ENV_SESSION = "AWS_SESSION_TOKEN"; + var ENV_EXPIRATION = "AWS_CREDENTIAL_EXPIRATION"; + var ENV_CREDENTIAL_SCOPE = "AWS_CREDENTIAL_SCOPE"; + var ENV_ACCOUNT_ID = "AWS_ACCOUNT_ID"; + var fromEnv = (init2) => async () => { + init2?.logger?.debug("@aws-sdk/credential-provider-env - fromEnv"); + const accessKeyId = process.env[ENV_KEY]; + const secretAccessKey = process.env[ENV_SECRET]; + const sessionToken = process.env[ENV_SESSION]; + const expiry = process.env[ENV_EXPIRATION]; + const credentialScope = process.env[ENV_CREDENTIAL_SCOPE]; + const accountId = process.env[ENV_ACCOUNT_ID]; + if (accessKeyId && secretAccessKey) { + const credentials = { + accessKeyId, + secretAccessKey, + ...sessionToken && { sessionToken }, + ...expiry && { expiration: new Date(expiry) }, + ...credentialScope && { credentialScope }, + ...accountId && { accountId } + }; + client2.setCredentialFeature(credentials, "CREDENTIALS_ENV_VARS", "g"); + return credentials; + } + throw new propertyProvider.CredentialsProviderError("Unable to find environment variable credentials.", { logger: init2?.logger }); + }; + exports.ENV_ACCOUNT_ID = ENV_ACCOUNT_ID; + exports.ENV_CREDENTIAL_SCOPE = ENV_CREDENTIAL_SCOPE; + exports.ENV_EXPIRATION = ENV_EXPIRATION; + exports.ENV_KEY = ENV_KEY; + exports.ENV_SECRET = ENV_SECRET; + exports.ENV_SESSION = ENV_SESSION; + exports.fromEnv = fromEnv; + } +}); + +// node_modules/.pnpm/@smithy+credential-provider-imds@4.2.13/node_modules/@smithy/credential-provider-imds/dist-cjs/index.js +var require_dist_cjs49 = __commonJS({ + "node_modules/.pnpm/@smithy+credential-provider-imds@4.2.13/node_modules/@smithy/credential-provider-imds/dist-cjs/index.js"(exports) { + "use strict"; + var propertyProvider = require_dist_cjs41(); + var url2 = __require("url"); + var buffer2 = __require("buffer"); + var http = __require("http"); + var nodeConfigProvider = require_dist_cjs43(); + var urlParser = require_dist_cjs25(); + function httpRequest2(options) { + return new Promise((resolve4, reject) => { + const req = http.request({ + method: "GET", + ...options, + hostname: options.hostname?.replace(/^\[(.+)\]$/, "$1") + }); + req.on("error", (err) => { + reject(Object.assign(new propertyProvider.ProviderError("Unable to connect to instance metadata service"), err)); + req.destroy(); + }); + req.on("timeout", () => { + reject(new propertyProvider.ProviderError("TimeoutError from instance metadata service")); + req.destroy(); + }); + req.on("response", (res) => { + const { statusCode = 400 } = res; + if (statusCode < 200 || 300 <= statusCode) { + reject(Object.assign(new propertyProvider.ProviderError("Error response received from instance metadata service"), { statusCode })); + req.destroy(); + } + const chunks = []; + res.on("data", (chunk) => { + chunks.push(chunk); + }); + res.on("end", () => { + resolve4(buffer2.Buffer.concat(chunks)); + req.destroy(); + }); + }); + req.end(); + }); + } + var isImdsCredentials = (arg) => Boolean(arg) && typeof arg === "object" && typeof arg.AccessKeyId === "string" && typeof arg.SecretAccessKey === "string" && typeof arg.Token === "string" && typeof arg.Expiration === "string"; + var fromImdsCredentials = (creds) => ({ + accessKeyId: creds.AccessKeyId, + secretAccessKey: creds.SecretAccessKey, + sessionToken: creds.Token, + expiration: new Date(creds.Expiration), + ...creds.AccountId && { accountId: creds.AccountId } + }); + var DEFAULT_TIMEOUT = 1e3; + var DEFAULT_MAX_RETRIES = 0; + var providerConfigFromInit = ({ maxRetries = DEFAULT_MAX_RETRIES, timeout = DEFAULT_TIMEOUT }) => ({ maxRetries, timeout }); + var retry = (toRetry, maxRetries) => { + let promise2 = toRetry(); + for (let i5 = 0; i5 < maxRetries; i5++) { + promise2 = promise2.catch(toRetry); + } + return promise2; + }; + var ENV_CMDS_FULL_URI = "AWS_CONTAINER_CREDENTIALS_FULL_URI"; + var ENV_CMDS_RELATIVE_URI = "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI"; + var ENV_CMDS_AUTH_TOKEN = "AWS_CONTAINER_AUTHORIZATION_TOKEN"; + var fromContainerMetadata = (init2 = {}) => { + const { timeout, maxRetries } = providerConfigFromInit(init2); + return () => retry(async () => { + const requestOptions = await getCmdsUri({ logger: init2.logger }); + const credsResponse = JSON.parse(await requestFromEcsImds(timeout, requestOptions)); + if (!isImdsCredentials(credsResponse)) { + throw new propertyProvider.CredentialsProviderError("Invalid response received from instance metadata service.", { + logger: init2.logger + }); + } + return fromImdsCredentials(credsResponse); + }, maxRetries); + }; + var requestFromEcsImds = async (timeout, options) => { + if (process.env[ENV_CMDS_AUTH_TOKEN]) { + options.headers = { + ...options.headers, + Authorization: process.env[ENV_CMDS_AUTH_TOKEN] + }; + } + const buffer3 = await httpRequest2({ + ...options, + timeout + }); + return buffer3.toString(); + }; + var CMDS_IP = "169.254.170.2"; + var GREENGRASS_HOSTS = { + localhost: true, + "127.0.0.1": true + }; + var GREENGRASS_PROTOCOLS = { + "http:": true, + "https:": true + }; + var getCmdsUri = async ({ logger: logger4 }) => { + if (process.env[ENV_CMDS_RELATIVE_URI]) { + return { + hostname: CMDS_IP, + path: process.env[ENV_CMDS_RELATIVE_URI] + }; + } + if (process.env[ENV_CMDS_FULL_URI]) { + const parsed = url2.parse(process.env[ENV_CMDS_FULL_URI]); + if (!parsed.hostname || !(parsed.hostname in GREENGRASS_HOSTS)) { + throw new propertyProvider.CredentialsProviderError(`${parsed.hostname} is not a valid container metadata service hostname`, { + tryNextLink: false, + logger: logger4 + }); + } + if (!parsed.protocol || !(parsed.protocol in GREENGRASS_PROTOCOLS)) { + throw new propertyProvider.CredentialsProviderError(`${parsed.protocol} is not a valid container metadata service protocol`, { + tryNextLink: false, + logger: logger4 + }); + } + return { + ...parsed, + port: parsed.port ? parseInt(parsed.port, 10) : void 0 + }; + } + throw new propertyProvider.CredentialsProviderError(`The container metadata credential provider cannot be used unless the ${ENV_CMDS_RELATIVE_URI} or ${ENV_CMDS_FULL_URI} environment variable is set`, { + tryNextLink: false, + logger: logger4 + }); + }; + var InstanceMetadataV1FallbackError = class _InstanceMetadataV1FallbackError extends propertyProvider.CredentialsProviderError { + tryNextLink; + name = "InstanceMetadataV1FallbackError"; + constructor(message2, tryNextLink = true) { + super(message2, tryNextLink); + this.tryNextLink = tryNextLink; + Object.setPrototypeOf(this, _InstanceMetadataV1FallbackError.prototype); + } + }; + exports.Endpoint = void 0; + (function(Endpoint) { + Endpoint["IPv4"] = "http://169.254.169.254"; + Endpoint["IPv6"] = "http://[fd00:ec2::254]"; + })(exports.Endpoint || (exports.Endpoint = {})); + var ENV_ENDPOINT_NAME = "AWS_EC2_METADATA_SERVICE_ENDPOINT"; + var CONFIG_ENDPOINT_NAME = "ec2_metadata_service_endpoint"; + var ENDPOINT_CONFIG_OPTIONS = { + environmentVariableSelector: (env2) => env2[ENV_ENDPOINT_NAME], + configFileSelector: (profile) => profile[CONFIG_ENDPOINT_NAME], + default: void 0 + }; + var EndpointMode; + (function(EndpointMode2) { + EndpointMode2["IPv4"] = "IPv4"; + EndpointMode2["IPv6"] = "IPv6"; + })(EndpointMode || (EndpointMode = {})); + var ENV_ENDPOINT_MODE_NAME = "AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE"; + var CONFIG_ENDPOINT_MODE_NAME = "ec2_metadata_service_endpoint_mode"; + var ENDPOINT_MODE_CONFIG_OPTIONS = { + environmentVariableSelector: (env2) => env2[ENV_ENDPOINT_MODE_NAME], + configFileSelector: (profile) => profile[CONFIG_ENDPOINT_MODE_NAME], + default: EndpointMode.IPv4 + }; + var getInstanceMetadataEndpoint = async () => urlParser.parseUrl(await getFromEndpointConfig() || await getFromEndpointModeConfig()); + var getFromEndpointConfig = async () => nodeConfigProvider.loadConfig(ENDPOINT_CONFIG_OPTIONS)(); + var getFromEndpointModeConfig = async () => { + const endpointMode = await nodeConfigProvider.loadConfig(ENDPOINT_MODE_CONFIG_OPTIONS)(); + switch (endpointMode) { + case EndpointMode.IPv4: + return exports.Endpoint.IPv4; + case EndpointMode.IPv6: + return exports.Endpoint.IPv6; + default: + throw new Error(`Unsupported endpoint mode: ${endpointMode}. Select from ${Object.values(EndpointMode)}`); + } + }; + var STATIC_STABILITY_REFRESH_INTERVAL_SECONDS = 5 * 60; + var STATIC_STABILITY_REFRESH_INTERVAL_JITTER_WINDOW_SECONDS = 5 * 60; + var STATIC_STABILITY_DOC_URL = "https://docs.aws.amazon.com/sdkref/latest/guide/feature-static-credentials.html"; + var getExtendedInstanceMetadataCredentials = (credentials, logger4) => { + const refreshInterval = STATIC_STABILITY_REFRESH_INTERVAL_SECONDS + Math.floor(Math.random() * STATIC_STABILITY_REFRESH_INTERVAL_JITTER_WINDOW_SECONDS); + const newExpiration = new Date(Date.now() + refreshInterval * 1e3); + logger4.warn(`Attempting credential expiration extension due to a credential service availability issue. A refresh of these credentials will be attempted after ${new Date(newExpiration)}. +For more information, please visit: ` + STATIC_STABILITY_DOC_URL); + const originalExpiration = credentials.originalExpiration ?? credentials.expiration; + return { + ...credentials, + ...originalExpiration ? { originalExpiration } : {}, + expiration: newExpiration + }; + }; + var staticStabilityProvider = (provider, options = {}) => { + const logger4 = options?.logger || console; + let pastCredentials; + return async () => { + let credentials; + try { + credentials = await provider(); + if (credentials.expiration && credentials.expiration.getTime() < Date.now()) { + credentials = getExtendedInstanceMetadataCredentials(credentials, logger4); + } + } catch (e5) { + if (pastCredentials) { + logger4.warn("Credential renew failed: ", e5); + credentials = getExtendedInstanceMetadataCredentials(pastCredentials, logger4); + } else { + throw e5; + } + } + pastCredentials = credentials; + return credentials; + }; + }; + var IMDS_PATH = "/latest/meta-data/iam/security-credentials/"; + var IMDS_TOKEN_PATH = "/latest/api/token"; + var AWS_EC2_METADATA_V1_DISABLED = "AWS_EC2_METADATA_V1_DISABLED"; + var PROFILE_AWS_EC2_METADATA_V1_DISABLED = "ec2_metadata_v1_disabled"; + var X_AWS_EC2_METADATA_TOKEN = "x-aws-ec2-metadata-token"; + var fromInstanceMetadata = (init2 = {}) => staticStabilityProvider(getInstanceMetadataProvider(init2), { logger: init2.logger }); + var getInstanceMetadataProvider = (init2 = {}) => { + let disableFetchToken = false; + const { logger: logger4, profile } = init2; + const { timeout, maxRetries } = providerConfigFromInit(init2); + const getCredentials = async (maxRetries2, options) => { + const isImdsV1Fallback = disableFetchToken || options.headers?.[X_AWS_EC2_METADATA_TOKEN] == null; + if (isImdsV1Fallback) { + let fallbackBlockedFromProfile = false; + let fallbackBlockedFromProcessEnv = false; + const configValue = await nodeConfigProvider.loadConfig({ + environmentVariableSelector: (env2) => { + const envValue = env2[AWS_EC2_METADATA_V1_DISABLED]; + fallbackBlockedFromProcessEnv = !!envValue && envValue !== "false"; + if (envValue === void 0) { + throw new propertyProvider.CredentialsProviderError(`${AWS_EC2_METADATA_V1_DISABLED} not set in env, checking config file next.`, { logger: init2.logger }); + } + return fallbackBlockedFromProcessEnv; + }, + configFileSelector: (profile2) => { + const profileValue = profile2[PROFILE_AWS_EC2_METADATA_V1_DISABLED]; + fallbackBlockedFromProfile = !!profileValue && profileValue !== "false"; + return fallbackBlockedFromProfile; + }, + default: false + }, { + profile + })(); + if (init2.ec2MetadataV1Disabled || configValue) { + const causes = []; + if (init2.ec2MetadataV1Disabled) + causes.push("credential provider initialization (runtime option ec2MetadataV1Disabled)"); + if (fallbackBlockedFromProfile) + causes.push(`config file profile (${PROFILE_AWS_EC2_METADATA_V1_DISABLED})`); + if (fallbackBlockedFromProcessEnv) + causes.push(`process environment variable (${AWS_EC2_METADATA_V1_DISABLED})`); + throw new InstanceMetadataV1FallbackError(`AWS EC2 Metadata v1 fallback has been blocked by AWS SDK configuration in the following: [${causes.join(", ")}].`); + } + } + const imdsProfile = (await retry(async () => { + let profile2; + try { + profile2 = await getProfile(options); + } catch (err) { + if (err.statusCode === 401) { + disableFetchToken = false; + } + throw err; + } + return profile2; + }, maxRetries2)).trim(); + return retry(async () => { + let creds; + try { + creds = await getCredentialsFromProfile(imdsProfile, options, init2); + } catch (err) { + if (err.statusCode === 401) { + disableFetchToken = false; + } + throw err; + } + return creds; + }, maxRetries2); + }; + return async () => { + const endpoint = await getInstanceMetadataEndpoint(); + if (disableFetchToken) { + logger4?.debug("AWS SDK Instance Metadata", "using v1 fallback (no token fetch)"); + return getCredentials(maxRetries, { ...endpoint, timeout }); + } else { + let token; + try { + token = (await getMetadataToken({ ...endpoint, timeout })).toString(); + } catch (error50) { + if (error50?.statusCode === 400) { + throw Object.assign(error50, { + message: "EC2 Metadata token request returned error" + }); + } else if (error50.message === "TimeoutError" || [403, 404, 405].includes(error50.statusCode)) { + disableFetchToken = true; + } + logger4?.debug("AWS SDK Instance Metadata", "using v1 fallback (initial)"); + return getCredentials(maxRetries, { ...endpoint, timeout }); + } + return getCredentials(maxRetries, { + ...endpoint, + headers: { + [X_AWS_EC2_METADATA_TOKEN]: token + }, + timeout + }); + } + }; + }; + var getMetadataToken = async (options) => httpRequest2({ + ...options, + path: IMDS_TOKEN_PATH, + method: "PUT", + headers: { + "x-aws-ec2-metadata-token-ttl-seconds": "21600" + } + }); + var getProfile = async (options) => (await httpRequest2({ ...options, path: IMDS_PATH })).toString(); + var getCredentialsFromProfile = async (profile, options, init2) => { + const credentialsResponse = JSON.parse((await httpRequest2({ + ...options, + path: IMDS_PATH + profile + })).toString()); + if (!isImdsCredentials(credentialsResponse)) { + throw new propertyProvider.CredentialsProviderError("Invalid response received from instance metadata service.", { + logger: init2.logger + }); + } + return fromImdsCredentials(credentialsResponse); + }; + exports.DEFAULT_MAX_RETRIES = DEFAULT_MAX_RETRIES; + exports.DEFAULT_TIMEOUT = DEFAULT_TIMEOUT; + exports.ENV_CMDS_AUTH_TOKEN = ENV_CMDS_AUTH_TOKEN; + exports.ENV_CMDS_FULL_URI = ENV_CMDS_FULL_URI; + exports.ENV_CMDS_RELATIVE_URI = ENV_CMDS_RELATIVE_URI; + exports.fromContainerMetadata = fromContainerMetadata; + exports.fromInstanceMetadata = fromInstanceMetadata; + exports.getInstanceMetadataEndpoint = getInstanceMetadataEndpoint; + exports.httpRequest = httpRequest2; + exports.providerConfigFromInit = providerConfigFromInit; + } +}); + +// node_modules/.pnpm/@aws-sdk+credential-provider-http@3.972.27/node_modules/@aws-sdk/credential-provider-http/dist-cjs/fromHttp/checkUrl.js +var require_checkUrl = __commonJS({ + "node_modules/.pnpm/@aws-sdk+credential-provider-http@3.972.27/node_modules/@aws-sdk/credential-provider-http/dist-cjs/fromHttp/checkUrl.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.checkUrl = void 0; + var property_provider_1 = require_dist_cjs41(); + var ECS_CONTAINER_HOST = "169.254.170.2"; + var EKS_CONTAINER_HOST_IPv4 = "169.254.170.23"; + var EKS_CONTAINER_HOST_IPv6 = "[fd00:ec2::23]"; + var checkUrl = (url2, logger4) => { + if (url2.protocol === "https:") { + return; + } + if (url2.hostname === ECS_CONTAINER_HOST || url2.hostname === EKS_CONTAINER_HOST_IPv4 || url2.hostname === EKS_CONTAINER_HOST_IPv6) { + return; + } + if (url2.hostname.includes("[")) { + if (url2.hostname === "[::1]" || url2.hostname === "[0000:0000:0000:0000:0000:0000:0000:0001]") { + return; + } + } else { + if (url2.hostname === "localhost") { + return; + } + const ipComponents = url2.hostname.split("."); + const inRange = (component) => { + const num = parseInt(component, 10); + return 0 <= num && num <= 255; + }; + if (ipComponents[0] === "127" && inRange(ipComponents[1]) && inRange(ipComponents[2]) && inRange(ipComponents[3]) && ipComponents.length === 4) { + return; + } + } + throw new property_provider_1.CredentialsProviderError(`URL not accepted. It must either be HTTPS or match one of the following: + - loopback CIDR 127.0.0.0/8 or [::1/128] + - ECS container host 169.254.170.2 + - EKS container host 169.254.170.23 or [fd00:ec2::23]`, { logger: logger4 }); + }; + exports.checkUrl = checkUrl; + } +}); + +// node_modules/.pnpm/@aws-sdk+credential-provider-http@3.972.27/node_modules/@aws-sdk/credential-provider-http/dist-cjs/fromHttp/requestHelpers.js +var require_requestHelpers = __commonJS({ + "node_modules/.pnpm/@aws-sdk+credential-provider-http@3.972.27/node_modules/@aws-sdk/credential-provider-http/dist-cjs/fromHttp/requestHelpers.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.createGetRequest = createGetRequest; + exports.getCredentials = getCredentials; + var property_provider_1 = require_dist_cjs41(); + var protocol_http_1 = require_dist_cjs2(); + var smithy_client_1 = require_dist_cjs27(); + var util_stream_1 = require_dist_cjs13(); + function createGetRequest(url2) { + return new protocol_http_1.HttpRequest({ + protocol: url2.protocol, + hostname: url2.hostname, + port: Number(url2.port), + path: url2.pathname, + query: Array.from(url2.searchParams.entries()).reduce((acc, [k5, v5]) => { + acc[k5] = v5; + return acc; + }, {}), + fragment: url2.hash + }); + } + async function getCredentials(response, logger4) { + const stream = (0, util_stream_1.sdkStreamMixin)(response.body); + const str = await stream.transformToString(); + if (response.statusCode === 200) { + const parsed = JSON.parse(str); + if (typeof parsed.AccessKeyId !== "string" || typeof parsed.SecretAccessKey !== "string" || typeof parsed.Token !== "string" || typeof parsed.Expiration !== "string") { + throw new property_provider_1.CredentialsProviderError("HTTP credential provider response not of the required format, an object matching: { AccessKeyId: string, SecretAccessKey: string, Token: string, Expiration: string(rfc3339) }", { logger: logger4 }); + } + return { + accessKeyId: parsed.AccessKeyId, + secretAccessKey: parsed.SecretAccessKey, + sessionToken: parsed.Token, + expiration: (0, smithy_client_1.parseRfc3339DateTime)(parsed.Expiration) + }; + } + if (response.statusCode >= 400 && response.statusCode < 500) { + let parsedBody = {}; + try { + parsedBody = JSON.parse(str); + } catch (e5) { + } + throw Object.assign(new property_provider_1.CredentialsProviderError(`Server responded with status: ${response.statusCode}`, { logger: logger4 }), { + Code: parsedBody.Code, + Message: parsedBody.Message + }); + } + throw new property_provider_1.CredentialsProviderError(`Server responded with status: ${response.statusCode}`, { logger: logger4 }); + } + } +}); + +// node_modules/.pnpm/@aws-sdk+credential-provider-http@3.972.27/node_modules/@aws-sdk/credential-provider-http/dist-cjs/fromHttp/retry-wrapper.js +var require_retry_wrapper = __commonJS({ + "node_modules/.pnpm/@aws-sdk+credential-provider-http@3.972.27/node_modules/@aws-sdk/credential-provider-http/dist-cjs/fromHttp/retry-wrapper.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.retryWrapper = void 0; + var retryWrapper = (toRetry, maxRetries, delayMs) => { + return async () => { + for (let i5 = 0; i5 < maxRetries; ++i5) { + try { + return await toRetry(); + } catch (e5) { + await new Promise((resolve4) => setTimeout(resolve4, delayMs)); + } + } + return await toRetry(); + }; + }; + exports.retryWrapper = retryWrapper; + } +}); + +// node_modules/.pnpm/@aws-sdk+credential-provider-http@3.972.27/node_modules/@aws-sdk/credential-provider-http/dist-cjs/fromHttp/fromHttp.js +var require_fromHttp = __commonJS({ + "node_modules/.pnpm/@aws-sdk+credential-provider-http@3.972.27/node_modules/@aws-sdk/credential-provider-http/dist-cjs/fromHttp/fromHttp.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.fromHttp = void 0; + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var client_1 = (init_client2(), __toCommonJS(client_exports)); + var node_http_handler_1 = require_dist_cjs10(); + var property_provider_1 = require_dist_cjs41(); + var promises_1 = tslib_1.__importDefault(__require("node:fs/promises")); + var checkUrl_1 = require_checkUrl(); + var requestHelpers_1 = require_requestHelpers(); + var retry_wrapper_1 = require_retry_wrapper(); + var AWS_CONTAINER_CREDENTIALS_RELATIVE_URI = "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI"; + var DEFAULT_LINK_LOCAL_HOST = "http://169.254.170.2"; + var AWS_CONTAINER_CREDENTIALS_FULL_URI = "AWS_CONTAINER_CREDENTIALS_FULL_URI"; + var AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE = "AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE"; + var AWS_CONTAINER_AUTHORIZATION_TOKEN = "AWS_CONTAINER_AUTHORIZATION_TOKEN"; + var fromHttp = (options = {}) => { + options.logger?.debug("@aws-sdk/credential-provider-http - fromHttp"); + let host; + const relative3 = options.awsContainerCredentialsRelativeUri ?? process.env[AWS_CONTAINER_CREDENTIALS_RELATIVE_URI]; + const full = options.awsContainerCredentialsFullUri ?? process.env[AWS_CONTAINER_CREDENTIALS_FULL_URI]; + const token = options.awsContainerAuthorizationToken ?? process.env[AWS_CONTAINER_AUTHORIZATION_TOKEN]; + const tokenFile = options.awsContainerAuthorizationTokenFile ?? process.env[AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE]; + const warn = options.logger?.constructor?.name === "NoOpLogger" || !options.logger?.warn ? console.warn : options.logger.warn.bind(options.logger); + if (relative3 && full) { + warn("@aws-sdk/credential-provider-http: you have set both awsContainerCredentialsRelativeUri and awsContainerCredentialsFullUri."); + warn("awsContainerCredentialsFullUri will take precedence."); + } + if (token && tokenFile) { + warn("@aws-sdk/credential-provider-http: you have set both awsContainerAuthorizationToken and awsContainerAuthorizationTokenFile."); + warn("awsContainerAuthorizationToken will take precedence."); + } + if (full) { + host = full; + } else if (relative3) { + host = `${DEFAULT_LINK_LOCAL_HOST}${relative3}`; + } else { + throw new property_provider_1.CredentialsProviderError(`No HTTP credential provider host provided. +Set AWS_CONTAINER_CREDENTIALS_FULL_URI or AWS_CONTAINER_CREDENTIALS_RELATIVE_URI.`, { logger: options.logger }); + } + const url2 = new URL(host); + (0, checkUrl_1.checkUrl)(url2, options.logger); + const requestHandler = node_http_handler_1.NodeHttpHandler.create({ + requestTimeout: options.timeout ?? 1e3, + connectionTimeout: options.timeout ?? 1e3 + }); + return (0, retry_wrapper_1.retryWrapper)(async () => { + const request = (0, requestHelpers_1.createGetRequest)(url2); + if (token) { + request.headers.Authorization = token; + } else if (tokenFile) { + request.headers.Authorization = (await promises_1.default.readFile(tokenFile)).toString(); + } + try { + const result = await requestHandler.handle(request); + return (0, requestHelpers_1.getCredentials)(result.response).then((creds) => (0, client_1.setCredentialFeature)(creds, "CREDENTIALS_HTTP", "z")); + } catch (e5) { + throw new property_provider_1.CredentialsProviderError(String(e5), { logger: options.logger }); + } + }, options.maxRetries ?? 3, options.timeout ?? 1e3); + }; + exports.fromHttp = fromHttp; + } +}); + +// node_modules/.pnpm/@aws-sdk+credential-provider-http@3.972.27/node_modules/@aws-sdk/credential-provider-http/dist-cjs/index.js +var require_dist_cjs50 = __commonJS({ + "node_modules/.pnpm/@aws-sdk+credential-provider-http@3.972.27/node_modules/@aws-sdk/credential-provider-http/dist-cjs/index.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.fromHttp = void 0; + var fromHttp_1 = require_fromHttp(); + Object.defineProperty(exports, "fromHttp", { enumerable: true, get: function() { + return fromHttp_1.fromHttp; + } }); + } +}); + +// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/auth/httpAuthSchemeProvider.js +function createAwsAuthSigv4HttpAuthOption(authParameters) { + return { + schemeId: "aws.auth#sigv4", + signingProperties: { + name: "sso-oauth", + region: authParameters.region + }, + propertiesExtractor: (config3, context) => ({ + signingProperties: { + config: config3, + context + } + }) + }; +} +function createSmithyApiNoAuthHttpAuthOption(authParameters) { + return { + schemeId: "smithy.api#noAuth" + }; +} +var import_util_middleware6, defaultSSOOIDCHttpAuthSchemeParametersProvider, defaultSSOOIDCHttpAuthSchemeProvider, resolveHttpAuthSchemeConfig; +var init_httpAuthSchemeProvider = __esm({ + "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/auth/httpAuthSchemeProvider.js"() { + init_httpAuthSchemes2(); + import_util_middleware6 = __toESM(require_dist_cjs18()); + defaultSSOOIDCHttpAuthSchemeParametersProvider = async (config3, context, input) => { + return { + operation: (0, import_util_middleware6.getSmithyContext)(context).operation, + region: await (0, import_util_middleware6.normalizeProvider)(config3.region)() || (() => { + throw new Error("expected `region` to be configured for `aws.auth#sigv4`"); + })() + }; + }; + defaultSSOOIDCHttpAuthSchemeProvider = (authParameters) => { + const options = []; + switch (authParameters.operation) { + case "CreateToken": { + options.push(createSmithyApiNoAuthHttpAuthOption(authParameters)); + break; + } + default: { + options.push(createAwsAuthSigv4HttpAuthOption(authParameters)); + } + } + return options; + }; + resolveHttpAuthSchemeConfig = (config3) => { + const config_0 = resolveAwsSdkSigV4Config(config3); + return Object.assign(config_0, { + authSchemePreference: (0, import_util_middleware6.normalizeProvider)(config3.authSchemePreference ?? []) + }); + }; + } +}); + +// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/endpoint/EndpointParameters.js +var resolveClientEndpointParameters, commonParams; +var init_EndpointParameters = __esm({ + "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/endpoint/EndpointParameters.js"() { + resolveClientEndpointParameters = (options) => { + return Object.assign(options, { + useDualstackEndpoint: options.useDualstackEndpoint ?? false, + useFipsEndpoint: options.useFipsEndpoint ?? false, + defaultSigningName: "sso-oauth" + }); + }; + commonParams = { + UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, + Endpoint: { type: "builtInParams", name: "endpoint" }, + Region: { type: "builtInParams", name: "region" }, + UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" } + }; + } +}); + +// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/package.json +var package_default; +var init_package = __esm({ + "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/package.json"() { + package_default = { + name: "@aws-sdk/nested-clients", + version: "3.996.19", + description: "Nested clients for AWS SDK packages.", + main: "./dist-cjs/index.js", + module: "./dist-es/index.js", + types: "./dist-types/index.d.ts", + scripts: { + build: "yarn lint && concurrently 'yarn:build:types' 'yarn:build:es' && yarn build:cjs", + "build:cjs": "node ../../scripts/compilation/inline nested-clients", + "build:es": "tsc -p tsconfig.es.json", + "build:include:deps": 'yarn g:turbo run build -F="$npm_package_name"', + "build:types": "tsc -p tsconfig.types.json", + "build:types:downlevel": "downlevel-dts dist-types dist-types/ts3.4", + clean: "premove dist-cjs dist-es dist-types tsconfig.cjs.tsbuildinfo tsconfig.es.tsbuildinfo tsconfig.types.tsbuildinfo", + lint: "node ../../scripts/validation/submodules-linter.js --pkg nested-clients", + test: "yarn g:vitest run", + "test:watch": "yarn g:vitest watch" + }, + engines: { + node: ">=20.0.0" + }, + sideEffects: false, + author: { + name: "AWS SDK for JavaScript Team", + url: "https://aws.amazon.com/javascript/" + }, + license: "Apache-2.0", + dependencies: { + "@aws-crypto/sha256-browser": "5.2.0", + "@aws-crypto/sha256-js": "5.2.0", + "@aws-sdk/core": "^3.973.27", + "@aws-sdk/middleware-host-header": "^3.972.9", + "@aws-sdk/middleware-logger": "^3.972.9", + "@aws-sdk/middleware-recursion-detection": "^3.972.10", + "@aws-sdk/middleware-user-agent": "^3.972.29", + "@aws-sdk/region-config-resolver": "^3.972.11", + "@aws-sdk/types": "^3.973.7", + "@aws-sdk/util-endpoints": "^3.996.6", + "@aws-sdk/util-user-agent-browser": "^3.972.9", + "@aws-sdk/util-user-agent-node": "^3.973.15", + "@smithy/config-resolver": "^4.4.14", + "@smithy/core": "^3.23.14", + "@smithy/fetch-http-handler": "^5.3.16", + "@smithy/hash-node": "^4.2.13", + "@smithy/invalid-dependency": "^4.2.13", + "@smithy/middleware-content-length": "^4.2.13", + "@smithy/middleware-endpoint": "^4.4.29", + "@smithy/middleware-retry": "^4.5.0", + "@smithy/middleware-serde": "^4.2.17", + "@smithy/middleware-stack": "^4.2.13", + "@smithy/node-config-provider": "^4.3.13", + "@smithy/node-http-handler": "^4.5.2", + "@smithy/protocol-http": "^5.3.13", + "@smithy/smithy-client": "^4.12.9", + "@smithy/types": "^4.14.0", + "@smithy/url-parser": "^4.2.13", + "@smithy/util-base64": "^4.3.2", + "@smithy/util-body-length-browser": "^4.2.2", + "@smithy/util-body-length-node": "^4.2.3", + "@smithy/util-defaults-mode-browser": "^4.3.45", + "@smithy/util-defaults-mode-node": "^4.2.49", + "@smithy/util-endpoints": "^3.3.4", + "@smithy/util-middleware": "^4.2.13", + "@smithy/util-retry": "^4.3.0", + "@smithy/util-utf8": "^4.2.2", + tslib: "^2.6.2" + }, + devDependencies: { + concurrently: "7.0.0", + "downlevel-dts": "0.10.1", + premove: "4.0.0", + typescript: "~5.8.3" + }, + typesVersions: { + "<4.5": { + "dist-types/*": [ + "dist-types/ts3.4/*" + ] + } + }, + files: [ + "./cognito-identity.d.ts", + "./cognito-identity.js", + "./signin.d.ts", + "./signin.js", + "./sso-oidc.d.ts", + "./sso-oidc.js", + "./sso.d.ts", + "./sso.js", + "./sts.d.ts", + "./sts.js", + "dist-*/**" + ], + browser: { + "./dist-es/submodules/cognito-identity/runtimeConfig": "./dist-es/submodules/cognito-identity/runtimeConfig.browser", + "./dist-es/submodules/signin/runtimeConfig": "./dist-es/submodules/signin/runtimeConfig.browser", + "./dist-es/submodules/sso-oidc/runtimeConfig": "./dist-es/submodules/sso-oidc/runtimeConfig.browser", + "./dist-es/submodules/sso/runtimeConfig": "./dist-es/submodules/sso/runtimeConfig.browser", + "./dist-es/submodules/sts/runtimeConfig": "./dist-es/submodules/sts/runtimeConfig.browser" + }, + "react-native": {}, + homepage: "https://github.com/aws/aws-sdk-js-v3/tree/main/packages/nested-clients", + repository: { + type: "git", + url: "https://github.com/aws/aws-sdk-js-v3.git", + directory: "packages/nested-clients" + }, + exports: { + "./package.json": "./package.json", + "./sso-oidc": { + types: "./dist-types/submodules/sso-oidc/index.d.ts", + module: "./dist-es/submodules/sso-oidc/index.js", + node: "./dist-cjs/submodules/sso-oidc/index.js", + import: "./dist-es/submodules/sso-oidc/index.js", + require: "./dist-cjs/submodules/sso-oidc/index.js" + }, + "./sts": { + types: "./dist-types/submodules/sts/index.d.ts", + module: "./dist-es/submodules/sts/index.js", + node: "./dist-cjs/submodules/sts/index.js", + import: "./dist-es/submodules/sts/index.js", + require: "./dist-cjs/submodules/sts/index.js" + }, + "./signin": { + types: "./dist-types/submodules/signin/index.d.ts", + module: "./dist-es/submodules/signin/index.js", + node: "./dist-cjs/submodules/signin/index.js", + import: "./dist-es/submodules/signin/index.js", + require: "./dist-cjs/submodules/signin/index.js" + }, + "./cognito-identity": { + types: "./dist-types/submodules/cognito-identity/index.d.ts", + module: "./dist-es/submodules/cognito-identity/index.js", + node: "./dist-cjs/submodules/cognito-identity/index.js", + import: "./dist-es/submodules/cognito-identity/index.js", + require: "./dist-cjs/submodules/cognito-identity/index.js" + }, + "./sso": { + types: "./dist-types/submodules/sso/index.d.ts", + module: "./dist-es/submodules/sso/index.js", + node: "./dist-cjs/submodules/sso/index.js", + import: "./dist-es/submodules/sso/index.js", + require: "./dist-cjs/submodules/sso/index.js" + } + } + }; + } +}); + +// node_modules/.pnpm/@aws-sdk+util-user-agent-node@3.973.15/node_modules/@aws-sdk/util-user-agent-node/dist-cjs/index.js +var require_dist_cjs51 = __commonJS({ + "node_modules/.pnpm/@aws-sdk+util-user-agent-node@3.973.15/node_modules/@aws-sdk/util-user-agent-node/dist-cjs/index.js"(exports) { + "use strict"; + var node_os = __require("node:os"); + var node_process = __require("node:process"); + var utilConfigProvider = require_dist_cjs31(); + var promises = __require("node:fs/promises"); + var node_path = __require("node:path"); + var middlewareUserAgent = require_dist_cjs37(); + var getRuntimeUserAgentPair = () => { + const runtimesToCheck = ["deno", "bun", "llrt"]; + for (const runtime of runtimesToCheck) { + if (node_process.versions[runtime]) { + return [`md/${runtime}`, node_process.versions[runtime]]; + } + } + return ["md/nodejs", node_process.versions.node]; + }; + var getNodeModulesParentDirs = (dirname3) => { + const cwd = process.cwd(); + if (!dirname3) { + return [cwd]; + } + const normalizedPath = node_path.normalize(dirname3); + const parts = normalizedPath.split(node_path.sep); + const nodeModulesIndex = parts.indexOf("node_modules"); + const parentDir = nodeModulesIndex !== -1 ? parts.slice(0, nodeModulesIndex).join(node_path.sep) : normalizedPath; + if (cwd === parentDir) { + return [cwd]; + } + return [parentDir, cwd]; + }; + var SEMVER_REGEX = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*)?$/; + var getSanitizedTypeScriptVersion = (version3 = "") => { + const match = version3.match(SEMVER_REGEX); + if (!match) { + return void 0; + } + const [major, minor, patch, prerelease] = [match[1], match[2], match[3], match[4]]; + return prerelease ? `${major}.${minor}.${patch}-${prerelease}` : `${major}.${minor}.${patch}`; + }; + var ALLOWED_PREFIXES = ["^", "~", ">=", "<=", ">", "<"]; + var ALLOWED_DIST_TAGS = ["latest", "beta", "dev", "rc", "insiders", "next"]; + var getSanitizedDevTypeScriptVersion = (version3 = "") => { + if (ALLOWED_DIST_TAGS.includes(version3)) { + return version3; + } + const prefix = ALLOWED_PREFIXES.find((p5) => version3.startsWith(p5)) ?? ""; + const sanitizedTypeScriptVersion = getSanitizedTypeScriptVersion(version3.slice(prefix.length)); + if (!sanitizedTypeScriptVersion) { + return void 0; + } + return `${prefix}${sanitizedTypeScriptVersion}`; + }; + var tscVersion; + var TS_PACKAGE_JSON = node_path.join("node_modules", "typescript", "package.json"); + var getTypeScriptUserAgentPair = async () => { + if (tscVersion === null) { + return void 0; + } else if (typeof tscVersion === "string") { + return ["md/tsc", tscVersion]; + } + let isTypeScriptDetectionDisabled = false; + try { + isTypeScriptDetectionDisabled = utilConfigProvider.booleanSelector(process.env, "AWS_SDK_JS_TYPESCRIPT_DETECTION_DISABLED", utilConfigProvider.SelectorType.ENV) || false; + } catch { + } + if (isTypeScriptDetectionDisabled) { + tscVersion = null; + return void 0; + } + const dirname3 = typeof __dirname !== "undefined" ? __dirname : void 0; + const nodeModulesParentDirs = getNodeModulesParentDirs(dirname3); + let versionFromApp; + for (const nodeModulesParentDir of nodeModulesParentDirs) { + try { + const appPackageJsonPath = node_path.join(nodeModulesParentDir, "package.json"); + const packageJson = await promises.readFile(appPackageJsonPath, "utf-8"); + const { dependencies, devDependencies } = JSON.parse(packageJson); + const version3 = devDependencies?.typescript ?? dependencies?.typescript; + if (typeof version3 !== "string") { + continue; + } + versionFromApp = version3; + break; + } catch { + } + } + if (!versionFromApp) { + tscVersion = null; + return void 0; + } + let versionFromNodeModules; + for (const nodeModulesParentDir of nodeModulesParentDirs) { + try { + const tsPackageJsonPath = node_path.join(nodeModulesParentDir, TS_PACKAGE_JSON); + const packageJson = await promises.readFile(tsPackageJsonPath, "utf-8"); + const { version: version3 } = JSON.parse(packageJson); + const sanitizedVersion2 = getSanitizedTypeScriptVersion(version3); + if (typeof sanitizedVersion2 !== "string") { + continue; + } + versionFromNodeModules = sanitizedVersion2; + break; + } catch { + } + } + if (versionFromNodeModules) { + tscVersion = versionFromNodeModules; + return ["md/tsc", tscVersion]; + } + const sanitizedVersion = getSanitizedDevTypeScriptVersion(versionFromApp); + if (typeof sanitizedVersion !== "string") { + tscVersion = null; + return void 0; + } + tscVersion = `dev_${sanitizedVersion}`; + return ["md/tsc", tscVersion]; + }; + var crtAvailability = { + isCrtAvailable: false + }; + var isCrtAvailable = () => { + if (crtAvailability.isCrtAvailable) { + return ["md/crt-avail"]; + } + return null; + }; + var createDefaultUserAgentProvider5 = ({ serviceId, clientVersion }) => { + const runtimeUserAgentPair = getRuntimeUserAgentPair(); + return async (config3) => { + const sections = [ + ["aws-sdk-js", clientVersion], + ["ua", "2.1"], + [`os/${node_os.platform()}`, node_os.release()], + ["lang/js"], + runtimeUserAgentPair + ]; + const typescriptUserAgentPair = await getTypeScriptUserAgentPair(); + if (typescriptUserAgentPair) { + sections.push(typescriptUserAgentPair); + } + const crtAvailable = isCrtAvailable(); + if (crtAvailable) { + sections.push(crtAvailable); + } + if (serviceId) { + sections.push([`api/${serviceId}`, clientVersion]); + } + if (node_process.env.AWS_EXECUTION_ENV) { + sections.push([`exec-env/${node_process.env.AWS_EXECUTION_ENV}`]); + } + const appId = await config3?.userAgentAppId?.(); + const resolvedUserAgent = appId ? [...sections, [`app/${appId}`]] : [...sections]; + return resolvedUserAgent; + }; + }; + var defaultUserAgent = createDefaultUserAgentProvider5; + var UA_APP_ID_ENV_NAME = "AWS_SDK_UA_APP_ID"; + var UA_APP_ID_INI_NAME = "sdk_ua_app_id"; + var UA_APP_ID_INI_NAME_DEPRECATED = "sdk-ua-app-id"; + var NODE_APP_ID_CONFIG_OPTIONS5 = { + environmentVariableSelector: (env2) => env2[UA_APP_ID_ENV_NAME], + configFileSelector: (profile) => profile[UA_APP_ID_INI_NAME] ?? profile[UA_APP_ID_INI_NAME_DEPRECATED], + default: middlewareUserAgent.DEFAULT_UA_APP_ID + }; + exports.NODE_APP_ID_CONFIG_OPTIONS = NODE_APP_ID_CONFIG_OPTIONS5; + exports.UA_APP_ID_ENV_NAME = UA_APP_ID_ENV_NAME; + exports.UA_APP_ID_INI_NAME = UA_APP_ID_INI_NAME; + exports.createDefaultUserAgentProvider = createDefaultUserAgentProvider5; + exports.crtAvailability = crtAvailability; + exports.defaultUserAgent = defaultUserAgent; + } +}); + +// node_modules/.pnpm/@smithy+hash-node@4.2.13/node_modules/@smithy/hash-node/dist-cjs/index.js +var require_dist_cjs52 = __commonJS({ + "node_modules/.pnpm/@smithy+hash-node@4.2.13/node_modules/@smithy/hash-node/dist-cjs/index.js"(exports) { + "use strict"; + var utilBufferFrom = require_dist_cjs5(); + var utilUtf8 = require_dist_cjs6(); + var buffer2 = __require("buffer"); + var crypto6 = __require("crypto"); + var Hash5 = class { + algorithmIdentifier; + secret; + hash; + constructor(algorithmIdentifier, secret) { + this.algorithmIdentifier = algorithmIdentifier; + this.secret = secret; + this.reset(); + } + update(toHash, encoding) { + this.hash.update(utilUtf8.toUint8Array(castSourceData(toHash, encoding))); + } + digest() { + return Promise.resolve(this.hash.digest()); + } + reset() { + this.hash = this.secret ? crypto6.createHmac(this.algorithmIdentifier, castSourceData(this.secret)) : crypto6.createHash(this.algorithmIdentifier); + } + }; + function castSourceData(toCast, encoding) { + if (buffer2.Buffer.isBuffer(toCast)) { + return toCast; + } + if (typeof toCast === "string") { + return utilBufferFrom.fromString(toCast, encoding); + } + if (ArrayBuffer.isView(toCast)) { + return utilBufferFrom.fromArrayBuffer(toCast.buffer, toCast.byteOffset, toCast.byteLength); + } + return utilBufferFrom.fromArrayBuffer(toCast); + } + exports.Hash = Hash5; + } +}); + +// node_modules/.pnpm/@smithy+util-body-length-node@4.2.3/node_modules/@smithy/util-body-length-node/dist-cjs/index.js +var require_dist_cjs53 = __commonJS({ + "node_modules/.pnpm/@smithy+util-body-length-node@4.2.3/node_modules/@smithy/util-body-length-node/dist-cjs/index.js"(exports) { + "use strict"; + var node_fs = __require("node:fs"); + var calculateBodyLength5 = (body) => { + if (!body) { + return 0; + } + if (typeof body === "string") { + return Buffer.byteLength(body); + } else if (typeof body.byteLength === "number") { + return body.byteLength; + } else if (typeof body.size === "number") { + return body.size; + } else if (typeof body.start === "number" && typeof body.end === "number") { + return body.end + 1 - body.start; + } else if (body instanceof node_fs.ReadStream) { + if (body.path != null) { + return node_fs.lstatSync(body.path).size; + } else if (typeof body.fd === "number") { + return node_fs.fstatSync(body.fd).size; + } + } + throw new Error(`Body Length computation failed for ${body}`); + }; + exports.calculateBodyLength = calculateBodyLength5; + } +}); + +// node_modules/.pnpm/@smithy+util-defaults-mode-node@4.2.50/node_modules/@smithy/util-defaults-mode-node/dist-cjs/index.js +var require_dist_cjs54 = __commonJS({ + "node_modules/.pnpm/@smithy+util-defaults-mode-node@4.2.50/node_modules/@smithy/util-defaults-mode-node/dist-cjs/index.js"(exports) { + "use strict"; + var configResolver = require_dist_cjs38(); + var nodeConfigProvider = require_dist_cjs43(); + var propertyProvider = require_dist_cjs41(); + var AWS_EXECUTION_ENV = "AWS_EXECUTION_ENV"; + var AWS_REGION_ENV = "AWS_REGION"; + var AWS_DEFAULT_REGION_ENV = "AWS_DEFAULT_REGION"; + var ENV_IMDS_DISABLED = "AWS_EC2_METADATA_DISABLED"; + var DEFAULTS_MODE_OPTIONS = ["in-region", "cross-region", "mobile", "standard", "legacy"]; + var IMDS_REGION_PATH = "/latest/meta-data/placement/region"; + var AWS_DEFAULTS_MODE_ENV = "AWS_DEFAULTS_MODE"; + var AWS_DEFAULTS_MODE_CONFIG = "defaults_mode"; + var NODE_DEFAULTS_MODE_CONFIG_OPTIONS = { + environmentVariableSelector: (env2) => { + return env2[AWS_DEFAULTS_MODE_ENV]; + }, + configFileSelector: (profile) => { + return profile[AWS_DEFAULTS_MODE_CONFIG]; + }, + default: "legacy" + }; + var resolveDefaultsModeConfig5 = ({ region = nodeConfigProvider.loadConfig(configResolver.NODE_REGION_CONFIG_OPTIONS), defaultsMode = nodeConfigProvider.loadConfig(NODE_DEFAULTS_MODE_CONFIG_OPTIONS) } = {}) => propertyProvider.memoize(async () => { + const mode = typeof defaultsMode === "function" ? await defaultsMode() : defaultsMode; + switch (mode?.toLowerCase()) { + case "auto": + return resolveNodeDefaultsModeAuto(region); + case "in-region": + case "cross-region": + case "mobile": + case "standard": + case "legacy": + return Promise.resolve(mode?.toLocaleLowerCase()); + case void 0: + return Promise.resolve("legacy"); + default: + throw new Error(`Invalid parameter for "defaultsMode", expect ${DEFAULTS_MODE_OPTIONS.join(", ")}, got ${mode}`); + } + }); + var resolveNodeDefaultsModeAuto = async (clientRegion) => { + if (clientRegion) { + const resolvedRegion = typeof clientRegion === "function" ? await clientRegion() : clientRegion; + const inferredRegion = await inferPhysicalRegion(); + if (!inferredRegion) { + return "standard"; + } + if (resolvedRegion === inferredRegion) { + return "in-region"; + } else { + return "cross-region"; + } + } + return "standard"; + }; + var inferPhysicalRegion = async () => { + if (process.env[AWS_EXECUTION_ENV] && (process.env[AWS_REGION_ENV] || process.env[AWS_DEFAULT_REGION_ENV])) { + return process.env[AWS_REGION_ENV] ?? process.env[AWS_DEFAULT_REGION_ENV]; + } + if (!process.env[ENV_IMDS_DISABLED]) { + try { + const { getInstanceMetadataEndpoint, httpRequest: httpRequest2 } = await Promise.resolve().then(() => __toESM(require_dist_cjs49())); + const endpoint = await getInstanceMetadataEndpoint(); + return (await httpRequest2({ ...endpoint, path: IMDS_REGION_PATH })).toString(); + } catch (e5) { + } + } + }; + exports.resolveDefaultsModeConfig = resolveDefaultsModeConfig5; + } +}); + +// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/endpoint/ruleset.js +var u, v, w, x, a, b2, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, _data, ruleSet; +var init_ruleset = __esm({ + "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/endpoint/ruleset.js"() { + u = "required"; + v = "fn"; + w = "argv"; + x = "ref"; + a = true; + b2 = "isSet"; + c = "booleanEquals"; + d = "error"; + e = "endpoint"; + f = "tree"; + g = "PartitionResult"; + h = "getAttr"; + i = { [u]: false, type: "string" }; + j = { [u]: true, default: false, type: "boolean" }; + k = { [x]: "Endpoint" }; + l = { [v]: c, [w]: [{ [x]: "UseFIPS" }, true] }; + m = { [v]: c, [w]: [{ [x]: "UseDualStack" }, true] }; + n = {}; + o = { [v]: h, [w]: [{ [x]: g }, "supportsFIPS"] }; + p = { [x]: g }; + q = { [v]: c, [w]: [true, { [v]: h, [w]: [p, "supportsDualStack"] }] }; + r = [l]; + s = [m]; + t = [{ [x]: "Region" }]; + _data = { + version: "1.0", + parameters: { Region: i, UseDualStack: j, UseFIPS: j, Endpoint: i }, + rules: [ + { + conditions: [{ [v]: b2, [w]: [k] }], + rules: [ + { conditions: r, error: "Invalid Configuration: FIPS and custom endpoint are not supported", type: d }, + { conditions: s, error: "Invalid Configuration: Dualstack and custom endpoint are not supported", type: d }, + { endpoint: { url: k, properties: n, headers: n }, type: e } + ], + type: f + }, + { + conditions: [{ [v]: b2, [w]: t }], + rules: [ + { + conditions: [{ [v]: "aws.partition", [w]: t, assign: g }], + rules: [ + { + conditions: [l, m], + rules: [ + { + conditions: [{ [v]: c, [w]: [a, o] }, q], + rules: [ + { + endpoint: { + url: "https://oidc-fips.{Region}.{PartitionResult#dualStackDnsSuffix}", + properties: n, + headers: n + }, + type: e + } + ], + type: f + }, + { error: "FIPS and DualStack are enabled, but this partition does not support one or both", type: d } + ], + type: f + }, + { + conditions: r, + rules: [ + { + conditions: [{ [v]: c, [w]: [o, a] }], + rules: [ + { + conditions: [{ [v]: "stringEquals", [w]: [{ [v]: h, [w]: [p, "name"] }, "aws-us-gov"] }], + endpoint: { url: "https://oidc.{Region}.amazonaws.com", properties: n, headers: n }, + type: e + }, + { + endpoint: { + url: "https://oidc-fips.{Region}.{PartitionResult#dnsSuffix}", + properties: n, + headers: n + }, + type: e + } + ], + type: f + }, + { error: "FIPS is enabled but this partition does not support FIPS", type: d } + ], + type: f + }, + { + conditions: s, + rules: [ + { + conditions: [q], + rules: [ + { + endpoint: { + url: "https://oidc.{Region}.{PartitionResult#dualStackDnsSuffix}", + properties: n, + headers: n + }, + type: e + } + ], + type: f + }, + { error: "DualStack is enabled but this partition does not support DualStack", type: d } + ], + type: f + }, + { + endpoint: { url: "https://oidc.{Region}.{PartitionResult#dnsSuffix}", properties: n, headers: n }, + type: e + } + ], + type: f + } + ], + type: f + }, + { error: "Invalid Configuration: Missing Region", type: d } + ] + }; + ruleSet = _data; + } +}); + +// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/endpoint/endpointResolver.js +var import_util_endpoints, import_util_endpoints2, cache, defaultEndpointResolver; +var init_endpointResolver = __esm({ + "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/endpoint/endpointResolver.js"() { + import_util_endpoints = __toESM(require_dist_cjs34()); + import_util_endpoints2 = __toESM(require_dist_cjs33()); + init_ruleset(); + cache = new import_util_endpoints2.EndpointCache({ + size: 50, + params: ["Endpoint", "Region", "UseDualStack", "UseFIPS"] + }); + defaultEndpointResolver = (endpointParams, context = {}) => { + return cache.get(endpointParams, () => (0, import_util_endpoints2.resolveEndpoint)(ruleSet, { + endpointParams, + logger: context.logger + })); + }; + import_util_endpoints2.customEndpointFunctions.aws = import_util_endpoints.awsEndpointFunctions; + } +}); + +// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/models/SSOOIDCServiceException.js +var import_smithy_client8, SSOOIDCServiceException; +var init_SSOOIDCServiceException = __esm({ + "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/models/SSOOIDCServiceException.js"() { + import_smithy_client8 = __toESM(require_dist_cjs27()); + SSOOIDCServiceException = class _SSOOIDCServiceException extends import_smithy_client8.ServiceException { + constructor(options) { + super(options); + Object.setPrototypeOf(this, _SSOOIDCServiceException.prototype); + } + }; + } +}); + +// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/models/errors.js +var AccessDeniedException, AuthorizationPendingException, ExpiredTokenException, InternalServerException, InvalidClientException, InvalidGrantException, InvalidRequestException, InvalidScopeException, SlowDownException, UnauthorizedClientException, UnsupportedGrantTypeException; +var init_errors3 = __esm({ + "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/models/errors.js"() { + init_SSOOIDCServiceException(); + AccessDeniedException = class _AccessDeniedException extends SSOOIDCServiceException { + name = "AccessDeniedException"; + $fault = "client"; + error; + reason; + error_description; + constructor(opts) { + super({ + name: "AccessDeniedException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _AccessDeniedException.prototype); + this.error = opts.error; + this.reason = opts.reason; + this.error_description = opts.error_description; + } + }; + AuthorizationPendingException = class _AuthorizationPendingException extends SSOOIDCServiceException { + name = "AuthorizationPendingException"; + $fault = "client"; + error; + error_description; + constructor(opts) { + super({ + name: "AuthorizationPendingException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _AuthorizationPendingException.prototype); + this.error = opts.error; + this.error_description = opts.error_description; + } + }; + ExpiredTokenException = class _ExpiredTokenException extends SSOOIDCServiceException { + name = "ExpiredTokenException"; + $fault = "client"; + error; + error_description; + constructor(opts) { + super({ + name: "ExpiredTokenException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _ExpiredTokenException.prototype); + this.error = opts.error; + this.error_description = opts.error_description; + } + }; + InternalServerException = class _InternalServerException extends SSOOIDCServiceException { + name = "InternalServerException"; + $fault = "server"; + error; + error_description; + constructor(opts) { + super({ + name: "InternalServerException", + $fault: "server", + ...opts + }); + Object.setPrototypeOf(this, _InternalServerException.prototype); + this.error = opts.error; + this.error_description = opts.error_description; + } + }; + InvalidClientException = class _InvalidClientException extends SSOOIDCServiceException { + name = "InvalidClientException"; + $fault = "client"; + error; + error_description; + constructor(opts) { + super({ + name: "InvalidClientException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _InvalidClientException.prototype); + this.error = opts.error; + this.error_description = opts.error_description; + } + }; + InvalidGrantException = class _InvalidGrantException extends SSOOIDCServiceException { + name = "InvalidGrantException"; + $fault = "client"; + error; + error_description; + constructor(opts) { + super({ + name: "InvalidGrantException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _InvalidGrantException.prototype); + this.error = opts.error; + this.error_description = opts.error_description; + } + }; + InvalidRequestException = class _InvalidRequestException extends SSOOIDCServiceException { + name = "InvalidRequestException"; + $fault = "client"; + error; + reason; + error_description; + constructor(opts) { + super({ + name: "InvalidRequestException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _InvalidRequestException.prototype); + this.error = opts.error; + this.reason = opts.reason; + this.error_description = opts.error_description; + } + }; + InvalidScopeException = class _InvalidScopeException extends SSOOIDCServiceException { + name = "InvalidScopeException"; + $fault = "client"; + error; + error_description; + constructor(opts) { + super({ + name: "InvalidScopeException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _InvalidScopeException.prototype); + this.error = opts.error; + this.error_description = opts.error_description; + } + }; + SlowDownException = class _SlowDownException extends SSOOIDCServiceException { + name = "SlowDownException"; + $fault = "client"; + error; + error_description; + constructor(opts) { + super({ + name: "SlowDownException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _SlowDownException.prototype); + this.error = opts.error; + this.error_description = opts.error_description; + } + }; + UnauthorizedClientException = class _UnauthorizedClientException extends SSOOIDCServiceException { + name = "UnauthorizedClientException"; + $fault = "client"; + error; + error_description; + constructor(opts) { + super({ + name: "UnauthorizedClientException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _UnauthorizedClientException.prototype); + this.error = opts.error; + this.error_description = opts.error_description; + } + }; + UnsupportedGrantTypeException = class _UnsupportedGrantTypeException extends SSOOIDCServiceException { + name = "UnsupportedGrantTypeException"; + $fault = "client"; + error; + error_description; + constructor(opts) { + super({ + name: "UnsupportedGrantTypeException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _UnsupportedGrantTypeException.prototype); + this.error = opts.error; + this.error_description = opts.error_description; + } + }; + } +}); + +// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/schemas/schemas_0.js +var _ADE, _APE, _AT, _CS, _CT, _CTR, _CTRr, _CV, _ETE, _ICE, _IGE, _IRE, _ISE, _ISEn, _IT, _RT, _SDE, _UCE, _UGTE, _aT, _c, _cI, _cS, _cV, _co, _dC, _e, _eI, _ed, _gT, _h, _hE, _iT, _r, _rT, _rU, _s, _sc, _se, _tT, n0, _s_registry, SSOOIDCServiceException$, n0_registry, AccessDeniedException$, AuthorizationPendingException$, ExpiredTokenException$, InternalServerException$, InvalidClientException$, InvalidGrantException$, InvalidRequestException$, InvalidScopeException$, SlowDownException$, UnauthorizedClientException$, UnsupportedGrantTypeException$, errorTypeRegistries, AccessToken, ClientSecret, CodeVerifier, IdToken, RefreshToken, CreateTokenRequest$, CreateTokenResponse$, Scopes, CreateToken$; +var init_schemas_0 = __esm({ + "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/schemas/schemas_0.js"() { + init_schema3(); + init_errors3(); + init_SSOOIDCServiceException(); + _ADE = "AccessDeniedException"; + _APE = "AuthorizationPendingException"; + _AT = "AccessToken"; + _CS = "ClientSecret"; + _CT = "CreateToken"; + _CTR = "CreateTokenRequest"; + _CTRr = "CreateTokenResponse"; + _CV = "CodeVerifier"; + _ETE = "ExpiredTokenException"; + _ICE = "InvalidClientException"; + _IGE = "InvalidGrantException"; + _IRE = "InvalidRequestException"; + _ISE = "InternalServerException"; + _ISEn = "InvalidScopeException"; + _IT = "IdToken"; + _RT = "RefreshToken"; + _SDE = "SlowDownException"; + _UCE = "UnauthorizedClientException"; + _UGTE = "UnsupportedGrantTypeException"; + _aT = "accessToken"; + _c = "client"; + _cI = "clientId"; + _cS = "clientSecret"; + _cV = "codeVerifier"; + _co = "code"; + _dC = "deviceCode"; + _e = "error"; + _eI = "expiresIn"; + _ed = "error_description"; + _gT = "grantType"; + _h = "http"; + _hE = "httpError"; + _iT = "idToken"; + _r = "reason"; + _rT = "refreshToken"; + _rU = "redirectUri"; + _s = "smithy.ts.sdk.synthetic.com.amazonaws.ssooidc"; + _sc = "scope"; + _se = "server"; + _tT = "tokenType"; + n0 = "com.amazonaws.ssooidc"; + _s_registry = TypeRegistry.for(_s); + SSOOIDCServiceException$ = [-3, _s, "SSOOIDCServiceException", 0, [], []]; + _s_registry.registerError(SSOOIDCServiceException$, SSOOIDCServiceException); + n0_registry = TypeRegistry.for(n0); + AccessDeniedException$ = [ + -3, + n0, + _ADE, + { [_e]: _c, [_hE]: 400 }, + [_e, _r, _ed], + [0, 0, 0] + ]; + n0_registry.registerError(AccessDeniedException$, AccessDeniedException); + AuthorizationPendingException$ = [ + -3, + n0, + _APE, + { [_e]: _c, [_hE]: 400 }, + [_e, _ed], + [0, 0] + ]; + n0_registry.registerError(AuthorizationPendingException$, AuthorizationPendingException); + ExpiredTokenException$ = [-3, n0, _ETE, { [_e]: _c, [_hE]: 400 }, [_e, _ed], [0, 0]]; + n0_registry.registerError(ExpiredTokenException$, ExpiredTokenException); + InternalServerException$ = [-3, n0, _ISE, { [_e]: _se, [_hE]: 500 }, [_e, _ed], [0, 0]]; + n0_registry.registerError(InternalServerException$, InternalServerException); + InvalidClientException$ = [-3, n0, _ICE, { [_e]: _c, [_hE]: 401 }, [_e, _ed], [0, 0]]; + n0_registry.registerError(InvalidClientException$, InvalidClientException); + InvalidGrantException$ = [-3, n0, _IGE, { [_e]: _c, [_hE]: 400 }, [_e, _ed], [0, 0]]; + n0_registry.registerError(InvalidGrantException$, InvalidGrantException); + InvalidRequestException$ = [ + -3, + n0, + _IRE, + { [_e]: _c, [_hE]: 400 }, + [_e, _r, _ed], + [0, 0, 0] + ]; + n0_registry.registerError(InvalidRequestException$, InvalidRequestException); + InvalidScopeException$ = [-3, n0, _ISEn, { [_e]: _c, [_hE]: 400 }, [_e, _ed], [0, 0]]; + n0_registry.registerError(InvalidScopeException$, InvalidScopeException); + SlowDownException$ = [-3, n0, _SDE, { [_e]: _c, [_hE]: 400 }, [_e, _ed], [0, 0]]; + n0_registry.registerError(SlowDownException$, SlowDownException); + UnauthorizedClientException$ = [ + -3, + n0, + _UCE, + { [_e]: _c, [_hE]: 400 }, + [_e, _ed], + [0, 0] + ]; + n0_registry.registerError(UnauthorizedClientException$, UnauthorizedClientException); + UnsupportedGrantTypeException$ = [ + -3, + n0, + _UGTE, + { [_e]: _c, [_hE]: 400 }, + [_e, _ed], + [0, 0] + ]; + n0_registry.registerError(UnsupportedGrantTypeException$, UnsupportedGrantTypeException); + errorTypeRegistries = [_s_registry, n0_registry]; + AccessToken = [0, n0, _AT, 8, 0]; + ClientSecret = [0, n0, _CS, 8, 0]; + CodeVerifier = [0, n0, _CV, 8, 0]; + IdToken = [0, n0, _IT, 8, 0]; + RefreshToken = [0, n0, _RT, 8, 0]; + CreateTokenRequest$ = [ + 3, + n0, + _CTR, + 0, + [_cI, _cS, _gT, _dC, _co, _rT, _sc, _rU, _cV], + [0, [() => ClientSecret, 0], 0, 0, 0, [() => RefreshToken, 0], 64 | 0, 0, [() => CodeVerifier, 0]], + 3 + ]; + CreateTokenResponse$ = [ + 3, + n0, + _CTRr, + 0, + [_aT, _tT, _eI, _rT, _iT], + [[() => AccessToken, 0], 0, 1, [() => RefreshToken, 0], [() => IdToken, 0]] + ]; + Scopes = 64 | 0; + CreateToken$ = [ + 9, + n0, + _CT, + { [_h]: ["POST", "/token", 200] }, + () => CreateTokenRequest$, + () => CreateTokenResponse$ + ]; + } +}); + +// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/runtimeConfig.shared.js +var import_smithy_client9, import_url_parser2, import_util_base648, import_util_utf88, getRuntimeConfig; +var init_runtimeConfig_shared = __esm({ + "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/runtimeConfig.shared.js"() { + init_httpAuthSchemes2(); + init_protocols2(); + init_dist_es(); + import_smithy_client9 = __toESM(require_dist_cjs27()); + import_url_parser2 = __toESM(require_dist_cjs25()); + import_util_base648 = __toESM(require_dist_cjs7()); + import_util_utf88 = __toESM(require_dist_cjs6()); + init_httpAuthSchemeProvider(); + init_endpointResolver(); + init_schemas_0(); + getRuntimeConfig = (config3) => { + return { + apiVersion: "2019-06-10", + base64Decoder: config3?.base64Decoder ?? import_util_base648.fromBase64, + base64Encoder: config3?.base64Encoder ?? import_util_base648.toBase64, + disableHostPrefix: config3?.disableHostPrefix ?? false, + endpointProvider: config3?.endpointProvider ?? defaultEndpointResolver, + extensions: config3?.extensions ?? [], + httpAuthSchemeProvider: config3?.httpAuthSchemeProvider ?? defaultSSOOIDCHttpAuthSchemeProvider, + httpAuthSchemes: config3?.httpAuthSchemes ?? [ + { + schemeId: "aws.auth#sigv4", + identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"), + signer: new AwsSdkSigV4Signer() + }, + { + schemeId: "smithy.api#noAuth", + identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})), + signer: new NoAuthSigner() + } + ], + logger: config3?.logger ?? new import_smithy_client9.NoOpLogger(), + protocol: config3?.protocol ?? AwsRestJsonProtocol, + protocolSettings: config3?.protocolSettings ?? { + defaultNamespace: "com.amazonaws.ssooidc", + errorTypeRegistries, + version: "2019-06-10", + serviceTarget: "AWSSSOOIDCService" + }, + serviceId: config3?.serviceId ?? "SSO OIDC", + urlParser: config3?.urlParser ?? import_url_parser2.parseUrl, + utf8Decoder: config3?.utf8Decoder ?? import_util_utf88.fromUtf8, + utf8Encoder: config3?.utf8Encoder ?? import_util_utf88.toUtf8 + }; + }; + } +}); + +// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/runtimeConfig.js +var import_util_user_agent_node, import_config_resolver, import_hash_node, import_middleware_retry, import_node_config_provider, import_node_http_handler, import_smithy_client10, import_util_body_length_node, import_util_defaults_mode_node, import_util_retry, getRuntimeConfig2; +var init_runtimeConfig = __esm({ + "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/runtimeConfig.js"() { + init_package(); + init_client2(); + init_httpAuthSchemes2(); + import_util_user_agent_node = __toESM(require_dist_cjs51()); + import_config_resolver = __toESM(require_dist_cjs38()); + import_hash_node = __toESM(require_dist_cjs52()); + import_middleware_retry = __toESM(require_dist_cjs46()); + import_node_config_provider = __toESM(require_dist_cjs43()); + import_node_http_handler = __toESM(require_dist_cjs10()); + import_smithy_client10 = __toESM(require_dist_cjs27()); + import_util_body_length_node = __toESM(require_dist_cjs53()); + import_util_defaults_mode_node = __toESM(require_dist_cjs54()); + import_util_retry = __toESM(require_dist_cjs36()); + init_runtimeConfig_shared(); + getRuntimeConfig2 = (config3) => { + (0, import_smithy_client10.emitWarningIfUnsupportedVersion)(process.version); + const defaultsMode = (0, import_util_defaults_mode_node.resolveDefaultsModeConfig)(config3); + const defaultConfigProvider = () => defaultsMode().then(import_smithy_client10.loadConfigsForDefaultMode); + const clientSharedValues = getRuntimeConfig(config3); + emitWarningIfUnsupportedVersion(process.version); + const loaderConfig = { + profile: config3?.profile, + logger: clientSharedValues.logger + }; + return { + ...clientSharedValues, + ...config3, + runtime: "node", + defaultsMode, + authSchemePreference: config3?.authSchemePreference ?? (0, import_node_config_provider.loadConfig)(NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig), + bodyLengthChecker: config3?.bodyLengthChecker ?? import_util_body_length_node.calculateBodyLength, + defaultUserAgentProvider: config3?.defaultUserAgentProvider ?? (0, import_util_user_agent_node.createDefaultUserAgentProvider)({ serviceId: clientSharedValues.serviceId, clientVersion: package_default.version }), + maxAttempts: config3?.maxAttempts ?? (0, import_node_config_provider.loadConfig)(import_middleware_retry.NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config3), + region: config3?.region ?? (0, import_node_config_provider.loadConfig)(import_config_resolver.NODE_REGION_CONFIG_OPTIONS, { ...import_config_resolver.NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }), + requestHandler: import_node_http_handler.NodeHttpHandler.create(config3?.requestHandler ?? defaultConfigProvider), + retryMode: config3?.retryMode ?? (0, import_node_config_provider.loadConfig)({ + ...import_middleware_retry.NODE_RETRY_MODE_CONFIG_OPTIONS, + default: async () => (await defaultConfigProvider()).retryMode || import_util_retry.DEFAULT_RETRY_MODE + }, config3), + sha256: config3?.sha256 ?? import_hash_node.Hash.bind(null, "sha256"), + streamCollector: config3?.streamCollector ?? import_node_http_handler.streamCollector, + useDualstackEndpoint: config3?.useDualstackEndpoint ?? (0, import_node_config_provider.loadConfig)(import_config_resolver.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig), + useFipsEndpoint: config3?.useFipsEndpoint ?? (0, import_node_config_provider.loadConfig)(import_config_resolver.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig), + userAgentAppId: config3?.userAgentAppId ?? (0, import_node_config_provider.loadConfig)(import_util_user_agent_node.NODE_APP_ID_CONFIG_OPTIONS, loaderConfig) + }; + }; + } +}); + +// node_modules/.pnpm/@aws-sdk+region-config-resolver@3.972.11/node_modules/@aws-sdk/region-config-resolver/dist-cjs/regionConfig/stsRegionDefaultResolver.js +var require_stsRegionDefaultResolver = __commonJS({ + "node_modules/.pnpm/@aws-sdk+region-config-resolver@3.972.11/node_modules/@aws-sdk/region-config-resolver/dist-cjs/regionConfig/stsRegionDefaultResolver.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.warning = void 0; + exports.stsRegionDefaultResolver = stsRegionDefaultResolver2; + var config_resolver_1 = require_dist_cjs38(); + var node_config_provider_1 = require_dist_cjs43(); + function stsRegionDefaultResolver2(loaderConfig = {}) { + return (0, node_config_provider_1.loadConfig)({ + ...config_resolver_1.NODE_REGION_CONFIG_OPTIONS, + async default() { + if (!exports.warning.silence) { + console.warn("@aws-sdk - WARN - default STS region of us-east-1 used. See @aws-sdk/credential-providers README and set a region explicitly."); + } + return "us-east-1"; + } + }, { ...config_resolver_1.NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }); + } + exports.warning = { + silence: false + }; + } +}); + +// node_modules/.pnpm/@aws-sdk+region-config-resolver@3.972.11/node_modules/@aws-sdk/region-config-resolver/dist-cjs/index.js +var require_dist_cjs55 = __commonJS({ + "node_modules/.pnpm/@aws-sdk+region-config-resolver@3.972.11/node_modules/@aws-sdk/region-config-resolver/dist-cjs/index.js"(exports) { + "use strict"; + var stsRegionDefaultResolver2 = require_stsRegionDefaultResolver(); + var configResolver = require_dist_cjs38(); + var getAwsRegionExtensionConfiguration5 = (runtimeConfig) => { + return { + setRegion(region) { + runtimeConfig.region = region; + }, + region() { + return runtimeConfig.region; + } + }; + }; + var resolveAwsRegionExtensionConfiguration5 = (awsRegionExtensionConfiguration) => { + return { + region: awsRegionExtensionConfiguration.region() + }; + }; + exports.NODE_REGION_CONFIG_FILE_OPTIONS = configResolver.NODE_REGION_CONFIG_FILE_OPTIONS; + exports.NODE_REGION_CONFIG_OPTIONS = configResolver.NODE_REGION_CONFIG_OPTIONS; + exports.REGION_ENV_NAME = configResolver.REGION_ENV_NAME; + exports.REGION_INI_NAME = configResolver.REGION_INI_NAME; + exports.resolveRegionConfig = configResolver.resolveRegionConfig; + exports.getAwsRegionExtensionConfiguration = getAwsRegionExtensionConfiguration5; + exports.resolveAwsRegionExtensionConfiguration = resolveAwsRegionExtensionConfiguration5; + Object.prototype.hasOwnProperty.call(stsRegionDefaultResolver2, "__proto__") && !Object.prototype.hasOwnProperty.call(exports, "__proto__") && Object.defineProperty(exports, "__proto__", { + enumerable: true, + value: stsRegionDefaultResolver2["__proto__"] + }); + Object.keys(stsRegionDefaultResolver2).forEach(function(k5) { + if (k5 !== "default" && !Object.prototype.hasOwnProperty.call(exports, k5)) exports[k5] = stsRegionDefaultResolver2[k5]; + }); + } +}); + +// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/auth/httpAuthExtensionConfiguration.js +var getHttpAuthExtensionConfiguration, resolveHttpAuthRuntimeConfig; +var init_httpAuthExtensionConfiguration = __esm({ + "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/auth/httpAuthExtensionConfiguration.js"() { + getHttpAuthExtensionConfiguration = (runtimeConfig) => { + const _httpAuthSchemes = runtimeConfig.httpAuthSchemes; + let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider; + let _credentials = runtimeConfig.credentials; + return { + setHttpAuthScheme(httpAuthScheme) { + const index2 = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId); + if (index2 === -1) { + _httpAuthSchemes.push(httpAuthScheme); + } else { + _httpAuthSchemes.splice(index2, 1, httpAuthScheme); + } + }, + httpAuthSchemes() { + return _httpAuthSchemes; + }, + setHttpAuthSchemeProvider(httpAuthSchemeProvider) { + _httpAuthSchemeProvider = httpAuthSchemeProvider; + }, + httpAuthSchemeProvider() { + return _httpAuthSchemeProvider; + }, + setCredentials(credentials) { + _credentials = credentials; + }, + credentials() { + return _credentials; + } + }; + }; + resolveHttpAuthRuntimeConfig = (config3) => { + return { + httpAuthSchemes: config3.httpAuthSchemes(), + httpAuthSchemeProvider: config3.httpAuthSchemeProvider(), + credentials: config3.credentials() + }; + }; + } +}); + +// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/runtimeExtensions.js +var import_region_config_resolver, import_protocol_http12, import_smithy_client11, resolveRuntimeExtensions; +var init_runtimeExtensions = __esm({ + "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/runtimeExtensions.js"() { + import_region_config_resolver = __toESM(require_dist_cjs55()); + import_protocol_http12 = __toESM(require_dist_cjs2()); + import_smithy_client11 = __toESM(require_dist_cjs27()); + init_httpAuthExtensionConfiguration(); + resolveRuntimeExtensions = (runtimeConfig, extensions) => { + const extensionConfiguration = Object.assign((0, import_region_config_resolver.getAwsRegionExtensionConfiguration)(runtimeConfig), (0, import_smithy_client11.getDefaultExtensionConfiguration)(runtimeConfig), (0, import_protocol_http12.getHttpHandlerExtensionConfiguration)(runtimeConfig), getHttpAuthExtensionConfiguration(runtimeConfig)); + extensions.forEach((extension2) => extension2.configure(extensionConfiguration)); + return Object.assign(runtimeConfig, (0, import_region_config_resolver.resolveAwsRegionExtensionConfiguration)(extensionConfiguration), (0, import_smithy_client11.resolveDefaultRuntimeConfig)(extensionConfiguration), (0, import_protocol_http12.resolveHttpHandlerRuntimeConfig)(extensionConfiguration), resolveHttpAuthRuntimeConfig(extensionConfiguration)); + }; + } +}); + +// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/SSOOIDCClient.js +var import_middleware_host_header, import_middleware_logger, import_middleware_recursion_detection, import_middleware_user_agent, import_config_resolver2, import_middleware_content_length, import_middleware_endpoint, import_middleware_retry2, import_smithy_client12, SSOOIDCClient; +var init_SSOOIDCClient = __esm({ + "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/SSOOIDCClient.js"() { + import_middleware_host_header = __toESM(require_dist_cjs20()); + import_middleware_logger = __toESM(require_dist_cjs21()); + import_middleware_recursion_detection = __toESM(require_dist_cjs22()); + import_middleware_user_agent = __toESM(require_dist_cjs37()); + import_config_resolver2 = __toESM(require_dist_cjs38()); + init_dist_es(); + init_schema3(); + import_middleware_content_length = __toESM(require_dist_cjs40()); + import_middleware_endpoint = __toESM(require_dist_cjs45()); + import_middleware_retry2 = __toESM(require_dist_cjs46()); + import_smithy_client12 = __toESM(require_dist_cjs27()); + init_httpAuthSchemeProvider(); + init_EndpointParameters(); + init_runtimeConfig(); + init_runtimeExtensions(); + SSOOIDCClient = class extends import_smithy_client12.Client { + config; + constructor(...[configuration]) { + const _config_0 = getRuntimeConfig2(configuration || {}); + super(_config_0); + this.initConfig = _config_0; + const _config_1 = resolveClientEndpointParameters(_config_0); + const _config_2 = (0, import_middleware_user_agent.resolveUserAgentConfig)(_config_1); + const _config_3 = (0, import_middleware_retry2.resolveRetryConfig)(_config_2); + const _config_4 = (0, import_config_resolver2.resolveRegionConfig)(_config_3); + const _config_5 = (0, import_middleware_host_header.resolveHostHeaderConfig)(_config_4); + const _config_6 = (0, import_middleware_endpoint.resolveEndpointConfig)(_config_5); + const _config_7 = resolveHttpAuthSchemeConfig(_config_6); + const _config_8 = resolveRuntimeExtensions(_config_7, configuration?.extensions || []); + this.config = _config_8; + this.middlewareStack.use(getSchemaSerdePlugin(this.config)); + this.middlewareStack.use((0, import_middleware_user_agent.getUserAgentPlugin)(this.config)); + this.middlewareStack.use((0, import_middleware_retry2.getRetryPlugin)(this.config)); + this.middlewareStack.use((0, import_middleware_content_length.getContentLengthPlugin)(this.config)); + this.middlewareStack.use((0, import_middleware_host_header.getHostHeaderPlugin)(this.config)); + this.middlewareStack.use((0, import_middleware_logger.getLoggerPlugin)(this.config)); + this.middlewareStack.use((0, import_middleware_recursion_detection.getRecursionDetectionPlugin)(this.config)); + this.middlewareStack.use(getHttpAuthSchemeEndpointRuleSetPlugin(this.config, { + httpAuthSchemeParametersProvider: defaultSSOOIDCHttpAuthSchemeParametersProvider, + identityProviderConfigProvider: async (config3) => new DefaultIdentityProviderConfig({ + "aws.auth#sigv4": config3.credentials + }) + })); + this.middlewareStack.use(getHttpSigningPlugin(this.config)); + } + destroy() { + super.destroy(); + } + }; + } +}); + +// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/commands/CreateTokenCommand.js +var import_middleware_endpoint2, import_smithy_client13, CreateTokenCommand; +var init_CreateTokenCommand = __esm({ + "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/commands/CreateTokenCommand.js"() { + import_middleware_endpoint2 = __toESM(require_dist_cjs45()); + import_smithy_client13 = __toESM(require_dist_cjs27()); + init_EndpointParameters(); + init_schemas_0(); + CreateTokenCommand = class extends import_smithy_client13.Command.classBuilder().ep(commonParams).m(function(Command2, cs, config3, o5) { + return [(0, import_middleware_endpoint2.getEndpointPlugin)(config3, Command2.getEndpointParameterInstructions())]; + }).s("AWSSSOOIDCService", "CreateToken", {}).n("SSOOIDCClient", "CreateTokenCommand").sc(CreateToken$).build() { + }; + } +}); + +// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/SSOOIDC.js +var import_smithy_client14, commands, SSOOIDC; +var init_SSOOIDC = __esm({ + "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/SSOOIDC.js"() { + import_smithy_client14 = __toESM(require_dist_cjs27()); + init_CreateTokenCommand(); + init_SSOOIDCClient(); + commands = { + CreateTokenCommand + }; + SSOOIDC = class extends SSOOIDCClient { + }; + (0, import_smithy_client14.createAggregatedClient)(commands, SSOOIDC); + } +}); + +// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/commands/index.js +var init_commands = __esm({ + "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/commands/index.js"() { + init_CreateTokenCommand(); + } +}); + +// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/models/enums.js +var AccessDeniedExceptionReason, InvalidRequestExceptionReason; +var init_enums = __esm({ + "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/models/enums.js"() { + AccessDeniedExceptionReason = { + KMS_ACCESS_DENIED: "KMS_AccessDeniedException" + }; + InvalidRequestExceptionReason = { + KMS_DISABLED_KEY: "KMS_DisabledException", + KMS_INVALID_KEY_USAGE: "KMS_InvalidKeyUsageException", + KMS_INVALID_STATE: "KMS_InvalidStateException", + KMS_KEY_NOT_FOUND: "KMS_NotFoundException" + }; + } +}); + +// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/models/models_0.js +var init_models_0 = __esm({ + "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/models/models_0.js"() { + } +}); + +// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/index.js +var sso_oidc_exports = {}; +__export(sso_oidc_exports, { + $Command: () => import_smithy_client13.Command, + AccessDeniedException: () => AccessDeniedException, + AccessDeniedException$: () => AccessDeniedException$, + AccessDeniedExceptionReason: () => AccessDeniedExceptionReason, + AuthorizationPendingException: () => AuthorizationPendingException, + AuthorizationPendingException$: () => AuthorizationPendingException$, + CreateToken$: () => CreateToken$, + CreateTokenCommand: () => CreateTokenCommand, + CreateTokenRequest$: () => CreateTokenRequest$, + CreateTokenResponse$: () => CreateTokenResponse$, + ExpiredTokenException: () => ExpiredTokenException, + ExpiredTokenException$: () => ExpiredTokenException$, + InternalServerException: () => InternalServerException, + InternalServerException$: () => InternalServerException$, + InvalidClientException: () => InvalidClientException, + InvalidClientException$: () => InvalidClientException$, + InvalidGrantException: () => InvalidGrantException, + InvalidGrantException$: () => InvalidGrantException$, + InvalidRequestException: () => InvalidRequestException, + InvalidRequestException$: () => InvalidRequestException$, + InvalidRequestExceptionReason: () => InvalidRequestExceptionReason, + InvalidScopeException: () => InvalidScopeException, + InvalidScopeException$: () => InvalidScopeException$, + SSOOIDC: () => SSOOIDC, + SSOOIDCClient: () => SSOOIDCClient, + SSOOIDCServiceException: () => SSOOIDCServiceException, + SSOOIDCServiceException$: () => SSOOIDCServiceException$, + SlowDownException: () => SlowDownException, + SlowDownException$: () => SlowDownException$, + UnauthorizedClientException: () => UnauthorizedClientException, + UnauthorizedClientException$: () => UnauthorizedClientException$, + UnsupportedGrantTypeException: () => UnsupportedGrantTypeException, + UnsupportedGrantTypeException$: () => UnsupportedGrantTypeException$, + __Client: () => import_smithy_client12.Client, + errorTypeRegistries: () => errorTypeRegistries +}); +var init_sso_oidc = __esm({ + "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/index.js"() { + init_SSOOIDCClient(); + init_SSOOIDC(); + init_commands(); + init_schemas_0(); + init_enums(); + init_errors3(); + init_models_0(); + init_SSOOIDCServiceException(); + } +}); + +// node_modules/.pnpm/@aws-sdk+token-providers@3.1026.0/node_modules/@aws-sdk/token-providers/dist-cjs/index.js +var require_dist_cjs56 = __commonJS({ + "node_modules/.pnpm/@aws-sdk+token-providers@3.1026.0/node_modules/@aws-sdk/token-providers/dist-cjs/index.js"(exports) { + "use strict"; + var client2 = (init_client2(), __toCommonJS(client_exports)); + var httpAuthSchemes = (init_httpAuthSchemes2(), __toCommonJS(httpAuthSchemes_exports)); + var propertyProvider = require_dist_cjs41(); + var sharedIniFileLoader = require_dist_cjs42(); + var node_fs = __require("node:fs"); + var fromEnvSigningName = ({ logger: logger4, signingName } = {}) => async () => { + logger4?.debug?.("@aws-sdk/token-providers - fromEnvSigningName"); + if (!signingName) { + throw new propertyProvider.TokenProviderError("Please pass 'signingName' to compute environment variable key", { logger: logger4 }); + } + const bearerTokenKey = httpAuthSchemes.getBearerTokenEnvKey(signingName); + if (!(bearerTokenKey in process.env)) { + throw new propertyProvider.TokenProviderError(`Token not present in '${bearerTokenKey}' environment variable`, { logger: logger4 }); + } + const token = { token: process.env[bearerTokenKey] }; + client2.setTokenFeature(token, "BEARER_SERVICE_ENV_VARS", "3"); + return token; + }; + var EXPIRE_WINDOW_MS = 5 * 60 * 1e3; + var REFRESH_MESSAGE = `To refresh this SSO session run 'aws sso login' with the corresponding profile.`; + var getSsoOidcClient = async (ssoRegion, init2 = {}, callerClientConfig) => { + const { SSOOIDCClient: SSOOIDCClient2 } = await Promise.resolve().then(() => (init_sso_oidc(), sso_oidc_exports)); + const coalesce = (prop) => init2.clientConfig?.[prop] ?? init2.parentClientConfig?.[prop] ?? callerClientConfig?.[prop]; + const ssoOidcClient = new SSOOIDCClient2(Object.assign({}, init2.clientConfig ?? {}, { + region: ssoRegion ?? init2.clientConfig?.region, + logger: coalesce("logger"), + userAgentAppId: coalesce("userAgentAppId") + })); + return ssoOidcClient; + }; + var getNewSsoOidcToken = async (ssoToken, ssoRegion, init2 = {}, callerClientConfig) => { + const { CreateTokenCommand: CreateTokenCommand2 } = await Promise.resolve().then(() => (init_sso_oidc(), sso_oidc_exports)); + const ssoOidcClient = await getSsoOidcClient(ssoRegion, init2, callerClientConfig); + return ssoOidcClient.send(new CreateTokenCommand2({ + clientId: ssoToken.clientId, + clientSecret: ssoToken.clientSecret, + refreshToken: ssoToken.refreshToken, + grantType: "refresh_token" + })); + }; + var validateTokenExpiry = (token) => { + if (token.expiration && token.expiration.getTime() < Date.now()) { + throw new propertyProvider.TokenProviderError(`Token is expired. ${REFRESH_MESSAGE}`, false); + } + }; + var validateTokenKey = (key, value, forRefresh = false) => { + if (typeof value === "undefined") { + throw new propertyProvider.TokenProviderError(`Value not present for '${key}' in SSO Token${forRefresh ? ". Cannot refresh" : ""}. ${REFRESH_MESSAGE}`, false); + } + }; + var { writeFile } = node_fs.promises; + var writeSSOTokenToFile = (id, ssoToken) => { + const tokenFilepath = sharedIniFileLoader.getSSOTokenFilepath(id); + const tokenString = JSON.stringify(ssoToken, null, 2); + return writeFile(tokenFilepath, tokenString); + }; + var lastRefreshAttemptTime = /* @__PURE__ */ new Date(0); + var fromSso = (init2 = {}) => async ({ callerClientConfig } = {}) => { + init2.logger?.debug("@aws-sdk/token-providers - fromSso"); + const profiles = await sharedIniFileLoader.parseKnownFiles(init2); + const profileName = sharedIniFileLoader.getProfileName({ + profile: init2.profile ?? callerClientConfig?.profile + }); + const profile = profiles[profileName]; + if (!profile) { + throw new propertyProvider.TokenProviderError(`Profile '${profileName}' could not be found in shared credentials file.`, false); + } else if (!profile["sso_session"]) { + throw new propertyProvider.TokenProviderError(`Profile '${profileName}' is missing required property 'sso_session'.`); + } + const ssoSessionName = profile["sso_session"]; + const ssoSessions = await sharedIniFileLoader.loadSsoSessionData(init2); + const ssoSession = ssoSessions[ssoSessionName]; + if (!ssoSession) { + throw new propertyProvider.TokenProviderError(`Sso session '${ssoSessionName}' could not be found in shared credentials file.`, false); + } + for (const ssoSessionRequiredKey of ["sso_start_url", "sso_region"]) { + if (!ssoSession[ssoSessionRequiredKey]) { + throw new propertyProvider.TokenProviderError(`Sso session '${ssoSessionName}' is missing required property '${ssoSessionRequiredKey}'.`, false); + } + } + ssoSession["sso_start_url"]; + const ssoRegion = ssoSession["sso_region"]; + let ssoToken; + try { + ssoToken = await sharedIniFileLoader.getSSOTokenFromFile(ssoSessionName); + } catch (e5) { + throw new propertyProvider.TokenProviderError(`The SSO session token associated with profile=${profileName} was not found or is invalid. ${REFRESH_MESSAGE}`, false); + } + validateTokenKey("accessToken", ssoToken.accessToken); + validateTokenKey("expiresAt", ssoToken.expiresAt); + const { accessToken, expiresAt } = ssoToken; + const existingToken = { token: accessToken, expiration: new Date(expiresAt) }; + if (existingToken.expiration.getTime() - Date.now() > EXPIRE_WINDOW_MS) { + return existingToken; + } + if (Date.now() - lastRefreshAttemptTime.getTime() < 30 * 1e3) { + validateTokenExpiry(existingToken); + return existingToken; + } + validateTokenKey("clientId", ssoToken.clientId, true); + validateTokenKey("clientSecret", ssoToken.clientSecret, true); + validateTokenKey("refreshToken", ssoToken.refreshToken, true); + try { + lastRefreshAttemptTime.setTime(Date.now()); + const newSsoOidcToken = await getNewSsoOidcToken(ssoToken, ssoRegion, init2, callerClientConfig); + validateTokenKey("accessToken", newSsoOidcToken.accessToken); + validateTokenKey("expiresIn", newSsoOidcToken.expiresIn); + const newTokenExpiration = new Date(Date.now() + newSsoOidcToken.expiresIn * 1e3); + try { + await writeSSOTokenToFile(ssoSessionName, { + ...ssoToken, + accessToken: newSsoOidcToken.accessToken, + expiresAt: newTokenExpiration.toISOString(), + refreshToken: newSsoOidcToken.refreshToken + }); + } catch (error50) { + } + return { + token: newSsoOidcToken.accessToken, + expiration: newTokenExpiration + }; + } catch (error50) { + validateTokenExpiry(existingToken); + return existingToken; + } + }; + var fromStatic = ({ token, logger: logger4 }) => async () => { + logger4?.debug("@aws-sdk/token-providers - fromStatic"); + if (!token || !token.token) { + throw new propertyProvider.TokenProviderError(`Please pass a valid token to fromStatic`, false); + } + return token; + }; + var nodeProvider = (init2 = {}) => propertyProvider.memoize(propertyProvider.chain(fromSso(init2), async () => { + throw new propertyProvider.TokenProviderError("Could not load token from any providers", false); + }), (token) => token.expiration !== void 0 && token.expiration.getTime() - Date.now() < 3e5, (token) => token.expiration !== void 0); + exports.fromEnvSigningName = fromEnvSigningName; + exports.fromSso = fromSso; + exports.fromStatic = fromStatic; + exports.nodeProvider = nodeProvider; + } +}); + +// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/auth/httpAuthSchemeProvider.js +function createAwsAuthSigv4HttpAuthOption2(authParameters) { + return { + schemeId: "aws.auth#sigv4", + signingProperties: { + name: "awsssoportal", + region: authParameters.region + }, + propertiesExtractor: (config3, context) => ({ + signingProperties: { + config: config3, + context + } + }) + }; +} +function createSmithyApiNoAuthHttpAuthOption2(authParameters) { + return { + schemeId: "smithy.api#noAuth" + }; +} +var import_util_middleware7, defaultSSOHttpAuthSchemeParametersProvider, defaultSSOHttpAuthSchemeProvider, resolveHttpAuthSchemeConfig2; +var init_httpAuthSchemeProvider2 = __esm({ + "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/auth/httpAuthSchemeProvider.js"() { + init_httpAuthSchemes2(); + import_util_middleware7 = __toESM(require_dist_cjs18()); + defaultSSOHttpAuthSchemeParametersProvider = async (config3, context, input) => { + return { + operation: (0, import_util_middleware7.getSmithyContext)(context).operation, + region: await (0, import_util_middleware7.normalizeProvider)(config3.region)() || (() => { + throw new Error("expected `region` to be configured for `aws.auth#sigv4`"); + })() + }; + }; + defaultSSOHttpAuthSchemeProvider = (authParameters) => { + const options = []; + switch (authParameters.operation) { + case "GetRoleCredentials": { + options.push(createSmithyApiNoAuthHttpAuthOption2(authParameters)); + break; + } + default: { + options.push(createAwsAuthSigv4HttpAuthOption2(authParameters)); + } + } + return options; + }; + resolveHttpAuthSchemeConfig2 = (config3) => { + const config_0 = resolveAwsSdkSigV4Config(config3); + return Object.assign(config_0, { + authSchemePreference: (0, import_util_middleware7.normalizeProvider)(config3.authSchemePreference ?? []) + }); + }; + } +}); + +// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/endpoint/EndpointParameters.js +var resolveClientEndpointParameters2, commonParams2; +var init_EndpointParameters2 = __esm({ + "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/endpoint/EndpointParameters.js"() { + resolveClientEndpointParameters2 = (options) => { + return Object.assign(options, { + useDualstackEndpoint: options.useDualstackEndpoint ?? false, + useFipsEndpoint: options.useFipsEndpoint ?? false, + defaultSigningName: "awsssoportal" + }); + }; + commonParams2 = { + UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, + Endpoint: { type: "builtInParams", name: "endpoint" }, + Region: { type: "builtInParams", name: "region" }, + UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" } + }; + } +}); + +// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/endpoint/ruleset.js +var u2, v2, w2, x2, a2, b3, c2, d2, e2, f2, g2, h2, i2, j2, k2, l2, m2, n2, o2, p2, q2, r2, s2, t2, _data2, ruleSet2; +var init_ruleset2 = __esm({ + "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/endpoint/ruleset.js"() { + u2 = "required"; + v2 = "fn"; + w2 = "argv"; + x2 = "ref"; + a2 = true; + b3 = "isSet"; + c2 = "booleanEquals"; + d2 = "error"; + e2 = "endpoint"; + f2 = "tree"; + g2 = "PartitionResult"; + h2 = "getAttr"; + i2 = { [u2]: false, type: "string" }; + j2 = { [u2]: true, default: false, type: "boolean" }; + k2 = { [x2]: "Endpoint" }; + l2 = { [v2]: c2, [w2]: [{ [x2]: "UseFIPS" }, true] }; + m2 = { [v2]: c2, [w2]: [{ [x2]: "UseDualStack" }, true] }; + n2 = {}; + o2 = { [v2]: h2, [w2]: [{ [x2]: g2 }, "supportsFIPS"] }; + p2 = { [x2]: g2 }; + q2 = { [v2]: c2, [w2]: [true, { [v2]: h2, [w2]: [p2, "supportsDualStack"] }] }; + r2 = [l2]; + s2 = [m2]; + t2 = [{ [x2]: "Region" }]; + _data2 = { + version: "1.0", + parameters: { Region: i2, UseDualStack: j2, UseFIPS: j2, Endpoint: i2 }, + rules: [ + { + conditions: [{ [v2]: b3, [w2]: [k2] }], + rules: [ + { conditions: r2, error: "Invalid Configuration: FIPS and custom endpoint are not supported", type: d2 }, + { conditions: s2, error: "Invalid Configuration: Dualstack and custom endpoint are not supported", type: d2 }, + { endpoint: { url: k2, properties: n2, headers: n2 }, type: e2 } + ], + type: f2 + }, + { + conditions: [{ [v2]: b3, [w2]: t2 }], + rules: [ + { + conditions: [{ [v2]: "aws.partition", [w2]: t2, assign: g2 }], + rules: [ + { + conditions: [l2, m2], + rules: [ + { + conditions: [{ [v2]: c2, [w2]: [a2, o2] }, q2], + rules: [ + { + endpoint: { + url: "https://portal.sso-fips.{Region}.{PartitionResult#dualStackDnsSuffix}", + properties: n2, + headers: n2 + }, + type: e2 + } + ], + type: f2 + }, + { error: "FIPS and DualStack are enabled, but this partition does not support one or both", type: d2 } + ], + type: f2 + }, + { + conditions: r2, + rules: [ + { + conditions: [{ [v2]: c2, [w2]: [o2, a2] }], + rules: [ + { + conditions: [{ [v2]: "stringEquals", [w2]: [{ [v2]: h2, [w2]: [p2, "name"] }, "aws-us-gov"] }], + endpoint: { url: "https://portal.sso.{Region}.amazonaws.com", properties: n2, headers: n2 }, + type: e2 + }, + { + endpoint: { + url: "https://portal.sso-fips.{Region}.{PartitionResult#dnsSuffix}", + properties: n2, + headers: n2 + }, + type: e2 + } + ], + type: f2 + }, + { error: "FIPS is enabled but this partition does not support FIPS", type: d2 } + ], + type: f2 + }, + { + conditions: s2, + rules: [ + { + conditions: [q2], + rules: [ + { + endpoint: { + url: "https://portal.sso.{Region}.{PartitionResult#dualStackDnsSuffix}", + properties: n2, + headers: n2 + }, + type: e2 + } + ], + type: f2 + }, + { error: "DualStack is enabled but this partition does not support DualStack", type: d2 } + ], + type: f2 + }, + { + endpoint: { url: "https://portal.sso.{Region}.{PartitionResult#dnsSuffix}", properties: n2, headers: n2 }, + type: e2 + } + ], + type: f2 + } + ], + type: f2 + }, + { error: "Invalid Configuration: Missing Region", type: d2 } + ] + }; + ruleSet2 = _data2; + } +}); + +// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/endpoint/endpointResolver.js +var import_util_endpoints3, import_util_endpoints4, cache2, defaultEndpointResolver2; +var init_endpointResolver2 = __esm({ + "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/endpoint/endpointResolver.js"() { + import_util_endpoints3 = __toESM(require_dist_cjs34()); + import_util_endpoints4 = __toESM(require_dist_cjs33()); + init_ruleset2(); + cache2 = new import_util_endpoints4.EndpointCache({ + size: 50, + params: ["Endpoint", "Region", "UseDualStack", "UseFIPS"] + }); + defaultEndpointResolver2 = (endpointParams, context = {}) => { + return cache2.get(endpointParams, () => (0, import_util_endpoints4.resolveEndpoint)(ruleSet2, { + endpointParams, + logger: context.logger + })); + }; + import_util_endpoints4.customEndpointFunctions.aws = import_util_endpoints3.awsEndpointFunctions; + } +}); + +// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/models/SSOServiceException.js +var import_smithy_client15, SSOServiceException; +var init_SSOServiceException = __esm({ + "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/models/SSOServiceException.js"() { + import_smithy_client15 = __toESM(require_dist_cjs27()); + SSOServiceException = class _SSOServiceException extends import_smithy_client15.ServiceException { + constructor(options) { + super(options); + Object.setPrototypeOf(this, _SSOServiceException.prototype); + } + }; + } +}); + +// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/models/errors.js +var InvalidRequestException2, ResourceNotFoundException, TooManyRequestsException, UnauthorizedException; +var init_errors4 = __esm({ + "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/models/errors.js"() { + init_SSOServiceException(); + InvalidRequestException2 = class _InvalidRequestException extends SSOServiceException { + name = "InvalidRequestException"; + $fault = "client"; + constructor(opts) { + super({ + name: "InvalidRequestException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _InvalidRequestException.prototype); + } + }; + ResourceNotFoundException = class _ResourceNotFoundException extends SSOServiceException { + name = "ResourceNotFoundException"; + $fault = "client"; + constructor(opts) { + super({ + name: "ResourceNotFoundException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _ResourceNotFoundException.prototype); + } + }; + TooManyRequestsException = class _TooManyRequestsException extends SSOServiceException { + name = "TooManyRequestsException"; + $fault = "client"; + constructor(opts) { + super({ + name: "TooManyRequestsException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _TooManyRequestsException.prototype); + } + }; + UnauthorizedException = class _UnauthorizedException extends SSOServiceException { + name = "UnauthorizedException"; + $fault = "client"; + constructor(opts) { + super({ + name: "UnauthorizedException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _UnauthorizedException.prototype); + } + }; + } +}); + +// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/schemas/schemas_0.js +var _ATT, _GRC, _GRCR, _GRCRe, _IRE2, _RC, _RNFE, _SAKT, _STT, _TMRE, _UE, _aI, _aKI, _aT2, _ai, _c2, _e2, _ex, _h2, _hE2, _hH, _hQ, _m, _rC, _rN, _rn, _s2, _sAK, _sT, _xasbt, n02, _s_registry2, SSOServiceException$, n0_registry2, InvalidRequestException$2, ResourceNotFoundException$, TooManyRequestsException$, UnauthorizedException$, errorTypeRegistries2, AccessTokenType, SecretAccessKeyType, SessionTokenType, GetRoleCredentialsRequest$, GetRoleCredentialsResponse$, RoleCredentials$, GetRoleCredentials$; +var init_schemas_02 = __esm({ + "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/schemas/schemas_0.js"() { + init_schema3(); + init_errors4(); + init_SSOServiceException(); + _ATT = "AccessTokenType"; + _GRC = "GetRoleCredentials"; + _GRCR = "GetRoleCredentialsRequest"; + _GRCRe = "GetRoleCredentialsResponse"; + _IRE2 = "InvalidRequestException"; + _RC = "RoleCredentials"; + _RNFE = "ResourceNotFoundException"; + _SAKT = "SecretAccessKeyType"; + _STT = "SessionTokenType"; + _TMRE = "TooManyRequestsException"; + _UE = "UnauthorizedException"; + _aI = "accountId"; + _aKI = "accessKeyId"; + _aT2 = "accessToken"; + _ai = "account_id"; + _c2 = "client"; + _e2 = "error"; + _ex = "expiration"; + _h2 = "http"; + _hE2 = "httpError"; + _hH = "httpHeader"; + _hQ = "httpQuery"; + _m = "message"; + _rC = "roleCredentials"; + _rN = "roleName"; + _rn = "role_name"; + _s2 = "smithy.ts.sdk.synthetic.com.amazonaws.sso"; + _sAK = "secretAccessKey"; + _sT = "sessionToken"; + _xasbt = "x-amz-sso_bearer_token"; + n02 = "com.amazonaws.sso"; + _s_registry2 = TypeRegistry.for(_s2); + SSOServiceException$ = [-3, _s2, "SSOServiceException", 0, [], []]; + _s_registry2.registerError(SSOServiceException$, SSOServiceException); + n0_registry2 = TypeRegistry.for(n02); + InvalidRequestException$2 = [-3, n02, _IRE2, { [_e2]: _c2, [_hE2]: 400 }, [_m], [0]]; + n0_registry2.registerError(InvalidRequestException$2, InvalidRequestException2); + ResourceNotFoundException$ = [-3, n02, _RNFE, { [_e2]: _c2, [_hE2]: 404 }, [_m], [0]]; + n0_registry2.registerError(ResourceNotFoundException$, ResourceNotFoundException); + TooManyRequestsException$ = [-3, n02, _TMRE, { [_e2]: _c2, [_hE2]: 429 }, [_m], [0]]; + n0_registry2.registerError(TooManyRequestsException$, TooManyRequestsException); + UnauthorizedException$ = [-3, n02, _UE, { [_e2]: _c2, [_hE2]: 401 }, [_m], [0]]; + n0_registry2.registerError(UnauthorizedException$, UnauthorizedException); + errorTypeRegistries2 = [_s_registry2, n0_registry2]; + AccessTokenType = [0, n02, _ATT, 8, 0]; + SecretAccessKeyType = [0, n02, _SAKT, 8, 0]; + SessionTokenType = [0, n02, _STT, 8, 0]; + GetRoleCredentialsRequest$ = [ + 3, + n02, + _GRCR, + 0, + [_rN, _aI, _aT2], + [ + [0, { [_hQ]: _rn }], + [0, { [_hQ]: _ai }], + [() => AccessTokenType, { [_hH]: _xasbt }] + ], + 3 + ]; + GetRoleCredentialsResponse$ = [ + 3, + n02, + _GRCRe, + 0, + [_rC], + [[() => RoleCredentials$, 0]] + ]; + RoleCredentials$ = [ + 3, + n02, + _RC, + 0, + [_aKI, _sAK, _sT, _ex], + [0, [() => SecretAccessKeyType, 0], [() => SessionTokenType, 0], 1] + ]; + GetRoleCredentials$ = [ + 9, + n02, + _GRC, + { [_h2]: ["GET", "/federation/credentials", 200] }, + () => GetRoleCredentialsRequest$, + () => GetRoleCredentialsResponse$ + ]; + } +}); + +// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/runtimeConfig.shared.js +var import_smithy_client16, import_url_parser3, import_util_base649, import_util_utf89, getRuntimeConfig3; +var init_runtimeConfig_shared2 = __esm({ + "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/runtimeConfig.shared.js"() { + init_httpAuthSchemes2(); + init_protocols2(); + init_dist_es(); + import_smithy_client16 = __toESM(require_dist_cjs27()); + import_url_parser3 = __toESM(require_dist_cjs25()); + import_util_base649 = __toESM(require_dist_cjs7()); + import_util_utf89 = __toESM(require_dist_cjs6()); + init_httpAuthSchemeProvider2(); + init_endpointResolver2(); + init_schemas_02(); + getRuntimeConfig3 = (config3) => { + return { + apiVersion: "2019-06-10", + base64Decoder: config3?.base64Decoder ?? import_util_base649.fromBase64, + base64Encoder: config3?.base64Encoder ?? import_util_base649.toBase64, + disableHostPrefix: config3?.disableHostPrefix ?? false, + endpointProvider: config3?.endpointProvider ?? defaultEndpointResolver2, + extensions: config3?.extensions ?? [], + httpAuthSchemeProvider: config3?.httpAuthSchemeProvider ?? defaultSSOHttpAuthSchemeProvider, + httpAuthSchemes: config3?.httpAuthSchemes ?? [ + { + schemeId: "aws.auth#sigv4", + identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"), + signer: new AwsSdkSigV4Signer() + }, + { + schemeId: "smithy.api#noAuth", + identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})), + signer: new NoAuthSigner() + } + ], + logger: config3?.logger ?? new import_smithy_client16.NoOpLogger(), + protocol: config3?.protocol ?? AwsRestJsonProtocol, + protocolSettings: config3?.protocolSettings ?? { + defaultNamespace: "com.amazonaws.sso", + errorTypeRegistries: errorTypeRegistries2, + version: "2019-06-10", + serviceTarget: "SWBPortalService" + }, + serviceId: config3?.serviceId ?? "SSO", + urlParser: config3?.urlParser ?? import_url_parser3.parseUrl, + utf8Decoder: config3?.utf8Decoder ?? import_util_utf89.fromUtf8, + utf8Encoder: config3?.utf8Encoder ?? import_util_utf89.toUtf8 + }; + }; + } +}); + +// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/runtimeConfig.js +var import_util_user_agent_node2, import_config_resolver3, import_hash_node2, import_middleware_retry3, import_node_config_provider2, import_node_http_handler2, import_smithy_client17, import_util_body_length_node2, import_util_defaults_mode_node2, import_util_retry2, getRuntimeConfig4; +var init_runtimeConfig2 = __esm({ + "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/runtimeConfig.js"() { + init_package(); + init_client2(); + init_httpAuthSchemes2(); + import_util_user_agent_node2 = __toESM(require_dist_cjs51()); + import_config_resolver3 = __toESM(require_dist_cjs38()); + import_hash_node2 = __toESM(require_dist_cjs52()); + import_middleware_retry3 = __toESM(require_dist_cjs46()); + import_node_config_provider2 = __toESM(require_dist_cjs43()); + import_node_http_handler2 = __toESM(require_dist_cjs10()); + import_smithy_client17 = __toESM(require_dist_cjs27()); + import_util_body_length_node2 = __toESM(require_dist_cjs53()); + import_util_defaults_mode_node2 = __toESM(require_dist_cjs54()); + import_util_retry2 = __toESM(require_dist_cjs36()); + init_runtimeConfig_shared2(); + getRuntimeConfig4 = (config3) => { + (0, import_smithy_client17.emitWarningIfUnsupportedVersion)(process.version); + const defaultsMode = (0, import_util_defaults_mode_node2.resolveDefaultsModeConfig)(config3); + const defaultConfigProvider = () => defaultsMode().then(import_smithy_client17.loadConfigsForDefaultMode); + const clientSharedValues = getRuntimeConfig3(config3); + emitWarningIfUnsupportedVersion(process.version); + const loaderConfig = { + profile: config3?.profile, + logger: clientSharedValues.logger + }; + return { + ...clientSharedValues, + ...config3, + runtime: "node", + defaultsMode, + authSchemePreference: config3?.authSchemePreference ?? (0, import_node_config_provider2.loadConfig)(NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig), + bodyLengthChecker: config3?.bodyLengthChecker ?? import_util_body_length_node2.calculateBodyLength, + defaultUserAgentProvider: config3?.defaultUserAgentProvider ?? (0, import_util_user_agent_node2.createDefaultUserAgentProvider)({ serviceId: clientSharedValues.serviceId, clientVersion: package_default.version }), + maxAttempts: config3?.maxAttempts ?? (0, import_node_config_provider2.loadConfig)(import_middleware_retry3.NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config3), + region: config3?.region ?? (0, import_node_config_provider2.loadConfig)(import_config_resolver3.NODE_REGION_CONFIG_OPTIONS, { ...import_config_resolver3.NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }), + requestHandler: import_node_http_handler2.NodeHttpHandler.create(config3?.requestHandler ?? defaultConfigProvider), + retryMode: config3?.retryMode ?? (0, import_node_config_provider2.loadConfig)({ + ...import_middleware_retry3.NODE_RETRY_MODE_CONFIG_OPTIONS, + default: async () => (await defaultConfigProvider()).retryMode || import_util_retry2.DEFAULT_RETRY_MODE + }, config3), + sha256: config3?.sha256 ?? import_hash_node2.Hash.bind(null, "sha256"), + streamCollector: config3?.streamCollector ?? import_node_http_handler2.streamCollector, + useDualstackEndpoint: config3?.useDualstackEndpoint ?? (0, import_node_config_provider2.loadConfig)(import_config_resolver3.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig), + useFipsEndpoint: config3?.useFipsEndpoint ?? (0, import_node_config_provider2.loadConfig)(import_config_resolver3.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig), + userAgentAppId: config3?.userAgentAppId ?? (0, import_node_config_provider2.loadConfig)(import_util_user_agent_node2.NODE_APP_ID_CONFIG_OPTIONS, loaderConfig) + }; + }; + } +}); + +// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/auth/httpAuthExtensionConfiguration.js +var getHttpAuthExtensionConfiguration2, resolveHttpAuthRuntimeConfig2; +var init_httpAuthExtensionConfiguration2 = __esm({ + "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/auth/httpAuthExtensionConfiguration.js"() { + getHttpAuthExtensionConfiguration2 = (runtimeConfig) => { + const _httpAuthSchemes = runtimeConfig.httpAuthSchemes; + let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider; + let _credentials = runtimeConfig.credentials; + return { + setHttpAuthScheme(httpAuthScheme) { + const index2 = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId); + if (index2 === -1) { + _httpAuthSchemes.push(httpAuthScheme); + } else { + _httpAuthSchemes.splice(index2, 1, httpAuthScheme); + } + }, + httpAuthSchemes() { + return _httpAuthSchemes; + }, + setHttpAuthSchemeProvider(httpAuthSchemeProvider) { + _httpAuthSchemeProvider = httpAuthSchemeProvider; + }, + httpAuthSchemeProvider() { + return _httpAuthSchemeProvider; + }, + setCredentials(credentials) { + _credentials = credentials; + }, + credentials() { + return _credentials; + } + }; + }; + resolveHttpAuthRuntimeConfig2 = (config3) => { + return { + httpAuthSchemes: config3.httpAuthSchemes(), + httpAuthSchemeProvider: config3.httpAuthSchemeProvider(), + credentials: config3.credentials() + }; + }; + } +}); + +// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/runtimeExtensions.js +var import_region_config_resolver2, import_protocol_http13, import_smithy_client18, resolveRuntimeExtensions2; +var init_runtimeExtensions2 = __esm({ + "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/runtimeExtensions.js"() { + import_region_config_resolver2 = __toESM(require_dist_cjs55()); + import_protocol_http13 = __toESM(require_dist_cjs2()); + import_smithy_client18 = __toESM(require_dist_cjs27()); + init_httpAuthExtensionConfiguration2(); + resolveRuntimeExtensions2 = (runtimeConfig, extensions) => { + const extensionConfiguration = Object.assign((0, import_region_config_resolver2.getAwsRegionExtensionConfiguration)(runtimeConfig), (0, import_smithy_client18.getDefaultExtensionConfiguration)(runtimeConfig), (0, import_protocol_http13.getHttpHandlerExtensionConfiguration)(runtimeConfig), getHttpAuthExtensionConfiguration2(runtimeConfig)); + extensions.forEach((extension2) => extension2.configure(extensionConfiguration)); + return Object.assign(runtimeConfig, (0, import_region_config_resolver2.resolveAwsRegionExtensionConfiguration)(extensionConfiguration), (0, import_smithy_client18.resolveDefaultRuntimeConfig)(extensionConfiguration), (0, import_protocol_http13.resolveHttpHandlerRuntimeConfig)(extensionConfiguration), resolveHttpAuthRuntimeConfig2(extensionConfiguration)); + }; + } +}); + +// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/SSOClient.js +var import_middleware_host_header2, import_middleware_logger2, import_middleware_recursion_detection2, import_middleware_user_agent2, import_config_resolver4, import_middleware_content_length2, import_middleware_endpoint3, import_middleware_retry4, import_smithy_client19, SSOClient; +var init_SSOClient = __esm({ + "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/SSOClient.js"() { + import_middleware_host_header2 = __toESM(require_dist_cjs20()); + import_middleware_logger2 = __toESM(require_dist_cjs21()); + import_middleware_recursion_detection2 = __toESM(require_dist_cjs22()); + import_middleware_user_agent2 = __toESM(require_dist_cjs37()); + import_config_resolver4 = __toESM(require_dist_cjs38()); + init_dist_es(); + init_schema3(); + import_middleware_content_length2 = __toESM(require_dist_cjs40()); + import_middleware_endpoint3 = __toESM(require_dist_cjs45()); + import_middleware_retry4 = __toESM(require_dist_cjs46()); + import_smithy_client19 = __toESM(require_dist_cjs27()); + init_httpAuthSchemeProvider2(); + init_EndpointParameters2(); + init_runtimeConfig2(); + init_runtimeExtensions2(); + SSOClient = class extends import_smithy_client19.Client { + config; + constructor(...[configuration]) { + const _config_0 = getRuntimeConfig4(configuration || {}); + super(_config_0); + this.initConfig = _config_0; + const _config_1 = resolveClientEndpointParameters2(_config_0); + const _config_2 = (0, import_middleware_user_agent2.resolveUserAgentConfig)(_config_1); + const _config_3 = (0, import_middleware_retry4.resolveRetryConfig)(_config_2); + const _config_4 = (0, import_config_resolver4.resolveRegionConfig)(_config_3); + const _config_5 = (0, import_middleware_host_header2.resolveHostHeaderConfig)(_config_4); + const _config_6 = (0, import_middleware_endpoint3.resolveEndpointConfig)(_config_5); + const _config_7 = resolveHttpAuthSchemeConfig2(_config_6); + const _config_8 = resolveRuntimeExtensions2(_config_7, configuration?.extensions || []); + this.config = _config_8; + this.middlewareStack.use(getSchemaSerdePlugin(this.config)); + this.middlewareStack.use((0, import_middleware_user_agent2.getUserAgentPlugin)(this.config)); + this.middlewareStack.use((0, import_middleware_retry4.getRetryPlugin)(this.config)); + this.middlewareStack.use((0, import_middleware_content_length2.getContentLengthPlugin)(this.config)); + this.middlewareStack.use((0, import_middleware_host_header2.getHostHeaderPlugin)(this.config)); + this.middlewareStack.use((0, import_middleware_logger2.getLoggerPlugin)(this.config)); + this.middlewareStack.use((0, import_middleware_recursion_detection2.getRecursionDetectionPlugin)(this.config)); + this.middlewareStack.use(getHttpAuthSchemeEndpointRuleSetPlugin(this.config, { + httpAuthSchemeParametersProvider: defaultSSOHttpAuthSchemeParametersProvider, + identityProviderConfigProvider: async (config3) => new DefaultIdentityProviderConfig({ + "aws.auth#sigv4": config3.credentials + }) + })); + this.middlewareStack.use(getHttpSigningPlugin(this.config)); + } + destroy() { + super.destroy(); + } + }; + } +}); + +// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/commands/GetRoleCredentialsCommand.js +var import_middleware_endpoint4, import_smithy_client20, GetRoleCredentialsCommand; +var init_GetRoleCredentialsCommand = __esm({ + "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/commands/GetRoleCredentialsCommand.js"() { + import_middleware_endpoint4 = __toESM(require_dist_cjs45()); + import_smithy_client20 = __toESM(require_dist_cjs27()); + init_EndpointParameters2(); + init_schemas_02(); + GetRoleCredentialsCommand = class extends import_smithy_client20.Command.classBuilder().ep(commonParams2).m(function(Command2, cs, config3, o5) { + return [(0, import_middleware_endpoint4.getEndpointPlugin)(config3, Command2.getEndpointParameterInstructions())]; + }).s("SWBPortalService", "GetRoleCredentials", {}).n("SSOClient", "GetRoleCredentialsCommand").sc(GetRoleCredentials$).build() { + }; + } +}); + +// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/SSO.js +var import_smithy_client21, commands2, SSO; +var init_SSO = __esm({ + "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/SSO.js"() { + import_smithy_client21 = __toESM(require_dist_cjs27()); + init_GetRoleCredentialsCommand(); + init_SSOClient(); + commands2 = { + GetRoleCredentialsCommand + }; + SSO = class extends SSOClient { + }; + (0, import_smithy_client21.createAggregatedClient)(commands2, SSO); + } +}); + +// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/commands/index.js +var init_commands2 = __esm({ + "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/commands/index.js"() { + init_GetRoleCredentialsCommand(); + } +}); + +// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/models/models_0.js +var init_models_02 = __esm({ + "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/models/models_0.js"() { + } +}); + +// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/index.js +var sso_exports = {}; +__export(sso_exports, { + $Command: () => import_smithy_client20.Command, + GetRoleCredentials$: () => GetRoleCredentials$, + GetRoleCredentialsCommand: () => GetRoleCredentialsCommand, + GetRoleCredentialsRequest$: () => GetRoleCredentialsRequest$, + GetRoleCredentialsResponse$: () => GetRoleCredentialsResponse$, + InvalidRequestException: () => InvalidRequestException2, + InvalidRequestException$: () => InvalidRequestException$2, + ResourceNotFoundException: () => ResourceNotFoundException, + ResourceNotFoundException$: () => ResourceNotFoundException$, + RoleCredentials$: () => RoleCredentials$, + SSO: () => SSO, + SSOClient: () => SSOClient, + SSOServiceException: () => SSOServiceException, + SSOServiceException$: () => SSOServiceException$, + TooManyRequestsException: () => TooManyRequestsException, + TooManyRequestsException$: () => TooManyRequestsException$, + UnauthorizedException: () => UnauthorizedException, + UnauthorizedException$: () => UnauthorizedException$, + __Client: () => import_smithy_client19.Client, + errorTypeRegistries: () => errorTypeRegistries2 +}); +var init_sso = __esm({ + "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/index.js"() { + init_SSOClient(); + init_SSO(); + init_commands2(); + init_schemas_02(); + init_errors4(); + init_models_02(); + init_SSOServiceException(); + } +}); + +// node_modules/.pnpm/@aws-sdk+credential-provider-sso@3.972.29/node_modules/@aws-sdk/credential-provider-sso/dist-cjs/loadSso-BKDNrsal.js +var require_loadSso_BKDNrsal = __commonJS({ + "node_modules/.pnpm/@aws-sdk+credential-provider-sso@3.972.29/node_modules/@aws-sdk/credential-provider-sso/dist-cjs/loadSso-BKDNrsal.js"(exports) { + "use strict"; + var sso = (init_sso(), __toCommonJS(sso_exports)); + exports.GetRoleCredentialsCommand = sso.GetRoleCredentialsCommand; + exports.SSOClient = sso.SSOClient; + } +}); + +// node_modules/.pnpm/@aws-sdk+credential-provider-sso@3.972.29/node_modules/@aws-sdk/credential-provider-sso/dist-cjs/index.js +var require_dist_cjs57 = __commonJS({ + "node_modules/.pnpm/@aws-sdk+credential-provider-sso@3.972.29/node_modules/@aws-sdk/credential-provider-sso/dist-cjs/index.js"(exports) { + "use strict"; + var propertyProvider = require_dist_cjs41(); + var sharedIniFileLoader = require_dist_cjs42(); + var client2 = (init_client2(), __toCommonJS(client_exports)); + var tokenProviders = require_dist_cjs56(); + var isSsoProfile = (arg) => arg && (typeof arg.sso_start_url === "string" || typeof arg.sso_account_id === "string" || typeof arg.sso_session === "string" || typeof arg.sso_region === "string" || typeof arg.sso_role_name === "string"); + var SHOULD_FAIL_CREDENTIAL_CHAIN = false; + var resolveSSOCredentials = async ({ ssoStartUrl, ssoSession, ssoAccountId, ssoRegion, ssoRoleName, ssoClient, clientConfig, parentClientConfig, callerClientConfig, profile, filepath, configFilepath, ignoreCache, logger: logger4 }) => { + let token; + const refreshMessage = `To refresh this SSO session run aws sso login with the corresponding profile.`; + if (ssoSession) { + try { + const _token = await tokenProviders.fromSso({ + profile, + filepath, + configFilepath, + ignoreCache + })(); + token = { + accessToken: _token.token, + expiresAt: new Date(_token.expiration).toISOString() + }; + } catch (e5) { + throw new propertyProvider.CredentialsProviderError(e5.message, { + tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN, + logger: logger4 + }); + } + } else { + try { + token = await sharedIniFileLoader.getSSOTokenFromFile(ssoStartUrl); + } catch (e5) { + throw new propertyProvider.CredentialsProviderError(`The SSO session associated with this profile is invalid. ${refreshMessage}`, { + tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN, + logger: logger4 + }); + } + } + if (new Date(token.expiresAt).getTime() - Date.now() <= 0) { + throw new propertyProvider.CredentialsProviderError(`The SSO session associated with this profile has expired. ${refreshMessage}`, { + tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN, + logger: logger4 + }); + } + const { accessToken } = token; + const { SSOClient: SSOClient2, GetRoleCredentialsCommand: GetRoleCredentialsCommand2 } = await Promise.resolve().then(function() { + return require_loadSso_BKDNrsal(); + }); + const sso = ssoClient || new SSOClient2(Object.assign({}, clientConfig ?? {}, { + logger: clientConfig?.logger ?? callerClientConfig?.logger ?? parentClientConfig?.logger, + region: clientConfig?.region ?? ssoRegion, + userAgentAppId: clientConfig?.userAgentAppId ?? callerClientConfig?.userAgentAppId ?? parentClientConfig?.userAgentAppId + })); + let ssoResp; + try { + ssoResp = await sso.send(new GetRoleCredentialsCommand2({ + accountId: ssoAccountId, + roleName: ssoRoleName, + accessToken + })); + } catch (e5) { + throw new propertyProvider.CredentialsProviderError(e5, { + tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN, + logger: logger4 + }); + } + const { roleCredentials: { accessKeyId, secretAccessKey, sessionToken, expiration, credentialScope, accountId } = {} } = ssoResp; + if (!accessKeyId || !secretAccessKey || !sessionToken || !expiration) { + throw new propertyProvider.CredentialsProviderError("SSO returns an invalid temporary credential.", { + tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN, + logger: logger4 + }); + } + const credentials = { + accessKeyId, + secretAccessKey, + sessionToken, + expiration: new Date(expiration), + ...credentialScope && { credentialScope }, + ...accountId && { accountId } + }; + if (ssoSession) { + client2.setCredentialFeature(credentials, "CREDENTIALS_SSO", "s"); + } else { + client2.setCredentialFeature(credentials, "CREDENTIALS_SSO_LEGACY", "u"); + } + return credentials; + }; + var validateSsoProfile = (profile, logger4) => { + const { sso_start_url, sso_account_id, sso_region, sso_role_name } = profile; + if (!sso_start_url || !sso_account_id || !sso_region || !sso_role_name) { + throw new propertyProvider.CredentialsProviderError(`Profile is configured with invalid SSO credentials. Required parameters "sso_account_id", "sso_region", "sso_role_name", "sso_start_url". Got ${Object.keys(profile).join(", ")} +Reference: https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sso.html`, { tryNextLink: false, logger: logger4 }); + } + return profile; + }; + var fromSSO = (init2 = {}) => async ({ callerClientConfig } = {}) => { + init2.logger?.debug("@aws-sdk/credential-provider-sso - fromSSO"); + const { ssoStartUrl, ssoAccountId, ssoRegion, ssoRoleName, ssoSession } = init2; + const { ssoClient } = init2; + const profileName = sharedIniFileLoader.getProfileName({ + profile: init2.profile ?? callerClientConfig?.profile + }); + if (!ssoStartUrl && !ssoAccountId && !ssoRegion && !ssoRoleName && !ssoSession) { + const profiles = await sharedIniFileLoader.parseKnownFiles(init2); + const profile = profiles[profileName]; + if (!profile) { + throw new propertyProvider.CredentialsProviderError(`Profile ${profileName} was not found.`, { logger: init2.logger }); + } + if (!isSsoProfile(profile)) { + throw new propertyProvider.CredentialsProviderError(`Profile ${profileName} is not configured with SSO credentials.`, { + logger: init2.logger + }); + } + if (profile?.sso_session) { + const ssoSessions = await sharedIniFileLoader.loadSsoSessionData(init2); + const session = ssoSessions[profile.sso_session]; + const conflictMsg = ` configurations in profile ${profileName} and sso-session ${profile.sso_session}`; + if (ssoRegion && ssoRegion !== session.sso_region) { + throw new propertyProvider.CredentialsProviderError(`Conflicting SSO region` + conflictMsg, { + tryNextLink: false, + logger: init2.logger + }); + } + if (ssoStartUrl && ssoStartUrl !== session.sso_start_url) { + throw new propertyProvider.CredentialsProviderError(`Conflicting SSO start_url` + conflictMsg, { + tryNextLink: false, + logger: init2.logger + }); + } + profile.sso_region = session.sso_region; + profile.sso_start_url = session.sso_start_url; + } + const { sso_start_url, sso_account_id, sso_region, sso_role_name, sso_session } = validateSsoProfile(profile, init2.logger); + return resolveSSOCredentials({ + ssoStartUrl: sso_start_url, + ssoSession: sso_session, + ssoAccountId: sso_account_id, + ssoRegion: sso_region, + ssoRoleName: sso_role_name, + ssoClient, + clientConfig: init2.clientConfig, + parentClientConfig: init2.parentClientConfig, + callerClientConfig: init2.callerClientConfig, + profile: profileName, + filepath: init2.filepath, + configFilepath: init2.configFilepath, + ignoreCache: init2.ignoreCache, + logger: init2.logger + }); + } else if (!ssoStartUrl || !ssoAccountId || !ssoRegion || !ssoRoleName) { + throw new propertyProvider.CredentialsProviderError('Incomplete configuration. The fromSSO() argument hash must include "ssoStartUrl", "ssoAccountId", "ssoRegion", "ssoRoleName"', { tryNextLink: false, logger: init2.logger }); + } else { + return resolveSSOCredentials({ + ssoStartUrl, + ssoSession, + ssoAccountId, + ssoRegion, + ssoRoleName, + ssoClient, + clientConfig: init2.clientConfig, + parentClientConfig: init2.parentClientConfig, + callerClientConfig: init2.callerClientConfig, + profile: profileName, + filepath: init2.filepath, + configFilepath: init2.configFilepath, + ignoreCache: init2.ignoreCache, + logger: init2.logger + }); + } + }; + exports.fromSSO = fromSSO; + exports.isSsoProfile = isSsoProfile; + exports.validateSsoProfile = validateSsoProfile; + } +}); + +// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/auth/httpAuthSchemeProvider.js +function createAwsAuthSigv4HttpAuthOption3(authParameters) { + return { + schemeId: "aws.auth#sigv4", + signingProperties: { + name: "signin", + region: authParameters.region + }, + propertiesExtractor: (config3, context) => ({ + signingProperties: { + config: config3, + context + } + }) + }; +} +function createSmithyApiNoAuthHttpAuthOption3(authParameters) { + return { + schemeId: "smithy.api#noAuth" + }; +} +var import_util_middleware8, defaultSigninHttpAuthSchemeParametersProvider, defaultSigninHttpAuthSchemeProvider, resolveHttpAuthSchemeConfig3; +var init_httpAuthSchemeProvider3 = __esm({ + "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/auth/httpAuthSchemeProvider.js"() { + init_httpAuthSchemes2(); + import_util_middleware8 = __toESM(require_dist_cjs18()); + defaultSigninHttpAuthSchemeParametersProvider = async (config3, context, input) => { + return { + operation: (0, import_util_middleware8.getSmithyContext)(context).operation, + region: await (0, import_util_middleware8.normalizeProvider)(config3.region)() || (() => { + throw new Error("expected `region` to be configured for `aws.auth#sigv4`"); + })() + }; + }; + defaultSigninHttpAuthSchemeProvider = (authParameters) => { + const options = []; + switch (authParameters.operation) { + case "CreateOAuth2Token": { + options.push(createSmithyApiNoAuthHttpAuthOption3(authParameters)); + break; + } + default: { + options.push(createAwsAuthSigv4HttpAuthOption3(authParameters)); + } + } + return options; + }; + resolveHttpAuthSchemeConfig3 = (config3) => { + const config_0 = resolveAwsSdkSigV4Config(config3); + return Object.assign(config_0, { + authSchemePreference: (0, import_util_middleware8.normalizeProvider)(config3.authSchemePreference ?? []) + }); + }; + } +}); + +// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/endpoint/EndpointParameters.js +var resolveClientEndpointParameters3, commonParams3; +var init_EndpointParameters3 = __esm({ + "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/endpoint/EndpointParameters.js"() { + resolveClientEndpointParameters3 = (options) => { + return Object.assign(options, { + useDualstackEndpoint: options.useDualstackEndpoint ?? false, + useFipsEndpoint: options.useFipsEndpoint ?? false, + defaultSigningName: "signin" + }); + }; + commonParams3 = { + UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, + Endpoint: { type: "builtInParams", name: "endpoint" }, + Region: { type: "builtInParams", name: "region" }, + UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" } + }; + } +}); + +// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/endpoint/ruleset.js +var u3, v3, w3, x3, a3, b4, c3, d3, e3, f3, g3, h3, i3, j3, k3, l3, m3, n3, o3, p3, q3, r3, s3, t3, _data3, ruleSet3; +var init_ruleset3 = __esm({ + "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/endpoint/ruleset.js"() { + u3 = "required"; + v3 = "fn"; + w3 = "argv"; + x3 = "ref"; + a3 = true; + b4 = "isSet"; + c3 = "booleanEquals"; + d3 = "error"; + e3 = "endpoint"; + f3 = "tree"; + g3 = "PartitionResult"; + h3 = "stringEquals"; + i3 = { [u3]: true, default: false, type: "boolean" }; + j3 = { [u3]: false, type: "string" }; + k3 = { [x3]: "Endpoint" }; + l3 = { [v3]: c3, [w3]: [{ [x3]: "UseFIPS" }, true] }; + m3 = { [v3]: c3, [w3]: [{ [x3]: "UseDualStack" }, true] }; + n3 = {}; + o3 = { [v3]: "getAttr", [w3]: [{ [x3]: g3 }, "name"] }; + p3 = { [v3]: c3, [w3]: [{ [x3]: "UseFIPS" }, false] }; + q3 = { [v3]: c3, [w3]: [{ [x3]: "UseDualStack" }, false] }; + r3 = { [v3]: "getAttr", [w3]: [{ [x3]: g3 }, "supportsFIPS"] }; + s3 = { [v3]: c3, [w3]: [true, { [v3]: "getAttr", [w3]: [{ [x3]: g3 }, "supportsDualStack"] }] }; + t3 = [{ [x3]: "Region" }]; + _data3 = { + version: "1.0", + parameters: { UseDualStack: i3, UseFIPS: i3, Endpoint: j3, Region: j3 }, + rules: [ + { + conditions: [{ [v3]: b4, [w3]: [k3] }], + rules: [ + { conditions: [l3], error: "Invalid Configuration: FIPS and custom endpoint are not supported", type: d3 }, + { + rules: [ + { + conditions: [m3], + error: "Invalid Configuration: Dualstack and custom endpoint are not supported", + type: d3 + }, + { endpoint: { url: k3, properties: n3, headers: n3 }, type: e3 } + ], + type: f3 + } + ], + type: f3 + }, + { + rules: [ + { + conditions: [{ [v3]: b4, [w3]: t3 }], + rules: [ + { + conditions: [{ [v3]: "aws.partition", [w3]: t3, assign: g3 }], + rules: [ + { + conditions: [{ [v3]: h3, [w3]: [o3, "aws"] }, p3, q3], + endpoint: { url: "https://{Region}.signin.aws.amazon.com", properties: n3, headers: n3 }, + type: e3 + }, + { + conditions: [{ [v3]: h3, [w3]: [o3, "aws-cn"] }, p3, q3], + endpoint: { url: "https://{Region}.signin.amazonaws.cn", properties: n3, headers: n3 }, + type: e3 + }, + { + conditions: [{ [v3]: h3, [w3]: [o3, "aws-us-gov"] }, p3, q3], + endpoint: { url: "https://{Region}.signin.amazonaws-us-gov.com", properties: n3, headers: n3 }, + type: e3 + }, + { + conditions: [l3, m3], + rules: [ + { + conditions: [{ [v3]: c3, [w3]: [a3, r3] }, s3], + rules: [ + { + endpoint: { + url: "https://signin-fips.{Region}.{PartitionResult#dualStackDnsSuffix}", + properties: n3, + headers: n3 + }, + type: e3 + } + ], + type: f3 + }, + { + error: "FIPS and DualStack are enabled, but this partition does not support one or both", + type: d3 + } + ], + type: f3 + }, + { + conditions: [l3, q3], + rules: [ + { + conditions: [{ [v3]: c3, [w3]: [r3, a3] }], + rules: [ + { + endpoint: { + url: "https://signin-fips.{Region}.{PartitionResult#dnsSuffix}", + properties: n3, + headers: n3 + }, + type: e3 + } + ], + type: f3 + }, + { error: "FIPS is enabled but this partition does not support FIPS", type: d3 } + ], + type: f3 + }, + { + conditions: [p3, m3], + rules: [ + { + conditions: [s3], + rules: [ + { + endpoint: { + url: "https://signin.{Region}.{PartitionResult#dualStackDnsSuffix}", + properties: n3, + headers: n3 + }, + type: e3 + } + ], + type: f3 + }, + { error: "DualStack is enabled but this partition does not support DualStack", type: d3 } + ], + type: f3 + }, + { + endpoint: { url: "https://signin.{Region}.{PartitionResult#dnsSuffix}", properties: n3, headers: n3 }, + type: e3 + } + ], + type: f3 + } + ], + type: f3 + }, + { error: "Invalid Configuration: Missing Region", type: d3 } + ], + type: f3 + } + ] + }; + ruleSet3 = _data3; + } +}); + +// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/endpoint/endpointResolver.js +var import_util_endpoints5, import_util_endpoints6, cache3, defaultEndpointResolver3; +var init_endpointResolver3 = __esm({ + "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/endpoint/endpointResolver.js"() { + import_util_endpoints5 = __toESM(require_dist_cjs34()); + import_util_endpoints6 = __toESM(require_dist_cjs33()); + init_ruleset3(); + cache3 = new import_util_endpoints6.EndpointCache({ + size: 50, + params: ["Endpoint", "Region", "UseDualStack", "UseFIPS"] + }); + defaultEndpointResolver3 = (endpointParams, context = {}) => { + return cache3.get(endpointParams, () => (0, import_util_endpoints6.resolveEndpoint)(ruleSet3, { + endpointParams, + logger: context.logger + })); + }; + import_util_endpoints6.customEndpointFunctions.aws = import_util_endpoints5.awsEndpointFunctions; + } +}); + +// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/models/SigninServiceException.js +var import_smithy_client22, SigninServiceException; +var init_SigninServiceException = __esm({ + "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/models/SigninServiceException.js"() { + import_smithy_client22 = __toESM(require_dist_cjs27()); + SigninServiceException = class _SigninServiceException extends import_smithy_client22.ServiceException { + constructor(options) { + super(options); + Object.setPrototypeOf(this, _SigninServiceException.prototype); + } + }; + } +}); + +// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/models/errors.js +var AccessDeniedException2, InternalServerException2, TooManyRequestsError, ValidationException; +var init_errors5 = __esm({ + "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/models/errors.js"() { + init_SigninServiceException(); + AccessDeniedException2 = class _AccessDeniedException extends SigninServiceException { + name = "AccessDeniedException"; + $fault = "client"; + error; + constructor(opts) { + super({ + name: "AccessDeniedException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _AccessDeniedException.prototype); + this.error = opts.error; + } + }; + InternalServerException2 = class _InternalServerException extends SigninServiceException { + name = "InternalServerException"; + $fault = "server"; + error; + constructor(opts) { + super({ + name: "InternalServerException", + $fault: "server", + ...opts + }); + Object.setPrototypeOf(this, _InternalServerException.prototype); + this.error = opts.error; + } + }; + TooManyRequestsError = class _TooManyRequestsError extends SigninServiceException { + name = "TooManyRequestsError"; + $fault = "client"; + error; + constructor(opts) { + super({ + name: "TooManyRequestsError", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _TooManyRequestsError.prototype); + this.error = opts.error; + } + }; + ValidationException = class _ValidationException extends SigninServiceException { + name = "ValidationException"; + $fault = "client"; + error; + constructor(opts) { + super({ + name: "ValidationException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _ValidationException.prototype); + this.error = opts.error; + } + }; + } +}); + +// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/schemas/schemas_0.js +var _ADE2, _AT2, _COAT, _COATR, _COATRB, _COATRBr, _COATRr, _ISE2, _RT2, _TMRE2, _VE, _aKI2, _aT3, _c3, _cI2, _cV2, _co2, _e3, _eI2, _gT2, _h3, _hE3, _iT2, _jN, _m2, _rT2, _rU2, _s3, _sAK2, _sT2, _se2, _tI, _tO, _tT2, n03, _s_registry3, SigninServiceException$, n0_registry3, AccessDeniedException$2, InternalServerException$2, TooManyRequestsError$, ValidationException$, errorTypeRegistries3, RefreshToken2, AccessToken$, CreateOAuth2TokenRequest$, CreateOAuth2TokenRequestBody$, CreateOAuth2TokenResponse$, CreateOAuth2TokenResponseBody$, CreateOAuth2Token$; +var init_schemas_03 = __esm({ + "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/schemas/schemas_0.js"() { + init_schema3(); + init_errors5(); + init_SigninServiceException(); + _ADE2 = "AccessDeniedException"; + _AT2 = "AccessToken"; + _COAT = "CreateOAuth2Token"; + _COATR = "CreateOAuth2TokenRequest"; + _COATRB = "CreateOAuth2TokenRequestBody"; + _COATRBr = "CreateOAuth2TokenResponseBody"; + _COATRr = "CreateOAuth2TokenResponse"; + _ISE2 = "InternalServerException"; + _RT2 = "RefreshToken"; + _TMRE2 = "TooManyRequestsError"; + _VE = "ValidationException"; + _aKI2 = "accessKeyId"; + _aT3 = "accessToken"; + _c3 = "client"; + _cI2 = "clientId"; + _cV2 = "codeVerifier"; + _co2 = "code"; + _e3 = "error"; + _eI2 = "expiresIn"; + _gT2 = "grantType"; + _h3 = "http"; + _hE3 = "httpError"; + _iT2 = "idToken"; + _jN = "jsonName"; + _m2 = "message"; + _rT2 = "refreshToken"; + _rU2 = "redirectUri"; + _s3 = "smithy.ts.sdk.synthetic.com.amazonaws.signin"; + _sAK2 = "secretAccessKey"; + _sT2 = "sessionToken"; + _se2 = "server"; + _tI = "tokenInput"; + _tO = "tokenOutput"; + _tT2 = "tokenType"; + n03 = "com.amazonaws.signin"; + _s_registry3 = TypeRegistry.for(_s3); + SigninServiceException$ = [-3, _s3, "SigninServiceException", 0, [], []]; + _s_registry3.registerError(SigninServiceException$, SigninServiceException); + n0_registry3 = TypeRegistry.for(n03); + AccessDeniedException$2 = [-3, n03, _ADE2, { [_e3]: _c3 }, [_e3, _m2], [0, 0], 2]; + n0_registry3.registerError(AccessDeniedException$2, AccessDeniedException2); + InternalServerException$2 = [-3, n03, _ISE2, { [_e3]: _se2, [_hE3]: 500 }, [_e3, _m2], [0, 0], 2]; + n0_registry3.registerError(InternalServerException$2, InternalServerException2); + TooManyRequestsError$ = [-3, n03, _TMRE2, { [_e3]: _c3, [_hE3]: 429 }, [_e3, _m2], [0, 0], 2]; + n0_registry3.registerError(TooManyRequestsError$, TooManyRequestsError); + ValidationException$ = [-3, n03, _VE, { [_e3]: _c3, [_hE3]: 400 }, [_e3, _m2], [0, 0], 2]; + n0_registry3.registerError(ValidationException$, ValidationException); + errorTypeRegistries3 = [_s_registry3, n0_registry3]; + RefreshToken2 = [0, n03, _RT2, 8, 0]; + AccessToken$ = [ + 3, + n03, + _AT2, + 8, + [_aKI2, _sAK2, _sT2], + [ + [0, { [_jN]: _aKI2 }], + [0, { [_jN]: _sAK2 }], + [0, { [_jN]: _sT2 }] + ], + 3 + ]; + CreateOAuth2TokenRequest$ = [ + 3, + n03, + _COATR, + 0, + [_tI], + [[() => CreateOAuth2TokenRequestBody$, 16]], + 1 + ]; + CreateOAuth2TokenRequestBody$ = [ + 3, + n03, + _COATRB, + 0, + [_cI2, _gT2, _co2, _rU2, _cV2, _rT2], + [ + [0, { [_jN]: _cI2 }], + [0, { [_jN]: _gT2 }], + 0, + [0, { [_jN]: _rU2 }], + [0, { [_jN]: _cV2 }], + [() => RefreshToken2, { [_jN]: _rT2 }] + ], + 2 + ]; + CreateOAuth2TokenResponse$ = [ + 3, + n03, + _COATRr, + 0, + [_tO], + [[() => CreateOAuth2TokenResponseBody$, 16]], + 1 + ]; + CreateOAuth2TokenResponseBody$ = [ + 3, + n03, + _COATRBr, + 0, + [_aT3, _tT2, _eI2, _rT2, _iT2], + [ + [() => AccessToken$, { [_jN]: _aT3 }], + [0, { [_jN]: _tT2 }], + [1, { [_jN]: _eI2 }], + [() => RefreshToken2, { [_jN]: _rT2 }], + [0, { [_jN]: _iT2 }] + ], + 4 + ]; + CreateOAuth2Token$ = [ + 9, + n03, + _COAT, + { [_h3]: ["POST", "/v1/token", 200] }, + () => CreateOAuth2TokenRequest$, + () => CreateOAuth2TokenResponse$ + ]; + } +}); + +// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/runtimeConfig.shared.js +var import_smithy_client23, import_url_parser4, import_util_base6410, import_util_utf810, getRuntimeConfig5; +var init_runtimeConfig_shared3 = __esm({ + "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/runtimeConfig.shared.js"() { + init_httpAuthSchemes2(); + init_protocols2(); + init_dist_es(); + import_smithy_client23 = __toESM(require_dist_cjs27()); + import_url_parser4 = __toESM(require_dist_cjs25()); + import_util_base6410 = __toESM(require_dist_cjs7()); + import_util_utf810 = __toESM(require_dist_cjs6()); + init_httpAuthSchemeProvider3(); + init_endpointResolver3(); + init_schemas_03(); + getRuntimeConfig5 = (config3) => { + return { + apiVersion: "2023-01-01", + base64Decoder: config3?.base64Decoder ?? import_util_base6410.fromBase64, + base64Encoder: config3?.base64Encoder ?? import_util_base6410.toBase64, + disableHostPrefix: config3?.disableHostPrefix ?? false, + endpointProvider: config3?.endpointProvider ?? defaultEndpointResolver3, + extensions: config3?.extensions ?? [], + httpAuthSchemeProvider: config3?.httpAuthSchemeProvider ?? defaultSigninHttpAuthSchemeProvider, + httpAuthSchemes: config3?.httpAuthSchemes ?? [ + { + schemeId: "aws.auth#sigv4", + identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"), + signer: new AwsSdkSigV4Signer() + }, + { + schemeId: "smithy.api#noAuth", + identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})), + signer: new NoAuthSigner() + } + ], + logger: config3?.logger ?? new import_smithy_client23.NoOpLogger(), + protocol: config3?.protocol ?? AwsRestJsonProtocol, + protocolSettings: config3?.protocolSettings ?? { + defaultNamespace: "com.amazonaws.signin", + errorTypeRegistries: errorTypeRegistries3, + version: "2023-01-01", + serviceTarget: "Signin" + }, + serviceId: config3?.serviceId ?? "Signin", + urlParser: config3?.urlParser ?? import_url_parser4.parseUrl, + utf8Decoder: config3?.utf8Decoder ?? import_util_utf810.fromUtf8, + utf8Encoder: config3?.utf8Encoder ?? import_util_utf810.toUtf8 + }; + }; + } +}); + +// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/runtimeConfig.js +var import_util_user_agent_node3, import_config_resolver5, import_hash_node3, import_middleware_retry5, import_node_config_provider3, import_node_http_handler3, import_smithy_client24, import_util_body_length_node3, import_util_defaults_mode_node3, import_util_retry3, getRuntimeConfig6; +var init_runtimeConfig3 = __esm({ + "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/runtimeConfig.js"() { + init_package(); + init_client2(); + init_httpAuthSchemes2(); + import_util_user_agent_node3 = __toESM(require_dist_cjs51()); + import_config_resolver5 = __toESM(require_dist_cjs38()); + import_hash_node3 = __toESM(require_dist_cjs52()); + import_middleware_retry5 = __toESM(require_dist_cjs46()); + import_node_config_provider3 = __toESM(require_dist_cjs43()); + import_node_http_handler3 = __toESM(require_dist_cjs10()); + import_smithy_client24 = __toESM(require_dist_cjs27()); + import_util_body_length_node3 = __toESM(require_dist_cjs53()); + import_util_defaults_mode_node3 = __toESM(require_dist_cjs54()); + import_util_retry3 = __toESM(require_dist_cjs36()); + init_runtimeConfig_shared3(); + getRuntimeConfig6 = (config3) => { + (0, import_smithy_client24.emitWarningIfUnsupportedVersion)(process.version); + const defaultsMode = (0, import_util_defaults_mode_node3.resolveDefaultsModeConfig)(config3); + const defaultConfigProvider = () => defaultsMode().then(import_smithy_client24.loadConfigsForDefaultMode); + const clientSharedValues = getRuntimeConfig5(config3); + emitWarningIfUnsupportedVersion(process.version); + const loaderConfig = { + profile: config3?.profile, + logger: clientSharedValues.logger + }; + return { + ...clientSharedValues, + ...config3, + runtime: "node", + defaultsMode, + authSchemePreference: config3?.authSchemePreference ?? (0, import_node_config_provider3.loadConfig)(NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig), + bodyLengthChecker: config3?.bodyLengthChecker ?? import_util_body_length_node3.calculateBodyLength, + defaultUserAgentProvider: config3?.defaultUserAgentProvider ?? (0, import_util_user_agent_node3.createDefaultUserAgentProvider)({ serviceId: clientSharedValues.serviceId, clientVersion: package_default.version }), + maxAttempts: config3?.maxAttempts ?? (0, import_node_config_provider3.loadConfig)(import_middleware_retry5.NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config3), + region: config3?.region ?? (0, import_node_config_provider3.loadConfig)(import_config_resolver5.NODE_REGION_CONFIG_OPTIONS, { ...import_config_resolver5.NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }), + requestHandler: import_node_http_handler3.NodeHttpHandler.create(config3?.requestHandler ?? defaultConfigProvider), + retryMode: config3?.retryMode ?? (0, import_node_config_provider3.loadConfig)({ + ...import_middleware_retry5.NODE_RETRY_MODE_CONFIG_OPTIONS, + default: async () => (await defaultConfigProvider()).retryMode || import_util_retry3.DEFAULT_RETRY_MODE + }, config3), + sha256: config3?.sha256 ?? import_hash_node3.Hash.bind(null, "sha256"), + streamCollector: config3?.streamCollector ?? import_node_http_handler3.streamCollector, + useDualstackEndpoint: config3?.useDualstackEndpoint ?? (0, import_node_config_provider3.loadConfig)(import_config_resolver5.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig), + useFipsEndpoint: config3?.useFipsEndpoint ?? (0, import_node_config_provider3.loadConfig)(import_config_resolver5.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig), + userAgentAppId: config3?.userAgentAppId ?? (0, import_node_config_provider3.loadConfig)(import_util_user_agent_node3.NODE_APP_ID_CONFIG_OPTIONS, loaderConfig) + }; + }; + } +}); + +// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/auth/httpAuthExtensionConfiguration.js +var getHttpAuthExtensionConfiguration3, resolveHttpAuthRuntimeConfig3; +var init_httpAuthExtensionConfiguration3 = __esm({ + "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/auth/httpAuthExtensionConfiguration.js"() { + getHttpAuthExtensionConfiguration3 = (runtimeConfig) => { + const _httpAuthSchemes = runtimeConfig.httpAuthSchemes; + let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider; + let _credentials = runtimeConfig.credentials; + return { + setHttpAuthScheme(httpAuthScheme) { + const index2 = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId); + if (index2 === -1) { + _httpAuthSchemes.push(httpAuthScheme); + } else { + _httpAuthSchemes.splice(index2, 1, httpAuthScheme); + } + }, + httpAuthSchemes() { + return _httpAuthSchemes; + }, + setHttpAuthSchemeProvider(httpAuthSchemeProvider) { + _httpAuthSchemeProvider = httpAuthSchemeProvider; + }, + httpAuthSchemeProvider() { + return _httpAuthSchemeProvider; + }, + setCredentials(credentials) { + _credentials = credentials; + }, + credentials() { + return _credentials; + } + }; + }; + resolveHttpAuthRuntimeConfig3 = (config3) => { + return { + httpAuthSchemes: config3.httpAuthSchemes(), + httpAuthSchemeProvider: config3.httpAuthSchemeProvider(), + credentials: config3.credentials() + }; + }; + } +}); + +// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/runtimeExtensions.js +var import_region_config_resolver3, import_protocol_http14, import_smithy_client25, resolveRuntimeExtensions3; +var init_runtimeExtensions3 = __esm({ + "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/runtimeExtensions.js"() { + import_region_config_resolver3 = __toESM(require_dist_cjs55()); + import_protocol_http14 = __toESM(require_dist_cjs2()); + import_smithy_client25 = __toESM(require_dist_cjs27()); + init_httpAuthExtensionConfiguration3(); + resolveRuntimeExtensions3 = (runtimeConfig, extensions) => { + const extensionConfiguration = Object.assign((0, import_region_config_resolver3.getAwsRegionExtensionConfiguration)(runtimeConfig), (0, import_smithy_client25.getDefaultExtensionConfiguration)(runtimeConfig), (0, import_protocol_http14.getHttpHandlerExtensionConfiguration)(runtimeConfig), getHttpAuthExtensionConfiguration3(runtimeConfig)); + extensions.forEach((extension2) => extension2.configure(extensionConfiguration)); + return Object.assign(runtimeConfig, (0, import_region_config_resolver3.resolveAwsRegionExtensionConfiguration)(extensionConfiguration), (0, import_smithy_client25.resolveDefaultRuntimeConfig)(extensionConfiguration), (0, import_protocol_http14.resolveHttpHandlerRuntimeConfig)(extensionConfiguration), resolveHttpAuthRuntimeConfig3(extensionConfiguration)); + }; + } +}); + +// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/SigninClient.js +var import_middleware_host_header3, import_middleware_logger3, import_middleware_recursion_detection3, import_middleware_user_agent3, import_config_resolver6, import_middleware_content_length3, import_middleware_endpoint5, import_middleware_retry6, import_smithy_client26, SigninClient; +var init_SigninClient = __esm({ + "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/SigninClient.js"() { + import_middleware_host_header3 = __toESM(require_dist_cjs20()); + import_middleware_logger3 = __toESM(require_dist_cjs21()); + import_middleware_recursion_detection3 = __toESM(require_dist_cjs22()); + import_middleware_user_agent3 = __toESM(require_dist_cjs37()); + import_config_resolver6 = __toESM(require_dist_cjs38()); + init_dist_es(); + init_schema3(); + import_middleware_content_length3 = __toESM(require_dist_cjs40()); + import_middleware_endpoint5 = __toESM(require_dist_cjs45()); + import_middleware_retry6 = __toESM(require_dist_cjs46()); + import_smithy_client26 = __toESM(require_dist_cjs27()); + init_httpAuthSchemeProvider3(); + init_EndpointParameters3(); + init_runtimeConfig3(); + init_runtimeExtensions3(); + SigninClient = class extends import_smithy_client26.Client { + config; + constructor(...[configuration]) { + const _config_0 = getRuntimeConfig6(configuration || {}); + super(_config_0); + this.initConfig = _config_0; + const _config_1 = resolveClientEndpointParameters3(_config_0); + const _config_2 = (0, import_middleware_user_agent3.resolveUserAgentConfig)(_config_1); + const _config_3 = (0, import_middleware_retry6.resolveRetryConfig)(_config_2); + const _config_4 = (0, import_config_resolver6.resolveRegionConfig)(_config_3); + const _config_5 = (0, import_middleware_host_header3.resolveHostHeaderConfig)(_config_4); + const _config_6 = (0, import_middleware_endpoint5.resolveEndpointConfig)(_config_5); + const _config_7 = resolveHttpAuthSchemeConfig3(_config_6); + const _config_8 = resolveRuntimeExtensions3(_config_7, configuration?.extensions || []); + this.config = _config_8; + this.middlewareStack.use(getSchemaSerdePlugin(this.config)); + this.middlewareStack.use((0, import_middleware_user_agent3.getUserAgentPlugin)(this.config)); + this.middlewareStack.use((0, import_middleware_retry6.getRetryPlugin)(this.config)); + this.middlewareStack.use((0, import_middleware_content_length3.getContentLengthPlugin)(this.config)); + this.middlewareStack.use((0, import_middleware_host_header3.getHostHeaderPlugin)(this.config)); + this.middlewareStack.use((0, import_middleware_logger3.getLoggerPlugin)(this.config)); + this.middlewareStack.use((0, import_middleware_recursion_detection3.getRecursionDetectionPlugin)(this.config)); + this.middlewareStack.use(getHttpAuthSchemeEndpointRuleSetPlugin(this.config, { + httpAuthSchemeParametersProvider: defaultSigninHttpAuthSchemeParametersProvider, + identityProviderConfigProvider: async (config3) => new DefaultIdentityProviderConfig({ + "aws.auth#sigv4": config3.credentials + }) + })); + this.middlewareStack.use(getHttpSigningPlugin(this.config)); + } + destroy() { + super.destroy(); + } + }; + } +}); + +// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/commands/CreateOAuth2TokenCommand.js +var import_middleware_endpoint6, import_smithy_client27, CreateOAuth2TokenCommand; +var init_CreateOAuth2TokenCommand = __esm({ + "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/commands/CreateOAuth2TokenCommand.js"() { + import_middleware_endpoint6 = __toESM(require_dist_cjs45()); + import_smithy_client27 = __toESM(require_dist_cjs27()); + init_EndpointParameters3(); + init_schemas_03(); + CreateOAuth2TokenCommand = class extends import_smithy_client27.Command.classBuilder().ep(commonParams3).m(function(Command2, cs, config3, o5) { + return [(0, import_middleware_endpoint6.getEndpointPlugin)(config3, Command2.getEndpointParameterInstructions())]; + }).s("Signin", "CreateOAuth2Token", {}).n("SigninClient", "CreateOAuth2TokenCommand").sc(CreateOAuth2Token$).build() { + }; + } +}); + +// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/Signin.js +var import_smithy_client28, commands3, Signin; +var init_Signin = __esm({ + "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/Signin.js"() { + import_smithy_client28 = __toESM(require_dist_cjs27()); + init_CreateOAuth2TokenCommand(); + init_SigninClient(); + commands3 = { + CreateOAuth2TokenCommand + }; + Signin = class extends SigninClient { + }; + (0, import_smithy_client28.createAggregatedClient)(commands3, Signin); + } +}); + +// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/commands/index.js +var init_commands3 = __esm({ + "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/commands/index.js"() { + init_CreateOAuth2TokenCommand(); + } +}); + +// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/models/enums.js +var OAuth2ErrorCode; +var init_enums2 = __esm({ + "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/models/enums.js"() { + OAuth2ErrorCode = { + AUTHCODE_EXPIRED: "AUTHCODE_EXPIRED", + INSUFFICIENT_PERMISSIONS: "INSUFFICIENT_PERMISSIONS", + INVALID_REQUEST: "INVALID_REQUEST", + SERVER_ERROR: "server_error", + TOKEN_EXPIRED: "TOKEN_EXPIRED", + USER_CREDENTIALS_CHANGED: "USER_CREDENTIALS_CHANGED" + }; + } +}); + +// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/models/models_0.js +var init_models_03 = __esm({ + "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/models/models_0.js"() { + } +}); + +// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/index.js +var signin_exports = {}; +__export(signin_exports, { + $Command: () => import_smithy_client27.Command, + AccessDeniedException: () => AccessDeniedException2, + AccessDeniedException$: () => AccessDeniedException$2, + AccessToken$: () => AccessToken$, + CreateOAuth2Token$: () => CreateOAuth2Token$, + CreateOAuth2TokenCommand: () => CreateOAuth2TokenCommand, + CreateOAuth2TokenRequest$: () => CreateOAuth2TokenRequest$, + CreateOAuth2TokenRequestBody$: () => CreateOAuth2TokenRequestBody$, + CreateOAuth2TokenResponse$: () => CreateOAuth2TokenResponse$, + CreateOAuth2TokenResponseBody$: () => CreateOAuth2TokenResponseBody$, + InternalServerException: () => InternalServerException2, + InternalServerException$: () => InternalServerException$2, + OAuth2ErrorCode: () => OAuth2ErrorCode, + Signin: () => Signin, + SigninClient: () => SigninClient, + SigninServiceException: () => SigninServiceException, + SigninServiceException$: () => SigninServiceException$, + TooManyRequestsError: () => TooManyRequestsError, + TooManyRequestsError$: () => TooManyRequestsError$, + ValidationException: () => ValidationException, + ValidationException$: () => ValidationException$, + __Client: () => import_smithy_client26.Client, + errorTypeRegistries: () => errorTypeRegistries3 +}); +var init_signin = __esm({ + "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/index.js"() { + init_SigninClient(); + init_Signin(); + init_commands3(); + init_schemas_03(); + init_enums2(); + init_errors5(); + init_models_03(); + init_SigninServiceException(); + } +}); + +// node_modules/.pnpm/@aws-sdk+credential-provider-login@3.972.29/node_modules/@aws-sdk/credential-provider-login/dist-cjs/index.js +var require_dist_cjs58 = __commonJS({ + "node_modules/.pnpm/@aws-sdk+credential-provider-login@3.972.29/node_modules/@aws-sdk/credential-provider-login/dist-cjs/index.js"(exports) { + "use strict"; + var client2 = (init_client2(), __toCommonJS(client_exports)); + var propertyProvider = require_dist_cjs41(); + var sharedIniFileLoader = require_dist_cjs42(); + var protocolHttp = require_dist_cjs2(); + var node_crypto = __require("node:crypto"); + var node_fs = __require("node:fs"); + var node_os = __require("node:os"); + var node_path = __require("node:path"); + var LoginCredentialsFetcher = class _LoginCredentialsFetcher { + profileData; + init; + callerClientConfig; + static REFRESH_THRESHOLD = 5 * 60 * 1e3; + constructor(profileData, init2, callerClientConfig) { + this.profileData = profileData; + this.init = init2; + this.callerClientConfig = callerClientConfig; + } + async loadCredentials() { + const token = await this.loadToken(); + if (!token) { + throw new propertyProvider.CredentialsProviderError(`Failed to load a token for session ${this.loginSession}, please re-authenticate using aws login`, { tryNextLink: false, logger: this.logger }); + } + const accessToken = token.accessToken; + const now2 = Date.now(); + const expiryTime = new Date(accessToken.expiresAt).getTime(); + const timeUntilExpiry = expiryTime - now2; + if (timeUntilExpiry <= _LoginCredentialsFetcher.REFRESH_THRESHOLD) { + return this.refresh(token); + } + return { + accessKeyId: accessToken.accessKeyId, + secretAccessKey: accessToken.secretAccessKey, + sessionToken: accessToken.sessionToken, + accountId: accessToken.accountId, + expiration: new Date(accessToken.expiresAt) + }; + } + get logger() { + return this.init?.logger; + } + get loginSession() { + return this.profileData.login_session; + } + async refresh(token) { + const { SigninClient: SigninClient2, CreateOAuth2TokenCommand: CreateOAuth2TokenCommand2 } = await Promise.resolve().then(() => (init_signin(), signin_exports)); + const { logger: logger4, userAgentAppId } = this.callerClientConfig ?? {}; + const isH22 = (requestHandler2) => { + return requestHandler2?.metadata?.handlerProtocol === "h2"; + }; + const requestHandler = isH22(this.callerClientConfig?.requestHandler) ? void 0 : this.callerClientConfig?.requestHandler; + const region = this.profileData.region ?? await this.callerClientConfig?.region?.() ?? process.env.AWS_REGION; + const client3 = new SigninClient2({ + credentials: { + accessKeyId: "", + secretAccessKey: "" + }, + region, + requestHandler, + logger: logger4, + userAgentAppId, + ...this.init?.clientConfig + }); + this.createDPoPInterceptor(client3.middlewareStack); + const commandInput = { + tokenInput: { + clientId: token.clientId, + refreshToken: token.refreshToken, + grantType: "refresh_token" + } + }; + try { + const response = await client3.send(new CreateOAuth2TokenCommand2(commandInput)); + const { accessKeyId, secretAccessKey, sessionToken } = response.tokenOutput?.accessToken ?? {}; + const { refreshToken: refreshToken2, expiresIn } = response.tokenOutput ?? {}; + if (!accessKeyId || !secretAccessKey || !sessionToken || !refreshToken2) { + throw new propertyProvider.CredentialsProviderError("Token refresh response missing required fields", { + logger: this.logger, + tryNextLink: false + }); + } + const expiresInMs = (expiresIn ?? 900) * 1e3; + const expiration = new Date(Date.now() + expiresInMs); + const updatedToken = { + ...token, + accessToken: { + ...token.accessToken, + accessKeyId, + secretAccessKey, + sessionToken, + expiresAt: expiration.toISOString() + }, + refreshToken: refreshToken2 + }; + await this.saveToken(updatedToken); + const newAccessToken = updatedToken.accessToken; + return { + accessKeyId: newAccessToken.accessKeyId, + secretAccessKey: newAccessToken.secretAccessKey, + sessionToken: newAccessToken.sessionToken, + accountId: newAccessToken.accountId, + expiration + }; + } catch (error50) { + if (error50.name === "AccessDeniedException") { + const errorType = error50.error; + let message2; + switch (errorType) { + case "TOKEN_EXPIRED": + message2 = "Your session has expired. Please reauthenticate."; + break; + case "USER_CREDENTIALS_CHANGED": + message2 = "Unable to refresh credentials because of a change in your password. Please reauthenticate with your new password."; + break; + case "INSUFFICIENT_PERMISSIONS": + message2 = "Unable to refresh credentials due to insufficient permissions. You may be missing permission for the 'CreateOAuth2Token' action."; + break; + default: + message2 = `Failed to refresh token: ${String(error50)}. Please re-authenticate using \`aws login\``; + } + throw new propertyProvider.CredentialsProviderError(message2, { logger: this.logger, tryNextLink: false }); + } + throw new propertyProvider.CredentialsProviderError(`Failed to refresh token: ${String(error50)}. Please re-authenticate using aws login`, { logger: this.logger }); + } + } + async loadToken() { + const tokenFilePath = this.getTokenFilePath(); + try { + let tokenData; + try { + tokenData = await sharedIniFileLoader.readFile(tokenFilePath, { ignoreCache: this.init?.ignoreCache }); + } catch { + tokenData = await node_fs.promises.readFile(tokenFilePath, "utf8"); + } + const token = JSON.parse(tokenData); + const missingFields = ["accessToken", "clientId", "refreshToken", "dpopKey"].filter((k5) => !token[k5]); + if (!token.accessToken?.accountId) { + missingFields.push("accountId"); + } + if (missingFields.length > 0) { + throw new propertyProvider.CredentialsProviderError(`Token validation failed, missing fields: ${missingFields.join(", ")}`, { + logger: this.logger, + tryNextLink: false + }); + } + return token; + } catch (error50) { + throw new propertyProvider.CredentialsProviderError(`Failed to load token from ${tokenFilePath}: ${String(error50)}`, { + logger: this.logger, + tryNextLink: false + }); + } + } + async saveToken(token) { + const tokenFilePath = this.getTokenFilePath(); + const directory = node_path.dirname(tokenFilePath); + try { + await node_fs.promises.mkdir(directory, { recursive: true }); + } catch (error50) { + } + await node_fs.promises.writeFile(tokenFilePath, JSON.stringify(token, null, 2), "utf8"); + } + getTokenFilePath() { + const directory = process.env.AWS_LOGIN_CACHE_DIRECTORY ?? node_path.join(node_os.homedir(), ".aws", "login", "cache"); + const loginSessionBytes = Buffer.from(this.loginSession, "utf8"); + const loginSessionSha256 = node_crypto.createHash("sha256").update(loginSessionBytes).digest("hex"); + return node_path.join(directory, `${loginSessionSha256}.json`); + } + derToRawSignature(derSignature) { + let offset = 2; + if (derSignature[offset] !== 2) { + throw new Error("Invalid DER signature"); + } + offset++; + const rLength = derSignature[offset++]; + let r5 = derSignature.subarray(offset, offset + rLength); + offset += rLength; + if (derSignature[offset] !== 2) { + throw new Error("Invalid DER signature"); + } + offset++; + const sLength = derSignature[offset++]; + let s5 = derSignature.subarray(offset, offset + sLength); + r5 = r5[0] === 0 ? r5.subarray(1) : r5; + s5 = s5[0] === 0 ? s5.subarray(1) : s5; + const rPadded = Buffer.concat([Buffer.alloc(32 - r5.length), r5]); + const sPadded = Buffer.concat([Buffer.alloc(32 - s5.length), s5]); + return Buffer.concat([rPadded, sPadded]); + } + createDPoPInterceptor(middlewareStack) { + middlewareStack.add((next) => async (args) => { + if (protocolHttp.HttpRequest.isInstance(args.request)) { + const request = args.request; + const actualEndpoint = `${request.protocol}//${request.hostname}${request.port ? `:${request.port}` : ""}${request.path}`; + const dpop = await this.generateDpop(request.method, actualEndpoint); + request.headers = { + ...request.headers, + DPoP: dpop + }; + } + return next(args); + }, { + step: "finalizeRequest", + name: "dpopInterceptor", + override: true + }); + } + async generateDpop(method = "POST", endpoint) { + const token = await this.loadToken(); + try { + const privateKey = node_crypto.createPrivateKey({ + key: token.dpopKey, + format: "pem", + type: "sec1" + }); + const publicKey = node_crypto.createPublicKey(privateKey); + const publicDer = publicKey.export({ format: "der", type: "spki" }); + let pointStart = -1; + for (let i5 = 0; i5 < publicDer.length; i5++) { + if (publicDer[i5] === 4) { + pointStart = i5; + break; + } + } + const x5 = publicDer.slice(pointStart + 1, pointStart + 33); + const y2 = publicDer.slice(pointStart + 33, pointStart + 65); + const header = { + alg: "ES256", + typ: "dpop+jwt", + jwk: { + kty: "EC", + crv: "P-256", + x: x5.toString("base64url"), + y: y2.toString("base64url") + } + }; + const payload2 = { + jti: crypto.randomUUID(), + htm: method, + htu: endpoint, + iat: Math.floor(Date.now() / 1e3) + }; + const headerB64 = Buffer.from(JSON.stringify(header)).toString("base64url"); + const payloadB64 = Buffer.from(JSON.stringify(payload2)).toString("base64url"); + const message2 = `${headerB64}.${payloadB64}`; + const asn1Signature = node_crypto.sign("sha256", Buffer.from(message2), privateKey); + const rawSignature = this.derToRawSignature(asn1Signature); + const signatureB64 = rawSignature.toString("base64url"); + return `${message2}.${signatureB64}`; + } catch (error50) { + throw new propertyProvider.CredentialsProviderError(`Failed to generate Dpop proof: ${error50 instanceof Error ? error50.message : String(error50)}`, { logger: this.logger, tryNextLink: false }); + } + } + }; + var fromLoginCredentials = (init2) => async ({ callerClientConfig } = {}) => { + init2?.logger?.debug?.("@aws-sdk/credential-providers - fromLoginCredentials"); + const profiles = await sharedIniFileLoader.parseKnownFiles(init2 || {}); + const profileName = sharedIniFileLoader.getProfileName({ + profile: init2?.profile ?? callerClientConfig?.profile + }); + const profile = profiles[profileName]; + if (!profile?.login_session) { + throw new propertyProvider.CredentialsProviderError(`Profile ${profileName} does not contain login_session.`, { + tryNextLink: true, + logger: init2?.logger + }); + } + const fetcher = new LoginCredentialsFetcher(profile, init2, callerClientConfig); + const credentials = await fetcher.loadCredentials(); + return client2.setCredentialFeature(credentials, "CREDENTIALS_LOGIN", "AD"); + }; + exports.fromLoginCredentials = fromLoginCredentials; + } +}); + +// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/auth/httpAuthSchemeProvider.js +function createAwsAuthSigv4HttpAuthOption4(authParameters) { + return { + schemeId: "aws.auth#sigv4", + signingProperties: { + name: "sts", + region: authParameters.region + }, + propertiesExtractor: (config3, context) => ({ + signingProperties: { + config: config3, + context + } + }) + }; +} +function createSmithyApiNoAuthHttpAuthOption4(authParameters) { + return { + schemeId: "smithy.api#noAuth" + }; +} +var import_util_middleware9, defaultSTSHttpAuthSchemeParametersProvider, defaultSTSHttpAuthSchemeProvider, resolveStsAuthConfig, resolveHttpAuthSchemeConfig4; +var init_httpAuthSchemeProvider4 = __esm({ + "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/auth/httpAuthSchemeProvider.js"() { + init_httpAuthSchemes2(); + import_util_middleware9 = __toESM(require_dist_cjs18()); + init_STSClient(); + defaultSTSHttpAuthSchemeParametersProvider = async (config3, context, input) => { + return { + operation: (0, import_util_middleware9.getSmithyContext)(context).operation, + region: await (0, import_util_middleware9.normalizeProvider)(config3.region)() || (() => { + throw new Error("expected `region` to be configured for `aws.auth#sigv4`"); + })() + }; + }; + defaultSTSHttpAuthSchemeProvider = (authParameters) => { + const options = []; + switch (authParameters.operation) { + case "AssumeRoleWithWebIdentity": { + options.push(createSmithyApiNoAuthHttpAuthOption4(authParameters)); + break; + } + default: { + options.push(createAwsAuthSigv4HttpAuthOption4(authParameters)); + } + } + return options; + }; + resolveStsAuthConfig = (input) => Object.assign(input, { + stsClientCtor: STSClient + }); + resolveHttpAuthSchemeConfig4 = (config3) => { + const config_0 = resolveStsAuthConfig(config3); + const config_1 = resolveAwsSdkSigV4Config(config_0); + return Object.assign(config_1, { + authSchemePreference: (0, import_util_middleware9.normalizeProvider)(config3.authSchemePreference ?? []) + }); + }; + } +}); + +// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/endpoint/EndpointParameters.js +var resolveClientEndpointParameters4, commonParams4; +var init_EndpointParameters4 = __esm({ + "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/endpoint/EndpointParameters.js"() { + resolveClientEndpointParameters4 = (options) => { + return Object.assign(options, { + useDualstackEndpoint: options.useDualstackEndpoint ?? false, + useFipsEndpoint: options.useFipsEndpoint ?? false, + useGlobalEndpoint: options.useGlobalEndpoint ?? false, + defaultSigningName: "sts" + }); + }; + commonParams4 = { + UseGlobalEndpoint: { type: "builtInParams", name: "useGlobalEndpoint" }, + UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, + Endpoint: { type: "builtInParams", name: "endpoint" }, + Region: { type: "builtInParams", name: "region" }, + UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" } + }; + } +}); + +// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/endpoint/ruleset.js +var F, G, H, I, J, a4, b5, c4, d4, e4, f4, g4, h4, i4, j4, k4, l4, m4, n4, o4, p4, q4, r4, s4, t4, u4, v4, w4, x4, y, z, A, B, C, D, E, _data4, ruleSet4; +var init_ruleset4 = __esm({ + "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/endpoint/ruleset.js"() { + F = "required"; + G = "type"; + H = "fn"; + I = "argv"; + J = "ref"; + a4 = false; + b5 = true; + c4 = "booleanEquals"; + d4 = "stringEquals"; + e4 = "sigv4"; + f4 = "sts"; + g4 = "us-east-1"; + h4 = "endpoint"; + i4 = "https://sts.{Region}.{PartitionResult#dnsSuffix}"; + j4 = "tree"; + k4 = "error"; + l4 = "getAttr"; + m4 = { [F]: false, [G]: "string" }; + n4 = { [F]: true, default: false, [G]: "boolean" }; + o4 = { [J]: "Endpoint" }; + p4 = { [H]: "isSet", [I]: [{ [J]: "Region" }] }; + q4 = { [J]: "Region" }; + r4 = { [H]: "aws.partition", [I]: [q4], assign: "PartitionResult" }; + s4 = { [J]: "UseFIPS" }; + t4 = { [J]: "UseDualStack" }; + u4 = { + url: "https://sts.amazonaws.com", + properties: { authSchemes: [{ name: e4, signingName: f4, signingRegion: g4 }] }, + headers: {} + }; + v4 = {}; + w4 = { conditions: [{ [H]: d4, [I]: [q4, "aws-global"] }], [h4]: u4, [G]: h4 }; + x4 = { [H]: c4, [I]: [s4, true] }; + y = { [H]: c4, [I]: [t4, true] }; + z = { [H]: l4, [I]: [{ [J]: "PartitionResult" }, "supportsFIPS"] }; + A = { [J]: "PartitionResult" }; + B = { [H]: c4, [I]: [true, { [H]: l4, [I]: [A, "supportsDualStack"] }] }; + C = [{ [H]: "isSet", [I]: [o4] }]; + D = [x4]; + E = [y]; + _data4 = { + version: "1.0", + parameters: { Region: m4, UseDualStack: n4, UseFIPS: n4, Endpoint: m4, UseGlobalEndpoint: n4 }, + rules: [ + { + conditions: [ + { [H]: c4, [I]: [{ [J]: "UseGlobalEndpoint" }, b5] }, + { [H]: "not", [I]: C }, + p4, + r4, + { [H]: c4, [I]: [s4, a4] }, + { [H]: c4, [I]: [t4, a4] } + ], + rules: [ + { conditions: [{ [H]: d4, [I]: [q4, "ap-northeast-1"] }], endpoint: u4, [G]: h4 }, + { conditions: [{ [H]: d4, [I]: [q4, "ap-south-1"] }], endpoint: u4, [G]: h4 }, + { conditions: [{ [H]: d4, [I]: [q4, "ap-southeast-1"] }], endpoint: u4, [G]: h4 }, + { conditions: [{ [H]: d4, [I]: [q4, "ap-southeast-2"] }], endpoint: u4, [G]: h4 }, + w4, + { conditions: [{ [H]: d4, [I]: [q4, "ca-central-1"] }], endpoint: u4, [G]: h4 }, + { conditions: [{ [H]: d4, [I]: [q4, "eu-central-1"] }], endpoint: u4, [G]: h4 }, + { conditions: [{ [H]: d4, [I]: [q4, "eu-north-1"] }], endpoint: u4, [G]: h4 }, + { conditions: [{ [H]: d4, [I]: [q4, "eu-west-1"] }], endpoint: u4, [G]: h4 }, + { conditions: [{ [H]: d4, [I]: [q4, "eu-west-2"] }], endpoint: u4, [G]: h4 }, + { conditions: [{ [H]: d4, [I]: [q4, "eu-west-3"] }], endpoint: u4, [G]: h4 }, + { conditions: [{ [H]: d4, [I]: [q4, "sa-east-1"] }], endpoint: u4, [G]: h4 }, + { conditions: [{ [H]: d4, [I]: [q4, g4] }], endpoint: u4, [G]: h4 }, + { conditions: [{ [H]: d4, [I]: [q4, "us-east-2"] }], endpoint: u4, [G]: h4 }, + { conditions: [{ [H]: d4, [I]: [q4, "us-west-1"] }], endpoint: u4, [G]: h4 }, + { conditions: [{ [H]: d4, [I]: [q4, "us-west-2"] }], endpoint: u4, [G]: h4 }, + { + endpoint: { + url: i4, + properties: { authSchemes: [{ name: e4, signingName: f4, signingRegion: "{Region}" }] }, + headers: v4 + }, + [G]: h4 + } + ], + [G]: j4 + }, + { + conditions: C, + rules: [ + { conditions: D, error: "Invalid Configuration: FIPS and custom endpoint are not supported", [G]: k4 }, + { conditions: E, error: "Invalid Configuration: Dualstack and custom endpoint are not supported", [G]: k4 }, + { endpoint: { url: o4, properties: v4, headers: v4 }, [G]: h4 } + ], + [G]: j4 + }, + { + conditions: [p4], + rules: [ + { + conditions: [r4], + rules: [ + { + conditions: [x4, y], + rules: [ + { + conditions: [{ [H]: c4, [I]: [b5, z] }, B], + rules: [ + { + endpoint: { + url: "https://sts-fips.{Region}.{PartitionResult#dualStackDnsSuffix}", + properties: v4, + headers: v4 + }, + [G]: h4 + } + ], + [G]: j4 + }, + { error: "FIPS and DualStack are enabled, but this partition does not support one or both", [G]: k4 } + ], + [G]: j4 + }, + { + conditions: D, + rules: [ + { + conditions: [{ [H]: c4, [I]: [z, b5] }], + rules: [ + { + conditions: [{ [H]: d4, [I]: [{ [H]: l4, [I]: [A, "name"] }, "aws-us-gov"] }], + endpoint: { url: "https://sts.{Region}.amazonaws.com", properties: v4, headers: v4 }, + [G]: h4 + }, + { + endpoint: { + url: "https://sts-fips.{Region}.{PartitionResult#dnsSuffix}", + properties: v4, + headers: v4 + }, + [G]: h4 + } + ], + [G]: j4 + }, + { error: "FIPS is enabled but this partition does not support FIPS", [G]: k4 } + ], + [G]: j4 + }, + { + conditions: E, + rules: [ + { + conditions: [B], + rules: [ + { + endpoint: { + url: "https://sts.{Region}.{PartitionResult#dualStackDnsSuffix}", + properties: v4, + headers: v4 + }, + [G]: h4 + } + ], + [G]: j4 + }, + { error: "DualStack is enabled but this partition does not support DualStack", [G]: k4 } + ], + [G]: j4 + }, + w4, + { endpoint: { url: i4, properties: v4, headers: v4 }, [G]: h4 } + ], + [G]: j4 + } + ], + [G]: j4 + }, + { error: "Invalid Configuration: Missing Region", [G]: k4 } + ] + }; + ruleSet4 = _data4; + } +}); + +// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/endpoint/endpointResolver.js +var import_util_endpoints7, import_util_endpoints8, cache4, defaultEndpointResolver4; +var init_endpointResolver4 = __esm({ + "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/endpoint/endpointResolver.js"() { + import_util_endpoints7 = __toESM(require_dist_cjs34()); + import_util_endpoints8 = __toESM(require_dist_cjs33()); + init_ruleset4(); + cache4 = new import_util_endpoints8.EndpointCache({ + size: 50, + params: ["Endpoint", "Region", "UseDualStack", "UseFIPS", "UseGlobalEndpoint"] + }); + defaultEndpointResolver4 = (endpointParams, context = {}) => { + return cache4.get(endpointParams, () => (0, import_util_endpoints8.resolveEndpoint)(ruleSet4, { + endpointParams, + logger: context.logger + })); + }; + import_util_endpoints8.customEndpointFunctions.aws = import_util_endpoints7.awsEndpointFunctions; + } +}); + +// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/models/STSServiceException.js +var import_smithy_client29, STSServiceException; +var init_STSServiceException = __esm({ + "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/models/STSServiceException.js"() { + import_smithy_client29 = __toESM(require_dist_cjs27()); + STSServiceException = class _STSServiceException extends import_smithy_client29.ServiceException { + constructor(options) { + super(options); + Object.setPrototypeOf(this, _STSServiceException.prototype); + } + }; + } +}); + +// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/models/errors.js +var ExpiredTokenException2, MalformedPolicyDocumentException, PackedPolicyTooLargeException, RegionDisabledException, IDPRejectedClaimException, InvalidIdentityTokenException, IDPCommunicationErrorException; +var init_errors6 = __esm({ + "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/models/errors.js"() { + init_STSServiceException(); + ExpiredTokenException2 = class _ExpiredTokenException extends STSServiceException { + name = "ExpiredTokenException"; + $fault = "client"; + constructor(opts) { + super({ + name: "ExpiredTokenException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _ExpiredTokenException.prototype); + } + }; + MalformedPolicyDocumentException = class _MalformedPolicyDocumentException extends STSServiceException { + name = "MalformedPolicyDocumentException"; + $fault = "client"; + constructor(opts) { + super({ + name: "MalformedPolicyDocumentException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _MalformedPolicyDocumentException.prototype); + } + }; + PackedPolicyTooLargeException = class _PackedPolicyTooLargeException extends STSServiceException { + name = "PackedPolicyTooLargeException"; + $fault = "client"; + constructor(opts) { + super({ + name: "PackedPolicyTooLargeException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _PackedPolicyTooLargeException.prototype); + } + }; + RegionDisabledException = class _RegionDisabledException extends STSServiceException { + name = "RegionDisabledException"; + $fault = "client"; + constructor(opts) { + super({ + name: "RegionDisabledException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _RegionDisabledException.prototype); + } + }; + IDPRejectedClaimException = class _IDPRejectedClaimException extends STSServiceException { + name = "IDPRejectedClaimException"; + $fault = "client"; + constructor(opts) { + super({ + name: "IDPRejectedClaimException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _IDPRejectedClaimException.prototype); + } + }; + InvalidIdentityTokenException = class _InvalidIdentityTokenException extends STSServiceException { + name = "InvalidIdentityTokenException"; + $fault = "client"; + constructor(opts) { + super({ + name: "InvalidIdentityTokenException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _InvalidIdentityTokenException.prototype); + } + }; + IDPCommunicationErrorException = class _IDPCommunicationErrorException extends STSServiceException { + name = "IDPCommunicationErrorException"; + $fault = "client"; + constructor(opts) { + super({ + name: "IDPCommunicationErrorException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _IDPCommunicationErrorException.prototype); + } + }; + } +}); + +// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/schemas/schemas_0.js +var _A, _AKI, _AR, _ARI, _ARR, _ARRs, _ARU, _ARWWI, _ARWWIR, _ARWWIRs, _Au, _C, _CA, _DS, _E, _EI, _ETE2, _IDPCEE, _IDPRCE, _IITE, _K, _MPDE, _P, _PA, _PAr, _PC, _PCLT, _PCr, _PDT, _PI, _PPS, _PPTLE, _Pr, _RA, _RDE, _RSN, _SAK, _SFWIT, _SI, _SN, _ST, _T, _TC, _TTK, _Ta, _V, _WIT, _a, _aKST, _aQE, _c4, _cTT, _e4, _hE4, _m3, _pDLT, _s4, _tLT, n04, _s_registry4, STSServiceException$, n0_registry4, ExpiredTokenException$2, IDPCommunicationErrorException$, IDPRejectedClaimException$, InvalidIdentityTokenException$, MalformedPolicyDocumentException$, PackedPolicyTooLargeException$, RegionDisabledException$, errorTypeRegistries4, accessKeySecretType, clientTokenType, AssumedRoleUser$, AssumeRoleRequest$, AssumeRoleResponse$, AssumeRoleWithWebIdentityRequest$, AssumeRoleWithWebIdentityResponse$, Credentials$, PolicyDescriptorType$, ProvidedContext$, Tag$, policyDescriptorListType, ProvidedContextsListType, tagKeyListType, tagListType, AssumeRole$, AssumeRoleWithWebIdentity$; +var init_schemas_04 = __esm({ + "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/schemas/schemas_0.js"() { + init_schema3(); + init_errors6(); + init_STSServiceException(); + _A = "Arn"; + _AKI = "AccessKeyId"; + _AR = "AssumeRole"; + _ARI = "AssumedRoleId"; + _ARR = "AssumeRoleRequest"; + _ARRs = "AssumeRoleResponse"; + _ARU = "AssumedRoleUser"; + _ARWWI = "AssumeRoleWithWebIdentity"; + _ARWWIR = "AssumeRoleWithWebIdentityRequest"; + _ARWWIRs = "AssumeRoleWithWebIdentityResponse"; + _Au = "Audience"; + _C = "Credentials"; + _CA = "ContextAssertion"; + _DS = "DurationSeconds"; + _E = "Expiration"; + _EI = "ExternalId"; + _ETE2 = "ExpiredTokenException"; + _IDPCEE = "IDPCommunicationErrorException"; + _IDPRCE = "IDPRejectedClaimException"; + _IITE = "InvalidIdentityTokenException"; + _K = "Key"; + _MPDE = "MalformedPolicyDocumentException"; + _P = "Policy"; + _PA = "PolicyArns"; + _PAr = "ProviderArn"; + _PC = "ProvidedContexts"; + _PCLT = "ProvidedContextsListType"; + _PCr = "ProvidedContext"; + _PDT = "PolicyDescriptorType"; + _PI = "ProviderId"; + _PPS = "PackedPolicySize"; + _PPTLE = "PackedPolicyTooLargeException"; + _Pr = "Provider"; + _RA = "RoleArn"; + _RDE = "RegionDisabledException"; + _RSN = "RoleSessionName"; + _SAK = "SecretAccessKey"; + _SFWIT = "SubjectFromWebIdentityToken"; + _SI = "SourceIdentity"; + _SN = "SerialNumber"; + _ST = "SessionToken"; + _T = "Tags"; + _TC = "TokenCode"; + _TTK = "TransitiveTagKeys"; + _Ta = "Tag"; + _V = "Value"; + _WIT = "WebIdentityToken"; + _a = "arn"; + _aKST = "accessKeySecretType"; + _aQE = "awsQueryError"; + _c4 = "client"; + _cTT = "clientTokenType"; + _e4 = "error"; + _hE4 = "httpError"; + _m3 = "message"; + _pDLT = "policyDescriptorListType"; + _s4 = "smithy.ts.sdk.synthetic.com.amazonaws.sts"; + _tLT = "tagListType"; + n04 = "com.amazonaws.sts"; + _s_registry4 = TypeRegistry.for(_s4); + STSServiceException$ = [-3, _s4, "STSServiceException", 0, [], []]; + _s_registry4.registerError(STSServiceException$, STSServiceException); + n0_registry4 = TypeRegistry.for(n04); + ExpiredTokenException$2 = [ + -3, + n04, + _ETE2, + { [_aQE]: [`ExpiredTokenException`, 400], [_e4]: _c4, [_hE4]: 400 }, + [_m3], + [0] + ]; + n0_registry4.registerError(ExpiredTokenException$2, ExpiredTokenException2); + IDPCommunicationErrorException$ = [ + -3, + n04, + _IDPCEE, + { [_aQE]: [`IDPCommunicationError`, 400], [_e4]: _c4, [_hE4]: 400 }, + [_m3], + [0] + ]; + n0_registry4.registerError(IDPCommunicationErrorException$, IDPCommunicationErrorException); + IDPRejectedClaimException$ = [ + -3, + n04, + _IDPRCE, + { [_aQE]: [`IDPRejectedClaim`, 403], [_e4]: _c4, [_hE4]: 403 }, + [_m3], + [0] + ]; + n0_registry4.registerError(IDPRejectedClaimException$, IDPRejectedClaimException); + InvalidIdentityTokenException$ = [ + -3, + n04, + _IITE, + { [_aQE]: [`InvalidIdentityToken`, 400], [_e4]: _c4, [_hE4]: 400 }, + [_m3], + [0] + ]; + n0_registry4.registerError(InvalidIdentityTokenException$, InvalidIdentityTokenException); + MalformedPolicyDocumentException$ = [ + -3, + n04, + _MPDE, + { [_aQE]: [`MalformedPolicyDocument`, 400], [_e4]: _c4, [_hE4]: 400 }, + [_m3], + [0] + ]; + n0_registry4.registerError(MalformedPolicyDocumentException$, MalformedPolicyDocumentException); + PackedPolicyTooLargeException$ = [ + -3, + n04, + _PPTLE, + { [_aQE]: [`PackedPolicyTooLarge`, 400], [_e4]: _c4, [_hE4]: 400 }, + [_m3], + [0] + ]; + n0_registry4.registerError(PackedPolicyTooLargeException$, PackedPolicyTooLargeException); + RegionDisabledException$ = [ + -3, + n04, + _RDE, + { [_aQE]: [`RegionDisabledException`, 403], [_e4]: _c4, [_hE4]: 403 }, + [_m3], + [0] + ]; + n0_registry4.registerError(RegionDisabledException$, RegionDisabledException); + errorTypeRegistries4 = [_s_registry4, n0_registry4]; + accessKeySecretType = [0, n04, _aKST, 8, 0]; + clientTokenType = [0, n04, _cTT, 8, 0]; + AssumedRoleUser$ = [3, n04, _ARU, 0, [_ARI, _A], [0, 0], 2]; + AssumeRoleRequest$ = [ + 3, + n04, + _ARR, + 0, + [_RA, _RSN, _PA, _P, _DS, _T, _TTK, _EI, _SN, _TC, _SI, _PC], + [0, 0, () => policyDescriptorListType, 0, 1, () => tagListType, 64 | 0, 0, 0, 0, 0, () => ProvidedContextsListType], + 2 + ]; + AssumeRoleResponse$ = [ + 3, + n04, + _ARRs, + 0, + [_C, _ARU, _PPS, _SI], + [[() => Credentials$, 0], () => AssumedRoleUser$, 1, 0] + ]; + AssumeRoleWithWebIdentityRequest$ = [ + 3, + n04, + _ARWWIR, + 0, + [_RA, _RSN, _WIT, _PI, _PA, _P, _DS], + [0, 0, [() => clientTokenType, 0], 0, () => policyDescriptorListType, 0, 1], + 3 + ]; + AssumeRoleWithWebIdentityResponse$ = [ + 3, + n04, + _ARWWIRs, + 0, + [_C, _SFWIT, _ARU, _PPS, _Pr, _Au, _SI], + [[() => Credentials$, 0], 0, () => AssumedRoleUser$, 1, 0, 0, 0] + ]; + Credentials$ = [ + 3, + n04, + _C, + 0, + [_AKI, _SAK, _ST, _E], + [0, [() => accessKeySecretType, 0], 0, 4], + 4 + ]; + PolicyDescriptorType$ = [3, n04, _PDT, 0, [_a], [0]]; + ProvidedContext$ = [3, n04, _PCr, 0, [_PAr, _CA], [0, 0]]; + Tag$ = [3, n04, _Ta, 0, [_K, _V], [0, 0], 2]; + policyDescriptorListType = [1, n04, _pDLT, 0, () => PolicyDescriptorType$]; + ProvidedContextsListType = [1, n04, _PCLT, 0, () => ProvidedContext$]; + tagKeyListType = 64 | 0; + tagListType = [1, n04, _tLT, 0, () => Tag$]; + AssumeRole$ = [9, n04, _AR, 0, () => AssumeRoleRequest$, () => AssumeRoleResponse$]; + AssumeRoleWithWebIdentity$ = [ + 9, + n04, + _ARWWI, + 0, + () => AssumeRoleWithWebIdentityRequest$, + () => AssumeRoleWithWebIdentityResponse$ + ]; + } +}); + +// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/runtimeConfig.shared.js +var import_smithy_client30, import_url_parser5, import_util_base6411, import_util_utf811, getRuntimeConfig7; +var init_runtimeConfig_shared4 = __esm({ + "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/runtimeConfig.shared.js"() { + init_httpAuthSchemes2(); + init_protocols2(); + init_dist_es(); + import_smithy_client30 = __toESM(require_dist_cjs27()); + import_url_parser5 = __toESM(require_dist_cjs25()); + import_util_base6411 = __toESM(require_dist_cjs7()); + import_util_utf811 = __toESM(require_dist_cjs6()); + init_httpAuthSchemeProvider4(); + init_endpointResolver4(); + init_schemas_04(); + getRuntimeConfig7 = (config3) => { + return { + apiVersion: "2011-06-15", + base64Decoder: config3?.base64Decoder ?? import_util_base6411.fromBase64, + base64Encoder: config3?.base64Encoder ?? import_util_base6411.toBase64, + disableHostPrefix: config3?.disableHostPrefix ?? false, + endpointProvider: config3?.endpointProvider ?? defaultEndpointResolver4, + extensions: config3?.extensions ?? [], + httpAuthSchemeProvider: config3?.httpAuthSchemeProvider ?? defaultSTSHttpAuthSchemeProvider, + httpAuthSchemes: config3?.httpAuthSchemes ?? [ + { + schemeId: "aws.auth#sigv4", + identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"), + signer: new AwsSdkSigV4Signer() + }, + { + schemeId: "smithy.api#noAuth", + identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})), + signer: new NoAuthSigner() + } + ], + logger: config3?.logger ?? new import_smithy_client30.NoOpLogger(), + protocol: config3?.protocol ?? AwsQueryProtocol, + protocolSettings: config3?.protocolSettings ?? { + defaultNamespace: "com.amazonaws.sts", + errorTypeRegistries: errorTypeRegistries4, + xmlNamespace: "https://sts.amazonaws.com/doc/2011-06-15/", + version: "2011-06-15", + serviceTarget: "AWSSecurityTokenServiceV20110615" + }, + serviceId: config3?.serviceId ?? "STS", + urlParser: config3?.urlParser ?? import_url_parser5.parseUrl, + utf8Decoder: config3?.utf8Decoder ?? import_util_utf811.fromUtf8, + utf8Encoder: config3?.utf8Encoder ?? import_util_utf811.toUtf8 + }; + }; + } +}); + +// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/runtimeConfig.js +var import_util_user_agent_node4, import_config_resolver7, import_hash_node4, import_middleware_retry7, import_node_config_provider4, import_node_http_handler4, import_smithy_client31, import_util_body_length_node4, import_util_defaults_mode_node4, import_util_retry4, getRuntimeConfig8; +var init_runtimeConfig4 = __esm({ + "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/runtimeConfig.js"() { + init_package(); + init_client2(); + init_httpAuthSchemes2(); + import_util_user_agent_node4 = __toESM(require_dist_cjs51()); + import_config_resolver7 = __toESM(require_dist_cjs38()); + init_dist_es(); + import_hash_node4 = __toESM(require_dist_cjs52()); + import_middleware_retry7 = __toESM(require_dist_cjs46()); + import_node_config_provider4 = __toESM(require_dist_cjs43()); + import_node_http_handler4 = __toESM(require_dist_cjs10()); + import_smithy_client31 = __toESM(require_dist_cjs27()); + import_util_body_length_node4 = __toESM(require_dist_cjs53()); + import_util_defaults_mode_node4 = __toESM(require_dist_cjs54()); + import_util_retry4 = __toESM(require_dist_cjs36()); + init_runtimeConfig_shared4(); + getRuntimeConfig8 = (config3) => { + (0, import_smithy_client31.emitWarningIfUnsupportedVersion)(process.version); + const defaultsMode = (0, import_util_defaults_mode_node4.resolveDefaultsModeConfig)(config3); + const defaultConfigProvider = () => defaultsMode().then(import_smithy_client31.loadConfigsForDefaultMode); + const clientSharedValues = getRuntimeConfig7(config3); + emitWarningIfUnsupportedVersion(process.version); + const loaderConfig = { + profile: config3?.profile, + logger: clientSharedValues.logger + }; + return { + ...clientSharedValues, + ...config3, + runtime: "node", + defaultsMode, + authSchemePreference: config3?.authSchemePreference ?? (0, import_node_config_provider4.loadConfig)(NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig), + bodyLengthChecker: config3?.bodyLengthChecker ?? import_util_body_length_node4.calculateBodyLength, + defaultUserAgentProvider: config3?.defaultUserAgentProvider ?? (0, import_util_user_agent_node4.createDefaultUserAgentProvider)({ serviceId: clientSharedValues.serviceId, clientVersion: package_default.version }), + httpAuthSchemes: config3?.httpAuthSchemes ?? [ + { + schemeId: "aws.auth#sigv4", + identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4") || (async (idProps) => await config3.credentialDefaultProvider(idProps?.__config || {})()), + signer: new AwsSdkSigV4Signer() + }, + { + schemeId: "smithy.api#noAuth", + identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})), + signer: new NoAuthSigner() + } + ], + maxAttempts: config3?.maxAttempts ?? (0, import_node_config_provider4.loadConfig)(import_middleware_retry7.NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config3), + region: config3?.region ?? (0, import_node_config_provider4.loadConfig)(import_config_resolver7.NODE_REGION_CONFIG_OPTIONS, { ...import_config_resolver7.NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }), + requestHandler: import_node_http_handler4.NodeHttpHandler.create(config3?.requestHandler ?? defaultConfigProvider), + retryMode: config3?.retryMode ?? (0, import_node_config_provider4.loadConfig)({ + ...import_middleware_retry7.NODE_RETRY_MODE_CONFIG_OPTIONS, + default: async () => (await defaultConfigProvider()).retryMode || import_util_retry4.DEFAULT_RETRY_MODE + }, config3), + sha256: config3?.sha256 ?? import_hash_node4.Hash.bind(null, "sha256"), + streamCollector: config3?.streamCollector ?? import_node_http_handler4.streamCollector, + useDualstackEndpoint: config3?.useDualstackEndpoint ?? (0, import_node_config_provider4.loadConfig)(import_config_resolver7.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig), + useFipsEndpoint: config3?.useFipsEndpoint ?? (0, import_node_config_provider4.loadConfig)(import_config_resolver7.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig), + userAgentAppId: config3?.userAgentAppId ?? (0, import_node_config_provider4.loadConfig)(import_util_user_agent_node4.NODE_APP_ID_CONFIG_OPTIONS, loaderConfig) + }; + }; + } +}); + +// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/auth/httpAuthExtensionConfiguration.js +var getHttpAuthExtensionConfiguration4, resolveHttpAuthRuntimeConfig4; +var init_httpAuthExtensionConfiguration4 = __esm({ + "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/auth/httpAuthExtensionConfiguration.js"() { + getHttpAuthExtensionConfiguration4 = (runtimeConfig) => { + const _httpAuthSchemes = runtimeConfig.httpAuthSchemes; + let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider; + let _credentials = runtimeConfig.credentials; + return { + setHttpAuthScheme(httpAuthScheme) { + const index2 = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId); + if (index2 === -1) { + _httpAuthSchemes.push(httpAuthScheme); + } else { + _httpAuthSchemes.splice(index2, 1, httpAuthScheme); + } + }, + httpAuthSchemes() { + return _httpAuthSchemes; + }, + setHttpAuthSchemeProvider(httpAuthSchemeProvider) { + _httpAuthSchemeProvider = httpAuthSchemeProvider; + }, + httpAuthSchemeProvider() { + return _httpAuthSchemeProvider; + }, + setCredentials(credentials) { + _credentials = credentials; + }, + credentials() { + return _credentials; + } + }; + }; + resolveHttpAuthRuntimeConfig4 = (config3) => { + return { + httpAuthSchemes: config3.httpAuthSchemes(), + httpAuthSchemeProvider: config3.httpAuthSchemeProvider(), + credentials: config3.credentials() + }; + }; + } +}); + +// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/runtimeExtensions.js +var import_region_config_resolver4, import_protocol_http15, import_smithy_client32, resolveRuntimeExtensions4; +var init_runtimeExtensions4 = __esm({ + "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/runtimeExtensions.js"() { + import_region_config_resolver4 = __toESM(require_dist_cjs55()); + import_protocol_http15 = __toESM(require_dist_cjs2()); + import_smithy_client32 = __toESM(require_dist_cjs27()); + init_httpAuthExtensionConfiguration4(); + resolveRuntimeExtensions4 = (runtimeConfig, extensions) => { + const extensionConfiguration = Object.assign((0, import_region_config_resolver4.getAwsRegionExtensionConfiguration)(runtimeConfig), (0, import_smithy_client32.getDefaultExtensionConfiguration)(runtimeConfig), (0, import_protocol_http15.getHttpHandlerExtensionConfiguration)(runtimeConfig), getHttpAuthExtensionConfiguration4(runtimeConfig)); + extensions.forEach((extension2) => extension2.configure(extensionConfiguration)); + return Object.assign(runtimeConfig, (0, import_region_config_resolver4.resolveAwsRegionExtensionConfiguration)(extensionConfiguration), (0, import_smithy_client32.resolveDefaultRuntimeConfig)(extensionConfiguration), (0, import_protocol_http15.resolveHttpHandlerRuntimeConfig)(extensionConfiguration), resolveHttpAuthRuntimeConfig4(extensionConfiguration)); + }; + } +}); + +// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/STSClient.js +var import_middleware_host_header4, import_middleware_logger4, import_middleware_recursion_detection4, import_middleware_user_agent4, import_config_resolver8, import_middleware_content_length4, import_middleware_endpoint7, import_middleware_retry8, import_smithy_client33, STSClient; +var init_STSClient = __esm({ + "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/STSClient.js"() { + import_middleware_host_header4 = __toESM(require_dist_cjs20()); + import_middleware_logger4 = __toESM(require_dist_cjs21()); + import_middleware_recursion_detection4 = __toESM(require_dist_cjs22()); + import_middleware_user_agent4 = __toESM(require_dist_cjs37()); + import_config_resolver8 = __toESM(require_dist_cjs38()); + init_dist_es(); + init_schema3(); + import_middleware_content_length4 = __toESM(require_dist_cjs40()); + import_middleware_endpoint7 = __toESM(require_dist_cjs45()); + import_middleware_retry8 = __toESM(require_dist_cjs46()); + import_smithy_client33 = __toESM(require_dist_cjs27()); + init_httpAuthSchemeProvider4(); + init_EndpointParameters4(); + init_runtimeConfig4(); + init_runtimeExtensions4(); + STSClient = class extends import_smithy_client33.Client { + config; + constructor(...[configuration]) { + const _config_0 = getRuntimeConfig8(configuration || {}); + super(_config_0); + this.initConfig = _config_0; + const _config_1 = resolveClientEndpointParameters4(_config_0); + const _config_2 = (0, import_middleware_user_agent4.resolveUserAgentConfig)(_config_1); + const _config_3 = (0, import_middleware_retry8.resolveRetryConfig)(_config_2); + const _config_4 = (0, import_config_resolver8.resolveRegionConfig)(_config_3); + const _config_5 = (0, import_middleware_host_header4.resolveHostHeaderConfig)(_config_4); + const _config_6 = (0, import_middleware_endpoint7.resolveEndpointConfig)(_config_5); + const _config_7 = resolveHttpAuthSchemeConfig4(_config_6); + const _config_8 = resolveRuntimeExtensions4(_config_7, configuration?.extensions || []); + this.config = _config_8; + this.middlewareStack.use(getSchemaSerdePlugin(this.config)); + this.middlewareStack.use((0, import_middleware_user_agent4.getUserAgentPlugin)(this.config)); + this.middlewareStack.use((0, import_middleware_retry8.getRetryPlugin)(this.config)); + this.middlewareStack.use((0, import_middleware_content_length4.getContentLengthPlugin)(this.config)); + this.middlewareStack.use((0, import_middleware_host_header4.getHostHeaderPlugin)(this.config)); + this.middlewareStack.use((0, import_middleware_logger4.getLoggerPlugin)(this.config)); + this.middlewareStack.use((0, import_middleware_recursion_detection4.getRecursionDetectionPlugin)(this.config)); + this.middlewareStack.use(getHttpAuthSchemeEndpointRuleSetPlugin(this.config, { + httpAuthSchemeParametersProvider: defaultSTSHttpAuthSchemeParametersProvider, + identityProviderConfigProvider: async (config3) => new DefaultIdentityProviderConfig({ + "aws.auth#sigv4": config3.credentials + }) + })); + this.middlewareStack.use(getHttpSigningPlugin(this.config)); + } + destroy() { + super.destroy(); + } + }; + } +}); + +// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/commands/AssumeRoleCommand.js +var import_middleware_endpoint8, import_smithy_client34, AssumeRoleCommand; +var init_AssumeRoleCommand = __esm({ + "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/commands/AssumeRoleCommand.js"() { + import_middleware_endpoint8 = __toESM(require_dist_cjs45()); + import_smithy_client34 = __toESM(require_dist_cjs27()); + init_EndpointParameters4(); + init_schemas_04(); + AssumeRoleCommand = class extends import_smithy_client34.Command.classBuilder().ep(commonParams4).m(function(Command2, cs, config3, o5) { + return [(0, import_middleware_endpoint8.getEndpointPlugin)(config3, Command2.getEndpointParameterInstructions())]; + }).s("AWSSecurityTokenServiceV20110615", "AssumeRole", {}).n("STSClient", "AssumeRoleCommand").sc(AssumeRole$).build() { + }; + } +}); + +// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/commands/AssumeRoleWithWebIdentityCommand.js +var import_middleware_endpoint9, import_smithy_client35, AssumeRoleWithWebIdentityCommand; +var init_AssumeRoleWithWebIdentityCommand = __esm({ + "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/commands/AssumeRoleWithWebIdentityCommand.js"() { + import_middleware_endpoint9 = __toESM(require_dist_cjs45()); + import_smithy_client35 = __toESM(require_dist_cjs27()); + init_EndpointParameters4(); + init_schemas_04(); + AssumeRoleWithWebIdentityCommand = class extends import_smithy_client35.Command.classBuilder().ep(commonParams4).m(function(Command2, cs, config3, o5) { + return [(0, import_middleware_endpoint9.getEndpointPlugin)(config3, Command2.getEndpointParameterInstructions())]; + }).s("AWSSecurityTokenServiceV20110615", "AssumeRoleWithWebIdentity", {}).n("STSClient", "AssumeRoleWithWebIdentityCommand").sc(AssumeRoleWithWebIdentity$).build() { + }; + } +}); + +// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/STS.js +var import_smithy_client36, commands4, STS; +var init_STS = __esm({ + "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/STS.js"() { + import_smithy_client36 = __toESM(require_dist_cjs27()); + init_AssumeRoleCommand(); + init_AssumeRoleWithWebIdentityCommand(); + init_STSClient(); + commands4 = { + AssumeRoleCommand, + AssumeRoleWithWebIdentityCommand + }; + STS = class extends STSClient { + }; + (0, import_smithy_client36.createAggregatedClient)(commands4, STS); + } +}); + +// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/commands/index.js +var init_commands4 = __esm({ + "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/commands/index.js"() { + init_AssumeRoleCommand(); + init_AssumeRoleWithWebIdentityCommand(); + } +}); + +// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/models/models_0.js +var init_models_04 = __esm({ + "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/models/models_0.js"() { + } +}); + +// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/defaultStsRoleAssumers.js +var import_region_config_resolver5, getAccountIdFromAssumedRoleUser, resolveRegion, getDefaultRoleAssumer, getDefaultRoleAssumerWithWebIdentity, isH2; +var init_defaultStsRoleAssumers = __esm({ + "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/defaultStsRoleAssumers.js"() { + init_client2(); + import_region_config_resolver5 = __toESM(require_dist_cjs55()); + init_AssumeRoleCommand(); + init_AssumeRoleWithWebIdentityCommand(); + getAccountIdFromAssumedRoleUser = (assumedRoleUser) => { + if (typeof assumedRoleUser?.Arn === "string") { + const arnComponents = assumedRoleUser.Arn.split(":"); + if (arnComponents.length > 4 && arnComponents[4] !== "") { + return arnComponents[4]; + } + } + return void 0; + }; + resolveRegion = async (_region, _parentRegion, credentialProviderLogger, loaderConfig = {}) => { + const region = typeof _region === "function" ? await _region() : _region; + const parentRegion = typeof _parentRegion === "function" ? await _parentRegion() : _parentRegion; + let stsDefaultRegion = ""; + const resolvedRegion = region ?? parentRegion ?? (stsDefaultRegion = await (0, import_region_config_resolver5.stsRegionDefaultResolver)(loaderConfig)()); + credentialProviderLogger?.debug?.("@aws-sdk/client-sts::resolveRegion", "accepting first of:", `${region} (credential provider clientConfig)`, `${parentRegion} (contextual client)`, `${stsDefaultRegion} (STS default: AWS_REGION, profile region, or us-east-1)`); + return resolvedRegion; + }; + getDefaultRoleAssumer = (stsOptions, STSClient2) => { + let stsClient; + let closureSourceCreds; + return async (sourceCreds, params) => { + closureSourceCreds = sourceCreds; + if (!stsClient) { + const { logger: logger4 = stsOptions?.parentClientConfig?.logger, profile = stsOptions?.parentClientConfig?.profile, region, requestHandler = stsOptions?.parentClientConfig?.requestHandler, credentialProviderLogger, userAgentAppId = stsOptions?.parentClientConfig?.userAgentAppId } = stsOptions; + const resolvedRegion = await resolveRegion(region, stsOptions?.parentClientConfig?.region, credentialProviderLogger, { + logger: logger4, + profile + }); + const isCompatibleRequestHandler = !isH2(requestHandler); + stsClient = new STSClient2({ + ...stsOptions, + userAgentAppId, + profile, + credentialDefaultProvider: () => async () => closureSourceCreds, + region: resolvedRegion, + requestHandler: isCompatibleRequestHandler ? requestHandler : void 0, + logger: logger4 + }); + } + const { Credentials, AssumedRoleUser } = await stsClient.send(new AssumeRoleCommand(params)); + if (!Credentials || !Credentials.AccessKeyId || !Credentials.SecretAccessKey) { + throw new Error(`Invalid response from STS.assumeRole call with role ${params.RoleArn}`); + } + const accountId = getAccountIdFromAssumedRoleUser(AssumedRoleUser); + const credentials = { + accessKeyId: Credentials.AccessKeyId, + secretAccessKey: Credentials.SecretAccessKey, + sessionToken: Credentials.SessionToken, + expiration: Credentials.Expiration, + ...Credentials.CredentialScope && { credentialScope: Credentials.CredentialScope }, + ...accountId && { accountId } + }; + setCredentialFeature(credentials, "CREDENTIALS_STS_ASSUME_ROLE", "i"); + return credentials; + }; + }; + getDefaultRoleAssumerWithWebIdentity = (stsOptions, STSClient2) => { + let stsClient; + return async (params) => { + if (!stsClient) { + const { logger: logger4 = stsOptions?.parentClientConfig?.logger, profile = stsOptions?.parentClientConfig?.profile, region, requestHandler = stsOptions?.parentClientConfig?.requestHandler, credentialProviderLogger, userAgentAppId = stsOptions?.parentClientConfig?.userAgentAppId } = stsOptions; + const resolvedRegion = await resolveRegion(region, stsOptions?.parentClientConfig?.region, credentialProviderLogger, { + logger: logger4, + profile + }); + const isCompatibleRequestHandler = !isH2(requestHandler); + stsClient = new STSClient2({ + ...stsOptions, + userAgentAppId, + profile, + region: resolvedRegion, + requestHandler: isCompatibleRequestHandler ? requestHandler : void 0, + logger: logger4 + }); + } + const { Credentials, AssumedRoleUser } = await stsClient.send(new AssumeRoleWithWebIdentityCommand(params)); + if (!Credentials || !Credentials.AccessKeyId || !Credentials.SecretAccessKey) { + throw new Error(`Invalid response from STS.assumeRoleWithWebIdentity call with role ${params.RoleArn}`); + } + const accountId = getAccountIdFromAssumedRoleUser(AssumedRoleUser); + const credentials = { + accessKeyId: Credentials.AccessKeyId, + secretAccessKey: Credentials.SecretAccessKey, + sessionToken: Credentials.SessionToken, + expiration: Credentials.Expiration, + ...Credentials.CredentialScope && { credentialScope: Credentials.CredentialScope }, + ...accountId && { accountId } + }; + if (accountId) { + setCredentialFeature(credentials, "RESOLVED_ACCOUNT_ID", "T"); + } + setCredentialFeature(credentials, "CREDENTIALS_STS_ASSUME_ROLE_WEB_ID", "k"); + return credentials; + }; + }; + isH2 = (requestHandler) => { + return requestHandler?.metadata?.handlerProtocol === "h2"; + }; + } +}); + +// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/defaultRoleAssumers.js +var getCustomizableStsClientCtor, getDefaultRoleAssumer2, getDefaultRoleAssumerWithWebIdentity2, decorateDefaultCredentialProvider; +var init_defaultRoleAssumers = __esm({ + "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/defaultRoleAssumers.js"() { + init_defaultStsRoleAssumers(); + init_STSClient(); + getCustomizableStsClientCtor = (baseCtor, customizations) => { + if (!customizations) + return baseCtor; + else + return class CustomizableSTSClient extends baseCtor { + constructor(config3) { + super(config3); + for (const customization of customizations) { + this.middlewareStack.use(customization); + } + } + }; + }; + getDefaultRoleAssumer2 = (stsOptions = {}, stsPlugins) => getDefaultRoleAssumer(stsOptions, getCustomizableStsClientCtor(STSClient, stsPlugins)); + getDefaultRoleAssumerWithWebIdentity2 = (stsOptions = {}, stsPlugins) => getDefaultRoleAssumerWithWebIdentity(stsOptions, getCustomizableStsClientCtor(STSClient, stsPlugins)); + decorateDefaultCredentialProvider = (provider) => (input) => provider({ + roleAssumer: getDefaultRoleAssumer2(input), + roleAssumerWithWebIdentity: getDefaultRoleAssumerWithWebIdentity2(input), + ...input + }); + } +}); + +// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/index.js +var sts_exports = {}; +__export(sts_exports, { + AssumeRole$: () => AssumeRole$, + AssumeRoleCommand: () => AssumeRoleCommand, + AssumeRoleRequest$: () => AssumeRoleRequest$, + AssumeRoleResponse$: () => AssumeRoleResponse$, + AssumeRoleWithWebIdentity$: () => AssumeRoleWithWebIdentity$, + AssumeRoleWithWebIdentityCommand: () => AssumeRoleWithWebIdentityCommand, + AssumeRoleWithWebIdentityRequest$: () => AssumeRoleWithWebIdentityRequest$, + AssumeRoleWithWebIdentityResponse$: () => AssumeRoleWithWebIdentityResponse$, + AssumedRoleUser$: () => AssumedRoleUser$, + Credentials$: () => Credentials$, + ExpiredTokenException: () => ExpiredTokenException2, + ExpiredTokenException$: () => ExpiredTokenException$2, + IDPCommunicationErrorException: () => IDPCommunicationErrorException, + IDPCommunicationErrorException$: () => IDPCommunicationErrorException$, + IDPRejectedClaimException: () => IDPRejectedClaimException, + IDPRejectedClaimException$: () => IDPRejectedClaimException$, + InvalidIdentityTokenException: () => InvalidIdentityTokenException, + InvalidIdentityTokenException$: () => InvalidIdentityTokenException$, + MalformedPolicyDocumentException: () => MalformedPolicyDocumentException, + MalformedPolicyDocumentException$: () => MalformedPolicyDocumentException$, + PackedPolicyTooLargeException: () => PackedPolicyTooLargeException, + PackedPolicyTooLargeException$: () => PackedPolicyTooLargeException$, + PolicyDescriptorType$: () => PolicyDescriptorType$, + ProvidedContext$: () => ProvidedContext$, + RegionDisabledException: () => RegionDisabledException, + RegionDisabledException$: () => RegionDisabledException$, + STS: () => STS, + STSClient: () => STSClient, + STSServiceException: () => STSServiceException, + STSServiceException$: () => STSServiceException$, + Tag$: () => Tag$, + __Client: () => import_smithy_client33.Client, + decorateDefaultCredentialProvider: () => decorateDefaultCredentialProvider, + errorTypeRegistries: () => errorTypeRegistries4, + getDefaultRoleAssumer: () => getDefaultRoleAssumer2, + getDefaultRoleAssumerWithWebIdentity: () => getDefaultRoleAssumerWithWebIdentity2 +}); +var init_sts = __esm({ + "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/index.js"() { + init_STSClient(); + init_STS(); + init_commands4(); + init_schemas_04(); + init_errors6(); + init_models_04(); + init_defaultRoleAssumers(); + init_STSServiceException(); + } +}); + +// node_modules/.pnpm/@aws-sdk+credential-provider-process@3.972.25/node_modules/@aws-sdk/credential-provider-process/dist-cjs/index.js +var require_dist_cjs59 = __commonJS({ + "node_modules/.pnpm/@aws-sdk+credential-provider-process@3.972.25/node_modules/@aws-sdk/credential-provider-process/dist-cjs/index.js"(exports) { + "use strict"; + var sharedIniFileLoader = require_dist_cjs42(); + var propertyProvider = require_dist_cjs41(); + var node_child_process = __require("node:child_process"); + var node_util = __require("node:util"); + var client2 = (init_client2(), __toCommonJS(client_exports)); + var getValidatedProcessCredentials = (profileName, data2, profiles) => { + if (data2.Version !== 1) { + throw Error(`Profile ${profileName} credential_process did not return Version 1.`); + } + if (data2.AccessKeyId === void 0 || data2.SecretAccessKey === void 0) { + throw Error(`Profile ${profileName} credential_process returned invalid credentials.`); + } + if (data2.Expiration) { + const currentTime = /* @__PURE__ */ new Date(); + const expireTime = new Date(data2.Expiration); + if (expireTime < currentTime) { + throw Error(`Profile ${profileName} credential_process returned expired credentials.`); + } + } + let accountId = data2.AccountId; + if (!accountId && profiles?.[profileName]?.aws_account_id) { + accountId = profiles[profileName].aws_account_id; + } + const credentials = { + accessKeyId: data2.AccessKeyId, + secretAccessKey: data2.SecretAccessKey, + ...data2.SessionToken && { sessionToken: data2.SessionToken }, + ...data2.Expiration && { expiration: new Date(data2.Expiration) }, + ...data2.CredentialScope && { credentialScope: data2.CredentialScope }, + ...accountId && { accountId } + }; + client2.setCredentialFeature(credentials, "CREDENTIALS_PROCESS", "w"); + return credentials; + }; + var resolveProcessCredentials = async (profileName, profiles, logger4) => { + const profile = profiles[profileName]; + if (profiles[profileName]) { + const credentialProcess = profile["credential_process"]; + if (credentialProcess !== void 0) { + const execPromise = node_util.promisify(sharedIniFileLoader.externalDataInterceptor?.getTokenRecord?.().exec ?? node_child_process.exec); + try { + const { stdout } = await execPromise(credentialProcess); + let data2; + try { + data2 = JSON.parse(stdout.trim()); + } catch { + throw Error(`Profile ${profileName} credential_process returned invalid JSON.`); + } + return getValidatedProcessCredentials(profileName, data2, profiles); + } catch (error50) { + throw new propertyProvider.CredentialsProviderError(error50.message, { logger: logger4 }); + } + } else { + throw new propertyProvider.CredentialsProviderError(`Profile ${profileName} did not contain credential_process.`, { logger: logger4 }); + } + } else { + throw new propertyProvider.CredentialsProviderError(`Profile ${profileName} could not be found in shared credentials file.`, { + logger: logger4 + }); + } + }; + var fromProcess = (init2 = {}) => async ({ callerClientConfig } = {}) => { + init2.logger?.debug("@aws-sdk/credential-provider-process - fromProcess"); + const profiles = await sharedIniFileLoader.parseKnownFiles(init2); + return resolveProcessCredentials(sharedIniFileLoader.getProfileName({ + profile: init2.profile ?? callerClientConfig?.profile + }), profiles, init2.logger); + }; + exports.fromProcess = fromProcess; + } +}); + +// node_modules/.pnpm/@aws-sdk+credential-provider-web-identity@3.972.29/node_modules/@aws-sdk/credential-provider-web-identity/dist-cjs/fromWebToken.js +var require_fromWebToken = __commonJS({ + "node_modules/.pnpm/@aws-sdk+credential-provider-web-identity@3.972.29/node_modules/@aws-sdk/credential-provider-web-identity/dist-cjs/fromWebToken.js"(exports) { + "use strict"; + var __createBinding2 = exports && exports.__createBinding || (Object.create ? (function(o5, m5, k5, k22) { + if (k22 === void 0) k22 = k5; + var desc3 = Object.getOwnPropertyDescriptor(m5, k5); + if (!desc3 || ("get" in desc3 ? !m5.__esModule : desc3.writable || desc3.configurable)) { + desc3 = { enumerable: true, get: function() { + return m5[k5]; + } }; + } + Object.defineProperty(o5, k22, desc3); + }) : (function(o5, m5, k5, k22) { + if (k22 === void 0) k22 = k5; + o5[k22] = m5[k5]; + })); + var __setModuleDefault2 = exports && exports.__setModuleDefault || (Object.create ? (function(o5, v5) { + Object.defineProperty(o5, "default", { enumerable: true, value: v5 }); + }) : function(o5, v5) { + o5["default"] = v5; + }); + var __importStar2 = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys2 = function(o5) { + ownKeys2 = Object.getOwnPropertyNames || function(o6) { + var ar = []; + for (var k5 in o6) if (Object.prototype.hasOwnProperty.call(o6, k5)) ar[ar.length] = k5; + return ar; + }; + return ownKeys2(o5); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k5 = ownKeys2(mod), i5 = 0; i5 < k5.length; i5++) if (k5[i5] !== "default") __createBinding2(result, mod, k5[i5]); + } + __setModuleDefault2(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.fromWebToken = void 0; + var fromWebToken = (init2) => async (awsIdentityProperties) => { + init2.logger?.debug("@aws-sdk/credential-provider-web-identity - fromWebToken"); + const { roleArn, roleSessionName, webIdentityToken, providerId, policyArns, policy, durationSeconds } = init2; + let { roleAssumerWithWebIdentity } = init2; + if (!roleAssumerWithWebIdentity) { + const { getDefaultRoleAssumerWithWebIdentity: getDefaultRoleAssumerWithWebIdentity3 } = await Promise.resolve().then(() => __importStar2((init_sts(), __toCommonJS(sts_exports)))); + roleAssumerWithWebIdentity = getDefaultRoleAssumerWithWebIdentity3({ + ...init2.clientConfig, + credentialProviderLogger: init2.logger, + parentClientConfig: { + ...awsIdentityProperties?.callerClientConfig, + ...init2.parentClientConfig + } + }, init2.clientPlugins); + } + return roleAssumerWithWebIdentity({ + RoleArn: roleArn, + RoleSessionName: roleSessionName ?? `aws-sdk-js-session-${Date.now()}`, + WebIdentityToken: webIdentityToken, + ProviderId: providerId, + PolicyArns: policyArns, + Policy: policy, + DurationSeconds: durationSeconds + }); + }; + exports.fromWebToken = fromWebToken; + } +}); + +// node_modules/.pnpm/@aws-sdk+credential-provider-web-identity@3.972.29/node_modules/@aws-sdk/credential-provider-web-identity/dist-cjs/fromTokenFile.js +var require_fromTokenFile = __commonJS({ + "node_modules/.pnpm/@aws-sdk+credential-provider-web-identity@3.972.29/node_modules/@aws-sdk/credential-provider-web-identity/dist-cjs/fromTokenFile.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.fromTokenFile = void 0; + var client_1 = (init_client2(), __toCommonJS(client_exports)); + var property_provider_1 = require_dist_cjs41(); + var shared_ini_file_loader_1 = require_dist_cjs42(); + var node_fs_1 = __require("node:fs"); + var fromWebToken_1 = require_fromWebToken(); + var ENV_TOKEN_FILE = "AWS_WEB_IDENTITY_TOKEN_FILE"; + var ENV_ROLE_ARN = "AWS_ROLE_ARN"; + var ENV_ROLE_SESSION_NAME = "AWS_ROLE_SESSION_NAME"; + var fromTokenFile = (init2 = {}) => async (awsIdentityProperties) => { + init2.logger?.debug("@aws-sdk/credential-provider-web-identity - fromTokenFile"); + const webIdentityTokenFile = init2?.webIdentityTokenFile ?? process.env[ENV_TOKEN_FILE]; + const roleArn = init2?.roleArn ?? process.env[ENV_ROLE_ARN]; + const roleSessionName = init2?.roleSessionName ?? process.env[ENV_ROLE_SESSION_NAME]; + if (!webIdentityTokenFile || !roleArn) { + throw new property_provider_1.CredentialsProviderError("Web identity configuration not specified", { + logger: init2.logger + }); + } + const credentials = await (0, fromWebToken_1.fromWebToken)({ + ...init2, + webIdentityToken: shared_ini_file_loader_1.externalDataInterceptor?.getTokenRecord?.()[webIdentityTokenFile] ?? (0, node_fs_1.readFileSync)(webIdentityTokenFile, { encoding: "ascii" }), + roleArn, + roleSessionName + })(awsIdentityProperties); + if (webIdentityTokenFile === process.env[ENV_TOKEN_FILE]) { + (0, client_1.setCredentialFeature)(credentials, "CREDENTIALS_ENV_VARS_STS_WEB_ID_TOKEN", "h"); + } + return credentials; + }; + exports.fromTokenFile = fromTokenFile; + } +}); + +// node_modules/.pnpm/@aws-sdk+credential-provider-web-identity@3.972.29/node_modules/@aws-sdk/credential-provider-web-identity/dist-cjs/index.js +var require_dist_cjs60 = __commonJS({ + "node_modules/.pnpm/@aws-sdk+credential-provider-web-identity@3.972.29/node_modules/@aws-sdk/credential-provider-web-identity/dist-cjs/index.js"(exports) { + "use strict"; + var fromTokenFile = require_fromTokenFile(); + var fromWebToken = require_fromWebToken(); + Object.prototype.hasOwnProperty.call(fromTokenFile, "__proto__") && !Object.prototype.hasOwnProperty.call(exports, "__proto__") && Object.defineProperty(exports, "__proto__", { + enumerable: true, + value: fromTokenFile["__proto__"] + }); + Object.keys(fromTokenFile).forEach(function(k5) { + if (k5 !== "default" && !Object.prototype.hasOwnProperty.call(exports, k5)) exports[k5] = fromTokenFile[k5]; + }); + Object.prototype.hasOwnProperty.call(fromWebToken, "__proto__") && !Object.prototype.hasOwnProperty.call(exports, "__proto__") && Object.defineProperty(exports, "__proto__", { + enumerable: true, + value: fromWebToken["__proto__"] + }); + Object.keys(fromWebToken).forEach(function(k5) { + if (k5 !== "default" && !Object.prototype.hasOwnProperty.call(exports, k5)) exports[k5] = fromWebToken[k5]; + }); + } +}); + +// node_modules/.pnpm/@aws-sdk+credential-provider-ini@3.972.29/node_modules/@aws-sdk/credential-provider-ini/dist-cjs/index.js +var require_dist_cjs61 = __commonJS({ + "node_modules/.pnpm/@aws-sdk+credential-provider-ini@3.972.29/node_modules/@aws-sdk/credential-provider-ini/dist-cjs/index.js"(exports) { + "use strict"; + var sharedIniFileLoader = require_dist_cjs42(); + var propertyProvider = require_dist_cjs41(); + var client2 = (init_client2(), __toCommonJS(client_exports)); + var credentialProviderLogin = require_dist_cjs58(); + var resolveCredentialSource = (credentialSource, profileName, logger4) => { + const sourceProvidersMap = { + EcsContainer: async (options) => { + const { fromHttp } = await Promise.resolve().then(() => __toESM(require_dist_cjs50())); + const { fromContainerMetadata } = await Promise.resolve().then(() => __toESM(require_dist_cjs49())); + logger4?.debug("@aws-sdk/credential-provider-ini - credential_source is EcsContainer"); + return async () => propertyProvider.chain(fromHttp(options ?? {}), fromContainerMetadata(options))().then(setNamedProvider); + }, + Ec2InstanceMetadata: async (options) => { + logger4?.debug("@aws-sdk/credential-provider-ini - credential_source is Ec2InstanceMetadata"); + const { fromInstanceMetadata } = await Promise.resolve().then(() => __toESM(require_dist_cjs49())); + return async () => fromInstanceMetadata(options)().then(setNamedProvider); + }, + Environment: async (options) => { + logger4?.debug("@aws-sdk/credential-provider-ini - credential_source is Environment"); + const { fromEnv } = await Promise.resolve().then(() => __toESM(require_dist_cjs48())); + return async () => fromEnv(options)().then(setNamedProvider); + } + }; + if (credentialSource in sourceProvidersMap) { + return sourceProvidersMap[credentialSource]; + } else { + throw new propertyProvider.CredentialsProviderError(`Unsupported credential source in profile ${profileName}. Got ${credentialSource}, expected EcsContainer or Ec2InstanceMetadata or Environment.`, { logger: logger4 }); + } + }; + var setNamedProvider = (creds) => client2.setCredentialFeature(creds, "CREDENTIALS_PROFILE_NAMED_PROVIDER", "p"); + var isAssumeRoleProfile = (arg, { profile = "default", logger: logger4 } = {}) => { + return Boolean(arg) && typeof arg === "object" && typeof arg.role_arn === "string" && ["undefined", "string"].indexOf(typeof arg.role_session_name) > -1 && ["undefined", "string"].indexOf(typeof arg.external_id) > -1 && ["undefined", "string"].indexOf(typeof arg.mfa_serial) > -1 && (isAssumeRoleWithSourceProfile(arg, { profile, logger: logger4 }) || isCredentialSourceProfile(arg, { profile, logger: logger4 })); + }; + var isAssumeRoleWithSourceProfile = (arg, { profile, logger: logger4 }) => { + const withSourceProfile = typeof arg.source_profile === "string" && typeof arg.credential_source === "undefined"; + if (withSourceProfile) { + logger4?.debug?.(` ${profile} isAssumeRoleWithSourceProfile source_profile=${arg.source_profile}`); + } + return withSourceProfile; + }; + var isCredentialSourceProfile = (arg, { profile, logger: logger4 }) => { + const withProviderProfile = typeof arg.credential_source === "string" && typeof arg.source_profile === "undefined"; + if (withProviderProfile) { + logger4?.debug?.(` ${profile} isCredentialSourceProfile credential_source=${arg.credential_source}`); + } + return withProviderProfile; + }; + var resolveAssumeRoleCredentials = async (profileName, profiles, options, callerClientConfig, visitedProfiles = {}, resolveProfileData2) => { + options.logger?.debug("@aws-sdk/credential-provider-ini - resolveAssumeRoleCredentials (STS)"); + const profileData = profiles[profileName]; + const { source_profile, region } = profileData; + if (!options.roleAssumer) { + const { getDefaultRoleAssumer: getDefaultRoleAssumer3 } = await Promise.resolve().then(() => (init_sts(), sts_exports)); + options.roleAssumer = getDefaultRoleAssumer3({ + ...options.clientConfig, + credentialProviderLogger: options.logger, + parentClientConfig: { + ...callerClientConfig, + ...options?.parentClientConfig, + region: region ?? options?.parentClientConfig?.region ?? callerClientConfig?.region + } + }, options.clientPlugins); + } + if (source_profile && source_profile in visitedProfiles) { + throw new propertyProvider.CredentialsProviderError(`Detected a cycle attempting to resolve credentials for profile ${sharedIniFileLoader.getProfileName(options)}. Profiles visited: ` + Object.keys(visitedProfiles).join(", "), { logger: options.logger }); + } + options.logger?.debug(`@aws-sdk/credential-provider-ini - finding credential resolver using ${source_profile ? `source_profile=[${source_profile}]` : `profile=[${profileName}]`}`); + const sourceCredsProvider = source_profile ? resolveProfileData2(source_profile, profiles, options, callerClientConfig, { + ...visitedProfiles, + [source_profile]: true + }, isCredentialSourceWithoutRoleArn(profiles[source_profile] ?? {})) : (await resolveCredentialSource(profileData.credential_source, profileName, options.logger)(options))(); + if (isCredentialSourceWithoutRoleArn(profileData)) { + return sourceCredsProvider.then((creds) => client2.setCredentialFeature(creds, "CREDENTIALS_PROFILE_SOURCE_PROFILE", "o")); + } else { + const params = { + RoleArn: profileData.role_arn, + RoleSessionName: profileData.role_session_name || `aws-sdk-js-${Date.now()}`, + ExternalId: profileData.external_id, + DurationSeconds: parseInt(profileData.duration_seconds || "3600", 10) + }; + const { mfa_serial } = profileData; + if (mfa_serial) { + if (!options.mfaCodeProvider) { + throw new propertyProvider.CredentialsProviderError(`Profile ${profileName} requires multi-factor authentication, but no MFA code callback was provided.`, { logger: options.logger, tryNextLink: false }); + } + params.SerialNumber = mfa_serial; + params.TokenCode = await options.mfaCodeProvider(mfa_serial); + } + const sourceCreds = await sourceCredsProvider; + return options.roleAssumer(sourceCreds, params).then((creds) => client2.setCredentialFeature(creds, "CREDENTIALS_PROFILE_SOURCE_PROFILE", "o")); + } + }; + var isCredentialSourceWithoutRoleArn = (section) => { + return !section.role_arn && !!section.credential_source; + }; + var isLoginProfile = (data2) => { + return Boolean(data2 && data2.login_session); + }; + var resolveLoginCredentials = async (profileName, options, callerClientConfig) => { + const credentials = await credentialProviderLogin.fromLoginCredentials({ + ...options, + profile: profileName + })({ callerClientConfig }); + return client2.setCredentialFeature(credentials, "CREDENTIALS_PROFILE_LOGIN", "AC"); + }; + var isProcessProfile = (arg) => Boolean(arg) && typeof arg === "object" && typeof arg.credential_process === "string"; + var resolveProcessCredentials = async (options, profile) => Promise.resolve().then(() => __toESM(require_dist_cjs59())).then(({ fromProcess }) => fromProcess({ + ...options, + profile + })().then((creds) => client2.setCredentialFeature(creds, "CREDENTIALS_PROFILE_PROCESS", "v"))); + var resolveSsoCredentials = async (profile, profileData, options = {}, callerClientConfig) => { + const { fromSSO } = await Promise.resolve().then(() => __toESM(require_dist_cjs57())); + return fromSSO({ + profile, + logger: options.logger, + parentClientConfig: options.parentClientConfig, + clientConfig: options.clientConfig + })({ + callerClientConfig + }).then((creds) => { + if (profileData.sso_session) { + return client2.setCredentialFeature(creds, "CREDENTIALS_PROFILE_SSO", "r"); + } else { + return client2.setCredentialFeature(creds, "CREDENTIALS_PROFILE_SSO_LEGACY", "t"); + } + }); + }; + var isSsoProfile = (arg) => arg && (typeof arg.sso_start_url === "string" || typeof arg.sso_account_id === "string" || typeof arg.sso_session === "string" || typeof arg.sso_region === "string" || typeof arg.sso_role_name === "string"); + var isStaticCredsProfile = (arg) => Boolean(arg) && typeof arg === "object" && typeof arg.aws_access_key_id === "string" && typeof arg.aws_secret_access_key === "string" && ["undefined", "string"].indexOf(typeof arg.aws_session_token) > -1 && ["undefined", "string"].indexOf(typeof arg.aws_account_id) > -1; + var resolveStaticCredentials = async (profile, options) => { + options?.logger?.debug("@aws-sdk/credential-provider-ini - resolveStaticCredentials"); + const credentials = { + accessKeyId: profile.aws_access_key_id, + secretAccessKey: profile.aws_secret_access_key, + sessionToken: profile.aws_session_token, + ...profile.aws_credential_scope && { credentialScope: profile.aws_credential_scope }, + ...profile.aws_account_id && { accountId: profile.aws_account_id } + }; + return client2.setCredentialFeature(credentials, "CREDENTIALS_PROFILE", "n"); + }; + var isWebIdentityProfile = (arg) => Boolean(arg) && typeof arg === "object" && typeof arg.web_identity_token_file === "string" && typeof arg.role_arn === "string" && ["undefined", "string"].indexOf(typeof arg.role_session_name) > -1; + var resolveWebIdentityCredentials = async (profile, options, callerClientConfig) => Promise.resolve().then(() => __toESM(require_dist_cjs60())).then(({ fromTokenFile }) => fromTokenFile({ + webIdentityTokenFile: profile.web_identity_token_file, + roleArn: profile.role_arn, + roleSessionName: profile.role_session_name, + roleAssumerWithWebIdentity: options.roleAssumerWithWebIdentity, + logger: options.logger, + parentClientConfig: options.parentClientConfig + })({ + callerClientConfig + }).then((creds) => client2.setCredentialFeature(creds, "CREDENTIALS_PROFILE_STS_WEB_ID_TOKEN", "q"))); + var resolveProfileData = async (profileName, profiles, options, callerClientConfig, visitedProfiles = {}, isAssumeRoleRecursiveCall = false) => { + const data2 = profiles[profileName]; + if (Object.keys(visitedProfiles).length > 0 && isStaticCredsProfile(data2)) { + return resolveStaticCredentials(data2, options); + } + if (isAssumeRoleRecursiveCall || isAssumeRoleProfile(data2, { profile: profileName, logger: options.logger })) { + return resolveAssumeRoleCredentials(profileName, profiles, options, callerClientConfig, visitedProfiles, resolveProfileData); + } + if (isStaticCredsProfile(data2)) { + return resolveStaticCredentials(data2, options); + } + if (isWebIdentityProfile(data2)) { + return resolveWebIdentityCredentials(data2, options, callerClientConfig); + } + if (isProcessProfile(data2)) { + return resolveProcessCredentials(options, profileName); + } + if (isSsoProfile(data2)) { + return await resolveSsoCredentials(profileName, data2, options, callerClientConfig); + } + if (isLoginProfile(data2)) { + return resolveLoginCredentials(profileName, options, callerClientConfig); + } + throw new propertyProvider.CredentialsProviderError(`Could not resolve credentials using profile: [${profileName}] in configuration/credentials file(s).`, { logger: options.logger }); + }; + var fromIni = (init2 = {}) => async ({ callerClientConfig } = {}) => { + init2.logger?.debug("@aws-sdk/credential-provider-ini - fromIni"); + const profiles = await sharedIniFileLoader.parseKnownFiles(init2); + return resolveProfileData(sharedIniFileLoader.getProfileName({ + profile: init2.profile ?? callerClientConfig?.profile + }), profiles, init2, callerClientConfig); + }; + exports.fromIni = fromIni; + } +}); + +// node_modules/.pnpm/@aws-sdk+credential-provider-node@3.972.30/node_modules/@aws-sdk/credential-provider-node/dist-cjs/index.js +var require_dist_cjs62 = __commonJS({ + "node_modules/.pnpm/@aws-sdk+credential-provider-node@3.972.30/node_modules/@aws-sdk/credential-provider-node/dist-cjs/index.js"(exports) { + "use strict"; + var credentialProviderEnv = require_dist_cjs48(); + var propertyProvider = require_dist_cjs41(); + var sharedIniFileLoader = require_dist_cjs42(); + var ENV_IMDS_DISABLED = "AWS_EC2_METADATA_DISABLED"; + var remoteProvider = async (init2) => { + const { ENV_CMDS_FULL_URI, ENV_CMDS_RELATIVE_URI, fromContainerMetadata, fromInstanceMetadata } = await Promise.resolve().then(() => __toESM(require_dist_cjs49())); + if (process.env[ENV_CMDS_RELATIVE_URI] || process.env[ENV_CMDS_FULL_URI]) { + init2.logger?.debug("@aws-sdk/credential-provider-node - remoteProvider::fromHttp/fromContainerMetadata"); + const { fromHttp } = await Promise.resolve().then(() => __toESM(require_dist_cjs50())); + return propertyProvider.chain(fromHttp(init2), fromContainerMetadata(init2)); + } + if (process.env[ENV_IMDS_DISABLED] && process.env[ENV_IMDS_DISABLED] !== "false") { + return async () => { + throw new propertyProvider.CredentialsProviderError("EC2 Instance Metadata Service access disabled", { logger: init2.logger }); + }; + } + init2.logger?.debug("@aws-sdk/credential-provider-node - remoteProvider::fromInstanceMetadata"); + return fromInstanceMetadata(init2); + }; + function memoizeChain(providers2, treatAsExpired) { + const chain = internalCreateChain(providers2); + let activeLock; + let passiveLock; + let credentials; + const provider = async (options) => { + if (options?.forceRefresh) { + return await chain(options); + } + if (credentials?.expiration) { + if (credentials?.expiration?.getTime() < Date.now()) { + credentials = void 0; + } + } + if (activeLock) { + await activeLock; + } else if (!credentials || treatAsExpired?.(credentials)) { + if (credentials) { + if (!passiveLock) { + passiveLock = chain(options).then((c5) => { + credentials = c5; + }).finally(() => { + passiveLock = void 0; + }); + } + } else { + activeLock = chain(options).then((c5) => { + credentials = c5; + }).finally(() => { + activeLock = void 0; + }); + return provider(options); + } + } + return credentials; + }; + return provider; + } + var internalCreateChain = (providers2) => async (awsIdentityProperties) => { + let lastProviderError; + for (const provider of providers2) { + try { + return await provider(awsIdentityProperties); + } catch (err) { + lastProviderError = err; + if (err?.tryNextLink) { + continue; + } + throw err; + } + } + throw lastProviderError; + }; + var multipleCredentialSourceWarningEmitted = false; + var defaultProvider = (init2 = {}) => memoizeChain([ + async () => { + const profile = init2.profile ?? process.env[sharedIniFileLoader.ENV_PROFILE]; + if (profile) { + const envStaticCredentialsAreSet = process.env[credentialProviderEnv.ENV_KEY] && process.env[credentialProviderEnv.ENV_SECRET]; + if (envStaticCredentialsAreSet) { + if (!multipleCredentialSourceWarningEmitted) { + const warnFn = init2.logger?.warn && init2.logger?.constructor?.name !== "NoOpLogger" ? init2.logger.warn.bind(init2.logger) : console.warn; + warnFn(`@aws-sdk/credential-provider-node - defaultProvider::fromEnv WARNING: + Multiple credential sources detected: + Both AWS_PROFILE and the pair AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY static credentials are set. + This SDK will proceed with the AWS_PROFILE value. + + However, a future version may change this behavior to prefer the ENV static credentials. + Please ensure that your environment only sets either the AWS_PROFILE or the + AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY pair. +`); + multipleCredentialSourceWarningEmitted = true; + } + } + throw new propertyProvider.CredentialsProviderError("AWS_PROFILE is set, skipping fromEnv provider.", { + logger: init2.logger, + tryNextLink: true + }); + } + init2.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromEnv"); + return credentialProviderEnv.fromEnv(init2)(); + }, + async (awsIdentityProperties) => { + init2.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromSSO"); + const { ssoStartUrl, ssoAccountId, ssoRegion, ssoRoleName, ssoSession } = init2; + if (!ssoStartUrl && !ssoAccountId && !ssoRegion && !ssoRoleName && !ssoSession) { + throw new propertyProvider.CredentialsProviderError("Skipping SSO provider in default chain (inputs do not include SSO fields).", { logger: init2.logger }); + } + const { fromSSO } = await Promise.resolve().then(() => __toESM(require_dist_cjs57())); + return fromSSO(init2)(awsIdentityProperties); + }, + async (awsIdentityProperties) => { + init2.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromIni"); + const { fromIni } = await Promise.resolve().then(() => __toESM(require_dist_cjs61())); + return fromIni(init2)(awsIdentityProperties); + }, + async (awsIdentityProperties) => { + init2.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromProcess"); + const { fromProcess } = await Promise.resolve().then(() => __toESM(require_dist_cjs59())); + return fromProcess(init2)(awsIdentityProperties); + }, + async (awsIdentityProperties) => { + init2.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromTokenFile"); + const { fromTokenFile } = await Promise.resolve().then(() => __toESM(require_dist_cjs60())); + return fromTokenFile(init2)(awsIdentityProperties); + }, + async () => { + init2.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::remoteProvider"); + return (await remoteProvider(init2))(); + }, + async () => { + throw new propertyProvider.CredentialsProviderError("Could not load credentials from any providers", { + tryNextLink: false, + logger: init2.logger + }); + } + ], credentialsTreatedAsExpired); + var credentialsWillNeedRefresh = (credentials) => credentials?.expiration !== void 0; + var credentialsTreatedAsExpired = (credentials) => credentials?.expiration !== void 0 && credentials.expiration.getTime() - Date.now() < 3e5; + exports.credentialsTreatedAsExpired = credentialsTreatedAsExpired; + exports.credentialsWillNeedRefresh = credentialsWillNeedRefresh; + exports.defaultProvider = defaultProvider; + } +}); + +// node_modules/.pnpm/@aws-sdk+middleware-bucket-endpoint@3.972.9/node_modules/@aws-sdk/middleware-bucket-endpoint/dist-cjs/index.js +var require_dist_cjs63 = __commonJS({ + "node_modules/.pnpm/@aws-sdk+middleware-bucket-endpoint@3.972.9/node_modules/@aws-sdk/middleware-bucket-endpoint/dist-cjs/index.js"(exports) { + "use strict"; + var utilConfigProvider = require_dist_cjs31(); + var utilArnParser = require_dist_cjs28(); + var protocolHttp = require_dist_cjs2(); + var NODE_DISABLE_MULTIREGION_ACCESS_POINT_ENV_NAME = "AWS_S3_DISABLE_MULTIREGION_ACCESS_POINTS"; + var NODE_DISABLE_MULTIREGION_ACCESS_POINT_INI_NAME = "s3_disable_multiregion_access_points"; + var NODE_DISABLE_MULTIREGION_ACCESS_POINT_CONFIG_OPTIONS = { + environmentVariableSelector: (env2) => utilConfigProvider.booleanSelector(env2, NODE_DISABLE_MULTIREGION_ACCESS_POINT_ENV_NAME, utilConfigProvider.SelectorType.ENV), + configFileSelector: (profile) => utilConfigProvider.booleanSelector(profile, NODE_DISABLE_MULTIREGION_ACCESS_POINT_INI_NAME, utilConfigProvider.SelectorType.CONFIG), + default: false + }; + var NODE_USE_ARN_REGION_ENV_NAME = "AWS_S3_USE_ARN_REGION"; + var NODE_USE_ARN_REGION_INI_NAME = "s3_use_arn_region"; + var NODE_USE_ARN_REGION_CONFIG_OPTIONS = { + environmentVariableSelector: (env2) => utilConfigProvider.booleanSelector(env2, NODE_USE_ARN_REGION_ENV_NAME, utilConfigProvider.SelectorType.ENV), + configFileSelector: (profile) => utilConfigProvider.booleanSelector(profile, NODE_USE_ARN_REGION_INI_NAME, utilConfigProvider.SelectorType.CONFIG), + default: void 0 + }; + var DOMAIN_PATTERN = /^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$/; + var IP_ADDRESS_PATTERN = /(\d+\.){3}\d+/; + var DOTS_PATTERN = /\.\./; + var DOT_PATTERN = /\./; + var S3_HOSTNAME_PATTERN = /^(.+\.)?s3(-fips)?(\.dualstack)?[.-]([a-z0-9-]+)\./; + var S3_US_EAST_1_ALTNAME_PATTERN = /^s3(-external-1)?\.amazonaws\.com$/; + var AWS_PARTITION_SUFFIX = "amazonaws.com"; + var isBucketNameOptions = (options) => typeof options.bucketName === "string"; + var isDnsCompatibleBucketName = (bucketName) => DOMAIN_PATTERN.test(bucketName) && !IP_ADDRESS_PATTERN.test(bucketName) && !DOTS_PATTERN.test(bucketName); + var getRegionalSuffix = (hostname3) => { + const parts = hostname3.match(S3_HOSTNAME_PATTERN); + return [parts[4], hostname3.replace(new RegExp(`^${parts[0]}`), "")]; + }; + var getSuffix = (hostname3) => S3_US_EAST_1_ALTNAME_PATTERN.test(hostname3) ? ["us-east-1", AWS_PARTITION_SUFFIX] : getRegionalSuffix(hostname3); + var getSuffixForArnEndpoint = (hostname3) => S3_US_EAST_1_ALTNAME_PATTERN.test(hostname3) ? [hostname3.replace(`.${AWS_PARTITION_SUFFIX}`, ""), AWS_PARTITION_SUFFIX] : getRegionalSuffix(hostname3); + var validateArnEndpointOptions = (options) => { + if (options.pathStyleEndpoint) { + throw new Error("Path-style S3 endpoint is not supported when bucket is an ARN"); + } + if (options.accelerateEndpoint) { + throw new Error("Accelerate endpoint is not supported when bucket is an ARN"); + } + if (!options.tlsCompatible) { + throw new Error("HTTPS is required when bucket is an ARN"); + } + }; + var validateService = (service) => { + if (service !== "s3" && service !== "s3-outposts" && service !== "s3-object-lambda") { + throw new Error("Expect 's3' or 's3-outposts' or 's3-object-lambda' in ARN service component"); + } + }; + var validateS3Service = (service) => { + if (service !== "s3") { + throw new Error("Expect 's3' in Accesspoint ARN service component"); + } + }; + var validateOutpostService = (service) => { + if (service !== "s3-outposts") { + throw new Error("Expect 's3-posts' in Outpost ARN service component"); + } + }; + var validatePartition = (partition, options) => { + if (partition !== options.clientPartition) { + throw new Error(`Partition in ARN is incompatible, got "${partition}" but expected "${options.clientPartition}"`); + } + }; + var validateRegion = (region, options) => { + }; + var validateRegionalClient = (region) => { + if (["s3-external-1", "aws-global"].includes(region)) { + throw new Error(`Client region ${region} is not regional`); + } + }; + var validateAccountId = (accountId) => { + if (!/[0-9]{12}/.exec(accountId)) { + throw new Error("Access point ARN accountID does not match regex '[0-9]{12}'"); + } + }; + var validateDNSHostLabel = (label, options = { tlsCompatible: true }) => { + if (label.length >= 64 || !/^[a-z0-9][a-z0-9.-]*[a-z0-9]$/.test(label) || /(\d+\.){3}\d+/.test(label) || /[.-]{2}/.test(label) || options?.tlsCompatible && DOT_PATTERN.test(label)) { + throw new Error(`Invalid DNS label ${label}`); + } + }; + var validateCustomEndpoint = (options) => { + if (options.isCustomEndpoint) { + if (options.dualstackEndpoint) + throw new Error("Dualstack endpoint is not supported with custom endpoint"); + if (options.accelerateEndpoint) + throw new Error("Accelerate endpoint is not supported with custom endpoint"); + } + }; + var getArnResources = (resource) => { + const delimiter = resource.includes(":") ? ":" : "/"; + const [resourceType, ...rest] = resource.split(delimiter); + if (resourceType === "accesspoint") { + if (rest.length !== 1 || rest[0] === "") { + throw new Error(`Access Point ARN should have one resource accesspoint${delimiter}{accesspointname}`); + } + return { accesspointName: rest[0] }; + } else if (resourceType === "outpost") { + if (!rest[0] || rest[1] !== "accesspoint" || !rest[2] || rest.length !== 3) { + throw new Error(`Outpost ARN should have resource outpost${delimiter}{outpostId}${delimiter}accesspoint${delimiter}{accesspointName}`); + } + const [outpostId, _, accesspointName] = rest; + return { outpostId, accesspointName }; + } else { + throw new Error(`ARN resource should begin with 'accesspoint${delimiter}' or 'outpost${delimiter}'`); + } + }; + var validateNoDualstack = (dualstackEndpoint) => { + }; + var validateNoFIPS = (useFipsEndpoint) => { + if (useFipsEndpoint) + throw new Error(`FIPS region is not supported with Outpost.`); + }; + var validateMrapAlias = (name) => { + try { + name.split(".").forEach((label) => { + validateDNSHostLabel(label); + }); + } catch (e5) { + throw new Error(`"${name}" is not a DNS compatible name.`); + } + }; + var bucketHostname = (options) => { + validateCustomEndpoint(options); + return isBucketNameOptions(options) ? getEndpointFromBucketName(options) : getEndpointFromArn(options); + }; + var getEndpointFromBucketName = ({ accelerateEndpoint = false, clientRegion: region, baseHostname, bucketName, dualstackEndpoint = false, fipsEndpoint = false, pathStyleEndpoint = false, tlsCompatible = true, isCustomEndpoint = false }) => { + const [clientRegion, hostnameSuffix] = isCustomEndpoint ? [region, baseHostname] : getSuffix(baseHostname); + if (pathStyleEndpoint || !isDnsCompatibleBucketName(bucketName) || tlsCompatible && DOT_PATTERN.test(bucketName)) { + return { + bucketEndpoint: false, + hostname: dualstackEndpoint ? `s3.dualstack.${clientRegion}.${hostnameSuffix}` : baseHostname + }; + } + if (accelerateEndpoint) { + baseHostname = `s3-accelerate${dualstackEndpoint ? ".dualstack" : ""}.${hostnameSuffix}`; + } else if (dualstackEndpoint) { + baseHostname = `s3.dualstack.${clientRegion}.${hostnameSuffix}`; + } + return { + bucketEndpoint: true, + hostname: `${bucketName}.${baseHostname}` + }; + }; + var getEndpointFromArn = (options) => { + const { isCustomEndpoint, baseHostname, clientRegion } = options; + const hostnameSuffix = isCustomEndpoint ? baseHostname : getSuffixForArnEndpoint(baseHostname)[1]; + const { pathStyleEndpoint, accelerateEndpoint = false, fipsEndpoint = false, tlsCompatible = true, bucketName, clientPartition = "aws" } = options; + validateArnEndpointOptions({ pathStyleEndpoint, accelerateEndpoint, tlsCompatible }); + const { service, partition, accountId, region, resource } = bucketName; + validateService(service); + validatePartition(partition, { clientPartition }); + validateAccountId(accountId); + const { accesspointName, outpostId } = getArnResources(resource); + if (service === "s3-object-lambda") { + return getEndpointFromObjectLambdaArn({ ...options, tlsCompatible, bucketName, accesspointName, hostnameSuffix }); + } + if (region === "") { + return getEndpointFromMRAPArn({ ...options, mrapAlias: accesspointName, hostnameSuffix }); + } + if (outpostId) { + return getEndpointFromOutpostArn({ ...options, clientRegion, outpostId, accesspointName, hostnameSuffix }); + } + return getEndpointFromAccessPointArn({ ...options, clientRegion, accesspointName, hostnameSuffix }); + }; + var getEndpointFromObjectLambdaArn = ({ dualstackEndpoint = false, fipsEndpoint = false, tlsCompatible = true, useArnRegion, clientRegion, clientSigningRegion = clientRegion, accesspointName, bucketName, hostnameSuffix }) => { + const { accountId, region, service } = bucketName; + validateRegionalClient(clientRegion); + const DNSHostLabel = `${accesspointName}-${accountId}`; + validateDNSHostLabel(DNSHostLabel, { tlsCompatible }); + const endpointRegion = useArnRegion ? region : clientRegion; + const signingRegion = useArnRegion ? region : clientSigningRegion; + return { + bucketEndpoint: true, + hostname: `${DNSHostLabel}.${service}${fipsEndpoint ? "-fips" : ""}.${endpointRegion}.${hostnameSuffix}`, + signingRegion, + signingService: service + }; + }; + var getEndpointFromMRAPArn = ({ disableMultiregionAccessPoints, dualstackEndpoint = false, isCustomEndpoint, mrapAlias, hostnameSuffix }) => { + if (disableMultiregionAccessPoints === true) { + throw new Error("SDK is attempting to use a MRAP ARN. Please enable to feature."); + } + validateMrapAlias(mrapAlias); + return { + bucketEndpoint: true, + hostname: `${mrapAlias}${isCustomEndpoint ? "" : `.accesspoint.s3-global`}.${hostnameSuffix}`, + signingRegion: "*" + }; + }; + var getEndpointFromOutpostArn = ({ useArnRegion, clientRegion, clientSigningRegion = clientRegion, bucketName, outpostId, dualstackEndpoint = false, fipsEndpoint = false, tlsCompatible = true, accesspointName, isCustomEndpoint, hostnameSuffix }) => { + validateRegionalClient(clientRegion); + const DNSHostLabel = `${accesspointName}-${bucketName.accountId}`; + validateDNSHostLabel(DNSHostLabel, { tlsCompatible }); + const endpointRegion = useArnRegion ? bucketName.region : clientRegion; + const signingRegion = useArnRegion ? bucketName.region : clientSigningRegion; + validateOutpostService(bucketName.service); + validateDNSHostLabel(outpostId, { tlsCompatible }); + validateNoFIPS(fipsEndpoint); + const hostnamePrefix = `${DNSHostLabel}.${outpostId}`; + return { + bucketEndpoint: true, + hostname: `${hostnamePrefix}${isCustomEndpoint ? "" : `.s3-outposts.${endpointRegion}`}.${hostnameSuffix}`, + signingRegion, + signingService: "s3-outposts" + }; + }; + var getEndpointFromAccessPointArn = ({ useArnRegion, clientRegion, clientSigningRegion = clientRegion, bucketName, dualstackEndpoint = false, fipsEndpoint = false, tlsCompatible = true, accesspointName, isCustomEndpoint, hostnameSuffix }) => { + validateRegionalClient(clientRegion); + const hostnamePrefix = `${accesspointName}-${bucketName.accountId}`; + validateDNSHostLabel(hostnamePrefix, { tlsCompatible }); + const endpointRegion = useArnRegion ? bucketName.region : clientRegion; + const signingRegion = useArnRegion ? bucketName.region : clientSigningRegion; + validateS3Service(bucketName.service); + return { + bucketEndpoint: true, + hostname: `${hostnamePrefix}${isCustomEndpoint ? "" : `.s3-accesspoint${fipsEndpoint ? "-fips" : ""}${dualstackEndpoint ? ".dualstack" : ""}.${endpointRegion}`}.${hostnameSuffix}`, + signingRegion + }; + }; + var bucketEndpointMiddleware = (options) => (next, context) => async (args) => { + const { Bucket: bucketName } = args.input; + let replaceBucketInPath = options.bucketEndpoint; + const request = args.request; + if (protocolHttp.HttpRequest.isInstance(request)) { + if (options.bucketEndpoint) { + request.hostname = bucketName; + } else if (utilArnParser.validate(bucketName)) { + const bucketArn = utilArnParser.parse(bucketName); + const clientRegion = await options.region(); + const useDualstackEndpoint = await options.useDualstackEndpoint(); + const useFipsEndpoint = await options.useFipsEndpoint(); + const { partition, signingRegion = clientRegion } = await options.regionInfoProvider(clientRegion, { useDualstackEndpoint, useFipsEndpoint }) || {}; + const useArnRegion = await options.useArnRegion(); + const { hostname: hostname3, bucketEndpoint, signingRegion: modifiedSigningRegion, signingService } = bucketHostname({ + bucketName: bucketArn, + baseHostname: request.hostname, + accelerateEndpoint: options.useAccelerateEndpoint, + dualstackEndpoint: useDualstackEndpoint, + fipsEndpoint: useFipsEndpoint, + pathStyleEndpoint: options.forcePathStyle, + tlsCompatible: request.protocol === "https:", + useArnRegion, + clientPartition: partition, + clientSigningRegion: signingRegion, + clientRegion, + isCustomEndpoint: options.isCustomEndpoint, + disableMultiregionAccessPoints: await options.disableMultiregionAccessPoints() + }); + if (modifiedSigningRegion && modifiedSigningRegion !== signingRegion) { + context["signing_region"] = modifiedSigningRegion; + } + if (signingService && signingService !== "s3") { + context["signing_service"] = signingService; + } + request.hostname = hostname3; + replaceBucketInPath = bucketEndpoint; + } else { + const clientRegion = await options.region(); + const dualstackEndpoint = await options.useDualstackEndpoint(); + const fipsEndpoint = await options.useFipsEndpoint(); + const { hostname: hostname3, bucketEndpoint } = bucketHostname({ + bucketName, + clientRegion, + baseHostname: request.hostname, + accelerateEndpoint: options.useAccelerateEndpoint, + dualstackEndpoint, + fipsEndpoint, + pathStyleEndpoint: options.forcePathStyle, + tlsCompatible: request.protocol === "https:", + isCustomEndpoint: options.isCustomEndpoint + }); + request.hostname = hostname3; + replaceBucketInPath = bucketEndpoint; + } + if (replaceBucketInPath) { + request.path = request.path.replace(/^(\/)?[^\/]+/, ""); + if (request.path === "") { + request.path = "/"; + } + } + } + return next({ ...args, request }); + }; + var bucketEndpointMiddlewareOptions = { + tags: ["BUCKET_ENDPOINT"], + name: "bucketEndpointMiddleware", + relation: "before", + toMiddleware: "hostHeaderMiddleware", + override: true + }; + var getBucketEndpointPlugin = (options) => ({ + applyToStack: (clientStack) => { + clientStack.addRelativeTo(bucketEndpointMiddleware(options), bucketEndpointMiddlewareOptions); + } + }); + function resolveBucketEndpointConfig(input) { + const { bucketEndpoint = false, forcePathStyle = false, useAccelerateEndpoint = false, useArnRegion, disableMultiregionAccessPoints = false } = input; + return Object.assign(input, { + bucketEndpoint, + forcePathStyle, + useAccelerateEndpoint, + useArnRegion: typeof useArnRegion === "function" ? useArnRegion : () => Promise.resolve(useArnRegion), + disableMultiregionAccessPoints: typeof disableMultiregionAccessPoints === "function" ? disableMultiregionAccessPoints : () => Promise.resolve(disableMultiregionAccessPoints) + }); + } + exports.NODE_DISABLE_MULTIREGION_ACCESS_POINT_CONFIG_OPTIONS = NODE_DISABLE_MULTIREGION_ACCESS_POINT_CONFIG_OPTIONS; + exports.NODE_DISABLE_MULTIREGION_ACCESS_POINT_ENV_NAME = NODE_DISABLE_MULTIREGION_ACCESS_POINT_ENV_NAME; + exports.NODE_DISABLE_MULTIREGION_ACCESS_POINT_INI_NAME = NODE_DISABLE_MULTIREGION_ACCESS_POINT_INI_NAME; + exports.NODE_USE_ARN_REGION_CONFIG_OPTIONS = NODE_USE_ARN_REGION_CONFIG_OPTIONS; + exports.NODE_USE_ARN_REGION_ENV_NAME = NODE_USE_ARN_REGION_ENV_NAME; + exports.NODE_USE_ARN_REGION_INI_NAME = NODE_USE_ARN_REGION_INI_NAME; + exports.bucketEndpointMiddleware = bucketEndpointMiddleware; + exports.bucketEndpointMiddlewareOptions = bucketEndpointMiddlewareOptions; + exports.bucketHostname = bucketHostname; + exports.getArnResources = getArnResources; + exports.getBucketEndpointPlugin = getBucketEndpointPlugin; + exports.getSuffixForArnEndpoint = getSuffixForArnEndpoint; + exports.resolveBucketEndpointConfig = resolveBucketEndpointConfig; + exports.validateAccountId = validateAccountId; + exports.validateDNSHostLabel = validateDNSHostLabel; + exports.validateNoDualstack = validateNoDualstack; + exports.validateNoFIPS = validateNoFIPS; + exports.validateOutpostService = validateOutpostService; + exports.validatePartition = validatePartition; + exports.validateRegion = validateRegion; + } +}); + +// node_modules/.pnpm/@smithy+eventstream-codec@4.2.13/node_modules/@smithy/eventstream-codec/dist-cjs/index.js +var require_dist_cjs64 = __commonJS({ + "node_modules/.pnpm/@smithy+eventstream-codec@4.2.13/node_modules/@smithy/eventstream-codec/dist-cjs/index.js"(exports) { + "use strict"; + var crc32 = require_main4(); + var utilHexEncoding = require_dist_cjs12(); + var Int64 = class _Int64 { + bytes; + constructor(bytes) { + this.bytes = bytes; + if (bytes.byteLength !== 8) { + throw new Error("Int64 buffers must be exactly 8 bytes"); + } + } + static fromNumber(number4) { + if (number4 > 9223372036854776e3 || number4 < -9223372036854776e3) { + throw new Error(`${number4} is too large (or, if negative, too small) to represent as an Int64`); + } + const bytes = new Uint8Array(8); + for (let i5 = 7, remaining = Math.abs(Math.round(number4)); i5 > -1 && remaining > 0; i5--, remaining /= 256) { + bytes[i5] = remaining; + } + if (number4 < 0) { + negate(bytes); + } + return new _Int64(bytes); + } + valueOf() { + const bytes = this.bytes.slice(0); + const negative = bytes[0] & 128; + if (negative) { + negate(bytes); + } + return parseInt(utilHexEncoding.toHex(bytes), 16) * (negative ? -1 : 1); + } + toString() { + return String(this.valueOf()); + } + }; + function negate(bytes) { + for (let i5 = 0; i5 < 8; i5++) { + bytes[i5] ^= 255; + } + for (let i5 = 7; i5 > -1; i5--) { + bytes[i5]++; + if (bytes[i5] !== 0) + break; + } + } + var HeaderMarshaller = class { + toUtf8; + fromUtf8; + constructor(toUtf811, fromUtf88) { + this.toUtf8 = toUtf811; + this.fromUtf8 = fromUtf88; + } + format(headers) { + const chunks = []; + for (const headerName of Object.keys(headers)) { + const bytes = this.fromUtf8(headerName); + chunks.push(Uint8Array.from([bytes.byteLength]), bytes, this.formatHeaderValue(headers[headerName])); + } + const out = new Uint8Array(chunks.reduce((carry, bytes) => carry + bytes.byteLength, 0)); + let position = 0; + for (const chunk of chunks) { + out.set(chunk, position); + position += chunk.byteLength; + } + return out; + } + formatHeaderValue(header) { + switch (header.type) { + case "boolean": + return Uint8Array.from([header.value ? 0 : 1]); + case "byte": + return Uint8Array.from([2, header.value]); + case "short": + const shortView = new DataView(new ArrayBuffer(3)); + shortView.setUint8(0, 3); + shortView.setInt16(1, header.value, false); + return new Uint8Array(shortView.buffer); + case "integer": + const intView = new DataView(new ArrayBuffer(5)); + intView.setUint8(0, 4); + intView.setInt32(1, header.value, false); + return new Uint8Array(intView.buffer); + case "long": + const longBytes = new Uint8Array(9); + longBytes[0] = 5; + longBytes.set(header.value.bytes, 1); + return longBytes; + case "binary": + const binView = new DataView(new ArrayBuffer(3 + header.value.byteLength)); + binView.setUint8(0, 6); + binView.setUint16(1, header.value.byteLength, false); + const binBytes = new Uint8Array(binView.buffer); + binBytes.set(header.value, 3); + return binBytes; + case "string": + const utf8Bytes = this.fromUtf8(header.value); + const strView = new DataView(new ArrayBuffer(3 + utf8Bytes.byteLength)); + strView.setUint8(0, 7); + strView.setUint16(1, utf8Bytes.byteLength, false); + const strBytes = new Uint8Array(strView.buffer); + strBytes.set(utf8Bytes, 3); + return strBytes; + case "timestamp": + const tsBytes = new Uint8Array(9); + tsBytes[0] = 8; + tsBytes.set(Int64.fromNumber(header.value.valueOf()).bytes, 1); + return tsBytes; + case "uuid": + if (!UUID_PATTERN2.test(header.value)) { + throw new Error(`Invalid UUID received: ${header.value}`); + } + const uuidBytes = new Uint8Array(17); + uuidBytes[0] = 9; + uuidBytes.set(utilHexEncoding.fromHex(header.value.replace(/\-/g, "")), 1); + return uuidBytes; + } + } + parse(headers) { + const out = {}; + let position = 0; + while (position < headers.byteLength) { + const nameLength = headers.getUint8(position++); + const name = this.toUtf8(new Uint8Array(headers.buffer, headers.byteOffset + position, nameLength)); + position += nameLength; + switch (headers.getUint8(position++)) { + case 0: + out[name] = { + type: BOOLEAN_TAG, + value: true + }; + break; + case 1: + out[name] = { + type: BOOLEAN_TAG, + value: false + }; + break; + case 2: + out[name] = { + type: BYTE_TAG, + value: headers.getInt8(position++) + }; + break; + case 3: + out[name] = { + type: SHORT_TAG, + value: headers.getInt16(position, false) + }; + position += 2; + break; + case 4: + out[name] = { + type: INT_TAG, + value: headers.getInt32(position, false) + }; + position += 4; + break; + case 5: + out[name] = { + type: LONG_TAG, + value: new Int64(new Uint8Array(headers.buffer, headers.byteOffset + position, 8)) + }; + position += 8; + break; + case 6: + const binaryLength = headers.getUint16(position, false); + position += 2; + out[name] = { + type: BINARY_TAG, + value: new Uint8Array(headers.buffer, headers.byteOffset + position, binaryLength) + }; + position += binaryLength; + break; + case 7: + const stringLength = headers.getUint16(position, false); + position += 2; + out[name] = { + type: STRING_TAG, + value: this.toUtf8(new Uint8Array(headers.buffer, headers.byteOffset + position, stringLength)) + }; + position += stringLength; + break; + case 8: + out[name] = { + type: TIMESTAMP_TAG, + value: new Date(new Int64(new Uint8Array(headers.buffer, headers.byteOffset + position, 8)).valueOf()) + }; + position += 8; + break; + case 9: + const uuidBytes = new Uint8Array(headers.buffer, headers.byteOffset + position, 16); + position += 16; + out[name] = { + type: UUID_TAG, + value: `${utilHexEncoding.toHex(uuidBytes.subarray(0, 4))}-${utilHexEncoding.toHex(uuidBytes.subarray(4, 6))}-${utilHexEncoding.toHex(uuidBytes.subarray(6, 8))}-${utilHexEncoding.toHex(uuidBytes.subarray(8, 10))}-${utilHexEncoding.toHex(uuidBytes.subarray(10))}` + }; + break; + default: + throw new Error(`Unrecognized header type tag`); + } + } + return out; + } + }; + var HEADER_VALUE_TYPE; + (function(HEADER_VALUE_TYPE2) { + HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["boolTrue"] = 0] = "boolTrue"; + HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["boolFalse"] = 1] = "boolFalse"; + HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["byte"] = 2] = "byte"; + HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["short"] = 3] = "short"; + HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["integer"] = 4] = "integer"; + HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["long"] = 5] = "long"; + HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["byteArray"] = 6] = "byteArray"; + HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["string"] = 7] = "string"; + HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["timestamp"] = 8] = "timestamp"; + HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["uuid"] = 9] = "uuid"; + })(HEADER_VALUE_TYPE || (HEADER_VALUE_TYPE = {})); + var BOOLEAN_TAG = "boolean"; + var BYTE_TAG = "byte"; + var SHORT_TAG = "short"; + var INT_TAG = "integer"; + var LONG_TAG = "long"; + var BINARY_TAG = "binary"; + var STRING_TAG = "string"; + var TIMESTAMP_TAG = "timestamp"; + var UUID_TAG = "uuid"; + var UUID_PATTERN2 = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/; + var PRELUDE_MEMBER_LENGTH = 4; + var PRELUDE_LENGTH = PRELUDE_MEMBER_LENGTH * 2; + var CHECKSUM_LENGTH = 4; + var MINIMUM_MESSAGE_LENGTH = PRELUDE_LENGTH + CHECKSUM_LENGTH * 2; + function splitMessage({ byteLength, byteOffset, buffer: buffer2 }) { + if (byteLength < MINIMUM_MESSAGE_LENGTH) { + throw new Error("Provided message too short to accommodate event stream message overhead"); + } + const view = new DataView(buffer2, byteOffset, byteLength); + const messageLength = view.getUint32(0, false); + if (byteLength !== messageLength) { + throw new Error("Reported message length does not match received message length"); + } + const headerLength = view.getUint32(PRELUDE_MEMBER_LENGTH, false); + const expectedPreludeChecksum = view.getUint32(PRELUDE_LENGTH, false); + const expectedMessageChecksum = view.getUint32(byteLength - CHECKSUM_LENGTH, false); + const checksummer = new crc32.Crc32().update(new Uint8Array(buffer2, byteOffset, PRELUDE_LENGTH)); + if (expectedPreludeChecksum !== checksummer.digest()) { + throw new Error(`The prelude checksum specified in the message (${expectedPreludeChecksum}) does not match the calculated CRC32 checksum (${checksummer.digest()})`); + } + checksummer.update(new Uint8Array(buffer2, byteOffset + PRELUDE_LENGTH, byteLength - (PRELUDE_LENGTH + CHECKSUM_LENGTH))); + if (expectedMessageChecksum !== checksummer.digest()) { + throw new Error(`The message checksum (${checksummer.digest()}) did not match the expected value of ${expectedMessageChecksum}`); + } + return { + headers: new DataView(buffer2, byteOffset + PRELUDE_LENGTH + CHECKSUM_LENGTH, headerLength), + body: new Uint8Array(buffer2, byteOffset + PRELUDE_LENGTH + CHECKSUM_LENGTH + headerLength, messageLength - headerLength - (PRELUDE_LENGTH + CHECKSUM_LENGTH + CHECKSUM_LENGTH)) + }; + } + var EventStreamCodec = class { + headerMarshaller; + messageBuffer; + isEndOfStream; + constructor(toUtf811, fromUtf88) { + this.headerMarshaller = new HeaderMarshaller(toUtf811, fromUtf88); + this.messageBuffer = []; + this.isEndOfStream = false; + } + feed(message2) { + this.messageBuffer.push(this.decode(message2)); + } + endOfStream() { + this.isEndOfStream = true; + } + getMessage() { + const message2 = this.messageBuffer.pop(); + const isEndOfStream = this.isEndOfStream; + return { + getMessage() { + return message2; + }, + isEndOfStream() { + return isEndOfStream; + } + }; + } + getAvailableMessages() { + const messages2 = this.messageBuffer; + this.messageBuffer = []; + const isEndOfStream = this.isEndOfStream; + return { + getMessages() { + return messages2; + }, + isEndOfStream() { + return isEndOfStream; + } + }; + } + encode({ headers: rawHeaders, body }) { + const headers = this.headerMarshaller.format(rawHeaders); + const length = headers.byteLength + body.byteLength + 16; + const out = new Uint8Array(length); + const view = new DataView(out.buffer, out.byteOffset, out.byteLength); + const checksum = new crc32.Crc32(); + view.setUint32(0, length, false); + view.setUint32(4, headers.byteLength, false); + view.setUint32(8, checksum.update(out.subarray(0, 8)).digest(), false); + out.set(headers, 12); + out.set(body, headers.byteLength + 12); + view.setUint32(length - 4, checksum.update(out.subarray(8, length - 4)).digest(), false); + return out; + } + decode(message2) { + const { headers, body } = splitMessage(message2); + return { headers: this.headerMarshaller.parse(headers), body }; + } + formatHeaders(rawHeaders) { + return this.headerMarshaller.format(rawHeaders); + } + }; + var MessageDecoderStream = class { + options; + constructor(options) { + this.options = options; + } + [Symbol.asyncIterator]() { + return this.asyncIterator(); + } + async *asyncIterator() { + for await (const bytes of this.options.inputStream) { + const decoded = this.options.decoder.decode(bytes); + yield decoded; + } + } + }; + var MessageEncoderStream = class { + options; + constructor(options) { + this.options = options; + } + [Symbol.asyncIterator]() { + return this.asyncIterator(); + } + async *asyncIterator() { + for await (const msg of this.options.messageStream) { + const encoded = this.options.encoder.encode(msg); + yield encoded; + } + if (this.options.includeEndFrame) { + yield new Uint8Array(0); + } + } + }; + var SmithyMessageDecoderStream = class { + options; + constructor(options) { + this.options = options; + } + [Symbol.asyncIterator]() { + return this.asyncIterator(); + } + async *asyncIterator() { + for await (const message2 of this.options.messageStream) { + const deserialized = await this.options.deserializer(message2); + if (deserialized === void 0) + continue; + yield deserialized; + } + } + }; + var SmithyMessageEncoderStream = class { + options; + constructor(options) { + this.options = options; + } + [Symbol.asyncIterator]() { + return this.asyncIterator(); + } + async *asyncIterator() { + for await (const chunk of this.options.inputStream) { + const payloadBuf = this.options.serializer(chunk); + yield payloadBuf; + } + } + }; + exports.EventStreamCodec = EventStreamCodec; + exports.HeaderMarshaller = HeaderMarshaller; + exports.Int64 = Int64; + exports.MessageDecoderStream = MessageDecoderStream; + exports.MessageEncoderStream = MessageEncoderStream; + exports.SmithyMessageDecoderStream = SmithyMessageDecoderStream; + exports.SmithyMessageEncoderStream = SmithyMessageEncoderStream; + } +}); + +// node_modules/.pnpm/@smithy+eventstream-serde-universal@4.2.13/node_modules/@smithy/eventstream-serde-universal/dist-cjs/index.js +var require_dist_cjs65 = __commonJS({ + "node_modules/.pnpm/@smithy+eventstream-serde-universal@4.2.13/node_modules/@smithy/eventstream-serde-universal/dist-cjs/index.js"(exports) { + "use strict"; + var eventstreamCodec = require_dist_cjs64(); + function getChunkedStream(source) { + let currentMessageTotalLength = 0; + let currentMessagePendingLength = 0; + let currentMessage = null; + let messageLengthBuffer = null; + const allocateMessage = (size2) => { + if (typeof size2 !== "number") { + throw new Error("Attempted to allocate an event message where size was not a number: " + size2); + } + currentMessageTotalLength = size2; + currentMessagePendingLength = 4; + currentMessage = new Uint8Array(size2); + const currentMessageView = new DataView(currentMessage.buffer); + currentMessageView.setUint32(0, size2, false); + }; + const iterator = async function* () { + const sourceIterator = source[Symbol.asyncIterator](); + while (true) { + const { value, done } = await sourceIterator.next(); + if (done) { + if (!currentMessageTotalLength) { + return; + } else if (currentMessageTotalLength === currentMessagePendingLength) { + yield currentMessage; + } else { + throw new Error("Truncated event message received."); + } + return; + } + const chunkLength = value.length; + let currentOffset = 0; + while (currentOffset < chunkLength) { + if (!currentMessage) { + const bytesRemaining = chunkLength - currentOffset; + if (!messageLengthBuffer) { + messageLengthBuffer = new Uint8Array(4); + } + const numBytesForTotal = Math.min(4 - currentMessagePendingLength, bytesRemaining); + messageLengthBuffer.set(value.slice(currentOffset, currentOffset + numBytesForTotal), currentMessagePendingLength); + currentMessagePendingLength += numBytesForTotal; + currentOffset += numBytesForTotal; + if (currentMessagePendingLength < 4) { + break; + } + allocateMessage(new DataView(messageLengthBuffer.buffer).getUint32(0, false)); + messageLengthBuffer = null; + } + const numBytesToWrite = Math.min(currentMessageTotalLength - currentMessagePendingLength, chunkLength - currentOffset); + currentMessage.set(value.slice(currentOffset, currentOffset + numBytesToWrite), currentMessagePendingLength); + currentMessagePendingLength += numBytesToWrite; + currentOffset += numBytesToWrite; + if (currentMessageTotalLength && currentMessageTotalLength === currentMessagePendingLength) { + yield currentMessage; + currentMessage = null; + currentMessageTotalLength = 0; + currentMessagePendingLength = 0; + } + } + } + }; + return { + [Symbol.asyncIterator]: iterator + }; + } + function getMessageUnmarshaller(deserializer, toUtf811) { + return async function(message2) { + const { value: messageType } = message2.headers[":message-type"]; + if (messageType === "error") { + const unmodeledError = new Error(message2.headers[":error-message"].value || "UnknownError"); + unmodeledError.name = message2.headers[":error-code"].value; + throw unmodeledError; + } else if (messageType === "exception") { + const code = message2.headers[":exception-type"].value; + const exception = { [code]: message2 }; + const deserializedException = await deserializer(exception); + if (deserializedException.$unknown) { + const error50 = new Error(toUtf811(message2.body)); + error50.name = code; + throw error50; + } + throw deserializedException[code]; + } else if (messageType === "event") { + const event = { + [message2.headers[":event-type"].value]: message2 + }; + const deserialized = await deserializer(event); + if (deserialized.$unknown) + return; + return deserialized; + } else { + throw Error(`Unrecognizable event type: ${message2.headers[":event-type"].value}`); + } + }; + } + var EventStreamMarshaller = class { + eventStreamCodec; + utfEncoder; + constructor({ utf8Encoder, utf8Decoder }) { + this.eventStreamCodec = new eventstreamCodec.EventStreamCodec(utf8Encoder, utf8Decoder); + this.utfEncoder = utf8Encoder; + } + deserialize(body, deserializer) { + const inputStream = getChunkedStream(body); + return new eventstreamCodec.SmithyMessageDecoderStream({ + messageStream: new eventstreamCodec.MessageDecoderStream({ inputStream, decoder: this.eventStreamCodec }), + deserializer: getMessageUnmarshaller(deserializer, this.utfEncoder) + }); + } + serialize(inputStream, serializer) { + return new eventstreamCodec.MessageEncoderStream({ + messageStream: new eventstreamCodec.SmithyMessageEncoderStream({ inputStream, serializer }), + encoder: this.eventStreamCodec, + includeEndFrame: true + }); + } + }; + var eventStreamSerdeProvider = (options) => new EventStreamMarshaller(options); + exports.EventStreamMarshaller = EventStreamMarshaller; + exports.eventStreamSerdeProvider = eventStreamSerdeProvider; + } +}); + +// node_modules/.pnpm/@smithy+eventstream-serde-node@4.2.13/node_modules/@smithy/eventstream-serde-node/dist-cjs/index.js +var require_dist_cjs66 = __commonJS({ + "node_modules/.pnpm/@smithy+eventstream-serde-node@4.2.13/node_modules/@smithy/eventstream-serde-node/dist-cjs/index.js"(exports) { + "use strict"; + var eventstreamSerdeUniversal = require_dist_cjs65(); + var stream = __require("stream"); + async function* readabletoIterable(readStream) { + let streamEnded = false; + let generationEnded = false; + const records = new Array(); + readStream.on("error", (err) => { + if (!streamEnded) { + streamEnded = true; + } + if (err) { + throw err; + } + }); + readStream.on("data", (data2) => { + records.push(data2); + }); + readStream.on("end", () => { + streamEnded = true; + }); + while (!generationEnded) { + const value = await new Promise((resolve4) => setTimeout(() => resolve4(records.shift()), 0)); + if (value) { + yield value; + } + generationEnded = streamEnded && records.length === 0; + } + } + var EventStreamMarshaller = class { + universalMarshaller; + constructor({ utf8Encoder, utf8Decoder }) { + this.universalMarshaller = new eventstreamSerdeUniversal.EventStreamMarshaller({ + utf8Decoder, + utf8Encoder + }); + } + deserialize(body, deserializer) { + const bodyIterable = typeof body[Symbol.asyncIterator] === "function" ? body : readabletoIterable(body); + return this.universalMarshaller.deserialize(bodyIterable, deserializer); + } + serialize(input, serializer) { + return stream.Readable.from(this.universalMarshaller.serialize(input, serializer)); + } + }; + var eventStreamSerdeProvider = (options) => new EventStreamMarshaller(options); + exports.EventStreamMarshaller = EventStreamMarshaller; + exports.eventStreamSerdeProvider = eventStreamSerdeProvider; + } +}); + +// node_modules/.pnpm/@smithy+hash-stream-node@4.2.13/node_modules/@smithy/hash-stream-node/dist-cjs/index.js +var require_dist_cjs67 = __commonJS({ + "node_modules/.pnpm/@smithy+hash-stream-node@4.2.13/node_modules/@smithy/hash-stream-node/dist-cjs/index.js"(exports) { + "use strict"; + var fs41 = __require("fs"); + var utilUtf8 = require_dist_cjs6(); + var stream = __require("stream"); + var HashCalculator = class extends stream.Writable { + hash; + constructor(hash2, options) { + super(options); + this.hash = hash2; + } + _write(chunk, encoding, callback) { + try { + this.hash.update(utilUtf8.toUint8Array(chunk)); + } catch (err) { + return callback(err); + } + callback(); + } + }; + var fileStreamHasher = (hashCtor, fileStream) => new Promise((resolve4, reject) => { + if (!isReadStream(fileStream)) { + reject(new Error("Unable to calculate hash for non-file streams.")); + return; + } + const fileStreamTee = fs41.createReadStream(fileStream.path, { + start: fileStream.start, + end: fileStream.end + }); + const hash2 = new hashCtor(); + const hashCalculator = new HashCalculator(hash2); + fileStreamTee.pipe(hashCalculator); + fileStreamTee.on("error", (err) => { + hashCalculator.end(); + reject(err); + }); + hashCalculator.on("error", reject); + hashCalculator.on("finish", function() { + hash2.digest().then(resolve4).catch(reject); + }); + }); + var isReadStream = (stream2) => typeof stream2.path === "string"; + var readableStreamHasher = (hashCtor, readableStream) => { + if (readableStream.readableFlowing !== null) { + throw new Error("Unable to calculate hash for flowing readable stream"); + } + const hash2 = new hashCtor(); + const hashCalculator = new HashCalculator(hash2); + readableStream.pipe(hashCalculator); + return new Promise((resolve4, reject) => { + readableStream.on("error", (err) => { + hashCalculator.end(); + reject(err); + }); + hashCalculator.on("error", reject); + hashCalculator.on("finish", () => { + hash2.digest().then(resolve4).catch(reject); + }); + }); + }; + exports.fileStreamHasher = fileStreamHasher; + exports.readableStreamHasher = readableStreamHasher; + } +}); + +// node_modules/.pnpm/@aws-sdk+client-s3@3.1030.0/node_modules/@aws-sdk/client-s3/dist-cjs/runtimeConfig.shared.js +var require_runtimeConfig_shared = __commonJS({ + "node_modules/.pnpm/@aws-sdk+client-s3@3.1030.0/node_modules/@aws-sdk/client-s3/dist-cjs/runtimeConfig.shared.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getRuntimeConfig = void 0; + var httpAuthSchemes_1 = (init_httpAuthSchemes2(), __toCommonJS(httpAuthSchemes_exports)); + var middleware_sdk_s3_1 = require_dist_cjs32(); + var signature_v4_multi_region_1 = require_dist_cjs47(); + var smithy_client_1 = require_dist_cjs27(); + var url_parser_1 = require_dist_cjs25(); + var util_base64_1 = require_dist_cjs7(); + var util_stream_1 = require_dist_cjs13(); + var util_utf8_1 = require_dist_cjs6(); + var httpAuthSchemeProvider_1 = require_httpAuthSchemeProvider(); + var endpointResolver_1 = require_endpointResolver(); + var schemas_0_1 = require_schemas_0(); + var getRuntimeConfig9 = (config3) => { + return { + apiVersion: "2006-03-01", + base64Decoder: config3?.base64Decoder ?? util_base64_1.fromBase64, + base64Encoder: config3?.base64Encoder ?? util_base64_1.toBase64, + disableHostPrefix: config3?.disableHostPrefix ?? false, + endpointProvider: config3?.endpointProvider ?? endpointResolver_1.defaultEndpointResolver, + extensions: config3?.extensions ?? [], + getAwsChunkedEncodingStream: config3?.getAwsChunkedEncodingStream ?? util_stream_1.getAwsChunkedEncodingStream, + httpAuthSchemeProvider: config3?.httpAuthSchemeProvider ?? httpAuthSchemeProvider_1.defaultS3HttpAuthSchemeProvider, + httpAuthSchemes: config3?.httpAuthSchemes ?? [ + { + schemeId: "aws.auth#sigv4", + identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"), + signer: new httpAuthSchemes_1.AwsSdkSigV4Signer() + }, + { + schemeId: "aws.auth#sigv4a", + identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4a"), + signer: new httpAuthSchemes_1.AwsSdkSigV4ASigner() + } + ], + logger: config3?.logger ?? new smithy_client_1.NoOpLogger(), + protocol: config3?.protocol ?? middleware_sdk_s3_1.S3RestXmlProtocol, + protocolSettings: config3?.protocolSettings ?? { + defaultNamespace: "com.amazonaws.s3", + errorTypeRegistries: schemas_0_1.errorTypeRegistries, + xmlNamespace: "http://s3.amazonaws.com/doc/2006-03-01/", + version: "2006-03-01", + serviceTarget: "AmazonS3" + }, + sdkStreamMixin: config3?.sdkStreamMixin ?? util_stream_1.sdkStreamMixin, + serviceId: config3?.serviceId ?? "S3", + signerConstructor: config3?.signerConstructor ?? signature_v4_multi_region_1.SignatureV4MultiRegion, + signingEscapePath: config3?.signingEscapePath ?? false, + urlParser: config3?.urlParser ?? url_parser_1.parseUrl, + useArnRegion: config3?.useArnRegion ?? void 0, + utf8Decoder: config3?.utf8Decoder ?? util_utf8_1.fromUtf8, + utf8Encoder: config3?.utf8Encoder ?? util_utf8_1.toUtf8 + }; + }; + exports.getRuntimeConfig = getRuntimeConfig9; + } +}); + +// node_modules/.pnpm/@aws-sdk+client-s3@3.1030.0/node_modules/@aws-sdk/client-s3/dist-cjs/runtimeConfig.js +var require_runtimeConfig = __commonJS({ + "node_modules/.pnpm/@aws-sdk+client-s3@3.1030.0/node_modules/@aws-sdk/client-s3/dist-cjs/runtimeConfig.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getRuntimeConfig = void 0; + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var package_json_1 = tslib_1.__importDefault(require_package2()); + var client_1 = (init_client2(), __toCommonJS(client_exports)); + var httpAuthSchemes_1 = (init_httpAuthSchemes2(), __toCommonJS(httpAuthSchemes_exports)); + var credential_provider_node_1 = require_dist_cjs62(); + var middleware_bucket_endpoint_1 = require_dist_cjs63(); + var middleware_flexible_checksums_1 = require_dist_cjs19(); + var middleware_sdk_s3_1 = require_dist_cjs32(); + var util_user_agent_node_1 = require_dist_cjs51(); + var config_resolver_1 = require_dist_cjs38(); + var eventstream_serde_node_1 = require_dist_cjs66(); + var hash_node_1 = require_dist_cjs52(); + var hash_stream_node_1 = require_dist_cjs67(); + var middleware_retry_1 = require_dist_cjs46(); + var node_config_provider_1 = require_dist_cjs43(); + var node_http_handler_1 = require_dist_cjs10(); + var smithy_client_1 = require_dist_cjs27(); + var util_body_length_node_1 = require_dist_cjs53(); + var util_defaults_mode_node_1 = require_dist_cjs54(); + var util_retry_1 = require_dist_cjs36(); + var runtimeConfig_shared_1 = require_runtimeConfig_shared(); + var getRuntimeConfig9 = (config3) => { + (0, smithy_client_1.emitWarningIfUnsupportedVersion)(process.version); + const defaultsMode = (0, util_defaults_mode_node_1.resolveDefaultsModeConfig)(config3); + const defaultConfigProvider = () => defaultsMode().then(smithy_client_1.loadConfigsForDefaultMode); + const clientSharedValues = (0, runtimeConfig_shared_1.getRuntimeConfig)(config3); + (0, client_1.emitWarningIfUnsupportedVersion)(process.version); + const loaderConfig = { + profile: config3?.profile, + logger: clientSharedValues.logger + }; + return { + ...clientSharedValues, + ...config3, + runtime: "node", + defaultsMode, + authSchemePreference: config3?.authSchemePreference ?? (0, node_config_provider_1.loadConfig)(httpAuthSchemes_1.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig), + bodyLengthChecker: config3?.bodyLengthChecker ?? util_body_length_node_1.calculateBodyLength, + credentialDefaultProvider: config3?.credentialDefaultProvider ?? credential_provider_node_1.defaultProvider, + defaultUserAgentProvider: config3?.defaultUserAgentProvider ?? (0, util_user_agent_node_1.createDefaultUserAgentProvider)({ serviceId: clientSharedValues.serviceId, clientVersion: package_json_1.default.version }), + disableS3ExpressSessionAuth: config3?.disableS3ExpressSessionAuth ?? (0, node_config_provider_1.loadConfig)(middleware_sdk_s3_1.NODE_DISABLE_S3_EXPRESS_SESSION_AUTH_OPTIONS, loaderConfig), + eventStreamSerdeProvider: config3?.eventStreamSerdeProvider ?? eventstream_serde_node_1.eventStreamSerdeProvider, + maxAttempts: config3?.maxAttempts ?? (0, node_config_provider_1.loadConfig)(middleware_retry_1.NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config3), + md5: config3?.md5 ?? hash_node_1.Hash.bind(null, "md5"), + region: config3?.region ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_REGION_CONFIG_OPTIONS, { ...config_resolver_1.NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }), + requestChecksumCalculation: config3?.requestChecksumCalculation ?? (0, node_config_provider_1.loadConfig)(middleware_flexible_checksums_1.NODE_REQUEST_CHECKSUM_CALCULATION_CONFIG_OPTIONS, loaderConfig), + requestHandler: node_http_handler_1.NodeHttpHandler.create(config3?.requestHandler ?? defaultConfigProvider), + responseChecksumValidation: config3?.responseChecksumValidation ?? (0, node_config_provider_1.loadConfig)(middleware_flexible_checksums_1.NODE_RESPONSE_CHECKSUM_VALIDATION_CONFIG_OPTIONS, loaderConfig), + retryMode: config3?.retryMode ?? (0, node_config_provider_1.loadConfig)({ + ...middleware_retry_1.NODE_RETRY_MODE_CONFIG_OPTIONS, + default: async () => (await defaultConfigProvider()).retryMode || util_retry_1.DEFAULT_RETRY_MODE + }, config3), + sha1: config3?.sha1 ?? hash_node_1.Hash.bind(null, "sha1"), + sha256: config3?.sha256 ?? hash_node_1.Hash.bind(null, "sha256"), + sigv4aSigningRegionSet: config3?.sigv4aSigningRegionSet ?? (0, node_config_provider_1.loadConfig)(httpAuthSchemes_1.NODE_SIGV4A_CONFIG_OPTIONS, loaderConfig), + streamCollector: config3?.streamCollector ?? node_http_handler_1.streamCollector, + streamHasher: config3?.streamHasher ?? hash_stream_node_1.readableStreamHasher, + useArnRegion: config3?.useArnRegion ?? (0, node_config_provider_1.loadConfig)(middleware_bucket_endpoint_1.NODE_USE_ARN_REGION_CONFIG_OPTIONS, loaderConfig), + useDualstackEndpoint: config3?.useDualstackEndpoint ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig), + useFipsEndpoint: config3?.useFipsEndpoint ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig), + userAgentAppId: config3?.userAgentAppId ?? (0, node_config_provider_1.loadConfig)(util_user_agent_node_1.NODE_APP_ID_CONFIG_OPTIONS, loaderConfig) + }; + }; + exports.getRuntimeConfig = getRuntimeConfig9; + } +}); + +// node_modules/.pnpm/@aws-sdk+middleware-ssec@3.972.9/node_modules/@aws-sdk/middleware-ssec/dist-cjs/index.js +var require_dist_cjs68 = __commonJS({ + "node_modules/.pnpm/@aws-sdk+middleware-ssec@3.972.9/node_modules/@aws-sdk/middleware-ssec/dist-cjs/index.js"(exports) { + "use strict"; + function ssecMiddleware(options) { + return (next) => async (args) => { + const input = { ...args.input }; + const properties = [ + { + target: "SSECustomerKey", + hash: "SSECustomerKeyMD5" + }, + { + target: "CopySourceSSECustomerKey", + hash: "CopySourceSSECustomerKeyMD5" + } + ]; + for (const prop of properties) { + const value = input[prop.target]; + if (value) { + let valueForHash; + if (typeof value === "string") { + if (isValidBase64EncodedSSECustomerKey(value, options)) { + valueForHash = options.base64Decoder(value); + } else { + valueForHash = options.utf8Decoder(value); + input[prop.target] = options.base64Encoder(valueForHash); + } + } else { + valueForHash = ArrayBuffer.isView(value) ? new Uint8Array(value.buffer, value.byteOffset, value.byteLength) : new Uint8Array(value); + input[prop.target] = options.base64Encoder(valueForHash); + } + const hash2 = new options.md5(); + hash2.update(valueForHash); + input[prop.hash] = options.base64Encoder(await hash2.digest()); + } + } + return next({ + ...args, + input + }); + }; + } + var ssecMiddlewareOptions = { + name: "ssecMiddleware", + step: "initialize", + tags: ["SSE"], + override: true + }; + var getSsecPlugin = (config3) => ({ + applyToStack: (clientStack) => { + clientStack.add(ssecMiddleware(config3), ssecMiddlewareOptions); + } + }); + function isValidBase64EncodedSSECustomerKey(str, options) { + const base64Regex2 = /^(?:[A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/; + if (!base64Regex2.test(str)) + return false; + try { + const decodedBytes = options.base64Decoder(str); + return decodedBytes.length === 32; + } catch { + return false; + } + } + exports.getSsecPlugin = getSsecPlugin; + exports.isValidBase64EncodedSSECustomerKey = isValidBase64EncodedSSECustomerKey; + exports.ssecMiddleware = ssecMiddleware; + exports.ssecMiddlewareOptions = ssecMiddlewareOptions; + } +}); + +// node_modules/.pnpm/@aws-sdk+middleware-location-constraint@3.972.9/node_modules/@aws-sdk/middleware-location-constraint/dist-cjs/index.js +var require_dist_cjs69 = __commonJS({ + "node_modules/.pnpm/@aws-sdk+middleware-location-constraint@3.972.9/node_modules/@aws-sdk/middleware-location-constraint/dist-cjs/index.js"(exports) { + "use strict"; + function locationConstraintMiddleware(options) { + return (next) => async (args) => { + const { CreateBucketConfiguration } = args.input; + const region = await options.region(); + if (!CreateBucketConfiguration?.LocationConstraint && !CreateBucketConfiguration?.Location) { + if (region !== "us-east-1") { + args.input.CreateBucketConfiguration = args.input.CreateBucketConfiguration ?? {}; + args.input.CreateBucketConfiguration.LocationConstraint = region; + } + } + return next(args); + }; + } + var locationConstraintMiddlewareOptions = { + step: "initialize", + tags: ["LOCATION_CONSTRAINT", "CREATE_BUCKET_CONFIGURATION"], + name: "locationConstraintMiddleware", + override: true + }; + var getLocationConstraintPlugin = (config3) => ({ + applyToStack: (clientStack) => { + clientStack.add(locationConstraintMiddleware(config3), locationConstraintMiddlewareOptions); + } + }); + exports.getLocationConstraintPlugin = getLocationConstraintPlugin; + exports.locationConstraintMiddleware = locationConstraintMiddleware; + exports.locationConstraintMiddlewareOptions = locationConstraintMiddlewareOptions; + } +}); + +// node_modules/.pnpm/@smithy+util-waiter@4.2.15/node_modules/@smithy/util-waiter/dist-cjs/index.js +var require_dist_cjs70 = __commonJS({ + "node_modules/.pnpm/@smithy+util-waiter@4.2.15/node_modules/@smithy/util-waiter/dist-cjs/index.js"(exports) { + "use strict"; + var getCircularReplacer = () => { + const seen = /* @__PURE__ */ new WeakSet(); + return (key, value) => { + if (typeof value === "object" && value !== null) { + if (seen.has(value)) { + return "[Circular]"; + } + seen.add(value); + } + return value; + }; + }; + var sleep = (seconds) => { + return new Promise((resolve4) => setTimeout(resolve4, seconds * 1e3)); + }; + var waiterServiceDefaults = { + minDelay: 2, + maxDelay: 120 + }; + exports.WaiterState = void 0; + (function(WaiterState) { + WaiterState["ABORTED"] = "ABORTED"; + WaiterState["FAILURE"] = "FAILURE"; + WaiterState["SUCCESS"] = "SUCCESS"; + WaiterState["RETRY"] = "RETRY"; + WaiterState["TIMEOUT"] = "TIMEOUT"; + })(exports.WaiterState || (exports.WaiterState = {})); + var checkExceptions = (result) => { + if (result.state === exports.WaiterState.ABORTED) { + const abortError = new Error(`${JSON.stringify({ + ...result, + reason: "Request was aborted" + }, getCircularReplacer())}`); + abortError.name = "AbortError"; + throw abortError; + } else if (result.state === exports.WaiterState.TIMEOUT) { + const timeoutError = new Error(`${JSON.stringify({ + ...result, + reason: "Waiter has timed out" + }, getCircularReplacer())}`); + timeoutError.name = "TimeoutError"; + throw timeoutError; + } else if (result.state !== exports.WaiterState.SUCCESS) { + throw new Error(`${JSON.stringify(result, getCircularReplacer())}`); + } + return result; + }; + var exponentialBackoffWithJitter = (minDelay, maxDelay, attemptCeiling, attempt) => { + if (attempt > attemptCeiling) + return maxDelay; + const delay3 = minDelay * 2 ** (attempt - 1); + return randomInRange(minDelay, delay3); + }; + var randomInRange = (min, max) => min + Math.random() * (max - min); + var runPolling = async ({ minDelay, maxDelay, maxWaitTime, abortController, client: client2, abortSignal }, input, acceptorChecks) => { + const observedResponses = {}; + const { state: state2, reason } = await acceptorChecks(client2, input); + if (reason) { + const message2 = createMessageFromResponse(reason); + observedResponses[message2] |= 0; + observedResponses[message2] += 1; + } + if (state2 !== exports.WaiterState.RETRY) { + return { state: state2, reason, observedResponses }; + } + let currentAttempt = 1; + const waitUntil = Date.now() + maxWaitTime * 1e3; + const attemptCeiling = Math.log(maxDelay / minDelay) / Math.log(2) + 1; + while (true) { + if (abortController?.signal?.aborted || abortSignal?.aborted) { + const message2 = "AbortController signal aborted."; + observedResponses[message2] |= 0; + observedResponses[message2] += 1; + return { state: exports.WaiterState.ABORTED, observedResponses }; + } + const delay3 = exponentialBackoffWithJitter(minDelay, maxDelay, attemptCeiling, currentAttempt); + if (Date.now() + delay3 * 1e3 > waitUntil) { + return { state: exports.WaiterState.TIMEOUT, observedResponses }; + } + await sleep(delay3); + const { state: state3, reason: reason2 } = await acceptorChecks(client2, input); + if (reason2) { + const message2 = createMessageFromResponse(reason2); + observedResponses[message2] |= 0; + observedResponses[message2] += 1; + } + if (state3 !== exports.WaiterState.RETRY) { + return { state: state3, reason: reason2, observedResponses }; + } + currentAttempt += 1; + } + }; + var createMessageFromResponse = (reason) => { + if (reason?.$responseBodyText) { + return `Deserialization error for body: ${reason.$responseBodyText}`; + } + if (reason?.$metadata?.httpStatusCode) { + if (reason.$response || reason.message) { + return `${reason.$response?.statusCode ?? reason.$metadata.httpStatusCode ?? "Unknown"}: ${reason.message}`; + } + return `${reason.$metadata.httpStatusCode}: OK`; + } + return String(reason?.message ?? JSON.stringify(reason, getCircularReplacer()) ?? "Unknown"); + }; + var validateWaiterOptions = (options) => { + if (options.maxWaitTime <= 0) { + throw new Error(`WaiterConfiguration.maxWaitTime must be greater than 0`); + } else if (options.minDelay <= 0) { + throw new Error(`WaiterConfiguration.minDelay must be greater than 0`); + } else if (options.maxDelay <= 0) { + throw new Error(`WaiterConfiguration.maxDelay must be greater than 0`); + } else if (options.maxWaitTime <= options.minDelay) { + throw new Error(`WaiterConfiguration.maxWaitTime [${options.maxWaitTime}] must be greater than WaiterConfiguration.minDelay [${options.minDelay}] for this waiter`); + } else if (options.maxDelay < options.minDelay) { + throw new Error(`WaiterConfiguration.maxDelay [${options.maxDelay}] must be greater than WaiterConfiguration.minDelay [${options.minDelay}] for this waiter`); + } + }; + var abortTimeout = (abortSignal) => { + let onAbort; + const promise2 = new Promise((resolve4) => { + onAbort = () => resolve4({ state: exports.WaiterState.ABORTED }); + if (typeof abortSignal.addEventListener === "function") { + abortSignal.addEventListener("abort", onAbort); + } else { + abortSignal.onabort = onAbort; + } + }); + return { + clearListener() { + if (typeof abortSignal.removeEventListener === "function") { + abortSignal.removeEventListener("abort", onAbort); + } + }, + aborted: promise2 + }; + }; + var createWaiter = async (options, input, acceptorChecks) => { + const params = { + ...waiterServiceDefaults, + ...options + }; + validateWaiterOptions(params); + const exitConditions = [runPolling(params, input, acceptorChecks)]; + const finalize2 = []; + if (options.abortSignal) { + const { aborted: aborted2, clearListener } = abortTimeout(options.abortSignal); + finalize2.push(clearListener); + exitConditions.push(aborted2); + } + if (options.abortController?.signal) { + const { aborted: aborted2, clearListener } = abortTimeout(options.abortController.signal); + finalize2.push(clearListener); + exitConditions.push(aborted2); + } + return Promise.race(exitConditions).then((result) => { + for (const fn of finalize2) { + fn(); + } + return result; + }); + }; + exports.checkExceptions = checkExceptions; + exports.createWaiter = createWaiter; + exports.waiterServiceDefaults = waiterServiceDefaults; + } +}); + +// node_modules/.pnpm/@aws-sdk+client-s3@3.1030.0/node_modules/@aws-sdk/client-s3/dist-cjs/index.js +var require_dist_cjs71 = __commonJS({ + "node_modules/.pnpm/@aws-sdk+client-s3@3.1030.0/node_modules/@aws-sdk/client-s3/dist-cjs/index.js"(exports) { + "use strict"; + var middlewareExpectContinue = require_dist_cjs3(); + var middlewareFlexibleChecksums = require_dist_cjs19(); + var middlewareHostHeader = require_dist_cjs20(); + var middlewareLogger = require_dist_cjs21(); + var middlewareRecursionDetection = require_dist_cjs22(); + var middlewareSdkS3 = require_dist_cjs32(); + var middlewareUserAgent = require_dist_cjs37(); + var configResolver = require_dist_cjs38(); + var core = (init_dist_es(), __toCommonJS(dist_es_exports)); + var schema2 = (init_schema3(), __toCommonJS(schema_exports2)); + var eventstreamSerdeConfigResolver = require_dist_cjs39(); + var middlewareContentLength = require_dist_cjs40(); + var middlewareEndpoint = require_dist_cjs45(); + var middlewareRetry = require_dist_cjs46(); + var smithyClient = require_dist_cjs27(); + var httpAuthSchemeProvider = require_httpAuthSchemeProvider(); + var schemas_0 = require_schemas_0(); + var runtimeConfig = require_runtimeConfig(); + var regionConfigResolver = require_dist_cjs55(); + var protocolHttp = require_dist_cjs2(); + var middlewareSsec = require_dist_cjs68(); + var middlewareLocationConstraint = require_dist_cjs69(); + var utilWaiter = require_dist_cjs70(); + var errors = require_errors(); + var S3ServiceException = require_S3ServiceException(); + var resolveClientEndpointParameters5 = (options) => { + return Object.assign(options, { + useFipsEndpoint: options.useFipsEndpoint ?? false, + useDualstackEndpoint: options.useDualstackEndpoint ?? false, + forcePathStyle: options.forcePathStyle ?? false, + useAccelerateEndpoint: options.useAccelerateEndpoint ?? false, + useGlobalEndpoint: options.useGlobalEndpoint ?? false, + disableMultiregionAccessPoints: options.disableMultiregionAccessPoints ?? false, + defaultSigningName: "s3", + clientContextParams: options.clientContextParams ?? {} + }); + }; + var commonParams5 = { + ForcePathStyle: { type: "clientContextParams", name: "forcePathStyle" }, + UseArnRegion: { type: "clientContextParams", name: "useArnRegion" }, + DisableMultiRegionAccessPoints: { type: "clientContextParams", name: "disableMultiregionAccessPoints" }, + Accelerate: { type: "clientContextParams", name: "useAccelerateEndpoint" }, + DisableS3ExpressSessionAuth: { type: "clientContextParams", name: "disableS3ExpressSessionAuth" }, + UseGlobalEndpoint: { type: "builtInParams", name: "useGlobalEndpoint" }, + UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, + Endpoint: { type: "builtInParams", name: "endpoint" }, + Region: { type: "builtInParams", name: "region" }, + UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" } + }; + var CreateSessionCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + DisableS3ExpressSessionAuth: { type: "staticContextParams", value: true }, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareSdkS3.getThrow200ExceptionsPlugin(config3) + ]; + }).s("AmazonS3", "CreateSession", {}).n("S3Client", "CreateSessionCommand").sc(schemas_0.CreateSession$).build() { + }; + var getHttpAuthExtensionConfiguration5 = (runtimeConfig2) => { + const _httpAuthSchemes = runtimeConfig2.httpAuthSchemes; + let _httpAuthSchemeProvider = runtimeConfig2.httpAuthSchemeProvider; + let _credentials = runtimeConfig2.credentials; + return { + setHttpAuthScheme(httpAuthScheme) { + const index2 = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId); + if (index2 === -1) { + _httpAuthSchemes.push(httpAuthScheme); + } else { + _httpAuthSchemes.splice(index2, 1, httpAuthScheme); + } + }, + httpAuthSchemes() { + return _httpAuthSchemes; + }, + setHttpAuthSchemeProvider(httpAuthSchemeProvider2) { + _httpAuthSchemeProvider = httpAuthSchemeProvider2; + }, + httpAuthSchemeProvider() { + return _httpAuthSchemeProvider; + }, + setCredentials(credentials) { + _credentials = credentials; + }, + credentials() { + return _credentials; + } + }; + }; + var resolveHttpAuthRuntimeConfig5 = (config3) => { + return { + httpAuthSchemes: config3.httpAuthSchemes(), + httpAuthSchemeProvider: config3.httpAuthSchemeProvider(), + credentials: config3.credentials() + }; + }; + var resolveRuntimeExtensions5 = (runtimeConfig2, extensions) => { + const extensionConfiguration = Object.assign(regionConfigResolver.getAwsRegionExtensionConfiguration(runtimeConfig2), smithyClient.getDefaultExtensionConfiguration(runtimeConfig2), protocolHttp.getHttpHandlerExtensionConfiguration(runtimeConfig2), getHttpAuthExtensionConfiguration5(runtimeConfig2)); + extensions.forEach((extension2) => extension2.configure(extensionConfiguration)); + return Object.assign(runtimeConfig2, regionConfigResolver.resolveAwsRegionExtensionConfiguration(extensionConfiguration), smithyClient.resolveDefaultRuntimeConfig(extensionConfiguration), protocolHttp.resolveHttpHandlerRuntimeConfig(extensionConfiguration), resolveHttpAuthRuntimeConfig5(extensionConfiguration)); + }; + var S3Client2 = class extends smithyClient.Client { + config; + constructor(...[configuration]) { + const _config_0 = runtimeConfig.getRuntimeConfig(configuration || {}); + super(_config_0); + this.initConfig = _config_0; + const _config_1 = resolveClientEndpointParameters5(_config_0); + const _config_2 = middlewareUserAgent.resolveUserAgentConfig(_config_1); + const _config_3 = middlewareFlexibleChecksums.resolveFlexibleChecksumsConfig(_config_2); + const _config_4 = middlewareRetry.resolveRetryConfig(_config_3); + const _config_5 = configResolver.resolveRegionConfig(_config_4); + const _config_6 = middlewareHostHeader.resolveHostHeaderConfig(_config_5); + const _config_7 = middlewareEndpoint.resolveEndpointConfig(_config_6); + const _config_8 = eventstreamSerdeConfigResolver.resolveEventStreamSerdeConfig(_config_7); + const _config_9 = httpAuthSchemeProvider.resolveHttpAuthSchemeConfig(_config_8); + const _config_10 = middlewareSdkS3.resolveS3Config(_config_9, { session: [() => this, CreateSessionCommand] }); + const _config_11 = resolveRuntimeExtensions5(_config_10, configuration?.extensions || []); + this.config = _config_11; + this.middlewareStack.use(schema2.getSchemaSerdePlugin(this.config)); + this.middlewareStack.use(middlewareUserAgent.getUserAgentPlugin(this.config)); + this.middlewareStack.use(middlewareRetry.getRetryPlugin(this.config)); + this.middlewareStack.use(middlewareContentLength.getContentLengthPlugin(this.config)); + this.middlewareStack.use(middlewareHostHeader.getHostHeaderPlugin(this.config)); + this.middlewareStack.use(middlewareLogger.getLoggerPlugin(this.config)); + this.middlewareStack.use(middlewareRecursionDetection.getRecursionDetectionPlugin(this.config)); + this.middlewareStack.use(core.getHttpAuthSchemeEndpointRuleSetPlugin(this.config, { + httpAuthSchemeParametersProvider: httpAuthSchemeProvider.defaultS3HttpAuthSchemeParametersProvider, + identityProviderConfigProvider: async (config3) => new core.DefaultIdentityProviderConfig({ + "aws.auth#sigv4": config3.credentials, + "aws.auth#sigv4a": config3.credentials + }) + })); + this.middlewareStack.use(core.getHttpSigningPlugin(this.config)); + this.middlewareStack.use(middlewareSdkS3.getValidateBucketNamePlugin(this.config)); + this.middlewareStack.use(middlewareExpectContinue.getAddExpectContinuePlugin(this.config)); + this.middlewareStack.use(middlewareSdkS3.getRegionRedirectMiddlewarePlugin(this.config)); + this.middlewareStack.use(middlewareSdkS3.getS3ExpressPlugin(this.config)); + this.middlewareStack.use(middlewareSdkS3.getS3ExpressHttpSigningPlugin(this.config)); + } + destroy() { + super.destroy(); + } + }; + var AbortMultipartUploadCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + Bucket: { type: "contextParams", name: "Bucket" }, + Key: { type: "contextParams", name: "Key" } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareSdkS3.getThrow200ExceptionsPlugin(config3) + ]; + }).s("AmazonS3", "AbortMultipartUpload", {}).n("S3Client", "AbortMultipartUploadCommand").sc(schemas_0.AbortMultipartUpload$).build() { + }; + var CompleteMultipartUploadCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + Bucket: { type: "contextParams", name: "Bucket" }, + Key: { type: "contextParams", name: "Key" } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareSdkS3.getThrow200ExceptionsPlugin(config3), + middlewareSsec.getSsecPlugin(config3) + ]; + }).s("AmazonS3", "CompleteMultipartUpload", {}).n("S3Client", "CompleteMultipartUploadCommand").sc(schemas_0.CompleteMultipartUpload$).build() { + }; + var CopyObjectCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + DisableS3ExpressSessionAuth: { type: "staticContextParams", value: true }, + Bucket: { type: "contextParams", name: "Bucket" }, + Key: { type: "contextParams", name: "Key" }, + CopySource: { type: "contextParams", name: "CopySource" } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareSdkS3.getThrow200ExceptionsPlugin(config3), + middlewareSsec.getSsecPlugin(config3) + ]; + }).s("AmazonS3", "CopyObject", {}).n("S3Client", "CopyObjectCommand").sc(schemas_0.CopyObject$).build() { + }; + var CreateBucketCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, + DisableAccessPoints: { type: "staticContextParams", value: true }, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareSdkS3.getThrow200ExceptionsPlugin(config3), + middlewareLocationConstraint.getLocationConstraintPlugin(config3) + ]; + }).s("AmazonS3", "CreateBucket", {}).n("S3Client", "CreateBucketCommand").sc(schemas_0.CreateBucket$).build() { + }; + var CreateBucketMetadataConfigurationCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareFlexibleChecksums.getFlexibleChecksumsPlugin(config3, { + requestAlgorithmMember: { "httpHeader": "x-amz-sdk-checksum-algorithm", "name": "ChecksumAlgorithm" }, + requestChecksumRequired: true + }) + ]; + }).s("AmazonS3", "CreateBucketMetadataConfiguration", {}).n("S3Client", "CreateBucketMetadataConfigurationCommand").sc(schemas_0.CreateBucketMetadataConfiguration$).build() { + }; + var CreateBucketMetadataTableConfigurationCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareFlexibleChecksums.getFlexibleChecksumsPlugin(config3, { + requestAlgorithmMember: { "httpHeader": "x-amz-sdk-checksum-algorithm", "name": "ChecksumAlgorithm" }, + requestChecksumRequired: true + }) + ]; + }).s("AmazonS3", "CreateBucketMetadataTableConfiguration", {}).n("S3Client", "CreateBucketMetadataTableConfigurationCommand").sc(schemas_0.CreateBucketMetadataTableConfiguration$).build() { + }; + var CreateMultipartUploadCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + Bucket: { type: "contextParams", name: "Bucket" }, + Key: { type: "contextParams", name: "Key" } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareSdkS3.getThrow200ExceptionsPlugin(config3), + middlewareSsec.getSsecPlugin(config3) + ]; + }).s("AmazonS3", "CreateMultipartUpload", {}).n("S3Client", "CreateMultipartUploadCommand").sc(schemas_0.CreateMultipartUpload$).build() { + }; + var DeleteBucketAnalyticsConfigurationCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions())]; + }).s("AmazonS3", "DeleteBucketAnalyticsConfiguration", {}).n("S3Client", "DeleteBucketAnalyticsConfigurationCommand").sc(schemas_0.DeleteBucketAnalyticsConfiguration$).build() { + }; + var DeleteBucketCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions())]; + }).s("AmazonS3", "DeleteBucket", {}).n("S3Client", "DeleteBucketCommand").sc(schemas_0.DeleteBucket$).build() { + }; + var DeleteBucketCorsCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions())]; + }).s("AmazonS3", "DeleteBucketCors", {}).n("S3Client", "DeleteBucketCorsCommand").sc(schemas_0.DeleteBucketCors$).build() { + }; + var DeleteBucketEncryptionCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions())]; + }).s("AmazonS3", "DeleteBucketEncryption", {}).n("S3Client", "DeleteBucketEncryptionCommand").sc(schemas_0.DeleteBucketEncryption$).build() { + }; + var DeleteBucketIntelligentTieringConfigurationCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions())]; + }).s("AmazonS3", "DeleteBucketIntelligentTieringConfiguration", {}).n("S3Client", "DeleteBucketIntelligentTieringConfigurationCommand").sc(schemas_0.DeleteBucketIntelligentTieringConfiguration$).build() { + }; + var DeleteBucketInventoryConfigurationCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions())]; + }).s("AmazonS3", "DeleteBucketInventoryConfiguration", {}).n("S3Client", "DeleteBucketInventoryConfigurationCommand").sc(schemas_0.DeleteBucketInventoryConfiguration$).build() { + }; + var DeleteBucketLifecycleCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions())]; + }).s("AmazonS3", "DeleteBucketLifecycle", {}).n("S3Client", "DeleteBucketLifecycleCommand").sc(schemas_0.DeleteBucketLifecycle$).build() { + }; + var DeleteBucketMetadataConfigurationCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions())]; + }).s("AmazonS3", "DeleteBucketMetadataConfiguration", {}).n("S3Client", "DeleteBucketMetadataConfigurationCommand").sc(schemas_0.DeleteBucketMetadataConfiguration$).build() { + }; + var DeleteBucketMetadataTableConfigurationCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions())]; + }).s("AmazonS3", "DeleteBucketMetadataTableConfiguration", {}).n("S3Client", "DeleteBucketMetadataTableConfigurationCommand").sc(schemas_0.DeleteBucketMetadataTableConfiguration$).build() { + }; + var DeleteBucketMetricsConfigurationCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions())]; + }).s("AmazonS3", "DeleteBucketMetricsConfiguration", {}).n("S3Client", "DeleteBucketMetricsConfigurationCommand").sc(schemas_0.DeleteBucketMetricsConfiguration$).build() { + }; + var DeleteBucketOwnershipControlsCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions())]; + }).s("AmazonS3", "DeleteBucketOwnershipControls", {}).n("S3Client", "DeleteBucketOwnershipControlsCommand").sc(schemas_0.DeleteBucketOwnershipControls$).build() { + }; + var DeleteBucketPolicyCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions())]; + }).s("AmazonS3", "DeleteBucketPolicy", {}).n("S3Client", "DeleteBucketPolicyCommand").sc(schemas_0.DeleteBucketPolicy$).build() { + }; + var DeleteBucketReplicationCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions())]; + }).s("AmazonS3", "DeleteBucketReplication", {}).n("S3Client", "DeleteBucketReplicationCommand").sc(schemas_0.DeleteBucketReplication$).build() { + }; + var DeleteBucketTaggingCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions())]; + }).s("AmazonS3", "DeleteBucketTagging", {}).n("S3Client", "DeleteBucketTaggingCommand").sc(schemas_0.DeleteBucketTagging$).build() { + }; + var DeleteBucketWebsiteCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions())]; + }).s("AmazonS3", "DeleteBucketWebsite", {}).n("S3Client", "DeleteBucketWebsiteCommand").sc(schemas_0.DeleteBucketWebsite$).build() { + }; + var DeleteObjectCommand2 = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + Bucket: { type: "contextParams", name: "Bucket" }, + Key: { type: "contextParams", name: "Key" } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareSdkS3.getThrow200ExceptionsPlugin(config3) + ]; + }).s("AmazonS3", "DeleteObject", {}).n("S3Client", "DeleteObjectCommand").sc(schemas_0.DeleteObject$).build() { + }; + var DeleteObjectsCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareFlexibleChecksums.getFlexibleChecksumsPlugin(config3, { + requestAlgorithmMember: { "httpHeader": "x-amz-sdk-checksum-algorithm", "name": "ChecksumAlgorithm" }, + requestChecksumRequired: true + }), + middlewareSdkS3.getThrow200ExceptionsPlugin(config3) + ]; + }).s("AmazonS3", "DeleteObjects", {}).n("S3Client", "DeleteObjectsCommand").sc(schemas_0.DeleteObjects$).build() { + }; + var DeleteObjectTaggingCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareSdkS3.getThrow200ExceptionsPlugin(config3) + ]; + }).s("AmazonS3", "DeleteObjectTagging", {}).n("S3Client", "DeleteObjectTaggingCommand").sc(schemas_0.DeleteObjectTagging$).build() { + }; + var DeletePublicAccessBlockCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions())]; + }).s("AmazonS3", "DeletePublicAccessBlock", {}).n("S3Client", "DeletePublicAccessBlockCommand").sc(schemas_0.DeletePublicAccessBlock$).build() { + }; + var GetBucketAbacCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareSdkS3.getThrow200ExceptionsPlugin(config3) + ]; + }).s("AmazonS3", "GetBucketAbac", {}).n("S3Client", "GetBucketAbacCommand").sc(schemas_0.GetBucketAbac$).build() { + }; + var GetBucketAccelerateConfigurationCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareSdkS3.getThrow200ExceptionsPlugin(config3) + ]; + }).s("AmazonS3", "GetBucketAccelerateConfiguration", {}).n("S3Client", "GetBucketAccelerateConfigurationCommand").sc(schemas_0.GetBucketAccelerateConfiguration$).build() { + }; + var GetBucketAclCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareSdkS3.getThrow200ExceptionsPlugin(config3) + ]; + }).s("AmazonS3", "GetBucketAcl", {}).n("S3Client", "GetBucketAclCommand").sc(schemas_0.GetBucketAcl$).build() { + }; + var GetBucketAnalyticsConfigurationCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareSdkS3.getThrow200ExceptionsPlugin(config3) + ]; + }).s("AmazonS3", "GetBucketAnalyticsConfiguration", {}).n("S3Client", "GetBucketAnalyticsConfigurationCommand").sc(schemas_0.GetBucketAnalyticsConfiguration$).build() { + }; + var GetBucketCorsCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareSdkS3.getThrow200ExceptionsPlugin(config3) + ]; + }).s("AmazonS3", "GetBucketCors", {}).n("S3Client", "GetBucketCorsCommand").sc(schemas_0.GetBucketCors$).build() { + }; + var GetBucketEncryptionCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareSdkS3.getThrow200ExceptionsPlugin(config3) + ]; + }).s("AmazonS3", "GetBucketEncryption", {}).n("S3Client", "GetBucketEncryptionCommand").sc(schemas_0.GetBucketEncryption$).build() { + }; + var GetBucketIntelligentTieringConfigurationCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareSdkS3.getThrow200ExceptionsPlugin(config3) + ]; + }).s("AmazonS3", "GetBucketIntelligentTieringConfiguration", {}).n("S3Client", "GetBucketIntelligentTieringConfigurationCommand").sc(schemas_0.GetBucketIntelligentTieringConfiguration$).build() { + }; + var GetBucketInventoryConfigurationCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareSdkS3.getThrow200ExceptionsPlugin(config3) + ]; + }).s("AmazonS3", "GetBucketInventoryConfiguration", {}).n("S3Client", "GetBucketInventoryConfigurationCommand").sc(schemas_0.GetBucketInventoryConfiguration$).build() { + }; + var GetBucketLifecycleConfigurationCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareSdkS3.getThrow200ExceptionsPlugin(config3) + ]; + }).s("AmazonS3", "GetBucketLifecycleConfiguration", {}).n("S3Client", "GetBucketLifecycleConfigurationCommand").sc(schemas_0.GetBucketLifecycleConfiguration$).build() { + }; + var GetBucketLocationCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareSdkS3.getThrow200ExceptionsPlugin(config3) + ]; + }).s("AmazonS3", "GetBucketLocation", {}).n("S3Client", "GetBucketLocationCommand").sc(schemas_0.GetBucketLocation$).build() { + }; + var GetBucketLoggingCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareSdkS3.getThrow200ExceptionsPlugin(config3) + ]; + }).s("AmazonS3", "GetBucketLogging", {}).n("S3Client", "GetBucketLoggingCommand").sc(schemas_0.GetBucketLogging$).build() { + }; + var GetBucketMetadataConfigurationCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareSdkS3.getThrow200ExceptionsPlugin(config3) + ]; + }).s("AmazonS3", "GetBucketMetadataConfiguration", {}).n("S3Client", "GetBucketMetadataConfigurationCommand").sc(schemas_0.GetBucketMetadataConfiguration$).build() { + }; + var GetBucketMetadataTableConfigurationCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareSdkS3.getThrow200ExceptionsPlugin(config3) + ]; + }).s("AmazonS3", "GetBucketMetadataTableConfiguration", {}).n("S3Client", "GetBucketMetadataTableConfigurationCommand").sc(schemas_0.GetBucketMetadataTableConfiguration$).build() { + }; + var GetBucketMetricsConfigurationCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareSdkS3.getThrow200ExceptionsPlugin(config3) + ]; + }).s("AmazonS3", "GetBucketMetricsConfiguration", {}).n("S3Client", "GetBucketMetricsConfigurationCommand").sc(schemas_0.GetBucketMetricsConfiguration$).build() { + }; + var GetBucketNotificationConfigurationCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareSdkS3.getThrow200ExceptionsPlugin(config3) + ]; + }).s("AmazonS3", "GetBucketNotificationConfiguration", {}).n("S3Client", "GetBucketNotificationConfigurationCommand").sc(schemas_0.GetBucketNotificationConfiguration$).build() { + }; + var GetBucketOwnershipControlsCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareSdkS3.getThrow200ExceptionsPlugin(config3) + ]; + }).s("AmazonS3", "GetBucketOwnershipControls", {}).n("S3Client", "GetBucketOwnershipControlsCommand").sc(schemas_0.GetBucketOwnershipControls$).build() { + }; + var GetBucketPolicyCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareSdkS3.getThrow200ExceptionsPlugin(config3) + ]; + }).s("AmazonS3", "GetBucketPolicy", {}).n("S3Client", "GetBucketPolicyCommand").sc(schemas_0.GetBucketPolicy$).build() { + }; + var GetBucketPolicyStatusCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareSdkS3.getThrow200ExceptionsPlugin(config3) + ]; + }).s("AmazonS3", "GetBucketPolicyStatus", {}).n("S3Client", "GetBucketPolicyStatusCommand").sc(schemas_0.GetBucketPolicyStatus$).build() { + }; + var GetBucketReplicationCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareSdkS3.getThrow200ExceptionsPlugin(config3) + ]; + }).s("AmazonS3", "GetBucketReplication", {}).n("S3Client", "GetBucketReplicationCommand").sc(schemas_0.GetBucketReplication$).build() { + }; + var GetBucketRequestPaymentCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareSdkS3.getThrow200ExceptionsPlugin(config3) + ]; + }).s("AmazonS3", "GetBucketRequestPayment", {}).n("S3Client", "GetBucketRequestPaymentCommand").sc(schemas_0.GetBucketRequestPayment$).build() { + }; + var GetBucketTaggingCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareSdkS3.getThrow200ExceptionsPlugin(config3) + ]; + }).s("AmazonS3", "GetBucketTagging", {}).n("S3Client", "GetBucketTaggingCommand").sc(schemas_0.GetBucketTagging$).build() { + }; + var GetBucketVersioningCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareSdkS3.getThrow200ExceptionsPlugin(config3) + ]; + }).s("AmazonS3", "GetBucketVersioning", {}).n("S3Client", "GetBucketVersioningCommand").sc(schemas_0.GetBucketVersioning$).build() { + }; + var GetBucketWebsiteCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareSdkS3.getThrow200ExceptionsPlugin(config3) + ]; + }).s("AmazonS3", "GetBucketWebsite", {}).n("S3Client", "GetBucketWebsiteCommand").sc(schemas_0.GetBucketWebsite$).build() { + }; + var GetObjectAclCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + Bucket: { type: "contextParams", name: "Bucket" }, + Key: { type: "contextParams", name: "Key" } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareSdkS3.getThrow200ExceptionsPlugin(config3) + ]; + }).s("AmazonS3", "GetObjectAcl", {}).n("S3Client", "GetObjectAclCommand").sc(schemas_0.GetObjectAcl$).build() { + }; + var GetObjectAttributesCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareSdkS3.getThrow200ExceptionsPlugin(config3), + middlewareSsec.getSsecPlugin(config3) + ]; + }).s("AmazonS3", "GetObjectAttributes", {}).n("S3Client", "GetObjectAttributesCommand").sc(schemas_0.GetObjectAttributes$).build() { + }; + var GetObjectCommand2 = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + Bucket: { type: "contextParams", name: "Bucket" }, + Key: { type: "contextParams", name: "Key" } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareFlexibleChecksums.getFlexibleChecksumsPlugin(config3, { + requestChecksumRequired: false, + requestValidationModeMember: "ChecksumMode", + "responseAlgorithms": ["CRC64NVME", "CRC32", "CRC32C", "SHA256", "SHA1"] + }), + middlewareSsec.getSsecPlugin(config3), + middlewareSdkS3.getS3ExpiresMiddlewarePlugin(config3) + ]; + }).s("AmazonS3", "GetObject", {}).n("S3Client", "GetObjectCommand").sc(schemas_0.GetObject$).build() { + }; + var GetObjectLegalHoldCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareSdkS3.getThrow200ExceptionsPlugin(config3) + ]; + }).s("AmazonS3", "GetObjectLegalHold", {}).n("S3Client", "GetObjectLegalHoldCommand").sc(schemas_0.GetObjectLegalHold$).build() { + }; + var GetObjectLockConfigurationCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareSdkS3.getThrow200ExceptionsPlugin(config3) + ]; + }).s("AmazonS3", "GetObjectLockConfiguration", {}).n("S3Client", "GetObjectLockConfigurationCommand").sc(schemas_0.GetObjectLockConfiguration$).build() { + }; + var GetObjectRetentionCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareSdkS3.getThrow200ExceptionsPlugin(config3) + ]; + }).s("AmazonS3", "GetObjectRetention", {}).n("S3Client", "GetObjectRetentionCommand").sc(schemas_0.GetObjectRetention$).build() { + }; + var GetObjectTaggingCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareSdkS3.getThrow200ExceptionsPlugin(config3) + ]; + }).s("AmazonS3", "GetObjectTagging", {}).n("S3Client", "GetObjectTaggingCommand").sc(schemas_0.GetObjectTagging$).build() { + }; + var GetObjectTorrentCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions())]; + }).s("AmazonS3", "GetObjectTorrent", {}).n("S3Client", "GetObjectTorrentCommand").sc(schemas_0.GetObjectTorrent$).build() { + }; + var GetPublicAccessBlockCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareSdkS3.getThrow200ExceptionsPlugin(config3) + ]; + }).s("AmazonS3", "GetPublicAccessBlock", {}).n("S3Client", "GetPublicAccessBlockCommand").sc(schemas_0.GetPublicAccessBlock$).build() { + }; + var HeadBucketCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareSdkS3.getThrow200ExceptionsPlugin(config3) + ]; + }).s("AmazonS3", "HeadBucket", {}).n("S3Client", "HeadBucketCommand").sc(schemas_0.HeadBucket$).build() { + }; + var HeadObjectCommand2 = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + Bucket: { type: "contextParams", name: "Bucket" }, + Key: { type: "contextParams", name: "Key" } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareSdkS3.getThrow200ExceptionsPlugin(config3), + middlewareSsec.getSsecPlugin(config3), + middlewareSdkS3.getS3ExpiresMiddlewarePlugin(config3) + ]; + }).s("AmazonS3", "HeadObject", {}).n("S3Client", "HeadObjectCommand").sc(schemas_0.HeadObject$).build() { + }; + var ListBucketAnalyticsConfigurationsCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareSdkS3.getThrow200ExceptionsPlugin(config3) + ]; + }).s("AmazonS3", "ListBucketAnalyticsConfigurations", {}).n("S3Client", "ListBucketAnalyticsConfigurationsCommand").sc(schemas_0.ListBucketAnalyticsConfigurations$).build() { + }; + var ListBucketIntelligentTieringConfigurationsCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareSdkS3.getThrow200ExceptionsPlugin(config3) + ]; + }).s("AmazonS3", "ListBucketIntelligentTieringConfigurations", {}).n("S3Client", "ListBucketIntelligentTieringConfigurationsCommand").sc(schemas_0.ListBucketIntelligentTieringConfigurations$).build() { + }; + var ListBucketInventoryConfigurationsCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareSdkS3.getThrow200ExceptionsPlugin(config3) + ]; + }).s("AmazonS3", "ListBucketInventoryConfigurations", {}).n("S3Client", "ListBucketInventoryConfigurationsCommand").sc(schemas_0.ListBucketInventoryConfigurations$).build() { + }; + var ListBucketMetricsConfigurationsCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareSdkS3.getThrow200ExceptionsPlugin(config3) + ]; + }).s("AmazonS3", "ListBucketMetricsConfigurations", {}).n("S3Client", "ListBucketMetricsConfigurationsCommand").sc(schemas_0.ListBucketMetricsConfigurations$).build() { + }; + var ListBucketsCommand = class extends smithyClient.Command.classBuilder().ep(commonParams5).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareSdkS3.getThrow200ExceptionsPlugin(config3) + ]; + }).s("AmazonS3", "ListBuckets", {}).n("S3Client", "ListBucketsCommand").sc(schemas_0.ListBuckets$).build() { + }; + var ListDirectoryBucketsCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareSdkS3.getThrow200ExceptionsPlugin(config3) + ]; + }).s("AmazonS3", "ListDirectoryBuckets", {}).n("S3Client", "ListDirectoryBucketsCommand").sc(schemas_0.ListDirectoryBuckets$).build() { + }; + var ListMultipartUploadsCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + Bucket: { type: "contextParams", name: "Bucket" }, + Prefix: { type: "contextParams", name: "Prefix" } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareSdkS3.getThrow200ExceptionsPlugin(config3) + ]; + }).s("AmazonS3", "ListMultipartUploads", {}).n("S3Client", "ListMultipartUploadsCommand").sc(schemas_0.ListMultipartUploads$).build() { + }; + var ListObjectsCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + Bucket: { type: "contextParams", name: "Bucket" }, + Prefix: { type: "contextParams", name: "Prefix" } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareSdkS3.getThrow200ExceptionsPlugin(config3) + ]; + }).s("AmazonS3", "ListObjects", {}).n("S3Client", "ListObjectsCommand").sc(schemas_0.ListObjects$).build() { + }; + var ListObjectsV2Command = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + Bucket: { type: "contextParams", name: "Bucket" }, + Prefix: { type: "contextParams", name: "Prefix" } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareSdkS3.getThrow200ExceptionsPlugin(config3) + ]; + }).s("AmazonS3", "ListObjectsV2", {}).n("S3Client", "ListObjectsV2Command").sc(schemas_0.ListObjectsV2$).build() { + }; + var ListObjectVersionsCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + Bucket: { type: "contextParams", name: "Bucket" }, + Prefix: { type: "contextParams", name: "Prefix" } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareSdkS3.getThrow200ExceptionsPlugin(config3) + ]; + }).s("AmazonS3", "ListObjectVersions", {}).n("S3Client", "ListObjectVersionsCommand").sc(schemas_0.ListObjectVersions$).build() { + }; + var ListPartsCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + Bucket: { type: "contextParams", name: "Bucket" }, + Key: { type: "contextParams", name: "Key" } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareSdkS3.getThrow200ExceptionsPlugin(config3), + middlewareSsec.getSsecPlugin(config3) + ]; + }).s("AmazonS3", "ListParts", {}).n("S3Client", "ListPartsCommand").sc(schemas_0.ListParts$).build() { + }; + var PutBucketAbacCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareFlexibleChecksums.getFlexibleChecksumsPlugin(config3, { + requestAlgorithmMember: { "httpHeader": "x-amz-sdk-checksum-algorithm", "name": "ChecksumAlgorithm" }, + requestChecksumRequired: false + }) + ]; + }).s("AmazonS3", "PutBucketAbac", {}).n("S3Client", "PutBucketAbacCommand").sc(schemas_0.PutBucketAbac$).build() { + }; + var PutBucketAccelerateConfigurationCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareFlexibleChecksums.getFlexibleChecksumsPlugin(config3, { + requestAlgorithmMember: { "httpHeader": "x-amz-sdk-checksum-algorithm", "name": "ChecksumAlgorithm" }, + requestChecksumRequired: false + }) + ]; + }).s("AmazonS3", "PutBucketAccelerateConfiguration", {}).n("S3Client", "PutBucketAccelerateConfigurationCommand").sc(schemas_0.PutBucketAccelerateConfiguration$).build() { + }; + var PutBucketAclCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareFlexibleChecksums.getFlexibleChecksumsPlugin(config3, { + requestAlgorithmMember: { "httpHeader": "x-amz-sdk-checksum-algorithm", "name": "ChecksumAlgorithm" }, + requestChecksumRequired: true + }) + ]; + }).s("AmazonS3", "PutBucketAcl", {}).n("S3Client", "PutBucketAclCommand").sc(schemas_0.PutBucketAcl$).build() { + }; + var PutBucketAnalyticsConfigurationCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions())]; + }).s("AmazonS3", "PutBucketAnalyticsConfiguration", {}).n("S3Client", "PutBucketAnalyticsConfigurationCommand").sc(schemas_0.PutBucketAnalyticsConfiguration$).build() { + }; + var PutBucketCorsCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareFlexibleChecksums.getFlexibleChecksumsPlugin(config3, { + requestAlgorithmMember: { "httpHeader": "x-amz-sdk-checksum-algorithm", "name": "ChecksumAlgorithm" }, + requestChecksumRequired: true + }) + ]; + }).s("AmazonS3", "PutBucketCors", {}).n("S3Client", "PutBucketCorsCommand").sc(schemas_0.PutBucketCors$).build() { + }; + var PutBucketEncryptionCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareFlexibleChecksums.getFlexibleChecksumsPlugin(config3, { + requestAlgorithmMember: { "httpHeader": "x-amz-sdk-checksum-algorithm", "name": "ChecksumAlgorithm" }, + requestChecksumRequired: true + }) + ]; + }).s("AmazonS3", "PutBucketEncryption", {}).n("S3Client", "PutBucketEncryptionCommand").sc(schemas_0.PutBucketEncryption$).build() { + }; + var PutBucketIntelligentTieringConfigurationCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions())]; + }).s("AmazonS3", "PutBucketIntelligentTieringConfiguration", {}).n("S3Client", "PutBucketIntelligentTieringConfigurationCommand").sc(schemas_0.PutBucketIntelligentTieringConfiguration$).build() { + }; + var PutBucketInventoryConfigurationCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions())]; + }).s("AmazonS3", "PutBucketInventoryConfiguration", {}).n("S3Client", "PutBucketInventoryConfigurationCommand").sc(schemas_0.PutBucketInventoryConfiguration$).build() { + }; + var PutBucketLifecycleConfigurationCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareFlexibleChecksums.getFlexibleChecksumsPlugin(config3, { + requestAlgorithmMember: { "httpHeader": "x-amz-sdk-checksum-algorithm", "name": "ChecksumAlgorithm" }, + requestChecksumRequired: true + }), + middlewareSdkS3.getThrow200ExceptionsPlugin(config3) + ]; + }).s("AmazonS3", "PutBucketLifecycleConfiguration", {}).n("S3Client", "PutBucketLifecycleConfigurationCommand").sc(schemas_0.PutBucketLifecycleConfiguration$).build() { + }; + var PutBucketLoggingCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareFlexibleChecksums.getFlexibleChecksumsPlugin(config3, { + requestAlgorithmMember: { "httpHeader": "x-amz-sdk-checksum-algorithm", "name": "ChecksumAlgorithm" }, + requestChecksumRequired: true + }) + ]; + }).s("AmazonS3", "PutBucketLogging", {}).n("S3Client", "PutBucketLoggingCommand").sc(schemas_0.PutBucketLogging$).build() { + }; + var PutBucketMetricsConfigurationCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions())]; + }).s("AmazonS3", "PutBucketMetricsConfiguration", {}).n("S3Client", "PutBucketMetricsConfigurationCommand").sc(schemas_0.PutBucketMetricsConfiguration$).build() { + }; + var PutBucketNotificationConfigurationCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions())]; + }).s("AmazonS3", "PutBucketNotificationConfiguration", {}).n("S3Client", "PutBucketNotificationConfigurationCommand").sc(schemas_0.PutBucketNotificationConfiguration$).build() { + }; + var PutBucketOwnershipControlsCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareFlexibleChecksums.getFlexibleChecksumsPlugin(config3, { + requestAlgorithmMember: { "httpHeader": "x-amz-sdk-checksum-algorithm", "name": "ChecksumAlgorithm" }, + requestChecksumRequired: true + }) + ]; + }).s("AmazonS3", "PutBucketOwnershipControls", {}).n("S3Client", "PutBucketOwnershipControlsCommand").sc(schemas_0.PutBucketOwnershipControls$).build() { + }; + var PutBucketPolicyCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareFlexibleChecksums.getFlexibleChecksumsPlugin(config3, { + requestAlgorithmMember: { "httpHeader": "x-amz-sdk-checksum-algorithm", "name": "ChecksumAlgorithm" }, + requestChecksumRequired: true + }) + ]; + }).s("AmazonS3", "PutBucketPolicy", {}).n("S3Client", "PutBucketPolicyCommand").sc(schemas_0.PutBucketPolicy$).build() { + }; + var PutBucketReplicationCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareFlexibleChecksums.getFlexibleChecksumsPlugin(config3, { + requestAlgorithmMember: { "httpHeader": "x-amz-sdk-checksum-algorithm", "name": "ChecksumAlgorithm" }, + requestChecksumRequired: true + }) + ]; + }).s("AmazonS3", "PutBucketReplication", {}).n("S3Client", "PutBucketReplicationCommand").sc(schemas_0.PutBucketReplication$).build() { + }; + var PutBucketRequestPaymentCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareFlexibleChecksums.getFlexibleChecksumsPlugin(config3, { + requestAlgorithmMember: { "httpHeader": "x-amz-sdk-checksum-algorithm", "name": "ChecksumAlgorithm" }, + requestChecksumRequired: true + }) + ]; + }).s("AmazonS3", "PutBucketRequestPayment", {}).n("S3Client", "PutBucketRequestPaymentCommand").sc(schemas_0.PutBucketRequestPayment$).build() { + }; + var PutBucketTaggingCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareFlexibleChecksums.getFlexibleChecksumsPlugin(config3, { + requestAlgorithmMember: { "httpHeader": "x-amz-sdk-checksum-algorithm", "name": "ChecksumAlgorithm" }, + requestChecksumRequired: true + }) + ]; + }).s("AmazonS3", "PutBucketTagging", {}).n("S3Client", "PutBucketTaggingCommand").sc(schemas_0.PutBucketTagging$).build() { + }; + var PutBucketVersioningCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareFlexibleChecksums.getFlexibleChecksumsPlugin(config3, { + requestAlgorithmMember: { "httpHeader": "x-amz-sdk-checksum-algorithm", "name": "ChecksumAlgorithm" }, + requestChecksumRequired: true + }) + ]; + }).s("AmazonS3", "PutBucketVersioning", {}).n("S3Client", "PutBucketVersioningCommand").sc(schemas_0.PutBucketVersioning$).build() { + }; + var PutBucketWebsiteCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareFlexibleChecksums.getFlexibleChecksumsPlugin(config3, { + requestAlgorithmMember: { "httpHeader": "x-amz-sdk-checksum-algorithm", "name": "ChecksumAlgorithm" }, + requestChecksumRequired: true + }) + ]; + }).s("AmazonS3", "PutBucketWebsite", {}).n("S3Client", "PutBucketWebsiteCommand").sc(schemas_0.PutBucketWebsite$).build() { + }; + var PutObjectAclCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + Bucket: { type: "contextParams", name: "Bucket" }, + Key: { type: "contextParams", name: "Key" } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareFlexibleChecksums.getFlexibleChecksumsPlugin(config3, { + requestAlgorithmMember: { "httpHeader": "x-amz-sdk-checksum-algorithm", "name": "ChecksumAlgorithm" }, + requestChecksumRequired: true + }), + middlewareSdkS3.getThrow200ExceptionsPlugin(config3) + ]; + }).s("AmazonS3", "PutObjectAcl", {}).n("S3Client", "PutObjectAclCommand").sc(schemas_0.PutObjectAcl$).build() { + }; + var PutObjectCommand2 = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + Bucket: { type: "contextParams", name: "Bucket" }, + Key: { type: "contextParams", name: "Key" } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareFlexibleChecksums.getFlexibleChecksumsPlugin(config3, { + requestAlgorithmMember: { "httpHeader": "x-amz-sdk-checksum-algorithm", "name": "ChecksumAlgorithm" }, + requestChecksumRequired: false + }), + middlewareSdkS3.getCheckContentLengthHeaderPlugin(config3), + middlewareSdkS3.getThrow200ExceptionsPlugin(config3), + middlewareSsec.getSsecPlugin(config3) + ]; + }).s("AmazonS3", "PutObject", {}).n("S3Client", "PutObjectCommand").sc(schemas_0.PutObject$).build() { + }; + var PutObjectLegalHoldCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareFlexibleChecksums.getFlexibleChecksumsPlugin(config3, { + requestAlgorithmMember: { "httpHeader": "x-amz-sdk-checksum-algorithm", "name": "ChecksumAlgorithm" }, + requestChecksumRequired: true + }), + middlewareSdkS3.getThrow200ExceptionsPlugin(config3) + ]; + }).s("AmazonS3", "PutObjectLegalHold", {}).n("S3Client", "PutObjectLegalHoldCommand").sc(schemas_0.PutObjectLegalHold$).build() { + }; + var PutObjectLockConfigurationCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareFlexibleChecksums.getFlexibleChecksumsPlugin(config3, { + requestAlgorithmMember: { "httpHeader": "x-amz-sdk-checksum-algorithm", "name": "ChecksumAlgorithm" }, + requestChecksumRequired: true + }), + middlewareSdkS3.getThrow200ExceptionsPlugin(config3) + ]; + }).s("AmazonS3", "PutObjectLockConfiguration", {}).n("S3Client", "PutObjectLockConfigurationCommand").sc(schemas_0.PutObjectLockConfiguration$).build() { + }; + var PutObjectRetentionCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareFlexibleChecksums.getFlexibleChecksumsPlugin(config3, { + requestAlgorithmMember: { "httpHeader": "x-amz-sdk-checksum-algorithm", "name": "ChecksumAlgorithm" }, + requestChecksumRequired: true + }), + middlewareSdkS3.getThrow200ExceptionsPlugin(config3) + ]; + }).s("AmazonS3", "PutObjectRetention", {}).n("S3Client", "PutObjectRetentionCommand").sc(schemas_0.PutObjectRetention$).build() { + }; + var PutObjectTaggingCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareFlexibleChecksums.getFlexibleChecksumsPlugin(config3, { + requestAlgorithmMember: { "httpHeader": "x-amz-sdk-checksum-algorithm", "name": "ChecksumAlgorithm" }, + requestChecksumRequired: true + }), + middlewareSdkS3.getThrow200ExceptionsPlugin(config3) + ]; + }).s("AmazonS3", "PutObjectTagging", {}).n("S3Client", "PutObjectTaggingCommand").sc(schemas_0.PutObjectTagging$).build() { + }; + var PutPublicAccessBlockCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareFlexibleChecksums.getFlexibleChecksumsPlugin(config3, { + requestAlgorithmMember: { "httpHeader": "x-amz-sdk-checksum-algorithm", "name": "ChecksumAlgorithm" }, + requestChecksumRequired: true + }) + ]; + }).s("AmazonS3", "PutPublicAccessBlock", {}).n("S3Client", "PutPublicAccessBlockCommand").sc(schemas_0.PutPublicAccessBlock$).build() { + }; + var RenameObjectCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + Bucket: { type: "contextParams", name: "Bucket" }, + Key: { type: "contextParams", name: "Key" } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareSdkS3.getThrow200ExceptionsPlugin(config3) + ]; + }).s("AmazonS3", "RenameObject", {}).n("S3Client", "RenameObjectCommand").sc(schemas_0.RenameObject$).build() { + }; + var RestoreObjectCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareFlexibleChecksums.getFlexibleChecksumsPlugin(config3, { + requestAlgorithmMember: { "httpHeader": "x-amz-sdk-checksum-algorithm", "name": "ChecksumAlgorithm" }, + requestChecksumRequired: false + }), + middlewareSdkS3.getThrow200ExceptionsPlugin(config3) + ]; + }).s("AmazonS3", "RestoreObject", {}).n("S3Client", "RestoreObjectCommand").sc(schemas_0.RestoreObject$).build() { + }; + var SelectObjectContentCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareSdkS3.getThrow200ExceptionsPlugin(config3), + middlewareSsec.getSsecPlugin(config3) + ]; + }).s("AmazonS3", "SelectObjectContent", { + eventStream: { + output: true + } + }).n("S3Client", "SelectObjectContentCommand").sc(schemas_0.SelectObjectContent$).build() { + }; + var UpdateBucketMetadataInventoryTableConfigurationCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareFlexibleChecksums.getFlexibleChecksumsPlugin(config3, { + requestAlgorithmMember: { "httpHeader": "x-amz-sdk-checksum-algorithm", "name": "ChecksumAlgorithm" }, + requestChecksumRequired: true + }) + ]; + }).s("AmazonS3", "UpdateBucketMetadataInventoryTableConfiguration", {}).n("S3Client", "UpdateBucketMetadataInventoryTableConfigurationCommand").sc(schemas_0.UpdateBucketMetadataInventoryTableConfiguration$).build() { + }; + var UpdateBucketMetadataJournalTableConfigurationCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareFlexibleChecksums.getFlexibleChecksumsPlugin(config3, { + requestAlgorithmMember: { "httpHeader": "x-amz-sdk-checksum-algorithm", "name": "ChecksumAlgorithm" }, + requestChecksumRequired: true + }) + ]; + }).s("AmazonS3", "UpdateBucketMetadataJournalTableConfiguration", {}).n("S3Client", "UpdateBucketMetadataJournalTableConfigurationCommand").sc(schemas_0.UpdateBucketMetadataJournalTableConfiguration$).build() { + }; + var UpdateObjectEncryptionCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareFlexibleChecksums.getFlexibleChecksumsPlugin(config3, { + requestAlgorithmMember: { "httpHeader": "x-amz-sdk-checksum-algorithm", "name": "ChecksumAlgorithm" }, + requestChecksumRequired: true + }), + middlewareSdkS3.getThrow200ExceptionsPlugin(config3) + ]; + }).s("AmazonS3", "UpdateObjectEncryption", {}).n("S3Client", "UpdateObjectEncryptionCommand").sc(schemas_0.UpdateObjectEncryption$).build() { + }; + var UploadPartCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + Bucket: { type: "contextParams", name: "Bucket" }, + Key: { type: "contextParams", name: "Key" } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareFlexibleChecksums.getFlexibleChecksumsPlugin(config3, { + requestAlgorithmMember: { "httpHeader": "x-amz-sdk-checksum-algorithm", "name": "ChecksumAlgorithm" }, + requestChecksumRequired: false + }), + middlewareSdkS3.getThrow200ExceptionsPlugin(config3), + middlewareSsec.getSsecPlugin(config3) + ]; + }).s("AmazonS3", "UploadPart", {}).n("S3Client", "UploadPartCommand").sc(schemas_0.UploadPart$).build() { + }; + var UploadPartCopyCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + DisableS3ExpressSessionAuth: { type: "staticContextParams", value: true }, + Bucket: { type: "contextParams", name: "Bucket" } + }).m(function(Command2, cs, config3, o5) { + return [ + middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), + middlewareSdkS3.getThrow200ExceptionsPlugin(config3), + middlewareSsec.getSsecPlugin(config3) + ]; + }).s("AmazonS3", "UploadPartCopy", {}).n("S3Client", "UploadPartCopyCommand").sc(schemas_0.UploadPartCopy$).build() { + }; + var WriteGetObjectResponseCommand = class extends smithyClient.Command.classBuilder().ep({ + ...commonParams5, + UseObjectLambdaEndpoint: { type: "staticContextParams", value: true } + }).m(function(Command2, cs, config3, o5) { + return [middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions())]; + }).s("AmazonS3", "WriteGetObjectResponse", {}).n("S3Client", "WriteGetObjectResponseCommand").sc(schemas_0.WriteGetObjectResponse$).build() { + }; + var paginateListBuckets = core.createPaginator(S3Client2, ListBucketsCommand, "ContinuationToken", "ContinuationToken", "MaxBuckets"); + var paginateListDirectoryBuckets = core.createPaginator(S3Client2, ListDirectoryBucketsCommand, "ContinuationToken", "ContinuationToken", "MaxDirectoryBuckets"); + var paginateListObjectsV2 = core.createPaginator(S3Client2, ListObjectsV2Command, "ContinuationToken", "NextContinuationToken", "MaxKeys"); + var paginateListParts = core.createPaginator(S3Client2, ListPartsCommand, "PartNumberMarker", "NextPartNumberMarker", "MaxParts"); + var checkState$3 = async (client2, input) => { + let reason; + try { + let result = await client2.send(new HeadBucketCommand(input)); + reason = result; + return { state: utilWaiter.WaiterState.SUCCESS, reason }; + } catch (exception) { + reason = exception; + if (exception.name && exception.name == "NotFound") { + return { state: utilWaiter.WaiterState.RETRY, reason }; + } + } + return { state: utilWaiter.WaiterState.RETRY, reason }; + }; + var waitForBucketExists = async (params, input) => { + const serviceDefaults = { minDelay: 5, maxDelay: 120 }; + return utilWaiter.createWaiter({ ...serviceDefaults, ...params }, input, checkState$3); + }; + var waitUntilBucketExists = async (params, input) => { + const serviceDefaults = { minDelay: 5, maxDelay: 120 }; + const result = await utilWaiter.createWaiter({ ...serviceDefaults, ...params }, input, checkState$3); + return utilWaiter.checkExceptions(result); + }; + var checkState$2 = async (client2, input) => { + let reason; + try { + let result = await client2.send(new HeadBucketCommand(input)); + reason = result; + } catch (exception) { + reason = exception; + if (exception.name && exception.name == "NotFound") { + return { state: utilWaiter.WaiterState.SUCCESS, reason }; + } + } + return { state: utilWaiter.WaiterState.RETRY, reason }; + }; + var waitForBucketNotExists = async (params, input) => { + const serviceDefaults = { minDelay: 5, maxDelay: 120 }; + return utilWaiter.createWaiter({ ...serviceDefaults, ...params }, input, checkState$2); + }; + var waitUntilBucketNotExists = async (params, input) => { + const serviceDefaults = { minDelay: 5, maxDelay: 120 }; + const result = await utilWaiter.createWaiter({ ...serviceDefaults, ...params }, input, checkState$2); + return utilWaiter.checkExceptions(result); + }; + var checkState$1 = async (client2, input) => { + let reason; + try { + let result = await client2.send(new HeadObjectCommand2(input)); + reason = result; + return { state: utilWaiter.WaiterState.SUCCESS, reason }; + } catch (exception) { + reason = exception; + if (exception.name && exception.name == "NotFound") { + return { state: utilWaiter.WaiterState.RETRY, reason }; + } + } + return { state: utilWaiter.WaiterState.RETRY, reason }; + }; + var waitForObjectExists = async (params, input) => { + const serviceDefaults = { minDelay: 5, maxDelay: 120 }; + return utilWaiter.createWaiter({ ...serviceDefaults, ...params }, input, checkState$1); + }; + var waitUntilObjectExists = async (params, input) => { + const serviceDefaults = { minDelay: 5, maxDelay: 120 }; + const result = await utilWaiter.createWaiter({ ...serviceDefaults, ...params }, input, checkState$1); + return utilWaiter.checkExceptions(result); + }; + var checkState = async (client2, input) => { + let reason; + try { + let result = await client2.send(new HeadObjectCommand2(input)); + reason = result; + } catch (exception) { + reason = exception; + if (exception.name && exception.name == "NotFound") { + return { state: utilWaiter.WaiterState.SUCCESS, reason }; + } + } + return { state: utilWaiter.WaiterState.RETRY, reason }; + }; + var waitForObjectNotExists = async (params, input) => { + const serviceDefaults = { minDelay: 5, maxDelay: 120 }; + return utilWaiter.createWaiter({ ...serviceDefaults, ...params }, input, checkState); + }; + var waitUntilObjectNotExists = async (params, input) => { + const serviceDefaults = { minDelay: 5, maxDelay: 120 }; + const result = await utilWaiter.createWaiter({ ...serviceDefaults, ...params }, input, checkState); + return utilWaiter.checkExceptions(result); + }; + var commands5 = { + AbortMultipartUploadCommand, + CompleteMultipartUploadCommand, + CopyObjectCommand, + CreateBucketCommand, + CreateBucketMetadataConfigurationCommand, + CreateBucketMetadataTableConfigurationCommand, + CreateMultipartUploadCommand, + CreateSessionCommand, + DeleteBucketCommand, + DeleteBucketAnalyticsConfigurationCommand, + DeleteBucketCorsCommand, + DeleteBucketEncryptionCommand, + DeleteBucketIntelligentTieringConfigurationCommand, + DeleteBucketInventoryConfigurationCommand, + DeleteBucketLifecycleCommand, + DeleteBucketMetadataConfigurationCommand, + DeleteBucketMetadataTableConfigurationCommand, + DeleteBucketMetricsConfigurationCommand, + DeleteBucketOwnershipControlsCommand, + DeleteBucketPolicyCommand, + DeleteBucketReplicationCommand, + DeleteBucketTaggingCommand, + DeleteBucketWebsiteCommand, + DeleteObjectCommand: DeleteObjectCommand2, + DeleteObjectsCommand, + DeleteObjectTaggingCommand, + DeletePublicAccessBlockCommand, + GetBucketAbacCommand, + GetBucketAccelerateConfigurationCommand, + GetBucketAclCommand, + GetBucketAnalyticsConfigurationCommand, + GetBucketCorsCommand, + GetBucketEncryptionCommand, + GetBucketIntelligentTieringConfigurationCommand, + GetBucketInventoryConfigurationCommand, + GetBucketLifecycleConfigurationCommand, + GetBucketLocationCommand, + GetBucketLoggingCommand, + GetBucketMetadataConfigurationCommand, + GetBucketMetadataTableConfigurationCommand, + GetBucketMetricsConfigurationCommand, + GetBucketNotificationConfigurationCommand, + GetBucketOwnershipControlsCommand, + GetBucketPolicyCommand, + GetBucketPolicyStatusCommand, + GetBucketReplicationCommand, + GetBucketRequestPaymentCommand, + GetBucketTaggingCommand, + GetBucketVersioningCommand, + GetBucketWebsiteCommand, + GetObjectCommand: GetObjectCommand2, + GetObjectAclCommand, + GetObjectAttributesCommand, + GetObjectLegalHoldCommand, + GetObjectLockConfigurationCommand, + GetObjectRetentionCommand, + GetObjectTaggingCommand, + GetObjectTorrentCommand, + GetPublicAccessBlockCommand, + HeadBucketCommand, + HeadObjectCommand: HeadObjectCommand2, + ListBucketAnalyticsConfigurationsCommand, + ListBucketIntelligentTieringConfigurationsCommand, + ListBucketInventoryConfigurationsCommand, + ListBucketMetricsConfigurationsCommand, + ListBucketsCommand, + ListDirectoryBucketsCommand, + ListMultipartUploadsCommand, + ListObjectsCommand, + ListObjectsV2Command, + ListObjectVersionsCommand, + ListPartsCommand, + PutBucketAbacCommand, + PutBucketAccelerateConfigurationCommand, + PutBucketAclCommand, + PutBucketAnalyticsConfigurationCommand, + PutBucketCorsCommand, + PutBucketEncryptionCommand, + PutBucketIntelligentTieringConfigurationCommand, + PutBucketInventoryConfigurationCommand, + PutBucketLifecycleConfigurationCommand, + PutBucketLoggingCommand, + PutBucketMetricsConfigurationCommand, + PutBucketNotificationConfigurationCommand, + PutBucketOwnershipControlsCommand, + PutBucketPolicyCommand, + PutBucketReplicationCommand, + PutBucketRequestPaymentCommand, + PutBucketTaggingCommand, + PutBucketVersioningCommand, + PutBucketWebsiteCommand, + PutObjectCommand: PutObjectCommand2, + PutObjectAclCommand, + PutObjectLegalHoldCommand, + PutObjectLockConfigurationCommand, + PutObjectRetentionCommand, + PutObjectTaggingCommand, + PutPublicAccessBlockCommand, + RenameObjectCommand, + RestoreObjectCommand, + SelectObjectContentCommand, + UpdateBucketMetadataInventoryTableConfigurationCommand, + UpdateBucketMetadataJournalTableConfigurationCommand, + UpdateObjectEncryptionCommand, + UploadPartCommand, + UploadPartCopyCommand, + WriteGetObjectResponseCommand + }; + var paginators = { + paginateListBuckets, + paginateListDirectoryBuckets, + paginateListObjectsV2, + paginateListParts + }; + var waiters = { + waitUntilBucketExists, + waitUntilBucketNotExists, + waitUntilObjectExists, + waitUntilObjectNotExists + }; + var S3 = class extends S3Client2 { + }; + smithyClient.createAggregatedClient(commands5, S3, { paginators, waiters }); + var BucketAbacStatus = { + Disabled: "Disabled", + Enabled: "Enabled" + }; + var RequestCharged = { + requester: "requester" + }; + var RequestPayer = { + requester: "requester" + }; + var BucketAccelerateStatus = { + Enabled: "Enabled", + Suspended: "Suspended" + }; + var Type = { + AmazonCustomerByEmail: "AmazonCustomerByEmail", + CanonicalUser: "CanonicalUser", + Group: "Group" + }; + var Permission = { + FULL_CONTROL: "FULL_CONTROL", + READ: "READ", + READ_ACP: "READ_ACP", + WRITE: "WRITE", + WRITE_ACP: "WRITE_ACP" + }; + var OwnerOverride = { + Destination: "Destination" + }; + var ChecksumType = { + COMPOSITE: "COMPOSITE", + FULL_OBJECT: "FULL_OBJECT" + }; + var ServerSideEncryption = { + AES256: "AES256", + aws_fsx: "aws:fsx", + aws_kms: "aws:kms", + aws_kms_dsse: "aws:kms:dsse" + }; + var ObjectCannedACL = { + authenticated_read: "authenticated-read", + aws_exec_read: "aws-exec-read", + bucket_owner_full_control: "bucket-owner-full-control", + bucket_owner_read: "bucket-owner-read", + private: "private", + public_read: "public-read", + public_read_write: "public-read-write" + }; + var ChecksumAlgorithm = { + CRC32: "CRC32", + CRC32C: "CRC32C", + CRC64NVME: "CRC64NVME", + SHA1: "SHA1", + SHA256: "SHA256" + }; + var MetadataDirective = { + COPY: "COPY", + REPLACE: "REPLACE" + }; + var ObjectLockLegalHoldStatus = { + OFF: "OFF", + ON: "ON" + }; + var ObjectLockMode = { + COMPLIANCE: "COMPLIANCE", + GOVERNANCE: "GOVERNANCE" + }; + var StorageClass = { + DEEP_ARCHIVE: "DEEP_ARCHIVE", + EXPRESS_ONEZONE: "EXPRESS_ONEZONE", + FSX_ONTAP: "FSX_ONTAP", + FSX_OPENZFS: "FSX_OPENZFS", + GLACIER: "GLACIER", + GLACIER_IR: "GLACIER_IR", + INTELLIGENT_TIERING: "INTELLIGENT_TIERING", + ONEZONE_IA: "ONEZONE_IA", + OUTPOSTS: "OUTPOSTS", + REDUCED_REDUNDANCY: "REDUCED_REDUNDANCY", + SNOW: "SNOW", + STANDARD: "STANDARD", + STANDARD_IA: "STANDARD_IA" + }; + var TaggingDirective = { + COPY: "COPY", + REPLACE: "REPLACE" + }; + var BucketCannedACL = { + authenticated_read: "authenticated-read", + private: "private", + public_read: "public-read", + public_read_write: "public-read-write" + }; + var BucketNamespace = { + ACCOUNT_REGIONAL: "account-regional", + GLOBAL: "global" + }; + var DataRedundancy = { + SingleAvailabilityZone: "SingleAvailabilityZone", + SingleLocalZone: "SingleLocalZone" + }; + var BucketType = { + Directory: "Directory" + }; + var LocationType = { + AvailabilityZone: "AvailabilityZone", + LocalZone: "LocalZone" + }; + var BucketLocationConstraint = { + EU: "EU", + af_south_1: "af-south-1", + ap_east_1: "ap-east-1", + ap_east_2: "ap-east-2", + ap_northeast_1: "ap-northeast-1", + ap_northeast_2: "ap-northeast-2", + ap_northeast_3: "ap-northeast-3", + ap_south_1: "ap-south-1", + ap_south_2: "ap-south-2", + ap_southeast_1: "ap-southeast-1", + ap_southeast_2: "ap-southeast-2", + ap_southeast_3: "ap-southeast-3", + ap_southeast_4: "ap-southeast-4", + ap_southeast_5: "ap-southeast-5", + ap_southeast_6: "ap-southeast-6", + ap_southeast_7: "ap-southeast-7", + ca_central_1: "ca-central-1", + ca_west_1: "ca-west-1", + cn_north_1: "cn-north-1", + cn_northwest_1: "cn-northwest-1", + eu_central_1: "eu-central-1", + eu_central_2: "eu-central-2", + eu_north_1: "eu-north-1", + eu_south_1: "eu-south-1", + eu_south_2: "eu-south-2", + eu_west_1: "eu-west-1", + eu_west_2: "eu-west-2", + eu_west_3: "eu-west-3", + il_central_1: "il-central-1", + me_central_1: "me-central-1", + me_south_1: "me-south-1", + mx_central_1: "mx-central-1", + sa_east_1: "sa-east-1", + us_east_2: "us-east-2", + us_gov_east_1: "us-gov-east-1", + us_gov_west_1: "us-gov-west-1", + us_west_1: "us-west-1", + us_west_2: "us-west-2" + }; + var ObjectOwnership = { + BucketOwnerEnforced: "BucketOwnerEnforced", + BucketOwnerPreferred: "BucketOwnerPreferred", + ObjectWriter: "ObjectWriter" + }; + var InventoryConfigurationState = { + DISABLED: "DISABLED", + ENABLED: "ENABLED" + }; + var TableSseAlgorithm = { + AES256: "AES256", + aws_kms: "aws:kms" + }; + var ExpirationState = { + DISABLED: "DISABLED", + ENABLED: "ENABLED" + }; + var SessionMode = { + ReadOnly: "ReadOnly", + ReadWrite: "ReadWrite" + }; + var AnalyticsS3ExportFileFormat = { + CSV: "CSV" + }; + var StorageClassAnalysisSchemaVersion = { + V_1: "V_1" + }; + var EncryptionType = { + NONE: "NONE", + SSE_C: "SSE-C" + }; + var IntelligentTieringStatus = { + Disabled: "Disabled", + Enabled: "Enabled" + }; + var IntelligentTieringAccessTier = { + ARCHIVE_ACCESS: "ARCHIVE_ACCESS", + DEEP_ARCHIVE_ACCESS: "DEEP_ARCHIVE_ACCESS" + }; + var InventoryFormat = { + CSV: "CSV", + ORC: "ORC", + Parquet: "Parquet" + }; + var InventoryIncludedObjectVersions = { + All: "All", + Current: "Current" + }; + var InventoryOptionalField = { + BucketKeyStatus: "BucketKeyStatus", + ChecksumAlgorithm: "ChecksumAlgorithm", + ETag: "ETag", + EncryptionStatus: "EncryptionStatus", + IntelligentTieringAccessTier: "IntelligentTieringAccessTier", + IsMultipartUploaded: "IsMultipartUploaded", + LastModifiedDate: "LastModifiedDate", + LifecycleExpirationDate: "LifecycleExpirationDate", + ObjectAccessControlList: "ObjectAccessControlList", + ObjectLockLegalHoldStatus: "ObjectLockLegalHoldStatus", + ObjectLockMode: "ObjectLockMode", + ObjectLockRetainUntilDate: "ObjectLockRetainUntilDate", + ObjectOwner: "ObjectOwner", + ReplicationStatus: "ReplicationStatus", + Size: "Size", + StorageClass: "StorageClass" + }; + var InventoryFrequency = { + Daily: "Daily", + Weekly: "Weekly" + }; + var TransitionStorageClass = { + DEEP_ARCHIVE: "DEEP_ARCHIVE", + GLACIER: "GLACIER", + GLACIER_IR: "GLACIER_IR", + INTELLIGENT_TIERING: "INTELLIGENT_TIERING", + ONEZONE_IA: "ONEZONE_IA", + STANDARD_IA: "STANDARD_IA" + }; + var ExpirationStatus = { + Disabled: "Disabled", + Enabled: "Enabled" + }; + var TransitionDefaultMinimumObjectSize = { + all_storage_classes_128K: "all_storage_classes_128K", + varies_by_storage_class: "varies_by_storage_class" + }; + var BucketLogsPermission = { + FULL_CONTROL: "FULL_CONTROL", + READ: "READ", + WRITE: "WRITE" + }; + var PartitionDateSource = { + DeliveryTime: "DeliveryTime", + EventTime: "EventTime" + }; + var S3TablesBucketType = { + aws: "aws", + customer: "customer" + }; + var Event = { + s3_IntelligentTiering: "s3:IntelligentTiering", + s3_LifecycleExpiration_: "s3:LifecycleExpiration:*", + s3_LifecycleExpiration_Delete: "s3:LifecycleExpiration:Delete", + s3_LifecycleExpiration_DeleteMarkerCreated: "s3:LifecycleExpiration:DeleteMarkerCreated", + s3_LifecycleTransition: "s3:LifecycleTransition", + s3_ObjectAcl_Put: "s3:ObjectAcl:Put", + s3_ObjectCreated_: "s3:ObjectCreated:*", + s3_ObjectCreated_CompleteMultipartUpload: "s3:ObjectCreated:CompleteMultipartUpload", + s3_ObjectCreated_Copy: "s3:ObjectCreated:Copy", + s3_ObjectCreated_Post: "s3:ObjectCreated:Post", + s3_ObjectCreated_Put: "s3:ObjectCreated:Put", + s3_ObjectRemoved_: "s3:ObjectRemoved:*", + s3_ObjectRemoved_Delete: "s3:ObjectRemoved:Delete", + s3_ObjectRemoved_DeleteMarkerCreated: "s3:ObjectRemoved:DeleteMarkerCreated", + s3_ObjectRestore_: "s3:ObjectRestore:*", + s3_ObjectRestore_Completed: "s3:ObjectRestore:Completed", + s3_ObjectRestore_Delete: "s3:ObjectRestore:Delete", + s3_ObjectRestore_Post: "s3:ObjectRestore:Post", + s3_ObjectTagging_: "s3:ObjectTagging:*", + s3_ObjectTagging_Delete: "s3:ObjectTagging:Delete", + s3_ObjectTagging_Put: "s3:ObjectTagging:Put", + s3_ReducedRedundancyLostObject: "s3:ReducedRedundancyLostObject", + s3_Replication_: "s3:Replication:*", + s3_Replication_OperationFailedReplication: "s3:Replication:OperationFailedReplication", + s3_Replication_OperationMissedThreshold: "s3:Replication:OperationMissedThreshold", + s3_Replication_OperationNotTracked: "s3:Replication:OperationNotTracked", + s3_Replication_OperationReplicatedAfterThreshold: "s3:Replication:OperationReplicatedAfterThreshold" + }; + var FilterRuleName = { + prefix: "prefix", + suffix: "suffix" + }; + var DeleteMarkerReplicationStatus = { + Disabled: "Disabled", + Enabled: "Enabled" + }; + var MetricsStatus = { + Disabled: "Disabled", + Enabled: "Enabled" + }; + var ReplicationTimeStatus = { + Disabled: "Disabled", + Enabled: "Enabled" + }; + var ExistingObjectReplicationStatus = { + Disabled: "Disabled", + Enabled: "Enabled" + }; + var ReplicaModificationsStatus = { + Disabled: "Disabled", + Enabled: "Enabled" + }; + var SseKmsEncryptedObjectsStatus = { + Disabled: "Disabled", + Enabled: "Enabled" + }; + var ReplicationRuleStatus = { + Disabled: "Disabled", + Enabled: "Enabled" + }; + var Payer = { + BucketOwner: "BucketOwner", + Requester: "Requester" + }; + var MFADeleteStatus = { + Disabled: "Disabled", + Enabled: "Enabled" + }; + var BucketVersioningStatus = { + Enabled: "Enabled", + Suspended: "Suspended" + }; + var Protocol = { + http: "http", + https: "https" + }; + var ReplicationStatus = { + COMPLETE: "COMPLETE", + COMPLETED: "COMPLETED", + FAILED: "FAILED", + PENDING: "PENDING", + REPLICA: "REPLICA" + }; + var ChecksumMode = { + ENABLED: "ENABLED" + }; + var ObjectAttributes = { + CHECKSUM: "Checksum", + ETAG: "ETag", + OBJECT_PARTS: "ObjectParts", + OBJECT_SIZE: "ObjectSize", + STORAGE_CLASS: "StorageClass" + }; + var ObjectLockEnabled = { + Enabled: "Enabled" + }; + var ObjectLockRetentionMode = { + COMPLIANCE: "COMPLIANCE", + GOVERNANCE: "GOVERNANCE" + }; + var ArchiveStatus = { + ARCHIVE_ACCESS: "ARCHIVE_ACCESS", + DEEP_ARCHIVE_ACCESS: "DEEP_ARCHIVE_ACCESS" + }; + var EncodingType = { + url: "url" + }; + var ObjectStorageClass = { + DEEP_ARCHIVE: "DEEP_ARCHIVE", + EXPRESS_ONEZONE: "EXPRESS_ONEZONE", + FSX_ONTAP: "FSX_ONTAP", + FSX_OPENZFS: "FSX_OPENZFS", + GLACIER: "GLACIER", + GLACIER_IR: "GLACIER_IR", + INTELLIGENT_TIERING: "INTELLIGENT_TIERING", + ONEZONE_IA: "ONEZONE_IA", + OUTPOSTS: "OUTPOSTS", + REDUCED_REDUNDANCY: "REDUCED_REDUNDANCY", + SNOW: "SNOW", + STANDARD: "STANDARD", + STANDARD_IA: "STANDARD_IA" + }; + var OptionalObjectAttributes = { + RESTORE_STATUS: "RestoreStatus" + }; + var ObjectVersionStorageClass = { + STANDARD: "STANDARD" + }; + var MFADelete = { + Disabled: "Disabled", + Enabled: "Enabled" + }; + var Tier = { + Bulk: "Bulk", + Expedited: "Expedited", + Standard: "Standard" + }; + var ExpressionType = { + SQL: "SQL" + }; + var CompressionType = { + BZIP2: "BZIP2", + GZIP: "GZIP", + NONE: "NONE" + }; + var FileHeaderInfo = { + IGNORE: "IGNORE", + NONE: "NONE", + USE: "USE" + }; + var JSONType = { + DOCUMENT: "DOCUMENT", + LINES: "LINES" + }; + var QuoteFields = { + ALWAYS: "ALWAYS", + ASNEEDED: "ASNEEDED" + }; + var RestoreRequestType = { + SELECT: "SELECT" + }; + exports.$Command = smithyClient.Command; + exports.__Client = smithyClient.Client; + exports.S3ServiceException = S3ServiceException.S3ServiceException; + exports.AbortMultipartUploadCommand = AbortMultipartUploadCommand; + exports.AnalyticsS3ExportFileFormat = AnalyticsS3ExportFileFormat; + exports.ArchiveStatus = ArchiveStatus; + exports.BucketAbacStatus = BucketAbacStatus; + exports.BucketAccelerateStatus = BucketAccelerateStatus; + exports.BucketCannedACL = BucketCannedACL; + exports.BucketLocationConstraint = BucketLocationConstraint; + exports.BucketLogsPermission = BucketLogsPermission; + exports.BucketNamespace = BucketNamespace; + exports.BucketType = BucketType; + exports.BucketVersioningStatus = BucketVersioningStatus; + exports.ChecksumAlgorithm = ChecksumAlgorithm; + exports.ChecksumMode = ChecksumMode; + exports.ChecksumType = ChecksumType; + exports.CompleteMultipartUploadCommand = CompleteMultipartUploadCommand; + exports.CompressionType = CompressionType; + exports.CopyObjectCommand = CopyObjectCommand; + exports.CreateBucketCommand = CreateBucketCommand; + exports.CreateBucketMetadataConfigurationCommand = CreateBucketMetadataConfigurationCommand; + exports.CreateBucketMetadataTableConfigurationCommand = CreateBucketMetadataTableConfigurationCommand; + exports.CreateMultipartUploadCommand = CreateMultipartUploadCommand; + exports.CreateSessionCommand = CreateSessionCommand; + exports.DataRedundancy = DataRedundancy; + exports.DeleteBucketAnalyticsConfigurationCommand = DeleteBucketAnalyticsConfigurationCommand; + exports.DeleteBucketCommand = DeleteBucketCommand; + exports.DeleteBucketCorsCommand = DeleteBucketCorsCommand; + exports.DeleteBucketEncryptionCommand = DeleteBucketEncryptionCommand; + exports.DeleteBucketIntelligentTieringConfigurationCommand = DeleteBucketIntelligentTieringConfigurationCommand; + exports.DeleteBucketInventoryConfigurationCommand = DeleteBucketInventoryConfigurationCommand; + exports.DeleteBucketLifecycleCommand = DeleteBucketLifecycleCommand; + exports.DeleteBucketMetadataConfigurationCommand = DeleteBucketMetadataConfigurationCommand; + exports.DeleteBucketMetadataTableConfigurationCommand = DeleteBucketMetadataTableConfigurationCommand; + exports.DeleteBucketMetricsConfigurationCommand = DeleteBucketMetricsConfigurationCommand; + exports.DeleteBucketOwnershipControlsCommand = DeleteBucketOwnershipControlsCommand; + exports.DeleteBucketPolicyCommand = DeleteBucketPolicyCommand; + exports.DeleteBucketReplicationCommand = DeleteBucketReplicationCommand; + exports.DeleteBucketTaggingCommand = DeleteBucketTaggingCommand; + exports.DeleteBucketWebsiteCommand = DeleteBucketWebsiteCommand; + exports.DeleteMarkerReplicationStatus = DeleteMarkerReplicationStatus; + exports.DeleteObjectCommand = DeleteObjectCommand2; + exports.DeleteObjectTaggingCommand = DeleteObjectTaggingCommand; + exports.DeleteObjectsCommand = DeleteObjectsCommand; + exports.DeletePublicAccessBlockCommand = DeletePublicAccessBlockCommand; + exports.EncodingType = EncodingType; + exports.EncryptionType = EncryptionType; + exports.Event = Event; + exports.ExistingObjectReplicationStatus = ExistingObjectReplicationStatus; + exports.ExpirationState = ExpirationState; + exports.ExpirationStatus = ExpirationStatus; + exports.ExpressionType = ExpressionType; + exports.FileHeaderInfo = FileHeaderInfo; + exports.FilterRuleName = FilterRuleName; + exports.GetBucketAbacCommand = GetBucketAbacCommand; + exports.GetBucketAccelerateConfigurationCommand = GetBucketAccelerateConfigurationCommand; + exports.GetBucketAclCommand = GetBucketAclCommand; + exports.GetBucketAnalyticsConfigurationCommand = GetBucketAnalyticsConfigurationCommand; + exports.GetBucketCorsCommand = GetBucketCorsCommand; + exports.GetBucketEncryptionCommand = GetBucketEncryptionCommand; + exports.GetBucketIntelligentTieringConfigurationCommand = GetBucketIntelligentTieringConfigurationCommand; + exports.GetBucketInventoryConfigurationCommand = GetBucketInventoryConfigurationCommand; + exports.GetBucketLifecycleConfigurationCommand = GetBucketLifecycleConfigurationCommand; + exports.GetBucketLocationCommand = GetBucketLocationCommand; + exports.GetBucketLoggingCommand = GetBucketLoggingCommand; + exports.GetBucketMetadataConfigurationCommand = GetBucketMetadataConfigurationCommand; + exports.GetBucketMetadataTableConfigurationCommand = GetBucketMetadataTableConfigurationCommand; + exports.GetBucketMetricsConfigurationCommand = GetBucketMetricsConfigurationCommand; + exports.GetBucketNotificationConfigurationCommand = GetBucketNotificationConfigurationCommand; + exports.GetBucketOwnershipControlsCommand = GetBucketOwnershipControlsCommand; + exports.GetBucketPolicyCommand = GetBucketPolicyCommand; + exports.GetBucketPolicyStatusCommand = GetBucketPolicyStatusCommand; + exports.GetBucketReplicationCommand = GetBucketReplicationCommand; + exports.GetBucketRequestPaymentCommand = GetBucketRequestPaymentCommand; + exports.GetBucketTaggingCommand = GetBucketTaggingCommand; + exports.GetBucketVersioningCommand = GetBucketVersioningCommand; + exports.GetBucketWebsiteCommand = GetBucketWebsiteCommand; + exports.GetObjectAclCommand = GetObjectAclCommand; + exports.GetObjectAttributesCommand = GetObjectAttributesCommand; + exports.GetObjectCommand = GetObjectCommand2; + exports.GetObjectLegalHoldCommand = GetObjectLegalHoldCommand; + exports.GetObjectLockConfigurationCommand = GetObjectLockConfigurationCommand; + exports.GetObjectRetentionCommand = GetObjectRetentionCommand; + exports.GetObjectTaggingCommand = GetObjectTaggingCommand; + exports.GetObjectTorrentCommand = GetObjectTorrentCommand; + exports.GetPublicAccessBlockCommand = GetPublicAccessBlockCommand; + exports.HeadBucketCommand = HeadBucketCommand; + exports.HeadObjectCommand = HeadObjectCommand2; + exports.IntelligentTieringAccessTier = IntelligentTieringAccessTier; + exports.IntelligentTieringStatus = IntelligentTieringStatus; + exports.InventoryConfigurationState = InventoryConfigurationState; + exports.InventoryFormat = InventoryFormat; + exports.InventoryFrequency = InventoryFrequency; + exports.InventoryIncludedObjectVersions = InventoryIncludedObjectVersions; + exports.InventoryOptionalField = InventoryOptionalField; + exports.JSONType = JSONType; + exports.ListBucketAnalyticsConfigurationsCommand = ListBucketAnalyticsConfigurationsCommand; + exports.ListBucketIntelligentTieringConfigurationsCommand = ListBucketIntelligentTieringConfigurationsCommand; + exports.ListBucketInventoryConfigurationsCommand = ListBucketInventoryConfigurationsCommand; + exports.ListBucketMetricsConfigurationsCommand = ListBucketMetricsConfigurationsCommand; + exports.ListBucketsCommand = ListBucketsCommand; + exports.ListDirectoryBucketsCommand = ListDirectoryBucketsCommand; + exports.ListMultipartUploadsCommand = ListMultipartUploadsCommand; + exports.ListObjectVersionsCommand = ListObjectVersionsCommand; + exports.ListObjectsCommand = ListObjectsCommand; + exports.ListObjectsV2Command = ListObjectsV2Command; + exports.ListPartsCommand = ListPartsCommand; + exports.LocationType = LocationType; + exports.MFADelete = MFADelete; + exports.MFADeleteStatus = MFADeleteStatus; + exports.MetadataDirective = MetadataDirective; + exports.MetricsStatus = MetricsStatus; + exports.ObjectAttributes = ObjectAttributes; + exports.ObjectCannedACL = ObjectCannedACL; + exports.ObjectLockEnabled = ObjectLockEnabled; + exports.ObjectLockLegalHoldStatus = ObjectLockLegalHoldStatus; + exports.ObjectLockMode = ObjectLockMode; + exports.ObjectLockRetentionMode = ObjectLockRetentionMode; + exports.ObjectOwnership = ObjectOwnership; + exports.ObjectStorageClass = ObjectStorageClass; + exports.ObjectVersionStorageClass = ObjectVersionStorageClass; + exports.OptionalObjectAttributes = OptionalObjectAttributes; + exports.OwnerOverride = OwnerOverride; + exports.PartitionDateSource = PartitionDateSource; + exports.Payer = Payer; + exports.Permission = Permission; + exports.Protocol = Protocol; + exports.PutBucketAbacCommand = PutBucketAbacCommand; + exports.PutBucketAccelerateConfigurationCommand = PutBucketAccelerateConfigurationCommand; + exports.PutBucketAclCommand = PutBucketAclCommand; + exports.PutBucketAnalyticsConfigurationCommand = PutBucketAnalyticsConfigurationCommand; + exports.PutBucketCorsCommand = PutBucketCorsCommand; + exports.PutBucketEncryptionCommand = PutBucketEncryptionCommand; + exports.PutBucketIntelligentTieringConfigurationCommand = PutBucketIntelligentTieringConfigurationCommand; + exports.PutBucketInventoryConfigurationCommand = PutBucketInventoryConfigurationCommand; + exports.PutBucketLifecycleConfigurationCommand = PutBucketLifecycleConfigurationCommand; + exports.PutBucketLoggingCommand = PutBucketLoggingCommand; + exports.PutBucketMetricsConfigurationCommand = PutBucketMetricsConfigurationCommand; + exports.PutBucketNotificationConfigurationCommand = PutBucketNotificationConfigurationCommand; + exports.PutBucketOwnershipControlsCommand = PutBucketOwnershipControlsCommand; + exports.PutBucketPolicyCommand = PutBucketPolicyCommand; + exports.PutBucketReplicationCommand = PutBucketReplicationCommand; + exports.PutBucketRequestPaymentCommand = PutBucketRequestPaymentCommand; + exports.PutBucketTaggingCommand = PutBucketTaggingCommand; + exports.PutBucketVersioningCommand = PutBucketVersioningCommand; + exports.PutBucketWebsiteCommand = PutBucketWebsiteCommand; + exports.PutObjectAclCommand = PutObjectAclCommand; + exports.PutObjectCommand = PutObjectCommand2; + exports.PutObjectLegalHoldCommand = PutObjectLegalHoldCommand; + exports.PutObjectLockConfigurationCommand = PutObjectLockConfigurationCommand; + exports.PutObjectRetentionCommand = PutObjectRetentionCommand; + exports.PutObjectTaggingCommand = PutObjectTaggingCommand; + exports.PutPublicAccessBlockCommand = PutPublicAccessBlockCommand; + exports.QuoteFields = QuoteFields; + exports.RenameObjectCommand = RenameObjectCommand; + exports.ReplicaModificationsStatus = ReplicaModificationsStatus; + exports.ReplicationRuleStatus = ReplicationRuleStatus; + exports.ReplicationStatus = ReplicationStatus; + exports.ReplicationTimeStatus = ReplicationTimeStatus; + exports.RequestCharged = RequestCharged; + exports.RequestPayer = RequestPayer; + exports.RestoreObjectCommand = RestoreObjectCommand; + exports.RestoreRequestType = RestoreRequestType; + exports.S3 = S3; + exports.S3Client = S3Client2; + exports.S3TablesBucketType = S3TablesBucketType; + exports.SelectObjectContentCommand = SelectObjectContentCommand; + exports.ServerSideEncryption = ServerSideEncryption; + exports.SessionMode = SessionMode; + exports.SseKmsEncryptedObjectsStatus = SseKmsEncryptedObjectsStatus; + exports.StorageClass = StorageClass; + exports.StorageClassAnalysisSchemaVersion = StorageClassAnalysisSchemaVersion; + exports.TableSseAlgorithm = TableSseAlgorithm; + exports.TaggingDirective = TaggingDirective; + exports.Tier = Tier; + exports.TransitionDefaultMinimumObjectSize = TransitionDefaultMinimumObjectSize; + exports.TransitionStorageClass = TransitionStorageClass; + exports.Type = Type; + exports.UpdateBucketMetadataInventoryTableConfigurationCommand = UpdateBucketMetadataInventoryTableConfigurationCommand; + exports.UpdateBucketMetadataJournalTableConfigurationCommand = UpdateBucketMetadataJournalTableConfigurationCommand; + exports.UpdateObjectEncryptionCommand = UpdateObjectEncryptionCommand; + exports.UploadPartCommand = UploadPartCommand; + exports.UploadPartCopyCommand = UploadPartCopyCommand; + exports.WriteGetObjectResponseCommand = WriteGetObjectResponseCommand; + exports.paginateListBuckets = paginateListBuckets; + exports.paginateListDirectoryBuckets = paginateListDirectoryBuckets; + exports.paginateListObjectsV2 = paginateListObjectsV2; + exports.paginateListParts = paginateListParts; + exports.waitForBucketExists = waitForBucketExists; + exports.waitForBucketNotExists = waitForBucketNotExists; + exports.waitForObjectExists = waitForObjectExists; + exports.waitForObjectNotExists = waitForObjectNotExists; + exports.waitUntilBucketExists = waitUntilBucketExists; + exports.waitUntilBucketNotExists = waitUntilBucketNotExists; + exports.waitUntilObjectExists = waitUntilObjectExists; + exports.waitUntilObjectNotExists = waitUntilObjectNotExists; + Object.prototype.hasOwnProperty.call(schemas_0, "__proto__") && !Object.prototype.hasOwnProperty.call(exports, "__proto__") && Object.defineProperty(exports, "__proto__", { + enumerable: true, + value: schemas_0["__proto__"] + }); + Object.keys(schemas_0).forEach(function(k5) { + if (k5 !== "default" && !Object.prototype.hasOwnProperty.call(exports, k5)) exports[k5] = schemas_0[k5]; + }); + Object.prototype.hasOwnProperty.call(errors, "__proto__") && !Object.prototype.hasOwnProperty.call(exports, "__proto__") && Object.defineProperty(exports, "__proto__", { + enumerable: true, + value: errors["__proto__"] + }); + Object.keys(errors).forEach(function(k5) { + if (k5 !== "default" && !Object.prototype.hasOwnProperty.call(exports, k5)) exports[k5] = errors[k5]; + }); + } +}); + +// node_modules/.pnpm/media-typer@0.3.0/node_modules/media-typer/index.js +var require_media_typer2 = __commonJS({ + "node_modules/.pnpm/media-typer@0.3.0/node_modules/media-typer/index.js"(exports) { + var paramRegExp = /; *([!#$%&'\*\+\-\.0-9A-Z\^_`a-z\|~]+) *= *("(?:[ !\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u0020-\u007e])*"|[!#$%&'\*\+\-\.0-9A-Z\^_`a-z\|~]+) */g; + var textRegExp = /^[\u0020-\u007e\u0080-\u00ff]+$/; + var tokenRegExp = /^[!#$%&'\*\+\-\.0-9A-Z\^_`a-z\|~]+$/; + var qescRegExp = /\\([\u0000-\u007f])/g; + var quoteRegExp = /([\\"])/g; + var subtypeNameRegExp = /^[A-Za-z0-9][A-Za-z0-9!#$&^_.-]{0,126}$/; + var typeNameRegExp = /^[A-Za-z0-9][A-Za-z0-9!#$&^_-]{0,126}$/; + var typeRegExp = /^ *([A-Za-z0-9][A-Za-z0-9!#$&^_-]{0,126})\/([A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}) *$/; + exports.format = format2; + exports.parse = parse5; + function format2(obj) { + if (!obj || typeof obj !== "object") { + throw new TypeError("argument obj is required"); + } + var parameters = obj.parameters; + var subtype = obj.subtype; + var suffix = obj.suffix; + var type = obj.type; + if (!type || !typeNameRegExp.test(type)) { + throw new TypeError("invalid type"); + } + if (!subtype || !subtypeNameRegExp.test(subtype)) { + throw new TypeError("invalid subtype"); + } + var string4 = type + "/" + subtype; + if (suffix) { + if (!typeNameRegExp.test(suffix)) { + throw new TypeError("invalid suffix"); + } + string4 += "+" + suffix; + } + if (parameters && typeof parameters === "object") { + var param; + var params = Object.keys(parameters).sort(); + for (var i5 = 0; i5 < params.length; i5++) { + param = params[i5]; + if (!tokenRegExp.test(param)) { + throw new TypeError("invalid parameter name"); + } + string4 += "; " + param + "=" + qstring(parameters[param]); + } + } + return string4; + } + function parse5(string4) { + if (!string4) { + throw new TypeError("argument string is required"); + } + if (typeof string4 === "object") { + string4 = getcontenttype(string4); + } + if (typeof string4 !== "string") { + throw new TypeError("argument string is required to be a string"); + } + var index2 = string4.indexOf(";"); + var type = index2 !== -1 ? string4.substr(0, index2) : string4; + var key; + var match; + var obj = splitType(type); + var params = {}; + var value; + paramRegExp.lastIndex = index2; + while (match = paramRegExp.exec(string4)) { + if (match.index !== index2) { + throw new TypeError("invalid parameter format"); + } + index2 += match[0].length; + key = match[1].toLowerCase(); + value = match[2]; + if (value[0] === '"') { + value = value.substr(1, value.length - 2).replace(qescRegExp, "$1"); + } + params[key] = value; + } + if (index2 !== -1 && index2 !== string4.length) { + throw new TypeError("invalid parameter format"); + } + obj.parameters = params; + return obj; + } + function getcontenttype(obj) { + if (typeof obj.getHeader === "function") { + return obj.getHeader("content-type"); + } + if (typeof obj.headers === "object") { + return obj.headers && obj.headers["content-type"]; + } + } + function qstring(val) { + var str = String(val); + if (tokenRegExp.test(str)) { + return str; + } + if (str.length > 0 && !textRegExp.test(str)) { + throw new TypeError("invalid parameter value"); + } + return '"' + str.replace(quoteRegExp, "\\$1") + '"'; + } + function splitType(string4) { + var match = typeRegExp.exec(string4.toLowerCase()); + if (!match) { + throw new TypeError("invalid media type"); + } + var type = match[1]; + var subtype = match[2]; + var suffix; + var index2 = subtype.lastIndexOf("+"); + if (index2 !== -1) { + suffix = subtype.substr(index2 + 1); + subtype = subtype.substr(0, index2); + } + var obj = { + type, + subtype, + suffix + }; + return obj; + } + } +}); + +// node_modules/.pnpm/mime-db@1.52.0/node_modules/mime-db/db.json +var require_db2 = __commonJS({ + "node_modules/.pnpm/mime-db@1.52.0/node_modules/mime-db/db.json"(exports, module) { + module.exports = { + "application/1d-interleaved-parityfec": { + source: "iana" + }, + "application/3gpdash-qoe-report+xml": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/3gpp-ims+xml": { + source: "iana", + compressible: true + }, + "application/3gpphal+json": { + source: "iana", + compressible: true + }, + "application/3gpphalforms+json": { + source: "iana", + compressible: true + }, + "application/a2l": { + source: "iana" + }, + "application/ace+cbor": { + source: "iana" + }, + "application/activemessage": { + source: "iana" + }, + "application/activity+json": { + source: "iana", + compressible: true + }, + "application/alto-costmap+json": { + source: "iana", + compressible: true + }, + "application/alto-costmapfilter+json": { + source: "iana", + compressible: true + }, + "application/alto-directory+json": { + source: "iana", + compressible: true + }, + "application/alto-endpointcost+json": { + source: "iana", + compressible: true + }, + "application/alto-endpointcostparams+json": { + source: "iana", + compressible: true + }, + "application/alto-endpointprop+json": { + source: "iana", + compressible: true + }, + "application/alto-endpointpropparams+json": { + source: "iana", + compressible: true + }, + "application/alto-error+json": { + source: "iana", + compressible: true + }, + "application/alto-networkmap+json": { + source: "iana", + compressible: true + }, + "application/alto-networkmapfilter+json": { + source: "iana", + compressible: true + }, + "application/alto-updatestreamcontrol+json": { + source: "iana", + compressible: true + }, + "application/alto-updatestreamparams+json": { + source: "iana", + compressible: true + }, + "application/aml": { + source: "iana" + }, + "application/andrew-inset": { + source: "iana", + extensions: ["ez"] + }, + "application/applefile": { + source: "iana" + }, + "application/applixware": { + source: "apache", + extensions: ["aw"] + }, + "application/at+jwt": { + source: "iana" + }, + "application/atf": { + source: "iana" + }, + "application/atfx": { + source: "iana" + }, + "application/atom+xml": { + source: "iana", + compressible: true, + extensions: ["atom"] + }, + "application/atomcat+xml": { + source: "iana", + compressible: true, + extensions: ["atomcat"] + }, + "application/atomdeleted+xml": { + source: "iana", + compressible: true, + extensions: ["atomdeleted"] + }, + "application/atomicmail": { + source: "iana" + }, + "application/atomsvc+xml": { + source: "iana", + compressible: true, + extensions: ["atomsvc"] + }, + "application/atsc-dwd+xml": { + source: "iana", + compressible: true, + extensions: ["dwd"] + }, + "application/atsc-dynamic-event-message": { + source: "iana" + }, + "application/atsc-held+xml": { + source: "iana", + compressible: true, + extensions: ["held"] + }, + "application/atsc-rdt+json": { + source: "iana", + compressible: true + }, + "application/atsc-rsat+xml": { + source: "iana", + compressible: true, + extensions: ["rsat"] + }, + "application/atxml": { + source: "iana" + }, + "application/auth-policy+xml": { + source: "iana", + compressible: true + }, + "application/bacnet-xdd+zip": { + source: "iana", + compressible: false + }, + "application/batch-smtp": { + source: "iana" + }, + "application/bdoc": { + compressible: false, + extensions: ["bdoc"] + }, + "application/beep+xml": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/calendar+json": { + source: "iana", + compressible: true + }, + "application/calendar+xml": { + source: "iana", + compressible: true, + extensions: ["xcs"] + }, + "application/call-completion": { + source: "iana" + }, + "application/cals-1840": { + source: "iana" + }, + "application/captive+json": { + source: "iana", + compressible: true + }, + "application/cbor": { + source: "iana" + }, + "application/cbor-seq": { + source: "iana" + }, + "application/cccex": { + source: "iana" + }, + "application/ccmp+xml": { + source: "iana", + compressible: true + }, + "application/ccxml+xml": { + source: "iana", + compressible: true, + extensions: ["ccxml"] + }, + "application/cdfx+xml": { + source: "iana", + compressible: true, + extensions: ["cdfx"] + }, + "application/cdmi-capability": { + source: "iana", + extensions: ["cdmia"] + }, + "application/cdmi-container": { + source: "iana", + extensions: ["cdmic"] + }, + "application/cdmi-domain": { + source: "iana", + extensions: ["cdmid"] + }, + "application/cdmi-object": { + source: "iana", + extensions: ["cdmio"] + }, + "application/cdmi-queue": { + source: "iana", + extensions: ["cdmiq"] + }, + "application/cdni": { + source: "iana" + }, + "application/cea": { + source: "iana" + }, + "application/cea-2018+xml": { + source: "iana", + compressible: true + }, + "application/cellml+xml": { + source: "iana", + compressible: true + }, + "application/cfw": { + source: "iana" + }, + "application/city+json": { + source: "iana", + compressible: true + }, + "application/clr": { + source: "iana" + }, + "application/clue+xml": { + source: "iana", + compressible: true + }, + "application/clue_info+xml": { + source: "iana", + compressible: true + }, + "application/cms": { + source: "iana" + }, + "application/cnrp+xml": { + source: "iana", + compressible: true + }, + "application/coap-group+json": { + source: "iana", + compressible: true + }, + "application/coap-payload": { + source: "iana" + }, + "application/commonground": { + source: "iana" + }, + "application/conference-info+xml": { + source: "iana", + compressible: true + }, + "application/cose": { + source: "iana" + }, + "application/cose-key": { + source: "iana" + }, + "application/cose-key-set": { + source: "iana" + }, + "application/cpl+xml": { + source: "iana", + compressible: true, + extensions: ["cpl"] + }, + "application/csrattrs": { + source: "iana" + }, + "application/csta+xml": { + source: "iana", + compressible: true + }, + "application/cstadata+xml": { + source: "iana", + compressible: true + }, + "application/csvm+json": { + source: "iana", + compressible: true + }, + "application/cu-seeme": { + source: "apache", + extensions: ["cu"] + }, + "application/cwt": { + source: "iana" + }, + "application/cybercash": { + source: "iana" + }, + "application/dart": { + compressible: true + }, + "application/dash+xml": { + source: "iana", + compressible: true, + extensions: ["mpd"] + }, + "application/dash-patch+xml": { + source: "iana", + compressible: true, + extensions: ["mpp"] + }, + "application/dashdelta": { + source: "iana" + }, + "application/davmount+xml": { + source: "iana", + compressible: true, + extensions: ["davmount"] + }, + "application/dca-rft": { + source: "iana" + }, + "application/dcd": { + source: "iana" + }, + "application/dec-dx": { + source: "iana" + }, + "application/dialog-info+xml": { + source: "iana", + compressible: true + }, + "application/dicom": { + source: "iana" + }, + "application/dicom+json": { + source: "iana", + compressible: true + }, + "application/dicom+xml": { + source: "iana", + compressible: true + }, + "application/dii": { + source: "iana" + }, + "application/dit": { + source: "iana" + }, + "application/dns": { + source: "iana" + }, + "application/dns+json": { + source: "iana", + compressible: true + }, + "application/dns-message": { + source: "iana" + }, + "application/docbook+xml": { + source: "apache", + compressible: true, + extensions: ["dbk"] + }, + "application/dots+cbor": { + source: "iana" + }, + "application/dskpp+xml": { + source: "iana", + compressible: true + }, + "application/dssc+der": { + source: "iana", + extensions: ["dssc"] + }, + "application/dssc+xml": { + source: "iana", + compressible: true, + extensions: ["xdssc"] + }, + "application/dvcs": { + source: "iana" + }, + "application/ecmascript": { + source: "iana", + compressible: true, + extensions: ["es", "ecma"] + }, + "application/edi-consent": { + source: "iana" + }, + "application/edi-x12": { + source: "iana", + compressible: false + }, + "application/edifact": { + source: "iana", + compressible: false + }, + "application/efi": { + source: "iana" + }, + "application/elm+json": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/elm+xml": { + source: "iana", + compressible: true + }, + "application/emergencycalldata.cap+xml": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/emergencycalldata.comment+xml": { + source: "iana", + compressible: true + }, + "application/emergencycalldata.control+xml": { + source: "iana", + compressible: true + }, + "application/emergencycalldata.deviceinfo+xml": { + source: "iana", + compressible: true + }, + "application/emergencycalldata.ecall.msd": { + source: "iana" + }, + "application/emergencycalldata.providerinfo+xml": { + source: "iana", + compressible: true + }, + "application/emergencycalldata.serviceinfo+xml": { + source: "iana", + compressible: true + }, + "application/emergencycalldata.subscriberinfo+xml": { + source: "iana", + compressible: true + }, + "application/emergencycalldata.veds+xml": { + source: "iana", + compressible: true + }, + "application/emma+xml": { + source: "iana", + compressible: true, + extensions: ["emma"] + }, + "application/emotionml+xml": { + source: "iana", + compressible: true, + extensions: ["emotionml"] + }, + "application/encaprtp": { + source: "iana" + }, + "application/epp+xml": { + source: "iana", + compressible: true + }, + "application/epub+zip": { + source: "iana", + compressible: false, + extensions: ["epub"] + }, + "application/eshop": { + source: "iana" + }, + "application/exi": { + source: "iana", + extensions: ["exi"] + }, + "application/expect-ct-report+json": { + source: "iana", + compressible: true + }, + "application/express": { + source: "iana", + extensions: ["exp"] + }, + "application/fastinfoset": { + source: "iana" + }, + "application/fastsoap": { + source: "iana" + }, + "application/fdt+xml": { + source: "iana", + compressible: true, + extensions: ["fdt"] + }, + "application/fhir+json": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/fhir+xml": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/fido.trusted-apps+json": { + compressible: true + }, + "application/fits": { + source: "iana" + }, + "application/flexfec": { + source: "iana" + }, + "application/font-sfnt": { + source: "iana" + }, + "application/font-tdpfr": { + source: "iana", + extensions: ["pfr"] + }, + "application/font-woff": { + source: "iana", + compressible: false + }, + "application/framework-attributes+xml": { + source: "iana", + compressible: true + }, + "application/geo+json": { + source: "iana", + compressible: true, + extensions: ["geojson"] + }, + "application/geo+json-seq": { + source: "iana" + }, + "application/geopackage+sqlite3": { + source: "iana" + }, + "application/geoxacml+xml": { + source: "iana", + compressible: true + }, + "application/gltf-buffer": { + source: "iana" + }, + "application/gml+xml": { + source: "iana", + compressible: true, + extensions: ["gml"] + }, + "application/gpx+xml": { + source: "apache", + compressible: true, + extensions: ["gpx"] + }, + "application/gxf": { + source: "apache", + extensions: ["gxf"] + }, + "application/gzip": { + source: "iana", + compressible: false, + extensions: ["gz"] + }, + "application/h224": { + source: "iana" + }, + "application/held+xml": { + source: "iana", + compressible: true + }, + "application/hjson": { + extensions: ["hjson"] + }, + "application/http": { + source: "iana" + }, + "application/hyperstudio": { + source: "iana", + extensions: ["stk"] + }, + "application/ibe-key-request+xml": { + source: "iana", + compressible: true + }, + "application/ibe-pkg-reply+xml": { + source: "iana", + compressible: true + }, + "application/ibe-pp-data": { + source: "iana" + }, + "application/iges": { + source: "iana" + }, + "application/im-iscomposing+xml": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/index": { + source: "iana" + }, + "application/index.cmd": { + source: "iana" + }, + "application/index.obj": { + source: "iana" + }, + "application/index.response": { + source: "iana" + }, + "application/index.vnd": { + source: "iana" + }, + "application/inkml+xml": { + source: "iana", + compressible: true, + extensions: ["ink", "inkml"] + }, + "application/iotp": { + source: "iana" + }, + "application/ipfix": { + source: "iana", + extensions: ["ipfix"] + }, + "application/ipp": { + source: "iana" + }, + "application/isup": { + source: "iana" + }, + "application/its+xml": { + source: "iana", + compressible: true, + extensions: ["its"] + }, + "application/java-archive": { + source: "apache", + compressible: false, + extensions: ["jar", "war", "ear"] + }, + "application/java-serialized-object": { + source: "apache", + compressible: false, + extensions: ["ser"] + }, + "application/java-vm": { + source: "apache", + compressible: false, + extensions: ["class"] + }, + "application/javascript": { + source: "iana", + charset: "UTF-8", + compressible: true, + extensions: ["js", "mjs"] + }, + "application/jf2feed+json": { + source: "iana", + compressible: true + }, + "application/jose": { + source: "iana" + }, + "application/jose+json": { + source: "iana", + compressible: true + }, + "application/jrd+json": { + source: "iana", + compressible: true + }, + "application/jscalendar+json": { + source: "iana", + compressible: true + }, + "application/json": { + source: "iana", + charset: "UTF-8", + compressible: true, + extensions: ["json", "map"] + }, + "application/json-patch+json": { + source: "iana", + compressible: true + }, + "application/json-seq": { + source: "iana" + }, + "application/json5": { + extensions: ["json5"] + }, + "application/jsonml+json": { + source: "apache", + compressible: true, + extensions: ["jsonml"] + }, + "application/jwk+json": { + source: "iana", + compressible: true + }, + "application/jwk-set+json": { + source: "iana", + compressible: true + }, + "application/jwt": { + source: "iana" + }, + "application/kpml-request+xml": { + source: "iana", + compressible: true + }, + "application/kpml-response+xml": { + source: "iana", + compressible: true + }, + "application/ld+json": { + source: "iana", + compressible: true, + extensions: ["jsonld"] + }, + "application/lgr+xml": { + source: "iana", + compressible: true, + extensions: ["lgr"] + }, + "application/link-format": { + source: "iana" + }, + "application/load-control+xml": { + source: "iana", + compressible: true + }, + "application/lost+xml": { + source: "iana", + compressible: true, + extensions: ["lostxml"] + }, + "application/lostsync+xml": { + source: "iana", + compressible: true + }, + "application/lpf+zip": { + source: "iana", + compressible: false + }, + "application/lxf": { + source: "iana" + }, + "application/mac-binhex40": { + source: "iana", + extensions: ["hqx"] + }, + "application/mac-compactpro": { + source: "apache", + extensions: ["cpt"] + }, + "application/macwriteii": { + source: "iana" + }, + "application/mads+xml": { + source: "iana", + compressible: true, + extensions: ["mads"] + }, + "application/manifest+json": { + source: "iana", + charset: "UTF-8", + compressible: true, + extensions: ["webmanifest"] + }, + "application/marc": { + source: "iana", + extensions: ["mrc"] + }, + "application/marcxml+xml": { + source: "iana", + compressible: true, + extensions: ["mrcx"] + }, + "application/mathematica": { + source: "iana", + extensions: ["ma", "nb", "mb"] + }, + "application/mathml+xml": { + source: "iana", + compressible: true, + extensions: ["mathml"] + }, + "application/mathml-content+xml": { + source: "iana", + compressible: true + }, + "application/mathml-presentation+xml": { + source: "iana", + compressible: true + }, + "application/mbms-associated-procedure-description+xml": { + source: "iana", + compressible: true + }, + "application/mbms-deregister+xml": { + source: "iana", + compressible: true + }, + "application/mbms-envelope+xml": { + source: "iana", + compressible: true + }, + "application/mbms-msk+xml": { + source: "iana", + compressible: true + }, + "application/mbms-msk-response+xml": { + source: "iana", + compressible: true + }, + "application/mbms-protection-description+xml": { + source: "iana", + compressible: true + }, + "application/mbms-reception-report+xml": { + source: "iana", + compressible: true + }, + "application/mbms-register+xml": { + source: "iana", + compressible: true + }, + "application/mbms-register-response+xml": { + source: "iana", + compressible: true + }, + "application/mbms-schedule+xml": { + source: "iana", + compressible: true + }, + "application/mbms-user-service-description+xml": { + source: "iana", + compressible: true + }, + "application/mbox": { + source: "iana", + extensions: ["mbox"] + }, + "application/media-policy-dataset+xml": { + source: "iana", + compressible: true, + extensions: ["mpf"] + }, + "application/media_control+xml": { + source: "iana", + compressible: true + }, + "application/mediaservercontrol+xml": { + source: "iana", + compressible: true, + extensions: ["mscml"] + }, + "application/merge-patch+json": { + source: "iana", + compressible: true + }, + "application/metalink+xml": { + source: "apache", + compressible: true, + extensions: ["metalink"] + }, + "application/metalink4+xml": { + source: "iana", + compressible: true, + extensions: ["meta4"] + }, + "application/mets+xml": { + source: "iana", + compressible: true, + extensions: ["mets"] + }, + "application/mf4": { + source: "iana" + }, + "application/mikey": { + source: "iana" + }, + "application/mipc": { + source: "iana" + }, + "application/missing-blocks+cbor-seq": { + source: "iana" + }, + "application/mmt-aei+xml": { + source: "iana", + compressible: true, + extensions: ["maei"] + }, + "application/mmt-usd+xml": { + source: "iana", + compressible: true, + extensions: ["musd"] + }, + "application/mods+xml": { + source: "iana", + compressible: true, + extensions: ["mods"] + }, + "application/moss-keys": { + source: "iana" + }, + "application/moss-signature": { + source: "iana" + }, + "application/mosskey-data": { + source: "iana" + }, + "application/mosskey-request": { + source: "iana" + }, + "application/mp21": { + source: "iana", + extensions: ["m21", "mp21"] + }, + "application/mp4": { + source: "iana", + extensions: ["mp4s", "m4p"] + }, + "application/mpeg4-generic": { + source: "iana" + }, + "application/mpeg4-iod": { + source: "iana" + }, + "application/mpeg4-iod-xmt": { + source: "iana" + }, + "application/mrb-consumer+xml": { + source: "iana", + compressible: true + }, + "application/mrb-publish+xml": { + source: "iana", + compressible: true + }, + "application/msc-ivr+xml": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/msc-mixer+xml": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/msword": { + source: "iana", + compressible: false, + extensions: ["doc", "dot"] + }, + "application/mud+json": { + source: "iana", + compressible: true + }, + "application/multipart-core": { + source: "iana" + }, + "application/mxf": { + source: "iana", + extensions: ["mxf"] + }, + "application/n-quads": { + source: "iana", + extensions: ["nq"] + }, + "application/n-triples": { + source: "iana", + extensions: ["nt"] + }, + "application/nasdata": { + source: "iana" + }, + "application/news-checkgroups": { + source: "iana", + charset: "US-ASCII" + }, + "application/news-groupinfo": { + source: "iana", + charset: "US-ASCII" + }, + "application/news-transmission": { + source: "iana" + }, + "application/nlsml+xml": { + source: "iana", + compressible: true + }, + "application/node": { + source: "iana", + extensions: ["cjs"] + }, + "application/nss": { + source: "iana" + }, + "application/oauth-authz-req+jwt": { + source: "iana" + }, + "application/oblivious-dns-message": { + source: "iana" + }, + "application/ocsp-request": { + source: "iana" + }, + "application/ocsp-response": { + source: "iana" + }, + "application/octet-stream": { + source: "iana", + compressible: false, + extensions: ["bin", "dms", "lrf", "mar", "so", "dist", "distz", "pkg", "bpk", "dump", "elc", "deploy", "exe", "dll", "deb", "dmg", "iso", "img", "msi", "msp", "msm", "buffer"] + }, + "application/oda": { + source: "iana", + extensions: ["oda"] + }, + "application/odm+xml": { + source: "iana", + compressible: true + }, + "application/odx": { + source: "iana" + }, + "application/oebps-package+xml": { + source: "iana", + compressible: true, + extensions: ["opf"] + }, + "application/ogg": { + source: "iana", + compressible: false, + extensions: ["ogx"] + }, + "application/omdoc+xml": { + source: "apache", + compressible: true, + extensions: ["omdoc"] + }, + "application/onenote": { + source: "apache", + extensions: ["onetoc", "onetoc2", "onetmp", "onepkg"] + }, + "application/opc-nodeset+xml": { + source: "iana", + compressible: true + }, + "application/oscore": { + source: "iana" + }, + "application/oxps": { + source: "iana", + extensions: ["oxps"] + }, + "application/p21": { + source: "iana" + }, + "application/p21+zip": { + source: "iana", + compressible: false + }, + "application/p2p-overlay+xml": { + source: "iana", + compressible: true, + extensions: ["relo"] + }, + "application/parityfec": { + source: "iana" + }, + "application/passport": { + source: "iana" + }, + "application/patch-ops-error+xml": { + source: "iana", + compressible: true, + extensions: ["xer"] + }, + "application/pdf": { + source: "iana", + compressible: false, + extensions: ["pdf"] + }, + "application/pdx": { + source: "iana" + }, + "application/pem-certificate-chain": { + source: "iana" + }, + "application/pgp-encrypted": { + source: "iana", + compressible: false, + extensions: ["pgp"] + }, + "application/pgp-keys": { + source: "iana", + extensions: ["asc"] + }, + "application/pgp-signature": { + source: "iana", + extensions: ["asc", "sig"] + }, + "application/pics-rules": { + source: "apache", + extensions: ["prf"] + }, + "application/pidf+xml": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/pidf-diff+xml": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/pkcs10": { + source: "iana", + extensions: ["p10"] + }, + "application/pkcs12": { + source: "iana" + }, + "application/pkcs7-mime": { + source: "iana", + extensions: ["p7m", "p7c"] + }, + "application/pkcs7-signature": { + source: "iana", + extensions: ["p7s"] + }, + "application/pkcs8": { + source: "iana", + extensions: ["p8"] + }, + "application/pkcs8-encrypted": { + source: "iana" + }, + "application/pkix-attr-cert": { + source: "iana", + extensions: ["ac"] + }, + "application/pkix-cert": { + source: "iana", + extensions: ["cer"] + }, + "application/pkix-crl": { + source: "iana", + extensions: ["crl"] + }, + "application/pkix-pkipath": { + source: "iana", + extensions: ["pkipath"] + }, + "application/pkixcmp": { + source: "iana", + extensions: ["pki"] + }, + "application/pls+xml": { + source: "iana", + compressible: true, + extensions: ["pls"] + }, + "application/poc-settings+xml": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/postscript": { + source: "iana", + compressible: true, + extensions: ["ai", "eps", "ps"] + }, + "application/ppsp-tracker+json": { + source: "iana", + compressible: true + }, + "application/problem+json": { + source: "iana", + compressible: true + }, + "application/problem+xml": { + source: "iana", + compressible: true + }, + "application/provenance+xml": { + source: "iana", + compressible: true, + extensions: ["provx"] + }, + "application/prs.alvestrand.titrax-sheet": { + source: "iana" + }, + "application/prs.cww": { + source: "iana", + extensions: ["cww"] + }, + "application/prs.cyn": { + source: "iana", + charset: "7-BIT" + }, + "application/prs.hpub+zip": { + source: "iana", + compressible: false + }, + "application/prs.nprend": { + source: "iana" + }, + "application/prs.plucker": { + source: "iana" + }, + "application/prs.rdf-xml-crypt": { + source: "iana" + }, + "application/prs.xsf+xml": { + source: "iana", + compressible: true + }, + "application/pskc+xml": { + source: "iana", + compressible: true, + extensions: ["pskcxml"] + }, + "application/pvd+json": { + source: "iana", + compressible: true + }, + "application/qsig": { + source: "iana" + }, + "application/raml+yaml": { + compressible: true, + extensions: ["raml"] + }, + "application/raptorfec": { + source: "iana" + }, + "application/rdap+json": { + source: "iana", + compressible: true + }, + "application/rdf+xml": { + source: "iana", + compressible: true, + extensions: ["rdf", "owl"] + }, + "application/reginfo+xml": { + source: "iana", + compressible: true, + extensions: ["rif"] + }, + "application/relax-ng-compact-syntax": { + source: "iana", + extensions: ["rnc"] + }, + "application/remote-printing": { + source: "iana" + }, + "application/reputon+json": { + source: "iana", + compressible: true + }, + "application/resource-lists+xml": { + source: "iana", + compressible: true, + extensions: ["rl"] + }, + "application/resource-lists-diff+xml": { + source: "iana", + compressible: true, + extensions: ["rld"] + }, + "application/rfc+xml": { + source: "iana", + compressible: true + }, + "application/riscos": { + source: "iana" + }, + "application/rlmi+xml": { + source: "iana", + compressible: true + }, + "application/rls-services+xml": { + source: "iana", + compressible: true, + extensions: ["rs"] + }, + "application/route-apd+xml": { + source: "iana", + compressible: true, + extensions: ["rapd"] + }, + "application/route-s-tsid+xml": { + source: "iana", + compressible: true, + extensions: ["sls"] + }, + "application/route-usd+xml": { + source: "iana", + compressible: true, + extensions: ["rusd"] + }, + "application/rpki-ghostbusters": { + source: "iana", + extensions: ["gbr"] + }, + "application/rpki-manifest": { + source: "iana", + extensions: ["mft"] + }, + "application/rpki-publication": { + source: "iana" + }, + "application/rpki-roa": { + source: "iana", + extensions: ["roa"] + }, + "application/rpki-updown": { + source: "iana" + }, + "application/rsd+xml": { + source: "apache", + compressible: true, + extensions: ["rsd"] + }, + "application/rss+xml": { + source: "apache", + compressible: true, + extensions: ["rss"] + }, + "application/rtf": { + source: "iana", + compressible: true, + extensions: ["rtf"] + }, + "application/rtploopback": { + source: "iana" + }, + "application/rtx": { + source: "iana" + }, + "application/samlassertion+xml": { + source: "iana", + compressible: true + }, + "application/samlmetadata+xml": { + source: "iana", + compressible: true + }, + "application/sarif+json": { + source: "iana", + compressible: true + }, + "application/sarif-external-properties+json": { + source: "iana", + compressible: true + }, + "application/sbe": { + source: "iana" + }, + "application/sbml+xml": { + source: "iana", + compressible: true, + extensions: ["sbml"] + }, + "application/scaip+xml": { + source: "iana", + compressible: true + }, + "application/scim+json": { + source: "iana", + compressible: true + }, + "application/scvp-cv-request": { + source: "iana", + extensions: ["scq"] + }, + "application/scvp-cv-response": { + source: "iana", + extensions: ["scs"] + }, + "application/scvp-vp-request": { + source: "iana", + extensions: ["spq"] + }, + "application/scvp-vp-response": { + source: "iana", + extensions: ["spp"] + }, + "application/sdp": { + source: "iana", + extensions: ["sdp"] + }, + "application/secevent+jwt": { + source: "iana" + }, + "application/senml+cbor": { + source: "iana" + }, + "application/senml+json": { + source: "iana", + compressible: true + }, + "application/senml+xml": { + source: "iana", + compressible: true, + extensions: ["senmlx"] + }, + "application/senml-etch+cbor": { + source: "iana" + }, + "application/senml-etch+json": { + source: "iana", + compressible: true + }, + "application/senml-exi": { + source: "iana" + }, + "application/sensml+cbor": { + source: "iana" + }, + "application/sensml+json": { + source: "iana", + compressible: true + }, + "application/sensml+xml": { + source: "iana", + compressible: true, + extensions: ["sensmlx"] + }, + "application/sensml-exi": { + source: "iana" + }, + "application/sep+xml": { + source: "iana", + compressible: true + }, + "application/sep-exi": { + source: "iana" + }, + "application/session-info": { + source: "iana" + }, + "application/set-payment": { + source: "iana" + }, + "application/set-payment-initiation": { + source: "iana", + extensions: ["setpay"] + }, + "application/set-registration": { + source: "iana" + }, + "application/set-registration-initiation": { + source: "iana", + extensions: ["setreg"] + }, + "application/sgml": { + source: "iana" + }, + "application/sgml-open-catalog": { + source: "iana" + }, + "application/shf+xml": { + source: "iana", + compressible: true, + extensions: ["shf"] + }, + "application/sieve": { + source: "iana", + extensions: ["siv", "sieve"] + }, + "application/simple-filter+xml": { + source: "iana", + compressible: true + }, + "application/simple-message-summary": { + source: "iana" + }, + "application/simplesymbolcontainer": { + source: "iana" + }, + "application/sipc": { + source: "iana" + }, + "application/slate": { + source: "iana" + }, + "application/smil": { + source: "iana" + }, + "application/smil+xml": { + source: "iana", + compressible: true, + extensions: ["smi", "smil"] + }, + "application/smpte336m": { + source: "iana" + }, + "application/soap+fastinfoset": { + source: "iana" + }, + "application/soap+xml": { + source: "iana", + compressible: true + }, + "application/sparql-query": { + source: "iana", + extensions: ["rq"] + }, + "application/sparql-results+xml": { + source: "iana", + compressible: true, + extensions: ["srx"] + }, + "application/spdx+json": { + source: "iana", + compressible: true + }, + "application/spirits-event+xml": { + source: "iana", + compressible: true + }, + "application/sql": { + source: "iana" + }, + "application/srgs": { + source: "iana", + extensions: ["gram"] + }, + "application/srgs+xml": { + source: "iana", + compressible: true, + extensions: ["grxml"] + }, + "application/sru+xml": { + source: "iana", + compressible: true, + extensions: ["sru"] + }, + "application/ssdl+xml": { + source: "apache", + compressible: true, + extensions: ["ssdl"] + }, + "application/ssml+xml": { + source: "iana", + compressible: true, + extensions: ["ssml"] + }, + "application/stix+json": { + source: "iana", + compressible: true + }, + "application/swid+xml": { + source: "iana", + compressible: true, + extensions: ["swidtag"] + }, + "application/tamp-apex-update": { + source: "iana" + }, + "application/tamp-apex-update-confirm": { + source: "iana" + }, + "application/tamp-community-update": { + source: "iana" + }, + "application/tamp-community-update-confirm": { + source: "iana" + }, + "application/tamp-error": { + source: "iana" + }, + "application/tamp-sequence-adjust": { + source: "iana" + }, + "application/tamp-sequence-adjust-confirm": { + source: "iana" + }, + "application/tamp-status-query": { + source: "iana" + }, + "application/tamp-status-response": { + source: "iana" + }, + "application/tamp-update": { + source: "iana" + }, + "application/tamp-update-confirm": { + source: "iana" + }, + "application/tar": { + compressible: true + }, + "application/taxii+json": { + source: "iana", + compressible: true + }, + "application/td+json": { + source: "iana", + compressible: true + }, + "application/tei+xml": { + source: "iana", + compressible: true, + extensions: ["tei", "teicorpus"] + }, + "application/tetra_isi": { + source: "iana" + }, + "application/thraud+xml": { + source: "iana", + compressible: true, + extensions: ["tfi"] + }, + "application/timestamp-query": { + source: "iana" + }, + "application/timestamp-reply": { + source: "iana" + }, + "application/timestamped-data": { + source: "iana", + extensions: ["tsd"] + }, + "application/tlsrpt+gzip": { + source: "iana" + }, + "application/tlsrpt+json": { + source: "iana", + compressible: true + }, + "application/tnauthlist": { + source: "iana" + }, + "application/token-introspection+jwt": { + source: "iana" + }, + "application/toml": { + compressible: true, + extensions: ["toml"] + }, + "application/trickle-ice-sdpfrag": { + source: "iana" + }, + "application/trig": { + source: "iana", + extensions: ["trig"] + }, + "application/ttml+xml": { + source: "iana", + compressible: true, + extensions: ["ttml"] + }, + "application/tve-trigger": { + source: "iana" + }, + "application/tzif": { + source: "iana" + }, + "application/tzif-leap": { + source: "iana" + }, + "application/ubjson": { + compressible: false, + extensions: ["ubj"] + }, + "application/ulpfec": { + source: "iana" + }, + "application/urc-grpsheet+xml": { + source: "iana", + compressible: true + }, + "application/urc-ressheet+xml": { + source: "iana", + compressible: true, + extensions: ["rsheet"] + }, + "application/urc-targetdesc+xml": { + source: "iana", + compressible: true, + extensions: ["td"] + }, + "application/urc-uisocketdesc+xml": { + source: "iana", + compressible: true + }, + "application/vcard+json": { + source: "iana", + compressible: true + }, + "application/vcard+xml": { + source: "iana", + compressible: true + }, + "application/vemmi": { + source: "iana" + }, + "application/vividence.scriptfile": { + source: "apache" + }, + "application/vnd.1000minds.decision-model+xml": { + source: "iana", + compressible: true, + extensions: ["1km"] + }, + "application/vnd.3gpp-prose+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp-prose-pc3ch+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp-v2x-local-service-information": { + source: "iana" + }, + "application/vnd.3gpp.5gnas": { + source: "iana" + }, + "application/vnd.3gpp.access-transfer-events+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.bsf+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.gmop+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.gtpc": { + source: "iana" + }, + "application/vnd.3gpp.interworking-data": { + source: "iana" + }, + "application/vnd.3gpp.lpp": { + source: "iana" + }, + "application/vnd.3gpp.mc-signalling-ear": { + source: "iana" + }, + "application/vnd.3gpp.mcdata-affiliation-command+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcdata-info+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcdata-payload": { + source: "iana" + }, + "application/vnd.3gpp.mcdata-service-config+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcdata-signalling": { + source: "iana" + }, + "application/vnd.3gpp.mcdata-ue-config+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcdata-user-profile+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcptt-affiliation-command+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcptt-floor-request+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcptt-info+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcptt-location-info+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcptt-mbms-usage-info+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcptt-service-config+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcptt-signed+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcptt-ue-config+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcptt-ue-init-config+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcptt-user-profile+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcvideo-affiliation-command+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcvideo-affiliation-info+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcvideo-info+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcvideo-location-info+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcvideo-mbms-usage-info+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcvideo-service-config+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcvideo-transmission-request+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcvideo-ue-config+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mcvideo-user-profile+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.mid-call+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.ngap": { + source: "iana" + }, + "application/vnd.3gpp.pfcp": { + source: "iana" + }, + "application/vnd.3gpp.pic-bw-large": { + source: "iana", + extensions: ["plb"] + }, + "application/vnd.3gpp.pic-bw-small": { + source: "iana", + extensions: ["psb"] + }, + "application/vnd.3gpp.pic-bw-var": { + source: "iana", + extensions: ["pvb"] + }, + "application/vnd.3gpp.s1ap": { + source: "iana" + }, + "application/vnd.3gpp.sms": { + source: "iana" + }, + "application/vnd.3gpp.sms+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.srvcc-ext+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.srvcc-info+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.state-and-event-info+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp.ussd+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp2.bcmcsinfo+xml": { + source: "iana", + compressible: true + }, + "application/vnd.3gpp2.sms": { + source: "iana" + }, + "application/vnd.3gpp2.tcap": { + source: "iana", + extensions: ["tcap"] + }, + "application/vnd.3lightssoftware.imagescal": { + source: "iana" + }, + "application/vnd.3m.post-it-notes": { + source: "iana", + extensions: ["pwn"] + }, + "application/vnd.accpac.simply.aso": { + source: "iana", + extensions: ["aso"] + }, + "application/vnd.accpac.simply.imp": { + source: "iana", + extensions: ["imp"] + }, + "application/vnd.acucobol": { + source: "iana", + extensions: ["acu"] + }, + "application/vnd.acucorp": { + source: "iana", + extensions: ["atc", "acutc"] + }, + "application/vnd.adobe.air-application-installer-package+zip": { + source: "apache", + compressible: false, + extensions: ["air"] + }, + "application/vnd.adobe.flash.movie": { + source: "iana" + }, + "application/vnd.adobe.formscentral.fcdt": { + source: "iana", + extensions: ["fcdt"] + }, + "application/vnd.adobe.fxp": { + source: "iana", + extensions: ["fxp", "fxpl"] + }, + "application/vnd.adobe.partial-upload": { + source: "iana" + }, + "application/vnd.adobe.xdp+xml": { + source: "iana", + compressible: true, + extensions: ["xdp"] + }, + "application/vnd.adobe.xfdf": { + source: "iana", + extensions: ["xfdf"] + }, + "application/vnd.aether.imp": { + source: "iana" + }, + "application/vnd.afpc.afplinedata": { + source: "iana" + }, + "application/vnd.afpc.afplinedata-pagedef": { + source: "iana" + }, + "application/vnd.afpc.cmoca-cmresource": { + source: "iana" + }, + "application/vnd.afpc.foca-charset": { + source: "iana" + }, + "application/vnd.afpc.foca-codedfont": { + source: "iana" + }, + "application/vnd.afpc.foca-codepage": { + source: "iana" + }, + "application/vnd.afpc.modca": { + source: "iana" + }, + "application/vnd.afpc.modca-cmtable": { + source: "iana" + }, + "application/vnd.afpc.modca-formdef": { + source: "iana" + }, + "application/vnd.afpc.modca-mediummap": { + source: "iana" + }, + "application/vnd.afpc.modca-objectcontainer": { + source: "iana" + }, + "application/vnd.afpc.modca-overlay": { + source: "iana" + }, + "application/vnd.afpc.modca-pagesegment": { + source: "iana" + }, + "application/vnd.age": { + source: "iana", + extensions: ["age"] + }, + "application/vnd.ah-barcode": { + source: "iana" + }, + "application/vnd.ahead.space": { + source: "iana", + extensions: ["ahead"] + }, + "application/vnd.airzip.filesecure.azf": { + source: "iana", + extensions: ["azf"] + }, + "application/vnd.airzip.filesecure.azs": { + source: "iana", + extensions: ["azs"] + }, + "application/vnd.amadeus+json": { + source: "iana", + compressible: true + }, + "application/vnd.amazon.ebook": { + source: "apache", + extensions: ["azw"] + }, + "application/vnd.amazon.mobi8-ebook": { + source: "iana" + }, + "application/vnd.americandynamics.acc": { + source: "iana", + extensions: ["acc"] + }, + "application/vnd.amiga.ami": { + source: "iana", + extensions: ["ami"] + }, + "application/vnd.amundsen.maze+xml": { + source: "iana", + compressible: true + }, + "application/vnd.android.ota": { + source: "iana" + }, + "application/vnd.android.package-archive": { + source: "apache", + compressible: false, + extensions: ["apk"] + }, + "application/vnd.anki": { + source: "iana" + }, + "application/vnd.anser-web-certificate-issue-initiation": { + source: "iana", + extensions: ["cii"] + }, + "application/vnd.anser-web-funds-transfer-initiation": { + source: "apache", + extensions: ["fti"] + }, + "application/vnd.antix.game-component": { + source: "iana", + extensions: ["atx"] + }, + "application/vnd.apache.arrow.file": { + source: "iana" + }, + "application/vnd.apache.arrow.stream": { + source: "iana" + }, + "application/vnd.apache.thrift.binary": { + source: "iana" + }, + "application/vnd.apache.thrift.compact": { + source: "iana" + }, + "application/vnd.apache.thrift.json": { + source: "iana" + }, + "application/vnd.api+json": { + source: "iana", + compressible: true + }, + "application/vnd.aplextor.warrp+json": { + source: "iana", + compressible: true + }, + "application/vnd.apothekende.reservation+json": { + source: "iana", + compressible: true + }, + "application/vnd.apple.installer+xml": { + source: "iana", + compressible: true, + extensions: ["mpkg"] + }, + "application/vnd.apple.keynote": { + source: "iana", + extensions: ["key"] + }, + "application/vnd.apple.mpegurl": { + source: "iana", + extensions: ["m3u8"] + }, + "application/vnd.apple.numbers": { + source: "iana", + extensions: ["numbers"] + }, + "application/vnd.apple.pages": { + source: "iana", + extensions: ["pages"] + }, + "application/vnd.apple.pkpass": { + compressible: false, + extensions: ["pkpass"] + }, + "application/vnd.arastra.swi": { + source: "iana" + }, + "application/vnd.aristanetworks.swi": { + source: "iana", + extensions: ["swi"] + }, + "application/vnd.artisan+json": { + source: "iana", + compressible: true + }, + "application/vnd.artsquare": { + source: "iana" + }, + "application/vnd.astraea-software.iota": { + source: "iana", + extensions: ["iota"] + }, + "application/vnd.audiograph": { + source: "iana", + extensions: ["aep"] + }, + "application/vnd.autopackage": { + source: "iana" + }, + "application/vnd.avalon+json": { + source: "iana", + compressible: true + }, + "application/vnd.avistar+xml": { + source: "iana", + compressible: true + }, + "application/vnd.balsamiq.bmml+xml": { + source: "iana", + compressible: true, + extensions: ["bmml"] + }, + "application/vnd.balsamiq.bmpr": { + source: "iana" + }, + "application/vnd.banana-accounting": { + source: "iana" + }, + "application/vnd.bbf.usp.error": { + source: "iana" + }, + "application/vnd.bbf.usp.msg": { + source: "iana" + }, + "application/vnd.bbf.usp.msg+json": { + source: "iana", + compressible: true + }, + "application/vnd.bekitzur-stech+json": { + source: "iana", + compressible: true + }, + "application/vnd.bint.med-content": { + source: "iana" + }, + "application/vnd.biopax.rdf+xml": { + source: "iana", + compressible: true + }, + "application/vnd.blink-idb-value-wrapper": { + source: "iana" + }, + "application/vnd.blueice.multipass": { + source: "iana", + extensions: ["mpm"] + }, + "application/vnd.bluetooth.ep.oob": { + source: "iana" + }, + "application/vnd.bluetooth.le.oob": { + source: "iana" + }, + "application/vnd.bmi": { + source: "iana", + extensions: ["bmi"] + }, + "application/vnd.bpf": { + source: "iana" + }, + "application/vnd.bpf3": { + source: "iana" + }, + "application/vnd.businessobjects": { + source: "iana", + extensions: ["rep"] + }, + "application/vnd.byu.uapi+json": { + source: "iana", + compressible: true + }, + "application/vnd.cab-jscript": { + source: "iana" + }, + "application/vnd.canon-cpdl": { + source: "iana" + }, + "application/vnd.canon-lips": { + source: "iana" + }, + "application/vnd.capasystems-pg+json": { + source: "iana", + compressible: true + }, + "application/vnd.cendio.thinlinc.clientconf": { + source: "iana" + }, + "application/vnd.century-systems.tcp_stream": { + source: "iana" + }, + "application/vnd.chemdraw+xml": { + source: "iana", + compressible: true, + extensions: ["cdxml"] + }, + "application/vnd.chess-pgn": { + source: "iana" + }, + "application/vnd.chipnuts.karaoke-mmd": { + source: "iana", + extensions: ["mmd"] + }, + "application/vnd.ciedi": { + source: "iana" + }, + "application/vnd.cinderella": { + source: "iana", + extensions: ["cdy"] + }, + "application/vnd.cirpack.isdn-ext": { + source: "iana" + }, + "application/vnd.citationstyles.style+xml": { + source: "iana", + compressible: true, + extensions: ["csl"] + }, + "application/vnd.claymore": { + source: "iana", + extensions: ["cla"] + }, + "application/vnd.cloanto.rp9": { + source: "iana", + extensions: ["rp9"] + }, + "application/vnd.clonk.c4group": { + source: "iana", + extensions: ["c4g", "c4d", "c4f", "c4p", "c4u"] + }, + "application/vnd.cluetrust.cartomobile-config": { + source: "iana", + extensions: ["c11amc"] + }, + "application/vnd.cluetrust.cartomobile-config-pkg": { + source: "iana", + extensions: ["c11amz"] + }, + "application/vnd.coffeescript": { + source: "iana" + }, + "application/vnd.collabio.xodocuments.document": { + source: "iana" + }, + "application/vnd.collabio.xodocuments.document-template": { + source: "iana" + }, + "application/vnd.collabio.xodocuments.presentation": { + source: "iana" + }, + "application/vnd.collabio.xodocuments.presentation-template": { + source: "iana" + }, + "application/vnd.collabio.xodocuments.spreadsheet": { + source: "iana" + }, + "application/vnd.collabio.xodocuments.spreadsheet-template": { + source: "iana" + }, + "application/vnd.collection+json": { + source: "iana", + compressible: true + }, + "application/vnd.collection.doc+json": { + source: "iana", + compressible: true + }, + "application/vnd.collection.next+json": { + source: "iana", + compressible: true + }, + "application/vnd.comicbook+zip": { + source: "iana", + compressible: false + }, + "application/vnd.comicbook-rar": { + source: "iana" + }, + "application/vnd.commerce-battelle": { + source: "iana" + }, + "application/vnd.commonspace": { + source: "iana", + extensions: ["csp"] + }, + "application/vnd.contact.cmsg": { + source: "iana", + extensions: ["cdbcmsg"] + }, + "application/vnd.coreos.ignition+json": { + source: "iana", + compressible: true + }, + "application/vnd.cosmocaller": { + source: "iana", + extensions: ["cmc"] + }, + "application/vnd.crick.clicker": { + source: "iana", + extensions: ["clkx"] + }, + "application/vnd.crick.clicker.keyboard": { + source: "iana", + extensions: ["clkk"] + }, + "application/vnd.crick.clicker.palette": { + source: "iana", + extensions: ["clkp"] + }, + "application/vnd.crick.clicker.template": { + source: "iana", + extensions: ["clkt"] + }, + "application/vnd.crick.clicker.wordbank": { + source: "iana", + extensions: ["clkw"] + }, + "application/vnd.criticaltools.wbs+xml": { + source: "iana", + compressible: true, + extensions: ["wbs"] + }, + "application/vnd.cryptii.pipe+json": { + source: "iana", + compressible: true + }, + "application/vnd.crypto-shade-file": { + source: "iana" + }, + "application/vnd.cryptomator.encrypted": { + source: "iana" + }, + "application/vnd.cryptomator.vault": { + source: "iana" + }, + "application/vnd.ctc-posml": { + source: "iana", + extensions: ["pml"] + }, + "application/vnd.ctct.ws+xml": { + source: "iana", + compressible: true + }, + "application/vnd.cups-pdf": { + source: "iana" + }, + "application/vnd.cups-postscript": { + source: "iana" + }, + "application/vnd.cups-ppd": { + source: "iana", + extensions: ["ppd"] + }, + "application/vnd.cups-raster": { + source: "iana" + }, + "application/vnd.cups-raw": { + source: "iana" + }, + "application/vnd.curl": { + source: "iana" + }, + "application/vnd.curl.car": { + source: "apache", + extensions: ["car"] + }, + "application/vnd.curl.pcurl": { + source: "apache", + extensions: ["pcurl"] + }, + "application/vnd.cyan.dean.root+xml": { + source: "iana", + compressible: true + }, + "application/vnd.cybank": { + source: "iana" + }, + "application/vnd.cyclonedx+json": { + source: "iana", + compressible: true + }, + "application/vnd.cyclonedx+xml": { + source: "iana", + compressible: true + }, + "application/vnd.d2l.coursepackage1p0+zip": { + source: "iana", + compressible: false + }, + "application/vnd.d3m-dataset": { + source: "iana" + }, + "application/vnd.d3m-problem": { + source: "iana" + }, + "application/vnd.dart": { + source: "iana", + compressible: true, + extensions: ["dart"] + }, + "application/vnd.data-vision.rdz": { + source: "iana", + extensions: ["rdz"] + }, + "application/vnd.datapackage+json": { + source: "iana", + compressible: true + }, + "application/vnd.dataresource+json": { + source: "iana", + compressible: true + }, + "application/vnd.dbf": { + source: "iana", + extensions: ["dbf"] + }, + "application/vnd.debian.binary-package": { + source: "iana" + }, + "application/vnd.dece.data": { + source: "iana", + extensions: ["uvf", "uvvf", "uvd", "uvvd"] + }, + "application/vnd.dece.ttml+xml": { + source: "iana", + compressible: true, + extensions: ["uvt", "uvvt"] + }, + "application/vnd.dece.unspecified": { + source: "iana", + extensions: ["uvx", "uvvx"] + }, + "application/vnd.dece.zip": { + source: "iana", + extensions: ["uvz", "uvvz"] + }, + "application/vnd.denovo.fcselayout-link": { + source: "iana", + extensions: ["fe_launch"] + }, + "application/vnd.desmume.movie": { + source: "iana" + }, + "application/vnd.dir-bi.plate-dl-nosuffix": { + source: "iana" + }, + "application/vnd.dm.delegation+xml": { + source: "iana", + compressible: true + }, + "application/vnd.dna": { + source: "iana", + extensions: ["dna"] + }, + "application/vnd.document+json": { + source: "iana", + compressible: true + }, + "application/vnd.dolby.mlp": { + source: "apache", + extensions: ["mlp"] + }, + "application/vnd.dolby.mobile.1": { + source: "iana" + }, + "application/vnd.dolby.mobile.2": { + source: "iana" + }, + "application/vnd.doremir.scorecloud-binary-document": { + source: "iana" + }, + "application/vnd.dpgraph": { + source: "iana", + extensions: ["dpg"] + }, + "application/vnd.dreamfactory": { + source: "iana", + extensions: ["dfac"] + }, + "application/vnd.drive+json": { + source: "iana", + compressible: true + }, + "application/vnd.ds-keypoint": { + source: "apache", + extensions: ["kpxx"] + }, + "application/vnd.dtg.local": { + source: "iana" + }, + "application/vnd.dtg.local.flash": { + source: "iana" + }, + "application/vnd.dtg.local.html": { + source: "iana" + }, + "application/vnd.dvb.ait": { + source: "iana", + extensions: ["ait"] + }, + "application/vnd.dvb.dvbisl+xml": { + source: "iana", + compressible: true + }, + "application/vnd.dvb.dvbj": { + source: "iana" + }, + "application/vnd.dvb.esgcontainer": { + source: "iana" + }, + "application/vnd.dvb.ipdcdftnotifaccess": { + source: "iana" + }, + "application/vnd.dvb.ipdcesgaccess": { + source: "iana" + }, + "application/vnd.dvb.ipdcesgaccess2": { + source: "iana" + }, + "application/vnd.dvb.ipdcesgpdd": { + source: "iana" + }, + "application/vnd.dvb.ipdcroaming": { + source: "iana" + }, + "application/vnd.dvb.iptv.alfec-base": { + source: "iana" + }, + "application/vnd.dvb.iptv.alfec-enhancement": { + source: "iana" + }, + "application/vnd.dvb.notif-aggregate-root+xml": { + source: "iana", + compressible: true + }, + "application/vnd.dvb.notif-container+xml": { + source: "iana", + compressible: true + }, + "application/vnd.dvb.notif-generic+xml": { + source: "iana", + compressible: true + }, + "application/vnd.dvb.notif-ia-msglist+xml": { + source: "iana", + compressible: true + }, + "application/vnd.dvb.notif-ia-registration-request+xml": { + source: "iana", + compressible: true + }, + "application/vnd.dvb.notif-ia-registration-response+xml": { + source: "iana", + compressible: true + }, + "application/vnd.dvb.notif-init+xml": { + source: "iana", + compressible: true + }, + "application/vnd.dvb.pfr": { + source: "iana" + }, + "application/vnd.dvb.service": { + source: "iana", + extensions: ["svc"] + }, + "application/vnd.dxr": { + source: "iana" + }, + "application/vnd.dynageo": { + source: "iana", + extensions: ["geo"] + }, + "application/vnd.dzr": { + source: "iana" + }, + "application/vnd.easykaraoke.cdgdownload": { + source: "iana" + }, + "application/vnd.ecdis-update": { + source: "iana" + }, + "application/vnd.ecip.rlp": { + source: "iana" + }, + "application/vnd.eclipse.ditto+json": { + source: "iana", + compressible: true + }, + "application/vnd.ecowin.chart": { + source: "iana", + extensions: ["mag"] + }, + "application/vnd.ecowin.filerequest": { + source: "iana" + }, + "application/vnd.ecowin.fileupdate": { + source: "iana" + }, + "application/vnd.ecowin.series": { + source: "iana" + }, + "application/vnd.ecowin.seriesrequest": { + source: "iana" + }, + "application/vnd.ecowin.seriesupdate": { + source: "iana" + }, + "application/vnd.efi.img": { + source: "iana" + }, + "application/vnd.efi.iso": { + source: "iana" + }, + "application/vnd.emclient.accessrequest+xml": { + source: "iana", + compressible: true + }, + "application/vnd.enliven": { + source: "iana", + extensions: ["nml"] + }, + "application/vnd.enphase.envoy": { + source: "iana" + }, + "application/vnd.eprints.data+xml": { + source: "iana", + compressible: true + }, + "application/vnd.epson.esf": { + source: "iana", + extensions: ["esf"] + }, + "application/vnd.epson.msf": { + source: "iana", + extensions: ["msf"] + }, + "application/vnd.epson.quickanime": { + source: "iana", + extensions: ["qam"] + }, + "application/vnd.epson.salt": { + source: "iana", + extensions: ["slt"] + }, + "application/vnd.epson.ssf": { + source: "iana", + extensions: ["ssf"] + }, + "application/vnd.ericsson.quickcall": { + source: "iana" + }, + "application/vnd.espass-espass+zip": { + source: "iana", + compressible: false + }, + "application/vnd.eszigno3+xml": { + source: "iana", + compressible: true, + extensions: ["es3", "et3"] + }, + "application/vnd.etsi.aoc+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.asic-e+zip": { + source: "iana", + compressible: false + }, + "application/vnd.etsi.asic-s+zip": { + source: "iana", + compressible: false + }, + "application/vnd.etsi.cug+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.iptvcommand+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.iptvdiscovery+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.iptvprofile+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.iptvsad-bc+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.iptvsad-cod+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.iptvsad-npvr+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.iptvservice+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.iptvsync+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.iptvueprofile+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.mcid+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.mheg5": { + source: "iana" + }, + "application/vnd.etsi.overload-control-policy-dataset+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.pstn+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.sci+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.simservs+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.timestamp-token": { + source: "iana" + }, + "application/vnd.etsi.tsl+xml": { + source: "iana", + compressible: true + }, + "application/vnd.etsi.tsl.der": { + source: "iana" + }, + "application/vnd.eu.kasparian.car+json": { + source: "iana", + compressible: true + }, + "application/vnd.eudora.data": { + source: "iana" + }, + "application/vnd.evolv.ecig.profile": { + source: "iana" + }, + "application/vnd.evolv.ecig.settings": { + source: "iana" + }, + "application/vnd.evolv.ecig.theme": { + source: "iana" + }, + "application/vnd.exstream-empower+zip": { + source: "iana", + compressible: false + }, + "application/vnd.exstream-package": { + source: "iana" + }, + "application/vnd.ezpix-album": { + source: "iana", + extensions: ["ez2"] + }, + "application/vnd.ezpix-package": { + source: "iana", + extensions: ["ez3"] + }, + "application/vnd.f-secure.mobile": { + source: "iana" + }, + "application/vnd.familysearch.gedcom+zip": { + source: "iana", + compressible: false + }, + "application/vnd.fastcopy-disk-image": { + source: "iana" + }, + "application/vnd.fdf": { + source: "iana", + extensions: ["fdf"] + }, + "application/vnd.fdsn.mseed": { + source: "iana", + extensions: ["mseed"] + }, + "application/vnd.fdsn.seed": { + source: "iana", + extensions: ["seed", "dataless"] + }, + "application/vnd.ffsns": { + source: "iana" + }, + "application/vnd.ficlab.flb+zip": { + source: "iana", + compressible: false + }, + "application/vnd.filmit.zfc": { + source: "iana" + }, + "application/vnd.fints": { + source: "iana" + }, + "application/vnd.firemonkeys.cloudcell": { + source: "iana" + }, + "application/vnd.flographit": { + source: "iana", + extensions: ["gph"] + }, + "application/vnd.fluxtime.clip": { + source: "iana", + extensions: ["ftc"] + }, + "application/vnd.font-fontforge-sfd": { + source: "iana" + }, + "application/vnd.framemaker": { + source: "iana", + extensions: ["fm", "frame", "maker", "book"] + }, + "application/vnd.frogans.fnc": { + source: "iana", + extensions: ["fnc"] + }, + "application/vnd.frogans.ltf": { + source: "iana", + extensions: ["ltf"] + }, + "application/vnd.fsc.weblaunch": { + source: "iana", + extensions: ["fsc"] + }, + "application/vnd.fujifilm.fb.docuworks": { + source: "iana" + }, + "application/vnd.fujifilm.fb.docuworks.binder": { + source: "iana" + }, + "application/vnd.fujifilm.fb.docuworks.container": { + source: "iana" + }, + "application/vnd.fujifilm.fb.jfi+xml": { + source: "iana", + compressible: true + }, + "application/vnd.fujitsu.oasys": { + source: "iana", + extensions: ["oas"] + }, + "application/vnd.fujitsu.oasys2": { + source: "iana", + extensions: ["oa2"] + }, + "application/vnd.fujitsu.oasys3": { + source: "iana", + extensions: ["oa3"] + }, + "application/vnd.fujitsu.oasysgp": { + source: "iana", + extensions: ["fg5"] + }, + "application/vnd.fujitsu.oasysprs": { + source: "iana", + extensions: ["bh2"] + }, + "application/vnd.fujixerox.art-ex": { + source: "iana" + }, + "application/vnd.fujixerox.art4": { + source: "iana" + }, + "application/vnd.fujixerox.ddd": { + source: "iana", + extensions: ["ddd"] + }, + "application/vnd.fujixerox.docuworks": { + source: "iana", + extensions: ["xdw"] + }, + "application/vnd.fujixerox.docuworks.binder": { + source: "iana", + extensions: ["xbd"] + }, + "application/vnd.fujixerox.docuworks.container": { + source: "iana" + }, + "application/vnd.fujixerox.hbpl": { + source: "iana" + }, + "application/vnd.fut-misnet": { + source: "iana" + }, + "application/vnd.futoin+cbor": { + source: "iana" + }, + "application/vnd.futoin+json": { + source: "iana", + compressible: true + }, + "application/vnd.fuzzysheet": { + source: "iana", + extensions: ["fzs"] + }, + "application/vnd.genomatix.tuxedo": { + source: "iana", + extensions: ["txd"] + }, + "application/vnd.gentics.grd+json": { + source: "iana", + compressible: true + }, + "application/vnd.geo+json": { + source: "iana", + compressible: true + }, + "application/vnd.geocube+xml": { + source: "iana", + compressible: true + }, + "application/vnd.geogebra.file": { + source: "iana", + extensions: ["ggb"] + }, + "application/vnd.geogebra.slides": { + source: "iana" + }, + "application/vnd.geogebra.tool": { + source: "iana", + extensions: ["ggt"] + }, + "application/vnd.geometry-explorer": { + source: "iana", + extensions: ["gex", "gre"] + }, + "application/vnd.geonext": { + source: "iana", + extensions: ["gxt"] + }, + "application/vnd.geoplan": { + source: "iana", + extensions: ["g2w"] + }, + "application/vnd.geospace": { + source: "iana", + extensions: ["g3w"] + }, + "application/vnd.gerber": { + source: "iana" + }, + "application/vnd.globalplatform.card-content-mgt": { + source: "iana" + }, + "application/vnd.globalplatform.card-content-mgt-response": { + source: "iana" + }, + "application/vnd.gmx": { + source: "iana", + extensions: ["gmx"] + }, + "application/vnd.google-apps.document": { + compressible: false, + extensions: ["gdoc"] + }, + "application/vnd.google-apps.presentation": { + compressible: false, + extensions: ["gslides"] + }, + "application/vnd.google-apps.spreadsheet": { + compressible: false, + extensions: ["gsheet"] + }, + "application/vnd.google-earth.kml+xml": { + source: "iana", + compressible: true, + extensions: ["kml"] + }, + "application/vnd.google-earth.kmz": { + source: "iana", + compressible: false, + extensions: ["kmz"] + }, + "application/vnd.gov.sk.e-form+xml": { + source: "iana", + compressible: true + }, + "application/vnd.gov.sk.e-form+zip": { + source: "iana", + compressible: false + }, + "application/vnd.gov.sk.xmldatacontainer+xml": { + source: "iana", + compressible: true + }, + "application/vnd.grafeq": { + source: "iana", + extensions: ["gqf", "gqs"] + }, + "application/vnd.gridmp": { + source: "iana" + }, + "application/vnd.groove-account": { + source: "iana", + extensions: ["gac"] + }, + "application/vnd.groove-help": { + source: "iana", + extensions: ["ghf"] + }, + "application/vnd.groove-identity-message": { + source: "iana", + extensions: ["gim"] + }, + "application/vnd.groove-injector": { + source: "iana", + extensions: ["grv"] + }, + "application/vnd.groove-tool-message": { + source: "iana", + extensions: ["gtm"] + }, + "application/vnd.groove-tool-template": { + source: "iana", + extensions: ["tpl"] + }, + "application/vnd.groove-vcard": { + source: "iana", + extensions: ["vcg"] + }, + "application/vnd.hal+json": { + source: "iana", + compressible: true + }, + "application/vnd.hal+xml": { + source: "iana", + compressible: true, + extensions: ["hal"] + }, + "application/vnd.handheld-entertainment+xml": { + source: "iana", + compressible: true, + extensions: ["zmm"] + }, + "application/vnd.hbci": { + source: "iana", + extensions: ["hbci"] + }, + "application/vnd.hc+json": { + source: "iana", + compressible: true + }, + "application/vnd.hcl-bireports": { + source: "iana" + }, + "application/vnd.hdt": { + source: "iana" + }, + "application/vnd.heroku+json": { + source: "iana", + compressible: true + }, + "application/vnd.hhe.lesson-player": { + source: "iana", + extensions: ["les"] + }, + "application/vnd.hl7cda+xml": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/vnd.hl7v2+xml": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/vnd.hp-hpgl": { + source: "iana", + extensions: ["hpgl"] + }, + "application/vnd.hp-hpid": { + source: "iana", + extensions: ["hpid"] + }, + "application/vnd.hp-hps": { + source: "iana", + extensions: ["hps"] + }, + "application/vnd.hp-jlyt": { + source: "iana", + extensions: ["jlt"] + }, + "application/vnd.hp-pcl": { + source: "iana", + extensions: ["pcl"] + }, + "application/vnd.hp-pclxl": { + source: "iana", + extensions: ["pclxl"] + }, + "application/vnd.httphone": { + source: "iana" + }, + "application/vnd.hydrostatix.sof-data": { + source: "iana", + extensions: ["sfd-hdstx"] + }, + "application/vnd.hyper+json": { + source: "iana", + compressible: true + }, + "application/vnd.hyper-item+json": { + source: "iana", + compressible: true + }, + "application/vnd.hyperdrive+json": { + source: "iana", + compressible: true + }, + "application/vnd.hzn-3d-crossword": { + source: "iana" + }, + "application/vnd.ibm.afplinedata": { + source: "iana" + }, + "application/vnd.ibm.electronic-media": { + source: "iana" + }, + "application/vnd.ibm.minipay": { + source: "iana", + extensions: ["mpy"] + }, + "application/vnd.ibm.modcap": { + source: "iana", + extensions: ["afp", "listafp", "list3820"] + }, + "application/vnd.ibm.rights-management": { + source: "iana", + extensions: ["irm"] + }, + "application/vnd.ibm.secure-container": { + source: "iana", + extensions: ["sc"] + }, + "application/vnd.iccprofile": { + source: "iana", + extensions: ["icc", "icm"] + }, + "application/vnd.ieee.1905": { + source: "iana" + }, + "application/vnd.igloader": { + source: "iana", + extensions: ["igl"] + }, + "application/vnd.imagemeter.folder+zip": { + source: "iana", + compressible: false + }, + "application/vnd.imagemeter.image+zip": { + source: "iana", + compressible: false + }, + "application/vnd.immervision-ivp": { + source: "iana", + extensions: ["ivp"] + }, + "application/vnd.immervision-ivu": { + source: "iana", + extensions: ["ivu"] + }, + "application/vnd.ims.imsccv1p1": { + source: "iana" + }, + "application/vnd.ims.imsccv1p2": { + source: "iana" + }, + "application/vnd.ims.imsccv1p3": { + source: "iana" + }, + "application/vnd.ims.lis.v2.result+json": { + source: "iana", + compressible: true + }, + "application/vnd.ims.lti.v2.toolconsumerprofile+json": { + source: "iana", + compressible: true + }, + "application/vnd.ims.lti.v2.toolproxy+json": { + source: "iana", + compressible: true + }, + "application/vnd.ims.lti.v2.toolproxy.id+json": { + source: "iana", + compressible: true + }, + "application/vnd.ims.lti.v2.toolsettings+json": { + source: "iana", + compressible: true + }, + "application/vnd.ims.lti.v2.toolsettings.simple+json": { + source: "iana", + compressible: true + }, + "application/vnd.informedcontrol.rms+xml": { + source: "iana", + compressible: true + }, + "application/vnd.informix-visionary": { + source: "iana" + }, + "application/vnd.infotech.project": { + source: "iana" + }, + "application/vnd.infotech.project+xml": { + source: "iana", + compressible: true + }, + "application/vnd.innopath.wamp.notification": { + source: "iana" + }, + "application/vnd.insors.igm": { + source: "iana", + extensions: ["igm"] + }, + "application/vnd.intercon.formnet": { + source: "iana", + extensions: ["xpw", "xpx"] + }, + "application/vnd.intergeo": { + source: "iana", + extensions: ["i2g"] + }, + "application/vnd.intertrust.digibox": { + source: "iana" + }, + "application/vnd.intertrust.nncp": { + source: "iana" + }, + "application/vnd.intu.qbo": { + source: "iana", + extensions: ["qbo"] + }, + "application/vnd.intu.qfx": { + source: "iana", + extensions: ["qfx"] + }, + "application/vnd.iptc.g2.catalogitem+xml": { + source: "iana", + compressible: true + }, + "application/vnd.iptc.g2.conceptitem+xml": { + source: "iana", + compressible: true + }, + "application/vnd.iptc.g2.knowledgeitem+xml": { + source: "iana", + compressible: true + }, + "application/vnd.iptc.g2.newsitem+xml": { + source: "iana", + compressible: true + }, + "application/vnd.iptc.g2.newsmessage+xml": { + source: "iana", + compressible: true + }, + "application/vnd.iptc.g2.packageitem+xml": { + source: "iana", + compressible: true + }, + "application/vnd.iptc.g2.planningitem+xml": { + source: "iana", + compressible: true + }, + "application/vnd.ipunplugged.rcprofile": { + source: "iana", + extensions: ["rcprofile"] + }, + "application/vnd.irepository.package+xml": { + source: "iana", + compressible: true, + extensions: ["irp"] + }, + "application/vnd.is-xpr": { + source: "iana", + extensions: ["xpr"] + }, + "application/vnd.isac.fcs": { + source: "iana", + extensions: ["fcs"] + }, + "application/vnd.iso11783-10+zip": { + source: "iana", + compressible: false + }, + "application/vnd.jam": { + source: "iana", + extensions: ["jam"] + }, + "application/vnd.japannet-directory-service": { + source: "iana" + }, + "application/vnd.japannet-jpnstore-wakeup": { + source: "iana" + }, + "application/vnd.japannet-payment-wakeup": { + source: "iana" + }, + "application/vnd.japannet-registration": { + source: "iana" + }, + "application/vnd.japannet-registration-wakeup": { + source: "iana" + }, + "application/vnd.japannet-setstore-wakeup": { + source: "iana" + }, + "application/vnd.japannet-verification": { + source: "iana" + }, + "application/vnd.japannet-verification-wakeup": { + source: "iana" + }, + "application/vnd.jcp.javame.midlet-rms": { + source: "iana", + extensions: ["rms"] + }, + "application/vnd.jisp": { + source: "iana", + extensions: ["jisp"] + }, + "application/vnd.joost.joda-archive": { + source: "iana", + extensions: ["joda"] + }, + "application/vnd.jsk.isdn-ngn": { + source: "iana" + }, + "application/vnd.kahootz": { + source: "iana", + extensions: ["ktz", "ktr"] + }, + "application/vnd.kde.karbon": { + source: "iana", + extensions: ["karbon"] + }, + "application/vnd.kde.kchart": { + source: "iana", + extensions: ["chrt"] + }, + "application/vnd.kde.kformula": { + source: "iana", + extensions: ["kfo"] + }, + "application/vnd.kde.kivio": { + source: "iana", + extensions: ["flw"] + }, + "application/vnd.kde.kontour": { + source: "iana", + extensions: ["kon"] + }, + "application/vnd.kde.kpresenter": { + source: "iana", + extensions: ["kpr", "kpt"] + }, + "application/vnd.kde.kspread": { + source: "iana", + extensions: ["ksp"] + }, + "application/vnd.kde.kword": { + source: "iana", + extensions: ["kwd", "kwt"] + }, + "application/vnd.kenameaapp": { + source: "iana", + extensions: ["htke"] + }, + "application/vnd.kidspiration": { + source: "iana", + extensions: ["kia"] + }, + "application/vnd.kinar": { + source: "iana", + extensions: ["kne", "knp"] + }, + "application/vnd.koan": { + source: "iana", + extensions: ["skp", "skd", "skt", "skm"] + }, + "application/vnd.kodak-descriptor": { + source: "iana", + extensions: ["sse"] + }, + "application/vnd.las": { + source: "iana" + }, + "application/vnd.las.las+json": { + source: "iana", + compressible: true + }, + "application/vnd.las.las+xml": { + source: "iana", + compressible: true, + extensions: ["lasxml"] + }, + "application/vnd.laszip": { + source: "iana" + }, + "application/vnd.leap+json": { + source: "iana", + compressible: true + }, + "application/vnd.liberty-request+xml": { + source: "iana", + compressible: true + }, + "application/vnd.llamagraphics.life-balance.desktop": { + source: "iana", + extensions: ["lbd"] + }, + "application/vnd.llamagraphics.life-balance.exchange+xml": { + source: "iana", + compressible: true, + extensions: ["lbe"] + }, + "application/vnd.logipipe.circuit+zip": { + source: "iana", + compressible: false + }, + "application/vnd.loom": { + source: "iana" + }, + "application/vnd.lotus-1-2-3": { + source: "iana", + extensions: ["123"] + }, + "application/vnd.lotus-approach": { + source: "iana", + extensions: ["apr"] + }, + "application/vnd.lotus-freelance": { + source: "iana", + extensions: ["pre"] + }, + "application/vnd.lotus-notes": { + source: "iana", + extensions: ["nsf"] + }, + "application/vnd.lotus-organizer": { + source: "iana", + extensions: ["org"] + }, + "application/vnd.lotus-screencam": { + source: "iana", + extensions: ["scm"] + }, + "application/vnd.lotus-wordpro": { + source: "iana", + extensions: ["lwp"] + }, + "application/vnd.macports.portpkg": { + source: "iana", + extensions: ["portpkg"] + }, + "application/vnd.mapbox-vector-tile": { + source: "iana", + extensions: ["mvt"] + }, + "application/vnd.marlin.drm.actiontoken+xml": { + source: "iana", + compressible: true + }, + "application/vnd.marlin.drm.conftoken+xml": { + source: "iana", + compressible: true + }, + "application/vnd.marlin.drm.license+xml": { + source: "iana", + compressible: true + }, + "application/vnd.marlin.drm.mdcf": { + source: "iana" + }, + "application/vnd.mason+json": { + source: "iana", + compressible: true + }, + "application/vnd.maxar.archive.3tz+zip": { + source: "iana", + compressible: false + }, + "application/vnd.maxmind.maxmind-db": { + source: "iana" + }, + "application/vnd.mcd": { + source: "iana", + extensions: ["mcd"] + }, + "application/vnd.medcalcdata": { + source: "iana", + extensions: ["mc1"] + }, + "application/vnd.mediastation.cdkey": { + source: "iana", + extensions: ["cdkey"] + }, + "application/vnd.meridian-slingshot": { + source: "iana" + }, + "application/vnd.mfer": { + source: "iana", + extensions: ["mwf"] + }, + "application/vnd.mfmp": { + source: "iana", + extensions: ["mfm"] + }, + "application/vnd.micro+json": { + source: "iana", + compressible: true + }, + "application/vnd.micrografx.flo": { + source: "iana", + extensions: ["flo"] + }, + "application/vnd.micrografx.igx": { + source: "iana", + extensions: ["igx"] + }, + "application/vnd.microsoft.portable-executable": { + source: "iana" + }, + "application/vnd.microsoft.windows.thumbnail-cache": { + source: "iana" + }, + "application/vnd.miele+json": { + source: "iana", + compressible: true + }, + "application/vnd.mif": { + source: "iana", + extensions: ["mif"] + }, + "application/vnd.minisoft-hp3000-save": { + source: "iana" + }, + "application/vnd.mitsubishi.misty-guard.trustweb": { + source: "iana" + }, + "application/vnd.mobius.daf": { + source: "iana", + extensions: ["daf"] + }, + "application/vnd.mobius.dis": { + source: "iana", + extensions: ["dis"] + }, + "application/vnd.mobius.mbk": { + source: "iana", + extensions: ["mbk"] + }, + "application/vnd.mobius.mqy": { + source: "iana", + extensions: ["mqy"] + }, + "application/vnd.mobius.msl": { + source: "iana", + extensions: ["msl"] + }, + "application/vnd.mobius.plc": { + source: "iana", + extensions: ["plc"] + }, + "application/vnd.mobius.txf": { + source: "iana", + extensions: ["txf"] + }, + "application/vnd.mophun.application": { + source: "iana", + extensions: ["mpn"] + }, + "application/vnd.mophun.certificate": { + source: "iana", + extensions: ["mpc"] + }, + "application/vnd.motorola.flexsuite": { + source: "iana" + }, + "application/vnd.motorola.flexsuite.adsi": { + source: "iana" + }, + "application/vnd.motorola.flexsuite.fis": { + source: "iana" + }, + "application/vnd.motorola.flexsuite.gotap": { + source: "iana" + }, + "application/vnd.motorola.flexsuite.kmr": { + source: "iana" + }, + "application/vnd.motorola.flexsuite.ttc": { + source: "iana" + }, + "application/vnd.motorola.flexsuite.wem": { + source: "iana" + }, + "application/vnd.motorola.iprm": { + source: "iana" + }, + "application/vnd.mozilla.xul+xml": { + source: "iana", + compressible: true, + extensions: ["xul"] + }, + "application/vnd.ms-3mfdocument": { + source: "iana" + }, + "application/vnd.ms-artgalry": { + source: "iana", + extensions: ["cil"] + }, + "application/vnd.ms-asf": { + source: "iana" + }, + "application/vnd.ms-cab-compressed": { + source: "iana", + extensions: ["cab"] + }, + "application/vnd.ms-color.iccprofile": { + source: "apache" + }, + "application/vnd.ms-excel": { + source: "iana", + compressible: false, + extensions: ["xls", "xlm", "xla", "xlc", "xlt", "xlw"] + }, + "application/vnd.ms-excel.addin.macroenabled.12": { + source: "iana", + extensions: ["xlam"] + }, + "application/vnd.ms-excel.sheet.binary.macroenabled.12": { + source: "iana", + extensions: ["xlsb"] + }, + "application/vnd.ms-excel.sheet.macroenabled.12": { + source: "iana", + extensions: ["xlsm"] + }, + "application/vnd.ms-excel.template.macroenabled.12": { + source: "iana", + extensions: ["xltm"] + }, + "application/vnd.ms-fontobject": { + source: "iana", + compressible: true, + extensions: ["eot"] + }, + "application/vnd.ms-htmlhelp": { + source: "iana", + extensions: ["chm"] + }, + "application/vnd.ms-ims": { + source: "iana", + extensions: ["ims"] + }, + "application/vnd.ms-lrm": { + source: "iana", + extensions: ["lrm"] + }, + "application/vnd.ms-office.activex+xml": { + source: "iana", + compressible: true + }, + "application/vnd.ms-officetheme": { + source: "iana", + extensions: ["thmx"] + }, + "application/vnd.ms-opentype": { + source: "apache", + compressible: true + }, + "application/vnd.ms-outlook": { + compressible: false, + extensions: ["msg"] + }, + "application/vnd.ms-package.obfuscated-opentype": { + source: "apache" + }, + "application/vnd.ms-pki.seccat": { + source: "apache", + extensions: ["cat"] + }, + "application/vnd.ms-pki.stl": { + source: "apache", + extensions: ["stl"] + }, + "application/vnd.ms-playready.initiator+xml": { + source: "iana", + compressible: true + }, + "application/vnd.ms-powerpoint": { + source: "iana", + compressible: false, + extensions: ["ppt", "pps", "pot"] + }, + "application/vnd.ms-powerpoint.addin.macroenabled.12": { + source: "iana", + extensions: ["ppam"] + }, + "application/vnd.ms-powerpoint.presentation.macroenabled.12": { + source: "iana", + extensions: ["pptm"] + }, + "application/vnd.ms-powerpoint.slide.macroenabled.12": { + source: "iana", + extensions: ["sldm"] + }, + "application/vnd.ms-powerpoint.slideshow.macroenabled.12": { + source: "iana", + extensions: ["ppsm"] + }, + "application/vnd.ms-powerpoint.template.macroenabled.12": { + source: "iana", + extensions: ["potm"] + }, + "application/vnd.ms-printdevicecapabilities+xml": { + source: "iana", + compressible: true + }, + "application/vnd.ms-printing.printticket+xml": { + source: "apache", + compressible: true + }, + "application/vnd.ms-printschematicket+xml": { + source: "iana", + compressible: true + }, + "application/vnd.ms-project": { + source: "iana", + extensions: ["mpp", "mpt"] + }, + "application/vnd.ms-tnef": { + source: "iana" + }, + "application/vnd.ms-windows.devicepairing": { + source: "iana" + }, + "application/vnd.ms-windows.nwprinting.oob": { + source: "iana" + }, + "application/vnd.ms-windows.printerpairing": { + source: "iana" + }, + "application/vnd.ms-windows.wsd.oob": { + source: "iana" + }, + "application/vnd.ms-wmdrm.lic-chlg-req": { + source: "iana" + }, + "application/vnd.ms-wmdrm.lic-resp": { + source: "iana" + }, + "application/vnd.ms-wmdrm.meter-chlg-req": { + source: "iana" + }, + "application/vnd.ms-wmdrm.meter-resp": { + source: "iana" + }, + "application/vnd.ms-word.document.macroenabled.12": { + source: "iana", + extensions: ["docm"] + }, + "application/vnd.ms-word.template.macroenabled.12": { + source: "iana", + extensions: ["dotm"] + }, + "application/vnd.ms-works": { + source: "iana", + extensions: ["wps", "wks", "wcm", "wdb"] + }, + "application/vnd.ms-wpl": { + source: "iana", + extensions: ["wpl"] + }, + "application/vnd.ms-xpsdocument": { + source: "iana", + compressible: false, + extensions: ["xps"] + }, + "application/vnd.msa-disk-image": { + source: "iana" + }, + "application/vnd.mseq": { + source: "iana", + extensions: ["mseq"] + }, + "application/vnd.msign": { + source: "iana" + }, + "application/vnd.multiad.creator": { + source: "iana" + }, + "application/vnd.multiad.creator.cif": { + source: "iana" + }, + "application/vnd.music-niff": { + source: "iana" + }, + "application/vnd.musician": { + source: "iana", + extensions: ["mus"] + }, + "application/vnd.muvee.style": { + source: "iana", + extensions: ["msty"] + }, + "application/vnd.mynfc": { + source: "iana", + extensions: ["taglet"] + }, + "application/vnd.nacamar.ybrid+json": { + source: "iana", + compressible: true + }, + "application/vnd.ncd.control": { + source: "iana" + }, + "application/vnd.ncd.reference": { + source: "iana" + }, + "application/vnd.nearst.inv+json": { + source: "iana", + compressible: true + }, + "application/vnd.nebumind.line": { + source: "iana" + }, + "application/vnd.nervana": { + source: "iana" + }, + "application/vnd.netfpx": { + source: "iana" + }, + "application/vnd.neurolanguage.nlu": { + source: "iana", + extensions: ["nlu"] + }, + "application/vnd.nimn": { + source: "iana" + }, + "application/vnd.nintendo.nitro.rom": { + source: "iana" + }, + "application/vnd.nintendo.snes.rom": { + source: "iana" + }, + "application/vnd.nitf": { + source: "iana", + extensions: ["ntf", "nitf"] + }, + "application/vnd.noblenet-directory": { + source: "iana", + extensions: ["nnd"] + }, + "application/vnd.noblenet-sealer": { + source: "iana", + extensions: ["nns"] + }, + "application/vnd.noblenet-web": { + source: "iana", + extensions: ["nnw"] + }, + "application/vnd.nokia.catalogs": { + source: "iana" + }, + "application/vnd.nokia.conml+wbxml": { + source: "iana" + }, + "application/vnd.nokia.conml+xml": { + source: "iana", + compressible: true + }, + "application/vnd.nokia.iptv.config+xml": { + source: "iana", + compressible: true + }, + "application/vnd.nokia.isds-radio-presets": { + source: "iana" + }, + "application/vnd.nokia.landmark+wbxml": { + source: "iana" + }, + "application/vnd.nokia.landmark+xml": { + source: "iana", + compressible: true + }, + "application/vnd.nokia.landmarkcollection+xml": { + source: "iana", + compressible: true + }, + "application/vnd.nokia.n-gage.ac+xml": { + source: "iana", + compressible: true, + extensions: ["ac"] + }, + "application/vnd.nokia.n-gage.data": { + source: "iana", + extensions: ["ngdat"] + }, + "application/vnd.nokia.n-gage.symbian.install": { + source: "iana", + extensions: ["n-gage"] + }, + "application/vnd.nokia.ncd": { + source: "iana" + }, + "application/vnd.nokia.pcd+wbxml": { + source: "iana" + }, + "application/vnd.nokia.pcd+xml": { + source: "iana", + compressible: true + }, + "application/vnd.nokia.radio-preset": { + source: "iana", + extensions: ["rpst"] + }, + "application/vnd.nokia.radio-presets": { + source: "iana", + extensions: ["rpss"] + }, + "application/vnd.novadigm.edm": { + source: "iana", + extensions: ["edm"] + }, + "application/vnd.novadigm.edx": { + source: "iana", + extensions: ["edx"] + }, + "application/vnd.novadigm.ext": { + source: "iana", + extensions: ["ext"] + }, + "application/vnd.ntt-local.content-share": { + source: "iana" + }, + "application/vnd.ntt-local.file-transfer": { + source: "iana" + }, + "application/vnd.ntt-local.ogw_remote-access": { + source: "iana" + }, + "application/vnd.ntt-local.sip-ta_remote": { + source: "iana" + }, + "application/vnd.ntt-local.sip-ta_tcp_stream": { + source: "iana" + }, + "application/vnd.oasis.opendocument.chart": { + source: "iana", + extensions: ["odc"] + }, + "application/vnd.oasis.opendocument.chart-template": { + source: "iana", + extensions: ["otc"] + }, + "application/vnd.oasis.opendocument.database": { + source: "iana", + extensions: ["odb"] + }, + "application/vnd.oasis.opendocument.formula": { + source: "iana", + extensions: ["odf"] + }, + "application/vnd.oasis.opendocument.formula-template": { + source: "iana", + extensions: ["odft"] + }, + "application/vnd.oasis.opendocument.graphics": { + source: "iana", + compressible: false, + extensions: ["odg"] + }, + "application/vnd.oasis.opendocument.graphics-template": { + source: "iana", + extensions: ["otg"] + }, + "application/vnd.oasis.opendocument.image": { + source: "iana", + extensions: ["odi"] + }, + "application/vnd.oasis.opendocument.image-template": { + source: "iana", + extensions: ["oti"] + }, + "application/vnd.oasis.opendocument.presentation": { + source: "iana", + compressible: false, + extensions: ["odp"] + }, + "application/vnd.oasis.opendocument.presentation-template": { + source: "iana", + extensions: ["otp"] + }, + "application/vnd.oasis.opendocument.spreadsheet": { + source: "iana", + compressible: false, + extensions: ["ods"] + }, + "application/vnd.oasis.opendocument.spreadsheet-template": { + source: "iana", + extensions: ["ots"] + }, + "application/vnd.oasis.opendocument.text": { + source: "iana", + compressible: false, + extensions: ["odt"] + }, + "application/vnd.oasis.opendocument.text-master": { + source: "iana", + extensions: ["odm"] + }, + "application/vnd.oasis.opendocument.text-template": { + source: "iana", + extensions: ["ott"] + }, + "application/vnd.oasis.opendocument.text-web": { + source: "iana", + extensions: ["oth"] + }, + "application/vnd.obn": { + source: "iana" + }, + "application/vnd.ocf+cbor": { + source: "iana" + }, + "application/vnd.oci.image.manifest.v1+json": { + source: "iana", + compressible: true + }, + "application/vnd.oftn.l10n+json": { + source: "iana", + compressible: true + }, + "application/vnd.oipf.contentaccessdownload+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oipf.contentaccessstreaming+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oipf.cspg-hexbinary": { + source: "iana" + }, + "application/vnd.oipf.dae.svg+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oipf.dae.xhtml+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oipf.mippvcontrolmessage+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oipf.pae.gem": { + source: "iana" + }, + "application/vnd.oipf.spdiscovery+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oipf.spdlist+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oipf.ueprofile+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oipf.userprofile+xml": { + source: "iana", + compressible: true + }, + "application/vnd.olpc-sugar": { + source: "iana", + extensions: ["xo"] + }, + "application/vnd.oma-scws-config": { + source: "iana" + }, + "application/vnd.oma-scws-http-request": { + source: "iana" + }, + "application/vnd.oma-scws-http-response": { + source: "iana" + }, + "application/vnd.oma.bcast.associated-procedure-parameter+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.bcast.drm-trigger+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.bcast.imd+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.bcast.ltkm": { + source: "iana" + }, + "application/vnd.oma.bcast.notification+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.bcast.provisioningtrigger": { + source: "iana" + }, + "application/vnd.oma.bcast.sgboot": { + source: "iana" + }, + "application/vnd.oma.bcast.sgdd+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.bcast.sgdu": { + source: "iana" + }, + "application/vnd.oma.bcast.simple-symbol-container": { + source: "iana" + }, + "application/vnd.oma.bcast.smartcard-trigger+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.bcast.sprov+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.bcast.stkm": { + source: "iana" + }, + "application/vnd.oma.cab-address-book+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.cab-feature-handler+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.cab-pcc+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.cab-subs-invite+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.cab-user-prefs+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.dcd": { + source: "iana" + }, + "application/vnd.oma.dcdc": { + source: "iana" + }, + "application/vnd.oma.dd2+xml": { + source: "iana", + compressible: true, + extensions: ["dd2"] + }, + "application/vnd.oma.drm.risd+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.group-usage-list+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.lwm2m+cbor": { + source: "iana" + }, + "application/vnd.oma.lwm2m+json": { + source: "iana", + compressible: true + }, + "application/vnd.oma.lwm2m+tlv": { + source: "iana" + }, + "application/vnd.oma.pal+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.poc.detailed-progress-report+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.poc.final-report+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.poc.groups+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.poc.invocation-descriptor+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.poc.optimized-progress-report+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.push": { + source: "iana" + }, + "application/vnd.oma.scidm.messages+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oma.xcap-directory+xml": { + source: "iana", + compressible: true + }, + "application/vnd.omads-email+xml": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/vnd.omads-file+xml": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/vnd.omads-folder+xml": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/vnd.omaloc-supl-init": { + source: "iana" + }, + "application/vnd.onepager": { + source: "iana" + }, + "application/vnd.onepagertamp": { + source: "iana" + }, + "application/vnd.onepagertamx": { + source: "iana" + }, + "application/vnd.onepagertat": { + source: "iana" + }, + "application/vnd.onepagertatp": { + source: "iana" + }, + "application/vnd.onepagertatx": { + source: "iana" + }, + "application/vnd.openblox.game+xml": { + source: "iana", + compressible: true, + extensions: ["obgx"] + }, + "application/vnd.openblox.game-binary": { + source: "iana" + }, + "application/vnd.openeye.oeb": { + source: "iana" + }, + "application/vnd.openofficeorg.extension": { + source: "apache", + extensions: ["oxt"] + }, + "application/vnd.openstreetmap.data+xml": { + source: "iana", + compressible: true, + extensions: ["osm"] + }, + "application/vnd.opentimestamps.ots": { + source: "iana" + }, + "application/vnd.openxmlformats-officedocument.custom-properties+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.customxmlproperties+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.drawing+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.drawingml.chart+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramcolors+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramdata+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramlayout+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramstyle+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.extended-properties+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.presentationml.commentauthors+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.presentationml.comments+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.presentationml.handoutmaster+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.presentationml.notesmaster+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.presentationml.notesslide+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.presentationml.presentation": { + source: "iana", + compressible: false, + extensions: ["pptx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.presentationml.presprops+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slide": { + source: "iana", + extensions: ["sldx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.slide+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slidelayout+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slidemaster+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slideshow": { + source: "iana", + extensions: ["ppsx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slideupdateinfo+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.presentationml.tablestyles+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.presentationml.tags+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.presentationml.template": { + source: "iana", + extensions: ["potx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.template.main+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.presentationml.viewprops+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.calcchain+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.externallink+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcachedefinition+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcacherecords+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivottable+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.querytable+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionheaders+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionlog+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedstrings+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": { + source: "iana", + compressible: false, + extensions: ["xlsx"] + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheetmetadata+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.tablesinglecells+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.template": { + source: "iana", + extensions: ["xltx"] + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.usernames+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.volatiledependencies+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.theme+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.themeoverride+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.vmldrawing": { + source: "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document": { + source: "iana", + compressible: false, + extensions: ["docx"] + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.fonttable+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.template": { + source: "iana", + extensions: ["dotx"] + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.websettings+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-package.core-properties+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml": { + source: "iana", + compressible: true + }, + "application/vnd.openxmlformats-package.relationships+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oracle.resource+json": { + source: "iana", + compressible: true + }, + "application/vnd.orange.indata": { + source: "iana" + }, + "application/vnd.osa.netdeploy": { + source: "iana" + }, + "application/vnd.osgeo.mapguide.package": { + source: "iana", + extensions: ["mgp"] + }, + "application/vnd.osgi.bundle": { + source: "iana" + }, + "application/vnd.osgi.dp": { + source: "iana", + extensions: ["dp"] + }, + "application/vnd.osgi.subsystem": { + source: "iana", + extensions: ["esa"] + }, + "application/vnd.otps.ct-kip+xml": { + source: "iana", + compressible: true + }, + "application/vnd.oxli.countgraph": { + source: "iana" + }, + "application/vnd.pagerduty+json": { + source: "iana", + compressible: true + }, + "application/vnd.palm": { + source: "iana", + extensions: ["pdb", "pqa", "oprc"] + }, + "application/vnd.panoply": { + source: "iana" + }, + "application/vnd.paos.xml": { + source: "iana" + }, + "application/vnd.patentdive": { + source: "iana" + }, + "application/vnd.patientecommsdoc": { + source: "iana" + }, + "application/vnd.pawaafile": { + source: "iana", + extensions: ["paw"] + }, + "application/vnd.pcos": { + source: "iana" + }, + "application/vnd.pg.format": { + source: "iana", + extensions: ["str"] + }, + "application/vnd.pg.osasli": { + source: "iana", + extensions: ["ei6"] + }, + "application/vnd.piaccess.application-licence": { + source: "iana" + }, + "application/vnd.picsel": { + source: "iana", + extensions: ["efif"] + }, + "application/vnd.pmi.widget": { + source: "iana", + extensions: ["wg"] + }, + "application/vnd.poc.group-advertisement+xml": { + source: "iana", + compressible: true + }, + "application/vnd.pocketlearn": { + source: "iana", + extensions: ["plf"] + }, + "application/vnd.powerbuilder6": { + source: "iana", + extensions: ["pbd"] + }, + "application/vnd.powerbuilder6-s": { + source: "iana" + }, + "application/vnd.powerbuilder7": { + source: "iana" + }, + "application/vnd.powerbuilder7-s": { + source: "iana" + }, + "application/vnd.powerbuilder75": { + source: "iana" + }, + "application/vnd.powerbuilder75-s": { + source: "iana" + }, + "application/vnd.preminet": { + source: "iana" + }, + "application/vnd.previewsystems.box": { + source: "iana", + extensions: ["box"] + }, + "application/vnd.proteus.magazine": { + source: "iana", + extensions: ["mgz"] + }, + "application/vnd.psfs": { + source: "iana" + }, + "application/vnd.publishare-delta-tree": { + source: "iana", + extensions: ["qps"] + }, + "application/vnd.pvi.ptid1": { + source: "iana", + extensions: ["ptid"] + }, + "application/vnd.pwg-multiplexed": { + source: "iana" + }, + "application/vnd.pwg-xhtml-print+xml": { + source: "iana", + compressible: true + }, + "application/vnd.qualcomm.brew-app-res": { + source: "iana" + }, + "application/vnd.quarantainenet": { + source: "iana" + }, + "application/vnd.quark.quarkxpress": { + source: "iana", + extensions: ["qxd", "qxt", "qwd", "qwt", "qxl", "qxb"] + }, + "application/vnd.quobject-quoxdocument": { + source: "iana" + }, + "application/vnd.radisys.moml+xml": { + source: "iana", + compressible: true + }, + "application/vnd.radisys.msml+xml": { + source: "iana", + compressible: true + }, + "application/vnd.radisys.msml-audit+xml": { + source: "iana", + compressible: true + }, + "application/vnd.radisys.msml-audit-conf+xml": { + source: "iana", + compressible: true + }, + "application/vnd.radisys.msml-audit-conn+xml": { + source: "iana", + compressible: true + }, + "application/vnd.radisys.msml-audit-dialog+xml": { + source: "iana", + compressible: true + }, + "application/vnd.radisys.msml-audit-stream+xml": { + source: "iana", + compressible: true + }, + "application/vnd.radisys.msml-conf+xml": { + source: "iana", + compressible: true + }, + "application/vnd.radisys.msml-dialog+xml": { + source: "iana", + compressible: true + }, + "application/vnd.radisys.msml-dialog-base+xml": { + source: "iana", + compressible: true + }, + "application/vnd.radisys.msml-dialog-fax-detect+xml": { + source: "iana", + compressible: true + }, + "application/vnd.radisys.msml-dialog-fax-sendrecv+xml": { + source: "iana", + compressible: true + }, + "application/vnd.radisys.msml-dialog-group+xml": { + source: "iana", + compressible: true + }, + "application/vnd.radisys.msml-dialog-speech+xml": { + source: "iana", + compressible: true + }, + "application/vnd.radisys.msml-dialog-transform+xml": { + source: "iana", + compressible: true + }, + "application/vnd.rainstor.data": { + source: "iana" + }, + "application/vnd.rapid": { + source: "iana" + }, + "application/vnd.rar": { + source: "iana", + extensions: ["rar"] + }, + "application/vnd.realvnc.bed": { + source: "iana", + extensions: ["bed"] + }, + "application/vnd.recordare.musicxml": { + source: "iana", + extensions: ["mxl"] + }, + "application/vnd.recordare.musicxml+xml": { + source: "iana", + compressible: true, + extensions: ["musicxml"] + }, + "application/vnd.renlearn.rlprint": { + source: "iana" + }, + "application/vnd.resilient.logic": { + source: "iana" + }, + "application/vnd.restful+json": { + source: "iana", + compressible: true + }, + "application/vnd.rig.cryptonote": { + source: "iana", + extensions: ["cryptonote"] + }, + "application/vnd.rim.cod": { + source: "apache", + extensions: ["cod"] + }, + "application/vnd.rn-realmedia": { + source: "apache", + extensions: ["rm"] + }, + "application/vnd.rn-realmedia-vbr": { + source: "apache", + extensions: ["rmvb"] + }, + "application/vnd.route66.link66+xml": { + source: "iana", + compressible: true, + extensions: ["link66"] + }, + "application/vnd.rs-274x": { + source: "iana" + }, + "application/vnd.ruckus.download": { + source: "iana" + }, + "application/vnd.s3sms": { + source: "iana" + }, + "application/vnd.sailingtracker.track": { + source: "iana", + extensions: ["st"] + }, + "application/vnd.sar": { + source: "iana" + }, + "application/vnd.sbm.cid": { + source: "iana" + }, + "application/vnd.sbm.mid2": { + source: "iana" + }, + "application/vnd.scribus": { + source: "iana" + }, + "application/vnd.sealed.3df": { + source: "iana" + }, + "application/vnd.sealed.csf": { + source: "iana" + }, + "application/vnd.sealed.doc": { + source: "iana" + }, + "application/vnd.sealed.eml": { + source: "iana" + }, + "application/vnd.sealed.mht": { + source: "iana" + }, + "application/vnd.sealed.net": { + source: "iana" + }, + "application/vnd.sealed.ppt": { + source: "iana" + }, + "application/vnd.sealed.tiff": { + source: "iana" + }, + "application/vnd.sealed.xls": { + source: "iana" + }, + "application/vnd.sealedmedia.softseal.html": { + source: "iana" + }, + "application/vnd.sealedmedia.softseal.pdf": { + source: "iana" + }, + "application/vnd.seemail": { + source: "iana", + extensions: ["see"] + }, + "application/vnd.seis+json": { + source: "iana", + compressible: true + }, + "application/vnd.sema": { + source: "iana", + extensions: ["sema"] + }, + "application/vnd.semd": { + source: "iana", + extensions: ["semd"] + }, + "application/vnd.semf": { + source: "iana", + extensions: ["semf"] + }, + "application/vnd.shade-save-file": { + source: "iana" + }, + "application/vnd.shana.informed.formdata": { + source: "iana", + extensions: ["ifm"] + }, + "application/vnd.shana.informed.formtemplate": { + source: "iana", + extensions: ["itp"] + }, + "application/vnd.shana.informed.interchange": { + source: "iana", + extensions: ["iif"] + }, + "application/vnd.shana.informed.package": { + source: "iana", + extensions: ["ipk"] + }, + "application/vnd.shootproof+json": { + source: "iana", + compressible: true + }, + "application/vnd.shopkick+json": { + source: "iana", + compressible: true + }, + "application/vnd.shp": { + source: "iana" + }, + "application/vnd.shx": { + source: "iana" + }, + "application/vnd.sigrok.session": { + source: "iana" + }, + "application/vnd.simtech-mindmapper": { + source: "iana", + extensions: ["twd", "twds"] + }, + "application/vnd.siren+json": { + source: "iana", + compressible: true + }, + "application/vnd.smaf": { + source: "iana", + extensions: ["mmf"] + }, + "application/vnd.smart.notebook": { + source: "iana" + }, + "application/vnd.smart.teacher": { + source: "iana", + extensions: ["teacher"] + }, + "application/vnd.snesdev-page-table": { + source: "iana" + }, + "application/vnd.software602.filler.form+xml": { + source: "iana", + compressible: true, + extensions: ["fo"] + }, + "application/vnd.software602.filler.form-xml-zip": { + source: "iana" + }, + "application/vnd.solent.sdkm+xml": { + source: "iana", + compressible: true, + extensions: ["sdkm", "sdkd"] + }, + "application/vnd.spotfire.dxp": { + source: "iana", + extensions: ["dxp"] + }, + "application/vnd.spotfire.sfs": { + source: "iana", + extensions: ["sfs"] + }, + "application/vnd.sqlite3": { + source: "iana" + }, + "application/vnd.sss-cod": { + source: "iana" + }, + "application/vnd.sss-dtf": { + source: "iana" + }, + "application/vnd.sss-ntf": { + source: "iana" + }, + "application/vnd.stardivision.calc": { + source: "apache", + extensions: ["sdc"] + }, + "application/vnd.stardivision.draw": { + source: "apache", + extensions: ["sda"] + }, + "application/vnd.stardivision.impress": { + source: "apache", + extensions: ["sdd"] + }, + "application/vnd.stardivision.math": { + source: "apache", + extensions: ["smf"] + }, + "application/vnd.stardivision.writer": { + source: "apache", + extensions: ["sdw", "vor"] + }, + "application/vnd.stardivision.writer-global": { + source: "apache", + extensions: ["sgl"] + }, + "application/vnd.stepmania.package": { + source: "iana", + extensions: ["smzip"] + }, + "application/vnd.stepmania.stepchart": { + source: "iana", + extensions: ["sm"] + }, + "application/vnd.street-stream": { + source: "iana" + }, + "application/vnd.sun.wadl+xml": { + source: "iana", + compressible: true, + extensions: ["wadl"] + }, + "application/vnd.sun.xml.calc": { + source: "apache", + extensions: ["sxc"] + }, + "application/vnd.sun.xml.calc.template": { + source: "apache", + extensions: ["stc"] + }, + "application/vnd.sun.xml.draw": { + source: "apache", + extensions: ["sxd"] + }, + "application/vnd.sun.xml.draw.template": { + source: "apache", + extensions: ["std"] + }, + "application/vnd.sun.xml.impress": { + source: "apache", + extensions: ["sxi"] + }, + "application/vnd.sun.xml.impress.template": { + source: "apache", + extensions: ["sti"] + }, + "application/vnd.sun.xml.math": { + source: "apache", + extensions: ["sxm"] + }, + "application/vnd.sun.xml.writer": { + source: "apache", + extensions: ["sxw"] + }, + "application/vnd.sun.xml.writer.global": { + source: "apache", + extensions: ["sxg"] + }, + "application/vnd.sun.xml.writer.template": { + source: "apache", + extensions: ["stw"] + }, + "application/vnd.sus-calendar": { + source: "iana", + extensions: ["sus", "susp"] + }, + "application/vnd.svd": { + source: "iana", + extensions: ["svd"] + }, + "application/vnd.swiftview-ics": { + source: "iana" + }, + "application/vnd.sycle+xml": { + source: "iana", + compressible: true + }, + "application/vnd.syft+json": { + source: "iana", + compressible: true + }, + "application/vnd.symbian.install": { + source: "apache", + extensions: ["sis", "sisx"] + }, + "application/vnd.syncml+xml": { + source: "iana", + charset: "UTF-8", + compressible: true, + extensions: ["xsm"] + }, + "application/vnd.syncml.dm+wbxml": { + source: "iana", + charset: "UTF-8", + extensions: ["bdm"] + }, + "application/vnd.syncml.dm+xml": { + source: "iana", + charset: "UTF-8", + compressible: true, + extensions: ["xdm"] + }, + "application/vnd.syncml.dm.notification": { + source: "iana" + }, + "application/vnd.syncml.dmddf+wbxml": { + source: "iana" + }, + "application/vnd.syncml.dmddf+xml": { + source: "iana", + charset: "UTF-8", + compressible: true, + extensions: ["ddf"] + }, + "application/vnd.syncml.dmtnds+wbxml": { + source: "iana" + }, + "application/vnd.syncml.dmtnds+xml": { + source: "iana", + charset: "UTF-8", + compressible: true + }, + "application/vnd.syncml.ds.notification": { + source: "iana" + }, + "application/vnd.tableschema+json": { + source: "iana", + compressible: true + }, + "application/vnd.tao.intent-module-archive": { + source: "iana", + extensions: ["tao"] + }, + "application/vnd.tcpdump.pcap": { + source: "iana", + extensions: ["pcap", "cap", "dmp"] + }, + "application/vnd.think-cell.ppttc+json": { + source: "iana", + compressible: true + }, + "application/vnd.tmd.mediaflex.api+xml": { + source: "iana", + compressible: true + }, + "application/vnd.tml": { + source: "iana" + }, + "application/vnd.tmobile-livetv": { + source: "iana", + extensions: ["tmo"] + }, + "application/vnd.tri.onesource": { + source: "iana" + }, + "application/vnd.trid.tpt": { + source: "iana", + extensions: ["tpt"] + }, + "application/vnd.triscape.mxs": { + source: "iana", + extensions: ["mxs"] + }, + "application/vnd.trueapp": { + source: "iana", + extensions: ["tra"] + }, + "application/vnd.truedoc": { + source: "iana" + }, + "application/vnd.ubisoft.webplayer": { + source: "iana" + }, + "application/vnd.ufdl": { + source: "iana", + extensions: ["ufd", "ufdl"] + }, + "application/vnd.uiq.theme": { + source: "iana", + extensions: ["utz"] + }, + "application/vnd.umajin": { + source: "iana", + extensions: ["umj"] + }, + "application/vnd.unity": { + source: "iana", + extensions: ["unityweb"] + }, + "application/vnd.uoml+xml": { + source: "iana", + compressible: true, + extensions: ["uoml"] + }, + "application/vnd.uplanet.alert": { + source: "iana" + }, + "application/vnd.uplanet.alert-wbxml": { + source: "iana" + }, + "application/vnd.uplanet.bearer-choice": { + source: "iana" + }, + "application/vnd.uplanet.bearer-choice-wbxml": { + source: "iana" + }, + "application/vnd.uplanet.cacheop": { + source: "iana" + }, + "application/vnd.uplanet.cacheop-wbxml": { + source: "iana" + }, + "application/vnd.uplanet.channel": { + source: "iana" + }, + "application/vnd.uplanet.channel-wbxml": { + source: "iana" + }, + "application/vnd.uplanet.list": { + source: "iana" + }, + "application/vnd.uplanet.list-wbxml": { + source: "iana" + }, + "application/vnd.uplanet.listcmd": { + source: "iana" + }, + "application/vnd.uplanet.listcmd-wbxml": { + source: "iana" + }, + "application/vnd.uplanet.signal": { + source: "iana" + }, + "application/vnd.uri-map": { + source: "iana" + }, + "application/vnd.valve.source.material": { + source: "iana" + }, + "application/vnd.vcx": { + source: "iana", + extensions: ["vcx"] + }, + "application/vnd.vd-study": { + source: "iana" + }, + "application/vnd.vectorworks": { + source: "iana" + }, + "application/vnd.vel+json": { + source: "iana", + compressible: true + }, + "application/vnd.verimatrix.vcas": { + source: "iana" + }, + "application/vnd.veritone.aion+json": { + source: "iana", + compressible: true + }, + "application/vnd.veryant.thin": { + source: "iana" + }, + "application/vnd.ves.encrypted": { + source: "iana" + }, + "application/vnd.vidsoft.vidconference": { + source: "iana" + }, + "application/vnd.visio": { + source: "iana", + extensions: ["vsd", "vst", "vss", "vsw"] + }, + "application/vnd.visionary": { + source: "iana", + extensions: ["vis"] + }, + "application/vnd.vividence.scriptfile": { + source: "iana" + }, + "application/vnd.vsf": { + source: "iana", + extensions: ["vsf"] + }, + "application/vnd.wap.sic": { + source: "iana" + }, + "application/vnd.wap.slc": { + source: "iana" + }, + "application/vnd.wap.wbxml": { + source: "iana", + charset: "UTF-8", + extensions: ["wbxml"] + }, + "application/vnd.wap.wmlc": { + source: "iana", + extensions: ["wmlc"] + }, + "application/vnd.wap.wmlscriptc": { + source: "iana", + extensions: ["wmlsc"] + }, + "application/vnd.webturbo": { + source: "iana", + extensions: ["wtb"] + }, + "application/vnd.wfa.dpp": { + source: "iana" + }, + "application/vnd.wfa.p2p": { + source: "iana" + }, + "application/vnd.wfa.wsc": { + source: "iana" + }, + "application/vnd.windows.devicepairing": { + source: "iana" + }, + "application/vnd.wmc": { + source: "iana" + }, + "application/vnd.wmf.bootstrap": { + source: "iana" + }, + "application/vnd.wolfram.mathematica": { + source: "iana" + }, + "application/vnd.wolfram.mathematica.package": { + source: "iana" + }, + "application/vnd.wolfram.player": { + source: "iana", + extensions: ["nbp"] + }, + "application/vnd.wordperfect": { + source: "iana", + extensions: ["wpd"] + }, + "application/vnd.wqd": { + source: "iana", + extensions: ["wqd"] + }, + "application/vnd.wrq-hp3000-labelled": { + source: "iana" + }, + "application/vnd.wt.stf": { + source: "iana", + extensions: ["stf"] + }, + "application/vnd.wv.csp+wbxml": { + source: "iana" + }, + "application/vnd.wv.csp+xml": { + source: "iana", + compressible: true + }, + "application/vnd.wv.ssp+xml": { + source: "iana", + compressible: true + }, + "application/vnd.xacml+json": { + source: "iana", + compressible: true + }, + "application/vnd.xara": { + source: "iana", + extensions: ["xar"] + }, + "application/vnd.xfdl": { + source: "iana", + extensions: ["xfdl"] + }, + "application/vnd.xfdl.webform": { + source: "iana" + }, + "application/vnd.xmi+xml": { + source: "iana", + compressible: true + }, + "application/vnd.xmpie.cpkg": { + source: "iana" + }, + "application/vnd.xmpie.dpkg": { + source: "iana" + }, + "application/vnd.xmpie.plan": { + source: "iana" + }, + "application/vnd.xmpie.ppkg": { + source: "iana" + }, + "application/vnd.xmpie.xlim": { + source: "iana" + }, + "application/vnd.yamaha.hv-dic": { + source: "iana", + extensions: ["hvd"] + }, + "application/vnd.yamaha.hv-script": { + source: "iana", + extensions: ["hvs"] + }, + "application/vnd.yamaha.hv-voice": { + source: "iana", + extensions: ["hvp"] + }, + "application/vnd.yamaha.openscoreformat": { + source: "iana", + extensions: ["osf"] + }, + "application/vnd.yamaha.openscoreformat.osfpvg+xml": { + source: "iana", + compressible: true, + extensions: ["osfpvg"] + }, + "application/vnd.yamaha.remote-setup": { + source: "iana" + }, + "application/vnd.yamaha.smaf-audio": { + source: "iana", + extensions: ["saf"] + }, + "application/vnd.yamaha.smaf-phrase": { + source: "iana", + extensions: ["spf"] + }, + "application/vnd.yamaha.through-ngn": { + source: "iana" + }, + "application/vnd.yamaha.tunnel-udpencap": { + source: "iana" + }, + "application/vnd.yaoweme": { + source: "iana" + }, + "application/vnd.yellowriver-custom-menu": { + source: "iana", + extensions: ["cmp"] + }, + "application/vnd.youtube.yt": { + source: "iana" + }, + "application/vnd.zul": { + source: "iana", + extensions: ["zir", "zirz"] + }, + "application/vnd.zzazz.deck+xml": { + source: "iana", + compressible: true, + extensions: ["zaz"] + }, + "application/voicexml+xml": { + source: "iana", + compressible: true, + extensions: ["vxml"] + }, + "application/voucher-cms+json": { + source: "iana", + compressible: true + }, + "application/vq-rtcpxr": { + source: "iana" + }, + "application/wasm": { + source: "iana", + compressible: true, + extensions: ["wasm"] + }, + "application/watcherinfo+xml": { + source: "iana", + compressible: true, + extensions: ["wif"] + }, + "application/webpush-options+json": { + source: "iana", + compressible: true + }, + "application/whoispp-query": { + source: "iana" + }, + "application/whoispp-response": { + source: "iana" + }, + "application/widget": { + source: "iana", + extensions: ["wgt"] + }, + "application/winhlp": { + source: "apache", + extensions: ["hlp"] + }, + "application/wita": { + source: "iana" + }, + "application/wordperfect5.1": { + source: "iana" + }, + "application/wsdl+xml": { + source: "iana", + compressible: true, + extensions: ["wsdl"] + }, + "application/wspolicy+xml": { + source: "iana", + compressible: true, + extensions: ["wspolicy"] + }, + "application/x-7z-compressed": { + source: "apache", + compressible: false, + extensions: ["7z"] + }, + "application/x-abiword": { + source: "apache", + extensions: ["abw"] + }, + "application/x-ace-compressed": { + source: "apache", + extensions: ["ace"] + }, + "application/x-amf": { + source: "apache" + }, + "application/x-apple-diskimage": { + source: "apache", + extensions: ["dmg"] + }, + "application/x-arj": { + compressible: false, + extensions: ["arj"] + }, + "application/x-authorware-bin": { + source: "apache", + extensions: ["aab", "x32", "u32", "vox"] + }, + "application/x-authorware-map": { + source: "apache", + extensions: ["aam"] + }, + "application/x-authorware-seg": { + source: "apache", + extensions: ["aas"] + }, + "application/x-bcpio": { + source: "apache", + extensions: ["bcpio"] + }, + "application/x-bdoc": { + compressible: false, + extensions: ["bdoc"] + }, + "application/x-bittorrent": { + source: "apache", + extensions: ["torrent"] + }, + "application/x-blorb": { + source: "apache", + extensions: ["blb", "blorb"] + }, + "application/x-bzip": { + source: "apache", + compressible: false, + extensions: ["bz"] + }, + "application/x-bzip2": { + source: "apache", + compressible: false, + extensions: ["bz2", "boz"] + }, + "application/x-cbr": { + source: "apache", + extensions: ["cbr", "cba", "cbt", "cbz", "cb7"] + }, + "application/x-cdlink": { + source: "apache", + extensions: ["vcd"] + }, + "application/x-cfs-compressed": { + source: "apache", + extensions: ["cfs"] + }, + "application/x-chat": { + source: "apache", + extensions: ["chat"] + }, + "application/x-chess-pgn": { + source: "apache", + extensions: ["pgn"] + }, + "application/x-chrome-extension": { + extensions: ["crx"] + }, + "application/x-cocoa": { + source: "nginx", + extensions: ["cco"] + }, + "application/x-compress": { + source: "apache" + }, + "application/x-conference": { + source: "apache", + extensions: ["nsc"] + }, + "application/x-cpio": { + source: "apache", + extensions: ["cpio"] + }, + "application/x-csh": { + source: "apache", + extensions: ["csh"] + }, + "application/x-deb": { + compressible: false + }, + "application/x-debian-package": { + source: "apache", + extensions: ["deb", "udeb"] + }, + "application/x-dgc-compressed": { + source: "apache", + extensions: ["dgc"] + }, + "application/x-director": { + source: "apache", + extensions: ["dir", "dcr", "dxr", "cst", "cct", "cxt", "w3d", "fgd", "swa"] + }, + "application/x-doom": { + source: "apache", + extensions: ["wad"] + }, + "application/x-dtbncx+xml": { + source: "apache", + compressible: true, + extensions: ["ncx"] + }, + "application/x-dtbook+xml": { + source: "apache", + compressible: true, + extensions: ["dtb"] + }, + "application/x-dtbresource+xml": { + source: "apache", + compressible: true, + extensions: ["res"] + }, + "application/x-dvi": { + source: "apache", + compressible: false, + extensions: ["dvi"] + }, + "application/x-envoy": { + source: "apache", + extensions: ["evy"] + }, + "application/x-eva": { + source: "apache", + extensions: ["eva"] + }, + "application/x-font-bdf": { + source: "apache", + extensions: ["bdf"] + }, + "application/x-font-dos": { + source: "apache" + }, + "application/x-font-framemaker": { + source: "apache" + }, + "application/x-font-ghostscript": { + source: "apache", + extensions: ["gsf"] + }, + "application/x-font-libgrx": { + source: "apache" + }, + "application/x-font-linux-psf": { + source: "apache", + extensions: ["psf"] + }, + "application/x-font-pcf": { + source: "apache", + extensions: ["pcf"] + }, + "application/x-font-snf": { + source: "apache", + extensions: ["snf"] + }, + "application/x-font-speedo": { + source: "apache" + }, + "application/x-font-sunos-news": { + source: "apache" + }, + "application/x-font-type1": { + source: "apache", + extensions: ["pfa", "pfb", "pfm", "afm"] + }, + "application/x-font-vfont": { + source: "apache" + }, + "application/x-freearc": { + source: "apache", + extensions: ["arc"] + }, + "application/x-futuresplash": { + source: "apache", + extensions: ["spl"] + }, + "application/x-gca-compressed": { + source: "apache", + extensions: ["gca"] + }, + "application/x-glulx": { + source: "apache", + extensions: ["ulx"] + }, + "application/x-gnumeric": { + source: "apache", + extensions: ["gnumeric"] + }, + "application/x-gramps-xml": { + source: "apache", + extensions: ["gramps"] + }, + "application/x-gtar": { + source: "apache", + extensions: ["gtar"] + }, + "application/x-gzip": { + source: "apache" + }, + "application/x-hdf": { + source: "apache", + extensions: ["hdf"] + }, + "application/x-httpd-php": { + compressible: true, + extensions: ["php"] + }, + "application/x-install-instructions": { + source: "apache", + extensions: ["install"] + }, + "application/x-iso9660-image": { + source: "apache", + extensions: ["iso"] + }, + "application/x-iwork-keynote-sffkey": { + extensions: ["key"] + }, + "application/x-iwork-numbers-sffnumbers": { + extensions: ["numbers"] + }, + "application/x-iwork-pages-sffpages": { + extensions: ["pages"] + }, + "application/x-java-archive-diff": { + source: "nginx", + extensions: ["jardiff"] + }, + "application/x-java-jnlp-file": { + source: "apache", + compressible: false, + extensions: ["jnlp"] + }, + "application/x-javascript": { + compressible: true + }, + "application/x-keepass2": { + extensions: ["kdbx"] + }, + "application/x-latex": { + source: "apache", + compressible: false, + extensions: ["latex"] + }, + "application/x-lua-bytecode": { + extensions: ["luac"] + }, + "application/x-lzh-compressed": { + source: "apache", + extensions: ["lzh", "lha"] + }, + "application/x-makeself": { + source: "nginx", + extensions: ["run"] + }, + "application/x-mie": { + source: "apache", + extensions: ["mie"] + }, + "application/x-mobipocket-ebook": { + source: "apache", + extensions: ["prc", "mobi"] + }, + "application/x-mpegurl": { + compressible: false + }, + "application/x-ms-application": { + source: "apache", + extensions: ["application"] + }, + "application/x-ms-shortcut": { + source: "apache", + extensions: ["lnk"] + }, + "application/x-ms-wmd": { + source: "apache", + extensions: ["wmd"] + }, + "application/x-ms-wmz": { + source: "apache", + extensions: ["wmz"] + }, + "application/x-ms-xbap": { + source: "apache", + extensions: ["xbap"] + }, + "application/x-msaccess": { + source: "apache", + extensions: ["mdb"] + }, + "application/x-msbinder": { + source: "apache", + extensions: ["obd"] + }, + "application/x-mscardfile": { + source: "apache", + extensions: ["crd"] + }, + "application/x-msclip": { + source: "apache", + extensions: ["clp"] + }, + "application/x-msdos-program": { + extensions: ["exe"] + }, + "application/x-msdownload": { + source: "apache", + extensions: ["exe", "dll", "com", "bat", "msi"] + }, + "application/x-msmediaview": { + source: "apache", + extensions: ["mvb", "m13", "m14"] + }, + "application/x-msmetafile": { + source: "apache", + extensions: ["wmf", "wmz", "emf", "emz"] + }, + "application/x-msmoney": { + source: "apache", + extensions: ["mny"] + }, + "application/x-mspublisher": { + source: "apache", + extensions: ["pub"] + }, + "application/x-msschedule": { + source: "apache", + extensions: ["scd"] + }, + "application/x-msterminal": { + source: "apache", + extensions: ["trm"] + }, + "application/x-mswrite": { + source: "apache", + extensions: ["wri"] + }, + "application/x-netcdf": { + source: "apache", + extensions: ["nc", "cdf"] + }, + "application/x-ns-proxy-autoconfig": { + compressible: true, + extensions: ["pac"] + }, + "application/x-nzb": { + source: "apache", + extensions: ["nzb"] + }, + "application/x-perl": { + source: "nginx", + extensions: ["pl", "pm"] + }, + "application/x-pilot": { + source: "nginx", + extensions: ["prc", "pdb"] + }, + "application/x-pkcs12": { + source: "apache", + compressible: false, + extensions: ["p12", "pfx"] + }, + "application/x-pkcs7-certificates": { + source: "apache", + extensions: ["p7b", "spc"] + }, + "application/x-pkcs7-certreqresp": { + source: "apache", + extensions: ["p7r"] + }, + "application/x-pki-message": { + source: "iana" + }, + "application/x-rar-compressed": { + source: "apache", + compressible: false, + extensions: ["rar"] + }, + "application/x-redhat-package-manager": { + source: "nginx", + extensions: ["rpm"] + }, + "application/x-research-info-systems": { + source: "apache", + extensions: ["ris"] + }, + "application/x-sea": { + source: "nginx", + extensions: ["sea"] + }, + "application/x-sh": { + source: "apache", + compressible: true, + extensions: ["sh"] + }, + "application/x-shar": { + source: "apache", + extensions: ["shar"] + }, + "application/x-shockwave-flash": { + source: "apache", + compressible: false, + extensions: ["swf"] + }, + "application/x-silverlight-app": { + source: "apache", + extensions: ["xap"] + }, + "application/x-sql": { + source: "apache", + extensions: ["sql"] + }, + "application/x-stuffit": { + source: "apache", + compressible: false, + extensions: ["sit"] + }, + "application/x-stuffitx": { + source: "apache", + extensions: ["sitx"] + }, + "application/x-subrip": { + source: "apache", + extensions: ["srt"] + }, + "application/x-sv4cpio": { + source: "apache", + extensions: ["sv4cpio"] + }, + "application/x-sv4crc": { + source: "apache", + extensions: ["sv4crc"] + }, + "application/x-t3vm-image": { + source: "apache", + extensions: ["t3"] + }, + "application/x-tads": { + source: "apache", + extensions: ["gam"] + }, + "application/x-tar": { + source: "apache", + compressible: true, + extensions: ["tar"] + }, + "application/x-tcl": { + source: "apache", + extensions: ["tcl", "tk"] + }, + "application/x-tex": { + source: "apache", + extensions: ["tex"] + }, + "application/x-tex-tfm": { + source: "apache", + extensions: ["tfm"] + }, + "application/x-texinfo": { + source: "apache", + extensions: ["texinfo", "texi"] + }, + "application/x-tgif": { + source: "apache", + extensions: ["obj"] + }, + "application/x-ustar": { + source: "apache", + extensions: ["ustar"] + }, + "application/x-virtualbox-hdd": { + compressible: true, + extensions: ["hdd"] + }, + "application/x-virtualbox-ova": { + compressible: true, + extensions: ["ova"] + }, + "application/x-virtualbox-ovf": { + compressible: true, + extensions: ["ovf"] + }, + "application/x-virtualbox-vbox": { + compressible: true, + extensions: ["vbox"] + }, + "application/x-virtualbox-vbox-extpack": { + compressible: false, + extensions: ["vbox-extpack"] + }, + "application/x-virtualbox-vdi": { + compressible: true, + extensions: ["vdi"] + }, + "application/x-virtualbox-vhd": { + compressible: true, + extensions: ["vhd"] + }, + "application/x-virtualbox-vmdk": { + compressible: true, + extensions: ["vmdk"] + }, + "application/x-wais-source": { + source: "apache", + extensions: ["src"] + }, + "application/x-web-app-manifest+json": { + compressible: true, + extensions: ["webapp"] + }, + "application/x-www-form-urlencoded": { + source: "iana", + compressible: true + }, + "application/x-x509-ca-cert": { + source: "iana", + extensions: ["der", "crt", "pem"] + }, + "application/x-x509-ca-ra-cert": { + source: "iana" + }, + "application/x-x509-next-ca-cert": { + source: "iana" + }, + "application/x-xfig": { + source: "apache", + extensions: ["fig"] + }, + "application/x-xliff+xml": { + source: "apache", + compressible: true, + extensions: ["xlf"] + }, + "application/x-xpinstall": { + source: "apache", + compressible: false, + extensions: ["xpi"] + }, + "application/x-xz": { + source: "apache", + extensions: ["xz"] + }, + "application/x-zmachine": { + source: "apache", + extensions: ["z1", "z2", "z3", "z4", "z5", "z6", "z7", "z8"] + }, + "application/x400-bp": { + source: "iana" + }, + "application/xacml+xml": { + source: "iana", + compressible: true + }, + "application/xaml+xml": { + source: "apache", + compressible: true, + extensions: ["xaml"] + }, + "application/xcap-att+xml": { + source: "iana", + compressible: true, + extensions: ["xav"] + }, + "application/xcap-caps+xml": { + source: "iana", + compressible: true, + extensions: ["xca"] + }, + "application/xcap-diff+xml": { + source: "iana", + compressible: true, + extensions: ["xdf"] + }, + "application/xcap-el+xml": { + source: "iana", + compressible: true, + extensions: ["xel"] + }, + "application/xcap-error+xml": { + source: "iana", + compressible: true + }, + "application/xcap-ns+xml": { + source: "iana", + compressible: true, + extensions: ["xns"] + }, + "application/xcon-conference-info+xml": { + source: "iana", + compressible: true + }, + "application/xcon-conference-info-diff+xml": { + source: "iana", + compressible: true + }, + "application/xenc+xml": { + source: "iana", + compressible: true, + extensions: ["xenc"] + }, + "application/xhtml+xml": { + source: "iana", + compressible: true, + extensions: ["xhtml", "xht"] + }, + "application/xhtml-voice+xml": { + source: "apache", + compressible: true + }, + "application/xliff+xml": { + source: "iana", + compressible: true, + extensions: ["xlf"] + }, + "application/xml": { + source: "iana", + compressible: true, + extensions: ["xml", "xsl", "xsd", "rng"] + }, + "application/xml-dtd": { + source: "iana", + compressible: true, + extensions: ["dtd"] + }, + "application/xml-external-parsed-entity": { + source: "iana" + }, + "application/xml-patch+xml": { + source: "iana", + compressible: true + }, + "application/xmpp+xml": { + source: "iana", + compressible: true + }, + "application/xop+xml": { + source: "iana", + compressible: true, + extensions: ["xop"] + }, + "application/xproc+xml": { + source: "apache", + compressible: true, + extensions: ["xpl"] + }, + "application/xslt+xml": { + source: "iana", + compressible: true, + extensions: ["xsl", "xslt"] + }, + "application/xspf+xml": { + source: "apache", + compressible: true, + extensions: ["xspf"] + }, + "application/xv+xml": { + source: "iana", + compressible: true, + extensions: ["mxml", "xhvml", "xvml", "xvm"] + }, + "application/yang": { + source: "iana", + extensions: ["yang"] + }, + "application/yang-data+json": { + source: "iana", + compressible: true + }, + "application/yang-data+xml": { + source: "iana", + compressible: true + }, + "application/yang-patch+json": { + source: "iana", + compressible: true + }, + "application/yang-patch+xml": { + source: "iana", + compressible: true + }, + "application/yin+xml": { + source: "iana", + compressible: true, + extensions: ["yin"] + }, + "application/zip": { + source: "iana", + compressible: false, + extensions: ["zip"] + }, + "application/zlib": { + source: "iana" + }, + "application/zstd": { + source: "iana" + }, + "audio/1d-interleaved-parityfec": { + source: "iana" + }, + "audio/32kadpcm": { + source: "iana" + }, + "audio/3gpp": { + source: "iana", + compressible: false, + extensions: ["3gpp"] + }, + "audio/3gpp2": { + source: "iana" + }, + "audio/aac": { + source: "iana" + }, + "audio/ac3": { + source: "iana" + }, + "audio/adpcm": { + source: "apache", + extensions: ["adp"] + }, + "audio/amr": { + source: "iana", + extensions: ["amr"] + }, + "audio/amr-wb": { + source: "iana" + }, + "audio/amr-wb+": { + source: "iana" + }, + "audio/aptx": { + source: "iana" + }, + "audio/asc": { + source: "iana" + }, + "audio/atrac-advanced-lossless": { + source: "iana" + }, + "audio/atrac-x": { + source: "iana" + }, + "audio/atrac3": { + source: "iana" + }, + "audio/basic": { + source: "iana", + compressible: false, + extensions: ["au", "snd"] + }, + "audio/bv16": { + source: "iana" + }, + "audio/bv32": { + source: "iana" + }, + "audio/clearmode": { + source: "iana" + }, + "audio/cn": { + source: "iana" + }, + "audio/dat12": { + source: "iana" + }, + "audio/dls": { + source: "iana" + }, + "audio/dsr-es201108": { + source: "iana" + }, + "audio/dsr-es202050": { + source: "iana" + }, + "audio/dsr-es202211": { + source: "iana" + }, + "audio/dsr-es202212": { + source: "iana" + }, + "audio/dv": { + source: "iana" + }, + "audio/dvi4": { + source: "iana" + }, + "audio/eac3": { + source: "iana" + }, + "audio/encaprtp": { + source: "iana" + }, + "audio/evrc": { + source: "iana" + }, + "audio/evrc-qcp": { + source: "iana" + }, + "audio/evrc0": { + source: "iana" + }, + "audio/evrc1": { + source: "iana" + }, + "audio/evrcb": { + source: "iana" + }, + "audio/evrcb0": { + source: "iana" + }, + "audio/evrcb1": { + source: "iana" + }, + "audio/evrcnw": { + source: "iana" + }, + "audio/evrcnw0": { + source: "iana" + }, + "audio/evrcnw1": { + source: "iana" + }, + "audio/evrcwb": { + source: "iana" + }, + "audio/evrcwb0": { + source: "iana" + }, + "audio/evrcwb1": { + source: "iana" + }, + "audio/evs": { + source: "iana" + }, + "audio/flexfec": { + source: "iana" + }, + "audio/fwdred": { + source: "iana" + }, + "audio/g711-0": { + source: "iana" + }, + "audio/g719": { + source: "iana" + }, + "audio/g722": { + source: "iana" + }, + "audio/g7221": { + source: "iana" + }, + "audio/g723": { + source: "iana" + }, + "audio/g726-16": { + source: "iana" + }, + "audio/g726-24": { + source: "iana" + }, + "audio/g726-32": { + source: "iana" + }, + "audio/g726-40": { + source: "iana" + }, + "audio/g728": { + source: "iana" + }, + "audio/g729": { + source: "iana" + }, + "audio/g7291": { + source: "iana" + }, + "audio/g729d": { + source: "iana" + }, + "audio/g729e": { + source: "iana" + }, + "audio/gsm": { + source: "iana" + }, + "audio/gsm-efr": { + source: "iana" + }, + "audio/gsm-hr-08": { + source: "iana" + }, + "audio/ilbc": { + source: "iana" + }, + "audio/ip-mr_v2.5": { + source: "iana" + }, + "audio/isac": { + source: "apache" + }, + "audio/l16": { + source: "iana" + }, + "audio/l20": { + source: "iana" + }, + "audio/l24": { + source: "iana", + compressible: false + }, + "audio/l8": { + source: "iana" + }, + "audio/lpc": { + source: "iana" + }, + "audio/melp": { + source: "iana" + }, + "audio/melp1200": { + source: "iana" + }, + "audio/melp2400": { + source: "iana" + }, + "audio/melp600": { + source: "iana" + }, + "audio/mhas": { + source: "iana" + }, + "audio/midi": { + source: "apache", + extensions: ["mid", "midi", "kar", "rmi"] + }, + "audio/mobile-xmf": { + source: "iana", + extensions: ["mxmf"] + }, + "audio/mp3": { + compressible: false, + extensions: ["mp3"] + }, + "audio/mp4": { + source: "iana", + compressible: false, + extensions: ["m4a", "mp4a"] + }, + "audio/mp4a-latm": { + source: "iana" + }, + "audio/mpa": { + source: "iana" + }, + "audio/mpa-robust": { + source: "iana" + }, + "audio/mpeg": { + source: "iana", + compressible: false, + extensions: ["mpga", "mp2", "mp2a", "mp3", "m2a", "m3a"] + }, + "audio/mpeg4-generic": { + source: "iana" + }, + "audio/musepack": { + source: "apache" + }, + "audio/ogg": { + source: "iana", + compressible: false, + extensions: ["oga", "ogg", "spx", "opus"] + }, + "audio/opus": { + source: "iana" + }, + "audio/parityfec": { + source: "iana" + }, + "audio/pcma": { + source: "iana" + }, + "audio/pcma-wb": { + source: "iana" + }, + "audio/pcmu": { + source: "iana" + }, + "audio/pcmu-wb": { + source: "iana" + }, + "audio/prs.sid": { + source: "iana" + }, + "audio/qcelp": { + source: "iana" + }, + "audio/raptorfec": { + source: "iana" + }, + "audio/red": { + source: "iana" + }, + "audio/rtp-enc-aescm128": { + source: "iana" + }, + "audio/rtp-midi": { + source: "iana" + }, + "audio/rtploopback": { + source: "iana" + }, + "audio/rtx": { + source: "iana" + }, + "audio/s3m": { + source: "apache", + extensions: ["s3m"] + }, + "audio/scip": { + source: "iana" + }, + "audio/silk": { + source: "apache", + extensions: ["sil"] + }, + "audio/smv": { + source: "iana" + }, + "audio/smv-qcp": { + source: "iana" + }, + "audio/smv0": { + source: "iana" + }, + "audio/sofa": { + source: "iana" + }, + "audio/sp-midi": { + source: "iana" + }, + "audio/speex": { + source: "iana" + }, + "audio/t140c": { + source: "iana" + }, + "audio/t38": { + source: "iana" + }, + "audio/telephone-event": { + source: "iana" + }, + "audio/tetra_acelp": { + source: "iana" + }, + "audio/tetra_acelp_bb": { + source: "iana" + }, + "audio/tone": { + source: "iana" + }, + "audio/tsvcis": { + source: "iana" + }, + "audio/uemclip": { + source: "iana" + }, + "audio/ulpfec": { + source: "iana" + }, + "audio/usac": { + source: "iana" + }, + "audio/vdvi": { + source: "iana" + }, + "audio/vmr-wb": { + source: "iana" + }, + "audio/vnd.3gpp.iufp": { + source: "iana" + }, + "audio/vnd.4sb": { + source: "iana" + }, + "audio/vnd.audiokoz": { + source: "iana" + }, + "audio/vnd.celp": { + source: "iana" + }, + "audio/vnd.cisco.nse": { + source: "iana" + }, + "audio/vnd.cmles.radio-events": { + source: "iana" + }, + "audio/vnd.cns.anp1": { + source: "iana" + }, + "audio/vnd.cns.inf1": { + source: "iana" + }, + "audio/vnd.dece.audio": { + source: "iana", + extensions: ["uva", "uvva"] + }, + "audio/vnd.digital-winds": { + source: "iana", + extensions: ["eol"] + }, + "audio/vnd.dlna.adts": { + source: "iana" + }, + "audio/vnd.dolby.heaac.1": { + source: "iana" + }, + "audio/vnd.dolby.heaac.2": { + source: "iana" + }, + "audio/vnd.dolby.mlp": { + source: "iana" + }, + "audio/vnd.dolby.mps": { + source: "iana" + }, + "audio/vnd.dolby.pl2": { + source: "iana" + }, + "audio/vnd.dolby.pl2x": { + source: "iana" + }, + "audio/vnd.dolby.pl2z": { + source: "iana" + }, + "audio/vnd.dolby.pulse.1": { + source: "iana" + }, + "audio/vnd.dra": { + source: "iana", + extensions: ["dra"] + }, + "audio/vnd.dts": { + source: "iana", + extensions: ["dts"] + }, + "audio/vnd.dts.hd": { + source: "iana", + extensions: ["dtshd"] + }, + "audio/vnd.dts.uhd": { + source: "iana" + }, + "audio/vnd.dvb.file": { + source: "iana" + }, + "audio/vnd.everad.plj": { + source: "iana" + }, + "audio/vnd.hns.audio": { + source: "iana" + }, + "audio/vnd.lucent.voice": { + source: "iana", + extensions: ["lvp"] + }, + "audio/vnd.ms-playready.media.pya": { + source: "iana", + extensions: ["pya"] + }, + "audio/vnd.nokia.mobile-xmf": { + source: "iana" + }, + "audio/vnd.nortel.vbk": { + source: "iana" + }, + "audio/vnd.nuera.ecelp4800": { + source: "iana", + extensions: ["ecelp4800"] + }, + "audio/vnd.nuera.ecelp7470": { + source: "iana", + extensions: ["ecelp7470"] + }, + "audio/vnd.nuera.ecelp9600": { + source: "iana", + extensions: ["ecelp9600"] + }, + "audio/vnd.octel.sbc": { + source: "iana" + }, + "audio/vnd.presonus.multitrack": { + source: "iana" + }, + "audio/vnd.qcelp": { + source: "iana" + }, + "audio/vnd.rhetorex.32kadpcm": { + source: "iana" + }, + "audio/vnd.rip": { + source: "iana", + extensions: ["rip"] + }, + "audio/vnd.rn-realaudio": { + compressible: false + }, + "audio/vnd.sealedmedia.softseal.mpeg": { + source: "iana" + }, + "audio/vnd.vmx.cvsd": { + source: "iana" + }, + "audio/vnd.wave": { + compressible: false + }, + "audio/vorbis": { + source: "iana", + compressible: false + }, + "audio/vorbis-config": { + source: "iana" + }, + "audio/wav": { + compressible: false, + extensions: ["wav"] + }, + "audio/wave": { + compressible: false, + extensions: ["wav"] + }, + "audio/webm": { + source: "apache", + compressible: false, + extensions: ["weba"] + }, + "audio/x-aac": { + source: "apache", + compressible: false, + extensions: ["aac"] + }, + "audio/x-aiff": { + source: "apache", + extensions: ["aif", "aiff", "aifc"] + }, + "audio/x-caf": { + source: "apache", + compressible: false, + extensions: ["caf"] + }, + "audio/x-flac": { + source: "apache", + extensions: ["flac"] + }, + "audio/x-m4a": { + source: "nginx", + extensions: ["m4a"] + }, + "audio/x-matroska": { + source: "apache", + extensions: ["mka"] + }, + "audio/x-mpegurl": { + source: "apache", + extensions: ["m3u"] + }, + "audio/x-ms-wax": { + source: "apache", + extensions: ["wax"] + }, + "audio/x-ms-wma": { + source: "apache", + extensions: ["wma"] + }, + "audio/x-pn-realaudio": { + source: "apache", + extensions: ["ram", "ra"] + }, + "audio/x-pn-realaudio-plugin": { + source: "apache", + extensions: ["rmp"] + }, + "audio/x-realaudio": { + source: "nginx", + extensions: ["ra"] + }, + "audio/x-tta": { + source: "apache" + }, + "audio/x-wav": { + source: "apache", + extensions: ["wav"] + }, + "audio/xm": { + source: "apache", + extensions: ["xm"] + }, + "chemical/x-cdx": { + source: "apache", + extensions: ["cdx"] + }, + "chemical/x-cif": { + source: "apache", + extensions: ["cif"] + }, + "chemical/x-cmdf": { + source: "apache", + extensions: ["cmdf"] + }, + "chemical/x-cml": { + source: "apache", + extensions: ["cml"] + }, + "chemical/x-csml": { + source: "apache", + extensions: ["csml"] + }, + "chemical/x-pdb": { + source: "apache" + }, + "chemical/x-xyz": { + source: "apache", + extensions: ["xyz"] + }, + "font/collection": { + source: "iana", + extensions: ["ttc"] + }, + "font/otf": { + source: "iana", + compressible: true, + extensions: ["otf"] + }, + "font/sfnt": { + source: "iana" + }, + "font/ttf": { + source: "iana", + compressible: true, + extensions: ["ttf"] + }, + "font/woff": { + source: "iana", + extensions: ["woff"] + }, + "font/woff2": { + source: "iana", + extensions: ["woff2"] + }, + "image/aces": { + source: "iana", + extensions: ["exr"] + }, + "image/apng": { + compressible: false, + extensions: ["apng"] + }, + "image/avci": { + source: "iana", + extensions: ["avci"] + }, + "image/avcs": { + source: "iana", + extensions: ["avcs"] + }, + "image/avif": { + source: "iana", + compressible: false, + extensions: ["avif"] + }, + "image/bmp": { + source: "iana", + compressible: true, + extensions: ["bmp"] + }, + "image/cgm": { + source: "iana", + extensions: ["cgm"] + }, + "image/dicom-rle": { + source: "iana", + extensions: ["drle"] + }, + "image/emf": { + source: "iana", + extensions: ["emf"] + }, + "image/fits": { + source: "iana", + extensions: ["fits"] + }, + "image/g3fax": { + source: "iana", + extensions: ["g3"] + }, + "image/gif": { + source: "iana", + compressible: false, + extensions: ["gif"] + }, + "image/heic": { + source: "iana", + extensions: ["heic"] + }, + "image/heic-sequence": { + source: "iana", + extensions: ["heics"] + }, + "image/heif": { + source: "iana", + extensions: ["heif"] + }, + "image/heif-sequence": { + source: "iana", + extensions: ["heifs"] + }, + "image/hej2k": { + source: "iana", + extensions: ["hej2"] + }, + "image/hsj2": { + source: "iana", + extensions: ["hsj2"] + }, + "image/ief": { + source: "iana", + extensions: ["ief"] + }, + "image/jls": { + source: "iana", + extensions: ["jls"] + }, + "image/jp2": { + source: "iana", + compressible: false, + extensions: ["jp2", "jpg2"] + }, + "image/jpeg": { + source: "iana", + compressible: false, + extensions: ["jpeg", "jpg", "jpe"] + }, + "image/jph": { + source: "iana", + extensions: ["jph"] + }, + "image/jphc": { + source: "iana", + extensions: ["jhc"] + }, + "image/jpm": { + source: "iana", + compressible: false, + extensions: ["jpm"] + }, + "image/jpx": { + source: "iana", + compressible: false, + extensions: ["jpx", "jpf"] + }, + "image/jxr": { + source: "iana", + extensions: ["jxr"] + }, + "image/jxra": { + source: "iana", + extensions: ["jxra"] + }, + "image/jxrs": { + source: "iana", + extensions: ["jxrs"] + }, + "image/jxs": { + source: "iana", + extensions: ["jxs"] + }, + "image/jxsc": { + source: "iana", + extensions: ["jxsc"] + }, + "image/jxsi": { + source: "iana", + extensions: ["jxsi"] + }, + "image/jxss": { + source: "iana", + extensions: ["jxss"] + }, + "image/ktx": { + source: "iana", + extensions: ["ktx"] + }, + "image/ktx2": { + source: "iana", + extensions: ["ktx2"] + }, + "image/naplps": { + source: "iana" + }, + "image/pjpeg": { + compressible: false + }, + "image/png": { + source: "iana", + compressible: false, + extensions: ["png"] + }, + "image/prs.btif": { + source: "iana", + extensions: ["btif"] + }, + "image/prs.pti": { + source: "iana", + extensions: ["pti"] + }, + "image/pwg-raster": { + source: "iana" + }, + "image/sgi": { + source: "apache", + extensions: ["sgi"] + }, + "image/svg+xml": { + source: "iana", + compressible: true, + extensions: ["svg", "svgz"] + }, + "image/t38": { + source: "iana", + extensions: ["t38"] + }, + "image/tiff": { + source: "iana", + compressible: false, + extensions: ["tif", "tiff"] + }, + "image/tiff-fx": { + source: "iana", + extensions: ["tfx"] + }, + "image/vnd.adobe.photoshop": { + source: "iana", + compressible: true, + extensions: ["psd"] + }, + "image/vnd.airzip.accelerator.azv": { + source: "iana", + extensions: ["azv"] + }, + "image/vnd.cns.inf2": { + source: "iana" + }, + "image/vnd.dece.graphic": { + source: "iana", + extensions: ["uvi", "uvvi", "uvg", "uvvg"] + }, + "image/vnd.djvu": { + source: "iana", + extensions: ["djvu", "djv"] + }, + "image/vnd.dvb.subtitle": { + source: "iana", + extensions: ["sub"] + }, + "image/vnd.dwg": { + source: "iana", + extensions: ["dwg"] + }, + "image/vnd.dxf": { + source: "iana", + extensions: ["dxf"] + }, + "image/vnd.fastbidsheet": { + source: "iana", + extensions: ["fbs"] + }, + "image/vnd.fpx": { + source: "iana", + extensions: ["fpx"] + }, + "image/vnd.fst": { + source: "iana", + extensions: ["fst"] + }, + "image/vnd.fujixerox.edmics-mmr": { + source: "iana", + extensions: ["mmr"] + }, + "image/vnd.fujixerox.edmics-rlc": { + source: "iana", + extensions: ["rlc"] + }, + "image/vnd.globalgraphics.pgb": { + source: "iana" + }, + "image/vnd.microsoft.icon": { + source: "iana", + compressible: true, + extensions: ["ico"] + }, + "image/vnd.mix": { + source: "iana" + }, + "image/vnd.mozilla.apng": { + source: "iana" + }, + "image/vnd.ms-dds": { + compressible: true, + extensions: ["dds"] + }, + "image/vnd.ms-modi": { + source: "iana", + extensions: ["mdi"] + }, + "image/vnd.ms-photo": { + source: "apache", + extensions: ["wdp"] + }, + "image/vnd.net-fpx": { + source: "iana", + extensions: ["npx"] + }, + "image/vnd.pco.b16": { + source: "iana", + extensions: ["b16"] + }, + "image/vnd.radiance": { + source: "iana" + }, + "image/vnd.sealed.png": { + source: "iana" + }, + "image/vnd.sealedmedia.softseal.gif": { + source: "iana" + }, + "image/vnd.sealedmedia.softseal.jpg": { + source: "iana" + }, + "image/vnd.svf": { + source: "iana" + }, + "image/vnd.tencent.tap": { + source: "iana", + extensions: ["tap"] + }, + "image/vnd.valve.source.texture": { + source: "iana", + extensions: ["vtf"] + }, + "image/vnd.wap.wbmp": { + source: "iana", + extensions: ["wbmp"] + }, + "image/vnd.xiff": { + source: "iana", + extensions: ["xif"] + }, + "image/vnd.zbrush.pcx": { + source: "iana", + extensions: ["pcx"] + }, + "image/webp": { + source: "apache", + extensions: ["webp"] + }, + "image/wmf": { + source: "iana", + extensions: ["wmf"] + }, + "image/x-3ds": { + source: "apache", + extensions: ["3ds"] + }, + "image/x-cmu-raster": { + source: "apache", + extensions: ["ras"] + }, + "image/x-cmx": { + source: "apache", + extensions: ["cmx"] + }, + "image/x-freehand": { + source: "apache", + extensions: ["fh", "fhc", "fh4", "fh5", "fh7"] + }, + "image/x-icon": { + source: "apache", + compressible: true, + extensions: ["ico"] + }, + "image/x-jng": { + source: "nginx", + extensions: ["jng"] + }, + "image/x-mrsid-image": { + source: "apache", + extensions: ["sid"] + }, + "image/x-ms-bmp": { + source: "nginx", + compressible: true, + extensions: ["bmp"] + }, + "image/x-pcx": { + source: "apache", + extensions: ["pcx"] + }, + "image/x-pict": { + source: "apache", + extensions: ["pic", "pct"] + }, + "image/x-portable-anymap": { + source: "apache", + extensions: ["pnm"] + }, + "image/x-portable-bitmap": { + source: "apache", + extensions: ["pbm"] + }, + "image/x-portable-graymap": { + source: "apache", + extensions: ["pgm"] + }, + "image/x-portable-pixmap": { + source: "apache", + extensions: ["ppm"] + }, + "image/x-rgb": { + source: "apache", + extensions: ["rgb"] + }, + "image/x-tga": { + source: "apache", + extensions: ["tga"] + }, + "image/x-xbitmap": { + source: "apache", + extensions: ["xbm"] + }, + "image/x-xcf": { + compressible: false + }, + "image/x-xpixmap": { + source: "apache", + extensions: ["xpm"] + }, + "image/x-xwindowdump": { + source: "apache", + extensions: ["xwd"] + }, + "message/cpim": { + source: "iana" + }, + "message/delivery-status": { + source: "iana" + }, + "message/disposition-notification": { + source: "iana", + extensions: [ + "disposition-notification" + ] + }, + "message/external-body": { + source: "iana" + }, + "message/feedback-report": { + source: "iana" + }, + "message/global": { + source: "iana", + extensions: ["u8msg"] + }, + "message/global-delivery-status": { + source: "iana", + extensions: ["u8dsn"] + }, + "message/global-disposition-notification": { + source: "iana", + extensions: ["u8mdn"] + }, + "message/global-headers": { + source: "iana", + extensions: ["u8hdr"] + }, + "message/http": { + source: "iana", + compressible: false + }, + "message/imdn+xml": { + source: "iana", + compressible: true + }, + "message/news": { + source: "iana" + }, + "message/partial": { + source: "iana", + compressible: false + }, + "message/rfc822": { + source: "iana", + compressible: true, + extensions: ["eml", "mime"] + }, + "message/s-http": { + source: "iana" + }, + "message/sip": { + source: "iana" + }, + "message/sipfrag": { + source: "iana" + }, + "message/tracking-status": { + source: "iana" + }, + "message/vnd.si.simp": { + source: "iana" + }, + "message/vnd.wfa.wsc": { + source: "iana", + extensions: ["wsc"] + }, + "model/3mf": { + source: "iana", + extensions: ["3mf"] + }, + "model/e57": { + source: "iana" + }, + "model/gltf+json": { + source: "iana", + compressible: true, + extensions: ["gltf"] + }, + "model/gltf-binary": { + source: "iana", + compressible: true, + extensions: ["glb"] + }, + "model/iges": { + source: "iana", + compressible: false, + extensions: ["igs", "iges"] + }, + "model/mesh": { + source: "iana", + compressible: false, + extensions: ["msh", "mesh", "silo"] + }, + "model/mtl": { + source: "iana", + extensions: ["mtl"] + }, + "model/obj": { + source: "iana", + extensions: ["obj"] + }, + "model/step": { + source: "iana" + }, + "model/step+xml": { + source: "iana", + compressible: true, + extensions: ["stpx"] + }, + "model/step+zip": { + source: "iana", + compressible: false, + extensions: ["stpz"] + }, + "model/step-xml+zip": { + source: "iana", + compressible: false, + extensions: ["stpxz"] + }, + "model/stl": { + source: "iana", + extensions: ["stl"] + }, + "model/vnd.collada+xml": { + source: "iana", + compressible: true, + extensions: ["dae"] + }, + "model/vnd.dwf": { + source: "iana", + extensions: ["dwf"] + }, + "model/vnd.flatland.3dml": { + source: "iana" + }, + "model/vnd.gdl": { + source: "iana", + extensions: ["gdl"] + }, + "model/vnd.gs-gdl": { + source: "apache" + }, + "model/vnd.gs.gdl": { + source: "iana" + }, + "model/vnd.gtw": { + source: "iana", + extensions: ["gtw"] + }, + "model/vnd.moml+xml": { + source: "iana", + compressible: true + }, + "model/vnd.mts": { + source: "iana", + extensions: ["mts"] + }, + "model/vnd.opengex": { + source: "iana", + extensions: ["ogex"] + }, + "model/vnd.parasolid.transmit.binary": { + source: "iana", + extensions: ["x_b"] + }, + "model/vnd.parasolid.transmit.text": { + source: "iana", + extensions: ["x_t"] + }, + "model/vnd.pytha.pyox": { + source: "iana" + }, + "model/vnd.rosette.annotated-data-model": { + source: "iana" + }, + "model/vnd.sap.vds": { + source: "iana", + extensions: ["vds"] + }, + "model/vnd.usdz+zip": { + source: "iana", + compressible: false, + extensions: ["usdz"] + }, + "model/vnd.valve.source.compiled-map": { + source: "iana", + extensions: ["bsp"] + }, + "model/vnd.vtu": { + source: "iana", + extensions: ["vtu"] + }, + "model/vrml": { + source: "iana", + compressible: false, + extensions: ["wrl", "vrml"] + }, + "model/x3d+binary": { + source: "apache", + compressible: false, + extensions: ["x3db", "x3dbz"] + }, + "model/x3d+fastinfoset": { + source: "iana", + extensions: ["x3db"] + }, + "model/x3d+vrml": { + source: "apache", + compressible: false, + extensions: ["x3dv", "x3dvz"] + }, + "model/x3d+xml": { + source: "iana", + compressible: true, + extensions: ["x3d", "x3dz"] + }, + "model/x3d-vrml": { + source: "iana", + extensions: ["x3dv"] + }, + "multipart/alternative": { + source: "iana", + compressible: false + }, + "multipart/appledouble": { + source: "iana" + }, + "multipart/byteranges": { + source: "iana" + }, + "multipart/digest": { + source: "iana" + }, + "multipart/encrypted": { + source: "iana", + compressible: false + }, + "multipart/form-data": { + source: "iana", + compressible: false + }, + "multipart/header-set": { + source: "iana" + }, + "multipart/mixed": { + source: "iana" + }, + "multipart/multilingual": { + source: "iana" + }, + "multipart/parallel": { + source: "iana" + }, + "multipart/related": { + source: "iana", + compressible: false + }, + "multipart/report": { + source: "iana" + }, + "multipart/signed": { + source: "iana", + compressible: false + }, + "multipart/vnd.bint.med-plus": { + source: "iana" + }, + "multipart/voice-message": { + source: "iana" + }, + "multipart/x-mixed-replace": { + source: "iana" + }, + "text/1d-interleaved-parityfec": { + source: "iana" + }, + "text/cache-manifest": { + source: "iana", + compressible: true, + extensions: ["appcache", "manifest"] + }, + "text/calendar": { + source: "iana", + extensions: ["ics", "ifb"] + }, + "text/calender": { + compressible: true + }, + "text/cmd": { + compressible: true + }, + "text/coffeescript": { + extensions: ["coffee", "litcoffee"] + }, + "text/cql": { + source: "iana" + }, + "text/cql-expression": { + source: "iana" + }, + "text/cql-identifier": { + source: "iana" + }, + "text/css": { + source: "iana", + charset: "UTF-8", + compressible: true, + extensions: ["css"] + }, + "text/csv": { + source: "iana", + compressible: true, + extensions: ["csv"] + }, + "text/csv-schema": { + source: "iana" + }, + "text/directory": { + source: "iana" + }, + "text/dns": { + source: "iana" + }, + "text/ecmascript": { + source: "iana" + }, + "text/encaprtp": { + source: "iana" + }, + "text/enriched": { + source: "iana" + }, + "text/fhirpath": { + source: "iana" + }, + "text/flexfec": { + source: "iana" + }, + "text/fwdred": { + source: "iana" + }, + "text/gff3": { + source: "iana" + }, + "text/grammar-ref-list": { + source: "iana" + }, + "text/html": { + source: "iana", + compressible: true, + extensions: ["html", "htm", "shtml"] + }, + "text/jade": { + extensions: ["jade"] + }, + "text/javascript": { + source: "iana", + compressible: true + }, + "text/jcr-cnd": { + source: "iana" + }, + "text/jsx": { + compressible: true, + extensions: ["jsx"] + }, + "text/less": { + compressible: true, + extensions: ["less"] + }, + "text/markdown": { + source: "iana", + compressible: true, + extensions: ["markdown", "md"] + }, + "text/mathml": { + source: "nginx", + extensions: ["mml"] + }, + "text/mdx": { + compressible: true, + extensions: ["mdx"] + }, + "text/mizar": { + source: "iana" + }, + "text/n3": { + source: "iana", + charset: "UTF-8", + compressible: true, + extensions: ["n3"] + }, + "text/parameters": { + source: "iana", + charset: "UTF-8" + }, + "text/parityfec": { + source: "iana" + }, + "text/plain": { + source: "iana", + compressible: true, + extensions: ["txt", "text", "conf", "def", "list", "log", "in", "ini"] + }, + "text/provenance-notation": { + source: "iana", + charset: "UTF-8" + }, + "text/prs.fallenstein.rst": { + source: "iana" + }, + "text/prs.lines.tag": { + source: "iana", + extensions: ["dsc"] + }, + "text/prs.prop.logic": { + source: "iana" + }, + "text/raptorfec": { + source: "iana" + }, + "text/red": { + source: "iana" + }, + "text/rfc822-headers": { + source: "iana" + }, + "text/richtext": { + source: "iana", + compressible: true, + extensions: ["rtx"] + }, + "text/rtf": { + source: "iana", + compressible: true, + extensions: ["rtf"] + }, + "text/rtp-enc-aescm128": { + source: "iana" + }, + "text/rtploopback": { + source: "iana" + }, + "text/rtx": { + source: "iana" + }, + "text/sgml": { + source: "iana", + extensions: ["sgml", "sgm"] + }, + "text/shaclc": { + source: "iana" + }, + "text/shex": { + source: "iana", + extensions: ["shex"] + }, + "text/slim": { + extensions: ["slim", "slm"] + }, + "text/spdx": { + source: "iana", + extensions: ["spdx"] + }, + "text/strings": { + source: "iana" + }, + "text/stylus": { + extensions: ["stylus", "styl"] + }, + "text/t140": { + source: "iana" + }, + "text/tab-separated-values": { + source: "iana", + compressible: true, + extensions: ["tsv"] + }, + "text/troff": { + source: "iana", + extensions: ["t", "tr", "roff", "man", "me", "ms"] + }, + "text/turtle": { + source: "iana", + charset: "UTF-8", + extensions: ["ttl"] + }, + "text/ulpfec": { + source: "iana" + }, + "text/uri-list": { + source: "iana", + compressible: true, + extensions: ["uri", "uris", "urls"] + }, + "text/vcard": { + source: "iana", + compressible: true, + extensions: ["vcard"] + }, + "text/vnd.a": { + source: "iana" + }, + "text/vnd.abc": { + source: "iana" + }, + "text/vnd.ascii-art": { + source: "iana" + }, + "text/vnd.curl": { + source: "iana", + extensions: ["curl"] + }, + "text/vnd.curl.dcurl": { + source: "apache", + extensions: ["dcurl"] + }, + "text/vnd.curl.mcurl": { + source: "apache", + extensions: ["mcurl"] + }, + "text/vnd.curl.scurl": { + source: "apache", + extensions: ["scurl"] + }, + "text/vnd.debian.copyright": { + source: "iana", + charset: "UTF-8" + }, + "text/vnd.dmclientscript": { + source: "iana" + }, + "text/vnd.dvb.subtitle": { + source: "iana", + extensions: ["sub"] + }, + "text/vnd.esmertec.theme-descriptor": { + source: "iana", + charset: "UTF-8" + }, + "text/vnd.familysearch.gedcom": { + source: "iana", + extensions: ["ged"] + }, + "text/vnd.ficlab.flt": { + source: "iana" + }, + "text/vnd.fly": { + source: "iana", + extensions: ["fly"] + }, + "text/vnd.fmi.flexstor": { + source: "iana", + extensions: ["flx"] + }, + "text/vnd.gml": { + source: "iana" + }, + "text/vnd.graphviz": { + source: "iana", + extensions: ["gv"] + }, + "text/vnd.hans": { + source: "iana" + }, + "text/vnd.hgl": { + source: "iana" + }, + "text/vnd.in3d.3dml": { + source: "iana", + extensions: ["3dml"] + }, + "text/vnd.in3d.spot": { + source: "iana", + extensions: ["spot"] + }, + "text/vnd.iptc.newsml": { + source: "iana" + }, + "text/vnd.iptc.nitf": { + source: "iana" + }, + "text/vnd.latex-z": { + source: "iana" + }, + "text/vnd.motorola.reflex": { + source: "iana" + }, + "text/vnd.ms-mediapackage": { + source: "iana" + }, + "text/vnd.net2phone.commcenter.command": { + source: "iana" + }, + "text/vnd.radisys.msml-basic-layout": { + source: "iana" + }, + "text/vnd.senx.warpscript": { + source: "iana" + }, + "text/vnd.si.uricatalogue": { + source: "iana" + }, + "text/vnd.sosi": { + source: "iana" + }, + "text/vnd.sun.j2me.app-descriptor": { + source: "iana", + charset: "UTF-8", + extensions: ["jad"] + }, + "text/vnd.trolltech.linguist": { + source: "iana", + charset: "UTF-8" + }, + "text/vnd.wap.si": { + source: "iana" + }, + "text/vnd.wap.sl": { + source: "iana" + }, + "text/vnd.wap.wml": { + source: "iana", + extensions: ["wml"] + }, + "text/vnd.wap.wmlscript": { + source: "iana", + extensions: ["wmls"] + }, + "text/vtt": { + source: "iana", + charset: "UTF-8", + compressible: true, + extensions: ["vtt"] + }, + "text/x-asm": { + source: "apache", + extensions: ["s", "asm"] + }, + "text/x-c": { + source: "apache", + extensions: ["c", "cc", "cxx", "cpp", "h", "hh", "dic"] + }, + "text/x-component": { + source: "nginx", + extensions: ["htc"] + }, + "text/x-fortran": { + source: "apache", + extensions: ["f", "for", "f77", "f90"] + }, + "text/x-gwt-rpc": { + compressible: true + }, + "text/x-handlebars-template": { + extensions: ["hbs"] + }, + "text/x-java-source": { + source: "apache", + extensions: ["java"] + }, + "text/x-jquery-tmpl": { + compressible: true + }, + "text/x-lua": { + extensions: ["lua"] + }, + "text/x-markdown": { + compressible: true, + extensions: ["mkd"] + }, + "text/x-nfo": { + source: "apache", + extensions: ["nfo"] + }, + "text/x-opml": { + source: "apache", + extensions: ["opml"] + }, + "text/x-org": { + compressible: true, + extensions: ["org"] + }, + "text/x-pascal": { + source: "apache", + extensions: ["p", "pas"] + }, + "text/x-processing": { + compressible: true, + extensions: ["pde"] + }, + "text/x-sass": { + extensions: ["sass"] + }, + "text/x-scss": { + extensions: ["scss"] + }, + "text/x-setext": { + source: "apache", + extensions: ["etx"] + }, + "text/x-sfv": { + source: "apache", + extensions: ["sfv"] + }, + "text/x-suse-ymp": { + compressible: true, + extensions: ["ymp"] + }, + "text/x-uuencode": { + source: "apache", + extensions: ["uu"] + }, + "text/x-vcalendar": { + source: "apache", + extensions: ["vcs"] + }, + "text/x-vcard": { + source: "apache", + extensions: ["vcf"] + }, + "text/xml": { + source: "iana", + compressible: true, + extensions: ["xml"] + }, + "text/xml-external-parsed-entity": { + source: "iana" + }, + "text/yaml": { + compressible: true, + extensions: ["yaml", "yml"] + }, + "video/1d-interleaved-parityfec": { + source: "iana" + }, + "video/3gpp": { + source: "iana", + extensions: ["3gp", "3gpp"] + }, + "video/3gpp-tt": { + source: "iana" + }, + "video/3gpp2": { + source: "iana", + extensions: ["3g2"] + }, + "video/av1": { + source: "iana" + }, + "video/bmpeg": { + source: "iana" + }, + "video/bt656": { + source: "iana" + }, + "video/celb": { + source: "iana" + }, + "video/dv": { + source: "iana" + }, + "video/encaprtp": { + source: "iana" + }, + "video/ffv1": { + source: "iana" + }, + "video/flexfec": { + source: "iana" + }, + "video/h261": { + source: "iana", + extensions: ["h261"] + }, + "video/h263": { + source: "iana", + extensions: ["h263"] + }, + "video/h263-1998": { + source: "iana" + }, + "video/h263-2000": { + source: "iana" + }, + "video/h264": { + source: "iana", + extensions: ["h264"] + }, + "video/h264-rcdo": { + source: "iana" + }, + "video/h264-svc": { + source: "iana" + }, + "video/h265": { + source: "iana" + }, + "video/iso.segment": { + source: "iana", + extensions: ["m4s"] + }, + "video/jpeg": { + source: "iana", + extensions: ["jpgv"] + }, + "video/jpeg2000": { + source: "iana" + }, + "video/jpm": { + source: "apache", + extensions: ["jpm", "jpgm"] + }, + "video/jxsv": { + source: "iana" + }, + "video/mj2": { + source: "iana", + extensions: ["mj2", "mjp2"] + }, + "video/mp1s": { + source: "iana" + }, + "video/mp2p": { + source: "iana" + }, + "video/mp2t": { + source: "iana", + extensions: ["ts"] + }, + "video/mp4": { + source: "iana", + compressible: false, + extensions: ["mp4", "mp4v", "mpg4"] + }, + "video/mp4v-es": { + source: "iana" + }, + "video/mpeg": { + source: "iana", + compressible: false, + extensions: ["mpeg", "mpg", "mpe", "m1v", "m2v"] + }, + "video/mpeg4-generic": { + source: "iana" + }, + "video/mpv": { + source: "iana" + }, + "video/nv": { + source: "iana" + }, + "video/ogg": { + source: "iana", + compressible: false, + extensions: ["ogv"] + }, + "video/parityfec": { + source: "iana" + }, + "video/pointer": { + source: "iana" + }, + "video/quicktime": { + source: "iana", + compressible: false, + extensions: ["qt", "mov"] + }, + "video/raptorfec": { + source: "iana" + }, + "video/raw": { + source: "iana" + }, + "video/rtp-enc-aescm128": { + source: "iana" + }, + "video/rtploopback": { + source: "iana" + }, + "video/rtx": { + source: "iana" + }, + "video/scip": { + source: "iana" + }, + "video/smpte291": { + source: "iana" + }, + "video/smpte292m": { + source: "iana" + }, + "video/ulpfec": { + source: "iana" + }, + "video/vc1": { + source: "iana" + }, + "video/vc2": { + source: "iana" + }, + "video/vnd.cctv": { + source: "iana" + }, + "video/vnd.dece.hd": { + source: "iana", + extensions: ["uvh", "uvvh"] + }, + "video/vnd.dece.mobile": { + source: "iana", + extensions: ["uvm", "uvvm"] + }, + "video/vnd.dece.mp4": { + source: "iana" + }, + "video/vnd.dece.pd": { + source: "iana", + extensions: ["uvp", "uvvp"] + }, + "video/vnd.dece.sd": { + source: "iana", + extensions: ["uvs", "uvvs"] + }, + "video/vnd.dece.video": { + source: "iana", + extensions: ["uvv", "uvvv"] + }, + "video/vnd.directv.mpeg": { + source: "iana" + }, + "video/vnd.directv.mpeg-tts": { + source: "iana" + }, + "video/vnd.dlna.mpeg-tts": { + source: "iana" + }, + "video/vnd.dvb.file": { + source: "iana", + extensions: ["dvb"] + }, + "video/vnd.fvt": { + source: "iana", + extensions: ["fvt"] + }, + "video/vnd.hns.video": { + source: "iana" + }, + "video/vnd.iptvforum.1dparityfec-1010": { + source: "iana" + }, + "video/vnd.iptvforum.1dparityfec-2005": { + source: "iana" + }, + "video/vnd.iptvforum.2dparityfec-1010": { + source: "iana" + }, + "video/vnd.iptvforum.2dparityfec-2005": { + source: "iana" + }, + "video/vnd.iptvforum.ttsavc": { + source: "iana" + }, + "video/vnd.iptvforum.ttsmpeg2": { + source: "iana" + }, + "video/vnd.motorola.video": { + source: "iana" + }, + "video/vnd.motorola.videop": { + source: "iana" + }, + "video/vnd.mpegurl": { + source: "iana", + extensions: ["mxu", "m4u"] + }, + "video/vnd.ms-playready.media.pyv": { + source: "iana", + extensions: ["pyv"] + }, + "video/vnd.nokia.interleaved-multimedia": { + source: "iana" + }, + "video/vnd.nokia.mp4vr": { + source: "iana" + }, + "video/vnd.nokia.videovoip": { + source: "iana" + }, + "video/vnd.objectvideo": { + source: "iana" + }, + "video/vnd.radgamettools.bink": { + source: "iana" + }, + "video/vnd.radgamettools.smacker": { + source: "iana" + }, + "video/vnd.sealed.mpeg1": { + source: "iana" + }, + "video/vnd.sealed.mpeg4": { + source: "iana" + }, + "video/vnd.sealed.swf": { + source: "iana" + }, + "video/vnd.sealedmedia.softseal.mov": { + source: "iana" + }, + "video/vnd.uvvu.mp4": { + source: "iana", + extensions: ["uvu", "uvvu"] + }, + "video/vnd.vivo": { + source: "iana", + extensions: ["viv"] + }, + "video/vnd.youtube.yt": { + source: "iana" + }, + "video/vp8": { + source: "iana" + }, + "video/vp9": { + source: "iana" + }, + "video/webm": { + source: "apache", + compressible: false, + extensions: ["webm"] + }, + "video/x-f4v": { + source: "apache", + extensions: ["f4v"] + }, + "video/x-fli": { + source: "apache", + extensions: ["fli"] + }, + "video/x-flv": { + source: "apache", + compressible: false, + extensions: ["flv"] + }, + "video/x-m4v": { + source: "apache", + extensions: ["m4v"] + }, + "video/x-matroska": { + source: "apache", + compressible: false, + extensions: ["mkv", "mk3d", "mks"] + }, + "video/x-mng": { + source: "apache", + extensions: ["mng"] + }, + "video/x-ms-asf": { + source: "apache", + extensions: ["asf", "asx"] + }, + "video/x-ms-vob": { + source: "apache", + extensions: ["vob"] + }, + "video/x-ms-wm": { + source: "apache", + extensions: ["wm"] + }, + "video/x-ms-wmv": { + source: "apache", + compressible: false, + extensions: ["wmv"] + }, + "video/x-ms-wmx": { + source: "apache", + extensions: ["wmx"] + }, + "video/x-ms-wvx": { + source: "apache", + extensions: ["wvx"] + }, + "video/x-msvideo": { + source: "apache", + extensions: ["avi"] + }, + "video/x-sgi-movie": { + source: "apache", + extensions: ["movie"] + }, + "video/x-smv": { + source: "apache", + extensions: ["smv"] + }, + "x-conference/x-cooltalk": { + source: "apache", + extensions: ["ice"] + }, + "x-shader/x-fragment": { + compressible: true + }, + "x-shader/x-vertex": { + compressible: true + } + }; + } +}); + +// node_modules/.pnpm/mime-db@1.52.0/node_modules/mime-db/index.js +var require_mime_db2 = __commonJS({ + "node_modules/.pnpm/mime-db@1.52.0/node_modules/mime-db/index.js"(exports, module) { + module.exports = require_db2(); + } +}); + +// node_modules/.pnpm/mime-types@2.1.35/node_modules/mime-types/index.js +var require_mime_types2 = __commonJS({ + "node_modules/.pnpm/mime-types@2.1.35/node_modules/mime-types/index.js"(exports) { + "use strict"; + var db = require_mime_db2(); + var extname2 = __require("path").extname; + var EXTRACT_TYPE_REGEXP = /^\s*([^;\s]*)(?:;|\s|$)/; + var TEXT_TYPE_REGEXP = /^text\//i; + exports.charset = charset; + exports.charsets = { lookup: charset }; + exports.contentType = contentType; + exports.extension = extension2; + exports.extensions = /* @__PURE__ */ Object.create(null); + exports.lookup = lookup; + exports.types = /* @__PURE__ */ Object.create(null); + populateMaps(exports.extensions, exports.types); + function charset(type) { + if (!type || typeof type !== "string") { + return false; + } + var match = EXTRACT_TYPE_REGEXP.exec(type); + var mime = match && db[match[1].toLowerCase()]; + if (mime && mime.charset) { + return mime.charset; + } + if (match && TEXT_TYPE_REGEXP.test(match[1])) { + return "UTF-8"; + } + return false; + } + function contentType(str) { + if (!str || typeof str !== "string") { + return false; + } + var mime = str.indexOf("/") === -1 ? exports.lookup(str) : str; + if (!mime) { + return false; + } + if (mime.indexOf("charset") === -1) { + var charset2 = exports.charset(mime); + if (charset2) mime += "; charset=" + charset2.toLowerCase(); + } + return mime; + } + function extension2(type) { + if (!type || typeof type !== "string") { + return false; + } + var match = EXTRACT_TYPE_REGEXP.exec(type); + var exts = match && exports.extensions[match[1].toLowerCase()]; + if (!exts || !exts.length) { + return false; + } + return exts[0]; + } + function lookup(path53) { + if (!path53 || typeof path53 !== "string") { + return false; + } + var extension3 = extname2("x." + path53).toLowerCase().substr(1); + if (!extension3) { + return false; + } + return exports.types[extension3] || false; + } + function populateMaps(extensions, types2) { + var preference = ["nginx", "apache", void 0, "iana"]; + Object.keys(db).forEach(function forEachMimeType(type) { + var mime = db[type]; + var exts = mime.extensions; + if (!exts || !exts.length) { + return; + } + extensions[type] = exts; + for (var i5 = 0; i5 < exts.length; i5++) { + var extension3 = exts[i5]; + if (types2[extension3]) { + var from = preference.indexOf(db[types2[extension3]].source); + var to = preference.indexOf(mime.source); + if (types2[extension3] !== "application/octet-stream" && (from > to || from === to && types2[extension3].substr(0, 12) === "application/")) { + continue; + } + } + types2[extension3] = type; + } + }); + } + } +}); + +// node_modules/.pnpm/type-is@1.6.18/node_modules/type-is/index.js +var require_type_is2 = __commonJS({ + "node_modules/.pnpm/type-is@1.6.18/node_modules/type-is/index.js"(exports, module) { + "use strict"; + var typer = require_media_typer2(); + var mime = require_mime_types2(); + module.exports = typeofrequest; + module.exports.is = typeis; + module.exports.hasBody = hasbody; + module.exports.normalize = normalize2; + module.exports.match = mimeMatch; + function typeis(value, types_) { + var i5; + var types2 = types_; + var val = tryNormalizeType(value); + if (!val) { + return false; + } + if (types2 && !Array.isArray(types2)) { + types2 = new Array(arguments.length - 1); + for (i5 = 0; i5 < types2.length; i5++) { + types2[i5] = arguments[i5 + 1]; + } + } + if (!types2 || !types2.length) { + return val; + } + var type; + for (i5 = 0; i5 < types2.length; i5++) { + if (mimeMatch(normalize2(type = types2[i5]), val)) { + return type[0] === "+" || type.indexOf("*") !== -1 ? val : type; + } + } + return false; + } + function hasbody(req) { + return req.headers["transfer-encoding"] !== void 0 || !isNaN(req.headers["content-length"]); + } + function typeofrequest(req, types_) { + var types2 = types_; + if (!hasbody(req)) { + return null; + } + if (arguments.length > 2) { + types2 = new Array(arguments.length - 1); + for (var i5 = 0; i5 < types2.length; i5++) { + types2[i5] = arguments[i5 + 1]; + } + } + var value = req.headers["content-type"]; + return typeis(value, types2); + } + function normalize2(type) { + if (typeof type !== "string") { + return false; + } + switch (type) { + case "urlencoded": + return "application/x-www-form-urlencoded"; + case "multipart": + return "multipart/*"; + } + if (type[0] === "+") { + return "*/*" + type; + } + return type.indexOf("/") === -1 ? mime.lookup(type) : type; + } + function mimeMatch(expected, actual) { + if (expected === false) { + return false; + } + var actualParts = actual.split("/"); + var expectedParts = expected.split("/"); + if (actualParts.length !== 2 || expectedParts.length !== 2) { + return false; + } + if (expectedParts[0] !== "*" && expectedParts[0] !== actualParts[0]) { + return false; + } + if (expectedParts[1].substr(0, 2) === "*+") { + return expectedParts[1].length <= actualParts[1].length + 1 && expectedParts[1].substr(1) === actualParts[1].substr(1 - expectedParts[1].length); + } + if (expectedParts[1] !== "*" && expectedParts[1] !== actualParts[1]) { + return false; + } + return true; + } + function normalizeType(value) { + var type = typer.parse(value); + type.parameters = void 0; + return typer.format(type); + } + function tryNormalizeType(value) { + if (!value) { + return null; + } + try { + return normalizeType(value); + } catch (err) { + return null; + } + } + } +}); + +// node_modules/.pnpm/busboy@1.6.0/node_modules/busboy/lib/utils.js +var require_utils4 = __commonJS({ + "node_modules/.pnpm/busboy@1.6.0/node_modules/busboy/lib/utils.js"(exports, module) { + "use strict"; + function parseContentType(str) { + if (str.length === 0) + return; + const params = /* @__PURE__ */ Object.create(null); + let i5 = 0; + for (; i5 < str.length; ++i5) { + const code = str.charCodeAt(i5); + if (TOKEN[code] !== 1) { + if (code !== 47 || i5 === 0) + return; + break; + } + } + if (i5 === str.length) + return; + const type = str.slice(0, i5).toLowerCase(); + const subtypeStart = ++i5; + for (; i5 < str.length; ++i5) { + const code = str.charCodeAt(i5); + if (TOKEN[code] !== 1) { + if (i5 === subtypeStart) + return; + if (parseContentTypeParams(str, i5, params) === void 0) + return; + break; + } + } + if (i5 === subtypeStart) + return; + const subtype = str.slice(subtypeStart, i5).toLowerCase(); + return { type, subtype, params }; + } + function parseContentTypeParams(str, i5, params) { + while (i5 < str.length) { + for (; i5 < str.length; ++i5) { + const code = str.charCodeAt(i5); + if (code !== 32 && code !== 9) + break; + } + if (i5 === str.length) + break; + if (str.charCodeAt(i5++) !== 59) + return; + for (; i5 < str.length; ++i5) { + const code = str.charCodeAt(i5); + if (code !== 32 && code !== 9) + break; + } + if (i5 === str.length) + return; + let name; + const nameStart = i5; + for (; i5 < str.length; ++i5) { + const code = str.charCodeAt(i5); + if (TOKEN[code] !== 1) { + if (code !== 61) + return; + break; + } + } + if (i5 === str.length) + return; + name = str.slice(nameStart, i5); + ++i5; + if (i5 === str.length) + return; + let value = ""; + let valueStart; + if (str.charCodeAt(i5) === 34) { + valueStart = ++i5; + let escaping = false; + for (; i5 < str.length; ++i5) { + const code = str.charCodeAt(i5); + if (code === 92) { + if (escaping) { + valueStart = i5; + escaping = false; + } else { + value += str.slice(valueStart, i5); + escaping = true; + } + continue; + } + if (code === 34) { + if (escaping) { + valueStart = i5; + escaping = false; + continue; + } + value += str.slice(valueStart, i5); + break; + } + if (escaping) { + valueStart = i5 - 1; + escaping = false; + } + if (QDTEXT[code] !== 1) + return; + } + if (i5 === str.length) + return; + ++i5; + } else { + valueStart = i5; + for (; i5 < str.length; ++i5) { + const code = str.charCodeAt(i5); + if (TOKEN[code] !== 1) { + if (i5 === valueStart) + return; + break; + } + } + value = str.slice(valueStart, i5); + } + name = name.toLowerCase(); + if (params[name] === void 0) + params[name] = value; + } + return params; + } + function parseDisposition(str, defDecoder) { + if (str.length === 0) + return; + const params = /* @__PURE__ */ Object.create(null); + let i5 = 0; + for (; i5 < str.length; ++i5) { + const code = str.charCodeAt(i5); + if (TOKEN[code] !== 1) { + if (parseDispositionParams(str, i5, params, defDecoder) === void 0) + return; + break; + } + } + const type = str.slice(0, i5).toLowerCase(); + return { type, params }; + } + function parseDispositionParams(str, i5, params, defDecoder) { + while (i5 < str.length) { + for (; i5 < str.length; ++i5) { + const code = str.charCodeAt(i5); + if (code !== 32 && code !== 9) + break; + } + if (i5 === str.length) + break; + if (str.charCodeAt(i5++) !== 59) + return; + for (; i5 < str.length; ++i5) { + const code = str.charCodeAt(i5); + if (code !== 32 && code !== 9) + break; + } + if (i5 === str.length) + return; + let name; + const nameStart = i5; + for (; i5 < str.length; ++i5) { + const code = str.charCodeAt(i5); + if (TOKEN[code] !== 1) { + if (code === 61) + break; + return; + } + } + if (i5 === str.length) + return; + let value = ""; + let valueStart; + let charset; + name = str.slice(nameStart, i5); + if (name.charCodeAt(name.length - 1) === 42) { + const charsetStart = ++i5; + for (; i5 < str.length; ++i5) { + const code = str.charCodeAt(i5); + if (CHARSET[code] !== 1) { + if (code !== 39) + return; + break; + } + } + if (i5 === str.length) + return; + charset = str.slice(charsetStart, i5); + ++i5; + for (; i5 < str.length; ++i5) { + const code = str.charCodeAt(i5); + if (code === 39) + break; + } + if (i5 === str.length) + return; + ++i5; + if (i5 === str.length) + return; + valueStart = i5; + let encode6 = 0; + for (; i5 < str.length; ++i5) { + const code = str.charCodeAt(i5); + if (EXTENDED_VALUE[code] !== 1) { + if (code === 37) { + let hexUpper; + let hexLower; + if (i5 + 2 < str.length && (hexUpper = HEX_VALUES[str.charCodeAt(i5 + 1)]) !== -1 && (hexLower = HEX_VALUES[str.charCodeAt(i5 + 2)]) !== -1) { + const byteVal = (hexUpper << 4) + hexLower; + value += str.slice(valueStart, i5); + value += String.fromCharCode(byteVal); + i5 += 2; + valueStart = i5 + 1; + if (byteVal >= 128) + encode6 = 2; + else if (encode6 === 0) + encode6 = 1; + continue; + } + return; + } + break; + } + } + value += str.slice(valueStart, i5); + value = convertToUTF8(value, charset, encode6); + if (value === void 0) + return; + } else { + ++i5; + if (i5 === str.length) + return; + if (str.charCodeAt(i5) === 34) { + valueStart = ++i5; + let escaping = false; + for (; i5 < str.length; ++i5) { + const code = str.charCodeAt(i5); + if (code === 92) { + if (escaping) { + valueStart = i5; + escaping = false; + } else { + value += str.slice(valueStart, i5); + escaping = true; + } + continue; + } + if (code === 34) { + if (escaping) { + valueStart = i5; + escaping = false; + continue; + } + value += str.slice(valueStart, i5); + break; + } + if (escaping) { + valueStart = i5 - 1; + escaping = false; + } + if (QDTEXT[code] !== 1) + return; + } + if (i5 === str.length) + return; + ++i5; + } else { + valueStart = i5; + for (; i5 < str.length; ++i5) { + const code = str.charCodeAt(i5); + if (TOKEN[code] !== 1) { + if (i5 === valueStart) + return; + break; + } + } + value = str.slice(valueStart, i5); + } + value = defDecoder(value, 2); + if (value === void 0) + return; + } + name = name.toLowerCase(); + if (params[name] === void 0) + params[name] = value; + } + return params; + } + function getDecoder(charset) { + let lc; + while (true) { + switch (charset) { + case "utf-8": + case "utf8": + return decoders2.utf8; + case "latin1": + case "ascii": + // TODO: Make these a separate, strict decoder? + case "us-ascii": + case "iso-8859-1": + case "iso8859-1": + case "iso88591": + case "iso_8859-1": + case "windows-1252": + case "iso_8859-1:1987": + case "cp1252": + case "x-cp1252": + return decoders2.latin1; + case "utf16le": + case "utf-16le": + case "ucs2": + case "ucs-2": + return decoders2.utf16le; + case "base64": + return decoders2.base64; + default: + if (lc === void 0) { + lc = true; + charset = charset.toLowerCase(); + continue; + } + return decoders2.other.bind(charset); + } + } + } + var decoders2 = { + utf8: (data2, hint) => { + if (data2.length === 0) + return ""; + if (typeof data2 === "string") { + if (hint < 2) + return data2; + data2 = Buffer.from(data2, "latin1"); + } + return data2.utf8Slice(0, data2.length); + }, + latin1: (data2, hint) => { + if (data2.length === 0) + return ""; + if (typeof data2 === "string") + return data2; + return data2.latin1Slice(0, data2.length); + }, + utf16le: (data2, hint) => { + if (data2.length === 0) + return ""; + if (typeof data2 === "string") + data2 = Buffer.from(data2, "latin1"); + return data2.ucs2Slice(0, data2.length); + }, + base64: (data2, hint) => { + if (data2.length === 0) + return ""; + if (typeof data2 === "string") + data2 = Buffer.from(data2, "latin1"); + return data2.base64Slice(0, data2.length); + }, + other: (data2, hint) => { + if (data2.length === 0) + return ""; + if (typeof data2 === "string") + data2 = Buffer.from(data2, "latin1"); + try { + const decoder2 = new TextDecoder(exports); + return decoder2.decode(data2); + } catch { + } + } + }; + function convertToUTF8(data2, charset, hint) { + const decode5 = getDecoder(charset); + if (decode5) + return decode5(data2, hint); + } + function basename3(path53) { + if (typeof path53 !== "string") + return ""; + for (let i5 = path53.length - 1; i5 >= 0; --i5) { + switch (path53.charCodeAt(i5)) { + case 47: + // '/' + case 92: + path53 = path53.slice(i5 + 1); + return path53 === ".." || path53 === "." ? "" : path53; + } + } + return path53 === ".." || path53 === "." ? "" : path53; + } + var TOKEN = [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 0, + 1, + 1, + 1, + 1, + 1, + 0, + 0, + 1, + 1, + 0, + 1, + 1, + 0, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 0, + 0, + 0, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 0, + 1, + 0, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ]; + var QDTEXT = [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 1, + 0, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 0, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 0, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1 + ]; + var CHARSET = [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 0, + 1, + 1, + 1, + 1, + 0, + 0, + 0, + 0, + 1, + 0, + 1, + 0, + 0, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 0, + 0, + 0, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 0, + 1, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ]; + var EXTENDED_VALUE = [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 0, + 1, + 1, + 0, + 1, + 0, + 0, + 0, + 0, + 1, + 0, + 1, + 1, + 0, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 0, + 0, + 0, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 0, + 1, + 0, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ]; + var HEX_VALUES = [ + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 10, + 11, + 12, + 13, + 14, + 15, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 10, + 11, + 12, + 13, + 14, + 15, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1 + ]; + module.exports = { + basename: basename3, + convertToUTF8, + getDecoder, + parseContentType, + parseDisposition + }; + } +}); + +// node_modules/.pnpm/streamsearch@1.1.0/node_modules/streamsearch/lib/sbmh.js +var require_sbmh = __commonJS({ + "node_modules/.pnpm/streamsearch@1.1.0/node_modules/streamsearch/lib/sbmh.js"(exports, module) { + "use strict"; + function memcmp(buf1, pos1, buf2, pos2, num) { + for (let i5 = 0; i5 < num; ++i5) { + if (buf1[pos1 + i5] !== buf2[pos2 + i5]) + return false; + } + return true; + } + var SBMH = class { + constructor(needle, cb) { + if (typeof cb !== "function") + throw new Error("Missing match callback"); + if (typeof needle === "string") + needle = Buffer.from(needle); + else if (!Buffer.isBuffer(needle)) + throw new Error(`Expected Buffer for needle, got ${typeof needle}`); + const needleLen = needle.length; + this.maxMatches = Infinity; + this.matches = 0; + this._cb = cb; + this._lookbehindSize = 0; + this._needle = needle; + this._bufPos = 0; + this._lookbehind = Buffer.allocUnsafe(needleLen); + this._occ = [ + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen, + needleLen + ]; + if (needleLen > 1) { + for (let i5 = 0; i5 < needleLen - 1; ++i5) + this._occ[needle[i5]] = needleLen - 1 - i5; + } + } + reset() { + this.matches = 0; + this._lookbehindSize = 0; + this._bufPos = 0; + } + push(chunk, pos) { + let result; + if (!Buffer.isBuffer(chunk)) + chunk = Buffer.from(chunk, "latin1"); + const chunkLen = chunk.length; + this._bufPos = pos || 0; + while (result !== chunkLen && this.matches < this.maxMatches) + result = feed(this, chunk); + return result; + } + destroy() { + const lbSize = this._lookbehindSize; + if (lbSize) + this._cb(false, this._lookbehind, 0, lbSize, false); + this.reset(); + } + }; + function feed(self2, data2) { + const len = data2.length; + const needle = self2._needle; + const needleLen = needle.length; + let pos = -self2._lookbehindSize; + const lastNeedleCharPos = needleLen - 1; + const lastNeedleChar = needle[lastNeedleCharPos]; + const end = len - needleLen; + const occ = self2._occ; + const lookbehind = self2._lookbehind; + if (pos < 0) { + while (pos < 0 && pos <= end) { + const nextPos = pos + lastNeedleCharPos; + const ch = nextPos < 0 ? lookbehind[self2._lookbehindSize + nextPos] : data2[nextPos]; + if (ch === lastNeedleChar && matchNeedle(self2, data2, pos, lastNeedleCharPos)) { + self2._lookbehindSize = 0; + ++self2.matches; + if (pos > -self2._lookbehindSize) + self2._cb(true, lookbehind, 0, self2._lookbehindSize + pos, false); + else + self2._cb(true, void 0, 0, 0, true); + return self2._bufPos = pos + needleLen; + } + pos += occ[ch]; + } + while (pos < 0 && !matchNeedle(self2, data2, pos, len - pos)) + ++pos; + if (pos < 0) { + const bytesToCutOff = self2._lookbehindSize + pos; + if (bytesToCutOff > 0) { + self2._cb(false, lookbehind, 0, bytesToCutOff, false); + } + self2._lookbehindSize -= bytesToCutOff; + lookbehind.copy(lookbehind, 0, bytesToCutOff, self2._lookbehindSize); + lookbehind.set(data2, self2._lookbehindSize); + self2._lookbehindSize += len; + self2._bufPos = len; + return len; + } + self2._cb(false, lookbehind, 0, self2._lookbehindSize, false); + self2._lookbehindSize = 0; + } + pos += self2._bufPos; + const firstNeedleChar = needle[0]; + while (pos <= end) { + const ch = data2[pos + lastNeedleCharPos]; + if (ch === lastNeedleChar && data2[pos] === firstNeedleChar && memcmp(needle, 0, data2, pos, lastNeedleCharPos)) { + ++self2.matches; + if (pos > 0) + self2._cb(true, data2, self2._bufPos, pos, true); + else + self2._cb(true, void 0, 0, 0, true); + return self2._bufPos = pos + needleLen; + } + pos += occ[ch]; + } + while (pos < len) { + if (data2[pos] !== firstNeedleChar || !memcmp(data2, pos, needle, 0, len - pos)) { + ++pos; + continue; + } + data2.copy(lookbehind, 0, pos, len); + self2._lookbehindSize = len - pos; + break; + } + if (pos > 0) + self2._cb(false, data2, self2._bufPos, pos < len ? pos : len, true); + self2._bufPos = len; + return len; + } + function matchNeedle(self2, data2, pos, len) { + const lb = self2._lookbehind; + const lbSize = self2._lookbehindSize; + const needle = self2._needle; + for (let i5 = 0; i5 < len; ++i5, ++pos) { + const ch = pos < 0 ? lb[lbSize + pos] : data2[pos]; + if (ch !== needle[i5]) + return false; + } + return true; + } + module.exports = SBMH; + } +}); + +// node_modules/.pnpm/busboy@1.6.0/node_modules/busboy/lib/types/multipart.js +var require_multipart = __commonJS({ + "node_modules/.pnpm/busboy@1.6.0/node_modules/busboy/lib/types/multipart.js"(exports, module) { + "use strict"; + var { Readable: Readable3, Writable } = __require("stream"); + var StreamSearch = require_sbmh(); + var { + basename: basename3, + convertToUTF8, + getDecoder, + parseContentType, + parseDisposition + } = require_utils4(); + var BUF_CRLF = Buffer.from("\r\n"); + var BUF_CR = Buffer.from("\r"); + var BUF_DASH = Buffer.from("-"); + function noop5() { + } + var MAX_HEADER_PAIRS = 2e3; + var MAX_HEADER_SIZE = 16 * 1024; + var HPARSER_NAME = 0; + var HPARSER_PRE_OWS = 1; + var HPARSER_VALUE = 2; + var HeaderParser = class { + constructor(cb) { + this.header = /* @__PURE__ */ Object.create(null); + this.pairCount = 0; + this.byteCount = 0; + this.state = HPARSER_NAME; + this.name = ""; + this.value = ""; + this.crlf = 0; + this.cb = cb; + } + reset() { + this.header = /* @__PURE__ */ Object.create(null); + this.pairCount = 0; + this.byteCount = 0; + this.state = HPARSER_NAME; + this.name = ""; + this.value = ""; + this.crlf = 0; + } + push(chunk, pos, end) { + let start = pos; + while (pos < end) { + switch (this.state) { + case HPARSER_NAME: { + let done = false; + for (; pos < end; ++pos) { + if (this.byteCount === MAX_HEADER_SIZE) + return -1; + ++this.byteCount; + const code = chunk[pos]; + if (TOKEN[code] !== 1) { + if (code !== 58) + return -1; + this.name += chunk.latin1Slice(start, pos); + if (this.name.length === 0) + return -1; + ++pos; + done = true; + this.state = HPARSER_PRE_OWS; + break; + } + } + if (!done) { + this.name += chunk.latin1Slice(start, pos); + break; + } + } + case HPARSER_PRE_OWS: { + let done = false; + for (; pos < end; ++pos) { + if (this.byteCount === MAX_HEADER_SIZE) + return -1; + ++this.byteCount; + const code = chunk[pos]; + if (code !== 32 && code !== 9) { + start = pos; + done = true; + this.state = HPARSER_VALUE; + break; + } + } + if (!done) + break; + } + case HPARSER_VALUE: + switch (this.crlf) { + case 0: + for (; pos < end; ++pos) { + if (this.byteCount === MAX_HEADER_SIZE) + return -1; + ++this.byteCount; + const code = chunk[pos]; + if (FIELD_VCHAR[code] !== 1) { + if (code !== 13) + return -1; + ++this.crlf; + break; + } + } + this.value += chunk.latin1Slice(start, pos++); + break; + case 1: + if (this.byteCount === MAX_HEADER_SIZE) + return -1; + ++this.byteCount; + if (chunk[pos++] !== 10) + return -1; + ++this.crlf; + break; + case 2: { + if (this.byteCount === MAX_HEADER_SIZE) + return -1; + ++this.byteCount; + const code = chunk[pos]; + if (code === 32 || code === 9) { + start = pos; + this.crlf = 0; + } else { + if (++this.pairCount < MAX_HEADER_PAIRS) { + this.name = this.name.toLowerCase(); + if (this.header[this.name] === void 0) + this.header[this.name] = [this.value]; + else + this.header[this.name].push(this.value); + } + if (code === 13) { + ++this.crlf; + ++pos; + } else { + start = pos; + this.crlf = 0; + this.state = HPARSER_NAME; + this.name = ""; + this.value = ""; + } + } + break; + } + case 3: { + if (this.byteCount === MAX_HEADER_SIZE) + return -1; + ++this.byteCount; + if (chunk[pos++] !== 10) + return -1; + const header = this.header; + this.reset(); + this.cb(header); + return pos; + } + } + break; + } + } + return pos; + } + }; + var FileStream = class extends Readable3 { + constructor(opts, owner) { + super(opts); + this.truncated = false; + this._readcb = null; + this.once("end", () => { + this._read(); + if (--owner._fileEndsLeft === 0 && owner._finalcb) { + const cb = owner._finalcb; + owner._finalcb = null; + process.nextTick(cb); + } + }); + } + _read(n5) { + const cb = this._readcb; + if (cb) { + this._readcb = null; + cb(); + } + } + }; + var ignoreData = { + push: (chunk, pos) => { + }, + destroy: () => { + } + }; + function callAndUnsetCb(self2, err) { + const cb = self2._writecb; + self2._writecb = null; + if (err) + self2.destroy(err); + else if (cb) + cb(); + } + function nullDecoder(val, hint) { + return val; + } + var Multipart = class extends Writable { + constructor(cfg) { + const streamOpts = { + autoDestroy: true, + emitClose: true, + highWaterMark: typeof cfg.highWaterMark === "number" ? cfg.highWaterMark : void 0 + }; + super(streamOpts); + if (!cfg.conType.params || typeof cfg.conType.params.boundary !== "string") + throw new Error("Multipart: Boundary not found"); + const boundary = cfg.conType.params.boundary; + const paramDecoder = typeof cfg.defParamCharset === "string" && cfg.defParamCharset ? getDecoder(cfg.defParamCharset) : nullDecoder; + const defCharset = cfg.defCharset || "utf8"; + const preservePath = cfg.preservePath; + const fileOpts = { + autoDestroy: true, + emitClose: true, + highWaterMark: typeof cfg.fileHwm === "number" ? cfg.fileHwm : void 0 + }; + const limits = cfg.limits; + const fieldSizeLimit = limits && typeof limits.fieldSize === "number" ? limits.fieldSize : 1 * 1024 * 1024; + const fileSizeLimit = limits && typeof limits.fileSize === "number" ? limits.fileSize : Infinity; + const filesLimit = limits && typeof limits.files === "number" ? limits.files : Infinity; + const fieldsLimit = limits && typeof limits.fields === "number" ? limits.fields : Infinity; + const partsLimit = limits && typeof limits.parts === "number" ? limits.parts : Infinity; + let parts = -1; + let fields = 0; + let files = 0; + let skipPart = false; + this._fileEndsLeft = 0; + this._fileStream = void 0; + this._complete = false; + let fileSize = 0; + let field; + let fieldSize = 0; + let partCharset; + let partEncoding; + let partType; + let partName; + let partTruncated = false; + let hitFilesLimit = false; + let hitFieldsLimit = false; + this._hparser = null; + const hparser = new HeaderParser((header) => { + this._hparser = null; + skipPart = false; + partType = "text/plain"; + partCharset = defCharset; + partEncoding = "7bit"; + partName = void 0; + partTruncated = false; + let filename; + if (!header["content-disposition"]) { + skipPart = true; + return; + } + const disp = parseDisposition( + header["content-disposition"][0], + paramDecoder + ); + if (!disp || disp.type !== "form-data") { + skipPart = true; + return; + } + if (disp.params) { + if (disp.params.name) + partName = disp.params.name; + if (disp.params["filename*"]) + filename = disp.params["filename*"]; + else if (disp.params.filename) + filename = disp.params.filename; + if (filename !== void 0 && !preservePath) + filename = basename3(filename); + } + if (header["content-type"]) { + const conType = parseContentType(header["content-type"][0]); + if (conType) { + partType = `${conType.type}/${conType.subtype}`; + if (conType.params && typeof conType.params.charset === "string") + partCharset = conType.params.charset.toLowerCase(); + } + } + if (header["content-transfer-encoding"]) + partEncoding = header["content-transfer-encoding"][0].toLowerCase(); + if (partType === "application/octet-stream" || filename !== void 0) { + if (files === filesLimit) { + if (!hitFilesLimit) { + hitFilesLimit = true; + this.emit("filesLimit"); + } + skipPart = true; + return; + } + ++files; + if (this.listenerCount("file") === 0) { + skipPart = true; + return; + } + fileSize = 0; + this._fileStream = new FileStream(fileOpts, this); + ++this._fileEndsLeft; + this.emit( + "file", + partName, + this._fileStream, + { + filename, + encoding: partEncoding, + mimeType: partType + } + ); + } else { + if (fields === fieldsLimit) { + if (!hitFieldsLimit) { + hitFieldsLimit = true; + this.emit("fieldsLimit"); + } + skipPart = true; + return; + } + ++fields; + if (this.listenerCount("field") === 0) { + skipPart = true; + return; + } + field = []; + fieldSize = 0; + } + }); + let matchPostBoundary = 0; + const ssCb = (isMatch2, data2, start, end, isDataSafe) => { + retrydata: + while (data2) { + if (this._hparser !== null) { + const ret = this._hparser.push(data2, start, end); + if (ret === -1) { + this._hparser = null; + hparser.reset(); + this.emit("error", new Error("Malformed part header")); + break; + } + start = ret; + } + if (start === end) + break; + if (matchPostBoundary !== 0) { + if (matchPostBoundary === 1) { + switch (data2[start]) { + case 45: + matchPostBoundary = 2; + ++start; + break; + case 13: + matchPostBoundary = 3; + ++start; + break; + default: + matchPostBoundary = 0; + } + if (start === end) + return; + } + if (matchPostBoundary === 2) { + matchPostBoundary = 0; + if (data2[start] === 45) { + this._complete = true; + this._bparser = ignoreData; + return; + } + const writecb = this._writecb; + this._writecb = noop5; + ssCb(false, BUF_DASH, 0, 1, false); + this._writecb = writecb; + } else if (matchPostBoundary === 3) { + matchPostBoundary = 0; + if (data2[start] === 10) { + ++start; + if (parts >= partsLimit) + break; + this._hparser = hparser; + if (start === end) + break; + continue retrydata; + } else { + const writecb = this._writecb; + this._writecb = noop5; + ssCb(false, BUF_CR, 0, 1, false); + this._writecb = writecb; + } + } + } + if (!skipPart) { + if (this._fileStream) { + let chunk; + const actualLen = Math.min(end - start, fileSizeLimit - fileSize); + if (!isDataSafe) { + chunk = Buffer.allocUnsafe(actualLen); + data2.copy(chunk, 0, start, start + actualLen); + } else { + chunk = data2.slice(start, start + actualLen); + } + fileSize += chunk.length; + if (fileSize === fileSizeLimit) { + if (chunk.length > 0) + this._fileStream.push(chunk); + this._fileStream.emit("limit"); + this._fileStream.truncated = true; + skipPart = true; + } else if (!this._fileStream.push(chunk)) { + if (this._writecb) + this._fileStream._readcb = this._writecb; + this._writecb = null; + } + } else if (field !== void 0) { + let chunk; + const actualLen = Math.min( + end - start, + fieldSizeLimit - fieldSize + ); + if (!isDataSafe) { + chunk = Buffer.allocUnsafe(actualLen); + data2.copy(chunk, 0, start, start + actualLen); + } else { + chunk = data2.slice(start, start + actualLen); + } + fieldSize += actualLen; + field.push(chunk); + if (fieldSize === fieldSizeLimit) { + skipPart = true; + partTruncated = true; + } + } + } + break; + } + if (isMatch2) { + matchPostBoundary = 1; + if (this._fileStream) { + this._fileStream.push(null); + this._fileStream = null; + } else if (field !== void 0) { + let data3; + switch (field.length) { + case 0: + data3 = ""; + break; + case 1: + data3 = convertToUTF8(field[0], partCharset, 0); + break; + default: + data3 = convertToUTF8( + Buffer.concat(field, fieldSize), + partCharset, + 0 + ); + } + field = void 0; + fieldSize = 0; + this.emit( + "field", + partName, + data3, + { + nameTruncated: false, + valueTruncated: partTruncated, + encoding: partEncoding, + mimeType: partType + } + ); + } + if (++parts === partsLimit) + this.emit("partsLimit"); + } + }; + this._bparser = new StreamSearch(`\r +--${boundary}`, ssCb); + this._writecb = null; + this._finalcb = null; + this.write(BUF_CRLF); + } + static detect(conType) { + return conType.type === "multipart" && conType.subtype === "form-data"; + } + _write(chunk, enc2, cb) { + this._writecb = cb; + this._bparser.push(chunk, 0); + if (this._writecb) + callAndUnsetCb(this); + } + _destroy(err, cb) { + this._hparser = null; + this._bparser = ignoreData; + if (!err) + err = checkEndState(this); + const fileStream = this._fileStream; + if (fileStream) { + this._fileStream = null; + fileStream.destroy(err); + } + cb(err); + } + _final(cb) { + this._bparser.destroy(); + if (!this._complete) + return cb(new Error("Unexpected end of form")); + if (this._fileEndsLeft) + this._finalcb = finalcb.bind(null, this, cb); + else + finalcb(this, cb); + } + }; + function finalcb(self2, cb, err) { + if (err) + return cb(err); + err = checkEndState(self2); + cb(err); + } + function checkEndState(self2) { + if (self2._hparser) + return new Error("Malformed part header"); + const fileStream = self2._fileStream; + if (fileStream) { + self2._fileStream = null; + fileStream.destroy(new Error("Unexpected end of file")); + } + if (!self2._complete) + return new Error("Unexpected end of form"); + } + var TOKEN = [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 0, + 1, + 1, + 1, + 1, + 1, + 0, + 0, + 1, + 1, + 0, + 1, + 1, + 0, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 0, + 0, + 0, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 0, + 1, + 0, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ]; + var FIELD_VCHAR = [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 0, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1 + ]; + module.exports = Multipart; + } +}); + +// node_modules/.pnpm/busboy@1.6.0/node_modules/busboy/lib/types/urlencoded.js +var require_urlencoded2 = __commonJS({ + "node_modules/.pnpm/busboy@1.6.0/node_modules/busboy/lib/types/urlencoded.js"(exports, module) { + "use strict"; + var { Writable } = __require("stream"); + var { getDecoder } = require_utils4(); + var URLEncoded = class extends Writable { + constructor(cfg) { + const streamOpts = { + autoDestroy: true, + emitClose: true, + highWaterMark: typeof cfg.highWaterMark === "number" ? cfg.highWaterMark : void 0 + }; + super(streamOpts); + let charset = cfg.defCharset || "utf8"; + if (cfg.conType.params && typeof cfg.conType.params.charset === "string") + charset = cfg.conType.params.charset; + this.charset = charset; + const limits = cfg.limits; + this.fieldSizeLimit = limits && typeof limits.fieldSize === "number" ? limits.fieldSize : 1 * 1024 * 1024; + this.fieldsLimit = limits && typeof limits.fields === "number" ? limits.fields : Infinity; + this.fieldNameSizeLimit = limits && typeof limits.fieldNameSize === "number" ? limits.fieldNameSize : 100; + this._inKey = true; + this._keyTrunc = false; + this._valTrunc = false; + this._bytesKey = 0; + this._bytesVal = 0; + this._fields = 0; + this._key = ""; + this._val = ""; + this._byte = -2; + this._lastPos = 0; + this._encode = 0; + this._decoder = getDecoder(charset); + } + static detect(conType) { + return conType.type === "application" && conType.subtype === "x-www-form-urlencoded"; + } + _write(chunk, enc2, cb) { + if (this._fields >= this.fieldsLimit) + return cb(); + let i5 = 0; + const len = chunk.length; + this._lastPos = 0; + if (this._byte !== -2) { + i5 = readPctEnc(this, chunk, i5, len); + if (i5 === -1) + return cb(new Error("Malformed urlencoded form")); + if (i5 >= len) + return cb(); + if (this._inKey) + ++this._bytesKey; + else + ++this._bytesVal; + } + main: + while (i5 < len) { + if (this._inKey) { + i5 = skipKeyBytes(this, chunk, i5, len); + while (i5 < len) { + switch (chunk[i5]) { + case 61: + if (this._lastPos < i5) + this._key += chunk.latin1Slice(this._lastPos, i5); + this._lastPos = ++i5; + this._key = this._decoder(this._key, this._encode); + this._encode = 0; + this._inKey = false; + continue main; + case 38: + if (this._lastPos < i5) + this._key += chunk.latin1Slice(this._lastPos, i5); + this._lastPos = ++i5; + this._key = this._decoder(this._key, this._encode); + this._encode = 0; + if (this._bytesKey > 0) { + this.emit( + "field", + this._key, + "", + { + nameTruncated: this._keyTrunc, + valueTruncated: false, + encoding: this.charset, + mimeType: "text/plain" + } + ); + } + this._key = ""; + this._val = ""; + this._keyTrunc = false; + this._valTrunc = false; + this._bytesKey = 0; + this._bytesVal = 0; + if (++this._fields >= this.fieldsLimit) { + this.emit("fieldsLimit"); + return cb(); + } + continue; + case 43: + if (this._lastPos < i5) + this._key += chunk.latin1Slice(this._lastPos, i5); + this._key += " "; + this._lastPos = i5 + 1; + break; + case 37: + if (this._encode === 0) + this._encode = 1; + if (this._lastPos < i5) + this._key += chunk.latin1Slice(this._lastPos, i5); + this._lastPos = i5 + 1; + this._byte = -1; + i5 = readPctEnc(this, chunk, i5 + 1, len); + if (i5 === -1) + return cb(new Error("Malformed urlencoded form")); + if (i5 >= len) + return cb(); + ++this._bytesKey; + i5 = skipKeyBytes(this, chunk, i5, len); + continue; + } + ++i5; + ++this._bytesKey; + i5 = skipKeyBytes(this, chunk, i5, len); + } + if (this._lastPos < i5) + this._key += chunk.latin1Slice(this._lastPos, i5); + } else { + i5 = skipValBytes(this, chunk, i5, len); + while (i5 < len) { + switch (chunk[i5]) { + case 38: + if (this._lastPos < i5) + this._val += chunk.latin1Slice(this._lastPos, i5); + this._lastPos = ++i5; + this._inKey = true; + this._val = this._decoder(this._val, this._encode); + this._encode = 0; + if (this._bytesKey > 0 || this._bytesVal > 0) { + this.emit( + "field", + this._key, + this._val, + { + nameTruncated: this._keyTrunc, + valueTruncated: this._valTrunc, + encoding: this.charset, + mimeType: "text/plain" + } + ); + } + this._key = ""; + this._val = ""; + this._keyTrunc = false; + this._valTrunc = false; + this._bytesKey = 0; + this._bytesVal = 0; + if (++this._fields >= this.fieldsLimit) { + this.emit("fieldsLimit"); + return cb(); + } + continue main; + case 43: + if (this._lastPos < i5) + this._val += chunk.latin1Slice(this._lastPos, i5); + this._val += " "; + this._lastPos = i5 + 1; + break; + case 37: + if (this._encode === 0) + this._encode = 1; + if (this._lastPos < i5) + this._val += chunk.latin1Slice(this._lastPos, i5); + this._lastPos = i5 + 1; + this._byte = -1; + i5 = readPctEnc(this, chunk, i5 + 1, len); + if (i5 === -1) + return cb(new Error("Malformed urlencoded form")); + if (i5 >= len) + return cb(); + ++this._bytesVal; + i5 = skipValBytes(this, chunk, i5, len); + continue; + } + ++i5; + ++this._bytesVal; + i5 = skipValBytes(this, chunk, i5, len); + } + if (this._lastPos < i5) + this._val += chunk.latin1Slice(this._lastPos, i5); + } + } + cb(); + } + _final(cb) { + if (this._byte !== -2) + return cb(new Error("Malformed urlencoded form")); + if (!this._inKey || this._bytesKey > 0 || this._bytesVal > 0) { + if (this._inKey) + this._key = this._decoder(this._key, this._encode); + else + this._val = this._decoder(this._val, this._encode); + this.emit( + "field", + this._key, + this._val, + { + nameTruncated: this._keyTrunc, + valueTruncated: this._valTrunc, + encoding: this.charset, + mimeType: "text/plain" + } + ); + } + cb(); + } + }; + function readPctEnc(self2, chunk, pos, len) { + if (pos >= len) + return len; + if (self2._byte === -1) { + const hexUpper = HEX_VALUES[chunk[pos++]]; + if (hexUpper === -1) + return -1; + if (hexUpper >= 8) + self2._encode = 2; + if (pos < len) { + const hexLower = HEX_VALUES[chunk[pos++]]; + if (hexLower === -1) + return -1; + if (self2._inKey) + self2._key += String.fromCharCode((hexUpper << 4) + hexLower); + else + self2._val += String.fromCharCode((hexUpper << 4) + hexLower); + self2._byte = -2; + self2._lastPos = pos; + } else { + self2._byte = hexUpper; + } + } else { + const hexLower = HEX_VALUES[chunk[pos++]]; + if (hexLower === -1) + return -1; + if (self2._inKey) + self2._key += String.fromCharCode((self2._byte << 4) + hexLower); + else + self2._val += String.fromCharCode((self2._byte << 4) + hexLower); + self2._byte = -2; + self2._lastPos = pos; + } + return pos; + } + function skipKeyBytes(self2, chunk, pos, len) { + if (self2._bytesKey > self2.fieldNameSizeLimit) { + if (!self2._keyTrunc) { + if (self2._lastPos < pos) + self2._key += chunk.latin1Slice(self2._lastPos, pos - 1); + } + self2._keyTrunc = true; + for (; pos < len; ++pos) { + const code = chunk[pos]; + if (code === 61 || code === 38) + break; + ++self2._bytesKey; + } + self2._lastPos = pos; + } + return pos; + } + function skipValBytes(self2, chunk, pos, len) { + if (self2._bytesVal > self2.fieldSizeLimit) { + if (!self2._valTrunc) { + if (self2._lastPos < pos) + self2._val += chunk.latin1Slice(self2._lastPos, pos - 1); + } + self2._valTrunc = true; + for (; pos < len; ++pos) { + if (chunk[pos] === 38) + break; + ++self2._bytesVal; + } + self2._lastPos = pos; + } + return pos; + } + var HEX_VALUES = [ + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 10, + 11, + 12, + 13, + 14, + 15, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 10, + 11, + 12, + 13, + 14, + 15, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1 + ]; + module.exports = URLEncoded; + } +}); + +// node_modules/.pnpm/busboy@1.6.0/node_modules/busboy/lib/index.js +var require_lib3 = __commonJS({ + "node_modules/.pnpm/busboy@1.6.0/node_modules/busboy/lib/index.js"(exports, module) { + "use strict"; + var { parseContentType } = require_utils4(); + function getInstance(cfg) { + const headers = cfg.headers; + const conType = parseContentType(headers["content-type"]); + if (!conType) + throw new Error("Malformed content type"); + for (const type of TYPES) { + const matched = type.detect(conType); + if (!matched) + continue; + const instanceCfg = { + limits: cfg.limits, + headers, + conType, + highWaterMark: void 0, + fileHwm: void 0, + defCharset: void 0, + defParamCharset: void 0, + preservePath: false + }; + if (cfg.highWaterMark) + instanceCfg.highWaterMark = cfg.highWaterMark; + if (cfg.fileHwm) + instanceCfg.fileHwm = cfg.fileHwm; + instanceCfg.defCharset = cfg.defCharset; + instanceCfg.defParamCharset = cfg.defParamCharset; + instanceCfg.preservePath = cfg.preservePath; + return new type(instanceCfg); + } + throw new Error(`Unsupported content type: ${headers["content-type"]}`); + } + var TYPES = [ + require_multipart(), + require_urlencoded2() + ].filter(function(typemod) { + return typeof typemod.detect === "function"; + }); + module.exports = (cfg) => { + if (typeof cfg !== "object" || cfg === null) + cfg = {}; + if (typeof cfg.headers !== "object" || cfg.headers === null || typeof cfg.headers["content-type"] !== "string") { + throw new Error("Missing Content-Type"); + } + return getInstance(cfg); + }; + } +}); + +// node_modules/.pnpm/append-field@1.0.0/node_modules/append-field/lib/parse-path.js +var require_parse_path = __commonJS({ + "node_modules/.pnpm/append-field@1.0.0/node_modules/append-field/lib/parse-path.js"(exports, module) { + var reFirstKey = /^[^\[]*/; + var reDigitPath = /^\[(\d+)\]/; + var reNormalPath = /^\[([^\]]+)\]/; + function parsePath(key) { + function failure() { + return [{ type: "object", key, last: true }]; + } + var firstKey = reFirstKey.exec(key)[0]; + if (!firstKey) return failure(); + var len = key.length; + var pos = firstKey.length; + var tail = { type: "object", key: firstKey }; + var steps = [tail]; + while (pos < len) { + var m5; + if (key[pos] === "[" && key[pos + 1] === "]") { + pos += 2; + tail.append = true; + if (pos !== len) return failure(); + continue; + } + m5 = reDigitPath.exec(key.substring(pos)); + if (m5 !== null) { + pos += m5[0].length; + tail.nextType = "array"; + tail = { type: "array", key: parseInt(m5[1], 10) }; + steps.push(tail); + continue; + } + m5 = reNormalPath.exec(key.substring(pos)); + if (m5 !== null) { + pos += m5[0].length; + tail.nextType = "object"; + tail = { type: "object", key: m5[1] }; + steps.push(tail); + continue; + } + return failure(); + } + tail.last = true; + return steps; + } + module.exports = parsePath; + } +}); + +// node_modules/.pnpm/append-field@1.0.0/node_modules/append-field/lib/set-value.js +var require_set_value = __commonJS({ + "node_modules/.pnpm/append-field@1.0.0/node_modules/append-field/lib/set-value.js"(exports, module) { + function valueType(value) { + if (value === void 0) return "undefined"; + if (Array.isArray(value)) return "array"; + if (typeof value === "object") return "object"; + return "scalar"; + } + function setLastValue(context, step, currentValue, entryValue) { + switch (valueType(currentValue)) { + case "undefined": + if (step.append) { + context[step.key] = [entryValue]; + } else { + context[step.key] = entryValue; + } + break; + case "array": + context[step.key].push(entryValue); + break; + case "object": + return setLastValue(currentValue, { type: "object", key: "", last: true }, currentValue[""], entryValue); + case "scalar": + context[step.key] = [context[step.key], entryValue]; + break; + } + return context; + } + function setValue(context, step, currentValue, entryValue) { + if (step.last) return setLastValue(context, step, currentValue, entryValue); + var obj; + switch (valueType(currentValue)) { + case "undefined": + if (step.nextType === "array") { + context[step.key] = []; + } else { + context[step.key] = /* @__PURE__ */ Object.create(null); + } + return context[step.key]; + case "object": + return context[step.key]; + case "array": + if (step.nextType === "array") { + return currentValue; + } + obj = /* @__PURE__ */ Object.create(null); + context[step.key] = obj; + currentValue.forEach(function(item, i5) { + if (item !== void 0) obj["" + i5] = item; + }); + return obj; + case "scalar": + obj = /* @__PURE__ */ Object.create(null); + obj[""] = currentValue; + context[step.key] = obj; + return obj; + } + } + module.exports = setValue; + } +}); + +// node_modules/.pnpm/append-field@1.0.0/node_modules/append-field/index.js +var require_append_field = __commonJS({ + "node_modules/.pnpm/append-field@1.0.0/node_modules/append-field/index.js"(exports, module) { + var parsePath = require_parse_path(); + var setValue = require_set_value(); + function appendField(store, key, value) { + var steps = parsePath(key); + steps.reduce(function(context, step) { + return setValue(context, step, context[step.key], value); + }, store); + } + module.exports = appendField; + } +}); + +// node_modules/.pnpm/multer@2.1.1/node_modules/multer/lib/counter.js +var require_counter = __commonJS({ + "node_modules/.pnpm/multer@2.1.1/node_modules/multer/lib/counter.js"(exports, module) { + var EventEmitter5 = __require("events").EventEmitter; + function Counter() { + EventEmitter5.call(this); + this.value = 0; + } + Counter.prototype = Object.create(EventEmitter5.prototype); + Counter.prototype.increment = function increment2() { + this.value++; + }; + Counter.prototype.decrement = function decrement() { + if (--this.value === 0) this.emit("zero"); + }; + Counter.prototype.isZero = function isZero() { + return this.value === 0; + }; + Counter.prototype.onceZero = function onceZero(fn) { + if (this.isZero()) return fn(); + this.once("zero", fn); + }; + module.exports = Counter; + } +}); + +// node_modules/.pnpm/multer@2.1.1/node_modules/multer/lib/multer-error.js +var require_multer_error = __commonJS({ + "node_modules/.pnpm/multer@2.1.1/node_modules/multer/lib/multer-error.js"(exports, module) { + var util2 = __require("util"); + var errorMessages = { + LIMIT_PART_COUNT: "Too many parts", + LIMIT_FILE_SIZE: "File too large", + LIMIT_FILE_COUNT: "Too many files", + LIMIT_FIELD_KEY: "Field name too long", + LIMIT_FIELD_VALUE: "Field value too long", + LIMIT_FIELD_COUNT: "Too many fields", + LIMIT_UNEXPECTED_FILE: "Unexpected field", + MISSING_FIELD_NAME: "Field name missing" + }; + function MulterError(code, field) { + Error.captureStackTrace(this, this.constructor); + this.name = this.constructor.name; + this.message = errorMessages[code]; + this.code = code; + if (field) this.field = field; + } + util2.inherits(MulterError, Error); + module.exports = MulterError; + } +}); + +// node_modules/.pnpm/multer@2.1.1/node_modules/multer/lib/file-appender.js +var require_file_appender = __commonJS({ + "node_modules/.pnpm/multer@2.1.1/node_modules/multer/lib/file-appender.js"(exports, module) { + function arrayRemove(arr, item) { + var idx = arr.indexOf(item); + if (~idx) arr.splice(idx, 1); + } + function FileAppender(strategy, req) { + this.strategy = strategy; + this.req = req; + switch (strategy) { + case "NONE": + break; + case "VALUE": + break; + case "ARRAY": + req.files = []; + break; + case "OBJECT": + req.files = /* @__PURE__ */ Object.create(null); + break; + default: + throw new Error("Unknown file strategy: " + strategy); + } + } + FileAppender.prototype.insertPlaceholder = function(file2) { + var placeholder = { + fieldname: file2.fieldname + }; + switch (this.strategy) { + case "NONE": + break; + case "VALUE": + break; + case "ARRAY": + this.req.files.push(placeholder); + break; + case "OBJECT": + if (this.req.files[file2.fieldname]) { + this.req.files[file2.fieldname].push(placeholder); + } else { + this.req.files[file2.fieldname] = [placeholder]; + } + break; + } + return placeholder; + }; + FileAppender.prototype.removePlaceholder = function(placeholder) { + switch (this.strategy) { + case "NONE": + break; + case "VALUE": + break; + case "ARRAY": + arrayRemove(this.req.files, placeholder); + break; + case "OBJECT": + if (this.req.files[placeholder.fieldname].length === 1) { + delete this.req.files[placeholder.fieldname]; + } else { + arrayRemove(this.req.files[placeholder.fieldname], placeholder); + } + break; + } + }; + FileAppender.prototype.replacePlaceholder = function(placeholder, file2) { + if (this.strategy === "VALUE") { + this.req.file = file2; + return; + } + delete placeholder.fieldname; + Object.assign(placeholder, file2); + }; + module.exports = FileAppender; + } +}); + +// node_modules/.pnpm/multer@2.1.1/node_modules/multer/lib/remove-uploaded-files.js +var require_remove_uploaded_files = __commonJS({ + "node_modules/.pnpm/multer@2.1.1/node_modules/multer/lib/remove-uploaded-files.js"(exports, module) { + function removeUploadedFiles(uploadedFiles, remove, cb) { + var length = uploadedFiles.length; + var errors = []; + if (length === 0) return cb(null, errors); + function handleFile(idx) { + var file2 = uploadedFiles[idx]; + remove(file2, function(err) { + if (err) { + err.file = file2; + err.field = file2.fieldname; + errors.push(err); + } + if (idx < length - 1) { + setImmediate(function() { + handleFile(idx + 1); + }); + } else { + cb(null, errors); + } + }); + } + handleFile(0); + } + module.exports = removeUploadedFiles; + } +}); + +// node_modules/.pnpm/multer@2.1.1/node_modules/multer/lib/make-middleware.js +var require_make_middleware = __commonJS({ + "node_modules/.pnpm/multer@2.1.1/node_modules/multer/lib/make-middleware.js"(exports, module) { + var is2 = require_type_is2(); + var Busboy = require_lib3(); + var appendField = require_append_field(); + var Counter = require_counter(); + var MulterError = require_multer_error(); + var FileAppender = require_file_appender(); + var removeUploadedFiles = require_remove_uploaded_files(); + function drainStream(stream) { + stream.on("readable", () => { + while (stream.read() !== null) { + } + }); + } + function makeMiddleware(setup) { + return function multerMiddleware(req, res, next) { + if (!is2(req, ["multipart"])) return next(); + var options = setup(); + var limits = options.limits; + var storage = options.storage; + var fileFilter = options.fileFilter; + var fileStrategy = options.fileStrategy; + var preservePath = options.preservePath; + var defParamCharset = options.defParamCharset; + req.body = /* @__PURE__ */ Object.create(null); + var busboy; + var appender = null; + var isDone = false; + var readFinished = false; + var errorOccured = false; + var pendingWrites = new Counter(); + var uploadedFiles = []; + function done(err) { + var called = false; + function onFinished() { + if (called) return; + called = true; + next(err); + } + if (isDone) return; + isDone = true; + if (busboy) { + req.unpipe(busboy); + setImmediate(() => { + busboy.removeAllListeners(); + }); + } + drainStream(req); + req.resume(); + if (err && req.readable && !req.destroyed) { + req.once("end", onFinished); + req.once("error", onFinished); + req.once("close", onFinished); + return; + } + next(err); + } + function indicateDone() { + if (readFinished && pendingWrites.isZero() && !errorOccured) done(); + } + function abortWithError(uploadError, skipPendingWait) { + if (errorOccured) return; + errorOccured = true; + function finishAbort() { + function remove(file2, cb) { + storage._removeFile(req, file2, cb); + } + removeUploadedFiles(uploadedFiles, remove, function(err, storageErrors) { + if (err) return done(err); + uploadError.storageErrors = storageErrors; + done(uploadError); + }); + } + if (skipPendingWait) { + finishAbort(); + } else { + pendingWrites.onceZero(finishAbort); + } + } + function abortWithCode(code, optionalField) { + abortWithError(new MulterError(code, optionalField)); + } + function handleRequestFailure(err) { + if (isDone) return; + if (busboy) { + req.unpipe(busboy); + busboy.destroy(err); + } + abortWithError(err, true); + } + req.on("error", function(err) { + handleRequestFailure(err || new Error("Request error")); + }); + req.on("aborted", function() { + handleRequestFailure(new Error("Request aborted")); + }); + req.on("close", function() { + if (req.readableEnded) return; + handleRequestFailure(new Error("Request closed")); + }); + try { + busboy = Busboy({ + headers: req.headers, + limits, + preservePath, + defParamCharset + }); + } catch (err) { + return next(err); + } + appender = new FileAppender(fileStrategy, req); + busboy.on("field", function(fieldname, value, { nameTruncated, valueTruncated }) { + if (fieldname == null) return abortWithCode("MISSING_FIELD_NAME"); + if (nameTruncated) return abortWithCode("LIMIT_FIELD_KEY"); + if (valueTruncated) return abortWithCode("LIMIT_FIELD_VALUE", fieldname); + if (limits && Object.prototype.hasOwnProperty.call(limits, "fieldNameSize")) { + if (fieldname.length > limits.fieldNameSize) return abortWithCode("LIMIT_FIELD_KEY"); + } + appendField(req.body, fieldname, value); + }); + busboy.on("file", function(fieldname, fileStream, { filename, encoding, mimeType }) { + var pendingWritesIncremented = false; + fileStream.on("error", function(err) { + if (pendingWritesIncremented) { + pendingWrites.decrement(); + } + abortWithError(err); + }); + if (fieldname == null) return abortWithCode("MISSING_FIELD_NAME"); + if (!filename) return fileStream.resume(); + if (limits && Object.prototype.hasOwnProperty.call(limits, "fieldNameSize")) { + if (fieldname.length > limits.fieldNameSize) return abortWithCode("LIMIT_FIELD_KEY"); + } + var file2 = { + fieldname, + originalname: filename, + encoding, + mimetype: mimeType + }; + var placeholder = appender.insertPlaceholder(file2); + fileFilter(req, file2, function(err, includeFile) { + if (errorOccured) { + appender.removePlaceholder(placeholder); + return fileStream.resume(); + } + if (err) { + appender.removePlaceholder(placeholder); + return abortWithError(err); + } + if (!includeFile) { + appender.removePlaceholder(placeholder); + return fileStream.resume(); + } + var aborting = false; + pendingWritesIncremented = true; + pendingWrites.increment(); + Object.defineProperty(file2, "stream", { + configurable: true, + enumerable: false, + value: fileStream + }); + fileStream.on("limit", function() { + aborting = true; + abortWithCode("LIMIT_FILE_SIZE", fieldname); + }); + storage._handleFile(req, file2, function(err2, info2) { + if (aborting) { + appender.removePlaceholder(placeholder); + uploadedFiles.push({ ...file2, ...info2 }); + return pendingWrites.decrement(); + } + if (err2) { + appender.removePlaceholder(placeholder); + pendingWrites.decrement(); + return abortWithError(err2); + } + var fileInfo = { ...file2, ...info2 }; + appender.replacePlaceholder(placeholder, fileInfo); + uploadedFiles.push(fileInfo); + pendingWrites.decrement(); + indicateDone(); + }); + }); + }); + busboy.on("error", function(err) { + abortWithError(err); + }); + busboy.on("partsLimit", function() { + abortWithCode("LIMIT_PART_COUNT"); + }); + busboy.on("filesLimit", function() { + abortWithCode("LIMIT_FILE_COUNT"); + }); + busboy.on("fieldsLimit", function() { + abortWithCode("LIMIT_FIELD_COUNT"); + }); + busboy.on("close", function() { + readFinished = true; + indicateDone(); + }); + req.pipe(busboy); + }; + } + module.exports = makeMiddleware; + } +}); + +// node_modules/.pnpm/multer@2.1.1/node_modules/multer/storage/disk.js +var require_disk = __commonJS({ + "node_modules/.pnpm/multer@2.1.1/node_modules/multer/storage/disk.js"(exports, module) { + var fs41 = __require("fs"); + var os24 = __require("os"); + var path53 = __require("path"); + var crypto6 = __require("crypto"); + function getFilename(req, file2, cb) { + crypto6.randomBytes(16, function(err, raw) { + cb(err, err ? void 0 : raw.toString("hex")); + }); + } + function getDestination(req, file2, cb) { + cb(null, os24.tmpdir()); + } + function DiskStorage(opts) { + this.getFilename = opts.filename || getFilename; + if (typeof opts.destination === "string") { + fs41.mkdirSync(opts.destination, { recursive: true }); + this.getDestination = function($0, $1, cb) { + cb(null, opts.destination); + }; + } else { + this.getDestination = opts.destination || getDestination; + } + } + DiskStorage.prototype._handleFile = function _handleFile(req, file2, cb) { + var that = this; + that.getDestination(req, file2, function(err, destination) { + if (err) return cb(err); + that.getFilename(req, file2, function(err2, filename) { + if (err2) return cb(err2); + var finalPath = path53.join(destination, filename); + var outStream = fs41.createWriteStream(finalPath); + file2.stream.pipe(outStream); + outStream.on("error", cb); + outStream.on("finish", function() { + cb(null, { + destination, + filename, + path: finalPath, + size: outStream.bytesWritten + }); + }); + }); + }); + }; + DiskStorage.prototype._removeFile = function _removeFile(req, file2, cb) { + var path54 = file2.path; + delete file2.destination; + delete file2.filename; + delete file2.path; + fs41.unlink(path54, cb); + }; + module.exports = function(opts) { + return new DiskStorage(opts); + }; + } +}); + +// node_modules/.pnpm/readable-stream@3.6.2/node_modules/readable-stream/lib/internal/streams/stream.js +var require_stream2 = __commonJS({ + "node_modules/.pnpm/readable-stream@3.6.2/node_modules/readable-stream/lib/internal/streams/stream.js"(exports, module) { + module.exports = __require("stream"); + } +}); + +// node_modules/.pnpm/readable-stream@3.6.2/node_modules/readable-stream/lib/internal/streams/buffer_list.js +var require_buffer_list = __commonJS({ + "node_modules/.pnpm/readable-stream@3.6.2/node_modules/readable-stream/lib/internal/streams/buffer_list.js"(exports, module) { + "use strict"; + function ownKeys2(object2, enumerableOnly) { + var keys = Object.keys(object2); + if (Object.getOwnPropertySymbols) { + var symbols = Object.getOwnPropertySymbols(object2); + enumerableOnly && (symbols = symbols.filter(function(sym) { + return Object.getOwnPropertyDescriptor(object2, sym).enumerable; + })), keys.push.apply(keys, symbols); + } + return keys; + } + function _objectSpread(target) { + for (var i5 = 1; i5 < arguments.length; i5++) { + var source = null != arguments[i5] ? arguments[i5] : {}; + i5 % 2 ? ownKeys2(Object(source), true).forEach(function(key) { + _defineProperty(target, key, source[key]); + }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys2(Object(source)).forEach(function(key) { + Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); + }); + } + return target; + } + function _defineProperty(obj, key, value) { + key = _toPropertyKey(key); + if (key in obj) { + Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true }); + } else { + obj[key] = value; + } + return obj; + } + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } + function _defineProperties(target, props) { + for (var i5 = 0; i5 < props.length; i5++) { + var descriptor = props[i5]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ("value" in descriptor) descriptor.writable = true; + Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); + } + } + function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) _defineProperties(Constructor.prototype, protoProps); + if (staticProps) _defineProperties(Constructor, staticProps); + Object.defineProperty(Constructor, "prototype", { writable: false }); + return Constructor; + } + function _toPropertyKey(arg) { + var key = _toPrimitive(arg, "string"); + return typeof key === "symbol" ? key : String(key); + } + function _toPrimitive(input, hint) { + if (typeof input !== "object" || input === null) return input; + var prim = input[Symbol.toPrimitive]; + if (prim !== void 0) { + var res = prim.call(input, hint || "default"); + if (typeof res !== "object") return res; + throw new TypeError("@@toPrimitive must return a primitive value."); + } + return (hint === "string" ? String : Number)(input); + } + var _require = __require("buffer"); + var Buffer2 = _require.Buffer; + var _require2 = __require("util"); + var inspect = _require2.inspect; + var custom3 = inspect && inspect.custom || "inspect"; + function copyBuffer(src, target, offset) { + Buffer2.prototype.copy.call(src, target, offset); + } + module.exports = /* @__PURE__ */ (function() { + function BufferList() { + _classCallCheck(this, BufferList); + this.head = null; + this.tail = null; + this.length = 0; + } + _createClass(BufferList, [{ + key: "push", + value: function push(v5) { + var entry = { + data: v5, + next: null + }; + if (this.length > 0) this.tail.next = entry; + else this.head = entry; + this.tail = entry; + ++this.length; + } + }, { + key: "unshift", + value: function unshift(v5) { + var entry = { + data: v5, + next: this.head + }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + } + }, { + key: "shift", + value: function shift() { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null; + else this.head = this.head.next; + --this.length; + return ret; + } + }, { + key: "clear", + value: function clear() { + this.head = this.tail = null; + this.length = 0; + } + }, { + key: "join", + value: function join4(s5) { + if (this.length === 0) return ""; + var p5 = this.head; + var ret = "" + p5.data; + while (p5 = p5.next) ret += s5 + p5.data; + return ret; + } + }, { + key: "concat", + value: function concat2(n5) { + if (this.length === 0) return Buffer2.alloc(0); + var ret = Buffer2.allocUnsafe(n5 >>> 0); + var p5 = this.head; + var i5 = 0; + while (p5) { + copyBuffer(p5.data, ret, i5); + i5 += p5.data.length; + p5 = p5.next; + } + return ret; + } + // Consumes a specified amount of bytes or characters from the buffered data. + }, { + key: "consume", + value: function consume(n5, hasStrings) { + var ret; + if (n5 < this.head.data.length) { + ret = this.head.data.slice(0, n5); + this.head.data = this.head.data.slice(n5); + } else if (n5 === this.head.data.length) { + ret = this.shift(); + } else { + ret = hasStrings ? this._getString(n5) : this._getBuffer(n5); + } + return ret; + } + }, { + key: "first", + value: function first() { + return this.head.data; + } + // Consumes a specified amount of characters from the buffered data. + }, { + key: "_getString", + value: function _getString(n5) { + var p5 = this.head; + var c5 = 1; + var ret = p5.data; + n5 -= ret.length; + while (p5 = p5.next) { + var str = p5.data; + var nb = n5 > str.length ? str.length : n5; + if (nb === str.length) ret += str; + else ret += str.slice(0, n5); + n5 -= nb; + if (n5 === 0) { + if (nb === str.length) { + ++c5; + if (p5.next) this.head = p5.next; + else this.head = this.tail = null; + } else { + this.head = p5; + p5.data = str.slice(nb); + } + break; + } + ++c5; + } + this.length -= c5; + return ret; + } + // Consumes a specified amount of bytes from the buffered data. + }, { + key: "_getBuffer", + value: function _getBuffer(n5) { + var ret = Buffer2.allocUnsafe(n5); + var p5 = this.head; + var c5 = 1; + p5.data.copy(ret); + n5 -= p5.data.length; + while (p5 = p5.next) { + var buf = p5.data; + var nb = n5 > buf.length ? buf.length : n5; + buf.copy(ret, ret.length - n5, 0, nb); + n5 -= nb; + if (n5 === 0) { + if (nb === buf.length) { + ++c5; + if (p5.next) this.head = p5.next; + else this.head = this.tail = null; + } else { + this.head = p5; + p5.data = buf.slice(nb); + } + break; + } + ++c5; + } + this.length -= c5; + return ret; + } + // Make sure the linked list only shows the minimal necessary information. + }, { + key: custom3, + value: function value(_, options) { + return inspect(this, _objectSpread(_objectSpread({}, options), {}, { + // Only inspect one level. + depth: 0, + // It should not recurse. + customInspect: false + })); + } + }]); + return BufferList; + })(); + } +}); + +// node_modules/.pnpm/readable-stream@3.6.2/node_modules/readable-stream/lib/internal/streams/destroy.js +var require_destroy = __commonJS({ + "node_modules/.pnpm/readable-stream@3.6.2/node_modules/readable-stream/lib/internal/streams/destroy.js"(exports, module) { + "use strict"; + function destroy(err, cb) { + var _this = this; + var readableDestroyed = this._readableState && this._readableState.destroyed; + var writableDestroyed = this._writableState && this._writableState.destroyed; + if (readableDestroyed || writableDestroyed) { + if (cb) { + cb(err); + } else if (err) { + if (!this._writableState) { + process.nextTick(emitErrorNT, this, err); + } else if (!this._writableState.errorEmitted) { + this._writableState.errorEmitted = true; + process.nextTick(emitErrorNT, this, err); + } + } + return this; + } + if (this._readableState) { + this._readableState.destroyed = true; + } + if (this._writableState) { + this._writableState.destroyed = true; + } + this._destroy(err || null, function(err2) { + if (!cb && err2) { + if (!_this._writableState) { + process.nextTick(emitErrorAndCloseNT, _this, err2); + } else if (!_this._writableState.errorEmitted) { + _this._writableState.errorEmitted = true; + process.nextTick(emitErrorAndCloseNT, _this, err2); + } else { + process.nextTick(emitCloseNT, _this); + } + } else if (cb) { + process.nextTick(emitCloseNT, _this); + cb(err2); + } else { + process.nextTick(emitCloseNT, _this); + } + }); + return this; + } + function emitErrorAndCloseNT(self2, err) { + emitErrorNT(self2, err); + emitCloseNT(self2); + } + function emitCloseNT(self2) { + if (self2._writableState && !self2._writableState.emitClose) return; + if (self2._readableState && !self2._readableState.emitClose) return; + self2.emit("close"); + } + function undestroy() { + if (this._readableState) { + this._readableState.destroyed = false; + this._readableState.reading = false; + this._readableState.ended = false; + this._readableState.endEmitted = false; + } + if (this._writableState) { + this._writableState.destroyed = false; + this._writableState.ended = false; + this._writableState.ending = false; + this._writableState.finalCalled = false; + this._writableState.prefinished = false; + this._writableState.finished = false; + this._writableState.errorEmitted = false; + } + } + function emitErrorNT(self2, err) { + self2.emit("error", err); + } + function errorOrDestroy(stream, err) { + var rState = stream._readableState; + var wState = stream._writableState; + if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err); + else stream.emit("error", err); + } + module.exports = { + destroy, + undestroy, + errorOrDestroy + }; + } +}); + +// node_modules/.pnpm/readable-stream@3.6.2/node_modules/readable-stream/errors.js +var require_errors2 = __commonJS({ + "node_modules/.pnpm/readable-stream@3.6.2/node_modules/readable-stream/errors.js"(exports, module) { + "use strict"; + var codes = {}; + function createErrorType(code, message2, Base) { + if (!Base) { + Base = Error; + } + function getMessage(arg1, arg2, arg3) { + if (typeof message2 === "string") { + return message2; + } else { + return message2(arg1, arg2, arg3); + } + } + class NodeError extends Base { + constructor(arg1, arg2, arg3) { + super(getMessage(arg1, arg2, arg3)); + } + } + NodeError.prototype.name = Base.name; + NodeError.prototype.code = code; + codes[code] = NodeError; + } + function oneOf(expected, thing) { + if (Array.isArray(expected)) { + const len = expected.length; + expected = expected.map((i5) => String(i5)); + if (len > 2) { + return `one of ${thing} ${expected.slice(0, len - 1).join(", ")}, or ` + expected[len - 1]; + } else if (len === 2) { + return `one of ${thing} ${expected[0]} or ${expected[1]}`; + } else { + return `of ${thing} ${expected[0]}`; + } + } else { + return `of ${thing} ${String(expected)}`; + } + } + function startsWith(str, search, pos) { + return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; + } + function endsWith(str, search, this_len) { + if (this_len === void 0 || this_len > str.length) { + this_len = str.length; + } + return str.substring(this_len - search.length, this_len) === search; + } + function includes(str, search, start) { + if (typeof start !== "number") { + start = 0; + } + if (start + search.length > str.length) { + return false; + } else { + return str.indexOf(search, start) !== -1; + } + } + createErrorType("ERR_INVALID_OPT_VALUE", function(name, value) { + return 'The value "' + value + '" is invalid for option "' + name + '"'; + }, TypeError); + createErrorType("ERR_INVALID_ARG_TYPE", function(name, expected, actual) { + let determiner; + if (typeof expected === "string" && startsWith(expected, "not ")) { + determiner = "must not be"; + expected = expected.replace(/^not /, ""); + } else { + determiner = "must be"; + } + let msg; + if (endsWith(name, " argument")) { + msg = `The ${name} ${determiner} ${oneOf(expected, "type")}`; + } else { + const type = includes(name, ".") ? "property" : "argument"; + msg = `The "${name}" ${type} ${determiner} ${oneOf(expected, "type")}`; + } + msg += `. Received type ${typeof actual}`; + return msg; + }, TypeError); + createErrorType("ERR_STREAM_PUSH_AFTER_EOF", "stream.push() after EOF"); + createErrorType("ERR_METHOD_NOT_IMPLEMENTED", function(name) { + return "The " + name + " method is not implemented"; + }); + createErrorType("ERR_STREAM_PREMATURE_CLOSE", "Premature close"); + createErrorType("ERR_STREAM_DESTROYED", function(name) { + return "Cannot call " + name + " after a stream was destroyed"; + }); + createErrorType("ERR_MULTIPLE_CALLBACK", "Callback called multiple times"); + createErrorType("ERR_STREAM_CANNOT_PIPE", "Cannot pipe, not readable"); + createErrorType("ERR_STREAM_WRITE_AFTER_END", "write after end"); + createErrorType("ERR_STREAM_NULL_VALUES", "May not write null values to stream", TypeError); + createErrorType("ERR_UNKNOWN_ENCODING", function(arg) { + return "Unknown encoding: " + arg; + }, TypeError); + createErrorType("ERR_STREAM_UNSHIFT_AFTER_END_EVENT", "stream.unshift() after end event"); + module.exports.codes = codes; + } +}); + +// node_modules/.pnpm/readable-stream@3.6.2/node_modules/readable-stream/lib/internal/streams/state.js +var require_state = __commonJS({ + "node_modules/.pnpm/readable-stream@3.6.2/node_modules/readable-stream/lib/internal/streams/state.js"(exports, module) { + "use strict"; + var ERR_INVALID_OPT_VALUE = require_errors2().codes.ERR_INVALID_OPT_VALUE; + function highWaterMarkFrom(options, isDuplex, duplexKey) { + return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null; + } + function getHighWaterMark(state2, options, duplexKey, isDuplex) { + var hwm = highWaterMarkFrom(options, isDuplex, duplexKey); + if (hwm != null) { + if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) { + var name = isDuplex ? duplexKey : "highWaterMark"; + throw new ERR_INVALID_OPT_VALUE(name, hwm); + } + return Math.floor(hwm); + } + return state2.objectMode ? 16 : 16 * 1024; + } + module.exports = { + getHighWaterMark + }; + } +}); + +// node_modules/.pnpm/util-deprecate@1.0.2/node_modules/util-deprecate/node.js +var require_node2 = __commonJS({ + "node_modules/.pnpm/util-deprecate@1.0.2/node_modules/util-deprecate/node.js"(exports, module) { + module.exports = __require("util").deprecate; + } +}); + +// node_modules/.pnpm/readable-stream@3.6.2/node_modules/readable-stream/lib/_stream_writable.js +var require_stream_writable = __commonJS({ + "node_modules/.pnpm/readable-stream@3.6.2/node_modules/readable-stream/lib/_stream_writable.js"(exports, module) { + "use strict"; + module.exports = Writable; + function CorkedRequest(state2) { + var _this = this; + this.next = null; + this.entry = null; + this.finish = function() { + onCorkedFinish(_this, state2); + }; + } + var Duplex; + Writable.WritableState = WritableState; + var internalUtil = { + deprecate: require_node2() + }; + var Stream3 = require_stream2(); + var Buffer2 = __require("buffer").Buffer; + var OurUint8Array = (typeof global !== "undefined" ? global : typeof window !== "undefined" ? window : typeof self !== "undefined" ? self : {}).Uint8Array || function() { + }; + function _uint8ArrayToBuffer(chunk) { + return Buffer2.from(chunk); + } + function _isUint8Array(obj) { + return Buffer2.isBuffer(obj) || obj instanceof OurUint8Array; + } + var destroyImpl = require_destroy(); + var _require = require_state(); + var getHighWaterMark = _require.getHighWaterMark; + var _require$codes = require_errors2().codes; + var ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE; + var ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED; + var ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK; + var ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE; + var ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; + var ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES; + var ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END; + var ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING; + var errorOrDestroy = destroyImpl.errorOrDestroy; + require_inherits()(Writable, Stream3); + function nop() { + } + function WritableState(options, stream, isDuplex) { + Duplex = Duplex || require_stream_duplex(); + options = options || {}; + if (typeof isDuplex !== "boolean") isDuplex = stream instanceof Duplex; + this.objectMode = !!options.objectMode; + if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; + this.highWaterMark = getHighWaterMark(this, options, "writableHighWaterMark", isDuplex); + this.finalCalled = false; + this.needDrain = false; + this.ending = false; + this.ended = false; + this.finished = false; + this.destroyed = false; + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; + this.defaultEncoding = options.defaultEncoding || "utf8"; + this.length = 0; + this.writing = false; + this.corked = 0; + this.sync = true; + this.bufferProcessing = false; + this.onwrite = function(er) { + onwrite(stream, er); + }; + this.writecb = null; + this.writelen = 0; + this.bufferedRequest = null; + this.lastBufferedRequest = null; + this.pendingcb = 0; + this.prefinished = false; + this.errorEmitted = false; + this.emitClose = options.emitClose !== false; + this.autoDestroy = !!options.autoDestroy; + this.bufferedRequestCount = 0; + this.corkedRequestsFree = new CorkedRequest(this); + } + WritableState.prototype.getBuffer = function getBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; + } + return out; + }; + (function() { + try { + Object.defineProperty(WritableState.prototype, "buffer", { + get: internalUtil.deprecate(function writableStateBufferGetter() { + return this.getBuffer(); + }, "_writableState.buffer is deprecated. Use _writableState.getBuffer instead.", "DEP0003") + }); + } catch (_) { + } + })(); + var realHasInstance; + if (typeof Symbol === "function" && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === "function") { + realHasInstance = Function.prototype[Symbol.hasInstance]; + Object.defineProperty(Writable, Symbol.hasInstance, { + value: function value(object2) { + if (realHasInstance.call(this, object2)) return true; + if (this !== Writable) return false; + return object2 && object2._writableState instanceof WritableState; + } + }); + } else { + realHasInstance = function realHasInstance2(object2) { + return object2 instanceof this; + }; + } + function Writable(options) { + Duplex = Duplex || require_stream_duplex(); + var isDuplex = this instanceof Duplex; + if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options); + this._writableState = new WritableState(options, this, isDuplex); + this.writable = true; + if (options) { + if (typeof options.write === "function") this._write = options.write; + if (typeof options.writev === "function") this._writev = options.writev; + if (typeof options.destroy === "function") this._destroy = options.destroy; + if (typeof options.final === "function") this._final = options.final; + } + Stream3.call(this); + } + Writable.prototype.pipe = function() { + errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE()); + }; + function writeAfterEnd(stream, cb) { + var er = new ERR_STREAM_WRITE_AFTER_END(); + errorOrDestroy(stream, er); + process.nextTick(cb, er); + } + function validChunk(stream, state2, chunk, cb) { + var er; + if (chunk === null) { + er = new ERR_STREAM_NULL_VALUES(); + } else if (typeof chunk !== "string" && !state2.objectMode) { + er = new ERR_INVALID_ARG_TYPE("chunk", ["string", "Buffer"], chunk); + } + if (er) { + errorOrDestroy(stream, er); + process.nextTick(cb, er); + return false; + } + return true; + } + Writable.prototype.write = function(chunk, encoding, cb) { + var state2 = this._writableState; + var ret = false; + var isBuf = !state2.objectMode && _isUint8Array(chunk); + if (isBuf && !Buffer2.isBuffer(chunk)) { + chunk = _uint8ArrayToBuffer(chunk); + } + if (typeof encoding === "function") { + cb = encoding; + encoding = null; + } + if (isBuf) encoding = "buffer"; + else if (!encoding) encoding = state2.defaultEncoding; + if (typeof cb !== "function") cb = nop; + if (state2.ending) writeAfterEnd(this, cb); + else if (isBuf || validChunk(this, state2, chunk, cb)) { + state2.pendingcb++; + ret = writeOrBuffer(this, state2, isBuf, chunk, encoding, cb); + } + return ret; + }; + Writable.prototype.cork = function() { + this._writableState.corked++; + }; + Writable.prototype.uncork = function() { + var state2 = this._writableState; + if (state2.corked) { + state2.corked--; + if (!state2.writing && !state2.corked && !state2.bufferProcessing && state2.bufferedRequest) clearBuffer(this, state2); + } + }; + Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + if (typeof encoding === "string") encoding = encoding.toLowerCase(); + if (!(["hex", "utf8", "utf-8", "ascii", "binary", "base64", "ucs2", "ucs-2", "utf16le", "utf-16le", "raw"].indexOf((encoding + "").toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding); + this._writableState.defaultEncoding = encoding; + return this; + }; + Object.defineProperty(Writable.prototype, "writableBuffer", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get2() { + return this._writableState && this._writableState.getBuffer(); + } + }); + function decodeChunk(state2, chunk, encoding) { + if (!state2.objectMode && state2.decodeStrings !== false && typeof chunk === "string") { + chunk = Buffer2.from(chunk, encoding); + } + return chunk; + } + Object.defineProperty(Writable.prototype, "writableHighWaterMark", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get2() { + return this._writableState.highWaterMark; + } + }); + function writeOrBuffer(stream, state2, isBuf, chunk, encoding, cb) { + if (!isBuf) { + var newChunk = decodeChunk(state2, chunk, encoding); + if (chunk !== newChunk) { + isBuf = true; + encoding = "buffer"; + chunk = newChunk; + } + } + var len = state2.objectMode ? 1 : chunk.length; + state2.length += len; + var ret = state2.length < state2.highWaterMark; + if (!ret) state2.needDrain = true; + if (state2.writing || state2.corked) { + var last = state2.lastBufferedRequest; + state2.lastBufferedRequest = { + chunk, + encoding, + isBuf, + callback: cb, + next: null + }; + if (last) { + last.next = state2.lastBufferedRequest; + } else { + state2.bufferedRequest = state2.lastBufferedRequest; + } + state2.bufferedRequestCount += 1; + } else { + doWrite(stream, state2, false, len, chunk, encoding, cb); + } + return ret; + } + function doWrite(stream, state2, writev, len, chunk, encoding, cb) { + state2.writelen = len; + state2.writecb = cb; + state2.writing = true; + state2.sync = true; + if (state2.destroyed) state2.onwrite(new ERR_STREAM_DESTROYED("write")); + else if (writev) stream._writev(chunk, state2.onwrite); + else stream._write(chunk, encoding, state2.onwrite); + state2.sync = false; + } + function onwriteError(stream, state2, sync, er, cb) { + --state2.pendingcb; + if (sync) { + process.nextTick(cb, er); + process.nextTick(finishMaybe, stream, state2); + stream._writableState.errorEmitted = true; + errorOrDestroy(stream, er); + } else { + cb(er); + stream._writableState.errorEmitted = true; + errorOrDestroy(stream, er); + finishMaybe(stream, state2); + } + } + function onwriteStateUpdate(state2) { + state2.writing = false; + state2.writecb = null; + state2.length -= state2.writelen; + state2.writelen = 0; + } + function onwrite(stream, er) { + var state2 = stream._writableState; + var sync = state2.sync; + var cb = state2.writecb; + if (typeof cb !== "function") throw new ERR_MULTIPLE_CALLBACK(); + onwriteStateUpdate(state2); + if (er) onwriteError(stream, state2, sync, er, cb); + else { + var finished = needFinish(state2) || stream.destroyed; + if (!finished && !state2.corked && !state2.bufferProcessing && state2.bufferedRequest) { + clearBuffer(stream, state2); + } + if (sync) { + process.nextTick(afterWrite, stream, state2, finished, cb); + } else { + afterWrite(stream, state2, finished, cb); + } + } + } + function afterWrite(stream, state2, finished, cb) { + if (!finished) onwriteDrain(stream, state2); + state2.pendingcb--; + cb(); + finishMaybe(stream, state2); + } + function onwriteDrain(stream, state2) { + if (state2.length === 0 && state2.needDrain) { + state2.needDrain = false; + stream.emit("drain"); + } + } + function clearBuffer(stream, state2) { + state2.bufferProcessing = true; + var entry = state2.bufferedRequest; + if (stream._writev && entry && entry.next) { + var l5 = state2.bufferedRequestCount; + var buffer2 = new Array(l5); + var holder = state2.corkedRequestsFree; + holder.entry = entry; + var count2 = 0; + var allBuffers = true; + while (entry) { + buffer2[count2] = entry; + if (!entry.isBuf) allBuffers = false; + entry = entry.next; + count2 += 1; + } + buffer2.allBuffers = allBuffers; + doWrite(stream, state2, true, state2.length, buffer2, "", holder.finish); + state2.pendingcb++; + state2.lastBufferedRequest = null; + if (holder.next) { + state2.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state2.corkedRequestsFree = new CorkedRequest(state2); + } + state2.bufferedRequestCount = 0; + } else { + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state2.objectMode ? 1 : chunk.length; + doWrite(stream, state2, false, len, chunk, encoding, cb); + entry = entry.next; + state2.bufferedRequestCount--; + if (state2.writing) { + break; + } + } + if (entry === null) state2.lastBufferedRequest = null; + } + state2.bufferedRequest = entry; + state2.bufferProcessing = false; + } + Writable.prototype._write = function(chunk, encoding, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED("_write()")); + }; + Writable.prototype._writev = null; + Writable.prototype.end = function(chunk, encoding, cb) { + var state2 = this._writableState; + if (typeof chunk === "function") { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === "function") { + cb = encoding; + encoding = null; + } + if (chunk !== null && chunk !== void 0) this.write(chunk, encoding); + if (state2.corked) { + state2.corked = 1; + this.uncork(); + } + if (!state2.ending) endWritable(this, state2, cb); + return this; + }; + Object.defineProperty(Writable.prototype, "writableLength", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get2() { + return this._writableState.length; + } + }); + function needFinish(state2) { + return state2.ending && state2.length === 0 && state2.bufferedRequest === null && !state2.finished && !state2.writing; + } + function callFinal(stream, state2) { + stream._final(function(err) { + state2.pendingcb--; + if (err) { + errorOrDestroy(stream, err); + } + state2.prefinished = true; + stream.emit("prefinish"); + finishMaybe(stream, state2); + }); + } + function prefinish(stream, state2) { + if (!state2.prefinished && !state2.finalCalled) { + if (typeof stream._final === "function" && !state2.destroyed) { + state2.pendingcb++; + state2.finalCalled = true; + process.nextTick(callFinal, stream, state2); + } else { + state2.prefinished = true; + stream.emit("prefinish"); + } + } + } + function finishMaybe(stream, state2) { + var need = needFinish(state2); + if (need) { + prefinish(stream, state2); + if (state2.pendingcb === 0) { + state2.finished = true; + stream.emit("finish"); + if (state2.autoDestroy) { + var rState = stream._readableState; + if (!rState || rState.autoDestroy && rState.endEmitted) { + stream.destroy(); + } + } + } + } + return need; + } + function endWritable(stream, state2, cb) { + state2.ending = true; + finishMaybe(stream, state2); + if (cb) { + if (state2.finished) process.nextTick(cb); + else stream.once("finish", cb); + } + state2.ended = true; + stream.writable = false; + } + function onCorkedFinish(corkReq, state2, err) { + var entry = corkReq.entry; + corkReq.entry = null; + while (entry) { + var cb = entry.callback; + state2.pendingcb--; + cb(err); + entry = entry.next; + } + state2.corkedRequestsFree.next = corkReq; + } + Object.defineProperty(Writable.prototype, "destroyed", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get2() { + if (this._writableState === void 0) { + return false; + } + return this._writableState.destroyed; + }, + set: function set2(value) { + if (!this._writableState) { + return; + } + this._writableState.destroyed = value; + } + }); + Writable.prototype.destroy = destroyImpl.destroy; + Writable.prototype._undestroy = destroyImpl.undestroy; + Writable.prototype._destroy = function(err, cb) { + cb(err); + }; + } +}); + +// node_modules/.pnpm/readable-stream@3.6.2/node_modules/readable-stream/lib/_stream_duplex.js +var require_stream_duplex = __commonJS({ + "node_modules/.pnpm/readable-stream@3.6.2/node_modules/readable-stream/lib/_stream_duplex.js"(exports, module) { + "use strict"; + var objectKeys = Object.keys || function(obj) { + var keys2 = []; + for (var key in obj) keys2.push(key); + return keys2; + }; + module.exports = Duplex; + var Readable3 = require_stream_readable(); + var Writable = require_stream_writable(); + require_inherits()(Duplex, Readable3); + { + keys = objectKeys(Writable.prototype); + for (v5 = 0; v5 < keys.length; v5++) { + method = keys[v5]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; + } + } + var keys; + var method; + var v5; + function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); + Readable3.call(this, options); + Writable.call(this, options); + this.allowHalfOpen = true; + if (options) { + if (options.readable === false) this.readable = false; + if (options.writable === false) this.writable = false; + if (options.allowHalfOpen === false) { + this.allowHalfOpen = false; + this.once("end", onend); + } + } + } + Object.defineProperty(Duplex.prototype, "writableHighWaterMark", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get2() { + return this._writableState.highWaterMark; + } + }); + Object.defineProperty(Duplex.prototype, "writableBuffer", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get2() { + return this._writableState && this._writableState.getBuffer(); + } + }); + Object.defineProperty(Duplex.prototype, "writableLength", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get2() { + return this._writableState.length; + } + }); + function onend() { + if (this._writableState.ended) return; + process.nextTick(onEndNT, this); + } + function onEndNT(self2) { + self2.end(); + } + Object.defineProperty(Duplex.prototype, "destroyed", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get2() { + if (this._readableState === void 0 || this._writableState === void 0) { + return false; + } + return this._readableState.destroyed && this._writableState.destroyed; + }, + set: function set2(value) { + if (this._readableState === void 0 || this._writableState === void 0) { + return; + } + this._readableState.destroyed = value; + this._writableState.destroyed = value; + } + }); + } +}); + +// node_modules/.pnpm/safe-buffer@5.2.1/node_modules/safe-buffer/index.js +var require_safe_buffer = __commonJS({ + "node_modules/.pnpm/safe-buffer@5.2.1/node_modules/safe-buffer/index.js"(exports, module) { + var buffer2 = __require("buffer"); + var Buffer2 = buffer2.Buffer; + function copyProps(src, dst) { + for (var key in src) { + dst[key] = src[key]; + } + } + if (Buffer2.from && Buffer2.alloc && Buffer2.allocUnsafe && Buffer2.allocUnsafeSlow) { + module.exports = buffer2; + } else { + copyProps(buffer2, exports); + exports.Buffer = SafeBuffer; + } + function SafeBuffer(arg, encodingOrOffset, length) { + return Buffer2(arg, encodingOrOffset, length); + } + SafeBuffer.prototype = Object.create(Buffer2.prototype); + copyProps(Buffer2, SafeBuffer); + SafeBuffer.from = function(arg, encodingOrOffset, length) { + if (typeof arg === "number") { + throw new TypeError("Argument must not be a number"); + } + return Buffer2(arg, encodingOrOffset, length); + }; + SafeBuffer.alloc = function(size2, fill, encoding) { + if (typeof size2 !== "number") { + throw new TypeError("Argument must be a number"); + } + var buf = Buffer2(size2); + if (fill !== void 0) { + if (typeof encoding === "string") { + buf.fill(fill, encoding); + } else { + buf.fill(fill); + } + } else { + buf.fill(0); + } + return buf; + }; + SafeBuffer.allocUnsafe = function(size2) { + if (typeof size2 !== "number") { + throw new TypeError("Argument must be a number"); + } + return Buffer2(size2); + }; + SafeBuffer.allocUnsafeSlow = function(size2) { + if (typeof size2 !== "number") { + throw new TypeError("Argument must be a number"); + } + return buffer2.SlowBuffer(size2); + }; + } +}); + +// node_modules/.pnpm/string_decoder@1.3.0/node_modules/string_decoder/lib/string_decoder.js +var require_string_decoder = __commonJS({ + "node_modules/.pnpm/string_decoder@1.3.0/node_modules/string_decoder/lib/string_decoder.js"(exports) { + "use strict"; + var Buffer2 = require_safe_buffer().Buffer; + var isEncoding = Buffer2.isEncoding || function(encoding) { + encoding = "" + encoding; + switch (encoding && encoding.toLowerCase()) { + case "hex": + case "utf8": + case "utf-8": + case "ascii": + case "binary": + case "base64": + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + case "raw": + return true; + default: + return false; + } + }; + function _normalizeEncoding(enc2) { + if (!enc2) return "utf8"; + var retried; + while (true) { + switch (enc2) { + case "utf8": + case "utf-8": + return "utf8"; + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + return "utf16le"; + case "latin1": + case "binary": + return "latin1"; + case "base64": + case "ascii": + case "hex": + return enc2; + default: + if (retried) return; + enc2 = ("" + enc2).toLowerCase(); + retried = true; + } + } + } + function normalizeEncoding(enc2) { + var nenc = _normalizeEncoding(enc2); + if (typeof nenc !== "string" && (Buffer2.isEncoding === isEncoding || !isEncoding(enc2))) throw new Error("Unknown encoding: " + enc2); + return nenc || enc2; + } + exports.StringDecoder = StringDecoder; + function StringDecoder(encoding) { + this.encoding = normalizeEncoding(encoding); + var nb; + switch (this.encoding) { + case "utf16le": + this.text = utf16Text; + this.end = utf16End; + nb = 4; + break; + case "utf8": + this.fillLast = utf8FillLast; + nb = 4; + break; + case "base64": + this.text = base64Text; + this.end = base64End; + nb = 3; + break; + default: + this.write = simpleWrite; + this.end = simpleEnd; + return; + } + this.lastNeed = 0; + this.lastTotal = 0; + this.lastChar = Buffer2.allocUnsafe(nb); + } + StringDecoder.prototype.write = function(buf) { + if (buf.length === 0) return ""; + var r5; + var i5; + if (this.lastNeed) { + r5 = this.fillLast(buf); + if (r5 === void 0) return ""; + i5 = this.lastNeed; + this.lastNeed = 0; + } else { + i5 = 0; + } + if (i5 < buf.length) return r5 ? r5 + this.text(buf, i5) : this.text(buf, i5); + return r5 || ""; + }; + StringDecoder.prototype.end = utf8End; + StringDecoder.prototype.text = utf8Text; + StringDecoder.prototype.fillLast = function(buf) { + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); + this.lastNeed -= buf.length; + }; + function utf8CheckByte(byte) { + if (byte <= 127) return 0; + else if (byte >> 5 === 6) return 2; + else if (byte >> 4 === 14) return 3; + else if (byte >> 3 === 30) return 4; + return byte >> 6 === 2 ? -1 : -2; + } + function utf8CheckIncomplete(self2, buf, i5) { + var j5 = buf.length - 1; + if (j5 < i5) return 0; + var nb = utf8CheckByte(buf[j5]); + if (nb >= 0) { + if (nb > 0) self2.lastNeed = nb - 1; + return nb; + } + if (--j5 < i5 || nb === -2) return 0; + nb = utf8CheckByte(buf[j5]); + if (nb >= 0) { + if (nb > 0) self2.lastNeed = nb - 2; + return nb; + } + if (--j5 < i5 || nb === -2) return 0; + nb = utf8CheckByte(buf[j5]); + if (nb >= 0) { + if (nb > 0) { + if (nb === 2) nb = 0; + else self2.lastNeed = nb - 3; + } + return nb; + } + return 0; + } + function utf8CheckExtraBytes(self2, buf, p5) { + if ((buf[0] & 192) !== 128) { + self2.lastNeed = 0; + return "\uFFFD"; + } + if (self2.lastNeed > 1 && buf.length > 1) { + if ((buf[1] & 192) !== 128) { + self2.lastNeed = 1; + return "\uFFFD"; + } + if (self2.lastNeed > 2 && buf.length > 2) { + if ((buf[2] & 192) !== 128) { + self2.lastNeed = 2; + return "\uFFFD"; + } + } + } + } + function utf8FillLast(buf) { + var p5 = this.lastTotal - this.lastNeed; + var r5 = utf8CheckExtraBytes(this, buf, p5); + if (r5 !== void 0) return r5; + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, p5, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, p5, 0, buf.length); + this.lastNeed -= buf.length; + } + function utf8Text(buf, i5) { + var total = utf8CheckIncomplete(this, buf, i5); + if (!this.lastNeed) return buf.toString("utf8", i5); + this.lastTotal = total; + var end = buf.length - (total - this.lastNeed); + buf.copy(this.lastChar, 0, end); + return buf.toString("utf8", i5, end); + } + function utf8End(buf) { + var r5 = buf && buf.length ? this.write(buf) : ""; + if (this.lastNeed) return r5 + "\uFFFD"; + return r5; + } + function utf16Text(buf, i5) { + if ((buf.length - i5) % 2 === 0) { + var r5 = buf.toString("utf16le", i5); + if (r5) { + var c5 = r5.charCodeAt(r5.length - 1); + if (c5 >= 55296 && c5 <= 56319) { + this.lastNeed = 2; + this.lastTotal = 4; + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + return r5.slice(0, -1); + } + } + return r5; + } + this.lastNeed = 1; + this.lastTotal = 2; + this.lastChar[0] = buf[buf.length - 1]; + return buf.toString("utf16le", i5, buf.length - 1); + } + function utf16End(buf) { + var r5 = buf && buf.length ? this.write(buf) : ""; + if (this.lastNeed) { + var end = this.lastTotal - this.lastNeed; + return r5 + this.lastChar.toString("utf16le", 0, end); + } + return r5; + } + function base64Text(buf, i5) { + var n5 = (buf.length - i5) % 3; + if (n5 === 0) return buf.toString("base64", i5); + this.lastNeed = 3 - n5; + this.lastTotal = 3; + if (n5 === 1) { + this.lastChar[0] = buf[buf.length - 1]; + } else { + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + } + return buf.toString("base64", i5, buf.length - n5); + } + function base64End(buf) { + var r5 = buf && buf.length ? this.write(buf) : ""; + if (this.lastNeed) return r5 + this.lastChar.toString("base64", 0, 3 - this.lastNeed); + return r5; + } + function simpleWrite(buf) { + return buf.toString(this.encoding); + } + function simpleEnd(buf) { + return buf && buf.length ? this.write(buf) : ""; + } + } +}); + +// node_modules/.pnpm/readable-stream@3.6.2/node_modules/readable-stream/lib/internal/streams/end-of-stream.js +var require_end_of_stream = __commonJS({ + "node_modules/.pnpm/readable-stream@3.6.2/node_modules/readable-stream/lib/internal/streams/end-of-stream.js"(exports, module) { + "use strict"; + var ERR_STREAM_PREMATURE_CLOSE = require_errors2().codes.ERR_STREAM_PREMATURE_CLOSE; + function once(callback) { + var called = false; + return function() { + if (called) return; + called = true; + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + callback.apply(this, args); + }; + } + function noop5() { + } + function isRequest2(stream) { + return stream.setHeader && typeof stream.abort === "function"; + } + function eos(stream, opts, callback) { + if (typeof opts === "function") return eos(stream, null, opts); + if (!opts) opts = {}; + callback = once(callback || noop5); + var readable = opts.readable || opts.readable !== false && stream.readable; + var writable = opts.writable || opts.writable !== false && stream.writable; + var onlegacyfinish = function onlegacyfinish2() { + if (!stream.writable) onfinish(); + }; + var writableEnded = stream._writableState && stream._writableState.finished; + var onfinish = function onfinish2() { + writable = false; + writableEnded = true; + if (!readable) callback.call(stream); + }; + var readableEnded = stream._readableState && stream._readableState.endEmitted; + var onend = function onend2() { + readable = false; + readableEnded = true; + if (!writable) callback.call(stream); + }; + var onerror = function onerror2(err) { + callback.call(stream, err); + }; + var onclose = function onclose2() { + var err; + if (readable && !readableEnded) { + if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream, err); + } + if (writable && !writableEnded) { + if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream, err); + } + }; + var onrequest = function onrequest2() { + stream.req.on("finish", onfinish); + }; + if (isRequest2(stream)) { + stream.on("complete", onfinish); + stream.on("abort", onclose); + if (stream.req) onrequest(); + else stream.on("request", onrequest); + } else if (writable && !stream._writableState) { + stream.on("end", onlegacyfinish); + stream.on("close", onlegacyfinish); + } + stream.on("end", onend); + stream.on("finish", onfinish); + if (opts.error !== false) stream.on("error", onerror); + stream.on("close", onclose); + return function() { + stream.removeListener("complete", onfinish); + stream.removeListener("abort", onclose); + stream.removeListener("request", onrequest); + if (stream.req) stream.req.removeListener("finish", onfinish); + stream.removeListener("end", onlegacyfinish); + stream.removeListener("close", onlegacyfinish); + stream.removeListener("finish", onfinish); + stream.removeListener("end", onend); + stream.removeListener("error", onerror); + stream.removeListener("close", onclose); + }; + } + module.exports = eos; + } +}); + +// node_modules/.pnpm/readable-stream@3.6.2/node_modules/readable-stream/lib/internal/streams/async_iterator.js +var require_async_iterator = __commonJS({ + "node_modules/.pnpm/readable-stream@3.6.2/node_modules/readable-stream/lib/internal/streams/async_iterator.js"(exports, module) { + "use strict"; + var _Object$setPrototypeO; + function _defineProperty(obj, key, value) { + key = _toPropertyKey(key); + if (key in obj) { + Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true }); + } else { + obj[key] = value; + } + return obj; + } + function _toPropertyKey(arg) { + var key = _toPrimitive(arg, "string"); + return typeof key === "symbol" ? key : String(key); + } + function _toPrimitive(input, hint) { + if (typeof input !== "object" || input === null) return input; + var prim = input[Symbol.toPrimitive]; + if (prim !== void 0) { + var res = prim.call(input, hint || "default"); + if (typeof res !== "object") return res; + throw new TypeError("@@toPrimitive must return a primitive value."); + } + return (hint === "string" ? String : Number)(input); + } + var finished = require_end_of_stream(); + var kLastResolve = /* @__PURE__ */ Symbol("lastResolve"); + var kLastReject = /* @__PURE__ */ Symbol("lastReject"); + var kError = /* @__PURE__ */ Symbol("error"); + var kEnded = /* @__PURE__ */ Symbol("ended"); + var kLastPromise = /* @__PURE__ */ Symbol("lastPromise"); + var kHandlePromise = /* @__PURE__ */ Symbol("handlePromise"); + var kStream = /* @__PURE__ */ Symbol("stream"); + function createIterResult(value, done) { + return { + value, + done + }; + } + function readAndResolve(iter) { + var resolve4 = iter[kLastResolve]; + if (resolve4 !== null) { + var data2 = iter[kStream].read(); + if (data2 !== null) { + iter[kLastPromise] = null; + iter[kLastResolve] = null; + iter[kLastReject] = null; + resolve4(createIterResult(data2, false)); + } + } + } + function onReadable(iter) { + process.nextTick(readAndResolve, iter); + } + function wrapForNext(lastPromise, iter) { + return function(resolve4, reject) { + lastPromise.then(function() { + if (iter[kEnded]) { + resolve4(createIterResult(void 0, true)); + return; + } + iter[kHandlePromise](resolve4, reject); + }, reject); + }; + } + var AsyncIteratorPrototype = Object.getPrototypeOf(function() { + }); + var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = { + get stream() { + return this[kStream]; + }, + next: function next() { + var _this = this; + var error50 = this[kError]; + if (error50 !== null) { + return Promise.reject(error50); + } + if (this[kEnded]) { + return Promise.resolve(createIterResult(void 0, true)); + } + if (this[kStream].destroyed) { + return new Promise(function(resolve4, reject) { + process.nextTick(function() { + if (_this[kError]) { + reject(_this[kError]); + } else { + resolve4(createIterResult(void 0, true)); + } + }); + }); + } + var lastPromise = this[kLastPromise]; + var promise2; + if (lastPromise) { + promise2 = new Promise(wrapForNext(lastPromise, this)); + } else { + var data2 = this[kStream].read(); + if (data2 !== null) { + return Promise.resolve(createIterResult(data2, false)); + } + promise2 = new Promise(this[kHandlePromise]); + } + this[kLastPromise] = promise2; + return promise2; + } + }, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function() { + return this; + }), _defineProperty(_Object$setPrototypeO, "return", function _return() { + var _this2 = this; + return new Promise(function(resolve4, reject) { + _this2[kStream].destroy(null, function(err) { + if (err) { + reject(err); + return; + } + resolve4(createIterResult(void 0, true)); + }); + }); + }), _Object$setPrototypeO), AsyncIteratorPrototype); + var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator2(stream) { + var _Object$create; + var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, { + value: stream, + writable: true + }), _defineProperty(_Object$create, kLastResolve, { + value: null, + writable: true + }), _defineProperty(_Object$create, kLastReject, { + value: null, + writable: true + }), _defineProperty(_Object$create, kError, { + value: null, + writable: true + }), _defineProperty(_Object$create, kEnded, { + value: stream._readableState.endEmitted, + writable: true + }), _defineProperty(_Object$create, kHandlePromise, { + value: function value(resolve4, reject) { + var data2 = iterator[kStream].read(); + if (data2) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + resolve4(createIterResult(data2, false)); + } else { + iterator[kLastResolve] = resolve4; + iterator[kLastReject] = reject; + } + }, + writable: true + }), _Object$create)); + iterator[kLastPromise] = null; + finished(stream, function(err) { + if (err && err.code !== "ERR_STREAM_PREMATURE_CLOSE") { + var reject = iterator[kLastReject]; + if (reject !== null) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + reject(err); + } + iterator[kError] = err; + return; + } + var resolve4 = iterator[kLastResolve]; + if (resolve4 !== null) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + resolve4(createIterResult(void 0, true)); + } + iterator[kEnded] = true; + }); + stream.on("readable", onReadable.bind(null, iterator)); + return iterator; + }; + module.exports = createReadableStreamAsyncIterator; + } +}); + +// node_modules/.pnpm/readable-stream@3.6.2/node_modules/readable-stream/lib/internal/streams/from.js +var require_from = __commonJS({ + "node_modules/.pnpm/readable-stream@3.6.2/node_modules/readable-stream/lib/internal/streams/from.js"(exports, module) { + "use strict"; + function asyncGeneratorStep(gen, resolve4, reject, _next, _throw, key, arg) { + try { + var info2 = gen[key](arg); + var value = info2.value; + } catch (error50) { + reject(error50); + return; + } + if (info2.done) { + resolve4(value); + } else { + Promise.resolve(value).then(_next, _throw); + } + } + function _asyncToGenerator(fn) { + return function() { + var self2 = this, args = arguments; + return new Promise(function(resolve4, reject) { + var gen = fn.apply(self2, args); + function _next(value) { + asyncGeneratorStep(gen, resolve4, reject, _next, _throw, "next", value); + } + function _throw(err) { + asyncGeneratorStep(gen, resolve4, reject, _next, _throw, "throw", err); + } + _next(void 0); + }); + }; + } + function ownKeys2(object2, enumerableOnly) { + var keys = Object.keys(object2); + if (Object.getOwnPropertySymbols) { + var symbols = Object.getOwnPropertySymbols(object2); + enumerableOnly && (symbols = symbols.filter(function(sym) { + return Object.getOwnPropertyDescriptor(object2, sym).enumerable; + })), keys.push.apply(keys, symbols); + } + return keys; + } + function _objectSpread(target) { + for (var i5 = 1; i5 < arguments.length; i5++) { + var source = null != arguments[i5] ? arguments[i5] : {}; + i5 % 2 ? ownKeys2(Object(source), true).forEach(function(key) { + _defineProperty(target, key, source[key]); + }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys2(Object(source)).forEach(function(key) { + Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); + }); + } + return target; + } + function _defineProperty(obj, key, value) { + key = _toPropertyKey(key); + if (key in obj) { + Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true }); + } else { + obj[key] = value; + } + return obj; + } + function _toPropertyKey(arg) { + var key = _toPrimitive(arg, "string"); + return typeof key === "symbol" ? key : String(key); + } + function _toPrimitive(input, hint) { + if (typeof input !== "object" || input === null) return input; + var prim = input[Symbol.toPrimitive]; + if (prim !== void 0) { + var res = prim.call(input, hint || "default"); + if (typeof res !== "object") return res; + throw new TypeError("@@toPrimitive must return a primitive value."); + } + return (hint === "string" ? String : Number)(input); + } + var ERR_INVALID_ARG_TYPE = require_errors2().codes.ERR_INVALID_ARG_TYPE; + function from(Readable3, iterable, opts) { + var iterator; + if (iterable && typeof iterable.next === "function") { + iterator = iterable; + } else if (iterable && iterable[Symbol.asyncIterator]) iterator = iterable[Symbol.asyncIterator](); + else if (iterable && iterable[Symbol.iterator]) iterator = iterable[Symbol.iterator](); + else throw new ERR_INVALID_ARG_TYPE("iterable", ["Iterable"], iterable); + var readable = new Readable3(_objectSpread({ + objectMode: true + }, opts)); + var reading = false; + readable._read = function() { + if (!reading) { + reading = true; + next(); + } + }; + function next() { + return _next2.apply(this, arguments); + } + function _next2() { + _next2 = _asyncToGenerator(function* () { + try { + var _yield$iterator$next = yield iterator.next(), value = _yield$iterator$next.value, done = _yield$iterator$next.done; + if (done) { + readable.push(null); + } else if (readable.push(yield value)) { + next(); + } else { + reading = false; + } + } catch (err) { + readable.destroy(err); + } + }); + return _next2.apply(this, arguments); + } + return readable; + } + module.exports = from; + } +}); + +// node_modules/.pnpm/readable-stream@3.6.2/node_modules/readable-stream/lib/_stream_readable.js +var require_stream_readable = __commonJS({ + "node_modules/.pnpm/readable-stream@3.6.2/node_modules/readable-stream/lib/_stream_readable.js"(exports, module) { + "use strict"; + module.exports = Readable3; + var Duplex; + Readable3.ReadableState = ReadableState; + var EE = __require("events").EventEmitter; + var EElistenerCount = function EElistenerCount2(emitter2, type) { + return emitter2.listeners(type).length; + }; + var Stream3 = require_stream2(); + var Buffer2 = __require("buffer").Buffer; + var OurUint8Array = (typeof global !== "undefined" ? global : typeof window !== "undefined" ? window : typeof self !== "undefined" ? self : {}).Uint8Array || function() { + }; + function _uint8ArrayToBuffer(chunk) { + return Buffer2.from(chunk); + } + function _isUint8Array(obj) { + return Buffer2.isBuffer(obj) || obj instanceof OurUint8Array; + } + var debugUtil = __require("util"); + var debug; + if (debugUtil && debugUtil.debuglog) { + debug = debugUtil.debuglog("stream"); + } else { + debug = function debug2() { + }; + } + var BufferList = require_buffer_list(); + var destroyImpl = require_destroy(); + var _require = require_state(); + var getHighWaterMark = _require.getHighWaterMark; + var _require$codes = require_errors2().codes; + var ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE; + var ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF; + var ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED; + var ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; + var StringDecoder; + var createReadableStreamAsyncIterator; + var from; + require_inherits()(Readable3, Stream3); + var errorOrDestroy = destroyImpl.errorOrDestroy; + var kProxyEvents = ["error", "close", "destroy", "pause", "resume"]; + function prependListener(emitter2, event, fn) { + if (typeof emitter2.prependListener === "function") return emitter2.prependListener(event, fn); + if (!emitter2._events || !emitter2._events[event]) emitter2.on(event, fn); + else if (Array.isArray(emitter2._events[event])) emitter2._events[event].unshift(fn); + else emitter2._events[event] = [fn, emitter2._events[event]]; + } + function ReadableState(options, stream, isDuplex) { + Duplex = Duplex || require_stream_duplex(); + options = options || {}; + if (typeof isDuplex !== "boolean") isDuplex = stream instanceof Duplex; + this.objectMode = !!options.objectMode; + if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + this.highWaterMark = getHighWaterMark(this, options, "readableHighWaterMark", isDuplex); + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; + this.sync = true; + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + this.paused = true; + this.emitClose = options.emitClose !== false; + this.autoDestroy = !!options.autoDestroy; + this.destroyed = false; + this.defaultEncoding = options.defaultEncoding || "utf8"; + this.awaitDrain = 0; + this.readingMore = false; + this.decoder = null; + this.encoding = null; + if (options.encoding) { + if (!StringDecoder) StringDecoder = require_string_decoder().StringDecoder; + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } + } + function Readable3(options) { + Duplex = Duplex || require_stream_duplex(); + if (!(this instanceof Readable3)) return new Readable3(options); + var isDuplex = this instanceof Duplex; + this._readableState = new ReadableState(options, this, isDuplex); + this.readable = true; + if (options) { + if (typeof options.read === "function") this._read = options.read; + if (typeof options.destroy === "function") this._destroy = options.destroy; + } + Stream3.call(this); + } + Object.defineProperty(Readable3.prototype, "destroyed", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get2() { + if (this._readableState === void 0) { + return false; + } + return this._readableState.destroyed; + }, + set: function set2(value) { + if (!this._readableState) { + return; + } + this._readableState.destroyed = value; + } + }); + Readable3.prototype.destroy = destroyImpl.destroy; + Readable3.prototype._undestroy = destroyImpl.undestroy; + Readable3.prototype._destroy = function(err, cb) { + cb(err); + }; + Readable3.prototype.push = function(chunk, encoding) { + var state2 = this._readableState; + var skipChunkCheck; + if (!state2.objectMode) { + if (typeof chunk === "string") { + encoding = encoding || state2.defaultEncoding; + if (encoding !== state2.encoding) { + chunk = Buffer2.from(chunk, encoding); + encoding = ""; + } + skipChunkCheck = true; + } + } else { + skipChunkCheck = true; + } + return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); + }; + Readable3.prototype.unshift = function(chunk) { + return readableAddChunk(this, chunk, null, true, false); + }; + function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { + debug("readableAddChunk", chunk); + var state2 = stream._readableState; + if (chunk === null) { + state2.reading = false; + onEofChunk(stream, state2); + } else { + var er; + if (!skipChunkCheck) er = chunkInvalid(state2, chunk); + if (er) { + errorOrDestroy(stream, er); + } else if (state2.objectMode || chunk && chunk.length > 0) { + if (typeof chunk !== "string" && !state2.objectMode && Object.getPrototypeOf(chunk) !== Buffer2.prototype) { + chunk = _uint8ArrayToBuffer(chunk); + } + if (addToFront) { + if (state2.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT()); + else addChunk(stream, state2, chunk, true); + } else if (state2.ended) { + errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF()); + } else if (state2.destroyed) { + return false; + } else { + state2.reading = false; + if (state2.decoder && !encoding) { + chunk = state2.decoder.write(chunk); + if (state2.objectMode || chunk.length !== 0) addChunk(stream, state2, chunk, false); + else maybeReadMore(stream, state2); + } else { + addChunk(stream, state2, chunk, false); + } + } + } else if (!addToFront) { + state2.reading = false; + maybeReadMore(stream, state2); + } + } + return !state2.ended && (state2.length < state2.highWaterMark || state2.length === 0); + } + function addChunk(stream, state2, chunk, addToFront) { + if (state2.flowing && state2.length === 0 && !state2.sync) { + state2.awaitDrain = 0; + stream.emit("data", chunk); + } else { + state2.length += state2.objectMode ? 1 : chunk.length; + if (addToFront) state2.buffer.unshift(chunk); + else state2.buffer.push(chunk); + if (state2.needReadable) emitReadable(stream); + } + maybeReadMore(stream, state2); + } + function chunkInvalid(state2, chunk) { + var er; + if (!_isUint8Array(chunk) && typeof chunk !== "string" && chunk !== void 0 && !state2.objectMode) { + er = new ERR_INVALID_ARG_TYPE("chunk", ["string", "Buffer", "Uint8Array"], chunk); + } + return er; + } + Readable3.prototype.isPaused = function() { + return this._readableState.flowing === false; + }; + Readable3.prototype.setEncoding = function(enc2) { + if (!StringDecoder) StringDecoder = require_string_decoder().StringDecoder; + var decoder2 = new StringDecoder(enc2); + this._readableState.decoder = decoder2; + this._readableState.encoding = this._readableState.decoder.encoding; + var p5 = this._readableState.buffer.head; + var content = ""; + while (p5 !== null) { + content += decoder2.write(p5.data); + p5 = p5.next; + } + this._readableState.buffer.clear(); + if (content !== "") this._readableState.buffer.push(content); + this._readableState.length = content.length; + return this; + }; + var MAX_HWM = 1073741824; + function computeNewHighWaterMark(n5) { + if (n5 >= MAX_HWM) { + n5 = MAX_HWM; + } else { + n5--; + n5 |= n5 >>> 1; + n5 |= n5 >>> 2; + n5 |= n5 >>> 4; + n5 |= n5 >>> 8; + n5 |= n5 >>> 16; + n5++; + } + return n5; + } + function howMuchToRead(n5, state2) { + if (n5 <= 0 || state2.length === 0 && state2.ended) return 0; + if (state2.objectMode) return 1; + if (n5 !== n5) { + if (state2.flowing && state2.length) return state2.buffer.head.data.length; + else return state2.length; + } + if (n5 > state2.highWaterMark) state2.highWaterMark = computeNewHighWaterMark(n5); + if (n5 <= state2.length) return n5; + if (!state2.ended) { + state2.needReadable = true; + return 0; + } + return state2.length; + } + Readable3.prototype.read = function(n5) { + debug("read", n5); + n5 = parseInt(n5, 10); + var state2 = this._readableState; + var nOrig = n5; + if (n5 !== 0) state2.emittedReadable = false; + if (n5 === 0 && state2.needReadable && ((state2.highWaterMark !== 0 ? state2.length >= state2.highWaterMark : state2.length > 0) || state2.ended)) { + debug("read: emitReadable", state2.length, state2.ended); + if (state2.length === 0 && state2.ended) endReadable(this); + else emitReadable(this); + return null; + } + n5 = howMuchToRead(n5, state2); + if (n5 === 0 && state2.ended) { + if (state2.length === 0) endReadable(this); + return null; + } + var doRead = state2.needReadable; + debug("need readable", doRead); + if (state2.length === 0 || state2.length - n5 < state2.highWaterMark) { + doRead = true; + debug("length less than watermark", doRead); + } + if (state2.ended || state2.reading) { + doRead = false; + debug("reading or ended", doRead); + } else if (doRead) { + debug("do read"); + state2.reading = true; + state2.sync = true; + if (state2.length === 0) state2.needReadable = true; + this._read(state2.highWaterMark); + state2.sync = false; + if (!state2.reading) n5 = howMuchToRead(nOrig, state2); + } + var ret; + if (n5 > 0) ret = fromList(n5, state2); + else ret = null; + if (ret === null) { + state2.needReadable = state2.length <= state2.highWaterMark; + n5 = 0; + } else { + state2.length -= n5; + state2.awaitDrain = 0; + } + if (state2.length === 0) { + if (!state2.ended) state2.needReadable = true; + if (nOrig !== n5 && state2.ended) endReadable(this); + } + if (ret !== null) this.emit("data", ret); + return ret; + }; + function onEofChunk(stream, state2) { + debug("onEofChunk"); + if (state2.ended) return; + if (state2.decoder) { + var chunk = state2.decoder.end(); + if (chunk && chunk.length) { + state2.buffer.push(chunk); + state2.length += state2.objectMode ? 1 : chunk.length; + } + } + state2.ended = true; + if (state2.sync) { + emitReadable(stream); + } else { + state2.needReadable = false; + if (!state2.emittedReadable) { + state2.emittedReadable = true; + emitReadable_(stream); + } + } + } + function emitReadable(stream) { + var state2 = stream._readableState; + debug("emitReadable", state2.needReadable, state2.emittedReadable); + state2.needReadable = false; + if (!state2.emittedReadable) { + debug("emitReadable", state2.flowing); + state2.emittedReadable = true; + process.nextTick(emitReadable_, stream); + } + } + function emitReadable_(stream) { + var state2 = stream._readableState; + debug("emitReadable_", state2.destroyed, state2.length, state2.ended); + if (!state2.destroyed && (state2.length || state2.ended)) { + stream.emit("readable"); + state2.emittedReadable = false; + } + state2.needReadable = !state2.flowing && !state2.ended && state2.length <= state2.highWaterMark; + flow(stream); + } + function maybeReadMore(stream, state2) { + if (!state2.readingMore) { + state2.readingMore = true; + process.nextTick(maybeReadMore_, stream, state2); + } + } + function maybeReadMore_(stream, state2) { + while (!state2.reading && !state2.ended && (state2.length < state2.highWaterMark || state2.flowing && state2.length === 0)) { + var len = state2.length; + debug("maybeReadMore read 0"); + stream.read(0); + if (len === state2.length) + break; + } + state2.readingMore = false; + } + Readable3.prototype._read = function(n5) { + errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED("_read()")); + }; + Readable3.prototype.pipe = function(dest, pipeOpts) { + var src = this; + var state2 = this._readableState; + switch (state2.pipesCount) { + case 0: + state2.pipes = dest; + break; + case 1: + state2.pipes = [state2.pipes, dest]; + break; + default: + state2.pipes.push(dest); + break; + } + state2.pipesCount += 1; + debug("pipe count=%d opts=%j", state2.pipesCount, pipeOpts); + var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; + var endFn = doEnd ? onend : unpipe; + if (state2.endEmitted) process.nextTick(endFn); + else src.once("end", endFn); + dest.on("unpipe", onunpipe); + function onunpipe(readable, unpipeInfo) { + debug("onunpipe"); + if (readable === src) { + if (unpipeInfo && unpipeInfo.hasUnpiped === false) { + unpipeInfo.hasUnpiped = true; + cleanup(); + } + } + } + function onend() { + debug("onend"); + dest.end(); + } + var ondrain = pipeOnDrain(src); + dest.on("drain", ondrain); + var cleanedUp = false; + function cleanup() { + debug("cleanup"); + dest.removeListener("close", onclose); + dest.removeListener("finish", onfinish); + dest.removeListener("drain", ondrain); + dest.removeListener("error", onerror); + dest.removeListener("unpipe", onunpipe); + src.removeListener("end", onend); + src.removeListener("end", unpipe); + src.removeListener("data", ondata); + cleanedUp = true; + if (state2.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } + src.on("data", ondata); + function ondata(chunk) { + debug("ondata"); + var ret = dest.write(chunk); + debug("dest.write", ret); + if (ret === false) { + if ((state2.pipesCount === 1 && state2.pipes === dest || state2.pipesCount > 1 && indexOf(state2.pipes, dest) !== -1) && !cleanedUp) { + debug("false write response, pause", state2.awaitDrain); + state2.awaitDrain++; + } + src.pause(); + } + } + function onerror(er) { + debug("onerror", er); + unpipe(); + dest.removeListener("error", onerror); + if (EElistenerCount(dest, "error") === 0) errorOrDestroy(dest, er); + } + prependListener(dest, "error", onerror); + function onclose() { + dest.removeListener("finish", onfinish); + unpipe(); + } + dest.once("close", onclose); + function onfinish() { + debug("onfinish"); + dest.removeListener("close", onclose); + unpipe(); + } + dest.once("finish", onfinish); + function unpipe() { + debug("unpipe"); + src.unpipe(dest); + } + dest.emit("pipe", src); + if (!state2.flowing) { + debug("pipe resume"); + src.resume(); + } + return dest; + }; + function pipeOnDrain(src) { + return function pipeOnDrainFunctionResult() { + var state2 = src._readableState; + debug("pipeOnDrain", state2.awaitDrain); + if (state2.awaitDrain) state2.awaitDrain--; + if (state2.awaitDrain === 0 && EElistenerCount(src, "data")) { + state2.flowing = true; + flow(src); + } + }; + } + Readable3.prototype.unpipe = function(dest) { + var state2 = this._readableState; + var unpipeInfo = { + hasUnpiped: false + }; + if (state2.pipesCount === 0) return this; + if (state2.pipesCount === 1) { + if (dest && dest !== state2.pipes) return this; + if (!dest) dest = state2.pipes; + state2.pipes = null; + state2.pipesCount = 0; + state2.flowing = false; + if (dest) dest.emit("unpipe", this, unpipeInfo); + return this; + } + if (!dest) { + var dests = state2.pipes; + var len = state2.pipesCount; + state2.pipes = null; + state2.pipesCount = 0; + state2.flowing = false; + for (var i5 = 0; i5 < len; i5++) dests[i5].emit("unpipe", this, { + hasUnpiped: false + }); + return this; + } + var index2 = indexOf(state2.pipes, dest); + if (index2 === -1) return this; + state2.pipes.splice(index2, 1); + state2.pipesCount -= 1; + if (state2.pipesCount === 1) state2.pipes = state2.pipes[0]; + dest.emit("unpipe", this, unpipeInfo); + return this; + }; + Readable3.prototype.on = function(ev, fn) { + var res = Stream3.prototype.on.call(this, ev, fn); + var state2 = this._readableState; + if (ev === "data") { + state2.readableListening = this.listenerCount("readable") > 0; + if (state2.flowing !== false) this.resume(); + } else if (ev === "readable") { + if (!state2.endEmitted && !state2.readableListening) { + state2.readableListening = state2.needReadable = true; + state2.flowing = false; + state2.emittedReadable = false; + debug("on readable", state2.length, state2.reading); + if (state2.length) { + emitReadable(this); + } else if (!state2.reading) { + process.nextTick(nReadingNextTick, this); + } + } + } + return res; + }; + Readable3.prototype.addListener = Readable3.prototype.on; + Readable3.prototype.removeListener = function(ev, fn) { + var res = Stream3.prototype.removeListener.call(this, ev, fn); + if (ev === "readable") { + process.nextTick(updateReadableListening, this); + } + return res; + }; + Readable3.prototype.removeAllListeners = function(ev) { + var res = Stream3.prototype.removeAllListeners.apply(this, arguments); + if (ev === "readable" || ev === void 0) { + process.nextTick(updateReadableListening, this); + } + return res; + }; + function updateReadableListening(self2) { + var state2 = self2._readableState; + state2.readableListening = self2.listenerCount("readable") > 0; + if (state2.resumeScheduled && !state2.paused) { + state2.flowing = true; + } else if (self2.listenerCount("data") > 0) { + self2.resume(); + } + } + function nReadingNextTick(self2) { + debug("readable nexttick read 0"); + self2.read(0); + } + Readable3.prototype.resume = function() { + var state2 = this._readableState; + if (!state2.flowing) { + debug("resume"); + state2.flowing = !state2.readableListening; + resume(this, state2); + } + state2.paused = false; + return this; + }; + function resume(stream, state2) { + if (!state2.resumeScheduled) { + state2.resumeScheduled = true; + process.nextTick(resume_, stream, state2); + } + } + function resume_(stream, state2) { + debug("resume", state2.reading); + if (!state2.reading) { + stream.read(0); + } + state2.resumeScheduled = false; + stream.emit("resume"); + flow(stream); + if (state2.flowing && !state2.reading) stream.read(0); + } + Readable3.prototype.pause = function() { + debug("call pause flowing=%j", this._readableState.flowing); + if (this._readableState.flowing !== false) { + debug("pause"); + this._readableState.flowing = false; + this.emit("pause"); + } + this._readableState.paused = true; + return this; + }; + function flow(stream) { + var state2 = stream._readableState; + debug("flow", state2.flowing); + while (state2.flowing && stream.read() !== null) ; + } + Readable3.prototype.wrap = function(stream) { + var _this = this; + var state2 = this._readableState; + var paused = false; + stream.on("end", function() { + debug("wrapped end"); + if (state2.decoder && !state2.ended) { + var chunk = state2.decoder.end(); + if (chunk && chunk.length) _this.push(chunk); + } + _this.push(null); + }); + stream.on("data", function(chunk) { + debug("wrapped data"); + if (state2.decoder) chunk = state2.decoder.write(chunk); + if (state2.objectMode && (chunk === null || chunk === void 0)) return; + else if (!state2.objectMode && (!chunk || !chunk.length)) return; + var ret = _this.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); + for (var i5 in stream) { + if (this[i5] === void 0 && typeof stream[i5] === "function") { + this[i5] = /* @__PURE__ */ (function methodWrap(method) { + return function methodWrapReturnFunction() { + return stream[method].apply(stream, arguments); + }; + })(i5); + } + } + for (var n5 = 0; n5 < kProxyEvents.length; n5++) { + stream.on(kProxyEvents[n5], this.emit.bind(this, kProxyEvents[n5])); + } + this._read = function(n6) { + debug("wrapped _read", n6); + if (paused) { + paused = false; + stream.resume(); + } + }; + return this; + }; + if (typeof Symbol === "function") { + Readable3.prototype[Symbol.asyncIterator] = function() { + if (createReadableStreamAsyncIterator === void 0) { + createReadableStreamAsyncIterator = require_async_iterator(); + } + return createReadableStreamAsyncIterator(this); + }; + } + Object.defineProperty(Readable3.prototype, "readableHighWaterMark", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get2() { + return this._readableState.highWaterMark; + } + }); + Object.defineProperty(Readable3.prototype, "readableBuffer", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get2() { + return this._readableState && this._readableState.buffer; + } + }); + Object.defineProperty(Readable3.prototype, "readableFlowing", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get2() { + return this._readableState.flowing; + }, + set: function set2(state2) { + if (this._readableState) { + this._readableState.flowing = state2; + } + } + }); + Readable3._fromList = fromList; + Object.defineProperty(Readable3.prototype, "readableLength", { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get2() { + return this._readableState.length; + } + }); + function fromList(n5, state2) { + if (state2.length === 0) return null; + var ret; + if (state2.objectMode) ret = state2.buffer.shift(); + else if (!n5 || n5 >= state2.length) { + if (state2.decoder) ret = state2.buffer.join(""); + else if (state2.buffer.length === 1) ret = state2.buffer.first(); + else ret = state2.buffer.concat(state2.length); + state2.buffer.clear(); + } else { + ret = state2.buffer.consume(n5, state2.decoder); + } + return ret; + } + function endReadable(stream) { + var state2 = stream._readableState; + debug("endReadable", state2.endEmitted); + if (!state2.endEmitted) { + state2.ended = true; + process.nextTick(endReadableNT, state2, stream); + } + } + function endReadableNT(state2, stream) { + debug("endReadableNT", state2.endEmitted, state2.length); + if (!state2.endEmitted && state2.length === 0) { + state2.endEmitted = true; + stream.readable = false; + stream.emit("end"); + if (state2.autoDestroy) { + var wState = stream._writableState; + if (!wState || wState.autoDestroy && wState.finished) { + stream.destroy(); + } + } + } + } + if (typeof Symbol === "function") { + Readable3.from = function(iterable, opts) { + if (from === void 0) { + from = require_from(); + } + return from(Readable3, iterable, opts); + }; + } + function indexOf(xs, x5) { + for (var i5 = 0, l5 = xs.length; i5 < l5; i5++) { + if (xs[i5] === x5) return i5; + } + return -1; + } + } +}); + +// node_modules/.pnpm/readable-stream@3.6.2/node_modules/readable-stream/lib/_stream_transform.js +var require_stream_transform = __commonJS({ + "node_modules/.pnpm/readable-stream@3.6.2/node_modules/readable-stream/lib/_stream_transform.js"(exports, module) { + "use strict"; + module.exports = Transform; + var _require$codes = require_errors2().codes; + var ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED; + var ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK; + var ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING; + var ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0; + var Duplex = require_stream_duplex(); + require_inherits()(Transform, Duplex); + function afterTransform(er, data2) { + var ts = this._transformState; + ts.transforming = false; + var cb = ts.writecb; + if (cb === null) { + return this.emit("error", new ERR_MULTIPLE_CALLBACK()); + } + ts.writechunk = null; + ts.writecb = null; + if (data2 != null) + this.push(data2); + cb(er); + var rs = this._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + this._read(rs.highWaterMark); + } + } + function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); + Duplex.call(this, options); + this._transformState = { + afterTransform: afterTransform.bind(this), + needTransform: false, + transforming: false, + writecb: null, + writechunk: null, + writeencoding: null + }; + this._readableState.needReadable = true; + this._readableState.sync = false; + if (options) { + if (typeof options.transform === "function") this._transform = options.transform; + if (typeof options.flush === "function") this._flush = options.flush; + } + this.on("prefinish", prefinish); + } + function prefinish() { + var _this = this; + if (typeof this._flush === "function" && !this._readableState.destroyed) { + this._flush(function(er, data2) { + done(_this, er, data2); + }); + } else { + done(this, null, null); + } + } + Transform.prototype.push = function(chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); + }; + Transform.prototype._transform = function(chunk, encoding, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED("_transform()")); + }; + Transform.prototype._write = function(chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } + }; + Transform.prototype._read = function(n5) { + var ts = this._transformState; + if (ts.writechunk !== null && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + ts.needTransform = true; + } + }; + Transform.prototype._destroy = function(err, cb) { + Duplex.prototype._destroy.call(this, err, function(err2) { + cb(err2); + }); + }; + function done(stream, er, data2) { + if (er) return stream.emit("error", er); + if (data2 != null) + stream.push(data2); + if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0(); + if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING(); + return stream.push(null); + } + } +}); + +// node_modules/.pnpm/readable-stream@3.6.2/node_modules/readable-stream/lib/_stream_passthrough.js +var require_stream_passthrough = __commonJS({ + "node_modules/.pnpm/readable-stream@3.6.2/node_modules/readable-stream/lib/_stream_passthrough.js"(exports, module) { + "use strict"; + module.exports = PassThrough; + var Transform = require_stream_transform(); + require_inherits()(PassThrough, Transform); + function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + Transform.call(this, options); + } + PassThrough.prototype._transform = function(chunk, encoding, cb) { + cb(null, chunk); + }; + } +}); + +// node_modules/.pnpm/readable-stream@3.6.2/node_modules/readable-stream/lib/internal/streams/pipeline.js +var require_pipeline = __commonJS({ + "node_modules/.pnpm/readable-stream@3.6.2/node_modules/readable-stream/lib/internal/streams/pipeline.js"(exports, module) { + "use strict"; + var eos; + function once(callback) { + var called = false; + return function() { + if (called) return; + called = true; + callback.apply(void 0, arguments); + }; + } + var _require$codes = require_errors2().codes; + var ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS; + var ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; + function noop5(err) { + if (err) throw err; + } + function isRequest2(stream) { + return stream.setHeader && typeof stream.abort === "function"; + } + function destroyer(stream, reading, writing, callback) { + callback = once(callback); + var closed = false; + stream.on("close", function() { + closed = true; + }); + if (eos === void 0) eos = require_end_of_stream(); + eos(stream, { + readable: reading, + writable: writing + }, function(err) { + if (err) return callback(err); + closed = true; + callback(); + }); + var destroyed = false; + return function(err) { + if (closed) return; + if (destroyed) return; + destroyed = true; + if (isRequest2(stream)) return stream.abort(); + if (typeof stream.destroy === "function") return stream.destroy(); + callback(err || new ERR_STREAM_DESTROYED("pipe")); + }; + } + function call(fn) { + fn(); + } + function pipe2(from, to) { + return from.pipe(to); + } + function popCallback(streams) { + if (!streams.length) return noop5; + if (typeof streams[streams.length - 1] !== "function") return noop5; + return streams.pop(); + } + function pipeline() { + for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) { + streams[_key] = arguments[_key]; + } + var callback = popCallback(streams); + if (Array.isArray(streams[0])) streams = streams[0]; + if (streams.length < 2) { + throw new ERR_MISSING_ARGS("streams"); + } + var error50; + var destroys = streams.map(function(stream, i5) { + var reading = i5 < streams.length - 1; + var writing = i5 > 0; + return destroyer(stream, reading, writing, function(err) { + if (!error50) error50 = err; + if (err) destroys.forEach(call); + if (reading) return; + destroys.forEach(call); + callback(error50); + }); + }); + return streams.reduce(pipe2); + } + module.exports = pipeline; + } +}); + +// node_modules/.pnpm/readable-stream@3.6.2/node_modules/readable-stream/readable.js +var require_readable = __commonJS({ + "node_modules/.pnpm/readable-stream@3.6.2/node_modules/readable-stream/readable.js"(exports, module) { + var Stream3 = __require("stream"); + if (process.env.READABLE_STREAM === "disable" && Stream3) { + module.exports = Stream3.Readable; + Object.assign(module.exports, Stream3); + module.exports.Stream = Stream3; + } else { + exports = module.exports = require_stream_readable(); + exports.Stream = Stream3 || exports; + exports.Readable = exports; + exports.Writable = require_stream_writable(); + exports.Duplex = require_stream_duplex(); + exports.Transform = require_stream_transform(); + exports.PassThrough = require_stream_passthrough(); + exports.finished = require_end_of_stream(); + exports.pipeline = require_pipeline(); + } + } +}); + +// node_modules/.pnpm/buffer-from@1.1.2/node_modules/buffer-from/index.js +var require_buffer_from = __commonJS({ + "node_modules/.pnpm/buffer-from@1.1.2/node_modules/buffer-from/index.js"(exports, module) { + var toString = Object.prototype.toString; + var isModern = typeof Buffer !== "undefined" && typeof Buffer.alloc === "function" && typeof Buffer.allocUnsafe === "function" && typeof Buffer.from === "function"; + function isArrayBuffer(input) { + return toString.call(input).slice(8, -1) === "ArrayBuffer"; + } + function fromArrayBuffer(obj, byteOffset, length) { + byteOffset >>>= 0; + var maxLength = obj.byteLength - byteOffset; + if (maxLength < 0) { + throw new RangeError("'offset' is out of bounds"); + } + if (length === void 0) { + length = maxLength; + } else { + length >>>= 0; + if (length > maxLength) { + throw new RangeError("'length' is out of bounds"); + } + } + return isModern ? Buffer.from(obj.slice(byteOffset, byteOffset + length)) : new Buffer(new Uint8Array(obj.slice(byteOffset, byteOffset + length))); + } + function fromString(string4, encoding) { + if (typeof encoding !== "string" || encoding === "") { + encoding = "utf8"; + } + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding'); + } + return isModern ? Buffer.from(string4, encoding) : new Buffer(string4, encoding); + } + function bufferFrom(value, encodingOrOffset, length) { + if (typeof value === "number") { + throw new TypeError('"value" argument must not be a number'); + } + if (isArrayBuffer(value)) { + return fromArrayBuffer(value, encodingOrOffset, length); + } + if (typeof value === "string") { + return fromString(value, encodingOrOffset); + } + return isModern ? Buffer.from(value) : new Buffer(value); + } + module.exports = bufferFrom; + } +}); + +// node_modules/.pnpm/typedarray@0.0.6/node_modules/typedarray/index.js +var require_typedarray = __commonJS({ + "node_modules/.pnpm/typedarray@0.0.6/node_modules/typedarray/index.js"(exports) { + var undefined2 = void 0; + var MAX_ARRAY_LENGTH = 1e5; + var ECMAScript = /* @__PURE__ */ (function() { + var opts = Object.prototype.toString, ophop = Object.prototype.hasOwnProperty; + return { + // Class returns internal [[Class]] property, used to avoid cross-frame instanceof issues: + Class: function(v5) { + return opts.call(v5).replace(/^\[object *|\]$/g, ""); + }, + HasProperty: function(o5, p5) { + return p5 in o5; + }, + HasOwnProperty: function(o5, p5) { + return ophop.call(o5, p5); + }, + IsCallable: function(o5) { + return typeof o5 === "function"; + }, + ToInt32: function(v5) { + return v5 >> 0; + }, + ToUint32: function(v5) { + return v5 >>> 0; + } + }; + })(); + var LN2 = Math.LN2; + var abs = Math.abs; + var floor = Math.floor; + var log2 = Math.log; + var min = Math.min; + var pow = Math.pow; + var round = Math.round; + function configureProperties(obj) { + if (getOwnPropNames && defineProp) { + var props = getOwnPropNames(obj), i5; + for (i5 = 0; i5 < props.length; i5 += 1) { + defineProp(obj, props[i5], { + value: obj[props[i5]], + writable: false, + enumerable: false, + configurable: false + }); + } + } + } + var defineProp; + if (Object.defineProperty && (function() { + try { + Object.defineProperty({}, "x", {}); + return true; + } catch (e5) { + return false; + } + })()) { + defineProp = Object.defineProperty; + } else { + defineProp = function(o5, p5, desc3) { + if (!o5 === Object(o5)) throw new TypeError("Object.defineProperty called on non-object"); + if (ECMAScript.HasProperty(desc3, "get") && Object.prototype.__defineGetter__) { + Object.prototype.__defineGetter__.call(o5, p5, desc3.get); + } + if (ECMAScript.HasProperty(desc3, "set") && Object.prototype.__defineSetter__) { + Object.prototype.__defineSetter__.call(o5, p5, desc3.set); + } + if (ECMAScript.HasProperty(desc3, "value")) { + o5[p5] = desc3.value; + } + return o5; + }; + } + var getOwnPropNames = Object.getOwnPropertyNames || function(o5) { + if (o5 !== Object(o5)) throw new TypeError("Object.getOwnPropertyNames called on non-object"); + var props = [], p5; + for (p5 in o5) { + if (ECMAScript.HasOwnProperty(o5, p5)) { + props.push(p5); + } + } + return props; + }; + function makeArrayAccessors(obj) { + if (!defineProp) { + return; + } + if (obj.length > MAX_ARRAY_LENGTH) throw new RangeError("Array too large for polyfill"); + function makeArrayAccessor(index2) { + defineProp(obj, index2, { + "get": function() { + return obj._getter(index2); + }, + "set": function(v5) { + obj._setter(index2, v5); + }, + enumerable: true, + configurable: false + }); + } + var i5; + for (i5 = 0; i5 < obj.length; i5 += 1) { + makeArrayAccessor(i5); + } + } + function as_signed(value, bits) { + var s5 = 32 - bits; + return value << s5 >> s5; + } + function as_unsigned(value, bits) { + var s5 = 32 - bits; + return value << s5 >>> s5; + } + function packI8(n5) { + return [n5 & 255]; + } + function unpackI8(bytes) { + return as_signed(bytes[0], 8); + } + function packU8(n5) { + return [n5 & 255]; + } + function unpackU8(bytes) { + return as_unsigned(bytes[0], 8); + } + function packU8Clamped(n5) { + n5 = round(Number(n5)); + return [n5 < 0 ? 0 : n5 > 255 ? 255 : n5 & 255]; + } + function packI16(n5) { + return [n5 >> 8 & 255, n5 & 255]; + } + function unpackI16(bytes) { + return as_signed(bytes[0] << 8 | bytes[1], 16); + } + function packU16(n5) { + return [n5 >> 8 & 255, n5 & 255]; + } + function unpackU16(bytes) { + return as_unsigned(bytes[0] << 8 | bytes[1], 16); + } + function packI32(n5) { + return [n5 >> 24 & 255, n5 >> 16 & 255, n5 >> 8 & 255, n5 & 255]; + } + function unpackI32(bytes) { + return as_signed(bytes[0] << 24 | bytes[1] << 16 | bytes[2] << 8 | bytes[3], 32); + } + function packU32(n5) { + return [n5 >> 24 & 255, n5 >> 16 & 255, n5 >> 8 & 255, n5 & 255]; + } + function unpackU32(bytes) { + return as_unsigned(bytes[0] << 24 | bytes[1] << 16 | bytes[2] << 8 | bytes[3], 32); + } + function packIEEE754(v5, ebits, fbits) { + var bias = (1 << ebits - 1) - 1, s5, e5, f5, ln, i5, bits, str, bytes; + function roundToEven(n5) { + var w5 = floor(n5), f6 = n5 - w5; + if (f6 < 0.5) + return w5; + if (f6 > 0.5) + return w5 + 1; + return w5 % 2 ? w5 + 1 : w5; + } + if (v5 !== v5) { + e5 = (1 << ebits) - 1; + f5 = pow(2, fbits - 1); + s5 = 0; + } else if (v5 === Infinity || v5 === -Infinity) { + e5 = (1 << ebits) - 1; + f5 = 0; + s5 = v5 < 0 ? 1 : 0; + } else if (v5 === 0) { + e5 = 0; + f5 = 0; + s5 = 1 / v5 === -Infinity ? 1 : 0; + } else { + s5 = v5 < 0; + v5 = abs(v5); + if (v5 >= pow(2, 1 - bias)) { + e5 = min(floor(log2(v5) / LN2), 1023); + f5 = roundToEven(v5 / pow(2, e5) * pow(2, fbits)); + if (f5 / pow(2, fbits) >= 2) { + e5 = e5 + 1; + f5 = 1; + } + if (e5 > bias) { + e5 = (1 << ebits) - 1; + f5 = 0; + } else { + e5 = e5 + bias; + f5 = f5 - pow(2, fbits); + } + } else { + e5 = 0; + f5 = roundToEven(v5 / pow(2, 1 - bias - fbits)); + } + } + bits = []; + for (i5 = fbits; i5; i5 -= 1) { + bits.push(f5 % 2 ? 1 : 0); + f5 = floor(f5 / 2); + } + for (i5 = ebits; i5; i5 -= 1) { + bits.push(e5 % 2 ? 1 : 0); + e5 = floor(e5 / 2); + } + bits.push(s5 ? 1 : 0); + bits.reverse(); + str = bits.join(""); + bytes = []; + while (str.length) { + bytes.push(parseInt(str.substring(0, 8), 2)); + str = str.substring(8); + } + return bytes; + } + function unpackIEEE754(bytes, ebits, fbits) { + var bits = [], i5, j5, b6, str, bias, s5, e5, f5; + for (i5 = bytes.length; i5; i5 -= 1) { + b6 = bytes[i5 - 1]; + for (j5 = 8; j5; j5 -= 1) { + bits.push(b6 % 2 ? 1 : 0); + b6 = b6 >> 1; + } + } + bits.reverse(); + str = bits.join(""); + bias = (1 << ebits - 1) - 1; + s5 = parseInt(str.substring(0, 1), 2) ? -1 : 1; + e5 = parseInt(str.substring(1, 1 + ebits), 2); + f5 = parseInt(str.substring(1 + ebits), 2); + if (e5 === (1 << ebits) - 1) { + return f5 !== 0 ? NaN : s5 * Infinity; + } else if (e5 > 0) { + return s5 * pow(2, e5 - bias) * (1 + f5 / pow(2, fbits)); + } else if (f5 !== 0) { + return s5 * pow(2, -(bias - 1)) * (f5 / pow(2, fbits)); + } else { + return s5 < 0 ? -0 : 0; + } + } + function unpackF64(b6) { + return unpackIEEE754(b6, 11, 52); + } + function packF64(v5) { + return packIEEE754(v5, 11, 52); + } + function unpackF32(b6) { + return unpackIEEE754(b6, 8, 23); + } + function packF32(v5) { + return packIEEE754(v5, 8, 23); + } + (function() { + var ArrayBuffer2 = function ArrayBuffer3(length) { + length = ECMAScript.ToInt32(length); + if (length < 0) throw new RangeError("ArrayBuffer size is not a small enough positive integer"); + this.byteLength = length; + this._bytes = []; + this._bytes.length = length; + var i5; + for (i5 = 0; i5 < this.byteLength; i5 += 1) { + this._bytes[i5] = 0; + } + configureProperties(this); + }; + exports.ArrayBuffer = exports.ArrayBuffer || ArrayBuffer2; + var ArrayBufferView = function ArrayBufferView2() { + }; + function makeConstructor(bytesPerElement, pack, unpack) { + var ctor; + ctor = function(buffer2, byteOffset, length) { + var array2, sequence, i5, s5; + if (!arguments.length || typeof arguments[0] === "number") { + this.length = ECMAScript.ToInt32(arguments[0]); + if (length < 0) throw new RangeError("ArrayBufferView size is not a small enough positive integer"); + this.byteLength = this.length * this.BYTES_PER_ELEMENT; + this.buffer = new ArrayBuffer2(this.byteLength); + this.byteOffset = 0; + } else if (typeof arguments[0] === "object" && arguments[0].constructor === ctor) { + array2 = arguments[0]; + this.length = array2.length; + this.byteLength = this.length * this.BYTES_PER_ELEMENT; + this.buffer = new ArrayBuffer2(this.byteLength); + this.byteOffset = 0; + for (i5 = 0; i5 < this.length; i5 += 1) { + this._setter(i5, array2._getter(i5)); + } + } else if (typeof arguments[0] === "object" && !(arguments[0] instanceof ArrayBuffer2 || ECMAScript.Class(arguments[0]) === "ArrayBuffer")) { + sequence = arguments[0]; + this.length = ECMAScript.ToUint32(sequence.length); + this.byteLength = this.length * this.BYTES_PER_ELEMENT; + this.buffer = new ArrayBuffer2(this.byteLength); + this.byteOffset = 0; + for (i5 = 0; i5 < this.length; i5 += 1) { + s5 = sequence[i5]; + this._setter(i5, Number(s5)); + } + } else if (typeof arguments[0] === "object" && (arguments[0] instanceof ArrayBuffer2 || ECMAScript.Class(arguments[0]) === "ArrayBuffer")) { + this.buffer = buffer2; + this.byteOffset = ECMAScript.ToUint32(byteOffset); + if (this.byteOffset > this.buffer.byteLength) { + throw new RangeError("byteOffset out of range"); + } + if (this.byteOffset % this.BYTES_PER_ELEMENT) { + throw new RangeError("ArrayBuffer length minus the byteOffset is not a multiple of the element size."); + } + if (arguments.length < 3) { + this.byteLength = this.buffer.byteLength - this.byteOffset; + if (this.byteLength % this.BYTES_PER_ELEMENT) { + throw new RangeError("length of buffer minus byteOffset not a multiple of the element size"); + } + this.length = this.byteLength / this.BYTES_PER_ELEMENT; + } else { + this.length = ECMAScript.ToUint32(length); + this.byteLength = this.length * this.BYTES_PER_ELEMENT; + } + if (this.byteOffset + this.byteLength > this.buffer.byteLength) { + throw new RangeError("byteOffset and length reference an area beyond the end of the buffer"); + } + } else { + throw new TypeError("Unexpected argument type(s)"); + } + this.constructor = ctor; + configureProperties(this); + makeArrayAccessors(this); + }; + ctor.prototype = new ArrayBufferView(); + ctor.prototype.BYTES_PER_ELEMENT = bytesPerElement; + ctor.prototype._pack = pack; + ctor.prototype._unpack = unpack; + ctor.BYTES_PER_ELEMENT = bytesPerElement; + ctor.prototype._getter = function(index2) { + if (arguments.length < 1) throw new SyntaxError("Not enough arguments"); + index2 = ECMAScript.ToUint32(index2); + if (index2 >= this.length) { + return undefined2; + } + var bytes = [], i5, o5; + for (i5 = 0, o5 = this.byteOffset + index2 * this.BYTES_PER_ELEMENT; i5 < this.BYTES_PER_ELEMENT; i5 += 1, o5 += 1) { + bytes.push(this.buffer._bytes[o5]); + } + return this._unpack(bytes); + }; + ctor.prototype.get = ctor.prototype._getter; + ctor.prototype._setter = function(index2, value) { + if (arguments.length < 2) throw new SyntaxError("Not enough arguments"); + index2 = ECMAScript.ToUint32(index2); + if (index2 >= this.length) { + return undefined2; + } + var bytes = this._pack(value), i5, o5; + for (i5 = 0, o5 = this.byteOffset + index2 * this.BYTES_PER_ELEMENT; i5 < this.BYTES_PER_ELEMENT; i5 += 1, o5 += 1) { + this.buffer._bytes[o5] = bytes[i5]; + } + }; + ctor.prototype.set = function(index2, value) { + if (arguments.length < 1) throw new SyntaxError("Not enough arguments"); + var array2, sequence, offset, len, i5, s5, d5, byteOffset, byteLength, tmp; + if (typeof arguments[0] === "object" && arguments[0].constructor === this.constructor) { + array2 = arguments[0]; + offset = ECMAScript.ToUint32(arguments[1]); + if (offset + array2.length > this.length) { + throw new RangeError("Offset plus length of array is out of range"); + } + byteOffset = this.byteOffset + offset * this.BYTES_PER_ELEMENT; + byteLength = array2.length * this.BYTES_PER_ELEMENT; + if (array2.buffer === this.buffer) { + tmp = []; + for (i5 = 0, s5 = array2.byteOffset; i5 < byteLength; i5 += 1, s5 += 1) { + tmp[i5] = array2.buffer._bytes[s5]; + } + for (i5 = 0, d5 = byteOffset; i5 < byteLength; i5 += 1, d5 += 1) { + this.buffer._bytes[d5] = tmp[i5]; + } + } else { + for (i5 = 0, s5 = array2.byteOffset, d5 = byteOffset; i5 < byteLength; i5 += 1, s5 += 1, d5 += 1) { + this.buffer._bytes[d5] = array2.buffer._bytes[s5]; + } + } + } else if (typeof arguments[0] === "object" && typeof arguments[0].length !== "undefined") { + sequence = arguments[0]; + len = ECMAScript.ToUint32(sequence.length); + offset = ECMAScript.ToUint32(arguments[1]); + if (offset + len > this.length) { + throw new RangeError("Offset plus length of array is out of range"); + } + for (i5 = 0; i5 < len; i5 += 1) { + s5 = sequence[i5]; + this._setter(offset + i5, Number(s5)); + } + } else { + throw new TypeError("Unexpected argument type(s)"); + } + }; + ctor.prototype.subarray = function(start, end) { + function clamp(v5, min2, max) { + return v5 < min2 ? min2 : v5 > max ? max : v5; + } + start = ECMAScript.ToInt32(start); + end = ECMAScript.ToInt32(end); + if (arguments.length < 1) { + start = 0; + } + if (arguments.length < 2) { + end = this.length; + } + if (start < 0) { + start = this.length + start; + } + if (end < 0) { + end = this.length + end; + } + start = clamp(start, 0, this.length); + end = clamp(end, 0, this.length); + var len = end - start; + if (len < 0) { + len = 0; + } + return new this.constructor( + this.buffer, + this.byteOffset + start * this.BYTES_PER_ELEMENT, + len + ); + }; + return ctor; + } + var Int8Array2 = makeConstructor(1, packI8, unpackI8); + var Uint8Array2 = makeConstructor(1, packU8, unpackU8); + var Uint8ClampedArray2 = makeConstructor(1, packU8Clamped, unpackU8); + var Int16Array2 = makeConstructor(2, packI16, unpackI16); + var Uint16Array2 = makeConstructor(2, packU16, unpackU16); + var Int32Array2 = makeConstructor(4, packI32, unpackI32); + var Uint32Array2 = makeConstructor(4, packU32, unpackU32); + var Float32Array2 = makeConstructor(4, packF32, unpackF32); + var Float64Array2 = makeConstructor(8, packF64, unpackF64); + exports.Int8Array = exports.Int8Array || Int8Array2; + exports.Uint8Array = exports.Uint8Array || Uint8Array2; + exports.Uint8ClampedArray = exports.Uint8ClampedArray || Uint8ClampedArray2; + exports.Int16Array = exports.Int16Array || Int16Array2; + exports.Uint16Array = exports.Uint16Array || Uint16Array2; + exports.Int32Array = exports.Int32Array || Int32Array2; + exports.Uint32Array = exports.Uint32Array || Uint32Array2; + exports.Float32Array = exports.Float32Array || Float32Array2; + exports.Float64Array = exports.Float64Array || Float64Array2; + })(); + (function() { + function r5(array2, index2) { + return ECMAScript.IsCallable(array2.get) ? array2.get(index2) : array2[index2]; + } + var IS_BIG_ENDIAN = (function() { + var u16array = new exports.Uint16Array([4660]), u8array = new exports.Uint8Array(u16array.buffer); + return r5(u8array, 0) === 18; + })(); + var DataView2 = function DataView3(buffer2, byteOffset, byteLength) { + if (arguments.length === 0) { + buffer2 = new exports.ArrayBuffer(0); + } else if (!(buffer2 instanceof exports.ArrayBuffer || ECMAScript.Class(buffer2) === "ArrayBuffer")) { + throw new TypeError("TypeError"); + } + this.buffer = buffer2 || new exports.ArrayBuffer(0); + this.byteOffset = ECMAScript.ToUint32(byteOffset); + if (this.byteOffset > this.buffer.byteLength) { + throw new RangeError("byteOffset out of range"); + } + if (arguments.length < 3) { + this.byteLength = this.buffer.byteLength - this.byteOffset; + } else { + this.byteLength = ECMAScript.ToUint32(byteLength); + } + if (this.byteOffset + this.byteLength > this.buffer.byteLength) { + throw new RangeError("byteOffset and length reference an area beyond the end of the buffer"); + } + configureProperties(this); + }; + function makeGetter(arrayType2) { + return function(byteOffset, littleEndian) { + byteOffset = ECMAScript.ToUint32(byteOffset); + if (byteOffset + arrayType2.BYTES_PER_ELEMENT > this.byteLength) { + throw new RangeError("Array index out of range"); + } + byteOffset += this.byteOffset; + var uint8Array = new exports.Uint8Array(this.buffer, byteOffset, arrayType2.BYTES_PER_ELEMENT), bytes = [], i5; + for (i5 = 0; i5 < arrayType2.BYTES_PER_ELEMENT; i5 += 1) { + bytes.push(r5(uint8Array, i5)); + } + if (Boolean(littleEndian) === Boolean(IS_BIG_ENDIAN)) { + bytes.reverse(); + } + return r5(new arrayType2(new exports.Uint8Array(bytes).buffer), 0); + }; + } + DataView2.prototype.getUint8 = makeGetter(exports.Uint8Array); + DataView2.prototype.getInt8 = makeGetter(exports.Int8Array); + DataView2.prototype.getUint16 = makeGetter(exports.Uint16Array); + DataView2.prototype.getInt16 = makeGetter(exports.Int16Array); + DataView2.prototype.getUint32 = makeGetter(exports.Uint32Array); + DataView2.prototype.getInt32 = makeGetter(exports.Int32Array); + DataView2.prototype.getFloat32 = makeGetter(exports.Float32Array); + DataView2.prototype.getFloat64 = makeGetter(exports.Float64Array); + function makeSetter(arrayType2) { + return function(byteOffset, value, littleEndian) { + byteOffset = ECMAScript.ToUint32(byteOffset); + if (byteOffset + arrayType2.BYTES_PER_ELEMENT > this.byteLength) { + throw new RangeError("Array index out of range"); + } + var typeArray = new arrayType2([value]), byteArray = new exports.Uint8Array(typeArray.buffer), bytes = [], i5, byteView; + for (i5 = 0; i5 < arrayType2.BYTES_PER_ELEMENT; i5 += 1) { + bytes.push(r5(byteArray, i5)); + } + if (Boolean(littleEndian) === Boolean(IS_BIG_ENDIAN)) { + bytes.reverse(); + } + byteView = new exports.Uint8Array(this.buffer, byteOffset, arrayType2.BYTES_PER_ELEMENT); + byteView.set(bytes); + }; + } + DataView2.prototype.setUint8 = makeSetter(exports.Uint8Array); + DataView2.prototype.setInt8 = makeSetter(exports.Int8Array); + DataView2.prototype.setUint16 = makeSetter(exports.Uint16Array); + DataView2.prototype.setInt16 = makeSetter(exports.Int16Array); + DataView2.prototype.setUint32 = makeSetter(exports.Uint32Array); + DataView2.prototype.setInt32 = makeSetter(exports.Int32Array); + DataView2.prototype.setFloat32 = makeSetter(exports.Float32Array); + DataView2.prototype.setFloat64 = makeSetter(exports.Float64Array); + exports.DataView = exports.DataView || DataView2; + })(); + } +}); + +// node_modules/.pnpm/concat-stream@2.0.0/node_modules/concat-stream/index.js +var require_concat_stream = __commonJS({ + "node_modules/.pnpm/concat-stream@2.0.0/node_modules/concat-stream/index.js"(exports, module) { + var Writable = require_readable().Writable; + var inherits = require_inherits(); + var bufferFrom = require_buffer_from(); + if (typeof Uint8Array === "undefined") { + U8 = require_typedarray().Uint8Array; + } else { + U8 = Uint8Array; + } + var U8; + function ConcatStream(opts, cb) { + if (!(this instanceof ConcatStream)) return new ConcatStream(opts, cb); + if (typeof opts === "function") { + cb = opts; + opts = {}; + } + if (!opts) opts = {}; + var encoding = opts.encoding; + var shouldInferEncoding = false; + if (!encoding) { + shouldInferEncoding = true; + } else { + encoding = String(encoding).toLowerCase(); + if (encoding === "u8" || encoding === "uint8") { + encoding = "uint8array"; + } + } + Writable.call(this, { objectMode: true }); + this.encoding = encoding; + this.shouldInferEncoding = shouldInferEncoding; + if (cb) this.on("finish", function() { + cb(this.getBody()); + }); + this.body = []; + } + module.exports = ConcatStream; + inherits(ConcatStream, Writable); + ConcatStream.prototype._write = function(chunk, enc2, next) { + this.body.push(chunk); + next(); + }; + ConcatStream.prototype.inferEncoding = function(buff) { + var firstBuffer = buff === void 0 ? this.body[0] : buff; + if (Buffer.isBuffer(firstBuffer)) return "buffer"; + if (typeof Uint8Array !== "undefined" && firstBuffer instanceof Uint8Array) return "uint8array"; + if (Array.isArray(firstBuffer)) return "array"; + if (typeof firstBuffer === "string") return "string"; + if (Object.prototype.toString.call(firstBuffer) === "[object Object]") return "object"; + return "buffer"; + }; + ConcatStream.prototype.getBody = function() { + if (!this.encoding && this.body.length === 0) return []; + if (this.shouldInferEncoding) this.encoding = this.inferEncoding(); + if (this.encoding === "array") return arrayConcat(this.body); + if (this.encoding === "string") return stringConcat(this.body); + if (this.encoding === "buffer") return bufferConcat(this.body); + if (this.encoding === "uint8array") return u8Concat(this.body); + return this.body; + }; + function isArrayish(arr) { + return /Array\]$/.test(Object.prototype.toString.call(arr)); + } + function isBufferish(p5) { + return typeof p5 === "string" || isArrayish(p5) || p5 && typeof p5.subarray === "function"; + } + function stringConcat(parts) { + var strings = []; + var needsToString = false; + for (var i5 = 0; i5 < parts.length; i5++) { + var p5 = parts[i5]; + if (typeof p5 === "string") { + strings.push(p5); + } else if (Buffer.isBuffer(p5)) { + strings.push(p5); + } else if (isBufferish(p5)) { + strings.push(bufferFrom(p5)); + } else { + strings.push(bufferFrom(String(p5))); + } + } + if (Buffer.isBuffer(parts[0])) { + strings = Buffer.concat(strings); + strings = strings.toString("utf8"); + } else { + strings = strings.join(""); + } + return strings; + } + function bufferConcat(parts) { + var bufs = []; + for (var i5 = 0; i5 < parts.length; i5++) { + var p5 = parts[i5]; + if (Buffer.isBuffer(p5)) { + bufs.push(p5); + } else if (isBufferish(p5)) { + bufs.push(bufferFrom(p5)); + } else { + bufs.push(bufferFrom(String(p5))); + } + } + return Buffer.concat(bufs); + } + function arrayConcat(parts) { + var res = []; + for (var i5 = 0; i5 < parts.length; i5++) { + res.push.apply(res, parts[i5]); + } + return res; + } + function u8Concat(parts) { + var len = 0; + for (var i5 = 0; i5 < parts.length; i5++) { + if (typeof parts[i5] === "string") { + parts[i5] = bufferFrom(parts[i5]); + } + len += parts[i5].length; + } + var u8 = new U8(len); + for (var i5 = 0, offset = 0; i5 < parts.length; i5++) { + var part = parts[i5]; + for (var j5 = 0; j5 < part.length; j5++) { + u8[offset++] = part[j5]; + } + } + return u8; + } + } +}); + +// node_modules/.pnpm/multer@2.1.1/node_modules/multer/storage/memory.js +var require_memory = __commonJS({ + "node_modules/.pnpm/multer@2.1.1/node_modules/multer/storage/memory.js"(exports, module) { + var concat2 = require_concat_stream(); + function MemoryStorage(opts) { + } + MemoryStorage.prototype._handleFile = function _handleFile(req, file2, cb) { + file2.stream.pipe(concat2({ encoding: "buffer" }, function(data2) { + cb(null, { + buffer: data2, + size: data2.length + }); + })); + }; + MemoryStorage.prototype._removeFile = function _removeFile(req, file2, cb) { + delete file2.buffer; + cb(null); + }; + module.exports = function(opts) { + return new MemoryStorage(opts); + }; + } +}); + +// node_modules/.pnpm/multer@2.1.1/node_modules/multer/index.js +var require_multer = __commonJS({ + "node_modules/.pnpm/multer@2.1.1/node_modules/multer/index.js"(exports, module) { + var makeMiddleware = require_make_middleware(); + var diskStorage = require_disk(); + var memoryStorage = require_memory(); + var MulterError = require_multer_error(); + function allowAll(req, file2, cb) { + cb(null, true); + } + function Multer(options) { + if (options.storage) { + this.storage = options.storage; + } else if (options.dest) { + this.storage = diskStorage({ destination: options.dest }); + } else { + this.storage = memoryStorage(); + } + this.limits = options.limits; + this.preservePath = options.preservePath; + this.defParamCharset = options.defParamCharset || "latin1"; + this.fileFilter = options.fileFilter || allowAll; + } + Multer.prototype._makeMiddleware = function(fields, fileStrategy) { + function setup() { + var fileFilter = this.fileFilter; + var filesLeft = /* @__PURE__ */ Object.create(null); + fields.forEach(function(field) { + if (typeof field.maxCount === "number") { + filesLeft[field.name] = field.maxCount; + } else { + filesLeft[field.name] = Infinity; + } + }); + function wrappedFileFilter(req, file2, cb) { + if ((filesLeft[file2.fieldname] || 0) <= 0) { + return cb(new MulterError("LIMIT_UNEXPECTED_FILE", file2.fieldname)); + } + filesLeft[file2.fieldname] -= 1; + fileFilter(req, file2, cb); + } + return { + limits: this.limits, + preservePath: this.preservePath, + defParamCharset: this.defParamCharset, + storage: this.storage, + fileFilter: wrappedFileFilter, + fileStrategy + }; + } + return makeMiddleware(setup.bind(this)); + }; + Multer.prototype.single = function(name) { + return this._makeMiddleware([{ name, maxCount: 1 }], "VALUE"); + }; + Multer.prototype.array = function(name, maxCount) { + return this._makeMiddleware([{ name, maxCount }], "ARRAY"); + }; + Multer.prototype.fields = function(fields) { + return this._makeMiddleware(fields, "OBJECT"); + }; + Multer.prototype.none = function() { + return this._makeMiddleware([], "NONE"); + }; + Multer.prototype.any = function() { + function setup() { + return { + limits: this.limits, + preservePath: this.preservePath, + defParamCharset: this.defParamCharset, + storage: this.storage, + fileFilter: this.fileFilter, + fileStrategy: "ARRAY" + }; + } + return makeMiddleware(setup.bind(this)); + }; + function multer3(options) { + if (options === void 0) { + return new Multer({}); + } + if (typeof options === "object" && options !== null) { + return new Multer(options); + } + throw new TypeError("Expected object for argument options"); + } + module.exports = multer3; + module.exports.diskStorage = diskStorage; + module.exports.memoryStorage = memoryStorage; + module.exports.MulterError = MulterError; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/codegen/code.js +var require_code = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/codegen/code.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.regexpCode = exports.getEsmExportName = exports.getProperty = exports.safeStringify = exports.stringify = exports.strConcat = exports.addCodeArg = exports.str = exports._ = exports.nil = exports._Code = exports.Name = exports.IDENTIFIER = exports._CodeOrName = void 0; + var _CodeOrName = class { + }; + exports._CodeOrName = _CodeOrName; + exports.IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i; + var Name2 = class extends _CodeOrName { + constructor(s5) { + super(); + if (!exports.IDENTIFIER.test(s5)) + throw new Error("CodeGen: name must be a valid identifier"); + this.str = s5; + } + toString() { + return this.str; + } + emptyStr() { + return false; + } + get names() { + return { [this.str]: 1 }; + } + }; + exports.Name = Name2; + var _Code = class extends _CodeOrName { + constructor(code) { + super(); + this._items = typeof code === "string" ? [code] : code; + } + toString() { + return this.str; + } + emptyStr() { + if (this._items.length > 1) + return false; + const item = this._items[0]; + return item === "" || item === '""'; + } + get str() { + var _a6; + return (_a6 = this._str) !== null && _a6 !== void 0 ? _a6 : this._str = this._items.reduce((s5, c5) => `${s5}${c5}`, ""); + } + get names() { + var _a6; + return (_a6 = this._names) !== null && _a6 !== void 0 ? _a6 : this._names = this._items.reduce((names, c5) => { + if (c5 instanceof Name2) + names[c5.str] = (names[c5.str] || 0) + 1; + return names; + }, {}); + } + }; + exports._Code = _Code; + exports.nil = new _Code(""); + function _(strs, ...args) { + const code = [strs[0]]; + let i5 = 0; + while (i5 < args.length) { + addCodeArg(code, args[i5]); + code.push(strs[++i5]); + } + return new _Code(code); + } + exports._ = _; + var plus = new _Code("+"); + function str(strs, ...args) { + const expr = [safeStringify2(strs[0])]; + let i5 = 0; + while (i5 < args.length) { + expr.push(plus); + addCodeArg(expr, args[i5]); + expr.push(plus, safeStringify2(strs[++i5])); + } + optimize(expr); + return new _Code(expr); + } + exports.str = str; + function addCodeArg(code, arg) { + if (arg instanceof _Code) + code.push(...arg._items); + else if (arg instanceof Name2) + code.push(arg); + else + code.push(interpolate(arg)); + } + exports.addCodeArg = addCodeArg; + function optimize(expr) { + let i5 = 1; + while (i5 < expr.length - 1) { + if (expr[i5] === plus) { + const res = mergeExprItems(expr[i5 - 1], expr[i5 + 1]); + if (res !== void 0) { + expr.splice(i5 - 1, 3, res); + continue; + } + expr[i5++] = "+"; + } + i5++; + } + } + function mergeExprItems(a5, b6) { + if (b6 === '""') + return a5; + if (a5 === '""') + return b6; + if (typeof a5 == "string") { + if (b6 instanceof Name2 || a5[a5.length - 1] !== '"') + return; + if (typeof b6 != "string") + return `${a5.slice(0, -1)}${b6}"`; + if (b6[0] === '"') + return a5.slice(0, -1) + b6.slice(1); + return; + } + if (typeof b6 == "string" && b6[0] === '"' && !(a5 instanceof Name2)) + return `"${a5}${b6.slice(1)}`; + return; + } + function strConcat(c1, c22) { + return c22.emptyStr() ? c1 : c1.emptyStr() ? c22 : str`${c1}${c22}`; + } + exports.strConcat = strConcat; + function interpolate(x5) { + return typeof x5 == "number" || typeof x5 == "boolean" || x5 === null ? x5 : safeStringify2(Array.isArray(x5) ? x5.join(",") : x5); + } + function stringify2(x5) { + return new _Code(safeStringify2(x5)); + } + exports.stringify = stringify2; + function safeStringify2(x5) { + return JSON.stringify(x5).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029"); + } + exports.safeStringify = safeStringify2; + function getProperty(key) { + return typeof key == "string" && exports.IDENTIFIER.test(key) ? new _Code(`.${key}`) : _`[${key}]`; + } + exports.getProperty = getProperty; + function getEsmExportName(key) { + if (typeof key == "string" && exports.IDENTIFIER.test(key)) { + return new _Code(`${key}`); + } + throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`); + } + exports.getEsmExportName = getEsmExportName; + function regexpCode(rx) { + return new _Code(rx.toString()); + } + exports.regexpCode = regexpCode; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/codegen/scope.js +var require_scope = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/codegen/scope.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ValueScope = exports.ValueScopeName = exports.Scope = exports.varKinds = exports.UsedValueState = void 0; + var code_1 = require_code(); + var ValueError = class extends Error { + constructor(name) { + super(`CodeGen: "code" for ${name} not defined`); + this.value = name.value; + } + }; + var UsedValueState; + (function(UsedValueState2) { + UsedValueState2[UsedValueState2["Started"] = 0] = "Started"; + UsedValueState2[UsedValueState2["Completed"] = 1] = "Completed"; + })(UsedValueState || (exports.UsedValueState = UsedValueState = {})); + exports.varKinds = { + const: new code_1.Name("const"), + let: new code_1.Name("let"), + var: new code_1.Name("var") + }; + var Scope = class { + constructor({ prefixes, parent } = {}) { + this._names = {}; + this._prefixes = prefixes; + this._parent = parent; + } + toName(nameOrPrefix) { + return nameOrPrefix instanceof code_1.Name ? nameOrPrefix : this.name(nameOrPrefix); + } + name(prefix) { + return new code_1.Name(this._newName(prefix)); + } + _newName(prefix) { + const ng = this._names[prefix] || this._nameGroup(prefix); + return `${prefix}${ng.index++}`; + } + _nameGroup(prefix) { + var _a6, _b; + if (((_b = (_a6 = this._parent) === null || _a6 === void 0 ? void 0 : _a6._prefixes) === null || _b === void 0 ? void 0 : _b.has(prefix)) || this._prefixes && !this._prefixes.has(prefix)) { + throw new Error(`CodeGen: prefix "${prefix}" is not allowed in this scope`); + } + return this._names[prefix] = { prefix, index: 0 }; + } + }; + exports.Scope = Scope; + var ValueScopeName = class extends code_1.Name { + constructor(prefix, nameStr) { + super(nameStr); + this.prefix = prefix; + } + setValue(value, { property, itemIndex }) { + this.value = value; + this.scopePath = (0, code_1._)`.${new code_1.Name(property)}[${itemIndex}]`; + } + }; + exports.ValueScopeName = ValueScopeName; + var line3 = (0, code_1._)`\n`; + var ValueScope = class extends Scope { + constructor(opts) { + super(opts); + this._values = {}; + this._scope = opts.scope; + this.opts = { ...opts, _n: opts.lines ? line3 : code_1.nil }; + } + get() { + return this._scope; + } + name(prefix) { + return new ValueScopeName(prefix, this._newName(prefix)); + } + value(nameOrPrefix, value) { + var _a6; + if (value.ref === void 0) + throw new Error("CodeGen: ref must be passed in value"); + const name = this.toName(nameOrPrefix); + const { prefix } = name; + const valueKey = (_a6 = value.key) !== null && _a6 !== void 0 ? _a6 : value.ref; + let vs = this._values[prefix]; + if (vs) { + const _name = vs.get(valueKey); + if (_name) + return _name; + } else { + vs = this._values[prefix] = /* @__PURE__ */ new Map(); + } + vs.set(valueKey, name); + const s5 = this._scope[prefix] || (this._scope[prefix] = []); + const itemIndex = s5.length; + s5[itemIndex] = value.ref; + name.setValue(value, { property: prefix, itemIndex }); + return name; + } + getValue(prefix, keyOrRef) { + const vs = this._values[prefix]; + if (!vs) + return; + return vs.get(keyOrRef); + } + scopeRefs(scopeName, values2 = this._values) { + return this._reduceValues(values2, (name) => { + if (name.scopePath === void 0) + throw new Error(`CodeGen: name "${name}" has no value`); + return (0, code_1._)`${scopeName}${name.scopePath}`; + }); + } + scopeCode(values2 = this._values, usedValues, getCode) { + return this._reduceValues(values2, (name) => { + if (name.value === void 0) + throw new Error(`CodeGen: name "${name}" has no value`); + return name.value.code; + }, usedValues, getCode); + } + _reduceValues(values2, valueCode, usedValues = {}, getCode) { + let code = code_1.nil; + for (const prefix in values2) { + const vs = values2[prefix]; + if (!vs) + continue; + const nameSet = usedValues[prefix] = usedValues[prefix] || /* @__PURE__ */ new Map(); + vs.forEach((name) => { + if (nameSet.has(name)) + return; + nameSet.set(name, UsedValueState.Started); + let c5 = valueCode(name); + if (c5) { + const def = this.opts.es5 ? exports.varKinds.var : exports.varKinds.const; + code = (0, code_1._)`${code}${def} ${name} = ${c5};${this.opts._n}`; + } else if (c5 = getCode === null || getCode === void 0 ? void 0 : getCode(name)) { + code = (0, code_1._)`${code}${c5}${this.opts._n}`; + } else { + throw new ValueError(name); + } + nameSet.set(name, UsedValueState.Completed); + }); + } + return code; + } + }; + exports.ValueScope = ValueScope; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/codegen/index.js +var require_codegen = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/codegen/index.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.or = exports.and = exports.not = exports.CodeGen = exports.operators = exports.varKinds = exports.ValueScopeName = exports.ValueScope = exports.Scope = exports.Name = exports.regexpCode = exports.stringify = exports.getProperty = exports.nil = exports.strConcat = exports.str = exports._ = void 0; + var code_1 = require_code(); + var scope_1 = require_scope(); + var code_2 = require_code(); + Object.defineProperty(exports, "_", { enumerable: true, get: function() { + return code_2._; + } }); + Object.defineProperty(exports, "str", { enumerable: true, get: function() { + return code_2.str; + } }); + Object.defineProperty(exports, "strConcat", { enumerable: true, get: function() { + return code_2.strConcat; + } }); + Object.defineProperty(exports, "nil", { enumerable: true, get: function() { + return code_2.nil; + } }); + Object.defineProperty(exports, "getProperty", { enumerable: true, get: function() { + return code_2.getProperty; + } }); + Object.defineProperty(exports, "stringify", { enumerable: true, get: function() { + return code_2.stringify; + } }); + Object.defineProperty(exports, "regexpCode", { enumerable: true, get: function() { + return code_2.regexpCode; + } }); + Object.defineProperty(exports, "Name", { enumerable: true, get: function() { + return code_2.Name; + } }); + var scope_2 = require_scope(); + Object.defineProperty(exports, "Scope", { enumerable: true, get: function() { + return scope_2.Scope; + } }); + Object.defineProperty(exports, "ValueScope", { enumerable: true, get: function() { + return scope_2.ValueScope; + } }); + Object.defineProperty(exports, "ValueScopeName", { enumerable: true, get: function() { + return scope_2.ValueScopeName; + } }); + Object.defineProperty(exports, "varKinds", { enumerable: true, get: function() { + return scope_2.varKinds; + } }); + exports.operators = { + GT: new code_1._Code(">"), + GTE: new code_1._Code(">="), + LT: new code_1._Code("<"), + LTE: new code_1._Code("<="), + EQ: new code_1._Code("==="), + NEQ: new code_1._Code("!=="), + NOT: new code_1._Code("!"), + OR: new code_1._Code("||"), + AND: new code_1._Code("&&"), + ADD: new code_1._Code("+") + }; + var Node = class { + optimizeNodes() { + return this; + } + optimizeNames(_names, _constants) { + return this; + } + }; + var Def = class extends Node { + constructor(varKind, name, rhs) { + super(); + this.varKind = varKind; + this.name = name; + this.rhs = rhs; + } + render({ es5, _n }) { + const varKind = es5 ? scope_1.varKinds.var : this.varKind; + const rhs = this.rhs === void 0 ? "" : ` = ${this.rhs}`; + return `${varKind} ${this.name}${rhs};` + _n; + } + optimizeNames(names, constants) { + if (!names[this.name.str]) + return; + if (this.rhs) + this.rhs = optimizeExpr(this.rhs, names, constants); + return this; + } + get names() { + return this.rhs instanceof code_1._CodeOrName ? this.rhs.names : {}; + } + }; + var Assign = class extends Node { + constructor(lhs, rhs, sideEffects) { + super(); + this.lhs = lhs; + this.rhs = rhs; + this.sideEffects = sideEffects; + } + render({ _n }) { + return `${this.lhs} = ${this.rhs};` + _n; + } + optimizeNames(names, constants) { + if (this.lhs instanceof code_1.Name && !names[this.lhs.str] && !this.sideEffects) + return; + this.rhs = optimizeExpr(this.rhs, names, constants); + return this; + } + get names() { + const names = this.lhs instanceof code_1.Name ? {} : { ...this.lhs.names }; + return addExprNames(names, this.rhs); + } + }; + var AssignOp = class extends Assign { + constructor(lhs, op2, rhs, sideEffects) { + super(lhs, rhs, sideEffects); + this.op = op2; + } + render({ _n }) { + return `${this.lhs} ${this.op}= ${this.rhs};` + _n; + } + }; + var Label = class extends Node { + constructor(label) { + super(); + this.label = label; + this.names = {}; + } + render({ _n }) { + return `${this.label}:` + _n; + } + }; + var Break = class extends Node { + constructor(label) { + super(); + this.label = label; + this.names = {}; + } + render({ _n }) { + const label = this.label ? ` ${this.label}` : ""; + return `break${label};` + _n; + } + }; + var Throw = class extends Node { + constructor(error50) { + super(); + this.error = error50; + } + render({ _n }) { + return `throw ${this.error};` + _n; + } + get names() { + return this.error.names; + } + }; + var AnyCode = class extends Node { + constructor(code) { + super(); + this.code = code; + } + render({ _n }) { + return `${this.code};` + _n; + } + optimizeNodes() { + return `${this.code}` ? this : void 0; + } + optimizeNames(names, constants) { + this.code = optimizeExpr(this.code, names, constants); + return this; + } + get names() { + return this.code instanceof code_1._CodeOrName ? this.code.names : {}; + } + }; + var ParentNode = class extends Node { + constructor(nodes = []) { + super(); + this.nodes = nodes; + } + render(opts) { + return this.nodes.reduce((code, n5) => code + n5.render(opts), ""); + } + optimizeNodes() { + const { nodes } = this; + let i5 = nodes.length; + while (i5--) { + const n5 = nodes[i5].optimizeNodes(); + if (Array.isArray(n5)) + nodes.splice(i5, 1, ...n5); + else if (n5) + nodes[i5] = n5; + else + nodes.splice(i5, 1); + } + return nodes.length > 0 ? this : void 0; + } + optimizeNames(names, constants) { + const { nodes } = this; + let i5 = nodes.length; + while (i5--) { + const n5 = nodes[i5]; + if (n5.optimizeNames(names, constants)) + continue; + subtractNames(names, n5.names); + nodes.splice(i5, 1); + } + return nodes.length > 0 ? this : void 0; + } + get names() { + return this.nodes.reduce((names, n5) => addNames(names, n5.names), {}); + } + }; + var BlockNode = class extends ParentNode { + render(opts) { + return "{" + opts._n + super.render(opts) + "}" + opts._n; + } + }; + var Root = class extends ParentNode { + }; + var Else = class extends BlockNode { + }; + Else.kind = "else"; + var If = class _If extends BlockNode { + constructor(condition, nodes) { + super(nodes); + this.condition = condition; + } + render(opts) { + let code = `if(${this.condition})` + super.render(opts); + if (this.else) + code += "else " + this.else.render(opts); + return code; + } + optimizeNodes() { + super.optimizeNodes(); + const cond = this.condition; + if (cond === true) + return this.nodes; + let e5 = this.else; + if (e5) { + const ns = e5.optimizeNodes(); + e5 = this.else = Array.isArray(ns) ? new Else(ns) : ns; + } + if (e5) { + if (cond === false) + return e5 instanceof _If ? e5 : e5.nodes; + if (this.nodes.length) + return this; + return new _If(not2(cond), e5 instanceof _If ? [e5] : e5.nodes); + } + if (cond === false || !this.nodes.length) + return void 0; + return this; + } + optimizeNames(names, constants) { + var _a6; + this.else = (_a6 = this.else) === null || _a6 === void 0 ? void 0 : _a6.optimizeNames(names, constants); + if (!(super.optimizeNames(names, constants) || this.else)) + return; + this.condition = optimizeExpr(this.condition, names, constants); + return this; + } + get names() { + const names = super.names; + addExprNames(names, this.condition); + if (this.else) + addNames(names, this.else.names); + return names; + } + }; + If.kind = "if"; + var For = class extends BlockNode { + }; + For.kind = "for"; + var ForLoop = class extends For { + constructor(iteration) { + super(); + this.iteration = iteration; + } + render(opts) { + return `for(${this.iteration})` + super.render(opts); + } + optimizeNames(names, constants) { + if (!super.optimizeNames(names, constants)) + return; + this.iteration = optimizeExpr(this.iteration, names, constants); + return this; + } + get names() { + return addNames(super.names, this.iteration.names); + } + }; + var ForRange = class extends For { + constructor(varKind, name, from, to) { + super(); + this.varKind = varKind; + this.name = name; + this.from = from; + this.to = to; + } + render(opts) { + const varKind = opts.es5 ? scope_1.varKinds.var : this.varKind; + const { name, from, to } = this; + return `for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)` + super.render(opts); + } + get names() { + const names = addExprNames(super.names, this.from); + return addExprNames(names, this.to); + } + }; + var ForIter = class extends For { + constructor(loop, varKind, name, iterable) { + super(); + this.loop = loop; + this.varKind = varKind; + this.name = name; + this.iterable = iterable; + } + render(opts) { + return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts); + } + optimizeNames(names, constants) { + if (!super.optimizeNames(names, constants)) + return; + this.iterable = optimizeExpr(this.iterable, names, constants); + return this; + } + get names() { + return addNames(super.names, this.iterable.names); + } + }; + var Func = class extends BlockNode { + constructor(name, args, async) { + super(); + this.name = name; + this.args = args; + this.async = async; + } + render(opts) { + const _async = this.async ? "async " : ""; + return `${_async}function ${this.name}(${this.args})` + super.render(opts); + } + }; + Func.kind = "func"; + var Return = class extends ParentNode { + render(opts) { + return "return " + super.render(opts); + } + }; + Return.kind = "return"; + var Try = class extends BlockNode { + render(opts) { + let code = "try" + super.render(opts); + if (this.catch) + code += this.catch.render(opts); + if (this.finally) + code += this.finally.render(opts); + return code; + } + optimizeNodes() { + var _a6, _b; + super.optimizeNodes(); + (_a6 = this.catch) === null || _a6 === void 0 ? void 0 : _a6.optimizeNodes(); + (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNodes(); + return this; + } + optimizeNames(names, constants) { + var _a6, _b; + super.optimizeNames(names, constants); + (_a6 = this.catch) === null || _a6 === void 0 ? void 0 : _a6.optimizeNames(names, constants); + (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNames(names, constants); + return this; + } + get names() { + const names = super.names; + if (this.catch) + addNames(names, this.catch.names); + if (this.finally) + addNames(names, this.finally.names); + return names; + } + }; + var Catch = class extends BlockNode { + constructor(error50) { + super(); + this.error = error50; + } + render(opts) { + return `catch(${this.error})` + super.render(opts); + } + }; + Catch.kind = "catch"; + var Finally = class extends BlockNode { + render(opts) { + return "finally" + super.render(opts); + } + }; + Finally.kind = "finally"; + var CodeGen = class { + constructor(extScope, opts = {}) { + this._values = {}; + this._blockStarts = []; + this._constants = {}; + this.opts = { ...opts, _n: opts.lines ? "\n" : "" }; + this._extScope = extScope; + this._scope = new scope_1.Scope({ parent: extScope }); + this._nodes = [new Root()]; + } + toString() { + return this._root.render(this.opts); + } + // returns unique name in the internal scope + name(prefix) { + return this._scope.name(prefix); + } + // reserves unique name in the external scope + scopeName(prefix) { + return this._extScope.name(prefix); + } + // reserves unique name in the external scope and assigns value to it + scopeValue(prefixOrName, value) { + const name = this._extScope.value(prefixOrName, value); + const vs = this._values[name.prefix] || (this._values[name.prefix] = /* @__PURE__ */ new Set()); + vs.add(name); + return name; + } + getScopeValue(prefix, keyOrRef) { + return this._extScope.getValue(prefix, keyOrRef); + } + // return code that assigns values in the external scope to the names that are used internally + // (same names that were returned by gen.scopeName or gen.scopeValue) + scopeRefs(scopeName) { + return this._extScope.scopeRefs(scopeName, this._values); + } + scopeCode() { + return this._extScope.scopeCode(this._values); + } + _def(varKind, nameOrPrefix, rhs, constant) { + const name = this._scope.toName(nameOrPrefix); + if (rhs !== void 0 && constant) + this._constants[name.str] = rhs; + this._leafNode(new Def(varKind, name, rhs)); + return name; + } + // `const` declaration (`var` in es5 mode) + const(nameOrPrefix, rhs, _constant) { + return this._def(scope_1.varKinds.const, nameOrPrefix, rhs, _constant); + } + // `let` declaration with optional assignment (`var` in es5 mode) + let(nameOrPrefix, rhs, _constant) { + return this._def(scope_1.varKinds.let, nameOrPrefix, rhs, _constant); + } + // `var` declaration with optional assignment + var(nameOrPrefix, rhs, _constant) { + return this._def(scope_1.varKinds.var, nameOrPrefix, rhs, _constant); + } + // assignment code + assign(lhs, rhs, sideEffects) { + return this._leafNode(new Assign(lhs, rhs, sideEffects)); + } + // `+=` code + add(lhs, rhs) { + return this._leafNode(new AssignOp(lhs, exports.operators.ADD, rhs)); + } + // appends passed SafeExpr to code or executes Block + code(c5) { + if (typeof c5 == "function") + c5(); + else if (c5 !== code_1.nil) + this._leafNode(new AnyCode(c5)); + return this; + } + // returns code for object literal for the passed argument list of key-value pairs + object(...keyValues) { + const code = ["{"]; + for (const [key, value] of keyValues) { + if (code.length > 1) + code.push(","); + code.push(key); + if (key !== value || this.opts.es5) { + code.push(":"); + (0, code_1.addCodeArg)(code, value); + } + } + code.push("}"); + return new code_1._Code(code); + } + // `if` clause (or statement if `thenBody` and, optionally, `elseBody` are passed) + if(condition, thenBody, elseBody) { + this._blockNode(new If(condition)); + if (thenBody && elseBody) { + this.code(thenBody).else().code(elseBody).endIf(); + } else if (thenBody) { + this.code(thenBody).endIf(); + } else if (elseBody) { + throw new Error('CodeGen: "else" body without "then" body'); + } + return this; + } + // `else if` clause - invalid without `if` or after `else` clauses + elseIf(condition) { + return this._elseNode(new If(condition)); + } + // `else` clause - only valid after `if` or `else if` clauses + else() { + return this._elseNode(new Else()); + } + // end `if` statement (needed if gen.if was used only with condition) + endIf() { + return this._endBlockNode(If, Else); + } + _for(node, forBody) { + this._blockNode(node); + if (forBody) + this.code(forBody).endFor(); + return this; + } + // a generic `for` clause (or statement if `forBody` is passed) + for(iteration, forBody) { + return this._for(new ForLoop(iteration), forBody); + } + // `for` statement for a range of values + forRange(nameOrPrefix, from, to, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.let) { + const name = this._scope.toName(nameOrPrefix); + return this._for(new ForRange(varKind, name, from, to), () => forBody(name)); + } + // `for-of` statement (in es5 mode replace with a normal for loop) + forOf(nameOrPrefix, iterable, forBody, varKind = scope_1.varKinds.const) { + const name = this._scope.toName(nameOrPrefix); + if (this.opts.es5) { + const arr = iterable instanceof code_1.Name ? iterable : this.var("_arr", iterable); + return this.forRange("_i", 0, (0, code_1._)`${arr}.length`, (i5) => { + this.var(name, (0, code_1._)`${arr}[${i5}]`); + forBody(name); + }); + } + return this._for(new ForIter("of", varKind, name, iterable), () => forBody(name)); + } + // `for-in` statement. + // With option `ownProperties` replaced with a `for-of` loop for object keys + forIn(nameOrPrefix, obj, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.const) { + if (this.opts.ownProperties) { + return this.forOf(nameOrPrefix, (0, code_1._)`Object.keys(${obj})`, forBody); + } + const name = this._scope.toName(nameOrPrefix); + return this._for(new ForIter("in", varKind, name, obj), () => forBody(name)); + } + // end `for` loop + endFor() { + return this._endBlockNode(For); + } + // `label` statement + label(label) { + return this._leafNode(new Label(label)); + } + // `break` statement + break(label) { + return this._leafNode(new Break(label)); + } + // `return` statement + return(value) { + const node = new Return(); + this._blockNode(node); + this.code(value); + if (node.nodes.length !== 1) + throw new Error('CodeGen: "return" should have one node'); + return this._endBlockNode(Return); + } + // `try` statement + try(tryBody, catchCode, finallyCode) { + if (!catchCode && !finallyCode) + throw new Error('CodeGen: "try" without "catch" and "finally"'); + const node = new Try(); + this._blockNode(node); + this.code(tryBody); + if (catchCode) { + const error50 = this.name("e"); + this._currNode = node.catch = new Catch(error50); + catchCode(error50); + } + if (finallyCode) { + this._currNode = node.finally = new Finally(); + this.code(finallyCode); + } + return this._endBlockNode(Catch, Finally); + } + // `throw` statement + throw(error50) { + return this._leafNode(new Throw(error50)); + } + // start self-balancing block + block(body, nodeCount) { + this._blockStarts.push(this._nodes.length); + if (body) + this.code(body).endBlock(nodeCount); + return this; + } + // end the current self-balancing block + endBlock(nodeCount) { + const len = this._blockStarts.pop(); + if (len === void 0) + throw new Error("CodeGen: not in self-balancing block"); + const toClose = this._nodes.length - len; + if (toClose < 0 || nodeCount !== void 0 && toClose !== nodeCount) { + throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`); + } + this._nodes.length = len; + return this; + } + // `function` heading (or definition if funcBody is passed) + func(name, args = code_1.nil, async, funcBody) { + this._blockNode(new Func(name, args, async)); + if (funcBody) + this.code(funcBody).endFunc(); + return this; + } + // end function definition + endFunc() { + return this._endBlockNode(Func); + } + optimize(n5 = 1) { + while (n5-- > 0) { + this._root.optimizeNodes(); + this._root.optimizeNames(this._root.names, this._constants); + } + } + _leafNode(node) { + this._currNode.nodes.push(node); + return this; + } + _blockNode(node) { + this._currNode.nodes.push(node); + this._nodes.push(node); + } + _endBlockNode(N1, N2) { + const n5 = this._currNode; + if (n5 instanceof N1 || N2 && n5 instanceof N2) { + this._nodes.pop(); + return this; + } + throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`); + } + _elseNode(node) { + const n5 = this._currNode; + if (!(n5 instanceof If)) { + throw new Error('CodeGen: "else" without "if"'); + } + this._currNode = n5.else = node; + return this; + } + get _root() { + return this._nodes[0]; + } + get _currNode() { + const ns = this._nodes; + return ns[ns.length - 1]; + } + set _currNode(node) { + const ns = this._nodes; + ns[ns.length - 1] = node; + } + }; + exports.CodeGen = CodeGen; + function addNames(names, from) { + for (const n5 in from) + names[n5] = (names[n5] || 0) + (from[n5] || 0); + return names; + } + function addExprNames(names, from) { + return from instanceof code_1._CodeOrName ? addNames(names, from.names) : names; + } + function optimizeExpr(expr, names, constants) { + if (expr instanceof code_1.Name) + return replaceName(expr); + if (!canOptimize(expr)) + return expr; + return new code_1._Code(expr._items.reduce((items, c5) => { + if (c5 instanceof code_1.Name) + c5 = replaceName(c5); + if (c5 instanceof code_1._Code) + items.push(...c5._items); + else + items.push(c5); + return items; + }, [])); + function replaceName(n5) { + const c5 = constants[n5.str]; + if (c5 === void 0 || names[n5.str] !== 1) + return n5; + delete names[n5.str]; + return c5; + } + function canOptimize(e5) { + return e5 instanceof code_1._Code && e5._items.some((c5) => c5 instanceof code_1.Name && names[c5.str] === 1 && constants[c5.str] !== void 0); + } + } + function subtractNames(names, from) { + for (const n5 in from) + names[n5] = (names[n5] || 0) - (from[n5] || 0); + } + function not2(x5) { + return typeof x5 == "boolean" || typeof x5 == "number" || x5 === null ? !x5 : (0, code_1._)`!${par(x5)}`; + } + exports.not = not2; + var andCode = mappend(exports.operators.AND); + function and2(...args) { + return args.reduce(andCode); + } + exports.and = and2; + var orCode = mappend(exports.operators.OR); + function or3(...args) { + return args.reduce(orCode); + } + exports.or = or3; + function mappend(op2) { + return (x5, y2) => x5 === code_1.nil ? y2 : y2 === code_1.nil ? x5 : (0, code_1._)`${par(x5)} ${op2} ${par(y2)}`; + } + function par(x5) { + return x5 instanceof code_1.Name ? x5 : (0, code_1._)`(${x5})`; + } + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/util.js +var require_util = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/util.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.checkStrictMode = exports.getErrorPath = exports.Type = exports.useFunc = exports.setEvaluated = exports.evaluatedPropsToName = exports.mergeEvaluated = exports.eachItem = exports.unescapeJsonPointer = exports.escapeJsonPointer = exports.escapeFragment = exports.unescapeFragment = exports.schemaRefOrVal = exports.schemaHasRulesButRef = exports.schemaHasRules = exports.checkUnknownRules = exports.alwaysValidSchema = exports.toHash = void 0; + var codegen_1 = require_codegen(); + var code_1 = require_code(); + function toHash(arr) { + const hash2 = {}; + for (const item of arr) + hash2[item] = true; + return hash2; + } + exports.toHash = toHash; + function alwaysValidSchema(it, schema2) { + if (typeof schema2 == "boolean") + return schema2; + if (Object.keys(schema2).length === 0) + return true; + checkUnknownRules(it, schema2); + return !schemaHasRules(schema2, it.self.RULES.all); + } + exports.alwaysValidSchema = alwaysValidSchema; + function checkUnknownRules(it, schema2 = it.schema) { + const { opts, self: self2 } = it; + if (!opts.strictSchema) + return; + if (typeof schema2 === "boolean") + return; + const rules = self2.RULES.keywords; + for (const key in schema2) { + if (!rules[key]) + checkStrictMode(it, `unknown keyword: "${key}"`); + } + } + exports.checkUnknownRules = checkUnknownRules; + function schemaHasRules(schema2, rules) { + if (typeof schema2 == "boolean") + return !schema2; + for (const key in schema2) + if (rules[key]) + return true; + return false; + } + exports.schemaHasRules = schemaHasRules; + function schemaHasRulesButRef(schema2, RULES) { + if (typeof schema2 == "boolean") + return !schema2; + for (const key in schema2) + if (key !== "$ref" && RULES.all[key]) + return true; + return false; + } + exports.schemaHasRulesButRef = schemaHasRulesButRef; + function schemaRefOrVal({ topSchemaRef, schemaPath }, schema2, keyword, $data) { + if (!$data) { + if (typeof schema2 == "number" || typeof schema2 == "boolean") + return schema2; + if (typeof schema2 == "string") + return (0, codegen_1._)`${schema2}`; + } + return (0, codegen_1._)`${topSchemaRef}${schemaPath}${(0, codegen_1.getProperty)(keyword)}`; + } + exports.schemaRefOrVal = schemaRefOrVal; + function unescapeFragment(str) { + return unescapeJsonPointer(decodeURIComponent(str)); + } + exports.unescapeFragment = unescapeFragment; + function escapeFragment(str) { + return encodeURIComponent(escapeJsonPointer(str)); + } + exports.escapeFragment = escapeFragment; + function escapeJsonPointer(str) { + if (typeof str == "number") + return `${str}`; + return str.replace(/~/g, "~0").replace(/\//g, "~1"); + } + exports.escapeJsonPointer = escapeJsonPointer; + function unescapeJsonPointer(str) { + return str.replace(/~1/g, "/").replace(/~0/g, "~"); + } + exports.unescapeJsonPointer = unescapeJsonPointer; + function eachItem(xs, f5) { + if (Array.isArray(xs)) { + for (const x5 of xs) + f5(x5); + } else { + f5(xs); + } + } + exports.eachItem = eachItem; + function makeMergeEvaluated({ mergeNames, mergeToName, mergeValues: mergeValues3, resultToName }) { + return (gen, from, to, toName) => { + const res = to === void 0 ? from : to instanceof codegen_1.Name ? (from instanceof codegen_1.Name ? mergeNames(gen, from, to) : mergeToName(gen, from, to), to) : from instanceof codegen_1.Name ? (mergeToName(gen, to, from), from) : mergeValues3(from, to); + return toName === codegen_1.Name && !(res instanceof codegen_1.Name) ? resultToName(gen, res) : res; + }; + } + exports.mergeEvaluated = { + props: makeMergeEvaluated({ + mergeNames: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true && ${from} !== undefined`, () => { + gen.if((0, codegen_1._)`${from} === true`, () => gen.assign(to, true), () => gen.assign(to, (0, codegen_1._)`${to} || {}`).code((0, codegen_1._)`Object.assign(${to}, ${from})`)); + }), + mergeToName: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true`, () => { + if (from === true) { + gen.assign(to, true); + } else { + gen.assign(to, (0, codegen_1._)`${to} || {}`); + setEvaluated(gen, to, from); + } + }), + mergeValues: (from, to) => from === true ? true : { ...from, ...to }, + resultToName: evaluatedPropsToName + }), + items: makeMergeEvaluated({ + mergeNames: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true && ${from} !== undefined`, () => gen.assign(to, (0, codegen_1._)`${from} === true ? true : ${to} > ${from} ? ${to} : ${from}`)), + mergeToName: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true`, () => gen.assign(to, from === true ? true : (0, codegen_1._)`${to} > ${from} ? ${to} : ${from}`)), + mergeValues: (from, to) => from === true ? true : Math.max(from, to), + resultToName: (gen, items) => gen.var("items", items) + }) + }; + function evaluatedPropsToName(gen, ps) { + if (ps === true) + return gen.var("props", true); + const props = gen.var("props", (0, codegen_1._)`{}`); + if (ps !== void 0) + setEvaluated(gen, props, ps); + return props; + } + exports.evaluatedPropsToName = evaluatedPropsToName; + function setEvaluated(gen, props, ps) { + Object.keys(ps).forEach((p5) => gen.assign((0, codegen_1._)`${props}${(0, codegen_1.getProperty)(p5)}`, true)); + } + exports.setEvaluated = setEvaluated; + var snippets = {}; + function useFunc(gen, f5) { + return gen.scopeValue("func", { + ref: f5, + code: snippets[f5.code] || (snippets[f5.code] = new code_1._Code(f5.code)) + }); + } + exports.useFunc = useFunc; + var Type; + (function(Type2) { + Type2[Type2["Num"] = 0] = "Num"; + Type2[Type2["Str"] = 1] = "Str"; + })(Type || (exports.Type = Type = {})); + function getErrorPath(dataProp, dataPropType, jsPropertySyntax) { + if (dataProp instanceof codegen_1.Name) { + const isNumber2 = dataPropType === Type.Num; + return jsPropertySyntax ? isNumber2 ? (0, codegen_1._)`"[" + ${dataProp} + "]"` : (0, codegen_1._)`"['" + ${dataProp} + "']"` : isNumber2 ? (0, codegen_1._)`"/" + ${dataProp}` : (0, codegen_1._)`"/" + ${dataProp}.replace(/~/g, "~0").replace(/\\//g, "~1")`; + } + return jsPropertySyntax ? (0, codegen_1.getProperty)(dataProp).toString() : "/" + escapeJsonPointer(dataProp); + } + exports.getErrorPath = getErrorPath; + function checkStrictMode(it, msg, mode = it.opts.strictSchema) { + if (!mode) + return; + msg = `strict mode: ${msg}`; + if (mode === true) + throw new Error(msg); + it.self.logger.warn(msg); + } + exports.checkStrictMode = checkStrictMode; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/names.js +var require_names = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/names.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var names = { + // validation function arguments + data: new codegen_1.Name("data"), + // data passed to validation function + // args passed from referencing schema + valCxt: new codegen_1.Name("valCxt"), + // validation/data context - should not be used directly, it is destructured to the names below + instancePath: new codegen_1.Name("instancePath"), + parentData: new codegen_1.Name("parentData"), + parentDataProperty: new codegen_1.Name("parentDataProperty"), + rootData: new codegen_1.Name("rootData"), + // root data - same as the data passed to the first/top validation function + dynamicAnchors: new codegen_1.Name("dynamicAnchors"), + // used to support recursiveRef and dynamicRef + // function scoped variables + vErrors: new codegen_1.Name("vErrors"), + // null or array of validation errors + errors: new codegen_1.Name("errors"), + // counter of validation errors + this: new codegen_1.Name("this"), + // "globals" + self: new codegen_1.Name("self"), + scope: new codegen_1.Name("scope"), + // JTD serialize/parse name for JSON string and position + json: new codegen_1.Name("json"), + jsonPos: new codegen_1.Name("jsonPos"), + jsonLen: new codegen_1.Name("jsonLen"), + jsonPart: new codegen_1.Name("jsonPart") + }; + exports.default = names; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/errors.js +var require_errors3 = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/errors.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.extendErrors = exports.resetErrorsCount = exports.reportExtraError = exports.reportError = exports.keyword$DataError = exports.keywordError = void 0; + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var names_1 = require_names(); + exports.keywordError = { + message: ({ keyword }) => (0, codegen_1.str)`must pass "${keyword}" keyword validation` + }; + exports.keyword$DataError = { + message: ({ keyword, schemaType }) => schemaType ? (0, codegen_1.str)`"${keyword}" keyword must be ${schemaType} ($data)` : (0, codegen_1.str)`"${keyword}" keyword is invalid ($data)` + }; + function reportError(cxt, error50 = exports.keywordError, errorPaths, overrideAllErrors) { + const { it } = cxt; + const { gen, compositeRule, allErrors } = it; + const errObj = errorObjectCode(cxt, error50, errorPaths); + if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : compositeRule || allErrors) { + addError(gen, errObj); + } else { + returnErrors(it, (0, codegen_1._)`[${errObj}]`); + } + } + exports.reportError = reportError; + function reportExtraError(cxt, error50 = exports.keywordError, errorPaths) { + const { it } = cxt; + const { gen, compositeRule, allErrors } = it; + const errObj = errorObjectCode(cxt, error50, errorPaths); + addError(gen, errObj); + if (!(compositeRule || allErrors)) { + returnErrors(it, names_1.default.vErrors); + } + } + exports.reportExtraError = reportExtraError; + function resetErrorsCount(gen, errsCount) { + gen.assign(names_1.default.errors, errsCount); + gen.if((0, codegen_1._)`${names_1.default.vErrors} !== null`, () => gen.if(errsCount, () => gen.assign((0, codegen_1._)`${names_1.default.vErrors}.length`, errsCount), () => gen.assign(names_1.default.vErrors, null))); + } + exports.resetErrorsCount = resetErrorsCount; + function extendErrors({ gen, keyword, schemaValue, data: data2, errsCount, it }) { + if (errsCount === void 0) + throw new Error("ajv implementation error"); + const err = gen.name("err"); + gen.forRange("i", errsCount, names_1.default.errors, (i5) => { + gen.const(err, (0, codegen_1._)`${names_1.default.vErrors}[${i5}]`); + gen.if((0, codegen_1._)`${err}.instancePath === undefined`, () => gen.assign((0, codegen_1._)`${err}.instancePath`, (0, codegen_1.strConcat)(names_1.default.instancePath, it.errorPath))); + gen.assign((0, codegen_1._)`${err}.schemaPath`, (0, codegen_1.str)`${it.errSchemaPath}/${keyword}`); + if (it.opts.verbose) { + gen.assign((0, codegen_1._)`${err}.schema`, schemaValue); + gen.assign((0, codegen_1._)`${err}.data`, data2); + } + }); + } + exports.extendErrors = extendErrors; + function addError(gen, errObj) { + const err = gen.const("err", errObj); + gen.if((0, codegen_1._)`${names_1.default.vErrors} === null`, () => gen.assign(names_1.default.vErrors, (0, codegen_1._)`[${err}]`), (0, codegen_1._)`${names_1.default.vErrors}.push(${err})`); + gen.code((0, codegen_1._)`${names_1.default.errors}++`); + } + function returnErrors(it, errs) { + const { gen, validateName, schemaEnv } = it; + if (schemaEnv.$async) { + gen.throw((0, codegen_1._)`new ${it.ValidationError}(${errs})`); + } else { + gen.assign((0, codegen_1._)`${validateName}.errors`, errs); + gen.return(false); + } + } + var E2 = { + keyword: new codegen_1.Name("keyword"), + schemaPath: new codegen_1.Name("schemaPath"), + // also used in JTD errors + params: new codegen_1.Name("params"), + propertyName: new codegen_1.Name("propertyName"), + message: new codegen_1.Name("message"), + schema: new codegen_1.Name("schema"), + parentSchema: new codegen_1.Name("parentSchema") + }; + function errorObjectCode(cxt, error50, errorPaths) { + const { createErrors } = cxt.it; + if (createErrors === false) + return (0, codegen_1._)`{}`; + return errorObject(cxt, error50, errorPaths); + } + function errorObject(cxt, error50, errorPaths = {}) { + const { gen, it } = cxt; + const keyValues = [ + errorInstancePath(it, errorPaths), + errorSchemaPath(cxt, errorPaths) + ]; + extraErrorProps(cxt, error50, keyValues); + return gen.object(...keyValues); + } + function errorInstancePath({ errorPath }, { instancePath }) { + const instPath = instancePath ? (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(instancePath, util_1.Type.Str)}` : errorPath; + return [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, instPath)]; + } + function errorSchemaPath({ keyword, it: { errSchemaPath } }, { schemaPath, parentSchema }) { + let schPath = parentSchema ? errSchemaPath : (0, codegen_1.str)`${errSchemaPath}/${keyword}`; + if (schemaPath) { + schPath = (0, codegen_1.str)`${schPath}${(0, util_1.getErrorPath)(schemaPath, util_1.Type.Str)}`; + } + return [E2.schemaPath, schPath]; + } + function extraErrorProps(cxt, { params, message: message2 }, keyValues) { + const { keyword, data: data2, schemaValue, it } = cxt; + const { opts, propertyName, topSchemaRef, schemaPath } = it; + keyValues.push([E2.keyword, keyword], [E2.params, typeof params == "function" ? params(cxt) : params || (0, codegen_1._)`{}`]); + if (opts.messages) { + keyValues.push([E2.message, typeof message2 == "function" ? message2(cxt) : message2]); + } + if (opts.verbose) { + keyValues.push([E2.schema, schemaValue], [E2.parentSchema, (0, codegen_1._)`${topSchemaRef}${schemaPath}`], [names_1.default.data, data2]); + } + if (propertyName) + keyValues.push([E2.propertyName, propertyName]); + } + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/boolSchema.js +var require_boolSchema = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/boolSchema.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.boolOrEmptySchema = exports.topBoolOrEmptySchema = void 0; + var errors_1 = require_errors3(); + var codegen_1 = require_codegen(); + var names_1 = require_names(); + var boolError = { + message: "boolean schema is false" + }; + function topBoolOrEmptySchema(it) { + const { gen, schema: schema2, validateName } = it; + if (schema2 === false) { + falseSchemaError(it, false); + } else if (typeof schema2 == "object" && schema2.$async === true) { + gen.return(names_1.default.data); + } else { + gen.assign((0, codegen_1._)`${validateName}.errors`, null); + gen.return(true); + } + } + exports.topBoolOrEmptySchema = topBoolOrEmptySchema; + function boolOrEmptySchema(it, valid) { + const { gen, schema: schema2 } = it; + if (schema2 === false) { + gen.var(valid, false); + falseSchemaError(it); + } else { + gen.var(valid, true); + } + } + exports.boolOrEmptySchema = boolOrEmptySchema; + function falseSchemaError(it, overrideAllErrors) { + const { gen, data: data2 } = it; + const cxt = { + gen, + keyword: "false schema", + data: data2, + schema: false, + schemaCode: false, + schemaValue: false, + params: {}, + it + }; + (0, errors_1.reportError)(cxt, boolError, void 0, overrideAllErrors); + } + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/rules.js +var require_rules = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/rules.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getRules = exports.isJSONType = void 0; + var _jsonTypes = ["string", "number", "integer", "boolean", "null", "object", "array"]; + var jsonTypes = new Set(_jsonTypes); + function isJSONType(x5) { + return typeof x5 == "string" && jsonTypes.has(x5); + } + exports.isJSONType = isJSONType; + function getRules() { + const groups = { + number: { type: "number", rules: [] }, + string: { type: "string", rules: [] }, + array: { type: "array", rules: [] }, + object: { type: "object", rules: [] } + }; + return { + types: { ...groups, integer: true, boolean: true, null: true }, + rules: [{ rules: [] }, groups.number, groups.string, groups.array, groups.object], + post: { rules: [] }, + all: {}, + keywords: {} + }; + } + exports.getRules = getRules; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/applicability.js +var require_applicability = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/applicability.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.shouldUseRule = exports.shouldUseGroup = exports.schemaHasRulesForType = void 0; + function schemaHasRulesForType({ schema: schema2, self: self2 }, type) { + const group = self2.RULES.types[type]; + return group && group !== true && shouldUseGroup(schema2, group); + } + exports.schemaHasRulesForType = schemaHasRulesForType; + function shouldUseGroup(schema2, group) { + return group.rules.some((rule) => shouldUseRule(schema2, rule)); + } + exports.shouldUseGroup = shouldUseGroup; + function shouldUseRule(schema2, rule) { + var _a6; + return schema2[rule.keyword] !== void 0 || ((_a6 = rule.definition.implements) === null || _a6 === void 0 ? void 0 : _a6.some((kwd) => schema2[kwd] !== void 0)); + } + exports.shouldUseRule = shouldUseRule; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/dataType.js +var require_dataType = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/dataType.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.reportTypeError = exports.checkDataTypes = exports.checkDataType = exports.coerceAndCheckDataType = exports.getJSONTypes = exports.getSchemaTypes = exports.DataType = void 0; + var rules_1 = require_rules(); + var applicability_1 = require_applicability(); + var errors_1 = require_errors3(); + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var DataType; + (function(DataType2) { + DataType2[DataType2["Correct"] = 0] = "Correct"; + DataType2[DataType2["Wrong"] = 1] = "Wrong"; + })(DataType || (exports.DataType = DataType = {})); + function getSchemaTypes(schema2) { + const types2 = getJSONTypes(schema2.type); + const hasNull = types2.includes("null"); + if (hasNull) { + if (schema2.nullable === false) + throw new Error("type: null contradicts nullable: false"); + } else { + if (!types2.length && schema2.nullable !== void 0) { + throw new Error('"nullable" cannot be used without "type"'); + } + if (schema2.nullable === true) + types2.push("null"); + } + return types2; + } + exports.getSchemaTypes = getSchemaTypes; + function getJSONTypes(ts) { + const types2 = Array.isArray(ts) ? ts : ts ? [ts] : []; + if (types2.every(rules_1.isJSONType)) + return types2; + throw new Error("type must be JSONType or JSONType[]: " + types2.join(",")); + } + exports.getJSONTypes = getJSONTypes; + function coerceAndCheckDataType(it, types2) { + const { gen, data: data2, opts } = it; + const coerceTo = coerceToTypes(types2, opts.coerceTypes); + const checkTypes = types2.length > 0 && !(coerceTo.length === 0 && types2.length === 1 && (0, applicability_1.schemaHasRulesForType)(it, types2[0])); + if (checkTypes) { + const wrongType = checkDataTypes(types2, data2, opts.strictNumbers, DataType.Wrong); + gen.if(wrongType, () => { + if (coerceTo.length) + coerceData(it, types2, coerceTo); + else + reportTypeError(it); + }); + } + return checkTypes; + } + exports.coerceAndCheckDataType = coerceAndCheckDataType; + var COERCIBLE = /* @__PURE__ */ new Set(["string", "number", "integer", "boolean", "null"]); + function coerceToTypes(types2, coerceTypes) { + return coerceTypes ? types2.filter((t5) => COERCIBLE.has(t5) || coerceTypes === "array" && t5 === "array") : []; + } + function coerceData(it, types2, coerceTo) { + const { gen, data: data2, opts } = it; + const dataType = gen.let("dataType", (0, codegen_1._)`typeof ${data2}`); + const coerced = gen.let("coerced", (0, codegen_1._)`undefined`); + if (opts.coerceTypes === "array") { + gen.if((0, codegen_1._)`${dataType} == 'object' && Array.isArray(${data2}) && ${data2}.length == 1`, () => gen.assign(data2, (0, codegen_1._)`${data2}[0]`).assign(dataType, (0, codegen_1._)`typeof ${data2}`).if(checkDataTypes(types2, data2, opts.strictNumbers), () => gen.assign(coerced, data2))); + } + gen.if((0, codegen_1._)`${coerced} !== undefined`); + for (const t5 of coerceTo) { + if (COERCIBLE.has(t5) || t5 === "array" && opts.coerceTypes === "array") { + coerceSpecificType(t5); + } + } + gen.else(); + reportTypeError(it); + gen.endIf(); + gen.if((0, codegen_1._)`${coerced} !== undefined`, () => { + gen.assign(data2, coerced); + assignParentData(it, coerced); + }); + function coerceSpecificType(t5) { + switch (t5) { + case "string": + gen.elseIf((0, codegen_1._)`${dataType} == "number" || ${dataType} == "boolean"`).assign(coerced, (0, codegen_1._)`"" + ${data2}`).elseIf((0, codegen_1._)`${data2} === null`).assign(coerced, (0, codegen_1._)`""`); + return; + case "number": + gen.elseIf((0, codegen_1._)`${dataType} == "boolean" || ${data2} === null + || (${dataType} == "string" && ${data2} && ${data2} == +${data2})`).assign(coerced, (0, codegen_1._)`+${data2}`); + return; + case "integer": + gen.elseIf((0, codegen_1._)`${dataType} === "boolean" || ${data2} === null + || (${dataType} === "string" && ${data2} && ${data2} == +${data2} && !(${data2} % 1))`).assign(coerced, (0, codegen_1._)`+${data2}`); + return; + case "boolean": + gen.elseIf((0, codegen_1._)`${data2} === "false" || ${data2} === 0 || ${data2} === null`).assign(coerced, false).elseIf((0, codegen_1._)`${data2} === "true" || ${data2} === 1`).assign(coerced, true); + return; + case "null": + gen.elseIf((0, codegen_1._)`${data2} === "" || ${data2} === 0 || ${data2} === false`); + gen.assign(coerced, null); + return; + case "array": + gen.elseIf((0, codegen_1._)`${dataType} === "string" || ${dataType} === "number" + || ${dataType} === "boolean" || ${data2} === null`).assign(coerced, (0, codegen_1._)`[${data2}]`); + } + } + } + function assignParentData({ gen, parentData, parentDataProperty }, expr) { + gen.if((0, codegen_1._)`${parentData} !== undefined`, () => gen.assign((0, codegen_1._)`${parentData}[${parentDataProperty}]`, expr)); + } + function checkDataType(dataType, data2, strictNums, correct = DataType.Correct) { + const EQ = correct === DataType.Correct ? codegen_1.operators.EQ : codegen_1.operators.NEQ; + let cond; + switch (dataType) { + case "null": + return (0, codegen_1._)`${data2} ${EQ} null`; + case "array": + cond = (0, codegen_1._)`Array.isArray(${data2})`; + break; + case "object": + cond = (0, codegen_1._)`${data2} && typeof ${data2} == "object" && !Array.isArray(${data2})`; + break; + case "integer": + cond = numCond((0, codegen_1._)`!(${data2} % 1) && !isNaN(${data2})`); + break; + case "number": + cond = numCond(); + break; + default: + return (0, codegen_1._)`typeof ${data2} ${EQ} ${dataType}`; + } + return correct === DataType.Correct ? cond : (0, codegen_1.not)(cond); + function numCond(_cond = codegen_1.nil) { + return (0, codegen_1.and)((0, codegen_1._)`typeof ${data2} == "number"`, _cond, strictNums ? (0, codegen_1._)`isFinite(${data2})` : codegen_1.nil); + } + } + exports.checkDataType = checkDataType; + function checkDataTypes(dataTypes, data2, strictNums, correct) { + if (dataTypes.length === 1) { + return checkDataType(dataTypes[0], data2, strictNums, correct); + } + let cond; + const types2 = (0, util_1.toHash)(dataTypes); + if (types2.array && types2.object) { + const notObj = (0, codegen_1._)`typeof ${data2} != "object"`; + cond = types2.null ? notObj : (0, codegen_1._)`!${data2} || ${notObj}`; + delete types2.null; + delete types2.array; + delete types2.object; + } else { + cond = codegen_1.nil; + } + if (types2.number) + delete types2.integer; + for (const t5 in types2) + cond = (0, codegen_1.and)(cond, checkDataType(t5, data2, strictNums, correct)); + return cond; + } + exports.checkDataTypes = checkDataTypes; + var typeError = { + message: ({ schema: schema2 }) => `must be ${schema2}`, + params: ({ schema: schema2, schemaValue }) => typeof schema2 == "string" ? (0, codegen_1._)`{type: ${schema2}}` : (0, codegen_1._)`{type: ${schemaValue}}` + }; + function reportTypeError(it) { + const cxt = getTypeErrorContext(it); + (0, errors_1.reportError)(cxt, typeError); + } + exports.reportTypeError = reportTypeError; + function getTypeErrorContext(it) { + const { gen, data: data2, schema: schema2 } = it; + const schemaCode = (0, util_1.schemaRefOrVal)(it, schema2, "type"); + return { + gen, + keyword: "type", + data: data2, + schema: schema2.type, + schemaCode, + schemaValue: schemaCode, + parentSchema: schema2, + params: {}, + it + }; + } + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/defaults.js +var require_defaults = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/defaults.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.assignDefaults = void 0; + var codegen_1 = require_codegen(); + var util_1 = require_util(); + function assignDefaults(it, ty) { + const { properties, items } = it.schema; + if (ty === "object" && properties) { + for (const key in properties) { + assignDefault(it, key, properties[key].default); + } + } else if (ty === "array" && Array.isArray(items)) { + items.forEach((sch, i5) => assignDefault(it, i5, sch.default)); + } + } + exports.assignDefaults = assignDefaults; + function assignDefault(it, prop, defaultValue) { + const { gen, compositeRule, data: data2, opts } = it; + if (defaultValue === void 0) + return; + const childData = (0, codegen_1._)`${data2}${(0, codegen_1.getProperty)(prop)}`; + if (compositeRule) { + (0, util_1.checkStrictMode)(it, `default is ignored for: ${childData}`); + return; + } + let condition = (0, codegen_1._)`${childData} === undefined`; + if (opts.useDefaults === "empty") { + condition = (0, codegen_1._)`${condition} || ${childData} === null || ${childData} === ""`; + } + gen.if(condition, (0, codegen_1._)`${childData} = ${(0, codegen_1.stringify)(defaultValue)}`); + } + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/code.js +var require_code2 = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/code.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateUnion = exports.validateArray = exports.usePattern = exports.callValidateCode = exports.schemaProperties = exports.allSchemaProperties = exports.noPropertyInData = exports.propertyInData = exports.isOwnProperty = exports.hasPropFunc = exports.reportMissingProp = exports.checkMissingProp = exports.checkReportMissingProp = void 0; + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var names_1 = require_names(); + var util_2 = require_util(); + function checkReportMissingProp(cxt, prop) { + const { gen, data: data2, it } = cxt; + gen.if(noPropertyInData(gen, data2, prop, it.opts.ownProperties), () => { + cxt.setParams({ missingProperty: (0, codegen_1._)`${prop}` }, true); + cxt.error(); + }); + } + exports.checkReportMissingProp = checkReportMissingProp; + function checkMissingProp({ gen, data: data2, it: { opts } }, properties, missing) { + return (0, codegen_1.or)(...properties.map((prop) => (0, codegen_1.and)(noPropertyInData(gen, data2, prop, opts.ownProperties), (0, codegen_1._)`${missing} = ${prop}`))); + } + exports.checkMissingProp = checkMissingProp; + function reportMissingProp(cxt, missing) { + cxt.setParams({ missingProperty: missing }, true); + cxt.error(); + } + exports.reportMissingProp = reportMissingProp; + function hasPropFunc(gen) { + return gen.scopeValue("func", { + // eslint-disable-next-line @typescript-eslint/unbound-method + ref: Object.prototype.hasOwnProperty, + code: (0, codegen_1._)`Object.prototype.hasOwnProperty` + }); + } + exports.hasPropFunc = hasPropFunc; + function isOwnProperty(gen, data2, property) { + return (0, codegen_1._)`${hasPropFunc(gen)}.call(${data2}, ${property})`; + } + exports.isOwnProperty = isOwnProperty; + function propertyInData(gen, data2, property, ownProperties) { + const cond = (0, codegen_1._)`${data2}${(0, codegen_1.getProperty)(property)} !== undefined`; + return ownProperties ? (0, codegen_1._)`${cond} && ${isOwnProperty(gen, data2, property)}` : cond; + } + exports.propertyInData = propertyInData; + function noPropertyInData(gen, data2, property, ownProperties) { + const cond = (0, codegen_1._)`${data2}${(0, codegen_1.getProperty)(property)} === undefined`; + return ownProperties ? (0, codegen_1.or)(cond, (0, codegen_1.not)(isOwnProperty(gen, data2, property))) : cond; + } + exports.noPropertyInData = noPropertyInData; + function allSchemaProperties(schemaMap) { + return schemaMap ? Object.keys(schemaMap).filter((p5) => p5 !== "__proto__") : []; + } + exports.allSchemaProperties = allSchemaProperties; + function schemaProperties(it, schemaMap) { + return allSchemaProperties(schemaMap).filter((p5) => !(0, util_1.alwaysValidSchema)(it, schemaMap[p5])); + } + exports.schemaProperties = schemaProperties; + function callValidateCode({ schemaCode, data: data2, it: { gen, topSchemaRef, schemaPath, errorPath }, it }, func, context, passSchema) { + const dataAndSchema = passSchema ? (0, codegen_1._)`${schemaCode}, ${data2}, ${topSchemaRef}${schemaPath}` : data2; + const valCxt = [ + [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, errorPath)], + [names_1.default.parentData, it.parentData], + [names_1.default.parentDataProperty, it.parentDataProperty], + [names_1.default.rootData, names_1.default.rootData] + ]; + if (it.opts.dynamicRef) + valCxt.push([names_1.default.dynamicAnchors, names_1.default.dynamicAnchors]); + const args = (0, codegen_1._)`${dataAndSchema}, ${gen.object(...valCxt)}`; + return context !== codegen_1.nil ? (0, codegen_1._)`${func}.call(${context}, ${args})` : (0, codegen_1._)`${func}(${args})`; + } + exports.callValidateCode = callValidateCode; + var newRegExp = (0, codegen_1._)`new RegExp`; + function usePattern({ gen, it: { opts } }, pattern) { + const u5 = opts.unicodeRegExp ? "u" : ""; + const { regExp } = opts.code; + const rx = regExp(pattern, u5); + return gen.scopeValue("pattern", { + key: rx.toString(), + ref: rx, + code: (0, codegen_1._)`${regExp.code === "new RegExp" ? newRegExp : (0, util_2.useFunc)(gen, regExp)}(${pattern}, ${u5})` + }); + } + exports.usePattern = usePattern; + function validateArray(cxt) { + const { gen, data: data2, keyword, it } = cxt; + const valid = gen.name("valid"); + if (it.allErrors) { + const validArr = gen.let("valid", true); + validateItems(() => gen.assign(validArr, false)); + return validArr; + } + gen.var(valid, true); + validateItems(() => gen.break()); + return valid; + function validateItems(notValid) { + const len = gen.const("len", (0, codegen_1._)`${data2}.length`); + gen.forRange("i", 0, len, (i5) => { + cxt.subschema({ + keyword, + dataProp: i5, + dataPropType: util_1.Type.Num + }, valid); + gen.if((0, codegen_1.not)(valid), notValid); + }); + } + } + exports.validateArray = validateArray; + function validateUnion(cxt) { + const { gen, schema: schema2, keyword, it } = cxt; + if (!Array.isArray(schema2)) + throw new Error("ajv implementation error"); + const alwaysValid = schema2.some((sch) => (0, util_1.alwaysValidSchema)(it, sch)); + if (alwaysValid && !it.opts.unevaluated) + return; + const valid = gen.let("valid", false); + const schValid = gen.name("_valid"); + gen.block(() => schema2.forEach((_sch, i5) => { + const schCxt = cxt.subschema({ + keyword, + schemaProp: i5, + compositeRule: true + }, schValid); + gen.assign(valid, (0, codegen_1._)`${valid} || ${schValid}`); + const merged = cxt.mergeValidEvaluated(schCxt, schValid); + if (!merged) + gen.if((0, codegen_1.not)(valid)); + })); + cxt.result(valid, () => cxt.reset(), () => cxt.error(true)); + } + exports.validateUnion = validateUnion; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/keyword.js +var require_keyword = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/keyword.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateKeywordUsage = exports.validSchemaType = exports.funcKeywordCode = exports.macroKeywordCode = void 0; + var codegen_1 = require_codegen(); + var names_1 = require_names(); + var code_1 = require_code2(); + var errors_1 = require_errors3(); + function macroKeywordCode(cxt, def) { + const { gen, keyword, schema: schema2, parentSchema, it } = cxt; + const macroSchema = def.macro.call(it.self, schema2, parentSchema, it); + const schemaRef = useKeyword(gen, keyword, macroSchema); + if (it.opts.validateSchema !== false) + it.self.validateSchema(macroSchema, true); + const valid = gen.name("valid"); + cxt.subschema({ + schema: macroSchema, + schemaPath: codegen_1.nil, + errSchemaPath: `${it.errSchemaPath}/${keyword}`, + topSchemaRef: schemaRef, + compositeRule: true + }, valid); + cxt.pass(valid, () => cxt.error(true)); + } + exports.macroKeywordCode = macroKeywordCode; + function funcKeywordCode(cxt, def) { + var _a6; + const { gen, keyword, schema: schema2, parentSchema, $data, it } = cxt; + checkAsyncKeyword(it, def); + const validate2 = !$data && def.compile ? def.compile.call(it.self, schema2, parentSchema, it) : def.validate; + const validateRef = useKeyword(gen, keyword, validate2); + const valid = gen.let("valid"); + cxt.block$data(valid, validateKeyword); + cxt.ok((_a6 = def.valid) !== null && _a6 !== void 0 ? _a6 : valid); + function validateKeyword() { + if (def.errors === false) { + assignValid(); + if (def.modifying) + modifyData(cxt); + reportErrs(() => cxt.error()); + } else { + const ruleErrs = def.async ? validateAsync() : validateSync(); + if (def.modifying) + modifyData(cxt); + reportErrs(() => addErrs(cxt, ruleErrs)); + } + } + function validateAsync() { + const ruleErrs = gen.let("ruleErrs", null); + gen.try(() => assignValid((0, codegen_1._)`await `), (e5) => gen.assign(valid, false).if((0, codegen_1._)`${e5} instanceof ${it.ValidationError}`, () => gen.assign(ruleErrs, (0, codegen_1._)`${e5}.errors`), () => gen.throw(e5))); + return ruleErrs; + } + function validateSync() { + const validateErrs = (0, codegen_1._)`${validateRef}.errors`; + gen.assign(validateErrs, null); + assignValid(codegen_1.nil); + return validateErrs; + } + function assignValid(_await = def.async ? (0, codegen_1._)`await ` : codegen_1.nil) { + const passCxt = it.opts.passContext ? names_1.default.this : names_1.default.self; + const passSchema = !("compile" in def && !$data || def.schema === false); + gen.assign(valid, (0, codegen_1._)`${_await}${(0, code_1.callValidateCode)(cxt, validateRef, passCxt, passSchema)}`, def.modifying); + } + function reportErrs(errors) { + var _a7; + gen.if((0, codegen_1.not)((_a7 = def.valid) !== null && _a7 !== void 0 ? _a7 : valid), errors); + } + } + exports.funcKeywordCode = funcKeywordCode; + function modifyData(cxt) { + const { gen, data: data2, it } = cxt; + gen.if(it.parentData, () => gen.assign(data2, (0, codegen_1._)`${it.parentData}[${it.parentDataProperty}]`)); + } + function addErrs(cxt, errs) { + const { gen } = cxt; + gen.if((0, codegen_1._)`Array.isArray(${errs})`, () => { + gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`).assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`); + (0, errors_1.extendErrors)(cxt); + }, () => cxt.error()); + } + function checkAsyncKeyword({ schemaEnv }, def) { + if (def.async && !schemaEnv.$async) + throw new Error("async keyword in sync schema"); + } + function useKeyword(gen, keyword, result) { + if (result === void 0) + throw new Error(`keyword "${keyword}" failed to compile`); + return gen.scopeValue("keyword", typeof result == "function" ? { ref: result } : { ref: result, code: (0, codegen_1.stringify)(result) }); + } + function validSchemaType(schema2, schemaType, allowUndefined = false) { + return !schemaType.length || schemaType.some((st) => st === "array" ? Array.isArray(schema2) : st === "object" ? schema2 && typeof schema2 == "object" && !Array.isArray(schema2) : typeof schema2 == st || allowUndefined && typeof schema2 == "undefined"); + } + exports.validSchemaType = validSchemaType; + function validateKeywordUsage({ schema: schema2, opts, self: self2, errSchemaPath }, def, keyword) { + if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) { + throw new Error("ajv implementation error"); + } + const deps = def.dependencies; + if (deps === null || deps === void 0 ? void 0 : deps.some((kwd) => !Object.prototype.hasOwnProperty.call(schema2, kwd))) { + throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(",")}`); + } + if (def.validateSchema) { + const valid = def.validateSchema(schema2[keyword]); + if (!valid) { + const msg = `keyword "${keyword}" value is invalid at path "${errSchemaPath}": ` + self2.errorsText(def.validateSchema.errors); + if (opts.validateSchema === "log") + self2.logger.error(msg); + else + throw new Error(msg); + } + } + } + exports.validateKeywordUsage = validateKeywordUsage; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/subschema.js +var require_subschema = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/subschema.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.extendSubschemaMode = exports.extendSubschemaData = exports.getSubschema = void 0; + var codegen_1 = require_codegen(); + var util_1 = require_util(); + function getSubschema(it, { keyword, schemaProp, schema: schema2, schemaPath, errSchemaPath, topSchemaRef }) { + if (keyword !== void 0 && schema2 !== void 0) { + throw new Error('both "keyword" and "schema" passed, only one allowed'); + } + if (keyword !== void 0) { + const sch = it.schema[keyword]; + return schemaProp === void 0 ? { + schema: sch, + schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}`, + errSchemaPath: `${it.errSchemaPath}/${keyword}` + } : { + schema: sch[schemaProp], + schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}${(0, codegen_1.getProperty)(schemaProp)}`, + errSchemaPath: `${it.errSchemaPath}/${keyword}/${(0, util_1.escapeFragment)(schemaProp)}` + }; + } + if (schema2 !== void 0) { + if (schemaPath === void 0 || errSchemaPath === void 0 || topSchemaRef === void 0) { + throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"'); + } + return { + schema: schema2, + schemaPath, + topSchemaRef, + errSchemaPath + }; + } + throw new Error('either "keyword" or "schema" must be passed'); + } + exports.getSubschema = getSubschema; + function extendSubschemaData(subschema, it, { dataProp, dataPropType: dpType, data: data2, dataTypes, propertyName }) { + if (data2 !== void 0 && dataProp !== void 0) { + throw new Error('both "data" and "dataProp" passed, only one allowed'); + } + const { gen } = it; + if (dataProp !== void 0) { + const { errorPath, dataPathArr, opts } = it; + const nextData = gen.let("data", (0, codegen_1._)`${it.data}${(0, codegen_1.getProperty)(dataProp)}`, true); + dataContextProps(nextData); + subschema.errorPath = (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(dataProp, dpType, opts.jsPropertySyntax)}`; + subschema.parentDataProperty = (0, codegen_1._)`${dataProp}`; + subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty]; + } + if (data2 !== void 0) { + const nextData = data2 instanceof codegen_1.Name ? data2 : gen.let("data", data2, true); + dataContextProps(nextData); + if (propertyName !== void 0) + subschema.propertyName = propertyName; + } + if (dataTypes) + subschema.dataTypes = dataTypes; + function dataContextProps(_nextData) { + subschema.data = _nextData; + subschema.dataLevel = it.dataLevel + 1; + subschema.dataTypes = []; + it.definedProperties = /* @__PURE__ */ new Set(); + subschema.parentData = it.data; + subschema.dataNames = [...it.dataNames, _nextData]; + } + } + exports.extendSubschemaData = extendSubschemaData; + function extendSubschemaMode(subschema, { jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors }) { + if (compositeRule !== void 0) + subschema.compositeRule = compositeRule; + if (createErrors !== void 0) + subschema.createErrors = createErrors; + if (allErrors !== void 0) + subschema.allErrors = allErrors; + subschema.jtdDiscriminator = jtdDiscriminator; + subschema.jtdMetadata = jtdMetadata; + } + exports.extendSubschemaMode = extendSubschemaMode; + } +}); + +// node_modules/.pnpm/fast-deep-equal@3.1.3/node_modules/fast-deep-equal/index.js +var require_fast_deep_equal = __commonJS({ + "node_modules/.pnpm/fast-deep-equal@3.1.3/node_modules/fast-deep-equal/index.js"(exports, module) { + "use strict"; + module.exports = function equal(a5, b6) { + if (a5 === b6) return true; + if (a5 && b6 && typeof a5 == "object" && typeof b6 == "object") { + if (a5.constructor !== b6.constructor) return false; + var length, i5, keys; + if (Array.isArray(a5)) { + length = a5.length; + if (length != b6.length) return false; + for (i5 = length; i5-- !== 0; ) + if (!equal(a5[i5], b6[i5])) return false; + return true; + } + if (a5.constructor === RegExp) return a5.source === b6.source && a5.flags === b6.flags; + if (a5.valueOf !== Object.prototype.valueOf) return a5.valueOf() === b6.valueOf(); + if (a5.toString !== Object.prototype.toString) return a5.toString() === b6.toString(); + keys = Object.keys(a5); + length = keys.length; + if (length !== Object.keys(b6).length) return false; + for (i5 = length; i5-- !== 0; ) + if (!Object.prototype.hasOwnProperty.call(b6, keys[i5])) return false; + for (i5 = length; i5-- !== 0; ) { + var key = keys[i5]; + if (!equal(a5[key], b6[key])) return false; + } + return true; + } + return a5 !== a5 && b6 !== b6; + }; + } +}); + +// node_modules/.pnpm/json-schema-traverse@1.0.0/node_modules/json-schema-traverse/index.js +var require_json_schema_traverse = __commonJS({ + "node_modules/.pnpm/json-schema-traverse@1.0.0/node_modules/json-schema-traverse/index.js"(exports, module) { + "use strict"; + var traverse = module.exports = function(schema2, opts, cb) { + if (typeof opts == "function") { + cb = opts; + opts = {}; + } + cb = opts.cb || cb; + var pre = typeof cb == "function" ? cb : cb.pre || function() { + }; + var post = cb.post || function() { + }; + _traverse(opts, pre, post, schema2, "", schema2); + }; + traverse.keywords = { + additionalItems: true, + items: true, + contains: true, + additionalProperties: true, + propertyNames: true, + not: true, + if: true, + then: true, + else: true + }; + traverse.arrayKeywords = { + items: true, + allOf: true, + anyOf: true, + oneOf: true + }; + traverse.propsKeywords = { + $defs: true, + definitions: true, + properties: true, + patternProperties: true, + dependencies: true + }; + traverse.skipKeywords = { + default: true, + enum: true, + const: true, + required: true, + maximum: true, + minimum: true, + exclusiveMaximum: true, + exclusiveMinimum: true, + multipleOf: true, + maxLength: true, + minLength: true, + pattern: true, + format: true, + maxItems: true, + minItems: true, + uniqueItems: true, + maxProperties: true, + minProperties: true + }; + function _traverse(opts, pre, post, schema2, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) { + if (schema2 && typeof schema2 == "object" && !Array.isArray(schema2)) { + pre(schema2, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); + for (var key in schema2) { + var sch = schema2[key]; + if (Array.isArray(sch)) { + if (key in traverse.arrayKeywords) { + for (var i5 = 0; i5 < sch.length; i5++) + _traverse(opts, pre, post, sch[i5], jsonPtr + "/" + key + "/" + i5, rootSchema, jsonPtr, key, schema2, i5); + } + } else if (key in traverse.propsKeywords) { + if (sch && typeof sch == "object") { + for (var prop in sch) + _traverse(opts, pre, post, sch[prop], jsonPtr + "/" + key + "/" + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema2, prop); + } + } else if (key in traverse.keywords || opts.allKeys && !(key in traverse.skipKeywords)) { + _traverse(opts, pre, post, sch, jsonPtr + "/" + key, rootSchema, jsonPtr, key, schema2); + } + } + post(schema2, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); + } + } + function escapeJsonPtr(str) { + return str.replace(/~/g, "~0").replace(/\//g, "~1"); + } + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/resolve.js +var require_resolve = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/resolve.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getSchemaRefs = exports.resolveUrl = exports.normalizeId = exports._getFullPath = exports.getFullPath = exports.inlineRef = void 0; + var util_1 = require_util(); + var equal = require_fast_deep_equal(); + var traverse = require_json_schema_traverse(); + var SIMPLE_INLINED = /* @__PURE__ */ new Set([ + "type", + "format", + "pattern", + "maxLength", + "minLength", + "maxProperties", + "minProperties", + "maxItems", + "minItems", + "maximum", + "minimum", + "uniqueItems", + "multipleOf", + "required", + "enum", + "const" + ]); + function inlineRef(schema2, limit = true) { + if (typeof schema2 == "boolean") + return true; + if (limit === true) + return !hasRef(schema2); + if (!limit) + return false; + return countKeys(schema2) <= limit; + } + exports.inlineRef = inlineRef; + var REF_KEYWORDS = /* @__PURE__ */ new Set([ + "$ref", + "$recursiveRef", + "$recursiveAnchor", + "$dynamicRef", + "$dynamicAnchor" + ]); + function hasRef(schema2) { + for (const key in schema2) { + if (REF_KEYWORDS.has(key)) + return true; + const sch = schema2[key]; + if (Array.isArray(sch) && sch.some(hasRef)) + return true; + if (typeof sch == "object" && hasRef(sch)) + return true; + } + return false; + } + function countKeys(schema2) { + let count2 = 0; + for (const key in schema2) { + if (key === "$ref") + return Infinity; + count2++; + if (SIMPLE_INLINED.has(key)) + continue; + if (typeof schema2[key] == "object") { + (0, util_1.eachItem)(schema2[key], (sch) => count2 += countKeys(sch)); + } + if (count2 === Infinity) + return Infinity; + } + return count2; + } + function getFullPath(resolver, id = "", normalize2) { + if (normalize2 !== false) + id = normalizeId(id); + const p5 = resolver.parse(id); + return _getFullPath(resolver, p5); + } + exports.getFullPath = getFullPath; + function _getFullPath(resolver, p5) { + const serialized = resolver.serialize(p5); + return serialized.split("#")[0] + "#"; + } + exports._getFullPath = _getFullPath; + var TRAILING_SLASH_HASH = /#\/?$/; + function normalizeId(id) { + return id ? id.replace(TRAILING_SLASH_HASH, "") : ""; + } + exports.normalizeId = normalizeId; + function resolveUrl(resolver, baseId, id) { + id = normalizeId(id); + return resolver.resolve(baseId, id); + } + exports.resolveUrl = resolveUrl; + var ANCHOR = /^[a-z_][-a-z0-9._]*$/i; + function getSchemaRefs(schema2, baseId) { + if (typeof schema2 == "boolean") + return {}; + const { schemaId, uriResolver } = this.opts; + const schId = normalizeId(schema2[schemaId] || baseId); + const baseIds = { "": schId }; + const pathPrefix = getFullPath(uriResolver, schId, false); + const localRefs = {}; + const schemaRefs = /* @__PURE__ */ new Set(); + traverse(schema2, { allKeys: true }, (sch, jsonPtr, _, parentJsonPtr) => { + if (parentJsonPtr === void 0) + return; + const fullPath = pathPrefix + jsonPtr; + let innerBaseId = baseIds[parentJsonPtr]; + if (typeof sch[schemaId] == "string") + innerBaseId = addRef.call(this, sch[schemaId]); + addAnchor.call(this, sch.$anchor); + addAnchor.call(this, sch.$dynamicAnchor); + baseIds[jsonPtr] = innerBaseId; + function addRef(ref) { + const _resolve = this.opts.uriResolver.resolve; + ref = normalizeId(innerBaseId ? _resolve(innerBaseId, ref) : ref); + if (schemaRefs.has(ref)) + throw ambiguos(ref); + schemaRefs.add(ref); + let schOrRef = this.refs[ref]; + if (typeof schOrRef == "string") + schOrRef = this.refs[schOrRef]; + if (typeof schOrRef == "object") { + checkAmbiguosRef(sch, schOrRef.schema, ref); + } else if (ref !== normalizeId(fullPath)) { + if (ref[0] === "#") { + checkAmbiguosRef(sch, localRefs[ref], ref); + localRefs[ref] = sch; + } else { + this.refs[ref] = fullPath; + } + } + return ref; + } + function addAnchor(anchor) { + if (typeof anchor == "string") { + if (!ANCHOR.test(anchor)) + throw new Error(`invalid anchor "${anchor}"`); + addRef.call(this, `#${anchor}`); + } + } + }); + return localRefs; + function checkAmbiguosRef(sch1, sch2, ref) { + if (sch2 !== void 0 && !equal(sch1, sch2)) + throw ambiguos(ref); + } + function ambiguos(ref) { + return new Error(`reference "${ref}" resolves to more than one schema`); + } + } + exports.getSchemaRefs = getSchemaRefs; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/index.js +var require_validate = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/index.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getData = exports.KeywordCxt = exports.validateFunctionCode = void 0; + var boolSchema_1 = require_boolSchema(); + var dataType_1 = require_dataType(); + var applicability_1 = require_applicability(); + var dataType_2 = require_dataType(); + var defaults_1 = require_defaults(); + var keyword_1 = require_keyword(); + var subschema_1 = require_subschema(); + var codegen_1 = require_codegen(); + var names_1 = require_names(); + var resolve_1 = require_resolve(); + var util_1 = require_util(); + var errors_1 = require_errors3(); + function validateFunctionCode(it) { + if (isSchemaObj(it)) { + checkKeywords(it); + if (schemaCxtHasRules(it)) { + topSchemaObjCode(it); + return; + } + } + validateFunction(it, () => (0, boolSchema_1.topBoolOrEmptySchema)(it)); + } + exports.validateFunctionCode = validateFunctionCode; + function validateFunction({ gen, validateName, schema: schema2, schemaEnv, opts }, body) { + if (opts.code.es5) { + gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${names_1.default.valCxt}`, schemaEnv.$async, () => { + gen.code((0, codegen_1._)`"use strict"; ${funcSourceUrl(schema2, opts)}`); + destructureValCxtES5(gen, opts); + gen.code(body); + }); + } else { + gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () => gen.code(funcSourceUrl(schema2, opts)).code(body)); + } + } + function destructureValCxt(opts) { + return (0, codegen_1._)`{${names_1.default.instancePath}="", ${names_1.default.parentData}, ${names_1.default.parentDataProperty}, ${names_1.default.rootData}=${names_1.default.data}${opts.dynamicRef ? (0, codegen_1._)`, ${names_1.default.dynamicAnchors}={}` : codegen_1.nil}}={}`; + } + function destructureValCxtES5(gen, opts) { + gen.if(names_1.default.valCxt, () => { + gen.var(names_1.default.instancePath, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.instancePath}`); + gen.var(names_1.default.parentData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentData}`); + gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentDataProperty}`); + gen.var(names_1.default.rootData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.rootData}`); + if (opts.dynamicRef) + gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.dynamicAnchors}`); + }, () => { + gen.var(names_1.default.instancePath, (0, codegen_1._)`""`); + gen.var(names_1.default.parentData, (0, codegen_1._)`undefined`); + gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`undefined`); + gen.var(names_1.default.rootData, names_1.default.data); + if (opts.dynamicRef) + gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`{}`); + }); + } + function topSchemaObjCode(it) { + const { schema: schema2, opts, gen } = it; + validateFunction(it, () => { + if (opts.$comment && schema2.$comment) + commentKeyword(it); + checkNoDefault(it); + gen.let(names_1.default.vErrors, null); + gen.let(names_1.default.errors, 0); + if (opts.unevaluated) + resetEvaluated(it); + typeAndKeywords(it); + returnResults(it); + }); + return; + } + function resetEvaluated(it) { + const { gen, validateName } = it; + it.evaluated = gen.const("evaluated", (0, codegen_1._)`${validateName}.evaluated`); + gen.if((0, codegen_1._)`${it.evaluated}.dynamicProps`, () => gen.assign((0, codegen_1._)`${it.evaluated}.props`, (0, codegen_1._)`undefined`)); + gen.if((0, codegen_1._)`${it.evaluated}.dynamicItems`, () => gen.assign((0, codegen_1._)`${it.evaluated}.items`, (0, codegen_1._)`undefined`)); + } + function funcSourceUrl(schema2, opts) { + const schId = typeof schema2 == "object" && schema2[opts.schemaId]; + return schId && (opts.code.source || opts.code.process) ? (0, codegen_1._)`/*# sourceURL=${schId} */` : codegen_1.nil; + } + function subschemaCode(it, valid) { + if (isSchemaObj(it)) { + checkKeywords(it); + if (schemaCxtHasRules(it)) { + subSchemaObjCode(it, valid); + return; + } + } + (0, boolSchema_1.boolOrEmptySchema)(it, valid); + } + function schemaCxtHasRules({ schema: schema2, self: self2 }) { + if (typeof schema2 == "boolean") + return !schema2; + for (const key in schema2) + if (self2.RULES.all[key]) + return true; + return false; + } + function isSchemaObj(it) { + return typeof it.schema != "boolean"; + } + function subSchemaObjCode(it, valid) { + const { schema: schema2, gen, opts } = it; + if (opts.$comment && schema2.$comment) + commentKeyword(it); + updateContext(it); + checkAsyncSchema(it); + const errsCount = gen.const("_errs", names_1.default.errors); + typeAndKeywords(it, errsCount); + gen.var(valid, (0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); + } + function checkKeywords(it) { + (0, util_1.checkUnknownRules)(it); + checkRefsAndKeywords(it); + } + function typeAndKeywords(it, errsCount) { + if (it.opts.jtd) + return schemaKeywords(it, [], false, errsCount); + const types2 = (0, dataType_1.getSchemaTypes)(it.schema); + const checkedTypes = (0, dataType_1.coerceAndCheckDataType)(it, types2); + schemaKeywords(it, types2, !checkedTypes, errsCount); + } + function checkRefsAndKeywords(it) { + const { schema: schema2, errSchemaPath, opts, self: self2 } = it; + if (schema2.$ref && opts.ignoreKeywordsWithRef && (0, util_1.schemaHasRulesButRef)(schema2, self2.RULES)) { + self2.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`); + } + } + function checkNoDefault(it) { + const { schema: schema2, opts } = it; + if (schema2.default !== void 0 && opts.useDefaults && opts.strictSchema) { + (0, util_1.checkStrictMode)(it, "default is ignored in the schema root"); + } + } + function updateContext(it) { + const schId = it.schema[it.opts.schemaId]; + if (schId) + it.baseId = (0, resolve_1.resolveUrl)(it.opts.uriResolver, it.baseId, schId); + } + function checkAsyncSchema(it) { + if (it.schema.$async && !it.schemaEnv.$async) + throw new Error("async schema in sync schema"); + } + function commentKeyword({ gen, schemaEnv, schema: schema2, errSchemaPath, opts }) { + const msg = schema2.$comment; + if (opts.$comment === true) { + gen.code((0, codegen_1._)`${names_1.default.self}.logger.log(${msg})`); + } else if (typeof opts.$comment == "function") { + const schemaPath = (0, codegen_1.str)`${errSchemaPath}/$comment`; + const rootName = gen.scopeValue("root", { ref: schemaEnv.root }); + gen.code((0, codegen_1._)`${names_1.default.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`); + } + } + function returnResults(it) { + const { gen, schemaEnv, validateName, ValidationError: ValidationError3, opts } = it; + if (schemaEnv.$async) { + gen.if((0, codegen_1._)`${names_1.default.errors} === 0`, () => gen.return(names_1.default.data), () => gen.throw((0, codegen_1._)`new ${ValidationError3}(${names_1.default.vErrors})`)); + } else { + gen.assign((0, codegen_1._)`${validateName}.errors`, names_1.default.vErrors); + if (opts.unevaluated) + assignEvaluated(it); + gen.return((0, codegen_1._)`${names_1.default.errors} === 0`); + } + } + function assignEvaluated({ gen, evaluated, props, items }) { + if (props instanceof codegen_1.Name) + gen.assign((0, codegen_1._)`${evaluated}.props`, props); + if (items instanceof codegen_1.Name) + gen.assign((0, codegen_1._)`${evaluated}.items`, items); + } + function schemaKeywords(it, types2, typeErrors, errsCount) { + const { gen, schema: schema2, data: data2, allErrors, opts, self: self2 } = it; + const { RULES } = self2; + if (schema2.$ref && (opts.ignoreKeywordsWithRef || !(0, util_1.schemaHasRulesButRef)(schema2, RULES))) { + gen.block(() => keywordCode(it, "$ref", RULES.all.$ref.definition)); + return; + } + if (!opts.jtd) + checkStrictTypes(it, types2); + gen.block(() => { + for (const group of RULES.rules) + groupKeywords(group); + groupKeywords(RULES.post); + }); + function groupKeywords(group) { + if (!(0, applicability_1.shouldUseGroup)(schema2, group)) + return; + if (group.type) { + gen.if((0, dataType_2.checkDataType)(group.type, data2, opts.strictNumbers)); + iterateKeywords(it, group); + if (types2.length === 1 && types2[0] === group.type && typeErrors) { + gen.else(); + (0, dataType_2.reportTypeError)(it); + } + gen.endIf(); + } else { + iterateKeywords(it, group); + } + if (!allErrors) + gen.if((0, codegen_1._)`${names_1.default.errors} === ${errsCount || 0}`); + } + } + function iterateKeywords(it, group) { + const { gen, schema: schema2, opts: { useDefaults } } = it; + if (useDefaults) + (0, defaults_1.assignDefaults)(it, group.type); + gen.block(() => { + for (const rule of group.rules) { + if ((0, applicability_1.shouldUseRule)(schema2, rule)) { + keywordCode(it, rule.keyword, rule.definition, group.type); + } + } + }); + } + function checkStrictTypes(it, types2) { + if (it.schemaEnv.meta || !it.opts.strictTypes) + return; + checkContextTypes(it, types2); + if (!it.opts.allowUnionTypes) + checkMultipleTypes(it, types2); + checkKeywordTypes(it, it.dataTypes); + } + function checkContextTypes(it, types2) { + if (!types2.length) + return; + if (!it.dataTypes.length) { + it.dataTypes = types2; + return; + } + types2.forEach((t5) => { + if (!includesType(it.dataTypes, t5)) { + strictTypesError(it, `type "${t5}" not allowed by context "${it.dataTypes.join(",")}"`); + } + }); + narrowSchemaTypes(it, types2); + } + function checkMultipleTypes(it, ts) { + if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) { + strictTypesError(it, "use allowUnionTypes to allow union type keyword"); + } + } + function checkKeywordTypes(it, ts) { + const rules = it.self.RULES.all; + for (const keyword in rules) { + const rule = rules[keyword]; + if (typeof rule == "object" && (0, applicability_1.shouldUseRule)(it.schema, rule)) { + const { type } = rule.definition; + if (type.length && !type.some((t5) => hasApplicableType(ts, t5))) { + strictTypesError(it, `missing type "${type.join(",")}" for keyword "${keyword}"`); + } + } + } + } + function hasApplicableType(schTs, kwdT) { + return schTs.includes(kwdT) || kwdT === "number" && schTs.includes("integer"); + } + function includesType(ts, t5) { + return ts.includes(t5) || t5 === "integer" && ts.includes("number"); + } + function narrowSchemaTypes(it, withTypes) { + const ts = []; + for (const t5 of it.dataTypes) { + if (includesType(withTypes, t5)) + ts.push(t5); + else if (withTypes.includes("integer") && t5 === "number") + ts.push("integer"); + } + it.dataTypes = ts; + } + function strictTypesError(it, msg) { + const schemaPath = it.schemaEnv.baseId + it.errSchemaPath; + msg += ` at "${schemaPath}" (strictTypes)`; + (0, util_1.checkStrictMode)(it, msg, it.opts.strictTypes); + } + var KeywordCxt = class { + constructor(it, def, keyword) { + (0, keyword_1.validateKeywordUsage)(it, def, keyword); + this.gen = it.gen; + this.allErrors = it.allErrors; + this.keyword = keyword; + this.data = it.data; + this.schema = it.schema[keyword]; + this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data; + this.schemaValue = (0, util_1.schemaRefOrVal)(it, this.schema, keyword, this.$data); + this.schemaType = def.schemaType; + this.parentSchema = it.schema; + this.params = {}; + this.it = it; + this.def = def; + if (this.$data) { + this.schemaCode = it.gen.const("vSchema", getData(this.$data, it)); + } else { + this.schemaCode = this.schemaValue; + if (!(0, keyword_1.validSchemaType)(this.schema, def.schemaType, def.allowUndefined)) { + throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`); + } + } + if ("code" in def ? def.trackErrors : def.errors !== false) { + this.errsCount = it.gen.const("_errs", names_1.default.errors); + } + } + result(condition, successAction, failAction) { + this.failResult((0, codegen_1.not)(condition), successAction, failAction); + } + failResult(condition, successAction, failAction) { + this.gen.if(condition); + if (failAction) + failAction(); + else + this.error(); + if (successAction) { + this.gen.else(); + successAction(); + if (this.allErrors) + this.gen.endIf(); + } else { + if (this.allErrors) + this.gen.endIf(); + else + this.gen.else(); + } + } + pass(condition, failAction) { + this.failResult((0, codegen_1.not)(condition), void 0, failAction); + } + fail(condition) { + if (condition === void 0) { + this.error(); + if (!this.allErrors) + this.gen.if(false); + return; + } + this.gen.if(condition); + this.error(); + if (this.allErrors) + this.gen.endIf(); + else + this.gen.else(); + } + fail$data(condition) { + if (!this.$data) + return this.fail(condition); + const { schemaCode } = this; + this.fail((0, codegen_1._)`${schemaCode} !== undefined && (${(0, codegen_1.or)(this.invalid$data(), condition)})`); + } + error(append, errorParams, errorPaths) { + if (errorParams) { + this.setParams(errorParams); + this._error(append, errorPaths); + this.setParams({}); + return; + } + this._error(append, errorPaths); + } + _error(append, errorPaths) { + ; + (append ? errors_1.reportExtraError : errors_1.reportError)(this, this.def.error, errorPaths); + } + $dataError() { + (0, errors_1.reportError)(this, this.def.$dataError || errors_1.keyword$DataError); + } + reset() { + if (this.errsCount === void 0) + throw new Error('add "trackErrors" to keyword definition'); + (0, errors_1.resetErrorsCount)(this.gen, this.errsCount); + } + ok(cond) { + if (!this.allErrors) + this.gen.if(cond); + } + setParams(obj, assign) { + if (assign) + Object.assign(this.params, obj); + else + this.params = obj; + } + block$data(valid, codeBlock, $dataValid = codegen_1.nil) { + this.gen.block(() => { + this.check$data(valid, $dataValid); + codeBlock(); + }); + } + check$data(valid = codegen_1.nil, $dataValid = codegen_1.nil) { + if (!this.$data) + return; + const { gen, schemaCode, schemaType, def } = this; + gen.if((0, codegen_1.or)((0, codegen_1._)`${schemaCode} === undefined`, $dataValid)); + if (valid !== codegen_1.nil) + gen.assign(valid, true); + if (schemaType.length || def.validateSchema) { + gen.elseIf(this.invalid$data()); + this.$dataError(); + if (valid !== codegen_1.nil) + gen.assign(valid, false); + } + gen.else(); + } + invalid$data() { + const { gen, schemaCode, schemaType, def, it } = this; + return (0, codegen_1.or)(wrong$DataType(), invalid$DataSchema()); + function wrong$DataType() { + if (schemaType.length) { + if (!(schemaCode instanceof codegen_1.Name)) + throw new Error("ajv implementation error"); + const st = Array.isArray(schemaType) ? schemaType : [schemaType]; + return (0, codegen_1._)`${(0, dataType_2.checkDataTypes)(st, schemaCode, it.opts.strictNumbers, dataType_2.DataType.Wrong)}`; + } + return codegen_1.nil; + } + function invalid$DataSchema() { + if (def.validateSchema) { + const validateSchemaRef = gen.scopeValue("validate$data", { ref: def.validateSchema }); + return (0, codegen_1._)`!${validateSchemaRef}(${schemaCode})`; + } + return codegen_1.nil; + } + } + subschema(appl, valid) { + const subschema = (0, subschema_1.getSubschema)(this.it, appl); + (0, subschema_1.extendSubschemaData)(subschema, this.it, appl); + (0, subschema_1.extendSubschemaMode)(subschema, appl); + const nextContext = { ...this.it, ...subschema, items: void 0, props: void 0 }; + subschemaCode(nextContext, valid); + return nextContext; + } + mergeEvaluated(schemaCxt, toName) { + const { it, gen } = this; + if (!it.opts.unevaluated) + return; + if (it.props !== true && schemaCxt.props !== void 0) { + it.props = util_1.mergeEvaluated.props(gen, schemaCxt.props, it.props, toName); + } + if (it.items !== true && schemaCxt.items !== void 0) { + it.items = util_1.mergeEvaluated.items(gen, schemaCxt.items, it.items, toName); + } + } + mergeValidEvaluated(schemaCxt, valid) { + const { it, gen } = this; + if (it.opts.unevaluated && (it.props !== true || it.items !== true)) { + gen.if(valid, () => this.mergeEvaluated(schemaCxt, codegen_1.Name)); + return true; + } + } + }; + exports.KeywordCxt = KeywordCxt; + function keywordCode(it, keyword, def, ruleType) { + const cxt = new KeywordCxt(it, def, keyword); + if ("code" in def) { + def.code(cxt, ruleType); + } else if (cxt.$data && def.validate) { + (0, keyword_1.funcKeywordCode)(cxt, def); + } else if ("macro" in def) { + (0, keyword_1.macroKeywordCode)(cxt, def); + } else if (def.compile || def.validate) { + (0, keyword_1.funcKeywordCode)(cxt, def); + } + } + var JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/; + var RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/; + function getData($data, { dataLevel, dataNames, dataPathArr }) { + let jsonPointer; + let data2; + if ($data === "") + return names_1.default.rootData; + if ($data[0] === "/") { + if (!JSON_POINTER.test($data)) + throw new Error(`Invalid JSON-pointer: ${$data}`); + jsonPointer = $data; + data2 = names_1.default.rootData; + } else { + const matches = RELATIVE_JSON_POINTER.exec($data); + if (!matches) + throw new Error(`Invalid JSON-pointer: ${$data}`); + const up = +matches[1]; + jsonPointer = matches[2]; + if (jsonPointer === "#") { + if (up >= dataLevel) + throw new Error(errorMsg("property/index", up)); + return dataPathArr[dataLevel - up]; + } + if (up > dataLevel) + throw new Error(errorMsg("data", up)); + data2 = dataNames[dataLevel - up]; + if (!jsonPointer) + return data2; + } + let expr = data2; + const segments = jsonPointer.split("/"); + for (const segment of segments) { + if (segment) { + data2 = (0, codegen_1._)`${data2}${(0, codegen_1.getProperty)((0, util_1.unescapeJsonPointer)(segment))}`; + expr = (0, codegen_1._)`${expr} && ${data2}`; + } + } + return expr; + function errorMsg(pointerType, up) { + return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`; + } + } + exports.getData = getData; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/validation_error.js +var require_validation_error = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/validation_error.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var ValidationError3 = class extends Error { + constructor(errors) { + super("validation failed"); + this.errors = errors; + this.ajv = this.validation = true; + } + }; + exports.default = ValidationError3; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/ref_error.js +var require_ref_error = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/ref_error.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var resolve_1 = require_resolve(); + var MissingRefError = class extends Error { + constructor(resolver, baseId, ref, msg) { + super(msg || `can't resolve reference ${ref} from id ${baseId}`); + this.missingRef = (0, resolve_1.resolveUrl)(resolver, baseId, ref); + this.missingSchema = (0, resolve_1.normalizeId)((0, resolve_1.getFullPath)(resolver, this.missingRef)); + } + }; + exports.default = MissingRefError; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/index.js +var require_compile = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/index.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.resolveSchema = exports.getCompilingSchema = exports.resolveRef = exports.compileSchema = exports.SchemaEnv = void 0; + var codegen_1 = require_codegen(); + var validation_error_1 = require_validation_error(); + var names_1 = require_names(); + var resolve_1 = require_resolve(); + var util_1 = require_util(); + var validate_1 = require_validate(); + var SchemaEnv = class { + constructor(env2) { + var _a6; + this.refs = {}; + this.dynamicAnchors = {}; + let schema2; + if (typeof env2.schema == "object") + schema2 = env2.schema; + this.schema = env2.schema; + this.schemaId = env2.schemaId; + this.root = env2.root || this; + this.baseId = (_a6 = env2.baseId) !== null && _a6 !== void 0 ? _a6 : (0, resolve_1.normalizeId)(schema2 === null || schema2 === void 0 ? void 0 : schema2[env2.schemaId || "$id"]); + this.schemaPath = env2.schemaPath; + this.localRefs = env2.localRefs; + this.meta = env2.meta; + this.$async = schema2 === null || schema2 === void 0 ? void 0 : schema2.$async; + this.refs = {}; + } + }; + exports.SchemaEnv = SchemaEnv; + function compileSchema(sch) { + const _sch = getCompilingSchema.call(this, sch); + if (_sch) + return _sch; + const rootId = (0, resolve_1.getFullPath)(this.opts.uriResolver, sch.root.baseId); + const { es5, lines } = this.opts.code; + const { ownProperties } = this.opts; + const gen = new codegen_1.CodeGen(this.scope, { es5, lines, ownProperties }); + let _ValidationError2; + if (sch.$async) { + _ValidationError2 = gen.scopeValue("Error", { + ref: validation_error_1.default, + code: (0, codegen_1._)`require("ajv/dist/runtime/validation_error").default` + }); + } + const validateName = gen.scopeName("validate"); + sch.validateName = validateName; + const schemaCxt = { + gen, + allErrors: this.opts.allErrors, + data: names_1.default.data, + parentData: names_1.default.parentData, + parentDataProperty: names_1.default.parentDataProperty, + dataNames: [names_1.default.data], + dataPathArr: [codegen_1.nil], + // TODO can its length be used as dataLevel if nil is removed? + dataLevel: 0, + dataTypes: [], + definedProperties: /* @__PURE__ */ new Set(), + topSchemaRef: gen.scopeValue("schema", this.opts.code.source === true ? { ref: sch.schema, code: (0, codegen_1.stringify)(sch.schema) } : { ref: sch.schema }), + validateName, + ValidationError: _ValidationError2, + schema: sch.schema, + schemaEnv: sch, + rootId, + baseId: sch.baseId || rootId, + schemaPath: codegen_1.nil, + errSchemaPath: sch.schemaPath || (this.opts.jtd ? "" : "#"), + errorPath: (0, codegen_1._)`""`, + opts: this.opts, + self: this + }; + let sourceCode; + try { + this._compilations.add(sch); + (0, validate_1.validateFunctionCode)(schemaCxt); + gen.optimize(this.opts.code.optimize); + const validateCode = gen.toString(); + sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${validateCode}`; + if (this.opts.code.process) + sourceCode = this.opts.code.process(sourceCode, sch); + const makeValidate = new Function(`${names_1.default.self}`, `${names_1.default.scope}`, sourceCode); + const validate2 = makeValidate(this, this.scope.get()); + this.scope.value(validateName, { ref: validate2 }); + validate2.errors = null; + validate2.schema = sch.schema; + validate2.schemaEnv = sch; + if (sch.$async) + validate2.$async = true; + if (this.opts.code.source === true) { + validate2.source = { validateName, validateCode, scopeValues: gen._values }; + } + if (this.opts.unevaluated) { + const { props, items } = schemaCxt; + validate2.evaluated = { + props: props instanceof codegen_1.Name ? void 0 : props, + items: items instanceof codegen_1.Name ? void 0 : items, + dynamicProps: props instanceof codegen_1.Name, + dynamicItems: items instanceof codegen_1.Name + }; + if (validate2.source) + validate2.source.evaluated = (0, codegen_1.stringify)(validate2.evaluated); + } + sch.validate = validate2; + return sch; + } catch (e5) { + delete sch.validate; + delete sch.validateName; + if (sourceCode) + this.logger.error("Error compiling schema, function code:", sourceCode); + throw e5; + } finally { + this._compilations.delete(sch); + } + } + exports.compileSchema = compileSchema; + function resolveRef2(root, baseId, ref) { + var _a6; + ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, ref); + const schOrFunc = root.refs[ref]; + if (schOrFunc) + return schOrFunc; + let _sch = resolve4.call(this, root, ref); + if (_sch === void 0) { + const schema2 = (_a6 = root.localRefs) === null || _a6 === void 0 ? void 0 : _a6[ref]; + const { schemaId } = this.opts; + if (schema2) + _sch = new SchemaEnv({ schema: schema2, schemaId, root, baseId }); + } + if (_sch === void 0) + return; + return root.refs[ref] = inlineOrCompile.call(this, _sch); + } + exports.resolveRef = resolveRef2; + function inlineOrCompile(sch) { + if ((0, resolve_1.inlineRef)(sch.schema, this.opts.inlineRefs)) + return sch.schema; + return sch.validate ? sch : compileSchema.call(this, sch); + } + function getCompilingSchema(schEnv) { + for (const sch of this._compilations) { + if (sameSchemaEnv(sch, schEnv)) + return sch; + } + } + exports.getCompilingSchema = getCompilingSchema; + function sameSchemaEnv(s1, s22) { + return s1.schema === s22.schema && s1.root === s22.root && s1.baseId === s22.baseId; + } + function resolve4(root, ref) { + let sch; + while (typeof (sch = this.refs[ref]) == "string") + ref = sch; + return sch || this.schemas[ref] || resolveSchema.call(this, root, ref); + } + function resolveSchema(root, ref) { + const p5 = this.opts.uriResolver.parse(ref); + const refPath = (0, resolve_1._getFullPath)(this.opts.uriResolver, p5); + let baseId = (0, resolve_1.getFullPath)(this.opts.uriResolver, root.baseId, void 0); + if (Object.keys(root.schema).length > 0 && refPath === baseId) { + return getJsonPointer.call(this, p5, root); + } + const id = (0, resolve_1.normalizeId)(refPath); + const schOrRef = this.refs[id] || this.schemas[id]; + if (typeof schOrRef == "string") { + const sch = resolveSchema.call(this, root, schOrRef); + if (typeof (sch === null || sch === void 0 ? void 0 : sch.schema) !== "object") + return; + return getJsonPointer.call(this, p5, sch); + } + if (typeof (schOrRef === null || schOrRef === void 0 ? void 0 : schOrRef.schema) !== "object") + return; + if (!schOrRef.validate) + compileSchema.call(this, schOrRef); + if (id === (0, resolve_1.normalizeId)(ref)) { + const { schema: schema2 } = schOrRef; + const { schemaId } = this.opts; + const schId = schema2[schemaId]; + if (schId) + baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); + return new SchemaEnv({ schema: schema2, schemaId, root, baseId }); + } + return getJsonPointer.call(this, p5, schOrRef); + } + exports.resolveSchema = resolveSchema; + var PREVENT_SCOPE_CHANGE = /* @__PURE__ */ new Set([ + "properties", + "patternProperties", + "enum", + "dependencies", + "definitions" + ]); + function getJsonPointer(parsedRef, { baseId, schema: schema2, root }) { + var _a6; + if (((_a6 = parsedRef.fragment) === null || _a6 === void 0 ? void 0 : _a6[0]) !== "/") + return; + for (const part of parsedRef.fragment.slice(1).split("/")) { + if (typeof schema2 === "boolean") + return; + const partSchema = schema2[(0, util_1.unescapeFragment)(part)]; + if (partSchema === void 0) + return; + schema2 = partSchema; + const schId = typeof schema2 === "object" && schema2[this.opts.schemaId]; + if (!PREVENT_SCOPE_CHANGE.has(part) && schId) { + baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); + } + } + let env2; + if (typeof schema2 != "boolean" && schema2.$ref && !(0, util_1.schemaHasRulesButRef)(schema2, this.RULES)) { + const $ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schema2.$ref); + env2 = resolveSchema.call(this, root, $ref); + } + const { schemaId } = this.opts; + env2 = env2 || new SchemaEnv({ schema: schema2, schemaId, root, baseId }); + if (env2.schema !== env2.root.schema) + return env2; + return void 0; + } + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/data.json +var require_data = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/data.json"(exports, module) { + module.exports = { + $id: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#", + description: "Meta-schema for $data reference (JSON AnySchema extension proposal)", + type: "object", + required: ["$data"], + properties: { + $data: { + type: "string", + anyOf: [{ format: "relative-json-pointer" }, { format: "json-pointer" }] + } + }, + additionalProperties: false + }; + } +}); + +// node_modules/.pnpm/fast-uri@3.1.0/node_modules/fast-uri/lib/utils.js +var require_utils5 = __commonJS({ + "node_modules/.pnpm/fast-uri@3.1.0/node_modules/fast-uri/lib/utils.js"(exports, module) { + "use strict"; + var isUUID = RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu); + var isIPv4 = RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u); + function stringArrayToHexStripped(input) { + let acc = ""; + let code = 0; + let i5 = 0; + for (i5 = 0; i5 < input.length; i5++) { + code = input[i5].charCodeAt(0); + if (code === 48) { + continue; + } + if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) { + return ""; + } + acc += input[i5]; + break; + } + for (i5 += 1; i5 < input.length; i5++) { + code = input[i5].charCodeAt(0); + if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) { + return ""; + } + acc += input[i5]; + } + return acc; + } + var nonSimpleDomain = RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u); + function consumeIsZone(buffer2) { + buffer2.length = 0; + return true; + } + function consumeHextets(buffer2, address, output) { + if (buffer2.length) { + const hex4 = stringArrayToHexStripped(buffer2); + if (hex4 !== "") { + address.push(hex4); + } else { + output.error = true; + return false; + } + buffer2.length = 0; + } + return true; + } + function getIPV6(input) { + let tokenCount = 0; + const output = { error: false, address: "", zone: "" }; + const address = []; + const buffer2 = []; + let endipv6Encountered = false; + let endIpv6 = false; + let consume = consumeHextets; + for (let i5 = 0; i5 < input.length; i5++) { + const cursor2 = input[i5]; + if (cursor2 === "[" || cursor2 === "]") { + continue; + } + if (cursor2 === ":") { + if (endipv6Encountered === true) { + endIpv6 = true; + } + if (!consume(buffer2, address, output)) { + break; + } + if (++tokenCount > 7) { + output.error = true; + break; + } + if (i5 > 0 && input[i5 - 1] === ":") { + endipv6Encountered = true; + } + address.push(":"); + continue; + } else if (cursor2 === "%") { + if (!consume(buffer2, address, output)) { + break; + } + consume = consumeIsZone; + } else { + buffer2.push(cursor2); + continue; + } + } + if (buffer2.length) { + if (consume === consumeIsZone) { + output.zone = buffer2.join(""); + } else if (endIpv6) { + address.push(buffer2.join("")); + } else { + address.push(stringArrayToHexStripped(buffer2)); + } + } + output.address = address.join(""); + return output; + } + function normalizeIPv62(host) { + if (findToken(host, ":") < 2) { + return { host, isIPV6: false }; + } + const ipv63 = getIPV6(host); + if (!ipv63.error) { + let newHost = ipv63.address; + let escapedHost = ipv63.address; + if (ipv63.zone) { + newHost += "%" + ipv63.zone; + escapedHost += "%25" + ipv63.zone; + } + return { host: newHost, isIPV6: true, escapedHost }; + } else { + return { host, isIPV6: false }; + } + } + function findToken(str, token) { + let ind = 0; + for (let i5 = 0; i5 < str.length; i5++) { + if (str[i5] === token) ind++; + } + return ind; + } + function removeDotSegments(path53) { + let input = path53; + const output = []; + let nextSlash = -1; + let len = 0; + while (len = input.length) { + if (len === 1) { + if (input === ".") { + break; + } else if (input === "/") { + output.push("/"); + break; + } else { + output.push(input); + break; + } + } else if (len === 2) { + if (input[0] === ".") { + if (input[1] === ".") { + break; + } else if (input[1] === "/") { + input = input.slice(2); + continue; + } + } else if (input[0] === "/") { + if (input[1] === "." || input[1] === "/") { + output.push("/"); + break; + } + } + } else if (len === 3) { + if (input === "/..") { + if (output.length !== 0) { + output.pop(); + } + output.push("/"); + break; + } + } + if (input[0] === ".") { + if (input[1] === ".") { + if (input[2] === "/") { + input = input.slice(3); + continue; + } + } else if (input[1] === "/") { + input = input.slice(2); + continue; + } + } else if (input[0] === "/") { + if (input[1] === ".") { + if (input[2] === "/") { + input = input.slice(2); + continue; + } else if (input[2] === ".") { + if (input[3] === "/") { + input = input.slice(3); + if (output.length !== 0) { + output.pop(); + } + continue; + } + } + } + } + if ((nextSlash = input.indexOf("/", 1)) === -1) { + output.push(input); + break; + } else { + output.push(input.slice(0, nextSlash)); + input = input.slice(nextSlash); + } + } + return output.join(""); + } + function normalizeComponentEncoding(component, esc2) { + const func = esc2 !== true ? escape : unescape; + if (component.scheme !== void 0) { + component.scheme = func(component.scheme); + } + if (component.userinfo !== void 0) { + component.userinfo = func(component.userinfo); + } + if (component.host !== void 0) { + component.host = func(component.host); + } + if (component.path !== void 0) { + component.path = func(component.path); + } + if (component.query !== void 0) { + component.query = func(component.query); + } + if (component.fragment !== void 0) { + component.fragment = func(component.fragment); + } + return component; + } + function recomposeAuthority(component) { + const uriTokens = []; + if (component.userinfo !== void 0) { + uriTokens.push(component.userinfo); + uriTokens.push("@"); + } + if (component.host !== void 0) { + let host = unescape(component.host); + if (!isIPv4(host)) { + const ipV6res = normalizeIPv62(host); + if (ipV6res.isIPV6 === true) { + host = `[${ipV6res.escapedHost}]`; + } else { + host = component.host; + } + } + uriTokens.push(host); + } + if (typeof component.port === "number" || typeof component.port === "string") { + uriTokens.push(":"); + uriTokens.push(String(component.port)); + } + return uriTokens.length ? uriTokens.join("") : void 0; + } + module.exports = { + nonSimpleDomain, + recomposeAuthority, + normalizeComponentEncoding, + removeDotSegments, + isIPv4, + isUUID, + normalizeIPv6: normalizeIPv62, + stringArrayToHexStripped + }; + } +}); + +// node_modules/.pnpm/fast-uri@3.1.0/node_modules/fast-uri/lib/schemes.js +var require_schemes = __commonJS({ + "node_modules/.pnpm/fast-uri@3.1.0/node_modules/fast-uri/lib/schemes.js"(exports, module) { + "use strict"; + var { isUUID } = require_utils5(); + var URN_REG = /([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu; + var supportedSchemeNames = ( + /** @type {const} */ + [ + "http", + "https", + "ws", + "wss", + "urn", + "urn:uuid" + ] + ); + function isValidSchemeName(name) { + return supportedSchemeNames.indexOf( + /** @type {*} */ + name + ) !== -1; + } + function wsIsSecure(wsComponent) { + if (wsComponent.secure === true) { + return true; + } else if (wsComponent.secure === false) { + return false; + } else if (wsComponent.scheme) { + return wsComponent.scheme.length === 3 && (wsComponent.scheme[0] === "w" || wsComponent.scheme[0] === "W") && (wsComponent.scheme[1] === "s" || wsComponent.scheme[1] === "S") && (wsComponent.scheme[2] === "s" || wsComponent.scheme[2] === "S"); + } else { + return false; + } + } + function httpParse(component) { + if (!component.host) { + component.error = component.error || "HTTP URIs must have a host."; + } + return component; + } + function httpSerialize(component) { + const secure = String(component.scheme).toLowerCase() === "https"; + if (component.port === (secure ? 443 : 80) || component.port === "") { + component.port = void 0; + } + if (!component.path) { + component.path = "/"; + } + return component; + } + function wsParse(wsComponent) { + wsComponent.secure = wsIsSecure(wsComponent); + wsComponent.resourceName = (wsComponent.path || "/") + (wsComponent.query ? "?" + wsComponent.query : ""); + wsComponent.path = void 0; + wsComponent.query = void 0; + return wsComponent; + } + function wsSerialize(wsComponent) { + if (wsComponent.port === (wsIsSecure(wsComponent) ? 443 : 80) || wsComponent.port === "") { + wsComponent.port = void 0; + } + if (typeof wsComponent.secure === "boolean") { + wsComponent.scheme = wsComponent.secure ? "wss" : "ws"; + wsComponent.secure = void 0; + } + if (wsComponent.resourceName) { + const [path53, query] = wsComponent.resourceName.split("?"); + wsComponent.path = path53 && path53 !== "/" ? path53 : void 0; + wsComponent.query = query; + wsComponent.resourceName = void 0; + } + wsComponent.fragment = void 0; + return wsComponent; + } + function urnParse(urnComponent, options) { + if (!urnComponent.path) { + urnComponent.error = "URN can not be parsed"; + return urnComponent; + } + const matches = urnComponent.path.match(URN_REG); + if (matches) { + const scheme = options.scheme || urnComponent.scheme || "urn"; + urnComponent.nid = matches[1].toLowerCase(); + urnComponent.nss = matches[2]; + const urnScheme = `${scheme}:${options.nid || urnComponent.nid}`; + const schemeHandler = getSchemeHandler(urnScheme); + urnComponent.path = void 0; + if (schemeHandler) { + urnComponent = schemeHandler.parse(urnComponent, options); + } + } else { + urnComponent.error = urnComponent.error || "URN can not be parsed."; + } + return urnComponent; + } + function urnSerialize(urnComponent, options) { + if (urnComponent.nid === void 0) { + throw new Error("URN without nid cannot be serialized"); + } + const scheme = options.scheme || urnComponent.scheme || "urn"; + const nid = urnComponent.nid.toLowerCase(); + const urnScheme = `${scheme}:${options.nid || nid}`; + const schemeHandler = getSchemeHandler(urnScheme); + if (schemeHandler) { + urnComponent = schemeHandler.serialize(urnComponent, options); + } + const uriComponent = urnComponent; + const nss = urnComponent.nss; + uriComponent.path = `${nid || options.nid}:${nss}`; + options.skipEscape = true; + return uriComponent; + } + function urnuuidParse(urnComponent, options) { + const uuidComponent = urnComponent; + uuidComponent.uuid = uuidComponent.nss; + uuidComponent.nss = void 0; + if (!options.tolerant && (!uuidComponent.uuid || !isUUID(uuidComponent.uuid))) { + uuidComponent.error = uuidComponent.error || "UUID is not valid."; + } + return uuidComponent; + } + function urnuuidSerialize(uuidComponent) { + const urnComponent = uuidComponent; + urnComponent.nss = (uuidComponent.uuid || "").toLowerCase(); + return urnComponent; + } + var http = ( + /** @type {SchemeHandler} */ + { + scheme: "http", + domainHost: true, + parse: httpParse, + serialize: httpSerialize + } + ); + var https = ( + /** @type {SchemeHandler} */ + { + scheme: "https", + domainHost: http.domainHost, + parse: httpParse, + serialize: httpSerialize + } + ); + var ws = ( + /** @type {SchemeHandler} */ + { + scheme: "ws", + domainHost: true, + parse: wsParse, + serialize: wsSerialize + } + ); + var wss = ( + /** @type {SchemeHandler} */ + { + scheme: "wss", + domainHost: ws.domainHost, + parse: ws.parse, + serialize: ws.serialize + } + ); + var urn = ( + /** @type {SchemeHandler} */ + { + scheme: "urn", + parse: urnParse, + serialize: urnSerialize, + skipNormalize: true + } + ); + var urnuuid = ( + /** @type {SchemeHandler} */ + { + scheme: "urn:uuid", + parse: urnuuidParse, + serialize: urnuuidSerialize, + skipNormalize: true + } + ); + var SCHEMES = ( + /** @type {Record} */ + { + http, + https, + ws, + wss, + urn, + "urn:uuid": urnuuid + } + ); + Object.setPrototypeOf(SCHEMES, null); + function getSchemeHandler(scheme) { + return scheme && (SCHEMES[ + /** @type {SchemeName} */ + scheme + ] || SCHEMES[ + /** @type {SchemeName} */ + scheme.toLowerCase() + ]) || void 0; + } + module.exports = { + wsIsSecure, + SCHEMES, + isValidSchemeName, + getSchemeHandler + }; + } +}); + +// node_modules/.pnpm/fast-uri@3.1.0/node_modules/fast-uri/index.js +var require_fast_uri = __commonJS({ + "node_modules/.pnpm/fast-uri@3.1.0/node_modules/fast-uri/index.js"(exports, module) { + "use strict"; + var { normalizeIPv6: normalizeIPv62, removeDotSegments, recomposeAuthority, normalizeComponentEncoding, isIPv4, nonSimpleDomain } = require_utils5(); + var { SCHEMES, getSchemeHandler } = require_schemes(); + function normalize2(uri, options) { + if (typeof uri === "string") { + uri = /** @type {T} */ + serialize(parse5(uri, options), options); + } else if (typeof uri === "object") { + uri = /** @type {T} */ + parse5(serialize(uri, options), options); + } + return uri; + } + function resolve4(baseURI, relativeURI, options) { + const schemelessOptions = options ? Object.assign({ scheme: "null" }, options) : { scheme: "null" }; + const resolved = resolveComponent(parse5(baseURI, schemelessOptions), parse5(relativeURI, schemelessOptions), schemelessOptions, true); + schemelessOptions.skipEscape = true; + return serialize(resolved, schemelessOptions); + } + function resolveComponent(base, relative3, options, skipNormalization) { + const target = {}; + if (!skipNormalization) { + base = parse5(serialize(base, options), options); + relative3 = parse5(serialize(relative3, options), options); + } + options = options || {}; + if (!options.tolerant && relative3.scheme) { + target.scheme = relative3.scheme; + target.userinfo = relative3.userinfo; + target.host = relative3.host; + target.port = relative3.port; + target.path = removeDotSegments(relative3.path || ""); + target.query = relative3.query; + } else { + if (relative3.userinfo !== void 0 || relative3.host !== void 0 || relative3.port !== void 0) { + target.userinfo = relative3.userinfo; + target.host = relative3.host; + target.port = relative3.port; + target.path = removeDotSegments(relative3.path || ""); + target.query = relative3.query; + } else { + if (!relative3.path) { + target.path = base.path; + if (relative3.query !== void 0) { + target.query = relative3.query; + } else { + target.query = base.query; + } + } else { + if (relative3.path[0] === "/") { + target.path = removeDotSegments(relative3.path); + } else { + if ((base.userinfo !== void 0 || base.host !== void 0 || base.port !== void 0) && !base.path) { + target.path = "/" + relative3.path; + } else if (!base.path) { + target.path = relative3.path; + } else { + target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative3.path; + } + target.path = removeDotSegments(target.path); + } + target.query = relative3.query; + } + target.userinfo = base.userinfo; + target.host = base.host; + target.port = base.port; + } + target.scheme = base.scheme; + } + target.fragment = relative3.fragment; + return target; + } + function equal(uriA, uriB, options) { + if (typeof uriA === "string") { + uriA = unescape(uriA); + uriA = serialize(normalizeComponentEncoding(parse5(uriA, options), true), { ...options, skipEscape: true }); + } else if (typeof uriA === "object") { + uriA = serialize(normalizeComponentEncoding(uriA, true), { ...options, skipEscape: true }); + } + if (typeof uriB === "string") { + uriB = unescape(uriB); + uriB = serialize(normalizeComponentEncoding(parse5(uriB, options), true), { ...options, skipEscape: true }); + } else if (typeof uriB === "object") { + uriB = serialize(normalizeComponentEncoding(uriB, true), { ...options, skipEscape: true }); + } + return uriA.toLowerCase() === uriB.toLowerCase(); + } + function serialize(cmpts, opts) { + const component = { + host: cmpts.host, + scheme: cmpts.scheme, + userinfo: cmpts.userinfo, + port: cmpts.port, + path: cmpts.path, + query: cmpts.query, + nid: cmpts.nid, + nss: cmpts.nss, + uuid: cmpts.uuid, + fragment: cmpts.fragment, + reference: cmpts.reference, + resourceName: cmpts.resourceName, + secure: cmpts.secure, + error: "" + }; + const options = Object.assign({}, opts); + const uriTokens = []; + const schemeHandler = getSchemeHandler(options.scheme || component.scheme); + if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(component, options); + if (component.path !== void 0) { + if (!options.skipEscape) { + component.path = escape(component.path); + if (component.scheme !== void 0) { + component.path = component.path.split("%3A").join(":"); + } + } else { + component.path = unescape(component.path); + } + } + if (options.reference !== "suffix" && component.scheme) { + uriTokens.push(component.scheme, ":"); + } + const authority = recomposeAuthority(component); + if (authority !== void 0) { + if (options.reference !== "suffix") { + uriTokens.push("//"); + } + uriTokens.push(authority); + if (component.path && component.path[0] !== "/") { + uriTokens.push("/"); + } + } + if (component.path !== void 0) { + let s5 = component.path; + if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) { + s5 = removeDotSegments(s5); + } + if (authority === void 0 && s5[0] === "/" && s5[1] === "/") { + s5 = "/%2F" + s5.slice(2); + } + uriTokens.push(s5); + } + if (component.query !== void 0) { + uriTokens.push("?", component.query); + } + if (component.fragment !== void 0) { + uriTokens.push("#", component.fragment); + } + return uriTokens.join(""); + } + var URI_PARSE = /^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u; + function parse5(uri, opts) { + const options = Object.assign({}, opts); + const parsed = { + scheme: void 0, + userinfo: void 0, + host: "", + port: void 0, + path: "", + query: void 0, + fragment: void 0 + }; + let isIP2 = false; + if (options.reference === "suffix") { + if (options.scheme) { + uri = options.scheme + ":" + uri; + } else { + uri = "//" + uri; + } + } + const matches = uri.match(URI_PARSE); + if (matches) { + parsed.scheme = matches[1]; + parsed.userinfo = matches[3]; + parsed.host = matches[4]; + parsed.port = parseInt(matches[5], 10); + parsed.path = matches[6] || ""; + parsed.query = matches[7]; + parsed.fragment = matches[8]; + if (isNaN(parsed.port)) { + parsed.port = matches[5]; + } + if (parsed.host) { + const ipv4result = isIPv4(parsed.host); + if (ipv4result === false) { + const ipv6result = normalizeIPv62(parsed.host); + parsed.host = ipv6result.host.toLowerCase(); + isIP2 = ipv6result.isIPV6; + } else { + isIP2 = true; + } + } + if (parsed.scheme === void 0 && parsed.userinfo === void 0 && parsed.host === void 0 && parsed.port === void 0 && parsed.query === void 0 && !parsed.path) { + parsed.reference = "same-document"; + } else if (parsed.scheme === void 0) { + parsed.reference = "relative"; + } else if (parsed.fragment === void 0) { + parsed.reference = "absolute"; + } else { + parsed.reference = "uri"; + } + if (options.reference && options.reference !== "suffix" && options.reference !== parsed.reference) { + parsed.error = parsed.error || "URI is not a " + options.reference + " reference."; + } + const schemeHandler = getSchemeHandler(options.scheme || parsed.scheme); + if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) { + if (parsed.host && (options.domainHost || schemeHandler && schemeHandler.domainHost) && isIP2 === false && nonSimpleDomain(parsed.host)) { + try { + parsed.host = URL.domainToASCII(parsed.host.toLowerCase()); + } catch (e5) { + parsed.error = parsed.error || "Host's domain name can not be converted to ASCII: " + e5; + } + } + } + if (!schemeHandler || schemeHandler && !schemeHandler.skipNormalize) { + if (uri.indexOf("%") !== -1) { + if (parsed.scheme !== void 0) { + parsed.scheme = unescape(parsed.scheme); + } + if (parsed.host !== void 0) { + parsed.host = unescape(parsed.host); + } + } + if (parsed.path) { + parsed.path = escape(unescape(parsed.path)); + } + if (parsed.fragment) { + parsed.fragment = encodeURI(decodeURIComponent(parsed.fragment)); + } + } + if (schemeHandler && schemeHandler.parse) { + schemeHandler.parse(parsed, options); + } + } else { + parsed.error = parsed.error || "URI can not be parsed."; + } + return parsed; + } + var fastUri = { + SCHEMES, + normalize: normalize2, + resolve: resolve4, + resolveComponent, + equal, + serialize, + parse: parse5 + }; + module.exports = fastUri; + module.exports.default = fastUri; + module.exports.fastUri = fastUri; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/uri.js +var require_uri2 = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/uri.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var uri = require_fast_uri(); + uri.code = 'require("ajv/dist/runtime/uri").default'; + exports.default = uri; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/core.js +var require_core = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/core.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = void 0; + var validate_1 = require_validate(); + Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function() { + return validate_1.KeywordCxt; + } }); + var codegen_1 = require_codegen(); + Object.defineProperty(exports, "_", { enumerable: true, get: function() { + return codegen_1._; + } }); + Object.defineProperty(exports, "str", { enumerable: true, get: function() { + return codegen_1.str; + } }); + Object.defineProperty(exports, "stringify", { enumerable: true, get: function() { + return codegen_1.stringify; + } }); + Object.defineProperty(exports, "nil", { enumerable: true, get: function() { + return codegen_1.nil; + } }); + Object.defineProperty(exports, "Name", { enumerable: true, get: function() { + return codegen_1.Name; + } }); + Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function() { + return codegen_1.CodeGen; + } }); + var validation_error_1 = require_validation_error(); + var ref_error_1 = require_ref_error(); + var rules_1 = require_rules(); + var compile_1 = require_compile(); + var codegen_2 = require_codegen(); + var resolve_1 = require_resolve(); + var dataType_1 = require_dataType(); + var util_1 = require_util(); + var $dataRefSchema = require_data(); + var uri_1 = require_uri2(); + var defaultRegExp = (str, flags) => new RegExp(str, flags); + defaultRegExp.code = "new RegExp"; + var META_IGNORE_OPTIONS = ["removeAdditional", "useDefaults", "coerceTypes"]; + var EXT_SCOPE_NAMES = /* @__PURE__ */ new Set([ + "validate", + "serialize", + "parse", + "wrapper", + "root", + "schema", + "keyword", + "pattern", + "formats", + "validate$data", + "func", + "obj", + "Error" + ]); + var removedOptions = { + errorDataPath: "", + format: "`validateFormats: false` can be used instead.", + nullable: '"nullable" keyword is supported by default.', + jsonPointers: "Deprecated jsPropertySyntax can be used instead.", + extendRefs: "Deprecated ignoreKeywordsWithRef can be used instead.", + missingRefs: "Pass empty schema with $id that should be ignored to ajv.addSchema.", + processCode: "Use option `code: {process: (code, schemaEnv: object) => string}`", + sourceCode: "Use option `code: {source: true}`", + strictDefaults: "It is default now, see option `strict`.", + strictKeywords: "It is default now, see option `strict`.", + uniqueItems: '"uniqueItems" keyword is always validated.', + unknownFormats: "Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).", + cache: "Map is used as cache, schema object as key.", + serialize: "Map is used as cache, schema object as key.", + ajvErrors: "It is default now." + }; + var deprecatedOptions = { + ignoreKeywordsWithRef: "", + jsPropertySyntax: "", + unicode: '"minLength"/"maxLength" account for unicode characters by default.' + }; + var MAX_EXPRESSION = 200; + function requiredOptions(o5) { + var _a6, _b, _c5, _d, _e5, _f, _g, _h4, _j, _k, _l, _m4, _o, _p, _q, _r2, _s5, _t, _u, _v, _w, _x, _y, _z, _0; + const s5 = o5.strict; + const _optz = (_a6 = o5.code) === null || _a6 === void 0 ? void 0 : _a6.optimize; + const optimize = _optz === true || _optz === void 0 ? 1 : _optz || 0; + const regExp = (_c5 = (_b = o5.code) === null || _b === void 0 ? void 0 : _b.regExp) !== null && _c5 !== void 0 ? _c5 : defaultRegExp; + const uriResolver = (_d = o5.uriResolver) !== null && _d !== void 0 ? _d : uri_1.default; + return { + strictSchema: (_f = (_e5 = o5.strictSchema) !== null && _e5 !== void 0 ? _e5 : s5) !== null && _f !== void 0 ? _f : true, + strictNumbers: (_h4 = (_g = o5.strictNumbers) !== null && _g !== void 0 ? _g : s5) !== null && _h4 !== void 0 ? _h4 : true, + strictTypes: (_k = (_j = o5.strictTypes) !== null && _j !== void 0 ? _j : s5) !== null && _k !== void 0 ? _k : "log", + strictTuples: (_m4 = (_l = o5.strictTuples) !== null && _l !== void 0 ? _l : s5) !== null && _m4 !== void 0 ? _m4 : "log", + strictRequired: (_p = (_o = o5.strictRequired) !== null && _o !== void 0 ? _o : s5) !== null && _p !== void 0 ? _p : false, + code: o5.code ? { ...o5.code, optimize, regExp } : { optimize, regExp }, + loopRequired: (_q = o5.loopRequired) !== null && _q !== void 0 ? _q : MAX_EXPRESSION, + loopEnum: (_r2 = o5.loopEnum) !== null && _r2 !== void 0 ? _r2 : MAX_EXPRESSION, + meta: (_s5 = o5.meta) !== null && _s5 !== void 0 ? _s5 : true, + messages: (_t = o5.messages) !== null && _t !== void 0 ? _t : true, + inlineRefs: (_u = o5.inlineRefs) !== null && _u !== void 0 ? _u : true, + schemaId: (_v = o5.schemaId) !== null && _v !== void 0 ? _v : "$id", + addUsedSchema: (_w = o5.addUsedSchema) !== null && _w !== void 0 ? _w : true, + validateSchema: (_x = o5.validateSchema) !== null && _x !== void 0 ? _x : true, + validateFormats: (_y = o5.validateFormats) !== null && _y !== void 0 ? _y : true, + unicodeRegExp: (_z = o5.unicodeRegExp) !== null && _z !== void 0 ? _z : true, + int32range: (_0 = o5.int32range) !== null && _0 !== void 0 ? _0 : true, + uriResolver + }; + } + var Ajv2 = class { + constructor(opts = {}) { + this.schemas = {}; + this.refs = {}; + this.formats = {}; + this._compilations = /* @__PURE__ */ new Set(); + this._loading = {}; + this._cache = /* @__PURE__ */ new Map(); + opts = this.opts = { ...opts, ...requiredOptions(opts) }; + const { es5, lines } = this.opts.code; + this.scope = new codegen_2.ValueScope({ scope: {}, prefixes: EXT_SCOPE_NAMES, es5, lines }); + this.logger = getLogger(opts.logger); + const formatOpt = opts.validateFormats; + opts.validateFormats = false; + this.RULES = (0, rules_1.getRules)(); + checkOptions.call(this, removedOptions, opts, "NOT SUPPORTED"); + checkOptions.call(this, deprecatedOptions, opts, "DEPRECATED", "warn"); + this._metaOpts = getMetaSchemaOptions.call(this); + if (opts.formats) + addInitialFormats.call(this); + this._addVocabularies(); + this._addDefaultMetaSchema(); + if (opts.keywords) + addInitialKeywords.call(this, opts.keywords); + if (typeof opts.meta == "object") + this.addMetaSchema(opts.meta); + addInitialSchemas.call(this); + opts.validateFormats = formatOpt; + } + _addVocabularies() { + this.addKeyword("$async"); + } + _addDefaultMetaSchema() { + const { $data, meta: meta3, schemaId } = this.opts; + let _dataRefSchema = $dataRefSchema; + if (schemaId === "id") { + _dataRefSchema = { ...$dataRefSchema }; + _dataRefSchema.id = _dataRefSchema.$id; + delete _dataRefSchema.$id; + } + if (meta3 && $data) + this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false); + } + defaultMeta() { + const { meta: meta3, schemaId } = this.opts; + return this.opts.defaultMeta = typeof meta3 == "object" ? meta3[schemaId] || meta3 : void 0; + } + validate(schemaKeyRef, data2) { + let v5; + if (typeof schemaKeyRef == "string") { + v5 = this.getSchema(schemaKeyRef); + if (!v5) + throw new Error(`no schema with key or ref "${schemaKeyRef}"`); + } else { + v5 = this.compile(schemaKeyRef); + } + const valid = v5(data2); + if (!("$async" in v5)) + this.errors = v5.errors; + return valid; + } + compile(schema2, _meta) { + const sch = this._addSchema(schema2, _meta); + return sch.validate || this._compileSchemaEnv(sch); + } + compileAsync(schema2, meta3) { + if (typeof this.opts.loadSchema != "function") { + throw new Error("options.loadSchema should be a function"); + } + const { loadSchema } = this.opts; + return runCompileAsync.call(this, schema2, meta3); + async function runCompileAsync(_schema, _meta) { + await loadMetaSchema.call(this, _schema.$schema); + const sch = this._addSchema(_schema, _meta); + return sch.validate || _compileAsync.call(this, sch); + } + async function loadMetaSchema($ref) { + if ($ref && !this.getSchema($ref)) { + await runCompileAsync.call(this, { $ref }, true); + } + } + async function _compileAsync(sch) { + try { + return this._compileSchemaEnv(sch); + } catch (e5) { + if (!(e5 instanceof ref_error_1.default)) + throw e5; + checkLoaded.call(this, e5); + await loadMissingSchema.call(this, e5.missingSchema); + return _compileAsync.call(this, sch); + } + } + function checkLoaded({ missingSchema: ref, missingRef }) { + if (this.refs[ref]) { + throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`); + } + } + async function loadMissingSchema(ref) { + const _schema = await _loadSchema.call(this, ref); + if (!this.refs[ref]) + await loadMetaSchema.call(this, _schema.$schema); + if (!this.refs[ref]) + this.addSchema(_schema, ref, meta3); + } + async function _loadSchema(ref) { + const p5 = this._loading[ref]; + if (p5) + return p5; + try { + return await (this._loading[ref] = loadSchema(ref)); + } finally { + delete this._loading[ref]; + } + } + } + // Adds schema to the instance + addSchema(schema2, key, _meta, _validateSchema = this.opts.validateSchema) { + if (Array.isArray(schema2)) { + for (const sch of schema2) + this.addSchema(sch, void 0, _meta, _validateSchema); + return this; + } + let id; + if (typeof schema2 === "object") { + const { schemaId } = this.opts; + id = schema2[schemaId]; + if (id !== void 0 && typeof id != "string") { + throw new Error(`schema ${schemaId} must be string`); + } + } + key = (0, resolve_1.normalizeId)(key || id); + this._checkUnique(key); + this.schemas[key] = this._addSchema(schema2, _meta, key, _validateSchema, true); + return this; + } + // Add schema that will be used to validate other schemas + // options in META_IGNORE_OPTIONS are alway set to false + addMetaSchema(schema2, key, _validateSchema = this.opts.validateSchema) { + this.addSchema(schema2, key, true, _validateSchema); + return this; + } + // Validate schema against its meta-schema + validateSchema(schema2, throwOrLogError) { + if (typeof schema2 == "boolean") + return true; + let $schema; + $schema = schema2.$schema; + if ($schema !== void 0 && typeof $schema != "string") { + throw new Error("$schema must be a string"); + } + $schema = $schema || this.opts.defaultMeta || this.defaultMeta(); + if (!$schema) { + this.logger.warn("meta-schema not available"); + this.errors = null; + return true; + } + const valid = this.validate($schema, schema2); + if (!valid && throwOrLogError) { + const message2 = "schema is invalid: " + this.errorsText(); + if (this.opts.validateSchema === "log") + this.logger.error(message2); + else + throw new Error(message2); + } + return valid; + } + // Get compiled schema by `key` or `ref`. + // (`key` that was passed to `addSchema` or full schema reference - `schema.$id` or resolved id) + getSchema(keyRef) { + let sch; + while (typeof (sch = getSchEnv.call(this, keyRef)) == "string") + keyRef = sch; + if (sch === void 0) { + const { schemaId } = this.opts; + const root = new compile_1.SchemaEnv({ schema: {}, schemaId }); + sch = compile_1.resolveSchema.call(this, root, keyRef); + if (!sch) + return; + this.refs[keyRef] = sch; + } + return sch.validate || this._compileSchemaEnv(sch); + } + // Remove cached schema(s). + // If no parameter is passed all schemas but meta-schemas are removed. + // If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed. + // Even if schema is referenced by other schemas it still can be removed as other schemas have local references. + removeSchema(schemaKeyRef) { + if (schemaKeyRef instanceof RegExp) { + this._removeAllSchemas(this.schemas, schemaKeyRef); + this._removeAllSchemas(this.refs, schemaKeyRef); + return this; + } + switch (typeof schemaKeyRef) { + case "undefined": + this._removeAllSchemas(this.schemas); + this._removeAllSchemas(this.refs); + this._cache.clear(); + return this; + case "string": { + const sch = getSchEnv.call(this, schemaKeyRef); + if (typeof sch == "object") + this._cache.delete(sch.schema); + delete this.schemas[schemaKeyRef]; + delete this.refs[schemaKeyRef]; + return this; + } + case "object": { + const cacheKey = schemaKeyRef; + this._cache.delete(cacheKey); + let id = schemaKeyRef[this.opts.schemaId]; + if (id) { + id = (0, resolve_1.normalizeId)(id); + delete this.schemas[id]; + delete this.refs[id]; + } + return this; + } + default: + throw new Error("ajv.removeSchema: invalid parameter"); + } + } + // add "vocabulary" - a collection of keywords + addVocabulary(definitions) { + for (const def of definitions) + this.addKeyword(def); + return this; + } + addKeyword(kwdOrDef, def) { + let keyword; + if (typeof kwdOrDef == "string") { + keyword = kwdOrDef; + if (typeof def == "object") { + this.logger.warn("these parameters are deprecated, see docs for addKeyword"); + def.keyword = keyword; + } + } else if (typeof kwdOrDef == "object" && def === void 0) { + def = kwdOrDef; + keyword = def.keyword; + if (Array.isArray(keyword) && !keyword.length) { + throw new Error("addKeywords: keyword must be string or non-empty array"); + } + } else { + throw new Error("invalid addKeywords parameters"); + } + checkKeyword.call(this, keyword, def); + if (!def) { + (0, util_1.eachItem)(keyword, (kwd) => addRule.call(this, kwd)); + return this; + } + keywordMetaschema.call(this, def); + const definition = { + ...def, + type: (0, dataType_1.getJSONTypes)(def.type), + schemaType: (0, dataType_1.getJSONTypes)(def.schemaType) + }; + (0, util_1.eachItem)(keyword, definition.type.length === 0 ? (k5) => addRule.call(this, k5, definition) : (k5) => definition.type.forEach((t5) => addRule.call(this, k5, definition, t5))); + return this; + } + getKeyword(keyword) { + const rule = this.RULES.all[keyword]; + return typeof rule == "object" ? rule.definition : !!rule; + } + // Remove keyword + removeKeyword(keyword) { + const { RULES } = this; + delete RULES.keywords[keyword]; + delete RULES.all[keyword]; + for (const group of RULES.rules) { + const i5 = group.rules.findIndex((rule) => rule.keyword === keyword); + if (i5 >= 0) + group.rules.splice(i5, 1); + } + return this; + } + // Add format + addFormat(name, format2) { + if (typeof format2 == "string") + format2 = new RegExp(format2); + this.formats[name] = format2; + return this; + } + errorsText(errors = this.errors, { separator = ", ", dataVar = "data" } = {}) { + if (!errors || errors.length === 0) + return "No errors"; + return errors.map((e5) => `${dataVar}${e5.instancePath} ${e5.message}`).reduce((text3, msg) => text3 + separator + msg); + } + $dataMetaSchema(metaSchema, keywordsJsonPointers) { + const rules = this.RULES.all; + metaSchema = JSON.parse(JSON.stringify(metaSchema)); + for (const jsonPointer of keywordsJsonPointers) { + const segments = jsonPointer.split("/").slice(1); + let keywords = metaSchema; + for (const seg of segments) + keywords = keywords[seg]; + for (const key in rules) { + const rule = rules[key]; + if (typeof rule != "object") + continue; + const { $data } = rule.definition; + const schema2 = keywords[key]; + if ($data && schema2) + keywords[key] = schemaOrData(schema2); + } + } + return metaSchema; + } + _removeAllSchemas(schemas, regex) { + for (const keyRef in schemas) { + const sch = schemas[keyRef]; + if (!regex || regex.test(keyRef)) { + if (typeof sch == "string") { + delete schemas[keyRef]; + } else if (sch && !sch.meta) { + this._cache.delete(sch.schema); + delete schemas[keyRef]; + } + } + } + } + _addSchema(schema2, meta3, baseId, validateSchema = this.opts.validateSchema, addSchema = this.opts.addUsedSchema) { + let id; + const { schemaId } = this.opts; + if (typeof schema2 == "object") { + id = schema2[schemaId]; + } else { + if (this.opts.jtd) + throw new Error("schema must be object"); + else if (typeof schema2 != "boolean") + throw new Error("schema must be object or boolean"); + } + let sch = this._cache.get(schema2); + if (sch !== void 0) + return sch; + baseId = (0, resolve_1.normalizeId)(id || baseId); + const localRefs = resolve_1.getSchemaRefs.call(this, schema2, baseId); + sch = new compile_1.SchemaEnv({ schema: schema2, schemaId, meta: meta3, baseId, localRefs }); + this._cache.set(sch.schema, sch); + if (addSchema && !baseId.startsWith("#")) { + if (baseId) + this._checkUnique(baseId); + this.refs[baseId] = sch; + } + if (validateSchema) + this.validateSchema(schema2, true); + return sch; + } + _checkUnique(id) { + if (this.schemas[id] || this.refs[id]) { + throw new Error(`schema with key or id "${id}" already exists`); + } + } + _compileSchemaEnv(sch) { + if (sch.meta) + this._compileMetaSchema(sch); + else + compile_1.compileSchema.call(this, sch); + if (!sch.validate) + throw new Error("ajv implementation error"); + return sch.validate; + } + _compileMetaSchema(sch) { + const currentOpts = this.opts; + this.opts = this._metaOpts; + try { + compile_1.compileSchema.call(this, sch); + } finally { + this.opts = currentOpts; + } + } + }; + Ajv2.ValidationError = validation_error_1.default; + Ajv2.MissingRefError = ref_error_1.default; + exports.default = Ajv2; + function checkOptions(checkOpts3, options, msg, log2 = "error") { + for (const key in checkOpts3) { + const opt = key; + if (opt in options) + this.logger[log2](`${msg}: option ${key}. ${checkOpts3[opt]}`); + } + } + function getSchEnv(keyRef) { + keyRef = (0, resolve_1.normalizeId)(keyRef); + return this.schemas[keyRef] || this.refs[keyRef]; + } + function addInitialSchemas() { + const optsSchemas = this.opts.schemas; + if (!optsSchemas) + return; + if (Array.isArray(optsSchemas)) + this.addSchema(optsSchemas); + else + for (const key in optsSchemas) + this.addSchema(optsSchemas[key], key); + } + function addInitialFormats() { + for (const name in this.opts.formats) { + const format2 = this.opts.formats[name]; + if (format2) + this.addFormat(name, format2); + } + } + function addInitialKeywords(defs) { + if (Array.isArray(defs)) { + this.addVocabulary(defs); + return; + } + this.logger.warn("keywords option as map is deprecated, pass array"); + for (const keyword in defs) { + const def = defs[keyword]; + if (!def.keyword) + def.keyword = keyword; + this.addKeyword(def); + } + } + function getMetaSchemaOptions() { + const metaOpts = { ...this.opts }; + for (const opt of META_IGNORE_OPTIONS) + delete metaOpts[opt]; + return metaOpts; + } + var noLogs = { log() { + }, warn() { + }, error() { + } }; + function getLogger(logger4) { + if (logger4 === false) + return noLogs; + if (logger4 === void 0) + return console; + if (logger4.log && logger4.warn && logger4.error) + return logger4; + throw new Error("logger must implement log, warn and error methods"); + } + var KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i; + function checkKeyword(keyword, def) { + const { RULES } = this; + (0, util_1.eachItem)(keyword, (kwd) => { + if (RULES.keywords[kwd]) + throw new Error(`Keyword ${kwd} is already defined`); + if (!KEYWORD_NAME.test(kwd)) + throw new Error(`Keyword ${kwd} has invalid name`); + }); + if (!def) + return; + if (def.$data && !("code" in def || "validate" in def)) { + throw new Error('$data keyword must have "code" or "validate" function'); + } + } + function addRule(keyword, definition, dataType) { + var _a6; + const post = definition === null || definition === void 0 ? void 0 : definition.post; + if (dataType && post) + throw new Error('keyword with "post" flag cannot have "type"'); + const { RULES } = this; + let ruleGroup = post ? RULES.post : RULES.rules.find(({ type: t5 }) => t5 === dataType); + if (!ruleGroup) { + ruleGroup = { type: dataType, rules: [] }; + RULES.rules.push(ruleGroup); + } + RULES.keywords[keyword] = true; + if (!definition) + return; + const rule = { + keyword, + definition: { + ...definition, + type: (0, dataType_1.getJSONTypes)(definition.type), + schemaType: (0, dataType_1.getJSONTypes)(definition.schemaType) + } + }; + if (definition.before) + addBeforeRule.call(this, ruleGroup, rule, definition.before); + else + ruleGroup.rules.push(rule); + RULES.all[keyword] = rule; + (_a6 = definition.implements) === null || _a6 === void 0 ? void 0 : _a6.forEach((kwd) => this.addKeyword(kwd)); + } + function addBeforeRule(ruleGroup, rule, before) { + const i5 = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before); + if (i5 >= 0) { + ruleGroup.rules.splice(i5, 0, rule); + } else { + ruleGroup.rules.push(rule); + this.logger.warn(`rule ${before} is not defined`); + } + } + function keywordMetaschema(def) { + let { metaSchema } = def; + if (metaSchema === void 0) + return; + if (def.$data && this.opts.$data) + metaSchema = schemaOrData(metaSchema); + def.validateSchema = this.compile(metaSchema, true); + } + var $dataRef = { + $ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#" + }; + function schemaOrData(schema2) { + return { anyOf: [schema2, $dataRef] }; + } + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/core/id.js +var require_id = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/core/id.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var def = { + keyword: "id", + code() { + throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID'); + } + }; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/core/ref.js +var require_ref2 = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/core/ref.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.callRef = exports.getValidate = void 0; + var ref_error_1 = require_ref_error(); + var code_1 = require_code2(); + var codegen_1 = require_codegen(); + var names_1 = require_names(); + var compile_1 = require_compile(); + var util_1 = require_util(); + var def = { + keyword: "$ref", + schemaType: "string", + code(cxt) { + const { gen, schema: $ref, it } = cxt; + const { baseId, schemaEnv: env2, validateName, opts, self: self2 } = it; + const { root } = env2; + if (($ref === "#" || $ref === "#/") && baseId === root.baseId) + return callRootRef(); + const schOrEnv = compile_1.resolveRef.call(self2, root, baseId, $ref); + if (schOrEnv === void 0) + throw new ref_error_1.default(it.opts.uriResolver, baseId, $ref); + if (schOrEnv instanceof compile_1.SchemaEnv) + return callValidate(schOrEnv); + return inlineRefSchema(schOrEnv); + function callRootRef() { + if (env2 === root) + return callRef(cxt, validateName, env2, env2.$async); + const rootName = gen.scopeValue("root", { ref: root }); + return callRef(cxt, (0, codegen_1._)`${rootName}.validate`, root, root.$async); + } + function callValidate(sch) { + const v5 = getValidate(cxt, sch); + callRef(cxt, v5, sch, sch.$async); + } + function inlineRefSchema(sch) { + const schName = gen.scopeValue("schema", opts.code.source === true ? { ref: sch, code: (0, codegen_1.stringify)(sch) } : { ref: sch }); + const valid = gen.name("valid"); + const schCxt = cxt.subschema({ + schema: sch, + dataTypes: [], + schemaPath: codegen_1.nil, + topSchemaRef: schName, + errSchemaPath: $ref + }, valid); + cxt.mergeEvaluated(schCxt); + cxt.ok(valid); + } + } + }; + function getValidate(cxt, sch) { + const { gen } = cxt; + return sch.validate ? gen.scopeValue("validate", { ref: sch.validate }) : (0, codegen_1._)`${gen.scopeValue("wrapper", { ref: sch })}.validate`; + } + exports.getValidate = getValidate; + function callRef(cxt, v5, sch, $async) { + const { gen, it } = cxt; + const { allErrors, schemaEnv: env2, opts } = it; + const passCxt = opts.passContext ? names_1.default.this : codegen_1.nil; + if ($async) + callAsyncRef(); + else + callSyncRef(); + function callAsyncRef() { + if (!env2.$async) + throw new Error("async schema referenced by sync schema"); + const valid = gen.let("valid"); + gen.try(() => { + gen.code((0, codegen_1._)`await ${(0, code_1.callValidateCode)(cxt, v5, passCxt)}`); + addEvaluatedFrom(v5); + if (!allErrors) + gen.assign(valid, true); + }, (e5) => { + gen.if((0, codegen_1._)`!(${e5} instanceof ${it.ValidationError})`, () => gen.throw(e5)); + addErrorsFrom(e5); + if (!allErrors) + gen.assign(valid, false); + }); + cxt.ok(valid); + } + function callSyncRef() { + cxt.result((0, code_1.callValidateCode)(cxt, v5, passCxt), () => addEvaluatedFrom(v5), () => addErrorsFrom(v5)); + } + function addErrorsFrom(source) { + const errs = (0, codegen_1._)`${source}.errors`; + gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`); + gen.assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`); + } + function addEvaluatedFrom(source) { + var _a6; + if (!it.opts.unevaluated) + return; + const schEvaluated = (_a6 = sch === null || sch === void 0 ? void 0 : sch.validate) === null || _a6 === void 0 ? void 0 : _a6.evaluated; + if (it.props !== true) { + if (schEvaluated && !schEvaluated.dynamicProps) { + if (schEvaluated.props !== void 0) { + it.props = util_1.mergeEvaluated.props(gen, schEvaluated.props, it.props); + } + } else { + const props = gen.var("props", (0, codegen_1._)`${source}.evaluated.props`); + it.props = util_1.mergeEvaluated.props(gen, props, it.props, codegen_1.Name); + } + } + if (it.items !== true) { + if (schEvaluated && !schEvaluated.dynamicItems) { + if (schEvaluated.items !== void 0) { + it.items = util_1.mergeEvaluated.items(gen, schEvaluated.items, it.items); + } + } else { + const items = gen.var("items", (0, codegen_1._)`${source}.evaluated.items`); + it.items = util_1.mergeEvaluated.items(gen, items, it.items, codegen_1.Name); + } + } + } + } + exports.callRef = callRef; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/core/index.js +var require_core2 = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/core/index.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var id_1 = require_id(); + var ref_1 = require_ref2(); + var core = [ + "$schema", + "$id", + "$defs", + "$vocabulary", + { keyword: "$comment" }, + "definitions", + id_1.default, + ref_1.default + ]; + exports.default = core; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitNumber.js +var require_limitNumber = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitNumber.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var ops = codegen_1.operators; + var KWDs = { + maximum: { okStr: "<=", ok: ops.LTE, fail: ops.GT }, + minimum: { okStr: ">=", ok: ops.GTE, fail: ops.LT }, + exclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE }, + exclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE } + }; + var error50 = { + message: ({ keyword, schemaCode }) => (0, codegen_1.str)`must be ${KWDs[keyword].okStr} ${schemaCode}`, + params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}` + }; + var def = { + keyword: Object.keys(KWDs), + type: "number", + schemaType: "number", + $data: true, + error: error50, + code(cxt) { + const { keyword, data: data2, schemaCode } = cxt; + cxt.fail$data((0, codegen_1._)`${data2} ${KWDs[keyword].fail} ${schemaCode} || isNaN(${data2})`); + } + }; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/multipleOf.js +var require_multipleOf = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/multipleOf.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var error50 = { + message: ({ schemaCode }) => (0, codegen_1.str)`must be multiple of ${schemaCode}`, + params: ({ schemaCode }) => (0, codegen_1._)`{multipleOf: ${schemaCode}}` + }; + var def = { + keyword: "multipleOf", + type: "number", + schemaType: "number", + $data: true, + error: error50, + code(cxt) { + const { gen, data: data2, schemaCode, it } = cxt; + const prec = it.opts.multipleOfPrecision; + const res = gen.let("res"); + const invalid = prec ? (0, codegen_1._)`Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}` : (0, codegen_1._)`${res} !== parseInt(${res})`; + cxt.fail$data((0, codegen_1._)`(${schemaCode} === 0 || (${res} = ${data2}/${schemaCode}, ${invalid}))`); + } + }; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/ucs2length.js +var require_ucs2length = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/ucs2length.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + function ucs2length(str) { + const len = str.length; + let length = 0; + let pos = 0; + let value; + while (pos < len) { + length++; + value = str.charCodeAt(pos++); + if (value >= 55296 && value <= 56319 && pos < len) { + value = str.charCodeAt(pos); + if ((value & 64512) === 56320) + pos++; + } + } + return length; + } + exports.default = ucs2length; + ucs2length.code = 'require("ajv/dist/runtime/ucs2length").default'; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitLength.js +var require_limitLength = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitLength.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var ucs2length_1 = require_ucs2length(); + var error50 = { + message({ keyword, schemaCode }) { + const comp = keyword === "maxLength" ? "more" : "fewer"; + return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} characters`; + }, + params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` + }; + var def = { + keyword: ["maxLength", "minLength"], + type: "string", + schemaType: "number", + $data: true, + error: error50, + code(cxt) { + const { keyword, data: data2, schemaCode, it } = cxt; + const op2 = keyword === "maxLength" ? codegen_1.operators.GT : codegen_1.operators.LT; + const len = it.opts.unicode === false ? (0, codegen_1._)`${data2}.length` : (0, codegen_1._)`${(0, util_1.useFunc)(cxt.gen, ucs2length_1.default)}(${data2})`; + cxt.fail$data((0, codegen_1._)`${len} ${op2} ${schemaCode}`); + } + }; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/pattern.js +var require_pattern = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/pattern.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var code_1 = require_code2(); + var util_1 = require_util(); + var codegen_1 = require_codegen(); + var error50 = { + message: ({ schemaCode }) => (0, codegen_1.str)`must match pattern "${schemaCode}"`, + params: ({ schemaCode }) => (0, codegen_1._)`{pattern: ${schemaCode}}` + }; + var def = { + keyword: "pattern", + type: "string", + schemaType: "string", + $data: true, + error: error50, + code(cxt) { + const { gen, data: data2, $data, schema: schema2, schemaCode, it } = cxt; + const u5 = it.opts.unicodeRegExp ? "u" : ""; + if ($data) { + const { regExp } = it.opts.code; + const regExpCode = regExp.code === "new RegExp" ? (0, codegen_1._)`new RegExp` : (0, util_1.useFunc)(gen, regExp); + const valid = gen.let("valid"); + gen.try(() => gen.assign(valid, (0, codegen_1._)`${regExpCode}(${schemaCode}, ${u5}).test(${data2})`), () => gen.assign(valid, false)); + cxt.fail$data((0, codegen_1._)`!${valid}`); + } else { + const regExp = (0, code_1.usePattern)(cxt, schema2); + cxt.fail$data((0, codegen_1._)`!${regExp}.test(${data2})`); + } + } + }; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitProperties.js +var require_limitProperties = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitProperties.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var error50 = { + message({ keyword, schemaCode }) { + const comp = keyword === "maxProperties" ? "more" : "fewer"; + return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} properties`; + }, + params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` + }; + var def = { + keyword: ["maxProperties", "minProperties"], + type: "object", + schemaType: "number", + $data: true, + error: error50, + code(cxt) { + const { keyword, data: data2, schemaCode } = cxt; + const op2 = keyword === "maxProperties" ? codegen_1.operators.GT : codegen_1.operators.LT; + cxt.fail$data((0, codegen_1._)`Object.keys(${data2}).length ${op2} ${schemaCode}`); + } + }; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/required.js +var require_required = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/required.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var code_1 = require_code2(); + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var error50 = { + message: ({ params: { missingProperty } }) => (0, codegen_1.str)`must have required property '${missingProperty}'`, + params: ({ params: { missingProperty } }) => (0, codegen_1._)`{missingProperty: ${missingProperty}}` + }; + var def = { + keyword: "required", + type: "object", + schemaType: "array", + $data: true, + error: error50, + code(cxt) { + const { gen, schema: schema2, schemaCode, data: data2, $data, it } = cxt; + const { opts } = it; + if (!$data && schema2.length === 0) + return; + const useLoop = schema2.length >= opts.loopRequired; + if (it.allErrors) + allErrorsMode(); + else + exitOnErrorMode(); + if (opts.strictRequired) { + const props = cxt.parentSchema.properties; + const { definedProperties } = cxt.it; + for (const requiredKey of schema2) { + if ((props === null || props === void 0 ? void 0 : props[requiredKey]) === void 0 && !definedProperties.has(requiredKey)) { + const schemaPath = it.schemaEnv.baseId + it.errSchemaPath; + const msg = `required property "${requiredKey}" is not defined at "${schemaPath}" (strictRequired)`; + (0, util_1.checkStrictMode)(it, msg, it.opts.strictRequired); + } + } + } + function allErrorsMode() { + if (useLoop || $data) { + cxt.block$data(codegen_1.nil, loopAllRequired); + } else { + for (const prop of schema2) { + (0, code_1.checkReportMissingProp)(cxt, prop); + } + } + } + function exitOnErrorMode() { + const missing = gen.let("missing"); + if (useLoop || $data) { + const valid = gen.let("valid", true); + cxt.block$data(valid, () => loopUntilMissing(missing, valid)); + cxt.ok(valid); + } else { + gen.if((0, code_1.checkMissingProp)(cxt, schema2, missing)); + (0, code_1.reportMissingProp)(cxt, missing); + gen.else(); + } + } + function loopAllRequired() { + gen.forOf("prop", schemaCode, (prop) => { + cxt.setParams({ missingProperty: prop }); + gen.if((0, code_1.noPropertyInData)(gen, data2, prop, opts.ownProperties), () => cxt.error()); + }); + } + function loopUntilMissing(missing, valid) { + cxt.setParams({ missingProperty: missing }); + gen.forOf(missing, schemaCode, () => { + gen.assign(valid, (0, code_1.propertyInData)(gen, data2, missing, opts.ownProperties)); + gen.if((0, codegen_1.not)(valid), () => { + cxt.error(); + gen.break(); + }); + }, codegen_1.nil); + } + } + }; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitItems.js +var require_limitItems = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitItems.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var error50 = { + message({ keyword, schemaCode }) { + const comp = keyword === "maxItems" ? "more" : "fewer"; + return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} items`; + }, + params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` + }; + var def = { + keyword: ["maxItems", "minItems"], + type: "array", + schemaType: "number", + $data: true, + error: error50, + code(cxt) { + const { keyword, data: data2, schemaCode } = cxt; + const op2 = keyword === "maxItems" ? codegen_1.operators.GT : codegen_1.operators.LT; + cxt.fail$data((0, codegen_1._)`${data2}.length ${op2} ${schemaCode}`); + } + }; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/equal.js +var require_equal = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/equal.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var equal = require_fast_deep_equal(); + equal.code = 'require("ajv/dist/runtime/equal").default'; + exports.default = equal; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/uniqueItems.js +var require_uniqueItems = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/uniqueItems.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var dataType_1 = require_dataType(); + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var equal_1 = require_equal(); + var error50 = { + message: ({ params: { i: i5, j: j5 } }) => (0, codegen_1.str)`must NOT have duplicate items (items ## ${j5} and ${i5} are identical)`, + params: ({ params: { i: i5, j: j5 } }) => (0, codegen_1._)`{i: ${i5}, j: ${j5}}` + }; + var def = { + keyword: "uniqueItems", + type: "array", + schemaType: "boolean", + $data: true, + error: error50, + code(cxt) { + const { gen, data: data2, $data, schema: schema2, parentSchema, schemaCode, it } = cxt; + if (!$data && !schema2) + return; + const valid = gen.let("valid"); + const itemTypes = parentSchema.items ? (0, dataType_1.getSchemaTypes)(parentSchema.items) : []; + cxt.block$data(valid, validateUniqueItems, (0, codegen_1._)`${schemaCode} === false`); + cxt.ok(valid); + function validateUniqueItems() { + const i5 = gen.let("i", (0, codegen_1._)`${data2}.length`); + const j5 = gen.let("j"); + cxt.setParams({ i: i5, j: j5 }); + gen.assign(valid, true); + gen.if((0, codegen_1._)`${i5} > 1`, () => (canOptimize() ? loopN : loopN2)(i5, j5)); + } + function canOptimize() { + return itemTypes.length > 0 && !itemTypes.some((t5) => t5 === "object" || t5 === "array"); + } + function loopN(i5, j5) { + const item = gen.name("item"); + const wrongType = (0, dataType_1.checkDataTypes)(itemTypes, item, it.opts.strictNumbers, dataType_1.DataType.Wrong); + const indices = gen.const("indices", (0, codegen_1._)`{}`); + gen.for((0, codegen_1._)`;${i5}--;`, () => { + gen.let(item, (0, codegen_1._)`${data2}[${i5}]`); + gen.if(wrongType, (0, codegen_1._)`continue`); + if (itemTypes.length > 1) + gen.if((0, codegen_1._)`typeof ${item} == "string"`, (0, codegen_1._)`${item} += "_"`); + gen.if((0, codegen_1._)`typeof ${indices}[${item}] == "number"`, () => { + gen.assign(j5, (0, codegen_1._)`${indices}[${item}]`); + cxt.error(); + gen.assign(valid, false).break(); + }).code((0, codegen_1._)`${indices}[${item}] = ${i5}`); + }); + } + function loopN2(i5, j5) { + const eql = (0, util_1.useFunc)(gen, equal_1.default); + const outer = gen.name("outer"); + gen.label(outer).for((0, codegen_1._)`;${i5}--;`, () => gen.for((0, codegen_1._)`${j5} = ${i5}; ${j5}--;`, () => gen.if((0, codegen_1._)`${eql}(${data2}[${i5}], ${data2}[${j5}])`, () => { + cxt.error(); + gen.assign(valid, false).break(outer); + }))); + } + } + }; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/const.js +var require_const = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/const.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var equal_1 = require_equal(); + var error50 = { + message: "must be equal to constant", + params: ({ schemaCode }) => (0, codegen_1._)`{allowedValue: ${schemaCode}}` + }; + var def = { + keyword: "const", + $data: true, + error: error50, + code(cxt) { + const { gen, data: data2, $data, schemaCode, schema: schema2 } = cxt; + if ($data || schema2 && typeof schema2 == "object") { + cxt.fail$data((0, codegen_1._)`!${(0, util_1.useFunc)(gen, equal_1.default)}(${data2}, ${schemaCode})`); + } else { + cxt.fail((0, codegen_1._)`${schema2} !== ${data2}`); + } + } + }; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/enum.js +var require_enum = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/enum.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var equal_1 = require_equal(); + var error50 = { + message: "must be equal to one of the allowed values", + params: ({ schemaCode }) => (0, codegen_1._)`{allowedValues: ${schemaCode}}` + }; + var def = { + keyword: "enum", + schemaType: "array", + $data: true, + error: error50, + code(cxt) { + const { gen, data: data2, $data, schema: schema2, schemaCode, it } = cxt; + if (!$data && schema2.length === 0) + throw new Error("enum must have non-empty array"); + const useLoop = schema2.length >= it.opts.loopEnum; + let eql; + const getEql = () => eql !== null && eql !== void 0 ? eql : eql = (0, util_1.useFunc)(gen, equal_1.default); + let valid; + if (useLoop || $data) { + valid = gen.let("valid"); + cxt.block$data(valid, loopEnum); + } else { + if (!Array.isArray(schema2)) + throw new Error("ajv implementation error"); + const vSchema = gen.const("vSchema", schemaCode); + valid = (0, codegen_1.or)(...schema2.map((_x, i5) => equalCode(vSchema, i5))); + } + cxt.pass(valid); + function loopEnum() { + gen.assign(valid, false); + gen.forOf("v", schemaCode, (v5) => gen.if((0, codegen_1._)`${getEql()}(${data2}, ${v5})`, () => gen.assign(valid, true).break())); + } + function equalCode(vSchema, i5) { + const sch = schema2[i5]; + return typeof sch === "object" && sch !== null ? (0, codegen_1._)`${getEql()}(${data2}, ${vSchema}[${i5}])` : (0, codegen_1._)`${data2} === ${sch}`; + } + } + }; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/index.js +var require_validation2 = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/index.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var limitNumber_1 = require_limitNumber(); + var multipleOf_1 = require_multipleOf(); + var limitLength_1 = require_limitLength(); + var pattern_1 = require_pattern(); + var limitProperties_1 = require_limitProperties(); + var required_1 = require_required(); + var limitItems_1 = require_limitItems(); + var uniqueItems_1 = require_uniqueItems(); + var const_1 = require_const(); + var enum_1 = require_enum(); + var validation = [ + // number + limitNumber_1.default, + multipleOf_1.default, + // string + limitLength_1.default, + pattern_1.default, + // object + limitProperties_1.default, + required_1.default, + // array + limitItems_1.default, + uniqueItems_1.default, + // any + { keyword: "type", schemaType: ["string", "array"] }, + { keyword: "nullable", schemaType: "boolean" }, + const_1.default, + enum_1.default + ]; + exports.default = validation; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/additionalItems.js +var require_additionalItems = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/additionalItems.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateAdditionalItems = void 0; + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var error50 = { + message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, + params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` + }; + var def = { + keyword: "additionalItems", + type: "array", + schemaType: ["boolean", "object"], + before: "uniqueItems", + error: error50, + code(cxt) { + const { parentSchema, it } = cxt; + const { items } = parentSchema; + if (!Array.isArray(items)) { + (0, util_1.checkStrictMode)(it, '"additionalItems" is ignored when "items" is not an array of schemas'); + return; + } + validateAdditionalItems(cxt, items); + } + }; + function validateAdditionalItems(cxt, items) { + const { gen, schema: schema2, data: data2, keyword, it } = cxt; + it.items = true; + const len = gen.const("len", (0, codegen_1._)`${data2}.length`); + if (schema2 === false) { + cxt.setParams({ len: items.length }); + cxt.pass((0, codegen_1._)`${len} <= ${items.length}`); + } else if (typeof schema2 == "object" && !(0, util_1.alwaysValidSchema)(it, schema2)) { + const valid = gen.var("valid", (0, codegen_1._)`${len} <= ${items.length}`); + gen.if((0, codegen_1.not)(valid), () => validateItems(valid)); + cxt.ok(valid); + } + function validateItems(valid) { + gen.forRange("i", items.length, len, (i5) => { + cxt.subschema({ keyword, dataProp: i5, dataPropType: util_1.Type.Num }, valid); + if (!it.allErrors) + gen.if((0, codegen_1.not)(valid), () => gen.break()); + }); + } + } + exports.validateAdditionalItems = validateAdditionalItems; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/items.js +var require_items = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/items.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateTuple = void 0; + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var code_1 = require_code2(); + var def = { + keyword: "items", + type: "array", + schemaType: ["object", "array", "boolean"], + before: "uniqueItems", + code(cxt) { + const { schema: schema2, it } = cxt; + if (Array.isArray(schema2)) + return validateTuple(cxt, "additionalItems", schema2); + it.items = true; + if ((0, util_1.alwaysValidSchema)(it, schema2)) + return; + cxt.ok((0, code_1.validateArray)(cxt)); + } + }; + function validateTuple(cxt, extraItems, schArr = cxt.schema) { + const { gen, parentSchema, data: data2, keyword, it } = cxt; + checkStrictTuple(parentSchema); + if (it.opts.unevaluated && schArr.length && it.items !== true) { + it.items = util_1.mergeEvaluated.items(gen, schArr.length, it.items); + } + const valid = gen.name("valid"); + const len = gen.const("len", (0, codegen_1._)`${data2}.length`); + schArr.forEach((sch, i5) => { + if ((0, util_1.alwaysValidSchema)(it, sch)) + return; + gen.if((0, codegen_1._)`${len} > ${i5}`, () => cxt.subschema({ + keyword, + schemaProp: i5, + dataProp: i5 + }, valid)); + cxt.ok(valid); + }); + function checkStrictTuple(sch) { + const { opts, errSchemaPath } = it; + const l5 = schArr.length; + const fullTuple = l5 === sch.minItems && (l5 === sch.maxItems || sch[extraItems] === false); + if (opts.strictTuples && !fullTuple) { + const msg = `"${keyword}" is ${l5}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path "${errSchemaPath}"`; + (0, util_1.checkStrictMode)(it, msg, opts.strictTuples); + } + } + } + exports.validateTuple = validateTuple; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/prefixItems.js +var require_prefixItems = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/prefixItems.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var items_1 = require_items(); + var def = { + keyword: "prefixItems", + type: "array", + schemaType: ["array"], + before: "uniqueItems", + code: (cxt) => (0, items_1.validateTuple)(cxt, "items") + }; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/items2020.js +var require_items2020 = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/items2020.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var code_1 = require_code2(); + var additionalItems_1 = require_additionalItems(); + var error50 = { + message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, + params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` + }; + var def = { + keyword: "items", + type: "array", + schemaType: ["object", "boolean"], + before: "uniqueItems", + error: error50, + code(cxt) { + const { schema: schema2, parentSchema, it } = cxt; + const { prefixItems } = parentSchema; + it.items = true; + if ((0, util_1.alwaysValidSchema)(it, schema2)) + return; + if (prefixItems) + (0, additionalItems_1.validateAdditionalItems)(cxt, prefixItems); + else + cxt.ok((0, code_1.validateArray)(cxt)); + } + }; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/contains.js +var require_contains = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/contains.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var error50 = { + message: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1.str)`must contain at least ${min} valid item(s)` : (0, codegen_1.str)`must contain at least ${min} and no more than ${max} valid item(s)`, + params: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1._)`{minContains: ${min}}` : (0, codegen_1._)`{minContains: ${min}, maxContains: ${max}}` + }; + var def = { + keyword: "contains", + type: "array", + schemaType: ["object", "boolean"], + before: "uniqueItems", + trackErrors: true, + error: error50, + code(cxt) { + const { gen, schema: schema2, parentSchema, data: data2, it } = cxt; + let min; + let max; + const { minContains, maxContains } = parentSchema; + if (it.opts.next) { + min = minContains === void 0 ? 1 : minContains; + max = maxContains; + } else { + min = 1; + } + const len = gen.const("len", (0, codegen_1._)`${data2}.length`); + cxt.setParams({ min, max }); + if (max === void 0 && min === 0) { + (0, util_1.checkStrictMode)(it, `"minContains" == 0 without "maxContains": "contains" keyword ignored`); + return; + } + if (max !== void 0 && min > max) { + (0, util_1.checkStrictMode)(it, `"minContains" > "maxContains" is always invalid`); + cxt.fail(); + return; + } + if ((0, util_1.alwaysValidSchema)(it, schema2)) { + let cond = (0, codegen_1._)`${len} >= ${min}`; + if (max !== void 0) + cond = (0, codegen_1._)`${cond} && ${len} <= ${max}`; + cxt.pass(cond); + return; + } + it.items = true; + const valid = gen.name("valid"); + if (max === void 0 && min === 1) { + validateItems(valid, () => gen.if(valid, () => gen.break())); + } else if (min === 0) { + gen.let(valid, true); + if (max !== void 0) + gen.if((0, codegen_1._)`${data2}.length > 0`, validateItemsWithCount); + } else { + gen.let(valid, false); + validateItemsWithCount(); + } + cxt.result(valid, () => cxt.reset()); + function validateItemsWithCount() { + const schValid = gen.name("_valid"); + const count2 = gen.let("count", 0); + validateItems(schValid, () => gen.if(schValid, () => checkLimits(count2))); + } + function validateItems(_valid, block) { + gen.forRange("i", 0, len, (i5) => { + cxt.subschema({ + keyword: "contains", + dataProp: i5, + dataPropType: util_1.Type.Num, + compositeRule: true + }, _valid); + block(); + }); + } + function checkLimits(count2) { + gen.code((0, codegen_1._)`${count2}++`); + if (max === void 0) { + gen.if((0, codegen_1._)`${count2} >= ${min}`, () => gen.assign(valid, true).break()); + } else { + gen.if((0, codegen_1._)`${count2} > ${max}`, () => gen.assign(valid, false).break()); + if (min === 1) + gen.assign(valid, true); + else + gen.if((0, codegen_1._)`${count2} >= ${min}`, () => gen.assign(valid, true)); + } + } + } + }; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/dependencies.js +var require_dependencies = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/dependencies.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateSchemaDeps = exports.validatePropertyDeps = exports.error = void 0; + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var code_1 = require_code2(); + exports.error = { + message: ({ params: { property, depsCount, deps } }) => { + const property_ies = depsCount === 1 ? "property" : "properties"; + return (0, codegen_1.str)`must have ${property_ies} ${deps} when property ${property} is present`; + }, + params: ({ params: { property, depsCount, deps, missingProperty } }) => (0, codegen_1._)`{property: ${property}, + missingProperty: ${missingProperty}, + depsCount: ${depsCount}, + deps: ${deps}}` + // TODO change to reference + }; + var def = { + keyword: "dependencies", + type: "object", + schemaType: "object", + error: exports.error, + code(cxt) { + const [propDeps, schDeps] = splitDependencies(cxt); + validatePropertyDeps(cxt, propDeps); + validateSchemaDeps(cxt, schDeps); + } + }; + function splitDependencies({ schema: schema2 }) { + const propertyDeps = {}; + const schemaDeps = {}; + for (const key in schema2) { + if (key === "__proto__") + continue; + const deps = Array.isArray(schema2[key]) ? propertyDeps : schemaDeps; + deps[key] = schema2[key]; + } + return [propertyDeps, schemaDeps]; + } + function validatePropertyDeps(cxt, propertyDeps = cxt.schema) { + const { gen, data: data2, it } = cxt; + if (Object.keys(propertyDeps).length === 0) + return; + const missing = gen.let("missing"); + for (const prop in propertyDeps) { + const deps = propertyDeps[prop]; + if (deps.length === 0) + continue; + const hasProperty = (0, code_1.propertyInData)(gen, data2, prop, it.opts.ownProperties); + cxt.setParams({ + property: prop, + depsCount: deps.length, + deps: deps.join(", ") + }); + if (it.allErrors) { + gen.if(hasProperty, () => { + for (const depProp of deps) { + (0, code_1.checkReportMissingProp)(cxt, depProp); + } + }); + } else { + gen.if((0, codegen_1._)`${hasProperty} && (${(0, code_1.checkMissingProp)(cxt, deps, missing)})`); + (0, code_1.reportMissingProp)(cxt, missing); + gen.else(); + } + } + } + exports.validatePropertyDeps = validatePropertyDeps; + function validateSchemaDeps(cxt, schemaDeps = cxt.schema) { + const { gen, data: data2, keyword, it } = cxt; + const valid = gen.name("valid"); + for (const prop in schemaDeps) { + if ((0, util_1.alwaysValidSchema)(it, schemaDeps[prop])) + continue; + gen.if( + (0, code_1.propertyInData)(gen, data2, prop, it.opts.ownProperties), + () => { + const schCxt = cxt.subschema({ keyword, schemaProp: prop }, valid); + cxt.mergeValidEvaluated(schCxt, valid); + }, + () => gen.var(valid, true) + // TODO var + ); + cxt.ok(valid); + } + } + exports.validateSchemaDeps = validateSchemaDeps; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/propertyNames.js +var require_propertyNames = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/propertyNames.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var error50 = { + message: "property name must be valid", + params: ({ params }) => (0, codegen_1._)`{propertyName: ${params.propertyName}}` + }; + var def = { + keyword: "propertyNames", + type: "object", + schemaType: ["object", "boolean"], + error: error50, + code(cxt) { + const { gen, schema: schema2, data: data2, it } = cxt; + if ((0, util_1.alwaysValidSchema)(it, schema2)) + return; + const valid = gen.name("valid"); + gen.forIn("key", data2, (key) => { + cxt.setParams({ propertyName: key }); + cxt.subschema({ + keyword: "propertyNames", + data: key, + dataTypes: ["string"], + propertyName: key, + compositeRule: true + }, valid); + gen.if((0, codegen_1.not)(valid), () => { + cxt.error(true); + if (!it.allErrors) + gen.break(); + }); + }); + cxt.ok(valid); + } + }; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js +var require_additionalProperties = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var code_1 = require_code2(); + var codegen_1 = require_codegen(); + var names_1 = require_names(); + var util_1 = require_util(); + var error50 = { + message: "must NOT have additional properties", + params: ({ params }) => (0, codegen_1._)`{additionalProperty: ${params.additionalProperty}}` + }; + var def = { + keyword: "additionalProperties", + type: ["object"], + schemaType: ["boolean", "object"], + allowUndefined: true, + trackErrors: true, + error: error50, + code(cxt) { + const { gen, schema: schema2, parentSchema, data: data2, errsCount, it } = cxt; + if (!errsCount) + throw new Error("ajv implementation error"); + const { allErrors, opts } = it; + it.props = true; + if (opts.removeAdditional !== "all" && (0, util_1.alwaysValidSchema)(it, schema2)) + return; + const props = (0, code_1.allSchemaProperties)(parentSchema.properties); + const patProps = (0, code_1.allSchemaProperties)(parentSchema.patternProperties); + checkAdditionalProperties(); + cxt.ok((0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); + function checkAdditionalProperties() { + gen.forIn("key", data2, (key) => { + if (!props.length && !patProps.length) + additionalPropertyCode(key); + else + gen.if(isAdditional(key), () => additionalPropertyCode(key)); + }); + } + function isAdditional(key) { + let definedProp; + if (props.length > 8) { + const propsSchema = (0, util_1.schemaRefOrVal)(it, parentSchema.properties, "properties"); + definedProp = (0, code_1.isOwnProperty)(gen, propsSchema, key); + } else if (props.length) { + definedProp = (0, codegen_1.or)(...props.map((p5) => (0, codegen_1._)`${key} === ${p5}`)); + } else { + definedProp = codegen_1.nil; + } + if (patProps.length) { + definedProp = (0, codegen_1.or)(definedProp, ...patProps.map((p5) => (0, codegen_1._)`${(0, code_1.usePattern)(cxt, p5)}.test(${key})`)); + } + return (0, codegen_1.not)(definedProp); + } + function deleteAdditional(key) { + gen.code((0, codegen_1._)`delete ${data2}[${key}]`); + } + function additionalPropertyCode(key) { + if (opts.removeAdditional === "all" || opts.removeAdditional && schema2 === false) { + deleteAdditional(key); + return; + } + if (schema2 === false) { + cxt.setParams({ additionalProperty: key }); + cxt.error(); + if (!allErrors) + gen.break(); + return; + } + if (typeof schema2 == "object" && !(0, util_1.alwaysValidSchema)(it, schema2)) { + const valid = gen.name("valid"); + if (opts.removeAdditional === "failing") { + applyAdditionalSchema(key, valid, false); + gen.if((0, codegen_1.not)(valid), () => { + cxt.reset(); + deleteAdditional(key); + }); + } else { + applyAdditionalSchema(key, valid); + if (!allErrors) + gen.if((0, codegen_1.not)(valid), () => gen.break()); + } + } + } + function applyAdditionalSchema(key, valid, errors) { + const subschema = { + keyword: "additionalProperties", + dataProp: key, + dataPropType: util_1.Type.Str + }; + if (errors === false) { + Object.assign(subschema, { + compositeRule: true, + createErrors: false, + allErrors: false + }); + } + cxt.subschema(subschema, valid); + } + } + }; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/properties.js +var require_properties = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/properties.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var validate_1 = require_validate(); + var code_1 = require_code2(); + var util_1 = require_util(); + var additionalProperties_1 = require_additionalProperties(); + var def = { + keyword: "properties", + type: "object", + schemaType: "object", + code(cxt) { + const { gen, schema: schema2, parentSchema, data: data2, it } = cxt; + if (it.opts.removeAdditional === "all" && parentSchema.additionalProperties === void 0) { + additionalProperties_1.default.code(new validate_1.KeywordCxt(it, additionalProperties_1.default, "additionalProperties")); + } + const allProps = (0, code_1.allSchemaProperties)(schema2); + for (const prop of allProps) { + it.definedProperties.add(prop); + } + if (it.opts.unevaluated && allProps.length && it.props !== true) { + it.props = util_1.mergeEvaluated.props(gen, (0, util_1.toHash)(allProps), it.props); + } + const properties = allProps.filter((p5) => !(0, util_1.alwaysValidSchema)(it, schema2[p5])); + if (properties.length === 0) + return; + const valid = gen.name("valid"); + for (const prop of properties) { + if (hasDefault(prop)) { + applyPropertySchema(prop); + } else { + gen.if((0, code_1.propertyInData)(gen, data2, prop, it.opts.ownProperties)); + applyPropertySchema(prop); + if (!it.allErrors) + gen.else().var(valid, true); + gen.endIf(); + } + cxt.it.definedProperties.add(prop); + cxt.ok(valid); + } + function hasDefault(prop) { + return it.opts.useDefaults && !it.compositeRule && schema2[prop].default !== void 0; + } + function applyPropertySchema(prop) { + cxt.subschema({ + keyword: "properties", + schemaProp: prop, + dataProp: prop + }, valid); + } + } + }; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/patternProperties.js +var require_patternProperties = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/patternProperties.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var code_1 = require_code2(); + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var util_2 = require_util(); + var def = { + keyword: "patternProperties", + type: "object", + schemaType: "object", + code(cxt) { + const { gen, schema: schema2, data: data2, parentSchema, it } = cxt; + const { opts } = it; + const patterns = (0, code_1.allSchemaProperties)(schema2); + const alwaysValidPatterns = patterns.filter((p5) => (0, util_1.alwaysValidSchema)(it, schema2[p5])); + if (patterns.length === 0 || alwaysValidPatterns.length === patterns.length && (!it.opts.unevaluated || it.props === true)) { + return; + } + const checkProperties = opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties; + const valid = gen.name("valid"); + if (it.props !== true && !(it.props instanceof codegen_1.Name)) { + it.props = (0, util_2.evaluatedPropsToName)(gen, it.props); + } + const { props } = it; + validatePatternProperties(); + function validatePatternProperties() { + for (const pat of patterns) { + if (checkProperties) + checkMatchingProperties(pat); + if (it.allErrors) { + validateProperties(pat); + } else { + gen.var(valid, true); + validateProperties(pat); + gen.if(valid); + } + } + } + function checkMatchingProperties(pat) { + for (const prop in checkProperties) { + if (new RegExp(pat).test(prop)) { + (0, util_1.checkStrictMode)(it, `property ${prop} matches pattern ${pat} (use allowMatchingProperties)`); + } + } + } + function validateProperties(pat) { + gen.forIn("key", data2, (key) => { + gen.if((0, codegen_1._)`${(0, code_1.usePattern)(cxt, pat)}.test(${key})`, () => { + const alwaysValid = alwaysValidPatterns.includes(pat); + if (!alwaysValid) { + cxt.subschema({ + keyword: "patternProperties", + schemaProp: pat, + dataProp: key, + dataPropType: util_2.Type.Str + }, valid); + } + if (it.opts.unevaluated && props !== true) { + gen.assign((0, codegen_1._)`${props}[${key}]`, true); + } else if (!alwaysValid && !it.allErrors) { + gen.if((0, codegen_1.not)(valid), () => gen.break()); + } + }); + }); + } + } + }; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/not.js +var require_not = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/not.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var util_1 = require_util(); + var def = { + keyword: "not", + schemaType: ["object", "boolean"], + trackErrors: true, + code(cxt) { + const { gen, schema: schema2, it } = cxt; + if ((0, util_1.alwaysValidSchema)(it, schema2)) { + cxt.fail(); + return; + } + const valid = gen.name("valid"); + cxt.subschema({ + keyword: "not", + compositeRule: true, + createErrors: false, + allErrors: false + }, valid); + cxt.failResult(valid, () => cxt.reset(), () => cxt.error()); + }, + error: { message: "must NOT be valid" } + }; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/anyOf.js +var require_anyOf = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/anyOf.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var code_1 = require_code2(); + var def = { + keyword: "anyOf", + schemaType: "array", + trackErrors: true, + code: code_1.validateUnion, + error: { message: "must match a schema in anyOf" } + }; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/oneOf.js +var require_oneOf = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/oneOf.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var error50 = { + message: "must match exactly one schema in oneOf", + params: ({ params }) => (0, codegen_1._)`{passingSchemas: ${params.passing}}` + }; + var def = { + keyword: "oneOf", + schemaType: "array", + trackErrors: true, + error: error50, + code(cxt) { + const { gen, schema: schema2, parentSchema, it } = cxt; + if (!Array.isArray(schema2)) + throw new Error("ajv implementation error"); + if (it.opts.discriminator && parentSchema.discriminator) + return; + const schArr = schema2; + const valid = gen.let("valid", false); + const passing = gen.let("passing", null); + const schValid = gen.name("_valid"); + cxt.setParams({ passing }); + gen.block(validateOneOf); + cxt.result(valid, () => cxt.reset(), () => cxt.error(true)); + function validateOneOf() { + schArr.forEach((sch, i5) => { + let schCxt; + if ((0, util_1.alwaysValidSchema)(it, sch)) { + gen.var(schValid, true); + } else { + schCxt = cxt.subschema({ + keyword: "oneOf", + schemaProp: i5, + compositeRule: true + }, schValid); + } + if (i5 > 0) { + gen.if((0, codegen_1._)`${schValid} && ${valid}`).assign(valid, false).assign(passing, (0, codegen_1._)`[${passing}, ${i5}]`).else(); + } + gen.if(schValid, () => { + gen.assign(valid, true); + gen.assign(passing, i5); + if (schCxt) + cxt.mergeEvaluated(schCxt, codegen_1.Name); + }); + }); + } + } + }; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/allOf.js +var require_allOf = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/allOf.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var util_1 = require_util(); + var def = { + keyword: "allOf", + schemaType: "array", + code(cxt) { + const { gen, schema: schema2, it } = cxt; + if (!Array.isArray(schema2)) + throw new Error("ajv implementation error"); + const valid = gen.name("valid"); + schema2.forEach((sch, i5) => { + if ((0, util_1.alwaysValidSchema)(it, sch)) + return; + const schCxt = cxt.subschema({ keyword: "allOf", schemaProp: i5 }, valid); + cxt.ok(valid); + cxt.mergeEvaluated(schCxt); + }); + } + }; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/if.js +var require_if = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/if.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var error50 = { + message: ({ params }) => (0, codegen_1.str)`must match "${params.ifClause}" schema`, + params: ({ params }) => (0, codegen_1._)`{failingKeyword: ${params.ifClause}}` + }; + var def = { + keyword: "if", + schemaType: ["object", "boolean"], + trackErrors: true, + error: error50, + code(cxt) { + const { gen, parentSchema, it } = cxt; + if (parentSchema.then === void 0 && parentSchema.else === void 0) { + (0, util_1.checkStrictMode)(it, '"if" without "then" and "else" is ignored'); + } + const hasThen = hasSchema(it, "then"); + const hasElse = hasSchema(it, "else"); + if (!hasThen && !hasElse) + return; + const valid = gen.let("valid", true); + const schValid = gen.name("_valid"); + validateIf(); + cxt.reset(); + if (hasThen && hasElse) { + const ifClause = gen.let("ifClause"); + cxt.setParams({ ifClause }); + gen.if(schValid, validateClause("then", ifClause), validateClause("else", ifClause)); + } else if (hasThen) { + gen.if(schValid, validateClause("then")); + } else { + gen.if((0, codegen_1.not)(schValid), validateClause("else")); + } + cxt.pass(valid, () => cxt.error(true)); + function validateIf() { + const schCxt = cxt.subschema({ + keyword: "if", + compositeRule: true, + createErrors: false, + allErrors: false + }, schValid); + cxt.mergeEvaluated(schCxt); + } + function validateClause(keyword, ifClause) { + return () => { + const schCxt = cxt.subschema({ keyword }, schValid); + gen.assign(valid, schValid); + cxt.mergeValidEvaluated(schCxt, valid); + if (ifClause) + gen.assign(ifClause, (0, codegen_1._)`${keyword}`); + else + cxt.setParams({ ifClause: keyword }); + }; + } + } + }; + function hasSchema(it, keyword) { + const schema2 = it.schema[keyword]; + return schema2 !== void 0 && !(0, util_1.alwaysValidSchema)(it, schema2); + } + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/thenElse.js +var require_thenElse = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/thenElse.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var util_1 = require_util(); + var def = { + keyword: ["then", "else"], + schemaType: ["object", "boolean"], + code({ keyword, parentSchema, it }) { + if (parentSchema.if === void 0) + (0, util_1.checkStrictMode)(it, `"${keyword}" without "if" is ignored`); + } + }; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/index.js +var require_applicator = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/index.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var additionalItems_1 = require_additionalItems(); + var prefixItems_1 = require_prefixItems(); + var items_1 = require_items(); + var items2020_1 = require_items2020(); + var contains_1 = require_contains(); + var dependencies_1 = require_dependencies(); + var propertyNames_1 = require_propertyNames(); + var additionalProperties_1 = require_additionalProperties(); + var properties_1 = require_properties(); + var patternProperties_1 = require_patternProperties(); + var not_1 = require_not(); + var anyOf_1 = require_anyOf(); + var oneOf_1 = require_oneOf(); + var allOf_1 = require_allOf(); + var if_1 = require_if(); + var thenElse_1 = require_thenElse(); + function getApplicator(draft2020 = false) { + const applicator = [ + // any + not_1.default, + anyOf_1.default, + oneOf_1.default, + allOf_1.default, + if_1.default, + thenElse_1.default, + // object + propertyNames_1.default, + additionalProperties_1.default, + dependencies_1.default, + properties_1.default, + patternProperties_1.default + ]; + if (draft2020) + applicator.push(prefixItems_1.default, items2020_1.default); + else + applicator.push(additionalItems_1.default, items_1.default); + applicator.push(contains_1.default); + return applicator; + } + exports.default = getApplicator; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/format/format.js +var require_format = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/format/format.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var error50 = { + message: ({ schemaCode }) => (0, codegen_1.str)`must match format "${schemaCode}"`, + params: ({ schemaCode }) => (0, codegen_1._)`{format: ${schemaCode}}` + }; + var def = { + keyword: "format", + type: ["number", "string"], + schemaType: "string", + $data: true, + error: error50, + code(cxt, ruleType) { + const { gen, data: data2, $data, schema: schema2, schemaCode, it } = cxt; + const { opts, errSchemaPath, schemaEnv, self: self2 } = it; + if (!opts.validateFormats) + return; + if ($data) + validate$DataFormat(); + else + validateFormat(); + function validate$DataFormat() { + const fmts = gen.scopeValue("formats", { + ref: self2.formats, + code: opts.code.formats + }); + const fDef = gen.const("fDef", (0, codegen_1._)`${fmts}[${schemaCode}]`); + const fType = gen.let("fType"); + const format2 = gen.let("format"); + gen.if((0, codegen_1._)`typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`, () => gen.assign(fType, (0, codegen_1._)`${fDef}.type || "string"`).assign(format2, (0, codegen_1._)`${fDef}.validate`), () => gen.assign(fType, (0, codegen_1._)`"string"`).assign(format2, fDef)); + cxt.fail$data((0, codegen_1.or)(unknownFmt(), invalidFmt())); + function unknownFmt() { + if (opts.strictSchema === false) + return codegen_1.nil; + return (0, codegen_1._)`${schemaCode} && !${format2}`; + } + function invalidFmt() { + const callFormat = schemaEnv.$async ? (0, codegen_1._)`(${fDef}.async ? await ${format2}(${data2}) : ${format2}(${data2}))` : (0, codegen_1._)`${format2}(${data2})`; + const validData = (0, codegen_1._)`(typeof ${format2} == "function" ? ${callFormat} : ${format2}.test(${data2}))`; + return (0, codegen_1._)`${format2} && ${format2} !== true && ${fType} === ${ruleType} && !${validData}`; + } + } + function validateFormat() { + const formatDef = self2.formats[schema2]; + if (!formatDef) { + unknownFormat(); + return; + } + if (formatDef === true) + return; + const [fmtType, format2, fmtRef] = getFormat(formatDef); + if (fmtType === ruleType) + cxt.pass(validCondition()); + function unknownFormat() { + if (opts.strictSchema === false) { + self2.logger.warn(unknownMsg()); + return; + } + throw new Error(unknownMsg()); + function unknownMsg() { + return `unknown format "${schema2}" ignored in schema at path "${errSchemaPath}"`; + } + } + function getFormat(fmtDef) { + const code = fmtDef instanceof RegExp ? (0, codegen_1.regexpCode)(fmtDef) : opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(schema2)}` : void 0; + const fmt = gen.scopeValue("formats", { key: schema2, ref: fmtDef, code }); + if (typeof fmtDef == "object" && !(fmtDef instanceof RegExp)) { + return [fmtDef.type || "string", fmtDef.validate, (0, codegen_1._)`${fmt}.validate`]; + } + return ["string", fmtDef, fmt]; + } + function validCondition() { + if (typeof formatDef == "object" && !(formatDef instanceof RegExp) && formatDef.async) { + if (!schemaEnv.$async) + throw new Error("async format in sync schema"); + return (0, codegen_1._)`await ${fmtRef}(${data2})`; + } + return typeof format2 == "function" ? (0, codegen_1._)`${fmtRef}(${data2})` : (0, codegen_1._)`${fmtRef}.test(${data2})`; + } + } + } + }; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/format/index.js +var require_format2 = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/format/index.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var format_1 = require_format(); + var format2 = [format_1.default]; + exports.default = format2; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/metadata.js +var require_metadata = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/metadata.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.contentVocabulary = exports.metadataVocabulary = void 0; + exports.metadataVocabulary = [ + "title", + "description", + "default", + "deprecated", + "readOnly", + "writeOnly", + "examples" + ]; + exports.contentVocabulary = [ + "contentMediaType", + "contentEncoding", + "contentSchema" + ]; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/draft7.js +var require_draft7 = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/draft7.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var core_1 = require_core2(); + var validation_1 = require_validation2(); + var applicator_1 = require_applicator(); + var format_1 = require_format2(); + var metadata_1 = require_metadata(); + var draft7Vocabularies = [ + core_1.default, + validation_1.default, + (0, applicator_1.default)(), + format_1.default, + metadata_1.metadataVocabulary, + metadata_1.contentVocabulary + ]; + exports.default = draft7Vocabularies; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/discriminator/types.js +var require_types = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/discriminator/types.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.DiscrError = void 0; + var DiscrError; + (function(DiscrError2) { + DiscrError2["Tag"] = "tag"; + DiscrError2["Mapping"] = "mapping"; + })(DiscrError || (exports.DiscrError = DiscrError = {})); + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/discriminator/index.js +var require_discriminator = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/discriminator/index.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var types_1 = require_types(); + var compile_1 = require_compile(); + var ref_error_1 = require_ref_error(); + var util_1 = require_util(); + var error50 = { + message: ({ params: { discrError, tagName } }) => discrError === types_1.DiscrError.Tag ? `tag "${tagName}" must be string` : `value of tag "${tagName}" must be in oneOf`, + params: ({ params: { discrError, tag: tag3, tagName } }) => (0, codegen_1._)`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag3}}` + }; + var def = { + keyword: "discriminator", + type: "object", + schemaType: "object", + error: error50, + code(cxt) { + const { gen, data: data2, schema: schema2, parentSchema, it } = cxt; + const { oneOf } = parentSchema; + if (!it.opts.discriminator) { + throw new Error("discriminator: requires discriminator option"); + } + const tagName = schema2.propertyName; + if (typeof tagName != "string") + throw new Error("discriminator: requires propertyName"); + if (schema2.mapping) + throw new Error("discriminator: mapping is not supported"); + if (!oneOf) + throw new Error("discriminator: requires oneOf keyword"); + const valid = gen.let("valid", false); + const tag3 = gen.const("tag", (0, codegen_1._)`${data2}${(0, codegen_1.getProperty)(tagName)}`); + gen.if((0, codegen_1._)`typeof ${tag3} == "string"`, () => validateMapping(), () => cxt.error(false, { discrError: types_1.DiscrError.Tag, tag: tag3, tagName })); + cxt.ok(valid); + function validateMapping() { + const mapping = getMapping(); + gen.if(false); + for (const tagValue in mapping) { + gen.elseIf((0, codegen_1._)`${tag3} === ${tagValue}`); + gen.assign(valid, applyTagSchema(mapping[tagValue])); + } + gen.else(); + cxt.error(false, { discrError: types_1.DiscrError.Mapping, tag: tag3, tagName }); + gen.endIf(); + } + function applyTagSchema(schemaProp) { + const _valid = gen.name("valid"); + const schCxt = cxt.subschema({ keyword: "oneOf", schemaProp }, _valid); + cxt.mergeEvaluated(schCxt, codegen_1.Name); + return _valid; + } + function getMapping() { + var _a6; + const oneOfMapping = {}; + const topRequired = hasRequired(parentSchema); + let tagRequired = true; + for (let i5 = 0; i5 < oneOf.length; i5++) { + let sch = oneOf[i5]; + if ((sch === null || sch === void 0 ? void 0 : sch.$ref) && !(0, util_1.schemaHasRulesButRef)(sch, it.self.RULES)) { + const ref = sch.$ref; + sch = compile_1.resolveRef.call(it.self, it.schemaEnv.root, it.baseId, ref); + if (sch instanceof compile_1.SchemaEnv) + sch = sch.schema; + if (sch === void 0) + throw new ref_error_1.default(it.opts.uriResolver, it.baseId, ref); + } + const propSch = (_a6 = sch === null || sch === void 0 ? void 0 : sch.properties) === null || _a6 === void 0 ? void 0 : _a6[tagName]; + if (typeof propSch != "object") { + throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${tagName}"`); + } + tagRequired = tagRequired && (topRequired || hasRequired(sch)); + addMappings(propSch, i5); + } + if (!tagRequired) + throw new Error(`discriminator: "${tagName}" must be required`); + return oneOfMapping; + function hasRequired({ required: required2 }) { + return Array.isArray(required2) && required2.includes(tagName); + } + function addMappings(sch, i5) { + if (sch.const) { + addMapping(sch.const, i5); + } else if (sch.enum) { + for (const tagValue of sch.enum) { + addMapping(tagValue, i5); + } + } else { + throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`); + } + } + function addMapping(tagValue, i5) { + if (typeof tagValue != "string" || tagValue in oneOfMapping) { + throw new Error(`discriminator: "${tagName}" values must be unique strings`); + } + oneOfMapping[tagValue] = i5; + } + } + } + }; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-draft-07.json +var require_json_schema_draft_07 = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-draft-07.json"(exports, module) { + module.exports = { + $schema: "http://json-schema.org/draft-07/schema#", + $id: "http://json-schema.org/draft-07/schema#", + title: "Core schema meta-schema", + definitions: { + schemaArray: { + type: "array", + minItems: 1, + items: { $ref: "#" } + }, + nonNegativeInteger: { + type: "integer", + minimum: 0 + }, + nonNegativeIntegerDefault0: { + allOf: [{ $ref: "#/definitions/nonNegativeInteger" }, { default: 0 }] + }, + simpleTypes: { + enum: ["array", "boolean", "integer", "null", "number", "object", "string"] + }, + stringArray: { + type: "array", + items: { type: "string" }, + uniqueItems: true, + default: [] + } + }, + type: ["object", "boolean"], + properties: { + $id: { + type: "string", + format: "uri-reference" + }, + $schema: { + type: "string", + format: "uri" + }, + $ref: { + type: "string", + format: "uri-reference" + }, + $comment: { + type: "string" + }, + title: { + type: "string" + }, + description: { + type: "string" + }, + default: true, + readOnly: { + type: "boolean", + default: false + }, + examples: { + type: "array", + items: true + }, + multipleOf: { + type: "number", + exclusiveMinimum: 0 + }, + maximum: { + type: "number" + }, + exclusiveMaximum: { + type: "number" + }, + minimum: { + type: "number" + }, + exclusiveMinimum: { + type: "number" + }, + maxLength: { $ref: "#/definitions/nonNegativeInteger" }, + minLength: { $ref: "#/definitions/nonNegativeIntegerDefault0" }, + pattern: { + type: "string", + format: "regex" + }, + additionalItems: { $ref: "#" }, + items: { + anyOf: [{ $ref: "#" }, { $ref: "#/definitions/schemaArray" }], + default: true + }, + maxItems: { $ref: "#/definitions/nonNegativeInteger" }, + minItems: { $ref: "#/definitions/nonNegativeIntegerDefault0" }, + uniqueItems: { + type: "boolean", + default: false + }, + contains: { $ref: "#" }, + maxProperties: { $ref: "#/definitions/nonNegativeInteger" }, + minProperties: { $ref: "#/definitions/nonNegativeIntegerDefault0" }, + required: { $ref: "#/definitions/stringArray" }, + additionalProperties: { $ref: "#" }, + definitions: { + type: "object", + additionalProperties: { $ref: "#" }, + default: {} + }, + properties: { + type: "object", + additionalProperties: { $ref: "#" }, + default: {} + }, + patternProperties: { + type: "object", + additionalProperties: { $ref: "#" }, + propertyNames: { format: "regex" }, + default: {} + }, + dependencies: { + type: "object", + additionalProperties: { + anyOf: [{ $ref: "#" }, { $ref: "#/definitions/stringArray" }] + } + }, + propertyNames: { $ref: "#" }, + const: true, + enum: { + type: "array", + items: true, + minItems: 1, + uniqueItems: true + }, + type: { + anyOf: [ + { $ref: "#/definitions/simpleTypes" }, + { + type: "array", + items: { $ref: "#/definitions/simpleTypes" }, + minItems: 1, + uniqueItems: true + } + ] + }, + format: { type: "string" }, + contentMediaType: { type: "string" }, + contentEncoding: { type: "string" }, + if: { $ref: "#" }, + then: { $ref: "#" }, + else: { $ref: "#" }, + allOf: { $ref: "#/definitions/schemaArray" }, + anyOf: { $ref: "#/definitions/schemaArray" }, + oneOf: { $ref: "#/definitions/schemaArray" }, + not: { $ref: "#" } + }, + default: true + }; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/ajv.js +var require_ajv = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/ajv.js"(exports, module) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv = void 0; + var core_1 = require_core(); + var draft7_1 = require_draft7(); + var discriminator_1 = require_discriminator(); + var draft7MetaSchema = require_json_schema_draft_07(); + var META_SUPPORT_DATA = ["/properties"]; + var META_SCHEMA_ID = "http://json-schema.org/draft-07/schema"; + var Ajv2 = class extends core_1.default { + _addVocabularies() { + super._addVocabularies(); + draft7_1.default.forEach((v5) => this.addVocabulary(v5)); + if (this.opts.discriminator) + this.addKeyword(discriminator_1.default); + } + _addDefaultMetaSchema() { + super._addDefaultMetaSchema(); + if (!this.opts.meta) + return; + const metaSchema = this.opts.$data ? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA) : draft7MetaSchema; + this.addMetaSchema(metaSchema, META_SCHEMA_ID, false); + this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID; + } + defaultMeta() { + return this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : void 0); + } + }; + exports.Ajv = Ajv2; + module.exports = exports = Ajv2; + module.exports.Ajv = Ajv2; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.default = Ajv2; + var validate_1 = require_validate(); + Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function() { + return validate_1.KeywordCxt; + } }); + var codegen_1 = require_codegen(); + Object.defineProperty(exports, "_", { enumerable: true, get: function() { + return codegen_1._; + } }); + Object.defineProperty(exports, "str", { enumerable: true, get: function() { + return codegen_1.str; + } }); + Object.defineProperty(exports, "stringify", { enumerable: true, get: function() { + return codegen_1.stringify; + } }); + Object.defineProperty(exports, "nil", { enumerable: true, get: function() { + return codegen_1.nil; + } }); + Object.defineProperty(exports, "Name", { enumerable: true, get: function() { + return codegen_1.Name; + } }); + Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function() { + return codegen_1.CodeGen; + } }); + var validation_error_1 = require_validation_error(); + Object.defineProperty(exports, "ValidationError", { enumerable: true, get: function() { + return validation_error_1.default; + } }); + var ref_error_1 = require_ref_error(); + Object.defineProperty(exports, "MissingRefError", { enumerable: true, get: function() { + return ref_error_1.default; + } }); + } +}); + +// node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.18.0/node_modules/ajv-formats/dist/formats.js +var require_formats2 = __commonJS({ + "node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.18.0/node_modules/ajv-formats/dist/formats.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.formatNames = exports.fastFormats = exports.fullFormats = void 0; + function fmtDef(validate2, compare) { + return { validate: validate2, compare }; + } + exports.fullFormats = { + // date: http://tools.ietf.org/html/rfc3339#section-5.6 + date: fmtDef(date7, compareDate), + // date-time: http://tools.ietf.org/html/rfc3339#section-5.6 + time: fmtDef(getTime(true), compareTime), + "date-time": fmtDef(getDateTime(true), compareDateTime), + "iso-time": fmtDef(getTime(), compareIsoTime), + "iso-date-time": fmtDef(getDateTime(), compareIsoDateTime), + // duration: https://tools.ietf.org/html/rfc3339#appendix-A + duration: /^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/, + uri, + "uri-reference": /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i, + // uri-template: https://tools.ietf.org/html/rfc6570 + "uri-template": /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i, + // For the source: https://gist.github.com/dperini/729294 + // For test cases: https://mathiasbynens.be/demo/url-regex + url: /^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu, + email: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i, + hostname: /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i, + // optimized https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html + ipv4: /^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/, + ipv6: /^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i, + regex, + // uuid: http://tools.ietf.org/html/rfc4122 + uuid: /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i, + // JSON-pointer: https://tools.ietf.org/html/rfc6901 + // uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A + "json-pointer": /^(?:\/(?:[^~/]|~0|~1)*)*$/, + "json-pointer-uri-fragment": /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i, + // relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00 + "relative-json-pointer": /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/, + // the following formats are used by the openapi specification: https://spec.openapis.org/oas/v3.0.0#data-types + // byte: https://github.com/miguelmota/is-base64 + byte, + // signed 32 bit integer + int32: { type: "number", validate: validateInt32 }, + // signed 64 bit integer + int64: { type: "number", validate: validateInt64 }, + // C-type float + float: { type: "number", validate: validateNumber }, + // C-type double + double: { type: "number", validate: validateNumber }, + // hint to the UI to hide input strings + password: true, + // unchecked string payload + binary: true + }; + exports.fastFormats = { + ...exports.fullFormats, + date: fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d$/, compareDate), + time: fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareTime), + "date-time": fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareDateTime), + "iso-time": fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, compareIsoTime), + "iso-date-time": fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, compareIsoDateTime), + // uri: https://github.com/mafintosh/is-my-json-valid/blob/master/formats.js + uri: /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i, + "uri-reference": /^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i, + // email (sources from jsen validator): + // http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address#answer-8829363 + // http://www.w3.org/TR/html5/forms.html#valid-e-mail-address (search for 'wilful violation') + email: /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i + }; + exports.formatNames = Object.keys(exports.fullFormats); + function isLeapYear2(year3) { + return year3 % 4 === 0 && (year3 % 100 !== 0 || year3 % 400 === 0); + } + var DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/; + var DAYS2 = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; + function date7(str) { + const matches = DATE.exec(str); + if (!matches) + return false; + const year3 = +matches[1]; + const month = +matches[2]; + const day2 = +matches[3]; + return month >= 1 && month <= 12 && day2 >= 1 && day2 <= (month === 2 && isLeapYear2(year3) ? 29 : DAYS2[month]); + } + function compareDate(d1, d22) { + if (!(d1 && d22)) + return void 0; + if (d1 > d22) + return 1; + if (d1 < d22) + return -1; + return 0; + } + var TIME = /^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i; + function getTime(strictTimeZone) { + return function time5(str) { + const matches = TIME.exec(str); + if (!matches) + return false; + const hr = +matches[1]; + const min = +matches[2]; + const sec2 = +matches[3]; + const tz = matches[4]; + const tzSign = matches[5] === "-" ? -1 : 1; + const tzH = +(matches[6] || 0); + const tzM = +(matches[7] || 0); + if (tzH > 23 || tzM > 59 || strictTimeZone && !tz) + return false; + if (hr <= 23 && min <= 59 && sec2 < 60) + return true; + const utcMin = min - tzM * tzSign; + const utcHr = hr - tzH * tzSign - (utcMin < 0 ? 1 : 0); + return (utcHr === 23 || utcHr === -1) && (utcMin === 59 || utcMin === -1) && sec2 < 61; + }; + } + function compareTime(s1, s22) { + if (!(s1 && s22)) + return void 0; + const t1 = (/* @__PURE__ */ new Date("2020-01-01T" + s1)).valueOf(); + const t22 = (/* @__PURE__ */ new Date("2020-01-01T" + s22)).valueOf(); + if (!(t1 && t22)) + return void 0; + return t1 - t22; + } + function compareIsoTime(t1, t22) { + if (!(t1 && t22)) + return void 0; + const a1 = TIME.exec(t1); + const a22 = TIME.exec(t22); + if (!(a1 && a22)) + return void 0; + t1 = a1[1] + a1[2] + a1[3]; + t22 = a22[1] + a22[2] + a22[3]; + if (t1 > t22) + return 1; + if (t1 < t22) + return -1; + return 0; + } + var DATE_TIME_SEPARATOR = /t|\s/i; + function getDateTime(strictTimeZone) { + const time5 = getTime(strictTimeZone); + return function date_time(str) { + const dateTime = str.split(DATE_TIME_SEPARATOR); + return dateTime.length === 2 && date7(dateTime[0]) && time5(dateTime[1]); + }; + } + function compareDateTime(dt1, dt2) { + if (!(dt1 && dt2)) + return void 0; + const d1 = new Date(dt1).valueOf(); + const d22 = new Date(dt2).valueOf(); + if (!(d1 && d22)) + return void 0; + return d1 - d22; + } + function compareIsoDateTime(dt1, dt2) { + if (!(dt1 && dt2)) + return void 0; + const [d1, t1] = dt1.split(DATE_TIME_SEPARATOR); + const [d22, t22] = dt2.split(DATE_TIME_SEPARATOR); + const res = compareDate(d1, d22); + if (res === void 0) + return void 0; + return res || compareTime(t1, t22); + } + var NOT_URI_FRAGMENT = /\/|:/; + var URI = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; + function uri(str) { + return NOT_URI_FRAGMENT.test(str) && URI.test(str); + } + var BYTE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm; + function byte(str) { + BYTE.lastIndex = 0; + return BYTE.test(str); + } + var MIN_INT32 = -(2 ** 31); + var MAX_INT322 = 2 ** 31 - 1; + function validateInt32(value) { + return Number.isInteger(value) && value <= MAX_INT322 && value >= MIN_INT32; + } + function validateInt64(value) { + return Number.isInteger(value); + } + function validateNumber() { + return true; + } + var Z_ANCHOR = /[^\\]\\Z/; + function regex(str) { + if (Z_ANCHOR.test(str)) + return false; + try { + new RegExp(str); + return true; + } catch (e5) { + return false; + } + } + } +}); + +// node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.18.0/node_modules/ajv-formats/dist/limit.js +var require_limit = __commonJS({ + "node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.18.0/node_modules/ajv-formats/dist/limit.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.formatLimitDefinition = void 0; + var ajv_1 = require_ajv(); + var codegen_1 = require_codegen(); + var ops = codegen_1.operators; + var KWDs = { + formatMaximum: { okStr: "<=", ok: ops.LTE, fail: ops.GT }, + formatMinimum: { okStr: ">=", ok: ops.GTE, fail: ops.LT }, + formatExclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE }, + formatExclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE } + }; + var error50 = { + message: ({ keyword, schemaCode }) => (0, codegen_1.str)`should be ${KWDs[keyword].okStr} ${schemaCode}`, + params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}` + }; + exports.formatLimitDefinition = { + keyword: Object.keys(KWDs), + type: "string", + schemaType: "string", + $data: true, + error: error50, + code(cxt) { + const { gen, data: data2, schemaCode, keyword, it } = cxt; + const { opts, self: self2 } = it; + if (!opts.validateFormats) + return; + const fCxt = new ajv_1.KeywordCxt(it, self2.RULES.all.format.definition, "format"); + if (fCxt.$data) + validate$DataFormat(); + else + validateFormat(); + function validate$DataFormat() { + const fmts = gen.scopeValue("formats", { + ref: self2.formats, + code: opts.code.formats + }); + const fmt = gen.const("fmt", (0, codegen_1._)`${fmts}[${fCxt.schemaCode}]`); + cxt.fail$data((0, codegen_1.or)((0, codegen_1._)`typeof ${fmt} != "object"`, (0, codegen_1._)`${fmt} instanceof RegExp`, (0, codegen_1._)`typeof ${fmt}.compare != "function"`, compareCode(fmt))); + } + function validateFormat() { + const format2 = fCxt.schema; + const fmtDef = self2.formats[format2]; + if (!fmtDef || fmtDef === true) + return; + if (typeof fmtDef != "object" || fmtDef instanceof RegExp || typeof fmtDef.compare != "function") { + throw new Error(`"${keyword}": format "${format2}" does not define "compare" function`); + } + const fmt = gen.scopeValue("formats", { + key: format2, + ref: fmtDef, + code: opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(format2)}` : void 0 + }); + cxt.fail$data(compareCode(fmt)); + } + function compareCode(fmt) { + return (0, codegen_1._)`${fmt}.compare(${data2}, ${schemaCode}) ${KWDs[keyword].fail} 0`; + } + }, + dependencies: ["format"] + }; + var formatLimitPlugin = (ajv) => { + ajv.addKeyword(exports.formatLimitDefinition); + return ajv; + }; + exports.default = formatLimitPlugin; + } +}); + +// node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.18.0/node_modules/ajv-formats/dist/index.js +var require_dist2 = __commonJS({ + "node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.18.0/node_modules/ajv-formats/dist/index.js"(exports, module) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var formats_1 = require_formats2(); + var limit_1 = require_limit(); + var codegen_1 = require_codegen(); + var fullName = new codegen_1.Name("fullFormats"); + var fastName = new codegen_1.Name("fastFormats"); + var formatsPlugin = (ajv, opts = { keywords: true }) => { + if (Array.isArray(opts)) { + addFormats2(ajv, opts, formats_1.fullFormats, fullName); + return ajv; + } + const [formats, exportName] = opts.mode === "fast" ? [formats_1.fastFormats, fastName] : [formats_1.fullFormats, fullName]; + const list2 = opts.formats || formats_1.formatNames; + addFormats2(ajv, list2, formats, exportName); + if (opts.keywords) + (0, limit_1.default)(ajv); + return ajv; + }; + formatsPlugin.get = (name, mode = "full") => { + const formats = mode === "fast" ? formats_1.fastFormats : formats_1.fullFormats; + const f5 = formats[name]; + if (!f5) + throw new Error(`Unknown format "${name}"`); + return f5; + }; + function addFormats2(ajv, list2, fs41, exportName) { + var _a6; + var _b; + (_a6 = (_b = ajv.opts.code).formats) !== null && _a6 !== void 0 ? _a6 : _b.formats = (0, codegen_1._)`require("ajv-formats/dist/formats").${exportName}`; + for (const f5 of list2) + ajv.addFormat(f5, fs41[f5]); + } + module.exports = exports = formatsPlugin; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.default = formatsPlugin; + } +}); + +// node_modules/.pnpm/@better-auth+utils@0.3.0/node_modules/@better-auth/utils/dist/random.mjs +function expandAlphabet(alphabet) { + switch (alphabet) { + case "a-z": + return "abcdefghijklmnopqrstuvwxyz"; + case "A-Z": + return "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + case "0-9": + return "0123456789"; + case "-_": + return "-_"; + default: + throw new Error(`Unsupported alphabet: ${alphabet}`); + } +} +function createRandomStringGenerator(...baseAlphabets) { + const baseCharSet = baseAlphabets.map(expandAlphabet).join(""); + if (baseCharSet.length === 0) { + throw new Error( + "No valid characters provided for random string generation." + ); + } + const baseCharSetLength = baseCharSet.length; + return (length, ...alphabets) => { + if (length <= 0) { + throw new Error("Length must be a positive integer."); + } + let charSet = baseCharSet; + let charSetLength = baseCharSetLength; + if (alphabets.length > 0) { + charSet = alphabets.map(expandAlphabet).join(""); + charSetLength = charSet.length; + } + const maxValid = Math.floor(256 / charSetLength) * charSetLength; + const buf = new Uint8Array(length * 2); + const bufLength = buf.length; + let result = ""; + let bufIndex = bufLength; + let rand; + while (result.length < length) { + if (bufIndex >= bufLength) { + crypto.getRandomValues(buf); + bufIndex = 0; + } + rand = buf[bufIndex++]; + if (rand < maxValid) { + result += charSet[rand % charSetLength]; + } + } + return result; + }; +} +var init_random = __esm({ + "node_modules/.pnpm/@better-auth+utils@0.3.0/node_modules/@better-auth/utils/dist/random.mjs"() { + } +}); + +// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/crypto/random.mjs +var generateRandomString; +var init_random2 = __esm({ + "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/crypto/random.mjs"() { + init_random(); + generateRandomString = createRandomStringGenerator("a-z", "0-9", "A-Z", "-_"); + } +}); + +// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/crypto/buffer.mjs +function constantTimeEqual(a5, b6) { + if (typeof a5 === "string") a5 = new TextEncoder().encode(a5); + if (typeof b6 === "string") b6 = new TextEncoder().encode(b6); + const aBuffer = new Uint8Array(a5); + const bBuffer = new Uint8Array(b6); + let c5 = aBuffer.length ^ bBuffer.length; + const length = Math.max(aBuffer.length, bBuffer.length); + for (let i5 = 0; i5 < length; i5++) c5 |= (i5 < aBuffer.length ? aBuffer[i5] : 0) ^ (i5 < bBuffer.length ? bBuffer[i5] : 0); + return c5 === 0; +} +var init_buffer = __esm({ + "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/crypto/buffer.mjs"() { + } +}); + +// node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/utils.js +function isBytes(a5) { + return a5 instanceof Uint8Array || ArrayBuffer.isView(a5) && a5.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a5 && a5.BYTES_PER_ELEMENT === 1; +} +function anumber(n5, title = "") { + if (typeof n5 !== "number") { + const prefix = title && `"${title}" `; + throw new TypeError(`${prefix}expected number, got ${typeof n5}`); + } + if (!Number.isSafeInteger(n5) || n5 < 0) { + const prefix = title && `"${title}" `; + throw new RangeError(`${prefix}expected integer >= 0, got ${n5}`); + } +} +function abytes(value, length, title = "") { + const bytes = isBytes(value); + const len = value?.length; + const needsLen = length !== void 0; + if (!bytes || needsLen && len !== length) { + const prefix = title && `"${title}" `; + const ofLen = needsLen ? ` of length ${length}` : ""; + const got = bytes ? `length=${len}` : `type=${typeof value}`; + const message2 = prefix + "expected Uint8Array" + ofLen + ", got " + got; + if (!bytes) + throw new TypeError(message2); + throw new RangeError(message2); + } + return value; +} +function ahash(h5) { + if (typeof h5 !== "function" || typeof h5.create !== "function") + throw new TypeError("Hash must wrapped by utils.createHasher"); + anumber(h5.outputLen); + anumber(h5.blockLen); + if (h5.outputLen < 1) + throw new Error('"outputLen" must be >= 1'); + if (h5.blockLen < 1) + throw new Error('"blockLen" must be >= 1'); +} +function aexists(instance, checkFinished = true) { + if (instance.destroyed) + throw new Error("Hash instance has been destroyed"); + if (checkFinished && instance.finished) + throw new Error("Hash#digest() has already been called"); +} +function aoutput(out, instance) { + abytes(out, void 0, "digestInto() output"); + const min = instance.outputLen; + if (out.length < min) { + throw new RangeError('"digestInto() output" expected to be of length >=' + min); + } +} +function u32(arr) { + return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); +} +function clean(...arrays) { + for (let i5 = 0; i5 < arrays.length; i5++) { + arrays[i5].fill(0); + } +} +function createView(arr) { + return new DataView(arr.buffer, arr.byteOffset, arr.byteLength); +} +function rotr(word, shift) { + return word << 32 - shift | word >>> shift; +} +function rotl(word, shift) { + return word << shift | word >>> 32 - shift >>> 0; +} +function byteSwap(word) { + return word << 24 & 4278190080 | word << 8 & 16711680 | word >>> 8 & 65280 | word >>> 24 & 255; +} +function byteSwap32(arr) { + for (let i5 = 0; i5 < arr.length; i5++) { + arr[i5] = byteSwap(arr[i5]); + } + return arr; +} +function asciiToBase16(ch) { + if (ch >= asciis._0 && ch <= asciis._9) + return ch - asciis._0; + if (ch >= asciis.A && ch <= asciis.F) + return ch - (asciis.A - 10); + if (ch >= asciis.a && ch <= asciis.f) + return ch - (asciis.a - 10); + return; +} +function hexToBytes2(hex4) { + if (typeof hex4 !== "string") + throw new TypeError("hex string expected, got " + typeof hex4); + if (hasHexBuiltin) { + try { + return Uint8Array.fromHex(hex4); + } catch (error50) { + if (error50 instanceof SyntaxError) + throw new RangeError(error50.message); + throw error50; + } + } + const hl = hex4.length; + const al = hl / 2; + if (hl % 2) + throw new RangeError("hex string expected, got unpadded hex of length " + hl); + const array2 = new Uint8Array(al); + for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) { + const n1 = asciiToBase16(hex4.charCodeAt(hi)); + const n22 = asciiToBase16(hex4.charCodeAt(hi + 1)); + if (n1 === void 0 || n22 === void 0) { + const char2 = hex4[hi] + hex4[hi + 1]; + throw new RangeError('hex string expected, got non-hex character "' + char2 + '" at index ' + hi); + } + array2[ai] = n1 * 16 + n22; + } + return array2; +} +async function asyncLoop(iters, tick, cb) { + let ts = Date.now(); + for (let i5 = 0; i5 < iters; i5++) { + cb(i5); + const diff = Date.now() - ts; + if (diff >= 0 && diff < tick) + continue; + await nextTick(); + ts += diff; + } +} +function utf8ToBytes(str) { + if (typeof str !== "string") + throw new TypeError("string expected"); + return new Uint8Array(new TextEncoder().encode(str)); +} +function kdfInputToBytes(data2, errorTitle = "") { + if (typeof data2 === "string") + return utf8ToBytes(data2); + return abytes(data2, void 0, errorTitle); +} +function checkOpts(defaults, opts) { + if (opts !== void 0 && {}.toString.call(opts) !== "[object Object]") + throw new TypeError("options must be object or undefined"); + const merged = Object.assign(defaults, opts); + return merged; +} +function createHasher(hashCons, info2 = {}) { + const hashC = (msg, opts) => hashCons(opts).update(msg).digest(); + const tmp = hashCons(void 0); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.canXOF = tmp.canXOF; + hashC.create = (opts) => hashCons(opts); + Object.assign(hashC, info2); + return Object.freeze(hashC); +} +var isLE, swap32IfBE, hasHexBuiltin, asciis, nextTick, oidNist; +var init_utils6 = __esm({ + "node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/utils.js"() { + isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)(); + swap32IfBE = isLE ? (u5) => u5 : byteSwap32; + hasHexBuiltin = /* @__PURE__ */ (() => ( + // @ts-ignore + typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function" + ))(); + asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 }; + nextTick = async () => { + }; + oidNist = (suffix) => ({ + // Current NIST hashAlgs suffixes used here fit in one DER subidentifier octet. + // Larger suffix values would need base-128 OID encoding and a different length byte. + oid: Uint8Array.from([6, 9, 96, 134, 72, 1, 101, 3, 4, 2, suffix]) + }); + } +}); + +// node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/hmac.js +var _HMAC, hmac2; +var init_hmac = __esm({ + "node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/hmac.js"() { + init_utils6(); + _HMAC = class { + oHash; + iHash; + blockLen; + outputLen; + canXOF = false; + finished = false; + destroyed = false; + constructor(hash2, key) { + ahash(hash2); + abytes(key, void 0, "key"); + this.iHash = hash2.create(); + if (typeof this.iHash.update !== "function") + throw new Error("Expected instance of class which extends utils.Hash"); + this.blockLen = this.iHash.blockLen; + this.outputLen = this.iHash.outputLen; + const blockLen = this.blockLen; + const pad = new Uint8Array(blockLen); + pad.set(key.length > blockLen ? hash2.create().update(key).digest() : key); + for (let i5 = 0; i5 < pad.length; i5++) + pad[i5] ^= 54; + this.iHash.update(pad); + this.oHash = hash2.create(); + for (let i5 = 0; i5 < pad.length; i5++) + pad[i5] ^= 54 ^ 92; + this.oHash.update(pad); + clean(pad); + } + update(buf) { + aexists(this); + this.iHash.update(buf); + return this; + } + digestInto(out) { + aexists(this); + aoutput(out, this); + this.finished = true; + const buf = out.subarray(0, this.outputLen); + this.iHash.digestInto(buf); + this.oHash.update(buf); + this.oHash.digestInto(buf); + this.destroy(); + } + digest() { + const out = new Uint8Array(this.oHash.outputLen); + this.digestInto(out); + return out; + } + _cloneInto(to) { + to ||= Object.create(Object.getPrototypeOf(this), {}); + const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this; + to = to; + to.finished = finished; + to.destroyed = destroyed; + to.blockLen = blockLen; + to.outputLen = outputLen; + to.oHash = oHash._cloneInto(to.oHash); + to.iHash = iHash._cloneInto(to.iHash); + return to; + } + clone() { + return this._cloneInto(); + } + destroy() { + this.destroyed = true; + this.oHash.destroy(); + this.iHash.destroy(); + } + }; + hmac2 = /* @__PURE__ */ (() => { + const hmac_ = ((hash2, key, message2) => new _HMAC(hash2, key).update(message2).digest()); + hmac_.create = (hash2, key) => new _HMAC(hash2, key); + return hmac_; + })(); + } +}); + +// node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/hkdf.js +function extract(hash2, ikm, salt) { + ahash(hash2); + if (salt === void 0) + salt = new Uint8Array(hash2.outputLen); + return hmac2(hash2, salt, ikm); +} +function expand(hash2, prk, info2, length = 32) { + ahash(hash2); + anumber(length, "length"); + abytes(prk, void 0, "prk"); + const olen = hash2.outputLen; + if (prk.length < olen) + throw new Error('"prk" must be at least HashLen octets'); + if (length > 255 * olen) + throw new Error("Length must be <= 255*HashLen"); + const blocks = Math.ceil(length / olen); + if (info2 === void 0) + info2 = EMPTY_BUFFER; + else + abytes(info2, void 0, "info"); + const okm = new Uint8Array(blocks * olen); + const HMAC = hmac2.create(hash2, prk); + const HMACTmp = HMAC._cloneInto(); + const T = new Uint8Array(HMAC.outputLen); + for (let counter = 0; counter < blocks; counter++) { + HKDF_COUNTER[0] = counter + 1; + HMACTmp.update(counter === 0 ? EMPTY_BUFFER : T).update(info2).update(HKDF_COUNTER).digestInto(T); + okm.set(T, olen * counter); + HMAC._cloneInto(HMACTmp); + } + HMAC.destroy(); + HMACTmp.destroy(); + clean(T, HKDF_COUNTER); + return okm.slice(0, length); +} +var HKDF_COUNTER, EMPTY_BUFFER, hkdf; +var init_hkdf = __esm({ + "node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/hkdf.js"() { + init_hmac(); + init_utils6(); + HKDF_COUNTER = /* @__PURE__ */ Uint8Array.of(0); + EMPTY_BUFFER = /* @__PURE__ */ Uint8Array.of(); + hkdf = (hash2, ikm, salt, info2, length) => expand(hash2, extract(hash2, ikm, salt), info2, length); + } +}); + +// node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/_md.js +function Chi(a5, b6, c5) { + return a5 & b6 ^ ~a5 & c5; +} +function Maj(a5, b6, c5) { + return a5 & b6 ^ a5 & c5 ^ b6 & c5; +} +var HashMD, SHA256_IV; +var init_md = __esm({ + "node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/_md.js"() { + init_utils6(); + HashMD = class { + blockLen; + outputLen; + canXOF = false; + padOffset; + isLE; + // For partial updates less than block size + buffer; + view; + finished = false; + length = 0; + pos = 0; + destroyed = false; + constructor(blockLen, outputLen, padOffset, isLE3) { + this.blockLen = blockLen; + this.outputLen = outputLen; + this.padOffset = padOffset; + this.isLE = isLE3; + this.buffer = new Uint8Array(blockLen); + this.view = createView(this.buffer); + } + update(data2) { + aexists(this); + abytes(data2); + const { view, buffer: buffer2, blockLen } = this; + const len = data2.length; + for (let pos = 0; pos < len; ) { + const take = Math.min(blockLen - this.pos, len - pos); + if (take === blockLen) { + const dataView3 = createView(data2); + for (; blockLen <= len - pos; pos += blockLen) + this.process(dataView3, pos); + continue; + } + buffer2.set(data2.subarray(pos, pos + take), this.pos); + this.pos += take; + pos += take; + if (this.pos === blockLen) { + this.process(view, 0); + this.pos = 0; + } + } + this.length += data2.length; + this.roundClean(); + return this; + } + digestInto(out) { + aexists(this); + aoutput(out, this); + this.finished = true; + const { buffer: buffer2, view, blockLen, isLE: isLE3 } = this; + let { pos } = this; + buffer2[pos++] = 128; + clean(this.buffer.subarray(pos)); + if (this.padOffset > blockLen - pos) { + this.process(view, 0); + pos = 0; + } + for (let i5 = pos; i5 < blockLen; i5++) + buffer2[i5] = 0; + view.setBigUint64(blockLen - 8, BigInt(this.length * 8), isLE3); + this.process(view, 0); + const oview = createView(out); + const len = this.outputLen; + if (len % 4) + throw new Error("_sha2: outputLen must be aligned to 32bit"); + const outLen = len / 4; + const state2 = this.get(); + if (outLen > state2.length) + throw new Error("_sha2: outputLen bigger than state"); + for (let i5 = 0; i5 < outLen; i5++) + oview.setUint32(4 * i5, state2[i5], isLE3); + } + digest() { + const { buffer: buffer2, outputLen } = this; + this.digestInto(buffer2); + const res = buffer2.slice(0, outputLen); + this.destroy(); + return res; + } + _cloneInto(to) { + to ||= new this.constructor(); + to.set(...this.get()); + const { blockLen, buffer: buffer2, length, finished, destroyed, pos } = this; + to.destroyed = destroyed; + to.finished = finished; + to.length = length; + to.pos = pos; + if (length % blockLen) + to.buffer.set(buffer2); + return to; + } + clone() { + return this._cloneInto(); + } + }; + SHA256_IV = /* @__PURE__ */ Uint32Array.from([ + 1779033703, + 3144134277, + 1013904242, + 2773480762, + 1359893119, + 2600822924, + 528734635, + 1541459225 + ]); + } +}); + +// node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/sha2.js +var SHA256_K, SHA256_W, SHA2_32B, _SHA256, sha2562; +var init_sha2 = __esm({ + "node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/sha2.js"() { + init_md(); + init_utils6(); + SHA256_K = /* @__PURE__ */ Uint32Array.from([ + 1116352408, + 1899447441, + 3049323471, + 3921009573, + 961987163, + 1508970993, + 2453635748, + 2870763221, + 3624381080, + 310598401, + 607225278, + 1426881987, + 1925078388, + 2162078206, + 2614888103, + 3248222580, + 3835390401, + 4022224774, + 264347078, + 604807628, + 770255983, + 1249150122, + 1555081692, + 1996064986, + 2554220882, + 2821834349, + 2952996808, + 3210313671, + 3336571891, + 3584528711, + 113926993, + 338241895, + 666307205, + 773529912, + 1294757372, + 1396182291, + 1695183700, + 1986661051, + 2177026350, + 2456956037, + 2730485921, + 2820302411, + 3259730800, + 3345764771, + 3516065817, + 3600352804, + 4094571909, + 275423344, + 430227734, + 506948616, + 659060556, + 883997877, + 958139571, + 1322822218, + 1537002063, + 1747873779, + 1955562222, + 2024104815, + 2227730452, + 2361852424, + 2428436474, + 2756734187, + 3204031479, + 3329325298 + ]); + SHA256_W = /* @__PURE__ */ new Uint32Array(64); + SHA2_32B = class extends HashMD { + constructor(outputLen) { + super(64, outputLen, 8, false); + } + get() { + const { A: A2, B: B2, C: C2, D: D2, E: E2, F: F2, G: G2, H: H2 } = this; + return [A2, B2, C2, D2, E2, F2, G2, H2]; + } + // prettier-ignore + set(A2, B2, C2, D2, E2, F2, G2, H2) { + this.A = A2 | 0; + this.B = B2 | 0; + this.C = C2 | 0; + this.D = D2 | 0; + this.E = E2 | 0; + this.F = F2 | 0; + this.G = G2 | 0; + this.H = H2 | 0; + } + process(view, offset) { + for (let i5 = 0; i5 < 16; i5++, offset += 4) + SHA256_W[i5] = view.getUint32(offset, false); + for (let i5 = 16; i5 < 64; i5++) { + const W15 = SHA256_W[i5 - 15]; + const W2 = SHA256_W[i5 - 2]; + const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3; + const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10; + SHA256_W[i5] = s1 + SHA256_W[i5 - 7] + s0 + SHA256_W[i5 - 16] | 0; + } + let { A: A2, B: B2, C: C2, D: D2, E: E2, F: F2, G: G2, H: H2 } = this; + for (let i5 = 0; i5 < 64; i5++) { + const sigma1 = rotr(E2, 6) ^ rotr(E2, 11) ^ rotr(E2, 25); + const T1 = H2 + sigma1 + Chi(E2, F2, G2) + SHA256_K[i5] + SHA256_W[i5] | 0; + const sigma0 = rotr(A2, 2) ^ rotr(A2, 13) ^ rotr(A2, 22); + const T2 = sigma0 + Maj(A2, B2, C2) | 0; + H2 = G2; + G2 = F2; + F2 = E2; + E2 = D2 + T1 | 0; + D2 = C2; + C2 = B2; + B2 = A2; + A2 = T1 + T2 | 0; + } + A2 = A2 + this.A | 0; + B2 = B2 + this.B | 0; + C2 = C2 + this.C | 0; + D2 = D2 + this.D | 0; + E2 = E2 + this.E | 0; + F2 = F2 + this.F | 0; + G2 = G2 + this.G | 0; + H2 = H2 + this.H | 0; + this.set(A2, B2, C2, D2, E2, F2, G2, H2); + } + roundClean() { + clean(SHA256_W); + } + destroy() { + this.destroyed = true; + this.set(0, 0, 0, 0, 0, 0, 0, 0); + clean(this.buffer); + } + }; + _SHA256 = class extends SHA2_32B { + // We cannot use array here since array allows indexing by variable + // which means optimizer/compiler cannot use registers. + A = SHA256_IV[0] | 0; + B = SHA256_IV[1] | 0; + C = SHA256_IV[2] | 0; + D = SHA256_IV[3] | 0; + E = SHA256_IV[4] | 0; + F = SHA256_IV[5] | 0; + G = SHA256_IV[6] | 0; + H = SHA256_IV[7] | 0; + constructor() { + super(32); + } + }; + sha2562 = /* @__PURE__ */ createHasher( + () => new _SHA256(), + /* @__PURE__ */ oidNist(1) + ); + } +}); + +// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/buffer_utils.js +function concat(...buffers) { + const size2 = buffers.reduce((acc, { length }) => acc + length, 0); + const buf = new Uint8Array(size2); + let i5 = 0; + for (const buffer2 of buffers) { + buf.set(buffer2, i5); + i5 += buffer2.length; + } + return buf; +} +function writeUInt32BE(buf, value, offset) { + if (value < 0 || value >= MAX_INT32) { + throw new RangeError(`value must be >= 0 and <= ${MAX_INT32 - 1}. Received ${value}`); + } + buf.set([value >>> 24, value >>> 16, value >>> 8, value & 255], offset); +} +function uint64be(value) { + const high = Math.floor(value / MAX_INT32); + const low = value % MAX_INT32; + const buf = new Uint8Array(8); + writeUInt32BE(buf, high, 0); + writeUInt32BE(buf, low, 4); + return buf; +} +function uint32be(value) { + const buf = new Uint8Array(4); + writeUInt32BE(buf, value); + return buf; +} +function encode2(string4) { + const bytes = new Uint8Array(string4.length); + for (let i5 = 0; i5 < string4.length; i5++) { + const code = string4.charCodeAt(i5); + if (code > 127) { + throw new TypeError("non-ASCII string encountered in encode()"); + } + bytes[i5] = code; + } + return bytes; +} +var encoder, decoder, MAX_INT32; +var init_buffer_utils = __esm({ + "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/buffer_utils.js"() { + encoder = new TextEncoder(); + decoder = new TextDecoder(); + MAX_INT32 = 2 ** 32; + } +}); + +// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/base64.js +function encodeBase64(input) { + if (Uint8Array.prototype.toBase64) { + return input.toBase64(); + } + const CHUNK_SIZE2 = 32768; + const arr = []; + for (let i5 = 0; i5 < input.length; i5 += CHUNK_SIZE2) { + arr.push(String.fromCharCode.apply(null, input.subarray(i5, i5 + CHUNK_SIZE2))); + } + return btoa(arr.join("")); +} +function decodeBase64(encoded) { + if (Uint8Array.fromBase64) { + return Uint8Array.fromBase64(encoded); + } + const binary2 = atob(encoded); + const bytes = new Uint8Array(binary2.length); + for (let i5 = 0; i5 < binary2.length; i5++) { + bytes[i5] = binary2.charCodeAt(i5); + } + return bytes; +} +var init_base64 = __esm({ + "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/base64.js"() { + } +}); + +// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/util/base64url.js +var base64url_exports = {}; +__export(base64url_exports, { + decode: () => decode2, + encode: () => encode3 +}); +function decode2(input) { + if (Uint8Array.fromBase64) { + return Uint8Array.fromBase64(typeof input === "string" ? input : decoder.decode(input), { + alphabet: "base64url" + }); + } + let encoded = input; + if (encoded instanceof Uint8Array) { + encoded = decoder.decode(encoded); + } + encoded = encoded.replace(/-/g, "+").replace(/_/g, "/"); + try { + return decodeBase64(encoded); + } catch { + throw new TypeError("The input to be decoded is not correctly encoded."); + } +} +function encode3(input) { + let unencoded = input; + if (typeof unencoded === "string") { + unencoded = encoder.encode(unencoded); + } + if (Uint8Array.prototype.toBase64) { + return unencoded.toBase64({ alphabet: "base64url", omitPadding: true }); + } + return encodeBase64(unencoded).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_"); +} +var init_base64url = __esm({ + "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/util/base64url.js"() { + init_buffer_utils(); + init_base64(); + } +}); + +// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/crypto_key.js +function getHashLength(hash2) { + return parseInt(hash2.name.slice(4), 10); +} +function checkHashLength(algorithm2, expected) { + const actual = getHashLength(algorithm2.hash); + if (actual !== expected) + throw unusable(`SHA-${expected}`, "algorithm.hash"); +} +function getNamedCurve(alg2) { + switch (alg2) { + case "ES256": + return "P-256"; + case "ES384": + return "P-384"; + case "ES512": + return "P-521"; + default: + throw new Error("unreachable"); + } +} +function checkUsage(key, usage) { + if (usage && !key.usages.includes(usage)) { + throw new TypeError(`CryptoKey does not support this operation, its usages must include ${usage}.`); + } +} +function checkSigCryptoKey(key, alg2, usage) { + switch (alg2) { + case "HS256": + case "HS384": + case "HS512": { + if (!isAlgorithm(key.algorithm, "HMAC")) + throw unusable("HMAC"); + checkHashLength(key.algorithm, parseInt(alg2.slice(2), 10)); + break; + } + case "RS256": + case "RS384": + case "RS512": { + if (!isAlgorithm(key.algorithm, "RSASSA-PKCS1-v1_5")) + throw unusable("RSASSA-PKCS1-v1_5"); + checkHashLength(key.algorithm, parseInt(alg2.slice(2), 10)); + break; + } + case "PS256": + case "PS384": + case "PS512": { + if (!isAlgorithm(key.algorithm, "RSA-PSS")) + throw unusable("RSA-PSS"); + checkHashLength(key.algorithm, parseInt(alg2.slice(2), 10)); + break; + } + case "Ed25519": + case "EdDSA": { + if (!isAlgorithm(key.algorithm, "Ed25519")) + throw unusable("Ed25519"); + break; + } + case "ML-DSA-44": + case "ML-DSA-65": + case "ML-DSA-87": { + if (!isAlgorithm(key.algorithm, alg2)) + throw unusable(alg2); + break; + } + case "ES256": + case "ES384": + case "ES512": { + if (!isAlgorithm(key.algorithm, "ECDSA")) + throw unusable("ECDSA"); + const expected = getNamedCurve(alg2); + const actual = key.algorithm.namedCurve; + if (actual !== expected) + throw unusable(expected, "algorithm.namedCurve"); + break; + } + default: + throw new TypeError("CryptoKey does not support this operation"); + } + checkUsage(key, usage); +} +function checkEncCryptoKey(key, alg2, usage) { + switch (alg2) { + case "A128GCM": + case "A192GCM": + case "A256GCM": { + if (!isAlgorithm(key.algorithm, "AES-GCM")) + throw unusable("AES-GCM"); + const expected = parseInt(alg2.slice(1, 4), 10); + const actual = key.algorithm.length; + if (actual !== expected) + throw unusable(expected, "algorithm.length"); + break; + } + case "A128KW": + case "A192KW": + case "A256KW": { + if (!isAlgorithm(key.algorithm, "AES-KW")) + throw unusable("AES-KW"); + const expected = parseInt(alg2.slice(1, 4), 10); + const actual = key.algorithm.length; + if (actual !== expected) + throw unusable(expected, "algorithm.length"); + break; + } + case "ECDH": { + switch (key.algorithm.name) { + case "ECDH": + case "X25519": + break; + default: + throw unusable("ECDH or X25519"); + } + break; + } + case "PBES2-HS256+A128KW": + case "PBES2-HS384+A192KW": + case "PBES2-HS512+A256KW": + if (!isAlgorithm(key.algorithm, "PBKDF2")) + throw unusable("PBKDF2"); + break; + case "RSA-OAEP": + case "RSA-OAEP-256": + case "RSA-OAEP-384": + case "RSA-OAEP-512": { + if (!isAlgorithm(key.algorithm, "RSA-OAEP")) + throw unusable("RSA-OAEP"); + checkHashLength(key.algorithm, parseInt(alg2.slice(9), 10) || 1); + break; + } + default: + throw new TypeError("CryptoKey does not support this operation"); + } + checkUsage(key, usage); +} +var unusable, isAlgorithm; +var init_crypto_key = __esm({ + "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/crypto_key.js"() { + unusable = (name, prop = "algorithm.name") => new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`); + isAlgorithm = (algorithm2, name) => algorithm2.name === name; + } +}); + +// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/invalid_key_input.js +function message(msg, actual, ...types2) { + types2 = types2.filter(Boolean); + if (types2.length > 2) { + const last = types2.pop(); + msg += `one of type ${types2.join(", ")}, or ${last}.`; + } else if (types2.length === 2) { + msg += `one of type ${types2[0]} or ${types2[1]}.`; + } else { + msg += `of type ${types2[0]}.`; + } + if (actual == null) { + msg += ` Received ${actual}`; + } else if (typeof actual === "function" && actual.name) { + msg += ` Received function ${actual.name}`; + } else if (typeof actual === "object" && actual != null) { + if (actual.constructor?.name) { + msg += ` Received an instance of ${actual.constructor.name}`; + } + } + return msg; +} +var invalidKeyInput, withAlg; +var init_invalid_key_input = __esm({ + "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/invalid_key_input.js"() { + invalidKeyInput = (actual, ...types2) => message("Key must be ", actual, ...types2); + withAlg = (alg2, actual, ...types2) => message(`Key for the ${alg2} algorithm must be `, actual, ...types2); + } +}); + +// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/util/errors.js +var JOSEError, JWTClaimValidationFailed, JWTExpired, JOSEAlgNotAllowed, JOSENotSupported, JWEDecryptionFailed, JWEInvalid, JWSInvalid, JWTInvalid, JWKInvalid, JWKSInvalid, JWKSNoMatchingKey, JWKSMultipleMatchingKeys, JWKSTimeout, JWSSignatureVerificationFailed; +var init_errors7 = __esm({ + "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/util/errors.js"() { + JOSEError = class extends Error { + static code = "ERR_JOSE_GENERIC"; + code = "ERR_JOSE_GENERIC"; + constructor(message2, options) { + super(message2, options); + this.name = this.constructor.name; + Error.captureStackTrace?.(this, this.constructor); + } + }; + JWTClaimValidationFailed = class extends JOSEError { + static code = "ERR_JWT_CLAIM_VALIDATION_FAILED"; + code = "ERR_JWT_CLAIM_VALIDATION_FAILED"; + claim; + reason; + payload; + constructor(message2, payload2, claim = "unspecified", reason = "unspecified") { + super(message2, { cause: { claim, reason, payload: payload2 } }); + this.claim = claim; + this.reason = reason; + this.payload = payload2; + } + }; + JWTExpired = class extends JOSEError { + static code = "ERR_JWT_EXPIRED"; + code = "ERR_JWT_EXPIRED"; + claim; + reason; + payload; + constructor(message2, payload2, claim = "unspecified", reason = "unspecified") { + super(message2, { cause: { claim, reason, payload: payload2 } }); + this.claim = claim; + this.reason = reason; + this.payload = payload2; + } + }; + JOSEAlgNotAllowed = class extends JOSEError { + static code = "ERR_JOSE_ALG_NOT_ALLOWED"; + code = "ERR_JOSE_ALG_NOT_ALLOWED"; + }; + JOSENotSupported = class extends JOSEError { + static code = "ERR_JOSE_NOT_SUPPORTED"; + code = "ERR_JOSE_NOT_SUPPORTED"; + }; + JWEDecryptionFailed = class extends JOSEError { + static code = "ERR_JWE_DECRYPTION_FAILED"; + code = "ERR_JWE_DECRYPTION_FAILED"; + constructor(message2 = "decryption operation failed", options) { + super(message2, options); + } + }; + JWEInvalid = class extends JOSEError { + static code = "ERR_JWE_INVALID"; + code = "ERR_JWE_INVALID"; + }; + JWSInvalid = class extends JOSEError { + static code = "ERR_JWS_INVALID"; + code = "ERR_JWS_INVALID"; + }; + JWTInvalid = class extends JOSEError { + static code = "ERR_JWT_INVALID"; + code = "ERR_JWT_INVALID"; + }; + JWKInvalid = class extends JOSEError { + static code = "ERR_JWK_INVALID"; + code = "ERR_JWK_INVALID"; + }; + JWKSInvalid = class extends JOSEError { + static code = "ERR_JWKS_INVALID"; + code = "ERR_JWKS_INVALID"; + }; + JWKSNoMatchingKey = class extends JOSEError { + static code = "ERR_JWKS_NO_MATCHING_KEY"; + code = "ERR_JWKS_NO_MATCHING_KEY"; + constructor(message2 = "no applicable key found in the JSON Web Key Set", options) { + super(message2, options); + } + }; + JWKSMultipleMatchingKeys = class extends JOSEError { + [Symbol.asyncIterator]; + static code = "ERR_JWKS_MULTIPLE_MATCHING_KEYS"; + code = "ERR_JWKS_MULTIPLE_MATCHING_KEYS"; + constructor(message2 = "multiple matching keys found in the JSON Web Key Set", options) { + super(message2, options); + } + }; + JWKSTimeout = class extends JOSEError { + static code = "ERR_JWKS_TIMEOUT"; + code = "ERR_JWKS_TIMEOUT"; + constructor(message2 = "request timed out", options) { + super(message2, options); + } + }; + JWSSignatureVerificationFailed = class extends JOSEError { + static code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED"; + code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED"; + constructor(message2 = "signature verification failed", options) { + super(message2, options); + } + }; + } +}); + +// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/is_key_like.js +function assertCryptoKey(key) { + if (!isCryptoKey(key)) { + throw new Error("CryptoKey instance expected"); + } +} +var isCryptoKey, isKeyObject, isKeyLike; +var init_is_key_like = __esm({ + "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/is_key_like.js"() { + isCryptoKey = (key) => { + if (key?.[Symbol.toStringTag] === "CryptoKey") + return true; + try { + return key instanceof CryptoKey; + } catch { + return false; + } + }; + isKeyObject = (key) => key?.[Symbol.toStringTag] === "KeyObject"; + isKeyLike = (key) => isCryptoKey(key) || isKeyObject(key); + } +}); + +// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/content_encryption.js +function cekLength(alg2) { + switch (alg2) { + case "A128GCM": + return 128; + case "A192GCM": + return 192; + case "A256GCM": + case "A128CBC-HS256": + return 256; + case "A192CBC-HS384": + return 384; + case "A256CBC-HS512": + return 512; + default: + throw new JOSENotSupported(`Unsupported JWE Algorithm: ${alg2}`); + } +} +function checkCekLength(cek, expected) { + const actual = cek.byteLength << 3; + if (actual !== expected) { + throw new JWEInvalid(`Invalid Content Encryption Key length. Expected ${expected} bits, got ${actual} bits`); + } +} +function ivBitLength(alg2) { + switch (alg2) { + case "A128GCM": + case "A128GCMKW": + case "A192GCM": + case "A192GCMKW": + case "A256GCM": + case "A256GCMKW": + return 96; + case "A128CBC-HS256": + case "A192CBC-HS384": + case "A256CBC-HS512": + return 128; + default: + throw new JOSENotSupported(`Unsupported JWE Algorithm: ${alg2}`); + } +} +function checkIvLength(enc2, iv) { + if (iv.length << 3 !== ivBitLength(enc2)) { + throw new JWEInvalid("Invalid Initialization Vector length"); + } +} +async function cbcKeySetup(enc2, cek, usage) { + if (!(cek instanceof Uint8Array)) { + throw new TypeError(invalidKeyInput(cek, "Uint8Array")); + } + const keySize = parseInt(enc2.slice(1, 4), 10); + const encKey = await crypto.subtle.importKey("raw", cek.subarray(keySize >> 3), "AES-CBC", false, [usage]); + const macKey = await crypto.subtle.importKey("raw", cek.subarray(0, keySize >> 3), { + hash: `SHA-${keySize << 1}`, + name: "HMAC" + }, false, ["sign"]); + return { encKey, macKey, keySize }; +} +async function cbcHmacTag(macKey, macData, keySize) { + return new Uint8Array((await crypto.subtle.sign("HMAC", macKey, macData)).slice(0, keySize >> 3)); +} +async function cbcEncrypt(enc2, plaintext, cek, iv, aad) { + const { encKey, macKey, keySize } = await cbcKeySetup(enc2, cek, "encrypt"); + const ciphertext = new Uint8Array(await crypto.subtle.encrypt({ + iv, + name: "AES-CBC" + }, encKey, plaintext)); + const macData = concat(aad, iv, ciphertext, uint64be(aad.length << 3)); + const tag3 = await cbcHmacTag(macKey, macData, keySize); + return { ciphertext, tag: tag3, iv }; +} +async function timingSafeEqual4(a5, b6) { + if (!(a5 instanceof Uint8Array)) { + throw new TypeError("First argument must be a buffer"); + } + if (!(b6 instanceof Uint8Array)) { + throw new TypeError("Second argument must be a buffer"); + } + const algorithm2 = { name: "HMAC", hash: "SHA-256" }; + const key = await crypto.subtle.generateKey(algorithm2, false, ["sign"]); + const aHmac = new Uint8Array(await crypto.subtle.sign(algorithm2, key, a5)); + const bHmac = new Uint8Array(await crypto.subtle.sign(algorithm2, key, b6)); + let out = 0; + let i5 = -1; + while (++i5 < 32) { + out |= aHmac[i5] ^ bHmac[i5]; + } + return out === 0; +} +async function cbcDecrypt(enc2, cek, ciphertext, iv, tag3, aad) { + const { encKey, macKey, keySize } = await cbcKeySetup(enc2, cek, "decrypt"); + const macData = concat(aad, iv, ciphertext, uint64be(aad.length << 3)); + const expectedTag = await cbcHmacTag(macKey, macData, keySize); + let macCheckPassed; + try { + macCheckPassed = await timingSafeEqual4(tag3, expectedTag); + } catch { + } + if (!macCheckPassed) { + throw new JWEDecryptionFailed(); + } + let plaintext; + try { + plaintext = new Uint8Array(await crypto.subtle.decrypt({ iv, name: "AES-CBC" }, encKey, ciphertext)); + } catch { + } + if (!plaintext) { + throw new JWEDecryptionFailed(); + } + return plaintext; +} +async function gcmEncrypt(enc2, plaintext, cek, iv, aad) { + let encKey; + if (cek instanceof Uint8Array) { + encKey = await crypto.subtle.importKey("raw", cek, "AES-GCM", false, ["encrypt"]); + } else { + checkEncCryptoKey(cek, enc2, "encrypt"); + encKey = cek; + } + const encrypted = new Uint8Array(await crypto.subtle.encrypt({ + additionalData: aad, + iv, + name: "AES-GCM", + tagLength: 128 + }, encKey, plaintext)); + const tag3 = encrypted.slice(-16); + const ciphertext = encrypted.slice(0, -16); + return { ciphertext, tag: tag3, iv }; +} +async function gcmDecrypt(enc2, cek, ciphertext, iv, tag3, aad) { + let encKey; + if (cek instanceof Uint8Array) { + encKey = await crypto.subtle.importKey("raw", cek, "AES-GCM", false, ["decrypt"]); + } else { + checkEncCryptoKey(cek, enc2, "decrypt"); + encKey = cek; + } + try { + return new Uint8Array(await crypto.subtle.decrypt({ + additionalData: aad, + iv, + name: "AES-GCM", + tagLength: 128 + }, encKey, concat(ciphertext, tag3))); + } catch { + throw new JWEDecryptionFailed(); + } +} +async function encrypt(enc2, plaintext, cek, iv, aad) { + if (!isCryptoKey(cek) && !(cek instanceof Uint8Array)) { + throw new TypeError(invalidKeyInput(cek, "CryptoKey", "KeyObject", "Uint8Array", "JSON Web Key")); + } + if (iv) { + checkIvLength(enc2, iv); + } else { + iv = generateIv(enc2); + } + switch (enc2) { + case "A128CBC-HS256": + case "A192CBC-HS384": + case "A256CBC-HS512": + if (cek instanceof Uint8Array) { + checkCekLength(cek, parseInt(enc2.slice(-3), 10)); + } + return cbcEncrypt(enc2, plaintext, cek, iv, aad); + case "A128GCM": + case "A192GCM": + case "A256GCM": + if (cek instanceof Uint8Array) { + checkCekLength(cek, parseInt(enc2.slice(1, 4), 10)); + } + return gcmEncrypt(enc2, plaintext, cek, iv, aad); + default: + throw new JOSENotSupported(unsupportedEnc); + } +} +async function decrypt(enc2, cek, ciphertext, iv, tag3, aad) { + if (!isCryptoKey(cek) && !(cek instanceof Uint8Array)) { + throw new TypeError(invalidKeyInput(cek, "CryptoKey", "KeyObject", "Uint8Array", "JSON Web Key")); + } + if (!iv) { + throw new JWEInvalid("JWE Initialization Vector missing"); + } + if (!tag3) { + throw new JWEInvalid("JWE Authentication Tag missing"); + } + checkIvLength(enc2, iv); + switch (enc2) { + case "A128CBC-HS256": + case "A192CBC-HS384": + case "A256CBC-HS512": + if (cek instanceof Uint8Array) + checkCekLength(cek, parseInt(enc2.slice(-3), 10)); + return cbcDecrypt(enc2, cek, ciphertext, iv, tag3, aad); + case "A128GCM": + case "A192GCM": + case "A256GCM": + if (cek instanceof Uint8Array) + checkCekLength(cek, parseInt(enc2.slice(1, 4), 10)); + return gcmDecrypt(enc2, cek, ciphertext, iv, tag3, aad); + default: + throw new JOSENotSupported(unsupportedEnc); + } +} +var generateCek, generateIv, unsupportedEnc; +var init_content_encryption = __esm({ + "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/content_encryption.js"() { + init_buffer_utils(); + init_crypto_key(); + init_invalid_key_input(); + init_errors7(); + init_is_key_like(); + generateCek = (alg2) => crypto.getRandomValues(new Uint8Array(cekLength(alg2) >> 3)); + generateIv = (alg2) => crypto.getRandomValues(new Uint8Array(ivBitLength(alg2) >> 3)); + unsupportedEnc = "Unsupported JWE Content Encryption Algorithm"; + } +}); + +// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/helpers.js +function assertNotSet(value, name) { + if (value) { + throw new TypeError(`${name} can only be called once`); + } +} +function decodeBase64url(value, label, ErrorClass) { + try { + return decode2(value); + } catch { + throw new ErrorClass(`Failed to base64url decode the ${label}`); + } +} +async function digest(algorithm2, data2) { + const subtleDigest = `SHA-${algorithm2.slice(-3)}`; + return new Uint8Array(await crypto.subtle.digest(subtleDigest, data2)); +} +var unprotected; +var init_helpers = __esm({ + "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/helpers.js"() { + init_base64url(); + unprotected = /* @__PURE__ */ Symbol(); + } +}); + +// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/type_checks.js +function isObject(input) { + if (!isObjectLike(input) || Object.prototype.toString.call(input) !== "[object Object]") { + return false; + } + if (Object.getPrototypeOf(input) === null) { + return true; + } + let proto = input; + while (Object.getPrototypeOf(proto) !== null) { + proto = Object.getPrototypeOf(proto); + } + return Object.getPrototypeOf(input) === proto; +} +function isDisjoint(...headers) { + const sources = headers.filter(Boolean); + if (sources.length === 0 || sources.length === 1) { + return true; + } + let acc; + for (const header of sources) { + const parameters = Object.keys(header); + if (!acc || acc.size === 0) { + acc = new Set(parameters); + continue; + } + for (const parameter of parameters) { + if (acc.has(parameter)) { + return false; + } + acc.add(parameter); + } + } + return true; +} +var isObjectLike, isJWK, isPrivateJWK, isPublicJWK, isSecretJWK; +var init_type_checks = __esm({ + "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/type_checks.js"() { + isObjectLike = (value) => typeof value === "object" && value !== null; + isJWK = (key) => isObject(key) && typeof key.kty === "string"; + isPrivateJWK = (key) => key.kty !== "oct" && (key.kty === "AKP" && typeof key.priv === "string" || typeof key.d === "string"); + isPublicJWK = (key) => key.kty !== "oct" && key.d === void 0 && key.priv === void 0; + isSecretJWK = (key) => key.kty === "oct" && typeof key.k === "string"; + } +}); + +// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/aeskw.js +function checkKeySize(key, alg2) { + if (key.algorithm.length !== parseInt(alg2.slice(1, 4), 10)) { + throw new TypeError(`Invalid key size for alg: ${alg2}`); + } +} +function getCryptoKey(key, alg2, usage) { + if (key instanceof Uint8Array) { + return crypto.subtle.importKey("raw", key, "AES-KW", true, [usage]); + } + checkEncCryptoKey(key, alg2, usage); + return key; +} +async function wrap(alg2, key, cek) { + const cryptoKey = await getCryptoKey(key, alg2, "wrapKey"); + checkKeySize(cryptoKey, alg2); + const cryptoKeyCek = await crypto.subtle.importKey("raw", cek, { hash: "SHA-256", name: "HMAC" }, true, ["sign"]); + return new Uint8Array(await crypto.subtle.wrapKey("raw", cryptoKeyCek, cryptoKey, "AES-KW")); +} +async function unwrap(alg2, key, encryptedKey) { + const cryptoKey = await getCryptoKey(key, alg2, "unwrapKey"); + checkKeySize(cryptoKey, alg2); + const cryptoKeyCek = await crypto.subtle.unwrapKey("raw", encryptedKey, cryptoKey, "AES-KW", { hash: "SHA-256", name: "HMAC" }, true, ["sign"]); + return new Uint8Array(await crypto.subtle.exportKey("raw", cryptoKeyCek)); +} +var init_aeskw = __esm({ + "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/aeskw.js"() { + init_crypto_key(); + } +}); + +// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/ecdhes.js +function lengthAndInput(input) { + return concat(uint32be(input.length), input); +} +async function concatKdf(Z, L, OtherInfo) { + const dkLen = L >> 3; + const hashLen = 32; + const reps = Math.ceil(dkLen / hashLen); + const dk = new Uint8Array(reps * hashLen); + for (let i5 = 1; i5 <= reps; i5++) { + const hashInput = new Uint8Array(4 + Z.length + OtherInfo.length); + hashInput.set(uint32be(i5), 0); + hashInput.set(Z, 4); + hashInput.set(OtherInfo, 4 + Z.length); + const hashResult = await digest("sha256", hashInput); + dk.set(hashResult, (i5 - 1) * hashLen); + } + return dk.slice(0, dkLen); +} +async function deriveKey(publicKey, privateKey, algorithm2, keyLength, apu = new Uint8Array(), apv = new Uint8Array()) { + checkEncCryptoKey(publicKey, "ECDH"); + checkEncCryptoKey(privateKey, "ECDH", "deriveBits"); + const algorithmID = lengthAndInput(encode2(algorithm2)); + const partyUInfo = lengthAndInput(apu); + const partyVInfo = lengthAndInput(apv); + const suppPubInfo = uint32be(keyLength); + const suppPrivInfo = new Uint8Array(); + const otherInfo = concat(algorithmID, partyUInfo, partyVInfo, suppPubInfo, suppPrivInfo); + const Z = new Uint8Array(await crypto.subtle.deriveBits({ + name: publicKey.algorithm.name, + public: publicKey + }, privateKey, getEcdhBitLength(publicKey))); + return concatKdf(Z, keyLength, otherInfo); +} +function getEcdhBitLength(publicKey) { + if (publicKey.algorithm.name === "X25519") { + return 256; + } + return Math.ceil(parseInt(publicKey.algorithm.namedCurve.slice(-3), 10) / 8) << 3; +} +function allowed(key) { + switch (key.algorithm.namedCurve) { + case "P-256": + case "P-384": + case "P-521": + return true; + default: + return key.algorithm.name === "X25519"; + } +} +var init_ecdhes = __esm({ + "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/ecdhes.js"() { + init_buffer_utils(); + init_crypto_key(); + init_helpers(); + } +}); + +// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/pbes2kw.js +function getCryptoKey2(key, alg2) { + if (key instanceof Uint8Array) { + return crypto.subtle.importKey("raw", key, "PBKDF2", false, [ + "deriveBits" + ]); + } + checkEncCryptoKey(key, alg2, "deriveBits"); + return key; +} +async function deriveKey2(p2s, alg2, p2c, key) { + if (!(p2s instanceof Uint8Array) || p2s.length < 8) { + throw new JWEInvalid("PBES2 Salt Input must be 8 or more octets"); + } + const salt = concatSalt(alg2, p2s); + const keylen = parseInt(alg2.slice(13, 16), 10); + const subtleAlg = { + hash: `SHA-${alg2.slice(8, 11)}`, + iterations: p2c, + name: "PBKDF2", + salt + }; + const cryptoKey = await getCryptoKey2(key, alg2); + return new Uint8Array(await crypto.subtle.deriveBits(subtleAlg, cryptoKey, keylen)); +} +async function wrap2(alg2, key, cek, p2c = 2048, p2s = crypto.getRandomValues(new Uint8Array(16))) { + const derived = await deriveKey2(p2s, alg2, p2c, key); + const encryptedKey = await wrap(alg2.slice(-6), derived, cek); + return { encryptedKey, p2c, p2s: encode3(p2s) }; +} +async function unwrap2(alg2, key, encryptedKey, p2c, p2s) { + const derived = await deriveKey2(p2s, alg2, p2c, key); + return unwrap(alg2.slice(-6), derived, encryptedKey); +} +var concatSalt; +var init_pbes2kw = __esm({ + "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/pbes2kw.js"() { + init_base64url(); + init_aeskw(); + init_crypto_key(); + init_buffer_utils(); + init_errors7(); + concatSalt = (alg2, p2sInput) => concat(encode2(alg2), Uint8Array.of(0), p2sInput); + } +}); + +// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/signing.js +function checkKeyLength(alg2, key) { + if (alg2.startsWith("RS") || alg2.startsWith("PS")) { + const { modulusLength } = key.algorithm; + if (typeof modulusLength !== "number" || modulusLength < 2048) { + throw new TypeError(`${alg2} requires key modulusLength to be 2048 bits or larger`); + } + } +} +function subtleAlgorithm(alg2, algorithm2) { + const hash2 = `SHA-${alg2.slice(-3)}`; + switch (alg2) { + case "HS256": + case "HS384": + case "HS512": + return { hash: hash2, name: "HMAC" }; + case "PS256": + case "PS384": + case "PS512": + return { hash: hash2, name: "RSA-PSS", saltLength: parseInt(alg2.slice(-3), 10) >> 3 }; + case "RS256": + case "RS384": + case "RS512": + return { hash: hash2, name: "RSASSA-PKCS1-v1_5" }; + case "ES256": + case "ES384": + case "ES512": + return { hash: hash2, name: "ECDSA", namedCurve: algorithm2.namedCurve }; + case "Ed25519": + case "EdDSA": + return { name: "Ed25519" }; + case "ML-DSA-44": + case "ML-DSA-65": + case "ML-DSA-87": + return { name: alg2 }; + default: + throw new JOSENotSupported(`alg ${alg2} is not supported either by JOSE or your javascript runtime`); + } +} +async function getSigKey(alg2, key, usage) { + if (key instanceof Uint8Array) { + if (!alg2.startsWith("HS")) { + throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject", "JSON Web Key")); + } + return crypto.subtle.importKey("raw", key, { hash: `SHA-${alg2.slice(-3)}`, name: "HMAC" }, false, [usage]); + } + checkSigCryptoKey(key, alg2, usage); + return key; +} +async function sign(alg2, key, data2) { + const cryptoKey = await getSigKey(alg2, key, "sign"); + checkKeyLength(alg2, cryptoKey); + const signature = await crypto.subtle.sign(subtleAlgorithm(alg2, cryptoKey.algorithm), cryptoKey, data2); + return new Uint8Array(signature); +} +async function verify(alg2, key, signature, data2) { + const cryptoKey = await getSigKey(alg2, key, "verify"); + checkKeyLength(alg2, cryptoKey); + const algorithm2 = subtleAlgorithm(alg2, cryptoKey.algorithm); + try { + return await crypto.subtle.verify(algorithm2, cryptoKey, signature, data2); + } catch { + return false; + } +} +var init_signing = __esm({ + "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/signing.js"() { + init_errors7(); + init_crypto_key(); + init_invalid_key_input(); + } +}); + +// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/rsaes.js +async function encrypt2(alg2, key, cek) { + checkEncCryptoKey(key, alg2, "encrypt"); + checkKeyLength(alg2, key); + return new Uint8Array(await crypto.subtle.encrypt(subtleAlgorithm2(alg2), key, cek)); +} +async function decrypt2(alg2, key, encryptedKey) { + checkEncCryptoKey(key, alg2, "decrypt"); + checkKeyLength(alg2, key); + return new Uint8Array(await crypto.subtle.decrypt(subtleAlgorithm2(alg2), key, encryptedKey)); +} +var subtleAlgorithm2; +var init_rsaes = __esm({ + "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/rsaes.js"() { + init_crypto_key(); + init_signing(); + init_errors7(); + subtleAlgorithm2 = (alg2) => { + switch (alg2) { + case "RSA-OAEP": + case "RSA-OAEP-256": + case "RSA-OAEP-384": + case "RSA-OAEP-512": + return "RSA-OAEP"; + default: + throw new JOSENotSupported(`alg ${alg2} is not supported either by JOSE or your javascript runtime`); + } + }; + } +}); + +// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/jwk_to_key.js +function subtleMapping(jwk) { + let algorithm2; + let keyUsages; + switch (jwk.kty) { + case "AKP": { + switch (jwk.alg) { + case "ML-DSA-44": + case "ML-DSA-65": + case "ML-DSA-87": + algorithm2 = { name: jwk.alg }; + keyUsages = jwk.priv ? ["sign"] : ["verify"]; + break; + default: + throw new JOSENotSupported(unsupportedAlg); + } + break; + } + case "RSA": { + switch (jwk.alg) { + case "PS256": + case "PS384": + case "PS512": + algorithm2 = { name: "RSA-PSS", hash: `SHA-${jwk.alg.slice(-3)}` }; + keyUsages = jwk.d ? ["sign"] : ["verify"]; + break; + case "RS256": + case "RS384": + case "RS512": + algorithm2 = { name: "RSASSA-PKCS1-v1_5", hash: `SHA-${jwk.alg.slice(-3)}` }; + keyUsages = jwk.d ? ["sign"] : ["verify"]; + break; + case "RSA-OAEP": + case "RSA-OAEP-256": + case "RSA-OAEP-384": + case "RSA-OAEP-512": + algorithm2 = { + name: "RSA-OAEP", + hash: `SHA-${parseInt(jwk.alg.slice(-3), 10) || 1}` + }; + keyUsages = jwk.d ? ["decrypt", "unwrapKey"] : ["encrypt", "wrapKey"]; + break; + default: + throw new JOSENotSupported(unsupportedAlg); + } + break; + } + case "EC": { + switch (jwk.alg) { + case "ES256": + case "ES384": + case "ES512": + algorithm2 = { + name: "ECDSA", + namedCurve: { ES256: "P-256", ES384: "P-384", ES512: "P-521" }[jwk.alg] + }; + keyUsages = jwk.d ? ["sign"] : ["verify"]; + break; + case "ECDH-ES": + case "ECDH-ES+A128KW": + case "ECDH-ES+A192KW": + case "ECDH-ES+A256KW": + algorithm2 = { name: "ECDH", namedCurve: jwk.crv }; + keyUsages = jwk.d ? ["deriveBits"] : []; + break; + default: + throw new JOSENotSupported(unsupportedAlg); + } + break; + } + case "OKP": { + switch (jwk.alg) { + case "Ed25519": + case "EdDSA": + algorithm2 = { name: "Ed25519" }; + keyUsages = jwk.d ? ["sign"] : ["verify"]; + break; + case "ECDH-ES": + case "ECDH-ES+A128KW": + case "ECDH-ES+A192KW": + case "ECDH-ES+A256KW": + algorithm2 = { name: jwk.crv }; + keyUsages = jwk.d ? ["deriveBits"] : []; + break; + default: + throw new JOSENotSupported(unsupportedAlg); + } + break; + } + default: + throw new JOSENotSupported('Invalid or unsupported JWK "kty" (Key Type) Parameter value'); + } + return { algorithm: algorithm2, keyUsages }; +} +async function jwkToKey(jwk) { + if (!jwk.alg) { + throw new TypeError('"alg" argument is required when "jwk.alg" is not present'); + } + const { algorithm: algorithm2, keyUsages } = subtleMapping(jwk); + const keyData = { ...jwk }; + if (keyData.kty !== "AKP") { + delete keyData.alg; + } + delete keyData.use; + return crypto.subtle.importKey("jwk", keyData, algorithm2, jwk.ext ?? (jwk.d || jwk.priv ? false : true), jwk.key_ops ?? keyUsages); +} +var unsupportedAlg; +var init_jwk_to_key = __esm({ + "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/jwk_to_key.js"() { + init_errors7(); + unsupportedAlg = 'Invalid or unsupported JWK "alg" (Algorithm) Parameter value'; + } +}); + +// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/normalize_key.js +async function normalizeKey(key, alg2) { + if (key instanceof Uint8Array) { + return key; + } + if (isCryptoKey(key)) { + return key; + } + if (isKeyObject(key)) { + if (key.type === "secret") { + return key.export(); + } + if ("toCryptoKey" in key && typeof key.toCryptoKey === "function") { + try { + return handleKeyObject(key, alg2); + } catch (err) { + if (err instanceof TypeError) { + throw err; + } + } + } + let jwk = key.export({ format: "jwk" }); + return handleJWK(key, jwk, alg2); + } + if (isJWK(key)) { + if (key.k) { + return decode2(key.k); + } + return handleJWK(key, key, alg2, true); + } + throw new Error("unreachable"); +} +var unusableForAlg, cache5, handleJWK, handleKeyObject; +var init_normalize_key = __esm({ + "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/normalize_key.js"() { + init_type_checks(); + init_base64url(); + init_jwk_to_key(); + init_is_key_like(); + unusableForAlg = "given KeyObject instance cannot be used for this algorithm"; + handleJWK = async (key, jwk, alg2, freeze3 = false) => { + cache5 ||= /* @__PURE__ */ new WeakMap(); + let cached4 = cache5.get(key); + if (cached4?.[alg2]) { + return cached4[alg2]; + } + const cryptoKey = await jwkToKey({ ...jwk, alg: alg2 }); + if (freeze3) + Object.freeze(key); + if (!cached4) { + cache5.set(key, { [alg2]: cryptoKey }); + } else { + cached4[alg2] = cryptoKey; + } + return cryptoKey; + }; + handleKeyObject = (keyObject, alg2) => { + cache5 ||= /* @__PURE__ */ new WeakMap(); + let cached4 = cache5.get(keyObject); + if (cached4?.[alg2]) { + return cached4[alg2]; + } + const isPublic = keyObject.type === "public"; + const extractable = isPublic ? true : false; + let cryptoKey; + if (keyObject.asymmetricKeyType === "x25519") { + switch (alg2) { + case "ECDH-ES": + case "ECDH-ES+A128KW": + case "ECDH-ES+A192KW": + case "ECDH-ES+A256KW": + break; + default: + throw new TypeError(unusableForAlg); + } + cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, isPublic ? [] : ["deriveBits"]); + } + if (keyObject.asymmetricKeyType === "ed25519") { + if (alg2 !== "EdDSA" && alg2 !== "Ed25519") { + throw new TypeError(unusableForAlg); + } + cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, [ + isPublic ? "verify" : "sign" + ]); + } + switch (keyObject.asymmetricKeyType) { + case "ml-dsa-44": + case "ml-dsa-65": + case "ml-dsa-87": { + if (alg2 !== keyObject.asymmetricKeyType.toUpperCase()) { + throw new TypeError(unusableForAlg); + } + cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, [ + isPublic ? "verify" : "sign" + ]); + } + } + if (keyObject.asymmetricKeyType === "rsa") { + let hash2; + switch (alg2) { + case "RSA-OAEP": + hash2 = "SHA-1"; + break; + case "RS256": + case "PS256": + case "RSA-OAEP-256": + hash2 = "SHA-256"; + break; + case "RS384": + case "PS384": + case "RSA-OAEP-384": + hash2 = "SHA-384"; + break; + case "RS512": + case "PS512": + case "RSA-OAEP-512": + hash2 = "SHA-512"; + break; + default: + throw new TypeError(unusableForAlg); + } + if (alg2.startsWith("RSA-OAEP")) { + return keyObject.toCryptoKey({ + name: "RSA-OAEP", + hash: hash2 + }, extractable, isPublic ? ["encrypt"] : ["decrypt"]); + } + cryptoKey = keyObject.toCryptoKey({ + name: alg2.startsWith("PS") ? "RSA-PSS" : "RSASSA-PKCS1-v1_5", + hash: hash2 + }, extractable, [isPublic ? "verify" : "sign"]); + } + if (keyObject.asymmetricKeyType === "ec") { + const nist = /* @__PURE__ */ new Map([ + ["prime256v1", "P-256"], + ["secp384r1", "P-384"], + ["secp521r1", "P-521"] + ]); + const namedCurve = nist.get(keyObject.asymmetricKeyDetails?.namedCurve); + if (!namedCurve) { + throw new TypeError(unusableForAlg); + } + const expectedCurve = { ES256: "P-256", ES384: "P-384", ES512: "P-521" }; + if (expectedCurve[alg2] && namedCurve === expectedCurve[alg2]) { + cryptoKey = keyObject.toCryptoKey({ + name: "ECDSA", + namedCurve + }, extractable, [isPublic ? "verify" : "sign"]); + } + if (alg2.startsWith("ECDH-ES")) { + cryptoKey = keyObject.toCryptoKey({ + name: "ECDH", + namedCurve + }, extractable, isPublic ? [] : ["deriveBits"]); + } + } + if (!cryptoKey) { + throw new TypeError(unusableForAlg); + } + if (!cached4) { + cache5.set(keyObject, { [alg2]: cryptoKey }); + } else { + cached4[alg2] = cryptoKey; + } + return cryptoKey; + }; + } +}); + +// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/key/import.js +async function importJWK(jwk, alg2, options) { + if (!isObject(jwk)) { + throw new TypeError("JWK must be an object"); + } + let ext; + alg2 ??= jwk.alg; + ext ??= options?.extractable ?? jwk.ext; + switch (jwk.kty) { + case "oct": + if (typeof jwk.k !== "string" || !jwk.k) { + throw new TypeError('missing "k" (Key Value) Parameter value'); + } + return decode2(jwk.k); + case "RSA": + if ("oth" in jwk && jwk.oth !== void 0) { + throw new JOSENotSupported('RSA JWK "oth" (Other Primes Info) Parameter value is not supported'); + } + return jwkToKey({ ...jwk, alg: alg2, ext }); + case "AKP": { + if (typeof jwk.alg !== "string" || !jwk.alg) { + throw new TypeError('missing "alg" (Algorithm) Parameter value'); + } + if (alg2 !== void 0 && alg2 !== jwk.alg) { + throw new TypeError("JWK alg and alg option value mismatch"); + } + return jwkToKey({ ...jwk, ext }); + } + case "EC": + case "OKP": + return jwkToKey({ ...jwk, alg: alg2, ext }); + default: + throw new JOSENotSupported('Unsupported "kty" (Key Type) Parameter value'); + } +} +var init_import = __esm({ + "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/key/import.js"() { + init_base64url(); + init_jwk_to_key(); + init_errors7(); + init_type_checks(); + } +}); + +// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/key_to_jwk.js +async function keyToJWK(key) { + if (isKeyObject(key)) { + if (key.type === "secret") { + key = key.export(); + } else { + return key.export({ format: "jwk" }); + } + } + if (key instanceof Uint8Array) { + return { + kty: "oct", + k: encode3(key) + }; + } + if (!isCryptoKey(key)) { + throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject", "Uint8Array")); + } + if (!key.extractable) { + throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK"); + } + const { ext, key_ops, alg: alg2, use: use2, ...jwk } = await crypto.subtle.exportKey("jwk", key); + if (jwk.kty === "AKP") { + ; + jwk.alg = alg2; + } + return jwk; +} +var init_key_to_jwk = __esm({ + "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/key_to_jwk.js"() { + init_invalid_key_input(); + init_base64url(); + init_is_key_like(); + } +}); + +// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/key/export.js +async function exportJWK(key) { + return keyToJWK(key); +} +var init_export = __esm({ + "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/key/export.js"() { + init_key_to_jwk(); + } +}); + +// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/aesgcmkw.js +async function wrap3(alg2, key, cek, iv) { + const jweAlgorithm = alg2.slice(0, 7); + const wrapped = await encrypt(jweAlgorithm, cek, key, iv, new Uint8Array()); + return { + encryptedKey: wrapped.ciphertext, + iv: encode3(wrapped.iv), + tag: encode3(wrapped.tag) + }; +} +async function unwrap3(alg2, key, encryptedKey, iv, tag3) { + const jweAlgorithm = alg2.slice(0, 7); + return decrypt(jweAlgorithm, key, encryptedKey, iv, tag3, new Uint8Array()); +} +var init_aesgcmkw = __esm({ + "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/aesgcmkw.js"() { + init_content_encryption(); + init_base64url(); + } +}); + +// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/key_management.js +function assertEncryptedKey(encryptedKey) { + if (encryptedKey === void 0) + throw new JWEInvalid("JWE Encrypted Key missing"); +} +async function decryptKeyManagement(alg2, key, encryptedKey, joseHeader, options) { + switch (alg2) { + case "dir": { + if (encryptedKey !== void 0) + throw new JWEInvalid("Encountered unexpected JWE Encrypted Key"); + return key; + } + case "ECDH-ES": + if (encryptedKey !== void 0) + throw new JWEInvalid("Encountered unexpected JWE Encrypted Key"); + case "ECDH-ES+A128KW": + case "ECDH-ES+A192KW": + case "ECDH-ES+A256KW": { + if (!isObject(joseHeader.epk)) + throw new JWEInvalid(`JOSE Header "epk" (Ephemeral Public Key) missing or invalid`); + assertCryptoKey(key); + if (!allowed(key)) + throw new JOSENotSupported("ECDH with the provided key is not allowed or not supported by your javascript runtime"); + const epk = await importJWK(joseHeader.epk, alg2); + assertCryptoKey(epk); + let partyUInfo; + let partyVInfo; + if (joseHeader.apu !== void 0) { + if (typeof joseHeader.apu !== "string") + throw new JWEInvalid(`JOSE Header "apu" (Agreement PartyUInfo) invalid`); + partyUInfo = decodeBase64url(joseHeader.apu, "apu", JWEInvalid); + } + if (joseHeader.apv !== void 0) { + if (typeof joseHeader.apv !== "string") + throw new JWEInvalid(`JOSE Header "apv" (Agreement PartyVInfo) invalid`); + partyVInfo = decodeBase64url(joseHeader.apv, "apv", JWEInvalid); + } + const sharedSecret = await deriveKey(epk, key, alg2 === "ECDH-ES" ? joseHeader.enc : alg2, alg2 === "ECDH-ES" ? cekLength(joseHeader.enc) : parseInt(alg2.slice(-5, -2), 10), partyUInfo, partyVInfo); + if (alg2 === "ECDH-ES") + return sharedSecret; + assertEncryptedKey(encryptedKey); + return unwrap(alg2.slice(-6), sharedSecret, encryptedKey); + } + case "RSA-OAEP": + case "RSA-OAEP-256": + case "RSA-OAEP-384": + case "RSA-OAEP-512": { + assertEncryptedKey(encryptedKey); + assertCryptoKey(key); + return decrypt2(alg2, key, encryptedKey); + } + case "PBES2-HS256+A128KW": + case "PBES2-HS384+A192KW": + case "PBES2-HS512+A256KW": { + assertEncryptedKey(encryptedKey); + if (typeof joseHeader.p2c !== "number") + throw new JWEInvalid(`JOSE Header "p2c" (PBES2 Count) missing or invalid`); + const p2cLimit = options?.maxPBES2Count || 1e4; + if (joseHeader.p2c > p2cLimit) + throw new JWEInvalid(`JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds`); + if (typeof joseHeader.p2s !== "string") + throw new JWEInvalid(`JOSE Header "p2s" (PBES2 Salt) missing or invalid`); + let p2s; + p2s = decodeBase64url(joseHeader.p2s, "p2s", JWEInvalid); + return unwrap2(alg2, key, encryptedKey, joseHeader.p2c, p2s); + } + case "A128KW": + case "A192KW": + case "A256KW": { + assertEncryptedKey(encryptedKey); + return unwrap(alg2, key, encryptedKey); + } + case "A128GCMKW": + case "A192GCMKW": + case "A256GCMKW": { + assertEncryptedKey(encryptedKey); + if (typeof joseHeader.iv !== "string") + throw new JWEInvalid(`JOSE Header "iv" (Initialization Vector) missing or invalid`); + if (typeof joseHeader.tag !== "string") + throw new JWEInvalid(`JOSE Header "tag" (Authentication Tag) missing or invalid`); + let iv; + iv = decodeBase64url(joseHeader.iv, "iv", JWEInvalid); + let tag3; + tag3 = decodeBase64url(joseHeader.tag, "tag", JWEInvalid); + return unwrap3(alg2, key, encryptedKey, iv, tag3); + } + default: { + throw new JOSENotSupported(unsupportedAlgHeader); + } + } +} +async function encryptKeyManagement(alg2, enc2, key, providedCek, providedParameters = {}) { + let encryptedKey; + let parameters; + let cek; + switch (alg2) { + case "dir": { + cek = key; + break; + } + case "ECDH-ES": + case "ECDH-ES+A128KW": + case "ECDH-ES+A192KW": + case "ECDH-ES+A256KW": { + assertCryptoKey(key); + if (!allowed(key)) { + throw new JOSENotSupported("ECDH with the provided key is not allowed or not supported by your javascript runtime"); + } + const { apu, apv } = providedParameters; + let ephemeralKey; + if (providedParameters.epk) { + ephemeralKey = await normalizeKey(providedParameters.epk, alg2); + } else { + ephemeralKey = (await crypto.subtle.generateKey(key.algorithm, true, ["deriveBits"])).privateKey; + } + const { x: x5, y: y2, crv, kty } = await exportJWK(ephemeralKey); + const sharedSecret = await deriveKey(key, ephemeralKey, alg2 === "ECDH-ES" ? enc2 : alg2, alg2 === "ECDH-ES" ? cekLength(enc2) : parseInt(alg2.slice(-5, -2), 10), apu, apv); + parameters = { epk: { x: x5, crv, kty } }; + if (kty === "EC") + parameters.epk.y = y2; + if (apu) + parameters.apu = encode3(apu); + if (apv) + parameters.apv = encode3(apv); + if (alg2 === "ECDH-ES") { + cek = sharedSecret; + break; + } + cek = providedCek || generateCek(enc2); + const kwAlg = alg2.slice(-6); + encryptedKey = await wrap(kwAlg, sharedSecret, cek); + break; + } + case "RSA-OAEP": + case "RSA-OAEP-256": + case "RSA-OAEP-384": + case "RSA-OAEP-512": { + cek = providedCek || generateCek(enc2); + assertCryptoKey(key); + encryptedKey = await encrypt2(alg2, key, cek); + break; + } + case "PBES2-HS256+A128KW": + case "PBES2-HS384+A192KW": + case "PBES2-HS512+A256KW": { + cek = providedCek || generateCek(enc2); + const { p2c, p2s } = providedParameters; + ({ encryptedKey, ...parameters } = await wrap2(alg2, key, cek, p2c, p2s)); + break; + } + case "A128KW": + case "A192KW": + case "A256KW": { + cek = providedCek || generateCek(enc2); + encryptedKey = await wrap(alg2, key, cek); + break; + } + case "A128GCMKW": + case "A192GCMKW": + case "A256GCMKW": { + cek = providedCek || generateCek(enc2); + const { iv } = providedParameters; + ({ encryptedKey, ...parameters } = await wrap3(alg2, key, cek, iv)); + break; + } + default: { + throw new JOSENotSupported(unsupportedAlgHeader); + } + } + return { cek, encryptedKey, parameters }; +} +var unsupportedAlgHeader; +var init_key_management = __esm({ + "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/key_management.js"() { + init_aeskw(); + init_ecdhes(); + init_pbes2kw(); + init_rsaes(); + init_base64url(); + init_normalize_key(); + init_errors7(); + init_helpers(); + init_content_encryption(); + init_import(); + init_export(); + init_type_checks(); + init_aesgcmkw(); + init_is_key_like(); + unsupportedAlgHeader = 'Invalid or unsupported "alg" (JWE Algorithm) header value'; + } +}); + +// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/validate_crit.js +function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) { + if (joseHeader.crit !== void 0 && protectedHeader?.crit === void 0) { + throw new Err('"crit" (Critical) Header Parameter MUST be integrity protected'); + } + if (!protectedHeader || protectedHeader.crit === void 0) { + return /* @__PURE__ */ new Set(); + } + if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input) => typeof input !== "string" || input.length === 0)) { + throw new Err('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present'); + } + let recognized; + if (recognizedOption !== void 0) { + recognized = new Map([...Object.entries(recognizedOption), ...recognizedDefault.entries()]); + } else { + recognized = recognizedDefault; + } + for (const parameter of protectedHeader.crit) { + if (!recognized.has(parameter)) { + throw new JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`); + } + if (joseHeader[parameter] === void 0) { + throw new Err(`Extension Header Parameter "${parameter}" is missing`); + } + if (recognized.get(parameter) && protectedHeader[parameter] === void 0) { + throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`); + } + } + return new Set(protectedHeader.crit); +} +var init_validate_crit = __esm({ + "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/validate_crit.js"() { + init_errors7(); + } +}); + +// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/validate_algorithms.js +function validateAlgorithms(option, algorithms) { + if (algorithms !== void 0 && (!Array.isArray(algorithms) || algorithms.some((s5) => typeof s5 !== "string"))) { + throw new TypeError(`"${option}" option must be an array of strings`); + } + if (!algorithms) { + return void 0; + } + return new Set(algorithms); +} +var init_validate_algorithms = __esm({ + "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/validate_algorithms.js"() { + } +}); + +// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/check_key_type.js +function checkKeyType(alg2, key, usage) { + switch (alg2.substring(0, 2)) { + case "A1": + case "A2": + case "di": + case "HS": + case "PB": + symmetricTypeCheck(alg2, key, usage); + break; + default: + asymmetricTypeCheck(alg2, key, usage); + } +} +var tag2, jwkMatchesOp, symmetricTypeCheck, asymmetricTypeCheck; +var init_check_key_type = __esm({ + "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/check_key_type.js"() { + init_invalid_key_input(); + init_is_key_like(); + init_type_checks(); + tag2 = (key) => key?.[Symbol.toStringTag]; + jwkMatchesOp = (alg2, key, usage) => { + if (key.use !== void 0) { + let expected; + switch (usage) { + case "sign": + case "verify": + expected = "sig"; + break; + case "encrypt": + case "decrypt": + expected = "enc"; + break; + } + if (key.use !== expected) { + throw new TypeError(`Invalid key for this operation, its "use" must be "${expected}" when present`); + } + } + if (key.alg !== void 0 && key.alg !== alg2) { + throw new TypeError(`Invalid key for this operation, its "alg" must be "${alg2}" when present`); + } + if (Array.isArray(key.key_ops)) { + let expectedKeyOp; + switch (true) { + case (usage === "sign" || usage === "verify"): + case alg2 === "dir": + case alg2.includes("CBC-HS"): + expectedKeyOp = usage; + break; + case alg2.startsWith("PBES2"): + expectedKeyOp = "deriveBits"; + break; + case /^A\d{3}(?:GCM)?(?:KW)?$/.test(alg2): + if (!alg2.includes("GCM") && alg2.endsWith("KW")) { + expectedKeyOp = usage === "encrypt" ? "wrapKey" : "unwrapKey"; + } else { + expectedKeyOp = usage; + } + break; + case (usage === "encrypt" && alg2.startsWith("RSA")): + expectedKeyOp = "wrapKey"; + break; + case usage === "decrypt": + expectedKeyOp = alg2.startsWith("RSA") ? "unwrapKey" : "deriveBits"; + break; + } + if (expectedKeyOp && key.key_ops?.includes?.(expectedKeyOp) === false) { + throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${expectedKeyOp}" when present`); + } + } + return true; + }; + symmetricTypeCheck = (alg2, key, usage) => { + if (key instanceof Uint8Array) + return; + if (isJWK(key)) { + if (isSecretJWK(key) && jwkMatchesOp(alg2, key, usage)) + return; + throw new TypeError(`JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present`); + } + if (!isKeyLike(key)) { + throw new TypeError(withAlg(alg2, key, "CryptoKey", "KeyObject", "JSON Web Key", "Uint8Array")); + } + if (key.type !== "secret") { + throw new TypeError(`${tag2(key)} instances for symmetric algorithms must be of type "secret"`); + } + }; + asymmetricTypeCheck = (alg2, key, usage) => { + if (isJWK(key)) { + switch (usage) { + case "decrypt": + case "sign": + if (isPrivateJWK(key) && jwkMatchesOp(alg2, key, usage)) + return; + throw new TypeError(`JSON Web Key for this operation must be a private JWK`); + case "encrypt": + case "verify": + if (isPublicJWK(key) && jwkMatchesOp(alg2, key, usage)) + return; + throw new TypeError(`JSON Web Key for this operation must be a public JWK`); + } + } + if (!isKeyLike(key)) { + throw new TypeError(withAlg(alg2, key, "CryptoKey", "KeyObject", "JSON Web Key")); + } + if (key.type === "secret") { + throw new TypeError(`${tag2(key)} instances for asymmetric algorithms must not be of type "secret"`); + } + if (key.type === "public") { + switch (usage) { + case "sign": + throw new TypeError(`${tag2(key)} instances for asymmetric algorithm signing must be of type "private"`); + case "decrypt": + throw new TypeError(`${tag2(key)} instances for asymmetric algorithm decryption must be of type "private"`); + } + } + if (key.type === "private") { + switch (usage) { + case "verify": + throw new TypeError(`${tag2(key)} instances for asymmetric algorithm verifying must be of type "public"`); + case "encrypt": + throw new TypeError(`${tag2(key)} instances for asymmetric algorithm encryption must be of type "public"`); + } + } + }; + } +}); + +// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/deflate.js +function supported(name) { + if (typeof globalThis[name] === "undefined") { + throw new JOSENotSupported(`JWE "zip" (Compression Algorithm) Header Parameter requires the ${name} API.`); + } +} +async function compress(input) { + supported("CompressionStream"); + const cs = new CompressionStream("deflate-raw"); + const writer = cs.writable.getWriter(); + writer.write(input).catch(() => { + }); + writer.close().catch(() => { + }); + const chunks = []; + const reader = cs.readable.getReader(); + for (; ; ) { + const { value, done } = await reader.read(); + if (done) + break; + chunks.push(value); + } + return concat(...chunks); +} +async function decompress(input, maxLength) { + supported("DecompressionStream"); + const ds = new DecompressionStream("deflate-raw"); + const writer = ds.writable.getWriter(); + writer.write(input).catch(() => { + }); + writer.close().catch(() => { + }); + const chunks = []; + let length = 0; + const reader = ds.readable.getReader(); + for (; ; ) { + const { value, done } = await reader.read(); + if (done) + break; + chunks.push(value); + length += value.byteLength; + if (maxLength !== Infinity && length > maxLength) { + throw new JWEInvalid("Decompressed plaintext exceeded the configured limit"); + } + } + return concat(...chunks); +} +var init_deflate = __esm({ + "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/deflate.js"() { + init_errors7(); + init_buffer_utils(); + } +}); + +// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwe/flattened/decrypt.js +async function flattenedDecrypt(jwe, key, options) { + if (!isObject(jwe)) { + throw new JWEInvalid("Flattened JWE must be an object"); + } + if (jwe.protected === void 0 && jwe.header === void 0 && jwe.unprotected === void 0) { + throw new JWEInvalid("JOSE Header missing"); + } + if (jwe.iv !== void 0 && typeof jwe.iv !== "string") { + throw new JWEInvalid("JWE Initialization Vector incorrect type"); + } + if (typeof jwe.ciphertext !== "string") { + throw new JWEInvalid("JWE Ciphertext missing or incorrect type"); + } + if (jwe.tag !== void 0 && typeof jwe.tag !== "string") { + throw new JWEInvalid("JWE Authentication Tag incorrect type"); + } + if (jwe.protected !== void 0 && typeof jwe.protected !== "string") { + throw new JWEInvalid("JWE Protected Header incorrect type"); + } + if (jwe.encrypted_key !== void 0 && typeof jwe.encrypted_key !== "string") { + throw new JWEInvalid("JWE Encrypted Key incorrect type"); + } + if (jwe.aad !== void 0 && typeof jwe.aad !== "string") { + throw new JWEInvalid("JWE AAD incorrect type"); + } + if (jwe.header !== void 0 && !isObject(jwe.header)) { + throw new JWEInvalid("JWE Shared Unprotected Header incorrect type"); + } + if (jwe.unprotected !== void 0 && !isObject(jwe.unprotected)) { + throw new JWEInvalid("JWE Per-Recipient Unprotected Header incorrect type"); + } + let parsedProt; + if (jwe.protected) { + try { + const protectedHeader2 = decode2(jwe.protected); + parsedProt = JSON.parse(decoder.decode(protectedHeader2)); + } catch { + throw new JWEInvalid("JWE Protected Header is invalid"); + } + } + if (!isDisjoint(parsedProt, jwe.header, jwe.unprotected)) { + throw new JWEInvalid("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint"); + } + const joseHeader = { + ...parsedProt, + ...jwe.header, + ...jwe.unprotected + }; + validateCrit(JWEInvalid, /* @__PURE__ */ new Map(), options?.crit, parsedProt, joseHeader); + if (joseHeader.zip !== void 0 && joseHeader.zip !== "DEF") { + throw new JOSENotSupported('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.'); + } + if (joseHeader.zip !== void 0 && !parsedProt?.zip) { + throw new JWEInvalid('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.'); + } + const { alg: alg2, enc: enc2 } = joseHeader; + if (typeof alg2 !== "string" || !alg2) { + throw new JWEInvalid("missing JWE Algorithm (alg) in JWE Header"); + } + if (typeof enc2 !== "string" || !enc2) { + throw new JWEInvalid("missing JWE Encryption Algorithm (enc) in JWE Header"); + } + const keyManagementAlgorithms = options && validateAlgorithms("keyManagementAlgorithms", options.keyManagementAlgorithms); + const contentEncryptionAlgorithms = options && validateAlgorithms("contentEncryptionAlgorithms", options.contentEncryptionAlgorithms); + if (keyManagementAlgorithms && !keyManagementAlgorithms.has(alg2) || !keyManagementAlgorithms && alg2.startsWith("PBES2")) { + throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed'); + } + if (contentEncryptionAlgorithms && !contentEncryptionAlgorithms.has(enc2)) { + throw new JOSEAlgNotAllowed('"enc" (Encryption Algorithm) Header Parameter value not allowed'); + } + let encryptedKey; + if (jwe.encrypted_key !== void 0) { + encryptedKey = decodeBase64url(jwe.encrypted_key, "encrypted_key", JWEInvalid); + } + let resolvedKey = false; + if (typeof key === "function") { + key = await key(parsedProt, jwe); + resolvedKey = true; + } + checkKeyType(alg2 === "dir" ? enc2 : alg2, key, "decrypt"); + const k5 = await normalizeKey(key, alg2); + let cek; + try { + cek = await decryptKeyManagement(alg2, k5, encryptedKey, joseHeader, options); + } catch (err) { + if (err instanceof TypeError || err instanceof JWEInvalid || err instanceof JOSENotSupported) { + throw err; + } + cek = generateCek(enc2); + } + let iv; + let tag3; + if (jwe.iv !== void 0) { + iv = decodeBase64url(jwe.iv, "iv", JWEInvalid); + } + if (jwe.tag !== void 0) { + tag3 = decodeBase64url(jwe.tag, "tag", JWEInvalid); + } + const protectedHeader = jwe.protected !== void 0 ? encode2(jwe.protected) : new Uint8Array(); + let additionalData; + if (jwe.aad !== void 0) { + additionalData = concat(protectedHeader, encode2("."), encode2(jwe.aad)); + } else { + additionalData = protectedHeader; + } + const ciphertext = decodeBase64url(jwe.ciphertext, "ciphertext", JWEInvalid); + const plaintext = await decrypt(enc2, cek, ciphertext, iv, tag3, additionalData); + const result = { plaintext }; + if (joseHeader.zip === "DEF") { + const maxDecompressedLength = options?.maxDecompressedLength ?? 25e4; + if (maxDecompressedLength === 0) { + throw new JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported.'); + } + if (maxDecompressedLength !== Infinity && (!Number.isSafeInteger(maxDecompressedLength) || maxDecompressedLength < 1)) { + throw new TypeError("maxDecompressedLength must be 0, a positive safe integer, or Infinity"); + } + result.plaintext = await decompress(plaintext, maxDecompressedLength).catch((cause) => { + if (cause instanceof JWEInvalid) + throw cause; + throw new JWEInvalid("Failed to decompress plaintext", { cause }); + }); + } + if (jwe.protected !== void 0) { + result.protectedHeader = parsedProt; + } + if (jwe.aad !== void 0) { + result.additionalAuthenticatedData = decodeBase64url(jwe.aad, "aad", JWEInvalid); + } + if (jwe.unprotected !== void 0) { + result.sharedUnprotectedHeader = jwe.unprotected; + } + if (jwe.header !== void 0) { + result.unprotectedHeader = jwe.header; + } + if (resolvedKey) { + return { ...result, key: k5 }; + } + return result; +} +var init_decrypt = __esm({ + "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwe/flattened/decrypt.js"() { + init_base64url(); + init_content_encryption(); + init_helpers(); + init_errors7(); + init_type_checks(); + init_type_checks(); + init_key_management(); + init_buffer_utils(); + init_content_encryption(); + init_validate_crit(); + init_validate_algorithms(); + init_normalize_key(); + init_check_key_type(); + init_deflate(); + } +}); + +// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwe/compact/decrypt.js +async function compactDecrypt(jwe, key, options) { + if (jwe instanceof Uint8Array) { + jwe = decoder.decode(jwe); + } + if (typeof jwe !== "string") { + throw new JWEInvalid("Compact JWE must be a string or Uint8Array"); + } + const { 0: protectedHeader, 1: encryptedKey, 2: iv, 3: ciphertext, 4: tag3, length } = jwe.split("."); + if (length !== 5) { + throw new JWEInvalid("Invalid Compact JWE"); + } + const decrypted = await flattenedDecrypt({ + ciphertext, + iv: iv || void 0, + protected: protectedHeader, + tag: tag3 || void 0, + encrypted_key: encryptedKey || void 0 + }, key, options); + const result = { plaintext: decrypted.plaintext, protectedHeader: decrypted.protectedHeader }; + if (typeof key === "function") { + return { ...result, key: decrypted.key }; + } + return result; +} +var init_decrypt2 = __esm({ + "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwe/compact/decrypt.js"() { + init_decrypt(); + init_errors7(); + init_buffer_utils(); + } +}); + +// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwe/flattened/encrypt.js +var FlattenedEncrypt; +var init_encrypt = __esm({ + "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwe/flattened/encrypt.js"() { + init_base64url(); + init_helpers(); + init_content_encryption(); + init_key_management(); + init_errors7(); + init_type_checks(); + init_buffer_utils(); + init_validate_crit(); + init_normalize_key(); + init_check_key_type(); + init_deflate(); + FlattenedEncrypt = class { + #plaintext; + #protectedHeader; + #sharedUnprotectedHeader; + #unprotectedHeader; + #aad; + #cek; + #iv; + #keyManagementParameters; + constructor(plaintext) { + if (!(plaintext instanceof Uint8Array)) { + throw new TypeError("plaintext must be an instance of Uint8Array"); + } + this.#plaintext = plaintext; + } + setKeyManagementParameters(parameters) { + assertNotSet(this.#keyManagementParameters, "setKeyManagementParameters"); + this.#keyManagementParameters = parameters; + return this; + } + setProtectedHeader(protectedHeader) { + assertNotSet(this.#protectedHeader, "setProtectedHeader"); + this.#protectedHeader = protectedHeader; + return this; + } + setSharedUnprotectedHeader(sharedUnprotectedHeader) { + assertNotSet(this.#sharedUnprotectedHeader, "setSharedUnprotectedHeader"); + this.#sharedUnprotectedHeader = sharedUnprotectedHeader; + return this; + } + setUnprotectedHeader(unprotectedHeader) { + assertNotSet(this.#unprotectedHeader, "setUnprotectedHeader"); + this.#unprotectedHeader = unprotectedHeader; + return this; + } + setAdditionalAuthenticatedData(aad) { + this.#aad = aad; + return this; + } + setContentEncryptionKey(cek) { + assertNotSet(this.#cek, "setContentEncryptionKey"); + this.#cek = cek; + return this; + } + setInitializationVector(iv) { + assertNotSet(this.#iv, "setInitializationVector"); + this.#iv = iv; + return this; + } + async encrypt(key, options) { + if (!this.#protectedHeader && !this.#unprotectedHeader && !this.#sharedUnprotectedHeader) { + throw new JWEInvalid("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()"); + } + if (!isDisjoint(this.#protectedHeader, this.#unprotectedHeader, this.#sharedUnprotectedHeader)) { + throw new JWEInvalid("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint"); + } + const joseHeader = { + ...this.#protectedHeader, + ...this.#unprotectedHeader, + ...this.#sharedUnprotectedHeader + }; + validateCrit(JWEInvalid, /* @__PURE__ */ new Map(), options?.crit, this.#protectedHeader, joseHeader); + if (joseHeader.zip !== void 0 && joseHeader.zip !== "DEF") { + throw new JOSENotSupported('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.'); + } + if (joseHeader.zip !== void 0 && !this.#protectedHeader?.zip) { + throw new JWEInvalid('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.'); + } + const { alg: alg2, enc: enc2 } = joseHeader; + if (typeof alg2 !== "string" || !alg2) { + throw new JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid'); + } + if (typeof enc2 !== "string" || !enc2) { + throw new JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid'); + } + let encryptedKey; + if (this.#cek && (alg2 === "dir" || alg2 === "ECDH-ES")) { + throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${alg2}`); + } + checkKeyType(alg2 === "dir" ? enc2 : alg2, key, "encrypt"); + let cek; + { + let parameters; + const k5 = await normalizeKey(key, alg2); + ({ cek, encryptedKey, parameters } = await encryptKeyManagement(alg2, enc2, k5, this.#cek, this.#keyManagementParameters)); + if (parameters) { + if (options && unprotected in options) { + if (!this.#unprotectedHeader) { + this.setUnprotectedHeader(parameters); + } else { + this.#unprotectedHeader = { ...this.#unprotectedHeader, ...parameters }; + } + } else if (!this.#protectedHeader) { + this.setProtectedHeader(parameters); + } else { + this.#protectedHeader = { ...this.#protectedHeader, ...parameters }; + } + } + } + let additionalData; + let protectedHeaderS; + let protectedHeaderB; + let aadMember; + if (this.#protectedHeader) { + protectedHeaderS = encode3(JSON.stringify(this.#protectedHeader)); + protectedHeaderB = encode2(protectedHeaderS); + } else { + protectedHeaderS = ""; + protectedHeaderB = new Uint8Array(); + } + if (this.#aad) { + aadMember = encode3(this.#aad); + const aadMemberBytes = encode2(aadMember); + additionalData = concat(protectedHeaderB, encode2("."), aadMemberBytes); + } else { + additionalData = protectedHeaderB; + } + let plaintext = this.#plaintext; + if (joseHeader.zip === "DEF") { + plaintext = await compress(plaintext).catch((cause) => { + throw new JWEInvalid("Failed to compress plaintext", { cause }); + }); + } + const { ciphertext, tag: tag3, iv } = await encrypt(enc2, plaintext, cek, this.#iv, additionalData); + const jwe = { + ciphertext: encode3(ciphertext) + }; + if (iv) { + jwe.iv = encode3(iv); + } + if (tag3) { + jwe.tag = encode3(tag3); + } + if (encryptedKey) { + jwe.encrypted_key = encode3(encryptedKey); + } + if (aadMember) { + jwe.aad = aadMember; + } + if (this.#protectedHeader) { + jwe.protected = protectedHeaderS; + } + if (this.#sharedUnprotectedHeader) { + jwe.unprotected = this.#sharedUnprotectedHeader; + } + if (this.#unprotectedHeader) { + jwe.header = this.#unprotectedHeader; + } + return jwe; + } + }; + } +}); + +// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/flattened/verify.js +async function flattenedVerify(jws, key, options) { + if (!isObject(jws)) { + throw new JWSInvalid("Flattened JWS must be an object"); + } + if (jws.protected === void 0 && jws.header === void 0) { + throw new JWSInvalid('Flattened JWS must have either of the "protected" or "header" members'); + } + if (jws.protected !== void 0 && typeof jws.protected !== "string") { + throw new JWSInvalid("JWS Protected Header incorrect type"); + } + if (jws.payload === void 0) { + throw new JWSInvalid("JWS Payload missing"); + } + if (typeof jws.signature !== "string") { + throw new JWSInvalid("JWS Signature missing or incorrect type"); + } + if (jws.header !== void 0 && !isObject(jws.header)) { + throw new JWSInvalid("JWS Unprotected Header incorrect type"); + } + let parsedProt = {}; + if (jws.protected) { + try { + const protectedHeader = decode2(jws.protected); + parsedProt = JSON.parse(decoder.decode(protectedHeader)); + } catch { + throw new JWSInvalid("JWS Protected Header is invalid"); + } + } + if (!isDisjoint(parsedProt, jws.header)) { + throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint"); + } + const joseHeader = { + ...parsedProt, + ...jws.header + }; + const extensions = validateCrit(JWSInvalid, /* @__PURE__ */ new Map([["b64", true]]), options?.crit, parsedProt, joseHeader); + let b64 = true; + if (extensions.has("b64")) { + b64 = parsedProt.b64; + if (typeof b64 !== "boolean") { + throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean'); + } + } + const { alg: alg2 } = joseHeader; + if (typeof alg2 !== "string" || !alg2) { + throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid'); + } + const algorithms = options && validateAlgorithms("algorithms", options.algorithms); + if (algorithms && !algorithms.has(alg2)) { + throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed'); + } + if (b64) { + if (typeof jws.payload !== "string") { + throw new JWSInvalid("JWS Payload must be a string"); + } + } else if (typeof jws.payload !== "string" && !(jws.payload instanceof Uint8Array)) { + throw new JWSInvalid("JWS Payload must be a string or an Uint8Array instance"); + } + let resolvedKey = false; + if (typeof key === "function") { + key = await key(parsedProt, jws); + resolvedKey = true; + } + checkKeyType(alg2, key, "verify"); + const data2 = concat(jws.protected !== void 0 ? encode2(jws.protected) : new Uint8Array(), encode2("."), typeof jws.payload === "string" ? b64 ? encode2(jws.payload) : encoder.encode(jws.payload) : jws.payload); + const signature = decodeBase64url(jws.signature, "signature", JWSInvalid); + const k5 = await normalizeKey(key, alg2); + const verified = await verify(alg2, k5, signature, data2); + if (!verified) { + throw new JWSSignatureVerificationFailed(); + } + let payload2; + if (b64) { + payload2 = decodeBase64url(jws.payload, "payload", JWSInvalid); + } else if (typeof jws.payload === "string") { + payload2 = encoder.encode(jws.payload); + } else { + payload2 = jws.payload; + } + const result = { payload: payload2 }; + if (jws.protected !== void 0) { + result.protectedHeader = parsedProt; + } + if (jws.header !== void 0) { + result.unprotectedHeader = jws.header; + } + if (resolvedKey) { + return { ...result, key: k5 }; + } + return result; +} +var init_verify = __esm({ + "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/flattened/verify.js"() { + init_base64url(); + init_signing(); + init_errors7(); + init_buffer_utils(); + init_helpers(); + init_type_checks(); + init_type_checks(); + init_check_key_type(); + init_validate_crit(); + init_validate_algorithms(); + init_normalize_key(); + } +}); + +// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/compact/verify.js +async function compactVerify(jws, key, options) { + if (jws instanceof Uint8Array) { + jws = decoder.decode(jws); + } + if (typeof jws !== "string") { + throw new JWSInvalid("Compact JWS must be a string or Uint8Array"); + } + const { 0: protectedHeader, 1: payload2, 2: signature, length } = jws.split("."); + if (length !== 3) { + throw new JWSInvalid("Invalid Compact JWS"); + } + const verified = await flattenedVerify({ payload: payload2, protected: protectedHeader, signature }, key, options); + const result = { payload: verified.payload, protectedHeader: verified.protectedHeader }; + if (typeof key === "function") { + return { ...result, key: verified.key }; + } + return result; +} +var init_verify2 = __esm({ + "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/compact/verify.js"() { + init_verify(); + init_errors7(); + init_buffer_utils(); + } +}); + +// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/jwt_claims_set.js +function secs(str) { + const matched = REGEX.exec(str); + if (!matched || matched[4] && matched[1]) { + throw new TypeError("Invalid time period format"); + } + const value = parseFloat(matched[2]); + const unit = matched[3].toLowerCase(); + let numericDate; + switch (unit) { + case "sec": + case "secs": + case "second": + case "seconds": + case "s": + numericDate = Math.round(value); + break; + case "minute": + case "minutes": + case "min": + case "mins": + case "m": + numericDate = Math.round(value * minute); + break; + case "hour": + case "hours": + case "hr": + case "hrs": + case "h": + numericDate = Math.round(value * hour); + break; + case "day": + case "days": + case "d": + numericDate = Math.round(value * day); + break; + case "week": + case "weeks": + case "w": + numericDate = Math.round(value * week); + break; + default: + numericDate = Math.round(value * year2); + break; + } + if (matched[1] === "-" || matched[4] === "ago") { + return -numericDate; + } + return numericDate; +} +function validateInput(label, input) { + if (!Number.isFinite(input)) { + throw new TypeError(`Invalid ${label} input`); + } + return input; +} +function validateClaimsSet(protectedHeader, encodedPayload, options = {}) { + let payload2; + try { + payload2 = JSON.parse(decoder.decode(encodedPayload)); + } catch { + } + if (!isObject(payload2)) { + throw new JWTInvalid("JWT Claims Set must be a top-level JSON object"); + } + const { typ } = options; + if (typ && (typeof protectedHeader.typ !== "string" || normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ))) { + throw new JWTClaimValidationFailed('unexpected "typ" JWT header value', payload2, "typ", "check_failed"); + } + const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options; + const presenceCheck = [...requiredClaims]; + if (maxTokenAge !== void 0) + presenceCheck.push("iat"); + if (audience !== void 0) + presenceCheck.push("aud"); + if (subject !== void 0) + presenceCheck.push("sub"); + if (issuer !== void 0) + presenceCheck.push("iss"); + for (const claim of new Set(presenceCheck.reverse())) { + if (!(claim in payload2)) { + throw new JWTClaimValidationFailed(`missing required "${claim}" claim`, payload2, claim, "missing"); + } + } + if (issuer && !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload2.iss)) { + throw new JWTClaimValidationFailed('unexpected "iss" claim value', payload2, "iss", "check_failed"); + } + if (subject && payload2.sub !== subject) { + throw new JWTClaimValidationFailed('unexpected "sub" claim value', payload2, "sub", "check_failed"); + } + if (audience && !checkAudiencePresence(payload2.aud, typeof audience === "string" ? [audience] : audience)) { + throw new JWTClaimValidationFailed('unexpected "aud" claim value', payload2, "aud", "check_failed"); + } + let tolerance; + switch (typeof options.clockTolerance) { + case "string": + tolerance = secs(options.clockTolerance); + break; + case "number": + tolerance = options.clockTolerance; + break; + case "undefined": + tolerance = 0; + break; + default: + throw new TypeError("Invalid clockTolerance option type"); + } + const { currentDate } = options; + const now2 = epoch(currentDate || /* @__PURE__ */ new Date()); + if ((payload2.iat !== void 0 || maxTokenAge) && typeof payload2.iat !== "number") { + throw new JWTClaimValidationFailed('"iat" claim must be a number', payload2, "iat", "invalid"); + } + if (payload2.nbf !== void 0) { + if (typeof payload2.nbf !== "number") { + throw new JWTClaimValidationFailed('"nbf" claim must be a number', payload2, "nbf", "invalid"); + } + if (payload2.nbf > now2 + tolerance) { + throw new JWTClaimValidationFailed('"nbf" claim timestamp check failed', payload2, "nbf", "check_failed"); + } + } + if (payload2.exp !== void 0) { + if (typeof payload2.exp !== "number") { + throw new JWTClaimValidationFailed('"exp" claim must be a number', payload2, "exp", "invalid"); + } + if (payload2.exp <= now2 - tolerance) { + throw new JWTExpired('"exp" claim timestamp check failed', payload2, "exp", "check_failed"); + } + } + if (maxTokenAge) { + const age = now2 - payload2.iat; + const max = typeof maxTokenAge === "number" ? maxTokenAge : secs(maxTokenAge); + if (age - tolerance > max) { + throw new JWTExpired('"iat" claim timestamp check failed (too far in the past)', payload2, "iat", "check_failed"); + } + if (age < 0 - tolerance) { + throw new JWTClaimValidationFailed('"iat" claim timestamp check failed (it should be in the past)', payload2, "iat", "check_failed"); + } + } + return payload2; +} +var epoch, minute, hour, day, week, year2, REGEX, normalizeTyp, checkAudiencePresence, JWTClaimsBuilder; +var init_jwt_claims_set = __esm({ + "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/jwt_claims_set.js"() { + init_errors7(); + init_buffer_utils(); + init_type_checks(); + epoch = (date7) => Math.floor(date7.getTime() / 1e3); + minute = 60; + hour = minute * 60; + day = hour * 24; + week = day * 7; + year2 = day * 365.25; + REGEX = /^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i; + normalizeTyp = (value) => { + if (value.includes("/")) { + return value.toLowerCase(); + } + return `application/${value.toLowerCase()}`; + }; + checkAudiencePresence = (audPayload, audOption) => { + if (typeof audPayload === "string") { + return audOption.includes(audPayload); + } + if (Array.isArray(audPayload)) { + return audOption.some(Set.prototype.has.bind(new Set(audPayload))); + } + return false; + }; + JWTClaimsBuilder = class { + #payload; + constructor(payload2) { + if (!isObject(payload2)) { + throw new TypeError("JWT Claims Set MUST be an object"); + } + this.#payload = structuredClone(payload2); + } + data() { + return encoder.encode(JSON.stringify(this.#payload)); + } + get iss() { + return this.#payload.iss; + } + set iss(value) { + this.#payload.iss = value; + } + get sub() { + return this.#payload.sub; + } + set sub(value) { + this.#payload.sub = value; + } + get aud() { + return this.#payload.aud; + } + set aud(value) { + this.#payload.aud = value; + } + set jti(value) { + this.#payload.jti = value; + } + set nbf(value) { + if (typeof value === "number") { + this.#payload.nbf = validateInput("setNotBefore", value); + } else if (value instanceof Date) { + this.#payload.nbf = validateInput("setNotBefore", epoch(value)); + } else { + this.#payload.nbf = epoch(/* @__PURE__ */ new Date()) + secs(value); + } + } + set exp(value) { + if (typeof value === "number") { + this.#payload.exp = validateInput("setExpirationTime", value); + } else if (value instanceof Date) { + this.#payload.exp = validateInput("setExpirationTime", epoch(value)); + } else { + this.#payload.exp = epoch(/* @__PURE__ */ new Date()) + secs(value); + } + } + set iat(value) { + if (value === void 0) { + this.#payload.iat = epoch(/* @__PURE__ */ new Date()); + } else if (value instanceof Date) { + this.#payload.iat = validateInput("setIssuedAt", epoch(value)); + } else if (typeof value === "string") { + this.#payload.iat = validateInput("setIssuedAt", epoch(/* @__PURE__ */ new Date()) + secs(value)); + } else { + this.#payload.iat = validateInput("setIssuedAt", value); + } + } + }; + } +}); + +// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwt/verify.js +async function jwtVerify(jwt2, key, options) { + const verified = await compactVerify(jwt2, key, options); + if (verified.protectedHeader.crit?.includes("b64") && verified.protectedHeader.b64 === false) { + throw new JWTInvalid("JWTs MUST NOT use unencoded payload"); + } + const payload2 = validateClaimsSet(verified.protectedHeader, verified.payload, options); + const result = { payload: payload2, protectedHeader: verified.protectedHeader }; + if (typeof key === "function") { + return { ...result, key: verified.key }; + } + return result; +} +var init_verify3 = __esm({ + "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwt/verify.js"() { + init_verify2(); + init_jwt_claims_set(); + init_errors7(); + } +}); + +// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwt/decrypt.js +async function jwtDecrypt(jwt2, key, options) { + const decrypted = await compactDecrypt(jwt2, key, options); + const payload2 = validateClaimsSet(decrypted.protectedHeader, decrypted.plaintext, options); + const { protectedHeader } = decrypted; + if (protectedHeader.iss !== void 0 && protectedHeader.iss !== payload2.iss) { + throw new JWTClaimValidationFailed('replicated "iss" claim header parameter mismatch', payload2, "iss", "mismatch"); + } + if (protectedHeader.sub !== void 0 && protectedHeader.sub !== payload2.sub) { + throw new JWTClaimValidationFailed('replicated "sub" claim header parameter mismatch', payload2, "sub", "mismatch"); + } + if (protectedHeader.aud !== void 0 && JSON.stringify(protectedHeader.aud) !== JSON.stringify(payload2.aud)) { + throw new JWTClaimValidationFailed('replicated "aud" claim header parameter mismatch', payload2, "aud", "mismatch"); + } + const result = { payload: payload2, protectedHeader }; + if (typeof key === "function") { + return { ...result, key: decrypted.key }; + } + return result; +} +var init_decrypt3 = __esm({ + "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwt/decrypt.js"() { + init_decrypt2(); + init_jwt_claims_set(); + init_errors7(); + } +}); + +// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwe/compact/encrypt.js +var CompactEncrypt; +var init_encrypt2 = __esm({ + "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwe/compact/encrypt.js"() { + init_encrypt(); + CompactEncrypt = class { + #flattened; + constructor(plaintext) { + this.#flattened = new FlattenedEncrypt(plaintext); + } + setContentEncryptionKey(cek) { + this.#flattened.setContentEncryptionKey(cek); + return this; + } + setInitializationVector(iv) { + this.#flattened.setInitializationVector(iv); + return this; + } + setProtectedHeader(protectedHeader) { + this.#flattened.setProtectedHeader(protectedHeader); + return this; + } + setKeyManagementParameters(parameters) { + this.#flattened.setKeyManagementParameters(parameters); + return this; + } + async encrypt(key, options) { + const jwe = await this.#flattened.encrypt(key, options); + return [jwe.protected, jwe.encrypted_key, jwe.iv, jwe.ciphertext, jwe.tag].join("."); + } + }; + } +}); + +// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/flattened/sign.js +var FlattenedSign; +var init_sign = __esm({ + "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/flattened/sign.js"() { + init_base64url(); + init_signing(); + init_type_checks(); + init_errors7(); + init_buffer_utils(); + init_check_key_type(); + init_validate_crit(); + init_normalize_key(); + init_helpers(); + FlattenedSign = class { + #payload; + #protectedHeader; + #unprotectedHeader; + constructor(payload2) { + if (!(payload2 instanceof Uint8Array)) { + throw new TypeError("payload must be an instance of Uint8Array"); + } + this.#payload = payload2; + } + setProtectedHeader(protectedHeader) { + assertNotSet(this.#protectedHeader, "setProtectedHeader"); + this.#protectedHeader = protectedHeader; + return this; + } + setUnprotectedHeader(unprotectedHeader) { + assertNotSet(this.#unprotectedHeader, "setUnprotectedHeader"); + this.#unprotectedHeader = unprotectedHeader; + return this; + } + async sign(key, options) { + if (!this.#protectedHeader && !this.#unprotectedHeader) { + throw new JWSInvalid("either setProtectedHeader or setUnprotectedHeader must be called before #sign()"); + } + if (!isDisjoint(this.#protectedHeader, this.#unprotectedHeader)) { + throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint"); + } + const joseHeader = { + ...this.#protectedHeader, + ...this.#unprotectedHeader + }; + const extensions = validateCrit(JWSInvalid, /* @__PURE__ */ new Map([["b64", true]]), options?.crit, this.#protectedHeader, joseHeader); + let b64 = true; + if (extensions.has("b64")) { + b64 = this.#protectedHeader.b64; + if (typeof b64 !== "boolean") { + throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean'); + } + } + const { alg: alg2 } = joseHeader; + if (typeof alg2 !== "string" || !alg2) { + throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid'); + } + checkKeyType(alg2, key, "sign"); + let payloadS; + let payloadB; + if (b64) { + payloadS = encode3(this.#payload); + payloadB = encode2(payloadS); + } else { + payloadB = this.#payload; + payloadS = ""; + } + let protectedHeaderString; + let protectedHeaderBytes; + if (this.#protectedHeader) { + protectedHeaderString = encode3(JSON.stringify(this.#protectedHeader)); + protectedHeaderBytes = encode2(protectedHeaderString); + } else { + protectedHeaderString = ""; + protectedHeaderBytes = new Uint8Array(); + } + const data2 = concat(protectedHeaderBytes, encode2("."), payloadB); + const k5 = await normalizeKey(key, alg2); + const signature = await sign(alg2, k5, data2); + const jws = { + signature: encode3(signature), + payload: payloadS + }; + if (this.#unprotectedHeader) { + jws.header = this.#unprotectedHeader; + } + if (this.#protectedHeader) { + jws.protected = protectedHeaderString; + } + return jws; + } + }; + } +}); + +// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/compact/sign.js +var CompactSign; +var init_sign2 = __esm({ + "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/compact/sign.js"() { + init_sign(); + CompactSign = class { + #flattened; + constructor(payload2) { + this.#flattened = new FlattenedSign(payload2); + } + setProtectedHeader(protectedHeader) { + this.#flattened.setProtectedHeader(protectedHeader); + return this; + } + async sign(key, options) { + const jws = await this.#flattened.sign(key, options); + if (jws.payload === void 0) { + throw new TypeError("use the flattened module for creating JWS with b64: false"); + } + return `${jws.protected}.${jws.payload}.${jws.signature}`; + } + }; + } +}); + +// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwt/sign.js +var SignJWT; +var init_sign3 = __esm({ + "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwt/sign.js"() { + init_sign2(); + init_errors7(); + init_jwt_claims_set(); + SignJWT = class { + #protectedHeader; + #jwt; + constructor(payload2 = {}) { + this.#jwt = new JWTClaimsBuilder(payload2); + } + setIssuer(issuer) { + this.#jwt.iss = issuer; + return this; + } + setSubject(subject) { + this.#jwt.sub = subject; + return this; + } + setAudience(audience) { + this.#jwt.aud = audience; + return this; + } + setJti(jwtId) { + this.#jwt.jti = jwtId; + return this; + } + setNotBefore(input) { + this.#jwt.nbf = input; + return this; + } + setExpirationTime(input) { + this.#jwt.exp = input; + return this; + } + setIssuedAt(input) { + this.#jwt.iat = input; + return this; + } + setProtectedHeader(protectedHeader) { + this.#protectedHeader = protectedHeader; + return this; + } + async sign(key, options) { + const sig = new CompactSign(this.#jwt.data()); + sig.setProtectedHeader(this.#protectedHeader); + if (Array.isArray(this.#protectedHeader?.crit) && this.#protectedHeader.crit.includes("b64") && this.#protectedHeader.b64 === false) { + throw new JWTInvalid("JWTs MUST NOT use unencoded payload"); + } + return sig.sign(key, options); + } + }; + } +}); + +// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwt/encrypt.js +var EncryptJWT; +var init_encrypt3 = __esm({ + "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwt/encrypt.js"() { + init_encrypt2(); + init_jwt_claims_set(); + init_helpers(); + EncryptJWT = class { + #cek; + #iv; + #keyManagementParameters; + #protectedHeader; + #replicateIssuerAsHeader; + #replicateSubjectAsHeader; + #replicateAudienceAsHeader; + #jwt; + constructor(payload2 = {}) { + this.#jwt = new JWTClaimsBuilder(payload2); + } + setIssuer(issuer) { + this.#jwt.iss = issuer; + return this; + } + setSubject(subject) { + this.#jwt.sub = subject; + return this; + } + setAudience(audience) { + this.#jwt.aud = audience; + return this; + } + setJti(jwtId) { + this.#jwt.jti = jwtId; + return this; + } + setNotBefore(input) { + this.#jwt.nbf = input; + return this; + } + setExpirationTime(input) { + this.#jwt.exp = input; + return this; + } + setIssuedAt(input) { + this.#jwt.iat = input; + return this; + } + setProtectedHeader(protectedHeader) { + assertNotSet(this.#protectedHeader, "setProtectedHeader"); + this.#protectedHeader = protectedHeader; + return this; + } + setKeyManagementParameters(parameters) { + assertNotSet(this.#keyManagementParameters, "setKeyManagementParameters"); + this.#keyManagementParameters = parameters; + return this; + } + setContentEncryptionKey(cek) { + assertNotSet(this.#cek, "setContentEncryptionKey"); + this.#cek = cek; + return this; + } + setInitializationVector(iv) { + assertNotSet(this.#iv, "setInitializationVector"); + this.#iv = iv; + return this; + } + replicateIssuerAsHeader() { + this.#replicateIssuerAsHeader = true; + return this; + } + replicateSubjectAsHeader() { + this.#replicateSubjectAsHeader = true; + return this; + } + replicateAudienceAsHeader() { + this.#replicateAudienceAsHeader = true; + return this; + } + async encrypt(key, options) { + const enc2 = new CompactEncrypt(this.#jwt.data()); + if (this.#protectedHeader && (this.#replicateIssuerAsHeader || this.#replicateSubjectAsHeader || this.#replicateAudienceAsHeader)) { + this.#protectedHeader = { + ...this.#protectedHeader, + iss: this.#replicateIssuerAsHeader ? this.#jwt.iss : void 0, + sub: this.#replicateSubjectAsHeader ? this.#jwt.sub : void 0, + aud: this.#replicateAudienceAsHeader ? this.#jwt.aud : void 0 + }; + } + enc2.setProtectedHeader(this.#protectedHeader); + if (this.#iv) { + enc2.setInitializationVector(this.#iv); + } + if (this.#cek) { + enc2.setContentEncryptionKey(this.#cek); + } + if (this.#keyManagementParameters) { + enc2.setKeyManagementParameters(this.#keyManagementParameters); + } + return enc2.encrypt(key, options); + } + }; + } +}); + +// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwk/thumbprint.js +async function calculateJwkThumbprint(key, digestAlgorithm) { + let jwk; + if (isJWK(key)) { + jwk = key; + } else if (isKeyLike(key)) { + jwk = await exportJWK(key); + } else { + throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject", "JSON Web Key")); + } + digestAlgorithm ??= "sha256"; + if (digestAlgorithm !== "sha256" && digestAlgorithm !== "sha384" && digestAlgorithm !== "sha512") { + throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"'); + } + let components; + switch (jwk.kty) { + case "AKP": + check(jwk.alg, '"alg" (Algorithm) Parameter'); + check(jwk.pub, '"pub" (Public key) Parameter'); + components = { alg: jwk.alg, kty: jwk.kty, pub: jwk.pub }; + break; + case "EC": + check(jwk.crv, '"crv" (Curve) Parameter'); + check(jwk.x, '"x" (X Coordinate) Parameter'); + check(jwk.y, '"y" (Y Coordinate) Parameter'); + components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y }; + break; + case "OKP": + check(jwk.crv, '"crv" (Subtype of Key Pair) Parameter'); + check(jwk.x, '"x" (Public Key) Parameter'); + components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x }; + break; + case "RSA": + check(jwk.e, '"e" (Exponent) Parameter'); + check(jwk.n, '"n" (Modulus) Parameter'); + components = { e: jwk.e, kty: jwk.kty, n: jwk.n }; + break; + case "oct": + check(jwk.k, '"k" (Key Value) Parameter'); + components = { k: jwk.k, kty: jwk.kty }; + break; + default: + throw new JOSENotSupported('"kty" (Key Type) Parameter missing or unsupported'); + } + const data2 = encode2(JSON.stringify(components)); + return encode3(await digest(digestAlgorithm, data2)); +} +var check; +var init_thumbprint = __esm({ + "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwk/thumbprint.js"() { + init_helpers(); + init_base64url(); + init_errors7(); + init_buffer_utils(); + init_is_key_like(); + init_type_checks(); + init_export(); + init_invalid_key_input(); + check = (value, description) => { + if (typeof value !== "string" || !value) { + throw new JWKInvalid(`${description} missing or invalid`); + } + }; + } +}); + +// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwks/local.js +function getKtyFromAlg(alg2) { + switch (typeof alg2 === "string" && alg2.slice(0, 2)) { + case "RS": + case "PS": + return "RSA"; + case "ES": + return "EC"; + case "Ed": + return "OKP"; + case "ML": + return "AKP"; + default: + throw new JOSENotSupported('Unsupported "alg" value for a JSON Web Key Set'); + } +} +function isJWKSLike(jwks) { + return jwks && typeof jwks === "object" && Array.isArray(jwks.keys) && jwks.keys.every(isJWKLike); +} +function isJWKLike(key) { + return isObject(key); +} +async function importWithAlgCache(cache7, jwk, alg2) { + const cached4 = cache7.get(jwk) || cache7.set(jwk, {}).get(jwk); + if (cached4[alg2] === void 0) { + const key = await importJWK({ ...jwk, ext: true }, alg2); + if (key instanceof Uint8Array || key.type !== "public") { + throw new JWKSInvalid("JSON Web Key Set members must be public keys"); + } + cached4[alg2] = key; + } + return cached4[alg2]; +} +function createLocalJWKSet(jwks) { + const set2 = new LocalJWKSet(jwks); + const localJWKSet = async (protectedHeader, token) => set2.getKey(protectedHeader, token); + Object.defineProperties(localJWKSet, { + jwks: { + value: () => structuredClone(set2.jwks()), + enumerable: false, + configurable: false, + writable: false + } + }); + return localJWKSet; +} +var LocalJWKSet; +var init_local = __esm({ + "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwks/local.js"() { + init_import(); + init_errors7(); + init_type_checks(); + LocalJWKSet = class { + #jwks; + #cached = /* @__PURE__ */ new WeakMap(); + constructor(jwks) { + if (!isJWKSLike(jwks)) { + throw new JWKSInvalid("JSON Web Key Set malformed"); + } + this.#jwks = structuredClone(jwks); + } + jwks() { + return this.#jwks; + } + async getKey(protectedHeader, token) { + const { alg: alg2, kid } = { ...protectedHeader, ...token?.header }; + const kty = getKtyFromAlg(alg2); + const candidates = this.#jwks.keys.filter((jwk2) => { + let candidate = kty === jwk2.kty; + if (candidate && typeof kid === "string") { + candidate = kid === jwk2.kid; + } + if (candidate && (typeof jwk2.alg === "string" || kty === "AKP")) { + candidate = alg2 === jwk2.alg; + } + if (candidate && typeof jwk2.use === "string") { + candidate = jwk2.use === "sig"; + } + if (candidate && Array.isArray(jwk2.key_ops)) { + candidate = jwk2.key_ops.includes("verify"); + } + if (candidate) { + switch (alg2) { + case "ES256": + candidate = jwk2.crv === "P-256"; + break; + case "ES384": + candidate = jwk2.crv === "P-384"; + break; + case "ES512": + candidate = jwk2.crv === "P-521"; + break; + case "Ed25519": + case "EdDSA": + candidate = jwk2.crv === "Ed25519"; + break; + } + } + return candidate; + }); + const { 0: jwk, length } = candidates; + if (length === 0) { + throw new JWKSNoMatchingKey(); + } + if (length !== 1) { + const error50 = new JWKSMultipleMatchingKeys(); + const _cached = this.#cached; + error50[Symbol.asyncIterator] = async function* () { + for (const jwk2 of candidates) { + try { + yield await importWithAlgCache(_cached, jwk2, alg2); + } catch { + } + } + }; + throw error50; + } + return importWithAlgCache(this.#cached, jwk, alg2); + } + }; + } +}); + +// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwks/remote.js +function isCloudflareWorkers() { + return typeof WebSocketPair !== "undefined" || typeof navigator !== "undefined" && navigator.userAgent === "Cloudflare-Workers" || typeof EdgeRuntime !== "undefined" && EdgeRuntime === "vercel"; +} +async function fetchJwks(url2, headers, signal, fetchImpl = fetch) { + const response = await fetchImpl(url2, { + method: "GET", + signal, + redirect: "manual", + headers + }).catch((err) => { + if (err.name === "TimeoutError") { + throw new JWKSTimeout(); + } + throw err; + }); + if (response.status !== 200) { + throw new JOSEError("Expected 200 OK from the JSON Web Key Set HTTP response"); + } + try { + return await response.json(); + } catch { + throw new JOSEError("Failed to parse the JSON Web Key Set HTTP response as JSON"); + } +} +function isFreshJwksCache(input, cacheMaxAge) { + if (typeof input !== "object" || input === null) { + return false; + } + if (!("uat" in input) || typeof input.uat !== "number" || Date.now() - input.uat >= cacheMaxAge) { + return false; + } + if (!("jwks" in input) || !isObject(input.jwks) || !Array.isArray(input.jwks.keys) || !Array.prototype.every.call(input.jwks.keys, isObject)) { + return false; + } + return true; +} +function createRemoteJWKSet(url2, options) { + const set2 = new RemoteJWKSet(url2, options); + const remoteJWKSet = async (protectedHeader, token) => set2.getKey(protectedHeader, token); + Object.defineProperties(remoteJWKSet, { + coolingDown: { + get: () => set2.coolingDown(), + enumerable: true, + configurable: false + }, + fresh: { + get: () => set2.fresh(), + enumerable: true, + configurable: false + }, + reload: { + value: () => set2.reload(), + enumerable: true, + configurable: false, + writable: false + }, + reloading: { + get: () => set2.pendingFetch(), + enumerable: true, + configurable: false + }, + jwks: { + value: () => set2.jwks(), + enumerable: true, + configurable: false, + writable: false + } + }); + return remoteJWKSet; +} +var USER_AGENT, customFetch, jwksCache, RemoteJWKSet; +var init_remote = __esm({ + "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwks/remote.js"() { + init_errors7(); + init_local(); + init_type_checks(); + if (typeof navigator === "undefined" || !navigator.userAgent?.startsWith?.("Mozilla/5.0 ")) { + const NAME = "jose"; + const VERSION = "v6.2.2"; + USER_AGENT = `${NAME}/${VERSION}`; + } + customFetch = /* @__PURE__ */ Symbol(); + jwksCache = /* @__PURE__ */ Symbol(); + RemoteJWKSet = class { + #url; + #timeoutDuration; + #cooldownDuration; + #cacheMaxAge; + #jwksTimestamp; + #pendingFetch; + #headers; + #customFetch; + #local; + #cache; + constructor(url2, options) { + if (!(url2 instanceof URL)) { + throw new TypeError("url must be an instance of URL"); + } + this.#url = new URL(url2.href); + this.#timeoutDuration = typeof options?.timeoutDuration === "number" ? options?.timeoutDuration : 5e3; + this.#cooldownDuration = typeof options?.cooldownDuration === "number" ? options?.cooldownDuration : 3e4; + this.#cacheMaxAge = typeof options?.cacheMaxAge === "number" ? options?.cacheMaxAge : 6e5; + this.#headers = new Headers(options?.headers); + if (USER_AGENT && !this.#headers.has("User-Agent")) { + this.#headers.set("User-Agent", USER_AGENT); + } + if (!this.#headers.has("accept")) { + this.#headers.set("accept", "application/json"); + this.#headers.append("accept", "application/jwk-set+json"); + } + this.#customFetch = options?.[customFetch]; + if (options?.[jwksCache] !== void 0) { + this.#cache = options?.[jwksCache]; + if (isFreshJwksCache(options?.[jwksCache], this.#cacheMaxAge)) { + this.#jwksTimestamp = this.#cache.uat; + this.#local = createLocalJWKSet(this.#cache.jwks); + } + } + } + pendingFetch() { + return !!this.#pendingFetch; + } + coolingDown() { + return typeof this.#jwksTimestamp === "number" ? Date.now() < this.#jwksTimestamp + this.#cooldownDuration : false; + } + fresh() { + return typeof this.#jwksTimestamp === "number" ? Date.now() < this.#jwksTimestamp + this.#cacheMaxAge : false; + } + jwks() { + return this.#local?.jwks(); + } + async getKey(protectedHeader, token) { + if (!this.#local || !this.fresh()) { + await this.reload(); + } + try { + return await this.#local(protectedHeader, token); + } catch (err) { + if (err instanceof JWKSNoMatchingKey) { + if (this.coolingDown() === false) { + await this.reload(); + return this.#local(protectedHeader, token); + } + } + throw err; + } + } + async reload() { + if (this.#pendingFetch && isCloudflareWorkers()) { + this.#pendingFetch = void 0; + } + this.#pendingFetch ||= fetchJwks(this.#url.href, this.#headers, AbortSignal.timeout(this.#timeoutDuration), this.#customFetch).then((json3) => { + this.#local = createLocalJWKSet(json3); + if (this.#cache) { + this.#cache.uat = Date.now(); + this.#cache.jwks = json3; + } + this.#jwksTimestamp = Date.now(); + this.#pendingFetch = void 0; + }).catch((err) => { + this.#pendingFetch = void 0; + throw err; + }); + await this.#pendingFetch; + } + }; + } +}); + +// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/util/decode_protected_header.js +function decodeProtectedHeader(token) { + let protectedB64u; + if (typeof token === "string") { + const parts = token.split("."); + if (parts.length === 3 || parts.length === 5) { + ; + [protectedB64u] = parts; + } + } else if (typeof token === "object" && token) { + if ("protected" in token) { + protectedB64u = token.protected; + } else { + throw new TypeError("Token does not contain a Protected Header"); + } + } + try { + if (typeof protectedB64u !== "string" || !protectedB64u) { + throw new Error(); + } + const result = JSON.parse(decoder.decode(decode2(protectedB64u))); + if (!isObject(result)) { + throw new Error(); + } + return result; + } catch { + throw new TypeError("Invalid Token or Protected Header formatting"); + } +} +var init_decode_protected_header = __esm({ + "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/util/decode_protected_header.js"() { + init_base64url(); + init_buffer_utils(); + init_type_checks(); + } +}); + +// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/util/decode_jwt.js +function decodeJwt(jwt2) { + if (typeof jwt2 !== "string") + throw new JWTInvalid("JWTs must use Compact JWS serialization, JWT must be a string"); + const { 1: payload2, length } = jwt2.split("."); + if (length === 5) + throw new JWTInvalid("Only JWTs using Compact JWS serialization can be decoded"); + if (length !== 3) + throw new JWTInvalid("Invalid JWT"); + if (!payload2) + throw new JWTInvalid("JWTs must contain a payload"); + let decoded; + try { + decoded = decode2(payload2); + } catch { + throw new JWTInvalid("Failed to base64url decode the payload"); + } + let result; + try { + result = JSON.parse(decoder.decode(decoded)); + } catch { + throw new JWTInvalid("Failed to parse the decoded payload as JSON"); + } + if (!isObject(result)) + throw new JWTInvalid("Invalid JWT Claims Set"); + return result; +} +var init_decode_jwt = __esm({ + "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/util/decode_jwt.js"() { + init_base64url(); + init_buffer_utils(); + init_type_checks(); + init_errors7(); + } +}); + +// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/index.js +var init_webapi = __esm({ + "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/index.js"() { + init_verify3(); + init_decrypt3(); + init_sign3(); + init_encrypt3(); + init_thumbprint(); + init_remote(); + init_import(); + init_decode_protected_header(); + init_decode_jwt(); + init_base64url(); + } +}); + +// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/crypto/jwt.mjs +async function signJWT(payload2, secret, expiresIn = 3600) { + return await new SignJWT(payload2).setProtectedHeader({ alg: "HS256" }).setIssuedAt().setExpirationTime(Math.floor(Date.now() / 1e3) + expiresIn).sign(new TextEncoder().encode(secret)); +} +async function verifyJWT(token, secret) { + try { + return (await jwtVerify(token, new TextEncoder().encode(secret))).payload; + } catch { + return null; + } +} +async function symmetricEncodeJWT(payload2, secret, salt, expiresIn = 3600) { + const encryptionSecret = hkdf(sha2562, new TextEncoder().encode(secret), new TextEncoder().encode(salt), info, 64); + const thumbprint = await calculateJwkThumbprint({ + kty: "oct", + k: base64url_exports.encode(encryptionSecret) + }, "sha256"); + return await new EncryptJWT(payload2).setProtectedHeader({ + alg, + enc, + kid: thumbprint + }).setIssuedAt().setExpirationTime(now() + expiresIn).setJti(crypto.randomUUID()).encrypt(encryptionSecret); +} +async function symmetricDecodeJWT(token, secret, salt) { + if (!token) return null; + try { + const { payload: payload2 } = await jwtDecrypt(token, async ({ kid }) => { + const encryptionSecret = hkdf(sha2562, new TextEncoder().encode(secret), new TextEncoder().encode(salt), info, 64); + if (kid === void 0) return encryptionSecret; + if (kid === await calculateJwkThumbprint({ + kty: "oct", + k: base64url_exports.encode(encryptionSecret) + }, "sha256")) return encryptionSecret; + throw new Error("no matching decryption secret"); + }, { + clockTolerance: 15, + keyManagementAlgorithms: [alg], + contentEncryptionAlgorithms: [enc, "A256GCM"] + }); + return payload2; + } catch { + return null; + } +} +var info, now, alg, enc; +var init_jwt = __esm({ + "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/crypto/jwt.mjs"() { + init_hkdf(); + init_sha2(); + init_webapi(); + info = new Uint8Array([ + 66, + 101, + 116, + 116, + 101, + 114, + 65, + 117, + 116, + 104, + 46, + 106, + 115, + 32, + 71, + 101, + 110, + 101, + 114, + 97, + 116, + 101, + 100, + 32, + 69, + 110, + 99, + 114, + 121, + 112, + 116, + 105, + 111, + 110, + 32, + 75, + 101, + 121 + ]); + now = () => Date.now() / 1e3 | 0; + alg = "dir"; + enc = "A256CBC-HS512"; + } +}); + +// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/utils/error-codes.mjs +function defineErrorCodes(codes) { + return codes; +} +var init_error_codes = __esm({ + "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/utils/error-codes.mjs"() { + } +}); + +// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/utils/db.mjs +function filterOutputFields(data2, additionalFields) { + if (!data2 || !additionalFields) return data2; + const returnFiltered = Object.entries(additionalFields).filter(([, { returned }]) => returned === false).map(([key]) => key); + return Object.entries(structuredClone(data2)).filter(([key]) => !returnFiltered.includes(key)).reduce((acc, [key, value]) => ({ + ...acc, + [key]: value + }), {}); +} +var init_db2 = __esm({ + "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/utils/db.mjs"() { + } +}); + +// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/utils/deprecate.mjs +function deprecate(fn, message2, logger4) { + let warned = false; + return function(...args) { + if (!warned) { + (logger4?.warn ?? console.warn)(`[Deprecation] ${message2}`); + warned = true; + } + return fn.apply(this, args); + }; +} +var init_deprecate = __esm({ + "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/utils/deprecate.mjs"() { + } +}); + +// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/utils/id.mjs +var generateId; +var init_id = __esm({ + "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/utils/id.mjs"() { + init_random(); + generateId = (size2) => { + return createRandomStringGenerator("a-z", "A-Z", "0-9")(size2 || 32); + }; + } +}); + +// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/core.js +// @__NO_SIDE_EFFECTS__ +function $constructor(name, initializer3, params) { + function init2(inst, def) { + if (!inst._zod) { + Object.defineProperty(inst, "_zod", { + value: { + def, + constr: _, + traits: /* @__PURE__ */ new Set() + }, + enumerable: false + }); + } + if (inst._zod.traits.has(name)) { + return; + } + inst._zod.traits.add(name); + initializer3(inst, def); + const proto = _.prototype; + const keys = Object.keys(proto); + for (let i5 = 0; i5 < keys.length; i5++) { + const k5 = keys[i5]; + if (!(k5 in inst)) { + inst[k5] = proto[k5].bind(inst); + } + } + } + const Parent = params?.Parent ?? Object; + class Definition extends Parent { + } + Object.defineProperty(Definition, "name", { value: name }); + function _(def) { + var _a6; + const inst = params?.Parent ? new Definition() : this; + init2(inst, def); + (_a6 = inst._zod).deferred ?? (_a6.deferred = []); + for (const fn of inst._zod.deferred) { + fn(); + } + return inst; + } + Object.defineProperty(_, "init", { value: init2 }); + Object.defineProperty(_, Symbol.hasInstance, { + value: (inst) => { + if (params?.Parent && inst instanceof params.Parent) + return true; + return inst?._zod?.traits?.has(name); + } + }); + Object.defineProperty(_, "name", { value: name }); + return _; +} +function config(newConfig) { + if (newConfig) + Object.assign(globalConfig, newConfig); + return globalConfig; +} +var NEVER2, $brand, $ZodAsyncError, $ZodEncodeError, globalConfig; +var init_core = __esm({ + "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/core.js"() { + NEVER2 = Object.freeze({ + status: "aborted" + }); + $brand = /* @__PURE__ */ Symbol("zod_brand"); + $ZodAsyncError = class extends Error { + constructor() { + super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`); + } + }; + $ZodEncodeError = class extends Error { + constructor(name) { + super(`Encountered unidirectional transform during encode: ${name}`); + this.name = "ZodEncodeError"; + } + }; + globalConfig = {}; + } +}); + +// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/util.js +var util_exports = {}; +__export(util_exports, { + BIGINT_FORMAT_RANGES: () => BIGINT_FORMAT_RANGES, + Class: () => Class, + NUMBER_FORMAT_RANGES: () => NUMBER_FORMAT_RANGES, + aborted: () => aborted, + allowsEval: () => allowsEval, + assert: () => assert, + assertEqual: () => assertEqual, + assertIs: () => assertIs, + assertNever: () => assertNever, + assertNotEqual: () => assertNotEqual, + assignProp: () => assignProp, + base64ToUint8Array: () => base64ToUint8Array, + base64urlToUint8Array: () => base64urlToUint8Array, + cached: () => cached3, + captureStackTrace: () => captureStackTrace, + cleanEnum: () => cleanEnum, + cleanRegex: () => cleanRegex, + clone: () => clone2, + cloneDef: () => cloneDef, + createTransparentProxy: () => createTransparentProxy, + defineLazy: () => defineLazy, + esc: () => esc, + escapeRegex: () => escapeRegex, + extend: () => extend, + finalizeIssue: () => finalizeIssue, + floatSafeRemainder: () => floatSafeRemainder2, + getElementAtPath: () => getElementAtPath, + getEnumValues: () => getEnumValues, + getLengthableOrigin: () => getLengthableOrigin, + getParsedType: () => getParsedType2, + getSizableOrigin: () => getSizableOrigin, + hexToUint8Array: () => hexToUint8Array, + isObject: () => isObject2, + isPlainObject: () => isPlainObject5, + issue: () => issue, + joinValues: () => joinValues, + jsonStringifyReplacer: () => jsonStringifyReplacer, + merge: () => merge, + mergeDefs: () => mergeDefs, + normalizeParams: () => normalizeParams, + nullish: () => nullish, + numKeys: () => numKeys, + objectClone: () => objectClone, + omit: () => omit, + optionalKeys: () => optionalKeys, + parsedType: () => parsedType, + partial: () => partial, + pick: () => pick, + prefixIssues: () => prefixIssues, + primitiveTypes: () => primitiveTypes, + promiseAllObject: () => promiseAllObject, + propertyKeyTypes: () => propertyKeyTypes, + randomString: () => randomString, + required: () => required, + safeExtend: () => safeExtend, + shallowClone: () => shallowClone, + slugify: () => slugify2, + stringifyPrimitive: () => stringifyPrimitive, + uint8ArrayToBase64: () => uint8ArrayToBase64, + uint8ArrayToBase64url: () => uint8ArrayToBase64url, + uint8ArrayToHex: () => uint8ArrayToHex, + unwrapMessage: () => unwrapMessage +}); +function assertEqual(val) { + return val; +} +function assertNotEqual(val) { + return val; +} +function assertIs(_arg) { +} +function assertNever(_x) { + throw new Error("Unexpected value in exhaustive check"); +} +function assert(_) { +} +function getEnumValues(entries2) { + const numericValues = Object.values(entries2).filter((v5) => typeof v5 === "number"); + const values2 = Object.entries(entries2).filter(([k5, _]) => numericValues.indexOf(+k5) === -1).map(([_, v5]) => v5); + return values2; +} +function joinValues(array2, separator = "|") { + return array2.map((val) => stringifyPrimitive(val)).join(separator); +} +function jsonStringifyReplacer(_, value) { + if (typeof value === "bigint") + return value.toString(); + return value; +} +function cached3(getter) { + const set2 = false; + return { + get value() { + if (!set2) { + const value = getter(); + Object.defineProperty(this, "value", { value }); + return value; + } + throw new Error("cached value already set"); + } + }; +} +function nullish(input) { + return input === null || input === void 0; +} +function cleanRegex(source) { + const start = source.startsWith("^") ? 1 : 0; + const end = source.endsWith("$") ? source.length - 1 : source.length; + return source.slice(start, end); +} +function floatSafeRemainder2(val, step) { + const valDecCount = (val.toString().split(".")[1] || "").length; + const stepString = step.toString(); + let stepDecCount = (stepString.split(".")[1] || "").length; + if (stepDecCount === 0 && /\d?e-\d?/.test(stepString)) { + const match = stepString.match(/\d?e-(\d?)/); + if (match?.[1]) { + stepDecCount = Number.parseInt(match[1]); + } + } + const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; + const valInt = Number.parseInt(val.toFixed(decCount).replace(".", "")); + const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", "")); + return valInt % stepInt / 10 ** decCount; +} +function defineLazy(object2, key, getter) { + let value = void 0; + Object.defineProperty(object2, key, { + get() { + if (value === EVALUATING) { + return void 0; + } + if (value === void 0) { + value = EVALUATING; + value = getter(); + } + return value; + }, + set(v5) { + Object.defineProperty(object2, key, { + value: v5 + // configurable: true, + }); + }, + configurable: true + }); +} +function objectClone(obj) { + return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj)); +} +function assignProp(target, prop, value) { + Object.defineProperty(target, prop, { + value, + writable: true, + enumerable: true, + configurable: true + }); +} +function mergeDefs(...defs) { + const mergedDescriptors = {}; + for (const def of defs) { + const descriptors = Object.getOwnPropertyDescriptors(def); + Object.assign(mergedDescriptors, descriptors); + } + return Object.defineProperties({}, mergedDescriptors); +} +function cloneDef(schema2) { + return mergeDefs(schema2._zod.def); +} +function getElementAtPath(obj, path53) { + if (!path53) + return obj; + return path53.reduce((acc, key) => acc?.[key], obj); +} +function promiseAllObject(promisesObj) { + const keys = Object.keys(promisesObj); + const promises = keys.map((key) => promisesObj[key]); + return Promise.all(promises).then((results) => { + const resolvedObj = {}; + for (let i5 = 0; i5 < keys.length; i5++) { + resolvedObj[keys[i5]] = results[i5]; + } + return resolvedObj; + }); +} +function randomString(length = 10) { + const chars = "abcdefghijklmnopqrstuvwxyz"; + let str = ""; + for (let i5 = 0; i5 < length; i5++) { + str += chars[Math.floor(Math.random() * chars.length)]; + } + return str; +} +function esc(str) { + return JSON.stringify(str); +} +function slugify2(input) { + return input.toLowerCase().trim().replace(/[^\w\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, ""); +} +function isObject2(data2) { + return typeof data2 === "object" && data2 !== null && !Array.isArray(data2); +} +function isPlainObject5(o5) { + if (isObject2(o5) === false) + return false; + const ctor = o5.constructor; + if (ctor === void 0) + return true; + if (typeof ctor !== "function") + return true; + const prot = ctor.prototype; + if (isObject2(prot) === false) + return false; + if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) { + return false; + } + return true; +} +function shallowClone(o5) { + if (isPlainObject5(o5)) + return { ...o5 }; + if (Array.isArray(o5)) + return [...o5]; + return o5; +} +function numKeys(data2) { + let keyCount = 0; + for (const key in data2) { + if (Object.prototype.hasOwnProperty.call(data2, key)) { + keyCount++; + } + } + return keyCount; +} +function escapeRegex(str) { + return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +} +function clone2(inst, def, params) { + const cl = new inst._zod.constr(def ?? inst._zod.def); + if (!def || params?.parent) + cl._zod.parent = inst; + return cl; +} +function normalizeParams(_params) { + const params = _params; + if (!params) + return {}; + if (typeof params === "string") + return { error: () => params }; + if (params?.message !== void 0) { + if (params?.error !== void 0) + throw new Error("Cannot specify both `message` and `error` params"); + params.error = params.message; + } + delete params.message; + if (typeof params.error === "string") + return { ...params, error: () => params.error }; + return params; +} +function createTransparentProxy(getter) { + let target; + return new Proxy({}, { + get(_, prop, receiver) { + target ?? (target = getter()); + return Reflect.get(target, prop, receiver); + }, + set(_, prop, value, receiver) { + target ?? (target = getter()); + return Reflect.set(target, prop, value, receiver); + }, + has(_, prop) { + target ?? (target = getter()); + return Reflect.has(target, prop); + }, + deleteProperty(_, prop) { + target ?? (target = getter()); + return Reflect.deleteProperty(target, prop); + }, + ownKeys(_) { + target ?? (target = getter()); + return Reflect.ownKeys(target); + }, + getOwnPropertyDescriptor(_, prop) { + target ?? (target = getter()); + return Reflect.getOwnPropertyDescriptor(target, prop); + }, + defineProperty(_, prop, descriptor) { + target ?? (target = getter()); + return Reflect.defineProperty(target, prop, descriptor); + } + }); +} +function stringifyPrimitive(value) { + if (typeof value === "bigint") + return value.toString() + "n"; + if (typeof value === "string") + return `"${value}"`; + return `${value}`; +} +function optionalKeys(shape) { + return Object.keys(shape).filter((k5) => { + return shape[k5]._zod.optin === "optional" && shape[k5]._zod.optout === "optional"; + }); +} +function pick(schema2, mask) { + const currDef = schema2._zod.def; + const checks = currDef.checks; + const hasChecks = checks && checks.length > 0; + if (hasChecks) { + throw new Error(".pick() cannot be used on object schemas containing refinements"); + } + const def = mergeDefs(schema2._zod.def, { + get shape() { + const newShape = {}; + for (const key in mask) { + if (!(key in currDef.shape)) { + throw new Error(`Unrecognized key: "${key}"`); + } + if (!mask[key]) + continue; + newShape[key] = currDef.shape[key]; + } + assignProp(this, "shape", newShape); + return newShape; + }, + checks: [] + }); + return clone2(schema2, def); +} +function omit(schema2, mask) { + const currDef = schema2._zod.def; + const checks = currDef.checks; + const hasChecks = checks && checks.length > 0; + if (hasChecks) { + throw new Error(".omit() cannot be used on object schemas containing refinements"); + } + const def = mergeDefs(schema2._zod.def, { + get shape() { + const newShape = { ...schema2._zod.def.shape }; + for (const key in mask) { + if (!(key in currDef.shape)) { + throw new Error(`Unrecognized key: "${key}"`); + } + if (!mask[key]) + continue; + delete newShape[key]; + } + assignProp(this, "shape", newShape); + return newShape; + }, + checks: [] + }); + return clone2(schema2, def); +} +function extend(schema2, shape) { + if (!isPlainObject5(shape)) { + throw new Error("Invalid input to extend: expected a plain object"); + } + const checks = schema2._zod.def.checks; + const hasChecks = checks && checks.length > 0; + if (hasChecks) { + const existingShape = schema2._zod.def.shape; + for (const key in shape) { + if (Object.getOwnPropertyDescriptor(existingShape, key) !== void 0) { + throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead."); + } + } + } + const def = mergeDefs(schema2._zod.def, { + get shape() { + const _shape = { ...schema2._zod.def.shape, ...shape }; + assignProp(this, "shape", _shape); + return _shape; + } + }); + return clone2(schema2, def); +} +function safeExtend(schema2, shape) { + if (!isPlainObject5(shape)) { + throw new Error("Invalid input to safeExtend: expected a plain object"); + } + const def = mergeDefs(schema2._zod.def, { + get shape() { + const _shape = { ...schema2._zod.def.shape, ...shape }; + assignProp(this, "shape", _shape); + return _shape; + } + }); + return clone2(schema2, def); +} +function merge(a5, b6) { + const def = mergeDefs(a5._zod.def, { + get shape() { + const _shape = { ...a5._zod.def.shape, ...b6._zod.def.shape }; + assignProp(this, "shape", _shape); + return _shape; + }, + get catchall() { + return b6._zod.def.catchall; + }, + checks: [] + // delete existing checks + }); + return clone2(a5, def); +} +function partial(Class2, schema2, mask) { + const currDef = schema2._zod.def; + const checks = currDef.checks; + const hasChecks = checks && checks.length > 0; + if (hasChecks) { + throw new Error(".partial() cannot be used on object schemas containing refinements"); + } + const def = mergeDefs(schema2._zod.def, { + get shape() { + const oldShape = schema2._zod.def.shape; + const shape = { ...oldShape }; + if (mask) { + for (const key in mask) { + if (!(key in oldShape)) { + throw new Error(`Unrecognized key: "${key}"`); + } + if (!mask[key]) + continue; + shape[key] = Class2 ? new Class2({ + type: "optional", + innerType: oldShape[key] + }) : oldShape[key]; + } + } else { + for (const key in oldShape) { + shape[key] = Class2 ? new Class2({ + type: "optional", + innerType: oldShape[key] + }) : oldShape[key]; + } + } + assignProp(this, "shape", shape); + return shape; + }, + checks: [] + }); + return clone2(schema2, def); +} +function required(Class2, schema2, mask) { + const def = mergeDefs(schema2._zod.def, { + get shape() { + const oldShape = schema2._zod.def.shape; + const shape = { ...oldShape }; + if (mask) { + for (const key in mask) { + if (!(key in shape)) { + throw new Error(`Unrecognized key: "${key}"`); + } + if (!mask[key]) + continue; + shape[key] = new Class2({ + type: "nonoptional", + innerType: oldShape[key] + }); + } + } else { + for (const key in oldShape) { + shape[key] = new Class2({ + type: "nonoptional", + innerType: oldShape[key] + }); + } + } + assignProp(this, "shape", shape); + return shape; + } + }); + return clone2(schema2, def); +} +function aborted(x5, startIndex = 0) { + if (x5.aborted === true) + return true; + for (let i5 = startIndex; i5 < x5.issues.length; i5++) { + if (x5.issues[i5]?.continue !== true) { + return true; + } + } + return false; +} +function prefixIssues(path53, issues2) { + return issues2.map((iss) => { + var _a6; + (_a6 = iss).path ?? (_a6.path = []); + iss.path.unshift(path53); + return iss; + }); +} +function unwrapMessage(message2) { + return typeof message2 === "string" ? message2 : message2?.message; +} +function finalizeIssue(iss, ctx, config3) { + const full = { ...iss, path: iss.path ?? [] }; + if (!iss.message) { + const message2 = unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config3.customError?.(iss)) ?? unwrapMessage(config3.localeError?.(iss)) ?? "Invalid input"; + full.message = message2; + } + delete full.inst; + delete full.continue; + if (!ctx?.reportInput) { + delete full.input; + } + return full; +} +function getSizableOrigin(input) { + if (input instanceof Set) + return "set"; + if (input instanceof Map) + return "map"; + if (input instanceof File) + return "file"; + return "unknown"; +} +function getLengthableOrigin(input) { + if (Array.isArray(input)) + return "array"; + if (typeof input === "string") + return "string"; + return "unknown"; +} +function parsedType(data2) { + const t5 = typeof data2; + switch (t5) { + case "number": { + return Number.isNaN(data2) ? "nan" : "number"; + } + case "object": { + if (data2 === null) { + return "null"; + } + if (Array.isArray(data2)) { + return "array"; + } + const obj = data2; + if (obj && Object.getPrototypeOf(obj) !== Object.prototype && "constructor" in obj && obj.constructor) { + return obj.constructor.name; + } + } + } + return t5; +} +function issue(...args) { + const [iss, input, inst] = args; + if (typeof iss === "string") { + return { + message: iss, + code: "custom", + input, + inst + }; + } + return { ...iss }; +} +function cleanEnum(obj) { + return Object.entries(obj).filter(([k5, _]) => { + return Number.isNaN(Number.parseInt(k5, 10)); + }).map((el) => el[1]); +} +function base64ToUint8Array(base644) { + const binaryString = atob(base644); + const bytes = new Uint8Array(binaryString.length); + for (let i5 = 0; i5 < binaryString.length; i5++) { + bytes[i5] = binaryString.charCodeAt(i5); + } + return bytes; +} +function uint8ArrayToBase64(bytes) { + let binaryString = ""; + for (let i5 = 0; i5 < bytes.length; i5++) { + binaryString += String.fromCharCode(bytes[i5]); + } + return btoa(binaryString); +} +function base64urlToUint8Array(base64url3) { + const base644 = base64url3.replace(/-/g, "+").replace(/_/g, "/"); + const padding = "=".repeat((4 - base644.length % 4) % 4); + return base64ToUint8Array(base644 + padding); +} +function uint8ArrayToBase64url(bytes) { + return uint8ArrayToBase64(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, ""); +} +function hexToUint8Array(hex4) { + const cleanHex = hex4.replace(/^0x/, ""); + if (cleanHex.length % 2 !== 0) { + throw new Error("Invalid hex string length"); + } + const bytes = new Uint8Array(cleanHex.length / 2); + for (let i5 = 0; i5 < cleanHex.length; i5 += 2) { + bytes[i5 / 2] = Number.parseInt(cleanHex.slice(i5, i5 + 2), 16); + } + return bytes; +} +function uint8ArrayToHex(bytes) { + return Array.from(bytes).map((b6) => b6.toString(16).padStart(2, "0")).join(""); +} +var EVALUATING, captureStackTrace, allowsEval, getParsedType2, propertyKeyTypes, primitiveTypes, NUMBER_FORMAT_RANGES, BIGINT_FORMAT_RANGES, Class; +var init_util = __esm({ + "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/util.js"() { + EVALUATING = /* @__PURE__ */ Symbol("evaluating"); + captureStackTrace = "captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => { + }; + allowsEval = cached3(() => { + if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) { + return false; + } + try { + const F2 = Function; + new F2(""); + return true; + } catch (_) { + return false; + } + }); + getParsedType2 = (data2) => { + const t5 = typeof data2; + switch (t5) { + case "undefined": + return "undefined"; + case "string": + return "string"; + case "number": + return Number.isNaN(data2) ? "nan" : "number"; + case "boolean": + return "boolean"; + case "function": + return "function"; + case "bigint": + return "bigint"; + case "symbol": + return "symbol"; + case "object": + if (Array.isArray(data2)) { + return "array"; + } + if (data2 === null) { + return "null"; + } + if (data2.then && typeof data2.then === "function" && data2.catch && typeof data2.catch === "function") { + return "promise"; + } + if (typeof Map !== "undefined" && data2 instanceof Map) { + return "map"; + } + if (typeof Set !== "undefined" && data2 instanceof Set) { + return "set"; + } + if (typeof Date !== "undefined" && data2 instanceof Date) { + return "date"; + } + if (typeof File !== "undefined" && data2 instanceof File) { + return "file"; + } + return "object"; + default: + throw new Error(`Unknown data type: ${t5}`); + } + }; + propertyKeyTypes = /* @__PURE__ */ new Set(["string", "number", "symbol"]); + primitiveTypes = /* @__PURE__ */ new Set(["string", "number", "bigint", "boolean", "symbol", "undefined"]); + NUMBER_FORMAT_RANGES = { + safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER], + int32: [-2147483648, 2147483647], + uint32: [0, 4294967295], + float32: [-34028234663852886e22, 34028234663852886e22], + float64: [-Number.MAX_VALUE, Number.MAX_VALUE] + }; + BIGINT_FORMAT_RANGES = { + int64: [/* @__PURE__ */ BigInt("-9223372036854775808"), /* @__PURE__ */ BigInt("9223372036854775807")], + uint64: [/* @__PURE__ */ BigInt(0), /* @__PURE__ */ BigInt("18446744073709551615")] + }; + Class = class { + constructor(..._args) { + } + }; + } +}); + +// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/errors.js +function flattenError(error50, mapper = (issue2) => issue2.message) { + const fieldErrors = {}; + const formErrors = []; + for (const sub of error50.issues) { + if (sub.path.length > 0) { + fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || []; + fieldErrors[sub.path[0]].push(mapper(sub)); + } else { + formErrors.push(mapper(sub)); + } + } + return { formErrors, fieldErrors }; +} +function formatError(error50, mapper = (issue2) => issue2.message) { + const fieldErrors = { _errors: [] }; + const processError = (error51) => { + for (const issue2 of error51.issues) { + if (issue2.code === "invalid_union" && issue2.errors.length) { + issue2.errors.map((issues2) => processError({ issues: issues2 })); + } else if (issue2.code === "invalid_key") { + processError({ issues: issue2.issues }); + } else if (issue2.code === "invalid_element") { + processError({ issues: issue2.issues }); + } else if (issue2.path.length === 0) { + fieldErrors._errors.push(mapper(issue2)); + } else { + let curr = fieldErrors; + let i5 = 0; + while (i5 < issue2.path.length) { + const el = issue2.path[i5]; + const terminal = i5 === issue2.path.length - 1; + if (!terminal) { + curr[el] = curr[el] || { _errors: [] }; + } else { + curr[el] = curr[el] || { _errors: [] }; + curr[el]._errors.push(mapper(issue2)); + } + curr = curr[el]; + i5++; + } + } + } + }; + processError(error50); + return fieldErrors; +} +function treeifyError(error50, mapper = (issue2) => issue2.message) { + const result = { errors: [] }; + const processError = (error51, path53 = []) => { + var _a6, _b; + for (const issue2 of error51.issues) { + if (issue2.code === "invalid_union" && issue2.errors.length) { + issue2.errors.map((issues2) => processError({ issues: issues2 }, issue2.path)); + } else if (issue2.code === "invalid_key") { + processError({ issues: issue2.issues }, issue2.path); + } else if (issue2.code === "invalid_element") { + processError({ issues: issue2.issues }, issue2.path); + } else { + const fullpath = [...path53, ...issue2.path]; + if (fullpath.length === 0) { + result.errors.push(mapper(issue2)); + continue; + } + let curr = result; + let i5 = 0; + while (i5 < fullpath.length) { + const el = fullpath[i5]; + const terminal = i5 === fullpath.length - 1; + if (typeof el === "string") { + curr.properties ?? (curr.properties = {}); + (_a6 = curr.properties)[el] ?? (_a6[el] = { errors: [] }); + curr = curr.properties[el]; + } else { + curr.items ?? (curr.items = []); + (_b = curr.items)[el] ?? (_b[el] = { errors: [] }); + curr = curr.items[el]; + } + if (terminal) { + curr.errors.push(mapper(issue2)); + } + i5++; + } + } + } + }; + processError(error50); + return result; +} +function toDotPath(_path) { + const segs = []; + const path53 = _path.map((seg) => typeof seg === "object" ? seg.key : seg); + for (const seg of path53) { + if (typeof seg === "number") + segs.push(`[${seg}]`); + else if (typeof seg === "symbol") + segs.push(`[${JSON.stringify(String(seg))}]`); + else if (/[^\w$]/.test(seg)) + segs.push(`[${JSON.stringify(seg)}]`); + else { + if (segs.length) + segs.push("."); + segs.push(seg); + } + } + return segs.join(""); +} +function prettifyError(error50) { + const lines = []; + const issues2 = [...error50.issues].sort((a5, b6) => (a5.path ?? []).length - (b6.path ?? []).length); + for (const issue2 of issues2) { + lines.push(`\u2716 ${issue2.message}`); + if (issue2.path?.length) + lines.push(` \u2192 at ${toDotPath(issue2.path)}`); + } + return lines.join("\n"); +} +var initializer, $ZodError, $ZodRealError; +var init_errors8 = __esm({ + "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/errors.js"() { + init_core(); + init_util(); + initializer = (inst, def) => { + inst.name = "$ZodError"; + Object.defineProperty(inst, "_zod", { + value: inst._zod, + enumerable: false + }); + Object.defineProperty(inst, "issues", { + value: def, + enumerable: false + }); + inst.message = JSON.stringify(def, jsonStringifyReplacer, 2); + Object.defineProperty(inst, "toString", { + value: () => inst.message, + enumerable: false + }); + }; + $ZodError = $constructor("$ZodError", initializer); + $ZodRealError = $constructor("$ZodError", initializer, { Parent: Error }); + } +}); + +// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/parse.js +var _parse, parse2, _parseAsync, parseAsync, _safeParse, safeParse, _safeParseAsync, safeParseAsync, _encode, encode4, _decode, decode3, _encodeAsync, encodeAsync, _decodeAsync, decodeAsync, _safeEncode, safeEncode, _safeDecode, safeDecode, _safeEncodeAsync, safeEncodeAsync, _safeDecodeAsync, safeDecodeAsync; +var init_parse = __esm({ + "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/parse.js"() { + init_core(); + init_errors8(); + init_util(); + _parse = (_Err) => (schema2, value, _ctx, _params) => { + const ctx = _ctx ? Object.assign(_ctx, { async: false }) : { async: false }; + const result = schema2._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) { + throw new $ZodAsyncError(); + } + if (result.issues.length) { + const e5 = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); + captureStackTrace(e5, _params?.callee); + throw e5; + } + return result.value; + }; + parse2 = /* @__PURE__ */ _parse($ZodRealError); + _parseAsync = (_Err) => async (schema2, value, _ctx, params) => { + const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true }; + let result = schema2._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) + result = await result; + if (result.issues.length) { + const e5 = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); + captureStackTrace(e5, params?.callee); + throw e5; + } + return result.value; + }; + parseAsync = /* @__PURE__ */ _parseAsync($ZodRealError); + _safeParse = (_Err) => (schema2, value, _ctx) => { + const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; + const result = schema2._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) { + throw new $ZodAsyncError(); + } + return result.issues.length ? { + success: false, + error: new (_Err ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) + } : { success: true, data: result.value }; + }; + safeParse = /* @__PURE__ */ _safeParse($ZodRealError); + _safeParseAsync = (_Err) => async (schema2, value, _ctx) => { + const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true }; + let result = schema2._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) + result = await result; + return result.issues.length ? { + success: false, + error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) + } : { success: true, data: result.value }; + }; + safeParseAsync = /* @__PURE__ */ _safeParseAsync($ZodRealError); + _encode = (_Err) => (schema2, value, _ctx) => { + const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" }; + return _parse(_Err)(schema2, value, ctx); + }; + encode4 = /* @__PURE__ */ _encode($ZodRealError); + _decode = (_Err) => (schema2, value, _ctx) => { + return _parse(_Err)(schema2, value, _ctx); + }; + decode3 = /* @__PURE__ */ _decode($ZodRealError); + _encodeAsync = (_Err) => async (schema2, value, _ctx) => { + const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" }; + return _parseAsync(_Err)(schema2, value, ctx); + }; + encodeAsync = /* @__PURE__ */ _encodeAsync($ZodRealError); + _decodeAsync = (_Err) => async (schema2, value, _ctx) => { + return _parseAsync(_Err)(schema2, value, _ctx); + }; + decodeAsync = /* @__PURE__ */ _decodeAsync($ZodRealError); + _safeEncode = (_Err) => (schema2, value, _ctx) => { + const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" }; + return _safeParse(_Err)(schema2, value, ctx); + }; + safeEncode = /* @__PURE__ */ _safeEncode($ZodRealError); + _safeDecode = (_Err) => (schema2, value, _ctx) => { + return _safeParse(_Err)(schema2, value, _ctx); + }; + safeDecode = /* @__PURE__ */ _safeDecode($ZodRealError); + _safeEncodeAsync = (_Err) => async (schema2, value, _ctx) => { + const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" }; + return _safeParseAsync(_Err)(schema2, value, ctx); + }; + safeEncodeAsync = /* @__PURE__ */ _safeEncodeAsync($ZodRealError); + _safeDecodeAsync = (_Err) => async (schema2, value, _ctx) => { + return _safeParseAsync(_Err)(schema2, value, _ctx); + }; + safeDecodeAsync = /* @__PURE__ */ _safeDecodeAsync($ZodRealError); + } +}); + +// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/regexes.js +var regexes_exports = {}; +__export(regexes_exports, { + base64: () => base64, + base64url: () => base64url, + bigint: () => bigint2, + boolean: () => boolean2, + browserEmail: () => browserEmail, + cidrv4: () => cidrv4, + cidrv6: () => cidrv6, + cuid: () => cuid, + cuid2: () => cuid2, + date: () => date3, + datetime: () => datetime, + domain: () => domain, + duration: () => duration, + e164: () => e164, + email: () => email, + emoji: () => emoji, + extendedDuration: () => extendedDuration, + guid: () => guid, + hex: () => hex, + hostname: () => hostname, + html5Email: () => html5Email, + idnEmail: () => idnEmail, + integer: () => integer2, + ipv4: () => ipv4, + ipv6: () => ipv6, + ksuid: () => ksuid, + lowercase: () => lowercase, + mac: () => mac, + md5_base64: () => md5_base64, + md5_base64url: () => md5_base64url, + md5_hex: () => md5_hex, + nanoid: () => nanoid, + null: () => _null, + number: () => number, + rfc5322Email: () => rfc5322Email, + sha1_base64: () => sha1_base64, + sha1_base64url: () => sha1_base64url, + sha1_hex: () => sha1_hex, + sha256_base64: () => sha256_base64, + sha256_base64url: () => sha256_base64url, + sha256_hex: () => sha256_hex, + sha384_base64: () => sha384_base64, + sha384_base64url: () => sha384_base64url, + sha384_hex: () => sha384_hex, + sha512_base64: () => sha512_base64, + sha512_base64url: () => sha512_base64url, + sha512_hex: () => sha512_hex, + string: () => string, + time: () => time3, + ulid: () => ulid, + undefined: () => _undefined, + unicodeEmail: () => unicodeEmail, + uppercase: () => uppercase, + uuid: () => uuid2, + uuid4: () => uuid4, + uuid6: () => uuid6, + uuid7: () => uuid7, + xid: () => xid +}); +function emoji() { + return new RegExp(_emoji, "u"); +} +function timeSource(args) { + const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`; + const regex = typeof args.precision === "number" ? args.precision === -1 ? `${hhmm}` : args.precision === 0 ? `${hhmm}:[0-5]\\d` : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`; + return regex; +} +function time3(args) { + return new RegExp(`^${timeSource(args)}$`); +} +function datetime(args) { + const time5 = timeSource({ precision: args.precision }); + const opts = ["Z"]; + if (args.local) + opts.push(""); + if (args.offset) + opts.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`); + const timeRegex2 = `${time5}(?:${opts.join("|")})`; + return new RegExp(`^${dateSource}T(?:${timeRegex2})$`); +} +function fixedBase64(bodyLength, padding) { + return new RegExp(`^[A-Za-z0-9+/]{${bodyLength}}${padding}$`); +} +function fixedBase64url(length) { + return new RegExp(`^[A-Za-z0-9_-]{${length}}$`); +} +var cuid, cuid2, ulid, xid, ksuid, nanoid, duration, extendedDuration, guid, uuid2, uuid4, uuid6, uuid7, email, html5Email, rfc5322Email, unicodeEmail, idnEmail, browserEmail, _emoji, ipv4, ipv6, mac, cidrv4, cidrv6, base64, base64url, hostname, domain, e164, dateSource, date3, string, bigint2, integer2, number, boolean2, _null, _undefined, lowercase, uppercase, hex, md5_hex, md5_base64, md5_base64url, sha1_hex, sha1_base64, sha1_base64url, sha256_hex, sha256_base64, sha256_base64url, sha384_hex, sha384_base64, sha384_base64url, sha512_hex, sha512_base64, sha512_base64url; +var init_regexes = __esm({ + "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/regexes.js"() { + init_util(); + cuid = /^[cC][^\s-]{8,}$/; + cuid2 = /^[0-9a-z]+$/; + ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/; + xid = /^[0-9a-vA-V]{20}$/; + ksuid = /^[A-Za-z0-9]{27}$/; + nanoid = /^[a-zA-Z0-9_-]{21}$/; + duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/; + extendedDuration = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; + guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/; + uuid2 = (version3) => { + if (!version3) + return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/; + return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version3}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`); + }; + uuid4 = /* @__PURE__ */ uuid2(4); + uuid6 = /* @__PURE__ */ uuid2(6); + uuid7 = /* @__PURE__ */ uuid2(7); + email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/; + html5Email = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; + rfc5322Email = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; + unicodeEmail = /^[^\s@"]{1,64}@[^\s@]{1,255}$/u; + idnEmail = unicodeEmail; + browserEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; + _emoji = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; + ipv4 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/; + ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/; + mac = (delimiter) => { + const escapedDelim = escapeRegex(delimiter ?? ":"); + return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`); + }; + cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/; + cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; + base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/; + base64url = /^[A-Za-z0-9_-]*$/; + hostname = /^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/; + domain = /^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/; + e164 = /^\+[1-9]\d{6,14}$/; + dateSource = `(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`; + date3 = /* @__PURE__ */ new RegExp(`^${dateSource}$`); + string = (params) => { + const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`; + return new RegExp(`^${regex}$`); + }; + bigint2 = /^-?\d+n?$/; + integer2 = /^-?\d+$/; + number = /^-?\d+(?:\.\d+)?$/; + boolean2 = /^(?:true|false)$/i; + _null = /^null$/i; + _undefined = /^undefined$/i; + lowercase = /^[^A-Z]*$/; + uppercase = /^[^a-z]*$/; + hex = /^[0-9a-fA-F]*$/; + md5_hex = /^[0-9a-fA-F]{32}$/; + md5_base64 = /* @__PURE__ */ fixedBase64(22, "=="); + md5_base64url = /* @__PURE__ */ fixedBase64url(22); + sha1_hex = /^[0-9a-fA-F]{40}$/; + sha1_base64 = /* @__PURE__ */ fixedBase64(27, "="); + sha1_base64url = /* @__PURE__ */ fixedBase64url(27); + sha256_hex = /^[0-9a-fA-F]{64}$/; + sha256_base64 = /* @__PURE__ */ fixedBase64(43, "="); + sha256_base64url = /* @__PURE__ */ fixedBase64url(43); + sha384_hex = /^[0-9a-fA-F]{96}$/; + sha384_base64 = /* @__PURE__ */ fixedBase64(64, ""); + sha384_base64url = /* @__PURE__ */ fixedBase64url(64); + sha512_hex = /^[0-9a-fA-F]{128}$/; + sha512_base64 = /* @__PURE__ */ fixedBase64(86, "=="); + sha512_base64url = /* @__PURE__ */ fixedBase64url(86); + } +}); + +// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/checks.js +function handleCheckPropertyResult(result, payload2, property) { + if (result.issues.length) { + payload2.issues.push(...prefixIssues(property, result.issues)); + } +} +var $ZodCheck, numericOriginMap, $ZodCheckLessThan, $ZodCheckGreaterThan, $ZodCheckMultipleOf, $ZodCheckNumberFormat, $ZodCheckBigIntFormat, $ZodCheckMaxSize, $ZodCheckMinSize, $ZodCheckSizeEquals, $ZodCheckMaxLength, $ZodCheckMinLength, $ZodCheckLengthEquals, $ZodCheckStringFormat, $ZodCheckRegex, $ZodCheckLowerCase, $ZodCheckUpperCase, $ZodCheckIncludes, $ZodCheckStartsWith, $ZodCheckEndsWith, $ZodCheckProperty, $ZodCheckMimeType, $ZodCheckOverwrite; +var init_checks2 = __esm({ + "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/checks.js"() { + init_core(); + init_regexes(); + init_util(); + $ZodCheck = /* @__PURE__ */ $constructor("$ZodCheck", (inst, def) => { + var _a6; + inst._zod ?? (inst._zod = {}); + inst._zod.def = def; + (_a6 = inst._zod).onattach ?? (_a6.onattach = []); + }); + numericOriginMap = { + number: "number", + bigint: "bigint", + object: "date" + }; + $ZodCheckLessThan = /* @__PURE__ */ $constructor("$ZodCheckLessThan", (inst, def) => { + $ZodCheck.init(inst, def); + const origin = numericOriginMap[typeof def.value]; + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY; + if (def.value < curr) { + if (def.inclusive) + bag.maximum = def.value; + else + bag.exclusiveMaximum = def.value; + } + }); + inst._zod.check = (payload2) => { + if (def.inclusive ? payload2.value <= def.value : payload2.value < def.value) { + return; + } + payload2.issues.push({ + origin, + code: "too_big", + maximum: typeof def.value === "object" ? def.value.getTime() : def.value, + input: payload2.value, + inclusive: def.inclusive, + inst, + continue: !def.abort + }); + }; + }); + $ZodCheckGreaterThan = /* @__PURE__ */ $constructor("$ZodCheckGreaterThan", (inst, def) => { + $ZodCheck.init(inst, def); + const origin = numericOriginMap[typeof def.value]; + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY; + if (def.value > curr) { + if (def.inclusive) + bag.minimum = def.value; + else + bag.exclusiveMinimum = def.value; + } + }); + inst._zod.check = (payload2) => { + if (def.inclusive ? payload2.value >= def.value : payload2.value > def.value) { + return; + } + payload2.issues.push({ + origin, + code: "too_small", + minimum: typeof def.value === "object" ? def.value.getTime() : def.value, + input: payload2.value, + inclusive: def.inclusive, + inst, + continue: !def.abort + }); + }; + }); + $ZodCheckMultipleOf = /* @__PURE__ */ $constructor("$ZodCheckMultipleOf", (inst, def) => { + $ZodCheck.init(inst, def); + inst._zod.onattach.push((inst2) => { + var _a6; + (_a6 = inst2._zod.bag).multipleOf ?? (_a6.multipleOf = def.value); + }); + inst._zod.check = (payload2) => { + if (typeof payload2.value !== typeof def.value) + throw new Error("Cannot mix number and bigint in multiple_of check."); + const isMultiple = typeof payload2.value === "bigint" ? payload2.value % def.value === BigInt(0) : floatSafeRemainder2(payload2.value, def.value) === 0; + if (isMultiple) + return; + payload2.issues.push({ + origin: typeof payload2.value, + code: "not_multiple_of", + divisor: def.value, + input: payload2.value, + inst, + continue: !def.abort + }); + }; + }); + $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat", (inst, def) => { + $ZodCheck.init(inst, def); + def.format = def.format || "float64"; + const isInt = def.format?.includes("int"); + const origin = isInt ? "int" : "number"; + const [minimum, maximum] = NUMBER_FORMAT_RANGES[def.format]; + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + bag.format = def.format; + bag.minimum = minimum; + bag.maximum = maximum; + if (isInt) + bag.pattern = integer2; + }); + inst._zod.check = (payload2) => { + const input = payload2.value; + if (isInt) { + if (!Number.isInteger(input)) { + payload2.issues.push({ + expected: origin, + format: def.format, + code: "invalid_type", + continue: false, + input, + inst + }); + return; + } + if (!Number.isSafeInteger(input)) { + if (input > 0) { + payload2.issues.push({ + input, + code: "too_big", + maximum: Number.MAX_SAFE_INTEGER, + note: "Integers must be within the safe integer range.", + inst, + origin, + inclusive: true, + continue: !def.abort + }); + } else { + payload2.issues.push({ + input, + code: "too_small", + minimum: Number.MIN_SAFE_INTEGER, + note: "Integers must be within the safe integer range.", + inst, + origin, + inclusive: true, + continue: !def.abort + }); + } + return; + } + } + if (input < minimum) { + payload2.issues.push({ + origin: "number", + input, + code: "too_small", + minimum, + inclusive: true, + inst, + continue: !def.abort + }); + } + if (input > maximum) { + payload2.issues.push({ + origin: "number", + input, + code: "too_big", + maximum, + inclusive: true, + inst, + continue: !def.abort + }); + } + }; + }); + $ZodCheckBigIntFormat = /* @__PURE__ */ $constructor("$ZodCheckBigIntFormat", (inst, def) => { + $ZodCheck.init(inst, def); + const [minimum, maximum] = BIGINT_FORMAT_RANGES[def.format]; + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + bag.format = def.format; + bag.minimum = minimum; + bag.maximum = maximum; + }); + inst._zod.check = (payload2) => { + const input = payload2.value; + if (input < minimum) { + payload2.issues.push({ + origin: "bigint", + input, + code: "too_small", + minimum, + inclusive: true, + inst, + continue: !def.abort + }); + } + if (input > maximum) { + payload2.issues.push({ + origin: "bigint", + input, + code: "too_big", + maximum, + inclusive: true, + inst, + continue: !def.abort + }); + } + }; + }); + $ZodCheckMaxSize = /* @__PURE__ */ $constructor("$ZodCheckMaxSize", (inst, def) => { + var _a6; + $ZodCheck.init(inst, def); + (_a6 = inst._zod.def).when ?? (_a6.when = (payload2) => { + const val = payload2.value; + return !nullish(val) && val.size !== void 0; + }); + inst._zod.onattach.push((inst2) => { + const curr = inst2._zod.bag.maximum ?? Number.POSITIVE_INFINITY; + if (def.maximum < curr) + inst2._zod.bag.maximum = def.maximum; + }); + inst._zod.check = (payload2) => { + const input = payload2.value; + const size2 = input.size; + if (size2 <= def.maximum) + return; + payload2.issues.push({ + origin: getSizableOrigin(input), + code: "too_big", + maximum: def.maximum, + inclusive: true, + input, + inst, + continue: !def.abort + }); + }; + }); + $ZodCheckMinSize = /* @__PURE__ */ $constructor("$ZodCheckMinSize", (inst, def) => { + var _a6; + $ZodCheck.init(inst, def); + (_a6 = inst._zod.def).when ?? (_a6.when = (payload2) => { + const val = payload2.value; + return !nullish(val) && val.size !== void 0; + }); + inst._zod.onattach.push((inst2) => { + const curr = inst2._zod.bag.minimum ?? Number.NEGATIVE_INFINITY; + if (def.minimum > curr) + inst2._zod.bag.minimum = def.minimum; + }); + inst._zod.check = (payload2) => { + const input = payload2.value; + const size2 = input.size; + if (size2 >= def.minimum) + return; + payload2.issues.push({ + origin: getSizableOrigin(input), + code: "too_small", + minimum: def.minimum, + inclusive: true, + input, + inst, + continue: !def.abort + }); + }; + }); + $ZodCheckSizeEquals = /* @__PURE__ */ $constructor("$ZodCheckSizeEquals", (inst, def) => { + var _a6; + $ZodCheck.init(inst, def); + (_a6 = inst._zod.def).when ?? (_a6.when = (payload2) => { + const val = payload2.value; + return !nullish(val) && val.size !== void 0; + }); + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + bag.minimum = def.size; + bag.maximum = def.size; + bag.size = def.size; + }); + inst._zod.check = (payload2) => { + const input = payload2.value; + const size2 = input.size; + if (size2 === def.size) + return; + const tooBig = size2 > def.size; + payload2.issues.push({ + origin: getSizableOrigin(input), + ...tooBig ? { code: "too_big", maximum: def.size } : { code: "too_small", minimum: def.size }, + inclusive: true, + exact: true, + input: payload2.value, + inst, + continue: !def.abort + }); + }; + }); + $ZodCheckMaxLength = /* @__PURE__ */ $constructor("$ZodCheckMaxLength", (inst, def) => { + var _a6; + $ZodCheck.init(inst, def); + (_a6 = inst._zod.def).when ?? (_a6.when = (payload2) => { + const val = payload2.value; + return !nullish(val) && val.length !== void 0; + }); + inst._zod.onattach.push((inst2) => { + const curr = inst2._zod.bag.maximum ?? Number.POSITIVE_INFINITY; + if (def.maximum < curr) + inst2._zod.bag.maximum = def.maximum; + }); + inst._zod.check = (payload2) => { + const input = payload2.value; + const length = input.length; + if (length <= def.maximum) + return; + const origin = getLengthableOrigin(input); + payload2.issues.push({ + origin, + code: "too_big", + maximum: def.maximum, + inclusive: true, + input, + inst, + continue: !def.abort + }); + }; + }); + $ZodCheckMinLength = /* @__PURE__ */ $constructor("$ZodCheckMinLength", (inst, def) => { + var _a6; + $ZodCheck.init(inst, def); + (_a6 = inst._zod.def).when ?? (_a6.when = (payload2) => { + const val = payload2.value; + return !nullish(val) && val.length !== void 0; + }); + inst._zod.onattach.push((inst2) => { + const curr = inst2._zod.bag.minimum ?? Number.NEGATIVE_INFINITY; + if (def.minimum > curr) + inst2._zod.bag.minimum = def.minimum; + }); + inst._zod.check = (payload2) => { + const input = payload2.value; + const length = input.length; + if (length >= def.minimum) + return; + const origin = getLengthableOrigin(input); + payload2.issues.push({ + origin, + code: "too_small", + minimum: def.minimum, + inclusive: true, + input, + inst, + continue: !def.abort + }); + }; + }); + $ZodCheckLengthEquals = /* @__PURE__ */ $constructor("$ZodCheckLengthEquals", (inst, def) => { + var _a6; + $ZodCheck.init(inst, def); + (_a6 = inst._zod.def).when ?? (_a6.when = (payload2) => { + const val = payload2.value; + return !nullish(val) && val.length !== void 0; + }); + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + bag.minimum = def.length; + bag.maximum = def.length; + bag.length = def.length; + }); + inst._zod.check = (payload2) => { + const input = payload2.value; + const length = input.length; + if (length === def.length) + return; + const origin = getLengthableOrigin(input); + const tooBig = length > def.length; + payload2.issues.push({ + origin, + ...tooBig ? { code: "too_big", maximum: def.length } : { code: "too_small", minimum: def.length }, + inclusive: true, + exact: true, + input: payload2.value, + inst, + continue: !def.abort + }); + }; + }); + $ZodCheckStringFormat = /* @__PURE__ */ $constructor("$ZodCheckStringFormat", (inst, def) => { + var _a6, _b; + $ZodCheck.init(inst, def); + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + bag.format = def.format; + if (def.pattern) { + bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); + bag.patterns.add(def.pattern); + } + }); + if (def.pattern) + (_a6 = inst._zod).check ?? (_a6.check = (payload2) => { + def.pattern.lastIndex = 0; + if (def.pattern.test(payload2.value)) + return; + payload2.issues.push({ + origin: "string", + code: "invalid_format", + format: def.format, + input: payload2.value, + ...def.pattern ? { pattern: def.pattern.toString() } : {}, + inst, + continue: !def.abort + }); + }); + else + (_b = inst._zod).check ?? (_b.check = () => { + }); + }); + $ZodCheckRegex = /* @__PURE__ */ $constructor("$ZodCheckRegex", (inst, def) => { + $ZodCheckStringFormat.init(inst, def); + inst._zod.check = (payload2) => { + def.pattern.lastIndex = 0; + if (def.pattern.test(payload2.value)) + return; + payload2.issues.push({ + origin: "string", + code: "invalid_format", + format: "regex", + input: payload2.value, + pattern: def.pattern.toString(), + inst, + continue: !def.abort + }); + }; + }); + $ZodCheckLowerCase = /* @__PURE__ */ $constructor("$ZodCheckLowerCase", (inst, def) => { + def.pattern ?? (def.pattern = lowercase); + $ZodCheckStringFormat.init(inst, def); + }); + $ZodCheckUpperCase = /* @__PURE__ */ $constructor("$ZodCheckUpperCase", (inst, def) => { + def.pattern ?? (def.pattern = uppercase); + $ZodCheckStringFormat.init(inst, def); + }); + $ZodCheckIncludes = /* @__PURE__ */ $constructor("$ZodCheckIncludes", (inst, def) => { + $ZodCheck.init(inst, def); + const escapedRegex = escapeRegex(def.includes); + const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position}}${escapedRegex}` : escapedRegex); + def.pattern = pattern; + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); + bag.patterns.add(pattern); + }); + inst._zod.check = (payload2) => { + if (payload2.value.includes(def.includes, def.position)) + return; + payload2.issues.push({ + origin: "string", + code: "invalid_format", + format: "includes", + includes: def.includes, + input: payload2.value, + inst, + continue: !def.abort + }); + }; + }); + $ZodCheckStartsWith = /* @__PURE__ */ $constructor("$ZodCheckStartsWith", (inst, def) => { + $ZodCheck.init(inst, def); + const pattern = new RegExp(`^${escapeRegex(def.prefix)}.*`); + def.pattern ?? (def.pattern = pattern); + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); + bag.patterns.add(pattern); + }); + inst._zod.check = (payload2) => { + if (payload2.value.startsWith(def.prefix)) + return; + payload2.issues.push({ + origin: "string", + code: "invalid_format", + format: "starts_with", + prefix: def.prefix, + input: payload2.value, + inst, + continue: !def.abort + }); + }; + }); + $ZodCheckEndsWith = /* @__PURE__ */ $constructor("$ZodCheckEndsWith", (inst, def) => { + $ZodCheck.init(inst, def); + const pattern = new RegExp(`.*${escapeRegex(def.suffix)}$`); + def.pattern ?? (def.pattern = pattern); + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); + bag.patterns.add(pattern); + }); + inst._zod.check = (payload2) => { + if (payload2.value.endsWith(def.suffix)) + return; + payload2.issues.push({ + origin: "string", + code: "invalid_format", + format: "ends_with", + suffix: def.suffix, + input: payload2.value, + inst, + continue: !def.abort + }); + }; + }); + $ZodCheckProperty = /* @__PURE__ */ $constructor("$ZodCheckProperty", (inst, def) => { + $ZodCheck.init(inst, def); + inst._zod.check = (payload2) => { + const result = def.schema._zod.run({ + value: payload2.value[def.property], + issues: [] + }, {}); + if (result instanceof Promise) { + return result.then((result2) => handleCheckPropertyResult(result2, payload2, def.property)); + } + handleCheckPropertyResult(result, payload2, def.property); + return; + }; + }); + $ZodCheckMimeType = /* @__PURE__ */ $constructor("$ZodCheckMimeType", (inst, def) => { + $ZodCheck.init(inst, def); + const mimeSet = new Set(def.mime); + inst._zod.onattach.push((inst2) => { + inst2._zod.bag.mime = def.mime; + }); + inst._zod.check = (payload2) => { + if (mimeSet.has(payload2.value.type)) + return; + payload2.issues.push({ + code: "invalid_value", + values: def.mime, + input: payload2.value.type, + inst, + continue: !def.abort + }); + }; + }); + $ZodCheckOverwrite = /* @__PURE__ */ $constructor("$ZodCheckOverwrite", (inst, def) => { + $ZodCheck.init(inst, def); + inst._zod.check = (payload2) => { + payload2.value = def.tx(payload2.value); + }; + }); + } +}); + +// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/doc.js +var Doc; +var init_doc = __esm({ + "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/doc.js"() { + Doc = class { + constructor(args = []) { + this.content = []; + this.indent = 0; + if (this) + this.args = args; + } + indented(fn) { + this.indent += 1; + fn(this); + this.indent -= 1; + } + write(arg) { + if (typeof arg === "function") { + arg(this, { execution: "sync" }); + arg(this, { execution: "async" }); + return; + } + const content = arg; + const lines = content.split("\n").filter((x5) => x5); + const minIndent = Math.min(...lines.map((x5) => x5.length - x5.trimStart().length)); + const dedented = lines.map((x5) => x5.slice(minIndent)).map((x5) => " ".repeat(this.indent * 2) + x5); + for (const line3 of dedented) { + this.content.push(line3); + } + } + compile() { + const F2 = Function; + const args = this?.args; + const content = this?.content ?? [``]; + const lines = [...content.map((x5) => ` ${x5}`)]; + return new F2(...args, lines.join("\n")); + } + }; + } +}); + +// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/versions.js +var version2; +var init_versions = __esm({ + "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/versions.js"() { + version2 = { + major: 4, + minor: 3, + patch: 6 + }; + } +}); + +// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/schemas.js +function isValidBase64(data2) { + if (data2 === "") + return true; + if (data2.length % 4 !== 0) + return false; + try { + atob(data2); + return true; + } catch { + return false; + } +} +function isValidBase64URL(data2) { + if (!base64url.test(data2)) + return false; + const base644 = data2.replace(/[-_]/g, (c5) => c5 === "-" ? "+" : "/"); + const padded = base644.padEnd(Math.ceil(base644.length / 4) * 4, "="); + return isValidBase64(padded); +} +function isValidJWT2(token, algorithm2 = null) { + try { + const tokensParts = token.split("."); + if (tokensParts.length !== 3) + return false; + const [header] = tokensParts; + if (!header) + return false; + const parsedHeader = JSON.parse(atob(header)); + if ("typ" in parsedHeader && parsedHeader?.typ !== "JWT") + return false; + if (!parsedHeader.alg) + return false; + if (algorithm2 && (!("alg" in parsedHeader) || parsedHeader.alg !== algorithm2)) + return false; + return true; + } catch { + return false; + } +} +function handleArrayResult(result, final, index2) { + if (result.issues.length) { + final.issues.push(...prefixIssues(index2, result.issues)); + } + final.value[index2] = result.value; +} +function handlePropertyResult(result, final, key, input, isOptionalOut) { + if (result.issues.length) { + if (isOptionalOut && !(key in input)) { + return; + } + final.issues.push(...prefixIssues(key, result.issues)); + } + if (result.value === void 0) { + if (key in input) { + final.value[key] = void 0; + } + } else { + final.value[key] = result.value; + } +} +function normalizeDef(def) { + const keys = Object.keys(def.shape); + for (const k5 of keys) { + if (!def.shape?.[k5]?._zod?.traits?.has("$ZodType")) { + throw new Error(`Invalid element at key "${k5}": expected a Zod schema`); + } + } + const okeys = optionalKeys(def.shape); + return { + ...def, + keys, + keySet: new Set(keys), + numKeys: keys.length, + optionalKeys: new Set(okeys) + }; +} +function handleCatchall(proms, input, payload2, ctx, def, inst) { + const unrecognized = []; + const keySet = def.keySet; + const _catchall = def.catchall._zod; + const t5 = _catchall.def.type; + const isOptionalOut = _catchall.optout === "optional"; + for (const key in input) { + if (keySet.has(key)) + continue; + if (t5 === "never") { + unrecognized.push(key); + continue; + } + const r5 = _catchall.run({ value: input[key], issues: [] }, ctx); + if (r5 instanceof Promise) { + proms.push(r5.then((r6) => handlePropertyResult(r6, payload2, key, input, isOptionalOut))); + } else { + handlePropertyResult(r5, payload2, key, input, isOptionalOut); + } + } + if (unrecognized.length) { + payload2.issues.push({ + code: "unrecognized_keys", + keys: unrecognized, + input, + inst + }); + } + if (!proms.length) + return payload2; + return Promise.all(proms).then(() => { + return payload2; + }); +} +function handleUnionResults(results, final, inst, ctx) { + for (const result of results) { + if (result.issues.length === 0) { + final.value = result.value; + return final; + } + } + const nonaborted = results.filter((r5) => !aborted(r5)); + if (nonaborted.length === 1) { + final.value = nonaborted[0].value; + return nonaborted[0]; + } + final.issues.push({ + code: "invalid_union", + input: final.value, + inst, + errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) + }); + return final; +} +function handleExclusiveUnionResults(results, final, inst, ctx) { + const successes = results.filter((r5) => r5.issues.length === 0); + if (successes.length === 1) { + final.value = successes[0].value; + return final; + } + if (successes.length === 0) { + final.issues.push({ + code: "invalid_union", + input: final.value, + inst, + errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) + }); + } else { + final.issues.push({ + code: "invalid_union", + input: final.value, + inst, + errors: [], + inclusive: false + }); + } + return final; +} +function mergeValues2(a5, b6) { + if (a5 === b6) { + return { valid: true, data: a5 }; + } + if (a5 instanceof Date && b6 instanceof Date && +a5 === +b6) { + return { valid: true, data: a5 }; + } + if (isPlainObject5(a5) && isPlainObject5(b6)) { + const bKeys = Object.keys(b6); + const sharedKeys = Object.keys(a5).filter((key) => bKeys.indexOf(key) !== -1); + const newObj = { ...a5, ...b6 }; + for (const key of sharedKeys) { + const sharedValue = mergeValues2(a5[key], b6[key]); + if (!sharedValue.valid) { + return { + valid: false, + mergeErrorPath: [key, ...sharedValue.mergeErrorPath] + }; + } + newObj[key] = sharedValue.data; + } + return { valid: true, data: newObj }; + } + if (Array.isArray(a5) && Array.isArray(b6)) { + if (a5.length !== b6.length) { + return { valid: false, mergeErrorPath: [] }; + } + const newArray = []; + for (let index2 = 0; index2 < a5.length; index2++) { + const itemA = a5[index2]; + const itemB = b6[index2]; + const sharedValue = mergeValues2(itemA, itemB); + if (!sharedValue.valid) { + return { + valid: false, + mergeErrorPath: [index2, ...sharedValue.mergeErrorPath] + }; + } + newArray.push(sharedValue.data); + } + return { valid: true, data: newArray }; + } + return { valid: false, mergeErrorPath: [] }; +} +function handleIntersectionResults(result, left, right) { + const unrecKeys = /* @__PURE__ */ new Map(); + let unrecIssue; + for (const iss of left.issues) { + if (iss.code === "unrecognized_keys") { + unrecIssue ?? (unrecIssue = iss); + for (const k5 of iss.keys) { + if (!unrecKeys.has(k5)) + unrecKeys.set(k5, {}); + unrecKeys.get(k5).l = true; + } + } else { + result.issues.push(iss); + } + } + for (const iss of right.issues) { + if (iss.code === "unrecognized_keys") { + for (const k5 of iss.keys) { + if (!unrecKeys.has(k5)) + unrecKeys.set(k5, {}); + unrecKeys.get(k5).r = true; + } + } else { + result.issues.push(iss); + } + } + const bothKeys = [...unrecKeys].filter(([, f5]) => f5.l && f5.r).map(([k5]) => k5); + if (bothKeys.length && unrecIssue) { + result.issues.push({ ...unrecIssue, keys: bothKeys }); + } + if (aborted(result)) + return result; + const merged = mergeValues2(left.value, right.value); + if (!merged.valid) { + throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(merged.mergeErrorPath)}`); + } + result.value = merged.data; + return result; +} +function handleTupleResult(result, final, index2) { + if (result.issues.length) { + final.issues.push(...prefixIssues(index2, result.issues)); + } + final.value[index2] = result.value; +} +function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) { + if (keyResult.issues.length) { + if (propertyKeyTypes.has(typeof key)) { + final.issues.push(...prefixIssues(key, keyResult.issues)); + } else { + final.issues.push({ + code: "invalid_key", + origin: "map", + input, + inst, + issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())) + }); + } + } + if (valueResult.issues.length) { + if (propertyKeyTypes.has(typeof key)) { + final.issues.push(...prefixIssues(key, valueResult.issues)); + } else { + final.issues.push({ + origin: "map", + code: "invalid_element", + input, + inst, + key, + issues: valueResult.issues.map((iss) => finalizeIssue(iss, ctx, config())) + }); + } + } + final.value.set(keyResult.value, valueResult.value); +} +function handleSetResult(result, final) { + if (result.issues.length) { + final.issues.push(...result.issues); + } + final.value.add(result.value); +} +function handleOptionalResult(result, input) { + if (result.issues.length && input === void 0) { + return { issues: [], value: void 0 }; + } + return result; +} +function handleDefaultResult(payload2, def) { + if (payload2.value === void 0) { + payload2.value = def.defaultValue; + } + return payload2; +} +function handleNonOptionalResult(payload2, inst) { + if (!payload2.issues.length && payload2.value === void 0) { + payload2.issues.push({ + code: "invalid_type", + expected: "nonoptional", + input: payload2.value, + inst + }); + } + return payload2; +} +function handlePipeResult(left, next, ctx) { + if (left.issues.length) { + left.aborted = true; + return left; + } + return next._zod.run({ value: left.value, issues: left.issues }, ctx); +} +function handleCodecAResult(result, def, ctx) { + if (result.issues.length) { + result.aborted = true; + return result; + } + const direction = ctx.direction || "forward"; + if (direction === "forward") { + const transformed = def.transform(result.value, result); + if (transformed instanceof Promise) { + return transformed.then((value) => handleCodecTxResult(result, value, def.out, ctx)); + } + return handleCodecTxResult(result, transformed, def.out, ctx); + } else { + const transformed = def.reverseTransform(result.value, result); + if (transformed instanceof Promise) { + return transformed.then((value) => handleCodecTxResult(result, value, def.in, ctx)); + } + return handleCodecTxResult(result, transformed, def.in, ctx); + } +} +function handleCodecTxResult(left, value, nextSchema, ctx) { + if (left.issues.length) { + left.aborted = true; + return left; + } + return nextSchema._zod.run({ value, issues: left.issues }, ctx); +} +function handleReadonlyResult(payload2) { + payload2.value = Object.freeze(payload2.value); + return payload2; +} +function handleRefineResult(result, payload2, input, inst) { + if (!result) { + const _iss = { + code: "custom", + input, + inst, + // incorporates params.error into issue reporting + path: [...inst._zod.def.path ?? []], + // incorporates params.error into issue reporting + continue: !inst._zod.def.abort + // params: inst._zod.def.params, + }; + if (inst._zod.def.params) + _iss.params = inst._zod.def.params; + payload2.issues.push(issue(_iss)); + } +} +var $ZodType, $ZodString, $ZodStringFormat, $ZodGUID, $ZodUUID, $ZodEmail, $ZodURL, $ZodEmoji, $ZodNanoID, $ZodCUID, $ZodCUID2, $ZodULID, $ZodXID, $ZodKSUID, $ZodISODateTime, $ZodISODate, $ZodISOTime, $ZodISODuration, $ZodIPv4, $ZodIPv6, $ZodMAC, $ZodCIDRv4, $ZodCIDRv6, $ZodBase64, $ZodBase64URL, $ZodE164, $ZodJWT, $ZodCustomStringFormat, $ZodNumber, $ZodNumberFormat, $ZodBoolean, $ZodBigInt, $ZodBigIntFormat, $ZodSymbol, $ZodUndefined, $ZodNull, $ZodAny, $ZodUnknown, $ZodNever, $ZodVoid, $ZodDate, $ZodArray, $ZodObject, $ZodObjectJIT, $ZodUnion, $ZodXor, $ZodDiscriminatedUnion, $ZodIntersection, $ZodTuple, $ZodRecord, $ZodMap, $ZodSet, $ZodEnum, $ZodLiteral, $ZodFile, $ZodTransform, $ZodOptional, $ZodExactOptional, $ZodNullable, $ZodDefault, $ZodPrefault, $ZodNonOptional, $ZodSuccess, $ZodCatch, $ZodNaN, $ZodPipe, $ZodCodec, $ZodReadonly, $ZodTemplateLiteral, $ZodFunction, $ZodPromise, $ZodLazy, $ZodCustom; +var init_schemas = __esm({ + "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/schemas.js"() { + init_checks2(); + init_core(); + init_doc(); + init_parse(); + init_regexes(); + init_util(); + init_versions(); + init_util(); + $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => { + var _a6; + inst ?? (inst = {}); + inst._zod.def = def; + inst._zod.bag = inst._zod.bag || {}; + inst._zod.version = version2; + const checks = [...inst._zod.def.checks ?? []]; + if (inst._zod.traits.has("$ZodCheck")) { + checks.unshift(inst); + } + for (const ch of checks) { + for (const fn of ch._zod.onattach) { + fn(inst); + } + } + if (checks.length === 0) { + (_a6 = inst._zod).deferred ?? (_a6.deferred = []); + inst._zod.deferred?.push(() => { + inst._zod.run = inst._zod.parse; + }); + } else { + const runChecks = (payload2, checks2, ctx) => { + let isAborted2 = aborted(payload2); + let asyncResult; + for (const ch of checks2) { + if (ch._zod.def.when) { + const shouldRun = ch._zod.def.when(payload2); + if (!shouldRun) + continue; + } else if (isAborted2) { + continue; + } + const currLen = payload2.issues.length; + const _ = ch._zod.check(payload2); + if (_ instanceof Promise && ctx?.async === false) { + throw new $ZodAsyncError(); + } + if (asyncResult || _ instanceof Promise) { + asyncResult = (asyncResult ?? Promise.resolve()).then(async () => { + await _; + const nextLen = payload2.issues.length; + if (nextLen === currLen) + return; + if (!isAborted2) + isAborted2 = aborted(payload2, currLen); + }); + } else { + const nextLen = payload2.issues.length; + if (nextLen === currLen) + continue; + if (!isAborted2) + isAborted2 = aborted(payload2, currLen); + } + } + if (asyncResult) { + return asyncResult.then(() => { + return payload2; + }); + } + return payload2; + }; + const handleCanaryResult = (canary, payload2, ctx) => { + if (aborted(canary)) { + canary.aborted = true; + return canary; + } + const checkResult = runChecks(payload2, checks, ctx); + if (checkResult instanceof Promise) { + if (ctx.async === false) + throw new $ZodAsyncError(); + return checkResult.then((checkResult2) => inst._zod.parse(checkResult2, ctx)); + } + return inst._zod.parse(checkResult, ctx); + }; + inst._zod.run = (payload2, ctx) => { + if (ctx.skipChecks) { + return inst._zod.parse(payload2, ctx); + } + if (ctx.direction === "backward") { + const canary = inst._zod.parse({ value: payload2.value, issues: [] }, { ...ctx, skipChecks: true }); + if (canary instanceof Promise) { + return canary.then((canary2) => { + return handleCanaryResult(canary2, payload2, ctx); + }); + } + return handleCanaryResult(canary, payload2, ctx); + } + const result = inst._zod.parse(payload2, ctx); + if (result instanceof Promise) { + if (ctx.async === false) + throw new $ZodAsyncError(); + return result.then((result2) => runChecks(result2, checks, ctx)); + } + return runChecks(result, checks, ctx); + }; + } + defineLazy(inst, "~standard", () => ({ + validate: (value) => { + try { + const r5 = safeParse(inst, value); + return r5.success ? { value: r5.data } : { issues: r5.error?.issues }; + } catch (_) { + return safeParseAsync(inst, value).then((r5) => r5.success ? { value: r5.data } : { issues: r5.error?.issues }); + } + }, + vendor: "zod", + version: 1 + })); + }); + $ZodString = /* @__PURE__ */ $constructor("$ZodString", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = [...inst?._zod.bag?.patterns ?? []].pop() ?? string(inst._zod.bag); + inst._zod.parse = (payload2, _) => { + if (def.coerce) + try { + payload2.value = String(payload2.value); + } catch (_2) { + } + if (typeof payload2.value === "string") + return payload2; + payload2.issues.push({ + expected: "string", + code: "invalid_type", + input: payload2.value, + inst + }); + return payload2; + }; + }); + $ZodStringFormat = /* @__PURE__ */ $constructor("$ZodStringFormat", (inst, def) => { + $ZodCheckStringFormat.init(inst, def); + $ZodString.init(inst, def); + }); + $ZodGUID = /* @__PURE__ */ $constructor("$ZodGUID", (inst, def) => { + def.pattern ?? (def.pattern = guid); + $ZodStringFormat.init(inst, def); + }); + $ZodUUID = /* @__PURE__ */ $constructor("$ZodUUID", (inst, def) => { + if (def.version) { + const versionMap = { + v1: 1, + v2: 2, + v3: 3, + v4: 4, + v5: 5, + v6: 6, + v7: 7, + v8: 8 + }; + const v5 = versionMap[def.version]; + if (v5 === void 0) + throw new Error(`Invalid UUID version: "${def.version}"`); + def.pattern ?? (def.pattern = uuid2(v5)); + } else + def.pattern ?? (def.pattern = uuid2()); + $ZodStringFormat.init(inst, def); + }); + $ZodEmail = /* @__PURE__ */ $constructor("$ZodEmail", (inst, def) => { + def.pattern ?? (def.pattern = email); + $ZodStringFormat.init(inst, def); + }); + $ZodURL = /* @__PURE__ */ $constructor("$ZodURL", (inst, def) => { + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload2) => { + try { + const trimmed = payload2.value.trim(); + const url2 = new URL(trimmed); + if (def.hostname) { + def.hostname.lastIndex = 0; + if (!def.hostname.test(url2.hostname)) { + payload2.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid hostname", + pattern: def.hostname.source, + input: payload2.value, + inst, + continue: !def.abort + }); + } + } + if (def.protocol) { + def.protocol.lastIndex = 0; + if (!def.protocol.test(url2.protocol.endsWith(":") ? url2.protocol.slice(0, -1) : url2.protocol)) { + payload2.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid protocol", + pattern: def.protocol.source, + input: payload2.value, + inst, + continue: !def.abort + }); + } + } + if (def.normalize) { + payload2.value = url2.href; + } else { + payload2.value = trimmed; + } + return; + } catch (_) { + payload2.issues.push({ + code: "invalid_format", + format: "url", + input: payload2.value, + inst, + continue: !def.abort + }); + } + }; + }); + $ZodEmoji = /* @__PURE__ */ $constructor("$ZodEmoji", (inst, def) => { + def.pattern ?? (def.pattern = emoji()); + $ZodStringFormat.init(inst, def); + }); + $ZodNanoID = /* @__PURE__ */ $constructor("$ZodNanoID", (inst, def) => { + def.pattern ?? (def.pattern = nanoid); + $ZodStringFormat.init(inst, def); + }); + $ZodCUID = /* @__PURE__ */ $constructor("$ZodCUID", (inst, def) => { + def.pattern ?? (def.pattern = cuid); + $ZodStringFormat.init(inst, def); + }); + $ZodCUID2 = /* @__PURE__ */ $constructor("$ZodCUID2", (inst, def) => { + def.pattern ?? (def.pattern = cuid2); + $ZodStringFormat.init(inst, def); + }); + $ZodULID = /* @__PURE__ */ $constructor("$ZodULID", (inst, def) => { + def.pattern ?? (def.pattern = ulid); + $ZodStringFormat.init(inst, def); + }); + $ZodXID = /* @__PURE__ */ $constructor("$ZodXID", (inst, def) => { + def.pattern ?? (def.pattern = xid); + $ZodStringFormat.init(inst, def); + }); + $ZodKSUID = /* @__PURE__ */ $constructor("$ZodKSUID", (inst, def) => { + def.pattern ?? (def.pattern = ksuid); + $ZodStringFormat.init(inst, def); + }); + $ZodISODateTime = /* @__PURE__ */ $constructor("$ZodISODateTime", (inst, def) => { + def.pattern ?? (def.pattern = datetime(def)); + $ZodStringFormat.init(inst, def); + }); + $ZodISODate = /* @__PURE__ */ $constructor("$ZodISODate", (inst, def) => { + def.pattern ?? (def.pattern = date3); + $ZodStringFormat.init(inst, def); + }); + $ZodISOTime = /* @__PURE__ */ $constructor("$ZodISOTime", (inst, def) => { + def.pattern ?? (def.pattern = time3(def)); + $ZodStringFormat.init(inst, def); + }); + $ZodISODuration = /* @__PURE__ */ $constructor("$ZodISODuration", (inst, def) => { + def.pattern ?? (def.pattern = duration); + $ZodStringFormat.init(inst, def); + }); + $ZodIPv4 = /* @__PURE__ */ $constructor("$ZodIPv4", (inst, def) => { + def.pattern ?? (def.pattern = ipv4); + $ZodStringFormat.init(inst, def); + inst._zod.bag.format = `ipv4`; + }); + $ZodIPv6 = /* @__PURE__ */ $constructor("$ZodIPv6", (inst, def) => { + def.pattern ?? (def.pattern = ipv6); + $ZodStringFormat.init(inst, def); + inst._zod.bag.format = `ipv6`; + inst._zod.check = (payload2) => { + try { + new URL(`http://[${payload2.value}]`); + } catch { + payload2.issues.push({ + code: "invalid_format", + format: "ipv6", + input: payload2.value, + inst, + continue: !def.abort + }); + } + }; + }); + $ZodMAC = /* @__PURE__ */ $constructor("$ZodMAC", (inst, def) => { + def.pattern ?? (def.pattern = mac(def.delimiter)); + $ZodStringFormat.init(inst, def); + inst._zod.bag.format = `mac`; + }); + $ZodCIDRv4 = /* @__PURE__ */ $constructor("$ZodCIDRv4", (inst, def) => { + def.pattern ?? (def.pattern = cidrv4); + $ZodStringFormat.init(inst, def); + }); + $ZodCIDRv6 = /* @__PURE__ */ $constructor("$ZodCIDRv6", (inst, def) => { + def.pattern ?? (def.pattern = cidrv6); + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload2) => { + const parts = payload2.value.split("/"); + try { + if (parts.length !== 2) + throw new Error(); + const [address, prefix] = parts; + if (!prefix) + throw new Error(); + const prefixNum = Number(prefix); + if (`${prefixNum}` !== prefix) + throw new Error(); + if (prefixNum < 0 || prefixNum > 128) + throw new Error(); + new URL(`http://[${address}]`); + } catch { + payload2.issues.push({ + code: "invalid_format", + format: "cidrv6", + input: payload2.value, + inst, + continue: !def.abort + }); + } + }; + }); + $ZodBase64 = /* @__PURE__ */ $constructor("$ZodBase64", (inst, def) => { + def.pattern ?? (def.pattern = base64); + $ZodStringFormat.init(inst, def); + inst._zod.bag.contentEncoding = "base64"; + inst._zod.check = (payload2) => { + if (isValidBase64(payload2.value)) + return; + payload2.issues.push({ + code: "invalid_format", + format: "base64", + input: payload2.value, + inst, + continue: !def.abort + }); + }; + }); + $ZodBase64URL = /* @__PURE__ */ $constructor("$ZodBase64URL", (inst, def) => { + def.pattern ?? (def.pattern = base64url); + $ZodStringFormat.init(inst, def); + inst._zod.bag.contentEncoding = "base64url"; + inst._zod.check = (payload2) => { + if (isValidBase64URL(payload2.value)) + return; + payload2.issues.push({ + code: "invalid_format", + format: "base64url", + input: payload2.value, + inst, + continue: !def.abort + }); + }; + }); + $ZodE164 = /* @__PURE__ */ $constructor("$ZodE164", (inst, def) => { + def.pattern ?? (def.pattern = e164); + $ZodStringFormat.init(inst, def); + }); + $ZodJWT = /* @__PURE__ */ $constructor("$ZodJWT", (inst, def) => { + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload2) => { + if (isValidJWT2(payload2.value, def.alg)) + return; + payload2.issues.push({ + code: "invalid_format", + format: "jwt", + input: payload2.value, + inst, + continue: !def.abort + }); + }; + }); + $ZodCustomStringFormat = /* @__PURE__ */ $constructor("$ZodCustomStringFormat", (inst, def) => { + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload2) => { + if (def.fn(payload2.value)) + return; + payload2.issues.push({ + code: "invalid_format", + format: def.format, + input: payload2.value, + inst, + continue: !def.abort + }); + }; + }); + $ZodNumber = /* @__PURE__ */ $constructor("$ZodNumber", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = inst._zod.bag.pattern ?? number; + inst._zod.parse = (payload2, _ctx) => { + if (def.coerce) + try { + payload2.value = Number(payload2.value); + } catch (_) { + } + const input = payload2.value; + if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) { + return payload2; + } + const received = typeof input === "number" ? Number.isNaN(input) ? "NaN" : !Number.isFinite(input) ? "Infinity" : void 0 : void 0; + payload2.issues.push({ + expected: "number", + code: "invalid_type", + input, + inst, + ...received ? { received } : {} + }); + return payload2; + }; + }); + $ZodNumberFormat = /* @__PURE__ */ $constructor("$ZodNumberFormat", (inst, def) => { + $ZodCheckNumberFormat.init(inst, def); + $ZodNumber.init(inst, def); + }); + $ZodBoolean = /* @__PURE__ */ $constructor("$ZodBoolean", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = boolean2; + inst._zod.parse = (payload2, _ctx) => { + if (def.coerce) + try { + payload2.value = Boolean(payload2.value); + } catch (_) { + } + const input = payload2.value; + if (typeof input === "boolean") + return payload2; + payload2.issues.push({ + expected: "boolean", + code: "invalid_type", + input, + inst + }); + return payload2; + }; + }); + $ZodBigInt = /* @__PURE__ */ $constructor("$ZodBigInt", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = bigint2; + inst._zod.parse = (payload2, _ctx) => { + if (def.coerce) + try { + payload2.value = BigInt(payload2.value); + } catch (_) { + } + if (typeof payload2.value === "bigint") + return payload2; + payload2.issues.push({ + expected: "bigint", + code: "invalid_type", + input: payload2.value, + inst + }); + return payload2; + }; + }); + $ZodBigIntFormat = /* @__PURE__ */ $constructor("$ZodBigIntFormat", (inst, def) => { + $ZodCheckBigIntFormat.init(inst, def); + $ZodBigInt.init(inst, def); + }); + $ZodSymbol = /* @__PURE__ */ $constructor("$ZodSymbol", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload2, _ctx) => { + const input = payload2.value; + if (typeof input === "symbol") + return payload2; + payload2.issues.push({ + expected: "symbol", + code: "invalid_type", + input, + inst + }); + return payload2; + }; + }); + $ZodUndefined = /* @__PURE__ */ $constructor("$ZodUndefined", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = _undefined; + inst._zod.values = /* @__PURE__ */ new Set([void 0]); + inst._zod.optin = "optional"; + inst._zod.optout = "optional"; + inst._zod.parse = (payload2, _ctx) => { + const input = payload2.value; + if (typeof input === "undefined") + return payload2; + payload2.issues.push({ + expected: "undefined", + code: "invalid_type", + input, + inst + }); + return payload2; + }; + }); + $ZodNull = /* @__PURE__ */ $constructor("$ZodNull", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = _null; + inst._zod.values = /* @__PURE__ */ new Set([null]); + inst._zod.parse = (payload2, _ctx) => { + const input = payload2.value; + if (input === null) + return payload2; + payload2.issues.push({ + expected: "null", + code: "invalid_type", + input, + inst + }); + return payload2; + }; + }); + $ZodAny = /* @__PURE__ */ $constructor("$ZodAny", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload2) => payload2; + }); + $ZodUnknown = /* @__PURE__ */ $constructor("$ZodUnknown", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload2) => payload2; + }); + $ZodNever = /* @__PURE__ */ $constructor("$ZodNever", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload2, _ctx) => { + payload2.issues.push({ + expected: "never", + code: "invalid_type", + input: payload2.value, + inst + }); + return payload2; + }; + }); + $ZodVoid = /* @__PURE__ */ $constructor("$ZodVoid", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload2, _ctx) => { + const input = payload2.value; + if (typeof input === "undefined") + return payload2; + payload2.issues.push({ + expected: "void", + code: "invalid_type", + input, + inst + }); + return payload2; + }; + }); + $ZodDate = /* @__PURE__ */ $constructor("$ZodDate", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload2, _ctx) => { + if (def.coerce) { + try { + payload2.value = new Date(payload2.value); + } catch (_err) { + } + } + const input = payload2.value; + const isDate2 = input instanceof Date; + const isValidDate = isDate2 && !Number.isNaN(input.getTime()); + if (isValidDate) + return payload2; + payload2.issues.push({ + expected: "date", + code: "invalid_type", + input, + ...isDate2 ? { received: "Invalid Date" } : {}, + inst + }); + return payload2; + }; + }); + $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload2, ctx) => { + const input = payload2.value; + if (!Array.isArray(input)) { + payload2.issues.push({ + expected: "array", + code: "invalid_type", + input, + inst + }); + return payload2; + } + payload2.value = Array(input.length); + const proms = []; + for (let i5 = 0; i5 < input.length; i5++) { + const item = input[i5]; + const result = def.element._zod.run({ + value: item, + issues: [] + }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result2) => handleArrayResult(result2, payload2, i5))); + } else { + handleArrayResult(result, payload2, i5); + } + } + if (proms.length) { + return Promise.all(proms).then(() => payload2); + } + return payload2; + }; + }); + $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => { + $ZodType.init(inst, def); + const desc3 = Object.getOwnPropertyDescriptor(def, "shape"); + if (!desc3?.get) { + const sh = def.shape; + Object.defineProperty(def, "shape", { + get: () => { + const newSh = { ...sh }; + Object.defineProperty(def, "shape", { + value: newSh + }); + return newSh; + } + }); + } + const _normalized = cached3(() => normalizeDef(def)); + defineLazy(inst._zod, "propValues", () => { + const shape = def.shape; + const propValues = {}; + for (const key in shape) { + const field = shape[key]._zod; + if (field.values) { + propValues[key] ?? (propValues[key] = /* @__PURE__ */ new Set()); + for (const v5 of field.values) + propValues[key].add(v5); + } + } + return propValues; + }); + const isObject4 = isObject2; + const catchall = def.catchall; + let value; + inst._zod.parse = (payload2, ctx) => { + value ?? (value = _normalized.value); + const input = payload2.value; + if (!isObject4(input)) { + payload2.issues.push({ + expected: "object", + code: "invalid_type", + input, + inst + }); + return payload2; + } + payload2.value = {}; + const proms = []; + const shape = value.shape; + for (const key of value.keys) { + const el = shape[key]; + const isOptionalOut = el._zod.optout === "optional"; + const r5 = el._zod.run({ value: input[key], issues: [] }, ctx); + if (r5 instanceof Promise) { + proms.push(r5.then((r6) => handlePropertyResult(r6, payload2, key, input, isOptionalOut))); + } else { + handlePropertyResult(r5, payload2, key, input, isOptionalOut); + } + } + if (!catchall) { + return proms.length ? Promise.all(proms).then(() => payload2) : payload2; + } + return handleCatchall(proms, input, payload2, ctx, _normalized.value, inst); + }; + }); + $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) => { + $ZodObject.init(inst, def); + const superParse = inst._zod.parse; + const _normalized = cached3(() => normalizeDef(def)); + const generateFastpass = (shape) => { + const doc = new Doc(["shape", "payload", "ctx"]); + const normalized = _normalized.value; + const parseStr = (key) => { + const k5 = esc(key); + return `shape[${k5}]._zod.run({ value: input[${k5}], issues: [] }, ctx)`; + }; + doc.write(`const input = payload.value;`); + const ids = /* @__PURE__ */ Object.create(null); + let counter = 0; + for (const key of normalized.keys) { + ids[key] = `key_${counter++}`; + } + doc.write(`const newResult = {};`); + for (const key of normalized.keys) { + const id = ids[key]; + const k5 = esc(key); + const schema2 = shape[key]; + const isOptionalOut = schema2?._zod?.optout === "optional"; + doc.write(`const ${id} = ${parseStr(key)};`); + if (isOptionalOut) { + doc.write(` + if (${id}.issues.length) { + if (${k5} in input) { + payload.issues = payload.issues.concat(${id}.issues.map(iss => ({ + ...iss, + path: iss.path ? [${k5}, ...iss.path] : [${k5}] + }))); + } + } + + if (${id}.value === undefined) { + if (${k5} in input) { + newResult[${k5}] = undefined; + } + } else { + newResult[${k5}] = ${id}.value; + } + + `); + } else { + doc.write(` + if (${id}.issues.length) { + payload.issues = payload.issues.concat(${id}.issues.map(iss => ({ + ...iss, + path: iss.path ? [${k5}, ...iss.path] : [${k5}] + }))); + } + + if (${id}.value === undefined) { + if (${k5} in input) { + newResult[${k5}] = undefined; + } + } else { + newResult[${k5}] = ${id}.value; + } + + `); + } + } + doc.write(`payload.value = newResult;`); + doc.write(`return payload;`); + const fn = doc.compile(); + return (payload2, ctx) => fn(shape, payload2, ctx); + }; + let fastpass; + const isObject4 = isObject2; + const jit = !globalConfig.jitless; + const allowsEval2 = allowsEval; + const fastEnabled = jit && allowsEval2.value; + const catchall = def.catchall; + let value; + inst._zod.parse = (payload2, ctx) => { + value ?? (value = _normalized.value); + const input = payload2.value; + if (!isObject4(input)) { + payload2.issues.push({ + expected: "object", + code: "invalid_type", + input, + inst + }); + return payload2; + } + if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) { + if (!fastpass) + fastpass = generateFastpass(def.shape); + payload2 = fastpass(payload2, ctx); + if (!catchall) + return payload2; + return handleCatchall([], input, payload2, ctx, value, inst); + } + return superParse(payload2, ctx); + }; + }); + $ZodUnion = /* @__PURE__ */ $constructor("$ZodUnion", (inst, def) => { + $ZodType.init(inst, def); + defineLazy(inst._zod, "optin", () => def.options.some((o5) => o5._zod.optin === "optional") ? "optional" : void 0); + defineLazy(inst._zod, "optout", () => def.options.some((o5) => o5._zod.optout === "optional") ? "optional" : void 0); + defineLazy(inst._zod, "values", () => { + if (def.options.every((o5) => o5._zod.values)) { + return new Set(def.options.flatMap((option) => Array.from(option._zod.values))); + } + return void 0; + }); + defineLazy(inst._zod, "pattern", () => { + if (def.options.every((o5) => o5._zod.pattern)) { + const patterns = def.options.map((o5) => o5._zod.pattern); + return new RegExp(`^(${patterns.map((p5) => cleanRegex(p5.source)).join("|")})$`); + } + return void 0; + }); + const single = def.options.length === 1; + const first = def.options[0]._zod.run; + inst._zod.parse = (payload2, ctx) => { + if (single) { + return first(payload2, ctx); + } + let async = false; + const results = []; + for (const option of def.options) { + const result = option._zod.run({ + value: payload2.value, + issues: [] + }, ctx); + if (result instanceof Promise) { + results.push(result); + async = true; + } else { + if (result.issues.length === 0) + return result; + results.push(result); + } + } + if (!async) + return handleUnionResults(results, payload2, inst, ctx); + return Promise.all(results).then((results2) => { + return handleUnionResults(results2, payload2, inst, ctx); + }); + }; + }); + $ZodXor = /* @__PURE__ */ $constructor("$ZodXor", (inst, def) => { + $ZodUnion.init(inst, def); + def.inclusive = false; + const single = def.options.length === 1; + const first = def.options[0]._zod.run; + inst._zod.parse = (payload2, ctx) => { + if (single) { + return first(payload2, ctx); + } + let async = false; + const results = []; + for (const option of def.options) { + const result = option._zod.run({ + value: payload2.value, + issues: [] + }, ctx); + if (result instanceof Promise) { + results.push(result); + async = true; + } else { + results.push(result); + } + } + if (!async) + return handleExclusiveUnionResults(results, payload2, inst, ctx); + return Promise.all(results).then((results2) => { + return handleExclusiveUnionResults(results2, payload2, inst, ctx); + }); + }; + }); + $ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("$ZodDiscriminatedUnion", (inst, def) => { + def.inclusive = false; + $ZodUnion.init(inst, def); + const _super = inst._zod.parse; + defineLazy(inst._zod, "propValues", () => { + const propValues = {}; + for (const option of def.options) { + const pv = option._zod.propValues; + if (!pv || Object.keys(pv).length === 0) + throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`); + for (const [k5, v5] of Object.entries(pv)) { + if (!propValues[k5]) + propValues[k5] = /* @__PURE__ */ new Set(); + for (const val of v5) { + propValues[k5].add(val); + } + } + } + return propValues; + }); + const disc = cached3(() => { + const opts = def.options; + const map4 = /* @__PURE__ */ new Map(); + for (const o5 of opts) { + const values2 = o5._zod.propValues?.[def.discriminator]; + if (!values2 || values2.size === 0) + throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(o5)}"`); + for (const v5 of values2) { + if (map4.has(v5)) { + throw new Error(`Duplicate discriminator value "${String(v5)}"`); + } + map4.set(v5, o5); + } + } + return map4; + }); + inst._zod.parse = (payload2, ctx) => { + const input = payload2.value; + if (!isObject2(input)) { + payload2.issues.push({ + code: "invalid_type", + expected: "object", + input, + inst + }); + return payload2; + } + const opt = disc.value.get(input?.[def.discriminator]); + if (opt) { + return opt._zod.run(payload2, ctx); + } + if (def.unionFallback) { + return _super(payload2, ctx); + } + payload2.issues.push({ + code: "invalid_union", + errors: [], + note: "No matching discriminator", + discriminator: def.discriminator, + input, + path: [def.discriminator], + inst + }); + return payload2; + }; + }); + $ZodIntersection = /* @__PURE__ */ $constructor("$ZodIntersection", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload2, ctx) => { + const input = payload2.value; + const left = def.left._zod.run({ value: input, issues: [] }, ctx); + const right = def.right._zod.run({ value: input, issues: [] }, ctx); + const async = left instanceof Promise || right instanceof Promise; + if (async) { + return Promise.all([left, right]).then(([left2, right2]) => { + return handleIntersectionResults(payload2, left2, right2); + }); + } + return handleIntersectionResults(payload2, left, right); + }; + }); + $ZodTuple = /* @__PURE__ */ $constructor("$ZodTuple", (inst, def) => { + $ZodType.init(inst, def); + const items = def.items; + inst._zod.parse = (payload2, ctx) => { + const input = payload2.value; + if (!Array.isArray(input)) { + payload2.issues.push({ + input, + inst, + expected: "tuple", + code: "invalid_type" + }); + return payload2; + } + payload2.value = []; + const proms = []; + const reversedIndex = [...items].reverse().findIndex((item) => item._zod.optin !== "optional"); + const optStart = reversedIndex === -1 ? 0 : items.length - reversedIndex; + if (!def.rest) { + const tooBig = input.length > items.length; + const tooSmall = input.length < optStart - 1; + if (tooBig || tooSmall) { + payload2.issues.push({ + ...tooBig ? { code: "too_big", maximum: items.length, inclusive: true } : { code: "too_small", minimum: items.length }, + input, + inst, + origin: "array" + }); + return payload2; + } + } + let i5 = -1; + for (const item of items) { + i5++; + if (i5 >= input.length) { + if (i5 >= optStart) + continue; + } + const result = item._zod.run({ + value: input[i5], + issues: [] + }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result2) => handleTupleResult(result2, payload2, i5))); + } else { + handleTupleResult(result, payload2, i5); + } + } + if (def.rest) { + const rest = input.slice(items.length); + for (const el of rest) { + i5++; + const result = def.rest._zod.run({ + value: el, + issues: [] + }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result2) => handleTupleResult(result2, payload2, i5))); + } else { + handleTupleResult(result, payload2, i5); + } + } + } + if (proms.length) + return Promise.all(proms).then(() => payload2); + return payload2; + }; + }); + $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload2, ctx) => { + const input = payload2.value; + if (!isPlainObject5(input)) { + payload2.issues.push({ + expected: "record", + code: "invalid_type", + input, + inst + }); + return payload2; + } + const proms = []; + const values2 = def.keyType._zod.values; + if (values2) { + payload2.value = {}; + const recordKeys = /* @__PURE__ */ new Set(); + for (const key of values2) { + if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") { + recordKeys.add(typeof key === "number" ? key.toString() : key); + const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result2) => { + if (result2.issues.length) { + payload2.issues.push(...prefixIssues(key, result2.issues)); + } + payload2.value[key] = result2.value; + })); + } else { + if (result.issues.length) { + payload2.issues.push(...prefixIssues(key, result.issues)); + } + payload2.value[key] = result.value; + } + } + } + let unrecognized; + for (const key in input) { + if (!recordKeys.has(key)) { + unrecognized = unrecognized ?? []; + unrecognized.push(key); + } + } + if (unrecognized && unrecognized.length > 0) { + payload2.issues.push({ + code: "unrecognized_keys", + input, + inst, + keys: unrecognized + }); + } + } else { + payload2.value = {}; + for (const key of Reflect.ownKeys(input)) { + if (key === "__proto__") + continue; + let keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); + if (keyResult instanceof Promise) { + throw new Error("Async schemas not supported in object keys currently"); + } + const checkNumericKey = typeof key === "string" && number.test(key) && keyResult.issues.length; + if (checkNumericKey) { + const retryResult = def.keyType._zod.run({ value: Number(key), issues: [] }, ctx); + if (retryResult instanceof Promise) { + throw new Error("Async schemas not supported in object keys currently"); + } + if (retryResult.issues.length === 0) { + keyResult = retryResult; + } + } + if (keyResult.issues.length) { + if (def.mode === "loose") { + payload2.value[key] = input[key]; + } else { + payload2.issues.push({ + code: "invalid_key", + origin: "record", + issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())), + input: key, + path: [key], + inst + }); + } + continue; + } + const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result2) => { + if (result2.issues.length) { + payload2.issues.push(...prefixIssues(key, result2.issues)); + } + payload2.value[keyResult.value] = result2.value; + })); + } else { + if (result.issues.length) { + payload2.issues.push(...prefixIssues(key, result.issues)); + } + payload2.value[keyResult.value] = result.value; + } + } + } + if (proms.length) { + return Promise.all(proms).then(() => payload2); + } + return payload2; + }; + }); + $ZodMap = /* @__PURE__ */ $constructor("$ZodMap", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload2, ctx) => { + const input = payload2.value; + if (!(input instanceof Map)) { + payload2.issues.push({ + expected: "map", + code: "invalid_type", + input, + inst + }); + return payload2; + } + const proms = []; + payload2.value = /* @__PURE__ */ new Map(); + for (const [key, value] of input) { + const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); + const valueResult = def.valueType._zod.run({ value, issues: [] }, ctx); + if (keyResult instanceof Promise || valueResult instanceof Promise) { + proms.push(Promise.all([keyResult, valueResult]).then(([keyResult2, valueResult2]) => { + handleMapResult(keyResult2, valueResult2, payload2, key, input, inst, ctx); + })); + } else { + handleMapResult(keyResult, valueResult, payload2, key, input, inst, ctx); + } + } + if (proms.length) + return Promise.all(proms).then(() => payload2); + return payload2; + }; + }); + $ZodSet = /* @__PURE__ */ $constructor("$ZodSet", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload2, ctx) => { + const input = payload2.value; + if (!(input instanceof Set)) { + payload2.issues.push({ + input, + inst, + expected: "set", + code: "invalid_type" + }); + return payload2; + } + const proms = []; + payload2.value = /* @__PURE__ */ new Set(); + for (const item of input) { + const result = def.valueType._zod.run({ value: item, issues: [] }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result2) => handleSetResult(result2, payload2))); + } else + handleSetResult(result, payload2); + } + if (proms.length) + return Promise.all(proms).then(() => payload2); + return payload2; + }; + }); + $ZodEnum = /* @__PURE__ */ $constructor("$ZodEnum", (inst, def) => { + $ZodType.init(inst, def); + const values2 = getEnumValues(def.entries); + const valuesSet = new Set(values2); + inst._zod.values = valuesSet; + inst._zod.pattern = new RegExp(`^(${values2.filter((k5) => propertyKeyTypes.has(typeof k5)).map((o5) => typeof o5 === "string" ? escapeRegex(o5) : o5.toString()).join("|")})$`); + inst._zod.parse = (payload2, _ctx) => { + const input = payload2.value; + if (valuesSet.has(input)) { + return payload2; + } + payload2.issues.push({ + code: "invalid_value", + values: values2, + input, + inst + }); + return payload2; + }; + }); + $ZodLiteral = /* @__PURE__ */ $constructor("$ZodLiteral", (inst, def) => { + $ZodType.init(inst, def); + if (def.values.length === 0) { + throw new Error("Cannot create literal schema with no valid values"); + } + const values2 = new Set(def.values); + inst._zod.values = values2; + inst._zod.pattern = new RegExp(`^(${def.values.map((o5) => typeof o5 === "string" ? escapeRegex(o5) : o5 ? escapeRegex(o5.toString()) : String(o5)).join("|")})$`); + inst._zod.parse = (payload2, _ctx) => { + const input = payload2.value; + if (values2.has(input)) { + return payload2; + } + payload2.issues.push({ + code: "invalid_value", + values: def.values, + input, + inst + }); + return payload2; + }; + }); + $ZodFile = /* @__PURE__ */ $constructor("$ZodFile", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload2, _ctx) => { + const input = payload2.value; + if (input instanceof File) + return payload2; + payload2.issues.push({ + expected: "file", + code: "invalid_type", + input, + inst + }); + return payload2; + }; + }); + $ZodTransform = /* @__PURE__ */ $constructor("$ZodTransform", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload2, ctx) => { + if (ctx.direction === "backward") { + throw new $ZodEncodeError(inst.constructor.name); + } + const _out = def.transform(payload2.value, payload2); + if (ctx.async) { + const output = _out instanceof Promise ? _out : Promise.resolve(_out); + return output.then((output2) => { + payload2.value = output2; + return payload2; + }); + } + if (_out instanceof Promise) { + throw new $ZodAsyncError(); + } + payload2.value = _out; + return payload2; + }; + }); + $ZodOptional = /* @__PURE__ */ $constructor("$ZodOptional", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.optin = "optional"; + inst._zod.optout = "optional"; + defineLazy(inst._zod, "values", () => { + return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, void 0]) : void 0; + }); + defineLazy(inst._zod, "pattern", () => { + const pattern = def.innerType._zod.pattern; + return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : void 0; + }); + inst._zod.parse = (payload2, ctx) => { + if (def.innerType._zod.optin === "optional") { + const result = def.innerType._zod.run(payload2, ctx); + if (result instanceof Promise) + return result.then((r5) => handleOptionalResult(r5, payload2.value)); + return handleOptionalResult(result, payload2.value); + } + if (payload2.value === void 0) { + return payload2; + } + return def.innerType._zod.run(payload2, ctx); + }; + }); + $ZodExactOptional = /* @__PURE__ */ $constructor("$ZodExactOptional", (inst, def) => { + $ZodOptional.init(inst, def); + defineLazy(inst._zod, "values", () => def.innerType._zod.values); + defineLazy(inst._zod, "pattern", () => def.innerType._zod.pattern); + inst._zod.parse = (payload2, ctx) => { + return def.innerType._zod.run(payload2, ctx); + }; + }); + $ZodNullable = /* @__PURE__ */ $constructor("$ZodNullable", (inst, def) => { + $ZodType.init(inst, def); + defineLazy(inst._zod, "optin", () => def.innerType._zod.optin); + defineLazy(inst._zod, "optout", () => def.innerType._zod.optout); + defineLazy(inst._zod, "pattern", () => { + const pattern = def.innerType._zod.pattern; + return pattern ? new RegExp(`^(${cleanRegex(pattern.source)}|null)$`) : void 0; + }); + defineLazy(inst._zod, "values", () => { + return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, null]) : void 0; + }); + inst._zod.parse = (payload2, ctx) => { + if (payload2.value === null) + return payload2; + return def.innerType._zod.run(payload2, ctx); + }; + }); + $ZodDefault = /* @__PURE__ */ $constructor("$ZodDefault", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.optin = "optional"; + defineLazy(inst._zod, "values", () => def.innerType._zod.values); + inst._zod.parse = (payload2, ctx) => { + if (ctx.direction === "backward") { + return def.innerType._zod.run(payload2, ctx); + } + if (payload2.value === void 0) { + payload2.value = def.defaultValue; + return payload2; + } + const result = def.innerType._zod.run(payload2, ctx); + if (result instanceof Promise) { + return result.then((result2) => handleDefaultResult(result2, def)); + } + return handleDefaultResult(result, def); + }; + }); + $ZodPrefault = /* @__PURE__ */ $constructor("$ZodPrefault", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.optin = "optional"; + defineLazy(inst._zod, "values", () => def.innerType._zod.values); + inst._zod.parse = (payload2, ctx) => { + if (ctx.direction === "backward") { + return def.innerType._zod.run(payload2, ctx); + } + if (payload2.value === void 0) { + payload2.value = def.defaultValue; + } + return def.innerType._zod.run(payload2, ctx); + }; + }); + $ZodNonOptional = /* @__PURE__ */ $constructor("$ZodNonOptional", (inst, def) => { + $ZodType.init(inst, def); + defineLazy(inst._zod, "values", () => { + const v5 = def.innerType._zod.values; + return v5 ? new Set([...v5].filter((x5) => x5 !== void 0)) : void 0; + }); + inst._zod.parse = (payload2, ctx) => { + const result = def.innerType._zod.run(payload2, ctx); + if (result instanceof Promise) { + return result.then((result2) => handleNonOptionalResult(result2, inst)); + } + return handleNonOptionalResult(result, inst); + }; + }); + $ZodSuccess = /* @__PURE__ */ $constructor("$ZodSuccess", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload2, ctx) => { + if (ctx.direction === "backward") { + throw new $ZodEncodeError("ZodSuccess"); + } + const result = def.innerType._zod.run(payload2, ctx); + if (result instanceof Promise) { + return result.then((result2) => { + payload2.value = result2.issues.length === 0; + return payload2; + }); + } + payload2.value = result.issues.length === 0; + return payload2; + }; + }); + $ZodCatch = /* @__PURE__ */ $constructor("$ZodCatch", (inst, def) => { + $ZodType.init(inst, def); + defineLazy(inst._zod, "optin", () => def.innerType._zod.optin); + defineLazy(inst._zod, "optout", () => def.innerType._zod.optout); + defineLazy(inst._zod, "values", () => def.innerType._zod.values); + inst._zod.parse = (payload2, ctx) => { + if (ctx.direction === "backward") { + return def.innerType._zod.run(payload2, ctx); + } + const result = def.innerType._zod.run(payload2, ctx); + if (result instanceof Promise) { + return result.then((result2) => { + payload2.value = result2.value; + if (result2.issues.length) { + payload2.value = def.catchValue({ + ...payload2, + error: { + issues: result2.issues.map((iss) => finalizeIssue(iss, ctx, config())) + }, + input: payload2.value + }); + payload2.issues = []; + } + return payload2; + }); + } + payload2.value = result.value; + if (result.issues.length) { + payload2.value = def.catchValue({ + ...payload2, + error: { + issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config())) + }, + input: payload2.value + }); + payload2.issues = []; + } + return payload2; + }; + }); + $ZodNaN = /* @__PURE__ */ $constructor("$ZodNaN", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload2, _ctx) => { + if (typeof payload2.value !== "number" || !Number.isNaN(payload2.value)) { + payload2.issues.push({ + input: payload2.value, + inst, + expected: "nan", + code: "invalid_type" + }); + return payload2; + } + return payload2; + }; + }); + $ZodPipe = /* @__PURE__ */ $constructor("$ZodPipe", (inst, def) => { + $ZodType.init(inst, def); + defineLazy(inst._zod, "values", () => def.in._zod.values); + defineLazy(inst._zod, "optin", () => def.in._zod.optin); + defineLazy(inst._zod, "optout", () => def.out._zod.optout); + defineLazy(inst._zod, "propValues", () => def.in._zod.propValues); + inst._zod.parse = (payload2, ctx) => { + if (ctx.direction === "backward") { + const right = def.out._zod.run(payload2, ctx); + if (right instanceof Promise) { + return right.then((right2) => handlePipeResult(right2, def.in, ctx)); + } + return handlePipeResult(right, def.in, ctx); + } + const left = def.in._zod.run(payload2, ctx); + if (left instanceof Promise) { + return left.then((left2) => handlePipeResult(left2, def.out, ctx)); + } + return handlePipeResult(left, def.out, ctx); + }; + }); + $ZodCodec = /* @__PURE__ */ $constructor("$ZodCodec", (inst, def) => { + $ZodType.init(inst, def); + defineLazy(inst._zod, "values", () => def.in._zod.values); + defineLazy(inst._zod, "optin", () => def.in._zod.optin); + defineLazy(inst._zod, "optout", () => def.out._zod.optout); + defineLazy(inst._zod, "propValues", () => def.in._zod.propValues); + inst._zod.parse = (payload2, ctx) => { + const direction = ctx.direction || "forward"; + if (direction === "forward") { + const left = def.in._zod.run(payload2, ctx); + if (left instanceof Promise) { + return left.then((left2) => handleCodecAResult(left2, def, ctx)); + } + return handleCodecAResult(left, def, ctx); + } else { + const right = def.out._zod.run(payload2, ctx); + if (right instanceof Promise) { + return right.then((right2) => handleCodecAResult(right2, def, ctx)); + } + return handleCodecAResult(right, def, ctx); + } + }; + }); + $ZodReadonly = /* @__PURE__ */ $constructor("$ZodReadonly", (inst, def) => { + $ZodType.init(inst, def); + defineLazy(inst._zod, "propValues", () => def.innerType._zod.propValues); + defineLazy(inst._zod, "values", () => def.innerType._zod.values); + defineLazy(inst._zod, "optin", () => def.innerType?._zod?.optin); + defineLazy(inst._zod, "optout", () => def.innerType?._zod?.optout); + inst._zod.parse = (payload2, ctx) => { + if (ctx.direction === "backward") { + return def.innerType._zod.run(payload2, ctx); + } + const result = def.innerType._zod.run(payload2, ctx); + if (result instanceof Promise) { + return result.then(handleReadonlyResult); + } + return handleReadonlyResult(result); + }; + }); + $ZodTemplateLiteral = /* @__PURE__ */ $constructor("$ZodTemplateLiteral", (inst, def) => { + $ZodType.init(inst, def); + const regexParts = []; + for (const part of def.parts) { + if (typeof part === "object" && part !== null) { + if (!part._zod.pattern) { + throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`); + } + const source = part._zod.pattern instanceof RegExp ? part._zod.pattern.source : part._zod.pattern; + if (!source) + throw new Error(`Invalid template literal part: ${part._zod.traits}`); + const start = source.startsWith("^") ? 1 : 0; + const end = source.endsWith("$") ? source.length - 1 : source.length; + regexParts.push(source.slice(start, end)); + } else if (part === null || primitiveTypes.has(typeof part)) { + regexParts.push(escapeRegex(`${part}`)); + } else { + throw new Error(`Invalid template literal part: ${part}`); + } + } + inst._zod.pattern = new RegExp(`^${regexParts.join("")}$`); + inst._zod.parse = (payload2, _ctx) => { + if (typeof payload2.value !== "string") { + payload2.issues.push({ + input: payload2.value, + inst, + expected: "string", + code: "invalid_type" + }); + return payload2; + } + inst._zod.pattern.lastIndex = 0; + if (!inst._zod.pattern.test(payload2.value)) { + payload2.issues.push({ + input: payload2.value, + inst, + code: "invalid_format", + format: def.format ?? "template_literal", + pattern: inst._zod.pattern.source + }); + return payload2; + } + return payload2; + }; + }); + $ZodFunction = /* @__PURE__ */ $constructor("$ZodFunction", (inst, def) => { + $ZodType.init(inst, def); + inst._def = def; + inst._zod.def = def; + inst.implement = (func) => { + if (typeof func !== "function") { + throw new Error("implement() must be called with a function"); + } + return function(...args) { + const parsedArgs = inst._def.input ? parse2(inst._def.input, args) : args; + const result = Reflect.apply(func, this, parsedArgs); + if (inst._def.output) { + return parse2(inst._def.output, result); + } + return result; + }; + }; + inst.implementAsync = (func) => { + if (typeof func !== "function") { + throw new Error("implementAsync() must be called with a function"); + } + return async function(...args) { + const parsedArgs = inst._def.input ? await parseAsync(inst._def.input, args) : args; + const result = await Reflect.apply(func, this, parsedArgs); + if (inst._def.output) { + return await parseAsync(inst._def.output, result); + } + return result; + }; + }; + inst._zod.parse = (payload2, _ctx) => { + if (typeof payload2.value !== "function") { + payload2.issues.push({ + code: "invalid_type", + expected: "function", + input: payload2.value, + inst + }); + return payload2; + } + const hasPromiseOutput = inst._def.output && inst._def.output._zod.def.type === "promise"; + if (hasPromiseOutput) { + payload2.value = inst.implementAsync(payload2.value); + } else { + payload2.value = inst.implement(payload2.value); + } + return payload2; + }; + inst.input = (...args) => { + const F2 = inst.constructor; + if (Array.isArray(args[0])) { + return new F2({ + type: "function", + input: new $ZodTuple({ + type: "tuple", + items: args[0], + rest: args[1] + }), + output: inst._def.output + }); + } + return new F2({ + type: "function", + input: args[0], + output: inst._def.output + }); + }; + inst.output = (output) => { + const F2 = inst.constructor; + return new F2({ + type: "function", + input: inst._def.input, + output + }); + }; + return inst; + }); + $ZodPromise = /* @__PURE__ */ $constructor("$ZodPromise", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload2, ctx) => { + return Promise.resolve(payload2.value).then((inner) => def.innerType._zod.run({ value: inner, issues: [] }, ctx)); + }; + }); + $ZodLazy = /* @__PURE__ */ $constructor("$ZodLazy", (inst, def) => { + $ZodType.init(inst, def); + defineLazy(inst._zod, "innerType", () => def.getter()); + defineLazy(inst._zod, "pattern", () => inst._zod.innerType?._zod?.pattern); + defineLazy(inst._zod, "propValues", () => inst._zod.innerType?._zod?.propValues); + defineLazy(inst._zod, "optin", () => inst._zod.innerType?._zod?.optin ?? void 0); + defineLazy(inst._zod, "optout", () => inst._zod.innerType?._zod?.optout ?? void 0); + inst._zod.parse = (payload2, ctx) => { + const inner = inst._zod.innerType; + return inner._zod.run(payload2, ctx); + }; + }); + $ZodCustom = /* @__PURE__ */ $constructor("$ZodCustom", (inst, def) => { + $ZodCheck.init(inst, def); + $ZodType.init(inst, def); + inst._zod.parse = (payload2, _) => { + return payload2; + }; + inst._zod.check = (payload2) => { + const input = payload2.value; + const r5 = def.fn(input); + if (r5 instanceof Promise) { + return r5.then((r6) => handleRefineResult(r6, payload2, input, inst)); + } + handleRefineResult(r5, payload2, input, inst); + return; + }; + }); + } +}); + +// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ar.js +function ar_default() { + return { + localeError: error2() + }; +} +var error2; +var init_ar = __esm({ + "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ar.js"() { + init_util(); + error2 = () => { + const Sizable = { + string: { unit: "\u062D\u0631\u0641", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, + file: { unit: "\u0628\u0627\u064A\u062A", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, + array: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, + set: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0645\u062F\u062E\u0644", + email: "\u0628\u0631\u064A\u062F \u0625\u0644\u0643\u062A\u0631\u0648\u0646\u064A", + url: "\u0631\u0627\u0628\u0637", + emoji: "\u0625\u064A\u0645\u0648\u062C\u064A", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "\u062A\u0627\u0631\u064A\u062E \u0648\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO", + date: "\u062A\u0627\u0631\u064A\u062E \u0628\u0645\u0639\u064A\u0627\u0631 ISO", + time: "\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO", + duration: "\u0645\u062F\u0629 \u0628\u0645\u0639\u064A\u0627\u0631 ISO", + ipv4: "\u0639\u0646\u0648\u0627\u0646 IPv4", + ipv6: "\u0639\u0646\u0648\u0627\u0646 IPv6", + cidrv4: "\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv4", + cidrv6: "\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv6", + base64: "\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64-encoded", + base64url: "\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64url-encoded", + json_string: "\u0646\u064E\u0635 \u0639\u0644\u0649 \u0647\u064A\u0626\u0629 JSON", + e164: "\u0631\u0642\u0645 \u0647\u0627\u062A\u0641 \u0628\u0645\u0639\u064A\u0627\u0631 E.164", + jwt: "JWT", + template_literal: "\u0645\u062F\u062E\u0644" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 instanceof ${issue2.expected}\u060C \u0648\u0644\u0643\u0646 \u062A\u0645 \u0625\u062F\u062E\u0627\u0644 ${received}`; + } + return `\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${expected}\u060C \u0648\u0644\u0643\u0646 \u062A\u0645 \u0625\u062F\u062E\u0627\u0644 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${stringifyPrimitive(issue2.values[0])}`; + return `\u0627\u062E\u062A\u064A\u0627\u0631 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062A\u0648\u0642\u0639 \u0627\u0646\u062A\u0642\u0627\u0621 \u0623\u062D\u062F \u0647\u0630\u0647 \u0627\u0644\u062E\u064A\u0627\u0631\u0627\u062A: ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return ` \u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${issue2.origin ?? "\u0627\u0644\u0642\u064A\u0645\u0629"} ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "\u0639\u0646\u0635\u0631"}`; + return `\u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${issue2.origin ?? "\u0627\u0644\u0642\u064A\u0645\u0629"} ${adj} ${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${issue2.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${adj} ${issue2.minimum.toString()} ${sizing.unit}`; + } + return `\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${issue2.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${adj} ${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0628\u062F\u0623 \u0628\u0640 "${issue2.prefix}"`; + if (_issue.format === "ends_with") + return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0646\u062A\u0647\u064A \u0628\u0640 "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u062A\u0636\u0645\u0651\u064E\u0646 "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0637\u0627\u0628\u0642 \u0627\u0644\u0646\u0645\u0637 ${_issue.pattern}`; + return `${FormatDictionary[_issue.format] ?? issue2.format} \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644`; + } + case "not_multiple_of": + return `\u0631\u0642\u0645 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0643\u0648\u0646 \u0645\u0646 \u0645\u0636\u0627\u0639\u0641\u0627\u062A ${issue2.divisor}`; + case "unrecognized_keys": + return `\u0645\u0639\u0631\u0641${issue2.keys.length > 1 ? "\u0627\u062A" : ""} \u063A\u0631\u064A\u0628${issue2.keys.length > 1 ? "\u0629" : ""}: ${joinValues(issue2.keys, "\u060C ")}`; + case "invalid_key": + return `\u0645\u0639\u0631\u0641 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${issue2.origin}`; + case "invalid_union": + return "\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644"; + case "invalid_element": + return `\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${issue2.origin}`; + default: + return "\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644"; + } + }; + }; + } +}); + +// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/az.js +function az_default() { + return { + localeError: error3() + }; +} +var error3; +var init_az = __esm({ + "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/az.js"() { + init_util(); + error3 = () => { + const Sizable = { + string: { unit: "simvol", verb: "olmal\u0131d\u0131r" }, + file: { unit: "bayt", verb: "olmal\u0131d\u0131r" }, + array: { unit: "element", verb: "olmal\u0131d\u0131r" }, + set: { unit: "element", verb: "olmal\u0131d\u0131r" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "input", + email: "email address", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO datetime", + date: "ISO date", + time: "ISO time", + duration: "ISO duration", + ipv4: "IPv4 address", + ipv6: "IPv6 address", + cidrv4: "IPv4 range", + cidrv6: "IPv6 range", + base64: "base64-encoded string", + base64url: "base64url-encoded string", + json_string: "JSON string", + e164: "E.164 number", + jwt: "JWT", + template_literal: "input" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n instanceof ${issue2.expected}, daxil olan ${received}`; + } + return `Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${expected}, daxil olan ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${stringifyPrimitive(issue2.values[0])}`; + return `Yanl\u0131\u015F se\xE7im: a\u015Fa\u011F\u0131dak\u0131lardan biri olmal\u0131d\u0131r: ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${issue2.origin ?? "d\u0259y\u0259r"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "element"}`; + return `\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${issue2.origin ?? "d\u0259y\u0259r"} ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + return `\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${issue2.origin} ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Yanl\u0131\u015F m\u0259tn: "${_issue.prefix}" il\u0259 ba\u015Flamal\u0131d\u0131r`; + if (_issue.format === "ends_with") + return `Yanl\u0131\u015F m\u0259tn: "${_issue.suffix}" il\u0259 bitm\u0259lidir`; + if (_issue.format === "includes") + return `Yanl\u0131\u015F m\u0259tn: "${_issue.includes}" daxil olmal\u0131d\u0131r`; + if (_issue.format === "regex") + return `Yanl\u0131\u015F m\u0259tn: ${_issue.pattern} \u015Fablonuna uy\u011Fun olmal\u0131d\u0131r`; + return `Yanl\u0131\u015F ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Yanl\u0131\u015F \u0259d\u0259d: ${issue2.divisor} il\u0259 b\xF6l\xFCn\u0259 bil\u0259n olmal\u0131d\u0131r`; + case "unrecognized_keys": + return `Tan\u0131nmayan a\xE7ar${issue2.keys.length > 1 ? "lar" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `${issue2.origin} daxilind\u0259 yanl\u0131\u015F a\xE7ar`; + case "invalid_union": + return "Yanl\u0131\u015F d\u0259y\u0259r"; + case "invalid_element": + return `${issue2.origin} daxilind\u0259 yanl\u0131\u015F d\u0259y\u0259r`; + default: + return `Yanl\u0131\u015F d\u0259y\u0259r`; + } + }; + }; + } +}); + +// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/be.js +function getBelarusianPlural(count2, one, few, many) { + const absCount = Math.abs(count2); + const lastDigit = absCount % 10; + const lastTwoDigits = absCount % 100; + if (lastTwoDigits >= 11 && lastTwoDigits <= 19) { + return many; + } + if (lastDigit === 1) { + return one; + } + if (lastDigit >= 2 && lastDigit <= 4) { + return few; + } + return many; +} +function be_default() { + return { + localeError: error4() + }; +} +var error4; +var init_be = __esm({ + "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/be.js"() { + init_util(); + error4 = () => { + const Sizable = { + string: { + unit: { + one: "\u0441\u0456\u043C\u0432\u0430\u043B", + few: "\u0441\u0456\u043C\u0432\u0430\u043B\u044B", + many: "\u0441\u0456\u043C\u0432\u0430\u043B\u0430\u045E" + }, + verb: "\u043C\u0435\u0446\u044C" + }, + array: { + unit: { + one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442", + few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B", + many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E" + }, + verb: "\u043C\u0435\u0446\u044C" + }, + set: { + unit: { + one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442", + few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B", + many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E" + }, + verb: "\u043C\u0435\u0446\u044C" + }, + file: { + unit: { + one: "\u0431\u0430\u0439\u0442", + few: "\u0431\u0430\u0439\u0442\u044B", + many: "\u0431\u0430\u0439\u0442\u0430\u045E" + }, + verb: "\u043C\u0435\u0446\u044C" + } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0443\u0432\u043E\u0434", + email: "email \u0430\u0434\u0440\u0430\u0441", + url: "URL", + emoji: "\u044D\u043C\u043E\u0434\u0437\u0456", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u0434\u0430\u0442\u0430 \u0456 \u0447\u0430\u0441", + date: "ISO \u0434\u0430\u0442\u0430", + time: "ISO \u0447\u0430\u0441", + duration: "ISO \u043F\u0440\u0430\u0446\u044F\u0433\u043B\u0430\u0441\u0446\u044C", + ipv4: "IPv4 \u0430\u0434\u0440\u0430\u0441", + ipv6: "IPv6 \u0430\u0434\u0440\u0430\u0441", + cidrv4: "IPv4 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D", + cidrv6: "IPv6 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D", + base64: "\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64", + base64url: "\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64url", + json_string: "JSON \u0440\u0430\u0434\u043E\u043A", + e164: "\u043D\u0443\u043C\u0430\u0440 E.164", + jwt: "JWT", + template_literal: "\u0443\u0432\u043E\u0434" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u043B\u0456\u043A", + array: "\u043C\u0430\u0441\u0456\u045E" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u045E\u0441\u044F instanceof ${issue2.expected}, \u0430\u0442\u0440\u044B\u043C\u0430\u043D\u0430 ${received}`; + } + return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u045E\u0441\u044F ${expected}, \u0430\u0442\u0440\u044B\u043C\u0430\u043D\u0430 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F ${stringifyPrimitive(issue2.values[0])}`; + return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0432\u0430\u0440\u044B\u044F\u043D\u0442: \u0447\u0430\u043A\u0430\u045E\u0441\u044F \u0430\u0434\u0437\u0456\u043D \u0437 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) { + const maxValue = Number(issue2.maximum); + const unit = getBelarusianPlural(maxValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); + return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${sizing.verb} ${adj}${issue2.maximum.toString()} ${unit}`; + } + return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + const minValue = Number(issue2.minimum); + const unit = getBelarusianPlural(minValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); + return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue2.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${sizing.verb} ${adj}${issue2.minimum.toString()} ${unit}`; + } + return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue2.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u043F\u0430\u0447\u044B\u043D\u0430\u0446\u0446\u0430 \u0437 "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u0430\u043A\u0430\u043D\u0447\u0432\u0430\u0446\u0446\u0430 \u043D\u0430 "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u043C\u044F\u0448\u0447\u0430\u0446\u044C "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0430\u0434\u043F\u0430\u0432\u044F\u0434\u0430\u0446\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${_issue.pattern}`; + return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043B\u0456\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0431\u044B\u0446\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${issue2.divisor}`; + case "unrecognized_keys": + return `\u041D\u0435\u0440\u0430\u0441\u043F\u0430\u0437\u043D\u0430\u043D\u044B ${issue2.keys.length > 1 ? "\u043A\u043B\u044E\u0447\u044B" : "\u043A\u043B\u044E\u0447"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043A\u043B\u044E\u0447 \u0443 ${issue2.origin}`; + case "invalid_union": + return "\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434"; + case "invalid_element": + return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u0430\u0435 \u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435 \u045E ${issue2.origin}`; + default: + return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434`; + } + }; + }; + } +}); + +// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/bg.js +function bg_default() { + return { + localeError: error5() + }; +} +var error5; +var init_bg = __esm({ + "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/bg.js"() { + init_util(); + error5 = () => { + const Sizable = { + string: { unit: "\u0441\u0438\u043C\u0432\u043E\u043B\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" }, + file: { unit: "\u0431\u0430\u0439\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" }, + array: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" }, + set: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0432\u0445\u043E\u0434", + email: "\u0438\u043C\u0435\u0439\u043B \u0430\u0434\u0440\u0435\u0441", + url: "URL", + emoji: "\u0435\u043C\u043E\u0434\u0436\u0438", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u0432\u0440\u0435\u043C\u0435", + date: "ISO \u0434\u0430\u0442\u0430", + time: "ISO \u0432\u0440\u0435\u043C\u0435", + duration: "ISO \u043F\u0440\u043E\u0434\u044A\u043B\u0436\u0438\u0442\u0435\u043B\u043D\u043E\u0441\u0442", + ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441", + ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441", + cidrv4: "IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", + cidrv6: "IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", + base64: "base64-\u043A\u043E\u0434\u0438\u0440\u0430\u043D \u043D\u0438\u0437", + base64url: "base64url-\u043A\u043E\u0434\u0438\u0440\u0430\u043D \u043D\u0438\u0437", + json_string: "JSON \u043D\u0438\u0437", + e164: "E.164 \u043D\u043E\u043C\u0435\u0440", + jwt: "JWT", + template_literal: "\u0432\u0445\u043E\u0434" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u0447\u0438\u0441\u043B\u043E", + array: "\u043C\u0430\u0441\u0438\u0432" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D instanceof ${issue2.expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D ${received}`; + } + return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D ${expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D ${stringifyPrimitive(issue2.values[0])}`; + return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430 \u043E\u043F\u0446\u0438\u044F: \u043E\u0447\u0430\u043A\u0432\u0430\u043D\u043E \u0435\u0434\u043D\u043E \u043E\u0442 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0422\u0432\u044A\u0440\u0434\u0435 \u0433\u043E\u043B\u044F\u043C\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${issue2.origin ?? "\u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442"} \u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430"}`; + return `\u0422\u0432\u044A\u0440\u0434\u0435 \u0433\u043E\u043B\u044F\u043C\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${issue2.origin ?? "\u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442"} \u0434\u0430 \u0431\u044A\u0434\u0435 ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0422\u0432\u044A\u0440\u0434\u0435 \u043C\u0430\u043B\u043A\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${issue2.origin} \u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430 ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `\u0422\u0432\u044A\u0440\u0434\u0435 \u043C\u0430\u043B\u043A\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${issue2.origin} \u0434\u0430 \u0431\u044A\u0434\u0435 ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0437\u0430\u043F\u043E\u0447\u0432\u0430 \u0441 "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0437\u0430\u0432\u044A\u0440\u0448\u0432\u0430 \u0441 "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0432\u043A\u043B\u044E\u0447\u0432\u0430 "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0441\u044A\u0432\u043F\u0430\u0434\u0430 \u0441 ${_issue.pattern}`; + let invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D"; + if (_issue.format === "emoji") + invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E"; + if (_issue.format === "datetime") + invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E"; + if (_issue.format === "date") + invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430"; + if (_issue.format === "time") + invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E"; + if (_issue.format === "duration") + invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430"; + return `${invalid_adj} ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E \u0447\u0438\u0441\u043B\u043E: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0431\u044A\u0434\u0435 \u043A\u0440\u0430\u0442\u043D\u043E \u043D\u0430 ${issue2.divisor}`; + case "unrecognized_keys": + return `\u041D\u0435\u0440\u0430\u0437\u043F\u043E\u0437\u043D\u0430\u0442${issue2.keys.length > 1 ? "\u0438" : ""} \u043A\u043B\u044E\u0447${issue2.keys.length > 1 ? "\u043E\u0432\u0435" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043A\u043B\u044E\u0447 \u0432 ${issue2.origin}`; + case "invalid_union": + return "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434"; + case "invalid_element": + return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430 \u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442 \u0432 ${issue2.origin}`; + default: + return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434`; + } + }; + }; + } +}); + +// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ca.js +function ca_default() { + return { + localeError: error6() + }; +} +var error6; +var init_ca = __esm({ + "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ca.js"() { + init_util(); + error6 = () => { + const Sizable = { + string: { unit: "car\xE0cters", verb: "contenir" }, + file: { unit: "bytes", verb: "contenir" }, + array: { unit: "elements", verb: "contenir" }, + set: { unit: "elements", verb: "contenir" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "entrada", + email: "adre\xE7a electr\xF2nica", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "data i hora ISO", + date: "data ISO", + time: "hora ISO", + duration: "durada ISO", + ipv4: "adre\xE7a IPv4", + ipv6: "adre\xE7a IPv6", + cidrv4: "rang IPv4", + cidrv6: "rang IPv6", + base64: "cadena codificada en base64", + base64url: "cadena codificada en base64url", + json_string: "cadena JSON", + e164: "n\xFAmero E.164", + jwt: "JWT", + template_literal: "entrada" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Tipus inv\xE0lid: s'esperava instanceof ${issue2.expected}, s'ha rebut ${received}`; + } + return `Tipus inv\xE0lid: s'esperava ${expected}, s'ha rebut ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Valor inv\xE0lid: s'esperava ${stringifyPrimitive(issue2.values[0])}`; + return `Opci\xF3 inv\xE0lida: s'esperava una de ${joinValues(issue2.values, " o ")}`; + case "too_big": { + const adj = issue2.inclusive ? "com a m\xE0xim" : "menys de"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Massa gran: s'esperava que ${issue2.origin ?? "el valor"} contingu\xE9s ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "elements"}`; + return `Massa gran: s'esperava que ${issue2.origin ?? "el valor"} fos ${adj} ${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? "com a m\xEDnim" : "m\xE9s de"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Massa petit: s'esperava que ${issue2.origin} contingu\xE9s ${adj} ${issue2.minimum.toString()} ${sizing.unit}`; + } + return `Massa petit: s'esperava que ${issue2.origin} fos ${adj} ${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `Format inv\xE0lid: ha de comen\xE7ar amb "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `Format inv\xE0lid: ha d'acabar amb "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Format inv\xE0lid: ha d'incloure "${_issue.includes}"`; + if (_issue.format === "regex") + return `Format inv\xE0lid: ha de coincidir amb el patr\xF3 ${_issue.pattern}`; + return `Format inv\xE0lid per a ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `N\xFAmero inv\xE0lid: ha de ser m\xFAltiple de ${issue2.divisor}`; + case "unrecognized_keys": + return `Clau${issue2.keys.length > 1 ? "s" : ""} no reconeguda${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Clau inv\xE0lida a ${issue2.origin}`; + case "invalid_union": + return "Entrada inv\xE0lida"; + // Could also be "Tipus d'unió invàlid" but "Entrada invàlida" is more general + case "invalid_element": + return `Element inv\xE0lid a ${issue2.origin}`; + default: + return `Entrada inv\xE0lida`; + } + }; + }; + } +}); + +// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/cs.js +function cs_default() { + return { + localeError: error7() + }; +} +var error7; +var init_cs = __esm({ + "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/cs.js"() { + init_util(); + error7 = () => { + const Sizable = { + string: { unit: "znak\u016F", verb: "m\xEDt" }, + file: { unit: "bajt\u016F", verb: "m\xEDt" }, + array: { unit: "prvk\u016F", verb: "m\xEDt" }, + set: { unit: "prvk\u016F", verb: "m\xEDt" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "regul\xE1rn\xED v\xFDraz", + email: "e-mailov\xE1 adresa", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "datum a \u010Das ve form\xE1tu ISO", + date: "datum ve form\xE1tu ISO", + time: "\u010Das ve form\xE1tu ISO", + duration: "doba trv\xE1n\xED ISO", + ipv4: "IPv4 adresa", + ipv6: "IPv6 adresa", + cidrv4: "rozsah IPv4", + cidrv6: "rozsah IPv6", + base64: "\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64", + base64url: "\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64url", + json_string: "\u0159et\u011Bzec ve form\xE1tu JSON", + e164: "\u010D\xEDslo E.164", + jwt: "JWT", + template_literal: "vstup" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u010D\xEDslo", + string: "\u0159et\u011Bzec", + function: "funkce", + array: "pole" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no instanceof ${issue2.expected}, obdr\u017Eeno ${received}`; + } + return `Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${expected}, obdr\u017Eeno ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${stringifyPrimitive(issue2.values[0])}`; + return `Neplatn\xE1 mo\u017Enost: o\u010Dek\xE1v\xE1na jedna z hodnot ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${issue2.origin ?? "hodnota"} mus\xED m\xEDt ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "prvk\u016F"}`; + } + return `Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${issue2.origin ?? "hodnota"} mus\xED b\xFDt ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${issue2.origin ?? "hodnota"} mus\xED m\xEDt ${adj}${issue2.minimum.toString()} ${sizing.unit ?? "prvk\u016F"}`; + } + return `Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${issue2.origin ?? "hodnota"} mus\xED b\xFDt ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Neplatn\xFD \u0159et\u011Bzec: mus\xED za\u010D\xEDnat na "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Neplatn\xFD \u0159et\u011Bzec: mus\xED kon\u010Dit na "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Neplatn\xFD \u0159et\u011Bzec: mus\xED obsahovat "${_issue.includes}"`; + if (_issue.format === "regex") + return `Neplatn\xFD \u0159et\u011Bzec: mus\xED odpov\xEDdat vzoru ${_issue.pattern}`; + return `Neplatn\xFD form\xE1t ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Neplatn\xE9 \u010D\xEDslo: mus\xED b\xFDt n\xE1sobkem ${issue2.divisor}`; + case "unrecognized_keys": + return `Nezn\xE1m\xE9 kl\xED\u010De: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Neplatn\xFD kl\xED\u010D v ${issue2.origin}`; + case "invalid_union": + return "Neplatn\xFD vstup"; + case "invalid_element": + return `Neplatn\xE1 hodnota v ${issue2.origin}`; + default: + return `Neplatn\xFD vstup`; + } + }; + }; + } +}); + +// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/da.js +function da_default() { + return { + localeError: error8() + }; +} +var error8; +var init_da = __esm({ + "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/da.js"() { + init_util(); + error8 = () => { + const Sizable = { + string: { unit: "tegn", verb: "havde" }, + file: { unit: "bytes", verb: "havde" }, + array: { unit: "elementer", verb: "indeholdt" }, + set: { unit: "elementer", verb: "indeholdt" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "input", + email: "e-mailadresse", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO dato- og klokkesl\xE6t", + date: "ISO-dato", + time: "ISO-klokkesl\xE6t", + duration: "ISO-varighed", + ipv4: "IPv4-omr\xE5de", + ipv6: "IPv6-omr\xE5de", + cidrv4: "IPv4-spektrum", + cidrv6: "IPv6-spektrum", + base64: "base64-kodet streng", + base64url: "base64url-kodet streng", + json_string: "JSON-streng", + e164: "E.164-nummer", + jwt: "JWT", + template_literal: "input" + }; + const TypeDictionary = { + nan: "NaN", + string: "streng", + number: "tal", + boolean: "boolean", + array: "liste", + object: "objekt", + set: "s\xE6t", + file: "fil" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Ugyldigt input: forventede instanceof ${issue2.expected}, fik ${received}`; + } + return `Ugyldigt input: forventede ${expected}, fik ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Ugyldig v\xE6rdi: forventede ${stringifyPrimitive(issue2.values[0])}`; + return `Ugyldigt valg: forventede en af f\xF8lgende ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + const origin = TypeDictionary[issue2.origin] ?? issue2.origin; + if (sizing) + return `For stor: forventede ${origin ?? "value"} ${sizing.verb} ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "elementer"}`; + return `For stor: forventede ${origin ?? "value"} havde ${adj} ${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + const origin = TypeDictionary[issue2.origin] ?? issue2.origin; + if (sizing) { + return `For lille: forventede ${origin} ${sizing.verb} ${adj} ${issue2.minimum.toString()} ${sizing.unit}`; + } + return `For lille: forventede ${origin} havde ${adj} ${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Ugyldig streng: skal starte med "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Ugyldig streng: skal ende med "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Ugyldig streng: skal indeholde "${_issue.includes}"`; + if (_issue.format === "regex") + return `Ugyldig streng: skal matche m\xF8nsteret ${_issue.pattern}`; + return `Ugyldig ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Ugyldigt tal: skal v\xE6re deleligt med ${issue2.divisor}`; + case "unrecognized_keys": + return `${issue2.keys.length > 1 ? "Ukendte n\xF8gler" : "Ukendt n\xF8gle"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Ugyldig n\xF8gle i ${issue2.origin}`; + case "invalid_union": + return "Ugyldigt input: matcher ingen af de tilladte typer"; + case "invalid_element": + return `Ugyldig v\xE6rdi i ${issue2.origin}`; + default: + return `Ugyldigt input`; + } + }; + }; + } +}); + +// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/de.js +function de_default() { + return { + localeError: error9() + }; +} +var error9; +var init_de = __esm({ + "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/de.js"() { + init_util(); + error9 = () => { + const Sizable = { + string: { unit: "Zeichen", verb: "zu haben" }, + file: { unit: "Bytes", verb: "zu haben" }, + array: { unit: "Elemente", verb: "zu haben" }, + set: { unit: "Elemente", verb: "zu haben" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "Eingabe", + email: "E-Mail-Adresse", + url: "URL", + emoji: "Emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO-Datum und -Uhrzeit", + date: "ISO-Datum", + time: "ISO-Uhrzeit", + duration: "ISO-Dauer", + ipv4: "IPv4-Adresse", + ipv6: "IPv6-Adresse", + cidrv4: "IPv4-Bereich", + cidrv6: "IPv6-Bereich", + base64: "Base64-codierter String", + base64url: "Base64-URL-codierter String", + json_string: "JSON-String", + e164: "E.164-Nummer", + jwt: "JWT", + template_literal: "Eingabe" + }; + const TypeDictionary = { + nan: "NaN", + number: "Zahl", + array: "Array" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Ung\xFCltige Eingabe: erwartet instanceof ${issue2.expected}, erhalten ${received}`; + } + return `Ung\xFCltige Eingabe: erwartet ${expected}, erhalten ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Ung\xFCltige Eingabe: erwartet ${stringifyPrimitive(issue2.values[0])}`; + return `Ung\xFCltige Option: erwartet eine von ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Zu gro\xDF: erwartet, dass ${issue2.origin ?? "Wert"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "Elemente"} hat`; + return `Zu gro\xDF: erwartet, dass ${issue2.origin ?? "Wert"} ${adj}${issue2.maximum.toString()} ist`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Zu klein: erwartet, dass ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} hat`; + } + return `Zu klein: erwartet, dass ${issue2.origin} ${adj}${issue2.minimum.toString()} ist`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Ung\xFCltiger String: muss mit "${_issue.prefix}" beginnen`; + if (_issue.format === "ends_with") + return `Ung\xFCltiger String: muss mit "${_issue.suffix}" enden`; + if (_issue.format === "includes") + return `Ung\xFCltiger String: muss "${_issue.includes}" enthalten`; + if (_issue.format === "regex") + return `Ung\xFCltiger String: muss dem Muster ${_issue.pattern} entsprechen`; + return `Ung\xFCltig: ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Ung\xFCltige Zahl: muss ein Vielfaches von ${issue2.divisor} sein`; + case "unrecognized_keys": + return `${issue2.keys.length > 1 ? "Unbekannte Schl\xFCssel" : "Unbekannter Schl\xFCssel"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Ung\xFCltiger Schl\xFCssel in ${issue2.origin}`; + case "invalid_union": + return "Ung\xFCltige Eingabe"; + case "invalid_element": + return `Ung\xFCltiger Wert in ${issue2.origin}`; + default: + return `Ung\xFCltige Eingabe`; + } + }; + }; + } +}); + +// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/en.js +function en_default2() { + return { + localeError: error10() + }; +} +var error10; +var init_en = __esm({ + "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/en.js"() { + init_util(); + error10 = () => { + const Sizable = { + string: { unit: "characters", verb: "to have" }, + file: { unit: "bytes", verb: "to have" }, + array: { unit: "items", verb: "to have" }, + set: { unit: "items", verb: "to have" }, + map: { unit: "entries", verb: "to have" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "input", + email: "email address", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO datetime", + date: "ISO date", + time: "ISO time", + duration: "ISO duration", + ipv4: "IPv4 address", + ipv6: "IPv6 address", + mac: "MAC address", + cidrv4: "IPv4 range", + cidrv6: "IPv6 range", + base64: "base64-encoded string", + base64url: "base64url-encoded string", + json_string: "JSON string", + e164: "E.164 number", + jwt: "JWT", + template_literal: "input" + }; + const TypeDictionary = { + // Compatibility: "nan" -> "NaN" for display + nan: "NaN" + // All other type names omitted - they fall back to raw values via ?? operator + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + return `Invalid input: expected ${expected}, received ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Invalid input: expected ${stringifyPrimitive(issue2.values[0])}`; + return `Invalid option: expected one of ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Too big: expected ${issue2.origin ?? "value"} to have ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elements"}`; + return `Too big: expected ${issue2.origin ?? "value"} to be ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Too small: expected ${issue2.origin} to have ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `Too small: expected ${issue2.origin} to be ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `Invalid string: must start with "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `Invalid string: must end with "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Invalid string: must include "${_issue.includes}"`; + if (_issue.format === "regex") + return `Invalid string: must match pattern ${_issue.pattern}`; + return `Invalid ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Invalid number: must be a multiple of ${issue2.divisor}`; + case "unrecognized_keys": + return `Unrecognized key${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Invalid key in ${issue2.origin}`; + case "invalid_union": + return "Invalid input"; + case "invalid_element": + return `Invalid value in ${issue2.origin}`; + default: + return `Invalid input`; + } + }; + }; + } +}); + +// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/eo.js +function eo_default() { + return { + localeError: error11() + }; +} +var error11; +var init_eo = __esm({ + "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/eo.js"() { + init_util(); + error11 = () => { + const Sizable = { + string: { unit: "karaktrojn", verb: "havi" }, + file: { unit: "bajtojn", verb: "havi" }, + array: { unit: "elementojn", verb: "havi" }, + set: { unit: "elementojn", verb: "havi" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "enigo", + email: "retadreso", + url: "URL", + emoji: "emo\u011Dio", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO-datotempo", + date: "ISO-dato", + time: "ISO-tempo", + duration: "ISO-da\u016Dro", + ipv4: "IPv4-adreso", + ipv6: "IPv6-adreso", + cidrv4: "IPv4-rango", + cidrv6: "IPv6-rango", + base64: "64-ume kodita karaktraro", + base64url: "URL-64-ume kodita karaktraro", + json_string: "JSON-karaktraro", + e164: "E.164-nombro", + jwt: "JWT", + template_literal: "enigo" + }; + const TypeDictionary = { + nan: "NaN", + number: "nombro", + array: "tabelo", + null: "senvalora" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Nevalida enigo: atendi\u011Dis instanceof ${issue2.expected}, ricevi\u011Dis ${received}`; + } + return `Nevalida enigo: atendi\u011Dis ${expected}, ricevi\u011Dis ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Nevalida enigo: atendi\u011Dis ${stringifyPrimitive(issue2.values[0])}`; + return `Nevalida opcio: atendi\u011Dis unu el ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Tro granda: atendi\u011Dis ke ${issue2.origin ?? "valoro"} havu ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementojn"}`; + return `Tro granda: atendi\u011Dis ke ${issue2.origin ?? "valoro"} havu ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Tro malgranda: atendi\u011Dis ke ${issue2.origin} havu ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `Tro malgranda: atendi\u011Dis ke ${issue2.origin} estu ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Nevalida karaktraro: devas komenci\u011Di per "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Nevalida karaktraro: devas fini\u011Di per "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Nevalida karaktraro: devas inkluzivi "${_issue.includes}"`; + if (_issue.format === "regex") + return `Nevalida karaktraro: devas kongrui kun la modelo ${_issue.pattern}`; + return `Nevalida ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Nevalida nombro: devas esti oblo de ${issue2.divisor}`; + case "unrecognized_keys": + return `Nekonata${issue2.keys.length > 1 ? "j" : ""} \u015Dlosilo${issue2.keys.length > 1 ? "j" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Nevalida \u015Dlosilo en ${issue2.origin}`; + case "invalid_union": + return "Nevalida enigo"; + case "invalid_element": + return `Nevalida valoro en ${issue2.origin}`; + default: + return `Nevalida enigo`; + } + }; + }; + } +}); + +// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/es.js +function es_default() { + return { + localeError: error12() + }; +} +var error12; +var init_es = __esm({ + "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/es.js"() { + init_util(); + error12 = () => { + const Sizable = { + string: { unit: "caracteres", verb: "tener" }, + file: { unit: "bytes", verb: "tener" }, + array: { unit: "elementos", verb: "tener" }, + set: { unit: "elementos", verb: "tener" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "entrada", + email: "direcci\xF3n de correo electr\xF3nico", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "fecha y hora ISO", + date: "fecha ISO", + time: "hora ISO", + duration: "duraci\xF3n ISO", + ipv4: "direcci\xF3n IPv4", + ipv6: "direcci\xF3n IPv6", + cidrv4: "rango IPv4", + cidrv6: "rango IPv6", + base64: "cadena codificada en base64", + base64url: "URL codificada en base64", + json_string: "cadena JSON", + e164: "n\xFAmero E.164", + jwt: "JWT", + template_literal: "entrada" + }; + const TypeDictionary = { + nan: "NaN", + string: "texto", + number: "n\xFAmero", + boolean: "booleano", + array: "arreglo", + object: "objeto", + set: "conjunto", + file: "archivo", + date: "fecha", + bigint: "n\xFAmero grande", + symbol: "s\xEDmbolo", + undefined: "indefinido", + null: "nulo", + function: "funci\xF3n", + map: "mapa", + record: "registro", + tuple: "tupla", + enum: "enumeraci\xF3n", + union: "uni\xF3n", + literal: "literal", + promise: "promesa", + void: "vac\xEDo", + never: "nunca", + unknown: "desconocido", + any: "cualquiera" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Entrada inv\xE1lida: se esperaba instanceof ${issue2.expected}, recibido ${received}`; + } + return `Entrada inv\xE1lida: se esperaba ${expected}, recibido ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Entrada inv\xE1lida: se esperaba ${stringifyPrimitive(issue2.values[0])}`; + return `Opci\xF3n inv\xE1lida: se esperaba una de ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + const origin = TypeDictionary[issue2.origin] ?? issue2.origin; + if (sizing) + return `Demasiado grande: se esperaba que ${origin ?? "valor"} tuviera ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementos"}`; + return `Demasiado grande: se esperaba que ${origin ?? "valor"} fuera ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + const origin = TypeDictionary[issue2.origin] ?? issue2.origin; + if (sizing) { + return `Demasiado peque\xF1o: se esperaba que ${origin} tuviera ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `Demasiado peque\xF1o: se esperaba que ${origin} fuera ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Cadena inv\xE1lida: debe comenzar con "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Cadena inv\xE1lida: debe terminar en "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Cadena inv\xE1lida: debe incluir "${_issue.includes}"`; + if (_issue.format === "regex") + return `Cadena inv\xE1lida: debe coincidir con el patr\xF3n ${_issue.pattern}`; + return `Inv\xE1lido ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `N\xFAmero inv\xE1lido: debe ser m\xFAltiplo de ${issue2.divisor}`; + case "unrecognized_keys": + return `Llave${issue2.keys.length > 1 ? "s" : ""} desconocida${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Llave inv\xE1lida en ${TypeDictionary[issue2.origin] ?? issue2.origin}`; + case "invalid_union": + return "Entrada inv\xE1lida"; + case "invalid_element": + return `Valor inv\xE1lido en ${TypeDictionary[issue2.origin] ?? issue2.origin}`; + default: + return `Entrada inv\xE1lida`; + } + }; + }; + } +}); + +// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/fa.js +function fa_default() { + return { + localeError: error13() + }; +} +var error13; +var init_fa = __esm({ + "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/fa.js"() { + init_util(); + error13 = () => { + const Sizable = { + string: { unit: "\u06A9\u0627\u0631\u0627\u06A9\u062A\u0631", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, + file: { unit: "\u0628\u0627\u06CC\u062A", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, + array: { unit: "\u0622\u06CC\u062A\u0645", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, + set: { unit: "\u0622\u06CC\u062A\u0645", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0648\u0631\u0648\u062F\u06CC", + email: "\u0622\u062F\u0631\u0633 \u0627\u06CC\u0645\u06CC\u0644", + url: "URL", + emoji: "\u0627\u06CC\u0645\u0648\u062C\u06CC", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "\u062A\u0627\u0631\u06CC\u062E \u0648 \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648", + date: "\u062A\u0627\u0631\u06CC\u062E \u0627\u06CC\u0632\u0648", + time: "\u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648", + duration: "\u0645\u062F\u062A \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648", + ipv4: "IPv4 \u0622\u062F\u0631\u0633", + ipv6: "IPv6 \u0622\u062F\u0631\u0633", + cidrv4: "IPv4 \u062F\u0627\u0645\u0646\u0647", + cidrv6: "IPv6 \u062F\u0627\u0645\u0646\u0647", + base64: "base64-encoded \u0631\u0634\u062A\u0647", + base64url: "base64url-encoded \u0631\u0634\u062A\u0647", + json_string: "JSON \u0631\u0634\u062A\u0647", + e164: "E.164 \u0639\u062F\u062F", + jwt: "JWT", + template_literal: "\u0648\u0631\u0648\u062F\u06CC" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u0639\u062F\u062F", + array: "\u0622\u0631\u0627\u06CC\u0647" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A instanceof ${issue2.expected} \u0645\u06CC\u200C\u0628\u0648\u062F\u060C ${received} \u062F\u0631\u06CC\u0627\u0641\u062A \u0634\u062F`; + } + return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${expected} \u0645\u06CC\u200C\u0628\u0648\u062F\u060C ${received} \u062F\u0631\u06CC\u0627\u0641\u062A \u0634\u062F`; + } + case "invalid_value": + if (issue2.values.length === 1) { + return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${stringifyPrimitive(issue2.values[0])} \u0645\u06CC\u200C\u0628\u0648\u062F`; + } + return `\u06AF\u0632\u06CC\u0646\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A \u06CC\u06A9\u06CC \u0627\u0632 ${joinValues(issue2.values, "|")} \u0645\u06CC\u200C\u0628\u0648\u062F`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${issue2.origin ?? "\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0639\u0646\u0635\u0631"} \u0628\u0627\u0634\u062F`; + } + return `\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${issue2.origin ?? "\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${adj}${issue2.maximum.toString()} \u0628\u0627\u0634\u062F`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${issue2.origin} \u0628\u0627\u06CC\u062F ${adj}${issue2.minimum.toString()} ${sizing.unit} \u0628\u0627\u0634\u062F`; + } + return `\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${issue2.origin} \u0628\u0627\u06CC\u062F ${adj}${issue2.minimum.toString()} \u0628\u0627\u0634\u062F`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${_issue.prefix}" \u0634\u0631\u0648\u0639 \u0634\u0648\u062F`; + } + if (_issue.format === "ends_with") { + return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${_issue.suffix}" \u062A\u0645\u0627\u0645 \u0634\u0648\u062F`; + } + if (_issue.format === "includes") { + return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0634\u0627\u0645\u0644 "${_issue.includes}" \u0628\u0627\u0634\u062F`; + } + if (_issue.format === "regex") { + return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 \u0627\u0644\u06AF\u0648\u06CC ${_issue.pattern} \u0645\u0637\u0627\u0628\u0642\u062A \u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F`; + } + return `${FormatDictionary[_issue.format] ?? issue2.format} \u0646\u0627\u0645\u0639\u062A\u0628\u0631`; + } + case "not_multiple_of": + return `\u0639\u062F\u062F \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0645\u0636\u0631\u0628 ${issue2.divisor} \u0628\u0627\u0634\u062F`; + case "unrecognized_keys": + return `\u06A9\u0644\u06CC\u062F${issue2.keys.length > 1 ? "\u0647\u0627\u06CC" : ""} \u0646\u0627\u0634\u0646\u0627\u0633: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u06A9\u0644\u06CC\u062F \u0646\u0627\u0634\u0646\u0627\u0633 \u062F\u0631 ${issue2.origin}`; + case "invalid_union": + return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631`; + case "invalid_element": + return `\u0645\u0642\u062F\u0627\u0631 \u0646\u0627\u0645\u0639\u062A\u0628\u0631 \u062F\u0631 ${issue2.origin}`; + default: + return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631`; + } + }; + }; + } +}); + +// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/fi.js +function fi_default() { + return { + localeError: error14() + }; +} +var error14; +var init_fi = __esm({ + "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/fi.js"() { + init_util(); + error14 = () => { + const Sizable = { + string: { unit: "merkki\xE4", subject: "merkkijonon" }, + file: { unit: "tavua", subject: "tiedoston" }, + array: { unit: "alkiota", subject: "listan" }, + set: { unit: "alkiota", subject: "joukon" }, + number: { unit: "", subject: "luvun" }, + bigint: { unit: "", subject: "suuren kokonaisluvun" }, + int: { unit: "", subject: "kokonaisluvun" }, + date: { unit: "", subject: "p\xE4iv\xE4m\xE4\xE4r\xE4n" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "s\xE4\xE4nn\xF6llinen lauseke", + email: "s\xE4hk\xF6postiosoite", + url: "URL-osoite", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO-aikaleima", + date: "ISO-p\xE4iv\xE4m\xE4\xE4r\xE4", + time: "ISO-aika", + duration: "ISO-kesto", + ipv4: "IPv4-osoite", + ipv6: "IPv6-osoite", + cidrv4: "IPv4-alue", + cidrv6: "IPv6-alue", + base64: "base64-koodattu merkkijono", + base64url: "base64url-koodattu merkkijono", + json_string: "JSON-merkkijono", + e164: "E.164-luku", + jwt: "JWT", + template_literal: "templaattimerkkijono" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Virheellinen tyyppi: odotettiin instanceof ${issue2.expected}, oli ${received}`; + } + return `Virheellinen tyyppi: odotettiin ${expected}, oli ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Virheellinen sy\xF6te: t\xE4ytyy olla ${stringifyPrimitive(issue2.values[0])}`; + return `Virheellinen valinta: t\xE4ytyy olla yksi seuraavista: ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Liian suuri: ${sizing.subject} t\xE4ytyy olla ${adj}${issue2.maximum.toString()} ${sizing.unit}`.trim(); + } + return `Liian suuri: arvon t\xE4ytyy olla ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Liian pieni: ${sizing.subject} t\xE4ytyy olla ${adj}${issue2.minimum.toString()} ${sizing.unit}`.trim(); + } + return `Liian pieni: arvon t\xE4ytyy olla ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Virheellinen sy\xF6te: t\xE4ytyy alkaa "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Virheellinen sy\xF6te: t\xE4ytyy loppua "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Virheellinen sy\xF6te: t\xE4ytyy sis\xE4lt\xE4\xE4 "${_issue.includes}"`; + if (_issue.format === "regex") { + return `Virheellinen sy\xF6te: t\xE4ytyy vastata s\xE4\xE4nn\xF6llist\xE4 lauseketta ${_issue.pattern}`; + } + return `Virheellinen ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Virheellinen luku: t\xE4ytyy olla luvun ${issue2.divisor} monikerta`; + case "unrecognized_keys": + return `${issue2.keys.length > 1 ? "Tuntemattomat avaimet" : "Tuntematon avain"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return "Virheellinen avain tietueessa"; + case "invalid_union": + return "Virheellinen unioni"; + case "invalid_element": + return "Virheellinen arvo joukossa"; + default: + return `Virheellinen sy\xF6te`; + } + }; + }; + } +}); + +// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/fr.js +function fr_default() { + return { + localeError: error15() + }; +} +var error15; +var init_fr = __esm({ + "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/fr.js"() { + init_util(); + error15 = () => { + const Sizable = { + string: { unit: "caract\xE8res", verb: "avoir" }, + file: { unit: "octets", verb: "avoir" }, + array: { unit: "\xE9l\xE9ments", verb: "avoir" }, + set: { unit: "\xE9l\xE9ments", verb: "avoir" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "entr\xE9e", + email: "adresse e-mail", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "date et heure ISO", + date: "date ISO", + time: "heure ISO", + duration: "dur\xE9e ISO", + ipv4: "adresse IPv4", + ipv6: "adresse IPv6", + cidrv4: "plage IPv4", + cidrv6: "plage IPv6", + base64: "cha\xEEne encod\xE9e en base64", + base64url: "cha\xEEne encod\xE9e en base64url", + json_string: "cha\xEEne JSON", + e164: "num\xE9ro E.164", + jwt: "JWT", + template_literal: "entr\xE9e" + }; + const TypeDictionary = { + nan: "NaN", + number: "nombre", + array: "tableau" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Entr\xE9e invalide : instanceof ${issue2.expected} attendu, ${received} re\xE7u`; + } + return `Entr\xE9e invalide : ${expected} attendu, ${received} re\xE7u`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Entr\xE9e invalide : ${stringifyPrimitive(issue2.values[0])} attendu`; + return `Option invalide : une valeur parmi ${joinValues(issue2.values, "|")} attendue`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Trop grand : ${issue2.origin ?? "valeur"} doit ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\xE9l\xE9ment(s)"}`; + return `Trop grand : ${issue2.origin ?? "valeur"} doit \xEAtre ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Trop petit : ${issue2.origin} doit ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `Trop petit : ${issue2.origin} doit \xEAtre ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Cha\xEEne invalide : doit commencer par "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Cha\xEEne invalide : doit se terminer par "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Cha\xEEne invalide : doit inclure "${_issue.includes}"`; + if (_issue.format === "regex") + return `Cha\xEEne invalide : doit correspondre au mod\xE8le ${_issue.pattern}`; + return `${FormatDictionary[_issue.format] ?? issue2.format} invalide`; + } + case "not_multiple_of": + return `Nombre invalide : doit \xEAtre un multiple de ${issue2.divisor}`; + case "unrecognized_keys": + return `Cl\xE9${issue2.keys.length > 1 ? "s" : ""} non reconnue${issue2.keys.length > 1 ? "s" : ""} : ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Cl\xE9 invalide dans ${issue2.origin}`; + case "invalid_union": + return "Entr\xE9e invalide"; + case "invalid_element": + return `Valeur invalide dans ${issue2.origin}`; + default: + return `Entr\xE9e invalide`; + } + }; + }; + } +}); + +// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/fr-CA.js +function fr_CA_default() { + return { + localeError: error16() + }; +} +var error16; +var init_fr_CA = __esm({ + "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/fr-CA.js"() { + init_util(); + error16 = () => { + const Sizable = { + string: { unit: "caract\xE8res", verb: "avoir" }, + file: { unit: "octets", verb: "avoir" }, + array: { unit: "\xE9l\xE9ments", verb: "avoir" }, + set: { unit: "\xE9l\xE9ments", verb: "avoir" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "entr\xE9e", + email: "adresse courriel", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "date-heure ISO", + date: "date ISO", + time: "heure ISO", + duration: "dur\xE9e ISO", + ipv4: "adresse IPv4", + ipv6: "adresse IPv6", + cidrv4: "plage IPv4", + cidrv6: "plage IPv6", + base64: "cha\xEEne encod\xE9e en base64", + base64url: "cha\xEEne encod\xE9e en base64url", + json_string: "cha\xEEne JSON", + e164: "num\xE9ro E.164", + jwt: "JWT", + template_literal: "entr\xE9e" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Entr\xE9e invalide : attendu instanceof ${issue2.expected}, re\xE7u ${received}`; + } + return `Entr\xE9e invalide : attendu ${expected}, re\xE7u ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Entr\xE9e invalide : attendu ${stringifyPrimitive(issue2.values[0])}`; + return `Option invalide : attendu l'une des valeurs suivantes ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "\u2264" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Trop grand : attendu que ${issue2.origin ?? "la valeur"} ait ${adj}${issue2.maximum.toString()} ${sizing.unit}`; + return `Trop grand : attendu que ${issue2.origin ?? "la valeur"} soit ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? "\u2265" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Trop petit : attendu que ${issue2.origin} ait ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `Trop petit : attendu que ${issue2.origin} soit ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `Cha\xEEne invalide : doit commencer par "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `Cha\xEEne invalide : doit se terminer par "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Cha\xEEne invalide : doit inclure "${_issue.includes}"`; + if (_issue.format === "regex") + return `Cha\xEEne invalide : doit correspondre au motif ${_issue.pattern}`; + return `${FormatDictionary[_issue.format] ?? issue2.format} invalide`; + } + case "not_multiple_of": + return `Nombre invalide : doit \xEAtre un multiple de ${issue2.divisor}`; + case "unrecognized_keys": + return `Cl\xE9${issue2.keys.length > 1 ? "s" : ""} non reconnue${issue2.keys.length > 1 ? "s" : ""} : ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Cl\xE9 invalide dans ${issue2.origin}`; + case "invalid_union": + return "Entr\xE9e invalide"; + case "invalid_element": + return `Valeur invalide dans ${issue2.origin}`; + default: + return `Entr\xE9e invalide`; + } + }; + }; + } +}); + +// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/he.js +function he_default() { + return { + localeError: error17() + }; +} +var error17; +var init_he = __esm({ + "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/he.js"() { + init_util(); + error17 = () => { + const TypeNames = { + string: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA", gender: "f" }, + number: { label: "\u05DE\u05E1\u05E4\u05E8", gender: "m" }, + boolean: { label: "\u05E2\u05E8\u05DA \u05D1\u05D5\u05DC\u05D9\u05D0\u05E0\u05D9", gender: "m" }, + bigint: { label: "BigInt", gender: "m" }, + date: { label: "\u05EA\u05D0\u05E8\u05D9\u05DA", gender: "m" }, + array: { label: "\u05DE\u05E2\u05E8\u05DA", gender: "m" }, + object: { label: "\u05D0\u05D5\u05D1\u05D9\u05D9\u05E7\u05D8", gender: "m" }, + null: { label: "\u05E2\u05E8\u05DA \u05E8\u05D9\u05E7 (null)", gender: "m" }, + undefined: { label: "\u05E2\u05E8\u05DA \u05DC\u05D0 \u05DE\u05D5\u05D2\u05D3\u05E8 (undefined)", gender: "m" }, + symbol: { label: "\u05E1\u05D9\u05DE\u05D1\u05D5\u05DC (Symbol)", gender: "m" }, + function: { label: "\u05E4\u05D5\u05E0\u05E7\u05E6\u05D9\u05D4", gender: "f" }, + map: { label: "\u05DE\u05E4\u05D4 (Map)", gender: "f" }, + set: { label: "\u05E7\u05D1\u05D5\u05E6\u05D4 (Set)", gender: "f" }, + file: { label: "\u05E7\u05D5\u05D1\u05E5", gender: "m" }, + promise: { label: "Promise", gender: "m" }, + NaN: { label: "NaN", gender: "m" }, + unknown: { label: "\u05E2\u05E8\u05DA \u05DC\u05D0 \u05D9\u05D3\u05D5\u05E2", gender: "m" }, + value: { label: "\u05E2\u05E8\u05DA", gender: "m" } + }; + const Sizable = { + string: { unit: "\u05EA\u05D5\u05D5\u05D9\u05DD", shortLabel: "\u05E7\u05E6\u05E8", longLabel: "\u05D0\u05E8\u05D5\u05DA" }, + file: { unit: "\u05D1\u05D9\u05D9\u05D8\u05D9\u05DD", shortLabel: "\u05E7\u05D8\u05DF", longLabel: "\u05D2\u05D3\u05D5\u05DC" }, + array: { unit: "\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD", shortLabel: "\u05E7\u05D8\u05DF", longLabel: "\u05D2\u05D3\u05D5\u05DC" }, + set: { unit: "\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD", shortLabel: "\u05E7\u05D8\u05DF", longLabel: "\u05D2\u05D3\u05D5\u05DC" }, + number: { unit: "", shortLabel: "\u05E7\u05D8\u05DF", longLabel: "\u05D2\u05D3\u05D5\u05DC" } + // no unit + }; + const typeEntry = (t5) => t5 ? TypeNames[t5] : void 0; + const typeLabel = (t5) => { + const e5 = typeEntry(t5); + if (e5) + return e5.label; + return t5 ?? TypeNames.unknown.label; + }; + const withDefinite = (t5) => `\u05D4${typeLabel(t5)}`; + const verbFor = (t5) => { + const e5 = typeEntry(t5); + const gender = e5?.gender ?? "m"; + return gender === "f" ? "\u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05D9\u05D5\u05EA" : "\u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA"; + }; + const getSizing = (origin) => { + if (!origin) + return null; + return Sizable[origin] ?? null; + }; + const FormatDictionary = { + regex: { label: "\u05E7\u05DC\u05D8", gender: "m" }, + email: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA \u05D0\u05D9\u05DE\u05D9\u05D9\u05DC", gender: "f" }, + url: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA \u05E8\u05E9\u05EA", gender: "f" }, + emoji: { label: "\u05D0\u05D9\u05DE\u05D5\u05D2'\u05D9", gender: "m" }, + uuid: { label: "UUID", gender: "m" }, + nanoid: { label: "nanoid", gender: "m" }, + guid: { label: "GUID", gender: "m" }, + cuid: { label: "cuid", gender: "m" }, + cuid2: { label: "cuid2", gender: "m" }, + ulid: { label: "ULID", gender: "m" }, + xid: { label: "XID", gender: "m" }, + ksuid: { label: "KSUID", gender: "m" }, + datetime: { label: "\u05EA\u05D0\u05E8\u05D9\u05DA \u05D5\u05D6\u05DE\u05DF ISO", gender: "m" }, + date: { label: "\u05EA\u05D0\u05E8\u05D9\u05DA ISO", gender: "m" }, + time: { label: "\u05D6\u05DE\u05DF ISO", gender: "m" }, + duration: { label: "\u05DE\u05E9\u05DA \u05D6\u05DE\u05DF ISO", gender: "m" }, + ipv4: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA IPv4", gender: "f" }, + ipv6: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA IPv6", gender: "f" }, + cidrv4: { label: "\u05D8\u05D5\u05D5\u05D7 IPv4", gender: "m" }, + cidrv6: { label: "\u05D8\u05D5\u05D5\u05D7 IPv6", gender: "m" }, + base64: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64", gender: "f" }, + base64url: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64 \u05DC\u05DB\u05EA\u05D5\u05D1\u05D5\u05EA \u05E8\u05E9\u05EA", gender: "f" }, + json_string: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA JSON", gender: "f" }, + e164: { label: "\u05DE\u05E1\u05E4\u05E8 E.164", gender: "m" }, + jwt: { label: "JWT", gender: "m" }, + ends_with: { label: "\u05E7\u05DC\u05D8", gender: "m" }, + includes: { label: "\u05E7\u05DC\u05D8", gender: "m" }, + lowercase: { label: "\u05E7\u05DC\u05D8", gender: "m" }, + starts_with: { label: "\u05E7\u05DC\u05D8", gender: "m" }, + uppercase: { label: "\u05E7\u05DC\u05D8", gender: "m" } + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expectedKey = issue2.expected; + const expected = TypeDictionary[expectedKey ?? ""] ?? typeLabel(expectedKey); + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? TypeNames[receivedType]?.label ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA instanceof ${issue2.expected}, \u05D4\u05EA\u05E7\u05D1\u05DC ${received}`; + } + return `\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${expected}, \u05D4\u05EA\u05E7\u05D1\u05DC ${received}`; + } + case "invalid_value": { + if (issue2.values.length === 1) { + return `\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05E2\u05E8\u05DA \u05D7\u05D9\u05D9\u05D1 \u05DC\u05D4\u05D9\u05D5\u05EA ${stringifyPrimitive(issue2.values[0])}`; + } + const stringified = issue2.values.map((v5) => stringifyPrimitive(v5)); + if (issue2.values.length === 2) { + return `\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05D0\u05E4\u05E9\u05E8\u05D5\u05D9\u05D5\u05EA \u05D4\u05DE\u05EA\u05D0\u05D9\u05DE\u05D5\u05EA \u05D4\u05DF ${stringified[0]} \u05D0\u05D5 ${stringified[1]}`; + } + const lastValue = stringified[stringified.length - 1]; + const restValues = stringified.slice(0, -1).join(", "); + return `\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05D0\u05E4\u05E9\u05E8\u05D5\u05D9\u05D5\u05EA \u05D4\u05DE\u05EA\u05D0\u05D9\u05DE\u05D5\u05EA \u05D4\u05DF ${restValues} \u05D0\u05D5 ${lastValue}`; + } + case "too_big": { + const sizing = getSizing(issue2.origin); + const subject = withDefinite(issue2.origin ?? "value"); + if (issue2.origin === "string") { + return `${sizing?.longLabel ?? "\u05D0\u05E8\u05D5\u05DA"} \u05DE\u05D3\u05D9: ${subject} \u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05DB\u05D9\u05DC ${issue2.maximum.toString()} ${sizing?.unit ?? ""} ${issue2.inclusive ? "\u05D0\u05D5 \u05E4\u05D7\u05D5\u05EA" : "\u05DC\u05DB\u05DC \u05D4\u05D9\u05D5\u05EA\u05E8"}`.trim(); + } + if (issue2.origin === "number") { + const comparison = issue2.inclusive ? `\u05E7\u05D8\u05DF \u05D0\u05D5 \u05E9\u05D5\u05D5\u05D4 \u05DC-${issue2.maximum}` : `\u05E7\u05D8\u05DF \u05DE-${issue2.maximum}`; + return `\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${subject} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${comparison}`; + } + if (issue2.origin === "array" || issue2.origin === "set") { + const verb = issue2.origin === "set" ? "\u05E6\u05E8\u05D9\u05DB\u05D4" : "\u05E6\u05E8\u05D9\u05DA"; + const comparison = issue2.inclusive ? `${issue2.maximum} ${sizing?.unit ?? ""} \u05D0\u05D5 \u05E4\u05D7\u05D5\u05EA` : `\u05E4\u05D7\u05D5\u05EA \u05DE-${issue2.maximum} ${sizing?.unit ?? ""}`; + return `\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${subject} ${verb} \u05DC\u05D4\u05DB\u05D9\u05DC ${comparison}`.trim(); + } + const adj = issue2.inclusive ? "<=" : "<"; + const be = verbFor(issue2.origin ?? "value"); + if (sizing?.unit) { + return `${sizing.longLabel} \u05DE\u05D3\u05D9: ${subject} ${be} ${adj}${issue2.maximum.toString()} ${sizing.unit}`; + } + return `${sizing?.longLabel ?? "\u05D2\u05D3\u05D5\u05DC"} \u05DE\u05D3\u05D9: ${subject} ${be} ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const sizing = getSizing(issue2.origin); + const subject = withDefinite(issue2.origin ?? "value"); + if (issue2.origin === "string") { + return `${sizing?.shortLabel ?? "\u05E7\u05E6\u05E8"} \u05DE\u05D3\u05D9: ${subject} \u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05DB\u05D9\u05DC ${issue2.minimum.toString()} ${sizing?.unit ?? ""} ${issue2.inclusive ? "\u05D0\u05D5 \u05D9\u05D5\u05EA\u05E8" : "\u05DC\u05E4\u05D7\u05D5\u05EA"}`.trim(); + } + if (issue2.origin === "number") { + const comparison = issue2.inclusive ? `\u05D2\u05D3\u05D5\u05DC \u05D0\u05D5 \u05E9\u05D5\u05D5\u05D4 \u05DC-${issue2.minimum}` : `\u05D2\u05D3\u05D5\u05DC \u05DE-${issue2.minimum}`; + return `\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${subject} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${comparison}`; + } + if (issue2.origin === "array" || issue2.origin === "set") { + const verb = issue2.origin === "set" ? "\u05E6\u05E8\u05D9\u05DB\u05D4" : "\u05E6\u05E8\u05D9\u05DA"; + if (issue2.minimum === 1 && issue2.inclusive) { + const singularPhrase = issue2.origin === "set" ? "\u05DC\u05E4\u05D7\u05D5\u05EA \u05E4\u05E8\u05D9\u05D8 \u05D0\u05D7\u05D3" : "\u05DC\u05E4\u05D7\u05D5\u05EA \u05E4\u05E8\u05D9\u05D8 \u05D0\u05D7\u05D3"; + return `\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${subject} ${verb} \u05DC\u05D4\u05DB\u05D9\u05DC ${singularPhrase}`; + } + const comparison = issue2.inclusive ? `${issue2.minimum} ${sizing?.unit ?? ""} \u05D0\u05D5 \u05D9\u05D5\u05EA\u05E8` : `\u05D9\u05D5\u05EA\u05E8 \u05DE-${issue2.minimum} ${sizing?.unit ?? ""}`; + return `\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${subject} ${verb} \u05DC\u05D4\u05DB\u05D9\u05DC ${comparison}`.trim(); + } + const adj = issue2.inclusive ? ">=" : ">"; + const be = verbFor(issue2.origin ?? "value"); + if (sizing?.unit) { + return `${sizing.shortLabel} \u05DE\u05D3\u05D9: ${subject} ${be} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `${sizing?.shortLabel ?? "\u05E7\u05D8\u05DF"} \u05DE\u05D3\u05D9: ${subject} ${be} ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D7\u05D9\u05DC \u05D1 "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05E1\u05EA\u05D9\u05D9\u05DD \u05D1 "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05DB\u05DC\u05D5\u05DC "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D0\u05D9\u05DD \u05DC\u05EA\u05D1\u05E0\u05D9\u05EA ${_issue.pattern}`; + const nounEntry = FormatDictionary[_issue.format]; + const noun = nounEntry?.label ?? _issue.format; + const gender = nounEntry?.gender ?? "m"; + const adjective = gender === "f" ? "\u05EA\u05E7\u05D9\u05E0\u05D4" : "\u05EA\u05E7\u05D9\u05DF"; + return `${noun} \u05DC\u05D0 ${adjective}`; + } + case "not_multiple_of": + return `\u05DE\u05E1\u05E4\u05E8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D7\u05D9\u05D9\u05D1 \u05DC\u05D4\u05D9\u05D5\u05EA \u05DE\u05DB\u05E4\u05DC\u05D4 \u05E9\u05DC ${issue2.divisor}`; + case "unrecognized_keys": + return `\u05DE\u05E4\u05EA\u05D7${issue2.keys.length > 1 ? "\u05D5\u05EA" : ""} \u05DC\u05D0 \u05DE\u05D6\u05D5\u05D4${issue2.keys.length > 1 ? "\u05D9\u05DD" : "\u05D4"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": { + return `\u05E9\u05D3\u05D4 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1\u05D0\u05D5\u05D1\u05D9\u05D9\u05E7\u05D8`; + } + case "invalid_union": + return "\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF"; + case "invalid_element": { + const place = withDefinite(issue2.origin ?? "array"); + return `\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1${place}`; + } + default: + return `\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF`; + } + }; + }; + } +}); + +// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/hu.js +function hu_default() { + return { + localeError: error18() + }; +} +var error18; +var init_hu = __esm({ + "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/hu.js"() { + init_util(); + error18 = () => { + const Sizable = { + string: { unit: "karakter", verb: "legyen" }, + file: { unit: "byte", verb: "legyen" }, + array: { unit: "elem", verb: "legyen" }, + set: { unit: "elem", verb: "legyen" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "bemenet", + email: "email c\xEDm", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO id\u0151b\xE9lyeg", + date: "ISO d\xE1tum", + time: "ISO id\u0151", + duration: "ISO id\u0151intervallum", + ipv4: "IPv4 c\xEDm", + ipv6: "IPv6 c\xEDm", + cidrv4: "IPv4 tartom\xE1ny", + cidrv6: "IPv6 tartom\xE1ny", + base64: "base64-k\xF3dolt string", + base64url: "base64url-k\xF3dolt string", + json_string: "JSON string", + e164: "E.164 sz\xE1m", + jwt: "JWT", + template_literal: "bemenet" + }; + const TypeDictionary = { + nan: "NaN", + number: "sz\xE1m", + array: "t\xF6mb" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k instanceof ${issue2.expected}, a kapott \xE9rt\xE9k ${received}`; + } + return `\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${expected}, a kapott \xE9rt\xE9k ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${stringifyPrimitive(issue2.values[0])}`; + return `\xC9rv\xE9nytelen opci\xF3: valamelyik \xE9rt\xE9k v\xE1rt ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `T\xFAl nagy: ${issue2.origin ?? "\xE9rt\xE9k"} m\xE9rete t\xFAl nagy ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elem"}`; + return `T\xFAl nagy: a bemeneti \xE9rt\xE9k ${issue2.origin ?? "\xE9rt\xE9k"} t\xFAl nagy: ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${issue2.origin} m\xE9rete t\xFAl kicsi ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${issue2.origin} t\xFAl kicsi ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\xC9rv\xE9nytelen string: "${_issue.prefix}" \xE9rt\xE9kkel kell kezd\u0151dnie`; + if (_issue.format === "ends_with") + return `\xC9rv\xE9nytelen string: "${_issue.suffix}" \xE9rt\xE9kkel kell v\xE9gz\u0151dnie`; + if (_issue.format === "includes") + return `\xC9rv\xE9nytelen string: "${_issue.includes}" \xE9rt\xE9ket kell tartalmaznia`; + if (_issue.format === "regex") + return `\xC9rv\xE9nytelen string: ${_issue.pattern} mint\xE1nak kell megfelelnie`; + return `\xC9rv\xE9nytelen ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\xC9rv\xE9nytelen sz\xE1m: ${issue2.divisor} t\xF6bbsz\xF6r\xF6s\xE9nek kell lennie`; + case "unrecognized_keys": + return `Ismeretlen kulcs${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\xC9rv\xE9nytelen kulcs ${issue2.origin}`; + case "invalid_union": + return "\xC9rv\xE9nytelen bemenet"; + case "invalid_element": + return `\xC9rv\xE9nytelen \xE9rt\xE9k: ${issue2.origin}`; + default: + return `\xC9rv\xE9nytelen bemenet`; + } + }; + }; + } +}); + +// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/hy.js +function getArmenianPlural(count2, one, many) { + return Math.abs(count2) === 1 ? one : many; +} +function withDefiniteArticle(word) { + if (!word) + return ""; + const vowels = ["\u0561", "\u0565", "\u0568", "\u056B", "\u0578", "\u0578\u0582", "\u0585"]; + const lastChar = word[word.length - 1]; + return word + (vowels.includes(lastChar) ? "\u0576" : "\u0568"); +} +function hy_default() { + return { + localeError: error19() + }; +} +var error19; +var init_hy = __esm({ + "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/hy.js"() { + init_util(); + error19 = () => { + const Sizable = { + string: { + unit: { + one: "\u0576\u0577\u0561\u0576", + many: "\u0576\u0577\u0561\u0576\u0576\u0565\u0580" + }, + verb: "\u0578\u0582\u0576\u0565\u0576\u0561\u056C" + }, + file: { + unit: { + one: "\u0562\u0561\u0575\u0569", + many: "\u0562\u0561\u0575\u0569\u0565\u0580" + }, + verb: "\u0578\u0582\u0576\u0565\u0576\u0561\u056C" + }, + array: { + unit: { + one: "\u057F\u0561\u0580\u0580", + many: "\u057F\u0561\u0580\u0580\u0565\u0580" + }, + verb: "\u0578\u0582\u0576\u0565\u0576\u0561\u056C" + }, + set: { + unit: { + one: "\u057F\u0561\u0580\u0580", + many: "\u057F\u0561\u0580\u0580\u0565\u0580" + }, + verb: "\u0578\u0582\u0576\u0565\u0576\u0561\u056C" + } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0574\u0578\u0582\u057F\u0584", + email: "\u0567\u056C. \u0570\u0561\u057D\u0581\u0565", + url: "URL", + emoji: "\u0567\u0574\u0578\u057B\u056B", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u0561\u0574\u057D\u0561\u0569\u056B\u057E \u0587 \u056A\u0561\u0574", + date: "ISO \u0561\u0574\u057D\u0561\u0569\u056B\u057E", + time: "ISO \u056A\u0561\u0574", + duration: "ISO \u057F\u0587\u0578\u0572\u0578\u0582\u0569\u0575\u0578\u0582\u0576", + ipv4: "IPv4 \u0570\u0561\u057D\u0581\u0565", + ipv6: "IPv6 \u0570\u0561\u057D\u0581\u0565", + cidrv4: "IPv4 \u0574\u056B\u057B\u0561\u056F\u0561\u0575\u0584", + cidrv6: "IPv6 \u0574\u056B\u057B\u0561\u056F\u0561\u0575\u0584", + base64: "base64 \u0571\u0587\u0561\u0579\u0561\u0583\u0578\u057E \u057F\u0578\u0572", + base64url: "base64url \u0571\u0587\u0561\u0579\u0561\u0583\u0578\u057E \u057F\u0578\u0572", + json_string: "JSON \u057F\u0578\u0572", + e164: "E.164 \u0570\u0561\u0574\u0561\u0580", + jwt: "JWT", + template_literal: "\u0574\u0578\u0582\u057F\u0584" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u0569\u056B\u057E", + array: "\u0566\u0561\u0576\u0563\u057E\u0561\u056E" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 instanceof ${issue2.expected}, \u057D\u057F\u0561\u0581\u057E\u0565\u056C \u0567 ${received}`; + } + return `\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 ${expected}, \u057D\u057F\u0561\u0581\u057E\u0565\u056C \u0567 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 ${stringifyPrimitive(issue2.values[1])}`; + return `\u054D\u056D\u0561\u056C \u057F\u0561\u0580\u0562\u0565\u0580\u0561\u056F\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 \u0570\u0565\u057F\u0587\u0575\u0561\u056C\u0576\u0565\u0580\u056B\u0581 \u0574\u0565\u056F\u0568\u055D ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) { + const maxValue = Number(issue2.maximum); + const unit = getArmenianPlural(maxValue, sizing.unit.one, sizing.unit.many); + return `\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0574\u0565\u056E \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${withDefiniteArticle(issue2.origin ?? "\u0561\u0580\u056A\u0565\u0584")} \u056F\u0578\u0582\u0576\u0565\u0576\u0561 ${adj}${issue2.maximum.toString()} ${unit}`; + } + return `\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0574\u0565\u056E \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${withDefiniteArticle(issue2.origin ?? "\u0561\u0580\u056A\u0565\u0584")} \u056C\u056B\u0576\u056B ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + const minValue = Number(issue2.minimum); + const unit = getArmenianPlural(minValue, sizing.unit.one, sizing.unit.many); + return `\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0583\u0578\u0584\u0580 \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${withDefiniteArticle(issue2.origin)} \u056F\u0578\u0582\u0576\u0565\u0576\u0561 ${adj}${issue2.minimum.toString()} ${unit}`; + } + return `\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0583\u0578\u0584\u0580 \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${withDefiniteArticle(issue2.origin)} \u056C\u056B\u0576\u056B ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u057D\u056F\u057D\u057E\u056B "${_issue.prefix}"-\u0578\u057E`; + if (_issue.format === "ends_with") + return `\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0561\u057E\u0561\u0580\u057F\u057E\u056B "${_issue.suffix}"-\u0578\u057E`; + if (_issue.format === "includes") + return `\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u057A\u0561\u0580\u0578\u0582\u0576\u0561\u056F\u056B "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0570\u0561\u0574\u0561\u057A\u0561\u057F\u0561\u057D\u056D\u0561\u0576\u056B ${_issue.pattern} \u0571\u0587\u0561\u0579\u0561\u0583\u056B\u0576`; + return `\u054D\u056D\u0561\u056C ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u054D\u056D\u0561\u056C \u0569\u056B\u057E\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0562\u0561\u0566\u0574\u0561\u057A\u0561\u057F\u056B\u056F \u056C\u056B\u0576\u056B ${issue2.divisor}-\u056B`; + case "unrecognized_keys": + return `\u0549\u0573\u0561\u0576\u0561\u0579\u057E\u0561\u056E \u0562\u0561\u0576\u0561\u056C\u056B${issue2.keys.length > 1 ? "\u0576\u0565\u0580" : ""}. ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u054D\u056D\u0561\u056C \u0562\u0561\u0576\u0561\u056C\u056B ${withDefiniteArticle(issue2.origin)}-\u0578\u0582\u0574`; + case "invalid_union": + return "\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574"; + case "invalid_element": + return `\u054D\u056D\u0561\u056C \u0561\u0580\u056A\u0565\u0584 ${withDefiniteArticle(issue2.origin)}-\u0578\u0582\u0574`; + default: + return `\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574`; + } + }; + }; + } +}); + +// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/id.js +function id_default() { + return { + localeError: error20() + }; +} +var error20; +var init_id2 = __esm({ + "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/id.js"() { + init_util(); + error20 = () => { + const Sizable = { + string: { unit: "karakter", verb: "memiliki" }, + file: { unit: "byte", verb: "memiliki" }, + array: { unit: "item", verb: "memiliki" }, + set: { unit: "item", verb: "memiliki" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "input", + email: "alamat email", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "tanggal dan waktu format ISO", + date: "tanggal format ISO", + time: "jam format ISO", + duration: "durasi format ISO", + ipv4: "alamat IPv4", + ipv6: "alamat IPv6", + cidrv4: "rentang alamat IPv4", + cidrv6: "rentang alamat IPv6", + base64: "string dengan enkode base64", + base64url: "string dengan enkode base64url", + json_string: "string JSON", + e164: "angka E.164", + jwt: "JWT", + template_literal: "input" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Input tidak valid: diharapkan instanceof ${issue2.expected}, diterima ${received}`; + } + return `Input tidak valid: diharapkan ${expected}, diterima ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Input tidak valid: diharapkan ${stringifyPrimitive(issue2.values[0])}`; + return `Pilihan tidak valid: diharapkan salah satu dari ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Terlalu besar: diharapkan ${issue2.origin ?? "value"} memiliki ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elemen"}`; + return `Terlalu besar: diharapkan ${issue2.origin ?? "value"} menjadi ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Terlalu kecil: diharapkan ${issue2.origin} memiliki ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `Terlalu kecil: diharapkan ${issue2.origin} menjadi ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `String tidak valid: harus dimulai dengan "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `String tidak valid: harus berakhir dengan "${_issue.suffix}"`; + if (_issue.format === "includes") + return `String tidak valid: harus menyertakan "${_issue.includes}"`; + if (_issue.format === "regex") + return `String tidak valid: harus sesuai pola ${_issue.pattern}`; + return `${FormatDictionary[_issue.format] ?? issue2.format} tidak valid`; + } + case "not_multiple_of": + return `Angka tidak valid: harus kelipatan dari ${issue2.divisor}`; + case "unrecognized_keys": + return `Kunci tidak dikenali ${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Kunci tidak valid di ${issue2.origin}`; + case "invalid_union": + return "Input tidak valid"; + case "invalid_element": + return `Nilai tidak valid di ${issue2.origin}`; + default: + return `Input tidak valid`; + } + }; + }; + } +}); + +// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/is.js +function is_default() { + return { + localeError: error21() + }; +} +var error21; +var init_is = __esm({ + "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/is.js"() { + init_util(); + error21 = () => { + const Sizable = { + string: { unit: "stafi", verb: "a\xF0 hafa" }, + file: { unit: "b\xE6ti", verb: "a\xF0 hafa" }, + array: { unit: "hluti", verb: "a\xF0 hafa" }, + set: { unit: "hluti", verb: "a\xF0 hafa" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "gildi", + email: "netfang", + url: "vefsl\xF3\xF0", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO dagsetning og t\xEDmi", + date: "ISO dagsetning", + time: "ISO t\xEDmi", + duration: "ISO t\xEDmalengd", + ipv4: "IPv4 address", + ipv6: "IPv6 address", + cidrv4: "IPv4 range", + cidrv6: "IPv6 range", + base64: "base64-encoded strengur", + base64url: "base64url-encoded strengur", + json_string: "JSON strengur", + e164: "E.164 t\xF6lugildi", + jwt: "JWT", + template_literal: "gildi" + }; + const TypeDictionary = { + nan: "NaN", + number: "n\xFAmer", + array: "fylki" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Rangt gildi: \xDE\xFA sl\xF3st inn ${received} \xFEar sem \xE1 a\xF0 vera instanceof ${issue2.expected}`; + } + return `Rangt gildi: \xDE\xFA sl\xF3st inn ${received} \xFEar sem \xE1 a\xF0 vera ${expected}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Rangt gildi: gert r\xE1\xF0 fyrir ${stringifyPrimitive(issue2.values[0])}`; + return `\xD3gilt val: m\xE1 vera eitt af eftirfarandi ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Of st\xF3rt: gert er r\xE1\xF0 fyrir a\xF0 ${issue2.origin ?? "gildi"} hafi ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "hluti"}`; + return `Of st\xF3rt: gert er r\xE1\xF0 fyrir a\xF0 ${issue2.origin ?? "gildi"} s\xE9 ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Of l\xEDti\xF0: gert er r\xE1\xF0 fyrir a\xF0 ${issue2.origin} hafi ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `Of l\xEDti\xF0: gert er r\xE1\xF0 fyrir a\xF0 ${issue2.origin} s\xE9 ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\xD3gildur strengur: ver\xF0ur a\xF0 byrja \xE1 "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `\xD3gildur strengur: ver\xF0ur a\xF0 enda \xE1 "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\xD3gildur strengur: ver\xF0ur a\xF0 innihalda "${_issue.includes}"`; + if (_issue.format === "regex") + return `\xD3gildur strengur: ver\xF0ur a\xF0 fylgja mynstri ${_issue.pattern}`; + return `Rangt ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `R\xF6ng tala: ver\xF0ur a\xF0 vera margfeldi af ${issue2.divisor}`; + case "unrecognized_keys": + return `\xD3\xFEekkt ${issue2.keys.length > 1 ? "ir lyklar" : "ur lykill"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Rangur lykill \xED ${issue2.origin}`; + case "invalid_union": + return "Rangt gildi"; + case "invalid_element": + return `Rangt gildi \xED ${issue2.origin}`; + default: + return `Rangt gildi`; + } + }; + }; + } +}); + +// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/it.js +function it_default() { + return { + localeError: error22() + }; +} +var error22; +var init_it = __esm({ + "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/it.js"() { + init_util(); + error22 = () => { + const Sizable = { + string: { unit: "caratteri", verb: "avere" }, + file: { unit: "byte", verb: "avere" }, + array: { unit: "elementi", verb: "avere" }, + set: { unit: "elementi", verb: "avere" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "input", + email: "indirizzo email", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "data e ora ISO", + date: "data ISO", + time: "ora ISO", + duration: "durata ISO", + ipv4: "indirizzo IPv4", + ipv6: "indirizzo IPv6", + cidrv4: "intervallo IPv4", + cidrv6: "intervallo IPv6", + base64: "stringa codificata in base64", + base64url: "URL codificata in base64", + json_string: "stringa JSON", + e164: "numero E.164", + jwt: "JWT", + template_literal: "input" + }; + const TypeDictionary = { + nan: "NaN", + number: "numero", + array: "vettore" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Input non valido: atteso instanceof ${issue2.expected}, ricevuto ${received}`; + } + return `Input non valido: atteso ${expected}, ricevuto ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Input non valido: atteso ${stringifyPrimitive(issue2.values[0])}`; + return `Opzione non valida: atteso uno tra ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Troppo grande: ${issue2.origin ?? "valore"} deve avere ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementi"}`; + return `Troppo grande: ${issue2.origin ?? "valore"} deve essere ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Troppo piccolo: ${issue2.origin} deve avere ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `Troppo piccolo: ${issue2.origin} deve essere ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Stringa non valida: deve iniziare con "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Stringa non valida: deve terminare con "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Stringa non valida: deve includere "${_issue.includes}"`; + if (_issue.format === "regex") + return `Stringa non valida: deve corrispondere al pattern ${_issue.pattern}`; + return `Invalid ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Numero non valido: deve essere un multiplo di ${issue2.divisor}`; + case "unrecognized_keys": + return `Chiav${issue2.keys.length > 1 ? "i" : "e"} non riconosciut${issue2.keys.length > 1 ? "e" : "a"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Chiave non valida in ${issue2.origin}`; + case "invalid_union": + return "Input non valido"; + case "invalid_element": + return `Valore non valido in ${issue2.origin}`; + default: + return `Input non valido`; + } + }; + }; + } +}); + +// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ja.js +function ja_default() { + return { + localeError: error23() + }; +} +var error23; +var init_ja = __esm({ + "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ja.js"() { + init_util(); + error23 = () => { + const Sizable = { + string: { unit: "\u6587\u5B57", verb: "\u3067\u3042\u308B" }, + file: { unit: "\u30D0\u30A4\u30C8", verb: "\u3067\u3042\u308B" }, + array: { unit: "\u8981\u7D20", verb: "\u3067\u3042\u308B" }, + set: { unit: "\u8981\u7D20", verb: "\u3067\u3042\u308B" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u5165\u529B\u5024", + email: "\u30E1\u30FC\u30EB\u30A2\u30C9\u30EC\u30B9", + url: "URL", + emoji: "\u7D75\u6587\u5B57", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO\u65E5\u6642", + date: "ISO\u65E5\u4ED8", + time: "ISO\u6642\u523B", + duration: "ISO\u671F\u9593", + ipv4: "IPv4\u30A2\u30C9\u30EC\u30B9", + ipv6: "IPv6\u30A2\u30C9\u30EC\u30B9", + cidrv4: "IPv4\u7BC4\u56F2", + cidrv6: "IPv6\u7BC4\u56F2", + base64: "base64\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217", + base64url: "base64url\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217", + json_string: "JSON\u6587\u5B57\u5217", + e164: "E.164\u756A\u53F7", + jwt: "JWT", + template_literal: "\u5165\u529B\u5024" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u6570\u5024", + array: "\u914D\u5217" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u7121\u52B9\u306A\u5165\u529B: instanceof ${issue2.expected}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F\u304C\u3001${received}\u304C\u5165\u529B\u3055\u308C\u307E\u3057\u305F`; + } + return `\u7121\u52B9\u306A\u5165\u529B: ${expected}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F\u304C\u3001${received}\u304C\u5165\u529B\u3055\u308C\u307E\u3057\u305F`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u7121\u52B9\u306A\u5165\u529B: ${stringifyPrimitive(issue2.values[0])}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F`; + return `\u7121\u52B9\u306A\u9078\u629E: ${joinValues(issue2.values, "\u3001")}\u306E\u3044\u305A\u308C\u304B\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; + case "too_big": { + const adj = issue2.inclusive ? "\u4EE5\u4E0B\u3067\u3042\u308B" : "\u3088\u308A\u5C0F\u3055\u3044"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u5927\u304D\u3059\u304E\u308B\u5024: ${issue2.origin ?? "\u5024"}\u306F${issue2.maximum.toString()}${sizing.unit ?? "\u8981\u7D20"}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; + return `\u5927\u304D\u3059\u304E\u308B\u5024: ${issue2.origin ?? "\u5024"}\u306F${issue2.maximum.toString()}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; + } + case "too_small": { + const adj = issue2.inclusive ? "\u4EE5\u4E0A\u3067\u3042\u308B" : "\u3088\u308A\u5927\u304D\u3044"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u5C0F\u3055\u3059\u304E\u308B\u5024: ${issue2.origin}\u306F${issue2.minimum.toString()}${sizing.unit}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; + return `\u5C0F\u3055\u3059\u304E\u308B\u5024: ${issue2.origin}\u306F${issue2.minimum.toString()}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u7121\u52B9\u306A\u6587\u5B57\u5217: "${_issue.prefix}"\u3067\u59CB\u307E\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; + if (_issue.format === "ends_with") + return `\u7121\u52B9\u306A\u6587\u5B57\u5217: "${_issue.suffix}"\u3067\u7D42\u308F\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; + if (_issue.format === "includes") + return `\u7121\u52B9\u306A\u6587\u5B57\u5217: "${_issue.includes}"\u3092\u542B\u3080\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; + if (_issue.format === "regex") + return `\u7121\u52B9\u306A\u6587\u5B57\u5217: \u30D1\u30BF\u30FC\u30F3${_issue.pattern}\u306B\u4E00\u81F4\u3059\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; + return `\u7121\u52B9\u306A${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u7121\u52B9\u306A\u6570\u5024: ${issue2.divisor}\u306E\u500D\u6570\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; + case "unrecognized_keys": + return `\u8A8D\u8B58\u3055\u308C\u3066\u3044\u306A\u3044\u30AD\u30FC${issue2.keys.length > 1 ? "\u7FA4" : ""}: ${joinValues(issue2.keys, "\u3001")}`; + case "invalid_key": + return `${issue2.origin}\u5185\u306E\u7121\u52B9\u306A\u30AD\u30FC`; + case "invalid_union": + return "\u7121\u52B9\u306A\u5165\u529B"; + case "invalid_element": + return `${issue2.origin}\u5185\u306E\u7121\u52B9\u306A\u5024`; + default: + return `\u7121\u52B9\u306A\u5165\u529B`; + } + }; + }; + } +}); + +// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ka.js +function ka_default() { + return { + localeError: error24() + }; +} +var error24; +var init_ka = __esm({ + "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ka.js"() { + init_util(); + error24 = () => { + const Sizable = { + string: { unit: "\u10E1\u10D8\u10DB\u10D1\u10DD\u10DA\u10DD", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" }, + file: { unit: "\u10D1\u10D0\u10D8\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" }, + array: { unit: "\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" }, + set: { unit: "\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0", + email: "\u10D4\u10DA-\u10E4\u10DD\u10E1\u10E2\u10D8\u10E1 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8", + url: "URL", + emoji: "\u10D4\u10DB\u10DD\u10EF\u10D8", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "\u10D7\u10D0\u10E0\u10D8\u10E6\u10D8-\u10D3\u10E0\u10DD", + date: "\u10D7\u10D0\u10E0\u10D8\u10E6\u10D8", + time: "\u10D3\u10E0\u10DD", + duration: "\u10EE\u10D0\u10DC\u10D2\u10E0\u10EB\u10DA\u10D8\u10D5\u10DD\u10D1\u10D0", + ipv4: "IPv4 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8", + ipv6: "IPv6 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8", + cidrv4: "IPv4 \u10D3\u10D8\u10D0\u10DE\u10D0\u10D6\u10DD\u10DC\u10D8", + cidrv6: "IPv6 \u10D3\u10D8\u10D0\u10DE\u10D0\u10D6\u10DD\u10DC\u10D8", + base64: "base64-\u10D9\u10DD\u10D3\u10D8\u10E0\u10D4\u10D1\u10E3\u10DA\u10D8 \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8", + base64url: "base64url-\u10D9\u10DD\u10D3\u10D8\u10E0\u10D4\u10D1\u10E3\u10DA\u10D8 \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8", + json_string: "JSON \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8", + e164: "E.164 \u10DC\u10DD\u10DB\u10D4\u10E0\u10D8", + jwt: "JWT", + template_literal: "\u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u10E0\u10D8\u10EA\u10EE\u10D5\u10D8", + string: "\u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8", + boolean: "\u10D1\u10E3\u10DA\u10D4\u10D0\u10DC\u10D8", + function: "\u10E4\u10E3\u10DC\u10E5\u10EA\u10D8\u10D0", + array: "\u10DB\u10D0\u10E1\u10D8\u10D5\u10D8" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 instanceof ${issue2.expected}, \u10DB\u10D8\u10E6\u10D4\u10D1\u10E3\u10DA\u10D8 ${received}`; + } + return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${expected}, \u10DB\u10D8\u10E6\u10D4\u10D1\u10E3\u10DA\u10D8 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${stringifyPrimitive(issue2.values[0])}`; + return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D0\u10E0\u10D8\u10D0\u10DC\u10E2\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8\u10D0 \u10D4\u10E0\u10D7-\u10D4\u10E0\u10D7\u10D8 ${joinValues(issue2.values, "|")}-\u10D3\u10D0\u10DC`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10D3\u10D8\u10D3\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${issue2.origin ?? "\u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit}`; + return `\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10D3\u10D8\u10D3\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${issue2.origin ?? "\u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0"} \u10D8\u10E7\u10DD\u10E1 ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10DE\u10D0\u10E2\u10D0\u10E0\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10DE\u10D0\u10E2\u10D0\u10E0\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${issue2.origin} \u10D8\u10E7\u10DD\u10E1 ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10D8\u10EC\u10E7\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 "${_issue.prefix}"-\u10D8\u10D7`; + } + if (_issue.format === "ends_with") + return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10DB\u10D7\u10D0\u10D5\u10E0\u10D3\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 "${_issue.suffix}"-\u10D8\u10D7`; + if (_issue.format === "includes") + return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1 "${_issue.includes}"-\u10E1`; + if (_issue.format === "regex") + return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D4\u10E1\u10D0\u10D1\u10D0\u10DB\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 \u10E8\u10D0\u10D1\u10DA\u10DD\u10DC\u10E1 ${_issue.pattern}`; + return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E0\u10D8\u10EA\u10EE\u10D5\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10D8\u10E7\u10DD\u10E1 ${issue2.divisor}-\u10D8\u10E1 \u10EF\u10D4\u10E0\u10D0\u10D3\u10D8`; + case "unrecognized_keys": + return `\u10E3\u10EA\u10DC\u10DD\u10D1\u10D8 \u10D2\u10D0\u10E1\u10D0\u10E6\u10D4\u10D1${issue2.keys.length > 1 ? "\u10D4\u10D1\u10D8" : "\u10D8"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D2\u10D0\u10E1\u10D0\u10E6\u10D4\u10D1\u10D8 ${issue2.origin}-\u10E8\u10D8`; + case "invalid_union": + return "\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0"; + case "invalid_element": + return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0 ${issue2.origin}-\u10E8\u10D8`; + default: + return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0`; + } + }; + }; + } +}); + +// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/km.js +function km_default() { + return { + localeError: error25() + }; +} +var error25; +var init_km = __esm({ + "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/km.js"() { + init_util(); + error25 = () => { + const Sizable = { + string: { unit: "\u178F\u17BD\u17A2\u1780\u17D2\u179F\u179A", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, + file: { unit: "\u1794\u17C3", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, + array: { unit: "\u1792\u17B6\u178F\u17BB", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, + set: { unit: "\u1792\u17B6\u178F\u17BB", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B", + email: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793\u17A2\u17CA\u17B8\u1798\u17C2\u179B", + url: "URL", + emoji: "\u179F\u1789\u17D2\u1789\u17B6\u17A2\u17B6\u179A\u1798\u17D2\u1798\u178E\u17CD", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 \u1793\u17B7\u1784\u1798\u17C9\u17C4\u1784 ISO", + date: "\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 ISO", + time: "\u1798\u17C9\u17C4\u1784 ISO", + duration: "\u179A\u1799\u17C8\u1796\u17C1\u179B ISO", + ipv4: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4", + ipv6: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6", + cidrv4: "\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4", + cidrv6: "\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6", + base64: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64", + base64url: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64url", + json_string: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A JSON", + e164: "\u179B\u17C1\u1781 E.164", + jwt: "JWT", + template_literal: "\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u179B\u17C1\u1781", + array: "\u17A2\u17B6\u179A\u17C1 (Array)", + null: "\u1782\u17D2\u1798\u17B6\u1793\u178F\u1798\u17D2\u179B\u17C3 (null)" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A instanceof ${issue2.expected} \u1794\u17C9\u17BB\u1793\u17D2\u178F\u17C2\u1791\u1791\u17BD\u179B\u1794\u17B6\u1793 ${received}`; + } + return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${expected} \u1794\u17C9\u17BB\u1793\u17D2\u178F\u17C2\u1791\u1791\u17BD\u179B\u1794\u17B6\u1793 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${stringifyPrimitive(issue2.values[0])}`; + return `\u1787\u1798\u17D2\u179A\u17BE\u179F\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1787\u17B6\u1798\u17BD\u1799\u1780\u17D2\u1793\u17BB\u1784\u1785\u17C6\u178E\u17C4\u1798 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue2.origin ?? "\u178F\u1798\u17D2\u179B\u17C3"} ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "\u1792\u17B6\u178F\u17BB"}`; + return `\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue2.origin ?? "\u178F\u1798\u17D2\u179B\u17C3"} ${adj} ${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue2.origin} ${adj} ${issue2.minimum.toString()} ${sizing.unit}`; + } + return `\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue2.origin} ${adj} ${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1785\u17B6\u1794\u17CB\u1795\u17D2\u178F\u17BE\u1798\u178A\u17C4\u1799 "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1794\u1789\u17D2\u1785\u1794\u17CB\u178A\u17C4\u1799 "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1798\u17B6\u1793 "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1795\u17D2\u1782\u17BC\u1795\u17D2\u1782\u1784\u1793\u17B9\u1784\u1791\u1798\u17D2\u179A\u1784\u17CB\u178A\u17C2\u179B\u1794\u17B6\u1793\u1780\u17C6\u178E\u178F\u17CB ${_issue.pattern}`; + return `\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u179B\u17C1\u1781\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1787\u17B6\u1796\u17A0\u17BB\u1782\u17BB\u178E\u1793\u17C3 ${issue2.divisor}`; + case "unrecognized_keys": + return `\u179A\u1780\u1783\u17BE\u1789\u179F\u17C4\u1798\u17B7\u1793\u179F\u17D2\u1782\u17B6\u179B\u17CB\u17D6 ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u179F\u17C4\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${issue2.origin}`; + case "invalid_union": + return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C`; + case "invalid_element": + return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${issue2.origin}`; + default: + return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C`; + } + }; + }; + } +}); + +// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/kh.js +function kh_default() { + return km_default(); +} +var init_kh = __esm({ + "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/kh.js"() { + init_km(); + } +}); + +// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ko.js +function ko_default() { + return { + localeError: error26() + }; +} +var error26; +var init_ko = __esm({ + "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ko.js"() { + init_util(); + error26 = () => { + const Sizable = { + string: { unit: "\uBB38\uC790", verb: "to have" }, + file: { unit: "\uBC14\uC774\uD2B8", verb: "to have" }, + array: { unit: "\uAC1C", verb: "to have" }, + set: { unit: "\uAC1C", verb: "to have" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\uC785\uB825", + email: "\uC774\uBA54\uC77C \uC8FC\uC18C", + url: "URL", + emoji: "\uC774\uBAA8\uC9C0", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \uB0A0\uC9DC\uC2DC\uAC04", + date: "ISO \uB0A0\uC9DC", + time: "ISO \uC2DC\uAC04", + duration: "ISO \uAE30\uAC04", + ipv4: "IPv4 \uC8FC\uC18C", + ipv6: "IPv6 \uC8FC\uC18C", + cidrv4: "IPv4 \uBC94\uC704", + cidrv6: "IPv6 \uBC94\uC704", + base64: "base64 \uC778\uCF54\uB529 \uBB38\uC790\uC5F4", + base64url: "base64url \uC778\uCF54\uB529 \uBB38\uC790\uC5F4", + json_string: "JSON \uBB38\uC790\uC5F4", + e164: "E.164 \uBC88\uD638", + jwt: "JWT", + template_literal: "\uC785\uB825" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\uC798\uBABB\uB41C \uC785\uB825: \uC608\uC0C1 \uD0C0\uC785\uC740 instanceof ${issue2.expected}, \uBC1B\uC740 \uD0C0\uC785\uC740 ${received}\uC785\uB2C8\uB2E4`; + } + return `\uC798\uBABB\uB41C \uC785\uB825: \uC608\uC0C1 \uD0C0\uC785\uC740 ${expected}, \uBC1B\uC740 \uD0C0\uC785\uC740 ${received}\uC785\uB2C8\uB2E4`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\uC798\uBABB\uB41C \uC785\uB825: \uAC12\uC740 ${stringifyPrimitive(issue2.values[0])} \uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4`; + return `\uC798\uBABB\uB41C \uC635\uC158: ${joinValues(issue2.values, "\uB610\uB294 ")} \uC911 \uD558\uB098\uC5EC\uC57C \uD569\uB2C8\uB2E4`; + case "too_big": { + const adj = issue2.inclusive ? "\uC774\uD558" : "\uBBF8\uB9CC"; + const suffix = adj === "\uBBF8\uB9CC" ? "\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4" : "\uC5EC\uC57C \uD569\uB2C8\uB2E4"; + const sizing = getSizing(issue2.origin); + const unit = sizing?.unit ?? "\uC694\uC18C"; + if (sizing) + return `${issue2.origin ?? "\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${issue2.maximum.toString()}${unit} ${adj}${suffix}`; + return `${issue2.origin ?? "\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${issue2.maximum.toString()} ${adj}${suffix}`; + } + case "too_small": { + const adj = issue2.inclusive ? "\uC774\uC0C1" : "\uCD08\uACFC"; + const suffix = adj === "\uC774\uC0C1" ? "\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4" : "\uC5EC\uC57C \uD569\uB2C8\uB2E4"; + const sizing = getSizing(issue2.origin); + const unit = sizing?.unit ?? "\uC694\uC18C"; + if (sizing) { + return `${issue2.origin ?? "\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${issue2.minimum.toString()}${unit} ${adj}${suffix}`; + } + return `${issue2.origin ?? "\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${issue2.minimum.toString()} ${adj}${suffix}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${_issue.prefix}"(\uC73C)\uB85C \uC2DC\uC791\uD574\uC57C \uD569\uB2C8\uB2E4`; + } + if (_issue.format === "ends_with") + return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${_issue.suffix}"(\uC73C)\uB85C \uB05D\uB098\uC57C \uD569\uB2C8\uB2E4`; + if (_issue.format === "includes") + return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${_issue.includes}"\uC744(\uB97C) \uD3EC\uD568\uD574\uC57C \uD569\uB2C8\uB2E4`; + if (_issue.format === "regex") + return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: \uC815\uADDC\uC2DD ${_issue.pattern} \uD328\uD134\uACFC \uC77C\uCE58\uD574\uC57C \uD569\uB2C8\uB2E4`; + return `\uC798\uBABB\uB41C ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\uC798\uBABB\uB41C \uC22B\uC790: ${issue2.divisor}\uC758 \uBC30\uC218\uC5EC\uC57C \uD569\uB2C8\uB2E4`; + case "unrecognized_keys": + return `\uC778\uC2DD\uD560 \uC218 \uC5C6\uB294 \uD0A4: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\uC798\uBABB\uB41C \uD0A4: ${issue2.origin}`; + case "invalid_union": + return `\uC798\uBABB\uB41C \uC785\uB825`; + case "invalid_element": + return `\uC798\uBABB\uB41C \uAC12: ${issue2.origin}`; + default: + return `\uC798\uBABB\uB41C \uC785\uB825`; + } + }; + }; + } +}); + +// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/lt.js +function getUnitTypeFromNumber(number4) { + const abs = Math.abs(number4); + const last = abs % 10; + const last2 = abs % 100; + if (last2 >= 11 && last2 <= 19 || last === 0) + return "many"; + if (last === 1) + return "one"; + return "few"; +} +function lt_default() { + return { + localeError: error27() + }; +} +var capitalizeFirstCharacter, error27; +var init_lt = __esm({ + "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/lt.js"() { + init_util(); + capitalizeFirstCharacter = (text3) => { + return text3.charAt(0).toUpperCase() + text3.slice(1); + }; + error27 = () => { + const Sizable = { + string: { + unit: { + one: "simbolis", + few: "simboliai", + many: "simboli\u0173" + }, + verb: { + smaller: { + inclusive: "turi b\u016Bti ne ilgesn\u0117 kaip", + notInclusive: "turi b\u016Bti trumpesn\u0117 kaip" + }, + bigger: { + inclusive: "turi b\u016Bti ne trumpesn\u0117 kaip", + notInclusive: "turi b\u016Bti ilgesn\u0117 kaip" + } + } + }, + file: { + unit: { + one: "baitas", + few: "baitai", + many: "bait\u0173" + }, + verb: { + smaller: { + inclusive: "turi b\u016Bti ne didesnis kaip", + notInclusive: "turi b\u016Bti ma\u017Eesnis kaip" + }, + bigger: { + inclusive: "turi b\u016Bti ne ma\u017Eesnis kaip", + notInclusive: "turi b\u016Bti didesnis kaip" + } + } + }, + array: { + unit: { + one: "element\u0105", + few: "elementus", + many: "element\u0173" + }, + verb: { + smaller: { + inclusive: "turi tur\u0117ti ne daugiau kaip", + notInclusive: "turi tur\u0117ti ma\u017Eiau kaip" + }, + bigger: { + inclusive: "turi tur\u0117ti ne ma\u017Eiau kaip", + notInclusive: "turi tur\u0117ti daugiau kaip" + } + } + }, + set: { + unit: { + one: "element\u0105", + few: "elementus", + many: "element\u0173" + }, + verb: { + smaller: { + inclusive: "turi tur\u0117ti ne daugiau kaip", + notInclusive: "turi tur\u0117ti ma\u017Eiau kaip" + }, + bigger: { + inclusive: "turi tur\u0117ti ne ma\u017Eiau kaip", + notInclusive: "turi tur\u0117ti daugiau kaip" + } + } + } + }; + function getSizing(origin, unitType, inclusive, targetShouldBe) { + const result = Sizable[origin] ?? null; + if (result === null) + return result; + return { + unit: result.unit[unitType], + verb: result.verb[targetShouldBe][inclusive ? "inclusive" : "notInclusive"] + }; + } + const FormatDictionary = { + regex: "\u012Fvestis", + email: "el. pa\u0161to adresas", + url: "URL", + emoji: "jaustukas", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO data ir laikas", + date: "ISO data", + time: "ISO laikas", + duration: "ISO trukm\u0117", + ipv4: "IPv4 adresas", + ipv6: "IPv6 adresas", + cidrv4: "IPv4 tinklo prefiksas (CIDR)", + cidrv6: "IPv6 tinklo prefiksas (CIDR)", + base64: "base64 u\u017Ekoduota eilut\u0117", + base64url: "base64url u\u017Ekoduota eilut\u0117", + json_string: "JSON eilut\u0117", + e164: "E.164 numeris", + jwt: "JWT", + template_literal: "\u012Fvestis" + }; + const TypeDictionary = { + nan: "NaN", + number: "skai\u010Dius", + bigint: "sveikasis skai\u010Dius", + string: "eilut\u0117", + boolean: "login\u0117 reik\u0161m\u0117", + undefined: "neapibr\u0117\u017Eta reik\u0161m\u0117", + function: "funkcija", + symbol: "simbolis", + array: "masyvas", + object: "objektas", + null: "nulin\u0117 reik\u0161m\u0117" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Gautas tipas ${received}, o tik\u0117tasi - instanceof ${issue2.expected}`; + } + return `Gautas tipas ${received}, o tik\u0117tasi - ${expected}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Privalo b\u016Bti ${stringifyPrimitive(issue2.values[0])}`; + return `Privalo b\u016Bti vienas i\u0161 ${joinValues(issue2.values, "|")} pasirinkim\u0173`; + case "too_big": { + const origin = TypeDictionary[issue2.origin] ?? issue2.origin; + const sizing = getSizing(issue2.origin, getUnitTypeFromNumber(Number(issue2.maximum)), issue2.inclusive ?? false, "smaller"); + if (sizing?.verb) + return `${capitalizeFirstCharacter(origin ?? issue2.origin ?? "reik\u0161m\u0117")} ${sizing.verb} ${issue2.maximum.toString()} ${sizing.unit ?? "element\u0173"}`; + const adj = issue2.inclusive ? "ne didesnis kaip" : "ma\u017Eesnis kaip"; + return `${capitalizeFirstCharacter(origin ?? issue2.origin ?? "reik\u0161m\u0117")} turi b\u016Bti ${adj} ${issue2.maximum.toString()} ${sizing?.unit}`; + } + case "too_small": { + const origin = TypeDictionary[issue2.origin] ?? issue2.origin; + const sizing = getSizing(issue2.origin, getUnitTypeFromNumber(Number(issue2.minimum)), issue2.inclusive ?? false, "bigger"); + if (sizing?.verb) + return `${capitalizeFirstCharacter(origin ?? issue2.origin ?? "reik\u0161m\u0117")} ${sizing.verb} ${issue2.minimum.toString()} ${sizing.unit ?? "element\u0173"}`; + const adj = issue2.inclusive ? "ne ma\u017Eesnis kaip" : "didesnis kaip"; + return `${capitalizeFirstCharacter(origin ?? issue2.origin ?? "reik\u0161m\u0117")} turi b\u016Bti ${adj} ${issue2.minimum.toString()} ${sizing?.unit}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `Eilut\u0117 privalo prasid\u0117ti "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `Eilut\u0117 privalo pasibaigti "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Eilut\u0117 privalo \u012Ftraukti "${_issue.includes}"`; + if (_issue.format === "regex") + return `Eilut\u0117 privalo atitikti ${_issue.pattern}`; + return `Neteisingas ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Skai\u010Dius privalo b\u016Bti ${issue2.divisor} kartotinis.`; + case "unrecognized_keys": + return `Neatpa\u017Eint${issue2.keys.length > 1 ? "i" : "as"} rakt${issue2.keys.length > 1 ? "ai" : "as"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return "Rastas klaidingas raktas"; + case "invalid_union": + return "Klaidinga \u012Fvestis"; + case "invalid_element": { + const origin = TypeDictionary[issue2.origin] ?? issue2.origin; + return `${capitalizeFirstCharacter(origin ?? issue2.origin ?? "reik\u0161m\u0117")} turi klaiding\u0105 \u012Fvest\u012F`; + } + default: + return "Klaidinga \u012Fvestis"; + } + }; + }; + } +}); + +// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/mk.js +function mk_default() { + return { + localeError: error28() + }; +} +var error28; +var init_mk = __esm({ + "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/mk.js"() { + init_util(); + error28 = () => { + const Sizable = { + string: { unit: "\u0437\u043D\u0430\u0446\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, + file: { unit: "\u0431\u0430\u0458\u0442\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, + array: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, + set: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0432\u043D\u0435\u0441", + email: "\u0430\u0434\u0440\u0435\u0441\u0430 \u043D\u0430 \u0435-\u043F\u043E\u0448\u0442\u0430", + url: "URL", + emoji: "\u0435\u043C\u043E\u045F\u0438", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u0434\u0430\u0442\u0443\u043C \u0438 \u0432\u0440\u0435\u043C\u0435", + date: "ISO \u0434\u0430\u0442\u0443\u043C", + time: "ISO \u0432\u0440\u0435\u043C\u0435", + duration: "ISO \u0432\u0440\u0435\u043C\u0435\u0442\u0440\u0430\u0435\u045A\u0435", + ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441\u0430", + ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441\u0430", + cidrv4: "IPv4 \u043E\u043F\u0441\u0435\u0433", + cidrv6: "IPv6 \u043E\u043F\u0441\u0435\u0433", + base64: "base64-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430", + base64url: "base64url-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430", + json_string: "JSON \u043D\u0438\u0437\u0430", + e164: "E.164 \u0431\u0440\u043E\u0458", + jwt: "JWT", + template_literal: "\u0432\u043D\u0435\u0441" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u0431\u0440\u043E\u0458", + array: "\u043D\u0438\u0437\u0430" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 instanceof ${issue2.expected}, \u043F\u0440\u0438\u043C\u0435\u043D\u043E ${received}`; + } + return `\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${expected}, \u043F\u0440\u0438\u043C\u0435\u043D\u043E ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Invalid input: expected ${stringifyPrimitive(issue2.values[0])}`; + return `\u0413\u0440\u0435\u0448\u0430\u043D\u0430 \u043E\u043F\u0446\u0438\u0458\u0430: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 \u0435\u0434\u043D\u0430 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.origin ?? "\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0438\u043C\u0430 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0438"}`; + return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.origin ?? "\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0431\u0438\u0434\u0435 ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.origin} \u0434\u0430 \u0438\u043C\u0430 ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.origin} \u0434\u0430 \u0431\u0438\u0434\u0435 ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u043F\u043E\u0447\u043D\u0443\u0432\u0430 \u0441\u043E "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u0432\u0440\u0448\u0443\u0432\u0430 \u0441\u043E "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0432\u043A\u043B\u0443\u0447\u0443\u0432\u0430 "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u043E\u0434\u0433\u043E\u0430\u0440\u0430 \u043D\u0430 \u043F\u0430\u0442\u0435\u0440\u043D\u043E\u0442 ${_issue.pattern}`; + return `Invalid ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u0413\u0440\u0435\u0448\u0435\u043D \u0431\u0440\u043E\u0458: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0431\u0438\u0434\u0435 \u0434\u0435\u043B\u0438\u0432 \u0441\u043E ${issue2.divisor}`; + case "unrecognized_keys": + return `${issue2.keys.length > 1 ? "\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D\u0438 \u043A\u043B\u0443\u0447\u0435\u0432\u0438" : "\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D \u043A\u043B\u0443\u0447"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u0413\u0440\u0435\u0448\u0435\u043D \u043A\u043B\u0443\u0447 \u0432\u043E ${issue2.origin}`; + case "invalid_union": + return "\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441"; + case "invalid_element": + return `\u0413\u0440\u0435\u0448\u043D\u0430 \u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442 \u0432\u043E ${issue2.origin}`; + default: + return `\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441`; + } + }; + }; + } +}); + +// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ms.js +function ms_default() { + return { + localeError: error29() + }; +} +var error29; +var init_ms = __esm({ + "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ms.js"() { + init_util(); + error29 = () => { + const Sizable = { + string: { unit: "aksara", verb: "mempunyai" }, + file: { unit: "bait", verb: "mempunyai" }, + array: { unit: "elemen", verb: "mempunyai" }, + set: { unit: "elemen", verb: "mempunyai" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "input", + email: "alamat e-mel", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "tarikh masa ISO", + date: "tarikh ISO", + time: "masa ISO", + duration: "tempoh ISO", + ipv4: "alamat IPv4", + ipv6: "alamat IPv6", + cidrv4: "julat IPv4", + cidrv6: "julat IPv6", + base64: "string dikodkan base64", + base64url: "string dikodkan base64url", + json_string: "string JSON", + e164: "nombor E.164", + jwt: "JWT", + template_literal: "input" + }; + const TypeDictionary = { + nan: "NaN", + number: "nombor" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Input tidak sah: dijangka instanceof ${issue2.expected}, diterima ${received}`; + } + return `Input tidak sah: dijangka ${expected}, diterima ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Input tidak sah: dijangka ${stringifyPrimitive(issue2.values[0])}`; + return `Pilihan tidak sah: dijangka salah satu daripada ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Terlalu besar: dijangka ${issue2.origin ?? "nilai"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elemen"}`; + return `Terlalu besar: dijangka ${issue2.origin ?? "nilai"} adalah ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Terlalu kecil: dijangka ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `Terlalu kecil: dijangka ${issue2.origin} adalah ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `String tidak sah: mesti bermula dengan "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `String tidak sah: mesti berakhir dengan "${_issue.suffix}"`; + if (_issue.format === "includes") + return `String tidak sah: mesti mengandungi "${_issue.includes}"`; + if (_issue.format === "regex") + return `String tidak sah: mesti sepadan dengan corak ${_issue.pattern}`; + return `${FormatDictionary[_issue.format] ?? issue2.format} tidak sah`; + } + case "not_multiple_of": + return `Nombor tidak sah: perlu gandaan ${issue2.divisor}`; + case "unrecognized_keys": + return `Kunci tidak dikenali: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Kunci tidak sah dalam ${issue2.origin}`; + case "invalid_union": + return "Input tidak sah"; + case "invalid_element": + return `Nilai tidak sah dalam ${issue2.origin}`; + default: + return `Input tidak sah`; + } + }; + }; + } +}); + +// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/nl.js +function nl_default() { + return { + localeError: error30() + }; +} +var error30; +var init_nl = __esm({ + "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/nl.js"() { + init_util(); + error30 = () => { + const Sizable = { + string: { unit: "tekens", verb: "heeft" }, + file: { unit: "bytes", verb: "heeft" }, + array: { unit: "elementen", verb: "heeft" }, + set: { unit: "elementen", verb: "heeft" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "invoer", + email: "emailadres", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO datum en tijd", + date: "ISO datum", + time: "ISO tijd", + duration: "ISO duur", + ipv4: "IPv4-adres", + ipv6: "IPv6-adres", + cidrv4: "IPv4-bereik", + cidrv6: "IPv6-bereik", + base64: "base64-gecodeerde tekst", + base64url: "base64 URL-gecodeerde tekst", + json_string: "JSON string", + e164: "E.164-nummer", + jwt: "JWT", + template_literal: "invoer" + }; + const TypeDictionary = { + nan: "NaN", + number: "getal" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Ongeldige invoer: verwacht instanceof ${issue2.expected}, ontving ${received}`; + } + return `Ongeldige invoer: verwacht ${expected}, ontving ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Ongeldige invoer: verwacht ${stringifyPrimitive(issue2.values[0])}`; + return `Ongeldige optie: verwacht \xE9\xE9n van ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + const longName = issue2.origin === "date" ? "laat" : issue2.origin === "string" ? "lang" : "groot"; + if (sizing) + return `Te ${longName}: verwacht dat ${issue2.origin ?? "waarde"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementen"} ${sizing.verb}`; + return `Te ${longName}: verwacht dat ${issue2.origin ?? "waarde"} ${adj}${issue2.maximum.toString()} is`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + const shortName = issue2.origin === "date" ? "vroeg" : issue2.origin === "string" ? "kort" : "klein"; + if (sizing) { + return `Te ${shortName}: verwacht dat ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} ${sizing.verb}`; + } + return `Te ${shortName}: verwacht dat ${issue2.origin} ${adj}${issue2.minimum.toString()} is`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `Ongeldige tekst: moet met "${_issue.prefix}" beginnen`; + } + if (_issue.format === "ends_with") + return `Ongeldige tekst: moet op "${_issue.suffix}" eindigen`; + if (_issue.format === "includes") + return `Ongeldige tekst: moet "${_issue.includes}" bevatten`; + if (_issue.format === "regex") + return `Ongeldige tekst: moet overeenkomen met patroon ${_issue.pattern}`; + return `Ongeldig: ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Ongeldig getal: moet een veelvoud van ${issue2.divisor} zijn`; + case "unrecognized_keys": + return `Onbekende key${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Ongeldige key in ${issue2.origin}`; + case "invalid_union": + return "Ongeldige invoer"; + case "invalid_element": + return `Ongeldige waarde in ${issue2.origin}`; + default: + return `Ongeldige invoer`; + } + }; + }; + } +}); + +// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/no.js +function no_default() { + return { + localeError: error31() + }; +} +var error31; +var init_no = __esm({ + "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/no.js"() { + init_util(); + error31 = () => { + const Sizable = { + string: { unit: "tegn", verb: "\xE5 ha" }, + file: { unit: "bytes", verb: "\xE5 ha" }, + array: { unit: "elementer", verb: "\xE5 inneholde" }, + set: { unit: "elementer", verb: "\xE5 inneholde" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "input", + email: "e-postadresse", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO dato- og klokkeslett", + date: "ISO-dato", + time: "ISO-klokkeslett", + duration: "ISO-varighet", + ipv4: "IPv4-omr\xE5de", + ipv6: "IPv6-omr\xE5de", + cidrv4: "IPv4-spekter", + cidrv6: "IPv6-spekter", + base64: "base64-enkodet streng", + base64url: "base64url-enkodet streng", + json_string: "JSON-streng", + e164: "E.164-nummer", + jwt: "JWT", + template_literal: "input" + }; + const TypeDictionary = { + nan: "NaN", + number: "tall", + array: "liste" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Ugyldig input: forventet instanceof ${issue2.expected}, fikk ${received}`; + } + return `Ugyldig input: forventet ${expected}, fikk ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Ugyldig verdi: forventet ${stringifyPrimitive(issue2.values[0])}`; + return `Ugyldig valg: forventet en av ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `For stor(t): forventet ${issue2.origin ?? "value"} til \xE5 ha ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementer"}`; + return `For stor(t): forventet ${issue2.origin ?? "value"} til \xE5 ha ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `For lite(n): forventet ${issue2.origin} til \xE5 ha ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `For lite(n): forventet ${issue2.origin} til \xE5 ha ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Ugyldig streng: m\xE5 starte med "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Ugyldig streng: m\xE5 ende med "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Ugyldig streng: m\xE5 inneholde "${_issue.includes}"`; + if (_issue.format === "regex") + return `Ugyldig streng: m\xE5 matche m\xF8nsteret ${_issue.pattern}`; + return `Ugyldig ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Ugyldig tall: m\xE5 v\xE6re et multiplum av ${issue2.divisor}`; + case "unrecognized_keys": + return `${issue2.keys.length > 1 ? "Ukjente n\xF8kler" : "Ukjent n\xF8kkel"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Ugyldig n\xF8kkel i ${issue2.origin}`; + case "invalid_union": + return "Ugyldig input"; + case "invalid_element": + return `Ugyldig verdi i ${issue2.origin}`; + default: + return `Ugyldig input`; + } + }; + }; + } +}); + +// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ota.js +function ota_default() { + return { + localeError: error32() + }; +} +var error32; +var init_ota = __esm({ + "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ota.js"() { + init_util(); + error32 = () => { + const Sizable = { + string: { unit: "harf", verb: "olmal\u0131d\u0131r" }, + file: { unit: "bayt", verb: "olmal\u0131d\u0131r" }, + array: { unit: "unsur", verb: "olmal\u0131d\u0131r" }, + set: { unit: "unsur", verb: "olmal\u0131d\u0131r" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "giren", + email: "epostag\xE2h", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO heng\xE2m\u0131", + date: "ISO tarihi", + time: "ISO zaman\u0131", + duration: "ISO m\xFCddeti", + ipv4: "IPv4 ni\u015F\xE2n\u0131", + ipv6: "IPv6 ni\u015F\xE2n\u0131", + cidrv4: "IPv4 menzili", + cidrv6: "IPv6 menzili", + base64: "base64-\u015Fifreli metin", + base64url: "base64url-\u015Fifreli metin", + json_string: "JSON metin", + e164: "E.164 say\u0131s\u0131", + jwt: "JWT", + template_literal: "giren" + }; + const TypeDictionary = { + nan: "NaN", + number: "numara", + array: "saf", + null: "gayb" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `F\xE2sit giren: umulan instanceof ${issue2.expected}, al\u0131nan ${received}`; + } + return `F\xE2sit giren: umulan ${expected}, al\u0131nan ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `F\xE2sit giren: umulan ${stringifyPrimitive(issue2.values[0])}`; + return `F\xE2sit tercih: m\xFBteberler ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Fazla b\xFCy\xFCk: ${issue2.origin ?? "value"}, ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elements"} sahip olmal\u0131yd\u0131.`; + return `Fazla b\xFCy\xFCk: ${issue2.origin ?? "value"}, ${adj}${issue2.maximum.toString()} olmal\u0131yd\u0131.`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Fazla k\xFC\xE7\xFCk: ${issue2.origin}, ${adj}${issue2.minimum.toString()} ${sizing.unit} sahip olmal\u0131yd\u0131.`; + } + return `Fazla k\xFC\xE7\xFCk: ${issue2.origin}, ${adj}${issue2.minimum.toString()} olmal\u0131yd\u0131.`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `F\xE2sit metin: "${_issue.prefix}" ile ba\u015Flamal\u0131.`; + if (_issue.format === "ends_with") + return `F\xE2sit metin: "${_issue.suffix}" ile bitmeli.`; + if (_issue.format === "includes") + return `F\xE2sit metin: "${_issue.includes}" ihtiv\xE2 etmeli.`; + if (_issue.format === "regex") + return `F\xE2sit metin: ${_issue.pattern} nak\u015F\u0131na uymal\u0131.`; + return `F\xE2sit ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `F\xE2sit say\u0131: ${issue2.divisor} kat\u0131 olmal\u0131yd\u0131.`; + case "unrecognized_keys": + return `Tan\u0131nmayan anahtar ${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `${issue2.origin} i\xE7in tan\u0131nmayan anahtar var.`; + case "invalid_union": + return "Giren tan\u0131namad\u0131."; + case "invalid_element": + return `${issue2.origin} i\xE7in tan\u0131nmayan k\u0131ymet var.`; + default: + return `K\u0131ymet tan\u0131namad\u0131.`; + } + }; + }; + } +}); + +// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ps.js +function ps_default() { + return { + localeError: error33() + }; +} +var error33; +var init_ps = __esm({ + "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ps.js"() { + init_util(); + error33 = () => { + const Sizable = { + string: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" }, + file: { unit: "\u0628\u0627\u06CC\u067C\u0633", verb: "\u0648\u0644\u0631\u064A" }, + array: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" }, + set: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0648\u0631\u0648\u062F\u064A", + email: "\u0628\u0631\u06CC\u069A\u0646\u0627\u0644\u06CC\u06A9", + url: "\u06CC\u0648 \u0622\u0631 \u0627\u0644", + emoji: "\u0627\u06CC\u0645\u0648\u062C\u064A", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "\u0646\u06CC\u067C\u0647 \u0627\u0648 \u0648\u062E\u062A", + date: "\u0646\u06D0\u067C\u0647", + time: "\u0648\u062E\u062A", + duration: "\u0645\u0648\u062F\u0647", + ipv4: "\u062F IPv4 \u067E\u062A\u0647", + ipv6: "\u062F IPv6 \u067E\u062A\u0647", + cidrv4: "\u062F IPv4 \u0633\u0627\u062D\u0647", + cidrv6: "\u062F IPv6 \u0633\u0627\u062D\u0647", + base64: "base64-encoded \u0645\u062A\u0646", + base64url: "base64url-encoded \u0645\u062A\u0646", + json_string: "JSON \u0645\u062A\u0646", + e164: "\u062F E.164 \u0634\u0645\u06D0\u0631\u0647", + jwt: "JWT", + template_literal: "\u0648\u0631\u0648\u062F\u064A" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u0639\u062F\u062F", + array: "\u0627\u0631\u06D0" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F instanceof ${issue2.expected} \u0648\u0627\u06CC, \u0645\u06AB\u0631 ${received} \u062A\u0631\u0644\u0627\u0633\u0647 \u0634\u0648`; + } + return `\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${expected} \u0648\u0627\u06CC, \u0645\u06AB\u0631 ${received} \u062A\u0631\u0644\u0627\u0633\u0647 \u0634\u0648`; + } + case "invalid_value": + if (issue2.values.length === 1) { + return `\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${stringifyPrimitive(issue2.values[0])} \u0648\u0627\u06CC`; + } + return `\u0646\u0627\u0633\u0645 \u0627\u0646\u062A\u062E\u0627\u0628: \u0628\u0627\u06CC\u062F \u06CC\u0648 \u0644\u0647 ${joinValues(issue2.values, "|")} \u0685\u062E\u0647 \u0648\u0627\u06CC`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${issue2.origin ?? "\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0639\u0646\u0635\u0631\u0648\u0646\u0647"} \u0648\u0644\u0631\u064A`; + } + return `\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${issue2.origin ?? "\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${adj}${issue2.maximum.toString()} \u0648\u064A`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${issue2.origin} \u0628\u0627\u06CC\u062F ${adj}${issue2.minimum.toString()} ${sizing.unit} \u0648\u0644\u0631\u064A`; + } + return `\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${issue2.origin} \u0628\u0627\u06CC\u062F ${adj}${issue2.minimum.toString()} \u0648\u064A`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${_issue.prefix}" \u0633\u0631\u0647 \u067E\u06CC\u0644 \u0634\u064A`; + } + if (_issue.format === "ends_with") { + return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${_issue.suffix}" \u0633\u0631\u0647 \u067E\u0627\u06CC \u062A\u0647 \u0648\u0631\u0633\u064A\u0696\u064A`; + } + if (_issue.format === "includes") { + return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F "${_issue.includes}" \u0648\u0644\u0631\u064A`; + } + if (_issue.format === "regex") { + return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F ${_issue.pattern} \u0633\u0631\u0647 \u0645\u0637\u0627\u0628\u0642\u062A \u0648\u0644\u0631\u064A`; + } + return `${FormatDictionary[_issue.format] ?? issue2.format} \u0646\u0627\u0633\u0645 \u062F\u06CC`; + } + case "not_multiple_of": + return `\u0646\u0627\u0633\u0645 \u0639\u062F\u062F: \u0628\u0627\u06CC\u062F \u062F ${issue2.divisor} \u0645\u0636\u0631\u0628 \u0648\u064A`; + case "unrecognized_keys": + return `\u0646\u0627\u0633\u0645 ${issue2.keys.length > 1 ? "\u06A9\u0644\u06CC\u0689\u0648\u0646\u0647" : "\u06A9\u0644\u06CC\u0689"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u0646\u0627\u0633\u0645 \u06A9\u0644\u06CC\u0689 \u067E\u0647 ${issue2.origin} \u06A9\u06D0`; + case "invalid_union": + return `\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A`; + case "invalid_element": + return `\u0646\u0627\u0633\u0645 \u0639\u0646\u0635\u0631 \u067E\u0647 ${issue2.origin} \u06A9\u06D0`; + default: + return `\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A`; + } + }; + }; + } +}); + +// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/pl.js +function pl_default() { + return { + localeError: error34() + }; +} +var error34; +var init_pl = __esm({ + "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/pl.js"() { + init_util(); + error34 = () => { + const Sizable = { + string: { unit: "znak\xF3w", verb: "mie\u0107" }, + file: { unit: "bajt\xF3w", verb: "mie\u0107" }, + array: { unit: "element\xF3w", verb: "mie\u0107" }, + set: { unit: "element\xF3w", verb: "mie\u0107" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "wyra\u017Cenie", + email: "adres email", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "data i godzina w formacie ISO", + date: "data w formacie ISO", + time: "godzina w formacie ISO", + duration: "czas trwania ISO", + ipv4: "adres IPv4", + ipv6: "adres IPv6", + cidrv4: "zakres IPv4", + cidrv6: "zakres IPv6", + base64: "ci\u0105g znak\xF3w zakodowany w formacie base64", + base64url: "ci\u0105g znak\xF3w zakodowany w formacie base64url", + json_string: "ci\u0105g znak\xF3w w formacie JSON", + e164: "liczba E.164", + jwt: "JWT", + template_literal: "wej\u015Bcie" + }; + const TypeDictionary = { + nan: "NaN", + number: "liczba", + array: "tablica" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano instanceof ${issue2.expected}, otrzymano ${received}`; + } + return `Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${expected}, otrzymano ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${stringifyPrimitive(issue2.values[0])}`; + return `Nieprawid\u0142owa opcja: oczekiwano jednej z warto\u015Bci ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Za du\u017Ca warto\u015B\u0107: oczekiwano, \u017Ce ${issue2.origin ?? "warto\u015B\u0107"} b\u0119dzie mie\u0107 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "element\xF3w"}`; + } + return `Zbyt du\u017C(y/a/e): oczekiwano, \u017Ce ${issue2.origin ?? "warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Za ma\u0142a warto\u015B\u0107: oczekiwano, \u017Ce ${issue2.origin ?? "warto\u015B\u0107"} b\u0119dzie mie\u0107 ${adj}${issue2.minimum.toString()} ${sizing.unit ?? "element\xF3w"}`; + } + return `Zbyt ma\u0142(y/a/e): oczekiwano, \u017Ce ${issue2.origin ?? "warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zaczyna\u0107 si\u0119 od "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi ko\u0144czy\u0107 si\u0119 na "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zawiera\u0107 "${_issue.includes}"`; + if (_issue.format === "regex") + return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi odpowiada\u0107 wzorcowi ${_issue.pattern}`; + return `Nieprawid\u0142ow(y/a/e) ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Nieprawid\u0142owa liczba: musi by\u0107 wielokrotno\u015Bci\u0105 ${issue2.divisor}`; + case "unrecognized_keys": + return `Nierozpoznane klucze${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Nieprawid\u0142owy klucz w ${issue2.origin}`; + case "invalid_union": + return "Nieprawid\u0142owe dane wej\u015Bciowe"; + case "invalid_element": + return `Nieprawid\u0142owa warto\u015B\u0107 w ${issue2.origin}`; + default: + return `Nieprawid\u0142owe dane wej\u015Bciowe`; + } + }; + }; + } +}); + +// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/pt.js +function pt_default() { + return { + localeError: error35() + }; +} +var error35; +var init_pt = __esm({ + "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/pt.js"() { + init_util(); + error35 = () => { + const Sizable = { + string: { unit: "caracteres", verb: "ter" }, + file: { unit: "bytes", verb: "ter" }, + array: { unit: "itens", verb: "ter" }, + set: { unit: "itens", verb: "ter" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "padr\xE3o", + email: "endere\xE7o de e-mail", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "data e hora ISO", + date: "data ISO", + time: "hora ISO", + duration: "dura\xE7\xE3o ISO", + ipv4: "endere\xE7o IPv4", + ipv6: "endere\xE7o IPv6", + cidrv4: "faixa de IPv4", + cidrv6: "faixa de IPv6", + base64: "texto codificado em base64", + base64url: "URL codificada em base64", + json_string: "texto JSON", + e164: "n\xFAmero E.164", + jwt: "JWT", + template_literal: "entrada" + }; + const TypeDictionary = { + nan: "NaN", + number: "n\xFAmero", + null: "nulo" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Tipo inv\xE1lido: esperado instanceof ${issue2.expected}, recebido ${received}`; + } + return `Tipo inv\xE1lido: esperado ${expected}, recebido ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Entrada inv\xE1lida: esperado ${stringifyPrimitive(issue2.values[0])}`; + return `Op\xE7\xE3o inv\xE1lida: esperada uma das ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Muito grande: esperado que ${issue2.origin ?? "valor"} tivesse ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementos"}`; + return `Muito grande: esperado que ${issue2.origin ?? "valor"} fosse ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Muito pequeno: esperado que ${issue2.origin} tivesse ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `Muito pequeno: esperado que ${issue2.origin} fosse ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Texto inv\xE1lido: deve come\xE7ar com "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Texto inv\xE1lido: deve terminar com "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Texto inv\xE1lido: deve incluir "${_issue.includes}"`; + if (_issue.format === "regex") + return `Texto inv\xE1lido: deve corresponder ao padr\xE3o ${_issue.pattern}`; + return `${FormatDictionary[_issue.format] ?? issue2.format} inv\xE1lido`; + } + case "not_multiple_of": + return `N\xFAmero inv\xE1lido: deve ser m\xFAltiplo de ${issue2.divisor}`; + case "unrecognized_keys": + return `Chave${issue2.keys.length > 1 ? "s" : ""} desconhecida${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Chave inv\xE1lida em ${issue2.origin}`; + case "invalid_union": + return "Entrada inv\xE1lida"; + case "invalid_element": + return `Valor inv\xE1lido em ${issue2.origin}`; + default: + return `Campo inv\xE1lido`; + } + }; + }; + } +}); + +// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ru.js +function getRussianPlural(count2, one, few, many) { + const absCount = Math.abs(count2); + const lastDigit = absCount % 10; + const lastTwoDigits = absCount % 100; + if (lastTwoDigits >= 11 && lastTwoDigits <= 19) { + return many; + } + if (lastDigit === 1) { + return one; + } + if (lastDigit >= 2 && lastDigit <= 4) { + return few; + } + return many; +} +function ru_default() { + return { + localeError: error36() + }; +} +var error36; +var init_ru = __esm({ + "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ru.js"() { + init_util(); + error36 = () => { + const Sizable = { + string: { + unit: { + one: "\u0441\u0438\u043C\u0432\u043E\u043B", + few: "\u0441\u0438\u043C\u0432\u043E\u043B\u0430", + many: "\u0441\u0438\u043C\u0432\u043E\u043B\u043E\u0432" + }, + verb: "\u0438\u043C\u0435\u0442\u044C" + }, + file: { + unit: { + one: "\u0431\u0430\u0439\u0442", + few: "\u0431\u0430\u0439\u0442\u0430", + many: "\u0431\u0430\u0439\u0442" + }, + verb: "\u0438\u043C\u0435\u0442\u044C" + }, + array: { + unit: { + one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442", + few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430", + many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432" + }, + verb: "\u0438\u043C\u0435\u0442\u044C" + }, + set: { + unit: { + one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442", + few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430", + many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432" + }, + verb: "\u0438\u043C\u0435\u0442\u044C" + } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0432\u0432\u043E\u0434", + email: "email \u0430\u0434\u0440\u0435\u0441", + url: "URL", + emoji: "\u044D\u043C\u043E\u0434\u0437\u0438", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u0434\u0430\u0442\u0430 \u0438 \u0432\u0440\u0435\u043C\u044F", + date: "ISO \u0434\u0430\u0442\u0430", + time: "ISO \u0432\u0440\u0435\u043C\u044F", + duration: "ISO \u0434\u043B\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u044C", + ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441", + ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441", + cidrv4: "IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", + cidrv6: "IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", + base64: "\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64", + base64url: "\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64url", + json_string: "JSON \u0441\u0442\u0440\u043E\u043A\u0430", + e164: "\u043D\u043E\u043C\u0435\u0440 E.164", + jwt: "JWT", + template_literal: "\u0432\u0432\u043E\u0434" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u0447\u0438\u0441\u043B\u043E", + array: "\u043C\u0430\u0441\u0441\u0438\u0432" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C instanceof ${issue2.expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u043E ${received}`; + } + return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u043E ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${stringifyPrimitive(issue2.values[0])}`; + return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0430\u0440\u0438\u0430\u043D\u0442: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C \u043E\u0434\u043D\u043E \u0438\u0437 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) { + const maxValue = Number(issue2.maximum); + const unit = getRussianPlural(maxValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); + return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${adj}${issue2.maximum.toString()} ${unit}`; + } + return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + const minValue = Number(issue2.minimum); + const unit = getRussianPlural(minValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); + return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue2.origin} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${adj}${issue2.minimum.toString()} ${unit}`; + } + return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue2.origin} \u0431\u0443\u0434\u0435\u0442 ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u043D\u0430\u0447\u0438\u043D\u0430\u0442\u044C\u0441\u044F \u0441 "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0437\u0430\u043A\u0430\u043D\u0447\u0438\u0432\u0430\u0442\u044C\u0441\u044F \u043D\u0430 "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u0434\u0435\u0440\u0436\u0430\u0442\u044C "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u043E\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u043E\u0432\u0430\u0442\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${_issue.pattern}`; + return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0447\u0438\u0441\u043B\u043E: \u0434\u043E\u043B\u0436\u043D\u043E \u0431\u044B\u0442\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${issue2.divisor}`; + case "unrecognized_keys": + return `\u041D\u0435\u0440\u0430\u0441\u043F\u043E\u0437\u043D\u0430\u043D\u043D${issue2.keys.length > 1 ? "\u044B\u0435" : "\u044B\u0439"} \u043A\u043B\u044E\u0447${issue2.keys.length > 1 ? "\u0438" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u043A\u043B\u044E\u0447 \u0432 ${issue2.origin}`; + case "invalid_union": + return "\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435"; + case "invalid_element": + return `\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u0432 ${issue2.origin}`; + default: + return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435`; + } + }; + }; + } +}); + +// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/sl.js +function sl_default() { + return { + localeError: error37() + }; +} +var error37; +var init_sl = __esm({ + "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/sl.js"() { + init_util(); + error37 = () => { + const Sizable = { + string: { unit: "znakov", verb: "imeti" }, + file: { unit: "bajtov", verb: "imeti" }, + array: { unit: "elementov", verb: "imeti" }, + set: { unit: "elementov", verb: "imeti" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "vnos", + email: "e-po\u0161tni naslov", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO datum in \u010Das", + date: "ISO datum", + time: "ISO \u010Das", + duration: "ISO trajanje", + ipv4: "IPv4 naslov", + ipv6: "IPv6 naslov", + cidrv4: "obseg IPv4", + cidrv6: "obseg IPv6", + base64: "base64 kodiran niz", + base64url: "base64url kodiran niz", + json_string: "JSON niz", + e164: "E.164 \u0161tevilka", + jwt: "JWT", + template_literal: "vnos" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u0161tevilo", + array: "tabela" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Neveljaven vnos: pri\u010Dakovano instanceof ${issue2.expected}, prejeto ${received}`; + } + return `Neveljaven vnos: pri\u010Dakovano ${expected}, prejeto ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Neveljaven vnos: pri\u010Dakovano ${stringifyPrimitive(issue2.values[0])}`; + return `Neveljavna mo\u017Enost: pri\u010Dakovano eno izmed ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Preveliko: pri\u010Dakovano, da bo ${issue2.origin ?? "vrednost"} imelo ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementov"}`; + return `Preveliko: pri\u010Dakovano, da bo ${issue2.origin ?? "vrednost"} ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Premajhno: pri\u010Dakovano, da bo ${issue2.origin} imelo ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `Premajhno: pri\u010Dakovano, da bo ${issue2.origin} ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `Neveljaven niz: mora se za\u010Deti z "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `Neveljaven niz: mora se kon\u010Dati z "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Neveljaven niz: mora vsebovati "${_issue.includes}"`; + if (_issue.format === "regex") + return `Neveljaven niz: mora ustrezati vzorcu ${_issue.pattern}`; + return `Neveljaven ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Neveljavno \u0161tevilo: mora biti ve\u010Dkratnik ${issue2.divisor}`; + case "unrecognized_keys": + return `Neprepoznan${issue2.keys.length > 1 ? "i klju\u010Di" : " klju\u010D"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Neveljaven klju\u010D v ${issue2.origin}`; + case "invalid_union": + return "Neveljaven vnos"; + case "invalid_element": + return `Neveljavna vrednost v ${issue2.origin}`; + default: + return "Neveljaven vnos"; + } + }; + }; + } +}); + +// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/sv.js +function sv_default() { + return { + localeError: error38() + }; +} +var error38; +var init_sv = __esm({ + "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/sv.js"() { + init_util(); + error38 = () => { + const Sizable = { + string: { unit: "tecken", verb: "att ha" }, + file: { unit: "bytes", verb: "att ha" }, + array: { unit: "objekt", verb: "att inneh\xE5lla" }, + set: { unit: "objekt", verb: "att inneh\xE5lla" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "regulj\xE4rt uttryck", + email: "e-postadress", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO-datum och tid", + date: "ISO-datum", + time: "ISO-tid", + duration: "ISO-varaktighet", + ipv4: "IPv4-intervall", + ipv6: "IPv6-intervall", + cidrv4: "IPv4-spektrum", + cidrv6: "IPv6-spektrum", + base64: "base64-kodad str\xE4ng", + base64url: "base64url-kodad str\xE4ng", + json_string: "JSON-str\xE4ng", + e164: "E.164-nummer", + jwt: "JWT", + template_literal: "mall-literal" + }; + const TypeDictionary = { + nan: "NaN", + number: "antal", + array: "lista" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Ogiltig inmatning: f\xF6rv\xE4ntat instanceof ${issue2.expected}, fick ${received}`; + } + return `Ogiltig inmatning: f\xF6rv\xE4ntat ${expected}, fick ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Ogiltig inmatning: f\xF6rv\xE4ntat ${stringifyPrimitive(issue2.values[0])}`; + return `Ogiltigt val: f\xF6rv\xE4ntade en av ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `F\xF6r stor(t): f\xF6rv\xE4ntade ${issue2.origin ?? "v\xE4rdet"} att ha ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "element"}`; + } + return `F\xF6r stor(t): f\xF6rv\xE4ntat ${issue2.origin ?? "v\xE4rdet"} att ha ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `F\xF6r lite(t): f\xF6rv\xE4ntade ${issue2.origin ?? "v\xE4rdet"} att ha ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `F\xF6r lite(t): f\xF6rv\xE4ntade ${issue2.origin ?? "v\xE4rdet"} att ha ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `Ogiltig str\xE4ng: m\xE5ste b\xF6rja med "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `Ogiltig str\xE4ng: m\xE5ste sluta med "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Ogiltig str\xE4ng: m\xE5ste inneh\xE5lla "${_issue.includes}"`; + if (_issue.format === "regex") + return `Ogiltig str\xE4ng: m\xE5ste matcha m\xF6nstret "${_issue.pattern}"`; + return `Ogiltig(t) ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Ogiltigt tal: m\xE5ste vara en multipel av ${issue2.divisor}`; + case "unrecognized_keys": + return `${issue2.keys.length > 1 ? "Ok\xE4nda nycklar" : "Ok\xE4nd nyckel"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Ogiltig nyckel i ${issue2.origin ?? "v\xE4rdet"}`; + case "invalid_union": + return "Ogiltig input"; + case "invalid_element": + return `Ogiltigt v\xE4rde i ${issue2.origin ?? "v\xE4rdet"}`; + default: + return `Ogiltig input`; + } + }; + }; + } +}); + +// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ta.js +function ta_default() { + return { + localeError: error39() + }; +} +var error39; +var init_ta = __esm({ + "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ta.js"() { + init_util(); + error39 = () => { + const Sizable = { + string: { unit: "\u0B8E\u0BB4\u0BC1\u0BA4\u0BCD\u0BA4\u0BC1\u0B95\u0BCD\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, + file: { unit: "\u0BAA\u0BC8\u0B9F\u0BCD\u0B9F\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, + array: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, + set: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1", + email: "\u0BAE\u0BBF\u0BA9\u0BCD\u0BA9\u0B9E\u0BCD\u0B9A\u0BB2\u0BCD \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u0BA4\u0BC7\u0BA4\u0BBF \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD", + date: "ISO \u0BA4\u0BC7\u0BA4\u0BBF", + time: "ISO \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD", + duration: "ISO \u0B95\u0BBE\u0BB2 \u0B85\u0BB3\u0BB5\u0BC1", + ipv4: "IPv4 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF", + ipv6: "IPv6 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF", + cidrv4: "IPv4 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1", + cidrv6: "IPv6 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1", + base64: "base64-encoded \u0B9A\u0BB0\u0BAE\u0BCD", + base64url: "base64url-encoded \u0B9A\u0BB0\u0BAE\u0BCD", + json_string: "JSON \u0B9A\u0BB0\u0BAE\u0BCD", + e164: "E.164 \u0B8E\u0BA3\u0BCD", + jwt: "JWT", + template_literal: "input" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u0B8E\u0BA3\u0BCD", + array: "\u0B85\u0BA3\u0BBF", + null: "\u0BB5\u0BC6\u0BB1\u0BC1\u0BAE\u0BC8" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 instanceof ${issue2.expected}, \u0BAA\u0BC6\u0BB1\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${received}`; + } + return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${expected}, \u0BAA\u0BC6\u0BB1\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${stringifyPrimitive(issue2.values[0])}`; + return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0BB0\u0BC1\u0BAA\u0BCD\u0BAA\u0BAE\u0BCD: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${joinValues(issue2.values, "|")} \u0B87\u0BB2\u0BCD \u0B92\u0BA9\u0BCD\u0BB1\u0BC1`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.origin ?? "\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD"} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; + } + return `\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.origin ?? "\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${adj}${issue2.maximum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; + } + return `\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.origin} ${adj}${issue2.minimum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${_issue.prefix}" \u0B87\u0BB2\u0BCD \u0BA4\u0BCA\u0B9F\u0B99\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; + if (_issue.format === "ends_with") + return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${_issue.suffix}" \u0B87\u0BB2\u0BCD \u0BAE\u0BC1\u0B9F\u0BBF\u0BB5\u0B9F\u0BC8\u0BAF \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; + if (_issue.format === "includes") + return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${_issue.includes}" \u0B90 \u0B89\u0BB3\u0BCD\u0BB3\u0B9F\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; + if (_issue.format === "regex") + return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: ${_issue.pattern} \u0BAE\u0BC1\u0BB1\u0BC8\u0BAA\u0BBE\u0B9F\u0BCD\u0B9F\u0BC1\u0B9F\u0BA9\u0BCD \u0BAA\u0BCA\u0BB0\u0BC1\u0BA8\u0BCD\u0BA4 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; + return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B8E\u0BA3\u0BCD: ${issue2.divisor} \u0B87\u0BA9\u0BCD \u0BAA\u0BB2\u0BAE\u0BBE\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; + case "unrecognized_keys": + return `\u0B85\u0B9F\u0BC8\u0BAF\u0BBE\u0BB3\u0BAE\u0BCD \u0BA4\u0BC6\u0BB0\u0BBF\u0BAF\u0BBE\u0BA4 \u0BB5\u0BBF\u0B9A\u0BC8${issue2.keys.length > 1 ? "\u0B95\u0BB3\u0BCD" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `${issue2.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0B9A\u0BC8`; + case "invalid_union": + return "\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1"; + case "invalid_element": + return `${issue2.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1`; + default: + return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1`; + } + }; + }; + } +}); + +// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/th.js +function th_default() { + return { + localeError: error40() + }; +} +var error40; +var init_th = __esm({ + "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/th.js"() { + init_util(); + error40 = () => { + const Sizable = { + string: { unit: "\u0E15\u0E31\u0E27\u0E2D\u0E31\u0E01\u0E29\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, + file: { unit: "\u0E44\u0E1A\u0E15\u0E4C", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, + array: { unit: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, + set: { unit: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19", + email: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48\u0E2D\u0E35\u0E40\u0E21\u0E25", + url: "URL", + emoji: "\u0E2D\u0E34\u0E42\u0E21\u0E08\u0E34", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO", + date: "\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E41\u0E1A\u0E1A ISO", + time: "\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO", + duration: "\u0E0A\u0E48\u0E27\u0E07\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO", + ipv4: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv4", + ipv6: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv6", + cidrv4: "\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv4", + cidrv6: "\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv6", + base64: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64", + base64url: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64 \u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A URL", + json_string: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A JSON", + e164: "\u0E40\u0E1A\u0E2D\u0E23\u0E4C\u0E42\u0E17\u0E23\u0E28\u0E31\u0E1E\u0E17\u0E4C\u0E23\u0E30\u0E2B\u0E27\u0E48\u0E32\u0E07\u0E1B\u0E23\u0E30\u0E40\u0E17\u0E28 (E.164)", + jwt: "\u0E42\u0E17\u0E40\u0E04\u0E19 JWT", + template_literal: "\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02", + array: "\u0E2D\u0E32\u0E23\u0E4C\u0E40\u0E23\u0E22\u0E4C (Array)", + null: "\u0E44\u0E21\u0E48\u0E21\u0E35\u0E04\u0E48\u0E32 (null)" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u0E1B\u0E23\u0E30\u0E40\u0E20\u0E17\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 instanceof ${issue2.expected} \u0E41\u0E15\u0E48\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A ${received}`; + } + return `\u0E1B\u0E23\u0E30\u0E40\u0E20\u0E17\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${expected} \u0E41\u0E15\u0E48\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0E04\u0E48\u0E32\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${stringifyPrimitive(issue2.values[0])}`; + return `\u0E15\u0E31\u0E27\u0E40\u0E25\u0E37\u0E2D\u0E01\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19\u0E2B\u0E19\u0E36\u0E48\u0E07\u0E43\u0E19 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "\u0E44\u0E21\u0E48\u0E40\u0E01\u0E34\u0E19" : "\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue2.origin ?? "\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23"}`; + return `\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue2.origin ?? "\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? "\u0E2D\u0E22\u0E48\u0E32\u0E07\u0E19\u0E49\u0E2D\u0E22" : "\u0E21\u0E32\u0E01\u0E01\u0E27\u0E48\u0E32"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue2.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue2.minimum.toString()} ${sizing.unit}`; + } + return `\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue2.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E02\u0E36\u0E49\u0E19\u0E15\u0E49\u0E19\u0E14\u0E49\u0E27\u0E22 "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E25\u0E07\u0E17\u0E49\u0E32\u0E22\u0E14\u0E49\u0E27\u0E22 "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E21\u0E35 "${_issue.includes}" \u0E2D\u0E22\u0E39\u0E48\u0E43\u0E19\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21`; + if (_issue.format === "regex") + return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14 ${_issue.pattern}`; + return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E40\u0E1B\u0E47\u0E19\u0E08\u0E33\u0E19\u0E27\u0E19\u0E17\u0E35\u0E48\u0E2B\u0E32\u0E23\u0E14\u0E49\u0E27\u0E22 ${issue2.divisor} \u0E44\u0E14\u0E49\u0E25\u0E07\u0E15\u0E31\u0E27`; + case "unrecognized_keys": + return `\u0E1E\u0E1A\u0E04\u0E35\u0E22\u0E4C\u0E17\u0E35\u0E48\u0E44\u0E21\u0E48\u0E23\u0E39\u0E49\u0E08\u0E31\u0E01: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u0E04\u0E35\u0E22\u0E4C\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${issue2.origin}`; + case "invalid_union": + return "\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E44\u0E21\u0E48\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E22\u0E39\u0E40\u0E19\u0E35\u0E22\u0E19\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14\u0E44\u0E27\u0E49"; + case "invalid_element": + return `\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${issue2.origin}`; + default: + return `\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07`; + } + }; + }; + } +}); + +// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/tr.js +function tr_default() { + return { + localeError: error41() + }; +} +var error41; +var init_tr = __esm({ + "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/tr.js"() { + init_util(); + error41 = () => { + const Sizable = { + string: { unit: "karakter", verb: "olmal\u0131" }, + file: { unit: "bayt", verb: "olmal\u0131" }, + array: { unit: "\xF6\u011Fe", verb: "olmal\u0131" }, + set: { unit: "\xF6\u011Fe", verb: "olmal\u0131" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "girdi", + email: "e-posta adresi", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO tarih ve saat", + date: "ISO tarih", + time: "ISO saat", + duration: "ISO s\xFCre", + ipv4: "IPv4 adresi", + ipv6: "IPv6 adresi", + cidrv4: "IPv4 aral\u0131\u011F\u0131", + cidrv6: "IPv6 aral\u0131\u011F\u0131", + base64: "base64 ile \u015Fifrelenmi\u015F metin", + base64url: "base64url ile \u015Fifrelenmi\u015F metin", + json_string: "JSON dizesi", + e164: "E.164 say\u0131s\u0131", + jwt: "JWT", + template_literal: "\u015Eablon dizesi" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Ge\xE7ersiz de\u011Fer: beklenen instanceof ${issue2.expected}, al\u0131nan ${received}`; + } + return `Ge\xE7ersiz de\u011Fer: beklenen ${expected}, al\u0131nan ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Ge\xE7ersiz de\u011Fer: beklenen ${stringifyPrimitive(issue2.values[0])}`; + return `Ge\xE7ersiz se\xE7enek: a\u015Fa\u011F\u0131dakilerden biri olmal\u0131: ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\xC7ok b\xFCy\xFCk: beklenen ${issue2.origin ?? "de\u011Fer"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\xF6\u011Fe"}`; + return `\xC7ok b\xFCy\xFCk: beklenen ${issue2.origin ?? "de\u011Fer"} ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\xC7ok k\xFC\xE7\xFCk: beklenen ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + return `\xC7ok k\xFC\xE7\xFCk: beklenen ${issue2.origin} ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Ge\xE7ersiz metin: "${_issue.prefix}" ile ba\u015Flamal\u0131`; + if (_issue.format === "ends_with") + return `Ge\xE7ersiz metin: "${_issue.suffix}" ile bitmeli`; + if (_issue.format === "includes") + return `Ge\xE7ersiz metin: "${_issue.includes}" i\xE7ermeli`; + if (_issue.format === "regex") + return `Ge\xE7ersiz metin: ${_issue.pattern} desenine uymal\u0131`; + return `Ge\xE7ersiz ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Ge\xE7ersiz say\u0131: ${issue2.divisor} ile tam b\xF6l\xFCnebilmeli`; + case "unrecognized_keys": + return `Tan\u0131nmayan anahtar${issue2.keys.length > 1 ? "lar" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `${issue2.origin} i\xE7inde ge\xE7ersiz anahtar`; + case "invalid_union": + return "Ge\xE7ersiz de\u011Fer"; + case "invalid_element": + return `${issue2.origin} i\xE7inde ge\xE7ersiz de\u011Fer`; + default: + return `Ge\xE7ersiz de\u011Fer`; + } + }; + }; + } +}); + +// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/uk.js +function uk_default() { + return { + localeError: error42() + }; +} +var error42; +var init_uk = __esm({ + "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/uk.js"() { + init_util(); + error42 = () => { + const Sizable = { + string: { unit: "\u0441\u0438\u043C\u0432\u043E\u043B\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, + file: { unit: "\u0431\u0430\u0439\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, + array: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, + set: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456", + email: "\u0430\u0434\u0440\u0435\u0441\u0430 \u0435\u043B\u0435\u043A\u0442\u0440\u043E\u043D\u043D\u043E\u0457 \u043F\u043E\u0448\u0442\u0438", + url: "URL", + emoji: "\u0435\u043C\u043E\u0434\u0437\u0456", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "\u0434\u0430\u0442\u0430 \u0442\u0430 \u0447\u0430\u0441 ISO", + date: "\u0434\u0430\u0442\u0430 ISO", + time: "\u0447\u0430\u0441 ISO", + duration: "\u0442\u0440\u0438\u0432\u0430\u043B\u0456\u0441\u0442\u044C ISO", + ipv4: "\u0430\u0434\u0440\u0435\u0441\u0430 IPv4", + ipv6: "\u0430\u0434\u0440\u0435\u0441\u0430 IPv6", + cidrv4: "\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv4", + cidrv6: "\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv6", + base64: "\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64", + base64url: "\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64url", + json_string: "\u0440\u044F\u0434\u043E\u043A JSON", + e164: "\u043D\u043E\u043C\u0435\u0440 E.164", + jwt: "JWT", + template_literal: "\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u0447\u0438\u0441\u043B\u043E", + array: "\u043C\u0430\u0441\u0438\u0432" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F instanceof ${issue2.expected}, \u043E\u0442\u0440\u0438\u043C\u0430\u043D\u043E ${received}`; + } + return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${expected}, \u043E\u0442\u0440\u0438\u043C\u0430\u043D\u043E ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${stringifyPrimitive(issue2.values[0])}`; + return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0430 \u043E\u043F\u0446\u0456\u044F: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F \u043E\u0434\u043D\u0435 \u0437 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432"}`; + return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} \u0431\u0443\u0434\u0435 ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue2.origin} \u0431\u0443\u0434\u0435 ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043F\u043E\u0447\u0438\u043D\u0430\u0442\u0438\u0441\u044F \u0437 "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0437\u0430\u043A\u0456\u043D\u0447\u0443\u0432\u0430\u0442\u0438\u0441\u044F \u043D\u0430 "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043C\u0456\u0441\u0442\u0438\u0442\u0438 "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0432\u0456\u0434\u043F\u043E\u0432\u0456\u0434\u0430\u0442\u0438 \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${_issue.pattern}`; + return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0447\u0438\u0441\u043B\u043E: \u043F\u043E\u0432\u0438\u043D\u043D\u043E \u0431\u0443\u0442\u0438 \u043A\u0440\u0430\u0442\u043D\u0438\u043C ${issue2.divisor}`; + case "unrecognized_keys": + return `\u041D\u0435\u0440\u043E\u0437\u043F\u0456\u0437\u043D\u0430\u043D\u0438\u0439 \u043A\u043B\u044E\u0447${issue2.keys.length > 1 ? "\u0456" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u043A\u043B\u044E\u0447 \u0443 ${issue2.origin}`; + case "invalid_union": + return "\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456"; + case "invalid_element": + return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F \u0443 ${issue2.origin}`; + default: + return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456`; + } + }; + }; + } +}); + +// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ua.js +function ua_default() { + return uk_default(); +} +var init_ua = __esm({ + "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ua.js"() { + init_uk(); + } +}); + +// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ur.js +function ur_default() { + return { + localeError: error43() + }; +} +var error43; +var init_ur = __esm({ + "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ur.js"() { + init_util(); + error43 = () => { + const Sizable = { + string: { unit: "\u062D\u0631\u0648\u0641", verb: "\u06C1\u0648\u0646\u0627" }, + file: { unit: "\u0628\u0627\u0626\u0679\u0633", verb: "\u06C1\u0648\u0646\u0627" }, + array: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" }, + set: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0627\u0646 \u067E\u0679", + email: "\u0627\u06CC \u0645\u06CC\u0644 \u0627\u06CC\u0688\u0631\u06CC\u0633", + url: "\u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644", + emoji: "\u0627\u06CC\u0645\u0648\u062C\u06CC", + uuid: "\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC", + uuidv4: "\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 4", + uuidv6: "\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 6", + nanoid: "\u0646\u06CC\u0646\u0648 \u0622\u0626\u06CC \u0688\u06CC", + guid: "\u062C\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC", + cuid: "\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC", + cuid2: "\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC 2", + ulid: "\u06CC\u0648 \u0627\u06CC\u0644 \u0622\u0626\u06CC \u0688\u06CC", + xid: "\u0627\u06CC\u06A9\u0633 \u0622\u0626\u06CC \u0688\u06CC", + ksuid: "\u06A9\u06D2 \u0627\u06CC\u0633 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC", + datetime: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0688\u06CC\u0679 \u0679\u0627\u0626\u0645", + date: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u062A\u0627\u0631\u06CC\u062E", + time: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0648\u0642\u062A", + duration: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0645\u062F\u062A", + ipv4: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0627\u06CC\u0688\u0631\u06CC\u0633", + ipv6: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0627\u06CC\u0688\u0631\u06CC\u0633", + cidrv4: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0631\u06CC\u0646\u062C", + cidrv6: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0631\u06CC\u0646\u062C", + base64: "\u0628\u06CC\u0633 64 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF", + base64url: "\u0628\u06CC\u0633 64 \u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF", + json_string: "\u062C\u06D2 \u0627\u06CC\u0633 \u0627\u0648 \u0627\u06CC\u0646 \u0633\u0679\u0631\u0646\u06AF", + e164: "\u0627\u06CC 164 \u0646\u0645\u0628\u0631", + jwt: "\u062C\u06D2 \u0688\u0628\u0644\u06CC\u0648 \u0679\u06CC", + template_literal: "\u0627\u0646 \u067E\u0679" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u0646\u0645\u0628\u0631", + array: "\u0622\u0631\u06D2", + null: "\u0646\u0644" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: instanceof ${issue2.expected} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627\u060C ${received} \u0645\u0648\u0635\u0648\u0644 \u06C1\u0648\u0627`; + } + return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${expected} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627\u060C ${received} \u0645\u0648\u0635\u0648\u0644 \u06C1\u0648\u0627`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${stringifyPrimitive(issue2.values[0])} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`; + return `\u063A\u0644\u0637 \u0622\u067E\u0634\u0646: ${joinValues(issue2.values, "|")} \u0645\u06CC\u06BA \u0633\u06D2 \u0627\u06CC\u06A9 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0628\u06C1\u062A \u0628\u0691\u0627: ${issue2.origin ?? "\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u06D2 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0639\u0646\u0627\u0635\u0631"} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`; + return `\u0628\u06C1\u062A \u0628\u0691\u0627: ${issue2.origin ?? "\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u0627 ${adj}${issue2.maximum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${issue2.origin} \u06A9\u06D2 ${adj}${issue2.minimum.toString()} ${sizing.unit} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`; + } + return `\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${issue2.origin} \u06A9\u0627 ${adj}${issue2.minimum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${_issue.prefix}" \u0633\u06D2 \u0634\u0631\u0648\u0639 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`; + } + if (_issue.format === "ends_with") + return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${_issue.suffix}" \u067E\u0631 \u062E\u062A\u0645 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`; + if (_issue.format === "includes") + return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${_issue.includes}" \u0634\u0627\u0645\u0644 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`; + if (_issue.format === "regex") + return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: \u067E\u06CC\u0679\u0631\u0646 ${_issue.pattern} \u0633\u06D2 \u0645\u06CC\u0686 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`; + return `\u063A\u0644\u0637 ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u063A\u0644\u0637 \u0646\u0645\u0628\u0631: ${issue2.divisor} \u06A9\u0627 \u0645\u0636\u0627\u0639\u0641 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`; + case "unrecognized_keys": + return `\u063A\u06CC\u0631 \u062A\u0633\u0644\u06CC\u0645 \u0634\u062F\u06C1 \u06A9\u06CC${issue2.keys.length > 1 ? "\u0632" : ""}: ${joinValues(issue2.keys, "\u060C ")}`; + case "invalid_key": + return `${issue2.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u06A9\u06CC`; + case "invalid_union": + return "\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679"; + case "invalid_element": + return `${issue2.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u0648\u06CC\u0644\u06CC\u0648`; + default: + return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679`; + } + }; + }; + } +}); + +// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/uz.js +function uz_default() { + return { + localeError: error44() + }; +} +var error44; +var init_uz = __esm({ + "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/uz.js"() { + init_util(); + error44 = () => { + const Sizable = { + string: { unit: "belgi", verb: "bo\u2018lishi kerak" }, + file: { unit: "bayt", verb: "bo\u2018lishi kerak" }, + array: { unit: "element", verb: "bo\u2018lishi kerak" }, + set: { unit: "element", verb: "bo\u2018lishi kerak" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "kirish", + email: "elektron pochta manzili", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO sana va vaqti", + date: "ISO sana", + time: "ISO vaqt", + duration: "ISO davomiylik", + ipv4: "IPv4 manzil", + ipv6: "IPv6 manzil", + mac: "MAC manzil", + cidrv4: "IPv4 diapazon", + cidrv6: "IPv6 diapazon", + base64: "base64 kodlangan satr", + base64url: "base64url kodlangan satr", + json_string: "JSON satr", + e164: "E.164 raqam", + jwt: "JWT", + template_literal: "kirish" + }; + const TypeDictionary = { + nan: "NaN", + number: "raqam", + array: "massiv" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Noto\u2018g\u2018ri kirish: kutilgan instanceof ${issue2.expected}, qabul qilingan ${received}`; + } + return `Noto\u2018g\u2018ri kirish: kutilgan ${expected}, qabul qilingan ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Noto\u2018g\u2018ri kirish: kutilgan ${stringifyPrimitive(issue2.values[0])}`; + return `Noto\u2018g\u2018ri variant: quyidagilardan biri kutilgan ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Juda katta: kutilgan ${issue2.origin ?? "qiymat"} ${adj}${issue2.maximum.toString()} ${sizing.unit} ${sizing.verb}`; + return `Juda katta: kutilgan ${issue2.origin ?? "qiymat"} ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Juda kichik: kutilgan ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} ${sizing.verb}`; + } + return `Juda kichik: kutilgan ${issue2.origin} ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Noto\u2018g\u2018ri satr: "${_issue.prefix}" bilan boshlanishi kerak`; + if (_issue.format === "ends_with") + return `Noto\u2018g\u2018ri satr: "${_issue.suffix}" bilan tugashi kerak`; + if (_issue.format === "includes") + return `Noto\u2018g\u2018ri satr: "${_issue.includes}" ni o\u2018z ichiga olishi kerak`; + if (_issue.format === "regex") + return `Noto\u2018g\u2018ri satr: ${_issue.pattern} shabloniga mos kelishi kerak`; + return `Noto\u2018g\u2018ri ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Noto\u2018g\u2018ri raqam: ${issue2.divisor} ning karralisi bo\u2018lishi kerak`; + case "unrecognized_keys": + return `Noma\u2019lum kalit${issue2.keys.length > 1 ? "lar" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `${issue2.origin} dagi kalit noto\u2018g\u2018ri`; + case "invalid_union": + return "Noto\u2018g\u2018ri kirish"; + case "invalid_element": + return `${issue2.origin} da noto\u2018g\u2018ri qiymat`; + default: + return `Noto\u2018g\u2018ri kirish`; + } + }; + }; + } +}); + +// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/vi.js +function vi_default() { + return { + localeError: error45() + }; +} +var error45; +var init_vi = __esm({ + "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/vi.js"() { + init_util(); + error45 = () => { + const Sizable = { + string: { unit: "k\xFD t\u1EF1", verb: "c\xF3" }, + file: { unit: "byte", verb: "c\xF3" }, + array: { unit: "ph\u1EA7n t\u1EED", verb: "c\xF3" }, + set: { unit: "ph\u1EA7n t\u1EED", verb: "c\xF3" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u0111\u1EA7u v\xE0o", + email: "\u0111\u1ECBa ch\u1EC9 email", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ng\xE0y gi\u1EDD ISO", + date: "ng\xE0y ISO", + time: "gi\u1EDD ISO", + duration: "kho\u1EA3ng th\u1EDDi gian ISO", + ipv4: "\u0111\u1ECBa ch\u1EC9 IPv4", + ipv6: "\u0111\u1ECBa ch\u1EC9 IPv6", + cidrv4: "d\u1EA3i IPv4", + cidrv6: "d\u1EA3i IPv6", + base64: "chu\u1ED7i m\xE3 h\xF3a base64", + base64url: "chu\u1ED7i m\xE3 h\xF3a base64url", + json_string: "chu\u1ED7i JSON", + e164: "s\u1ED1 E.164", + jwt: "JWT", + template_literal: "\u0111\u1EA7u v\xE0o" + }; + const TypeDictionary = { + nan: "NaN", + number: "s\u1ED1", + array: "m\u1EA3ng" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i instanceof ${issue2.expected}, nh\u1EADn \u0111\u01B0\u1EE3c ${received}`; + } + return `\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${expected}, nh\u1EADn \u0111\u01B0\u1EE3c ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${stringifyPrimitive(issue2.values[0])}`; + return `T\xF9y ch\u1ECDn kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i m\u1ED9t trong c\xE1c gi\xE1 tr\u1ECB ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${issue2.origin ?? "gi\xE1 tr\u1ECB"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "ph\u1EA7n t\u1EED"}`; + return `Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${issue2.origin ?? "gi\xE1 tr\u1ECB"} ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${issue2.origin} ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i b\u1EAFt \u0111\u1EA7u b\u1EB1ng "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i k\u1EBFt th\xFAc b\u1EB1ng "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i bao g\u1ED3m "${_issue.includes}"`; + if (_issue.format === "regex") + return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i kh\u1EDBp v\u1EDBi m\u1EABu ${_issue.pattern}`; + return `${FormatDictionary[_issue.format] ?? issue2.format} kh\xF4ng h\u1EE3p l\u1EC7`; + } + case "not_multiple_of": + return `S\u1ED1 kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i l\xE0 b\u1ED9i s\u1ED1 c\u1EE7a ${issue2.divisor}`; + case "unrecognized_keys": + return `Kh\xF3a kh\xF4ng \u0111\u01B0\u1EE3c nh\u1EADn d\u1EA1ng: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Kh\xF3a kh\xF4ng h\u1EE3p l\u1EC7 trong ${issue2.origin}`; + case "invalid_union": + return "\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7"; + case "invalid_element": + return `Gi\xE1 tr\u1ECB kh\xF4ng h\u1EE3p l\u1EC7 trong ${issue2.origin}`; + default: + return `\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7`; + } + }; + }; + } +}); + +// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/zh-CN.js +function zh_CN_default() { + return { + localeError: error46() + }; +} +var error46; +var init_zh_CN = __esm({ + "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/zh-CN.js"() { + init_util(); + error46 = () => { + const Sizable = { + string: { unit: "\u5B57\u7B26", verb: "\u5305\u542B" }, + file: { unit: "\u5B57\u8282", verb: "\u5305\u542B" }, + array: { unit: "\u9879", verb: "\u5305\u542B" }, + set: { unit: "\u9879", verb: "\u5305\u542B" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u8F93\u5165", + email: "\u7535\u5B50\u90AE\u4EF6", + url: "URL", + emoji: "\u8868\u60C5\u7B26\u53F7", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO\u65E5\u671F\u65F6\u95F4", + date: "ISO\u65E5\u671F", + time: "ISO\u65F6\u95F4", + duration: "ISO\u65F6\u957F", + ipv4: "IPv4\u5730\u5740", + ipv6: "IPv6\u5730\u5740", + cidrv4: "IPv4\u7F51\u6BB5", + cidrv6: "IPv6\u7F51\u6BB5", + base64: "base64\u7F16\u7801\u5B57\u7B26\u4E32", + base64url: "base64url\u7F16\u7801\u5B57\u7B26\u4E32", + json_string: "JSON\u5B57\u7B26\u4E32", + e164: "E.164\u53F7\u7801", + jwt: "JWT", + template_literal: "\u8F93\u5165" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u6570\u5B57", + array: "\u6570\u7EC4", + null: "\u7A7A\u503C(null)" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B instanceof ${issue2.expected}\uFF0C\u5B9E\u9645\u63A5\u6536 ${received}`; + } + return `\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${expected}\uFF0C\u5B9E\u9645\u63A5\u6536 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${stringifyPrimitive(issue2.values[0])}`; + return `\u65E0\u6548\u9009\u9879\uFF1A\u671F\u671B\u4EE5\u4E0B\u4E4B\u4E00 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${issue2.origin ?? "\u503C"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u4E2A\u5143\u7D20"}`; + return `\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${issue2.origin ?? "\u503C"} ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${issue2.origin} ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${_issue.prefix}" \u5F00\u5934`; + if (_issue.format === "ends_with") + return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${_issue.suffix}" \u7ED3\u5C3E`; + if (_issue.format === "includes") + return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u5305\u542B "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u6EE1\u8DB3\u6B63\u5219\u8868\u8FBE\u5F0F ${_issue.pattern}`; + return `\u65E0\u6548${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u65E0\u6548\u6570\u5B57\uFF1A\u5FC5\u987B\u662F ${issue2.divisor} \u7684\u500D\u6570`; + case "unrecognized_keys": + return `\u51FA\u73B0\u672A\u77E5\u7684\u952E(key): ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `${issue2.origin} \u4E2D\u7684\u952E(key)\u65E0\u6548`; + case "invalid_union": + return "\u65E0\u6548\u8F93\u5165"; + case "invalid_element": + return `${issue2.origin} \u4E2D\u5305\u542B\u65E0\u6548\u503C(value)`; + default: + return `\u65E0\u6548\u8F93\u5165`; + } + }; + }; + } +}); + +// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/zh-TW.js +function zh_TW_default() { + return { + localeError: error47() + }; +} +var error47; +var init_zh_TW = __esm({ + "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/zh-TW.js"() { + init_util(); + error47 = () => { + const Sizable = { + string: { unit: "\u5B57\u5143", verb: "\u64C1\u6709" }, + file: { unit: "\u4F4D\u5143\u7D44", verb: "\u64C1\u6709" }, + array: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" }, + set: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u8F38\u5165", + email: "\u90F5\u4EF6\u5730\u5740", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u65E5\u671F\u6642\u9593", + date: "ISO \u65E5\u671F", + time: "ISO \u6642\u9593", + duration: "ISO \u671F\u9593", + ipv4: "IPv4 \u4F4D\u5740", + ipv6: "IPv6 \u4F4D\u5740", + cidrv4: "IPv4 \u7BC4\u570D", + cidrv6: "IPv6 \u7BC4\u570D", + base64: "base64 \u7DE8\u78BC\u5B57\u4E32", + base64url: "base64url \u7DE8\u78BC\u5B57\u4E32", + json_string: "JSON \u5B57\u4E32", + e164: "E.164 \u6578\u503C", + jwt: "JWT", + template_literal: "\u8F38\u5165" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA instanceof ${issue2.expected}\uFF0C\u4F46\u6536\u5230 ${received}`; + } + return `\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${expected}\uFF0C\u4F46\u6536\u5230 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${stringifyPrimitive(issue2.values[0])}`; + return `\u7121\u6548\u7684\u9078\u9805\uFF1A\u9810\u671F\u70BA\u4EE5\u4E0B\u5176\u4E2D\u4E4B\u4E00 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${issue2.origin ?? "\u503C"} \u61C9\u70BA ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u500B\u5143\u7D20"}`; + return `\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${issue2.origin ?? "\u503C"} \u61C9\u70BA ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${issue2.origin} \u61C9\u70BA ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${issue2.origin} \u61C9\u70BA ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${_issue.prefix}" \u958B\u982D`; + } + if (_issue.format === "ends_with") + return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${_issue.suffix}" \u7D50\u5C3E`; + if (_issue.format === "includes") + return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u5305\u542B "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u7B26\u5408\u683C\u5F0F ${_issue.pattern}`; + return `\u7121\u6548\u7684 ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u7121\u6548\u7684\u6578\u5B57\uFF1A\u5FC5\u9808\u70BA ${issue2.divisor} \u7684\u500D\u6578`; + case "unrecognized_keys": + return `\u7121\u6CD5\u8B58\u5225\u7684\u9375\u503C${issue2.keys.length > 1 ? "\u5011" : ""}\uFF1A${joinValues(issue2.keys, "\u3001")}`; + case "invalid_key": + return `${issue2.origin} \u4E2D\u6709\u7121\u6548\u7684\u9375\u503C`; + case "invalid_union": + return "\u7121\u6548\u7684\u8F38\u5165\u503C"; + case "invalid_element": + return `${issue2.origin} \u4E2D\u6709\u7121\u6548\u7684\u503C`; + default: + return `\u7121\u6548\u7684\u8F38\u5165\u503C`; + } + }; + }; + } +}); + +// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/yo.js +function yo_default() { + return { + localeError: error48() + }; +} +var error48; +var init_yo = __esm({ + "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/yo.js"() { + init_util(); + error48 = () => { + const Sizable = { + string: { unit: "\xE0mi", verb: "n\xED" }, + file: { unit: "bytes", verb: "n\xED" }, + array: { unit: "nkan", verb: "n\xED" }, + set: { unit: "nkan", verb: "n\xED" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "\u1EB9\u0300r\u1ECD \xECb\xE1w\u1ECDl\xE9", + email: "\xE0d\xEDr\u1EB9\u0301s\xEC \xECm\u1EB9\u0301l\xEC", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "\xE0k\xF3k\xF2 ISO", + date: "\u1ECDj\u1ECD\u0301 ISO", + time: "\xE0k\xF3k\xF2 ISO", + duration: "\xE0k\xF3k\xF2 t\xF3 p\xE9 ISO", + ipv4: "\xE0d\xEDr\u1EB9\u0301s\xEC IPv4", + ipv6: "\xE0d\xEDr\u1EB9\u0301s\xEC IPv6", + cidrv4: "\xE0gb\xE8gb\xE8 IPv4", + cidrv6: "\xE0gb\xE8gb\xE8 IPv6", + base64: "\u1ECD\u0300r\u1ECD\u0300 t\xED a k\u1ECD\u0301 n\xED base64", + base64url: "\u1ECD\u0300r\u1ECD\u0300 base64url", + json_string: "\u1ECD\u0300r\u1ECD\u0300 JSON", + e164: "n\u1ECD\u0301mb\xE0 E.164", + jwt: "JWT", + template_literal: "\u1EB9\u0300r\u1ECD \xECb\xE1w\u1ECDl\xE9" + }; + const TypeDictionary = { + nan: "NaN", + number: "n\u1ECD\u0301mb\xE0", + array: "akop\u1ECD" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": { + const expected = TypeDictionary[issue2.expected] ?? issue2.expected; + const receivedType = parsedType(issue2.input); + const received = TypeDictionary[receivedType] ?? receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi instanceof ${issue2.expected}, \xE0m\u1ECD\u0300 a r\xED ${received}`; + } + return `\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi ${expected}, \xE0m\u1ECD\u0300 a r\xED ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi ${stringifyPrimitive(issue2.values[0])}`; + return `\xC0\u1E63\xE0y\xE0n a\u1E63\xEC\u1E63e: yan \u1ECD\u0300kan l\xE1ra ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `T\xF3 p\u1ECD\u0300 j\xF9: a n\xED l\xE1ti j\u1EB9\u0301 p\xE9 ${issue2.origin ?? "iye"} ${sizing.verb} ${adj}${issue2.maximum} ${sizing.unit}`; + return `T\xF3 p\u1ECD\u0300 j\xF9: a n\xED l\xE1ti j\u1EB9\u0301 ${adj}${issue2.maximum}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `K\xE9r\xE9 ju: a n\xED l\xE1ti j\u1EB9\u0301 p\xE9 ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum} ${sizing.unit}`; + return `K\xE9r\xE9 ju: a n\xED l\xE1ti j\u1EB9\u0301 ${adj}${issue2.minimum}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 b\u1EB9\u0300r\u1EB9\u0300 p\u1EB9\u0300l\xFA "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 par\xED p\u1EB9\u0300l\xFA "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 n\xED "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 b\xE1 \xE0p\u1EB9\u1EB9r\u1EB9 mu ${_issue.pattern}`; + return `A\u1E63\xEC\u1E63e: ${FormatDictionary[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `N\u1ECD\u0301mb\xE0 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 j\u1EB9\u0301 \xE8y\xE0 p\xEDp\xEDn ti ${issue2.divisor}`; + case "unrecognized_keys": + return `B\u1ECDt\xECn\xEC \xE0\xECm\u1ECD\u0300: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `B\u1ECDt\xECn\xEC a\u1E63\xEC\u1E63e n\xEDn\xFA ${issue2.origin}`; + case "invalid_union": + return "\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e"; + case "invalid_element": + return `Iye a\u1E63\xEC\u1E63e n\xEDn\xFA ${issue2.origin}`; + default: + return "\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e"; + } + }; + }; + } +}); + +// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/index.js +var locales_exports = {}; +__export(locales_exports, { + ar: () => ar_default, + az: () => az_default, + be: () => be_default, + bg: () => bg_default, + ca: () => ca_default, + cs: () => cs_default, + da: () => da_default, + de: () => de_default, + en: () => en_default2, + eo: () => eo_default, + es: () => es_default, + fa: () => fa_default, + fi: () => fi_default, + fr: () => fr_default, + frCA: () => fr_CA_default, + he: () => he_default, + hu: () => hu_default, + hy: () => hy_default, + id: () => id_default, + is: () => is_default, + it: () => it_default, + ja: () => ja_default, + ka: () => ka_default, + kh: () => kh_default, + km: () => km_default, + ko: () => ko_default, + lt: () => lt_default, + mk: () => mk_default, + ms: () => ms_default, + nl: () => nl_default, + no: () => no_default, + ota: () => ota_default, + pl: () => pl_default, + ps: () => ps_default, + pt: () => pt_default, + ru: () => ru_default, + sl: () => sl_default, + sv: () => sv_default, + ta: () => ta_default, + th: () => th_default, + tr: () => tr_default, + ua: () => ua_default, + uk: () => uk_default, + ur: () => ur_default, + uz: () => uz_default, + vi: () => vi_default, + yo: () => yo_default, + zhCN: () => zh_CN_default, + zhTW: () => zh_TW_default +}); +var init_locales = __esm({ + "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/index.js"() { + init_ar(); + init_az(); + init_be(); + init_bg(); + init_ca(); + init_cs(); + init_da(); + init_de(); + init_en(); + init_eo(); + init_es(); + init_fa(); + init_fi(); + init_fr(); + init_fr_CA(); + init_he(); + init_hu(); + init_hy(); + init_id2(); + init_is(); + init_it(); + init_ja(); + init_ka(); + init_kh(); + init_km(); + init_ko(); + init_lt(); + init_mk(); + init_ms(); + init_nl(); + init_no(); + init_ota(); + init_ps(); + init_pl(); + init_pt(); + init_ru(); + init_sl(); + init_sv(); + init_ta(); + init_th(); + init_tr(); + init_ua(); + init_uk(); + init_ur(); + init_uz(); + init_vi(); + init_zh_CN(); + init_zh_TW(); + init_yo(); + } +}); + +// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/registries.js +function registry() { + return new $ZodRegistry(); +} +var _a2, $output, $input, $ZodRegistry, globalRegistry; +var init_registries = __esm({ + "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/registries.js"() { + $output = /* @__PURE__ */ Symbol("ZodOutput"); + $input = /* @__PURE__ */ Symbol("ZodInput"); + $ZodRegistry = class { + constructor() { + this._map = /* @__PURE__ */ new WeakMap(); + this._idmap = /* @__PURE__ */ new Map(); + } + add(schema2, ..._meta) { + const meta3 = _meta[0]; + this._map.set(schema2, meta3); + if (meta3 && typeof meta3 === "object" && "id" in meta3) { + this._idmap.set(meta3.id, schema2); + } + return this; + } + clear() { + this._map = /* @__PURE__ */ new WeakMap(); + this._idmap = /* @__PURE__ */ new Map(); + return this; + } + remove(schema2) { + const meta3 = this._map.get(schema2); + if (meta3 && typeof meta3 === "object" && "id" in meta3) { + this._idmap.delete(meta3.id); + } + this._map.delete(schema2); + return this; + } + get(schema2) { + const p5 = schema2._zod.parent; + if (p5) { + const pm = { ...this.get(p5) ?? {} }; + delete pm.id; + const f5 = { ...pm, ...this._map.get(schema2) }; + return Object.keys(f5).length ? f5 : void 0; + } + return this._map.get(schema2); + } + has(schema2) { + return this._map.has(schema2); + } + }; + (_a2 = globalThis).__zod_globalRegistry ?? (_a2.__zod_globalRegistry = registry()); + globalRegistry = globalThis.__zod_globalRegistry; + } +}); + +// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/api.js +// @__NO_SIDE_EFFECTS__ +function _string(Class2, params) { + return new Class2({ + type: "string", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _coercedString(Class2, params) { + return new Class2({ + type: "string", + coerce: true, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _email(Class2, params) { + return new Class2({ + type: "string", + format: "email", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _guid(Class2, params) { + return new Class2({ + type: "string", + format: "guid", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _uuid(Class2, params) { + return new Class2({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _uuidv4(Class2, params) { + return new Class2({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + version: "v4", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _uuidv6(Class2, params) { + return new Class2({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + version: "v6", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _uuidv7(Class2, params) { + return new Class2({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + version: "v7", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _url(Class2, params) { + return new Class2({ + type: "string", + format: "url", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _emoji2(Class2, params) { + return new Class2({ + type: "string", + format: "emoji", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _nanoid(Class2, params) { + return new Class2({ + type: "string", + format: "nanoid", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _cuid(Class2, params) { + return new Class2({ + type: "string", + format: "cuid", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _cuid2(Class2, params) { + return new Class2({ + type: "string", + format: "cuid2", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _ulid(Class2, params) { + return new Class2({ + type: "string", + format: "ulid", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _xid(Class2, params) { + return new Class2({ + type: "string", + format: "xid", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _ksuid(Class2, params) { + return new Class2({ + type: "string", + format: "ksuid", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _ipv4(Class2, params) { + return new Class2({ + type: "string", + format: "ipv4", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _ipv6(Class2, params) { + return new Class2({ + type: "string", + format: "ipv6", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _mac(Class2, params) { + return new Class2({ + type: "string", + format: "mac", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _cidrv4(Class2, params) { + return new Class2({ + type: "string", + format: "cidrv4", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _cidrv6(Class2, params) { + return new Class2({ + type: "string", + format: "cidrv6", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _base64(Class2, params) { + return new Class2({ + type: "string", + format: "base64", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _base64url(Class2, params) { + return new Class2({ + type: "string", + format: "base64url", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _e164(Class2, params) { + return new Class2({ + type: "string", + format: "e164", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _jwt(Class2, params) { + return new Class2({ + type: "string", + format: "jwt", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _isoDateTime(Class2, params) { + return new Class2({ + type: "string", + format: "datetime", + check: "string_format", + offset: false, + local: false, + precision: null, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _isoDate(Class2, params) { + return new Class2({ + type: "string", + format: "date", + check: "string_format", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _isoTime(Class2, params) { + return new Class2({ + type: "string", + format: "time", + check: "string_format", + precision: null, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _isoDuration(Class2, params) { + return new Class2({ + type: "string", + format: "duration", + check: "string_format", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _number(Class2, params) { + return new Class2({ + type: "number", + checks: [], + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _coercedNumber(Class2, params) { + return new Class2({ + type: "number", + coerce: true, + checks: [], + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _int(Class2, params) { + return new Class2({ + type: "number", + check: "number_format", + abort: false, + format: "safeint", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _float32(Class2, params) { + return new Class2({ + type: "number", + check: "number_format", + abort: false, + format: "float32", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _float64(Class2, params) { + return new Class2({ + type: "number", + check: "number_format", + abort: false, + format: "float64", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _int32(Class2, params) { + return new Class2({ + type: "number", + check: "number_format", + abort: false, + format: "int32", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _uint32(Class2, params) { + return new Class2({ + type: "number", + check: "number_format", + abort: false, + format: "uint32", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _boolean(Class2, params) { + return new Class2({ + type: "boolean", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _coercedBoolean(Class2, params) { + return new Class2({ + type: "boolean", + coerce: true, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _bigint(Class2, params) { + return new Class2({ + type: "bigint", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _coercedBigint(Class2, params) { + return new Class2({ + type: "bigint", + coerce: true, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _int64(Class2, params) { + return new Class2({ + type: "bigint", + check: "bigint_format", + abort: false, + format: "int64", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _uint64(Class2, params) { + return new Class2({ + type: "bigint", + check: "bigint_format", + abort: false, + format: "uint64", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _symbol(Class2, params) { + return new Class2({ + type: "symbol", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _undefined2(Class2, params) { + return new Class2({ + type: "undefined", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _null2(Class2, params) { + return new Class2({ + type: "null", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _any(Class2) { + return new Class2({ + type: "any" + }); +} +// @__NO_SIDE_EFFECTS__ +function _unknown(Class2) { + return new Class2({ + type: "unknown" + }); +} +// @__NO_SIDE_EFFECTS__ +function _never(Class2, params) { + return new Class2({ + type: "never", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _void(Class2, params) { + return new Class2({ + type: "void", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _date(Class2, params) { + return new Class2({ + type: "date", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _coercedDate(Class2, params) { + return new Class2({ + type: "date", + coerce: true, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _nan(Class2, params) { + return new Class2({ + type: "nan", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _lt(value, params) { + return new $ZodCheckLessThan({ + check: "less_than", + ...normalizeParams(params), + value, + inclusive: false + }); +} +// @__NO_SIDE_EFFECTS__ +function _lte(value, params) { + return new $ZodCheckLessThan({ + check: "less_than", + ...normalizeParams(params), + value, + inclusive: true + }); +} +// @__NO_SIDE_EFFECTS__ +function _gt(value, params) { + return new $ZodCheckGreaterThan({ + check: "greater_than", + ...normalizeParams(params), + value, + inclusive: false + }); +} +// @__NO_SIDE_EFFECTS__ +function _gte(value, params) { + return new $ZodCheckGreaterThan({ + check: "greater_than", + ...normalizeParams(params), + value, + inclusive: true + }); +} +// @__NO_SIDE_EFFECTS__ +function _positive(params) { + return /* @__PURE__ */ _gt(0, params); +} +// @__NO_SIDE_EFFECTS__ +function _negative(params) { + return /* @__PURE__ */ _lt(0, params); +} +// @__NO_SIDE_EFFECTS__ +function _nonpositive(params) { + return /* @__PURE__ */ _lte(0, params); +} +// @__NO_SIDE_EFFECTS__ +function _nonnegative(params) { + return /* @__PURE__ */ _gte(0, params); +} +// @__NO_SIDE_EFFECTS__ +function _multipleOf(value, params) { + return new $ZodCheckMultipleOf({ + check: "multiple_of", + ...normalizeParams(params), + value + }); +} +// @__NO_SIDE_EFFECTS__ +function _maxSize(maximum, params) { + return new $ZodCheckMaxSize({ + check: "max_size", + ...normalizeParams(params), + maximum + }); +} +// @__NO_SIDE_EFFECTS__ +function _minSize(minimum, params) { + return new $ZodCheckMinSize({ + check: "min_size", + ...normalizeParams(params), + minimum + }); +} +// @__NO_SIDE_EFFECTS__ +function _size(size2, params) { + return new $ZodCheckSizeEquals({ + check: "size_equals", + ...normalizeParams(params), + size: size2 + }); +} +// @__NO_SIDE_EFFECTS__ +function _maxLength(maximum, params) { + const ch = new $ZodCheckMaxLength({ + check: "max_length", + ...normalizeParams(params), + maximum + }); + return ch; +} +// @__NO_SIDE_EFFECTS__ +function _minLength(minimum, params) { + return new $ZodCheckMinLength({ + check: "min_length", + ...normalizeParams(params), + minimum + }); +} +// @__NO_SIDE_EFFECTS__ +function _length(length, params) { + return new $ZodCheckLengthEquals({ + check: "length_equals", + ...normalizeParams(params), + length + }); +} +// @__NO_SIDE_EFFECTS__ +function _regex(pattern, params) { + return new $ZodCheckRegex({ + check: "string_format", + format: "regex", + ...normalizeParams(params), + pattern + }); +} +// @__NO_SIDE_EFFECTS__ +function _lowercase(params) { + return new $ZodCheckLowerCase({ + check: "string_format", + format: "lowercase", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _uppercase(params) { + return new $ZodCheckUpperCase({ + check: "string_format", + format: "uppercase", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _includes(includes, params) { + return new $ZodCheckIncludes({ + check: "string_format", + format: "includes", + ...normalizeParams(params), + includes + }); +} +// @__NO_SIDE_EFFECTS__ +function _startsWith(prefix, params) { + return new $ZodCheckStartsWith({ + check: "string_format", + format: "starts_with", + ...normalizeParams(params), + prefix + }); +} +// @__NO_SIDE_EFFECTS__ +function _endsWith(suffix, params) { + return new $ZodCheckEndsWith({ + check: "string_format", + format: "ends_with", + ...normalizeParams(params), + suffix + }); +} +// @__NO_SIDE_EFFECTS__ +function _property(property, schema2, params) { + return new $ZodCheckProperty({ + check: "property", + property, + schema: schema2, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _mime(types2, params) { + return new $ZodCheckMimeType({ + check: "mime_type", + mime: types2, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _overwrite(tx) { + return new $ZodCheckOverwrite({ + check: "overwrite", + tx + }); +} +// @__NO_SIDE_EFFECTS__ +function _normalize(form) { + return /* @__PURE__ */ _overwrite((input) => input.normalize(form)); +} +// @__NO_SIDE_EFFECTS__ +function _trim() { + return /* @__PURE__ */ _overwrite((input) => input.trim()); +} +// @__NO_SIDE_EFFECTS__ +function _toLowerCase() { + return /* @__PURE__ */ _overwrite((input) => input.toLowerCase()); +} +// @__NO_SIDE_EFFECTS__ +function _toUpperCase() { + return /* @__PURE__ */ _overwrite((input) => input.toUpperCase()); +} +// @__NO_SIDE_EFFECTS__ +function _slugify() { + return /* @__PURE__ */ _overwrite((input) => slugify2(input)); +} +// @__NO_SIDE_EFFECTS__ +function _array(Class2, element, params) { + return new Class2({ + type: "array", + element, + // get element() { + // return element; + // }, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _union(Class2, options, params) { + return new Class2({ + type: "union", + options, + ...normalizeParams(params) + }); +} +function _xor(Class2, options, params) { + return new Class2({ + type: "union", + options, + inclusive: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _discriminatedUnion(Class2, discriminator, options, params) { + return new Class2({ + type: "union", + options, + discriminator, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _intersection(Class2, left, right) { + return new Class2({ + type: "intersection", + left, + right + }); +} +// @__NO_SIDE_EFFECTS__ +function _tuple(Class2, items, _paramsOrRest, _params) { + const hasRest = _paramsOrRest instanceof $ZodType; + const params = hasRest ? _params : _paramsOrRest; + const rest = hasRest ? _paramsOrRest : null; + return new Class2({ + type: "tuple", + items, + rest, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _record(Class2, keyType, valueType, params) { + return new Class2({ + type: "record", + keyType, + valueType, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _map(Class2, keyType, valueType, params) { + return new Class2({ + type: "map", + keyType, + valueType, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _set(Class2, valueType, params) { + return new Class2({ + type: "set", + valueType, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _enum(Class2, values2, params) { + const entries2 = Array.isArray(values2) ? Object.fromEntries(values2.map((v5) => [v5, v5])) : values2; + return new Class2({ + type: "enum", + entries: entries2, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _nativeEnum(Class2, entries2, params) { + return new Class2({ + type: "enum", + entries: entries2, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _literal(Class2, value, params) { + return new Class2({ + type: "literal", + values: Array.isArray(value) ? value : [value], + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _file(Class2, params) { + return new Class2({ + type: "file", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _transform(Class2, fn) { + return new Class2({ + type: "transform", + transform: fn + }); +} +// @__NO_SIDE_EFFECTS__ +function _optional(Class2, innerType) { + return new Class2({ + type: "optional", + innerType + }); +} +// @__NO_SIDE_EFFECTS__ +function _nullable(Class2, innerType) { + return new Class2({ + type: "nullable", + innerType + }); +} +// @__NO_SIDE_EFFECTS__ +function _default(Class2, innerType, defaultValue) { + return new Class2({ + type: "default", + innerType, + get defaultValue() { + return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue); + } + }); +} +// @__NO_SIDE_EFFECTS__ +function _nonoptional(Class2, innerType, params) { + return new Class2({ + type: "nonoptional", + innerType, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _success(Class2, innerType) { + return new Class2({ + type: "success", + innerType + }); +} +// @__NO_SIDE_EFFECTS__ +function _catch(Class2, innerType, catchValue) { + return new Class2({ + type: "catch", + innerType, + catchValue: typeof catchValue === "function" ? catchValue : () => catchValue + }); +} +// @__NO_SIDE_EFFECTS__ +function _pipe(Class2, in_, out) { + return new Class2({ + type: "pipe", + in: in_, + out + }); +} +// @__NO_SIDE_EFFECTS__ +function _readonly(Class2, innerType) { + return new Class2({ + type: "readonly", + innerType + }); +} +// @__NO_SIDE_EFFECTS__ +function _templateLiteral(Class2, parts, params) { + return new Class2({ + type: "template_literal", + parts, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _lazy(Class2, getter) { + return new Class2({ + type: "lazy", + getter + }); +} +// @__NO_SIDE_EFFECTS__ +function _promise(Class2, innerType) { + return new Class2({ + type: "promise", + innerType + }); +} +// @__NO_SIDE_EFFECTS__ +function _custom(Class2, fn, _params) { + const norm = normalizeParams(_params); + norm.abort ?? (norm.abort = true); + const schema2 = new Class2({ + type: "custom", + check: "custom", + fn, + ...norm + }); + return schema2; +} +// @__NO_SIDE_EFFECTS__ +function _refine(Class2, fn, _params) { + const schema2 = new Class2({ + type: "custom", + check: "custom", + fn, + ...normalizeParams(_params) + }); + return schema2; +} +// @__NO_SIDE_EFFECTS__ +function _superRefine(fn) { + const ch = /* @__PURE__ */ _check((payload2) => { + payload2.addIssue = (issue2) => { + if (typeof issue2 === "string") { + payload2.issues.push(issue(issue2, payload2.value, ch._zod.def)); + } else { + const _issue = issue2; + if (_issue.fatal) + _issue.continue = false; + _issue.code ?? (_issue.code = "custom"); + _issue.input ?? (_issue.input = payload2.value); + _issue.inst ?? (_issue.inst = ch); + _issue.continue ?? (_issue.continue = !ch._zod.def.abort); + payload2.issues.push(issue(_issue)); + } + }; + return fn(payload2.value, payload2); + }); + return ch; +} +// @__NO_SIDE_EFFECTS__ +function _check(fn, params) { + const ch = new $ZodCheck({ + check: "custom", + ...normalizeParams(params) + }); + ch._zod.check = fn; + return ch; +} +// @__NO_SIDE_EFFECTS__ +function describe(description) { + const ch = new $ZodCheck({ check: "describe" }); + ch._zod.onattach = [ + (inst) => { + const existing = globalRegistry.get(inst) ?? {}; + globalRegistry.add(inst, { ...existing, description }); + } + ]; + ch._zod.check = () => { + }; + return ch; +} +// @__NO_SIDE_EFFECTS__ +function meta(metadata) { + const ch = new $ZodCheck({ check: "meta" }); + ch._zod.onattach = [ + (inst) => { + const existing = globalRegistry.get(inst) ?? {}; + globalRegistry.add(inst, { ...existing, ...metadata }); + } + ]; + ch._zod.check = () => { + }; + return ch; +} +// @__NO_SIDE_EFFECTS__ +function _stringbool(Classes, _params) { + const params = normalizeParams(_params); + let truthyArray = params.truthy ?? ["true", "1", "yes", "on", "y", "enabled"]; + let falsyArray = params.falsy ?? ["false", "0", "no", "off", "n", "disabled"]; + if (params.case !== "sensitive") { + truthyArray = truthyArray.map((v5) => typeof v5 === "string" ? v5.toLowerCase() : v5); + falsyArray = falsyArray.map((v5) => typeof v5 === "string" ? v5.toLowerCase() : v5); + } + const truthySet = new Set(truthyArray); + const falsySet = new Set(falsyArray); + const _Codec = Classes.Codec ?? $ZodCodec; + const _Boolean = Classes.Boolean ?? $ZodBoolean; + const _String = Classes.String ?? $ZodString; + const stringSchema = new _String({ type: "string", error: params.error }); + const booleanSchema = new _Boolean({ type: "boolean", error: params.error }); + const codec2 = new _Codec({ + type: "pipe", + in: stringSchema, + out: booleanSchema, + transform: ((input, payload2) => { + let data2 = input; + if (params.case !== "sensitive") + data2 = data2.toLowerCase(); + if (truthySet.has(data2)) { + return true; + } else if (falsySet.has(data2)) { + return false; + } else { + payload2.issues.push({ + code: "invalid_value", + expected: "stringbool", + values: [...truthySet, ...falsySet], + input: payload2.value, + inst: codec2, + continue: false + }); + return {}; + } + }), + reverseTransform: ((input, _payload) => { + if (input === true) { + return truthyArray[0] || "true"; + } else { + return falsyArray[0] || "false"; + } + }), + error: params.error + }); + return codec2; +} +// @__NO_SIDE_EFFECTS__ +function _stringFormat(Class2, format2, fnOrRegex, _params = {}) { + const params = normalizeParams(_params); + const def = { + ...normalizeParams(_params), + check: "string_format", + type: "string", + format: format2, + fn: typeof fnOrRegex === "function" ? fnOrRegex : (val) => fnOrRegex.test(val), + ...params + }; + if (fnOrRegex instanceof RegExp) { + def.pattern = fnOrRegex; + } + const inst = new Class2(def); + return inst; +} +var TimePrecision; +var init_api = __esm({ + "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/api.js"() { + init_checks2(); + init_registries(); + init_schemas(); + init_util(); + TimePrecision = { + Any: null, + Minute: -1, + Second: 0, + Millisecond: 3, + Microsecond: 6 + }; + } +}); + +// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/to-json-schema.js +function initializeContext(params) { + let target = params?.target ?? "draft-2020-12"; + if (target === "draft-4") + target = "draft-04"; + if (target === "draft-7") + target = "draft-07"; + return { + processors: params.processors ?? {}, + metadataRegistry: params?.metadata ?? globalRegistry, + target, + unrepresentable: params?.unrepresentable ?? "throw", + override: params?.override ?? (() => { + }), + io: params?.io ?? "output", + counter: 0, + seen: /* @__PURE__ */ new Map(), + cycles: params?.cycles ?? "ref", + reused: params?.reused ?? "inline", + external: params?.external ?? void 0 + }; +} +function process2(schema2, ctx, _params = { path: [], schemaPath: [] }) { + var _a6; + const def = schema2._zod.def; + const seen = ctx.seen.get(schema2); + if (seen) { + seen.count++; + const isCycle = _params.schemaPath.includes(schema2); + if (isCycle) { + seen.cycle = _params.path; + } + return seen.schema; + } + const result = { schema: {}, count: 1, cycle: void 0, path: _params.path }; + ctx.seen.set(schema2, result); + const overrideSchema = schema2._zod.toJSONSchema?.(); + if (overrideSchema) { + result.schema = overrideSchema; + } else { + const params = { + ..._params, + schemaPath: [..._params.schemaPath, schema2], + path: _params.path + }; + if (schema2._zod.processJSONSchema) { + schema2._zod.processJSONSchema(ctx, result.schema, params); + } else { + const _json = result.schema; + const processor = ctx.processors[def.type]; + if (!processor) { + throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`); + } + processor(schema2, ctx, _json, params); + } + const parent = schema2._zod.parent; + if (parent) { + if (!result.ref) + result.ref = parent; + process2(parent, ctx, params); + ctx.seen.get(parent).isParent = true; + } + } + const meta3 = ctx.metadataRegistry.get(schema2); + if (meta3) + Object.assign(result.schema, meta3); + if (ctx.io === "input" && isTransforming(schema2)) { + delete result.schema.examples; + delete result.schema.default; + } + if (ctx.io === "input" && result.schema._prefault) + (_a6 = result.schema).default ?? (_a6.default = result.schema._prefault); + delete result.schema._prefault; + const _result = ctx.seen.get(schema2); + return _result.schema; +} +function extractDefs(ctx, schema2) { + const root = ctx.seen.get(schema2); + if (!root) + throw new Error("Unprocessed schema. This is a bug in Zod."); + const idToSchema = /* @__PURE__ */ new Map(); + for (const entry of ctx.seen.entries()) { + const id = ctx.metadataRegistry.get(entry[0])?.id; + if (id) { + const existing = idToSchema.get(id); + if (existing && existing !== entry[0]) { + throw new Error(`Duplicate schema id "${id}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`); + } + idToSchema.set(id, entry[0]); + } + } + const makeURI = (entry) => { + const defsSegment = ctx.target === "draft-2020-12" ? "$defs" : "definitions"; + if (ctx.external) { + const externalId = ctx.external.registry.get(entry[0])?.id; + const uriGenerator = ctx.external.uri ?? ((id2) => id2); + if (externalId) { + return { ref: uriGenerator(externalId) }; + } + const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`; + entry[1].defId = id; + return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${id}` }; + } + if (entry[1] === root) { + return { ref: "#" }; + } + const uriPrefix = `#`; + const defUriPrefix = `${uriPrefix}/${defsSegment}/`; + const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`; + return { defId, ref: defUriPrefix + defId }; + }; + const extractToDef = (entry) => { + if (entry[1].schema.$ref) { + return; + } + const seen = entry[1]; + const { ref, defId } = makeURI(entry); + seen.def = { ...seen.schema }; + if (defId) + seen.defId = defId; + const schema3 = seen.schema; + for (const key in schema3) { + delete schema3[key]; + } + schema3.$ref = ref; + }; + if (ctx.cycles === "throw") { + for (const entry of ctx.seen.entries()) { + const seen = entry[1]; + if (seen.cycle) { + throw new Error(`Cycle detected: #/${seen.cycle?.join("/")}/ + +Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`); + } + } + } + for (const entry of ctx.seen.entries()) { + const seen = entry[1]; + if (schema2 === entry[0]) { + extractToDef(entry); + continue; + } + if (ctx.external) { + const ext = ctx.external.registry.get(entry[0])?.id; + if (schema2 !== entry[0] && ext) { + extractToDef(entry); + continue; + } + } + const id = ctx.metadataRegistry.get(entry[0])?.id; + if (id) { + extractToDef(entry); + continue; + } + if (seen.cycle) { + extractToDef(entry); + continue; + } + if (seen.count > 1) { + if (ctx.reused === "ref") { + extractToDef(entry); + continue; + } + } + } +} +function finalize(ctx, schema2) { + const root = ctx.seen.get(schema2); + if (!root) + throw new Error("Unprocessed schema. This is a bug in Zod."); + const flattenRef = (zodSchema) => { + const seen = ctx.seen.get(zodSchema); + if (seen.ref === null) + return; + const schema3 = seen.def ?? seen.schema; + const _cached = { ...schema3 }; + const ref = seen.ref; + seen.ref = null; + if (ref) { + flattenRef(ref); + const refSeen = ctx.seen.get(ref); + const refSchema = refSeen.schema; + if (refSchema.$ref && (ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0")) { + schema3.allOf = schema3.allOf ?? []; + schema3.allOf.push(refSchema); + } else { + Object.assign(schema3, refSchema); + } + Object.assign(schema3, _cached); + const isParentRef = zodSchema._zod.parent === ref; + if (isParentRef) { + for (const key in schema3) { + if (key === "$ref" || key === "allOf") + continue; + if (!(key in _cached)) { + delete schema3[key]; + } + } + } + if (refSchema.$ref && refSeen.def) { + for (const key in schema3) { + if (key === "$ref" || key === "allOf") + continue; + if (key in refSeen.def && JSON.stringify(schema3[key]) === JSON.stringify(refSeen.def[key])) { + delete schema3[key]; + } + } + } + } + const parent = zodSchema._zod.parent; + if (parent && parent !== ref) { + flattenRef(parent); + const parentSeen = ctx.seen.get(parent); + if (parentSeen?.schema.$ref) { + schema3.$ref = parentSeen.schema.$ref; + if (parentSeen.def) { + for (const key in schema3) { + if (key === "$ref" || key === "allOf") + continue; + if (key in parentSeen.def && JSON.stringify(schema3[key]) === JSON.stringify(parentSeen.def[key])) { + delete schema3[key]; + } + } + } + } + } + ctx.override({ + zodSchema, + jsonSchema: schema3, + path: seen.path ?? [] + }); + }; + for (const entry of [...ctx.seen.entries()].reverse()) { + flattenRef(entry[0]); + } + const result = {}; + if (ctx.target === "draft-2020-12") { + result.$schema = "https://json-schema.org/draft/2020-12/schema"; + } else if (ctx.target === "draft-07") { + result.$schema = "http://json-schema.org/draft-07/schema#"; + } else if (ctx.target === "draft-04") { + result.$schema = "http://json-schema.org/draft-04/schema#"; + } else if (ctx.target === "openapi-3.0") { + } else { + } + if (ctx.external?.uri) { + const id = ctx.external.registry.get(schema2)?.id; + if (!id) + throw new Error("Schema is missing an `id` property"); + result.$id = ctx.external.uri(id); + } + Object.assign(result, root.def ?? root.schema); + const defs = ctx.external?.defs ?? {}; + for (const entry of ctx.seen.entries()) { + const seen = entry[1]; + if (seen.def && seen.defId) { + defs[seen.defId] = seen.def; + } + } + if (ctx.external) { + } else { + if (Object.keys(defs).length > 0) { + if (ctx.target === "draft-2020-12") { + result.$defs = defs; + } else { + result.definitions = defs; + } + } + } + try { + const finalized = JSON.parse(JSON.stringify(result)); + Object.defineProperty(finalized, "~standard", { + value: { + ...schema2["~standard"], + jsonSchema: { + input: createStandardJSONSchemaMethod(schema2, "input", ctx.processors), + output: createStandardJSONSchemaMethod(schema2, "output", ctx.processors) + } + }, + enumerable: false, + writable: false + }); + return finalized; + } catch (_err) { + throw new Error("Error converting schema to JSON."); + } +} +function isTransforming(_schema, _ctx) { + const ctx = _ctx ?? { seen: /* @__PURE__ */ new Set() }; + if (ctx.seen.has(_schema)) + return false; + ctx.seen.add(_schema); + const def = _schema._zod.def; + if (def.type === "transform") + return true; + if (def.type === "array") + return isTransforming(def.element, ctx); + if (def.type === "set") + return isTransforming(def.valueType, ctx); + if (def.type === "lazy") + return isTransforming(def.getter(), ctx); + if (def.type === "promise" || def.type === "optional" || def.type === "nonoptional" || def.type === "nullable" || def.type === "readonly" || def.type === "default" || def.type === "prefault") { + return isTransforming(def.innerType, ctx); + } + if (def.type === "intersection") { + return isTransforming(def.left, ctx) || isTransforming(def.right, ctx); + } + if (def.type === "record" || def.type === "map") { + return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx); + } + if (def.type === "pipe") { + return isTransforming(def.in, ctx) || isTransforming(def.out, ctx); + } + if (def.type === "object") { + for (const key in def.shape) { + if (isTransforming(def.shape[key], ctx)) + return true; + } + return false; + } + if (def.type === "union") { + for (const option of def.options) { + if (isTransforming(option, ctx)) + return true; + } + return false; + } + if (def.type === "tuple") { + for (const item of def.items) { + if (isTransforming(item, ctx)) + return true; + } + if (def.rest && isTransforming(def.rest, ctx)) + return true; + return false; + } + return false; +} +var createToJSONSchemaMethod, createStandardJSONSchemaMethod; +var init_to_json_schema = __esm({ + "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/to-json-schema.js"() { + init_registries(); + createToJSONSchemaMethod = (schema2, processors = {}) => (params) => { + const ctx = initializeContext({ ...params, processors }); + process2(schema2, ctx); + extractDefs(ctx, schema2); + return finalize(ctx, schema2); + }; + createStandardJSONSchemaMethod = (schema2, io, processors = {}) => (params) => { + const { libraryOptions, target } = params ?? {}; + const ctx = initializeContext({ ...libraryOptions ?? {}, target, io, processors }); + process2(schema2, ctx); + extractDefs(ctx, schema2); + return finalize(ctx, schema2); + }; + } +}); + +// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/json-schema-processors.js +function toJSONSchema(input, params) { + if ("_idmap" in input) { + const registry2 = input; + const ctx2 = initializeContext({ ...params, processors: allProcessors }); + const defs = {}; + for (const entry of registry2._idmap.entries()) { + const [_, schema2] = entry; + process2(schema2, ctx2); + } + const schemas = {}; + const external = { + registry: registry2, + uri: params?.uri, + defs + }; + ctx2.external = external; + for (const entry of registry2._idmap.entries()) { + const [key, schema2] = entry; + extractDefs(ctx2, schema2); + schemas[key] = finalize(ctx2, schema2); + } + if (Object.keys(defs).length > 0) { + const defsSegment = ctx2.target === "draft-2020-12" ? "$defs" : "definitions"; + schemas.__shared = { + [defsSegment]: defs + }; + } + return { schemas }; + } + const ctx = initializeContext({ ...params, processors: allProcessors }); + process2(input, ctx); + extractDefs(ctx, input); + return finalize(ctx, input); +} +var formatMap, stringProcessor, numberProcessor, booleanProcessor, bigintProcessor, symbolProcessor, nullProcessor, undefinedProcessor, voidProcessor, neverProcessor, anyProcessor, unknownProcessor, dateProcessor, enumProcessor, literalProcessor, nanProcessor, templateLiteralProcessor, fileProcessor, successProcessor, customProcessor, functionProcessor, transformProcessor, mapProcessor, setProcessor, arrayProcessor, objectProcessor, unionProcessor, intersectionProcessor, tupleProcessor, recordProcessor, nullableProcessor, nonoptionalProcessor, defaultProcessor, prefaultProcessor, catchProcessor, pipeProcessor, readonlyProcessor, promiseProcessor, optionalProcessor, lazyProcessor, allProcessors; +var init_json_schema_processors = __esm({ + "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/json-schema-processors.js"() { + init_to_json_schema(); + init_util(); + formatMap = { + guid: "uuid", + url: "uri", + datetime: "date-time", + json_string: "json-string", + regex: "" + // do not set + }; + stringProcessor = (schema2, ctx, _json, _params) => { + const json3 = _json; + json3.type = "string"; + const { minimum, maximum, format: format2, patterns, contentEncoding } = schema2._zod.bag; + if (typeof minimum === "number") + json3.minLength = minimum; + if (typeof maximum === "number") + json3.maxLength = maximum; + if (format2) { + json3.format = formatMap[format2] ?? format2; + if (json3.format === "") + delete json3.format; + if (format2 === "time") { + delete json3.format; + } + } + if (contentEncoding) + json3.contentEncoding = contentEncoding; + if (patterns && patterns.size > 0) { + const regexes = [...patterns]; + if (regexes.length === 1) + json3.pattern = regexes[0].source; + else if (regexes.length > 1) { + json3.allOf = [ + ...regexes.map((regex) => ({ + ...ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0" ? { type: "string" } : {}, + pattern: regex.source + })) + ]; + } + } + }; + numberProcessor = (schema2, ctx, _json, _params) => { + const json3 = _json; + const { minimum, maximum, format: format2, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema2._zod.bag; + if (typeof format2 === "string" && format2.includes("int")) + json3.type = "integer"; + else + json3.type = "number"; + if (typeof exclusiveMinimum === "number") { + if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") { + json3.minimum = exclusiveMinimum; + json3.exclusiveMinimum = true; + } else { + json3.exclusiveMinimum = exclusiveMinimum; + } + } + if (typeof minimum === "number") { + json3.minimum = minimum; + if (typeof exclusiveMinimum === "number" && ctx.target !== "draft-04") { + if (exclusiveMinimum >= minimum) + delete json3.minimum; + else + delete json3.exclusiveMinimum; + } + } + if (typeof exclusiveMaximum === "number") { + if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") { + json3.maximum = exclusiveMaximum; + json3.exclusiveMaximum = true; + } else { + json3.exclusiveMaximum = exclusiveMaximum; + } + } + if (typeof maximum === "number") { + json3.maximum = maximum; + if (typeof exclusiveMaximum === "number" && ctx.target !== "draft-04") { + if (exclusiveMaximum <= maximum) + delete json3.maximum; + else + delete json3.exclusiveMaximum; + } + } + if (typeof multipleOf === "number") + json3.multipleOf = multipleOf; + }; + booleanProcessor = (_schema, _ctx, json3, _params) => { + json3.type = "boolean"; + }; + bigintProcessor = (_schema, ctx, _json, _params) => { + if (ctx.unrepresentable === "throw") { + throw new Error("BigInt cannot be represented in JSON Schema"); + } + }; + symbolProcessor = (_schema, ctx, _json, _params) => { + if (ctx.unrepresentable === "throw") { + throw new Error("Symbols cannot be represented in JSON Schema"); + } + }; + nullProcessor = (_schema, ctx, json3, _params) => { + if (ctx.target === "openapi-3.0") { + json3.type = "string"; + json3.nullable = true; + json3.enum = [null]; + } else { + json3.type = "null"; + } + }; + undefinedProcessor = (_schema, ctx, _json, _params) => { + if (ctx.unrepresentable === "throw") { + throw new Error("Undefined cannot be represented in JSON Schema"); + } + }; + voidProcessor = (_schema, ctx, _json, _params) => { + if (ctx.unrepresentable === "throw") { + throw new Error("Void cannot be represented in JSON Schema"); + } + }; + neverProcessor = (_schema, _ctx, json3, _params) => { + json3.not = {}; + }; + anyProcessor = (_schema, _ctx, _json, _params) => { + }; + unknownProcessor = (_schema, _ctx, _json, _params) => { + }; + dateProcessor = (_schema, ctx, _json, _params) => { + if (ctx.unrepresentable === "throw") { + throw new Error("Date cannot be represented in JSON Schema"); + } + }; + enumProcessor = (schema2, _ctx, json3, _params) => { + const def = schema2._zod.def; + const values2 = getEnumValues(def.entries); + if (values2.every((v5) => typeof v5 === "number")) + json3.type = "number"; + if (values2.every((v5) => typeof v5 === "string")) + json3.type = "string"; + json3.enum = values2; + }; + literalProcessor = (schema2, ctx, json3, _params) => { + const def = schema2._zod.def; + const vals = []; + for (const val of def.values) { + if (val === void 0) { + if (ctx.unrepresentable === "throw") { + throw new Error("Literal `undefined` cannot be represented in JSON Schema"); + } else { + } + } else if (typeof val === "bigint") { + if (ctx.unrepresentable === "throw") { + throw new Error("BigInt literals cannot be represented in JSON Schema"); + } else { + vals.push(Number(val)); + } + } else { + vals.push(val); + } + } + if (vals.length === 0) { + } else if (vals.length === 1) { + const val = vals[0]; + json3.type = val === null ? "null" : typeof val; + if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") { + json3.enum = [val]; + } else { + json3.const = val; + } + } else { + if (vals.every((v5) => typeof v5 === "number")) + json3.type = "number"; + if (vals.every((v5) => typeof v5 === "string")) + json3.type = "string"; + if (vals.every((v5) => typeof v5 === "boolean")) + json3.type = "boolean"; + if (vals.every((v5) => v5 === null)) + json3.type = "null"; + json3.enum = vals; + } + }; + nanProcessor = (_schema, ctx, _json, _params) => { + if (ctx.unrepresentable === "throw") { + throw new Error("NaN cannot be represented in JSON Schema"); + } + }; + templateLiteralProcessor = (schema2, _ctx, json3, _params) => { + const _json = json3; + const pattern = schema2._zod.pattern; + if (!pattern) + throw new Error("Pattern not found in template literal"); + _json.type = "string"; + _json.pattern = pattern.source; + }; + fileProcessor = (schema2, _ctx, json3, _params) => { + const _json = json3; + const file2 = { + type: "string", + format: "binary", + contentEncoding: "binary" + }; + const { minimum, maximum, mime } = schema2._zod.bag; + if (minimum !== void 0) + file2.minLength = minimum; + if (maximum !== void 0) + file2.maxLength = maximum; + if (mime) { + if (mime.length === 1) { + file2.contentMediaType = mime[0]; + Object.assign(_json, file2); + } else { + Object.assign(_json, file2); + _json.anyOf = mime.map((m5) => ({ contentMediaType: m5 })); + } + } else { + Object.assign(_json, file2); + } + }; + successProcessor = (_schema, _ctx, json3, _params) => { + json3.type = "boolean"; + }; + customProcessor = (_schema, ctx, _json, _params) => { + if (ctx.unrepresentable === "throw") { + throw new Error("Custom types cannot be represented in JSON Schema"); + } + }; + functionProcessor = (_schema, ctx, _json, _params) => { + if (ctx.unrepresentable === "throw") { + throw new Error("Function types cannot be represented in JSON Schema"); + } + }; + transformProcessor = (_schema, ctx, _json, _params) => { + if (ctx.unrepresentable === "throw") { + throw new Error("Transforms cannot be represented in JSON Schema"); + } + }; + mapProcessor = (_schema, ctx, _json, _params) => { + if (ctx.unrepresentable === "throw") { + throw new Error("Map cannot be represented in JSON Schema"); + } + }; + setProcessor = (_schema, ctx, _json, _params) => { + if (ctx.unrepresentable === "throw") { + throw new Error("Set cannot be represented in JSON Schema"); + } + }; + arrayProcessor = (schema2, ctx, _json, params) => { + const json3 = _json; + const def = schema2._zod.def; + const { minimum, maximum } = schema2._zod.bag; + if (typeof minimum === "number") + json3.minItems = minimum; + if (typeof maximum === "number") + json3.maxItems = maximum; + json3.type = "array"; + json3.items = process2(def.element, ctx, { ...params, path: [...params.path, "items"] }); + }; + objectProcessor = (schema2, ctx, _json, params) => { + const json3 = _json; + const def = schema2._zod.def; + json3.type = "object"; + json3.properties = {}; + const shape = def.shape; + for (const key in shape) { + json3.properties[key] = process2(shape[key], ctx, { + ...params, + path: [...params.path, "properties", key] + }); + } + const allKeys = new Set(Object.keys(shape)); + const requiredKeys = new Set([...allKeys].filter((key) => { + const v5 = def.shape[key]._zod; + if (ctx.io === "input") { + return v5.optin === void 0; + } else { + return v5.optout === void 0; + } + })); + if (requiredKeys.size > 0) { + json3.required = Array.from(requiredKeys); + } + if (def.catchall?._zod.def.type === "never") { + json3.additionalProperties = false; + } else if (!def.catchall) { + if (ctx.io === "output") + json3.additionalProperties = false; + } else if (def.catchall) { + json3.additionalProperties = process2(def.catchall, ctx, { + ...params, + path: [...params.path, "additionalProperties"] + }); + } + }; + unionProcessor = (schema2, ctx, json3, params) => { + const def = schema2._zod.def; + const isExclusive = def.inclusive === false; + const options = def.options.map((x5, i5) => process2(x5, ctx, { + ...params, + path: [...params.path, isExclusive ? "oneOf" : "anyOf", i5] + })); + if (isExclusive) { + json3.oneOf = options; + } else { + json3.anyOf = options; + } + }; + intersectionProcessor = (schema2, ctx, json3, params) => { + const def = schema2._zod.def; + const a5 = process2(def.left, ctx, { + ...params, + path: [...params.path, "allOf", 0] + }); + const b6 = process2(def.right, ctx, { + ...params, + path: [...params.path, "allOf", 1] + }); + const isSimpleIntersection = (val) => "allOf" in val && Object.keys(val).length === 1; + const allOf = [ + ...isSimpleIntersection(a5) ? a5.allOf : [a5], + ...isSimpleIntersection(b6) ? b6.allOf : [b6] + ]; + json3.allOf = allOf; + }; + tupleProcessor = (schema2, ctx, _json, params) => { + const json3 = _json; + const def = schema2._zod.def; + json3.type = "array"; + const prefixPath = ctx.target === "draft-2020-12" ? "prefixItems" : "items"; + const restPath = ctx.target === "draft-2020-12" ? "items" : ctx.target === "openapi-3.0" ? "items" : "additionalItems"; + const prefixItems = def.items.map((x5, i5) => process2(x5, ctx, { + ...params, + path: [...params.path, prefixPath, i5] + })); + const rest = def.rest ? process2(def.rest, ctx, { + ...params, + path: [...params.path, restPath, ...ctx.target === "openapi-3.0" ? [def.items.length] : []] + }) : null; + if (ctx.target === "draft-2020-12") { + json3.prefixItems = prefixItems; + if (rest) { + json3.items = rest; + } + } else if (ctx.target === "openapi-3.0") { + json3.items = { + anyOf: prefixItems + }; + if (rest) { + json3.items.anyOf.push(rest); + } + json3.minItems = prefixItems.length; + if (!rest) { + json3.maxItems = prefixItems.length; + } + } else { + json3.items = prefixItems; + if (rest) { + json3.additionalItems = rest; + } + } + const { minimum, maximum } = schema2._zod.bag; + if (typeof minimum === "number") + json3.minItems = minimum; + if (typeof maximum === "number") + json3.maxItems = maximum; + }; + recordProcessor = (schema2, ctx, _json, params) => { + const json3 = _json; + const def = schema2._zod.def; + json3.type = "object"; + const keyType = def.keyType; + const keyBag = keyType._zod.bag; + const patterns = keyBag?.patterns; + if (def.mode === "loose" && patterns && patterns.size > 0) { + const valueSchema = process2(def.valueType, ctx, { + ...params, + path: [...params.path, "patternProperties", "*"] + }); + json3.patternProperties = {}; + for (const pattern of patterns) { + json3.patternProperties[pattern.source] = valueSchema; + } + } else { + if (ctx.target === "draft-07" || ctx.target === "draft-2020-12") { + json3.propertyNames = process2(def.keyType, ctx, { + ...params, + path: [...params.path, "propertyNames"] + }); + } + json3.additionalProperties = process2(def.valueType, ctx, { + ...params, + path: [...params.path, "additionalProperties"] + }); + } + const keyValues = keyType._zod.values; + if (keyValues) { + const validKeyValues = [...keyValues].filter((v5) => typeof v5 === "string" || typeof v5 === "number"); + if (validKeyValues.length > 0) { + json3.required = validKeyValues; + } + } + }; + nullableProcessor = (schema2, ctx, json3, params) => { + const def = schema2._zod.def; + const inner = process2(def.innerType, ctx, params); + const seen = ctx.seen.get(schema2); + if (ctx.target === "openapi-3.0") { + seen.ref = def.innerType; + json3.nullable = true; + } else { + json3.anyOf = [inner, { type: "null" }]; + } + }; + nonoptionalProcessor = (schema2, ctx, _json, params) => { + const def = schema2._zod.def; + process2(def.innerType, ctx, params); + const seen = ctx.seen.get(schema2); + seen.ref = def.innerType; + }; + defaultProcessor = (schema2, ctx, json3, params) => { + const def = schema2._zod.def; + process2(def.innerType, ctx, params); + const seen = ctx.seen.get(schema2); + seen.ref = def.innerType; + json3.default = JSON.parse(JSON.stringify(def.defaultValue)); + }; + prefaultProcessor = (schema2, ctx, json3, params) => { + const def = schema2._zod.def; + process2(def.innerType, ctx, params); + const seen = ctx.seen.get(schema2); + seen.ref = def.innerType; + if (ctx.io === "input") + json3._prefault = JSON.parse(JSON.stringify(def.defaultValue)); + }; + catchProcessor = (schema2, ctx, json3, params) => { + const def = schema2._zod.def; + process2(def.innerType, ctx, params); + const seen = ctx.seen.get(schema2); + seen.ref = def.innerType; + let catchValue; + try { + catchValue = def.catchValue(void 0); + } catch { + throw new Error("Dynamic catch values are not supported in JSON Schema"); + } + json3.default = catchValue; + }; + pipeProcessor = (schema2, ctx, _json, params) => { + const def = schema2._zod.def; + const innerType = ctx.io === "input" ? def.in._zod.def.type === "transform" ? def.out : def.in : def.out; + process2(innerType, ctx, params); + const seen = ctx.seen.get(schema2); + seen.ref = innerType; + }; + readonlyProcessor = (schema2, ctx, json3, params) => { + const def = schema2._zod.def; + process2(def.innerType, ctx, params); + const seen = ctx.seen.get(schema2); + seen.ref = def.innerType; + json3.readOnly = true; + }; + promiseProcessor = (schema2, ctx, _json, params) => { + const def = schema2._zod.def; + process2(def.innerType, ctx, params); + const seen = ctx.seen.get(schema2); + seen.ref = def.innerType; + }; + optionalProcessor = (schema2, ctx, _json, params) => { + const def = schema2._zod.def; + process2(def.innerType, ctx, params); + const seen = ctx.seen.get(schema2); + seen.ref = def.innerType; + }; + lazyProcessor = (schema2, ctx, _json, params) => { + const innerType = schema2._zod.innerType; + process2(innerType, ctx, params); + const seen = ctx.seen.get(schema2); + seen.ref = innerType; + }; + allProcessors = { + string: stringProcessor, + number: numberProcessor, + boolean: booleanProcessor, + bigint: bigintProcessor, + symbol: symbolProcessor, + null: nullProcessor, + undefined: undefinedProcessor, + void: voidProcessor, + never: neverProcessor, + any: anyProcessor, + unknown: unknownProcessor, + date: dateProcessor, + enum: enumProcessor, + literal: literalProcessor, + nan: nanProcessor, + template_literal: templateLiteralProcessor, + file: fileProcessor, + success: successProcessor, + custom: customProcessor, + function: functionProcessor, + transform: transformProcessor, + map: mapProcessor, + set: setProcessor, + array: arrayProcessor, + object: objectProcessor, + union: unionProcessor, + intersection: intersectionProcessor, + tuple: tupleProcessor, + record: recordProcessor, + nullable: nullableProcessor, + nonoptional: nonoptionalProcessor, + default: defaultProcessor, + prefault: prefaultProcessor, + catch: catchProcessor, + pipe: pipeProcessor, + readonly: readonlyProcessor, + promise: promiseProcessor, + optional: optionalProcessor, + lazy: lazyProcessor + }; + } +}); + +// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/json-schema-generator.js +var JSONSchemaGenerator; +var init_json_schema_generator = __esm({ + "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/json-schema-generator.js"() { + init_json_schema_processors(); + init_to_json_schema(); + JSONSchemaGenerator = class { + /** @deprecated Access via ctx instead */ + get metadataRegistry() { + return this.ctx.metadataRegistry; + } + /** @deprecated Access via ctx instead */ + get target() { + return this.ctx.target; + } + /** @deprecated Access via ctx instead */ + get unrepresentable() { + return this.ctx.unrepresentable; + } + /** @deprecated Access via ctx instead */ + get override() { + return this.ctx.override; + } + /** @deprecated Access via ctx instead */ + get io() { + return this.ctx.io; + } + /** @deprecated Access via ctx instead */ + get counter() { + return this.ctx.counter; + } + set counter(value) { + this.ctx.counter = value; + } + /** @deprecated Access via ctx instead */ + get seen() { + return this.ctx.seen; + } + constructor(params) { + let normalizedTarget = params?.target ?? "draft-2020-12"; + if (normalizedTarget === "draft-4") + normalizedTarget = "draft-04"; + if (normalizedTarget === "draft-7") + normalizedTarget = "draft-07"; + this.ctx = initializeContext({ + processors: allProcessors, + target: normalizedTarget, + ...params?.metadata && { metadata: params.metadata }, + ...params?.unrepresentable && { unrepresentable: params.unrepresentable }, + ...params?.override && { override: params.override }, + ...params?.io && { io: params.io } + }); + } + /** + * Process a schema to prepare it for JSON Schema generation. + * This must be called before emit(). + */ + process(schema2, _params = { path: [], schemaPath: [] }) { + return process2(schema2, this.ctx, _params); + } + /** + * Emit the final JSON Schema after processing. + * Must call process() first. + */ + emit(schema2, _params) { + if (_params) { + if (_params.cycles) + this.ctx.cycles = _params.cycles; + if (_params.reused) + this.ctx.reused = _params.reused; + if (_params.external) + this.ctx.external = _params.external; + } + extractDefs(this.ctx, schema2); + const result = finalize(this.ctx, schema2); + const { "~standard": _, ...plainResult } = result; + return plainResult; + } + }; + } +}); + +// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/json-schema.js +var json_schema_exports = {}; +var init_json_schema = __esm({ + "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/json-schema.js"() { + } +}); + +// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/index.js +var core_exports2 = {}; +__export(core_exports2, { + $ZodAny: () => $ZodAny, + $ZodArray: () => $ZodArray, + $ZodAsyncError: () => $ZodAsyncError, + $ZodBase64: () => $ZodBase64, + $ZodBase64URL: () => $ZodBase64URL, + $ZodBigInt: () => $ZodBigInt, + $ZodBigIntFormat: () => $ZodBigIntFormat, + $ZodBoolean: () => $ZodBoolean, + $ZodCIDRv4: () => $ZodCIDRv4, + $ZodCIDRv6: () => $ZodCIDRv6, + $ZodCUID: () => $ZodCUID, + $ZodCUID2: () => $ZodCUID2, + $ZodCatch: () => $ZodCatch, + $ZodCheck: () => $ZodCheck, + $ZodCheckBigIntFormat: () => $ZodCheckBigIntFormat, + $ZodCheckEndsWith: () => $ZodCheckEndsWith, + $ZodCheckGreaterThan: () => $ZodCheckGreaterThan, + $ZodCheckIncludes: () => $ZodCheckIncludes, + $ZodCheckLengthEquals: () => $ZodCheckLengthEquals, + $ZodCheckLessThan: () => $ZodCheckLessThan, + $ZodCheckLowerCase: () => $ZodCheckLowerCase, + $ZodCheckMaxLength: () => $ZodCheckMaxLength, + $ZodCheckMaxSize: () => $ZodCheckMaxSize, + $ZodCheckMimeType: () => $ZodCheckMimeType, + $ZodCheckMinLength: () => $ZodCheckMinLength, + $ZodCheckMinSize: () => $ZodCheckMinSize, + $ZodCheckMultipleOf: () => $ZodCheckMultipleOf, + $ZodCheckNumberFormat: () => $ZodCheckNumberFormat, + $ZodCheckOverwrite: () => $ZodCheckOverwrite, + $ZodCheckProperty: () => $ZodCheckProperty, + $ZodCheckRegex: () => $ZodCheckRegex, + $ZodCheckSizeEquals: () => $ZodCheckSizeEquals, + $ZodCheckStartsWith: () => $ZodCheckStartsWith, + $ZodCheckStringFormat: () => $ZodCheckStringFormat, + $ZodCheckUpperCase: () => $ZodCheckUpperCase, + $ZodCodec: () => $ZodCodec, + $ZodCustom: () => $ZodCustom, + $ZodCustomStringFormat: () => $ZodCustomStringFormat, + $ZodDate: () => $ZodDate, + $ZodDefault: () => $ZodDefault, + $ZodDiscriminatedUnion: () => $ZodDiscriminatedUnion, + $ZodE164: () => $ZodE164, + $ZodEmail: () => $ZodEmail, + $ZodEmoji: () => $ZodEmoji, + $ZodEncodeError: () => $ZodEncodeError, + $ZodEnum: () => $ZodEnum, + $ZodError: () => $ZodError, + $ZodExactOptional: () => $ZodExactOptional, + $ZodFile: () => $ZodFile, + $ZodFunction: () => $ZodFunction, + $ZodGUID: () => $ZodGUID, + $ZodIPv4: () => $ZodIPv4, + $ZodIPv6: () => $ZodIPv6, + $ZodISODate: () => $ZodISODate, + $ZodISODateTime: () => $ZodISODateTime, + $ZodISODuration: () => $ZodISODuration, + $ZodISOTime: () => $ZodISOTime, + $ZodIntersection: () => $ZodIntersection, + $ZodJWT: () => $ZodJWT, + $ZodKSUID: () => $ZodKSUID, + $ZodLazy: () => $ZodLazy, + $ZodLiteral: () => $ZodLiteral, + $ZodMAC: () => $ZodMAC, + $ZodMap: () => $ZodMap, + $ZodNaN: () => $ZodNaN, + $ZodNanoID: () => $ZodNanoID, + $ZodNever: () => $ZodNever, + $ZodNonOptional: () => $ZodNonOptional, + $ZodNull: () => $ZodNull, + $ZodNullable: () => $ZodNullable, + $ZodNumber: () => $ZodNumber, + $ZodNumberFormat: () => $ZodNumberFormat, + $ZodObject: () => $ZodObject, + $ZodObjectJIT: () => $ZodObjectJIT, + $ZodOptional: () => $ZodOptional, + $ZodPipe: () => $ZodPipe, + $ZodPrefault: () => $ZodPrefault, + $ZodPromise: () => $ZodPromise, + $ZodReadonly: () => $ZodReadonly, + $ZodRealError: () => $ZodRealError, + $ZodRecord: () => $ZodRecord, + $ZodRegistry: () => $ZodRegistry, + $ZodSet: () => $ZodSet, + $ZodString: () => $ZodString, + $ZodStringFormat: () => $ZodStringFormat, + $ZodSuccess: () => $ZodSuccess, + $ZodSymbol: () => $ZodSymbol, + $ZodTemplateLiteral: () => $ZodTemplateLiteral, + $ZodTransform: () => $ZodTransform, + $ZodTuple: () => $ZodTuple, + $ZodType: () => $ZodType, + $ZodULID: () => $ZodULID, + $ZodURL: () => $ZodURL, + $ZodUUID: () => $ZodUUID, + $ZodUndefined: () => $ZodUndefined, + $ZodUnion: () => $ZodUnion, + $ZodUnknown: () => $ZodUnknown, + $ZodVoid: () => $ZodVoid, + $ZodXID: () => $ZodXID, + $ZodXor: () => $ZodXor, + $brand: () => $brand, + $constructor: () => $constructor, + $input: () => $input, + $output: () => $output, + Doc: () => Doc, + JSONSchema: () => json_schema_exports, + JSONSchemaGenerator: () => JSONSchemaGenerator, + NEVER: () => NEVER2, + TimePrecision: () => TimePrecision, + _any: () => _any, + _array: () => _array, + _base64: () => _base64, + _base64url: () => _base64url, + _bigint: () => _bigint, + _boolean: () => _boolean, + _catch: () => _catch, + _check: () => _check, + _cidrv4: () => _cidrv4, + _cidrv6: () => _cidrv6, + _coercedBigint: () => _coercedBigint, + _coercedBoolean: () => _coercedBoolean, + _coercedDate: () => _coercedDate, + _coercedNumber: () => _coercedNumber, + _coercedString: () => _coercedString, + _cuid: () => _cuid, + _cuid2: () => _cuid2, + _custom: () => _custom, + _date: () => _date, + _decode: () => _decode, + _decodeAsync: () => _decodeAsync, + _default: () => _default, + _discriminatedUnion: () => _discriminatedUnion, + _e164: () => _e164, + _email: () => _email, + _emoji: () => _emoji2, + _encode: () => _encode, + _encodeAsync: () => _encodeAsync, + _endsWith: () => _endsWith, + _enum: () => _enum, + _file: () => _file, + _float32: () => _float32, + _float64: () => _float64, + _gt: () => _gt, + _gte: () => _gte, + _guid: () => _guid, + _includes: () => _includes, + _int: () => _int, + _int32: () => _int32, + _int64: () => _int64, + _intersection: () => _intersection, + _ipv4: () => _ipv4, + _ipv6: () => _ipv6, + _isoDate: () => _isoDate, + _isoDateTime: () => _isoDateTime, + _isoDuration: () => _isoDuration, + _isoTime: () => _isoTime, + _jwt: () => _jwt, + _ksuid: () => _ksuid, + _lazy: () => _lazy, + _length: () => _length, + _literal: () => _literal, + _lowercase: () => _lowercase, + _lt: () => _lt, + _lte: () => _lte, + _mac: () => _mac, + _map: () => _map, + _max: () => _lte, + _maxLength: () => _maxLength, + _maxSize: () => _maxSize, + _mime: () => _mime, + _min: () => _gte, + _minLength: () => _minLength, + _minSize: () => _minSize, + _multipleOf: () => _multipleOf, + _nan: () => _nan, + _nanoid: () => _nanoid, + _nativeEnum: () => _nativeEnum, + _negative: () => _negative, + _never: () => _never, + _nonnegative: () => _nonnegative, + _nonoptional: () => _nonoptional, + _nonpositive: () => _nonpositive, + _normalize: () => _normalize, + _null: () => _null2, + _nullable: () => _nullable, + _number: () => _number, + _optional: () => _optional, + _overwrite: () => _overwrite, + _parse: () => _parse, + _parseAsync: () => _parseAsync, + _pipe: () => _pipe, + _positive: () => _positive, + _promise: () => _promise, + _property: () => _property, + _readonly: () => _readonly, + _record: () => _record, + _refine: () => _refine, + _regex: () => _regex, + _safeDecode: () => _safeDecode, + _safeDecodeAsync: () => _safeDecodeAsync, + _safeEncode: () => _safeEncode, + _safeEncodeAsync: () => _safeEncodeAsync, + _safeParse: () => _safeParse, + _safeParseAsync: () => _safeParseAsync, + _set: () => _set, + _size: () => _size, + _slugify: () => _slugify, + _startsWith: () => _startsWith, + _string: () => _string, + _stringFormat: () => _stringFormat, + _stringbool: () => _stringbool, + _success: () => _success, + _superRefine: () => _superRefine, + _symbol: () => _symbol, + _templateLiteral: () => _templateLiteral, + _toLowerCase: () => _toLowerCase, + _toUpperCase: () => _toUpperCase, + _transform: () => _transform, + _trim: () => _trim, + _tuple: () => _tuple, + _uint32: () => _uint32, + _uint64: () => _uint64, + _ulid: () => _ulid, + _undefined: () => _undefined2, + _union: () => _union, + _unknown: () => _unknown, + _uppercase: () => _uppercase, + _url: () => _url, + _uuid: () => _uuid, + _uuidv4: () => _uuidv4, + _uuidv6: () => _uuidv6, + _uuidv7: () => _uuidv7, + _void: () => _void, + _xid: () => _xid, + _xor: () => _xor, + clone: () => clone2, + config: () => config, + createStandardJSONSchemaMethod: () => createStandardJSONSchemaMethod, + createToJSONSchemaMethod: () => createToJSONSchemaMethod, + decode: () => decode3, + decodeAsync: () => decodeAsync, + describe: () => describe, + encode: () => encode4, + encodeAsync: () => encodeAsync, + extractDefs: () => extractDefs, + finalize: () => finalize, + flattenError: () => flattenError, + formatError: () => formatError, + globalConfig: () => globalConfig, + globalRegistry: () => globalRegistry, + initializeContext: () => initializeContext, + isValidBase64: () => isValidBase64, + isValidBase64URL: () => isValidBase64URL, + isValidJWT: () => isValidJWT2, + locales: () => locales_exports, + meta: () => meta, + parse: () => parse2, + parseAsync: () => parseAsync, + prettifyError: () => prettifyError, + process: () => process2, + regexes: () => regexes_exports, + registry: () => registry, + safeDecode: () => safeDecode, + safeDecodeAsync: () => safeDecodeAsync, + safeEncode: () => safeEncode, + safeEncodeAsync: () => safeEncodeAsync, + safeParse: () => safeParse, + safeParseAsync: () => safeParseAsync, + toDotPath: () => toDotPath, + toJSONSchema: () => toJSONSchema, + treeifyError: () => treeifyError, + util: () => util_exports, + version: () => version2 +}); +var init_core2 = __esm({ + "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/index.js"() { + init_core(); + init_parse(); + init_errors8(); + init_schemas(); + init_checks2(); + init_versions(); + init_util(); + init_regexes(); + init_locales(); + init_registries(); + init_doc(); + init_api(); + init_to_json_schema(); + init_json_schema_processors(); + init_json_schema_generator(); + init_json_schema(); + } +}); + +// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/checks.js +var checks_exports2 = {}; +__export(checks_exports2, { + endsWith: () => _endsWith, + gt: () => _gt, + gte: () => _gte, + includes: () => _includes, + length: () => _length, + lowercase: () => _lowercase, + lt: () => _lt, + lte: () => _lte, + maxLength: () => _maxLength, + maxSize: () => _maxSize, + mime: () => _mime, + minLength: () => _minLength, + minSize: () => _minSize, + multipleOf: () => _multipleOf, + negative: () => _negative, + nonnegative: () => _nonnegative, + nonpositive: () => _nonpositive, + normalize: () => _normalize, + overwrite: () => _overwrite, + positive: () => _positive, + property: () => _property, + regex: () => _regex, + size: () => _size, + slugify: () => _slugify, + startsWith: () => _startsWith, + toLowerCase: () => _toLowerCase, + toUpperCase: () => _toUpperCase, + trim: () => _trim, + uppercase: () => _uppercase +}); +var init_checks3 = __esm({ + "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/checks.js"() { + init_core2(); + } +}); + +// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/iso.js +var iso_exports = {}; +__export(iso_exports, { + ZodISODate: () => ZodISODate, + ZodISODateTime: () => ZodISODateTime, + ZodISODuration: () => ZodISODuration, + ZodISOTime: () => ZodISOTime, + date: () => date4, + datetime: () => datetime2, + duration: () => duration2, + time: () => time4 +}); +function datetime2(params) { + return _isoDateTime(ZodISODateTime, params); +} +function date4(params) { + return _isoDate(ZodISODate, params); +} +function time4(params) { + return _isoTime(ZodISOTime, params); +} +function duration2(params) { + return _isoDuration(ZodISODuration, params); +} +var ZodISODateTime, ZodISODate, ZodISOTime, ZodISODuration; +var init_iso = __esm({ + "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/iso.js"() { + init_core2(); + init_schemas2(); + ZodISODateTime = /* @__PURE__ */ $constructor("ZodISODateTime", (inst, def) => { + $ZodISODateTime.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodISODate = /* @__PURE__ */ $constructor("ZodISODate", (inst, def) => { + $ZodISODate.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodISOTime = /* @__PURE__ */ $constructor("ZodISOTime", (inst, def) => { + $ZodISOTime.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodISODuration = /* @__PURE__ */ $constructor("ZodISODuration", (inst, def) => { + $ZodISODuration.init(inst, def); + ZodStringFormat.init(inst, def); + }); + } +}); + +// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/errors.js +var initializer2, ZodError2, ZodRealError; +var init_errors9 = __esm({ + "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/errors.js"() { + init_core2(); + init_core2(); + init_util(); + initializer2 = (inst, issues2) => { + $ZodError.init(inst, issues2); + inst.name = "ZodError"; + Object.defineProperties(inst, { + format: { + value: (mapper) => formatError(inst, mapper) + // enumerable: false, + }, + flatten: { + value: (mapper) => flattenError(inst, mapper) + // enumerable: false, + }, + addIssue: { + value: (issue2) => { + inst.issues.push(issue2); + inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2); + } + // enumerable: false, + }, + addIssues: { + value: (issues3) => { + inst.issues.push(...issues3); + inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2); + } + // enumerable: false, + }, + isEmpty: { + get() { + return inst.issues.length === 0; + } + // enumerable: false, + } + }); + }; + ZodError2 = $constructor("ZodError", initializer2); + ZodRealError = $constructor("ZodError", initializer2, { + Parent: Error + }); + } +}); + +// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/parse.js +var parse3, parseAsync2, safeParse2, safeParseAsync2, encode5, decode4, encodeAsync2, decodeAsync2, safeEncode2, safeDecode2, safeEncodeAsync2, safeDecodeAsync2; +var init_parse2 = __esm({ + "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/parse.js"() { + init_core2(); + init_errors9(); + parse3 = /* @__PURE__ */ _parse(ZodRealError); + parseAsync2 = /* @__PURE__ */ _parseAsync(ZodRealError); + safeParse2 = /* @__PURE__ */ _safeParse(ZodRealError); + safeParseAsync2 = /* @__PURE__ */ _safeParseAsync(ZodRealError); + encode5 = /* @__PURE__ */ _encode(ZodRealError); + decode4 = /* @__PURE__ */ _decode(ZodRealError); + encodeAsync2 = /* @__PURE__ */ _encodeAsync(ZodRealError); + decodeAsync2 = /* @__PURE__ */ _decodeAsync(ZodRealError); + safeEncode2 = /* @__PURE__ */ _safeEncode(ZodRealError); + safeDecode2 = /* @__PURE__ */ _safeDecode(ZodRealError); + safeEncodeAsync2 = /* @__PURE__ */ _safeEncodeAsync(ZodRealError); + safeDecodeAsync2 = /* @__PURE__ */ _safeDecodeAsync(ZodRealError); + } +}); + +// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/schemas.js +var schemas_exports2 = {}; +__export(schemas_exports2, { + ZodAny: () => ZodAny2, + ZodArray: () => ZodArray2, + ZodBase64: () => ZodBase64, + ZodBase64URL: () => ZodBase64URL, + ZodBigInt: () => ZodBigInt2, + ZodBigIntFormat: () => ZodBigIntFormat, + ZodBoolean: () => ZodBoolean2, + ZodCIDRv4: () => ZodCIDRv4, + ZodCIDRv6: () => ZodCIDRv6, + ZodCUID: () => ZodCUID, + ZodCUID2: () => ZodCUID2, + ZodCatch: () => ZodCatch2, + ZodCodec: () => ZodCodec, + ZodCustom: () => ZodCustom, + ZodCustomStringFormat: () => ZodCustomStringFormat, + ZodDate: () => ZodDate2, + ZodDefault: () => ZodDefault2, + ZodDiscriminatedUnion: () => ZodDiscriminatedUnion2, + ZodE164: () => ZodE164, + ZodEmail: () => ZodEmail, + ZodEmoji: () => ZodEmoji, + ZodEnum: () => ZodEnum2, + ZodExactOptional: () => ZodExactOptional, + ZodFile: () => ZodFile, + ZodFunction: () => ZodFunction2, + ZodGUID: () => ZodGUID, + ZodIPv4: () => ZodIPv4, + ZodIPv6: () => ZodIPv6, + ZodIntersection: () => ZodIntersection2, + ZodJWT: () => ZodJWT, + ZodKSUID: () => ZodKSUID, + ZodLazy: () => ZodLazy2, + ZodLiteral: () => ZodLiteral2, + ZodMAC: () => ZodMAC, + ZodMap: () => ZodMap2, + ZodNaN: () => ZodNaN2, + ZodNanoID: () => ZodNanoID, + ZodNever: () => ZodNever2, + ZodNonOptional: () => ZodNonOptional, + ZodNull: () => ZodNull2, + ZodNullable: () => ZodNullable2, + ZodNumber: () => ZodNumber2, + ZodNumberFormat: () => ZodNumberFormat, + ZodObject: () => ZodObject2, + ZodOptional: () => ZodOptional2, + ZodPipe: () => ZodPipe, + ZodPrefault: () => ZodPrefault, + ZodPromise: () => ZodPromise2, + ZodReadonly: () => ZodReadonly2, + ZodRecord: () => ZodRecord2, + ZodSet: () => ZodSet2, + ZodString: () => ZodString2, + ZodStringFormat: () => ZodStringFormat, + ZodSuccess: () => ZodSuccess, + ZodSymbol: () => ZodSymbol2, + ZodTemplateLiteral: () => ZodTemplateLiteral, + ZodTransform: () => ZodTransform, + ZodTuple: () => ZodTuple2, + ZodType: () => ZodType2, + ZodULID: () => ZodULID, + ZodURL: () => ZodURL, + ZodUUID: () => ZodUUID, + ZodUndefined: () => ZodUndefined2, + ZodUnion: () => ZodUnion2, + ZodUnknown: () => ZodUnknown2, + ZodVoid: () => ZodVoid2, + ZodXID: () => ZodXID, + ZodXor: () => ZodXor, + _ZodString: () => _ZodString, + _default: () => _default2, + _function: () => _function, + any: () => any, + array: () => array, + base64: () => base642, + base64url: () => base64url2, + bigint: () => bigint3, + boolean: () => boolean3, + catch: () => _catch2, + check: () => check2, + cidrv4: () => cidrv42, + cidrv6: () => cidrv62, + codec: () => codec, + cuid: () => cuid3, + cuid2: () => cuid22, + custom: () => custom2, + date: () => date5, + describe: () => describe2, + discriminatedUnion: () => discriminatedUnion, + e164: () => e1642, + email: () => email2, + emoji: () => emoji2, + enum: () => _enum2, + exactOptional: () => exactOptional, + file: () => file, + float32: () => float32, + float64: () => float64, + function: () => _function, + guid: () => guid2, + hash: () => hash, + hex: () => hex2, + hostname: () => hostname2, + httpUrl: () => httpUrl, + instanceof: () => _instanceof, + int: () => int, + int32: () => int32, + int64: () => int64, + intersection: () => intersection, + ipv4: () => ipv42, + ipv6: () => ipv62, + json: () => json2, + jwt: () => jwt, + keyof: () => keyof, + ksuid: () => ksuid2, + lazy: () => lazy, + literal: () => literal, + looseObject: () => looseObject, + looseRecord: () => looseRecord, + mac: () => mac2, + map: () => map2, + meta: () => meta2, + nan: () => nan, + nanoid: () => nanoid2, + nativeEnum: () => nativeEnum, + never: () => never, + nonoptional: () => nonoptional, + null: () => _null3, + nullable: () => nullable, + nullish: () => nullish2, + number: () => number2, + object: () => object, + optional: () => optional, + partialRecord: () => partialRecord, + pipe: () => pipe, + prefault: () => prefault, + preprocess: () => preprocess, + promise: () => promise, + readonly: () => readonly, + record: () => record, + refine: () => refine, + set: () => set, + strictObject: () => strictObject, + string: () => string2, + stringFormat: () => stringFormat, + stringbool: () => stringbool, + success: () => success, + superRefine: () => superRefine, + symbol: () => symbol, + templateLiteral: () => templateLiteral, + transform: () => transform, + tuple: () => tuple, + uint32: () => uint32, + uint64: () => uint64, + ulid: () => ulid2, + undefined: () => _undefined3, + union: () => union2, + unknown: () => unknown, + url: () => url, + uuid: () => uuid3, + uuidv4: () => uuidv4, + uuidv6: () => uuidv6, + uuidv7: () => uuidv7, + void: () => _void2, + xid: () => xid2, + xor: () => xor2 +}); +function string2(params) { + return _string(ZodString2, params); +} +function email2(params) { + return _email(ZodEmail, params); +} +function guid2(params) { + return _guid(ZodGUID, params); +} +function uuid3(params) { + return _uuid(ZodUUID, params); +} +function uuidv4(params) { + return _uuidv4(ZodUUID, params); +} +function uuidv6(params) { + return _uuidv6(ZodUUID, params); +} +function uuidv7(params) { + return _uuidv7(ZodUUID, params); +} +function url(params) { + return _url(ZodURL, params); +} +function httpUrl(params) { + return _url(ZodURL, { + protocol: /^https?$/, + hostname: regexes_exports.domain, + ...util_exports.normalizeParams(params) + }); +} +function emoji2(params) { + return _emoji2(ZodEmoji, params); +} +function nanoid2(params) { + return _nanoid(ZodNanoID, params); +} +function cuid3(params) { + return _cuid(ZodCUID, params); +} +function cuid22(params) { + return _cuid2(ZodCUID2, params); +} +function ulid2(params) { + return _ulid(ZodULID, params); +} +function xid2(params) { + return _xid(ZodXID, params); +} +function ksuid2(params) { + return _ksuid(ZodKSUID, params); +} +function ipv42(params) { + return _ipv4(ZodIPv4, params); +} +function mac2(params) { + return _mac(ZodMAC, params); +} +function ipv62(params) { + return _ipv6(ZodIPv6, params); +} +function cidrv42(params) { + return _cidrv4(ZodCIDRv4, params); +} +function cidrv62(params) { + return _cidrv6(ZodCIDRv6, params); +} +function base642(params) { + return _base64(ZodBase64, params); +} +function base64url2(params) { + return _base64url(ZodBase64URL, params); +} +function e1642(params) { + return _e164(ZodE164, params); +} +function jwt(params) { + return _jwt(ZodJWT, params); +} +function stringFormat(format2, fnOrRegex, _params = {}) { + return _stringFormat(ZodCustomStringFormat, format2, fnOrRegex, _params); +} +function hostname2(_params) { + return _stringFormat(ZodCustomStringFormat, "hostname", regexes_exports.hostname, _params); +} +function hex2(_params) { + return _stringFormat(ZodCustomStringFormat, "hex", regexes_exports.hex, _params); +} +function hash(alg2, params) { + const enc2 = params?.enc ?? "hex"; + const format2 = `${alg2}_${enc2}`; + const regex = regexes_exports[format2]; + if (!regex) + throw new Error(`Unrecognized hash format: ${format2}`); + return _stringFormat(ZodCustomStringFormat, format2, regex, params); +} +function number2(params) { + return _number(ZodNumber2, params); +} +function int(params) { + return _int(ZodNumberFormat, params); +} +function float32(params) { + return _float32(ZodNumberFormat, params); +} +function float64(params) { + return _float64(ZodNumberFormat, params); +} +function int32(params) { + return _int32(ZodNumberFormat, params); +} +function uint32(params) { + return _uint32(ZodNumberFormat, params); +} +function boolean3(params) { + return _boolean(ZodBoolean2, params); +} +function bigint3(params) { + return _bigint(ZodBigInt2, params); +} +function int64(params) { + return _int64(ZodBigIntFormat, params); +} +function uint64(params) { + return _uint64(ZodBigIntFormat, params); +} +function symbol(params) { + return _symbol(ZodSymbol2, params); +} +function _undefined3(params) { + return _undefined2(ZodUndefined2, params); +} +function _null3(params) { + return _null2(ZodNull2, params); +} +function any() { + return _any(ZodAny2); +} +function unknown() { + return _unknown(ZodUnknown2); +} +function never(params) { + return _never(ZodNever2, params); +} +function _void2(params) { + return _void(ZodVoid2, params); +} +function date5(params) { + return _date(ZodDate2, params); +} +function array(element, params) { + return _array(ZodArray2, element, params); +} +function keyof(schema2) { + const shape = schema2._zod.def.shape; + return _enum2(Object.keys(shape)); +} +function object(shape, params) { + const def = { + type: "object", + shape: shape ?? {}, + ...util_exports.normalizeParams(params) + }; + return new ZodObject2(def); +} +function strictObject(shape, params) { + return new ZodObject2({ + type: "object", + shape, + catchall: never(), + ...util_exports.normalizeParams(params) + }); +} +function looseObject(shape, params) { + return new ZodObject2({ + type: "object", + shape, + catchall: unknown(), + ...util_exports.normalizeParams(params) + }); +} +function union2(options, params) { + return new ZodUnion2({ + type: "union", + options, + ...util_exports.normalizeParams(params) + }); +} +function xor2(options, params) { + return new ZodXor({ + type: "union", + options, + inclusive: false, + ...util_exports.normalizeParams(params) + }); +} +function discriminatedUnion(discriminator, options, params) { + return new ZodDiscriminatedUnion2({ + type: "union", + options, + discriminator, + ...util_exports.normalizeParams(params) + }); +} +function intersection(left, right) { + return new ZodIntersection2({ + type: "intersection", + left, + right + }); +} +function tuple(items, _paramsOrRest, _params) { + const hasRest = _paramsOrRest instanceof $ZodType; + const params = hasRest ? _params : _paramsOrRest; + const rest = hasRest ? _paramsOrRest : null; + return new ZodTuple2({ + type: "tuple", + items, + rest, + ...util_exports.normalizeParams(params) + }); +} +function record(keyType, valueType, params) { + return new ZodRecord2({ + type: "record", + keyType, + valueType, + ...util_exports.normalizeParams(params) + }); +} +function partialRecord(keyType, valueType, params) { + const k5 = clone2(keyType); + k5._zod.values = void 0; + return new ZodRecord2({ + type: "record", + keyType: k5, + valueType, + ...util_exports.normalizeParams(params) + }); +} +function looseRecord(keyType, valueType, params) { + return new ZodRecord2({ + type: "record", + keyType, + valueType, + mode: "loose", + ...util_exports.normalizeParams(params) + }); +} +function map2(keyType, valueType, params) { + return new ZodMap2({ + type: "map", + keyType, + valueType, + ...util_exports.normalizeParams(params) + }); +} +function set(valueType, params) { + return new ZodSet2({ + type: "set", + valueType, + ...util_exports.normalizeParams(params) + }); +} +function _enum2(values2, params) { + const entries2 = Array.isArray(values2) ? Object.fromEntries(values2.map((v5) => [v5, v5])) : values2; + return new ZodEnum2({ + type: "enum", + entries: entries2, + ...util_exports.normalizeParams(params) + }); +} +function nativeEnum(entries2, params) { + return new ZodEnum2({ + type: "enum", + entries: entries2, + ...util_exports.normalizeParams(params) + }); +} +function literal(value, params) { + return new ZodLiteral2({ + type: "literal", + values: Array.isArray(value) ? value : [value], + ...util_exports.normalizeParams(params) + }); +} +function file(params) { + return _file(ZodFile, params); +} +function transform(fn) { + return new ZodTransform({ + type: "transform", + transform: fn + }); +} +function optional(innerType) { + return new ZodOptional2({ + type: "optional", + innerType + }); +} +function exactOptional(innerType) { + return new ZodExactOptional({ + type: "optional", + innerType + }); +} +function nullable(innerType) { + return new ZodNullable2({ + type: "nullable", + innerType + }); +} +function nullish2(innerType) { + return optional(nullable(innerType)); +} +function _default2(innerType, defaultValue) { + return new ZodDefault2({ + type: "default", + innerType, + get defaultValue() { + return typeof defaultValue === "function" ? defaultValue() : util_exports.shallowClone(defaultValue); + } + }); +} +function prefault(innerType, defaultValue) { + return new ZodPrefault({ + type: "prefault", + innerType, + get defaultValue() { + return typeof defaultValue === "function" ? defaultValue() : util_exports.shallowClone(defaultValue); + } + }); +} +function nonoptional(innerType, params) { + return new ZodNonOptional({ + type: "nonoptional", + innerType, + ...util_exports.normalizeParams(params) + }); +} +function success(innerType) { + return new ZodSuccess({ + type: "success", + innerType + }); +} +function _catch2(innerType, catchValue) { + return new ZodCatch2({ + type: "catch", + innerType, + catchValue: typeof catchValue === "function" ? catchValue : () => catchValue + }); +} +function nan(params) { + return _nan(ZodNaN2, params); +} +function pipe(in_, out) { + return new ZodPipe({ + type: "pipe", + in: in_, + out + // ...util.normalizeParams(params), + }); +} +function codec(in_, out, params) { + return new ZodCodec({ + type: "pipe", + in: in_, + out, + transform: params.decode, + reverseTransform: params.encode + }); +} +function readonly(innerType) { + return new ZodReadonly2({ + type: "readonly", + innerType + }); +} +function templateLiteral(parts, params) { + return new ZodTemplateLiteral({ + type: "template_literal", + parts, + ...util_exports.normalizeParams(params) + }); +} +function lazy(getter) { + return new ZodLazy2({ + type: "lazy", + getter + }); +} +function promise(innerType) { + return new ZodPromise2({ + type: "promise", + innerType + }); +} +function _function(params) { + return new ZodFunction2({ + type: "function", + input: Array.isArray(params?.input) ? tuple(params?.input) : params?.input ?? array(unknown()), + output: params?.output ?? unknown() + }); +} +function check2(fn) { + const ch = new $ZodCheck({ + check: "custom" + // ...util.normalizeParams(params), + }); + ch._zod.check = fn; + return ch; +} +function custom2(fn, _params) { + return _custom(ZodCustom, fn ?? (() => true), _params); +} +function refine(fn, _params = {}) { + return _refine(ZodCustom, fn, _params); +} +function superRefine(fn) { + return _superRefine(fn); +} +function _instanceof(cls, params = {}) { + const inst = new ZodCustom({ + type: "custom", + check: "custom", + fn: (data2) => data2 instanceof cls, + abort: true, + ...util_exports.normalizeParams(params) + }); + inst._zod.bag.Class = cls; + inst._zod.check = (payload2) => { + if (!(payload2.value instanceof cls)) { + payload2.issues.push({ + code: "invalid_type", + expected: cls.name, + input: payload2.value, + inst, + path: [...inst._zod.def.path ?? []] + }); + } + }; + return inst; +} +function json2(params) { + const jsonSchema = lazy(() => { + return union2([string2(params), number2(), boolean3(), _null3(), array(jsonSchema), record(string2(), jsonSchema)]); + }); + return jsonSchema; +} +function preprocess(fn, schema2) { + return pipe(transform(fn), schema2); +} +var ZodType2, _ZodString, ZodString2, ZodStringFormat, ZodEmail, ZodGUID, ZodUUID, ZodURL, ZodEmoji, ZodNanoID, ZodCUID, ZodCUID2, ZodULID, ZodXID, ZodKSUID, ZodIPv4, ZodMAC, ZodIPv6, ZodCIDRv4, ZodCIDRv6, ZodBase64, ZodBase64URL, ZodE164, ZodJWT, ZodCustomStringFormat, ZodNumber2, ZodNumberFormat, ZodBoolean2, ZodBigInt2, ZodBigIntFormat, ZodSymbol2, ZodUndefined2, ZodNull2, ZodAny2, ZodUnknown2, ZodNever2, ZodVoid2, ZodDate2, ZodArray2, ZodObject2, ZodUnion2, ZodXor, ZodDiscriminatedUnion2, ZodIntersection2, ZodTuple2, ZodRecord2, ZodMap2, ZodSet2, ZodEnum2, ZodLiteral2, ZodFile, ZodTransform, ZodOptional2, ZodExactOptional, ZodNullable2, ZodDefault2, ZodPrefault, ZodNonOptional, ZodSuccess, ZodCatch2, ZodNaN2, ZodPipe, ZodCodec, ZodReadonly2, ZodTemplateLiteral, ZodLazy2, ZodPromise2, ZodFunction2, ZodCustom, describe2, meta2, stringbool; +var init_schemas2 = __esm({ + "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/schemas.js"() { + init_core2(); + init_core2(); + init_json_schema_processors(); + init_to_json_schema(); + init_checks3(); + init_iso(); + init_parse2(); + ZodType2 = /* @__PURE__ */ $constructor("ZodType", (inst, def) => { + $ZodType.init(inst, def); + Object.assign(inst["~standard"], { + jsonSchema: { + input: createStandardJSONSchemaMethod(inst, "input"), + output: createStandardJSONSchemaMethod(inst, "output") + } + }); + inst.toJSONSchema = createToJSONSchemaMethod(inst, {}); + inst.def = def; + inst.type = def.type; + Object.defineProperty(inst, "_def", { value: def }); + inst.check = (...checks) => { + return inst.clone(util_exports.mergeDefs(def, { + checks: [ + ...def.checks ?? [], + ...checks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch) + ] + }), { + parent: true + }); + }; + inst.with = inst.check; + inst.clone = (def2, params) => clone2(inst, def2, params); + inst.brand = () => inst; + inst.register = ((reg, meta3) => { + reg.add(inst, meta3); + return inst; + }); + inst.parse = (data2, params) => parse3(inst, data2, params, { callee: inst.parse }); + inst.safeParse = (data2, params) => safeParse2(inst, data2, params); + inst.parseAsync = async (data2, params) => parseAsync2(inst, data2, params, { callee: inst.parseAsync }); + inst.safeParseAsync = async (data2, params) => safeParseAsync2(inst, data2, params); + inst.spa = inst.safeParseAsync; + inst.encode = (data2, params) => encode5(inst, data2, params); + inst.decode = (data2, params) => decode4(inst, data2, params); + inst.encodeAsync = async (data2, params) => encodeAsync2(inst, data2, params); + inst.decodeAsync = async (data2, params) => decodeAsync2(inst, data2, params); + inst.safeEncode = (data2, params) => safeEncode2(inst, data2, params); + inst.safeDecode = (data2, params) => safeDecode2(inst, data2, params); + inst.safeEncodeAsync = async (data2, params) => safeEncodeAsync2(inst, data2, params); + inst.safeDecodeAsync = async (data2, params) => safeDecodeAsync2(inst, data2, params); + inst.refine = (check3, params) => inst.check(refine(check3, params)); + inst.superRefine = (refinement) => inst.check(superRefine(refinement)); + inst.overwrite = (fn) => inst.check(_overwrite(fn)); + inst.optional = () => optional(inst); + inst.exactOptional = () => exactOptional(inst); + inst.nullable = () => nullable(inst); + inst.nullish = () => optional(nullable(inst)); + inst.nonoptional = (params) => nonoptional(inst, params); + inst.array = () => array(inst); + inst.or = (arg) => union2([inst, arg]); + inst.and = (arg) => intersection(inst, arg); + inst.transform = (tx) => pipe(inst, transform(tx)); + inst.default = (def2) => _default2(inst, def2); + inst.prefault = (def2) => prefault(inst, def2); + inst.catch = (params) => _catch2(inst, params); + inst.pipe = (target) => pipe(inst, target); + inst.readonly = () => readonly(inst); + inst.describe = (description) => { + const cl = inst.clone(); + globalRegistry.add(cl, { description }); + return cl; + }; + Object.defineProperty(inst, "description", { + get() { + return globalRegistry.get(inst)?.description; + }, + configurable: true + }); + inst.meta = (...args) => { + if (args.length === 0) { + return globalRegistry.get(inst); + } + const cl = inst.clone(); + globalRegistry.add(cl, args[0]); + return cl; + }; + inst.isOptional = () => inst.safeParse(void 0).success; + inst.isNullable = () => inst.safeParse(null).success; + inst.apply = (fn) => fn(inst); + return inst; + }); + _ZodString = /* @__PURE__ */ $constructor("_ZodString", (inst, def) => { + $ZodString.init(inst, def); + ZodType2.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => stringProcessor(inst, ctx, json3, params); + const bag = inst._zod.bag; + inst.format = bag.format ?? null; + inst.minLength = bag.minimum ?? null; + inst.maxLength = bag.maximum ?? null; + inst.regex = (...args) => inst.check(_regex(...args)); + inst.includes = (...args) => inst.check(_includes(...args)); + inst.startsWith = (...args) => inst.check(_startsWith(...args)); + inst.endsWith = (...args) => inst.check(_endsWith(...args)); + inst.min = (...args) => inst.check(_minLength(...args)); + inst.max = (...args) => inst.check(_maxLength(...args)); + inst.length = (...args) => inst.check(_length(...args)); + inst.nonempty = (...args) => inst.check(_minLength(1, ...args)); + inst.lowercase = (params) => inst.check(_lowercase(params)); + inst.uppercase = (params) => inst.check(_uppercase(params)); + inst.trim = () => inst.check(_trim()); + inst.normalize = (...args) => inst.check(_normalize(...args)); + inst.toLowerCase = () => inst.check(_toLowerCase()); + inst.toUpperCase = () => inst.check(_toUpperCase()); + inst.slugify = () => inst.check(_slugify()); + }); + ZodString2 = /* @__PURE__ */ $constructor("ZodString", (inst, def) => { + $ZodString.init(inst, def); + _ZodString.init(inst, def); + inst.email = (params) => inst.check(_email(ZodEmail, params)); + inst.url = (params) => inst.check(_url(ZodURL, params)); + inst.jwt = (params) => inst.check(_jwt(ZodJWT, params)); + inst.emoji = (params) => inst.check(_emoji2(ZodEmoji, params)); + inst.guid = (params) => inst.check(_guid(ZodGUID, params)); + inst.uuid = (params) => inst.check(_uuid(ZodUUID, params)); + inst.uuidv4 = (params) => inst.check(_uuidv4(ZodUUID, params)); + inst.uuidv6 = (params) => inst.check(_uuidv6(ZodUUID, params)); + inst.uuidv7 = (params) => inst.check(_uuidv7(ZodUUID, params)); + inst.nanoid = (params) => inst.check(_nanoid(ZodNanoID, params)); + inst.guid = (params) => inst.check(_guid(ZodGUID, params)); + inst.cuid = (params) => inst.check(_cuid(ZodCUID, params)); + inst.cuid2 = (params) => inst.check(_cuid2(ZodCUID2, params)); + inst.ulid = (params) => inst.check(_ulid(ZodULID, params)); + inst.base64 = (params) => inst.check(_base64(ZodBase64, params)); + inst.base64url = (params) => inst.check(_base64url(ZodBase64URL, params)); + inst.xid = (params) => inst.check(_xid(ZodXID, params)); + inst.ksuid = (params) => inst.check(_ksuid(ZodKSUID, params)); + inst.ipv4 = (params) => inst.check(_ipv4(ZodIPv4, params)); + inst.ipv6 = (params) => inst.check(_ipv6(ZodIPv6, params)); + inst.cidrv4 = (params) => inst.check(_cidrv4(ZodCIDRv4, params)); + inst.cidrv6 = (params) => inst.check(_cidrv6(ZodCIDRv6, params)); + inst.e164 = (params) => inst.check(_e164(ZodE164, params)); + inst.datetime = (params) => inst.check(datetime2(params)); + inst.date = (params) => inst.check(date4(params)); + inst.time = (params) => inst.check(time4(params)); + inst.duration = (params) => inst.check(duration2(params)); + }); + ZodStringFormat = /* @__PURE__ */ $constructor("ZodStringFormat", (inst, def) => { + $ZodStringFormat.init(inst, def); + _ZodString.init(inst, def); + }); + ZodEmail = /* @__PURE__ */ $constructor("ZodEmail", (inst, def) => { + $ZodEmail.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodGUID = /* @__PURE__ */ $constructor("ZodGUID", (inst, def) => { + $ZodGUID.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodUUID = /* @__PURE__ */ $constructor("ZodUUID", (inst, def) => { + $ZodUUID.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodURL = /* @__PURE__ */ $constructor("ZodURL", (inst, def) => { + $ZodURL.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodEmoji = /* @__PURE__ */ $constructor("ZodEmoji", (inst, def) => { + $ZodEmoji.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodNanoID = /* @__PURE__ */ $constructor("ZodNanoID", (inst, def) => { + $ZodNanoID.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodCUID = /* @__PURE__ */ $constructor("ZodCUID", (inst, def) => { + $ZodCUID.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodCUID2 = /* @__PURE__ */ $constructor("ZodCUID2", (inst, def) => { + $ZodCUID2.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodULID = /* @__PURE__ */ $constructor("ZodULID", (inst, def) => { + $ZodULID.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodXID = /* @__PURE__ */ $constructor("ZodXID", (inst, def) => { + $ZodXID.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodKSUID = /* @__PURE__ */ $constructor("ZodKSUID", (inst, def) => { + $ZodKSUID.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodIPv4 = /* @__PURE__ */ $constructor("ZodIPv4", (inst, def) => { + $ZodIPv4.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodMAC = /* @__PURE__ */ $constructor("ZodMAC", (inst, def) => { + $ZodMAC.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodIPv6 = /* @__PURE__ */ $constructor("ZodIPv6", (inst, def) => { + $ZodIPv6.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodCIDRv4 = /* @__PURE__ */ $constructor("ZodCIDRv4", (inst, def) => { + $ZodCIDRv4.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodCIDRv6 = /* @__PURE__ */ $constructor("ZodCIDRv6", (inst, def) => { + $ZodCIDRv6.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodBase64 = /* @__PURE__ */ $constructor("ZodBase64", (inst, def) => { + $ZodBase64.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodBase64URL = /* @__PURE__ */ $constructor("ZodBase64URL", (inst, def) => { + $ZodBase64URL.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodE164 = /* @__PURE__ */ $constructor("ZodE164", (inst, def) => { + $ZodE164.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodJWT = /* @__PURE__ */ $constructor("ZodJWT", (inst, def) => { + $ZodJWT.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodCustomStringFormat = /* @__PURE__ */ $constructor("ZodCustomStringFormat", (inst, def) => { + $ZodCustomStringFormat.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodNumber2 = /* @__PURE__ */ $constructor("ZodNumber", (inst, def) => { + $ZodNumber.init(inst, def); + ZodType2.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => numberProcessor(inst, ctx, json3, params); + inst.gt = (value, params) => inst.check(_gt(value, params)); + inst.gte = (value, params) => inst.check(_gte(value, params)); + inst.min = (value, params) => inst.check(_gte(value, params)); + inst.lt = (value, params) => inst.check(_lt(value, params)); + inst.lte = (value, params) => inst.check(_lte(value, params)); + inst.max = (value, params) => inst.check(_lte(value, params)); + inst.int = (params) => inst.check(int(params)); + inst.safe = (params) => inst.check(int(params)); + inst.positive = (params) => inst.check(_gt(0, params)); + inst.nonnegative = (params) => inst.check(_gte(0, params)); + inst.negative = (params) => inst.check(_lt(0, params)); + inst.nonpositive = (params) => inst.check(_lte(0, params)); + inst.multipleOf = (value, params) => inst.check(_multipleOf(value, params)); + inst.step = (value, params) => inst.check(_multipleOf(value, params)); + inst.finite = () => inst; + const bag = inst._zod.bag; + inst.minValue = Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null; + inst.maxValue = Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null; + inst.isInt = (bag.format ?? "").includes("int") || Number.isSafeInteger(bag.multipleOf ?? 0.5); + inst.isFinite = true; + inst.format = bag.format ?? null; + }); + ZodNumberFormat = /* @__PURE__ */ $constructor("ZodNumberFormat", (inst, def) => { + $ZodNumberFormat.init(inst, def); + ZodNumber2.init(inst, def); + }); + ZodBoolean2 = /* @__PURE__ */ $constructor("ZodBoolean", (inst, def) => { + $ZodBoolean.init(inst, def); + ZodType2.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => booleanProcessor(inst, ctx, json3, params); + }); + ZodBigInt2 = /* @__PURE__ */ $constructor("ZodBigInt", (inst, def) => { + $ZodBigInt.init(inst, def); + ZodType2.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => bigintProcessor(inst, ctx, json3, params); + inst.gte = (value, params) => inst.check(_gte(value, params)); + inst.min = (value, params) => inst.check(_gte(value, params)); + inst.gt = (value, params) => inst.check(_gt(value, params)); + inst.gte = (value, params) => inst.check(_gte(value, params)); + inst.min = (value, params) => inst.check(_gte(value, params)); + inst.lt = (value, params) => inst.check(_lt(value, params)); + inst.lte = (value, params) => inst.check(_lte(value, params)); + inst.max = (value, params) => inst.check(_lte(value, params)); + inst.positive = (params) => inst.check(_gt(BigInt(0), params)); + inst.negative = (params) => inst.check(_lt(BigInt(0), params)); + inst.nonpositive = (params) => inst.check(_lte(BigInt(0), params)); + inst.nonnegative = (params) => inst.check(_gte(BigInt(0), params)); + inst.multipleOf = (value, params) => inst.check(_multipleOf(value, params)); + const bag = inst._zod.bag; + inst.minValue = bag.minimum ?? null; + inst.maxValue = bag.maximum ?? null; + inst.format = bag.format ?? null; + }); + ZodBigIntFormat = /* @__PURE__ */ $constructor("ZodBigIntFormat", (inst, def) => { + $ZodBigIntFormat.init(inst, def); + ZodBigInt2.init(inst, def); + }); + ZodSymbol2 = /* @__PURE__ */ $constructor("ZodSymbol", (inst, def) => { + $ZodSymbol.init(inst, def); + ZodType2.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => symbolProcessor(inst, ctx, json3, params); + }); + ZodUndefined2 = /* @__PURE__ */ $constructor("ZodUndefined", (inst, def) => { + $ZodUndefined.init(inst, def); + ZodType2.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => undefinedProcessor(inst, ctx, json3, params); + }); + ZodNull2 = /* @__PURE__ */ $constructor("ZodNull", (inst, def) => { + $ZodNull.init(inst, def); + ZodType2.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => nullProcessor(inst, ctx, json3, params); + }); + ZodAny2 = /* @__PURE__ */ $constructor("ZodAny", (inst, def) => { + $ZodAny.init(inst, def); + ZodType2.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => anyProcessor(inst, ctx, json3, params); + }); + ZodUnknown2 = /* @__PURE__ */ $constructor("ZodUnknown", (inst, def) => { + $ZodUnknown.init(inst, def); + ZodType2.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => unknownProcessor(inst, ctx, json3, params); + }); + ZodNever2 = /* @__PURE__ */ $constructor("ZodNever", (inst, def) => { + $ZodNever.init(inst, def); + ZodType2.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => neverProcessor(inst, ctx, json3, params); + }); + ZodVoid2 = /* @__PURE__ */ $constructor("ZodVoid", (inst, def) => { + $ZodVoid.init(inst, def); + ZodType2.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => voidProcessor(inst, ctx, json3, params); + }); + ZodDate2 = /* @__PURE__ */ $constructor("ZodDate", (inst, def) => { + $ZodDate.init(inst, def); + ZodType2.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => dateProcessor(inst, ctx, json3, params); + inst.min = (value, params) => inst.check(_gte(value, params)); + inst.max = (value, params) => inst.check(_lte(value, params)); + const c5 = inst._zod.bag; + inst.minDate = c5.minimum ? new Date(c5.minimum) : null; + inst.maxDate = c5.maximum ? new Date(c5.maximum) : null; + }); + ZodArray2 = /* @__PURE__ */ $constructor("ZodArray", (inst, def) => { + $ZodArray.init(inst, def); + ZodType2.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => arrayProcessor(inst, ctx, json3, params); + inst.element = def.element; + inst.min = (minLength, params) => inst.check(_minLength(minLength, params)); + inst.nonempty = (params) => inst.check(_minLength(1, params)); + inst.max = (maxLength, params) => inst.check(_maxLength(maxLength, params)); + inst.length = (len, params) => inst.check(_length(len, params)); + inst.unwrap = () => inst.element; + }); + ZodObject2 = /* @__PURE__ */ $constructor("ZodObject", (inst, def) => { + $ZodObjectJIT.init(inst, def); + ZodType2.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => objectProcessor(inst, ctx, json3, params); + util_exports.defineLazy(inst, "shape", () => { + return def.shape; + }); + inst.keyof = () => _enum2(Object.keys(inst._zod.def.shape)); + inst.catchall = (catchall) => inst.clone({ ...inst._zod.def, catchall }); + inst.passthrough = () => inst.clone({ ...inst._zod.def, catchall: unknown() }); + inst.loose = () => inst.clone({ ...inst._zod.def, catchall: unknown() }); + inst.strict = () => inst.clone({ ...inst._zod.def, catchall: never() }); + inst.strip = () => inst.clone({ ...inst._zod.def, catchall: void 0 }); + inst.extend = (incoming) => { + return util_exports.extend(inst, incoming); + }; + inst.safeExtend = (incoming) => { + return util_exports.safeExtend(inst, incoming); + }; + inst.merge = (other) => util_exports.merge(inst, other); + inst.pick = (mask) => util_exports.pick(inst, mask); + inst.omit = (mask) => util_exports.omit(inst, mask); + inst.partial = (...args) => util_exports.partial(ZodOptional2, inst, args[0]); + inst.required = (...args) => util_exports.required(ZodNonOptional, inst, args[0]); + }); + ZodUnion2 = /* @__PURE__ */ $constructor("ZodUnion", (inst, def) => { + $ZodUnion.init(inst, def); + ZodType2.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => unionProcessor(inst, ctx, json3, params); + inst.options = def.options; + }); + ZodXor = /* @__PURE__ */ $constructor("ZodXor", (inst, def) => { + ZodUnion2.init(inst, def); + $ZodXor.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => unionProcessor(inst, ctx, json3, params); + inst.options = def.options; + }); + ZodDiscriminatedUnion2 = /* @__PURE__ */ $constructor("ZodDiscriminatedUnion", (inst, def) => { + ZodUnion2.init(inst, def); + $ZodDiscriminatedUnion.init(inst, def); + }); + ZodIntersection2 = /* @__PURE__ */ $constructor("ZodIntersection", (inst, def) => { + $ZodIntersection.init(inst, def); + ZodType2.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => intersectionProcessor(inst, ctx, json3, params); + }); + ZodTuple2 = /* @__PURE__ */ $constructor("ZodTuple", (inst, def) => { + $ZodTuple.init(inst, def); + ZodType2.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => tupleProcessor(inst, ctx, json3, params); + inst.rest = (rest) => inst.clone({ + ...inst._zod.def, + rest + }); + }); + ZodRecord2 = /* @__PURE__ */ $constructor("ZodRecord", (inst, def) => { + $ZodRecord.init(inst, def); + ZodType2.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => recordProcessor(inst, ctx, json3, params); + inst.keyType = def.keyType; + inst.valueType = def.valueType; + }); + ZodMap2 = /* @__PURE__ */ $constructor("ZodMap", (inst, def) => { + $ZodMap.init(inst, def); + ZodType2.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => mapProcessor(inst, ctx, json3, params); + inst.keyType = def.keyType; + inst.valueType = def.valueType; + inst.min = (...args) => inst.check(_minSize(...args)); + inst.nonempty = (params) => inst.check(_minSize(1, params)); + inst.max = (...args) => inst.check(_maxSize(...args)); + inst.size = (...args) => inst.check(_size(...args)); + }); + ZodSet2 = /* @__PURE__ */ $constructor("ZodSet", (inst, def) => { + $ZodSet.init(inst, def); + ZodType2.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => setProcessor(inst, ctx, json3, params); + inst.min = (...args) => inst.check(_minSize(...args)); + inst.nonempty = (params) => inst.check(_minSize(1, params)); + inst.max = (...args) => inst.check(_maxSize(...args)); + inst.size = (...args) => inst.check(_size(...args)); + }); + ZodEnum2 = /* @__PURE__ */ $constructor("ZodEnum", (inst, def) => { + $ZodEnum.init(inst, def); + ZodType2.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => enumProcessor(inst, ctx, json3, params); + inst.enum = def.entries; + inst.options = Object.values(def.entries); + const keys = new Set(Object.keys(def.entries)); + inst.extract = (values2, params) => { + const newEntries = {}; + for (const value of values2) { + if (keys.has(value)) { + newEntries[value] = def.entries[value]; + } else + throw new Error(`Key ${value} not found in enum`); + } + return new ZodEnum2({ + ...def, + checks: [], + ...util_exports.normalizeParams(params), + entries: newEntries + }); + }; + inst.exclude = (values2, params) => { + const newEntries = { ...def.entries }; + for (const value of values2) { + if (keys.has(value)) { + delete newEntries[value]; + } else + throw new Error(`Key ${value} not found in enum`); + } + return new ZodEnum2({ + ...def, + checks: [], + ...util_exports.normalizeParams(params), + entries: newEntries + }); + }; + }); + ZodLiteral2 = /* @__PURE__ */ $constructor("ZodLiteral", (inst, def) => { + $ZodLiteral.init(inst, def); + ZodType2.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => literalProcessor(inst, ctx, json3, params); + inst.values = new Set(def.values); + Object.defineProperty(inst, "value", { + get() { + if (def.values.length > 1) { + throw new Error("This schema contains multiple valid literal values. Use `.values` instead."); + } + return def.values[0]; + } + }); + }); + ZodFile = /* @__PURE__ */ $constructor("ZodFile", (inst, def) => { + $ZodFile.init(inst, def); + ZodType2.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => fileProcessor(inst, ctx, json3, params); + inst.min = (size2, params) => inst.check(_minSize(size2, params)); + inst.max = (size2, params) => inst.check(_maxSize(size2, params)); + inst.mime = (types2, params) => inst.check(_mime(Array.isArray(types2) ? types2 : [types2], params)); + }); + ZodTransform = /* @__PURE__ */ $constructor("ZodTransform", (inst, def) => { + $ZodTransform.init(inst, def); + ZodType2.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => transformProcessor(inst, ctx, json3, params); + inst._zod.parse = (payload2, _ctx) => { + if (_ctx.direction === "backward") { + throw new $ZodEncodeError(inst.constructor.name); + } + payload2.addIssue = (issue2) => { + if (typeof issue2 === "string") { + payload2.issues.push(util_exports.issue(issue2, payload2.value, def)); + } else { + const _issue = issue2; + if (_issue.fatal) + _issue.continue = false; + _issue.code ?? (_issue.code = "custom"); + _issue.input ?? (_issue.input = payload2.value); + _issue.inst ?? (_issue.inst = inst); + payload2.issues.push(util_exports.issue(_issue)); + } + }; + const output = def.transform(payload2.value, payload2); + if (output instanceof Promise) { + return output.then((output2) => { + payload2.value = output2; + return payload2; + }); + } + payload2.value = output; + return payload2; + }; + }); + ZodOptional2 = /* @__PURE__ */ $constructor("ZodOptional", (inst, def) => { + $ZodOptional.init(inst, def); + ZodType2.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => optionalProcessor(inst, ctx, json3, params); + inst.unwrap = () => inst._zod.def.innerType; + }); + ZodExactOptional = /* @__PURE__ */ $constructor("ZodExactOptional", (inst, def) => { + $ZodExactOptional.init(inst, def); + ZodType2.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => optionalProcessor(inst, ctx, json3, params); + inst.unwrap = () => inst._zod.def.innerType; + }); + ZodNullable2 = /* @__PURE__ */ $constructor("ZodNullable", (inst, def) => { + $ZodNullable.init(inst, def); + ZodType2.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => nullableProcessor(inst, ctx, json3, params); + inst.unwrap = () => inst._zod.def.innerType; + }); + ZodDefault2 = /* @__PURE__ */ $constructor("ZodDefault", (inst, def) => { + $ZodDefault.init(inst, def); + ZodType2.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => defaultProcessor(inst, ctx, json3, params); + inst.unwrap = () => inst._zod.def.innerType; + inst.removeDefault = inst.unwrap; + }); + ZodPrefault = /* @__PURE__ */ $constructor("ZodPrefault", (inst, def) => { + $ZodPrefault.init(inst, def); + ZodType2.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => prefaultProcessor(inst, ctx, json3, params); + inst.unwrap = () => inst._zod.def.innerType; + }); + ZodNonOptional = /* @__PURE__ */ $constructor("ZodNonOptional", (inst, def) => { + $ZodNonOptional.init(inst, def); + ZodType2.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => nonoptionalProcessor(inst, ctx, json3, params); + inst.unwrap = () => inst._zod.def.innerType; + }); + ZodSuccess = /* @__PURE__ */ $constructor("ZodSuccess", (inst, def) => { + $ZodSuccess.init(inst, def); + ZodType2.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => successProcessor(inst, ctx, json3, params); + inst.unwrap = () => inst._zod.def.innerType; + }); + ZodCatch2 = /* @__PURE__ */ $constructor("ZodCatch", (inst, def) => { + $ZodCatch.init(inst, def); + ZodType2.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => catchProcessor(inst, ctx, json3, params); + inst.unwrap = () => inst._zod.def.innerType; + inst.removeCatch = inst.unwrap; + }); + ZodNaN2 = /* @__PURE__ */ $constructor("ZodNaN", (inst, def) => { + $ZodNaN.init(inst, def); + ZodType2.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => nanProcessor(inst, ctx, json3, params); + }); + ZodPipe = /* @__PURE__ */ $constructor("ZodPipe", (inst, def) => { + $ZodPipe.init(inst, def); + ZodType2.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => pipeProcessor(inst, ctx, json3, params); + inst.in = def.in; + inst.out = def.out; + }); + ZodCodec = /* @__PURE__ */ $constructor("ZodCodec", (inst, def) => { + ZodPipe.init(inst, def); + $ZodCodec.init(inst, def); + }); + ZodReadonly2 = /* @__PURE__ */ $constructor("ZodReadonly", (inst, def) => { + $ZodReadonly.init(inst, def); + ZodType2.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => readonlyProcessor(inst, ctx, json3, params); + inst.unwrap = () => inst._zod.def.innerType; + }); + ZodTemplateLiteral = /* @__PURE__ */ $constructor("ZodTemplateLiteral", (inst, def) => { + $ZodTemplateLiteral.init(inst, def); + ZodType2.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => templateLiteralProcessor(inst, ctx, json3, params); + }); + ZodLazy2 = /* @__PURE__ */ $constructor("ZodLazy", (inst, def) => { + $ZodLazy.init(inst, def); + ZodType2.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => lazyProcessor(inst, ctx, json3, params); + inst.unwrap = () => inst._zod.def.getter(); + }); + ZodPromise2 = /* @__PURE__ */ $constructor("ZodPromise", (inst, def) => { + $ZodPromise.init(inst, def); + ZodType2.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => promiseProcessor(inst, ctx, json3, params); + inst.unwrap = () => inst._zod.def.innerType; + }); + ZodFunction2 = /* @__PURE__ */ $constructor("ZodFunction", (inst, def) => { + $ZodFunction.init(inst, def); + ZodType2.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => functionProcessor(inst, ctx, json3, params); + }); + ZodCustom = /* @__PURE__ */ $constructor("ZodCustom", (inst, def) => { + $ZodCustom.init(inst, def); + ZodType2.init(inst, def); + inst._zod.processJSONSchema = (ctx, json3, params) => customProcessor(inst, ctx, json3, params); + }); + describe2 = describe; + meta2 = meta; + stringbool = (...args) => _stringbool({ + Codec: ZodCodec, + Boolean: ZodBoolean2, + String: ZodString2 + }, ...args); + } +}); + +// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/compat.js +function setErrorMap2(map4) { + config({ + customError: map4 + }); +} +function getErrorMap2() { + return config().customError; +} +var ZodIssueCode2, ZodFirstPartyTypeKind2; +var init_compat = __esm({ + "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/compat.js"() { + init_core2(); + init_core2(); + ZodIssueCode2 = { + invalid_type: "invalid_type", + too_big: "too_big", + too_small: "too_small", + invalid_format: "invalid_format", + not_multiple_of: "not_multiple_of", + unrecognized_keys: "unrecognized_keys", + invalid_union: "invalid_union", + invalid_key: "invalid_key", + invalid_element: "invalid_element", + invalid_value: "invalid_value", + custom: "custom" + }; + /* @__PURE__ */ (function(ZodFirstPartyTypeKind3) { + })(ZodFirstPartyTypeKind2 || (ZodFirstPartyTypeKind2 = {})); + } +}); + +// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/from-json-schema.js +function detectVersion(schema2, defaultTarget) { + const $schema = schema2.$schema; + if ($schema === "https://json-schema.org/draft/2020-12/schema") { + return "draft-2020-12"; + } + if ($schema === "http://json-schema.org/draft-07/schema#") { + return "draft-7"; + } + if ($schema === "http://json-schema.org/draft-04/schema#") { + return "draft-4"; + } + return defaultTarget ?? "draft-2020-12"; +} +function resolveRef(ref, ctx) { + if (!ref.startsWith("#")) { + throw new Error("External $ref is not supported, only local refs (#/...) are allowed"); + } + const path53 = ref.slice(1).split("/").filter(Boolean); + if (path53.length === 0) { + return ctx.rootSchema; + } + const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions"; + if (path53[0] === defsKey) { + const key = path53[1]; + if (!key || !ctx.defs[key]) { + throw new Error(`Reference not found: ${ref}`); + } + return ctx.defs[key]; + } + throw new Error(`Reference not found: ${ref}`); +} +function convertBaseSchema(schema2, ctx) { + if (schema2.not !== void 0) { + if (typeof schema2.not === "object" && Object.keys(schema2.not).length === 0) { + return z2.never(); + } + throw new Error("not is not supported in Zod (except { not: {} } for never)"); + } + if (schema2.unevaluatedItems !== void 0) { + throw new Error("unevaluatedItems is not supported"); + } + if (schema2.unevaluatedProperties !== void 0) { + throw new Error("unevaluatedProperties is not supported"); + } + if (schema2.if !== void 0 || schema2.then !== void 0 || schema2.else !== void 0) { + throw new Error("Conditional schemas (if/then/else) are not supported"); + } + if (schema2.dependentSchemas !== void 0 || schema2.dependentRequired !== void 0) { + throw new Error("dependentSchemas and dependentRequired are not supported"); + } + if (schema2.$ref) { + const refPath = schema2.$ref; + if (ctx.refs.has(refPath)) { + return ctx.refs.get(refPath); + } + if (ctx.processing.has(refPath)) { + return z2.lazy(() => { + if (!ctx.refs.has(refPath)) { + throw new Error(`Circular reference not resolved: ${refPath}`); + } + return ctx.refs.get(refPath); + }); + } + ctx.processing.add(refPath); + const resolved = resolveRef(refPath, ctx); + const zodSchema2 = convertSchema(resolved, ctx); + ctx.refs.set(refPath, zodSchema2); + ctx.processing.delete(refPath); + return zodSchema2; + } + if (schema2.enum !== void 0) { + const enumValues = schema2.enum; + if (ctx.version === "openapi-3.0" && schema2.nullable === true && enumValues.length === 1 && enumValues[0] === null) { + return z2.null(); + } + if (enumValues.length === 0) { + return z2.never(); + } + if (enumValues.length === 1) { + return z2.literal(enumValues[0]); + } + if (enumValues.every((v5) => typeof v5 === "string")) { + return z2.enum(enumValues); + } + const literalSchemas = enumValues.map((v5) => z2.literal(v5)); + if (literalSchemas.length < 2) { + return literalSchemas[0]; + } + return z2.union([literalSchemas[0], literalSchemas[1], ...literalSchemas.slice(2)]); + } + if (schema2.const !== void 0) { + return z2.literal(schema2.const); + } + const type = schema2.type; + if (Array.isArray(type)) { + const typeSchemas = type.map((t5) => { + const typeSchema = { ...schema2, type: t5 }; + return convertBaseSchema(typeSchema, ctx); + }); + if (typeSchemas.length === 0) { + return z2.never(); + } + if (typeSchemas.length === 1) { + return typeSchemas[0]; + } + return z2.union(typeSchemas); + } + if (!type) { + return z2.any(); + } + let zodSchema; + switch (type) { + case "string": { + let stringSchema = z2.string(); + if (schema2.format) { + const format2 = schema2.format; + if (format2 === "email") { + stringSchema = stringSchema.check(z2.email()); + } else if (format2 === "uri" || format2 === "uri-reference") { + stringSchema = stringSchema.check(z2.url()); + } else if (format2 === "uuid" || format2 === "guid") { + stringSchema = stringSchema.check(z2.uuid()); + } else if (format2 === "date-time") { + stringSchema = stringSchema.check(z2.iso.datetime()); + } else if (format2 === "date") { + stringSchema = stringSchema.check(z2.iso.date()); + } else if (format2 === "time") { + stringSchema = stringSchema.check(z2.iso.time()); + } else if (format2 === "duration") { + stringSchema = stringSchema.check(z2.iso.duration()); + } else if (format2 === "ipv4") { + stringSchema = stringSchema.check(z2.ipv4()); + } else if (format2 === "ipv6") { + stringSchema = stringSchema.check(z2.ipv6()); + } else if (format2 === "mac") { + stringSchema = stringSchema.check(z2.mac()); + } else if (format2 === "cidr") { + stringSchema = stringSchema.check(z2.cidrv4()); + } else if (format2 === "cidr-v6") { + stringSchema = stringSchema.check(z2.cidrv6()); + } else if (format2 === "base64") { + stringSchema = stringSchema.check(z2.base64()); + } else if (format2 === "base64url") { + stringSchema = stringSchema.check(z2.base64url()); + } else if (format2 === "e164") { + stringSchema = stringSchema.check(z2.e164()); + } else if (format2 === "jwt") { + stringSchema = stringSchema.check(z2.jwt()); + } else if (format2 === "emoji") { + stringSchema = stringSchema.check(z2.emoji()); + } else if (format2 === "nanoid") { + stringSchema = stringSchema.check(z2.nanoid()); + } else if (format2 === "cuid") { + stringSchema = stringSchema.check(z2.cuid()); + } else if (format2 === "cuid2") { + stringSchema = stringSchema.check(z2.cuid2()); + } else if (format2 === "ulid") { + stringSchema = stringSchema.check(z2.ulid()); + } else if (format2 === "xid") { + stringSchema = stringSchema.check(z2.xid()); + } else if (format2 === "ksuid") { + stringSchema = stringSchema.check(z2.ksuid()); + } + } + if (typeof schema2.minLength === "number") { + stringSchema = stringSchema.min(schema2.minLength); + } + if (typeof schema2.maxLength === "number") { + stringSchema = stringSchema.max(schema2.maxLength); + } + if (schema2.pattern) { + stringSchema = stringSchema.regex(new RegExp(schema2.pattern)); + } + zodSchema = stringSchema; + break; + } + case "number": + case "integer": { + let numberSchema = type === "integer" ? z2.number().int() : z2.number(); + if (typeof schema2.minimum === "number") { + numberSchema = numberSchema.min(schema2.minimum); + } + if (typeof schema2.maximum === "number") { + numberSchema = numberSchema.max(schema2.maximum); + } + if (typeof schema2.exclusiveMinimum === "number") { + numberSchema = numberSchema.gt(schema2.exclusiveMinimum); + } else if (schema2.exclusiveMinimum === true && typeof schema2.minimum === "number") { + numberSchema = numberSchema.gt(schema2.minimum); + } + if (typeof schema2.exclusiveMaximum === "number") { + numberSchema = numberSchema.lt(schema2.exclusiveMaximum); + } else if (schema2.exclusiveMaximum === true && typeof schema2.maximum === "number") { + numberSchema = numberSchema.lt(schema2.maximum); + } + if (typeof schema2.multipleOf === "number") { + numberSchema = numberSchema.multipleOf(schema2.multipleOf); + } + zodSchema = numberSchema; + break; + } + case "boolean": { + zodSchema = z2.boolean(); + break; + } + case "null": { + zodSchema = z2.null(); + break; + } + case "object": { + const shape = {}; + const properties = schema2.properties || {}; + const requiredSet = new Set(schema2.required || []); + for (const [key, propSchema] of Object.entries(properties)) { + const propZodSchema = convertSchema(propSchema, ctx); + shape[key] = requiredSet.has(key) ? propZodSchema : propZodSchema.optional(); + } + if (schema2.propertyNames) { + const keySchema = convertSchema(schema2.propertyNames, ctx); + const valueSchema = schema2.additionalProperties && typeof schema2.additionalProperties === "object" ? convertSchema(schema2.additionalProperties, ctx) : z2.any(); + if (Object.keys(shape).length === 0) { + zodSchema = z2.record(keySchema, valueSchema); + break; + } + const objectSchema2 = z2.object(shape).passthrough(); + const recordSchema = z2.looseRecord(keySchema, valueSchema); + zodSchema = z2.intersection(objectSchema2, recordSchema); + break; + } + if (schema2.patternProperties) { + const patternProps = schema2.patternProperties; + const patternKeys = Object.keys(patternProps); + const looseRecords = []; + for (const pattern of patternKeys) { + const patternValue = convertSchema(patternProps[pattern], ctx); + const keySchema = z2.string().regex(new RegExp(pattern)); + looseRecords.push(z2.looseRecord(keySchema, patternValue)); + } + const schemasToIntersect = []; + if (Object.keys(shape).length > 0) { + schemasToIntersect.push(z2.object(shape).passthrough()); + } + schemasToIntersect.push(...looseRecords); + if (schemasToIntersect.length === 0) { + zodSchema = z2.object({}).passthrough(); + } else if (schemasToIntersect.length === 1) { + zodSchema = schemasToIntersect[0]; + } else { + let result = z2.intersection(schemasToIntersect[0], schemasToIntersect[1]); + for (let i5 = 2; i5 < schemasToIntersect.length; i5++) { + result = z2.intersection(result, schemasToIntersect[i5]); + } + zodSchema = result; + } + break; + } + const objectSchema = z2.object(shape); + if (schema2.additionalProperties === false) { + zodSchema = objectSchema.strict(); + } else if (typeof schema2.additionalProperties === "object") { + zodSchema = objectSchema.catchall(convertSchema(schema2.additionalProperties, ctx)); + } else { + zodSchema = objectSchema.passthrough(); + } + break; + } + case "array": { + const prefixItems = schema2.prefixItems; + const items = schema2.items; + if (prefixItems && Array.isArray(prefixItems)) { + const tupleItems = prefixItems.map((item) => convertSchema(item, ctx)); + const rest = items && typeof items === "object" && !Array.isArray(items) ? convertSchema(items, ctx) : void 0; + if (rest) { + zodSchema = z2.tuple(tupleItems).rest(rest); + } else { + zodSchema = z2.tuple(tupleItems); + } + if (typeof schema2.minItems === "number") { + zodSchema = zodSchema.check(z2.minLength(schema2.minItems)); + } + if (typeof schema2.maxItems === "number") { + zodSchema = zodSchema.check(z2.maxLength(schema2.maxItems)); + } + } else if (Array.isArray(items)) { + const tupleItems = items.map((item) => convertSchema(item, ctx)); + const rest = schema2.additionalItems && typeof schema2.additionalItems === "object" ? convertSchema(schema2.additionalItems, ctx) : void 0; + if (rest) { + zodSchema = z2.tuple(tupleItems).rest(rest); + } else { + zodSchema = z2.tuple(tupleItems); + } + if (typeof schema2.minItems === "number") { + zodSchema = zodSchema.check(z2.minLength(schema2.minItems)); + } + if (typeof schema2.maxItems === "number") { + zodSchema = zodSchema.check(z2.maxLength(schema2.maxItems)); + } + } else if (items !== void 0) { + const element = convertSchema(items, ctx); + let arraySchema = z2.array(element); + if (typeof schema2.minItems === "number") { + arraySchema = arraySchema.min(schema2.minItems); + } + if (typeof schema2.maxItems === "number") { + arraySchema = arraySchema.max(schema2.maxItems); + } + zodSchema = arraySchema; + } else { + zodSchema = z2.array(z2.any()); + } + break; + } + default: + throw new Error(`Unsupported type: ${type}`); + } + if (schema2.description) { + zodSchema = zodSchema.describe(schema2.description); + } + if (schema2.default !== void 0) { + zodSchema = zodSchema.default(schema2.default); + } + return zodSchema; +} +function convertSchema(schema2, ctx) { + if (typeof schema2 === "boolean") { + return schema2 ? z2.any() : z2.never(); + } + let baseSchema = convertBaseSchema(schema2, ctx); + const hasExplicitType = schema2.type || schema2.enum !== void 0 || schema2.const !== void 0; + if (schema2.anyOf && Array.isArray(schema2.anyOf)) { + const options = schema2.anyOf.map((s5) => convertSchema(s5, ctx)); + const anyOfUnion = z2.union(options); + baseSchema = hasExplicitType ? z2.intersection(baseSchema, anyOfUnion) : anyOfUnion; + } + if (schema2.oneOf && Array.isArray(schema2.oneOf)) { + const options = schema2.oneOf.map((s5) => convertSchema(s5, ctx)); + const oneOfUnion = z2.xor(options); + baseSchema = hasExplicitType ? z2.intersection(baseSchema, oneOfUnion) : oneOfUnion; + } + if (schema2.allOf && Array.isArray(schema2.allOf)) { + if (schema2.allOf.length === 0) { + baseSchema = hasExplicitType ? baseSchema : z2.any(); + } else { + let result = hasExplicitType ? baseSchema : convertSchema(schema2.allOf[0], ctx); + const startIdx = hasExplicitType ? 0 : 1; + for (let i5 = startIdx; i5 < schema2.allOf.length; i5++) { + result = z2.intersection(result, convertSchema(schema2.allOf[i5], ctx)); + } + baseSchema = result; + } + } + if (schema2.nullable === true && ctx.version === "openapi-3.0") { + baseSchema = z2.nullable(baseSchema); + } + if (schema2.readOnly === true) { + baseSchema = z2.readonly(baseSchema); + } + const extraMeta = {}; + const coreMetadataKeys = ["$id", "id", "$comment", "$anchor", "$vocabulary", "$dynamicRef", "$dynamicAnchor"]; + for (const key of coreMetadataKeys) { + if (key in schema2) { + extraMeta[key] = schema2[key]; + } + } + const contentMetadataKeys = ["contentEncoding", "contentMediaType", "contentSchema"]; + for (const key of contentMetadataKeys) { + if (key in schema2) { + extraMeta[key] = schema2[key]; + } + } + for (const key of Object.keys(schema2)) { + if (!RECOGNIZED_KEYS.has(key)) { + extraMeta[key] = schema2[key]; + } + } + if (Object.keys(extraMeta).length > 0) { + ctx.registry.add(baseSchema, extraMeta); + } + return baseSchema; +} +function fromJSONSchema(schema2, params) { + if (typeof schema2 === "boolean") { + return schema2 ? z2.any() : z2.never(); + } + const version3 = detectVersion(schema2, params?.defaultTarget); + const defs = schema2.$defs || schema2.definitions || {}; + const ctx = { + version: version3, + defs, + refs: /* @__PURE__ */ new Map(), + processing: /* @__PURE__ */ new Set(), + rootSchema: schema2, + registry: params?.registry ?? globalRegistry + }; + return convertSchema(schema2, ctx); +} +var z2, RECOGNIZED_KEYS; +var init_from_json_schema = __esm({ + "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/from-json-schema.js"() { + init_registries(); + init_checks3(); + init_iso(); + init_schemas2(); + z2 = { + ...schemas_exports2, + ...checks_exports2, + iso: iso_exports + }; + RECOGNIZED_KEYS = /* @__PURE__ */ new Set([ + // Schema identification + "$schema", + "$ref", + "$defs", + "definitions", + // Core schema keywords + "$id", + "id", + "$comment", + "$anchor", + "$vocabulary", + "$dynamicRef", + "$dynamicAnchor", + // Type + "type", + "enum", + "const", + // Composition + "anyOf", + "oneOf", + "allOf", + "not", + // Object + "properties", + "required", + "additionalProperties", + "patternProperties", + "propertyNames", + "minProperties", + "maxProperties", + // Array + "items", + "prefixItems", + "additionalItems", + "minItems", + "maxItems", + "uniqueItems", + "contains", + "minContains", + "maxContains", + // String + "minLength", + "maxLength", + "pattern", + "format", + // Number + "minimum", + "maximum", + "exclusiveMinimum", + "exclusiveMaximum", + "multipleOf", + // Already handled metadata + "description", + "default", + // Content + "contentEncoding", + "contentMediaType", + "contentSchema", + // Unsupported (error-throwing) + "unevaluatedItems", + "unevaluatedProperties", + "if", + "then", + "else", + "dependentSchemas", + "dependentRequired", + // OpenAPI + "nullable", + "readOnly" + ]); + } +}); + +// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/coerce.js +var coerce_exports = {}; +__export(coerce_exports, { + bigint: () => bigint4, + boolean: () => boolean4, + date: () => date6, + number: () => number3, + string: () => string3 +}); +function string3(params) { + return _coercedString(ZodString2, params); +} +function number3(params) { + return _coercedNumber(ZodNumber2, params); +} +function boolean4(params) { + return _coercedBoolean(ZodBoolean2, params); +} +function bigint4(params) { + return _coercedBigint(ZodBigInt2, params); +} +function date6(params) { + return _coercedDate(ZodDate2, params); +} +var init_coerce = __esm({ + "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/coerce.js"() { + init_core2(); + init_schemas2(); + } +}); + +// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/external.js +var external_exports2 = {}; +__export(external_exports2, { + $brand: () => $brand, + $input: () => $input, + $output: () => $output, + NEVER: () => NEVER2, + TimePrecision: () => TimePrecision, + ZodAny: () => ZodAny2, + ZodArray: () => ZodArray2, + ZodBase64: () => ZodBase64, + ZodBase64URL: () => ZodBase64URL, + ZodBigInt: () => ZodBigInt2, + ZodBigIntFormat: () => ZodBigIntFormat, + ZodBoolean: () => ZodBoolean2, + ZodCIDRv4: () => ZodCIDRv4, + ZodCIDRv6: () => ZodCIDRv6, + ZodCUID: () => ZodCUID, + ZodCUID2: () => ZodCUID2, + ZodCatch: () => ZodCatch2, + ZodCodec: () => ZodCodec, + ZodCustom: () => ZodCustom, + ZodCustomStringFormat: () => ZodCustomStringFormat, + ZodDate: () => ZodDate2, + ZodDefault: () => ZodDefault2, + ZodDiscriminatedUnion: () => ZodDiscriminatedUnion2, + ZodE164: () => ZodE164, + ZodEmail: () => ZodEmail, + ZodEmoji: () => ZodEmoji, + ZodEnum: () => ZodEnum2, + ZodError: () => ZodError2, + ZodExactOptional: () => ZodExactOptional, + ZodFile: () => ZodFile, + ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind2, + ZodFunction: () => ZodFunction2, + ZodGUID: () => ZodGUID, + ZodIPv4: () => ZodIPv4, + ZodIPv6: () => ZodIPv6, + ZodISODate: () => ZodISODate, + ZodISODateTime: () => ZodISODateTime, + ZodISODuration: () => ZodISODuration, + ZodISOTime: () => ZodISOTime, + ZodIntersection: () => ZodIntersection2, + ZodIssueCode: () => ZodIssueCode2, + ZodJWT: () => ZodJWT, + ZodKSUID: () => ZodKSUID, + ZodLazy: () => ZodLazy2, + ZodLiteral: () => ZodLiteral2, + ZodMAC: () => ZodMAC, + ZodMap: () => ZodMap2, + ZodNaN: () => ZodNaN2, + ZodNanoID: () => ZodNanoID, + ZodNever: () => ZodNever2, + ZodNonOptional: () => ZodNonOptional, + ZodNull: () => ZodNull2, + ZodNullable: () => ZodNullable2, + ZodNumber: () => ZodNumber2, + ZodNumberFormat: () => ZodNumberFormat, + ZodObject: () => ZodObject2, + ZodOptional: () => ZodOptional2, + ZodPipe: () => ZodPipe, + ZodPrefault: () => ZodPrefault, + ZodPromise: () => ZodPromise2, + ZodReadonly: () => ZodReadonly2, + ZodRealError: () => ZodRealError, + ZodRecord: () => ZodRecord2, + ZodSet: () => ZodSet2, + ZodString: () => ZodString2, + ZodStringFormat: () => ZodStringFormat, + ZodSuccess: () => ZodSuccess, + ZodSymbol: () => ZodSymbol2, + ZodTemplateLiteral: () => ZodTemplateLiteral, + ZodTransform: () => ZodTransform, + ZodTuple: () => ZodTuple2, + ZodType: () => ZodType2, + ZodULID: () => ZodULID, + ZodURL: () => ZodURL, + ZodUUID: () => ZodUUID, + ZodUndefined: () => ZodUndefined2, + ZodUnion: () => ZodUnion2, + ZodUnknown: () => ZodUnknown2, + ZodVoid: () => ZodVoid2, + ZodXID: () => ZodXID, + ZodXor: () => ZodXor, + _ZodString: () => _ZodString, + _default: () => _default2, + _function: () => _function, + any: () => any, + array: () => array, + base64: () => base642, + base64url: () => base64url2, + bigint: () => bigint3, + boolean: () => boolean3, + catch: () => _catch2, + check: () => check2, + cidrv4: () => cidrv42, + cidrv6: () => cidrv62, + clone: () => clone2, + codec: () => codec, + coerce: () => coerce_exports, + config: () => config, + core: () => core_exports2, + cuid: () => cuid3, + cuid2: () => cuid22, + custom: () => custom2, + date: () => date5, + decode: () => decode4, + decodeAsync: () => decodeAsync2, + describe: () => describe2, + discriminatedUnion: () => discriminatedUnion, + e164: () => e1642, + email: () => email2, + emoji: () => emoji2, + encode: () => encode5, + encodeAsync: () => encodeAsync2, + endsWith: () => _endsWith, + enum: () => _enum2, + exactOptional: () => exactOptional, + file: () => file, + flattenError: () => flattenError, + float32: () => float32, + float64: () => float64, + formatError: () => formatError, + fromJSONSchema: () => fromJSONSchema, + function: () => _function, + getErrorMap: () => getErrorMap2, + globalRegistry: () => globalRegistry, + gt: () => _gt, + gte: () => _gte, + guid: () => guid2, + hash: () => hash, + hex: () => hex2, + hostname: () => hostname2, + httpUrl: () => httpUrl, + includes: () => _includes, + instanceof: () => _instanceof, + int: () => int, + int32: () => int32, + int64: () => int64, + intersection: () => intersection, + ipv4: () => ipv42, + ipv6: () => ipv62, + iso: () => iso_exports, + json: () => json2, + jwt: () => jwt, + keyof: () => keyof, + ksuid: () => ksuid2, + lazy: () => lazy, + length: () => _length, + literal: () => literal, + locales: () => locales_exports, + looseObject: () => looseObject, + looseRecord: () => looseRecord, + lowercase: () => _lowercase, + lt: () => _lt, + lte: () => _lte, + mac: () => mac2, + map: () => map2, + maxLength: () => _maxLength, + maxSize: () => _maxSize, + meta: () => meta2, + mime: () => _mime, + minLength: () => _minLength, + minSize: () => _minSize, + multipleOf: () => _multipleOf, + nan: () => nan, + nanoid: () => nanoid2, + nativeEnum: () => nativeEnum, + negative: () => _negative, + never: () => never, + nonnegative: () => _nonnegative, + nonoptional: () => nonoptional, + nonpositive: () => _nonpositive, + normalize: () => _normalize, + null: () => _null3, + nullable: () => nullable, + nullish: () => nullish2, + number: () => number2, + object: () => object, + optional: () => optional, + overwrite: () => _overwrite, + parse: () => parse3, + parseAsync: () => parseAsync2, + partialRecord: () => partialRecord, + pipe: () => pipe, + positive: () => _positive, + prefault: () => prefault, + preprocess: () => preprocess, + prettifyError: () => prettifyError, + promise: () => promise, + property: () => _property, + readonly: () => readonly, + record: () => record, + refine: () => refine, + regex: () => _regex, + regexes: () => regexes_exports, + registry: () => registry, + safeDecode: () => safeDecode2, + safeDecodeAsync: () => safeDecodeAsync2, + safeEncode: () => safeEncode2, + safeEncodeAsync: () => safeEncodeAsync2, + safeParse: () => safeParse2, + safeParseAsync: () => safeParseAsync2, + set: () => set, + setErrorMap: () => setErrorMap2, + size: () => _size, + slugify: () => _slugify, + startsWith: () => _startsWith, + strictObject: () => strictObject, + string: () => string2, + stringFormat: () => stringFormat, + stringbool: () => stringbool, + success: () => success, + superRefine: () => superRefine, + symbol: () => symbol, + templateLiteral: () => templateLiteral, + toJSONSchema: () => toJSONSchema, + toLowerCase: () => _toLowerCase, + toUpperCase: () => _toUpperCase, + transform: () => transform, + treeifyError: () => treeifyError, + trim: () => _trim, + tuple: () => tuple, + uint32: () => uint32, + uint64: () => uint64, + ulid: () => ulid2, + undefined: () => _undefined3, + union: () => union2, + unknown: () => unknown, + uppercase: () => _uppercase, + url: () => url, + util: () => util_exports, + uuid: () => uuid3, + uuidv4: () => uuidv4, + uuidv6: () => uuidv6, + uuidv7: () => uuidv7, + void: () => _void2, + xid: () => xid2, + xor: () => xor2 +}); +var init_external = __esm({ + "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/external.js"() { + init_core2(); + init_schemas2(); + init_checks3(); + init_errors9(); + init_parse2(); + init_compat(); + init_core2(); + init_en(); + init_core2(); + init_json_schema_processors(); + init_from_json_schema(); + init_locales(); + init_iso(); + init_iso(); + init_coerce(); + config(en_default2()); + } +}); + +// node_modules/.pnpm/zod@4.3.6/node_modules/zod/index.js +var zod_exports = {}; +__export(zod_exports, { + $brand: () => $brand, + $input: () => $input, + $output: () => $output, + NEVER: () => NEVER2, + TimePrecision: () => TimePrecision, + ZodAny: () => ZodAny2, + ZodArray: () => ZodArray2, + ZodBase64: () => ZodBase64, + ZodBase64URL: () => ZodBase64URL, + ZodBigInt: () => ZodBigInt2, + ZodBigIntFormat: () => ZodBigIntFormat, + ZodBoolean: () => ZodBoolean2, + ZodCIDRv4: () => ZodCIDRv4, + ZodCIDRv6: () => ZodCIDRv6, + ZodCUID: () => ZodCUID, + ZodCUID2: () => ZodCUID2, + ZodCatch: () => ZodCatch2, + ZodCodec: () => ZodCodec, + ZodCustom: () => ZodCustom, + ZodCustomStringFormat: () => ZodCustomStringFormat, + ZodDate: () => ZodDate2, + ZodDefault: () => ZodDefault2, + ZodDiscriminatedUnion: () => ZodDiscriminatedUnion2, + ZodE164: () => ZodE164, + ZodEmail: () => ZodEmail, + ZodEmoji: () => ZodEmoji, + ZodEnum: () => ZodEnum2, + ZodError: () => ZodError2, + ZodExactOptional: () => ZodExactOptional, + ZodFile: () => ZodFile, + ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind2, + ZodFunction: () => ZodFunction2, + ZodGUID: () => ZodGUID, + ZodIPv4: () => ZodIPv4, + ZodIPv6: () => ZodIPv6, + ZodISODate: () => ZodISODate, + ZodISODateTime: () => ZodISODateTime, + ZodISODuration: () => ZodISODuration, + ZodISOTime: () => ZodISOTime, + ZodIntersection: () => ZodIntersection2, + ZodIssueCode: () => ZodIssueCode2, + ZodJWT: () => ZodJWT, + ZodKSUID: () => ZodKSUID, + ZodLazy: () => ZodLazy2, + ZodLiteral: () => ZodLiteral2, + ZodMAC: () => ZodMAC, + ZodMap: () => ZodMap2, + ZodNaN: () => ZodNaN2, + ZodNanoID: () => ZodNanoID, + ZodNever: () => ZodNever2, + ZodNonOptional: () => ZodNonOptional, + ZodNull: () => ZodNull2, + ZodNullable: () => ZodNullable2, + ZodNumber: () => ZodNumber2, + ZodNumberFormat: () => ZodNumberFormat, + ZodObject: () => ZodObject2, + ZodOptional: () => ZodOptional2, + ZodPipe: () => ZodPipe, + ZodPrefault: () => ZodPrefault, + ZodPromise: () => ZodPromise2, + ZodReadonly: () => ZodReadonly2, + ZodRealError: () => ZodRealError, + ZodRecord: () => ZodRecord2, + ZodSet: () => ZodSet2, + ZodString: () => ZodString2, + ZodStringFormat: () => ZodStringFormat, + ZodSuccess: () => ZodSuccess, + ZodSymbol: () => ZodSymbol2, + ZodTemplateLiteral: () => ZodTemplateLiteral, + ZodTransform: () => ZodTransform, + ZodTuple: () => ZodTuple2, + ZodType: () => ZodType2, + ZodULID: () => ZodULID, + ZodURL: () => ZodURL, + ZodUUID: () => ZodUUID, + ZodUndefined: () => ZodUndefined2, + ZodUnion: () => ZodUnion2, + ZodUnknown: () => ZodUnknown2, + ZodVoid: () => ZodVoid2, + ZodXID: () => ZodXID, + ZodXor: () => ZodXor, + _ZodString: () => _ZodString, + _default: () => _default2, + _function: () => _function, + any: () => any, + array: () => array, + base64: () => base642, + base64url: () => base64url2, + bigint: () => bigint3, + boolean: () => boolean3, + catch: () => _catch2, + check: () => check2, + cidrv4: () => cidrv42, + cidrv6: () => cidrv62, + clone: () => clone2, + codec: () => codec, + coerce: () => coerce_exports, + config: () => config, + core: () => core_exports2, + cuid: () => cuid3, + cuid2: () => cuid22, + custom: () => custom2, + date: () => date5, + decode: () => decode4, + decodeAsync: () => decodeAsync2, + default: () => zod_default, + describe: () => describe2, + discriminatedUnion: () => discriminatedUnion, + e164: () => e1642, + email: () => email2, + emoji: () => emoji2, + encode: () => encode5, + encodeAsync: () => encodeAsync2, + endsWith: () => _endsWith, + enum: () => _enum2, + exactOptional: () => exactOptional, + file: () => file, + flattenError: () => flattenError, + float32: () => float32, + float64: () => float64, + formatError: () => formatError, + fromJSONSchema: () => fromJSONSchema, + function: () => _function, + getErrorMap: () => getErrorMap2, + globalRegistry: () => globalRegistry, + gt: () => _gt, + gte: () => _gte, + guid: () => guid2, + hash: () => hash, + hex: () => hex2, + hostname: () => hostname2, + httpUrl: () => httpUrl, + includes: () => _includes, + instanceof: () => _instanceof, + int: () => int, + int32: () => int32, + int64: () => int64, + intersection: () => intersection, + ipv4: () => ipv42, + ipv6: () => ipv62, + iso: () => iso_exports, + json: () => json2, + jwt: () => jwt, + keyof: () => keyof, + ksuid: () => ksuid2, + lazy: () => lazy, + length: () => _length, + literal: () => literal, + locales: () => locales_exports, + looseObject: () => looseObject, + looseRecord: () => looseRecord, + lowercase: () => _lowercase, + lt: () => _lt, + lte: () => _lte, + mac: () => mac2, + map: () => map2, + maxLength: () => _maxLength, + maxSize: () => _maxSize, + meta: () => meta2, + mime: () => _mime, + minLength: () => _minLength, + minSize: () => _minSize, + multipleOf: () => _multipleOf, + nan: () => nan, + nanoid: () => nanoid2, + nativeEnum: () => nativeEnum, + negative: () => _negative, + never: () => never, + nonnegative: () => _nonnegative, + nonoptional: () => nonoptional, + nonpositive: () => _nonpositive, + normalize: () => _normalize, + null: () => _null3, + nullable: () => nullable, + nullish: () => nullish2, + number: () => number2, + object: () => object, + optional: () => optional, + overwrite: () => _overwrite, + parse: () => parse3, + parseAsync: () => parseAsync2, + partialRecord: () => partialRecord, + pipe: () => pipe, + positive: () => _positive, + prefault: () => prefault, + preprocess: () => preprocess, + prettifyError: () => prettifyError, + promise: () => promise, + property: () => _property, + readonly: () => readonly, + record: () => record, + refine: () => refine, + regex: () => _regex, + regexes: () => regexes_exports, + registry: () => registry, + safeDecode: () => safeDecode2, + safeDecodeAsync: () => safeDecodeAsync2, + safeEncode: () => safeEncode2, + safeEncodeAsync: () => safeEncodeAsync2, + safeParse: () => safeParse2, + safeParseAsync: () => safeParseAsync2, + set: () => set, + setErrorMap: () => setErrorMap2, + size: () => _size, + slugify: () => _slugify, + startsWith: () => _startsWith, + strictObject: () => strictObject, + string: () => string2, + stringFormat: () => stringFormat, + stringbool: () => stringbool, + success: () => success, + superRefine: () => superRefine, + symbol: () => symbol, + templateLiteral: () => templateLiteral, + toJSONSchema: () => toJSONSchema, + toLowerCase: () => _toLowerCase, + toUpperCase: () => _toUpperCase, + transform: () => transform, + treeifyError: () => treeifyError, + trim: () => _trim, + tuple: () => tuple, + uint32: () => uint32, + uint64: () => uint64, + ulid: () => ulid2, + undefined: () => _undefined3, + union: () => union2, + unknown: () => unknown, + uppercase: () => _uppercase, + url: () => url, + util: () => util_exports, + uuid: () => uuid3, + uuidv4: () => uuidv4, + uuidv6: () => uuidv6, + uuidv7: () => uuidv7, + void: () => _void2, + xid: () => xid2, + xor: () => xor2, + z: () => external_exports2 +}); +var zod_default; +var init_zod = __esm({ + "node_modules/.pnpm/zod@4.3.6/node_modules/zod/index.js"() { + init_external(); + init_external(); + zod_default = external_exports2; + } +}); + +// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/utils/ip.mjs +function isValidIP2(ip) { + return ipv42().safeParse(ip).success || ipv62().safeParse(ip).success; +} +function isIPv6(ip) { + return ipv62().safeParse(ip).success; +} +function extractIPv4FromMapped(ipv63) { + const lower = ipv63.toLowerCase(); + if (lower.startsWith("::ffff:")) { + const ipv4Part = lower.substring(7); + if (ipv42().safeParse(ipv4Part).success) return ipv4Part; + } + const parts = ipv63.split(":"); + if (parts.length === 7 && parts[5]?.toLowerCase() === "ffff") { + const ipv4Part = parts[6]; + if (ipv4Part && ipv42().safeParse(ipv4Part).success) return ipv4Part; + } + if (lower.includes("::ffff:") || lower.includes(":ffff:")) { + const groups = expandIPv6(ipv63); + if (groups.length === 8 && groups[0] === "0000" && groups[1] === "0000" && groups[2] === "0000" && groups[3] === "0000" && groups[4] === "0000" && groups[5] === "ffff" && groups[6] && groups[7]) return `${Number.parseInt(groups[6].substring(0, 2), 16)}.${Number.parseInt(groups[6].substring(2, 4), 16)}.${Number.parseInt(groups[7].substring(0, 2), 16)}.${Number.parseInt(groups[7].substring(2, 4), 16)}`; + } + return null; +} +function expandIPv6(ipv63) { + if (ipv63.includes("::")) { + const sides = ipv63.split("::"); + const left = sides[0] ? sides[0].split(":") : []; + const right = sides[1] ? sides[1].split(":") : []; + const missingGroups = 8 - left.length - right.length; + const zeros = Array(missingGroups).fill("0000"); + const paddedLeft = left.map((g5) => g5.padStart(4, "0")); + const paddedRight = right.map((g5) => g5.padStart(4, "0")); + return [ + ...paddedLeft, + ...zeros, + ...paddedRight + ]; + } + return ipv63.split(":").map((g5) => g5.padStart(4, "0")); +} +function normalizeIPv6(ipv63, subnetPrefix) { + const groups = expandIPv6(ipv63); + if (subnetPrefix && subnetPrefix < 128) { + let bitsRemaining = subnetPrefix; + return groups.map((group) => { + if (bitsRemaining <= 0) return "0000"; + if (bitsRemaining >= 16) { + bitsRemaining -= 16; + return group; + } + const masked = Number.parseInt(group, 16) & (65535 << 16 - bitsRemaining & 65535); + bitsRemaining = 0; + return masked.toString(16).padStart(4, "0"); + }).join(":").toLowerCase(); + } + return groups.join(":").toLowerCase(); +} +function normalizeIP(ip, options = {}) { + if (ipv42().safeParse(ip).success) return ip.toLowerCase(); + if (!isIPv6(ip)) return ip.toLowerCase(); + const ipv43 = extractIPv4FromMapped(ip); + if (ipv43) return ipv43.toLowerCase(); + return normalizeIPv6(ip, options.ipv6Subnet || 64); +} +function createRateLimitKey(ip, path53) { + return `${ip}|${path53}`; +} +var init_ip = __esm({ + "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/utils/ip.mjs"() { + init_zod(); + } +}); + +// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/env/env-impl.mjs +function toBoolean(val) { + return val ? val !== "false" : false; +} +function getEnvVar(key, fallback) { + if (typeof process !== "undefined" && process.env) return process.env[key] ?? fallback; + if (typeof Deno !== "undefined") return Deno.env.get(key) ?? fallback; + if (typeof Bun !== "undefined") return Bun.env[key] ?? fallback; + return fallback; +} +function getBooleanEnvVar(key, fallback = true) { + const value = getEnvVar(key); + if (!value) return fallback; + return value !== "0" && value.toLowerCase() !== "false" && value !== ""; +} +var _envShim, _getEnv, env, nodeENV, isProduction, isDevelopment, isTest, ENV; +var init_env_impl = __esm({ + "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/env/env-impl.mjs"() { + _envShim = /* @__PURE__ */ Object.create(null); + _getEnv = (useShim) => globalThis.process?.env || globalThis.Deno?.env.toObject() || globalThis.__env__ || (useShim ? _envShim : globalThis); + env = new Proxy(_envShim, { + get(_, prop) { + return _getEnv()[prop] ?? _envShim[prop]; + }, + has(_, prop) { + return prop in _getEnv() || prop in _envShim; + }, + set(_, prop, value) { + const env$1 = _getEnv(true); + env$1[prop] = value; + return true; + }, + deleteProperty(_, prop) { + if (!prop) return false; + const env$1 = _getEnv(true); + delete env$1[prop]; + return true; + }, + ownKeys() { + const env$1 = _getEnv(true); + return Object.keys(env$1); + } + }); + nodeENV = typeof process !== "undefined" && process.env && "production" || ""; + isProduction = nodeENV === "production"; + isDevelopment = () => nodeENV === "dev" || nodeENV === "development"; + isTest = () => nodeENV === "test" || toBoolean(env.TEST); + ENV = Object.freeze({ + get BETTER_AUTH_SECRET() { + return getEnvVar("BETTER_AUTH_SECRET"); + }, + get AUTH_SECRET() { + return getEnvVar("AUTH_SECRET"); + }, + get BETTER_AUTH_TELEMETRY() { + return getEnvVar("BETTER_AUTH_TELEMETRY"); + }, + get BETTER_AUTH_TELEMETRY_ID() { + return getEnvVar("BETTER_AUTH_TELEMETRY_ID"); + }, + get NODE_ENV() { + return getEnvVar("NODE_ENV", "development"); + }, + get PACKAGE_VERSION() { + return getEnvVar("PACKAGE_VERSION", "0.0.0"); + }, + get BETTER_AUTH_TELEMETRY_ENDPOINT() { + return getEnvVar("BETTER_AUTH_TELEMETRY_ENDPOINT", ""); + } + }); + } +}); + +// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/env/color-depth.mjs +function getColorDepth() { + if (getEnvVar("FORCE_COLOR") !== void 0) switch (getEnvVar("FORCE_COLOR")) { + case "": + case "1": + case "true": + return COLORS_16; + case "2": + return COLORS_256; + case "3": + return COLORS_16m; + default: + return COLORS_2; + } + if (getEnvVar("NODE_DISABLE_COLORS") !== void 0 && getEnvVar("NODE_DISABLE_COLORS") !== "" || getEnvVar("NO_COLOR") !== void 0 && getEnvVar("NO_COLOR") !== "" || getEnvVar("TERM") === "dumb") return COLORS_2; + if (getEnvVar("TMUX")) return COLORS_16m; + if ("TF_BUILD" in env && "AGENT_NAME" in env) return COLORS_16; + if ("CI" in env) { + for (const { 0: envName, 1: colors } of CI_ENVS_MAP) if (envName in env) return colors; + if (getEnvVar("CI_NAME") === "codeship") return COLORS_256; + return COLORS_2; + } + if ("TEAMCITY_VERSION" in env) return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.exec(getEnvVar("TEAMCITY_VERSION")) !== null ? COLORS_16 : COLORS_2; + switch (getEnvVar("TERM_PROGRAM")) { + case "iTerm.app": + if (!getEnvVar("TERM_PROGRAM_VERSION") || /^[0-2]\./.exec(getEnvVar("TERM_PROGRAM_VERSION")) !== null) return COLORS_256; + return COLORS_16m; + case "HyperTerm": + case "MacTerm": + return COLORS_16m; + case "Apple_Terminal": + return COLORS_256; + } + if (getEnvVar("COLORTERM") === "truecolor" || getEnvVar("COLORTERM") === "24bit") return COLORS_16m; + if (getEnvVar("TERM")) { + if (/truecolor/.exec(getEnvVar("TERM")) !== null) return COLORS_16m; + if (/^xterm-256/.exec(getEnvVar("TERM")) !== null) return COLORS_256; + const termEnv = getEnvVar("TERM").toLowerCase(); + if (TERM_ENVS[termEnv]) return TERM_ENVS[termEnv]; + if (TERM_ENVS_REG_EXP.some((term) => term.exec(termEnv) !== null)) return COLORS_16; + } + if (getEnvVar("COLORTERM")) return COLORS_16; + return COLORS_2; +} +var COLORS_2, COLORS_16, COLORS_256, COLORS_16m, TERM_ENVS, CI_ENVS_MAP, TERM_ENVS_REG_EXP; +var init_color_depth = __esm({ + "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/env/color-depth.mjs"() { + init_env_impl(); + COLORS_2 = 1; + COLORS_16 = 4; + COLORS_256 = 8; + COLORS_16m = 24; + TERM_ENVS = { + eterm: COLORS_16, + cons25: COLORS_16, + console: COLORS_16, + cygwin: COLORS_16, + dtterm: COLORS_16, + gnome: COLORS_16, + hurd: COLORS_16, + jfbterm: COLORS_16, + konsole: COLORS_16, + kterm: COLORS_16, + mlterm: COLORS_16, + mosh: COLORS_16m, + putty: COLORS_16, + st: COLORS_16, + "rxvt-unicode-24bit": COLORS_16m, + terminator: COLORS_16m, + "xterm-kitty": COLORS_16m + }; + CI_ENVS_MAP = new Map(Object.entries({ + APPVEYOR: COLORS_256, + BUILDKITE: COLORS_256, + CIRCLECI: COLORS_16m, + DRONE: COLORS_256, + GITEA_ACTIONS: COLORS_16m, + GITHUB_ACTIONS: COLORS_16m, + GITLAB_CI: COLORS_256, + TRAVIS: COLORS_256 + })); + TERM_ENVS_REG_EXP = [ + /ansi/, + /color/, + /linux/, + /direct/, + /^con[0-9]*x[0-9]/, + /^rxvt/, + /^screen/, + /^xterm/, + /^vt100/, + /^vt220/ + ]; + } +}); + +// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/env/logger.mjs +function shouldPublishLog(currentLogLevel, logLevel) { + return levels.indexOf(logLevel) >= levels.indexOf(currentLogLevel); +} +var TTY_COLORS, levels, levelColors, formatMessage, createLogger, logger3; +var init_logger2 = __esm({ + "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/env/logger.mjs"() { + init_color_depth(); + TTY_COLORS = { + reset: "\x1B[0m", + bright: "\x1B[1m", + dim: "\x1B[2m", + undim: "\x1B[22m", + underscore: "\x1B[4m", + blink: "\x1B[5m", + reverse: "\x1B[7m", + hidden: "\x1B[8m", + fg: { + black: "\x1B[30m", + red: "\x1B[31m", + green: "\x1B[32m", + yellow: "\x1B[33m", + blue: "\x1B[34m", + magenta: "\x1B[35m", + cyan: "\x1B[36m", + white: "\x1B[37m" + }, + bg: { + black: "\x1B[40m", + red: "\x1B[41m", + green: "\x1B[42m", + yellow: "\x1B[43m", + blue: "\x1B[44m", + magenta: "\x1B[45m", + cyan: "\x1B[46m", + white: "\x1B[47m" + } + }; + levels = [ + "debug", + "info", + "success", + "warn", + "error" + ]; + levelColors = { + info: TTY_COLORS.fg.blue, + success: TTY_COLORS.fg.green, + warn: TTY_COLORS.fg.yellow, + error: TTY_COLORS.fg.red, + debug: TTY_COLORS.fg.magenta + }; + formatMessage = (level, message2, colorsEnabled) => { + const timestamp2 = (/* @__PURE__ */ new Date()).toISOString(); + if (colorsEnabled) return `${TTY_COLORS.dim}${timestamp2}${TTY_COLORS.reset} ${levelColors[level]}${level.toUpperCase()}${TTY_COLORS.reset} ${TTY_COLORS.bright}[Better Auth]:${TTY_COLORS.reset} ${message2}`; + return `${timestamp2} ${level.toUpperCase()} [Better Auth]: ${message2}`; + }; + createLogger = (options) => { + const enabled = options?.disabled !== true; + const logLevel = options?.level ?? "warn"; + const colorsEnabled = options?.disableColors !== void 0 ? !options.disableColors : getColorDepth() !== 1; + const LogFunc = (level, message2, args = []) => { + if (!enabled || !shouldPublishLog(logLevel, level)) return; + const formattedMessage = formatMessage(level, message2, colorsEnabled); + if (!options || typeof options.log !== "function") { + if (level === "error") console.error(formattedMessage, ...args); + else if (level === "warn") console.warn(formattedMessage, ...args); + else console.log(formattedMessage, ...args); + return; + } + options.log(level === "success" ? "info" : level, message2, ...args); + }; + return { + ...Object.fromEntries(levels.map((level) => [level, (...[message2, ...args]) => LogFunc(level, message2, args)])), + get level() { + return logLevel; + } + }; + }; + logger3 = createLogger(); + } +}); + +// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/env/index.mjs +var init_env = __esm({ + "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/env/index.mjs"() { + init_env_impl(); + init_color_depth(); + init_logger2(); + } +}); + +// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/utils/json.mjs +function safeJSONParse(data2) { + function reviver(_, value) { + if (typeof value === "string") { + if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/.test(value)) { + const date7 = new Date(value); + if (!isNaN(date7.getTime())) return date7; + } + } + return value; + } + try { + if (typeof data2 !== "string") return data2; + return JSON.parse(data2, reviver); + } catch (e5) { + logger3.error("Error parsing JSON", { error: e5 }); + return null; + } +} +var init_json2 = __esm({ + "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/utils/json.mjs"() { + init_logger2(); + init_env(); + } +}); + +// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/utils/string.mjs +var init_string = __esm({ + "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/utils/string.mjs"() { + } +}); + +// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/utils/url.mjs +function normalizePathname(requestUrl, basePath) { + let pathname; + try { + pathname = new URL(requestUrl).pathname.replace(/\/+$/, "") || "/"; + } catch { + return "/"; + } + if (basePath === "/" || basePath === "") return pathname; + if (pathname === basePath) return "/"; + if (pathname.startsWith(basePath + "/")) return pathname.slice(basePath.length).replace(/\/+$/, "") || "/"; + return pathname; +} +var init_url = __esm({ + "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/utils/url.mjs"() { + } +}); + +// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/utils/index.mjs +var init_utils7 = __esm({ + "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/utils/index.mjs"() { + init_db2(); + init_deprecate(); + init_error_codes(); + init_id(); + init_ip(); + init_json2(); + init_string(); + init_url(); + } +}); + +// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/error/codes.mjs +var BASE_ERROR_CODES; +var init_codes = __esm({ + "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/error/codes.mjs"() { + init_error_codes(); + init_utils7(); + BASE_ERROR_CODES = defineErrorCodes({ + USER_NOT_FOUND: "User not found", + FAILED_TO_CREATE_USER: "Failed to create user", + FAILED_TO_CREATE_SESSION: "Failed to create session", + FAILED_TO_UPDATE_USER: "Failed to update user", + FAILED_TO_GET_SESSION: "Failed to get session", + INVALID_PASSWORD: "Invalid password", + INVALID_EMAIL: "Invalid email", + INVALID_EMAIL_OR_PASSWORD: "Invalid email or password", + SOCIAL_ACCOUNT_ALREADY_LINKED: "Social account already linked", + PROVIDER_NOT_FOUND: "Provider not found", + INVALID_TOKEN: "Invalid token", + ID_TOKEN_NOT_SUPPORTED: "id_token not supported", + FAILED_TO_GET_USER_INFO: "Failed to get user info", + USER_EMAIL_NOT_FOUND: "User email not found", + EMAIL_NOT_VERIFIED: "Email not verified", + PASSWORD_TOO_SHORT: "Password too short", + PASSWORD_TOO_LONG: "Password too long", + USER_ALREADY_EXISTS: "User already exists.", + USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL: "User already exists. Use another email.", + EMAIL_CAN_NOT_BE_UPDATED: "Email can not be updated", + CREDENTIAL_ACCOUNT_NOT_FOUND: "Credential account not found", + SESSION_EXPIRED: "Session expired. Re-authenticate to perform this action.", + FAILED_TO_UNLINK_LAST_ACCOUNT: "You can't unlink your last account", + ACCOUNT_NOT_FOUND: "Account not found", + USER_ALREADY_HAS_PASSWORD: "User already has a password. Provide that to delete the account.", + CROSS_SITE_NAVIGATION_LOGIN_BLOCKED: "Cross-site navigation login blocked. This request appears to be a CSRF attack.", + VERIFICATION_EMAIL_NOT_ENABLED: "Verification email isn't enabled", + EMAIL_ALREADY_VERIFIED: "Email is already verified", + EMAIL_MISMATCH: "Email mismatch", + SESSION_NOT_FRESH: "Session is not fresh", + LINKED_ACCOUNT_ALREADY_EXISTS: "Linked account already exists", + INVALID_ORIGIN: "Invalid origin", + INVALID_CALLBACK_URL: "Invalid callbackURL", + INVALID_REDIRECT_URL: "Invalid redirectURL", + INVALID_ERROR_CALLBACK_URL: "Invalid errorCallbackURL", + INVALID_NEW_USER_CALLBACK_URL: "Invalid newUserCallbackURL", + MISSING_OR_NULL_ORIGIN: "Missing or null Origin", + CALLBACK_URL_REQUIRED: "callbackURL is required", + FAILED_TO_CREATE_VERIFICATION: "Unable to create verification", + FIELD_NOT_ALLOWED: "Field not allowed to be set", + ASYNC_VALIDATION_NOT_SUPPORTED: "Async validation is not supported", + VALIDATION_ERROR: "Validation Error", + MISSING_FIELD: "Field is required" + }); + } +}); + +// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/error/index.mjs +var BetterAuthError; +var init_error = __esm({ + "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/error/index.mjs"() { + init_codes(); + BetterAuthError = class extends Error { + constructor(message2, options) { + super(message2, options); + this.name = "BetterAuthError"; + this.message = message2; + this.stack = ""; + } + }; + } +}); + +// node_modules/.pnpm/@better-auth+utils@0.3.0/node_modules/@better-auth/utils/dist/hex.mjs +var hexadecimal, hex3; +var init_hex = __esm({ + "node_modules/.pnpm/@better-auth+utils@0.3.0/node_modules/@better-auth/utils/dist/hex.mjs"() { + hexadecimal = "0123456789abcdef"; + hex3 = { + encode: (data2) => { + if (typeof data2 === "string") { + data2 = new TextEncoder().encode(data2); + } + if (data2.byteLength === 0) { + return ""; + } + const buffer2 = new Uint8Array(data2); + let result = ""; + for (const byte of buffer2) { + result += byte.toString(16).padStart(2, "0"); + } + return result; + }, + decode: (data2) => { + if (!data2) { + return ""; + } + if (typeof data2 === "string") { + if (data2.length % 2 !== 0) { + throw new Error("Invalid hexadecimal string"); + } + if (!new RegExp(`^[${hexadecimal}]+$`).test(data2)) { + throw new Error("Invalid hexadecimal string"); + } + const result = new Uint8Array(data2.length / 2); + for (let i5 = 0; i5 < data2.length; i5 += 2) { + result[i5 / 2] = parseInt(data2.slice(i5, i5 + 2), 16); + } + return new TextDecoder().decode(result); + } + return new TextDecoder().decode(data2); + } + }; + } +}); + +// node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/pbkdf2.js +function pbkdf2Init(hash2, _password, _salt, _opts) { + ahash(hash2); + const opts = checkOpts({ dkLen: 32, asyncTick: 10 }, _opts); + const { c: c5, dkLen, asyncTick } = opts; + anumber(c5, "c"); + anumber(dkLen, "dkLen"); + anumber(asyncTick, "asyncTick"); + if (c5 < 1) + throw new Error("iterations (c) must be >= 1"); + if (dkLen < 1) + throw new Error('"dkLen" must be >= 1'); + if (dkLen > (2 ** 32 - 1) * hash2.outputLen) + throw new Error("derived key too long"); + const password = kdfInputToBytes(_password, "password"); + const salt = kdfInputToBytes(_salt, "salt"); + const DK = new Uint8Array(dkLen); + const PRF = hmac2.create(hash2, password); + const PRFSalt = PRF._cloneInto().update(salt); + return { c: c5, dkLen, asyncTick, DK, PRF, PRFSalt }; +} +function pbkdf2Output(PRF, PRFSalt, DK, prfW, u5) { + PRF.destroy(); + PRFSalt.destroy(); + if (prfW) + prfW.destroy(); + clean(u5); + return DK; +} +function pbkdf2(hash2, password, salt, opts) { + const { c: c5, dkLen, DK, PRF, PRFSalt } = pbkdf2Init(hash2, password, salt, opts); + let prfW; + const arr = new Uint8Array(4); + const view = createView(arr); + const u5 = new Uint8Array(PRF.outputLen); + for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) { + const Ti = DK.subarray(pos, pos + PRF.outputLen); + view.setInt32(0, ti, false); + (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u5); + Ti.set(u5.subarray(0, Ti.length)); + for (let ui = 1; ui < c5; ui++) { + PRF._cloneInto(prfW).update(u5).digestInto(u5); + for (let i5 = 0; i5 < Ti.length; i5++) + Ti[i5] ^= u5[i5]; + } + } + return pbkdf2Output(PRF, PRFSalt, DK, prfW, u5); +} +var init_pbkdf2 = __esm({ + "node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/pbkdf2.js"() { + init_hmac(); + init_utils6(); + } +}); + +// node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/scrypt.js +function XorAndSalsa(prev, pi, input, ii, out, oi) { + let y00 = prev[pi++] ^ input[ii++], y01 = prev[pi++] ^ input[ii++]; + let y02 = prev[pi++] ^ input[ii++], y03 = prev[pi++] ^ input[ii++]; + let y04 = prev[pi++] ^ input[ii++], y05 = prev[pi++] ^ input[ii++]; + let y06 = prev[pi++] ^ input[ii++], y07 = prev[pi++] ^ input[ii++]; + let y08 = prev[pi++] ^ input[ii++], y09 = prev[pi++] ^ input[ii++]; + let y10 = prev[pi++] ^ input[ii++], y11 = prev[pi++] ^ input[ii++]; + let y12 = prev[pi++] ^ input[ii++], y13 = prev[pi++] ^ input[ii++]; + let y14 = prev[pi++] ^ input[ii++], y15 = prev[pi++] ^ input[ii++]; + let x00 = y00, x01 = y01, x02 = y02, x03 = y03, x04 = y04, x05 = y05, x06 = y06, x07 = y07, x08 = y08, x09 = y09, x10 = y10, x11 = y11, x12 = y12, x13 = y13, x14 = y14, x15 = y15; + for (let i5 = 0; i5 < 8; i5 += 2) { + x04 ^= rotl(x00 + x12 | 0, 7); + x08 ^= rotl(x04 + x00 | 0, 9); + x12 ^= rotl(x08 + x04 | 0, 13); + x00 ^= rotl(x12 + x08 | 0, 18); + x09 ^= rotl(x05 + x01 | 0, 7); + x13 ^= rotl(x09 + x05 | 0, 9); + x01 ^= rotl(x13 + x09 | 0, 13); + x05 ^= rotl(x01 + x13 | 0, 18); + x14 ^= rotl(x10 + x06 | 0, 7); + x02 ^= rotl(x14 + x10 | 0, 9); + x06 ^= rotl(x02 + x14 | 0, 13); + x10 ^= rotl(x06 + x02 | 0, 18); + x03 ^= rotl(x15 + x11 | 0, 7); + x07 ^= rotl(x03 + x15 | 0, 9); + x11 ^= rotl(x07 + x03 | 0, 13); + x15 ^= rotl(x11 + x07 | 0, 18); + x01 ^= rotl(x00 + x03 | 0, 7); + x02 ^= rotl(x01 + x00 | 0, 9); + x03 ^= rotl(x02 + x01 | 0, 13); + x00 ^= rotl(x03 + x02 | 0, 18); + x06 ^= rotl(x05 + x04 | 0, 7); + x07 ^= rotl(x06 + x05 | 0, 9); + x04 ^= rotl(x07 + x06 | 0, 13); + x05 ^= rotl(x04 + x07 | 0, 18); + x11 ^= rotl(x10 + x09 | 0, 7); + x08 ^= rotl(x11 + x10 | 0, 9); + x09 ^= rotl(x08 + x11 | 0, 13); + x10 ^= rotl(x09 + x08 | 0, 18); + x12 ^= rotl(x15 + x14 | 0, 7); + x13 ^= rotl(x12 + x15 | 0, 9); + x14 ^= rotl(x13 + x12 | 0, 13); + x15 ^= rotl(x14 + x13 | 0, 18); + } + out[oi++] = y00 + x00 | 0; + out[oi++] = y01 + x01 | 0; + out[oi++] = y02 + x02 | 0; + out[oi++] = y03 + x03 | 0; + out[oi++] = y04 + x04 | 0; + out[oi++] = y05 + x05 | 0; + out[oi++] = y06 + x06 | 0; + out[oi++] = y07 + x07 | 0; + out[oi++] = y08 + x08 | 0; + out[oi++] = y09 + x09 | 0; + out[oi++] = y10 + x10 | 0; + out[oi++] = y11 + x11 | 0; + out[oi++] = y12 + x12 | 0; + out[oi++] = y13 + x13 | 0; + out[oi++] = y14 + x14 | 0; + out[oi++] = y15 + x15 | 0; +} +function BlockMix(input, ii, out, oi, r5) { + let head = oi + 0; + let tail = oi + 16 * r5; + for (let i5 = 0; i5 < 16; i5++) + out[tail + i5] = input[ii + (2 * r5 - 1) * 16 + i5]; + for (let i5 = 0; i5 < r5; i5++, head += 16, ii += 16) { + XorAndSalsa(out, tail, input, ii, out, head); + if (i5 > 0) + tail += 16; + XorAndSalsa(out, head, input, ii += 16, out, tail); + } +} +function scryptInit(password, salt, _opts) { + const opts = checkOpts({ + dkLen: 32, + asyncTick: 10, + maxmem: 1024 ** 3 + 1024 + }, _opts); + const { N, r: r5, p: p5, dkLen, asyncTick, maxmem, onProgress } = opts; + anumber(N, "N"); + anumber(r5, "r"); + anumber(p5, "p"); + anumber(dkLen, "dkLen"); + anumber(asyncTick, "asyncTick"); + anumber(maxmem, "maxmem"); + if (onProgress !== void 0 && typeof onProgress !== "function") + throw new Error("progressCb must be a function"); + const blockSize = 128 * r5; + const blockSize32 = blockSize / 4; + const pow32 = Math.pow(2, 32); + if (N <= 1 || (N & N - 1) !== 0 || N > pow32) + throw new Error('"N" expected a power of 2, and 2^1 <= N <= 2^32'); + if (p5 < 1 || p5 > (pow32 - 1) * 32 / blockSize) + throw new Error('"p" expected integer 1..((2^32 - 1) * 32) / (128 * r)'); + if (dkLen < 1 || dkLen > (pow32 - 1) * 32) + throw new Error('"dkLen" expected integer 1..(2^32 - 1) * 32'); + const memUsed = blockSize * (N + p5 + 1); + if (memUsed > maxmem) + throw new Error('"maxmem" limit was hit: memUsed(128*r*(N+p+1))=' + memUsed + ", maxmem=" + maxmem); + const B2 = pbkdf2(sha2562, password, salt, { c: 1, dkLen: blockSize * p5 }); + const B32 = u32(B2); + const V = u32(new Uint8Array(blockSize * N)); + const tmp = u32(new Uint8Array(blockSize)); + let blockMixCb = () => { + }; + if (onProgress) { + const totalBlockMix = 2 * N * p5; + const callbackPer = Math.max(Math.floor(totalBlockMix / 1e4), 1); + let blockMixCnt = 0; + blockMixCb = () => { + blockMixCnt++; + if (onProgress && (!(blockMixCnt % callbackPer) || blockMixCnt === totalBlockMix)) + onProgress(blockMixCnt / totalBlockMix); + }; + } + return { N, r: r5, p: p5, dkLen, blockSize32, V, B32, B: B2, tmp, blockMixCb, asyncTick }; +} +function scryptOutput(password, dkLen, B2, V, tmp) { + const res = pbkdf2(sha2562, password, B2, { c: 1, dkLen }); + clean(B2, V, tmp); + return res; +} +async function scryptAsync(password, salt, opts) { + const { N, r: r5, p: p5, dkLen, blockSize32, V, B32, B: B2, tmp, blockMixCb, asyncTick } = scryptInit(password, salt, opts); + swap32IfBE(B32); + for (let pi = 0; pi < p5; pi++) { + const Pi = blockSize32 * pi; + for (let i5 = 0; i5 < blockSize32; i5++) + V[i5] = B32[Pi + i5]; + let pos = 0; + await asyncLoop(N - 1, asyncTick, () => { + BlockMix(V, pos, V, pos += blockSize32, r5); + blockMixCb(); + }); + BlockMix(V, (N - 1) * blockSize32, B32, Pi, r5); + blockMixCb(); + await asyncLoop(N, asyncTick, () => { + const j5 = (B32[Pi + blockSize32 - 16] & N - 1) >>> 0; + for (let k5 = 0; k5 < blockSize32; k5++) + tmp[k5] = B32[Pi + k5] ^ V[j5 * blockSize32 + k5]; + BlockMix(tmp, 0, B32, Pi, r5); + blockMixCb(); + }); + } + swap32IfBE(B32); + return scryptOutput(password, dkLen, B2, V, tmp); +} +var init_scrypt = __esm({ + "node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/scrypt.js"() { + init_pbkdf2(); + init_sha2(); + init_utils6(); + } +}); + +// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/crypto/password.mjs +async function generateKey(password, salt) { + return await scryptAsync(password.normalize("NFKC"), salt, { + N: config2.N, + p: config2.p, + r: config2.r, + dkLen: config2.dkLen, + maxmem: 128 * config2.N * config2.r * 2 + }); +} +var config2, hashPassword, verifyPassword; +var init_password = __esm({ + "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/crypto/password.mjs"() { + init_buffer(); + init_error(); + init_hex(); + init_scrypt(); + init_utils6(); + config2 = { + N: 16384, + r: 16, + p: 1, + dkLen: 64 + }; + hashPassword = async (password) => { + const salt = hex3.encode(crypto.getRandomValues(new Uint8Array(16))); + const key = await generateKey(password, salt); + return `${salt}:${hex3.encode(key)}`; + }; + verifyPassword = async ({ hash: hash2, password }) => { + const [salt, key] = hash2.split(":"); + if (!salt || !key) throw new BetterAuthError("Invalid password hash"); + return constantTimeEqual(await generateKey(password, salt), hexToBytes2(key)); + }; + } +}); + +// node_modules/.pnpm/@better-auth+utils@0.3.0/node_modules/@better-auth/utils/dist/index.mjs +function getWebcryptoSubtle() { + const cr = typeof globalThis !== "undefined" && globalThis.crypto; + if (cr && typeof cr.subtle === "object" && cr.subtle != null) + return cr.subtle; + throw new Error("crypto.subtle must be defined"); +} +var init_dist = __esm({ + "node_modules/.pnpm/@better-auth+utils@0.3.0/node_modules/@better-auth/utils/dist/index.mjs"() { + } +}); + +// node_modules/.pnpm/@better-auth+utils@0.3.0/node_modules/@better-auth/utils/dist/base64.mjs +function getAlphabet(urlSafe) { + return urlSafe ? "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_" : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; +} +function base64Encode(data2, alphabet, padding) { + let result = ""; + let buffer2 = 0; + let shift = 0; + for (const byte of data2) { + buffer2 = buffer2 << 8 | byte; + shift += 8; + while (shift >= 6) { + shift -= 6; + result += alphabet[buffer2 >> shift & 63]; + } + } + if (shift > 0) { + result += alphabet[buffer2 << 6 - shift & 63]; + } + if (padding) { + const padCount = (4 - result.length % 4) % 4; + result += "=".repeat(padCount); + } + return result; +} +function base64Decode(data2, alphabet) { + const decodeMap2 = /* @__PURE__ */ new Map(); + for (let i5 = 0; i5 < alphabet.length; i5++) { + decodeMap2.set(alphabet[i5], i5); + } + const result = []; + let buffer2 = 0; + let bitsCollected = 0; + for (const char2 of data2) { + if (char2 === "=") + break; + const value = decodeMap2.get(char2); + if (value === void 0) { + throw new Error(`Invalid Base64 character: ${char2}`); + } + buffer2 = buffer2 << 6 | value; + bitsCollected += 6; + if (bitsCollected >= 8) { + bitsCollected -= 8; + result.push(buffer2 >> bitsCollected & 255); + } + } + return Uint8Array.from(result); +} +var base643, base64Url; +var init_base642 = __esm({ + "node_modules/.pnpm/@better-auth+utils@0.3.0/node_modules/@better-auth/utils/dist/base64.mjs"() { + base643 = { + encode(data2, options = {}) { + const alphabet = getAlphabet(false); + const buffer2 = typeof data2 === "string" ? new TextEncoder().encode(data2) : new Uint8Array(data2); + return base64Encode(buffer2, alphabet, options.padding ?? true); + }, + decode(data2) { + if (typeof data2 !== "string") { + data2 = new TextDecoder().decode(data2); + } + const urlSafe = data2.includes("-") || data2.includes("_"); + const alphabet = getAlphabet(urlSafe); + return base64Decode(data2, alphabet); + } + }; + base64Url = { + encode(data2, options = {}) { + const alphabet = getAlphabet(true); + const buffer2 = typeof data2 === "string" ? new TextEncoder().encode(data2) : new Uint8Array(data2); + return base64Encode(buffer2, alphabet, options.padding ?? true); + }, + decode(data2) { + const urlSafe = data2.includes("-") || data2.includes("_"); + const alphabet = getAlphabet(urlSafe); + return base64Decode(data2, alphabet); + } + }; + } +}); + +// node_modules/.pnpm/@better-auth+utils@0.3.0/node_modules/@better-auth/utils/dist/hash.mjs +function createHash17(algorithm2, encoding) { + return { + digest: async (input) => { + const encoder3 = new TextEncoder(); + const data2 = typeof input === "string" ? encoder3.encode(input) : input; + const hashBuffer2 = await getWebcryptoSubtle().digest(algorithm2, data2); + if (encoding === "hex") { + const hashArray = Array.from(new Uint8Array(hashBuffer2)); + const hashHex = hashArray.map((b6) => b6.toString(16).padStart(2, "0")).join(""); + return hashHex; + } + if (encoding === "base64" || encoding === "base64url" || encoding === "base64urlnopad") { + if (encoding.includes("url")) { + return base64Url.encode(hashBuffer2, { + padding: encoding !== "base64urlnopad" + }); + } + const hashBase64 = base643.encode(hashBuffer2); + return hashBase64; + } + return hashBuffer2; + } + }; +} +var init_hash = __esm({ + "node_modules/.pnpm/@better-auth+utils@0.3.0/node_modules/@better-auth/utils/dist/hash.mjs"() { + init_base642(); + init_dist(); + } +}); + +// node_modules/.pnpm/@noble+ciphers@2.2.0/node_modules/@noble/ciphers/utils.js +function isBytes2(a5) { + return a5 instanceof Uint8Array || ArrayBuffer.isView(a5) && a5.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a5 && a5.BYTES_PER_ELEMENT === 1; +} +function abool(b6) { + if (typeof b6 !== "boolean") + throw new TypeError(`boolean expected, not ${b6}`); +} +function anumber2(n5) { + if (typeof n5 !== "number") + throw new TypeError("number expected, got " + typeof n5); + if (!Number.isSafeInteger(n5) || n5 < 0) + throw new RangeError("positive integer expected, got " + n5); +} +function abytes2(value, length, title = "") { + const bytes = isBytes2(value); + const len = value?.length; + const needsLen = length !== void 0; + if (!bytes || needsLen && len !== length) { + const prefix = title && `"${title}" `; + const ofLen = needsLen ? ` of length ${length}` : ""; + const got = bytes ? `length=${len}` : `type=${typeof value}`; + const message2 = prefix + "expected Uint8Array" + ofLen + ", got " + got; + if (!bytes) + throw new TypeError(message2); + throw new RangeError(message2); + } + return value; +} +function aexists2(instance, checkFinished = true) { + if (instance.destroyed) + throw new Error("Hash instance has been destroyed"); + if (checkFinished && instance.finished) + throw new Error("Hash#digest() has already been called"); +} +function aoutput2(out, instance, onlyAligned = false) { + abytes2(out, void 0, "output"); + const min = instance.outputLen; + if (out.length < min) { + throw new RangeError("digestInto() expects output buffer of length at least " + min); + } + if (onlyAligned && !isAligned32(out)) + throw new Error("invalid output, must be aligned"); +} +function u322(arr) { + return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); +} +function clean2(...arrays) { + for (let i5 = 0; i5 < arrays.length; i5++) { + arrays[i5].fill(0); + } +} +function createView2(arr) { + return new DataView(arr.buffer, arr.byteOffset, arr.byteLength); +} +function bytesToHex(bytes) { + abytes2(bytes); + if (hasHexBuiltin2) + return bytes.toHex(); + let hex4 = ""; + for (let i5 = 0; i5 < bytes.length; i5++) { + hex4 += hexes[bytes[i5]]; + } + return hex4; +} +function asciiToBase162(ch) { + if (ch >= asciis2._0 && ch <= asciis2._9) + return ch - asciis2._0; + if (ch >= asciis2.A && ch <= asciis2.F) + return ch - (asciis2.A - 10); + if (ch >= asciis2.a && ch <= asciis2.f) + return ch - (asciis2.a - 10); + return; +} +function hexToBytes3(hex4) { + if (typeof hex4 !== "string") + throw new TypeError("hex string expected, got " + typeof hex4); + if (hasHexBuiltin2) { + try { + return Uint8Array.fromHex(hex4); + } catch (error50) { + if (error50 instanceof SyntaxError) + throw new RangeError(error50.message); + throw error50; + } + } + const hl = hex4.length; + const al = hl / 2; + if (hl % 2) + throw new RangeError("hex string expected, got unpadded hex of length " + hl); + const array2 = new Uint8Array(al); + for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) { + const n1 = asciiToBase162(hex4.charCodeAt(hi)); + const n22 = asciiToBase162(hex4.charCodeAt(hi + 1)); + if (n1 === void 0 || n22 === void 0) { + const char2 = hex4[hi] + hex4[hi + 1]; + throw new RangeError('hex string expected, got non-hex character "' + char2 + '" at index ' + hi); + } + array2[ai] = n1 * 16 + n22; + } + return array2; +} +function utf8ToBytes2(str) { + if (typeof str !== "string") + throw new TypeError("string expected"); + return new Uint8Array(new TextEncoder().encode(str)); +} +function overlapBytes(a5, b6) { + if (!a5.byteLength || !b6.byteLength) + return false; + return a5.buffer === b6.buffer && // best we can do, may fail with an obscure Proxy + a5.byteOffset < b6.byteOffset + b6.byteLength && // a starts before b end + b6.byteOffset < a5.byteOffset + a5.byteLength; +} +function concatBytes(...arrays) { + let sum = 0; + for (let i5 = 0; i5 < arrays.length; i5++) { + const a5 = arrays[i5]; + abytes2(a5); + sum += a5.length; + } + const res = new Uint8Array(sum); + for (let i5 = 0, pad = 0; i5 < arrays.length; i5++) { + const a5 = arrays[i5]; + res.set(a5, pad); + pad += a5.length; + } + return res; +} +function checkOpts2(defaults, opts) { + if (opts == null || typeof opts !== "object") + throw new Error("options must be defined"); + const merged = Object.assign(defaults, opts); + return merged; +} +function equalBytes(a5, b6) { + if (a5.length !== b6.length) + return false; + let diff = 0; + for (let i5 = 0; i5 < a5.length; i5++) + diff |= a5[i5] ^ b6[i5]; + return diff === 0; +} +function wrapMacConstructor(keyLen, macCons, fromMsg) { + const mac3 = macCons; + const getArgs = fromMsg || (() => []); + const macC = (msg, key) => mac3(key, ...getArgs(msg)).update(msg).digest(); + const tmp = mac3(new Uint8Array(keyLen), ...getArgs(new Uint8Array(0))); + macC.outputLen = tmp.outputLen; + macC.blockLen = tmp.blockLen; + macC.create = (key, ...args) => mac3(key, ...args); + return macC; +} +function getOutput(expectedLength, out, onlyAligned = true) { + if (out === void 0) + return new Uint8Array(expectedLength); + abytes2(out, void 0, "output"); + if (out.length !== expectedLength) + throw new Error('"output" expected Uint8Array of length ' + expectedLength + ", got: " + out.length); + if (onlyAligned && !isAligned32(out)) + throw new Error("invalid output, must be aligned"); + return out; +} +function u64Lengths(dataLength, aadLength, isLE3) { + anumber2(dataLength); + anumber2(aadLength); + abool(isLE3); + const num = new Uint8Array(16); + const view = createView2(num); + view.setBigUint64(0, BigInt(aadLength), isLE3); + view.setBigUint64(8, BigInt(dataLength), isLE3); + return num; +} +function isAligned32(bytes) { + return bytes.byteOffset % 4 === 0; +} +function copyBytes(bytes) { + return Uint8Array.from(abytes2(bytes)); +} +function randomBytes6(bytesLength = 32) { + anumber2(bytesLength); + const cr = typeof globalThis === "object" ? globalThis.crypto : null; + if (typeof cr?.getRandomValues !== "function") + throw new Error("crypto.getRandomValues must be defined"); + return cr.getRandomValues(new Uint8Array(bytesLength)); +} +function managedNonce(fn, randomBytes_ = randomBytes6) { + const { nonceLength } = fn; + anumber2(nonceLength); + const addNonce = (nonce, ciphertext, plaintext) => { + const out = concatBytes(nonce, ciphertext); + if (!overlapBytes(plaintext, ciphertext)) + ciphertext.fill(0); + return out; + }; + const res = ((key, ...args) => ({ + encrypt(plaintext) { + abytes2(plaintext); + const nonce = randomBytes_(nonceLength); + const encrypted = fn(key, nonce, ...args).encrypt(plaintext); + if (encrypted instanceof Promise) + return encrypted.then((ct) => addNonce(nonce, ct, plaintext)); + return addNonce(nonce, encrypted, plaintext); + }, + decrypt(ciphertext) { + abytes2(ciphertext); + const nonce = ciphertext.subarray(0, nonceLength); + const decrypted = ciphertext.subarray(nonceLength); + return fn(key, nonce, ...args).decrypt(decrypted); + } + })); + if ("blockSize" in fn) + res.blockSize = fn.blockSize; + if ("tagLength" in fn) + res.tagLength = fn.tagLength; + return res; +} +var isLE2, byteSwap2, swap8IfBE, byteSwap322, swap32IfBE2, hasHexBuiltin2, hexes, asciis2, wrapCipher; +var init_utils8 = __esm({ + "node_modules/.pnpm/@noble+ciphers@2.2.0/node_modules/@noble/ciphers/utils.js"() { + isLE2 = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)(); + byteSwap2 = (word) => word << 24 & 4278190080 | word << 8 & 16711680 | word >>> 8 & 65280 | word >>> 24 & 255; + swap8IfBE = isLE2 ? (n5) => n5 : (n5) => byteSwap2(n5) >>> 0; + byteSwap322 = (arr) => { + for (let i5 = 0; i5 < arr.length; i5++) + arr[i5] = byteSwap2(arr[i5]); + return arr; + }; + swap32IfBE2 = isLE2 ? (u5) => u5 : byteSwap322; + hasHexBuiltin2 = /* @__PURE__ */ (() => ( + // @ts-ignore + typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function" + ))(); + hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i5) => i5.toString(16).padStart(2, "0")); + asciis2 = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 }; + wrapCipher = /* @__NO_SIDE_EFFECTS__ */ (params, constructor) => { + function wrappedCipher(key, ...args) { + abytes2(key, void 0, "key"); + if (params.nonceLength !== void 0) { + const nonce = args[0]; + abytes2(nonce, params.varSizeNonce ? void 0 : params.nonceLength, "nonce"); + } + const tagl = params.tagLength; + if (tagl && args[1] !== void 0) + abytes2(args[1], void 0, "AAD"); + const cipher = constructor(key, ...args); + const checkOutput = (fnLength, output) => { + if (output !== void 0) { + if (fnLength !== 2) + throw new Error("cipher output not supported"); + abytes2(output, void 0, "output"); + } + }; + let called = false; + const wrCipher = { + encrypt(data2, output) { + if (called) + throw new Error("cannot encrypt() twice with same key + nonce"); + called = true; + abytes2(data2); + checkOutput(cipher.encrypt.length, output); + return cipher.encrypt(data2, output); + }, + decrypt(data2, output) { + abytes2(data2); + if (tagl && data2.length < tagl) + throw new Error('"ciphertext" expected length bigger than tagLength=' + tagl); + checkOutput(cipher.decrypt.length, output); + return cipher.decrypt(data2, output); + } + }; + return wrCipher; + } + Object.assign(wrappedCipher, params); + return wrappedCipher; + }; + } +}); + +// node_modules/.pnpm/@noble+ciphers@2.2.0/node_modules/@noble/ciphers/_arx.js +function rotl2(a5, b6) { + return a5 << b6 | a5 >>> 32 - b6; +} +function runCipher(core, sigma, key, nonce, data2, output, counter, rounds) { + const len = data2.length; + const block = new Uint8Array(BLOCK_LEN); + const b32 = u322(block); + const isAligned = isLE2 && isAligned32(data2) && isAligned32(output); + const d32 = isAligned ? u322(data2) : U32_EMPTY; + const o32 = isAligned ? u322(output) : U32_EMPTY; + if (!isLE2) { + for (let pos = 0; pos < len; counter++) { + core(sigma, key, nonce, b32, counter, rounds); + swap32IfBE2(b32); + if (counter >= MAX_COUNTER) + throw new Error("arx: counter overflow"); + const take = Math.min(BLOCK_LEN, len - pos); + for (let j5 = 0, posj; j5 < take; j5++) { + posj = pos + j5; + output[posj] = data2[posj] ^ block[j5]; + } + pos += take; + } + return; + } + for (let pos = 0; pos < len; counter++) { + core(sigma, key, nonce, b32, counter, rounds); + if (counter >= MAX_COUNTER) + throw new Error("arx: counter overflow"); + const take = Math.min(BLOCK_LEN, len - pos); + if (isAligned && take === BLOCK_LEN) { + const pos32 = pos / 4; + if (pos % 4 !== 0) + throw new Error("arx: invalid block position"); + for (let j5 = 0, posj; j5 < BLOCK_LEN32; j5++) { + posj = pos32 + j5; + o32[posj] = d32[posj] ^ b32[j5]; + } + pos += BLOCK_LEN; + continue; + } + for (let j5 = 0, posj; j5 < take; j5++) { + posj = pos + j5; + output[posj] = data2[posj] ^ block[j5]; + } + pos += take; + } +} +function createCipher(core, opts) { + const { allowShortKeys, extendNonceFn, counterLength, counterRight, rounds } = checkOpts2({ allowShortKeys: false, counterLength: 8, counterRight: false, rounds: 20 }, opts); + if (typeof core !== "function") + throw new Error("core must be a function"); + anumber2(counterLength); + anumber2(rounds); + abool(counterRight); + abool(allowShortKeys); + return (key, nonce, data2, output, counter = 0) => { + abytes2(key, void 0, "key"); + abytes2(nonce, void 0, "nonce"); + abytes2(data2, void 0, "data"); + const len = data2.length; + output = getOutput(len, output, false); + anumber2(counter); + if (counter < 0 || counter >= MAX_COUNTER) + throw new Error("arx: counter overflow"); + const toClean = []; + let l5 = key.length; + let k5; + let sigma; + if (l5 === 32) { + toClean.push(k5 = copyBytes(key)); + sigma = sigma32_32; + } else if (l5 === 16 && allowShortKeys) { + k5 = new Uint8Array(32); + k5.set(key); + k5.set(key, 16); + sigma = sigma16_32; + toClean.push(k5); + } else { + abytes2(key, 32, "arx key"); + throw new Error("invalid key size"); + } + if (!isLE2 || !isAligned32(nonce)) + toClean.push(nonce = copyBytes(nonce)); + let k32 = u322(k5); + if (extendNonceFn) { + if (nonce.length !== 24) + throw new Error(`arx: extended nonce must be 24 bytes`); + const n16 = nonce.subarray(0, 16); + if (isLE2) + extendNonceFn(sigma, k32, u322(n16), k32); + else { + const sigmaRaw = swap32IfBE2(Uint32Array.from(sigma)); + extendNonceFn(sigmaRaw, k32, u322(n16), k32); + clean2(sigmaRaw); + swap32IfBE2(k32); + } + nonce = nonce.subarray(16); + } else if (!isLE2) + swap32IfBE2(k32); + const nonceNcLen = 16 - counterLength; + if (nonceNcLen !== nonce.length) + throw new Error(`arx: nonce must be ${nonceNcLen} or 16 bytes`); + if (nonceNcLen !== 12) { + const nc = new Uint8Array(12); + nc.set(nonce, counterRight ? 0 : 12 - nonce.length); + nonce = nc; + toClean.push(nonce); + } + const n32 = swap32IfBE2(u322(nonce)); + try { + runCipher(core, sigma, k32, n32, data2, output, counter, rounds); + return output; + } finally { + clean2(...toClean); + } + }; +} +var encodeStr, sigma16_32, sigma32_32, BLOCK_LEN, BLOCK_LEN32, MAX_COUNTER, U32_EMPTY; +var init_arx = __esm({ + "node_modules/.pnpm/@noble+ciphers@2.2.0/node_modules/@noble/ciphers/_arx.js"() { + init_utils8(); + encodeStr = (str) => Uint8Array.from(str.split(""), (c5) => c5.charCodeAt(0)); + sigma16_32 = /* @__PURE__ */ (() => swap32IfBE2(u322(encodeStr("expand 16-byte k"))))(); + sigma32_32 = /* @__PURE__ */ (() => swap32IfBE2(u322(encodeStr("expand 32-byte k"))))(); + BLOCK_LEN = 64; + BLOCK_LEN32 = 16; + MAX_COUNTER = /* @__PURE__ */ (() => 2 ** 32 - 1)(); + U32_EMPTY = /* @__PURE__ */ Uint32Array.of(); + } +}); + +// node_modules/.pnpm/@noble+ciphers@2.2.0/node_modules/@noble/ciphers/_poly1305.js +function u8to16(a5, i5) { + return a5[i5++] & 255 | (a5[i5++] & 255) << 8; +} +var Poly1305, poly1305; +var init_poly1305 = __esm({ + "node_modules/.pnpm/@noble+ciphers@2.2.0/node_modules/@noble/ciphers/_poly1305.js"() { + init_utils8(); + Poly1305 = class { + blockLen = 16; + outputLen = 16; + buffer = new Uint8Array(16); + r = new Uint16Array(10); + // Allocating 1 array with .subarray() here is slower than 3 + h = new Uint16Array(10); + pad = new Uint16Array(8); + pos = 0; + finished = false; + destroyed = false; + // Can be speed-up using BigUint64Array, at the cost of complexity + constructor(key) { + key = copyBytes(abytes2(key, 32, "key")); + const t0 = u8to16(key, 0); + const t1 = u8to16(key, 2); + const t22 = u8to16(key, 4); + const t32 = u8to16(key, 6); + const t42 = u8to16(key, 8); + const t5 = u8to16(key, 10); + const t6 = u8to16(key, 12); + const t7 = u8to16(key, 14); + this.r[0] = t0 & 8191; + this.r[1] = (t0 >>> 13 | t1 << 3) & 8191; + this.r[2] = (t1 >>> 10 | t22 << 6) & 7939; + this.r[3] = (t22 >>> 7 | t32 << 9) & 8191; + this.r[4] = (t32 >>> 4 | t42 << 12) & 255; + this.r[5] = t42 >>> 1 & 8190; + this.r[6] = (t42 >>> 14 | t5 << 2) & 8191; + this.r[7] = (t5 >>> 11 | t6 << 5) & 8065; + this.r[8] = (t6 >>> 8 | t7 << 8) & 8191; + this.r[9] = t7 >>> 5 & 127; + for (let i5 = 0; i5 < 8; i5++) + this.pad[i5] = u8to16(key, 16 + 2 * i5); + } + process(data2, offset, isLast = false) { + const hibit = isLast ? 0 : 1 << 11; + const { h: h5, r: r5 } = this; + const r0 = r5[0]; + const r1 = r5[1]; + const r22 = r5[2]; + const r32 = r5[3]; + const r42 = r5[4]; + const r52 = r5[5]; + const r6 = r5[6]; + const r7 = r5[7]; + const r8 = r5[8]; + const r9 = r5[9]; + const t0 = u8to16(data2, offset + 0); + const t1 = u8to16(data2, offset + 2); + const t22 = u8to16(data2, offset + 4); + const t32 = u8to16(data2, offset + 6); + const t42 = u8to16(data2, offset + 8); + const t5 = u8to16(data2, offset + 10); + const t6 = u8to16(data2, offset + 12); + const t7 = u8to16(data2, offset + 14); + let h0 = h5[0] + (t0 & 8191); + let h1 = h5[1] + ((t0 >>> 13 | t1 << 3) & 8191); + let h22 = h5[2] + ((t1 >>> 10 | t22 << 6) & 8191); + let h32 = h5[3] + ((t22 >>> 7 | t32 << 9) & 8191); + let h42 = h5[4] + ((t32 >>> 4 | t42 << 12) & 8191); + let h52 = h5[5] + (t42 >>> 1 & 8191); + let h6 = h5[6] + ((t42 >>> 14 | t5 << 2) & 8191); + let h7 = h5[7] + ((t5 >>> 11 | t6 << 5) & 8191); + let h8 = h5[8] + ((t6 >>> 8 | t7 << 8) & 8191); + let h9 = h5[9] + (t7 >>> 5 | hibit); + let c5 = 0; + let d0 = c5 + h0 * r0 + h1 * (5 * r9) + h22 * (5 * r8) + h32 * (5 * r7) + h42 * (5 * r6); + c5 = d0 >>> 13; + d0 &= 8191; + d0 += h52 * (5 * r52) + h6 * (5 * r42) + h7 * (5 * r32) + h8 * (5 * r22) + h9 * (5 * r1); + c5 += d0 >>> 13; + d0 &= 8191; + let d1 = c5 + h0 * r1 + h1 * r0 + h22 * (5 * r9) + h32 * (5 * r8) + h42 * (5 * r7); + c5 = d1 >>> 13; + d1 &= 8191; + d1 += h52 * (5 * r6) + h6 * (5 * r52) + h7 * (5 * r42) + h8 * (5 * r32) + h9 * (5 * r22); + c5 += d1 >>> 13; + d1 &= 8191; + let d22 = c5 + h0 * r22 + h1 * r1 + h22 * r0 + h32 * (5 * r9) + h42 * (5 * r8); + c5 = d22 >>> 13; + d22 &= 8191; + d22 += h52 * (5 * r7) + h6 * (5 * r6) + h7 * (5 * r52) + h8 * (5 * r42) + h9 * (5 * r32); + c5 += d22 >>> 13; + d22 &= 8191; + let d32 = c5 + h0 * r32 + h1 * r22 + h22 * r1 + h32 * r0 + h42 * (5 * r9); + c5 = d32 >>> 13; + d32 &= 8191; + d32 += h52 * (5 * r8) + h6 * (5 * r7) + h7 * (5 * r6) + h8 * (5 * r52) + h9 * (5 * r42); + c5 += d32 >>> 13; + d32 &= 8191; + let d42 = c5 + h0 * r42 + h1 * r32 + h22 * r22 + h32 * r1 + h42 * r0; + c5 = d42 >>> 13; + d42 &= 8191; + d42 += h52 * (5 * r9) + h6 * (5 * r8) + h7 * (5 * r7) + h8 * (5 * r6) + h9 * (5 * r52); + c5 += d42 >>> 13; + d42 &= 8191; + let d5 = c5 + h0 * r52 + h1 * r42 + h22 * r32 + h32 * r22 + h42 * r1; + c5 = d5 >>> 13; + d5 &= 8191; + d5 += h52 * r0 + h6 * (5 * r9) + h7 * (5 * r8) + h8 * (5 * r7) + h9 * (5 * r6); + c5 += d5 >>> 13; + d5 &= 8191; + let d6 = c5 + h0 * r6 + h1 * r52 + h22 * r42 + h32 * r32 + h42 * r22; + c5 = d6 >>> 13; + d6 &= 8191; + d6 += h52 * r1 + h6 * r0 + h7 * (5 * r9) + h8 * (5 * r8) + h9 * (5 * r7); + c5 += d6 >>> 13; + d6 &= 8191; + let d7 = c5 + h0 * r7 + h1 * r6 + h22 * r52 + h32 * r42 + h42 * r32; + c5 = d7 >>> 13; + d7 &= 8191; + d7 += h52 * r22 + h6 * r1 + h7 * r0 + h8 * (5 * r9) + h9 * (5 * r8); + c5 += d7 >>> 13; + d7 &= 8191; + let d8 = c5 + h0 * r8 + h1 * r7 + h22 * r6 + h32 * r52 + h42 * r42; + c5 = d8 >>> 13; + d8 &= 8191; + d8 += h52 * r32 + h6 * r22 + h7 * r1 + h8 * r0 + h9 * (5 * r9); + c5 += d8 >>> 13; + d8 &= 8191; + let d9 = c5 + h0 * r9 + h1 * r8 + h22 * r7 + h32 * r6 + h42 * r52; + c5 = d9 >>> 13; + d9 &= 8191; + d9 += h52 * r42 + h6 * r32 + h7 * r22 + h8 * r1 + h9 * r0; + c5 += d9 >>> 13; + d9 &= 8191; + c5 = (c5 << 2) + c5 | 0; + c5 = c5 + d0 | 0; + d0 = c5 & 8191; + c5 = c5 >>> 13; + d1 += c5; + h5[0] = d0; + h5[1] = d1; + h5[2] = d22; + h5[3] = d32; + h5[4] = d42; + h5[5] = d5; + h5[6] = d6; + h5[7] = d7; + h5[8] = d8; + h5[9] = d9; + } + finalize() { + const { h: h5, pad } = this; + const g5 = new Uint16Array(10); + let c5 = h5[1] >>> 13; + h5[1] &= 8191; + for (let i5 = 2; i5 < 10; i5++) { + h5[i5] += c5; + c5 = h5[i5] >>> 13; + h5[i5] &= 8191; + } + h5[0] += c5 * 5; + c5 = h5[0] >>> 13; + h5[0] &= 8191; + h5[1] += c5; + c5 = h5[1] >>> 13; + h5[1] &= 8191; + h5[2] += c5; + g5[0] = h5[0] + 5; + c5 = g5[0] >>> 13; + g5[0] &= 8191; + for (let i5 = 1; i5 < 10; i5++) { + g5[i5] = h5[i5] + c5; + c5 = g5[i5] >>> 13; + g5[i5] &= 8191; + } + g5[9] -= 1 << 13; + let mask = (c5 ^ 1) - 1; + for (let i5 = 0; i5 < 10; i5++) + g5[i5] &= mask; + mask = ~mask; + for (let i5 = 0; i5 < 10; i5++) + h5[i5] = h5[i5] & mask | g5[i5]; + h5[0] = (h5[0] | h5[1] << 13) & 65535; + h5[1] = (h5[1] >>> 3 | h5[2] << 10) & 65535; + h5[2] = (h5[2] >>> 6 | h5[3] << 7) & 65535; + h5[3] = (h5[3] >>> 9 | h5[4] << 4) & 65535; + h5[4] = (h5[4] >>> 12 | h5[5] << 1 | h5[6] << 14) & 65535; + h5[5] = (h5[6] >>> 2 | h5[7] << 11) & 65535; + h5[6] = (h5[7] >>> 5 | h5[8] << 8) & 65535; + h5[7] = (h5[8] >>> 8 | h5[9] << 5) & 65535; + let f5 = h5[0] + pad[0]; + h5[0] = f5 & 65535; + for (let i5 = 1; i5 < 8; i5++) { + f5 = (h5[i5] + pad[i5] | 0) + (f5 >>> 16) | 0; + h5[i5] = f5 & 65535; + } + clean2(g5); + } + update(data2) { + aexists2(this); + abytes2(data2); + data2 = copyBytes(data2); + const { buffer: buffer2, blockLen } = this; + const len = data2.length; + for (let pos = 0; pos < len; ) { + const take = Math.min(blockLen - this.pos, len - pos); + if (take === blockLen) { + for (; blockLen <= len - pos; pos += blockLen) + this.process(data2, pos); + continue; + } + buffer2.set(data2.subarray(pos, pos + take), this.pos); + this.pos += take; + pos += take; + if (this.pos === blockLen) { + this.process(buffer2, 0, false); + this.pos = 0; + } + } + return this; + } + destroy() { + this.destroyed = true; + clean2(this.h, this.r, this.buffer, this.pad); + } + digestInto(out) { + aexists2(this); + aoutput2(out, this); + this.finished = true; + const { buffer: buffer2, h: h5 } = this; + let { pos } = this; + if (pos) { + buffer2[pos++] = 1; + for (; pos < 16; pos++) + buffer2[pos] = 0; + this.process(buffer2, 0, true); + } + this.finalize(); + let opos = 0; + for (let i5 = 0; i5 < 8; i5++) { + out[opos++] = h5[i5] >>> 0; + out[opos++] = h5[i5] >>> 8; + } + } + digest() { + const { buffer: buffer2, outputLen } = this; + this.digestInto(buffer2); + const res = buffer2.slice(0, outputLen); + this.destroy(); + return res; + } + }; + poly1305 = /* @__PURE__ */ wrapMacConstructor(32, (key) => new Poly1305(key)); + } +}); + +// node_modules/.pnpm/@noble+ciphers@2.2.0/node_modules/@noble/ciphers/chacha.js +function chachaCore(s5, k5, n5, out, cnt, rounds = 20) { + let y00 = s5[0], y01 = s5[1], y02 = s5[2], y03 = s5[3], y04 = k5[0], y05 = k5[1], y06 = k5[2], y07 = k5[3], y08 = k5[4], y09 = k5[5], y10 = k5[6], y11 = k5[7], y12 = cnt, y13 = n5[0], y14 = n5[1], y15 = n5[2]; + let x00 = y00, x01 = y01, x02 = y02, x03 = y03, x04 = y04, x05 = y05, x06 = y06, x07 = y07, x08 = y08, x09 = y09, x10 = y10, x11 = y11, x12 = y12, x13 = y13, x14 = y14, x15 = y15; + for (let r5 = 0; r5 < rounds; r5 += 2) { + x00 = x00 + x04 | 0; + x12 = rotl2(x12 ^ x00, 16); + x08 = x08 + x12 | 0; + x04 = rotl2(x04 ^ x08, 12); + x00 = x00 + x04 | 0; + x12 = rotl2(x12 ^ x00, 8); + x08 = x08 + x12 | 0; + x04 = rotl2(x04 ^ x08, 7); + x01 = x01 + x05 | 0; + x13 = rotl2(x13 ^ x01, 16); + x09 = x09 + x13 | 0; + x05 = rotl2(x05 ^ x09, 12); + x01 = x01 + x05 | 0; + x13 = rotl2(x13 ^ x01, 8); + x09 = x09 + x13 | 0; + x05 = rotl2(x05 ^ x09, 7); + x02 = x02 + x06 | 0; + x14 = rotl2(x14 ^ x02, 16); + x10 = x10 + x14 | 0; + x06 = rotl2(x06 ^ x10, 12); + x02 = x02 + x06 | 0; + x14 = rotl2(x14 ^ x02, 8); + x10 = x10 + x14 | 0; + x06 = rotl2(x06 ^ x10, 7); + x03 = x03 + x07 | 0; + x15 = rotl2(x15 ^ x03, 16); + x11 = x11 + x15 | 0; + x07 = rotl2(x07 ^ x11, 12); + x03 = x03 + x07 | 0; + x15 = rotl2(x15 ^ x03, 8); + x11 = x11 + x15 | 0; + x07 = rotl2(x07 ^ x11, 7); + x00 = x00 + x05 | 0; + x15 = rotl2(x15 ^ x00, 16); + x10 = x10 + x15 | 0; + x05 = rotl2(x05 ^ x10, 12); + x00 = x00 + x05 | 0; + x15 = rotl2(x15 ^ x00, 8); + x10 = x10 + x15 | 0; + x05 = rotl2(x05 ^ x10, 7); + x01 = x01 + x06 | 0; + x12 = rotl2(x12 ^ x01, 16); + x11 = x11 + x12 | 0; + x06 = rotl2(x06 ^ x11, 12); + x01 = x01 + x06 | 0; + x12 = rotl2(x12 ^ x01, 8); + x11 = x11 + x12 | 0; + x06 = rotl2(x06 ^ x11, 7); + x02 = x02 + x07 | 0; + x13 = rotl2(x13 ^ x02, 16); + x08 = x08 + x13 | 0; + x07 = rotl2(x07 ^ x08, 12); + x02 = x02 + x07 | 0; + x13 = rotl2(x13 ^ x02, 8); + x08 = x08 + x13 | 0; + x07 = rotl2(x07 ^ x08, 7); + x03 = x03 + x04 | 0; + x14 = rotl2(x14 ^ x03, 16); + x09 = x09 + x14 | 0; + x04 = rotl2(x04 ^ x09, 12); + x03 = x03 + x04 | 0; + x14 = rotl2(x14 ^ x03, 8); + x09 = x09 + x14 | 0; + x04 = rotl2(x04 ^ x09, 7); + } + let oi = 0; + out[oi++] = y00 + x00 | 0; + out[oi++] = y01 + x01 | 0; + out[oi++] = y02 + x02 | 0; + out[oi++] = y03 + x03 | 0; + out[oi++] = y04 + x04 | 0; + out[oi++] = y05 + x05 | 0; + out[oi++] = y06 + x06 | 0; + out[oi++] = y07 + x07 | 0; + out[oi++] = y08 + x08 | 0; + out[oi++] = y09 + x09 | 0; + out[oi++] = y10 + x10 | 0; + out[oi++] = y11 + x11 | 0; + out[oi++] = y12 + x12 | 0; + out[oi++] = y13 + x13 | 0; + out[oi++] = y14 + x14 | 0; + out[oi++] = y15 + x15 | 0; +} +function hchacha(s5, k5, i5, out) { + let x00 = swap8IfBE(s5[0]), x01 = swap8IfBE(s5[1]), x02 = swap8IfBE(s5[2]), x03 = swap8IfBE(s5[3]), x04 = swap8IfBE(k5[0]), x05 = swap8IfBE(k5[1]), x06 = swap8IfBE(k5[2]), x07 = swap8IfBE(k5[3]), x08 = swap8IfBE(k5[4]), x09 = swap8IfBE(k5[5]), x10 = swap8IfBE(k5[6]), x11 = swap8IfBE(k5[7]), x12 = swap8IfBE(i5[0]), x13 = swap8IfBE(i5[1]), x14 = swap8IfBE(i5[2]), x15 = swap8IfBE(i5[3]); + for (let r5 = 0; r5 < 20; r5 += 2) { + x00 = x00 + x04 | 0; + x12 = rotl2(x12 ^ x00, 16); + x08 = x08 + x12 | 0; + x04 = rotl2(x04 ^ x08, 12); + x00 = x00 + x04 | 0; + x12 = rotl2(x12 ^ x00, 8); + x08 = x08 + x12 | 0; + x04 = rotl2(x04 ^ x08, 7); + x01 = x01 + x05 | 0; + x13 = rotl2(x13 ^ x01, 16); + x09 = x09 + x13 | 0; + x05 = rotl2(x05 ^ x09, 12); + x01 = x01 + x05 | 0; + x13 = rotl2(x13 ^ x01, 8); + x09 = x09 + x13 | 0; + x05 = rotl2(x05 ^ x09, 7); + x02 = x02 + x06 | 0; + x14 = rotl2(x14 ^ x02, 16); + x10 = x10 + x14 | 0; + x06 = rotl2(x06 ^ x10, 12); + x02 = x02 + x06 | 0; + x14 = rotl2(x14 ^ x02, 8); + x10 = x10 + x14 | 0; + x06 = rotl2(x06 ^ x10, 7); + x03 = x03 + x07 | 0; + x15 = rotl2(x15 ^ x03, 16); + x11 = x11 + x15 | 0; + x07 = rotl2(x07 ^ x11, 12); + x03 = x03 + x07 | 0; + x15 = rotl2(x15 ^ x03, 8); + x11 = x11 + x15 | 0; + x07 = rotl2(x07 ^ x11, 7); + x00 = x00 + x05 | 0; + x15 = rotl2(x15 ^ x00, 16); + x10 = x10 + x15 | 0; + x05 = rotl2(x05 ^ x10, 12); + x00 = x00 + x05 | 0; + x15 = rotl2(x15 ^ x00, 8); + x10 = x10 + x15 | 0; + x05 = rotl2(x05 ^ x10, 7); + x01 = x01 + x06 | 0; + x12 = rotl2(x12 ^ x01, 16); + x11 = x11 + x12 | 0; + x06 = rotl2(x06 ^ x11, 12); + x01 = x01 + x06 | 0; + x12 = rotl2(x12 ^ x01, 8); + x11 = x11 + x12 | 0; + x06 = rotl2(x06 ^ x11, 7); + x02 = x02 + x07 | 0; + x13 = rotl2(x13 ^ x02, 16); + x08 = x08 + x13 | 0; + x07 = rotl2(x07 ^ x08, 12); + x02 = x02 + x07 | 0; + x13 = rotl2(x13 ^ x02, 8); + x08 = x08 + x13 | 0; + x07 = rotl2(x07 ^ x08, 7); + x03 = x03 + x04 | 0; + x14 = rotl2(x14 ^ x03, 16); + x09 = x09 + x14 | 0; + x04 = rotl2(x04 ^ x09, 12); + x03 = x03 + x04 | 0; + x14 = rotl2(x14 ^ x03, 8); + x09 = x09 + x14 | 0; + x04 = rotl2(x04 ^ x09, 7); + } + let oi = 0; + out[oi++] = x00; + out[oi++] = x01; + out[oi++] = x02; + out[oi++] = x03; + out[oi++] = x12; + out[oi++] = x13; + out[oi++] = x14; + out[oi++] = x15; + swap32IfBE2(out); +} +function computeTag(fn, key, nonce, ciphertext, AAD) { + if (AAD !== void 0) + abytes2(AAD, void 0, "AAD"); + const authKey = fn(key, nonce, ZEROS32); + const lengths = u64Lengths(ciphertext.length, AAD ? AAD.length : 0, true); + const h5 = poly1305.create(authKey); + if (AAD) + updatePadded(h5, AAD); + updatePadded(h5, ciphertext); + h5.update(lengths); + const res = h5.digest(); + clean2(authKey, lengths); + return res; +} +var xchacha20, ZEROS16, updatePadded, ZEROS32, _poly1305_aead, xchacha20poly1305; +var init_chacha = __esm({ + "node_modules/.pnpm/@noble+ciphers@2.2.0/node_modules/@noble/ciphers/chacha.js"() { + init_arx(); + init_poly1305(); + init_utils8(); + xchacha20 = /* @__PURE__ */ createCipher(chachaCore, { + counterRight: false, + counterLength: 8, + extendNonceFn: hchacha, + allowShortKeys: false + }); + ZEROS16 = /* @__PURE__ */ new Uint8Array(16); + updatePadded = (h5, msg) => { + h5.update(msg); + const leftover = msg.length % 16; + if (leftover) + h5.update(ZEROS16.subarray(leftover)); + }; + ZEROS32 = /* @__PURE__ */ new Uint8Array(32); + _poly1305_aead = (xorStream) => (key, nonce, AAD) => { + const tagLength = 16; + return { + encrypt(plaintext, output) { + const plength = plaintext.length; + output = getOutput(plength + tagLength, output, false); + output.set(plaintext); + const oPlain = output.subarray(0, -tagLength); + xorStream(key, nonce, oPlain, oPlain, 1); + const tag3 = computeTag(xorStream, key, nonce, oPlain, AAD); + output.set(tag3, plength); + clean2(tag3); + return output; + }, + decrypt(ciphertext, output) { + output = getOutput(ciphertext.length - tagLength, output, false); + const data2 = ciphertext.subarray(0, -tagLength); + const passedTag = ciphertext.subarray(-tagLength); + const tag3 = computeTag(xorStream, key, nonce, data2, AAD); + if (!equalBytes(passedTag, tag3)) { + clean2(tag3); + throw new Error("invalid tag"); + } + output.set(ciphertext.subarray(0, -tagLength)); + xorStream(key, nonce, output, output, 1); + clean2(tag3); + return output; + } + }; + }; + xchacha20poly1305 = /* @__PURE__ */ wrapCipher( + { blockSize: 64, nonceLength: 24, tagLength: 16 }, + /* @__PURE__ */ _poly1305_aead(xchacha20) + ); + } +}); + +// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/crypto/index.mjs +var symmetricEncrypt, symmetricDecrypt; +var init_crypto = __esm({ + "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/crypto/index.mjs"() { + init_buffer(); + init_jwt(); + init_password(); + init_random2(); + init_dist(); + init_hash(); + init_chacha(); + init_utils8(); + symmetricEncrypt = async ({ key, data: data2 }) => { + const keyAsBytes = await createHash17("SHA-256").digest(key); + const dataAsBytes = utf8ToBytes2(data2); + return bytesToHex(managedNonce(xchacha20poly1305)(new Uint8Array(keyAsBytes)).encrypt(dataAsBytes)); + }; + symmetricDecrypt = async ({ key, data: data2 }) => { + const keyAsBytes = await createHash17("SHA-256").digest(key); + const dataAsBytes = hexToBytes3(data2); + const chacha = managedNonce(xchacha20poly1305)(new Uint8Array(keyAsBytes)); + return new TextDecoder().decode(chacha.decrypt(dataAsBytes)); + }; + } +}); + +// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/utils/date.mjs +var getDate; +var init_date2 = __esm({ + "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/utils/date.mjs"() { + getDate = (span, unit = "ms") => { + return new Date(Date.now() + (unit === "sec" ? span * 1e3 : span)); + }; + } +}); + +// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/db/get-tables.mjs +var getAuthTables; +var init_get_tables = __esm({ + "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/db/get-tables.mjs"() { + getAuthTables = (options) => { + const pluginSchema = (options.plugins ?? []).reduce((acc, plugin) => { + const schema2 = plugin.schema; + if (!schema2) return acc; + for (const [key, value] of Object.entries(schema2)) acc[key] = { + fields: { + ...acc[key]?.fields, + ...value.fields + }, + modelName: value.modelName || key + }; + return acc; + }, {}); + const shouldAddRateLimitTable = options.rateLimit?.storage === "database"; + const rateLimitTable = { rateLimit: { + modelName: options.rateLimit?.modelName || "rateLimit", + fields: { + key: { + type: "string", + unique: true, + required: true, + fieldName: options.rateLimit?.fields?.key || "key" + }, + count: { + type: "number", + required: true, + fieldName: options.rateLimit?.fields?.count || "count" + }, + lastRequest: { + type: "number", + bigint: true, + required: true, + fieldName: options.rateLimit?.fields?.lastRequest || "lastRequest", + defaultValue: () => Date.now() + } + } + } }; + const { user, session, account, verification, ...pluginTables } = pluginSchema; + const sessionTable = { session: { + modelName: options.session?.modelName || "session", + fields: { + expiresAt: { + type: "date", + required: true, + fieldName: options.session?.fields?.expiresAt || "expiresAt" + }, + token: { + type: "string", + required: true, + fieldName: options.session?.fields?.token || "token", + unique: true + }, + createdAt: { + type: "date", + required: true, + fieldName: options.session?.fields?.createdAt || "createdAt", + defaultValue: () => /* @__PURE__ */ new Date() + }, + updatedAt: { + type: "date", + required: true, + fieldName: options.session?.fields?.updatedAt || "updatedAt", + onUpdate: () => /* @__PURE__ */ new Date() + }, + ipAddress: { + type: "string", + required: false, + fieldName: options.session?.fields?.ipAddress || "ipAddress" + }, + userAgent: { + type: "string", + required: false, + fieldName: options.session?.fields?.userAgent || "userAgent" + }, + userId: { + type: "string", + fieldName: options.session?.fields?.userId || "userId", + references: { + model: options.user?.modelName || "user", + field: "id", + onDelete: "cascade" + }, + required: true, + index: true + }, + ...session?.fields, + ...options.session?.additionalFields + }, + order: 2 + } }; + return { + user: { + modelName: options.user?.modelName || "user", + fields: { + name: { + type: "string", + required: true, + fieldName: options.user?.fields?.name || "name", + sortable: true + }, + email: { + type: "string", + unique: true, + required: true, + fieldName: options.user?.fields?.email || "email", + sortable: true + }, + emailVerified: { + type: "boolean", + defaultValue: false, + required: true, + fieldName: options.user?.fields?.emailVerified || "emailVerified", + input: false + }, + image: { + type: "string", + required: false, + fieldName: options.user?.fields?.image || "image" + }, + createdAt: { + type: "date", + defaultValue: () => /* @__PURE__ */ new Date(), + required: true, + fieldName: options.user?.fields?.createdAt || "createdAt" + }, + updatedAt: { + type: "date", + defaultValue: () => /* @__PURE__ */ new Date(), + onUpdate: () => /* @__PURE__ */ new Date(), + required: true, + fieldName: options.user?.fields?.updatedAt || "updatedAt" + }, + ...user?.fields, + ...options.user?.additionalFields + }, + order: 1 + }, + ...!options.secondaryStorage || options.session?.storeSessionInDatabase ? sessionTable : {}, + account: { + modelName: options.account?.modelName || "account", + fields: { + accountId: { + type: "string", + required: true, + fieldName: options.account?.fields?.accountId || "accountId" + }, + providerId: { + type: "string", + required: true, + fieldName: options.account?.fields?.providerId || "providerId" + }, + userId: { + type: "string", + references: { + model: options.user?.modelName || "user", + field: "id", + onDelete: "cascade" + }, + required: true, + fieldName: options.account?.fields?.userId || "userId", + index: true + }, + accessToken: { + type: "string", + required: false, + returned: false, + fieldName: options.account?.fields?.accessToken || "accessToken" + }, + refreshToken: { + type: "string", + required: false, + returned: false, + fieldName: options.account?.fields?.refreshToken || "refreshToken" + }, + idToken: { + type: "string", + required: false, + returned: false, + fieldName: options.account?.fields?.idToken || "idToken" + }, + accessTokenExpiresAt: { + type: "date", + required: false, + returned: false, + fieldName: options.account?.fields?.accessTokenExpiresAt || "accessTokenExpiresAt" + }, + refreshTokenExpiresAt: { + type: "date", + required: false, + returned: false, + fieldName: options.account?.fields?.refreshTokenExpiresAt || "refreshTokenExpiresAt" + }, + scope: { + type: "string", + required: false, + fieldName: options.account?.fields?.scope || "scope" + }, + password: { + type: "string", + required: false, + returned: false, + fieldName: options.account?.fields?.password || "password" + }, + createdAt: { + type: "date", + required: true, + fieldName: options.account?.fields?.createdAt || "createdAt", + defaultValue: () => /* @__PURE__ */ new Date() + }, + updatedAt: { + type: "date", + required: true, + fieldName: options.account?.fields?.updatedAt || "updatedAt", + onUpdate: () => /* @__PURE__ */ new Date() + }, + ...account?.fields, + ...options.account?.additionalFields + }, + order: 3 + }, + verification: { + modelName: options.verification?.modelName || "verification", + fields: { + identifier: { + type: "string", + required: true, + fieldName: options.verification?.fields?.identifier || "identifier", + index: true + }, + value: { + type: "string", + required: true, + fieldName: options.verification?.fields?.value || "value" + }, + expiresAt: { + type: "date", + required: true, + fieldName: options.verification?.fields?.expiresAt || "expiresAt" + }, + createdAt: { + type: "date", + required: true, + defaultValue: () => /* @__PURE__ */ new Date(), + fieldName: options.verification?.fields?.createdAt || "createdAt" + }, + updatedAt: { + type: "date", + required: true, + defaultValue: () => /* @__PURE__ */ new Date(), + onUpdate: () => /* @__PURE__ */ new Date(), + fieldName: options.verification?.fields?.updatedAt || "updatedAt" + }, + ...verification?.fields, + ...options.verification?.additionalFields + }, + order: 4 + }, + ...pluginTables, + ...shouldAddRateLimitTable ? rateLimitTable : {} + }; + }; + } +}); + +// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/db/schema/shared.mjs +var coreSchema; +var init_shared = __esm({ + "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/db/schema/shared.mjs"() { + init_zod(); + coreSchema = object({ + id: string2(), + createdAt: date5().default(() => /* @__PURE__ */ new Date()), + updatedAt: date5().default(() => /* @__PURE__ */ new Date()) + }); + } +}); + +// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/db/schema/account.mjs +var accountSchema; +var init_account = __esm({ + "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/db/schema/account.mjs"() { + init_shared(); + init_zod(); + accountSchema = coreSchema.extend({ + providerId: string2(), + accountId: string2(), + userId: coerce_exports.string(), + accessToken: string2().nullish(), + refreshToken: string2().nullish(), + idToken: string2().nullish(), + accessTokenExpiresAt: date5().nullish(), + refreshTokenExpiresAt: date5().nullish(), + scope: string2().nullish(), + password: string2().nullish() + }); + } +}); + +// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/db/schema/rate-limit.mjs +var rateLimitSchema; +var init_rate_limit = __esm({ + "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/db/schema/rate-limit.mjs"() { + init_zod(); + rateLimitSchema = object({ + key: string2(), + count: number2(), + lastRequest: number2() + }); + } +}); + +// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/db/schema/session.mjs +var sessionSchema; +var init_session3 = __esm({ + "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/db/schema/session.mjs"() { + init_shared(); + init_zod(); + sessionSchema = coreSchema.extend({ + userId: coerce_exports.string(), + expiresAt: date5(), + token: string2(), + ipAddress: string2().nullish(), + userAgent: string2().nullish() + }); + } +}); + +// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/db/schema/user.mjs +var userSchema; +var init_user = __esm({ + "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/db/schema/user.mjs"() { + init_shared(); + init_zod(); + userSchema = coreSchema.extend({ + email: string2().transform((val) => val.toLowerCase()), + emailVerified: boolean3().default(false), + name: string2(), + image: string2().nullish() + }); + } +}); + +// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/db/schema/verification.mjs +var verificationSchema; +var init_verification = __esm({ + "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/db/schema/verification.mjs"() { + init_shared(); + init_zod(); + verificationSchema = coreSchema.extend({ + value: string2(), + expiresAt: date5(), + identifier: string2() + }); + } +}); + +// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/db/index.mjs +var db_exports = {}; +__export(db_exports, { + accountSchema: () => accountSchema, + coreSchema: () => coreSchema, + getAuthTables: () => getAuthTables, + rateLimitSchema: () => rateLimitSchema, + sessionSchema: () => sessionSchema, + userSchema: () => userSchema, + verificationSchema: () => verificationSchema +}); +var init_db3 = __esm({ + "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/db/index.mjs"() { + init_get_tables(); + init_shared(); + init_account(); + init_rate_limit(); + init_session3(); + init_user(); + init_verification(); + } +}); + +// node_modules/.pnpm/better-call@1.1.8_zod@4.3.6/node_modules/better-call/dist/error.mjs +function isErrorStackTraceLimitWritable() { + const desc3 = Object.getOwnPropertyDescriptor(Error, "stackTraceLimit"); + if (desc3 === void 0) return Object.isExtensible(Error); + return Object.prototype.hasOwnProperty.call(desc3, "writable") ? desc3.writable : desc3.set !== void 0; +} +function hideInternalStackFrames(stack) { + const lines = stack.split("\n at "); + if (lines.length <= 1) return stack; + lines.splice(1, 1); + return lines.join("\n at "); +} +function makeErrorForHideStackFrame(Base, clazz) { + class HideStackFramesError extends Base { + #hiddenStack; + constructor(...args) { + if (isErrorStackTraceLimitWritable()) { + const limit = Error.stackTraceLimit; + Error.stackTraceLimit = 0; + super(...args); + Error.stackTraceLimit = limit; + } else super(...args); + const stack = (/* @__PURE__ */ new Error()).stack; + if (stack) this.#hiddenStack = hideInternalStackFrames(stack.replace(/^Error/, this.name)); + } + get errorStack() { + return this.#hiddenStack; + } + } + Object.defineProperty(HideStackFramesError.prototype, "constructor", { + get() { + return clazz; + }, + enumerable: false, + configurable: true + }); + return HideStackFramesError; +} +var statusCodes, InternalAPIError, ValidationError, BetterCallError, APIError; +var init_error2 = __esm({ + "node_modules/.pnpm/better-call@1.1.8_zod@4.3.6/node_modules/better-call/dist/error.mjs"() { + statusCodes = { + OK: 200, + CREATED: 201, + ACCEPTED: 202, + NO_CONTENT: 204, + MULTIPLE_CHOICES: 300, + MOVED_PERMANENTLY: 301, + FOUND: 302, + SEE_OTHER: 303, + NOT_MODIFIED: 304, + TEMPORARY_REDIRECT: 307, + BAD_REQUEST: 400, + UNAUTHORIZED: 401, + PAYMENT_REQUIRED: 402, + FORBIDDEN: 403, + NOT_FOUND: 404, + METHOD_NOT_ALLOWED: 405, + NOT_ACCEPTABLE: 406, + PROXY_AUTHENTICATION_REQUIRED: 407, + REQUEST_TIMEOUT: 408, + CONFLICT: 409, + GONE: 410, + LENGTH_REQUIRED: 411, + PRECONDITION_FAILED: 412, + PAYLOAD_TOO_LARGE: 413, + URI_TOO_LONG: 414, + UNSUPPORTED_MEDIA_TYPE: 415, + RANGE_NOT_SATISFIABLE: 416, + EXPECTATION_FAILED: 417, + "I'M_A_TEAPOT": 418, + MISDIRECTED_REQUEST: 421, + UNPROCESSABLE_ENTITY: 422, + LOCKED: 423, + FAILED_DEPENDENCY: 424, + TOO_EARLY: 425, + UPGRADE_REQUIRED: 426, + PRECONDITION_REQUIRED: 428, + TOO_MANY_REQUESTS: 429, + REQUEST_HEADER_FIELDS_TOO_LARGE: 431, + UNAVAILABLE_FOR_LEGAL_REASONS: 451, + INTERNAL_SERVER_ERROR: 500, + NOT_IMPLEMENTED: 501, + BAD_GATEWAY: 502, + SERVICE_UNAVAILABLE: 503, + GATEWAY_TIMEOUT: 504, + HTTP_VERSION_NOT_SUPPORTED: 505, + VARIANT_ALSO_NEGOTIATES: 506, + INSUFFICIENT_STORAGE: 507, + LOOP_DETECTED: 508, + NOT_EXTENDED: 510, + NETWORK_AUTHENTICATION_REQUIRED: 511 + }; + InternalAPIError = class extends Error { + constructor(status = "INTERNAL_SERVER_ERROR", body = void 0, headers = {}, statusCode = typeof status === "number" ? status : statusCodes[status]) { + super(body?.message, body?.cause ? { cause: body.cause } : void 0); + this.status = status; + this.body = body; + this.headers = headers; + this.statusCode = statusCode; + this.name = "APIError"; + this.status = status; + this.headers = headers; + this.statusCode = statusCode; + this.body = body ? { + code: body?.message?.toUpperCase().replace(/ /g, "_").replace(/[^A-Z0-9_]/g, ""), + ...body + } : void 0; + } + }; + ValidationError = class extends InternalAPIError { + constructor(message2, issues2) { + super(400, { + message: message2, + code: "VALIDATION_ERROR" + }); + this.message = message2; + this.issues = issues2; + this.issues = issues2; + } + }; + BetterCallError = class extends Error { + constructor(message2) { + super(message2); + this.name = "BetterCallError"; + } + }; + APIError = makeErrorForHideStackFrame(InternalAPIError, Error); + } +}); + +// node_modules/.pnpm/better-call@1.1.8_zod@4.3.6/node_modules/better-call/dist/utils.mjs +async function getBody(request, allowedMediaTypes) { + const contentType = request.headers.get("content-type") || ""; + const normalizedContentType = contentType.toLowerCase(); + if (!request.body) return; + if (allowedMediaTypes && allowedMediaTypes.length > 0) { + if (!allowedMediaTypes.some((allowed2) => { + const normalizedContentTypeBase = normalizedContentType.split(";")[0].trim(); + const normalizedAllowed = allowed2.toLowerCase().trim(); + return normalizedContentTypeBase === normalizedAllowed || normalizedContentTypeBase.includes(normalizedAllowed); + })) { + if (!normalizedContentType) throw new APIError(415, { + message: `Content-Type is required. Allowed types: ${allowedMediaTypes.join(", ")}`, + code: "UNSUPPORTED_MEDIA_TYPE" + }); + throw new APIError(415, { + message: `Content-Type "${contentType}" is not allowed. Allowed types: ${allowedMediaTypes.join(", ")}`, + code: "UNSUPPORTED_MEDIA_TYPE" + }); + } + } + if (jsonContentTypeRegex.test(normalizedContentType)) return await request.json(); + if (normalizedContentType.includes("application/x-www-form-urlencoded")) { + const formData = await request.formData(); + const result = {}; + formData.forEach((value, key) => { + result[key] = value.toString(); + }); + return result; + } + if (normalizedContentType.includes("multipart/form-data")) { + const formData = await request.formData(); + const result = {}; + formData.forEach((value, key) => { + result[key] = value; + }); + return result; + } + if (normalizedContentType.includes("text/plain")) return await request.text(); + if (normalizedContentType.includes("application/octet-stream")) return await request.arrayBuffer(); + if (normalizedContentType.includes("application/pdf") || normalizedContentType.includes("image/") || normalizedContentType.includes("video/")) return await request.blob(); + if (normalizedContentType.includes("application/stream") || request.body instanceof ReadableStream) return request.body; + return await request.text(); +} +function isAPIError(error50) { + return error50 instanceof APIError || error50?.name === "APIError"; +} +function tryDecode(str) { + try { + return str.includes("%") ? decodeURIComponent(str) : str; + } catch { + return str; + } +} +async function tryCatch(promise2) { + try { + return { + data: await promise2, + error: null + }; + } catch (error50) { + return { + data: null, + error: error50 + }; + } +} +function isRequest(obj) { + return obj instanceof Request || Object.prototype.toString.call(obj) === "[object Request]"; +} +var jsonContentTypeRegex; +var init_utils9 = __esm({ + "node_modules/.pnpm/better-call@1.1.8_zod@4.3.6/node_modules/better-call/dist/utils.mjs"() { + init_error2(); + jsonContentTypeRegex = /^application\/([a-z0-9.+-]*\+)?json/i; + } +}); + +// node_modules/.pnpm/better-call@1.1.8_zod@4.3.6/node_modules/better-call/dist/to-response.mjs +function isJSONSerializable(value) { + if (value === void 0) return false; + const t5 = typeof value; + if (t5 === "string" || t5 === "number" || t5 === "boolean" || t5 === null) return true; + if (t5 !== "object") return false; + if (Array.isArray(value)) return true; + if (value.buffer) return false; + return value.constructor && value.constructor.name === "Object" || typeof value.toJSON === "function"; +} +function safeStringify(obj, replacer, space) { + let id = 0; + const seen = /* @__PURE__ */ new WeakMap(); + const safeReplacer = (key, value) => { + if (typeof value === "bigint") return value.toString(); + if (typeof value === "object" && value !== null) { + if (seen.has(value)) return `[Circular ref-${seen.get(value)}]`; + seen.set(value, id++); + } + if (replacer) return replacer(key, value); + return value; + }; + return JSON.stringify(obj, safeReplacer, space); +} +function isJSONResponse(value) { + if (!value || typeof value !== "object") return false; + return "_flag" in value && value._flag === "json"; +} +function toResponse(data2, init2) { + if (data2 instanceof Response) { + if (init2?.headers instanceof Headers) init2.headers.forEach((value, key) => { + data2.headers.set(key, value); + }); + return data2; + } + if (isJSONResponse(data2)) { + const body$1 = data2.body; + const routerResponse = data2.routerResponse; + if (routerResponse instanceof Response) return routerResponse; + const headers$1 = new Headers(); + if (routerResponse?.headers) { + const headers$2 = new Headers(routerResponse.headers); + for (const [key, value] of headers$2.entries()) headers$2.set(key, value); + } + if (data2.headers) for (const [key, value] of new Headers(data2.headers).entries()) headers$1.set(key, value); + if (init2?.headers) for (const [key, value] of new Headers(init2.headers).entries()) headers$1.set(key, value); + headers$1.set("Content-Type", "application/json"); + return new Response(JSON.stringify(body$1), { + ...routerResponse, + headers: headers$1, + status: data2.status ?? init2?.status ?? routerResponse?.status, + statusText: init2?.statusText ?? routerResponse?.statusText + }); + } + if (isAPIError(data2)) return toResponse(data2.body, { + status: init2?.status ?? data2.statusCode, + statusText: data2.status.toString(), + headers: init2?.headers || data2.headers + }); + let body = data2; + let headers = new Headers(init2?.headers); + if (!data2) { + if (data2 === null) body = JSON.stringify(null); + headers.set("content-type", "application/json"); + } else if (typeof data2 === "string") { + body = data2; + headers.set("Content-Type", "text/plain"); + } else if (data2 instanceof ArrayBuffer || ArrayBuffer.isView(data2)) { + body = data2; + headers.set("Content-Type", "application/octet-stream"); + } else if (data2 instanceof Blob) { + body = data2; + headers.set("Content-Type", data2.type || "application/octet-stream"); + } else if (data2 instanceof FormData) body = data2; + else if (data2 instanceof URLSearchParams) { + body = data2; + headers.set("Content-Type", "application/x-www-form-urlencoded"); + } else if (data2 instanceof ReadableStream) { + body = data2; + headers.set("Content-Type", "application/octet-stream"); + } else if (isJSONSerializable(data2)) { + body = safeStringify(data2); + headers.set("Content-Type", "application/json"); + } + return new Response(body, { + ...init2, + headers + }); +} +var init_to_response = __esm({ + "node_modules/.pnpm/better-call@1.1.8_zod@4.3.6/node_modules/better-call/dist/to-response.mjs"() { + init_error2(); + init_utils9(); + } +}); + +// node_modules/.pnpm/better-call@1.1.8_zod@4.3.6/node_modules/better-call/dist/crypto.mjs +var algorithm, getCryptoKey3, verifySignature, makeSignature, signCookieValue; +var init_crypto2 = __esm({ + "node_modules/.pnpm/better-call@1.1.8_zod@4.3.6/node_modules/better-call/dist/crypto.mjs"() { + init_dist(); + algorithm = { + name: "HMAC", + hash: "SHA-256" + }; + getCryptoKey3 = async (secret) => { + const secretBuf = typeof secret === "string" ? new TextEncoder().encode(secret) : secret; + return await getWebcryptoSubtle().importKey("raw", secretBuf, algorithm, false, ["sign", "verify"]); + }; + verifySignature = async (base64Signature, value, secret) => { + try { + const signatureBinStr = atob(base64Signature); + const signature = new Uint8Array(signatureBinStr.length); + for (let i5 = 0, len = signatureBinStr.length; i5 < len; i5++) signature[i5] = signatureBinStr.charCodeAt(i5); + return await getWebcryptoSubtle().verify(algorithm, secret, signature, new TextEncoder().encode(value)); + } catch (e5) { + return false; + } + }; + makeSignature = async (value, secret) => { + const key = await getCryptoKey3(secret); + const signature = await getWebcryptoSubtle().sign(algorithm.name, key, new TextEncoder().encode(value)); + return btoa(String.fromCharCode(...new Uint8Array(signature))); + }; + signCookieValue = async (value, secret) => { + const signature = await makeSignature(value, secret); + value = `${value}.${signature}`; + value = encodeURIComponent(value); + return value; + }; + } +}); + +// node_modules/.pnpm/better-call@1.1.8_zod@4.3.6/node_modules/better-call/dist/cookies.mjs +function parseCookies(str) { + if (typeof str !== "string") throw new TypeError("argument str must be a string"); + const cookies = /* @__PURE__ */ new Map(); + let index2 = 0; + while (index2 < str.length) { + const eqIdx = str.indexOf("=", index2); + if (eqIdx === -1) break; + let endIdx = str.indexOf(";", index2); + if (endIdx === -1) endIdx = str.length; + else if (endIdx < eqIdx) { + index2 = str.lastIndexOf(";", eqIdx - 1) + 1; + continue; + } + const key = str.slice(index2, eqIdx).trim(); + if (!cookies.has(key)) { + let val = str.slice(eqIdx + 1, endIdx).trim(); + if (val.codePointAt(0) === 34) val = val.slice(1, -1); + cookies.set(key, tryDecode(val)); + } + index2 = endIdx + 1; + } + return cookies; +} +var getCookieKey, _serialize, serializeCookie, serializeSignedCookie; +var init_cookies = __esm({ + "node_modules/.pnpm/better-call@1.1.8_zod@4.3.6/node_modules/better-call/dist/cookies.mjs"() { + init_utils9(); + init_crypto2(); + getCookieKey = (key, prefix) => { + let finalKey = key; + if (prefix) if (prefix === "secure") finalKey = "__Secure-" + key; + else if (prefix === "host") finalKey = "__Host-" + key; + else return; + return finalKey; + }; + _serialize = (key, value, opt = {}) => { + let cookie; + if (opt?.prefix === "secure") cookie = `${`__Secure-${key}`}=${value}`; + else if (opt?.prefix === "host") cookie = `${`__Host-${key}`}=${value}`; + else cookie = `${key}=${value}`; + if (key.startsWith("__Secure-") && !opt.secure) opt.secure = true; + if (key.startsWith("__Host-")) { + if (!opt.secure) opt.secure = true; + if (opt.path !== "/") opt.path = "/"; + if (opt.domain) opt.domain = void 0; + } + if (opt && typeof opt.maxAge === "number" && opt.maxAge >= 0) { + if (opt.maxAge > 3456e4) throw new Error("Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration."); + cookie += `; Max-Age=${Math.floor(opt.maxAge)}`; + } + if (opt.domain && opt.prefix !== "host") cookie += `; Domain=${opt.domain}`; + if (opt.path) cookie += `; Path=${opt.path}`; + if (opt.expires) { + if (opt.expires.getTime() - Date.now() > 3456e7) throw new Error("Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future."); + cookie += `; Expires=${opt.expires.toUTCString()}`; + } + if (opt.httpOnly) cookie += "; HttpOnly"; + if (opt.secure) cookie += "; Secure"; + if (opt.sameSite) cookie += `; SameSite=${opt.sameSite.charAt(0).toUpperCase() + opt.sameSite.slice(1)}`; + if (opt.partitioned) { + if (!opt.secure) opt.secure = true; + cookie += "; Partitioned"; + } + return cookie; + }; + serializeCookie = (key, value, opt) => { + value = encodeURIComponent(value); + return _serialize(key, value, opt); + }; + serializeSignedCookie = async (key, value, secret, opt) => { + value = await signCookieValue(value, secret); + return _serialize(key, value, opt); + }; + } +}); + +// node_modules/.pnpm/better-call@1.1.8_zod@4.3.6/node_modules/better-call/dist/validator.mjs +async function runValidation(options, context = {}) { + let request = { + body: context.body, + query: context.query + }; + if (options.body) { + const result = await options.body["~standard"].validate(context.body); + if (result.issues) return { + data: null, + error: fromError(result.issues, "body") + }; + request.body = result.value; + } + if (options.query) { + const result = await options.query["~standard"].validate(context.query); + if (result.issues) return { + data: null, + error: fromError(result.issues, "query") + }; + request.query = result.value; + } + if (options.requireHeaders && !context.headers) return { + data: null, + error: { + message: "Headers is required", + issues: [] + } + }; + if (options.requireRequest && !context.request) return { + data: null, + error: { + message: "Request is required", + issues: [] + } + }; + return { + data: request, + error: null + }; +} +function fromError(error50, validating) { + return { + message: error50.map((e5) => { + return `[${e5.path?.length ? `${validating}.` + e5.path.map((x5) => typeof x5 === "object" ? x5.key : x5).join(".") : validating}] ${e5.message}`; + }).join("; "), + issues: error50 + }; +} +var init_validator = __esm({ + "node_modules/.pnpm/better-call@1.1.8_zod@4.3.6/node_modules/better-call/dist/validator.mjs"() { + } +}); + +// node_modules/.pnpm/better-call@1.1.8_zod@4.3.6/node_modules/better-call/dist/context.mjs +var createInternalContext; +var init_context = __esm({ + "node_modules/.pnpm/better-call@1.1.8_zod@4.3.6/node_modules/better-call/dist/context.mjs"() { + init_error2(); + init_utils9(); + init_validator(); + init_crypto2(); + init_cookies(); + createInternalContext = async (context, { options, path: path53 }) => { + const headers = new Headers(); + let responseStatus = void 0; + const { data: data2, error: error50 } = await runValidation(options, context); + if (error50) throw new ValidationError(error50.message, error50.issues); + const requestHeaders = "headers" in context ? context.headers instanceof Headers ? context.headers : new Headers(context.headers) : "request" in context && isRequest(context.request) ? context.request.headers : null; + const requestCookies = requestHeaders?.get("cookie"); + const parsedCookies = requestCookies ? parseCookies(requestCookies) : void 0; + const internalContext = { + ...context, + body: data2.body, + query: data2.query, + path: context.path || path53 || "virtual:", + context: "context" in context && context.context ? context.context : {}, + returned: void 0, + headers: context?.headers, + request: context?.request, + params: "params" in context ? context.params : void 0, + method: context.method ?? (Array.isArray(options.method) ? options.method[0] : options.method === "*" ? "GET" : options.method), + setHeader: (key, value) => { + headers.set(key, value); + }, + getHeader: (key) => { + if (!requestHeaders) return null; + return requestHeaders.get(key); + }, + getCookie: (key, prefix) => { + const finalKey = getCookieKey(key, prefix); + if (!finalKey) return null; + return parsedCookies?.get(finalKey) || null; + }, + getSignedCookie: async (key, secret, prefix) => { + const finalKey = getCookieKey(key, prefix); + if (!finalKey) return null; + const value = parsedCookies?.get(finalKey); + if (!value) return null; + const signatureStartPos = value.lastIndexOf("."); + if (signatureStartPos < 1) return null; + const signedValue = value.substring(0, signatureStartPos); + const signature = value.substring(signatureStartPos + 1); + if (signature.length !== 44 || !signature.endsWith("=")) return null; + return await verifySignature(signature, signedValue, await getCryptoKey3(secret)) ? signedValue : false; + }, + setCookie: (key, value, options$1) => { + const cookie = serializeCookie(key, value, options$1); + headers.append("set-cookie", cookie); + return cookie; + }, + setSignedCookie: async (key, value, secret, options$1) => { + const cookie = await serializeSignedCookie(key, value, secret, options$1); + headers.append("set-cookie", cookie); + return cookie; + }, + redirect: (url2) => { + headers.set("location", url2); + return new APIError("FOUND", void 0, headers); + }, + error: (status, body, headers$1) => { + return new APIError(status, body, headers$1); + }, + setStatus: (status) => { + responseStatus = status; + }, + json: (json3, routerResponse) => { + if (!context.asResponse) return json3; + return { + body: routerResponse?.body || json3, + routerResponse, + _flag: "json" + }; + }, + responseHeaders: headers, + get responseStatus() { + return responseStatus; + } + }; + for (const middleware of options.use || []) { + const response = await middleware({ + ...internalContext, + returnHeaders: true, + asResponse: false + }); + if (response.response) Object.assign(internalContext.context, response.response); + if (response.headers) response.headers.forEach((value, key) => { + internalContext.responseHeaders.set(key, value); + }); + } + return internalContext; + }; + } +}); + +// node_modules/.pnpm/better-call@1.1.8_zod@4.3.6/node_modules/better-call/dist/endpoint.mjs +function createEndpoint(pathOrOptions, handlerOrOptions, handlerOrNever) { + const path53 = typeof pathOrOptions === "string" ? pathOrOptions : void 0; + const options = typeof handlerOrOptions === "object" ? handlerOrOptions : pathOrOptions; + const handler = typeof handlerOrOptions === "function" ? handlerOrOptions : handlerOrNever; + if ((options.method === "GET" || options.method === "HEAD") && options.body) throw new BetterCallError("Body is not allowed with GET or HEAD methods"); + if (path53 && /\/{2,}/.test(path53)) throw new BetterCallError("Path cannot contain consecutive slashes"); + const internalHandler = async (...inputCtx) => { + const context = inputCtx[0] || {}; + const { data: internalContext, error: validationError } = await tryCatch(createInternalContext(context, { + options, + path: path53 + })); + if (validationError) { + if (!(validationError instanceof ValidationError)) throw validationError; + if (options.onValidationError) await options.onValidationError({ + message: validationError.message, + issues: validationError.issues + }); + throw new APIError(400, { + message: validationError.message, + code: "VALIDATION_ERROR" + }); + } + const response = await handler(internalContext).catch(async (e5) => { + if (isAPIError(e5)) { + const onAPIError = options.onAPIError; + if (onAPIError) await onAPIError(e5); + if (context.asResponse) return e5; + } + throw e5; + }); + const headers = internalContext.responseHeaders; + const status = internalContext.responseStatus; + return context.asResponse ? toResponse(response, { + headers, + status + }) : context.returnHeaders ? context.returnStatus ? { + headers, + response, + status + } : { + headers, + response + } : context.returnStatus ? { + response, + status + } : response; + }; + internalHandler.options = options; + internalHandler.path = path53; + return internalHandler; +} +var init_endpoint = __esm({ + "node_modules/.pnpm/better-call@1.1.8_zod@4.3.6/node_modules/better-call/dist/endpoint.mjs"() { + init_error2(); + init_utils9(); + init_to_response(); + init_context(); + createEndpoint.create = (opts) => { + return (path53, options, handler) => { + return createEndpoint(path53, { + ...options, + use: [...options?.use || [], ...opts?.use || []] + }, handler); + }; + }; + } +}); + +// node_modules/.pnpm/better-call@1.1.8_zod@4.3.6/node_modules/better-call/dist/middleware.mjs +function createMiddleware(optionsOrHandler, handler) { + const internalHandler = async (inputCtx) => { + const context = inputCtx; + const _handler = typeof optionsOrHandler === "function" ? optionsOrHandler : handler; + const internalContext = await createInternalContext(context, { + options: typeof optionsOrHandler === "function" ? {} : optionsOrHandler, + path: "/" + }); + if (!_handler) throw new Error("handler must be defined"); + const response = await _handler(internalContext); + const headers = internalContext.responseHeaders; + return context.returnHeaders ? { + headers, + response + } : response; + }; + internalHandler.options = typeof optionsOrHandler === "function" ? {} : optionsOrHandler; + return internalHandler; +} +var init_middleware = __esm({ + "node_modules/.pnpm/better-call@1.1.8_zod@4.3.6/node_modules/better-call/dist/middleware.mjs"() { + init_context(); + init_endpoint(); + createMiddleware.create = (opts) => { + function fn(optionsOrHandler, handler) { + if (typeof optionsOrHandler === "function") return createMiddleware({ use: opts?.use }, optionsOrHandler); + if (!handler) throw new Error("Middleware handler is required"); + return createMiddleware({ + ...optionsOrHandler, + method: "*", + use: [...opts?.use || [], ...optionsOrHandler.use || []] + }, handler); + } + return fn; + }; + } +}); + +// node_modules/.pnpm/better-call@1.1.8_zod@4.3.6/node_modules/better-call/dist/openapi.mjs +function getTypeFromZodType(zodType) { + switch (zodType.constructor.name) { + case "ZodString": + return "string"; + case "ZodNumber": + return "number"; + case "ZodBoolean": + return "boolean"; + case "ZodObject": + return "object"; + case "ZodArray": + return "array"; + default: + return "string"; + } +} +function getParameters(options) { + const parameters = []; + if (options.metadata?.openapi?.parameters) { + parameters.push(...options.metadata.openapi.parameters); + return parameters; + } + if (options.query instanceof ZodObject2) Object.entries(options.query.shape).forEach(([key, value]) => { + if (value instanceof ZodObject2) parameters.push({ + name: key, + in: "query", + schema: { + type: getTypeFromZodType(value), + ..."minLength" in value && value.minLength ? { minLength: value.minLength } : {}, + description: value.description + } + }); + }); + return parameters; +} +function getRequestBody(options) { + if (options.metadata?.openapi?.requestBody) return options.metadata.openapi.requestBody; + if (!options.body) return void 0; + if (options.body instanceof ZodObject2 || options.body instanceof ZodOptional2) { + const shape = options.body.shape; + if (!shape) return void 0; + const properties = {}; + const required2 = []; + Object.entries(shape).forEach(([key, value]) => { + if (value instanceof ZodObject2) { + properties[key] = { + type: getTypeFromZodType(value), + description: value.description + }; + if (!(value instanceof ZodOptional2)) required2.push(key); + } + }); + return { + required: options.body instanceof ZodOptional2 ? false : options.body ? true : false, + content: { "application/json": { schema: { + type: "object", + properties, + required: required2 + } } } + }; + } +} +function getResponse(responses) { + return { + "400": { + content: { "application/json": { schema: { + type: "object", + properties: { message: { type: "string" } }, + required: ["message"] + } } }, + description: "Bad Request. Usually due to missing parameters, or invalid parameters." + }, + "401": { + content: { "application/json": { schema: { + type: "object", + properties: { message: { type: "string" } }, + required: ["message"] + } } }, + description: "Unauthorized. Due to missing or invalid authentication." + }, + "403": { + content: { "application/json": { schema: { + type: "object", + properties: { message: { type: "string" } } + } } }, + description: "Forbidden. You do not have permission to access this resource or to perform this action." + }, + "404": { + content: { "application/json": { schema: { + type: "object", + properties: { message: { type: "string" } } + } } }, + description: "Not Found. The requested resource was not found." + }, + "429": { + content: { "application/json": { schema: { + type: "object", + properties: { message: { type: "string" } } + } } }, + description: "Too Many Requests. You have exceeded the rate limit. Try again later." + }, + "500": { + content: { "application/json": { schema: { + type: "object", + properties: { message: { type: "string" } } + } } }, + description: "Internal Server Error. This is a problem with the server that you cannot fix." + }, + ...responses + }; +} +async function generator(endpoints, config3) { + const components = { schemas: {} }; + Object.entries(endpoints).forEach(([_, value]) => { + const options = value.options; + if (!value.path || options.metadata?.SERVER_ONLY) return; + if (options.method === "GET") paths[value.path] = { get: { + tags: ["Default", ...options.metadata?.openapi?.tags || []], + description: options.metadata?.openapi?.description, + operationId: options.metadata?.openapi?.operationId, + security: [{ bearerAuth: [] }], + parameters: getParameters(options), + responses: getResponse(options.metadata?.openapi?.responses) + } }; + if (options.method === "POST") { + const body = getRequestBody(options); + paths[value.path] = { post: { + tags: ["Default", ...options.metadata?.openapi?.tags || []], + description: options.metadata?.openapi?.description, + operationId: options.metadata?.openapi?.operationId, + security: [{ bearerAuth: [] }], + parameters: getParameters(options), + ...body ? { requestBody: body } : { requestBody: { content: { "application/json": { schema: { + type: "object", + properties: {} + } } } } }, + responses: getResponse(options.metadata?.openapi?.responses) + } }; + } + }); + return { + openapi: "3.1.1", + info: { + title: "Better Auth", + description: "API Reference for your Better Auth Instance", + version: "1.1.0" + }, + components, + security: [{ apiKeyCookie: [] }], + servers: [{ url: config3?.url }], + tags: [{ + name: "Default", + description: "Default endpoints that are included with Better Auth by default. These endpoints are not part of any plugin." + }], + paths + }; +} +var paths, getHTML; +var init_openapi = __esm({ + "node_modules/.pnpm/better-call@1.1.8_zod@4.3.6/node_modules/better-call/dist/openapi.mjs"() { + init_zod(); + paths = {}; + getHTML = (apiReference, config3) => ` + + + Scalar API Reference + + + + + + + + +`; + } +}); + +// node_modules/.pnpm/rou3@0.7.12/node_modules/rou3/dist/index.mjs +function createRouter() { + return { + root: { key: "" }, + static: new NullProtoObj() + }; +} +function splitPath(path53) { + const [_, ...s5] = path53.split("/"); + return s5[s5.length - 1] === "" ? s5.slice(0, -1) : s5; +} +function getMatchParams(segments, paramsMap) { + const params = new NullProtoObj(); + for (const [index2, name] of paramsMap) { + const segment = index2 < 0 ? segments.slice(-(index2 + 1)).join("/") : segments[index2]; + if (typeof name === "string") params[name] = segment; + else { + const match = segment.match(name); + if (match) for (const key in match.groups) params[key] = match.groups[key]; + } + } + return params; +} +function addRoute(ctx, method = "", path53, data2) { + method = method.toUpperCase(); + if (path53.charCodeAt(0) !== 47) path53 = `/${path53}`; + path53 = path53.replace(/\\:/g, "%3A"); + const segments = splitPath(path53); + let node = ctx.root; + let _unnamedParamIndex = 0; + const paramsMap = []; + const paramsRegexp = []; + for (let i5 = 0; i5 < segments.length; i5++) { + let segment = segments[i5]; + if (segment.startsWith("**")) { + if (!node.wildcard) node.wildcard = { key: "**" }; + node = node.wildcard; + paramsMap.push([ + -(i5 + 1), + segment.split(":")[1] || "_", + segment.length === 2 + ]); + break; + } + if (segment === "*" || segment.includes(":")) { + if (!node.param) node.param = { key: "*" }; + node = node.param; + if (segment === "*") paramsMap.push([ + i5, + `_${_unnamedParamIndex++}`, + true + ]); + else if (segment.includes(":", 1)) { + const regexp = getParamRegexp(segment); + paramsRegexp[i5] = regexp; + node.hasRegexParam = true; + paramsMap.push([ + i5, + regexp, + false + ]); + } else paramsMap.push([ + i5, + segment.slice(1), + false + ]); + continue; + } + if (segment === "\\*") segment = segments[i5] = "*"; + else if (segment === "\\*\\*") segment = segments[i5] = "**"; + const child = node.static?.[segment]; + if (child) node = child; + else { + const staticNode = { key: segment }; + if (!node.static) node.static = new NullProtoObj(); + node.static[segment] = staticNode; + node = staticNode; + } + } + const hasParams = paramsMap.length > 0; + if (!node.methods) node.methods = new NullProtoObj(); + node.methods[method] ??= []; + node.methods[method].push({ + data: data2 || null, + paramsRegexp, + paramsMap: hasParams ? paramsMap : void 0 + }); + if (!hasParams) ctx.static["/" + segments.join("/")] = node; +} +function getParamRegexp(segment) { + const regex = segment.replace(/:(\w+)/g, (_, id) => `(?<${id}>[^/]+)`).replace(/\./g, "\\."); + return /* @__PURE__ */ new RegExp(`^${regex}$`); +} +function findRoute(ctx, method = "", path53, opts) { + if (path53.charCodeAt(path53.length - 1) === 47) path53 = path53.slice(0, -1); + const staticNode = ctx.static[path53]; + if (staticNode && staticNode.methods) { + const staticMatch = staticNode.methods[method] || staticNode.methods[""]; + if (staticMatch !== void 0) return staticMatch[0]; + } + const segments = splitPath(path53); + const match = _lookupTree(ctx, ctx.root, method, segments, 0)?.[0]; + if (match === void 0) return; + if (opts?.params === false) return match; + return { + data: match.data, + params: match.paramsMap ? getMatchParams(segments, match.paramsMap) : void 0 + }; +} +function _lookupTree(ctx, node, method, segments, index2) { + if (index2 === segments.length) { + if (node.methods) { + const match = node.methods[method] || node.methods[""]; + if (match) return match; + } + if (node.param && node.param.methods) { + const match = node.param.methods[method] || node.param.methods[""]; + if (match) { + const pMap = match[0].paramsMap; + if (pMap?.[pMap?.length - 1]?.[2]) return match; + } + } + if (node.wildcard && node.wildcard.methods) { + const match = node.wildcard.methods[method] || node.wildcard.methods[""]; + if (match) { + const pMap = match[0].paramsMap; + if (pMap?.[pMap?.length - 1]?.[2]) return match; + } + } + return; + } + const segment = segments[index2]; + if (node.static) { + const staticChild = node.static[segment]; + if (staticChild) { + const match = _lookupTree(ctx, staticChild, method, segments, index2 + 1); + if (match) return match; + } + } + if (node.param) { + const match = _lookupTree(ctx, node.param, method, segments, index2 + 1); + if (match) { + if (node.param.hasRegexParam) { + const exactMatch = match.find((m5) => m5.paramsRegexp[index2]?.test(segment)) || match.find((m5) => !m5.paramsRegexp[index2]); + return exactMatch ? [exactMatch] : void 0; + } + return match; + } + } + if (node.wildcard && node.wildcard.methods) return node.wildcard.methods[method] || node.wildcard.methods[""]; +} +function findAllRoutes(ctx, method = "", path53, opts) { + if (path53.charCodeAt(path53.length - 1) === 47) path53 = path53.slice(0, -1); + const segments = splitPath(path53); + const matches = _findAll(ctx, ctx.root, method, segments, 0); + if (opts?.params === false) return matches; + return matches.map((m5) => { + return { + data: m5.data, + params: m5.paramsMap ? getMatchParams(segments, m5.paramsMap) : void 0 + }; + }); +} +function _findAll(ctx, node, method, segments, index2, matches = []) { + const segment = segments[index2]; + if (node.wildcard && node.wildcard.methods) { + const match = node.wildcard.methods[method] || node.wildcard.methods[""]; + if (match) matches.push(...match); + } + if (node.param) { + _findAll(ctx, node.param, method, segments, index2 + 1, matches); + if (index2 === segments.length && node.param.methods) { + const match = node.param.methods[method] || node.param.methods[""]; + if (match) { + const pMap = match[0].paramsMap; + if (pMap?.[pMap?.length - 1]?.[2]) matches.push(...match); + } + } + } + const staticChild = node.static?.[segment]; + if (staticChild) _findAll(ctx, staticChild, method, segments, index2 + 1, matches); + if (index2 === segments.length && node.methods) { + const match = node.methods[method] || node.methods[""]; + if (match) matches.push(...match); + } + return matches; +} +var NullProtoObj; +var init_dist2 = __esm({ + "node_modules/.pnpm/rou3@0.7.12/node_modules/rou3/dist/index.mjs"() { + NullProtoObj = /* @__PURE__ */ (() => { + const e5 = function() { + }; + return e5.prototype = /* @__PURE__ */ Object.create(null), Object.freeze(e5.prototype), e5; + })(); + } +}); + +// node_modules/.pnpm/better-call@1.1.8_zod@4.3.6/node_modules/better-call/dist/router.mjs +var createRouter$1; +var init_router = __esm({ + "node_modules/.pnpm/better-call@1.1.8_zod@4.3.6/node_modules/better-call/dist/router.mjs"() { + init_utils9(); + init_to_response(); + init_endpoint(); + init_openapi(); + init_dist2(); + createRouter$1 = (endpoints, config3) => { + if (!config3?.openapi?.disabled) { + const openapi = { + path: "/api/reference", + ...config3?.openapi + }; + endpoints["openapi"] = createEndpoint(openapi.path, { method: "GET" }, async (c5) => { + const schema2 = await generator(endpoints); + return new Response(getHTML(schema2, openapi.scalar), { headers: { "Content-Type": "text/html" } }); + }); + } + const router2 = createRouter(); + const middlewareRouter = createRouter(); + for (const endpoint of Object.values(endpoints)) { + if (!endpoint.options || !endpoint.path) continue; + if (endpoint.options?.metadata?.SERVER_ONLY) continue; + const methods2 = Array.isArray(endpoint.options?.method) ? endpoint.options.method : [endpoint.options?.method]; + for (const method of methods2) addRoute(router2, method, endpoint.path, endpoint); + } + if (config3?.routerMiddleware?.length) for (const { path: path53, middleware } of config3.routerMiddleware) addRoute(middlewareRouter, "*", path53, middleware); + const processRequest = async (request) => { + const url2 = new URL(request.url); + const pathname = url2.pathname; + const path53 = config3?.basePath && config3.basePath !== "/" ? pathname.split(config3.basePath).reduce((acc, curr, index2) => { + if (index2 !== 0) if (index2 > 1) acc.push(`${config3.basePath}${curr}`); + else acc.push(curr); + return acc; + }, []).join("") : url2.pathname; + if (!path53?.length) return new Response(null, { + status: 404, + statusText: "Not Found" + }); + if (/\/{2,}/.test(path53)) return new Response(null, { + status: 404, + statusText: "Not Found" + }); + const route = findRoute(router2, request.method, path53); + if (path53.endsWith("/") !== route?.data?.path?.endsWith("/") && !config3?.skipTrailingSlashes) return new Response(null, { + status: 404, + statusText: "Not Found" + }); + if (!route?.data) return new Response(null, { + status: 404, + statusText: "Not Found" + }); + const query = {}; + url2.searchParams.forEach((value, key) => { + if (key in query) if (Array.isArray(query[key])) query[key].push(value); + else query[key] = [query[key], value]; + else query[key] = value; + }); + const handler = route.data; + try { + const allowedMediaTypes = handler.options.metadata?.allowedMediaTypes || config3?.allowedMediaTypes; + const context = { + path: path53, + method: request.method, + headers: request.headers, + params: route.params ? JSON.parse(JSON.stringify(route.params)) : {}, + request, + body: handler.options.disableBody ? void 0 : await getBody(handler.options.cloneRequest ? request.clone() : request, allowedMediaTypes), + query, + _flag: "router", + asResponse: true, + context: config3?.routerContext + }; + const middlewareRoutes = findAllRoutes(middlewareRouter, "*", path53); + if (middlewareRoutes?.length) for (const { data: middleware, params } of middlewareRoutes) { + const res = await middleware({ + ...context, + params, + asResponse: false + }); + if (res instanceof Response) return res; + } + return await handler(context); + } catch (error50) { + if (config3?.onError) try { + const errorResponse = await config3.onError(error50); + if (errorResponse instanceof Response) return toResponse(errorResponse); + } catch (error$1) { + if (isAPIError(error$1)) return toResponse(error$1); + throw error$1; + } + if (config3?.throwError) throw error50; + if (isAPIError(error50)) return toResponse(error50); + console.error(`# SERVER_ERROR: `, error50); + return new Response(null, { + status: 500, + statusText: "Internal Server Error" + }); + } + }; + return { + handler: async (request) => { + const onReq = await config3?.onRequest?.(request); + if (onReq instanceof Response) return onReq; + const res = await processRequest(isRequest(onReq) ? onReq : request); + const onRes = await config3?.onResponse?.(res); + if (onRes instanceof Response) return onRes; + return res; + }, + endpoints + }; + }; + } +}); + +// node_modules/.pnpm/better-call@1.1.8_zod@4.3.6/node_modules/better-call/dist/index.mjs +var init_dist3 = __esm({ + "node_modules/.pnpm/better-call@1.1.8_zod@4.3.6/node_modules/better-call/dist/index.mjs"() { + init_error2(); + init_to_response(); + init_cookies(); + init_context(); + init_endpoint(); + init_middleware(); + init_openapi(); + init_router(); + } +}); + +// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/db/schema.mjs +function parseOutputData(data2, schema2) { + const fields = schema2.fields; + const parsedData = {}; + for (const key in data2) { + const field = fields[key]; + if (!field) { + parsedData[key] = data2[key]; + continue; + } + if (field.returned === false && key !== "id") continue; + parsedData[key] = data2[key]; + } + return parsedData; +} +function getFields(options, table, mode) { + const cacheKey = `${table}:${mode}`; + if (!cache6.has(options)) cache6.set(options, /* @__PURE__ */ new Map()); + const tableCache = cache6.get(options); + if (tableCache.has(cacheKey)) return tableCache.get(cacheKey); + const coreSchema2 = mode === "output" ? getAuthTables(options)[table]?.fields ?? {} : {}; + const additionalFields = table === "user" || table === "session" || table === "account" ? options[table]?.additionalFields : void 0; + let schema2 = { + ...coreSchema2, + ...additionalFields ?? {} + }; + for (const plugin of options.plugins || []) if (plugin.schema && plugin.schema[table]) schema2 = { + ...schema2, + ...plugin.schema[table].fields + }; + tableCache.set(cacheKey, schema2); + return schema2; +} +function parseUserOutput(options, user) { + return parseOutputData(user, { fields: getFields(options, "user", "output") }); +} +function parseSessionOutput(options, session) { + return parseOutputData(session, { fields: getFields(options, "session", "output") }); +} +function parseAccountOutput(options, account) { + const { accessToken: _accessToken, refreshToken: _refreshToken, idToken: _idToken, accessTokenExpiresAt: _accessTokenExpiresAt, refreshTokenExpiresAt: _refreshTokenExpiresAt, password: _password, ...rest } = parseOutputData(account, { fields: getFields(options, "account", "output") }); + return rest; +} +function parseInputData(data2, schema2) { + const action = schema2.action || "create"; + const fields = schema2.fields; + const parsedData = Object.assign(/* @__PURE__ */ Object.create(null), null); + for (const key in fields) { + if (key in data2) { + if (fields[key].input === false) { + if (fields[key].defaultValue !== void 0) { + if (action !== "update") { + parsedData[key] = fields[key].defaultValue; + continue; + } + } + if (data2[key]) throw new APIError("BAD_REQUEST", { message: `${key} is not allowed to be set` }); + continue; + } + if (fields[key].validator?.input && data2[key] !== void 0) { + const result = fields[key].validator.input["~standard"].validate(data2[key]); + if (result instanceof Promise) throw new APIError("INTERNAL_SERVER_ERROR", { message: "Async validation is not supported for additional fields" }); + if ("issues" in result && result.issues) throw new APIError("BAD_REQUEST", { message: result.issues[0]?.message || "Validation Error" }); + parsedData[key] = result.value; + continue; + } + if (fields[key].transform?.input && data2[key] !== void 0) { + parsedData[key] = fields[key].transform?.input(data2[key]); + continue; + } + parsedData[key] = data2[key]; + continue; + } + if (fields[key].defaultValue !== void 0 && action === "create") { + if (typeof fields[key].defaultValue === "function") { + parsedData[key] = fields[key].defaultValue(); + continue; + } + parsedData[key] = fields[key].defaultValue; + continue; + } + if (fields[key].required && action === "create") throw new APIError("BAD_REQUEST", { message: `${key} is required` }); + } + return parsedData; +} +function parseUserInput(options, user = {}, action) { + return parseInputData(user, { + fields: getFields(options, "user", "input"), + action + }); +} +function parseAdditionalUserInput(options, user) { + const schema2 = getFields(options, "user", "input"); + return parseInputData(user || {}, { fields: schema2 }); +} +function parseAccountInput(options, account) { + return parseInputData(account, { fields: getFields(options, "account", "input") }); +} +function parseSessionInput(options, session) { + return parseInputData(session, { fields: getFields(options, "session", "input") }); +} +function mergeSchema(schema2, newSchema) { + if (!newSchema) return schema2; + for (const table in newSchema) { + const newModelName = newSchema[table]?.modelName; + if (newModelName) schema2[table].modelName = newModelName; + for (const field in schema2[table].fields) { + const newField = newSchema[table]?.fields?.[field]; + if (!newField) continue; + schema2[table].fields[field].fieldName = newField; + } + } + return schema2; +} +var cache6; +var init_schema4 = __esm({ + "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/db/schema.mjs"() { + init_db3(); + init_dist3(); + cache6 = /* @__PURE__ */ new WeakMap(); + } +}); + +// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/cookies/session-store.mjs +function parseCookiesFromContext(ctx) { + const cookieHeader = ctx.headers?.get("cookie"); + if (!cookieHeader) return {}; + const cookies = {}; + const pairs = cookieHeader.split("; "); + for (const pair of pairs) { + const [name, ...valueParts] = pair.split("="); + if (name && valueParts.length > 0) cookies[name] = valueParts.join("="); + } + return cookies; +} +function getChunkIndex(cookieName) { + const parts = cookieName.split("."); + const lastPart = parts[parts.length - 1]; + const index2 = parseInt(lastPart || "0", 10); + return isNaN(index2) ? 0 : index2; +} +function readExistingChunks(cookieName, ctx) { + const chunks = {}; + const cookies = parseCookiesFromContext(ctx); + for (const [name, value] of Object.entries(cookies)) if (name.startsWith(cookieName)) chunks[name] = value; + return chunks; +} +function joinChunks(chunks) { + return Object.keys(chunks).sort((a5, b6) => { + return getChunkIndex(a5) - getChunkIndex(b6); + }).map((key) => chunks[key]).join(""); +} +function chunkCookie(storeName, cookie, chunks, logger4) { + const chunkCount = Math.ceil(cookie.value.length / CHUNK_SIZE); + if (chunkCount === 1) { + chunks[cookie.name] = cookie.value; + return [cookie]; + } + const cookies = []; + for (let i5 = 0; i5 < chunkCount; i5++) { + const name = `${cookie.name}.${i5}`; + const start = i5 * CHUNK_SIZE; + const value = cookie.value.substring(start, start + CHUNK_SIZE); + cookies.push({ + ...cookie, + name, + value + }); + chunks[name] = value; + } + logger4.debug(`CHUNKING_${storeName.toUpperCase()}_COOKIE`, { + message: `${storeName} cookie exceeds allowed ${ALLOWED_COOKIE_SIZE} bytes.`, + emptyCookieSize: ESTIMATED_EMPTY_COOKIE_SIZE, + valueSize: cookie.value.length, + chunkCount, + chunks: cookies.map((c5) => c5.value.length + ESTIMATED_EMPTY_COOKIE_SIZE) + }); + return cookies; +} +function getCleanCookies(chunks, cookieOptions) { + const cleanedChunks = {}; + for (const name in chunks) cleanedChunks[name] = { + name, + value: "", + attributes: { + ...cookieOptions, + maxAge: 0 + } + }; + return cleanedChunks; +} +function getChunkedCookie(ctx, cookieName) { + const value = ctx.getCookie(cookieName); + if (value) return value; + const chunks = []; + const cookieHeader = ctx.headers?.get("cookie"); + if (!cookieHeader) return null; + const cookies = {}; + const pairs = cookieHeader.split("; "); + for (const pair of pairs) { + const [name, ...valueParts] = pair.split("="); + if (name && valueParts.length > 0) cookies[name] = valueParts.join("="); + } + for (const [name, val] of Object.entries(cookies)) if (name.startsWith(cookieName + ".")) { + const indexStr = name.split(".").at(-1); + const index2 = parseInt(indexStr || "0", 10); + if (!isNaN(index2)) chunks.push({ + index: index2, + value: val + }); + } + if (chunks.length > 0) { + chunks.sort((a5, b6) => a5.index - b6.index); + return chunks.map((c5) => c5.value).join(""); + } + return null; +} +async function setAccountCookie(c5, accountData) { + const accountDataCookie = c5.context.authCookies.accountData; + const options = { + maxAge: 300, + ...accountDataCookie.attributes + }; + const data2 = await symmetricEncodeJWT(accountData, c5.context.secret, "better-auth-account", options.maxAge); + if (data2.length > ALLOWED_COOKIE_SIZE) { + const accountStore = createAccountStore(accountDataCookie.name, options, c5); + const cookies = accountStore.chunk(data2, options); + accountStore.setCookies(cookies); + } else { + const accountStore = createAccountStore(accountDataCookie.name, options, c5); + if (accountStore.hasChunks()) { + const cleanCookies = accountStore.clean(); + accountStore.setCookies(cleanCookies); + } + c5.setCookie(accountDataCookie.name, data2, options); + } +} +async function getAccountCookie(c5) { + const accountCookie = getChunkedCookie(c5, c5.context.authCookies.accountData.name); + if (accountCookie) { + const accountData = safeJSONParse(await symmetricDecodeJWT(accountCookie, c5.context.secret, "better-auth-account")); + if (accountData) return accountData; + } + return null; +} +var ALLOWED_COOKIE_SIZE, ESTIMATED_EMPTY_COOKIE_SIZE, CHUNK_SIZE, storeFactory, createSessionStore, createAccountStore, getSessionQuerySchema; +var init_session_store = __esm({ + "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/cookies/session-store.mjs"() { + init_jwt(); + init_crypto(); + init_utils7(); + init_zod(); + ALLOWED_COOKIE_SIZE = 4096; + ESTIMATED_EMPTY_COOKIE_SIZE = 200; + CHUNK_SIZE = ALLOWED_COOKIE_SIZE - ESTIMATED_EMPTY_COOKIE_SIZE; + storeFactory = (storeName) => (cookieName, cookieOptions, ctx) => { + const chunks = readExistingChunks(cookieName, ctx); + const logger4 = ctx.context.logger; + return { + getValue() { + return joinChunks(chunks); + }, + hasChunks() { + return Object.keys(chunks).length > 0; + }, + chunk(value, options) { + const cleanedChunks = getCleanCookies(chunks, cookieOptions); + for (const name in chunks) delete chunks[name]; + const cookies = cleanedChunks; + const chunked = chunkCookie(storeName, { + name: cookieName, + value, + attributes: { + ...cookieOptions, + ...options + } + }, chunks, logger4); + for (const chunk of chunked) cookies[chunk.name] = chunk; + return Object.values(cookies); + }, + clean() { + const cleanedChunks = getCleanCookies(chunks, cookieOptions); + for (const name in chunks) delete chunks[name]; + return Object.values(cleanedChunks); + }, + setCookies(cookies) { + for (const cookie of cookies) ctx.setCookie(cookie.name, cookie.value, cookie.attributes); + } + }; + }; + createSessionStore = storeFactory("Session"); + createAccountStore = storeFactory("Account"); + getSessionQuerySchema = optional(object({ + disableCookieCache: coerce_exports.boolean().meta({ description: "Disable cookie cache and fetch session from database" }).optional(), + disableRefresh: coerce_exports.boolean().meta({ description: "Disable session refresh. Useful for checking session status, without updating the session" }).optional() + })); + } +}); + +// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/utils/is-promise.mjs +function isPromise(obj) { + return !!obj && (typeof obj === "object" || typeof obj === "function") && typeof obj.then === "function"; +} +var init_is_promise = __esm({ + "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/utils/is-promise.mjs"() { + } +}); + +// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/utils/time.mjs +function parse4(value) { + const match = REGEX2.exec(value); + if (!match || match[4] && match[1]) throw new TypeError(`Invalid time string format: "${value}". Use formats like "7d", "30m", "1 hour", etc.`); + const n5 = parseFloat(match[2]); + const unit = match[3].toLowerCase(); + let result; + switch (unit) { + case "years": + case "year": + case "yrs": + case "yr": + case "y": + result = n5 * YEAR; + break; + case "months": + case "month": + case "mo": + result = n5 * MONTH; + break; + case "weeks": + case "week": + case "w": + result = n5 * WEEK; + break; + case "days": + case "day": + case "d": + result = n5 * DAY; + break; + case "hours": + case "hour": + case "hrs": + case "hr": + case "h": + result = n5 * HOUR; + break; + case "minutes": + case "minute": + case "mins": + case "min": + case "m": + result = n5 * MIN; + break; + case "seconds": + case "second": + case "secs": + case "sec": + case "s": + result = n5 * SEC; + break; + default: + throw new TypeError(`Unknown time unit: "${unit}"`); + } + if (match[1] === "-" || match[4] === "ago") return -result; + return result; +} +function sec(value) { + return Math.round(parse4(value) / 1e3); +} +var SEC, MIN, HOUR, DAY, WEEK, MONTH, YEAR, REGEX2; +var init_time2 = __esm({ + "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/utils/time.mjs"() { + SEC = 1e3; + MIN = SEC * 60; + HOUR = MIN * 60; + DAY = HOUR * 24; + WEEK = DAY * 7; + MONTH = DAY * 30; + YEAR = DAY * 365.25; + REGEX2 = /^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|months?|mo|years?|yrs?|y)(?: (ago|from now))?$/i; + } +}); + +// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/cookies/cookie-utils.mjs +var SECURE_COOKIE_PREFIX; +var init_cookie_utils = __esm({ + "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/cookies/cookie-utils.mjs"() { + SECURE_COOKIE_PREFIX = "__Secure-"; + } +}); + +// node_modules/.pnpm/@better-auth+utils@0.3.0/node_modules/@better-auth/utils/dist/binary.mjs +var decoders, encoder2, binary; +var init_binary = __esm({ + "node_modules/.pnpm/@better-auth+utils@0.3.0/node_modules/@better-auth/utils/dist/binary.mjs"() { + decoders = /* @__PURE__ */ new Map(); + encoder2 = new TextEncoder(); + binary = { + decode: (data2, encoding = "utf-8") => { + if (!decoders.has(encoding)) { + decoders.set(encoding, new TextDecoder(encoding)); + } + const decoder2 = decoders.get(encoding); + return decoder2.decode(data2); + }, + encode: encoder2.encode + }; + } +}); + +// node_modules/.pnpm/@better-auth+utils@0.3.0/node_modules/@better-auth/utils/dist/hmac.mjs +var createHMAC; +var init_hmac2 = __esm({ + "node_modules/.pnpm/@better-auth+utils@0.3.0/node_modules/@better-auth/utils/dist/hmac.mjs"() { + init_hex(); + init_base642(); + init_dist(); + createHMAC = (algorithm2 = "SHA-256", encoding = "none") => { + const hmac3 = { + importKey: async (key, keyUsage) => { + return getWebcryptoSubtle().importKey( + "raw", + typeof key === "string" ? new TextEncoder().encode(key) : key, + { name: "HMAC", hash: { name: algorithm2 } }, + false, + [keyUsage] + ); + }, + sign: async (hmacKey, data2) => { + if (typeof hmacKey === "string") { + hmacKey = await hmac3.importKey(hmacKey, "sign"); + } + const signature = await getWebcryptoSubtle().sign( + "HMAC", + hmacKey, + typeof data2 === "string" ? new TextEncoder().encode(data2) : data2 + ); + if (encoding === "hex") { + return hex3.encode(signature); + } + if (encoding === "base64" || encoding === "base64url" || encoding === "base64urlnopad") { + return base64Url.encode(signature, { + padding: encoding !== "base64urlnopad" + }); + } + return signature; + }, + verify: async (hmacKey, data2, signature) => { + if (typeof hmacKey === "string") { + hmacKey = await hmac3.importKey(hmacKey, "verify"); + } + if (encoding === "hex") { + signature = hex3.decode(signature); + } + if (encoding === "base64" || encoding === "base64url" || encoding === "base64urlnopad") { + signature = await base643.decode(signature); + } + return getWebcryptoSubtle().verify( + "HMAC", + hmacKey, + typeof signature === "string" ? new TextEncoder().encode(signature) : signature, + typeof data2 === "string" ? new TextEncoder().encode(data2) : data2 + ); + } + }; + return hmac3; + }; + } +}); + +// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/cookies/index.mjs +function createCookieGetter(options) { + const secureCookiePrefix = (options.advanced?.useSecureCookies !== void 0 ? options.advanced?.useSecureCookies : options.baseURL ? options.baseURL.startsWith("https://") ? true : false : isProduction) ? SECURE_COOKIE_PREFIX : ""; + const crossSubdomainEnabled = !!options.advanced?.crossSubDomainCookies?.enabled; + const domain2 = crossSubdomainEnabled ? options.advanced?.crossSubDomainCookies?.domain || (options.baseURL ? new URL(options.baseURL).hostname : void 0) : void 0; + if (crossSubdomainEnabled && !domain2) throw new BetterAuthError("baseURL is required when crossSubdomainCookies are enabled"); + function createCookie(cookieName, overrideAttributes = {}) { + const prefix = options.advanced?.cookiePrefix || "better-auth"; + const name = options.advanced?.cookies?.[cookieName]?.name || `${prefix}.${cookieName}`; + const attributes = options.advanced?.cookies?.[cookieName]?.attributes; + return { + name: `${secureCookiePrefix}${name}`, + attributes: { + secure: !!secureCookiePrefix, + sameSite: "lax", + path: "/", + httpOnly: true, + ...crossSubdomainEnabled ? { domain: domain2 } : {}, + ...options.advanced?.defaultCookieAttributes, + ...overrideAttributes, + ...attributes + } + }; + } + return createCookie; +} +function getCookies(options) { + const createCookie = createCookieGetter(options); + const sessionToken = createCookie("session_token", { maxAge: options.session?.expiresIn || sec("7d") }); + const sessionData = createCookie("session_data", { maxAge: options.session?.cookieCache?.maxAge || 300 }); + const accountData = createCookie("account_data", { maxAge: options.session?.cookieCache?.maxAge || 300 }); + const dontRememberToken = createCookie("dont_remember"); + return { + sessionToken: { + name: sessionToken.name, + attributes: sessionToken.attributes + }, + sessionData: { + name: sessionData.name, + attributes: sessionData.attributes + }, + dontRememberToken: { + name: dontRememberToken.name, + attributes: dontRememberToken.attributes + }, + accountData: { + name: accountData.name, + attributes: accountData.attributes + } + }; +} +async function setCookieCache(ctx, session, dontRememberMe) { + if (!ctx.context.options.session?.cookieCache?.enabled) return; + const filteredSession = filterOutputFields(session.session, ctx.context.options.session?.additionalFields); + const filteredUser = parseUserOutput(ctx.context.options, session.user); + const versionConfig = ctx.context.options.session?.cookieCache?.version; + let version3 = "1"; + if (versionConfig) { + if (typeof versionConfig === "string") version3 = versionConfig; + else if (typeof versionConfig === "function") { + const result = versionConfig(session.session, session.user); + version3 = isPromise(result) ? await result : result; + } + } + const sessionData = { + session: filteredSession, + user: filteredUser, + updatedAt: Date.now(), + version: version3 + }; + const options = { + ...ctx.context.authCookies.sessionData.attributes, + maxAge: dontRememberMe ? void 0 : ctx.context.authCookies.sessionData.attributes.maxAge + }; + const expiresAtDate = getDate(options.maxAge || 60, "sec").getTime(); + const strategy = ctx.context.options.session?.cookieCache?.strategy || "compact"; + let data2; + if (strategy === "jwe") data2 = await symmetricEncodeJWT(sessionData, ctx.context.secret, "better-auth-session", options.maxAge || 300); + else if (strategy === "jwt") data2 = await signJWT(sessionData, ctx.context.secret, options.maxAge || 300); + else data2 = base64Url.encode(JSON.stringify({ + session: sessionData, + expiresAt: expiresAtDate, + signature: await createHMAC("SHA-256", "base64urlnopad").sign(ctx.context.secret, JSON.stringify({ + ...sessionData, + expiresAt: expiresAtDate + })) + }), { padding: false }); + if (data2.length > 4093) { + const sessionStore = createSessionStore(ctx.context.authCookies.sessionData.name, options, ctx); + const cookies = sessionStore.chunk(data2, options); + sessionStore.setCookies(cookies); + } else { + const sessionStore = createSessionStore(ctx.context.authCookies.sessionData.name, options, ctx); + if (sessionStore.hasChunks()) { + const cleanCookies = sessionStore.clean(); + sessionStore.setCookies(cleanCookies); + } + ctx.setCookie(ctx.context.authCookies.sessionData.name, data2, options); + } + if (ctx.context.options.account?.storeAccountCookie) { + const accountData = await getAccountCookie(ctx); + if (accountData) await setAccountCookie(ctx, accountData); + } +} +async function setSessionCookie(ctx, session, dontRememberMe, overrides) { + const dontRememberMeCookie = await ctx.getSignedCookie(ctx.context.authCookies.dontRememberToken.name, ctx.context.secret); + dontRememberMe = dontRememberMe !== void 0 ? dontRememberMe : !!dontRememberMeCookie; + const options = ctx.context.authCookies.sessionToken.attributes; + const maxAge = dontRememberMe ? void 0 : ctx.context.sessionConfig.expiresIn; + await ctx.setSignedCookie(ctx.context.authCookies.sessionToken.name, session.session.token, ctx.context.secret, { + ...options, + maxAge, + ...overrides + }); + if (dontRememberMe) await ctx.setSignedCookie(ctx.context.authCookies.dontRememberToken.name, "true", ctx.context.secret, ctx.context.authCookies.dontRememberToken.attributes); + await setCookieCache(ctx, session, dontRememberMe); + ctx.context.setNewSession(session); +} +function expireCookie(ctx, cookie) { + ctx.setCookie(cookie.name, "", { + ...cookie.attributes, + maxAge: 0 + }); +} +function deleteSessionCookie(ctx, skipDontRememberMe) { + expireCookie(ctx, ctx.context.authCookies.sessionToken); + expireCookie(ctx, ctx.context.authCookies.sessionData); + if (ctx.context.options.account?.storeAccountCookie) { + expireCookie(ctx, ctx.context.authCookies.accountData); + const accountStore = createAccountStore(ctx.context.authCookies.accountData.name, ctx.context.authCookies.accountData.attributes, ctx); + const cleanCookies$1 = accountStore.clean(); + accountStore.setCookies(cleanCookies$1); + } + if (ctx.context.oauthConfig.storeStateStrategy === "cookie") expireCookie(ctx, ctx.context.createAuthCookie("oauth_state")); + const sessionStore = createSessionStore(ctx.context.authCookies.sessionData.name, ctx.context.authCookies.sessionData.attributes, ctx); + const cleanCookies = sessionStore.clean(); + sessionStore.setCookies(cleanCookies); + if (!skipDontRememberMe) expireCookie(ctx, ctx.context.authCookies.dontRememberToken); +} +var init_cookies2 = __esm({ + "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/cookies/index.mjs"() { + init_date2(); + init_schema4(); + init_jwt(); + init_session_store(); + init_is_promise(); + init_time2(); + init_cookie_utils(); + init_env(); + init_error(); + init_utils7(); + init_base642(); + init_binary(); + init_hmac2(); + } +}); + +// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/state.mjs +async function generateGenericState(c5, stateData, settings) { + const state2 = generateRandomString(32); + if (c5.context.oauthConfig.storeStateStrategy === "cookie") { + const encryptedData = await symmetricEncrypt({ + key: c5.context.secret, + data: JSON.stringify(stateData) + }); + const stateCookie$1 = c5.context.createAuthCookie(settings?.cookieName ?? "oauth_state", { maxAge: 600 }); + c5.setCookie(stateCookie$1.name, encryptedData, stateCookie$1.attributes); + return { + state: state2, + codeVerifier: stateData.codeVerifier + }; + } + const stateCookie = c5.context.createAuthCookie(settings?.cookieName ?? "state", { maxAge: 300 }); + await c5.setSignedCookie(stateCookie.name, state2, c5.context.secret, stateCookie.attributes); + const expiresAt = /* @__PURE__ */ new Date(); + expiresAt.setMinutes(expiresAt.getMinutes() + 10); + const verification = await c5.context.internalAdapter.createVerificationValue({ + value: JSON.stringify(stateData), + identifier: state2, + expiresAt + }); + if (!verification) throw new StateError("Unable to create verification. Make sure the database adapter is properly working and there is a verification table in the database", { code: "state_generation_error" }); + return { + state: verification.identifier, + codeVerifier: stateData.codeVerifier + }; +} +async function parseGenericState(c5, state2, settings) { + const storeStateStrategy = c5.context.oauthConfig.storeStateStrategy; + let parsedData; + if (storeStateStrategy === "cookie") { + const stateCookie = c5.context.createAuthCookie(settings?.cookieName ?? "oauth_state"); + const encryptedData = c5.getCookie(stateCookie.name); + if (!encryptedData) throw new StateError("State mismatch: auth state cookie not found", { + code: "state_mismatch", + details: { state: state2 } + }); + try { + const decryptedData = await symmetricDecrypt({ + key: c5.context.secret, + data: encryptedData + }); + parsedData = stateDataSchema.parse(JSON.parse(decryptedData)); + } catch (error50) { + throw new StateError("State invalid: Failed to decrypt or parse auth state", { + code: "state_invalid", + details: { state: state2 }, + cause: error50 + }); + } + expireCookie(c5, stateCookie); + } else { + const data2 = await c5.context.internalAdapter.findVerificationValue(state2); + if (!data2) throw new StateError("State mismatch: verification not found", { + code: "state_mismatch", + details: { state: state2 } + }); + parsedData = stateDataSchema.parse(JSON.parse(data2.value)); + const stateCookie = c5.context.createAuthCookie(settings?.cookieName ?? "state"); + const stateCookieValue = await c5.getSignedCookie(stateCookie.name, c5.context.secret); + if (!c5.context.oauthConfig.skipStateCookieCheck && (!stateCookieValue || stateCookieValue !== state2)) throw new StateError("State mismatch: State not persisted correctly", { + code: "state_security_mismatch", + details: { state: state2 } + }); + expireCookie(c5, stateCookie); + await c5.context.internalAdapter.deleteVerificationValue(data2.id); + } + if (parsedData.expiresAt < Date.now()) throw new StateError("Invalid state: request expired", { + code: "state_mismatch", + details: { expiresAt: parsedData.expiresAt } + }); + return parsedData; +} +var stateDataSchema, StateError; +var init_state = __esm({ + "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/state.mjs"() { + init_random2(); + init_crypto(); + init_cookies2(); + init_error(); + init_zod(); + stateDataSchema = looseObject({ + callbackURL: string2(), + codeVerifier: string2(), + errorURL: string2().optional(), + newUserURL: string2().optional(), + expiresAt: number2(), + link: object({ + email: string2(), + userId: coerce_exports.string() + }).optional(), + requestSignUp: boolean3().optional() + }); + StateError = class extends BetterAuthError { + code; + details; + constructor(message2, options) { + super(message2, options); + this.code = options.code; + this.details = options.details; + } + }; + } +}); + +// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/context/global.mjs +function __getBetterAuthGlobal() { + if (!globalThis[symbol2]) { + globalThis[symbol2] = { + version: __betterAuthVersion, + epoch: 1, + context: __context + }; + bind = globalThis[symbol2]; + } + bind = globalThis[symbol2]; + if (bind.version !== __betterAuthVersion) { + bind.version = __betterAuthVersion; + bind.epoch++; + } + return globalThis[symbol2]; +} +function getBetterAuthVersion() { + return __getBetterAuthGlobal().version; +} +var symbol2, bind, __context, __betterAuthVersion; +var init_global = __esm({ + "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/context/global.mjs"() { + symbol2 = /* @__PURE__ */ Symbol.for("better-auth:global"); + bind = null; + __context = {}; + __betterAuthVersion = "1.4.18"; + } +}); + +// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/async_hooks/index.mjs +async function getAsyncLocalStorage() { + const mod = await AsyncLocalStoragePromise; + if (mod === null) throw new Error("getAsyncLocalStorage is only available in server code"); + else return mod; +} +var AsyncLocalStoragePromise; +var init_async_hooks = __esm({ + "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/async_hooks/index.mjs"() { + AsyncLocalStoragePromise = import( + /* @vite-ignore */ + /* webpackIgnore: true */ + "node:async_hooks" + ).then((mod) => mod.AsyncLocalStorage).catch((err) => { + if ("AsyncLocalStorage" in globalThis) return globalThis.AsyncLocalStorage; + if (typeof window !== "undefined") return null; + console.warn("[better-auth] Warning: AsyncLocalStorage is not available in this environment. Some features may not work as expected."); + console.warn("[better-auth] Please read more about this warning at https://better-auth.com/docs/installation#mount-handler"); + console.warn("[better-auth] If you are using Cloudflare Workers, please see: https://developers.cloudflare.com/workers/configuration/compatibility-flags/#nodejs-compatibility-flag"); + throw err; + }); + } +}); + +// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/context/endpoint-context.mjs +async function getCurrentAuthContext() { + const context = (await ensureAsyncStorage()).getStore(); + if (!context) throw new Error("No auth context found. Please make sure you are calling this function within a `runWithEndpointContext` callback."); + return context; +} +async function runWithEndpointContext(context, fn) { + return (await ensureAsyncStorage()).run(context, fn); +} +var ensureAsyncStorage; +var init_endpoint_context = __esm({ + "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/context/endpoint-context.mjs"() { + init_global(); + init_async_hooks(); + ensureAsyncStorage = async () => { + const betterAuthGlobal = __getBetterAuthGlobal(); + if (!betterAuthGlobal.context.endpointContextAsyncStorage) { + const AsyncLocalStorage$1 = await getAsyncLocalStorage(); + betterAuthGlobal.context.endpointContextAsyncStorage = new AsyncLocalStorage$1(); + } + return betterAuthGlobal.context.endpointContextAsyncStorage; + }; + } +}); + +// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/context/request-state.mjs +async function hasRequestState() { + return (await ensureAsyncStorage2()).getStore() !== void 0; +} +async function getCurrentRequestState() { + const store = (await ensureAsyncStorage2()).getStore(); + if (!store) throw new Error("No request state found. Please make sure you are calling this function within a `runWithRequestState` callback."); + return store; +} +async function runWithRequestState(store, fn) { + return (await ensureAsyncStorage2()).run(store, fn); +} +function defineRequestState(initFn) { + const ref = Object.freeze({}); + return { + get ref() { + return ref; + }, + async get() { + const store = await getCurrentRequestState(); + if (!store.has(ref)) { + const initialValue = await initFn(); + store.set(ref, initialValue); + return initialValue; + } + return store.get(ref); + }, + async set(value) { + (await getCurrentRequestState()).set(ref, value); + } + }; +} +var ensureAsyncStorage2; +var init_request_state = __esm({ + "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/context/request-state.mjs"() { + init_global(); + init_async_hooks(); + ensureAsyncStorage2 = async () => { + const betterAuthGlobal = __getBetterAuthGlobal(); + if (!betterAuthGlobal.context.requestStateAsyncStorage) { + const AsyncLocalStorage$1 = await getAsyncLocalStorage(); + betterAuthGlobal.context.requestStateAsyncStorage = new AsyncLocalStorage$1(); + } + return betterAuthGlobal.context.requestStateAsyncStorage; + }; + } +}); + +// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/context/transaction.mjs +var ensureAsyncStorage3, getCurrentAdapter, runWithAdapter, runWithTransaction; +var init_transaction = __esm({ + "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/context/transaction.mjs"() { + init_global(); + init_async_hooks(); + ensureAsyncStorage3 = async () => { + const betterAuthGlobal = __getBetterAuthGlobal(); + if (!betterAuthGlobal.context.adapterAsyncStorage) { + const AsyncLocalStorage$1 = await getAsyncLocalStorage(); + betterAuthGlobal.context.adapterAsyncStorage = new AsyncLocalStorage$1(); + } + return betterAuthGlobal.context.adapterAsyncStorage; + }; + getCurrentAdapter = async (fallback) => { + return ensureAsyncStorage3().then((als) => { + return als.getStore() || fallback; + }).catch(() => { + return fallback; + }); + }; + runWithAdapter = async (adapter, fn) => { + let called = true; + return ensureAsyncStorage3().then((als) => { + called = true; + return als.run(adapter, fn); + }).catch((err) => { + if (!called) return fn(); + throw err; + }); + }; + runWithTransaction = async (adapter, fn) => { + let called = true; + return ensureAsyncStorage3().then((als) => { + called = true; + return adapter.transaction(async (trx) => { + return als.run(trx, fn); + }); + }).catch((err) => { + if (!called) return fn(); + throw err; + }); + }; + } +}); + +// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/context/index.mjs +var init_context2 = __esm({ + "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/context/index.mjs"() { + init_global(); + init_endpoint_context(); + init_request_state(); + init_transaction(); + } +}); + +// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/api/middlewares/oauth.mjs +var getOAuthState, setOAuthState; +var init_oauth = __esm({ + "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/api/middlewares/oauth.mjs"() { + init_context2(); + ({ get: getOAuthState, set: setOAuthState } = defineRequestState(() => null)); + } +}); + +// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/oauth2/state.mjs +async function generateState(c5, link, additionalData) { + const callbackURL = c5.body?.callbackURL || c5.context.options.baseURL; + if (!callbackURL) throw new APIError("BAD_REQUEST", { message: "callbackURL is required" }); + const codeVerifier = generateRandomString(128); + const stateData = { + ...additionalData ? additionalData : {}, + callbackURL, + codeVerifier, + errorURL: c5.body?.errorCallbackURL, + newUserURL: c5.body?.newUserCallbackURL, + link, + expiresAt: Date.now() + 600 * 1e3, + requestSignUp: c5.body?.requestSignUp + }; + await setOAuthState(stateData); + try { + return generateGenericState(c5, stateData); + } catch (error50) { + c5.context.logger.error("Failed to create verification", error50); + throw new APIError("INTERNAL_SERVER_ERROR", { + message: "Unable to create verification", + cause: error50 + }); + } +} +async function parseState(c5) { + const state2 = c5.query.state || c5.body.state; + const errorURL = c5.context.options.onAPIError?.errorURL || `${c5.context.baseURL}/error`; + let parsedData; + try { + parsedData = await parseGenericState(c5, state2); + } catch (error50) { + c5.context.logger.error("Failed to parse state", error50); + if (error50 instanceof StateError && error50.code === "state_security_mismatch") throw c5.redirect(`${errorURL}?error=state_mismatch`); + throw c5.redirect(`${errorURL}?error=please_restart_the_process`); + } + if (!parsedData.errorURL) parsedData.errorURL = errorURL; + if (parsedData) await setOAuthState(parsedData); + return parsedData; +} +var init_state2 = __esm({ + "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/oauth2/state.mjs"() { + init_oauth(); + init_random2(); + init_crypto(); + init_state(); + init_dist3(); + } +}); + +// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/utils/hide-metadata.mjs +var HIDE_METADATA; +var init_hide_metadata = __esm({ + "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/utils/hide-metadata.mjs"() { + HIDE_METADATA = { scope: "server" }; + } +}); + +// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/utils/index.mjs +var init_utils10 = __esm({ + "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/utils/index.mjs"() { + init_state(); + init_state2(); + init_hide_metadata(); + init_utils7(); + } +}); + +// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/utils/get-request-ip.mjs +function getIp(req, options) { + if (options.advanced?.ipAddress?.disableIpTracking) return null; + const headers = "headers" in req ? req.headers : req; + const ipHeaders = options.advanced?.ipAddress?.ipAddressHeaders || ["x-forwarded-for"]; + for (const key of ipHeaders) { + const value = "get" in headers ? headers.get(key) : headers[key]; + if (typeof value === "string") { + const ip = value.split(",")[0].trim(); + if (isValidIP2(ip)) return normalizeIP(ip, { ipv6Subnet: options.advanced?.ipAddress?.ipv6Subnet }); + } + } + if (isTest() || isDevelopment()) return LOCALHOST_IP; + return null; +} +var LOCALHOST_IP; +var init_get_request_ip = __esm({ + "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/utils/get-request-ip.mjs"() { + init_env(); + init_utils7(); + LOCALHOST_IP = "127.0.0.1"; + } +}); + +// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/utils/url.mjs +function checkHasPath(url2) { + try { + return (new URL(url2).pathname.replace(/\/+$/, "") || "/") !== "/"; + } catch { + throw new BetterAuthError(`Invalid base URL: ${url2}. Please provide a valid base URL.`); + } +} +function assertHasProtocol(url2) { + try { + const parsedUrl = new URL(url2); + if (parsedUrl.protocol !== "http:" && parsedUrl.protocol !== "https:") throw new BetterAuthError(`Invalid base URL: ${url2}. URL must include 'http://' or 'https://'`); + } catch (error50) { + if (error50 instanceof BetterAuthError) throw error50; + throw new BetterAuthError(`Invalid base URL: ${url2}. Please provide a valid base URL.`, { cause: error50 }); + } +} +function withPath(url2, path53 = "/api/auth") { + assertHasProtocol(url2); + if (checkHasPath(url2)) return url2; + const trimmedUrl = url2.replace(/\/+$/, ""); + if (!path53 || path53 === "/") return trimmedUrl; + path53 = path53.startsWith("/") ? path53 : `/${path53}`; + return `${trimmedUrl}${path53}`; +} +function validateProxyHeader(header, type) { + if (!header || header.trim() === "") return false; + if (type === "proto") return header === "http" || header === "https"; + if (type === "host") { + if ([ + /\.\./, + /\0/, + /[\s]/, + /^[.]/, + /[<>'"]/, + /javascript:/i, + /file:/i, + /data:/i + ].some((pattern) => pattern.test(header))) return false; + return /^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*(:[0-9]{1,5})?$/.test(header) || /^(\d{1,3}\.){3}\d{1,3}(:[0-9]{1,5})?$/.test(header) || /^\[[0-9a-fA-F:]+\](:[0-9]{1,5})?$/.test(header) || /^localhost(:[0-9]{1,5})?$/i.test(header); + } + return false; +} +function getBaseURL(url2, path53, request, loadEnv, trustedProxyHeaders) { + if (url2) return withPath(url2, path53); + if (loadEnv !== false) { + const fromEnv = env.BETTER_AUTH_URL || env.NEXT_PUBLIC_BETTER_AUTH_URL || env.PUBLIC_BETTER_AUTH_URL || env.NUXT_PUBLIC_BETTER_AUTH_URL || env.NUXT_PUBLIC_AUTH_URL || (env.BASE_URL !== "/" ? env.BASE_URL : void 0); + if (fromEnv) return withPath(fromEnv, path53); + } + const fromRequest = request?.headers.get("x-forwarded-host"); + const fromRequestProto = request?.headers.get("x-forwarded-proto"); + if (fromRequest && fromRequestProto && trustedProxyHeaders) { + if (validateProxyHeader(fromRequestProto, "proto") && validateProxyHeader(fromRequest, "host")) try { + return withPath(`${fromRequestProto}://${fromRequest}`, path53); + } catch (_error) { + } + } + if (request) { + const url$1 = getOrigin(request.url); + if (!url$1) throw new BetterAuthError("Could not get origin from request. Please provide a valid base URL."); + return withPath(url$1, path53); + } + if (typeof window !== "undefined" && window.location) return withPath(window.location.origin, path53); +} +function getOrigin(url2) { + try { + const parsedUrl = new URL(url2); + return parsedUrl.origin === "null" ? null : parsedUrl.origin; + } catch { + return null; + } +} +function getProtocol(url2) { + try { + return new URL(url2).protocol; + } catch { + return null; + } +} +function getHost(url2) { + try { + return new URL(url2).host; + } catch { + return null; + } +} +var init_url2 = __esm({ + "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/utils/url.mjs"() { + init_env(); + init_error(); + } +}); + +// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/utils/wildcard.mjs +function escapeRegExpChar(char2) { + if (char2 === "-" || char2 === "^" || char2 === "$" || char2 === "+" || char2 === "." || char2 === "(" || char2 === ")" || char2 === "|" || char2 === "[" || char2 === "]" || char2 === "{" || char2 === "}" || char2 === "*" || char2 === "?" || char2 === "\\") return `\\${char2}`; + else return char2; +} +function escapeRegExpString(str) { + let result = ""; + for (let i5 = 0; i5 < str.length; i5++) result += escapeRegExpChar(str[i5]); + return result; +} +function transform2(pattern, separator = true) { + if (Array.isArray(pattern)) return `(?:${pattern.map((p5) => `^${transform2(p5, separator)}$`).join("|")})`; + let separatorSplitter = ""; + let separatorMatcher = ""; + let wildcard = "."; + if (separator === true) { + separatorSplitter = "/"; + separatorMatcher = "[/\\\\]"; + wildcard = "[^/\\\\]"; + } else if (separator) { + separatorSplitter = separator; + separatorMatcher = escapeRegExpString(separatorSplitter); + if (separatorMatcher.length > 1) { + separatorMatcher = `(?:${separatorMatcher})`; + wildcard = `((?!${separatorMatcher}).)`; + } else wildcard = `[^${separatorMatcher}]`; + } + const requiredSeparator = separator ? `${separatorMatcher}+?` : ""; + const optionalSeparator = separator ? `${separatorMatcher}*?` : ""; + const segments = separator ? pattern.split(separatorSplitter) : [pattern]; + let result = ""; + for (let s5 = 0; s5 < segments.length; s5++) { + const segment = segments[s5]; + const nextSegment = segments[s5 + 1]; + let currentSeparator = ""; + if (!segment && s5 > 0) continue; + if (separator) if (s5 === segments.length - 1) currentSeparator = optionalSeparator; + else if (nextSegment !== "**") currentSeparator = requiredSeparator; + else currentSeparator = ""; + if (separator && segment === "**") { + if (currentSeparator) { + result += s5 === 0 ? "" : currentSeparator; + result += `(?:${wildcard}*?${currentSeparator})*?`; + } + continue; + } + for (let c5 = 0; c5 < segment.length; c5++) { + const char2 = segment[c5]; + if (char2 === "\\") { + if (c5 < segment.length - 1) { + result += escapeRegExpChar(segment[c5 + 1]); + c5++; + } + } else if (char2 === "?") result += wildcard; + else if (char2 === "*") result += `${wildcard}*?`; + else result += escapeRegExpChar(char2); + } + result += currentSeparator; + } + return result; +} +function isMatch(regexp, sample) { + if (typeof sample !== "string") throw new TypeError(`Sample must be a string, but ${typeof sample} given`); + return regexp.test(sample); +} +function wildcardMatch(pattern, options) { + if (typeof pattern !== "string" && !Array.isArray(pattern)) throw new TypeError(`The first argument must be a single pattern string or an array of patterns, but ${typeof pattern} given`); + if (typeof options === "string" || typeof options === "boolean") options = { separator: options }; + if (arguments.length === 2 && !(typeof options === "undefined" || typeof options === "object" && options !== null && !Array.isArray(options))) throw new TypeError(`The second argument must be an options object or a string/boolean separator, but ${typeof options} given`); + options = options || {}; + if (options.separator === "\\") throw new Error("\\ is not a valid separator because it is used for escaping. Try setting the separator to `true` instead"); + const regexpPattern = transform2(pattern, options.separator); + const regexp = new RegExp(`^${regexpPattern}$`, options.flags); + const fn = isMatch.bind(null, regexp); + fn.options = options; + fn.pattern = pattern; + fn.regexp = regexp; + return fn; +} +var init_wildcard = __esm({ + "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/utils/wildcard.mjs"() { + } +}); + +// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/auth/trusted-origins.mjs +var matchesOriginPattern; +var init_trusted_origins = __esm({ + "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/auth/trusted-origins.mjs"() { + init_url2(); + init_wildcard(); + matchesOriginPattern = (url2, pattern, settings) => { + if (url2.startsWith("/")) { + if (settings?.allowRelativePaths) return url2.startsWith("/") && /^\/(?!\/|\\|%2f|%5c)[\w\-.\+/@]*(?:\?[\w\-.\+/=&%@]*)?$/.test(url2); + return false; + } + if (pattern.includes("*") || pattern.includes("?")) { + if (pattern.includes("://")) return wildcardMatch(pattern)(getOrigin(url2) || url2); + const host = getHost(url2); + if (!host) return false; + return wildcardMatch(pattern)(host); + } + const protocol = getProtocol(url2); + return protocol === "http:" || protocol === "https:" || !protocol ? pattern === getOrigin(url2) : url2.startsWith(pattern); + }; + } +}); + +// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/api/index.mjs +function createAuthEndpoint(pathOrOptions, handlerOrOptions, handlerOrNever) { + const path53 = typeof pathOrOptions === "string" ? pathOrOptions : void 0; + const options = typeof handlerOrOptions === "object" ? handlerOrOptions : pathOrOptions; + const handler = typeof handlerOrOptions === "function" ? handlerOrOptions : handlerOrNever; + if (path53) return createEndpoint(path53, { + ...options, + use: [...options?.use || [], ...use] + }, async (ctx) => runWithEndpointContext(ctx, () => handler(ctx))); + return createEndpoint({ + ...options, + use: [...options?.use || [], ...use] + }, async (ctx) => runWithEndpointContext(ctx, () => handler(ctx))); +} +var optionsMiddleware, createAuthMiddleware, use; +var init_api2 = __esm({ + "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/api/index.mjs"() { + init_endpoint_context(); + init_context2(); + init_dist3(); + optionsMiddleware = createMiddleware(async () => { + return {}; + }); + createAuthMiddleware = createMiddleware.create({ use: [optionsMiddleware, createMiddleware(async () => { + return {}; + })] }); + use = [optionsMiddleware]; + } +}); + +// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/api/middlewares/origin-check.mjs +function shouldSkipCSRFForBackwardCompat(ctx) { + return ctx.context.skipOriginCheck === true && ctx.context.options.advanced?.disableCSRFCheck === void 0; +} +async function validateOrigin(ctx, forceValidate = false) { + const headers = ctx.request?.headers; + if (!headers || !ctx.request) return; + const originHeader = headers.get("origin") || headers.get("referer") || ""; + const useCookies = headers.has("cookie"); + if (ctx.context.skipCSRFCheck) return; + if (shouldSkipCSRFForBackwardCompat(ctx)) { + ctx.context.options.advanced?.disableOriginCheck === true && logBackwardCompatWarning(); + return; + } + const skipOriginCheck = ctx.context.skipOriginCheck; + if (Array.isArray(skipOriginCheck)) try { + const basePath = new URL(ctx.context.baseURL).pathname; + const currentPath = normalizePathname(ctx.request.url, basePath); + if (skipOriginCheck.some((skipPath) => currentPath.startsWith(skipPath))) return; + } catch { + } + if (!(forceValidate || useCookies)) return; + if (!originHeader || originHeader === "null") throw new APIError("FORBIDDEN", { message: BASE_ERROR_CODES.MISSING_OR_NULL_ORIGIN }); + const trustedOrigins = Array.isArray(ctx.context.options.trustedOrigins) ? ctx.context.trustedOrigins : [...ctx.context.trustedOrigins, ...(await ctx.context.options.trustedOrigins?.(ctx.request))?.filter((v5) => Boolean(v5)) || []]; + if (!trustedOrigins.some((origin) => matchesOriginPattern(originHeader, origin))) { + ctx.context.logger.error(`Invalid origin: ${originHeader}`); + ctx.context.logger.info(`If it's a valid URL, please add ${originHeader} to trustedOrigins in your auth config +`, `Current list of trustedOrigins: ${trustedOrigins}`); + throw new APIError("FORBIDDEN", { message: "Invalid origin" }); + } +} +async function validateFormCsrf(ctx) { + const req = ctx.request; + if (!req) return; + if (ctx.context.skipCSRFCheck) return; + if (shouldSkipCSRFForBackwardCompat(ctx)) return; + const headers = req.headers; + if (headers.has("cookie")) return await validateOrigin(ctx); + const site = headers.get("Sec-Fetch-Site"); + const mode = headers.get("Sec-Fetch-Mode"); + const dest = headers.get("Sec-Fetch-Dest"); + if (Boolean(site && site.trim() || mode && mode.trim() || dest && dest.trim())) { + if (site === "cross-site" && mode === "navigate") { + ctx.context.logger.error("Blocked cross-site navigation login attempt (CSRF protection)", { + secFetchSite: site, + secFetchMode: mode, + secFetchDest: dest + }); + throw new APIError("FORBIDDEN", { message: BASE_ERROR_CODES.CROSS_SITE_NAVIGATION_LOGIN_BLOCKED }); + } + return await validateOrigin(ctx, true); + } +} +var logBackwardCompatWarning, originCheckMiddleware, originCheck, formCsrfMiddleware; +var init_origin_check = __esm({ + "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/api/middlewares/origin-check.mjs"() { + init_trusted_origins(); + init_error(); + init_utils7(); + init_dist3(); + init_api2(); + logBackwardCompatWarning = deprecate(function logBackwardCompatWarning$1() { + }, "disableOriginCheck: true currently also disables CSRF checks. In a future version, disableOriginCheck will ONLY disable URL validation. To keep CSRF disabled, add disableCSRFCheck: true to your config."); + originCheckMiddleware = createAuthMiddleware(async (ctx) => { + if (ctx.request?.method === "GET" || ctx.request?.method === "OPTIONS" || ctx.request?.method === "HEAD" || !ctx.request) return; + await validateOrigin(ctx); + if (ctx.context.skipOriginCheck) return; + const { body, query } = ctx; + const callbackURL = body?.callbackURL || query?.callbackURL; + const redirectURL = body?.redirectTo; + const errorCallbackURL = body?.errorCallbackURL; + const newUserCallbackURL = body?.newUserCallbackURL; + const validateURL = (url2, label) => { + if (!url2) return; + if (!ctx.context.isTrustedOrigin(url2, { allowRelativePaths: label !== "origin" })) { + ctx.context.logger.error(`Invalid ${label}: ${url2}`); + ctx.context.logger.info(`If it's a valid URL, please add ${url2} to trustedOrigins in your auth config +`, `Current list of trustedOrigins: ${ctx.context.trustedOrigins}`); + throw new APIError("FORBIDDEN", { message: `Invalid ${label}` }); + } + }; + callbackURL && validateURL(callbackURL, "callbackURL"); + redirectURL && validateURL(redirectURL, "redirectURL"); + errorCallbackURL && validateURL(errorCallbackURL, "errorCallbackURL"); + newUserCallbackURL && validateURL(newUserCallbackURL, "newUserCallbackURL"); + }); + originCheck = (getValue) => createAuthMiddleware(async (ctx) => { + if (!ctx.request) return; + if (ctx.context.skipOriginCheck) return; + const callbackURL = getValue(ctx); + const validateURL = (url2, label) => { + if (!url2) return; + if (!ctx.context.isTrustedOrigin(url2, { allowRelativePaths: label !== "origin" })) { + ctx.context.logger.error(`Invalid ${label}: ${url2}`); + ctx.context.logger.info(`If it's a valid URL, please add ${url2} to trustedOrigins in your auth config +`, `Current list of trustedOrigins: ${ctx.context.trustedOrigins}`); + throw new APIError("FORBIDDEN", { message: `Invalid ${label}` }); + } + }; + const callbacks = Array.isArray(callbackURL) ? callbackURL : [callbackURL]; + for (const url2 of callbacks) validateURL(url2, "callbackURL"); + }); + formCsrfMiddleware = createAuthMiddleware(async (ctx) => { + if (!ctx.request) return; + await validateFormCsrf(ctx); + }); + } +}); + +// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/api/middlewares/index.mjs +var init_middlewares = __esm({ + "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/api/middlewares/index.mjs"() { + init_oauth(); + init_origin_check(); + } +}); + +// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/api/rate-limiter/index.mjs +function shouldRateLimit(max, window2, rateLimitData) { + const now2 = Date.now(); + const windowInMs = window2 * 1e3; + return now2 - rateLimitData.lastRequest < windowInMs && rateLimitData.count >= max; +} +function rateLimitResponse(retryAfter) { + return new Response(JSON.stringify({ message: "Too many requests. Please try again later." }), { + status: 429, + statusText: "Too Many Requests", + headers: { "X-Retry-After": retryAfter.toString() } + }); +} +function getRetryAfter(lastRequest, window2) { + const now2 = Date.now(); + const windowInMs = window2 * 1e3; + return Math.ceil((lastRequest + windowInMs - now2) / 1e3); +} +function createDatabaseStorageWrapper(ctx) { + const model = "rateLimit"; + const db = ctx.adapter; + return { + get: async (key) => { + const data2 = (await db.findMany({ + model, + where: [{ + field: "key", + value: key + }] + }))[0]; + if (typeof data2?.lastRequest === "bigint") data2.lastRequest = Number(data2.lastRequest); + return data2; + }, + set: async (key, value, _update) => { + try { + if (_update) await db.updateMany({ + model, + where: [{ + field: "key", + value: key + }], + update: { + count: value.count, + lastRequest: value.lastRequest + } + }); + else await db.create({ + model, + data: { + key, + count: value.count, + lastRequest: value.lastRequest + } + }); + } catch (e5) { + ctx.logger.error("Error setting rate limit", e5); + } + } + }; +} +function getRateLimitStorage(ctx, rateLimitSettings) { + if (ctx.options.rateLimit?.customStorage) return ctx.options.rateLimit.customStorage; + const storage = ctx.rateLimit.storage; + if (storage === "secondary-storage") return { + get: async (key) => { + const data2 = await ctx.options.secondaryStorage?.get(key); + return data2 ? safeJSONParse(data2) : null; + }, + set: async (key, value, _update) => { + const ttl = rateLimitSettings?.window ?? ctx.options.rateLimit?.window ?? 10; + await ctx.options.secondaryStorage?.set?.(key, JSON.stringify(value), ttl); + } + }; + else if (storage === "memory") return { + async get(key) { + const entry = memory.get(key); + if (!entry) return null; + if (Date.now() >= entry.expiresAt) { + memory.delete(key); + return null; + } + return entry.data; + }, + async set(key, value, _update) { + const ttl = rateLimitSettings?.window ?? ctx.options.rateLimit?.window ?? 10; + const expiresAt = Date.now() + ttl * 1e3; + memory.set(key, { + data: value, + expiresAt + }); + } + }; + return createDatabaseStorageWrapper(ctx); +} +async function onRequestRateLimit(req, ctx) { + if (!ctx.rateLimit.enabled) return; + const basePath = new URL(ctx.baseURL).pathname; + const path53 = normalizePathname(req.url, basePath); + let currentWindow = ctx.rateLimit.window; + let currentMax = ctx.rateLimit.max; + const ip = getIp(req, ctx.options); + if (!ip) return; + const key = createRateLimitKey(ip, path53); + const specialRule = getDefaultSpecialRules().find((rule) => rule.pathMatcher(path53)); + if (specialRule) { + currentWindow = specialRule.window; + currentMax = specialRule.max; + } + for (const plugin of ctx.options.plugins || []) if (plugin.rateLimit) { + const matchedRule = plugin.rateLimit.find((rule) => rule.pathMatcher(path53)); + if (matchedRule) { + currentWindow = matchedRule.window; + currentMax = matchedRule.max; + break; + } + } + if (ctx.rateLimit.customRules) { + const _path = Object.keys(ctx.rateLimit.customRules).find((p5) => { + if (p5.includes("*")) return wildcardMatch(p5)(path53); + return p5 === path53; + }); + if (_path) { + const customRule = ctx.rateLimit.customRules[_path]; + const resolved = typeof customRule === "function" ? await customRule(req, { + window: currentWindow, + max: currentMax + }) : customRule; + if (resolved) { + currentWindow = resolved.window; + currentMax = resolved.max; + } + if (resolved === false) return; + } + } + const storage = getRateLimitStorage(ctx, { window: currentWindow }); + const data2 = await storage.get(key); + const now2 = Date.now(); + if (!data2) await storage.set(key, { + key, + count: 1, + lastRequest: now2 + }); + else { + const timeSinceLastRequest = now2 - data2.lastRequest; + if (shouldRateLimit(currentMax, currentWindow, data2)) return rateLimitResponse(getRetryAfter(data2.lastRequest, currentWindow)); + else if (timeSinceLastRequest > currentWindow * 1e3) await storage.set(key, { + ...data2, + count: 1, + lastRequest: now2 + }, true); + else await storage.set(key, { + ...data2, + count: data2.count + 1, + lastRequest: now2 + }, true); + } +} +function getDefaultSpecialRules() { + return [{ + pathMatcher(path53) { + return path53.startsWith("/sign-in") || path53.startsWith("/sign-up") || path53.startsWith("/change-password") || path53.startsWith("/change-email"); + }, + window: 10, + max: 3 + }]; +} +var memory; +var init_rate_limiter = __esm({ + "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/api/rate-limiter/index.mjs"() { + init_get_request_ip(); + init_wildcard(); + init_utils7(); + memory = /* @__PURE__ */ new Map(); + } +}); + +// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/_virtual/rolldown_runtime.mjs +var __defProp2, __getOwnPropDesc2, __getOwnPropNames2, __hasOwnProp2, __export2, __copyProps2, __reExport; +var init_rolldown_runtime = __esm({ + "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/_virtual/rolldown_runtime.mjs"() { + __defProp2 = Object.defineProperty; + __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; + __getOwnPropNames2 = Object.getOwnPropertyNames; + __hasOwnProp2 = Object.prototype.hasOwnProperty; + __export2 = (all, symbols) => { + let target = {}; + for (var name in all) { + __defProp2(target, name, { + get: all[name], + enumerable: true + }); + } + if (symbols) { + __defProp2(target, Symbol.toStringTag, { value: "Module" }); + } + return target; + }; + __copyProps2 = (to, from, except2, desc3) => { + if (from && typeof from === "object" || typeof from === "function") { + for (var keys = __getOwnPropNames2(from), i5 = 0, n5 = keys.length, key; i5 < n5; i5++) { + key = keys[i5]; + if (!__hasOwnProp2.call(to, key) && key !== except2) { + __defProp2(to, key, { + get: ((k5) => from[k5]).bind(null, key), + enumerable: !(desc3 = __getOwnPropDesc2(from, key)) || desc3.enumerable + }); + } + } + } + return to; + }; + __reExport = (target, mod, secondTarget, symbols) => { + if (symbols) { + __defProp2(target, Symbol.toStringTag, { value: "Module" }); + secondTarget && __defProp2(secondTarget, Symbol.toStringTag, { value: "Module" }); + } + __copyProps2(target, mod, "default"), secondTarget && __copyProps2(secondTarget, mod, "default"); + }; + } +}); + +// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/db/adapter/get-default-model-name.mjs +var initGetDefaultModelName; +var init_get_default_model_name = __esm({ + "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/db/adapter/get-default-model-name.mjs"() { + init_error(); + initGetDefaultModelName = ({ usePlural, schema: schema2 }) => { + const getDefaultModelName = (model) => { + if (usePlural && model.charAt(model.length - 1) === "s") { + const pluralessModel = model.slice(0, -1); + let m$1 = schema2[pluralessModel] ? pluralessModel : void 0; + if (!m$1) m$1 = Object.entries(schema2).find(([_, f5]) => f5.modelName === pluralessModel)?.[0]; + if (m$1) return m$1; + } + let m5 = schema2[model] ? model : void 0; + if (!m5) m5 = Object.entries(schema2).find(([_, f5]) => f5.modelName === model)?.[0]; + if (!m5) throw new BetterAuthError(`Model "${model}" not found in schema`); + return m5; + }; + return getDefaultModelName; + }; + } +}); + +// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/db/adapter/get-default-field-name.mjs +var initGetDefaultFieldName; +var init_get_default_field_name = __esm({ + "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/db/adapter/get-default-field-name.mjs"() { + init_error(); + init_get_default_model_name(); + initGetDefaultFieldName = ({ schema: schema2, usePlural }) => { + const getDefaultModelName = initGetDefaultModelName({ + schema: schema2, + usePlural + }); + const getDefaultFieldName = ({ field, model: unsafeModel }) => { + if (field === "id" || field === "_id") return "id"; + const model = getDefaultModelName(unsafeModel); + let f5 = schema2[model]?.fields[field]; + if (!f5) { + const result = Object.entries(schema2[model].fields).find(([_, f$1]) => f$1.fieldName === field); + if (result) { + f5 = result[1]; + field = result[0]; + } + } + if (!f5) throw new BetterAuthError(`Field ${field} not found in model ${model}`); + return field; + }; + return getDefaultFieldName; + }; + } +}); + +// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/db/adapter/get-id-field.mjs +var initGetIdField; +var init_get_id_field = __esm({ + "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/db/adapter/get-id-field.mjs"() { + init_logger2(); + init_env(); + init_id(); + init_utils7(); + init_get_default_model_name(); + initGetIdField = ({ usePlural, schema: schema2, disableIdGeneration, options, customIdGenerator, supportsUUIDs }) => { + const getDefaultModelName = initGetDefaultModelName({ + usePlural, + schema: schema2 + }); + const idField = ({ customModelName, forceAllowId }) => { + const useNumberId = options.advanced?.database?.useNumberId || options.advanced?.database?.generateId === "serial"; + const useUUIDs = options.advanced?.database?.generateId === "uuid"; + const shouldGenerateId = (() => { + if (disableIdGeneration) return false; + else if (useNumberId && !forceAllowId) return false; + else if (useUUIDs) return !supportsUUIDs; + else return true; + })(); + const model = getDefaultModelName(customModelName ?? "id"); + return { + type: useNumberId ? "number" : "string", + required: shouldGenerateId ? true : false, + ...shouldGenerateId ? { defaultValue() { + if (disableIdGeneration) return void 0; + const generateId$1 = options.advanced?.database?.generateId; + if (generateId$1 === false || useNumberId) return void 0; + if (typeof generateId$1 === "function") return generateId$1({ model }); + if (customIdGenerator) return customIdGenerator({ model }); + if (generateId$1 === "uuid") return crypto.randomUUID(); + return generateId(); + } } : {}, + transform: { + input: (value) => { + if (!value) return void 0; + if (useNumberId) { + const numberValue = Number(value); + if (isNaN(numberValue)) return; + return numberValue; + } + if (useUUIDs) { + if (shouldGenerateId && !forceAllowId) return value; + if (disableIdGeneration) return void 0; + if (supportsUUIDs) return void 0; + if (forceAllowId && typeof value === "string") if (/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value)) return value; + else { + const stack = (/* @__PURE__ */ new Error()).stack?.split("\n").filter((_, i5) => i5 !== 1).join("\n").replace("Error:", ""); + logger3.warn("[Adapter Factory] - Invalid UUID value for field `id` provided when `forceAllowId` is true. Generating a new UUID.", stack); + } + if (typeof value !== "string" && !supportsUUIDs) return crypto.randomUUID(); + return; + } + return value; + }, + output: (value) => { + if (!value) return void 0; + return String(value); + } + } + }; + }; + return idField; + }; + } +}); + +// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/db/adapter/get-field-attributes.mjs +var initGetFieldAttributes; +var init_get_field_attributes = __esm({ + "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/db/adapter/get-field-attributes.mjs"() { + init_error(); + init_get_default_model_name(); + init_get_default_field_name(); + init_get_id_field(); + initGetFieldAttributes = ({ usePlural, schema: schema2, options, customIdGenerator, disableIdGeneration }) => { + const getDefaultModelName = initGetDefaultModelName({ + usePlural, + schema: schema2 + }); + const getDefaultFieldName = initGetDefaultFieldName({ + usePlural, + schema: schema2 + }); + const idField = initGetIdField({ + usePlural, + schema: schema2, + options, + customIdGenerator, + disableIdGeneration + }); + const getFieldAttributes = ({ model, field }) => { + const defaultModelName = getDefaultModelName(model); + const defaultFieldName = getDefaultFieldName({ + field, + model: defaultModelName + }); + const fields = schema2[defaultModelName].fields; + fields.id = idField({ customModelName: defaultModelName }); + const fieldAttributes = fields[defaultFieldName]; + if (!fieldAttributes) throw new BetterAuthError(`Field ${field} not found in model ${model}`); + return fieldAttributes; + }; + return getFieldAttributes; + }; + } +}); + +// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/db/adapter/get-field-name.mjs +var initGetFieldName; +var init_get_field_name = __esm({ + "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/db/adapter/get-field-name.mjs"() { + init_get_default_model_name(); + init_get_default_field_name(); + initGetFieldName = ({ schema: schema2, usePlural }) => { + const getDefaultModelName = initGetDefaultModelName({ + schema: schema2, + usePlural + }); + const getDefaultFieldName = initGetDefaultFieldName({ + schema: schema2, + usePlural + }); + function getFieldName({ model: modelName, field: fieldName }) { + const model = getDefaultModelName(modelName); + const field = getDefaultFieldName({ + model, + field: fieldName + }); + return schema2[model]?.fields[field]?.fieldName || field; + } + return getFieldName; + }; + } +}); + +// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/db/adapter/get-model-name.mjs +var initGetModelName; +var init_get_model_name = __esm({ + "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/db/adapter/get-model-name.mjs"() { + init_get_default_model_name(); + initGetModelName = ({ usePlural, schema: schema2 }) => { + const getDefaultModelName = initGetDefaultModelName({ + schema: schema2, + usePlural + }); + const getModelName = (model) => { + const defaultModelKey = getDefaultModelName(model); + if (schema2 && schema2[defaultModelKey] && schema2[defaultModelKey].modelName !== model) return usePlural ? `${schema2[defaultModelKey].modelName}s` : schema2[defaultModelKey].modelName; + return usePlural ? `${model}s` : model; + }; + return getModelName; + }; + } +}); + +// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/db/adapter/utils.mjs +function withApplyDefault(value, field, action) { + if (action === "update") { + if (value === void 0 && field.onUpdate !== void 0) { + if (typeof field.onUpdate === "function") return field.onUpdate(); + return field.onUpdate; + } + return value; + } + if (action === "create") { + if (value === void 0 || field.required === true && value === null) { + if (field.defaultValue !== void 0) { + if (typeof field.defaultValue === "function") return field.defaultValue(); + return field.defaultValue; + } + } + } + return value; +} +var init_utils11 = __esm({ + "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/db/adapter/utils.mjs"() { + } +}); + +// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/db/adapter/factory.mjs +function formatTransactionId(transactionId$1) { + if (getColorDepth() < 8) return `#${transactionId$1}`; + return `${TTY_COLORS.fg.magenta}#${transactionId$1}${TTY_COLORS.reset}`; +} +function formatStep(step, total) { + return `${TTY_COLORS.bg.black}${TTY_COLORS.fg.yellow}[${step}/${total}]${TTY_COLORS.reset}`; +} +function formatMethod(method) { + return `${TTY_COLORS.bright}${method}${TTY_COLORS.reset}`; +} +function formatAction(action) { + return `${TTY_COLORS.dim}(${action})${TTY_COLORS.reset}`; +} +var debugLogs, transactionId, createAsIsTransaction, createAdapterFactory; +var init_factory = __esm({ + "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/db/adapter/factory.mjs"() { + init_get_tables(); + init_color_depth(); + init_logger2(); + init_env(); + init_json2(); + init_error(); + init_get_default_model_name(); + init_get_default_field_name(); + init_get_id_field(); + init_get_field_attributes(); + init_get_field_name(); + init_get_model_name(); + init_utils11(); + debugLogs = []; + transactionId = -1; + createAsIsTransaction = (adapter) => (fn) => fn(adapter); + createAdapterFactory = ({ adapter: customAdapter, config: cfg }) => (options) => { + const uniqueAdapterFactoryInstanceId = Math.random().toString(36).substring(2, 15); + const config3 = { + ...cfg, + supportsBooleans: cfg.supportsBooleans ?? true, + supportsDates: cfg.supportsDates ?? true, + supportsJSON: cfg.supportsJSON ?? false, + adapterName: cfg.adapterName ?? cfg.adapterId, + supportsNumericIds: cfg.supportsNumericIds ?? true, + supportsUUIDs: cfg.supportsUUIDs ?? false, + supportsArrays: cfg.supportsArrays ?? false, + transaction: cfg.transaction ?? false, + disableTransformInput: cfg.disableTransformInput ?? false, + disableTransformOutput: cfg.disableTransformOutput ?? false, + disableTransformJoin: cfg.disableTransformJoin ?? false + }; + if ((options.advanced?.database?.useNumberId === true || options.advanced?.database?.generateId === "serial") && config3.supportsNumericIds === false) throw new BetterAuthError(`[${config3.adapterName}] Your database or database adapter does not support numeric ids. Please disable "useNumberId" in your config.`); + const schema2 = getAuthTables(options); + const debugLog = (...args) => { + if (config3.debugLogs === true || typeof config3.debugLogs === "object") { + const logger$1 = createLogger({ level: "info" }); + if (typeof config3.debugLogs === "object" && "isRunningAdapterTests" in config3.debugLogs) { + if (config3.debugLogs.isRunningAdapterTests) { + args.shift(); + debugLogs.push({ + instance: uniqueAdapterFactoryInstanceId, + args + }); + } + return; + } + if (typeof config3.debugLogs === "object" && config3.debugLogs.logCondition && !config3.debugLogs.logCondition?.()) return; + if (typeof args[0] === "object" && "method" in args[0]) { + const method = args.shift().method; + if (typeof config3.debugLogs === "object") { + if (method === "create" && !config3.debugLogs.create) return; + else if (method === "update" && !config3.debugLogs.update) return; + else if (method === "updateMany" && !config3.debugLogs.updateMany) return; + else if (method === "findOne" && !config3.debugLogs.findOne) return; + else if (method === "findMany" && !config3.debugLogs.findMany) return; + else if (method === "delete" && !config3.debugLogs.delete) return; + else if (method === "deleteMany" && !config3.debugLogs.deleteMany) return; + else if (method === "count" && !config3.debugLogs.count) return; + } + logger$1.info(`[${config3.adapterName}]`, ...args); + } else logger$1.info(`[${config3.adapterName}]`, ...args); + } + }; + const logger4 = createLogger(options.logger); + const getDefaultModelName = initGetDefaultModelName({ + usePlural: config3.usePlural, + schema: schema2 + }); + const getDefaultFieldName = initGetDefaultFieldName({ + usePlural: config3.usePlural, + schema: schema2 + }); + const getModelName = initGetModelName({ + usePlural: config3.usePlural, + schema: schema2 + }); + const getFieldName = initGetFieldName({ + schema: schema2, + usePlural: config3.usePlural + }); + const idField = initGetIdField({ + schema: schema2, + options, + usePlural: config3.usePlural, + disableIdGeneration: config3.disableIdGeneration, + customIdGenerator: config3.customIdGenerator, + supportsUUIDs: config3.supportsUUIDs + }); + const getFieldAttributes = initGetFieldAttributes({ + schema: schema2, + options, + usePlural: config3.usePlural, + disableIdGeneration: config3.disableIdGeneration, + customIdGenerator: config3.customIdGenerator + }); + const transformInput = async (data2, defaultModelName, action, forceAllowId) => { + const transformedData = {}; + const fields = schema2[defaultModelName].fields; + const newMappedKeys = config3.mapKeysTransformInput ?? {}; + const useNumberId = options.advanced?.database?.useNumberId || options.advanced?.database?.generateId === "serial"; + fields.id = idField({ + customModelName: defaultModelName, + forceAllowId: forceAllowId && "id" in data2 + }); + for (const field in fields) { + let value = data2[field]; + const fieldAttributes = fields[field]; + const newFieldName = newMappedKeys[field] || fields[field].fieldName || field; + if (value === void 0 && (fieldAttributes.defaultValue === void 0 && !fieldAttributes.transform?.input && !(action === "update" && fieldAttributes.onUpdate) || action === "update" && !fieldAttributes.onUpdate)) continue; + if (fieldAttributes && fieldAttributes.type === "date" && !(value instanceof Date) && typeof value === "string") try { + value = new Date(value); + } catch { + logger4.error("[Adapter Factory] Failed to convert string to date", { + value, + field + }); + } + let newValue = withApplyDefault(value, fieldAttributes, action); + if (fieldAttributes.transform?.input) newValue = await fieldAttributes.transform.input(newValue); + if (fieldAttributes.references?.field === "id" && useNumberId) if (Array.isArray(newValue)) newValue = newValue.map((x5) => x5 !== null ? Number(x5) : null); + else newValue = newValue !== null ? Number(newValue) : null; + else if (config3.supportsJSON === false && typeof newValue === "object" && fieldAttributes.type === "json") newValue = JSON.stringify(newValue); + else if (config3.supportsArrays === false && Array.isArray(newValue) && (fieldAttributes.type === "string[]" || fieldAttributes.type === "number[]")) newValue = JSON.stringify(newValue); + else if (config3.supportsDates === false && newValue instanceof Date && fieldAttributes.type === "date") newValue = newValue.toISOString(); + else if (config3.supportsBooleans === false && typeof newValue === "boolean") newValue = newValue ? 1 : 0; + if (config3.customTransformInput) newValue = config3.customTransformInput({ + data: newValue, + action, + field: newFieldName, + fieldAttributes, + model: getModelName(defaultModelName), + schema: schema2, + options + }); + if (newValue !== void 0) transformedData[newFieldName] = newValue; + } + return transformedData; + }; + const transformOutput = async (data2, unsafe_model, select2 = [], join4) => { + const transformSingleOutput = async (data$1, unsafe_model$1, select$1 = []) => { + if (!data$1) return null; + const newMappedKeys = config3.mapKeysTransformOutput ?? {}; + const transformedData$1 = {}; + const tableSchema = schema2[getDefaultModelName(unsafe_model$1)].fields; + const idKey = Object.entries(newMappedKeys).find(([_, v5]) => v5 === "id")?.[0]; + tableSchema[idKey ?? "id"] = { type: options.advanced?.database?.useNumberId || options.advanced?.database?.generateId === "serial" ? "number" : "string" }; + for (const key in tableSchema) { + if (select$1.length && !select$1.includes(key)) continue; + const field = tableSchema[key]; + if (field) { + const originalKey = field.fieldName || key; + let newValue = data$1[Object.entries(newMappedKeys).find(([_, v5]) => v5 === originalKey)?.[0] || originalKey]; + if (field.transform?.output) newValue = await field.transform.output(newValue); + const newFieldName = newMappedKeys[key] || key; + if (originalKey === "id" || field.references?.field === "id") { + if (typeof newValue !== "undefined" && newValue !== null) newValue = String(newValue); + } else if (config3.supportsJSON === false && typeof newValue === "string" && field.type === "json") newValue = safeJSONParse(newValue); + else if (config3.supportsArrays === false && typeof newValue === "string" && (field.type === "string[]" || field.type === "number[]")) newValue = safeJSONParse(newValue); + else if (config3.supportsDates === false && typeof newValue === "string" && field.type === "date") newValue = new Date(newValue); + else if (config3.supportsBooleans === false && typeof newValue === "number" && field.type === "boolean") newValue = newValue === 1; + if (config3.customTransformOutput) newValue = config3.customTransformOutput({ + data: newValue, + field: newFieldName, + fieldAttributes: field, + select: select$1, + model: getModelName(unsafe_model$1), + schema: schema2, + options + }); + transformedData$1[newFieldName] = newValue; + } + } + return transformedData$1; + }; + if (!join4 || Object.keys(join4).length === 0) return await transformSingleOutput(data2, unsafe_model, select2); + unsafe_model = getDefaultModelName(unsafe_model); + const transformedData = await transformSingleOutput(data2, unsafe_model, select2); + const requiredModels = Object.entries(join4).map(([model, joinConfig]) => ({ + modelName: getModelName(model), + defaultModelName: getDefaultModelName(model), + joinConfig + })); + if (!data2) return null; + for (const { modelName, defaultModelName, joinConfig } of requiredModels) { + let joinedData = await (async () => { + if (options.experimental?.joins) return data2[modelName]; + else return await handleFallbackJoin({ + baseModel: unsafe_model, + baseData: transformedData, + joinModel: modelName, + specificJoinConfig: joinConfig + }); + })(); + if (joinedData === void 0 || joinedData === null) joinedData = joinConfig.relation === "one-to-one" ? null : []; + if (joinConfig.relation === "one-to-many" && !Array.isArray(joinedData)) joinedData = [joinedData]; + const transformed = []; + if (Array.isArray(joinedData)) for (const item of joinedData) { + const transformedItem = await transformSingleOutput(item, modelName, []); + transformed.push(transformedItem); + } + else { + const transformedItem = await transformSingleOutput(joinedData, modelName, []); + transformed.push(transformedItem); + } + transformedData[defaultModelName] = (joinConfig.relation === "one-to-one" ? transformed[0] : transformed) ?? null; + } + return transformedData; + }; + const transformWhereClause = ({ model, where, action }) => { + if (!where) return void 0; + const newMappedKeys = config3.mapKeysTransformInput ?? {}; + return where.map((w5) => { + const { field: unsafe_field, value, operator = "eq", connector = "AND" } = w5; + if (operator === "in") { + if (!Array.isArray(value)) throw new BetterAuthError("Value must be an array"); + } + let newValue = value; + const defaultModelName = getDefaultModelName(model); + const defaultFieldName = getDefaultFieldName({ + field: unsafe_field, + model + }); + const fieldName = newMappedKeys[defaultFieldName] || getFieldName({ + field: defaultFieldName, + model: defaultModelName + }); + const fieldAttr = getFieldAttributes({ + field: defaultFieldName, + model: defaultModelName + }); + const useNumberId = options.advanced?.database?.useNumberId || options.advanced?.database?.generateId === "serial"; + if (defaultFieldName === "id" || fieldAttr.references?.field === "id") { + if (useNumberId) if (Array.isArray(value)) newValue = value.map(Number); + else newValue = Number(value); + } + if (fieldAttr.type === "date" && value instanceof Date && !config3.supportsDates) newValue = value.toISOString(); + if (fieldAttr.type === "boolean" && typeof value === "boolean" && !config3.supportsBooleans) newValue = value ? 1 : 0; + if (fieldAttr.type === "json" && typeof value === "object" && !config3.supportsJSON) try { + newValue = JSON.stringify(value); + } catch (error50) { + throw new Error(`Failed to stringify JSON value for field ${fieldName}`, { cause: error50 }); + } + if (config3.customTransformInput) newValue = config3.customTransformInput({ + data: newValue, + fieldAttributes: fieldAttr, + field: fieldName, + model: getModelName(model), + schema: schema2, + options, + action + }); + return { + operator, + connector, + field: fieldName, + value: newValue + }; + }); + }; + const transformJoinClause = (baseModel, unsanitizedJoin, select2) => { + if (!unsanitizedJoin) return void 0; + if (Object.keys(unsanitizedJoin).length === 0) return void 0; + const transformedJoin = {}; + for (const [model, join4] of Object.entries(unsanitizedJoin)) { + if (!join4) continue; + const defaultModelName = getDefaultModelName(model); + const defaultBaseModelName = getDefaultModelName(baseModel); + let foreignKeys = Object.entries(schema2[defaultModelName].fields).filter(([field, fieldAttributes]) => fieldAttributes.references && getDefaultModelName(fieldAttributes.references.model) === defaultBaseModelName); + let isForwardJoin = true; + if (!foreignKeys.length) { + foreignKeys = Object.entries(schema2[defaultBaseModelName].fields).filter(([field, fieldAttributes]) => fieldAttributes.references && getDefaultModelName(fieldAttributes.references.model) === defaultModelName); + isForwardJoin = false; + } + if (!foreignKeys.length) throw new BetterAuthError(`No foreign key found for model ${model} and base model ${baseModel} while performing join operation.`); + else if (foreignKeys.length > 1) throw new BetterAuthError(`Multiple foreign keys found for model ${model} and base model ${baseModel} while performing join operation. Only one foreign key is supported.`); + const [foreignKey, foreignKeyAttributes] = foreignKeys[0]; + if (!foreignKeyAttributes.references) throw new BetterAuthError(`No references found for foreign key ${foreignKey} on model ${model} while performing join operation.`); + let from; + let to; + let requiredSelectField; + if (isForwardJoin) { + requiredSelectField = foreignKeyAttributes.references.field; + from = getFieldName({ + model: baseModel, + field: requiredSelectField + }); + to = getFieldName({ + model, + field: foreignKey + }); + } else { + requiredSelectField = foreignKey; + from = getFieldName({ + model: baseModel, + field: requiredSelectField + }); + to = getFieldName({ + model, + field: foreignKeyAttributes.references.field + }); + } + if (select2 && !select2.includes(requiredSelectField)) select2.push(requiredSelectField); + const isUnique = to === "id" ? true : foreignKeyAttributes.unique ?? false; + let limit = options.advanced?.database?.defaultFindManyLimit ?? 100; + if (isUnique) limit = 1; + else if (typeof join4 === "object" && typeof join4.limit === "number") limit = join4.limit; + transformedJoin[getModelName(model)] = { + on: { + from, + to + }, + limit, + relation: isUnique ? "one-to-one" : "one-to-many" + }; + } + return { + join: transformedJoin, + select: select2 + }; + }; + const handleFallbackJoin = async ({ baseModel, baseData, joinModel, specificJoinConfig: joinConfig }) => { + if (!baseData) return baseData; + const modelName = getModelName(joinModel); + const field = joinConfig.on.to; + const value = baseData[getDefaultFieldName({ + field: joinConfig.on.from, + model: baseModel + })]; + if (value === null || value === void 0) return joinConfig.relation === "one-to-one" ? null : []; + let result; + const where = transformWhereClause({ + model: modelName, + where: [{ + field, + value, + operator: "eq", + connector: "AND" + }], + action: "findOne" + }); + try { + if (joinConfig.relation === "one-to-one") result = await adapterInstance.findOne({ + model: modelName, + where + }); + else { + const limit = joinConfig.limit ?? options.advanced?.database?.defaultFindManyLimit ?? 100; + result = await adapterInstance.findMany({ + model: modelName, + where, + limit + }); + } + } catch (error50) { + logger4.error(`Failed to query fallback join for model ${modelName}:`, { + where, + limit: joinConfig.limit + }); + console.error(error50); + throw error50; + } + return result; + }; + const adapterInstance = customAdapter({ + options, + schema: schema2, + debugLog, + getFieldName, + getModelName, + getDefaultModelName, + getDefaultFieldName, + getFieldAttributes, + transformInput, + transformOutput, + transformWhereClause + }); + let lazyLoadTransaction = null; + const adapter = { + transaction: async (cb) => { + if (!lazyLoadTransaction) if (!config3.transaction) lazyLoadTransaction = createAsIsTransaction(adapter); + else { + logger4.debug(`[${config3.adapterName}] - Using provided transaction implementation.`); + lazyLoadTransaction = config3.transaction; + } + return lazyLoadTransaction(cb); + }, + create: async ({ data: unsafeData, model: unsafeModel, select: select2, forceAllowId = false }) => { + transactionId++; + const thisTransactionId = transactionId; + const model = getModelName(unsafeModel); + unsafeModel = getDefaultModelName(unsafeModel); + if ("id" in unsafeData && typeof unsafeData.id !== "undefined" && !forceAllowId) { + logger4.warn(`[${config3.adapterName}] - You are trying to create a record with an id. This is not allowed as we handle id generation for you, unless you pass in the \`forceAllowId\` parameter. The id will be ignored.`); + const stack = (/* @__PURE__ */ new Error()).stack?.split("\n").filter((_, i5) => i5 !== 1).join("\n").replace("Error:", "Create method with `id` being called at:"); + console.log(stack); + unsafeData.id = void 0; + } + debugLog({ method: "create" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 4)}`, `${formatMethod("create")} ${formatAction("Unsafe Input")}:`, { + model, + data: unsafeData + }); + let data2 = unsafeData; + if (!config3.disableTransformInput) data2 = await transformInput(unsafeData, unsafeModel, "create", forceAllowId); + debugLog({ method: "create" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 4)}`, `${formatMethod("create")} ${formatAction("Parsed Input")}:`, { + model, + data: data2 + }); + const res = await adapterInstance.create({ + data: data2, + model + }); + debugLog({ method: "create" }, `${formatTransactionId(thisTransactionId)} ${formatStep(3, 4)}`, `${formatMethod("create")} ${formatAction("DB Result")}:`, { + model, + res + }); + let transformed = res; + if (!config3.disableTransformOutput) transformed = await transformOutput(res, unsafeModel, select2, void 0); + debugLog({ method: "create" }, `${formatTransactionId(thisTransactionId)} ${formatStep(4, 4)}`, `${formatMethod("create")} ${formatAction("Parsed Result")}:`, { + model, + data: transformed + }); + return transformed; + }, + update: async ({ model: unsafeModel, where: unsafeWhere, update: unsafeData }) => { + transactionId++; + const thisTransactionId = transactionId; + unsafeModel = getDefaultModelName(unsafeModel); + const model = getModelName(unsafeModel); + const where = transformWhereClause({ + model: unsafeModel, + where: unsafeWhere, + action: "update" + }); + debugLog({ method: "update" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 4)}`, `${formatMethod("update")} ${formatAction("Unsafe Input")}:`, { + model, + data: unsafeData + }); + let data2 = unsafeData; + if (!config3.disableTransformInput) data2 = await transformInput(unsafeData, unsafeModel, "update"); + debugLog({ method: "update" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 4)}`, `${formatMethod("update")} ${formatAction("Parsed Input")}:`, { + model, + data: data2 + }); + const res = await adapterInstance.update({ + model, + where, + update: data2 + }); + debugLog({ method: "update" }, `${formatTransactionId(thisTransactionId)} ${formatStep(3, 4)}`, `${formatMethod("update")} ${formatAction("DB Result")}:`, { + model, + data: res + }); + let transformed = res; + if (!config3.disableTransformOutput) transformed = await transformOutput(res, unsafeModel, void 0, void 0); + debugLog({ method: "update" }, `${formatTransactionId(thisTransactionId)} ${formatStep(4, 4)}`, `${formatMethod("update")} ${formatAction("Parsed Result")}:`, { + model, + data: transformed + }); + return transformed; + }, + updateMany: async ({ model: unsafeModel, where: unsafeWhere, update: unsafeData }) => { + transactionId++; + const thisTransactionId = transactionId; + const model = getModelName(unsafeModel); + const where = transformWhereClause({ + model: unsafeModel, + where: unsafeWhere, + action: "updateMany" + }); + unsafeModel = getDefaultModelName(unsafeModel); + debugLog({ method: "updateMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 4)}`, `${formatMethod("updateMany")} ${formatAction("Unsafe Input")}:`, { + model, + data: unsafeData + }); + let data2 = unsafeData; + if (!config3.disableTransformInput) data2 = await transformInput(unsafeData, unsafeModel, "update"); + debugLog({ method: "updateMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 4)}`, `${formatMethod("updateMany")} ${formatAction("Parsed Input")}:`, { + model, + data: data2 + }); + const updatedCount = await adapterInstance.updateMany({ + model, + where, + update: data2 + }); + debugLog({ method: "updateMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(3, 4)}`, `${formatMethod("updateMany")} ${formatAction("DB Result")}:`, { + model, + data: updatedCount + }); + debugLog({ method: "updateMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(4, 4)}`, `${formatMethod("updateMany")} ${formatAction("Parsed Result")}:`, { + model, + data: updatedCount + }); + return updatedCount; + }, + findOne: async ({ model: unsafeModel, where: unsafeWhere, select: select2, join: unsafeJoin }) => { + transactionId++; + const thisTransactionId = transactionId; + const model = getModelName(unsafeModel); + const where = transformWhereClause({ + model: unsafeModel, + where: unsafeWhere, + action: "findOne" + }); + unsafeModel = getDefaultModelName(unsafeModel); + let join4; + let passJoinToAdapter = true; + if (!config3.disableTransformJoin) { + const result = transformJoinClause(unsafeModel, unsafeJoin, select2); + if (result) { + join4 = result.join; + select2 = result.select; + } + if (!options.experimental?.joins && join4 && Object.keys(join4).length > 0) passJoinToAdapter = false; + } else join4 = unsafeJoin; + debugLog({ method: "findOne" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 3)}`, `${formatMethod("findOne")}:`, { + model, + where, + select: select2, + join: join4 + }); + const res = await adapterInstance.findOne({ + model, + where, + select: select2, + join: passJoinToAdapter ? join4 : void 0 + }); + debugLog({ method: "findOne" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 3)}`, `${formatMethod("findOne")} ${formatAction("DB Result")}:`, { + model, + data: res + }); + let transformed = res; + if (!config3.disableTransformOutput) transformed = await transformOutput(res, unsafeModel, select2, join4); + debugLog({ method: "findOne" }, `${formatTransactionId(thisTransactionId)} ${formatStep(3, 3)}`, `${formatMethod("findOne")} ${formatAction("Parsed Result")}:`, { + model, + data: transformed + }); + return transformed; + }, + findMany: async ({ model: unsafeModel, where: unsafeWhere, limit: unsafeLimit, sortBy, offset, join: unsafeJoin }) => { + transactionId++; + const thisTransactionId = transactionId; + const limit = unsafeLimit ?? options.advanced?.database?.defaultFindManyLimit ?? 100; + const model = getModelName(unsafeModel); + const where = transformWhereClause({ + model: unsafeModel, + where: unsafeWhere, + action: "findMany" + }); + unsafeModel = getDefaultModelName(unsafeModel); + let join4; + let passJoinToAdapter = true; + if (!config3.disableTransformJoin) { + const result = transformJoinClause(unsafeModel, unsafeJoin, void 0); + if (result) join4 = result.join; + if (!options.experimental?.joins && join4 && Object.keys(join4).length > 0) passJoinToAdapter = false; + } else join4 = unsafeJoin; + debugLog({ method: "findMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 3)}`, `${formatMethod("findMany")}:`, { + model, + where, + limit, + sortBy, + offset, + join: join4 + }); + const res = await adapterInstance.findMany({ + model, + where, + limit, + sortBy, + offset, + join: passJoinToAdapter ? join4 : void 0 + }); + debugLog({ method: "findMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 3)}`, `${formatMethod("findMany")} ${formatAction("DB Result")}:`, { + model, + data: res + }); + let transformed = res; + if (!config3.disableTransformOutput) transformed = await Promise.all(res.map(async (r5) => { + return await transformOutput(r5, unsafeModel, void 0, join4); + })); + debugLog({ method: "findMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(3, 3)}`, `${formatMethod("findMany")} ${formatAction("Parsed Result")}:`, { + model, + data: transformed + }); + return transformed; + }, + delete: async ({ model: unsafeModel, where: unsafeWhere }) => { + transactionId++; + const thisTransactionId = transactionId; + const model = getModelName(unsafeModel); + const where = transformWhereClause({ + model: unsafeModel, + where: unsafeWhere, + action: "delete" + }); + unsafeModel = getDefaultModelName(unsafeModel); + debugLog({ method: "delete" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 2)}`, `${formatMethod("delete")}:`, { + model, + where + }); + await adapterInstance.delete({ + model, + where + }); + debugLog({ method: "delete" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 2)}`, `${formatMethod("delete")} ${formatAction("DB Result")}:`, { model }); + }, + deleteMany: async ({ model: unsafeModel, where: unsafeWhere }) => { + transactionId++; + const thisTransactionId = transactionId; + const model = getModelName(unsafeModel); + const where = transformWhereClause({ + model: unsafeModel, + where: unsafeWhere, + action: "deleteMany" + }); + unsafeModel = getDefaultModelName(unsafeModel); + debugLog({ method: "deleteMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 2)}`, `${formatMethod("deleteMany")} ${formatAction("DeleteMany")}:`, { + model, + where + }); + const res = await adapterInstance.deleteMany({ + model, + where + }); + debugLog({ method: "deleteMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 2)}`, `${formatMethod("deleteMany")} ${formatAction("DB Result")}:`, { + model, + data: res + }); + return res; + }, + count: async ({ model: unsafeModel, where: unsafeWhere }) => { + transactionId++; + const thisTransactionId = transactionId; + const model = getModelName(unsafeModel); + const where = transformWhereClause({ + model: unsafeModel, + where: unsafeWhere, + action: "count" + }); + unsafeModel = getDefaultModelName(unsafeModel); + debugLog({ method: "count" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 2)}`, `${formatMethod("count")}:`, { + model, + where + }); + const res = await adapterInstance.count({ + model, + where + }); + debugLog({ method: "count" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 2)}`, `${formatMethod("count")}:`, { + model, + data: res + }); + return res; + }, + createSchema: adapterInstance.createSchema ? async (_, file2) => { + const tables = getAuthTables(options); + if (options.secondaryStorage && !options.session?.storeSessionInDatabase) delete tables.session; + return adapterInstance.createSchema({ + file: file2, + tables + }); + } : void 0, + options: { + adapterConfig: config3, + ...adapterInstance.options ?? {} + }, + id: config3.adapterId, + ...config3.debugLogs?.isRunningAdapterTests ? { adapterTestDebugLogs: { + resetDebugLogs() { + debugLogs = debugLogs.filter((log2) => log2.instance !== uniqueAdapterFactoryInstanceId); + }, + printDebugLogs() { + const separator = `\u2500`.repeat(80); + const logs = debugLogs.filter((log$1) => log$1.instance === uniqueAdapterFactoryInstanceId); + if (logs.length === 0) return; + const log2 = logs.reverse().map((log$1) => { + log$1.args[0] = ` +${log$1.args[0]}`; + return [...log$1.args, "\n"]; + }).reduce((prev, curr) => { + return [...curr, ...prev]; + }, [` +${separator}`]); + console.log(...log2); + } + } } : {} + }; + return adapter; + }; + } +}); + +// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/db/adapter/index.mjs +var init_adapter = __esm({ + "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/db/adapter/index.mjs"() { + init_get_default_model_name(); + init_get_default_field_name(); + init_get_id_field(); + init_get_field_attributes(); + init_get_field_name(); + init_get_model_name(); + init_utils11(); + init_factory(); + } +}); + +// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/adapters/memory-adapter/memory-adapter.mjs +var memoryAdapter; +var init_memory_adapter = __esm({ + "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/adapters/memory-adapter/memory-adapter.mjs"() { + init_env(); + init_adapter(); + memoryAdapter = (db, config3) => { + let lazyOptions = null; + const adapterCreator = createAdapterFactory({ + config: { + adapterId: "memory", + adapterName: "Memory Adapter", + usePlural: false, + debugLogs: config3?.debugLogs || false, + supportsArrays: true, + customTransformInput(props) { + if ((props.options.advanced?.database?.useNumberId || props.options.advanced?.database?.generateId === "serial") && props.field === "id" && props.action === "create") return db[props.model].length + 1; + return props.data; + }, + transaction: async (cb) => { + const clone3 = structuredClone(db); + try { + return await cb(adapterCreator(lazyOptions)); + } catch (error50) { + Object.keys(db).forEach((key) => { + db[key] = clone3[key]; + }); + throw error50; + } + } + }, + adapter: ({ getFieldName, options, getModelName }) => { + const applySortToRecords = (records, sortBy, model) => { + if (!sortBy) return records; + return records.sort((a5, b6) => { + const field = getFieldName({ + model, + field: sortBy.field + }); + const aValue = a5[field]; + const bValue = b6[field]; + let comparison = 0; + if (aValue == null && bValue == null) comparison = 0; + else if (aValue == null) comparison = -1; + else if (bValue == null) comparison = 1; + else if (typeof aValue === "string" && typeof bValue === "string") comparison = aValue.localeCompare(bValue); + else if (aValue instanceof Date && bValue instanceof Date) comparison = aValue.getTime() - bValue.getTime(); + else if (typeof aValue === "number" && typeof bValue === "number") comparison = aValue - bValue; + else if (typeof aValue === "boolean" && typeof bValue === "boolean") comparison = aValue === bValue ? 0 : aValue ? 1 : -1; + else comparison = String(aValue).localeCompare(String(bValue)); + return sortBy.direction === "asc" ? comparison : -comparison; + }); + }; + function convertWhereClause(where, model, join4) { + const execute11 = (where$1, model$1) => { + const table = db[model$1]; + if (!table) { + logger3.error(`[MemoryAdapter] Model ${model$1} not found in the DB`, Object.keys(db)); + throw new Error(`Model ${model$1} not found`); + } + const evalClause = (record2, clause) => { + const { field, value, operator } = clause; + switch (operator) { + case "in": + if (!Array.isArray(value)) throw new Error("Value must be an array"); + return value.includes(record2[field]); + case "not_in": + if (!Array.isArray(value)) throw new Error("Value must be an array"); + return !value.includes(record2[field]); + case "contains": + return record2[field].includes(value); + case "starts_with": + return record2[field].startsWith(value); + case "ends_with": + return record2[field].endsWith(value); + case "ne": + return record2[field] !== value; + case "gt": + return value != null && Boolean(record2[field] > value); + case "gte": + return value != null && Boolean(record2[field] >= value); + case "lt": + return value != null && Boolean(record2[field] < value); + case "lte": + return value != null && Boolean(record2[field] <= value); + default: + return record2[field] === value; + } + }; + return table.filter((record2) => { + if (!where$1.length || where$1.length === 0) return true; + let result = evalClause(record2, where$1[0]); + for (const clause of where$1) { + const clauseResult = evalClause(record2, clause); + if (clause.connector === "OR") result = result || clauseResult; + else result = result && clauseResult; + } + return result; + }); + }; + if (!join4) return execute11(where, model); + const baseRecords = execute11(where, model); + const grouped = /* @__PURE__ */ new Map(); + const seenIds = /* @__PURE__ */ new Map(); + for (const baseRecord of baseRecords) { + const baseId = String(baseRecord.id); + if (!grouped.has(baseId)) { + const nested = { ...baseRecord }; + for (const [joinModel, joinAttr] of Object.entries(join4)) { + const joinModelName = getModelName(joinModel); + if (joinAttr.relation === "one-to-one") nested[joinModelName] = null; + else { + nested[joinModelName] = []; + seenIds.set(`${baseId}-${joinModel}`, /* @__PURE__ */ new Set()); + } + } + grouped.set(baseId, nested); + } + const nestedEntry = grouped.get(baseId); + for (const [joinModel, joinAttr] of Object.entries(join4)) { + const joinModelName = getModelName(joinModel); + const joinTable = db[joinModelName]; + if (!joinTable) { + logger3.error(`[MemoryAdapter] JoinOption model ${joinModelName} not found in the DB`, Object.keys(db)); + throw new Error(`JoinOption model ${joinModelName} not found`); + } + const matchingRecords = joinTable.filter((joinRecord) => joinRecord[joinAttr.on.to] === baseRecord[joinAttr.on.from]); + if (joinAttr.relation === "one-to-one") nestedEntry[joinModelName] = matchingRecords[0] || null; + else { + const seenSet = seenIds.get(`${baseId}-${joinModel}`); + const limit = joinAttr.limit ?? 100; + let count2 = 0; + for (const matchingRecord of matchingRecords) { + if (count2 >= limit) break; + if (!seenSet.has(matchingRecord.id)) { + nestedEntry[joinModelName].push(matchingRecord); + seenSet.add(matchingRecord.id); + count2++; + } + } + } + } + } + return Array.from(grouped.values()); + } + return { + create: async ({ model, data: data2 }) => { + if (options.advanced?.database?.useNumberId || options.advanced?.database?.generateId === "serial") data2.id = db[getModelName(model)].length + 1; + if (!db[model]) db[model] = []; + db[model].push(data2); + return data2; + }, + findOne: async ({ model, where, join: join4 }) => { + const res = convertWhereClause(where, model, join4); + if (join4) { + const resArray = res; + if (!resArray.length) return null; + return resArray[0]; + } + return res[0] || null; + }, + findMany: async ({ model, where, sortBy, limit, offset, join: join4 }) => { + const res = convertWhereClause(where || [], model, join4); + if (join4) { + const resArray = res; + if (!resArray.length) return []; + applySortToRecords(resArray, sortBy, model); + let paginatedRecords = resArray; + if (offset !== void 0) paginatedRecords = paginatedRecords.slice(offset); + if (limit !== void 0) paginatedRecords = paginatedRecords.slice(0, limit); + return paginatedRecords; + } + let table = applySortToRecords(res, sortBy, model); + if (offset !== void 0) table = table.slice(offset); + if (limit !== void 0) table = table.slice(0, limit); + return table || []; + }, + count: async ({ model, where }) => { + if (where) return convertWhereClause(where, model).length; + return db[model].length; + }, + update: async ({ model, where, update }) => { + const res = convertWhereClause(where, model); + res.forEach((record2) => { + Object.assign(record2, update); + }); + return res[0] || null; + }, + delete: async ({ model, where }) => { + const table = db[model]; + const res = convertWhereClause(where, model); + db[model] = table.filter((record2) => !res.includes(record2)); + }, + deleteMany: async ({ model, where }) => { + const table = db[model]; + const res = convertWhereClause(where, model); + let count2 = 0; + db[model] = table.filter((record2) => { + if (res.includes(record2)) { + count2++; + return false; + } + return !res.includes(record2); + }); + return count2; + }, + updateMany({ model, where, update }) { + const res = convertWhereClause(where, model); + res.forEach((record2) => { + Object.assign(record2, update); + }); + return res[0] || null; + } + }; + } + }); + return (options) => { + lazyOptions = options; + return adapterCreator(options); + }; + }; + } +}); + +// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/adapters/memory-adapter/index.mjs +var memory_adapter_exports = {}; +__export(memory_adapter_exports, { + memoryAdapter: () => memoryAdapter +}); +var init_memory_adapter2 = __esm({ + "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/adapters/memory-adapter/index.mjs"() { + init_memory_adapter(); + } +}); + +// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/db/adapter-base.mjs +async function getBaseAdapter(options, handleDirectDatabase) { + let adapter; + if (!options.database) { + const tables = getAuthTables(options); + const memoryDB = Object.keys(tables).reduce((acc, key) => { + acc[key] = []; + return acc; + }, {}); + const { memoryAdapter: memoryAdapter2 } = await Promise.resolve().then(() => (init_memory_adapter2(), memory_adapter_exports)); + adapter = memoryAdapter2(memoryDB)(options); + } else if (typeof options.database === "function") adapter = options.database(options); + else adapter = await handleDirectDatabase(options); + if (!adapter.transaction) { + logger3.warn("Adapter does not correctly implement transaction function, patching it automatically. Please update your adapter implementation."); + adapter.transaction = async (cb) => { + return cb(adapter); + }; + } + return adapter; +} +var init_adapter_base = __esm({ + "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/db/adapter-base.mjs"() { + init_db3(); + init_env(); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/object-utils.js +function isUndefined(obj) { + return typeof obj === "undefined" || obj === void 0; +} +function isString(obj) { + return typeof obj === "string"; +} +function isNumber(obj) { + return typeof obj === "number"; +} +function isBoolean(obj) { + return typeof obj === "boolean"; +} +function isNull2(obj) { + return obj === null; +} +function isDate(obj) { + return obj instanceof Date; +} +function isBigInt(obj) { + return typeof obj === "bigint"; +} +function isBuffer(obj) { + return typeof Buffer !== "undefined" && Buffer.isBuffer(obj); +} +function isFunction(obj) { + return typeof obj === "function"; +} +function isObject3(obj) { + return typeof obj === "object" && obj !== null; +} +function freeze2(obj) { + return Object.freeze(obj); +} +function asArray(arg) { + if (isReadonlyArray(arg)) { + return arg; + } else { + return [arg]; + } +} +function isReadonlyArray(arg) { + return Array.isArray(arg); +} +function noop3(obj) { + return obj; +} +var init_object_utils = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/object-utils.js"() { + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/alter-table-node.js +var AlterTableNode; +var init_alter_table_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/alter-table-node.js"() { + init_object_utils(); + AlterTableNode = freeze2({ + is(node) { + return node.kind === "AlterTableNode"; + }, + create(table) { + return freeze2({ + kind: "AlterTableNode", + table + }); + }, + cloneWithTableProps(node, props) { + return freeze2({ + ...node, + ...props + }); + }, + cloneWithColumnAlteration(node, columnAlteration) { + return freeze2({ + ...node, + columnAlterations: node.columnAlterations ? [...node.columnAlterations, columnAlteration] : [columnAlteration] + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/identifier-node.js +var IdentifierNode; +var init_identifier_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/identifier-node.js"() { + init_object_utils(); + IdentifierNode = freeze2({ + is(node) { + return node.kind === "IdentifierNode"; + }, + create(name) { + return freeze2({ + kind: "IdentifierNode", + name + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/create-index-node.js +var CreateIndexNode; +var init_create_index_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/create-index-node.js"() { + init_object_utils(); + init_identifier_node(); + CreateIndexNode = freeze2({ + is(node) { + return node.kind === "CreateIndexNode"; + }, + create(name) { + return freeze2({ + kind: "CreateIndexNode", + name: IdentifierNode.create(name) + }); + }, + cloneWith(node, props) { + return freeze2({ + ...node, + ...props + }); + }, + cloneWithColumns(node, columns) { + return freeze2({ + ...node, + columns: [...node.columns || [], ...columns] + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/create-schema-node.js +var CreateSchemaNode; +var init_create_schema_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/create-schema-node.js"() { + init_object_utils(); + init_identifier_node(); + CreateSchemaNode = freeze2({ + is(node) { + return node.kind === "CreateSchemaNode"; + }, + create(schema2, params) { + return freeze2({ + kind: "CreateSchemaNode", + schema: IdentifierNode.create(schema2), + ...params + }); + }, + cloneWith(createSchema, params) { + return freeze2({ + ...createSchema, + ...params + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/create-table-node.js +var ON_COMMIT_ACTIONS, CreateTableNode; +var init_create_table_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/create-table-node.js"() { + init_object_utils(); + ON_COMMIT_ACTIONS = ["preserve rows", "delete rows", "drop"]; + CreateTableNode = freeze2({ + is(node) { + return node.kind === "CreateTableNode"; + }, + create(table) { + return freeze2({ + kind: "CreateTableNode", + table, + columns: freeze2([]) + }); + }, + cloneWithColumn(createTable, column) { + return freeze2({ + ...createTable, + columns: freeze2([...createTable.columns, column]) + }); + }, + cloneWithConstraint(createTable, constraint) { + return freeze2({ + ...createTable, + constraints: createTable.constraints ? freeze2([...createTable.constraints, constraint]) : freeze2([constraint]) + }); + }, + cloneWithFrontModifier(createTable, modifier) { + return freeze2({ + ...createTable, + frontModifiers: createTable.frontModifiers ? freeze2([...createTable.frontModifiers, modifier]) : freeze2([modifier]) + }); + }, + cloneWithEndModifier(createTable, modifier) { + return freeze2({ + ...createTable, + endModifiers: createTable.endModifiers ? freeze2([...createTable.endModifiers, modifier]) : freeze2([modifier]) + }); + }, + cloneWith(createTable, params) { + return freeze2({ + ...createTable, + ...params + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/schemable-identifier-node.js +var SchemableIdentifierNode; +var init_schemable_identifier_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/schemable-identifier-node.js"() { + init_object_utils(); + init_identifier_node(); + SchemableIdentifierNode = freeze2({ + is(node) { + return node.kind === "SchemableIdentifierNode"; + }, + create(identifier) { + return freeze2({ + kind: "SchemableIdentifierNode", + identifier: IdentifierNode.create(identifier) + }); + }, + createWithSchema(schema2, identifier) { + return freeze2({ + kind: "SchemableIdentifierNode", + schema: IdentifierNode.create(schema2), + identifier: IdentifierNode.create(identifier) + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/drop-index-node.js +var DropIndexNode; +var init_drop_index_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/drop-index-node.js"() { + init_object_utils(); + init_schemable_identifier_node(); + DropIndexNode = freeze2({ + is(node) { + return node.kind === "DropIndexNode"; + }, + create(name, params) { + return freeze2({ + kind: "DropIndexNode", + name: SchemableIdentifierNode.create(name), + ...params + }); + }, + cloneWith(dropIndex, props) { + return freeze2({ + ...dropIndex, + ...props + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/drop-schema-node.js +var DropSchemaNode; +var init_drop_schema_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/drop-schema-node.js"() { + init_object_utils(); + init_identifier_node(); + DropSchemaNode = freeze2({ + is(node) { + return node.kind === "DropSchemaNode"; + }, + create(schema2, params) { + return freeze2({ + kind: "DropSchemaNode", + schema: IdentifierNode.create(schema2), + ...params + }); + }, + cloneWith(dropSchema, params) { + return freeze2({ + ...dropSchema, + ...params + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/drop-table-node.js +var DropTableNode; +var init_drop_table_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/drop-table-node.js"() { + init_object_utils(); + DropTableNode = freeze2({ + is(node) { + return node.kind === "DropTableNode"; + }, + create(table, params) { + return freeze2({ + kind: "DropTableNode", + table, + ...params + }); + }, + cloneWith(dropIndex, params) { + return freeze2({ + ...dropIndex, + ...params + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/alias-node.js +var AliasNode; +var init_alias_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/alias-node.js"() { + init_object_utils(); + AliasNode = freeze2({ + is(node) { + return node.kind === "AliasNode"; + }, + create(node, alias) { + return freeze2({ + kind: "AliasNode", + node, + alias + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/table-node.js +var TableNode; +var init_table_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/table-node.js"() { + init_object_utils(); + init_schemable_identifier_node(); + TableNode = freeze2({ + is(node) { + return node.kind === "TableNode"; + }, + create(table) { + return freeze2({ + kind: "TableNode", + table: SchemableIdentifierNode.create(table) + }); + }, + createWithSchema(schema2, table) { + return freeze2({ + kind: "TableNode", + table: SchemableIdentifierNode.createWithSchema(schema2, table) + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/operation-node-source.js +function isOperationNodeSource(obj) { + return isObject3(obj) && isFunction(obj.toOperationNode); +} +var init_operation_node_source = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/operation-node-source.js"() { + init_object_utils(); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/expression/expression.js +function isExpression(obj) { + return isObject3(obj) && "expressionType" in obj && isOperationNodeSource(obj); +} +function isAliasedExpression(obj) { + return isObject3(obj) && "expression" in obj && isString(obj.alias) && isOperationNodeSource(obj); +} +var init_expression = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/expression/expression.js"() { + init_operation_node_source(); + init_object_utils(); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/select-modifier-node.js +var SelectModifierNode; +var init_select_modifier_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/select-modifier-node.js"() { + init_object_utils(); + SelectModifierNode = freeze2({ + is(node) { + return node.kind === "SelectModifierNode"; + }, + create(modifier, of) { + return freeze2({ + kind: "SelectModifierNode", + modifier, + of + }); + }, + createWithExpression(modifier) { + return freeze2({ + kind: "SelectModifierNode", + rawModifier: modifier + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/and-node.js +var AndNode; +var init_and_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/and-node.js"() { + init_object_utils(); + AndNode = freeze2({ + is(node) { + return node.kind === "AndNode"; + }, + create(left, right) { + return freeze2({ + kind: "AndNode", + left, + right + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/or-node.js +var OrNode; +var init_or_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/or-node.js"() { + init_object_utils(); + OrNode = freeze2({ + is(node) { + return node.kind === "OrNode"; + }, + create(left, right) { + return freeze2({ + kind: "OrNode", + left, + right + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/on-node.js +var OnNode; +var init_on_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/on-node.js"() { + init_object_utils(); + init_and_node(); + init_or_node(); + OnNode = freeze2({ + is(node) { + return node.kind === "OnNode"; + }, + create(filter) { + return freeze2({ + kind: "OnNode", + on: filter + }); + }, + cloneWithOperation(onNode, operator, operation2) { + return freeze2({ + ...onNode, + on: operator === "And" ? AndNode.create(onNode.on, operation2) : OrNode.create(onNode.on, operation2) + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/join-node.js +var JoinNode; +var init_join_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/join-node.js"() { + init_object_utils(); + init_on_node(); + JoinNode = freeze2({ + is(node) { + return node.kind === "JoinNode"; + }, + create(joinType, table) { + return freeze2({ + kind: "JoinNode", + joinType, + table, + on: void 0 + }); + }, + createWithOn(joinType, table, on) { + return freeze2({ + kind: "JoinNode", + joinType, + table, + on: OnNode.create(on) + }); + }, + cloneWithOn(joinNode, operation2) { + return freeze2({ + ...joinNode, + on: joinNode.on ? OnNode.cloneWithOperation(joinNode.on, "And", operation2) : OnNode.create(operation2) + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/binary-operation-node.js +var BinaryOperationNode; +var init_binary_operation_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/binary-operation-node.js"() { + init_object_utils(); + BinaryOperationNode = freeze2({ + is(node) { + return node.kind === "BinaryOperationNode"; + }, + create(leftOperand, operator, rightOperand) { + return freeze2({ + kind: "BinaryOperationNode", + leftOperand, + operator, + rightOperand + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/operator-node.js +function isJSONOperator(op2) { + return isString(op2) && JSON_OPERATORS.includes(op2); +} +var COMPARISON_OPERATORS, ARITHMETIC_OPERATORS, JSON_OPERATORS, BINARY_OPERATORS, UNARY_FILTER_OPERATORS, UNARY_OPERATORS, OPERATORS, OperatorNode; +var init_operator_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/operator-node.js"() { + init_object_utils(); + COMPARISON_OPERATORS = [ + "=", + "==", + "!=", + "<>", + ">", + ">=", + "<", + "<=", + "in", + "not in", + "is", + "is not", + "like", + "not like", + "match", + "ilike", + "not ilike", + "@>", + "<@", + "^@", + "&&", + "?", + "?&", + "?|", + "!<", + "!>", + "<=>", + "!~", + "~", + "~*", + "!~*", + "@@", + "@@@", + "!!", + "<->", + "regexp", + "is distinct from", + "is not distinct from" + ]; + ARITHMETIC_OPERATORS = [ + "+", + "-", + "*", + "/", + "%", + "^", + "&", + "|", + "#", + "<<", + ">>" + ]; + JSON_OPERATORS = ["->", "->>"]; + BINARY_OPERATORS = [ + ...COMPARISON_OPERATORS, + ...ARITHMETIC_OPERATORS, + "&&", + "||" + ]; + UNARY_FILTER_OPERATORS = ["exists", "not exists"]; + UNARY_OPERATORS = ["not", "-", ...UNARY_FILTER_OPERATORS]; + OPERATORS = [ + ...BINARY_OPERATORS, + ...JSON_OPERATORS, + ...UNARY_OPERATORS, + "between", + "between symmetric" + ]; + OperatorNode = freeze2({ + is(node) { + return node.kind === "OperatorNode"; + }, + create(operator) { + return freeze2({ + kind: "OperatorNode", + operator + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/column-node.js +var ColumnNode; +var init_column_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/column-node.js"() { + init_object_utils(); + init_identifier_node(); + ColumnNode = freeze2({ + is(node) { + return node.kind === "ColumnNode"; + }, + create(column) { + return freeze2({ + kind: "ColumnNode", + column: IdentifierNode.create(column) + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/select-all-node.js +var SelectAllNode; +var init_select_all_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/select-all-node.js"() { + init_object_utils(); + SelectAllNode = freeze2({ + is(node) { + return node.kind === "SelectAllNode"; + }, + create() { + return freeze2({ + kind: "SelectAllNode" + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/reference-node.js +var ReferenceNode; +var init_reference_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/reference-node.js"() { + init_select_all_node(); + init_object_utils(); + ReferenceNode = freeze2({ + is(node) { + return node.kind === "ReferenceNode"; + }, + create(column, table) { + return freeze2({ + kind: "ReferenceNode", + table, + column + }); + }, + createSelectAll(table) { + return freeze2({ + kind: "ReferenceNode", + table, + column: SelectAllNode.create() + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dynamic/dynamic-reference-builder.js +function isDynamicReferenceBuilder(obj) { + return isObject3(obj) && isOperationNodeSource(obj) && isString(obj.dynamicReference); +} +var DynamicReferenceBuilder; +var init_dynamic_reference_builder = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dynamic/dynamic-reference-builder.js"() { + init_operation_node_source(); + init_reference_parser(); + init_object_utils(); + DynamicReferenceBuilder = class { + #dynamicReference; + get dynamicReference() { + return this.#dynamicReference; + } + /** + * @private + * + * This needs to be here just so that the typings work. Without this + * the generated .d.ts file contains no reference to the type param R + * which causes this type to be equal to DynamicReferenceBuilder with + * any R. + */ + get refType() { + return void 0; + } + constructor(reference) { + this.#dynamicReference = reference; + } + toOperationNode() { + return parseSimpleReferenceExpression(this.#dynamicReference); + } + }; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/order-by-item-node.js +var OrderByItemNode; +var init_order_by_item_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/order-by-item-node.js"() { + init_object_utils(); + OrderByItemNode = freeze2({ + is(node) { + return node.kind === "OrderByItemNode"; + }, + create(orderBy, direction) { + return freeze2({ + kind: "OrderByItemNode", + orderBy, + direction + }); + }, + cloneWith(node, props) { + return freeze2({ + ...node, + ...props + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/raw-node.js +var RawNode; +var init_raw_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/raw-node.js"() { + init_object_utils(); + RawNode = freeze2({ + is(node) { + return node.kind === "RawNode"; + }, + create(sqlFragments, parameters) { + return freeze2({ + kind: "RawNode", + sqlFragments: freeze2(sqlFragments), + parameters: freeze2(parameters) + }); + }, + createWithSql(sql3) { + return RawNode.create([sql3], []); + }, + createWithChild(child) { + return RawNode.create(["", ""], [child]); + }, + createWithChildren(children) { + return RawNode.create(new Array(children.length + 1).fill(""), children); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/collate-node.js +var CollateNode; +var init_collate_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/collate-node.js"() { + init_object_utils(); + init_identifier_node(); + CollateNode = freeze2({ + is(node) { + return node.kind === "CollateNode"; + }, + create(collation) { + return freeze2({ + kind: "CollateNode", + collation: IdentifierNode.create(collation) + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/order-by-item-builder.js +var OrderByItemBuilder; +var init_order_by_item_builder = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/order-by-item-builder.js"() { + init_collate_node(); + init_order_by_item_node(); + init_raw_node(); + init_object_utils(); + OrderByItemBuilder = class _OrderByItemBuilder { + #props; + constructor(props) { + this.#props = freeze2(props); + } + /** + * Adds `desc` to the `order by` item. + * + * See {@link asc} for the opposite. + */ + desc() { + return new _OrderByItemBuilder({ + node: OrderByItemNode.cloneWith(this.#props.node, { + direction: RawNode.createWithSql("desc") + }) + }); + } + /** + * Adds `asc` to the `order by` item. + * + * See {@link desc} for the opposite. + */ + asc() { + return new _OrderByItemBuilder({ + node: OrderByItemNode.cloneWith(this.#props.node, { + direction: RawNode.createWithSql("asc") + }) + }); + } + /** + * Adds `nulls last` to the `order by` item. + * + * This is only supported by some dialects like PostgreSQL and SQLite. + * + * See {@link nullsFirst} for the opposite. + */ + nullsLast() { + return new _OrderByItemBuilder({ + node: OrderByItemNode.cloneWith(this.#props.node, { nulls: "last" }) + }); + } + /** + * Adds `nulls first` to the `order by` item. + * + * This is only supported by some dialects like PostgreSQL and SQLite. + * + * See {@link nullsLast} for the opposite. + */ + nullsFirst() { + return new _OrderByItemBuilder({ + node: OrderByItemNode.cloneWith(this.#props.node, { nulls: "first" }) + }); + } + /** + * Adds `collate ` to the `order by` item. + */ + collate(collation) { + return new _OrderByItemBuilder({ + node: OrderByItemNode.cloneWith(this.#props.node, { + collation: CollateNode.create(collation) + }) + }); + } + toOperationNode() { + return this.#props.node; + } + }; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/log-once.js +function logOnce(message2) { + if (LOGGED_MESSAGES.has(message2)) { + return; + } + LOGGED_MESSAGES.add(message2); + console.log(message2); +} +var LOGGED_MESSAGES; +var init_log_once = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/log-once.js"() { + LOGGED_MESSAGES = /* @__PURE__ */ new Set(); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/order-by-parser.js +function isOrderByDirection(thing) { + return thing === "asc" || thing === "desc"; +} +function parseOrderBy(args) { + if (args.length === 2) { + return [parseOrderByItem(args[0], args[1])]; + } + if (args.length === 1) { + const [orderBy] = args; + if (Array.isArray(orderBy)) { + logOnce("orderBy(array) is deprecated, use multiple orderBy calls instead."); + return orderBy.map((item) => parseOrderByItem(item)); + } + return [parseOrderByItem(orderBy)]; + } + throw new Error(`Invalid number of arguments at order by! expected 1-2, received ${args.length}`); +} +function parseOrderByItem(expr, modifiers) { + const parsedRef = parseOrderByExpression(expr); + if (OrderByItemNode.is(parsedRef)) { + if (modifiers) { + throw new Error("Cannot specify direction twice!"); + } + return parsedRef; + } + return parseOrderByWithModifiers(parsedRef, modifiers); +} +function parseOrderByExpression(expr) { + if (isExpressionOrFactory(expr)) { + return parseExpression(expr); + } + if (isDynamicReferenceBuilder(expr)) { + return expr.toOperationNode(); + } + const [ref, direction] = expr.split(" "); + if (direction) { + logOnce("`orderBy('column asc')` is deprecated. Use `orderBy('column', 'asc')` instead."); + return parseOrderByWithModifiers(parseStringReference(ref), direction); + } + return parseStringReference(expr); +} +function parseOrderByWithModifiers(expr, modifiers) { + if (typeof modifiers === "string") { + if (!isOrderByDirection(modifiers)) { + throw new Error(`Invalid order by direction: ${modifiers}`); + } + return OrderByItemNode.create(expr, RawNode.createWithSql(modifiers)); + } + if (isExpression(modifiers)) { + logOnce("`orderBy(..., expr)` is deprecated. Use `orderBy(..., 'asc')` or `orderBy(..., (ob) => ...)` instead."); + return OrderByItemNode.create(expr, modifiers.toOperationNode()); + } + const node = OrderByItemNode.create(expr); + if (!modifiers) { + return node; + } + return modifiers(new OrderByItemBuilder({ node })).toOperationNode(); +} +var init_order_by_parser = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/order-by-parser.js"() { + init_dynamic_reference_builder(); + init_expression(); + init_order_by_item_node(); + init_raw_node(); + init_order_by_item_builder(); + init_log_once(); + init_expression_parser(); + init_reference_parser(); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/json-reference-node.js +var JSONReferenceNode; +var init_json_reference_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/json-reference-node.js"() { + init_object_utils(); + JSONReferenceNode = freeze2({ + is(node) { + return node.kind === "JSONReferenceNode"; + }, + create(reference, traversal) { + return freeze2({ + kind: "JSONReferenceNode", + reference, + traversal + }); + }, + cloneWithTraversal(node, traversal) { + return freeze2({ + ...node, + traversal + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/json-operator-chain-node.js +var JSONOperatorChainNode; +var init_json_operator_chain_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/json-operator-chain-node.js"() { + init_object_utils(); + JSONOperatorChainNode = freeze2({ + is(node) { + return node.kind === "JSONOperatorChainNode"; + }, + create(operator) { + return freeze2({ + kind: "JSONOperatorChainNode", + operator, + values: freeze2([]) + }); + }, + cloneWithValue(node, value) { + return freeze2({ + ...node, + values: freeze2([...node.values, value]) + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/json-path-node.js +var JSONPathNode; +var init_json_path_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/json-path-node.js"() { + init_object_utils(); + JSONPathNode = freeze2({ + is(node) { + return node.kind === "JSONPathNode"; + }, + create(inOperator) { + return freeze2({ + kind: "JSONPathNode", + inOperator, + pathLegs: freeze2([]) + }); + }, + cloneWithLeg(jsonPathNode, pathLeg) { + return freeze2({ + ...jsonPathNode, + pathLegs: freeze2([...jsonPathNode.pathLegs, pathLeg]) + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/reference-parser.js +function parseSimpleReferenceExpression(exp) { + if (isString(exp)) { + return parseStringReference(exp); + } + return exp.toOperationNode(); +} +function parseReferenceExpressionOrList(arg) { + if (isReadonlyArray(arg)) { + return arg.map((it) => parseReferenceExpression(it)); + } else { + return [parseReferenceExpression(arg)]; + } +} +function parseReferenceExpression(exp) { + if (isExpressionOrFactory(exp)) { + return parseExpression(exp); + } + return parseSimpleReferenceExpression(exp); +} +function parseJSONReference(ref, op2) { + const referenceNode = parseStringReference(ref); + if (isJSONOperator(op2)) { + return JSONReferenceNode.create(referenceNode, JSONOperatorChainNode.create(OperatorNode.create(op2))); + } + const opWithoutLastChar = op2.slice(0, -1); + if (isJSONOperator(opWithoutLastChar)) { + return JSONReferenceNode.create(referenceNode, JSONPathNode.create(OperatorNode.create(opWithoutLastChar))); + } + throw new Error(`Invalid JSON operator: ${op2}`); +} +function parseStringReference(ref) { + const COLUMN_SEPARATOR = "."; + if (!ref.includes(COLUMN_SEPARATOR)) { + return ReferenceNode.create(ColumnNode.create(ref)); + } + const parts = ref.split(COLUMN_SEPARATOR).map(trim); + if (parts.length === 3) { + return parseStringReferenceWithTableAndSchema(parts); + } + if (parts.length === 2) { + return parseStringReferenceWithTable(parts); + } + throw new Error(`invalid column reference ${ref}`); +} +function parseAliasedStringReference(ref) { + const ALIAS_SEPARATOR = " as "; + if (ref.includes(ALIAS_SEPARATOR)) { + const [columnRef, alias] = ref.split(ALIAS_SEPARATOR).map(trim); + return AliasNode.create(parseStringReference(columnRef), IdentifierNode.create(alias)); + } else { + return parseStringReference(ref); + } +} +function parseColumnName(column) { + return ColumnNode.create(column); +} +function parseOrderedColumnName(column) { + const ORDER_SEPARATOR = " "; + if (column.includes(ORDER_SEPARATOR)) { + const [columnName, order] = column.split(ORDER_SEPARATOR).map(trim); + if (!isOrderByDirection(order)) { + throw new Error(`invalid order direction "${order}" next to "${columnName}"`); + } + return parseOrderBy([columnName, order])[0]; + } else { + return parseColumnName(column); + } +} +function parseStringReferenceWithTableAndSchema(parts) { + const [schema2, table, column] = parts; + return ReferenceNode.create(ColumnNode.create(column), TableNode.createWithSchema(schema2, table)); +} +function parseStringReferenceWithTable(parts) { + const [table, column] = parts; + return ReferenceNode.create(ColumnNode.create(column), TableNode.create(table)); +} +function trim(str) { + return str.trim(); +} +var init_reference_parser = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/reference-parser.js"() { + init_alias_node(); + init_column_node(); + init_reference_node(); + init_table_node(); + init_object_utils(); + init_expression_parser(); + init_identifier_node(); + init_order_by_parser(); + init_operator_node(); + init_json_reference_node(); + init_json_operator_chain_node(); + init_json_path_node(); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/primitive-value-list-node.js +var PrimitiveValueListNode; +var init_primitive_value_list_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/primitive-value-list-node.js"() { + init_object_utils(); + PrimitiveValueListNode = freeze2({ + is(node) { + return node.kind === "PrimitiveValueListNode"; + }, + create(values2) { + return freeze2({ + kind: "PrimitiveValueListNode", + values: freeze2([...values2]) + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/value-list-node.js +var ValueListNode; +var init_value_list_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/value-list-node.js"() { + init_object_utils(); + ValueListNode = freeze2({ + is(node) { + return node.kind === "ValueListNode"; + }, + create(values2) { + return freeze2({ + kind: "ValueListNode", + values: freeze2(values2) + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/value-node.js +var ValueNode; +var init_value_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/value-node.js"() { + init_object_utils(); + ValueNode = freeze2({ + is(node) { + return node.kind === "ValueNode"; + }, + create(value) { + return freeze2({ + kind: "ValueNode", + value + }); + }, + createImmediate(value) { + return freeze2({ + kind: "ValueNode", + value, + immediate: true + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/value-parser.js +function parseValueExpressionOrList(arg) { + if (isReadonlyArray(arg)) { + return parseValueExpressionList(arg); + } + return parseValueExpression(arg); +} +function parseValueExpression(exp) { + if (isExpressionOrFactory(exp)) { + return parseExpression(exp); + } + return ValueNode.create(exp); +} +function isSafeImmediateValue(value) { + return isNumber(value) || isBoolean(value) || isNull2(value); +} +function parseSafeImmediateValue(value) { + if (!isSafeImmediateValue(value)) { + throw new Error(`unsafe immediate value ${JSON.stringify(value)}`); + } + return ValueNode.createImmediate(value); +} +function parseValueExpressionList(arg) { + if (arg.some(isExpressionOrFactory)) { + return ValueListNode.create(arg.map((it) => parseValueExpression(it))); + } + return PrimitiveValueListNode.create(arg); +} +var init_value_parser = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/value-parser.js"() { + init_primitive_value_list_node(); + init_value_list_node(); + init_value_node(); + init_object_utils(); + init_expression_parser(); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/parens-node.js +var ParensNode; +var init_parens_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/parens-node.js"() { + init_object_utils(); + ParensNode = freeze2({ + is(node) { + return node.kind === "ParensNode"; + }, + create(node) { + return freeze2({ + kind: "ParensNode", + node + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/binary-operation-parser.js +function parseValueBinaryOperationOrExpression(args) { + if (args.length === 3) { + return parseValueBinaryOperation(args[0], args[1], args[2]); + } else if (args.length === 1) { + return parseValueExpression(args[0]); + } + throw new Error(`invalid arguments: ${JSON.stringify(args)}`); +} +function parseValueBinaryOperation(left, operator, right) { + if (isIsOperator(operator) && needsIsOperator(right)) { + return BinaryOperationNode.create(parseReferenceExpression(left), parseOperator(operator), ValueNode.createImmediate(right)); + } + return BinaryOperationNode.create(parseReferenceExpression(left), parseOperator(operator), parseValueExpressionOrList(right)); +} +function parseReferentialBinaryOperation(left, operator, right) { + return BinaryOperationNode.create(parseReferenceExpression(left), parseOperator(operator), parseReferenceExpression(right)); +} +function parseFilterObject(obj, combinator) { + return parseFilterList(Object.entries(obj).filter(([, v5]) => !isUndefined(v5)).map(([k5, v5]) => parseValueBinaryOperation(k5, needsIsOperator(v5) ? "is" : "=", v5)), combinator); +} +function parseFilterList(list2, combinator, withParens = true) { + const combine = combinator === "and" ? AndNode.create : OrNode.create; + if (list2.length === 0) { + return BinaryOperationNode.create(ValueNode.createImmediate(1), OperatorNode.create("="), ValueNode.createImmediate(combinator === "and" ? 1 : 0)); + } + let node = toOperationNode(list2[0]); + for (let i5 = 1; i5 < list2.length; ++i5) { + node = combine(node, toOperationNode(list2[i5])); + } + if (list2.length > 1 && withParens) { + return ParensNode.create(node); + } + return node; +} +function isIsOperator(operator) { + return operator === "is" || operator === "is not"; +} +function needsIsOperator(value) { + return isNull2(value) || isBoolean(value); +} +function parseOperator(operator) { + if (isString(operator) && OPERATORS.includes(operator)) { + return OperatorNode.create(operator); + } + if (isOperationNodeSource(operator)) { + return operator.toOperationNode(); + } + throw new Error(`invalid operator ${JSON.stringify(operator)}`); +} +function toOperationNode(nodeOrSource) { + return isOperationNodeSource(nodeOrSource) ? nodeOrSource.toOperationNode() : nodeOrSource; +} +var init_binary_operation_parser = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/binary-operation-parser.js"() { + init_binary_operation_node(); + init_object_utils(); + init_operation_node_source(); + init_operator_node(); + init_reference_parser(); + init_value_parser(); + init_value_node(); + init_and_node(); + init_parens_node(); + init_or_node(); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/order-by-node.js +var OrderByNode; +var init_order_by_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/order-by-node.js"() { + init_object_utils(); + OrderByNode = freeze2({ + is(node) { + return node.kind === "OrderByNode"; + }, + create(items) { + return freeze2({ + kind: "OrderByNode", + items: freeze2([...items]) + }); + }, + cloneWithItems(orderBy, items) { + return freeze2({ + ...orderBy, + items: freeze2([...orderBy.items, ...items]) + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/partition-by-node.js +var PartitionByNode; +var init_partition_by_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/partition-by-node.js"() { + init_object_utils(); + PartitionByNode = freeze2({ + is(node) { + return node.kind === "PartitionByNode"; + }, + create(items) { + return freeze2({ + kind: "PartitionByNode", + items: freeze2(items) + }); + }, + cloneWithItems(partitionBy, items) { + return freeze2({ + ...partitionBy, + items: freeze2([...partitionBy.items, ...items]) + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/over-node.js +var OverNode; +var init_over_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/over-node.js"() { + init_object_utils(); + init_order_by_node(); + init_partition_by_node(); + OverNode = freeze2({ + is(node) { + return node.kind === "OverNode"; + }, + create() { + return freeze2({ + kind: "OverNode" + }); + }, + cloneWithOrderByItems(overNode, items) { + return freeze2({ + ...overNode, + orderBy: overNode.orderBy ? OrderByNode.cloneWithItems(overNode.orderBy, items) : OrderByNode.create(items) + }); + }, + cloneWithPartitionByItems(overNode, items) { + return freeze2({ + ...overNode, + partitionBy: overNode.partitionBy ? PartitionByNode.cloneWithItems(overNode.partitionBy, items) : PartitionByNode.create(items) + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/from-node.js +var FromNode; +var init_from_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/from-node.js"() { + init_object_utils(); + FromNode = freeze2({ + is(node) { + return node.kind === "FromNode"; + }, + create(froms) { + return freeze2({ + kind: "FromNode", + froms: freeze2(froms) + }); + }, + cloneWithFroms(from, froms) { + return freeze2({ + ...from, + froms: freeze2([...from.froms, ...froms]) + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/group-by-node.js +var GroupByNode; +var init_group_by_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/group-by-node.js"() { + init_object_utils(); + GroupByNode = freeze2({ + is(node) { + return node.kind === "GroupByNode"; + }, + create(items) { + return freeze2({ + kind: "GroupByNode", + items: freeze2(items) + }); + }, + cloneWithItems(groupBy, items) { + return freeze2({ + ...groupBy, + items: freeze2([...groupBy.items, ...items]) + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/having-node.js +var HavingNode; +var init_having_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/having-node.js"() { + init_object_utils(); + init_and_node(); + init_or_node(); + HavingNode = freeze2({ + is(node) { + return node.kind === "HavingNode"; + }, + create(filter) { + return freeze2({ + kind: "HavingNode", + having: filter + }); + }, + cloneWithOperation(havingNode, operator, operation2) { + return freeze2({ + ...havingNode, + having: operator === "And" ? AndNode.create(havingNode.having, operation2) : OrNode.create(havingNode.having, operation2) + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/insert-query-node.js +var InsertQueryNode; +var init_insert_query_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/insert-query-node.js"() { + init_object_utils(); + InsertQueryNode = freeze2({ + is(node) { + return node.kind === "InsertQueryNode"; + }, + create(into, withNode, replace) { + return freeze2({ + kind: "InsertQueryNode", + into, + ...withNode && { with: withNode }, + replace + }); + }, + createWithoutInto() { + return freeze2({ + kind: "InsertQueryNode" + }); + }, + cloneWith(insertQuery, props) { + return freeze2({ + ...insertQuery, + ...props + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/list-node.js +var ListNode; +var init_list_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/list-node.js"() { + init_object_utils(); + ListNode = freeze2({ + is(node) { + return node.kind === "ListNode"; + }, + create(items) { + return freeze2({ + kind: "ListNode", + items: freeze2(items) + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/update-query-node.js +var UpdateQueryNode; +var init_update_query_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/update-query-node.js"() { + init_object_utils(); + init_from_node(); + init_list_node(); + UpdateQueryNode = freeze2({ + is(node) { + return node.kind === "UpdateQueryNode"; + }, + create(tables, withNode) { + return freeze2({ + kind: "UpdateQueryNode", + // For backwards compatibility, use the raw table node when there's only one table + // and don't rename the property to something like `tables`. + table: tables.length === 1 ? tables[0] : ListNode.create(tables), + ...withNode && { with: withNode } + }); + }, + createWithoutTable() { + return freeze2({ + kind: "UpdateQueryNode" + }); + }, + cloneWithFromItems(updateQuery, fromItems) { + return freeze2({ + ...updateQuery, + from: updateQuery.from ? FromNode.cloneWithFroms(updateQuery.from, fromItems) : FromNode.create(fromItems) + }); + }, + cloneWithUpdates(updateQuery, updates) { + return freeze2({ + ...updateQuery, + updates: updateQuery.updates ? freeze2([...updateQuery.updates, ...updates]) : updates + }); + }, + cloneWithLimit(updateQuery, limit) { + return freeze2({ + ...updateQuery, + limit + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/using-node.js +var UsingNode; +var init_using_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/using-node.js"() { + init_object_utils(); + UsingNode = freeze2({ + is(node) { + return node.kind === "UsingNode"; + }, + create(tables) { + return freeze2({ + kind: "UsingNode", + tables: freeze2(tables) + }); + }, + cloneWithTables(using, tables) { + return freeze2({ + ...using, + tables: freeze2([...using.tables, ...tables]) + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/delete-query-node.js +var DeleteQueryNode; +var init_delete_query_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/delete-query-node.js"() { + init_object_utils(); + init_from_node(); + init_using_node(); + init_query_node(); + DeleteQueryNode = freeze2({ + is(node) { + return node.kind === "DeleteQueryNode"; + }, + create(fromItems, withNode) { + return freeze2({ + kind: "DeleteQueryNode", + from: FromNode.create(fromItems), + ...withNode && { with: withNode } + }); + }, + // TODO: remove in v0.29 + /** + * @deprecated Use `QueryNode.cloneWithoutOrderBy` instead. + */ + cloneWithOrderByItems: (node, items) => QueryNode.cloneWithOrderByItems(node, items), + // TODO: remove in v0.29 + /** + * @deprecated Use `QueryNode.cloneWithoutOrderBy` instead. + */ + cloneWithoutOrderBy: (node) => QueryNode.cloneWithoutOrderBy(node), + cloneWithLimit(deleteNode, limit) { + return freeze2({ + ...deleteNode, + limit + }); + }, + cloneWithoutLimit(deleteNode) { + return freeze2({ + ...deleteNode, + limit: void 0 + }); + }, + cloneWithUsing(deleteNode, tables) { + return freeze2({ + ...deleteNode, + using: deleteNode.using !== void 0 ? UsingNode.cloneWithTables(deleteNode.using, tables) : UsingNode.create(tables) + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/where-node.js +var WhereNode; +var init_where_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/where-node.js"() { + init_object_utils(); + init_and_node(); + init_or_node(); + WhereNode = freeze2({ + is(node) { + return node.kind === "WhereNode"; + }, + create(filter) { + return freeze2({ + kind: "WhereNode", + where: filter + }); + }, + cloneWithOperation(whereNode, operator, operation2) { + return freeze2({ + ...whereNode, + where: operator === "And" ? AndNode.create(whereNode.where, operation2) : OrNode.create(whereNode.where, operation2) + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/returning-node.js +var ReturningNode; +var init_returning_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/returning-node.js"() { + init_object_utils(); + ReturningNode = freeze2({ + is(node) { + return node.kind === "ReturningNode"; + }, + create(selections) { + return freeze2({ + kind: "ReturningNode", + selections: freeze2(selections) + }); + }, + cloneWithSelections(returning, selections) { + return freeze2({ + ...returning, + selections: returning.selections ? freeze2([...returning.selections, ...selections]) : freeze2(selections) + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/explain-node.js +var ExplainNode; +var init_explain_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/explain-node.js"() { + init_object_utils(); + ExplainNode = freeze2({ + is(node) { + return node.kind === "ExplainNode"; + }, + create(format2, options) { + return freeze2({ + kind: "ExplainNode", + format: format2, + options + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/when-node.js +var WhenNode; +var init_when_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/when-node.js"() { + init_object_utils(); + WhenNode = freeze2({ + is(node) { + return node.kind === "WhenNode"; + }, + create(condition) { + return freeze2({ + kind: "WhenNode", + condition + }); + }, + cloneWithResult(whenNode, result) { + return freeze2({ + ...whenNode, + result + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/merge-query-node.js +var MergeQueryNode; +var init_merge_query_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/merge-query-node.js"() { + init_object_utils(); + init_when_node(); + MergeQueryNode = freeze2({ + is(node) { + return node.kind === "MergeQueryNode"; + }, + create(into, withNode) { + return freeze2({ + kind: "MergeQueryNode", + into, + ...withNode && { with: withNode } + }); + }, + cloneWithUsing(mergeNode, using) { + return freeze2({ + ...mergeNode, + using + }); + }, + cloneWithWhen(mergeNode, when) { + return freeze2({ + ...mergeNode, + whens: mergeNode.whens ? freeze2([...mergeNode.whens, when]) : freeze2([when]) + }); + }, + cloneWithThen(mergeNode, then) { + return freeze2({ + ...mergeNode, + whens: mergeNode.whens ? freeze2([ + ...mergeNode.whens.slice(0, -1), + WhenNode.cloneWithResult(mergeNode.whens[mergeNode.whens.length - 1], then) + ]) : void 0 + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/output-node.js +var OutputNode; +var init_output_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/output-node.js"() { + init_object_utils(); + OutputNode = freeze2({ + is(node) { + return node.kind === "OutputNode"; + }, + create(selections) { + return freeze2({ + kind: "OutputNode", + selections: freeze2(selections) + }); + }, + cloneWithSelections(output, selections) { + return freeze2({ + ...output, + selections: output.selections ? freeze2([...output.selections, ...selections]) : freeze2(selections) + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/query-node.js +var QueryNode; +var init_query_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/query-node.js"() { + init_insert_query_node(); + init_select_query_node(); + init_update_query_node(); + init_delete_query_node(); + init_where_node(); + init_object_utils(); + init_returning_node(); + init_explain_node(); + init_merge_query_node(); + init_output_node(); + init_order_by_node(); + QueryNode = freeze2({ + is(node) { + return SelectQueryNode.is(node) || InsertQueryNode.is(node) || UpdateQueryNode.is(node) || DeleteQueryNode.is(node) || MergeQueryNode.is(node); + }, + cloneWithEndModifier(node, modifier) { + return freeze2({ + ...node, + endModifiers: node.endModifiers ? freeze2([...node.endModifiers, modifier]) : freeze2([modifier]) + }); + }, + cloneWithWhere(node, operation2) { + return freeze2({ + ...node, + where: node.where ? WhereNode.cloneWithOperation(node.where, "And", operation2) : WhereNode.create(operation2) + }); + }, + cloneWithJoin(node, join4) { + return freeze2({ + ...node, + joins: node.joins ? freeze2([...node.joins, join4]) : freeze2([join4]) + }); + }, + cloneWithReturning(node, selections) { + return freeze2({ + ...node, + returning: node.returning ? ReturningNode.cloneWithSelections(node.returning, selections) : ReturningNode.create(selections) + }); + }, + cloneWithoutReturning(node) { + return freeze2({ + ...node, + returning: void 0 + }); + }, + cloneWithoutWhere(node) { + return freeze2({ + ...node, + where: void 0 + }); + }, + cloneWithExplain(node, format2, options) { + return freeze2({ + ...node, + explain: ExplainNode.create(format2, options?.toOperationNode()) + }); + }, + cloneWithTop(node, top) { + return freeze2({ + ...node, + top + }); + }, + cloneWithOutput(node, selections) { + return freeze2({ + ...node, + output: node.output ? OutputNode.cloneWithSelections(node.output, selections) : OutputNode.create(selections) + }); + }, + cloneWithOrderByItems(node, items) { + return freeze2({ + ...node, + orderBy: node.orderBy ? OrderByNode.cloneWithItems(node.orderBy, items) : OrderByNode.create(items) + }); + }, + cloneWithoutOrderBy(node) { + return freeze2({ + ...node, + orderBy: void 0 + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/select-query-node.js +var SelectQueryNode; +var init_select_query_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/select-query-node.js"() { + init_object_utils(); + init_from_node(); + init_group_by_node(); + init_having_node(); + init_query_node(); + SelectQueryNode = freeze2({ + is(node) { + return node.kind === "SelectQueryNode"; + }, + create(withNode) { + return freeze2({ + kind: "SelectQueryNode", + ...withNode && { with: withNode } + }); + }, + createFrom(fromItems, withNode) { + return freeze2({ + kind: "SelectQueryNode", + from: FromNode.create(fromItems), + ...withNode && { with: withNode } + }); + }, + cloneWithSelections(select2, selections) { + return freeze2({ + ...select2, + selections: select2.selections ? freeze2([...select2.selections, ...selections]) : freeze2(selections) + }); + }, + cloneWithDistinctOn(select2, expressions) { + return freeze2({ + ...select2, + distinctOn: select2.distinctOn ? freeze2([...select2.distinctOn, ...expressions]) : freeze2(expressions) + }); + }, + cloneWithFrontModifier(select2, modifier) { + return freeze2({ + ...select2, + frontModifiers: select2.frontModifiers ? freeze2([...select2.frontModifiers, modifier]) : freeze2([modifier]) + }); + }, + // TODO: remove in v0.29 + /** + * @deprecated Use `QueryNode.cloneWithoutOrderBy` instead. + */ + cloneWithOrderByItems: (node, items) => QueryNode.cloneWithOrderByItems(node, items), + cloneWithGroupByItems(selectNode, items) { + return freeze2({ + ...selectNode, + groupBy: selectNode.groupBy ? GroupByNode.cloneWithItems(selectNode.groupBy, items) : GroupByNode.create(items) + }); + }, + cloneWithLimit(selectNode, limit) { + return freeze2({ + ...selectNode, + limit + }); + }, + cloneWithOffset(selectNode, offset) { + return freeze2({ + ...selectNode, + offset + }); + }, + cloneWithFetch(selectNode, fetch2) { + return freeze2({ + ...selectNode, + fetch: fetch2 + }); + }, + cloneWithHaving(selectNode, operation2) { + return freeze2({ + ...selectNode, + having: selectNode.having ? HavingNode.cloneWithOperation(selectNode.having, "And", operation2) : HavingNode.create(operation2) + }); + }, + cloneWithSetOperations(selectNode, setOperations) { + return freeze2({ + ...selectNode, + setOperations: selectNode.setOperations ? freeze2([...selectNode.setOperations, ...setOperations]) : freeze2([...setOperations]) + }); + }, + cloneWithoutSelections(select2) { + return freeze2({ + ...select2, + selections: [] + }); + }, + cloneWithoutLimit(select2) { + return freeze2({ + ...select2, + limit: void 0 + }); + }, + cloneWithoutOffset(select2) { + return freeze2({ + ...select2, + offset: void 0 + }); + }, + // TODO: remove in v0.29 + /** + * @deprecated Use `QueryNode.cloneWithoutOrderBy` instead. + */ + cloneWithoutOrderBy: (node) => QueryNode.cloneWithoutOrderBy(node), + cloneWithoutGroupBy(select2) { + return freeze2({ + ...select2, + groupBy: void 0 + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/join-builder.js +var JoinBuilder; +var init_join_builder = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/join-builder.js"() { + init_join_node(); + init_raw_node(); + init_binary_operation_parser(); + init_object_utils(); + JoinBuilder = class _JoinBuilder { + #props; + constructor(props) { + this.#props = freeze2(props); + } + on(...args) { + return new _JoinBuilder({ + ...this.#props, + joinNode: JoinNode.cloneWithOn(this.#props.joinNode, parseValueBinaryOperationOrExpression(args)) + }); + } + /** + * Just like {@link WhereInterface.whereRef} but adds an item to the join's + * `on` clause instead. + * + * See {@link WhereInterface.whereRef} for documentation and examples. + */ + onRef(lhs, op2, rhs) { + return new _JoinBuilder({ + ...this.#props, + joinNode: JoinNode.cloneWithOn(this.#props.joinNode, parseReferentialBinaryOperation(lhs, op2, rhs)) + }); + } + /** + * Adds `on true`. + */ + onTrue() { + return new _JoinBuilder({ + ...this.#props, + joinNode: JoinNode.cloneWithOn(this.#props.joinNode, RawNode.createWithSql("true")) + }); + } + /** + * Simply calls the provided function passing `this` as the only argument. `$call` returns + * what the provided function returns. + */ + $call(func) { + return func(this); + } + toOperationNode() { + return this.#props.joinNode; + } + }; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/partition-by-item-node.js +var PartitionByItemNode; +var init_partition_by_item_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/partition-by-item-node.js"() { + init_object_utils(); + PartitionByItemNode = freeze2({ + is(node) { + return node.kind === "PartitionByItemNode"; + }, + create(partitionBy) { + return freeze2({ + kind: "PartitionByItemNode", + partitionBy + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/partition-by-parser.js +function parsePartitionBy(partitionBy) { + return parseReferenceExpressionOrList(partitionBy).map(PartitionByItemNode.create); +} +var init_partition_by_parser = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/partition-by-parser.js"() { + init_partition_by_item_node(); + init_reference_parser(); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/over-builder.js +var OverBuilder; +var init_over_builder = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/over-builder.js"() { + init_over_node(); + init_query_node(); + init_order_by_parser(); + init_partition_by_parser(); + init_object_utils(); + OverBuilder = class _OverBuilder { + #props; + constructor(props) { + this.#props = freeze2(props); + } + orderBy(...args) { + return new _OverBuilder({ + overNode: OverNode.cloneWithOrderByItems(this.#props.overNode, parseOrderBy(args)) + }); + } + clearOrderBy() { + return new _OverBuilder({ + overNode: QueryNode.cloneWithoutOrderBy(this.#props.overNode) + }); + } + partitionBy(partitionBy) { + return new _OverBuilder({ + overNode: OverNode.cloneWithPartitionByItems(this.#props.overNode, parsePartitionBy(partitionBy)) + }); + } + /** + * Simply calls the provided function passing `this` as the only argument. `$call` returns + * what the provided function returns. + */ + $call(func) { + return func(this); + } + toOperationNode() { + return this.#props.overNode; + } + }; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/selection-node.js +var SelectionNode; +var init_selection_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/selection-node.js"() { + init_object_utils(); + init_reference_node(); + init_select_all_node(); + SelectionNode = freeze2({ + is(node) { + return node.kind === "SelectionNode"; + }, + create(selection) { + return freeze2({ + kind: "SelectionNode", + selection + }); + }, + createSelectAll() { + return freeze2({ + kind: "SelectionNode", + selection: SelectAllNode.create() + }); + }, + createSelectAllFromTable(table) { + return freeze2({ + kind: "SelectionNode", + selection: ReferenceNode.createSelectAll(table) + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/select-parser.js +function parseSelectArg(selection) { + if (isFunction(selection)) { + return parseSelectArg(selection(expressionBuilder())); + } else if (isReadonlyArray(selection)) { + return selection.map((it) => parseSelectExpression(it)); + } else { + return [parseSelectExpression(selection)]; + } +} +function parseSelectExpression(selection) { + if (isString(selection)) { + return SelectionNode.create(parseAliasedStringReference(selection)); + } else if (isDynamicReferenceBuilder(selection)) { + return SelectionNode.create(selection.toOperationNode()); + } else { + return SelectionNode.create(parseAliasedExpression(selection)); + } +} +function parseSelectAll(table) { + if (!table) { + return [SelectionNode.createSelectAll()]; + } else if (Array.isArray(table)) { + return table.map(parseSelectAllArg); + } else { + return [parseSelectAllArg(table)]; + } +} +function parseSelectAllArg(table) { + if (isString(table)) { + return SelectionNode.createSelectAllFromTable(parseTable(table)); + } + throw new Error(`invalid value selectAll expression: ${JSON.stringify(table)}`); +} +var init_select_parser = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/select-parser.js"() { + init_object_utils(); + init_selection_node(); + init_reference_parser(); + init_dynamic_reference_builder(); + init_expression_parser(); + init_table_parser(); + init_expression_builder(); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/values-node.js +var ValuesNode; +var init_values_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/values-node.js"() { + init_object_utils(); + ValuesNode = freeze2({ + is(node) { + return node.kind === "ValuesNode"; + }, + create(values2) { + return freeze2({ + kind: "ValuesNode", + values: freeze2(values2) + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/default-insert-value-node.js +var DefaultInsertValueNode; +var init_default_insert_value_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/default-insert-value-node.js"() { + init_object_utils(); + DefaultInsertValueNode = freeze2({ + is(node) { + return node.kind === "DefaultInsertValueNode"; + }, + create() { + return freeze2({ + kind: "DefaultInsertValueNode" + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/insert-values-parser.js +function parseInsertExpression(arg) { + const objectOrList = isFunction(arg) ? arg(expressionBuilder()) : arg; + const list2 = isReadonlyArray(objectOrList) ? objectOrList : freeze2([objectOrList]); + return parseInsertColumnsAndValues(list2); +} +function parseInsertColumnsAndValues(rows) { + const columns = parseColumnNamesAndIndexes(rows); + return [ + freeze2([...columns.keys()].map(ColumnNode.create)), + ValuesNode.create(rows.map((row) => parseRowValues(row, columns))) + ]; +} +function parseColumnNamesAndIndexes(rows) { + const columns = /* @__PURE__ */ new Map(); + for (const row of rows) { + const cols = Object.keys(row); + for (const col of cols) { + if (!columns.has(col) && row[col] !== void 0) { + columns.set(col, columns.size); + } + } + } + return columns; +} +function parseRowValues(row, columns) { + const rowColumns = Object.keys(row); + const rowValues = Array.from({ + length: columns.size + }); + let hasUndefinedOrComplexColumns = false; + let indexedRowColumns = rowColumns.length; + for (const col of rowColumns) { + const columnIdx = columns.get(col); + if (isUndefined(columnIdx)) { + indexedRowColumns--; + continue; + } + const value = row[col]; + if (isUndefined(value) || isExpressionOrFactory(value)) { + hasUndefinedOrComplexColumns = true; + } + rowValues[columnIdx] = value; + } + const hasMissingColumns = indexedRowColumns < columns.size; + if (hasMissingColumns || hasUndefinedOrComplexColumns) { + const defaultValue = DefaultInsertValueNode.create(); + return ValueListNode.create(rowValues.map((it) => isUndefined(it) ? defaultValue : parseValueExpression(it))); + } + return PrimitiveValueListNode.create(rowValues); +} +var init_insert_values_parser = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/insert-values-parser.js"() { + init_column_node(); + init_primitive_value_list_node(); + init_value_list_node(); + init_object_utils(); + init_value_parser(); + init_values_node(); + init_expression_parser(); + init_default_insert_value_node(); + init_expression_builder(); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/column-update-node.js +var ColumnUpdateNode; +var init_column_update_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/column-update-node.js"() { + init_object_utils(); + ColumnUpdateNode = freeze2({ + is(node) { + return node.kind === "ColumnUpdateNode"; + }, + create(column, value) { + return freeze2({ + kind: "ColumnUpdateNode", + column, + value + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/update-set-parser.js +function parseUpdate(...args) { + if (args.length === 2) { + return [ + ColumnUpdateNode.create(parseReferenceExpression(args[0]), parseValueExpression(args[1])) + ]; + } + return parseUpdateObjectExpression(args[0]); +} +function parseUpdateObjectExpression(update) { + const updateObj = isFunction(update) ? update(expressionBuilder()) : update; + return Object.entries(updateObj).filter(([_, value]) => value !== void 0).map(([key, value]) => { + return ColumnUpdateNode.create(ColumnNode.create(key), parseValueExpression(value)); + }); +} +var init_update_set_parser = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/update-set-parser.js"() { + init_column_node(); + init_column_update_node(); + init_expression_builder(); + init_object_utils(); + init_value_parser(); + init_reference_parser(); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/on-duplicate-key-node.js +var OnDuplicateKeyNode; +var init_on_duplicate_key_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/on-duplicate-key-node.js"() { + init_object_utils(); + OnDuplicateKeyNode = freeze2({ + is(node) { + return node.kind === "OnDuplicateKeyNode"; + }, + create(updates) { + return freeze2({ + kind: "OnDuplicateKeyNode", + updates + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/insert-result.js +var InsertResult; +var init_insert_result = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/insert-result.js"() { + InsertResult = class { + /** + * The auto incrementing primary key of the inserted row. + * + * This property can be undefined when the query contains an `on conflict` + * clause that makes the query succeed even when nothing gets inserted. + * + * This property is always undefined on dialects like PostgreSQL that + * don't return the inserted id by default. On those dialects you need + * to use the {@link ReturningInterface.returning | returning} method. + */ + insertId; + /** + * Affected rows count. + */ + numInsertedOrUpdatedRows; + constructor(insertId, numInsertedOrUpdatedRows) { + this.insertId = insertId; + this.numInsertedOrUpdatedRows = numInsertedOrUpdatedRows; + } + }; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/no-result-error.js +function isNoResultErrorConstructor(fn) { + return Object.prototype.hasOwnProperty.call(fn, "prototype"); +} +var NoResultError; +var init_no_result_error = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/no-result-error.js"() { + NoResultError = class extends Error { + /** + * The operation node tree of the query that was executed. + */ + node; + constructor(node) { + super("no result"); + this.node = node; + } + }; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/on-conflict-node.js +var OnConflictNode; +var init_on_conflict_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/on-conflict-node.js"() { + init_object_utils(); + init_where_node(); + OnConflictNode = freeze2({ + is(node) { + return node.kind === "OnConflictNode"; + }, + create() { + return freeze2({ + kind: "OnConflictNode" + }); + }, + cloneWith(node, props) { + return freeze2({ + ...node, + ...props + }); + }, + cloneWithIndexWhere(node, operation2) { + return freeze2({ + ...node, + indexWhere: node.indexWhere ? WhereNode.cloneWithOperation(node.indexWhere, "And", operation2) : WhereNode.create(operation2) + }); + }, + cloneWithIndexOrWhere(node, operation2) { + return freeze2({ + ...node, + indexWhere: node.indexWhere ? WhereNode.cloneWithOperation(node.indexWhere, "Or", operation2) : WhereNode.create(operation2) + }); + }, + cloneWithUpdateWhere(node, operation2) { + return freeze2({ + ...node, + updateWhere: node.updateWhere ? WhereNode.cloneWithOperation(node.updateWhere, "And", operation2) : WhereNode.create(operation2) + }); + }, + cloneWithUpdateOrWhere(node, operation2) { + return freeze2({ + ...node, + updateWhere: node.updateWhere ? WhereNode.cloneWithOperation(node.updateWhere, "Or", operation2) : WhereNode.create(operation2) + }); + }, + cloneWithoutIndexWhere(node) { + return freeze2({ + ...node, + indexWhere: void 0 + }); + }, + cloneWithoutUpdateWhere(node) { + return freeze2({ + ...node, + updateWhere: void 0 + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/on-conflict-builder.js +var OnConflictBuilder, OnConflictDoNothingBuilder, OnConflictUpdateBuilder; +var init_on_conflict_builder = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/on-conflict-builder.js"() { + init_column_node(); + init_identifier_node(); + init_on_conflict_node(); + init_binary_operation_parser(); + init_update_set_parser(); + init_object_utils(); + OnConflictBuilder = class _OnConflictBuilder { + #props; + constructor(props) { + this.#props = freeze2(props); + } + /** + * Specify a single column as the conflict target. + * + * Also see the {@link columns}, {@link constraint} and {@link expression} + * methods for alternative ways to specify the conflict target. + */ + column(column) { + const columnNode = ColumnNode.create(column); + return new _OnConflictBuilder({ + ...this.#props, + onConflictNode: OnConflictNode.cloneWith(this.#props.onConflictNode, { + columns: this.#props.onConflictNode.columns ? freeze2([...this.#props.onConflictNode.columns, columnNode]) : freeze2([columnNode]) + }) + }); + } + /** + * Specify a list of columns as the conflict target. + * + * Also see the {@link column}, {@link constraint} and {@link expression} + * methods for alternative ways to specify the conflict target. + */ + columns(columns) { + const columnNodes = columns.map(ColumnNode.create); + return new _OnConflictBuilder({ + ...this.#props, + onConflictNode: OnConflictNode.cloneWith(this.#props.onConflictNode, { + columns: this.#props.onConflictNode.columns ? freeze2([...this.#props.onConflictNode.columns, ...columnNodes]) : freeze2(columnNodes) + }) + }); + } + /** + * Specify a specific constraint by name as the conflict target. + * + * Also see the {@link column}, {@link columns} and {@link expression} + * methods for alternative ways to specify the conflict target. + */ + constraint(constraintName) { + return new _OnConflictBuilder({ + ...this.#props, + onConflictNode: OnConflictNode.cloneWith(this.#props.onConflictNode, { + constraint: IdentifierNode.create(constraintName) + }) + }); + } + /** + * Specify an expression as the conflict target. + * + * This can be used if the unique index is an expression index. + * + * Also see the {@link column}, {@link columns} and {@link constraint} + * methods for alternative ways to specify the conflict target. + */ + expression(expression) { + return new _OnConflictBuilder({ + ...this.#props, + onConflictNode: OnConflictNode.cloneWith(this.#props.onConflictNode, { + indexExpression: expression.toOperationNode() + }) + }); + } + where(...args) { + return new _OnConflictBuilder({ + ...this.#props, + onConflictNode: OnConflictNode.cloneWithIndexWhere(this.#props.onConflictNode, parseValueBinaryOperationOrExpression(args)) + }); + } + whereRef(lhs, op2, rhs) { + return new _OnConflictBuilder({ + ...this.#props, + onConflictNode: OnConflictNode.cloneWithIndexWhere(this.#props.onConflictNode, parseReferentialBinaryOperation(lhs, op2, rhs)) + }); + } + clearWhere() { + return new _OnConflictBuilder({ + ...this.#props, + onConflictNode: OnConflictNode.cloneWithoutIndexWhere(this.#props.onConflictNode) + }); + } + /** + * Adds the "do nothing" conflict action. + * + * ### Examples + * + * ```ts + * const id = 1 + * const first_name = 'John' + * + * await db + * .insertInto('person') + * .values({ first_name, id }) + * .onConflict((oc) => oc + * .column('id') + * .doNothing() + * ) + * .execute() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * insert into "person" ("first_name", "id") + * values ($1, $2) + * on conflict ("id") do nothing + * ``` + */ + doNothing() { + return new OnConflictDoNothingBuilder({ + ...this.#props, + onConflictNode: OnConflictNode.cloneWith(this.#props.onConflictNode, { + doNothing: true + }) + }); + } + /** + * Adds the "do update set" conflict action. + * + * ### Examples + * + * ```ts + * const id = 1 + * const first_name = 'John' + * + * await db + * .insertInto('person') + * .values({ first_name, id }) + * .onConflict((oc) => oc + * .column('id') + * .doUpdateSet({ first_name }) + * ) + * .execute() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * insert into "person" ("first_name", "id") + * values ($1, $2) + * on conflict ("id") + * do update set "first_name" = $3 + * ``` + * + * In the next example we use the `ref` method to reference + * columns of the virtual table `excluded` in a type-safe way + * to create an upsert operation: + * + * ```ts + * import type { NewPerson } from 'type-editor' // imaginary module + * + * async function upsertPerson(person: NewPerson): Promise { + * await db.insertInto('person') + * .values(person) + * .onConflict((oc) => oc + * .column('id') + * .doUpdateSet((eb) => ({ + * first_name: eb.ref('excluded.first_name'), + * last_name: eb.ref('excluded.last_name') + * }) + * ) + * ) + * .execute() + * } + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * insert into "person" ("first_name", "last_name") + * values ($1, $2) + * on conflict ("id") + * do update set + * "first_name" = excluded."first_name", + * "last_name" = excluded."last_name" + * ``` + */ + doUpdateSet(update) { + return new OnConflictUpdateBuilder({ + ...this.#props, + onConflictNode: OnConflictNode.cloneWith(this.#props.onConflictNode, { + updates: parseUpdateObjectExpression(update) + }) + }); + } + /** + * Simply calls the provided function passing `this` as the only argument. `$call` returns + * what the provided function returns. + */ + $call(func) { + return func(this); + } + }; + OnConflictDoNothingBuilder = class { + #props; + constructor(props) { + this.#props = freeze2(props); + } + toOperationNode() { + return this.#props.onConflictNode; + } + }; + OnConflictUpdateBuilder = class _OnConflictUpdateBuilder { + #props; + constructor(props) { + this.#props = freeze2(props); + } + where(...args) { + return new _OnConflictUpdateBuilder({ + ...this.#props, + onConflictNode: OnConflictNode.cloneWithUpdateWhere(this.#props.onConflictNode, parseValueBinaryOperationOrExpression(args)) + }); + } + /** + * Specify a where condition for the update operation. + * + * See {@link WhereInterface.whereRef} for more info. + */ + whereRef(lhs, op2, rhs) { + return new _OnConflictUpdateBuilder({ + ...this.#props, + onConflictNode: OnConflictNode.cloneWithUpdateWhere(this.#props.onConflictNode, parseReferentialBinaryOperation(lhs, op2, rhs)) + }); + } + clearWhere() { + return new _OnConflictUpdateBuilder({ + ...this.#props, + onConflictNode: OnConflictNode.cloneWithoutUpdateWhere(this.#props.onConflictNode) + }); + } + /** + * Simply calls the provided function passing `this` as the only argument. `$call` returns + * what the provided function returns. + */ + $call(func) { + return func(this); + } + toOperationNode() { + return this.#props.onConflictNode; + } + }; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/top-node.js +var TopNode; +var init_top_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/top-node.js"() { + init_object_utils(); + TopNode = freeze2({ + is(node) { + return node.kind === "TopNode"; + }, + create(expression, modifiers) { + return freeze2({ + kind: "TopNode", + expression, + modifiers + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/top-parser.js +function parseTop(expression, modifiers) { + if (!isNumber(expression) && !isBigInt(expression)) { + throw new Error(`Invalid top expression: ${expression}`); + } + if (!isUndefined(modifiers) && !isTopModifiers(modifiers)) { + throw new Error(`Invalid top modifiers: ${modifiers}`); + } + return TopNode.create(expression, modifiers); +} +function isTopModifiers(modifiers) { + return modifiers === "percent" || modifiers === "with ties" || modifiers === "percent with ties"; +} +var init_top_parser = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/top-parser.js"() { + init_top_node(); + init_object_utils(); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/or-action-node.js +var OrActionNode; +var init_or_action_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/or-action-node.js"() { + init_object_utils(); + OrActionNode = freeze2({ + is(node) { + return node.kind === "OrActionNode"; + }, + create(action) { + return freeze2({ + kind: "OrActionNode", + action + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/insert-query-builder.js +var InsertQueryBuilder; +var init_insert_query_builder = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/insert-query-builder.js"() { + init_select_parser(); + init_insert_values_parser(); + init_insert_query_node(); + init_query_node(); + init_update_set_parser(); + init_object_utils(); + init_on_duplicate_key_node(); + init_insert_result(); + init_no_result_error(); + init_expression_parser(); + init_column_node(); + init_on_conflict_builder(); + init_on_conflict_node(); + init_top_parser(); + init_or_action_node(); + InsertQueryBuilder = class _InsertQueryBuilder { + #props; + constructor(props) { + this.#props = freeze2(props); + } + /** + * Sets the values to insert for an {@link Kysely.insertInto | insert} query. + * + * This method takes an object whose keys are column names and values are + * values to insert. In addition to the column's type, the values can be + * raw {@link sql} snippets or select queries. + * + * You must provide all fields you haven't explicitly marked as nullable + * or optional using {@link Generated} or {@link ColumnType}. + * + * The return value of an `insert` query is an instance of {@link InsertResult}. The + * {@link InsertResult.insertId | insertId} field holds the auto incremented primary + * key if the database returned one. + * + * On PostgreSQL and some other dialects, you need to call `returning` to get + * something out of the query. + * + * Also see the {@link expression} method for inserting the result of a select + * query or any other expression. + * + * ### Examples + * + * + * + * Insert a single row: + * + * ```ts + * const result = await db + * .insertInto('person') + * .values({ + * first_name: 'Jennifer', + * last_name: 'Aniston', + * age: 40 + * }) + * .executeTakeFirst() + * + * // `insertId` is only available on dialects that + * // automatically return the id of the inserted row + * // such as MySQL and SQLite. On PostgreSQL, for example, + * // you need to add a `returning` clause to the query to + * // get anything out. See the "returning data" example. + * console.log(result.insertId) + * ``` + * + * The generated SQL (MySQL): + * + * ```sql + * insert into `person` (`first_name`, `last_name`, `age`) values (?, ?, ?) + * ``` + * + * + * + * On dialects that support it (for example PostgreSQL) you can insert multiple + * rows by providing an array. Note that the return value is once again very + * dialect-specific. Some databases may only return the id of the *last* inserted + * row and some return nothing at all unless you call `returning`. + * + * ```ts + * await db + * .insertInto('person') + * .values([{ + * first_name: 'Jennifer', + * last_name: 'Aniston', + * age: 40, + * }, { + * first_name: 'Arnold', + * last_name: 'Schwarzenegger', + * age: 70, + * }]) + * .execute() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * insert into "person" ("first_name", "last_name", "age") values (($1, $2, $3), ($4, $5, $6)) + * ``` + * + * + * + * On supported dialects like PostgreSQL you need to chain `returning` to the query to get + * the inserted row's columns (or any other expression) as the return value. `returning` + * works just like `select`. Refer to `select` method's examples and documentation for + * more info. + * + * ```ts + * const result = await db + * .insertInto('person') + * .values({ + * first_name: 'Jennifer', + * last_name: 'Aniston', + * age: 40, + * }) + * .returning(['id', 'first_name as name']) + * .executeTakeFirstOrThrow() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * insert into "person" ("first_name", "last_name", "age") values ($1, $2, $3) returning "id", "first_name" as "name" + * ``` + * + * + * + * In addition to primitives, the values can also be arbitrary expressions. + * You can build the expressions by using a callback and calling the methods + * on the expression builder passed to it: + * + * ```ts + * import { sql } from 'kysely' + * + * const ani = "Ani" + * const ston = "ston" + * + * const result = await db + * .insertInto('person') + * .values(({ ref, selectFrom, fn }) => ({ + * first_name: 'Jennifer', + * last_name: sql`concat(${ani}, ${ston})`, + * middle_name: ref('first_name'), + * age: selectFrom('person') + * .select(fn.avg('age').as('avg_age')), + * })) + * .executeTakeFirst() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * insert into "person" ( + * "first_name", + * "last_name", + * "middle_name", + * "age" + * ) + * values ( + * $1, + * concat($2, $3), + * "first_name", + * (select avg("age") as "avg_age" from "person") + * ) + * ``` + * + * You can also use the callback version of subqueries or raw expressions: + * + * ```ts + * await db.with('jennifer', (db) => db + * .selectFrom('person') + * .where('first_name', '=', 'Jennifer') + * .select(['id', 'first_name', 'gender']) + * .limit(1) + * ).insertInto('pet').values((eb) => ({ + * owner_id: eb.selectFrom('jennifer').select('id'), + * name: eb.selectFrom('jennifer').select('first_name'), + * species: 'cat', + * })) + * .execute() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * with "jennifer" as ( + * select "id", "first_name", "gender" + * from "person" + * where "first_name" = $1 + * limit $2 + * ) + * insert into "pet" ("owner_id", "name", "species") + * values ( + * (select "id" from "jennifer"), + * (select "first_name" from "jennifer"), + * $3 + * ) + * ``` + */ + values(insert) { + const [columns, values2] = parseInsertExpression(insert); + return new _InsertQueryBuilder({ + ...this.#props, + queryNode: InsertQueryNode.cloneWith(this.#props.queryNode, { + columns, + values: values2 + }) + }); + } + /** + * Sets the columns to insert. + * + * The {@link values} method sets both the columns and the values and this method + * is not needed. But if you are using the {@link expression} method, you can use + * this method to set the columns to insert. + * + * ### Examples + * + * ```ts + * await db.insertInto('person') + * .columns(['first_name']) + * .expression((eb) => eb.selectFrom('pet').select('pet.name')) + * .execute() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * insert into "person" ("first_name") + * select "pet"."name" from "pet" + * ``` + */ + columns(columns) { + return new _InsertQueryBuilder({ + ...this.#props, + queryNode: InsertQueryNode.cloneWith(this.#props.queryNode, { + columns: freeze2(columns.map(ColumnNode.create)) + }) + }); + } + /** + * Insert an arbitrary expression. For example the result of a select query. + * + * ### Examples + * + * + * + * You can create an `INSERT INTO SELECT FROM` query using the `expression` method. + * This API doesn't follow our WYSIWYG principles and might be a bit difficult to + * remember. The reasons for this design stem from implementation difficulties. + * + * ```ts + * const result = await db.insertInto('person') + * .columns(['first_name', 'last_name', 'age']) + * .expression((eb) => eb + * .selectFrom('pet') + * .select((eb) => [ + * 'pet.name', + * eb.val('Petson').as('last_name'), + * eb.lit(7).as('age'), + * ]) + * ) + * .execute() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * insert into "person" ("first_name", "last_name", "age") + * select "pet"."name", $1 as "last_name", 7 as "age from "pet" + * ``` + */ + expression(expression) { + return new _InsertQueryBuilder({ + ...this.#props, + queryNode: InsertQueryNode.cloneWith(this.#props.queryNode, { + values: parseExpression(expression) + }) + }); + } + /** + * Creates an `insert into "person" default values` query. + * + * ### Examples + * + * ```ts + * await db.insertInto('person') + * .defaultValues() + * .execute() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * insert into "person" default values + * ``` + */ + defaultValues() { + return new _InsertQueryBuilder({ + ...this.#props, + queryNode: InsertQueryNode.cloneWith(this.#props.queryNode, { + defaultValues: true + }) + }); + } + /** + * This can be used to add any additional SQL to the end of the query. + * + * ### Examples + * + * ```ts + * import { sql } from 'kysely' + * + * await db.insertInto('person') + * .values({ + * first_name: 'John', + * last_name: 'Doe', + * gender: 'male', + * }) + * .modifyEnd(sql`-- This is a comment`) + * .execute() + * ``` + * + * The generated SQL (MySQL): + * + * ```sql + * insert into `person` ("first_name", "last_name", "gender") + * values (?, ?, ?) -- This is a comment + * ``` + */ + modifyEnd(modifier) { + return new _InsertQueryBuilder({ + ...this.#props, + queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, modifier.toOperationNode()) + }); + } + /** + * Changes an `insert into` query to an `insert ignore into` query. + * + * This is only supported by some dialects like MySQL. + * + * To avoid a footgun, when invoked with the SQLite dialect, this method will + * be handled like {@link orIgnore}. See also, {@link orAbort}, {@link orFail}, + * {@link orReplace}, and {@link orRollback}. + * + * If you use the ignore modifier, ignorable errors that occur while executing the + * insert statement are ignored. For example, without ignore, a row that duplicates + * an existing unique index or primary key value in the table causes a duplicate-key + * error and the statement is aborted. With ignore, the row is discarded and no error + * occurs. + * + * ### Examples + * + * ```ts + * await db.insertInto('person') + * .ignore() + * .values({ + * first_name: 'John', + * last_name: 'Doe', + * gender: 'female', + * }) + * .execute() + * ``` + * + * The generated SQL (MySQL): + * + * ```sql + * insert ignore into `person` (`first_name`, `last_name`, `gender`) values (?, ?, ?) + * ``` + * + * The generated SQL (SQLite): + * + * ```sql + * insert or ignore into "person" ("first_name", "last_name", "gender") values (?, ?, ?) + * ``` + */ + ignore() { + return new _InsertQueryBuilder({ + ...this.#props, + queryNode: InsertQueryNode.cloneWith(this.#props.queryNode, { + orAction: OrActionNode.create("ignore") + }) + }); + } + /** + * Changes an `insert into` query to an `insert or ignore into` query. + * + * This is only supported by some dialects like SQLite. + * + * To avoid a footgun, when invoked with the MySQL dialect, this method will + * be handled like {@link ignore}. + * + * See also, {@link orAbort}, {@link orFail}, {@link orReplace}, and {@link orRollback}. + * + * ### Examples + * + * ```ts + * await db.insertInto('person') + * .orIgnore() + * .values({ + * first_name: 'John', + * last_name: 'Doe', + * gender: 'female', + * }) + * .execute() + * ``` + * + * The generated SQL (SQLite): + * + * ```sql + * insert or ignore into "person" ("first_name", "last_name", "gender") values (?, ?, ?) + * ``` + * + * The generated SQL (MySQL): + * + * ```sql + * insert ignore into `person` (`first_name`, `last_name`, `gender`) values (?, ?, ?) + * ``` + */ + orIgnore() { + return new _InsertQueryBuilder({ + ...this.#props, + queryNode: InsertQueryNode.cloneWith(this.#props.queryNode, { + orAction: OrActionNode.create("ignore") + }) + }); + } + /** + * Changes an `insert into` query to an `insert or abort into` query. + * + * This is only supported by some dialects like SQLite. + * + * See also, {@link orIgnore}, {@link orFail}, {@link orReplace}, and {@link orRollback}. + * + * ### Examples + * + * ```ts + * await db.insertInto('person') + * .orAbort() + * .values({ + * first_name: 'John', + * last_name: 'Doe', + * gender: 'female', + * }) + * .execute() + * ``` + * + * The generated SQL (SQLite): + * + * ```sql + * insert or abort into "person" ("first_name", "last_name", "gender") values (?, ?, ?) + * ``` + */ + orAbort() { + return new _InsertQueryBuilder({ + ...this.#props, + queryNode: InsertQueryNode.cloneWith(this.#props.queryNode, { + orAction: OrActionNode.create("abort") + }) + }); + } + /** + * Changes an `insert into` query to an `insert or fail into` query. + * + * This is only supported by some dialects like SQLite. + * + * See also, {@link orIgnore}, {@link orAbort}, {@link orReplace}, and {@link orRollback}. + * + * ### Examples + * + * ```ts + * await db.insertInto('person') + * .orFail() + * .values({ + * first_name: 'John', + * last_name: 'Doe', + * gender: 'female', + * }) + * .execute() + * ``` + * + * The generated SQL (SQLite): + * + * ```sql + * insert or fail into "person" ("first_name", "last_name", "gender") values (?, ?, ?) + * ``` + */ + orFail() { + return new _InsertQueryBuilder({ + ...this.#props, + queryNode: InsertQueryNode.cloneWith(this.#props.queryNode, { + orAction: OrActionNode.create("fail") + }) + }); + } + /** + * Changes an `insert into` query to an `insert or replace into` query. + * + * This is only supported by some dialects like SQLite. + * + * You can also use {@link Kysely.replaceInto} to achieve the same result. + * + * See also, {@link orIgnore}, {@link orAbort}, {@link orFail}, and {@link orRollback}. + * + * ### Examples + * + * ```ts + * await db.insertInto('person') + * .orReplace() + * .values({ + * first_name: 'John', + * last_name: 'Doe', + * gender: 'female', + * }) + * .execute() + * ``` + * + * The generated SQL (SQLite): + * + * ```sql + * insert or replace into "person" ("first_name", "last_name", "gender") values (?, ?, ?) + * ``` + */ + orReplace() { + return new _InsertQueryBuilder({ + ...this.#props, + queryNode: InsertQueryNode.cloneWith(this.#props.queryNode, { + orAction: OrActionNode.create("replace") + }) + }); + } + /** + * Changes an `insert into` query to an `insert or rollback into` query. + * + * This is only supported by some dialects like SQLite. + * + * See also, {@link orIgnore}, {@link orAbort}, {@link orFail}, and {@link orReplace}. + * + * ### Examples + * + * ```ts + * await db.insertInto('person') + * .orRollback() + * .values({ + * first_name: 'John', + * last_name: 'Doe', + * gender: 'female', + * }) + * .execute() + * ``` + * + * The generated SQL (SQLite): + * + * ```sql + * insert or rollback into "person" ("first_name", "last_name", "gender") values (?, ?, ?) + * ``` + */ + orRollback() { + return new _InsertQueryBuilder({ + ...this.#props, + queryNode: InsertQueryNode.cloneWith(this.#props.queryNode, { + orAction: OrActionNode.create("rollback") + }) + }); + } + /** + * Changes an `insert into` query to an `insert top into` query. + * + * `top` clause is only supported by some dialects like MS SQL Server. + * + * ### Examples + * + * Insert the first 5 rows: + * + * ```ts + * import { sql } from 'kysely' + * + * await db.insertInto('person') + * .top(5) + * .columns(['first_name', 'gender']) + * .expression( + * (eb) => eb.selectFrom('pet').select(['name', sql.lit('other').as('gender')]) + * ) + * .execute() + * ``` + * + * The generated SQL (MS SQL Server): + * + * ```sql + * insert top(5) into "person" ("first_name", "gender") select "name", 'other' as "gender" from "pet" + * ``` + * + * Insert the first 50 percent of rows: + * + * ```ts + * import { sql } from 'kysely' + * + * await db.insertInto('person') + * .top(50, 'percent') + * .columns(['first_name', 'gender']) + * .expression( + * (eb) => eb.selectFrom('pet').select(['name', sql.lit('other').as('gender')]) + * ) + * .execute() + * ``` + * + * The generated SQL (MS SQL Server): + * + * ```sql + * insert top(50) percent into "person" ("first_name", "gender") select "name", 'other' as "gender" from "pet" + * ``` + */ + top(expression, modifiers) { + return new _InsertQueryBuilder({ + ...this.#props, + queryNode: QueryNode.cloneWithTop(this.#props.queryNode, parseTop(expression, modifiers)) + }); + } + /** + * Adds an `on conflict` clause to the query. + * + * `on conflict` is only supported by some dialects like PostgreSQL and SQLite. On MySQL + * you can use {@link ignore} and {@link onDuplicateKeyUpdate} to achieve similar results. + * + * ### Examples + * + * ```ts + * await db + * .insertInto('pet') + * .values({ + * name: 'Catto', + * species: 'cat', + * owner_id: 3, + * }) + * .onConflict((oc) => oc + * .column('name') + * .doUpdateSet({ species: 'hamster' }) + * ) + * .execute() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * insert into "pet" ("name", "species", "owner_id") + * values ($1, $2, $3) + * on conflict ("name") + * do update set "species" = $4 + * ``` + * + * You can provide the name of the constraint instead of a column name: + * + * ```ts + * await db + * .insertInto('pet') + * .values({ + * name: 'Catto', + * species: 'cat', + * owner_id: 3, + * }) + * .onConflict((oc) => oc + * .constraint('pet_name_key') + * .doUpdateSet({ species: 'hamster' }) + * ) + * .execute() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * insert into "pet" ("name", "species", "owner_id") + * values ($1, $2, $3) + * on conflict on constraint "pet_name_key" + * do update set "species" = $4 + * ``` + * + * You can also specify an expression as the conflict target in case + * the unique index is an expression index: + * + * ```ts + * import { sql } from 'kysely' + * + * await db + * .insertInto('pet') + * .values({ + * name: 'Catto', + * species: 'cat', + * owner_id: 3, + * }) + * .onConflict((oc) => oc + * .expression(sql`lower(name)`) + * .doUpdateSet({ species: 'hamster' }) + * ) + * .execute() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * insert into "pet" ("name", "species", "owner_id") + * values ($1, $2, $3) + * on conflict (lower(name)) + * do update set "species" = $4 + * ``` + * + * You can add a filter for the update statement like this: + * + * ```ts + * await db + * .insertInto('pet') + * .values({ + * name: 'Catto', + * species: 'cat', + * owner_id: 3, + * }) + * .onConflict((oc) => oc + * .column('name') + * .doUpdateSet({ species: 'hamster' }) + * .where('excluded.name', '!=', 'Catto') + * ) + * .execute() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * insert into "pet" ("name", "species", "owner_id") + * values ($1, $2, $3) + * on conflict ("name") + * do update set "species" = $4 + * where "excluded"."name" != $5 + * ``` + * + * You can create an `on conflict do nothing` clauses like this: + * + * ```ts + * await db + * .insertInto('pet') + * .values({ + * name: 'Catto', + * species: 'cat', + * owner_id: 3, + * }) + * .onConflict((oc) => oc + * .column('name') + * .doNothing() + * ) + * .execute() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * insert into "pet" ("name", "species", "owner_id") + * values ($1, $2, $3) + * on conflict ("name") do nothing + * ``` + * + * You can refer to the columns of the virtual `excluded` table + * in a type-safe way using a callback and the `ref` method of + * `ExpressionBuilder`: + * + * ```ts + * await db.insertInto('person') + * .values({ + * id: 1, + * first_name: 'John', + * last_name: 'Doe', + * gender: 'male', + * }) + * .onConflict(oc => oc + * .column('id') + * .doUpdateSet({ + * first_name: (eb) => eb.ref('excluded.first_name'), + * last_name: (eb) => eb.ref('excluded.last_name') + * }) + * ) + * .execute() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * insert into "person" ("id", "first_name", "last_name", "gender") + * values ($1, $2, $3, $4) + * on conflict ("id") + * do update set + * "first_name" = "excluded"."first_name", + * "last_name" = "excluded"."last_name" + * ``` + */ + onConflict(callback) { + return new _InsertQueryBuilder({ + ...this.#props, + queryNode: InsertQueryNode.cloneWith(this.#props.queryNode, { + onConflict: callback(new OnConflictBuilder({ + onConflictNode: OnConflictNode.create() + })).toOperationNode() + }) + }); + } + /** + * Adds `on duplicate key update` to the query. + * + * If you specify `on duplicate key update`, and a row is inserted that would cause + * a duplicate value in a unique index or primary key, an update of the old row occurs. + * + * This is only implemented by some dialects like MySQL. On most dialects you should + * use {@link onConflict} instead. + * + * ### Examples + * + * ```ts + * await db + * .insertInto('person') + * .values({ + * id: 1, + * first_name: 'John', + * last_name: 'Doe', + * gender: 'male', + * }) + * .onDuplicateKeyUpdate({ updated_at: new Date().toISOString() }) + * .execute() + * ``` + * + * The generated SQL (MySQL): + * + * ```sql + * insert into `person` (`id`, `first_name`, `last_name`, `gender`) + * values (?, ?, ?, ?) + * on duplicate key update `updated_at` = ? + * ``` + */ + onDuplicateKeyUpdate(update) { + return new _InsertQueryBuilder({ + ...this.#props, + queryNode: InsertQueryNode.cloneWith(this.#props.queryNode, { + onDuplicateKey: OnDuplicateKeyNode.create(parseUpdateObjectExpression(update)) + }) + }); + } + returning(selection) { + return new _InsertQueryBuilder({ + ...this.#props, + queryNode: QueryNode.cloneWithReturning(this.#props.queryNode, parseSelectArg(selection)) + }); + } + returningAll() { + return new _InsertQueryBuilder({ + ...this.#props, + queryNode: QueryNode.cloneWithReturning(this.#props.queryNode, parseSelectAll()) + }); + } + output(args) { + return new _InsertQueryBuilder({ + ...this.#props, + queryNode: QueryNode.cloneWithOutput(this.#props.queryNode, parseSelectArg(args)) + }); + } + outputAll(table) { + return new _InsertQueryBuilder({ + ...this.#props, + queryNode: QueryNode.cloneWithOutput(this.#props.queryNode, parseSelectAll(table)) + }); + } + /** + * Clears all `returning` clauses from the query. + * + * ### Examples + * + * ```ts + * await db.insertInto('person') + * .values({ first_name: 'James', last_name: 'Smith', gender: 'male' }) + * .returning(['first_name']) + * .clearReturning() + * .execute() + * ``` + * + * The generated SQL(PostgreSQL): + * + * ```sql + * insert into "person" ("first_name", "last_name", "gender") values ($1, $2, $3) + * ``` + */ + clearReturning() { + return new _InsertQueryBuilder({ + ...this.#props, + queryNode: QueryNode.cloneWithoutReturning(this.#props.queryNode) + }); + } + /** + * Simply calls the provided function passing `this` as the only argument. `$call` returns + * what the provided function returns. + * + * If you want to conditionally call a method on `this`, see + * the {@link $if} method. + * + * ### Examples + * + * The next example uses a helper function `log` to log a query: + * + * ```ts + * import type { Compilable } from 'kysely' + * + * function log(qb: T): T { + * console.log(qb.compile()) + * return qb + * } + * + * await db.insertInto('person') + * .values({ first_name: 'John', last_name: 'Doe', gender: 'male' }) + * .$call(log) + * .execute() + * ``` + */ + $call(func) { + return func(this); + } + /** + * Call `func(this)` if `condition` is true. + * + * This method is especially handy with optional selects. Any `returning` or `returningAll` + * method calls add columns as optional fields to the output type when called inside + * the `func` callback. This is because we can't know if those selections were actually + * made before running the code. + * + * You can also call any other methods inside the callback. + * + * ### Examples + * + * ```ts + * import type { NewPerson } from 'type-editor' // imaginary module + * + * async function insertPerson(values: NewPerson, returnLastName: boolean) { + * return await db + * .insertInto('person') + * .values(values) + * .returning(['id', 'first_name']) + * .$if(returnLastName, (qb) => qb.returning('last_name')) + * .executeTakeFirstOrThrow() + * } + * ``` + * + * Any selections added inside the `if` callback will be added as optional fields to the + * output type since we can't know if the selections were actually made before running + * the code. In the example above the return type of the `insertPerson` function is: + * + * ```ts + * Promise<{ + * id: number + * first_name: string + * last_name?: string + * }> + * ``` + */ + $if(condition, func) { + if (condition) { + return func(this); + } + return new _InsertQueryBuilder({ + ...this.#props + }); + } + /** + * Change the output type of the query. + * + * This method call doesn't change the SQL in any way. This methods simply + * returns a copy of this `InsertQueryBuilder` with a new output type. + */ + $castTo() { + return new _InsertQueryBuilder(this.#props); + } + /** + * Narrows (parts of) the output type of the query. + * + * Kysely tries to be as type-safe as possible, but in some cases we have to make + * compromises for better maintainability and compilation performance. At present, + * Kysely doesn't narrow the output type of the query based on {@link values} input + * when using {@link returning} or {@link returningAll}. + * + * This utility method is very useful for these situations, as it removes unncessary + * runtime assertion/guard code. Its input type is limited to the output type + * of the query, so you can't add a column that doesn't exist, or change a column's + * type to something that doesn't exist in its union type. + * + * ### Examples + * + * Turn this code: + * + * ```ts + * import type { Person } from 'type-editor' // imaginary module + * + * const person = await db.insertInto('person') + * .values({ + * first_name: 'John', + * last_name: 'Doe', + * gender: 'male', + * nullable_column: 'hell yeah!' + * }) + * .returningAll() + * .executeTakeFirstOrThrow() + * + * if (isWithNoNullValue(person)) { + * functionThatExpectsPersonWithNonNullValue(person) + * } + * + * function isWithNoNullValue(person: Person): person is Person & { nullable_column: string } { + * return person.nullable_column != null + * } + * ``` + * + * Into this: + * + * ```ts + * import type { NotNull } from 'kysely' + * + * const person = await db.insertInto('person') + * .values({ + * first_name: 'John', + * last_name: 'Doe', + * gender: 'male', + * nullable_column: 'hell yeah!' + * }) + * .returningAll() + * .$narrowType<{ nullable_column: NotNull }>() + * .executeTakeFirstOrThrow() + * + * functionThatExpectsPersonWithNonNullValue(person) + * ``` + */ + $narrowType() { + return new _InsertQueryBuilder(this.#props); + } + /** + * Asserts that query's output row type equals the given type `T`. + * + * This method can be used to simplify excessively complex types to make TypeScript happy + * and much faster. + * + * Kysely uses complex type magic to achieve its type safety. This complexity is sometimes too much + * for TypeScript and you get errors like this: + * + * ``` + * error TS2589: Type instantiation is excessively deep and possibly infinite. + * ``` + * + * In these case you can often use this method to help TypeScript a little bit. When you use this + * method to assert the output type of a query, Kysely can drop the complex output type that + * consists of multiple nested helper types and replace it with the simple asserted type. + * + * Using this method doesn't reduce type safety at all. You have to pass in a type that is + * structurally equal to the current type. + * + * ### Examples + * + * ```ts + * import type { NewPerson, NewPet, Species } from 'type-editor' // imaginary module + * + * async function insertPersonAndPet(person: NewPerson, pet: Omit) { + * return await db + * .with('new_person', (qb) => qb + * .insertInto('person') + * .values(person) + * .returning('id') + * .$assertType<{ id: number }>() + * ) + * .with('new_pet', (qb) => qb + * .insertInto('pet') + * .values((eb) => ({ + * owner_id: eb.selectFrom('new_person').select('id'), + * ...pet + * })) + * .returning(['name as pet_name', 'species']) + * .$assertType<{ pet_name: string, species: Species }>() + * ) + * .selectFrom(['new_person', 'new_pet']) + * .selectAll() + * .executeTakeFirstOrThrow() + * } + * ``` + */ + $assertType() { + return new _InsertQueryBuilder(this.#props); + } + /** + * Returns a copy of this InsertQueryBuilder instance with the given plugin installed. + */ + withPlugin(plugin) { + return new _InsertQueryBuilder({ + ...this.#props, + executor: this.#props.executor.withPlugin(plugin) + }); + } + toOperationNode() { + return this.#props.executor.transformQuery(this.#props.queryNode, this.#props.queryId); + } + compile() { + return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId); + } + /** + * Executes the query and returns an array of rows. + * + * Also see the {@link executeTakeFirst} and {@link executeTakeFirstOrThrow} methods. + */ + async execute() { + const compiledQuery = this.compile(); + const result = await this.#props.executor.executeQuery(compiledQuery); + const { adapter } = this.#props.executor; + const query = compiledQuery.query; + if (query.returning && adapter.supportsReturning || query.output && adapter.supportsOutput) { + return result.rows; + } + return [ + new InsertResult(result.insertId, result.numAffectedRows ?? BigInt(0)) + ]; + } + /** + * Executes the query and returns the first result or undefined if + * the query returned no result. + */ + async executeTakeFirst() { + const [result] = await this.execute(); + return result; + } + /** + * Executes the query and returns the first result or throws if + * the query returned no result. + * + * By default an instance of {@link NoResultError} is thrown, but you can + * provide a custom error class, or callback as the only argument to throw a different + * error. + */ + async executeTakeFirstOrThrow(errorConstructor = NoResultError) { + const result = await this.executeTakeFirst(); + if (result === void 0) { + const error50 = isNoResultErrorConstructor(errorConstructor) ? new errorConstructor(this.toOperationNode()) : errorConstructor(this.toOperationNode()); + throw error50; + } + return result; + } + async *stream(chunkSize = 100) { + const compiledQuery = this.compile(); + const stream = this.#props.executor.stream(compiledQuery, chunkSize); + for await (const item of stream) { + yield* item.rows; + } + } + async explain(format2, options) { + const builder = new _InsertQueryBuilder({ + ...this.#props, + queryNode: QueryNode.cloneWithExplain(this.#props.queryNode, format2, options) + }); + return await builder.execute(); + } + }; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/delete-result.js +var DeleteResult; +var init_delete_result = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/delete-result.js"() { + DeleteResult = class { + numDeletedRows; + constructor(numDeletedRows) { + this.numDeletedRows = numDeletedRows; + } + }; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/limit-node.js +var LimitNode; +var init_limit_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/limit-node.js"() { + init_object_utils(); + LimitNode = freeze2({ + is(node) { + return node.kind === "LimitNode"; + }, + create(limit) { + return freeze2({ + kind: "LimitNode", + limit + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/delete-query-builder.js +var _a3, DeleteQueryBuilder; +var init_delete_query_builder = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/delete-query-builder.js"() { + init_join_parser(); + init_table_parser(); + init_select_parser(); + init_query_node(); + init_object_utils(); + init_no_result_error(); + init_delete_result(); + init_delete_query_node(); + init_limit_node(); + init_order_by_parser(); + init_binary_operation_parser(); + init_value_parser(); + init_top_parser(); + DeleteQueryBuilder = class { + #props; + constructor(props) { + this.#props = freeze2(props); + } + where(...args) { + return new _a3({ + ...this.#props, + queryNode: QueryNode.cloneWithWhere(this.#props.queryNode, parseValueBinaryOperationOrExpression(args)) + }); + } + whereRef(lhs, op2, rhs) { + return new _a3({ + ...this.#props, + queryNode: QueryNode.cloneWithWhere(this.#props.queryNode, parseReferentialBinaryOperation(lhs, op2, rhs)) + }); + } + clearWhere() { + return new _a3({ + ...this.#props, + queryNode: QueryNode.cloneWithoutWhere(this.#props.queryNode) + }); + } + /** + * Changes a `delete from` query into a `delete top from` query. + * + * `top` clause is only supported by some dialects like MS SQL Server. + * + * ### Examples + * + * Delete the first 5 rows: + * + * ```ts + * await db + * .deleteFrom('person') + * .top(5) + * .where('age', '>', 18) + * .executeTakeFirstOrThrow() + * ``` + * + * The generated SQL (MS SQL Server): + * + * ```sql + * delete top(5) from "person" where "age" > @1 + * ``` + * + * Delete the first 50% of rows: + * + * ```ts + * await db + * .deleteFrom('person') + * .top(50, 'percent') + * .where('age', '>', 18) + * .executeTakeFirstOrThrow() + * ``` + * + * The generated SQL (MS SQL Server): + * + * ```sql + * delete top(50) percent from "person" where "age" > @1 + * ``` + */ + top(expression, modifiers) { + return new _a3({ + ...this.#props, + queryNode: QueryNode.cloneWithTop(this.#props.queryNode, parseTop(expression, modifiers)) + }); + } + using(tables) { + return new _a3({ + ...this.#props, + queryNode: DeleteQueryNode.cloneWithUsing(this.#props.queryNode, parseTableExpressionOrList(tables)) + }); + } + innerJoin(...args) { + return this.#join("InnerJoin", args); + } + leftJoin(...args) { + return this.#join("LeftJoin", args); + } + rightJoin(...args) { + return this.#join("RightJoin", args); + } + fullJoin(...args) { + return this.#join("FullJoin", args); + } + #join(joinType, args) { + return new _a3({ + ...this.#props, + queryNode: QueryNode.cloneWithJoin(this.#props.queryNode, parseJoin(joinType, args)) + }); + } + returning(selection) { + return new _a3({ + ...this.#props, + queryNode: QueryNode.cloneWithReturning(this.#props.queryNode, parseSelectArg(selection)) + }); + } + returningAll(table) { + return new _a3({ + ...this.#props, + queryNode: QueryNode.cloneWithReturning(this.#props.queryNode, parseSelectAll(table)) + }); + } + output(args) { + return new _a3({ + ...this.#props, + queryNode: QueryNode.cloneWithOutput(this.#props.queryNode, parseSelectArg(args)) + }); + } + outputAll(table) { + return new _a3({ + ...this.#props, + queryNode: QueryNode.cloneWithOutput(this.#props.queryNode, parseSelectAll(table)) + }); + } + /** + * Clears all `returning` clauses from the query. + * + * ### Examples + * + * ```ts + * await db.deleteFrom('pet') + * .returningAll() + * .where('name', '=', 'Max') + * .clearReturning() + * .execute() + * ``` + * + * The generated SQL(PostgreSQL): + * + * ```sql + * delete from "pet" where "name" = "Max" + * ``` + */ + clearReturning() { + return new _a3({ + ...this.#props, + queryNode: QueryNode.cloneWithoutReturning(this.#props.queryNode) + }); + } + /** + * Clears the `limit` clause from the query. + * + * ### Examples + * + * ```ts + * await db.deleteFrom('pet') + * .returningAll() + * .where('name', '=', 'Max') + * .limit(5) + * .clearLimit() + * .execute() + * ``` + * + * The generated SQL(PostgreSQL): + * + * ```sql + * delete from "pet" where "name" = "Max" returning * + * ``` + */ + clearLimit() { + return new _a3({ + ...this.#props, + queryNode: DeleteQueryNode.cloneWithoutLimit(this.#props.queryNode) + }); + } + orderBy(...args) { + return new _a3({ + ...this.#props, + queryNode: QueryNode.cloneWithOrderByItems(this.#props.queryNode, parseOrderBy(args)) + }); + } + clearOrderBy() { + return new _a3({ + ...this.#props, + queryNode: QueryNode.cloneWithoutOrderBy(this.#props.queryNode) + }); + } + /** + * Adds a limit clause to the query. + * + * A limit clause in a delete query is only supported by some dialects + * like MySQL. + * + * ### Examples + * + * Delete 5 oldest items in a table: + * + * ```ts + * await db + * .deleteFrom('pet') + * .orderBy('created_at') + * .limit(5) + * .execute() + * ``` + * + * The generated SQL (MySQL): + * + * ```sql + * delete from `pet` order by `created_at` limit ? + * ``` + */ + limit(limit) { + return new _a3({ + ...this.#props, + queryNode: DeleteQueryNode.cloneWithLimit(this.#props.queryNode, LimitNode.create(parseValueExpression(limit))) + }); + } + /** + * This can be used to add any additional SQL to the end of the query. + * + * ### Examples + * + * ```ts + * import { sql } from 'kysely' + * + * await db.deleteFrom('person') + * .where('first_name', '=', 'John') + * .modifyEnd(sql`-- This is a comment`) + * .execute() + * ``` + * + * The generated SQL (MySQL): + * + * ```sql + * delete from `person` + * where `first_name` = "John" -- This is a comment + * ``` + */ + modifyEnd(modifier) { + return new _a3({ + ...this.#props, + queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, modifier.toOperationNode()) + }); + } + /** + * Simply calls the provided function passing `this` as the only argument. `$call` returns + * what the provided function returns. + * + * If you want to conditionally call a method on `this`, see + * the {@link $if} method. + * + * ### Examples + * + * The next example uses a helper function `log` to log a query: + * + * ```ts + * import type { Compilable } from 'kysely' + * + * function log(qb: T): T { + * console.log(qb.compile()) + * return qb + * } + * + * await db.deleteFrom('person') + * .$call(log) + * .execute() + * ``` + */ + $call(func) { + return func(this); + } + /** + * Call `func(this)` if `condition` is true. + * + * This method is especially handy with optional selects. Any `returning` or `returningAll` + * method calls add columns as optional fields to the output type when called inside + * the `func` callback. This is because we can't know if those selections were actually + * made before running the code. + * + * You can also call any other methods inside the callback. + * + * ### Examples + * + * ```ts + * async function deletePerson(id: number, returnLastName: boolean) { + * return await db + * .deleteFrom('person') + * .where('id', '=', id) + * .returning(['id', 'first_name']) + * .$if(returnLastName, (qb) => qb.returning('last_name')) + * .executeTakeFirstOrThrow() + * } + * ``` + * + * Any selections added inside the `if` callback will be added as optional fields to the + * output type since we can't know if the selections were actually made before running + * the code. In the example above the return type of the `deletePerson` function is: + * + * ```ts + * Promise<{ + * id: number + * first_name: string + * last_name?: string + * }> + * ``` + */ + $if(condition, func) { + if (condition) { + return func(this); + } + return new _a3({ + ...this.#props + }); + } + /** + * Change the output type of the query. + * + * This method call doesn't change the SQL in any way. This methods simply + * returns a copy of this `DeleteQueryBuilder` with a new output type. + */ + $castTo() { + return new _a3(this.#props); + } + /** + * Narrows (parts of) the output type of the query. + * + * Kysely tries to be as type-safe as possible, but in some cases we have to make + * compromises for better maintainability and compilation performance. At present, + * Kysely doesn't narrow the output type of the query when using {@link where} and {@link returning} or {@link returningAll}. + * + * This utility method is very useful for these situations, as it removes unncessary + * runtime assertion/guard code. Its input type is limited to the output type + * of the query, so you can't add a column that doesn't exist, or change a column's + * type to something that doesn't exist in its union type. + * + * ### Examples + * + * Turn this code: + * + * ```ts + * import type { Person } from 'type-editor' // imaginary module + * + * const person = await db.deleteFrom('person') + * .where('id', '=', 3) + * .where('nullable_column', 'is not', null) + * .returningAll() + * .executeTakeFirstOrThrow() + * + * if (isWithNoNullValue(person)) { + * functionThatExpectsPersonWithNonNullValue(person) + * } + * + * function isWithNoNullValue(person: Person): person is Person & { nullable_column: string } { + * return person.nullable_column != null + * } + * ``` + * + * Into this: + * + * ```ts + * import type { NotNull } from 'kysely' + * + * const person = await db.deleteFrom('person') + * .where('id', '=', 3) + * .where('nullable_column', 'is not', null) + * .returningAll() + * .$narrowType<{ nullable_column: NotNull }>() + * .executeTakeFirstOrThrow() + * + * functionThatExpectsPersonWithNonNullValue(person) + * ``` + */ + $narrowType() { + return new _a3(this.#props); + } + /** + * Asserts that query's output row type equals the given type `T`. + * + * This method can be used to simplify excessively complex types to make TypeScript happy + * and much faster. + * + * Kysely uses complex type magic to achieve its type safety. This complexity is sometimes too much + * for TypeScript and you get errors like this: + * + * ``` + * error TS2589: Type instantiation is excessively deep and possibly infinite. + * ``` + * + * In these case you can often use this method to help TypeScript a little bit. When you use this + * method to assert the output type of a query, Kysely can drop the complex output type that + * consists of multiple nested helper types and replace it with the simple asserted type. + * + * Using this method doesn't reduce type safety at all. You have to pass in a type that is + * structurally equal to the current type. + * + * ### Examples + * + * ```ts + * import type { Species } from 'type-editor' // imaginary module + * + * async function deletePersonAndPets(personId: number) { + * return await db + * .with('deleted_person', (qb) => qb + * .deleteFrom('person') + * .where('id', '=', personId) + * .returning('first_name') + * .$assertType<{ first_name: string }>() + * ) + * .with('deleted_pets', (qb) => qb + * .deleteFrom('pet') + * .where('owner_id', '=', personId) + * .returning(['name as pet_name', 'species']) + * .$assertType<{ pet_name: string, species: Species }>() + * ) + * .selectFrom(['deleted_person', 'deleted_pets']) + * .selectAll() + * .execute() + * } + * ``` + */ + $assertType() { + return new _a3(this.#props); + } + /** + * Returns a copy of this DeleteQueryBuilder instance with the given plugin installed. + */ + withPlugin(plugin) { + return new _a3({ + ...this.#props, + executor: this.#props.executor.withPlugin(plugin) + }); + } + toOperationNode() { + return this.#props.executor.transformQuery(this.#props.queryNode, this.#props.queryId); + } + compile() { + return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId); + } + /** + * Executes the query and returns an array of rows. + * + * Also see the {@link executeTakeFirst} and {@link executeTakeFirstOrThrow} methods. + */ + async execute() { + const compiledQuery = this.compile(); + const result = await this.#props.executor.executeQuery(compiledQuery); + const { adapter } = this.#props.executor; + const query = compiledQuery.query; + if (query.returning && adapter.supportsReturning || query.output && adapter.supportsOutput) { + return result.rows; + } + return [new DeleteResult(result.numAffectedRows ?? BigInt(0))]; + } + /** + * Executes the query and returns the first result or undefined if + * the query returned no result. + */ + async executeTakeFirst() { + const [result] = await this.execute(); + return result; + } + /** + * Executes the query and returns the first result or throws if + * the query returned no result. + * + * By default an instance of {@link NoResultError} is thrown, but you can + * provide a custom error class, or callback as the only argument to throw a different + * error. + */ + async executeTakeFirstOrThrow(errorConstructor = NoResultError) { + const result = await this.executeTakeFirst(); + if (result === void 0) { + const error50 = isNoResultErrorConstructor(errorConstructor) ? new errorConstructor(this.toOperationNode()) : errorConstructor(this.toOperationNode()); + throw error50; + } + return result; + } + async *stream(chunkSize = 100) { + const compiledQuery = this.compile(); + const stream = this.#props.executor.stream(compiledQuery, chunkSize); + for await (const item of stream) { + yield* item.rows; + } + } + async explain(format2, options) { + const builder = new _a3({ + ...this.#props, + queryNode: QueryNode.cloneWithExplain(this.#props.queryNode, format2, options) + }); + return await builder.execute(); + } + }; + _a3 = DeleteQueryBuilder; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/update-result.js +var UpdateResult; +var init_update_result = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/update-result.js"() { + UpdateResult = class { + /** + * The number of rows the update query updated (even if not changed). + */ + numUpdatedRows; + /** + * The number of rows the update query changed. + * + * This is **optional** and only supported in dialects such as MySQL. + * You would probably use {@link numUpdatedRows} in most cases. + */ + numChangedRows; + constructor(numUpdatedRows, numChangedRows) { + this.numUpdatedRows = numUpdatedRows; + this.numChangedRows = numChangedRows; + } + }; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/update-query-builder.js +var _a4, UpdateQueryBuilder; +var init_update_query_builder = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/update-query-builder.js"() { + init_join_parser(); + init_table_parser(); + init_select_parser(); + init_query_node(); + init_update_query_node(); + init_update_set_parser(); + init_object_utils(); + init_update_result(); + init_no_result_error(); + init_binary_operation_parser(); + init_value_parser(); + init_limit_node(); + init_top_parser(); + init_order_by_parser(); + UpdateQueryBuilder = class { + #props; + constructor(props) { + this.#props = freeze2(props); + } + where(...args) { + return new _a4({ + ...this.#props, + queryNode: QueryNode.cloneWithWhere(this.#props.queryNode, parseValueBinaryOperationOrExpression(args)) + }); + } + whereRef(lhs, op2, rhs) { + return new _a4({ + ...this.#props, + queryNode: QueryNode.cloneWithWhere(this.#props.queryNode, parseReferentialBinaryOperation(lhs, op2, rhs)) + }); + } + clearWhere() { + return new _a4({ + ...this.#props, + queryNode: QueryNode.cloneWithoutWhere(this.#props.queryNode) + }); + } + /** + * Changes an `update` query into a `update top` query. + * + * `top` clause is only supported by some dialects like MS SQL Server. + * + * ### Examples + * + * Update the first row: + * + * ```ts + * await db.updateTable('person') + * .top(1) + * .set({ first_name: 'Foo' }) + * .where('age', '>', 18) + * .executeTakeFirstOrThrow() + * ``` + * + * The generated SQL (MS SQL Server): + * + * ```sql + * update top(1) "person" set "first_name" = @1 where "age" > @2 + * ``` + * + * Update the 50% first rows: + * + * ```ts + * await db.updateTable('person') + * .top(50, 'percent') + * .set({ first_name: 'Foo' }) + * .where('age', '>', 18) + * .executeTakeFirstOrThrow() + * ``` + * + * The generated SQL (MS SQL Server): + * + * ```sql + * update top(50) percent "person" set "first_name" = @1 where "age" > @2 + * ``` + */ + top(expression, modifiers) { + return new _a4({ + ...this.#props, + queryNode: QueryNode.cloneWithTop(this.#props.queryNode, parseTop(expression, modifiers)) + }); + } + from(from) { + return new _a4({ + ...this.#props, + queryNode: UpdateQueryNode.cloneWithFromItems(this.#props.queryNode, parseTableExpressionOrList(from)) + }); + } + innerJoin(...args) { + return this.#join("InnerJoin", args); + } + leftJoin(...args) { + return this.#join("LeftJoin", args); + } + rightJoin(...args) { + return this.#join("RightJoin", args); + } + fullJoin(...args) { + return this.#join("FullJoin", args); + } + #join(joinType, args) { + return new _a4({ + ...this.#props, + queryNode: QueryNode.cloneWithJoin(this.#props.queryNode, parseJoin(joinType, args)) + }); + } + orderBy(...args) { + return new _a4({ + ...this.#props, + queryNode: QueryNode.cloneWithOrderByItems(this.#props.queryNode, parseOrderBy(args)) + }); + } + clearOrderBy() { + return new _a4({ + ...this.#props, + queryNode: QueryNode.cloneWithoutOrderBy(this.#props.queryNode) + }); + } + /** + * Adds a limit clause to the update query for supported databases, such as MySQL. + * + * ### Examples + * + * Update the first 2 rows in the 'person' table: + * + * ```ts + * await db + * .updateTable('person') + * .set({ first_name: 'Foo' }) + * .limit(2) + * .execute() + * ``` + * + * The generated SQL (MySQL): + * + * ```sql + * update `person` set `first_name` = ? limit ? + * ``` + */ + limit(limit) { + return new _a4({ + ...this.#props, + queryNode: UpdateQueryNode.cloneWithLimit(this.#props.queryNode, LimitNode.create(parseValueExpression(limit))) + }); + } + set(...args) { + return new _a4({ + ...this.#props, + queryNode: UpdateQueryNode.cloneWithUpdates(this.#props.queryNode, parseUpdate(...args)) + }); + } + returning(selection) { + return new _a4({ + ...this.#props, + queryNode: QueryNode.cloneWithReturning(this.#props.queryNode, parseSelectArg(selection)) + }); + } + returningAll(table) { + return new _a4({ + ...this.#props, + queryNode: QueryNode.cloneWithReturning(this.#props.queryNode, parseSelectAll(table)) + }); + } + output(args) { + return new _a4({ + ...this.#props, + queryNode: QueryNode.cloneWithOutput(this.#props.queryNode, parseSelectArg(args)) + }); + } + outputAll(table) { + return new _a4({ + ...this.#props, + queryNode: QueryNode.cloneWithOutput(this.#props.queryNode, parseSelectAll(table)) + }); + } + /** + * This can be used to add any additional SQL to the end of the query. + * + * ### Examples + * + * ```ts + * import { sql } from 'kysely' + * + * await db.updateTable('person') + * .set({ age: 39 }) + * .where('first_name', '=', 'John') + * .modifyEnd(sql.raw('-- This is a comment')) + * .execute() + * ``` + * + * The generated SQL (MySQL): + * + * ```sql + * update `person` + * set `age` = 39 + * where `first_name` = "John" -- This is a comment + * ``` + */ + modifyEnd(modifier) { + return new _a4({ + ...this.#props, + queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, modifier.toOperationNode()) + }); + } + /** + * Clears all `returning` clauses from the query. + * + * ### Examples + * + * ```ts + * db.updateTable('person') + * .returningAll() + * .set({ age: 39 }) + * .where('first_name', '=', 'John') + * .clearReturning() + * ``` + * + * The generated SQL(PostgreSQL): + * + * ```sql + * update "person" set "age" = 39 where "first_name" = "John" + * ``` + */ + clearReturning() { + return new _a4({ + ...this.#props, + queryNode: QueryNode.cloneWithoutReturning(this.#props.queryNode) + }); + } + /** + * Simply calls the provided function passing `this` as the only argument. `$call` returns + * what the provided function returns. + * + * If you want to conditionally call a method on `this`, see + * the {@link $if} method. + * + * ### Examples + * + * The next example uses a helper function `log` to log a query: + * + * ```ts + * import type { Compilable } from 'kysely' + * import type { PersonUpdate } from 'type-editor' // imaginary module + * + * function log(qb: T): T { + * console.log(qb.compile()) + * return qb + * } + * + * const values = { + * first_name: 'John', + * } satisfies PersonUpdate + * + * db.updateTable('person') + * .set(values) + * .$call(log) + * .execute() + * ``` + */ + $call(func) { + return func(this); + } + /** + * Call `func(this)` if `condition` is true. + * + * This method is especially handy with optional selects. Any `returning` or `returningAll` + * method calls add columns as optional fields to the output type when called inside + * the `func` callback. This is because we can't know if those selections were actually + * made before running the code. + * + * You can also call any other methods inside the callback. + * + * ### Examples + * + * ```ts + * import type { PersonUpdate } from 'type-editor' // imaginary module + * + * async function updatePerson(id: number, updates: PersonUpdate, returnLastName: boolean) { + * return await db + * .updateTable('person') + * .set(updates) + * .where('id', '=', id) + * .returning(['id', 'first_name']) + * .$if(returnLastName, (qb) => qb.returning('last_name')) + * .executeTakeFirstOrThrow() + * } + * ``` + * + * Any selections added inside the `if` callback will be added as optional fields to the + * output type since we can't know if the selections were actually made before running + * the code. In the example above the return type of the `updatePerson` function is: + * + * ```ts + * Promise<{ + * id: number + * first_name: string + * last_name?: string + * }> + * ``` + */ + $if(condition, func) { + if (condition) { + return func(this); + } + return new _a4({ + ...this.#props + }); + } + /** + * Change the output type of the query. + * + * This method call doesn't change the SQL in any way. This methods simply + * returns a copy of this `UpdateQueryBuilder` with a new output type. + */ + $castTo() { + return new _a4(this.#props); + } + /** + * Narrows (parts of) the output type of the query. + * + * Kysely tries to be as type-safe as possible, but in some cases we have to make + * compromises for better maintainability and compilation performance. At present, + * Kysely doesn't narrow the output type of the query based on {@link set} input + * when using {@link where} and/or {@link returning} or {@link returningAll}. + * + * This utility method is very useful for these situations, as it removes unncessary + * runtime assertion/guard code. Its input type is limited to the output type + * of the query, so you can't add a column that doesn't exist, or change a column's + * type to something that doesn't exist in its union type. + * + * ### Examples + * + * Turn this code: + * + * ```ts + * import type { Person } from 'type-editor' // imaginary module + * + * const id = 1 + * const now = new Date().toISOString() + * + * const person = await db.updateTable('person') + * .set({ deleted_at: now }) + * .where('id', '=', id) + * .where('nullable_column', 'is not', null) + * .returningAll() + * .executeTakeFirstOrThrow() + * + * if (isWithNoNullValue(person)) { + * functionThatExpectsPersonWithNonNullValue(person) + * } + * + * function isWithNoNullValue(person: Person): person is Person & { nullable_column: string } { + * return person.nullable_column != null + * } + * ``` + * + * Into this: + * + * ```ts + * import type { NotNull } from 'kysely' + * + * const id = 1 + * const now = new Date().toISOString() + * + * const person = await db.updateTable('person') + * .set({ deleted_at: now }) + * .where('id', '=', id) + * .where('nullable_column', 'is not', null) + * .returningAll() + * .$narrowType<{ deleted_at: Date; nullable_column: NotNull }>() + * .executeTakeFirstOrThrow() + * + * functionThatExpectsPersonWithNonNullValue(person) + * ``` + */ + $narrowType() { + return new _a4(this.#props); + } + /** + * Asserts that query's output row type equals the given type `T`. + * + * This method can be used to simplify excessively complex types to make TypeScript happy + * and much faster. + * + * Kysely uses complex type magic to achieve its type safety. This complexity is sometimes too much + * for TypeScript and you get errors like this: + * + * ``` + * error TS2589: Type instantiation is excessively deep and possibly infinite. + * ``` + * + * In these case you can often use this method to help TypeScript a little bit. When you use this + * method to assert the output type of a query, Kysely can drop the complex output type that + * consists of multiple nested helper types and replace it with the simple asserted type. + * + * Using this method doesn't reduce type safety at all. You have to pass in a type that is + * structurally equal to the current type. + * + * ### Examples + * + * ```ts + * import type { PersonUpdate, PetUpdate, Species } from 'type-editor' // imaginary module + * + * const person = { + * id: 1, + * gender: 'other', + * } satisfies PersonUpdate + * + * const pet = { + * name: 'Fluffy', + * } satisfies PetUpdate + * + * const result = await db + * .with('updated_person', (qb) => qb + * .updateTable('person') + * .set(person) + * .where('id', '=', person.id) + * .returning('first_name') + * .$assertType<{ first_name: string }>() + * ) + * .with('updated_pet', (qb) => qb + * .updateTable('pet') + * .set(pet) + * .where('owner_id', '=', person.id) + * .returning(['name as pet_name', 'species']) + * .$assertType<{ pet_name: string, species: Species }>() + * ) + * .selectFrom(['updated_person', 'updated_pet']) + * .selectAll() + * .executeTakeFirstOrThrow() + * ``` + */ + $assertType() { + return new _a4(this.#props); + } + /** + * Returns a copy of this UpdateQueryBuilder instance with the given plugin installed. + */ + withPlugin(plugin) { + return new _a4({ + ...this.#props, + executor: this.#props.executor.withPlugin(plugin) + }); + } + toOperationNode() { + return this.#props.executor.transformQuery(this.#props.queryNode, this.#props.queryId); + } + compile() { + return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId); + } + /** + * Executes the query and returns an array of rows. + * + * Also see the {@link executeTakeFirst} and {@link executeTakeFirstOrThrow} methods. + */ + async execute() { + const compiledQuery = this.compile(); + const result = await this.#props.executor.executeQuery(compiledQuery); + const { adapter } = this.#props.executor; + const query = compiledQuery.query; + if (query.returning && adapter.supportsReturning || query.output && adapter.supportsOutput) { + return result.rows; + } + return [ + new UpdateResult(result.numAffectedRows ?? BigInt(0), result.numChangedRows) + ]; + } + /** + * Executes the query and returns the first result or undefined if + * the query returned no result. + */ + async executeTakeFirst() { + const [result] = await this.execute(); + return result; + } + /** + * Executes the query and returns the first result or throws if + * the query returned no result. + * + * By default an instance of {@link NoResultError} is thrown, but you can + * provide a custom error class, or callback as the only argument to throw a different + * error. + */ + async executeTakeFirstOrThrow(errorConstructor = NoResultError) { + const result = await this.executeTakeFirst(); + if (result === void 0) { + const error50 = isNoResultErrorConstructor(errorConstructor) ? new errorConstructor(this.toOperationNode()) : errorConstructor(this.toOperationNode()); + throw error50; + } + return result; + } + async *stream(chunkSize = 100) { + const compiledQuery = this.compile(); + const stream = this.#props.executor.stream(compiledQuery, chunkSize); + for await (const item of stream) { + yield* item.rows; + } + } + async explain(format2, options) { + const builder = new _a4({ + ...this.#props, + queryNode: QueryNode.cloneWithExplain(this.#props.queryNode, format2, options) + }); + return await builder.execute(); + } + }; + _a4 = UpdateQueryBuilder; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/common-table-expression-name-node.js +var CommonTableExpressionNameNode; +var init_common_table_expression_name_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/common-table-expression-name-node.js"() { + init_object_utils(); + init_column_node(); + init_table_node(); + CommonTableExpressionNameNode = freeze2({ + is(node) { + return node.kind === "CommonTableExpressionNameNode"; + }, + create(tableName, columnNames) { + return freeze2({ + kind: "CommonTableExpressionNameNode", + table: TableNode.create(tableName), + columns: columnNames ? freeze2(columnNames.map(ColumnNode.create)) : void 0 + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/common-table-expression-node.js +var CommonTableExpressionNode; +var init_common_table_expression_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/common-table-expression-node.js"() { + init_object_utils(); + CommonTableExpressionNode = freeze2({ + is(node) { + return node.kind === "CommonTableExpressionNode"; + }, + create(name, expression) { + return freeze2({ + kind: "CommonTableExpressionNode", + name, + expression + }); + }, + cloneWith(node, props) { + return freeze2({ + ...node, + ...props + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/cte-builder.js +var CTEBuilder; +var init_cte_builder = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/cte-builder.js"() { + init_common_table_expression_node(); + init_object_utils(); + CTEBuilder = class _CTEBuilder { + #props; + constructor(props) { + this.#props = freeze2(props); + } + /** + * Makes the common table expression materialized. + */ + materialized() { + return new _CTEBuilder({ + ...this.#props, + node: CommonTableExpressionNode.cloneWith(this.#props.node, { + materialized: true + }) + }); + } + /** + * Makes the common table expression not materialized. + */ + notMaterialized() { + return new _CTEBuilder({ + ...this.#props, + node: CommonTableExpressionNode.cloneWith(this.#props.node, { + materialized: false + }) + }); + } + toOperationNode() { + return this.#props.node; + } + }; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/with-parser.js +function parseCommonTableExpression(nameOrBuilderCallback, expression) { + const expressionNode = expression(createQueryCreator()).toOperationNode(); + if (isFunction(nameOrBuilderCallback)) { + return nameOrBuilderCallback(cteBuilderFactory(expressionNode)).toOperationNode(); + } + return CommonTableExpressionNode.create(parseCommonTableExpressionName(nameOrBuilderCallback), expressionNode); +} +function cteBuilderFactory(expressionNode) { + return (name) => { + return new CTEBuilder({ + node: CommonTableExpressionNode.create(parseCommonTableExpressionName(name), expressionNode) + }); + }; +} +function parseCommonTableExpressionName(name) { + if (name.includes("(")) { + const parts = name.split(/[\(\)]/); + const table = parts[0]; + const columns = parts[1].split(",").map((it) => it.trim()); + return CommonTableExpressionNameNode.create(table, columns); + } else { + return CommonTableExpressionNameNode.create(name); + } +} +var init_with_parser = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/with-parser.js"() { + init_common_table_expression_name_node(); + init_parse_utils2(); + init_object_utils(); + init_cte_builder(); + init_common_table_expression_node(); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/with-node.js +var WithNode; +var init_with_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/with-node.js"() { + init_object_utils(); + WithNode = freeze2({ + is(node) { + return node.kind === "WithNode"; + }, + create(expression, params) { + return freeze2({ + kind: "WithNode", + expressions: freeze2([expression]), + ...params + }); + }, + cloneWithExpression(withNode, expression) { + return freeze2({ + ...withNode, + expressions: freeze2([...withNode.expressions, expression]) + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/random-string.js +function randomString2(length) { + let chars = ""; + for (let i5 = 0; i5 < length; ++i5) { + chars += randomChar(); + } + return chars; +} +function randomChar() { + return CHARS[~~(Math.random() * CHARS.length)]; +} +var CHARS; +var init_random_string = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/random-string.js"() { + CHARS = [ + "A", + "B", + "C", + "D", + "E", + "F", + "G", + "H", + "I", + "J", + "K", + "L", + "M", + "N", + "O", + "P", + "Q", + "R", + "S", + "T", + "U", + "V", + "W", + "X", + "Y", + "Z", + "a", + "b", + "c", + "d", + "e", + "f", + "g", + "h", + "i", + "j", + "k", + "l", + "m", + "n", + "o", + "p", + "q", + "r", + "s", + "t", + "u", + "v", + "w", + "x", + "y", + "z", + "0", + "1", + "2", + "3", + "4", + "5", + "6", + "7", + "8", + "9" + ]; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/query-id.js +function createQueryId() { + return new LazyQueryId(); +} +var LazyQueryId; +var init_query_id = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/query-id.js"() { + init_random_string(); + LazyQueryId = class { + #queryId; + get queryId() { + if (this.#queryId === void 0) { + this.#queryId = randomString2(8); + } + return this.#queryId; + } + }; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/require-all-props.js +function requireAllProps(obj) { + return obj; +} +var init_require_all_props = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/require-all-props.js"() { + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/operation-node-transformer.js +var OperationNodeTransformer; +var init_operation_node_transformer = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/operation-node-transformer.js"() { + init_object_utils(); + init_require_all_props(); + OperationNodeTransformer = class { + nodeStack = []; + #transformers = freeze2({ + AliasNode: this.transformAlias.bind(this), + ColumnNode: this.transformColumn.bind(this), + IdentifierNode: this.transformIdentifier.bind(this), + SchemableIdentifierNode: this.transformSchemableIdentifier.bind(this), + RawNode: this.transformRaw.bind(this), + ReferenceNode: this.transformReference.bind(this), + SelectQueryNode: this.transformSelectQuery.bind(this), + SelectionNode: this.transformSelection.bind(this), + TableNode: this.transformTable.bind(this), + FromNode: this.transformFrom.bind(this), + SelectAllNode: this.transformSelectAll.bind(this), + AndNode: this.transformAnd.bind(this), + OrNode: this.transformOr.bind(this), + ValueNode: this.transformValue.bind(this), + ValueListNode: this.transformValueList.bind(this), + PrimitiveValueListNode: this.transformPrimitiveValueList.bind(this), + ParensNode: this.transformParens.bind(this), + JoinNode: this.transformJoin.bind(this), + OperatorNode: this.transformOperator.bind(this), + WhereNode: this.transformWhere.bind(this), + InsertQueryNode: this.transformInsertQuery.bind(this), + DeleteQueryNode: this.transformDeleteQuery.bind(this), + ReturningNode: this.transformReturning.bind(this), + CreateTableNode: this.transformCreateTable.bind(this), + AddColumnNode: this.transformAddColumn.bind(this), + ColumnDefinitionNode: this.transformColumnDefinition.bind(this), + DropTableNode: this.transformDropTable.bind(this), + DataTypeNode: this.transformDataType.bind(this), + OrderByNode: this.transformOrderBy.bind(this), + OrderByItemNode: this.transformOrderByItem.bind(this), + GroupByNode: this.transformGroupBy.bind(this), + GroupByItemNode: this.transformGroupByItem.bind(this), + UpdateQueryNode: this.transformUpdateQuery.bind(this), + ColumnUpdateNode: this.transformColumnUpdate.bind(this), + LimitNode: this.transformLimit.bind(this), + OffsetNode: this.transformOffset.bind(this), + OnConflictNode: this.transformOnConflict.bind(this), + OnDuplicateKeyNode: this.transformOnDuplicateKey.bind(this), + CreateIndexNode: this.transformCreateIndex.bind(this), + DropIndexNode: this.transformDropIndex.bind(this), + ListNode: this.transformList.bind(this), + PrimaryKeyConstraintNode: this.transformPrimaryKeyConstraint.bind(this), + UniqueConstraintNode: this.transformUniqueConstraint.bind(this), + ReferencesNode: this.transformReferences.bind(this), + CheckConstraintNode: this.transformCheckConstraint.bind(this), + WithNode: this.transformWith.bind(this), + CommonTableExpressionNode: this.transformCommonTableExpression.bind(this), + CommonTableExpressionNameNode: this.transformCommonTableExpressionName.bind(this), + HavingNode: this.transformHaving.bind(this), + CreateSchemaNode: this.transformCreateSchema.bind(this), + DropSchemaNode: this.transformDropSchema.bind(this), + AlterTableNode: this.transformAlterTable.bind(this), + DropColumnNode: this.transformDropColumn.bind(this), + RenameColumnNode: this.transformRenameColumn.bind(this), + AlterColumnNode: this.transformAlterColumn.bind(this), + ModifyColumnNode: this.transformModifyColumn.bind(this), + AddConstraintNode: this.transformAddConstraint.bind(this), + DropConstraintNode: this.transformDropConstraint.bind(this), + RenameConstraintNode: this.transformRenameConstraint.bind(this), + ForeignKeyConstraintNode: this.transformForeignKeyConstraint.bind(this), + CreateViewNode: this.transformCreateView.bind(this), + RefreshMaterializedViewNode: this.transformRefreshMaterializedView.bind(this), + DropViewNode: this.transformDropView.bind(this), + GeneratedNode: this.transformGenerated.bind(this), + DefaultValueNode: this.transformDefaultValue.bind(this), + OnNode: this.transformOn.bind(this), + ValuesNode: this.transformValues.bind(this), + SelectModifierNode: this.transformSelectModifier.bind(this), + CreateTypeNode: this.transformCreateType.bind(this), + DropTypeNode: this.transformDropType.bind(this), + ExplainNode: this.transformExplain.bind(this), + DefaultInsertValueNode: this.transformDefaultInsertValue.bind(this), + AggregateFunctionNode: this.transformAggregateFunction.bind(this), + OverNode: this.transformOver.bind(this), + PartitionByNode: this.transformPartitionBy.bind(this), + PartitionByItemNode: this.transformPartitionByItem.bind(this), + SetOperationNode: this.transformSetOperation.bind(this), + BinaryOperationNode: this.transformBinaryOperation.bind(this), + UnaryOperationNode: this.transformUnaryOperation.bind(this), + UsingNode: this.transformUsing.bind(this), + FunctionNode: this.transformFunction.bind(this), + CaseNode: this.transformCase.bind(this), + WhenNode: this.transformWhen.bind(this), + JSONReferenceNode: this.transformJSONReference.bind(this), + JSONPathNode: this.transformJSONPath.bind(this), + JSONPathLegNode: this.transformJSONPathLeg.bind(this), + JSONOperatorChainNode: this.transformJSONOperatorChain.bind(this), + TupleNode: this.transformTuple.bind(this), + MergeQueryNode: this.transformMergeQuery.bind(this), + MatchedNode: this.transformMatched.bind(this), + AddIndexNode: this.transformAddIndex.bind(this), + CastNode: this.transformCast.bind(this), + FetchNode: this.transformFetch.bind(this), + TopNode: this.transformTop.bind(this), + OutputNode: this.transformOutput.bind(this), + OrActionNode: this.transformOrAction.bind(this), + CollateNode: this.transformCollate.bind(this) + }); + transformNode(node, queryId) { + if (!node) { + return node; + } + this.nodeStack.push(node); + const out = this.transformNodeImpl(node, queryId); + this.nodeStack.pop(); + return freeze2(out); + } + transformNodeImpl(node, queryId) { + return this.#transformers[node.kind](node, queryId); + } + transformNodeList(list2, queryId) { + if (!list2) { + return list2; + } + return freeze2(list2.map((node) => this.transformNode(node, queryId))); + } + transformSelectQuery(node, queryId) { + return requireAllProps({ + kind: "SelectQueryNode", + from: this.transformNode(node.from, queryId), + selections: this.transformNodeList(node.selections, queryId), + distinctOn: this.transformNodeList(node.distinctOn, queryId), + joins: this.transformNodeList(node.joins, queryId), + groupBy: this.transformNode(node.groupBy, queryId), + orderBy: this.transformNode(node.orderBy, queryId), + where: this.transformNode(node.where, queryId), + frontModifiers: this.transformNodeList(node.frontModifiers, queryId), + endModifiers: this.transformNodeList(node.endModifiers, queryId), + limit: this.transformNode(node.limit, queryId), + offset: this.transformNode(node.offset, queryId), + with: this.transformNode(node.with, queryId), + having: this.transformNode(node.having, queryId), + explain: this.transformNode(node.explain, queryId), + setOperations: this.transformNodeList(node.setOperations, queryId), + fetch: this.transformNode(node.fetch, queryId), + top: this.transformNode(node.top, queryId) + }); + } + transformSelection(node, queryId) { + return requireAllProps({ + kind: "SelectionNode", + selection: this.transformNode(node.selection, queryId) + }); + } + transformColumn(node, queryId) { + return requireAllProps({ + kind: "ColumnNode", + column: this.transformNode(node.column, queryId) + }); + } + transformAlias(node, queryId) { + return requireAllProps({ + kind: "AliasNode", + node: this.transformNode(node.node, queryId), + alias: this.transformNode(node.alias, queryId) + }); + } + transformTable(node, queryId) { + return requireAllProps({ + kind: "TableNode", + table: this.transformNode(node.table, queryId) + }); + } + transformFrom(node, queryId) { + return requireAllProps({ + kind: "FromNode", + froms: this.transformNodeList(node.froms, queryId) + }); + } + transformReference(node, queryId) { + return requireAllProps({ + kind: "ReferenceNode", + column: this.transformNode(node.column, queryId), + table: this.transformNode(node.table, queryId) + }); + } + transformAnd(node, queryId) { + return requireAllProps({ + kind: "AndNode", + left: this.transformNode(node.left, queryId), + right: this.transformNode(node.right, queryId) + }); + } + transformOr(node, queryId) { + return requireAllProps({ + kind: "OrNode", + left: this.transformNode(node.left, queryId), + right: this.transformNode(node.right, queryId) + }); + } + transformValueList(node, queryId) { + return requireAllProps({ + kind: "ValueListNode", + values: this.transformNodeList(node.values, queryId) + }); + } + transformParens(node, queryId) { + return requireAllProps({ + kind: "ParensNode", + node: this.transformNode(node.node, queryId) + }); + } + transformJoin(node, queryId) { + return requireAllProps({ + kind: "JoinNode", + joinType: node.joinType, + table: this.transformNode(node.table, queryId), + on: this.transformNode(node.on, queryId) + }); + } + transformRaw(node, queryId) { + return requireAllProps({ + kind: "RawNode", + sqlFragments: freeze2([...node.sqlFragments]), + parameters: this.transformNodeList(node.parameters, queryId) + }); + } + transformWhere(node, queryId) { + return requireAllProps({ + kind: "WhereNode", + where: this.transformNode(node.where, queryId) + }); + } + transformInsertQuery(node, queryId) { + return requireAllProps({ + kind: "InsertQueryNode", + into: this.transformNode(node.into, queryId), + columns: this.transformNodeList(node.columns, queryId), + values: this.transformNode(node.values, queryId), + returning: this.transformNode(node.returning, queryId), + onConflict: this.transformNode(node.onConflict, queryId), + onDuplicateKey: this.transformNode(node.onDuplicateKey, queryId), + endModifiers: this.transformNodeList(node.endModifiers, queryId), + with: this.transformNode(node.with, queryId), + ignore: node.ignore, + orAction: this.transformNode(node.orAction, queryId), + replace: node.replace, + explain: this.transformNode(node.explain, queryId), + defaultValues: node.defaultValues, + top: this.transformNode(node.top, queryId), + output: this.transformNode(node.output, queryId) + }); + } + transformValues(node, queryId) { + return requireAllProps({ + kind: "ValuesNode", + values: this.transformNodeList(node.values, queryId) + }); + } + transformDeleteQuery(node, queryId) { + return requireAllProps({ + kind: "DeleteQueryNode", + from: this.transformNode(node.from, queryId), + using: this.transformNode(node.using, queryId), + joins: this.transformNodeList(node.joins, queryId), + where: this.transformNode(node.where, queryId), + returning: this.transformNode(node.returning, queryId), + endModifiers: this.transformNodeList(node.endModifiers, queryId), + with: this.transformNode(node.with, queryId), + orderBy: this.transformNode(node.orderBy, queryId), + limit: this.transformNode(node.limit, queryId), + explain: this.transformNode(node.explain, queryId), + top: this.transformNode(node.top, queryId), + output: this.transformNode(node.output, queryId) + }); + } + transformReturning(node, queryId) { + return requireAllProps({ + kind: "ReturningNode", + selections: this.transformNodeList(node.selections, queryId) + }); + } + transformCreateTable(node, queryId) { + return requireAllProps({ + kind: "CreateTableNode", + table: this.transformNode(node.table, queryId), + columns: this.transformNodeList(node.columns, queryId), + constraints: this.transformNodeList(node.constraints, queryId), + temporary: node.temporary, + ifNotExists: node.ifNotExists, + onCommit: node.onCommit, + frontModifiers: this.transformNodeList(node.frontModifiers, queryId), + endModifiers: this.transformNodeList(node.endModifiers, queryId), + selectQuery: this.transformNode(node.selectQuery, queryId) + }); + } + transformColumnDefinition(node, queryId) { + return requireAllProps({ + kind: "ColumnDefinitionNode", + column: this.transformNode(node.column, queryId), + dataType: this.transformNode(node.dataType, queryId), + references: this.transformNode(node.references, queryId), + primaryKey: node.primaryKey, + autoIncrement: node.autoIncrement, + unique: node.unique, + notNull: node.notNull, + unsigned: node.unsigned, + defaultTo: this.transformNode(node.defaultTo, queryId), + check: this.transformNode(node.check, queryId), + generated: this.transformNode(node.generated, queryId), + frontModifiers: this.transformNodeList(node.frontModifiers, queryId), + endModifiers: this.transformNodeList(node.endModifiers, queryId), + nullsNotDistinct: node.nullsNotDistinct, + identity: node.identity, + ifNotExists: node.ifNotExists + }); + } + transformAddColumn(node, queryId) { + return requireAllProps({ + kind: "AddColumnNode", + column: this.transformNode(node.column, queryId) + }); + } + transformDropTable(node, queryId) { + return requireAllProps({ + kind: "DropTableNode", + table: this.transformNode(node.table, queryId), + ifExists: node.ifExists, + cascade: node.cascade + }); + } + transformOrderBy(node, queryId) { + return requireAllProps({ + kind: "OrderByNode", + items: this.transformNodeList(node.items, queryId) + }); + } + transformOrderByItem(node, queryId) { + return requireAllProps({ + kind: "OrderByItemNode", + orderBy: this.transformNode(node.orderBy, queryId), + direction: this.transformNode(node.direction, queryId), + collation: this.transformNode(node.collation, queryId), + nulls: node.nulls + }); + } + transformGroupBy(node, queryId) { + return requireAllProps({ + kind: "GroupByNode", + items: this.transformNodeList(node.items, queryId) + }); + } + transformGroupByItem(node, queryId) { + return requireAllProps({ + kind: "GroupByItemNode", + groupBy: this.transformNode(node.groupBy, queryId) + }); + } + transformUpdateQuery(node, queryId) { + return requireAllProps({ + kind: "UpdateQueryNode", + table: this.transformNode(node.table, queryId), + from: this.transformNode(node.from, queryId), + joins: this.transformNodeList(node.joins, queryId), + where: this.transformNode(node.where, queryId), + updates: this.transformNodeList(node.updates, queryId), + returning: this.transformNode(node.returning, queryId), + endModifiers: this.transformNodeList(node.endModifiers, queryId), + with: this.transformNode(node.with, queryId), + explain: this.transformNode(node.explain, queryId), + limit: this.transformNode(node.limit, queryId), + top: this.transformNode(node.top, queryId), + output: this.transformNode(node.output, queryId), + orderBy: this.transformNode(node.orderBy, queryId) + }); + } + transformColumnUpdate(node, queryId) { + return requireAllProps({ + kind: "ColumnUpdateNode", + column: this.transformNode(node.column, queryId), + value: this.transformNode(node.value, queryId) + }); + } + transformLimit(node, queryId) { + return requireAllProps({ + kind: "LimitNode", + limit: this.transformNode(node.limit, queryId) + }); + } + transformOffset(node, queryId) { + return requireAllProps({ + kind: "OffsetNode", + offset: this.transformNode(node.offset, queryId) + }); + } + transformOnConflict(node, queryId) { + return requireAllProps({ + kind: "OnConflictNode", + columns: this.transformNodeList(node.columns, queryId), + constraint: this.transformNode(node.constraint, queryId), + indexExpression: this.transformNode(node.indexExpression, queryId), + indexWhere: this.transformNode(node.indexWhere, queryId), + updates: this.transformNodeList(node.updates, queryId), + updateWhere: this.transformNode(node.updateWhere, queryId), + doNothing: node.doNothing + }); + } + transformOnDuplicateKey(node, queryId) { + return requireAllProps({ + kind: "OnDuplicateKeyNode", + updates: this.transformNodeList(node.updates, queryId) + }); + } + transformCreateIndex(node, queryId) { + return requireAllProps({ + kind: "CreateIndexNode", + name: this.transformNode(node.name, queryId), + table: this.transformNode(node.table, queryId), + columns: this.transformNodeList(node.columns, queryId), + unique: node.unique, + using: this.transformNode(node.using, queryId), + ifNotExists: node.ifNotExists, + where: this.transformNode(node.where, queryId), + nullsNotDistinct: node.nullsNotDistinct + }); + } + transformList(node, queryId) { + return requireAllProps({ + kind: "ListNode", + items: this.transformNodeList(node.items, queryId) + }); + } + transformDropIndex(node, queryId) { + return requireAllProps({ + kind: "DropIndexNode", + name: this.transformNode(node.name, queryId), + table: this.transformNode(node.table, queryId), + ifExists: node.ifExists, + cascade: node.cascade + }); + } + transformPrimaryKeyConstraint(node, queryId) { + return requireAllProps({ + kind: "PrimaryKeyConstraintNode", + columns: this.transformNodeList(node.columns, queryId), + name: this.transformNode(node.name, queryId), + deferrable: node.deferrable, + initiallyDeferred: node.initiallyDeferred + }); + } + transformUniqueConstraint(node, queryId) { + return requireAllProps({ + kind: "UniqueConstraintNode", + columns: this.transformNodeList(node.columns, queryId), + name: this.transformNode(node.name, queryId), + nullsNotDistinct: node.nullsNotDistinct, + deferrable: node.deferrable, + initiallyDeferred: node.initiallyDeferred + }); + } + transformForeignKeyConstraint(node, queryId) { + return requireAllProps({ + kind: "ForeignKeyConstraintNode", + columns: this.transformNodeList(node.columns, queryId), + references: this.transformNode(node.references, queryId), + name: this.transformNode(node.name, queryId), + onDelete: node.onDelete, + onUpdate: node.onUpdate, + deferrable: node.deferrable, + initiallyDeferred: node.initiallyDeferred + }); + } + transformSetOperation(node, queryId) { + return requireAllProps({ + kind: "SetOperationNode", + operator: node.operator, + expression: this.transformNode(node.expression, queryId), + all: node.all + }); + } + transformReferences(node, queryId) { + return requireAllProps({ + kind: "ReferencesNode", + table: this.transformNode(node.table, queryId), + columns: this.transformNodeList(node.columns, queryId), + onDelete: node.onDelete, + onUpdate: node.onUpdate + }); + } + transformCheckConstraint(node, queryId) { + return requireAllProps({ + kind: "CheckConstraintNode", + expression: this.transformNode(node.expression, queryId), + name: this.transformNode(node.name, queryId) + }); + } + transformWith(node, queryId) { + return requireAllProps({ + kind: "WithNode", + expressions: this.transformNodeList(node.expressions, queryId), + recursive: node.recursive + }); + } + transformCommonTableExpression(node, queryId) { + return requireAllProps({ + kind: "CommonTableExpressionNode", + name: this.transformNode(node.name, queryId), + materialized: node.materialized, + expression: this.transformNode(node.expression, queryId) + }); + } + transformCommonTableExpressionName(node, queryId) { + return requireAllProps({ + kind: "CommonTableExpressionNameNode", + table: this.transformNode(node.table, queryId), + columns: this.transformNodeList(node.columns, queryId) + }); + } + transformHaving(node, queryId) { + return requireAllProps({ + kind: "HavingNode", + having: this.transformNode(node.having, queryId) + }); + } + transformCreateSchema(node, queryId) { + return requireAllProps({ + kind: "CreateSchemaNode", + schema: this.transformNode(node.schema, queryId), + ifNotExists: node.ifNotExists + }); + } + transformDropSchema(node, queryId) { + return requireAllProps({ + kind: "DropSchemaNode", + schema: this.transformNode(node.schema, queryId), + ifExists: node.ifExists, + cascade: node.cascade + }); + } + transformAlterTable(node, queryId) { + return requireAllProps({ + kind: "AlterTableNode", + table: this.transformNode(node.table, queryId), + renameTo: this.transformNode(node.renameTo, queryId), + setSchema: this.transformNode(node.setSchema, queryId), + columnAlterations: this.transformNodeList(node.columnAlterations, queryId), + addConstraint: this.transformNode(node.addConstraint, queryId), + dropConstraint: this.transformNode(node.dropConstraint, queryId), + renameConstraint: this.transformNode(node.renameConstraint, queryId), + addIndex: this.transformNode(node.addIndex, queryId), + dropIndex: this.transformNode(node.dropIndex, queryId) + }); + } + transformDropColumn(node, queryId) { + return requireAllProps({ + kind: "DropColumnNode", + column: this.transformNode(node.column, queryId) + }); + } + transformRenameColumn(node, queryId) { + return requireAllProps({ + kind: "RenameColumnNode", + column: this.transformNode(node.column, queryId), + renameTo: this.transformNode(node.renameTo, queryId) + }); + } + transformAlterColumn(node, queryId) { + return requireAllProps({ + kind: "AlterColumnNode", + column: this.transformNode(node.column, queryId), + dataType: this.transformNode(node.dataType, queryId), + dataTypeExpression: this.transformNode(node.dataTypeExpression, queryId), + setDefault: this.transformNode(node.setDefault, queryId), + dropDefault: node.dropDefault, + setNotNull: node.setNotNull, + dropNotNull: node.dropNotNull + }); + } + transformModifyColumn(node, queryId) { + return requireAllProps({ + kind: "ModifyColumnNode", + column: this.transformNode(node.column, queryId) + }); + } + transformAddConstraint(node, queryId) { + return requireAllProps({ + kind: "AddConstraintNode", + constraint: this.transformNode(node.constraint, queryId) + }); + } + transformDropConstraint(node, queryId) { + return requireAllProps({ + kind: "DropConstraintNode", + constraintName: this.transformNode(node.constraintName, queryId), + ifExists: node.ifExists, + modifier: node.modifier + }); + } + transformRenameConstraint(node, queryId) { + return requireAllProps({ + kind: "RenameConstraintNode", + oldName: this.transformNode(node.oldName, queryId), + newName: this.transformNode(node.newName, queryId) + }); + } + transformCreateView(node, queryId) { + return requireAllProps({ + kind: "CreateViewNode", + name: this.transformNode(node.name, queryId), + temporary: node.temporary, + orReplace: node.orReplace, + ifNotExists: node.ifNotExists, + materialized: node.materialized, + columns: this.transformNodeList(node.columns, queryId), + as: this.transformNode(node.as, queryId) + }); + } + transformRefreshMaterializedView(node, queryId) { + return requireAllProps({ + kind: "RefreshMaterializedViewNode", + name: this.transformNode(node.name, queryId), + concurrently: node.concurrently, + withNoData: node.withNoData + }); + } + transformDropView(node, queryId) { + return requireAllProps({ + kind: "DropViewNode", + name: this.transformNode(node.name, queryId), + ifExists: node.ifExists, + materialized: node.materialized, + cascade: node.cascade + }); + } + transformGenerated(node, queryId) { + return requireAllProps({ + kind: "GeneratedNode", + byDefault: node.byDefault, + always: node.always, + identity: node.identity, + stored: node.stored, + expression: this.transformNode(node.expression, queryId) + }); + } + transformDefaultValue(node, queryId) { + return requireAllProps({ + kind: "DefaultValueNode", + defaultValue: this.transformNode(node.defaultValue, queryId) + }); + } + transformOn(node, queryId) { + return requireAllProps({ + kind: "OnNode", + on: this.transformNode(node.on, queryId) + }); + } + transformSelectModifier(node, queryId) { + return requireAllProps({ + kind: "SelectModifierNode", + modifier: node.modifier, + rawModifier: this.transformNode(node.rawModifier, queryId), + of: this.transformNodeList(node.of, queryId) + }); + } + transformCreateType(node, queryId) { + return requireAllProps({ + kind: "CreateTypeNode", + name: this.transformNode(node.name, queryId), + enum: this.transformNode(node.enum, queryId) + }); + } + transformDropType(node, queryId) { + return requireAllProps({ + kind: "DropTypeNode", + name: this.transformNode(node.name, queryId), + ifExists: node.ifExists + }); + } + transformExplain(node, queryId) { + return requireAllProps({ + kind: "ExplainNode", + format: node.format, + options: this.transformNode(node.options, queryId) + }); + } + transformSchemableIdentifier(node, queryId) { + return requireAllProps({ + kind: "SchemableIdentifierNode", + schema: this.transformNode(node.schema, queryId), + identifier: this.transformNode(node.identifier, queryId) + }); + } + transformAggregateFunction(node, queryId) { + return requireAllProps({ + kind: "AggregateFunctionNode", + func: node.func, + aggregated: this.transformNodeList(node.aggregated, queryId), + distinct: node.distinct, + orderBy: this.transformNode(node.orderBy, queryId), + withinGroup: this.transformNode(node.withinGroup, queryId), + filter: this.transformNode(node.filter, queryId), + over: this.transformNode(node.over, queryId) + }); + } + transformOver(node, queryId) { + return requireAllProps({ + kind: "OverNode", + orderBy: this.transformNode(node.orderBy, queryId), + partitionBy: this.transformNode(node.partitionBy, queryId) + }); + } + transformPartitionBy(node, queryId) { + return requireAllProps({ + kind: "PartitionByNode", + items: this.transformNodeList(node.items, queryId) + }); + } + transformPartitionByItem(node, queryId) { + return requireAllProps({ + kind: "PartitionByItemNode", + partitionBy: this.transformNode(node.partitionBy, queryId) + }); + } + transformBinaryOperation(node, queryId) { + return requireAllProps({ + kind: "BinaryOperationNode", + leftOperand: this.transformNode(node.leftOperand, queryId), + operator: this.transformNode(node.operator, queryId), + rightOperand: this.transformNode(node.rightOperand, queryId) + }); + } + transformUnaryOperation(node, queryId) { + return requireAllProps({ + kind: "UnaryOperationNode", + operator: this.transformNode(node.operator, queryId), + operand: this.transformNode(node.operand, queryId) + }); + } + transformUsing(node, queryId) { + return requireAllProps({ + kind: "UsingNode", + tables: this.transformNodeList(node.tables, queryId) + }); + } + transformFunction(node, queryId) { + return requireAllProps({ + kind: "FunctionNode", + func: node.func, + arguments: this.transformNodeList(node.arguments, queryId) + }); + } + transformCase(node, queryId) { + return requireAllProps({ + kind: "CaseNode", + value: this.transformNode(node.value, queryId), + when: this.transformNodeList(node.when, queryId), + else: this.transformNode(node.else, queryId), + isStatement: node.isStatement + }); + } + transformWhen(node, queryId) { + return requireAllProps({ + kind: "WhenNode", + condition: this.transformNode(node.condition, queryId), + result: this.transformNode(node.result, queryId) + }); + } + transformJSONReference(node, queryId) { + return requireAllProps({ + kind: "JSONReferenceNode", + reference: this.transformNode(node.reference, queryId), + traversal: this.transformNode(node.traversal, queryId) + }); + } + transformJSONPath(node, queryId) { + return requireAllProps({ + kind: "JSONPathNode", + inOperator: this.transformNode(node.inOperator, queryId), + pathLegs: this.transformNodeList(node.pathLegs, queryId) + }); + } + transformJSONPathLeg(node, _queryId) { + return requireAllProps({ + kind: "JSONPathLegNode", + type: node.type, + value: node.value + }); + } + transformJSONOperatorChain(node, queryId) { + return requireAllProps({ + kind: "JSONOperatorChainNode", + operator: this.transformNode(node.operator, queryId), + values: this.transformNodeList(node.values, queryId) + }); + } + transformTuple(node, queryId) { + return requireAllProps({ + kind: "TupleNode", + values: this.transformNodeList(node.values, queryId) + }); + } + transformMergeQuery(node, queryId) { + return requireAllProps({ + kind: "MergeQueryNode", + into: this.transformNode(node.into, queryId), + using: this.transformNode(node.using, queryId), + whens: this.transformNodeList(node.whens, queryId), + with: this.transformNode(node.with, queryId), + top: this.transformNode(node.top, queryId), + endModifiers: this.transformNodeList(node.endModifiers, queryId), + output: this.transformNode(node.output, queryId), + returning: this.transformNode(node.returning, queryId) + }); + } + transformMatched(node, _queryId) { + return requireAllProps({ + kind: "MatchedNode", + not: node.not, + bySource: node.bySource + }); + } + transformAddIndex(node, queryId) { + return requireAllProps({ + kind: "AddIndexNode", + name: this.transformNode(node.name, queryId), + columns: this.transformNodeList(node.columns, queryId), + unique: node.unique, + using: this.transformNode(node.using, queryId), + ifNotExists: node.ifNotExists + }); + } + transformCast(node, queryId) { + return requireAllProps({ + kind: "CastNode", + expression: this.transformNode(node.expression, queryId), + dataType: this.transformNode(node.dataType, queryId) + }); + } + transformFetch(node, queryId) { + return requireAllProps({ + kind: "FetchNode", + rowCount: this.transformNode(node.rowCount, queryId), + modifier: node.modifier + }); + } + transformTop(node, _queryId) { + return requireAllProps({ + kind: "TopNode", + expression: node.expression, + modifiers: node.modifiers + }); + } + transformOutput(node, queryId) { + return requireAllProps({ + kind: "OutputNode", + selections: this.transformNodeList(node.selections, queryId) + }); + } + transformDataType(node, _queryId) { + return node; + } + transformSelectAll(node, _queryId) { + return node; + } + transformIdentifier(node, _queryId) { + return node; + } + transformValue(node, _queryId) { + return node; + } + transformPrimitiveValueList(node, _queryId) { + return node; + } + transformOperator(node, _queryId) { + return node; + } + transformDefaultInsertValue(node, _queryId) { + return node; + } + transformOrAction(node, _queryId) { + return node; + } + transformCollate(node, _queryId) { + return node; + } + }; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/with-schema/with-schema-transformer.js +var ROOT_OPERATION_NODES, SCHEMALESS_FUNCTIONS, WithSchemaTransformer; +var init_with_schema_transformer = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/with-schema/with-schema-transformer.js"() { + init_alias_node(); + init_identifier_node(); + init_join_node(); + init_list_node(); + init_operation_node_transformer(); + init_schemable_identifier_node(); + init_table_node(); + init_using_node(); + init_object_utils(); + ROOT_OPERATION_NODES = freeze2({ + AlterTableNode: true, + CreateIndexNode: true, + CreateSchemaNode: true, + CreateTableNode: true, + CreateTypeNode: true, + CreateViewNode: true, + RefreshMaterializedViewNode: true, + DeleteQueryNode: true, + DropIndexNode: true, + DropSchemaNode: true, + DropTableNode: true, + DropTypeNode: true, + DropViewNode: true, + InsertQueryNode: true, + RawNode: true, + SelectQueryNode: true, + UpdateQueryNode: true, + MergeQueryNode: true + }); + SCHEMALESS_FUNCTIONS = { + json_agg: true, + to_json: true + }; + WithSchemaTransformer = class extends OperationNodeTransformer { + #schema; + #schemableIds = /* @__PURE__ */ new Set(); + #ctes = /* @__PURE__ */ new Set(); + constructor(schema2) { + super(); + this.#schema = schema2; + } + transformNodeImpl(node, queryId) { + if (!this.#isRootOperationNode(node)) { + return super.transformNodeImpl(node, queryId); + } + const ctes = this.#collectCTEs(node); + for (const cte of ctes) { + this.#ctes.add(cte); + } + const tables = this.#collectSchemableIds(node); + for (const table of tables) { + this.#schemableIds.add(table); + } + const transformed = super.transformNodeImpl(node, queryId); + for (const table of tables) { + this.#schemableIds.delete(table); + } + for (const cte of ctes) { + this.#ctes.delete(cte); + } + return transformed; + } + transformSchemableIdentifier(node, queryId) { + const transformed = super.transformSchemableIdentifier(node, queryId); + if (transformed.schema || !this.#schemableIds.has(node.identifier.name)) { + return transformed; + } + return { + ...transformed, + schema: IdentifierNode.create(this.#schema) + }; + } + transformReferences(node, queryId) { + const transformed = super.transformReferences(node, queryId); + if (transformed.table.table.schema) { + return transformed; + } + return { + ...transformed, + table: TableNode.createWithSchema(this.#schema, transformed.table.table.identifier.name) + }; + } + transformAggregateFunction(node, queryId) { + return { + ...super.transformAggregateFunction({ ...node, aggregated: [] }, queryId), + aggregated: this.#transformTableArgsWithoutSchemas(node, queryId, "aggregated") + }; + } + transformFunction(node, queryId) { + return { + ...super.transformFunction({ ...node, arguments: [] }, queryId), + arguments: this.#transformTableArgsWithoutSchemas(node, queryId, "arguments") + }; + } + transformSelectModifier(node, queryId) { + return { + ...super.transformSelectModifier({ ...node, of: void 0 }, queryId), + of: node.of?.map((item) => TableNode.is(item) && !item.table.schema ? { + ...item, + table: this.transformIdentifier(item.table.identifier, queryId) + } : this.transformNode(item, queryId)) + }; + } + #transformTableArgsWithoutSchemas(node, queryId, argsKey) { + return SCHEMALESS_FUNCTIONS[node.func] ? node[argsKey].map((arg) => !TableNode.is(arg) || arg.table.schema ? this.transformNode(arg, queryId) : { + ...arg, + table: this.transformIdentifier(arg.table.identifier, queryId) + }) : this.transformNodeList(node[argsKey], queryId); + } + #isRootOperationNode(node) { + return node.kind in ROOT_OPERATION_NODES; + } + #collectSchemableIds(node) { + const schemableIds = /* @__PURE__ */ new Set(); + if ("name" in node && node.name && SchemableIdentifierNode.is(node.name)) { + this.#collectSchemableId(node.name, schemableIds); + } + if ("from" in node && node.from) { + for (const from of node.from.froms) { + this.#collectSchemableIdsFromTableExpr(from, schemableIds); + } + } + if ("into" in node && node.into) { + this.#collectSchemableIdsFromTableExpr(node.into, schemableIds); + } + if ("table" in node && node.table) { + this.#collectSchemableIdsFromTableExpr(node.table, schemableIds); + } + if ("joins" in node && node.joins) { + for (const join4 of node.joins) { + this.#collectSchemableIdsFromTableExpr(join4.table, schemableIds); + } + } + if ("using" in node && node.using) { + if (JoinNode.is(node.using)) { + this.#collectSchemableIdsFromTableExpr(node.using.table, schemableIds); + } else { + this.#collectSchemableIdsFromTableExpr(node.using, schemableIds); + } + } + return schemableIds; + } + #collectCTEs(node) { + const ctes = /* @__PURE__ */ new Set(); + if ("with" in node && node.with) { + this.#collectCTEIds(node.with, ctes); + } + return ctes; + } + #collectSchemableIdsFromTableExpr(node, schemableIds) { + if (TableNode.is(node)) { + return this.#collectSchemableId(node.table, schemableIds); + } + if (AliasNode.is(node) && TableNode.is(node.node)) { + return this.#collectSchemableId(node.node.table, schemableIds); + } + if (ListNode.is(node)) { + for (const table of node.items) { + this.#collectSchemableIdsFromTableExpr(table, schemableIds); + } + return; + } + if (UsingNode.is(node)) { + for (const table of node.tables) { + this.#collectSchemableIdsFromTableExpr(table, schemableIds); + } + return; + } + } + #collectSchemableId(node, schemableIds) { + const id = node.identifier.name; + if (!this.#schemableIds.has(id) && !this.#ctes.has(id)) { + schemableIds.add(id); + } + } + #collectCTEIds(node, ctes) { + for (const expr of node.expressions) { + const cteId = expr.name.table.table.identifier.name; + if (!this.#ctes.has(cteId)) { + ctes.add(cteId); + } + } + } + }; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/with-schema/with-schema-plugin.js +var WithSchemaPlugin; +var init_with_schema_plugin = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/with-schema/with-schema-plugin.js"() { + init_with_schema_transformer(); + WithSchemaPlugin = class { + #transformer; + constructor(schema2) { + this.#transformer = new WithSchemaTransformer(schema2); + } + transformQuery(args) { + return this.#transformer.transformNode(args.node, args.queryId); + } + async transformResult(args) { + return args.result; + } + }; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/matched-node.js +var MatchedNode; +var init_matched_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/matched-node.js"() { + init_object_utils(); + MatchedNode = freeze2({ + is(node) { + return node.kind === "MatchedNode"; + }, + create(not2, bySource = false) { + return freeze2({ + kind: "MatchedNode", + not: not2, + bySource + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/merge-parser.js +function parseMergeWhen(type, args, refRight) { + return WhenNode.create(parseFilterList([ + MatchedNode.create(!type.isMatched, type.bySource), + ...args && args.length > 0 ? [ + args.length === 3 && refRight ? parseReferentialBinaryOperation(args[0], args[1], args[2]) : parseValueBinaryOperationOrExpression(args) + ] : [] + ], "and", false)); +} +function parseMergeThen(result) { + if (isString(result)) { + return RawNode.create([result], []); + } + if (isOperationNodeSource(result)) { + return result.toOperationNode(); + } + return result; +} +var init_merge_parser = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/merge-parser.js"() { + init_matched_node(); + init_operation_node_source(); + init_raw_node(); + init_when_node(); + init_object_utils(); + init_binary_operation_parser(); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/deferred.js +var Deferred; +var init_deferred = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/deferred.js"() { + Deferred = class { + #promise; + #resolve; + #reject; + constructor() { + this.#promise = new Promise((resolve4, reject) => { + this.#reject = reject; + this.#resolve = resolve4; + }); + } + get promise() { + return this.#promise; + } + resolve = (value) => { + if (this.#resolve) { + this.#resolve(value); + } + }; + reject = (reason) => { + if (this.#reject) { + this.#reject(reason); + } + }; + }; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/provide-controlled-connection.js +async function provideControlledConnection(connectionProvider) { + const connectionDefer = new Deferred(); + const connectionReleaseDefer = new Deferred(); + connectionProvider.provideConnection(async (connection2) => { + connectionDefer.resolve(connection2); + return await connectionReleaseDefer.promise; + }).catch((ex) => connectionDefer.reject(ex)); + return freeze2({ + connection: await connectionDefer.promise, + release: connectionReleaseDefer.resolve + }); +} +var init_provide_controlled_connection = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/provide-controlled-connection.js"() { + init_deferred(); + init_object_utils(); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-executor/query-executor-base.js +var NO_PLUGINS, QueryExecutorBase; +var init_query_executor_base = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-executor/query-executor-base.js"() { + init_object_utils(); + init_provide_controlled_connection(); + init_log_once(); + NO_PLUGINS = freeze2([]); + QueryExecutorBase = class { + #plugins; + constructor(plugins2 = NO_PLUGINS) { + this.#plugins = plugins2; + } + get plugins() { + return this.#plugins; + } + transformQuery(node, queryId) { + for (const plugin of this.#plugins) { + const transformedNode = plugin.transformQuery({ node, queryId }); + if (transformedNode.kind === node.kind) { + node = transformedNode; + } else { + throw new Error([ + `KyselyPlugin.transformQuery must return a node`, + `of the same kind that was given to it.`, + `The plugin was given a ${node.kind}`, + `but it returned a ${transformedNode.kind}` + ].join(" ")); + } + } + return node; + } + async executeQuery(compiledQuery) { + return await this.provideConnection(async (connection2) => { + const result = await connection2.executeQuery(compiledQuery); + if ("numUpdatedOrDeletedRows" in result) { + logOnce("kysely:warning: outdated driver/plugin detected! `QueryResult.numUpdatedOrDeletedRows` has been replaced with `QueryResult.numAffectedRows`."); + } + return await this.#transformResult(result, compiledQuery.queryId); + }); + } + async *stream(compiledQuery, chunkSize) { + const { connection: connection2, release } = await provideControlledConnection(this); + try { + for await (const result of connection2.streamQuery(compiledQuery, chunkSize)) { + yield await this.#transformResult(result, compiledQuery.queryId); + } + } finally { + release(); + } + } + async #transformResult(result, queryId) { + for (const plugin of this.#plugins) { + result = await plugin.transformResult({ result, queryId }); + } + return result; + } + }; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-executor/noop-query-executor.js +var NoopQueryExecutor, NOOP_QUERY_EXECUTOR; +var init_noop_query_executor = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-executor/noop-query-executor.js"() { + init_query_executor_base(); + NoopQueryExecutor = class _NoopQueryExecutor extends QueryExecutorBase { + get adapter() { + throw new Error("this query cannot be compiled to SQL"); + } + compileQuery() { + throw new Error("this query cannot be compiled to SQL"); + } + provideConnection() { + throw new Error("this query cannot be executed"); + } + withConnectionProvider() { + throw new Error("this query cannot have a connection provider"); + } + withPlugin(plugin) { + return new _NoopQueryExecutor([...this.plugins, plugin]); + } + withPlugins(plugins2) { + return new _NoopQueryExecutor([...this.plugins, ...plugins2]); + } + withPluginAtFront(plugin) { + return new _NoopQueryExecutor([plugin, ...this.plugins]); + } + withoutPlugins() { + return new _NoopQueryExecutor([]); + } + }; + NOOP_QUERY_EXECUTOR = new NoopQueryExecutor(); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/merge-result.js +var MergeResult; +var init_merge_result = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/merge-result.js"() { + MergeResult = class { + numChangedRows; + constructor(numChangedRows) { + this.numChangedRows = numChangedRows; + } + }; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/merge-query-builder.js +var MergeQueryBuilder, WheneableMergeQueryBuilder, MatchedThenableMergeQueryBuilder, NotMatchedThenableMergeQueryBuilder; +var init_merge_query_builder = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/merge-query-builder.js"() { + init_insert_query_node(); + init_merge_query_node(); + init_query_node(); + init_update_query_node(); + init_insert_values_parser(); + init_join_parser(); + init_merge_parser(); + init_select_parser(); + init_top_parser(); + init_noop_query_executor(); + init_object_utils(); + init_merge_result(); + init_no_result_error(); + init_update_query_builder(); + MergeQueryBuilder = class _MergeQueryBuilder { + #props; + constructor(props) { + this.#props = freeze2(props); + } + /** + * This can be used to add any additional SQL to the end of the query. + * + * ### Examples + * + * ```ts + * import { sql } from 'kysely' + * + * await db + * .mergeInto('person') + * .using('pet', 'pet.owner_id', 'person.id') + * .whenMatched() + * .thenDelete() + * .modifyEnd(sql.raw('-- this is a comment')) + * .execute() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * merge into "person" using "pet" on "pet"."owner_id" = "person"."id" when matched then delete -- this is a comment + * ``` + */ + modifyEnd(modifier) { + return new _MergeQueryBuilder({ + ...this.#props, + queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, modifier.toOperationNode()) + }); + } + /** + * Changes a `merge into` query to an `merge top into` query. + * + * `top` clause is only supported by some dialects like MS SQL Server. + * + * ### Examples + * + * Affect 5 matched rows at most: + * + * ```ts + * await db.mergeInto('person') + * .top(5) + * .using('pet', 'person.id', 'pet.owner_id') + * .whenMatched() + * .thenDelete() + * .execute() + * ``` + * + * The generated SQL (MS SQL Server): + * + * ```sql + * merge top(5) into "person" + * using "pet" on "person"."id" = "pet"."owner_id" + * when matched then + * delete + * ``` + * + * Affect 50% of matched rows: + * + * ```ts + * await db.mergeInto('person') + * .top(50, 'percent') + * .using('pet', 'person.id', 'pet.owner_id') + * .whenMatched() + * .thenDelete() + * .execute() + * ``` + * + * The generated SQL (MS SQL Server): + * + * ```sql + * merge top(50) percent into "person" + * using "pet" on "person"."id" = "pet"."owner_id" + * when matched then + * delete + * ``` + */ + top(expression, modifiers) { + return new _MergeQueryBuilder({ + ...this.#props, + queryNode: QueryNode.cloneWithTop(this.#props.queryNode, parseTop(expression, modifiers)) + }); + } + using(...args) { + return new WheneableMergeQueryBuilder({ + ...this.#props, + queryNode: MergeQueryNode.cloneWithUsing(this.#props.queryNode, parseJoin("Using", args)) + }); + } + returning(args) { + return new _MergeQueryBuilder({ + ...this.#props, + queryNode: QueryNode.cloneWithReturning(this.#props.queryNode, parseSelectArg(args)) + }); + } + returningAll(table) { + return new _MergeQueryBuilder({ + ...this.#props, + queryNode: QueryNode.cloneWithReturning(this.#props.queryNode, parseSelectAll(table)) + }); + } + output(args) { + return new _MergeQueryBuilder({ + ...this.#props, + queryNode: QueryNode.cloneWithOutput(this.#props.queryNode, parseSelectArg(args)) + }); + } + outputAll(table) { + return new _MergeQueryBuilder({ + ...this.#props, + queryNode: QueryNode.cloneWithOutput(this.#props.queryNode, parseSelectAll(table)) + }); + } + }; + WheneableMergeQueryBuilder = class _WheneableMergeQueryBuilder { + #props; + constructor(props) { + this.#props = freeze2(props); + } + /** + * This can be used to add any additional SQL to the end of the query. + * + * ### Examples + * + * ```ts + * import { sql } from 'kysely' + * + * await db + * .mergeInto('person') + * .using('pet', 'pet.owner_id', 'person.id') + * .whenMatched() + * .thenDelete() + * .modifyEnd(sql.raw('-- this is a comment')) + * .execute() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * merge into "person" using "pet" on "pet"."owner_id" = "person"."id" when matched then delete -- this is a comment + * ``` + */ + modifyEnd(modifier) { + return new _WheneableMergeQueryBuilder({ + ...this.#props, + queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, modifier.toOperationNode()) + }); + } + /** + * See {@link MergeQueryBuilder.top}. + */ + top(expression, modifiers) { + return new _WheneableMergeQueryBuilder({ + ...this.#props, + queryNode: QueryNode.cloneWithTop(this.#props.queryNode, parseTop(expression, modifiers)) + }); + } + /** + * Adds a simple `when matched` clause to the query. + * + * For a `when matched` clause with an `and` condition, see {@link whenMatchedAnd}. + * + * For a simple `when not matched` clause, see {@link whenNotMatched}. + * + * For a `when not matched` clause with an `and` condition, see {@link whenNotMatchedAnd}. + * + * ### Examples + * + * ```ts + * const result = await db.mergeInto('person') + * .using('pet', 'person.id', 'pet.owner_id') + * .whenMatched() + * .thenDelete() + * .execute() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * merge into "person" + * using "pet" on "person"."id" = "pet"."owner_id" + * when matched then + * delete + * ``` + */ + whenMatched() { + return this.#whenMatched([]); + } + whenMatchedAnd(...args) { + return this.#whenMatched(args); + } + /** + * Adds the `when matched` clause to the query with an `and` condition. But unlike + * {@link whenMatchedAnd}, this method accepts a column reference as the 3rd argument. + * + * This method is similar to {@link SelectQueryBuilder.whereRef}, so see the documentation + * for that method for more examples. + */ + whenMatchedAndRef(lhs, op2, rhs) { + return this.#whenMatched([lhs, op2, rhs], true); + } + #whenMatched(args, refRight) { + return new MatchedThenableMergeQueryBuilder({ + ...this.#props, + queryNode: MergeQueryNode.cloneWithWhen(this.#props.queryNode, parseMergeWhen({ isMatched: true }, args, refRight)) + }); + } + /** + * Adds a simple `when not matched` clause to the query. + * + * For a `when not matched` clause with an `and` condition, see {@link whenNotMatchedAnd}. + * + * For a simple `when matched` clause, see {@link whenMatched}. + * + * For a `when matched` clause with an `and` condition, see {@link whenMatchedAnd}. + * + * ### Examples + * + * ```ts + * const result = await db.mergeInto('person') + * .using('pet', 'person.id', 'pet.owner_id') + * .whenNotMatched() + * .thenInsertValues({ + * first_name: 'John', + * last_name: 'Doe', + * }) + * .execute() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * merge into "person" + * using "pet" on "person"."id" = "pet"."owner_id" + * when not matched then + * insert ("first_name", "last_name") values ($1, $2) + * ``` + */ + whenNotMatched() { + return this.#whenNotMatched([]); + } + whenNotMatchedAnd(...args) { + return this.#whenNotMatched(args); + } + /** + * Adds the `when not matched` clause to the query with an `and` condition. But unlike + * {@link whenNotMatchedAnd}, this method accepts a column reference as the 3rd argument. + * + * Unlike {@link whenMatchedAndRef}, you cannot reference columns from the target table. + * + * This method is similar to {@link SelectQueryBuilder.whereRef}, so see the documentation + * for that method for more examples. + */ + whenNotMatchedAndRef(lhs, op2, rhs) { + return this.#whenNotMatched([lhs, op2, rhs], true); + } + /** + * Adds a simple `when not matched by source` clause to the query. + * + * Supported in MS SQL Server. + * + * Similar to {@link whenNotMatched}, but returns a {@link MatchedThenableMergeQueryBuilder}. + */ + whenNotMatchedBySource() { + return this.#whenNotMatched([], false, true); + } + whenNotMatchedBySourceAnd(...args) { + return this.#whenNotMatched(args, false, true); + } + /** + * Adds the `when not matched by source` clause to the query with an `and` condition. + * + * Similar to {@link whenNotMatchedAndRef}, but you can reference columns from + * the target table, and not from source table and returns a {@link MatchedThenableMergeQueryBuilder}. + */ + whenNotMatchedBySourceAndRef(lhs, op2, rhs) { + return this.#whenNotMatched([lhs, op2, rhs], true, true); + } + returning(args) { + return new _WheneableMergeQueryBuilder({ + ...this.#props, + queryNode: QueryNode.cloneWithReturning(this.#props.queryNode, parseSelectArg(args)) + }); + } + returningAll(table) { + return new _WheneableMergeQueryBuilder({ + ...this.#props, + queryNode: QueryNode.cloneWithReturning(this.#props.queryNode, parseSelectAll(table)) + }); + } + output(args) { + return new _WheneableMergeQueryBuilder({ + ...this.#props, + queryNode: QueryNode.cloneWithOutput(this.#props.queryNode, parseSelectArg(args)) + }); + } + outputAll(table) { + return new _WheneableMergeQueryBuilder({ + ...this.#props, + queryNode: QueryNode.cloneWithOutput(this.#props.queryNode, parseSelectAll(table)) + }); + } + #whenNotMatched(args, refRight = false, bySource = false) { + const props = { + ...this.#props, + queryNode: MergeQueryNode.cloneWithWhen(this.#props.queryNode, parseMergeWhen({ isMatched: false, bySource }, args, refRight)) + }; + const Builder2 = bySource ? MatchedThenableMergeQueryBuilder : NotMatchedThenableMergeQueryBuilder; + return new Builder2(props); + } + /** + * Simply calls the provided function passing `this` as the only argument. `$call` returns + * what the provided function returns. + * + * If you want to conditionally call a method on `this`, see + * the {@link $if} method. + * + * ### Examples + * + * The next example uses a helper function `log` to log a query: + * + * ```ts + * import type { Compilable } from 'kysely' + * + * function log(qb: T): T { + * console.log(qb.compile()) + * return qb + * } + * + * await db.updateTable('person') + * .set({ first_name: 'John' }) + * .$call(log) + * .execute() + * ``` + */ + $call(func) { + return func(this); + } + /** + * Call `func(this)` if `condition` is true. + * + * This method is especially handy with optional selects. Any `returning` or `returningAll` + * method calls add columns as optional fields to the output type when called inside + * the `func` callback. This is because we can't know if those selections were actually + * made before running the code. + * + * You can also call any other methods inside the callback. + * + * ### Examples + * + * ```ts + * import type { PersonUpdate } from 'type-editor' // imaginary module + * + * async function updatePerson(id: number, updates: PersonUpdate, returnLastName: boolean) { + * return await db + * .updateTable('person') + * .set(updates) + * .where('id', '=', id) + * .returning(['id', 'first_name']) + * .$if(returnLastName, (qb) => qb.returning('last_name')) + * .executeTakeFirstOrThrow() + * } + * ``` + * + * Any selections added inside the `if` callback will be added as optional fields to the + * output type since we can't know if the selections were actually made before running + * the code. In the example above the return type of the `updatePerson` function is: + * + * ```ts + * Promise<{ + * id: number + * first_name: string + * last_name?: string + * }> + * ``` + */ + $if(condition, func) { + if (condition) { + return func(this); + } + return new _WheneableMergeQueryBuilder({ + ...this.#props + }); + } + toOperationNode() { + return this.#props.executor.transformQuery(this.#props.queryNode, this.#props.queryId); + } + compile() { + return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId); + } + /** + * Executes the query and returns an array of rows. + * + * Also see the {@link executeTakeFirst} and {@link executeTakeFirstOrThrow} methods. + */ + async execute() { + const compiledQuery = this.compile(); + const result = await this.#props.executor.executeQuery(compiledQuery); + const { adapter } = this.#props.executor; + const query = compiledQuery.query; + if (query.returning && adapter.supportsReturning || query.output && adapter.supportsOutput) { + return result.rows; + } + return [new MergeResult(result.numAffectedRows)]; + } + /** + * Executes the query and returns the first result or undefined if + * the query returned no result. + */ + async executeTakeFirst() { + const [result] = await this.execute(); + return result; + } + /** + * Executes the query and returns the first result or throws if + * the query returned no result. + * + * By default an instance of {@link NoResultError} is thrown, but you can + * provide a custom error class, or callback as the only argument to throw a different + * error. + */ + async executeTakeFirstOrThrow(errorConstructor = NoResultError) { + const result = await this.executeTakeFirst(); + if (result === void 0) { + const error50 = isNoResultErrorConstructor(errorConstructor) ? new errorConstructor(this.toOperationNode()) : errorConstructor(this.toOperationNode()); + throw error50; + } + return result; + } + }; + MatchedThenableMergeQueryBuilder = class { + #props; + constructor(props) { + this.#props = freeze2(props); + } + /** + * Performs the `delete` action. + * + * To perform the `do nothing` action, see {@link thenDoNothing}. + * + * To perform the `update` action, see {@link thenUpdate} or {@link thenUpdateSet}. + * + * ### Examples + * + * ```ts + * const result = await db.mergeInto('person') + * .using('pet', 'person.id', 'pet.owner_id') + * .whenMatched() + * .thenDelete() + * .execute() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * merge into "person" + * using "pet" on "person"."id" = "pet"."owner_id" + * when matched then + * delete + * ``` + */ + thenDelete() { + return new WheneableMergeQueryBuilder({ + ...this.#props, + queryNode: MergeQueryNode.cloneWithThen(this.#props.queryNode, parseMergeThen("delete")) + }); + } + /** + * Performs the `do nothing` action. + * + * This is supported in PostgreSQL. + * + * To perform the `delete` action, see {@link thenDelete}. + * + * To perform the `update` action, see {@link thenUpdate} or {@link thenUpdateSet}. + * + * ### Examples + * + * ```ts + * const result = await db.mergeInto('person') + * .using('pet', 'person.id', 'pet.owner_id') + * .whenMatched() + * .thenDoNothing() + * .execute() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * merge into "person" + * using "pet" on "person"."id" = "pet"."owner_id" + * when matched then + * do nothing + * ``` + */ + thenDoNothing() { + return new WheneableMergeQueryBuilder({ + ...this.#props, + queryNode: MergeQueryNode.cloneWithThen(this.#props.queryNode, parseMergeThen("do nothing")) + }); + } + /** + * Perform an `update` operation with a full-fledged {@link UpdateQueryBuilder}. + * This is handy when multiple `set` invocations are needed. + * + * For a shorthand version of this method, see {@link thenUpdateSet}. + * + * To perform the `delete` action, see {@link thenDelete}. + * + * To perform the `do nothing` action, see {@link thenDoNothing}. + * + * ### Examples + * + * ```ts + * import { sql } from 'kysely' + * + * const result = await db.mergeInto('person') + * .using('pet', 'person.id', 'pet.owner_id') + * .whenMatched() + * .thenUpdate((ub) => ub + * .set(sql`metadata['has_pets']`, 'Y') + * .set({ + * updated_at: new Date().toISOString(), + * }) + * ) + * .execute() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * merge into "person" + * using "pet" on "person"."id" = "pet"."owner_id" + * when matched then + * update set metadata['has_pets'] = $1, "updated_at" = $2 + * ``` + */ + thenUpdate(set2) { + return new WheneableMergeQueryBuilder({ + ...this.#props, + queryNode: MergeQueryNode.cloneWithThen(this.#props.queryNode, parseMergeThen(set2(new UpdateQueryBuilder({ + queryId: this.#props.queryId, + executor: NOOP_QUERY_EXECUTOR, + queryNode: UpdateQueryNode.createWithoutTable() + })))) + }); + } + thenUpdateSet(...args) { + return this.thenUpdate((ub) => ub.set(...args)); + } + }; + NotMatchedThenableMergeQueryBuilder = class { + #props; + constructor(props) { + this.#props = freeze2(props); + } + /** + * Performs the `do nothing` action. + * + * This is supported in PostgreSQL. + * + * To perform the `insert` action, see {@link thenInsertValues}. + * + * ### Examples + * + * ```ts + * const result = await db.mergeInto('person') + * .using('pet', 'person.id', 'pet.owner_id') + * .whenNotMatched() + * .thenDoNothing() + * .execute() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * merge into "person" + * using "pet" on "person"."id" = "pet"."owner_id" + * when not matched then + * do nothing + * ``` + */ + thenDoNothing() { + return new WheneableMergeQueryBuilder({ + ...this.#props, + queryNode: MergeQueryNode.cloneWithThen(this.#props.queryNode, parseMergeThen("do nothing")) + }); + } + thenInsertValues(insert) { + const [columns, values2] = parseInsertExpression(insert); + return new WheneableMergeQueryBuilder({ + ...this.#props, + queryNode: MergeQueryNode.cloneWithThen(this.#props.queryNode, parseMergeThen(InsertQueryNode.cloneWith(InsertQueryNode.createWithoutInto(), { + columns, + values: values2 + }))) + }); + } + }; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-creator.js +var QueryCreator; +var init_query_creator = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-creator.js"() { + init_select_query_builder(); + init_insert_query_builder(); + init_delete_query_builder(); + init_update_query_builder(); + init_delete_query_node(); + init_insert_query_node(); + init_select_query_node(); + init_update_query_node(); + init_table_parser(); + init_with_parser(); + init_with_node(); + init_query_id(); + init_with_schema_plugin(); + init_object_utils(); + init_select_parser(); + init_merge_query_builder(); + init_merge_query_node(); + QueryCreator = class _QueryCreator { + #props; + constructor(props) { + this.#props = freeze2(props); + } + /** + * Creates a `select` query builder for the given table or tables. + * + * The tables passed to this method are built as the query's `from` clause. + * + * ### Examples + * + * Create a select query for one table: + * + * ```ts + * db.selectFrom('person').selectAll() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * select * from "person" + * ``` + * + * Create a select query for one table with an alias: + * + * ```ts + * const persons = await db.selectFrom('person as p') + * .select(['p.id', 'first_name']) + * .execute() + * + * console.log(persons[0].id) + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * select "p"."id", "first_name" from "person" as "p" + * ``` + * + * Create a select query from a subquery: + * + * ```ts + * const persons = await db.selectFrom( + * (eb) => eb.selectFrom('person').select('person.id as identifier').as('p') + * ) + * .select('p.identifier') + * .execute() + * + * console.log(persons[0].identifier) + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * select "p"."identifier", + * from ( + * select "person"."id" as "identifier" from "person" + * ) as p + * ``` + * + * Create a select query from raw sql: + * + * ```ts + * import { sql } from 'kysely' + * + * const items = await db + * .selectFrom(sql<{ one: number }>`(select 1 as one)`.as('q')) + * .select('q.one') + * .execute() + * + * console.log(items[0].one) + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * select "q"."one", + * from ( + * select 1 as one + * ) as q + * ``` + * + * When you use the `sql` tag you need to also provide the result type of the + * raw snippet / query so that Kysely can figure out what columns are + * available for the rest of the query. + * + * The `selectFrom` method also accepts an array for multiple tables. All + * the above examples can also be used in an array. + * + * ```ts + * import { sql } from 'kysely' + * + * const items = await db.selectFrom([ + * 'person as p', + * db.selectFrom('pet').select('pet.species').as('a'), + * sql<{ one: number }>`(select 1 as one)`.as('q') + * ]) + * .select(['p.id', 'a.species', 'q.one']) + * .execute() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * select "p".id, "a"."species", "q"."one" + * from + * "person" as "p", + * (select "pet"."species" from "pet") as a, + * (select 1 as one) as "q" + * ``` + */ + selectFrom(from) { + return createSelectQueryBuilder({ + queryId: createQueryId(), + executor: this.#props.executor, + queryNode: SelectQueryNode.createFrom(parseTableExpressionOrList(from), this.#props.withNode) + }); + } + selectNoFrom(selection) { + return createSelectQueryBuilder({ + queryId: createQueryId(), + executor: this.#props.executor, + queryNode: SelectQueryNode.cloneWithSelections(SelectQueryNode.create(this.#props.withNode), parseSelectArg(selection)) + }); + } + /** + * Creates an insert query. + * + * The return value of this query is an instance of {@link InsertResult}. {@link InsertResult} + * has the {@link InsertResult.insertId | insertId} field that holds the auto incremented id of + * the inserted row if the db returned one. + * + * See the {@link InsertQueryBuilder.values | values} method for more info and examples. Also see + * the {@link ReturningInterface.returning | returning} method for a way to return columns + * on supported databases like PostgreSQL. + * + * ### Examples + * + * ```ts + * const result = await db + * .insertInto('person') + * .values({ + * first_name: 'Jennifer', + * last_name: 'Aniston' + * }) + * .executeTakeFirst() + * + * console.log(result.insertId) + * ``` + * + * Some databases like PostgreSQL support the `returning` method: + * + * ```ts + * const { id } = await db + * .insertInto('person') + * .values({ + * first_name: 'Jennifer', + * last_name: 'Aniston' + * }) + * .returning('id') + * .executeTakeFirstOrThrow() + * ``` + */ + insertInto(table) { + return new InsertQueryBuilder({ + queryId: createQueryId(), + executor: this.#props.executor, + queryNode: InsertQueryNode.create(parseTable(table), this.#props.withNode) + }); + } + /** + * Creates a "replace into" query. + * + * This is only supported by some dialects like MySQL or SQLite. + * + * Similar to MySQL's {@link InsertQueryBuilder.onDuplicateKeyUpdate} that deletes + * and inserts values on collision instead of updating existing rows. + * + * An alias of SQLite's {@link InsertQueryBuilder.orReplace}. + * + * The return value of this query is an instance of {@link InsertResult}. {@link InsertResult} + * has the {@link InsertResult.insertId | insertId} field that holds the auto incremented id of + * the inserted row if the db returned one. + * + * See the {@link InsertQueryBuilder.values | values} method for more info and examples. + * + * ### Examples + * + * ```ts + * const result = await db + * .replaceInto('person') + * .values({ + * first_name: 'Jennifer', + * last_name: 'Aniston' + * }) + * .executeTakeFirstOrThrow() + * + * console.log(result.insertId) + * ``` + * + * The generated SQL (MySQL): + * + * ```sql + * replace into `person` (`first_name`, `last_name`) values (?, ?) + * ``` + */ + replaceInto(table) { + return new InsertQueryBuilder({ + queryId: createQueryId(), + executor: this.#props.executor, + queryNode: InsertQueryNode.create(parseTable(table), this.#props.withNode, true) + }); + } + /** + * Creates a delete query. + * + * See the {@link DeleteQueryBuilder.where} method for examples on how to specify + * a where clause for the delete operation. + * + * The return value of the query is an instance of {@link DeleteResult}. + * + * ### Examples + * + * + * + * Delete a single row: + * + * ```ts + * const result = await db + * .deleteFrom('person') + * .where('person.id', '=', 1) + * .executeTakeFirst() + * + * console.log(result.numDeletedRows) + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * delete from "person" where "person"."id" = $1 + * ``` + * + * Some databases such as MySQL support deleting from multiple tables: + * + * ```ts + * const result = await db + * .deleteFrom(['person', 'pet']) + * .using('person') + * .innerJoin('pet', 'pet.owner_id', 'person.id') + * .where('person.id', '=', 1) + * .executeTakeFirst() + * ``` + * + * The generated SQL (MySQL): + * + * ```sql + * delete from `person`, `pet` + * using `person` + * inner join `pet` on `pet`.`owner_id` = `person`.`id` + * where `person`.`id` = ? + * ``` + */ + deleteFrom(from) { + return new DeleteQueryBuilder({ + queryId: createQueryId(), + executor: this.#props.executor, + queryNode: DeleteQueryNode.create(parseTableExpressionOrList(from), this.#props.withNode) + }); + } + /** + * Creates an update query. + * + * See the {@link UpdateQueryBuilder.where} method for examples on how to specify + * a where clause for the update operation. + * + * See the {@link UpdateQueryBuilder.set} method for examples on how to + * specify the updates. + * + * The return value of the query is an {@link UpdateResult}. + * + * ### Examples + * + * ```ts + * const result = await db + * .updateTable('person') + * .set({ first_name: 'Jennifer' }) + * .where('person.id', '=', 1) + * .executeTakeFirst() + * + * console.log(result.numUpdatedRows) + * ``` + */ + updateTable(tables) { + return new UpdateQueryBuilder({ + queryId: createQueryId(), + executor: this.#props.executor, + queryNode: UpdateQueryNode.create(parseTableExpressionOrList(tables), this.#props.withNode) + }); + } + /** + * Creates a merge query. + * + * The return value of the query is a {@link MergeResult}. + * + * See the {@link MergeQueryBuilder.using} method for examples on how to specify + * the other table. + * + * ### Examples + * + * + * + * Update a target column based on the existence of a source row: + * + * ```ts + * const result = await db + * .mergeInto('person as target') + * .using('pet as source', 'source.owner_id', 'target.id') + * .whenMatchedAnd('target.has_pets', '!=', 'Y') + * .thenUpdateSet({ has_pets: 'Y' }) + * .whenNotMatchedBySourceAnd('target.has_pets', '=', 'Y') + * .thenUpdateSet({ has_pets: 'N' }) + * .executeTakeFirstOrThrow() + * + * console.log(result.numChangedRows) + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * merge into "person" + * using "pet" + * on "pet"."owner_id" = "person"."id" + * when matched and "has_pets" != $1 + * then update set "has_pets" = $2 + * when not matched by source and "has_pets" = $3 + * then update set "has_pets" = $4 + * ``` + * + * + * + * Merge new entries from a temporary changes table: + * + * ```ts + * const result = await db + * .mergeInto('wine as target') + * .using( + * 'wine_stock_change as source', + * 'source.wine_name', + * 'target.name', + * ) + * .whenNotMatchedAnd('source.stock_delta', '>', 0) + * .thenInsertValues(({ ref }) => ({ + * name: ref('source.wine_name'), + * stock: ref('source.stock_delta'), + * })) + * .whenMatchedAnd( + * (eb) => eb('target.stock', '+', eb.ref('source.stock_delta')), + * '>', + * 0, + * ) + * .thenUpdateSet('stock', (eb) => + * eb('target.stock', '+', eb.ref('source.stock_delta')), + * ) + * .whenMatched() + * .thenDelete() + * .executeTakeFirstOrThrow() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * merge into "wine" as "target" + * using "wine_stock_change" as "source" + * on "source"."wine_name" = "target"."name" + * when not matched and "source"."stock_delta" > $1 + * then insert ("name", "stock") values ("source"."wine_name", "source"."stock_delta") + * when matched and "target"."stock" + "source"."stock_delta" > $2 + * then update set "stock" = "target"."stock" + "source"."stock_delta" + * when matched + * then delete + * ``` + */ + mergeInto(targetTable) { + return new MergeQueryBuilder({ + queryId: createQueryId(), + executor: this.#props.executor, + queryNode: MergeQueryNode.create(parseAliasedTable(targetTable), this.#props.withNode) + }); + } + /** + * Creates a `with` query (Common Table Expression). + * + * ### Examples + * + * + * + * Common table expressions (CTE) are a great way to modularize complex queries. + * Essentially they allow you to run multiple separate queries within a + * single roundtrip to the DB. + * + * Since CTEs are a part of the main query, query optimizers inside DB + * engines are able to optimize the overall query. For example, postgres + * is able to inline the CTEs inside the using queries if it decides it's + * faster. + * + * ```ts + * const result = await db + * // Create a CTE called `jennifers` that selects all + * // persons named 'Jennifer'. + * .with('jennifers', (db) => db + * .selectFrom('person') + * .where('first_name', '=', 'Jennifer') + * .select(['id', 'age']) + * ) + * // Select all rows from the `jennifers` CTE and + * // further filter it. + * .with('adult_jennifers', (db) => db + * .selectFrom('jennifers') + * .where('age', '>', 18) + * .select(['id', 'age']) + * ) + * // Finally select all adult jennifers that are + * // also younger than 60. + * .selectFrom('adult_jennifers') + * .where('age', '<', 60) + * .selectAll() + * .execute() + * ``` + * + * + * + * Some databases like postgres also allow you to run other queries than selects + * in CTEs. On these databases CTEs are extremely powerful: + * + * ```ts + * const result = await db + * .with('new_person', (db) => db + * .insertInto('person') + * .values({ + * first_name: 'Jennifer', + * age: 35, + * }) + * .returning('id') + * ) + * .with('new_pet', (db) => db + * .insertInto('pet') + * .values({ + * name: 'Doggo', + * species: 'dog', + * is_favorite: true, + * // Use the id of the person we just inserted. + * owner_id: db + * .selectFrom('new_person') + * .select('id') + * }) + * .returning('id') + * ) + * .selectFrom(['new_person', 'new_pet']) + * .select([ + * 'new_person.id as person_id', + * 'new_pet.id as pet_id' + * ]) + * .execute() + * ``` + * + * The CTE name can optionally specify column names in addition to + * a name. In that case Kysely requires the expression to retun + * rows with the same columns. + * + * ```ts + * await db + * .with('jennifers(id, age)', (db) => db + * .selectFrom('person') + * .where('first_name', '=', 'Jennifer') + * // This is ok since we return columns with the same + * // names as specified by `jennifers(id, age)`. + * .select(['id', 'age']) + * ) + * .selectFrom('jennifers') + * .selectAll() + * .execute() + * ``` + * + * The first argument can also be a callback. The callback is passed + * a `CTEBuilder` instance that can be used to configure the CTE: + * + * ```ts + * await db + * .with( + * (cte) => cte('jennifers').materialized(), + * (db) => db + * .selectFrom('person') + * .where('first_name', '=', 'Jennifer') + * .select(['id', 'age']) + * ) + * .selectFrom('jennifers') + * .selectAll() + * .execute() + * ``` + */ + with(nameOrBuilder, expression) { + const cte = parseCommonTableExpression(nameOrBuilder, expression); + return new _QueryCreator({ + ...this.#props, + withNode: this.#props.withNode ? WithNode.cloneWithExpression(this.#props.withNode, cte) : WithNode.create(cte) + }); + } + /** + * Creates a recursive `with` query (Common Table Expression). + * + * Note that recursiveness is a property of the whole `with` statement. + * You cannot have recursive and non-recursive CTEs in a same `with` statement. + * Therefore the recursiveness is determined by the **first** `with` or + * `withRecusive` call you make. + * + * See the {@link with} method for examples and more documentation. + */ + withRecursive(nameOrBuilder, expression) { + const cte = parseCommonTableExpression(nameOrBuilder, expression); + return new _QueryCreator({ + ...this.#props, + withNode: this.#props.withNode ? WithNode.cloneWithExpression(this.#props.withNode, cte) : WithNode.create(cte, { recursive: true }) + }); + } + /** + * Returns a copy of this query creator instance with the given plugin installed. + */ + withPlugin(plugin) { + return new _QueryCreator({ + ...this.#props, + executor: this.#props.executor.withPlugin(plugin) + }); + } + /** + * Returns a copy of this query creator instance without any plugins. + */ + withoutPlugins() { + return new _QueryCreator({ + ...this.#props, + executor: this.#props.executor.withoutPlugins() + }); + } + /** + * Sets the schema to be used for all table references that don't explicitly + * specify a schema. + * + * This only affects the query created through the builder returned from + * this method and doesn't modify the `db` instance. + * + * See [this recipe](https://github.com/kysely-org/kysely/blob/master/site/docs/recipes/0007-schemas.md) + * for a more detailed explanation. + * + * ### Examples + * + * ``` + * await db + * .withSchema('mammals') + * .selectFrom('pet') + * .selectAll() + * .innerJoin('public.person', 'public.person.id', 'pet.owner_id') + * .execute() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * select * from "mammals"."pet" + * inner join "public"."person" + * on "public"."person"."id" = "mammals"."pet"."owner_id" + * ``` + * + * `withSchema` is smart enough to not add schema for aliases, + * common table expressions or other places where the schema + * doesn't belong to: + * + * ``` + * await db + * .withSchema('mammals') + * .selectFrom('pet as p') + * .select('p.name') + * .execute() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * select "p"."name" from "mammals"."pet" as "p" + * ``` + */ + withSchema(schema2) { + return new _QueryCreator({ + ...this.#props, + executor: this.#props.executor.withPluginAtFront(new WithSchemaPlugin(schema2)) + }); + } + }; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/parse-utils.js +function createQueryCreator() { + return new QueryCreator({ + executor: NOOP_QUERY_EXECUTOR + }); +} +function createJoinBuilder(joinType, table) { + return new JoinBuilder({ + joinNode: JoinNode.create(joinType, parseTableExpression(table)) + }); +} +function createOverBuilder() { + return new OverBuilder({ + overNode: OverNode.create() + }); +} +var init_parse_utils2 = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/parse-utils.js"() { + init_join_node(); + init_over_node(); + init_join_builder(); + init_over_builder(); + init_query_creator(); + init_noop_query_executor(); + init_table_parser(); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/join-parser.js +function parseJoin(joinType, args) { + if (args.length === 3) { + return parseSingleOnJoin(joinType, args[0], args[1], args[2]); + } else if (args.length === 2) { + return parseCallbackJoin(joinType, args[0], args[1]); + } else if (args.length === 1) { + return parseOnlessJoin(joinType, args[0]); + } else { + throw new Error("not implemented"); + } +} +function parseCallbackJoin(joinType, from, callback) { + return callback(createJoinBuilder(joinType, from)).toOperationNode(); +} +function parseSingleOnJoin(joinType, from, lhsColumn, rhsColumn) { + return JoinNode.createWithOn(joinType, parseTableExpression(from), parseReferentialBinaryOperation(lhsColumn, "=", rhsColumn)); +} +function parseOnlessJoin(joinType, from) { + return JoinNode.create(joinType, parseTableExpression(from)); +} +var init_join_parser = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/join-parser.js"() { + init_join_node(); + init_binary_operation_parser(); + init_parse_utils2(); + init_table_parser(); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/offset-node.js +var OffsetNode; +var init_offset_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/offset-node.js"() { + init_object_utils(); + OffsetNode = freeze2({ + is(node) { + return node.kind === "OffsetNode"; + }, + create(offset) { + return freeze2({ + kind: "OffsetNode", + offset + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/group-by-item-node.js +var GroupByItemNode; +var init_group_by_item_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/group-by-item-node.js"() { + init_object_utils(); + GroupByItemNode = freeze2({ + is(node) { + return node.kind === "GroupByItemNode"; + }, + create(groupBy) { + return freeze2({ + kind: "GroupByItemNode", + groupBy + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/group-by-parser.js +function parseGroupBy(groupBy) { + groupBy = isFunction(groupBy) ? groupBy(expressionBuilder()) : groupBy; + return parseReferenceExpressionOrList(groupBy).map(GroupByItemNode.create); +} +var init_group_by_parser = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/group-by-parser.js"() { + init_group_by_item_node(); + init_expression_builder(); + init_object_utils(); + init_reference_parser(); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/set-operation-node.js +var SetOperationNode; +var init_set_operation_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/set-operation-node.js"() { + init_object_utils(); + SetOperationNode = freeze2({ + is(node) { + return node.kind === "SetOperationNode"; + }, + create(operator, expression, all) { + return freeze2({ + kind: "SetOperationNode", + operator, + expression, + all + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/set-operation-parser.js +function parseSetOperations(operator, expression, all) { + if (isFunction(expression)) { + expression = expression(createExpressionBuilder()); + } + if (!isReadonlyArray(expression)) { + expression = [expression]; + } + return expression.map((expr) => SetOperationNode.create(operator, parseExpression(expr), all)); +} +var init_set_operation_parser = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/set-operation-parser.js"() { + init_expression_builder(); + init_set_operation_node(); + init_object_utils(); + init_expression_parser(); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/expression/expression-wrapper.js +var ExpressionWrapper, AliasedExpressionWrapper, OrWrapper, AndWrapper; +var init_expression_wrapper = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/expression/expression-wrapper.js"() { + init_alias_node(); + init_and_node(); + init_identifier_node(); + init_operation_node_source(); + init_or_node(); + init_parens_node(); + init_binary_operation_parser(); + ExpressionWrapper = class _ExpressionWrapper { + #node; + constructor(node) { + this.#node = node; + } + /** @private */ + get expressionType() { + return void 0; + } + as(alias) { + return new AliasedExpressionWrapper(this, alias); + } + or(...args) { + return new OrWrapper(OrNode.create(this.#node, parseValueBinaryOperationOrExpression(args))); + } + and(...args) { + return new AndWrapper(AndNode.create(this.#node, parseValueBinaryOperationOrExpression(args))); + } + /** + * Change the output type of the expression. + * + * This method call doesn't change the SQL in any way. This methods simply + * returns a copy of this `ExpressionWrapper` with a new output type. + */ + $castTo() { + return new _ExpressionWrapper(this.#node); + } + /** + * Omit null from the expression's type. + * + * This function can be useful in cases where you know an expression can't be + * null, but Kysely is unable to infer it. + * + * This method call doesn't change the SQL in any way. This methods simply + * returns a copy of `this` with a new output type. + */ + $notNull() { + return new _ExpressionWrapper(this.#node); + } + toOperationNode() { + return this.#node; + } + }; + AliasedExpressionWrapper = class { + #expr; + #alias; + constructor(expr, alias) { + this.#expr = expr; + this.#alias = alias; + } + /** @private */ + get expression() { + return this.#expr; + } + /** @private */ + get alias() { + return this.#alias; + } + toOperationNode() { + return AliasNode.create(this.#expr.toOperationNode(), isOperationNodeSource(this.#alias) ? this.#alias.toOperationNode() : IdentifierNode.create(this.#alias)); + } + }; + OrWrapper = class _OrWrapper { + #node; + constructor(node) { + this.#node = node; + } + /** @private */ + get expressionType() { + return void 0; + } + as(alias) { + return new AliasedExpressionWrapper(this, alias); + } + or(...args) { + return new _OrWrapper(OrNode.create(this.#node, parseValueBinaryOperationOrExpression(args))); + } + /** + * Change the output type of the expression. + * + * This method call doesn't change the SQL in any way. This methods simply + * returns a copy of this `OrWrapper` with a new output type. + */ + $castTo() { + return new _OrWrapper(this.#node); + } + toOperationNode() { + return ParensNode.create(this.#node); + } + }; + AndWrapper = class _AndWrapper { + #node; + constructor(node) { + this.#node = node; + } + /** @private */ + get expressionType() { + return void 0; + } + as(alias) { + return new AliasedExpressionWrapper(this, alias); + } + and(...args) { + return new _AndWrapper(AndNode.create(this.#node, parseValueBinaryOperationOrExpression(args))); + } + /** + * Change the output type of the expression. + * + * This method call doesn't change the SQL in any way. This methods simply + * returns a copy of this `AndWrapper` with a new output type. + */ + $castTo() { + return new _AndWrapper(this.#node); + } + toOperationNode() { + return ParensNode.create(this.#node); + } + }; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/fetch-node.js +var FetchNode; +var init_fetch_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/fetch-node.js"() { + init_object_utils(); + init_value_node(); + FetchNode = freeze2({ + is(node) { + return node.kind === "FetchNode"; + }, + create(rowCount, modifier) { + return { + kind: "FetchNode", + rowCount: ValueNode.create(rowCount), + modifier + }; + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/fetch-parser.js +function parseFetch(rowCount, modifier) { + if (!isNumber(rowCount) && !isBigInt(rowCount)) { + throw new Error(`Invalid fetch row count: ${rowCount}`); + } + if (!isFetchModifier(modifier)) { + throw new Error(`Invalid fetch modifier: ${modifier}`); + } + return FetchNode.create(rowCount, modifier); +} +function isFetchModifier(value) { + return value === "only" || value === "with ties"; +} +var init_fetch_parser = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/fetch-parser.js"() { + init_fetch_node(); + init_object_utils(); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/select-query-builder.js +function createSelectQueryBuilder(props) { + return new SelectQueryBuilderImpl(props); +} +var _a5, SelectQueryBuilderImpl, AliasedSelectQueryBuilderImpl; +var init_select_query_builder = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/select-query-builder.js"() { + init_alias_node(); + init_select_modifier_node(); + init_join_parser(); + init_table_parser(); + init_select_parser(); + init_reference_parser(); + init_select_query_node(); + init_query_node(); + init_order_by_parser(); + init_limit_node(); + init_offset_node(); + init_object_utils(); + init_group_by_parser(); + init_no_result_error(); + init_identifier_node(); + init_set_operation_parser(); + init_binary_operation_parser(); + init_expression_wrapper(); + init_value_parser(); + init_fetch_parser(); + init_top_parser(); + SelectQueryBuilderImpl = class { + #props; + constructor(props) { + this.#props = freeze2(props); + } + get expressionType() { + return void 0; + } + get isSelectQueryBuilder() { + return true; + } + where(...args) { + return new _a5({ + ...this.#props, + queryNode: QueryNode.cloneWithWhere(this.#props.queryNode, parseValueBinaryOperationOrExpression(args)) + }); + } + whereRef(lhs, op2, rhs) { + return new _a5({ + ...this.#props, + queryNode: QueryNode.cloneWithWhere(this.#props.queryNode, parseReferentialBinaryOperation(lhs, op2, rhs)) + }); + } + having(...args) { + return new _a5({ + ...this.#props, + queryNode: SelectQueryNode.cloneWithHaving(this.#props.queryNode, parseValueBinaryOperationOrExpression(args)) + }); + } + havingRef(lhs, op2, rhs) { + return new _a5({ + ...this.#props, + queryNode: SelectQueryNode.cloneWithHaving(this.#props.queryNode, parseReferentialBinaryOperation(lhs, op2, rhs)) + }); + } + select(selection) { + return new _a5({ + ...this.#props, + queryNode: SelectQueryNode.cloneWithSelections(this.#props.queryNode, parseSelectArg(selection)) + }); + } + distinctOn(selection) { + return new _a5({ + ...this.#props, + queryNode: SelectQueryNode.cloneWithDistinctOn(this.#props.queryNode, parseReferenceExpressionOrList(selection)) + }); + } + modifyFront(modifier) { + return new _a5({ + ...this.#props, + queryNode: SelectQueryNode.cloneWithFrontModifier(this.#props.queryNode, SelectModifierNode.createWithExpression(modifier.toOperationNode())) + }); + } + modifyEnd(modifier) { + return new _a5({ + ...this.#props, + queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, SelectModifierNode.createWithExpression(modifier.toOperationNode())) + }); + } + distinct() { + return new _a5({ + ...this.#props, + queryNode: SelectQueryNode.cloneWithFrontModifier(this.#props.queryNode, SelectModifierNode.create("Distinct")) + }); + } + forUpdate(of) { + return new _a5({ + ...this.#props, + queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, SelectModifierNode.create("ForUpdate", of ? asArray(of).map(parseTable) : void 0)) + }); + } + forShare(of) { + return new _a5({ + ...this.#props, + queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, SelectModifierNode.create("ForShare", of ? asArray(of).map(parseTable) : void 0)) + }); + } + forKeyShare(of) { + return new _a5({ + ...this.#props, + queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, SelectModifierNode.create("ForKeyShare", of ? asArray(of).map(parseTable) : void 0)) + }); + } + forNoKeyUpdate(of) { + return new _a5({ + ...this.#props, + queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, SelectModifierNode.create("ForNoKeyUpdate", of ? asArray(of).map(parseTable) : void 0)) + }); + } + skipLocked() { + return new _a5({ + ...this.#props, + queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, SelectModifierNode.create("SkipLocked")) + }); + } + noWait() { + return new _a5({ + ...this.#props, + queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, SelectModifierNode.create("NoWait")) + }); + } + selectAll(table) { + return new _a5({ + ...this.#props, + queryNode: SelectQueryNode.cloneWithSelections(this.#props.queryNode, parseSelectAll(table)) + }); + } + innerJoin(...args) { + return this.#join("InnerJoin", args); + } + leftJoin(...args) { + return this.#join("LeftJoin", args); + } + rightJoin(...args) { + return this.#join("RightJoin", args); + } + fullJoin(...args) { + return this.#join("FullJoin", args); + } + crossJoin(...args) { + return this.#join("CrossJoin", args); + } + innerJoinLateral(...args) { + return this.#join("LateralInnerJoin", args); + } + leftJoinLateral(...args) { + return this.#join("LateralLeftJoin", args); + } + crossJoinLateral(...args) { + return this.#join("LateralCrossJoin", args); + } + crossApply(...args) { + return this.#join("CrossApply", args); + } + outerApply(...args) { + return this.#join("OuterApply", args); + } + #join(joinType, args) { + return new _a5({ + ...this.#props, + queryNode: QueryNode.cloneWithJoin(this.#props.queryNode, parseJoin(joinType, args)) + }); + } + orderBy(...args) { + return new _a5({ + ...this.#props, + queryNode: QueryNode.cloneWithOrderByItems(this.#props.queryNode, parseOrderBy(args)) + }); + } + groupBy(groupBy) { + return new _a5({ + ...this.#props, + queryNode: SelectQueryNode.cloneWithGroupByItems(this.#props.queryNode, parseGroupBy(groupBy)) + }); + } + limit(limit) { + return new _a5({ + ...this.#props, + queryNode: SelectQueryNode.cloneWithLimit(this.#props.queryNode, LimitNode.create(parseValueExpression(limit))) + }); + } + offset(offset) { + return new _a5({ + ...this.#props, + queryNode: SelectQueryNode.cloneWithOffset(this.#props.queryNode, OffsetNode.create(parseValueExpression(offset))) + }); + } + fetch(rowCount, modifier = "only") { + return new _a5({ + ...this.#props, + queryNode: SelectQueryNode.cloneWithFetch(this.#props.queryNode, parseFetch(rowCount, modifier)) + }); + } + top(expression, modifiers) { + return new _a5({ + ...this.#props, + queryNode: QueryNode.cloneWithTop(this.#props.queryNode, parseTop(expression, modifiers)) + }); + } + union(expression) { + return new _a5({ + ...this.#props, + queryNode: SelectQueryNode.cloneWithSetOperations(this.#props.queryNode, parseSetOperations("union", expression, false)) + }); + } + unionAll(expression) { + return new _a5({ + ...this.#props, + queryNode: SelectQueryNode.cloneWithSetOperations(this.#props.queryNode, parseSetOperations("union", expression, true)) + }); + } + intersect(expression) { + return new _a5({ + ...this.#props, + queryNode: SelectQueryNode.cloneWithSetOperations(this.#props.queryNode, parseSetOperations("intersect", expression, false)) + }); + } + intersectAll(expression) { + return new _a5({ + ...this.#props, + queryNode: SelectQueryNode.cloneWithSetOperations(this.#props.queryNode, parseSetOperations("intersect", expression, true)) + }); + } + except(expression) { + return new _a5({ + ...this.#props, + queryNode: SelectQueryNode.cloneWithSetOperations(this.#props.queryNode, parseSetOperations("except", expression, false)) + }); + } + exceptAll(expression) { + return new _a5({ + ...this.#props, + queryNode: SelectQueryNode.cloneWithSetOperations(this.#props.queryNode, parseSetOperations("except", expression, true)) + }); + } + as(alias) { + return new AliasedSelectQueryBuilderImpl(this, alias); + } + clearSelect() { + return new _a5({ + ...this.#props, + queryNode: SelectQueryNode.cloneWithoutSelections(this.#props.queryNode) + }); + } + clearWhere() { + return new _a5({ + ...this.#props, + queryNode: QueryNode.cloneWithoutWhere(this.#props.queryNode) + }); + } + clearLimit() { + return new _a5({ + ...this.#props, + queryNode: SelectQueryNode.cloneWithoutLimit(this.#props.queryNode) + }); + } + clearOffset() { + return new _a5({ + ...this.#props, + queryNode: SelectQueryNode.cloneWithoutOffset(this.#props.queryNode) + }); + } + clearOrderBy() { + return new _a5({ + ...this.#props, + queryNode: QueryNode.cloneWithoutOrderBy(this.#props.queryNode) + }); + } + clearGroupBy() { + return new _a5({ + ...this.#props, + queryNode: SelectQueryNode.cloneWithoutGroupBy(this.#props.queryNode) + }); + } + $call(func) { + return func(this); + } + $if(condition, func) { + if (condition) { + return func(this); + } + return new _a5({ + ...this.#props + }); + } + $castTo() { + return new _a5(this.#props); + } + $narrowType() { + return new _a5(this.#props); + } + $assertType() { + return new _a5(this.#props); + } + $asTuple() { + return new ExpressionWrapper(this.toOperationNode()); + } + $asScalar() { + return new ExpressionWrapper(this.toOperationNode()); + } + withPlugin(plugin) { + return new _a5({ + ...this.#props, + executor: this.#props.executor.withPlugin(plugin) + }); + } + toOperationNode() { + return this.#props.executor.transformQuery(this.#props.queryNode, this.#props.queryId); + } + compile() { + return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId); + } + async execute() { + const compiledQuery = this.compile(); + const result = await this.#props.executor.executeQuery(compiledQuery); + return result.rows; + } + async executeTakeFirst() { + const [result] = await this.execute(); + return result; + } + async executeTakeFirstOrThrow(errorConstructor = NoResultError) { + const result = await this.executeTakeFirst(); + if (result === void 0) { + const error50 = isNoResultErrorConstructor(errorConstructor) ? new errorConstructor(this.toOperationNode()) : errorConstructor(this.toOperationNode()); + throw error50; + } + return result; + } + async *stream(chunkSize = 100) { + const compiledQuery = this.compile(); + const stream = this.#props.executor.stream(compiledQuery, chunkSize); + for await (const item of stream) { + yield* item.rows; + } + } + async explain(format2, options) { + const builder = new _a5({ + ...this.#props, + queryNode: QueryNode.cloneWithExplain(this.#props.queryNode, format2, options) + }); + return await builder.execute(); + } + }; + _a5 = SelectQueryBuilderImpl; + AliasedSelectQueryBuilderImpl = class { + #queryBuilder; + #alias; + constructor(queryBuilder, alias) { + this.#queryBuilder = queryBuilder; + this.#alias = alias; + } + get expression() { + return this.#queryBuilder; + } + get alias() { + return this.#alias; + } + get isAliasedSelectQueryBuilder() { + return true; + } + toOperationNode() { + return AliasNode.create(this.#queryBuilder.toOperationNode(), IdentifierNode.create(this.#alias)); + } + }; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/aggregate-function-node.js +var AggregateFunctionNode; +var init_aggregate_function_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/aggregate-function-node.js"() { + init_object_utils(); + init_where_node(); + init_order_by_node(); + AggregateFunctionNode = freeze2({ + is(node) { + return node.kind === "AggregateFunctionNode"; + }, + create(aggregateFunction, aggregated = []) { + return freeze2({ + kind: "AggregateFunctionNode", + func: aggregateFunction, + aggregated + }); + }, + cloneWithDistinct(aggregateFunctionNode) { + return freeze2({ + ...aggregateFunctionNode, + distinct: true + }); + }, + cloneWithOrderBy(aggregateFunctionNode, orderItems, withinGroup = false) { + const prop = withinGroup ? "withinGroup" : "orderBy"; + return freeze2({ + ...aggregateFunctionNode, + [prop]: aggregateFunctionNode[prop] ? OrderByNode.cloneWithItems(aggregateFunctionNode[prop], orderItems) : OrderByNode.create(orderItems) + }); + }, + cloneWithFilter(aggregateFunctionNode, filter) { + return freeze2({ + ...aggregateFunctionNode, + filter: aggregateFunctionNode.filter ? WhereNode.cloneWithOperation(aggregateFunctionNode.filter, "And", filter) : WhereNode.create(filter) + }); + }, + cloneWithOrFilter(aggregateFunctionNode, filter) { + return freeze2({ + ...aggregateFunctionNode, + filter: aggregateFunctionNode.filter ? WhereNode.cloneWithOperation(aggregateFunctionNode.filter, "Or", filter) : WhereNode.create(filter) + }); + }, + cloneWithOver(aggregateFunctionNode, over) { + return freeze2({ + ...aggregateFunctionNode, + over + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/function-node.js +var FunctionNode; +var init_function_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/function-node.js"() { + init_object_utils(); + FunctionNode = freeze2({ + is(node) { + return node.kind === "FunctionNode"; + }, + create(func, args) { + return freeze2({ + kind: "FunctionNode", + func, + arguments: args + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/aggregate-function-builder.js +var AggregateFunctionBuilder, AliasedAggregateFunctionBuilder; +var init_aggregate_function_builder = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/aggregate-function-builder.js"() { + init_object_utils(); + init_aggregate_function_node(); + init_alias_node(); + init_identifier_node(); + init_parse_utils2(); + init_binary_operation_parser(); + init_order_by_parser(); + init_query_node(); + AggregateFunctionBuilder = class _AggregateFunctionBuilder { + #props; + constructor(props) { + this.#props = freeze2(props); + } + /** @private */ + get expressionType() { + return void 0; + } + /** + * Returns an aliased version of the function. + * + * In addition to slapping `as "the_alias"` to the end of the SQL, + * this method also provides strict typing: + * + * ```ts + * const result = await db + * .selectFrom('person') + * .select( + * (eb) => eb.fn.count('id').as('person_count') + * ) + * .executeTakeFirstOrThrow() + * + * // `person_count: number` field exists in the result type. + * console.log(result.person_count) + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * select count("id") as "person_count" + * from "person" + * ``` + */ + as(alias) { + return new AliasedAggregateFunctionBuilder(this, alias); + } + /** + * Adds a `distinct` clause inside the function. + * + * ### Examples + * + * ```ts + * const result = await db + * .selectFrom('person') + * .select((eb) => + * eb.fn.count('first_name').distinct().as('first_name_count') + * ) + * .executeTakeFirstOrThrow() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * select count(distinct "first_name") as "first_name_count" + * from "person" + * ``` + */ + distinct() { + return new _AggregateFunctionBuilder({ + ...this.#props, + aggregateFunctionNode: AggregateFunctionNode.cloneWithDistinct(this.#props.aggregateFunctionNode) + }); + } + orderBy(...args) { + return new _AggregateFunctionBuilder({ + ...this.#props, + aggregateFunctionNode: QueryNode.cloneWithOrderByItems(this.#props.aggregateFunctionNode, parseOrderBy(args)) + }); + } + clearOrderBy() { + return new _AggregateFunctionBuilder({ + ...this.#props, + aggregateFunctionNode: QueryNode.cloneWithoutOrderBy(this.#props.aggregateFunctionNode) + }); + } + withinGroupOrderBy(...args) { + return new _AggregateFunctionBuilder({ + ...this.#props, + aggregateFunctionNode: AggregateFunctionNode.cloneWithOrderBy(this.#props.aggregateFunctionNode, parseOrderBy(args), true) + }); + } + filterWhere(...args) { + return new _AggregateFunctionBuilder({ + ...this.#props, + aggregateFunctionNode: AggregateFunctionNode.cloneWithFilter(this.#props.aggregateFunctionNode, parseValueBinaryOperationOrExpression(args)) + }); + } + /** + * Adds a `filter` clause with a nested `where` clause after the function, where + * both sides of the operator are references to columns. + * + * Similar to {@link WhereInterface}'s `whereRef` method. + * + * ### Examples + * + * Count people with same first and last names versus general public: + * + * ```ts + * const result = await db + * .selectFrom('person') + * .select((eb) => [ + * eb.fn + * .count('id') + * .filterWhereRef('first_name', '=', 'last_name') + * .as('repeat_name_count'), + * eb.fn.count('id').as('total_count'), + * ]) + * .executeTakeFirstOrThrow() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * select + * count("id") filter(where "first_name" = "last_name") as "repeat_name_count", + * count("id") as "total_count" + * from "person" + * ``` + */ + filterWhereRef(lhs, op2, rhs) { + return new _AggregateFunctionBuilder({ + ...this.#props, + aggregateFunctionNode: AggregateFunctionNode.cloneWithFilter(this.#props.aggregateFunctionNode, parseReferentialBinaryOperation(lhs, op2, rhs)) + }); + } + /** + * Adds an `over` clause (window functions) after the function. + * + * ### Examples + * + * ```ts + * const result = await db + * .selectFrom('person') + * .select( + * (eb) => eb.fn.avg('age').over().as('average_age') + * ) + * .execute() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * select avg("age") over() as "average_age" + * from "person" + * ``` + * + * Also supports passing a callback that returns an over builder, + * allowing to add partition by and sort by clauses inside over. + * + * ```ts + * const result = await db + * .selectFrom('person') + * .select( + * (eb) => eb.fn.avg('age').over( + * ob => ob.partitionBy('last_name').orderBy('first_name', 'asc') + * ).as('average_age') + * ) + * .execute() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * select avg("age") over(partition by "last_name" order by "first_name" asc) as "average_age" + * from "person" + * ``` + */ + over(over) { + const builder = createOverBuilder(); + return new _AggregateFunctionBuilder({ + ...this.#props, + aggregateFunctionNode: AggregateFunctionNode.cloneWithOver(this.#props.aggregateFunctionNode, (over ? over(builder) : builder).toOperationNode()) + }); + } + /** + * Simply calls the provided function passing `this` as the only argument. `$call` returns + * what the provided function returns. + */ + $call(func) { + return func(this); + } + /** + * Casts the expression to the given type. + * + * This method call doesn't change the SQL in any way. This methods simply + * returns a copy of this `AggregateFunctionBuilder` with a new output type. + */ + $castTo() { + return new _AggregateFunctionBuilder(this.#props); + } + /** + * Omit null from the expression's type. + * + * This function can be useful in cases where you know an expression can't be + * null, but Kysely is unable to infer it. + * + * This method call doesn't change the SQL in any way. This methods simply + * returns a copy of `this` with a new output type. + */ + $notNull() { + return new _AggregateFunctionBuilder(this.#props); + } + toOperationNode() { + return this.#props.aggregateFunctionNode; + } + }; + AliasedAggregateFunctionBuilder = class { + #aggregateFunctionBuilder; + #alias; + constructor(aggregateFunctionBuilder, alias) { + this.#aggregateFunctionBuilder = aggregateFunctionBuilder; + this.#alias = alias; + } + /** @private */ + get expression() { + return this.#aggregateFunctionBuilder; + } + /** @private */ + get alias() { + return this.#alias; + } + toOperationNode() { + return AliasNode.create(this.#aggregateFunctionBuilder.toOperationNode(), IdentifierNode.create(this.#alias)); + } + }; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/function-module.js +function createFunctionModule() { + const fn = (name, args) => { + return new ExpressionWrapper(FunctionNode.create(name, parseReferenceExpressionOrList(args ?? []))); + }; + const agg = (name, args) => { + return new AggregateFunctionBuilder({ + aggregateFunctionNode: AggregateFunctionNode.create(name, args ? parseReferenceExpressionOrList(args) : void 0) + }); + }; + return Object.assign(fn, { + agg, + avg(column) { + return agg("avg", [column]); + }, + coalesce(...values2) { + return fn("coalesce", values2); + }, + count(column) { + return agg("count", [column]); + }, + countAll(table) { + return new AggregateFunctionBuilder({ + aggregateFunctionNode: AggregateFunctionNode.create("count", parseSelectAll(table)) + }); + }, + max(column) { + return agg("max", [column]); + }, + min(column) { + return agg("min", [column]); + }, + sum(column) { + return agg("sum", [column]); + }, + any(column) { + return fn("any", [column]); + }, + jsonAgg(table) { + return new AggregateFunctionBuilder({ + aggregateFunctionNode: AggregateFunctionNode.create("json_agg", [ + isString(table) ? parseTable(table) : table.toOperationNode() + ]) + }); + }, + toJson(table) { + return new ExpressionWrapper(FunctionNode.create("to_json", [ + isString(table) ? parseTable(table) : table.toOperationNode() + ])); + } + }); +} +var init_function_module = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/function-module.js"() { + init_expression_wrapper(); + init_aggregate_function_node(); + init_function_node(); + init_reference_parser(); + init_select_parser(); + init_aggregate_function_builder(); + init_object_utils(); + init_table_parser(); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/unary-operation-node.js +var UnaryOperationNode; +var init_unary_operation_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/unary-operation-node.js"() { + init_object_utils(); + UnaryOperationNode = freeze2({ + is(node) { + return node.kind === "UnaryOperationNode"; + }, + create(operator, operand) { + return freeze2({ + kind: "UnaryOperationNode", + operator, + operand + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/unary-operation-parser.js +function parseUnaryOperation(operator, operand) { + return UnaryOperationNode.create(OperatorNode.create(operator), parseReferenceExpression(operand)); +} +var init_unary_operation_parser = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/unary-operation-parser.js"() { + init_operator_node(); + init_unary_operation_node(); + init_reference_parser(); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/case-node.js +var CaseNode; +var init_case_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/case-node.js"() { + init_object_utils(); + init_when_node(); + CaseNode = freeze2({ + is(node) { + return node.kind === "CaseNode"; + }, + create(value) { + return freeze2({ + kind: "CaseNode", + value + }); + }, + cloneWithWhen(caseNode, when) { + return freeze2({ + ...caseNode, + when: freeze2(caseNode.when ? [...caseNode.when, when] : [when]) + }); + }, + cloneWithThen(caseNode, then) { + return freeze2({ + ...caseNode, + when: caseNode.when ? freeze2([ + ...caseNode.when.slice(0, -1), + WhenNode.cloneWithResult(caseNode.when[caseNode.when.length - 1], then) + ]) : void 0 + }); + }, + cloneWith(caseNode, props) { + return freeze2({ + ...caseNode, + ...props + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/case-builder.js +var CaseBuilder, CaseThenBuilder, CaseWhenBuilder, CaseEndBuilder; +var init_case_builder = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/case-builder.js"() { + init_expression_wrapper(); + init_object_utils(); + init_case_node(); + init_when_node(); + init_binary_operation_parser(); + init_value_parser(); + CaseBuilder = class { + #props; + constructor(props) { + this.#props = freeze2(props); + } + when(...args) { + return new CaseThenBuilder({ + ...this.#props, + node: CaseNode.cloneWithWhen(this.#props.node, WhenNode.create(parseValueBinaryOperationOrExpression(args))) + }); + } + }; + CaseThenBuilder = class { + #props; + constructor(props) { + this.#props = freeze2(props); + } + then(valueExpression) { + return new CaseWhenBuilder({ + ...this.#props, + node: CaseNode.cloneWithThen(this.#props.node, isSafeImmediateValue(valueExpression) ? parseSafeImmediateValue(valueExpression) : parseValueExpression(valueExpression)) + }); + } + }; + CaseWhenBuilder = class { + #props; + constructor(props) { + this.#props = freeze2(props); + } + when(...args) { + return new CaseThenBuilder({ + ...this.#props, + node: CaseNode.cloneWithWhen(this.#props.node, WhenNode.create(parseValueBinaryOperationOrExpression(args))) + }); + } + else(valueExpression) { + return new CaseEndBuilder({ + ...this.#props, + node: CaseNode.cloneWith(this.#props.node, { + else: isSafeImmediateValue(valueExpression) ? parseSafeImmediateValue(valueExpression) : parseValueExpression(valueExpression) + }) + }); + } + end() { + return new ExpressionWrapper(CaseNode.cloneWith(this.#props.node, { isStatement: false })); + } + endCase() { + return new ExpressionWrapper(CaseNode.cloneWith(this.#props.node, { isStatement: true })); + } + }; + CaseEndBuilder = class { + #props; + constructor(props) { + this.#props = freeze2(props); + } + end() { + return new ExpressionWrapper(CaseNode.cloneWith(this.#props.node, { isStatement: false })); + } + endCase() { + return new ExpressionWrapper(CaseNode.cloneWith(this.#props.node, { isStatement: true })); + } + }; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/json-path-leg-node.js +var JSONPathLegNode; +var init_json_path_leg_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/json-path-leg-node.js"() { + init_object_utils(); + JSONPathLegNode = freeze2({ + is(node) { + return node.kind === "JSONPathLegNode"; + }, + create(type, value) { + return freeze2({ + kind: "JSONPathLegNode", + type, + value + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/json-path-builder.js +var JSONPathBuilder, TraversedJSONPathBuilder, AliasedJSONPathBuilder; +var init_json_path_builder = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/json-path-builder.js"() { + init_alias_node(); + init_identifier_node(); + init_json_operator_chain_node(); + init_json_path_leg_node(); + init_json_path_node(); + init_json_reference_node(); + init_operation_node_source(); + init_value_node(); + JSONPathBuilder = class { + #node; + constructor(node) { + this.#node = node; + } + /** + * Access an element of a JSON array in a specific location. + * + * Since there's no guarantee an element exists in the given array location, the + * resulting type is always nullable. If you're sure the element exists, you + * should use {@link SelectQueryBuilder.$assertType} to narrow the type safely. + * + * See also {@link key} to access properties of JSON objects. + * + * ### Examples + * + * ```ts + * await db.selectFrom('person') + * .select(eb => + * eb.ref('nicknames', '->').at(0).as('primary_nickname') + * ) + * .execute() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * select "nicknames"->0 as "primary_nickname" from "person" + *``` + * + * Combined with {@link key}: + * + * ```ts + * db.selectFrom('person').select(eb => + * eb.ref('experience', '->').at(0).key('role').as('first_role') + * ) + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * select "experience"->0->'role' as "first_role" from "person" + * ``` + * + * You can use `'last'` to access the last element of the array in MySQL: + * + * ```ts + * db.selectFrom('person').select(eb => + * eb.ref('nicknames', '->$').at('last').as('last_nickname') + * ) + * ``` + * + * The generated SQL (MySQL): + * + * ```sql + * select `nicknames`->'$[last]' as `last_nickname` from `person` + * ``` + * + * Or `'#-1'` in SQLite: + * + * ```ts + * db.selectFrom('person').select(eb => + * eb.ref('nicknames', '->>$').at('#-1').as('last_nickname') + * ) + * ``` + * + * The generated SQL (SQLite): + * + * ```sql + * select "nicknames"->>'$[#-1]' as `last_nickname` from `person` + * ``` + */ + at(index2) { + return this.#createBuilderWithPathLeg("ArrayLocation", index2); + } + /** + * Access a property of a JSON object. + * + * If a field is optional, the resulting type will be nullable. + * + * See also {@link at} to access elements of JSON arrays. + * + * ### Examples + * + * ```ts + * db.selectFrom('person').select(eb => + * eb.ref('address', '->').key('city').as('city') + * ) + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * select "address"->'city' as "city" from "person" + * ``` + * + * Going deeper: + * + * ```ts + * db.selectFrom('person').select(eb => + * eb.ref('profile', '->$').key('website').key('url').as('website_url') + * ) + * ``` + * + * The generated SQL (MySQL): + * + * ```sql + * select `profile`->'$.website.url' as `website_url` from `person` + * ``` + * + * Combined with {@link at}: + * + * ```ts + * db.selectFrom('person').select(eb => + * eb.ref('profile', '->').key('addresses').at(0).key('city').as('city') + * ) + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * select "profile"->'addresses'->0->'city' as "city" from "person" + * ``` + */ + key(key) { + return this.#createBuilderWithPathLeg("Member", key); + } + #createBuilderWithPathLeg(legType, value) { + if (JSONReferenceNode.is(this.#node)) { + return new TraversedJSONPathBuilder(JSONReferenceNode.cloneWithTraversal(this.#node, JSONPathNode.is(this.#node.traversal) ? JSONPathNode.cloneWithLeg(this.#node.traversal, JSONPathLegNode.create(legType, value)) : JSONOperatorChainNode.cloneWithValue(this.#node.traversal, ValueNode.createImmediate(value)))); + } + return new TraversedJSONPathBuilder(JSONPathNode.cloneWithLeg(this.#node, JSONPathLegNode.create(legType, value))); + } + }; + TraversedJSONPathBuilder = class _TraversedJSONPathBuilder extends JSONPathBuilder { + #node; + constructor(node) { + super(node); + this.#node = node; + } + /** @private */ + get expressionType() { + return void 0; + } + as(alias) { + return new AliasedJSONPathBuilder(this, alias); + } + /** + * Change the output type of the json path. + * + * This method call doesn't change the SQL in any way. This methods simply + * returns a copy of this `JSONPathBuilder` with a new output type. + */ + $castTo() { + return new _TraversedJSONPathBuilder(this.#node); + } + $notNull() { + return new _TraversedJSONPathBuilder(this.#node); + } + toOperationNode() { + return this.#node; + } + }; + AliasedJSONPathBuilder = class { + #jsonPath; + #alias; + constructor(jsonPath, alias) { + this.#jsonPath = jsonPath; + this.#alias = alias; + } + /** @private */ + get expression() { + return this.#jsonPath; + } + /** @private */ + get alias() { + return this.#alias; + } + toOperationNode() { + return AliasNode.create(this.#jsonPath.toOperationNode(), isOperationNodeSource(this.#alias) ? this.#alias.toOperationNode() : IdentifierNode.create(this.#alias)); + } + }; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/tuple-node.js +var TupleNode; +var init_tuple_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/tuple-node.js"() { + init_object_utils(); + TupleNode = freeze2({ + is(node) { + return node.kind === "TupleNode"; + }, + create(values2) { + return freeze2({ + kind: "TupleNode", + values: freeze2(values2) + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/data-type-node.js +function isColumnDataType(dataType) { + if (SIMPLE_COLUMN_DATA_TYPES.includes(dataType)) { + return true; + } + if (COLUMN_DATA_TYPE_REGEX.some((r5) => r5.test(dataType))) { + return true; + } + return false; +} +var SIMPLE_COLUMN_DATA_TYPES, COLUMN_DATA_TYPE_REGEX, DataTypeNode; +var init_data_type_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/data-type-node.js"() { + init_object_utils(); + SIMPLE_COLUMN_DATA_TYPES = [ + "varchar", + "char", + "text", + "integer", + "int2", + "int4", + "int8", + "smallint", + "bigint", + "boolean", + "real", + "double precision", + "float4", + "float8", + "decimal", + "numeric", + "binary", + "bytea", + "date", + "datetime", + "time", + "timetz", + "timestamp", + "timestamptz", + "serial", + "bigserial", + "uuid", + "json", + "jsonb", + "blob", + "varbinary", + "int4range", + "int4multirange", + "int8range", + "int8multirange", + "numrange", + "nummultirange", + "tsrange", + "tsmultirange", + "tstzrange", + "tstzmultirange", + "daterange", + "datemultirange" + ]; + COLUMN_DATA_TYPE_REGEX = [ + /^varchar\(\d+\)$/, + /^char\(\d+\)$/, + /^decimal\(\d+, \d+\)$/, + /^numeric\(\d+, \d+\)$/, + /^binary\(\d+\)$/, + /^datetime\(\d+\)$/, + /^time\(\d+\)$/, + /^timetz\(\d+\)$/, + /^timestamp\(\d+\)$/, + /^timestamptz\(\d+\)$/, + /^varbinary\(\d+\)$/ + ]; + DataTypeNode = freeze2({ + is(node) { + return node.kind === "DataTypeNode"; + }, + create(dataType) { + return freeze2({ + kind: "DataTypeNode", + dataType + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/data-type-parser.js +function parseDataTypeExpression(dataType) { + if (isOperationNodeSource(dataType)) { + return dataType.toOperationNode(); + } + if (isColumnDataType(dataType)) { + return DataTypeNode.create(dataType); + } + throw new Error(`invalid column data type ${JSON.stringify(dataType)}`); +} +var init_data_type_parser = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/data-type-parser.js"() { + init_data_type_node(); + init_operation_node_source(); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/cast-node.js +var CastNode; +var init_cast_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/cast-node.js"() { + init_object_utils(); + CastNode = freeze2({ + is(node) { + return node.kind === "CastNode"; + }, + create(expression, dataType) { + return freeze2({ + kind: "CastNode", + expression, + dataType + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/expression/expression-builder.js +function createExpressionBuilder(executor = NOOP_QUERY_EXECUTOR) { + function binary2(lhs, op2, rhs) { + return new ExpressionWrapper(parseValueBinaryOperation(lhs, op2, rhs)); + } + function unary(op2, expr) { + return new ExpressionWrapper(parseUnaryOperation(op2, expr)); + } + const eb = Object.assign(binary2, { + fn: void 0, + eb: void 0, + selectFrom(table) { + return createSelectQueryBuilder({ + queryId: createQueryId(), + executor, + queryNode: SelectQueryNode.createFrom(parseTableExpressionOrList(table)) + }); + }, + case(reference) { + return new CaseBuilder({ + node: CaseNode.create(isUndefined(reference) ? void 0 : parseReferenceExpression(reference)) + }); + }, + ref(reference, op2) { + if (isUndefined(op2)) { + return new ExpressionWrapper(parseStringReference(reference)); + } + return new JSONPathBuilder(parseJSONReference(reference, op2)); + }, + jsonPath() { + return new JSONPathBuilder(JSONPathNode.create()); + }, + table(table) { + return new ExpressionWrapper(parseTable(table)); + }, + val(value) { + return new ExpressionWrapper(parseValueExpression(value)); + }, + refTuple(...values2) { + return new ExpressionWrapper(TupleNode.create(values2.map(parseReferenceExpression))); + }, + tuple(...values2) { + return new ExpressionWrapper(TupleNode.create(values2.map(parseValueExpression))); + }, + lit(value) { + return new ExpressionWrapper(parseSafeImmediateValue(value)); + }, + unary, + not(expr) { + return unary("not", expr); + }, + exists(expr) { + return unary("exists", expr); + }, + neg(expr) { + return unary("-", expr); + }, + between(expr, start, end) { + return new ExpressionWrapper(BinaryOperationNode.create(parseReferenceExpression(expr), OperatorNode.create("between"), AndNode.create(parseValueExpression(start), parseValueExpression(end)))); + }, + betweenSymmetric(expr, start, end) { + return new ExpressionWrapper(BinaryOperationNode.create(parseReferenceExpression(expr), OperatorNode.create("between symmetric"), AndNode.create(parseValueExpression(start), parseValueExpression(end)))); + }, + and(exprs) { + if (isReadonlyArray(exprs)) { + return new ExpressionWrapper(parseFilterList(exprs, "and")); + } + return new ExpressionWrapper(parseFilterObject(exprs, "and")); + }, + or(exprs) { + if (isReadonlyArray(exprs)) { + return new ExpressionWrapper(parseFilterList(exprs, "or")); + } + return new ExpressionWrapper(parseFilterObject(exprs, "or")); + }, + parens(...args) { + const node = parseValueBinaryOperationOrExpression(args); + if (ParensNode.is(node)) { + return new ExpressionWrapper(node); + } else { + return new ExpressionWrapper(ParensNode.create(node)); + } + }, + cast(expr, dataType) { + return new ExpressionWrapper(CastNode.create(parseReferenceExpression(expr), parseDataTypeExpression(dataType))); + }, + withSchema(schema2) { + return createExpressionBuilder(executor.withPluginAtFront(new WithSchemaPlugin(schema2))); + } + }); + eb.fn = createFunctionModule(); + eb.eb = eb; + return eb; +} +function expressionBuilder(_) { + return createExpressionBuilder(); +} +var init_expression_builder = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/expression/expression-builder.js"() { + init_select_query_builder(); + init_select_query_node(); + init_table_parser(); + init_with_schema_plugin(); + init_query_id(); + init_function_module(); + init_reference_parser(); + init_binary_operation_parser(); + init_parens_node(); + init_expression_wrapper(); + init_operator_node(); + init_unary_operation_parser(); + init_value_parser(); + init_noop_query_executor(); + init_case_builder(); + init_case_node(); + init_object_utils(); + init_json_path_builder(); + init_binary_operation_node(); + init_and_node(); + init_tuple_node(); + init_json_path_node(); + init_data_type_parser(); + init_cast_node(); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/expression-parser.js +function parseExpression(exp) { + if (isOperationNodeSource(exp)) { + return exp.toOperationNode(); + } else if (isFunction(exp)) { + return exp(expressionBuilder()).toOperationNode(); + } + throw new Error(`invalid expression: ${JSON.stringify(exp)}`); +} +function parseAliasedExpression(exp) { + if (isOperationNodeSource(exp)) { + return exp.toOperationNode(); + } else if (isFunction(exp)) { + return exp(expressionBuilder()).toOperationNode(); + } + throw new Error(`invalid aliased expression: ${JSON.stringify(exp)}`); +} +function isExpressionOrFactory(obj) { + return isExpression(obj) || isAliasedExpression(obj) || isFunction(obj); +} +var init_expression_parser = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/expression-parser.js"() { + init_expression(); + init_operation_node_source(); + init_expression_builder(); + init_object_utils(); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dynamic/dynamic-table-builder.js +function isAliasedDynamicTableBuilder(obj) { + return isObject3(obj) && isOperationNodeSource(obj) && isString(obj.table) && isString(obj.alias); +} +var DynamicTableBuilder, AliasedDynamicTableBuilder; +var init_dynamic_table_builder = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dynamic/dynamic-table-builder.js"() { + init_alias_node(); + init_identifier_node(); + init_operation_node_source(); + init_table_parser(); + init_object_utils(); + DynamicTableBuilder = class { + #table; + get table() { + return this.#table; + } + constructor(table) { + this.#table = table; + } + as(alias) { + return new AliasedDynamicTableBuilder(this.#table, alias); + } + }; + AliasedDynamicTableBuilder = class { + #table; + #alias; + get table() { + return this.#table; + } + get alias() { + return this.#alias; + } + constructor(table, alias) { + this.#table = table; + this.#alias = alias; + } + toOperationNode() { + return AliasNode.create(parseTable(this.#table), IdentifierNode.create(this.#alias)); + } + }; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/table-parser.js +function parseTableExpressionOrList(table) { + if (isReadonlyArray(table)) { + return table.map((it) => parseTableExpression(it)); + } else { + return [parseTableExpression(table)]; + } +} +function parseTableExpression(table) { + if (isString(table)) { + return parseAliasedTable(table); + } else if (isAliasedDynamicTableBuilder(table)) { + return table.toOperationNode(); + } else { + return parseAliasedExpression(table); + } +} +function parseAliasedTable(from) { + const ALIAS_SEPARATOR = " as "; + if (from.includes(ALIAS_SEPARATOR)) { + const [table, alias] = from.split(ALIAS_SEPARATOR).map(trim2); + return AliasNode.create(parseTable(table), IdentifierNode.create(alias)); + } else { + return parseTable(from); + } +} +function parseTable(from) { + const SCHEMA_SEPARATOR = "."; + if (from.includes(SCHEMA_SEPARATOR)) { + const [schema2, table] = from.split(SCHEMA_SEPARATOR).map(trim2); + return TableNode.createWithSchema(schema2, table); + } else { + return TableNode.create(from); + } +} +function trim2(str) { + return str.trim(); +} +var init_table_parser = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/table-parser.js"() { + init_object_utils(); + init_alias_node(); + init_table_node(); + init_expression_parser(); + init_identifier_node(); + init_dynamic_table_builder(); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/add-column-node.js +var AddColumnNode; +var init_add_column_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/add-column-node.js"() { + init_object_utils(); + AddColumnNode = freeze2({ + is(node) { + return node.kind === "AddColumnNode"; + }, + create(column) { + return freeze2({ + kind: "AddColumnNode", + column + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/column-definition-node.js +var ColumnDefinitionNode; +var init_column_definition_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/column-definition-node.js"() { + init_object_utils(); + init_column_node(); + ColumnDefinitionNode = freeze2({ + is(node) { + return node.kind === "ColumnDefinitionNode"; + }, + create(column, dataType) { + return freeze2({ + kind: "ColumnDefinitionNode", + column: ColumnNode.create(column), + dataType + }); + }, + cloneWithFrontModifier(node, modifier) { + return freeze2({ + ...node, + frontModifiers: node.frontModifiers ? freeze2([...node.frontModifiers, modifier]) : [modifier] + }); + }, + cloneWithEndModifier(node, modifier) { + return freeze2({ + ...node, + endModifiers: node.endModifiers ? freeze2([...node.endModifiers, modifier]) : [modifier] + }); + }, + cloneWith(node, props) { + return freeze2({ + ...node, + ...props + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/drop-column-node.js +var DropColumnNode; +var init_drop_column_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/drop-column-node.js"() { + init_object_utils(); + init_column_node(); + DropColumnNode = freeze2({ + is(node) { + return node.kind === "DropColumnNode"; + }, + create(column) { + return freeze2({ + kind: "DropColumnNode", + column: ColumnNode.create(column) + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/rename-column-node.js +var RenameColumnNode; +var init_rename_column_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/rename-column-node.js"() { + init_object_utils(); + init_column_node(); + RenameColumnNode = freeze2({ + is(node) { + return node.kind === "RenameColumnNode"; + }, + create(column, newColumn) { + return freeze2({ + kind: "RenameColumnNode", + column: ColumnNode.create(column), + renameTo: ColumnNode.create(newColumn) + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/check-constraint-node.js +var CheckConstraintNode; +var init_check_constraint_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/check-constraint-node.js"() { + init_object_utils(); + init_identifier_node(); + CheckConstraintNode = freeze2({ + is(node) { + return node.kind === "CheckConstraintNode"; + }, + create(expression, constraintName) { + return freeze2({ + kind: "CheckConstraintNode", + expression, + name: constraintName ? IdentifierNode.create(constraintName) : void 0 + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/references-node.js +var ON_MODIFY_FOREIGN_ACTIONS, ReferencesNode; +var init_references_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/references-node.js"() { + init_object_utils(); + ON_MODIFY_FOREIGN_ACTIONS = [ + "no action", + "restrict", + "cascade", + "set null", + "set default" + ]; + ReferencesNode = freeze2({ + is(node) { + return node.kind === "ReferencesNode"; + }, + create(table, columns) { + return freeze2({ + kind: "ReferencesNode", + table, + columns: freeze2([...columns]) + }); + }, + cloneWithOnDelete(references, onDelete) { + return freeze2({ + ...references, + onDelete + }); + }, + cloneWithOnUpdate(references, onUpdate) { + return freeze2({ + ...references, + onUpdate + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/default-value-parser.js +function parseDefaultValueExpression(value) { + return isOperationNodeSource(value) ? value.toOperationNode() : ValueNode.createImmediate(value); +} +var init_default_value_parser = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/default-value-parser.js"() { + init_operation_node_source(); + init_value_node(); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/generated-node.js +var GeneratedNode; +var init_generated_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/generated-node.js"() { + init_object_utils(); + GeneratedNode = freeze2({ + is(node) { + return node.kind === "GeneratedNode"; + }, + create(params) { + return freeze2({ + kind: "GeneratedNode", + ...params + }); + }, + createWithExpression(expression) { + return freeze2({ + kind: "GeneratedNode", + always: true, + expression + }); + }, + cloneWith(node, params) { + return freeze2({ + ...node, + ...params + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/default-value-node.js +var DefaultValueNode; +var init_default_value_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/default-value-node.js"() { + init_object_utils(); + DefaultValueNode = freeze2({ + is(node) { + return node.kind === "DefaultValueNode"; + }, + create(defaultValue) { + return freeze2({ + kind: "DefaultValueNode", + defaultValue + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/on-modify-action-parser.js +function parseOnModifyForeignAction(action) { + if (ON_MODIFY_FOREIGN_ACTIONS.includes(action)) { + return action; + } + throw new Error(`invalid OnModifyForeignAction ${action}`); +} +var init_on_modify_action_parser = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/on-modify-action-parser.js"() { + init_references_node(); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/column-definition-builder.js +var ColumnDefinitionBuilder; +var init_column_definition_builder = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/column-definition-builder.js"() { + init_check_constraint_node(); + init_references_node(); + init_select_all_node(); + init_reference_parser(); + init_column_definition_node(); + init_default_value_parser(); + init_generated_node(); + init_default_value_node(); + init_on_modify_action_parser(); + ColumnDefinitionBuilder = class _ColumnDefinitionBuilder { + #node; + constructor(node) { + this.#node = node; + } + /** + * Adds `auto_increment` or `autoincrement` to the column definition + * depending on the dialect. + * + * Some dialects like PostgreSQL don't support this. On PostgreSQL + * you can use the `serial` or `bigserial` data type instead. + * + * ### Examples + * + * ```ts + * await db.schema + * .createTable('person') + * .addColumn('id', 'integer', col => col.autoIncrement().primaryKey()) + * .execute() + * ``` + * + * The generated SQL (MySQL): + * + * ```sql + * create table `person` ( + * `id` integer primary key auto_increment + * ) + * ``` + */ + autoIncrement() { + return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, { autoIncrement: true })); + } + /** + * Makes the column an identity column. + * + * This only works on some dialects like MS SQL Server (MSSQL). + * + * For PostgreSQL's `generated always as identity` use {@link generatedAlwaysAsIdentity}. + * + * ### Examples + * + * ```ts + * await db.schema + * .createTable('person') + * .addColumn('id', 'integer', col => col.identity().primaryKey()) + * .execute() + * ``` + * + * The generated SQL (MSSQL): + * + * ```sql + * create table "person" ( + * "id" integer identity primary key + * ) + * ``` + */ + identity() { + return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, { identity: true })); + } + /** + * Makes the column the primary key. + * + * If you want to specify a composite primary key use the + * {@link CreateTableBuilder.addPrimaryKeyConstraint} method. + * + * ### Examples + * + * ```ts + * await db.schema + * .createTable('person') + * .addColumn('id', 'integer', col => col.primaryKey()) + * .execute() + * ``` + * + * The generated SQL (MySQL): + * + * ```sql + * create table `person` ( + * `id` integer primary key + * ) + */ + primaryKey() { + return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, { primaryKey: true })); + } + /** + * Adds a foreign key constraint for the column. + * + * If your database engine doesn't support foreign key constraints in the + * column definition (like MySQL 5) you need to call the table level + * {@link CreateTableBuilder.addForeignKeyConstraint} method instead. + * + * ### Examples + * + * ```ts + * await db.schema + * .createTable('pet') + * .addColumn('owner_id', 'integer', (col) => col.references('person.id')) + * .execute() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * create table "pet" ( + * "owner_id" integer references "person" ("id") + * ) + * ``` + */ + references(ref) { + const references = parseStringReference(ref); + if (!references.table || SelectAllNode.is(references.column)) { + throw new Error(`invalid call references('${ref}'). The reference must have format table.column or schema.table.column`); + } + return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, { + references: ReferencesNode.create(references.table, [ + references.column + ]) + })); + } + /** + * Adds an `on delete` constraint for the foreign key column. + * + * If your database engine doesn't support foreign key constraints in the + * column definition (like MySQL 5) you need to call the table level + * {@link CreateTableBuilder.addForeignKeyConstraint} method instead. + * + * ### Examples + * + * ```ts + * await db.schema + * .createTable('pet') + * .addColumn( + * 'owner_id', + * 'integer', + * (col) => col.references('person.id').onDelete('cascade') + * ) + * .execute() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * create table "pet" ( + * "owner_id" integer references "person" ("id") on delete cascade + * ) + * ``` + */ + onDelete(onDelete) { + if (!this.#node.references) { + throw new Error("on delete constraint can only be added for foreign keys"); + } + return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, { + references: ReferencesNode.cloneWithOnDelete(this.#node.references, parseOnModifyForeignAction(onDelete)) + })); + } + /** + * Adds an `on update` constraint for the foreign key column. + * + * If your database engine doesn't support foreign key constraints in the + * column definition (like MySQL 5) you need to call the table level + * {@link CreateTableBuilder.addForeignKeyConstraint} method instead. + * + * ### Examples + * + * ```ts + * await db.schema + * .createTable('pet') + * .addColumn( + * 'owner_id', + * 'integer', + * (col) => col.references('person.id').onUpdate('cascade') + * ) + * .execute() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * create table "pet" ( + * "owner_id" integer references "person" ("id") on update cascade + * ) + * ``` + */ + onUpdate(onUpdate) { + if (!this.#node.references) { + throw new Error("on update constraint can only be added for foreign keys"); + } + return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, { + references: ReferencesNode.cloneWithOnUpdate(this.#node.references, parseOnModifyForeignAction(onUpdate)) + })); + } + /** + * Adds a unique constraint for the column. + * + * ### Examples + * + * ```ts + * await db.schema + * .createTable('person') + * .addColumn('email', 'varchar(255)', col => col.unique()) + * .execute() + * ``` + * + * The generated SQL (MySQL): + * + * ```sql + * create table `person` ( + * `email` varchar(255) unique + * ) + * ``` + */ + unique() { + return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, { unique: true })); + } + /** + * Adds a `not null` constraint for the column. + * + * ### Examples + * + * ```ts + * await db.schema + * .createTable('person') + * .addColumn('first_name', 'varchar(255)', col => col.notNull()) + * .execute() + * ``` + * + * The generated SQL (MySQL): + * + * ```sql + * create table `person` ( + * `first_name` varchar(255) not null + * ) + * ``` + */ + notNull() { + return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, { notNull: true })); + } + /** + * Adds a `unsigned` modifier for the column. + * + * This only works on some dialects like MySQL. + * + * ### Examples + * + * ```ts + * await db.schema + * .createTable('person') + * .addColumn('age', 'integer', col => col.unsigned()) + * .execute() + * ``` + * + * The generated SQL (MySQL): + * + * ```sql + * create table `person` ( + * `age` integer unsigned + * ) + * ``` + */ + unsigned() { + return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, { unsigned: true })); + } + /** + * Adds a default value constraint for the column. + * + * ### Examples + * + * ```ts + * await db.schema + * .createTable('pet') + * .addColumn('number_of_legs', 'integer', (col) => col.defaultTo(4)) + * .execute() + * ``` + * + * The generated SQL (MySQL): + * + * ```sql + * create table `pet` ( + * `number_of_legs` integer default 4 + * ) + * ``` + * + * Values passed to `defaultTo` are interpreted as value literals by default. You can define + * an arbitrary SQL expression using the {@link sql} template tag: + * + * ```ts + * import { sql } from 'kysely' + * + * await db.schema + * .createTable('pet') + * .addColumn( + * 'created_at', + * 'timestamp', + * (col) => col.defaultTo(sql`CURRENT_TIMESTAMP`) + * ) + * .execute() + * ``` + * + * The generated SQL (MySQL): + * + * ```sql + * create table `pet` ( + * `created_at` timestamp default CURRENT_TIMESTAMP + * ) + * ``` + */ + defaultTo(value) { + return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, { + defaultTo: DefaultValueNode.create(parseDefaultValueExpression(value)) + })); + } + /** + * Adds a check constraint for the column. + * + * ### Examples + * + * ```ts + * import { sql } from 'kysely' + * + * await db.schema + * .createTable('pet') + * .addColumn('number_of_legs', 'integer', (col) => + * col.check(sql`number_of_legs < 5`) + * ) + * .execute() + * ``` + * + * The generated SQL (MySQL): + * + * ```sql + * create table `pet` ( + * `number_of_legs` integer check (number_of_legs < 5) + * ) + * ``` + */ + check(expression) { + return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, { + check: CheckConstraintNode.create(expression.toOperationNode()) + })); + } + /** + * Makes the column a generated column using a `generated always as` statement. + * + * ### Examples + * + * ```ts + * import { sql } from 'kysely' + * + * await db.schema + * .createTable('person') + * .addColumn('full_name', 'varchar(255)', + * (col) => col.generatedAlwaysAs(sql`concat(first_name, ' ', last_name)`) + * ) + * .execute() + * ``` + * + * The generated SQL (MySQL): + * + * ```sql + * create table `person` ( + * `full_name` varchar(255) generated always as (concat(first_name, ' ', last_name)) + * ) + * ``` + */ + generatedAlwaysAs(expression) { + return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, { + generated: GeneratedNode.createWithExpression(expression.toOperationNode()) + })); + } + /** + * Adds the `generated always as identity` specifier. + * + * This only works on some dialects like PostgreSQL. + * + * For MS SQL Server (MSSQL)'s identity column use {@link identity}. + * + * ### Examples + * + * ```ts + * await db.schema + * .createTable('person') + * .addColumn('id', 'integer', col => col.generatedAlwaysAsIdentity().primaryKey()) + * .execute() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * create table "person" ( + * "id" integer generated always as identity primary key + * ) + * ``` + */ + generatedAlwaysAsIdentity() { + return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, { + generated: GeneratedNode.create({ identity: true, always: true }) + })); + } + /** + * Adds the `generated by default as identity` specifier on supported dialects. + * + * This only works on some dialects like PostgreSQL. + * + * For MS SQL Server (MSSQL)'s identity column use {@link identity}. + * + * ### Examples + * + * ```ts + * await db.schema + * .createTable('person') + * .addColumn('id', 'integer', col => col.generatedByDefaultAsIdentity().primaryKey()) + * .execute() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * create table "person" ( + * "id" integer generated by default as identity primary key + * ) + * ``` + */ + generatedByDefaultAsIdentity() { + return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, { + generated: GeneratedNode.create({ identity: true, byDefault: true }) + })); + } + /** + * Makes a generated column stored instead of virtual. This method can only + * be used with {@link generatedAlwaysAs} + * + * ### Examples + * + * ```ts + * import { sql } from 'kysely' + * + * await db.schema + * .createTable('person') + * .addColumn('full_name', 'varchar(255)', (col) => col + * .generatedAlwaysAs(sql`concat(first_name, ' ', last_name)`) + * .stored() + * ) + * .execute() + * ``` + * + * The generated SQL (MySQL): + * + * ```sql + * create table `person` ( + * `full_name` varchar(255) generated always as (concat(first_name, ' ', last_name)) stored + * ) + * ``` + */ + stored() { + if (!this.#node.generated) { + throw new Error("stored() can only be called after generatedAlwaysAs"); + } + return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, { + generated: GeneratedNode.cloneWith(this.#node.generated, { + stored: true + }) + })); + } + /** + * This can be used to add any additional SQL right after the column's data type. + * + * ### Examples + * + * ```ts + * import { sql } from 'kysely' + * + * await db.schema + * .createTable('person') + * .addColumn('id', 'integer', col => col.primaryKey()) + * .addColumn( + * 'first_name', + * 'varchar(36)', + * (col) => col.modifyFront(sql`collate utf8mb4_general_ci`).notNull() + * ) + * .execute() + * ``` + * + * The generated SQL (MySQL): + * + * ```sql + * create table `person` ( + * `id` integer primary key, + * `first_name` varchar(36) collate utf8mb4_general_ci not null + * ) + * ``` + */ + modifyFront(modifier) { + return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWithFrontModifier(this.#node, modifier.toOperationNode())); + } + /** + * Adds `nulls not distinct` specifier. + * Should be used with `unique` constraint. + * + * This only works on some dialects like PostgreSQL. + * + * ### Examples + * + * ```ts + * db.schema + * .createTable('person') + * .addColumn('id', 'integer', col => col.primaryKey()) + * .addColumn('first_name', 'varchar(30)', col => col.unique().nullsNotDistinct()) + * .execute() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * create table "person" ( + * "id" integer primary key, + * "first_name" varchar(30) unique nulls not distinct + * ) + * ``` + */ + nullsNotDistinct() { + return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, { nullsNotDistinct: true })); + } + /** + * Adds `if not exists` specifier. This only works for PostgreSQL. + * + * ### Examples + * + * ```ts + * await db.schema + * .alterTable('person') + * .addColumn('email', 'varchar(255)', col => col.unique().ifNotExists()) + * .execute() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * alter table "person" add column if not exists "email" varchar(255) unique + * ``` + */ + ifNotExists() { + return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, { ifNotExists: true })); + } + /** + * This can be used to add any additional SQL to the end of the column definition. + * + * ### Examples + * + * ```ts + * import { sql } from 'kysely' + * + * await db.schema + * .createTable('person') + * .addColumn('id', 'integer', col => col.primaryKey()) + * .addColumn( + * 'age', + * 'integer', + * col => col.unsigned() + * .notNull() + * .modifyEnd(sql`comment ${sql.lit('it is not polite to ask a woman her age')}`) + * ) + * .execute() + * ``` + * + * The generated SQL (MySQL): + * + * ```sql + * create table `person` ( + * `id` integer primary key, + * `age` integer unsigned not null comment 'it is not polite to ask a woman her age' + * ) + * ``` + */ + modifyEnd(modifier) { + return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWithEndModifier(this.#node, modifier.toOperationNode())); + } + /** + * Simply calls the provided function passing `this` as the only argument. `$call` returns + * what the provided function returns. + */ + $call(func) { + return func(this); + } + toOperationNode() { + return this.#node; + } + }; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/modify-column-node.js +var ModifyColumnNode; +var init_modify_column_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/modify-column-node.js"() { + init_object_utils(); + ModifyColumnNode = freeze2({ + is(node) { + return node.kind === "ModifyColumnNode"; + }, + create(column) { + return freeze2({ + kind: "ModifyColumnNode", + column + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/foreign-key-constraint-node.js +var ForeignKeyConstraintNode; +var init_foreign_key_constraint_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/foreign-key-constraint-node.js"() { + init_object_utils(); + init_identifier_node(); + init_references_node(); + ForeignKeyConstraintNode = freeze2({ + is(node) { + return node.kind === "ForeignKeyConstraintNode"; + }, + create(sourceColumns, targetTable, targetColumns, constraintName) { + return freeze2({ + kind: "ForeignKeyConstraintNode", + columns: sourceColumns, + references: ReferencesNode.create(targetTable, targetColumns), + name: constraintName ? IdentifierNode.create(constraintName) : void 0 + }); + }, + cloneWith(node, props) { + return freeze2({ + ...node, + ...props + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/foreign-key-constraint-builder.js +var ForeignKeyConstraintBuilder; +var init_foreign_key_constraint_builder = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/foreign-key-constraint-builder.js"() { + init_foreign_key_constraint_node(); + init_on_modify_action_parser(); + ForeignKeyConstraintBuilder = class _ForeignKeyConstraintBuilder { + #node; + constructor(node) { + this.#node = node; + } + onDelete(onDelete) { + return new _ForeignKeyConstraintBuilder(ForeignKeyConstraintNode.cloneWith(this.#node, { + onDelete: parseOnModifyForeignAction(onDelete) + })); + } + onUpdate(onUpdate) { + return new _ForeignKeyConstraintBuilder(ForeignKeyConstraintNode.cloneWith(this.#node, { + onUpdate: parseOnModifyForeignAction(onUpdate) + })); + } + deferrable() { + return new _ForeignKeyConstraintBuilder(ForeignKeyConstraintNode.cloneWith(this.#node, { deferrable: true })); + } + notDeferrable() { + return new _ForeignKeyConstraintBuilder(ForeignKeyConstraintNode.cloneWith(this.#node, { deferrable: false })); + } + initiallyDeferred() { + return new _ForeignKeyConstraintBuilder(ForeignKeyConstraintNode.cloneWith(this.#node, { + initiallyDeferred: true + })); + } + initiallyImmediate() { + return new _ForeignKeyConstraintBuilder(ForeignKeyConstraintNode.cloneWith(this.#node, { + initiallyDeferred: false + })); + } + /** + * Simply calls the provided function passing `this` as the only argument. `$call` returns + * what the provided function returns. + */ + $call(func) { + return func(this); + } + toOperationNode() { + return this.#node; + } + }; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/add-constraint-node.js +var AddConstraintNode; +var init_add_constraint_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/add-constraint-node.js"() { + init_object_utils(); + AddConstraintNode = freeze2({ + is(node) { + return node.kind === "AddConstraintNode"; + }, + create(constraint) { + return freeze2({ + kind: "AddConstraintNode", + constraint + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/unique-constraint-node.js +var UniqueConstraintNode; +var init_unique_constraint_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/unique-constraint-node.js"() { + init_object_utils(); + init_column_node(); + init_identifier_node(); + UniqueConstraintNode = freeze2({ + is(node) { + return node.kind === "UniqueConstraintNode"; + }, + create(columns, constraintName, nullsNotDistinct) { + return freeze2({ + kind: "UniqueConstraintNode", + columns: freeze2(columns.map(ColumnNode.create)), + name: constraintName ? IdentifierNode.create(constraintName) : void 0, + nullsNotDistinct + }); + }, + cloneWith(node, props) { + return freeze2({ + ...node, + ...props + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/drop-constraint-node.js +var DropConstraintNode; +var init_drop_constraint_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/drop-constraint-node.js"() { + init_object_utils(); + init_identifier_node(); + DropConstraintNode = freeze2({ + is(node) { + return node.kind === "DropConstraintNode"; + }, + create(constraintName) { + return freeze2({ + kind: "DropConstraintNode", + constraintName: IdentifierNode.create(constraintName) + }); + }, + cloneWith(dropConstraint, props) { + return freeze2({ + ...dropConstraint, + ...props + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/alter-column-node.js +var AlterColumnNode; +var init_alter_column_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/alter-column-node.js"() { + init_object_utils(); + init_column_node(); + AlterColumnNode = freeze2({ + is(node) { + return node.kind === "AlterColumnNode"; + }, + create(column, prop, value) { + return freeze2({ + kind: "AlterColumnNode", + column: ColumnNode.create(column), + [prop]: value + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/alter-column-builder.js +var AlterColumnBuilder, AlteredColumnBuilder; +var init_alter_column_builder = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/alter-column-builder.js"() { + init_alter_column_node(); + init_data_type_parser(); + init_default_value_parser(); + AlterColumnBuilder = class { + #column; + constructor(column) { + this.#column = column; + } + setDataType(dataType) { + return new AlteredColumnBuilder(AlterColumnNode.create(this.#column, "dataType", parseDataTypeExpression(dataType))); + } + setDefault(value) { + return new AlteredColumnBuilder(AlterColumnNode.create(this.#column, "setDefault", parseDefaultValueExpression(value))); + } + dropDefault() { + return new AlteredColumnBuilder(AlterColumnNode.create(this.#column, "dropDefault", true)); + } + setNotNull() { + return new AlteredColumnBuilder(AlterColumnNode.create(this.#column, "setNotNull", true)); + } + dropNotNull() { + return new AlteredColumnBuilder(AlterColumnNode.create(this.#column, "dropNotNull", true)); + } + /** + * Simply calls the provided function passing `this` as the only argument. `$call` returns + * what the provided function returns. + */ + $call(func) { + return func(this); + } + }; + AlteredColumnBuilder = class { + #alterColumnNode; + constructor(alterColumnNode) { + this.#alterColumnNode = alterColumnNode; + } + toOperationNode() { + return this.#alterColumnNode; + } + }; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/alter-table-executor.js +var AlterTableExecutor; +var init_alter_table_executor = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/alter-table-executor.js"() { + init_object_utils(); + AlterTableExecutor = class { + #props; + constructor(props) { + this.#props = freeze2(props); + } + toOperationNode() { + return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId); + } + compile() { + return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId); + } + async execute() { + await this.#props.executor.executeQuery(this.compile()); + } + }; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/alter-table-add-foreign-key-constraint-builder.js +var AlterTableAddForeignKeyConstraintBuilder; +var init_alter_table_add_foreign_key_constraint_builder = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/alter-table-add-foreign-key-constraint-builder.js"() { + init_add_constraint_node(); + init_alter_table_node(); + init_object_utils(); + AlterTableAddForeignKeyConstraintBuilder = class _AlterTableAddForeignKeyConstraintBuilder { + #props; + constructor(props) { + this.#props = freeze2(props); + } + onDelete(onDelete) { + return new _AlterTableAddForeignKeyConstraintBuilder({ + ...this.#props, + constraintBuilder: this.#props.constraintBuilder.onDelete(onDelete) + }); + } + onUpdate(onUpdate) { + return new _AlterTableAddForeignKeyConstraintBuilder({ + ...this.#props, + constraintBuilder: this.#props.constraintBuilder.onUpdate(onUpdate) + }); + } + deferrable() { + return new _AlterTableAddForeignKeyConstraintBuilder({ + ...this.#props, + constraintBuilder: this.#props.constraintBuilder.deferrable() + }); + } + notDeferrable() { + return new _AlterTableAddForeignKeyConstraintBuilder({ + ...this.#props, + constraintBuilder: this.#props.constraintBuilder.notDeferrable() + }); + } + initiallyDeferred() { + return new _AlterTableAddForeignKeyConstraintBuilder({ + ...this.#props, + constraintBuilder: this.#props.constraintBuilder.initiallyDeferred() + }); + } + initiallyImmediate() { + return new _AlterTableAddForeignKeyConstraintBuilder({ + ...this.#props, + constraintBuilder: this.#props.constraintBuilder.initiallyImmediate() + }); + } + /** + * Simply calls the provided function passing `this` as the only argument. `$call` returns + * what the provided function returns. + */ + $call(func) { + return func(this); + } + toOperationNode() { + return this.#props.executor.transformQuery(AlterTableNode.cloneWithTableProps(this.#props.node, { + addConstraint: AddConstraintNode.create(this.#props.constraintBuilder.toOperationNode()) + }), this.#props.queryId); + } + compile() { + return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId); + } + async execute() { + await this.#props.executor.executeQuery(this.compile()); + } + }; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/alter-table-drop-constraint-builder.js +var AlterTableDropConstraintBuilder; +var init_alter_table_drop_constraint_builder = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/alter-table-drop-constraint-builder.js"() { + init_alter_table_node(); + init_drop_constraint_node(); + init_object_utils(); + AlterTableDropConstraintBuilder = class _AlterTableDropConstraintBuilder { + #props; + constructor(props) { + this.#props = freeze2(props); + } + ifExists() { + return new _AlterTableDropConstraintBuilder({ + ...this.#props, + node: AlterTableNode.cloneWithTableProps(this.#props.node, { + dropConstraint: DropConstraintNode.cloneWith(this.#props.node.dropConstraint, { + ifExists: true + }) + }) + }); + } + cascade() { + return new _AlterTableDropConstraintBuilder({ + ...this.#props, + node: AlterTableNode.cloneWithTableProps(this.#props.node, { + dropConstraint: DropConstraintNode.cloneWith(this.#props.node.dropConstraint, { + modifier: "cascade" + }) + }) + }); + } + restrict() { + return new _AlterTableDropConstraintBuilder({ + ...this.#props, + node: AlterTableNode.cloneWithTableProps(this.#props.node, { + dropConstraint: DropConstraintNode.cloneWith(this.#props.node.dropConstraint, { + modifier: "restrict" + }) + }) + }); + } + /** + * Simply calls the provided function passing `this` as the only argument. `$call` returns + * what the provided function returns. + */ + $call(func) { + return func(this); + } + toOperationNode() { + return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId); + } + compile() { + return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId); + } + async execute() { + await this.#props.executor.executeQuery(this.compile()); + } + }; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/primary-key-constraint-node.js +var PrimaryKeyConstraintNode; +var init_primary_key_constraint_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/primary-key-constraint-node.js"() { + init_object_utils(); + init_column_node(); + init_identifier_node(); + PrimaryKeyConstraintNode = freeze2({ + is(node) { + return node.kind === "PrimaryKeyConstraintNode"; + }, + create(columns, constraintName) { + return freeze2({ + kind: "PrimaryKeyConstraintNode", + columns: freeze2(columns.map(ColumnNode.create)), + name: constraintName ? IdentifierNode.create(constraintName) : void 0 + }); + }, + cloneWith(node, props) { + return freeze2({ ...node, ...props }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/add-index-node.js +var AddIndexNode; +var init_add_index_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/add-index-node.js"() { + init_object_utils(); + init_identifier_node(); + AddIndexNode = freeze2({ + is(node) { + return node.kind === "AddIndexNode"; + }, + create(name) { + return freeze2({ + kind: "AddIndexNode", + name: IdentifierNode.create(name) + }); + }, + cloneWith(node, props) { + return freeze2({ + ...node, + ...props + }); + }, + cloneWithColumns(node, columns) { + return freeze2({ + ...node, + columns: [...node.columns || [], ...columns] + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/alter-table-add-index-builder.js +var AlterTableAddIndexBuilder; +var init_alter_table_add_index_builder = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/alter-table-add-index-builder.js"() { + init_add_index_node(); + init_alter_table_node(); + init_raw_node(); + init_reference_parser(); + init_object_utils(); + AlterTableAddIndexBuilder = class _AlterTableAddIndexBuilder { + #props; + constructor(props) { + this.#props = freeze2(props); + } + /** + * Makes the index unique. + * + * ### Examples + * + * ```ts + * await db.schema + * .alterTable('person') + * .addIndex('person_first_name_index') + * .unique() + * .column('email') + * .execute() + * ``` + * + * The generated SQL (MySQL): + * + * ```sql + * alter table `person` add unique index `person_first_name_index` (`email`) + * ``` + */ + unique() { + return new _AlterTableAddIndexBuilder({ + ...this.#props, + node: AlterTableNode.cloneWithTableProps(this.#props.node, { + addIndex: AddIndexNode.cloneWith(this.#props.node.addIndex, { + unique: true + }) + }) + }); + } + /** + * Adds a column to the index. + * + * Also see {@link columns} for adding multiple columns at once or {@link expression} + * for specifying an arbitrary expression. + * + * ### Examples + * + * ```ts + * await db.schema + * .alterTable('person') + * .addIndex('person_first_name_and_age_index') + * .column('first_name') + * .column('age desc') + * .execute() + * ``` + * + * The generated SQL (MySQL): + * + * ```sql + * alter table `person` add index `person_first_name_and_age_index` (`first_name`, `age` desc) + * ``` + */ + column(column) { + return new _AlterTableAddIndexBuilder({ + ...this.#props, + node: AlterTableNode.cloneWithTableProps(this.#props.node, { + addIndex: AddIndexNode.cloneWithColumns(this.#props.node.addIndex, [ + parseOrderedColumnName(column) + ]) + }) + }); + } + /** + * Specifies a list of columns for the index. + * + * Also see {@link column} for adding a single column or {@link expression} for + * specifying an arbitrary expression. + * + * ### Examples + * + * ```ts + * await db.schema + * .alterTable('person') + * .addIndex('person_first_name_and_age_index') + * .columns(['first_name', 'age desc']) + * .execute() + * ``` + * + * The generated SQL (MySQL): + * + * ```sql + * alter table `person` add index `person_first_name_and_age_index` (`first_name`, `age` desc) + * ``` + */ + columns(columns) { + return new _AlterTableAddIndexBuilder({ + ...this.#props, + node: AlterTableNode.cloneWithTableProps(this.#props.node, { + addIndex: AddIndexNode.cloneWithColumns(this.#props.node.addIndex, columns.map(parseOrderedColumnName)) + }) + }); + } + /** + * Specifies an arbitrary expression for the index. + * + * ### Examples + * + * ```ts + * import { sql } from 'kysely' + * + * await db.schema + * .alterTable('person') + * .addIndex('person_first_name_index') + * .expression(sql`(first_name < 'Sami')`) + * .execute() + * ``` + * + * The generated SQL (MySQL): + * + * ```sql + * alter table `person` add index `person_first_name_index` ((first_name < 'Sami')) + * ``` + */ + expression(expression) { + return new _AlterTableAddIndexBuilder({ + ...this.#props, + node: AlterTableNode.cloneWithTableProps(this.#props.node, { + addIndex: AddIndexNode.cloneWithColumns(this.#props.node.addIndex, [ + expression.toOperationNode() + ]) + }) + }); + } + using(indexType) { + return new _AlterTableAddIndexBuilder({ + ...this.#props, + node: AlterTableNode.cloneWithTableProps(this.#props.node, { + addIndex: AddIndexNode.cloneWith(this.#props.node.addIndex, { + using: RawNode.createWithSql(indexType) + }) + }) + }); + } + /** + * Simply calls the provided function passing `this` as the only argument. `$call` returns + * what the provided function returns. + */ + $call(func) { + return func(this); + } + toOperationNode() { + return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId); + } + compile() { + return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId); + } + async execute() { + await this.#props.executor.executeQuery(this.compile()); + } + }; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/unique-constraint-builder.js +var UniqueConstraintNodeBuilder; +var init_unique_constraint_builder = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/unique-constraint-builder.js"() { + init_unique_constraint_node(); + UniqueConstraintNodeBuilder = class _UniqueConstraintNodeBuilder { + #node; + constructor(node) { + this.#node = node; + } + /** + * Adds `nulls not distinct` to the unique constraint definition + * + * Supported by PostgreSQL dialect only + */ + nullsNotDistinct() { + return new _UniqueConstraintNodeBuilder(UniqueConstraintNode.cloneWith(this.#node, { nullsNotDistinct: true })); + } + deferrable() { + return new _UniqueConstraintNodeBuilder(UniqueConstraintNode.cloneWith(this.#node, { deferrable: true })); + } + notDeferrable() { + return new _UniqueConstraintNodeBuilder(UniqueConstraintNode.cloneWith(this.#node, { deferrable: false })); + } + initiallyDeferred() { + return new _UniqueConstraintNodeBuilder(UniqueConstraintNode.cloneWith(this.#node, { + initiallyDeferred: true + })); + } + initiallyImmediate() { + return new _UniqueConstraintNodeBuilder(UniqueConstraintNode.cloneWith(this.#node, { + initiallyDeferred: false + })); + } + /** + * Simply calls the provided function passing `this` as the only argument. `$call` returns + * what the provided function returns. + */ + $call(func) { + return func(this); + } + toOperationNode() { + return this.#node; + } + }; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/primary-key-constraint-builder.js +var PrimaryKeyConstraintBuilder; +var init_primary_key_constraint_builder = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/primary-key-constraint-builder.js"() { + init_primary_key_constraint_node(); + PrimaryKeyConstraintBuilder = class _PrimaryKeyConstraintBuilder { + #node; + constructor(node) { + this.#node = node; + } + deferrable() { + return new _PrimaryKeyConstraintBuilder(PrimaryKeyConstraintNode.cloneWith(this.#node, { deferrable: true })); + } + notDeferrable() { + return new _PrimaryKeyConstraintBuilder(PrimaryKeyConstraintNode.cloneWith(this.#node, { deferrable: false })); + } + initiallyDeferred() { + return new _PrimaryKeyConstraintBuilder(PrimaryKeyConstraintNode.cloneWith(this.#node, { + initiallyDeferred: true + })); + } + initiallyImmediate() { + return new _PrimaryKeyConstraintBuilder(PrimaryKeyConstraintNode.cloneWith(this.#node, { + initiallyDeferred: false + })); + } + /** + * Simply calls the provided function passing `this` as the only argument. `$call` returns + * what the provided function returns. + */ + $call(func) { + return func(this); + } + toOperationNode() { + return this.#node; + } + }; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/check-constraint-builder.js +var CheckConstraintBuilder; +var init_check_constraint_builder = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/check-constraint-builder.js"() { + CheckConstraintBuilder = class { + #node; + constructor(node) { + this.#node = node; + } + /** + * Simply calls the provided function passing `this` as the only argument. `$call` returns + * what the provided function returns. + */ + $call(func) { + return func(this); + } + toOperationNode() { + return this.#node; + } + }; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/rename-constraint-node.js +var RenameConstraintNode; +var init_rename_constraint_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/rename-constraint-node.js"() { + init_object_utils(); + init_identifier_node(); + RenameConstraintNode = freeze2({ + is(node) { + return node.kind === "RenameConstraintNode"; + }, + create(oldName, newName) { + return freeze2({ + kind: "RenameConstraintNode", + oldName: IdentifierNode.create(oldName), + newName: IdentifierNode.create(newName) + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/alter-table-builder.js +var AlterTableBuilder, AlterTableColumnAlteringBuilder; +var init_alter_table_builder = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/alter-table-builder.js"() { + init_add_column_node(); + init_alter_table_node(); + init_column_definition_node(); + init_drop_column_node(); + init_identifier_node(); + init_rename_column_node(); + init_object_utils(); + init_column_definition_builder(); + init_modify_column_node(); + init_data_type_parser(); + init_foreign_key_constraint_builder(); + init_add_constraint_node(); + init_unique_constraint_node(); + init_check_constraint_node(); + init_foreign_key_constraint_node(); + init_column_node(); + init_table_parser(); + init_drop_constraint_node(); + init_alter_column_builder(); + init_alter_table_executor(); + init_alter_table_add_foreign_key_constraint_builder(); + init_alter_table_drop_constraint_builder(); + init_primary_key_constraint_node(); + init_drop_index_node(); + init_add_index_node(); + init_alter_table_add_index_builder(); + init_unique_constraint_builder(); + init_primary_key_constraint_builder(); + init_check_constraint_builder(); + init_rename_constraint_node(); + AlterTableBuilder = class { + #props; + constructor(props) { + this.#props = freeze2(props); + } + renameTo(newTableName) { + return new AlterTableExecutor({ + ...this.#props, + node: AlterTableNode.cloneWithTableProps(this.#props.node, { + renameTo: parseTable(newTableName) + }) + }); + } + setSchema(newSchema) { + return new AlterTableExecutor({ + ...this.#props, + node: AlterTableNode.cloneWithTableProps(this.#props.node, { + setSchema: IdentifierNode.create(newSchema) + }) + }); + } + alterColumn(column, alteration) { + const builder = alteration(new AlterColumnBuilder(column)); + return new AlterTableColumnAlteringBuilder({ + ...this.#props, + node: AlterTableNode.cloneWithColumnAlteration(this.#props.node, builder.toOperationNode()) + }); + } + dropColumn(column) { + return new AlterTableColumnAlteringBuilder({ + ...this.#props, + node: AlterTableNode.cloneWithColumnAlteration(this.#props.node, DropColumnNode.create(column)) + }); + } + renameColumn(column, newColumn) { + return new AlterTableColumnAlteringBuilder({ + ...this.#props, + node: AlterTableNode.cloneWithColumnAlteration(this.#props.node, RenameColumnNode.create(column, newColumn)) + }); + } + addColumn(columnName, dataType, build = noop3) { + const builder = build(new ColumnDefinitionBuilder(ColumnDefinitionNode.create(columnName, parseDataTypeExpression(dataType)))); + return new AlterTableColumnAlteringBuilder({ + ...this.#props, + node: AlterTableNode.cloneWithColumnAlteration(this.#props.node, AddColumnNode.create(builder.toOperationNode())) + }); + } + modifyColumn(columnName, dataType, build = noop3) { + const builder = build(new ColumnDefinitionBuilder(ColumnDefinitionNode.create(columnName, parseDataTypeExpression(dataType)))); + return new AlterTableColumnAlteringBuilder({ + ...this.#props, + node: AlterTableNode.cloneWithColumnAlteration(this.#props.node, ModifyColumnNode.create(builder.toOperationNode())) + }); + } + /** + * See {@link CreateTableBuilder.addUniqueConstraint} + */ + addUniqueConstraint(constraintName, columns, build = noop3) { + const uniqueConstraintBuilder = build(new UniqueConstraintNodeBuilder(UniqueConstraintNode.create(columns, constraintName))); + return new AlterTableExecutor({ + ...this.#props, + node: AlterTableNode.cloneWithTableProps(this.#props.node, { + addConstraint: AddConstraintNode.create(uniqueConstraintBuilder.toOperationNode()) + }) + }); + } + /** + * See {@link CreateTableBuilder.addCheckConstraint} + */ + addCheckConstraint(constraintName, checkExpression, build = noop3) { + const constraintBuilder = build(new CheckConstraintBuilder(CheckConstraintNode.create(checkExpression.toOperationNode(), constraintName))); + return new AlterTableExecutor({ + ...this.#props, + node: AlterTableNode.cloneWithTableProps(this.#props.node, { + addConstraint: AddConstraintNode.create(constraintBuilder.toOperationNode()) + }) + }); + } + /** + * See {@link CreateTableBuilder.addForeignKeyConstraint} + * + * Unlike {@link CreateTableBuilder.addForeignKeyConstraint} this method returns + * the constraint builder and doesn't take a callback as the last argument. This + * is because you can only add one column per `ALTER TABLE` query. + */ + addForeignKeyConstraint(constraintName, columns, targetTable, targetColumns, build = noop3) { + const constraintBuilder = build(new ForeignKeyConstraintBuilder(ForeignKeyConstraintNode.create(columns.map(ColumnNode.create), parseTable(targetTable), targetColumns.map(ColumnNode.create), constraintName))); + return new AlterTableAddForeignKeyConstraintBuilder({ + ...this.#props, + constraintBuilder + }); + } + /** + * See {@link CreateTableBuilder.addPrimaryKeyConstraint} + */ + addPrimaryKeyConstraint(constraintName, columns, build = noop3) { + const constraintBuilder = build(new PrimaryKeyConstraintBuilder(PrimaryKeyConstraintNode.create(columns, constraintName))); + return new AlterTableExecutor({ + ...this.#props, + node: AlterTableNode.cloneWithTableProps(this.#props.node, { + addConstraint: AddConstraintNode.create(constraintBuilder.toOperationNode()) + }) + }); + } + dropConstraint(constraintName) { + return new AlterTableDropConstraintBuilder({ + ...this.#props, + node: AlterTableNode.cloneWithTableProps(this.#props.node, { + dropConstraint: DropConstraintNode.create(constraintName) + }) + }); + } + renameConstraint(oldName, newName) { + return new AlterTableDropConstraintBuilder({ + ...this.#props, + node: AlterTableNode.cloneWithTableProps(this.#props.node, { + renameConstraint: RenameConstraintNode.create(oldName, newName) + }) + }); + } + /** + * This can be used to add index to table. + * + * ### Examples + * + * ```ts + * db.schema.alterTable('person') + * .addIndex('person_email_index') + * .column('email') + * .unique() + * .execute() + * ``` + * + * The generated SQL (MySQL): + * + * ```sql + * alter table `person` add unique index `person_email_index` (`email`) + * ``` + */ + addIndex(indexName) { + return new AlterTableAddIndexBuilder({ + ...this.#props, + node: AlterTableNode.cloneWithTableProps(this.#props.node, { + addIndex: AddIndexNode.create(indexName) + }) + }); + } + /** + * This can be used to drop index from table. + * + * ### Examples + * + * ```ts + * db.schema.alterTable('person') + * .dropIndex('person_email_index') + * .execute() + * ``` + * + * The generated SQL (MySQL): + * + * ```sql + * alter table `person` drop index `test_first_name_index` + * ``` + */ + dropIndex(indexName) { + return new AlterTableExecutor({ + ...this.#props, + node: AlterTableNode.cloneWithTableProps(this.#props.node, { + dropIndex: DropIndexNode.create(indexName) + }) + }); + } + /** + * Calls the given function passing `this` as the only argument. + * + * See {@link CreateTableBuilder.$call} + */ + $call(func) { + return func(this); + } + }; + AlterTableColumnAlteringBuilder = class _AlterTableColumnAlteringBuilder { + #props; + constructor(props) { + this.#props = freeze2(props); + } + alterColumn(column, alteration) { + const builder = alteration(new AlterColumnBuilder(column)); + return new _AlterTableColumnAlteringBuilder({ + ...this.#props, + node: AlterTableNode.cloneWithColumnAlteration(this.#props.node, builder.toOperationNode()) + }); + } + dropColumn(column) { + return new _AlterTableColumnAlteringBuilder({ + ...this.#props, + node: AlterTableNode.cloneWithColumnAlteration(this.#props.node, DropColumnNode.create(column)) + }); + } + renameColumn(column, newColumn) { + return new _AlterTableColumnAlteringBuilder({ + ...this.#props, + node: AlterTableNode.cloneWithColumnAlteration(this.#props.node, RenameColumnNode.create(column, newColumn)) + }); + } + addColumn(columnName, dataType, build = noop3) { + const builder = build(new ColumnDefinitionBuilder(ColumnDefinitionNode.create(columnName, parseDataTypeExpression(dataType)))); + return new _AlterTableColumnAlteringBuilder({ + ...this.#props, + node: AlterTableNode.cloneWithColumnAlteration(this.#props.node, AddColumnNode.create(builder.toOperationNode())) + }); + } + modifyColumn(columnName, dataType, build = noop3) { + const builder = build(new ColumnDefinitionBuilder(ColumnDefinitionNode.create(columnName, parseDataTypeExpression(dataType)))); + return new _AlterTableColumnAlteringBuilder({ + ...this.#props, + node: AlterTableNode.cloneWithColumnAlteration(this.#props.node, ModifyColumnNode.create(builder.toOperationNode())) + }); + } + toOperationNode() { + return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId); + } + compile() { + return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId); + } + async execute() { + await this.#props.executor.executeQuery(this.compile()); + } + }; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/immediate-value/immediate-value-transformer.js +var ImmediateValueTransformer; +var init_immediate_value_transformer = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/immediate-value/immediate-value-transformer.js"() { + init_operation_node_transformer(); + init_value_list_node(); + init_value_node(); + ImmediateValueTransformer = class extends OperationNodeTransformer { + transformPrimitiveValueList(node) { + return ValueListNode.create(node.values.map(ValueNode.createImmediate)); + } + transformValue(node) { + return ValueNode.createImmediate(node.value); + } + }; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/create-index-builder.js +var CreateIndexBuilder; +var init_create_index_builder = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/create-index-builder.js"() { + init_create_index_node(); + init_raw_node(); + init_reference_parser(); + init_table_parser(); + init_object_utils(); + init_binary_operation_parser(); + init_query_node(); + init_immediate_value_transformer(); + CreateIndexBuilder = class _CreateIndexBuilder { + #props; + constructor(props) { + this.#props = freeze2(props); + } + /** + * Adds the "if not exists" modifier. + * + * If the index already exists, no error is thrown if this method has been called. + */ + ifNotExists() { + return new _CreateIndexBuilder({ + ...this.#props, + node: CreateIndexNode.cloneWith(this.#props.node, { + ifNotExists: true + }) + }); + } + /** + * Makes the index unique. + */ + unique() { + return new _CreateIndexBuilder({ + ...this.#props, + node: CreateIndexNode.cloneWith(this.#props.node, { + unique: true + }) + }); + } + /** + * Adds `nulls not distinct` specifier to index. + * This only works on some dialects like PostgreSQL. + * + * ### Examples + * + * ```ts + * db.schema.createIndex('person_first_name_index') + * .on('person') + * .column('first_name') + * .nullsNotDistinct() + * .execute() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * create index "person_first_name_index" + * on "test" ("first_name") + * nulls not distinct; + * ``` + */ + nullsNotDistinct() { + return new _CreateIndexBuilder({ + ...this.#props, + node: CreateIndexNode.cloneWith(this.#props.node, { + nullsNotDistinct: true + }) + }); + } + /** + * Specifies the table for the index. + */ + on(table) { + return new _CreateIndexBuilder({ + ...this.#props, + node: CreateIndexNode.cloneWith(this.#props.node, { + table: parseTable(table) + }) + }); + } + /** + * Adds a column to the index. + * + * Also see {@link columns} for adding multiple columns at once or {@link expression} + * for specifying an arbitrary expression. + * + * ### Examples + * + * ```ts + * await db.schema + * .createIndex('person_first_name_and_age_index') + * .on('person') + * .column('first_name') + * .column('age desc') + * .execute() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * create index "person_first_name_and_age_index" on "person" ("first_name", "age" desc) + * ``` + */ + column(column) { + return new _CreateIndexBuilder({ + ...this.#props, + node: CreateIndexNode.cloneWithColumns(this.#props.node, [ + parseOrderedColumnName(column) + ]) + }); + } + /** + * Specifies a list of columns for the index. + * + * Also see {@link column} for adding a single column or {@link expression} for + * specifying an arbitrary expression. + * + * ### Examples + * + * ```ts + * await db.schema + * .createIndex('person_first_name_and_age_index') + * .on('person') + * .columns(['first_name', 'age desc']) + * .execute() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * create index "person_first_name_and_age_index" on "person" ("first_name", "age" desc) + * ``` + */ + columns(columns) { + return new _CreateIndexBuilder({ + ...this.#props, + node: CreateIndexNode.cloneWithColumns(this.#props.node, columns.map(parseOrderedColumnName)) + }); + } + /** + * Specifies an arbitrary expression for the index. + * + * ### Examples + * + * ```ts + * import { sql } from 'kysely' + * + * await db.schema + * .createIndex('person_first_name_index') + * .on('person') + * .expression(sql`first_name COLLATE "fi_FI"`) + * .execute() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * create index "person_first_name_index" on "person" (first_name COLLATE "fi_FI") + * ``` + */ + expression(expression) { + return new _CreateIndexBuilder({ + ...this.#props, + node: CreateIndexNode.cloneWithColumns(this.#props.node, [ + expression.toOperationNode() + ]) + }); + } + using(indexType) { + return new _CreateIndexBuilder({ + ...this.#props, + node: CreateIndexNode.cloneWith(this.#props.node, { + using: RawNode.createWithSql(indexType) + }) + }); + } + where(...args) { + const transformer = new ImmediateValueTransformer(); + return new _CreateIndexBuilder({ + ...this.#props, + node: QueryNode.cloneWithWhere(this.#props.node, transformer.transformNode(parseValueBinaryOperationOrExpression(args), this.#props.queryId)) + }); + } + /** + * Simply calls the provided function passing `this` as the only argument. `$call` returns + * what the provided function returns. + */ + $call(func) { + return func(this); + } + toOperationNode() { + return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId); + } + compile() { + return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId); + } + async execute() { + await this.#props.executor.executeQuery(this.compile()); + } + }; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/create-schema-builder.js +var CreateSchemaBuilder; +var init_create_schema_builder = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/create-schema-builder.js"() { + init_create_schema_node(); + init_object_utils(); + CreateSchemaBuilder = class _CreateSchemaBuilder { + #props; + constructor(props) { + this.#props = freeze2(props); + } + ifNotExists() { + return new _CreateSchemaBuilder({ + ...this.#props, + node: CreateSchemaNode.cloneWith(this.#props.node, { ifNotExists: true }) + }); + } + /** + * Simply calls the provided function passing `this` as the only argument. `$call` returns + * what the provided function returns. + */ + $call(func) { + return func(this); + } + toOperationNode() { + return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId); + } + compile() { + return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId); + } + async execute() { + await this.#props.executor.executeQuery(this.compile()); + } + }; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/on-commit-action-parse.js +function parseOnCommitAction(action) { + if (ON_COMMIT_ACTIONS.includes(action)) { + return action; + } + throw new Error(`invalid OnCommitAction ${action}`); +} +var init_on_commit_action_parse = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/on-commit-action-parse.js"() { + init_create_table_node(); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/create-table-builder.js +var CreateTableBuilder; +var init_create_table_builder = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/create-table-builder.js"() { + init_column_definition_node(); + init_create_table_node(); + init_column_definition_builder(); + init_object_utils(); + init_foreign_key_constraint_node(); + init_column_node(); + init_foreign_key_constraint_builder(); + init_data_type_parser(); + init_primary_key_constraint_node(); + init_unique_constraint_node(); + init_check_constraint_node(); + init_table_parser(); + init_on_commit_action_parse(); + init_unique_constraint_builder(); + init_expression_parser(); + init_primary_key_constraint_builder(); + init_check_constraint_builder(); + CreateTableBuilder = class _CreateTableBuilder { + #props; + constructor(props) { + this.#props = freeze2(props); + } + /** + * Adds the "temporary" modifier. + * + * Use this to create a temporary table. + */ + temporary() { + return new _CreateTableBuilder({ + ...this.#props, + node: CreateTableNode.cloneWith(this.#props.node, { + temporary: true + }) + }); + } + /** + * Adds an "on commit" statement. + * + * This can be used in conjunction with temporary tables on supported databases + * like PostgreSQL. + */ + onCommit(onCommit) { + return new _CreateTableBuilder({ + ...this.#props, + node: CreateTableNode.cloneWith(this.#props.node, { + onCommit: parseOnCommitAction(onCommit) + }) + }); + } + /** + * Adds the "if not exists" modifier. + * + * If the table already exists, no error is thrown if this method has been called. + */ + ifNotExists() { + return new _CreateTableBuilder({ + ...this.#props, + node: CreateTableNode.cloneWith(this.#props.node, { + ifNotExists: true + }) + }); + } + /** + * Adds a column to the table. + * + * ### Examples + * + * ```ts + * import { sql } from 'kysely' + * + * await db.schema + * .createTable('person') + * .addColumn('id', 'integer', (col) => col.autoIncrement().primaryKey()) + * .addColumn('first_name', 'varchar(50)', (col) => col.notNull()) + * .addColumn('last_name', 'varchar(255)') + * .addColumn('bank_balance', 'numeric(8, 2)') + * // You can specify any data type using the `sql` tag if the types + * // don't include it. + * .addColumn('data', sql`any_type_here`) + * .addColumn('parent_id', 'integer', (col) => + * col.references('person.id').onDelete('cascade') + * ) + * ``` + * + * With this method, it's once again good to remember that Kysely just builds the + * query and doesn't provide the same API for all databases. For example, some + * databases like older MySQL don't support the `references` statement in the + * column definition. Instead foreign key constraints need to be defined in the + * `create table` query. See the next example: + * + * ```ts + * await db.schema + * .createTable('person') + * .addColumn('id', 'integer', (col) => col.primaryKey()) + * .addColumn('parent_id', 'integer') + * .addForeignKeyConstraint( + * 'person_parent_id_fk', + * ['parent_id'], + * 'person', + * ['id'], + * (cb) => cb.onDelete('cascade') + * ) + * .execute() + * ``` + * + * Another good example is that PostgreSQL doesn't support the `auto_increment` + * keyword and you need to define an autoincrementing column for example using + * `serial`: + * + * ```ts + * await db.schema + * .createTable('person') + * .addColumn('id', 'serial', (col) => col.primaryKey()) + * .execute() + * ``` + */ + addColumn(columnName, dataType, build = noop3) { + const columnBuilder = build(new ColumnDefinitionBuilder(ColumnDefinitionNode.create(columnName, parseDataTypeExpression(dataType)))); + return new _CreateTableBuilder({ + ...this.#props, + node: CreateTableNode.cloneWithColumn(this.#props.node, columnBuilder.toOperationNode()) + }); + } + /** + * Adds a primary key constraint for one or more columns. + * + * The constraint name can be anything you want, but it must be unique + * across the whole database. + * + * ### Examples + * + * ```ts + * await db.schema + * .createTable('person') + * .addColumn('first_name', 'varchar(64)') + * .addColumn('last_name', 'varchar(64)') + * .addPrimaryKeyConstraint('primary_key', ['first_name', 'last_name']) + * .execute() + * ``` + */ + addPrimaryKeyConstraint(constraintName, columns, build = noop3) { + const constraintBuilder = build(new PrimaryKeyConstraintBuilder(PrimaryKeyConstraintNode.create(columns, constraintName))); + return new _CreateTableBuilder({ + ...this.#props, + node: CreateTableNode.cloneWithConstraint(this.#props.node, constraintBuilder.toOperationNode()) + }); + } + /** + * Adds a unique constraint for one or more columns. + * + * The constraint name can be anything you want, but it must be unique + * across the whole database. + * + * ### Examples + * + * ```ts + * await db.schema + * .createTable('person') + * .addColumn('first_name', 'varchar(64)') + * .addColumn('last_name', 'varchar(64)') + * .addUniqueConstraint( + * 'first_name_last_name_unique', + * ['first_name', 'last_name'] + * ) + * .execute() + * ``` + * + * In dialects such as PostgreSQL you can specify `nulls not distinct` as follows: + * + * ```ts + * await db.schema + * .createTable('person') + * .addColumn('first_name', 'varchar(64)') + * .addColumn('last_name', 'varchar(64)') + * .addUniqueConstraint( + * 'first_name_last_name_unique', + * ['first_name', 'last_name'], + * (cb) => cb.nullsNotDistinct() + * ) + * .execute() + * ``` + */ + addUniqueConstraint(constraintName, columns, build = noop3) { + const uniqueConstraintBuilder = build(new UniqueConstraintNodeBuilder(UniqueConstraintNode.create(columns, constraintName))); + return new _CreateTableBuilder({ + ...this.#props, + node: CreateTableNode.cloneWithConstraint(this.#props.node, uniqueConstraintBuilder.toOperationNode()) + }); + } + /** + * Adds a check constraint. + * + * The constraint name can be anything you want, but it must be unique + * across the whole database. + * + * ### Examples + * + * ```ts + * import { sql } from 'kysely' + * + * await db.schema + * .createTable('animal') + * .addColumn('number_of_legs', 'integer') + * .addCheckConstraint('check_legs', sql`number_of_legs < 5`) + * .execute() + * ``` + */ + addCheckConstraint(constraintName, checkExpression, build = noop3) { + const constraintBuilder = build(new CheckConstraintBuilder(CheckConstraintNode.create(checkExpression.toOperationNode(), constraintName))); + return new _CreateTableBuilder({ + ...this.#props, + node: CreateTableNode.cloneWithConstraint(this.#props.node, constraintBuilder.toOperationNode()) + }); + } + /** + * Adds a foreign key constraint. + * + * The constraint name can be anything you want, but it must be unique + * across the whole database. + * + * ### Examples + * + * ```ts + * await db.schema + * .createTable('pet') + * .addColumn('owner_id', 'integer') + * .addForeignKeyConstraint( + * 'owner_id_foreign', + * ['owner_id'], + * 'person', + * ['id'], + * ) + * .execute() + * ``` + * + * Add constraint for multiple columns: + * + * ```ts + * await db.schema + * .createTable('pet') + * .addColumn('owner_id1', 'integer') + * .addColumn('owner_id2', 'integer') + * .addForeignKeyConstraint( + * 'owner_id_foreign', + * ['owner_id1', 'owner_id2'], + * 'person', + * ['id1', 'id2'], + * (cb) => cb.onDelete('cascade') + * ) + * .execute() + * ``` + */ + addForeignKeyConstraint(constraintName, columns, targetTable, targetColumns, build = noop3) { + const builder = build(new ForeignKeyConstraintBuilder(ForeignKeyConstraintNode.create(columns.map(ColumnNode.create), parseTable(targetTable), targetColumns.map(ColumnNode.create), constraintName))); + return new _CreateTableBuilder({ + ...this.#props, + node: CreateTableNode.cloneWithConstraint(this.#props.node, builder.toOperationNode()) + }); + } + /** + * This can be used to add any additional SQL to the front of the query __after__ the `create` keyword. + * + * Also see {@link temporary}. + * + * ### Examples + * + * ```ts + * import { sql } from 'kysely' + * + * await db.schema + * .createTable('person') + * .modifyFront(sql`global temporary`) + * .addColumn('id', 'integer', col => col.primaryKey()) + * .addColumn('first_name', 'varchar(64)', col => col.notNull()) + * .addColumn('last_name', 'varchar(64)', col => col.notNull()) + * .execute() + * ``` + * + * The generated SQL (Postgres): + * + * ```sql + * create global temporary table "person" ( + * "id" integer primary key, + * "first_name" varchar(64) not null, + * "last_name" varchar(64) not null + * ) + * ``` + */ + modifyFront(modifier) { + return new _CreateTableBuilder({ + ...this.#props, + node: CreateTableNode.cloneWithFrontModifier(this.#props.node, modifier.toOperationNode()) + }); + } + /** + * This can be used to add any additional SQL to the end of the query. + * + * Also see {@link onCommit}. + * + * ### Examples + * + * ```ts + * import { sql } from 'kysely' + * + * await db.schema + * .createTable('person') + * .addColumn('id', 'integer', col => col.primaryKey()) + * .addColumn('first_name', 'varchar(64)', col => col.notNull()) + * .addColumn('last_name', 'varchar(64)', col => col.notNull()) + * .modifyEnd(sql`collate utf8_unicode_ci`) + * .execute() + * ``` + * + * The generated SQL (MySQL): + * + * ```sql + * create table `person` ( + * `id` integer primary key, + * `first_name` varchar(64) not null, + * `last_name` varchar(64) not null + * ) collate utf8_unicode_ci + * ``` + */ + modifyEnd(modifier) { + return new _CreateTableBuilder({ + ...this.#props, + node: CreateTableNode.cloneWithEndModifier(this.#props.node, modifier.toOperationNode()) + }); + } + /** + * Allows to create table from `select` query. + * + * ### Examples + * + * ```ts + * await db.schema + * .createTable('copy') + * .temporary() + * .as(db.selectFrom('person').select(['first_name', 'last_name'])) + * .execute() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * create temporary table "copy" as + * select "first_name", "last_name" from "person" + * ``` + */ + as(expression) { + return new _CreateTableBuilder({ + ...this.#props, + node: CreateTableNode.cloneWith(this.#props.node, { + selectQuery: parseExpression(expression) + }) + }); + } + /** + * Calls the given function passing `this` as the only argument. + * + * ### Examples + * + * ```ts + * await db.schema + * .createTable('test') + * .$call((builder) => builder.addColumn('id', 'integer')) + * .execute() + * ``` + * + * This is useful for creating reusable functions that can be called with a builder. + * + * ```ts + * import { type CreateTableBuilder, sql } from 'kysely' + * + * const addDefaultColumns = (ctb: CreateTableBuilder) => { + * return ctb + * .addColumn('id', 'integer', (col) => col.notNull()) + * .addColumn('created_at', 'date', (col) => + * col.notNull().defaultTo(sql`now()`) + * ) + * .addColumn('updated_at', 'date', (col) => + * col.notNull().defaultTo(sql`now()`) + * ) + * } + * + * await db.schema + * .createTable('test') + * .$call(addDefaultColumns) + * .execute() + * ``` + */ + $call(func) { + return func(this); + } + toOperationNode() { + return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId); + } + compile() { + return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId); + } + async execute() { + await this.#props.executor.executeQuery(this.compile()); + } + }; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/drop-index-builder.js +var DropIndexBuilder; +var init_drop_index_builder = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/drop-index-builder.js"() { + init_drop_index_node(); + init_table_parser(); + init_object_utils(); + DropIndexBuilder = class _DropIndexBuilder { + #props; + constructor(props) { + this.#props = freeze2(props); + } + /** + * Specifies the table the index was created for. This is not needed + * in all dialects. + */ + on(table) { + return new _DropIndexBuilder({ + ...this.#props, + node: DropIndexNode.cloneWith(this.#props.node, { + table: parseTable(table) + }) + }); + } + ifExists() { + return new _DropIndexBuilder({ + ...this.#props, + node: DropIndexNode.cloneWith(this.#props.node, { + ifExists: true + }) + }); + } + cascade() { + return new _DropIndexBuilder({ + ...this.#props, + node: DropIndexNode.cloneWith(this.#props.node, { + cascade: true + }) + }); + } + /** + * Simply calls the provided function passing `this` as the only argument. `$call` returns + * what the provided function returns. + */ + $call(func) { + return func(this); + } + toOperationNode() { + return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId); + } + compile() { + return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId); + } + async execute() { + await this.#props.executor.executeQuery(this.compile()); + } + }; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/drop-schema-builder.js +var DropSchemaBuilder; +var init_drop_schema_builder = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/drop-schema-builder.js"() { + init_drop_schema_node(); + init_object_utils(); + DropSchemaBuilder = class _DropSchemaBuilder { + #props; + constructor(props) { + this.#props = freeze2(props); + } + ifExists() { + return new _DropSchemaBuilder({ + ...this.#props, + node: DropSchemaNode.cloneWith(this.#props.node, { + ifExists: true + }) + }); + } + cascade() { + return new _DropSchemaBuilder({ + ...this.#props, + node: DropSchemaNode.cloneWith(this.#props.node, { + cascade: true + }) + }); + } + /** + * Simply calls the provided function passing `this` as the only argument. `$call` returns + * what the provided function returns. + */ + $call(func) { + return func(this); + } + toOperationNode() { + return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId); + } + compile() { + return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId); + } + async execute() { + await this.#props.executor.executeQuery(this.compile()); + } + }; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/drop-table-builder.js +var DropTableBuilder; +var init_drop_table_builder = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/drop-table-builder.js"() { + init_drop_table_node(); + init_object_utils(); + DropTableBuilder = class _DropTableBuilder { + #props; + constructor(props) { + this.#props = freeze2(props); + } + ifExists() { + return new _DropTableBuilder({ + ...this.#props, + node: DropTableNode.cloneWith(this.#props.node, { + ifExists: true + }) + }); + } + cascade() { + return new _DropTableBuilder({ + ...this.#props, + node: DropTableNode.cloneWith(this.#props.node, { + cascade: true + }) + }); + } + /** + * Simply calls the provided function passing `this` as the only argument. `$call` returns + * what the provided function returns. + */ + $call(func) { + return func(this); + } + toOperationNode() { + return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId); + } + compile() { + return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId); + } + async execute() { + await this.#props.executor.executeQuery(this.compile()); + } + }; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/create-view-node.js +var CreateViewNode; +var init_create_view_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/create-view-node.js"() { + init_object_utils(); + init_schemable_identifier_node(); + CreateViewNode = freeze2({ + is(node) { + return node.kind === "CreateViewNode"; + }, + create(name) { + return freeze2({ + kind: "CreateViewNode", + name: SchemableIdentifierNode.create(name) + }); + }, + cloneWith(createView3, params) { + return freeze2({ + ...createView3, + ...params + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/immediate-value/immediate-value-plugin.js +var ImmediateValuePlugin; +var init_immediate_value_plugin = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/immediate-value/immediate-value-plugin.js"() { + init_immediate_value_transformer(); + ImmediateValuePlugin = class { + #transformer = new ImmediateValueTransformer(); + transformQuery(args) { + return this.#transformer.transformNode(args.node, args.queryId); + } + transformResult(args) { + return Promise.resolve(args.result); + } + }; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/create-view-builder.js +var CreateViewBuilder; +var init_create_view_builder = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/create-view-builder.js"() { + init_object_utils(); + init_create_view_node(); + init_reference_parser(); + init_immediate_value_plugin(); + CreateViewBuilder = class _CreateViewBuilder { + #props; + constructor(props) { + this.#props = freeze2(props); + } + /** + * Adds the "temporary" modifier. + * + * Use this to create a temporary view. + */ + temporary() { + return new _CreateViewBuilder({ + ...this.#props, + node: CreateViewNode.cloneWith(this.#props.node, { + temporary: true + }) + }); + } + materialized() { + return new _CreateViewBuilder({ + ...this.#props, + node: CreateViewNode.cloneWith(this.#props.node, { + materialized: true + }) + }); + } + /** + * Only implemented on some dialects like SQLite. On most dialects, use {@link orReplace}. + */ + ifNotExists() { + return new _CreateViewBuilder({ + ...this.#props, + node: CreateViewNode.cloneWith(this.#props.node, { + ifNotExists: true + }) + }); + } + orReplace() { + return new _CreateViewBuilder({ + ...this.#props, + node: CreateViewNode.cloneWith(this.#props.node, { + orReplace: true + }) + }); + } + columns(columns) { + return new _CreateViewBuilder({ + ...this.#props, + node: CreateViewNode.cloneWith(this.#props.node, { + columns: columns.map(parseColumnName) + }) + }); + } + /** + * Sets the select query or a `values` statement that creates the view. + * + * WARNING! + * Some dialects don't support parameterized queries in DDL statements and therefore + * the query or raw {@link sql } expression passed here is interpolated into a single + * string opening an SQL injection vulnerability. DO NOT pass unchecked user input + * into the query or raw expression passed to this method! + */ + as(query) { + const queryNode = query.withPlugin(new ImmediateValuePlugin()).toOperationNode(); + return new _CreateViewBuilder({ + ...this.#props, + node: CreateViewNode.cloneWith(this.#props.node, { + as: queryNode + }) + }); + } + /** + * Simply calls the provided function passing `this` as the only argument. `$call` returns + * what the provided function returns. + */ + $call(func) { + return func(this); + } + toOperationNode() { + return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId); + } + compile() { + return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId); + } + async execute() { + await this.#props.executor.executeQuery(this.compile()); + } + }; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/drop-view-node.js +var DropViewNode; +var init_drop_view_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/drop-view-node.js"() { + init_object_utils(); + init_schemable_identifier_node(); + DropViewNode = freeze2({ + is(node) { + return node.kind === "DropViewNode"; + }, + create(name) { + return freeze2({ + kind: "DropViewNode", + name: SchemableIdentifierNode.create(name) + }); + }, + cloneWith(dropView, params) { + return freeze2({ + ...dropView, + ...params + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/drop-view-builder.js +var DropViewBuilder; +var init_drop_view_builder = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/drop-view-builder.js"() { + init_object_utils(); + init_drop_view_node(); + DropViewBuilder = class _DropViewBuilder { + #props; + constructor(props) { + this.#props = freeze2(props); + } + materialized() { + return new _DropViewBuilder({ + ...this.#props, + node: DropViewNode.cloneWith(this.#props.node, { + materialized: true + }) + }); + } + ifExists() { + return new _DropViewBuilder({ + ...this.#props, + node: DropViewNode.cloneWith(this.#props.node, { + ifExists: true + }) + }); + } + cascade() { + return new _DropViewBuilder({ + ...this.#props, + node: DropViewNode.cloneWith(this.#props.node, { + cascade: true + }) + }); + } + /** + * Simply calls the provided function passing `this` as the only argument. `$call` returns + * what the provided function returns. + */ + $call(func) { + return func(this); + } + toOperationNode() { + return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId); + } + compile() { + return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId); + } + async execute() { + await this.#props.executor.executeQuery(this.compile()); + } + }; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/create-type-node.js +var CreateTypeNode; +var init_create_type_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/create-type-node.js"() { + init_object_utils(); + init_value_list_node(); + init_value_node(); + CreateTypeNode = freeze2({ + is(node) { + return node.kind === "CreateTypeNode"; + }, + create(name) { + return freeze2({ + kind: "CreateTypeNode", + name + }); + }, + cloneWithEnum(createType, values2) { + return freeze2({ + ...createType, + enum: ValueListNode.create(values2.map(ValueNode.createImmediate)) + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/create-type-builder.js +var CreateTypeBuilder; +var init_create_type_builder = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/create-type-builder.js"() { + init_object_utils(); + init_create_type_node(); + CreateTypeBuilder = class _CreateTypeBuilder { + #props; + constructor(props) { + this.#props = freeze2(props); + } + toOperationNode() { + return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId); + } + /** + * Creates an anum type. + * + * ### Examples + * + * ```ts + * db.schema.createType('species').asEnum(['cat', 'dog', 'frog']) + * ``` + */ + asEnum(values2) { + return new _CreateTypeBuilder({ + ...this.#props, + node: CreateTypeNode.cloneWithEnum(this.#props.node, values2) + }); + } + /** + * Simply calls the provided function passing `this` as the only argument. `$call` returns + * what the provided function returns. + */ + $call(func) { + return func(this); + } + compile() { + return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId); + } + async execute() { + await this.#props.executor.executeQuery(this.compile()); + } + }; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/drop-type-node.js +var DropTypeNode; +var init_drop_type_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/drop-type-node.js"() { + init_object_utils(); + DropTypeNode = freeze2({ + is(node) { + return node.kind === "DropTypeNode"; + }, + create(name) { + return freeze2({ + kind: "DropTypeNode", + name + }); + }, + cloneWith(dropType, params) { + return freeze2({ + ...dropType, + ...params + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/drop-type-builder.js +var DropTypeBuilder; +var init_drop_type_builder = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/drop-type-builder.js"() { + init_drop_type_node(); + init_object_utils(); + DropTypeBuilder = class _DropTypeBuilder { + #props; + constructor(props) { + this.#props = freeze2(props); + } + ifExists() { + return new _DropTypeBuilder({ + ...this.#props, + node: DropTypeNode.cloneWith(this.#props.node, { + ifExists: true + }) + }); + } + /** + * Simply calls the provided function passing `this` as the only argument. `$call` returns + * what the provided function returns. + */ + $call(func) { + return func(this); + } + toOperationNode() { + return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId); + } + compile() { + return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId); + } + async execute() { + await this.#props.executor.executeQuery(this.compile()); + } + }; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/identifier-parser.js +function parseSchemableIdentifier(id) { + const SCHEMA_SEPARATOR = "."; + if (id.includes(SCHEMA_SEPARATOR)) { + const parts = id.split(SCHEMA_SEPARATOR).map(trim3); + if (parts.length === 2) { + return SchemableIdentifierNode.createWithSchema(parts[0], parts[1]); + } else { + throw new Error(`invalid schemable identifier ${id}`); + } + } else { + return SchemableIdentifierNode.create(id); + } +} +function trim3(str) { + return str.trim(); +} +var init_identifier_parser = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/identifier-parser.js"() { + init_schemable_identifier_node(); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/refresh-materialized-view-node.js +var RefreshMaterializedViewNode; +var init_refresh_materialized_view_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/refresh-materialized-view-node.js"() { + init_object_utils(); + init_schemable_identifier_node(); + RefreshMaterializedViewNode = freeze2({ + is(node) { + return node.kind === "RefreshMaterializedViewNode"; + }, + create(name) { + return freeze2({ + kind: "RefreshMaterializedViewNode", + name: SchemableIdentifierNode.create(name) + }); + }, + cloneWith(createView3, params) { + return freeze2({ + ...createView3, + ...params + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/refresh-materialized-view-builder.js +var RefreshMaterializedViewBuilder; +var init_refresh_materialized_view_builder = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/refresh-materialized-view-builder.js"() { + init_object_utils(); + init_refresh_materialized_view_node(); + RefreshMaterializedViewBuilder = class _RefreshMaterializedViewBuilder { + #props; + constructor(props) { + this.#props = freeze2(props); + } + /** + * Adds the "concurrently" modifier. + * + * Use this to refresh the view without locking out concurrent selects on the materialized view. + * + * WARNING! + * This cannot be used with the "with no data" modifier. + */ + concurrently() { + return new _RefreshMaterializedViewBuilder({ + ...this.#props, + node: RefreshMaterializedViewNode.cloneWith(this.#props.node, { + concurrently: true, + withNoData: false + }) + }); + } + /** + * Adds the "with data" modifier. + * + * If specified (or defaults) the backing query is executed to provide the new data, and the materialized view is left in a scannable state + */ + withData() { + return new _RefreshMaterializedViewBuilder({ + ...this.#props, + node: RefreshMaterializedViewNode.cloneWith(this.#props.node, { + withNoData: false + }) + }); + } + /** + * Adds the "with no data" modifier. + * + * If specified, no new data is generated and the materialized view is left in an unscannable state. + * + * WARNING! + * This cannot be used with the "concurrently" modifier. + */ + withNoData() { + return new _RefreshMaterializedViewBuilder({ + ...this.#props, + node: RefreshMaterializedViewNode.cloneWith(this.#props.node, { + withNoData: true, + concurrently: false + }) + }); + } + /** + * Simply calls the provided function passing `this` as the only argument. `$call` returns + * what the provided function returns. + */ + $call(func) { + return func(this); + } + toOperationNode() { + return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId); + } + compile() { + return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId); + } + async execute() { + await this.#props.executor.executeQuery(this.compile()); + } + }; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/schema.js +var SchemaModule; +var init_schema5 = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/schema.js"() { + init_alter_table_node(); + init_create_index_node(); + init_create_schema_node(); + init_create_table_node(); + init_drop_index_node(); + init_drop_schema_node(); + init_drop_table_node(); + init_table_parser(); + init_alter_table_builder(); + init_create_index_builder(); + init_create_schema_builder(); + init_create_table_builder(); + init_drop_index_builder(); + init_drop_schema_builder(); + init_drop_table_builder(); + init_query_id(); + init_with_schema_plugin(); + init_create_view_builder(); + init_create_view_node(); + init_drop_view_builder(); + init_drop_view_node(); + init_create_type_builder(); + init_drop_type_builder(); + init_create_type_node(); + init_drop_type_node(); + init_identifier_parser(); + init_refresh_materialized_view_builder(); + init_refresh_materialized_view_node(); + SchemaModule = class _SchemaModule { + #executor; + constructor(executor) { + this.#executor = executor; + } + /** + * Create a new table. + * + * ### Examples + * + * This example creates a new table with columns `id`, `first_name`, + * `last_name` and `gender`: + * + * ```ts + * await db.schema + * .createTable('person') + * .addColumn('id', 'integer', col => col.primaryKey().autoIncrement()) + * .addColumn('first_name', 'varchar', col => col.notNull()) + * .addColumn('last_name', 'varchar', col => col.notNull()) + * .addColumn('gender', 'varchar') + * .execute() + * ``` + * + * This example creates a table with a foreign key. Not all database + * engines support column-level foreign key constraint definitions. + * For example if you are using MySQL 5.X see the next example after + * this one. + * + * ```ts + * await db.schema + * .createTable('pet') + * .addColumn('id', 'integer', col => col.primaryKey().autoIncrement()) + * .addColumn('owner_id', 'integer', col => col + * .references('person.id') + * .onDelete('cascade') + * ) + * .execute() + * ``` + * + * This example adds a foreign key constraint for a columns just + * like the previous example, but using a table-level statement. + * On MySQL 5.X you need to define foreign key constraints like + * this: + * + * ```ts + * await db.schema + * .createTable('pet') + * .addColumn('id', 'integer', col => col.primaryKey().autoIncrement()) + * .addColumn('owner_id', 'integer') + * .addForeignKeyConstraint( + * 'pet_owner_id_foreign', ['owner_id'], 'person', ['id'], + * (constraint) => constraint.onDelete('cascade') + * ) + * .execute() + * ``` + */ + createTable(table) { + return new CreateTableBuilder({ + queryId: createQueryId(), + executor: this.#executor, + node: CreateTableNode.create(parseTable(table)) + }); + } + /** + * Drop a table. + * + * ### Examples + * + * ```ts + * await db.schema + * .dropTable('person') + * .execute() + * ``` + */ + dropTable(table) { + return new DropTableBuilder({ + queryId: createQueryId(), + executor: this.#executor, + node: DropTableNode.create(parseTable(table)) + }); + } + /** + * Create a new index. + * + * ### Examples + * + * ```ts + * await db.schema + * .createIndex('person_full_name_unique_index') + * .on('person') + * .columns(['first_name', 'last_name']) + * .execute() + * ``` + */ + createIndex(indexName) { + return new CreateIndexBuilder({ + queryId: createQueryId(), + executor: this.#executor, + node: CreateIndexNode.create(indexName) + }); + } + /** + * Drop an index. + * + * ### Examples + * + * ```ts + * await db.schema + * .dropIndex('person_full_name_unique_index') + * .execute() + * ``` + */ + dropIndex(indexName) { + return new DropIndexBuilder({ + queryId: createQueryId(), + executor: this.#executor, + node: DropIndexNode.create(indexName) + }); + } + /** + * Create a new schema. + * + * ### Examples + * + * ```ts + * await db.schema + * .createSchema('some_schema') + * .execute() + * ``` + */ + createSchema(schema2) { + return new CreateSchemaBuilder({ + queryId: createQueryId(), + executor: this.#executor, + node: CreateSchemaNode.create(schema2) + }); + } + /** + * Drop a schema. + * + * ### Examples + * + * ```ts + * await db.schema + * .dropSchema('some_schema') + * .execute() + * ``` + */ + dropSchema(schema2) { + return new DropSchemaBuilder({ + queryId: createQueryId(), + executor: this.#executor, + node: DropSchemaNode.create(schema2) + }); + } + /** + * Alter a table. + * + * ### Examples + * + * ```ts + * await db.schema + * .alterTable('person') + * .alterColumn('first_name', (ac) => ac.setDataType('text')) + * .execute() + * ``` + */ + alterTable(table) { + return new AlterTableBuilder({ + queryId: createQueryId(), + executor: this.#executor, + node: AlterTableNode.create(parseTable(table)) + }); + } + /** + * Create a new view. + * + * ### Examples + * + * ```ts + * await db.schema + * .createView('dogs') + * .orReplace() + * .as(db.selectFrom('pet').selectAll().where('species', '=', 'dog')) + * .execute() + * ``` + */ + createView(viewName) { + return new CreateViewBuilder({ + queryId: createQueryId(), + executor: this.#executor, + node: CreateViewNode.create(viewName) + }); + } + /** + * Refresh a materialized view. + * + * ### Examples + * + * ```ts + * await db.schema + * .refreshMaterializedView('my_view') + * .concurrently() + * .execute() + * ``` + */ + refreshMaterializedView(viewName) { + return new RefreshMaterializedViewBuilder({ + queryId: createQueryId(), + executor: this.#executor, + node: RefreshMaterializedViewNode.create(viewName) + }); + } + /** + * Drop a view. + * + * ### Examples + * + * ```ts + * await db.schema + * .dropView('dogs') + * .ifExists() + * .execute() + * ``` + */ + dropView(viewName) { + return new DropViewBuilder({ + queryId: createQueryId(), + executor: this.#executor, + node: DropViewNode.create(viewName) + }); + } + /** + * Create a new type. + * + * Only some dialects like PostgreSQL have user-defined types. + * + * ### Examples + * + * ```ts + * await db.schema + * .createType('species') + * .asEnum(['dog', 'cat', 'frog']) + * .execute() + * ``` + */ + createType(typeName) { + return new CreateTypeBuilder({ + queryId: createQueryId(), + executor: this.#executor, + node: CreateTypeNode.create(parseSchemableIdentifier(typeName)) + }); + } + /** + * Drop a type. + * + * Only some dialects like PostgreSQL have user-defined types. + * + * ### Examples + * + * ```ts + * await db.schema + * .dropType('species') + * .ifExists() + * .execute() + * ``` + */ + dropType(typeName) { + return new DropTypeBuilder({ + queryId: createQueryId(), + executor: this.#executor, + node: DropTypeNode.create(parseSchemableIdentifier(typeName)) + }); + } + /** + * Returns a copy of this schema module with the given plugin installed. + */ + withPlugin(plugin) { + return new _SchemaModule(this.#executor.withPlugin(plugin)); + } + /** + * Returns a copy of this schema module without any plugins. + */ + withoutPlugins() { + return new _SchemaModule(this.#executor.withoutPlugins()); + } + /** + * See {@link QueryCreator.withSchema} + */ + withSchema(schema2) { + return new _SchemaModule(this.#executor.withPluginAtFront(new WithSchemaPlugin(schema2))); + } + }; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dynamic/dynamic.js +var DynamicModule; +var init_dynamic = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dynamic/dynamic.js"() { + init_dynamic_reference_builder(); + init_dynamic_table_builder(); + DynamicModule = class { + /** + * Creates a dynamic reference to a column that is not know at compile time. + * + * Kysely is built in a way that by default you can't refer to tables or columns + * that are not actually visible in the current query and context. This is all + * done by TypeScript at compile time, which means that you need to know the + * columns and tables at compile time. This is not always the case of course. + * + * This method is meant to be used in those cases where the column names + * come from the user input or are not otherwise known at compile time. + * + * WARNING! Unlike values, column names are not escaped by the database engine + * or Kysely and if you pass in unchecked column names using this method, you + * create an SQL injection vulnerability. Always __always__ validate the user + * input before passing it to this method. + * + * There are couple of examples below for some use cases, but you can pass + * `ref` to other methods as well. If the types allow you to pass a `ref` + * value to some place, it should work. + * + * ### Examples + * + * Filter by a column not know at compile time: + * + * ```ts + * async function someQuery(filterColumn: string, filterValue: string) { + * const { ref } = db.dynamic + * + * return await db + * .selectFrom('person') + * .selectAll() + * .where(ref(filterColumn), '=', filterValue) + * .execute() + * } + * + * someQuery('first_name', 'Arnold') + * someQuery('person.last_name', 'Aniston') + * ``` + * + * Order by a column not know at compile time: + * + * ```ts + * async function someQuery(orderBy: string) { + * const { ref } = db.dynamic + * + * return await db + * .selectFrom('person') + * .select('person.first_name as fn') + * .orderBy(ref(orderBy)) + * .execute() + * } + * + * someQuery('fn') + * ``` + * + * In this example we add selections dynamically: + * + * ```ts + * const { ref } = db.dynamic + * + * // Some column name provided by the user. Value not known at compile time. + * const columnFromUserInput: PossibleColumns = 'birthdate'; + * + * // A type that lists all possible values `columnFromUserInput` can have. + * // You can use `keyof Person` if any column of an interface is allowed. + * type PossibleColumns = 'last_name' | 'first_name' | 'birthdate' + * + * const [person] = await db.selectFrom('person') + * .select([ + * ref(columnFromUserInput), + * 'id' + * ]) + * .execute() + * + * // The resulting type contains all `PossibleColumns` as optional fields + * // because we cannot know which field was actually selected before + * // running the code. + * const lastName: string | null | undefined = person?.last_name + * const firstName: string | undefined = person?.first_name + * const birthDate: Date | null | undefined = person?.birthdate + * + * // The result type also contains the compile time selection `id`. + * person?.id + * ``` + */ + ref(reference) { + return new DynamicReferenceBuilder(reference); + } + /** + * Creates a table reference to a table that's not fully known at compile time. + * + * The type `T` is allowed to be a union of multiple tables. + * + * + * + * A generic type-safe helper function for finding a row by a column value: + * + * ```ts + * import { SelectType } from 'kysely' + * import { Database } from 'type-editor' + * + * async function getRowByColumn< + * T extends keyof Database, + * C extends keyof Database[T] & string, + * V extends SelectType, + * >(t: T, c: C, v: V) { + * // We need to use the dynamic module since the table name + * // is not known at compile time. + * const { table, ref } = db.dynamic + * + * return await db + * .selectFrom(table(t).as('t')) + * .selectAll() + * .where(ref(c), '=', v) + * .orderBy('t.id') + * .executeTakeFirstOrThrow() + * } + * + * const person = await getRowByColumn('person', 'first_name', 'Arnold') + * ``` + */ + table(table) { + return new DynamicTableBuilder(table); + } + }; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/driver/default-connection-provider.js +var DefaultConnectionProvider; +var init_default_connection_provider = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/driver/default-connection-provider.js"() { + DefaultConnectionProvider = class { + #driver; + constructor(driver) { + this.#driver = driver; + } + async provideConnection(consumer) { + const connection2 = await this.#driver.acquireConnection(); + try { + return await consumer(connection2); + } finally { + await this.#driver.releaseConnection(connection2); + } + } + }; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-executor/default-query-executor.js +var DefaultQueryExecutor; +var init_default_query_executor = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-executor/default-query-executor.js"() { + init_query_executor_base(); + DefaultQueryExecutor = class _DefaultQueryExecutor extends QueryExecutorBase { + #compiler; + #adapter; + #connectionProvider; + constructor(compiler, adapter, connectionProvider, plugins2 = []) { + super(plugins2); + this.#compiler = compiler; + this.#adapter = adapter; + this.#connectionProvider = connectionProvider; + } + get adapter() { + return this.#adapter; + } + compileQuery(node, queryId) { + return this.#compiler.compileQuery(node, queryId); + } + provideConnection(consumer) { + return this.#connectionProvider.provideConnection(consumer); + } + withPlugins(plugins2) { + return new _DefaultQueryExecutor(this.#compiler, this.#adapter, this.#connectionProvider, [...this.plugins, ...plugins2]); + } + withPlugin(plugin) { + return new _DefaultQueryExecutor(this.#compiler, this.#adapter, this.#connectionProvider, [...this.plugins, plugin]); + } + withPluginAtFront(plugin) { + return new _DefaultQueryExecutor(this.#compiler, this.#adapter, this.#connectionProvider, [plugin, ...this.plugins]); + } + withConnectionProvider(connectionProvider) { + return new _DefaultQueryExecutor(this.#compiler, this.#adapter, connectionProvider, [...this.plugins]); + } + withoutPlugins() { + return new _DefaultQueryExecutor(this.#compiler, this.#adapter, this.#connectionProvider, []); + } + }; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/performance-now.js +function performanceNow() { + if (typeof performance !== "undefined" && isFunction(performance.now)) { + return performance.now(); + } else { + return Date.now(); + } +} +var init_performance_now = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/performance-now.js"() { + init_object_utils(); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/driver/runtime-driver.js +var RuntimeDriver; +var init_runtime_driver = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/driver/runtime-driver.js"() { + init_performance_now(); + RuntimeDriver = class { + #driver; + #log; + #initPromise; + #initDone; + #destroyPromise; + #connections = /* @__PURE__ */ new WeakSet(); + constructor(driver, log2) { + this.#initDone = false; + this.#driver = driver; + this.#log = log2; + } + async init() { + if (this.#destroyPromise) { + throw new Error("driver has already been destroyed"); + } + if (!this.#initPromise) { + this.#initPromise = this.#driver.init().then(() => { + this.#initDone = true; + }).catch((err) => { + this.#initPromise = void 0; + return Promise.reject(err); + }); + } + await this.#initPromise; + } + async acquireConnection() { + if (this.#destroyPromise) { + throw new Error("driver has already been destroyed"); + } + if (!this.#initDone) { + await this.init(); + } + const connection2 = await this.#driver.acquireConnection(); + if (!this.#connections.has(connection2)) { + if (this.#needsLogging()) { + this.#addLogging(connection2); + } + this.#connections.add(connection2); + } + return connection2; + } + async releaseConnection(connection2) { + await this.#driver.releaseConnection(connection2); + } + beginTransaction(connection2, settings) { + return this.#driver.beginTransaction(connection2, settings); + } + commitTransaction(connection2) { + return this.#driver.commitTransaction(connection2); + } + rollbackTransaction(connection2) { + return this.#driver.rollbackTransaction(connection2); + } + savepoint(connection2, savepointName, compileQuery) { + if (this.#driver.savepoint) { + return this.#driver.savepoint(connection2, savepointName, compileQuery); + } + throw new Error("The `savepoint` method is not supported by this driver"); + } + rollbackToSavepoint(connection2, savepointName, compileQuery) { + if (this.#driver.rollbackToSavepoint) { + return this.#driver.rollbackToSavepoint(connection2, savepointName, compileQuery); + } + throw new Error("The `rollbackToSavepoint` method is not supported by this driver"); + } + releaseSavepoint(connection2, savepointName, compileQuery) { + if (this.#driver.releaseSavepoint) { + return this.#driver.releaseSavepoint(connection2, savepointName, compileQuery); + } + throw new Error("The `releaseSavepoint` method is not supported by this driver"); + } + async destroy() { + if (!this.#initPromise) { + return; + } + await this.#initPromise; + if (!this.#destroyPromise) { + this.#destroyPromise = this.#driver.destroy().catch((err) => { + this.#destroyPromise = void 0; + return Promise.reject(err); + }); + } + await this.#destroyPromise; + } + #needsLogging() { + return this.#log.isLevelEnabled("query") || this.#log.isLevelEnabled("error"); + } + // This method monkey patches the database connection's executeQuery method + // by adding logging code around it. Monkey patching is not pretty, but it's + // the best option in this case. + #addLogging(connection2) { + const executeQuery = connection2.executeQuery; + const streamQuery = connection2.streamQuery; + const dis = this; + connection2.executeQuery = async (compiledQuery) => { + let caughtError; + const startTime = performanceNow(); + try { + return await executeQuery.call(connection2, compiledQuery); + } catch (error50) { + caughtError = error50; + await dis.#logError(error50, compiledQuery, startTime); + throw error50; + } finally { + if (!caughtError) { + await dis.#logQuery(compiledQuery, startTime); + } + } + }; + connection2.streamQuery = async function* (compiledQuery, chunkSize) { + let caughtError; + const startTime = performanceNow(); + try { + for await (const result of streamQuery.call(connection2, compiledQuery, chunkSize)) { + yield result; + } + } catch (error50) { + caughtError = error50; + await dis.#logError(error50, compiledQuery, startTime); + throw error50; + } finally { + if (!caughtError) { + await dis.#logQuery(compiledQuery, startTime, true); + } + } + }; + } + async #logError(error50, compiledQuery, startTime) { + await this.#log.error(() => ({ + level: "error", + error: error50, + query: compiledQuery, + queryDurationMillis: this.#calculateDurationMillis(startTime) + })); + } + async #logQuery(compiledQuery, startTime, isStream = false) { + await this.#log.query(() => ({ + level: "query", + isStream, + query: compiledQuery, + queryDurationMillis: this.#calculateDurationMillis(startTime) + })); + } + #calculateDurationMillis(startTime) { + return performanceNow() - startTime; + } + }; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/driver/single-connection-provider.js +var ignoreError, SingleConnectionProvider; +var init_single_connection_provider = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/driver/single-connection-provider.js"() { + ignoreError = () => { + }; + SingleConnectionProvider = class { + #connection; + #runningPromise; + constructor(connection2) { + this.#connection = connection2; + } + async provideConnection(consumer) { + while (this.#runningPromise) { + await this.#runningPromise.catch(ignoreError); + } + this.#runningPromise = this.#run(consumer).finally(() => { + this.#runningPromise = void 0; + }); + return this.#runningPromise; + } + // Run the runner in an async function to make sure it doesn't + // throw synchronous errors. + async #run(runner) { + return await runner(this.#connection); + } + }; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/driver/driver.js +function validateTransactionSettings(settings) { + if (settings.accessMode && !TRANSACTION_ACCESS_MODES.includes(settings.accessMode)) { + throw new Error(`invalid transaction access mode ${settings.accessMode}`); + } + if (settings.isolationLevel && !TRANSACTION_ISOLATION_LEVELS.includes(settings.isolationLevel)) { + throw new Error(`invalid transaction isolation level ${settings.isolationLevel}`); + } +} +var TRANSACTION_ACCESS_MODES, TRANSACTION_ISOLATION_LEVELS; +var init_driver2 = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/driver/driver.js"() { + TRANSACTION_ACCESS_MODES = ["read only", "read write"]; + TRANSACTION_ISOLATION_LEVELS = [ + "read uncommitted", + "read committed", + "repeatable read", + "serializable", + "snapshot" + ]; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/log.js +function defaultLogger(event) { + if (event.level === "query") { + const prefix = `kysely:query:${event.isStream ? "stream:" : ""}`; + console.log(`${prefix} ${event.query.sql}`); + console.log(`${prefix} duration: ${event.queryDurationMillis.toFixed(1)}ms`); + } else if (event.level === "error") { + if (event.error instanceof Error) { + console.error(`kysely:error: ${event.error.stack ?? event.error.message}`); + } else { + console.error(`kysely:error: ${JSON.stringify({ + error: event.error, + query: event.query.sql, + queryDurationMillis: event.queryDurationMillis + })}`); + } + } +} +var logLevels, LOG_LEVELS, Log; +var init_log = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/log.js"() { + init_object_utils(); + logLevels = ["query", "error"]; + LOG_LEVELS = freeze2(logLevels); + Log = class { + #levels; + #logger; + constructor(config3) { + if (isFunction(config3)) { + this.#logger = config3; + this.#levels = freeze2({ + query: true, + error: true + }); + } else { + this.#logger = defaultLogger; + this.#levels = freeze2({ + query: config3.includes("query"), + error: config3.includes("error") + }); + } + } + isLevelEnabled(level) { + return this.#levels[level]; + } + async query(getEvent) { + if (this.#levels.query) { + await this.#logger(getEvent()); + } + } + async error(getEvent) { + if (this.#levels.error) { + await this.#logger(getEvent()); + } + } + }; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/compilable.js +function isCompilable(value) { + return isObject3(value) && isFunction(value.compile); +} +var init_compilable = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/compilable.js"() { + init_object_utils(); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/kysely.js +function isKyselyProps(obj) { + return isObject3(obj) && isObject3(obj.config) && isObject3(obj.driver) && isObject3(obj.executor) && isObject3(obj.dialect); +} +function assertNotCommittedOrRolledBack(state2) { + if (state2.isCommitted) { + throw new Error("Transaction is already committed"); + } + if (state2.isRolledBack) { + throw new Error("Transaction is already rolled back"); + } +} +var Kysely, Transaction, ConnectionBuilder, TransactionBuilder, ControlledTransactionBuilder, ControlledTransaction, Command, NotCommittedOrRolledBackAssertingExecutor; +var init_kysely = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/kysely.js"() { + init_schema5(); + init_dynamic(); + init_default_connection_provider(); + init_query_creator(); + init_default_query_executor(); + init_object_utils(); + init_runtime_driver(); + init_single_connection_provider(); + init_driver2(); + init_function_module(); + init_log(); + init_query_id(); + init_compilable(); + init_case_builder(); + init_case_node(); + init_expression_parser(); + init_with_schema_plugin(); + init_provide_controlled_connection(); + init_log_once(); + Symbol.asyncDispose ??= /* @__PURE__ */ Symbol("Symbol.asyncDispose"); + Kysely = class _Kysely extends QueryCreator { + #props; + constructor(args) { + let superProps; + let props; + if (isKyselyProps(args)) { + superProps = { executor: args.executor }; + props = { ...args }; + } else { + const dialect = args.dialect; + const driver = dialect.createDriver(); + const compiler = dialect.createQueryCompiler(); + const adapter = dialect.createAdapter(); + const log2 = new Log(args.log ?? []); + const runtimeDriver = new RuntimeDriver(driver, log2); + const connectionProvider = new DefaultConnectionProvider(runtimeDriver); + const executor = new DefaultQueryExecutor(compiler, adapter, connectionProvider, args.plugins ?? []); + superProps = { executor }; + props = { + config: args, + executor, + dialect, + driver: runtimeDriver + }; + } + super(superProps); + this.#props = freeze2(props); + } + /** + * Returns the {@link SchemaModule} module for building database schema. + */ + get schema() { + return new SchemaModule(this.#props.executor); + } + /** + * Returns a the {@link DynamicModule} module. + * + * The {@link DynamicModule} module can be used to bypass strict typing and + * passing in dynamic values for the queries. + */ + get dynamic() { + return new DynamicModule(); + } + /** + * Returns a {@link DatabaseIntrospector | database introspector}. + */ + get introspection() { + return this.#props.dialect.createIntrospector(this.withoutPlugins()); + } + case(value) { + return new CaseBuilder({ + node: CaseNode.create(isUndefined(value) ? void 0 : parseExpression(value)) + }); + } + /** + * Returns a {@link FunctionModule} that can be used to write somewhat type-safe function + * calls. + * + * ```ts + * const { count } = db.fn + * + * await db.selectFrom('person') + * .innerJoin('pet', 'pet.owner_id', 'person.id') + * .select([ + * 'id', + * count('pet.id').as('person_count'), + * ]) + * .groupBy('person.id') + * .having(count('pet.id'), '>', 10) + * .execute() + * ``` + * + * The generated SQL (PostgreSQL): + * + * ```sql + * select "person"."id", count("pet"."id") as "person_count" + * from "person" + * inner join "pet" on "pet"."owner_id" = "person"."id" + * group by "person"."id" + * having count("pet"."id") > $1 + * ``` + * + * Why "somewhat" type-safe? Because the function calls are not bound to the + * current query context. They allow you to reference columns and tables that + * are not in the current query. E.g. remove the `innerJoin` from the previous + * query and TypeScript won't even complain. + * + * If you want to make the function calls fully type-safe, you can use the + * {@link ExpressionBuilder.fn} getter for a query context-aware, stricter {@link FunctionModule}. + * + * ```ts + * await db.selectFrom('person') + * .innerJoin('pet', 'pet.owner_id', 'person.id') + * .select((eb) => [ + * 'person.id', + * eb.fn.count('pet.id').as('pet_count') + * ]) + * .groupBy('person.id') + * .having((eb) => eb.fn.count('pet.id'), '>', 10) + * .execute() + * ``` + */ + get fn() { + return createFunctionModule(); + } + /** + * Creates a {@link TransactionBuilder} that can be used to run queries inside a transaction. + * + * The returned {@link TransactionBuilder} can be used to configure the transaction. The + * {@link TransactionBuilder.execute} method can then be called to run the transaction. + * {@link TransactionBuilder.execute} takes a function that is run inside the + * transaction. If the function throws an exception, + * 1. the exception is caught, + * 2. the transaction is rolled back, and + * 3. the exception is thrown again. + * Otherwise the transaction is committed. + * + * The callback function passed to the {@link TransactionBuilder.execute | execute} + * method gets the transaction object as its only argument. The transaction is + * of type {@link Transaction} which inherits {@link Kysely}. Any query + * started through the transaction object is executed inside the transaction. + * + * To run a controlled transaction, allowing you to commit and rollback manually, + * use {@link startTransaction} instead. + * + * ### Examples + * + * + * + * This example inserts two rows in a transaction. If an exception is thrown inside + * the callback passed to the `execute` method, + * 1. the exception is caught, + * 2. the transaction is rolled back, and + * 3. the exception is thrown again. + * Otherwise the transaction is committed. + * + * ```ts + * const catto = await db.transaction().execute(async (trx) => { + * const jennifer = await trx.insertInto('person') + * .values({ + * first_name: 'Jennifer', + * last_name: 'Aniston', + * age: 40, + * }) + * .returning('id') + * .executeTakeFirstOrThrow() + * + * return await trx.insertInto('pet') + * .values({ + * owner_id: jennifer.id, + * name: 'Catto', + * species: 'cat', + * is_favorite: false, + * }) + * .returningAll() + * .executeTakeFirst() + * }) + * ``` + * + * Setting the isolation level: + * + * ```ts + * import type { Kysely } from 'kysely' + * + * await db + * .transaction() + * .setIsolationLevel('serializable') + * .execute(async (trx) => { + * await doStuff(trx) + * }) + * + * async function doStuff(kysely: typeof db) { + * // ... + * } + * ``` + */ + transaction() { + return new TransactionBuilder({ ...this.#props }); + } + /** + * Creates a {@link ControlledTransactionBuilder} that can be used to run queries inside a controlled transaction. + * + * The returned {@link ControlledTransactionBuilder} can be used to configure the transaction. + * The {@link ControlledTransactionBuilder.execute} method can then be called + * to start the transaction and return a {@link ControlledTransaction}. + * + * A {@link ControlledTransaction} allows you to commit and rollback manually, + * execute savepoint commands. It extends {@link Transaction} which extends {@link Kysely}, + * so you can run queries inside the transaction. Once the transaction is committed, + * or rolled back, it can't be used anymore - all queries will throw an error. + * This is to prevent accidentally running queries outside the transaction - where + * atomicity is not guaranteed anymore. + * + * ### Examples + * + * + * + * A controlled transaction allows you to commit and rollback manually, execute + * savepoint commands, and queries in general. + * + * In this example we start a transaction, use it to insert two rows and then commit + * the transaction. If an error is thrown, we catch it and rollback the transaction. + * + * ```ts + * const trx = await db.startTransaction().execute() + * + * try { + * const jennifer = await trx.insertInto('person') + * .values({ + * first_name: 'Jennifer', + * last_name: 'Aniston', + * age: 40, + * }) + * .returning('id') + * .executeTakeFirstOrThrow() + * + * const catto = await trx.insertInto('pet') + * .values({ + * owner_id: jennifer.id, + * name: 'Catto', + * species: 'cat', + * is_favorite: false, + * }) + * .returningAll() + * .executeTakeFirstOrThrow() + * + * await trx.commit().execute() + * + * // ... + * } catch (error) { + * await trx.rollback().execute() + * } + * ``` + * + * + * + * A controlled transaction allows you to commit and rollback manually, execute + * savepoint commands, and queries in general. + * + * In this example we start a transaction, insert a person, create a savepoint, + * try inserting a toy and a pet, and if an error is thrown, we rollback to the + * savepoint. Eventually we release the savepoint, insert an audit record and + * commit the transaction. If an error is thrown, we catch it and rollback the + * transaction. + * + * ```ts + * const trx = await db.startTransaction().execute() + * + * try { + * const jennifer = await trx + * .insertInto('person') + * .values({ + * first_name: 'Jennifer', + * last_name: 'Aniston', + * age: 40, + * }) + * .returning('id') + * .executeTakeFirstOrThrow() + * + * const trxAfterJennifer = await trx.savepoint('after_jennifer').execute() + * + * try { + * const catto = await trxAfterJennifer + * .insertInto('pet') + * .values({ + * owner_id: jennifer.id, + * name: 'Catto', + * species: 'cat', + * }) + * .returning('id') + * .executeTakeFirstOrThrow() + * + * await trxAfterJennifer + * .insertInto('toy') + * .values({ name: 'Bone', price: 1.99, pet_id: catto.id }) + * .execute() + * } catch (error) { + * await trxAfterJennifer.rollbackToSavepoint('after_jennifer').execute() + * } + * + * await trxAfterJennifer.releaseSavepoint('after_jennifer').execute() + * + * await trx.insertInto('audit').values({ action: 'added Jennifer' }).execute() + * + * await trx.commit().execute() + * } catch (error) { + * await trx.rollback().execute() + * } + * ``` + */ + startTransaction() { + return new ControlledTransactionBuilder({ ...this.#props }); + } + /** + * Provides a kysely instance bound to a single database connection. + * + * ### Examples + * + * ```ts + * await db + * .connection() + * .execute(async (db) => { + * // `db` is an instance of `Kysely` that's bound to a single + * // database connection. All queries executed through `db` use + * // the same connection. + * await doStuff(db) + * }) + * + * async function doStuff(kysely: typeof db) { + * // ... + * } + * ``` + */ + connection() { + return new ConnectionBuilder({ ...this.#props }); + } + /** + * Returns a copy of this Kysely instance with the given plugin installed. + */ + withPlugin(plugin) { + return new _Kysely({ + ...this.#props, + executor: this.#props.executor.withPlugin(plugin) + }); + } + /** + * Returns a copy of this Kysely instance without any plugins. + */ + withoutPlugins() { + return new _Kysely({ + ...this.#props, + executor: this.#props.executor.withoutPlugins() + }); + } + /** + * @override + */ + withSchema(schema2) { + return new _Kysely({ + ...this.#props, + executor: this.#props.executor.withPluginAtFront(new WithSchemaPlugin(schema2)) + }); + } + /** + * Returns a copy of this Kysely instance with tables added to its + * database type. + * + * This method only modifies the types and doesn't affect any of the + * executed queries in any way. + * + * ### Examples + * + * The following example adds and uses a temporary table: + * + * ```ts + * await db.schema + * .createTable('temp_table') + * .temporary() + * .addColumn('some_column', 'integer') + * .execute() + * + * const tempDb = db.withTables<{ + * temp_table: { + * some_column: number + * } + * }>() + * + * await tempDb + * .insertInto('temp_table') + * .values({ some_column: 100 }) + * .execute() + * ``` + */ + withTables() { + return new _Kysely({ ...this.#props }); + } + /** + * Releases all resources and disconnects from the database. + * + * You need to call this when you are done using the `Kysely` instance. + */ + async destroy() { + await this.#props.driver.destroy(); + } + /** + * Returns true if this `Kysely` instance is a transaction. + * + * You can also use `db instanceof Transaction`. + */ + get isTransaction() { + return false; + } + /** + * @internal + * @private + */ + getExecutor() { + return this.#props.executor; + } + /** + * Executes a given compiled query or query builder. + * + * See {@link https://github.com/kysely-org/kysely/blob/master/site/docs/recipes/0004-splitting-query-building-and-execution.md#execute-compiled-queries splitting build, compile and execute code recipe} for more information. + */ + executeQuery(query, queryId) { + if (queryId !== void 0) { + logOnce("Passing `queryId` in `db.executeQuery` is deprecated and will result in a compile-time error in the future."); + } + const compiledQuery = isCompilable(query) ? query.compile() : query; + return this.getExecutor().executeQuery(compiledQuery); + } + async [Symbol.asyncDispose]() { + await this.destroy(); + } + }; + Transaction = class _Transaction extends Kysely { + #props; + constructor(props) { + super(props); + this.#props = props; + } + // The return type is `true` instead of `boolean` to make Kysely + // unassignable to Transaction while allowing assignment the + // other way around. + get isTransaction() { + return true; + } + transaction() { + throw new Error("calling the transaction method for a Transaction is not supported"); + } + connection() { + throw new Error("calling the connection method for a Transaction is not supported"); + } + async destroy() { + throw new Error("calling the destroy method for a Transaction is not supported"); + } + withPlugin(plugin) { + return new _Transaction({ + ...this.#props, + executor: this.#props.executor.withPlugin(plugin) + }); + } + withoutPlugins() { + return new _Transaction({ + ...this.#props, + executor: this.#props.executor.withoutPlugins() + }); + } + withSchema(schema2) { + return new _Transaction({ + ...this.#props, + executor: this.#props.executor.withPluginAtFront(new WithSchemaPlugin(schema2)) + }); + } + withTables() { + return new _Transaction({ ...this.#props }); + } + }; + ConnectionBuilder = class { + #props; + constructor(props) { + this.#props = freeze2(props); + } + async execute(callback) { + return this.#props.executor.provideConnection(async (connection2) => { + const executor = this.#props.executor.withConnectionProvider(new SingleConnectionProvider(connection2)); + const db = new Kysely({ + ...this.#props, + executor + }); + return await callback(db); + }); + } + }; + TransactionBuilder = class _TransactionBuilder { + #props; + constructor(props) { + this.#props = freeze2(props); + } + setAccessMode(accessMode) { + return new _TransactionBuilder({ + ...this.#props, + accessMode + }); + } + setIsolationLevel(isolationLevel) { + return new _TransactionBuilder({ + ...this.#props, + isolationLevel + }); + } + async execute(callback) { + const { isolationLevel, accessMode, ...kyselyProps } = this.#props; + const settings = { isolationLevel, accessMode }; + validateTransactionSettings(settings); + return this.#props.executor.provideConnection(async (connection2) => { + const state2 = { isCommitted: false, isRolledBack: false }; + const executor = new NotCommittedOrRolledBackAssertingExecutor(this.#props.executor.withConnectionProvider(new SingleConnectionProvider(connection2)), state2); + const transaction = new Transaction({ + ...kyselyProps, + executor + }); + let transactionBegun = false; + try { + await this.#props.driver.beginTransaction(connection2, settings); + transactionBegun = true; + const result = await callback(transaction); + await this.#props.driver.commitTransaction(connection2); + state2.isCommitted = true; + return result; + } catch (error50) { + if (transactionBegun) { + await this.#props.driver.rollbackTransaction(connection2); + state2.isRolledBack = true; + } + throw error50; + } + }); + } + }; + ControlledTransactionBuilder = class _ControlledTransactionBuilder { + #props; + constructor(props) { + this.#props = freeze2(props); + } + setAccessMode(accessMode) { + return new _ControlledTransactionBuilder({ + ...this.#props, + accessMode + }); + } + setIsolationLevel(isolationLevel) { + return new _ControlledTransactionBuilder({ + ...this.#props, + isolationLevel + }); + } + async execute() { + const { isolationLevel, accessMode, ...props } = this.#props; + const settings = { isolationLevel, accessMode }; + validateTransactionSettings(settings); + const connection2 = await provideControlledConnection(this.#props.executor); + await this.#props.driver.beginTransaction(connection2.connection, settings); + return new ControlledTransaction({ + ...props, + connection: connection2, + executor: this.#props.executor.withConnectionProvider(new SingleConnectionProvider(connection2.connection)) + }); + } + }; + ControlledTransaction = class _ControlledTransaction extends Transaction { + #props; + #compileQuery; + #state; + constructor(props) { + const state2 = { isCommitted: false, isRolledBack: false }; + props = { + ...props, + executor: new NotCommittedOrRolledBackAssertingExecutor(props.executor, state2) + }; + const { connection: connection2, ...transactionProps } = props; + super(transactionProps); + this.#props = freeze2(props); + this.#state = state2; + const queryId = createQueryId(); + this.#compileQuery = (node) => props.executor.compileQuery(node, queryId); + } + get isCommitted() { + return this.#state.isCommitted; + } + get isRolledBack() { + return this.#state.isRolledBack; + } + /** + * Commits the transaction. + * + * See {@link rollback}. + * + * ### Examples + * + * ```ts + * import type { Kysely } from 'kysely' + * import type { Database } from 'type-editor' // imaginary module + * + * const trx = await db.startTransaction().execute() + * + * try { + * await doSomething(trx) + * + * await trx.commit().execute() + * } catch (error) { + * await trx.rollback().execute() + * } + * + * async function doSomething(kysely: Kysely) {} + * ``` + */ + commit() { + assertNotCommittedOrRolledBack(this.#state); + return new Command(async () => { + await this.#props.driver.commitTransaction(this.#props.connection.connection); + this.#state.isCommitted = true; + this.#props.connection.release(); + }); + } + /** + * Rolls back the transaction. + * + * See {@link commit} and {@link rollbackToSavepoint}. + * + * ### Examples + * + * ```ts + * import type { Kysely } from 'kysely' + * import type { Database } from 'type-editor' // imaginary module + * + * const trx = await db.startTransaction().execute() + * + * try { + * await doSomething(trx) + * + * await trx.commit().execute() + * } catch (error) { + * await trx.rollback().execute() + * } + * + * async function doSomething(kysely: Kysely) {} + * ``` + */ + rollback() { + assertNotCommittedOrRolledBack(this.#state); + return new Command(async () => { + await this.#props.driver.rollbackTransaction(this.#props.connection.connection); + this.#state.isRolledBack = true; + this.#props.connection.release(); + }); + } + /** + * Creates a savepoint with a given name. + * + * See {@link rollbackToSavepoint} and {@link releaseSavepoint}. + * + * For a type-safe experience, you should use the returned instance from now on. + * + * ### Examples + * + * ```ts + * import type { Kysely } from 'kysely' + * import type { Database } from 'type-editor' // imaginary module + * + * const trx = await db.startTransaction().execute() + * + * await insertJennifer(trx) + * + * const trxAfterJennifer = await trx.savepoint('after_jennifer').execute() + * + * try { + * await doSomething(trxAfterJennifer) + * } catch (error) { + * await trxAfterJennifer.rollbackToSavepoint('after_jennifer').execute() + * } + * + * async function insertJennifer(kysely: Kysely) {} + * async function doSomething(kysely: Kysely) {} + * ``` + */ + savepoint(savepointName) { + assertNotCommittedOrRolledBack(this.#state); + return new Command(async () => { + await this.#props.driver.savepoint?.(this.#props.connection.connection, savepointName, this.#compileQuery); + return new _ControlledTransaction({ ...this.#props }); + }); + } + /** + * Rolls back to a savepoint with a given name. + * + * See {@link savepoint} and {@link releaseSavepoint}. + * + * You must use the same instance returned by {@link savepoint}, or + * escape the type-check by using `as any`. + * + * ### Examples + * + * ```ts + * import type { Kysely } from 'kysely' + * import type { Database } from 'type-editor' // imaginary module + * + * const trx = await db.startTransaction().execute() + * + * await insertJennifer(trx) + * + * const trxAfterJennifer = await trx.savepoint('after_jennifer').execute() + * + * try { + * await doSomething(trxAfterJennifer) + * } catch (error) { + * await trxAfterJennifer.rollbackToSavepoint('after_jennifer').execute() + * } + * + * async function insertJennifer(kysely: Kysely) {} + * async function doSomething(kysely: Kysely) {} + * ``` + */ + rollbackToSavepoint(savepointName) { + assertNotCommittedOrRolledBack(this.#state); + return new Command(async () => { + await this.#props.driver.rollbackToSavepoint?.(this.#props.connection.connection, savepointName, this.#compileQuery); + return new _ControlledTransaction({ ...this.#props }); + }); + } + /** + * Releases a savepoint with a given name. + * + * See {@link savepoint} and {@link rollbackToSavepoint}. + * + * You must use the same instance returned by {@link savepoint}, or + * escape the type-check by using `as any`. + * + * ### Examples + * + * ```ts + * import type { Kysely } from 'kysely' + * import type { Database } from 'type-editor' // imaginary module + * + * const trx = await db.startTransaction().execute() + * + * await insertJennifer(trx) + * + * const trxAfterJennifer = await trx.savepoint('after_jennifer').execute() + * + * try { + * await doSomething(trxAfterJennifer) + * } catch (error) { + * await trxAfterJennifer.rollbackToSavepoint('after_jennifer').execute() + * } + * + * await trxAfterJennifer.releaseSavepoint('after_jennifer').execute() + * + * await doSomethingElse(trx) + * + * async function insertJennifer(kysely: Kysely) {} + * async function doSomething(kysely: Kysely) {} + * async function doSomethingElse(kysely: Kysely) {} + * ``` + */ + releaseSavepoint(savepointName) { + assertNotCommittedOrRolledBack(this.#state); + return new Command(async () => { + await this.#props.driver.releaseSavepoint?.(this.#props.connection.connection, savepointName, this.#compileQuery); + return new _ControlledTransaction({ ...this.#props }); + }); + } + withPlugin(plugin) { + return new _ControlledTransaction({ + ...this.#props, + executor: this.#props.executor.withPlugin(plugin) + }); + } + withoutPlugins() { + return new _ControlledTransaction({ + ...this.#props, + executor: this.#props.executor.withoutPlugins() + }); + } + withSchema(schema2) { + return new _ControlledTransaction({ + ...this.#props, + executor: this.#props.executor.withPluginAtFront(new WithSchemaPlugin(schema2)) + }); + } + withTables() { + return new _ControlledTransaction({ ...this.#props }); + } + }; + Command = class { + #cb; + constructor(cb) { + this.#cb = cb; + } + /** + * Executes the command. + */ + async execute() { + return await this.#cb(); + } + }; + NotCommittedOrRolledBackAssertingExecutor = class _NotCommittedOrRolledBackAssertingExecutor { + #executor; + #state; + constructor(executor, state2) { + if (executor instanceof _NotCommittedOrRolledBackAssertingExecutor) { + this.#executor = executor.#executor; + } else { + this.#executor = executor; + } + this.#state = state2; + } + get adapter() { + return this.#executor.adapter; + } + get plugins() { + return this.#executor.plugins; + } + transformQuery(node, queryId) { + return this.#executor.transformQuery(node, queryId); + } + compileQuery(node, queryId) { + return this.#executor.compileQuery(node, queryId); + } + provideConnection(consumer) { + return this.#executor.provideConnection(consumer); + } + executeQuery(compiledQuery) { + assertNotCommittedOrRolledBack(this.#state); + return this.#executor.executeQuery(compiledQuery); + } + stream(compiledQuery, chunkSize) { + assertNotCommittedOrRolledBack(this.#state); + return this.#executor.stream(compiledQuery, chunkSize); + } + withConnectionProvider(connectionProvider) { + return new _NotCommittedOrRolledBackAssertingExecutor(this.#executor.withConnectionProvider(connectionProvider), this.#state); + } + withPlugin(plugin) { + return new _NotCommittedOrRolledBackAssertingExecutor(this.#executor.withPlugin(plugin), this.#state); + } + withPlugins(plugins2) { + return new _NotCommittedOrRolledBackAssertingExecutor(this.#executor.withPlugins(plugins2), this.#state); + } + withPluginAtFront(plugin) { + return new _NotCommittedOrRolledBackAssertingExecutor(this.#executor.withPluginAtFront(plugin), this.#state); + } + withoutPlugins() { + return new _NotCommittedOrRolledBackAssertingExecutor(this.#executor.withoutPlugins(), this.#state); + } + }; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/where-interface.js +var init_where_interface = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/where-interface.js"() { + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/returning-interface.js +var init_returning_interface = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/returning-interface.js"() { + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/output-interface.js +var init_output_interface = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/output-interface.js"() { + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/having-interface.js +var init_having_interface = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/having-interface.js"() { + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/order-by-interface.js +var init_order_by_interface = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/order-by-interface.js"() { + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/raw-builder/raw-builder.js +function createRawBuilder(props) { + return new RawBuilderImpl(props); +} +var RawBuilderImpl, AliasedRawBuilderImpl; +var init_raw_builder = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/raw-builder/raw-builder.js"() { + init_alias_node(); + init_object_utils(); + init_noop_query_executor(); + init_identifier_node(); + init_operation_node_source(); + RawBuilderImpl = class _RawBuilderImpl { + #props; + constructor(props) { + this.#props = freeze2(props); + } + get expressionType() { + return void 0; + } + get isRawBuilder() { + return true; + } + as(alias) { + return new AliasedRawBuilderImpl(this, alias); + } + $castTo() { + return new _RawBuilderImpl({ ...this.#props }); + } + $notNull() { + return new _RawBuilderImpl(this.#props); + } + withPlugin(plugin) { + return new _RawBuilderImpl({ + ...this.#props, + plugins: this.#props.plugins !== void 0 ? freeze2([...this.#props.plugins, plugin]) : freeze2([plugin]) + }); + } + toOperationNode() { + return this.#toOperationNode(this.#getExecutor()); + } + compile(executorProvider) { + return this.#compile(this.#getExecutor(executorProvider)); + } + async execute(executorProvider) { + const executor = this.#getExecutor(executorProvider); + return executor.executeQuery(this.#compile(executor)); + } + #getExecutor(executorProvider) { + const executor = executorProvider !== void 0 ? executorProvider.getExecutor() : NOOP_QUERY_EXECUTOR; + return this.#props.plugins !== void 0 ? executor.withPlugins(this.#props.plugins) : executor; + } + #toOperationNode(executor) { + return executor.transformQuery(this.#props.rawNode, this.#props.queryId); + } + #compile(executor) { + return executor.compileQuery(this.#toOperationNode(executor), this.#props.queryId); + } + }; + AliasedRawBuilderImpl = class { + #rawBuilder; + #alias; + constructor(rawBuilder, alias) { + this.#rawBuilder = rawBuilder; + this.#alias = alias; + } + get expression() { + return this.#rawBuilder; + } + get alias() { + return this.#alias; + } + get rawBuilder() { + return this.#rawBuilder; + } + toOperationNode() { + return AliasNode.create(this.#rawBuilder.toOperationNode(), isOperationNodeSource(this.#alias) ? this.#alias.toOperationNode() : IdentifierNode.create(this.#alias)); + } + }; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/raw-builder/sql.js +function parseParameter(param) { + if (isOperationNodeSource(param)) { + return param.toOperationNode(); + } + return parseValueExpression(param); +} +var sql2; +var init_sql3 = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/raw-builder/sql.js"() { + init_identifier_node(); + init_operation_node_source(); + init_raw_node(); + init_value_node(); + init_reference_parser(); + init_table_parser(); + init_value_parser(); + init_query_id(); + init_raw_builder(); + sql2 = Object.assign((sqlFragments, ...parameters) => { + return createRawBuilder({ + queryId: createQueryId(), + rawNode: RawNode.create(sqlFragments, parameters?.map(parseParameter) ?? []) + }); + }, { + ref(columnReference) { + return createRawBuilder({ + queryId: createQueryId(), + rawNode: RawNode.createWithChild(parseStringReference(columnReference)) + }); + }, + val(value) { + return createRawBuilder({ + queryId: createQueryId(), + rawNode: RawNode.createWithChild(parseValueExpression(value)) + }); + }, + value(value) { + return this.val(value); + }, + table(tableReference) { + return createRawBuilder({ + queryId: createQueryId(), + rawNode: RawNode.createWithChild(parseTable(tableReference)) + }); + }, + id(...ids) { + const fragments = new Array(ids.length + 1).fill("."); + fragments[0] = ""; + fragments[fragments.length - 1] = ""; + return createRawBuilder({ + queryId: createQueryId(), + rawNode: RawNode.create(fragments, ids.map(IdentifierNode.create)) + }); + }, + lit(value) { + return createRawBuilder({ + queryId: createQueryId(), + rawNode: RawNode.createWithChild(ValueNode.createImmediate(value)) + }); + }, + literal(value) { + return this.lit(value); + }, + raw(sql3) { + return createRawBuilder({ + queryId: createQueryId(), + rawNode: RawNode.createWithSql(sql3) + }); + }, + join(array2, separator = sql2`, `) { + const nodes = new Array(Math.max(2 * array2.length - 1, 0)); + const sep = separator.toOperationNode(); + for (let i5 = 0; i5 < array2.length; ++i5) { + nodes[2 * i5] = parseParameter(array2[i5]); + if (i5 !== array2.length - 1) { + nodes[2 * i5 + 1] = sep; + } + } + return createRawBuilder({ + queryId: createQueryId(), + rawNode: RawNode.createWithChildren(nodes) + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-executor/query-executor.js +var init_query_executor = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-executor/query-executor.js"() { + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-executor/query-executor-provider.js +var init_query_executor_provider = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-executor/query-executor-provider.js"() { + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/operation-node-visitor.js +var OperationNodeVisitor; +var init_operation_node_visitor = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/operation-node-visitor.js"() { + init_object_utils(); + OperationNodeVisitor = class { + nodeStack = []; + get parentNode() { + return this.nodeStack[this.nodeStack.length - 2]; + } + #visitors = freeze2({ + AliasNode: this.visitAlias.bind(this), + ColumnNode: this.visitColumn.bind(this), + IdentifierNode: this.visitIdentifier.bind(this), + SchemableIdentifierNode: this.visitSchemableIdentifier.bind(this), + RawNode: this.visitRaw.bind(this), + ReferenceNode: this.visitReference.bind(this), + SelectQueryNode: this.visitSelectQuery.bind(this), + SelectionNode: this.visitSelection.bind(this), + TableNode: this.visitTable.bind(this), + FromNode: this.visitFrom.bind(this), + SelectAllNode: this.visitSelectAll.bind(this), + AndNode: this.visitAnd.bind(this), + OrNode: this.visitOr.bind(this), + ValueNode: this.visitValue.bind(this), + ValueListNode: this.visitValueList.bind(this), + PrimitiveValueListNode: this.visitPrimitiveValueList.bind(this), + ParensNode: this.visitParens.bind(this), + JoinNode: this.visitJoin.bind(this), + OperatorNode: this.visitOperator.bind(this), + WhereNode: this.visitWhere.bind(this), + InsertQueryNode: this.visitInsertQuery.bind(this), + DeleteQueryNode: this.visitDeleteQuery.bind(this), + ReturningNode: this.visitReturning.bind(this), + CreateTableNode: this.visitCreateTable.bind(this), + AddColumnNode: this.visitAddColumn.bind(this), + ColumnDefinitionNode: this.visitColumnDefinition.bind(this), + DropTableNode: this.visitDropTable.bind(this), + DataTypeNode: this.visitDataType.bind(this), + OrderByNode: this.visitOrderBy.bind(this), + OrderByItemNode: this.visitOrderByItem.bind(this), + GroupByNode: this.visitGroupBy.bind(this), + GroupByItemNode: this.visitGroupByItem.bind(this), + UpdateQueryNode: this.visitUpdateQuery.bind(this), + ColumnUpdateNode: this.visitColumnUpdate.bind(this), + LimitNode: this.visitLimit.bind(this), + OffsetNode: this.visitOffset.bind(this), + OnConflictNode: this.visitOnConflict.bind(this), + OnDuplicateKeyNode: this.visitOnDuplicateKey.bind(this), + CreateIndexNode: this.visitCreateIndex.bind(this), + DropIndexNode: this.visitDropIndex.bind(this), + ListNode: this.visitList.bind(this), + PrimaryKeyConstraintNode: this.visitPrimaryKeyConstraint.bind(this), + UniqueConstraintNode: this.visitUniqueConstraint.bind(this), + ReferencesNode: this.visitReferences.bind(this), + CheckConstraintNode: this.visitCheckConstraint.bind(this), + WithNode: this.visitWith.bind(this), + CommonTableExpressionNode: this.visitCommonTableExpression.bind(this), + CommonTableExpressionNameNode: this.visitCommonTableExpressionName.bind(this), + HavingNode: this.visitHaving.bind(this), + CreateSchemaNode: this.visitCreateSchema.bind(this), + DropSchemaNode: this.visitDropSchema.bind(this), + AlterTableNode: this.visitAlterTable.bind(this), + DropColumnNode: this.visitDropColumn.bind(this), + RenameColumnNode: this.visitRenameColumn.bind(this), + AlterColumnNode: this.visitAlterColumn.bind(this), + ModifyColumnNode: this.visitModifyColumn.bind(this), + AddConstraintNode: this.visitAddConstraint.bind(this), + DropConstraintNode: this.visitDropConstraint.bind(this), + RenameConstraintNode: this.visitRenameConstraint.bind(this), + ForeignKeyConstraintNode: this.visitForeignKeyConstraint.bind(this), + CreateViewNode: this.visitCreateView.bind(this), + RefreshMaterializedViewNode: this.visitRefreshMaterializedView.bind(this), + DropViewNode: this.visitDropView.bind(this), + GeneratedNode: this.visitGenerated.bind(this), + DefaultValueNode: this.visitDefaultValue.bind(this), + OnNode: this.visitOn.bind(this), + ValuesNode: this.visitValues.bind(this), + SelectModifierNode: this.visitSelectModifier.bind(this), + CreateTypeNode: this.visitCreateType.bind(this), + DropTypeNode: this.visitDropType.bind(this), + ExplainNode: this.visitExplain.bind(this), + DefaultInsertValueNode: this.visitDefaultInsertValue.bind(this), + AggregateFunctionNode: this.visitAggregateFunction.bind(this), + OverNode: this.visitOver.bind(this), + PartitionByNode: this.visitPartitionBy.bind(this), + PartitionByItemNode: this.visitPartitionByItem.bind(this), + SetOperationNode: this.visitSetOperation.bind(this), + BinaryOperationNode: this.visitBinaryOperation.bind(this), + UnaryOperationNode: this.visitUnaryOperation.bind(this), + UsingNode: this.visitUsing.bind(this), + FunctionNode: this.visitFunction.bind(this), + CaseNode: this.visitCase.bind(this), + WhenNode: this.visitWhen.bind(this), + JSONReferenceNode: this.visitJSONReference.bind(this), + JSONPathNode: this.visitJSONPath.bind(this), + JSONPathLegNode: this.visitJSONPathLeg.bind(this), + JSONOperatorChainNode: this.visitJSONOperatorChain.bind(this), + TupleNode: this.visitTuple.bind(this), + MergeQueryNode: this.visitMergeQuery.bind(this), + MatchedNode: this.visitMatched.bind(this), + AddIndexNode: this.visitAddIndex.bind(this), + CastNode: this.visitCast.bind(this), + FetchNode: this.visitFetch.bind(this), + TopNode: this.visitTop.bind(this), + OutputNode: this.visitOutput.bind(this), + OrActionNode: this.visitOrAction.bind(this), + CollateNode: this.visitCollate.bind(this) + }); + visitNode = (node) => { + this.nodeStack.push(node); + this.#visitors[node.kind](node); + this.nodeStack.pop(); + }; + }; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-compiler/default-query-compiler.js +var LIT_WRAP_REGEX, DefaultQueryCompiler, SELECT_MODIFIER_SQL, SELECT_MODIFIER_PRIORITY, JOIN_TYPE_SQL; +var init_default_query_compiler = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-compiler/default-query-compiler.js"() { + init_create_table_node(); + init_insert_query_node(); + init_operation_node_visitor(); + init_operator_node(); + init_parens_node(); + init_raw_node(); + init_object_utils(); + init_create_view_node(); + init_set_operation_node(); + init_when_node(); + init_log_once(); + LIT_WRAP_REGEX = /'/g; + DefaultQueryCompiler = class extends OperationNodeVisitor { + #sql = ""; + #parameters = []; + get numParameters() { + return this.#parameters.length; + } + compileQuery(node, queryId) { + this.#sql = ""; + this.#parameters = []; + this.nodeStack.splice(0, this.nodeStack.length); + this.visitNode(node); + return freeze2({ + query: node, + queryId, + sql: this.getSql(), + parameters: [...this.#parameters] + }); + } + getSql() { + return this.#sql; + } + visitSelectQuery(node) { + const wrapInParens = this.parentNode !== void 0 && !ParensNode.is(this.parentNode) && !InsertQueryNode.is(this.parentNode) && !CreateTableNode.is(this.parentNode) && !CreateViewNode.is(this.parentNode) && !SetOperationNode.is(this.parentNode); + if (this.parentNode === void 0 && node.explain) { + this.visitNode(node.explain); + this.append(" "); + } + if (wrapInParens) { + this.append("("); + } + if (node.with) { + this.visitNode(node.with); + this.append(" "); + } + this.append("select"); + if (node.distinctOn) { + this.append(" "); + this.compileDistinctOn(node.distinctOn); + } + if (node.frontModifiers?.length) { + this.append(" "); + this.compileList(node.frontModifiers, " "); + } + if (node.top) { + this.append(" "); + this.visitNode(node.top); + } + if (node.selections) { + this.append(" "); + this.compileList(node.selections); + } + if (node.from) { + this.append(" "); + this.visitNode(node.from); + } + if (node.joins) { + this.append(" "); + this.compileList(node.joins, " "); + } + if (node.where) { + this.append(" "); + this.visitNode(node.where); + } + if (node.groupBy) { + this.append(" "); + this.visitNode(node.groupBy); + } + if (node.having) { + this.append(" "); + this.visitNode(node.having); + } + if (node.setOperations) { + this.append(" "); + this.compileList(node.setOperations, " "); + } + if (node.orderBy) { + this.append(" "); + this.visitNode(node.orderBy); + } + if (node.limit) { + this.append(" "); + this.visitNode(node.limit); + } + if (node.offset) { + this.append(" "); + this.visitNode(node.offset); + } + if (node.fetch) { + this.append(" "); + this.visitNode(node.fetch); + } + if (node.endModifiers?.length) { + this.append(" "); + this.compileList(this.sortSelectModifiers([...node.endModifiers]), " "); + } + if (wrapInParens) { + this.append(")"); + } + } + visitFrom(node) { + this.append("from "); + this.compileList(node.froms); + } + visitSelection(node) { + this.visitNode(node.selection); + } + visitColumn(node) { + this.visitNode(node.column); + } + compileDistinctOn(expressions) { + this.append("distinct on ("); + this.compileList(expressions); + this.append(")"); + } + compileList(nodes, separator = ", ") { + const lastIndex = nodes.length - 1; + for (let i5 = 0; i5 <= lastIndex; i5++) { + this.visitNode(nodes[i5]); + if (i5 < lastIndex) { + this.append(separator); + } + } + } + visitWhere(node) { + this.append("where "); + this.visitNode(node.where); + } + visitHaving(node) { + this.append("having "); + this.visitNode(node.having); + } + visitInsertQuery(node) { + const wrapInParens = this.parentNode !== void 0 && !ParensNode.is(this.parentNode) && !RawNode.is(this.parentNode) && !WhenNode.is(this.parentNode); + if (this.parentNode === void 0 && node.explain) { + this.visitNode(node.explain); + this.append(" "); + } + if (wrapInParens) { + this.append("("); + } + if (node.with) { + this.visitNode(node.with); + this.append(" "); + } + this.append(node.replace ? "replace" : "insert"); + if (node.ignore) { + logOnce("`InsertQueryNode.ignore` is deprecated. Use `InsertQueryNode.orAction` instead."); + this.append(" ignore"); + } + if (node.orAction) { + this.append(" "); + this.visitNode(node.orAction); + } + if (node.top) { + this.append(" "); + this.visitNode(node.top); + } + if (node.into) { + this.append(" into "); + this.visitNode(node.into); + } + if (node.columns) { + this.append(" ("); + this.compileList(node.columns); + this.append(")"); + } + if (node.output) { + this.append(" "); + this.visitNode(node.output); + } + if (node.values) { + this.append(" "); + this.visitNode(node.values); + } + if (node.defaultValues) { + this.append(" "); + this.append("default values"); + } + if (node.onConflict) { + this.append(" "); + this.visitNode(node.onConflict); + } + if (node.onDuplicateKey) { + this.append(" "); + this.visitNode(node.onDuplicateKey); + } + if (node.returning) { + this.append(" "); + this.visitNode(node.returning); + } + if (wrapInParens) { + this.append(")"); + } + if (node.endModifiers?.length) { + this.append(" "); + this.compileList(node.endModifiers, " "); + } + } + visitValues(node) { + this.append("values "); + this.compileList(node.values); + } + visitDeleteQuery(node) { + const wrapInParens = this.parentNode !== void 0 && !ParensNode.is(this.parentNode) && !RawNode.is(this.parentNode); + if (this.parentNode === void 0 && node.explain) { + this.visitNode(node.explain); + this.append(" "); + } + if (wrapInParens) { + this.append("("); + } + if (node.with) { + this.visitNode(node.with); + this.append(" "); + } + this.append("delete "); + if (node.top) { + this.visitNode(node.top); + this.append(" "); + } + this.visitNode(node.from); + if (node.output) { + this.append(" "); + this.visitNode(node.output); + } + if (node.using) { + this.append(" "); + this.visitNode(node.using); + } + if (node.joins) { + this.append(" "); + this.compileList(node.joins, " "); + } + if (node.where) { + this.append(" "); + this.visitNode(node.where); + } + if (node.orderBy) { + this.append(" "); + this.visitNode(node.orderBy); + } + if (node.limit) { + this.append(" "); + this.visitNode(node.limit); + } + if (node.returning) { + this.append(" "); + this.visitNode(node.returning); + } + if (wrapInParens) { + this.append(")"); + } + if (node.endModifiers?.length) { + this.append(" "); + this.compileList(node.endModifiers, " "); + } + } + visitReturning(node) { + this.append("returning "); + this.compileList(node.selections); + } + visitAlias(node) { + this.visitNode(node.node); + this.append(" as "); + this.visitNode(node.alias); + } + visitReference(node) { + if (node.table) { + this.visitNode(node.table); + this.append("."); + } + this.visitNode(node.column); + } + visitSelectAll(_) { + this.append("*"); + } + visitIdentifier(node) { + this.append(this.getLeftIdentifierWrapper()); + this.compileUnwrappedIdentifier(node); + this.append(this.getRightIdentifierWrapper()); + } + compileUnwrappedIdentifier(node) { + if (!isString(node.name)) { + throw new Error("a non-string identifier was passed to compileUnwrappedIdentifier."); + } + this.append(this.sanitizeIdentifier(node.name)); + } + visitAnd(node) { + this.visitNode(node.left); + this.append(" and "); + this.visitNode(node.right); + } + visitOr(node) { + this.visitNode(node.left); + this.append(" or "); + this.visitNode(node.right); + } + visitValue(node) { + if (node.immediate) { + this.appendImmediateValue(node.value); + } else { + this.appendValue(node.value); + } + } + visitValueList(node) { + this.append("("); + this.compileList(node.values); + this.append(")"); + } + visitTuple(node) { + this.append("("); + this.compileList(node.values); + this.append(")"); + } + visitPrimitiveValueList(node) { + this.append("("); + const { values: values2 } = node; + for (let i5 = 0; i5 < values2.length; ++i5) { + this.appendValue(values2[i5]); + if (i5 !== values2.length - 1) { + this.append(", "); + } + } + this.append(")"); + } + visitParens(node) { + this.append("("); + this.visitNode(node.node); + this.append(")"); + } + visitJoin(node) { + this.append(JOIN_TYPE_SQL[node.joinType]); + this.append(" "); + this.visitNode(node.table); + if (node.on) { + this.append(" "); + this.visitNode(node.on); + } + } + visitOn(node) { + this.append("on "); + this.visitNode(node.on); + } + visitRaw(node) { + const { sqlFragments, parameters: params } = node; + for (let i5 = 0; i5 < sqlFragments.length; ++i5) { + this.append(sqlFragments[i5]); + if (params.length > i5) { + this.visitNode(params[i5]); + } + } + } + visitOperator(node) { + this.append(node.operator); + } + visitTable(node) { + this.visitNode(node.table); + } + visitSchemableIdentifier(node) { + if (node.schema) { + this.visitNode(node.schema); + this.append("."); + } + this.visitNode(node.identifier); + } + visitCreateTable(node) { + this.append("create "); + if (node.frontModifiers?.length) { + this.compileList(node.frontModifiers, " "); + this.append(" "); + } + if (node.temporary) { + this.append("temporary "); + } + this.append("table "); + if (node.ifNotExists) { + this.append("if not exists "); + } + this.visitNode(node.table); + if (!node.selectQuery) { + this.append(" ("); + this.compileList([...node.columns, ...node.constraints ?? []]); + this.append(")"); + } + if (node.onCommit) { + this.append(" on commit "); + this.append(node.onCommit); + } + if (node.endModifiers?.length) { + this.append(" "); + this.compileList(node.endModifiers, " "); + } + if (node.selectQuery) { + this.append(" as "); + this.visitNode(node.selectQuery); + } + } + visitColumnDefinition(node) { + if (node.ifNotExists) { + this.append("if not exists "); + } + this.visitNode(node.column); + this.append(" "); + this.visitNode(node.dataType); + if (node.unsigned) { + this.append(" unsigned"); + } + if (node.frontModifiers && node.frontModifiers.length > 0) { + this.append(" "); + this.compileList(node.frontModifiers, " "); + } + if (node.generated) { + this.append(" "); + this.visitNode(node.generated); + } + if (node.identity) { + this.append(" identity"); + } + if (node.defaultTo) { + this.append(" "); + this.visitNode(node.defaultTo); + } + if (node.notNull) { + this.append(" not null"); + } + if (node.unique) { + this.append(" unique"); + } + if (node.nullsNotDistinct) { + this.append(" nulls not distinct"); + } + if (node.primaryKey) { + this.append(" primary key"); + } + if (node.autoIncrement) { + this.append(" "); + this.append(this.getAutoIncrement()); + } + if (node.references) { + this.append(" "); + this.visitNode(node.references); + } + if (node.check) { + this.append(" "); + this.visitNode(node.check); + } + if (node.endModifiers && node.endModifiers.length > 0) { + this.append(" "); + this.compileList(node.endModifiers, " "); + } + } + getAutoIncrement() { + return "auto_increment"; + } + visitReferences(node) { + this.append("references "); + this.visitNode(node.table); + this.append(" ("); + this.compileList(node.columns); + this.append(")"); + if (node.onDelete) { + this.append(" on delete "); + this.append(node.onDelete); + } + if (node.onUpdate) { + this.append(" on update "); + this.append(node.onUpdate); + } + } + visitDropTable(node) { + this.append("drop table "); + if (node.ifExists) { + this.append("if exists "); + } + this.visitNode(node.table); + if (node.cascade) { + this.append(" cascade"); + } + } + visitDataType(node) { + this.append(node.dataType); + } + visitOrderBy(node) { + this.append("order by "); + this.compileList(node.items); + } + visitOrderByItem(node) { + this.visitNode(node.orderBy); + if (node.collation) { + this.append(" "); + this.visitNode(node.collation); + } + if (node.direction) { + this.append(" "); + this.visitNode(node.direction); + } + if (node.nulls) { + this.append(" nulls "); + this.append(node.nulls); + } + } + visitGroupBy(node) { + this.append("group by "); + this.compileList(node.items); + } + visitGroupByItem(node) { + this.visitNode(node.groupBy); + } + visitUpdateQuery(node) { + const wrapInParens = this.parentNode !== void 0 && !ParensNode.is(this.parentNode) && !RawNode.is(this.parentNode) && !WhenNode.is(this.parentNode); + if (this.parentNode === void 0 && node.explain) { + this.visitNode(node.explain); + this.append(" "); + } + if (wrapInParens) { + this.append("("); + } + if (node.with) { + this.visitNode(node.with); + this.append(" "); + } + this.append("update "); + if (node.top) { + this.visitNode(node.top); + this.append(" "); + } + if (node.table) { + this.visitNode(node.table); + this.append(" "); + } + this.append("set "); + if (node.updates) { + this.compileList(node.updates); + } + if (node.output) { + this.append(" "); + this.visitNode(node.output); + } + if (node.from) { + this.append(" "); + this.visitNode(node.from); + } + if (node.joins) { + if (!node.from) { + throw new Error("Joins in an update query are only supported as a part of a PostgreSQL 'update set from join' query. If you want to create a MySQL 'update join set' query, see https://kysely.dev/docs/examples/update/my-sql-joins"); + } + this.append(" "); + this.compileList(node.joins, " "); + } + if (node.where) { + this.append(" "); + this.visitNode(node.where); + } + if (node.returning) { + this.append(" "); + this.visitNode(node.returning); + } + if (node.orderBy) { + this.append(" "); + this.visitNode(node.orderBy); + } + if (node.limit) { + this.append(" "); + this.visitNode(node.limit); + } + if (wrapInParens) { + this.append(")"); + } + if (node.endModifiers?.length) { + this.append(" "); + this.compileList(node.endModifiers, " "); + } + } + visitColumnUpdate(node) { + this.visitNode(node.column); + this.append(" = "); + this.visitNode(node.value); + } + visitLimit(node) { + this.append("limit "); + this.visitNode(node.limit); + } + visitOffset(node) { + this.append("offset "); + this.visitNode(node.offset); + } + visitOnConflict(node) { + this.append("on conflict"); + if (node.columns) { + this.append(" ("); + this.compileList(node.columns); + this.append(")"); + } else if (node.constraint) { + this.append(" on constraint "); + this.visitNode(node.constraint); + } else if (node.indexExpression) { + this.append(" ("); + this.visitNode(node.indexExpression); + this.append(")"); + } + if (node.indexWhere) { + this.append(" "); + this.visitNode(node.indexWhere); + } + if (node.doNothing === true) { + this.append(" do nothing"); + } else if (node.updates) { + this.append(" do update set "); + this.compileList(node.updates); + if (node.updateWhere) { + this.append(" "); + this.visitNode(node.updateWhere); + } + } + } + visitOnDuplicateKey(node) { + this.append("on duplicate key update "); + this.compileList(node.updates); + } + visitCreateIndex(node) { + this.append("create "); + if (node.unique) { + this.append("unique "); + } + this.append("index "); + if (node.ifNotExists) { + this.append("if not exists "); + } + this.visitNode(node.name); + if (node.table) { + this.append(" on "); + this.visitNode(node.table); + } + if (node.using) { + this.append(" using "); + this.visitNode(node.using); + } + if (node.columns) { + this.append(" ("); + this.compileList(node.columns); + this.append(")"); + } + if (node.nullsNotDistinct) { + this.append(" nulls not distinct"); + } + if (node.where) { + this.append(" "); + this.visitNode(node.where); + } + } + visitDropIndex(node) { + this.append("drop index "); + if (node.ifExists) { + this.append("if exists "); + } + this.visitNode(node.name); + if (node.table) { + this.append(" on "); + this.visitNode(node.table); + } + if (node.cascade) { + this.append(" cascade"); + } + } + visitCreateSchema(node) { + this.append("create schema "); + if (node.ifNotExists) { + this.append("if not exists "); + } + this.visitNode(node.schema); + } + visitDropSchema(node) { + this.append("drop schema "); + if (node.ifExists) { + this.append("if exists "); + } + this.visitNode(node.schema); + if (node.cascade) { + this.append(" cascade"); + } + } + visitPrimaryKeyConstraint(node) { + if (node.name) { + this.append("constraint "); + this.visitNode(node.name); + this.append(" "); + } + this.append("primary key ("); + this.compileList(node.columns); + this.append(")"); + this.buildDeferrable(node); + } + buildDeferrable(node) { + if (node.deferrable !== void 0) { + if (node.deferrable) { + this.append(" deferrable"); + } else { + this.append(" not deferrable"); + } + } + if (node.initiallyDeferred !== void 0) { + if (node.initiallyDeferred) { + this.append(" initially deferred"); + } else { + this.append(" initially immediate"); + } + } + } + visitUniqueConstraint(node) { + if (node.name) { + this.append("constraint "); + this.visitNode(node.name); + this.append(" "); + } + this.append("unique"); + if (node.nullsNotDistinct) { + this.append(" nulls not distinct"); + } + this.append(" ("); + this.compileList(node.columns); + this.append(")"); + this.buildDeferrable(node); + } + visitCheckConstraint(node) { + if (node.name) { + this.append("constraint "); + this.visitNode(node.name); + this.append(" "); + } + this.append("check ("); + this.visitNode(node.expression); + this.append(")"); + } + visitForeignKeyConstraint(node) { + if (node.name) { + this.append("constraint "); + this.visitNode(node.name); + this.append(" "); + } + this.append("foreign key ("); + this.compileList(node.columns); + this.append(") "); + this.visitNode(node.references); + if (node.onDelete) { + this.append(" on delete "); + this.append(node.onDelete); + } + if (node.onUpdate) { + this.append(" on update "); + this.append(node.onUpdate); + } + this.buildDeferrable(node); + } + visitList(node) { + this.compileList(node.items); + } + visitWith(node) { + this.append("with "); + if (node.recursive) { + this.append("recursive "); + } + this.compileList(node.expressions); + } + visitCommonTableExpression(node) { + this.visitNode(node.name); + this.append(" as "); + if (isBoolean(node.materialized)) { + if (!node.materialized) { + this.append("not "); + } + this.append("materialized "); + } + this.visitNode(node.expression); + } + visitCommonTableExpressionName(node) { + this.visitNode(node.table); + if (node.columns) { + this.append("("); + this.compileList(node.columns); + this.append(")"); + } + } + visitAlterTable(node) { + this.append("alter table "); + this.visitNode(node.table); + this.append(" "); + if (node.renameTo) { + this.append("rename to "); + this.visitNode(node.renameTo); + } + if (node.setSchema) { + this.append("set schema "); + this.visitNode(node.setSchema); + } + if (node.addConstraint) { + this.visitNode(node.addConstraint); + } + if (node.dropConstraint) { + this.visitNode(node.dropConstraint); + } + if (node.renameConstraint) { + this.visitNode(node.renameConstraint); + } + if (node.columnAlterations) { + this.compileColumnAlterations(node.columnAlterations); + } + if (node.addIndex) { + this.visitNode(node.addIndex); + } + if (node.dropIndex) { + this.visitNode(node.dropIndex); + } + } + visitAddColumn(node) { + this.append("add column "); + this.visitNode(node.column); + } + visitRenameColumn(node) { + this.append("rename column "); + this.visitNode(node.column); + this.append(" to "); + this.visitNode(node.renameTo); + } + visitDropColumn(node) { + this.append("drop column "); + this.visitNode(node.column); + } + visitAlterColumn(node) { + this.append("alter column "); + this.visitNode(node.column); + this.append(" "); + if (node.dataType) { + if (this.announcesNewColumnDataType()) { + this.append("type "); + } + this.visitNode(node.dataType); + if (node.dataTypeExpression) { + this.append("using "); + this.visitNode(node.dataTypeExpression); + } + } + if (node.setDefault) { + this.append("set default "); + this.visitNode(node.setDefault); + } + if (node.dropDefault) { + this.append("drop default"); + } + if (node.setNotNull) { + this.append("set not null"); + } + if (node.dropNotNull) { + this.append("drop not null"); + } + } + visitModifyColumn(node) { + this.append("modify column "); + this.visitNode(node.column); + } + visitAddConstraint(node) { + this.append("add "); + this.visitNode(node.constraint); + } + visitDropConstraint(node) { + this.append("drop constraint "); + if (node.ifExists) { + this.append("if exists "); + } + this.visitNode(node.constraintName); + if (node.modifier === "cascade") { + this.append(" cascade"); + } else if (node.modifier === "restrict") { + this.append(" restrict"); + } + } + visitRenameConstraint(node) { + this.append("rename constraint "); + this.visitNode(node.oldName); + this.append(" to "); + this.visitNode(node.newName); + } + visitSetOperation(node) { + this.append(node.operator); + this.append(" "); + if (node.all) { + this.append("all "); + } + this.visitNode(node.expression); + } + visitCreateView(node) { + this.append("create "); + if (node.orReplace) { + this.append("or replace "); + } + if (node.materialized) { + this.append("materialized "); + } + if (node.temporary) { + this.append("temporary "); + } + this.append("view "); + if (node.ifNotExists) { + this.append("if not exists "); + } + this.visitNode(node.name); + this.append(" "); + if (node.columns) { + this.append("("); + this.compileList(node.columns); + this.append(") "); + } + if (node.as) { + this.append("as "); + this.visitNode(node.as); + } + } + visitRefreshMaterializedView(node) { + this.append("refresh materialized view "); + if (node.concurrently) { + this.append("concurrently "); + } + this.visitNode(node.name); + if (node.withNoData) { + this.append(" with no data"); + } else { + this.append(" with data"); + } + } + visitDropView(node) { + this.append("drop "); + if (node.materialized) { + this.append("materialized "); + } + this.append("view "); + if (node.ifExists) { + this.append("if exists "); + } + this.visitNode(node.name); + if (node.cascade) { + this.append(" cascade"); + } + } + visitGenerated(node) { + this.append("generated "); + if (node.always) { + this.append("always "); + } + if (node.byDefault) { + this.append("by default "); + } + this.append("as "); + if (node.identity) { + this.append("identity"); + } + if (node.expression) { + this.append("("); + this.visitNode(node.expression); + this.append(")"); + } + if (node.stored) { + this.append(" stored"); + } + } + visitDefaultValue(node) { + this.append("default "); + this.visitNode(node.defaultValue); + } + visitSelectModifier(node) { + if (node.rawModifier) { + this.visitNode(node.rawModifier); + } else { + this.append(SELECT_MODIFIER_SQL[node.modifier]); + } + if (node.of) { + this.append(" of "); + this.compileList(node.of, ", "); + } + } + visitCreateType(node) { + this.append("create type "); + this.visitNode(node.name); + if (node.enum) { + this.append(" as enum "); + this.visitNode(node.enum); + } + } + visitDropType(node) { + this.append("drop type "); + if (node.ifExists) { + this.append("if exists "); + } + this.visitNode(node.name); + } + visitExplain(node) { + this.append("explain"); + if (node.options || node.format) { + this.append(" "); + this.append(this.getLeftExplainOptionsWrapper()); + if (node.options) { + this.visitNode(node.options); + if (node.format) { + this.append(this.getExplainOptionsDelimiter()); + } + } + if (node.format) { + this.append("format"); + this.append(this.getExplainOptionAssignment()); + this.append(node.format); + } + this.append(this.getRightExplainOptionsWrapper()); + } + } + visitDefaultInsertValue(_) { + this.append("default"); + } + visitAggregateFunction(node) { + this.append(node.func); + this.append("("); + if (node.distinct) { + this.append("distinct "); + } + this.compileList(node.aggregated); + if (node.orderBy) { + this.append(" "); + this.visitNode(node.orderBy); + } + this.append(")"); + if (node.withinGroup) { + this.append(" within group ("); + this.visitNode(node.withinGroup); + this.append(")"); + } + if (node.filter) { + this.append(" filter("); + this.visitNode(node.filter); + this.append(")"); + } + if (node.over) { + this.append(" "); + this.visitNode(node.over); + } + } + visitOver(node) { + this.append("over("); + if (node.partitionBy) { + this.visitNode(node.partitionBy); + if (node.orderBy) { + this.append(" "); + } + } + if (node.orderBy) { + this.visitNode(node.orderBy); + } + this.append(")"); + } + visitPartitionBy(node) { + this.append("partition by "); + this.compileList(node.items); + } + visitPartitionByItem(node) { + this.visitNode(node.partitionBy); + } + visitBinaryOperation(node) { + this.visitNode(node.leftOperand); + this.append(" "); + this.visitNode(node.operator); + this.append(" "); + this.visitNode(node.rightOperand); + } + visitUnaryOperation(node) { + this.visitNode(node.operator); + if (!this.isMinusOperator(node.operator)) { + this.append(" "); + } + this.visitNode(node.operand); + } + isMinusOperator(node) { + return OperatorNode.is(node) && node.operator === "-"; + } + visitUsing(node) { + this.append("using "); + this.compileList(node.tables); + } + visitFunction(node) { + this.append(node.func); + this.append("("); + this.compileList(node.arguments); + this.append(")"); + } + visitCase(node) { + this.append("case"); + if (node.value) { + this.append(" "); + this.visitNode(node.value); + } + if (node.when) { + this.append(" "); + this.compileList(node.when, " "); + } + if (node.else) { + this.append(" else "); + this.visitNode(node.else); + } + this.append(" end"); + if (node.isStatement) { + this.append(" case"); + } + } + visitWhen(node) { + this.append("when "); + this.visitNode(node.condition); + if (node.result) { + this.append(" then "); + this.visitNode(node.result); + } + } + visitJSONReference(node) { + this.visitNode(node.reference); + this.visitNode(node.traversal); + } + visitJSONPath(node) { + if (node.inOperator) { + this.visitNode(node.inOperator); + } + this.append("'$"); + for (const pathLeg of node.pathLegs) { + this.visitNode(pathLeg); + } + this.append("'"); + } + visitJSONPathLeg(node) { + const isArrayLocation = node.type === "ArrayLocation"; + this.append(isArrayLocation ? "[" : "."); + this.append(typeof node.value === "string" ? this.sanitizeStringLiteral(node.value) : String(node.value)); + if (isArrayLocation) { + this.append("]"); + } + } + visitJSONOperatorChain(node) { + for (let i5 = 0, len = node.values.length; i5 < len; i5++) { + if (i5 === len - 1) { + this.visitNode(node.operator); + } else { + this.append("->"); + } + this.visitNode(node.values[i5]); + } + } + visitMergeQuery(node) { + if (node.with) { + this.visitNode(node.with); + this.append(" "); + } + this.append("merge "); + if (node.top) { + this.visitNode(node.top); + this.append(" "); + } + this.append("into "); + this.visitNode(node.into); + if (node.using) { + this.append(" "); + this.visitNode(node.using); + } + if (node.whens) { + this.append(" "); + this.compileList(node.whens, " "); + } + if (node.returning) { + this.append(" "); + this.visitNode(node.returning); + } + if (node.output) { + this.append(" "); + this.visitNode(node.output); + } + if (node.endModifiers?.length) { + this.append(" "); + this.compileList(node.endModifiers, " "); + } + } + visitMatched(node) { + if (node.not) { + this.append("not "); + } + this.append("matched"); + if (node.bySource) { + this.append(" by source"); + } + } + visitAddIndex(node) { + this.append("add "); + if (node.unique) { + this.append("unique "); + } + this.append("index "); + this.visitNode(node.name); + if (node.columns) { + this.append(" ("); + this.compileList(node.columns); + this.append(")"); + } + if (node.using) { + this.append(" using "); + this.visitNode(node.using); + } + } + visitCast(node) { + this.append("cast("); + this.visitNode(node.expression); + this.append(" as "); + this.visitNode(node.dataType); + this.append(")"); + } + visitFetch(node) { + this.append("fetch next "); + this.visitNode(node.rowCount); + this.append(` rows ${node.modifier}`); + } + visitOutput(node) { + this.append("output "); + this.compileList(node.selections); + } + visitTop(node) { + this.append(`top(${node.expression})`); + if (node.modifiers) { + this.append(` ${node.modifiers}`); + } + } + visitOrAction(node) { + this.append(node.action); + } + visitCollate(node) { + this.append("collate "); + this.visitNode(node.collation); + } + append(str) { + this.#sql += str; + } + appendValue(parameter) { + this.addParameter(parameter); + this.append(this.getCurrentParameterPlaceholder()); + } + getLeftIdentifierWrapper() { + return '"'; + } + getRightIdentifierWrapper() { + return '"'; + } + getCurrentParameterPlaceholder() { + return "$" + this.numParameters; + } + getLeftExplainOptionsWrapper() { + return "("; + } + getExplainOptionAssignment() { + return " "; + } + getExplainOptionsDelimiter() { + return ", "; + } + getRightExplainOptionsWrapper() { + return ")"; + } + sanitizeIdentifier(identifier) { + const leftWrap = this.getLeftIdentifierWrapper(); + const rightWrap = this.getRightIdentifierWrapper(); + let sanitized = ""; + for (const c5 of identifier) { + sanitized += c5; + if (c5 === leftWrap) { + sanitized += leftWrap; + } else if (c5 === rightWrap) { + sanitized += rightWrap; + } + } + return sanitized; + } + sanitizeStringLiteral(value) { + return value.replace(LIT_WRAP_REGEX, "''"); + } + addParameter(parameter) { + this.#parameters.push(parameter); + } + appendImmediateValue(value) { + if (isString(value)) { + this.appendStringLiteral(value); + } else if (isNumber(value) || isBoolean(value) || isBigInt(value)) { + this.append(value.toString()); + } else if (isNull2(value)) { + this.append("null"); + } else if (isDate(value)) { + this.appendImmediateValue(value.toISOString()); + } else { + throw new Error(`invalid immediate value ${value}`); + } + } + appendStringLiteral(value) { + this.append("'"); + this.append(this.sanitizeStringLiteral(value)); + this.append("'"); + } + sortSelectModifiers(arr) { + arr.sort((left, right) => left.modifier && right.modifier ? SELECT_MODIFIER_PRIORITY[left.modifier] - SELECT_MODIFIER_PRIORITY[right.modifier] : 1); + return freeze2(arr); + } + compileColumnAlterations(columnAlterations) { + this.compileList(columnAlterations); + } + /** + * controls whether the dialect adds a "type" keyword before a column's new data + * type in an ALTER TABLE statement. + */ + announcesNewColumnDataType() { + return true; + } + }; + SELECT_MODIFIER_SQL = freeze2({ + ForKeyShare: "for key share", + ForNoKeyUpdate: "for no key update", + ForUpdate: "for update", + ForShare: "for share", + NoWait: "nowait", + SkipLocked: "skip locked", + Distinct: "distinct" + }); + SELECT_MODIFIER_PRIORITY = freeze2({ + ForKeyShare: 1, + ForNoKeyUpdate: 1, + ForUpdate: 1, + ForShare: 1, + NoWait: 2, + SkipLocked: 2, + Distinct: 0 + }); + JOIN_TYPE_SQL = freeze2({ + InnerJoin: "inner join", + LeftJoin: "left join", + RightJoin: "right join", + FullJoin: "full join", + CrossJoin: "cross join", + LateralInnerJoin: "inner join lateral", + LateralLeftJoin: "left join lateral", + LateralCrossJoin: "cross join lateral", + OuterApply: "outer apply", + CrossApply: "cross apply", + Using: "using" + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-compiler/compiled-query.js +var CompiledQuery; +var init_compiled_query = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-compiler/compiled-query.js"() { + init_raw_node(); + init_object_utils(); + init_query_id(); + CompiledQuery = freeze2({ + raw(sql3, parameters = []) { + return freeze2({ + sql: sql3, + query: RawNode.createWithSql(sql3), + parameters: freeze2(parameters), + queryId: createQueryId() + }); + } + }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/driver/database-connection.js +var init_database_connection = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/driver/database-connection.js"() { + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/driver/connection-provider.js +var init_connection_provider = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/driver/connection-provider.js"() { + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/driver/dummy-driver.js +var init_dummy_driver = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/driver/dummy-driver.js"() { + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/dialect.js +var init_dialect2 = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/dialect.js"() { + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/dialect-adapter.js +var init_dialect_adapter = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/dialect-adapter.js"() { + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/dialect-adapter-base.js +var DialectAdapterBase; +var init_dialect_adapter_base = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/dialect-adapter-base.js"() { + DialectAdapterBase = class { + get supportsCreateIfNotExists() { + return true; + } + get supportsTransactionalDdl() { + return false; + } + get supportsReturning() { + return false; + } + get supportsOutput() { + return false; + } + }; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/database-introspector.js +var init_database_introspector = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/database-introspector.js"() { + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/savepoint-parser.js +function parseSavepointCommand(command, savepointName) { + return RawNode.createWithChildren([ + RawNode.createWithSql(`${command} `), + IdentifierNode.create(savepointName) + // ensures savepointName gets sanitized + ]); +} +var init_savepoint_parser = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/savepoint-parser.js"() { + init_identifier_node(); + init_raw_node(); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/sqlite/sqlite-driver.js +var SqliteDriver, SqliteConnection, ConnectionMutex; +var init_sqlite_driver = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/sqlite/sqlite-driver.js"() { + init_select_query_node(); + init_savepoint_parser(); + init_compiled_query(); + init_object_utils(); + init_query_id(); + SqliteDriver = class { + #config; + #connectionMutex = new ConnectionMutex(); + #db; + #connection; + constructor(config3) { + this.#config = freeze2({ ...config3 }); + } + async init() { + this.#db = isFunction(this.#config.database) ? await this.#config.database() : this.#config.database; + this.#connection = new SqliteConnection(this.#db); + if (this.#config.onCreateConnection) { + await this.#config.onCreateConnection(this.#connection); + } + } + async acquireConnection() { + await this.#connectionMutex.lock(); + return this.#connection; + } + async beginTransaction(connection2) { + await connection2.executeQuery(CompiledQuery.raw("begin")); + } + async commitTransaction(connection2) { + await connection2.executeQuery(CompiledQuery.raw("commit")); + } + async rollbackTransaction(connection2) { + await connection2.executeQuery(CompiledQuery.raw("rollback")); + } + async savepoint(connection2, savepointName, compileQuery) { + await connection2.executeQuery(compileQuery(parseSavepointCommand("savepoint", savepointName), createQueryId())); + } + async rollbackToSavepoint(connection2, savepointName, compileQuery) { + await connection2.executeQuery(compileQuery(parseSavepointCommand("rollback to", savepointName), createQueryId())); + } + async releaseSavepoint(connection2, savepointName, compileQuery) { + await connection2.executeQuery(compileQuery(parseSavepointCommand("release", savepointName), createQueryId())); + } + async releaseConnection() { + this.#connectionMutex.unlock(); + } + async destroy() { + this.#db?.close(); + } + }; + SqliteConnection = class { + #db; + constructor(db) { + this.#db = db; + } + executeQuery(compiledQuery) { + const { sql: sql3, parameters } = compiledQuery; + const stmt = this.#db.prepare(sql3); + if (stmt.reader) { + return Promise.resolve({ + rows: stmt.all(parameters) + }); + } + const { changes, lastInsertRowid } = stmt.run(parameters); + return Promise.resolve({ + numAffectedRows: changes !== void 0 && changes !== null ? BigInt(changes) : void 0, + insertId: lastInsertRowid !== void 0 && lastInsertRowid !== null ? BigInt(lastInsertRowid) : void 0, + rows: [] + }); + } + async *streamQuery(compiledQuery, _chunkSize) { + const { sql: sql3, parameters, query } = compiledQuery; + const stmt = this.#db.prepare(sql3); + if (SelectQueryNode.is(query)) { + const iter = stmt.iterate(parameters); + for (const row of iter) { + yield { + rows: [row] + }; + } + } else { + throw new Error("Sqlite driver only supports streaming of select queries"); + } + } + }; + ConnectionMutex = class { + #promise; + #resolve; + async lock() { + while (this.#promise) { + await this.#promise; + } + this.#promise = new Promise((resolve4) => { + this.#resolve = resolve4; + }); + } + unlock() { + const resolve4 = this.#resolve; + this.#promise = void 0; + this.#resolve = void 0; + resolve4?.(); + } + }; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/sqlite/sqlite-query-compiler.js +var ID_WRAP_REGEX, SqliteQueryCompiler; +var init_sqlite_query_compiler = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/sqlite/sqlite-query-compiler.js"() { + init_default_query_compiler(); + ID_WRAP_REGEX = /"/g; + SqliteQueryCompiler = class extends DefaultQueryCompiler { + visitOrAction(node) { + this.append("or "); + this.append(node.action); + } + getCurrentParameterPlaceholder() { + return "?"; + } + getLeftExplainOptionsWrapper() { + return ""; + } + getRightExplainOptionsWrapper() { + return ""; + } + getLeftIdentifierWrapper() { + return '"'; + } + getRightIdentifierWrapper() { + return '"'; + } + getAutoIncrement() { + return "autoincrement"; + } + sanitizeIdentifier(identifier) { + return identifier.replace(ID_WRAP_REGEX, '""'); + } + visitDefaultInsertValue(_) { + this.append("null"); + } + }; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/migration/migrator.js +var DEFAULT_MIGRATION_TABLE, DEFAULT_MIGRATION_LOCK_TABLE, NO_MIGRATIONS; +var init_migrator = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/migration/migrator.js"() { + init_object_utils(); + DEFAULT_MIGRATION_TABLE = "kysely_migration"; + DEFAULT_MIGRATION_LOCK_TABLE = "kysely_migration_lock"; + NO_MIGRATIONS = freeze2({ __noMigrations__: true }); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/sqlite/sqlite-introspector.js +var SqliteIntrospector; +var init_sqlite_introspector = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/sqlite/sqlite-introspector.js"() { + init_migrator(); + init_sql3(); + SqliteIntrospector = class { + #db; + constructor(db) { + this.#db = db; + } + async getSchemas() { + return []; + } + async getTables(options = { withInternalKyselyTables: false }) { + return await this.#getTableMetadata(options); + } + async getMetadata(options) { + return { + tables: await this.getTables(options) + }; + } + #tablesQuery(qb, options) { + let tablesQuery = qb.selectFrom("sqlite_master").where("type", "in", ["table", "view"]).where("name", "not like", "sqlite_%").select(["name", "sql", "type"]).orderBy("name"); + if (!options.withInternalKyselyTables) { + tablesQuery = tablesQuery.where("name", "!=", DEFAULT_MIGRATION_TABLE).where("name", "!=", DEFAULT_MIGRATION_LOCK_TABLE); + } + return tablesQuery; + } + async #getTableMetadata(options) { + const tablesResult = await this.#tablesQuery(this.#db, options).execute(); + const tableMetadata = await this.#db.with("table_list", (qb) => this.#tablesQuery(qb, options)).selectFrom([ + "table_list as tl", + sql2`pragma_table_info(tl.name)`.as("p") + ]).select([ + "tl.name as table", + "p.cid", + "p.name", + "p.type", + "p.notnull", + "p.dflt_value", + "p.pk" + ]).orderBy("tl.name").orderBy("p.cid").execute(); + const columnsByTable = {}; + for (const row of tableMetadata) { + columnsByTable[row.table] ??= []; + columnsByTable[row.table].push(row); + } + return tablesResult.map(({ name, sql: sql3, type }) => { + let autoIncrementCol = sql3?.split(/[\(\),]/)?.find((it) => it.toLowerCase().includes("autoincrement"))?.trimStart()?.split(/\s+/)?.[0]?.replace(/["`]/g, ""); + const columns = columnsByTable[name] ?? []; + if (!autoIncrementCol) { + const pkCols = columns.filter((r5) => r5.pk > 0); + if (pkCols.length === 1 && pkCols[0].type.toLowerCase() === "integer") { + autoIncrementCol = pkCols[0].name; + } + } + return { + name, + isView: type === "view", + columns: columns.map((col) => ({ + name: col.name, + dataType: col.type, + isNullable: !col.notnull, + isAutoIncrementing: col.name === autoIncrementCol, + hasDefaultValue: col.dflt_value != null, + comment: void 0 + })) + }; + }); + } + }; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/sqlite/sqlite-adapter.js +var SqliteAdapter; +var init_sqlite_adapter = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/sqlite/sqlite-adapter.js"() { + init_dialect_adapter_base(); + SqliteAdapter = class extends DialectAdapterBase { + get supportsTransactionalDdl() { + return false; + } + get supportsReturning() { + return true; + } + async acquireMigrationLock(_db, _opt) { + } + async releaseMigrationLock(_db, _opt) { + } + }; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/sqlite/sqlite-dialect.js +var SqliteDialect; +var init_sqlite_dialect = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/sqlite/sqlite-dialect.js"() { + init_sqlite_driver(); + init_sqlite_query_compiler(); + init_sqlite_introspector(); + init_sqlite_adapter(); + init_object_utils(); + SqliteDialect = class { + #config; + constructor(config3) { + this.#config = freeze2({ ...config3 }); + } + createDriver() { + return new SqliteDriver(this.#config); + } + createQueryCompiler() { + return new SqliteQueryCompiler(); + } + createAdapter() { + return new SqliteAdapter(); + } + createIntrospector(db) { + return new SqliteIntrospector(db); + } + }; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/sqlite/sqlite-dialect-config.js +var init_sqlite_dialect_config = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/sqlite/sqlite-dialect-config.js"() { + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/postgres/postgres-query-compiler.js +var ID_WRAP_REGEX2, PostgresQueryCompiler; +var init_postgres_query_compiler = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/postgres/postgres-query-compiler.js"() { + init_default_query_compiler(); + ID_WRAP_REGEX2 = /"/g; + PostgresQueryCompiler = class extends DefaultQueryCompiler { + sanitizeIdentifier(identifier) { + return identifier.replace(ID_WRAP_REGEX2, '""'); + } + }; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/postgres/postgres-introspector.js +var PostgresIntrospector; +var init_postgres_introspector = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/postgres/postgres-introspector.js"() { + init_migrator(); + init_object_utils(); + init_sql3(); + PostgresIntrospector = class { + #db; + constructor(db) { + this.#db = db; + } + async getSchemas() { + let rawSchemas = await this.#db.selectFrom("pg_catalog.pg_namespace").select("nspname").$castTo().execute(); + return rawSchemas.map((it) => ({ name: it.nspname })); + } + async getTables(options = { withInternalKyselyTables: false }) { + let query = this.#db.selectFrom("pg_catalog.pg_attribute as a").innerJoin("pg_catalog.pg_class as c", "a.attrelid", "c.oid").innerJoin("pg_catalog.pg_namespace as ns", "c.relnamespace", "ns.oid").innerJoin("pg_catalog.pg_type as typ", "a.atttypid", "typ.oid").innerJoin("pg_catalog.pg_namespace as dtns", "typ.typnamespace", "dtns.oid").select([ + "a.attname as column", + "a.attnotnull as not_null", + "a.atthasdef as has_default", + "c.relname as table", + "c.relkind as table_type", + "ns.nspname as schema", + "typ.typname as type", + "dtns.nspname as type_schema", + sql2`col_description(a.attrelid, a.attnum)`.as("column_description"), + sql2`pg_get_serial_sequence(quote_ident(ns.nspname) || '.' || quote_ident(c.relname), a.attname)`.as("auto_incrementing") + ]).where("c.relkind", "in", [ + "r", + "v", + "p" + ]).where("ns.nspname", "!~", "^pg_").where("ns.nspname", "!=", "information_schema").where("ns.nspname", "!=", "crdb_internal").where(sql2`has_schema_privilege(ns.nspname, 'USAGE')`).where("a.attnum", ">=", 0).where("a.attisdropped", "!=", true).orderBy("ns.nspname").orderBy("c.relname").orderBy("a.attnum").$castTo(); + if (!options.withInternalKyselyTables) { + query = query.where("c.relname", "!=", DEFAULT_MIGRATION_TABLE).where("c.relname", "!=", DEFAULT_MIGRATION_LOCK_TABLE); + } + const rawColumns = await query.execute(); + return this.#parseTableMetadata(rawColumns); + } + async getMetadata(options) { + return { + tables: await this.getTables(options) + }; + } + #parseTableMetadata(columns) { + const tableDictionary = /* @__PURE__ */ new Map(); + for (let i5 = 0, len = columns.length; i5 < len; i5++) { + const column = columns[i5]; + const { schema: schema2, table } = column; + const tableKey = `schema:${schema2};table:${table}`; + if (!tableDictionary.has(tableKey)) { + tableDictionary.set(tableKey, freeze2({ + columns: [], + isView: column.table_type === "v", + name: table, + schema: schema2 + })); + } + tableDictionary.get(tableKey).columns.push(freeze2({ + comment: column.column_description ?? void 0, + dataType: column.type, + dataTypeSchema: column.type_schema, + hasDefaultValue: column.has_default, + isAutoIncrementing: column.auto_incrementing !== null, + isNullable: !column.not_null, + name: column.column + })); + } + return Array.from(tableDictionary.values()); + } + }; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/postgres/postgres-adapter.js +var LOCK_ID, PostgresAdapter; +var init_postgres_adapter = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/postgres/postgres-adapter.js"() { + init_sql3(); + init_dialect_adapter_base(); + LOCK_ID = BigInt("3853314791062309107"); + PostgresAdapter = class extends DialectAdapterBase { + get supportsTransactionalDdl() { + return true; + } + get supportsReturning() { + return true; + } + async acquireMigrationLock(db, _opt) { + await sql2`select pg_advisory_xact_lock(${sql2.lit(LOCK_ID)})`.execute(db); + } + async releaseMigrationLock(_db, _opt) { + } + }; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/stack-trace-utils.js +function extendStackTrace(err, stackError) { + if (isStackHolder(err) && stackError.stack) { + const stackExtension = stackError.stack.split("\n").slice(1).join("\n"); + err.stack += ` +${stackExtension}`; + return err; + } + return err; +} +function isStackHolder(obj) { + return isObject3(obj) && isString(obj.stack); +} +var init_stack_trace_utils = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/stack-trace-utils.js"() { + init_object_utils(); + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mysql/mysql-driver.js +function isOkPacket(obj) { + return isObject3(obj) && "insertId" in obj && "affectedRows" in obj; +} +var PRIVATE_RELEASE_METHOD, MysqlDriver, MysqlConnection; +var init_mysql_driver = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mysql/mysql-driver.js"() { + init_savepoint_parser(); + init_compiled_query(); + init_object_utils(); + init_query_id(); + init_stack_trace_utils(); + PRIVATE_RELEASE_METHOD = /* @__PURE__ */ Symbol(); + MysqlDriver = class { + #config; + #connections = /* @__PURE__ */ new WeakMap(); + #pool; + constructor(configOrPool) { + this.#config = freeze2({ ...configOrPool }); + } + async init() { + this.#pool = isFunction(this.#config.pool) ? await this.#config.pool() : this.#config.pool; + } + async acquireConnection() { + const rawConnection = await this.#acquireConnection(); + let connection2 = this.#connections.get(rawConnection); + if (!connection2) { + connection2 = new MysqlConnection(rawConnection); + this.#connections.set(rawConnection, connection2); + if (this.#config?.onCreateConnection) { + await this.#config.onCreateConnection(connection2); + } + } + if (this.#config?.onReserveConnection) { + await this.#config.onReserveConnection(connection2); + } + return connection2; + } + async #acquireConnection() { + return new Promise((resolve4, reject) => { + this.#pool.getConnection(async (err, rawConnection) => { + if (err) { + reject(err); + } else { + resolve4(rawConnection); + } + }); + }); + } + async beginTransaction(connection2, settings) { + if (settings.isolationLevel || settings.accessMode) { + const parts = []; + if (settings.isolationLevel) { + parts.push(`isolation level ${settings.isolationLevel}`); + } + if (settings.accessMode) { + parts.push(settings.accessMode); + } + const sql3 = `set transaction ${parts.join(", ")}`; + await connection2.executeQuery(CompiledQuery.raw(sql3)); + } + await connection2.executeQuery(CompiledQuery.raw("begin")); + } + async commitTransaction(connection2) { + await connection2.executeQuery(CompiledQuery.raw("commit")); + } + async rollbackTransaction(connection2) { + await connection2.executeQuery(CompiledQuery.raw("rollback")); + } + async savepoint(connection2, savepointName, compileQuery) { + await connection2.executeQuery(compileQuery(parseSavepointCommand("savepoint", savepointName), createQueryId())); + } + async rollbackToSavepoint(connection2, savepointName, compileQuery) { + await connection2.executeQuery(compileQuery(parseSavepointCommand("rollback to", savepointName), createQueryId())); + } + async releaseSavepoint(connection2, savepointName, compileQuery) { + await connection2.executeQuery(compileQuery(parseSavepointCommand("release savepoint", savepointName), createQueryId())); + } + async releaseConnection(connection2) { + connection2[PRIVATE_RELEASE_METHOD](); + } + async destroy() { + return new Promise((resolve4, reject) => { + this.#pool.end((err) => { + if (err) { + reject(err); + } else { + resolve4(); + } + }); + }); + } + }; + MysqlConnection = class { + #rawConnection; + constructor(rawConnection) { + this.#rawConnection = rawConnection; + } + async executeQuery(compiledQuery) { + try { + const result = await this.#executeQuery(compiledQuery); + if (isOkPacket(result)) { + const { insertId, affectedRows, changedRows } = result; + return { + insertId: insertId !== void 0 && insertId !== null && insertId.toString() !== "0" ? BigInt(insertId) : void 0, + numAffectedRows: affectedRows !== void 0 && affectedRows !== null ? BigInt(affectedRows) : void 0, + numChangedRows: changedRows !== void 0 && changedRows !== null ? BigInt(changedRows) : void 0, + rows: [] + }; + } else if (Array.isArray(result)) { + return { + rows: result + }; + } + return { + rows: [] + }; + } catch (err) { + throw extendStackTrace(err, new Error()); + } + } + #executeQuery(compiledQuery) { + return new Promise((resolve4, reject) => { + this.#rawConnection.query(compiledQuery.sql, compiledQuery.parameters, (err, result) => { + if (err) { + reject(err); + } else { + resolve4(result); + } + }); + }); + } + async *streamQuery(compiledQuery, _chunkSize) { + const stream = this.#rawConnection.query(compiledQuery.sql, compiledQuery.parameters).stream({ + objectMode: true + }); + try { + for await (const row of stream) { + yield { + rows: [row] + }; + } + } catch (ex) { + if (ex && typeof ex === "object" && "code" in ex && // @ts-ignore + ex.code === "ERR_STREAM_PREMATURE_CLOSE") { + return; + } + throw ex; + } + } + [PRIVATE_RELEASE_METHOD]() { + this.#rawConnection.release(); + } + }; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mysql/mysql-query-compiler.js +var LITERAL_ESCAPE_REGEX, ID_WRAP_REGEX3, MysqlQueryCompiler; +var init_mysql_query_compiler = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mysql/mysql-query-compiler.js"() { + init_default_query_compiler(); + LITERAL_ESCAPE_REGEX = /\\|'/g; + ID_WRAP_REGEX3 = /`/g; + MysqlQueryCompiler = class extends DefaultQueryCompiler { + getCurrentParameterPlaceholder() { + return "?"; + } + getLeftExplainOptionsWrapper() { + return ""; + } + getExplainOptionAssignment() { + return "="; + } + getExplainOptionsDelimiter() { + return " "; + } + getRightExplainOptionsWrapper() { + return ""; + } + getLeftIdentifierWrapper() { + return ID_WRAP_REGEX3.source; + } + getRightIdentifierWrapper() { + return ID_WRAP_REGEX3.source; + } + sanitizeIdentifier(identifier) { + return identifier.replace(ID_WRAP_REGEX3, "``"); + } + /** + * MySQL requires escaping backslashes in string literals when using the + * default NO_BACKSLASH_ESCAPES=OFF mode. Without this, a backslash + * followed by a quote (\') can break out of the string literal. + * + * @see https://dev.mysql.com/doc/refman/9.6/en/string-literals.html + */ + sanitizeStringLiteral(value) { + return value.replace(LITERAL_ESCAPE_REGEX, (char2) => char2 === "\\" ? "\\\\" : "''"); + } + visitCreateIndex(node) { + this.append("create "); + if (node.unique) { + this.append("unique "); + } + this.append("index "); + if (node.ifNotExists) { + this.append("if not exists "); + } + this.visitNode(node.name); + if (node.using) { + this.append(" using "); + this.visitNode(node.using); + } + if (node.table) { + this.append(" on "); + this.visitNode(node.table); + } + if (node.columns) { + this.append(" ("); + this.compileList(node.columns); + this.append(")"); + } + if (node.where) { + this.append(" "); + this.visitNode(node.where); + } + } + }; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mysql/mysql-introspector.js +var MysqlIntrospector; +var init_mysql_introspector = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mysql/mysql-introspector.js"() { + init_migrator(); + init_object_utils(); + init_sql3(); + MysqlIntrospector = class { + #db; + constructor(db) { + this.#db = db; + } + async getSchemas() { + let rawSchemas = await this.#db.selectFrom("information_schema.schemata").select("schema_name").$castTo().execute(); + return rawSchemas.map((it) => ({ name: it.SCHEMA_NAME })); + } + async getTables(options = { withInternalKyselyTables: false }) { + let query = this.#db.selectFrom("information_schema.columns as columns").innerJoin("information_schema.tables as tables", (b6) => b6.onRef("columns.TABLE_CATALOG", "=", "tables.TABLE_CATALOG").onRef("columns.TABLE_SCHEMA", "=", "tables.TABLE_SCHEMA").onRef("columns.TABLE_NAME", "=", "tables.TABLE_NAME")).select([ + "columns.COLUMN_NAME", + "columns.COLUMN_DEFAULT", + "columns.TABLE_NAME", + "columns.TABLE_SCHEMA", + "tables.TABLE_TYPE", + "columns.IS_NULLABLE", + "columns.DATA_TYPE", + "columns.EXTRA", + "columns.COLUMN_COMMENT" + ]).where("columns.TABLE_SCHEMA", "=", sql2`database()`).orderBy("columns.TABLE_NAME").orderBy("columns.ORDINAL_POSITION").$castTo(); + if (!options.withInternalKyselyTables) { + query = query.where("columns.TABLE_NAME", "!=", DEFAULT_MIGRATION_TABLE).where("columns.TABLE_NAME", "!=", DEFAULT_MIGRATION_LOCK_TABLE); + } + const rawColumns = await query.execute(); + return this.#parseTableMetadata(rawColumns); + } + async getMetadata(options) { + return { + tables: await this.getTables(options) + }; + } + #parseTableMetadata(columns) { + return columns.reduce((tables, it) => { + let table = tables.find((tbl) => tbl.name === it.TABLE_NAME); + if (!table) { + table = freeze2({ + name: it.TABLE_NAME, + isView: it.TABLE_TYPE === "VIEW", + schema: it.TABLE_SCHEMA, + columns: [] + }); + tables.push(table); + } + table.columns.push(freeze2({ + name: it.COLUMN_NAME, + dataType: it.DATA_TYPE, + isNullable: it.IS_NULLABLE === "YES", + isAutoIncrementing: it.EXTRA.toLowerCase().includes("auto_increment"), + hasDefaultValue: it.COLUMN_DEFAULT !== null, + comment: it.COLUMN_COMMENT === "" ? void 0 : it.COLUMN_COMMENT + })); + return tables; + }, []); + } + }; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mysql/mysql-adapter.js +var LOCK_ID2, LOCK_TIMEOUT_SECONDS, MysqlAdapter; +var init_mysql_adapter = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mysql/mysql-adapter.js"() { + init_sql3(); + init_dialect_adapter_base(); + LOCK_ID2 = "ea586330-2c93-47c8-908d-981d9d270f9d"; + LOCK_TIMEOUT_SECONDS = 60 * 60; + MysqlAdapter = class extends DialectAdapterBase { + get supportsTransactionalDdl() { + return false; + } + get supportsReturning() { + return false; + } + async acquireMigrationLock(db, _opt) { + await sql2`select get_lock(${sql2.lit(LOCK_ID2)}, ${sql2.lit(LOCK_TIMEOUT_SECONDS)})`.execute(db); + } + async releaseMigrationLock(db, _opt) { + await sql2`select release_lock(${sql2.lit(LOCK_ID2)})`.execute(db); + } + }; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mysql/mysql-dialect.js +var MysqlDialect; +var init_mysql_dialect = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mysql/mysql-dialect.js"() { + init_mysql_driver(); + init_mysql_query_compiler(); + init_mysql_introspector(); + init_mysql_adapter(); + MysqlDialect = class { + #config; + constructor(config3) { + this.#config = config3; + } + createDriver() { + return new MysqlDriver(this.#config); + } + createQueryCompiler() { + return new MysqlQueryCompiler(); + } + createAdapter() { + return new MysqlAdapter(); + } + createIntrospector(db) { + return new MysqlIntrospector(db); + } + }; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mysql/mysql-dialect-config.js +var init_mysql_dialect_config = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mysql/mysql-dialect-config.js"() { + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/postgres/postgres-driver.js +var PRIVATE_RELEASE_METHOD2, PostgresDriver, PostgresConnection; +var init_postgres_driver = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/postgres/postgres-driver.js"() { + init_savepoint_parser(); + init_compiled_query(); + init_object_utils(); + init_query_id(); + init_stack_trace_utils(); + PRIVATE_RELEASE_METHOD2 = /* @__PURE__ */ Symbol(); + PostgresDriver = class { + #config; + #connections = /* @__PURE__ */ new WeakMap(); + #pool; + constructor(config3) { + this.#config = freeze2({ ...config3 }); + } + async init() { + this.#pool = isFunction(this.#config.pool) ? await this.#config.pool() : this.#config.pool; + } + async acquireConnection() { + const client2 = await this.#pool.connect(); + let connection2 = this.#connections.get(client2); + if (!connection2) { + connection2 = new PostgresConnection(client2, { + cursor: this.#config.cursor ?? null + }); + this.#connections.set(client2, connection2); + if (this.#config.onCreateConnection) { + await this.#config.onCreateConnection(connection2); + } + } + if (this.#config.onReserveConnection) { + await this.#config.onReserveConnection(connection2); + } + return connection2; + } + async beginTransaction(connection2, settings) { + if (settings.isolationLevel || settings.accessMode) { + let sql3 = "start transaction"; + if (settings.isolationLevel) { + sql3 += ` isolation level ${settings.isolationLevel}`; + } + if (settings.accessMode) { + sql3 += ` ${settings.accessMode}`; + } + await connection2.executeQuery(CompiledQuery.raw(sql3)); + } else { + await connection2.executeQuery(CompiledQuery.raw("begin")); + } + } + async commitTransaction(connection2) { + await connection2.executeQuery(CompiledQuery.raw("commit")); + } + async rollbackTransaction(connection2) { + await connection2.executeQuery(CompiledQuery.raw("rollback")); + } + async savepoint(connection2, savepointName, compileQuery) { + await connection2.executeQuery(compileQuery(parseSavepointCommand("savepoint", savepointName), createQueryId())); + } + async rollbackToSavepoint(connection2, savepointName, compileQuery) { + await connection2.executeQuery(compileQuery(parseSavepointCommand("rollback to", savepointName), createQueryId())); + } + async releaseSavepoint(connection2, savepointName, compileQuery) { + await connection2.executeQuery(compileQuery(parseSavepointCommand("release", savepointName), createQueryId())); + } + async releaseConnection(connection2) { + connection2[PRIVATE_RELEASE_METHOD2](); + } + async destroy() { + if (this.#pool) { + const pool = this.#pool; + this.#pool = void 0; + await pool.end(); + } + } + }; + PostgresConnection = class { + #client; + #options; + constructor(client2, options) { + this.#client = client2; + this.#options = options; + } + async executeQuery(compiledQuery) { + try { + const { command, rowCount, rows } = await this.#client.query(compiledQuery.sql, [...compiledQuery.parameters]); + return { + numAffectedRows: command === "INSERT" || command === "UPDATE" || command === "DELETE" || command === "MERGE" ? BigInt(rowCount) : void 0, + rows: rows ?? [] + }; + } catch (err) { + throw extendStackTrace(err, new Error()); + } + } + async *streamQuery(compiledQuery, chunkSize) { + if (!this.#options.cursor) { + throw new Error("'cursor' is not present in your postgres dialect config. It's required to make streaming work in postgres."); + } + if (!Number.isInteger(chunkSize) || chunkSize <= 0) { + throw new Error("chunkSize must be a positive integer"); + } + const cursor2 = this.#client.query(new this.#options.cursor(compiledQuery.sql, compiledQuery.parameters.slice())); + try { + while (true) { + const rows = await cursor2.read(chunkSize); + if (rows.length === 0) { + break; + } + yield { + rows + }; + } + } finally { + await cursor2.close(); + } + } + [PRIVATE_RELEASE_METHOD2]() { + this.#client.release(); + } + }; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/postgres/postgres-dialect-config.js +var init_postgres_dialect_config = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/postgres/postgres-dialect-config.js"() { + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/postgres/postgres-dialect.js +var PostgresDialect; +var init_postgres_dialect = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/postgres/postgres-dialect.js"() { + init_postgres_driver(); + init_postgres_introspector(); + init_postgres_query_compiler(); + init_postgres_adapter(); + PostgresDialect = class { + #config; + constructor(config3) { + this.#config = config3; + } + createDriver() { + return new PostgresDriver(this.#config); + } + createQueryCompiler() { + return new PostgresQueryCompiler(); + } + createAdapter() { + return new PostgresAdapter(); + } + createIntrospector(db) { + return new PostgresIntrospector(db); + } + }; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mssql/mssql-adapter.js +var MssqlAdapter; +var init_mssql_adapter = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mssql/mssql-adapter.js"() { + init_migrator(); + init_sql3(); + init_dialect_adapter_base(); + MssqlAdapter = class extends DialectAdapterBase { + get supportsCreateIfNotExists() { + return false; + } + get supportsTransactionalDdl() { + return true; + } + get supportsOutput() { + return true; + } + async acquireMigrationLock(db) { + await sql2`exec sp_getapplock @DbPrincipal = ${sql2.lit("dbo")}, @Resource = ${sql2.lit(DEFAULT_MIGRATION_TABLE)}, @LockMode = ${sql2.lit("Exclusive")}`.execute(db); + } + async releaseMigrationLock() { + } + }; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mssql/mssql-dialect-config.js +var init_mssql_dialect_config = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mssql/mssql-dialect-config.js"() { + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mssql/mssql-driver.js +var PRIVATE_RESET_METHOD, PRIVATE_DESTROY_METHOD, PRIVATE_VALIDATE_METHOD, MssqlDriver, MssqlConnection, MssqlRequest; +var init_mssql_driver = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mssql/mssql-driver.js"() { + init_object_utils(); + init_compiled_query(); + init_stack_trace_utils(); + init_random_string(); + init_deferred(); + PRIVATE_RESET_METHOD = /* @__PURE__ */ Symbol(); + PRIVATE_DESTROY_METHOD = /* @__PURE__ */ Symbol(); + PRIVATE_VALIDATE_METHOD = /* @__PURE__ */ Symbol(); + MssqlDriver = class { + #config; + #pool; + constructor(config3) { + this.#config = freeze2({ ...config3 }); + const { tarn, tedious, validateConnections } = this.#config; + const { validateConnections: deprecatedValidateConnections, ...poolOptions } = tarn.options; + this.#pool = new tarn.Pool({ + ...poolOptions, + create: async () => { + const connection2 = await tedious.connectionFactory(); + return await new MssqlConnection(connection2, tedious).connect(); + }, + destroy: async (connection2) => { + await connection2[PRIVATE_DESTROY_METHOD](); + }, + // @ts-ignore `tarn` accepts a function that returns a promise here, but + // the types are not aligned and it type errors. + validate: validateConnections === false || deprecatedValidateConnections === false ? void 0 : (connection2) => connection2[PRIVATE_VALIDATE_METHOD]() + }); + } + async init() { + } + async acquireConnection() { + return await this.#pool.acquire().promise; + } + async beginTransaction(connection2, settings) { + await connection2.beginTransaction(settings); + } + async commitTransaction(connection2) { + await connection2.commitTransaction(); + } + async rollbackTransaction(connection2) { + await connection2.rollbackTransaction(); + } + async savepoint(connection2, savepointName) { + await connection2.savepoint(savepointName); + } + async rollbackToSavepoint(connection2, savepointName) { + await connection2.rollbackTransaction(savepointName); + } + async releaseConnection(connection2) { + if (this.#config.resetConnectionsOnRelease || this.#config.tedious.resetConnectionOnRelease) { + await connection2[PRIVATE_RESET_METHOD](); + } + this.#pool.release(connection2); + } + async destroy() { + await this.#pool.destroy(); + } + }; + MssqlConnection = class { + #connection; + #hasSocketError; + #tedious; + constructor(connection2, tedious) { + this.#connection = connection2; + this.#hasSocketError = false; + this.#tedious = tedious; + } + async beginTransaction(settings) { + const { isolationLevel } = settings; + await new Promise((resolve4, reject) => this.#connection.beginTransaction((error50) => { + if (error50) + reject(error50); + else + resolve4(void 0); + }, isolationLevel ? randomString2(8) : void 0, isolationLevel ? this.#getTediousIsolationLevel(isolationLevel) : void 0)); + } + async commitTransaction() { + await new Promise((resolve4, reject) => this.#connection.commitTransaction((error50) => { + if (error50) + reject(error50); + else + resolve4(void 0); + })); + } + async connect() { + const { promise: waitForConnected, reject, resolve: resolve4 } = new Deferred(); + this.#connection.connect((error50) => { + if (error50) { + return reject(error50); + } + resolve4(); + }); + this.#connection.on("error", (error50) => { + if (error50 instanceof Error && "code" in error50 && error50.code === "ESOCKET") { + this.#hasSocketError = true; + } + console.error(error50); + reject(error50); + }); + function endListener() { + reject(new Error("The connection ended without ever completing the connection")); + } + this.#connection.once("end", endListener); + await waitForConnected; + this.#connection.off("end", endListener); + return this; + } + async executeQuery(compiledQuery) { + try { + const deferred = new Deferred(); + const request = new MssqlRequest({ + compiledQuery, + tedious: this.#tedious, + onDone: deferred + }); + this.#connection.execSql(request.request); + const { rowCount, rows } = await deferred.promise; + return { + numAffectedRows: rowCount !== void 0 ? BigInt(rowCount) : void 0, + rows + }; + } catch (err) { + throw extendStackTrace(err, new Error()); + } + } + async rollbackTransaction(savepointName) { + await new Promise((resolve4, reject) => this.#connection.rollbackTransaction((error50) => { + if (error50) + reject(error50); + else + resolve4(void 0); + }, savepointName)); + } + async savepoint(savepointName) { + await new Promise((resolve4, reject) => this.#connection.saveTransaction((error50) => { + if (error50) + reject(error50); + else + resolve4(void 0); + }, savepointName)); + } + async *streamQuery(compiledQuery, chunkSize) { + if (!Number.isInteger(chunkSize) || chunkSize <= 0) { + throw new Error("chunkSize must be a positive integer"); + } + const request = new MssqlRequest({ + compiledQuery, + streamChunkSize: chunkSize, + tedious: this.#tedious + }); + this.#connection.execSql(request.request); + try { + while (true) { + const rows = await request.readChunk(); + if (rows.length === 0) { + break; + } + yield { rows }; + if (rows.length < chunkSize) { + break; + } + } + } finally { + await this.#cancelRequest(request); + } + } + #getTediousIsolationLevel(isolationLevel) { + const { ISOLATION_LEVEL } = this.#tedious; + const mapper = { + "read committed": ISOLATION_LEVEL.READ_COMMITTED, + "read uncommitted": ISOLATION_LEVEL.READ_UNCOMMITTED, + "repeatable read": ISOLATION_LEVEL.REPEATABLE_READ, + serializable: ISOLATION_LEVEL.SERIALIZABLE, + snapshot: ISOLATION_LEVEL.SNAPSHOT + }; + const tediousIsolationLevel = mapper[isolationLevel]; + if (tediousIsolationLevel === void 0) { + throw new Error(`Unknown isolation level: ${isolationLevel}`); + } + return tediousIsolationLevel; + } + #cancelRequest(request) { + return new Promise((resolve4) => { + request.request.once("requestCompleted", resolve4); + const wasCanceled = this.#connection.cancel(); + if (!wasCanceled) { + request.request.off("requestCompleted", resolve4); + resolve4(); + } + }); + } + [PRIVATE_DESTROY_METHOD]() { + if ("closed" in this.#connection && this.#connection.closed) { + return Promise.resolve(); + } + return new Promise((resolve4) => { + this.#connection.once("end", resolve4); + this.#connection.close(); + }); + } + async [PRIVATE_RESET_METHOD]() { + await new Promise((resolve4, reject) => { + this.#connection.reset((error50) => { + if (error50) { + return reject(error50); + } + resolve4(); + }); + }); + } + async [PRIVATE_VALIDATE_METHOD]() { + if (this.#hasSocketError || this.#isConnectionClosed()) { + return false; + } + try { + const deferred = new Deferred(); + const request = new MssqlRequest({ + compiledQuery: CompiledQuery.raw("select 1"), + onDone: deferred, + tedious: this.#tedious + }); + this.#connection.execSql(request.request); + await deferred.promise; + return true; + } catch { + return false; + } + } + #isConnectionClosed() { + return "closed" in this.#connection && Boolean(this.#connection.closed); + } + }; + MssqlRequest = class { + #request; + #rows; + #streamChunkSize; + #subscribers; + #tedious; + #rowCount; + constructor(props) { + const { compiledQuery, onDone, streamChunkSize, tedious } = props; + this.#rows = []; + this.#streamChunkSize = streamChunkSize; + this.#subscribers = {}; + this.#tedious = tedious; + if (onDone) { + const subscriptionKey = "onDone"; + this.#subscribers[subscriptionKey] = (event, error50) => { + if (event === "chunkReady") { + return; + } + delete this.#subscribers[subscriptionKey]; + if (event === "error") { + return onDone.reject(error50); + } + onDone.resolve({ + rowCount: this.#rowCount, + rows: this.#rows + }); + }; + } + this.#request = new this.#tedious.Request(compiledQuery.sql, (err, rowCount) => { + if (err) { + return Object.values(this.#subscribers).forEach((subscriber) => subscriber("error", err instanceof AggregateError ? err.errors : err)); + } + this.#rowCount = rowCount; + }); + this.#addParametersToRequest(compiledQuery.parameters); + this.#attachListeners(); + } + get request() { + return this.#request; + } + readChunk() { + const subscriptionKey = this.readChunk.name; + return new Promise((resolve4, reject) => { + this.#subscribers[subscriptionKey] = (event, error50) => { + delete this.#subscribers[subscriptionKey]; + if (event === "error") { + return reject(error50); + } + resolve4(this.#rows.splice(0, this.#streamChunkSize)); + }; + this.#request.resume(); + }); + } + #addParametersToRequest(parameters) { + for (let i5 = 0; i5 < parameters.length; i5++) { + const parameter = parameters[i5]; + this.#request.addParameter(String(i5 + 1), this.#getTediousDataType(parameter), parameter); + } + } + #attachListeners() { + const pauseAndEmitChunkReady = this.#streamChunkSize ? () => { + if (this.#streamChunkSize <= this.#rows.length) { + this.#request.pause(); + Object.values(this.#subscribers).forEach((subscriber) => subscriber("chunkReady")); + } + } : () => { + }; + const rowListener = (columns) => { + const row = {}; + for (const column of columns) { + row[column.metadata.colName] = column.value; + } + this.#rows.push(row); + pauseAndEmitChunkReady(); + }; + this.#request.on("row", rowListener); + this.#request.once("requestCompleted", () => { + Object.values(this.#subscribers).forEach((subscriber) => subscriber("completed")); + this.#request.off("row", rowListener); + }); + } + #getTediousDataType(value) { + if (isNull2(value) || isUndefined(value) || isString(value)) { + return this.#tedious.TYPES.NVarChar; + } + if (isBigInt(value) || isNumber(value) && value % 1 === 0) { + if (value < -2147483648 || value > 2147483647) { + return this.#tedious.TYPES.BigInt; + } else { + return this.#tedious.TYPES.Int; + } + } + if (isNumber(value)) { + return this.#tedious.TYPES.Float; + } + if (isBoolean(value)) { + return this.#tedious.TYPES.Bit; + } + if (isDate(value)) { + return this.#tedious.TYPES.DateTime; + } + if (isBuffer(value)) { + return this.#tedious.TYPES.VarBinary; + } + return this.#tedious.TYPES.NVarChar; + } + }; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mssql/mssql-introspector.js +var MssqlIntrospector; +var init_mssql_introspector = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mssql/mssql-introspector.js"() { + init_migrator(); + init_object_utils(); + MssqlIntrospector = class { + #db; + constructor(db) { + this.#db = db; + } + async getSchemas() { + return await this.#db.selectFrom("sys.schemas").select("name").execute(); + } + async getTables(options = { withInternalKyselyTables: false }) { + const rawColumns = await this.#db.selectFrom("sys.tables as tables").leftJoin("sys.schemas as table_schemas", "table_schemas.schema_id", "tables.schema_id").innerJoin("sys.columns as columns", "columns.object_id", "tables.object_id").innerJoin("sys.types as types", "types.user_type_id", "columns.user_type_id").leftJoin("sys.schemas as type_schemas", "type_schemas.schema_id", "types.schema_id").leftJoin("sys.extended_properties as comments", (join4) => join4.onRef("comments.major_id", "=", "tables.object_id").onRef("comments.minor_id", "=", "columns.column_id").on("comments.name", "=", "MS_Description")).$if(!options.withInternalKyselyTables, (qb) => qb.where("tables.name", "!=", DEFAULT_MIGRATION_TABLE).where("tables.name", "!=", DEFAULT_MIGRATION_LOCK_TABLE)).select([ + "tables.name as table_name", + (eb) => eb.ref("tables.type").$castTo().as("table_type"), + "table_schemas.name as table_schema_name", + "columns.default_object_id as column_default_object_id", + "columns.generated_always_type_desc as column_generated_always_type", + "columns.is_computed as column_is_computed", + "columns.is_identity as column_is_identity", + "columns.is_nullable as column_is_nullable", + "columns.is_rowguidcol as column_is_rowguidcol", + "columns.name as column_name", + "types.is_nullable as type_is_nullable", + "types.name as type_name", + "type_schemas.name as type_schema_name", + "comments.value as column_comment" + ]).unionAll(this.#db.selectFrom("sys.views as views").leftJoin("sys.schemas as view_schemas", "view_schemas.schema_id", "views.schema_id").innerJoin("sys.columns as columns", "columns.object_id", "views.object_id").innerJoin("sys.types as types", "types.user_type_id", "columns.user_type_id").leftJoin("sys.schemas as type_schemas", "type_schemas.schema_id", "types.schema_id").leftJoin("sys.extended_properties as comments", (join4) => join4.onRef("comments.major_id", "=", "views.object_id").onRef("comments.minor_id", "=", "columns.column_id").on("comments.name", "=", "MS_Description")).select([ + "views.name as table_name", + "views.type as table_type", + "view_schemas.name as table_schema_name", + "columns.default_object_id as column_default_object_id", + "columns.generated_always_type_desc as column_generated_always_type", + "columns.is_computed as column_is_computed", + "columns.is_identity as column_is_identity", + "columns.is_nullable as column_is_nullable", + "columns.is_rowguidcol as column_is_rowguidcol", + "columns.name as column_name", + "types.is_nullable as type_is_nullable", + "types.name as type_name", + "type_schemas.name as type_schema_name", + "comments.value as column_comment" + ])).orderBy("table_schema_name").orderBy("table_name").orderBy("column_name").execute(); + const tableDictionary = {}; + for (const rawColumn of rawColumns) { + const key = `${rawColumn.table_schema_name}.${rawColumn.table_name}`; + const table = tableDictionary[key] = tableDictionary[key] || freeze2({ + columns: [], + isView: rawColumn.table_type === "V ", + name: rawColumn.table_name, + schema: rawColumn.table_schema_name ?? void 0 + }); + table.columns.push(freeze2({ + dataType: rawColumn.type_name, + dataTypeSchema: rawColumn.type_schema_name ?? void 0, + hasDefaultValue: rawColumn.column_default_object_id > 0 || rawColumn.column_generated_always_type !== "NOT_APPLICABLE" || rawColumn.column_is_identity || rawColumn.column_is_computed || rawColumn.column_is_rowguidcol, + isAutoIncrementing: rawColumn.column_is_identity, + isNullable: rawColumn.column_is_nullable && rawColumn.type_is_nullable, + name: rawColumn.column_name, + comment: rawColumn.column_comment ?? void 0 + })); + } + return Object.values(tableDictionary); + } + async getMetadata(options) { + return { + tables: await this.getTables(options) + }; + } + }; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mssql/mssql-query-compiler.js +var COLLATION_CHAR_REGEX, MssqlQueryCompiler; +var init_mssql_query_compiler = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mssql/mssql-query-compiler.js"() { + init_default_query_compiler(); + COLLATION_CHAR_REGEX = /^[a-z0-9_]$/i; + MssqlQueryCompiler = class extends DefaultQueryCompiler { + getCurrentParameterPlaceholder() { + return `@${this.numParameters}`; + } + visitOffset(node) { + super.visitOffset(node); + this.append(" rows"); + } + // mssql allows multi-column alterations in a single statement, + // but you can only use the command keyword/s once. + // it also doesn't support multiple kinds of commands in the same + // alter table statement, but we compile that anyway for the sake + // of WYSIWYG. + compileColumnAlterations(columnAlterations) { + const nodesByKind = {}; + for (const columnAlteration of columnAlterations) { + if (!nodesByKind[columnAlteration.kind]) { + nodesByKind[columnAlteration.kind] = []; + } + nodesByKind[columnAlteration.kind].push(columnAlteration); + } + let first = true; + if (nodesByKind.AddColumnNode) { + this.append("add "); + this.compileList(nodesByKind.AddColumnNode); + first = false; + } + if (nodesByKind.AlterColumnNode) { + if (!first) + this.append(", "); + this.compileList(nodesByKind.AlterColumnNode); + } + if (nodesByKind.DropColumnNode) { + if (!first) + this.append(", "); + this.append("drop column "); + this.compileList(nodesByKind.DropColumnNode); + } + if (nodesByKind.ModifyColumnNode) { + if (!first) + this.append(", "); + this.compileList(nodesByKind.ModifyColumnNode); + } + if (nodesByKind.RenameColumnNode) { + if (!first) + this.append(", "); + this.compileList(nodesByKind.RenameColumnNode); + } + } + visitAddColumn(node) { + this.visitNode(node.column); + } + visitDropColumn(node) { + this.visitNode(node.column); + } + visitMergeQuery(node) { + super.visitMergeQuery(node); + this.append(";"); + } + visitCollate(node) { + this.append("collate "); + const { name } = node.collation; + for (const char2 of name) { + if (!COLLATION_CHAR_REGEX.test(char2)) { + throw new Error(`Invalid collation: ${name}`); + } + } + this.append(name); + } + announcesNewColumnDataType() { + return false; + } + }; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mssql/mssql-dialect.js +var MssqlDialect; +var init_mssql_dialect = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mssql/mssql-dialect.js"() { + init_mssql_adapter(); + init_mssql_driver(); + init_mssql_introspector(); + init_mssql_query_compiler(); + MssqlDialect = class { + #config; + constructor(config3) { + this.#config = config3; + } + createDriver() { + return new MssqlDriver(this.#config); + } + createQueryCompiler() { + return new MssqlQueryCompiler(); + } + createAdapter() { + return new MssqlAdapter(); + } + createIntrospector(db) { + return new MssqlIntrospector(db); + } + }; + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-compiler/query-compiler.js +var init_query_compiler = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-compiler/query-compiler.js"() { + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/migration/file-migration-provider.js +var init_file_migration_provider = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/migration/file-migration-provider.js"() { + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/kysely-plugin.js +var init_kysely_plugin = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/kysely-plugin.js"() { + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/camel-case/camel-case-plugin.js +var init_camel_case_plugin = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/camel-case/camel-case-plugin.js"() { + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/deduplicate-joins/deduplicate-joins-plugin.js +var init_deduplicate_joins_plugin = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/deduplicate-joins/deduplicate-joins-plugin.js"() { + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/parse-json-results/parse-json-results-plugin.js +var init_parse_json_results_plugin = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/parse-json-results/parse-json-results-plugin.js"() { + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/handle-empty-in-lists/handle-empty-in-lists-plugin.js +var init_handle_empty_in_lists_plugin = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/handle-empty-in-lists/handle-empty-in-lists-plugin.js"() { + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/handle-empty-in-lists/handle-empty-in-lists.js +var init_handle_empty_in_lists = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/handle-empty-in-lists/handle-empty-in-lists.js"() { + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/constraint-node.js +var init_constraint_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/constraint-node.js"() { + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/operation-node.js +var init_operation_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/operation-node.js"() { + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/simple-reference-expression-node.js +var init_simple_reference_expression_node = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/simple-reference-expression-node.js"() { + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/column-type.js +var init_column_type = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/column-type.js"() { + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/explainable.js +var init_explainable = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/explainable.js"() { + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/streamable.js +var init_streamable = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/streamable.js"() { + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/infer-result.js +var init_infer_result = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/infer-result.js"() { + } +}); + +// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/index.js +var init_esm = __esm({ + "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/index.js"() { + init_kysely(); + init_query_creator(); + init_expression(); + init_expression_wrapper(); + init_where_interface(); + init_returning_interface(); + init_output_interface(); + init_having_interface(); + init_order_by_interface(); + init_select_query_builder(); + init_insert_query_builder(); + init_update_query_builder(); + init_delete_query_builder(); + init_no_result_error(); + init_join_builder(); + init_function_module(); + init_insert_result(); + init_delete_result(); + init_update_result(); + init_on_conflict_builder(); + init_aggregate_function_builder(); + init_case_builder(); + init_json_path_builder(); + init_merge_query_builder(); + init_merge_result(); + init_order_by_item_builder(); + init_raw_builder(); + init_sql3(); + init_query_executor(); + init_default_query_executor(); + init_noop_query_executor(); + init_query_executor_provider(); + init_default_query_compiler(); + init_compiled_query(); + init_schema5(); + init_create_table_builder(); + init_create_type_builder(); + init_drop_table_builder(); + init_drop_type_builder(); + init_create_index_builder(); + init_drop_index_builder(); + init_create_schema_builder(); + init_drop_schema_builder(); + init_column_definition_builder(); + init_foreign_key_constraint_builder(); + init_alter_table_builder(); + init_create_view_builder(); + init_refresh_materialized_view_builder(); + init_drop_view_builder(); + init_alter_column_builder(); + init_dynamic(); + init_dynamic_reference_builder(); + init_dynamic_table_builder(); + init_driver2(); + init_database_connection(); + init_connection_provider(); + init_default_connection_provider(); + init_single_connection_provider(); + init_dummy_driver(); + init_dialect2(); + init_dialect_adapter(); + init_dialect_adapter_base(); + init_database_introspector(); + init_sqlite_dialect(); + init_sqlite_dialect_config(); + init_sqlite_driver(); + init_postgres_query_compiler(); + init_postgres_introspector(); + init_postgres_adapter(); + init_mysql_dialect(); + init_mysql_dialect_config(); + init_mysql_driver(); + init_mysql_query_compiler(); + init_mysql_introspector(); + init_mysql_adapter(); + init_postgres_driver(); + init_postgres_dialect_config(); + init_postgres_dialect(); + init_sqlite_query_compiler(); + init_sqlite_introspector(); + init_sqlite_adapter(); + init_mssql_adapter(); + init_mssql_dialect_config(); + init_mssql_dialect(); + init_mssql_driver(); + init_mssql_introspector(); + init_mssql_query_compiler(); + init_default_query_compiler(); + init_query_compiler(); + init_migrator(); + init_file_migration_provider(); + init_kysely_plugin(); + init_camel_case_plugin(); + init_deduplicate_joins_plugin(); + init_with_schema_plugin(); + init_parse_json_results_plugin(); + init_handle_empty_in_lists_plugin(); + init_handle_empty_in_lists(); + init_add_column_node(); + init_add_constraint_node(); + init_add_index_node(); + init_aggregate_function_node(); + init_alias_node(); + init_alter_column_node(); + init_alter_table_node(); + init_and_node(); + init_binary_operation_node(); + init_case_node(); + init_cast_node(); + init_check_constraint_node(); + init_collate_node(); + init_column_definition_node(); + init_column_node(); + init_column_update_node(); + init_common_table_expression_name_node(); + init_common_table_expression_node(); + init_constraint_node(); + init_create_index_node(); + init_create_schema_node(); + init_create_table_node(); + init_create_type_node(); + init_create_view_node(); + init_refresh_materialized_view_node(); + init_data_type_node(); + init_default_insert_value_node(); + init_default_value_node(); + init_delete_query_node(); + init_drop_column_node(); + init_drop_constraint_node(); + init_drop_index_node(); + init_drop_schema_node(); + init_drop_table_node(); + init_drop_type_node(); + init_drop_view_node(); + init_explain_node(); + init_fetch_node(); + init_foreign_key_constraint_node(); + init_from_node(); + init_function_node(); + init_generated_node(); + init_group_by_item_node(); + init_group_by_node(); + init_having_node(); + init_identifier_node(); + init_insert_query_node(); + init_join_node(); + init_json_operator_chain_node(); + init_json_path_leg_node(); + init_json_path_node(); + init_json_reference_node(); + init_limit_node(); + init_list_node(); + init_matched_node(); + init_merge_query_node(); + init_modify_column_node(); + init_offset_node(); + init_on_conflict_node(); + init_on_duplicate_key_node(); + init_on_node(); + init_operation_node_source(); + init_operation_node_transformer(); + init_operation_node_visitor(); + init_operation_node(); + init_operator_node(); + init_or_action_node(); + init_or_node(); + init_order_by_item_node(); + init_order_by_node(); + init_output_node(); + init_over_node(); + init_parens_node(); + init_partition_by_item_node(); + init_partition_by_node(); + init_primary_key_constraint_node(); + init_primitive_value_list_node(); + init_query_node(); + init_raw_node(); + init_reference_node(); + init_references_node(); + init_rename_column_node(); + init_rename_constraint_node(); + init_returning_node(); + init_schemable_identifier_node(); + init_select_all_node(); + init_select_modifier_node(); + init_select_query_node(); + init_selection_node(); + init_set_operation_node(); + init_simple_reference_expression_node(); + init_table_node(); + init_top_node(); + init_tuple_node(); + init_unary_operation_node(); + init_unique_constraint_node(); + init_update_query_node(); + init_using_node(); + init_value_list_node(); + init_value_node(); + init_values_node(); + init_when_node(); + init_where_node(); + init_with_node(); + init_column_type(); + init_compilable(); + init_explainable(); + init_streamable(); + init_log(); + init_infer_result(); + } +}); + +// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/adapters/kysely-adapter/bun-sqlite-dialect.mjs +var bun_sqlite_dialect_exports = {}; +__export(bun_sqlite_dialect_exports, { + BunSqliteDialect: () => BunSqliteDialect +}); +var BunSqliteAdapter, BunSqliteDriver, BunSqliteConnection, ConnectionMutex2, BunSqliteIntrospector, BunSqliteQueryCompiler, BunSqliteDialect; +var init_bun_sqlite_dialect = __esm({ + "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/adapters/kysely-adapter/bun-sqlite-dialect.mjs"() { + init_esm(); + BunSqliteAdapter = class { + get supportsCreateIfNotExists() { + return true; + } + get supportsTransactionalDdl() { + return false; + } + get supportsReturning() { + return true; + } + async acquireMigrationLock() { + } + async releaseMigrationLock() { + } + get supportsOutput() { + return true; + } + }; + BunSqliteDriver = class { + #config; + #connectionMutex = new ConnectionMutex2(); + #db; + #connection; + constructor(config3) { + this.#config = { ...config3 }; + } + async init() { + this.#db = this.#config.database; + this.#connection = new BunSqliteConnection(this.#db); + if (this.#config.onCreateConnection) await this.#config.onCreateConnection(this.#connection); + } + async acquireConnection() { + await this.#connectionMutex.lock(); + return this.#connection; + } + async beginTransaction(connection2) { + await connection2.executeQuery(CompiledQuery.raw("begin")); + } + async commitTransaction(connection2) { + await connection2.executeQuery(CompiledQuery.raw("commit")); + } + async rollbackTransaction(connection2) { + await connection2.executeQuery(CompiledQuery.raw("rollback")); + } + async releaseConnection() { + this.#connectionMutex.unlock(); + } + async destroy() { + this.#db?.close(); + } + }; + BunSqliteConnection = class { + #db; + constructor(db) { + this.#db = db; + } + executeQuery(compiledQuery) { + const { sql: sql$1, parameters } = compiledQuery; + const stmt = this.#db.prepare(sql$1); + return Promise.resolve({ rows: stmt.all(parameters) }); + } + async *streamQuery() { + throw new Error("Streaming query is not supported by SQLite driver."); + } + }; + ConnectionMutex2 = class { + #promise; + #resolve; + async lock() { + while (await this.#promise) await this.#promise; + this.#promise = new Promise((resolve4) => { + this.#resolve = resolve4; + }); + } + unlock() { + const resolve4 = this.#resolve; + this.#promise = void 0; + this.#resolve = void 0; + resolve4?.(); + } + }; + BunSqliteIntrospector = class { + #db; + constructor(db) { + this.#db = db; + } + async getSchemas() { + return []; + } + async getTables(options = { withInternalKyselyTables: false }) { + let query = this.#db.selectFrom("sqlite_schema").where("type", "=", "table").where("name", "not like", "sqlite_%").select("name").$castTo(); + if (!options.withInternalKyselyTables) query = query.where("name", "!=", DEFAULT_MIGRATION_TABLE).where("name", "!=", DEFAULT_MIGRATION_LOCK_TABLE); + const tables = await query.execute(); + return Promise.all(tables.map(({ name }) => this.#getTableMetadata(name))); + } + async getMetadata(options) { + return { tables: await this.getTables(options) }; + } + async #getTableMetadata(table) { + const db = this.#db; + const autoIncrementCol = (await db.selectFrom("sqlite_master").where("name", "=", table).select("sql").$castTo().execute())[0]?.sql?.split(/[\(\),]/)?.find((it) => it.toLowerCase().includes("autoincrement"))?.split(/\s+/)?.[0]?.replace(/["`]/g, ""); + return { + name: table, + columns: (await db.selectFrom(sql2`pragma_table_info(${table})`.as("table_info")).select([ + "name", + "type", + "notnull", + "dflt_value" + ]).execute()).map((col) => ({ + name: col.name, + dataType: col.type, + isNullable: !col.notnull, + isAutoIncrementing: col.name === autoIncrementCol, + hasDefaultValue: col.dflt_value != null + })), + isView: true + }; + } + }; + BunSqliteQueryCompiler = class extends DefaultQueryCompiler { + getCurrentParameterPlaceholder() { + return "?"; + } + getLeftIdentifierWrapper() { + return '"'; + } + getRightIdentifierWrapper() { + return '"'; + } + getAutoIncrement() { + return "autoincrement"; + } + }; + BunSqliteDialect = class { + #config; + constructor(config3) { + this.#config = { ...config3 }; + } + createDriver() { + return new BunSqliteDriver(this.#config); + } + createQueryCompiler() { + return new BunSqliteQueryCompiler(); + } + createAdapter() { + return new BunSqliteAdapter(); + } + createIntrospector(db) { + return new BunSqliteIntrospector(db); + } + }; + } +}); + +// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/adapters/kysely-adapter/node-sqlite-dialect.mjs +var node_sqlite_dialect_exports = {}; +__export(node_sqlite_dialect_exports, { + NodeSqliteDialect: () => NodeSqliteDialect +}); +var NodeSqliteAdapter, NodeSqliteDriver, NodeSqliteConnection, ConnectionMutex3, NodeSqliteIntrospector, NodeSqliteQueryCompiler, NodeSqliteDialect; +var init_node_sqlite_dialect = __esm({ + "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/adapters/kysely-adapter/node-sqlite-dialect.mjs"() { + init_esm(); + NodeSqliteAdapter = class { + get supportsCreateIfNotExists() { + return true; + } + get supportsTransactionalDdl() { + return false; + } + get supportsReturning() { + return true; + } + async acquireMigrationLock() { + } + async releaseMigrationLock() { + } + get supportsOutput() { + return true; + } + }; + NodeSqliteDriver = class { + #config; + #connectionMutex = new ConnectionMutex3(); + #db; + #connection; + constructor(config3) { + this.#config = { ...config3 }; + } + async init() { + this.#db = this.#config.database; + this.#connection = new NodeSqliteConnection(this.#db); + if (this.#config.onCreateConnection) await this.#config.onCreateConnection(this.#connection); + } + async acquireConnection() { + await this.#connectionMutex.lock(); + return this.#connection; + } + async beginTransaction(connection2) { + await connection2.executeQuery(CompiledQuery.raw("begin")); + } + async commitTransaction(connection2) { + await connection2.executeQuery(CompiledQuery.raw("commit")); + } + async rollbackTransaction(connection2) { + await connection2.executeQuery(CompiledQuery.raw("rollback")); + } + async releaseConnection() { + this.#connectionMutex.unlock(); + } + async destroy() { + this.#db?.close(); + } + }; + NodeSqliteConnection = class { + #db; + constructor(db) { + this.#db = db; + } + executeQuery(compiledQuery) { + const { sql: sql$1, parameters } = compiledQuery; + const rows = this.#db.prepare(sql$1).all(...parameters); + return Promise.resolve({ rows }); + } + async *streamQuery() { + throw new Error("Streaming query is not supported by SQLite driver."); + } + }; + ConnectionMutex3 = class { + #promise; + #resolve; + async lock() { + while (await this.#promise) await this.#promise; + this.#promise = new Promise((resolve4) => { + this.#resolve = resolve4; + }); + } + unlock() { + const resolve4 = this.#resolve; + this.#promise = void 0; + this.#resolve = void 0; + resolve4?.(); + } + }; + NodeSqliteIntrospector = class { + #db; + constructor(db) { + this.#db = db; + } + async getSchemas() { + return []; + } + async getTables(options = { withInternalKyselyTables: false }) { + let query = this.#db.selectFrom("sqlite_schema").where("type", "=", "table").where("name", "not like", "sqlite_%").select("name").$castTo(); + if (!options.withInternalKyselyTables) query = query.where("name", "!=", DEFAULT_MIGRATION_TABLE).where("name", "!=", DEFAULT_MIGRATION_LOCK_TABLE); + const tables = await query.execute(); + return Promise.all(tables.map(({ name }) => this.#getTableMetadata(name))); + } + async getMetadata(options) { + return { tables: await this.getTables(options) }; + } + async #getTableMetadata(table) { + const db = this.#db; + const autoIncrementCol = (await db.selectFrom("sqlite_master").where("name", "=", table).select("sql").$castTo().execute())[0]?.sql?.split(/[\(\),]/)?.find((it) => it.toLowerCase().includes("autoincrement"))?.split(/\s+/)?.[0]?.replace(/["`]/g, ""); + return { + name: table, + columns: (await db.selectFrom(sql2`pragma_table_info(${table})`.as("table_info")).select([ + "name", + "type", + "notnull", + "dflt_value" + ]).execute()).map((col) => ({ + name: col.name, + dataType: col.type, + isNullable: !col.notnull, + isAutoIncrementing: col.name === autoIncrementCol, + hasDefaultValue: col.dflt_value != null + })), + isView: true + }; + } + }; + NodeSqliteQueryCompiler = class extends DefaultQueryCompiler { + getCurrentParameterPlaceholder() { + return "?"; + } + getLeftIdentifierWrapper() { + return '"'; + } + getRightIdentifierWrapper() { + return '"'; + } + getAutoIncrement() { + return "autoincrement"; + } + }; + NodeSqliteDialect = class { + #config; + constructor(config3) { + this.#config = { ...config3 }; + } + createDriver() { + return new NodeSqliteDriver(this.#config); + } + createQueryCompiler() { + return new NodeSqliteQueryCompiler(); + } + createAdapter() { + return new NodeSqliteAdapter(); + } + createIntrospector(db) { + return new NodeSqliteIntrospector(db); + } + }; + } +}); + +// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/adapters/kysely-adapter/dialect.mjs +function getKyselyDatabaseType(db) { + if (!db) return null; + if ("dialect" in db) return getKyselyDatabaseType(db.dialect); + if ("createDriver" in db) { + if (db instanceof SqliteDialect) return "sqlite"; + if (db instanceof MysqlDialect) return "mysql"; + if (db instanceof PostgresDialect) return "postgres"; + if (db instanceof MssqlDialect) return "mssql"; + } + if ("aggregate" in db) return "sqlite"; + if ("getConnection" in db) return "mysql"; + if ("connect" in db) return "postgres"; + if ("fileControl" in db) return "sqlite"; + if ("open" in db && "close" in db && "prepare" in db) return "sqlite"; + return null; +} +var createKyselyAdapter; +var init_dialect3 = __esm({ + "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/adapters/kysely-adapter/dialect.mjs"() { + init_esm(); + createKyselyAdapter = async (config3) => { + const db = config3.database; + if (!db) return { + kysely: null, + databaseType: null, + transaction: void 0 + }; + if ("db" in db) return { + kysely: db.db, + databaseType: db.type, + transaction: db.transaction + }; + if ("dialect" in db) return { + kysely: new Kysely({ dialect: db.dialect }), + databaseType: db.type, + transaction: db.transaction + }; + let dialect = void 0; + const databaseType = getKyselyDatabaseType(db); + if ("createDriver" in db) dialect = db; + if ("aggregate" in db && !("createSession" in db)) dialect = new SqliteDialect({ database: db }); + if ("getConnection" in db) dialect = new MysqlDialect(db); + if ("connect" in db) dialect = new PostgresDialect({ pool: db }); + if ("fileControl" in db) { + const { BunSqliteDialect: BunSqliteDialect2 } = await Promise.resolve().then(() => (init_bun_sqlite_dialect(), bun_sqlite_dialect_exports)); + dialect = new BunSqliteDialect2({ database: db }); + } + if ("createSession" in db) { + let DatabaseSync = void 0; + try { + const nodeSqlite = "node:sqlite"; + ({ DatabaseSync } = await import( + /* @vite-ignore */ + /* webpackIgnore: true */ + nodeSqlite + )); + } catch (error50) { + if (error50 !== null && typeof error50 === "object" && "code" in error50 && error50.code !== "ERR_UNKNOWN_BUILTIN_MODULE") throw error50; + } + if (DatabaseSync && db instanceof DatabaseSync) { + const { NodeSqliteDialect: NodeSqliteDialect2 } = await Promise.resolve().then(() => (init_node_sqlite_dialect(), node_sqlite_dialect_exports)); + dialect = new NodeSqliteDialect2({ database: db }); + } + } + return { + kysely: dialect ? new Kysely({ dialect }) : null, + databaseType, + transaction: void 0 + }; + }; + } +}); + +// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/adapters/kysely-adapter/kysely-adapter.mjs +var kyselyAdapter; +var init_kysely_adapter = __esm({ + "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/adapters/kysely-adapter/kysely-adapter.mjs"() { + init_esm(); + init_adapter(); + kyselyAdapter = (db, config3) => { + let lazyOptions = null; + const createCustomAdapter = (db$1) => { + return ({ getFieldName, schema: schema2, getDefaultFieldName, getDefaultModelName, getFieldAttributes, getModelName }) => { + const selectAllJoins = (join4) => { + const allSelects = []; + const allSelectsStr = []; + if (join4) for (const [joinModel, _] of Object.entries(join4)) { + const fields = schema2[getDefaultModelName(joinModel)]?.fields; + const [_joinModelSchema, joinModelName] = joinModel.includes(".") ? joinModel.split(".") : [void 0, joinModel]; + if (!fields) continue; + fields.id = { type: "string" }; + for (const [field, fieldAttr] of Object.entries(fields)) { + allSelects.push(sql2`${sql2.ref(`join_${joinModelName}`)}.${sql2.ref(fieldAttr.fieldName || field)} as ${sql2.ref(`_joined_${joinModelName}_${fieldAttr.fieldName || field}`)}`); + allSelectsStr.push({ + joinModel, + joinModelRef: joinModelName, + fieldName: fieldAttr.fieldName || field + }); + } + } + return { + allSelectsStr, + allSelects + }; + }; + const withReturning = async (values2, builder, model, where) => { + let res; + if (config3?.type === "mysql") { + await builder.execute(); + const field = values2.id ? "id" : where.length > 0 && where[0]?.field ? where[0].field : "id"; + if (!values2.id && where.length === 0) { + res = await db$1.selectFrom(model).selectAll().orderBy(getFieldName({ + model, + field + }), "desc").limit(1).executeTakeFirst(); + return res; + } + const value = values2[field] || where[0]?.value; + res = await db$1.selectFrom(model).selectAll().orderBy(getFieldName({ + model, + field + }), "desc").where(getFieldName({ + model, + field + }), "=", value).limit(1).executeTakeFirst(); + return res; + } + if (config3?.type === "mssql") { + res = await builder.outputAll("inserted").executeTakeFirst(); + return res; + } + res = await builder.returningAll().executeTakeFirst(); + return res; + }; + function convertWhereClause(model, w5) { + if (!w5) return { + and: null, + or: null + }; + const conditions = { + and: [], + or: [] + }; + w5.forEach((condition) => { + const { field: _field, value: _value, operator = "=", connector = "AND" } = condition; + const value = _value; + const field = getFieldName({ + model, + field: _field + }); + const expr = (eb) => { + const f5 = `${model}.${field}`; + if (operator.toLowerCase() === "in") return eb(f5, "in", Array.isArray(value) ? value : [value]); + if (operator.toLowerCase() === "not_in") return eb(f5, "not in", Array.isArray(value) ? value : [value]); + if (operator === "contains") return eb(f5, "like", `%${value}%`); + if (operator === "starts_with") return eb(f5, "like", `${value}%`); + if (operator === "ends_with") return eb(f5, "like", `%${value}`); + if (operator === "eq") return eb(f5, "=", value); + if (operator === "ne") return eb(f5, "<>", value); + if (operator === "gt") return eb(f5, ">", value); + if (operator === "gte") return eb(f5, ">=", value); + if (operator === "lt") return eb(f5, "<", value); + if (operator === "lte") return eb(f5, "<=", value); + return eb(f5, operator, value); + }; + if (connector === "OR") conditions.or.push(expr); + else conditions.and.push(expr); + }); + return { + and: conditions.and.length ? conditions.and : null, + or: conditions.or.length ? conditions.or : null + }; + } + function processJoinedResults(rows, joinConfig, allSelectsStr) { + if (!joinConfig || !rows.length) return rows; + const groupedByMainId = /* @__PURE__ */ new Map(); + for (const currentRow of rows) { + const mainModelFields = {}; + const joinedModelFields = {}; + for (const [joinModel] of Object.entries(joinConfig)) joinedModelFields[getModelName(joinModel)] = {}; + for (const [key, value] of Object.entries(currentRow)) { + const keyStr = String(key); + let assigned = false; + for (const { joinModel, fieldName, joinModelRef } of allSelectsStr) if (keyStr === `_joined_${joinModelRef}_${fieldName}`) { + joinedModelFields[getModelName(joinModel)][getFieldName({ + model: joinModel, + field: fieldName + })] = value; + assigned = true; + break; + } + if (!assigned) mainModelFields[key] = value; + } + const mainId = mainModelFields.id; + if (!mainId) continue; + if (!groupedByMainId.has(mainId)) { + const entry$1 = { ...mainModelFields }; + for (const [joinModel, joinAttr] of Object.entries(joinConfig)) entry$1[getModelName(joinModel)] = joinAttr.relation === "one-to-one" ? null : []; + groupedByMainId.set(mainId, entry$1); + } + const entry = groupedByMainId.get(mainId); + for (const [joinModel, joinAttr] of Object.entries(joinConfig)) { + const isUnique = joinAttr.relation === "one-to-one"; + const limit = joinAttr.limit ?? 100; + const joinedObj = joinedModelFields[getModelName(joinModel)]; + const hasData = joinedObj && Object.keys(joinedObj).length > 0 && Object.values(joinedObj).some((value) => value !== null && value !== void 0); + if (isUnique) entry[getModelName(joinModel)] = hasData ? joinedObj : null; + else { + const joinModelName = getModelName(joinModel); + if (Array.isArray(entry[joinModelName]) && hasData) { + if (entry[joinModelName].length >= limit) continue; + const idFieldName = getFieldName({ + model: joinModel, + field: "id" + }); + const joinedId = joinedObj[idFieldName]; + if (joinedId) { + if (!entry[joinModelName].some((item) => item[idFieldName] === joinedId) && entry[joinModelName].length < limit) entry[joinModelName].push(joinedObj); + } else if (entry[joinModelName].length < limit) entry[joinModelName].push(joinedObj); + } + } + } + } + const result = Array.from(groupedByMainId.values()); + for (const entry of result) for (const [joinModel, joinAttr] of Object.entries(joinConfig)) if (joinAttr.relation !== "one-to-one") { + const joinModelName = getModelName(joinModel); + if (Array.isArray(entry[joinModelName])) { + const limit = joinAttr.limit ?? 100; + if (entry[joinModelName].length > limit) entry[joinModelName] = entry[joinModelName].slice(0, limit); + } + } + return result; + } + return { + async create({ data: data2, model }) { + return await withReturning(data2, db$1.insertInto(model).values(data2), model, []); + }, + async findOne({ model, where, select: select2, join: join4 }) { + const { and: and2, or: or3 } = convertWhereClause(model, where); + let query = db$1.selectFrom((eb) => { + let b6 = eb.selectFrom(model); + if (and2) b6 = b6.where((eb$1) => eb$1.and(and2.map((expr) => expr(eb$1)))); + if (or3) b6 = b6.where((eb$1) => eb$1.or(or3.map((expr) => expr(eb$1)))); + return b6.selectAll().as("primary"); + }).selectAll("primary"); + if (join4) for (const [joinModel, joinAttr] of Object.entries(join4)) { + const [_joinModelSchema, joinModelName] = joinModel.includes(".") ? joinModel.split(".") : [void 0, joinModel]; + query = query.leftJoin(`${joinModel} as join_${joinModelName}`, (join$1) => join$1.onRef(`join_${joinModelName}.${joinAttr.on.to}`, "=", `primary.${joinAttr.on.from}`)); + } + const { allSelectsStr, allSelects } = selectAllJoins(join4); + query = query.select(allSelects); + const res = await query.execute(); + if (!res || !Array.isArray(res) || res.length === 0) return null; + const row = res[0]; + if (join4) return processJoinedResults(res, join4, allSelectsStr)[0]; + return row; + }, + async findMany({ model, where, limit, offset, sortBy, join: join4 }) { + const { and: and2, or: or3 } = convertWhereClause(model, where); + let query = db$1.selectFrom((eb) => { + let b6 = eb.selectFrom(model); + if (config3?.type === "mssql") { + if (offset !== void 0) { + if (!sortBy) b6 = b6.orderBy(getFieldName({ + model, + field: "id" + })); + b6 = b6.offset(offset).fetch(limit || 100); + } else if (limit !== void 0) b6 = b6.top(limit); + } else { + if (limit !== void 0) b6 = b6.limit(limit); + if (offset !== void 0) b6 = b6.offset(offset); + } + if (sortBy?.field) b6 = b6.orderBy(`${getFieldName({ + model, + field: sortBy.field + })}`, sortBy.direction); + if (and2) b6 = b6.where((eb$1) => eb$1.and(and2.map((expr) => expr(eb$1)))); + if (or3) b6 = b6.where((eb$1) => eb$1.or(or3.map((expr) => expr(eb$1)))); + return b6.selectAll().as("primary"); + }).selectAll("primary"); + if (join4) for (const [joinModel, joinAttr] of Object.entries(join4)) { + const [_joinModelSchema, joinModelName] = joinModel.includes(".") ? joinModel.split(".") : [void 0, joinModel]; + query = query.leftJoin(`${joinModel} as join_${joinModelName}`, (join$1) => join$1.onRef(`join_${joinModelName}.${joinAttr.on.to}`, "=", `primary.${joinAttr.on.from}`)); + } + const { allSelectsStr, allSelects } = selectAllJoins(join4); + query = query.select(allSelects); + if (sortBy?.field) query = query.orderBy(`${getFieldName({ + model, + field: sortBy.field + })}`, sortBy.direction); + const res = await query.execute(); + if (!res) return []; + if (join4) return processJoinedResults(res, join4, allSelectsStr); + return res; + }, + async update({ model, where, update: values2 }) { + const { and: and2, or: or3 } = convertWhereClause(model, where); + let query = db$1.updateTable(model).set(values2); + if (and2) query = query.where((eb) => eb.and(and2.map((expr) => expr(eb)))); + if (or3) query = query.where((eb) => eb.or(or3.map((expr) => expr(eb)))); + return await withReturning(values2, query, model, where); + }, + async updateMany({ model, where, update: values2 }) { + const { and: and2, or: or3 } = convertWhereClause(model, where); + let query = db$1.updateTable(model).set(values2); + if (and2) query = query.where((eb) => eb.and(and2.map((expr) => expr(eb)))); + if (or3) query = query.where((eb) => eb.or(or3.map((expr) => expr(eb)))); + const res = (await query.executeTakeFirst()).numUpdatedRows; + return res > Number.MAX_SAFE_INTEGER ? Number.MAX_SAFE_INTEGER : Number(res); + }, + async count({ model, where }) { + const { and: and2, or: or3 } = convertWhereClause(model, where); + let query = db$1.selectFrom(model).select(db$1.fn.count("id").as("count")); + if (and2) query = query.where((eb) => eb.and(and2.map((expr) => expr(eb)))); + if (or3) query = query.where((eb) => eb.or(or3.map((expr) => expr(eb)))); + const res = await query.execute(); + if (typeof res[0].count === "number") return res[0].count; + if (typeof res[0].count === "bigint") return Number(res[0].count); + return parseInt(res[0].count); + }, + async delete({ model, where }) { + const { and: and2, or: or3 } = convertWhereClause(model, where); + let query = db$1.deleteFrom(model); + if (and2) query = query.where((eb) => eb.and(and2.map((expr) => expr(eb)))); + if (or3) query = query.where((eb) => eb.or(or3.map((expr) => expr(eb)))); + await query.execute(); + }, + async deleteMany({ model, where }) { + const { and: and2, or: or3 } = convertWhereClause(model, where); + let query = db$1.deleteFrom(model); + if (and2) query = query.where((eb) => eb.and(and2.map((expr) => expr(eb)))); + if (or3) query = query.where((eb) => eb.or(or3.map((expr) => expr(eb)))); + const res = (await query.executeTakeFirst()).numDeletedRows; + return res > Number.MAX_SAFE_INTEGER ? Number.MAX_SAFE_INTEGER : Number(res); + }, + options: config3 + }; + }; + }; + let adapterOptions = null; + adapterOptions = { + config: { + adapterId: "kysely", + adapterName: "Kysely Adapter", + usePlural: config3?.usePlural, + debugLogs: config3?.debugLogs, + supportsBooleans: config3?.type === "sqlite" || config3?.type === "mssql" || config3?.type === "mysql" || !config3?.type ? false : true, + supportsDates: config3?.type === "sqlite" || config3?.type === "mssql" || !config3?.type ? false : true, + supportsJSON: config3?.type === "postgres" ? true : false, + supportsArrays: false, + supportsUUIDs: config3?.type === "postgres" ? true : false, + transaction: config3?.transaction ? (cb) => db.transaction().execute((trx) => { + return cb(createAdapterFactory({ + config: adapterOptions.config, + adapter: createCustomAdapter(trx) + })(lazyOptions)); + }) : false + }, + adapter: createCustomAdapter(db) + }; + const adapter = createAdapterFactory(adapterOptions); + return (options) => { + lazyOptions = options; + return adapter(options); + }; + }; + } +}); + +// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/adapters/kysely-adapter/index.mjs +var kysely_adapter_exports = {}; +__export(kysely_adapter_exports, { + createKyselyAdapter: () => createKyselyAdapter, + getKyselyDatabaseType: () => getKyselyDatabaseType, + kyselyAdapter: () => kyselyAdapter +}); +var init_kysely_adapter2 = __esm({ + "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/adapters/kysely-adapter/index.mjs"() { + init_dialect3(); + init_kysely_adapter(); + } +}); + +// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/db/adapter-kysely.mjs +async function getAdapter(options) { + return getBaseAdapter(options, async (opts) => { + const { createKyselyAdapter: createKyselyAdapter2 } = await Promise.resolve().then(() => (init_kysely_adapter2(), kysely_adapter_exports)); + const { kysely, databaseType, transaction } = await createKyselyAdapter2(opts); + if (!kysely) throw new BetterAuthError("Failed to initialize database adapter"); + const { kyselyAdapter: kyselyAdapter2 } = await Promise.resolve().then(() => (init_kysely_adapter2(), kysely_adapter_exports)); + return kyselyAdapter2(kysely, { + type: databaseType || "sqlite", + debugLogs: opts.database && "debugLogs" in opts.database ? opts.database.debugLogs : false, + transaction + })(opts); + }); +} +var init_adapter_kysely = __esm({ + "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/db/adapter-kysely.mjs"() { + init_adapter_base(); + init_error(); + } +}); + +// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/db/field.mjs +var createFieldAttribute; +var init_field = __esm({ + "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/db/field.mjs"() { + createFieldAttribute = (type, config3) => { + return { + type, + ...config3 + }; + }; + } +}); + +// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/db/field-converter.mjs +function convertToDB(fields, values2) { + const result = values2.id ? { id: values2.id } : {}; + for (const key in fields) { + const field = fields[key]; + const value = values2[key]; + if (value === void 0) continue; + result[field.fieldName || key] = value; + } + return result; +} +function convertFromDB(fields, values2) { + if (!values2) return null; + const result = { id: values2.id }; + for (const [key, value] of Object.entries(fields)) result[key] = values2[value.fieldName || key]; + return result; +} +var init_field_converter = __esm({ + "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/db/field-converter.mjs"() { + } +}); + +// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/db/with-hooks.mjs +function getWithHooks(adapter, ctx) { + const hooks = ctx.hooks; + async function createWithHooks(data2, model, customCreateFn) { + const context = await getCurrentAuthContext().catch(() => null); + let actualData = data2; + for (const hook of hooks || []) { + const toRun = hook[model]?.create?.before; + if (toRun) { + const result = await toRun(actualData, context); + if (result === false) return null; + if (typeof result === "object" && "data" in result) actualData = { + ...actualData, + ...result.data + }; + } + } + const customCreated = customCreateFn ? await customCreateFn.fn(actualData) : null; + const created = !customCreateFn || customCreateFn.executeMainFn ? await (await getCurrentAdapter(adapter)).create({ + model, + data: actualData, + forceAllowId: true + }) : customCreated; + for (const hook of hooks || []) { + const toRun = hook[model]?.create?.after; + if (toRun) await toRun(created, context); + } + return created; + } + async function updateWithHooks(data2, where, model, customUpdateFn) { + const context = await getCurrentAuthContext().catch(() => null); + let actualData = data2; + for (const hook of hooks || []) { + const toRun = hook[model]?.update?.before; + if (toRun) { + const result = await toRun(data2, context); + if (result === false) return null; + if (typeof result === "object" && "data" in result) actualData = { + ...actualData, + ...result.data + }; + } + } + const customUpdated = customUpdateFn ? await customUpdateFn.fn(actualData) : null; + const updated = !customUpdateFn || customUpdateFn.executeMainFn ? await (await getCurrentAdapter(adapter)).update({ + model, + update: actualData, + where + }) : customUpdated; + for (const hook of hooks || []) { + const toRun = hook[model]?.update?.after; + if (toRun) await toRun(updated, context); + } + return updated; + } + async function updateManyWithHooks(data2, where, model, customUpdateFn) { + const context = await getCurrentAuthContext().catch(() => null); + let actualData = data2; + for (const hook of hooks || []) { + const toRun = hook[model]?.update?.before; + if (toRun) { + const result = await toRun(data2, context); + if (result === false) return null; + if (typeof result === "object" && "data" in result) actualData = { + ...actualData, + ...result.data + }; + } + } + const customUpdated = customUpdateFn ? await customUpdateFn.fn(actualData) : null; + const updated = !customUpdateFn || customUpdateFn.executeMainFn ? await (await getCurrentAdapter(adapter)).updateMany({ + model, + update: actualData, + where + }) : customUpdated; + for (const hook of hooks || []) { + const toRun = hook[model]?.update?.after; + if (toRun) await toRun(updated, context); + } + return updated; + } + async function deleteWithHooks(where, model, customDeleteFn) { + const context = await getCurrentAuthContext().catch(() => null); + let entityToDelete = null; + try { + entityToDelete = (await (await getCurrentAdapter(adapter)).findMany({ + model, + where, + limit: 1 + }))[0] || null; + } catch { + } + if (entityToDelete) for (const hook of hooks || []) { + const toRun = hook[model]?.delete?.before; + if (toRun) { + if (await toRun(entityToDelete, context) === false) return null; + } + } + const customDeleted = customDeleteFn ? await customDeleteFn.fn(where) : null; + const deleted = !customDeleteFn || customDeleteFn.executeMainFn ? await (await getCurrentAdapter(adapter)).delete({ + model, + where + }) : customDeleted; + if (entityToDelete) for (const hook of hooks || []) { + const toRun = hook[model]?.delete?.after; + if (toRun) await toRun(entityToDelete, context); + } + return deleted; + } + async function deleteManyWithHooks(where, model, customDeleteFn) { + const context = await getCurrentAuthContext().catch(() => null); + let entitiesToDelete = []; + try { + entitiesToDelete = await (await getCurrentAdapter(adapter)).findMany({ + model, + where + }); + } catch { + } + for (const entity of entitiesToDelete) for (const hook of hooks || []) { + const toRun = hook[model]?.delete?.before; + if (toRun) { + if (await toRun(entity, context) === false) return null; + } + } + const customDeleted = customDeleteFn ? await customDeleteFn.fn(where) : null; + const deleted = !customDeleteFn || customDeleteFn.executeMainFn ? await (await getCurrentAdapter(adapter)).deleteMany({ + model, + where + }) : customDeleted; + for (const entity of entitiesToDelete) for (const hook of hooks || []) { + const toRun = hook[model]?.delete?.after; + if (toRun) await toRun(entity, context); + } + return deleted; + } + return { + createWithHooks, + updateWithHooks, + updateManyWithHooks, + deleteWithHooks, + deleteManyWithHooks + }; +} +var init_with_hooks = __esm({ + "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/db/with-hooks.mjs"() { + init_context2(); + } +}); + +// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/db/internal-adapter.mjs +var createInternalAdapter; +var init_internal_adapter = __esm({ + "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/db/internal-adapter.mjs"() { + init_date2(); + init_get_request_ip(); + init_schema4(); + init_with_hooks(); + init_context2(); + init_utils7(); + createInternalAdapter = (adapter, ctx) => { + const logger4 = ctx.logger; + const options = ctx.options; + const secondaryStorage = options.secondaryStorage; + const sessionExpiration = options.session?.expiresIn || 3600 * 24 * 7; + const { createWithHooks, updateWithHooks, updateManyWithHooks, deleteWithHooks, deleteManyWithHooks } = getWithHooks(adapter, ctx); + async function refreshUserSessions(user) { + if (!secondaryStorage) return; + const listRaw = await secondaryStorage.get(`active-sessions-${user.id}`); + if (!listRaw) return; + const now2 = Date.now(); + const validSessions = (safeJSONParse(listRaw) || []).filter((s5) => s5.expiresAt > now2); + await Promise.all(validSessions.map(async ({ token }) => { + const cached4 = await secondaryStorage.get(token); + if (!cached4) return; + const parsed = safeJSONParse(cached4); + if (!parsed) return; + const sessionTTL = Math.max(Math.floor(new Date(parsed.session.expiresAt).getTime() - now2) / 1e3, 0); + await secondaryStorage.set(token, JSON.stringify({ + session: parsed.session, + user + }), Math.floor(sessionTTL)); + })); + } + return { + createOAuthUser: async (user, account) => { + return runWithTransaction(adapter, async () => { + const createdUser = await createWithHooks({ + createdAt: /* @__PURE__ */ new Date(), + updatedAt: /* @__PURE__ */ new Date(), + ...user + }, "user", void 0); + return { + user: createdUser, + account: await createWithHooks({ + ...account, + userId: createdUser.id, + createdAt: /* @__PURE__ */ new Date(), + updatedAt: /* @__PURE__ */ new Date() + }, "account", void 0) + }; + }); + }, + createUser: async (user) => { + return await createWithHooks({ + createdAt: /* @__PURE__ */ new Date(), + updatedAt: /* @__PURE__ */ new Date(), + ...user, + email: user.email?.toLowerCase() + }, "user", void 0); + }, + createAccount: async (account) => { + return await createWithHooks({ + createdAt: /* @__PURE__ */ new Date(), + updatedAt: /* @__PURE__ */ new Date(), + ...account + }, "account", void 0); + }, + listSessions: async (userId) => { + if (secondaryStorage) { + const currentList = await secondaryStorage.get(`active-sessions-${userId}`); + if (!currentList) return []; + const list2 = safeJSONParse(currentList) || []; + const now2 = Date.now(); + const seenTokens = /* @__PURE__ */ new Set(); + const sessions = []; + for (const { token, expiresAt } of list2) { + if (expiresAt <= now2 || seenTokens.has(token)) continue; + seenTokens.add(token); + const data2 = await secondaryStorage.get(token); + if (!data2) continue; + try { + const parsed = typeof data2 === "string" ? JSON.parse(data2) : data2; + if (!parsed?.session) continue; + sessions.push(parseSessionOutput(ctx.options, { + ...parsed.session, + expiresAt: new Date(parsed.session.expiresAt) + })); + } catch { + continue; + } + } + return sessions; + } + return await (await getCurrentAdapter(adapter)).findMany({ + model: "session", + where: [{ + field: "userId", + value: userId + }] + }); + }, + listUsers: async (limit, offset, sortBy, where) => { + return await (await getCurrentAdapter(adapter)).findMany({ + model: "user", + limit, + offset, + sortBy, + where + }); + }, + countTotalUsers: async (where) => { + const total = await (await getCurrentAdapter(adapter)).count({ + model: "user", + where + }); + if (typeof total === "string") return parseInt(total); + return total; + }, + deleteUser: async (userId) => { + if (!secondaryStorage || options.session?.storeSessionInDatabase) await deleteManyWithHooks([{ + field: "userId", + value: userId + }], "session", void 0); + await deleteManyWithHooks([{ + field: "userId", + value: userId + }], "account", void 0); + await deleteWithHooks([{ + field: "id", + value: userId + }], "user", void 0); + }, + createSession: async (userId, dontRememberMe, override, overrideAll) => { + const ctx$1 = await getCurrentAuthContext().catch(() => null); + const headers = ctx$1?.headers || ctx$1?.request?.headers; + const { id: _, ...rest } = override || {}; + const defaultAdditionalFields = parseSessionInput(ctx$1?.context.options ?? options, {}); + const data2 = { + ipAddress: ctx$1?.request || ctx$1?.headers ? getIp(ctx$1?.request || ctx$1?.headers, ctx$1?.context.options) || "" : "", + userAgent: headers?.get("user-agent") || "", + ...rest, + expiresAt: dontRememberMe ? getDate(3600 * 24, "sec") : getDate(sessionExpiration, "sec"), + userId, + token: generateId(32), + createdAt: /* @__PURE__ */ new Date(), + updatedAt: /* @__PURE__ */ new Date(), + ...defaultAdditionalFields, + ...overrideAll ? rest : {} + }; + return await createWithHooks(data2, "session", secondaryStorage ? { + fn: async (sessionData) => { + const currentList = await secondaryStorage.get(`active-sessions-${userId}`); + let list2 = []; + const now2 = Date.now(); + if (currentList) { + list2 = safeJSONParse(currentList) || []; + list2 = list2.filter((session) => session.expiresAt > now2 && session.token !== data2.token); + } + const sorted = [...list2, { + token: data2.token, + expiresAt: data2.expiresAt.getTime() + }].sort((a5, b6) => a5.expiresAt - b6.expiresAt); + const furthestSessionExp = sorted.at(-1)?.expiresAt ?? data2.expiresAt.getTime(); + const furthestSessionTTL = Math.max(Math.floor((furthestSessionExp - now2) / 1e3), 0); + if (furthestSessionTTL > 0) await secondaryStorage.set(`active-sessions-${userId}`, JSON.stringify(sorted), furthestSessionTTL); + const user = await adapter.findOne({ + model: "user", + where: [{ + field: "id", + value: userId + }] + }); + const sessionTTL = Math.max(Math.floor((data2.expiresAt.getTime() - now2) / 1e3), 0); + if (sessionTTL > 0) await secondaryStorage.set(data2.token, JSON.stringify({ + session: sessionData, + user + }), sessionTTL); + return sessionData; + }, + executeMainFn: options.session?.storeSessionInDatabase + } : void 0); + }, + findSession: async (token) => { + if (secondaryStorage) { + const sessionStringified = await secondaryStorage.get(token); + if (!sessionStringified && !options.session?.storeSessionInDatabase) return null; + if (sessionStringified) { + const s5 = safeJSONParse(sessionStringified); + if (!s5) return null; + return { + session: parseSessionOutput(ctx.options, { + ...s5.session, + expiresAt: new Date(s5.session.expiresAt), + createdAt: new Date(s5.session.createdAt), + updatedAt: new Date(s5.session.updatedAt) + }), + user: parseUserOutput(ctx.options, { + ...s5.user, + createdAt: new Date(s5.user.createdAt), + updatedAt: new Date(s5.user.updatedAt) + }) + }; + } + } + const result = await (await getCurrentAdapter(adapter)).findOne({ + model: "session", + where: [{ + value: token, + field: "token" + }], + join: { user: true } + }); + if (!result) return null; + const { user, ...session } = result; + if (!user) return null; + return { + session: parseSessionOutput(ctx.options, session), + user: parseUserOutput(ctx.options, user) + }; + }, + findSessions: async (sessionTokens) => { + if (secondaryStorage) { + const sessions$1 = []; + for (const sessionToken of sessionTokens) { + const sessionStringified = await secondaryStorage.get(sessionToken); + if (sessionStringified) try { + const s5 = typeof sessionStringified === "string" ? JSON.parse(sessionStringified) : sessionStringified; + if (!s5?.session) continue; + const session = { + session: { + ...s5.session, + expiresAt: new Date(s5.session.expiresAt) + }, + user: { + ...s5.user, + createdAt: new Date(s5.user.createdAt), + updatedAt: new Date(s5.user.updatedAt) + } + }; + sessions$1.push(session); + } catch { + continue; + } + } + return sessions$1; + } + const sessions = await (await getCurrentAdapter(adapter)).findMany({ + model: "session", + where: [{ + field: "token", + value: sessionTokens, + operator: "in" + }], + join: { user: true } + }); + if (!sessions.length) return []; + if (sessions.some((session) => !session.user)) return []; + return sessions.map((_session) => { + const { user, ...session } = _session; + return { + session, + user + }; + }); + }, + updateSession: async (sessionToken, session) => { + return await updateWithHooks(session, [{ + field: "token", + value: sessionToken + }], "session", secondaryStorage ? { + async fn(data2) { + const currentSession = await secondaryStorage.get(sessionToken); + if (!currentSession) return null; + const parsedSession = safeJSONParse(currentSession); + if (!parsedSession) return null; + const mergedSession = { + ...parsedSession.session, + ...data2, + expiresAt: new Date(data2.expiresAt ?? parsedSession.session.expiresAt), + createdAt: new Date(parsedSession.session.createdAt), + updatedAt: new Date(data2.updatedAt ?? parsedSession.session.updatedAt) + }; + const updatedSession = parseSessionOutput(ctx.options, mergedSession); + const now2 = Date.now(); + const expiresMs = new Date(updatedSession.expiresAt).getTime(); + const sessionTTL = Math.max(Math.floor((expiresMs - now2) / 1e3), 0); + if (sessionTTL > 0) { + await secondaryStorage.set(sessionToken, JSON.stringify({ + session: updatedSession, + user: parsedSession.user + }), sessionTTL); + const listKey = `active-sessions-${updatedSession.userId}`; + const listRaw = await secondaryStorage.get(listKey); + const sorted = (listRaw ? safeJSONParse(listRaw) || [] : []).filter((s5) => s5.token !== sessionToken && s5.expiresAt > now2).concat([{ + token: sessionToken, + expiresAt: expiresMs + }]).sort((a5, b6) => a5.expiresAt - b6.expiresAt); + const furthestSessionExp = sorted.at(-1)?.expiresAt; + if (furthestSessionExp && furthestSessionExp > now2) await secondaryStorage.set(listKey, JSON.stringify(sorted), Math.floor((furthestSessionExp - now2) / 1e3)); + else await secondaryStorage.delete(listKey); + } + return updatedSession; + }, + executeMainFn: options.session?.storeSessionInDatabase + } : void 0); + }, + deleteSession: async (token) => { + if (secondaryStorage) { + const data2 = await secondaryStorage.get(token); + if (data2) { + const { session } = safeJSONParse(data2) ?? {}; + if (!session) { + logger4.error("Session not found in secondary storage"); + return; + } + const userId = session.userId; + const currentList = await secondaryStorage.get(`active-sessions-${userId}`); + if (currentList) { + const list2 = safeJSONParse(currentList) || []; + const now2 = Date.now(); + const filtered = list2.filter((session$1) => session$1.expiresAt > now2 && session$1.token !== token); + const furthestSessionExp = filtered.sort((a5, b6) => a5.expiresAt - b6.expiresAt).at(-1)?.expiresAt; + if (filtered.length > 0 && furthestSessionExp && furthestSessionExp > Date.now()) await secondaryStorage.set(`active-sessions-${userId}`, JSON.stringify(filtered), Math.floor((furthestSessionExp - now2) / 1e3)); + else await secondaryStorage.delete(`active-sessions-${userId}`); + } else logger4.error("Active sessions list not found in secondary storage"); + } + await secondaryStorage.delete(token); + if (!options.session?.storeSessionInDatabase || ctx.options.session?.preserveSessionInDatabase) return; + } + await deleteWithHooks([{ + field: "token", + value: token + }], "session", void 0); + }, + deleteAccounts: async (userId) => { + await deleteManyWithHooks([{ + field: "userId", + value: userId + }], "account", void 0); + }, + deleteAccount: async (accountId) => { + await deleteWithHooks([{ + field: "id", + value: accountId + }], "account", void 0); + }, + deleteSessions: async (userIdOrSessionTokens) => { + if (secondaryStorage) { + if (typeof userIdOrSessionTokens === "string") { + const activeSession = await secondaryStorage.get(`active-sessions-${userIdOrSessionTokens}`); + const sessions = activeSession ? safeJSONParse(activeSession) : []; + if (!sessions) return; + for (const session of sessions) await secondaryStorage.delete(session.token); + await secondaryStorage.delete(`active-sessions-${userIdOrSessionTokens}`); + } else for (const sessionToken of userIdOrSessionTokens) if (await secondaryStorage.get(sessionToken)) await secondaryStorage.delete(sessionToken); + if (!options.session?.storeSessionInDatabase || ctx.options.session?.preserveSessionInDatabase) return; + } + await deleteManyWithHooks([{ + field: Array.isArray(userIdOrSessionTokens) ? "token" : "userId", + value: userIdOrSessionTokens, + operator: Array.isArray(userIdOrSessionTokens) ? "in" : void 0 + }], "session", void 0); + }, + findOAuthUser: async (email3, accountId, providerId) => { + const account = await (await getCurrentAdapter(adapter)).findOne({ + model: "account", + where: [{ + value: accountId, + field: "accountId" + }, { + value: providerId, + field: "providerId" + }], + join: { user: true } + }); + if (account) if (account.user) return { + user: account.user, + linkedAccount: account, + accounts: [account] + }; + else { + const user = await (await getCurrentAdapter(adapter)).findOne({ + model: "user", + where: [{ + value: email3.toLowerCase(), + field: "email" + }] + }); + if (user) return { + user, + linkedAccount: account, + accounts: [account] + }; + return null; + } + else { + const user = await (await getCurrentAdapter(adapter)).findOne({ + model: "user", + where: [{ + value: email3.toLowerCase(), + field: "email" + }] + }); + if (user) return { + user, + linkedAccount: null, + accounts: await (await getCurrentAdapter(adapter)).findMany({ + model: "account", + where: [{ + value: user.id, + field: "userId" + }] + }) || [] + }; + else return null; + } + }, + findUserByEmail: async (email3, options$1) => { + const result = await (await getCurrentAdapter(adapter)).findOne({ + model: "user", + where: [{ + value: email3.toLowerCase(), + field: "email" + }], + join: { ...options$1?.includeAccounts ? { account: true } : {} } + }); + if (!result) return null; + const { account: accounts, ...user } = result; + return { + user, + accounts: accounts ?? [] + }; + }, + findUserById: async (userId) => { + if (!userId) return null; + return await (await getCurrentAdapter(adapter)).findOne({ + model: "user", + where: [{ + field: "id", + value: userId + }] + }); + }, + linkAccount: async (account) => { + return await createWithHooks({ + createdAt: /* @__PURE__ */ new Date(), + updatedAt: /* @__PURE__ */ new Date(), + ...account + }, "account", void 0); + }, + updateUser: async (userId, data2) => { + const user = await updateWithHooks(data2, [{ + field: "id", + value: userId + }], "user", void 0); + await refreshUserSessions(user); + return user; + }, + updateUserByEmail: async (email3, data2) => { + const user = await updateWithHooks(data2, [{ + field: "email", + value: email3.toLowerCase() + }], "user", void 0); + await refreshUserSessions(user); + return user; + }, + updatePassword: async (userId, password) => { + await updateManyWithHooks({ password }, [{ + field: "userId", + value: userId + }, { + field: "providerId", + value: "credential" + }], "account", void 0); + }, + findAccounts: async (userId) => { + return await (await getCurrentAdapter(adapter)).findMany({ + model: "account", + where: [{ + field: "userId", + value: userId + }] + }); + }, + findAccount: async (accountId) => { + return await (await getCurrentAdapter(adapter)).findOne({ + model: "account", + where: [{ + field: "accountId", + value: accountId + }] + }); + }, + findAccountByProviderId: async (accountId, providerId) => { + return await (await getCurrentAdapter(adapter)).findOne({ + model: "account", + where: [{ + field: "accountId", + value: accountId + }, { + field: "providerId", + value: providerId + }] + }); + }, + findAccountByUserId: async (userId) => { + return await (await getCurrentAdapter(adapter)).findMany({ + model: "account", + where: [{ + field: "userId", + value: userId + }] + }); + }, + updateAccount: async (id, data2) => { + return await updateWithHooks(data2, [{ + field: "id", + value: id + }], "account", void 0); + }, + createVerificationValue: async (data2) => { + return await createWithHooks({ + createdAt: /* @__PURE__ */ new Date(), + updatedAt: /* @__PURE__ */ new Date(), + ...data2 + }, "verification", void 0); + }, + findVerificationValue: async (identifier) => { + const verification = await (await getCurrentAdapter(adapter)).findMany({ + model: "verification", + where: [{ + field: "identifier", + value: identifier + }], + sortBy: { + field: "createdAt", + direction: "desc" + }, + limit: 1 + }); + if (!options.verification?.disableCleanup) await deleteManyWithHooks([{ + field: "expiresAt", + value: /* @__PURE__ */ new Date(), + operator: "lt" + }], "verification", void 0); + return verification[0]; + }, + deleteVerificationValue: async (id) => { + await deleteWithHooks([{ + field: "id", + value: id + }], "verification", void 0); + }, + deleteVerificationByIdentifier: async (identifier) => { + await deleteWithHooks([{ + field: "identifier", + value: identifier + }], "verification", void 0); + }, + updateVerificationValue: async (id, data2) => { + return await updateWithHooks(data2, [{ + field: "id", + value: id + }], "verification", void 0); + } + }; + }; + } +}); + +// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/db/to-zod.mjs +function toZodSchema({ fields, isClientSide }) { + const zodFields = Object.keys(fields).reduce((acc, key) => { + const field = fields[key]; + if (!field) return acc; + if (isClientSide && field.input === false) return acc; + let schema2; + if (field.type === "json") schema2 = json2 ? json2() : any(); + else if (field.type === "string[]" || field.type === "number[]") schema2 = array(field.type === "string[]" ? string2() : number2()); + else if (Array.isArray(field.type)) schema2 = any(); + else schema2 = zod_exports[field.type](); + if (field?.required === false) schema2 = schema2.optional(); + if (!isClientSide && field?.returned === false) return acc; + return { + ...acc, + [key]: schema2 + }; + }, {}); + return object(zodFields); +} +var init_to_zod = __esm({ + "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/db/to-zod.mjs"() { + init_zod(); + } +}); + +// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/db/get-schema.mjs +function getSchema(config3) { + const tables = (0, db_exports2.getAuthTables)(config3); + const schema2 = {}; + for (const key in tables) { + const table = tables[key]; + const fields = table.fields; + const actualFields = {}; + Object.entries(fields).forEach(([key$1, field]) => { + actualFields[field.fieldName || key$1] = field; + if (field.references) { + const refTable = tables[field.references.model]; + if (refTable) actualFields[field.fieldName || key$1].references = { + ...field.references, + model: refTable.modelName, + field: field.references.field + }; + } + }); + if (schema2[table.modelName]) { + schema2[table.modelName].fields = { + ...schema2[table.modelName].fields, + ...actualFields + }; + continue; + } + schema2[table.modelName] = { + fields: actualFields, + order: table.order || Infinity + }; + } + return schema2; +} +var init_get_schema = __esm({ + "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/db/get-schema.mjs"() { + init_db4(); + } +}); + +// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/db/get-migration.mjs +function matchType(columnDataType, fieldType, dbType) { + function normalize2(type) { + return type.toLowerCase().split("(")[0].trim(); + } + if (fieldType === "string[]" || fieldType === "number[]") return columnDataType.toLowerCase().includes("json"); + const types2 = map3[dbType]; + return (Array.isArray(fieldType) ? types2["string"].map((t5) => t5.toLowerCase()) : types2[fieldType].map((t5) => t5.toLowerCase())).includes(normalize2(columnDataType)); +} +async function getPostgresSchema(db) { + try { + const result = await sql2`SHOW search_path`.execute(db); + if (result.rows[0]?.search_path) return result.rows[0].search_path.split(",").map((s5) => s5.trim()).map((s5) => s5.replace(/^["']|["']$/g, "")).filter((s5) => !s5.startsWith("$"))[0] || "public"; + } catch { + } + return "public"; +} +async function getMigrations(config3) { + const betterAuthSchema = getSchema(config3); + const logger$1 = createLogger(config3.logger); + let { kysely: db, databaseType: dbType } = await createKyselyAdapter(config3); + if (!dbType) { + logger$1.warn("Could not determine database type, defaulting to sqlite. Please provide a type in the database options to avoid this."); + dbType = "sqlite"; + } + if (!db) { + logger$1.error("Only kysely adapter is supported for migrations. You can use `generate` command to generate the schema, if you're using a different adapter."); + process.exit(1); + } + let currentSchema = "public"; + if (dbType === "postgres") { + currentSchema = await getPostgresSchema(db); + logger$1.debug(`PostgreSQL migration: Using schema '${currentSchema}' (from search_path)`); + try { + if (!(await sql2` + SELECT schema_name + FROM information_schema.schemata + WHERE schema_name = ${currentSchema} + `.execute(db)).rows[0]) logger$1.warn(`Schema '${currentSchema}' does not exist. Tables will be inspected from available schemas. Consider creating the schema first or checking your database configuration.`); + } catch (error50) { + logger$1.debug(`Could not verify schema existence: ${error50 instanceof Error ? error50.message : String(error50)}`); + } + } + const allTableMetadata = await db.introspection.getTables(); + let tableMetadata = allTableMetadata; + if (dbType === "postgres") try { + const tablesInSchema = await sql2` + SELECT table_name + FROM information_schema.tables + WHERE table_schema = ${currentSchema} + AND table_type = 'BASE TABLE' + `.execute(db); + const tableNamesInSchema = new Set(tablesInSchema.rows.map((row) => row.table_name)); + tableMetadata = allTableMetadata.filter((table) => table.schema === currentSchema && tableNamesInSchema.has(table.name)); + logger$1.debug(`Found ${tableMetadata.length} table(s) in schema '${currentSchema}': ${tableMetadata.map((t5) => t5.name).join(", ") || "(none)"}`); + } catch (error50) { + logger$1.warn(`Could not filter tables by schema. Using all discovered tables. Error: ${error50 instanceof Error ? error50.message : String(error50)}`); + } + const toBeCreated = []; + const toBeAdded = []; + for (const [key, value] of Object.entries(betterAuthSchema)) { + const table = tableMetadata.find((t5) => t5.name === key); + if (!table) { + const tIndex = toBeCreated.findIndex((t5) => t5.table === key); + const tableData = { + table: key, + fields: value.fields, + order: value.order || Infinity + }; + const insertIndex = toBeCreated.findIndex((t5) => (t5.order || Infinity) > tableData.order); + if (insertIndex === -1) if (tIndex === -1) toBeCreated.push(tableData); + else toBeCreated[tIndex].fields = { + ...toBeCreated[tIndex].fields, + ...value.fields + }; + else toBeCreated.splice(insertIndex, 0, tableData); + continue; + } + const toBeAddedFields = {}; + for (const [fieldName, field] of Object.entries(value.fields)) { + const column = table.columns.find((c5) => c5.name === fieldName); + if (!column) { + toBeAddedFields[fieldName] = field; + continue; + } + if (matchType(column.dataType, field.type, dbType)) continue; + else logger$1.warn(`Field ${fieldName} in table ${key} has a different type in the database. Expected ${field.type} but got ${column.dataType}.`); + } + if (Object.keys(toBeAddedFields).length > 0) toBeAdded.push({ + table: key, + fields: toBeAddedFields, + order: value.order || Infinity + }); + } + const migrations = []; + const useUUIDs = config3.advanced?.database?.generateId === "uuid"; + const useNumberId = config3.advanced?.database?.useNumberId || config3.advanced?.database?.generateId === "serial"; + function getType(field, fieldName) { + const type = field.type; + const provider = dbType || "sqlite"; + const typeMap = { + string: { + sqlite: "text", + postgres: "text", + mysql: field.unique ? "varchar(255)" : field.references ? "varchar(36)" : field.sortable ? "varchar(255)" : field.index ? "varchar(255)" : "text", + mssql: field.unique || field.sortable ? "varchar(255)" : field.references ? "varchar(36)" : "varchar(8000)" + }, + boolean: { + sqlite: "integer", + postgres: "boolean", + mysql: "boolean", + mssql: "smallint" + }, + number: { + sqlite: field.bigint ? "bigint" : "integer", + postgres: field.bigint ? "bigint" : "integer", + mysql: field.bigint ? "bigint" : "integer", + mssql: field.bigint ? "bigint" : "integer" + }, + date: { + sqlite: "date", + postgres: "timestamptz", + mysql: "timestamp(3)", + mssql: sql2`datetime2(3)` + }, + json: { + sqlite: "text", + postgres: "jsonb", + mysql: "json", + mssql: "varchar(8000)" + }, + id: { + postgres: useNumberId ? sql2`integer GENERATED BY DEFAULT AS IDENTITY` : useUUIDs ? "uuid" : "text", + mysql: useNumberId ? "integer" : useUUIDs ? "varchar(36)" : "varchar(36)", + mssql: useNumberId ? "integer" : useUUIDs ? "varchar(36)" : "varchar(36)", + sqlite: useNumberId ? "integer" : "text" + }, + foreignKeyId: { + postgres: useNumberId ? "integer" : useUUIDs ? "uuid" : "text", + mysql: useNumberId ? "integer" : useUUIDs ? "varchar(36)" : "varchar(36)", + mssql: useNumberId ? "integer" : useUUIDs ? "varchar(36)" : "varchar(36)", + sqlite: useNumberId ? "integer" : "text" + }, + "string[]": { + sqlite: "text", + postgres: "jsonb", + mysql: "json", + mssql: "varchar(8000)" + }, + "number[]": { + sqlite: "text", + postgres: "jsonb", + mysql: "json", + mssql: "varchar(8000)" + } + }; + if (fieldName === "id" || field.references?.field === "id") { + if (fieldName === "id") return typeMap.id[provider]; + return typeMap.foreignKeyId[provider]; + } + if (Array.isArray(type)) return "text"; + if (!(type in typeMap)) throw new Error(`Unsupported field type '${String(type)}' for field '${fieldName}'. Allowed types are: string, number, boolean, date, string[], number[]. If you need to store structured data, store it as a JSON string (type: "string") or split it into primitive fields. See https://better-auth.com/docs/advanced/schema#additional-fields`); + return typeMap[type][provider]; + } + const getModelName = initGetModelName({ + schema: getAuthTables(config3), + usePlural: false + }); + const getFieldName = initGetFieldName({ + schema: getAuthTables(config3), + usePlural: false + }); + function getReferencePath(model, field) { + try { + return `${getModelName(model)}.${getFieldName({ + model, + field + })}`; + } catch { + return `${model}.${field}`; + } + } + if (toBeAdded.length) for (const table of toBeAdded) for (const [fieldName, field] of Object.entries(table.fields)) { + const type = getType(field, fieldName); + const builder = db.schema.alterTable(table.table); + if (field.index) { + const index2 = db.schema.alterTable(table.table).addIndex(`${table.table}_${fieldName}_idx`); + migrations.push(index2); + } + const built = builder.addColumn(fieldName, type, (col) => { + col = field.required !== false ? col.notNull() : col; + if (field.references) col = col.references(getReferencePath(field.references.model, field.references.field)).onDelete(field.references.onDelete || "cascade"); + if (field.unique) col = col.unique(); + if (field.type === "date" && typeof field.defaultValue === "function" && (dbType === "postgres" || dbType === "mysql" || dbType === "mssql")) if (dbType === "mysql") col = col.defaultTo(sql2`CURRENT_TIMESTAMP(3)`); + else col = col.defaultTo(sql2`CURRENT_TIMESTAMP`); + return col; + }); + migrations.push(built); + } + const toBeIndexed = []; + if (config3.advanced?.database?.useNumberId) logger$1.warn("`useNumberId` is deprecated. Please use `generateId` with `serial` instead."); + if (toBeCreated.length) for (const table of toBeCreated) { + const idType = getType({ type: useNumberId ? "number" : "string" }, "id"); + let dbT = db.schema.createTable(table.table).addColumn("id", idType, (col) => { + if (useNumberId) { + if (dbType === "postgres") return col.primaryKey().notNull(); + else if (dbType === "sqlite") return col.primaryKey().notNull(); + else if (dbType === "mssql") return col.identity().primaryKey().notNull(); + return col.autoIncrement().primaryKey().notNull(); + } + if (useUUIDs) { + if (dbType === "postgres") return col.primaryKey().defaultTo(sql2`pg_catalog.gen_random_uuid()`).notNull(); + return col.primaryKey().notNull(); + } + return col.primaryKey().notNull(); + }); + for (const [fieldName, field] of Object.entries(table.fields)) { + const type = getType(field, fieldName); + dbT = dbT.addColumn(fieldName, type, (col) => { + col = field.required !== false ? col.notNull() : col; + if (field.references) col = col.references(getReferencePath(field.references.model, field.references.field)).onDelete(field.references.onDelete || "cascade"); + if (field.unique) col = col.unique(); + if (field.type === "date" && typeof field.defaultValue === "function" && (dbType === "postgres" || dbType === "mysql" || dbType === "mssql")) if (dbType === "mysql") col = col.defaultTo(sql2`CURRENT_TIMESTAMP(3)`); + else col = col.defaultTo(sql2`CURRENT_TIMESTAMP`); + return col; + }); + if (field.index) { + const builder = db.schema.createIndex(`${table.table}_${fieldName}_${field.unique ? "uidx" : "idx"}`).on(table.table).columns([fieldName]); + toBeIndexed.push(field.unique ? builder.unique() : builder); + } + } + migrations.push(dbT); + } + if (toBeIndexed.length) for (const index2 of toBeIndexed) migrations.push(index2); + async function runMigrations() { + for (const migration of migrations) await migration.execute(); + } + async function compileMigrations() { + return migrations.map((m5) => m5.compile().sql).join(";\n\n") + ";"; + } + return { + toBeCreated, + toBeAdded, + runMigrations, + compileMigrations + }; +} +var map3; +var init_get_migration = __esm({ + "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/db/get-migration.mjs"() { + init_dialect3(); + init_get_schema(); + init_db3(); + init_env(); + init_esm(); + init_adapter(); + map3 = { + postgres: { + string: [ + "character varying", + "varchar", + "text", + "uuid" + ], + number: [ + "int4", + "integer", + "bigint", + "smallint", + "numeric", + "real", + "double precision" + ], + boolean: ["bool", "boolean"], + date: [ + "timestamptz", + "timestamp", + "date" + ], + json: ["json", "jsonb"] + }, + mysql: { + string: [ + "varchar", + "text", + "uuid" + ], + number: [ + "integer", + "int", + "bigint", + "smallint", + "decimal", + "float", + "double" + ], + boolean: ["boolean", "tinyint"], + date: [ + "timestamp", + "datetime", + "date" + ], + json: ["json"] + }, + sqlite: { + string: ["TEXT"], + number: ["INTEGER", "REAL"], + boolean: ["INTEGER", "BOOLEAN"], + date: ["DATE", "INTEGER"], + json: ["TEXT"] + }, + mssql: { + string: [ + "varchar", + "nvarchar", + "uniqueidentifier" + ], + number: [ + "int", + "bigint", + "smallint", + "decimal", + "float", + "double" + ], + boolean: ["bit", "smallint"], + date: [ + "datetime2", + "date", + "datetime" + ], + json: ["varchar", "nvarchar"] + } + }; + } +}); + +// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/db/index.mjs +var db_exports2; +var init_db4 = __esm({ + "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/db/index.mjs"() { + init_rolldown_runtime(); + init_adapter_base(); + init_adapter_kysely(); + init_field(); + init_field_converter(); + init_schema4(); + init_with_hooks(); + init_internal_adapter(); + init_to_zod(); + init_get_schema(); + init_get_migration(); + init_db3(); + init_db3(); + db_exports2 = /* @__PURE__ */ __export2({ + convertFromDB: () => convertFromDB, + convertToDB: () => convertToDB, + createFieldAttribute: () => createFieldAttribute, + createInternalAdapter: () => createInternalAdapter, + getAdapter: () => getAdapter, + getBaseAdapter: () => getBaseAdapter, + getMigrations: () => getMigrations, + getSchema: () => getSchema, + getWithHooks: () => getWithHooks, + matchType: () => matchType, + mergeSchema: () => mergeSchema, + parseAccountInput: () => parseAccountInput, + parseAccountOutput: () => parseAccountOutput, + parseAdditionalUserInput: () => parseAdditionalUserInput, + parseInputData: () => parseInputData, + parseSessionInput: () => parseSessionInput, + parseSessionOutput: () => parseSessionOutput, + parseUserInput: () => parseUserInput, + parseUserOutput: () => parseUserOutput, + toZodSchema: () => toZodSchema + }); + __reExport(db_exports2, db_exports); + } +}); + +// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/api/routes/session.mjs +var getSession, getSessionFromCtx, sessionMiddleware, sensitiveSessionMiddleware, requestOnlySessionMiddleware, freshSessionMiddleware, listSessions, revokeSession, revokeSessions, revokeOtherSessions; +var init_session4 = __esm({ + "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/api/routes/session.mjs"() { + init_date2(); + init_schema4(); + init_db4(); + init_jwt(); + init_crypto(); + init_session_store(); + init_cookies2(); + init_error(); + init_utils7(); + init_dist3(); + init_zod(); + init_api2(); + init_base642(); + init_binary(); + init_hmac2(); + getSession = () => createAuthEndpoint("/get-session", { + method: "GET", + operationId: "getSession", + query: getSessionQuerySchema, + requireHeaders: true, + metadata: { openapi: { + operationId: "getSession", + description: "Get the current session", + responses: { "200": { + description: "Success", + content: { "application/json": { schema: { + type: "object", + nullable: true, + properties: { + session: { $ref: "#/components/schemas/Session" }, + user: { $ref: "#/components/schemas/User" } + }, + required: ["session", "user"] + } } } + } } + } } + }, async (ctx) => { + try { + const sessionCookieToken = await ctx.getSignedCookie(ctx.context.authCookies.sessionToken.name, ctx.context.secret); + if (!sessionCookieToken) return null; + const sessionDataCookie = getChunkedCookie(ctx, ctx.context.authCookies.sessionData.name); + let sessionDataPayload = null; + if (sessionDataCookie) { + const strategy = ctx.context.options.session?.cookieCache?.strategy || "compact"; + if (strategy === "jwe") { + const payload2 = await symmetricDecodeJWT(sessionDataCookie, ctx.context.secret, "better-auth-session"); + if (payload2 && payload2.session && payload2.user) sessionDataPayload = { + session: { + session: payload2.session, + user: payload2.user, + updatedAt: payload2.updatedAt, + version: payload2.version + }, + expiresAt: payload2.exp ? payload2.exp * 1e3 : Date.now() + }; + else { + expireCookie(ctx, ctx.context.authCookies.sessionData); + return ctx.json(null); + } + } else if (strategy === "jwt") { + const payload2 = await verifyJWT(sessionDataCookie, ctx.context.secret); + if (payload2 && payload2.session && payload2.user) sessionDataPayload = { + session: { + session: payload2.session, + user: payload2.user, + updatedAt: payload2.updatedAt, + version: payload2.version + }, + expiresAt: payload2.exp ? payload2.exp * 1e3 : Date.now() + }; + else { + expireCookie(ctx, ctx.context.authCookies.sessionData); + return ctx.json(null); + } + } else { + const parsed = safeJSONParse(binary.decode(base64Url.decode(sessionDataCookie))); + if (parsed) if (await createHMAC("SHA-256", "base64urlnopad").verify(ctx.context.secret, JSON.stringify({ + ...parsed.session, + expiresAt: parsed.expiresAt + }), parsed.signature)) sessionDataPayload = parsed; + else { + expireCookie(ctx, ctx.context.authCookies.sessionData); + return ctx.json(null); + } + } + } + const dontRememberMe = await ctx.getSignedCookie(ctx.context.authCookies.dontRememberToken.name, ctx.context.secret); + if (sessionDataPayload?.session && ctx.context.options.session?.cookieCache?.enabled && !ctx.query?.disableCookieCache) { + const session$1 = sessionDataPayload.session; + const versionConfig = ctx.context.options.session?.cookieCache?.version; + let expectedVersion = "1"; + if (versionConfig) { + if (typeof versionConfig === "string") expectedVersion = versionConfig; + else if (typeof versionConfig === "function") { + const result = versionConfig(session$1.session, session$1.user); + expectedVersion = result instanceof Promise ? await result : result; + } + } + if ((session$1.version || "1") !== expectedVersion) expireCookie(ctx, ctx.context.authCookies.sessionData); + else { + const cachedSessionExpiresAt = new Date(session$1.session.expiresAt); + if (sessionDataPayload.expiresAt < Date.now() || cachedSessionExpiresAt < /* @__PURE__ */ new Date()) expireCookie(ctx, ctx.context.authCookies.sessionData); + else { + const cookieRefreshCache = ctx.context.sessionConfig.cookieRefreshCache; + if (cookieRefreshCache === false) { + ctx.context.session = session$1; + const parsedSession$2 = parseSessionOutput(ctx.context.options, { + ...session$1.session, + expiresAt: new Date(session$1.session.expiresAt), + createdAt: new Date(session$1.session.createdAt), + updatedAt: new Date(session$1.session.updatedAt) + }); + const parsedUser$2 = parseUserOutput(ctx.context.options, { + ...session$1.user, + createdAt: new Date(session$1.user.createdAt), + updatedAt: new Date(session$1.user.updatedAt) + }); + return ctx.json({ + session: parsedSession$2, + user: parsedUser$2 + }); + } + if (sessionDataPayload.expiresAt - Date.now() < cookieRefreshCache.updateAge * 1e3) { + const newExpiresAt = getDate(ctx.context.options.session?.cookieCache?.maxAge || 300, "sec"); + const refreshedSession = { + session: { + ...session$1.session, + expiresAt: newExpiresAt + }, + user: session$1.user, + updatedAt: Date.now() + }; + await setCookieCache(ctx, refreshedSession, false); + const parsedRefreshedSession = parseSessionOutput(ctx.context.options, { + ...refreshedSession.session, + expiresAt: new Date(refreshedSession.session.expiresAt), + createdAt: new Date(refreshedSession.session.createdAt), + updatedAt: new Date(refreshedSession.session.updatedAt) + }); + const parsedRefreshedUser = parseUserOutput(ctx.context.options, { + ...refreshedSession.user, + createdAt: new Date(refreshedSession.user.createdAt), + updatedAt: new Date(refreshedSession.user.updatedAt) + }); + ctx.context.session = { + session: parsedRefreshedSession, + user: parsedRefreshedUser + }; + return ctx.json({ + session: parsedRefreshedSession, + user: parsedRefreshedUser + }); + } + const parsedSession$1 = parseSessionOutput(ctx.context.options, { + ...session$1.session, + expiresAt: new Date(session$1.session.expiresAt), + createdAt: new Date(session$1.session.createdAt), + updatedAt: new Date(session$1.session.updatedAt) + }); + const parsedUser$1 = parseUserOutput(ctx.context.options, { + ...session$1.user, + createdAt: new Date(session$1.user.createdAt), + updatedAt: new Date(session$1.user.updatedAt) + }); + ctx.context.session = { + session: parsedSession$1, + user: parsedUser$1 + }; + return ctx.json({ + session: parsedSession$1, + user: parsedUser$1 + }); + } + } + } + const session = await ctx.context.internalAdapter.findSession(sessionCookieToken); + ctx.context.session = session; + if (!session || session.session.expiresAt < /* @__PURE__ */ new Date()) { + deleteSessionCookie(ctx); + if (session) + await ctx.context.internalAdapter.deleteSession(session.session.token); + return ctx.json(null); + } + if (dontRememberMe || ctx.query?.disableRefresh) { + const parsedSession$1 = parseSessionOutput(ctx.context.options, session.session); + const parsedUser$1 = parseUserOutput(ctx.context.options, session.user); + return ctx.json({ + session: parsedSession$1, + user: parsedUser$1 + }); + } + const expiresIn = ctx.context.sessionConfig.expiresIn; + const updateAge = ctx.context.sessionConfig.updateAge; + if (session.session.expiresAt.valueOf() - expiresIn * 1e3 + updateAge * 1e3 <= Date.now() && (!ctx.query?.disableRefresh || !ctx.context.options.session?.disableSessionRefresh)) { + const updatedSession = await ctx.context.internalAdapter.updateSession(session.session.token, { + expiresAt: getDate(ctx.context.sessionConfig.expiresIn, "sec"), + updatedAt: /* @__PURE__ */ new Date() + }); + if (!updatedSession) { + deleteSessionCookie(ctx); + return ctx.json(null, { status: 401 }); + } + const maxAge = (updatedSession.expiresAt.valueOf() - Date.now()) / 1e3; + await setSessionCookie(ctx, { + session: updatedSession, + user: session.user + }, false, { maxAge }); + const parsedUpdatedSession = parseSessionOutput(ctx.context.options, updatedSession); + const parsedUser$1 = parseUserOutput(ctx.context.options, session.user); + return ctx.json({ + session: parsedUpdatedSession, + user: parsedUser$1 + }); + } + await setCookieCache(ctx, session, !!dontRememberMe); + const parsedSession = parseSessionOutput(ctx.context.options, session.session); + const parsedUser = parseUserOutput(ctx.context.options, session.user); + return ctx.json({ + session: parsedSession, + user: parsedUser + }); + } catch (error50) { + ctx.context.logger.error("INTERNAL_SERVER_ERROR", error50); + throw new APIError("INTERNAL_SERVER_ERROR", { message: BASE_ERROR_CODES.FAILED_TO_GET_SESSION }); + } + }); + getSessionFromCtx = async (ctx, config3) => { + if (ctx.context.session) return ctx.context.session; + const session = await getSession()({ + ...ctx, + asResponse: false, + headers: ctx.headers, + returnHeaders: false, + returnStatus: false, + query: { + ...config3, + ...ctx.query + } + }).catch((e5) => { + return null; + }); + ctx.context.session = session; + return session; + }; + sessionMiddleware = createAuthMiddleware(async (ctx) => { + const session = await getSessionFromCtx(ctx); + if (!session?.session) throw new APIError("UNAUTHORIZED"); + return { session }; + }); + sensitiveSessionMiddleware = createAuthMiddleware(async (ctx) => { + const session = await getSessionFromCtx(ctx, { disableCookieCache: true }); + if (!session?.session) throw new APIError("UNAUTHORIZED"); + return { session }; + }); + requestOnlySessionMiddleware = createAuthMiddleware(async (ctx) => { + const session = await getSessionFromCtx(ctx); + if (!session?.session && (ctx.request || ctx.headers)) throw new APIError("UNAUTHORIZED"); + return { session }; + }); + freshSessionMiddleware = createAuthMiddleware(async (ctx) => { + const session = await getSessionFromCtx(ctx); + if (!session?.session) throw new APIError("UNAUTHORIZED"); + if (ctx.context.sessionConfig.freshAge === 0) return { session }; + const freshAge = ctx.context.sessionConfig.freshAge; + const lastUpdated = new Date(session.session.updatedAt || session.session.createdAt).getTime(); + if (!(Date.now() - lastUpdated < freshAge * 1e3)) throw new APIError("FORBIDDEN", { message: "Session is not fresh" }); + return { session }; + }); + listSessions = () => createAuthEndpoint("/list-sessions", { + method: "GET", + operationId: "listUserSessions", + use: [sessionMiddleware], + requireHeaders: true, + metadata: { openapi: { + operationId: "listUserSessions", + description: "List all active sessions for the user", + responses: { "200": { + description: "Success", + content: { "application/json": { schema: { + type: "array", + items: { $ref: "#/components/schemas/Session" } + } } } + } } + } } + }, async (ctx) => { + try { + const activeSessions = (await ctx.context.internalAdapter.listSessions(ctx.context.session.user.id)).filter((session) => { + return session.expiresAt > /* @__PURE__ */ new Date(); + }); + return ctx.json(activeSessions.map((session) => parseSessionOutput(ctx.context.options, session))); + } catch (e5) { + ctx.context.logger.error(e5); + throw ctx.error("INTERNAL_SERVER_ERROR"); + } + }); + revokeSession = createAuthEndpoint("/revoke-session", { + method: "POST", + body: object({ token: string2().meta({ description: "The token to revoke" }) }), + use: [sensitiveSessionMiddleware], + requireHeaders: true, + metadata: { openapi: { + description: "Revoke a single session", + requestBody: { content: { "application/json": { schema: { + type: "object", + properties: { token: { + type: "string", + description: "The token to revoke" + } }, + required: ["token"] + } } } }, + responses: { "200": { + description: "Success", + content: { "application/json": { schema: { + type: "object", + properties: { status: { + type: "boolean", + description: "Indicates if the session was revoked successfully" + } }, + required: ["status"] + } } } + } } + } } + }, async (ctx) => { + const token = ctx.body.token; + if ((await ctx.context.internalAdapter.findSession(token))?.session.userId === ctx.context.session.user.id) try { + await ctx.context.internalAdapter.deleteSession(token); + } catch (error50) { + ctx.context.logger.error(error50 && typeof error50 === "object" && "name" in error50 ? error50.name : "", error50); + throw new APIError("INTERNAL_SERVER_ERROR"); + } + return ctx.json({ status: true }); + }); + revokeSessions = createAuthEndpoint("/revoke-sessions", { + method: "POST", + use: [sensitiveSessionMiddleware], + requireHeaders: true, + metadata: { openapi: { + description: "Revoke all sessions for the user", + responses: { "200": { + description: "Success", + content: { "application/json": { schema: { + type: "object", + properties: { status: { + type: "boolean", + description: "Indicates if all sessions were revoked successfully" + } }, + required: ["status"] + } } } + } } + } } + }, async (ctx) => { + try { + await ctx.context.internalAdapter.deleteSessions(ctx.context.session.user.id); + } catch (error50) { + ctx.context.logger.error(error50 && typeof error50 === "object" && "name" in error50 ? error50.name : "", error50); + throw new APIError("INTERNAL_SERVER_ERROR"); + } + return ctx.json({ status: true }); + }); + revokeOtherSessions = createAuthEndpoint("/revoke-other-sessions", { + method: "POST", + requireHeaders: true, + use: [sensitiveSessionMiddleware], + metadata: { openapi: { + description: "Revoke all other sessions for the user except the current one", + responses: { "200": { + description: "Success", + content: { "application/json": { schema: { + type: "object", + properties: { status: { + type: "boolean", + description: "Indicates if all other sessions were revoked successfully" + } }, + required: ["status"] + } } } + } } + } } + }, async (ctx) => { + const session = ctx.context.session; + if (!session.user) throw new APIError("UNAUTHORIZED"); + const otherSessions = (await ctx.context.internalAdapter.listSessions(session.user.id)).filter((session$1) => { + return session$1.expiresAt > /* @__PURE__ */ new Date(); + }).filter((session$1) => session$1.token !== ctx.context.session.session.token); + await Promise.all(otherSessions.map((session$1) => ctx.context.internalAdapter.deleteSession(session$1.token))); + return ctx.json({ status: true }); + }); + } +}); + +// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/oauth2/utils.mjs +function decryptOAuthToken(token, ctx) { + if (!token) return token; + if (ctx.options.account?.encryptOAuthTokens) return symmetricDecrypt({ + key: ctx.secret, + data: token + }); + return token; +} +function setTokenUtil(token, ctx) { + if (ctx.options.account?.encryptOAuthTokens && token) return symmetricEncrypt({ + key: ctx.secret, + data: token + }); + return token; +} +var init_utils12 = __esm({ + "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/oauth2/utils.mjs"() { + init_crypto(); + } +}); + +// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/oauth2/utils.mjs +function getOAuth2Tokens(data2) { + const getDate2 = (seconds) => { + const now2 = /* @__PURE__ */ new Date(); + return new Date(now2.getTime() + seconds * 1e3); + }; + return { + tokenType: data2.token_type, + accessToken: data2.access_token, + refreshToken: data2.refresh_token, + accessTokenExpiresAt: data2.expires_in ? getDate2(data2.expires_in) : void 0, + refreshTokenExpiresAt: data2.refresh_token_expires_in ? getDate2(data2.refresh_token_expires_in) : void 0, + scopes: data2?.scope ? typeof data2.scope === "string" ? data2.scope.split(" ") : data2.scope : [], + idToken: data2.id_token, + raw: data2 + }; +} +async function generateCodeChallenge(codeVerifier) { + const data2 = new TextEncoder().encode(codeVerifier); + const hash2 = await crypto.subtle.digest("SHA-256", data2); + return base64Url.encode(new Uint8Array(hash2), { padding: false }); +} +var init_utils13 = __esm({ + "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/oauth2/utils.mjs"() { + init_base642(); + } +}); + +// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/oauth2/create-authorization-url.mjs +async function createAuthorizationURL({ id, options, authorizationEndpoint, state: state2, codeVerifier, scopes, claims, redirectURI, duration: duration3, prompt, accessType, responseType, display, loginHint, hd, responseMode, additionalParams, scopeJoiner }) { + const url2 = new URL(options.authorizationEndpoint || authorizationEndpoint); + url2.searchParams.set("response_type", responseType || "code"); + const primaryClientId = Array.isArray(options.clientId) ? options.clientId[0] : options.clientId; + url2.searchParams.set("client_id", primaryClientId); + url2.searchParams.set("state", state2); + if (scopes) url2.searchParams.set("scope", scopes.join(scopeJoiner || " ")); + url2.searchParams.set("redirect_uri", options.redirectURI || redirectURI); + duration3 && url2.searchParams.set("duration", duration3); + display && url2.searchParams.set("display", display); + loginHint && url2.searchParams.set("login_hint", loginHint); + prompt && url2.searchParams.set("prompt", prompt); + hd && url2.searchParams.set("hd", hd); + accessType && url2.searchParams.set("access_type", accessType); + responseMode && url2.searchParams.set("response_mode", responseMode); + if (codeVerifier) { + const codeChallenge = await generateCodeChallenge(codeVerifier); + url2.searchParams.set("code_challenge_method", "S256"); + url2.searchParams.set("code_challenge", codeChallenge); + } + if (claims) { + const claimsObj = claims.reduce((acc, claim) => { + acc[claim] = null; + return acc; + }, {}); + url2.searchParams.set("claims", JSON.stringify({ id_token: { + email: null, + email_verified: null, + ...claimsObj + } })); + } + if (additionalParams) Object.entries(additionalParams).forEach(([key, value]) => { + url2.searchParams.set(key, value); + }); + return url2; +} +var init_create_authorization_url = __esm({ + "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/oauth2/create-authorization-url.mjs"() { + init_utils13(); + } +}); + +// node_modules/.pnpm/@better-fetch+fetch@1.1.21/node_modules/@better-fetch/fetch/dist/index.js +function createRetryStrategy(options) { + if (typeof options === "number") { + return new LinearRetryStrategy({ + type: "linear", + attempts: options, + delay: 1e3 + }); + } + switch (options.type) { + case "linear": + return new LinearRetryStrategy(options); + case "exponential": + return new ExponentialRetryStrategy(options); + default: + throw new Error("Invalid retry strategy"); + } +} +function detectResponseType(request) { + const _contentType = request.headers.get("content-type"); + const textTypes = /* @__PURE__ */ new Set([ + "image/svg", + "application/xml", + "application/xhtml", + "application/html" + ]); + if (!_contentType) { + return "json"; + } + const contentType = _contentType.split(";").shift() || ""; + if (JSON_RE.test(contentType)) { + return "json"; + } + if (textTypes.has(contentType) || contentType.startsWith("text/")) { + return "text"; + } + return "blob"; +} +function isJSONParsable(value) { + try { + JSON.parse(value); + return true; + } catch (error50) { + return false; + } +} +function isJSONSerializable2(value) { + if (value === void 0) { + return false; + } + const t5 = typeof value; + if (t5 === "string" || t5 === "number" || t5 === "boolean" || t5 === null) { + return true; + } + if (t5 !== "object") { + return false; + } + if (Array.isArray(value)) { + return true; + } + if (value.buffer) { + return false; + } + return value.constructor && value.constructor.name === "Object" || typeof value.toJSON === "function"; +} +function jsonParse(text3) { + try { + return JSON.parse(text3); + } catch (error50) { + return text3; + } +} +function isFunction2(value) { + return typeof value === "function"; +} +function getFetch(options) { + if (options == null ? void 0 : options.customFetchImpl) { + return options.customFetchImpl; + } + if (typeof globalThis !== "undefined" && isFunction2(globalThis.fetch)) { + return globalThis.fetch; + } + if (typeof window !== "undefined" && isFunction2(window.fetch)) { + return window.fetch; + } + throw new Error("No fetch implementation found"); +} +async function getHeaders(opts) { + const headers = new Headers(opts == null ? void 0 : opts.headers); + const authHeader = await getAuthHeader(opts); + for (const [key, value] of Object.entries(authHeader || {})) { + headers.set(key, value); + } + if (!headers.has("content-type")) { + const t5 = detectContentType(opts == null ? void 0 : opts.body); + if (t5) { + headers.set("content-type", t5); + } + } + return headers; +} +function detectContentType(body) { + if (isJSONSerializable2(body)) { + return "application/json"; + } + return null; +} +function getBody2(options) { + if (!(options == null ? void 0 : options.body)) { + return null; + } + const headers = new Headers(options == null ? void 0 : options.headers); + if (isJSONSerializable2(options.body) && !headers.has("content-type")) { + for (const [key, value] of Object.entries(options == null ? void 0 : options.body)) { + if (value instanceof Date) { + options.body[key] = value.toISOString(); + } + } + return JSON.stringify(options.body); + } + if (headers.has("content-type") && headers.get("content-type") === "application/x-www-form-urlencoded") { + if (isJSONSerializable2(options.body)) { + return new URLSearchParams(options.body).toString(); + } + return options.body; + } + return options.body; +} +function getMethod(url2, options) { + var _a6; + if (options == null ? void 0 : options.method) { + return options.method.toUpperCase(); + } + if (url2.startsWith("@")) { + const pMethod = (_a6 = url2.split("@")[1]) == null ? void 0 : _a6.split("/")[0]; + if (!methods.includes(pMethod)) { + return (options == null ? void 0 : options.body) ? "POST" : "GET"; + } + return pMethod.toUpperCase(); + } + return (options == null ? void 0 : options.body) ? "POST" : "GET"; +} +function getTimeout(options, controller) { + let abortTimeout; + if (!(options == null ? void 0 : options.signal) && (options == null ? void 0 : options.timeout)) { + abortTimeout = setTimeout(() => controller == null ? void 0 : controller.abort(), options == null ? void 0 : options.timeout); + } + return { + abortTimeout, + clearTimeout: () => { + if (abortTimeout) { + clearTimeout(abortTimeout); + } + } + }; +} +async function parseStandardSchema(schema2, input) { + const result = await schema2["~standard"].validate(input); + if (result.issues) { + throw new ValidationError2(result.issues); + } + return result.value; +} +function getURL2(url2, option) { + const { baseURL, params, query } = option || { + query: {}, + params: {}, + baseURL: "" + }; + let basePath = url2.startsWith("http") ? url2.split("/").slice(0, 3).join("/") : baseURL || ""; + if (url2.startsWith("@")) { + const m5 = url2.toString().split("@")[1].split("/")[0]; + if (methods.includes(m5)) { + url2 = url2.replace(`@${m5}/`, "/"); + } + } + if (!basePath.endsWith("/")) basePath += "/"; + let [path53, urlQuery] = url2.replace(basePath, "").split("?"); + const queryParams = new URLSearchParams(urlQuery); + for (const [key, value] of Object.entries(query || {})) { + if (value == null) continue; + let serializedValue; + if (typeof value === "string") { + serializedValue = value; + } else if (Array.isArray(value)) { + for (const val of value) { + queryParams.append(key, val); + } + continue; + } else { + serializedValue = JSON.stringify(value); + } + queryParams.set(key, serializedValue); + } + if (params) { + if (Array.isArray(params)) { + const paramPaths = path53.split("/").filter((p5) => p5.startsWith(":")); + for (const [index2, key] of paramPaths.entries()) { + const value = params[index2]; + path53 = path53.replace(key, value); + } + } else { + for (const [key, value] of Object.entries(params)) { + path53 = path53.replace(`:${key}`, String(value)); + } + } + } + path53 = path53.split("/").map(encodeURIComponent).join("/"); + if (path53.startsWith("/")) path53 = path53.slice(1); + let queryParamString = queryParams.toString(); + queryParamString = queryParamString.length > 0 ? `?${queryParamString}`.replace(/\+/g, "%20") : ""; + if (!basePath.startsWith("http")) { + return `${basePath}${path53}${queryParamString}`; + } + const _url2 = new URL(`${path53}${queryParamString}`, basePath); + return _url2; +} +var __defProp3, __defProps, __getOwnPropDescs, __getOwnPropSymbols, __hasOwnProp3, __propIsEnum, __defNormalProp, __spreadValues, __spreadProps, BetterFetchError, initializePlugins, LinearRetryStrategy, ExponentialRetryStrategy, getAuthHeader, JSON_RE, ValidationError2, methods, betterFetch; +var init_dist4 = __esm({ + "node_modules/.pnpm/@better-fetch+fetch@1.1.21/node_modules/@better-fetch/fetch/dist/index.js"() { + __defProp3 = Object.defineProperty; + __defProps = Object.defineProperties; + __getOwnPropDescs = Object.getOwnPropertyDescriptors; + __getOwnPropSymbols = Object.getOwnPropertySymbols; + __hasOwnProp3 = Object.prototype.hasOwnProperty; + __propIsEnum = Object.prototype.propertyIsEnumerable; + __defNormalProp = (obj, key, value) => key in obj ? __defProp3(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; + __spreadValues = (a5, b6) => { + for (var prop in b6 || (b6 = {})) + if (__hasOwnProp3.call(b6, prop)) + __defNormalProp(a5, prop, b6[prop]); + if (__getOwnPropSymbols) + for (var prop of __getOwnPropSymbols(b6)) { + if (__propIsEnum.call(b6, prop)) + __defNormalProp(a5, prop, b6[prop]); + } + return a5; + }; + __spreadProps = (a5, b6) => __defProps(a5, __getOwnPropDescs(b6)); + BetterFetchError = class extends Error { + constructor(status, statusText, error50) { + super(statusText || status.toString(), { + cause: error50 + }); + this.status = status; + this.statusText = statusText; + this.error = error50; + Error.captureStackTrace(this, this.constructor); + } + }; + initializePlugins = async (url2, options) => { + var _a6, _b, _c5, _d, _e5, _f; + let opts = options || {}; + const hooks = { + onRequest: [options == null ? void 0 : options.onRequest], + onResponse: [options == null ? void 0 : options.onResponse], + onSuccess: [options == null ? void 0 : options.onSuccess], + onError: [options == null ? void 0 : options.onError], + onRetry: [options == null ? void 0 : options.onRetry] + }; + if (!options || !(options == null ? void 0 : options.plugins)) { + return { + url: url2, + options: opts, + hooks + }; + } + for (const plugin of (options == null ? void 0 : options.plugins) || []) { + if (plugin.init) { + const pluginRes = await ((_a6 = plugin.init) == null ? void 0 : _a6.call(plugin, url2.toString(), options)); + opts = pluginRes.options || opts; + url2 = pluginRes.url; + } + hooks.onRequest.push((_b = plugin.hooks) == null ? void 0 : _b.onRequest); + hooks.onResponse.push((_c5 = plugin.hooks) == null ? void 0 : _c5.onResponse); + hooks.onSuccess.push((_d = plugin.hooks) == null ? void 0 : _d.onSuccess); + hooks.onError.push((_e5 = plugin.hooks) == null ? void 0 : _e5.onError); + hooks.onRetry.push((_f = plugin.hooks) == null ? void 0 : _f.onRetry); + } + return { + url: url2, + options: opts, + hooks + }; + }; + LinearRetryStrategy = class { + constructor(options) { + this.options = options; + } + shouldAttemptRetry(attempt, response) { + if (this.options.shouldRetry) { + return Promise.resolve( + attempt < this.options.attempts && this.options.shouldRetry(response) + ); + } + return Promise.resolve(attempt < this.options.attempts); + } + getDelay() { + return this.options.delay; + } + }; + ExponentialRetryStrategy = class { + constructor(options) { + this.options = options; + } + shouldAttemptRetry(attempt, response) { + if (this.options.shouldRetry) { + return Promise.resolve( + attempt < this.options.attempts && this.options.shouldRetry(response) + ); + } + return Promise.resolve(attempt < this.options.attempts); + } + getDelay(attempt) { + const delay3 = Math.min( + this.options.maxDelay, + this.options.baseDelay * 2 ** attempt + ); + return delay3; + } + }; + getAuthHeader = async (options) => { + const headers = {}; + const getValue = async (value) => typeof value === "function" ? await value() : value; + if (options == null ? void 0 : options.auth) { + if (options.auth.type === "Bearer") { + const token = await getValue(options.auth.token); + if (!token) { + return headers; + } + headers["authorization"] = `Bearer ${token}`; + } else if (options.auth.type === "Basic") { + const [username, password] = await Promise.all([ + getValue(options.auth.username), + getValue(options.auth.password) + ]); + if (!username || !password) { + return headers; + } + headers["authorization"] = `Basic ${btoa(`${username}:${password}`)}`; + } else if (options.auth.type === "Custom") { + const [prefix, value] = await Promise.all([ + getValue(options.auth.prefix), + getValue(options.auth.value) + ]); + if (!value) { + return headers; + } + headers["authorization"] = `${prefix != null ? prefix : ""} ${value}`; + } + } + return headers; + }; + JSON_RE = /^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i; + ValidationError2 = class _ValidationError extends Error { + constructor(issues2, message2) { + super(message2 || JSON.stringify(issues2, null, 2)); + this.issues = issues2; + Object.setPrototypeOf(this, _ValidationError.prototype); + } + }; + methods = ["get", "post", "put", "patch", "delete"]; + betterFetch = async (url2, options) => { + var _a6, _b, _c5, _d, _e5, _f, _g, _h4; + const { + hooks, + url: __url, + options: opts + } = await initializePlugins(url2, options); + const fetch2 = getFetch(opts); + const controller = new AbortController(); + const signal = (_a6 = opts.signal) != null ? _a6 : controller.signal; + const _url2 = getURL2(__url, opts); + const body = getBody2(opts); + const headers = await getHeaders(opts); + const method = getMethod(__url, opts); + let context = __spreadProps(__spreadValues({}, opts), { + url: _url2, + headers, + body, + method, + signal + }); + for (const onRequest of hooks.onRequest) { + if (onRequest) { + const res = await onRequest(context); + if (typeof res === "object" && res !== null) { + context = res; + } + } + } + if ("pipeTo" in context && typeof context.pipeTo === "function" || typeof ((_b = options == null ? void 0 : options.body) == null ? void 0 : _b.pipe) === "function") { + if (!("duplex" in context)) { + context.duplex = "half"; + } + } + const { clearTimeout: clearTimeout2 } = getTimeout(opts, controller); + let response = await fetch2(context.url, context); + clearTimeout2(); + const responseContext = { + response, + request: context + }; + for (const onResponse of hooks.onResponse) { + if (onResponse) { + const r5 = await onResponse(__spreadProps(__spreadValues({}, responseContext), { + response: ((_c5 = options == null ? void 0 : options.hookOptions) == null ? void 0 : _c5.cloneResponse) ? response.clone() : response + })); + if (r5 instanceof Response) { + response = r5; + } else if (typeof r5 === "object" && r5 !== null) { + response = r5.response; + } + } + } + if (response.ok) { + const hasBody = context.method !== "HEAD"; + if (!hasBody) { + return { + data: "", + error: null + }; + } + const responseType = detectResponseType(response); + const successContext = { + data: null, + response, + request: context + }; + if (responseType === "json" || responseType === "text") { + const text3 = await response.text(); + const parser2 = (_d = context.jsonParser) != null ? _d : jsonParse; + successContext.data = await parser2(text3); + } else { + successContext.data = await response[responseType](); + } + if (context == null ? void 0 : context.output) { + if (context.output && !context.disableValidation) { + successContext.data = await parseStandardSchema( + context.output, + successContext.data + ); + } + } + for (const onSuccess of hooks.onSuccess) { + if (onSuccess) { + await onSuccess(__spreadProps(__spreadValues({}, successContext), { + response: ((_e5 = options == null ? void 0 : options.hookOptions) == null ? void 0 : _e5.cloneResponse) ? response.clone() : response + })); + } + } + if (options == null ? void 0 : options.throw) { + return successContext.data; + } + return { + data: successContext.data, + error: null + }; + } + const parser = (_f = options == null ? void 0 : options.jsonParser) != null ? _f : jsonParse; + const responseText = await response.text(); + const isJSONResponse2 = isJSONParsable(responseText); + const errorObject = isJSONResponse2 ? await parser(responseText) : null; + const errorContext = { + response, + responseText, + request: context, + error: __spreadProps(__spreadValues({}, errorObject), { + status: response.status, + statusText: response.statusText + }) + }; + for (const onError of hooks.onError) { + if (onError) { + await onError(__spreadProps(__spreadValues({}, errorContext), { + response: ((_g = options == null ? void 0 : options.hookOptions) == null ? void 0 : _g.cloneResponse) ? response.clone() : response + })); + } + } + if (options == null ? void 0 : options.retry) { + const retryStrategy = createRetryStrategy(options.retry); + const _retryAttempt = (_h4 = options.retryAttempt) != null ? _h4 : 0; + if (await retryStrategy.shouldAttemptRetry(_retryAttempt, response)) { + for (const onRetry of hooks.onRetry) { + if (onRetry) { + await onRetry(responseContext); + } + } + const delay3 = retryStrategy.getDelay(_retryAttempt); + await new Promise((resolve4) => setTimeout(resolve4, delay3)); + return await betterFetch(url2, __spreadProps(__spreadValues({}, options), { + retryAttempt: _retryAttempt + 1 + })); + } + } + if (options == null ? void 0 : options.throw) { + throw new BetterFetchError( + response.status, + response.statusText, + isJSONResponse2 ? errorObject : responseText + ); + } + return { + data: null, + error: __spreadProps(__spreadValues({}, errorObject), { + status: response.status, + statusText: response.statusText + }) + }; + }; + } +}); + +// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/oauth2/refresh-access-token.mjs +function createRefreshAccessTokenRequest({ refreshToken: refreshToken2, options, authentication, extraParams, resource }) { + const body = new URLSearchParams(); + const headers = { + "content-type": "application/x-www-form-urlencoded", + accept: "application/json" + }; + body.set("grant_type", "refresh_token"); + body.set("refresh_token", refreshToken2); + if (authentication === "basic") { + const primaryClientId = Array.isArray(options.clientId) ? options.clientId[0] : options.clientId; + if (primaryClientId) headers["authorization"] = "Basic " + base643.encode(`${primaryClientId}:${options.clientSecret ?? ""}`); + else headers["authorization"] = "Basic " + base643.encode(`:${options.clientSecret ?? ""}`); + } else { + const primaryClientId = Array.isArray(options.clientId) ? options.clientId[0] : options.clientId; + body.set("client_id", primaryClientId); + if (options.clientSecret) body.set("client_secret", options.clientSecret); + } + if (resource) if (typeof resource === "string") body.append("resource", resource); + else for (const _resource of resource) body.append("resource", _resource); + if (extraParams) for (const [key, value] of Object.entries(extraParams)) body.set(key, value); + return { + body, + headers + }; +} +async function refreshAccessToken({ refreshToken: refreshToken2, options, tokenEndpoint, authentication, extraParams }) { + const { body, headers } = createRefreshAccessTokenRequest({ + refreshToken: refreshToken2, + options, + authentication, + extraParams + }); + const { data: data2, error: error50 } = await betterFetch(tokenEndpoint, { + method: "POST", + body, + headers + }); + if (error50) throw error50; + const tokens = { + accessToken: data2.access_token, + refreshToken: data2.refresh_token, + tokenType: data2.token_type, + scopes: data2.scope?.split(" "), + idToken: data2.id_token + }; + if (data2.expires_in) { + const now2 = /* @__PURE__ */ new Date(); + tokens.accessTokenExpiresAt = new Date(now2.getTime() + data2.expires_in * 1e3); + } + return tokens; +} +var init_refresh_access_token = __esm({ + "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/oauth2/refresh-access-token.mjs"() { + init_base642(); + init_dist4(); + } +}); + +// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/oauth2/client-credentials-token.mjs +var init_client_credentials_token = __esm({ + "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/oauth2/client-credentials-token.mjs"() { + init_base642(); + init_dist4(); + } +}); + +// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/oauth2/verify.mjs +var init_verify4 = __esm({ + "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/oauth2/verify.mjs"() { + init_logger2(); + init_env(); + init_dist4(); + init_dist3(); + } +}); + +// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/oauth2/index.mjs +var init_oauth2 = __esm({ + "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/oauth2/index.mjs"() { + init_client_credentials_token(); + init_utils13(); + init_create_authorization_url(); + init_refresh_access_token(); + init_validate_authorization_code(); + init_verify4(); + } +}); + +// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/oauth2/validate-authorization-code.mjs +function createAuthorizationCodeRequest({ code, codeVerifier, redirectURI, options, authentication, deviceId, headers, additionalParams = {}, resource }) { + const body = new URLSearchParams(); + const requestHeaders = { + "content-type": "application/x-www-form-urlencoded", + accept: "application/json", + ...headers + }; + body.set("grant_type", "authorization_code"); + body.set("code", code); + codeVerifier && body.set("code_verifier", codeVerifier); + options.clientKey && body.set("client_key", options.clientKey); + deviceId && body.set("device_id", deviceId); + body.set("redirect_uri", options.redirectURI || redirectURI); + if (resource) if (typeof resource === "string") body.append("resource", resource); + else for (const _resource of resource) body.append("resource", _resource); + if (authentication === "basic") { + const primaryClientId = Array.isArray(options.clientId) ? options.clientId[0] : options.clientId; + requestHeaders["authorization"] = `Basic ${base643.encode(`${primaryClientId}:${options.clientSecret ?? ""}`)}`; + } else { + const primaryClientId = Array.isArray(options.clientId) ? options.clientId[0] : options.clientId; + body.set("client_id", primaryClientId); + if (options.clientSecret) body.set("client_secret", options.clientSecret); + } + for (const [key, value] of Object.entries(additionalParams)) if (!body.has(key)) body.append(key, value); + return { + body, + headers: requestHeaders + }; +} +async function validateAuthorizationCode({ code, codeVerifier, redirectURI, options, tokenEndpoint, authentication, deviceId, headers, additionalParams = {}, resource }) { + const { body, headers: requestHeaders } = createAuthorizationCodeRequest({ + code, + codeVerifier, + redirectURI, + options, + authentication, + deviceId, + headers, + additionalParams, + resource + }); + const { data: data2, error: error50 } = await betterFetch(tokenEndpoint, { + method: "POST", + body, + headers: requestHeaders + }); + if (error50) throw error50; + return getOAuth2Tokens(data2); +} +var init_validate_authorization_code = __esm({ + "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/oauth2/validate-authorization-code.mjs"() { + init_utils13(); + init_oauth2(); + init_base642(); + init_dist4(); + } +}); + +// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/apple.mjs +var apple, getApplePublicKey; +var init_apple = __esm({ + "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/apple.mjs"() { + init_create_authorization_url(); + init_refresh_access_token(); + init_validate_authorization_code(); + init_oauth2(); + init_dist4(); + init_webapi(); + init_dist3(); + apple = (options) => { + const tokenEndpoint = "https://appleid.apple.com/auth/token"; + return { + id: "apple", + name: "Apple", + async createAuthorizationURL({ state: state2, scopes, redirectURI }) { + const _scope = options.disableDefaultScope ? [] : ["email", "name"]; + if (options.scope) _scope.push(...options.scope); + if (scopes) _scope.push(...scopes); + return await createAuthorizationURL({ + id: "apple", + options, + authorizationEndpoint: "https://appleid.apple.com/auth/authorize", + scopes: _scope, + state: state2, + redirectURI, + responseMode: "form_post", + responseType: "code id_token" + }); + }, + validateAuthorizationCode: async ({ code, codeVerifier, redirectURI }) => { + return validateAuthorizationCode({ + code, + codeVerifier, + redirectURI, + options, + tokenEndpoint + }); + }, + async verifyIdToken(token, nonce) { + if (options.disableIdTokenSignIn) return false; + if (options.verifyIdToken) return options.verifyIdToken(token, nonce); + const { kid, alg: jwtAlg } = decodeProtectedHeader(token); + if (!kid || !jwtAlg) return false; + const { payload: jwtClaims } = await jwtVerify(token, await getApplePublicKey(kid), { + algorithms: [jwtAlg], + issuer: "https://appleid.apple.com", + audience: options.audience && options.audience.length ? options.audience : options.appBundleIdentifier ? options.appBundleIdentifier : options.clientId, + maxTokenAge: "1h" + }); + ["email_verified", "is_private_email"].forEach((field) => { + if (jwtClaims[field] !== void 0) jwtClaims[field] = Boolean(jwtClaims[field]); + }); + if (nonce && jwtClaims.nonce !== nonce) return false; + return !!jwtClaims; + }, + refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { + return refreshAccessToken({ + refreshToken: refreshToken2, + options: { + clientId: options.clientId, + clientKey: options.clientKey, + clientSecret: options.clientSecret + }, + tokenEndpoint: "https://appleid.apple.com/auth/token" + }); + }, + async getUserInfo(token) { + if (options.getUserInfo) return options.getUserInfo(token); + if (!token.idToken) return null; + const profile = decodeJwt(token.idToken); + if (!profile) return null; + let name; + if (token.user?.name) name = `${token.user.name.firstName || ""} ${token.user.name.lastName || ""}`.trim() || " "; + else name = profile.name || " "; + const emailVerified = typeof profile.email_verified === "boolean" ? profile.email_verified : profile.email_verified === "true"; + const enrichedProfile = { + ...profile, + name + }; + const userMap = await options.mapProfileToUser?.(enrichedProfile); + return { + user: { + id: profile.sub, + name: enrichedProfile.name, + emailVerified, + email: profile.email, + ...userMap + }, + data: enrichedProfile + }; + }, + options + }; + }; + getApplePublicKey = async (kid) => { + const { data: data2 } = await betterFetch(`https://appleid.apple.com/auth/keys`); + if (!data2?.keys) throw new APIError("BAD_REQUEST", { message: "Keys not found" }); + const jwk = data2.keys.find((key) => key.kid === kid); + if (!jwk) throw new Error(`JWK with kid ${kid} not found`); + return await importJWK(jwk, jwk.alg); + }; + } +}); + +// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/atlassian.mjs +var atlassian; +var init_atlassian = __esm({ + "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/atlassian.mjs"() { + init_logger2(); + init_env(); + init_error(); + init_create_authorization_url(); + init_refresh_access_token(); + init_validate_authorization_code(); + init_oauth2(); + init_dist4(); + atlassian = (options) => { + return { + id: "atlassian", + name: "Atlassian", + async createAuthorizationURL({ state: state2, scopes, codeVerifier, redirectURI }) { + if (!options.clientId || !options.clientSecret) { + logger3.error("Client Id and Secret are required for Atlassian"); + throw new BetterAuthError("CLIENT_ID_AND_SECRET_REQUIRED"); + } + if (!codeVerifier) throw new BetterAuthError("codeVerifier is required for Atlassian"); + const _scopes = options.disableDefaultScope ? [] : ["read:jira-user", "offline_access"]; + if (options.scope) _scopes.push(...options.scope); + if (scopes) _scopes.push(...scopes); + return createAuthorizationURL({ + id: "atlassian", + options, + authorizationEndpoint: "https://auth.atlassian.com/authorize", + scopes: _scopes, + state: state2, + codeVerifier, + redirectURI, + additionalParams: { audience: "api.atlassian.com" }, + prompt: options.prompt + }); + }, + validateAuthorizationCode: async ({ code, codeVerifier, redirectURI }) => { + return validateAuthorizationCode({ + code, + codeVerifier, + redirectURI, + options, + tokenEndpoint: "https://auth.atlassian.com/oauth/token" + }); + }, + refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { + return refreshAccessToken({ + refreshToken: refreshToken2, + options: { + clientId: options.clientId, + clientSecret: options.clientSecret + }, + tokenEndpoint: "https://auth.atlassian.com/oauth/token" + }); + }, + async getUserInfo(token) { + if (options.getUserInfo) return options.getUserInfo(token); + if (!token.accessToken) return null; + try { + const { data: profile } = await betterFetch("https://api.atlassian.com/me", { headers: { Authorization: `Bearer ${token.accessToken}` } }); + if (!profile) return null; + const userMap = await options.mapProfileToUser?.(profile); + return { + user: { + id: profile.account_id, + name: profile.name, + email: profile.email, + image: profile.picture, + emailVerified: false, + ...userMap + }, + data: profile + }; + } catch (error50) { + logger3.error("Failed to fetch user info from Figma:", error50); + return null; + } + }, + options + }; + }; + } +}); + +// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/cognito.mjs +var cognito, getCognitoPublicKey; +var init_cognito = __esm({ + "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/cognito.mjs"() { + init_logger2(); + init_env(); + init_error(); + init_create_authorization_url(); + init_refresh_access_token(); + init_validate_authorization_code(); + init_oauth2(); + init_dist4(); + init_webapi(); + init_dist3(); + cognito = (options) => { + if (!options.domain || !options.region || !options.userPoolId) { + logger3.error("Domain, region and userPoolId are required for Amazon Cognito. Make sure to provide them in the options."); + throw new BetterAuthError("DOMAIN_AND_REGION_REQUIRED"); + } + const cleanDomain = options.domain.replace(/^https?:\/\//, ""); + const authorizationEndpoint = `https://${cleanDomain}/oauth2/authorize`; + const tokenEndpoint = `https://${cleanDomain}/oauth2/token`; + const userInfoEndpoint = `https://${cleanDomain}/oauth2/userinfo`; + return { + id: "cognito", + name: "Cognito", + async createAuthorizationURL({ state: state2, scopes, codeVerifier, redirectURI }) { + if (!options.clientId) { + logger3.error("ClientId is required for Amazon Cognito. Make sure to provide them in the options."); + throw new BetterAuthError("CLIENT_ID_AND_SECRET_REQUIRED"); + } + if (options.requireClientSecret && !options.clientSecret) { + logger3.error("Client Secret is required when requireClientSecret is true. Make sure to provide it in the options."); + throw new BetterAuthError("CLIENT_SECRET_REQUIRED"); + } + const _scopes = options.disableDefaultScope ? [] : [ + "openid", + "profile", + "email" + ]; + if (options.scope) _scopes.push(...options.scope); + if (scopes) _scopes.push(...scopes); + const url2 = await createAuthorizationURL({ + id: "cognito", + options: { ...options }, + authorizationEndpoint, + scopes: _scopes, + state: state2, + codeVerifier, + redirectURI, + prompt: options.prompt + }); + const scopeValue = url2.searchParams.get("scope"); + if (scopeValue) { + url2.searchParams.delete("scope"); + const encodedScope = encodeURIComponent(scopeValue); + const urlString = url2.toString(); + const separator = urlString.includes("?") ? "&" : "?"; + return new URL(`${urlString}${separator}scope=${encodedScope}`); + } + return url2; + }, + validateAuthorizationCode: async ({ code, codeVerifier, redirectURI }) => { + return validateAuthorizationCode({ + code, + codeVerifier, + redirectURI, + options, + tokenEndpoint + }); + }, + refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { + return refreshAccessToken({ + refreshToken: refreshToken2, + options: { + clientId: options.clientId, + clientKey: options.clientKey, + clientSecret: options.clientSecret + }, + tokenEndpoint + }); + }, + async verifyIdToken(token, nonce) { + if (options.disableIdTokenSignIn) return false; + if (options.verifyIdToken) return options.verifyIdToken(token, nonce); + try { + const { kid, alg: jwtAlg } = decodeProtectedHeader(token); + if (!kid || !jwtAlg) return false; + const publicKey = await getCognitoPublicKey(kid, options.region, options.userPoolId); + const expectedIssuer = `https://cognito-idp.${options.region}.amazonaws.com/${options.userPoolId}`; + const { payload: jwtClaims } = await jwtVerify(token, publicKey, { + algorithms: [jwtAlg], + issuer: expectedIssuer, + audience: options.clientId, + maxTokenAge: "1h" + }); + if (nonce && jwtClaims.nonce !== nonce) return false; + return true; + } catch (error50) { + logger3.error("Failed to verify ID token:", error50); + return false; + } + }, + async getUserInfo(token) { + if (options.getUserInfo) return options.getUserInfo(token); + if (token.idToken) try { + const profile = decodeJwt(token.idToken); + if (!profile) return null; + const name = profile.name || profile.given_name || profile.username || profile.email; + const enrichedProfile = { + ...profile, + name + }; + const userMap = await options.mapProfileToUser?.(enrichedProfile); + return { + user: { + id: profile.sub, + name: enrichedProfile.name, + email: profile.email, + image: profile.picture, + emailVerified: profile.email_verified, + ...userMap + }, + data: enrichedProfile + }; + } catch (error50) { + logger3.error("Failed to decode ID token:", error50); + } + if (token.accessToken) try { + const { data: userInfo } = await betterFetch(userInfoEndpoint, { headers: { Authorization: `Bearer ${token.accessToken}` } }); + if (userInfo) { + const userMap = await options.mapProfileToUser?.(userInfo); + return { + user: { + id: userInfo.sub, + name: userInfo.name || userInfo.given_name || userInfo.username, + email: userInfo.email, + image: userInfo.picture, + emailVerified: userInfo.email_verified, + ...userMap + }, + data: userInfo + }; + } + } catch (error50) { + logger3.error("Failed to fetch user info from Cognito:", error50); + } + return null; + }, + options + }; + }; + getCognitoPublicKey = async (kid, region, userPoolId) => { + const COGNITO_JWKS_URI = `https://cognito-idp.${region}.amazonaws.com/${userPoolId}/.well-known/jwks.json`; + try { + const { data: data2 } = await betterFetch(COGNITO_JWKS_URI); + if (!data2?.keys) throw new APIError("BAD_REQUEST", { message: "Keys not found" }); + const jwk = data2.keys.find((key) => key.kid === kid); + if (!jwk) throw new Error(`JWK with kid ${kid} not found`); + return await importJWK(jwk, jwk.alg); + } catch (error50) { + logger3.error("Failed to fetch Cognito public key:", error50); + throw error50; + } + }; + } +}); + +// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/discord.mjs +var discord; +var init_discord = __esm({ + "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/discord.mjs"() { + init_refresh_access_token(); + init_validate_authorization_code(); + init_oauth2(); + init_dist4(); + discord = (options) => { + return { + id: "discord", + name: "Discord", + createAuthorizationURL({ state: state2, scopes, redirectURI }) { + const _scopes = options.disableDefaultScope ? [] : ["identify", "email"]; + if (scopes) _scopes.push(...scopes); + if (options.scope) _scopes.push(...options.scope); + const permissionsParam = _scopes.includes("bot") && options.permissions !== void 0 ? `&permissions=${options.permissions}` : ""; + return new URL(`https://discord.com/api/oauth2/authorize?scope=${_scopes.join("+")}&response_type=code&client_id=${options.clientId}&redirect_uri=${encodeURIComponent(options.redirectURI || redirectURI)}&state=${state2}&prompt=${options.prompt || "none"}${permissionsParam}`); + }, + validateAuthorizationCode: async ({ code, redirectURI }) => { + return validateAuthorizationCode({ + code, + redirectURI, + options, + tokenEndpoint: "https://discord.com/api/oauth2/token" + }); + }, + refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { + return refreshAccessToken({ + refreshToken: refreshToken2, + options: { + clientId: options.clientId, + clientKey: options.clientKey, + clientSecret: options.clientSecret + }, + tokenEndpoint: "https://discord.com/api/oauth2/token" + }); + }, + async getUserInfo(token) { + if (options.getUserInfo) return options.getUserInfo(token); + const { data: profile, error: error50 } = await betterFetch("https://discord.com/api/users/@me", { headers: { authorization: `Bearer ${token.accessToken}` } }); + if (error50) return null; + if (profile.avatar === null) profile.image_url = `https://cdn.discordapp.com/embed/avatars/${profile.discriminator === "0" ? Number(BigInt(profile.id) >> BigInt(22)) % 6 : parseInt(profile.discriminator) % 5}.png`; + else { + const format2 = profile.avatar.startsWith("a_") ? "gif" : "png"; + profile.image_url = `https://cdn.discordapp.com/avatars/${profile.id}/${profile.avatar}.${format2}`; + } + const userMap = await options.mapProfileToUser?.(profile); + return { + user: { + id: profile.id, + name: profile.global_name || profile.username || "", + email: profile.email, + emailVerified: profile.verified, + image: profile.image_url, + ...userMap + }, + data: profile + }; + }, + options + }; + }; + } +}); + +// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/dropbox.mjs +var dropbox; +var init_dropbox = __esm({ + "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/dropbox.mjs"() { + init_create_authorization_url(); + init_refresh_access_token(); + init_validate_authorization_code(); + init_oauth2(); + init_dist4(); + dropbox = (options) => { + const tokenEndpoint = "https://api.dropboxapi.com/oauth2/token"; + return { + id: "dropbox", + name: "Dropbox", + createAuthorizationURL: async ({ state: state2, scopes, codeVerifier, redirectURI }) => { + const _scopes = options.disableDefaultScope ? [] : ["account_info.read"]; + if (options.scope) _scopes.push(...options.scope); + if (scopes) _scopes.push(...scopes); + const additionalParams = {}; + if (options.accessType) additionalParams.token_access_type = options.accessType; + return await createAuthorizationURL({ + id: "dropbox", + options, + authorizationEndpoint: "https://www.dropbox.com/oauth2/authorize", + scopes: _scopes, + state: state2, + redirectURI, + codeVerifier, + additionalParams + }); + }, + validateAuthorizationCode: async ({ code, codeVerifier, redirectURI }) => { + return await validateAuthorizationCode({ + code, + codeVerifier, + redirectURI, + options, + tokenEndpoint + }); + }, + refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { + return refreshAccessToken({ + refreshToken: refreshToken2, + options: { + clientId: options.clientId, + clientKey: options.clientKey, + clientSecret: options.clientSecret + }, + tokenEndpoint: "https://api.dropbox.com/oauth2/token" + }); + }, + async getUserInfo(token) { + if (options.getUserInfo) return options.getUserInfo(token); + const { data: profile, error: error50 } = await betterFetch("https://api.dropboxapi.com/2/users/get_current_account", { + method: "POST", + headers: { Authorization: `Bearer ${token.accessToken}` } + }); + if (error50) return null; + const userMap = await options.mapProfileToUser?.(profile); + return { + user: { + id: profile.account_id, + name: profile.name?.display_name, + email: profile.email, + emailVerified: profile.email_verified || false, + image: profile.profile_photo_url, + ...userMap + }, + data: profile + }; + }, + options + }; + }; + } +}); + +// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/facebook.mjs +var facebook; +var init_facebook = __esm({ + "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/facebook.mjs"() { + init_create_authorization_url(); + init_refresh_access_token(); + init_validate_authorization_code(); + init_oauth2(); + init_dist4(); + init_webapi(); + facebook = (options) => { + return { + id: "facebook", + name: "Facebook", + async createAuthorizationURL({ state: state2, scopes, redirectURI, loginHint }) { + const _scopes = options.disableDefaultScope ? [] : ["email", "public_profile"]; + if (options.scope) _scopes.push(...options.scope); + if (scopes) _scopes.push(...scopes); + return await createAuthorizationURL({ + id: "facebook", + options, + authorizationEndpoint: "https://www.facebook.com/v24.0/dialog/oauth", + scopes: _scopes, + state: state2, + redirectURI, + loginHint, + additionalParams: options.configId ? { config_id: options.configId } : {} + }); + }, + validateAuthorizationCode: async ({ code, redirectURI }) => { + return validateAuthorizationCode({ + code, + redirectURI, + options, + tokenEndpoint: "https://graph.facebook.com/v24.0/oauth/access_token" + }); + }, + async verifyIdToken(token, nonce) { + if (options.disableIdTokenSignIn) return false; + if (options.verifyIdToken) return options.verifyIdToken(token, nonce); + if (token.split(".").length === 3) try { + const { payload: jwtClaims } = await jwtVerify(token, createRemoteJWKSet(new URL("https://limited.facebook.com/.well-known/oauth/openid/jwks/")), { + algorithms: ["RS256"], + audience: options.clientId, + issuer: "https://www.facebook.com" + }); + if (nonce && jwtClaims.nonce !== nonce) return false; + return !!jwtClaims; + } catch { + return false; + } + return true; + }, + refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { + return refreshAccessToken({ + refreshToken: refreshToken2, + options: { + clientId: options.clientId, + clientKey: options.clientKey, + clientSecret: options.clientSecret + }, + tokenEndpoint: "https://graph.facebook.com/v24.0/oauth/access_token" + }); + }, + async getUserInfo(token) { + if (options.getUserInfo) return options.getUserInfo(token); + if (token.idToken && token.idToken.split(".").length === 3) { + const profile$1 = decodeJwt(token.idToken); + const user = { + id: profile$1.sub, + name: profile$1.name, + email: profile$1.email, + picture: { data: { + url: profile$1.picture, + height: 100, + width: 100, + is_silhouette: false + } } + }; + const userMap$1 = await options.mapProfileToUser?.({ + ...user, + email_verified: false + }); + return { + user: { + ...user, + emailVerified: false, + ...userMap$1 + }, + data: profile$1 + }; + } + const { data: profile, error: error50 } = await betterFetch("https://graph.facebook.com/me?fields=" + [ + "id", + "name", + "email", + "picture", + ...options?.fields || [] + ].join(","), { auth: { + type: "Bearer", + token: token.accessToken + } }); + if (error50) return null; + const userMap = await options.mapProfileToUser?.(profile); + return { + user: { + id: profile.id, + name: profile.name, + email: profile.email, + image: profile.picture.data.url, + emailVerified: profile.email_verified, + ...userMap + }, + data: profile + }; + }, + options + }; + }; + } +}); + +// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/figma.mjs +var figma; +var init_figma = __esm({ + "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/figma.mjs"() { + init_logger2(); + init_env(); + init_error(); + init_create_authorization_url(); + init_refresh_access_token(); + init_validate_authorization_code(); + init_oauth2(); + init_dist4(); + figma = (options) => { + return { + id: "figma", + name: "Figma", + async createAuthorizationURL({ state: state2, scopes, codeVerifier, redirectURI }) { + if (!options.clientId || !options.clientSecret) { + logger3.error("Client Id and Client Secret are required for Figma. Make sure to provide them in the options."); + throw new BetterAuthError("CLIENT_ID_AND_SECRET_REQUIRED"); + } + if (!codeVerifier) throw new BetterAuthError("codeVerifier is required for Figma"); + const _scopes = options.disableDefaultScope ? [] : ["current_user:read"]; + if (options.scope) _scopes.push(...options.scope); + if (scopes) _scopes.push(...scopes); + return await createAuthorizationURL({ + id: "figma", + options, + authorizationEndpoint: "https://www.figma.com/oauth", + scopes: _scopes, + state: state2, + codeVerifier, + redirectURI + }); + }, + validateAuthorizationCode: async ({ code, codeVerifier, redirectURI }) => { + return validateAuthorizationCode({ + code, + codeVerifier, + redirectURI, + options, + tokenEndpoint: "https://api.figma.com/v1/oauth/token", + authentication: "basic" + }); + }, + refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { + return refreshAccessToken({ + refreshToken: refreshToken2, + options: { + clientId: options.clientId, + clientKey: options.clientKey, + clientSecret: options.clientSecret + }, + tokenEndpoint: "https://api.figma.com/v1/oauth/token", + authentication: "basic" + }); + }, + async getUserInfo(token) { + if (options.getUserInfo) return options.getUserInfo(token); + try { + const { data: profile } = await betterFetch("https://api.figma.com/v1/me", { headers: { Authorization: `Bearer ${token.accessToken}` } }); + if (!profile) { + logger3.error("Failed to fetch user from Figma"); + return null; + } + const userMap = await options.mapProfileToUser?.(profile); + return { + user: { + id: profile.id, + name: profile.handle, + email: profile.email, + image: profile.img_url, + emailVerified: false, + ...userMap + }, + data: profile + }; + } catch (error50) { + logger3.error("Failed to fetch user info from Figma:", error50); + return null; + } + }, + options + }; + }; + } +}); + +// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/github.mjs +var github; +var init_github = __esm({ + "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/github.mjs"() { + init_logger2(); + init_env(); + init_utils13(); + init_create_authorization_url(); + init_refresh_access_token(); + init_validate_authorization_code(); + init_oauth2(); + init_dist4(); + github = (options) => { + const tokenEndpoint = "https://github.com/login/oauth/access_token"; + return { + id: "github", + name: "GitHub", + createAuthorizationURL({ state: state2, scopes, loginHint, codeVerifier, redirectURI }) { + const _scopes = options.disableDefaultScope ? [] : ["read:user", "user:email"]; + if (options.scope) _scopes.push(...options.scope); + if (scopes) _scopes.push(...scopes); + return createAuthorizationURL({ + id: "github", + options, + authorizationEndpoint: "https://github.com/login/oauth/authorize", + scopes: _scopes, + state: state2, + codeVerifier, + redirectURI, + loginHint, + prompt: options.prompt + }); + }, + validateAuthorizationCode: async ({ code, codeVerifier, redirectURI }) => { + const { body, headers: requestHeaders } = createAuthorizationCodeRequest({ + code, + codeVerifier, + redirectURI, + options + }); + const { data: data2, error: error50 } = await betterFetch(tokenEndpoint, { + method: "POST", + body, + headers: requestHeaders + }); + if (error50) { + logger3.error("GitHub OAuth token exchange failed:", error50); + return null; + } + if ("error" in data2) { + logger3.error("GitHub OAuth token exchange failed:", data2); + return null; + } + return getOAuth2Tokens(data2); + }, + refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { + return refreshAccessToken({ + refreshToken: refreshToken2, + options: { + clientId: options.clientId, + clientKey: options.clientKey, + clientSecret: options.clientSecret + }, + tokenEndpoint: "https://github.com/login/oauth/access_token" + }); + }, + async getUserInfo(token) { + if (options.getUserInfo) return options.getUserInfo(token); + const { data: profile, error: error50 } = await betterFetch("https://api.github.com/user", { headers: { + "User-Agent": "better-auth", + authorization: `Bearer ${token.accessToken}` + } }); + if (error50) return null; + const { data: emails } = await betterFetch("https://api.github.com/user/emails", { headers: { + Authorization: `Bearer ${token.accessToken}`, + "User-Agent": "better-auth" + } }); + if (!profile.email && emails) profile.email = (emails.find((e5) => e5.primary) ?? emails[0])?.email; + const emailVerified = emails?.find((e5) => e5.email === profile.email)?.verified ?? false; + const userMap = await options.mapProfileToUser?.(profile); + return { + user: { + id: profile.id, + name: profile.name || profile.login, + email: profile.email, + image: profile.avatar_url, + emailVerified, + ...userMap + }, + data: profile + }; + }, + options + }; + }; + } +}); + +// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/gitlab.mjs +var cleanDoubleSlashes, issuerToEndpoints, gitlab; +var init_gitlab = __esm({ + "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/gitlab.mjs"() { + init_create_authorization_url(); + init_refresh_access_token(); + init_validate_authorization_code(); + init_oauth2(); + init_dist4(); + cleanDoubleSlashes = (input = "") => { + return input.split("://").map((str) => str.replace(/\/{2,}/g, "/")).join("://"); + }; + issuerToEndpoints = (issuer) => { + const baseUrl = issuer || "https://gitlab.com"; + return { + authorizationEndpoint: cleanDoubleSlashes(`${baseUrl}/oauth/authorize`), + tokenEndpoint: cleanDoubleSlashes(`${baseUrl}/oauth/token`), + userinfoEndpoint: cleanDoubleSlashes(`${baseUrl}/api/v4/user`) + }; + }; + gitlab = (options) => { + const { authorizationEndpoint, tokenEndpoint, userinfoEndpoint } = issuerToEndpoints(options.issuer); + const issuerId = "gitlab"; + return { + id: issuerId, + name: "Gitlab", + createAuthorizationURL: async ({ state: state2, scopes, codeVerifier, loginHint, redirectURI }) => { + const _scopes = options.disableDefaultScope ? [] : ["read_user"]; + if (options.scope) _scopes.push(...options.scope); + if (scopes) _scopes.push(...scopes); + return await createAuthorizationURL({ + id: issuerId, + options, + authorizationEndpoint, + scopes: _scopes, + state: state2, + redirectURI, + codeVerifier, + loginHint + }); + }, + validateAuthorizationCode: async ({ code, redirectURI, codeVerifier }) => { + return validateAuthorizationCode({ + code, + redirectURI, + options, + codeVerifier, + tokenEndpoint + }); + }, + refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { + return refreshAccessToken({ + refreshToken: refreshToken2, + options: { + clientId: options.clientId, + clientKey: options.clientKey, + clientSecret: options.clientSecret + }, + tokenEndpoint + }); + }, + async getUserInfo(token) { + if (options.getUserInfo) return options.getUserInfo(token); + const { data: profile, error: error50 } = await betterFetch(userinfoEndpoint, { headers: { authorization: `Bearer ${token.accessToken}` } }); + if (error50 || profile.state !== "active" || profile.locked) return null; + const userMap = await options.mapProfileToUser?.(profile); + return { + user: { + id: profile.id, + name: profile.name ?? profile.username, + email: profile.email, + image: profile.avatar_url, + emailVerified: profile.email_verified ?? false, + ...userMap + }, + data: profile + }; + }, + options + }; + }; + } +}); + +// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/google.mjs +var google, getGooglePublicKey; +var init_google = __esm({ + "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/google.mjs"() { + init_logger2(); + init_env(); + init_error(); + init_create_authorization_url(); + init_refresh_access_token(); + init_validate_authorization_code(); + init_oauth2(); + init_dist4(); + init_webapi(); + init_dist3(); + google = (options) => { + return { + id: "google", + name: "Google", + async createAuthorizationURL({ state: state2, scopes, codeVerifier, redirectURI, loginHint, display }) { + if (!options.clientId || !options.clientSecret) { + logger3.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."); + throw new BetterAuthError("CLIENT_ID_AND_SECRET_REQUIRED"); + } + if (!codeVerifier) throw new BetterAuthError("codeVerifier is required for Google"); + const _scopes = options.disableDefaultScope ? [] : [ + "email", + "profile", + "openid" + ]; + if (options.scope) _scopes.push(...options.scope); + if (scopes) _scopes.push(...scopes); + return await createAuthorizationURL({ + id: "google", + options, + authorizationEndpoint: "https://accounts.google.com/o/oauth2/v2/auth", + scopes: _scopes, + state: state2, + codeVerifier, + redirectURI, + prompt: options.prompt, + accessType: options.accessType, + display: display || options.display, + loginHint, + hd: options.hd, + additionalParams: { include_granted_scopes: "true" } + }); + }, + validateAuthorizationCode: async ({ code, codeVerifier, redirectURI }) => { + return validateAuthorizationCode({ + code, + codeVerifier, + redirectURI, + options, + tokenEndpoint: "https://oauth2.googleapis.com/token" + }); + }, + refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { + return refreshAccessToken({ + refreshToken: refreshToken2, + options: { + clientId: options.clientId, + clientKey: options.clientKey, + clientSecret: options.clientSecret + }, + tokenEndpoint: "https://oauth2.googleapis.com/token" + }); + }, + async verifyIdToken(token, nonce) { + if (options.disableIdTokenSignIn) return false; + if (options.verifyIdToken) return options.verifyIdToken(token, nonce); + const { kid, alg: jwtAlg } = decodeProtectedHeader(token); + if (!kid || !jwtAlg) return false; + const { payload: jwtClaims } = await jwtVerify(token, await getGooglePublicKey(kid), { + algorithms: [jwtAlg], + issuer: ["https://accounts.google.com", "accounts.google.com"], + audience: options.clientId, + maxTokenAge: "1h" + }); + if (nonce && jwtClaims.nonce !== nonce) return false; + return true; + }, + async getUserInfo(token) { + if (options.getUserInfo) return options.getUserInfo(token); + if (!token.idToken) return null; + const user = decodeJwt(token.idToken); + const userMap = await options.mapProfileToUser?.(user); + return { + user: { + id: user.sub, + name: user.name, + email: user.email, + image: user.picture, + emailVerified: user.email_verified, + ...userMap + }, + data: user + }; + }, + options + }; + }; + getGooglePublicKey = async (kid) => { + const { data: data2 } = await betterFetch("https://www.googleapis.com/oauth2/v3/certs"); + if (!data2?.keys) throw new APIError("BAD_REQUEST", { message: "Keys not found" }); + const jwk = data2.keys.find((key) => key.kid === kid); + if (!jwk) throw new Error(`JWK with kid ${kid} not found`); + return await importJWK(jwk, jwk.alg); + }; + } +}); + +// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/huggingface.mjs +var huggingface; +var init_huggingface = __esm({ + "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/huggingface.mjs"() { + init_create_authorization_url(); + init_refresh_access_token(); + init_validate_authorization_code(); + init_oauth2(); + init_dist4(); + huggingface = (options) => { + return { + id: "huggingface", + name: "Hugging Face", + createAuthorizationURL({ state: state2, scopes, codeVerifier, redirectURI }) { + const _scopes = options.disableDefaultScope ? [] : [ + "openid", + "profile", + "email" + ]; + if (options.scope) _scopes.push(...options.scope); + if (scopes) _scopes.push(...scopes); + return createAuthorizationURL({ + id: "huggingface", + options, + authorizationEndpoint: "https://huggingface.co/oauth/authorize", + scopes: _scopes, + state: state2, + codeVerifier, + redirectURI + }); + }, + validateAuthorizationCode: async ({ code, codeVerifier, redirectURI }) => { + return validateAuthorizationCode({ + code, + codeVerifier, + redirectURI, + options, + tokenEndpoint: "https://huggingface.co/oauth/token" + }); + }, + refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { + return refreshAccessToken({ + refreshToken: refreshToken2, + options: { + clientId: options.clientId, + clientKey: options.clientKey, + clientSecret: options.clientSecret + }, + tokenEndpoint: "https://huggingface.co/oauth/token" + }); + }, + async getUserInfo(token) { + if (options.getUserInfo) return options.getUserInfo(token); + const { data: profile, error: error50 } = await betterFetch("https://huggingface.co/oauth/userinfo", { + method: "GET", + headers: { Authorization: `Bearer ${token.accessToken}` } + }); + if (error50) return null; + const userMap = await options.mapProfileToUser?.(profile); + return { + user: { + id: profile.sub, + name: profile.name || profile.preferred_username, + email: profile.email, + image: profile.picture, + emailVerified: profile.email_verified ?? false, + ...userMap + }, + data: profile + }; + }, + options + }; + }; + } +}); + +// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/kakao.mjs +var kakao; +var init_kakao = __esm({ + "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/kakao.mjs"() { + init_create_authorization_url(); + init_refresh_access_token(); + init_validate_authorization_code(); + init_oauth2(); + init_dist4(); + kakao = (options) => { + return { + id: "kakao", + name: "Kakao", + createAuthorizationURL({ state: state2, scopes, redirectURI }) { + const _scopes = options.disableDefaultScope ? [] : [ + "account_email", + "profile_image", + "profile_nickname" + ]; + if (options.scope) _scopes.push(...options.scope); + if (scopes) _scopes.push(...scopes); + return createAuthorizationURL({ + id: "kakao", + options, + authorizationEndpoint: "https://kauth.kakao.com/oauth/authorize", + scopes: _scopes, + state: state2, + redirectURI + }); + }, + validateAuthorizationCode: async ({ code, redirectURI }) => { + return validateAuthorizationCode({ + code, + redirectURI, + options, + tokenEndpoint: "https://kauth.kakao.com/oauth/token" + }); + }, + refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { + return refreshAccessToken({ + refreshToken: refreshToken2, + options: { + clientId: options.clientId, + clientKey: options.clientKey, + clientSecret: options.clientSecret + }, + tokenEndpoint: "https://kauth.kakao.com/oauth/token" + }); + }, + async getUserInfo(token) { + if (options.getUserInfo) return options.getUserInfo(token); + const { data: profile, error: error50 } = await betterFetch("https://kapi.kakao.com/v2/user/me", { headers: { Authorization: `Bearer ${token.accessToken}` } }); + if (error50 || !profile) return null; + const userMap = await options.mapProfileToUser?.(profile); + const account = profile.kakao_account || {}; + const kakaoProfile = account.profile || {}; + return { + user: { + id: String(profile.id), + name: kakaoProfile.nickname || account.name || void 0, + email: account.email, + image: kakaoProfile.profile_image_url || kakaoProfile.thumbnail_image_url, + emailVerified: !!account.is_email_valid && !!account.is_email_verified, + ...userMap + }, + data: profile + }; + }, + options + }; + }; + } +}); + +// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/kick.mjs +var kick; +var init_kick = __esm({ + "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/kick.mjs"() { + init_create_authorization_url(); + init_refresh_access_token(); + init_validate_authorization_code(); + init_oauth2(); + init_dist4(); + kick = (options) => { + return { + id: "kick", + name: "Kick", + createAuthorizationURL({ state: state2, scopes, redirectURI, codeVerifier }) { + const _scopes = options.disableDefaultScope ? [] : ["user:read"]; + if (options.scope) _scopes.push(...options.scope); + if (scopes) _scopes.push(...scopes); + return createAuthorizationURL({ + id: "kick", + redirectURI, + options, + authorizationEndpoint: "https://id.kick.com/oauth/authorize", + scopes: _scopes, + codeVerifier, + state: state2 + }); + }, + async validateAuthorizationCode({ code, redirectURI, codeVerifier }) { + return validateAuthorizationCode({ + code, + redirectURI, + options, + tokenEndpoint: "https://id.kick.com/oauth/token", + codeVerifier + }); + }, + refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { + return refreshAccessToken({ + refreshToken: refreshToken2, + options: { + clientId: options.clientId, + clientSecret: options.clientSecret + }, + tokenEndpoint: "https://id.kick.com/oauth/token" + }); + }, + async getUserInfo(token) { + if (options.getUserInfo) return options.getUserInfo(token); + const { data: data2, error: error50 } = await betterFetch("https://api.kick.com/public/v1/users", { + method: "GET", + headers: { Authorization: `Bearer ${token.accessToken}` } + }); + if (error50) return null; + const profile = data2.data[0]; + const userMap = await options.mapProfileToUser?.(profile); + return { + user: { + id: profile.user_id, + name: profile.name, + email: profile.email, + image: profile.profile_picture, + emailVerified: false, + ...userMap + }, + data: profile + }; + }, + options + }; + }; + } +}); + +// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/line.mjs +var line2; +var init_line2 = __esm({ + "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/line.mjs"() { + init_create_authorization_url(); + init_refresh_access_token(); + init_validate_authorization_code(); + init_oauth2(); + init_dist4(); + init_webapi(); + line2 = (options) => { + const authorizationEndpoint = "https://access.line.me/oauth2/v2.1/authorize"; + const tokenEndpoint = "https://api.line.me/oauth2/v2.1/token"; + const userInfoEndpoint = "https://api.line.me/oauth2/v2.1/userinfo"; + const verifyIdTokenEndpoint = "https://api.line.me/oauth2/v2.1/verify"; + return { + id: "line", + name: "LINE", + async createAuthorizationURL({ state: state2, scopes, codeVerifier, redirectURI, loginHint }) { + const _scopes = options.disableDefaultScope ? [] : [ + "openid", + "profile", + "email" + ]; + if (options.scope) _scopes.push(...options.scope); + if (scopes) _scopes.push(...scopes); + return await createAuthorizationURL({ + id: "line", + options, + authorizationEndpoint, + scopes: _scopes, + state: state2, + codeVerifier, + redirectURI, + loginHint + }); + }, + validateAuthorizationCode: async ({ code, codeVerifier, redirectURI }) => { + return validateAuthorizationCode({ + code, + codeVerifier, + redirectURI, + options, + tokenEndpoint + }); + }, + refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { + return refreshAccessToken({ + refreshToken: refreshToken2, + options: { + clientId: options.clientId, + clientSecret: options.clientSecret + }, + tokenEndpoint + }); + }, + async verifyIdToken(token, nonce) { + if (options.disableIdTokenSignIn) return false; + if (options.verifyIdToken) return options.verifyIdToken(token, nonce); + const body = new URLSearchParams(); + body.set("id_token", token); + body.set("client_id", options.clientId); + if (nonce) body.set("nonce", nonce); + const { data: data2, error: error50 } = await betterFetch(verifyIdTokenEndpoint, { + method: "POST", + headers: { "content-type": "application/x-www-form-urlencoded" }, + body + }); + if (error50 || !data2) return false; + if (data2.aud !== options.clientId) return false; + if (data2.nonce && data2.nonce !== nonce) return false; + return true; + }, + async getUserInfo(token) { + if (options.getUserInfo) return options.getUserInfo(token); + let profile = null; + if (token.idToken) try { + profile = decodeJwt(token.idToken); + } catch { + } + if (!profile) { + const { data: data2 } = await betterFetch(userInfoEndpoint, { headers: { authorization: `Bearer ${token.accessToken}` } }); + profile = data2 || null; + } + if (!profile) return null; + const userMap = await options.mapProfileToUser?.(profile); + const id = profile.sub || profile.userId; + const name = profile.name || profile.displayName; + const image = profile.picture || profile.pictureUrl || void 0; + return { + user: { + id, + name, + email: profile.email, + image, + emailVerified: false, + ...userMap + }, + data: profile + }; + }, + options + }; + }; + } +}); + +// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/linear.mjs +var linear; +var init_linear = __esm({ + "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/linear.mjs"() { + init_create_authorization_url(); + init_refresh_access_token(); + init_validate_authorization_code(); + init_oauth2(); + init_dist4(); + linear = (options) => { + const tokenEndpoint = "https://api.linear.app/oauth/token"; + return { + id: "linear", + name: "Linear", + createAuthorizationURL({ state: state2, scopes, loginHint, redirectURI }) { + const _scopes = options.disableDefaultScope ? [] : ["read"]; + if (options.scope) _scopes.push(...options.scope); + if (scopes) _scopes.push(...scopes); + return createAuthorizationURL({ + id: "linear", + options, + authorizationEndpoint: "https://linear.app/oauth/authorize", + scopes: _scopes, + state: state2, + redirectURI, + loginHint + }); + }, + validateAuthorizationCode: async ({ code, redirectURI }) => { + return validateAuthorizationCode({ + code, + redirectURI, + options, + tokenEndpoint + }); + }, + refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { + return refreshAccessToken({ + refreshToken: refreshToken2, + options: { + clientId: options.clientId, + clientKey: options.clientKey, + clientSecret: options.clientSecret + }, + tokenEndpoint + }); + }, + async getUserInfo(token) { + if (options.getUserInfo) return options.getUserInfo(token); + const { data: profile, error: error50 } = await betterFetch("https://api.linear.app/graphql", { + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: `Bearer ${token.accessToken}` + }, + body: JSON.stringify({ query: ` + query { + viewer { + id + name + email + avatarUrl + active + createdAt + updatedAt + } + } + ` }) + }); + if (error50 || !profile?.data?.viewer) return null; + const userData = profile.data.viewer; + const userMap = await options.mapProfileToUser?.(userData); + return { + user: { + id: profile.data.viewer.id, + name: profile.data.viewer.name, + email: profile.data.viewer.email, + image: profile.data.viewer.avatarUrl, + emailVerified: false, + ...userMap + }, + data: userData + }; + }, + options + }; + }; + } +}); + +// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/linkedin.mjs +var linkedin; +var init_linkedin = __esm({ + "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/linkedin.mjs"() { + init_create_authorization_url(); + init_refresh_access_token(); + init_validate_authorization_code(); + init_oauth2(); + init_dist4(); + linkedin = (options) => { + const authorizationEndpoint = "https://www.linkedin.com/oauth/v2/authorization"; + const tokenEndpoint = "https://www.linkedin.com/oauth/v2/accessToken"; + return { + id: "linkedin", + name: "Linkedin", + createAuthorizationURL: async ({ state: state2, scopes, redirectURI, loginHint }) => { + const _scopes = options.disableDefaultScope ? [] : [ + "profile", + "email", + "openid" + ]; + if (options.scope) _scopes.push(...options.scope); + if (scopes) _scopes.push(...scopes); + return await createAuthorizationURL({ + id: "linkedin", + options, + authorizationEndpoint, + scopes: _scopes, + state: state2, + loginHint, + redirectURI + }); + }, + validateAuthorizationCode: async ({ code, redirectURI }) => { + return await validateAuthorizationCode({ + code, + redirectURI, + options, + tokenEndpoint + }); + }, + refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { + return refreshAccessToken({ + refreshToken: refreshToken2, + options: { + clientId: options.clientId, + clientKey: options.clientKey, + clientSecret: options.clientSecret + }, + tokenEndpoint + }); + }, + async getUserInfo(token) { + if (options.getUserInfo) return options.getUserInfo(token); + const { data: profile, error: error50 } = await betterFetch("https://api.linkedin.com/v2/userinfo", { + method: "GET", + headers: { Authorization: `Bearer ${token.accessToken}` } + }); + if (error50) return null; + const userMap = await options.mapProfileToUser?.(profile); + return { + user: { + id: profile.sub, + name: profile.name, + email: profile.email, + emailVerified: profile.email_verified || false, + image: profile.picture, + ...userMap + }, + data: profile + }; + }, + options + }; + }; + } +}); + +// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/microsoft-entra-id.mjs +var microsoft; +var init_microsoft_entra_id = __esm({ + "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/microsoft-entra-id.mjs"() { + init_logger2(); + init_env(); + init_create_authorization_url(); + init_refresh_access_token(); + init_validate_authorization_code(); + init_oauth2(); + init_base642(); + init_dist4(); + init_webapi(); + microsoft = (options) => { + const tenant = options.tenantId || "common"; + const authority = options.authority || "https://login.microsoftonline.com"; + const authorizationEndpoint = `${authority}/${tenant}/oauth2/v2.0/authorize`; + const tokenEndpoint = `${authority}/${tenant}/oauth2/v2.0/token`; + return { + id: "microsoft", + name: "Microsoft EntraID", + createAuthorizationURL(data2) { + const scopes = options.disableDefaultScope ? [] : [ + "openid", + "profile", + "email", + "User.Read", + "offline_access" + ]; + if (options.scope) scopes.push(...options.scope); + if (data2.scopes) scopes.push(...data2.scopes); + return createAuthorizationURL({ + id: "microsoft", + options, + authorizationEndpoint, + state: data2.state, + codeVerifier: data2.codeVerifier, + scopes, + redirectURI: data2.redirectURI, + prompt: options.prompt, + loginHint: data2.loginHint + }); + }, + validateAuthorizationCode({ code, codeVerifier, redirectURI }) { + return validateAuthorizationCode({ + code, + codeVerifier, + redirectURI, + options, + tokenEndpoint + }); + }, + async getUserInfo(token) { + if (options.getUserInfo) return options.getUserInfo(token); + if (!token.idToken) return null; + const user = decodeJwt(token.idToken); + const profilePhotoSize = options.profilePhotoSize || 48; + await betterFetch(`https://graph.microsoft.com/v1.0/me/photos/${profilePhotoSize}x${profilePhotoSize}/$value`, { + headers: { Authorization: `Bearer ${token.accessToken}` }, + async onResponse(context) { + if (options.disableProfilePhoto || !context.response.ok) return; + try { + const pictureBuffer = await context.response.clone().arrayBuffer(); + user.picture = `data:image/jpeg;base64, ${base643.encode(pictureBuffer)}`; + } catch (e5) { + logger3.error(e5 && typeof e5 === "object" && "name" in e5 ? e5.name : "", e5); + } + } + }); + const userMap = await options.mapProfileToUser?.(user); + const emailVerified = user.email_verified !== void 0 ? user.email_verified : user.email && (user.verified_primary_email?.includes(user.email) || user.verified_secondary_email?.includes(user.email)) ? true : false; + return { + user: { + id: user.sub, + name: user.name, + email: user.email, + image: user.picture, + emailVerified, + ...userMap + }, + data: user + }; + }, + refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { + const scopes = options.disableDefaultScope ? [] : [ + "openid", + "profile", + "email", + "User.Read", + "offline_access" + ]; + if (options.scope) scopes.push(...options.scope); + return refreshAccessToken({ + refreshToken: refreshToken2, + options: { + clientId: options.clientId, + clientSecret: options.clientSecret + }, + extraParams: { scope: scopes.join(" ") }, + tokenEndpoint + }); + }, + options + }; + }; + } +}); + +// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/naver.mjs +var naver; +var init_naver = __esm({ + "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/naver.mjs"() { + init_create_authorization_url(); + init_refresh_access_token(); + init_validate_authorization_code(); + init_oauth2(); + init_dist4(); + naver = (options) => { + return { + id: "naver", + name: "Naver", + createAuthorizationURL({ state: state2, scopes, redirectURI }) { + const _scopes = options.disableDefaultScope ? [] : ["profile", "email"]; + if (options.scope) _scopes.push(...options.scope); + if (scopes) _scopes.push(...scopes); + return createAuthorizationURL({ + id: "naver", + options, + authorizationEndpoint: "https://nid.naver.com/oauth2.0/authorize", + scopes: _scopes, + state: state2, + redirectURI + }); + }, + validateAuthorizationCode: async ({ code, redirectURI }) => { + return validateAuthorizationCode({ + code, + redirectURI, + options, + tokenEndpoint: "https://nid.naver.com/oauth2.0/token" + }); + }, + refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { + return refreshAccessToken({ + refreshToken: refreshToken2, + options: { + clientId: options.clientId, + clientKey: options.clientKey, + clientSecret: options.clientSecret + }, + tokenEndpoint: "https://nid.naver.com/oauth2.0/token" + }); + }, + async getUserInfo(token) { + if (options.getUserInfo) return options.getUserInfo(token); + const { data: profile, error: error50 } = await betterFetch("https://openapi.naver.com/v1/nid/me", { headers: { Authorization: `Bearer ${token.accessToken}` } }); + if (error50 || !profile || profile.resultcode !== "00") return null; + const userMap = await options.mapProfileToUser?.(profile); + const res = profile.response || {}; + return { + user: { + id: res.id, + name: res.name || res.nickname, + email: res.email, + image: res.profile_image, + emailVerified: false, + ...userMap + }, + data: profile + }; + }, + options + }; + }; + } +}); + +// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/notion.mjs +var notion; +var init_notion = __esm({ + "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/notion.mjs"() { + init_create_authorization_url(); + init_refresh_access_token(); + init_validate_authorization_code(); + init_oauth2(); + init_dist4(); + notion = (options) => { + const tokenEndpoint = "https://api.notion.com/v1/oauth/token"; + return { + id: "notion", + name: "Notion", + createAuthorizationURL({ state: state2, scopes, loginHint, redirectURI }) { + const _scopes = options.disableDefaultScope ? [] : []; + if (options.scope) _scopes.push(...options.scope); + if (scopes) _scopes.push(...scopes); + return createAuthorizationURL({ + id: "notion", + options, + authorizationEndpoint: "https://api.notion.com/v1/oauth/authorize", + scopes: _scopes, + state: state2, + redirectURI, + loginHint, + additionalParams: { owner: "user" } + }); + }, + validateAuthorizationCode: async ({ code, redirectURI }) => { + return validateAuthorizationCode({ + code, + redirectURI, + options, + tokenEndpoint, + authentication: "basic" + }); + }, + refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { + return refreshAccessToken({ + refreshToken: refreshToken2, + options: { + clientId: options.clientId, + clientKey: options.clientKey, + clientSecret: options.clientSecret + }, + tokenEndpoint + }); + }, + async getUserInfo(token) { + if (options.getUserInfo) return options.getUserInfo(token); + const { data: profile, error: error50 } = await betterFetch("https://api.notion.com/v1/users/me", { headers: { + Authorization: `Bearer ${token.accessToken}`, + "Notion-Version": "2022-06-28" + } }); + if (error50 || !profile) return null; + const userProfile = profile.bot?.owner?.user; + if (!userProfile) return null; + const userMap = await options.mapProfileToUser?.(userProfile); + return { + user: { + id: userProfile.id, + name: userProfile.name || "Notion User", + email: userProfile.person?.email || null, + image: userProfile.avatar_url, + emailVerified: false, + ...userMap + }, + data: userProfile + }; + }, + options + }; + }; + } +}); + +// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/paybin.mjs +var paybin; +var init_paybin = __esm({ + "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/paybin.mjs"() { + init_logger2(); + init_env(); + init_error(); + init_create_authorization_url(); + init_refresh_access_token(); + init_validate_authorization_code(); + init_oauth2(); + init_webapi(); + paybin = (options) => { + const issuer = options.issuer || "https://idp.paybin.io"; + const authorizationEndpoint = `${issuer}/oauth2/authorize`; + const tokenEndpoint = `${issuer}/oauth2/token`; + return { + id: "paybin", + name: "Paybin", + async createAuthorizationURL({ state: state2, scopes, codeVerifier, redirectURI, loginHint }) { + if (!options.clientId || !options.clientSecret) { + logger3.error("Client Id and Client Secret is required for Paybin. Make sure to provide them in the options."); + throw new BetterAuthError("CLIENT_ID_AND_SECRET_REQUIRED"); + } + if (!codeVerifier) throw new BetterAuthError("codeVerifier is required for Paybin"); + const _scopes = options.disableDefaultScope ? [] : [ + "openid", + "email", + "profile" + ]; + if (options.scope) _scopes.push(...options.scope); + if (scopes) _scopes.push(...scopes); + return await createAuthorizationURL({ + id: "paybin", + options, + authorizationEndpoint, + scopes: _scopes, + state: state2, + codeVerifier, + redirectURI, + prompt: options.prompt, + loginHint + }); + }, + validateAuthorizationCode: async ({ code, codeVerifier, redirectURI }) => { + return validateAuthorizationCode({ + code, + codeVerifier, + redirectURI, + options, + tokenEndpoint + }); + }, + refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { + return refreshAccessToken({ + refreshToken: refreshToken2, + options: { + clientId: options.clientId, + clientKey: options.clientKey, + clientSecret: options.clientSecret + }, + tokenEndpoint + }); + }, + async getUserInfo(token) { + if (options.getUserInfo) return options.getUserInfo(token); + if (!token.idToken) return null; + const user = decodeJwt(token.idToken); + const userMap = await options.mapProfileToUser?.(user); + return { + user: { + id: user.sub, + name: user.name || user.preferred_username || (user.email ? user.email.split("@")[0] : "User") || "User", + email: user.email, + image: user.picture, + emailVerified: user.email_verified || false, + ...userMap + }, + data: user + }; + }, + options + }; + }; + } +}); + +// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/paypal.mjs +var paypal; +var init_paypal = __esm({ + "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/paypal.mjs"() { + init_logger2(); + init_env(); + init_error(); + init_create_authorization_url(); + init_oauth2(); + init_base642(); + init_dist4(); + init_webapi(); + paypal = (options) => { + const isSandbox = (options.environment || "sandbox") === "sandbox"; + const authorizationEndpoint = isSandbox ? "https://www.sandbox.paypal.com/signin/authorize" : "https://www.paypal.com/signin/authorize"; + const tokenEndpoint = isSandbox ? "https://api-m.sandbox.paypal.com/v1/oauth2/token" : "https://api-m.paypal.com/v1/oauth2/token"; + const userInfoEndpoint = isSandbox ? "https://api-m.sandbox.paypal.com/v1/identity/oauth2/userinfo" : "https://api-m.paypal.com/v1/identity/oauth2/userinfo"; + return { + id: "paypal", + name: "PayPal", + async createAuthorizationURL({ state: state2, codeVerifier, redirectURI }) { + if (!options.clientId || !options.clientSecret) { + logger3.error("Client Id and Client Secret is required for PayPal. Make sure to provide them in the options."); + throw new BetterAuthError("CLIENT_ID_AND_SECRET_REQUIRED"); + } + return await createAuthorizationURL({ + id: "paypal", + options, + authorizationEndpoint, + scopes: [], + state: state2, + codeVerifier, + redirectURI, + prompt: options.prompt + }); + }, + validateAuthorizationCode: async ({ code, redirectURI }) => { + const credentials = base643.encode(`${options.clientId}:${options.clientSecret}`); + try { + const response = await betterFetch(tokenEndpoint, { + method: "POST", + headers: { + Authorization: `Basic ${credentials}`, + Accept: "application/json", + "Accept-Language": "en_US", + "Content-Type": "application/x-www-form-urlencoded" + }, + body: new URLSearchParams({ + grant_type: "authorization_code", + code, + redirect_uri: redirectURI + }).toString() + }); + if (!response.data) throw new BetterAuthError("FAILED_TO_GET_ACCESS_TOKEN"); + const data2 = response.data; + return { + accessToken: data2.access_token, + refreshToken: data2.refresh_token, + accessTokenExpiresAt: data2.expires_in ? new Date(Date.now() + data2.expires_in * 1e3) : void 0, + idToken: data2.id_token + }; + } catch (error50) { + logger3.error("PayPal token exchange failed:", error50); + throw new BetterAuthError("FAILED_TO_GET_ACCESS_TOKEN"); + } + }, + refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { + const credentials = base643.encode(`${options.clientId}:${options.clientSecret}`); + try { + const response = await betterFetch(tokenEndpoint, { + method: "POST", + headers: { + Authorization: `Basic ${credentials}`, + Accept: "application/json", + "Accept-Language": "en_US", + "Content-Type": "application/x-www-form-urlencoded" + }, + body: new URLSearchParams({ + grant_type: "refresh_token", + refresh_token: refreshToken2 + }).toString() + }); + if (!response.data) throw new BetterAuthError("FAILED_TO_REFRESH_ACCESS_TOKEN"); + const data2 = response.data; + return { + accessToken: data2.access_token, + refreshToken: data2.refresh_token, + accessTokenExpiresAt: data2.expires_in ? new Date(Date.now() + data2.expires_in * 1e3) : void 0 + }; + } catch (error50) { + logger3.error("PayPal token refresh failed:", error50); + throw new BetterAuthError("FAILED_TO_REFRESH_ACCESS_TOKEN"); + } + }, + async verifyIdToken(token, nonce) { + if (options.disableIdTokenSignIn) return false; + if (options.verifyIdToken) return options.verifyIdToken(token, nonce); + try { + return !!decodeJwt(token).sub; + } catch (error50) { + logger3.error("Failed to verify PayPal ID token:", error50); + return false; + } + }, + async getUserInfo(token) { + if (options.getUserInfo) return options.getUserInfo(token); + if (!token.accessToken) { + logger3.error("Access token is required to fetch PayPal user info"); + return null; + } + try { + const response = await betterFetch(`${userInfoEndpoint}?schema=paypalv1.1`, { headers: { + Authorization: `Bearer ${token.accessToken}`, + Accept: "application/json" + } }); + if (!response.data) { + logger3.error("Failed to fetch user info from PayPal"); + return null; + } + const userInfo = response.data; + const userMap = await options.mapProfileToUser?.(userInfo); + return { + user: { + id: userInfo.user_id, + name: userInfo.name, + email: userInfo.email, + image: userInfo.picture, + emailVerified: userInfo.email_verified, + ...userMap + }, + data: userInfo + }; + } catch (error50) { + logger3.error("Failed to fetch user info from PayPal:", error50); + return null; + } + }, + options + }; + }; + } +}); + +// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/polar.mjs +var polar; +var init_polar = __esm({ + "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/polar.mjs"() { + init_create_authorization_url(); + init_refresh_access_token(); + init_validate_authorization_code(); + init_oauth2(); + init_dist4(); + polar = (options) => { + return { + id: "polar", + name: "Polar", + createAuthorizationURL({ state: state2, scopes, codeVerifier, redirectURI }) { + const _scopes = options.disableDefaultScope ? [] : [ + "openid", + "profile", + "email" + ]; + if (options.scope) _scopes.push(...options.scope); + if (scopes) _scopes.push(...scopes); + return createAuthorizationURL({ + id: "polar", + options, + authorizationEndpoint: "https://polar.sh/oauth2/authorize", + scopes: _scopes, + state: state2, + codeVerifier, + redirectURI, + prompt: options.prompt + }); + }, + validateAuthorizationCode: async ({ code, codeVerifier, redirectURI }) => { + return validateAuthorizationCode({ + code, + codeVerifier, + redirectURI, + options, + tokenEndpoint: "https://api.polar.sh/v1/oauth2/token" + }); + }, + refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { + return refreshAccessToken({ + refreshToken: refreshToken2, + options: { + clientId: options.clientId, + clientKey: options.clientKey, + clientSecret: options.clientSecret + }, + tokenEndpoint: "https://api.polar.sh/v1/oauth2/token" + }); + }, + async getUserInfo(token) { + if (options.getUserInfo) return options.getUserInfo(token); + const { data: profile, error: error50 } = await betterFetch("https://api.polar.sh/v1/oauth2/userinfo", { headers: { Authorization: `Bearer ${token.accessToken}` } }); + if (error50) return null; + const userMap = await options.mapProfileToUser?.(profile); + return { + user: { + id: profile.id, + name: profile.public_name || profile.username, + email: profile.email, + image: profile.avatar_url, + emailVerified: profile.email_verified ?? false, + ...userMap + }, + data: profile + }; + }, + options + }; + }; + } +}); + +// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/reddit.mjs +var reddit; +var init_reddit = __esm({ + "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/reddit.mjs"() { + init_utils13(); + init_create_authorization_url(); + init_refresh_access_token(); + init_oauth2(); + init_base642(); + init_dist4(); + reddit = (options) => { + return { + id: "reddit", + name: "Reddit", + createAuthorizationURL({ state: state2, scopes, redirectURI }) { + const _scopes = options.disableDefaultScope ? [] : ["identity"]; + if (options.scope) _scopes.push(...options.scope); + if (scopes) _scopes.push(...scopes); + return createAuthorizationURL({ + id: "reddit", + options, + authorizationEndpoint: "https://www.reddit.com/api/v1/authorize", + scopes: _scopes, + state: state2, + redirectURI, + duration: options.duration + }); + }, + validateAuthorizationCode: async ({ code, redirectURI }) => { + const body = new URLSearchParams({ + grant_type: "authorization_code", + code, + redirect_uri: options.redirectURI || redirectURI + }); + const { data: data2, error: error50 } = await betterFetch("https://www.reddit.com/api/v1/access_token", { + method: "POST", + headers: { + "content-type": "application/x-www-form-urlencoded", + accept: "text/plain", + "user-agent": "better-auth", + Authorization: `Basic ${base643.encode(`${options.clientId}:${options.clientSecret}`)}` + }, + body: body.toString() + }); + if (error50) throw error50; + return getOAuth2Tokens(data2); + }, + refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { + return refreshAccessToken({ + refreshToken: refreshToken2, + options: { + clientId: options.clientId, + clientKey: options.clientKey, + clientSecret: options.clientSecret + }, + authentication: "basic", + tokenEndpoint: "https://www.reddit.com/api/v1/access_token" + }); + }, + async getUserInfo(token) { + if (options.getUserInfo) return options.getUserInfo(token); + const { data: profile, error: error50 } = await betterFetch("https://oauth.reddit.com/api/v1/me", { headers: { + Authorization: `Bearer ${token.accessToken}`, + "User-Agent": "better-auth" + } }); + if (error50) return null; + const userMap = await options.mapProfileToUser?.(profile); + return { + user: { + id: profile.id, + name: profile.name, + email: profile.oauth_client_id, + emailVerified: profile.has_verified_email, + image: profile.icon_img?.split("?")[0], + ...userMap + }, + data: profile + }; + }, + options + }; + }; + } +}); + +// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/roblox.mjs +var roblox; +var init_roblox = __esm({ + "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/roblox.mjs"() { + init_refresh_access_token(); + init_validate_authorization_code(); + init_oauth2(); + init_dist4(); + roblox = (options) => { + return { + id: "roblox", + name: "Roblox", + createAuthorizationURL({ state: state2, scopes, redirectURI }) { + const _scopes = options.disableDefaultScope ? [] : ["openid", "profile"]; + if (options.scope) _scopes.push(...options.scope); + if (scopes) _scopes.push(...scopes); + return new URL(`https://apis.roblox.com/oauth/v1/authorize?scope=${_scopes.join("+")}&response_type=code&client_id=${options.clientId}&redirect_uri=${encodeURIComponent(options.redirectURI || redirectURI)}&state=${state2}&prompt=${options.prompt || "select_account consent"}`); + }, + validateAuthorizationCode: async ({ code, redirectURI }) => { + return validateAuthorizationCode({ + code, + redirectURI: options.redirectURI || redirectURI, + options, + tokenEndpoint: "https://apis.roblox.com/oauth/v1/token", + authentication: "post" + }); + }, + refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { + return refreshAccessToken({ + refreshToken: refreshToken2, + options: { + clientId: options.clientId, + clientKey: options.clientKey, + clientSecret: options.clientSecret + }, + tokenEndpoint: "https://apis.roblox.com/oauth/v1/token" + }); + }, + async getUserInfo(token) { + if (options.getUserInfo) return options.getUserInfo(token); + const { data: profile, error: error50 } = await betterFetch("https://apis.roblox.com/oauth/v1/userinfo", { headers: { authorization: `Bearer ${token.accessToken}` } }); + if (error50) return null; + const userMap = await options.mapProfileToUser?.(profile); + return { + user: { + id: profile.sub, + name: profile.nickname || profile.preferred_username || "", + image: profile.picture, + email: profile.preferred_username || null, + emailVerified: false, + ...userMap + }, + data: { ...profile } + }; + }, + options + }; + }; + } +}); + +// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/salesforce.mjs +var salesforce; +var init_salesforce = __esm({ + "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/salesforce.mjs"() { + init_logger2(); + init_env(); + init_error(); + init_create_authorization_url(); + init_refresh_access_token(); + init_validate_authorization_code(); + init_oauth2(); + init_dist4(); + salesforce = (options) => { + const isSandbox = (options.environment ?? "production") === "sandbox"; + const authorizationEndpoint = options.loginUrl ? `https://${options.loginUrl}/services/oauth2/authorize` : isSandbox ? "https://test.salesforce.com/services/oauth2/authorize" : "https://login.salesforce.com/services/oauth2/authorize"; + const tokenEndpoint = options.loginUrl ? `https://${options.loginUrl}/services/oauth2/token` : isSandbox ? "https://test.salesforce.com/services/oauth2/token" : "https://login.salesforce.com/services/oauth2/token"; + const userInfoEndpoint = options.loginUrl ? `https://${options.loginUrl}/services/oauth2/userinfo` : isSandbox ? "https://test.salesforce.com/services/oauth2/userinfo" : "https://login.salesforce.com/services/oauth2/userinfo"; + return { + id: "salesforce", + name: "Salesforce", + async createAuthorizationURL({ state: state2, scopes, codeVerifier, redirectURI }) { + if (!options.clientId || !options.clientSecret) { + logger3.error("Client Id and Client Secret are required for Salesforce. Make sure to provide them in the options."); + throw new BetterAuthError("CLIENT_ID_AND_SECRET_REQUIRED"); + } + if (!codeVerifier) throw new BetterAuthError("codeVerifier is required for Salesforce"); + const _scopes = options.disableDefaultScope ? [] : [ + "openid", + "email", + "profile" + ]; + if (options.scope) _scopes.push(...options.scope); + if (scopes) _scopes.push(...scopes); + return createAuthorizationURL({ + id: "salesforce", + options, + authorizationEndpoint, + scopes: _scopes, + state: state2, + codeVerifier, + redirectURI: options.redirectURI || redirectURI + }); + }, + validateAuthorizationCode: async ({ code, codeVerifier, redirectURI }) => { + return validateAuthorizationCode({ + code, + codeVerifier, + redirectURI: options.redirectURI || redirectURI, + options, + tokenEndpoint + }); + }, + refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { + return refreshAccessToken({ + refreshToken: refreshToken2, + options: { + clientId: options.clientId, + clientSecret: options.clientSecret + }, + tokenEndpoint + }); + }, + async getUserInfo(token) { + if (options.getUserInfo) return options.getUserInfo(token); + try { + const { data: user } = await betterFetch(userInfoEndpoint, { headers: { Authorization: `Bearer ${token.accessToken}` } }); + if (!user) { + logger3.error("Failed to fetch user info from Salesforce"); + return null; + } + const userMap = await options.mapProfileToUser?.(user); + return { + user: { + id: user.user_id, + name: user.name, + email: user.email, + image: user.photos?.picture || user.photos?.thumbnail, + emailVerified: user.email_verified ?? false, + ...userMap + }, + data: user + }; + } catch (error50) { + logger3.error("Failed to fetch user info from Salesforce:", error50); + return null; + } + }, + options + }; + }; + } +}); + +// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/slack.mjs +var slack; +var init_slack = __esm({ + "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/slack.mjs"() { + init_refresh_access_token(); + init_validate_authorization_code(); + init_oauth2(); + init_dist4(); + slack = (options) => { + return { + id: "slack", + name: "Slack", + createAuthorizationURL({ state: state2, scopes, redirectURI }) { + const _scopes = options.disableDefaultScope ? [] : [ + "openid", + "profile", + "email" + ]; + if (scopes) _scopes.push(...scopes); + if (options.scope) _scopes.push(...options.scope); + const url2 = new URL("https://slack.com/openid/connect/authorize"); + url2.searchParams.set("scope", _scopes.join(" ")); + url2.searchParams.set("response_type", "code"); + url2.searchParams.set("client_id", options.clientId); + url2.searchParams.set("redirect_uri", options.redirectURI || redirectURI); + url2.searchParams.set("state", state2); + return url2; + }, + validateAuthorizationCode: async ({ code, redirectURI }) => { + return validateAuthorizationCode({ + code, + redirectURI, + options, + tokenEndpoint: "https://slack.com/api/openid.connect.token" + }); + }, + refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { + return refreshAccessToken({ + refreshToken: refreshToken2, + options: { + clientId: options.clientId, + clientKey: options.clientKey, + clientSecret: options.clientSecret + }, + tokenEndpoint: "https://slack.com/api/openid.connect.token" + }); + }, + async getUserInfo(token) { + if (options.getUserInfo) return options.getUserInfo(token); + const { data: profile, error: error50 } = await betterFetch("https://slack.com/api/openid.connect.userInfo", { headers: { authorization: `Bearer ${token.accessToken}` } }); + if (error50) return null; + const userMap = await options.mapProfileToUser?.(profile); + return { + user: { + id: profile["https://slack.com/user_id"], + name: profile.name || "", + email: profile.email, + emailVerified: profile.email_verified, + image: profile.picture || profile["https://slack.com/user_image_512"], + ...userMap + }, + data: profile + }; + }, + options + }; + }; + } +}); + +// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/spotify.mjs +var spotify; +var init_spotify = __esm({ + "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/spotify.mjs"() { + init_create_authorization_url(); + init_refresh_access_token(); + init_validate_authorization_code(); + init_oauth2(); + init_dist4(); + spotify = (options) => { + return { + id: "spotify", + name: "Spotify", + createAuthorizationURL({ state: state2, scopes, codeVerifier, redirectURI }) { + const _scopes = options.disableDefaultScope ? [] : ["user-read-email"]; + if (options.scope) _scopes.push(...options.scope); + if (scopes) _scopes.push(...scopes); + return createAuthorizationURL({ + id: "spotify", + options, + authorizationEndpoint: "https://accounts.spotify.com/authorize", + scopes: _scopes, + state: state2, + codeVerifier, + redirectURI + }); + }, + validateAuthorizationCode: async ({ code, codeVerifier, redirectURI }) => { + return validateAuthorizationCode({ + code, + codeVerifier, + redirectURI, + options, + tokenEndpoint: "https://accounts.spotify.com/api/token" + }); + }, + refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { + return refreshAccessToken({ + refreshToken: refreshToken2, + options: { + clientId: options.clientId, + clientKey: options.clientKey, + clientSecret: options.clientSecret + }, + tokenEndpoint: "https://accounts.spotify.com/api/token" + }); + }, + async getUserInfo(token) { + if (options.getUserInfo) return options.getUserInfo(token); + const { data: profile, error: error50 } = await betterFetch("https://api.spotify.com/v1/me", { + method: "GET", + headers: { Authorization: `Bearer ${token.accessToken}` } + }); + if (error50) return null; + const userMap = await options.mapProfileToUser?.(profile); + return { + user: { + id: profile.id, + name: profile.display_name, + email: profile.email, + image: profile.images[0]?.url, + emailVerified: false, + ...userMap + }, + data: profile + }; + }, + options + }; + }; + } +}); + +// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/tiktok.mjs +var tiktok; +var init_tiktok = __esm({ + "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/tiktok.mjs"() { + init_refresh_access_token(); + init_validate_authorization_code(); + init_oauth2(); + init_dist4(); + tiktok = (options) => { + return { + id: "tiktok", + name: "TikTok", + createAuthorizationURL({ state: state2, scopes, redirectURI }) { + const _scopes = options.disableDefaultScope ? [] : ["user.info.profile"]; + if (options.scope) _scopes.push(...options.scope); + if (scopes) _scopes.push(...scopes); + return new URL(`https://www.tiktok.com/v2/auth/authorize?scope=${_scopes.join(",")}&response_type=code&client_key=${options.clientKey}&redirect_uri=${encodeURIComponent(options.redirectURI || redirectURI)}&state=${state2}`); + }, + validateAuthorizationCode: async ({ code, redirectURI }) => { + return validateAuthorizationCode({ + code, + redirectURI: options.redirectURI || redirectURI, + options: { + clientKey: options.clientKey, + clientSecret: options.clientSecret + }, + tokenEndpoint: "https://open.tiktokapis.com/v2/oauth/token/" + }); + }, + refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { + return refreshAccessToken({ + refreshToken: refreshToken2, + options: { clientSecret: options.clientSecret }, + tokenEndpoint: "https://open.tiktokapis.com/v2/oauth/token/", + authentication: "post", + extraParams: { client_key: options.clientKey } + }); + }, + async getUserInfo(token) { + if (options.getUserInfo) return options.getUserInfo(token); + const { data: profile, error: error50 } = await betterFetch(`https://open.tiktokapis.com/v2/user/info/?fields=${[ + "open_id", + "avatar_large_url", + "display_name", + "username" + ].join(",")}`, { headers: { authorization: `Bearer ${token.accessToken}` } }); + if (error50) return null; + return { + user: { + email: profile.data.user.email || profile.data.user.username, + id: profile.data.user.open_id, + name: profile.data.user.display_name || profile.data.user.username, + image: profile.data.user.avatar_large_url, + emailVerified: false + }, + data: profile + }; + }, + options + }; + }; + } +}); + +// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/twitch.mjs +var twitch; +var init_twitch = __esm({ + "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/twitch.mjs"() { + init_logger2(); + init_env(); + init_create_authorization_url(); + init_refresh_access_token(); + init_validate_authorization_code(); + init_oauth2(); + init_webapi(); + twitch = (options) => { + return { + id: "twitch", + name: "Twitch", + createAuthorizationURL({ state: state2, scopes, redirectURI }) { + const _scopes = options.disableDefaultScope ? [] : ["user:read:email", "openid"]; + if (options.scope) _scopes.push(...options.scope); + if (scopes) _scopes.push(...scopes); + return createAuthorizationURL({ + id: "twitch", + redirectURI, + options, + authorizationEndpoint: "https://id.twitch.tv/oauth2/authorize", + scopes: _scopes, + state: state2, + claims: options.claims || [ + "email", + "email_verified", + "preferred_username", + "picture" + ] + }); + }, + validateAuthorizationCode: async ({ code, redirectURI }) => { + return validateAuthorizationCode({ + code, + redirectURI, + options, + tokenEndpoint: "https://id.twitch.tv/oauth2/token" + }); + }, + refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { + return refreshAccessToken({ + refreshToken: refreshToken2, + options: { + clientId: options.clientId, + clientKey: options.clientKey, + clientSecret: options.clientSecret + }, + tokenEndpoint: "https://id.twitch.tv/oauth2/token" + }); + }, + async getUserInfo(token) { + if (options.getUserInfo) return options.getUserInfo(token); + const idToken = token.idToken; + if (!idToken) { + logger3.error("No idToken found in token"); + return null; + } + const profile = decodeJwt(idToken); + const userMap = await options.mapProfileToUser?.(profile); + return { + user: { + id: profile.sub, + name: profile.preferred_username, + email: profile.email, + image: profile.picture, + emailVerified: profile.email_verified, + ...userMap + }, + data: profile + }; + }, + options + }; + }; + } +}); + +// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/twitter.mjs +var twitter; +var init_twitter = __esm({ + "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/twitter.mjs"() { + init_create_authorization_url(); + init_refresh_access_token(); + init_validate_authorization_code(); + init_oauth2(); + init_dist4(); + twitter = (options) => { + return { + id: "twitter", + name: "Twitter", + createAuthorizationURL(data2) { + const _scopes = options.disableDefaultScope ? [] : [ + "users.read", + "tweet.read", + "offline.access", + "users.email" + ]; + if (options.scope) _scopes.push(...options.scope); + if (data2.scopes) _scopes.push(...data2.scopes); + return createAuthorizationURL({ + id: "twitter", + options, + authorizationEndpoint: "https://x.com/i/oauth2/authorize", + scopes: _scopes, + state: data2.state, + codeVerifier: data2.codeVerifier, + redirectURI: data2.redirectURI + }); + }, + validateAuthorizationCode: async ({ code, codeVerifier, redirectURI }) => { + return validateAuthorizationCode({ + code, + codeVerifier, + authentication: "basic", + redirectURI, + options, + tokenEndpoint: "https://api.x.com/2/oauth2/token" + }); + }, + refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { + return refreshAccessToken({ + refreshToken: refreshToken2, + options: { + clientId: options.clientId, + clientKey: options.clientKey, + clientSecret: options.clientSecret + }, + authentication: "basic", + tokenEndpoint: "https://api.x.com/2/oauth2/token" + }); + }, + async getUserInfo(token) { + if (options.getUserInfo) return options.getUserInfo(token); + const { data: profile, error: profileError } = await betterFetch("https://api.x.com/2/users/me?user.fields=profile_image_url", { + method: "GET", + headers: { Authorization: `Bearer ${token.accessToken}` } + }); + if (profileError) return null; + const { data: emailData, error: emailError } = await betterFetch("https://api.x.com/2/users/me?user.fields=confirmed_email", { + method: "GET", + headers: { Authorization: `Bearer ${token.accessToken}` } + }); + let emailVerified = false; + if (!emailError && emailData?.data?.confirmed_email) { + profile.data.email = emailData.data.confirmed_email; + emailVerified = true; + } + const userMap = await options.mapProfileToUser?.(profile); + return { + user: { + id: profile.data.id, + name: profile.data.name, + email: profile.data.email || profile.data.username || null, + image: profile.data.profile_image_url, + emailVerified, + ...userMap + }, + data: profile + }; + }, + options + }; + }; + } +}); + +// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/vercel.mjs +var vercel; +var init_vercel = __esm({ + "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/vercel.mjs"() { + init_error(); + init_create_authorization_url(); + init_validate_authorization_code(); + init_oauth2(); + init_dist4(); + vercel = (options) => { + return { + id: "vercel", + name: "Vercel", + createAuthorizationURL({ state: state2, scopes, codeVerifier, redirectURI }) { + if (!codeVerifier) throw new BetterAuthError("codeVerifier is required for Vercel"); + let _scopes = void 0; + if (options.scope !== void 0 || scopes !== void 0) { + _scopes = []; + if (options.scope) _scopes.push(...options.scope); + if (scopes) _scopes.push(...scopes); + } + return createAuthorizationURL({ + id: "vercel", + options, + authorizationEndpoint: "https://vercel.com/oauth/authorize", + scopes: _scopes, + state: state2, + codeVerifier, + redirectURI + }); + }, + validateAuthorizationCode: async ({ code, codeVerifier, redirectURI }) => { + return validateAuthorizationCode({ + code, + codeVerifier, + redirectURI, + options, + tokenEndpoint: "https://api.vercel.com/login/oauth/token" + }); + }, + async getUserInfo(token) { + if (options.getUserInfo) return options.getUserInfo(token); + const { data: profile, error: error50 } = await betterFetch("https://api.vercel.com/login/oauth/userinfo", { headers: { Authorization: `Bearer ${token.accessToken}` } }); + if (error50 || !profile) return null; + const userMap = await options.mapProfileToUser?.(profile); + return { + user: { + id: profile.sub, + name: profile.name ?? profile.preferred_username, + email: profile.email, + image: profile.picture, + emailVerified: profile.email_verified ?? false, + ...userMap + }, + data: profile + }; + }, + options + }; + }; + } +}); + +// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/vk.mjs +var vk; +var init_vk = __esm({ + "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/vk.mjs"() { + init_create_authorization_url(); + init_refresh_access_token(); + init_validate_authorization_code(); + init_oauth2(); + init_dist4(); + vk = (options) => { + return { + id: "vk", + name: "VK", + async createAuthorizationURL({ state: state2, scopes, codeVerifier, redirectURI }) { + const _scopes = options.disableDefaultScope ? [] : ["email", "phone"]; + if (options.scope) _scopes.push(...options.scope); + if (scopes) _scopes.push(...scopes); + return createAuthorizationURL({ + id: "vk", + options, + authorizationEndpoint: "https://id.vk.com/authorize", + scopes: _scopes, + state: state2, + redirectURI, + codeVerifier + }); + }, + validateAuthorizationCode: async ({ code, codeVerifier, redirectURI, deviceId }) => { + return validateAuthorizationCode({ + code, + codeVerifier, + redirectURI: options.redirectURI || redirectURI, + options, + deviceId, + tokenEndpoint: "https://id.vk.com/oauth2/auth" + }); + }, + refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { + return refreshAccessToken({ + refreshToken: refreshToken2, + options: { + clientId: options.clientId, + clientKey: options.clientKey, + clientSecret: options.clientSecret + }, + tokenEndpoint: "https://id.vk.com/oauth2/auth" + }); + }, + async getUserInfo(data2) { + if (options.getUserInfo) return options.getUserInfo(data2); + if (!data2.accessToken) return null; + const formBody = new URLSearchParams({ + access_token: data2.accessToken, + client_id: options.clientId + }).toString(); + const { data: profile, error: error50 } = await betterFetch("https://id.vk.com/oauth2/user_info", { + method: "POST", + headers: { "Content-Type": "application/x-www-form-urlencoded" }, + body: formBody + }); + if (error50) return null; + const userMap = await options.mapProfileToUser?.(profile); + if (!profile.user.email && !userMap?.email) return null; + return { + user: { + id: profile.user.user_id, + first_name: profile.user.first_name, + last_name: profile.user.last_name, + email: profile.user.email, + image: profile.user.avatar, + emailVerified: false, + birthday: profile.user.birthday, + sex: profile.user.sex, + name: `${profile.user.first_name} ${profile.user.last_name}`, + ...userMap + }, + data: profile + }; + }, + options + }; + }; + } +}); + +// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/zoom.mjs +var zoom; +var init_zoom = __esm({ + "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/zoom.mjs"() { + init_utils13(); + init_refresh_access_token(); + init_validate_authorization_code(); + init_oauth2(); + init_dist4(); + zoom = (userOptions) => { + const options = { + pkce: true, + ...userOptions + }; + return { + id: "zoom", + name: "Zoom", + createAuthorizationURL: async ({ state: state2, redirectURI, codeVerifier }) => { + const params = new URLSearchParams({ + response_type: "code", + redirect_uri: options.redirectURI ? options.redirectURI : redirectURI, + client_id: options.clientId, + state: state2 + }); + if (options.pkce) { + const codeChallenge = await generateCodeChallenge(codeVerifier); + params.set("code_challenge_method", "S256"); + params.set("code_challenge", codeChallenge); + } + const url2 = new URL("https://zoom.us/oauth/authorize"); + url2.search = params.toString(); + return url2; + }, + validateAuthorizationCode: async ({ code, redirectURI, codeVerifier }) => { + return validateAuthorizationCode({ + code, + redirectURI: options.redirectURI || redirectURI, + codeVerifier, + options, + tokenEndpoint: "https://zoom.us/oauth/token", + authentication: "post" + }); + }, + refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => refreshAccessToken({ + refreshToken: refreshToken2, + options: { + clientId: options.clientId, + clientKey: options.clientKey, + clientSecret: options.clientSecret + }, + tokenEndpoint: "https://zoom.us/oauth/token" + }), + async getUserInfo(token) { + if (options.getUserInfo) return options.getUserInfo(token); + const { data: profile, error: error50 } = await betterFetch("https://api.zoom.us/v2/users/me", { headers: { authorization: `Bearer ${token.accessToken}` } }); + if (error50) return null; + const userMap = await options.mapProfileToUser?.(profile); + return { + user: { + id: profile.id, + name: profile.display_name, + image: profile.pic_url, + email: profile.email, + emailVerified: Boolean(profile.verified), + ...userMap + }, + data: { ...profile } + }; + } + }; + }; + } +}); + +// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/index.mjs +var socialProviders, socialProviderList, SocialProviderListEnum; +var init_social_providers = __esm({ + "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/index.mjs"() { + init_apple(); + init_atlassian(); + init_cognito(); + init_discord(); + init_dropbox(); + init_facebook(); + init_figma(); + init_github(); + init_gitlab(); + init_google(); + init_huggingface(); + init_kakao(); + init_kick(); + init_line2(); + init_linear(); + init_linkedin(); + init_microsoft_entra_id(); + init_naver(); + init_notion(); + init_paybin(); + init_paypal(); + init_polar(); + init_reddit(); + init_roblox(); + init_salesforce(); + init_slack(); + init_spotify(); + init_tiktok(); + init_twitch(); + init_twitter(); + init_vercel(); + init_vk(); + init_zoom(); + init_zod(); + socialProviders = { + apple, + atlassian, + cognito, + discord, + facebook, + figma, + github, + microsoft, + google, + huggingface, + slack, + spotify, + twitch, + twitter, + dropbox, + kick, + linear, + linkedin, + gitlab, + tiktok, + reddit, + roblox, + salesforce, + vk, + zoom, + notion, + kakao, + naver, + line: line2, + paybin, + paypal, + polar, + vercel + }; + socialProviderList = Object.keys(socialProviders); + SocialProviderListEnum = _enum2(socialProviderList).or(string2()); + } +}); + +// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/api/routes/account.mjs +var listUserAccounts, linkSocialAccount, unlinkAccount, getAccessToken, refreshToken, accountInfoQuerySchema, accountInfo; +var init_account2 = __esm({ + "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/api/routes/account.mjs"() { + init_schema4(); + init_session_store(); + init_state2(); + init_utils12(); + init_session4(); + init_error(); + init_dist3(); + init_zod(); + init_social_providers(); + init_api2(); + listUserAccounts = createAuthEndpoint("/list-accounts", { + method: "GET", + use: [sessionMiddleware], + metadata: { openapi: { + operationId: "listUserAccounts", + description: "List all accounts linked to the user", + responses: { "200": { + description: "Success", + content: { "application/json": { schema: { + type: "array", + items: { + type: "object", + properties: { + id: { type: "string" }, + providerId: { type: "string" }, + createdAt: { + type: "string", + format: "date-time" + }, + updatedAt: { + type: "string", + format: "date-time" + }, + accountId: { type: "string" }, + userId: { type: "string" }, + scopes: { + type: "array", + items: { type: "string" } + } + }, + required: [ + "id", + "providerId", + "createdAt", + "updatedAt", + "accountId", + "userId", + "scopes" + ] + } + } } } + } } + } } + }, async (c5) => { + const session = c5.context.session; + const accounts = await c5.context.internalAdapter.findAccounts(session.user.id); + return c5.json(accounts.map((a5) => { + const { scope, ...parsed } = parseAccountOutput(c5.context.options, a5); + return { + ...parsed, + scopes: scope?.split(",") || [] + }; + })); + }); + linkSocialAccount = createAuthEndpoint("/link-social", { + method: "POST", + requireHeaders: true, + body: object({ + callbackURL: string2().meta({ description: "The URL to redirect to after the user has signed in" }).optional(), + provider: SocialProviderListEnum, + idToken: object({ + token: string2(), + nonce: string2().optional(), + accessToken: string2().optional(), + refreshToken: string2().optional(), + scopes: array(string2()).optional() + }).optional(), + requestSignUp: boolean3().optional(), + scopes: array(string2()).meta({ description: "Additional scopes to request from the provider" }).optional(), + errorCallbackURL: string2().meta({ description: "The URL to redirect to if there is an error during the link process" }).optional(), + disableRedirect: boolean3().meta({ description: "Disable automatic redirection to the provider. Useful for handling the redirection yourself" }).optional(), + additionalData: record(string2(), any()).optional() + }), + use: [sessionMiddleware], + metadata: { openapi: { + description: "Link a social account to the user", + operationId: "linkSocialAccount", + responses: { "200": { + description: "Success", + content: { "application/json": { schema: { + type: "object", + properties: { + url: { + type: "string", + description: "The authorization URL to redirect the user to" + }, + redirect: { + type: "boolean", + description: "Indicates if the user should be redirected to the authorization URL" + }, + status: { type: "boolean" } + }, + required: ["redirect"] + } } } + } } + } } + }, async (c5) => { + const session = c5.context.session; + const provider = c5.context.socialProviders.find((p5) => p5.id === c5.body.provider); + if (!provider) { + c5.context.logger.error("Provider not found. Make sure to add the provider in your auth config", { provider: c5.body.provider }); + throw new APIError("NOT_FOUND", { message: BASE_ERROR_CODES.PROVIDER_NOT_FOUND }); + } + if (c5.body.idToken) { + if (!provider.verifyIdToken) { + c5.context.logger.error("Provider does not support id token verification", { provider: c5.body.provider }); + throw new APIError("NOT_FOUND", { message: BASE_ERROR_CODES.ID_TOKEN_NOT_SUPPORTED }); + } + const { token, nonce } = c5.body.idToken; + if (!await provider.verifyIdToken(token, nonce)) { + c5.context.logger.error("Invalid id token", { provider: c5.body.provider }); + throw new APIError("UNAUTHORIZED", { message: BASE_ERROR_CODES.INVALID_TOKEN }); + } + const linkingUserInfo = await provider.getUserInfo({ + idToken: token, + accessToken: c5.body.idToken.accessToken, + refreshToken: c5.body.idToken.refreshToken + }); + if (!linkingUserInfo || !linkingUserInfo?.user) { + c5.context.logger.error("Failed to get user info", { provider: c5.body.provider }); + throw new APIError("UNAUTHORIZED", { message: BASE_ERROR_CODES.FAILED_TO_GET_USER_INFO }); + } + const linkingUserId = String(linkingUserInfo.user.id); + if (!linkingUserInfo.user.email) { + c5.context.logger.error("User email not found", { provider: c5.body.provider }); + throw new APIError("UNAUTHORIZED", { message: BASE_ERROR_CODES.USER_EMAIL_NOT_FOUND }); + } + if ((await c5.context.internalAdapter.findAccounts(session.user.id)).find((a5) => a5.providerId === provider.id && a5.accountId === linkingUserId)) return c5.json({ + url: "", + status: true, + redirect: false + }); + if (!c5.context.options.account?.accountLinking?.trustedProviders?.includes(provider.id) && !linkingUserInfo.user.emailVerified || c5.context.options.account?.accountLinking?.enabled === false) throw new APIError("UNAUTHORIZED", { message: "Account not linked - linking not allowed" }); + if (linkingUserInfo.user.email !== session.user.email && c5.context.options.account?.accountLinking?.allowDifferentEmails !== true) throw new APIError("UNAUTHORIZED", { message: "Account not linked - different emails not allowed" }); + try { + await c5.context.internalAdapter.createAccount({ + userId: session.user.id, + providerId: provider.id, + accountId: linkingUserId, + accessToken: c5.body.idToken.accessToken, + idToken: token, + refreshToken: c5.body.idToken.refreshToken, + scope: c5.body.idToken.scopes?.join(",") + }); + } catch { + throw new APIError("EXPECTATION_FAILED", { message: "Account not linked - unable to create account" }); + } + if (c5.context.options.account?.accountLinking?.updateUserInfoOnLink === true) try { + await c5.context.internalAdapter.updateUser(session.user.id, { + name: linkingUserInfo.user?.name, + image: linkingUserInfo.user?.image + }); + } catch (e5) { + console.warn("Could not update user - " + e5.toString()); + } + return c5.json({ + url: "", + status: true, + redirect: false + }); + } + const state2 = await generateState(c5, { + userId: session.user.id, + email: session.user.email + }, c5.body.additionalData); + const url2 = await provider.createAuthorizationURL({ + state: state2.state, + codeVerifier: state2.codeVerifier, + redirectURI: `${c5.context.baseURL}/callback/${provider.id}`, + scopes: c5.body.scopes + }); + if (!c5.body.disableRedirect) c5.setHeader("Location", url2.toString()); + return c5.json({ + url: url2.toString(), + redirect: !c5.body.disableRedirect + }); + }); + unlinkAccount = createAuthEndpoint("/unlink-account", { + method: "POST", + body: object({ + providerId: string2(), + accountId: string2().optional() + }), + use: [freshSessionMiddleware], + metadata: { openapi: { + description: "Unlink an account", + responses: { "200": { + description: "Success", + content: { "application/json": { schema: { + type: "object", + properties: { status: { type: "boolean" } } + } } } + } } + } } + }, async (ctx) => { + const { providerId, accountId } = ctx.body; + const accounts = await ctx.context.internalAdapter.findAccounts(ctx.context.session.user.id); + if (accounts.length === 1 && !ctx.context.options.account?.accountLinking?.allowUnlinkingAll) throw new APIError("BAD_REQUEST", { message: BASE_ERROR_CODES.FAILED_TO_UNLINK_LAST_ACCOUNT }); + const accountExist = accounts.find((account) => accountId ? account.accountId === accountId && account.providerId === providerId : account.providerId === providerId); + if (!accountExist) throw new APIError("BAD_REQUEST", { message: BASE_ERROR_CODES.ACCOUNT_NOT_FOUND }); + await ctx.context.internalAdapter.deleteAccount(accountExist.id); + return ctx.json({ status: true }); + }); + getAccessToken = createAuthEndpoint("/get-access-token", { + method: "POST", + body: object({ + providerId: string2().meta({ description: "The provider ID for the OAuth provider" }), + accountId: string2().meta({ description: "The account ID associated with the refresh token" }).optional(), + userId: string2().meta({ description: "The user ID associated with the account" }).optional() + }), + metadata: { openapi: { + description: "Get a valid access token, doing a refresh if needed", + responses: { + 200: { + description: "A Valid access token", + content: { "application/json": { schema: { + type: "object", + properties: { + tokenType: { type: "string" }, + idToken: { type: "string" }, + accessToken: { type: "string" }, + accessTokenExpiresAt: { + type: "string", + format: "date-time" + } + } + } } } + }, + 400: { description: "Invalid refresh token or provider configuration" } + } + } } + }, async (ctx) => { + const { providerId, accountId, userId } = ctx.body || {}; + const req = ctx.request; + const session = await getSessionFromCtx(ctx); + if (req && !session) throw ctx.error("UNAUTHORIZED"); + const resolvedUserId = session?.user?.id || userId; + if (!resolvedUserId) throw ctx.error("UNAUTHORIZED"); + if (!ctx.context.socialProviders.find((p5) => p5.id === providerId)) throw new APIError("BAD_REQUEST", { message: `Provider ${providerId} is not supported.` }); + const accountData = await getAccountCookie(ctx); + let account = void 0; + if (accountData && providerId === accountData.providerId && (!accountId || accountData.id === accountId)) account = accountData; + else account = (await ctx.context.internalAdapter.findAccounts(resolvedUserId)).find((acc) => accountId ? acc.id === accountId && acc.providerId === providerId : acc.providerId === providerId); + if (!account) throw new APIError("BAD_REQUEST", { message: "Account not found" }); + const provider = ctx.context.socialProviders.find((p5) => p5.id === providerId); + if (!provider) throw new APIError("BAD_REQUEST", { message: `Provider ${providerId} not found.` }); + try { + let newTokens = null; + const accessTokenExpired = account.accessTokenExpiresAt && new Date(account.accessTokenExpiresAt).getTime() - Date.now() < 5e3; + if (account.refreshToken && accessTokenExpired && provider.refreshAccessToken) { + const refreshToken$1 = await decryptOAuthToken(account.refreshToken, ctx.context); + newTokens = await provider.refreshAccessToken(refreshToken$1); + const updatedData = { + accessToken: await setTokenUtil(newTokens.accessToken, ctx.context), + accessTokenExpiresAt: newTokens.accessTokenExpiresAt, + refreshToken: await setTokenUtil(newTokens.refreshToken, ctx.context), + refreshTokenExpiresAt: newTokens.refreshTokenExpiresAt + }; + let updatedAccount = null; + if (account.id) updatedAccount = await ctx.context.internalAdapter.updateAccount(account.id, updatedData); + if (ctx.context.options.account?.storeAccountCookie) await setAccountCookie(ctx, { + ...account, + ...updatedAccount ?? updatedData + }); + } + const accessTokenExpiresAt = (() => { + if (newTokens?.accessTokenExpiresAt) { + if (typeof newTokens.accessTokenExpiresAt === "string") return new Date(newTokens.accessTokenExpiresAt); + return newTokens.accessTokenExpiresAt; + } + if (account.accessTokenExpiresAt) { + if (typeof account.accessTokenExpiresAt === "string") return new Date(account.accessTokenExpiresAt); + return account.accessTokenExpiresAt; + } + })(); + const tokens = { + accessToken: newTokens?.accessToken ?? await decryptOAuthToken(account.accessToken ?? "", ctx.context), + accessTokenExpiresAt, + scopes: account.scope?.split(",") ?? [], + idToken: newTokens?.idToken ?? account.idToken ?? void 0 + }; + return ctx.json(tokens); + } catch (error50) { + throw new APIError("BAD_REQUEST", { + message: "Failed to get a valid access token", + cause: error50 + }); + } + }); + refreshToken = createAuthEndpoint("/refresh-token", { + method: "POST", + body: object({ + providerId: string2().meta({ description: "The provider ID for the OAuth provider" }), + accountId: string2().meta({ description: "The account ID associated with the refresh token" }).optional(), + userId: string2().meta({ description: "The user ID associated with the account" }).optional() + }), + metadata: { openapi: { + description: "Refresh the access token using a refresh token", + responses: { + 200: { + description: "Access token refreshed successfully", + content: { "application/json": { schema: { + type: "object", + properties: { + tokenType: { type: "string" }, + idToken: { type: "string" }, + accessToken: { type: "string" }, + refreshToken: { type: "string" }, + accessTokenExpiresAt: { + type: "string", + format: "date-time" + }, + refreshTokenExpiresAt: { + type: "string", + format: "date-time" + } + } + } } } + }, + 400: { description: "Invalid refresh token or provider configuration" } + } + } } + }, async (ctx) => { + const { providerId, accountId, userId } = ctx.body; + const req = ctx.request; + const session = await getSessionFromCtx(ctx); + if (req && !session) throw ctx.error("UNAUTHORIZED"); + const resolvedUserId = session?.user?.id || userId; + if (!resolvedUserId) throw new APIError("BAD_REQUEST", { message: `Either userId or session is required` }); + const provider = ctx.context.socialProviders.find((p5) => p5.id === providerId); + if (!provider) throw new APIError("BAD_REQUEST", { message: `Provider ${providerId} not found.` }); + if (!provider.refreshAccessToken) throw new APIError("BAD_REQUEST", { message: `Provider ${providerId} does not support token refreshing.` }); + let account = void 0; + const accountData = await getAccountCookie(ctx); + if (accountData && (!providerId || providerId === accountData?.providerId)) account = accountData; + else account = (await ctx.context.internalAdapter.findAccounts(resolvedUserId)).find((acc) => accountId ? acc.id === accountId && acc.providerId === providerId : acc.providerId === providerId); + if (!account) throw new APIError("BAD_REQUEST", { message: "Account not found" }); + let refreshToken$1 = void 0; + if (accountData && providerId === accountData.providerId) refreshToken$1 = accountData.refreshToken ?? void 0; + else refreshToken$1 = account.refreshToken ?? void 0; + if (!refreshToken$1) throw new APIError("BAD_REQUEST", { message: "Refresh token not found" }); + try { + const decryptedRefreshToken = await decryptOAuthToken(refreshToken$1, ctx.context); + const tokens = await provider.refreshAccessToken(decryptedRefreshToken); + if (account.id) { + const updateData = { + ...account || {}, + accessToken: await setTokenUtil(tokens.accessToken, ctx.context), + refreshToken: await setTokenUtil(tokens.refreshToken, ctx.context), + accessTokenExpiresAt: tokens.accessTokenExpiresAt, + refreshTokenExpiresAt: tokens.refreshTokenExpiresAt, + scope: tokens.scopes?.join(",") || account.scope, + idToken: tokens.idToken || account.idToken + }; + await ctx.context.internalAdapter.updateAccount(account.id, updateData); + } + if (accountData && providerId === accountData.providerId && ctx.context.options.account?.storeAccountCookie) await setAccountCookie(ctx, { + ...accountData, + accessToken: await setTokenUtil(tokens.accessToken, ctx.context), + refreshToken: await setTokenUtil(tokens.refreshToken, ctx.context), + accessTokenExpiresAt: tokens.accessTokenExpiresAt, + refreshTokenExpiresAt: tokens.refreshTokenExpiresAt, + scope: tokens.scopes?.join(",") || accountData.scope, + idToken: tokens.idToken || accountData.idToken + }); + return ctx.json({ + accessToken: tokens.accessToken, + refreshToken: tokens.refreshToken, + accessTokenExpiresAt: tokens.accessTokenExpiresAt, + refreshTokenExpiresAt: tokens.refreshTokenExpiresAt, + scope: tokens.scopes?.join(",") || account.scope, + idToken: tokens.idToken || account.idToken, + providerId: account.providerId, + accountId: account.accountId + }); + } catch (error50) { + throw new APIError("BAD_REQUEST", { + message: "Failed to refresh access token", + cause: error50 + }); + } + }); + accountInfoQuerySchema = optional(object({ accountId: string2().meta({ description: "The provider given account id for which to get the account info" }).optional() })); + accountInfo = createAuthEndpoint("/account-info", { + method: "GET", + use: [sessionMiddleware], + metadata: { openapi: { + description: "Get the account info provided by the provider", + responses: { "200": { + description: "Success", + content: { "application/json": { schema: { + type: "object", + properties: { + user: { + type: "object", + properties: { + id: { type: "string" }, + name: { type: "string" }, + email: { type: "string" }, + image: { type: "string" }, + emailVerified: { type: "boolean" } + }, + required: ["id", "emailVerified"] + }, + data: { + type: "object", + properties: {}, + additionalProperties: true + } + }, + required: ["user", "data"], + additionalProperties: false + } } } + } } + } }, + query: accountInfoQuerySchema + }, async (ctx) => { + const providedAccountId = ctx.query?.accountId; + let account = void 0; + if (!providedAccountId) { + if (ctx.context.options.account?.storeAccountCookie) { + const accountData = await getAccountCookie(ctx); + if (accountData) account = accountData; + } + } else { + const accountData = await ctx.context.internalAdapter.findAccount(providedAccountId); + if (accountData) account = accountData; + } + if (!account || account.userId !== ctx.context.session.user.id) throw new APIError("BAD_REQUEST", { message: "Account not found" }); + const provider = ctx.context.socialProviders.find((p5) => p5.id === account.providerId); + if (!provider) throw new APIError("INTERNAL_SERVER_ERROR", { message: `Provider account provider is ${account.providerId} but it is not configured` }); + const tokens = await getAccessToken({ + ...ctx, + method: "POST", + body: { + accountId: account.id, + providerId: account.providerId + }, + returnHeaders: false, + returnStatus: false + }); + if (!tokens.accessToken) throw new APIError("BAD_REQUEST", { message: "Access token not found" }); + const info2 = await provider.getUserInfo({ + ...tokens, + accessToken: tokens.accessToken + }); + return ctx.json(info2); + }); + } +}); + +// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/api/routes/email-verification.mjs +async function createEmailVerificationToken(secret, email3, updateTo, expiresIn = 3600, extraPayload) { + return await signJWT({ + email: email3.toLowerCase(), + updateTo, + ...extraPayload + }, secret, expiresIn); +} +async function sendVerificationEmailFn(ctx, user) { + if (!ctx.context.options.emailVerification?.sendVerificationEmail) { + ctx.context.logger.error("Verification email isn't enabled."); + throw new APIError("BAD_REQUEST", { message: "Verification email isn't enabled" }); + } + const token = await createEmailVerificationToken(ctx.context.secret, user.email, void 0, ctx.context.options.emailVerification?.expiresIn); + const callbackURL = ctx.body.callbackURL ? encodeURIComponent(ctx.body.callbackURL) : encodeURIComponent("/"); + const url2 = `${ctx.context.baseURL}/verify-email?token=${token}&callbackURL=${callbackURL}`; + await ctx.context.runInBackgroundOrAwait(ctx.context.options.emailVerification.sendVerificationEmail({ + user, + url: url2, + token + }, ctx.request)); +} +var sendVerificationEmail, verifyEmail; +var init_email_verification = __esm({ + "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/api/routes/email-verification.mjs"() { + init_schema4(); + init_origin_check(); + init_middlewares(); + init_jwt(); + init_cookies2(); + init_session4(); + init_error(); + init_dist3(); + init_zod(); + init_api2(); + init_webapi(); + init_errors7(); + sendVerificationEmail = createAuthEndpoint("/send-verification-email", { + method: "POST", + operationId: "sendVerificationEmail", + body: object({ + email: email2().meta({ description: "The email to send the verification email to" }), + callbackURL: string2().meta({ description: "The URL to use for email verification callback" }).optional() + }), + metadata: { openapi: { + operationId: "sendVerificationEmail", + description: "Send a verification email to the user", + requestBody: { content: { "application/json": { schema: { + type: "object", + properties: { + email: { + type: "string", + description: "The email to send the verification email to", + example: "user@example.com" + }, + callbackURL: { + type: "string", + description: "The URL to use for email verification callback", + example: "https://example.com/callback", + nullable: true + } + }, + required: ["email"] + } } } }, + responses: { + "200": { + description: "Success", + content: { "application/json": { schema: { + type: "object", + properties: { status: { + type: "boolean", + description: "Indicates if the email was sent successfully", + example: true + } } + } } } + }, + "400": { + description: "Bad Request", + content: { "application/json": { schema: { + type: "object", + properties: { message: { + type: "string", + description: "Error message", + example: "Verification email isn't enabled" + } } + } } } + } + } + } } + }, async (ctx) => { + if (!ctx.context.options.emailVerification?.sendVerificationEmail) { + ctx.context.logger.error("Verification email isn't enabled."); + throw new APIError("BAD_REQUEST", { message: "Verification email isn't enabled" }); + } + const { email: email3 } = ctx.body; + const session = await getSessionFromCtx(ctx); + if (!session) { + const user = await ctx.context.internalAdapter.findUserByEmail(email3); + if (!user) { + await createEmailVerificationToken(ctx.context.secret, email3, void 0, ctx.context.options.emailVerification?.expiresIn); + return ctx.json({ status: true }); + } + await sendVerificationEmailFn(ctx, user.user); + return ctx.json({ status: true }); + } + if (session?.user.email !== email3) throw new APIError("BAD_REQUEST", { message: BASE_ERROR_CODES.EMAIL_MISMATCH }); + if (session?.user.emailVerified) throw new APIError("BAD_REQUEST", { message: BASE_ERROR_CODES.EMAIL_ALREADY_VERIFIED }); + await sendVerificationEmailFn(ctx, session.user); + return ctx.json({ status: true }); + }); + verifyEmail = createAuthEndpoint("/verify-email", { + method: "GET", + operationId: "verifyEmail", + query: object({ + token: string2().meta({ description: "The token to verify the email" }), + callbackURL: string2().meta({ description: "The URL to redirect to after email verification" }).optional() + }), + use: [originCheck((ctx) => ctx.query.callbackURL)], + metadata: { openapi: { + description: "Verify the email of the user", + parameters: [{ + name: "token", + in: "query", + description: "The token to verify the email", + required: true, + schema: { type: "string" } + }, { + name: "callbackURL", + in: "query", + description: "The URL to redirect to after email verification", + required: false, + schema: { type: "string" } + }], + responses: { "200": { + description: "Success", + content: { "application/json": { schema: { + type: "object", + properties: { + user: { + type: "object", + $ref: "#/components/schemas/User" + }, + status: { + type: "boolean", + description: "Indicates if the email was verified successfully" + } + }, + required: ["user", "status"] + } } } + } } + } } + }, async (ctx) => { + function redirectOnError(error50) { + if (ctx.query.callbackURL) { + if (ctx.query.callbackURL.includes("?")) throw ctx.redirect(`${ctx.query.callbackURL}&error=${error50}`); + throw ctx.redirect(`${ctx.query.callbackURL}?error=${error50}`); + } + throw new APIError("UNAUTHORIZED", { message: error50 }); + } + const { token } = ctx.query; + let jwt2; + try { + jwt2 = await jwtVerify(token, new TextEncoder().encode(ctx.context.secret), { algorithms: ["HS256"] }); + } catch (e5) { + if (e5 instanceof JWTExpired) return redirectOnError("token_expired"); + return redirectOnError("invalid_token"); + } + const parsed = object({ + email: email2(), + updateTo: string2().optional(), + requestType: string2().optional() + }).parse(jwt2.payload); + const user = await ctx.context.internalAdapter.findUserByEmail(parsed.email); + if (!user) return redirectOnError("user_not_found"); + if (parsed.updateTo) { + const session = await getSessionFromCtx(ctx); + if (session && session.user.email !== parsed.email) return redirectOnError("unauthorized"); + switch (parsed.requestType) { + case "change-email-confirmation": { + const newToken = await createEmailVerificationToken(ctx.context.secret, parsed.email, parsed.updateTo, ctx.context.options.emailVerification?.expiresIn, { requestType: "change-email-verification" }); + const updateCallbackURL = ctx.query.callbackURL ? encodeURIComponent(ctx.query.callbackURL) : encodeURIComponent("/"); + const url2 = `${ctx.context.baseURL}/verify-email?token=${newToken}&callbackURL=${updateCallbackURL}`; + if (ctx.context.options.emailVerification?.sendVerificationEmail) await ctx.context.runInBackgroundOrAwait(ctx.context.options.emailVerification.sendVerificationEmail({ + user: { + ...user.user, + email: parsed.updateTo + }, + url: url2, + token: newToken + }, ctx.request)); + if (ctx.query.callbackURL) throw ctx.redirect(ctx.query.callbackURL); + return ctx.json({ status: true }); + } + case "change-email-verification": { + let activeSession = session; + if (!activeSession) { + const newSession = await ctx.context.internalAdapter.createSession(user.user.id); + if (!newSession) throw new APIError("INTERNAL_SERVER_ERROR", { message: BASE_ERROR_CODES.FAILED_TO_CREATE_SESSION }); + activeSession = { + session: newSession, + user: user.user + }; + } + if (ctx.context.options.emailVerification?.onEmailVerification) await ctx.context.options.emailVerification.onEmailVerification(user.user, ctx.request); + const updatedUser$1 = await ctx.context.internalAdapter.updateUserByEmail(parsed.email, { + email: parsed.updateTo, + emailVerified: true + }); + if (ctx.context.options.emailVerification?.afterEmailVerification) await ctx.context.options.emailVerification.afterEmailVerification(updatedUser$1, ctx.request); + await setSessionCookie(ctx, { + session: activeSession.session, + user: { + ...activeSession.user, + email: parsed.updateTo, + emailVerified: true + } + }); + if (ctx.query.callbackURL) throw ctx.redirect(ctx.query.callbackURL); + return ctx.json({ + status: true, + user: parseUserOutput(ctx.context.options, updatedUser$1) + }); + } + default: { + let activeSession = session; + if (!activeSession) { + const newSession = await ctx.context.internalAdapter.createSession(user.user.id); + if (!newSession) throw new APIError("INTERNAL_SERVER_ERROR", { message: BASE_ERROR_CODES.FAILED_TO_CREATE_SESSION }); + activeSession = { + session: newSession, + user: user.user + }; + } + const updatedUser$1 = await ctx.context.internalAdapter.updateUserByEmail(parsed.email, { + email: parsed.updateTo, + emailVerified: false + }); + const newToken = await createEmailVerificationToken(ctx.context.secret, parsed.updateTo); + const updateCallbackURL = ctx.query.callbackURL ? encodeURIComponent(ctx.query.callbackURL) : encodeURIComponent("/"); + if (ctx.context.options.emailVerification?.sendVerificationEmail) await ctx.context.runInBackgroundOrAwait(ctx.context.options.emailVerification.sendVerificationEmail({ + user: updatedUser$1, + url: `${ctx.context.baseURL}/verify-email?token=${newToken}&callbackURL=${updateCallbackURL}`, + token: newToken + }, ctx.request)); + await setSessionCookie(ctx, { + session: activeSession.session, + user: { + ...activeSession.user, + email: parsed.updateTo, + emailVerified: false + } + }); + if (ctx.query.callbackURL) throw ctx.redirect(ctx.query.callbackURL); + return ctx.json({ + status: true, + user: parseUserOutput(ctx.context.options, updatedUser$1) + }); + } + } + } + if (user.user.emailVerified) { + if (ctx.query.callbackURL) throw ctx.redirect(ctx.query.callbackURL); + return ctx.json({ + status: true, + user: null + }); + } + if (ctx.context.options.emailVerification?.beforeEmailVerification) await ctx.context.options.emailVerification.beforeEmailVerification(user.user, ctx.request); + if (ctx.context.options.emailVerification?.onEmailVerification) await ctx.context.options.emailVerification.onEmailVerification(user.user, ctx.request); + const updatedUser = await ctx.context.internalAdapter.updateUserByEmail(parsed.email, { emailVerified: true }); + if (ctx.context.options.emailVerification?.afterEmailVerification) await ctx.context.options.emailVerification.afterEmailVerification(updatedUser, ctx.request); + if (ctx.context.options.emailVerification?.autoSignInAfterVerification) { + const currentSession = await getSessionFromCtx(ctx); + if (!currentSession || currentSession.user.email !== parsed.email) { + const session = await ctx.context.internalAdapter.createSession(user.user.id); + if (!session) throw new APIError("INTERNAL_SERVER_ERROR", { message: "Failed to create session" }); + await setSessionCookie(ctx, { + session, + user: { + ...user.user, + emailVerified: true + } + }); + } else await setSessionCookie(ctx, { + session: currentSession.session, + user: { + ...currentSession.user, + emailVerified: true + } + }); + } + if (ctx.query.callbackURL) throw ctx.redirect(ctx.query.callbackURL); + return ctx.json({ + status: true, + user: null + }); + }); + } +}); + +// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/oauth2/link-account.mjs +async function handleOAuthUserInfo(c5, opts) { + const { userInfo, account, callbackURL, disableSignUp, overrideUserInfo } = opts; + const dbUser = await c5.context.internalAdapter.findOAuthUser(userInfo.email.toLowerCase(), account.accountId, account.providerId).catch((e5) => { + logger3.error("Better auth was unable to query your database.\nError: ", e5); + const errorURL = c5.context.options.onAPIError?.errorURL || `${c5.context.baseURL}/error`; + throw c5.redirect(`${errorURL}?error=internal_server_error`); + }); + let user = dbUser?.user; + const isRegister = !user; + if (dbUser) { + const linkedAccount = dbUser.linkedAccount ?? dbUser.accounts.find((acc) => acc.providerId === account.providerId && acc.accountId === account.accountId); + if (!linkedAccount) { + const accountLinking = c5.context.options.account?.accountLinking; + const trustedProviders = c5.context.options.account?.accountLinking?.trustedProviders; + if (!(opts.isTrustedProvider || trustedProviders?.includes(account.providerId)) && !userInfo.emailVerified || accountLinking?.enabled === false || accountLinking?.disableImplicitLinking === true) { + if (isDevelopment()) logger3.warn(`User already exist but account isn't linked to ${account.providerId}. To read more about how account linking works in Better Auth see https://www.better-auth.com/docs/concepts/users-accounts#account-linking.`); + return { + error: "account not linked", + data: null + }; + } + try { + await c5.context.internalAdapter.linkAccount({ + providerId: account.providerId, + accountId: userInfo.id.toString(), + userId: dbUser.user.id, + accessToken: await setTokenUtil(account.accessToken, c5.context), + refreshToken: await setTokenUtil(account.refreshToken, c5.context), + idToken: account.idToken, + accessTokenExpiresAt: account.accessTokenExpiresAt, + refreshTokenExpiresAt: account.refreshTokenExpiresAt, + scope: account.scope + }); + } catch (e5) { + logger3.error("Unable to link account", e5); + return { + error: "unable to link account", + data: null + }; + } + if (userInfo.emailVerified && !dbUser.user.emailVerified && userInfo.email.toLowerCase() === dbUser.user.email) await c5.context.internalAdapter.updateUser(dbUser.user.id, { emailVerified: true }); + } else { + const freshTokens = c5.context.options.account?.updateAccountOnSignIn !== false ? Object.fromEntries(Object.entries({ + idToken: account.idToken, + accessToken: await setTokenUtil(account.accessToken, c5.context), + refreshToken: await setTokenUtil(account.refreshToken, c5.context), + accessTokenExpiresAt: account.accessTokenExpiresAt, + refreshTokenExpiresAt: account.refreshTokenExpiresAt, + scope: account.scope + }).filter(([_, value]) => value !== void 0)) : {}; + if (c5.context.options.account?.storeAccountCookie) await setAccountCookie(c5, { + ...linkedAccount, + ...freshTokens + }); + if (Object.keys(freshTokens).length > 0) await c5.context.internalAdapter.updateAccount(linkedAccount.id, freshTokens); + if (userInfo.emailVerified && !dbUser.user.emailVerified && userInfo.email.toLowerCase() === dbUser.user.email) await c5.context.internalAdapter.updateUser(dbUser.user.id, { emailVerified: true }); + } + if (overrideUserInfo) { + const { id: _, ...restUserInfo } = userInfo; + user = await c5.context.internalAdapter.updateUser(dbUser.user.id, { + ...restUserInfo, + email: userInfo.email.toLowerCase(), + emailVerified: userInfo.email.toLowerCase() === dbUser.user.email ? dbUser.user.emailVerified || userInfo.emailVerified : userInfo.emailVerified + }); + } + } else { + if (disableSignUp) return { + error: "signup disabled", + data: null, + isRegister: false + }; + try { + const { id: _, ...restUserInfo } = userInfo; + const accountData = { + accessToken: await setTokenUtil(account.accessToken, c5.context), + refreshToken: await setTokenUtil(account.refreshToken, c5.context), + idToken: account.idToken, + accessTokenExpiresAt: account.accessTokenExpiresAt, + refreshTokenExpiresAt: account.refreshTokenExpiresAt, + scope: account.scope, + providerId: account.providerId, + accountId: userInfo.id.toString() + }; + const { user: createdUser, account: createdAccount } = await c5.context.internalAdapter.createOAuthUser({ + ...restUserInfo, + email: userInfo.email.toLowerCase() + }, accountData); + user = createdUser; + if (c5.context.options.account?.storeAccountCookie) await setAccountCookie(c5, createdAccount); + if (!userInfo.emailVerified && user && c5.context.options.emailVerification?.sendOnSignUp && c5.context.options.emailVerification?.sendVerificationEmail) { + const token = await createEmailVerificationToken(c5.context.secret, user.email, void 0, c5.context.options.emailVerification?.expiresIn); + const url2 = `${c5.context.baseURL}/verify-email?token=${token}&callbackURL=${callbackURL}`; + await c5.context.runInBackgroundOrAwait(c5.context.options.emailVerification.sendVerificationEmail({ + user, + url: url2, + token + }, c5.request)); + } + } catch (e5) { + logger3.error(e5); + if (e5 instanceof APIError) return { + error: e5.message, + data: null, + isRegister: false + }; + return { + error: "unable to create user", + data: null, + isRegister: false + }; + } + } + if (!user) return { + error: "unable to create user", + data: null, + isRegister: false + }; + const session = await c5.context.internalAdapter.createSession(user.id); + if (!session) return { + error: "unable to create session", + data: null, + isRegister: false + }; + return { + data: { + session, + user + }, + error: null, + isRegister + }; +} +var init_link_account = __esm({ + "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/oauth2/link-account.mjs"() { + init_session_store(); + init_utils12(); + init_email_verification(); + init_api3(); + init_env(); + } +}); + +// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/api/routes/callback.mjs +var schema, callbackOAuth; +var init_callback = __esm({ + "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/api/routes/callback.mjs"() { + init_cookies2(); + init_state2(); + init_utils12(); + init_link_account(); + init_hide_metadata(); + init_utils7(); + init_zod(); + init_api2(); + schema = object({ + code: string2().optional(), + error: string2().optional(), + device_id: string2().optional(), + error_description: string2().optional(), + state: string2().optional(), + user: string2().optional() + }); + callbackOAuth = createAuthEndpoint("/callback/:id", { + method: ["GET", "POST"], + operationId: "handleOAuthCallback", + body: schema.optional(), + query: schema.optional(), + metadata: { + ...HIDE_METADATA, + allowedMediaTypes: ["application/x-www-form-urlencoded", "application/json"] + } + }, async (c5) => { + let queryOrBody; + const defaultErrorURL = c5.context.options.onAPIError?.errorURL || `${c5.context.baseURL}/error`; + if (c5.method === "POST") { + const postData = c5.body ? schema.parse(c5.body) : {}; + const queryData = c5.query ? schema.parse(c5.query) : {}; + const mergedData = schema.parse({ + ...postData, + ...queryData + }); + const params = new URLSearchParams(); + for (const [key, value] of Object.entries(mergedData)) if (value !== void 0 && value !== null) params.set(key, String(value)); + const redirectURL = `${c5.context.baseURL}/callback/${c5.params.id}?${params.toString()}`; + throw c5.redirect(redirectURL); + } + try { + if (c5.method === "GET") queryOrBody = schema.parse(c5.query); + else if (c5.method === "POST") queryOrBody = schema.parse(c5.body); + else throw new Error("Unsupported method"); + } catch (e5) { + c5.context.logger.error("INVALID_CALLBACK_REQUEST", e5); + throw c5.redirect(`${defaultErrorURL}?error=invalid_callback_request`); + } + const { code, error: error50, state: state2, error_description, device_id, user: userData } = queryOrBody; + if (!state2) { + c5.context.logger.error("State not found", error50); + const url2 = `${defaultErrorURL}${defaultErrorURL.includes("?") ? "&" : "?"}state=state_not_found`; + throw c5.redirect(url2); + } + const { codeVerifier, callbackURL, link, errorURL, newUserURL, requestSignUp } = await parseState(c5); + function redirectOnError(error$1, description) { + const baseURL = errorURL ?? defaultErrorURL; + const params = new URLSearchParams({ error: error$1 }); + if (description) params.set("error_description", description); + const url2 = `${baseURL}${baseURL.includes("?") ? "&" : "?"}${params.toString()}`; + throw c5.redirect(url2); + } + if (error50) redirectOnError(error50, error_description); + if (!code) { + c5.context.logger.error("Code not found"); + throw redirectOnError("no_code"); + } + const provider = c5.context.socialProviders.find((p5) => p5.id === c5.params.id); + if (!provider) { + c5.context.logger.error("Oauth provider with id", c5.params.id, "not found"); + throw redirectOnError("oauth_provider_not_found"); + } + let tokens; + try { + tokens = await provider.validateAuthorizationCode({ + code, + codeVerifier, + deviceId: device_id, + redirectURI: `${c5.context.baseURL}/callback/${provider.id}` + }); + } catch (e5) { + c5.context.logger.error("", e5); + throw redirectOnError("invalid_code"); + } + if (!tokens) throw redirectOnError("invalid_code"); + const parsedUserData = userData ? safeJSONParse(userData) : null; + const userInfo = await provider.getUserInfo({ + ...tokens, + user: parsedUserData ?? void 0 + }).then((res) => res?.user); + if (!userInfo) { + c5.context.logger.error("Unable to get user info"); + return redirectOnError("unable_to_get_user_info"); + } + if (!callbackURL) { + c5.context.logger.error("No callback URL found"); + throw redirectOnError("no_callback_url"); + } + if (link) { + if (!c5.context.options.account?.accountLinking?.trustedProviders?.includes(provider.id) && !userInfo.emailVerified || c5.context.options.account?.accountLinking?.enabled === false) { + c5.context.logger.error("Unable to link account - untrusted provider"); + return redirectOnError("unable_to_link_account"); + } + if (userInfo.email !== link.email && c5.context.options.account?.accountLinking?.allowDifferentEmails !== true) return redirectOnError("email_doesn't_match"); + const existingAccount = await c5.context.internalAdapter.findAccount(String(userInfo.id)); + if (existingAccount) { + if (existingAccount.userId.toString() !== link.userId.toString()) return redirectOnError("account_already_linked_to_different_user"); + const updateData = Object.fromEntries(Object.entries({ + accessToken: await setTokenUtil(tokens.accessToken, c5.context), + refreshToken: await setTokenUtil(tokens.refreshToken, c5.context), + idToken: tokens.idToken, + accessTokenExpiresAt: tokens.accessTokenExpiresAt, + refreshTokenExpiresAt: tokens.refreshTokenExpiresAt, + scope: tokens.scopes?.join(",") + }).filter(([_, value]) => value !== void 0)); + await c5.context.internalAdapter.updateAccount(existingAccount.id, updateData); + } else if (!await c5.context.internalAdapter.createAccount({ + userId: link.userId, + providerId: provider.id, + accountId: String(userInfo.id), + ...tokens, + accessToken: await setTokenUtil(tokens.accessToken, c5.context), + refreshToken: await setTokenUtil(tokens.refreshToken, c5.context), + scope: tokens.scopes?.join(",") + })) return redirectOnError("unable_to_link_account"); + let toRedirectTo$1; + try { + toRedirectTo$1 = callbackURL.toString(); + } catch { + toRedirectTo$1 = callbackURL; + } + throw c5.redirect(toRedirectTo$1); + } + if (!userInfo.email) { + c5.context.logger.error("Provider did not return email. This could be due to misconfiguration in the provider settings."); + return redirectOnError("email_not_found"); + } + const accountData = { + providerId: provider.id, + accountId: String(userInfo.id), + ...tokens, + scope: tokens.scopes?.join(",") + }; + const result = await handleOAuthUserInfo(c5, { + userInfo: { + ...userInfo, + id: String(userInfo.id), + email: userInfo.email, + name: userInfo.name || userInfo.email + }, + account: accountData, + callbackURL, + disableSignUp: provider.disableImplicitSignUp && !requestSignUp || provider.options?.disableSignUp, + overrideUserInfo: provider.options?.overrideUserInfoOnSignIn + }); + if (result.error) { + c5.context.logger.error(result.error.split(" ").join("_")); + return redirectOnError(result.error.split(" ").join("_")); + } + const { session, user } = result.data; + await setSessionCookie(c5, { + session, + user + }); + let toRedirectTo; + try { + toRedirectTo = (result.isRegister ? newUserURL || callbackURL : callbackURL).toString(); + } catch { + toRedirectTo = result.isRegister ? newUserURL || callbackURL : callbackURL; + } + throw c5.redirect(toRedirectTo); + }); + } +}); + +// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/api/routes/error.mjs +function sanitize(input) { + return input.replace(//g, ">").replace(/"/g, """).replace(/'/g, "'").replace(/&(?!amp;|lt;|gt;|quot;|#39;|#x[0-9a-fA-F]+;|#[0-9]+;)/g, "&"); +} +var html2, error49; +var init_error3 = __esm({ + "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/api/routes/error.mjs"() { + init_hide_metadata(); + init_env(); + init_api2(); + html2 = (options, code = "Unknown", description = null) => { + const custom3 = options.onAPIError?.customizeDefaultErrorPage; + return ` + + + + + Error + + + +
+${custom3?.disableBackgroundGrid ? "" : ` +
+
+`} + +
+ ${custom3?.disableCornerDecorations ? "" : ` + +
+
+ +
+
`} + +
+
+
+

+ ERROR +

+
+
+
+ +

+ Something went wrong +

+ +
+ + CODE: + + + ${sanitize(code)} + +
+ +

+ ${!description ? `We encountered an unexpected error. Please try again or return to the home page. If you're a developer, you can find more information about the error here.` : description} +

+
+ + +
+
+ +`; + }; + error49 = createAuthEndpoint("/error", { + method: "GET", + metadata: { + ...HIDE_METADATA, + openapi: { + description: "Displays an error page", + responses: { "200": { + description: "Success", + content: { "text/html": { schema: { + type: "string", + description: "The HTML content of the error page" + } } } + } } + } + } + }, async (c5) => { + const url2 = new URL(c5.request?.url || ""); + const unsanitizedCode = url2.searchParams.get("error") || "UNKNOWN"; + const unsanitizedDescription = url2.searchParams.get("error_description") || null; + const safeCode = /^[\'A-Za-z0-9_-]+$/.test(unsanitizedCode || "") ? unsanitizedCode : "UNKNOWN"; + const safeDescription = unsanitizedDescription ? sanitize(unsanitizedDescription) : null; + const queryParams = new URLSearchParams(); + queryParams.set("error", safeCode); + if (unsanitizedDescription) queryParams.set("error_description", unsanitizedDescription); + const options = c5.context.options; + const errorURL = options.onAPIError?.errorURL; + if (errorURL) return new Response(null, { + status: 302, + headers: { Location: `${errorURL}${errorURL.includes("?") ? "&" : "?"}${queryParams.toString()}` } + }); + if (isProduction && !options.onAPIError?.customizeDefaultErrorPage) return new Response(null, { + status: 302, + headers: { Location: `/?${queryParams.toString()}` } + }); + return new Response(html2(c5.context.options, safeCode, safeDescription), { headers: { "Content-Type": "text/html" } }); + }); + } +}); + +// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/api/routes/ok.mjs +var ok; +var init_ok = __esm({ + "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/api/routes/ok.mjs"() { + init_hide_metadata(); + init_api2(); + ok = createAuthEndpoint("/ok", { + method: "GET", + metadata: { + ...HIDE_METADATA, + openapi: { + description: "Check if the API is working", + responses: { "200": { + description: "API is working", + content: { "application/json": { schema: { + type: "object", + properties: { ok: { + type: "boolean", + description: "Indicates if the API is working" + } }, + required: ["ok"] + } } } + } } + } + } + }, async (ctx) => { + return ctx.json({ ok: true }); + }); + } +}); + +// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/utils/password.mjs +async function validatePassword(ctx, data2) { + const credentialAccount = (await ctx.context.internalAdapter.findAccounts(data2.userId))?.find((account) => account.providerId === "credential"); + const currentPassword = credentialAccount?.password; + if (!credentialAccount || !currentPassword) return false; + return await ctx.context.password.verify({ + hash: currentPassword, + password: data2.password + }); +} +async function checkPassword(userId, c5) { + const credentialAccount = (await c5.context.internalAdapter.findAccounts(userId))?.find((account) => account.providerId === "credential"); + const currentPassword = credentialAccount?.password; + if (!credentialAccount || !currentPassword || !c5.body.password) throw new APIError("BAD_REQUEST", { message: "No password credential found" }); + if (!await c5.context.password.verify({ + hash: currentPassword, + password: c5.body.password + })) throw new APIError("BAD_REQUEST", { message: "Invalid password" }); + return true; +} +var init_password2 = __esm({ + "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/utils/password.mjs"() { + init_dist3(); + } +}); + +// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/api/routes/password.mjs +function redirectError(ctx, callbackURL, query) { + const url2 = callbackURL ? new URL(callbackURL, ctx.baseURL) : new URL(`${ctx.baseURL}/error`); + if (query) Object.entries(query).forEach(([k5, v5]) => url2.searchParams.set(k5, v5)); + return url2.href; +} +function redirectCallback(ctx, callbackURL, query) { + const url2 = new URL(callbackURL, ctx.baseURL); + if (query) Object.entries(query).forEach(([k5, v5]) => url2.searchParams.set(k5, v5)); + return url2.href; +} +var requestPasswordReset, requestPasswordResetCallback, resetPassword, verifyPassword2; +var init_password3 = __esm({ + "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/api/routes/password.mjs"() { + init_date2(); + init_origin_check(); + init_middlewares(); + init_session4(); + init_utils10(); + init_password2(); + init_error(); + init_dist3(); + init_zod(); + init_api2(); + requestPasswordReset = createAuthEndpoint("/request-password-reset", { + method: "POST", + body: object({ + email: email2().meta({ description: "The email address of the user to send a password reset email to" }), + redirectTo: string2().meta({ description: "The URL to redirect the user to reset their password. If the token isn't valid or expired, it'll be redirected with a query parameter `?error=INVALID_TOKEN`. If the token is valid, it'll be redirected with a query parameter `?token=VALID_TOKEN" }).optional() + }), + metadata: { openapi: { + operationId: "requestPasswordReset", + description: "Send a password reset email to the user", + responses: { "200": { + description: "Success", + content: { "application/json": { schema: { + type: "object", + properties: { + status: { type: "boolean" }, + message: { type: "string" } + } + } } } + } } + } } + }, async (ctx) => { + if (!ctx.context.options.emailAndPassword?.sendResetPassword) { + ctx.context.logger.error("Reset password isn't enabled.Please pass an emailAndPassword.sendResetPassword function in your auth config!"); + throw new APIError("BAD_REQUEST", { message: "Reset password isn't enabled" }); + } + const { email: email3, redirectTo } = ctx.body; + const user = await ctx.context.internalAdapter.findUserByEmail(email3, { includeAccounts: true }); + if (!user) { + generateId(24); + await ctx.context.internalAdapter.findVerificationValue("dummy-verification-token"); + ctx.context.logger.error("Reset Password: User not found", { email: email3 }); + return ctx.json({ + status: true, + message: "If this email exists in our system, check your email for the reset link" + }); + } + const expiresAt = getDate(ctx.context.options.emailAndPassword.resetPasswordTokenExpiresIn || 3600 * 1, "sec"); + const verificationToken = generateId(24); + await ctx.context.internalAdapter.createVerificationValue({ + value: user.user.id, + identifier: `reset-password:${verificationToken}`, + expiresAt + }); + const callbackURL = redirectTo ? encodeURIComponent(redirectTo) : ""; + const url2 = `${ctx.context.baseURL}/reset-password/${verificationToken}?callbackURL=${callbackURL}`; + await ctx.context.runInBackgroundOrAwait(ctx.context.options.emailAndPassword.sendResetPassword({ + user: user.user, + url: url2, + token: verificationToken + }, ctx.request)); + return ctx.json({ + status: true, + message: "If this email exists in our system, check your email for the reset link" + }); + }); + requestPasswordResetCallback = createAuthEndpoint("/reset-password/:token", { + method: "GET", + operationId: "forgetPasswordCallback", + query: object({ callbackURL: string2().meta({ description: "The URL to redirect the user to reset their password" }) }), + use: [originCheck((ctx) => ctx.query.callbackURL)], + metadata: { openapi: { + operationId: "resetPasswordCallback", + description: "Redirects the user to the callback URL with the token", + parameters: [{ + name: "token", + in: "path", + required: true, + description: "The token to reset the password", + schema: { type: "string" } + }, { + name: "callbackURL", + in: "query", + required: true, + description: "The URL to redirect the user to reset their password", + schema: { type: "string" } + }], + responses: { "200": { + description: "Success", + content: { "application/json": { schema: { + type: "object", + properties: { token: { type: "string" } } + } } } + } } + } } + }, async (ctx) => { + const { token } = ctx.params; + const { callbackURL } = ctx.query; + if (!token || !callbackURL) throw ctx.redirect(redirectError(ctx.context, callbackURL, { error: "INVALID_TOKEN" })); + const verification = await ctx.context.internalAdapter.findVerificationValue(`reset-password:${token}`); + if (!verification || verification.expiresAt < /* @__PURE__ */ new Date()) throw ctx.redirect(redirectError(ctx.context, callbackURL, { error: "INVALID_TOKEN" })); + throw ctx.redirect(redirectCallback(ctx.context, callbackURL, { token })); + }); + resetPassword = createAuthEndpoint("/reset-password", { + method: "POST", + operationId: "resetPassword", + query: object({ token: string2().optional() }).optional(), + body: object({ + newPassword: string2().meta({ description: "The new password to set" }), + token: string2().meta({ description: "The token to reset the password" }).optional() + }), + metadata: { openapi: { + operationId: "resetPassword", + description: "Reset the password for a user", + responses: { "200": { + description: "Success", + content: { "application/json": { schema: { + type: "object", + properties: { status: { type: "boolean" } } + } } } + } } + } } + }, async (ctx) => { + const token = ctx.body.token || ctx.query?.token; + if (!token) throw new APIError("BAD_REQUEST", { message: BASE_ERROR_CODES.INVALID_TOKEN }); + const { newPassword } = ctx.body; + const minLength = ctx.context.password?.config.minPasswordLength; + const maxLength = ctx.context.password?.config.maxPasswordLength; + if (newPassword.length < minLength) throw new APIError("BAD_REQUEST", { message: BASE_ERROR_CODES.PASSWORD_TOO_SHORT }); + if (newPassword.length > maxLength) throw new APIError("BAD_REQUEST", { message: BASE_ERROR_CODES.PASSWORD_TOO_LONG }); + const id = `reset-password:${token}`; + const verification = await ctx.context.internalAdapter.findVerificationValue(id); + if (!verification || verification.expiresAt < /* @__PURE__ */ new Date()) throw new APIError("BAD_REQUEST", { message: BASE_ERROR_CODES.INVALID_TOKEN }); + const userId = verification.value; + const hashedPassword = await ctx.context.password.hash(newPassword); + if (!(await ctx.context.internalAdapter.findAccounts(userId)).find((ac) => ac.providerId === "credential")) await ctx.context.internalAdapter.createAccount({ + userId, + providerId: "credential", + password: hashedPassword, + accountId: userId + }); + else await ctx.context.internalAdapter.updatePassword(userId, hashedPassword); + await ctx.context.internalAdapter.deleteVerificationValue(verification.id); + if (ctx.context.options.emailAndPassword?.onPasswordReset) { + const user = await ctx.context.internalAdapter.findUserById(userId); + if (user) await ctx.context.options.emailAndPassword.onPasswordReset({ user }, ctx.request); + } + if (ctx.context.options.emailAndPassword?.revokeSessionsOnPasswordReset) await ctx.context.internalAdapter.deleteSessions(userId); + return ctx.json({ status: true }); + }); + verifyPassword2 = createAuthEndpoint("/verify-password", { + method: "POST", + body: object({ password: string2().meta({ description: "The password to verify" }) }), + metadata: { + scope: "server", + openapi: { + operationId: "verifyPassword", + description: "Verify the current user's password", + responses: { "200": { + description: "Success", + content: { "application/json": { schema: { + type: "object", + properties: { status: { type: "boolean" } } + } } } + } } + } + }, + use: [sensitiveSessionMiddleware] + }, async (ctx) => { + const { password } = ctx.body; + const session = ctx.context.session; + if (!await validatePassword(ctx, { + password, + userId: session.user.id + })) throw new APIError("BAD_REQUEST", { message: BASE_ERROR_CODES.INVALID_PASSWORD }); + return ctx.json({ status: true }); + }); + } +}); + +// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/api/routes/sign-in.mjs +var socialSignInBodySchema, signInSocial, signInEmail; +var init_sign_in = __esm({ + "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/api/routes/sign-in.mjs"() { + init_schema4(); + init_origin_check(); + init_cookies2(); + init_state2(); + init_link_account(); + init_email_verification(); + init_utils10(); + init_error(); + init_dist3(); + init_zod(); + init_social_providers(); + init_api2(); + socialSignInBodySchema = object({ + callbackURL: string2().meta({ description: "Callback URL to redirect to after the user has signed in" }).optional(), + newUserCallbackURL: string2().optional(), + errorCallbackURL: string2().meta({ description: "Callback URL to redirect to if an error happens" }).optional(), + provider: SocialProviderListEnum, + disableRedirect: boolean3().meta({ description: "Disable automatic redirection to the provider. Useful for handling the redirection yourself" }).optional(), + idToken: optional(object({ + token: string2().meta({ description: "ID token from the provider" }), + nonce: string2().meta({ description: "Nonce used to generate the token" }).optional(), + accessToken: string2().meta({ description: "Access token from the provider" }).optional(), + refreshToken: string2().meta({ description: "Refresh token from the provider" }).optional(), + expiresAt: number2().meta({ description: "Expiry date of the token" }).optional() + })), + scopes: array(string2()).meta({ description: "Array of scopes to request from the provider. This will override the default scopes passed." }).optional(), + requestSignUp: boolean3().meta({ description: "Explicitly request sign-up. Useful when disableImplicitSignUp is true for this provider" }).optional(), + loginHint: string2().meta({ description: "The login hint to use for the authorization code request" }).optional(), + additionalData: record(string2(), any()).optional().meta({ description: "Additional data to be passed through the OAuth flow" }) + }); + signInSocial = () => createAuthEndpoint("/sign-in/social", { + method: "POST", + operationId: "socialSignIn", + body: socialSignInBodySchema, + metadata: { + $Infer: { + body: {}, + returned: {} + }, + openapi: { + description: "Sign in with a social provider", + operationId: "socialSignIn", + responses: { "200": { + description: "Success - Returns either session details or redirect URL", + content: { "application/json": { schema: { + type: "object", + description: "Session response when idToken is provided", + properties: { + token: { type: "string" }, + user: { + type: "object", + $ref: "#/components/schemas/User" + }, + url: { type: "string" }, + redirect: { + type: "boolean", + enum: [false] + } + }, + required: [ + "redirect", + "token", + "user" + ] + } } } + } } + } + } + }, async (c5) => { + const provider = c5.context.socialProviders.find((p5) => p5.id === c5.body.provider); + if (!provider) { + c5.context.logger.error("Provider not found. Make sure to add the provider in your auth config", { provider: c5.body.provider }); + throw new APIError("NOT_FOUND", { message: BASE_ERROR_CODES.PROVIDER_NOT_FOUND }); + } + if (c5.body.idToken) { + if (!provider.verifyIdToken) { + c5.context.logger.error("Provider does not support id token verification", { provider: c5.body.provider }); + throw new APIError("NOT_FOUND", { message: BASE_ERROR_CODES.ID_TOKEN_NOT_SUPPORTED }); + } + const { token, nonce } = c5.body.idToken; + if (!await provider.verifyIdToken(token, nonce)) { + c5.context.logger.error("Invalid id token", { provider: c5.body.provider }); + throw new APIError("UNAUTHORIZED", { message: BASE_ERROR_CODES.INVALID_TOKEN }); + } + const userInfo = await provider.getUserInfo({ + idToken: token, + accessToken: c5.body.idToken.accessToken, + refreshToken: c5.body.idToken.refreshToken + }); + if (!userInfo || !userInfo?.user) { + c5.context.logger.error("Failed to get user info", { provider: c5.body.provider }); + throw new APIError("UNAUTHORIZED", { message: BASE_ERROR_CODES.FAILED_TO_GET_USER_INFO }); + } + if (!userInfo.user.email) { + c5.context.logger.error("User email not found", { provider: c5.body.provider }); + throw new APIError("UNAUTHORIZED", { message: BASE_ERROR_CODES.USER_EMAIL_NOT_FOUND }); + } + const data2 = await handleOAuthUserInfo(c5, { + userInfo: { + ...userInfo.user, + email: userInfo.user.email, + id: String(userInfo.user.id), + name: userInfo.user.name || "", + image: userInfo.user.image, + emailVerified: userInfo.user.emailVerified || false + }, + account: { + providerId: provider.id, + accountId: String(userInfo.user.id), + accessToken: c5.body.idToken.accessToken + }, + callbackURL: c5.body.callbackURL, + disableSignUp: provider.disableImplicitSignUp && !c5.body.requestSignUp || provider.disableSignUp + }); + if (data2.error) throw new APIError("UNAUTHORIZED", { message: data2.error }); + await setSessionCookie(c5, data2.data); + return c5.json({ + redirect: false, + token: data2.data.session.token, + url: void 0, + user: parseUserOutput(c5.context.options, data2.data.user) + }); + } + const { codeVerifier, state: state2 } = await generateState(c5, void 0, c5.body.additionalData); + const url2 = await provider.createAuthorizationURL({ + state: state2, + codeVerifier, + redirectURI: `${c5.context.baseURL}/callback/${provider.id}`, + scopes: c5.body.scopes, + loginHint: c5.body.loginHint + }); + if (!c5.body.disableRedirect) c5.setHeader("Location", url2.toString()); + return c5.json({ + url: url2.toString(), + redirect: !c5.body.disableRedirect + }); + }); + signInEmail = () => createAuthEndpoint("/sign-in/email", { + method: "POST", + operationId: "signInEmail", + use: [formCsrfMiddleware], + body: object({ + email: string2().meta({ description: "Email of the user" }), + password: string2().meta({ description: "Password of the user" }), + callbackURL: string2().meta({ description: "Callback URL to use as a redirect for email verification" }).optional(), + rememberMe: boolean3().meta({ description: "If this is false, the session will not be remembered. Default is `true`." }).default(true).optional() + }), + metadata: { + allowedMediaTypes: ["application/x-www-form-urlencoded", "application/json"], + $Infer: { + body: {}, + returned: {} + }, + openapi: { + operationId: "signInEmail", + description: "Sign in with email and password", + responses: { "200": { + description: "Success - Returns either session details or redirect URL", + content: { "application/json": { schema: { + type: "object", + description: "Session response when idToken is provided", + properties: { + redirect: { + type: "boolean", + enum: [false] + }, + token: { + type: "string", + description: "Session token" + }, + url: { + type: "string", + nullable: true + }, + user: { + type: "object", + $ref: "#/components/schemas/User" + } + }, + required: [ + "redirect", + "token", + "user" + ] + } } } + } } + } + } + }, async (ctx) => { + if (!ctx.context.options?.emailAndPassword?.enabled) { + ctx.context.logger.error("Email and password is not enabled. Make sure to enable it in the options on you `auth.ts` file. Check `https://better-auth.com/docs/authentication/email-password` for more!"); + throw new APIError("BAD_REQUEST", { message: "Email and password is not enabled" }); + } + const { email: email3, password } = ctx.body; + if (!email2().safeParse(email3).success) throw new APIError("BAD_REQUEST", { message: BASE_ERROR_CODES.INVALID_EMAIL }); + const user = await ctx.context.internalAdapter.findUserByEmail(email3, { includeAccounts: true }); + if (!user) { + await ctx.context.password.hash(password); + ctx.context.logger.error("User not found", { email: email3 }); + throw new APIError("UNAUTHORIZED", { message: BASE_ERROR_CODES.INVALID_EMAIL_OR_PASSWORD }); + } + const credentialAccount = user.accounts.find((a5) => a5.providerId === "credential"); + if (!credentialAccount) { + await ctx.context.password.hash(password); + ctx.context.logger.error("Credential account not found", { email: email3 }); + throw new APIError("UNAUTHORIZED", { message: BASE_ERROR_CODES.INVALID_EMAIL_OR_PASSWORD }); + } + const currentPassword = credentialAccount?.password; + if (!currentPassword) { + await ctx.context.password.hash(password); + ctx.context.logger.error("Password not found", { email: email3 }); + throw new APIError("UNAUTHORIZED", { message: BASE_ERROR_CODES.INVALID_EMAIL_OR_PASSWORD }); + } + if (!await ctx.context.password.verify({ + hash: currentPassword, + password + })) { + ctx.context.logger.error("Invalid password"); + throw new APIError("UNAUTHORIZED", { message: BASE_ERROR_CODES.INVALID_EMAIL_OR_PASSWORD }); + } + if (ctx.context.options?.emailAndPassword?.requireEmailVerification && !user.user.emailVerified) { + if (!ctx.context.options?.emailVerification?.sendVerificationEmail) throw new APIError("FORBIDDEN", { message: BASE_ERROR_CODES.EMAIL_NOT_VERIFIED }); + if (ctx.context.options?.emailVerification?.sendOnSignIn) { + const token = await createEmailVerificationToken(ctx.context.secret, user.user.email, void 0, ctx.context.options.emailVerification?.expiresIn); + const callbackURL = ctx.body.callbackURL ? encodeURIComponent(ctx.body.callbackURL) : encodeURIComponent("/"); + const url2 = `${ctx.context.baseURL}/verify-email?token=${token}&callbackURL=${callbackURL}`; + await ctx.context.runInBackgroundOrAwait(ctx.context.options.emailVerification.sendVerificationEmail({ + user: user.user, + url: url2, + token + }, ctx.request)); + } + throw new APIError("FORBIDDEN", { message: BASE_ERROR_CODES.EMAIL_NOT_VERIFIED }); + } + const session = await ctx.context.internalAdapter.createSession(user.user.id, ctx.body.rememberMe === false); + if (!session) { + ctx.context.logger.error("Failed to create session"); + throw new APIError("UNAUTHORIZED", { message: BASE_ERROR_CODES.FAILED_TO_CREATE_SESSION }); + } + await setSessionCookie(ctx, { + session, + user: user.user + }, ctx.body.rememberMe === false); + if (ctx.body.callbackURL) ctx.setHeader("Location", ctx.body.callbackURL); + return ctx.json({ + redirect: !!ctx.body.callbackURL, + token: session.token, + url: ctx.body.callbackURL, + user: parseUserOutput(ctx.context.options, user.user) + }); + }); + } +}); + +// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/api/routes/sign-out.mjs +var signOut; +var init_sign_out = __esm({ + "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/api/routes/sign-out.mjs"() { + init_cookies2(); + init_api2(); + signOut = createAuthEndpoint("/sign-out", { + method: "POST", + operationId: "signOut", + requireHeaders: true, + metadata: { openapi: { + operationId: "signOut", + description: "Sign out the current user", + responses: { "200": { + description: "Success", + content: { "application/json": { schema: { + type: "object", + properties: { success: { type: "boolean" } } + } } } + } } + } } + }, async (ctx) => { + const sessionCookieToken = await ctx.getSignedCookie(ctx.context.authCookies.sessionToken.name, ctx.context.secret); + if (sessionCookieToken) try { + await ctx.context.internalAdapter.deleteSession(sessionCookieToken); + } catch (e5) { + ctx.context.logger.error("Failed to delete session from database", e5); + } + deleteSessionCookie(ctx); + return ctx.json({ success: true }); + }); + } +}); + +// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/api/routes/sign-up.mjs +var signUpEmailBodySchema, signUpEmail; +var init_sign_up = __esm({ + "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/api/routes/sign-up.mjs"() { + init_schema4(); + init_db4(); + init_origin_check(); + init_cookies2(); + init_email_verification(); + init_context2(); + init_env(); + init_error(); + init_dist3(); + init_zod(); + init_api2(); + signUpEmailBodySchema = object({ + name: string2(), + email: email2(), + password: string2().nonempty(), + image: string2().optional(), + callbackURL: string2().optional(), + rememberMe: boolean3().optional() + }).and(record(string2(), any())); + signUpEmail = () => createAuthEndpoint("/sign-up/email", { + method: "POST", + operationId: "signUpWithEmailAndPassword", + use: [formCsrfMiddleware], + body: signUpEmailBodySchema, + metadata: { + allowedMediaTypes: ["application/x-www-form-urlencoded", "application/json"], + $Infer: { + body: {}, + returned: {} + }, + openapi: { + operationId: "signUpWithEmailAndPassword", + description: "Sign up a user using email and password", + requestBody: { content: { "application/json": { schema: { + type: "object", + properties: { + name: { + type: "string", + description: "The name of the user" + }, + email: { + type: "string", + description: "The email of the user" + }, + password: { + type: "string", + description: "The password of the user" + }, + image: { + type: "string", + description: "The profile image URL of the user" + }, + callbackURL: { + type: "string", + description: "The URL to use for email verification callback" + }, + rememberMe: { + type: "boolean", + description: "If this is false, the session will not be remembered. Default is `true`." + } + }, + required: [ + "name", + "email", + "password" + ] + } } } }, + responses: { + "200": { + description: "Successfully created user", + content: { "application/json": { schema: { + type: "object", + properties: { + token: { + type: "string", + nullable: true, + description: "Authentication token for the session" + }, + user: { + type: "object", + properties: { + id: { + type: "string", + description: "The unique identifier of the user" + }, + email: { + type: "string", + format: "email", + description: "The email address of the user" + }, + name: { + type: "string", + description: "The name of the user" + }, + image: { + type: "string", + format: "uri", + nullable: true, + description: "The profile image URL of the user" + }, + emailVerified: { + type: "boolean", + description: "Whether the email has been verified" + }, + createdAt: { + type: "string", + format: "date-time", + description: "When the user was created" + }, + updatedAt: { + type: "string", + format: "date-time", + description: "When the user was last updated" + } + }, + required: [ + "id", + "email", + "name", + "emailVerified", + "createdAt", + "updatedAt" + ] + } + }, + required: ["user"] + } } } + }, + "422": { + description: "Unprocessable Entity. User already exists or failed to create user.", + content: { "application/json": { schema: { + type: "object", + properties: { message: { type: "string" } } + } } } + } + } + } + } + }, async (ctx) => { + return runWithTransaction(ctx.context.adapter, async () => { + if (!ctx.context.options.emailAndPassword?.enabled || ctx.context.options.emailAndPassword?.disableSignUp) throw new APIError("BAD_REQUEST", { message: "Email and password sign up is not enabled" }); + const body = ctx.body; + const { name, email: email3, password, image, callbackURL: _callbackURL, rememberMe, ...rest } = body; + if (!email2().safeParse(email3).success) throw new APIError("BAD_REQUEST", { message: BASE_ERROR_CODES.INVALID_EMAIL }); + if (!password || typeof password !== "string") throw new APIError("BAD_REQUEST", { message: BASE_ERROR_CODES.INVALID_PASSWORD }); + const minPasswordLength = ctx.context.password.config.minPasswordLength; + if (password.length < minPasswordLength) { + ctx.context.logger.error("Password is too short"); + throw new APIError("BAD_REQUEST", { message: BASE_ERROR_CODES.PASSWORD_TOO_SHORT }); + } + const maxPasswordLength = ctx.context.password.config.maxPasswordLength; + if (password.length > maxPasswordLength) { + ctx.context.logger.error("Password is too long"); + throw new APIError("BAD_REQUEST", { message: BASE_ERROR_CODES.PASSWORD_TOO_LONG }); + } + if ((await ctx.context.internalAdapter.findUserByEmail(email3))?.user) { + ctx.context.logger.info(`Sign-up attempt for existing email: ${email3}`); + throw new APIError("UNPROCESSABLE_ENTITY", { message: BASE_ERROR_CODES.USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL }); + } + const hash2 = await ctx.context.password.hash(password); + let createdUser; + try { + const data2 = parseUserInput(ctx.context.options, rest, "create"); + createdUser = await ctx.context.internalAdapter.createUser({ + email: email3.toLowerCase(), + name, + image, + ...data2, + emailVerified: false + }); + if (!createdUser) throw new APIError("BAD_REQUEST", { message: BASE_ERROR_CODES.FAILED_TO_CREATE_USER }); + } catch (e5) { + if (isDevelopment()) ctx.context.logger.error("Failed to create user", e5); + if (e5 instanceof APIError) throw e5; + ctx.context.logger?.error("Failed to create user", e5); + throw new APIError("UNPROCESSABLE_ENTITY", { message: BASE_ERROR_CODES.FAILED_TO_CREATE_USER }); + } + if (!createdUser) throw new APIError("UNPROCESSABLE_ENTITY", { message: BASE_ERROR_CODES.FAILED_TO_CREATE_USER }); + await ctx.context.internalAdapter.linkAccount({ + userId: createdUser.id, + providerId: "credential", + accountId: createdUser.id, + password: hash2 + }); + if (ctx.context.options.emailVerification?.sendOnSignUp ?? ctx.context.options.emailAndPassword.requireEmailVerification) { + const token = await createEmailVerificationToken(ctx.context.secret, createdUser.email, void 0, ctx.context.options.emailVerification?.expiresIn); + const callbackURL = body.callbackURL ? encodeURIComponent(body.callbackURL) : encodeURIComponent("/"); + const url2 = `${ctx.context.baseURL}/verify-email?token=${token}&callbackURL=${callbackURL}`; + if (ctx.context.options.emailVerification?.sendVerificationEmail) await ctx.context.runInBackgroundOrAwait(ctx.context.options.emailVerification.sendVerificationEmail({ + user: createdUser, + url: url2, + token + }, ctx.request)); + } + if (ctx.context.options.emailAndPassword.autoSignIn === false || ctx.context.options.emailAndPassword.requireEmailVerification) return ctx.json({ + token: null, + user: parseUserOutput(ctx.context.options, createdUser) + }); + const session = await ctx.context.internalAdapter.createSession(createdUser.id, rememberMe === false); + if (!session) throw new APIError("BAD_REQUEST", { message: BASE_ERROR_CODES.FAILED_TO_CREATE_SESSION }); + await setSessionCookie(ctx, { + session, + user: createdUser + }, rememberMe === false); + return ctx.json({ + token: session.token, + user: parseUserOutput(ctx.context.options, createdUser) + }); + }); + }); + } +}); + +// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/api/routes/update-user.mjs +var updateUserBodySchema, updateUser, changePassword, setPassword, deleteUser, deleteUserCallback, changeEmail; +var init_update_user = __esm({ + "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/api/routes/update-user.mjs"() { + init_schema4(); + init_origin_check(); + init_middlewares(); + init_random2(); + init_crypto(); + init_cookies2(); + init_session4(); + init_email_verification(); + init_error(); + init_dist3(); + init_zod(); + init_api2(); + updateUserBodySchema = record(string2().meta({ description: "Field name must be a string" }), any()); + updateUser = () => createAuthEndpoint("/update-user", { + method: "POST", + operationId: "updateUser", + body: updateUserBodySchema, + use: [sessionMiddleware], + metadata: { + $Infer: { body: {} }, + openapi: { + operationId: "updateUser", + description: "Update the current user", + requestBody: { content: { "application/json": { schema: { + type: "object", + properties: { + name: { + type: "string", + description: "The name of the user" + }, + image: { + type: "string", + description: "The image of the user", + nullable: true + } + } + } } } }, + responses: { "200": { + description: "Success", + content: { "application/json": { schema: { + type: "object", + properties: { user: { + type: "object", + $ref: "#/components/schemas/User" + } } + } } } + } } + } + } + }, async (ctx) => { + const body = ctx.body; + if (typeof body !== "object" || Array.isArray(body)) throw new APIError("BAD_REQUEST", { message: "Body must be an object" }); + if (body.email) throw new APIError("BAD_REQUEST", { message: BASE_ERROR_CODES.EMAIL_CAN_NOT_BE_UPDATED }); + const { name, image, ...rest } = body; + const session = ctx.context.session; + const additionalFields = parseUserInput(ctx.context.options, rest, "update"); + if (image === void 0 && name === void 0 && Object.keys(additionalFields).length === 0) throw new APIError("BAD_REQUEST", { message: "No fields to update" }); + const updatedUser = await ctx.context.internalAdapter.updateUser(session.user.id, { + name, + image, + ...additionalFields + }) ?? { + ...session.user, + ...name !== void 0 && { name }, + ...image !== void 0 && { image }, + ...additionalFields + }; + await setSessionCookie(ctx, { + session: session.session, + user: updatedUser + }); + return ctx.json({ status: true }); + }); + changePassword = createAuthEndpoint("/change-password", { + method: "POST", + operationId: "changePassword", + body: object({ + newPassword: string2().meta({ description: "The new password to set" }), + currentPassword: string2().meta({ description: "The current password is required" }), + revokeOtherSessions: boolean3().meta({ description: "Must be a boolean value" }).optional() + }), + use: [sensitiveSessionMiddleware], + metadata: { openapi: { + operationId: "changePassword", + description: "Change the password of the user", + responses: { "200": { + description: "Password successfully changed", + content: { "application/json": { schema: { + type: "object", + properties: { + token: { + type: "string", + nullable: true, + description: "New session token if other sessions were revoked" + }, + user: { + type: "object", + properties: { + id: { + type: "string", + description: "The unique identifier of the user" + }, + email: { + type: "string", + format: "email", + description: "The email address of the user" + }, + name: { + type: "string", + description: "The name of the user" + }, + image: { + type: "string", + format: "uri", + nullable: true, + description: "The profile image URL of the user" + }, + emailVerified: { + type: "boolean", + description: "Whether the email has been verified" + }, + createdAt: { + type: "string", + format: "date-time", + description: "When the user was created" + }, + updatedAt: { + type: "string", + format: "date-time", + description: "When the user was last updated" + } + }, + required: [ + "id", + "email", + "name", + "emailVerified", + "createdAt", + "updatedAt" + ] + } + }, + required: ["user"] + } } } + } } + } } + }, async (ctx) => { + const { newPassword, currentPassword, revokeOtherSessions: revokeOtherSessions2 } = ctx.body; + const session = ctx.context.session; + const minPasswordLength = ctx.context.password.config.minPasswordLength; + if (newPassword.length < minPasswordLength) { + ctx.context.logger.error("Password is too short"); + throw new APIError("BAD_REQUEST", { message: BASE_ERROR_CODES.PASSWORD_TOO_SHORT }); + } + const maxPasswordLength = ctx.context.password.config.maxPasswordLength; + if (newPassword.length > maxPasswordLength) { + ctx.context.logger.error("Password is too long"); + throw new APIError("BAD_REQUEST", { message: BASE_ERROR_CODES.PASSWORD_TOO_LONG }); + } + const account = (await ctx.context.internalAdapter.findAccounts(session.user.id)).find((account$1) => account$1.providerId === "credential" && account$1.password); + if (!account || !account.password) throw new APIError("BAD_REQUEST", { message: BASE_ERROR_CODES.CREDENTIAL_ACCOUNT_NOT_FOUND }); + const passwordHash = await ctx.context.password.hash(newPassword); + if (!await ctx.context.password.verify({ + hash: account.password, + password: currentPassword + })) throw new APIError("BAD_REQUEST", { message: BASE_ERROR_CODES.INVALID_PASSWORD }); + await ctx.context.internalAdapter.updateAccount(account.id, { password: passwordHash }); + let token = null; + if (revokeOtherSessions2) { + await ctx.context.internalAdapter.deleteSessions(session.user.id); + const newSession = await ctx.context.internalAdapter.createSession(session.user.id); + if (!newSession) throw new APIError("INTERNAL_SERVER_ERROR", { message: BASE_ERROR_CODES.FAILED_TO_GET_SESSION }); + await setSessionCookie(ctx, { + session: newSession, + user: session.user + }); + token = newSession.token; + } + return ctx.json({ + token, + user: parseUserOutput(ctx.context.options, session.user) + }); + }); + setPassword = createAuthEndpoint({ + method: "POST", + body: object({ newPassword: string2().meta({ description: "The new password to set is required" }) }), + use: [sensitiveSessionMiddleware] + }, async (ctx) => { + const { newPassword } = ctx.body; + const session = ctx.context.session; + const minPasswordLength = ctx.context.password.config.minPasswordLength; + if (newPassword.length < minPasswordLength) { + ctx.context.logger.error("Password is too short"); + throw new APIError("BAD_REQUEST", { message: BASE_ERROR_CODES.PASSWORD_TOO_SHORT }); + } + const maxPasswordLength = ctx.context.password.config.maxPasswordLength; + if (newPassword.length > maxPasswordLength) { + ctx.context.logger.error("Password is too long"); + throw new APIError("BAD_REQUEST", { message: BASE_ERROR_CODES.PASSWORD_TOO_LONG }); + } + const account = (await ctx.context.internalAdapter.findAccounts(session.user.id)).find((account$1) => account$1.providerId === "credential" && account$1.password); + const passwordHash = await ctx.context.password.hash(newPassword); + if (!account) { + await ctx.context.internalAdapter.linkAccount({ + userId: session.user.id, + providerId: "credential", + accountId: session.user.id, + password: passwordHash + }); + return ctx.json({ status: true }); + } + throw new APIError("BAD_REQUEST", { message: "user already has a password" }); + }); + deleteUser = createAuthEndpoint("/delete-user", { + method: "POST", + use: [sensitiveSessionMiddleware], + body: object({ + callbackURL: string2().meta({ description: "The callback URL to redirect to after the user is deleted" }).optional(), + password: string2().meta({ description: "The password of the user is required to delete the user" }).optional(), + token: string2().meta({ description: "The token to delete the user is required" }).optional() + }), + metadata: { openapi: { + operationId: "deleteUser", + description: "Delete the user", + requestBody: { content: { "application/json": { schema: { + type: "object", + properties: { + callbackURL: { + type: "string", + description: "The callback URL to redirect to after the user is deleted" + }, + password: { + type: "string", + description: "The user's password. Required if session is not fresh" + }, + token: { + type: "string", + description: "The deletion verification token" + } + } + } } } }, + responses: { "200": { + description: "User deletion processed successfully", + content: { "application/json": { schema: { + type: "object", + properties: { + success: { + type: "boolean", + description: "Indicates if the operation was successful" + }, + message: { + type: "string", + enum: ["User deleted", "Verification email sent"], + description: "Status message of the deletion process" + } + }, + required: ["success", "message"] + } } } + } } + } } + }, async (ctx) => { + if (!ctx.context.options.user?.deleteUser?.enabled) { + ctx.context.logger.error("Delete user is disabled. Enable it in the options"); + throw new APIError("NOT_FOUND"); + } + const session = ctx.context.session; + if (ctx.body.password) { + const account = (await ctx.context.internalAdapter.findAccounts(session.user.id)).find((account$1) => account$1.providerId === "credential" && account$1.password); + if (!account || !account.password) throw new APIError("BAD_REQUEST", { message: BASE_ERROR_CODES.CREDENTIAL_ACCOUNT_NOT_FOUND }); + if (!await ctx.context.password.verify({ + hash: account.password, + password: ctx.body.password + })) throw new APIError("BAD_REQUEST", { message: BASE_ERROR_CODES.INVALID_PASSWORD }); + } + if (ctx.body.token) { + await deleteUserCallback({ + ...ctx, + query: { token: ctx.body.token } + }); + return ctx.json({ + success: true, + message: "User deleted" + }); + } + if (ctx.context.options.user.deleteUser?.sendDeleteAccountVerification) { + const token = generateRandomString(32, "0-9", "a-z"); + await ctx.context.internalAdapter.createVerificationValue({ + value: session.user.id, + identifier: `delete-account-${token}`, + expiresAt: new Date(Date.now() + (ctx.context.options.user.deleteUser?.deleteTokenExpiresIn || 3600 * 24) * 1e3) + }); + const url2 = `${ctx.context.baseURL}/delete-user/callback?token=${token}&callbackURL=${ctx.body.callbackURL || "/"}`; + await ctx.context.runInBackgroundOrAwait(ctx.context.options.user.deleteUser.sendDeleteAccountVerification({ + user: session.user, + url: url2, + token + }, ctx.request)); + return ctx.json({ + success: true, + message: "Verification email sent" + }); + } + if (!ctx.body.password && ctx.context.sessionConfig.freshAge !== 0) { + const currentAge = new Date(session.session.createdAt).getTime(); + const freshAge = ctx.context.sessionConfig.freshAge * 1e3; + if (Date.now() - currentAge > freshAge * 1e3) throw new APIError("BAD_REQUEST", { message: BASE_ERROR_CODES.SESSION_EXPIRED }); + } + const beforeDelete = ctx.context.options.user.deleteUser?.beforeDelete; + if (beforeDelete) await beforeDelete(session.user, ctx.request); + await ctx.context.internalAdapter.deleteUser(session.user.id); + await ctx.context.internalAdapter.deleteSessions(session.user.id); + deleteSessionCookie(ctx); + const afterDelete = ctx.context.options.user.deleteUser?.afterDelete; + if (afterDelete) await afterDelete(session.user, ctx.request); + return ctx.json({ + success: true, + message: "User deleted" + }); + }); + deleteUserCallback = createAuthEndpoint("/delete-user/callback", { + method: "GET", + query: object({ + token: string2().meta({ description: "The token to verify the deletion request" }), + callbackURL: string2().meta({ description: "The URL to redirect to after deletion" }).optional() + }), + use: [originCheck((ctx) => ctx.query.callbackURL)], + metadata: { openapi: { + description: "Callback to complete user deletion with verification token", + responses: { "200": { + description: "User successfully deleted", + content: { "application/json": { schema: { + type: "object", + properties: { + success: { + type: "boolean", + description: "Indicates if the deletion was successful" + }, + message: { + type: "string", + enum: ["User deleted"], + description: "Confirmation message" + } + }, + required: ["success", "message"] + } } } + } } + } } + }, async (ctx) => { + if (!ctx.context.options.user?.deleteUser?.enabled) { + ctx.context.logger.error("Delete user is disabled. Enable it in the options"); + throw new APIError("NOT_FOUND"); + } + const session = await getSessionFromCtx(ctx); + if (!session) throw new APIError("NOT_FOUND", { message: BASE_ERROR_CODES.FAILED_TO_GET_USER_INFO }); + const token = await ctx.context.internalAdapter.findVerificationValue(`delete-account-${ctx.query.token}`); + if (!token || token.expiresAt < /* @__PURE__ */ new Date()) throw new APIError("NOT_FOUND", { message: BASE_ERROR_CODES.INVALID_TOKEN }); + if (token.value !== session.user.id) throw new APIError("NOT_FOUND", { message: BASE_ERROR_CODES.INVALID_TOKEN }); + const beforeDelete = ctx.context.options.user.deleteUser?.beforeDelete; + if (beforeDelete) await beforeDelete(session.user, ctx.request); + await ctx.context.internalAdapter.deleteUser(session.user.id); + await ctx.context.internalAdapter.deleteSessions(session.user.id); + await ctx.context.internalAdapter.deleteAccounts(session.user.id); + await ctx.context.internalAdapter.deleteVerificationValue(token.id); + deleteSessionCookie(ctx); + const afterDelete = ctx.context.options.user.deleteUser?.afterDelete; + if (afterDelete) await afterDelete(session.user, ctx.request); + if (ctx.query.callbackURL) throw ctx.redirect(ctx.query.callbackURL || "/"); + return ctx.json({ + success: true, + message: "User deleted" + }); + }); + changeEmail = createAuthEndpoint("/change-email", { + method: "POST", + body: object({ + newEmail: email2().meta({ description: "The new email address to set must be a valid email address" }), + callbackURL: string2().meta({ description: "The URL to redirect to after email verification" }).optional() + }), + use: [sensitiveSessionMiddleware], + metadata: { openapi: { + operationId: "changeEmail", + responses: { + "200": { + description: "Email change request processed successfully", + content: { "application/json": { schema: { + type: "object", + properties: { + user: { + type: "object", + $ref: "#/components/schemas/User" + }, + status: { + type: "boolean", + description: "Indicates if the request was successful" + }, + message: { + type: "string", + enum: ["Email updated", "Verification email sent"], + description: "Status message of the email change process", + nullable: true + } + }, + required: ["status"] + } } } + }, + "422": { + description: "Unprocessable Entity. Email already exists", + content: { "application/json": { schema: { + type: "object", + properties: { message: { type: "string" } } + } } } + } + } + } } + }, async (ctx) => { + if (!ctx.context.options.user?.changeEmail?.enabled) { + ctx.context.logger.error("Change email is disabled."); + throw new APIError("BAD_REQUEST", { message: "Change email is disabled" }); + } + const newEmail = ctx.body.newEmail.toLowerCase(); + if (newEmail === ctx.context.session.user.email) { + ctx.context.logger.error("Email is the same"); + throw new APIError("BAD_REQUEST", { message: "Email is the same" }); + } + if (await ctx.context.internalAdapter.findUserByEmail(newEmail)) { + ctx.context.logger.error("Email already exists"); + throw new APIError("UNPROCESSABLE_ENTITY", { message: BASE_ERROR_CODES.USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL }); + } + if (ctx.context.session.user.emailVerified !== true && ctx.context.options.user.changeEmail.updateEmailWithoutVerification) { + await ctx.context.internalAdapter.updateUserByEmail(ctx.context.session.user.email, { email: newEmail }); + await setSessionCookie(ctx, { + session: ctx.context.session.session, + user: { + ...ctx.context.session.user, + email: newEmail + } + }); + if (ctx.context.options.emailVerification?.sendVerificationEmail) { + const token$1 = await createEmailVerificationToken(ctx.context.secret, newEmail, void 0, ctx.context.options.emailVerification?.expiresIn); + const url$1 = `${ctx.context.baseURL}/verify-email?token=${token$1}&callbackURL=${ctx.body.callbackURL || "/"}`; + await ctx.context.runInBackgroundOrAwait(ctx.context.options.emailVerification.sendVerificationEmail({ + user: { + ...ctx.context.session.user, + email: newEmail + }, + url: url$1, + token: token$1 + }, ctx.request)); + } + return ctx.json({ status: true }); + } + if (ctx.context.session.user.emailVerified && (ctx.context.options.user.changeEmail.sendChangeEmailConfirmation || ctx.context.options.user.changeEmail.sendChangeEmailVerification)) { + const token$1 = await createEmailVerificationToken(ctx.context.secret, ctx.context.session.user.email, newEmail, ctx.context.options.emailVerification?.expiresIn, { requestType: "change-email-confirmation" }); + const url$1 = `${ctx.context.baseURL}/verify-email?token=${token$1}&callbackURL=${ctx.body.callbackURL || "/"}`; + const sendFn = ctx.context.options.user.changeEmail.sendChangeEmailConfirmation || ctx.context.options.user.changeEmail.sendChangeEmailVerification; + if (sendFn) await ctx.context.runInBackgroundOrAwait(sendFn({ + user: ctx.context.session.user, + newEmail, + url: url$1, + token: token$1 + }, ctx.request)); + return ctx.json({ status: true }); + } + if (!ctx.context.options.emailVerification?.sendVerificationEmail) { + ctx.context.logger.error("Verification email isn't enabled."); + throw new APIError("BAD_REQUEST", { message: "Verification email isn't enabled" }); + } + const token = await createEmailVerificationToken(ctx.context.secret, ctx.context.session.user.email, newEmail, ctx.context.options.emailVerification?.expiresIn, { requestType: "change-email-verification" }); + const url2 = `${ctx.context.baseURL}/verify-email?token=${token}&callbackURL=${ctx.body.callbackURL || "/"}`; + await ctx.context.runInBackgroundOrAwait(ctx.context.options.emailVerification.sendVerificationEmail({ + user: { + ...ctx.context.session.user, + email: newEmail + }, + url: url2, + token + }, ctx.request)); + return ctx.json({ status: true }); + }); + } +}); + +// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/api/routes/index.mjs +var init_routes = __esm({ + "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/api/routes/index.mjs"() { + init_session4(); + init_account2(); + init_callback(); + init_email_verification(); + init_error3(); + init_ok(); + init_password3(); + init_sign_in(); + init_sign_out(); + init_sign_up(); + init_update_user(); + } +}); + +// node_modules/.pnpm/defu@6.1.7/node_modules/defu/dist/defu.mjs +function isPlainObject6(value) { + if (value === null || typeof value !== "object") { + return false; + } + const prototype = Object.getPrototypeOf(value); + if (prototype !== null && prototype !== Object.prototype && Object.getPrototypeOf(prototype) !== null) { + return false; + } + if (Symbol.iterator in value) { + return false; + } + if (Symbol.toStringTag in value) { + return Object.prototype.toString.call(value) === "[object Module]"; + } + return true; +} +function _defu(baseObject, defaults, namespace = ".", merger) { + if (!isPlainObject6(defaults)) { + return _defu(baseObject, {}, namespace, merger); + } + const object2 = { ...defaults }; + for (const key of Object.keys(baseObject)) { + if (key === "__proto__" || key === "constructor") { + continue; + } + const value = baseObject[key]; + if (value === null || value === void 0) { + continue; + } + if (merger && merger(object2, key, value, namespace)) { + continue; + } + if (Array.isArray(value) && Array.isArray(object2[key])) { + object2[key] = [...value, ...object2[key]]; + } else if (isPlainObject6(value) && isPlainObject6(object2[key])) { + object2[key] = _defu( + value, + object2[key], + (namespace ? `${namespace}.` : "") + key.toString(), + merger + ); + } else { + object2[key] = value; + } + } + return object2; +} +function createDefu(merger) { + return (...arguments_) => ( + // eslint-disable-next-line unicorn/no-array-reduce + arguments_.reduce((p5, c5) => _defu(p5, c5, "", merger), {}) + ); +} +var defu, defuFn, defuArrayFn; +var init_defu = __esm({ + "node_modules/.pnpm/defu@6.1.7/node_modules/defu/dist/defu.mjs"() { + defu = createDefu(); + defuFn = createDefu((object2, key, currentValue) => { + if (object2[key] !== void 0 && typeof currentValue === "function") { + object2[key] = currentValue(object2[key]); + return true; + } + }); + defuArrayFn = createDefu((object2, key, currentValue) => { + if (Array.isArray(object2[key]) && typeof currentValue === "function") { + object2[key] = currentValue(object2[key]); + return true; + } + }); + } +}); + +// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/api/to-auth-endpoints.mjs +function toAuthEndpoints(endpoints, ctx) { + const api = {}; + for (const [key, endpoint] of Object.entries(endpoints)) { + api[key] = async (context) => { + const run = async () => { + const authContext = await ctx; + let internalContext = { + ...context, + context: { + ...authContext, + returned: void 0, + responseHeaders: void 0, + session: null + }, + path: endpoint.path, + headers: context?.headers ? new Headers(context?.headers) : void 0 + }; + return runWithEndpointContext(internalContext, async () => { + const { beforeHooks, afterHooks } = getHooks(authContext); + const before = await runBeforeHooks(internalContext, beforeHooks); + if ("context" in before && before.context && typeof before.context === "object") { + const { headers, ...rest } = before.context; + if (headers) headers.forEach((value, key$1) => { + internalContext.headers.set(key$1, value); + }); + internalContext = defuReplaceArrays(rest, internalContext); + } else if (before) return context?.asResponse ? toResponse(before, { headers: context?.headers }) : context?.returnHeaders ? { + headers: context?.headers, + response: before + } : before; + internalContext.asResponse = false; + internalContext.returnHeaders = true; + internalContext.returnStatus = true; + const result = await runWithEndpointContext(internalContext, () => endpoint(internalContext)).catch((e5) => { + if (e5 instanceof APIError) + return { + response: e5, + status: e5.statusCode, + headers: e5.headers ? new Headers(e5.headers) : null + }; + throw e5; + }); + if (result && result instanceof Response) return result; + internalContext.context.returned = result.response; + internalContext.context.responseHeaders = result.headers; + const after = await runAfterHooks(internalContext, afterHooks); + if (after.response) result.response = after.response; + if (result.response instanceof APIError && shouldPublishLog(authContext.logger.level, "debug")) result.response.stack = result.response.errorStack; + if (result.response instanceof APIError && !context?.asResponse) throw result.response; + return context?.asResponse ? toResponse(result.response, { + headers: result.headers, + status: result.status + }) : context?.returnHeaders ? context?.returnStatus ? { + headers: result.headers, + response: result.response, + status: result.status + } : { + headers: result.headers, + response: result.response + } : context?.returnStatus ? { + response: result.response, + status: result.status + } : result.response; + }); + }; + if (await hasRequestState()) return run(); + else return runWithRequestState(/* @__PURE__ */ new WeakMap(), run); + }; + api[key].path = endpoint.path; + api[key].options = endpoint.options; + } + return api; +} +async function runBeforeHooks(context, hooks) { + let modifiedContext = {}; + for (const hook of hooks) { + let matched = false; + try { + matched = hook.matcher(context); + } catch (error50) { + const hookSource = hooksSourceWeakMap.get(hook.handler) ?? "unknown"; + context.context.logger.error(`An error occurred during ${hookSource} hook matcher execution:`, error50); + throw new APIError("INTERNAL_SERVER_ERROR", { message: `An error occurred during hook matcher execution. Check the logs for more details.` }); + } + if (matched) { + const result = await hook.handler({ + ...context, + returnHeaders: false + }).catch((e5) => { + if (e5 instanceof APIError && shouldPublishLog(context.context.logger.level, "debug")) e5.stack = e5.errorStack; + throw e5; + }); + if (result && typeof result === "object") { + if ("context" in result && typeof result.context === "object") { + const { headers, ...rest } = result.context; + if (headers instanceof Headers) if (modifiedContext.headers) headers.forEach((value, key) => { + modifiedContext.headers?.set(key, value); + }); + else modifiedContext.headers = headers; + modifiedContext = defuReplaceArrays(rest, modifiedContext); + continue; + } + return result; + } + } + } + return { context: modifiedContext }; +} +async function runAfterHooks(context, hooks) { + for (const hook of hooks) if (hook.matcher(context)) { + const result = await hook.handler(context).catch((e5) => { + if (e5 instanceof APIError) { + if (shouldPublishLog(context.context.logger.level, "debug")) e5.stack = e5.errorStack; + return { + response: e5, + headers: e5.headers ? new Headers(e5.headers) : null + }; + } + throw e5; + }); + if (result.headers) result.headers.forEach((value, key) => { + if (!context.context.responseHeaders) context.context.responseHeaders = new Headers({ [key]: value }); + else if (key.toLowerCase() === "set-cookie") context.context.responseHeaders.append(key, value); + else context.context.responseHeaders.set(key, value); + }); + if (result.response) context.context.returned = result.response; + } + return { + response: context.context.returned, + headers: context.context.responseHeaders + }; +} +function getHooks(authContext) { + const plugins2 = authContext.options.plugins || []; + const beforeHooks = []; + const afterHooks = []; + const beforeHookHandler = authContext.options.hooks?.before; + if (beforeHookHandler) { + hooksSourceWeakMap.set(beforeHookHandler, "user"); + beforeHooks.push({ + matcher: () => true, + handler: beforeHookHandler + }); + } + const afterHookHandler = authContext.options.hooks?.after; + if (afterHookHandler) { + hooksSourceWeakMap.set(afterHookHandler, "user"); + afterHooks.push({ + matcher: () => true, + handler: afterHookHandler + }); + } + const pluginBeforeHooks = plugins2.filter((plugin) => plugin.hooks?.before).map((plugin) => plugin.hooks?.before).flat(); + const pluginAfterHooks = plugins2.filter((plugin) => plugin.hooks?.after).map((plugin) => plugin.hooks?.after).flat(); + if (pluginBeforeHooks.length) beforeHooks.push(...pluginBeforeHooks); + if (pluginAfterHooks.length) afterHooks.push(...pluginAfterHooks); + return { + beforeHooks, + afterHooks + }; +} +var defuReplaceArrays, hooksSourceWeakMap; +var init_to_auth_endpoints = __esm({ + "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/api/to-auth-endpoints.mjs"() { + init_context2(); + init_env(); + init_dist3(); + init_defu(); + defuReplaceArrays = createDefu((obj, key, value) => { + if (Array.isArray(obj[key]) && Array.isArray(value)) { + obj[key] = value; + return true; + } + }); + hooksSourceWeakMap = /* @__PURE__ */ new WeakMap(); + } +}); + +// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/api/index.mjs +function checkEndpointConflicts(options, logger$1) { + const endpointRegistry = /* @__PURE__ */ new Map(); + options.plugins?.forEach((plugin) => { + if (plugin.endpoints) { + for (const [key, endpoint] of Object.entries(plugin.endpoints)) if (endpoint && "path" in endpoint && typeof endpoint.path === "string") { + const path53 = endpoint.path; + let methods2 = []; + if (endpoint.options && "method" in endpoint.options) { + if (Array.isArray(endpoint.options.method)) methods2 = endpoint.options.method; + else if (typeof endpoint.options.method === "string") methods2 = [endpoint.options.method]; + } + if (methods2.length === 0) methods2 = ["*"]; + if (!endpointRegistry.has(path53)) endpointRegistry.set(path53, []); + endpointRegistry.get(path53).push({ + pluginId: plugin.id, + endpointKey: key, + methods: methods2 + }); + } + } + }); + const conflicts = []; + for (const [path53, entries2] of endpointRegistry.entries()) if (entries2.length > 1) { + const methodMap = /* @__PURE__ */ new Map(); + let hasConflict = false; + for (const entry of entries2) for (const method of entry.methods) { + if (!methodMap.has(method)) methodMap.set(method, []); + methodMap.get(method).push(entry.pluginId); + if (methodMap.get(method).length > 1) hasConflict = true; + if (method === "*" && entries2.length > 1) hasConflict = true; + else if (method !== "*" && methodMap.has("*")) hasConflict = true; + } + if (hasConflict) { + const uniquePlugins = [...new Set(entries2.map((e5) => e5.pluginId))]; + const conflictingMethods = []; + for (const [method, plugins2] of methodMap.entries()) if (plugins2.length > 1 || method === "*" && entries2.length > 1 || method !== "*" && methodMap.has("*")) conflictingMethods.push(method); + conflicts.push({ + path: path53, + plugins: uniquePlugins, + conflictingMethods + }); + } + } + if (conflicts.length > 0) { + const conflictMessages = conflicts.map((conflict2) => ` - "${conflict2.path}" [${conflict2.conflictingMethods.join(", ")}] used by plugins: ${conflict2.plugins.join(", ")}`).join("\n"); + logger$1.error(`Endpoint path conflicts detected! Multiple plugins are trying to use the same endpoint paths with conflicting HTTP methods: +${conflictMessages} + +To resolve this, you can: + 1. Use only one of the conflicting plugins + 2. Configure the plugins to use different paths (if supported) + 3. Ensure plugins use different HTTP methods for the same path +`); + } +} +function getEndpoints(ctx, options) { + const pluginEndpoints = options.plugins?.reduce((acc, plugin) => { + return { + ...acc, + ...plugin.endpoints + }; + }, {}) ?? {}; + const middlewares = options.plugins?.map((plugin) => plugin.middlewares?.map((m5) => { + const middleware = (async (context) => { + const authContext = await ctx; + return m5.middleware({ + ...context, + context: { + ...authContext, + ...context.context + } + }); + }); + middleware.options = m5.middleware.options; + return { + path: m5.path, + middleware + }; + })).filter((plugin) => plugin !== void 0).flat() || []; + return { + api: toAuthEndpoints({ + signInSocial: signInSocial(), + callbackOAuth, + getSession: getSession(), + signOut, + signUpEmail: signUpEmail(), + signInEmail: signInEmail(), + resetPassword, + verifyPassword: verifyPassword2, + verifyEmail, + sendVerificationEmail, + changeEmail, + changePassword, + setPassword, + updateUser: updateUser(), + deleteUser, + requestPasswordReset, + requestPasswordResetCallback, + listSessions: listSessions(), + revokeSession, + revokeSessions, + revokeOtherSessions, + linkSocialAccount, + listUserAccounts, + deleteUserCallback, + unlinkAccount, + refreshToken, + getAccessToken, + accountInfo, + ...pluginEndpoints, + ok, + error: error49 + }, ctx), + middlewares + }; +} +var router; +var init_api3 = __esm({ + "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/api/index.mjs"() { + init_get_request_ip(); + init_oauth(); + init_origin_check(); + init_middlewares(); + init_rate_limiter(); + init_session4(); + init_account2(); + init_callback(); + init_email_verification(); + init_error3(); + init_ok(); + init_password3(); + init_sign_in(); + init_sign_out(); + init_sign_up(); + init_update_user(); + init_routes(); + init_to_auth_endpoints(); + init_env(); + init_utils7(); + init_dist3(); + init_api2(); + router = (ctx, options) => { + const { api, middlewares } = getEndpoints(ctx, options); + const basePath = new URL(ctx.baseURL).pathname; + return createRouter$1(api, { + routerContext: ctx, + openapi: { disabled: true }, + basePath, + routerMiddleware: [{ + path: "/**", + middleware: originCheckMiddleware + }, ...middlewares], + allowedMediaTypes: ["application/json"], + skipTrailingSlashes: options.advanced?.skipTrailingSlashes ?? false, + async onRequest(req) { + const disabledPaths = ctx.options.disabledPaths || []; + const normalizedPath = normalizePathname(req.url, basePath); + if (disabledPaths.includes(normalizedPath)) return new Response("Not Found", { status: 404 }); + let currentRequest = req; + for (const plugin of ctx.options.plugins || []) if (plugin.onRequest) { + const response = await plugin.onRequest(currentRequest, ctx); + if (response && "response" in response) return response.response; + if (response && "request" in response) currentRequest = response.request; + } + const rateLimitResponse2 = await onRequestRateLimit(currentRequest, ctx); + if (rateLimitResponse2) return rateLimitResponse2; + return currentRequest; + }, + async onResponse(res) { + for (const plugin of ctx.options.plugins || []) if (plugin.onResponse) { + const response = await plugin.onResponse(res, ctx); + if (response) return response.response; + } + return res; + }, + onError(e5) { + if (e5 instanceof APIError && e5.status === "FOUND") return; + if (options.onAPIError?.throw) throw e5; + if (options.onAPIError?.onError) { + options.onAPIError.onError(e5, ctx); + return; + } + const optLogLevel = options.logger?.level; + const log2 = optLogLevel === "error" || optLogLevel === "warn" || optLogLevel === "debug" ? logger3 : void 0; + if (options.logger?.disabled !== true) { + if (e5 && typeof e5 === "object" && "message" in e5 && typeof e5.message === "string") { + if (e5.message.includes("no column") || e5.message.includes("column") || e5.message.includes("relation") || e5.message.includes("table") || e5.message.includes("does not exist")) { + ctx.logger?.error(e5.message); + return; + } + } + if (e5 instanceof APIError) { + if (e5.status === "INTERNAL_SERVER_ERROR") ctx.logger.error(e5.status, e5); + log2?.error(e5.message); + } else ctx.logger?.error(e5 && typeof e5 === "object" && "name" in e5 ? e5.name : "", e5); + } + } + }); + }; + } +}); + +// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/utils/constants.mjs +var DEFAULT_SECRET; +var init_constants = __esm({ + "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/utils/constants.mjs"() { + DEFAULT_SECRET = "better-auth-secret-12345678901234567890"; + } +}); + +// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/context/helpers.mjs +async function runPluginInit(ctx) { + let options = ctx.options; + const plugins2 = options.plugins || []; + let context = ctx; + const dbHooks = []; + for (const plugin of plugins2) if (plugin.init) { + const initPromise = plugin.init(context); + let result; + if (isPromise(initPromise)) result = await initPromise; + else result = initPromise; + if (typeof result === "object") { + if (result.options) { + const { databaseHooks, ...restOpts } = result.options; + if (databaseHooks) dbHooks.push(databaseHooks); + options = defu(options, restOpts); + } + if (result.context) context = { + ...context, + ...result.context + }; + } + } + dbHooks.push(options.databaseHooks); + context.internalAdapter = createInternalAdapter(context.adapter, { + options, + logger: context.logger, + hooks: dbHooks.filter((u5) => u5 !== void 0), + generateId: context.generateId + }); + context.options = options; + return { context }; +} +function getInternalPlugins(options) { + const plugins2 = []; + if (options.advanced?.crossSubDomainCookies?.enabled) { + } + return plugins2; +} +async function getTrustedOrigins(options, request) { + const baseURL = getBaseURL(options.baseURL, options.basePath, request); + const trustedOrigins = baseURL ? [new URL(baseURL).origin] : []; + if (options.trustedOrigins) { + if (Array.isArray(options.trustedOrigins)) trustedOrigins.push(...options.trustedOrigins); + if (typeof options.trustedOrigins === "function") { + const validOrigins = await options.trustedOrigins(request); + trustedOrigins.push(...validOrigins); + } + } + const envTrustedOrigins = env.BETTER_AUTH_TRUSTED_ORIGINS; + if (envTrustedOrigins) trustedOrigins.push(...envTrustedOrigins.split(",")); + return trustedOrigins.filter((v5) => Boolean(v5)); +} +var init_helpers2 = __esm({ + "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/context/helpers.mjs"() { + init_internal_adapter(); + init_url2(); + init_is_promise(); + init_env(); + init_defu(); + } +}); + +// node_modules/.pnpm/@better-auth+telemetry@1.4.18_@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch_psxvmkd33sibviw74qwagmhkji/node_modules/@better-auth/telemetry/dist/index.mjs +function getTelemetryAuthConfig(options, context) { + return { + database: context?.database, + adapter: context?.adapter, + emailVerification: { + sendVerificationEmail: !!options.emailVerification?.sendVerificationEmail, + sendOnSignUp: !!options.emailVerification?.sendOnSignUp, + sendOnSignIn: !!options.emailVerification?.sendOnSignIn, + autoSignInAfterVerification: !!options.emailVerification?.autoSignInAfterVerification, + expiresIn: options.emailVerification?.expiresIn, + onEmailVerification: !!options.emailVerification?.onEmailVerification, + afterEmailVerification: !!options.emailVerification?.afterEmailVerification + }, + emailAndPassword: { + enabled: !!options.emailAndPassword?.enabled, + disableSignUp: !!options.emailAndPassword?.disableSignUp, + requireEmailVerification: !!options.emailAndPassword?.requireEmailVerification, + maxPasswordLength: options.emailAndPassword?.maxPasswordLength, + minPasswordLength: options.emailAndPassword?.minPasswordLength, + sendResetPassword: !!options.emailAndPassword?.sendResetPassword, + resetPasswordTokenExpiresIn: options.emailAndPassword?.resetPasswordTokenExpiresIn, + onPasswordReset: !!options.emailAndPassword?.onPasswordReset, + password: { + hash: !!options.emailAndPassword?.password?.hash, + verify: !!options.emailAndPassword?.password?.verify + }, + autoSignIn: !!options.emailAndPassword?.autoSignIn, + revokeSessionsOnPasswordReset: !!options.emailAndPassword?.revokeSessionsOnPasswordReset + }, + socialProviders: Object.keys(options.socialProviders || {}).map((p5) => { + const provider = options.socialProviders?.[p5]; + if (!provider) return {}; + return { + id: p5, + mapProfileToUser: !!provider.mapProfileToUser, + disableDefaultScope: !!provider.disableDefaultScope, + disableIdTokenSignIn: !!provider.disableIdTokenSignIn, + disableImplicitSignUp: provider.disableImplicitSignUp, + disableSignUp: provider.disableSignUp, + getUserInfo: !!provider.getUserInfo, + overrideUserInfoOnSignIn: !!provider.overrideUserInfoOnSignIn, + prompt: provider.prompt, + verifyIdToken: !!provider.verifyIdToken, + scope: provider.scope, + refreshAccessToken: !!provider.refreshAccessToken + }; + }), + plugins: options.plugins?.map((p5) => p5.id.toString()), + user: { + modelName: options.user?.modelName, + fields: options.user?.fields, + additionalFields: options.user?.additionalFields, + changeEmail: { + enabled: options.user?.changeEmail?.enabled, + sendChangeEmailVerification: !!options.user?.changeEmail?.sendChangeEmailVerification + } + }, + verification: { + modelName: options.verification?.modelName, + disableCleanup: options.verification?.disableCleanup, + fields: options.verification?.fields + }, + session: { + modelName: options.session?.modelName, + additionalFields: options.session?.additionalFields, + cookieCache: { + enabled: options.session?.cookieCache?.enabled, + maxAge: options.session?.cookieCache?.maxAge, + strategy: options.session?.cookieCache?.strategy + }, + disableSessionRefresh: options.session?.disableSessionRefresh, + expiresIn: options.session?.expiresIn, + fields: options.session?.fields, + freshAge: options.session?.freshAge, + preserveSessionInDatabase: options.session?.preserveSessionInDatabase, + storeSessionInDatabase: options.session?.storeSessionInDatabase, + updateAge: options.session?.updateAge + }, + account: { + modelName: options.account?.modelName, + fields: options.account?.fields, + encryptOAuthTokens: options.account?.encryptOAuthTokens, + updateAccountOnSignIn: options.account?.updateAccountOnSignIn, + accountLinking: { + enabled: options.account?.accountLinking?.enabled, + trustedProviders: options.account?.accountLinking?.trustedProviders, + updateUserInfoOnLink: options.account?.accountLinking?.updateUserInfoOnLink, + allowUnlinkingAll: options.account?.accountLinking?.allowUnlinkingAll + } + }, + hooks: { + after: !!options.hooks?.after, + before: !!options.hooks?.before + }, + secondaryStorage: !!options.secondaryStorage, + advanced: { + cookiePrefix: !!options.advanced?.cookiePrefix, + cookies: !!options.advanced?.cookies, + crossSubDomainCookies: { + domain: !!options.advanced?.crossSubDomainCookies?.domain, + enabled: options.advanced?.crossSubDomainCookies?.enabled, + additionalCookies: options.advanced?.crossSubDomainCookies?.additionalCookies + }, + database: { + useNumberId: !!options.advanced?.database?.useNumberId || options.advanced?.database?.generateId === "serial", + generateId: options.advanced?.database?.generateId, + defaultFindManyLimit: options.advanced?.database?.defaultFindManyLimit + }, + useSecureCookies: options.advanced?.useSecureCookies, + ipAddress: { + disableIpTracking: options.advanced?.ipAddress?.disableIpTracking, + ipAddressHeaders: options.advanced?.ipAddress?.ipAddressHeaders + }, + disableCSRFCheck: options.advanced?.disableCSRFCheck, + cookieAttributes: { + expires: options.advanced?.defaultCookieAttributes?.expires, + secure: options.advanced?.defaultCookieAttributes?.secure, + sameSite: options.advanced?.defaultCookieAttributes?.sameSite, + domain: !!options.advanced?.defaultCookieAttributes?.domain, + path: options.advanced?.defaultCookieAttributes?.path, + httpOnly: options.advanced?.defaultCookieAttributes?.httpOnly + } + }, + trustedOrigins: options.trustedOrigins?.length, + rateLimit: { + storage: options.rateLimit?.storage, + modelName: options.rateLimit?.modelName, + window: options.rateLimit?.window, + customStorage: !!options.rateLimit?.customStorage, + enabled: options.rateLimit?.enabled, + max: options.rateLimit?.max + }, + onAPIError: { + errorURL: options.onAPIError?.errorURL, + onError: !!options.onAPIError?.onError, + throw: options.onAPIError?.throw + }, + logger: { + disabled: options.logger?.disabled, + level: options.logger?.level, + log: !!options.logger?.log + }, + databaseHooks: { + user: { + create: { + after: !!options.databaseHooks?.user?.create?.after, + before: !!options.databaseHooks?.user?.create?.before + }, + update: { + after: !!options.databaseHooks?.user?.update?.after, + before: !!options.databaseHooks?.user?.update?.before + } + }, + session: { + create: { + after: !!options.databaseHooks?.session?.create?.after, + before: !!options.databaseHooks?.session?.create?.before + }, + update: { + after: !!options.databaseHooks?.session?.update?.after, + before: !!options.databaseHooks?.session?.update?.before + } + }, + account: { + create: { + after: !!options.databaseHooks?.account?.create?.after, + before: !!options.databaseHooks?.account?.create?.before + }, + update: { + after: !!options.databaseHooks?.account?.update?.after, + before: !!options.databaseHooks?.account?.update?.before + } + }, + verification: { + create: { + after: !!options.databaseHooks?.verification?.create?.after, + before: !!options.databaseHooks?.verification?.create?.before + }, + update: { + after: !!options.databaseHooks?.verification?.update?.after, + before: !!options.databaseHooks?.verification?.update?.before + } + } + } + }; +} +async function readRootPackageJson() { + if (packageJSONCache) return packageJSONCache; + try { + const cwd = typeof process !== "undefined" && typeof process.cwd === "function" ? process.cwd() : ""; + if (!cwd) return void 0; + const importRuntime$1 = (m5) => Function("mm", "return import(mm)")(m5); + const [{ default: fs41 }, { default: path53 }] = await Promise.all([importRuntime$1("fs/promises"), importRuntime$1("path")]); + const raw = await fs41.readFile(path53.join(cwd, "package.json"), "utf-8"); + packageJSONCache = JSON.parse(raw); + return packageJSONCache; + } catch { + } +} +async function getPackageVersion(pkg2) { + if (packageJSONCache) return packageJSONCache.dependencies?.[pkg2] || packageJSONCache.devDependencies?.[pkg2] || packageJSONCache.peerDependencies?.[pkg2]; + try { + const cwd = typeof process !== "undefined" && typeof process.cwd === "function" ? process.cwd() : ""; + if (!cwd) throw new Error("no-cwd"); + const importRuntime$1 = (m5) => Function("mm", "return import(mm)")(m5); + const [{ default: fs41 }, { default: path53 }] = await Promise.all([importRuntime$1("fs/promises"), importRuntime$1("path")]); + const pkgJsonPath = path53.join(cwd, "node_modules", pkg2, "package.json"); + const raw = await fs41.readFile(pkgJsonPath, "utf-8"); + return JSON.parse(raw).version || await getVersionFromLocalPackageJson(pkg2) || void 0; + } catch { + } + return await getVersionFromLocalPackageJson(pkg2); +} +async function getVersionFromLocalPackageJson(pkg2) { + const json3 = await readRootPackageJson(); + if (!json3) return void 0; + return { + ...json3.dependencies, + ...json3.devDependencies, + ...json3.peerDependencies + }[pkg2]; +} +async function getNameFromLocalPackageJson() { + return (await readRootPackageJson())?.name; +} +async function detectDatabase() { + for (const [pkg2, name] of Object.entries(DATABASES)) { + const version3 = await getPackageVersion(pkg2); + if (version3) return { + name, + version: version3 + }; + } +} +async function detectFramework() { + for (const [pkg2, name] of Object.entries(FRAMEWORKS)) { + const version3 = await getPackageVersion(pkg2); + if (version3) return { + name, + version: version3 + }; + } +} +function detectPackageManager() { + const userAgent = env.npm_config_user_agent; + if (!userAgent) return; + const pmSpec = userAgent.split(" ")[0]; + const separatorPos = pmSpec.lastIndexOf("/"); + const name = pmSpec.substring(0, separatorPos); + return { + name: name === "npminstall" ? "cnpm" : name, + version: pmSpec.substring(separatorPos + 1) + }; +} +function getVendor() { + const hasAny = (...keys) => keys.some((k5) => Boolean(env[k5])); + if (hasAny("CF_PAGES", "CF_PAGES_URL", "CF_ACCOUNT_ID") || typeof navigator !== "undefined" && navigator.userAgent === "Cloudflare-Workers") return "cloudflare"; + if (hasAny("VERCEL", "VERCEL_URL", "VERCEL_ENV")) return "vercel"; + if (hasAny("NETLIFY", "NETLIFY_URL")) return "netlify"; + if (hasAny("RENDER", "RENDER_URL", "RENDER_INTERNAL_HOSTNAME", "RENDER_SERVICE_ID")) return "render"; + if (hasAny("AWS_LAMBDA_FUNCTION_NAME", "AWS_EXECUTION_ENV", "LAMBDA_TASK_ROOT")) return "aws"; + if (hasAny("GOOGLE_CLOUD_FUNCTION_NAME", "GOOGLE_CLOUD_PROJECT", "GCP_PROJECT", "K_SERVICE")) return "gcp"; + if (hasAny("AZURE_FUNCTION_NAME", "FUNCTIONS_WORKER_RUNTIME", "WEBSITE_INSTANCE_ID", "WEBSITE_SITE_NAME")) return "azure"; + if (hasAny("DENO_DEPLOYMENT_ID", "DENO_REGION")) return "deno-deploy"; + if (hasAny("FLY_APP_NAME", "FLY_REGION", "FLY_ALLOC_ID")) return "fly-io"; + if (hasAny("RAILWAY_STATIC_URL", "RAILWAY_ENVIRONMENT_NAME")) return "railway"; + if (hasAny("DYNO", "HEROKU_APP_NAME")) return "heroku"; + if (hasAny("DO_DEPLOYMENT_ID", "DO_APP_NAME", "DIGITALOCEAN")) return "digitalocean"; + if (hasAny("KOYEB", "KOYEB_DEPLOYMENT_ID", "KOYEB_APP_NAME")) return "koyeb"; + return null; +} +async function detectSystemInfo() { + try { + if (getVendor() === "cloudflare") return "cloudflare"; + const os24 = await importRuntime("os"); + const cpus = os24.cpus(); + return { + deploymentVendor: getVendor(), + systemPlatform: os24.platform(), + systemRelease: os24.release(), + systemArchitecture: os24.arch(), + cpuCount: cpus.length, + cpuModel: cpus.length ? cpus[0].model : null, + cpuSpeed: cpus.length ? cpus[0].speed : null, + memory: os24.totalmem(), + isWSL: await isWsl(), + isDocker: await isDocker(), + isTTY: typeof process !== "undefined" && process.stdout ? process.stdout.isTTY : null + }; + } catch { + return { + systemPlatform: null, + systemRelease: null, + systemArchitecture: null, + cpuCount: null, + cpuModel: null, + cpuSpeed: null, + memory: null, + isWSL: null, + isDocker: null, + isTTY: null + }; + } +} +async function hasDockerEnv() { + if (getVendor() === "cloudflare") return false; + try { + (await importRuntime("fs")).statSync("/.dockerenv"); + return true; + } catch { + return false; + } +} +async function hasDockerCGroup() { + if (getVendor() === "cloudflare") return false; + try { + return (await importRuntime("fs")).readFileSync("/proc/self/cgroup", "utf8").includes("docker"); + } catch { + return false; + } +} +async function isDocker() { + if (getVendor() === "cloudflare") return false; + if (isDockerCached === void 0) isDockerCached = await hasDockerEnv() || await hasDockerCGroup(); + return isDockerCached; +} +async function isWsl() { + try { + if (getVendor() === "cloudflare") return false; + if (typeof process === "undefined" || process?.platform !== "linux") return false; + const fs41 = await importRuntime("fs"); + if ((await importRuntime("os")).release().toLowerCase().includes("microsoft")) { + if (await isInsideContainer()) return false; + return true; + } + return fs41.readFileSync("/proc/version", "utf8").toLowerCase().includes("microsoft") ? !await isInsideContainer() : false; + } catch { + return false; + } +} +async function isInsideContainer() { + if (isInsideContainerCached === void 0) isInsideContainerCached = await hasContainerEnv() || await isDocker(); + return isInsideContainerCached; +} +function isCI() { + return env.CI !== "false" && ("BUILD_ID" in env || "BUILD_NUMBER" in env || "CI" in env || "CI_APP_ID" in env || "CI_BUILD_ID" in env || "CI_BUILD_NUMBER" in env || "CI_NAME" in env || "CONTINUOUS_INTEGRATION" in env || "RUN_ID" in env); +} +function detectRuntime() { + if (typeof Deno !== "undefined") return { + name: "deno", + version: Deno?.version?.deno ?? null + }; + if (typeof Bun !== "undefined") return { + name: "bun", + version: Bun?.version ?? null + }; + if (typeof process !== "undefined" && process?.versions?.node) return { + name: "node", + version: process.versions.node ?? null + }; + return { + name: "edge", + version: null + }; +} +function detectEnvironment() { + return getEnvVar("NODE_ENV") === "production" ? "production" : isCI() ? "ci" : isTest() ? "test" : "development"; +} +async function hashToBase64(data2) { + const buffer2 = await createHash17("SHA-256").digest(data2); + return base643.encode(buffer2); +} +async function getProjectId(baseUrl) { + if (projectIdCached) return projectIdCached; + const projectName = await getNameFromLocalPackageJson(); + if (projectName) { + projectIdCached = await hashToBase64(baseUrl ? baseUrl + projectName : projectName); + return projectIdCached; + } + if (baseUrl) { + projectIdCached = await hashToBase64(baseUrl); + return projectIdCached; + } + projectIdCached = generateId2(32); + return projectIdCached; +} +async function createTelemetry(options, context) { + const debugEnabled = options.telemetry?.debug || getBooleanEnvVar("BETTER_AUTH_TELEMETRY_DEBUG", false); + const telemetryEndpoint = ENV.BETTER_AUTH_TELEMETRY_ENDPOINT; + if (!telemetryEndpoint && !context?.customTrack) return { publish: noop4 }; + const track = async (event) => { + if (context?.customTrack) await context.customTrack(event).catch(logger3.error); + else if (telemetryEndpoint) if (debugEnabled) logger3.info("telemetry event", JSON.stringify(event, null, 2)); + else await betterFetch(telemetryEndpoint, { + method: "POST", + body: event + }).catch(logger3.error); + }; + const isEnabled = async () => { + const telemetryEnabled = options.telemetry?.enabled !== void 0 ? options.telemetry.enabled : false; + return (getBooleanEnvVar("BETTER_AUTH_TELEMETRY", false) || telemetryEnabled) && (context?.skipTestCheck || !isTest()); + }; + const enabled = await isEnabled(); + let anonymousId; + if (enabled) { + anonymousId = await getProjectId(options.baseURL); + track({ + type: "init", + payload: { + config: getTelemetryAuthConfig(options, context), + runtime: detectRuntime(), + database: await detectDatabase(), + framework: await detectFramework(), + environment: detectEnvironment(), + systemInfo: await detectSystemInfo(), + packageManager: detectPackageManager() + }, + anonymousId + }); + } + return { publish: async (event) => { + if (!enabled) return; + if (!anonymousId) anonymousId = await getProjectId(options.baseURL); + await track({ + type: event.type, + payload: event.payload, + anonymousId + }); + } }; +} +var packageJSONCache, DATABASES, FRAMEWORKS, importRuntime, isDockerCached, isInsideContainerCached, hasContainerEnv, generateId2, projectIdCached, noop4; +var init_dist5 = __esm({ + "node_modules/.pnpm/@better-auth+telemetry@1.4.18_@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch_psxvmkd33sibviw74qwagmhkji/node_modules/@better-auth/telemetry/dist/index.mjs"() { + init_env(); + init_dist4(); + init_base642(); + init_hash(); + init_random(); + DATABASES = { + pg: "postgresql", + mysql: "mysql", + mariadb: "mariadb", + sqlite3: "sqlite", + "better-sqlite3": "sqlite", + "@prisma/client": "prisma", + mongoose: "mongodb", + mongodb: "mongodb", + "drizzle-orm": "drizzle" + }; + FRAMEWORKS = { + next: "next", + nuxt: "nuxt", + "@remix-run/server-runtime": "remix", + astro: "astro", + "@sveltejs/kit": "sveltekit", + "solid-start": "solid-start", + "tanstack-start": "tanstack-start", + hono: "hono", + express: "express", + elysia: "elysia", + expo: "expo" + }; + importRuntime = (m5) => { + return Function("mm", "return import(mm)")(m5); + }; + hasContainerEnv = async () => { + if (getVendor() === "cloudflare") return false; + try { + (await importRuntime("fs")).statSync("/run/.containerenv"); + return true; + } catch { + return false; + } + }; + generateId2 = (size2) => { + return createRandomStringGenerator("a-z", "A-Z", "0-9")(size2 || 32); + }; + projectIdCached = null; + noop4 = async function noop$1() { + }; + } +}); + +// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/context/create-context.mjs +function estimateEntropy(str) { + const unique2 = new Set(str).size; + if (unique2 === 0) return 0; + return Math.log2(Math.pow(unique2, str.length)); +} +function validateSecret(secret, logger$1) { + const isDefaultSecret = secret === DEFAULT_SECRET; + if (isTest()) return; + if (isDefaultSecret && isProduction) throw new BetterAuthError("You are using the default secret. Please set `BETTER_AUTH_SECRET` in your environment variables or pass `secret` in your auth config."); + if (!secret) throw new BetterAuthError("BETTER_AUTH_SECRET is missing. Set it in your environment or pass `secret` to betterAuth({ secret })."); + if (secret.length < 32) logger$1.warn(`[better-auth] Warning: your BETTER_AUTH_SECRET should be at least 32 characters long for adequate security. Generate one with \`npx @better-auth/cli secret\` or \`openssl rand -base64 32\`.`); + if (estimateEntropy(secret) < 120) logger$1.warn("[better-auth] Warning: your BETTER_AUTH_SECRET appears low-entropy. Use a randomly generated secret for production."); +} +async function createAuthContext(adapter, options, getDatabaseType) { + if (!options.database) options = defu(options, { + session: { cookieCache: { + enabled: true, + strategy: "jwe", + refreshCache: true + } }, + account: { + storeStateStrategy: "cookie", + storeAccountCookie: true + } + }); + const plugins2 = options.plugins || []; + const internalPlugins = getInternalPlugins(options); + const logger$1 = createLogger(options.logger); + const baseURL = getBaseURL(options.baseURL, options.basePath); + if (!baseURL) logger$1.warn(`[better-auth] Base URL could not be determined. Please set a valid base URL using the baseURL config option or the BETTER_AUTH_BASE_URL environment variable. Without this, callbacks and redirects may not work correctly.`); + if (adapter.id === "memory" && options.advanced?.database?.generateId === false) logger$1.error(`[better-auth] Misconfiguration detected. +You are using the memory DB with generateId: false. +This will cause no id to be generated for any model. +Most of the features of Better Auth will not work correctly.`); + const secret = options.secret || env.BETTER_AUTH_SECRET || env.AUTH_SECRET || DEFAULT_SECRET; + validateSecret(secret, logger$1); + options = { + ...options, + secret, + baseURL: baseURL ? new URL(baseURL).origin : "", + basePath: options.basePath || "/api/auth", + plugins: plugins2.concat(internalPlugins) + }; + checkEndpointConflicts(options, logger$1); + const cookies = getCookies(options); + const tables = getAuthTables(options); + const providers2 = Object.entries(options.socialProviders || {}).map(([key, config3]) => { + if (config3 == null) return null; + if (config3.enabled === false) return null; + if (!config3.clientId) logger$1.warn(`Social provider ${key} is missing clientId or clientSecret`); + const provider = socialProviders[key](config3); + provider.disableImplicitSignUp = config3.disableImplicitSignUp; + return provider; + }).filter((x5) => x5 !== null); + const generateIdFunc = ({ model, size: size2 }) => { + if (typeof options.advanced?.generateId === "function") return options.advanced.generateId({ + model, + size: size2 + }); + const dbGenerateId = options?.advanced?.database?.generateId; + if (typeof dbGenerateId === "function") return dbGenerateId({ + model, + size: size2 + }); + if (dbGenerateId === "uuid") return crypto.randomUUID(); + if (dbGenerateId === "serial" || dbGenerateId === false) return false; + return generateId(size2); + }; + const { publish } = await createTelemetry(options, { + adapter: adapter.id, + database: typeof options.database === "function" ? "adapter" : getDatabaseType(options.database) + }); + const trustedOrigins = await getTrustedOrigins(options); + const initOrPromise = runPluginInit({ + appName: options.appName || "Better Auth", + baseURL: baseURL || "", + version: getBetterAuthVersion(), + socialProviders: providers2, + options, + oauthConfig: { + storeStateStrategy: options.account?.storeStateStrategy || (options.database ? "database" : "cookie"), + skipStateCookieCheck: !!options.account?.skipStateCookieCheck + }, + tables, + trustedOrigins, + isTrustedOrigin(url2, settings) { + return this.trustedOrigins.some((origin) => matchesOriginPattern(url2, origin, settings)); + }, + sessionConfig: { + updateAge: options.session?.updateAge !== void 0 ? options.session.updateAge : 1440 * 60, + expiresIn: options.session?.expiresIn || 3600 * 24 * 7, + freshAge: options.session?.freshAge === void 0 ? 3600 * 24 : options.session.freshAge, + cookieRefreshCache: (() => { + const refreshCache = options.session?.cookieCache?.refreshCache; + const maxAge = options.session?.cookieCache?.maxAge || 300; + if ((!!options.database || !!options.secondaryStorage) && refreshCache) { + logger$1.warn("[better-auth] `session.cookieCache.refreshCache` is enabled while `database` or `secondaryStorage` is configured. `refreshCache` is meant for stateless (DB-less) setups. Disabling `refreshCache` \u2014 remove it from your config to silence this warning."); + return false; + } + if (refreshCache === false || refreshCache === void 0) return false; + if (refreshCache === true) return { + enabled: true, + updateAge: Math.floor(maxAge * 0.2) + }; + return { + enabled: true, + updateAge: refreshCache.updateAge !== void 0 ? refreshCache.updateAge : Math.floor(maxAge * 0.2) + }; + })() + }, + secret, + rateLimit: { + ...options.rateLimit, + enabled: options.rateLimit?.enabled ?? isProduction, + window: options.rateLimit?.window || 10, + max: options.rateLimit?.max || 100, + storage: options.rateLimit?.storage || (options.secondaryStorage ? "secondary-storage" : "memory") + }, + authCookies: cookies, + logger: logger$1, + generateId: generateIdFunc, + session: null, + secondaryStorage: options.secondaryStorage, + password: { + hash: options.emailAndPassword?.password?.hash || hashPassword, + verify: options.emailAndPassword?.password?.verify || verifyPassword, + config: { + minPasswordLength: options.emailAndPassword?.minPasswordLength || 8, + maxPasswordLength: options.emailAndPassword?.maxPasswordLength || 128 + }, + checkPassword + }, + setNewSession(session) { + this.newSession = session; + }, + newSession: null, + adapter, + internalAdapter: createInternalAdapter(adapter, { + options, + logger: logger$1, + hooks: options.databaseHooks ? [options.databaseHooks] : [], + generateId: generateIdFunc + }), + createAuthCookie: createCookieGetter(options), + async runMigrations() { + throw new BetterAuthError("runMigrations will be set by the specific init implementation"); + }, + publishTelemetry: publish, + skipCSRFCheck: !!options.advanced?.disableCSRFCheck, + skipOriginCheck: options.advanced?.disableOriginCheck !== void 0 ? options.advanced.disableOriginCheck : isTest() ? true : false, + runInBackground: options.advanced?.backgroundTasks?.handler ?? ((p5) => { + p5.catch(() => { + }); + }), + async runInBackgroundOrAwait(promise2) { + try { + if (options.advanced?.backgroundTasks?.handler) { + if (promise2 instanceof Promise) options.advanced.backgroundTasks.handler(promise2.catch((e5) => { + logger$1.error("Failed to run background task:", e5); + })); + } else await promise2; + } catch (e5) { + logger$1.error("Failed to run background task:", e5); + } + }, + getPlugin: (id) => options.plugins.find((p5) => p5.id === id) ?? null + }); + let context; + if (isPromise(initOrPromise)) ({ context } = await initOrPromise); + else ({ context } = initOrPromise); + if (typeof context.options.emailVerification?.onEmailVerification === "function") context.options.emailVerification.onEmailVerification = deprecate(context.options.emailVerification.onEmailVerification, "Use `afterEmailVerification` instead. This will be removed in 1.5", context.logger); + return context; +} +var init_create_context = __esm({ + "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/context/create-context.mjs"() { + init_internal_adapter(); + init_url2(); + init_trusted_origins(); + init_password(); + init_is_promise(); + init_cookies2(); + init_utils10(); + init_password2(); + init_api3(); + init_constants(); + init_helpers2(); + init_context2(); + init_db3(); + init_env(); + init_error(); + init_utils7(); + init_social_providers(); + init_dist5(); + init_defu(); + } +}); + +// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/context/init.mjs +var init; +var init_init = __esm({ + "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/context/init.mjs"() { + init_dialect3(); + init_adapter_kysely(); + init_get_migration(); + init_create_context(); + init_error(); + init = async (options) => { + const adapter = await getAdapter(options); + const getDatabaseType = (database) => getKyselyDatabaseType(database) || "unknown"; + const ctx = await createAuthContext(adapter, options, getDatabaseType); + ctx.runMigrations = async function() { + if (!options.database || "updateMany" in options.database) throw new BetterAuthError("Database is not provided or it's an adapter. Migrations are only supported with a database instance."); + const { runMigrations } = await getMigrations(options); + await runMigrations(); + }; + return ctx; + }; + } +}); + +// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/auth/base.mjs +var createBetterAuth; +var init_base = __esm({ + "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/auth/base.mjs"() { + init_url2(); + init_api3(); + init_helpers2(); + init_context2(); + init_error(); + createBetterAuth = (options, initFn) => { + const authContext = initFn(options); + const { api } = getEndpoints(authContext, options); + return { + handler: async (request) => { + const ctx = await authContext; + const basePath = ctx.options.basePath || "/api/auth"; + if (!ctx.options.baseURL) { + const baseURL = getBaseURL(void 0, basePath, request, void 0, ctx.options.advanced?.trustedProxyHeaders); + if (baseURL) { + ctx.baseURL = baseURL; + ctx.options.baseURL = getOrigin(ctx.baseURL) || void 0; + } else throw new BetterAuthError("Could not get base URL from request. Please provide a valid base URL."); + } + ctx.trustedOrigins = await getTrustedOrigins(ctx.options, request); + const { handler } = router(ctx, options); + return runWithAdapter(ctx.adapter, () => handler(request)); + }, + api, + options, + $context: authContext, + $ERROR_CODES: { + ...options.plugins?.reduce((acc, plugin) => { + if (plugin.$ERROR_CODES) return { + ...acc, + ...plugin.$ERROR_CODES + }; + return acc; + }, {}), + ...BASE_ERROR_CODES + } + }; + }; + } +}); + +// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/auth/full.mjs +var betterAuth; +var init_full = __esm({ + "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/auth/full.mjs"() { + init_init(); + init_base(); + betterAuth = (options) => { + return createBetterAuth(options, init); + }; + } +}); + +// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/index.mjs +var init_dist6 = __esm({ + "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/index.mjs"() { + } +}); + +// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/index.mjs +var init_dist7 = __esm({ + "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/index.mjs"() { + init_state(); + init_state2(); + init_hide_metadata(); + init_utils10(); + init_api3(); + init_full(); + init_context2(); + init_dist5(); + init_dist6(); + init_db3(); + init_env(); + init_error(); + init_oauth2(); + init_utils7(); + } +}); + +// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/adapters/drizzle-adapter/drizzle-adapter.mjs +var drizzleAdapter; +var init_drizzle_adapter = __esm({ + "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/adapters/drizzle-adapter/drizzle-adapter.mjs"() { + init_env(); + init_error(); + init_adapter(); + init_drizzle_orm(); + drizzleAdapter = (db, config3) => { + let lazyOptions = null; + const createCustomAdapter = (db$1) => ({ getFieldName, options }) => { + function getSchema2(model) { + const schema2 = config3.schema || db$1._.fullSchema; + if (!schema2) throw new BetterAuthError("Drizzle adapter failed to initialize. Schema not found. Please provide a schema object in the adapter options object."); + const schemaModel = schema2[model]; + if (!schemaModel) throw new BetterAuthError(`[# Drizzle Adapter]: The model "${model}" was not found in the schema object. Please pass the schema directly to the adapter options.`); + return schemaModel; + } + const withReturning = async (model, builder, data2, where) => { + if (config3.provider !== "mysql") return (await builder.returning())[0]; + await builder.execute(); + const schemaModel = getSchema2(model); + const builderVal = builder.config?.values; + if (where?.length) { + const clause = convertWhereClause(where.map((w5) => { + if (data2[w5.field] !== void 0) return { + ...w5, + value: data2[w5.field] + }; + return w5; + }), model); + return (await db$1.select().from(schemaModel).where(...clause))[0]; + } else if (builderVal && builderVal[0]?.id?.value) { + let tId = builderVal[0]?.id?.value; + if (!tId) tId = (await db$1.select({ id: sql`LAST_INSERT_ID()` }).from(schemaModel).orderBy(desc(schemaModel.id)).limit(1))[0].id; + return (await db$1.select().from(schemaModel).where(eq(schemaModel.id, tId)).limit(1).execute())[0]; + } else if (data2.id) return (await db$1.select().from(schemaModel).where(eq(schemaModel.id, data2.id)).limit(1).execute())[0]; + else { + if (!("id" in schemaModel)) throw new BetterAuthError(`The model "${model}" does not have an "id" field. Please use the "id" field as your primary key.`); + return (await db$1.select().from(schemaModel).orderBy(desc(schemaModel.id)).limit(1).execute())[0]; + } + }; + function convertWhereClause(where, model) { + const schemaModel = getSchema2(model); + if (!where) return []; + if (where.length === 1) { + const w5 = where[0]; + if (!w5) return []; + const field = getFieldName({ + model, + field: w5.field + }); + if (!schemaModel[field]) throw new BetterAuthError(`The field "${w5.field}" does not exist in the schema for the model "${model}". Please update your schema.`); + if (w5.operator === "in") { + if (!Array.isArray(w5.value)) throw new BetterAuthError(`The value for the field "${w5.field}" must be an array when using the "in" operator.`); + return [inArray(schemaModel[field], w5.value)]; + } + if (w5.operator === "not_in") { + if (!Array.isArray(w5.value)) throw new BetterAuthError(`The value for the field "${w5.field}" must be an array when using the "not_in" operator.`); + return [notInArray(schemaModel[field], w5.value)]; + } + if (w5.operator === "contains") return [like(schemaModel[field], `%${w5.value}%`)]; + if (w5.operator === "starts_with") return [like(schemaModel[field], `${w5.value}%`)]; + if (w5.operator === "ends_with") return [like(schemaModel[field], `%${w5.value}`)]; + if (w5.operator === "lt") return [lt(schemaModel[field], w5.value)]; + if (w5.operator === "lte") return [lte(schemaModel[field], w5.value)]; + if (w5.operator === "ne") return [ne(schemaModel[field], w5.value)]; + if (w5.operator === "gt") return [gt(schemaModel[field], w5.value)]; + if (w5.operator === "gte") return [gte(schemaModel[field], w5.value)]; + return [eq(schemaModel[field], w5.value)]; + } + const andGroup = where.filter((w5) => w5.connector === "AND" || !w5.connector); + const orGroup = where.filter((w5) => w5.connector === "OR"); + const andClause = and(...andGroup.map((w5) => { + const field = getFieldName({ + model, + field: w5.field + }); + if (w5.operator === "in") { + if (!Array.isArray(w5.value)) throw new BetterAuthError(`The value for the field "${w5.field}" must be an array when using the "in" operator.`); + return inArray(schemaModel[field], w5.value); + } + if (w5.operator === "not_in") { + if (!Array.isArray(w5.value)) throw new BetterAuthError(`The value for the field "${w5.field}" must be an array when using the "not_in" operator.`); + return notInArray(schemaModel[field], w5.value); + } + if (w5.operator === "contains") return like(schemaModel[field], `%${w5.value}%`); + if (w5.operator === "starts_with") return like(schemaModel[field], `${w5.value}%`); + if (w5.operator === "ends_with") return like(schemaModel[field], `%${w5.value}`); + if (w5.operator === "lt") return lt(schemaModel[field], w5.value); + if (w5.operator === "lte") return lte(schemaModel[field], w5.value); + if (w5.operator === "gt") return gt(schemaModel[field], w5.value); + if (w5.operator === "gte") return gte(schemaModel[field], w5.value); + if (w5.operator === "ne") return ne(schemaModel[field], w5.value); + return eq(schemaModel[field], w5.value); + })); + const orClause = or(...orGroup.map((w5) => { + const field = getFieldName({ + model, + field: w5.field + }); + if (w5.operator === "in") { + if (!Array.isArray(w5.value)) throw new BetterAuthError(`The value for the field "${w5.field}" must be an array when using the "in" operator.`); + return inArray(schemaModel[field], w5.value); + } + if (w5.operator === "not_in") { + if (!Array.isArray(w5.value)) throw new BetterAuthError(`The value for the field "${w5.field}" must be an array when using the "not_in" operator.`); + return notInArray(schemaModel[field], w5.value); + } + if (w5.operator === "contains") return like(schemaModel[field], `%${w5.value}%`); + if (w5.operator === "starts_with") return like(schemaModel[field], `${w5.value}%`); + if (w5.operator === "ends_with") return like(schemaModel[field], `%${w5.value}`); + if (w5.operator === "lt") return lt(schemaModel[field], w5.value); + if (w5.operator === "lte") return lte(schemaModel[field], w5.value); + if (w5.operator === "gt") return gt(schemaModel[field], w5.value); + if (w5.operator === "gte") return gte(schemaModel[field], w5.value); + if (w5.operator === "ne") return ne(schemaModel[field], w5.value); + return eq(schemaModel[field], w5.value); + })); + const clause = []; + if (andGroup.length) clause.push(andClause); + if (orGroup.length) clause.push(orClause); + return clause; + } + function checkMissingFields(schema2, model, values2) { + if (!schema2) throw new BetterAuthError("Drizzle adapter failed to initialize. Drizzle Schema not found. Please provide a schema object in the adapter options object."); + for (const key in values2) if (!schema2[key]) throw new BetterAuthError(`The field "${key}" does not exist in the "${model}" Drizzle schema. Please update your drizzle schema or re-generate using "npx @better-auth/cli@latest generate".`); + } + return { + async create({ model, data: values2 }) { + const schemaModel = getSchema2(model); + checkMissingFields(schemaModel, model, values2); + return await withReturning(model, db$1.insert(schemaModel).values(values2), values2); + }, + async findOne({ model, where, join: join4 }) { + const schemaModel = getSchema2(model); + const clause = convertWhereClause(where, model); + if (options.experimental?.joins) if (!db$1.query || !db$1.query[model]) { + logger3.error(`[# Drizzle Adapter]: The model "${model}" was not found in the query object. Please update your Drizzle schema to include relations or re-generate using "npx @better-auth/cli@latest generate".`); + logger3.info("Falling back to regular query"); + } else { + let includes; + const pluralJoinResults = []; + if (join4) { + includes = {}; + const joinEntries = Object.entries(join4); + for (const [model$1, joinAttr] of joinEntries) { + const limit = joinAttr.limit ?? options.advanced?.database?.defaultFindManyLimit ?? 100; + const isUnique = joinAttr.relation === "one-to-one"; + const pluralSuffix = isUnique || config3.usePlural ? "" : "s"; + includes[`${model$1}${pluralSuffix}`] = isUnique ? true : { limit }; + if (!isUnique) pluralJoinResults.push(`${model$1}${pluralSuffix}`); + } + } + const res$1 = await db$1.query[model].findFirst({ + where: clause[0], + with: includes + }); + if (res$1) for (const pluralJoinResult of pluralJoinResults) { + const singularKey = !config3.usePlural ? pluralJoinResult.slice(0, -1) : pluralJoinResult; + res$1[singularKey] = res$1[pluralJoinResult]; + if (pluralJoinResult !== singularKey) delete res$1[pluralJoinResult]; + } + return res$1; + } + const res = await db$1.select().from(schemaModel).where(...clause); + if (!res.length) return null; + return res[0]; + }, + async findMany({ model, where, sortBy, limit, offset, join: join4 }) { + const schemaModel = getSchema2(model); + const clause = where ? convertWhereClause(where, model) : []; + const sortFn = sortBy?.direction === "desc" ? desc : asc; + if (options.experimental?.joins) if (!db$1.query[model]) { + logger3.error(`[# Drizzle Adapter]: The model "${model}" was not found in the query object. Please update your Drizzle schema to include relations or re-generate using "npx @better-auth/cli@latest generate".`); + logger3.info("Falling back to regular query"); + } else { + let includes; + const pluralJoinResults = []; + if (join4) { + includes = {}; + const joinEntries = Object.entries(join4); + for (const [model$1, joinAttr] of joinEntries) { + const isUnique = joinAttr.relation === "one-to-one"; + const limit$1 = joinAttr.limit ?? options.advanced?.database?.defaultFindManyLimit ?? 100; + const pluralSuffix = isUnique || config3.usePlural ? "" : "s"; + includes[`${model$1}${pluralSuffix}`] = isUnique ? true : { limit: limit$1 }; + if (!isUnique) pluralJoinResults.push(`${model$1}${pluralSuffix}`); + } + } + let orderBy = void 0; + if (sortBy?.field) orderBy = [sortFn(schemaModel[getFieldName({ + model, + field: sortBy?.field + })])]; + const res = await db$1.query[model].findMany({ + where: clause[0], + with: includes, + limit: limit ?? 100, + offset: offset ?? 0, + orderBy + }); + if (res) for (const item of res) for (const pluralJoinResult of pluralJoinResults) { + const singularKey = !config3.usePlural ? pluralJoinResult.slice(0, -1) : pluralJoinResult; + if (singularKey === pluralJoinResult) continue; + item[singularKey] = item[pluralJoinResult]; + delete item[pluralJoinResult]; + } + return res; + } + let builder = db$1.select().from(schemaModel); + const effectiveLimit = limit; + const effectiveOffset = offset; + if (typeof effectiveLimit !== "undefined") builder = builder.limit(effectiveLimit); + if (typeof effectiveOffset !== "undefined") builder = builder.offset(effectiveOffset); + if (sortBy?.field) builder = builder.orderBy(sortFn(schemaModel[getFieldName({ + model, + field: sortBy?.field + })])); + return await builder.where(...clause); + }, + async count({ model, where }) { + const schemaModel = getSchema2(model); + const clause = where ? convertWhereClause(where, model) : []; + return (await db$1.select({ count: count() }).from(schemaModel).where(...clause))[0].count; + }, + async update({ model, where, update: values2 }) { + const schemaModel = getSchema2(model); + const clause = convertWhereClause(where, model); + return await withReturning(model, db$1.update(schemaModel).set(values2).where(...clause), values2, where); + }, + async updateMany({ model, where, update: values2 }) { + const schemaModel = getSchema2(model); + const clause = convertWhereClause(where, model); + return await db$1.update(schemaModel).set(values2).where(...clause); + }, + async delete({ model, where }) { + const schemaModel = getSchema2(model); + const clause = convertWhereClause(where, model); + return await db$1.delete(schemaModel).where(...clause); + }, + async deleteMany({ model, where }) { + const schemaModel = getSchema2(model); + const clause = convertWhereClause(where, model); + const res = await db$1.delete(schemaModel).where(...clause); + let count$1 = 0; + if (res && "rowCount" in res) count$1 = res.rowCount; + else if (Array.isArray(res)) count$1 = res.length; + else if (res && ("affectedRows" in res || "rowsAffected" in res || "changes" in res)) count$1 = res.affectedRows ?? res.rowsAffected ?? res.changes; + if (typeof count$1 !== "number") logger3.error("[Drizzle Adapter] The result of the deleteMany operation is not a number. This is likely a bug in the adapter. Please report this issue to the Better Auth team.", { + res, + model, + where + }); + return count$1; + }, + options: config3 + }; + }; + let adapterOptions = null; + adapterOptions = { + config: { + adapterId: "drizzle", + adapterName: "Drizzle Adapter", + usePlural: config3.usePlural ?? false, + debugLogs: config3.debugLogs ?? false, + supportsUUIDs: config3.provider === "pg" ? true : false, + supportsJSON: config3.provider === "pg" ? true : false, + supportsArrays: config3.provider === "pg" ? true : false, + transaction: config3.transaction ?? false ? (cb) => db.transaction((tx) => { + return cb(createAdapterFactory({ + config: adapterOptions.config, + adapter: createCustomAdapter(tx) + })(lazyOptions)); + }) : false + }, + adapter: createCustomAdapter(db) + }; + const adapter = createAdapterFactory(adapterOptions); + return (options) => { + lazyOptions = options; + return adapter(options); + }; + }; + } +}); + +// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/adapters/drizzle-adapter/index.mjs +var init_drizzle_adapter2 = __esm({ + "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/adapters/drizzle-adapter/index.mjs"() { + init_drizzle_adapter(); + } +}); + +// node_modules/.pnpm/set-cookie-parser@2.7.2/node_modules/set-cookie-parser/lib/set-cookie.js +var require_set_cookie = __commonJS({ + "node_modules/.pnpm/set-cookie-parser@2.7.2/node_modules/set-cookie-parser/lib/set-cookie.js"(exports, module) { + "use strict"; + var defaultParseOptions = { + decodeValues: true, + map: false, + silent: false + }; + function isForbiddenKey(key) { + return typeof key !== "string" || key in {}; + } + function createNullObj() { + return /* @__PURE__ */ Object.create(null); + } + function isNonEmptyString(str) { + return typeof str === "string" && !!str.trim(); + } + function parseString(setCookieValue, options) { + var parts = setCookieValue.split(";").filter(isNonEmptyString); + var nameValuePairStr = parts.shift(); + var parsed = parseNameValuePair(nameValuePairStr); + var name = parsed.name; + var value = parsed.value; + options = options ? Object.assign({}, defaultParseOptions, options) : defaultParseOptions; + if (isForbiddenKey(name)) { + return null; + } + try { + value = options.decodeValues ? decodeURIComponent(value) : value; + } catch (e5) { + console.error( + "set-cookie-parser: failed to decode cookie value. Set options.decodeValues=false to disable decoding.", + e5 + ); + } + var cookie = createNullObj(); + cookie.name = name; + cookie.value = value; + parts.forEach(function(part) { + var sides = part.split("="); + var key = sides.shift().trimLeft().toLowerCase(); + if (isForbiddenKey(key)) { + return; + } + var value2 = sides.join("="); + if (key === "expires") { + cookie.expires = new Date(value2); + } else if (key === "max-age") { + var n5 = parseInt(value2, 10); + if (!Number.isNaN(n5)) cookie.maxAge = n5; + } else if (key === "secure") { + cookie.secure = true; + } else if (key === "httponly") { + cookie.httpOnly = true; + } else if (key === "samesite") { + cookie.sameSite = value2; + } else if (key === "partitioned") { + cookie.partitioned = true; + } else if (key) { + cookie[key] = value2; + } + }); + return cookie; + } + function parseNameValuePair(nameValuePairStr) { + var name = ""; + var value = ""; + var nameValueArr = nameValuePairStr.split("="); + if (nameValueArr.length > 1) { + name = nameValueArr.shift(); + value = nameValueArr.join("="); + } else { + value = nameValuePairStr; + } + return { name, value }; + } + function parse5(input, options) { + options = options ? Object.assign({}, defaultParseOptions, options) : defaultParseOptions; + if (!input) { + if (!options.map) { + return []; + } else { + return createNullObj(); + } + } + if (input.headers) { + if (typeof input.headers.getSetCookie === "function") { + input = input.headers.getSetCookie(); + } else if (input.headers["set-cookie"]) { + input = input.headers["set-cookie"]; + } else { + var sch = input.headers[Object.keys(input.headers).find(function(key) { + return key.toLowerCase() === "set-cookie"; + })]; + if (!sch && input.headers.cookie && !options.silent) { + console.warn( + "Warning: set-cookie-parser appears to have been called on a request object. It is designed to parse Set-Cookie headers from responses, not Cookie headers from requests. Set the option {silent: true} to suppress this warning." + ); + } + input = sch; + } + } + if (!Array.isArray(input)) { + input = [input]; + } + if (!options.map) { + return input.filter(isNonEmptyString).map(function(str) { + return parseString(str, options); + }).filter(Boolean); + } else { + var cookies = createNullObj(); + return input.filter(isNonEmptyString).reduce(function(cookies2, str) { + var cookie = parseString(str, options); + if (cookie && !isForbiddenKey(cookie.name)) { + cookies2[cookie.name] = cookie; + } + return cookies2; + }, cookies); + } + } + function splitCookiesString2(cookiesString) { + if (Array.isArray(cookiesString)) { + return cookiesString; + } + if (typeof cookiesString !== "string") { + return []; + } + var cookiesStrings = []; + var pos = 0; + var start; + var ch; + var lastComma; + var nextStart; + var cookiesSeparatorFound; + function skipWhitespace() { + while (pos < cookiesString.length && /\s/.test(cookiesString.charAt(pos))) { + pos += 1; + } + return pos < cookiesString.length; + } + function notSpecialChar() { + ch = cookiesString.charAt(pos); + return ch !== "=" && ch !== ";" && ch !== ","; + } + while (pos < cookiesString.length) { + start = pos; + cookiesSeparatorFound = false; + while (skipWhitespace()) { + ch = cookiesString.charAt(pos); + if (ch === ",") { + lastComma = pos; + pos += 1; + skipWhitespace(); + nextStart = pos; + while (pos < cookiesString.length && notSpecialChar()) { + pos += 1; + } + if (pos < cookiesString.length && cookiesString.charAt(pos) === "=") { + cookiesSeparatorFound = true; + pos = nextStart; + cookiesStrings.push(cookiesString.substring(start, lastComma)); + start = pos; + } else { + pos = lastComma + 1; + } + } else { + pos += 1; + } + } + if (!cookiesSeparatorFound || pos >= cookiesString.length) { + cookiesStrings.push(cookiesString.substring(start, cookiesString.length)); + } + } + return cookiesStrings; + } + module.exports = parse5; + module.exports.parse = parse5; + module.exports.parseString = parseString; + module.exports.splitCookiesString = splitCookiesString2; + } +}); + +// node_modules/.pnpm/better-call@1.1.8_zod@4.3.6/node_modules/better-call/dist/adapters/node/request.mjs +function get_raw_body(req, body_size_limit) { + const h5 = req.headers; + if (!h5["content-type"]) return null; + const content_length = Number(h5["content-length"]); + if (req.httpVersionMajor === 1 && isNaN(content_length) && h5["transfer-encoding"] == null || content_length === 0) return null; + let length = content_length; + if (body_size_limit) { + if (!length) length = body_size_limit; + else if (length > body_size_limit) throw Error(`Received content-length of ${length}, but only accept up to ${body_size_limit} bytes.`); + } + if (req.destroyed) { + const readable = new ReadableStream(); + readable.cancel(); + return readable; + } + let size2 = 0; + let cancelled = false; + return new ReadableStream({ + start(controller) { + req.on("error", (error50) => { + cancelled = true; + controller.error(error50); + }); + req.on("end", () => { + if (cancelled) return; + controller.close(); + }); + req.on("data", (chunk) => { + if (cancelled) return; + size2 += chunk.length; + if (size2 > length) { + cancelled = true; + controller.error(/* @__PURE__ */ new Error(`request body size exceeded ${content_length ? "'content-length'" : "BODY_SIZE_LIMIT"} of ${length}`)); + return; + } + controller.enqueue(chunk); + if (controller.desiredSize === null || controller.desiredSize <= 0) req.pause(); + }); + }, + pull() { + req.resume(); + }, + cancel(reason) { + cancelled = true; + req.destroy(reason); + } + }); +} +function getRequest({ request, base, bodySizeLimit }) { + const baseUrl = request?.baseUrl; + const fullPath = baseUrl ? baseUrl + request.url : request.url; + const maybeConsumedReq = request; + let body = void 0; + const method = request.method; + if (method !== "GET" && method !== "HEAD") if (maybeConsumedReq.body !== void 0) { + const bodyContent = typeof maybeConsumedReq.body === "string" ? maybeConsumedReq.body : JSON.stringify(maybeConsumedReq.body); + body = new ReadableStream({ start(controller) { + controller.enqueue(new TextEncoder().encode(bodyContent)); + controller.close(); + } }); + } else body = get_raw_body(request, bodySizeLimit); + return new Request(base + fullPath, { + duplex: "half", + method: request.method, + body, + headers: request.headers + }); +} +async function setResponse(res, response) { + for (const [key, value] of response.headers) try { + res.setHeader(key, key === "set-cookie" ? set_cookie_parser.splitCookiesString(response.headers.get(key)) : value); + } catch (error50) { + res.getHeaderNames().forEach((name) => res.removeHeader(name)); + res.writeHead(500).end(String(error50)); + return; + } + res.writeHead(response.status); + if (!response.body) { + res.end(); + return; + } + if (response.body.locked) { + res.end("Fatal error: Response body is locked. This can happen when the response was already read (for example through 'response.json()' or 'response.text()')."); + return; + } + const reader = response.body.getReader(); + if (res.destroyed) { + reader.cancel(); + return; + } + const cancel = (error50) => { + res.off("close", cancel); + res.off("error", cancel); + reader.cancel(error50).catch(() => { + }); + if (error50) res.destroy(error50); + }; + res.on("close", cancel); + res.on("error", cancel); + next(); + async function next() { + try { + for (; ; ) { + const { done, value } = await reader.read(); + if (done) break; + if (!res.write(value)) { + res.once("drain", next); + return; + } + } + res.end(); + } catch (error50) { + cancel(error50 instanceof Error ? error50 : new Error(String(error50))); + } + } +} +var set_cookie_parser; +var init_request = __esm({ + "node_modules/.pnpm/better-call@1.1.8_zod@4.3.6/node_modules/better-call/dist/adapters/node/request.mjs"() { + set_cookie_parser = __toESM(require_set_cookie(), 1); + } +}); + +// node_modules/.pnpm/better-call@1.1.8_zod@4.3.6/node_modules/better-call/dist/node.mjs +function toNodeHandler(handler) { + return async (req, res) => { + return setResponse(res, await handler(getRequest({ + base: `${req.headers["x-forwarded-proto"] || (req.socket.encrypted ? "https" : "http")}://${req.headers[":authority"] || req.headers.host}`, + request: req + }))); + }; +} +var init_node = __esm({ + "node_modules/.pnpm/better-call@1.1.8_zod@4.3.6/node_modules/better-call/dist/node.mjs"() { + init_request(); + } +}); + +// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/integrations/node.mjs +var toNodeHandler2; +var init_node2 = __esm({ + "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/integrations/node.mjs"() { + init_node(); + toNodeHandler2 = (auth) => { + return "handler" in auth ? toNodeHandler(auth.handler) : toNodeHandler(auth); + }; + } +}); + +// server/src/auth/better-auth.ts +var better_auth_exports = {}; +__export(better_auth_exports, { + createBetterAuthHandler: () => createBetterAuthHandler, + createBetterAuthInstance: () => createBetterAuthInstance, + deriveAuthTrustedOrigins: () => deriveAuthTrustedOrigins, + resolveBetterAuthSession: () => resolveBetterAuthSession, + resolveBetterAuthSessionFromHeaders: () => resolveBetterAuthSessionFromHeaders +}); +function headersFromNodeHeaders(rawHeaders) { + const headers = new Headers(); + for (const [key, raw] of Object.entries(rawHeaders)) { + if (!raw) continue; + if (Array.isArray(raw)) { + for (const value of raw) headers.append(key, value); + continue; + } + headers.set(key, raw); + } + return headers; +} +function headersFromExpressRequest(req) { + return headersFromNodeHeaders(req.headers); +} +function deriveAuthTrustedOrigins(config3) { + const baseUrl = config3.authBaseUrlMode === "explicit" ? config3.authPublicBaseUrl : void 0; + const trustedOrigins = /* @__PURE__ */ new Set(); + if (baseUrl) { + try { + trustedOrigins.add(new URL(baseUrl).origin); + } catch { + } + } + if (config3.deploymentMode === "authenticated") { + for (const hostname3 of config3.allowedHostnames) { + const trimmed = hostname3.trim().toLowerCase(); + if (!trimmed) continue; + trustedOrigins.add(`https://${trimmed}`); + trustedOrigins.add(`http://${trimmed}`); + } + } + return Array.from(trustedOrigins); +} +function createBetterAuthInstance(db, config3, trustedOrigins) { + const baseUrl = config3.authBaseUrlMode === "explicit" ? config3.authPublicBaseUrl : void 0; + const secret = process.env.BETTER_AUTH_SECRET ?? process.env.TASKCORE_AGENT_JWT_SECRET; + if (!secret) { + throw new Error( + "BETTER_AUTH_SECRET (or TASKCORE_AGENT_JWT_SECRET) must be set. For local development, set BETTER_AUTH_SECRET=taskcore-dev-secret in your .env file." + ); + } + const effectiveTrustedOrigins = trustedOrigins ?? deriveAuthTrustedOrigins(config3); + const publicUrl = process.env.TASKCORE_PUBLIC_URL ?? baseUrl; + const isHttpOnly = publicUrl ? publicUrl.startsWith("http://") : false; + const authConfig = { + baseURL: baseUrl, + secret, + trustedOrigins: effectiveTrustedOrigins, + database: drizzleAdapter(db, { + provider: "pg", + schema: { + user: authUsers, + session: authSessions, + account: authAccounts, + verification: authVerifications + } + }), + emailAndPassword: { + enabled: true, + requireEmailVerification: false, + disableSignUp: config3.authDisableSignUp + }, + ...isHttpOnly ? { advanced: { useSecureCookies: false } } : {} + }; + if (!baseUrl) { + delete authConfig.baseURL; + } + return betterAuth(authConfig); +} +function createBetterAuthHandler(auth) { + const handler = toNodeHandler2(auth); + return (req, res, next) => { + void Promise.resolve(handler(req, res)).catch(next); + }; +} +async function resolveBetterAuthSessionFromHeaders(auth, headers) { + const api = auth.api; + if (!api?.getSession) return null; + const sessionValue = await api.getSession({ + headers + }); + if (!sessionValue || typeof sessionValue !== "object") return null; + const value = sessionValue; + const session = value.session?.id && value.session.userId ? { id: value.session.id, userId: value.session.userId } : null; + const user = value.user?.id ? { + id: value.user.id, + email: value.user.email ?? null, + name: value.user.name ?? null + } : null; + if (!session || !user) return null; + return { session, user }; +} +async function resolveBetterAuthSession(auth, req) { + return resolveBetterAuthSessionFromHeaders(auth, headersFromExpressRequest(req)); +} +var init_better_auth = __esm({ + "server/src/auth/better-auth.ts"() { + "use strict"; + init_dist7(); + init_drizzle_adapter2(); + init_node2(); + init_src2(); + } +}); + +// server/src/vercel.ts +init_src2(); + +// server/src/app.ts +var import_express25 = __toESM(require_express2(), 1); +import path52 from "node:path"; +import fs40 from "node:fs"; +import { fileURLToPath as fileURLToPath19 } from "node:url"; + +// server/src/middleware/logger.ts +var import_pino = __toESM(require_pino(), 1); +var import_pino_http = __toESM(require_logger(), 1); +import path3 from "node:path"; + +// server/src/config-file.ts +import fs3 from "node:fs"; + +// node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/external.js +var external_exports = {}; +__export(external_exports, { + BRAND: () => BRAND, + DIRTY: () => DIRTY, + EMPTY_PATH: () => EMPTY_PATH, + INVALID: () => INVALID, + NEVER: () => NEVER, + OK: () => OK, + ParseStatus: () => ParseStatus, + Schema: () => ZodType, + ZodAny: () => ZodAny, + ZodArray: () => ZodArray, + ZodBigInt: () => ZodBigInt, + ZodBoolean: () => ZodBoolean, + ZodBranded: () => ZodBranded, + ZodCatch: () => ZodCatch, + ZodDate: () => ZodDate, + ZodDefault: () => ZodDefault, + ZodDiscriminatedUnion: () => ZodDiscriminatedUnion, + ZodEffects: () => ZodEffects, + ZodEnum: () => ZodEnum, + ZodError: () => ZodError, + ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind, + ZodFunction: () => ZodFunction, + ZodIntersection: () => ZodIntersection, + ZodIssueCode: () => ZodIssueCode, + ZodLazy: () => ZodLazy, + ZodLiteral: () => ZodLiteral, + ZodMap: () => ZodMap, + ZodNaN: () => ZodNaN, + ZodNativeEnum: () => ZodNativeEnum, + ZodNever: () => ZodNever, + ZodNull: () => ZodNull, + ZodNullable: () => ZodNullable, + ZodNumber: () => ZodNumber, + ZodObject: () => ZodObject, + ZodOptional: () => ZodOptional, + ZodParsedType: () => ZodParsedType, + ZodPipeline: () => ZodPipeline, + ZodPromise: () => ZodPromise, + ZodReadonly: () => ZodReadonly, + ZodRecord: () => ZodRecord, + ZodSchema: () => ZodType, + ZodSet: () => ZodSet, + ZodString: () => ZodString, + ZodSymbol: () => ZodSymbol, + ZodTransformer: () => ZodEffects, + ZodTuple: () => ZodTuple, + ZodType: () => ZodType, + ZodUndefined: () => ZodUndefined, + ZodUnion: () => ZodUnion, + ZodUnknown: () => ZodUnknown, + ZodVoid: () => ZodVoid, + addIssueToContext: () => addIssueToContext, + any: () => anyType, + array: () => arrayType, + bigint: () => bigIntType, + boolean: () => booleanType, + coerce: () => coerce, + custom: () => custom, + date: () => dateType, + datetimeRegex: () => datetimeRegex, + defaultErrorMap: () => en_default, + discriminatedUnion: () => discriminatedUnionType, + effect: () => effectsType, + enum: () => enumType, + function: () => functionType, + getErrorMap: () => getErrorMap, + getParsedType: () => getParsedType, + instanceof: () => instanceOfType, + intersection: () => intersectionType, + isAborted: () => isAborted, + isAsync: () => isAsync, + isDirty: () => isDirty, + isValid: () => isValid, + late: () => late, + lazy: () => lazyType, + literal: () => literalType, + makeIssue: () => makeIssue, + map: () => mapType, + nan: () => nanType, + nativeEnum: () => nativeEnumType, + never: () => neverType, + null: () => nullType, + nullable: () => nullableType, + number: () => numberType, + object: () => objectType, + objectUtil: () => objectUtil, + oboolean: () => oboolean, + onumber: () => onumber, + optional: () => optionalType, + ostring: () => ostring, + pipeline: () => pipelineType, + preprocess: () => preprocessType, + promise: () => promiseType, + quotelessJson: () => quotelessJson, + record: () => recordType, + set: () => setType, + setErrorMap: () => setErrorMap, + strictObject: () => strictObjectType, + string: () => stringType, + symbol: () => symbolType, + transformer: () => effectsType, + tuple: () => tupleType, + undefined: () => undefinedType, + union: () => unionType, + unknown: () => unknownType, + util: () => util, + void: () => voidType +}); + +// node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/util.js +var util; +(function(util2) { + util2.assertEqual = (_) => { + }; + function assertIs2(_arg) { + } + util2.assertIs = assertIs2; + function assertNever2(_x) { + throw new Error(); + } + util2.assertNever = assertNever2; + util2.arrayToEnum = (items) => { + const obj = {}; + for (const item of items) { + obj[item] = item; + } + return obj; + }; + util2.getValidEnumValues = (obj) => { + const validKeys = util2.objectKeys(obj).filter((k5) => typeof obj[obj[k5]] !== "number"); + const filtered = {}; + for (const k5 of validKeys) { + filtered[k5] = obj[k5]; + } + return util2.objectValues(filtered); + }; + util2.objectValues = (obj) => { + return util2.objectKeys(obj).map(function(e5) { + return obj[e5]; + }); + }; + util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object2) => { + const keys = []; + for (const key in object2) { + if (Object.prototype.hasOwnProperty.call(object2, key)) { + keys.push(key); + } + } + return keys; + }; + util2.find = (arr, checker) => { + for (const item of arr) { + if (checker(item)) + return item; + } + return void 0; + }; + util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val; + function joinValues2(array2, separator = " | ") { + return array2.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator); + } + util2.joinValues = joinValues2; + util2.jsonStringifyReplacer = (_, value) => { + if (typeof value === "bigint") { + return value.toString(); + } + return value; + }; +})(util || (util = {})); +var objectUtil; +(function(objectUtil2) { + objectUtil2.mergeShapes = (first, second) => { + return { + ...first, + ...second + // second overwrites first + }; + }; +})(objectUtil || (objectUtil = {})); +var ZodParsedType = util.arrayToEnum([ + "string", + "nan", + "number", + "integer", + "float", + "boolean", + "date", + "bigint", + "symbol", + "function", + "undefined", + "null", + "array", + "object", + "unknown", + "promise", + "void", + "never", + "map", + "set" +]); +var getParsedType = (data2) => { + const t5 = typeof data2; + switch (t5) { + case "undefined": + return ZodParsedType.undefined; + case "string": + return ZodParsedType.string; + case "number": + return Number.isNaN(data2) ? ZodParsedType.nan : ZodParsedType.number; + case "boolean": + return ZodParsedType.boolean; + case "function": + return ZodParsedType.function; + case "bigint": + return ZodParsedType.bigint; + case "symbol": + return ZodParsedType.symbol; + case "object": + if (Array.isArray(data2)) { + return ZodParsedType.array; + } + if (data2 === null) { + return ZodParsedType.null; + } + if (data2.then && typeof data2.then === "function" && data2.catch && typeof data2.catch === "function") { + return ZodParsedType.promise; + } + if (typeof Map !== "undefined" && data2 instanceof Map) { + return ZodParsedType.map; + } + if (typeof Set !== "undefined" && data2 instanceof Set) { + return ZodParsedType.set; + } + if (typeof Date !== "undefined" && data2 instanceof Date) { + return ZodParsedType.date; + } + return ZodParsedType.object; + default: + return ZodParsedType.unknown; + } +}; + +// node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/ZodError.js +var ZodIssueCode = util.arrayToEnum([ + "invalid_type", + "invalid_literal", + "custom", + "invalid_union", + "invalid_union_discriminator", + "invalid_enum_value", + "unrecognized_keys", + "invalid_arguments", + "invalid_return_type", + "invalid_date", + "invalid_string", + "too_small", + "too_big", + "invalid_intersection_types", + "not_multiple_of", + "not_finite" +]); +var quotelessJson = (obj) => { + const json3 = JSON.stringify(obj, null, 2); + return json3.replace(/"([^"]+)":/g, "$1:"); +}; +var ZodError = class _ZodError extends Error { + get errors() { + return this.issues; + } + constructor(issues2) { + super(); + this.issues = []; + this.addIssue = (sub) => { + this.issues = [...this.issues, sub]; + }; + this.addIssues = (subs = []) => { + this.issues = [...this.issues, ...subs]; + }; + const actualProto = new.target.prototype; + if (Object.setPrototypeOf) { + Object.setPrototypeOf(this, actualProto); + } else { + this.__proto__ = actualProto; + } + this.name = "ZodError"; + this.issues = issues2; + } + format(_mapper) { + const mapper = _mapper || function(issue2) { + return issue2.message; + }; + const fieldErrors = { _errors: [] }; + const processError = (error50) => { + for (const issue2 of error50.issues) { + if (issue2.code === "invalid_union") { + issue2.unionErrors.map(processError); + } else if (issue2.code === "invalid_return_type") { + processError(issue2.returnTypeError); + } else if (issue2.code === "invalid_arguments") { + processError(issue2.argumentsError); + } else if (issue2.path.length === 0) { + fieldErrors._errors.push(mapper(issue2)); + } else { + let curr = fieldErrors; + let i5 = 0; + while (i5 < issue2.path.length) { + const el = issue2.path[i5]; + const terminal = i5 === issue2.path.length - 1; + if (!terminal) { + curr[el] = curr[el] || { _errors: [] }; + } else { + curr[el] = curr[el] || { _errors: [] }; + curr[el]._errors.push(mapper(issue2)); + } + curr = curr[el]; + i5++; + } + } + } + }; + processError(this); + return fieldErrors; + } + static assert(value) { + if (!(value instanceof _ZodError)) { + throw new Error(`Not a ZodError: ${value}`); + } + } + toString() { + return this.message; + } + get message() { + return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2); + } + get isEmpty() { + return this.issues.length === 0; + } + flatten(mapper = (issue2) => issue2.message) { + const fieldErrors = {}; + const formErrors = []; + for (const sub of this.issues) { + if (sub.path.length > 0) { + const firstEl = sub.path[0]; + fieldErrors[firstEl] = fieldErrors[firstEl] || []; + fieldErrors[firstEl].push(mapper(sub)); + } else { + formErrors.push(mapper(sub)); + } + } + return { formErrors, fieldErrors }; + } + get formErrors() { + return this.flatten(); + } +}; +ZodError.create = (issues2) => { + const error50 = new ZodError(issues2); + return error50; +}; + +// node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/locales/en.js +var errorMap = (issue2, _ctx) => { + let message2; + switch (issue2.code) { + case ZodIssueCode.invalid_type: + if (issue2.received === ZodParsedType.undefined) { + message2 = "Required"; + } else { + message2 = `Expected ${issue2.expected}, received ${issue2.received}`; + } + break; + case ZodIssueCode.invalid_literal: + message2 = `Invalid literal value, expected ${JSON.stringify(issue2.expected, util.jsonStringifyReplacer)}`; + break; + case ZodIssueCode.unrecognized_keys: + message2 = `Unrecognized key(s) in object: ${util.joinValues(issue2.keys, ", ")}`; + break; + case ZodIssueCode.invalid_union: + message2 = `Invalid input`; + break; + case ZodIssueCode.invalid_union_discriminator: + message2 = `Invalid discriminator value. Expected ${util.joinValues(issue2.options)}`; + break; + case ZodIssueCode.invalid_enum_value: + message2 = `Invalid enum value. Expected ${util.joinValues(issue2.options)}, received '${issue2.received}'`; + break; + case ZodIssueCode.invalid_arguments: + message2 = `Invalid function arguments`; + break; + case ZodIssueCode.invalid_return_type: + message2 = `Invalid function return type`; + break; + case ZodIssueCode.invalid_date: + message2 = `Invalid date`; + break; + case ZodIssueCode.invalid_string: + if (typeof issue2.validation === "object") { + if ("includes" in issue2.validation) { + message2 = `Invalid input: must include "${issue2.validation.includes}"`; + if (typeof issue2.validation.position === "number") { + message2 = `${message2} at one or more positions greater than or equal to ${issue2.validation.position}`; + } + } else if ("startsWith" in issue2.validation) { + message2 = `Invalid input: must start with "${issue2.validation.startsWith}"`; + } else if ("endsWith" in issue2.validation) { + message2 = `Invalid input: must end with "${issue2.validation.endsWith}"`; + } else { + util.assertNever(issue2.validation); + } + } else if (issue2.validation !== "regex") { + message2 = `Invalid ${issue2.validation}`; + } else { + message2 = "Invalid"; + } + break; + case ZodIssueCode.too_small: + if (issue2.type === "array") + message2 = `Array must contain ${issue2.exact ? "exactly" : issue2.inclusive ? `at least` : `more than`} ${issue2.minimum} element(s)`; + else if (issue2.type === "string") + message2 = `String must contain ${issue2.exact ? "exactly" : issue2.inclusive ? `at least` : `over`} ${issue2.minimum} character(s)`; + else if (issue2.type === "number") + message2 = `Number must be ${issue2.exact ? `exactly equal to ` : issue2.inclusive ? `greater than or equal to ` : `greater than `}${issue2.minimum}`; + else if (issue2.type === "bigint") + message2 = `Number must be ${issue2.exact ? `exactly equal to ` : issue2.inclusive ? `greater than or equal to ` : `greater than `}${issue2.minimum}`; + else if (issue2.type === "date") + message2 = `Date must be ${issue2.exact ? `exactly equal to ` : issue2.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue2.minimum))}`; + else + message2 = "Invalid input"; + break; + case ZodIssueCode.too_big: + if (issue2.type === "array") + message2 = `Array must contain ${issue2.exact ? `exactly` : issue2.inclusive ? `at most` : `less than`} ${issue2.maximum} element(s)`; + else if (issue2.type === "string") + message2 = `String must contain ${issue2.exact ? `exactly` : issue2.inclusive ? `at most` : `under`} ${issue2.maximum} character(s)`; + else if (issue2.type === "number") + message2 = `Number must be ${issue2.exact ? `exactly` : issue2.inclusive ? `less than or equal to` : `less than`} ${issue2.maximum}`; + else if (issue2.type === "bigint") + message2 = `BigInt must be ${issue2.exact ? `exactly` : issue2.inclusive ? `less than or equal to` : `less than`} ${issue2.maximum}`; + else if (issue2.type === "date") + message2 = `Date must be ${issue2.exact ? `exactly` : issue2.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue2.maximum))}`; + else + message2 = "Invalid input"; + break; + case ZodIssueCode.custom: + message2 = `Invalid input`; + break; + case ZodIssueCode.invalid_intersection_types: + message2 = `Intersection results could not be merged`; + break; + case ZodIssueCode.not_multiple_of: + message2 = `Number must be a multiple of ${issue2.multipleOf}`; + break; + case ZodIssueCode.not_finite: + message2 = "Number must be finite"; + break; + default: + message2 = _ctx.defaultError; + util.assertNever(issue2); + } + return { message: message2 }; +}; +var en_default = errorMap; + +// node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/errors.js +var overrideErrorMap = en_default; +function setErrorMap(map4) { + overrideErrorMap = map4; +} +function getErrorMap() { + return overrideErrorMap; +} + +// node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/parseUtil.js +var makeIssue = (params) => { + const { data: data2, path: path53, errorMaps, issueData } = params; + const fullPath = [...path53, ...issueData.path || []]; + const fullIssue = { + ...issueData, + path: fullPath + }; + if (issueData.message !== void 0) { + return { + ...issueData, + path: fullPath, + message: issueData.message + }; + } + let errorMessage = ""; + const maps = errorMaps.filter((m5) => !!m5).slice().reverse(); + for (const map4 of maps) { + errorMessage = map4(fullIssue, { data: data2, defaultError: errorMessage }).message; + } + return { + ...issueData, + path: fullPath, + message: errorMessage + }; +}; +var EMPTY_PATH = []; +function addIssueToContext(ctx, issueData) { + const overrideMap = getErrorMap(); + const issue2 = makeIssue({ + issueData, + data: ctx.data, + path: ctx.path, + errorMaps: [ + ctx.common.contextualErrorMap, + // contextual error map is first priority + ctx.schemaErrorMap, + // then schema-bound map if available + overrideMap, + // then global override map + overrideMap === en_default ? void 0 : en_default + // then global default map + ].filter((x5) => !!x5) + }); + ctx.common.issues.push(issue2); +} +var ParseStatus = class _ParseStatus { + constructor() { + this.value = "valid"; + } + dirty() { + if (this.value === "valid") + this.value = "dirty"; + } + abort() { + if (this.value !== "aborted") + this.value = "aborted"; + } + static mergeArray(status, results) { + const arrayValue = []; + for (const s5 of results) { + if (s5.status === "aborted") + return INVALID; + if (s5.status === "dirty") + status.dirty(); + arrayValue.push(s5.value); + } + return { status: status.value, value: arrayValue }; + } + static async mergeObjectAsync(status, pairs) { + const syncPairs = []; + for (const pair of pairs) { + const key = await pair.key; + const value = await pair.value; + syncPairs.push({ + key, + value + }); + } + return _ParseStatus.mergeObjectSync(status, syncPairs); + } + static mergeObjectSync(status, pairs) { + const finalObject = {}; + for (const pair of pairs) { + const { key, value } = pair; + if (key.status === "aborted") + return INVALID; + if (value.status === "aborted") + return INVALID; + if (key.status === "dirty") + status.dirty(); + if (value.status === "dirty") + status.dirty(); + if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) { + finalObject[key.value] = value.value; + } + } + return { status: status.value, value: finalObject }; + } +}; +var INVALID = Object.freeze({ + status: "aborted" +}); +var DIRTY = (value) => ({ status: "dirty", value }); +var OK = (value) => ({ status: "valid", value }); +var isAborted = (x5) => x5.status === "aborted"; +var isDirty = (x5) => x5.status === "dirty"; +var isValid = (x5) => x5.status === "valid"; +var isAsync = (x5) => typeof Promise !== "undefined" && x5 instanceof Promise; + +// node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/errorUtil.js +var errorUtil; +(function(errorUtil2) { + errorUtil2.errToObj = (message2) => typeof message2 === "string" ? { message: message2 } : message2 || {}; + errorUtil2.toString = (message2) => typeof message2 === "string" ? message2 : message2?.message; +})(errorUtil || (errorUtil = {})); + +// node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/types.js +var ParseInputLazyPath = class { + constructor(parent, value, path53, key) { + this._cachedPath = []; + this.parent = parent; + this.data = value; + this._path = path53; + this._key = key; + } + get path() { + if (!this._cachedPath.length) { + if (Array.isArray(this._key)) { + this._cachedPath.push(...this._path, ...this._key); + } else { + this._cachedPath.push(...this._path, this._key); + } + } + return this._cachedPath; + } +}; +var handleResult = (ctx, result) => { + if (isValid(result)) { + return { success: true, data: result.value }; + } else { + if (!ctx.common.issues.length) { + throw new Error("Validation failed but no issues detected."); + } + return { + success: false, + get error() { + if (this._error) + return this._error; + const error50 = new ZodError(ctx.common.issues); + this._error = error50; + return this._error; + } + }; + } +}; +function processCreateParams(params) { + if (!params) + return {}; + const { errorMap: errorMap2, invalid_type_error, required_error, description } = params; + if (errorMap2 && (invalid_type_error || required_error)) { + throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`); + } + if (errorMap2) + return { errorMap: errorMap2, description }; + const customMap = (iss, ctx) => { + const { message: message2 } = params; + if (iss.code === "invalid_enum_value") { + return { message: message2 ?? ctx.defaultError }; + } + if (typeof ctx.data === "undefined") { + return { message: message2 ?? required_error ?? ctx.defaultError }; + } + if (iss.code !== "invalid_type") + return { message: ctx.defaultError }; + return { message: message2 ?? invalid_type_error ?? ctx.defaultError }; + }; + return { errorMap: customMap, description }; +} +var ZodType = class { + get description() { + return this._def.description; + } + _getType(input) { + return getParsedType(input.data); + } + _getOrReturnCtx(input, ctx) { + return ctx || { + common: input.parent.common, + data: input.data, + parsedType: getParsedType(input.data), + schemaErrorMap: this._def.errorMap, + path: input.path, + parent: input.parent + }; + } + _processInputParams(input) { + return { + status: new ParseStatus(), + ctx: { + common: input.parent.common, + data: input.data, + parsedType: getParsedType(input.data), + schemaErrorMap: this._def.errorMap, + path: input.path, + parent: input.parent + } + }; + } + _parseSync(input) { + const result = this._parse(input); + if (isAsync(result)) { + throw new Error("Synchronous parse encountered promise."); + } + return result; + } + _parseAsync(input) { + const result = this._parse(input); + return Promise.resolve(result); + } + parse(data2, params) { + const result = this.safeParse(data2, params); + if (result.success) + return result.data; + throw result.error; + } + safeParse(data2, params) { + const ctx = { + common: { + issues: [], + async: params?.async ?? false, + contextualErrorMap: params?.errorMap + }, + path: params?.path || [], + schemaErrorMap: this._def.errorMap, + parent: null, + data: data2, + parsedType: getParsedType(data2) + }; + const result = this._parseSync({ data: data2, path: ctx.path, parent: ctx }); + return handleResult(ctx, result); + } + "~validate"(data2) { + const ctx = { + common: { + issues: [], + async: !!this["~standard"].async + }, + path: [], + schemaErrorMap: this._def.errorMap, + parent: null, + data: data2, + parsedType: getParsedType(data2) + }; + if (!this["~standard"].async) { + try { + const result = this._parseSync({ data: data2, path: [], parent: ctx }); + return isValid(result) ? { + value: result.value + } : { + issues: ctx.common.issues + }; + } catch (err) { + if (err?.message?.toLowerCase()?.includes("encountered")) { + this["~standard"].async = true; + } + ctx.common = { + issues: [], + async: true + }; + } + } + return this._parseAsync({ data: data2, path: [], parent: ctx }).then((result) => isValid(result) ? { + value: result.value + } : { + issues: ctx.common.issues + }); + } + async parseAsync(data2, params) { + const result = await this.safeParseAsync(data2, params); + if (result.success) + return result.data; + throw result.error; + } + async safeParseAsync(data2, params) { + const ctx = { + common: { + issues: [], + contextualErrorMap: params?.errorMap, + async: true + }, + path: params?.path || [], + schemaErrorMap: this._def.errorMap, + parent: null, + data: data2, + parsedType: getParsedType(data2) + }; + const maybeAsyncResult = this._parse({ data: data2, path: ctx.path, parent: ctx }); + const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult)); + return handleResult(ctx, result); + } + refine(check3, message2) { + const getIssueProperties = (val) => { + if (typeof message2 === "string" || typeof message2 === "undefined") { + return { message: message2 }; + } else if (typeof message2 === "function") { + return message2(val); + } else { + return message2; + } + }; + return this._refinement((val, ctx) => { + const result = check3(val); + const setError = () => ctx.addIssue({ + code: ZodIssueCode.custom, + ...getIssueProperties(val) + }); + if (typeof Promise !== "undefined" && result instanceof Promise) { + return result.then((data2) => { + if (!data2) { + setError(); + return false; + } else { + return true; + } + }); + } + if (!result) { + setError(); + return false; + } else { + return true; + } + }); + } + refinement(check3, refinementData) { + return this._refinement((val, ctx) => { + if (!check3(val)) { + ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData); + return false; + } else { + return true; + } + }); + } + _refinement(refinement) { + return new ZodEffects({ + schema: this, + typeName: ZodFirstPartyTypeKind.ZodEffects, + effect: { type: "refinement", refinement } + }); + } + superRefine(refinement) { + return this._refinement(refinement); + } + constructor(def) { + this.spa = this.safeParseAsync; + this._def = def; + this.parse = this.parse.bind(this); + this.safeParse = this.safeParse.bind(this); + this.parseAsync = this.parseAsync.bind(this); + this.safeParseAsync = this.safeParseAsync.bind(this); + this.spa = this.spa.bind(this); + this.refine = this.refine.bind(this); + this.refinement = this.refinement.bind(this); + this.superRefine = this.superRefine.bind(this); + this.optional = this.optional.bind(this); + this.nullable = this.nullable.bind(this); + this.nullish = this.nullish.bind(this); + this.array = this.array.bind(this); + this.promise = this.promise.bind(this); + this.or = this.or.bind(this); + this.and = this.and.bind(this); + this.transform = this.transform.bind(this); + this.brand = this.brand.bind(this); + this.default = this.default.bind(this); + this.catch = this.catch.bind(this); + this.describe = this.describe.bind(this); + this.pipe = this.pipe.bind(this); + this.readonly = this.readonly.bind(this); + this.isNullable = this.isNullable.bind(this); + this.isOptional = this.isOptional.bind(this); + this["~standard"] = { + version: 1, + vendor: "zod", + validate: (data2) => this["~validate"](data2) + }; + } + optional() { + return ZodOptional.create(this, this._def); + } + nullable() { + return ZodNullable.create(this, this._def); + } + nullish() { + return this.nullable().optional(); + } + array() { + return ZodArray.create(this); + } + promise() { + return ZodPromise.create(this, this._def); + } + or(option) { + return ZodUnion.create([this, option], this._def); + } + and(incoming) { + return ZodIntersection.create(this, incoming, this._def); + } + transform(transform3) { + return new ZodEffects({ + ...processCreateParams(this._def), + schema: this, + typeName: ZodFirstPartyTypeKind.ZodEffects, + effect: { type: "transform", transform: transform3 } + }); + } + default(def) { + const defaultValueFunc = typeof def === "function" ? def : () => def; + return new ZodDefault({ + ...processCreateParams(this._def), + innerType: this, + defaultValue: defaultValueFunc, + typeName: ZodFirstPartyTypeKind.ZodDefault + }); + } + brand() { + return new ZodBranded({ + typeName: ZodFirstPartyTypeKind.ZodBranded, + type: this, + ...processCreateParams(this._def) + }); + } + catch(def) { + const catchValueFunc = typeof def === "function" ? def : () => def; + return new ZodCatch({ + ...processCreateParams(this._def), + innerType: this, + catchValue: catchValueFunc, + typeName: ZodFirstPartyTypeKind.ZodCatch + }); + } + describe(description) { + const This = this.constructor; + return new This({ + ...this._def, + description + }); + } + pipe(target) { + return ZodPipeline.create(this, target); + } + readonly() { + return ZodReadonly.create(this); + } + isOptional() { + return this.safeParse(void 0).success; + } + isNullable() { + return this.safeParse(null).success; + } +}; +var cuidRegex = /^c[^\s-]{8,}$/i; +var cuid2Regex = /^[0-9a-z]+$/; +var ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i; +var uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i; +var nanoidRegex = /^[a-z0-9_-]{21}$/i; +var jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/; +var durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; +var emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i; +var _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; +var emojiRegex; +var ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/; +var ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/; +var ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/; +var ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; +var base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/; +var base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/; +var dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`; +var dateRegex = new RegExp(`^${dateRegexSource}$`); +function timeRegexSource(args) { + let secondsRegexSource = `[0-5]\\d`; + if (args.precision) { + secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`; + } else if (args.precision == null) { + secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`; + } + const secondsQuantifier = args.precision ? "+" : "?"; + return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`; +} +function timeRegex(args) { + return new RegExp(`^${timeRegexSource(args)}$`); +} +function datetimeRegex(args) { + let regex = `${dateRegexSource}T${timeRegexSource(args)}`; + const opts = []; + opts.push(args.local ? `Z?` : `Z`); + if (args.offset) + opts.push(`([+-]\\d{2}:?\\d{2})`); + regex = `${regex}(${opts.join("|")})`; + return new RegExp(`^${regex}$`); +} +function isValidIP(ip, version3) { + if ((version3 === "v4" || !version3) && ipv4Regex.test(ip)) { + return true; + } + if ((version3 === "v6" || !version3) && ipv6Regex.test(ip)) { + return true; + } + return false; +} +function isValidJWT(jwt2, alg2) { + if (!jwtRegex.test(jwt2)) + return false; + try { + const [header] = jwt2.split("."); + if (!header) + return false; + const base644 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "="); + const decoded = JSON.parse(atob(base644)); + if (typeof decoded !== "object" || decoded === null) + return false; + if ("typ" in decoded && decoded?.typ !== "JWT") + return false; + if (!decoded.alg) + return false; + if (alg2 && decoded.alg !== alg2) + return false; + return true; + } catch { + return false; + } +} +function isValidCidr(ip, version3) { + if ((version3 === "v4" || !version3) && ipv4CidrRegex.test(ip)) { + return true; + } + if ((version3 === "v6" || !version3) && ipv6CidrRegex.test(ip)) { + return true; + } + return false; +} +var ZodString = class _ZodString2 extends ZodType { + _parse(input) { + if (this._def.coerce) { + input.data = String(input.data); + } + const parsedType2 = this._getType(input); + if (parsedType2 !== ZodParsedType.string) { + const ctx2 = this._getOrReturnCtx(input); + addIssueToContext(ctx2, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.string, + received: ctx2.parsedType + }); + return INVALID; + } + const status = new ParseStatus(); + let ctx = void 0; + for (const check3 of this._def.checks) { + if (check3.kind === "min") { + if (input.data.length < check3.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: check3.value, + type: "string", + inclusive: true, + exact: false, + message: check3.message + }); + status.dirty(); + } + } else if (check3.kind === "max") { + if (input.data.length > check3.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: check3.value, + type: "string", + inclusive: true, + exact: false, + message: check3.message + }); + status.dirty(); + } + } else if (check3.kind === "length") { + const tooBig = input.data.length > check3.value; + const tooSmall = input.data.length < check3.value; + if (tooBig || tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + if (tooBig) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: check3.value, + type: "string", + inclusive: true, + exact: true, + message: check3.message + }); + } else if (tooSmall) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: check3.value, + type: "string", + inclusive: true, + exact: true, + message: check3.message + }); + } + status.dirty(); + } + } else if (check3.kind === "email") { + if (!emailRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "email", + code: ZodIssueCode.invalid_string, + message: check3.message + }); + status.dirty(); + } + } else if (check3.kind === "emoji") { + if (!emojiRegex) { + emojiRegex = new RegExp(_emojiRegex, "u"); + } + if (!emojiRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "emoji", + code: ZodIssueCode.invalid_string, + message: check3.message + }); + status.dirty(); + } + } else if (check3.kind === "uuid") { + if (!uuidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "uuid", + code: ZodIssueCode.invalid_string, + message: check3.message + }); + status.dirty(); + } + } else if (check3.kind === "nanoid") { + if (!nanoidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "nanoid", + code: ZodIssueCode.invalid_string, + message: check3.message + }); + status.dirty(); + } + } else if (check3.kind === "cuid") { + if (!cuidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "cuid", + code: ZodIssueCode.invalid_string, + message: check3.message + }); + status.dirty(); + } + } else if (check3.kind === "cuid2") { + if (!cuid2Regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "cuid2", + code: ZodIssueCode.invalid_string, + message: check3.message + }); + status.dirty(); + } + } else if (check3.kind === "ulid") { + if (!ulidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "ulid", + code: ZodIssueCode.invalid_string, + message: check3.message + }); + status.dirty(); + } + } else if (check3.kind === "url") { + try { + new URL(input.data); + } catch { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "url", + code: ZodIssueCode.invalid_string, + message: check3.message + }); + status.dirty(); + } + } else if (check3.kind === "regex") { + check3.regex.lastIndex = 0; + const testResult = check3.regex.test(input.data); + if (!testResult) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "regex", + code: ZodIssueCode.invalid_string, + message: check3.message + }); + status.dirty(); + } + } else if (check3.kind === "trim") { + input.data = input.data.trim(); + } else if (check3.kind === "includes") { + if (!input.data.includes(check3.value, check3.position)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: { includes: check3.value, position: check3.position }, + message: check3.message + }); + status.dirty(); + } + } else if (check3.kind === "toLowerCase") { + input.data = input.data.toLowerCase(); + } else if (check3.kind === "toUpperCase") { + input.data = input.data.toUpperCase(); + } else if (check3.kind === "startsWith") { + if (!input.data.startsWith(check3.value)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: { startsWith: check3.value }, + message: check3.message + }); + status.dirty(); + } + } else if (check3.kind === "endsWith") { + if (!input.data.endsWith(check3.value)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: { endsWith: check3.value }, + message: check3.message + }); + status.dirty(); + } + } else if (check3.kind === "datetime") { + const regex = datetimeRegex(check3); + if (!regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: "datetime", + message: check3.message + }); + status.dirty(); + } + } else if (check3.kind === "date") { + const regex = dateRegex; + if (!regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: "date", + message: check3.message + }); + status.dirty(); + } + } else if (check3.kind === "time") { + const regex = timeRegex(check3); + if (!regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: "time", + message: check3.message + }); + status.dirty(); + } + } else if (check3.kind === "duration") { + if (!durationRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "duration", + code: ZodIssueCode.invalid_string, + message: check3.message + }); + status.dirty(); + } + } else if (check3.kind === "ip") { + if (!isValidIP(input.data, check3.version)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "ip", + code: ZodIssueCode.invalid_string, + message: check3.message + }); + status.dirty(); + } + } else if (check3.kind === "jwt") { + if (!isValidJWT(input.data, check3.alg)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "jwt", + code: ZodIssueCode.invalid_string, + message: check3.message + }); + status.dirty(); + } + } else if (check3.kind === "cidr") { + if (!isValidCidr(input.data, check3.version)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "cidr", + code: ZodIssueCode.invalid_string, + message: check3.message + }); + status.dirty(); + } + } else if (check3.kind === "base64") { + if (!base64Regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "base64", + code: ZodIssueCode.invalid_string, + message: check3.message + }); + status.dirty(); + } + } else if (check3.kind === "base64url") { + if (!base64urlRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "base64url", + code: ZodIssueCode.invalid_string, + message: check3.message + }); + status.dirty(); + } + } else { + util.assertNever(check3); + } + } + return { status: status.value, value: input.data }; + } + _regex(regex, validation, message2) { + return this.refinement((data2) => regex.test(data2), { + validation, + code: ZodIssueCode.invalid_string, + ...errorUtil.errToObj(message2) + }); + } + _addCheck(check3) { + return new _ZodString2({ + ...this._def, + checks: [...this._def.checks, check3] + }); + } + email(message2) { + return this._addCheck({ kind: "email", ...errorUtil.errToObj(message2) }); + } + url(message2) { + return this._addCheck({ kind: "url", ...errorUtil.errToObj(message2) }); + } + emoji(message2) { + return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message2) }); + } + uuid(message2) { + return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message2) }); + } + nanoid(message2) { + return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message2) }); + } + cuid(message2) { + return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message2) }); + } + cuid2(message2) { + return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message2) }); + } + ulid(message2) { + return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message2) }); + } + base64(message2) { + return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message2) }); + } + base64url(message2) { + return this._addCheck({ + kind: "base64url", + ...errorUtil.errToObj(message2) + }); + } + jwt(options) { + return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) }); + } + ip(options) { + return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) }); + } + cidr(options) { + return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) }); + } + datetime(options) { + if (typeof options === "string") { + return this._addCheck({ + kind: "datetime", + precision: null, + offset: false, + local: false, + message: options + }); + } + return this._addCheck({ + kind: "datetime", + precision: typeof options?.precision === "undefined" ? null : options?.precision, + offset: options?.offset ?? false, + local: options?.local ?? false, + ...errorUtil.errToObj(options?.message) + }); + } + date(message2) { + return this._addCheck({ kind: "date", message: message2 }); + } + time(options) { + if (typeof options === "string") { + return this._addCheck({ + kind: "time", + precision: null, + message: options + }); + } + return this._addCheck({ + kind: "time", + precision: typeof options?.precision === "undefined" ? null : options?.precision, + ...errorUtil.errToObj(options?.message) + }); + } + duration(message2) { + return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message2) }); + } + regex(regex, message2) { + return this._addCheck({ + kind: "regex", + regex, + ...errorUtil.errToObj(message2) + }); + } + includes(value, options) { + return this._addCheck({ + kind: "includes", + value, + position: options?.position, + ...errorUtil.errToObj(options?.message) + }); + } + startsWith(value, message2) { + return this._addCheck({ + kind: "startsWith", + value, + ...errorUtil.errToObj(message2) + }); + } + endsWith(value, message2) { + return this._addCheck({ + kind: "endsWith", + value, + ...errorUtil.errToObj(message2) + }); + } + min(minLength, message2) { + return this._addCheck({ + kind: "min", + value: minLength, + ...errorUtil.errToObj(message2) + }); + } + max(maxLength, message2) { + return this._addCheck({ + kind: "max", + value: maxLength, + ...errorUtil.errToObj(message2) + }); + } + length(len, message2) { + return this._addCheck({ + kind: "length", + value: len, + ...errorUtil.errToObj(message2) + }); + } + /** + * Equivalent to `.min(1)` + */ + nonempty(message2) { + return this.min(1, errorUtil.errToObj(message2)); + } + trim() { + return new _ZodString2({ + ...this._def, + checks: [...this._def.checks, { kind: "trim" }] + }); + } + toLowerCase() { + return new _ZodString2({ + ...this._def, + checks: [...this._def.checks, { kind: "toLowerCase" }] + }); + } + toUpperCase() { + return new _ZodString2({ + ...this._def, + checks: [...this._def.checks, { kind: "toUpperCase" }] + }); + } + get isDatetime() { + return !!this._def.checks.find((ch) => ch.kind === "datetime"); + } + get isDate() { + return !!this._def.checks.find((ch) => ch.kind === "date"); + } + get isTime() { + return !!this._def.checks.find((ch) => ch.kind === "time"); + } + get isDuration() { + return !!this._def.checks.find((ch) => ch.kind === "duration"); + } + get isEmail() { + return !!this._def.checks.find((ch) => ch.kind === "email"); + } + get isURL() { + return !!this._def.checks.find((ch) => ch.kind === "url"); + } + get isEmoji() { + return !!this._def.checks.find((ch) => ch.kind === "emoji"); + } + get isUUID() { + return !!this._def.checks.find((ch) => ch.kind === "uuid"); + } + get isNANOID() { + return !!this._def.checks.find((ch) => ch.kind === "nanoid"); + } + get isCUID() { + return !!this._def.checks.find((ch) => ch.kind === "cuid"); + } + get isCUID2() { + return !!this._def.checks.find((ch) => ch.kind === "cuid2"); + } + get isULID() { + return !!this._def.checks.find((ch) => ch.kind === "ulid"); + } + get isIP() { + return !!this._def.checks.find((ch) => ch.kind === "ip"); + } + get isCIDR() { + return !!this._def.checks.find((ch) => ch.kind === "cidr"); + } + get isBase64() { + return !!this._def.checks.find((ch) => ch.kind === "base64"); + } + get isBase64url() { + return !!this._def.checks.find((ch) => ch.kind === "base64url"); + } + get minLength() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min; + } + get maxLength() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max; + } +}; +ZodString.create = (params) => { + return new ZodString({ + checks: [], + typeName: ZodFirstPartyTypeKind.ZodString, + coerce: params?.coerce ?? false, + ...processCreateParams(params) + }); +}; +function floatSafeRemainder(val, step) { + const valDecCount = (val.toString().split(".")[1] || "").length; + const stepDecCount = (step.toString().split(".")[1] || "").length; + const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; + const valInt = Number.parseInt(val.toFixed(decCount).replace(".", "")); + const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", "")); + return valInt % stepInt / 10 ** decCount; +} +var ZodNumber = class _ZodNumber extends ZodType { + constructor() { + super(...arguments); + this.min = this.gte; + this.max = this.lte; + this.step = this.multipleOf; + } + _parse(input) { + if (this._def.coerce) { + input.data = Number(input.data); + } + const parsedType2 = this._getType(input); + if (parsedType2 !== ZodParsedType.number) { + const ctx2 = this._getOrReturnCtx(input); + addIssueToContext(ctx2, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.number, + received: ctx2.parsedType + }); + return INVALID; + } + let ctx = void 0; + const status = new ParseStatus(); + for (const check3 of this._def.checks) { + if (check3.kind === "int") { + if (!util.isInteger(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: "integer", + received: "float", + message: check3.message + }); + status.dirty(); + } + } else if (check3.kind === "min") { + const tooSmall = check3.inclusive ? input.data < check3.value : input.data <= check3.value; + if (tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: check3.value, + type: "number", + inclusive: check3.inclusive, + exact: false, + message: check3.message + }); + status.dirty(); + } + } else if (check3.kind === "max") { + const tooBig = check3.inclusive ? input.data > check3.value : input.data >= check3.value; + if (tooBig) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: check3.value, + type: "number", + inclusive: check3.inclusive, + exact: false, + message: check3.message + }); + status.dirty(); + } + } else if (check3.kind === "multipleOf") { + if (floatSafeRemainder(input.data, check3.value) !== 0) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.not_multiple_of, + multipleOf: check3.value, + message: check3.message + }); + status.dirty(); + } + } else if (check3.kind === "finite") { + if (!Number.isFinite(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.not_finite, + message: check3.message + }); + status.dirty(); + } + } else { + util.assertNever(check3); + } + } + return { status: status.value, value: input.data }; + } + gte(value, message2) { + return this.setLimit("min", value, true, errorUtil.toString(message2)); + } + gt(value, message2) { + return this.setLimit("min", value, false, errorUtil.toString(message2)); + } + lte(value, message2) { + return this.setLimit("max", value, true, errorUtil.toString(message2)); + } + lt(value, message2) { + return this.setLimit("max", value, false, errorUtil.toString(message2)); + } + setLimit(kind, value, inclusive, message2) { + return new _ZodNumber({ + ...this._def, + checks: [ + ...this._def.checks, + { + kind, + value, + inclusive, + message: errorUtil.toString(message2) + } + ] + }); + } + _addCheck(check3) { + return new _ZodNumber({ + ...this._def, + checks: [...this._def.checks, check3] + }); + } + int(message2) { + return this._addCheck({ + kind: "int", + message: errorUtil.toString(message2) + }); + } + positive(message2) { + return this._addCheck({ + kind: "min", + value: 0, + inclusive: false, + message: errorUtil.toString(message2) + }); + } + negative(message2) { + return this._addCheck({ + kind: "max", + value: 0, + inclusive: false, + message: errorUtil.toString(message2) + }); + } + nonpositive(message2) { + return this._addCheck({ + kind: "max", + value: 0, + inclusive: true, + message: errorUtil.toString(message2) + }); + } + nonnegative(message2) { + return this._addCheck({ + kind: "min", + value: 0, + inclusive: true, + message: errorUtil.toString(message2) + }); + } + multipleOf(value, message2) { + return this._addCheck({ + kind: "multipleOf", + value, + message: errorUtil.toString(message2) + }); + } + finite(message2) { + return this._addCheck({ + kind: "finite", + message: errorUtil.toString(message2) + }); + } + safe(message2) { + return this._addCheck({ + kind: "min", + inclusive: true, + value: Number.MIN_SAFE_INTEGER, + message: errorUtil.toString(message2) + })._addCheck({ + kind: "max", + inclusive: true, + value: Number.MAX_SAFE_INTEGER, + message: errorUtil.toString(message2) + }); + } + get minValue() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min; + } + get maxValue() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max; + } + get isInt() { + return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value)); + } + get isFinite() { + let max = null; + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") { + return true; + } else if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } else if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return Number.isFinite(min) && Number.isFinite(max); + } +}; +ZodNumber.create = (params) => { + return new ZodNumber({ + checks: [], + typeName: ZodFirstPartyTypeKind.ZodNumber, + coerce: params?.coerce || false, + ...processCreateParams(params) + }); +}; +var ZodBigInt = class _ZodBigInt extends ZodType { + constructor() { + super(...arguments); + this.min = this.gte; + this.max = this.lte; + } + _parse(input) { + if (this._def.coerce) { + try { + input.data = BigInt(input.data); + } catch { + return this._getInvalidInput(input); + } + } + const parsedType2 = this._getType(input); + if (parsedType2 !== ZodParsedType.bigint) { + return this._getInvalidInput(input); + } + let ctx = void 0; + const status = new ParseStatus(); + for (const check3 of this._def.checks) { + if (check3.kind === "min") { + const tooSmall = check3.inclusive ? input.data < check3.value : input.data <= check3.value; + if (tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + type: "bigint", + minimum: check3.value, + inclusive: check3.inclusive, + message: check3.message + }); + status.dirty(); + } + } else if (check3.kind === "max") { + const tooBig = check3.inclusive ? input.data > check3.value : input.data >= check3.value; + if (tooBig) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + type: "bigint", + maximum: check3.value, + inclusive: check3.inclusive, + message: check3.message + }); + status.dirty(); + } + } else if (check3.kind === "multipleOf") { + if (input.data % check3.value !== BigInt(0)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.not_multiple_of, + multipleOf: check3.value, + message: check3.message + }); + status.dirty(); + } + } else { + util.assertNever(check3); + } + } + return { status: status.value, value: input.data }; + } + _getInvalidInput(input) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.bigint, + received: ctx.parsedType + }); + return INVALID; + } + gte(value, message2) { + return this.setLimit("min", value, true, errorUtil.toString(message2)); + } + gt(value, message2) { + return this.setLimit("min", value, false, errorUtil.toString(message2)); + } + lte(value, message2) { + return this.setLimit("max", value, true, errorUtil.toString(message2)); + } + lt(value, message2) { + return this.setLimit("max", value, false, errorUtil.toString(message2)); + } + setLimit(kind, value, inclusive, message2) { + return new _ZodBigInt({ + ...this._def, + checks: [ + ...this._def.checks, + { + kind, + value, + inclusive, + message: errorUtil.toString(message2) + } + ] + }); + } + _addCheck(check3) { + return new _ZodBigInt({ + ...this._def, + checks: [...this._def.checks, check3] + }); + } + positive(message2) { + return this._addCheck({ + kind: "min", + value: BigInt(0), + inclusive: false, + message: errorUtil.toString(message2) + }); + } + negative(message2) { + return this._addCheck({ + kind: "max", + value: BigInt(0), + inclusive: false, + message: errorUtil.toString(message2) + }); + } + nonpositive(message2) { + return this._addCheck({ + kind: "max", + value: BigInt(0), + inclusive: true, + message: errorUtil.toString(message2) + }); + } + nonnegative(message2) { + return this._addCheck({ + kind: "min", + value: BigInt(0), + inclusive: true, + message: errorUtil.toString(message2) + }); + } + multipleOf(value, message2) { + return this._addCheck({ + kind: "multipleOf", + value, + message: errorUtil.toString(message2) + }); + } + get minValue() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min; + } + get maxValue() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max; + } +}; +ZodBigInt.create = (params) => { + return new ZodBigInt({ + checks: [], + typeName: ZodFirstPartyTypeKind.ZodBigInt, + coerce: params?.coerce ?? false, + ...processCreateParams(params) + }); +}; +var ZodBoolean = class extends ZodType { + _parse(input) { + if (this._def.coerce) { + input.data = Boolean(input.data); + } + const parsedType2 = this._getType(input); + if (parsedType2 !== ZodParsedType.boolean) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.boolean, + received: ctx.parsedType + }); + return INVALID; + } + return OK(input.data); + } +}; +ZodBoolean.create = (params) => { + return new ZodBoolean({ + typeName: ZodFirstPartyTypeKind.ZodBoolean, + coerce: params?.coerce || false, + ...processCreateParams(params) + }); +}; +var ZodDate = class _ZodDate extends ZodType { + _parse(input) { + if (this._def.coerce) { + input.data = new Date(input.data); + } + const parsedType2 = this._getType(input); + if (parsedType2 !== ZodParsedType.date) { + const ctx2 = this._getOrReturnCtx(input); + addIssueToContext(ctx2, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.date, + received: ctx2.parsedType + }); + return INVALID; + } + if (Number.isNaN(input.data.getTime())) { + const ctx2 = this._getOrReturnCtx(input); + addIssueToContext(ctx2, { + code: ZodIssueCode.invalid_date + }); + return INVALID; + } + const status = new ParseStatus(); + let ctx = void 0; + for (const check3 of this._def.checks) { + if (check3.kind === "min") { + if (input.data.getTime() < check3.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + message: check3.message, + inclusive: true, + exact: false, + minimum: check3.value, + type: "date" + }); + status.dirty(); + } + } else if (check3.kind === "max") { + if (input.data.getTime() > check3.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + message: check3.message, + inclusive: true, + exact: false, + maximum: check3.value, + type: "date" + }); + status.dirty(); + } + } else { + util.assertNever(check3); + } + } + return { + status: status.value, + value: new Date(input.data.getTime()) + }; + } + _addCheck(check3) { + return new _ZodDate({ + ...this._def, + checks: [...this._def.checks, check3] + }); + } + min(minDate, message2) { + return this._addCheck({ + kind: "min", + value: minDate.getTime(), + message: errorUtil.toString(message2) + }); + } + max(maxDate, message2) { + return this._addCheck({ + kind: "max", + value: maxDate.getTime(), + message: errorUtil.toString(message2) + }); + } + get minDate() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min != null ? new Date(min) : null; + } + get maxDate() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max != null ? new Date(max) : null; + } +}; +ZodDate.create = (params) => { + return new ZodDate({ + checks: [], + coerce: params?.coerce || false, + typeName: ZodFirstPartyTypeKind.ZodDate, + ...processCreateParams(params) + }); +}; +var ZodSymbol = class extends ZodType { + _parse(input) { + const parsedType2 = this._getType(input); + if (parsedType2 !== ZodParsedType.symbol) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.symbol, + received: ctx.parsedType + }); + return INVALID; + } + return OK(input.data); + } +}; +ZodSymbol.create = (params) => { + return new ZodSymbol({ + typeName: ZodFirstPartyTypeKind.ZodSymbol, + ...processCreateParams(params) + }); +}; +var ZodUndefined = class extends ZodType { + _parse(input) { + const parsedType2 = this._getType(input); + if (parsedType2 !== ZodParsedType.undefined) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.undefined, + received: ctx.parsedType + }); + return INVALID; + } + return OK(input.data); + } +}; +ZodUndefined.create = (params) => { + return new ZodUndefined({ + typeName: ZodFirstPartyTypeKind.ZodUndefined, + ...processCreateParams(params) + }); +}; +var ZodNull = class extends ZodType { + _parse(input) { + const parsedType2 = this._getType(input); + if (parsedType2 !== ZodParsedType.null) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.null, + received: ctx.parsedType + }); + return INVALID; + } + return OK(input.data); + } +}; +ZodNull.create = (params) => { + return new ZodNull({ + typeName: ZodFirstPartyTypeKind.ZodNull, + ...processCreateParams(params) + }); +}; +var ZodAny = class extends ZodType { + constructor() { + super(...arguments); + this._any = true; + } + _parse(input) { + return OK(input.data); + } +}; +ZodAny.create = (params) => { + return new ZodAny({ + typeName: ZodFirstPartyTypeKind.ZodAny, + ...processCreateParams(params) + }); +}; +var ZodUnknown = class extends ZodType { + constructor() { + super(...arguments); + this._unknown = true; + } + _parse(input) { + return OK(input.data); + } +}; +ZodUnknown.create = (params) => { + return new ZodUnknown({ + typeName: ZodFirstPartyTypeKind.ZodUnknown, + ...processCreateParams(params) + }); +}; +var ZodNever = class extends ZodType { + _parse(input) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.never, + received: ctx.parsedType + }); + return INVALID; + } +}; +ZodNever.create = (params) => { + return new ZodNever({ + typeName: ZodFirstPartyTypeKind.ZodNever, + ...processCreateParams(params) + }); +}; +var ZodVoid = class extends ZodType { + _parse(input) { + const parsedType2 = this._getType(input); + if (parsedType2 !== ZodParsedType.undefined) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.void, + received: ctx.parsedType + }); + return INVALID; + } + return OK(input.data); + } +}; +ZodVoid.create = (params) => { + return new ZodVoid({ + typeName: ZodFirstPartyTypeKind.ZodVoid, + ...processCreateParams(params) + }); +}; +var ZodArray = class _ZodArray extends ZodType { + _parse(input) { + const { ctx, status } = this._processInputParams(input); + const def = this._def; + if (ctx.parsedType !== ZodParsedType.array) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.array, + received: ctx.parsedType + }); + return INVALID; + } + if (def.exactLength !== null) { + const tooBig = ctx.data.length > def.exactLength.value; + const tooSmall = ctx.data.length < def.exactLength.value; + if (tooBig || tooSmall) { + addIssueToContext(ctx, { + code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small, + minimum: tooSmall ? def.exactLength.value : void 0, + maximum: tooBig ? def.exactLength.value : void 0, + type: "array", + inclusive: true, + exact: true, + message: def.exactLength.message + }); + status.dirty(); + } + } + if (def.minLength !== null) { + if (ctx.data.length < def.minLength.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: def.minLength.value, + type: "array", + inclusive: true, + exact: false, + message: def.minLength.message + }); + status.dirty(); + } + } + if (def.maxLength !== null) { + if (ctx.data.length > def.maxLength.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: def.maxLength.value, + type: "array", + inclusive: true, + exact: false, + message: def.maxLength.message + }); + status.dirty(); + } + } + if (ctx.common.async) { + return Promise.all([...ctx.data].map((item, i5) => { + return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i5)); + })).then((result2) => { + return ParseStatus.mergeArray(status, result2); + }); + } + const result = [...ctx.data].map((item, i5) => { + return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i5)); + }); + return ParseStatus.mergeArray(status, result); + } + get element() { + return this._def.type; + } + min(minLength, message2) { + return new _ZodArray({ + ...this._def, + minLength: { value: minLength, message: errorUtil.toString(message2) } + }); + } + max(maxLength, message2) { + return new _ZodArray({ + ...this._def, + maxLength: { value: maxLength, message: errorUtil.toString(message2) } + }); + } + length(len, message2) { + return new _ZodArray({ + ...this._def, + exactLength: { value: len, message: errorUtil.toString(message2) } + }); + } + nonempty(message2) { + return this.min(1, message2); + } +}; +ZodArray.create = (schema2, params) => { + return new ZodArray({ + type: schema2, + minLength: null, + maxLength: null, + exactLength: null, + typeName: ZodFirstPartyTypeKind.ZodArray, + ...processCreateParams(params) + }); +}; +function deepPartialify(schema2) { + if (schema2 instanceof ZodObject) { + const newShape = {}; + for (const key in schema2.shape) { + const fieldSchema = schema2.shape[key]; + newShape[key] = ZodOptional.create(deepPartialify(fieldSchema)); + } + return new ZodObject({ + ...schema2._def, + shape: () => newShape + }); + } else if (schema2 instanceof ZodArray) { + return new ZodArray({ + ...schema2._def, + type: deepPartialify(schema2.element) + }); + } else if (schema2 instanceof ZodOptional) { + return ZodOptional.create(deepPartialify(schema2.unwrap())); + } else if (schema2 instanceof ZodNullable) { + return ZodNullable.create(deepPartialify(schema2.unwrap())); + } else if (schema2 instanceof ZodTuple) { + return ZodTuple.create(schema2.items.map((item) => deepPartialify(item))); + } else { + return schema2; + } +} +var ZodObject = class _ZodObject extends ZodType { + constructor() { + super(...arguments); + this._cached = null; + this.nonstrict = this.passthrough; + this.augment = this.extend; + } + _getCached() { + if (this._cached !== null) + return this._cached; + const shape = this._def.shape(); + const keys = util.objectKeys(shape); + this._cached = { shape, keys }; + return this._cached; + } + _parse(input) { + const parsedType2 = this._getType(input); + if (parsedType2 !== ZodParsedType.object) { + const ctx2 = this._getOrReturnCtx(input); + addIssueToContext(ctx2, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.object, + received: ctx2.parsedType + }); + return INVALID; + } + const { status, ctx } = this._processInputParams(input); + const { shape, keys: shapeKeys } = this._getCached(); + const extraKeys = []; + if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) { + for (const key in ctx.data) { + if (!shapeKeys.includes(key)) { + extraKeys.push(key); + } + } + } + const pairs = []; + for (const key of shapeKeys) { + const keyValidator = shape[key]; + const value = ctx.data[key]; + pairs.push({ + key: { status: "valid", value: key }, + value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)), + alwaysSet: key in ctx.data + }); + } + if (this._def.catchall instanceof ZodNever) { + const unknownKeys = this._def.unknownKeys; + if (unknownKeys === "passthrough") { + for (const key of extraKeys) { + pairs.push({ + key: { status: "valid", value: key }, + value: { status: "valid", value: ctx.data[key] } + }); + } + } else if (unknownKeys === "strict") { + if (extraKeys.length > 0) { + addIssueToContext(ctx, { + code: ZodIssueCode.unrecognized_keys, + keys: extraKeys + }); + status.dirty(); + } + } else if (unknownKeys === "strip") { + } else { + throw new Error(`Internal ZodObject error: invalid unknownKeys value.`); + } + } else { + const catchall = this._def.catchall; + for (const key of extraKeys) { + const value = ctx.data[key]; + pairs.push({ + key: { status: "valid", value: key }, + value: catchall._parse( + new ParseInputLazyPath(ctx, value, ctx.path, key) + //, ctx.child(key), value, getParsedType(value) + ), + alwaysSet: key in ctx.data + }); + } + } + if (ctx.common.async) { + return Promise.resolve().then(async () => { + const syncPairs = []; + for (const pair of pairs) { + const key = await pair.key; + const value = await pair.value; + syncPairs.push({ + key, + value, + alwaysSet: pair.alwaysSet + }); + } + return syncPairs; + }).then((syncPairs) => { + return ParseStatus.mergeObjectSync(status, syncPairs); + }); + } else { + return ParseStatus.mergeObjectSync(status, pairs); + } + } + get shape() { + return this._def.shape(); + } + strict(message2) { + errorUtil.errToObj; + return new _ZodObject({ + ...this._def, + unknownKeys: "strict", + ...message2 !== void 0 ? { + errorMap: (issue2, ctx) => { + const defaultError = this._def.errorMap?.(issue2, ctx).message ?? ctx.defaultError; + if (issue2.code === "unrecognized_keys") + return { + message: errorUtil.errToObj(message2).message ?? defaultError + }; + return { + message: defaultError + }; + } + } : {} + }); + } + strip() { + return new _ZodObject({ + ...this._def, + unknownKeys: "strip" + }); + } + passthrough() { + return new _ZodObject({ + ...this._def, + unknownKeys: "passthrough" + }); + } + // const AugmentFactory = + // (def: Def) => + // ( + // augmentation: Augmentation + // ): ZodObject< + // extendShape, Augmentation>, + // Def["unknownKeys"], + // Def["catchall"] + // > => { + // return new ZodObject({ + // ...def, + // shape: () => ({ + // ...def.shape(), + // ...augmentation, + // }), + // }) as any; + // }; + extend(augmentation) { + return new _ZodObject({ + ...this._def, + shape: () => ({ + ...this._def.shape(), + ...augmentation + }) + }); + } + /** + * Prior to zod@1.0.12 there was a bug in the + * inferred type of merged objects. Please + * upgrade if you are experiencing issues. + */ + merge(merging) { + const merged = new _ZodObject({ + unknownKeys: merging._def.unknownKeys, + catchall: merging._def.catchall, + shape: () => ({ + ...this._def.shape(), + ...merging._def.shape() + }), + typeName: ZodFirstPartyTypeKind.ZodObject + }); + return merged; + } + // merge< + // Incoming extends AnyZodObject, + // Augmentation extends Incoming["shape"], + // NewOutput extends { + // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation + // ? Augmentation[k]["_output"] + // : k extends keyof Output + // ? Output[k] + // : never; + // }, + // NewInput extends { + // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation + // ? Augmentation[k]["_input"] + // : k extends keyof Input + // ? Input[k] + // : never; + // } + // >( + // merging: Incoming + // ): ZodObject< + // extendShape>, + // Incoming["_def"]["unknownKeys"], + // Incoming["_def"]["catchall"], + // NewOutput, + // NewInput + // > { + // const merged: any = new ZodObject({ + // unknownKeys: merging._def.unknownKeys, + // catchall: merging._def.catchall, + // shape: () => + // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), + // typeName: ZodFirstPartyTypeKind.ZodObject, + // }) as any; + // return merged; + // } + setKey(key, schema2) { + return this.augment({ [key]: schema2 }); + } + // merge( + // merging: Incoming + // ): //ZodObject = (merging) => { + // ZodObject< + // extendShape>, + // Incoming["_def"]["unknownKeys"], + // Incoming["_def"]["catchall"] + // > { + // // const mergedShape = objectUtil.mergeShapes( + // // this._def.shape(), + // // merging._def.shape() + // // ); + // const merged: any = new ZodObject({ + // unknownKeys: merging._def.unknownKeys, + // catchall: merging._def.catchall, + // shape: () => + // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), + // typeName: ZodFirstPartyTypeKind.ZodObject, + // }) as any; + // return merged; + // } + catchall(index2) { + return new _ZodObject({ + ...this._def, + catchall: index2 + }); + } + pick(mask) { + const shape = {}; + for (const key of util.objectKeys(mask)) { + if (mask[key] && this.shape[key]) { + shape[key] = this.shape[key]; + } + } + return new _ZodObject({ + ...this._def, + shape: () => shape + }); + } + omit(mask) { + const shape = {}; + for (const key of util.objectKeys(this.shape)) { + if (!mask[key]) { + shape[key] = this.shape[key]; + } + } + return new _ZodObject({ + ...this._def, + shape: () => shape + }); + } + /** + * @deprecated + */ + deepPartial() { + return deepPartialify(this); + } + partial(mask) { + const newShape = {}; + for (const key of util.objectKeys(this.shape)) { + const fieldSchema = this.shape[key]; + if (mask && !mask[key]) { + newShape[key] = fieldSchema; + } else { + newShape[key] = fieldSchema.optional(); + } + } + return new _ZodObject({ + ...this._def, + shape: () => newShape + }); + } + required(mask) { + const newShape = {}; + for (const key of util.objectKeys(this.shape)) { + if (mask && !mask[key]) { + newShape[key] = this.shape[key]; + } else { + const fieldSchema = this.shape[key]; + let newField = fieldSchema; + while (newField instanceof ZodOptional) { + newField = newField._def.innerType; + } + newShape[key] = newField; + } + } + return new _ZodObject({ + ...this._def, + shape: () => newShape + }); + } + keyof() { + return createZodEnum(util.objectKeys(this.shape)); + } +}; +ZodObject.create = (shape, params) => { + return new ZodObject({ + shape: () => shape, + unknownKeys: "strip", + catchall: ZodNever.create(), + typeName: ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params) + }); +}; +ZodObject.strictCreate = (shape, params) => { + return new ZodObject({ + shape: () => shape, + unknownKeys: "strict", + catchall: ZodNever.create(), + typeName: ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params) + }); +}; +ZodObject.lazycreate = (shape, params) => { + return new ZodObject({ + shape, + unknownKeys: "strip", + catchall: ZodNever.create(), + typeName: ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params) + }); +}; +var ZodUnion = class extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + const options = this._def.options; + function handleResults(results) { + for (const result of results) { + if (result.result.status === "valid") { + return result.result; + } + } + for (const result of results) { + if (result.result.status === "dirty") { + ctx.common.issues.push(...result.ctx.common.issues); + return result.result; + } + } + const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues)); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_union, + unionErrors + }); + return INVALID; + } + if (ctx.common.async) { + return Promise.all(options.map(async (option) => { + const childCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [] + }, + parent: null + }; + return { + result: await option._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: childCtx + }), + ctx: childCtx + }; + })).then(handleResults); + } else { + let dirty = void 0; + const issues2 = []; + for (const option of options) { + const childCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [] + }, + parent: null + }; + const result = option._parseSync({ + data: ctx.data, + path: ctx.path, + parent: childCtx + }); + if (result.status === "valid") { + return result; + } else if (result.status === "dirty" && !dirty) { + dirty = { result, ctx: childCtx }; + } + if (childCtx.common.issues.length) { + issues2.push(childCtx.common.issues); + } + } + if (dirty) { + ctx.common.issues.push(...dirty.ctx.common.issues); + return dirty.result; + } + const unionErrors = issues2.map((issues3) => new ZodError(issues3)); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_union, + unionErrors + }); + return INVALID; + } + } + get options() { + return this._def.options; + } +}; +ZodUnion.create = (types2, params) => { + return new ZodUnion({ + options: types2, + typeName: ZodFirstPartyTypeKind.ZodUnion, + ...processCreateParams(params) + }); +}; +var getDiscriminator = (type) => { + if (type instanceof ZodLazy) { + return getDiscriminator(type.schema); + } else if (type instanceof ZodEffects) { + return getDiscriminator(type.innerType()); + } else if (type instanceof ZodLiteral) { + return [type.value]; + } else if (type instanceof ZodEnum) { + return type.options; + } else if (type instanceof ZodNativeEnum) { + return util.objectValues(type.enum); + } else if (type instanceof ZodDefault) { + return getDiscriminator(type._def.innerType); + } else if (type instanceof ZodUndefined) { + return [void 0]; + } else if (type instanceof ZodNull) { + return [null]; + } else if (type instanceof ZodOptional) { + return [void 0, ...getDiscriminator(type.unwrap())]; + } else if (type instanceof ZodNullable) { + return [null, ...getDiscriminator(type.unwrap())]; + } else if (type instanceof ZodBranded) { + return getDiscriminator(type.unwrap()); + } else if (type instanceof ZodReadonly) { + return getDiscriminator(type.unwrap()); + } else if (type instanceof ZodCatch) { + return getDiscriminator(type._def.innerType); + } else { + return []; + } +}; +var ZodDiscriminatedUnion = class _ZodDiscriminatedUnion extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.object) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.object, + received: ctx.parsedType + }); + return INVALID; + } + const discriminator = this.discriminator; + const discriminatorValue = ctx.data[discriminator]; + const option = this.optionsMap.get(discriminatorValue); + if (!option) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_union_discriminator, + options: Array.from(this.optionsMap.keys()), + path: [discriminator] + }); + return INVALID; + } + if (ctx.common.async) { + return option._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + } else { + return option._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + } + } + get discriminator() { + return this._def.discriminator; + } + get options() { + return this._def.options; + } + get optionsMap() { + return this._def.optionsMap; + } + /** + * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor. + * However, it only allows a union of objects, all of which need to share a discriminator property. This property must + * have a different value for each object in the union. + * @param discriminator the name of the discriminator property + * @param types an array of object schemas + * @param params + */ + static create(discriminator, options, params) { + const optionsMap = /* @__PURE__ */ new Map(); + for (const type of options) { + const discriminatorValues = getDiscriminator(type.shape[discriminator]); + if (!discriminatorValues.length) { + throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`); + } + for (const value of discriminatorValues) { + if (optionsMap.has(value)) { + throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`); + } + optionsMap.set(value, type); + } + } + return new _ZodDiscriminatedUnion({ + typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion, + discriminator, + options, + optionsMap, + ...processCreateParams(params) + }); + } +}; +function mergeValues(a5, b6) { + const aType = getParsedType(a5); + const bType = getParsedType(b6); + if (a5 === b6) { + return { valid: true, data: a5 }; + } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) { + const bKeys = util.objectKeys(b6); + const sharedKeys = util.objectKeys(a5).filter((key) => bKeys.indexOf(key) !== -1); + const newObj = { ...a5, ...b6 }; + for (const key of sharedKeys) { + const sharedValue = mergeValues(a5[key], b6[key]); + if (!sharedValue.valid) { + return { valid: false }; + } + newObj[key] = sharedValue.data; + } + return { valid: true, data: newObj }; + } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) { + if (a5.length !== b6.length) { + return { valid: false }; + } + const newArray = []; + for (let index2 = 0; index2 < a5.length; index2++) { + const itemA = a5[index2]; + const itemB = b6[index2]; + const sharedValue = mergeValues(itemA, itemB); + if (!sharedValue.valid) { + return { valid: false }; + } + newArray.push(sharedValue.data); + } + return { valid: true, data: newArray }; + } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a5 === +b6) { + return { valid: true, data: a5 }; + } else { + return { valid: false }; + } +} +var ZodIntersection = class extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + const handleParsed = (parsedLeft, parsedRight) => { + if (isAborted(parsedLeft) || isAborted(parsedRight)) { + return INVALID; + } + const merged = mergeValues(parsedLeft.value, parsedRight.value); + if (!merged.valid) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_intersection_types + }); + return INVALID; + } + if (isDirty(parsedLeft) || isDirty(parsedRight)) { + status.dirty(); + } + return { status: status.value, value: merged.data }; + }; + if (ctx.common.async) { + return Promise.all([ + this._def.left._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }), + this._def.right._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }) + ]).then(([left, right]) => handleParsed(left, right)); + } else { + return handleParsed(this._def.left._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }), this._def.right._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + })); + } + } +}; +ZodIntersection.create = (left, right, params) => { + return new ZodIntersection({ + left, + right, + typeName: ZodFirstPartyTypeKind.ZodIntersection, + ...processCreateParams(params) + }); +}; +var ZodTuple = class _ZodTuple extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.array) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.array, + received: ctx.parsedType + }); + return INVALID; + } + if (ctx.data.length < this._def.items.length) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: this._def.items.length, + inclusive: true, + exact: false, + type: "array" + }); + return INVALID; + } + const rest = this._def.rest; + if (!rest && ctx.data.length > this._def.items.length) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: this._def.items.length, + inclusive: true, + exact: false, + type: "array" + }); + status.dirty(); + } + const items = [...ctx.data].map((item, itemIndex) => { + const schema2 = this._def.items[itemIndex] || this._def.rest; + if (!schema2) + return null; + return schema2._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex)); + }).filter((x5) => !!x5); + if (ctx.common.async) { + return Promise.all(items).then((results) => { + return ParseStatus.mergeArray(status, results); + }); + } else { + return ParseStatus.mergeArray(status, items); + } + } + get items() { + return this._def.items; + } + rest(rest) { + return new _ZodTuple({ + ...this._def, + rest + }); + } +}; +ZodTuple.create = (schemas, params) => { + if (!Array.isArray(schemas)) { + throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); + } + return new ZodTuple({ + items: schemas, + typeName: ZodFirstPartyTypeKind.ZodTuple, + rest: null, + ...processCreateParams(params) + }); +}; +var ZodRecord = class _ZodRecord extends ZodType { + get keySchema() { + return this._def.keyType; + } + get valueSchema() { + return this._def.valueType; + } + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.object) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.object, + received: ctx.parsedType + }); + return INVALID; + } + const pairs = []; + const keyType = this._def.keyType; + const valueType = this._def.valueType; + for (const key in ctx.data) { + pairs.push({ + key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)), + value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)), + alwaysSet: key in ctx.data + }); + } + if (ctx.common.async) { + return ParseStatus.mergeObjectAsync(status, pairs); + } else { + return ParseStatus.mergeObjectSync(status, pairs); + } + } + get element() { + return this._def.valueType; + } + static create(first, second, third) { + if (second instanceof ZodType) { + return new _ZodRecord({ + keyType: first, + valueType: second, + typeName: ZodFirstPartyTypeKind.ZodRecord, + ...processCreateParams(third) + }); + } + return new _ZodRecord({ + keyType: ZodString.create(), + valueType: first, + typeName: ZodFirstPartyTypeKind.ZodRecord, + ...processCreateParams(second) + }); + } +}; +var ZodMap = class extends ZodType { + get keySchema() { + return this._def.keyType; + } + get valueSchema() { + return this._def.valueType; + } + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.map) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.map, + received: ctx.parsedType + }); + return INVALID; + } + const keyType = this._def.keyType; + const valueType = this._def.valueType; + const pairs = [...ctx.data.entries()].map(([key, value], index2) => { + return { + key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index2, "key"])), + value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index2, "value"])) + }; + }); + if (ctx.common.async) { + const finalMap = /* @__PURE__ */ new Map(); + return Promise.resolve().then(async () => { + for (const pair of pairs) { + const key = await pair.key; + const value = await pair.value; + if (key.status === "aborted" || value.status === "aborted") { + return INVALID; + } + if (key.status === "dirty" || value.status === "dirty") { + status.dirty(); + } + finalMap.set(key.value, value.value); + } + return { status: status.value, value: finalMap }; + }); + } else { + const finalMap = /* @__PURE__ */ new Map(); + for (const pair of pairs) { + const key = pair.key; + const value = pair.value; + if (key.status === "aborted" || value.status === "aborted") { + return INVALID; + } + if (key.status === "dirty" || value.status === "dirty") { + status.dirty(); + } + finalMap.set(key.value, value.value); + } + return { status: status.value, value: finalMap }; + } + } +}; +ZodMap.create = (keyType, valueType, params) => { + return new ZodMap({ + valueType, + keyType, + typeName: ZodFirstPartyTypeKind.ZodMap, + ...processCreateParams(params) + }); +}; +var ZodSet = class _ZodSet extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.set) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.set, + received: ctx.parsedType + }); + return INVALID; + } + const def = this._def; + if (def.minSize !== null) { + if (ctx.data.size < def.minSize.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: def.minSize.value, + type: "set", + inclusive: true, + exact: false, + message: def.minSize.message + }); + status.dirty(); + } + } + if (def.maxSize !== null) { + if (ctx.data.size > def.maxSize.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: def.maxSize.value, + type: "set", + inclusive: true, + exact: false, + message: def.maxSize.message + }); + status.dirty(); + } + } + const valueType = this._def.valueType; + function finalizeSet(elements2) { + const parsedSet = /* @__PURE__ */ new Set(); + for (const element of elements2) { + if (element.status === "aborted") + return INVALID; + if (element.status === "dirty") + status.dirty(); + parsedSet.add(element.value); + } + return { status: status.value, value: parsedSet }; + } + const elements = [...ctx.data.values()].map((item, i5) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i5))); + if (ctx.common.async) { + return Promise.all(elements).then((elements2) => finalizeSet(elements2)); + } else { + return finalizeSet(elements); + } + } + min(minSize, message2) { + return new _ZodSet({ + ...this._def, + minSize: { value: minSize, message: errorUtil.toString(message2) } + }); + } + max(maxSize, message2) { + return new _ZodSet({ + ...this._def, + maxSize: { value: maxSize, message: errorUtil.toString(message2) } + }); + } + size(size2, message2) { + return this.min(size2, message2).max(size2, message2); + } + nonempty(message2) { + return this.min(1, message2); + } +}; +ZodSet.create = (valueType, params) => { + return new ZodSet({ + valueType, + minSize: null, + maxSize: null, + typeName: ZodFirstPartyTypeKind.ZodSet, + ...processCreateParams(params) + }); +}; +var ZodFunction = class _ZodFunction extends ZodType { + constructor() { + super(...arguments); + this.validate = this.implement; + } + _parse(input) { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.function) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.function, + received: ctx.parsedType + }); + return INVALID; + } + function makeArgsIssue(args, error50) { + return makeIssue({ + data: args, + path: ctx.path, + errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x5) => !!x5), + issueData: { + code: ZodIssueCode.invalid_arguments, + argumentsError: error50 + } + }); + } + function makeReturnsIssue(returns, error50) { + return makeIssue({ + data: returns, + path: ctx.path, + errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x5) => !!x5), + issueData: { + code: ZodIssueCode.invalid_return_type, + returnTypeError: error50 + } + }); + } + const params = { errorMap: ctx.common.contextualErrorMap }; + const fn = ctx.data; + if (this._def.returns instanceof ZodPromise) { + const me = this; + return OK(async function(...args) { + const error50 = new ZodError([]); + const parsedArgs = await me._def.args.parseAsync(args, params).catch((e5) => { + error50.addIssue(makeArgsIssue(args, e5)); + throw error50; + }); + const result = await Reflect.apply(fn, this, parsedArgs); + const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e5) => { + error50.addIssue(makeReturnsIssue(result, e5)); + throw error50; + }); + return parsedReturns; + }); + } else { + const me = this; + return OK(function(...args) { + const parsedArgs = me._def.args.safeParse(args, params); + if (!parsedArgs.success) { + throw new ZodError([makeArgsIssue(args, parsedArgs.error)]); + } + const result = Reflect.apply(fn, this, parsedArgs.data); + const parsedReturns = me._def.returns.safeParse(result, params); + if (!parsedReturns.success) { + throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]); + } + return parsedReturns.data; + }); + } + } + parameters() { + return this._def.args; + } + returnType() { + return this._def.returns; + } + args(...items) { + return new _ZodFunction({ + ...this._def, + args: ZodTuple.create(items).rest(ZodUnknown.create()) + }); + } + returns(returnType) { + return new _ZodFunction({ + ...this._def, + returns: returnType + }); + } + implement(func) { + const validatedFunc = this.parse(func); + return validatedFunc; + } + strictImplement(func) { + const validatedFunc = this.parse(func); + return validatedFunc; + } + static create(args, returns, params) { + return new _ZodFunction({ + args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()), + returns: returns || ZodUnknown.create(), + typeName: ZodFirstPartyTypeKind.ZodFunction, + ...processCreateParams(params) + }); + } +}; +var ZodLazy = class extends ZodType { + get schema() { + return this._def.getter(); + } + _parse(input) { + const { ctx } = this._processInputParams(input); + const lazySchema = this._def.getter(); + return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx }); + } +}; +ZodLazy.create = (getter, params) => { + return new ZodLazy({ + getter, + typeName: ZodFirstPartyTypeKind.ZodLazy, + ...processCreateParams(params) + }); +}; +var ZodLiteral = class extends ZodType { + _parse(input) { + if (input.data !== this._def.value) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + received: ctx.data, + code: ZodIssueCode.invalid_literal, + expected: this._def.value + }); + return INVALID; + } + return { status: "valid", value: input.data }; + } + get value() { + return this._def.value; + } +}; +ZodLiteral.create = (value, params) => { + return new ZodLiteral({ + value, + typeName: ZodFirstPartyTypeKind.ZodLiteral, + ...processCreateParams(params) + }); +}; +function createZodEnum(values2, params) { + return new ZodEnum({ + values: values2, + typeName: ZodFirstPartyTypeKind.ZodEnum, + ...processCreateParams(params) + }); +} +var ZodEnum = class _ZodEnum extends ZodType { + _parse(input) { + if (typeof input.data !== "string") { + const ctx = this._getOrReturnCtx(input); + const expectedValues = this._def.values; + addIssueToContext(ctx, { + expected: util.joinValues(expectedValues), + received: ctx.parsedType, + code: ZodIssueCode.invalid_type + }); + return INVALID; + } + if (!this._cache) { + this._cache = new Set(this._def.values); + } + if (!this._cache.has(input.data)) { + const ctx = this._getOrReturnCtx(input); + const expectedValues = this._def.values; + addIssueToContext(ctx, { + received: ctx.data, + code: ZodIssueCode.invalid_enum_value, + options: expectedValues + }); + return INVALID; + } + return OK(input.data); + } + get options() { + return this._def.values; + } + get enum() { + const enumValues = {}; + for (const val of this._def.values) { + enumValues[val] = val; + } + return enumValues; + } + get Values() { + const enumValues = {}; + for (const val of this._def.values) { + enumValues[val] = val; + } + return enumValues; + } + get Enum() { + const enumValues = {}; + for (const val of this._def.values) { + enumValues[val] = val; + } + return enumValues; + } + extract(values2, newDef = this._def) { + return _ZodEnum.create(values2, { + ...this._def, + ...newDef + }); + } + exclude(values2, newDef = this._def) { + return _ZodEnum.create(this.options.filter((opt) => !values2.includes(opt)), { + ...this._def, + ...newDef + }); + } +}; +ZodEnum.create = createZodEnum; +var ZodNativeEnum = class extends ZodType { + _parse(input) { + const nativeEnumValues = util.getValidEnumValues(this._def.values); + const ctx = this._getOrReturnCtx(input); + if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) { + const expectedValues = util.objectValues(nativeEnumValues); + addIssueToContext(ctx, { + expected: util.joinValues(expectedValues), + received: ctx.parsedType, + code: ZodIssueCode.invalid_type + }); + return INVALID; + } + if (!this._cache) { + this._cache = new Set(util.getValidEnumValues(this._def.values)); + } + if (!this._cache.has(input.data)) { + const expectedValues = util.objectValues(nativeEnumValues); + addIssueToContext(ctx, { + received: ctx.data, + code: ZodIssueCode.invalid_enum_value, + options: expectedValues + }); + return INVALID; + } + return OK(input.data); + } + get enum() { + return this._def.values; + } +}; +ZodNativeEnum.create = (values2, params) => { + return new ZodNativeEnum({ + values: values2, + typeName: ZodFirstPartyTypeKind.ZodNativeEnum, + ...processCreateParams(params) + }); +}; +var ZodPromise = class extends ZodType { + unwrap() { + return this._def.type; + } + _parse(input) { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.promise, + received: ctx.parsedType + }); + return INVALID; + } + const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data); + return OK(promisified.then((data2) => { + return this._def.type.parseAsync(data2, { + path: ctx.path, + errorMap: ctx.common.contextualErrorMap + }); + })); + } +}; +ZodPromise.create = (schema2, params) => { + return new ZodPromise({ + type: schema2, + typeName: ZodFirstPartyTypeKind.ZodPromise, + ...processCreateParams(params) + }); +}; +var ZodEffects = class extends ZodType { + innerType() { + return this._def.schema; + } + sourceType() { + return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema; + } + _parse(input) { + const { status, ctx } = this._processInputParams(input); + const effect = this._def.effect || null; + const checkCtx = { + addIssue: (arg) => { + addIssueToContext(ctx, arg); + if (arg.fatal) { + status.abort(); + } else { + status.dirty(); + } + }, + get path() { + return ctx.path; + } + }; + checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx); + if (effect.type === "preprocess") { + const processed = effect.transform(ctx.data, checkCtx); + if (ctx.common.async) { + return Promise.resolve(processed).then(async (processed2) => { + if (status.value === "aborted") + return INVALID; + const result = await this._def.schema._parseAsync({ + data: processed2, + path: ctx.path, + parent: ctx + }); + if (result.status === "aborted") + return INVALID; + if (result.status === "dirty") + return DIRTY(result.value); + if (status.value === "dirty") + return DIRTY(result.value); + return result; + }); + } else { + if (status.value === "aborted") + return INVALID; + const result = this._def.schema._parseSync({ + data: processed, + path: ctx.path, + parent: ctx + }); + if (result.status === "aborted") + return INVALID; + if (result.status === "dirty") + return DIRTY(result.value); + if (status.value === "dirty") + return DIRTY(result.value); + return result; + } + } + if (effect.type === "refinement") { + const executeRefinement = (acc) => { + const result = effect.refinement(acc, checkCtx); + if (ctx.common.async) { + return Promise.resolve(result); + } + if (result instanceof Promise) { + throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead."); + } + return acc; + }; + if (ctx.common.async === false) { + const inner = this._def.schema._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + if (inner.status === "aborted") + return INVALID; + if (inner.status === "dirty") + status.dirty(); + executeRefinement(inner.value); + return { status: status.value, value: inner.value }; + } else { + return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => { + if (inner.status === "aborted") + return INVALID; + if (inner.status === "dirty") + status.dirty(); + return executeRefinement(inner.value).then(() => { + return { status: status.value, value: inner.value }; + }); + }); + } + } + if (effect.type === "transform") { + if (ctx.common.async === false) { + const base = this._def.schema._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + if (!isValid(base)) + return INVALID; + const result = effect.transform(base.value, checkCtx); + if (result instanceof Promise) { + throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`); + } + return { status: status.value, value: result }; + } else { + return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => { + if (!isValid(base)) + return INVALID; + return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ + status: status.value, + value: result + })); + }); + } + } + util.assertNever(effect); + } +}; +ZodEffects.create = (schema2, effect, params) => { + return new ZodEffects({ + schema: schema2, + typeName: ZodFirstPartyTypeKind.ZodEffects, + effect, + ...processCreateParams(params) + }); +}; +ZodEffects.createWithPreprocess = (preprocess2, schema2, params) => { + return new ZodEffects({ + schema: schema2, + effect: { type: "preprocess", transform: preprocess2 }, + typeName: ZodFirstPartyTypeKind.ZodEffects, + ...processCreateParams(params) + }); +}; +var ZodOptional = class extends ZodType { + _parse(input) { + const parsedType2 = this._getType(input); + if (parsedType2 === ZodParsedType.undefined) { + return OK(void 0); + } + return this._def.innerType._parse(input); + } + unwrap() { + return this._def.innerType; + } +}; +ZodOptional.create = (type, params) => { + return new ZodOptional({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodOptional, + ...processCreateParams(params) + }); +}; +var ZodNullable = class extends ZodType { + _parse(input) { + const parsedType2 = this._getType(input); + if (parsedType2 === ZodParsedType.null) { + return OK(null); + } + return this._def.innerType._parse(input); + } + unwrap() { + return this._def.innerType; + } +}; +ZodNullable.create = (type, params) => { + return new ZodNullable({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodNullable, + ...processCreateParams(params) + }); +}; +var ZodDefault = class extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + let data2 = ctx.data; + if (ctx.parsedType === ZodParsedType.undefined) { + data2 = this._def.defaultValue(); + } + return this._def.innerType._parse({ + data: data2, + path: ctx.path, + parent: ctx + }); + } + removeDefault() { + return this._def.innerType; + } +}; +ZodDefault.create = (type, params) => { + return new ZodDefault({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodDefault, + defaultValue: typeof params.default === "function" ? params.default : () => params.default, + ...processCreateParams(params) + }); +}; +var ZodCatch = class extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + const newCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [] + } + }; + const result = this._def.innerType._parse({ + data: newCtx.data, + path: newCtx.path, + parent: { + ...newCtx + } + }); + if (isAsync(result)) { + return result.then((result2) => { + return { + status: "valid", + value: result2.status === "valid" ? result2.value : this._def.catchValue({ + get error() { + return new ZodError(newCtx.common.issues); + }, + input: newCtx.data + }) + }; + }); + } else { + return { + status: "valid", + value: result.status === "valid" ? result.value : this._def.catchValue({ + get error() { + return new ZodError(newCtx.common.issues); + }, + input: newCtx.data + }) + }; + } + } + removeCatch() { + return this._def.innerType; + } +}; +ZodCatch.create = (type, params) => { + return new ZodCatch({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodCatch, + catchValue: typeof params.catch === "function" ? params.catch : () => params.catch, + ...processCreateParams(params) + }); +}; +var ZodNaN = class extends ZodType { + _parse(input) { + const parsedType2 = this._getType(input); + if (parsedType2 !== ZodParsedType.nan) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.nan, + received: ctx.parsedType + }); + return INVALID; + } + return { status: "valid", value: input.data }; + } +}; +ZodNaN.create = (params) => { + return new ZodNaN({ + typeName: ZodFirstPartyTypeKind.ZodNaN, + ...processCreateParams(params) + }); +}; +var BRAND = /* @__PURE__ */ Symbol("zod_brand"); +var ZodBranded = class extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + const data2 = ctx.data; + return this._def.type._parse({ + data: data2, + path: ctx.path, + parent: ctx + }); + } + unwrap() { + return this._def.type; + } +}; +var ZodPipeline = class _ZodPipeline extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.common.async) { + const handleAsync = async () => { + const inResult = await this._def.in._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + if (inResult.status === "aborted") + return INVALID; + if (inResult.status === "dirty") { + status.dirty(); + return DIRTY(inResult.value); + } else { + return this._def.out._parseAsync({ + data: inResult.value, + path: ctx.path, + parent: ctx + }); + } + }; + return handleAsync(); + } else { + const inResult = this._def.in._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + if (inResult.status === "aborted") + return INVALID; + if (inResult.status === "dirty") { + status.dirty(); + return { + status: "dirty", + value: inResult.value + }; + } else { + return this._def.out._parseSync({ + data: inResult.value, + path: ctx.path, + parent: ctx + }); + } + } + } + static create(a5, b6) { + return new _ZodPipeline({ + in: a5, + out: b6, + typeName: ZodFirstPartyTypeKind.ZodPipeline + }); + } +}; +var ZodReadonly = class extends ZodType { + _parse(input) { + const result = this._def.innerType._parse(input); + const freeze3 = (data2) => { + if (isValid(data2)) { + data2.value = Object.freeze(data2.value); + } + return data2; + }; + return isAsync(result) ? result.then((data2) => freeze3(data2)) : freeze3(result); + } + unwrap() { + return this._def.innerType; + } +}; +ZodReadonly.create = (type, params) => { + return new ZodReadonly({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodReadonly, + ...processCreateParams(params) + }); +}; +function cleanParams(params, data2) { + const p5 = typeof params === "function" ? params(data2) : typeof params === "string" ? { message: params } : params; + const p22 = typeof p5 === "string" ? { message: p5 } : p5; + return p22; +} +function custom(check3, _params = {}, fatal) { + if (check3) + return ZodAny.create().superRefine((data2, ctx) => { + const r5 = check3(data2); + if (r5 instanceof Promise) { + return r5.then((r6) => { + if (!r6) { + const params = cleanParams(_params, data2); + const _fatal = params.fatal ?? fatal ?? true; + ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); + } + }); + } + if (!r5) { + const params = cleanParams(_params, data2); + const _fatal = params.fatal ?? fatal ?? true; + ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); + } + return; + }); + return ZodAny.create(); +} +var late = { + object: ZodObject.lazycreate +}; +var ZodFirstPartyTypeKind; +(function(ZodFirstPartyTypeKind3) { + ZodFirstPartyTypeKind3["ZodString"] = "ZodString"; + ZodFirstPartyTypeKind3["ZodNumber"] = "ZodNumber"; + ZodFirstPartyTypeKind3["ZodNaN"] = "ZodNaN"; + ZodFirstPartyTypeKind3["ZodBigInt"] = "ZodBigInt"; + ZodFirstPartyTypeKind3["ZodBoolean"] = "ZodBoolean"; + ZodFirstPartyTypeKind3["ZodDate"] = "ZodDate"; + ZodFirstPartyTypeKind3["ZodSymbol"] = "ZodSymbol"; + ZodFirstPartyTypeKind3["ZodUndefined"] = "ZodUndefined"; + ZodFirstPartyTypeKind3["ZodNull"] = "ZodNull"; + ZodFirstPartyTypeKind3["ZodAny"] = "ZodAny"; + ZodFirstPartyTypeKind3["ZodUnknown"] = "ZodUnknown"; + ZodFirstPartyTypeKind3["ZodNever"] = "ZodNever"; + ZodFirstPartyTypeKind3["ZodVoid"] = "ZodVoid"; + ZodFirstPartyTypeKind3["ZodArray"] = "ZodArray"; + ZodFirstPartyTypeKind3["ZodObject"] = "ZodObject"; + ZodFirstPartyTypeKind3["ZodUnion"] = "ZodUnion"; + ZodFirstPartyTypeKind3["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion"; + ZodFirstPartyTypeKind3["ZodIntersection"] = "ZodIntersection"; + ZodFirstPartyTypeKind3["ZodTuple"] = "ZodTuple"; + ZodFirstPartyTypeKind3["ZodRecord"] = "ZodRecord"; + ZodFirstPartyTypeKind3["ZodMap"] = "ZodMap"; + ZodFirstPartyTypeKind3["ZodSet"] = "ZodSet"; + ZodFirstPartyTypeKind3["ZodFunction"] = "ZodFunction"; + ZodFirstPartyTypeKind3["ZodLazy"] = "ZodLazy"; + ZodFirstPartyTypeKind3["ZodLiteral"] = "ZodLiteral"; + ZodFirstPartyTypeKind3["ZodEnum"] = "ZodEnum"; + ZodFirstPartyTypeKind3["ZodEffects"] = "ZodEffects"; + ZodFirstPartyTypeKind3["ZodNativeEnum"] = "ZodNativeEnum"; + ZodFirstPartyTypeKind3["ZodOptional"] = "ZodOptional"; + ZodFirstPartyTypeKind3["ZodNullable"] = "ZodNullable"; + ZodFirstPartyTypeKind3["ZodDefault"] = "ZodDefault"; + ZodFirstPartyTypeKind3["ZodCatch"] = "ZodCatch"; + ZodFirstPartyTypeKind3["ZodPromise"] = "ZodPromise"; + ZodFirstPartyTypeKind3["ZodBranded"] = "ZodBranded"; + ZodFirstPartyTypeKind3["ZodPipeline"] = "ZodPipeline"; + ZodFirstPartyTypeKind3["ZodReadonly"] = "ZodReadonly"; +})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {})); +var instanceOfType = (cls, params = { + message: `Input not instance of ${cls.name}` +}) => custom((data2) => data2 instanceof cls, params); +var stringType = ZodString.create; +var numberType = ZodNumber.create; +var nanType = ZodNaN.create; +var bigIntType = ZodBigInt.create; +var booleanType = ZodBoolean.create; +var dateType = ZodDate.create; +var symbolType = ZodSymbol.create; +var undefinedType = ZodUndefined.create; +var nullType = ZodNull.create; +var anyType = ZodAny.create; +var unknownType = ZodUnknown.create; +var neverType = ZodNever.create; +var voidType = ZodVoid.create; +var arrayType = ZodArray.create; +var objectType = ZodObject.create; +var strictObjectType = ZodObject.strictCreate; +var unionType = ZodUnion.create; +var discriminatedUnionType = ZodDiscriminatedUnion.create; +var intersectionType = ZodIntersection.create; +var tupleType = ZodTuple.create; +var recordType = ZodRecord.create; +var mapType = ZodMap.create; +var setType = ZodSet.create; +var functionType = ZodFunction.create; +var lazyType = ZodLazy.create; +var literalType = ZodLiteral.create; +var enumType = ZodEnum.create; +var nativeEnumType = ZodNativeEnum.create; +var promiseType = ZodPromise.create; +var effectsType = ZodEffects.create; +var optionalType = ZodOptional.create; +var nullableType = ZodNullable.create; +var preprocessType = ZodEffects.createWithPreprocess; +var pipelineType = ZodPipeline.create; +var ostring = () => stringType().optional(); +var onumber = () => numberType().optional(); +var oboolean = () => booleanType().optional(); +var coerce = { + string: ((arg) => ZodString.create({ ...arg, coerce: true })), + number: ((arg) => ZodNumber.create({ ...arg, coerce: true })), + boolean: ((arg) => ZodBoolean.create({ + ...arg, + coerce: true + })), + bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })), + date: ((arg) => ZodDate.create({ ...arg, coerce: true })) +}; +var NEVER = INVALID; + +// packages/shared/src/constants.ts +var COMPANY_STATUSES = ["active", "paused", "archived"]; +var DEPLOYMENT_MODES = ["local_trusted", "authenticated"]; +var DEPLOYMENT_EXPOSURES = ["private", "public"]; +var BIND_MODES = ["loopback", "lan", "tailnet", "custom"]; +var AUTH_BASE_URL_MODES = ["auto", "explicit"]; +var AGENT_STATUSES = [ + "active", + "paused", + "idle", + "running", + "error", + "pending_approval", + "terminated" +]; +var AGENT_ADAPTER_TYPES = [ + "process", + "http", + "claude_local", + "codex_local", + "gemini_local", + "opencode_local", + "pi_local", + "cursor", + "openclaw_gateway" +]; +var AGENT_ROLES = [ + "ceo", + "cto", + "cmo", + "cfo", + "engineer", + "designer", + "pm", + "qa", + "devops", + "researcher", + "general" +]; +var AGENT_ICON_NAMES = [ + "bot", + "cpu", + "brain", + "zap", + "rocket", + "code", + "terminal", + "shield", + "eye", + "search", + "wrench", + "hammer", + "lightbulb", + "sparkles", + "star", + "heart", + "flame", + "bug", + "cog", + "database", + "globe", + "lock", + "mail", + "message-square", + "file-code", + "git-branch", + "package", + "puzzle", + "target", + "wand", + "atom", + "circuit-board", + "radar", + "swords", + "telescope", + "microscope", + "crown", + "gem", + "hexagon", + "pentagon", + "fingerprint" +]; +var ISSUE_STATUSES = [ + "backlog", + "todo", + "in_progress", + "in_review", + "done", + "blocked", + "cancelled" +]; +var INBOX_MINE_ISSUE_STATUSES = [ + "backlog", + "todo", + "in_progress", + "in_review", + "blocked", + "done" +]; +var INBOX_MINE_ISSUE_STATUS_FILTER = INBOX_MINE_ISSUE_STATUSES.join(","); +var ISSUE_PRIORITIES = ["critical", "high", "medium", "low"]; +var ISSUE_EXECUTION_POLICY_MODES = ["normal", "auto"]; +var ISSUE_EXECUTION_STAGE_TYPES = ["review", "approval"]; +var ISSUE_EXECUTION_STATE_STATUSES = ["idle", "pending", "changes_requested", "completed"]; +var ISSUE_EXECUTION_DECISION_OUTCOMES = ["approved", "changes_requested"]; +var GOAL_LEVELS = ["company", "team", "agent", "task"]; +var GOAL_STATUSES = ["planned", "active", "achieved", "cancelled"]; +var PROJECT_STATUSES = [ + "backlog", + "planned", + "in_progress", + "completed", + "cancelled" +]; +var ROUTINE_STATUSES = ["active", "paused", "archived"]; +var ROUTINE_CONCURRENCY_POLICIES = ["coalesce_if_active", "always_enqueue", "skip_if_active"]; +var ROUTINE_CATCH_UP_POLICIES = ["skip_missed", "enqueue_missed_with_cap"]; +var ROUTINE_TRIGGER_KINDS = ["schedule", "webhook", "api"]; +var ROUTINE_TRIGGER_SIGNING_MODES = ["bearer", "hmac_sha256", "github_hmac", "none"]; +var ROUTINE_VARIABLE_TYPES = ["text", "textarea", "number", "boolean", "select"]; +var PROJECT_COLORS = [ + "#6366f1", + // indigo + "#8b5cf6", + // violet + "#ec4899", + // pink + "#ef4444", + // red + "#f97316", + // orange + "#eab308", + // yellow + "#22c55e", + // green + "#14b8a6", + // teal + "#06b6d4", + // cyan + "#3b82f6" + // blue +]; +var APPROVAL_TYPES = [ + "hire_agent", + "approve_ceo_strategy", + "budget_override_required", + "request_board_approval" +]; +var SECRET_PROVIDERS = [ + "local_encrypted", + "aws_secrets_manager", + "gcp_secret_manager", + "vault" +]; +var STORAGE_PROVIDERS = ["local_disk", "s3"]; +var BILLING_TYPES = [ + "metered_api", + "subscription_included", + "subscription_overage", + "credits", + "fixed", + "unknown" +]; +var FINANCE_EVENT_KINDS = [ + "inference_charge", + "platform_fee", + "credit_purchase", + "credit_refund", + "credit_expiry", + "byok_fee", + "gateway_overhead", + "log_storage_charge", + "logpush_charge", + "provisioned_capacity_charge", + "training_charge", + "custom_model_import_charge", + "custom_model_storage_charge", + "manual_adjustment" +]; +var FINANCE_DIRECTIONS = ["debit", "credit"]; +var FINANCE_UNITS = [ + "input_token", + "output_token", + "cached_input_token", + "request", + "credit_usd", + "credit_unit", + "model_unit_minute", + "model_unit_hour", + "gb_month", + "train_token", + "unknown" +]; +var BUDGET_SCOPE_TYPES = ["company", "agent", "project"]; +var BUDGET_METRICS = ["billed_cents"]; +var BUDGET_WINDOW_KINDS = ["calendar_month_utc", "lifetime"]; +var BUDGET_INCIDENT_RESOLUTION_ACTIONS = [ + "keep_paused", + "raise_budget_and_resume" +]; +var INVITE_JOIN_TYPES = ["human", "agent", "both"]; +var JOIN_REQUEST_TYPES = ["human", "agent"]; +var JOIN_REQUEST_STATUSES = ["pending_approval", "approved", "rejected"]; +var PERMISSION_KEYS = [ + "agents:create", + "users:invite", + "users:manage_permissions", + "tasks:assign", + "tasks:assign_scope", + "joins:approve" +]; +var PLUGIN_API_VERSION = 1; +var PLUGIN_STATUSES = [ + "installed", + "ready", + "disabled", + "error", + "upgrade_pending", + "uninstalled" +]; +var PLUGIN_CATEGORIES = [ + "connector", + "workspace", + "automation", + "ui" +]; +var PLUGIN_CAPABILITIES = [ + // Data Read + "companies.read", + "projects.read", + "project.workspaces.read", + "issues.read", + "issue.comments.read", + "issue.documents.read", + "agents.read", + "goals.read", + "goals.create", + "goals.update", + "activity.read", + "costs.read", + // Data Write + "issues.create", + "issues.update", + "issue.comments.create", + "issue.documents.write", + "agents.pause", + "agents.resume", + "agents.invoke", + "agent.sessions.create", + "agent.sessions.list", + "agent.sessions.send", + "agent.sessions.close", + "activity.log.write", + "metrics.write", + "telemetry.track", + // Plugin State + "plugin.state.read", + "plugin.state.write", + // Runtime / Integration + "events.subscribe", + "events.emit", + "jobs.schedule", + "webhooks.receive", + "http.outbound", + "secrets.read-ref", + // Agent Tools + "agent.tools.register", + // UI + "instance.settings.register", + "ui.sidebar.register", + "ui.page.register", + "ui.detailTab.register", + "ui.dashboardWidget.register", + "ui.commentAnnotation.register", + "ui.action.register" +]; +var PLUGIN_UI_SLOT_TYPES = [ + "page", + "detailTab", + "taskDetailView", + "dashboardWidget", + "sidebar", + "sidebarPanel", + "projectSidebarItem", + "globalToolbarButton", + "toolbarButton", + "contextMenuItem", + "commentAnnotation", + "commentContextMenuItem", + "settingsPage" +]; +var PLUGIN_RESERVED_COMPANY_ROUTE_SEGMENTS = [ + "dashboard", + "onboarding", + "companies", + "company", + "settings", + "plugins", + "org", + "agents", + "projects", + "issues", + "goals", + "approvals", + "costs", + "activity", + "inbox", + "design-guide", + "tests" +]; +var PLUGIN_LAUNCHER_PLACEMENT_ZONES = [ + "page", + "detailTab", + "taskDetailView", + "dashboardWidget", + "sidebar", + "sidebarPanel", + "projectSidebarItem", + "globalToolbarButton", + "toolbarButton", + "contextMenuItem", + "commentAnnotation", + "commentContextMenuItem", + "settingsPage" +]; +var PLUGIN_LAUNCHER_ACTIONS = [ + "navigate", + "openModal", + "openDrawer", + "openPopover", + "performAction", + "deepLink" +]; +var PLUGIN_LAUNCHER_BOUNDS = [ + "inline", + "compact", + "default", + "wide", + "full" +]; +var PLUGIN_LAUNCHER_RENDER_ENVIRONMENTS = [ + "hostInline", + "hostOverlay", + "hostRoute", + "external", + "iframe" +]; +var PLUGIN_UI_SLOT_ENTITY_TYPES = [ + "project", + "issue", + "agent", + "goal", + "run", + "comment" +]; +var PLUGIN_STATE_SCOPE_KINDS = [ + "instance", + "company", + "project", + "project_workspace", + "agent", + "issue", + "goal", + "run" +]; +var PLUGIN_EVENT_TYPES = [ + "company.created", + "company.updated", + "project.created", + "project.updated", + "project.workspace_created", + "project.workspace_updated", + "project.workspace_deleted", + "issue.created", + "issue.updated", + "issue.comment.created", + "agent.created", + "agent.updated", + "agent.status_changed", + "agent.run.started", + "agent.run.finished", + "agent.run.failed", + "agent.run.cancelled", + "goal.created", + "goal.updated", + "approval.created", + "approval.decided", + "cost_event.created", + "activity.logged" +]; + +// packages/shared/src/adapter-type.ts +var agentAdapterTypeSchema = external_exports.string().trim().min(1).default("process").describe(`Known built-in adapters: ${AGENT_ADAPTER_TYPES.join(", ")}. External adapters may register additional non-empty string types at runtime.`); +var optionalAgentAdapterTypeSchema = external_exports.string().trim().min(1).optional(); + +// packages/shared/src/vercel-postgres.ts +function resolvePostgresUrlFromEnv() { + const direct = process.env.DATABASE_URL?.trim(); + if (direct) return direct; + const pooled = process.env.POSTGRES_URL?.trim(); + if (pooled) return pooled; + const nonPooling = process.env.POSTGRES_URL_NON_POOLING?.trim(); + if (nonPooling) return nonPooling; + const host = process.env.PGHOST?.trim(); + const database = process.env.PGDATABASE?.trim(); + if (!host || !database) return void 0; + const user = encodeURIComponent(process.env.PGUSER?.trim() || "postgres"); + const password = process.env.PGPASSWORD ? encodeURIComponent(process.env.PGPASSWORD) : ""; + const port = process.env.PGPORT?.trim() || "5432"; + const auth = `${user}${password ? `:${password}` : ""}`; + let url2 = `postgres://${auth}@${host}:${port}/${database}`; + const sslMode = process.env.PGSSLMODE?.trim(); + if (sslMode && sslMode !== "disable") { + url2 += "?sslmode=require"; + } + return url2; +} + +// packages/shared/src/network-bind.ts +var LOOPBACK_BIND_HOST = "127.0.0.1"; +var ALL_INTERFACES_BIND_HOST = "0.0.0.0"; +function normalizeHost(host) { + const trimmed = host?.trim(); + return trimmed ? trimmed : void 0; +} +function isLoopbackHost(host) { + const normalized = normalizeHost(host)?.toLowerCase(); + return normalized === "127.0.0.1" || normalized === "localhost" || normalized === "::1"; +} +function isAllInterfacesHost(host) { + const normalized = normalizeHost(host)?.toLowerCase(); + return normalized === "0.0.0.0" || normalized === "::"; +} +function inferBindModeFromHost(host, opts) { + const normalized = normalizeHost(host); + const tailnetBindHost = normalizeHost(opts?.tailnetBindHost); + if (!normalized || isLoopbackHost(normalized)) return "loopback"; + if (isAllInterfacesHost(normalized)) return "lan"; + if (tailnetBindHost && normalized === tailnetBindHost) return "tailnet"; + return "custom"; +} +function validateConfiguredBindMode(input) { + const bind2 = input.bind ?? inferBindModeFromHost(input.host); + const customBindHost = normalizeHost(input.customBindHost); + const errors = []; + if (input.deploymentMode === "local_trusted" && bind2 !== "loopback") { + errors.push("local_trusted requires server.bind=loopback"); + } + if (bind2 === "custom" && !customBindHost) { + const legacyHost = normalizeHost(input.host); + if (!legacyHost || isLoopbackHost(legacyHost) || isAllInterfacesHost(legacyHost)) { + errors.push("server.customBindHost is required when server.bind=custom"); + } + } + if (input.deploymentMode === "authenticated" && input.deploymentExposure === "public" && bind2 === "tailnet") { + errors.push("server.bind=tailnet is only supported for authenticated/private deployments"); + } + return errors; +} +function resolveRuntimeBind(input) { + const bind2 = input.bind ?? inferBindModeFromHost(input.host, { tailnetBindHost: input.tailnetBindHost }); + const legacyHost = normalizeHost(input.host); + const customBindHost = normalizeHost(input.customBindHost) ?? (bind2 === "custom" && legacyHost && !isLoopbackHost(legacyHost) && !isAllInterfacesHost(legacyHost) ? legacyHost : void 0); + switch (bind2) { + case "loopback": + return { bind: bind2, host: LOOPBACK_BIND_HOST, customBindHost, errors: [] }; + case "lan": + return { bind: bind2, host: ALL_INTERFACES_BIND_HOST, customBindHost, errors: [] }; + case "custom": + return customBindHost ? { bind: bind2, host: customBindHost, customBindHost, errors: [] } : { bind: bind2, host: legacyHost ?? LOOPBACK_BIND_HOST, errors: ["server.customBindHost is required when server.bind=custom"] }; + case "tailnet": { + const tailnetBindHost = normalizeHost(input.tailnetBindHost); + return tailnetBindHost ? { bind: bind2, host: tailnetBindHost, customBindHost, errors: [] } : { + bind: bind2, + host: legacyHost ?? LOOPBACK_BIND_HOST, + customBindHost, + errors: [ + "server.bind=tailnet requires a detected Tailscale address or TASKCORE_TAILNET_BIND_HOST" + ] + }; + } + } +} + +// packages/shared/src/validators/sidebar-preferences.ts +var sidebarOrderedIdSchema = external_exports.string().uuid(); +var sidebarOrderPreferenceSchema = external_exports.object({ + orderedIds: external_exports.array(sidebarOrderedIdSchema), + updatedAt: external_exports.coerce.date().nullable() +}); +var upsertSidebarOrderPreferenceSchema = external_exports.object({ + orderedIds: external_exports.array(sidebarOrderedIdSchema) +}); + +// packages/shared/src/validators/execution-workspace.ts +var executionWorkspaceStatusSchema = external_exports.enum([ + "active", + "idle", + "in_review", + "archived", + "cleanup_failed" +]); +var executionWorkspaceConfigSchema = external_exports.object({ + provisionCommand: external_exports.string().optional().nullable(), + teardownCommand: external_exports.string().optional().nullable(), + cleanupCommand: external_exports.string().optional().nullable(), + workspaceRuntime: external_exports.record(external_exports.unknown()).optional().nullable(), + desiredState: external_exports.enum(["running", "stopped"]).optional().nullable(), + serviceStates: external_exports.record(external_exports.enum(["running", "stopped"])).optional().nullable() +}).strict(); +var workspaceRuntimeControlTargetSchema = external_exports.object({ + workspaceCommandId: external_exports.string().min(1).optional().nullable(), + runtimeServiceId: external_exports.string().uuid().optional().nullable(), + serviceIndex: external_exports.number().int().nonnegative().optional().nullable() +}).strict(); +var executionWorkspaceCloseReadinessStateSchema = external_exports.enum([ + "ready", + "ready_with_warnings", + "blocked" +]); +var executionWorkspaceCloseActionKindSchema = external_exports.enum([ + "archive_record", + "stop_runtime_services", + "cleanup_command", + "teardown_command", + "git_worktree_remove", + "git_branch_delete", + "remove_local_directory" +]); +var executionWorkspaceCloseActionSchema = external_exports.object({ + kind: executionWorkspaceCloseActionKindSchema, + label: external_exports.string(), + description: external_exports.string(), + command: external_exports.string().nullable() +}).strict(); +var executionWorkspaceCloseLinkedIssueSchema = external_exports.object({ + id: external_exports.string().uuid(), + identifier: external_exports.string().nullable(), + title: external_exports.string(), + status: external_exports.string(), + isTerminal: external_exports.boolean() +}).strict(); +var executionWorkspaceCloseGitReadinessSchema = external_exports.object({ + repoRoot: external_exports.string().nullable(), + workspacePath: external_exports.string().nullable(), + branchName: external_exports.string().nullable(), + baseRef: external_exports.string().nullable(), + hasDirtyTrackedFiles: external_exports.boolean(), + hasUntrackedFiles: external_exports.boolean(), + dirtyEntryCount: external_exports.number().int().nonnegative(), + untrackedEntryCount: external_exports.number().int().nonnegative(), + aheadCount: external_exports.number().int().nonnegative().nullable(), + behindCount: external_exports.number().int().nonnegative().nullable(), + isMergedIntoBase: external_exports.boolean().nullable(), + createdByRuntime: external_exports.boolean() +}).strict(); +var workspaceRuntimeServiceSchema = external_exports.object({ + id: external_exports.string(), + companyId: external_exports.string().uuid(), + projectId: external_exports.string().uuid().nullable(), + projectWorkspaceId: external_exports.string().uuid().nullable(), + executionWorkspaceId: external_exports.string().uuid().nullable(), + issueId: external_exports.string().uuid().nullable(), + scopeType: external_exports.enum(["project_workspace", "execution_workspace", "run", "agent"]), + scopeId: external_exports.string().nullable(), + serviceName: external_exports.string(), + status: external_exports.enum(["starting", "running", "stopped", "failed"]), + lifecycle: external_exports.enum(["shared", "ephemeral"]), + reuseKey: external_exports.string().nullable(), + command: external_exports.string().nullable(), + cwd: external_exports.string().nullable(), + port: external_exports.number().int().nullable(), + url: external_exports.string().nullable(), + provider: external_exports.enum(["local_process", "adapter_managed"]), + providerRef: external_exports.string().nullable(), + ownerAgentId: external_exports.string().uuid().nullable(), + startedByRunId: external_exports.string().uuid().nullable(), + lastUsedAt: external_exports.coerce.date(), + startedAt: external_exports.coerce.date(), + stoppedAt: external_exports.coerce.date().nullable(), + stopPolicy: external_exports.record(external_exports.unknown()).nullable(), + healthStatus: external_exports.enum(["unknown", "healthy", "unhealthy"]), + configIndex: external_exports.number().int().nonnegative().nullable().optional(), + createdAt: external_exports.coerce.date(), + updatedAt: external_exports.coerce.date() +}).strict(); +var executionWorkspaceCloseReadinessSchema = external_exports.object({ + workspaceId: external_exports.string().uuid(), + state: executionWorkspaceCloseReadinessStateSchema, + blockingReasons: external_exports.array(external_exports.string()), + warnings: external_exports.array(external_exports.string()), + linkedIssues: external_exports.array(executionWorkspaceCloseLinkedIssueSchema), + plannedActions: external_exports.array(executionWorkspaceCloseActionSchema), + isDestructiveCloseAllowed: external_exports.boolean(), + isSharedWorkspace: external_exports.boolean(), + isProjectPrimaryWorkspace: external_exports.boolean(), + git: executionWorkspaceCloseGitReadinessSchema.nullable(), + runtimeServices: external_exports.array(workspaceRuntimeServiceSchema) +}).strict(); +var updateExecutionWorkspaceSchema = external_exports.object({ + name: external_exports.string().min(1).optional(), + cwd: external_exports.string().optional().nullable(), + repoUrl: external_exports.string().optional().nullable(), + baseRef: external_exports.string().optional().nullable(), + branchName: external_exports.string().optional().nullable(), + providerRef: external_exports.string().optional().nullable(), + status: executionWorkspaceStatusSchema.optional(), + cleanupEligibleAt: external_exports.string().datetime().optional().nullable(), + cleanupReason: external_exports.string().optional().nullable(), + config: executionWorkspaceConfigSchema.optional().nullable(), + metadata: external_exports.record(external_exports.unknown()).optional().nullable() +}).strict(); + +// packages/shared/src/workspace-commands.ts +function isRecord(value) { + return typeof value === "object" && value !== null && !Array.isArray(value); +} +function readNonEmptyString(value) { + if (typeof value !== "string") return null; + const trimmed = value.trim(); + return trimmed.length > 0 ? trimmed : null; +} +function slugify(value) { + const normalized = (value ?? "").trim().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/-+/g, "-").replace(/^-+|-+$/g, ""); + return normalized.length > 0 ? normalized : null; +} +function deriveWorkspaceCommandId(input) { + const explicitId = slugify(input.explicitId); + if (explicitId) return explicitId; + const nameSlug = slugify(input.name); + return nameSlug ? `${input.kind}:${nameSlug}` : `${input.kind}:${input.index + 1}`; +} +function buildWorkspaceCommandDefinition(input) { + return { + id: deriveWorkspaceCommandId({ + kind: input.kind, + explicitId: readNonEmptyString(input.entry.id), + name: readNonEmptyString(input.entry.name) ?? readNonEmptyString(input.entry.label) ?? readNonEmptyString(input.entry.title) ?? input.fallbackName, + index: input.sourceIndex + }), + name: readNonEmptyString(input.entry.name) ?? readNonEmptyString(input.entry.label) ?? readNonEmptyString(input.entry.title) ?? input.fallbackName, + kind: input.kind, + command: readNonEmptyString(input.entry.command), + cwd: readNonEmptyString(input.entry.cwd), + lifecycle: input.kind === "service" ? input.entry.lifecycle === "ephemeral" ? "ephemeral" : "shared" : null, + serviceIndex: input.serviceIndex, + disabledReason: readNonEmptyString(input.entry.disabledReason), + rawConfig: { ...input.entry }, + source: { + type: "taskcore", + key: input.sourceKey, + index: input.sourceIndex + } + }; +} +function uniqueWorkspaceCommandId(seen, commandId, sourceKey, sourceIndex) { + if (!seen.has(commandId)) { + seen.add(commandId); + return commandId; + } + const fallbackId = `${commandId}-${sourceKey}-${sourceIndex + 1}`; + seen.add(fallbackId); + return fallbackId; +} +function readCommandEntries(workspaceRuntime, key) { + const raw = workspaceRuntime?.[key]; + return Array.isArray(raw) ? raw.filter((entry) => isRecord(entry)) : []; +} +function listWorkspaceCommandDefinitions(workspaceRuntime) { + if (!workspaceRuntime) return []; + const commandEntries = readCommandEntries(workspaceRuntime, "commands"); + const seenIds = /* @__PURE__ */ new Set(); + let nextServiceIndex = 0; + const finalize2 = (command) => ({ + ...command, + id: uniqueWorkspaceCommandId(seenIds, command.id, command.source.key, command.source.index) + }); + if (commandEntries.length > 0) { + return commandEntries.map((entry, index2) => finalize2(buildWorkspaceCommandDefinition({ + entry, + kind: entry.kind === "job" ? "job" : "service", + sourceKey: "commands", + sourceIndex: index2, + serviceIndex: entry.kind === "job" ? null : nextServiceIndex++, + fallbackName: entry.kind === "job" ? `Job ${index2 + 1}` : `Service ${index2 + 1}` + }))); + } + const serviceDefinitions = readCommandEntries(workspaceRuntime, "services").map((entry, index2) => finalize2(buildWorkspaceCommandDefinition({ + entry, + kind: "service", + sourceKey: "services", + sourceIndex: index2, + serviceIndex: nextServiceIndex++, + fallbackName: `Service ${index2 + 1}` + }))); + const jobDefinitions = readCommandEntries(workspaceRuntime, "jobs").map((entry, index2) => finalize2(buildWorkspaceCommandDefinition({ + entry, + kind: "job", + sourceKey: "jobs", + sourceIndex: index2, + serviceIndex: null, + fallbackName: `Job ${index2 + 1}` + }))); + return [...serviceDefinitions, ...jobDefinitions]; +} +function listWorkspaceServiceCommandDefinitions(workspaceRuntime) { + return listWorkspaceCommandDefinitions(workspaceRuntime).filter((command) => command.kind === "service"); +} +function findWorkspaceCommandDefinition(workspaceRuntime, workspaceCommandId) { + const normalizedId = readNonEmptyString(workspaceCommandId); + if (!normalizedId) return null; + return listWorkspaceCommandDefinitions(workspaceRuntime).find((command) => command.id === normalizedId) ?? null; +} +function scoreWorkspaceRuntimeServiceMatch(command, runtimeService) { + if (command.serviceIndex !== null && runtimeService.configIndex !== null && runtimeService.configIndex !== void 0) { + return runtimeService.configIndex === command.serviceIndex ? 100 : -1; + } + let score = 0; + if (runtimeService.serviceName === command.name) score += 4; + if ((runtimeService.command ?? null) === (command.command ?? null)) score += 4; + if (command.cwd && runtimeService.cwd && (runtimeService.cwd === command.cwd || runtimeService.cwd.endsWith(`/${command.cwd}`))) { + score += 2; + } + return score; +} +function matchWorkspaceRuntimeServiceToCommand(command, runtimeServices) { + let bestMatch = null; + let bestScore = -1; + for (const runtimeService of runtimeServices ?? []) { + const score = scoreWorkspaceRuntimeServiceMatch(command, runtimeService); + if (score > bestScore) { + bestMatch = runtimeService; + bestScore = score; + } + } + return bestScore > 0 ? bestMatch : null; +} + +// packages/shared/src/types/feedback.ts +var FEEDBACK_TARGET_TYPES = ["issue_comment", "issue_document_revision"]; +var FEEDBACK_VOTE_VALUES = ["up", "down"]; +var FEEDBACK_DATA_SHARING_PREFERENCES = ["allowed", "not_allowed", "prompt"]; +var DEFAULT_FEEDBACK_DATA_SHARING_PREFERENCE = "prompt"; +var FEEDBACK_TRACE_STATUSES = ["local_only", "pending", "sent", "failed"]; +var DEFAULT_FEEDBACK_DATA_SHARING_TERMS_VERSION = "feedback-data-sharing-v1"; + +// packages/shared/src/types/instance.ts +var DAILY_RETENTION_PRESETS = [3, 7, 14]; +var WEEKLY_RETENTION_PRESETS = [1, 2, 4]; +var MONTHLY_RETENTION_PRESETS = [1, 3, 6]; +var DEFAULT_BACKUP_RETENTION = { + dailyDays: 7, + weeklyWeeks: 4, + monthlyMonths: 1 +}; + +// packages/shared/src/execution-workspace-guards.ts +var CLOSED_EXECUTION_WORKSPACE_STATUSES = /* @__PURE__ */ new Set(["archived", "cleanup_failed"]); +function isClosedIsolatedExecutionWorkspace(workspace) { + if (!workspace) return false; + if (workspace.mode !== "isolated_workspace") return false; + return workspace.closedAt != null || CLOSED_EXECUTION_WORKSPACE_STATUSES.has(workspace.status); +} +function getClosedIsolatedExecutionWorkspaceMessage(workspace) { + return `This issue is linked to the closed workspace "${workspace.name}". Move it to an open workspace before adding comments or resuming work.`; +} + +// packages/shared/src/validators/feedback.ts +var feedbackTargetTypeSchema = external_exports.enum(FEEDBACK_TARGET_TYPES); +var feedbackTraceStatusSchema = external_exports.enum(FEEDBACK_TRACE_STATUSES); +var feedbackVoteValueSchema = external_exports.enum(FEEDBACK_VOTE_VALUES); +var feedbackDataSharingPreferenceSchema = external_exports.enum(FEEDBACK_DATA_SHARING_PREFERENCES); +var upsertIssueFeedbackVoteSchema = external_exports.object({ + targetType: feedbackTargetTypeSchema, + targetId: external_exports.string().uuid(), + vote: feedbackVoteValueSchema, + reason: external_exports.string().trim().max(1e3).optional(), + allowSharing: external_exports.boolean().optional() +}); + +// packages/shared/src/validators/instance.ts +function presetSchema(presets, label) { + return external_exports.number().refine( + (v5) => presets.includes(v5), + { message: `${label} must be one of: ${presets.join(", ")}` } + ); +} +var backupRetentionPolicySchema = external_exports.object({ + dailyDays: presetSchema(DAILY_RETENTION_PRESETS, "dailyDays").default(DEFAULT_BACKUP_RETENTION.dailyDays), + weeklyWeeks: presetSchema(WEEKLY_RETENTION_PRESETS, "weeklyWeeks").default(DEFAULT_BACKUP_RETENTION.weeklyWeeks), + monthlyMonths: presetSchema(MONTHLY_RETENTION_PRESETS, "monthlyMonths").default(DEFAULT_BACKUP_RETENTION.monthlyMonths) +}); +var instanceGeneralSettingsSchema = external_exports.object({ + censorUsernameInLogs: external_exports.boolean().default(false), + keyboardShortcuts: external_exports.boolean().default(false), + feedbackDataSharingPreference: feedbackDataSharingPreferenceSchema.default( + DEFAULT_FEEDBACK_DATA_SHARING_PREFERENCE + ), + backupRetention: backupRetentionPolicySchema.default(DEFAULT_BACKUP_RETENTION) +}).strict(); +var patchInstanceGeneralSettingsSchema = instanceGeneralSettingsSchema.partial(); +var instanceExperimentalSettingsSchema = external_exports.object({ + enableIsolatedWorkspaces: external_exports.boolean().default(false), + autoRestartDevServerWhenIdle: external_exports.boolean().default(false) +}).strict(); +var patchInstanceExperimentalSettingsSchema = instanceExperimentalSettingsSchema.partial(); + +// packages/shared/src/validators/budget.ts +var upsertBudgetPolicySchema = external_exports.object({ + scopeType: external_exports.enum(BUDGET_SCOPE_TYPES), + scopeId: external_exports.string().uuid(), + metric: external_exports.enum(BUDGET_METRICS).optional().default("billed_cents"), + windowKind: external_exports.enum(BUDGET_WINDOW_KINDS).optional().default("calendar_month_utc"), + amount: external_exports.number().int().nonnegative(), + warnPercent: external_exports.number().int().min(1).max(99).optional().default(80), + hardStopEnabled: external_exports.boolean().optional().default(true), + notifyEnabled: external_exports.boolean().optional().default(true), + isActive: external_exports.boolean().optional().default(true) +}); +var resolveBudgetIncidentSchema = external_exports.object({ + action: external_exports.enum(BUDGET_INCIDENT_RESOLUTION_ACTIONS), + amount: external_exports.number().int().nonnegative().optional(), + decisionNote: external_exports.string().optional().nullable() +}).superRefine((value, ctx) => { + if (value.action === "raise_budget_and_resume" && typeof value.amount !== "number") { + ctx.addIssue({ + code: external_exports.ZodIssueCode.custom, + message: "amount is required when raising a budget", + path: ["amount"] + }); + } +}); + +// packages/shared/src/validators/company.ts +var logoAssetIdSchema = external_exports.string().uuid().nullable().optional(); +var brandColorSchema = external_exports.string().regex(/^#[0-9a-fA-F]{6}$/).nullable().optional(); +var feedbackDataSharingTermsVersionSchema = external_exports.string().min(1).nullable().optional(); +var createCompanySchema = external_exports.object({ + name: external_exports.string().min(1), + description: external_exports.string().optional().nullable(), + budgetMonthlyCents: external_exports.number().int().nonnegative().optional().default(0) +}); +var updateCompanySchema = createCompanySchema.partial().extend({ + status: external_exports.enum(COMPANY_STATUSES).optional(), + spentMonthlyCents: external_exports.number().int().nonnegative().optional(), + requireBoardApprovalForNewAgents: external_exports.boolean().optional(), + feedbackDataSharingEnabled: external_exports.boolean().optional(), + feedbackDataSharingConsentAt: external_exports.coerce.date().nullable().optional(), + feedbackDataSharingConsentByUserId: external_exports.string().min(1).nullable().optional(), + feedbackDataSharingTermsVersion: feedbackDataSharingTermsVersionSchema, + brandColor: brandColorSchema, + logoAssetId: logoAssetIdSchema +}); +var updateCompanyBrandingSchema = external_exports.object({ + name: external_exports.string().min(1).optional(), + description: external_exports.string().nullable().optional(), + brandColor: brandColorSchema, + logoAssetId: logoAssetIdSchema +}).strict().refine( + (value) => value.name !== void 0 || value.description !== void 0 || value.brandColor !== void 0 || value.logoAssetId !== void 0, + "At least one branding field must be provided" +); + +// packages/shared/src/validators/company-skill.ts +var companySkillSourceTypeSchema = external_exports.enum(["local_path", "github", "url", "catalog", "skills_sh"]); +var companySkillTrustLevelSchema = external_exports.enum(["markdown_only", "assets", "scripts_executables"]); +var companySkillCompatibilitySchema = external_exports.enum(["compatible", "unknown", "invalid"]); +var companySkillSourceBadgeSchema = external_exports.enum(["taskcore", "github", "local", "url", "catalog", "skills_sh"]); +var companySkillFileInventoryEntrySchema = external_exports.object({ + path: external_exports.string().min(1), + kind: external_exports.enum(["skill", "markdown", "reference", "script", "asset", "other"]) +}); +var companySkillSchema = external_exports.object({ + id: external_exports.string().uuid(), + companyId: external_exports.string().uuid(), + key: external_exports.string().min(1), + slug: external_exports.string().min(1), + name: external_exports.string().min(1), + description: external_exports.string().nullable(), + markdown: external_exports.string(), + sourceType: companySkillSourceTypeSchema, + sourceLocator: external_exports.string().nullable(), + sourceRef: external_exports.string().nullable(), + trustLevel: companySkillTrustLevelSchema, + compatibility: companySkillCompatibilitySchema, + fileInventory: external_exports.array(companySkillFileInventoryEntrySchema).default([]), + metadata: external_exports.record(external_exports.unknown()).nullable(), + createdAt: external_exports.coerce.date(), + updatedAt: external_exports.coerce.date() +}); +var companySkillListItemSchema = companySkillSchema.extend({ + attachedAgentCount: external_exports.number().int().nonnegative(), + editable: external_exports.boolean(), + editableReason: external_exports.string().nullable(), + sourceLabel: external_exports.string().nullable(), + sourceBadge: companySkillSourceBadgeSchema +}); +var companySkillUsageAgentSchema = external_exports.object({ + id: external_exports.string().uuid(), + name: external_exports.string().min(1), + urlKey: external_exports.string().min(1), + adapterType: external_exports.string().min(1), + desired: external_exports.boolean(), + actualState: external_exports.string().nullable() +}); +var companySkillDetailSchema = companySkillSchema.extend({ + attachedAgentCount: external_exports.number().int().nonnegative(), + usedByAgents: external_exports.array(companySkillUsageAgentSchema).default([]), + editable: external_exports.boolean(), + editableReason: external_exports.string().nullable(), + sourceLabel: external_exports.string().nullable(), + sourceBadge: companySkillSourceBadgeSchema +}); +var companySkillUpdateStatusSchema = external_exports.object({ + supported: external_exports.boolean(), + reason: external_exports.string().nullable(), + trackingRef: external_exports.string().nullable(), + currentRef: external_exports.string().nullable(), + latestRef: external_exports.string().nullable(), + hasUpdate: external_exports.boolean() +}); +var companySkillImportSchema = external_exports.object({ + source: external_exports.string().min(1) +}); +var companySkillProjectScanRequestSchema = external_exports.object({ + projectIds: external_exports.array(external_exports.string().uuid()).optional(), + workspaceIds: external_exports.array(external_exports.string().uuid()).optional() +}); +var companySkillProjectScanSkippedSchema = external_exports.object({ + projectId: external_exports.string().uuid(), + projectName: external_exports.string().min(1), + workspaceId: external_exports.string().uuid().nullable(), + workspaceName: external_exports.string().nullable(), + path: external_exports.string().nullable(), + reason: external_exports.string().min(1) +}); +var companySkillProjectScanConflictSchema = external_exports.object({ + slug: external_exports.string().min(1), + key: external_exports.string().min(1), + projectId: external_exports.string().uuid(), + projectName: external_exports.string().min(1), + workspaceId: external_exports.string().uuid(), + workspaceName: external_exports.string().min(1), + path: external_exports.string().min(1), + existingSkillId: external_exports.string().uuid(), + existingSkillKey: external_exports.string().min(1), + existingSourceLocator: external_exports.string().nullable(), + reason: external_exports.string().min(1) +}); +var companySkillProjectScanResultSchema = external_exports.object({ + scannedProjects: external_exports.number().int().nonnegative(), + scannedWorkspaces: external_exports.number().int().nonnegative(), + discovered: external_exports.number().int().nonnegative(), + imported: external_exports.array(companySkillSchema), + updated: external_exports.array(companySkillSchema), + skipped: external_exports.array(companySkillProjectScanSkippedSchema), + conflicts: external_exports.array(companySkillProjectScanConflictSchema), + warnings: external_exports.array(external_exports.string()) +}); +var companySkillCreateSchema = external_exports.object({ + name: external_exports.string().min(1), + slug: external_exports.string().min(1).nullable().optional(), + description: external_exports.string().nullable().optional(), + markdown: external_exports.string().nullable().optional() +}); +var companySkillFileDetailSchema = external_exports.object({ + skillId: external_exports.string().uuid(), + path: external_exports.string().min(1), + kind: external_exports.enum(["skill", "markdown", "reference", "script", "asset", "other"]), + content: external_exports.string(), + language: external_exports.string().nullable(), + markdown: external_exports.boolean(), + editable: external_exports.boolean() +}); +var companySkillFileUpdateSchema = external_exports.object({ + path: external_exports.string().min(1), + content: external_exports.string() +}); + +// packages/shared/src/validators/adapter-skills.ts +var agentSkillStateSchema = external_exports.enum([ + "available", + "configured", + "installed", + "missing", + "stale", + "external" +]); +var agentSkillOriginSchema = external_exports.enum([ + "company_managed", + "taskcore_required", + "user_installed", + "external_unknown" +]); +var agentSkillSyncModeSchema = external_exports.enum([ + "unsupported", + "persistent", + "ephemeral" +]); +var agentSkillEntrySchema = external_exports.object({ + key: external_exports.string().min(1), + runtimeName: external_exports.string().min(1).nullable(), + desired: external_exports.boolean(), + managed: external_exports.boolean(), + required: external_exports.boolean().optional(), + requiredReason: external_exports.string().nullable().optional(), + state: agentSkillStateSchema, + origin: agentSkillOriginSchema.optional(), + originLabel: external_exports.string().nullable().optional(), + locationLabel: external_exports.string().nullable().optional(), + readOnly: external_exports.boolean().optional(), + sourcePath: external_exports.string().nullable().optional(), + targetPath: external_exports.string().nullable().optional(), + detail: external_exports.string().nullable().optional() +}); +var agentSkillSnapshotSchema = external_exports.object({ + adapterType: external_exports.string().min(1), + supported: external_exports.boolean(), + mode: agentSkillSyncModeSchema, + desiredSkills: external_exports.array(external_exports.string().min(1)), + entries: external_exports.array(agentSkillEntrySchema), + warnings: external_exports.array(external_exports.string()) +}); +var agentSkillSyncSchema = external_exports.object({ + desiredSkills: external_exports.array(external_exports.string().min(1)) +}); + +// packages/shared/src/validators/issue.ts +var ISSUE_EXECUTION_WORKSPACE_PREFERENCES = [ + "inherit", + "shared_workspace", + "isolated_workspace", + "operator_branch", + "reuse_existing", + "agent_default" +]; +var executionWorkspaceStrategySchema = external_exports.object({ + type: external_exports.enum(["project_primary", "git_worktree", "adapter_managed", "cloud_sandbox"]).optional(), + baseRef: external_exports.string().optional().nullable(), + branchTemplate: external_exports.string().optional().nullable(), + worktreeParentDir: external_exports.string().optional().nullable(), + provisionCommand: external_exports.string().optional().nullable(), + teardownCommand: external_exports.string().optional().nullable() +}).strict(); +var issueExecutionWorkspaceSettingsSchema = external_exports.object({ + mode: external_exports.enum(ISSUE_EXECUTION_WORKSPACE_PREFERENCES).optional(), + workspaceStrategy: executionWorkspaceStrategySchema.optional().nullable(), + workspaceRuntime: external_exports.record(external_exports.unknown()).optional().nullable() +}).strict(); +var issueAssigneeAdapterOverridesSchema = external_exports.object({ + adapterConfig: external_exports.record(external_exports.unknown()).optional(), + useProjectWorkspace: external_exports.boolean().optional() +}).strict(); +var issueExecutionStagePrincipalBaseSchema = external_exports.object({ + type: external_exports.enum(["agent", "user"]), + agentId: external_exports.string().uuid().optional().nullable(), + userId: external_exports.string().optional().nullable() +}); +var issueExecutionStagePrincipalSchema = issueExecutionStagePrincipalBaseSchema.superRefine((value, ctx) => { + if (value.type === "agent") { + if (!value.agentId) { + ctx.addIssue({ code: external_exports.ZodIssueCode.custom, message: "Agent participants require agentId", path: ["agentId"] }); + } + if (value.userId) { + ctx.addIssue({ code: external_exports.ZodIssueCode.custom, message: "Agent participants cannot set userId", path: ["userId"] }); + } + return; + } + if (!value.userId) { + ctx.addIssue({ code: external_exports.ZodIssueCode.custom, message: "User participants require userId", path: ["userId"] }); + } + if (value.agentId) { + ctx.addIssue({ code: external_exports.ZodIssueCode.custom, message: "User participants cannot set agentId", path: ["agentId"] }); + } +}); +var issueExecutionStageParticipantSchema = issueExecutionStagePrincipalBaseSchema.extend({ + id: external_exports.string().uuid().optional() +}).superRefine((value, ctx) => { + if (value.type === "agent") { + if (!value.agentId) { + ctx.addIssue({ code: external_exports.ZodIssueCode.custom, message: "Agent participants require agentId", path: ["agentId"] }); + } + if (value.userId) { + ctx.addIssue({ code: external_exports.ZodIssueCode.custom, message: "Agent participants cannot set userId", path: ["userId"] }); + } + return; + } + if (!value.userId) { + ctx.addIssue({ code: external_exports.ZodIssueCode.custom, message: "User participants require userId", path: ["userId"] }); + } + if (value.agentId) { + ctx.addIssue({ code: external_exports.ZodIssueCode.custom, message: "User participants cannot set agentId", path: ["agentId"] }); + } +}); +var issueExecutionStageSchema = external_exports.object({ + id: external_exports.string().uuid().optional(), + type: external_exports.enum(ISSUE_EXECUTION_STAGE_TYPES), + approvalsNeeded: external_exports.literal(1).optional().default(1), + participants: external_exports.array(issueExecutionStageParticipantSchema).default([]) +}); +var issueExecutionPolicySchema = external_exports.object({ + mode: external_exports.enum(ISSUE_EXECUTION_POLICY_MODES).optional().default("normal"), + commentRequired: external_exports.boolean().optional().default(true), + stages: external_exports.array(issueExecutionStageSchema).default([]) +}); +var issueExecutionStateSchema = external_exports.object({ + status: external_exports.enum(ISSUE_EXECUTION_STATE_STATUSES), + currentStageId: external_exports.string().uuid().nullable(), + currentStageIndex: external_exports.number().int().nonnegative().nullable(), + currentStageType: external_exports.enum(ISSUE_EXECUTION_STAGE_TYPES).nullable(), + currentParticipant: issueExecutionStagePrincipalSchema.nullable(), + returnAssignee: issueExecutionStagePrincipalSchema.nullable(), + completedStageIds: external_exports.array(external_exports.string().uuid()).default([]), + lastDecisionId: external_exports.string().uuid().nullable(), + lastDecisionOutcome: external_exports.enum(ISSUE_EXECUTION_DECISION_OUTCOMES).nullable() +}); +var createIssueSchema = external_exports.object({ + projectId: external_exports.string().uuid().optional().nullable(), + projectWorkspaceId: external_exports.string().uuid().optional().nullable(), + goalId: external_exports.string().uuid().optional().nullable(), + parentId: external_exports.string().uuid().optional().nullable(), + blockedByIssueIds: external_exports.array(external_exports.string().uuid()).optional(), + inheritExecutionWorkspaceFromIssueId: external_exports.string().uuid().optional().nullable(), + title: external_exports.string().min(1), + description: external_exports.string().optional().nullable(), + status: external_exports.enum(ISSUE_STATUSES).optional().default("backlog"), + priority: external_exports.enum(ISSUE_PRIORITIES).optional().default("medium"), + assigneeAgentId: external_exports.string().uuid().optional().nullable(), + assigneeUserId: external_exports.string().optional().nullable(), + requestDepth: external_exports.number().int().nonnegative().optional().default(0), + billingCode: external_exports.string().optional().nullable(), + assigneeAdapterOverrides: issueAssigneeAdapterOverridesSchema.optional().nullable(), + executionPolicy: issueExecutionPolicySchema.optional().nullable(), + executionWorkspaceId: external_exports.string().uuid().optional().nullable(), + executionWorkspacePreference: external_exports.enum(ISSUE_EXECUTION_WORKSPACE_PREFERENCES).optional().nullable(), + executionWorkspaceSettings: issueExecutionWorkspaceSettingsSchema.optional().nullable(), + labelIds: external_exports.array(external_exports.string().uuid()).optional() +}); +var createIssueLabelSchema = external_exports.object({ + name: external_exports.string().trim().min(1).max(48), + color: external_exports.string().regex(/^#(?:[0-9a-fA-F]{6})$/, "Color must be a 6-digit hex value") +}); +var updateIssueSchema = createIssueSchema.partial().extend({ + assigneeAgentId: external_exports.string().trim().min(1).optional().nullable(), + comment: external_exports.string().min(1).optional(), + reopen: external_exports.boolean().optional(), + interrupt: external_exports.boolean().optional(), + hiddenAt: external_exports.string().datetime().nullable().optional() +}); +var checkoutIssueSchema = external_exports.object({ + agentId: external_exports.string().uuid(), + expectedStatuses: external_exports.array(external_exports.enum(ISSUE_STATUSES)).nonempty() +}); +var addIssueCommentSchema = external_exports.object({ + body: external_exports.string().min(1), + reopen: external_exports.boolean().optional(), + interrupt: external_exports.boolean().optional() +}); +var linkIssueApprovalSchema = external_exports.object({ + approvalId: external_exports.string().uuid() +}); +var createIssueAttachmentMetadataSchema = external_exports.object({ + issueCommentId: external_exports.string().uuid().optional().nullable() +}); +var ISSUE_DOCUMENT_FORMATS = ["markdown"]; +var issueDocumentFormatSchema = external_exports.enum(ISSUE_DOCUMENT_FORMATS); +var issueDocumentKeySchema = external_exports.string().trim().min(1).max(64).regex(/^[a-z0-9][a-z0-9_-]*$/, "Document key must be lowercase letters, numbers, _ or -"); +var upsertIssueDocumentSchema = external_exports.object({ + title: external_exports.string().trim().max(200).nullable().optional(), + format: issueDocumentFormatSchema, + body: external_exports.string().max(524288), + changeSummary: external_exports.string().trim().max(500).nullable().optional(), + baseRevisionId: external_exports.string().uuid().nullable().optional() +}); +var restoreIssueDocumentRevisionSchema = external_exports.object({}); + +// packages/shared/src/validators/routine.ts +var routineVariableValueSchema = external_exports.union([external_exports.string(), external_exports.number().finite(), external_exports.boolean()]); +var routineVariableSchema = external_exports.object({ + name: external_exports.string().trim().regex(/^[A-Za-z][A-Za-z0-9_]*$/), + label: external_exports.string().trim().max(120).optional().nullable(), + type: external_exports.enum(ROUTINE_VARIABLE_TYPES).optional().default("text"), + defaultValue: routineVariableValueSchema.optional().nullable(), + required: external_exports.boolean().optional().default(true), + options: external_exports.array(external_exports.string().trim().min(1).max(120)).max(50).optional().default([]) +}).superRefine((value, ctx) => { + if (value.type === "select" && value.options.length === 0) { + ctx.addIssue({ + code: external_exports.ZodIssueCode.custom, + path: ["options"], + message: "Select variables require at least one option" + }); + } + if (value.type !== "select" && value.options.length > 0) { + ctx.addIssue({ + code: external_exports.ZodIssueCode.custom, + path: ["options"], + message: "Only select variables can define options" + }); + } + if (value.type === "select" && value.defaultValue != null) { + if (typeof value.defaultValue !== "string" || !value.options.includes(value.defaultValue)) { + ctx.addIssue({ + code: external_exports.ZodIssueCode.custom, + path: ["defaultValue"], + message: "Select variable defaults must match one of the allowed options" + }); + } + } +}); +var createRoutineSchema = external_exports.object({ + projectId: external_exports.string().uuid().optional().nullable(), + goalId: external_exports.string().uuid().optional().nullable(), + parentIssueId: external_exports.string().uuid().optional().nullable(), + title: external_exports.string().trim().min(1).max(200), + description: external_exports.string().optional().nullable(), + assigneeAgentId: external_exports.string().uuid().optional().nullable(), + priority: external_exports.enum(ISSUE_PRIORITIES).optional().default("medium"), + status: external_exports.enum(ROUTINE_STATUSES).optional().default("active"), + concurrencyPolicy: external_exports.enum(ROUTINE_CONCURRENCY_POLICIES).optional().default("coalesce_if_active"), + catchUpPolicy: external_exports.enum(ROUTINE_CATCH_UP_POLICIES).optional().default("skip_missed"), + variables: external_exports.array(routineVariableSchema).optional().default([]) +}); +var updateRoutineSchema = createRoutineSchema.partial(); +var baseTriggerSchema = external_exports.object({ + label: external_exports.string().trim().max(120).optional().nullable(), + enabled: external_exports.boolean().optional().default(true) +}); +var createRoutineTriggerSchema = external_exports.discriminatedUnion("kind", [ + baseTriggerSchema.extend({ + kind: external_exports.literal("schedule"), + cronExpression: external_exports.string().trim().min(1), + timezone: external_exports.string().trim().min(1).default("UTC") + }), + baseTriggerSchema.extend({ + kind: external_exports.literal("webhook"), + signingMode: external_exports.enum(ROUTINE_TRIGGER_SIGNING_MODES).optional().default("bearer"), + replayWindowSec: external_exports.number().int().min(30).max(86400).optional().default(300) + }), + baseTriggerSchema.extend({ + kind: external_exports.literal("api") + }) +]); +var updateRoutineTriggerSchema = external_exports.object({ + label: external_exports.string().trim().max(120).optional().nullable(), + enabled: external_exports.boolean().optional(), + cronExpression: external_exports.string().trim().min(1).optional().nullable(), + timezone: external_exports.string().trim().min(1).optional().nullable(), + signingMode: external_exports.enum(ROUTINE_TRIGGER_SIGNING_MODES).optional().nullable(), + replayWindowSec: external_exports.number().int().min(30).max(86400).optional().nullable() +}); +var runRoutineSchema = external_exports.object({ + triggerId: external_exports.string().uuid().optional().nullable(), + payload: external_exports.record(external_exports.unknown()).optional().nullable(), + variables: external_exports.record(routineVariableValueSchema).optional().nullable(), + projectId: external_exports.string().uuid().optional().nullable(), + assigneeAgentId: external_exports.string().uuid().optional().nullable(), + idempotencyKey: external_exports.string().trim().max(255).optional().nullable(), + source: external_exports.enum(["manual", "api"]).optional().default("manual"), + executionWorkspaceId: external_exports.string().uuid().optional().nullable(), + executionWorkspacePreference: external_exports.enum(ISSUE_EXECUTION_WORKSPACE_PREFERENCES).optional().nullable(), + executionWorkspaceSettings: issueExecutionWorkspaceSettingsSchema.optional().nullable() +}); +var rotateRoutineTriggerSecretSchema = external_exports.object({}); + +// packages/shared/src/validators/company-portability.ts +var portabilityIncludeSchema = external_exports.object({ + company: external_exports.boolean().optional(), + agents: external_exports.boolean().optional(), + projects: external_exports.boolean().optional(), + issues: external_exports.boolean().optional(), + skills: external_exports.boolean().optional() +}).partial(); +var portabilityEnvInputSchema = external_exports.object({ + key: external_exports.string().min(1), + description: external_exports.string().nullable(), + agentSlug: external_exports.string().min(1).nullable(), + projectSlug: external_exports.string().min(1).nullable(), + kind: external_exports.enum(["secret", "plain"]), + requirement: external_exports.enum(["required", "optional"]), + defaultValue: external_exports.string().nullable(), + portability: external_exports.enum(["portable", "system_dependent"]) +}); +var portabilityFileEntrySchema = external_exports.union([ + external_exports.string(), + external_exports.object({ + encoding: external_exports.literal("base64"), + data: external_exports.string(), + contentType: external_exports.string().min(1).optional().nullable() + }) +]); +var portabilityCompanyManifestEntrySchema = external_exports.object({ + path: external_exports.string().min(1), + name: external_exports.string().min(1), + description: external_exports.string().nullable(), + brandColor: external_exports.string().nullable(), + logoPath: external_exports.string().nullable(), + requireBoardApprovalForNewAgents: external_exports.boolean(), + feedbackDataSharingEnabled: external_exports.boolean().default(false), + feedbackDataSharingConsentAt: external_exports.string().datetime().nullable().default(null), + feedbackDataSharingConsentByUserId: external_exports.string().nullable().default(null), + feedbackDataSharingTermsVersion: external_exports.string().nullable().default(null) +}); +var portabilitySidebarOrderSchema = external_exports.object({ + agents: external_exports.array(external_exports.string().min(1)).default([]), + projects: external_exports.array(external_exports.string().min(1)).default([]) +}); +var portabilityAgentManifestEntrySchema = external_exports.object({ + slug: external_exports.string().min(1), + name: external_exports.string().min(1), + path: external_exports.string().min(1), + skills: external_exports.array(external_exports.string().min(1)).default([]), + role: external_exports.string().min(1), + title: external_exports.string().nullable(), + icon: external_exports.string().nullable(), + capabilities: external_exports.string().nullable(), + reportsToSlug: external_exports.string().min(1).nullable(), + adapterType: external_exports.string().min(1), + adapterConfig: external_exports.record(external_exports.unknown()), + runtimeConfig: external_exports.record(external_exports.unknown()), + permissions: external_exports.record(external_exports.unknown()), + budgetMonthlyCents: external_exports.number().int().nonnegative(), + metadata: external_exports.record(external_exports.unknown()).nullable() +}); +var portabilitySkillManifestEntrySchema = external_exports.object({ + key: external_exports.string().min(1), + slug: external_exports.string().min(1), + name: external_exports.string().min(1), + path: external_exports.string().min(1), + description: external_exports.string().nullable(), + sourceType: external_exports.string().min(1), + sourceLocator: external_exports.string().nullable(), + sourceRef: external_exports.string().nullable(), + trustLevel: external_exports.string().nullable(), + compatibility: external_exports.string().nullable(), + metadata: external_exports.record(external_exports.unknown()).nullable(), + fileInventory: external_exports.array(external_exports.object({ + path: external_exports.string().min(1), + kind: external_exports.string().min(1) + })).default([]) +}); +var portabilityProjectManifestEntrySchema = external_exports.object({ + slug: external_exports.string().min(1), + name: external_exports.string().min(1), + path: external_exports.string().min(1), + description: external_exports.string().nullable(), + ownerAgentSlug: external_exports.string().min(1).nullable(), + leadAgentSlug: external_exports.string().min(1).nullable(), + targetDate: external_exports.string().nullable(), + color: external_exports.string().nullable(), + status: external_exports.string().nullable(), + executionWorkspacePolicy: external_exports.record(external_exports.unknown()).nullable(), + workspaces: external_exports.array(external_exports.object({ + key: external_exports.string().min(1), + name: external_exports.string().min(1), + sourceType: external_exports.string().nullable(), + repoUrl: external_exports.string().nullable(), + repoRef: external_exports.string().nullable(), + defaultRef: external_exports.string().nullable(), + visibility: external_exports.string().nullable(), + setupCommand: external_exports.string().nullable(), + cleanupCommand: external_exports.string().nullable(), + metadata: external_exports.record(external_exports.unknown()).nullable(), + isPrimary: external_exports.boolean() + })).default([]), + metadata: external_exports.record(external_exports.unknown()).nullable() +}); +var portabilityIssueRoutineTriggerManifestEntrySchema = external_exports.object({ + kind: external_exports.string().min(1), + label: external_exports.string().nullable(), + enabled: external_exports.boolean(), + cronExpression: external_exports.string().nullable(), + timezone: external_exports.string().nullable(), + signingMode: external_exports.string().nullable(), + replayWindowSec: external_exports.number().int().nullable() +}); +var portabilityIssueRoutineManifestEntrySchema = external_exports.object({ + concurrencyPolicy: external_exports.string().nullable(), + catchUpPolicy: external_exports.string().nullable(), + variables: external_exports.array(routineVariableSchema).nullable().optional(), + triggers: external_exports.array(portabilityIssueRoutineTriggerManifestEntrySchema).default([]) +}); +var portabilityIssueManifestEntrySchema = external_exports.object({ + slug: external_exports.string().min(1), + identifier: external_exports.string().min(1).nullable(), + title: external_exports.string().min(1), + path: external_exports.string().min(1), + projectSlug: external_exports.string().min(1).nullable(), + projectWorkspaceKey: external_exports.string().min(1).nullable(), + assigneeAgentSlug: external_exports.string().min(1).nullable(), + description: external_exports.string().nullable(), + recurring: external_exports.boolean().default(false), + routine: portabilityIssueRoutineManifestEntrySchema.nullable(), + legacyRecurrence: external_exports.record(external_exports.unknown()).nullable(), + status: external_exports.string().nullable(), + priority: external_exports.string().nullable(), + labelIds: external_exports.array(external_exports.string().min(1)).default([]), + billingCode: external_exports.string().nullable(), + executionWorkspaceSettings: external_exports.record(external_exports.unknown()).nullable(), + assigneeAdapterOverrides: external_exports.record(external_exports.unknown()).nullable(), + metadata: external_exports.record(external_exports.unknown()).nullable() +}); +var portabilityManifestSchema = external_exports.object({ + schemaVersion: external_exports.number().int().positive(), + generatedAt: external_exports.string().datetime(), + source: external_exports.object({ + companyId: external_exports.string().uuid(), + companyName: external_exports.string().min(1) + }).nullable(), + includes: external_exports.object({ + company: external_exports.boolean(), + agents: external_exports.boolean(), + projects: external_exports.boolean(), + issues: external_exports.boolean(), + skills: external_exports.boolean() + }), + company: portabilityCompanyManifestEntrySchema.nullable(), + sidebar: portabilitySidebarOrderSchema.nullable(), + agents: external_exports.array(portabilityAgentManifestEntrySchema), + skills: external_exports.array(portabilitySkillManifestEntrySchema).default([]), + projects: external_exports.array(portabilityProjectManifestEntrySchema).default([]), + issues: external_exports.array(portabilityIssueManifestEntrySchema).default([]), + envInputs: external_exports.array(portabilityEnvInputSchema).default([]) +}); +var portabilitySourceSchema = external_exports.discriminatedUnion("type", [ + external_exports.object({ + type: external_exports.literal("inline"), + rootPath: external_exports.string().min(1).optional().nullable(), + files: external_exports.record(portabilityFileEntrySchema) + }), + external_exports.object({ + type: external_exports.literal("github"), + url: external_exports.string().url() + }) +]); +var portabilityTargetSchema = external_exports.discriminatedUnion("mode", [ + external_exports.object({ + mode: external_exports.literal("new_company"), + newCompanyName: external_exports.string().min(1).optional().nullable() + }), + external_exports.object({ + mode: external_exports.literal("existing_company"), + companyId: external_exports.string().uuid() + }) +]); +var portabilityAgentSelectionSchema = external_exports.union([ + external_exports.literal("all"), + external_exports.array(external_exports.string().min(1)) +]); +var portabilityCollisionStrategySchema = external_exports.enum(["rename", "skip", "replace"]); +var companyPortabilityExportSchema = external_exports.object({ + include: portabilityIncludeSchema.optional(), + agents: external_exports.array(external_exports.string().min(1)).optional(), + skills: external_exports.array(external_exports.string().min(1)).optional(), + projects: external_exports.array(external_exports.string().min(1)).optional(), + issues: external_exports.array(external_exports.string().min(1)).optional(), + projectIssues: external_exports.array(external_exports.string().min(1)).optional(), + selectedFiles: external_exports.array(external_exports.string().min(1)).optional(), + expandReferencedSkills: external_exports.boolean().optional(), + sidebarOrder: portabilitySidebarOrderSchema.partial().optional() +}); +var companyPortabilityPreviewSchema = external_exports.object({ + source: portabilitySourceSchema, + include: portabilityIncludeSchema.optional(), + target: portabilityTargetSchema, + agents: portabilityAgentSelectionSchema.optional(), + collisionStrategy: portabilityCollisionStrategySchema.optional(), + nameOverrides: external_exports.record(external_exports.string().min(1), external_exports.string().min(1)).optional(), + selectedFiles: external_exports.array(external_exports.string().min(1)).optional() +}); +var portabilityAdapterOverrideSchema = external_exports.object({ + adapterType: external_exports.string().min(1), + adapterConfig: external_exports.record(external_exports.unknown()).optional() +}); +var companyPortabilityImportSchema = companyPortabilityPreviewSchema.extend({ + adapterOverrides: external_exports.record(external_exports.string().min(1), portabilityAdapterOverrideSchema).optional() +}); + +// packages/shared/src/validators/secret.ts +var envBindingPlainSchema = external_exports.object({ + type: external_exports.literal("plain"), + value: external_exports.string() +}); +var envBindingSecretRefSchema = external_exports.object({ + type: external_exports.literal("secret_ref"), + secretId: external_exports.string().uuid(), + version: external_exports.union([external_exports.literal("latest"), external_exports.number().int().positive()]).optional() +}); +var envBindingSchema = external_exports.union([ + external_exports.string(), + envBindingPlainSchema, + envBindingSecretRefSchema +]); +var envConfigSchema = external_exports.record(envBindingSchema); +var createSecretSchema = external_exports.object({ + name: external_exports.string().min(1), + provider: external_exports.enum(SECRET_PROVIDERS).optional(), + value: external_exports.string().min(1), + description: external_exports.string().optional().nullable(), + externalRef: external_exports.string().optional().nullable() +}); +var rotateSecretSchema = external_exports.object({ + value: external_exports.string().min(1), + externalRef: external_exports.string().optional().nullable() +}); +var updateSecretSchema = external_exports.object({ + name: external_exports.string().min(1).optional(), + description: external_exports.string().optional().nullable(), + externalRef: external_exports.string().optional().nullable() +}); + +// packages/shared/src/validators/agent.ts +var agentPermissionsSchema = external_exports.object({ + canCreateAgents: external_exports.boolean().optional().default(false) +}); +var agentInstructionsBundleModeSchema = external_exports.enum(["managed", "external"]); +var updateAgentInstructionsBundleSchema = external_exports.object({ + mode: agentInstructionsBundleModeSchema.optional(), + rootPath: external_exports.string().trim().min(1).nullable().optional(), + entryFile: external_exports.string().trim().min(1).optional(), + clearLegacyPromptTemplate: external_exports.boolean().optional().default(false) +}); +var upsertAgentInstructionsFileSchema = external_exports.object({ + path: external_exports.string().trim().min(1), + content: external_exports.string(), + clearLegacyPromptTemplate: external_exports.boolean().optional().default(false) +}); +var adapterConfigSchema = external_exports.record(external_exports.unknown()).superRefine((value, ctx) => { + const envValue = value.env; + if (envValue === void 0) return; + const parsed = envConfigSchema.safeParse(envValue); + if (!parsed.success) { + ctx.addIssue({ + code: external_exports.ZodIssueCode.custom, + message: "adapterConfig.env must be a map of valid env bindings", + path: ["env"] + }); + } +}); +var createAgentSchema = external_exports.object({ + name: external_exports.string().min(1), + role: external_exports.enum(AGENT_ROLES).optional().default("general"), + title: external_exports.string().optional().nullable(), + icon: external_exports.enum(AGENT_ICON_NAMES).optional().nullable(), + reportsTo: external_exports.string().uuid().optional().nullable(), + capabilities: external_exports.string().optional().nullable(), + desiredSkills: external_exports.array(external_exports.string().min(1)).optional(), + adapterType: agentAdapterTypeSchema, + adapterConfig: adapterConfigSchema.optional().default({}), + runtimeConfig: external_exports.record(external_exports.unknown()).optional().default({}), + budgetMonthlyCents: external_exports.number().int().nonnegative().optional().default(0), + permissions: agentPermissionsSchema.optional(), + metadata: external_exports.record(external_exports.unknown()).optional().nullable() +}); +var createAgentHireSchema = createAgentSchema.extend({ + sourceIssueId: external_exports.string().uuid().optional().nullable(), + sourceIssueIds: external_exports.array(external_exports.string().uuid()).optional() +}); +var updateAgentSchema = createAgentSchema.omit({ permissions: true }).partial().extend({ + permissions: external_exports.never().optional(), + replaceAdapterConfig: external_exports.boolean().optional(), + status: external_exports.enum(AGENT_STATUSES).optional(), + spentMonthlyCents: external_exports.number().int().nonnegative().optional() +}); +var updateAgentInstructionsPathSchema = external_exports.object({ + path: external_exports.string().trim().min(1).nullable(), + adapterConfigKey: external_exports.string().trim().min(1).optional() +}); +var createAgentKeySchema = external_exports.object({ + name: external_exports.string().min(1).default("default") +}); +var agentMineInboxQuerySchema = external_exports.object({ + userId: external_exports.string().trim().min(1), + status: external_exports.string().trim().min(1).optional().default(INBOX_MINE_ISSUE_STATUS_FILTER) +}); +var wakeAgentSchema = external_exports.object({ + source: external_exports.enum(["timer", "assignment", "on_demand", "automation"]).optional().default("on_demand"), + triggerDetail: external_exports.enum(["manual", "ping", "callback", "system"]).optional(), + reason: external_exports.string().optional().nullable(), + payload: external_exports.record(external_exports.unknown()).optional().nullable(), + idempotencyKey: external_exports.string().optional().nullable(), + forceFreshSession: external_exports.preprocess( + (value) => value === null ? void 0 : value, + external_exports.boolean().optional().default(false) + ) +}); +var resetAgentSessionSchema = external_exports.object({ + taskKey: external_exports.string().min(1).optional().nullable() +}); +var testAdapterEnvironmentSchema = external_exports.object({ + adapterConfig: adapterConfigSchema.optional().default({}) +}); +var updateAgentPermissionsSchema = external_exports.object({ + canCreateAgents: external_exports.boolean(), + canAssignTasks: external_exports.boolean() +}); + +// packages/shared/src/validators/project.ts +var executionWorkspaceStrategySchema2 = external_exports.object({ + type: external_exports.enum(["project_primary", "git_worktree", "adapter_managed", "cloud_sandbox"]).optional(), + baseRef: external_exports.string().optional().nullable(), + branchTemplate: external_exports.string().optional().nullable(), + worktreeParentDir: external_exports.string().optional().nullable(), + provisionCommand: external_exports.string().optional().nullable(), + teardownCommand: external_exports.string().optional().nullable() +}).strict(); +var projectExecutionWorkspacePolicySchema = external_exports.object({ + enabled: external_exports.boolean(), + defaultMode: external_exports.enum(["shared_workspace", "isolated_workspace", "operator_branch", "adapter_default"]).optional(), + allowIssueOverride: external_exports.boolean().optional(), + defaultProjectWorkspaceId: external_exports.string().uuid().optional().nullable(), + workspaceStrategy: executionWorkspaceStrategySchema2.optional().nullable(), + workspaceRuntime: external_exports.record(external_exports.unknown()).optional().nullable(), + branchPolicy: external_exports.record(external_exports.unknown()).optional().nullable(), + pullRequestPolicy: external_exports.record(external_exports.unknown()).optional().nullable(), + runtimePolicy: external_exports.record(external_exports.unknown()).optional().nullable(), + cleanupPolicy: external_exports.record(external_exports.unknown()).optional().nullable() +}).strict(); +var projectWorkspaceRuntimeConfigSchema = external_exports.object({ + workspaceRuntime: external_exports.record(external_exports.unknown()).optional().nullable(), + desiredState: external_exports.enum(["running", "stopped"]).optional().nullable(), + serviceStates: external_exports.record(external_exports.enum(["running", "stopped"])).optional().nullable() +}).strict(); +var projectWorkspaceSourceTypeSchema = external_exports.enum(["local_path", "git_repo", "remote_managed", "non_git_path"]); +var projectWorkspaceVisibilitySchema = external_exports.enum(["default", "advanced"]); +var projectWorkspaceFields = { + name: external_exports.string().min(1).optional(), + sourceType: projectWorkspaceSourceTypeSchema.optional(), + cwd: external_exports.string().min(1).optional().nullable(), + repoUrl: external_exports.string().url().optional().nullable(), + repoRef: external_exports.string().optional().nullable(), + defaultRef: external_exports.string().optional().nullable(), + visibility: projectWorkspaceVisibilitySchema.optional(), + setupCommand: external_exports.string().optional().nullable(), + cleanupCommand: external_exports.string().optional().nullable(), + remoteProvider: external_exports.string().optional().nullable(), + remoteWorkspaceRef: external_exports.string().optional().nullable(), + sharedWorkspaceKey: external_exports.string().optional().nullable(), + metadata: external_exports.record(external_exports.unknown()).optional().nullable(), + runtimeConfig: projectWorkspaceRuntimeConfigSchema.optional().nullable() +}; +function validateProjectWorkspace(value, ctx) { + const sourceType = value.sourceType ?? "local_path"; + const hasCwd = typeof value.cwd === "string" && value.cwd.trim().length > 0; + const hasRepo = typeof value.repoUrl === "string" && value.repoUrl.trim().length > 0; + const hasRemoteRef = typeof value.remoteWorkspaceRef === "string" && value.remoteWorkspaceRef.trim().length > 0; + if (sourceType === "remote_managed") { + if (!hasRemoteRef && !hasRepo) { + ctx.addIssue({ + code: external_exports.ZodIssueCode.custom, + message: "Remote-managed workspace requires remoteWorkspaceRef or repoUrl.", + path: ["remoteWorkspaceRef"] + }); + } + return; + } + if (!hasCwd && !hasRepo) { + ctx.addIssue({ + code: external_exports.ZodIssueCode.custom, + message: "Workspace requires at least one of cwd or repoUrl.", + path: ["cwd"] + }); + } +} +var createProjectWorkspaceSchema = external_exports.object({ + ...projectWorkspaceFields, + isPrimary: external_exports.boolean().optional().default(false) +}).superRefine(validateProjectWorkspace); +var updateProjectWorkspaceSchema = external_exports.object({ + ...projectWorkspaceFields, + isPrimary: external_exports.boolean().optional() +}).partial(); +var projectFields = { + /** @deprecated Use goalIds instead */ + goalId: external_exports.string().uuid().optional().nullable(), + goalIds: external_exports.array(external_exports.string().uuid()).optional(), + name: external_exports.string().min(1), + description: external_exports.string().optional().nullable(), + status: external_exports.enum(PROJECT_STATUSES).optional().default("backlog"), + leadAgentId: external_exports.string().uuid().optional().nullable(), + targetDate: external_exports.string().optional().nullable(), + color: external_exports.string().optional().nullable(), + env: envConfigSchema.optional().nullable(), + executionWorkspacePolicy: projectExecutionWorkspacePolicySchema.optional().nullable(), + archivedAt: external_exports.string().datetime().optional().nullable() +}; +var createProjectSchema = external_exports.object({ + ...projectFields, + workspace: createProjectWorkspaceSchema.optional() +}); +var updateProjectSchema = external_exports.object(projectFields).partial(); + +// packages/shared/src/validators/work-product.ts +var issueWorkProductTypeSchema = external_exports.enum([ + "preview_url", + "runtime_service", + "pull_request", + "branch", + "commit", + "artifact", + "document" +]); +var issueWorkProductStatusSchema = external_exports.enum([ + "active", + "ready_for_review", + "approved", + "changes_requested", + "merged", + "closed", + "failed", + "archived", + "draft" +]); +var issueWorkProductReviewStateSchema = external_exports.enum([ + "none", + "needs_board_review", + "approved", + "changes_requested" +]); +var createIssueWorkProductSchema = external_exports.object({ + projectId: external_exports.string().uuid().optional().nullable(), + executionWorkspaceId: external_exports.string().uuid().optional().nullable(), + runtimeServiceId: external_exports.string().uuid().optional().nullable(), + type: issueWorkProductTypeSchema, + provider: external_exports.string().min(1), + externalId: external_exports.string().optional().nullable(), + title: external_exports.string().min(1), + url: external_exports.string().url().optional().nullable(), + status: issueWorkProductStatusSchema.default("active"), + reviewState: issueWorkProductReviewStateSchema.optional().default("none"), + isPrimary: external_exports.boolean().optional().default(false), + healthStatus: external_exports.enum(["unknown", "healthy", "unhealthy"]).optional().default("unknown"), + summary: external_exports.string().optional().nullable(), + metadata: external_exports.record(external_exports.unknown()).optional().nullable(), + createdByRunId: external_exports.string().uuid().optional().nullable() +}); +var updateIssueWorkProductSchema = createIssueWorkProductSchema.partial(); + +// packages/shared/src/validators/goal.ts +var createGoalSchema = external_exports.object({ + title: external_exports.string().min(1), + description: external_exports.string().optional().nullable(), + level: external_exports.enum(GOAL_LEVELS).optional().default("task"), + status: external_exports.enum(GOAL_STATUSES).optional().default("planned"), + parentId: external_exports.string().uuid().optional().nullable(), + ownerAgentId: external_exports.string().uuid().optional().nullable() +}); +var updateGoalSchema = createGoalSchema.partial(); + +// packages/shared/src/validators/approval.ts +var createApprovalSchema = external_exports.object({ + type: external_exports.enum(APPROVAL_TYPES), + requestedByAgentId: external_exports.string().uuid().optional().nullable(), + payload: external_exports.record(external_exports.unknown()), + issueIds: external_exports.array(external_exports.string().uuid()).optional() +}); +var resolveApprovalSchema = external_exports.object({ + decisionNote: external_exports.string().optional().nullable(), + decidedByUserId: external_exports.string().optional().default("board") +}); +var requestApprovalRevisionSchema = external_exports.object({ + decisionNote: external_exports.string().optional().nullable(), + decidedByUserId: external_exports.string().optional().default("board") +}); +var resubmitApprovalSchema = external_exports.object({ + payload: external_exports.record(external_exports.unknown()).optional() +}); +var addApprovalCommentSchema = external_exports.object({ + body: external_exports.string().min(1) +}); + +// packages/shared/src/validators/cost.ts +var createCostEventSchema = external_exports.object({ + agentId: external_exports.string().uuid(), + issueId: external_exports.string().uuid().optional().nullable(), + projectId: external_exports.string().uuid().optional().nullable(), + goalId: external_exports.string().uuid().optional().nullable(), + heartbeatRunId: external_exports.string().uuid().optional().nullable(), + billingCode: external_exports.string().optional().nullable(), + provider: external_exports.string().min(1), + biller: external_exports.string().min(1).optional(), + billingType: external_exports.enum(BILLING_TYPES).optional().default("unknown"), + model: external_exports.string().min(1), + inputTokens: external_exports.number().int().nonnegative().optional().default(0), + cachedInputTokens: external_exports.number().int().nonnegative().optional().default(0), + outputTokens: external_exports.number().int().nonnegative().optional().default(0), + costCents: external_exports.number().int().nonnegative(), + occurredAt: external_exports.string().datetime() +}).transform((value) => ({ + ...value, + biller: value.biller ?? value.provider +})); +var updateBudgetSchema = external_exports.object({ + budgetMonthlyCents: external_exports.number().int().nonnegative() +}); + +// packages/shared/src/validators/finance.ts +var createFinanceEventSchema = external_exports.object({ + agentId: external_exports.string().uuid().optional().nullable(), + issueId: external_exports.string().uuid().optional().nullable(), + projectId: external_exports.string().uuid().optional().nullable(), + goalId: external_exports.string().uuid().optional().nullable(), + heartbeatRunId: external_exports.string().uuid().optional().nullable(), + costEventId: external_exports.string().uuid().optional().nullable(), + billingCode: external_exports.string().optional().nullable(), + description: external_exports.string().max(500).optional().nullable(), + eventKind: external_exports.enum(FINANCE_EVENT_KINDS), + direction: external_exports.enum(FINANCE_DIRECTIONS).optional().default("debit"), + biller: external_exports.string().min(1), + provider: external_exports.string().min(1).optional().nullable(), + executionAdapterType: external_exports.enum(AGENT_ADAPTER_TYPES).optional().nullable(), + pricingTier: external_exports.string().min(1).optional().nullable(), + region: external_exports.string().min(1).optional().nullable(), + model: external_exports.string().min(1).optional().nullable(), + quantity: external_exports.number().int().nonnegative().optional().nullable(), + unit: external_exports.enum(FINANCE_UNITS).optional().nullable(), + amountCents: external_exports.number().int().nonnegative(), + currency: external_exports.string().length(3).optional().default("USD"), + estimated: external_exports.boolean().optional().default(false), + externalInvoiceId: external_exports.string().optional().nullable(), + metadataJson: external_exports.record(external_exports.string(), external_exports.unknown()).optional().nullable(), + occurredAt: external_exports.string().datetime() +}).transform((value) => ({ + ...value, + currency: value.currency.toUpperCase() +})); + +// packages/shared/src/validators/asset.ts +var createAssetImageMetadataSchema = external_exports.object({ + namespace: external_exports.string().trim().min(1).max(120).regex(/^[a-zA-Z0-9/_-]+$/).optional() +}); + +// packages/shared/src/validators/access.ts +var createCompanyInviteSchema = external_exports.object({ + allowedJoinTypes: external_exports.enum(INVITE_JOIN_TYPES).default("both"), + defaultsPayload: external_exports.record(external_exports.string(), external_exports.unknown()).optional().nullable(), + agentMessage: external_exports.string().max(4e3).optional().nullable() +}); +var createOpenClawInvitePromptSchema = external_exports.object({ + agentMessage: external_exports.string().max(4e3).optional().nullable() +}); +var acceptInviteSchema = external_exports.object({ + requestType: external_exports.enum(JOIN_REQUEST_TYPES), + agentName: external_exports.string().min(1).max(120).optional(), + adapterType: optionalAgentAdapterTypeSchema, + capabilities: external_exports.string().max(4e3).optional().nullable(), + agentDefaultsPayload: external_exports.record(external_exports.string(), external_exports.unknown()).optional().nullable(), + // OpenClaw join compatibility fields accepted at top level. + responsesWebhookUrl: external_exports.string().max(4e3).optional().nullable(), + responsesWebhookMethod: external_exports.string().max(32).optional().nullable(), + responsesWebhookHeaders: external_exports.record(external_exports.string(), external_exports.unknown()).optional().nullable(), + taskcoreApiUrl: external_exports.string().max(4e3).optional().nullable(), + webhookAuthHeader: external_exports.string().max(4e3).optional().nullable() +}); +var listJoinRequestsQuerySchema = external_exports.object({ + status: external_exports.enum(JOIN_REQUEST_STATUSES).optional(), + requestType: external_exports.enum(JOIN_REQUEST_TYPES).optional() +}); +var claimJoinRequestApiKeySchema = external_exports.object({ + claimSecret: external_exports.string().min(16).max(256) +}); +var boardCliAuthAccessLevelSchema = external_exports.enum([ + "board", + "instance_admin_required" +]); +var createCliAuthChallengeSchema = external_exports.object({ + command: external_exports.string().min(1).max(240), + clientName: external_exports.string().max(120).optional().nullable(), + requestedAccess: boardCliAuthAccessLevelSchema.default("board"), + requestedCompanyId: external_exports.string().uuid().optional().nullable() +}); +var resolveCliAuthChallengeSchema = external_exports.object({ + token: external_exports.string().min(16).max(256) +}); +var updateMemberPermissionsSchema = external_exports.object({ + grants: external_exports.array( + external_exports.object({ + permissionKey: external_exports.enum(PERMISSION_KEYS), + scope: external_exports.record(external_exports.string(), external_exports.unknown()).optional().nullable() + }) + ) +}); +var updateUserCompanyAccessSchema = external_exports.object({ + companyIds: external_exports.array(external_exports.string().uuid()).default([]) +}); + +// packages/shared/src/validators/plugin.ts +var jsonSchemaSchema = external_exports.record(external_exports.unknown()).refine( + (val) => { + if (Object.keys(val).length === 0) return true; + return typeof val.type === "string" || val.$ref !== void 0 || val.oneOf !== void 0 || val.anyOf !== void 0 || val.allOf !== void 0; + }, + { message: "Must be a valid JSON Schema object (requires at least a 'type', '$ref', or composition keyword)" } +); +var CRON_FIELD_PATTERN = /^(\*(?:\/[0-9]+)?|[0-9]+(?:-[0-9]+)?(?:\/[0-9]+)?)(?:,(\*(?:\/[0-9]+)?|[0-9]+(?:-[0-9]+)?(?:\/[0-9]+)?))*$/; +function isValidCronExpression(expression) { + const trimmed = expression.trim(); + if (!trimmed) return false; + const fields = trimmed.split(/\s+/); + if (fields.length !== 5) return false; + return fields.every((f5) => CRON_FIELD_PATTERN.test(f5)); +} +var pluginJobDeclarationSchema = external_exports.object({ + jobKey: external_exports.string().min(1), + displayName: external_exports.string().min(1), + description: external_exports.string().optional(), + schedule: external_exports.string().refine( + (val) => isValidCronExpression(val), + { message: "schedule must be a valid 5-field cron expression (e.g. '*/15 * * * *')" } + ).optional() +}); +var pluginWebhookDeclarationSchema = external_exports.object({ + endpointKey: external_exports.string().min(1), + displayName: external_exports.string().min(1), + description: external_exports.string().optional() +}); +var pluginToolDeclarationSchema = external_exports.object({ + name: external_exports.string().min(1), + displayName: external_exports.string().min(1), + description: external_exports.string().min(1), + parametersSchema: jsonSchemaSchema +}); +var pluginUiSlotDeclarationSchema = external_exports.object({ + type: external_exports.enum(PLUGIN_UI_SLOT_TYPES), + id: external_exports.string().min(1), + displayName: external_exports.string().min(1), + exportName: external_exports.string().min(1), + entityTypes: external_exports.array(external_exports.enum(PLUGIN_UI_SLOT_ENTITY_TYPES)).optional(), + routePath: external_exports.string().regex(/^[a-z0-9][a-z0-9-]*$/, { + message: "routePath must be a lowercase single-segment slug (letters, numbers, hyphens)" + }).optional(), + order: external_exports.number().int().optional() +}).superRefine((value, ctx) => { + const entityScopedTypes = ["detailTab", "taskDetailView", "contextMenuItem", "commentAnnotation", "commentContextMenuItem", "projectSidebarItem"]; + if (entityScopedTypes.includes(value.type) && (!value.entityTypes || value.entityTypes.length === 0)) { + ctx.addIssue({ + code: external_exports.ZodIssueCode.custom, + message: `${value.type} slots require at least one entityType`, + path: ["entityTypes"] + }); + } + if (value.type === "projectSidebarItem" && value.entityTypes && !value.entityTypes.includes("project")) { + ctx.addIssue({ + code: external_exports.ZodIssueCode.custom, + message: 'projectSidebarItem slots require entityTypes to include "project"', + path: ["entityTypes"] + }); + } + if (value.type === "commentAnnotation" && value.entityTypes && !value.entityTypes.includes("comment")) { + ctx.addIssue({ + code: external_exports.ZodIssueCode.custom, + message: 'commentAnnotation slots require entityTypes to include "comment"', + path: ["entityTypes"] + }); + } + if (value.type === "commentContextMenuItem" && value.entityTypes && !value.entityTypes.includes("comment")) { + ctx.addIssue({ + code: external_exports.ZodIssueCode.custom, + message: 'commentContextMenuItem slots require entityTypes to include "comment"', + path: ["entityTypes"] + }); + } + if (value.routePath && value.type !== "page") { + ctx.addIssue({ + code: external_exports.ZodIssueCode.custom, + message: "routePath is only supported for page slots", + path: ["routePath"] + }); + } + if (value.routePath && PLUGIN_RESERVED_COMPANY_ROUTE_SEGMENTS.includes(value.routePath)) { + ctx.addIssue({ + code: external_exports.ZodIssueCode.custom, + message: `routePath "${value.routePath}" is reserved by the host`, + path: ["routePath"] + }); + } +}); +var entityScopedLauncherPlacementZones = [ + "detailTab", + "taskDetailView", + "contextMenuItem", + "commentAnnotation", + "commentContextMenuItem", + "projectSidebarItem" +]; +var launcherBoundsByEnvironment = { + hostInline: ["inline", "compact", "default"], + hostOverlay: ["compact", "default", "wide", "full"], + hostRoute: ["default", "wide", "full"], + external: [], + iframe: ["compact", "default", "wide", "full"] +}; +var pluginLauncherActionDeclarationSchema = external_exports.object({ + type: external_exports.enum(PLUGIN_LAUNCHER_ACTIONS), + target: external_exports.string().min(1), + params: external_exports.record(external_exports.unknown()).optional() +}).superRefine((value, ctx) => { + if (value.type === "performAction" && value.target.includes("/")) { + ctx.addIssue({ + code: external_exports.ZodIssueCode.custom, + message: "performAction launchers must target an action key, not a route or URL", + path: ["target"] + }); + } + if (value.type === "navigate" && /^https?:\/\//.test(value.target)) { + ctx.addIssue({ + code: external_exports.ZodIssueCode.custom, + message: "navigate launchers must target a host route, not an absolute URL", + path: ["target"] + }); + } +}); +var pluginLauncherRenderDeclarationSchema = external_exports.object({ + environment: external_exports.enum(PLUGIN_LAUNCHER_RENDER_ENVIRONMENTS), + bounds: external_exports.enum(PLUGIN_LAUNCHER_BOUNDS).optional() +}).superRefine((value, ctx) => { + if (!value.bounds) { + return; + } + const supportedBounds = launcherBoundsByEnvironment[value.environment]; + if (!supportedBounds.includes(value.bounds)) { + ctx.addIssue({ + code: external_exports.ZodIssueCode.custom, + message: `bounds "${value.bounds}" is not supported for render environment "${value.environment}"`, + path: ["bounds"] + }); + } +}); +var pluginLauncherDeclarationSchema = external_exports.object({ + id: external_exports.string().min(1), + displayName: external_exports.string().min(1), + description: external_exports.string().optional(), + placementZone: external_exports.enum(PLUGIN_LAUNCHER_PLACEMENT_ZONES), + exportName: external_exports.string().min(1).optional(), + entityTypes: external_exports.array(external_exports.enum(PLUGIN_UI_SLOT_ENTITY_TYPES)).optional(), + order: external_exports.number().int().optional(), + action: pluginLauncherActionDeclarationSchema, + render: pluginLauncherRenderDeclarationSchema.optional() +}).superRefine((value, ctx) => { + if (entityScopedLauncherPlacementZones.some((zone) => zone === value.placementZone) && (!value.entityTypes || value.entityTypes.length === 0)) { + ctx.addIssue({ + code: external_exports.ZodIssueCode.custom, + message: `${value.placementZone} launchers require at least one entityType`, + path: ["entityTypes"] + }); + } + if (value.placementZone === "projectSidebarItem" && value.entityTypes && !value.entityTypes.includes("project")) { + ctx.addIssue({ + code: external_exports.ZodIssueCode.custom, + message: 'projectSidebarItem launchers require entityTypes to include "project"', + path: ["entityTypes"] + }); + } + if (value.action.type === "performAction" && value.render) { + ctx.addIssue({ + code: external_exports.ZodIssueCode.custom, + message: "performAction launchers cannot declare render hints", + path: ["render"] + }); + } + if (["openModal", "openDrawer", "openPopover"].includes(value.action.type) && !value.render) { + ctx.addIssue({ + code: external_exports.ZodIssueCode.custom, + message: `${value.action.type} launchers require render metadata`, + path: ["render"] + }); + } + if (value.action.type === "openModal" && value.render?.environment === "hostInline") { + ctx.addIssue({ + code: external_exports.ZodIssueCode.custom, + message: "openModal launchers cannot use the hostInline render environment", + path: ["render", "environment"] + }); + } + if (value.action.type === "openDrawer" && value.render && !["hostOverlay", "iframe"].includes(value.render.environment)) { + ctx.addIssue({ + code: external_exports.ZodIssueCode.custom, + message: "openDrawer launchers must use hostOverlay or iframe render environments", + path: ["render", "environment"] + }); + } + if (value.action.type === "openPopover" && value.render?.environment === "hostRoute") { + ctx.addIssue({ + code: external_exports.ZodIssueCode.custom, + message: "openPopover launchers cannot use the hostRoute render environment", + path: ["render", "environment"] + }); + } +}); +var pluginManifestV1Schema = external_exports.object({ + id: external_exports.string().min(1).regex( + /^[a-z0-9][a-z0-9._-]*$/, + "Plugin id must start with a lowercase alphanumeric and contain only lowercase letters, digits, dots, hyphens, or underscores" + ), + apiVersion: external_exports.literal(1), + version: external_exports.string().min(1).regex( + /^\d+\.\d+\.\d+(-[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?(\+[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?$/, + "Version must follow semver (e.g. 1.0.0 or 1.0.0-beta.1)" + ), + displayName: external_exports.string().min(1).max(100), + description: external_exports.string().min(1).max(500), + author: external_exports.string().min(1).max(200), + categories: external_exports.array(external_exports.enum(PLUGIN_CATEGORIES)).min(1), + minimumHostVersion: external_exports.string().regex( + /^\d+\.\d+\.\d+(-[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?(\+[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?$/, + "minimumHostVersion must follow semver (e.g. 1.0.0)" + ).optional(), + minimumTaskcoreVersion: external_exports.string().regex( + /^\d+\.\d+\.\d+(-[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?(\+[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?$/, + "minimumTaskcoreVersion must follow semver (e.g. 1.0.0)" + ).optional(), + capabilities: external_exports.array(external_exports.enum(PLUGIN_CAPABILITIES)).min(1), + entrypoints: external_exports.object({ + worker: external_exports.string().min(1), + ui: external_exports.string().min(1).optional() + }), + instanceConfigSchema: jsonSchemaSchema.optional(), + jobs: external_exports.array(pluginJobDeclarationSchema).optional(), + webhooks: external_exports.array(pluginWebhookDeclarationSchema).optional(), + tools: external_exports.array(pluginToolDeclarationSchema).optional(), + launchers: external_exports.array(pluginLauncherDeclarationSchema).optional(), + ui: external_exports.object({ + slots: external_exports.array(pluginUiSlotDeclarationSchema).min(1).optional(), + launchers: external_exports.array(pluginLauncherDeclarationSchema).optional() + }).optional() +}).superRefine((manifest, ctx) => { + const hasUiSlots = (manifest.ui?.slots?.length ?? 0) > 0; + const hasUiLaunchers = (manifest.ui?.launchers?.length ?? 0) > 0; + if ((hasUiSlots || hasUiLaunchers) && !manifest.entrypoints.ui) { + ctx.addIssue({ + code: external_exports.ZodIssueCode.custom, + message: "entrypoints.ui is required when ui.slots or ui.launchers are declared", + path: ["entrypoints", "ui"] + }); + } + if (manifest.minimumHostVersion && manifest.minimumTaskcoreVersion && manifest.minimumHostVersion !== manifest.minimumTaskcoreVersion) { + ctx.addIssue({ + code: external_exports.ZodIssueCode.custom, + message: "minimumHostVersion and minimumTaskcoreVersion must match when both are declared", + path: ["minimumHostVersion"] + }); + } + if (manifest.tools && manifest.tools.length > 0) { + if (!manifest.capabilities.includes("agent.tools.register")) { + ctx.addIssue({ + code: external_exports.ZodIssueCode.custom, + message: "Capability 'agent.tools.register' is required when tools are declared", + path: ["capabilities"] + }); + } + } + if (manifest.jobs && manifest.jobs.length > 0) { + if (!manifest.capabilities.includes("jobs.schedule")) { + ctx.addIssue({ + code: external_exports.ZodIssueCode.custom, + message: "Capability 'jobs.schedule' is required when jobs are declared", + path: ["capabilities"] + }); + } + } + if (manifest.webhooks && manifest.webhooks.length > 0) { + if (!manifest.capabilities.includes("webhooks.receive")) { + ctx.addIssue({ + code: external_exports.ZodIssueCode.custom, + message: "Capability 'webhooks.receive' is required when webhooks are declared", + path: ["capabilities"] + }); + } + } + if (manifest.jobs) { + const jobKeys = manifest.jobs.map((j5) => j5.jobKey); + const duplicates = jobKeys.filter((key, i5) => jobKeys.indexOf(key) !== i5); + if (duplicates.length > 0) { + ctx.addIssue({ + code: external_exports.ZodIssueCode.custom, + message: `Duplicate job keys: ${[...new Set(duplicates)].join(", ")}`, + path: ["jobs"] + }); + } + } + if (manifest.webhooks) { + const endpointKeys = manifest.webhooks.map((w5) => w5.endpointKey); + const duplicates = endpointKeys.filter((key, i5) => endpointKeys.indexOf(key) !== i5); + if (duplicates.length > 0) { + ctx.addIssue({ + code: external_exports.ZodIssueCode.custom, + message: `Duplicate webhook endpoint keys: ${[...new Set(duplicates)].join(", ")}`, + path: ["webhooks"] + }); + } + } + if (manifest.tools) { + const toolNames = manifest.tools.map((t5) => t5.name); + const duplicates = toolNames.filter((name, i5) => toolNames.indexOf(name) !== i5); + if (duplicates.length > 0) { + ctx.addIssue({ + code: external_exports.ZodIssueCode.custom, + message: `Duplicate tool names: ${[...new Set(duplicates)].join(", ")}`, + path: ["tools"] + }); + } + } + if (manifest.ui) { + if (manifest.ui.slots) { + const slotIds = manifest.ui.slots.map((s5) => s5.id); + const duplicates = slotIds.filter((id, i5) => slotIds.indexOf(id) !== i5); + if (duplicates.length > 0) { + ctx.addIssue({ + code: external_exports.ZodIssueCode.custom, + message: `Duplicate UI slot ids: ${[...new Set(duplicates)].join(", ")}`, + path: ["ui", "slots"] + }); + } + } + } + const allLaunchers = [ + ...manifest.launchers ?? [], + ...manifest.ui?.launchers ?? [] + ]; + if (allLaunchers.length > 0) { + const launcherIds = allLaunchers.map((launcher) => launcher.id); + const duplicates = launcherIds.filter((id, i5) => launcherIds.indexOf(id) !== i5); + if (duplicates.length > 0) { + ctx.addIssue({ + code: external_exports.ZodIssueCode.custom, + message: `Duplicate launcher ids: ${[...new Set(duplicates)].join(", ")}`, + path: manifest.ui?.launchers ? ["ui", "launchers"] : ["launchers"] + }); + } + } +}); +var installPluginSchema = external_exports.object({ + packageName: external_exports.string().min(1), + version: external_exports.string().min(1).optional(), + /** Set by loader for local-path installs so the worker can be resolved. */ + packagePath: external_exports.string().min(1).optional() +}); +var upsertPluginConfigSchema = external_exports.object({ + configJson: external_exports.record(external_exports.unknown()) +}); +var patchPluginConfigSchema = external_exports.object({ + configJson: external_exports.record(external_exports.unknown()) +}); +var updatePluginStatusSchema = external_exports.object({ + status: external_exports.enum(PLUGIN_STATUSES), + lastError: external_exports.string().nullable().optional() +}); +var uninstallPluginSchema = external_exports.object({ + removeData: external_exports.boolean().optional().default(false) +}); +var pluginStateScopeKeySchema = external_exports.object({ + scopeKind: external_exports.enum(PLUGIN_STATE_SCOPE_KINDS), + scopeId: external_exports.string().min(1).optional(), + namespace: external_exports.string().min(1).optional(), + stateKey: external_exports.string().min(1) +}); +var setPluginStateSchema = external_exports.object({ + scopeKind: external_exports.enum(PLUGIN_STATE_SCOPE_KINDS), + scopeId: external_exports.string().min(1).optional(), + namespace: external_exports.string().min(1).optional(), + stateKey: external_exports.string().min(1), + /** JSON-serializable value to store. */ + value: external_exports.unknown() +}); +var listPluginStateSchema = external_exports.object({ + scopeKind: external_exports.enum(PLUGIN_STATE_SCOPE_KINDS).optional(), + scopeId: external_exports.string().min(1).optional(), + namespace: external_exports.string().min(1).optional() +}); + +// packages/shared/src/api.ts +var API_PREFIX = "/api"; +var API = { + health: `${API_PREFIX}/health`, + companies: `${API_PREFIX}/companies`, + agents: `${API_PREFIX}/agents`, + projects: `${API_PREFIX}/projects`, + issues: `${API_PREFIX}/issues`, + goals: `${API_PREFIX}/goals`, + approvals: `${API_PREFIX}/approvals`, + secrets: `${API_PREFIX}/secrets`, + costs: `${API_PREFIX}/costs`, + activity: `${API_PREFIX}/activity`, + dashboard: `${API_PREFIX}/dashboard`, + sidebarBadges: `${API_PREFIX}/sidebar-badges`, + sidebarPreferences: `${API_PREFIX}/sidebar-preferences`, + invites: `${API_PREFIX}/invites`, + joinRequests: `${API_PREFIX}/join-requests`, + members: `${API_PREFIX}/members`, + admin: `${API_PREFIX}/admin` +}; + +// packages/shared/src/agent-url-key.ts +var AGENT_URL_KEY_DELIM_RE = /[^a-z0-9]+/g; +var AGENT_URL_KEY_TRIM_RE = /^-+|-+$/g; +var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i; +function isUuidLike(value) { + if (typeof value !== "string") return false; + return UUID_RE.test(value.trim()); +} +function normalizeAgentUrlKey(value) { + if (typeof value !== "string") return null; + const normalized = value.trim().toLowerCase().replace(AGENT_URL_KEY_DELIM_RE, "-").replace(AGENT_URL_KEY_TRIM_RE, ""); + return normalized.length > 0 ? normalized : null; +} +function deriveAgentUrlKey(name, fallback) { + return normalizeAgentUrlKey(name) ?? normalizeAgentUrlKey(fallback) ?? "agent"; +} + +// packages/shared/src/project-url-key.ts +var PROJECT_URL_KEY_DELIM_RE = /[^a-z0-9]+/g; +var PROJECT_URL_KEY_TRIM_RE = /^-+|-+$/g; +var NON_ASCII_RE = /[^\x00-\x7F]/; +var UUID_RE2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i; +function normalizeProjectUrlKey(value) { + if (typeof value !== "string") return null; + const normalized = value.trim().toLowerCase().replace(PROJECT_URL_KEY_DELIM_RE, "-").replace(PROJECT_URL_KEY_TRIM_RE, ""); + return normalized.length > 0 ? normalized : null; +} +function hasNonAsciiContent(value) { + if (typeof value !== "string") return false; + return NON_ASCII_RE.test(value); +} +function shortIdFromUuid(value) { + if (typeof value !== "string" || !UUID_RE2.test(value.trim())) return null; + return value.trim().replace(/-/g, "").slice(0, 8).toLowerCase(); +} +function deriveProjectUrlKey(name, fallback) { + const base = normalizeProjectUrlKey(name); + if (base && !hasNonAsciiContent(name)) return base; + const shortId = shortIdFromUuid(fallback); + if (base && shortId) return `${base}-${shortId}`; + if (shortId) return shortId; + return base ?? normalizeProjectUrlKey(fallback) ?? "project"; +} + +// packages/shared/src/project-mentions.ts +var PROJECT_MENTION_SCHEME = "project://"; +var AGENT_MENTION_SCHEME = "agent://"; +var SKILL_MENTION_SCHEME = "skill://"; +var HEX_COLOR_RE = /^[0-9a-f]{6}$/i; +var HEX_COLOR_SHORT_RE = /^[0-9a-f]{3}$/i; +var HEX_COLOR_WITH_HASH_RE = /^#[0-9a-f]{6}$/i; +var HEX_COLOR_SHORT_WITH_HASH_RE = /^#[0-9a-f]{3}$/i; +var PROJECT_MENTION_LINK_RE = /\[[^\]]*]\((project:\/\/[^)\s]+)\)/gi; +var AGENT_MENTION_LINK_RE = /\[[^\]]*]\((agent:\/\/[^)\s]+)\)/gi; +var SKILL_MENTION_LINK_RE = /\[[^\]]*]\((skill:\/\/[^)\s]+)\)/gi; +var AGENT_ICON_NAME_RE = /^[a-z0-9-]+$/i; +var SKILL_SLUG_RE = /^[a-z0-9][a-z0-9-]*$/i; +function normalizeHexColor(input) { + if (!input) return null; + const trimmed = input.trim(); + if (!trimmed) return null; + if (HEX_COLOR_WITH_HASH_RE.test(trimmed)) { + return trimmed.toLowerCase(); + } + if (HEX_COLOR_RE.test(trimmed)) { + return `#${trimmed.toLowerCase()}`; + } + if (HEX_COLOR_SHORT_WITH_HASH_RE.test(trimmed)) { + const raw = trimmed.slice(1).toLowerCase(); + return `#${raw[0]}${raw[0]}${raw[1]}${raw[1]}${raw[2]}${raw[2]}`; + } + if (HEX_COLOR_SHORT_RE.test(trimmed)) { + const raw = trimmed.toLowerCase(); + return `#${raw[0]}${raw[0]}${raw[1]}${raw[1]}${raw[2]}${raw[2]}`; + } + return null; +} +function parseProjectMentionHref(href) { + if (!href.startsWith(PROJECT_MENTION_SCHEME)) return null; + let url2; + try { + url2 = new URL(href); + } catch { + return null; + } + if (url2.protocol !== "project:") return null; + const projectId = `${url2.hostname}${url2.pathname}`.replace(/^\/+/, "").trim(); + if (!projectId) return null; + const color = normalizeHexColor(url2.searchParams.get("c") ?? url2.searchParams.get("color")); + return { + projectId, + color + }; +} +function parseAgentMentionHref(href) { + if (!href.startsWith(AGENT_MENTION_SCHEME)) return null; + let url2; + try { + url2 = new URL(href); + } catch { + return null; + } + if (url2.protocol !== "agent:") return null; + const agentId = `${url2.hostname}${url2.pathname}`.replace(/^\/+/, "").trim(); + if (!agentId) return null; + return { + agentId, + icon: normalizeAgentIcon(url2.searchParams.get("i") ?? url2.searchParams.get("icon")) + }; +} +function parseSkillMentionHref(href) { + if (!href.startsWith(SKILL_MENTION_SCHEME)) return null; + let url2; + try { + url2 = new URL(href); + } catch { + return null; + } + if (url2.protocol !== "skill:") return null; + const skillId = `${url2.hostname}${url2.pathname}`.replace(/^\/+/, "").trim(); + if (!skillId) return null; + return { + skillId, + slug: normalizeSkillSlug(url2.searchParams.get("s") ?? url2.searchParams.get("slug")) + }; +} +function extractProjectMentionIds(markdown) { + if (!markdown) return []; + const ids = /* @__PURE__ */ new Set(); + const re = new RegExp(PROJECT_MENTION_LINK_RE); + let match; + while ((match = re.exec(markdown)) !== null) { + const parsed = parseProjectMentionHref(match[1]); + if (parsed) ids.add(parsed.projectId); + } + return [...ids]; +} +function extractAgentMentionIds(markdown) { + if (!markdown) return []; + const ids = /* @__PURE__ */ new Set(); + const re = new RegExp(AGENT_MENTION_LINK_RE); + let match; + while ((match = re.exec(markdown)) !== null) { + const parsed = parseAgentMentionHref(match[1]); + if (parsed) ids.add(parsed.agentId); + } + return [...ids]; +} +function extractSkillMentionIds(markdown) { + if (!markdown) return []; + const ids = /* @__PURE__ */ new Set(); + const re = new RegExp(SKILL_MENTION_LINK_RE); + let match; + while ((match = re.exec(markdown)) !== null) { + const parsed = parseSkillMentionHref(match[1]); + if (parsed) ids.add(parsed.skillId); + } + return [...ids]; +} +function normalizeAgentIcon(input) { + if (!input) return null; + const trimmed = input.trim().toLowerCase(); + if (!trimmed || !AGENT_ICON_NAME_RE.test(trimmed)) return null; + return trimmed; +} +function normalizeSkillSlug(input) { + if (!input) return null; + const trimmed = input.trim().toLowerCase(); + if (!trimmed || !SKILL_SLUG_RE.test(trimmed)) return null; + return trimmed; +} + +// packages/shared/src/routine-variables.ts +var ROUTINE_VARIABLE_MATCHER = /\{\{\s*([A-Za-z][A-Za-z0-9_]*)\s*\}\}/g; +var BUILTIN_ROUTINE_VARIABLE_NAMES = /* @__PURE__ */ new Set(["date"]); +function isBuiltinRoutineVariable(name) { + return BUILTIN_ROUTINE_VARIABLE_NAMES.has(name); +} +function getBuiltinRoutineVariableValues() { + return { + date: (/* @__PURE__ */ new Date()).toISOString().slice(0, 10) + }; +} +function normalizeRoutineTemplateInput(input) { + const templates = Array.isArray(input) ? input : [input]; + return templates.filter((template) => typeof template === "string" && template.length > 0); +} +function extractRoutineVariableNames(template) { + const found = /* @__PURE__ */ new Set(); + for (const source of normalizeRoutineTemplateInput(template)) { + for (const match of source.matchAll(ROUTINE_VARIABLE_MATCHER)) { + const name = match[1]; + if (name && !found.has(name)) { + found.add(name); + } + } + } + return [...found]; +} +function defaultRoutineVariable(name) { + return { + name, + label: null, + type: "text", + defaultValue: null, + required: true, + options: [] + }; +} +function syncRoutineVariablesWithTemplate(template, existing) { + const names = extractRoutineVariableNames(template).filter((name) => !isBuiltinRoutineVariable(name)); + const existingByName = new Map((existing ?? []).map((variable) => [variable.name, variable])); + return names.map((name) => existingByName.get(name) ?? defaultRoutineVariable(name)); +} +function stringifyRoutineVariableValue(value) { + if (typeof value === "string") return value; + if (typeof value === "number" || typeof value === "boolean") return String(value); + if (value == null) return ""; + try { + return JSON.stringify(value); + } catch { + return String(value); + } +} +function interpolateRoutineTemplate(template, values2) { + if (template == null) return null; + if (!values2 || Object.keys(values2).length === 0) return template; + return template.replace(ROUTINE_VARIABLE_MATCHER, (match, rawName) => { + if (!(rawName in values2)) return match; + return stringifyRoutineVariableValue(values2[rawName]); + }); +} + +// packages/shared/src/config-schema.ts +var configMetaSchema = external_exports.object({ + version: external_exports.literal(1), + updatedAt: external_exports.string(), + source: external_exports.enum(["onboard", "configure", "doctor"]) +}); +var llmConfigSchema = external_exports.object({ + provider: external_exports.enum(["claude", "openai"]), + apiKey: external_exports.string().optional() +}); +var databaseBackupConfigSchema = external_exports.object({ + enabled: external_exports.boolean().default(true), + intervalMinutes: external_exports.number().int().min(1).max(7 * 24 * 60).default(60), + retentionDays: external_exports.number().int().min(1).max(3650).default(7), + dir: external_exports.string().default("~/.taskcore/instances/default/data/backups") +}); +var databaseConfigSchema = external_exports.object({ + mode: external_exports.enum(["embedded-postgres", "postgres"]).default("embedded-postgres"), + connectionString: external_exports.string().optional(), + embeddedPostgresDataDir: external_exports.string().default("~/.taskcore/instances/default/db"), + embeddedPostgresPort: external_exports.number().int().min(1).max(65535).default(54329), + backup: databaseBackupConfigSchema.default({ + enabled: true, + intervalMinutes: 60, + retentionDays: 7, + dir: "~/.taskcore/instances/default/data/backups" + }) +}); +var loggingConfigSchema = external_exports.object({ + mode: external_exports.enum(["file", "cloud"]), + logDir: external_exports.string().default("~/.taskcore/instances/default/logs") +}); +var serverConfigSchema = external_exports.object({ + deploymentMode: external_exports.enum(DEPLOYMENT_MODES).default("local_trusted"), + exposure: external_exports.enum(DEPLOYMENT_EXPOSURES).default("private"), + bind: external_exports.enum(BIND_MODES).optional(), + customBindHost: external_exports.string().optional(), + host: external_exports.string().default("127.0.0.1"), + port: external_exports.number().int().min(1).max(65535).default(3100), + allowedHostnames: external_exports.array(external_exports.string().min(1)).default([]), + serveUi: external_exports.boolean().default(true) +}); +var authConfigSchema = external_exports.object({ + baseUrlMode: external_exports.enum(AUTH_BASE_URL_MODES).default("auto"), + publicBaseUrl: external_exports.string().url().optional(), + disableSignUp: external_exports.boolean().default(false) +}); +var storageLocalDiskConfigSchema = external_exports.object({ + baseDir: external_exports.string().default("~/.taskcore/instances/default/data/storage") +}); +var storageS3ConfigSchema = external_exports.object({ + bucket: external_exports.string().min(1).default("taskcore"), + region: external_exports.string().min(1).default("us-east-1"), + endpoint: external_exports.string().optional(), + prefix: external_exports.string().default(""), + forcePathStyle: external_exports.boolean().default(false) +}); +var storageConfigSchema = external_exports.object({ + provider: external_exports.enum(STORAGE_PROVIDERS).default("local_disk"), + localDisk: storageLocalDiskConfigSchema.default({ + baseDir: "~/.taskcore/instances/default/data/storage" + }), + s3: storageS3ConfigSchema.default({ + bucket: "taskcore", + region: "us-east-1", + prefix: "", + forcePathStyle: false + }) +}); +var secretsLocalEncryptedConfigSchema = external_exports.object({ + keyFilePath: external_exports.string().default("~/.taskcore/instances/default/secrets/master.key") +}); +var secretsConfigSchema = external_exports.object({ + provider: external_exports.enum(SECRET_PROVIDERS).default("local_encrypted"), + strictMode: external_exports.boolean().default(false), + localEncrypted: secretsLocalEncryptedConfigSchema.default({ + keyFilePath: "~/.taskcore/instances/default/secrets/master.key" + }) +}); +var telemetryConfigSchema = external_exports.object({ + enabled: external_exports.boolean().default(true) +}).default({}); +var taskcoreConfigSchema = external_exports.object({ + $meta: configMetaSchema, + llm: llmConfigSchema.optional(), + database: databaseConfigSchema, + logging: loggingConfigSchema, + server: serverConfigSchema, + telemetry: telemetryConfigSchema, + auth: authConfigSchema.default({ + baseUrlMode: "auto", + disableSignUp: false + }), + storage: storageConfigSchema.default({ + provider: "local_disk", + localDisk: { + baseDir: "~/.taskcore/instances/default/data/storage" + }, + s3: { + bucket: "taskcore", + region: "us-east-1", + prefix: "", + forcePathStyle: false + } + }), + secrets: secretsConfigSchema.default({ + provider: "local_encrypted", + strictMode: false, + localEncrypted: { + keyFilePath: "~/.taskcore/instances/default/secrets/master.key" + } + }) +}).superRefine((value, ctx) => { + if (value.server.deploymentMode === "local_trusted" && value.server.exposure !== "private") { + ctx.addIssue({ + code: external_exports.ZodIssueCode.custom, + message: "server.exposure must be private when deploymentMode is local_trusted", + path: ["server", "exposure"] + }); + } + for (const message2 of validateConfiguredBindMode({ + deploymentMode: value.server.deploymentMode, + deploymentExposure: value.server.exposure, + bind: value.server.bind, + host: value.server.host, + customBindHost: value.server.customBindHost + })) { + ctx.addIssue({ + code: external_exports.ZodIssueCode.custom, + message: message2, + path: message2.includes("customBindHost") ? ["server", "customBindHost"] : ["server", "bind"] + }); + } + if (value.auth.baseUrlMode === "explicit" && !value.auth.publicBaseUrl) { + ctx.addIssue({ + code: external_exports.ZodIssueCode.custom, + message: "auth.publicBaseUrl is required when auth.baseUrlMode is explicit", + path: ["auth", "publicBaseUrl"] + }); + } + if (value.server.exposure === "public" && value.auth.baseUrlMode !== "explicit") { + ctx.addIssue({ + code: external_exports.ZodIssueCode.custom, + message: "auth.baseUrlMode must be explicit when deploymentMode=authenticated and exposure=public", + path: ["auth", "baseUrlMode"] + }); + } + if (value.server.exposure === "public" && !value.auth.publicBaseUrl) { + ctx.addIssue({ + code: external_exports.ZodIssueCode.custom, + message: "auth.publicBaseUrl is required when deploymentMode=authenticated and exposure=public", + path: ["auth", "publicBaseUrl"] + }); + } +}); + +// server/src/paths.ts +import fs2 from "node:fs"; +import path2 from "node:path"; + +// server/src/home-paths.ts +import os2 from "node:os"; +import path from "node:path"; +var DEFAULT_INSTANCE_ID = "default"; +var INSTANCE_ID_RE = /^[a-zA-Z0-9_-]+$/; +var PATH_SEGMENT_RE = /^[a-zA-Z0-9_-]+$/; +var FRIENDLY_PATH_SEGMENT_RE = /[^a-zA-Z0-9._-]+/g; +function expandHomePrefix(value) { + if (value === "~") return os2.homedir(); + if (value.startsWith("~/")) return path.resolve(os2.homedir(), value.slice(2)); + return value; +} +function resolveTaskcoreHomeDir() { + const envHome = process.env.TASKCORE_HOME?.trim(); + if (envHome) return path.resolve(expandHomePrefix(envHome)); + return path.resolve(os2.homedir(), ".taskcore"); +} +function resolveTaskcoreInstanceId() { + const raw = process.env.TASKCORE_INSTANCE_ID?.trim() || DEFAULT_INSTANCE_ID; + if (!INSTANCE_ID_RE.test(raw)) { + throw new Error(`Invalid TASKCORE_INSTANCE_ID '${raw}'.`); + } + return raw; +} +function resolveTaskcoreInstanceRoot() { + return path.resolve(resolveTaskcoreHomeDir(), "instances", resolveTaskcoreInstanceId()); +} +function resolveDefaultConfigPath() { + return path.resolve(resolveTaskcoreInstanceRoot(), "config.json"); +} +function resolveDefaultEmbeddedPostgresDir() { + return path.resolve(resolveTaskcoreInstanceRoot(), "db"); +} +function resolveDefaultLogsDir() { + return path.resolve(resolveTaskcoreInstanceRoot(), "logs"); +} +function resolveDefaultSecretsKeyFilePath() { + return path.resolve(resolveTaskcoreInstanceRoot(), "secrets", "master.key"); +} +function resolveDefaultStorageDir() { + return path.resolve(resolveTaskcoreInstanceRoot(), "data", "storage"); +} +function resolveDefaultBackupDir() { + return path.resolve(resolveTaskcoreInstanceRoot(), "data", "backups"); +} +function resolveDefaultAgentWorkspaceDir(agentId) { + const trimmed = agentId.trim(); + if (!PATH_SEGMENT_RE.test(trimmed)) { + throw new Error(`Invalid agent id for workspace path '${agentId}'.`); + } + return path.resolve(resolveTaskcoreInstanceRoot(), "workspaces", trimmed); +} +function sanitizeFriendlyPathSegment(value, fallback = "_default") { + const trimmed = value?.trim() ?? ""; + if (!trimmed) return fallback; + const sanitized = trimmed.replace(FRIENDLY_PATH_SEGMENT_RE, "-").replace(/^-+|-+$/g, ""); + return sanitized || fallback; +} +function resolveManagedProjectWorkspaceDir(input) { + const companyId = input.companyId.trim(); + const projectId = input.projectId.trim(); + if (!companyId || !projectId) { + throw new Error("Managed project workspace path requires companyId and projectId."); + } + return path.resolve( + resolveTaskcoreInstanceRoot(), + "projects", + sanitizeFriendlyPathSegment(companyId, "company"), + sanitizeFriendlyPathSegment(projectId, "project"), + sanitizeFriendlyPathSegment(input.repoName, "_default") + ); +} +function resolveHomeAwarePath(value) { + return path.resolve(expandHomePrefix(value)); +} + +// server/src/paths.ts +var TASKCORE_CONFIG_BASENAME = "config.json"; +var TASKCORE_ENV_FILENAME = ".env"; +function findConfigFileFromAncestors(startDir) { + const absoluteStartDir = path2.resolve(startDir); + let currentDir = absoluteStartDir; + while (true) { + const candidate = path2.resolve(currentDir, ".taskcore", TASKCORE_CONFIG_BASENAME); + if (fs2.existsSync(candidate)) { + return candidate; + } + const nextDir = path2.resolve(currentDir, ".."); + if (nextDir === currentDir) break; + currentDir = nextDir; + } + return null; +} +function resolveTaskcoreConfigPath(overridePath) { + if (overridePath) return path2.resolve(overridePath); + if (process.env.TASKCORE_CONFIG) return path2.resolve(process.env.TASKCORE_CONFIG); + return findConfigFileFromAncestors(process.cwd()) ?? resolveDefaultConfigPath(); +} +function resolveTaskcoreEnvPath(overrideConfigPath) { + return path2.resolve(path2.dirname(resolveTaskcoreConfigPath(overrideConfigPath)), TASKCORE_ENV_FILENAME); +} + +// server/src/config-file.ts +function readConfigFile() { + const configPath = resolveTaskcoreConfigPath(); + if (!fs3.existsSync(configPath)) return null; + try { + const raw = JSON.parse(fs3.readFileSync(configPath, "utf-8")); + return taskcoreConfigSchema.parse(raw); + } catch { + return null; + } +} + +// server/src/middleware/http-log-policy.ts +var SILENCED_SUCCESS_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD"]); +var SILENCED_SUCCESS_API_PATHS = [ + /^\/api\/health(?:\/|$)/, + /^\/api\/companies\/[^/]+\/activity(?:\/|$)/, + /^\/api\/companies\/[^/]+\/dashboard(?:\/|$)/, + /^\/api\/companies\/[^/]+\/heartbeat-runs(?:\/|$)/, + /^\/api\/companies\/[^/]+\/issues(?:\/|$)/, + /^\/api\/companies\/[^/]+\/live-runs(?:\/|$)/, + /^\/api\/companies\/[^/]+\/sidebar-badges(?:\/|$)/, + /^\/api\/heartbeat-runs\/[^/]+\/log(?:\/|$)/ +]; +var SILENCED_SUCCESS_STATIC_PREFIXES = [ + "/@fs/", + "/@id/", + "/@react-refresh", + "/@vite/", + "/_plugins/", + "/assets/", + "/node_modules/", + "/src/" +]; +var SILENCED_SUCCESS_STATIC_PATHS = /* @__PURE__ */ new Set([ + "/favicon.ico", + "/site.webmanifest" +]); +function normalizePath(url2) { + const trimmed = url2.trim(); + if (trimmed.length === 0) return "/"; + const pathname = trimmed.split("?")[0]?.trim() ?? "/"; + return pathname.length > 0 ? pathname : "/"; +} +function shouldSilenceHttpSuccessLog(method, url2, statusCode) { + if (statusCode >= 400) return false; + if (statusCode === 304) return true; + if (!method || !url2) return false; + if (!SILENCED_SUCCESS_METHODS.has(method.toUpperCase())) return false; + const pathname = normalizePath(url2); + if (SILENCED_SUCCESS_STATIC_PATHS.has(pathname)) return true; + if (SILENCED_SUCCESS_STATIC_PREFIXES.some((prefix) => pathname.startsWith(prefix))) return true; + return SILENCED_SUCCESS_API_PATHS.some((pattern) => pattern.test(pathname)); +} + +// server/src/middleware/logger.ts +function isServerlessRuntime() { + return process.env.VERCEL === "1" || process.env.NOW === "1"; +} +function resolveServerLogDir() { + const envOverride = process.env.TASKCORE_LOG_DIR?.trim(); + if (envOverride) return resolveHomeAwarePath(envOverride); + const fileLogDir = readConfigFile()?.logging.logDir?.trim(); + if (fileLogDir) return resolveHomeAwarePath(fileLogDir); + return resolveDefaultLogsDir(); +} +var logDir = resolveServerLogDir(); +var sharedOpts = { + translateTime: "SYS:HH:MM:ss", + ignore: "pid,hostname", + singleLine: true +}; +var logger = isServerlessRuntime() ? (0, import_pino.default)({ + level: process.env.LOG_LEVEL?.trim() || "info", + redact: ["req.headers.authorization"] +}) : (0, import_pino.default)({ + level: "debug", + redact: ["req.headers.authorization"] +}, import_pino.default.transport({ + targets: [ + { + target: "pino-pretty", + options: { ...sharedOpts, ignore: "pid,hostname,req,res,responseTime", colorize: true, destination: 1 }, + level: "info" + }, + { + target: "pino-pretty", + options: { ...sharedOpts, colorize: false, destination: path3.join(logDir, "server.log"), mkdir: true }, + level: "debug" + } + ] +})); +var httpLogger = (0, import_pino_http.pinoHttp)({ + logger, + customLogLevel(_req, res, err) { + if (shouldSilenceHttpSuccessLog(_req.method, _req.url, res.statusCode)) { + return "silent"; + } + if (err || res.statusCode >= 500) return "error"; + if (res.statusCode >= 400) return "warn"; + return "info"; + }, + customSuccessMessage(req, res) { + return `${req.method} ${req.url} ${res.statusCode}`; + }, + customErrorMessage(req, res, err) { + const ctx = res.__errorContext; + const errMsg = ctx?.error?.message || err?.message || res.err?.message || "unknown error"; + return `${req.method} ${req.url} ${res.statusCode} \u2014 ${errMsg}`; + }, + customProps(req, res) { + if (res.statusCode >= 400) { + const ctx = res.__errorContext; + if (ctx) { + return { + errorContext: ctx.error, + reqBody: ctx.reqBody, + reqParams: ctx.reqParams, + reqQuery: ctx.reqQuery + }; + } + const props = {}; + const { body, params, query } = req; + if (body && typeof body === "object" && Object.keys(body).length > 0) { + props.reqBody = body; + } + if (params && typeof params === "object" && Object.keys(params).length > 0) { + props.reqParams = params; + } + if (query && typeof query === "object" && Object.keys(query).length > 0) { + props.reqQuery = query; + } + if (req.route?.path) { + props.routePath = req.route.path; + } + return props; + } + return {}; + } +}); + +// server/src/errors.ts +var HttpError = class extends Error { + status; + details; + constructor(status, message2, details) { + super(message2); + this.status = status; + this.details = details; + } +}; +function badRequest(message2, details) { + return new HttpError(400, message2, details); +} +function unauthorized(message2 = "Unauthorized") { + return new HttpError(401, message2); +} +function forbidden(message2 = "Forbidden") { + return new HttpError(403, message2); +} +function notFound(message2 = "Not found") { + return new HttpError(404, message2); +} +function conflict(message2, details) { + return new HttpError(409, message2, details); +} +function unprocessable(message2, details) { + return new HttpError(422, message2, details); +} + +// packages/shared/src/telemetry/events.ts +function trackProjectCreated(client2) { + client2.track("project.created"); +} +function trackRoutineCreated(client2) { + client2.track("routine.created"); +} +function trackRoutineRun(client2, dims) { + client2.track("routine.run", { + source: dims.source, + status: dims.status + }); +} +function trackGoalCreated(client2, dims) { + client2.track("goal.created", dims?.goalLevel ? { goal_level: dims.goalLevel } : void 0); +} +function trackAgentCreated(client2, dims) { + client2.track("agent.created", { + agent_role: dims.agentRole, + ...dims.agentId ? { agent_id: dims.agentId } : {} + }); +} +function trackSkillImported(client2, dims) { + client2.track("skill.imported", { + source_type: dims.sourceType, + ...dims.skillRef ? { skill_ref: dims.skillRef } : {} + }); +} +function trackAgentFirstHeartbeat(client2, dims) { + client2.track("agent.first_heartbeat", { + agent_role: dims.agentRole, + ...dims.agentId ? { agent_id: dims.agentId } : {} + }); +} +function trackAgentTaskCompleted(client2, dims) { + client2.track("agent.task_completed", { + agent_role: dims.agentRole, + ...dims.agentId ? { agent_id: dims.agentId } : {}, + ...dims.adapterType ? { adapter_type: dims.adapterType } : {}, + ...dims.model ? { model: dims.model } : {} + }); +} +function trackErrorHandlerCrash(client2, dims) { + client2.track("error.handler_crash", { error_code: dims.errorCode }); +} + +// server/src/version.ts +import { createRequire } from "node:module"; +var require2 = createRequire(import.meta.url); +var pkg = require2("../package.json"); +var serverVersion = pkg.version ?? "0.0.0"; + +// server/src/telemetry.ts +var client = null; +function getTelemetryClient() { + return client; +} + +// server/src/middleware/error-handler.ts +function attachErrorContext(req, res, payload2, rawError) { + res.__errorContext = { + error: payload2, + method: req.method, + url: req.originalUrl, + reqBody: req.body, + reqParams: req.params, + reqQuery: req.query + }; + if (rawError) { + res.err = rawError; + } +} +function errorHandler(err, req, res, _next) { + if (err instanceof HttpError) { + if (err.status >= 500) { + attachErrorContext( + req, + res, + { message: err.message, stack: err.stack, name: err.name, details: err.details }, + err + ); + const tc2 = getTelemetryClient(); + if (tc2) trackErrorHandlerCrash(tc2, { errorCode: err.name }); + } + res.status(err.status).json({ + error: err.message, + ...err.details ? { details: err.details } : {} + }); + return; + } + if (err instanceof ZodError) { + res.status(400).json({ error: "Validation error", details: err.errors }); + return; + } + const rootError = err instanceof Error ? err : new Error(String(err)); + attachErrorContext( + req, + res, + err instanceof Error ? { message: err.message, stack: err.stack, name: err.name } : { message: String(err), raw: err, stack: rootError.stack, name: rootError.name }, + rootError + ); + const tc = getTelemetryClient(); + if (tc) trackErrorHandlerCrash(tc, { errorCode: rootError.name }); + res.status(500).json({ error: "Internal server error" }); +} + +// server/src/middleware/validate.ts +function validate(schema2) { + return (req, _res, next) => { + req.body = schema2.parse(req.body); + next(); + }; +} + +// server/src/middleware/auth.ts +init_drizzle_orm(); +init_src2(); +import { createHash as createHash2 } from "node:crypto"; + +// server/src/agent-auth-jwt.ts +import { createHmac, timingSafeEqual } from "node:crypto"; +var JWT_ALGORITHM = "HS256"; +function parseNumber(value, fallback) { + const parsed = Number(value); + if (!Number.isFinite(parsed) || parsed <= 0) return fallback; + return Math.floor(parsed); +} +function jwtConfig() { + const secret = process.env.TASKCORE_AGENT_JWT_SECRET?.trim() || process.env.BETTER_AUTH_SECRET?.trim(); + if (!secret) return null; + return { + secret, + ttlSeconds: parseNumber(process.env.TASKCORE_AGENT_JWT_TTL_SECONDS, 60 * 60 * 48), + issuer: process.env.TASKCORE_AGENT_JWT_ISSUER ?? "taskcore", + audience: process.env.TASKCORE_AGENT_JWT_AUDIENCE ?? "taskcore-api" + }; +} +function base64UrlEncode(value) { + return Buffer.from(value, "utf8").toString("base64url"); +} +function base64UrlDecode(value) { + return Buffer.from(value, "base64url").toString("utf8"); +} +function signPayload(secret, signingInput) { + return createHmac("sha256", secret).update(signingInput).digest("base64url"); +} +function parseJson(value) { + try { + const parsed = JSON.parse(value); + return parsed && typeof parsed === "object" ? parsed : null; + } catch { + return null; + } +} +function safeCompare(a5, b6) { + const left = Buffer.from(a5); + const right = Buffer.from(b6); + if (left.length !== right.length) return false; + return timingSafeEqual(left, right); +} +function createLocalAgentJwt(agentId, companyId, adapterType, runId) { + const config3 = jwtConfig(); + if (!config3) return null; + const now2 = Math.floor(Date.now() / 1e3); + const claims = { + sub: agentId, + company_id: companyId, + adapter_type: adapterType, + run_id: runId, + iat: now2, + exp: now2 + config3.ttlSeconds, + iss: config3.issuer, + aud: config3.audience + }; + const header = { + alg: JWT_ALGORITHM, + typ: "JWT" + }; + const signingInput = `${base64UrlEncode(JSON.stringify(header))}.${base64UrlEncode(JSON.stringify(claims))}`; + const signature = signPayload(config3.secret, signingInput); + return `${signingInput}.${signature}`; +} +function verifyLocalAgentJwt(token) { + if (!token) return null; + const config3 = jwtConfig(); + if (!config3) return null; + const parts = token.split("."); + if (parts.length !== 3) return null; + const [headerB64, claimsB64, signature] = parts; + const header = parseJson(base64UrlDecode(headerB64)); + if (!header || header.alg !== JWT_ALGORITHM) return null; + const signingInput = `${headerB64}.${claimsB64}`; + const expectedSig = signPayload(config3.secret, signingInput); + if (!safeCompare(signature, expectedSig)) return null; + const claims = parseJson(base64UrlDecode(claimsB64)); + if (!claims) return null; + const sub = typeof claims.sub === "string" ? claims.sub : null; + const companyId = typeof claims.company_id === "string" ? claims.company_id : null; + const adapterType = typeof claims.adapter_type === "string" ? claims.adapter_type : null; + const runId = typeof claims.run_id === "string" ? claims.run_id : null; + const iat = typeof claims.iat === "number" ? claims.iat : null; + const exp = typeof claims.exp === "number" ? claims.exp : null; + if (!sub || !companyId || !adapterType || !runId || !iat || !exp) return null; + const now2 = Math.floor(Date.now() / 1e3); + if (exp < now2) return null; + const issuer = typeof claims.iss === "string" ? claims.iss : void 0; + const audience = typeof claims.aud === "string" ? claims.aud : void 0; + if (issuer && issuer !== config3.issuer) return null; + if (audience && audience !== config3.audience) return null; + return { + sub, + company_id: companyId, + adapter_type: adapterType, + run_id: runId, + iat, + exp, + ...issuer ? { iss: issuer } : {}, + ...audience ? { aud: audience } : {}, + jti: typeof claims.jti === "string" ? claims.jti : void 0 + }; +} + +// server/src/services/board-auth.ts +init_drizzle_orm(); +init_src2(); +import { createHash, randomBytes, timingSafeEqual as timingSafeEqual2 } from "node:crypto"; +var BOARD_API_KEY_TTL_MS = 30 * 24 * 60 * 60 * 1e3; +var CLI_AUTH_CHALLENGE_TTL_MS = 10 * 60 * 1e3; +function hashBearerToken(token) { + return createHash("sha256").update(token).digest("hex"); +} +function tokenHashesMatch(left, right) { + const leftBytes = Buffer.from(left, "utf8"); + const rightBytes = Buffer.from(right, "utf8"); + return leftBytes.length === rightBytes.length && timingSafeEqual2(leftBytes, rightBytes); +} +function createBoardApiToken() { + return `pcp_board_${randomBytes(24).toString("hex")}`; +} +function createCliAuthSecret() { + return `pcp_cli_auth_${randomBytes(24).toString("hex")}`; +} +function boardApiKeyExpiresAt(nowMs = Date.now()) { + return new Date(nowMs + BOARD_API_KEY_TTL_MS); +} +function cliAuthChallengeExpiresAt(nowMs = Date.now()) { + return new Date(nowMs + CLI_AUTH_CHALLENGE_TTL_MS); +} +function challengeStatusForRow(row) { + if (row.cancelledAt) return "cancelled"; + if (row.expiresAt.getTime() <= Date.now()) return "expired"; + if (row.approvedAt && row.boardApiKeyId) return "approved"; + return "pending"; +} +function boardAuthService(db) { + async function resolveBoardAccess(userId) { + const [user, memberships, adminRole] = await Promise.all([ + db.select({ + id: authUsers.id, + name: authUsers.name, + email: authUsers.email + }).from(authUsers).where(eq(authUsers.id, userId)).then((rows) => rows[0] ?? null), + db.select({ companyId: companyMemberships.companyId }).from(companyMemberships).where( + and( + eq(companyMemberships.principalType, "user"), + eq(companyMemberships.principalId, userId), + eq(companyMemberships.status, "active") + ) + ).then((rows) => rows.map((row) => row.companyId)), + db.select({ id: instanceUserRoles.id }).from(instanceUserRoles).where(and(eq(instanceUserRoles.userId, userId), eq(instanceUserRoles.role, "instance_admin"))).then((rows) => rows[0] ?? null) + ]); + return { + user, + companyIds: memberships, + isInstanceAdmin: Boolean(adminRole) + }; + } + async function resolveBoardActivityCompanyIds(input) { + const access = await resolveBoardAccess(input.userId); + const companyIds = new Set(access.companyIds); + if (companyIds.size === 0 && input.requestedCompanyId?.trim()) { + companyIds.add(input.requestedCompanyId.trim()); + } + if (companyIds.size === 0 && input.boardApiKeyId?.trim()) { + const challengeCompanyIds = await db.select({ requestedCompanyId: cliAuthChallenges.requestedCompanyId }).from(cliAuthChallenges).where(eq(cliAuthChallenges.boardApiKeyId, input.boardApiKeyId.trim())).then( + (rows) => rows.map((row) => row.requestedCompanyId?.trim() ?? null).filter((value) => Boolean(value)) + ); + for (const companyId of challengeCompanyIds) { + companyIds.add(companyId); + } + } + if (companyIds.size === 0 && access.isInstanceAdmin) { + const allCompanyIds = await db.select({ id: companies.id }).from(companies).then((rows) => rows.map((row) => row.id)); + for (const companyId of allCompanyIds) { + companyIds.add(companyId); + } + } + return Array.from(companyIds); + } + async function findBoardApiKeyByToken(token) { + const tokenHash = hashBearerToken(token); + const now2 = /* @__PURE__ */ new Date(); + return db.select().from(boardApiKeys).where( + and( + eq(boardApiKeys.keyHash, tokenHash), + isNull(boardApiKeys.revokedAt) + ) + ).then((rows) => rows.find((row) => !row.expiresAt || row.expiresAt.getTime() > now2.getTime()) ?? null); + } + async function touchBoardApiKey(id) { + await db.update(boardApiKeys).set({ lastUsedAt: /* @__PURE__ */ new Date() }).where(eq(boardApiKeys.id, id)); + } + async function revokeBoardApiKey(id) { + const now2 = /* @__PURE__ */ new Date(); + return db.update(boardApiKeys).set({ revokedAt: now2, lastUsedAt: now2 }).where(and(eq(boardApiKeys.id, id), isNull(boardApiKeys.revokedAt))).returning().then((rows) => rows[0] ?? null); + } + async function createCliAuthChallenge(input) { + const challengeSecret = createCliAuthSecret(); + const pendingBoardToken = createBoardApiToken(); + const expiresAt = cliAuthChallengeExpiresAt(); + const labelBase = input.clientName?.trim() || "taskcore cli"; + const pendingKeyName = input.requestedAccess === "instance_admin_required" ? `${labelBase} (instance admin)` : `${labelBase} (board)`; + const created = await db.insert(cliAuthChallenges).values({ + secretHash: hashBearerToken(challengeSecret), + command: input.command.trim(), + clientName: input.clientName?.trim() || null, + requestedAccess: input.requestedAccess, + requestedCompanyId: input.requestedCompanyId?.trim() || null, + pendingKeyHash: hashBearerToken(pendingBoardToken), + pendingKeyName, + expiresAt + }).returning().then((rows) => rows[0]); + return { + challenge: created, + challengeSecret, + pendingBoardToken + }; + } + async function getCliAuthChallenge(id) { + return db.select().from(cliAuthChallenges).where(eq(cliAuthChallenges.id, id)).then((rows) => rows[0] ?? null); + } + async function getCliAuthChallengeBySecret(id, token) { + const challenge = await getCliAuthChallenge(id); + if (!challenge) return null; + if (!tokenHashesMatch(challenge.secretHash, hashBearerToken(token))) return null; + return challenge; + } + async function describeCliAuthChallenge(id, token) { + const challenge = await getCliAuthChallengeBySecret(id, token); + if (!challenge) return null; + const [company, approvedBy] = await Promise.all([ + challenge.requestedCompanyId ? db.select({ id: companies.id, name: companies.name }).from(companies).where(eq(companies.id, challenge.requestedCompanyId)).then((rows) => rows[0] ?? null) : Promise.resolve(null), + challenge.approvedByUserId ? db.select({ id: authUsers.id, name: authUsers.name, email: authUsers.email }).from(authUsers).where(eq(authUsers.id, challenge.approvedByUserId)).then((rows) => rows[0] ?? null) : Promise.resolve(null) + ]); + return { + id: challenge.id, + status: challengeStatusForRow(challenge), + command: challenge.command, + clientName: challenge.clientName ?? null, + requestedAccess: challenge.requestedAccess, + requestedCompanyId: challenge.requestedCompanyId ?? null, + requestedCompanyName: company?.name ?? null, + approvedAt: challenge.approvedAt?.toISOString() ?? null, + cancelledAt: challenge.cancelledAt?.toISOString() ?? null, + expiresAt: challenge.expiresAt.toISOString(), + approvedByUser: approvedBy ? { + id: approvedBy.id, + name: approvedBy.name, + email: approvedBy.email + } : null + }; + } + async function approveCliAuthChallenge(id, token, userId) { + const access = await resolveBoardAccess(userId); + return db.transaction(async (tx) => { + await tx.execute( + sql`select ${cliAuthChallenges.id} from ${cliAuthChallenges} where ${cliAuthChallenges.id} = ${id} for update` + ); + const challenge = await tx.select().from(cliAuthChallenges).where(eq(cliAuthChallenges.id, id)).then((rows) => rows[0] ?? null); + if (!challenge || !tokenHashesMatch(challenge.secretHash, hashBearerToken(token))) { + throw notFound("CLI auth challenge not found"); + } + const status = challengeStatusForRow(challenge); + if (status === "expired") return { status, challenge }; + if (status === "cancelled") return { status, challenge }; + if (challenge.requestedAccess === "instance_admin_required" && !access.isInstanceAdmin) { + throw forbidden("Instance admin required"); + } + let boardKeyId = challenge.boardApiKeyId; + if (!boardKeyId) { + const createdKey = await tx.insert(boardApiKeys).values({ + userId, + name: challenge.pendingKeyName, + keyHash: challenge.pendingKeyHash, + expiresAt: boardApiKeyExpiresAt() + }).returning().then((rows) => rows[0]); + boardKeyId = createdKey.id; + } + const approvedAt = challenge.approvedAt ?? /* @__PURE__ */ new Date(); + const updated = await tx.update(cliAuthChallenges).set({ + approvedByUserId: userId, + boardApiKeyId: boardKeyId, + approvedAt, + updatedAt: /* @__PURE__ */ new Date() + }).where(eq(cliAuthChallenges.id, challenge.id)).returning().then((rows) => rows[0] ?? challenge); + return { status: "approved", challenge: updated }; + }); + } + async function cancelCliAuthChallenge(id, token) { + const challenge = await getCliAuthChallengeBySecret(id, token); + if (!challenge) throw notFound("CLI auth challenge not found"); + const status = challengeStatusForRow(challenge); + if (status === "approved") return { status, challenge }; + if (status === "expired") return { status, challenge }; + if (status === "cancelled") return { status, challenge }; + const updated = await db.update(cliAuthChallenges).set({ + cancelledAt: /* @__PURE__ */ new Date(), + updatedAt: /* @__PURE__ */ new Date() + }).where(eq(cliAuthChallenges.id, challenge.id)).returning().then((rows) => rows[0] ?? challenge); + return { status: "cancelled", challenge: updated }; + } + async function assertCurrentBoardKey(keyId, userId) { + if (!keyId || !userId) throw conflict("Board API key context is required"); + const key = await db.select().from(boardApiKeys).where(and(eq(boardApiKeys.id, keyId), eq(boardApiKeys.userId, userId))).then((rows) => rows[0] ?? null); + if (!key || key.revokedAt) throw notFound("Board API key not found"); + return key; + } + return { + resolveBoardAccess, + findBoardApiKeyByToken, + touchBoardApiKey, + revokeBoardApiKey, + createCliAuthChallenge, + getCliAuthChallengeBySecret, + describeCliAuthChallenge, + approveCliAuthChallenge, + cancelCliAuthChallenge, + assertCurrentBoardKey, + resolveBoardActivityCompanyIds + }; +} + +// server/src/middleware/auth.ts +function hashToken(token) { + return createHash2("sha256").update(token).digest("hex"); +} +function actorMiddleware(db, opts) { + const boardAuth = boardAuthService(db); + return async (req, _res, next) => { + req.actor = opts.deploymentMode === "local_trusted" ? { type: "board", userId: "local-board", isInstanceAdmin: true, source: "local_implicit" } : { type: "none", source: "none" }; + const runIdHeader = req.header("x-taskcore-run-id"); + const authHeader = req.header("authorization"); + if (!authHeader?.toLowerCase().startsWith("bearer ")) { + if (opts.deploymentMode === "authenticated" && opts.resolveSession) { + let session = null; + try { + session = await opts.resolveSession(req); + } catch (err) { + logger.warn( + { err, method: req.method, url: req.originalUrl }, + "Failed to resolve auth session from request headers" + ); + } + if (session?.user?.id) { + const userId = session.user.id; + const [roleRow, memberships] = await Promise.all([ + db.select({ id: instanceUserRoles.id }).from(instanceUserRoles).where(and(eq(instanceUserRoles.userId, userId), eq(instanceUserRoles.role, "instance_admin"))).then((rows) => rows[0] ?? null), + db.select({ companyId: companyMemberships.companyId }).from(companyMemberships).where( + and( + eq(companyMemberships.principalType, "user"), + eq(companyMemberships.principalId, userId), + eq(companyMemberships.status, "active") + ) + ) + ]); + req.actor = { + type: "board", + userId, + companyIds: memberships.map((row) => row.companyId), + isInstanceAdmin: Boolean(roleRow), + runId: runIdHeader ?? void 0, + source: "session" + }; + next(); + return; + } + } + if (runIdHeader) req.actor.runId = runIdHeader; + next(); + return; + } + const token = authHeader.slice("bearer ".length).trim(); + if (!token) { + next(); + return; + } + const boardKey = await boardAuth.findBoardApiKeyByToken(token); + if (boardKey) { + const access = await boardAuth.resolveBoardAccess(boardKey.userId); + if (access.user) { + await boardAuth.touchBoardApiKey(boardKey.id); + req.actor = { + type: "board", + userId: boardKey.userId, + companyIds: access.companyIds, + isInstanceAdmin: access.isInstanceAdmin, + keyId: boardKey.id, + runId: runIdHeader || void 0, + source: "board_key" + }; + next(); + return; + } + } + const tokenHash = hashToken(token); + const key = await db.select().from(agentApiKeys).where(and(eq(agentApiKeys.keyHash, tokenHash), isNull(agentApiKeys.revokedAt))).then((rows) => rows[0] ?? null); + if (!key) { + const claims = verifyLocalAgentJwt(token); + if (!claims) { + next(); + return; + } + const agentRecord2 = await db.select().from(agents).where(eq(agents.id, claims.sub)).then((rows) => rows[0] ?? null); + if (!agentRecord2 || agentRecord2.companyId !== claims.company_id) { + next(); + return; + } + if (agentRecord2.status === "terminated" || agentRecord2.status === "pending_approval") { + next(); + return; + } + req.actor = { + type: "agent", + agentId: claims.sub, + companyId: claims.company_id, + keyId: void 0, + runId: runIdHeader || claims.run_id || void 0, + source: "agent_jwt" + }; + next(); + return; + } + await db.update(agentApiKeys).set({ lastUsedAt: /* @__PURE__ */ new Date() }).where(eq(agentApiKeys.id, key.id)); + const agentRecord = await db.select().from(agents).where(eq(agents.id, key.agentId)).then((rows) => rows[0] ?? null); + if (!agentRecord || agentRecord.status === "terminated" || agentRecord.status === "pending_approval") { + next(); + return; + } + req.actor = { + type: "agent", + agentId: key.agentId, + companyId: key.companyId, + keyId: key.id, + runId: runIdHeader || void 0, + source: "agent_key" + }; + next(); + }; +} + +// server/src/middleware/board-mutation-guard.ts +var SAFE_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD", "OPTIONS"]); +var DEFAULT_DEV_ORIGINS = [ + "http://localhost:3100", + "http://127.0.0.1:3100" +]; +function parseOrigin(value) { + if (!value) return null; + try { + const url2 = new URL(value); + return `${url2.protocol}//${url2.host}`.toLowerCase(); + } catch { + return null; + } +} +function trustedOriginsForRequest(req) { + const origins = new Set(DEFAULT_DEV_ORIGINS.map((value) => value.toLowerCase())); + const forwardedHost = req.header("x-forwarded-host")?.split(",")[0]?.trim(); + const host = forwardedHost || req.header("host")?.trim(); + if (host) { + origins.add(`http://${host}`.toLowerCase()); + origins.add(`https://${host}`.toLowerCase()); + } + return origins; +} +function isTrustedBoardMutationRequest(req) { + const allowedOrigins = trustedOriginsForRequest(req); + const origin = parseOrigin(req.header("origin")); + if (origin && allowedOrigins.has(origin)) return true; + const refererOrigin = parseOrigin(req.header("referer")); + if (refererOrigin && allowedOrigins.has(refererOrigin)) return true; + return false; +} +function boardMutationGuard() { + return (req, res, next) => { + if (SAFE_METHODS.has(req.method.toUpperCase())) { + next(); + return; + } + if (req.actor.type !== "board") { + next(); + return; + } + if (req.actor.source === "local_implicit" || req.actor.source === "board_key") { + next(); + return; + } + if (!isTrustedBoardMutationRequest(req)) { + res.status(403).json({ error: "Board mutation requires trusted browser origin" }); + return; + } + next(); + }; +} + +// server/src/middleware/private-hostname-guard.ts +function isLoopbackHostname(hostname3) { + const normalized = hostname3.trim().toLowerCase(); + return normalized === "localhost" || normalized === "127.0.0.1" || normalized === "::1"; +} +function extractHostname(req) { + const forwardedHost = req.header("x-forwarded-host")?.split(",")[0]?.trim(); + const hostHeader = req.header("host")?.trim(); + const raw = forwardedHost || hostHeader; + if (!raw) return null; + try { + return new URL(`http://${raw}`).hostname.trim().toLowerCase(); + } catch { + return raw.trim().toLowerCase(); + } +} +function normalizeAllowedHostnames(values2) { + const unique2 = /* @__PURE__ */ new Set(); + for (const value of values2) { + const trimmed = value.trim().toLowerCase(); + if (!trimmed) continue; + unique2.add(trimmed); + } + return Array.from(unique2); +} +function resolvePrivateHostnameAllowSet(opts) { + const configuredAllow = normalizeAllowedHostnames(opts.allowedHostnames); + const bindHost = opts.bindHost.trim().toLowerCase(); + const allowSet = new Set(configuredAllow); + if (bindHost && bindHost !== "0.0.0.0") { + allowSet.add(bindHost); + } + allowSet.add("localhost"); + allowSet.add("127.0.0.1"); + allowSet.add("::1"); + return allowSet; +} +function blockedHostnameMessage(hostname3) { + return `Hostname '${hostname3}' is not allowed for this Taskcore instance. If you want to allow this hostname, please run pnpm taskcore allowed-hostname ${hostname3}`; +} +function privateHostnameGuard(opts) { + if (!opts.enabled) { + return (_req, _res, next) => next(); + } + const allowSet = resolvePrivateHostnameAllowSet({ + allowedHostnames: opts.allowedHostnames, + bindHost: opts.bindHost + }); + return (req, res, next) => { + const hostname3 = extractHostname(req); + const wantsJson = req.path.startsWith("/api") || req.accepts(["json", "html", "text"]) === "json"; + if (!hostname3) { + const error51 = "Missing Host header. If you want to allow a hostname, run pnpm taskcore allowed-hostname ."; + if (wantsJson) { + res.status(403).json({ error: error51 }); + } else { + res.status(403).type("text/plain").send(error51); + } + return; + } + if (isLoopbackHostname(hostname3) || allowSet.has(hostname3)) { + next(); + return; + } + const error50 = blockedHostnameMessage(hostname3); + if (wantsJson) { + res.status(403).json({ error: error50 }); + } else { + res.status(403).type("text/plain").send(error50); + } + }; +} + +// server/src/routes/health.ts +var import_express = __toESM(require_express2(), 1); +init_drizzle_orm(); +init_src2(); + +// server/src/dev-server-status.ts +import { existsSync, readFileSync, statSync } from "node:fs"; +var MAX_PERSISTED_DEV_SERVER_STATUS_BYTES = 64 * 1024; +function normalizeStringArray(value) { + if (!Array.isArray(value)) return []; + return value.filter((entry) => typeof entry === "string").map((entry) => entry.trim()).filter((entry) => entry.length > 0); +} +function normalizeTimestamp(value) { + if (typeof value !== "string") return null; + const trimmed = value.trim(); + return trimmed.length > 0 ? trimmed : null; +} +function readPersistedDevServerStatus(env2 = process.env) { + const filePath = env2.TASKCORE_DEV_SERVER_STATUS_FILE?.trim(); + if (!filePath || !existsSync(filePath)) return null; + try { + if (statSync(filePath).size > MAX_PERSISTED_DEV_SERVER_STATUS_BYTES) { + return null; + } + const raw = JSON.parse(readFileSync(filePath, "utf8")); + const changedPathsSample = normalizeStringArray(raw.changedPathsSample).slice(0, 5); + const pendingMigrations = normalizeStringArray(raw.pendingMigrations); + const changedPathCountRaw = raw.changedPathCount; + const changedPathCount = typeof changedPathCountRaw === "number" && Number.isFinite(changedPathCountRaw) ? Math.max(0, Math.trunc(changedPathCountRaw)) : changedPathsSample.length; + const dirtyRaw = raw.dirty; + const dirty = typeof dirtyRaw === "boolean" ? dirtyRaw : changedPathCount > 0 || pendingMigrations.length > 0; + return { + dirty, + lastChangedAt: normalizeTimestamp(raw.lastChangedAt), + changedPathCount, + changedPathsSample, + pendingMigrations, + lastRestartAt: normalizeTimestamp(raw.lastRestartAt) + }; + } catch { + return null; + } +} +function toDevServerHealthStatus(persisted, opts) { + const hasPathChanges = persisted.changedPathCount > 0; + const hasPendingMigrations = persisted.pendingMigrations.length > 0; + const reason = hasPathChanges && hasPendingMigrations ? "backend_changes_and_pending_migrations" : hasPendingMigrations ? "pending_migrations" : hasPathChanges ? "backend_changes" : null; + const restartRequired = persisted.dirty || reason !== null; + return { + enabled: true, + restartRequired, + reason, + lastChangedAt: persisted.lastChangedAt, + changedPathCount: persisted.changedPathCount, + changedPathsSample: persisted.changedPathsSample, + pendingMigrations: persisted.pendingMigrations, + autoRestartEnabled: opts.autoRestartEnabled, + activeRunCount: opts.activeRunCount, + waitingForIdle: restartRequired && opts.autoRestartEnabled && opts.activeRunCount > 0, + lastRestartAt: persisted.lastRestartAt + }; +} + +// server/src/services/instance-settings.ts +init_src2(); +init_drizzle_orm(); +var DEFAULT_SINGLETON_KEY = "default"; +function normalizeGeneralSettings(raw) { + const parsed = instanceGeneralSettingsSchema.safeParse(raw ?? {}); + if (parsed.success) { + return { + censorUsernameInLogs: parsed.data.censorUsernameInLogs ?? false, + keyboardShortcuts: parsed.data.keyboardShortcuts ?? false, + feedbackDataSharingPreference: parsed.data.feedbackDataSharingPreference ?? DEFAULT_FEEDBACK_DATA_SHARING_PREFERENCE, + backupRetention: parsed.data.backupRetention ?? DEFAULT_BACKUP_RETENTION + }; + } + return { + censorUsernameInLogs: false, + keyboardShortcuts: false, + feedbackDataSharingPreference: DEFAULT_FEEDBACK_DATA_SHARING_PREFERENCE, + backupRetention: DEFAULT_BACKUP_RETENTION + }; +} +function normalizeExperimentalSettings(raw) { + const parsed = instanceExperimentalSettingsSchema.safeParse(raw ?? {}); + if (parsed.success) { + return { + enableIsolatedWorkspaces: parsed.data.enableIsolatedWorkspaces ?? false, + autoRestartDevServerWhenIdle: parsed.data.autoRestartDevServerWhenIdle ?? false + }; + } + return { + enableIsolatedWorkspaces: false, + autoRestartDevServerWhenIdle: false + }; +} +function toInstanceSettings(row) { + return { + id: row.id, + general: normalizeGeneralSettings(row.general), + experimental: normalizeExperimentalSettings(row.experimental), + createdAt: row.createdAt, + updatedAt: row.updatedAt + }; +} +function instanceSettingsService(db) { + async function getOrCreateRow() { + const existing = await db.select().from(instanceSettings).where(eq(instanceSettings.singletonKey, DEFAULT_SINGLETON_KEY)).then((rows) => rows[0] ?? null); + if (existing) return existing; + const now2 = /* @__PURE__ */ new Date(); + const [created] = await db.insert(instanceSettings).values({ + singletonKey: DEFAULT_SINGLETON_KEY, + general: {}, + experimental: {}, + createdAt: now2, + updatedAt: now2 + }).onConflictDoUpdate({ + target: [instanceSettings.singletonKey], + set: { + updatedAt: now2 + } + }).returning(); + return created; + } + return { + get: async () => toInstanceSettings(await getOrCreateRow()), + getGeneral: async () => { + const row = await getOrCreateRow(); + return normalizeGeneralSettings(row.general); + }, + getExperimental: async () => { + const row = await getOrCreateRow(); + return normalizeExperimentalSettings(row.experimental); + }, + updateGeneral: async (patch) => { + const current = await getOrCreateRow(); + const nextGeneral = normalizeGeneralSettings({ + ...normalizeGeneralSettings(current.general), + ...patch + }); + const now2 = /* @__PURE__ */ new Date(); + const [updated] = await db.update(instanceSettings).set({ + general: { ...nextGeneral }, + updatedAt: now2 + }).where(eq(instanceSettings.id, current.id)).returning(); + return toInstanceSettings(updated ?? current); + }, + updateExperimental: async (patch) => { + const current = await getOrCreateRow(); + const nextExperimental = normalizeExperimentalSettings({ + ...normalizeExperimentalSettings(current.experimental), + ...patch + }); + const now2 = /* @__PURE__ */ new Date(); + const [updated] = await db.update(instanceSettings).set({ + experimental: { ...nextExperimental }, + updatedAt: now2 + }).where(eq(instanceSettings.id, current.id)).returning(); + return toInstanceSettings(updated ?? current); + }, + listCompanyIds: async () => db.select({ id: companies.id }).from(companies).then((rows) => rows.map((row) => row.id)) + }; +} + +// server/src/routes/health.ts +function healthRoutes(db, opts = { + deploymentMode: "local_trusted", + deploymentExposure: "private", + authReady: true, + companyDeletionEnabled: true +}) { + const router2 = (0, import_express.Router)(); + router2.get("/", async (_req, res) => { + if (!db) { + res.json({ status: "ok", version: serverVersion }); + return; + } + try { + await db.execute(sql`SELECT 1`); + } catch { + res.status(503).json({ + status: "unhealthy", + version: serverVersion, + error: "database_unreachable" + }); + return; + } + let bootstrapStatus = "ready"; + let bootstrapInviteActive = false; + if (opts.deploymentMode === "authenticated") { + const roleCount = await db.select({ count: count() }).from(instanceUserRoles).where(sql`${instanceUserRoles.role} = 'instance_admin'`).then((rows) => Number(rows[0]?.count ?? 0)); + bootstrapStatus = roleCount > 0 ? "ready" : "bootstrap_pending"; + if (bootstrapStatus === "bootstrap_pending") { + const now2 = /* @__PURE__ */ new Date(); + const inviteCount = await db.select({ count: count() }).from(invites).where( + and( + eq(invites.inviteType, "bootstrap_ceo"), + isNull(invites.revokedAt), + isNull(invites.acceptedAt), + gt(invites.expiresAt, now2) + ) + ).then((rows) => Number(rows[0]?.count ?? 0)); + bootstrapInviteActive = inviteCount > 0; + } + } + const persistedDevServerStatus = readPersistedDevServerStatus(); + let devServer; + if (persistedDevServerStatus) { + const instanceSettings2 = instanceSettingsService(db); + const experimentalSettings = await instanceSettings2.getExperimental(); + const activeRunCount = await db.select({ count: count() }).from(heartbeatRuns).where(inArray(heartbeatRuns.status, ["queued", "running"])).then((rows) => Number(rows[0]?.count ?? 0)); + devServer = toDevServerHealthStatus(persistedDevServerStatus, { + autoRestartEnabled: experimentalSettings.autoRestartDevServerWhenIdle ?? false, + activeRunCount + }); + } + res.json({ + status: "ok", + version: serverVersion, + deploymentMode: opts.deploymentMode, + deploymentExposure: opts.deploymentExposure, + authReady: opts.authReady, + bootstrapStatus, + bootstrapInviteActive, + features: { + companyDeletionEnabled: opts.companyDeletionEnabled + }, + ...devServer ? { devServer } : {} + }); + }); + return router2; +} + +// server/src/routes/companies.ts +var import_express2 = __toESM(require_express2(), 1); + +// server/src/services/companies.ts +init_drizzle_orm(); +init_src2(); +function companyService(db) { + const ISSUE_PREFIX_FALLBACK = "CMP"; + const companySelection = { + id: companies.id, + name: companies.name, + description: companies.description, + status: companies.status, + issuePrefix: companies.issuePrefix, + issueCounter: companies.issueCounter, + budgetMonthlyCents: companies.budgetMonthlyCents, + spentMonthlyCents: companies.spentMonthlyCents, + requireBoardApprovalForNewAgents: companies.requireBoardApprovalForNewAgents, + feedbackDataSharingEnabled: companies.feedbackDataSharingEnabled, + feedbackDataSharingConsentAt: companies.feedbackDataSharingConsentAt, + feedbackDataSharingConsentByUserId: companies.feedbackDataSharingConsentByUserId, + feedbackDataSharingTermsVersion: companies.feedbackDataSharingTermsVersion, + brandColor: companies.brandColor, + logoAssetId: companyLogos.assetId, + createdAt: companies.createdAt, + updatedAt: companies.updatedAt + }; + function enrichCompany(company) { + return { + ...company, + logoUrl: company.logoAssetId ? `/api/assets/${company.logoAssetId}/content` : null + }; + } + function currentUtcMonthWindow3(now2 = /* @__PURE__ */ new Date()) { + const year3 = now2.getUTCFullYear(); + const month = now2.getUTCMonth(); + return { + start: new Date(Date.UTC(year3, month, 1, 0, 0, 0, 0)), + end: new Date(Date.UTC(year3, month + 1, 1, 0, 0, 0, 0)) + }; + } + async function getMonthlySpendByCompanyIds(companyIds, database = db) { + if (companyIds.length === 0) return /* @__PURE__ */ new Map(); + const { start, end } = currentUtcMonthWindow3(); + const rows = await database.select({ + companyId: costEvents.companyId, + spentMonthlyCents: sql`coalesce(sum(${costEvents.costCents}), 0)::int` + }).from(costEvents).where( + and( + inArray(costEvents.companyId, companyIds), + gte(costEvents.occurredAt, start), + lt(costEvents.occurredAt, end) + ) + ).groupBy(costEvents.companyId); + return new Map(rows.map((row) => [row.companyId, Number(row.spentMonthlyCents ?? 0)])); + } + async function hydrateCompanySpend(rows, database = db) { + const spendByCompanyId = await getMonthlySpendByCompanyIds(rows.map((row) => row.id), database); + return rows.map((row) => ({ + ...row, + spentMonthlyCents: spendByCompanyId.get(row.id) ?? 0 + })); + } + function getCompanyQuery(database) { + return database.select(companySelection).from(companies).leftJoin(companyLogos, eq(companyLogos.companyId, companies.id)); + } + function deriveIssuePrefixBase(name) { + const normalized = name.toUpperCase().replace(/[^A-Z]/g, ""); + return normalized.slice(0, 3) || ISSUE_PREFIX_FALLBACK; + } + function suffixForAttempt(attempt) { + if (attempt <= 1) return ""; + return "A".repeat(attempt - 1); + } + function isIssuePrefixConflict(error50) { + const constraint = typeof error50 === "object" && error50 !== null && "constraint" in error50 ? error50.constraint : typeof error50 === "object" && error50 !== null && "constraint_name" in error50 ? error50.constraint_name : void 0; + return typeof error50 === "object" && error50 !== null && "code" in error50 && error50.code === "23505" && constraint === "companies_issue_prefix_idx"; + } + async function createCompanyWithUniquePrefix(data2) { + const base = deriveIssuePrefixBase(data2.name); + let suffix = 1; + while (suffix < 1e4) { + const candidate = `${base}${suffixForAttempt(suffix)}`; + try { + const rows = await db.insert(companies).values({ ...data2, issuePrefix: candidate }).returning(); + return rows[0]; + } catch (error50) { + if (!isIssuePrefixConflict(error50)) throw error50; + } + suffix += 1; + } + throw new Error("Unable to allocate unique issue prefix"); + } + return { + list: async () => { + const rows = await getCompanyQuery(db); + const hydrated = await hydrateCompanySpend(rows); + return hydrated.map((row) => enrichCompany(row)); + }, + getById: async (id) => { + const row = await getCompanyQuery(db).where(eq(companies.id, id)).then((rows) => rows[0] ?? null); + if (!row) return null; + const [hydrated] = await hydrateCompanySpend([row], db); + return enrichCompany(hydrated); + }, + create: async (data2) => { + const created = await createCompanyWithUniquePrefix(data2); + const row = await getCompanyQuery(db).where(eq(companies.id, created.id)).then((rows) => rows[0] ?? null); + if (!row) throw notFound("Company not found after creation"); + const [hydrated] = await hydrateCompanySpend([row], db); + return enrichCompany(hydrated); + }, + update: (id, data2) => db.transaction(async (tx) => { + const existing = await getCompanyQuery(tx).where(eq(companies.id, id)).then((rows) => rows[0] ?? null); + if (!existing) return null; + const { logoAssetId, ...companyPatch } = data2; + if (logoAssetId !== void 0 && logoAssetId !== null) { + const nextLogoAsset = await tx.select({ id: assets.id, companyId: assets.companyId }).from(assets).where(eq(assets.id, logoAssetId)).then((rows) => rows[0] ?? null); + if (!nextLogoAsset) throw notFound("Logo asset not found"); + if (nextLogoAsset.companyId !== existing.id) { + throw unprocessable("Logo asset must belong to the same company"); + } + } + const updated = await tx.update(companies).set({ ...companyPatch, updatedAt: /* @__PURE__ */ new Date() }).where(eq(companies.id, id)).returning().then((rows) => rows[0] ?? null); + if (!updated) return null; + if (logoAssetId === null) { + await tx.delete(companyLogos).where(eq(companyLogos.companyId, id)); + } else if (logoAssetId !== void 0) { + await tx.insert(companyLogos).values({ + companyId: id, + assetId: logoAssetId + }).onConflictDoUpdate({ + target: companyLogos.companyId, + set: { + assetId: logoAssetId, + updatedAt: /* @__PURE__ */ new Date() + } + }); + } + if (logoAssetId !== void 0 && existing.logoAssetId && existing.logoAssetId !== logoAssetId) { + await tx.delete(assets).where(eq(assets.id, existing.logoAssetId)); + } + const [hydrated] = await hydrateCompanySpend([{ + ...updated, + logoAssetId: logoAssetId === void 0 ? existing.logoAssetId : logoAssetId + }], tx); + return enrichCompany(hydrated); + }), + archive: (id) => db.transaction(async (tx) => { + const updated = await tx.update(companies).set({ status: "archived", updatedAt: /* @__PURE__ */ new Date() }).where(eq(companies.id, id)).returning().then((rows) => rows[0] ?? null); + if (!updated) return null; + const row = await getCompanyQuery(tx).where(eq(companies.id, id)).then((rows) => rows[0] ?? null); + if (!row) return null; + const [hydrated] = await hydrateCompanySpend([row], tx); + return enrichCompany(hydrated); + }), + remove: (id) => db.transaction(async (tx) => { + await tx.delete(heartbeatRunEvents).where(eq(heartbeatRunEvents.companyId, id)); + await tx.delete(agentTaskSessions).where(eq(agentTaskSessions.companyId, id)); + await tx.delete(activityLog).where(eq(activityLog.companyId, id)); + await tx.delete(heartbeatRuns).where(eq(heartbeatRuns.companyId, id)); + await tx.delete(agentWakeupRequests).where(eq(agentWakeupRequests.companyId, id)); + await tx.delete(agentApiKeys).where(eq(agentApiKeys.companyId, id)); + await tx.delete(agentRuntimeState).where(eq(agentRuntimeState.companyId, id)); + await tx.delete(issueComments).where(eq(issueComments.companyId, id)); + await tx.delete(costEvents).where(eq(costEvents.companyId, id)); + await tx.delete(financeEvents).where(eq(financeEvents.companyId, id)); + await tx.delete(approvalComments).where(eq(approvalComments.companyId, id)); + await tx.delete(approvals).where(eq(approvals.companyId, id)); + await tx.delete(companySecrets).where(eq(companySecrets.companyId, id)); + await tx.delete(joinRequests).where(eq(joinRequests.companyId, id)); + await tx.delete(invites).where(eq(invites.companyId, id)); + await tx.delete(principalPermissionGrants).where(eq(principalPermissionGrants.companyId, id)); + await tx.delete(companyMemberships).where(eq(companyMemberships.companyId, id)); + await tx.delete(companySkills).where(eq(companySkills.companyId, id)); + await tx.delete(issueReadStates).where(eq(issueReadStates.companyId, id)); + await tx.delete(issues).where(eq(issues.companyId, id)); + await tx.delete(companyLogos).where(eq(companyLogos.companyId, id)); + await tx.delete(assets).where(eq(assets.companyId, id)); + await tx.delete(goals).where(eq(goals.companyId, id)); + await tx.delete(projects).where(eq(projects.companyId, id)); + await tx.delete(agents).where(eq(agents.companyId, id)); + const rows = await tx.delete(companies).where(eq(companies.id, id)).returning(); + return rows[0] ?? null; + }), + stats: () => Promise.all([ + db.select({ companyId: agents.companyId, count: count() }).from(agents).groupBy(agents.companyId), + db.select({ companyId: issues.companyId, count: count() }).from(issues).groupBy(issues.companyId) + ]).then(([agentRows, issueRows]) => { + const result = {}; + for (const row of agentRows) { + result[row.companyId] = { agentCount: row.count, issueCount: 0 }; + } + for (const row of issueRows) { + if (result[row.companyId]) { + result[row.companyId].issueCount = row.count; + } else { + result[row.companyId] = { agentCount: 0, issueCount: row.count }; + } + } + return result; + }) + }; +} + +// server/src/services/feedback.ts +init_drizzle_orm(); +init_src2(); +import { readFile, readdir } from "node:fs/promises"; +import path20 from "node:path"; + +// packages/adapter-utils/src/server-utils.ts +import { spawn } from "node:child_process"; +import { constants as fsConstants, promises as fs4 } from "node:fs"; +import path4 from "node:path"; +function resolveProcessGroupId(child) { + if (process.platform === "win32") return null; + return typeof child.pid === "number" && child.pid > 0 ? child.pid : null; +} +function signalRunningProcess(running, signal) { + if (process.platform !== "win32" && running.processGroupId && running.processGroupId > 0) { + try { + process.kill(-running.processGroupId, signal); + return; + } catch { + } + } + if (!running.child.killed) { + running.child.kill(signal); + } +} +var runningProcesses = /* @__PURE__ */ new Map(); +var MAX_CAPTURE_BYTES = 4 * 1024 * 1024; +var MAX_EXCERPT_BYTES = 32 * 1024; +var SENSITIVE_ENV_KEY = /(key|token|secret|password|passwd|authorization|cookie)/i; +var TASKCORE_SKILL_ROOT_RELATIVE_CANDIDATES = [ + "../../skills", + "../../../../../skills" +]; +function normalizePathSlashes(value) { + return value.replaceAll("\\", "/"); +} +function isMaintainerOnlySkillTarget(candidate) { + return normalizePathSlashes(candidate).includes("/.agents/skills/"); +} +function skillLocationLabel(value) { + if (typeof value !== "string") return null; + const trimmed = value.trim(); + return trimmed.length > 0 ? trimmed : null; +} +function buildManagedSkillOrigin(entry) { + if (entry.required) { + return { + origin: "taskcore_required", + originLabel: "Required by Taskcore", + readOnly: false + }; + } + return { + origin: "company_managed", + originLabel: "Managed by Taskcore", + readOnly: false + }; +} +function resolveInstalledEntryTarget(skillsHome, entryName, dirent, linkedPath) { + const fullPath = path4.join(skillsHome, entryName); + if (dirent.isSymbolicLink()) { + return { + targetPath: linkedPath ? path4.resolve(path4.dirname(fullPath), linkedPath) : null, + kind: "symlink" + }; + } + if (dirent.isDirectory()) { + return { targetPath: fullPath, kind: "directory" }; + } + return { targetPath: fullPath, kind: "file" }; +} +function parseObject(value) { + if (typeof value !== "object" || value === null || Array.isArray(value)) { + return {}; + } + return value; +} +function asString(value, fallback) { + return typeof value === "string" && value.length > 0 ? value : fallback; +} +function asNumber(value, fallback) { + return typeof value === "number" && Number.isFinite(value) ? value : fallback; +} +function asBoolean(value, fallback) { + return typeof value === "boolean" ? value : fallback; +} +function asStringArray(value) { + return Array.isArray(value) ? value.filter((item) => typeof item === "string") : []; +} +function parseJson2(value) { + try { + return JSON.parse(value); + } catch { + return null; + } +} +function appendWithCap(prev, chunk, cap = MAX_CAPTURE_BYTES) { + const combined = prev + chunk; + return combined.length > cap ? combined.slice(combined.length - cap) : combined; +} +function resolvePathValue(obj, dottedPath) { + const parts = dottedPath.split("."); + let cursor2 = obj; + for (const part of parts) { + if (typeof cursor2 !== "object" || cursor2 === null || Array.isArray(cursor2)) { + return ""; + } + cursor2 = cursor2[part]; + } + if (cursor2 === null || cursor2 === void 0) return ""; + if (typeof cursor2 === "string") return cursor2; + if (typeof cursor2 === "number" || typeof cursor2 === "boolean") return String(cursor2); + try { + return JSON.stringify(cursor2); + } catch { + return ""; + } +} +function renderTemplate(template, data2) { + return template.replace(/{{\s*([a-zA-Z0-9_.-]+)\s*}}/g, (_, path53) => resolvePathValue(data2, path53)); +} +function joinPromptSections(sections, separator = "\n\n") { + return sections.map((value) => typeof value === "string" ? value.trim() : "").filter(Boolean).join(separator); +} +function normalizeTaskcoreWakeIssue(value) { + const issue2 = parseObject(value); + const id = asString(issue2.id, "").trim() || null; + const identifier = asString(issue2.identifier, "").trim() || null; + const title = asString(issue2.title, "").trim() || null; + const status = asString(issue2.status, "").trim() || null; + const priority = asString(issue2.priority, "").trim() || null; + if (!id && !identifier && !title) return null; + return { + id, + identifier, + title, + status, + priority + }; +} +function normalizeTaskcoreWakeComment(value) { + const comment = parseObject(value); + const author = parseObject(comment.author); + const body = asString(comment.body, ""); + if (!body.trim()) return null; + return { + id: asString(comment.id, "").trim() || null, + issueId: asString(comment.issueId, "").trim() || null, + body, + bodyTruncated: asBoolean(comment.bodyTruncated, false), + createdAt: asString(comment.createdAt, "").trim() || null, + authorType: asString(author.type, "").trim() || null, + authorId: asString(author.id, "").trim() || null + }; +} +function normalizeTaskcoreWakeExecutionPrincipal(value) { + const principal = parseObject(value); + const typeRaw = asString(principal.type, "").trim().toLowerCase(); + if (typeRaw !== "agent" && typeRaw !== "user") return null; + return { + type: typeRaw, + agentId: asString(principal.agentId, "").trim() || null, + userId: asString(principal.userId, "").trim() || null + }; +} +function normalizeTaskcoreWakeExecutionStage(value) { + const stage = parseObject(value); + const wakeRoleRaw = asString(stage.wakeRole, "").trim().toLowerCase(); + const wakeRole = wakeRoleRaw === "reviewer" || wakeRoleRaw === "approver" || wakeRoleRaw === "executor" ? wakeRoleRaw : null; + const allowedActions = Array.isArray(stage.allowedActions) ? stage.allowedActions.filter((entry) => typeof entry === "string" && entry.trim().length > 0).map((entry) => entry.trim()) : []; + const currentParticipant = normalizeTaskcoreWakeExecutionPrincipal(stage.currentParticipant); + const returnAssignee = normalizeTaskcoreWakeExecutionPrincipal(stage.returnAssignee); + const stageId = asString(stage.stageId, "").trim() || null; + const stageType = asString(stage.stageType, "").trim() || null; + const lastDecisionOutcome = asString(stage.lastDecisionOutcome, "").trim() || null; + if (!wakeRole && !stageId && !stageType && !currentParticipant && !returnAssignee && !lastDecisionOutcome && allowedActions.length === 0) { + return null; + } + return { + wakeRole, + stageId, + stageType, + currentParticipant, + returnAssignee, + lastDecisionOutcome, + allowedActions + }; +} +function normalizeTaskcoreWakePayload(value) { + const payload2 = parseObject(value); + const comments = Array.isArray(payload2.comments) ? payload2.comments.map((entry) => normalizeTaskcoreWakeComment(entry)).filter((entry) => Boolean(entry)) : []; + const commentWindow = parseObject(payload2.commentWindow); + const commentIds = Array.isArray(payload2.commentIds) ? payload2.commentIds.filter((entry) => typeof entry === "string" && entry.trim().length > 0).map((entry) => entry.trim()) : []; + const executionStage = normalizeTaskcoreWakeExecutionStage(payload2.executionStage); + if (comments.length === 0 && commentIds.length === 0 && !executionStage && !normalizeTaskcoreWakeIssue(payload2.issue)) { + return null; + } + return { + reason: asString(payload2.reason, "").trim() || null, + issue: normalizeTaskcoreWakeIssue(payload2.issue), + checkedOutByHarness: asBoolean(payload2.checkedOutByHarness, false), + executionStage, + commentIds, + latestCommentId: asString(payload2.latestCommentId, "").trim() || null, + comments, + requestedCount: asNumber(commentWindow.requestedCount, comments.length || commentIds.length), + includedCount: asNumber(commentWindow.includedCount, comments.length), + missingCount: asNumber(commentWindow.missingCount, 0), + truncated: asBoolean(payload2.truncated, false), + fallbackFetchNeeded: asBoolean(payload2.fallbackFetchNeeded, false) + }; +} +function stringifyTaskcoreWakePayload(value) { + const normalized = normalizeTaskcoreWakePayload(value); + if (!normalized) return null; + return JSON.stringify(normalized); +} +function renderTaskcoreWakePrompt(value, options = {}) { + const normalized = normalizeTaskcoreWakePayload(value); + if (!normalized) return ""; + const resumedSession = options.resumedSession === true; + const executionStage = normalized.executionStage; + const principalLabel = (principal) => { + if (!principal || !principal.type) return "unknown"; + if (principal.type === "agent") return principal.agentId ? `agent ${principal.agentId}` : "agent"; + return principal.userId ? `user ${principal.userId}` : "user"; + }; + const lines = resumedSession ? [ + "## Taskcore Resume Delta", + "", + "You are resuming an existing Taskcore session.", + "This heartbeat is scoped to the issue below. Do not switch to another issue until you have handled this wake.", + "Focus on the new wake delta below and continue the current task without restating the full heartbeat boilerplate.", + "Fetch the API thread only when `fallbackFetchNeeded` is true or you need broader history than this batch.", + "", + `- reason: ${normalized.reason ?? "unknown"}`, + `- issue: ${normalized.issue?.identifier ?? normalized.issue?.id ?? "unknown"}${normalized.issue?.title ? ` ${normalized.issue.title}` : ""}`, + `- pending comments: ${normalized.includedCount}/${normalized.requestedCount}`, + `- latest comment id: ${normalized.latestCommentId ?? "unknown"}`, + `- fallback fetch needed: ${normalized.fallbackFetchNeeded ? "yes" : "no"}` + ] : [ + "## Taskcore Wake Payload", + "", + "Treat this wake payload as the highest-priority change for the current heartbeat.", + "This heartbeat is scoped to the issue below. Do not switch to another issue until you have handled this wake.", + "Before generic repo exploration or boilerplate heartbeat updates, acknowledge the latest comment and explain how it changes your next action.", + "Use this inline wake data first before refetching the issue thread.", + "Only fetch the API thread when `fallbackFetchNeeded` is true or you need broader history than this batch.", + "", + `- reason: ${normalized.reason ?? "unknown"}`, + `- issue: ${normalized.issue?.identifier ?? normalized.issue?.id ?? "unknown"}${normalized.issue?.title ? ` ${normalized.issue.title}` : ""}`, + `- pending comments: ${normalized.includedCount}/${normalized.requestedCount}`, + `- latest comment id: ${normalized.latestCommentId ?? "unknown"}`, + `- fallback fetch needed: ${normalized.fallbackFetchNeeded ? "yes" : "no"}` + ]; + if (normalized.issue?.status) { + lines.push(`- issue status: ${normalized.issue.status}`); + } + if (normalized.issue?.priority) { + lines.push(`- issue priority: ${normalized.issue.priority}`); + } + if (normalized.checkedOutByHarness) { + lines.push("- checkout: already claimed by the harness for this run"); + } + if (normalized.missingCount > 0) { + lines.push(`- omitted comments: ${normalized.missingCount}`); + } + if (executionStage) { + lines.push( + `- execution wake role: ${executionStage.wakeRole ?? "unknown"}`, + `- execution stage: ${executionStage.stageType ?? "unknown"}`, + `- execution participant: ${principalLabel(executionStage.currentParticipant)}`, + `- execution return assignee: ${principalLabel(executionStage.returnAssignee)}`, + `- last decision outcome: ${executionStage.lastDecisionOutcome ?? "none"}` + ); + if (executionStage.allowedActions.length > 0) { + lines.push(`- allowed actions: ${executionStage.allowedActions.join(", ")}`); + } + lines.push(""); + if (executionStage.wakeRole === "reviewer" || executionStage.wakeRole === "approver") { + lines.push( + `You are waking as the active ${executionStage.wakeRole} for this issue.`, + "Do not execute the task itself or continue executor work.", + "Review the issue and choose one of the allowed actions above.", + "If you request changes, the workflow routes back to the stored return assignee.", + "" + ); + } else if (executionStage.wakeRole === "executor") { + lines.push( + "You are waking because changes were requested in the execution workflow.", + "Address the requested changes on this issue and resubmit when the work is ready.", + "" + ); + } + } + if (normalized.checkedOutByHarness) { + lines.push( + "", + "The harness already checked out this issue for the current run.", + "Do not call `/api/issues/{id}/checkout` again unless you intentionally switch to a different task.", + "" + ); + } + if (normalized.comments.length > 0) { + lines.push("New comments in order:"); + } + for (const [index2, comment] of normalized.comments.entries()) { + const authorLabel = comment.authorId ? `${comment.authorType ?? "unknown"} ${comment.authorId}` : comment.authorType ?? "unknown"; + lines.push( + `${index2 + 1}. comment ${comment.id ?? "unknown"} at ${comment.createdAt ?? "unknown"} by ${authorLabel}`, + comment.body + ); + if (comment.bodyTruncated) { + lines.push("[comment body truncated]"); + } + lines.push(""); + } + return lines.join("\n").trim(); +} +function redactEnvForLogs(env2) { + const redacted = {}; + for (const [key, value] of Object.entries(env2)) { + redacted[key] = SENSITIVE_ENV_KEY.test(key) ? "***REDACTED***" : value; + } + return redacted; +} +function buildInvocationEnvForLogs(env2, options = {}) { + const merged = { ...env2 }; + const runtimeEnv = options.runtimeEnv ?? {}; + for (const key of options.includeRuntimeKeys ?? []) { + if (key in merged) continue; + const value = runtimeEnv[key]; + if (typeof value !== "string" || value.length === 0) continue; + merged[key] = value; + } + const resolvedCommand = options.resolvedCommand?.trim(); + if (resolvedCommand) { + merged[options.resolvedCommandEnvKey ?? "TASKCORE_RESOLVED_COMMAND"] = resolvedCommand; + } + return redactEnvForLogs(merged); +} +function buildTaskcoreEnv(agent) { + const resolveHostForUrl = (rawHost) => { + const host = rawHost.trim(); + if (!host || host === "0.0.0.0" || host === "::") return "localhost"; + if (host.includes(":") && !host.startsWith("[") && !host.endsWith("]")) return `[${host}]`; + return host; + }; + const vars = { + TASKCORE_AGENT_ID: agent.id, + TASKCORE_COMPANY_ID: agent.companyId + }; + const runtimeHost = resolveHostForUrl( + process.env.TASKCORE_LISTEN_HOST ?? process.env.HOST ?? "localhost" + ); + const runtimePort = process.env.TASKCORE_LISTEN_PORT ?? process.env.PORT ?? "3100"; + const apiUrl = process.env.TASKCORE_API_URL ?? `http://${runtimeHost}:${runtimePort}`; + vars.TASKCORE_API_URL = apiUrl; + return vars; +} +function defaultPathForPlatform() { + if (process.platform === "win32") { + return "C:\\Windows\\System32;C:\\Windows;C:\\Windows\\System32\\Wbem"; + } + return "/usr/local/bin:/opt/homebrew/bin:/usr/local/sbin:/usr/bin:/bin:/usr/sbin:/sbin"; +} +function windowsPathExts(env2) { + return (env2.PATHEXT ?? ".EXE;.CMD;.BAT;.COM").split(";").filter(Boolean); +} +async function pathExists(candidate) { + try { + await fs4.access(candidate, process.platform === "win32" ? fsConstants.F_OK : fsConstants.X_OK); + return true; + } catch { + return false; + } +} +async function resolveCommandPath(command, cwd, env2) { + const hasPathSeparator = command.includes("/") || command.includes("\\"); + if (hasPathSeparator) { + const absolute = path4.isAbsolute(command) ? command : path4.resolve(cwd, command); + return await pathExists(absolute) ? absolute : null; + } + const pathValue = env2.PATH ?? env2.Path ?? ""; + const delimiter = process.platform === "win32" ? ";" : ":"; + const dirs = pathValue.split(delimiter).filter(Boolean); + const exts = process.platform === "win32" ? windowsPathExts(env2) : [""]; + const hasExtension = process.platform === "win32" && path4.extname(command).length > 0; + for (const dir of dirs) { + const candidates = process.platform === "win32" ? hasExtension ? [path4.join(dir, command)] : exts.map((ext) => path4.join(dir, `${command}${ext}`)) : [path4.join(dir, command)]; + for (const candidate of candidates) { + if (await pathExists(candidate)) return candidate; + } + } + return null; +} +async function resolveCommandForLogs(command, cwd, env2) { + return await resolveCommandPath(command, cwd, env2) ?? command; +} +function quoteForCmd(arg) { + if (!arg.length) return '""'; + const escaped = arg.replace(/"/g, '""'); + return /[\s"&<>|^()]/.test(escaped) ? `"${escaped}"` : escaped; +} +function resolveWindowsCmdShell(env2) { + const fallbackRoot = env2.SystemRoot || process.env.SystemRoot || "C:\\Windows"; + return path4.join(fallbackRoot, "System32", "cmd.exe"); +} +async function resolveSpawnTarget(command, args, cwd, env2) { + const resolved = await resolveCommandPath(command, cwd, env2); + const executable = resolved ?? command; + if (process.platform !== "win32") { + return { command: executable, args }; + } + if (/\.(cmd|bat)$/i.test(executable)) { + const shell = resolveWindowsCmdShell(env2); + const commandLine = [quoteForCmd(executable), ...args.map(quoteForCmd)].join(" "); + return { + command: shell, + args: ["/d", "/s", "/c", commandLine] + }; + } + return { command: executable, args }; +} +function ensurePathInEnv(env2) { + if (typeof env2.PATH === "string" && env2.PATH.length > 0) return env2; + if (typeof env2.Path === "string" && env2.Path.length > 0) return env2; + return { ...env2, PATH: defaultPathForPlatform() }; +} +async function ensureAbsoluteDirectory(cwd, opts = {}) { + if (!path4.isAbsolute(cwd)) { + throw new Error(`Working directory must be an absolute path: "${cwd}"`); + } + const assertDirectory = async () => { + const stats = await fs4.stat(cwd); + if (!stats.isDirectory()) { + throw new Error(`Working directory is not a directory: "${cwd}"`); + } + }; + try { + await assertDirectory(); + return; + } catch (err) { + const code = err.code; + if (!opts.createIfMissing || code !== "ENOENT") { + if (code === "ENOENT") { + throw new Error(`Working directory does not exist: "${cwd}"`); + } + throw err instanceof Error ? err : new Error(String(err)); + } + } + try { + await fs4.mkdir(cwd, { recursive: true }); + await assertDirectory(); + } catch (err) { + const reason = err instanceof Error ? err.message : String(err); + throw new Error(`Could not create working directory "${cwd}": ${reason}`); + } +} +async function resolveTaskcoreSkillsDir(moduleDir, additionalCandidates = []) { + const candidates = [ + ...TASKCORE_SKILL_ROOT_RELATIVE_CANDIDATES.map((relativePath) => path4.resolve(moduleDir, relativePath)), + ...additionalCandidates.map((candidate) => path4.resolve(candidate)) + ]; + const seenRoots = /* @__PURE__ */ new Set(); + for (const root of candidates) { + if (seenRoots.has(root)) continue; + seenRoots.add(root); + const isDirectory = await fs4.stat(root).then((stats) => stats.isDirectory()).catch(() => false); + if (isDirectory) return root; + } + return null; +} +async function listTaskcoreSkillEntries(moduleDir, additionalCandidates = []) { + const root = await resolveTaskcoreSkillsDir(moduleDir, additionalCandidates); + if (!root) return []; + try { + const entries2 = await fs4.readdir(root, { withFileTypes: true }); + return entries2.filter((entry) => entry.isDirectory()).map((entry) => ({ + key: `taskcore/taskcore/${entry.name}`, + runtimeName: entry.name, + source: path4.join(root, entry.name), + required: true, + requiredReason: "Bundled Taskcore skills are always available for local adapters." + })); + } catch { + return []; + } +} +async function readInstalledSkillTargets(skillsHome) { + const entries2 = await fs4.readdir(skillsHome, { withFileTypes: true }).catch(() => []); + const out = /* @__PURE__ */ new Map(); + for (const entry of entries2) { + const fullPath = path4.join(skillsHome, entry.name); + const linkedPath = entry.isSymbolicLink() ? await fs4.readlink(fullPath).catch(() => null) : null; + out.set(entry.name, resolveInstalledEntryTarget(skillsHome, entry.name, entry, linkedPath)); + } + return out; +} +function buildPersistentSkillSnapshot(options) { + const { + adapterType, + availableEntries, + desiredSkills, + installed, + skillsHome, + locationLabel, + installedDetail, + missingDetail, + externalConflictDetail, + externalDetail + } = options; + const availableByKey = new Map(availableEntries.map((entry) => [entry.key, entry])); + const desiredSet = new Set(desiredSkills); + const entries2 = []; + const warnings = [...options.warnings ?? []]; + for (const available of availableEntries) { + const installedEntry = installed.get(available.runtimeName) ?? null; + const desired = desiredSet.has(available.key); + let state2 = "available"; + let managed = false; + let detail = null; + if (installedEntry?.targetPath === available.source) { + managed = true; + state2 = desired ? "installed" : "stale"; + detail = installedDetail ?? null; + } else if (installedEntry) { + state2 = "external"; + detail = desired ? externalConflictDetail : externalDetail; + } else if (desired) { + state2 = "missing"; + detail = missingDetail; + } + entries2.push({ + key: available.key, + runtimeName: available.runtimeName, + desired, + managed, + state: state2, + sourcePath: available.source, + targetPath: path4.join(skillsHome, available.runtimeName), + detail, + required: Boolean(available.required), + requiredReason: available.requiredReason ?? null, + ...buildManagedSkillOrigin(available) + }); + } + for (const desiredSkill of desiredSkills) { + if (availableByKey.has(desiredSkill)) continue; + warnings.push(`Desired skill "${desiredSkill}" is not available from the Taskcore skills directory.`); + entries2.push({ + key: desiredSkill, + runtimeName: null, + desired: true, + managed: true, + state: "missing", + sourcePath: null, + targetPath: null, + detail: "Taskcore cannot find this skill in the local runtime skills directory.", + origin: "external_unknown", + originLabel: "External or unavailable", + readOnly: false + }); + } + for (const [name, installedEntry] of installed.entries()) { + if (availableEntries.some((entry) => entry.runtimeName === name)) continue; + entries2.push({ + key: name, + runtimeName: name, + desired: false, + managed: false, + state: "external", + origin: "user_installed", + originLabel: "User-installed", + locationLabel: skillLocationLabel(locationLabel), + readOnly: true, + sourcePath: null, + targetPath: installedEntry.targetPath ?? path4.join(skillsHome, name), + detail: externalDetail + }); + } + entries2.sort((left, right) => left.key.localeCompare(right.key)); + return { + adapterType, + supported: true, + mode: "persistent", + desiredSkills, + entries: entries2, + warnings + }; +} +function normalizeConfiguredTaskcoreRuntimeSkills(value) { + if (!Array.isArray(value)) return []; + const out = []; + for (const rawEntry of value) { + const entry = parseObject(rawEntry); + const key = asString(entry.key, asString(entry.name, "")).trim(); + const runtimeName = asString(entry.runtimeName, asString(entry.name, "")).trim(); + const source = asString(entry.source, "").trim(); + if (!key || !runtimeName || !source) continue; + out.push({ + key, + runtimeName, + source, + required: asBoolean(entry.required, false), + requiredReason: typeof entry.requiredReason === "string" && entry.requiredReason.trim().length > 0 ? entry.requiredReason.trim() : null + }); + } + return out; +} +async function readTaskcoreRuntimeSkillEntries(config3, moduleDir, additionalCandidates = []) { + const configuredEntries = normalizeConfiguredTaskcoreRuntimeSkills(config3.taskcoreRuntimeSkills); + if (configuredEntries.length > 0) return configuredEntries; + return listTaskcoreSkillEntries(moduleDir, additionalCandidates); +} +function readTaskcoreSkillSyncPreference(config3) { + const raw = config3.taskcoreSkillSync; + if (typeof raw !== "object" || raw === null || Array.isArray(raw)) { + return { explicit: false, desiredSkills: [] }; + } + const syncConfig = raw; + const desiredValues = syncConfig.desiredSkills; + const desired = Array.isArray(desiredValues) ? desiredValues.filter((value) => typeof value === "string").map((value) => value.trim()).filter(Boolean) : []; + return { + explicit: Object.prototype.hasOwnProperty.call(raw, "desiredSkills"), + desiredSkills: Array.from(new Set(desired)) + }; +} +function canonicalizeDesiredTaskcoreSkillReference(reference, availableEntries) { + const normalizedReference = reference.trim().toLowerCase(); + if (!normalizedReference) return ""; + const exactKey = availableEntries.find((entry) => entry.key.trim().toLowerCase() === normalizedReference); + if (exactKey) return exactKey.key; + const byRuntimeName = availableEntries.filter( + (entry) => typeof entry.runtimeName === "string" && entry.runtimeName.trim().toLowerCase() === normalizedReference + ); + if (byRuntimeName.length === 1) return byRuntimeName[0].key; + const slugMatches = availableEntries.filter( + (entry) => entry.key.trim().toLowerCase().split("/").pop() === normalizedReference + ); + if (slugMatches.length === 1) return slugMatches[0].key; + return normalizedReference; +} +function resolveTaskcoreDesiredSkillNames(config3, availableEntries) { + const preference = readTaskcoreSkillSyncPreference(config3); + const requiredSkills = availableEntries.filter((entry) => entry.required).map((entry) => entry.key); + if (!preference.explicit) { + return Array.from(new Set(requiredSkills)); + } + const desiredSkills = preference.desiredSkills.map((reference) => canonicalizeDesiredTaskcoreSkillReference(reference, availableEntries)).filter(Boolean); + return Array.from(/* @__PURE__ */ new Set([...requiredSkills, ...desiredSkills])); +} +function writeTaskcoreSkillSyncPreference(config3, desiredSkills) { + const next = { ...config3 }; + const raw = next.taskcoreSkillSync; + const current = typeof raw === "object" && raw !== null && !Array.isArray(raw) ? { ...raw } : {}; + current.desiredSkills = Array.from( + new Set( + desiredSkills.map((value) => value.trim()).filter(Boolean) + ) + ); + next.taskcoreSkillSync = current; + return next; +} +async function ensureTaskcoreSkillSymlink(source, target, linkSkill = (linkSource, linkTarget) => fs4.symlink(linkSource, linkTarget)) { + const existing = await fs4.lstat(target).catch(() => null); + if (!existing) { + await linkSkill(source, target); + return "created"; + } + if (!existing.isSymbolicLink()) { + return "skipped"; + } + const linkedPath = await fs4.readlink(target).catch(() => null); + if (!linkedPath) return "skipped"; + const resolvedLinkedPath = path4.resolve(path4.dirname(target), linkedPath); + if (resolvedLinkedPath === source) { + return "skipped"; + } + const linkedPathExists = await fs4.stat(resolvedLinkedPath).then(() => true).catch(() => false); + if (linkedPathExists) { + return "skipped"; + } + await fs4.unlink(target); + await linkSkill(source, target); + return "repaired"; +} +async function removeMaintainerOnlySkillSymlinks(skillsHome, allowedSkillNames) { + const allowed2 = new Set(Array.from(allowedSkillNames)); + try { + const entries2 = await fs4.readdir(skillsHome, { withFileTypes: true }); + const removed = []; + for (const entry of entries2) { + if (allowed2.has(entry.name)) continue; + const target = path4.join(skillsHome, entry.name); + const existing = await fs4.lstat(target).catch(() => null); + if (!existing?.isSymbolicLink()) continue; + const linkedPath = await fs4.readlink(target).catch(() => null); + if (!linkedPath) continue; + const resolvedLinkedPath = path4.isAbsolute(linkedPath) ? linkedPath : path4.resolve(path4.dirname(target), linkedPath); + if (!isMaintainerOnlySkillTarget(linkedPath) && !isMaintainerOnlySkillTarget(resolvedLinkedPath)) { + continue; + } + await fs4.unlink(target); + removed.push(entry.name); + } + return removed; + } catch { + return []; + } +} +async function ensureCommandResolvable(command, cwd, env2) { + const resolved = await resolveCommandPath(command, cwd, env2); + if (resolved) return; + if (command.includes("/") || command.includes("\\")) { + const absolute = path4.isAbsolute(command) ? command : path4.resolve(cwd, command); + throw new Error(`Command is not executable: "${command}" (resolved: "${absolute}")`); + } + throw new Error(`Command not found in PATH: "${command}"`); +} +async function runChildProcess(runId, command, args, opts) { + const onLogError = opts.onLogError ?? ((err, id, msg) => console.warn({ err, runId: id }, msg)); + return new Promise((resolve4, reject) => { + const rawMerged = { ...process.env, ...opts.env }; + const CLAUDE_CODE_NESTING_VARS = [ + "CLAUDECODE", + "CLAUDE_CODE_ENTRYPOINT", + "CLAUDE_CODE_SESSION", + "CLAUDE_CODE_PARENT_SESSION" + ]; + for (const key of CLAUDE_CODE_NESTING_VARS) { + delete rawMerged[key]; + } + const mergedEnv = ensurePathInEnv(rawMerged); + void resolveSpawnTarget(command, args, opts.cwd, mergedEnv).then((target) => { + const child = spawn(target.command, target.args, { + cwd: opts.cwd, + env: mergedEnv, + detached: process.platform !== "win32", + shell: false, + stdio: [opts.stdin != null ? "pipe" : "ignore", "pipe", "pipe"] + }); + const startedAt = (/* @__PURE__ */ new Date()).toISOString(); + const processGroupId = resolveProcessGroupId(child); + const spawnPersistPromise = typeof child.pid === "number" && child.pid > 0 && opts.onSpawn ? opts.onSpawn({ pid: child.pid, processGroupId, startedAt }).catch((err) => { + onLogError(err, runId, "failed to record child process metadata"); + }) : Promise.resolve(); + runningProcesses.set(runId, { child, graceSec: opts.graceSec, processGroupId }); + let timedOut = false; + let stdout = ""; + let stderr = ""; + let logChain = Promise.resolve(); + const timeout = opts.timeoutSec > 0 ? setTimeout(() => { + timedOut = true; + signalRunningProcess({ child, processGroupId }, "SIGTERM"); + setTimeout(() => { + signalRunningProcess({ child, processGroupId }, "SIGKILL"); + }, Math.max(1, opts.graceSec) * 1e3); + }, opts.timeoutSec * 1e3) : null; + child.stdout?.on("data", (chunk) => { + const text3 = String(chunk); + stdout = appendWithCap(stdout, text3); + logChain = logChain.then(() => opts.onLog("stdout", text3)).catch((err) => onLogError(err, runId, "failed to append stdout log chunk")); + }); + child.stderr?.on("data", (chunk) => { + const text3 = String(chunk); + stderr = appendWithCap(stderr, text3); + logChain = logChain.then(() => opts.onLog("stderr", text3)).catch((err) => onLogError(err, runId, "failed to append stderr log chunk")); + }); + const stdin = child.stdin; + if (opts.stdin != null && stdin) { + void spawnPersistPromise.finally(() => { + if (child.killed || stdin.destroyed) return; + stdin.write(opts.stdin); + stdin.end(); + }); + } + child.on("error", (err) => { + if (timeout) clearTimeout(timeout); + runningProcesses.delete(runId); + const errno = err.code; + const pathValue = mergedEnv.PATH ?? mergedEnv.Path ?? ""; + const msg = errno === "ENOENT" ? `Failed to start command "${command}" in "${opts.cwd}". Verify adapter command, working directory, and PATH (${pathValue}).` : `Failed to start command "${command}" in "${opts.cwd}": ${err.message}`; + reject(new Error(msg)); + }); + child.on("close", (code, signal) => { + if (timeout) clearTimeout(timeout); + runningProcesses.delete(runId); + void logChain.finally(() => { + resolve4({ + exitCode: code, + signal, + timedOut, + stdout, + stderr, + pid: child.pid ?? null, + startedAt + }); + }); + }); + }).catch(reject); + }); +} + +// packages/adapters/claude-local/src/server/execute.ts +import fs6 from "node:fs/promises"; +import path7 from "node:path"; +import { fileURLToPath as fileURLToPath3 } from "node:url"; + +// packages/adapters/claude-local/src/server/parse.ts +var CLAUDE_AUTH_REQUIRED_RE = /(?:not\s+logged\s+in|please\s+log\s+in|please\s+run\s+`?claude\s+login`?|login\s+required|requires\s+login|unauthorized|authentication\s+required)/i; +var URL_RE = /(https?:\/\/[^\s'"`<>()[\]{};,!?]+[^\s'"`<>()[\]{};,!.?:]+)/gi; +function parseClaudeStreamJson(stdout) { + let sessionId = null; + let model = ""; + let finalResult = null; + const assistantTexts = []; + for (const rawLine of stdout.split(/\r?\n/)) { + const line3 = rawLine.trim(); + if (!line3) continue; + const event = parseJson2(line3); + if (!event) continue; + const type = asString(event.type, ""); + if (type === "system" && asString(event.subtype, "") === "init") { + sessionId = asString(event.session_id, sessionId ?? "") || sessionId; + model = asString(event.model, model); + continue; + } + if (type === "assistant") { + sessionId = asString(event.session_id, sessionId ?? "") || sessionId; + const message2 = parseObject(event.message); + const content = Array.isArray(message2.content) ? message2.content : []; + for (const entry of content) { + if (typeof entry !== "object" || entry === null || Array.isArray(entry)) continue; + const block = entry; + if (asString(block.type, "") === "text") { + const text3 = asString(block.text, ""); + if (text3) assistantTexts.push(text3); + } + } + continue; + } + if (type === "result") { + finalResult = event; + sessionId = asString(event.session_id, sessionId ?? "") || sessionId; + } + } + if (!finalResult) { + return { + sessionId, + model, + costUsd: null, + usage: null, + summary: assistantTexts.join("\n\n").trim(), + resultJson: null + }; + } + const usageObj = parseObject(finalResult.usage); + const usage = { + inputTokens: asNumber(usageObj.input_tokens, 0), + cachedInputTokens: asNumber(usageObj.cache_read_input_tokens, 0), + outputTokens: asNumber(usageObj.output_tokens, 0) + }; + const costRaw = finalResult.total_cost_usd; + const costUsd = typeof costRaw === "number" && Number.isFinite(costRaw) ? costRaw : null; + const summary = asString(finalResult.result, assistantTexts.join("\n\n")).trim(); + return { + sessionId, + model, + costUsd, + usage, + summary, + resultJson: finalResult + }; +} +function extractClaudeErrorMessages(parsed) { + const raw = Array.isArray(parsed.errors) ? parsed.errors : []; + const messages2 = []; + for (const entry of raw) { + if (typeof entry === "string") { + const msg2 = entry.trim(); + if (msg2) messages2.push(msg2); + continue; + } + if (typeof entry !== "object" || entry === null || Array.isArray(entry)) { + continue; + } + const obj = entry; + const msg = asString(obj.message, "") || asString(obj.error, "") || asString(obj.code, ""); + if (msg) { + messages2.push(msg); + continue; + } + try { + messages2.push(JSON.stringify(obj)); + } catch { + } + } + return messages2; +} +function extractClaudeLoginUrl(text3) { + const match = text3.match(URL_RE); + if (!match || match.length === 0) return null; + for (const rawUrl of match) { + const cleaned = rawUrl.replace(/[\])}.!,?;:'\"]+$/g, ""); + if (cleaned.includes("claude") || cleaned.includes("anthropic") || cleaned.includes("auth")) { + return cleaned; + } + } + return match[0]?.replace(/[\])}.!,?;:'\"]+$/g, "") ?? null; +} +function detectClaudeLoginRequired(input) { + const resultText = asString(input.parsed?.result, "").trim(); + const messages2 = [resultText, ...extractClaudeErrorMessages(input.parsed ?? {}), input.stdout, input.stderr].join("\n").split(/\r?\n/).map((line3) => line3.trim()).filter(Boolean); + const requiresLogin = messages2.some((line3) => CLAUDE_AUTH_REQUIRED_RE.test(line3)); + return { + requiresLogin, + loginUrl: extractClaudeLoginUrl([input.stdout, input.stderr].join("\n")) + }; +} +function describeClaudeFailure(parsed) { + const subtype = asString(parsed.subtype, ""); + const resultText = asString(parsed.result, "").trim(); + const errors = extractClaudeErrorMessages(parsed); + let detail = resultText; + if (!detail && errors.length > 0) { + detail = errors[0] ?? ""; + } + const parts = ["Claude run failed"]; + if (subtype) parts.push(`subtype=${subtype}`); + if (detail) parts.push(detail); + return parts.length > 1 ? parts.join(": ") : null; +} +function isClaudeMaxTurnsResult(parsed) { + if (!parsed) return false; + const subtype = asString(parsed.subtype, "").trim().toLowerCase(); + if (subtype === "error_max_turns") return true; + const stopReason = asString(parsed.stop_reason, "").trim().toLowerCase(); + if (stopReason === "max_turns") return true; + const resultText = asString(parsed.result, "").trim(); + return /max(?:imum)?\s+turns?/i.test(resultText); +} +function isClaudeUnknownSessionError(parsed) { + const resultText = asString(parsed.result, "").trim(); + const allMessages = [resultText, ...extractClaudeErrorMessages(parsed)].map((msg) => msg.trim()).filter(Boolean); + return allMessages.some( + (msg) => /no conversation found with session id|unknown session|session .* not found/i.test(msg) + ); +} + +// packages/adapters/claude-local/src/server/skills.ts +import os3 from "node:os"; +import path5 from "node:path"; +import { fileURLToPath as fileURLToPath2 } from "node:url"; +var __moduleDir = path5.dirname(fileURLToPath2(import.meta.url)); +function asString2(value) { + return typeof value === "string" && value.trim().length > 0 ? value.trim() : null; +} +function resolveClaudeSkillsHome(config3) { + const env2 = typeof config3.env === "object" && config3.env !== null && !Array.isArray(config3.env) ? config3.env : {}; + const configuredHome = asString2(env2.HOME); + const home = configuredHome ? path5.resolve(configuredHome) : os3.homedir(); + return path5.join(home, ".claude", "skills"); +} +async function buildClaudeSkillSnapshot(config3) { + const availableEntries = await readTaskcoreRuntimeSkillEntries(config3, __moduleDir); + const availableByKey = new Map(availableEntries.map((entry) => [entry.key, entry])); + const desiredSkills = resolveTaskcoreDesiredSkillNames(config3, availableEntries); + const desiredSet = new Set(desiredSkills); + const skillsHome = resolveClaudeSkillsHome(config3); + const installed = await readInstalledSkillTargets(skillsHome); + const entries2 = availableEntries.map((entry) => ({ + key: entry.key, + runtimeName: entry.runtimeName, + desired: desiredSet.has(entry.key), + managed: true, + state: desiredSet.has(entry.key) ? "configured" : "available", + origin: entry.required ? "taskcore_required" : "company_managed", + originLabel: entry.required ? "Required by Taskcore" : "Managed by Taskcore", + readOnly: false, + sourcePath: entry.source, + targetPath: null, + detail: desiredSet.has(entry.key) ? "Will be materialized into the stable Taskcore-managed Claude prompt bundle on the next run." : null, + required: Boolean(entry.required), + requiredReason: entry.requiredReason ?? null + })); + const warnings = []; + for (const desiredSkill of desiredSkills) { + if (availableByKey.has(desiredSkill)) continue; + warnings.push(`Desired skill "${desiredSkill}" is not available from the Taskcore skills directory.`); + entries2.push({ + key: desiredSkill, + runtimeName: null, + desired: true, + managed: true, + state: "missing", + origin: "external_unknown", + originLabel: "External or unavailable", + readOnly: false, + sourcePath: void 0, + targetPath: void 0, + detail: "Taskcore cannot find this skill in the local runtime skills directory." + }); + } + for (const [name, installedEntry] of installed.entries()) { + if (availableEntries.some((entry) => entry.runtimeName === name)) continue; + entries2.push({ + key: name, + runtimeName: name, + desired: false, + managed: false, + state: "external", + origin: "user_installed", + originLabel: "User-installed", + locationLabel: "~/.claude/skills", + readOnly: true, + sourcePath: null, + targetPath: installedEntry.targetPath ?? path5.join(skillsHome, name), + detail: "Installed outside Taskcore management in the Claude skills home." + }); + } + entries2.sort((left, right) => left.key.localeCompare(right.key)); + return { + adapterType: "claude_local", + supported: true, + mode: "ephemeral", + desiredSkills, + entries: entries2, + warnings + }; +} +async function listClaudeSkills(ctx) { + return buildClaudeSkillSnapshot(ctx.config); +} +async function syncClaudeSkills(ctx, _desiredSkills) { + return buildClaudeSkillSnapshot(ctx.config); +} +function resolveClaudeDesiredSkillNames(config3, availableEntries) { + return resolveTaskcoreDesiredSkillNames(config3, availableEntries); +} + +// packages/adapters/claude-local/src/index.ts +var models = [ + { id: "claude-opus-4-6", label: "Claude Opus 4.6" }, + { id: "claude-sonnet-4-6", label: "Claude Sonnet 4.6" }, + { id: "claude-haiku-4-6", label: "Claude Haiku 4.6" }, + { id: "claude-sonnet-4-5-20250929", label: "Claude Sonnet 4.5" }, + { id: "claude-haiku-4-5-20251001", label: "Claude Haiku 4.5" } +]; +var agentConfigurationDoc = `# claude_local agent configuration + +Adapter: claude_local + +Core fields: +- cwd (string, optional): default absolute working directory fallback for the agent process (created if missing when possible) +- instructionsFilePath (string, optional): absolute path to a markdown instructions file injected at runtime +- model (string, optional): Claude model id +- effort (string, optional): reasoning effort passed via --effort (low|medium|high) +- chrome (boolean, optional): pass --chrome when running Claude +- promptTemplate (string, optional): run prompt template +- maxTurnsPerRun (number, optional): max turns for one run +- dangerouslySkipPermissions (boolean, optional, default true): pass --dangerously-skip-permissions to claude; defaults to true because Taskcore runs Claude in headless --print mode where interactive permission prompts cannot be answered +- command (string, optional): defaults to "claude" +- extraArgs (string[], optional): additional CLI args +- env (object, optional): KEY=VALUE environment variables +- workspaceStrategy (object, optional): execution workspace strategy; currently supports { type: "git_worktree", baseRef?, branchTemplate?, worktreeParentDir? } +- workspaceRuntime (object, optional): reserved for workspace runtime metadata; workspace runtime services are manually controlled from the workspace UI and are not auto-started by heartbeats + +Operational fields: +- timeoutSec (number, optional): run timeout in seconds +- graceSec (number, optional): SIGTERM grace period in seconds + +Notes: +- When Taskcore realizes a workspace/runtime for a run, it injects TASKCORE_WORKSPACE_* and TASKCORE_RUNTIME_* env vars for agent-side tooling. +`; + +// packages/adapters/claude-local/src/server/models.ts +var BEDROCK_MODELS = [ + { id: "us.anthropic.claude-opus-4-6-v1", label: "Bedrock Opus 4.6" }, + { id: "us.anthropic.claude-sonnet-4-5-20250929-v2:0", label: "Bedrock Sonnet 4.5" }, + { id: "us.anthropic.claude-haiku-4-5-20251001-v1:0", label: "Bedrock Haiku 4.5" } +]; +function isBedrockEnv() { + return process.env.CLAUDE_CODE_USE_BEDROCK === "1" || process.env.CLAUDE_CODE_USE_BEDROCK === "true" || typeof process.env.ANTHROPIC_BEDROCK_BASE_URL === "string" && process.env.ANTHROPIC_BEDROCK_BASE_URL.trim().length > 0; +} +async function listClaudeModels() { + return isBedrockEnv() ? BEDROCK_MODELS : models; +} +function isBedrockModelId(model) { + return /^\w+\.anthropic\./.test(model) || model.startsWith("arn:aws:bedrock:"); +} + +// packages/adapters/claude-local/src/server/prompt-cache.ts +import { constants as fsConstants2 } from "node:fs"; +import fs5 from "node:fs/promises"; +import os4 from "node:os"; +import path6 from "node:path"; +import { createHash as createHash3 } from "node:crypto"; +var DEFAULT_TASKCORE_INSTANCE_ID = "default"; +function nonEmpty(value) { + return typeof value === "string" && value.trim().length > 0 ? value.trim() : null; +} +function resolveManagedClaudePromptCacheRoot(env2, companyId) { + const taskcoreHome = nonEmpty(env2.TASKCORE_HOME) ?? path6.resolve(os4.homedir(), ".taskcore"); + const instanceId = nonEmpty(env2.TASKCORE_INSTANCE_ID) ?? DEFAULT_TASKCORE_INSTANCE_ID; + return path6.resolve( + taskcoreHome, + "instances", + instanceId, + "companies", + companyId, + "claude-prompt-cache" + ); +} +async function hashPathContents(candidate, hash2, relativePath, seenDirectories) { + const stat5 = await fs5.lstat(candidate); + if (stat5.isSymbolicLink()) { + hash2.update(`symlink:${relativePath} +`); + const resolved = await fs5.realpath(candidate).catch(() => null); + if (!resolved) { + hash2.update("missing\n"); + return; + } + await hashPathContents(resolved, hash2, relativePath, seenDirectories); + return; + } + if (stat5.isDirectory()) { + const realDir = await fs5.realpath(candidate).catch(() => candidate); + hash2.update(`dir:${relativePath} +`); + if (seenDirectories.has(realDir)) { + hash2.update("loop\n"); + return; + } + seenDirectories.add(realDir); + const entries2 = await fs5.readdir(candidate, { withFileTypes: true }); + entries2.sort((left, right) => left.name.localeCompare(right.name)); + for (const entry of entries2) { + const childRelativePath = relativePath.length > 0 ? `${relativePath}/${entry.name}` : entry.name; + await hashPathContents(path6.join(candidate, entry.name), hash2, childRelativePath, seenDirectories); + } + return; + } + if (stat5.isFile()) { + hash2.update(`file:${relativePath} +`); + hash2.update(await fs5.readFile(candidate)); + hash2.update("\n"); + return; + } + hash2.update(`other:${relativePath}:${stat5.mode} +`); +} +async function buildClaudePromptBundleKey(input) { + const hash2 = createHash3("sha256"); + hash2.update("taskcore-claude-prompt-bundle:v1\n"); + if (input.instructionsContents) { + hash2.update("instructions\n"); + hash2.update(input.instructionsContents); + hash2.update("\n"); + } else { + hash2.update("instructions:none\n"); + } + const sortedSkills = [...input.skills].sort((left, right) => left.runtimeName.localeCompare(right.runtimeName)); + for (const entry of sortedSkills) { + hash2.update(`skill:${entry.key}:${entry.runtimeName} +`); + await hashPathContents(entry.source, hash2, entry.runtimeName, /* @__PURE__ */ new Set()); + } + return hash2.digest("hex"); +} +async function ensureReadableFile(targetPath, contents) { + try { + await fs5.access(targetPath, fsConstants2.R_OK); + return; + } catch { + } + await fs5.mkdir(path6.dirname(targetPath), { recursive: true }); + const tempPath = `${targetPath}.${process.pid}.${Date.now()}.tmp`; + try { + await fs5.writeFile(tempPath, contents, "utf8"); + await fs5.rename(tempPath, targetPath); + } catch (err) { + const targetReadable = await fs5.access(targetPath, fsConstants2.R_OK).then(() => true).catch(() => false); + if (!targetReadable) { + throw err; + } + } finally { + await fs5.rm(tempPath, { force: true }).catch(() => { + }); + } +} +async function prepareClaudePromptBundle(input) { + const { companyId, skills, instructionsContents, onLog } = input; + const bundleKey = await buildClaudePromptBundleKey({ + skills, + instructionsContents + }); + const rootDir = path6.join(resolveManagedClaudePromptCacheRoot(process.env, companyId), bundleKey); + const skillsHome = path6.join(rootDir, ".claude", "skills"); + await fs5.mkdir(skillsHome, { recursive: true }); + for (const entry of skills) { + const target = path6.join(skillsHome, entry.runtimeName); + try { + await ensureTaskcoreSkillSymlink(entry.source, target); + } catch (err) { + await onLog( + "stderr", + `[taskcore] Failed to materialize Claude skill "${entry.key}" into ${skillsHome}: ${err instanceof Error ? err.message : String(err)} +` + ); + } + } + const instructionsFilePath = instructionsContents ? path6.join(rootDir, "agent-instructions.md") : null; + if (instructionsFilePath && instructionsContents) { + await ensureReadableFile(instructionsFilePath, instructionsContents); + } + return { + bundleKey, + rootDir, + addDir: rootDir, + instructionsFilePath + }; +} + +// packages/adapters/claude-local/src/server/execute.ts +var __moduleDir2 = path7.dirname(fileURLToPath3(import.meta.url)); +function buildLoginResult(input) { + return { + exitCode: input.proc.exitCode, + signal: input.proc.signal, + timedOut: input.proc.timedOut, + stdout: input.proc.stdout, + stderr: input.proc.stderr, + loginUrl: input.loginUrl + }; +} +function hasNonEmptyEnvValue(env2, key) { + const raw = env2[key]; + return typeof raw === "string" && raw.trim().length > 0; +} +function isBedrockAuth(env2) { + return env2.CLAUDE_CODE_USE_BEDROCK === "1" || env2.CLAUDE_CODE_USE_BEDROCK === "true" || hasNonEmptyEnvValue(env2, "ANTHROPIC_BEDROCK_BASE_URL"); +} +function resolveClaudeBillingType(env2) { + if (isBedrockAuth(env2)) return "metered_api"; + return hasNonEmptyEnvValue(env2, "ANTHROPIC_API_KEY") ? "api" : "subscription"; +} +async function buildClaudeRuntimeConfig(input) { + const { runId, agent, config: config3, context, authToken } = input; + const command = asString(config3.command, "claude"); + const workspaceContext = parseObject(context.taskcoreWorkspace); + const workspaceCwd = asString(workspaceContext.cwd, ""); + const workspaceSource = asString(workspaceContext.source, ""); + const workspaceStrategy = asString(workspaceContext.strategy, ""); + const workspaceId = asString(workspaceContext.workspaceId, "") || null; + const workspaceRepoUrl = asString(workspaceContext.repoUrl, "") || null; + const workspaceRepoRef = asString(workspaceContext.repoRef, "") || null; + const workspaceBranch = asString(workspaceContext.branchName, "") || null; + const workspaceWorktreePath = asString(workspaceContext.worktreePath, "") || null; + const agentHome = asString(workspaceContext.agentHome, "") || null; + const workspaceHints = Array.isArray(context.taskcoreWorkspaces) ? context.taskcoreWorkspaces.filter( + (value) => typeof value === "object" && value !== null + ) : []; + const runtimeServiceIntents = Array.isArray(context.taskcoreRuntimeServiceIntents) ? context.taskcoreRuntimeServiceIntents.filter( + (value) => typeof value === "object" && value !== null + ) : []; + const runtimeServices = Array.isArray(context.taskcoreRuntimeServices) ? context.taskcoreRuntimeServices.filter( + (value) => typeof value === "object" && value !== null + ) : []; + const runtimePrimaryUrl = asString(context.taskcoreRuntimePrimaryUrl, ""); + const configuredCwd = asString(config3.cwd, ""); + const useConfiguredInsteadOfAgentHome = workspaceSource === "agent_home" && configuredCwd.length > 0; + const effectiveWorkspaceCwd = useConfiguredInsteadOfAgentHome ? "" : workspaceCwd; + const cwd = effectiveWorkspaceCwd || configuredCwd || process.cwd(); + await ensureAbsoluteDirectory(cwd, { createIfMissing: true }); + const envConfig = parseObject(config3.env); + const hasExplicitApiKey = typeof envConfig.TASKCORE_API_KEY === "string" && envConfig.TASKCORE_API_KEY.trim().length > 0; + const env2 = { ...buildTaskcoreEnv(agent) }; + env2.TASKCORE_RUN_ID = runId; + const wakeTaskId = typeof context.taskId === "string" && context.taskId.trim().length > 0 && context.taskId.trim() || typeof context.issueId === "string" && context.issueId.trim().length > 0 && context.issueId.trim() || null; + const wakeReason = typeof context.wakeReason === "string" && context.wakeReason.trim().length > 0 ? context.wakeReason.trim() : null; + const wakeCommentId = typeof context.wakeCommentId === "string" && context.wakeCommentId.trim().length > 0 && context.wakeCommentId.trim() || typeof context.commentId === "string" && context.commentId.trim().length > 0 && context.commentId.trim() || null; + const approvalId = typeof context.approvalId === "string" && context.approvalId.trim().length > 0 ? context.approvalId.trim() : null; + const approvalStatus = typeof context.approvalStatus === "string" && context.approvalStatus.trim().length > 0 ? context.approvalStatus.trim() : null; + const linkedIssueIds = Array.isArray(context.issueIds) ? context.issueIds.filter((value) => typeof value === "string" && value.trim().length > 0) : []; + const wakePayloadJson = stringifyTaskcoreWakePayload(context.taskcoreWake); + if (wakeTaskId) { + env2.TASKCORE_TASK_ID = wakeTaskId; + } + if (wakeReason) { + env2.TASKCORE_WAKE_REASON = wakeReason; + } + if (wakeCommentId) { + env2.TASKCORE_WAKE_COMMENT_ID = wakeCommentId; + } + if (approvalId) { + env2.TASKCORE_APPROVAL_ID = approvalId; + } + if (approvalStatus) { + env2.TASKCORE_APPROVAL_STATUS = approvalStatus; + } + if (linkedIssueIds.length > 0) { + env2.TASKCORE_LINKED_ISSUE_IDS = linkedIssueIds.join(","); + } + if (wakePayloadJson) { + env2.TASKCORE_WAKE_PAYLOAD_JSON = wakePayloadJson; + } + if (effectiveWorkspaceCwd) { + env2.TASKCORE_WORKSPACE_CWD = effectiveWorkspaceCwd; + } + if (workspaceSource) { + env2.TASKCORE_WORKSPACE_SOURCE = workspaceSource; + } + if (workspaceStrategy) { + env2.TASKCORE_WORKSPACE_STRATEGY = workspaceStrategy; + } + if (workspaceId) { + env2.TASKCORE_WORKSPACE_ID = workspaceId; + } + if (workspaceRepoUrl) { + env2.TASKCORE_WORKSPACE_REPO_URL = workspaceRepoUrl; + } + if (workspaceRepoRef) { + env2.TASKCORE_WORKSPACE_REPO_REF = workspaceRepoRef; + } + if (workspaceBranch) { + env2.TASKCORE_WORKSPACE_BRANCH = workspaceBranch; + } + if (workspaceWorktreePath) { + env2.TASKCORE_WORKSPACE_WORKTREE_PATH = workspaceWorktreePath; + } + if (agentHome) { + env2.AGENT_HOME = agentHome; + } + if (workspaceHints.length > 0) { + env2.TASKCORE_WORKSPACES_JSON = JSON.stringify(workspaceHints); + } + if (runtimeServiceIntents.length > 0) { + env2.TASKCORE_RUNTIME_SERVICE_INTENTS_JSON = JSON.stringify(runtimeServiceIntents); + } + if (runtimeServices.length > 0) { + env2.TASKCORE_RUNTIME_SERVICES_JSON = JSON.stringify(runtimeServices); + } + if (runtimePrimaryUrl) { + env2.TASKCORE_RUNTIME_PRIMARY_URL = runtimePrimaryUrl; + } + for (const [key, value] of Object.entries(envConfig)) { + if (typeof value === "string") env2[key] = value; + } + if (!hasExplicitApiKey && authToken) { + env2.TASKCORE_API_KEY = authToken; + } + const runtimeEnv = ensurePathInEnv({ ...process.env, ...env2 }); + await ensureCommandResolvable(command, cwd, runtimeEnv); + const resolvedCommand = await resolveCommandForLogs(command, cwd, runtimeEnv); + const loggedEnv = buildInvocationEnvForLogs(env2, { + runtimeEnv, + includeRuntimeKeys: ["HOME", "CLAUDE_CONFIG_DIR"], + resolvedCommand + }); + const timeoutSec = asNumber(config3.timeoutSec, 0); + const graceSec = asNumber(config3.graceSec, 20); + const extraArgs = (() => { + const fromExtraArgs = asStringArray(config3.extraArgs); + if (fromExtraArgs.length > 0) return fromExtraArgs; + return asStringArray(config3.args); + })(); + return { + command, + resolvedCommand, + cwd, + workspaceId, + workspaceRepoUrl, + workspaceRepoRef, + env: env2, + loggedEnv, + timeoutSec, + graceSec, + extraArgs + }; +} +async function runClaudeLogin(input) { + const onLog = input.onLog ?? (async () => { + }); + const runtime = await buildClaudeRuntimeConfig({ + runId: input.runId, + agent: input.agent, + config: input.config, + context: input.context ?? {}, + authToken: input.authToken + }); + const proc = await runChildProcess(input.runId, runtime.command, ["login"], { + cwd: runtime.cwd, + env: runtime.env, + timeoutSec: runtime.timeoutSec, + graceSec: runtime.graceSec, + onLog + }); + const loginMeta = detectClaudeLoginRequired({ + parsed: null, + stdout: proc.stdout, + stderr: proc.stderr + }); + return buildLoginResult({ + proc, + loginUrl: loginMeta.loginUrl + }); +} +async function execute(ctx) { + const { runId, agent, runtime, config: config3, context, onLog, onMeta, onSpawn, authToken } = ctx; + const promptTemplate = asString( + config3.promptTemplate, + "You are agent {{agent.id}} ({{agent.name}}). Continue your Taskcore work." + ); + const model = asString(config3.model, ""); + const effort = asString(config3.effort, ""); + const chrome = asBoolean(config3.chrome, false); + const maxTurns = asNumber(config3.maxTurnsPerRun, 0); + const dangerouslySkipPermissions = asBoolean(config3.dangerouslySkipPermissions, true); + const instructionsFilePath = asString(config3.instructionsFilePath, "").trim(); + const instructionsFileDir = instructionsFilePath ? `${path7.dirname(instructionsFilePath)}/` : ""; + const runtimeConfig = await buildClaudeRuntimeConfig({ + runId, + agent, + config: config3, + context, + authToken + }); + const { + command, + resolvedCommand, + cwd, + workspaceId, + workspaceRepoUrl, + workspaceRepoRef, + env: env2, + loggedEnv, + timeoutSec, + graceSec, + extraArgs + } = runtimeConfig; + const effectiveEnv = Object.fromEntries( + Object.entries({ ...process.env, ...env2 }).filter( + (entry) => typeof entry[1] === "string" + ) + ); + const billingType = resolveClaudeBillingType(effectiveEnv); + const claudeSkillEntries = await readTaskcoreRuntimeSkillEntries(config3, __moduleDir2); + const desiredSkillNames = new Set(resolveClaudeDesiredSkillNames(config3, claudeSkillEntries)); + let combinedInstructionsContents = null; + if (instructionsFilePath) { + try { + const instructionsContent = await fs6.readFile(instructionsFilePath, "utf-8"); + const pathDirective = ` +The above agent instructions were loaded from ${instructionsFilePath}. Resolve any relative file references from ${instructionsFileDir}. This base directory is authoritative for sibling instruction files such as ./HEARTBEAT.md, ./SOUL.md, and ./TOOLS.md; do not resolve those from the parent agent directory.`; + combinedInstructionsContents = instructionsContent + pathDirective; + } catch (err) { + const reason = err instanceof Error ? err.message : String(err); + await onLog( + "stderr", + `[taskcore] Warning: could not read agent instructions file "${instructionsFilePath}": ${reason} +` + ); + } + } + const promptBundle = await prepareClaudePromptBundle({ + companyId: agent.companyId, + skills: claudeSkillEntries.filter((entry) => desiredSkillNames.has(entry.key)), + instructionsContents: combinedInstructionsContents, + onLog + }); + const effectiveInstructionsFilePath = promptBundle.instructionsFilePath ?? void 0; + const runtimeSessionParams = parseObject(runtime.sessionParams); + const runtimeSessionId = asString(runtimeSessionParams.sessionId, runtime.sessionId ?? ""); + const runtimeSessionCwd = asString(runtimeSessionParams.cwd, ""); + const runtimePromptBundleKey = asString(runtimeSessionParams.promptBundleKey, ""); + const hasMatchingPromptBundle = runtimePromptBundleKey.length === 0 || runtimePromptBundleKey === promptBundle.bundleKey; + const canResumeSession = runtimeSessionId.length > 0 && hasMatchingPromptBundle && (runtimeSessionCwd.length === 0 || path7.resolve(runtimeSessionCwd) === path7.resolve(cwd)); + const sessionId = canResumeSession ? runtimeSessionId : null; + if (runtimeSessionId && runtimeSessionCwd.length > 0 && path7.resolve(runtimeSessionCwd) !== path7.resolve(cwd)) { + await onLog( + "stdout", + `[taskcore] Claude session "${runtimeSessionId}" was saved for cwd "${runtimeSessionCwd}" and will not be resumed in "${cwd}". +` + ); + } + if (runtimeSessionId && runtimePromptBundleKey.length > 0 && runtimePromptBundleKey !== promptBundle.bundleKey) { + await onLog( + "stdout", + `[taskcore] Claude session "${runtimeSessionId}" was saved for prompt bundle "${runtimePromptBundleKey}" and will not be resumed with "${promptBundle.bundleKey}". +` + ); + } + const bootstrapPromptTemplate = asString(config3.bootstrapPromptTemplate, ""); + const templateData = { + agentId: agent.id, + companyId: agent.companyId, + runId, + company: { id: agent.companyId }, + agent, + run: { id: runId, source: "on_demand" }, + context + }; + const renderedBootstrapPrompt = !sessionId && bootstrapPromptTemplate.trim().length > 0 ? renderTemplate(bootstrapPromptTemplate, templateData).trim() : ""; + const wakePrompt = renderTaskcoreWakePrompt(context.taskcoreWake, { resumedSession: Boolean(sessionId) }); + const shouldUseResumeDeltaPrompt = Boolean(sessionId) && wakePrompt.length > 0; + const renderedPrompt = shouldUseResumeDeltaPrompt ? "" : renderTemplate(promptTemplate, templateData); + const sessionHandoffNote = asString(context.taskcoreSessionHandoffMarkdown, "").trim(); + const prompt = joinPromptSections([ + renderedBootstrapPrompt, + wakePrompt, + sessionHandoffNote, + renderedPrompt + ]); + const promptMetrics = { + promptChars: prompt.length, + bootstrapPromptChars: renderedBootstrapPrompt.length, + wakePromptChars: wakePrompt.length, + sessionHandoffChars: sessionHandoffNote.length, + heartbeatPromptChars: renderedPrompt.length + }; + const buildClaudeArgs = (resumeSessionId, attemptInstructionsFilePath) => { + const args = ["--print", "-", "--output-format", "stream-json", "--verbose"]; + if (resumeSessionId) args.push("--resume", resumeSessionId); + if (dangerouslySkipPermissions) args.push("--dangerously-skip-permissions"); + if (chrome) args.push("--chrome"); + if (model && (!isBedrockAuth(effectiveEnv) || isBedrockModelId(model))) { + args.push("--model", model); + } + if (effort) args.push("--effort", effort); + if (maxTurns > 0) args.push("--max-turns", String(maxTurns)); + if (attemptInstructionsFilePath && !resumeSessionId) { + args.push("--append-system-prompt-file", attemptInstructionsFilePath); + } + args.push("--add-dir", promptBundle.addDir); + if (extraArgs.length > 0) args.push(...extraArgs); + return args; + }; + const parseFallbackErrorMessage = (proc) => { + const stderrLine = proc.stderr.split(/\r?\n/).map((line3) => line3.trim()).find(Boolean) ?? ""; + if ((proc.exitCode ?? 0) === 0) { + return "Failed to parse claude JSON output"; + } + return stderrLine ? `Claude exited with code ${proc.exitCode ?? -1}: ${stderrLine}` : `Claude exited with code ${proc.exitCode ?? -1}`; + }; + const runAttempt = async (resumeSessionId) => { + const attemptInstructionsFilePath = resumeSessionId ? void 0 : effectiveInstructionsFilePath; + const args = buildClaudeArgs(resumeSessionId, attemptInstructionsFilePath); + const commandNotes = []; + if (!resumeSessionId) { + commandNotes.push(`Using stable Claude prompt bundle ${promptBundle.bundleKey}.`); + } + if (attemptInstructionsFilePath && !resumeSessionId) { + commandNotes.push( + `Injected agent instructions via --append-system-prompt-file ${instructionsFilePath} (with path directive appended)` + ); + } + if (onMeta) { + await onMeta({ + adapterType: "claude_local", + command: resolvedCommand, + cwd, + commandArgs: args, + commandNotes, + env: loggedEnv, + prompt, + promptMetrics, + context + }); + } + const proc = await runChildProcess(runId, command, args, { + cwd, + env: env2, + stdin: prompt, + timeoutSec, + graceSec, + onSpawn, + onLog + }); + const parsedStream = parseClaudeStreamJson(proc.stdout); + const parsed = parsedStream.resultJson ?? parseJson2(proc.stdout); + return { proc, parsedStream, parsed }; + }; + const toAdapterResult = (attempt, opts) => { + const { proc, parsedStream, parsed } = attempt; + const loginMeta = detectClaudeLoginRequired({ + parsed, + stdout: proc.stdout, + stderr: proc.stderr + }); + const errorMeta = loginMeta.loginUrl != null ? { + loginUrl: loginMeta.loginUrl + } : void 0; + if (proc.timedOut) { + return { + exitCode: proc.exitCode, + signal: proc.signal, + timedOut: true, + errorMessage: `Timed out after ${timeoutSec}s`, + errorCode: "timeout", + errorMeta, + clearSession: Boolean(opts.clearSessionOnMissingSession) + }; + } + if (!parsed) { + return { + exitCode: proc.exitCode, + signal: proc.signal, + timedOut: false, + errorMessage: parseFallbackErrorMessage(proc), + errorCode: loginMeta.requiresLogin ? "claude_auth_required" : null, + errorMeta, + resultJson: { + stdout: proc.stdout, + stderr: proc.stderr + }, + clearSession: Boolean(opts.clearSessionOnMissingSession) + }; + } + const usage = parsedStream.usage ?? (() => { + const usageObj = parseObject(parsed.usage); + return { + inputTokens: asNumber(usageObj.input_tokens, 0), + cachedInputTokens: asNumber(usageObj.cache_read_input_tokens, 0), + outputTokens: asNumber(usageObj.output_tokens, 0) + }; + })(); + const resolvedSessionId = parsedStream.sessionId ?? (asString(parsed.session_id, opts.fallbackSessionId ?? "") || opts.fallbackSessionId); + const resolvedSessionParams = resolvedSessionId ? { + sessionId: resolvedSessionId, + cwd, + promptBundleKey: promptBundle.bundleKey, + ...workspaceId ? { workspaceId } : {}, + ...workspaceRepoUrl ? { repoUrl: workspaceRepoUrl } : {}, + ...workspaceRepoRef ? { repoRef: workspaceRepoRef } : {} + } : null; + const clearSessionForMaxTurns = isClaudeMaxTurnsResult(parsed); + return { + exitCode: proc.exitCode, + signal: proc.signal, + timedOut: false, + errorMessage: (proc.exitCode ?? 0) === 0 ? null : describeClaudeFailure(parsed) ?? `Claude exited with code ${proc.exitCode ?? -1}`, + errorCode: loginMeta.requiresLogin ? "claude_auth_required" : null, + errorMeta, + usage, + sessionId: resolvedSessionId, + sessionParams: resolvedSessionParams, + sessionDisplayId: resolvedSessionId, + provider: "anthropic", + biller: isBedrockAuth(effectiveEnv) ? "aws_bedrock" : "anthropic", + model: parsedStream.model || asString(parsed.model, model), + billingType, + costUsd: parsedStream.costUsd ?? asNumber(parsed.total_cost_usd, 0), + resultJson: parsed, + summary: parsedStream.summary || asString(parsed.result, ""), + clearSession: clearSessionForMaxTurns || Boolean(opts.clearSessionOnMissingSession && !resolvedSessionId) + }; + }; + const initial = await runAttempt(sessionId ?? null); + if (sessionId && !initial.proc.timedOut && (initial.proc.exitCode ?? 0) !== 0 && initial.parsed && isClaudeUnknownSessionError(initial.parsed)) { + await onLog( + "stdout", + `[taskcore] Claude resume session "${sessionId}" is unavailable; retrying with a fresh session. +` + ); + const retry = await runAttempt(null); + return toAdapterResult(retry, { fallbackSessionId: null, clearSessionOnMissingSession: true }); + } + return toAdapterResult(initial, { fallbackSessionId: runtimeSessionId || runtime.sessionId }); +} + +// packages/adapters/claude-local/src/server/test.ts +import path8 from "node:path"; +function summarizeStatus(checks) { + if (checks.some((check3) => check3.level === "error")) return "fail"; + if (checks.some((check3) => check3.level === "warn")) return "warn"; + return "pass"; +} +function isNonEmpty(value) { + return typeof value === "string" && value.trim().length > 0; +} +function firstNonEmptyLine(text3) { + return text3.split(/\r?\n/).map((line3) => line3.trim()).find(Boolean) ?? ""; +} +function commandLooksLike(command, expected) { + const base = path8.basename(command).toLowerCase(); + return base === expected || base === `${expected}.cmd` || base === `${expected}.exe`; +} +function summarizeProbeDetail(stdout, stderr) { + const raw = firstNonEmptyLine(stderr) || firstNonEmptyLine(stdout); + if (!raw) return null; + const clean3 = raw.replace(/\s+/g, " ").trim(); + const max = 240; + return clean3.length > max ? `${clean3.slice(0, max - 1)}\u2026` : clean3; +} +async function testEnvironment(ctx) { + const checks = []; + const config3 = parseObject(ctx.config); + const command = asString(config3.command, "claude"); + const cwd = asString(config3.cwd, process.cwd()); + try { + await ensureAbsoluteDirectory(cwd, { createIfMissing: true }); + checks.push({ + code: "claude_cwd_valid", + level: "info", + message: `Working directory is valid: ${cwd}` + }); + } catch (err) { + checks.push({ + code: "claude_cwd_invalid", + level: "error", + message: err instanceof Error ? err.message : "Invalid working directory", + detail: cwd + }); + } + const envConfig = parseObject(config3.env); + const env2 = {}; + for (const [key, value] of Object.entries(envConfig)) { + if (typeof value === "string") env2[key] = value; + } + const runtimeEnv = ensurePathInEnv({ ...process.env, ...env2 }); + try { + await ensureCommandResolvable(command, cwd, runtimeEnv); + checks.push({ + code: "claude_command_resolvable", + level: "info", + message: `Command is executable: ${command}` + }); + } catch (err) { + checks.push({ + code: "claude_command_unresolvable", + level: "error", + message: err instanceof Error ? err.message : "Command is not executable", + detail: command + }); + } + const hasBedrock = env2.CLAUDE_CODE_USE_BEDROCK === "1" || env2.CLAUDE_CODE_USE_BEDROCK === "true" || process.env.CLAUDE_CODE_USE_BEDROCK === "1" || process.env.CLAUDE_CODE_USE_BEDROCK === "true" || isNonEmpty(env2.ANTHROPIC_BEDROCK_BASE_URL) || isNonEmpty(process.env.ANTHROPIC_BEDROCK_BASE_URL); + const configApiKey = env2.ANTHROPIC_API_KEY; + const hostApiKey = process.env.ANTHROPIC_API_KEY; + if (hasBedrock) { + const source = env2.CLAUDE_CODE_USE_BEDROCK === "1" || env2.CLAUDE_CODE_USE_BEDROCK === "true" || isNonEmpty(env2.ANTHROPIC_BEDROCK_BASE_URL) ? "adapter config env" : "server environment"; + checks.push({ + code: "claude_bedrock_auth", + level: "info", + message: "AWS Bedrock auth detected. Claude will use Bedrock for inference.", + detail: `Detected in ${source}.`, + hint: "Ensure AWS credentials (AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY or AWS_PROFILE) and AWS_REGION are configured." + }); + } else if (isNonEmpty(configApiKey) || isNonEmpty(hostApiKey)) { + const source = isNonEmpty(configApiKey) ? "adapter config env" : "server environment"; + checks.push({ + code: "claude_anthropic_api_key_overrides_subscription", + level: "warn", + message: "ANTHROPIC_API_KEY is set. Claude will use API-key auth instead of subscription credentials.", + detail: `Detected in ${source}.`, + hint: "Unset ANTHROPIC_API_KEY if you want subscription-based Claude login behavior." + }); + } else { + checks.push({ + code: "claude_subscription_mode_possible", + level: "info", + message: "ANTHROPIC_API_KEY is not set; subscription-based auth can be used if Claude is logged in." + }); + } + const canRunProbe = checks.every((check3) => check3.code !== "claude_cwd_invalid" && check3.code !== "claude_command_unresolvable"); + if (canRunProbe) { + if (!commandLooksLike(command, "claude")) { + checks.push({ + code: "claude_hello_probe_skipped_custom_command", + level: "info", + message: "Skipped hello probe because command is not `claude`.", + detail: command, + hint: "Use the `claude` CLI command to run the automatic login and installation probe." + }); + } else { + const model = asString(config3.model, "").trim(); + const effort = asString(config3.effort, "").trim(); + const chrome = asBoolean(config3.chrome, false); + const maxTurns = asNumber(config3.maxTurnsPerRun, 0); + const dangerouslySkipPermissions = asBoolean(config3.dangerouslySkipPermissions, true); + const extraArgs = (() => { + const fromExtraArgs = asStringArray(config3.extraArgs); + if (fromExtraArgs.length > 0) return fromExtraArgs; + return asStringArray(config3.args); + })(); + const args = ["--print", "-", "--output-format", "stream-json", "--verbose"]; + if (dangerouslySkipPermissions) args.push("--dangerously-skip-permissions"); + if (chrome) args.push("--chrome"); + if (model && (!hasBedrock || isBedrockModelId(model))) { + args.push("--model", model); + } + if (effort) args.push("--effort", effort); + if (maxTurns > 0) args.push("--max-turns", String(maxTurns)); + if (extraArgs.length > 0) args.push(...extraArgs); + const probe = await runChildProcess( + `claude-envtest-${Date.now()}-${Math.random().toString(16).slice(2)}`, + command, + args, + { + cwd, + env: env2, + timeoutSec: 45, + graceSec: 5, + stdin: "Respond with hello.", + onLog: async () => { + } + } + ); + const parsedStream = parseClaudeStreamJson(probe.stdout); + const parsed = parsedStream.resultJson; + const loginMeta = detectClaudeLoginRequired({ + parsed, + stdout: probe.stdout, + stderr: probe.stderr + }); + const detail = summarizeProbeDetail(probe.stdout, probe.stderr); + if (probe.timedOut) { + checks.push({ + code: "claude_hello_probe_timed_out", + level: "warn", + message: "Claude hello probe timed out.", + hint: "Retry the probe. If this persists, verify Claude can run `Respond with hello` from this directory manually." + }); + } else if (loginMeta.requiresLogin) { + checks.push({ + code: "claude_hello_probe_auth_required", + level: "warn", + message: "Claude CLI is installed, but login is required.", + ...detail ? { detail } : {}, + hint: loginMeta.loginUrl ? `Run \`claude login\` and complete sign-in at ${loginMeta.loginUrl}, then retry.` : "Run `claude login` in this environment, then retry the probe." + }); + } else if ((probe.exitCode ?? 1) === 0) { + const summary = parsedStream.summary.trim(); + const hasHello = /\bhello\b/i.test(summary); + checks.push({ + code: hasHello ? "claude_hello_probe_passed" : "claude_hello_probe_unexpected_output", + level: hasHello ? "info" : "warn", + message: hasHello ? "Claude hello probe succeeded." : "Claude probe ran but did not return `hello` as expected.", + ...summary ? { detail: summary.replace(/\s+/g, " ").trim().slice(0, 240) } : {}, + ...hasHello ? {} : { + hint: "Try the probe manually (`claude --print - --output-format stream-json --verbose`) and prompt `Respond with hello`." + } + }); + } else { + checks.push({ + code: "claude_hello_probe_failed", + level: "error", + message: "Claude hello probe failed.", + ...detail ? { detail } : {}, + hint: "Run `claude --print - --output-format stream-json --verbose` manually in this directory and prompt `Respond with hello` to debug." + }); + } + } + } + return { + adapterType: ctx.adapterType, + status: summarizeStatus(checks), + checks, + testedAt: (/* @__PURE__ */ new Date()).toISOString() + }; +} + +// packages/adapters/claude-local/src/server/quota.ts +import { execFile } from "node:child_process"; +import fs7 from "node:fs/promises"; +import os5 from "node:os"; +import path9 from "node:path"; +import { promisify } from "node:util"; +var execFileAsync = promisify(execFile); +var CLAUDE_USAGE_SOURCE_OAUTH = "anthropic-oauth"; +var CLAUDE_USAGE_SOURCE_CLI = "claude-cli"; +function claudeConfigDir() { + const fromEnv = process.env.CLAUDE_CONFIG_DIR; + if (typeof fromEnv === "string" && fromEnv.trim().length > 0) return fromEnv.trim(); + return path9.join(os5.homedir(), ".claude"); +} +function hasNonEmptyProcessEnv(key) { + const value = process.env[key]; + return typeof value === "string" && value.trim().length > 0; +} +function createClaudeQuotaEnv() { + const env2 = {}; + for (const [key, value] of Object.entries(process.env)) { + if (typeof value !== "string") continue; + if (key.startsWith("ANTHROPIC_")) continue; + env2[key] = value; + } + return env2; +} +function stripBackspaces(text3) { + let out = ""; + for (const char2 of text3) { + if (char2 === "\b") { + out = out.slice(0, -1); + } else { + out += char2; + } + } + return out; +} +function stripAnsi(text3) { + return text3.replace(/\u001B\][^\u0007]*(?:\u0007|\u001B\\)/g, "").replace(/\u001B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g, ""); +} +function cleanTerminalText(text3) { + return stripAnsi(stripBackspaces(text3)).replace(/\u0000/g, "").replace(/\r/g, "\n"); +} +function normalizeForLabelSearch(text3) { + return text3.toLowerCase().replace(/[^a-z0-9]+/g, ""); +} +function trimToLatestUsagePanel(text3) { + const lower = text3.toLowerCase(); + const settingsIndex = lower.lastIndexOf("settings:"); + if (settingsIndex < 0) return null; + let tail = text3.slice(settingsIndex); + const tailLower = tail.toLowerCase(); + if (!tailLower.includes("usage")) return null; + if (!tailLower.includes("current session") && !tailLower.includes("loading usage")) return null; + const stopMarkers = [ + "status dialog dismissed", + "checking for updates", + "press ctrl-c again to exit" + ]; + let stopIndex = -1; + for (const marker of stopMarkers) { + const markerIndex = tailLower.indexOf(marker); + if (markerIndex >= 0 && (stopIndex === -1 || markerIndex < stopIndex)) { + stopIndex = markerIndex; + } + } + if (stopIndex >= 0) { + tail = tail.slice(0, stopIndex); + } + return tail; +} +async function readClaudeTokenFromFile(credPath) { + let raw; + try { + raw = await fs7.readFile(credPath, "utf8"); + } catch { + return null; + } + let parsed; + try { + parsed = JSON.parse(raw); + } catch { + return null; + } + if (typeof parsed !== "object" || parsed === null) return null; + const obj = parsed; + const oauth = obj["claudeAiOauth"]; + if (typeof oauth !== "object" || oauth === null) return null; + const token = oauth["accessToken"]; + return typeof token === "string" && token.length > 0 ? token : null; +} +async function readClaudeAuthStatus() { + try { + const { stdout } = await execFileAsync("claude", ["auth", "status"], { + env: process.env, + timeout: 5e3, + maxBuffer: 1024 * 1024 + }); + const parsed = JSON.parse(stdout); + return { + loggedIn: parsed.loggedIn === true, + authMethod: typeof parsed.authMethod === "string" ? parsed.authMethod : null, + subscriptionType: typeof parsed.subscriptionType === "string" ? parsed.subscriptionType : null + }; + } catch { + return null; + } +} +function describeClaudeSubscriptionAuth(status) { + if (!status?.loggedIn || status.authMethod !== "claude.ai") return null; + return status.subscriptionType ? `Claude is logged in via claude.ai (${status.subscriptionType})` : "Claude is logged in via claude.ai"; +} +async function readClaudeToken() { + const configDir = claudeConfigDir(); + for (const filename of [".credentials.json", "credentials.json"]) { + const token = await readClaudeTokenFromFile(path9.join(configDir, filename)); + if (token) return token; + } + return null; +} +function formatCurrencyAmount(value, currency) { + const code = typeof currency === "string" && currency.trim().length > 0 ? currency.trim().toUpperCase() : "USD"; + return new Intl.NumberFormat("en-US", { + style: "currency", + currency: code, + maximumFractionDigits: 2 + }).format(value); +} +function formatExtraUsageLabel(extraUsage) { + const monthlyLimit = extraUsage.monthly_limit; + const usedCredits = extraUsage.used_credits; + if (typeof monthlyLimit !== "number" || !Number.isFinite(monthlyLimit) || typeof usedCredits !== "number" || !Number.isFinite(usedCredits)) { + return null; + } + return `${formatCurrencyAmount(usedCredits, extraUsage.currency)} / ${formatCurrencyAmount(monthlyLimit, extraUsage.currency)}`; +} +function toPercent(utilization) { + if (utilization == null) return null; + return Math.min(100, Math.round(utilization * 100)); +} +async function fetchWithTimeout(url2, init2, ms = 8e3) { + const controller = new AbortController(); + const timer2 = setTimeout(() => controller.abort(), ms); + try { + return await fetch(url2, { ...init2, signal: controller.signal }); + } finally { + clearTimeout(timer2); + } +} +async function fetchClaudeQuota(token) { + const resp = await fetchWithTimeout("https://api.anthropic.com/api/oauth/usage", { + headers: { + Authorization: `Bearer ${token}`, + "anthropic-beta": "oauth-2025-04-20" + } + }); + if (!resp.ok) throw new Error(`anthropic usage api returned ${resp.status}`); + const body = await resp.json(); + const windows = []; + if (body.five_hour != null) { + windows.push({ + label: "Current session", + usedPercent: toPercent(body.five_hour.utilization), + resetsAt: body.five_hour.resets_at ?? null, + valueLabel: null, + detail: null + }); + } + if (body.seven_day != null) { + windows.push({ + label: "Current week (all models)", + usedPercent: toPercent(body.seven_day.utilization), + resetsAt: body.seven_day.resets_at ?? null, + valueLabel: null, + detail: null + }); + } + if (body.seven_day_sonnet != null) { + windows.push({ + label: "Current week (Sonnet only)", + usedPercent: toPercent(body.seven_day_sonnet.utilization), + resetsAt: body.seven_day_sonnet.resets_at ?? null, + valueLabel: null, + detail: null + }); + } + if (body.seven_day_opus != null) { + windows.push({ + label: "Current week (Opus only)", + usedPercent: toPercent(body.seven_day_opus.utilization), + resetsAt: body.seven_day_opus.resets_at ?? null, + valueLabel: null, + detail: null + }); + } + if (body.extra_usage != null) { + windows.push({ + label: "Extra usage", + usedPercent: body.extra_usage.is_enabled === false ? null : toPercent(body.extra_usage.utilization), + resetsAt: null, + valueLabel: body.extra_usage.is_enabled === false ? "Not enabled" : formatExtraUsageLabel(body.extra_usage), + detail: body.extra_usage.is_enabled === false ? "Extra usage not enabled" : "Monthly extra usage pool" + }); + } + return windows; +} +function usageOutputLooksRelevant(text3) { + const normalized = normalizeForLabelSearch(text3); + return normalized.includes("currentsession") || normalized.includes("currentweek") || normalized.includes("loadingusage") || normalized.includes("failedtoloadusagedata") || normalized.includes("tokenexpired") || normalized.includes("authenticationerror") || normalized.includes("ratelimited"); +} +function usageOutputLooksComplete(text3) { + const normalized = normalizeForLabelSearch(text3); + if (normalized.includes("failedtoloadusagedata") || normalized.includes("tokenexpired") || normalized.includes("authenticationerror") || normalized.includes("ratelimited")) { + return true; + } + return normalized.includes("currentsession") && (normalized.includes("currentweek") || normalized.includes("extrausage")) && /[0-9]{1,3}(?:\.[0-9]+)?%/i.test(text3); +} +function extractUsageError(text3) { + const lower = text3.toLowerCase(); + const compact = lower.replace(/\s+/g, ""); + if (lower.includes("token_expired") || lower.includes("token has expired")) { + return "Claude CLI token expired. Run `claude login` to refresh."; + } + if (lower.includes("authentication_error")) { + return "Claude CLI authentication error. Run `claude login`."; + } + if (lower.includes("rate_limit_error") || lower.includes("rate limited") || compact.includes("ratelimited")) { + return "Claude CLI usage endpoint is rate limited right now. Please try again later."; + } + if (lower.includes("failed to load usage data") || compact.includes("failedtoloadusagedata")) { + return "Claude CLI could not load usage data. Open the CLI and retry `/usage`."; + } + return null; +} +function percentFromLine(line3) { + const match = line3.match(/([0-9]{1,3}(?:\.[0-9]+)?)\s*%/i); + if (!match) return null; + const rawValue = Number(match[1]); + if (!Number.isFinite(rawValue)) return null; + const clamped = Math.min(100, Math.max(0, rawValue)); + const lower = line3.toLowerCase(); + if (lower.includes("remaining") || lower.includes("left") || lower.includes("available")) { + return Math.max(0, Math.min(100, Math.round(100 - clamped))); + } + return Math.round(clamped); +} +function isQuotaLabel(line3) { + const normalized = normalizeForLabelSearch(line3); + return normalized === "currentsession" || normalized === "currentweekallmodels" || normalized === "currentweeksonnetonly" || normalized === "currentweeksonnet" || normalized === "currentweekopusonly" || normalized === "currentweekopus" || normalized === "extrausage"; +} +function canonicalQuotaLabel(line3) { + switch (normalizeForLabelSearch(line3)) { + case "currentsession": + return "Current session"; + case "currentweekallmodels": + return "Current week (all models)"; + case "currentweeksonnetonly": + case "currentweeksonnet": + return "Current week (Sonnet only)"; + case "currentweekopusonly": + case "currentweekopus": + return "Current week (Opus only)"; + case "extrausage": + return "Extra usage"; + default: + return line3; + } +} +function formatClaudeCliDetail(label, lines) { + const normalizedLabel = normalizeForLabelSearch(label); + if (normalizedLabel === "extrausage") { + const compact = lines.join(" ").replace(/\s+/g, "").toLowerCase(); + if (compact.includes("extrausagenotenabled")) { + return "Extra usage not enabled \u2022 /extra-usage to enable"; + } + const firstLine = lines.find((line3) => line3.trim().length > 0) ?? null; + return firstLine; + } + const resetLine = lines.find((line3) => /^resets/i.test(line3) || normalizeForLabelSearch(line3).startsWith("resets")); + if (!resetLine) return null; + return resetLine.replace(/^Resets/i, "Resets ").replace(/([A-Z][a-z]{2})(\d)/g, "$1 $2").replace(/(\d)at(\d)/g, "$1 at $2").replace(/(am|pm)\(/gi, "$1 (").replace(/([A-Za-z])\(/g, "$1 (").replace(/\s+/g, " ").trim(); +} +function parseClaudeCliUsageText(text3) { + const cleaned = trimToLatestUsagePanel(cleanTerminalText(text3)) ?? cleanTerminalText(text3); + const usageError = extractUsageError(cleaned); + if (usageError) throw new Error(usageError); + const lines = cleaned.split("\n").map((line3) => line3.trim()).filter((line3) => line3.length > 0); + const sections = []; + let current = null; + for (const line3 of lines) { + if (isQuotaLabel(line3)) { + if (current) sections.push(current); + current = { label: canonicalQuotaLabel(line3), lines: [] }; + continue; + } + if (current) current.lines.push(line3); + } + if (current) sections.push(current); + const windows = sections.map((section) => { + const usedPercent = section.lines.map(percentFromLine).find((value) => value != null) ?? null; + return { + label: section.label, + usedPercent, + resetsAt: null, + valueLabel: null, + detail: formatClaudeCliDetail(section.label, section.lines) + }; + }); + if (!windows.some((window2) => normalizeForLabelSearch(window2.label) === "currentsession")) { + throw new Error("Could not parse Claude CLI usage output."); + } + return windows; +} +function quoteForShell(value) { + return `'${value.replace(/'/g, `'\\''`)}'`; +} +function buildClaudeCliShellProbeCommand() { + const feed = "(sleep 2; printf '/usage\\r'; sleep 6; printf '\\033'; sleep 1; printf '\\003')"; + const claudeCommand = 'claude --tools ""'; + if (process.platform === "darwin") { + return `${feed} | script -q /dev/null ${claudeCommand}`; + } + return `${feed} | script -q -e -f -c ${quoteForShell(claudeCommand)} /dev/null`; +} +async function captureClaudeCliUsageText(timeoutMs = 12e3) { + const command = buildClaudeCliShellProbeCommand(); + try { + const { stdout, stderr } = await execFileAsync("sh", ["-c", command], { + env: createClaudeQuotaEnv(), + timeout: timeoutMs, + maxBuffer: 8 * 1024 * 1024 + }); + const output = `${stdout}${stderr}`; + const cleaned = cleanTerminalText(output); + if (usageOutputLooksComplete(cleaned)) return output; + throw new Error("Claude CLI usage probe ended before rendering usage."); + } catch (error50) { + const stdout = typeof error50 === "object" && error50 !== null && "stdout" in error50 && typeof error50.stdout === "string" ? error50.stdout : ""; + const stderr = typeof error50 === "object" && error50 !== null && "stderr" in error50 && typeof error50.stderr === "string" ? error50.stderr : ""; + const output = `${stdout}${stderr}`; + const cleaned = cleanTerminalText(output); + if (usageOutputLooksComplete(cleaned)) return output; + if (usageOutputLooksRelevant(cleaned)) { + throw new Error("Claude CLI usage probe ended before rendering usage."); + } + throw error50 instanceof Error ? error50 : new Error(String(error50)); + } +} +async function fetchClaudeCliQuota() { + const rawText = await captureClaudeCliUsageText(); + return parseClaudeCliUsageText(rawText); +} +function formatProviderError(source, error50) { + const message2 = error50 instanceof Error ? error50.message : String(error50); + return `${source}: ${message2}`; +} +async function getQuotaWindows() { + if (process.env.CLAUDE_CODE_USE_BEDROCK === "1" || process.env.CLAUDE_CODE_USE_BEDROCK === "true" || hasNonEmptyProcessEnv("ANTHROPIC_BEDROCK_BASE_URL")) { + return { provider: "anthropic", source: "bedrock", ok: true, windows: [] }; + } + const authStatus = await readClaudeAuthStatus(); + const authDescription = describeClaudeSubscriptionAuth(authStatus); + const token = await readClaudeToken(); + const errors = []; + if (token) { + try { + const windows = await fetchClaudeQuota(token); + return { provider: "anthropic", source: CLAUDE_USAGE_SOURCE_OAUTH, ok: true, windows }; + } catch (error50) { + errors.push(formatProviderError("Anthropic OAuth usage", error50)); + } + } + try { + const windows = await fetchClaudeCliQuota(); + return { provider: "anthropic", source: CLAUDE_USAGE_SOURCE_CLI, ok: true, windows }; + } catch (error50) { + errors.push(formatProviderError("Claude CLI /usage", error50)); + } + if (hasNonEmptyProcessEnv("ANTHROPIC_API_KEY") && !authDescription) { + return { + provider: "anthropic", + ok: false, + error: errors[0] ?? "ANTHROPIC_API_KEY is set and no local Claude subscription session is available for quota polling", + windows: [] + }; + } + if (authDescription) { + return { + provider: "anthropic", + ok: false, + error: errors.length > 0 ? `${authDescription}, but quota polling failed (${errors.join("; ")})` : `${authDescription}, but Taskcore could not load subscription quota data`, + windows: [] + }; + } + return { + provider: "anthropic", + ok: false, + error: errors[0] ?? "no local claude auth token", + windows: [] + }; +} + +// packages/adapters/claude-local/src/server/index.ts +function readNonEmptyString2(value) { + return typeof value === "string" && value.trim().length > 0 ? value.trim() : null; +} +var sessionCodec = { + deserialize(raw) { + if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return null; + const record2 = raw; + const sessionId = readNonEmptyString2(record2.sessionId) ?? readNonEmptyString2(record2.session_id); + if (!sessionId) return null; + const cwd = readNonEmptyString2(record2.cwd) ?? readNonEmptyString2(record2.workdir) ?? readNonEmptyString2(record2.folder); + const promptBundleKey = readNonEmptyString2(record2.promptBundleKey) ?? readNonEmptyString2(record2.prompt_bundle_key); + const workspaceId = readNonEmptyString2(record2.workspaceId) ?? readNonEmptyString2(record2.workspace_id); + const repoUrl = readNonEmptyString2(record2.repoUrl) ?? readNonEmptyString2(record2.repo_url); + const repoRef = readNonEmptyString2(record2.repoRef) ?? readNonEmptyString2(record2.repo_ref); + return { + sessionId, + ...cwd ? { cwd } : {}, + ...promptBundleKey ? { promptBundleKey } : {}, + ...workspaceId ? { workspaceId } : {}, + ...repoUrl ? { repoUrl } : {}, + ...repoRef ? { repoRef } : {} + }; + }, + serialize(params) { + if (!params) return null; + const sessionId = readNonEmptyString2(params.sessionId) ?? readNonEmptyString2(params.session_id); + if (!sessionId) return null; + const cwd = readNonEmptyString2(params.cwd) ?? readNonEmptyString2(params.workdir) ?? readNonEmptyString2(params.folder); + const promptBundleKey = readNonEmptyString2(params.promptBundleKey) ?? readNonEmptyString2(params.prompt_bundle_key); + const workspaceId = readNonEmptyString2(params.workspaceId) ?? readNonEmptyString2(params.workspace_id); + const repoUrl = readNonEmptyString2(params.repoUrl) ?? readNonEmptyString2(params.repo_url); + const repoRef = readNonEmptyString2(params.repoRef) ?? readNonEmptyString2(params.repo_ref); + return { + sessionId, + ...cwd ? { cwd } : {}, + ...promptBundleKey ? { promptBundleKey } : {}, + ...workspaceId ? { workspaceId } : {}, + ...repoUrl ? { repoUrl } : {}, + ...repoRef ? { repoRef } : {} + }; + }, + getDisplayId(params) { + if (!params) return null; + return readNonEmptyString2(params.sessionId) ?? readNonEmptyString2(params.session_id); + } +}; + +// packages/adapters/codex-local/src/server/execute.ts +import fs9 from "node:fs/promises"; +import path12 from "node:path"; +import { fileURLToPath as fileURLToPath5 } from "node:url"; + +// packages/adapter-utils/src/session-compaction.ts +var DEFAULT_SESSION_COMPACTION_POLICY = { + enabled: true, + maxSessionRuns: 200, + maxRawInputTokens: 2e6, + maxSessionAgeHours: 72 +}; +var ADAPTER_MANAGED_SESSION_POLICY = { + enabled: true, + maxSessionRuns: 0, + maxRawInputTokens: 0, + maxSessionAgeHours: 0 +}; +var LEGACY_SESSIONED_ADAPTER_TYPES = /* @__PURE__ */ new Set([ + "claude_local", + "codex_local", + "cursor", + "gemini_local", + "hermes_local", + "opencode_local", + "pi_local" +]); +var ADAPTER_SESSION_MANAGEMENT = { + claude_local: { + supportsSessionResume: true, + nativeContextManagement: "confirmed", + defaultSessionCompaction: ADAPTER_MANAGED_SESSION_POLICY + }, + codex_local: { + supportsSessionResume: true, + nativeContextManagement: "confirmed", + defaultSessionCompaction: ADAPTER_MANAGED_SESSION_POLICY + }, + cursor: { + supportsSessionResume: true, + nativeContextManagement: "unknown", + defaultSessionCompaction: DEFAULT_SESSION_COMPACTION_POLICY + }, + gemini_local: { + supportsSessionResume: true, + nativeContextManagement: "unknown", + defaultSessionCompaction: DEFAULT_SESSION_COMPACTION_POLICY + }, + opencode_local: { + supportsSessionResume: true, + nativeContextManagement: "unknown", + defaultSessionCompaction: DEFAULT_SESSION_COMPACTION_POLICY + }, + pi_local: { + supportsSessionResume: true, + nativeContextManagement: "unknown", + defaultSessionCompaction: DEFAULT_SESSION_COMPACTION_POLICY + }, + hermes_local: { + supportsSessionResume: true, + nativeContextManagement: "confirmed", + defaultSessionCompaction: ADAPTER_MANAGED_SESSION_POLICY + } +}; +function isRecord2(value) { + return typeof value === "object" && value !== null && !Array.isArray(value); +} +function readBoolean(value) { + if (typeof value === "boolean") return value; + if (typeof value === "number") { + if (value === 1) return true; + if (value === 0) return false; + return void 0; + } + if (typeof value !== "string") return void 0; + const normalized = value.trim().toLowerCase(); + if (normalized === "true" || normalized === "1" || normalized === "yes" || normalized === "on") { + return true; + } + if (normalized === "false" || normalized === "0" || normalized === "no" || normalized === "off") { + return false; + } + return void 0; +} +function readNumber(value) { + if (typeof value === "number" && Number.isFinite(value)) { + return Math.max(0, Math.floor(value)); + } + if (typeof value !== "string") return void 0; + const parsed = Number(value.trim()); + return Number.isFinite(parsed) ? Math.max(0, Math.floor(parsed)) : void 0; +} +function getAdapterSessionManagement(adapterType) { + if (!adapterType) return null; + return ADAPTER_SESSION_MANAGEMENT[adapterType] ?? null; +} +function readSessionCompactionOverride(runtimeConfig) { + const runtime = isRecord2(runtimeConfig) ? runtimeConfig : {}; + const heartbeat = isRecord2(runtime.heartbeat) ? runtime.heartbeat : {}; + const compaction = isRecord2( + heartbeat.sessionCompaction ?? heartbeat.sessionRotation ?? runtime.sessionCompaction + ) ? heartbeat.sessionCompaction ?? heartbeat.sessionRotation ?? runtime.sessionCompaction : {}; + const explicit = {}; + const enabled = readBoolean(compaction.enabled); + const maxSessionRuns = readNumber(compaction.maxSessionRuns); + const maxRawInputTokens = readNumber(compaction.maxRawInputTokens); + const maxSessionAgeHours = readNumber(compaction.maxSessionAgeHours); + if (enabled !== void 0) explicit.enabled = enabled; + if (maxSessionRuns !== void 0) explicit.maxSessionRuns = maxSessionRuns; + if (maxRawInputTokens !== void 0) explicit.maxRawInputTokens = maxRawInputTokens; + if (maxSessionAgeHours !== void 0) explicit.maxSessionAgeHours = maxSessionAgeHours; + return explicit; +} +function resolveSessionCompactionPolicy(adapterType, runtimeConfig) { + const adapterSessionManagement = getAdapterSessionManagement(adapterType); + const explicitOverride = readSessionCompactionOverride(runtimeConfig); + const hasExplicitOverride = Object.keys(explicitOverride).length > 0; + const fallbackEnabled = Boolean(adapterType && LEGACY_SESSIONED_ADAPTER_TYPES.has(adapterType)); + const basePolicy = adapterSessionManagement?.defaultSessionCompaction ?? { + ...DEFAULT_SESSION_COMPACTION_POLICY, + enabled: fallbackEnabled + }; + return { + policy: { + enabled: explicitOverride.enabled ?? basePolicy.enabled, + maxSessionRuns: explicitOverride.maxSessionRuns ?? basePolicy.maxSessionRuns, + maxRawInputTokens: explicitOverride.maxRawInputTokens ?? basePolicy.maxRawInputTokens, + maxSessionAgeHours: explicitOverride.maxSessionAgeHours ?? basePolicy.maxSessionAgeHours + }, + adapterSessionManagement, + explicitOverride, + source: hasExplicitOverride ? "agent_override" : adapterSessionManagement ? "adapter_default" : "legacy_fallback" + }; +} +function hasSessionCompactionThresholds(policy) { + return policy.maxSessionRuns > 0 || policy.maxRawInputTokens > 0 || policy.maxSessionAgeHours > 0; +} + +// packages/adapter-utils/src/billing.ts +function readEnv(env2, key) { + const value = env2[key]; + return typeof value === "string" && value.trim().length > 0 ? value.trim() : null; +} +function inferOpenAiCompatibleBiller(env2, fallback = "openai") { + const explicitOpenRouterKey = readEnv(env2, "OPENROUTER_API_KEY"); + if (explicitOpenRouterKey) return "openrouter"; + const baseUrl = readEnv(env2, "OPENAI_BASE_URL") ?? readEnv(env2, "OPENAI_API_BASE") ?? readEnv(env2, "OPENAI_API_BASE_URL"); + if (baseUrl && /openrouter\.ai/i.test(baseUrl)) return "openrouter"; + return fallback; +} + +// packages/adapters/codex-local/src/server/parse.ts +function parseCodexJsonl(stdout) { + let sessionId = null; + let finalMessage = null; + let errorMessage = null; + const usage = { + inputTokens: 0, + cachedInputTokens: 0, + outputTokens: 0 + }; + for (const rawLine of stdout.split(/\r?\n/)) { + const line3 = rawLine.trim(); + if (!line3) continue; + const event = parseJson2(line3); + if (!event) continue; + const type = asString(event.type, ""); + if (type === "thread.started") { + sessionId = asString(event.thread_id, sessionId ?? "") || sessionId; + continue; + } + if (type === "error") { + const msg = asString(event.message, "").trim(); + if (msg) errorMessage = msg; + continue; + } + if (type === "item.completed") { + const item = parseObject(event.item); + if (asString(item.type, "") === "agent_message") { + const text3 = asString(item.text, ""); + if (text3) finalMessage = text3; + } + continue; + } + if (type === "turn.completed") { + const usageObj = parseObject(event.usage); + usage.inputTokens = asNumber(usageObj.input_tokens, usage.inputTokens); + usage.cachedInputTokens = asNumber(usageObj.cached_input_tokens, usage.cachedInputTokens); + usage.outputTokens = asNumber(usageObj.output_tokens, usage.outputTokens); + continue; + } + if (type === "turn.failed") { + const err = parseObject(event.error); + const msg = asString(err.message, "").trim(); + if (msg) errorMessage = msg; + } + } + return { + sessionId, + summary: finalMessage?.trim() ?? "", + usage, + errorMessage + }; +} +function isCodexUnknownSessionError(stdout, stderr) { + const haystack = `${stdout} +${stderr}`.split(/\r?\n/).map((line3) => line3.trim()).filter(Boolean).join("\n"); + return /unknown (session|thread)|session .* not found|thread .* not found|conversation .* not found|missing rollout path for thread|state db missing rollout path|no rollout found for thread id/i.test( + haystack + ); +} + +// packages/adapters/codex-local/src/server/codex-home.ts +import fs8 from "node:fs/promises"; +import os6 from "node:os"; +import path10 from "node:path"; +var TRUTHY_ENV_RE = /^(1|true|yes|on)$/i; +var COPIED_SHARED_FILES = ["config.json", "config.toml", "instructions.md"]; +var SYMLINKED_SHARED_FILES = ["auth.json"]; +var DEFAULT_TASKCORE_INSTANCE_ID2 = "default"; +function nonEmpty2(value) { + return typeof value === "string" && value.trim().length > 0 ? value.trim() : null; +} +async function pathExists2(candidate) { + return fs8.access(candidate).then(() => true).catch(() => false); +} +function resolveSharedCodexHomeDir(env2 = process.env) { + const fromEnv = nonEmpty2(env2.CODEX_HOME); + return fromEnv ? path10.resolve(fromEnv) : path10.join(os6.homedir(), ".codex"); +} +function isWorktreeMode(env2) { + return TRUTHY_ENV_RE.test(env2.TASKCORE_IN_WORKTREE ?? ""); +} +function resolveManagedCodexHomeDir(env2, companyId) { + const taskcoreHome = nonEmpty2(env2.TASKCORE_HOME) ?? path10.resolve(os6.homedir(), ".taskcore"); + const instanceId = nonEmpty2(env2.TASKCORE_INSTANCE_ID) ?? DEFAULT_TASKCORE_INSTANCE_ID2; + return companyId ? path10.resolve(taskcoreHome, "instances", instanceId, "companies", companyId, "codex-home") : path10.resolve(taskcoreHome, "instances", instanceId, "codex-home"); +} +async function ensureParentDir(target) { + await fs8.mkdir(path10.dirname(target), { recursive: true }); +} +async function ensureSymlink(target, source) { + const existing = await fs8.lstat(target).catch(() => null); + if (!existing) { + await ensureParentDir(target); + await fs8.symlink(source, target); + return; + } + if (!existing.isSymbolicLink()) { + return; + } + const linkedPath = await fs8.readlink(target).catch(() => null); + if (!linkedPath) return; + const resolvedLinkedPath = path10.resolve(path10.dirname(target), linkedPath); + if (resolvedLinkedPath === source) return; + await fs8.unlink(target); + await fs8.symlink(source, target); +} +async function ensureCopiedFile(target, source) { + const existing = await fs8.lstat(target).catch(() => null); + if (existing) return; + await ensureParentDir(target); + await fs8.copyFile(source, target); +} +async function prepareManagedCodexHome(env2, onLog, companyId) { + const targetHome = resolveManagedCodexHomeDir(env2, companyId); + const sourceHome = resolveSharedCodexHomeDir(env2); + if (path10.resolve(sourceHome) === path10.resolve(targetHome)) return targetHome; + await fs8.mkdir(targetHome, { recursive: true }); + for (const name of SYMLINKED_SHARED_FILES) { + const source = path10.join(sourceHome, name); + if (!await pathExists2(source)) continue; + await ensureSymlink(path10.join(targetHome, name), source); + } + for (const name of COPIED_SHARED_FILES) { + const source = path10.join(sourceHome, name); + if (!await pathExists2(source)) continue; + await ensureCopiedFile(path10.join(targetHome, name), source); + } + await onLog( + "stdout", + `[taskcore] Using ${isWorktreeMode(env2) ? "worktree-isolated" : "Taskcore-managed"} Codex home "${targetHome}" (seeded from "${sourceHome}"). +` + ); + return targetHome; +} + +// packages/adapters/codex-local/src/server/skills.ts +import path11 from "node:path"; +import { fileURLToPath as fileURLToPath4 } from "node:url"; +var __moduleDir3 = path11.dirname(fileURLToPath4(import.meta.url)); +async function buildCodexSkillSnapshot(config3) { + const availableEntries = await readTaskcoreRuntimeSkillEntries(config3, __moduleDir3); + const availableByKey = new Map(availableEntries.map((entry) => [entry.key, entry])); + const desiredSkills = resolveTaskcoreDesiredSkillNames(config3, availableEntries); + const desiredSet = new Set(desiredSkills); + const entries2 = availableEntries.map((entry) => ({ + key: entry.key, + runtimeName: entry.runtimeName, + desired: desiredSet.has(entry.key), + managed: true, + state: desiredSet.has(entry.key) ? "configured" : "available", + origin: entry.required ? "taskcore_required" : "company_managed", + originLabel: entry.required ? "Required by Taskcore" : "Managed by Taskcore", + readOnly: false, + sourcePath: entry.source, + targetPath: null, + detail: desiredSet.has(entry.key) ? "Will be linked into the effective CODEX_HOME/skills/ directory on the next run." : null, + required: Boolean(entry.required), + requiredReason: entry.requiredReason ?? null + })); + const warnings = []; + for (const desiredSkill of desiredSkills) { + if (availableByKey.has(desiredSkill)) continue; + warnings.push(`Desired skill "${desiredSkill}" is not available from the Taskcore skills directory.`); + entries2.push({ + key: desiredSkill, + runtimeName: null, + desired: true, + managed: true, + state: "missing", + origin: "external_unknown", + originLabel: "External or unavailable", + readOnly: false, + sourcePath: null, + targetPath: null, + detail: "Taskcore cannot find this skill in the local runtime skills directory." + }); + } + entries2.sort((left, right) => left.key.localeCompare(right.key)); + return { + adapterType: "codex_local", + supported: true, + mode: "ephemeral", + desiredSkills, + entries: entries2, + warnings + }; +} +async function listCodexSkills(ctx) { + return buildCodexSkillSnapshot(ctx.config); +} +async function syncCodexSkills(ctx, _desiredSkills) { + return buildCodexSkillSnapshot(ctx.config); +} +function resolveCodexDesiredSkillNames(config3, availableEntries) { + return resolveTaskcoreDesiredSkillNames(config3, availableEntries); +} + +// packages/adapters/codex-local/src/index.ts +var DEFAULT_CODEX_LOCAL_MODEL = "gpt-5.3-codex"; +var DEFAULT_CODEX_LOCAL_BYPASS_APPROVALS_AND_SANDBOX = true; +var CODEX_LOCAL_FAST_MODE_SUPPORTED_MODELS = ["gpt-5.4"]; +function isCodexLocalFastModeSupported(model) { + const normalizedModel = typeof model === "string" ? model.trim() : ""; + return CODEX_LOCAL_FAST_MODE_SUPPORTED_MODELS.includes( + normalizedModel + ); +} +var models2 = [ + { id: "gpt-5.4", label: "gpt-5.4" }, + { id: DEFAULT_CODEX_LOCAL_MODEL, label: DEFAULT_CODEX_LOCAL_MODEL }, + { id: "gpt-5.3-codex-spark", label: "gpt-5.3-codex-spark" }, + { id: "gpt-5", label: "gpt-5" }, + { id: "o3", label: "o3" }, + { id: "o4-mini", label: "o4-mini" }, + { id: "gpt-5-mini", label: "gpt-5-mini" }, + { id: "gpt-5-nano", label: "gpt-5-nano" }, + { id: "o3-mini", label: "o3-mini" }, + { id: "codex-mini-latest", label: "Codex Mini" } +]; +var agentConfigurationDoc2 = `# codex_local agent configuration + +Adapter: codex_local + +Core fields: +- cwd (string, optional): default absolute working directory fallback for the agent process (created if missing when possible) +- instructionsFilePath (string, optional): absolute path to a markdown instructions file prepended to stdin prompt at runtime +- model (string, optional): Codex model id +- modelReasoningEffort (string, optional): reasoning effort override (minimal|low|medium|high|xhigh) passed via -c model_reasoning_effort=... +- promptTemplate (string, optional): run prompt template +- search (boolean, optional): run codex with --search +- fastMode (boolean, optional): enable Codex Fast mode; currently supported on GPT-5.4 only and consumes credits faster +- dangerouslyBypassApprovalsAndSandbox (boolean, optional): run with bypass flag +- command (string, optional): defaults to "codex" +- extraArgs (string[], optional): additional CLI args +- env (object, optional): KEY=VALUE environment variables +- workspaceStrategy (object, optional): execution workspace strategy; currently supports { type: "git_worktree", baseRef?, branchTemplate?, worktreeParentDir? } +- workspaceRuntime (object, optional): reserved for workspace runtime metadata; workspace runtime services are manually controlled from the workspace UI and are not auto-started by heartbeats + +Operational fields: +- timeoutSec (number, optional): run timeout in seconds +- graceSec (number, optional): SIGTERM grace period in seconds + +Notes: +- Prompts are piped via stdin (Codex receives "-" prompt argument). +- If instructionsFilePath is configured, Taskcore prepends that file's contents to the stdin prompt on every run. +- Codex exec automatically applies repo-scoped AGENTS.md instructions from the active workspace. Taskcore cannot suppress that discovery in exec mode, so repo AGENTS.md files may still apply even when you only configured an explicit instructionsFilePath. +- Taskcore injects desired local skills into the effective CODEX_HOME/skills/ directory at execution time so Codex can discover "$taskcore" and related skills without polluting the project working directory. In managed-home mode (the default) this is ~/.taskcore/instances//companies//codex-home/skills/; when CODEX_HOME is explicitly overridden in adapter config, that override is used instead. +- Unless explicitly overridden in adapter config, Taskcore runs Codex with a per-company managed CODEX_HOME under the active Taskcore instance and seeds auth/config from the shared Codex home (the CODEX_HOME env var, when set, or ~/.codex). +- Some model/tool combinations reject certain effort levels (for example minimal with web search enabled). +- Fast mode is currently supported on GPT-5.4 only. When enabled, Taskcore applies \`service_tier="fast"\` and \`features.fast_mode=true\`. +- When Taskcore realizes a workspace/runtime for a run, it injects TASKCORE_WORKSPACE_* and TASKCORE_RUNTIME_* env vars for agent-side tooling. +`; + +// packages/adapters/codex-local/src/server/codex-args.ts +function readExtraArgs(config3) { + const fromExtraArgs = asStringArray(asRecord(config3).extraArgs); + if (fromExtraArgs.length > 0) return fromExtraArgs; + return asStringArray(asRecord(config3).args); +} +function asRecord(value) { + return typeof value === "object" && value !== null && !Array.isArray(value) ? value : {}; +} +function formatFastModeSupportedModels() { + return CODEX_LOCAL_FAST_MODE_SUPPORTED_MODELS.join(", "); +} +function buildCodexExecArgs(config3, options = {}) { + const record2 = asRecord(config3); + const model = asString(record2.model, "").trim(); + const modelReasoningEffort = asString( + record2.modelReasoningEffort, + asString(record2.reasoningEffort, "") + ).trim(); + const search = asBoolean(record2.search, false); + const fastModeRequested = asBoolean(record2.fastMode, false); + const fastModeApplied = fastModeRequested && isCodexLocalFastModeSupported(model); + const bypass = asBoolean( + record2.dangerouslyBypassApprovalsAndSandbox, + asBoolean(record2.dangerouslyBypassSandbox, false) + ); + const extraArgs = readExtraArgs(record2); + const args = ["exec", "--json"]; + if (search) args.unshift("--search"); + if (bypass) args.push("--dangerously-bypass-approvals-and-sandbox"); + if (model) args.push("--model", model); + if (modelReasoningEffort) { + args.push("-c", `model_reasoning_effort=${JSON.stringify(modelReasoningEffort)}`); + } + if (fastModeApplied) { + args.push("-c", 'service_tier="fast"', "-c", "features.fast_mode=true"); + } + if (extraArgs.length > 0) args.push(...extraArgs); + if (options.resumeSessionId) args.push("resume", options.resumeSessionId, "-"); + else args.push("-"); + return { + args, + model, + fastModeRequested, + fastModeApplied, + fastModeIgnoredReason: fastModeRequested && !fastModeApplied ? `Configured fast mode is currently only supported on ${formatFastModeSupportedModels()}; Taskcore will ignore it for model ${model || "(default)"}.` : null + }; +} + +// packages/adapters/codex-local/src/server/execute.ts +var __moduleDir4 = path12.dirname(fileURLToPath5(import.meta.url)); +var CODEX_ROLLOUT_NOISE_RE = /^\d{4}-\d{2}-\d{2}T[^\s]+\s+ERROR\s+codex_core::rollout::list:\s+state db missing rollout path for thread\s+[a-z0-9-]+$/i; +function stripCodexRolloutNoise(text3) { + const parts = text3.split(/\r?\n/); + const kept = []; + for (const part of parts) { + const trimmed = part.trim(); + if (!trimmed) { + kept.push(part); + continue; + } + if (CODEX_ROLLOUT_NOISE_RE.test(trimmed)) continue; + kept.push(part); + } + return kept.join("\n"); +} +function firstNonEmptyLine2(text3) { + return text3.split(/\r?\n/).map((line3) => line3.trim()).find(Boolean) ?? ""; +} +function hasNonEmptyEnvValue2(env2, key) { + const raw = env2[key]; + return typeof raw === "string" && raw.trim().length > 0; +} +function resolveCodexBillingType(env2) { + return hasNonEmptyEnvValue2(env2, "OPENAI_API_KEY") ? "api" : "subscription"; +} +function resolveCodexBiller(env2, billingType) { + const openAiCompatibleBiller = inferOpenAiCompatibleBiller(env2, "openai"); + if (openAiCompatibleBiller === "openrouter") return "openrouter"; + return billingType === "subscription" ? "chatgpt" : openAiCompatibleBiller ?? "openai"; +} +async function isLikelyTaskcoreRepoRoot(candidate) { + const [hasWorkspace, hasPackageJson, hasServerDir, hasAdapterUtilsDir] = await Promise.all([ + pathExists2(path12.join(candidate, "pnpm-workspace.yaml")), + pathExists2(path12.join(candidate, "package.json")), + pathExists2(path12.join(candidate, "server")), + pathExists2(path12.join(candidate, "packages", "adapter-utils")) + ]); + return hasWorkspace && hasPackageJson && hasServerDir && hasAdapterUtilsDir; +} +async function isLikelyTaskcoreRuntimeSkillPath(candidate, skillName, options = {}) { + if (path12.basename(candidate) !== skillName) return false; + const skillsRoot = path12.dirname(candidate); + if (path12.basename(skillsRoot) !== "skills") return false; + if (options.requireSkillMarkdown !== false && !await pathExists2(path12.join(candidate, "SKILL.md"))) { + return false; + } + let cursor2 = path12.dirname(skillsRoot); + for (let depth = 0; depth < 6; depth += 1) { + if (await isLikelyTaskcoreRepoRoot(cursor2)) return true; + const parent = path12.dirname(cursor2); + if (parent === cursor2) break; + cursor2 = parent; + } + return false; +} +async function pruneBrokenUnavailableTaskcoreSkillSymlinks(skillsHome, allowedSkillNames, onLog) { + const allowed2 = new Set(Array.from(allowedSkillNames)); + const entries2 = await fs9.readdir(skillsHome, { withFileTypes: true }).catch(() => []); + for (const entry of entries2) { + if (allowed2.has(entry.name) || !entry.isSymbolicLink()) continue; + const target = path12.join(skillsHome, entry.name); + const linkedPath = await fs9.readlink(target).catch(() => null); + if (!linkedPath) continue; + const resolvedLinkedPath = path12.resolve(path12.dirname(target), linkedPath); + if (await pathExists2(resolvedLinkedPath)) continue; + if (!await isLikelyTaskcoreRuntimeSkillPath(resolvedLinkedPath, entry.name, { + requireSkillMarkdown: false + })) { + continue; + } + await fs9.unlink(target).catch(() => { + }); + await onLog( + "stdout", + `[taskcore] Removed stale Codex skill "${entry.name}" from ${skillsHome} +` + ); + } +} +function resolveCodexSkillsDir(codexHome) { + return path12.join(codexHome, "skills"); +} +async function ensureCodexSkillsInjected(onLog, options = {}) { + const allSkillsEntries = options.skillsEntries ?? await readTaskcoreRuntimeSkillEntries({}, __moduleDir4); + const desiredSkillNames = options.desiredSkillNames ?? allSkillsEntries.map((entry) => entry.key); + const desiredSet = new Set(desiredSkillNames); + const skillsEntries = allSkillsEntries.filter((entry) => desiredSet.has(entry.key)); + if (skillsEntries.length === 0) return; + const skillsHome = options.skillsHome ?? resolveCodexSkillsDir(resolveSharedCodexHomeDir()); + await fs9.mkdir(skillsHome, { recursive: true }); + const linkSkill = options.linkSkill; + for (const entry of skillsEntries) { + const target = path12.join(skillsHome, entry.runtimeName); + try { + const existing = await fs9.lstat(target).catch(() => null); + if (existing?.isSymbolicLink()) { + const linkedPath = await fs9.readlink(target).catch(() => null); + const resolvedLinkedPath = linkedPath ? path12.resolve(path12.dirname(target), linkedPath) : null; + if (resolvedLinkedPath && resolvedLinkedPath !== entry.source && await isLikelyTaskcoreRuntimeSkillPath(resolvedLinkedPath, entry.runtimeName)) { + await fs9.unlink(target); + if (linkSkill) { + await linkSkill(entry.source, target); + } else { + await fs9.symlink(entry.source, target); + } + await onLog( + "stdout", + `[taskcore] Repaired Codex skill "${entry.runtimeName}" into ${skillsHome} +` + ); + continue; + } + } + const result = await ensureTaskcoreSkillSymlink(entry.source, target, linkSkill); + if (result === "skipped") continue; + await onLog( + "stdout", + `[taskcore] ${result === "repaired" ? "Repaired" : "Injected"} Codex skill "${entry.runtimeName}" into ${skillsHome} +` + ); + } catch (err) { + await onLog( + "stderr", + `[taskcore] Failed to inject Codex skill "${entry.key}" into ${skillsHome}: ${err instanceof Error ? err.message : String(err)} +` + ); + } + } + await pruneBrokenUnavailableTaskcoreSkillSymlinks( + skillsHome, + skillsEntries.map((entry) => entry.runtimeName), + onLog + ); +} +async function execute2(ctx) { + const { runId, agent, runtime, config: config3, context, onLog, onMeta, onSpawn, authToken } = ctx; + const promptTemplate = asString( + config3.promptTemplate, + "You are agent {{agent.id}} ({{agent.name}}). Continue your Taskcore work." + ); + const command = asString(config3.command, "codex"); + const model = asString(config3.model, ""); + const workspaceContext = parseObject(context.taskcoreWorkspace); + const workspaceCwd = asString(workspaceContext.cwd, ""); + const workspaceSource = asString(workspaceContext.source, ""); + const workspaceStrategy = asString(workspaceContext.strategy, ""); + const workspaceId = asString(workspaceContext.workspaceId, ""); + const workspaceRepoUrl = asString(workspaceContext.repoUrl, ""); + const workspaceRepoRef = asString(workspaceContext.repoRef, ""); + const workspaceBranch = asString(workspaceContext.branchName, ""); + const workspaceWorktreePath = asString(workspaceContext.worktreePath, ""); + const agentHome = asString(workspaceContext.agentHome, ""); + const workspaceHints = Array.isArray(context.taskcoreWorkspaces) ? context.taskcoreWorkspaces.filter( + (value) => typeof value === "object" && value !== null + ) : []; + const runtimeServiceIntents = Array.isArray(context.taskcoreRuntimeServiceIntents) ? context.taskcoreRuntimeServiceIntents.filter( + (value) => typeof value === "object" && value !== null + ) : []; + const runtimeServices = Array.isArray(context.taskcoreRuntimeServices) ? context.taskcoreRuntimeServices.filter( + (value) => typeof value === "object" && value !== null + ) : []; + const runtimePrimaryUrl = asString(context.taskcoreRuntimePrimaryUrl, ""); + const configuredCwd = asString(config3.cwd, ""); + const useConfiguredInsteadOfAgentHome = workspaceSource === "agent_home" && configuredCwd.length > 0; + const effectiveWorkspaceCwd = useConfiguredInsteadOfAgentHome ? "" : workspaceCwd; + const cwd = effectiveWorkspaceCwd || configuredCwd || process.cwd(); + const envConfig = parseObject(config3.env); + const configuredCodexHome = typeof envConfig.CODEX_HOME === "string" && envConfig.CODEX_HOME.trim().length > 0 ? path12.resolve(envConfig.CODEX_HOME.trim()) : null; + const codexSkillEntries = await readTaskcoreRuntimeSkillEntries(config3, __moduleDir4); + const desiredSkillNames = resolveCodexDesiredSkillNames(config3, codexSkillEntries); + await ensureAbsoluteDirectory(cwd, { createIfMissing: true }); + const preparedManagedCodexHome = configuredCodexHome ? null : await prepareManagedCodexHome(process.env, onLog, agent.companyId); + const defaultCodexHome = resolveManagedCodexHomeDir(process.env, agent.companyId); + const effectiveCodexHome = configuredCodexHome ?? preparedManagedCodexHome ?? defaultCodexHome; + await fs9.mkdir(effectiveCodexHome, { recursive: true }); + const codexSkillsDir = resolveCodexSkillsDir(effectiveCodexHome); + await ensureCodexSkillsInjected( + onLog, + { + skillsHome: codexSkillsDir, + skillsEntries: codexSkillEntries, + desiredSkillNames + } + ); + const hasExplicitApiKey = typeof envConfig.TASKCORE_API_KEY === "string" && envConfig.TASKCORE_API_KEY.trim().length > 0; + const env2 = { ...buildTaskcoreEnv(agent) }; + env2.CODEX_HOME = effectiveCodexHome; + env2.TASKCORE_RUN_ID = runId; + const wakeTaskId = typeof context.taskId === "string" && context.taskId.trim().length > 0 && context.taskId.trim() || typeof context.issueId === "string" && context.issueId.trim().length > 0 && context.issueId.trim() || null; + const wakeReason = typeof context.wakeReason === "string" && context.wakeReason.trim().length > 0 ? context.wakeReason.trim() : null; + const wakeCommentId = typeof context.wakeCommentId === "string" && context.wakeCommentId.trim().length > 0 && context.wakeCommentId.trim() || typeof context.commentId === "string" && context.commentId.trim().length > 0 && context.commentId.trim() || null; + const approvalId = typeof context.approvalId === "string" && context.approvalId.trim().length > 0 ? context.approvalId.trim() : null; + const approvalStatus = typeof context.approvalStatus === "string" && context.approvalStatus.trim().length > 0 ? context.approvalStatus.trim() : null; + const linkedIssueIds = Array.isArray(context.issueIds) ? context.issueIds.filter((value) => typeof value === "string" && value.trim().length > 0) : []; + const wakePayloadJson = stringifyTaskcoreWakePayload(context.taskcoreWake); + if (wakeTaskId) { + env2.TASKCORE_TASK_ID = wakeTaskId; + } + if (wakeReason) { + env2.TASKCORE_WAKE_REASON = wakeReason; + } + if (wakeCommentId) { + env2.TASKCORE_WAKE_COMMENT_ID = wakeCommentId; + } + if (approvalId) { + env2.TASKCORE_APPROVAL_ID = approvalId; + } + if (approvalStatus) { + env2.TASKCORE_APPROVAL_STATUS = approvalStatus; + } + if (linkedIssueIds.length > 0) { + env2.TASKCORE_LINKED_ISSUE_IDS = linkedIssueIds.join(","); + } + if (wakePayloadJson) { + env2.TASKCORE_WAKE_PAYLOAD_JSON = wakePayloadJson; + } + if (effectiveWorkspaceCwd) { + env2.TASKCORE_WORKSPACE_CWD = effectiveWorkspaceCwd; + } + if (workspaceSource) { + env2.TASKCORE_WORKSPACE_SOURCE = workspaceSource; + } + if (workspaceStrategy) { + env2.TASKCORE_WORKSPACE_STRATEGY = workspaceStrategy; + } + if (workspaceId) { + env2.TASKCORE_WORKSPACE_ID = workspaceId; + } + if (workspaceRepoUrl) { + env2.TASKCORE_WORKSPACE_REPO_URL = workspaceRepoUrl; + } + if (workspaceRepoRef) { + env2.TASKCORE_WORKSPACE_REPO_REF = workspaceRepoRef; + } + if (workspaceBranch) { + env2.TASKCORE_WORKSPACE_BRANCH = workspaceBranch; + } + if (workspaceWorktreePath) { + env2.TASKCORE_WORKSPACE_WORKTREE_PATH = workspaceWorktreePath; + } + if (agentHome) { + env2.AGENT_HOME = agentHome; + } + if (workspaceHints.length > 0) { + env2.TASKCORE_WORKSPACES_JSON = JSON.stringify(workspaceHints); + } + if (runtimeServiceIntents.length > 0) { + env2.TASKCORE_RUNTIME_SERVICE_INTENTS_JSON = JSON.stringify(runtimeServiceIntents); + } + if (runtimeServices.length > 0) { + env2.TASKCORE_RUNTIME_SERVICES_JSON = JSON.stringify(runtimeServices); + } + if (runtimePrimaryUrl) { + env2.TASKCORE_RUNTIME_PRIMARY_URL = runtimePrimaryUrl; + } + for (const [k5, v5] of Object.entries(envConfig)) { + if (typeof v5 === "string") env2[k5] = v5; + } + if (!hasExplicitApiKey && authToken) { + env2.TASKCORE_API_KEY = authToken; + } + const effectiveEnv = Object.fromEntries( + Object.entries({ ...process.env, ...env2 }).filter( + (entry) => typeof entry[1] === "string" + ) + ); + const billingType = resolveCodexBillingType(effectiveEnv); + const runtimeEnv = ensurePathInEnv(effectiveEnv); + await ensureCommandResolvable(command, cwd, runtimeEnv); + const resolvedCommand = await resolveCommandForLogs(command, cwd, runtimeEnv); + const loggedEnv = buildInvocationEnvForLogs(env2, { + runtimeEnv, + includeRuntimeKeys: ["HOME"], + resolvedCommand + }); + const timeoutSec = asNumber(config3.timeoutSec, 0); + const graceSec = asNumber(config3.graceSec, 20); + const runtimeSessionParams = parseObject(runtime.sessionParams); + const runtimeSessionId = asString(runtimeSessionParams.sessionId, runtime.sessionId ?? ""); + const runtimeSessionCwd = asString(runtimeSessionParams.cwd, ""); + const canResumeSession = runtimeSessionId.length > 0 && (runtimeSessionCwd.length === 0 || path12.resolve(runtimeSessionCwd) === path12.resolve(cwd)); + const sessionId = canResumeSession ? runtimeSessionId : null; + if (runtimeSessionId && !canResumeSession) { + await onLog( + "stdout", + `[taskcore] Codex session "${runtimeSessionId}" was saved for cwd "${runtimeSessionCwd}" and will not be resumed in "${cwd}". +` + ); + } + const instructionsFilePath = asString(config3.instructionsFilePath, "").trim(); + const instructionsDir = instructionsFilePath ? `${path12.dirname(instructionsFilePath)}/` : ""; + let instructionsPrefix = ""; + let instructionsChars = 0; + if (instructionsFilePath) { + try { + const instructionsContents = await fs9.readFile(instructionsFilePath, "utf8"); + instructionsPrefix = `${instructionsContents} + +The above agent instructions were loaded from ${instructionsFilePath}. Resolve any relative file references from ${instructionsDir}. + +`; + instructionsChars = instructionsPrefix.length; + } catch (err) { + const reason = err instanceof Error ? err.message : String(err); + await onLog( + "stdout", + `[taskcore] Warning: could not read agent instructions file "${instructionsFilePath}": ${reason} +` + ); + } + } + const repoAgentsNote = "Codex exec automatically applies repo-scoped AGENTS.md instructions from the current workspace; Taskcore does not currently suppress that discovery."; + const bootstrapPromptTemplate = asString(config3.bootstrapPromptTemplate, ""); + const templateData = { + agentId: agent.id, + companyId: agent.companyId, + runId, + company: { id: agent.companyId }, + agent, + run: { id: runId, source: "on_demand" }, + context + }; + const renderedBootstrapPrompt = !sessionId && bootstrapPromptTemplate.trim().length > 0 ? renderTemplate(bootstrapPromptTemplate, templateData).trim() : ""; + const wakePrompt = renderTaskcoreWakePrompt(context.taskcoreWake, { resumedSession: Boolean(sessionId) }); + const shouldUseResumeDeltaPrompt = Boolean(sessionId) && wakePrompt.length > 0; + const promptInstructionsPrefix = shouldUseResumeDeltaPrompt ? "" : instructionsPrefix; + instructionsChars = promptInstructionsPrefix.length; + const commandNotes = (() => { + if (!instructionsFilePath) { + return [repoAgentsNote]; + } + if (instructionsPrefix.length > 0) { + if (shouldUseResumeDeltaPrompt) { + return [ + `Loaded agent instructions from ${instructionsFilePath}`, + "Skipped stdin instruction reinjection because an existing Codex session is being resumed with a wake delta.", + repoAgentsNote + ]; + } + return [ + `Loaded agent instructions from ${instructionsFilePath}`, + `Prepended instructions + path directive to stdin prompt (relative references from ${instructionsDir}).`, + repoAgentsNote + ]; + } + return [ + `Configured instructionsFilePath ${instructionsFilePath}, but file could not be read; continuing without injected instructions.`, + repoAgentsNote + ]; + })(); + const renderedPrompt = shouldUseResumeDeltaPrompt ? "" : renderTemplate(promptTemplate, templateData); + const sessionHandoffNote = asString(context.taskcoreSessionHandoffMarkdown, "").trim(); + const prompt = joinPromptSections([ + promptInstructionsPrefix, + renderedBootstrapPrompt, + wakePrompt, + sessionHandoffNote, + renderedPrompt + ]); + const promptMetrics = { + promptChars: prompt.length, + instructionsChars, + bootstrapPromptChars: renderedBootstrapPrompt.length, + wakePromptChars: wakePrompt.length, + sessionHandoffChars: sessionHandoffNote.length, + heartbeatPromptChars: renderedPrompt.length + }; + const runAttempt = async (resumeSessionId) => { + const execArgs = buildCodexExecArgs(config3, { resumeSessionId }); + const args = execArgs.args; + const commandNotesWithFastMode = execArgs.fastModeIgnoredReason == null ? commandNotes : [...commandNotes, execArgs.fastModeIgnoredReason]; + if (onMeta) { + await onMeta({ + adapterType: "codex_local", + command: resolvedCommand, + cwd, + commandNotes: commandNotesWithFastMode, + commandArgs: args.map((value, idx) => { + if (idx === args.length - 1 && value !== "-") return ``; + return value; + }), + env: loggedEnv, + prompt, + promptMetrics, + context + }); + } + const proc = await runChildProcess(runId, command, args, { + cwd, + env: env2, + stdin: prompt, + timeoutSec, + graceSec, + onSpawn, + onLog: async (stream, chunk) => { + if (stream !== "stderr") { + await onLog(stream, chunk); + return; + } + const cleaned = stripCodexRolloutNoise(chunk); + if (!cleaned.trim()) return; + await onLog(stream, cleaned); + } + }); + const cleanedStderr = stripCodexRolloutNoise(proc.stderr); + return { + proc: { + ...proc, + stderr: cleanedStderr + }, + rawStderr: proc.stderr, + parsed: parseCodexJsonl(proc.stdout) + }; + }; + const toResult = (attempt, clearSessionOnMissingSession = false) => { + if (attempt.proc.timedOut) { + return { + exitCode: attempt.proc.exitCode, + signal: attempt.proc.signal, + timedOut: true, + errorMessage: `Timed out after ${timeoutSec}s`, + clearSession: clearSessionOnMissingSession + }; + } + const resolvedSessionId = attempt.parsed.sessionId ?? runtimeSessionId ?? runtime.sessionId ?? null; + const resolvedSessionParams = resolvedSessionId ? { + sessionId: resolvedSessionId, + cwd, + ...workspaceId ? { workspaceId } : {}, + ...workspaceRepoUrl ? { repoUrl: workspaceRepoUrl } : {}, + ...workspaceRepoRef ? { repoRef: workspaceRepoRef } : {} + } : null; + const parsedError = typeof attempt.parsed.errorMessage === "string" ? attempt.parsed.errorMessage.trim() : ""; + const stderrLine = firstNonEmptyLine2(attempt.proc.stderr); + const fallbackErrorMessage = parsedError || stderrLine || `Codex exited with code ${attempt.proc.exitCode ?? -1}`; + return { + exitCode: attempt.proc.exitCode, + signal: attempt.proc.signal, + timedOut: false, + errorMessage: (attempt.proc.exitCode ?? 0) === 0 ? null : fallbackErrorMessage, + usage: attempt.parsed.usage, + sessionId: resolvedSessionId, + sessionParams: resolvedSessionParams, + sessionDisplayId: resolvedSessionId, + provider: "openai", + biller: resolveCodexBiller(effectiveEnv, billingType), + model, + billingType, + costUsd: null, + resultJson: { + stdout: attempt.proc.stdout, + stderr: attempt.proc.stderr + }, + summary: attempt.parsed.summary, + clearSession: Boolean(clearSessionOnMissingSession && !resolvedSessionId) + }; + }; + const initial = await runAttempt(sessionId); + if (sessionId && !initial.proc.timedOut && (initial.proc.exitCode ?? 0) !== 0 && isCodexUnknownSessionError(initial.proc.stdout, initial.rawStderr)) { + await onLog( + "stdout", + `[taskcore] Codex resume session "${sessionId}" is unavailable; retrying with a fresh session. +` + ); + const retry = await runAttempt(null); + return toResult(retry, true); + } + return toResult(initial); +} + +// packages/adapters/codex-local/src/server/test.ts +import path14 from "node:path"; + +// packages/adapters/codex-local/src/server/quota.ts +import { spawn as spawn2 } from "node:child_process"; +import fs10 from "node:fs/promises"; +import os7 from "node:os"; +import path13 from "node:path"; +var CODEX_USAGE_SOURCE_RPC = "codex-rpc"; +var CODEX_USAGE_SOURCE_WHAM = "codex-wham"; +function codexHomeDir() { + const fromEnv = process.env.CODEX_HOME; + if (typeof fromEnv === "string" && fromEnv.trim().length > 0) return fromEnv.trim(); + return path13.join(os7.homedir(), ".codex"); +} +function base64UrlDecode2(input) { + try { + let normalized = input.replace(/-/g, "+").replace(/_/g, "/"); + const remainder = normalized.length % 4; + if (remainder > 0) normalized += "=".repeat(4 - remainder); + return Buffer.from(normalized, "base64").toString("utf8"); + } catch { + return null; + } +} +function decodeJwtPayload(token) { + if (typeof token !== "string" || token.trim().length === 0) return null; + const parts = token.split("."); + if (parts.length < 2) return null; + const decoded = base64UrlDecode2(parts[1] ?? ""); + if (!decoded) return null; + try { + const parsed = JSON.parse(decoded); + return typeof parsed === "object" && parsed !== null ? parsed : null; + } catch { + return null; + } +} +function readNestedString(record2, pathSegments) { + let current = record2; + for (const segment of pathSegments) { + if (typeof current !== "object" || current === null || Array.isArray(current)) return null; + current = current[segment]; + } + return typeof current === "string" && current.trim().length > 0 ? current.trim() : null; +} +function parsePlanAndEmailFromToken(idToken, accessToken) { + const payloads = [decodeJwtPayload(idToken), decodeJwtPayload(accessToken)].filter( + (value) => value != null + ); + for (const payload2 of payloads) { + const directEmail = typeof payload2.email === "string" ? payload2.email : null; + const authBlock = typeof payload2["https://api.openai.com/auth"] === "object" && payload2["https://api.openai.com/auth"] !== null && !Array.isArray(payload2["https://api.openai.com/auth"]) ? payload2["https://api.openai.com/auth"] : null; + const profileBlock = typeof payload2["https://api.openai.com/profile"] === "object" && payload2["https://api.openai.com/profile"] !== null && !Array.isArray(payload2["https://api.openai.com/profile"]) ? payload2["https://api.openai.com/profile"] : null; + const email3 = directEmail ?? (typeof profileBlock?.email === "string" ? profileBlock.email : null) ?? (typeof authBlock?.chatgpt_user_email === "string" ? authBlock.chatgpt_user_email : null); + const planType = typeof authBlock?.chatgpt_plan_type === "string" ? authBlock.chatgpt_plan_type : null; + if (email3 || planType) return { email: email3 ?? null, planType }; + } + return { email: null, planType: null }; +} +async function readCodexAuthInfo(codexHome) { + const authPath = path13.join(codexHome ?? codexHomeDir(), "auth.json"); + let raw; + try { + raw = await fs10.readFile(authPath, "utf8"); + } catch { + return null; + } + let parsed; + try { + parsed = JSON.parse(raw); + } catch { + return null; + } + if (typeof parsed !== "object" || parsed === null) return null; + const obj = parsed; + const modern = obj; + const legacy = obj; + const accessToken = legacy.accessToken ?? modern.tokens?.access_token ?? readNestedString(obj, ["tokens", "access_token"]); + if (typeof accessToken !== "string" || accessToken.length === 0) return null; + const accountId = legacy.accountId ?? modern.tokens?.account_id ?? readNestedString(obj, ["tokens", "account_id"]); + const refreshToken2 = modern.tokens?.refresh_token ?? readNestedString(obj, ["tokens", "refresh_token"]); + const idToken = modern.tokens?.id_token ?? readNestedString(obj, ["tokens", "id_token"]); + const { email: email3, planType } = parsePlanAndEmailFromToken(idToken, accessToken); + return { + accessToken, + accountId: typeof accountId === "string" && accountId.trim().length > 0 ? accountId.trim() : null, + refreshToken: typeof refreshToken2 === "string" && refreshToken2.trim().length > 0 ? refreshToken2.trim() : null, + idToken: typeof idToken === "string" && idToken.trim().length > 0 ? idToken.trim() : null, + email: email3, + planType, + lastRefresh: typeof modern.last_refresh === "string" && modern.last_refresh.trim().length > 0 ? modern.last_refresh.trim() : null + }; +} +async function readCodexToken() { + const auth = await readCodexAuthInfo(); + if (!auth) return null; + return { token: auth.accessToken, accountId: auth.accountId }; +} +async function fetchWithTimeout2(url2, init2, ms = 8e3) { + const controller = new AbortController(); + const timer2 = setTimeout(() => controller.abort(), ms); + try { + return await fetch(url2, { ...init2, signal: controller.signal }); + } finally { + clearTimeout(timer2); + } +} +function normalizeCodexUsedPercent(rawPct) { + if (rawPct == null) return null; + return Math.min(100, Math.round(rawPct < 1 ? rawPct * 100 : rawPct)); +} +async function fetchCodexQuota(token, accountId) { + const headers = { + Authorization: `Bearer ${token}` + }; + if (accountId) headers["ChatGPT-Account-Id"] = accountId; + const resp = await fetchWithTimeout2("https://chatgpt.com/backend-api/wham/usage", { headers }); + if (!resp.ok) throw new Error(`chatgpt wham api returned ${resp.status}`); + const body = await resp.json(); + const windows = []; + const rateLimit = body.rate_limit; + if (rateLimit?.primary_window != null) { + const w5 = rateLimit.primary_window; + windows.push({ + label: "5h limit", + usedPercent: normalizeCodexUsedPercent(w5.used_percent), + resetsAt: typeof w5.reset_at === "number" ? unixSecondsToIso(w5.reset_at) : w5.reset_at ?? null, + valueLabel: null, + detail: null + }); + } + if (rateLimit?.secondary_window != null) { + const w5 = rateLimit.secondary_window; + windows.push({ + label: "Weekly limit", + usedPercent: normalizeCodexUsedPercent(w5.used_percent), + resetsAt: typeof w5.reset_at === "number" ? unixSecondsToIso(w5.reset_at) : w5.reset_at ?? null, + valueLabel: null, + detail: null + }); + } + if (body.credits != null && body.credits.unlimited !== true) { + const balance = body.credits.balance; + const valueLabel = balance != null ? `$${(balance / 100).toFixed(2)} remaining` : "N/A"; + windows.push({ + label: "Credits", + usedPercent: null, + resetsAt: null, + valueLabel, + detail: null + }); + } + return windows; +} +function unixSecondsToIso(value) { + if (typeof value !== "number" || !Number.isFinite(value)) return null; + return new Date(value * 1e3).toISOString(); +} +function buildCodexRpcWindow(label, window2) { + if (!window2) return null; + return { + label, + usedPercent: normalizeCodexUsedPercent(window2.usedPercent), + resetsAt: unixSecondsToIso(window2.resetsAt), + valueLabel: null, + detail: null + }; +} +function parseCreditBalance(value) { + if (typeof value === "number" && Number.isFinite(value)) { + return `$${value.toFixed(2)} remaining`; + } + if (typeof value === "string" && value.trim().length > 0) { + const parsed = Number(value); + if (Number.isFinite(parsed)) { + return `$${parsed.toFixed(2)} remaining`; + } + return value.trim(); + } + return null; +} +function mapCodexRpcQuota(result, account) { + const windows = []; + const limitOrder = ["codex"]; + const limitsById = result.rateLimitsByLimitId ?? {}; + for (const key of Object.keys(limitsById)) { + if (!limitOrder.includes(key)) limitOrder.push(key); + } + const rootLimit = result.rateLimits ?? null; + const allLimits = /* @__PURE__ */ new Map(); + if (rootLimit?.limitId) allLimits.set(rootLimit.limitId, rootLimit); + for (const [key, value] of Object.entries(limitsById)) { + allLimits.set(key, value); + } + if (!allLimits.has("codex") && rootLimit) allLimits.set("codex", rootLimit); + for (const limitId of limitOrder) { + const limit = allLimits.get(limitId); + if (!limit) continue; + const prefix = limitId === "codex" ? "" : `${limit.limitName ?? limitId} \xB7 `; + const primary = buildCodexRpcWindow(`${prefix}5h limit`, limit.primary); + if (primary) windows.push(primary); + const secondary = buildCodexRpcWindow(`${prefix}Weekly limit`, limit.secondary); + if (secondary) windows.push(secondary); + if (limitId === "codex" && limit.credits && limit.credits.unlimited !== true) { + windows.push({ + label: "Credits", + usedPercent: null, + resetsAt: null, + valueLabel: parseCreditBalance(limit.credits.balance) ?? "N/A", + detail: null + }); + } + } + return { + windows, + email: typeof account?.account?.email === "string" && account.account.email.trim().length > 0 ? account.account.email.trim() : null, + planType: typeof account?.account?.planType === "string" && account.account.planType.trim().length > 0 ? account.account.planType.trim() : typeof rootLimit?.planType === "string" && rootLimit.planType.trim().length > 0 ? rootLimit.planType.trim() : null + }; +} +var CodexRpcClient = class { + proc = spawn2( + "codex", + ["-s", "read-only", "-a", "untrusted", "app-server"], + { stdio: ["pipe", "pipe", "pipe"], env: process.env } + ); + nextId = 1; + buffer = ""; + pending = /* @__PURE__ */ new Map(); + stderr = ""; + constructor() { + this.proc.stdout.setEncoding("utf8"); + this.proc.stderr.setEncoding("utf8"); + this.proc.stdout.on("data", (chunk) => this.onStdout(chunk)); + this.proc.stderr.on("data", (chunk) => { + this.stderr += chunk; + }); + this.proc.on("exit", () => { + for (const request of this.pending.values()) { + clearTimeout(request.timer); + request.reject(new Error(this.stderr.trim() || "codex app-server closed unexpectedly")); + } + this.pending.clear(); + }); + this.proc.on("error", (err) => { + for (const request of this.pending.values()) { + clearTimeout(request.timer); + request.reject(err); + } + this.pending.clear(); + }); + } + onStdout(chunk) { + this.buffer += chunk; + while (true) { + const newlineIndex = this.buffer.indexOf("\n"); + if (newlineIndex < 0) break; + const line3 = this.buffer.slice(0, newlineIndex).trim(); + this.buffer = this.buffer.slice(newlineIndex + 1); + if (!line3) continue; + let parsed; + try { + parsed = JSON.parse(line3); + } catch { + continue; + } + const id = typeof parsed.id === "number" ? parsed.id : null; + if (id == null) continue; + const pending = this.pending.get(id); + if (!pending) continue; + this.pending.delete(id); + clearTimeout(pending.timer); + pending.resolve(parsed); + } + } + request(method, params = {}, timeoutMs = 6e3) { + const id = this.nextId++; + const payload2 = JSON.stringify({ id, method, params }) + "\n"; + return new Promise((resolve4, reject) => { + const timer2 = setTimeout(() => { + this.pending.delete(id); + reject(new Error(`codex app-server timed out on ${method}`)); + }, timeoutMs); + this.pending.set(id, { resolve: resolve4, reject, timer: timer2 }); + this.proc.stdin.write(payload2); + }); + } + notify(method, params = {}) { + this.proc.stdin.write(JSON.stringify({ method, params }) + "\n"); + } + async initialize() { + await this.request("initialize", { + clientInfo: { + name: "taskcore", + version: "0.0.0" + } + }); + this.notify("initialized", {}); + } + async fetchRateLimits() { + const message2 = await this.request("account/rateLimits/read"); + return message2.result ?? {}; + } + async fetchAccount() { + try { + const message2 = await this.request("account/read"); + return message2.result ?? null; + } catch { + return null; + } + } + async shutdown() { + this.proc.kill("SIGTERM"); + } +}; +async function fetchCodexRpcQuota() { + const client2 = new CodexRpcClient(); + try { + await client2.initialize(); + const [limits, account] = await Promise.all([ + client2.fetchRateLimits(), + client2.fetchAccount() + ]); + return mapCodexRpcQuota(limits, account); + } finally { + await client2.shutdown(); + } +} +function formatProviderError2(source, error50) { + const message2 = error50 instanceof Error ? error50.message : String(error50); + return `${source}: ${message2}`; +} +async function getQuotaWindows2() { + const errors = []; + try { + const rpc = await fetchCodexRpcQuota(); + if (rpc.windows.length > 0) { + return { provider: "openai", source: CODEX_USAGE_SOURCE_RPC, ok: true, windows: rpc.windows }; + } + } catch (error50) { + errors.push(formatProviderError2("Codex app-server", error50)); + } + const auth = await readCodexToken(); + if (auth) { + try { + const windows = await fetchCodexQuota(auth.token, auth.accountId); + return { provider: "openai", source: CODEX_USAGE_SOURCE_WHAM, ok: true, windows }; + } catch (error50) { + errors.push(formatProviderError2("ChatGPT WHAM usage", error50)); + } + } else { + errors.push("no local codex auth token"); + } + return { + provider: "openai", + ok: false, + error: errors.join("; "), + windows: [] + }; +} + +// packages/adapters/codex-local/src/server/test.ts +function summarizeStatus2(checks) { + if (checks.some((check3) => check3.level === "error")) return "fail"; + if (checks.some((check3) => check3.level === "warn")) return "warn"; + return "pass"; +} +function isNonEmpty2(value) { + return typeof value === "string" && value.trim().length > 0; +} +function firstNonEmptyLine3(text3) { + return text3.split(/\r?\n/).map((line3) => line3.trim()).find(Boolean) ?? ""; +} +function commandLooksLike2(command, expected) { + const base = path14.basename(command).toLowerCase(); + return base === expected || base === `${expected}.cmd` || base === `${expected}.exe`; +} +function summarizeProbeDetail2(stdout, stderr, parsedError) { + const raw = parsedError?.trim() || firstNonEmptyLine3(stderr) || firstNonEmptyLine3(stdout); + if (!raw) return null; + const clean3 = raw.replace(/\s+/g, " ").trim(); + const max = 240; + return clean3.length > max ? `${clean3.slice(0, max - 1)}\u2026` : clean3; +} +var CODEX_AUTH_REQUIRED_RE = /(?:not\s+logged\s+in|login\s+required|authentication\s+required|unauthorized|invalid(?:\s+or\s+missing)?\s+api(?:[_\s-]?key)?|openai[_\s-]?api[_\s-]?key|api[_\s-]?key.*required|please\s+run\s+`?codex\s+login`?)/i; +async function testEnvironment2(ctx) { + const checks = []; + const config3 = parseObject(ctx.config); + const command = asString(config3.command, "codex"); + const cwd = asString(config3.cwd, process.cwd()); + try { + await ensureAbsoluteDirectory(cwd, { createIfMissing: true }); + checks.push({ + code: "codex_cwd_valid", + level: "info", + message: `Working directory is valid: ${cwd}` + }); + } catch (err) { + checks.push({ + code: "codex_cwd_invalid", + level: "error", + message: err instanceof Error ? err.message : "Invalid working directory", + detail: cwd + }); + } + const envConfig = parseObject(config3.env); + const env2 = {}; + for (const [key, value] of Object.entries(envConfig)) { + if (typeof value === "string") env2[key] = value; + } + const runtimeEnv = ensurePathInEnv({ ...process.env, ...env2 }); + try { + await ensureCommandResolvable(command, cwd, runtimeEnv); + checks.push({ + code: "codex_command_resolvable", + level: "info", + message: `Command is executable: ${command}` + }); + } catch (err) { + checks.push({ + code: "codex_command_unresolvable", + level: "error", + message: err instanceof Error ? err.message : "Command is not executable", + detail: command + }); + } + const configOpenAiKey = env2.OPENAI_API_KEY; + const hostOpenAiKey = process.env.OPENAI_API_KEY; + if (isNonEmpty2(configOpenAiKey) || isNonEmpty2(hostOpenAiKey)) { + const source = isNonEmpty2(configOpenAiKey) ? "adapter config env" : "server environment"; + checks.push({ + code: "codex_openai_api_key_present", + level: "info", + message: "OPENAI_API_KEY is set for Codex authentication.", + detail: `Detected in ${source}.` + }); + } else { + const codexHome = isNonEmpty2(env2.CODEX_HOME) ? env2.CODEX_HOME : void 0; + const codexAuth = await readCodexAuthInfo(codexHome).catch(() => null); + if (codexAuth) { + checks.push({ + code: "codex_native_auth_present", + level: "info", + message: "Codex is authenticated via its own auth configuration.", + detail: codexAuth.email ? `Logged in as ${codexAuth.email}.` : `Credentials found in ${path14.join(codexHome ?? codexHomeDir(), "auth.json")}.` + }); + } else { + checks.push({ + code: "codex_openai_api_key_missing", + level: "warn", + message: "OPENAI_API_KEY is not set. Codex runs may fail until authentication is configured.", + hint: "Set OPENAI_API_KEY in adapter env, shell environment, or run `codex auth` to log in." + }); + } + } + const canRunProbe = checks.every((check3) => check3.code !== "codex_cwd_invalid" && check3.code !== "codex_command_unresolvable"); + if (canRunProbe) { + if (!commandLooksLike2(command, "codex")) { + checks.push({ + code: "codex_hello_probe_skipped_custom_command", + level: "info", + message: "Skipped hello probe because command is not `codex`.", + detail: command, + hint: "Use the `codex` CLI command to run the automatic login and installation probe." + }); + } else { + const execArgs = buildCodexExecArgs({ ...config3, fastMode: false }); + const args = execArgs.args; + if (execArgs.fastModeIgnoredReason) { + checks.push({ + code: "codex_fast_mode_unsupported_model", + level: "warn", + message: execArgs.fastModeIgnoredReason, + hint: "Switch the agent model to GPT-5.4 to enable Codex Fast mode." + }); + } + const probe = await runChildProcess( + `codex-envtest-${Date.now()}-${Math.random().toString(16).slice(2)}`, + command, + args, + { + cwd, + env: env2, + timeoutSec: 45, + graceSec: 5, + stdin: "Respond with hello.", + onLog: async () => { + } + } + ); + const parsed = parseCodexJsonl(probe.stdout); + const detail = summarizeProbeDetail2(probe.stdout, probe.stderr, parsed.errorMessage); + const authEvidence = `${parsed.errorMessage ?? ""} +${probe.stdout} +${probe.stderr}`.trim(); + if (probe.timedOut) { + checks.push({ + code: "codex_hello_probe_timed_out", + level: "warn", + message: "Codex hello probe timed out.", + hint: "Retry the probe. If this persists, verify Codex can run `Respond with hello` from this directory manually." + }); + } else if ((probe.exitCode ?? 1) === 0) { + const summary = parsed.summary.trim(); + const hasHello = /\bhello\b/i.test(summary); + checks.push({ + code: hasHello ? "codex_hello_probe_passed" : "codex_hello_probe_unexpected_output", + level: hasHello ? "info" : "warn", + message: hasHello ? "Codex hello probe succeeded." : "Codex probe ran but did not return `hello` as expected.", + ...summary ? { detail: summary.replace(/\s+/g, " ").trim().slice(0, 240) } : {}, + ...hasHello ? {} : { + hint: "Try the probe manually (`codex exec --json -` then prompt: Respond with hello) to inspect full output." + } + }); + } else if (CODEX_AUTH_REQUIRED_RE.test(authEvidence)) { + checks.push({ + code: "codex_hello_probe_auth_required", + level: "warn", + message: "Codex CLI is installed, but authentication is not ready.", + ...detail ? { detail } : {}, + hint: "Configure OPENAI_API_KEY in adapter env/shell or run `codex login`, then retry the probe." + }); + } else { + checks.push({ + code: "codex_hello_probe_failed", + level: "error", + message: "Codex hello probe failed.", + ...detail ? { detail } : {}, + hint: "Run `codex exec --json -` manually in this working directory and prompt `Respond with hello` to debug." + }); + } + } + } + return { + adapterType: ctx.adapterType, + status: summarizeStatus2(checks), + checks, + testedAt: (/* @__PURE__ */ new Date()).toISOString() + }; +} + +// packages/adapters/codex-local/src/server/index.ts +function readNonEmptyString3(value) { + return typeof value === "string" && value.trim().length > 0 ? value.trim() : null; +} +var sessionCodec2 = { + deserialize(raw) { + if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return null; + const record2 = raw; + const sessionId = readNonEmptyString3(record2.sessionId) ?? readNonEmptyString3(record2.session_id); + if (!sessionId) return null; + const cwd = readNonEmptyString3(record2.cwd) ?? readNonEmptyString3(record2.workdir) ?? readNonEmptyString3(record2.folder); + const workspaceId = readNonEmptyString3(record2.workspaceId) ?? readNonEmptyString3(record2.workspace_id); + const repoUrl = readNonEmptyString3(record2.repoUrl) ?? readNonEmptyString3(record2.repo_url); + const repoRef = readNonEmptyString3(record2.repoRef) ?? readNonEmptyString3(record2.repo_ref); + return { + sessionId, + ...cwd ? { cwd } : {}, + ...workspaceId ? { workspaceId } : {}, + ...repoUrl ? { repoUrl } : {}, + ...repoRef ? { repoRef } : {} + }; + }, + serialize(params) { + if (!params) return null; + const sessionId = readNonEmptyString3(params.sessionId) ?? readNonEmptyString3(params.session_id); + if (!sessionId) return null; + const cwd = readNonEmptyString3(params.cwd) ?? readNonEmptyString3(params.workdir) ?? readNonEmptyString3(params.folder); + const workspaceId = readNonEmptyString3(params.workspaceId) ?? readNonEmptyString3(params.workspace_id); + const repoUrl = readNonEmptyString3(params.repoUrl) ?? readNonEmptyString3(params.repo_url); + const repoRef = readNonEmptyString3(params.repoRef) ?? readNonEmptyString3(params.repo_ref); + return { + sessionId, + ...cwd ? { cwd } : {}, + ...workspaceId ? { workspaceId } : {}, + ...repoUrl ? { repoUrl } : {}, + ...repoRef ? { repoRef } : {} + }; + }, + getDisplayId(params) { + if (!params) return null; + return readNonEmptyString3(params.sessionId) ?? readNonEmptyString3(params.session_id); + } +}; + +// packages/adapters/opencode-local/src/server/execute.ts +import fs12 from "node:fs/promises"; +import os10 from "node:os"; +import path16 from "node:path"; +import { fileURLToPath as fileURLToPath6 } from "node:url"; + +// packages/adapters/opencode-local/src/server/parse.ts +function errorText(value) { + if (typeof value === "string") return value; + const rec = parseObject(value); + const message2 = asString(rec.message, "").trim(); + if (message2) return message2; + const data2 = parseObject(rec.data); + const nestedMessage = asString(data2.message, "").trim(); + if (nestedMessage) return nestedMessage; + const name = asString(rec.name, "").trim(); + if (name) return name; + const code = asString(rec.code, "").trim(); + if (code) return code; + try { + return JSON.stringify(rec); + } catch { + return ""; + } +} +function parseOpenCodeJsonl(stdout) { + let sessionId = null; + const messages2 = []; + const errors = []; + const usage = { + inputTokens: 0, + cachedInputTokens: 0, + outputTokens: 0 + }; + let costUsd = 0; + for (const rawLine of stdout.split(/\r?\n/)) { + const line3 = rawLine.trim(); + if (!line3) continue; + const event = parseJson2(line3); + if (!event) continue; + const currentSessionId = asString(event.sessionID, "").trim(); + if (currentSessionId) sessionId = currentSessionId; + const type = asString(event.type, ""); + if (type === "text") { + const part = parseObject(event.part); + const text3 = asString(part.text, "").trim(); + if (text3) messages2.push(text3); + continue; + } + if (type === "step_finish") { + const part = parseObject(event.part); + const tokens = parseObject(part.tokens); + const cache7 = parseObject(tokens.cache); + usage.inputTokens += asNumber(tokens.input, 0); + usage.cachedInputTokens += asNumber(cache7.read, 0); + usage.outputTokens += asNumber(tokens.output, 0) + asNumber(tokens.reasoning, 0); + costUsd += asNumber(part.cost, 0); + continue; + } + if (type === "tool_use") { + const part = parseObject(event.part); + const state2 = parseObject(part.state); + if (asString(state2.status, "") === "error") { + const text3 = asString(state2.error, "").trim(); + if (text3) errors.push(text3); + } + continue; + } + if (type === "error") { + const text3 = errorText(event.error ?? event.message).trim(); + if (text3) errors.push(text3); + continue; + } + } + return { + sessionId, + summary: messages2.join("\n\n").trim(), + usage, + costUsd, + errorMessage: errors.length > 0 ? errors.join("\n") : null + }; +} +function isOpenCodeUnknownSessionError(stdout, stderr) { + const haystack = `${stdout} +${stderr}`.split(/\r?\n/).map((line3) => line3.trim()).filter(Boolean).join("\n"); + return /unknown\s+session|session\b.*\bnot\s+found|resource\s+not\s+found:.*[\\/]session[\\/].*\.json|notfounderror|no session/i.test( + haystack + ); +} + +// packages/adapters/opencode-local/src/server/models.ts +import { createHash as createHash4 } from "node:crypto"; +import os8 from "node:os"; +var MODELS_CACHE_TTL_MS = 6e4; +var MODELS_DISCOVERY_TIMEOUT_MS = 2e4; +function resolveOpenCodeCommand(input) { + const envOverride = typeof process.env.TASKCORE_OPENCODE_COMMAND === "string" && process.env.TASKCORE_OPENCODE_COMMAND.trim().length > 0 ? process.env.TASKCORE_OPENCODE_COMMAND.trim() : "opencode"; + return asString(input, envOverride); +} +var discoveryCache = /* @__PURE__ */ new Map(); +var VOLATILE_ENV_KEY_PREFIXES = ["TASKCORE_", "npm_", "NPM_"]; +var VOLATILE_ENV_KEY_EXACT = /* @__PURE__ */ new Set(["PWD", "OLDPWD", "SHLVL", "_", "TERM_SESSION_ID", "HOME"]); +function dedupeModels(models8) { + const seen = /* @__PURE__ */ new Set(); + const deduped = []; + for (const model of models8) { + const id = model.id.trim(); + if (!id || seen.has(id)) continue; + seen.add(id); + deduped.push({ id, label: model.label.trim() || id }); + } + return deduped; +} +function sortModels(models8) { + return [...models8].sort( + (a5, b6) => a5.id.localeCompare(b6.id, "en", { numeric: true, sensitivity: "base" }) + ); +} +function firstNonEmptyLine4(text3) { + return text3.split(/\r?\n/).map((line3) => line3.trim()).find(Boolean) ?? ""; +} +function parseModelsOutput(stdout) { + const parsed = []; + for (const raw of stdout.split(/\r?\n/)) { + const line3 = raw.trim(); + if (!line3) continue; + const firstToken = line3.split(/\s+/)[0]?.trim() ?? ""; + if (!firstToken.includes("/")) continue; + const provider = firstToken.slice(0, firstToken.indexOf("/")).trim(); + const model = firstToken.slice(firstToken.indexOf("/") + 1).trim(); + if (!provider || !model) continue; + parsed.push({ id: `${provider}/${model}`, label: `${provider}/${model}` }); + } + return dedupeModels(parsed); +} +function normalizeEnv(input) { + const envInput = typeof input === "object" && input !== null && !Array.isArray(input) ? input : {}; + const env2 = {}; + for (const [key, value] of Object.entries(envInput)) { + if (typeof value === "string") env2[key] = value; + } + return env2; +} +function isVolatileEnvKey(key) { + if (VOLATILE_ENV_KEY_EXACT.has(key)) return true; + return VOLATILE_ENV_KEY_PREFIXES.some((prefix) => key.startsWith(prefix)); +} +function hashValue(value) { + return createHash4("sha256").update(value).digest("hex"); +} +function discoveryCacheKey(command, cwd, env2) { + const envKey = Object.entries(env2).filter(([key]) => !isVolatileEnvKey(key)).sort(([a5], [b6]) => a5.localeCompare(b6)).map(([key, value]) => `${key}=${hashValue(value)}`).join("\n"); + return `${command} +${cwd} +${envKey}`; +} +function pruneExpiredDiscoveryCache(now2) { + for (const [key, value] of discoveryCache.entries()) { + if (value.expiresAt <= now2) discoveryCache.delete(key); + } +} +async function discoverOpenCodeModels(input = {}) { + const command = resolveOpenCodeCommand(input.command); + const cwd = asString(input.cwd, process.cwd()); + const env2 = normalizeEnv(input.env); + let resolvedHome; + try { + resolvedHome = os8.userInfo().homedir || void 0; + } catch { + } + const runtimeEnv = normalizeEnv(ensurePathInEnv({ ...process.env, ...env2, ...resolvedHome ? { HOME: resolvedHome } : {}, OPENCODE_DISABLE_PROJECT_CONFIG: "true" })); + const result = await runChildProcess( + `opencode-models-${Date.now()}-${Math.random().toString(16).slice(2)}`, + command, + ["models"], + { + cwd, + env: runtimeEnv, + timeoutSec: MODELS_DISCOVERY_TIMEOUT_MS / 1e3, + graceSec: 3, + onLog: async () => { + } + } + ); + if (result.timedOut) { + throw new Error(`\`opencode models\` timed out after ${MODELS_DISCOVERY_TIMEOUT_MS / 1e3}s.`); + } + if ((result.exitCode ?? 1) !== 0) { + const detail = firstNonEmptyLine4(result.stderr) || firstNonEmptyLine4(result.stdout); + throw new Error(detail ? `\`opencode models\` failed: ${detail}` : "`opencode models` failed."); + } + return sortModels(parseModelsOutput(result.stdout)); +} +async function discoverOpenCodeModelsCached(input = {}) { + const command = resolveOpenCodeCommand(input.command); + const cwd = asString(input.cwd, process.cwd()); + const env2 = normalizeEnv(input.env); + const key = discoveryCacheKey(command, cwd, env2); + const now2 = Date.now(); + pruneExpiredDiscoveryCache(now2); + const cached4 = discoveryCache.get(key); + if (cached4 && cached4.expiresAt > now2) return cached4.models; + const models8 = await discoverOpenCodeModels({ command, cwd, env: env2 }); + discoveryCache.set(key, { expiresAt: now2 + MODELS_CACHE_TTL_MS, models: models8 }); + return models8; +} +async function ensureOpenCodeModelConfiguredAndAvailable(input) { + const model = asString(input.model, "").trim(); + if (!model) { + throw new Error("OpenCode requires `adapterConfig.model` in provider/model format."); + } + const models8 = await discoverOpenCodeModelsCached({ + command: input.command, + cwd: input.cwd, + env: input.env + }); + if (models8.length === 0) { + throw new Error("OpenCode returned no models. Run `opencode models` and verify provider auth."); + } + if (!models8.some((entry) => entry.id === model)) { + const sample = models8.slice(0, 12).map((entry) => entry.id).join(", "); + throw new Error( + `Configured OpenCode model is unavailable: ${model}. Available models: ${sample}${models8.length > 12 ? ", ..." : ""}` + ); + } + return models8; +} +async function listOpenCodeModels() { + try { + return await discoverOpenCodeModelsCached(); + } catch { + return []; + } +} + +// packages/adapters/opencode-local/src/server/runtime-config.ts +import fs11 from "node:fs/promises"; +import os9 from "node:os"; +import path15 from "node:path"; +function resolveXdgConfigHome(env2) { + return typeof env2.XDG_CONFIG_HOME === "string" && env2.XDG_CONFIG_HOME.trim() || typeof process.env.XDG_CONFIG_HOME === "string" && process.env.XDG_CONFIG_HOME.trim() || path15.join(os9.homedir(), ".config"); +} +function isPlainObject(value) { + return typeof value === "object" && value !== null && !Array.isArray(value); +} +async function readJsonObject(filepath) { + try { + const raw = await fs11.readFile(filepath, "utf8"); + const parsed = JSON.parse(raw); + return isPlainObject(parsed) ? parsed : {}; + } catch { + return {}; + } +} +async function prepareOpenCodeRuntimeConfig(input) { + const skipPermissions = asBoolean(input.config.dangerouslySkipPermissions, true); + if (!skipPermissions) { + return { + env: input.env, + notes: [], + cleanup: async () => { + } + }; + } + const sourceConfigDir = path15.join(resolveXdgConfigHome(input.env), "opencode"); + const runtimeConfigHome = await fs11.mkdtemp(path15.join(os9.tmpdir(), "taskcore-opencode-config-")); + const runtimeConfigDir = path15.join(runtimeConfigHome, "opencode"); + const runtimeConfigPath = path15.join(runtimeConfigDir, "opencode.json"); + await fs11.mkdir(runtimeConfigDir, { recursive: true }); + try { + await fs11.cp(sourceConfigDir, runtimeConfigDir, { + recursive: true, + force: true, + errorOnExist: false, + dereference: false + }); + } catch (err) { + if (err?.code !== "ENOENT") { + throw err; + } + } + const existingConfig = await readJsonObject(runtimeConfigPath); + const existingPermission = isPlainObject(existingConfig.permission) ? existingConfig.permission : {}; + const nextConfig = { + ...existingConfig, + permission: { + ...existingPermission, + external_directory: "allow" + } + }; + await fs11.writeFile(runtimeConfigPath, `${JSON.stringify(nextConfig, null, 2)} +`, "utf8"); + return { + env: { + ...input.env, + XDG_CONFIG_HOME: runtimeConfigHome + }, + notes: [ + "Injected runtime OpenCode config with permission.external_directory=allow to avoid headless approval prompts." + ], + cleanup: async () => { + await fs11.rm(runtimeConfigHome, { recursive: true, force: true }); + } + }; +} + +// packages/adapters/opencode-local/src/server/execute.ts +var __moduleDir5 = path16.dirname(fileURLToPath6(import.meta.url)); +function firstNonEmptyLine5(text3) { + return text3.split(/\r?\n/).map((line3) => line3.trim()).find(Boolean) ?? ""; +} +function parseModelProvider(model) { + if (!model) return null; + const trimmed = model.trim(); + if (!trimmed.includes("/")) return null; + return trimmed.slice(0, trimmed.indexOf("/")).trim() || null; +} +function resolveOpenCodeBiller(env2, provider) { + return inferOpenAiCompatibleBiller(env2, null) ?? provider ?? "unknown"; +} +function claudeSkillsHome() { + return path16.join(os10.homedir(), ".claude", "skills"); +} +async function ensureOpenCodeSkillsInjected(onLog, skillsEntries, desiredSkillNames) { + const skillsHome = claudeSkillsHome(); + await fs12.mkdir(skillsHome, { recursive: true }); + const desiredSet = new Set(desiredSkillNames ?? skillsEntries.map((entry) => entry.key)); + const selectedEntries = skillsEntries.filter((entry) => desiredSet.has(entry.key)); + const removedSkills = await removeMaintainerOnlySkillSymlinks( + skillsHome, + selectedEntries.map((entry) => entry.runtimeName) + ); + for (const skillName of removedSkills) { + await onLog( + "stderr", + `[taskcore] Removed maintainer-only OpenCode skill "${skillName}" from ${skillsHome} +` + ); + } + for (const entry of selectedEntries) { + const target = path16.join(skillsHome, entry.runtimeName); + try { + const result = await ensureTaskcoreSkillSymlink(entry.source, target); + if (result === "skipped") continue; + await onLog( + "stderr", + `[taskcore] ${result === "repaired" ? "Repaired" : "Injected"} OpenCode skill "${entry.key}" into ${skillsHome} +` + ); + } catch (err) { + await onLog( + "stderr", + `[taskcore] Failed to inject OpenCode skill "${entry.key}" into ${skillsHome}: ${err instanceof Error ? err.message : String(err)} +` + ); + } + } +} +async function execute3(ctx) { + const { runId, agent, runtime, config: config3, context, onLog, onMeta, onSpawn, authToken } = ctx; + const promptTemplate = asString( + config3.promptTemplate, + "You are agent {{agent.id}} ({{agent.name}}). Continue your Taskcore work." + ); + const command = asString(config3.command, "opencode"); + const model = asString(config3.model, "").trim(); + const variant = asString(config3.variant, "").trim(); + const workspaceContext = parseObject(context.taskcoreWorkspace); + const workspaceCwd = asString(workspaceContext.cwd, ""); + const workspaceSource = asString(workspaceContext.source, ""); + const workspaceId = asString(workspaceContext.workspaceId, ""); + const workspaceRepoUrl = asString(workspaceContext.repoUrl, ""); + const workspaceRepoRef = asString(workspaceContext.repoRef, ""); + const agentHome = asString(workspaceContext.agentHome, ""); + const workspaceHints = Array.isArray(context.taskcoreWorkspaces) ? context.taskcoreWorkspaces.filter( + (value) => typeof value === "object" && value !== null + ) : []; + const configuredCwd = asString(config3.cwd, ""); + const useConfiguredInsteadOfAgentHome = workspaceSource === "agent_home" && configuredCwd.length > 0; + const effectiveWorkspaceCwd = useConfiguredInsteadOfAgentHome ? "" : workspaceCwd; + const cwd = effectiveWorkspaceCwd || configuredCwd || process.cwd(); + await ensureAbsoluteDirectory(cwd, { createIfMissing: true }); + const openCodeSkillEntries = await readTaskcoreRuntimeSkillEntries(config3, __moduleDir5); + const desiredOpenCodeSkillNames = resolveTaskcoreDesiredSkillNames(config3, openCodeSkillEntries); + await ensureOpenCodeSkillsInjected( + onLog, + openCodeSkillEntries, + desiredOpenCodeSkillNames + ); + const envConfig = parseObject(config3.env); + const hasExplicitApiKey = typeof envConfig.TASKCORE_API_KEY === "string" && envConfig.TASKCORE_API_KEY.trim().length > 0; + const env2 = { ...buildTaskcoreEnv(agent) }; + env2.TASKCORE_RUN_ID = runId; + const wakeTaskId = typeof context.taskId === "string" && context.taskId.trim().length > 0 && context.taskId.trim() || typeof context.issueId === "string" && context.issueId.trim().length > 0 && context.issueId.trim() || null; + const wakeReason = typeof context.wakeReason === "string" && context.wakeReason.trim().length > 0 ? context.wakeReason.trim() : null; + const wakeCommentId = typeof context.wakeCommentId === "string" && context.wakeCommentId.trim().length > 0 && context.wakeCommentId.trim() || typeof context.commentId === "string" && context.commentId.trim().length > 0 && context.commentId.trim() || null; + const approvalId = typeof context.approvalId === "string" && context.approvalId.trim().length > 0 ? context.approvalId.trim() : null; + const approvalStatus = typeof context.approvalStatus === "string" && context.approvalStatus.trim().length > 0 ? context.approvalStatus.trim() : null; + const linkedIssueIds = Array.isArray(context.issueIds) ? context.issueIds.filter((value) => typeof value === "string" && value.trim().length > 0) : []; + const wakePayloadJson = stringifyTaskcoreWakePayload(context.taskcoreWake); + if (wakeTaskId) env2.TASKCORE_TASK_ID = wakeTaskId; + if (wakeReason) env2.TASKCORE_WAKE_REASON = wakeReason; + if (wakeCommentId) env2.TASKCORE_WAKE_COMMENT_ID = wakeCommentId; + if (approvalId) env2.TASKCORE_APPROVAL_ID = approvalId; + if (approvalStatus) env2.TASKCORE_APPROVAL_STATUS = approvalStatus; + if (linkedIssueIds.length > 0) env2.TASKCORE_LINKED_ISSUE_IDS = linkedIssueIds.join(","); + if (wakePayloadJson) env2.TASKCORE_WAKE_PAYLOAD_JSON = wakePayloadJson; + if (effectiveWorkspaceCwd) env2.TASKCORE_WORKSPACE_CWD = effectiveWorkspaceCwd; + if (workspaceSource) env2.TASKCORE_WORKSPACE_SOURCE = workspaceSource; + if (workspaceId) env2.TASKCORE_WORKSPACE_ID = workspaceId; + if (workspaceRepoUrl) env2.TASKCORE_WORKSPACE_REPO_URL = workspaceRepoUrl; + if (workspaceRepoRef) env2.TASKCORE_WORKSPACE_REPO_REF = workspaceRepoRef; + if (agentHome) env2.AGENT_HOME = agentHome; + if (workspaceHints.length > 0) env2.TASKCORE_WORKSPACES_JSON = JSON.stringify(workspaceHints); + for (const [key, value] of Object.entries(envConfig)) { + if (typeof value === "string") env2[key] = value; + } + env2.OPENCODE_DISABLE_PROJECT_CONFIG = "true"; + if (!hasExplicitApiKey && authToken) { + env2.TASKCORE_API_KEY = authToken; + } + const preparedRuntimeConfig = await prepareOpenCodeRuntimeConfig({ env: env2, config: config3 }); + try { + const runtimeEnv = Object.fromEntries( + Object.entries(ensurePathInEnv({ ...process.env, ...preparedRuntimeConfig.env })).filter( + (entry) => typeof entry[1] === "string" + ) + ); + await ensureCommandResolvable(command, cwd, runtimeEnv); + const resolvedCommand = await resolveCommandForLogs(command, cwd, runtimeEnv); + const loggedEnv = buildInvocationEnvForLogs(preparedRuntimeConfig.env, { + runtimeEnv, + includeRuntimeKeys: ["HOME"], + resolvedCommand + }); + await ensureOpenCodeModelConfiguredAndAvailable({ + model, + command, + cwd, + env: runtimeEnv + }); + const timeoutSec = asNumber(config3.timeoutSec, 0); + const graceSec = asNumber(config3.graceSec, 20); + const extraArgs = (() => { + const fromExtraArgs = asStringArray(config3.extraArgs); + if (fromExtraArgs.length > 0) return fromExtraArgs; + return asStringArray(config3.args); + })(); + const runtimeSessionParams = parseObject(runtime.sessionParams); + const runtimeSessionId = asString(runtimeSessionParams.sessionId, runtime.sessionId ?? ""); + const runtimeSessionCwd = asString(runtimeSessionParams.cwd, ""); + const canResumeSession = runtimeSessionId.length > 0 && (runtimeSessionCwd.length === 0 || path16.resolve(runtimeSessionCwd) === path16.resolve(cwd)); + const sessionId = canResumeSession ? runtimeSessionId : null; + if (runtimeSessionId && !canResumeSession) { + await onLog( + "stdout", + `[taskcore] OpenCode session "${runtimeSessionId}" was saved for cwd "${runtimeSessionCwd}" and will not be resumed in "${cwd}". +` + ); + } + const instructionsFilePath = asString(config3.instructionsFilePath, "").trim(); + const resolvedInstructionsFilePath = instructionsFilePath ? path16.resolve(cwd, instructionsFilePath) : ""; + const instructionsDir = resolvedInstructionsFilePath ? `${path16.dirname(resolvedInstructionsFilePath)}/` : ""; + let instructionsPrefix = ""; + if (resolvedInstructionsFilePath) { + try { + const instructionsContents = await fs12.readFile(resolvedInstructionsFilePath, "utf8"); + instructionsPrefix = `${instructionsContents} + +The above agent instructions were loaded from ${resolvedInstructionsFilePath}. Resolve any relative file references from ${instructionsDir}. + +`; + } catch (err) { + const reason = err instanceof Error ? err.message : String(err); + await onLog( + "stdout", + `[taskcore] Warning: could not read agent instructions file "${resolvedInstructionsFilePath}": ${reason} +` + ); + } + } + const commandNotes = (() => { + const notes = [...preparedRuntimeConfig.notes]; + if (!resolvedInstructionsFilePath) return notes; + if (instructionsPrefix.length > 0) { + notes.push(`Loaded agent instructions from ${resolvedInstructionsFilePath}`); + notes.push( + `Prepended instructions + path directive to stdin prompt (relative references from ${instructionsDir}).` + ); + return notes; + } + notes.push( + `Configured instructionsFilePath ${resolvedInstructionsFilePath}, but file could not be read; continuing without injected instructions.` + ); + return notes; + })(); + const bootstrapPromptTemplate = asString(config3.bootstrapPromptTemplate, ""); + const templateData = { + agentId: agent.id, + companyId: agent.companyId, + runId, + company: { id: agent.companyId }, + agent, + run: { id: runId, source: "on_demand" }, + context + }; + const renderedBootstrapPrompt = !sessionId && bootstrapPromptTemplate.trim().length > 0 ? renderTemplate(bootstrapPromptTemplate, templateData).trim() : ""; + const wakePrompt = renderTaskcoreWakePrompt(context.taskcoreWake, { resumedSession: Boolean(sessionId) }); + const shouldUseResumeDeltaPrompt = Boolean(sessionId) && wakePrompt.length > 0; + const renderedPrompt = shouldUseResumeDeltaPrompt ? "" : renderTemplate(promptTemplate, templateData); + const sessionHandoffNote = asString(context.taskcoreSessionHandoffMarkdown, "").trim(); + const prompt = joinPromptSections([ + instructionsPrefix, + renderedBootstrapPrompt, + wakePrompt, + sessionHandoffNote, + renderedPrompt + ]); + const promptMetrics = { + promptChars: prompt.length, + instructionsChars: instructionsPrefix.length, + bootstrapPromptChars: renderedBootstrapPrompt.length, + wakePromptChars: wakePrompt.length, + sessionHandoffChars: sessionHandoffNote.length, + heartbeatPromptChars: renderedPrompt.length + }; + const buildArgs = (resumeSessionId) => { + const args = ["run", "--format", "json"]; + if (resumeSessionId) args.push("--session", resumeSessionId); + if (model) args.push("--model", model); + if (variant) args.push("--variant", variant); + if (extraArgs.length > 0) args.push(...extraArgs); + return args; + }; + const runAttempt = async (resumeSessionId) => { + const args = buildArgs(resumeSessionId); + if (onMeta) { + await onMeta({ + adapterType: "opencode_local", + command: resolvedCommand, + cwd, + commandNotes, + commandArgs: [...args, ``], + env: loggedEnv, + prompt, + promptMetrics, + context + }); + } + const proc = await runChildProcess(runId, command, args, { + cwd, + env: runtimeEnv, + stdin: prompt, + timeoutSec, + graceSec, + onSpawn, + onLog + }); + return { + proc, + rawStderr: proc.stderr, + parsed: parseOpenCodeJsonl(proc.stdout) + }; + }; + const toResult = (attempt, clearSessionOnMissingSession = false) => { + if (attempt.proc.timedOut) { + return { + exitCode: attempt.proc.exitCode, + signal: attempt.proc.signal, + timedOut: true, + errorMessage: `Timed out after ${timeoutSec}s`, + clearSession: clearSessionOnMissingSession + }; + } + const resolvedSessionId = attempt.parsed.sessionId ?? (clearSessionOnMissingSession ? null : runtimeSessionId ?? runtime.sessionId ?? null); + const resolvedSessionParams = resolvedSessionId ? { + sessionId: resolvedSessionId, + cwd, + ...workspaceId ? { workspaceId } : {}, + ...workspaceRepoUrl ? { repoUrl: workspaceRepoUrl } : {}, + ...workspaceRepoRef ? { repoRef: workspaceRepoRef } : {} + } : null; + const parsedError = typeof attempt.parsed.errorMessage === "string" ? attempt.parsed.errorMessage.trim() : ""; + const stderrLine = firstNonEmptyLine5(attempt.proc.stderr); + const rawExitCode = attempt.proc.exitCode; + const synthesizedExitCode = parsedError && (rawExitCode ?? 0) === 0 ? 1 : rawExitCode; + const fallbackErrorMessage = parsedError || stderrLine || `OpenCode exited with code ${synthesizedExitCode ?? -1}`; + const modelId = model || null; + return { + exitCode: synthesizedExitCode, + signal: attempt.proc.signal, + timedOut: false, + errorMessage: (synthesizedExitCode ?? 0) === 0 ? null : fallbackErrorMessage, + usage: { + inputTokens: attempt.parsed.usage.inputTokens, + outputTokens: attempt.parsed.usage.outputTokens, + cachedInputTokens: attempt.parsed.usage.cachedInputTokens + }, + sessionId: resolvedSessionId, + sessionParams: resolvedSessionParams, + sessionDisplayId: resolvedSessionId, + provider: parseModelProvider(modelId), + biller: resolveOpenCodeBiller(runtimeEnv, parseModelProvider(modelId)), + model: modelId, + billingType: "unknown", + costUsd: attempt.parsed.costUsd, + resultJson: { + stdout: attempt.proc.stdout, + stderr: attempt.proc.stderr + }, + summary: attempt.parsed.summary, + clearSession: Boolean(clearSessionOnMissingSession && !attempt.parsed.sessionId) + }; + }; + const initial = await runAttempt(sessionId); + const initialFailed = !initial.proc.timedOut && ((initial.proc.exitCode ?? 0) !== 0 || Boolean(initial.parsed.errorMessage)); + if (sessionId && initialFailed && isOpenCodeUnknownSessionError(initial.proc.stdout, initial.rawStderr)) { + await onLog( + "stdout", + `[taskcore] OpenCode session "${sessionId}" is unavailable; retrying with a fresh session. +` + ); + const retry = await runAttempt(null); + return toResult(retry, true); + } + return toResult(initial); + } finally { + await preparedRuntimeConfig.cleanup(); + } +} + +// packages/adapters/opencode-local/src/server/skills.ts +import fs13 from "node:fs/promises"; +import os11 from "node:os"; +import path17 from "node:path"; +import { fileURLToPath as fileURLToPath7 } from "node:url"; +var __moduleDir6 = path17.dirname(fileURLToPath7(import.meta.url)); +function asString3(value) { + return typeof value === "string" && value.trim().length > 0 ? value.trim() : null; +} +function resolveOpenCodeSkillsHome(config3) { + const env2 = typeof config3.env === "object" && config3.env !== null && !Array.isArray(config3.env) ? config3.env : {}; + const configuredHome = asString3(env2.HOME); + const home = configuredHome ? path17.resolve(configuredHome) : os11.homedir(); + return path17.join(home, ".claude", "skills"); +} +async function buildOpenCodeSkillSnapshot(config3) { + const availableEntries = await readTaskcoreRuntimeSkillEntries(config3, __moduleDir6); + const desiredSkills = resolveTaskcoreDesiredSkillNames(config3, availableEntries); + const skillsHome = resolveOpenCodeSkillsHome(config3); + const installed = await readInstalledSkillTargets(skillsHome); + return buildPersistentSkillSnapshot({ + adapterType: "opencode_local", + availableEntries, + desiredSkills, + installed, + skillsHome, + locationLabel: "~/.claude/skills", + installedDetail: "Installed in the shared Claude/OpenCode skills home.", + missingDetail: "Configured but not currently linked into the shared Claude/OpenCode skills home.", + externalConflictDetail: "Skill name is occupied by an external installation in the shared skills home.", + externalDetail: "Installed outside Taskcore management in the shared skills home.", + warnings: [ + "OpenCode currently uses the shared Claude skills home (~/.claude/skills)." + ] + }); +} +async function listOpenCodeSkills(ctx) { + return buildOpenCodeSkillSnapshot(ctx.config); +} +async function syncOpenCodeSkills(ctx, desiredSkills) { + const availableEntries = await readTaskcoreRuntimeSkillEntries(ctx.config, __moduleDir6); + const desiredSet = /* @__PURE__ */ new Set([ + ...desiredSkills, + ...availableEntries.filter((entry) => entry.required).map((entry) => entry.key) + ]); + const skillsHome = resolveOpenCodeSkillsHome(ctx.config); + await fs13.mkdir(skillsHome, { recursive: true }); + const installed = await readInstalledSkillTargets(skillsHome); + const availableByRuntimeName = new Map(availableEntries.map((entry) => [entry.runtimeName, entry])); + for (const available of availableEntries) { + if (!desiredSet.has(available.key)) continue; + const target = path17.join(skillsHome, available.runtimeName); + await ensureTaskcoreSkillSymlink(available.source, target); + } + for (const [name, installedEntry] of installed.entries()) { + const available = availableByRuntimeName.get(name); + if (!available) continue; + if (desiredSet.has(available.key)) continue; + if (installedEntry.targetPath !== available.source) continue; + await fs13.unlink(path17.join(skillsHome, name)).catch(() => { + }); + } + return buildOpenCodeSkillSnapshot(ctx.config); +} + +// packages/adapters/opencode-local/src/server/test.ts +function summarizeStatus3(checks) { + if (checks.some((check3) => check3.level === "error")) return "fail"; + if (checks.some((check3) => check3.level === "warn")) return "warn"; + return "pass"; +} +function firstNonEmptyLine6(text3) { + return text3.split(/\r?\n/).map((line3) => line3.trim()).find(Boolean) ?? ""; +} +function summarizeProbeDetail3(stdout, stderr, parsedError) { + const raw = parsedError?.trim() || firstNonEmptyLine6(stderr) || firstNonEmptyLine6(stdout); + if (!raw) return null; + const clean3 = raw.replace(/\s+/g, " ").trim(); + const max = 240; + return clean3.length > max ? `${clean3.slice(0, max - 1)}...` : clean3; +} +function normalizeEnv2(input) { + if (typeof input !== "object" || input === null || Array.isArray(input)) return {}; + const env2 = {}; + for (const [key, value] of Object.entries(input)) { + if (typeof value === "string") env2[key] = value; + } + return env2; +} +var OPENCODE_AUTH_REQUIRED_RE = /(?:auth(?:entication)?\s+required|api\s*key|invalid\s*api\s*key|not\s+logged\s+in|opencode\s+auth\s+login|free\s+usage\s+exceeded)/i; +async function testEnvironment3(ctx) { + const checks = []; + const config3 = parseObject(ctx.config); + const command = asString(config3.command, "opencode"); + const cwd = asString(config3.cwd, process.cwd()); + try { + await ensureAbsoluteDirectory(cwd, { createIfMissing: false }); + checks.push({ + code: "opencode_cwd_valid", + level: "info", + message: `Working directory is valid: ${cwd}` + }); + } catch (err) { + checks.push({ + code: "opencode_cwd_invalid", + level: "error", + message: err instanceof Error ? err.message : "Invalid working directory", + detail: cwd + }); + } + const envConfig = parseObject(config3.env); + const env2 = {}; + for (const [key, value] of Object.entries(envConfig)) { + if (typeof value === "string") env2[key] = value; + } + const openaiKeyOverride = "OPENAI_API_KEY" in envConfig ? asString(envConfig.OPENAI_API_KEY, "") : null; + if (openaiKeyOverride !== null && openaiKeyOverride.trim() === "") { + checks.push({ + code: "opencode_openai_api_key_missing", + level: "warn", + message: "OPENAI_API_KEY override is empty.", + hint: "The OPENAI_API_KEY override is empty. Set a valid key or remove the override." + }); + } + env2.OPENCODE_DISABLE_PROJECT_CONFIG = "true"; + const preparedRuntimeConfig = await prepareOpenCodeRuntimeConfig({ env: env2, config: config3 }); + if (asBoolean(config3.dangerouslySkipPermissions, true)) { + checks.push({ + code: "opencode_headless_permissions_enabled", + level: "info", + message: "Headless OpenCode external-directory permissions are auto-approved for unattended runs." + }); + } + try { + const runtimeEnv = normalizeEnv2(ensurePathInEnv({ ...process.env, ...preparedRuntimeConfig.env })); + const cwdInvalid = checks.some((check3) => check3.code === "opencode_cwd_invalid"); + if (cwdInvalid) { + checks.push({ + code: "opencode_command_skipped", + level: "warn", + message: "Skipped command check because working directory validation failed.", + detail: command + }); + } else { + try { + await ensureCommandResolvable(command, cwd, runtimeEnv); + checks.push({ + code: "opencode_command_resolvable", + level: "info", + message: `Command is executable: ${command}` + }); + } catch (err) { + checks.push({ + code: "opencode_command_unresolvable", + level: "error", + message: err instanceof Error ? err.message : "Command is not executable", + detail: command + }); + } + } + const canRunProbe = checks.every((check3) => check3.code !== "opencode_cwd_invalid" && check3.code !== "opencode_command_unresolvable"); + let modelValidationPassed = false; + const configuredModel = asString(config3.model, "").trim(); + if (canRunProbe && configuredModel) { + try { + const discovered = await discoverOpenCodeModels({ command, cwd, env: runtimeEnv }); + if (discovered.length > 0) { + checks.push({ + code: "opencode_models_discovered", + level: "info", + message: `Discovered ${discovered.length} model(s) from OpenCode providers.` + }); + } else { + checks.push({ + code: "opencode_models_empty", + level: "error", + message: "OpenCode returned no models.", + hint: "Run `opencode models` and verify provider authentication." + }); + } + } catch (err) { + const errMsg = err instanceof Error ? err.message : String(err); + if (/ProviderModelNotFoundError/i.test(errMsg)) { + checks.push({ + code: "opencode_hello_probe_model_unavailable", + level: "warn", + message: "The configured model was not found by the provider.", + detail: errMsg, + hint: "Run `opencode models` and choose an available provider/model ID." + }); + } else { + checks.push({ + code: "opencode_models_discovery_failed", + level: "error", + message: errMsg || "OpenCode model discovery failed.", + hint: "Run `opencode models` manually to verify provider auth and config." + }); + } + } + } else if (canRunProbe && !configuredModel) { + try { + const discovered = await discoverOpenCodeModels({ command, cwd, env: runtimeEnv }); + if (discovered.length > 0) { + checks.push({ + code: "opencode_models_discovered", + level: "info", + message: `Discovered ${discovered.length} model(s) from OpenCode providers.` + }); + } + } catch (err) { + const errMsg = err instanceof Error ? err.message : String(err); + if (/ProviderModelNotFoundError/i.test(errMsg)) { + checks.push({ + code: "opencode_hello_probe_model_unavailable", + level: "warn", + message: "The configured model was not found by the provider.", + detail: errMsg, + hint: "Run `opencode models` and choose an available provider/model ID." + }); + } else { + checks.push({ + code: "opencode_models_discovery_failed", + level: "warn", + message: errMsg || "OpenCode model discovery failed (best-effort, no model configured).", + hint: "Run `opencode models` manually to verify provider auth and config." + }); + } + } + } + const modelUnavailable = checks.some((check3) => check3.code === "opencode_hello_probe_model_unavailable"); + if (!configuredModel && !modelUnavailable) { + } else if (configuredModel && canRunProbe) { + try { + await ensureOpenCodeModelConfiguredAndAvailable({ + model: configuredModel, + command, + cwd, + env: runtimeEnv + }); + checks.push({ + code: "opencode_model_configured", + level: "info", + message: `Configured model: ${configuredModel}` + }); + modelValidationPassed = true; + } catch (err) { + checks.push({ + code: "opencode_model_invalid", + level: "error", + message: err instanceof Error ? err.message : "Configured model is unavailable.", + hint: "Run `opencode models` and choose a currently available provider/model ID." + }); + } + } + if (canRunProbe && modelValidationPassed) { + const extraArgs = (() => { + const fromExtraArgs = asStringArray(config3.extraArgs); + if (fromExtraArgs.length > 0) return fromExtraArgs; + return asStringArray(config3.args); + })(); + const variant = asString(config3.variant, "").trim(); + const probeModel = configuredModel; + const args = ["run", "--format", "json"]; + args.push("--model", probeModel); + if (variant) args.push("--variant", variant); + if (extraArgs.length > 0) args.push(...extraArgs); + try { + const probe = await runChildProcess( + `opencode-envtest-${Date.now()}-${Math.random().toString(16).slice(2)}`, + command, + args, + { + cwd, + env: runtimeEnv, + timeoutSec: 60, + graceSec: 5, + stdin: "Respond with hello.", + onLog: async () => { + } + } + ); + const parsed = parseOpenCodeJsonl(probe.stdout); + const detail = summarizeProbeDetail3(probe.stdout, probe.stderr, parsed.errorMessage); + const authEvidence = `${parsed.errorMessage ?? ""} +${probe.stdout} +${probe.stderr}`.trim(); + if (probe.timedOut) { + checks.push({ + code: "opencode_hello_probe_timed_out", + level: "warn", + message: "OpenCode hello probe timed out.", + hint: "Retry the probe. If this persists, run OpenCode manually in this working directory." + }); + } else if ((probe.exitCode ?? 1) === 0 && !parsed.errorMessage) { + const summary = parsed.summary.trim(); + const hasHello = /\bhello\b/i.test(summary); + checks.push({ + code: hasHello ? "opencode_hello_probe_passed" : "opencode_hello_probe_unexpected_output", + level: hasHello ? "info" : "warn", + message: hasHello ? "OpenCode hello probe succeeded." : "OpenCode probe ran but did not return `hello` as expected.", + ...summary ? { detail: summary.replace(/\s+/g, " ").trim().slice(0, 240) } : {}, + ...hasHello ? {} : { + hint: "Run `opencode run --format json` manually and prompt `Respond with hello` to inspect output." + } + }); + } else if (/ProviderModelNotFoundError/i.test(authEvidence)) { + checks.push({ + code: "opencode_hello_probe_model_unavailable", + level: "warn", + message: "The configured model was not found by the provider.", + ...detail ? { detail } : {}, + hint: "Run `opencode models` and choose an available provider/model ID." + }); + } else if (OPENCODE_AUTH_REQUIRED_RE.test(authEvidence)) { + checks.push({ + code: "opencode_hello_probe_auth_required", + level: "warn", + message: "OpenCode is installed, but provider authentication is not ready.", + ...detail ? { detail } : {}, + hint: "Run `opencode auth login` or set provider credentials, then retry the probe." + }); + } else { + checks.push({ + code: "opencode_hello_probe_failed", + level: "error", + message: "OpenCode hello probe failed.", + ...detail ? { detail } : {}, + hint: "Run `opencode run --format json` manually in this working directory to debug." + }); + } + } catch (err) { + checks.push({ + code: "opencode_hello_probe_failed", + level: "error", + message: "OpenCode hello probe failed.", + detail: err instanceof Error ? err.message : String(err), + hint: "Run `opencode run --format json` manually in this working directory to debug." + }); + } + } + } finally { + await preparedRuntimeConfig.cleanup(); + } + return { + adapterType: ctx.adapterType, + status: summarizeStatus3(checks), + checks, + testedAt: (/* @__PURE__ */ new Date()).toISOString() + }; +} + +// packages/adapters/opencode-local/src/server/index.ts +function readNonEmptyString4(value) { + return typeof value === "string" && value.trim().length > 0 ? value.trim() : null; +} +var sessionCodec3 = { + deserialize(raw) { + if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return null; + const record2 = raw; + const sessionId = readNonEmptyString4(record2.sessionId) ?? readNonEmptyString4(record2.session_id) ?? readNonEmptyString4(record2.sessionID); + if (!sessionId) return null; + const cwd = readNonEmptyString4(record2.cwd) ?? readNonEmptyString4(record2.workdir) ?? readNonEmptyString4(record2.folder); + const workspaceId = readNonEmptyString4(record2.workspaceId) ?? readNonEmptyString4(record2.workspace_id); + const repoUrl = readNonEmptyString4(record2.repoUrl) ?? readNonEmptyString4(record2.repo_url); + const repoRef = readNonEmptyString4(record2.repoRef) ?? readNonEmptyString4(record2.repo_ref); + return { + sessionId, + ...cwd ? { cwd } : {}, + ...workspaceId ? { workspaceId } : {}, + ...repoUrl ? { repoUrl } : {}, + ...repoRef ? { repoRef } : {} + }; + }, + serialize(params) { + if (!params) return null; + const sessionId = readNonEmptyString4(params.sessionId) ?? readNonEmptyString4(params.session_id) ?? readNonEmptyString4(params.sessionID); + if (!sessionId) return null; + const cwd = readNonEmptyString4(params.cwd) ?? readNonEmptyString4(params.workdir) ?? readNonEmptyString4(params.folder); + const workspaceId = readNonEmptyString4(params.workspaceId) ?? readNonEmptyString4(params.workspace_id); + const repoUrl = readNonEmptyString4(params.repoUrl) ?? readNonEmptyString4(params.repo_url); + const repoRef = readNonEmptyString4(params.repoRef) ?? readNonEmptyString4(params.repo_ref); + return { + sessionId, + ...cwd ? { cwd } : {}, + ...workspaceId ? { workspaceId } : {}, + ...repoUrl ? { repoUrl } : {}, + ...repoRef ? { repoRef } : {} + }; + }, + getDisplayId(params) { + if (!params) return null; + return readNonEmptyString4(params.sessionId) ?? readNonEmptyString4(params.session_id) ?? readNonEmptyString4(params.sessionID); + } +}; + +// server/src/services/agent-instructions.ts +import fs14 from "node:fs/promises"; +import path18 from "node:path"; +var ENTRY_FILE_DEFAULT = "AGENTS.md"; +var MODE_KEY = "instructionsBundleMode"; +var ROOT_KEY = "instructionsRootPath"; +var ENTRY_KEY = "instructionsEntryFile"; +var FILE_KEY = "instructionsFilePath"; +var PROMPT_KEY = "promptTemplate"; +var BOOTSTRAP_PROMPT_KEY = "bootstrapPromptTemplate"; +var LEGACY_PROMPT_TEMPLATE_PATH = "promptTemplate.legacy.md"; +var IGNORED_INSTRUCTIONS_FILE_NAMES = /* @__PURE__ */ new Set([".DS_Store", "Thumbs.db", "Desktop.ini"]); +var IGNORED_INSTRUCTIONS_DIRECTORY_NAMES = /* @__PURE__ */ new Set([ + ".git", + ".nox", + ".pytest_cache", + ".ruff_cache", + ".tox", + ".venv", + "__pycache__", + "node_modules", + "venv" +]); +function asRecord2(value) { + if (typeof value !== "object" || value === null || Array.isArray(value)) return {}; + return value; +} +function asString4(value) { + if (typeof value !== "string") return null; + const trimmed = value.trim(); + return trimmed.length > 0 ? trimmed : null; +} +function isBundleMode(value) { + return value === "managed" || value === "external"; +} +function inferLanguage(relativePath) { + const lower = relativePath.toLowerCase(); + if (lower.endsWith(".md")) return "markdown"; + if (lower.endsWith(".json")) return "json"; + if (lower.endsWith(".yaml") || lower.endsWith(".yml")) return "yaml"; + if (lower.endsWith(".ts") || lower.endsWith(".tsx")) return "typescript"; + if (lower.endsWith(".js") || lower.endsWith(".jsx") || lower.endsWith(".mjs") || lower.endsWith(".cjs")) { + return "javascript"; + } + if (lower.endsWith(".sh")) return "bash"; + if (lower.endsWith(".py")) return "python"; + if (lower.endsWith(".toml")) return "toml"; + if (lower.endsWith(".txt")) return "text"; + return "text"; +} +function isMarkdown(relativePath) { + return relativePath.toLowerCase().endsWith(".md"); +} +function normalizeRelativeFilePath(candidatePath) { + const normalized = path18.posix.normalize(candidatePath.replaceAll("\\", "/")).replace(/^\/+/, ""); + if (!normalized || normalized === "." || normalized === ".." || normalized.startsWith("../")) { + throw unprocessable("Instructions file path must stay within the bundle root"); + } + return normalized; +} +function resolvePathWithinRoot(rootPath, relativePath) { + const normalizedRelativePath = normalizeRelativeFilePath(relativePath); + const absoluteRoot = path18.resolve(rootPath); + const absolutePath = path18.resolve(absoluteRoot, normalizedRelativePath); + const relativeToRoot = path18.relative(absoluteRoot, absolutePath); + if (relativeToRoot === ".." || relativeToRoot.startsWith(`..${path18.sep}`)) { + throw unprocessable("Instructions file path must stay within the bundle root"); + } + return absolutePath; +} +function resolveManagedInstructionsRoot(agent) { + return path18.resolve( + resolveTaskcoreInstanceRoot(), + "companies", + agent.companyId, + "agents", + agent.id, + "instructions" + ); +} +function resolveLegacyInstructionsPath(candidatePath, config3) { + if (path18.isAbsolute(candidatePath)) return candidatePath; + const cwd = asString4(config3.cwd); + if (!cwd || !path18.isAbsolute(cwd)) { + throw unprocessable( + "Legacy relative instructionsFilePath requires adapterConfig.cwd to be set to an absolute path" + ); + } + return path18.resolve(cwd, candidatePath); +} +async function statIfExists(targetPath) { + return fs14.stat(targetPath).catch(() => null); +} +function shouldIgnoreInstructionsEntry(entry) { + if (entry.name === "." || entry.name === "..") return true; + if (entry.isDirectory()) { + return IGNORED_INSTRUCTIONS_DIRECTORY_NAMES.has(entry.name); + } + if (!entry.isFile()) return false; + return IGNORED_INSTRUCTIONS_FILE_NAMES.has(entry.name) || entry.name.startsWith("._") || entry.name.endsWith(".pyc") || entry.name.endsWith(".pyo"); +} +async function listFilesRecursive(rootPath) { + const output = []; + async function walk(currentPath, relativeDir) { + const entries2 = await fs14.readdir(currentPath, { withFileTypes: true }).catch(() => []); + for (const entry of entries2) { + if (shouldIgnoreInstructionsEntry(entry)) continue; + const absolutePath = path18.join(currentPath, entry.name); + const relativePath = normalizeRelativeFilePath( + relativeDir ? path18.posix.join(relativeDir, entry.name) : entry.name + ); + if (entry.isDirectory()) { + await walk(absolutePath, relativePath); + continue; + } + if (!entry.isFile()) continue; + output.push(relativePath); + } + } + await walk(rootPath, ""); + return output.sort((left, right) => left.localeCompare(right)); +} +async function readFileSummary(rootPath, relativePath, entryFile) { + const absolutePath = resolvePathWithinRoot(rootPath, relativePath); + const stat5 = await fs14.stat(absolutePath); + return { + path: relativePath, + size: stat5.size, + language: inferLanguage(relativePath), + markdown: isMarkdown(relativePath), + isEntryFile: relativePath === entryFile, + editable: true, + deprecated: false, + virtual: false + }; +} +async function readLegacyInstructions(agent, config3) { + const instructionsFilePath = asString4(config3[FILE_KEY]); + if (instructionsFilePath) { + try { + const resolvedPath2 = resolveLegacyInstructionsPath(instructionsFilePath, config3); + return await fs14.readFile(resolvedPath2, "utf8"); + } catch { + } + } + return asString4(config3[PROMPT_KEY]) ?? ""; +} +function deriveBundleState(agent) { + const config3 = asRecord2(agent.adapterConfig); + const warnings = []; + const storedModeRaw = config3[MODE_KEY]; + const storedRootRaw = asString4(config3[ROOT_KEY]); + const legacyInstructionsPath = asString4(config3[FILE_KEY]); + let mode = isBundleMode(storedModeRaw) ? storedModeRaw : null; + let rootPath = storedRootRaw ? resolveHomeAwarePath(storedRootRaw) : null; + let entryFile = ENTRY_FILE_DEFAULT; + const storedEntryRaw = asString4(config3[ENTRY_KEY]); + if (storedEntryRaw) { + try { + entryFile = normalizeRelativeFilePath(storedEntryRaw); + } catch { + warnings.push(`Ignored invalid instructions entry file "${storedEntryRaw}".`); + } + } + if (!rootPath && legacyInstructionsPath) { + try { + const resolvedLegacyPath = resolveLegacyInstructionsPath(legacyInstructionsPath, config3); + rootPath = path18.dirname(resolvedLegacyPath); + entryFile = path18.basename(resolvedLegacyPath); + mode = resolvedLegacyPath.startsWith(`${resolveManagedInstructionsRoot(agent)}${path18.sep}`) || resolvedLegacyPath === path18.join(resolveManagedInstructionsRoot(agent), entryFile) ? "managed" : "external"; + if (!path18.isAbsolute(legacyInstructionsPath)) { + warnings.push("Using legacy relative instructionsFilePath; migrate this agent to a managed or absolute external bundle."); + } + } catch (err) { + warnings.push(err instanceof Error ? err.message : String(err)); + } + } + const resolvedEntryPath = rootPath ? path18.resolve(rootPath, entryFile) : null; + return { + config: config3, + mode, + rootPath, + entryFile, + resolvedEntryPath, + warnings, + legacyPromptTemplateActive: Boolean(asString4(config3[PROMPT_KEY])), + legacyBootstrapPromptTemplateActive: Boolean(asString4(config3[BOOTSTRAP_PROMPT_KEY])) + }; +} +async function recoverManagedBundleState(agent, state2) { + const managedRootPath = resolveManagedInstructionsRoot(agent); + const stat5 = await statIfExists(managedRootPath); + if (!stat5?.isDirectory()) return state2; + const files = await listFilesRecursive(managedRootPath); + if (files.length === 0) return state2; + const recoveredEntryFile = files.includes(state2.entryFile) ? state2.entryFile : files.includes(ENTRY_FILE_DEFAULT) ? ENTRY_FILE_DEFAULT : files[0]; + if (!state2.rootPath) { + return { + ...state2, + mode: "managed", + rootPath: managedRootPath, + entryFile: recoveredEntryFile, + resolvedEntryPath: path18.resolve(managedRootPath, recoveredEntryFile) + }; + } + if (state2.mode === "external") return state2; + const resolvedConfiguredRoot = path18.resolve(state2.rootPath); + const configuredRootMatchesManaged = resolvedConfiguredRoot === managedRootPath; + const hasEntryMismatch = recoveredEntryFile !== state2.entryFile; + if (configuredRootMatchesManaged && !hasEntryMismatch) { + return state2; + } + const warnings = [...state2.warnings]; + if (!configuredRootMatchesManaged) { + warnings.push( + `Recovered managed instructions from disk at ${managedRootPath}; ignoring stale configured root ${state2.rootPath}.` + ); + } + if (hasEntryMismatch) { + warnings.push( + `Recovered managed instructions entry file from disk as ${recoveredEntryFile}; previous entry ${state2.entryFile} was missing.` + ); + } + return { + ...state2, + mode: "managed", + rootPath: managedRootPath, + entryFile: recoveredEntryFile, + resolvedEntryPath: path18.resolve(managedRootPath, recoveredEntryFile), + warnings + }; +} +function toBundle(agent, state2, files) { + const nextFiles = [...files]; + if (state2.legacyPromptTemplateActive && !nextFiles.some((file2) => file2.path === LEGACY_PROMPT_TEMPLATE_PATH)) { + const legacyPromptTemplate = asString4(state2.config[PROMPT_KEY]) ?? ""; + nextFiles.push({ + path: LEGACY_PROMPT_TEMPLATE_PATH, + size: legacyPromptTemplate.length, + language: "markdown", + markdown: true, + isEntryFile: false, + editable: true, + deprecated: true, + virtual: true + }); + } + nextFiles.sort((left, right) => left.path.localeCompare(right.path)); + return { + agentId: agent.id, + companyId: agent.companyId, + mode: state2.mode, + rootPath: state2.rootPath, + managedRootPath: resolveManagedInstructionsRoot(agent), + entryFile: state2.entryFile, + resolvedEntryPath: state2.resolvedEntryPath, + editable: Boolean(state2.rootPath), + warnings: state2.warnings, + legacyPromptTemplateActive: state2.legacyPromptTemplateActive, + legacyBootstrapPromptTemplateActive: state2.legacyBootstrapPromptTemplateActive, + files: nextFiles + }; +} +function applyBundleConfig(config3, input) { + const next = { + ...config3, + [MODE_KEY]: input.mode, + [ROOT_KEY]: input.rootPath, + [ENTRY_KEY]: input.entryFile, + [FILE_KEY]: path18.resolve(input.rootPath, input.entryFile) + }; + if (input.clearLegacyPromptTemplate) { + delete next[PROMPT_KEY]; + delete next[BOOTSTRAP_PROMPT_KEY]; + } + return next; +} +function buildPersistedBundleConfig(derived, current, options) { + const currentRootPath = current.rootPath ? path18.resolve(current.rootPath) : null; + const derivedRootPath = derived.rootPath ? path18.resolve(derived.rootPath) : null; + const configMatchesRecoveredState = derived.mode === current.mode && derivedRootPath !== null && currentRootPath !== null && derivedRootPath === currentRootPath && derived.entryFile === current.entryFile; + if (configMatchesRecoveredState && !options?.clearLegacyPromptTemplate) { + return current.config; + } + if (!current.rootPath || !current.mode) { + return current.config; + } + return applyBundleConfig(current.config, { + mode: current.mode, + rootPath: current.rootPath, + entryFile: current.entryFile, + clearLegacyPromptTemplate: options?.clearLegacyPromptTemplate + }); +} +async function writeBundleFiles(rootPath, files, options) { + for (const [relativePath, content] of Object.entries(files)) { + const normalizedPath = normalizeRelativeFilePath(relativePath); + const absolutePath = resolvePathWithinRoot(rootPath, normalizedPath); + const existingStat = await statIfExists(absolutePath); + if (existingStat?.isFile() && !options?.overwriteExisting) continue; + await fs14.mkdir(path18.dirname(absolutePath), { recursive: true }); + await fs14.writeFile(absolutePath, content, "utf8"); + } +} +function syncInstructionsBundleConfigFromFilePath(agent, adapterConfig) { + const instructionsFilePath = asString4(adapterConfig[FILE_KEY]); + const next = { ...adapterConfig }; + if (!instructionsFilePath) { + delete next[MODE_KEY]; + delete next[ROOT_KEY]; + delete next[ENTRY_KEY]; + return next; + } + const resolvedPath2 = resolveLegacyInstructionsPath(instructionsFilePath, adapterConfig); + const rootPath = path18.dirname(resolvedPath2); + const entryFile = path18.basename(resolvedPath2); + const mode = resolvedPath2.startsWith(`${resolveManagedInstructionsRoot(agent)}${path18.sep}`) || resolvedPath2 === path18.join(resolveManagedInstructionsRoot(agent), entryFile) ? "managed" : "external"; + return applyBundleConfig(next, { mode, rootPath, entryFile }); +} +function agentInstructionsService() { + async function getBundle(agent) { + const state2 = await recoverManagedBundleState(agent, deriveBundleState(agent)); + if (!state2.rootPath) return toBundle(agent, state2, []); + const stat5 = await statIfExists(state2.rootPath); + if (!stat5?.isDirectory()) { + return toBundle(agent, { + ...state2, + warnings: [...state2.warnings, `Instructions root does not exist: ${state2.rootPath}`] + }, []); + } + const files = await listFilesRecursive(state2.rootPath); + const summaries = await Promise.all(files.map((relativePath) => readFileSummary(state2.rootPath, relativePath, state2.entryFile))); + return toBundle(agent, state2, summaries); + } + async function readFile5(agent, relativePath) { + const state2 = await recoverManagedBundleState(agent, deriveBundleState(agent)); + if (relativePath === LEGACY_PROMPT_TEMPLATE_PATH) { + const content2 = asString4(state2.config[PROMPT_KEY]); + if (content2 === null) throw notFound("Instructions file not found"); + return { + path: LEGACY_PROMPT_TEMPLATE_PATH, + size: content2.length, + language: "markdown", + markdown: true, + isEntryFile: false, + editable: true, + deprecated: true, + virtual: true, + content: content2 + }; + } + if (!state2.rootPath) throw notFound("Agent instructions bundle is not configured"); + const absolutePath = resolvePathWithinRoot(state2.rootPath, relativePath); + const [content, stat5] = await Promise.all([ + fs14.readFile(absolutePath, "utf8").catch(() => null), + fs14.stat(absolutePath).catch(() => null) + ]); + if (content === null || !stat5?.isFile()) throw notFound("Instructions file not found"); + const normalizedPath = normalizeRelativeFilePath(relativePath); + return { + path: normalizedPath, + size: stat5.size, + language: inferLanguage(normalizedPath), + markdown: isMarkdown(normalizedPath), + isEntryFile: normalizedPath === state2.entryFile, + editable: true, + deprecated: false, + virtual: false, + content + }; + } + async function ensureWritableBundle(agent, options) { + const derived = deriveBundleState(agent); + const current = await recoverManagedBundleState(agent, derived); + if (current.rootPath && current.mode) { + const adapterConfig = buildPersistedBundleConfig(derived, current, options); + return { + adapterConfig, + state: deriveBundleState({ ...agent, adapterConfig }) + }; + } + const managedRoot = resolveManagedInstructionsRoot(agent); + const entryFile = current.entryFile || ENTRY_FILE_DEFAULT; + const nextConfig = applyBundleConfig(current.config, { + mode: "managed", + rootPath: managedRoot, + entryFile, + clearLegacyPromptTemplate: options?.clearLegacyPromptTemplate + }); + await fs14.mkdir(managedRoot, { recursive: true }); + const entryPath = resolvePathWithinRoot(managedRoot, entryFile); + const entryStat = await statIfExists(entryPath); + if (!entryStat?.isFile()) { + const legacyInstructions = await readLegacyInstructions(agent, current.config); + if (legacyInstructions.trim().length > 0) { + await fs14.mkdir(path18.dirname(entryPath), { recursive: true }); + await fs14.writeFile(entryPath, legacyInstructions, "utf8"); + } + } + return { + adapterConfig: nextConfig, + state: deriveBundleState({ ...agent, adapterConfig: nextConfig }) + }; + } + async function updateBundle(agent, input) { + const state2 = await recoverManagedBundleState(agent, deriveBundleState(agent)); + const nextMode = input.mode ?? state2.mode ?? "managed"; + const nextEntryFile = input.entryFile ? normalizeRelativeFilePath(input.entryFile) : state2.entryFile; + let nextRootPath; + if (nextMode === "managed") { + nextRootPath = resolveManagedInstructionsRoot(agent); + } else { + const rootPath = asString4(input.rootPath) ?? state2.rootPath; + if (!rootPath) { + throw unprocessable("External instructions bundles require an absolute rootPath"); + } + const resolvedRoot = resolveHomeAwarePath(rootPath); + if (!path18.isAbsolute(resolvedRoot)) { + throw unprocessable("External instructions bundles require an absolute rootPath"); + } + nextRootPath = resolvedRoot; + } + await fs14.mkdir(nextRootPath, { recursive: true }); + const existingFiles = await listFilesRecursive(nextRootPath); + const exported = await exportFiles(agent); + if (existingFiles.length === 0) { + await writeBundleFiles(nextRootPath, exported.files); + } + const refreshedFiles = existingFiles.length === 0 ? await listFilesRecursive(nextRootPath) : existingFiles; + if (!refreshedFiles.includes(nextEntryFile)) { + const nextEntryContent = exported.files[nextEntryFile] ?? exported.files[exported.entryFile] ?? ""; + await writeBundleFiles(nextRootPath, { [nextEntryFile]: nextEntryContent }); + } + const nextConfig = applyBundleConfig(state2.config, { + mode: nextMode, + rootPath: nextRootPath, + entryFile: nextEntryFile, + clearLegacyPromptTemplate: input.clearLegacyPromptTemplate + }); + const nextBundle = await getBundle({ ...agent, adapterConfig: nextConfig }); + return { bundle: nextBundle, adapterConfig: nextConfig }; + } + async function writeFile(agent, relativePath, content, options) { + const current = deriveBundleState(agent); + if (relativePath === LEGACY_PROMPT_TEMPLATE_PATH) { + const adapterConfig = { + ...current.config, + [PROMPT_KEY]: content + }; + const nextAgent2 = { ...agent, adapterConfig }; + const [bundle2, file3] = await Promise.all([ + getBundle(nextAgent2), + readFile5(nextAgent2, LEGACY_PROMPT_TEMPLATE_PATH) + ]); + return { bundle: bundle2, file: file3, adapterConfig }; + } + const prepared = await ensureWritableBundle(agent, options); + const absolutePath = resolvePathWithinRoot(prepared.state.rootPath, relativePath); + await fs14.mkdir(path18.dirname(absolutePath), { recursive: true }); + await fs14.writeFile(absolutePath, content, "utf8"); + const nextAgent = { ...agent, adapterConfig: prepared.adapterConfig }; + const [bundle, file2] = await Promise.all([ + getBundle(nextAgent), + readFile5(nextAgent, relativePath) + ]); + return { bundle, file: file2, adapterConfig: prepared.adapterConfig }; + } + async function deleteFile(agent, relativePath) { + const derived = deriveBundleState(agent); + const state2 = await recoverManagedBundleState(agent, derived); + if (relativePath === LEGACY_PROMPT_TEMPLATE_PATH) { + throw unprocessable("Cannot delete the legacy promptTemplate pseudo-file"); + } + if (!state2.rootPath) throw notFound("Agent instructions bundle is not configured"); + const normalizedPath = normalizeRelativeFilePath(relativePath); + if (normalizedPath === state2.entryFile) { + throw unprocessable("Cannot delete the bundle entry file"); + } + const absolutePath = resolvePathWithinRoot(state2.rootPath, normalizedPath); + await fs14.rm(absolutePath, { force: true }); + const adapterConfig = buildPersistedBundleConfig(derived, state2); + const bundle = await getBundle({ ...agent, adapterConfig }); + return { bundle, adapterConfig }; + } + async function exportFiles(agent) { + const state2 = await recoverManagedBundleState(agent, deriveBundleState(agent)); + if (state2.rootPath) { + const stat5 = await statIfExists(state2.rootPath); + if (stat5?.isDirectory()) { + const relativePaths = await listFilesRecursive(state2.rootPath); + const files = Object.fromEntries(await Promise.all(relativePaths.map(async (relativePath) => { + const absolutePath = resolvePathWithinRoot(state2.rootPath, relativePath); + const content = await fs14.readFile(absolutePath, "utf8"); + return [relativePath, content]; + }))); + if (Object.keys(files).length > 0) { + return { files, entryFile: state2.entryFile, warnings: state2.warnings }; + } + } + } + const legacyBody = await readLegacyInstructions(agent, state2.config); + return { + files: { [state2.entryFile]: legacyBody || "_No AGENTS instructions were resolved from current agent config._" }, + entryFile: state2.entryFile, + warnings: state2.warnings + }; + } + async function materializeManagedBundle(agent, files, options) { + const rootPath = resolveManagedInstructionsRoot(agent); + const entryFile = options?.entryFile ? normalizeRelativeFilePath(options.entryFile) : ENTRY_FILE_DEFAULT; + if (options?.replaceExisting) { + await fs14.rm(rootPath, { recursive: true, force: true }); + } + await fs14.mkdir(rootPath, { recursive: true }); + const normalizedEntries = Object.entries(files).map(([relativePath, content]) => [ + normalizeRelativeFilePath(relativePath), + content + ]); + for (const [relativePath, content] of normalizedEntries) { + const absolutePath = resolvePathWithinRoot(rootPath, relativePath); + await fs14.mkdir(path18.dirname(absolutePath), { recursive: true }); + await fs14.writeFile(absolutePath, content, "utf8"); + } + if (!normalizedEntries.some(([relativePath]) => relativePath === entryFile)) { + await fs14.writeFile(resolvePathWithinRoot(rootPath, entryFile), "", "utf8"); + } + const adapterConfig = applyBundleConfig(asRecord2(agent.adapterConfig), { + mode: "managed", + rootPath, + entryFile, + clearLegacyPromptTemplate: options?.clearLegacyPromptTemplate + }); + const bundle = await getBundle({ ...agent, adapterConfig }); + return { bundle, adapterConfig }; + } + return { + getBundle, + readFile: readFile5, + updateBundle, + writeFile, + deleteFile, + exportFiles, + ensureManagedBundle: ensureWritableBundle, + materializeManagedBundle + }; +} + +// server/src/services/feedback-redaction.ts +import { createHash as createHash5 } from "node:crypto"; + +// server/src/log-redaction.ts +import os12 from "node:os"; +var CURRENT_USER_REDACTION_TOKEN = "*"; +function isPlainObject2(value) { + if (typeof value !== "object" || value === null || Array.isArray(value)) return false; + const proto = Object.getPrototypeOf(value); + return proto === Object.prototype || proto === null; +} +function escapeRegExp(value) { + return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +} +function uniqueNonEmpty(values2) { + return Array.from(new Set(values2.map((value) => value?.trim() ?? "").filter(Boolean))); +} +function splitPathSegments(value) { + return value.replace(/[\\/]+$/, "").split(/[\\/]+/).filter(Boolean); +} +function replaceLastPathSegment(pathValue, replacement) { + const normalized = pathValue.replace(/[\\/]+$/, ""); + const lastSeparator = Math.max(normalized.lastIndexOf("/"), normalized.lastIndexOf("\\")); + if (lastSeparator < 0) return replacement; + return `${normalized.slice(0, lastSeparator + 1)}${replacement}`; +} +function maskUserNameForLogs(value, fallback = CURRENT_USER_REDACTION_TOKEN) { + const trimmed = value.trim(); + if (!trimmed) return fallback; + return `${trimmed[0]}${"*".repeat(Math.max(1, Array.from(trimmed).length - 1))}`; +} +function defaultUserNames() { + const candidates = [ + process.env.USER, + process.env.LOGNAME, + process.env.USERNAME + ]; + try { + candidates.push(os12.userInfo().username); + } catch { + } + return uniqueNonEmpty(candidates); +} +function defaultHomeDirs(userNames) { + const candidates = [ + process.env.HOME, + process.env.USERPROFILE + ]; + try { + candidates.push(os12.homedir()); + } catch { + } + for (const userName of userNames) { + candidates.push(`/Users/${userName}`); + candidates.push(`/home/${userName}`); + candidates.push(`C:\\Users\\${userName}`); + } + return uniqueNonEmpty(candidates); +} +var cachedCurrentUserCandidates = null; +function getDefaultCurrentUserCandidates() { + if (cachedCurrentUserCandidates) return cachedCurrentUserCandidates; + const userNames = defaultUserNames(); + cachedCurrentUserCandidates = { + userNames, + homeDirs: defaultHomeDirs(userNames), + replacement: CURRENT_USER_REDACTION_TOKEN + }; + return cachedCurrentUserCandidates; +} +function resolveCurrentUserCandidates(opts) { + const defaults = getDefaultCurrentUserCandidates(); + const userNames = uniqueNonEmpty(opts?.userNames ?? defaults.userNames); + const homeDirs = uniqueNonEmpty(opts?.homeDirs ?? defaults.homeDirs); + const replacement = opts?.replacement?.trim() || defaults.replacement; + return { userNames, homeDirs, replacement }; +} +function redactCurrentUserText(input, opts) { + if (!input) return input; + if (opts?.enabled === false) return input; + const { userNames, homeDirs, replacement } = resolveCurrentUserCandidates(opts); + let result = input; + for (const homeDir of [...homeDirs].sort((a5, b6) => b6.length - a5.length)) { + const lastSegment = splitPathSegments(homeDir).pop() ?? ""; + const replacementDir = lastSegment ? replaceLastPathSegment(homeDir, maskUserNameForLogs(lastSegment, replacement)) : replacement; + result = result.split(homeDir).join(replacementDir); + } + for (const userName of [...userNames].sort((a5, b6) => b6.length - a5.length)) { + const pattern = new RegExp(`(? redactCurrentUserValue(entry, opts)); + } + if (!isPlainObject2(value)) { + return value; + } + const redacted = {}; + for (const [key, entry] of Object.entries(value)) { + redacted[key] = redactCurrentUserValue(entry, opts); + } + return redacted; +} + +// server/src/redaction.ts +var SECRET_PAYLOAD_KEY_RE = /(api[-_]?key|access[-_]?token|auth(?:_?token)?|authorization|bearer|secret|passwd|password|credential|jwt|private[-_]?key|cookie|connectionstring)/i; +var JWT_VALUE_RE = /^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)?$/; +var REDACTED_EVENT_VALUE = "***REDACTED***"; +function isPlainObject3(value) { + if (typeof value !== "object" || value === null || Array.isArray(value)) return false; + const proto = Object.getPrototypeOf(value); + return proto === Object.prototype || proto === null; +} +function sanitizeValue(value) { + if (value === null || value === void 0) return value; + if (Array.isArray(value)) return value.map(sanitizeValue); + if (isSecretRefBinding(value)) return value; + if (isPlainBinding(value)) return { type: "plain", value: sanitizeValue(value.value) }; + if (!isPlainObject3(value)) return value; + return sanitizeRecord(value); +} +function isSecretRefBinding(value) { + if (!isPlainObject3(value)) return false; + return value.type === "secret_ref" && typeof value.secretId === "string"; +} +function isPlainBinding(value) { + if (!isPlainObject3(value)) return false; + return value.type === "plain" && "value" in value; +} +function sanitizeRecord(record2) { + const redacted = {}; + for (const [key, value] of Object.entries(record2)) { + if (SECRET_PAYLOAD_KEY_RE.test(key)) { + if (isSecretRefBinding(value)) { + redacted[key] = sanitizeValue(value); + continue; + } + if (isPlainBinding(value)) { + redacted[key] = { type: "plain", value: REDACTED_EVENT_VALUE }; + continue; + } + redacted[key] = REDACTED_EVENT_VALUE; + continue; + } + if (typeof value === "string" && JWT_VALUE_RE.test(value)) { + redacted[key] = REDACTED_EVENT_VALUE; + continue; + } + redacted[key] = sanitizeValue(value); + } + return redacted; +} +function redactEventPayload(payload2) { + if (!payload2) return null; + if (!isPlainObject3(payload2)) return payload2; + return sanitizeRecord(payload2); +} + +// server/src/services/feedback-redaction.ts +var SECRET_ASSIGNMENT_RE = /\b(api[-_]?key|access[-_]?token|auth(?:_?token)?|authorization|bearer|secret|passwd|password|credential|jwt|private[-_]?key|cookie|connectionstring)\s*[:=]\s*([^\s,;]+)/gi; +var FREE_TEXT_PATTERNS = [ + { + kind: "pem_block", + regex: /-----BEGIN [^-]+-----[\s\S]+?-----END [^-]+-----/g, + replacement: "[REDACTED_PEM_BLOCK]" + }, + { + kind: "secret_assignment", + regex: SECRET_ASSIGNMENT_RE, + replacement: (_match, key) => `${key}=[REDACTED]` + }, + { + kind: "bearer_token", + regex: /Bearer\s+[A-Za-z0-9._~+/-]+=*/gi, + replacement: "Bearer [REDACTED_TOKEN]" + }, + { + kind: "github_token", + regex: /\bgh[pousr]_[A-Za-z0-9_]{20,}\b/g, + replacement: "[REDACTED_GITHUB_TOKEN]" + }, + { + kind: "provider_api_key", + regex: /\bsk-(?:ant-)?[A-Za-z0-9_-]{12,}\b/g, + replacement: "[REDACTED_API_KEY]" + }, + { + kind: "jwt", + regex: /\b[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)?\b/g, + replacement: "[REDACTED_JWT]" + }, + { + kind: "dsn", + regex: /\b(?:postgres(?:ql)?|mysql|mongodb(?:\+srv)?|redis|amqp|kafka|nats|mssql):\/\/[^\s<>'")]+/gi, + replacement: "[REDACTED_CONNECTION_STRING]" + }, + { + kind: "email", + regex: /\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/gi, + replacement: "[REDACTED_EMAIL]" + }, + { + kind: "phone", + regex: /(? 0) { + output = result.output; + recordField(state2, fieldPath); + increment(state2, pattern.kind, result.matches); + } + } + if (output.length > maxLength) { + output = `${output.slice(0, Math.max(0, maxLength - 1))}...`; + state2.truncatedFields.add(fieldPath); + } + return output; +} +function sanitizeFeedbackValue(value, state2, fieldPath, maxStringLength) { + if (typeof value === "string") { + return sanitizeFeedbackText(value, state2, fieldPath, maxStringLength); + } + if (Array.isArray(value)) { + return value.map((entry, index2) => sanitizeFeedbackValue(entry, state2, `${fieldPath}[${index2}]`, maxStringLength)); + } + if (!isPlainRecord(value)) { + return value; + } + const structurallySanitized = sanitizeRecord(value); + if (stableStringify(structurallySanitized) !== stableStringify(value)) { + recordField(state2, fieldPath); + increment(state2, "structured_secret", 1); + } + const output = {}; + for (const [key, entry] of Object.entries(structurallySanitized)) { + output[key] = sanitizeFeedbackValue(entry, state2, `${fieldPath}.${key}`, maxStringLength); + } + return output; +} +function finalizeFeedbackRedactionSummary(state2) { + return { + strategy: "deterministic_feedback_v2", + redactedFields: Array.from(state2.redactedFields).sort(), + truncatedFields: Array.from(state2.truncatedFields).sort(), + omittedFields: Array.from(state2.omittedFields).sort(), + notes: Array.from(state2.notes).sort(), + counts: Object.fromEntries(Array.from(state2.counts.entries()).sort(([left], [right]) => left.localeCompare(right))) + }; +} +function stableStringify(value) { + if (value === null || typeof value !== "object") { + return JSON.stringify(value); + } + if (Array.isArray(value)) { + return `[${value.map((entry) => stableStringify(entry)).join(",")}]`; + } + const entries2 = Object.entries(value).sort(([left], [right]) => left.localeCompare(right)).map(([key, entry]) => `${JSON.stringify(key)}:${stableStringify(entry)}`); + return `{${entries2.join(",")}}`; +} +function sha256Digest(value) { + return createHash5("sha256").update(stableStringify(value)).digest("hex"); +} + +// server/src/services/run-log-store.ts +import { createReadStream, promises as fs15 } from "node:fs"; +import path19 from "node:path"; +import { createHash as createHash6 } from "node:crypto"; +function safeSegments(...segments) { + return segments.map((segment) => segment.replace(/[^a-zA-Z0-9._-]/g, "_")); +} +function resolveWithin(basePath, relativePath) { + const resolved = path19.resolve(basePath, relativePath); + const base = path19.resolve(basePath) + path19.sep; + if (!resolved.startsWith(base) && resolved !== path19.resolve(basePath)) { + throw new Error("Invalid log path"); + } + return resolved; +} +function createLocalFileRunLogStore(basePath) { + async function ensureDir(relativeDir) { + const dir = resolveWithin(basePath, relativeDir); + await fs15.mkdir(dir, { recursive: true }); + } + async function readFileRange(filePath, offset, limitBytes) { + const stat5 = await fs15.stat(filePath).catch(() => null); + if (!stat5) throw notFound("Run log not found"); + const start = Math.max(0, Math.min(offset, stat5.size)); + const end = Math.max(start, Math.min(start + limitBytes - 1, stat5.size - 1)); + if (start > end) { + return { content: "", nextOffset: start }; + } + const chunks = []; + await new Promise((resolve4, reject) => { + const stream = createReadStream(filePath, { start, end }); + stream.on("data", (chunk) => { + chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)); + }); + stream.on("error", reject); + stream.on("end", () => resolve4()); + }); + const content = Buffer.concat(chunks).toString("utf8"); + const nextOffset = end + 1 < stat5.size ? end + 1 : void 0; + return { content, nextOffset }; + } + async function sha256File(filePath) { + return new Promise((resolve4, reject) => { + const hash2 = createHash6("sha256"); + const stream = createReadStream(filePath); + stream.on("data", (chunk) => hash2.update(chunk)); + stream.on("error", reject); + stream.on("end", () => resolve4(hash2.digest("hex"))); + }); + } + return { + async begin(input) { + const [companyId, agentId] = safeSegments(input.companyId, input.agentId); + const runId = safeSegments(input.runId)[0]; + const relDir = path19.join(companyId, agentId); + const relPath = path19.join(relDir, `${runId}.ndjson`); + await ensureDir(relDir); + const absPath = resolveWithin(basePath, relPath); + await fs15.writeFile(absPath, "", "utf8"); + return { store: "local_file", logRef: relPath }; + }, + async append(handle, event) { + if (handle.store !== "local_file") return; + const absPath = resolveWithin(basePath, handle.logRef); + const line3 = JSON.stringify({ + ts: event.ts, + stream: event.stream, + chunk: event.chunk + }); + await fs15.appendFile(absPath, `${line3} +`, "utf8"); + }, + async finalize(handle) { + if (handle.store !== "local_file") { + return { bytes: 0, compressed: false }; + } + const absPath = resolveWithin(basePath, handle.logRef); + const stat5 = await fs15.stat(absPath).catch(() => null); + if (!stat5) throw notFound("Run log not found"); + const hash2 = await sha256File(absPath); + return { + bytes: stat5.size, + sha256: hash2, + compressed: false + }; + }, + async read(handle, opts) { + if (handle.store !== "local_file") { + throw notFound("Run log not found"); + } + const absPath = resolveWithin(basePath, handle.logRef); + const offset = opts?.offset ?? 0; + const limitBytes = opts?.limitBytes ?? 256e3; + return readFileRange(absPath, offset, limitBytes); + } + }; +} +var cachedStore = null; +function getRunLogStore() { + if (cachedStore) return cachedStore; + const basePath = process.env.RUN_LOG_BASE_PATH ?? path19.resolve(resolveTaskcoreInstanceRoot(), "data", "run-logs"); + cachedStore = createLocalFileRunLogStore(basePath); + return cachedStore; +} + +// server/src/services/feedback.ts +var FEEDBACK_SCHEMA_VERSION = "taskcore-feedback-envelope-v2"; +var FEEDBACK_BUNDLE_VERSION = "taskcore-feedback-bundle-v2"; +var FEEDBACK_PAYLOAD_VERSION = "taskcore-feedback-v1"; +var FEEDBACK_DESTINATION = "taskcore_labs_feedback_v1"; +var FEEDBACK_CONTEXT_WINDOW = 3; +var MAX_EXCERPT_CHARS = 200; +var MAX_PRIMARY_CONTENT_CHARS = 8e3; +var MAX_CONTEXT_ITEM_BODY_CHARS = 3e3; +var MAX_TOTAL_CONTEXT_CHARS = 12e3; +var MAX_DESCRIPTION_CHARS = 1200; +var MAX_INSTRUCTIONS_BODY_CHARS = 8e3; +var MAX_PATH_CHARS = 600; +var MAX_SKILLS = 20; +var MAX_INSTRUCTION_FILES = 20; +var MAX_TRACE_FILE_CHARS = 1e7; +var DEFAULT_INSTANCE_SETTINGS_SINGLETON_KEY = "default"; +var FEEDBACK_EXPORT_BACKEND_NOT_CONFIGURED = "Feedback export backend is not configured"; +var feedbackExportColumns = getTableColumns(feedbackExports); +var instructionsSvc = agentInstructionsService(); +function asRecord3(value) { + if (!value || typeof value !== "object" || Array.isArray(value)) return null; + return value; +} +function asString5(value) { + if (typeof value !== "string") return null; + const trimmed = value.trim(); + return trimmed.length > 0 ? trimmed : null; +} +function asNumber2(value) { + if (typeof value !== "number" || !Number.isFinite(value)) return null; + return value; +} +function asBoolean2(value) { + return typeof value === "boolean" ? value : null; +} +function uniqueNonEmpty2(values2) { + return Array.from(new Set(values2.map((value) => value?.trim() ?? "").filter(Boolean))); +} +function truncateExcerpt(text3, max = MAX_EXCERPT_CHARS) { + const normalized = text3.replace(/\s+/g, " ").trim(); + if (!normalized) return null; + return normalized.length <= max ? normalized : `${normalized.slice(0, max - 1)}...`; +} +function contentTypeForPath(filePath) { + const lower = filePath.toLowerCase(); + if (lower.endsWith(".jsonl") || lower.endsWith(".ndjson")) return "application/x-ndjson"; + if (lower.endsWith(".json")) return "application/json"; + if (lower.endsWith(".md")) return "text/markdown; charset=utf-8"; + return "text/plain; charset=utf-8"; +} +function normalizeInstanceGeneralSettings(raw) { + const parsed = instanceGeneralSettingsSchema.safeParse(raw ?? {}); + if (parsed.success) return parsed.data; + return { + censorUsernameInLogs: false, + feedbackDataSharingPreference: DEFAULT_FEEDBACK_DATA_SHARING_PREFERENCE + }; +} +function buildIssuePath(identifier) { + if (!identifier) return null; + const prefix = identifier.split("-")[0]?.trim(); + if (!prefix) return null; + return `/${prefix}/issues/${identifier}`; +} +function buildTargetSummary(input) { + return { + label: input.label, + excerpt: input.excerpt, + authorAgentId: input.authorAgentId, + authorUserId: input.authorUserId, + createdAt: input.createdAt, + documentKey: input.documentKey ?? null, + documentTitle: input.documentTitle ?? null, + revisionNumber: input.revisionNumber ?? null + }; +} +function normalizeReason(vote, reason) { + if (vote !== "down" || typeof reason !== "string") return null; + const trimmed = reason.trim(); + return trimmed.length > 0 ? trimmed : null; +} +function normalizeSkillReference(value) { + return value.trim().toLowerCase(); +} +function matchesSkillReference(skill, reference) { + const normalized = normalizeSkillReference(reference); + if (!normalized) return false; + if (skill.key.toLowerCase() === normalized) return true; + if (skill.slug.toLowerCase() === normalized) return true; + if (skill.name.toLowerCase() === normalized) return true; + const keyTail = skill.key.split("/").pop()?.toLowerCase(); + return keyTail === normalized; +} +function buildExportId(feedbackVoteId, sharedAt) { + return `fbexp_${sha256Digest(`${feedbackVoteId}:${sharedAt.toISOString()}`).slice(0, 24)}`; +} +function resolveSourceRunId(payloadSnapshot) { + const targetRunId = asString5(asRecord3(payloadSnapshot?.target)?.createdByRunId); + if (targetRunId) return targetRunId; + const bundle = asRecord3(payloadSnapshot?.bundle); + const agentContext = asRecord3(bundle?.agentContext); + const runtime = asRecord3(agentContext?.runtime); + return asString5(asRecord3(runtime?.sourceRun)?.id); +} +function makeBundleFile(input) { + return { + path: input.path, + contentType: input.contentType, + encoding: "utf8", + byteLength: Buffer.byteLength(input.contents, "utf8"), + sha256: sha256Digest(input.contents), + source: input.source, + contents: input.contents + }; +} +function appendNote(notes, note) { + if (note.trim().length === 0 || notes.includes(note)) return; + notes.push(note); +} +async function readTextFileIfPresent(filePath, state2, fieldPath) { + if (!filePath) return null; + const raw = await readFile(filePath, "utf8").catch(() => null); + if (raw == null) return null; + return sanitizeFeedbackText(raw, state2, fieldPath, MAX_TRACE_FILE_CHARS); +} +async function listChildFiles(dirPath) { + const entries2 = await readdir(dirPath, { withFileTypes: true }).catch(() => []); + return entries2.filter((entry) => entry.isFile()).map((entry) => path20.join(dirPath, entry.name)).sort((left, right) => left.localeCompare(right)); +} +async function listNestedFiles(dirPath, maxDepth = 4) { + async function walk(currentPath, depth) { + const entries2 = await readdir(currentPath, { withFileTypes: true }).catch(() => []); + const files = entries2.filter((entry) => entry.isFile()).map((entry) => path20.join(currentPath, entry.name)).sort((left, right) => left.localeCompare(right)); + if (depth >= maxDepth) return files; + const childDirs = entries2.filter((entry) => entry.isDirectory()).map((entry) => path20.join(currentPath, entry.name)).sort((left, right) => left.localeCompare(right)); + const nested = await Promise.all(childDirs.map((childDir) => walk(childDir, depth + 1))); + return [...files, ...nested.flat()]; + } + return walk(dirPath, 0); +} +async function findMatchingFile(rootDir, matcher, maxDepth = 5) { + async function search(dirPath, depth) { + const entries2 = await readdir(dirPath, { withFileTypes: true }).catch(() => []); + for (const entry of entries2) { + const absolutePath = path20.join(dirPath, entry.name); + if (entry.isFile() && matcher(absolutePath, entry.name)) { + return absolutePath; + } + } + if (depth >= maxDepth) return null; + for (const entry of entries2) { + if (!entry.isDirectory()) continue; + const found = await search(path20.join(dirPath, entry.name), depth + 1); + if (found) return found; + } + return null; + } + return search(rootDir, 0); +} +async function readFullRunLog(run) { + if (run.logStore !== "local_file" || !run.logRef) return null; + const store = getRunLogStore(); + let offset = 0; + let combined = ""; + while (true) { + const result = await store.read({ store: "local_file", logRef: run.logRef }, { + offset, + limitBytes: 512e3 + }).catch(() => null); + if (!result) return combined || null; + combined += result.content; + if (result.nextOffset == null) break; + offset = result.nextOffset; + } + return combined || null; +} +function parseRunLogEntries(logText) { + if (!logText) return []; + const entries2 = []; + for (const rawLine of logText.split(/\r?\n/)) { + const line3 = rawLine.trim(); + if (!line3) continue; + try { + const parsed = JSON.parse(line3); + const ts = asString5(parsed.ts) ?? (/* @__PURE__ */ new Date(0)).toISOString(); + const stream = asString5(parsed.stream) ?? "stdout"; + const chunk = typeof parsed.chunk === "string" ? parsed.chunk : ""; + entries2.push({ ts, stream, chunk }); + } catch { + } + } + return entries2; +} +function captureStatusFromFiles(files) { + const sources = new Set(files.map((file2) => file2.source)); + if (sources.has("codex_session")) return "full"; + if (sources.has("claude_project_session") || sources.has("claude_debug_log")) return "full"; + if (sources.has("opencode_session") && sources.has("opencode_message") && sources.has("opencode_message_part")) { + return "full"; + } + const hasAdapterFiles = files.some( + (file2) => file2.source !== "taskcore_run" && file2.source !== "taskcore_run_events" && file2.source !== "taskcore_run_log" + ); + if (hasAdapterFiles) return "partial"; + return files.length > 0 ? "partial" : "unavailable"; +} +async function buildCodexTraceFiles(input) { + const files = []; + if (!input.sessionId) { + appendNote(input.notes, "codex_session_id_missing"); + return { files, raw: null, normalized: null }; + } + const managedRoot = path20.join( + resolveTaskcoreInstanceRoot(), + "companies", + input.companyId, + "codex-home", + "sessions" + ); + const sharedRoot = path20.join(codexHomeDir(), "sessions"); + const sessionFile = await findMatchingFile(managedRoot, (_absolutePath, name) => name.includes(input.sessionId), 6) ?? await findMatchingFile(sharedRoot, (_absolutePath, name) => name.includes(input.sessionId), 6); + const sessionText = await readTextFileIfPresent(sessionFile, input.state, "bundle.rawAdapterTrace.codex.session"); + if (!sessionText) { + appendNote(input.notes, "codex_session_file_missing"); + return { files, raw: null, normalized: null }; + } + files.push(makeBundleFile({ + path: "adapter/codex/session.jsonl", + contentType: "application/x-ndjson", + source: "codex_session", + contents: sessionText + })); + return { + files, + raw: { + adapterType: "codex_local", + sessionId: input.sessionId, + sessionFile: sessionFile ? path20.basename(sessionFile) : null + }, + normalized: sanitizeFeedbackValue( + { + adapterType: "codex_local", + sessionId: input.sessionId, + summary: parseCodexJsonl(sessionText) + }, + input.state, + "bundle.normalizedAdapterTrace.codex", + MAX_TRACE_FILE_CHARS + ) + }; +} +async function buildClaudeTraceFiles(input) { + const files = []; + const sanitizedStdout = sanitizeFeedbackText( + input.stdoutText, + input.state, + "bundle.rawAdapterTrace.claude.stdout", + MAX_TRACE_FILE_CHARS + ); + if (sanitizedStdout.trim().length > 0) { + files.push(makeBundleFile({ + path: "adapter/claude/stream-json.ndjson", + contentType: "application/x-ndjson", + source: "claude_stream_json", + contents: sanitizedStdout + })); + } + const projectsRoot = path20.join(claudeConfigDir(), "projects"); + const projectSessionFile = input.sessionId ? await findMatchingFile(projectsRoot, (_absolutePath, name) => name === `${input.sessionId}.jsonl`, 6) : null; + const projectSessionText = await readTextFileIfPresent( + projectSessionFile, + input.state, + "bundle.rawAdapterTrace.claude.projectSession" + ); + if (projectSessionText) { + files.push(makeBundleFile({ + path: "adapter/claude/session.jsonl", + contentType: "application/x-ndjson", + source: "claude_project_session", + contents: projectSessionText + })); + } else if (input.sessionId) { + appendNote(input.notes, "claude_project_session_missing"); + } + const projectSessionArtifactsDir = projectSessionFile ? path20.join(path20.dirname(projectSessionFile), input.sessionId ?? "") : null; + const projectSessionArtifactFiles = projectSessionArtifactsDir ? await listNestedFiles(projectSessionArtifactsDir, 4) : []; + for (const filePath of projectSessionArtifactFiles) { + const relativePath = path20.relative(projectSessionArtifactsDir, filePath).split(path20.sep).join("/"); + const fileText = await readTextFileIfPresent( + filePath, + input.state, + `bundle.rawAdapterTrace.claude.projectArtifacts.${relativePath}` + ); + if (!fileText) continue; + files.push(makeBundleFile({ + path: `adapter/claude/session/${relativePath}`, + contentType: contentTypeForPath(filePath), + source: "claude_project_artifact", + contents: fileText + })); + } + const debugLogText = await readTextFileIfPresent( + input.sessionId ? path20.join(claudeConfigDir(), "debug", `${input.sessionId}.txt`) : null, + input.state, + "bundle.rawAdapterTrace.claude.debugLog" + ); + if (debugLogText) { + files.push(makeBundleFile({ + path: "adapter/claude/debug.txt", + contentType: "text/plain; charset=utf-8", + source: "claude_debug_log", + contents: debugLogText + })); + } + const taskDir = input.sessionId ? path20.join(claudeConfigDir(), "tasks", input.sessionId) : null; + const taskFiles = taskDir ? await listChildFiles(taskDir) : []; + const metadataPieces = []; + for (const filePath of taskFiles) { + const fileText = await readTextFileIfPresent( + filePath, + input.state, + `bundle.rawAdapterTrace.claude.taskMetadata.${path20.basename(filePath)}` + ); + if (!fileText) continue; + metadataPieces.push(`# ${path20.basename(filePath)} +${fileText}`); + } + if (metadataPieces.length > 0) { + files.push(makeBundleFile({ + path: "adapter/claude/task-metadata.txt", + contentType: "text/plain; charset=utf-8", + source: "claude_task_metadata", + contents: `${metadataPieces.join("\n\n")} +` + })); + } else if (input.sessionId) { + appendNote(input.notes, "claude_task_metadata_missing"); + } + if (files.length === 0) { + appendNote(input.notes, "claude_stream_trace_missing"); + } + return { + files, + raw: { + adapterType: "claude_local", + sessionId: input.sessionId, + projectSessionFound: Boolean(projectSessionText), + projectArtifactsCount: projectSessionArtifactFiles.length, + debugLogFound: Boolean(debugLogText), + taskDirPresent: taskFiles.length > 0 + }, + normalized: sanitizeFeedbackValue( + { + adapterType: "claude_local", + sessionId: input.sessionId, + summary: parseClaudeStreamJson(input.stdoutText) + }, + input.state, + "bundle.normalizedAdapterTrace.claude", + MAX_TRACE_FILE_CHARS + ) + }; +} +async function buildOpenCodeTraceFiles(input) { + const files = []; + if (!input.sessionId) { + appendNote(input.notes, "opencode_session_id_missing"); + return { + files, + raw: null, + normalized: sanitizeFeedbackValue( + { + adapterType: "opencode_local", + summary: parseOpenCodeJsonl(input.stdoutText) + }, + input.state, + "bundle.normalizedAdapterTrace.opencode", + MAX_TRACE_FILE_CHARS + ) + }; + } + const opencodeRoot = resolveHomeAwarePath( + process.env.TASKCORE_OPENCODE_STORAGE_DIR ?? "~/.local/share/opencode" + ); + const sessionRoot = path20.join(opencodeRoot, "storage", "session"); + const diffRoot = path20.join(opencodeRoot, "storage", "session_diff"); + const messageRoot = path20.join(opencodeRoot, "storage", "message"); + const partRoot = path20.join(opencodeRoot, "storage", "part"); + const todoRoot = path20.join(opencodeRoot, "storage", "todo"); + const projectRoot = path20.join(opencodeRoot, "storage", "project"); + const sessionFile = await findMatchingFile( + sessionRoot, + (_absolutePath, name) => name === `${input.sessionId}.json`, + 6 + ); + const diffFile = path20.join(diffRoot, `${input.sessionId}.json`); + const sessionRaw = sessionFile ? await readFile(sessionFile, "utf8").catch(() => null) : null; + const sessionText = sessionRaw == null ? null : sanitizeFeedbackText(sessionRaw, input.state, "bundle.rawAdapterTrace.opencode.session", MAX_TRACE_FILE_CHARS); + if (sessionText) { + files.push(makeBundleFile({ + path: "adapter/opencode/session.json", + contentType: "application/json", + source: "opencode_session", + contents: sessionText + })); + } else { + appendNote(input.notes, "opencode_session_file_missing"); + } + const diffText = await readTextFileIfPresent( + diffFile, + input.state, + "bundle.rawAdapterTrace.opencode.sessionDiff" + ); + if (diffText) { + files.push(makeBundleFile({ + path: "adapter/opencode/session-diff.json", + contentType: "application/json", + source: "opencode_session_diff", + contents: diffText + })); + } + const messageFiles = await listChildFiles(path20.join(messageRoot, input.sessionId)); + const messageIds = []; + for (const filePath of messageFiles) { + const messageText = await readTextFileIfPresent( + filePath, + input.state, + `bundle.rawAdapterTrace.opencode.messages.${path20.basename(filePath)}` + ); + if (!messageText) continue; + messageIds.push(path20.basename(filePath, path20.extname(filePath))); + files.push(makeBundleFile({ + path: `adapter/opencode/messages/${path20.basename(filePath)}`, + contentType: "application/json", + source: "opencode_message", + contents: messageText + })); + } + if (messageFiles.length === 0) { + appendNote(input.notes, "opencode_message_files_missing"); + } + let partFilesCount = 0; + for (const messageId of messageIds) { + const partFiles = await listChildFiles(path20.join(partRoot, messageId)); + for (const filePath of partFiles) { + const partText = await readTextFileIfPresent( + filePath, + input.state, + `bundle.rawAdapterTrace.opencode.parts.${messageId}.${path20.basename(filePath)}` + ); + if (!partText) continue; + partFilesCount += 1; + files.push(makeBundleFile({ + path: `adapter/opencode/parts/${messageId}/${path20.basename(filePath)}`, + contentType: "application/json", + source: "opencode_message_part", + contents: partText + })); + } + } + if (messageIds.length > 0 && partFilesCount === 0) { + appendNote(input.notes, "opencode_message_parts_missing"); + } + const parsedSession = (() => { + if (!sessionRaw) return null; + try { + return JSON.parse(sessionRaw); + } catch { + return null; + } + })(); + const projectId = asString5(parsedSession?.projectID) ?? asString5(parsedSession?.projectId); + const projectText = await readTextFileIfPresent( + projectId ? path20.join(projectRoot, `${projectId}.json`) : null, + input.state, + "bundle.rawAdapterTrace.opencode.project" + ); + if (projectText) { + files.push(makeBundleFile({ + path: "adapter/opencode/project.json", + contentType: "application/json", + source: "opencode_project", + contents: projectText + })); + } + const todoText = await readTextFileIfPresent( + path20.join(todoRoot, `${input.sessionId}.json`), + input.state, + "bundle.rawAdapterTrace.opencode.todo" + ); + if (todoText) { + files.push(makeBundleFile({ + path: "adapter/opencode/todo.json", + contentType: "application/json", + source: "opencode_todo", + contents: todoText + })); + } + return { + files, + raw: { + adapterType: "opencode_local", + sessionId: input.sessionId, + sessionFileFound: Boolean(sessionText), + sessionDiffFound: Boolean(diffText), + messageFilesCount: messageFiles.length, + partFilesCount, + projectFound: Boolean(projectText), + todoFound: Boolean(todoText) + }, + normalized: sanitizeFeedbackValue( + { + adapterType: "opencode_local", + sessionId: input.sessionId, + summary: parseOpenCodeJsonl(input.stdoutText) + }, + input.state, + "bundle.normalizedAdapterTrace.opencode", + MAX_TRACE_FILE_CHARS + ) + }; +} +function truncateFailureReason(error50) { + const message2 = error50 instanceof Error ? error50.message : String(error50); + return message2.trim().slice(0, 1e3) || "Feedback export failed"; +} +function mapTraceRow(row, includePayload) { + const targetSummary = asRecord3(row.targetSummary); + return { + id: row.id, + companyId: row.companyId, + feedbackVoteId: row.feedbackVoteId, + issueId: row.issueId, + projectId: row.projectId ?? null, + issueIdentifier: row.issueIdentifier, + issueTitle: row.issueTitle, + authorUserId: row.authorUserId, + targetType: row.targetType, + targetId: row.targetId, + vote: row.vote, + status: row.status, + destination: row.destination ?? null, + exportId: row.exportId ?? null, + consentVersion: row.consentVersion ?? null, + schemaVersion: row.schemaVersion, + bundleVersion: row.bundleVersion, + payloadVersion: row.payloadVersion, + payloadDigest: row.payloadDigest ?? null, + payloadSnapshot: includePayload ? asRecord3(row.payloadSnapshot) : null, + targetSummary: targetSummary ?? buildTargetSummary({ + label: row.targetType, + excerpt: null, + authorAgentId: null, + authorUserId: null, + createdAt: null + }), + redactionSummary: asRecord3(row.redactionSummary), + attemptCount: row.attemptCount, + lastAttemptedAt: row.lastAttemptedAt ?? null, + exportedAt: row.exportedAt ?? null, + failureReason: row.failureReason ?? null, + createdAt: row.createdAt, + updatedAt: row.updatedAt + }; +} +async function resolveFeedbackTarget(db, issue2, targetType, targetId) { + const issuePath = buildIssuePath(issue2.identifier); + if (targetType === "issue_comment") { + const targetComment = await db.select({ + id: issueComments.id, + issueId: issueComments.issueId, + companyId: issueComments.companyId, + authorAgentId: issueComments.authorAgentId, + authorUserId: issueComments.authorUserId, + createdByRunId: issueComments.createdByRunId, + body: issueComments.body, + createdAt: issueComments.createdAt + }).from(issueComments).where(eq(issueComments.id, targetId)).then((rows) => rows[0] ?? null); + if (!targetComment || targetComment.issueId !== issue2.id || targetComment.companyId !== issue2.companyId) { + throw notFound("Feedback target not found"); + } + if (!targetComment.authorAgentId) { + throw unprocessable("Feedback voting is only available on agent-authored issue comments"); + } + const record2 = { + targetType, + targetId, + label: "Comment", + body: targetComment.body, + createdAt: targetComment.createdAt, + authorAgentId: targetComment.authorAgentId, + authorUserId: targetComment.authorUserId, + createdByRunId: targetComment.createdByRunId ?? null, + documentId: null, + documentKey: null, + documentTitle: null, + revisionNumber: null, + issuePath, + targetPath: issuePath ? `${issuePath}#comment-${targetComment.id}` : null, + payloadTarget: { + type: targetType, + id: targetComment.id, + createdAt: targetComment.createdAt.toISOString(), + authorAgentId: targetComment.authorAgentId, + authorUserId: targetComment.authorUserId, + createdByRunId: targetComment.createdByRunId ?? null, + issuePath, + targetPath: issuePath ? `${issuePath}#comment-${targetComment.id}` : null + } + }; + return record2; + } + if (targetType === "issue_document_revision") { + const targetRevision = await db.select({ + id: documentRevisions.id, + companyId: documentRevisions.companyId, + documentId: documentRevisions.documentId, + revisionNumber: documentRevisions.revisionNumber, + body: documentRevisions.body, + createdByAgentId: documentRevisions.createdByAgentId, + createdByUserId: documentRevisions.createdByUserId, + createdByRunId: documentRevisions.createdByRunId, + createdAt: documentRevisions.createdAt, + issueId: issueDocuments.issueId, + key: issueDocuments.key, + title: documents.title + }).from(documentRevisions).innerJoin(documents, eq(documentRevisions.documentId, documents.id)).innerJoin(issueDocuments, eq(issueDocuments.documentId, documents.id)).where(eq(documentRevisions.id, targetId)).then((rows) => rows.find((row) => row.issueId === issue2.id) ?? null); + if (!targetRevision || targetRevision.companyId !== issue2.companyId) { + throw notFound("Feedback target not found"); + } + if (!targetRevision.createdByAgentId) { + throw unprocessable("Feedback voting is only available on agent-authored document revisions"); + } + const record2 = { + targetType, + targetId, + label: `${targetRevision.key} rev ${targetRevision.revisionNumber}`, + body: targetRevision.body, + createdAt: targetRevision.createdAt, + authorAgentId: targetRevision.createdByAgentId, + authorUserId: targetRevision.createdByUserId, + createdByRunId: targetRevision.createdByRunId ?? null, + documentId: targetRevision.documentId, + documentKey: targetRevision.key, + documentTitle: targetRevision.title ?? null, + revisionNumber: targetRevision.revisionNumber, + issuePath, + targetPath: issuePath ? `${issuePath}#document-${encodeURIComponent(targetRevision.key)}` : null, + payloadTarget: { + type: targetType, + id: targetRevision.id, + documentId: targetRevision.documentId, + documentKey: targetRevision.key, + documentTitle: targetRevision.title ?? null, + revisionNumber: targetRevision.revisionNumber, + createdAt: targetRevision.createdAt.toISOString(), + authorAgentId: targetRevision.createdByAgentId, + authorUserId: targetRevision.createdByUserId, + createdByRunId: targetRevision.createdByRunId ?? null, + issuePath, + targetPath: issuePath ? `${issuePath}#document-${encodeURIComponent(targetRevision.key)}` : null + } + }; + return record2; + } + throw unprocessable("Unsupported feedback target type"); +} +async function listIssueContextItems(db, issue2) { + const [commentRows, revisionRows] = await Promise.all([ + db.select({ + targetId: issueComments.id, + body: issueComments.body, + createdAt: issueComments.createdAt, + authorAgentId: issueComments.authorAgentId, + authorUserId: issueComments.authorUserId, + createdByRunId: issueComments.createdByRunId + }).from(issueComments).where(and(eq(issueComments.companyId, issue2.companyId), eq(issueComments.issueId, issue2.id))), + db.select({ + targetId: documentRevisions.id, + body: documentRevisions.body, + createdAt: documentRevisions.createdAt, + authorAgentId: documentRevisions.createdByAgentId, + authorUserId: documentRevisions.createdByUserId, + createdByRunId: documentRevisions.createdByRunId, + documentId: documentRevisions.documentId, + documentKey: issueDocuments.key, + documentTitle: documents.title, + revisionNumber: documentRevisions.revisionNumber + }).from(documentRevisions).innerJoin(documents, eq(documentRevisions.documentId, documents.id)).innerJoin(issueDocuments, eq(issueDocuments.documentId, documents.id)).where(and(eq(documentRevisions.companyId, issue2.companyId), eq(issueDocuments.issueId, issue2.id))) + ]); + const issuePath = buildIssuePath(issue2.identifier); + const items = [ + ...commentRows.map((row) => ({ + targetType: "issue_comment", + targetId: row.targetId, + label: "Comment", + body: row.body, + createdAt: row.createdAt, + authorAgentId: row.authorAgentId, + authorUserId: row.authorUserId, + createdByRunId: row.createdByRunId ?? null, + documentId: null, + documentKey: null, + documentTitle: null, + revisionNumber: null, + issuePath, + targetPath: issuePath ? `${issuePath}#comment-${row.targetId}` : null + })), + ...revisionRows.map((row) => ({ + targetType: "issue_document_revision", + targetId: row.targetId, + label: `${row.documentKey} rev ${row.revisionNumber}`, + body: row.body, + createdAt: row.createdAt, + authorAgentId: row.authorAgentId, + authorUserId: row.authorUserId, + createdByRunId: row.createdByRunId ?? null, + documentId: row.documentId, + documentKey: row.documentKey, + documentTitle: row.documentTitle ?? null, + revisionNumber: row.revisionNumber, + issuePath, + targetPath: issuePath ? `${issuePath}#document-${encodeURIComponent(row.documentKey)}` : null + })) + ]; + return items.sort((left, right) => { + const byDate = left.createdAt.getTime() - right.createdAt.getTime(); + if (byDate !== 0) return byDate; + return left.targetId.localeCompare(right.targetId); + }); +} +async function buildIssueContext(db, issue2, target, state2) { + const items = await listIssueContextItems(db, issue2); + const targetIndex = items.findIndex((item) => item.targetType === target.targetType && item.targetId === target.targetId); + const before = targetIndex >= 0 ? items.slice(Math.max(0, targetIndex - FEEDBACK_CONTEXT_WINDOW), targetIndex) : []; + const after = targetIndex >= 0 ? items.slice(targetIndex + 1, targetIndex + 1 + FEEDBACK_CONTEXT_WINDOW) : []; + let remainingChars = MAX_TOTAL_CONTEXT_CHARS; + const serializedItems = [...before, ...after].map((item, index2) => { + const relation = index2 < before.length ? "before" : "after"; + if (remainingChars <= 0) { + state2.omittedFields.add("bundle.issueContext.items"); + return null; + } + const maxChars = Math.min(MAX_CONTEXT_ITEM_BODY_CHARS, remainingChars); + const body = sanitizeFeedbackText( + item.body, + state2, + `bundle.issueContext.items.${index2}.body`, + maxChars + ); + remainingChars -= body.length; + return { + type: item.targetType, + id: item.targetId, + label: item.label, + relation, + createdAt: item.createdAt.toISOString(), + authorAgentId: item.authorAgentId, + authorUserId: item.authorUserId, + createdByRunId: item.createdByRunId, + documentKey: item.documentKey, + documentTitle: item.documentTitle, + revisionNumber: item.revisionNumber, + targetPath: item.targetPath, + body, + excerpt: truncateExcerpt(body) + }; + }).filter((item) => item !== null); + const descriptionExcerpt = issue2.description ? sanitizeFeedbackText(issue2.description, state2, "bundle.issueContext.issue.description", MAX_DESCRIPTION_CHARS) : null; + return { + issue: { + id: issue2.id, + identifier: issue2.identifier, + title: issue2.title, + projectId: issue2.projectId, + path: buildIssuePath(issue2.identifier), + descriptionExcerpt: descriptionExcerpt ? truncateExcerpt(descriptionExcerpt, MAX_DESCRIPTION_CHARS) : null + }, + items: serializedItems + }; +} +async function buildAgentContext(db, companyId, authorAgentId, createdByRunId, state2) { + if (!authorAgentId) { + state2.notes.add("author_agent_missing"); + return null; + } + const agent = await db.select({ + id: agents.id, + companyId: agents.companyId, + name: agents.name, + role: agents.role, + title: agents.title, + status: agents.status, + adapterType: agents.adapterType, + adapterConfig: agents.adapterConfig, + runtimeConfig: agents.runtimeConfig + }).from(agents).where(eq(agents.id, authorAgentId)).then((rows) => rows[0] ?? null); + if (!agent || agent.companyId !== companyId) { + state2.notes.add("author_agent_unavailable"); + return null; + } + const adapterConfig = asRecord3(agent.adapterConfig) ?? {}; + const runtimeConfig = asRecord3(agent.runtimeConfig) ?? {}; + const desiredSkillRefs = uniqueNonEmpty2(readTaskcoreSkillSyncPreference(adapterConfig).desiredSkills).slice(0, MAX_SKILLS); + const availableSkills = desiredSkillRefs.length === 0 ? [] : await db.select().from(companySkills).where(eq(companySkills.companyId, companyId)); + const matchedSkills = availableSkills.filter((skill) => desiredSkillRefs.some((reference) => matchesSkillReference(skill, reference))).slice(0, MAX_SKILLS); + const unresolvedSkillRefs = desiredSkillRefs.filter( + (reference) => !matchedSkills.some((skill) => matchesSkillReference(skill, reference)) + ); + if (availableSkills.length > MAX_SKILLS || desiredSkillRefs.length > MAX_SKILLS) { + state2.omittedFields.add("bundle.agentContext.skills"); + } + const run = createdByRunId ? await db.select({ + id: heartbeatRuns.id, + companyId: heartbeatRuns.companyId, + agentId: heartbeatRuns.agentId, + invocationSource: heartbeatRuns.invocationSource, + status: heartbeatRuns.status, + startedAt: heartbeatRuns.startedAt, + finishedAt: heartbeatRuns.finishedAt, + usageJson: heartbeatRuns.usageJson, + sessionIdBefore: heartbeatRuns.sessionIdBefore, + sessionIdAfter: heartbeatRuns.sessionIdAfter, + externalRunId: heartbeatRuns.externalRunId + }).from(heartbeatRuns).where(eq(heartbeatRuns.id, createdByRunId)).then((rows) => rows[0] ?? null) : null; + const runCosts = run ? await db.select({ + provider: costEvents.provider, + biller: costEvents.biller, + billingType: costEvents.billingType, + model: costEvents.model, + inputTokens: costEvents.inputTokens, + cachedInputTokens: costEvents.cachedInputTokens, + outputTokens: costEvents.outputTokens, + costCents: costEvents.costCents + }).from(costEvents).where(and(eq(costEvents.companyId, companyId), eq(costEvents.heartbeatRunId, run.id))) : []; + const usage = asRecord3(run?.usageJson) ?? {}; + const runtime = { + configuredModel: asString5(adapterConfig.model), + configuredInstructionsBundleMode: asString5(adapterConfig.instructionsBundleMode), + configuredInstructionsEntryFile: asString5(adapterConfig.instructionsEntryFile), + configuredInstructionsFilePath: asString5(adapterConfig.instructionsFilePath), + configuredInstructionsRootPath: asString5(adapterConfig.instructionsRootPath), + heartbeatPolicy: sanitizeFeedbackValue(runtimeConfig.heartbeat ?? null, state2, "bundle.agentContext.runtime.heartbeatPolicy", 400), + provenanceMode: run ? "source_run" : "vote_time_snapshot", + sourceRun: run ? sanitizeFeedbackValue({ + id: run.id, + invocationSource: run.invocationSource, + status: run.status, + startedAt: run.startedAt?.toISOString() ?? null, + finishedAt: run.finishedAt?.toISOString() ?? null, + externalRunId: run.externalRunId ?? null, + sessionIdBefore: run.sessionIdBefore ?? null, + sessionIdAfter: run.sessionIdAfter ?? null, + usage: { + provider: asString5(usage.provider), + biller: asString5(usage.biller), + billingType: asString5(usage.billingType), + model: asString5(usage.model), + inputTokens: asNumber2(usage.inputTokens) ?? asNumber2(usage.rawInputTokens), + cachedInputTokens: asNumber2(usage.cachedInputTokens) ?? asNumber2(usage.rawCachedInputTokens), + outputTokens: asNumber2(usage.outputTokens) ?? asNumber2(usage.rawOutputTokens), + costUsd: asNumber2(usage.costUsd), + usageSource: asString5(usage.usageSource), + sessionReused: asBoolean2(usage.sessionReused), + taskSessionReused: asBoolean2(usage.taskSessionReused), + freshSession: asBoolean2(usage.freshSession), + sessionRotated: asBoolean2(usage.sessionRotated), + sessionRotationReason: asString5(usage.sessionRotationReason) + } + }, state2, "bundle.agentContext.runtime.sourceRun", 400) : null, + costSummary: runCosts.length > 0 ? { + providers: uniqueNonEmpty2(runCosts.map((row) => row.provider)), + billers: uniqueNonEmpty2(runCosts.map((row) => row.biller)), + billingTypes: uniqueNonEmpty2(runCosts.map((row) => row.billingType)), + models: uniqueNonEmpty2(runCosts.map((row) => row.model)), + inputTokens: runCosts.reduce((sum, row) => sum + row.inputTokens, 0), + cachedInputTokens: runCosts.reduce((sum, row) => sum + row.cachedInputTokens, 0), + outputTokens: runCosts.reduce((sum, row) => sum + row.outputTokens, 0), + costCents: runCosts.reduce((sum, row) => sum + row.costCents, 0) + } : null + }; + const instructionsBundle = await instructionsSvc.getBundle({ + id: agent.id, + companyId: agent.companyId, + name: agent.name, + adapterConfig: agent.adapterConfig + }).catch(() => null); + let entryDigest = null; + let entryBody = null; + if (instructionsBundle) { + const readableEntryPath = instructionsBundle.files.find((file2) => file2.path === instructionsBundle.entryFile)?.path ?? instructionsBundle.files[0]?.path ?? null; + if (readableEntryPath) { + const entryFile = await instructionsSvc.readFile({ + id: agent.id, + companyId: agent.companyId, + name: agent.name, + adapterConfig: agent.adapterConfig + }, readableEntryPath).catch(() => null); + if (entryFile) { + entryDigest = sha256Digest(entryFile.content); + entryBody = sanitizeFeedbackText( + entryFile.content, + state2, + "bundle.agentContext.instructions.entryBody", + MAX_INSTRUCTIONS_BODY_CHARS + ); + } + } + if (instructionsBundle.files.length > MAX_INSTRUCTION_FILES) { + state2.omittedFields.add("bundle.agentContext.instructions.files"); + } + } + return { + agent: { + id: agent.id, + name: agent.name, + role: agent.role, + title: agent.title, + status: agent.status, + adapterType: agent.adapterType + }, + runtime: sanitizeFeedbackValue(runtime, state2, "bundle.agentContext.runtime", 400), + skills: { + desiredRefs: desiredSkillRefs, + unresolvedRefs: unresolvedSkillRefs, + items: matchedSkills.map((skill, index2) => ({ + key: skill.key, + slug: skill.slug, + name: skill.name, + sourceType: skill.sourceType, + sourceLocator: skill.sourceLocator == null ? null : skill.sourceType === "github" || skill.sourceType === "skills_sh" || skill.sourceType === "url" ? skill.sourceLocator : sanitizeFeedbackText( + skill.sourceLocator, + state2, + `bundle.agentContext.skills.items.${index2}.sourceLocator`, + MAX_PATH_CHARS + ), + sourceRef: skill.sourceRef, + trustLevel: skill.trustLevel, + compatibility: skill.compatibility, + fileInventory: skill.fileInventory + })) + }, + instructions: instructionsBundle ? { + mode: instructionsBundle.mode, + entryFile: instructionsBundle.entryFile, + resolvedEntryPath: instructionsBundle.resolvedEntryPath ? sanitizeFeedbackText( + instructionsBundle.resolvedEntryPath, + state2, + "bundle.agentContext.instructions.resolvedEntryPath", + MAX_PATH_CHARS + ) : null, + warnings: instructionsBundle.warnings.map((warning, index2) => sanitizeFeedbackText( + warning, + state2, + `bundle.agentContext.instructions.warnings.${index2}`, + 400 + )), + legacyPromptTemplateActive: instructionsBundle.legacyPromptTemplateActive, + legacyBootstrapPromptTemplateActive: instructionsBundle.legacyBootstrapPromptTemplateActive, + fileCount: instructionsBundle.files.length, + files: instructionsBundle.files.slice(0, MAX_INSTRUCTION_FILES).map((file2) => ({ + path: file2.path, + size: file2.size, + language: file2.language, + markdown: file2.markdown, + isEntryFile: file2.isEntryFile, + virtual: file2.virtual + })), + entryDigest, + entryBody + } : null, + taskcore: { + schemaVersion: FEEDBACK_SCHEMA_VERSION, + bundleVersion: FEEDBACK_BUNDLE_VERSION + } + }; +} +async function buildPayloadArtifacts(db, input) { + const state2 = createFeedbackRedactionState(); + const primaryBody = sanitizeFeedbackText( + input.target.body, + state2, + "bundle.primaryContent.body", + MAX_PRIMARY_CONTENT_CHARS + ); + const primaryContent = { + type: input.target.targetType, + id: input.target.targetId, + label: input.target.label, + createdAt: input.target.createdAt.toISOString(), + authorAgentId: input.target.authorAgentId, + authorUserId: input.target.authorUserId, + createdByRunId: input.target.createdByRunId, + documentId: input.target.documentId, + documentKey: input.target.documentKey, + documentTitle: input.target.documentTitle, + revisionNumber: input.target.revisionNumber, + targetPath: input.target.targetPath, + body: primaryBody, + excerpt: truncateExcerpt(primaryBody) + }; + const targetSummary = buildTargetSummary({ + label: input.target.label, + excerpt: primaryContent.excerpt, + authorAgentId: input.target.authorAgentId, + authorUserId: input.target.authorUserId, + createdAt: input.target.createdAt, + documentKey: input.target.documentKey, + documentTitle: input.target.documentTitle, + revisionNumber: input.target.revisionNumber + }); + const basePayload = { + schemaVersion: FEEDBACK_SCHEMA_VERSION, + bundleVersion: FEEDBACK_BUNDLE_VERSION, + sourceApp: "taskcore", + capturedAt: input.now.toISOString(), + consentVersion: input.consentVersion, + vote: { + id: input.voteId, + value: input.vote, + reason: input.reason, + authorUserId: input.authorUserId, + sharedWithLabs: input.sharedWithLabs, + sharedAt: input.sharedWithLabs ? input.now.toISOString() : null + }, + target: input.target.payloadTarget + }; + if (!input.sharedWithLabs) { + state2.notes.add("local_only_trace_stores_metadata_only"); + const payloadSnapshot2 = { + ...basePayload, + exportId: null, + exportEligible: false, + bundle: null + }; + const redactionSummary2 = finalizeFeedbackRedactionSummary(state2); + return { + exportId: null, + targetSummary, + redactionSummary: redactionSummary2, + payloadSnapshot: { + ...payloadSnapshot2, + redactionSummary: redactionSummary2 + }, + payloadDigest: sha256Digest({ + ...payloadSnapshot2, + redactionSummary: redactionSummary2 + }) + }; + } + const exportId = buildExportId(input.voteId, input.now); + const [issueContext, agentContext] = await Promise.all([ + buildIssueContext(db, input.issue, input.target, state2), + buildAgentContext(db, input.issue.companyId, input.target.authorAgentId, input.target.createdByRunId, state2) + ]); + const payloadSnapshot = { + ...basePayload, + exportId, + exportEligible: true, + bundle: { + primaryContent, + issueContext, + agentContext + } + }; + const redactionSummary = finalizeFeedbackRedactionSummary(state2); + const payloadWithSummary = { + ...payloadSnapshot, + redactionSummary + }; + return { + exportId, + targetSummary, + redactionSummary, + payloadSnapshot: payloadWithSummary, + payloadDigest: sha256Digest(payloadWithSummary) + }; +} +async function buildFeedbackTraceBundleFromRow(db, row) { + const trace = mapTraceRow(row, true); + const payloadSnapshot = asRecord3(trace.payloadSnapshot); + const notes = []; + const state2 = createFeedbackRedactionState(); + const files = []; + const sourceRunId = resolveSourceRunId(payloadSnapshot); + let taskcoreRun = null; + let rawAdapterTrace = null; + let normalizedAdapterTrace = null; + let adapterType = null; + if (!sourceRunId) { + appendNote(notes, "source_run_missing"); + } else { + const run = await db.select({ + id: heartbeatRuns.id, + companyId: heartbeatRuns.companyId, + agentId: heartbeatRuns.agentId, + invocationSource: heartbeatRuns.invocationSource, + status: heartbeatRuns.status, + startedAt: heartbeatRuns.startedAt, + finishedAt: heartbeatRuns.finishedAt, + createdAt: heartbeatRuns.createdAt, + updatedAt: heartbeatRuns.updatedAt, + error: heartbeatRuns.error, + errorCode: heartbeatRuns.errorCode, + usageJson: heartbeatRuns.usageJson, + resultJson: heartbeatRuns.resultJson, + sessionIdBefore: heartbeatRuns.sessionIdBefore, + sessionIdAfter: heartbeatRuns.sessionIdAfter, + externalRunId: heartbeatRuns.externalRunId, + contextSnapshot: heartbeatRuns.contextSnapshot, + logStore: heartbeatRuns.logStore, + logRef: heartbeatRuns.logRef, + logBytes: heartbeatRuns.logBytes, + logSha256: heartbeatRuns.logSha256, + agentName: agents.name, + agentRole: agents.role, + agentTitle: agents.title, + adapterType: agents.adapterType + }).from(heartbeatRuns).innerJoin(agents, eq(heartbeatRuns.agentId, agents.id)).where(eq(heartbeatRuns.id, sourceRunId)).then((rows) => rows[0] ?? null); + if (!run || run.companyId !== row.companyId) { + appendNote(notes, "source_run_unavailable"); + } else { + adapterType = run.adapterType; + const events = await db.select().from(heartbeatRunEvents).where(eq(heartbeatRunEvents.runId, run.id)).orderBy(asc(heartbeatRunEvents.seq)); + const logText = await readFullRunLog(run); + const logEntries = parseRunLogEntries(logText); + const stdoutText = logEntries.filter((entry) => entry.stream === "stdout").map((entry) => entry.chunk).join(""); + taskcoreRun = sanitizeFeedbackValue( + { + id: run.id, + companyId: run.companyId, + agentId: run.agentId, + agentName: run.agentName, + agentRole: run.agentRole, + agentTitle: run.agentTitle, + adapterType: run.adapterType, + invocationSource: run.invocationSource, + status: run.status, + startedAt: run.startedAt?.toISOString() ?? null, + finishedAt: run.finishedAt?.toISOString() ?? null, + createdAt: run.createdAt.toISOString(), + updatedAt: run.updatedAt.toISOString(), + error: run.error, + errorCode: run.errorCode, + usage: asRecord3(run.usageJson), + result: asRecord3(run.resultJson), + sessionIdBefore: run.sessionIdBefore, + sessionIdAfter: run.sessionIdAfter, + externalRunId: run.externalRunId, + contextSnapshot: asRecord3(run.contextSnapshot), + logStore: run.logStore, + logRef: run.logRef, + logBytes: run.logBytes, + logSha256: run.logSha256, + eventCount: events.length + }, + state2, + "bundle.taskcoreRun", + MAX_TRACE_FILE_CHARS + ); + files.push(makeBundleFile({ + path: "taskcore/run.json", + contentType: "application/json", + source: "taskcore_run", + contents: `${JSON.stringify(taskcoreRun, null, 2)} +` + })); + const sanitizedEvents = sanitizeFeedbackValue( + events, + state2, + "bundle.taskcoreRun.events", + MAX_TRACE_FILE_CHARS + ); + files.push(makeBundleFile({ + path: "taskcore/run-events.json", + contentType: "application/json", + source: "taskcore_run_events", + contents: `${JSON.stringify(sanitizedEvents, null, 2)} +` + })); + if (logText) { + files.push(makeBundleFile({ + path: "taskcore/run-log.ndjson", + contentType: "application/x-ndjson", + source: "taskcore_run_log", + contents: `${sanitizeFeedbackText(logText, state2, "bundle.taskcoreRun.log", MAX_TRACE_FILE_CHARS)} +` + })); + } else { + appendNote(notes, "run_log_missing"); + } + if (run.adapterType === "codex_local") { + const adapter = await buildCodexTraceFiles({ + companyId: row.companyId, + sessionId: run.sessionIdAfter ?? run.sessionIdBefore, + state: state2, + notes + }); + files.push(...adapter.files); + rawAdapterTrace = adapter.raw; + normalizedAdapterTrace = adapter.normalized; + } else if (run.adapterType === "claude_local") { + const adapter = await buildClaudeTraceFiles({ + sessionId: run.sessionIdAfter ?? run.sessionIdBefore, + stdoutText, + state: state2, + notes + }); + files.push(...adapter.files); + rawAdapterTrace = adapter.raw; + normalizedAdapterTrace = adapter.normalized; + } else if (run.adapterType === "opencode_local") { + const adapter = await buildOpenCodeTraceFiles({ + sessionId: run.sessionIdAfter ?? run.sessionIdBefore, + stdoutText, + state: state2, + notes + }); + files.push(...adapter.files); + rawAdapterTrace = adapter.raw; + normalizedAdapterTrace = adapter.normalized; + } else { + appendNote(notes, "adapter_specific_trace_not_supported"); + } + } + } + const privacy = { + ...asRecord3(trace.redactionSummary) ?? {}, + bundleRedactionSummary: finalizeFeedbackRedactionSummary(state2) + }; + const captureStatus = captureStatusFromFiles(files); + if (captureStatus !== "full" && files.length > 0) { + appendNote(notes, "adapter_trace_partial"); + } + const envelope = sanitizeFeedbackValue( + { + traceId: trace.id, + exportId: trace.exportId, + companyId: trace.companyId, + feedbackVoteId: trace.feedbackVoteId, + issueId: trace.issueId, + issueIdentifier: trace.issueIdentifier, + issueTitle: trace.issueTitle, + projectId: trace.projectId, + authorUserId: trace.authorUserId, + targetType: trace.targetType, + targetId: trace.targetId, + vote: trace.vote, + status: trace.status, + destination: trace.destination, + consentVersion: trace.consentVersion, + schemaVersion: trace.schemaVersion, + bundleVersion: trace.bundleVersion, + payloadVersion: trace.payloadVersion, + payloadDigest: trace.payloadDigest, + createdAt: trace.createdAt.toISOString(), + exportedAt: trace.exportedAt?.toISOString() ?? null + }, + state2, + "bundle.envelope", + MAX_TRACE_FILE_CHARS + ); + const surface = sanitizeFeedbackValue( + { + target: asRecord3(payloadSnapshot?.target), + summary: trace.targetSummary + }, + state2, + "bundle.surface", + MAX_TRACE_FILE_CHARS + ); + const bundle = { + traceId: trace.id, + exportId: trace.exportId, + companyId: trace.companyId, + issueId: trace.issueId, + issueIdentifier: trace.issueIdentifier, + adapterType, + captureStatus, + notes, + envelope, + surface, + taskcoreRun, + rawAdapterTrace, + normalizedAdapterTrace, + privacy, + integrity: { + payloadDigest: trace.payloadDigest, + bundleDigest: sha256Digest({ + traceId: trace.id, + files: files.map((file2) => ({ + path: file2.path, + source: file2.source, + sha256: file2.sha256 + })), + captureStatus + }) + }, + files + }; + return bundle; +} +function feedbackService(db, options = {}) { + return { + listIssueVotesForUser: async (issueId, authorUserId) => db.select().from(feedbackVotes).where(and(eq(feedbackVotes.issueId, issueId), eq(feedbackVotes.authorUserId, authorUserId))), + listFeedbackTraces: async (input) => { + const filters = [eq(feedbackExports.companyId, input.companyId)]; + if (input.issueId) filters.push(eq(feedbackExports.issueId, input.issueId)); + if (input.projectId) filters.push(eq(feedbackExports.projectId, input.projectId)); + if (input.targetType) filters.push(eq(feedbackExports.targetType, input.targetType)); + if (input.vote) filters.push(eq(feedbackExports.vote, input.vote)); + if (input.status) filters.push(eq(feedbackExports.status, input.status)); + if (input.sharedOnly) filters.push(ne(feedbackExports.status, "local_only")); + if (input.from) filters.push(gte(feedbackExports.createdAt, input.from)); + if (input.to) filters.push(lte(feedbackExports.createdAt, input.to)); + const rows = await db.select({ + ...feedbackExportColumns, + issueIdentifier: issues.identifier, + issueTitle: issues.title + }).from(feedbackExports).innerJoin(issues, eq(feedbackExports.issueId, issues.id)).where(and(...filters)).orderBy(desc(feedbackExports.createdAt)); + return rows.map((row) => mapTraceRow(row, input.includePayload === true)); + }, + getFeedbackTraceById: async (traceId, includePayload = true) => { + const row = await db.select({ + ...feedbackExportColumns, + issueIdentifier: issues.identifier, + issueTitle: issues.title + }).from(feedbackExports).innerJoin(issues, eq(feedbackExports.issueId, issues.id)).where(eq(feedbackExports.id, traceId)).then((rows) => rows[0] ?? null); + return row ? mapTraceRow(row, includePayload) : null; + }, + getFeedbackTraceBundle: async (traceId) => { + const row = await db.select({ + ...feedbackExportColumns, + issueIdentifier: issues.identifier, + issueTitle: issues.title + }).from(feedbackExports).innerJoin(issues, eq(feedbackExports.issueId, issues.id)).where(eq(feedbackExports.id, traceId)).then((rows) => rows[0] ?? null); + return row ? buildFeedbackTraceBundleFromRow(db, row) : null; + }, + flushPendingFeedbackTraces: async (input) => { + const shareClient = options.shareClient; + if (!shareClient) { + const filters2 = [eq(feedbackExports.status, "pending")]; + if (input?.companyId) { + filters2.push(eq(feedbackExports.companyId, input.companyId)); + } + if (input?.traceId) { + filters2.push(eq(feedbackExports.id, input.traceId)); + } + const rows2 = await db.select({ + id: feedbackExports.id, + attemptCount: feedbackExports.attemptCount + }).from(feedbackExports).where(and(...filters2)).orderBy(asc(feedbackExports.createdAt), asc(feedbackExports.id)).limit(Math.max(1, Math.min(input?.limit ?? 25, 200))); + const attemptAt = input?.now ?? /* @__PURE__ */ new Date(); + for (const row of rows2) { + await db.update(feedbackExports).set({ + status: "failed", + attemptCount: row.attemptCount + 1, + lastAttemptedAt: attemptAt, + failureReason: FEEDBACK_EXPORT_BACKEND_NOT_CONFIGURED, + updatedAt: attemptAt + }).where(eq(feedbackExports.id, row.id)); + } + return { + attempted: rows2.length, + sent: 0, + failed: rows2.length + }; + } + const limit = Math.max(1, Math.min(input?.limit ?? 25, 200)); + const filters = [ + or(eq(feedbackExports.status, "pending"), eq(feedbackExports.status, "failed")) + ]; + if (input?.companyId) { + filters.push(eq(feedbackExports.companyId, input.companyId)); + } + if (input?.traceId) { + filters.push(eq(feedbackExports.id, input.traceId)); + } + const rows = await db.select({ + ...feedbackExportColumns, + issueIdentifier: issues.identifier, + issueTitle: issues.title + }).from(feedbackExports).innerJoin(issues, eq(feedbackExports.issueId, issues.id)).where(and(...filters)).orderBy(asc(feedbackExports.createdAt), asc(feedbackExports.id)).limit(limit); + let attempted = 0; + let sent = 0; + let failed = 0; + for (const row of rows) { + const attemptAt = input?.now ?? /* @__PURE__ */ new Date(); + attempted += 1; + try { + const bundle = await buildFeedbackTraceBundleFromRow(db, row); + await shareClient.uploadTraceBundle(bundle); + await db.update(feedbackExports).set({ + status: "sent", + attemptCount: row.attemptCount + 1, + lastAttemptedAt: attemptAt, + exportedAt: attemptAt, + failureReason: null, + updatedAt: attemptAt + }).where(eq(feedbackExports.id, row.id)); + sent += 1; + } catch (error50) { + await db.update(feedbackExports).set({ + status: "failed", + attemptCount: row.attemptCount + 1, + lastAttemptedAt: attemptAt, + failureReason: truncateFailureReason(error50), + updatedAt: attemptAt + }).where(eq(feedbackExports.id, row.id)); + failed += 1; + } + } + return { + attempted, + sent, + failed + }; + }, + saveIssueVote: async (input) => db.transaction(async (tx) => { + const issue2 = await tx.select({ + id: issues.id, + companyId: issues.companyId, + projectId: issues.projectId, + identifier: issues.identifier, + title: issues.title, + description: issues.description + }).from(issues).where(eq(issues.id, input.issueId)).then((rows) => rows[0] ?? null); + if (!issue2) throw notFound("Issue not found"); + const target = await resolveFeedbackTarget(tx, issue2, input.targetType, input.targetId); + const existingCompany = await tx.select({ + feedbackDataSharingEnabled: companies.feedbackDataSharingEnabled, + feedbackDataSharingTermsVersion: companies.feedbackDataSharingTermsVersion + }).from(companies).where(eq(companies.id, issue2.companyId)).then((rows) => rows[0] ?? null); + if (!existingCompany) throw notFound("Company not found"); + const now2 = /* @__PURE__ */ new Date(); + const normalizedReason = normalizeReason(input.vote, input.reason); + const sharedWithLabs = input.allowSharing === true; + let consentEnabledNow = false; + let consentVersion = existingCompany.feedbackDataSharingTermsVersion ?? null; + let persistedSharingPreference = null; + if (sharedWithLabs && !existingCompany.feedbackDataSharingEnabled) { + consentEnabledNow = true; + consentVersion = DEFAULT_FEEDBACK_DATA_SHARING_TERMS_VERSION; + await tx.update(companies).set({ + feedbackDataSharingEnabled: true, + feedbackDataSharingConsentAt: now2, + feedbackDataSharingConsentByUserId: input.authorUserId, + feedbackDataSharingTermsVersion: consentVersion, + updatedAt: now2 + }).where(eq(companies.id, issue2.companyId)); + } + const existingInstanceSettings = await tx.select({ + id: instanceSettings.id, + general: instanceSettings.general + }).from(instanceSettings).where(eq(instanceSettings.singletonKey, DEFAULT_INSTANCE_SETTINGS_SINGLETON_KEY)).then((rows) => rows[0] ?? null); + const currentInstanceSettings = existingInstanceSettings ?? await tx.insert(instanceSettings).values({ + singletonKey: DEFAULT_INSTANCE_SETTINGS_SINGLETON_KEY, + general: {}, + experimental: {}, + createdAt: now2, + updatedAt: now2 + }).onConflictDoUpdate({ + target: [instanceSettings.singletonKey], + set: { + updatedAt: now2 + } + }).returning({ + id: instanceSettings.id, + general: instanceSettings.general + }).then((rows) => rows[0] ?? null); + const currentGeneral = normalizeInstanceGeneralSettings(currentInstanceSettings?.general); + if (currentInstanceSettings && currentGeneral.feedbackDataSharingPreference === "prompt") { + const nextSharingPreference = sharedWithLabs ? "allowed" : "not_allowed"; + const currentGeneralRaw = asRecord3(currentInstanceSettings.general) ?? {}; + await tx.update(instanceSettings).set({ + general: { + ...currentGeneralRaw, + censorUsernameInLogs: currentGeneral.censorUsernameInLogs, + feedbackDataSharingPreference: nextSharingPreference + }, + updatedAt: now2 + }).where(eq(instanceSettings.id, currentInstanceSettings.id)); + persistedSharingPreference = nextSharingPreference; + } + const [savedVote] = await tx.insert(feedbackVotes).values({ + companyId: issue2.companyId, + issueId: issue2.id, + targetType: input.targetType, + targetId: input.targetId, + authorUserId: input.authorUserId, + vote: input.vote, + reason: normalizedReason, + sharedWithLabs, + sharedAt: sharedWithLabs ? now2 : null, + consentVersion: sharedWithLabs ? consentVersion ?? DEFAULT_FEEDBACK_DATA_SHARING_TERMS_VERSION : null, + redactionSummary: null, + updatedAt: now2 + }).onConflictDoUpdate({ + target: [ + feedbackVotes.companyId, + feedbackVotes.targetType, + feedbackVotes.targetId, + feedbackVotes.authorUserId + ], + set: { + vote: input.vote, + reason: normalizedReason, + sharedWithLabs, + sharedAt: sharedWithLabs ? now2 : null, + consentVersion: sharedWithLabs ? consentVersion ?? DEFAULT_FEEDBACK_DATA_SHARING_TERMS_VERSION : null, + redactionSummary: null, + updatedAt: now2 + } + }).returning(); + const artifacts = await buildPayloadArtifacts(tx, { + issue: issue2, + target, + voteId: savedVote.id, + vote: input.vote, + reason: normalizedReason, + authorUserId: input.authorUserId, + consentVersion: sharedWithLabs ? consentVersion ?? DEFAULT_FEEDBACK_DATA_SHARING_TERMS_VERSION : null, + sharedWithLabs, + now: now2 + }); + await tx.update(feedbackVotes).set({ + redactionSummary: artifacts.redactionSummary, + updatedAt: now2 + }).where(eq(feedbackVotes.id, savedVote.id)); + const [savedTrace] = await tx.insert(feedbackExports).values({ + companyId: issue2.companyId, + feedbackVoteId: savedVote.id, + issueId: issue2.id, + projectId: issue2.projectId, + authorUserId: input.authorUserId, + targetType: input.targetType, + targetId: input.targetId, + vote: input.vote, + status: sharedWithLabs ? "pending" : "local_only", + destination: sharedWithLabs ? FEEDBACK_DESTINATION : null, + exportId: artifacts.exportId, + consentVersion: sharedWithLabs ? consentVersion ?? DEFAULT_FEEDBACK_DATA_SHARING_TERMS_VERSION : null, + schemaVersion: FEEDBACK_SCHEMA_VERSION, + bundleVersion: FEEDBACK_BUNDLE_VERSION, + payloadVersion: FEEDBACK_PAYLOAD_VERSION, + payloadDigest: artifacts.payloadDigest, + payloadSnapshot: artifacts.payloadSnapshot, + targetSummary: artifacts.targetSummary, + redactionSummary: artifacts.redactionSummary, + updatedAt: now2 + }).onConflictDoUpdate({ + target: [feedbackExports.feedbackVoteId], + set: { + issueId: issue2.id, + projectId: issue2.projectId, + authorUserId: input.authorUserId, + targetType: input.targetType, + targetId: input.targetId, + vote: input.vote, + status: sharedWithLabs ? "pending" : "local_only", + destination: sharedWithLabs ? FEEDBACK_DESTINATION : null, + exportId: artifacts.exportId, + consentVersion: sharedWithLabs ? consentVersion ?? DEFAULT_FEEDBACK_DATA_SHARING_TERMS_VERSION : null, + schemaVersion: FEEDBACK_SCHEMA_VERSION, + bundleVersion: FEEDBACK_BUNDLE_VERSION, + payloadVersion: FEEDBACK_PAYLOAD_VERSION, + payloadDigest: artifacts.payloadDigest, + payloadSnapshot: artifacts.payloadSnapshot, + targetSummary: artifacts.targetSummary, + redactionSummary: artifacts.redactionSummary, + failureReason: null, + updatedAt: now2 + } + }).returning({ + id: feedbackExports.id + }); + return { + vote: { + ...savedVote, + redactionSummary: artifacts.redactionSummary + }, + traceId: savedTrace?.id ?? null, + consentEnabledNow, + persistedSharingPreference, + sharingEnabled: sharedWithLabs + }; + }) + }; +} + +// server/src/services/company-skills.ts +init_drizzle_orm(); +init_src2(); +import { createHash as createHash10 } from "node:crypto"; +import { promises as fs27 } from "node:fs"; +import path34 from "node:path"; +import { fileURLToPath as fileURLToPath15 } from "node:url"; + +// packages/adapters/cursor-local/src/server/execute.ts +import fs16 from "node:fs/promises"; +import os13 from "node:os"; +import path21 from "node:path"; +import { fileURLToPath as fileURLToPath8 } from "node:url"; + +// packages/adapters/cursor-local/src/index.ts +var DEFAULT_CURSOR_LOCAL_MODEL = "auto"; +var CURSOR_FALLBACK_MODEL_IDS = [ + "auto", + "composer-1.5", + "composer-1", + "gpt-5.3-codex-low", + "gpt-5.3-codex-low-fast", + "gpt-5.3-codex", + "gpt-5.3-codex-fast", + "gpt-5.3-codex-high", + "gpt-5.3-codex-high-fast", + "gpt-5.3-codex-xhigh", + "gpt-5.3-codex-xhigh-fast", + "gpt-5.3-codex-spark-preview", + "gpt-5.2", + "gpt-5.2-codex-low", + "gpt-5.2-codex-low-fast", + "gpt-5.2-codex", + "gpt-5.2-codex-fast", + "gpt-5.2-codex-high", + "gpt-5.2-codex-high-fast", + "gpt-5.2-codex-xhigh", + "gpt-5.2-codex-xhigh-fast", + "gpt-5.1-codex-max", + "gpt-5.1-codex-max-high", + "gpt-5.2-high", + "gpt-5.1-high", + "gpt-5.1-codex-mini", + "opus-4.6-thinking", + "opus-4.6", + "opus-4.5", + "opus-4.5-thinking", + "sonnet-4.6", + "sonnet-4.6-thinking", + "sonnet-4.5", + "sonnet-4.5-thinking", + "gemini-3.1-pro", + "gemini-3-pro", + "gemini-3-flash", + "grok", + "kimi-k2.5" +]; +var models3 = CURSOR_FALLBACK_MODEL_IDS.map((id) => ({ id, label: id })); +var agentConfigurationDoc3 = `# cursor agent configuration + +Adapter: cursor + +Use when: +- You want Taskcore to run Cursor Agent CLI locally as the agent runtime +- You want Cursor chat session resume across heartbeats via --resume +- You want structured stream output in run logs via --output-format stream-json + +Don't use when: +- You need webhook-style external invocation (use openclaw_gateway or http) +- You only need one-shot shell commands (use process) +- Cursor Agent CLI is not installed on the machine + +Core fields: +- cwd (string, optional): default absolute working directory fallback for the agent process (created if missing when possible) +- instructionsFilePath (string, optional): absolute path to a markdown instructions file prepended to the run prompt +- promptTemplate (string, optional): run prompt template +- model (string, optional): Cursor model id (for example auto or gpt-5.3-codex) +- mode (string, optional): Cursor execution mode passed as --mode (plan|ask). Leave unset for normal autonomous runs. +- command (string, optional): defaults to "agent" +- extraArgs (string[], optional): additional CLI args +- env (object, optional): KEY=VALUE environment variables + +Operational fields: +- timeoutSec (number, optional): run timeout in seconds +- graceSec (number, optional): SIGTERM grace period in seconds + +Notes: +- Runs are executed with: agent -p --output-format stream-json ... +- Prompts are piped to Cursor via stdin. +- Sessions are resumed with --resume when stored session cwd matches current cwd. +- Taskcore auto-injects local skills into "~/.cursor/skills" when missing, so Cursor can discover "$taskcore" and related skills on local runs. +- Taskcore auto-adds --yolo unless one of --trust/--yolo/-f is already present in extraArgs. +`; + +// packages/adapters/cursor-local/src/shared/stream.ts +function normalizeCursorStreamLine(rawLine) { + const trimmed = rawLine.trim(); + if (!trimmed) return { stream: null, line: "" }; + const prefixed = trimmed.match(/^(stdout|stderr)\s*[:=]?\s*([\[{].*)$/i); + if (!prefixed) { + return { stream: null, line: trimmed }; + } + const stream = prefixed[1]?.toLowerCase() === "stderr" ? "stderr" : "stdout"; + const line3 = (prefixed[2] ?? "").trim(); + return { stream, line: line3 }; +} + +// packages/adapters/cursor-local/src/server/parse.ts +function asErrorText(value) { + if (typeof value === "string") return value; + const rec = parseObject(value); + const message2 = asString(rec.message, "") || asString(rec.error, "") || asString(rec.code, "") || asString(rec.detail, ""); + if (message2) return message2; + try { + return JSON.stringify(rec); + } catch { + return ""; + } +} +function collectAssistantText(message2) { + if (typeof message2 === "string") { + const trimmed = message2.trim(); + return trimmed ? [trimmed] : []; + } + const rec = parseObject(message2); + const direct = asString(rec.text, "").trim(); + const lines = direct ? [direct] : []; + const content = Array.isArray(rec.content) ? rec.content : []; + for (const partRaw of content) { + const part = parseObject(partRaw); + const type = asString(part.type, "").trim(); + if (type === "output_text" || type === "text") { + const text3 = asString(part.text, "").trim(); + if (text3) lines.push(text3); + } + } + return lines; +} +function readSessionId(event) { + return asString(event.session_id, "").trim() || asString(event.sessionId, "").trim() || asString(event.sessionID, "").trim() || null; +} +function parseCursorJsonl(stdout) { + let sessionId = null; + const messages2 = []; + let errorMessage = null; + let totalCostUsd = 0; + const usage = { + inputTokens: 0, + cachedInputTokens: 0, + outputTokens: 0 + }; + for (const rawLine of stdout.split(/\r?\n/)) { + const line3 = normalizeCursorStreamLine(rawLine).line; + if (!line3) continue; + const event = parseJson2(line3); + if (!event) continue; + const foundSession = readSessionId(event); + if (foundSession) sessionId = foundSession; + const type = asString(event.type, "").trim(); + if (type === "assistant") { + messages2.push(...collectAssistantText(event.message)); + continue; + } + if (type === "result") { + const usageObj = parseObject(event.usage); + usage.inputTokens += asNumber( + usageObj.input_tokens, + asNumber(usageObj.inputTokens, 0) + ); + usage.cachedInputTokens += asNumber( + usageObj.cached_input_tokens, + asNumber(usageObj.cachedInputTokens, asNumber(usageObj.cache_read_input_tokens, 0)) + ); + usage.outputTokens += asNumber( + usageObj.output_tokens, + asNumber(usageObj.outputTokens, 0) + ); + totalCostUsd += asNumber(event.total_cost_usd, asNumber(event.cost_usd, asNumber(event.cost, 0))); + const isError = event.is_error === true || asString(event.subtype, "").toLowerCase() === "error"; + const resultText = asString(event.result, "").trim(); + if (resultText && messages2.length === 0) { + messages2.push(resultText); + } + if (isError) { + const resultError = asErrorText(event.error ?? event.message ?? event.result).trim(); + if (resultError) errorMessage = resultError; + } + continue; + } + if (type === "error") { + const message2 = asErrorText(event.message ?? event.error ?? event.detail).trim(); + if (message2) errorMessage = message2; + continue; + } + if (type === "system") { + const subtype = asString(event.subtype, "").trim().toLowerCase(); + if (subtype === "error") { + const message2 = asErrorText(event.message ?? event.error ?? event.detail).trim(); + if (message2) errorMessage = message2; + } + continue; + } + if (type === "text") { + const part = parseObject(event.part); + const text3 = asString(part.text, "").trim(); + if (text3) messages2.push(text3); + continue; + } + if (type === "step_finish") { + const part = parseObject(event.part); + const tokens = parseObject(part.tokens); + const cache7 = parseObject(tokens.cache); + usage.inputTokens += asNumber(tokens.input, 0); + usage.cachedInputTokens += asNumber(cache7.read, 0); + usage.outputTokens += asNumber(tokens.output, 0); + totalCostUsd += asNumber(part.cost, 0); + continue; + } + } + return { + sessionId, + summary: messages2.join("\n\n").trim(), + usage, + costUsd: totalCostUsd > 0 ? totalCostUsd : null, + errorMessage + }; +} +function isCursorUnknownSessionError(stdout, stderr) { + const haystack = `${stdout} +${stderr}`.split(/\r?\n/).map((line3) => line3.trim()).filter(Boolean).join("\n"); + return /unknown\s+(session|chat)|session\s+.*\s+not\s+found|chat\s+.*\s+not\s+found|resume\s+.*\s+not\s+found|could\s+not\s+resume/i.test( + haystack + ); +} + +// packages/adapters/cursor-local/src/shared/trust.ts +function hasCursorTrustBypassArg(args) { + return args.some( + (arg) => arg === "--trust" || arg === "--yolo" || arg === "-f" || arg.startsWith("--trust=") + ); +} + +// packages/adapters/cursor-local/src/server/execute.ts +var __moduleDir7 = path21.dirname(fileURLToPath8(import.meta.url)); +function firstNonEmptyLine7(text3) { + return text3.split(/\r?\n/).map((line3) => line3.trim()).find(Boolean) ?? ""; +} +function hasNonEmptyEnvValue3(env2, key) { + const raw = env2[key]; + return typeof raw === "string" && raw.trim().length > 0; +} +function resolveCursorBillingType(env2) { + return hasNonEmptyEnvValue3(env2, "CURSOR_API_KEY") || hasNonEmptyEnvValue3(env2, "OPENAI_API_KEY") ? "api" : "subscription"; +} +function resolveCursorBiller(env2, billingType, provider) { + const openAiCompatibleBiller = inferOpenAiCompatibleBiller(env2, null); + if (openAiCompatibleBiller === "openrouter") return "openrouter"; + if (billingType === "subscription") return "cursor"; + return provider ?? "cursor"; +} +function resolveProviderFromModel(model) { + const trimmed = model.trim().toLowerCase(); + if (!trimmed) return null; + const slash = trimmed.indexOf("/"); + if (slash > 0) return trimmed.slice(0, slash); + if (trimmed.includes("sonnet") || trimmed.includes("claude")) return "anthropic"; + if (trimmed.startsWith("gpt") || trimmed.startsWith("o")) return "openai"; + return null; +} +function normalizeMode(rawMode) { + const mode = rawMode.trim().toLowerCase(); + if (mode === "plan" || mode === "ask") return mode; + return null; +} +function renderTaskcoreEnvNote(env2) { + const taskcoreKeys = Object.keys(env2).filter((key) => key.startsWith("TASKCORE_")).sort(); + if (taskcoreKeys.length === 0) return ""; + return [ + "Taskcore runtime note:", + `The following TASKCORE_* environment variables are available in this run: ${taskcoreKeys.join(", ")}`, + "Do not assume these variables are missing without checking your shell environment.", + "", + "" + ].join("\n"); +} +function cursorSkillsHome() { + return path21.join(os13.homedir(), ".cursor", "skills"); +} +async function ensureCursorSkillsInjected(onLog, options = {}) { + const skillsEntries = options.skillsEntries ?? (options.skillsDir ? (await fs16.readdir(options.skillsDir, { withFileTypes: true })).filter((entry) => entry.isDirectory()).map((entry) => ({ + key: entry.name, + runtimeName: entry.name, + source: path21.join(options.skillsDir, entry.name) + })) : await readTaskcoreRuntimeSkillEntries({}, __moduleDir7)); + if (skillsEntries.length === 0) return; + const skillsHome = options.skillsHome ?? cursorSkillsHome(); + try { + await fs16.mkdir(skillsHome, { recursive: true }); + } catch (err) { + await onLog( + "stderr", + `[taskcore] Failed to prepare Cursor skills directory ${skillsHome}: ${err instanceof Error ? err.message : String(err)} +` + ); + return; + } + const removedSkills = await removeMaintainerOnlySkillSymlinks( + skillsHome, + skillsEntries.map((entry) => entry.runtimeName) + ); + for (const skillName of removedSkills) { + await onLog( + "stderr", + `[taskcore] Removed maintainer-only Cursor skill "${skillName}" from ${skillsHome} +` + ); + } + const linkSkill = options.linkSkill ?? ((source, target) => fs16.symlink(source, target)); + for (const entry of skillsEntries) { + const target = path21.join(skillsHome, entry.runtimeName); + try { + const result = await ensureTaskcoreSkillSymlink(entry.source, target, linkSkill); + if (result === "skipped") continue; + await onLog( + "stderr", + `[taskcore] ${result === "repaired" ? "Repaired" : "Injected"} Cursor skill "${entry.key}" into ${skillsHome} +` + ); + } catch (err) { + await onLog( + "stderr", + `[taskcore] Failed to inject Cursor skill "${entry.key}" into ${skillsHome}: ${err instanceof Error ? err.message : String(err)} +` + ); + } + } +} +async function execute4(ctx) { + const { runId, agent, runtime, config: config3, context, onLog, onMeta, onSpawn, authToken } = ctx; + const promptTemplate = asString( + config3.promptTemplate, + "You are agent {{agent.id}} ({{agent.name}}). Continue your Taskcore work." + ); + const command = asString(config3.command, "agent"); + const model = asString(config3.model, DEFAULT_CURSOR_LOCAL_MODEL).trim(); + const mode = normalizeMode(asString(config3.mode, "")); + const workspaceContext = parseObject(context.taskcoreWorkspace); + const workspaceCwd = asString(workspaceContext.cwd, ""); + const workspaceSource = asString(workspaceContext.source, ""); + const workspaceId = asString(workspaceContext.workspaceId, ""); + const workspaceRepoUrl = asString(workspaceContext.repoUrl, ""); + const workspaceRepoRef = asString(workspaceContext.repoRef, ""); + const agentHome = asString(workspaceContext.agentHome, ""); + const workspaceHints = Array.isArray(context.taskcoreWorkspaces) ? context.taskcoreWorkspaces.filter( + (value) => typeof value === "object" && value !== null + ) : []; + const configuredCwd = asString(config3.cwd, ""); + const useConfiguredInsteadOfAgentHome = workspaceSource === "agent_home" && configuredCwd.length > 0; + const effectiveWorkspaceCwd = useConfiguredInsteadOfAgentHome ? "" : workspaceCwd; + const cwd = effectiveWorkspaceCwd || configuredCwd || process.cwd(); + await ensureAbsoluteDirectory(cwd, { createIfMissing: true }); + const cursorSkillEntries = await readTaskcoreRuntimeSkillEntries(config3, __moduleDir7); + const desiredCursorSkillNames = resolveTaskcoreDesiredSkillNames(config3, cursorSkillEntries); + await ensureCursorSkillsInjected(onLog, { + skillsEntries: cursorSkillEntries.filter((entry) => desiredCursorSkillNames.includes(entry.key)) + }); + const envConfig = parseObject(config3.env); + const hasExplicitApiKey = typeof envConfig.TASKCORE_API_KEY === "string" && envConfig.TASKCORE_API_KEY.trim().length > 0; + const env2 = { ...buildTaskcoreEnv(agent) }; + env2.TASKCORE_RUN_ID = runId; + const wakeTaskId = typeof context.taskId === "string" && context.taskId.trim().length > 0 && context.taskId.trim() || typeof context.issueId === "string" && context.issueId.trim().length > 0 && context.issueId.trim() || null; + const wakeReason = typeof context.wakeReason === "string" && context.wakeReason.trim().length > 0 ? context.wakeReason.trim() : null; + const wakeCommentId = typeof context.wakeCommentId === "string" && context.wakeCommentId.trim().length > 0 && context.wakeCommentId.trim() || typeof context.commentId === "string" && context.commentId.trim().length > 0 && context.commentId.trim() || null; + const approvalId = typeof context.approvalId === "string" && context.approvalId.trim().length > 0 ? context.approvalId.trim() : null; + const approvalStatus = typeof context.approvalStatus === "string" && context.approvalStatus.trim().length > 0 ? context.approvalStatus.trim() : null; + const linkedIssueIds = Array.isArray(context.issueIds) ? context.issueIds.filter((value) => typeof value === "string" && value.trim().length > 0) : []; + const wakePayloadJson = stringifyTaskcoreWakePayload(context.taskcoreWake); + if (wakeTaskId) { + env2.TASKCORE_TASK_ID = wakeTaskId; + } + if (wakeReason) { + env2.TASKCORE_WAKE_REASON = wakeReason; + } + if (wakeCommentId) { + env2.TASKCORE_WAKE_COMMENT_ID = wakeCommentId; + } + if (approvalId) { + env2.TASKCORE_APPROVAL_ID = approvalId; + } + if (approvalStatus) { + env2.TASKCORE_APPROVAL_STATUS = approvalStatus; + } + if (linkedIssueIds.length > 0) { + env2.TASKCORE_LINKED_ISSUE_IDS = linkedIssueIds.join(","); + } + if (wakePayloadJson) { + env2.TASKCORE_WAKE_PAYLOAD_JSON = wakePayloadJson; + } + if (effectiveWorkspaceCwd) { + env2.TASKCORE_WORKSPACE_CWD = effectiveWorkspaceCwd; + } + if (workspaceSource) { + env2.TASKCORE_WORKSPACE_SOURCE = workspaceSource; + } + if (workspaceId) { + env2.TASKCORE_WORKSPACE_ID = workspaceId; + } + if (workspaceRepoUrl) { + env2.TASKCORE_WORKSPACE_REPO_URL = workspaceRepoUrl; + } + if (workspaceRepoRef) { + env2.TASKCORE_WORKSPACE_REPO_REF = workspaceRepoRef; + } + if (agentHome) { + env2.AGENT_HOME = agentHome; + } + if (workspaceHints.length > 0) { + env2.TASKCORE_WORKSPACES_JSON = JSON.stringify(workspaceHints); + } + for (const [k5, v5] of Object.entries(envConfig)) { + if (typeof v5 === "string") env2[k5] = v5; + } + if (!hasExplicitApiKey && authToken) { + env2.TASKCORE_API_KEY = authToken; + } + const effectiveEnv = Object.fromEntries( + Object.entries({ ...process.env, ...env2 }).filter( + (entry) => typeof entry[1] === "string" + ) + ); + const billingType = resolveCursorBillingType(effectiveEnv); + const runtimeEnv = ensurePathInEnv(effectiveEnv); + await ensureCommandResolvable(command, cwd, runtimeEnv); + const resolvedCommand = await resolveCommandForLogs(command, cwd, runtimeEnv); + const loggedEnv = buildInvocationEnvForLogs(env2, { + runtimeEnv, + includeRuntimeKeys: ["HOME"], + resolvedCommand + }); + const timeoutSec = asNumber(config3.timeoutSec, 0); + const graceSec = asNumber(config3.graceSec, 20); + const extraArgs = (() => { + const fromExtraArgs = asStringArray(config3.extraArgs); + if (fromExtraArgs.length > 0) return fromExtraArgs; + return asStringArray(config3.args); + })(); + const autoTrustEnabled = !hasCursorTrustBypassArg(extraArgs); + const runtimeSessionParams = parseObject(runtime.sessionParams); + const runtimeSessionId = asString(runtimeSessionParams.sessionId, runtime.sessionId ?? ""); + const runtimeSessionCwd = asString(runtimeSessionParams.cwd, ""); + const canResumeSession = runtimeSessionId.length > 0 && (runtimeSessionCwd.length === 0 || path21.resolve(runtimeSessionCwd) === path21.resolve(cwd)); + const sessionId = canResumeSession ? runtimeSessionId : null; + if (runtimeSessionId && !canResumeSession) { + await onLog( + "stdout", + `[taskcore] Cursor session "${runtimeSessionId}" was saved for cwd "${runtimeSessionCwd}" and will not be resumed in "${cwd}". +` + ); + } + const instructionsFilePath = asString(config3.instructionsFilePath, "").trim(); + const instructionsDir = instructionsFilePath ? `${path21.dirname(instructionsFilePath)}/` : ""; + let instructionsPrefix = ""; + let instructionsChars = 0; + if (instructionsFilePath) { + try { + const instructionsContents = await fs16.readFile(instructionsFilePath, "utf8"); + instructionsPrefix = `${instructionsContents} + +The above agent instructions were loaded from ${instructionsFilePath}. Resolve any relative file references from ${instructionsDir}. + +`; + instructionsChars = instructionsPrefix.length; + } catch (err) { + const reason = err instanceof Error ? err.message : String(err); + await onLog( + "stdout", + `[taskcore] Warning: could not read agent instructions file "${instructionsFilePath}": ${reason} +` + ); + } + } + const commandNotes = (() => { + const notes = []; + if (autoTrustEnabled) { + notes.push("Auto-added --yolo to bypass interactive prompts."); + } + notes.push("Prompt is piped to Cursor via stdin."); + if (!instructionsFilePath) return notes; + if (instructionsPrefix.length > 0) { + notes.push( + `Loaded agent instructions from ${instructionsFilePath}`, + `Prepended instructions + path directive to prompt (relative references from ${instructionsDir}).` + ); + return notes; + } + notes.push( + `Configured instructionsFilePath ${instructionsFilePath}, but file could not be read; continuing without injected instructions.` + ); + return notes; + })(); + const bootstrapPromptTemplate = asString(config3.bootstrapPromptTemplate, ""); + const templateData = { + agentId: agent.id, + companyId: agent.companyId, + runId, + company: { id: agent.companyId }, + agent, + run: { id: runId, source: "on_demand" }, + context + }; + const renderedBootstrapPrompt = !sessionId && bootstrapPromptTemplate.trim().length > 0 ? renderTemplate(bootstrapPromptTemplate, templateData).trim() : ""; + const wakePrompt = renderTaskcoreWakePrompt(context.taskcoreWake, { resumedSession: Boolean(sessionId) }); + const shouldUseResumeDeltaPrompt = Boolean(sessionId) && wakePrompt.length > 0; + const renderedPrompt = shouldUseResumeDeltaPrompt ? "" : renderTemplate(promptTemplate, templateData); + const sessionHandoffNote = asString(context.taskcoreSessionHandoffMarkdown, "").trim(); + const taskcoreEnvNote = renderTaskcoreEnvNote(env2); + const prompt = joinPromptSections([ + instructionsPrefix, + renderedBootstrapPrompt, + wakePrompt, + sessionHandoffNote, + taskcoreEnvNote, + renderedPrompt + ]); + const promptMetrics = { + promptChars: prompt.length, + instructionsChars, + bootstrapPromptChars: renderedBootstrapPrompt.length, + wakePromptChars: wakePrompt.length, + sessionHandoffChars: sessionHandoffNote.length, + runtimeNoteChars: taskcoreEnvNote.length, + heartbeatPromptChars: renderedPrompt.length + }; + const buildArgs = (resumeSessionId) => { + const args = ["-p", "--output-format", "stream-json", "--workspace", cwd]; + if (resumeSessionId) args.push("--resume", resumeSessionId); + if (model) args.push("--model", model); + if (mode) args.push("--mode", mode); + if (autoTrustEnabled) args.push("--yolo"); + if (extraArgs.length > 0) args.push(...extraArgs); + return args; + }; + const runAttempt = async (resumeSessionId) => { + const args = buildArgs(resumeSessionId); + if (onMeta) { + await onMeta({ + adapterType: "cursor", + command: resolvedCommand, + cwd, + commandNotes, + commandArgs: args, + env: loggedEnv, + prompt, + promptMetrics, + context + }); + } + let stdoutLineBuffer = ""; + const emitNormalizedStdoutLine = async (rawLine) => { + const normalized = normalizeCursorStreamLine(rawLine); + if (!normalized.line) return; + await onLog(normalized.stream ?? "stdout", `${normalized.line} +`); + }; + const flushStdoutChunk = async (chunk, finalize2 = false) => { + const combined = `${stdoutLineBuffer}${chunk}`; + const lines = combined.split(/\r?\n/); + stdoutLineBuffer = lines.pop() ?? ""; + for (const line3 of lines) { + await emitNormalizedStdoutLine(line3); + } + if (finalize2) { + const trailing = stdoutLineBuffer.trim(); + stdoutLineBuffer = ""; + if (trailing) { + await emitNormalizedStdoutLine(trailing); + } + } + }; + const proc = await runChildProcess(runId, command, args, { + cwd, + env: env2, + timeoutSec, + graceSec, + stdin: prompt, + onSpawn, + onLog: async (stream, chunk) => { + if (stream !== "stdout") { + await onLog(stream, chunk); + return; + } + await flushStdoutChunk(chunk); + } + }); + await flushStdoutChunk("", true); + return { + proc, + parsed: parseCursorJsonl(proc.stdout) + }; + }; + const providerFromModel = resolveProviderFromModel(model); + const toResult = (attempt, clearSessionOnMissingSession = false) => { + if (attempt.proc.timedOut) { + return { + exitCode: attempt.proc.exitCode, + signal: attempt.proc.signal, + timedOut: true, + errorMessage: `Timed out after ${timeoutSec}s`, + clearSession: clearSessionOnMissingSession + }; + } + const resolvedSessionId = attempt.parsed.sessionId ?? runtimeSessionId ?? runtime.sessionId ?? null; + const resolvedSessionParams = resolvedSessionId ? { + sessionId: resolvedSessionId, + cwd, + ...workspaceId ? { workspaceId } : {}, + ...workspaceRepoUrl ? { repoUrl: workspaceRepoUrl } : {}, + ...workspaceRepoRef ? { repoRef: workspaceRepoRef } : {} + } : null; + const parsedError = typeof attempt.parsed.errorMessage === "string" ? attempt.parsed.errorMessage.trim() : ""; + const stderrLine = firstNonEmptyLine7(attempt.proc.stderr); + const fallbackErrorMessage = parsedError || stderrLine || `Cursor exited with code ${attempt.proc.exitCode ?? -1}`; + return { + exitCode: attempt.proc.exitCode, + signal: attempt.proc.signal, + timedOut: false, + errorMessage: (attempt.proc.exitCode ?? 0) === 0 ? null : fallbackErrorMessage, + usage: attempt.parsed.usage, + sessionId: resolvedSessionId, + sessionParams: resolvedSessionParams, + sessionDisplayId: resolvedSessionId, + provider: providerFromModel, + biller: resolveCursorBiller(effectiveEnv, billingType, providerFromModel), + model, + billingType, + costUsd: attempt.parsed.costUsd, + resultJson: { + stdout: attempt.proc.stdout, + stderr: attempt.proc.stderr + }, + summary: attempt.parsed.summary, + clearSession: Boolean(clearSessionOnMissingSession && !resolvedSessionId) + }; + }; + const initial = await runAttempt(sessionId); + if (sessionId && !initial.proc.timedOut && (initial.proc.exitCode ?? 0) !== 0 && isCursorUnknownSessionError(initial.proc.stdout, initial.proc.stderr)) { + await onLog( + "stdout", + `[taskcore] Cursor resume session "${sessionId}" is unavailable; retrying with a fresh session. +` + ); + const retry = await runAttempt(null); + return toResult(retry, true); + } + return toResult(initial); +} + +// packages/adapters/cursor-local/src/server/skills.ts +import fs17 from "node:fs/promises"; +import os14 from "node:os"; +import path22 from "node:path"; +import { fileURLToPath as fileURLToPath9 } from "node:url"; +var __moduleDir8 = path22.dirname(fileURLToPath9(import.meta.url)); +function asString6(value) { + return typeof value === "string" && value.trim().length > 0 ? value.trim() : null; +} +function resolveCursorSkillsHome(config3) { + const env2 = typeof config3.env === "object" && config3.env !== null && !Array.isArray(config3.env) ? config3.env : {}; + const configuredHome = asString6(env2.HOME); + const home = configuredHome ? path22.resolve(configuredHome) : os14.homedir(); + return path22.join(home, ".cursor", "skills"); +} +async function buildCursorSkillSnapshot(config3) { + const availableEntries = await readTaskcoreRuntimeSkillEntries(config3, __moduleDir8); + const desiredSkills = resolveTaskcoreDesiredSkillNames(config3, availableEntries); + const skillsHome = resolveCursorSkillsHome(config3); + const installed = await readInstalledSkillTargets(skillsHome); + return buildPersistentSkillSnapshot({ + adapterType: "cursor", + availableEntries, + desiredSkills, + installed, + skillsHome, + locationLabel: "~/.cursor/skills", + missingDetail: "Configured but not currently linked into the Cursor skills home.", + externalConflictDetail: "Skill name is occupied by an external installation.", + externalDetail: "Installed outside Taskcore management." + }); +} +async function listCursorSkills(ctx) { + return buildCursorSkillSnapshot(ctx.config); +} +async function syncCursorSkills(ctx, desiredSkills) { + const availableEntries = await readTaskcoreRuntimeSkillEntries(ctx.config, __moduleDir8); + const desiredSet = /* @__PURE__ */ new Set([ + ...desiredSkills, + ...availableEntries.filter((entry) => entry.required).map((entry) => entry.key) + ]); + const skillsHome = resolveCursorSkillsHome(ctx.config); + await fs17.mkdir(skillsHome, { recursive: true }); + const installed = await readInstalledSkillTargets(skillsHome); + const availableByRuntimeName = new Map(availableEntries.map((entry) => [entry.runtimeName, entry])); + for (const available of availableEntries) { + if (!desiredSet.has(available.key)) continue; + const target = path22.join(skillsHome, available.runtimeName); + await ensureTaskcoreSkillSymlink(available.source, target); + } + for (const [name, installedEntry] of installed.entries()) { + const available = availableByRuntimeName.get(name); + if (!available) continue; + if (desiredSet.has(available.key)) continue; + if (installedEntry.targetPath !== available.source) continue; + await fs17.unlink(path22.join(skillsHome, name)).catch(() => { + }); + } + return buildCursorSkillSnapshot(ctx.config); +} + +// packages/adapters/cursor-local/src/server/test.ts +import fs18 from "node:fs/promises"; +import os15 from "node:os"; +import path23 from "node:path"; +function summarizeStatus4(checks) { + if (checks.some((check3) => check3.level === "error")) return "fail"; + if (checks.some((check3) => check3.level === "warn")) return "warn"; + return "pass"; +} +function isNonEmpty3(value) { + return typeof value === "string" && value.trim().length > 0; +} +function firstNonEmptyLine8(text3) { + return text3.split(/\r?\n/).map((line3) => line3.trim()).find(Boolean) ?? ""; +} +function commandLooksLike3(command, expected) { + const base = path23.basename(command).toLowerCase(); + return base === expected || base === `${expected}.cmd` || base === `${expected}.exe`; +} +function summarizeProbeDetail4(stdout, stderr, parsedError) { + const raw = parsedError?.trim() || firstNonEmptyLine8(stderr) || firstNonEmptyLine8(stdout); + if (!raw) return null; + const clean3 = raw.replace(/\s+/g, " ").trim(); + const max = 240; + return clean3.length > max ? `${clean3.slice(0, max - 1)}\u2026` : clean3; +} +function cursorConfigPath(cursorHome) { + return path23.join(cursorHome ?? path23.join(os15.homedir(), ".cursor"), "cli-config.json"); +} +async function readCursorAuthInfo(cursorHome) { + let raw; + try { + raw = await fs18.readFile(cursorConfigPath(cursorHome), "utf8"); + } catch { + return null; + } + let parsed; + try { + parsed = JSON.parse(raw); + } catch { + return null; + } + if (typeof parsed !== "object" || parsed === null) return null; + const obj = parsed; + const authInfo = obj.authInfo; + if (typeof authInfo !== "object" || authInfo === null) return null; + const info2 = authInfo; + const email3 = typeof info2.email === "string" && info2.email.trim().length > 0 ? info2.email.trim() : null; + const displayName = typeof info2.displayName === "string" && info2.displayName.trim().length > 0 ? info2.displayName.trim() : null; + const userId = typeof info2.userId === "number" ? info2.userId : null; + if (!email3 && !displayName && userId == null) return null; + return { email: email3, displayName, userId }; +} +var CURSOR_AUTH_REQUIRED_RE = /(?:authentication\s+required|not\s+authenticated|not\s+logged\s+in|unauthorized|invalid(?:\s+or\s+missing)?\s+api(?:[_\s-]?key)?|cursor[_\s-]?api[_\s-]?key|run\s+'?agent\s+login'?\s+first|api(?:[_\s-]?key)?(?:\s+is)?\s+required)/i; +async function testEnvironment4(ctx) { + const checks = []; + const config3 = parseObject(ctx.config); + const command = asString(config3.command, "agent"); + const cwd = asString(config3.cwd, process.cwd()); + try { + await ensureAbsoluteDirectory(cwd, { createIfMissing: true }); + checks.push({ + code: "cursor_cwd_valid", + level: "info", + message: `Working directory is valid: ${cwd}` + }); + } catch (err) { + checks.push({ + code: "cursor_cwd_invalid", + level: "error", + message: err instanceof Error ? err.message : "Invalid working directory", + detail: cwd + }); + } + const envConfig = parseObject(config3.env); + const env2 = {}; + for (const [key, value] of Object.entries(envConfig)) { + if (typeof value === "string") env2[key] = value; + } + const runtimeEnv = ensurePathInEnv({ ...process.env, ...env2 }); + try { + await ensureCommandResolvable(command, cwd, runtimeEnv); + checks.push({ + code: "cursor_command_resolvable", + level: "info", + message: `Command is executable: ${command}` + }); + } catch (err) { + checks.push({ + code: "cursor_command_unresolvable", + level: "error", + message: err instanceof Error ? err.message : "Command is not executable", + detail: command + }); + } + const configCursorApiKey = env2.CURSOR_API_KEY; + const hostCursorApiKey = process.env.CURSOR_API_KEY; + if (isNonEmpty3(configCursorApiKey) || isNonEmpty3(hostCursorApiKey)) { + const source = isNonEmpty3(configCursorApiKey) ? "adapter config env" : "server environment"; + checks.push({ + code: "cursor_api_key_present", + level: "info", + message: "CURSOR_API_KEY is set for Cursor authentication.", + detail: `Detected in ${source}.` + }); + } else { + const cursorHome = isNonEmpty3(env2.CURSOR_HOME) ? env2.CURSOR_HOME : void 0; + const cursorAuth = await readCursorAuthInfo(cursorHome).catch(() => null); + if (cursorAuth) { + checks.push({ + code: "cursor_native_auth_present", + level: "info", + message: "Cursor is authenticated via `agent login`.", + detail: cursorAuth.email ? `Logged in as ${cursorAuth.email}.` : `Credentials found in ${cursorConfigPath(cursorHome)}.` + }); + } else { + checks.push({ + code: "cursor_api_key_missing", + level: "warn", + message: "CURSOR_API_KEY is not set. Cursor runs may fail until authentication is configured.", + hint: "Set CURSOR_API_KEY in adapter env or run `agent login`." + }); + } + } + const canRunProbe = checks.every((check3) => check3.code !== "cursor_cwd_invalid" && check3.code !== "cursor_command_unresolvable"); + if (canRunProbe) { + if (!commandLooksLike3(command, "agent")) { + checks.push({ + code: "cursor_hello_probe_skipped_custom_command", + level: "info", + message: "Skipped hello probe because command is not `agent`.", + detail: command, + hint: "Use the `agent` CLI command to run the automatic installation and auth probe." + }); + } else { + const model = asString(config3.model, DEFAULT_CURSOR_LOCAL_MODEL).trim(); + const extraArgs = (() => { + const fromExtraArgs = asStringArray(config3.extraArgs); + if (fromExtraArgs.length > 0) return fromExtraArgs; + return asStringArray(config3.args); + })(); + const autoTrustEnabled = !hasCursorTrustBypassArg(extraArgs); + const args = ["-p", "--mode", "ask", "--output-format", "json", "--workspace", cwd]; + if (model) args.push("--model", model); + if (autoTrustEnabled) args.push("--yolo"); + if (extraArgs.length > 0) args.push(...extraArgs); + args.push("Respond with hello."); + const probe = await runChildProcess( + `cursor-envtest-${Date.now()}-${Math.random().toString(16).slice(2)}`, + command, + args, + { + cwd, + env: env2, + timeoutSec: 45, + graceSec: 5, + onLog: async () => { + } + } + ); + const parsed = parseCursorJsonl(probe.stdout); + const detail = summarizeProbeDetail4(probe.stdout, probe.stderr, parsed.errorMessage); + const authEvidence = `${parsed.errorMessage ?? ""} +${probe.stdout} +${probe.stderr}`.trim(); + if (probe.timedOut) { + checks.push({ + code: "cursor_hello_probe_timed_out", + level: "warn", + message: "Cursor hello probe timed out.", + hint: 'Retry the probe. If this persists, verify `agent -p --mode ask --output-format json "Respond with hello."` manually.' + }); + } else if ((probe.exitCode ?? 1) === 0) { + const summary = parsed.summary.trim(); + const hasHello = /\bhello\b/i.test(summary); + checks.push({ + code: hasHello ? "cursor_hello_probe_passed" : "cursor_hello_probe_unexpected_output", + level: hasHello ? "info" : "warn", + message: hasHello ? "Cursor hello probe succeeded." : "Cursor probe ran but did not return `hello` as expected.", + ...summary ? { detail: summary.replace(/\s+/g, " ").trim().slice(0, 240) } : {}, + ...hasHello ? {} : { + hint: 'Try `agent -p --mode ask --output-format json "Respond with hello."` manually to inspect full output.' + } + }); + } else if (CURSOR_AUTH_REQUIRED_RE.test(authEvidence)) { + checks.push({ + code: "cursor_hello_probe_auth_required", + level: "warn", + message: "Cursor CLI is installed, but authentication is not ready.", + ...detail ? { detail } : {}, + hint: "Run `agent login` or configure CURSOR_API_KEY in adapter env/shell, then retry the probe." + }); + } else { + checks.push({ + code: "cursor_hello_probe_failed", + level: "error", + message: "Cursor hello probe failed.", + ...detail ? { detail } : {}, + hint: 'Run `agent -p --mode ask --output-format json "Respond with hello."` manually in this working directory to debug.' + }); + } + } + } + return { + adapterType: ctx.adapterType, + status: summarizeStatus4(checks), + checks, + testedAt: (/* @__PURE__ */ new Date()).toISOString() + }; +} + +// packages/adapters/cursor-local/src/server/index.ts +function readNonEmptyString5(value) { + return typeof value === "string" && value.trim().length > 0 ? value.trim() : null; +} +var sessionCodec4 = { + deserialize(raw) { + if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return null; + const record2 = raw; + const sessionId = readNonEmptyString5(record2.sessionId) ?? readNonEmptyString5(record2.session_id) ?? readNonEmptyString5(record2.sessionID); + if (!sessionId) return null; + const cwd = readNonEmptyString5(record2.cwd) ?? readNonEmptyString5(record2.workdir) ?? readNonEmptyString5(record2.folder); + const workspaceId = readNonEmptyString5(record2.workspaceId) ?? readNonEmptyString5(record2.workspace_id); + const repoUrl = readNonEmptyString5(record2.repoUrl) ?? readNonEmptyString5(record2.repo_url); + const repoRef = readNonEmptyString5(record2.repoRef) ?? readNonEmptyString5(record2.repo_ref); + return { + sessionId, + ...cwd ? { cwd } : {}, + ...workspaceId ? { workspaceId } : {}, + ...repoUrl ? { repoUrl } : {}, + ...repoRef ? { repoRef } : {} + }; + }, + serialize(params) { + if (!params) return null; + const sessionId = readNonEmptyString5(params.sessionId) ?? readNonEmptyString5(params.session_id) ?? readNonEmptyString5(params.sessionID); + if (!sessionId) return null; + const cwd = readNonEmptyString5(params.cwd) ?? readNonEmptyString5(params.workdir) ?? readNonEmptyString5(params.folder); + const workspaceId = readNonEmptyString5(params.workspaceId) ?? readNonEmptyString5(params.workspace_id); + const repoUrl = readNonEmptyString5(params.repoUrl) ?? readNonEmptyString5(params.repo_url); + const repoRef = readNonEmptyString5(params.repoRef) ?? readNonEmptyString5(params.repo_ref); + return { + sessionId, + ...cwd ? { cwd } : {}, + ...workspaceId ? { workspaceId } : {}, + ...repoUrl ? { repoUrl } : {}, + ...repoRef ? { repoRef } : {} + }; + }, + getDisplayId(params) { + if (!params) return null; + return readNonEmptyString5(params.sessionId) ?? readNonEmptyString5(params.session_id) ?? readNonEmptyString5(params.sessionID); + } +}; + +// packages/adapters/gemini-local/src/server/execute.ts +import fs19 from "node:fs/promises"; +import os16 from "node:os"; +import path24 from "node:path"; +import { fileURLToPath as fileURLToPath10 } from "node:url"; + +// packages/adapters/gemini-local/src/index.ts +var DEFAULT_GEMINI_LOCAL_MODEL = "auto"; +var models4 = [ + { id: DEFAULT_GEMINI_LOCAL_MODEL, label: "Auto" }, + { id: "gemini-2.5-pro", label: "Gemini 2.5 Pro" }, + { id: "gemini-2.5-flash", label: "Gemini 2.5 Flash" }, + { id: "gemini-2.5-flash-lite", label: "Gemini 2.5 Flash Lite" }, + { id: "gemini-2.0-flash", label: "Gemini 2.0 Flash" }, + { id: "gemini-2.0-flash-lite", label: "Gemini 2.0 Flash Lite" } +]; +var agentConfigurationDoc4 = `# gemini_local agent configuration + +Adapter: gemini_local + +Use when: +- You want Taskcore to run the Gemini CLI locally on the host machine +- You want Gemini chat sessions resumed across heartbeats with --resume +- You want Taskcore skills injected locally without polluting the global environment + +Don't use when: +- You need webhook-style external invocation (use http or openclaw_gateway) +- You only need a one-shot script without an AI coding agent loop (use process) +- Gemini CLI is not installed on the machine that runs Taskcore + +Core fields: +- cwd (string, optional): default absolute working directory fallback for the agent process (created if missing when possible) +- instructionsFilePath (string, optional): absolute path to a markdown instructions file prepended to the run prompt +- promptTemplate (string, optional): run prompt template +- model (string, optional): Gemini model id. Defaults to auto. +- sandbox (boolean, optional): run in sandbox mode (default: false, passes --sandbox=none) +- command (string, optional): defaults to "gemini" +- extraArgs (string[], optional): additional CLI args +- env (object, optional): KEY=VALUE environment variables + +Operational fields: +- timeoutSec (number, optional): run timeout in seconds +- graceSec (number, optional): SIGTERM grace period in seconds + +Notes: +- Runs use positional prompt arguments, not stdin. +- Sessions resume with --resume when stored session cwd matches the current cwd. +- Taskcore auto-injects local skills into \`~/.gemini/skills/\` via symlinks, so the CLI can discover both credentials and skills in their natural location. +- Authentication can use GEMINI_API_KEY / GOOGLE_API_KEY or local Gemini CLI login. +`; + +// packages/adapters/gemini-local/src/server/parse.ts +function collectMessageText(message2) { + if (typeof message2 === "string") { + const trimmed = message2.trim(); + return trimmed ? [trimmed] : []; + } + const record2 = parseObject(message2); + const direct = asString(record2.text, "").trim(); + const lines = direct ? [direct] : []; + const content = Array.isArray(record2.content) ? record2.content : []; + for (const partRaw of content) { + const part = parseObject(partRaw); + const type = asString(part.type, "").trim(); + if (type === "output_text" || type === "text" || type === "content") { + const text3 = asString(part.text, "").trim() || asString(part.content, "").trim(); + if (text3) lines.push(text3); + } + } + return lines; +} +function readSessionId2(event) { + return asString(event.session_id, "").trim() || asString(event.sessionId, "").trim() || asString(event.sessionID, "").trim() || asString(event.checkpoint_id, "").trim() || asString(event.thread_id, "").trim() || null; +} +function asErrorText2(value) { + if (typeof value === "string") return value; + const rec = parseObject(value); + const message2 = asString(rec.message, "") || asString(rec.error, "") || asString(rec.code, "") || asString(rec.detail, ""); + if (message2) return message2; + try { + return JSON.stringify(rec); + } catch { + return ""; + } +} +function accumulateUsage(target, usageRaw) { + const usage = parseObject(usageRaw); + const usageMetadata = parseObject(usage.usageMetadata); + const source = Object.keys(usageMetadata).length > 0 ? usageMetadata : usage; + target.inputTokens += asNumber( + source.input_tokens, + asNumber(source.inputTokens, asNumber(source.promptTokenCount, 0)) + ); + target.cachedInputTokens += asNumber( + source.cached_input_tokens, + asNumber(source.cachedInputTokens, asNumber(source.cachedContentTokenCount, 0)) + ); + target.outputTokens += asNumber( + source.output_tokens, + asNumber(source.outputTokens, asNumber(source.candidatesTokenCount, 0)) + ); +} +function parseGeminiJsonl(stdout) { + let sessionId = null; + const messages2 = []; + let errorMessage = null; + let costUsd = null; + let resultEvent = null; + let question = null; + const usage = { + inputTokens: 0, + cachedInputTokens: 0, + outputTokens: 0 + }; + for (const rawLine of stdout.split(/\r?\n/)) { + const line3 = rawLine.trim(); + if (!line3) continue; + const event = parseJson2(line3); + if (!event) continue; + const foundSessionId = readSessionId2(event); + if (foundSessionId) sessionId = foundSessionId; + const type = asString(event.type, "").trim(); + if (type === "assistant") { + messages2.push(...collectMessageText(event.message)); + const messageObj = parseObject(event.message); + const content = Array.isArray(messageObj.content) ? messageObj.content : []; + for (const partRaw of content) { + const part = parseObject(partRaw); + if (asString(part.type, "").trim() === "question") { + question = { + prompt: asString(part.prompt, "").trim(), + choices: (Array.isArray(part.choices) ? part.choices : []).map((choiceRaw) => { + const choice = parseObject(choiceRaw); + return { + key: asString(choice.key, "").trim(), + label: asString(choice.label, "").trim(), + description: asString(choice.description, "").trim() || void 0 + }; + }) + }; + break; + } + } + continue; + } + if (type === "result") { + resultEvent = event; + accumulateUsage(usage, event.usage ?? event.usageMetadata); + const resultText = asString(event.result, "").trim() || asString(event.text, "").trim() || asString(event.response, "").trim(); + if (resultText && messages2.length === 0) messages2.push(resultText); + costUsd = asNumber(event.total_cost_usd, asNumber(event.cost_usd, asNumber(event.cost, costUsd ?? 0))) || costUsd; + const isError = event.is_error === true || asString(event.subtype, "").toLowerCase() === "error"; + if (isError) { + const text3 = asErrorText2(event.error ?? event.message ?? event.result).trim(); + if (text3) errorMessage = text3; + } + continue; + } + if (type === "error") { + const text3 = asErrorText2(event.error ?? event.message ?? event.detail).trim(); + if (text3) errorMessage = text3; + continue; + } + if (type === "system") { + const subtype = asString(event.subtype, "").trim().toLowerCase(); + if (subtype === "error") { + const text3 = asErrorText2(event.error ?? event.message ?? event.detail).trim(); + if (text3) errorMessage = text3; + } + continue; + } + if (type === "text") { + const part = parseObject(event.part); + const text3 = asString(part.text, "").trim(); + if (text3) messages2.push(text3); + continue; + } + if (type === "step_finish" || event.usage || event.usageMetadata) { + accumulateUsage(usage, event.usage ?? event.usageMetadata); + costUsd = asNumber(event.total_cost_usd, asNumber(event.cost_usd, asNumber(event.cost, costUsd ?? 0))) || costUsd; + continue; + } + } + return { + sessionId, + summary: messages2.join("\n\n").trim(), + usage, + costUsd, + errorMessage, + resultEvent, + question + }; +} +function isGeminiUnknownSessionError(stdout, stderr) { + const haystack = `${stdout} +${stderr}`.split(/\r?\n/).map((line3) => line3.trim()).filter(Boolean).join("\n"); + return /unknown\s+session|session\s+.*\s+not\s+found|resume\s+.*\s+not\s+found|checkpoint\s+.*\s+not\s+found|cannot\s+resume|failed\s+to\s+resume/i.test( + haystack + ); +} +function extractGeminiErrorMessages(parsed) { + const messages2 = []; + const errorMsg = asString(parsed.error, "").trim(); + if (errorMsg) messages2.push(errorMsg); + const raw = Array.isArray(parsed.errors) ? parsed.errors : []; + for (const entry of raw) { + if (typeof entry === "string") { + const msg2 = entry.trim(); + if (msg2) messages2.push(msg2); + continue; + } + if (typeof entry !== "object" || entry === null || Array.isArray(entry)) continue; + const obj = entry; + const msg = asString(obj.message, "") || asString(obj.error, "") || asString(obj.code, ""); + if (msg) { + messages2.push(msg); + continue; + } + try { + messages2.push(JSON.stringify(obj)); + } catch { + } + } + return messages2; +} +function describeGeminiFailure(parsed) { + const status = asString(parsed.status, ""); + const errors = extractGeminiErrorMessages(parsed); + const detail = errors[0] ?? ""; + const parts = ["Gemini run failed"]; + if (status) parts.push(`status=${status}`); + if (detail) parts.push(detail); + return parts.length > 1 ? parts.join(": ") : null; +} +var GEMINI_AUTH_REQUIRED_RE = /(?:not\s+authenticated|please\s+authenticate|api[_ ]?key\s+(?:required|missing|invalid)|authentication\s+required|unauthorized|invalid\s+credentials|not\s+logged\s+in|login\s+required|run\s+`?gemini\s+auth(?:\s+login)?`?\s+first)/i; +var GEMINI_QUOTA_EXHAUSTED_RE = /(?:resource_exhausted|quota|rate[-\s]?limit|too many requests|\b429\b|billing details)/i; +function detectGeminiAuthRequired(input) { + const errors = extractGeminiErrorMessages(input.parsed ?? {}); + const messages2 = [...errors, input.stdout, input.stderr].join("\n").split(/\r?\n/).map((line3) => line3.trim()).filter(Boolean); + const requiresAuth = messages2.some((line3) => GEMINI_AUTH_REQUIRED_RE.test(line3)); + return { requiresAuth }; +} +function detectGeminiQuotaExhausted(input) { + const errors = extractGeminiErrorMessages(input.parsed ?? {}); + const messages2 = [...errors, input.stdout, input.stderr].join("\n").split(/\r?\n/).map((line3) => line3.trim()).filter(Boolean); + const exhausted = messages2.some((line3) => GEMINI_QUOTA_EXHAUSTED_RE.test(line3)); + return { exhausted }; +} +function isGeminiTurnLimitResult(parsed, exitCode) { + if (exitCode === 53) return true; + if (!parsed) return false; + const status = asString(parsed.status, "").trim().toLowerCase(); + if (status === "turn_limit" || status === "max_turns") return true; + const error50 = asString(parsed.error, "").trim(); + return /turn\s*limit|max(?:imum)?\s+turns?/i.test(error50); +} + +// packages/adapters/gemini-local/src/server/utils.ts +function firstNonEmptyLine9(text3) { + return text3.split(/\r?\n/).map((line3) => line3.trim()).find(Boolean) ?? ""; +} + +// packages/adapters/gemini-local/src/server/execute.ts +var __moduleDir9 = path24.dirname(fileURLToPath10(import.meta.url)); +function hasNonEmptyEnvValue4(env2, key) { + const raw = env2[key]; + return typeof raw === "string" && raw.trim().length > 0; +} +function resolveGeminiBillingType(env2) { + return hasNonEmptyEnvValue4(env2, "GEMINI_API_KEY") || hasNonEmptyEnvValue4(env2, "GOOGLE_API_KEY") ? "api" : "subscription"; +} +function renderTaskcoreEnvNote2(env2) { + const taskcoreKeys = Object.keys(env2).filter((key) => key.startsWith("TASKCORE_")).sort(); + if (taskcoreKeys.length === 0) return ""; + return [ + "Taskcore runtime note:", + `The following TASKCORE_* environment variables are available in this run: ${taskcoreKeys.join(", ")}`, + "Do not assume these variables are missing without checking your shell environment.", + "", + "" + ].join("\n"); +} +function renderApiAccessNote(env2) { + if (!hasNonEmptyEnvValue4(env2, "TASKCORE_API_URL") || !hasNonEmptyEnvValue4(env2, "TASKCORE_API_KEY")) return ""; + return [ + "Taskcore API access note:", + "Use run_shell_command with curl to make Taskcore API requests.", + "GET example:", + ` run_shell_command({ command: "curl -s -H \\"Authorization: Bearer $TASKCORE_API_KEY\\" \\"$TASKCORE_API_URL/api/agents/me\\"" })`, + "POST/PATCH example:", + ` run_shell_command({ command: "curl -s -X POST -H \\"Authorization: Bearer $TASKCORE_API_KEY\\" -H 'Content-Type: application/json' -H \\"X-Taskcore-Run-Id: $TASKCORE_RUN_ID\\" -d '{...}' \\"$TASKCORE_API_URL/api/issues/{id}/checkout\\"" })`, + "", + "" + ].join("\n"); +} +function geminiSkillsHome() { + return path24.join(os16.homedir(), ".gemini", "skills"); +} +async function ensureGeminiSkillsInjected(onLog, skillsEntries, desiredSkillNames) { + const desiredSet = new Set(desiredSkillNames ?? skillsEntries.map((entry) => entry.key)); + const selectedEntries = skillsEntries.filter((entry) => desiredSet.has(entry.key)); + if (selectedEntries.length === 0) return; + const skillsHome = geminiSkillsHome(); + try { + await fs19.mkdir(skillsHome, { recursive: true }); + } catch (err) { + await onLog( + "stderr", + `[taskcore] Failed to prepare Gemini skills directory ${skillsHome}: ${err instanceof Error ? err.message : String(err)} +` + ); + return; + } + const removedSkills = await removeMaintainerOnlySkillSymlinks( + skillsHome, + selectedEntries.map((entry) => entry.runtimeName) + ); + for (const skillName of removedSkills) { + await onLog( + "stderr", + `[taskcore] Removed maintainer-only Gemini skill "${skillName}" from ${skillsHome} +` + ); + } + for (const entry of selectedEntries) { + const target = path24.join(skillsHome, entry.runtimeName); + try { + const result = await ensureTaskcoreSkillSymlink(entry.source, target); + if (result === "skipped") continue; + await onLog( + "stderr", + `[taskcore] ${result === "repaired" ? "Repaired" : "Linked"} Gemini skill: ${entry.key} +` + ); + } catch (err) { + await onLog( + "stderr", + `[taskcore] Failed to link Gemini skill "${entry.key}": ${err instanceof Error ? err.message : String(err)} +` + ); + } + } +} +async function execute5(ctx) { + const { runId, agent, runtime, config: config3, context, onLog, onMeta, onSpawn, authToken } = ctx; + const promptTemplate = asString( + config3.promptTemplate, + "You are agent {{agent.id}} ({{agent.name}}). Continue your Taskcore work." + ); + const command = asString(config3.command, "gemini"); + const model = asString(config3.model, DEFAULT_GEMINI_LOCAL_MODEL).trim(); + const sandbox = asBoolean(config3.sandbox, false); + const workspaceContext = parseObject(context.taskcoreWorkspace); + const workspaceCwd = asString(workspaceContext.cwd, ""); + const workspaceSource = asString(workspaceContext.source, ""); + const workspaceId = asString(workspaceContext.workspaceId, ""); + const workspaceRepoUrl = asString(workspaceContext.repoUrl, ""); + const workspaceRepoRef = asString(workspaceContext.repoRef, ""); + const agentHome = asString(workspaceContext.agentHome, ""); + const workspaceHints = Array.isArray(context.taskcoreWorkspaces) ? context.taskcoreWorkspaces.filter( + (value) => typeof value === "object" && value !== null + ) : []; + const configuredCwd = asString(config3.cwd, ""); + const useConfiguredInsteadOfAgentHome = workspaceSource === "agent_home" && configuredCwd.length > 0; + const effectiveWorkspaceCwd = useConfiguredInsteadOfAgentHome ? "" : workspaceCwd; + const cwd = effectiveWorkspaceCwd || configuredCwd || process.cwd(); + await ensureAbsoluteDirectory(cwd, { createIfMissing: true }); + const geminiSkillEntries = await readTaskcoreRuntimeSkillEntries(config3, __moduleDir9); + const desiredGeminiSkillNames = resolveTaskcoreDesiredSkillNames(config3, geminiSkillEntries); + await ensureGeminiSkillsInjected(onLog, geminiSkillEntries, desiredGeminiSkillNames); + const envConfig = parseObject(config3.env); + const hasExplicitApiKey = typeof envConfig.TASKCORE_API_KEY === "string" && envConfig.TASKCORE_API_KEY.trim().length > 0; + const env2 = { ...buildTaskcoreEnv(agent) }; + env2.TASKCORE_RUN_ID = runId; + const wakeTaskId = typeof context.taskId === "string" && context.taskId.trim().length > 0 && context.taskId.trim() || typeof context.issueId === "string" && context.issueId.trim().length > 0 && context.issueId.trim() || null; + const wakeReason = typeof context.wakeReason === "string" && context.wakeReason.trim().length > 0 ? context.wakeReason.trim() : null; + const wakeCommentId = typeof context.wakeCommentId === "string" && context.wakeCommentId.trim().length > 0 && context.wakeCommentId.trim() || typeof context.commentId === "string" && context.commentId.trim().length > 0 && context.commentId.trim() || null; + const approvalId = typeof context.approvalId === "string" && context.approvalId.trim().length > 0 ? context.approvalId.trim() : null; + const approvalStatus = typeof context.approvalStatus === "string" && context.approvalStatus.trim().length > 0 ? context.approvalStatus.trim() : null; + const linkedIssueIds = Array.isArray(context.issueIds) ? context.issueIds.filter((value) => typeof value === "string" && value.trim().length > 0) : []; + const wakePayloadJson = stringifyTaskcoreWakePayload(context.taskcoreWake); + if (wakeTaskId) env2.TASKCORE_TASK_ID = wakeTaskId; + if (wakeReason) env2.TASKCORE_WAKE_REASON = wakeReason; + if (wakeCommentId) env2.TASKCORE_WAKE_COMMENT_ID = wakeCommentId; + if (approvalId) env2.TASKCORE_APPROVAL_ID = approvalId; + if (approvalStatus) env2.TASKCORE_APPROVAL_STATUS = approvalStatus; + if (linkedIssueIds.length > 0) env2.TASKCORE_LINKED_ISSUE_IDS = linkedIssueIds.join(","); + if (wakePayloadJson) env2.TASKCORE_WAKE_PAYLOAD_JSON = wakePayloadJson; + if (effectiveWorkspaceCwd) env2.TASKCORE_WORKSPACE_CWD = effectiveWorkspaceCwd; + if (workspaceSource) env2.TASKCORE_WORKSPACE_SOURCE = workspaceSource; + if (workspaceId) env2.TASKCORE_WORKSPACE_ID = workspaceId; + if (workspaceRepoUrl) env2.TASKCORE_WORKSPACE_REPO_URL = workspaceRepoUrl; + if (workspaceRepoRef) env2.TASKCORE_WORKSPACE_REPO_REF = workspaceRepoRef; + if (agentHome) env2.AGENT_HOME = agentHome; + if (workspaceHints.length > 0) env2.TASKCORE_WORKSPACES_JSON = JSON.stringify(workspaceHints); + for (const [key, value] of Object.entries(envConfig)) { + if (typeof value === "string") env2[key] = value; + } + if (!hasExplicitApiKey && authToken) { + env2.TASKCORE_API_KEY = authToken; + } + const effectiveEnv = Object.fromEntries( + Object.entries({ ...process.env, ...env2 }).filter( + (entry) => typeof entry[1] === "string" + ) + ); + const billingType = resolveGeminiBillingType(effectiveEnv); + const runtimeEnv = ensurePathInEnv(effectiveEnv); + await ensureCommandResolvable(command, cwd, runtimeEnv); + const resolvedCommand = await resolveCommandForLogs(command, cwd, runtimeEnv); + const loggedEnv = buildInvocationEnvForLogs(env2, { + runtimeEnv, + includeRuntimeKeys: ["HOME"], + resolvedCommand + }); + const timeoutSec = asNumber(config3.timeoutSec, 0); + const graceSec = asNumber(config3.graceSec, 20); + const extraArgs = (() => { + const fromExtraArgs = asStringArray(config3.extraArgs); + if (fromExtraArgs.length > 0) return fromExtraArgs; + return asStringArray(config3.args); + })(); + const runtimeSessionParams = parseObject(runtime.sessionParams); + const runtimeSessionId = asString(runtimeSessionParams.sessionId, runtime.sessionId ?? ""); + const runtimeSessionCwd = asString(runtimeSessionParams.cwd, ""); + const canResumeSession = runtimeSessionId.length > 0 && (runtimeSessionCwd.length === 0 || path24.resolve(runtimeSessionCwd) === path24.resolve(cwd)); + const sessionId = canResumeSession ? runtimeSessionId : null; + if (runtimeSessionId && !canResumeSession) { + await onLog( + "stdout", + `[taskcore] Gemini session "${runtimeSessionId}" was saved for cwd "${runtimeSessionCwd}" and will not be resumed in "${cwd}". +` + ); + } + const instructionsFilePath = asString(config3.instructionsFilePath, "").trim(); + const instructionsDir = instructionsFilePath ? `${path24.dirname(instructionsFilePath)}/` : ""; + let instructionsPrefix = ""; + if (instructionsFilePath) { + try { + const instructionsContents = await fs19.readFile(instructionsFilePath, "utf8"); + instructionsPrefix = `${instructionsContents} + +The above agent instructions were loaded from ${instructionsFilePath}. Resolve any relative file references from ${instructionsDir}. + +`; + } catch (err) { + const reason = err instanceof Error ? err.message : String(err); + await onLog( + "stdout", + `[taskcore] Warning: could not read agent instructions file "${instructionsFilePath}": ${reason} +` + ); + } + } + const commandNotes = (() => { + const notes = ["Prompt is passed to Gemini via --prompt for non-interactive execution."]; + notes.push("Added --approval-mode yolo for unattended execution."); + if (!instructionsFilePath) return notes; + if (instructionsPrefix.length > 0) { + notes.push( + `Loaded agent instructions from ${instructionsFilePath}`, + `Prepended instructions + path directive to prompt (relative references from ${instructionsDir}).` + ); + return notes; + } + notes.push( + `Configured instructionsFilePath ${instructionsFilePath}, but file could not be read; continuing without injected instructions.` + ); + return notes; + })(); + const bootstrapPromptTemplate = asString(config3.bootstrapPromptTemplate, ""); + const templateData = { + agentId: agent.id, + companyId: agent.companyId, + runId, + company: { id: agent.companyId }, + agent, + run: { id: runId, source: "on_demand" }, + context + }; + const renderedBootstrapPrompt = !sessionId && bootstrapPromptTemplate.trim().length > 0 ? renderTemplate(bootstrapPromptTemplate, templateData).trim() : ""; + const wakePrompt = renderTaskcoreWakePrompt(context.taskcoreWake, { resumedSession: Boolean(sessionId) }); + const shouldUseResumeDeltaPrompt = Boolean(sessionId) && wakePrompt.length > 0; + const renderedPrompt = shouldUseResumeDeltaPrompt ? "" : renderTemplate(promptTemplate, templateData); + const sessionHandoffNote = asString(context.taskcoreSessionHandoffMarkdown, "").trim(); + const taskcoreEnvNote = renderTaskcoreEnvNote2(env2); + const apiAccessNote = renderApiAccessNote(env2); + const prompt = joinPromptSections([ + instructionsPrefix, + renderedBootstrapPrompt, + wakePrompt, + sessionHandoffNote, + taskcoreEnvNote, + apiAccessNote, + renderedPrompt + ]); + const promptMetrics = { + promptChars: prompt.length, + instructionsChars: instructionsPrefix.length, + bootstrapPromptChars: renderedBootstrapPrompt.length, + wakePromptChars: wakePrompt.length, + sessionHandoffChars: sessionHandoffNote.length, + runtimeNoteChars: taskcoreEnvNote.length + apiAccessNote.length, + heartbeatPromptChars: renderedPrompt.length + }; + const buildArgs = (resumeSessionId) => { + const args = ["--output-format", "stream-json"]; + if (resumeSessionId) args.push("--resume", resumeSessionId); + if (model && model !== DEFAULT_GEMINI_LOCAL_MODEL) args.push("--model", model); + args.push("--approval-mode", "yolo"); + if (sandbox) { + args.push("--sandbox"); + } else { + args.push("--sandbox=none"); + } + if (extraArgs.length > 0) args.push(...extraArgs); + args.push("--prompt", prompt); + return args; + }; + const runAttempt = async (resumeSessionId) => { + const args = buildArgs(resumeSessionId); + if (onMeta) { + await onMeta({ + adapterType: "gemini_local", + command: resolvedCommand, + cwd, + commandNotes, + commandArgs: args.map((value, index2) => index2 === args.length - 1 ? `` : value), + env: loggedEnv, + prompt, + promptMetrics, + context + }); + } + const proc = await runChildProcess(runId, command, args, { + cwd, + env: env2, + timeoutSec, + graceSec, + onSpawn, + onLog + }); + return { + proc, + parsed: parseGeminiJsonl(proc.stdout) + }; + }; + const toResult = (attempt, clearSessionOnMissingSession = false, isRetry = false) => { + const authMeta = detectGeminiAuthRequired({ + parsed: attempt.parsed.resultEvent, + stdout: attempt.proc.stdout, + stderr: attempt.proc.stderr + }); + if (attempt.proc.timedOut) { + return { + exitCode: attempt.proc.exitCode, + signal: attempt.proc.signal, + timedOut: true, + errorMessage: `Timed out after ${timeoutSec}s`, + errorCode: authMeta.requiresAuth ? "gemini_auth_required" : null, + clearSession: clearSessionOnMissingSession + }; + } + const clearSessionForTurnLimit = isGeminiTurnLimitResult(attempt.parsed.resultEvent, attempt.proc.exitCode); + const canFallbackToRuntimeSession = !isRetry; + const resolvedSessionId = attempt.parsed.sessionId ?? (canFallbackToRuntimeSession ? runtimeSessionId ?? runtime.sessionId ?? null : null); + const resolvedSessionParams = resolvedSessionId ? { + sessionId: resolvedSessionId, + cwd, + ...workspaceId ? { workspaceId } : {}, + ...workspaceRepoUrl ? { repoUrl: workspaceRepoUrl } : {}, + ...workspaceRepoRef ? { repoRef: workspaceRepoRef } : {} + } : null; + const parsedError = typeof attempt.parsed.errorMessage === "string" ? attempt.parsed.errorMessage.trim() : ""; + const stderrLine = firstNonEmptyLine9(attempt.proc.stderr); + const structuredFailure = attempt.parsed.resultEvent ? describeGeminiFailure(attempt.parsed.resultEvent) : null; + const fallbackErrorMessage = parsedError || structuredFailure || stderrLine || `Gemini exited with code ${attempt.proc.exitCode ?? -1}`; + return { + exitCode: attempt.proc.exitCode, + signal: attempt.proc.signal, + timedOut: false, + errorMessage: (attempt.proc.exitCode ?? 0) === 0 ? null : fallbackErrorMessage, + errorCode: (attempt.proc.exitCode ?? 0) !== 0 && authMeta.requiresAuth ? "gemini_auth_required" : null, + usage: attempt.parsed.usage, + sessionId: resolvedSessionId, + sessionParams: resolvedSessionParams, + sessionDisplayId: resolvedSessionId, + provider: "google", + biller: "google", + model, + billingType, + costUsd: attempt.parsed.costUsd, + resultJson: attempt.parsed.resultEvent ?? { + stdout: attempt.proc.stdout, + stderr: attempt.proc.stderr + }, + summary: attempt.parsed.summary, + question: attempt.parsed.question, + clearSession: clearSessionForTurnLimit || Boolean(clearSessionOnMissingSession && !resolvedSessionId) + }; + }; + const initial = await runAttempt(sessionId); + if (sessionId && !initial.proc.timedOut && (initial.proc.exitCode ?? 0) !== 0 && isGeminiUnknownSessionError(initial.proc.stdout, initial.proc.stderr)) { + await onLog( + "stdout", + `[taskcore] Gemini resume session "${sessionId}" is unavailable; retrying with a fresh session. +` + ); + const retry = await runAttempt(null); + return toResult(retry, true, true); + } + return toResult(initial); +} + +// packages/adapters/gemini-local/src/server/skills.ts +import fs20 from "node:fs/promises"; +import os17 from "node:os"; +import path25 from "node:path"; +import { fileURLToPath as fileURLToPath11 } from "node:url"; +var __moduleDir10 = path25.dirname(fileURLToPath11(import.meta.url)); +function asString7(value) { + return typeof value === "string" && value.trim().length > 0 ? value.trim() : null; +} +function resolveGeminiSkillsHome(config3) { + const env2 = typeof config3.env === "object" && config3.env !== null && !Array.isArray(config3.env) ? config3.env : {}; + const configuredHome = asString7(env2.HOME); + const home = configuredHome ? path25.resolve(configuredHome) : os17.homedir(); + return path25.join(home, ".gemini", "skills"); +} +async function buildGeminiSkillSnapshot(config3) { + const availableEntries = await readTaskcoreRuntimeSkillEntries(config3, __moduleDir10); + const desiredSkills = resolveTaskcoreDesiredSkillNames(config3, availableEntries); + const skillsHome = resolveGeminiSkillsHome(config3); + const installed = await readInstalledSkillTargets(skillsHome); + return buildPersistentSkillSnapshot({ + adapterType: "gemini_local", + availableEntries, + desiredSkills, + installed, + skillsHome, + locationLabel: "~/.gemini/skills", + missingDetail: "Configured but not currently linked into the Gemini skills home.", + externalConflictDetail: "Skill name is occupied by an external installation.", + externalDetail: "Installed outside Taskcore management." + }); +} +async function listGeminiSkills(ctx) { + return buildGeminiSkillSnapshot(ctx.config); +} +async function syncGeminiSkills(ctx, desiredSkills) { + const availableEntries = await readTaskcoreRuntimeSkillEntries(ctx.config, __moduleDir10); + const desiredSet = /* @__PURE__ */ new Set([ + ...desiredSkills, + ...availableEntries.filter((entry) => entry.required).map((entry) => entry.key) + ]); + const skillsHome = resolveGeminiSkillsHome(ctx.config); + await fs20.mkdir(skillsHome, { recursive: true }); + const installed = await readInstalledSkillTargets(skillsHome); + const availableByRuntimeName = new Map(availableEntries.map((entry) => [entry.runtimeName, entry])); + for (const available of availableEntries) { + if (!desiredSet.has(available.key)) continue; + const target = path25.join(skillsHome, available.runtimeName); + await ensureTaskcoreSkillSymlink(available.source, target); + } + for (const [name, installedEntry] of installed.entries()) { + const available = availableByRuntimeName.get(name); + if (!available) continue; + if (desiredSet.has(available.key)) continue; + if (installedEntry.targetPath !== available.source) continue; + await fs20.unlink(path25.join(skillsHome, name)).catch(() => { + }); + } + return buildGeminiSkillSnapshot(ctx.config); +} + +// packages/adapters/gemini-local/src/server/test.ts +import path26 from "node:path"; +function summarizeStatus5(checks) { + if (checks.some((check3) => check3.level === "error")) return "fail"; + if (checks.some((check3) => check3.level === "warn")) return "warn"; + return "pass"; +} +function isNonEmpty4(value) { + return typeof value === "string" && value.trim().length > 0; +} +function commandLooksLike4(command, expected) { + const base = path26.basename(command).toLowerCase(); + return base === expected || base === `${expected}.cmd` || base === `${expected}.exe`; +} +function summarizeProbeDetail5(stdout, stderr, parsedError) { + const raw = parsedError?.trim() || firstNonEmptyLine9(stderr) || firstNonEmptyLine9(stdout); + if (!raw) return null; + const clean3 = raw.replace(/\s+/g, " ").trim(); + const max = 240; + return clean3.length > max ? `${clean3.slice(0, max - 1)}\u2026` : clean3; +} +async function testEnvironment5(ctx) { + const checks = []; + const config3 = parseObject(ctx.config); + const command = asString(config3.command, "gemini"); + const cwd = asString(config3.cwd, process.cwd()); + try { + await ensureAbsoluteDirectory(cwd, { createIfMissing: true }); + checks.push({ + code: "gemini_cwd_valid", + level: "info", + message: `Working directory is valid: ${cwd}` + }); + } catch (err) { + checks.push({ + code: "gemini_cwd_invalid", + level: "error", + message: err instanceof Error ? err.message : "Invalid working directory", + detail: cwd + }); + } + const envConfig = parseObject(config3.env); + const env2 = {}; + for (const [key, value] of Object.entries(envConfig)) { + if (typeof value === "string") env2[key] = value; + } + const runtimeEnv = ensurePathInEnv({ ...process.env, ...env2 }); + try { + await ensureCommandResolvable(command, cwd, runtimeEnv); + checks.push({ + code: "gemini_command_resolvable", + level: "info", + message: `Command is executable: ${command}` + }); + } catch (err) { + checks.push({ + code: "gemini_command_unresolvable", + level: "error", + message: err instanceof Error ? err.message : "Command is not executable", + detail: command + }); + } + const configGeminiApiKey = env2.GEMINI_API_KEY; + const hostGeminiApiKey = process.env.GEMINI_API_KEY; + const configGoogleApiKey = env2.GOOGLE_API_KEY; + const hostGoogleApiKey = process.env.GOOGLE_API_KEY; + const hasGca = env2.GOOGLE_GENAI_USE_GCA === "true" || process.env.GOOGLE_GENAI_USE_GCA === "true"; + if (isNonEmpty4(configGeminiApiKey) || isNonEmpty4(hostGeminiApiKey) || isNonEmpty4(configGoogleApiKey) || isNonEmpty4(hostGoogleApiKey) || hasGca) { + const source = hasGca ? "Google account login (GCA)" : isNonEmpty4(configGeminiApiKey) || isNonEmpty4(configGoogleApiKey) ? "adapter config env" : "server environment"; + checks.push({ + code: "gemini_api_key_present", + level: "info", + message: "Gemini API credentials are set for CLI authentication.", + detail: `Detected in ${source}.` + }); + } else { + checks.push({ + code: "gemini_api_key_missing", + level: "info", + message: "No explicit API key detected. Gemini CLI may still authenticate via `gemini auth login` (OAuth).", + hint: "If the hello probe fails with an auth error, set GEMINI_API_KEY or GOOGLE_API_KEY in adapter env, or run `gemini auth login`." + }); + } + const canRunProbe = checks.every((check3) => check3.code !== "gemini_cwd_invalid" && check3.code !== "gemini_command_unresolvable"); + if (canRunProbe) { + if (!commandLooksLike4(command, "gemini")) { + checks.push({ + code: "gemini_hello_probe_skipped_custom_command", + level: "info", + message: "Skipped hello probe because command is not `gemini`.", + detail: command, + hint: "Use the `gemini` CLI command to run the automatic installation and auth probe." + }); + } else { + const model = asString(config3.model, DEFAULT_GEMINI_LOCAL_MODEL).trim(); + const approvalMode = asString(config3.approvalMode, asBoolean(config3.yolo, false) ? "yolo" : "default"); + const sandbox = asBoolean(config3.sandbox, false); + const helloProbeTimeoutSec = Math.max(1, asNumber(config3.helloProbeTimeoutSec, 10)); + const extraArgs = (() => { + const fromExtraArgs = asStringArray(config3.extraArgs); + if (fromExtraArgs.length > 0) return fromExtraArgs; + return asStringArray(config3.args); + })(); + const args = ["--output-format", "stream-json", "--prompt", "Respond with hello."]; + if (model && model !== DEFAULT_GEMINI_LOCAL_MODEL) args.push("--model", model); + if (approvalMode !== "default") args.push("--approval-mode", approvalMode); + if (sandbox) { + args.push("--sandbox"); + } else { + args.push("--sandbox=none"); + } + if (extraArgs.length > 0) args.push(...extraArgs); + const probe = await runChildProcess( + `gemini-envtest-${Date.now()}-${Math.random().toString(16).slice(2)}`, + command, + args, + { + cwd, + env: env2, + timeoutSec: helloProbeTimeoutSec, + graceSec: 5, + onLog: async () => { + } + } + ); + const parsed = parseGeminiJsonl(probe.stdout); + const detail = summarizeProbeDetail5(probe.stdout, probe.stderr, parsed.errorMessage); + const authMeta = detectGeminiAuthRequired({ + parsed: parsed.resultEvent, + stdout: probe.stdout, + stderr: probe.stderr + }); + const quotaMeta = detectGeminiQuotaExhausted({ + parsed: parsed.resultEvent, + stdout: probe.stdout, + stderr: probe.stderr + }); + if (quotaMeta.exhausted) { + checks.push({ + code: "gemini_hello_probe_quota_exhausted", + level: "warn", + message: probe.timedOut ? "Gemini CLI is retrying after quota exhaustion." : "Gemini CLI authentication is configured, but the current account or API key is over quota.", + ...detail ? { detail } : {}, + hint: "The configured Gemini account or API key is over quota. Check ai.google.dev usage/billing, then retry the probe." + }); + } else if (probe.timedOut) { + checks.push({ + code: "gemini_hello_probe_timed_out", + level: "warn", + message: "Gemini hello probe timed out.", + hint: "Retry the probe. If this persists, verify Gemini can run `Respond with hello.` from this directory manually." + }); + } else if ((probe.exitCode ?? 1) === 0) { + const summary = parsed.summary.trim(); + const hasHello = /\bhello\b/i.test(summary); + checks.push({ + code: hasHello ? "gemini_hello_probe_passed" : "gemini_hello_probe_unexpected_output", + level: hasHello ? "info" : "warn", + message: hasHello ? "Gemini hello probe succeeded." : "Gemini probe ran but did not return `hello` as expected.", + ...summary ? { detail: summary.replace(/\s+/g, " ").trim().slice(0, 240) } : {}, + ...hasHello ? {} : { + hint: 'Try `gemini --output-format json "Respond with hello."` manually to inspect full output.' + } + }); + } else if (authMeta.requiresAuth) { + checks.push({ + code: "gemini_hello_probe_auth_required", + level: "warn", + message: "Gemini CLI is installed, but authentication is not ready.", + ...detail ? { detail } : {}, + hint: "Run `gemini auth` or configure GEMINI_API_KEY / GOOGLE_API_KEY in adapter env/shell, then retry the probe." + }); + } else { + checks.push({ + code: "gemini_hello_probe_failed", + level: "error", + message: "Gemini hello probe failed.", + ...detail ? { detail } : {}, + hint: 'Run `gemini --output-format json "Respond with hello."` manually in this working directory to debug.' + }); + } + } + } + return { + adapterType: ctx.adapterType, + status: summarizeStatus5(checks), + checks, + testedAt: (/* @__PURE__ */ new Date()).toISOString() + }; +} + +// packages/adapters/gemini-local/src/server/index.ts +function readNonEmptyString6(value) { + return typeof value === "string" && value.trim().length > 0 ? value.trim() : null; +} +var sessionCodec5 = { + deserialize(raw) { + if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return null; + const record2 = raw; + const sessionId = readNonEmptyString6(record2.sessionId) ?? readNonEmptyString6(record2.session_id) ?? readNonEmptyString6(record2.sessionID); + if (!sessionId) return null; + const cwd = readNonEmptyString6(record2.cwd) ?? readNonEmptyString6(record2.workdir) ?? readNonEmptyString6(record2.folder); + const workspaceId = readNonEmptyString6(record2.workspaceId) ?? readNonEmptyString6(record2.workspace_id); + const repoUrl = readNonEmptyString6(record2.repoUrl) ?? readNonEmptyString6(record2.repo_url); + const repoRef = readNonEmptyString6(record2.repoRef) ?? readNonEmptyString6(record2.repo_ref); + return { + sessionId, + ...cwd ? { cwd } : {}, + ...workspaceId ? { workspaceId } : {}, + ...repoUrl ? { repoUrl } : {}, + ...repoRef ? { repoRef } : {} + }; + }, + serialize(params) { + if (!params) return null; + const sessionId = readNonEmptyString6(params.sessionId) ?? readNonEmptyString6(params.session_id) ?? readNonEmptyString6(params.sessionID); + if (!sessionId) return null; + const cwd = readNonEmptyString6(params.cwd) ?? readNonEmptyString6(params.workdir) ?? readNonEmptyString6(params.folder); + const workspaceId = readNonEmptyString6(params.workspaceId) ?? readNonEmptyString6(params.workspace_id); + const repoUrl = readNonEmptyString6(params.repoUrl) ?? readNonEmptyString6(params.repo_url); + const repoRef = readNonEmptyString6(params.repoRef) ?? readNonEmptyString6(params.repo_ref); + return { + sessionId, + ...cwd ? { cwd } : {}, + ...workspaceId ? { workspaceId } : {}, + ...repoUrl ? { repoUrl } : {}, + ...repoRef ? { repoRef } : {} + }; + }, + getDisplayId(params) { + if (!params) return null; + return readNonEmptyString6(params.sessionId) ?? readNonEmptyString6(params.session_id) ?? readNonEmptyString6(params.sessionID); + } +}; + +// packages/adapters/opencode-local/src/index.ts +var DEFAULT_OPENCODE_LOCAL_MODEL = "openai/gpt-5.2-codex"; +var models5 = [ + { id: DEFAULT_OPENCODE_LOCAL_MODEL, label: DEFAULT_OPENCODE_LOCAL_MODEL }, + { id: "openai/gpt-5.4", label: "openai/gpt-5.4" }, + { id: "openai/gpt-5.2", label: "openai/gpt-5.2" }, + { id: "openai/gpt-5.1-codex-max", label: "openai/gpt-5.1-codex-max" }, + { id: "openai/gpt-5.1-codex-mini", label: "openai/gpt-5.1-codex-mini" } +]; +var agentConfigurationDoc5 = `# opencode_local agent configuration + +Adapter: opencode_local + +Use when: +- You want Taskcore to run OpenCode locally as the agent runtime +- You want provider/model routing in OpenCode format (provider/model) +- You want OpenCode session resume across heartbeats via --session + +Don't use when: +- You need webhook-style external invocation (use openclaw_gateway or http) +- You only need one-shot shell commands (use process) +- OpenCode CLI is not installed on the machine + +Core fields: +- cwd (string, optional): default absolute working directory fallback for the agent process (created if missing when possible) +- instructionsFilePath (string, optional): absolute path to a markdown instructions file prepended to the run prompt +- model (string, required): OpenCode model id in provider/model format (for example anthropic/claude-sonnet-4-5) +- variant (string, optional): provider-specific reasoning/profile variant passed as --variant (for example minimal|low|medium|high|xhigh|max) +- dangerouslySkipPermissions (boolean, optional): inject a runtime OpenCode config that allows \`external_directory\` access without interactive prompts; defaults to true for unattended Taskcore runs +- promptTemplate (string, optional): run prompt template +- command (string, optional): defaults to "opencode" +- extraArgs (string[], optional): additional CLI args +- env (object, optional): KEY=VALUE environment variables + +Operational fields: +- timeoutSec (number, optional): run timeout in seconds +- graceSec (number, optional): SIGTERM grace period in seconds + +Notes: +- OpenCode supports multiple providers and models. Use \`opencode models\` to list available options in provider/model format. +- Taskcore requires an explicit \`model\` value for \`opencode_local\` agents. +- Runs are executed with: opencode run --format json ... +- Sessions are resumed with --session when stored session cwd matches current cwd. +- The adapter sets OPENCODE_DISABLE_PROJECT_CONFIG=true to prevent OpenCode from writing an opencode.json config file into the project working directory. Model selection is passed via the --model CLI flag instead. +- When \`dangerouslySkipPermissions\` is enabled, Taskcore injects a temporary runtime config with \`permission.external_directory=allow\` so headless runs do not stall on approval prompts. +`; + +// packages/adapters/openclaw-gateway/src/server/execute.ts +import crypto3, { randomUUID } from "node:crypto"; + +// node_modules/.pnpm/ws@8.20.0/node_modules/ws/wrapper.mjs +var import_stream5 = __toESM(require_stream(), 1); +var import_extension = __toESM(require_extension(), 1); +var import_permessage_deflate = __toESM(require_permessage_deflate(), 1); +var import_receiver = __toESM(require_receiver(), 1); +var import_sender = __toESM(require_sender(), 1); +var import_subprotocol = __toESM(require_subprotocol(), 1); +var import_websocket = __toESM(require_websocket(), 1); +var import_websocket_server = __toESM(require_websocket_server(), 1); + +// packages/adapters/openclaw-gateway/src/server/execute.ts +var PROTOCOL_VERSION = 3; +var DEFAULT_SCOPES = ["operator.admin"]; +var DEFAULT_CLIENT_ID = "gateway-client"; +var DEFAULT_CLIENT_MODE = "backend"; +var DEFAULT_CLIENT_VERSION = "taskcore"; +var DEFAULT_ROLE = "operator"; +var SENSITIVE_LOG_KEY_PATTERN = /(^|[_-])(auth|authorization|token|secret|password|api[_-]?key|private[_-]?key)([_-]|$)|^x-openclaw-(auth|token)$/i; +var ED25519_SPKI_PREFIX = Buffer.from("302a300506032b6570032100", "hex"); +function asRecord4(value) { + if (typeof value !== "object" || value === null || Array.isArray(value)) return null; + return value; +} +function nonEmpty3(value) { + return typeof value === "string" && value.trim().length > 0 ? value.trim() : null; +} +function parseOptionalPositiveInteger(value) { + if (typeof value === "number" && Number.isFinite(value)) { + return Math.max(1, Math.floor(value)); + } + if (typeof value === "string" && value.trim().length > 0) { + const parsed = Number.parseInt(value.trim(), 10); + if (Number.isFinite(parsed)) return Math.max(1, Math.floor(parsed)); + } + return null; +} +function parseBoolean(value, fallback = false) { + if (typeof value === "boolean") return value; + if (typeof value === "string") { + const normalized = value.trim().toLowerCase(); + if (normalized === "true" || normalized === "1") return true; + if (normalized === "false" || normalized === "0") return false; + } + return fallback; +} +function normalizeSessionKeyStrategy(value) { + const normalized = asString(value, "issue").trim().toLowerCase(); + if (normalized === "fixed" || normalized === "run") return normalized; + return "issue"; +} +function prefixSessionKeyForAgent(sessionKey, agentId) { + if (!agentId || sessionKey.startsWith("agent:")) return sessionKey; + return `agent:${agentId}:${sessionKey}`; +} +function resolveSessionKey(input) { + const fallback = input.configuredSessionKey ?? "taskcore"; + if (input.strategy === "run") { + return prefixSessionKeyForAgent(`taskcore:run:${input.runId}`, input.agentId); + } + if (input.strategy === "issue" && input.issueId) { + return prefixSessionKeyForAgent(`taskcore:issue:${input.issueId}`, input.agentId); + } + return prefixSessionKeyForAgent(fallback, input.agentId); +} +function isLoopbackHost2(hostname3) { + const value = hostname3.trim().toLowerCase(); + return value === "localhost" || value === "127.0.0.1" || value === "::1"; +} +function toStringRecord(value) { + const parsed = parseObject(value); + const out = {}; + for (const [key, entry] of Object.entries(parsed)) { + if (typeof entry === "string") out[key] = entry; + } + return out; +} +function toStringArray(value) { + if (Array.isArray(value)) { + return value.filter((entry) => typeof entry === "string").map((entry) => entry.trim()).filter(Boolean); + } + if (typeof value === "string") { + return value.split(",").map((entry) => entry.trim()).filter(Boolean); + } + return []; +} +function normalizeScopes(value) { + const parsed = toStringArray(value); + return parsed.length > 0 ? parsed : [...DEFAULT_SCOPES]; +} +function uniqueScopes(scopes) { + return Array.from(new Set(scopes.map((scope) => scope.trim()).filter(Boolean))); +} +function headerMapGetIgnoreCase(headers, key) { + const match = Object.entries(headers).find(([entryKey]) => entryKey.toLowerCase() === key.toLowerCase()); + return match ? match[1] : null; +} +function headerMapHasIgnoreCase(headers, key) { + return Object.keys(headers).some((entryKey) => entryKey.toLowerCase() === key.toLowerCase()); +} +function getGatewayErrorDetails(err) { + if (!err || typeof err !== "object") return null; + const candidate = err.gatewayDetails; + return asRecord4(candidate); +} +function extractPairingRequestId(err) { + const details = getGatewayErrorDetails(err); + const fromDetails = nonEmpty3(details?.requestId); + if (fromDetails) return fromDetails; + const message2 = err instanceof Error ? err.message : String(err); + const match = message2.match(/requestId\s*[:=]\s*([A-Za-z0-9_-]+)/i); + return match?.[1] ?? null; +} +function toAuthorizationHeaderValue(rawToken) { + const trimmed = rawToken.trim(); + if (!trimmed) return trimmed; + return /^bearer\s+/i.test(trimmed) ? trimmed : `Bearer ${trimmed}`; +} +function tokenFromAuthHeader(rawHeader) { + if (!rawHeader) return null; + const trimmed = rawHeader.trim(); + if (!trimmed) return null; + const match = trimmed.match(/^bearer\s+(.+)$/i); + return match ? nonEmpty3(match[1]) : trimmed; +} +function resolveAuthToken(config3, headers) { + const explicit = nonEmpty3(config3.authToken) ?? nonEmpty3(config3.token); + if (explicit) return explicit; + const tokenHeader = headerMapGetIgnoreCase(headers, "x-openclaw-token"); + if (nonEmpty3(tokenHeader)) return nonEmpty3(tokenHeader); + const authHeader = headerMapGetIgnoreCase(headers, "x-openclaw-auth") ?? headerMapGetIgnoreCase(headers, "authorization"); + return tokenFromAuthHeader(authHeader); +} +function isSensitiveLogKey(key) { + return SENSITIVE_LOG_KEY_PATTERN.test(key.trim()); +} +function sha256Prefix(value) { + return crypto3.createHash("sha256").update(value).digest("hex").slice(0, 12); +} +function redactSecretForLog(value) { + return `[redacted len=${value.length} sha256=${sha256Prefix(value)}]`; +} +function truncateForLog(value, maxChars = 320) { + if (value.length <= maxChars) return value; + return `${value.slice(0, maxChars)}... [truncated ${value.length - maxChars} chars]`; +} +function redactForLog(value, keyPath = [], depth = 0) { + const currentKey = keyPath[keyPath.length - 1] ?? ""; + if (typeof value === "string") { + if (isSensitiveLogKey(currentKey)) return redactSecretForLog(value); + return truncateForLog(value); + } + if (typeof value === "number" || typeof value === "boolean" || value == null) { + return value; + } + if (Array.isArray(value)) { + if (depth >= 6) return "[array-truncated]"; + const out = value.slice(0, 20).map((entry, index2) => redactForLog(entry, [...keyPath, `${index2}`], depth + 1)); + if (value.length > 20) out.push(`[+${value.length - 20} more items]`); + return out; + } + if (typeof value === "object") { + if (depth >= 6) return "[object-truncated]"; + const entries2 = Object.entries(value); + const out = {}; + for (const [key, entry] of entries2.slice(0, 80)) { + out[key] = redactForLog(entry, [...keyPath, key], depth + 1); + } + if (entries2.length > 80) { + out.__truncated__ = `+${entries2.length - 80} keys`; + } + return out; + } + return String(value); +} +function stringifyForLog(value, maxChars) { + const text3 = JSON.stringify(value); + if (text3.length <= maxChars) return text3; + return `${text3.slice(0, maxChars)}... [truncated ${text3.length - maxChars} chars]`; +} +function buildWakePayload(ctx) { + const { runId, agent, context } = ctx; + return { + runId, + agentId: agent.id, + companyId: agent.companyId, + taskId: nonEmpty3(context.taskId) ?? nonEmpty3(context.issueId), + issueId: nonEmpty3(context.issueId), + wakeReason: nonEmpty3(context.wakeReason), + wakeCommentId: nonEmpty3(context.wakeCommentId) ?? nonEmpty3(context.commentId), + approvalId: nonEmpty3(context.approvalId), + approvalStatus: nonEmpty3(context.approvalStatus), + issueIds: Array.isArray(context.issueIds) ? context.issueIds.filter( + (value) => typeof value === "string" && value.trim().length > 0 + ) : [] + }; +} +function resolveTaskcoreApiUrlOverride(value) { + const raw = nonEmpty3(value); + if (!raw) return null; + try { + const parsed = new URL(raw); + if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return null; + return parsed.toString(); + } catch { + return null; + } +} +function buildTaskcoreEnvForWake(ctx, wakePayload) { + const taskcoreApiUrlOverride = resolveTaskcoreApiUrlOverride(ctx.config.taskcoreApiUrl); + const taskcoreEnv = { + ...buildTaskcoreEnv(ctx.agent), + TASKCORE_RUN_ID: ctx.runId + }; + if (taskcoreApiUrlOverride) { + taskcoreEnv.TASKCORE_API_URL = taskcoreApiUrlOverride; + } + if (wakePayload.taskId) taskcoreEnv.TASKCORE_TASK_ID = wakePayload.taskId; + if (wakePayload.wakeReason) taskcoreEnv.TASKCORE_WAKE_REASON = wakePayload.wakeReason; + if (wakePayload.wakeCommentId) taskcoreEnv.TASKCORE_WAKE_COMMENT_ID = wakePayload.wakeCommentId; + if (wakePayload.approvalId) taskcoreEnv.TASKCORE_APPROVAL_ID = wakePayload.approvalId; + if (wakePayload.approvalStatus) taskcoreEnv.TASKCORE_APPROVAL_STATUS = wakePayload.approvalStatus; + if (wakePayload.issueIds.length > 0) { + taskcoreEnv.TASKCORE_LINKED_ISSUE_IDS = wakePayload.issueIds.join(","); + } + return taskcoreEnv; +} +function buildWakeText(payload2, taskcoreEnv, structuredWakePrompt) { + const claimedApiKeyPath = "~/.openclaw/workspace/taskcore-claimed-api-key.json"; + const orderedKeys = [ + "TASKCORE_RUN_ID", + "TASKCORE_AGENT_ID", + "TASKCORE_COMPANY_ID", + "TASKCORE_API_URL", + "TASKCORE_TASK_ID", + "TASKCORE_WAKE_REASON", + "TASKCORE_WAKE_COMMENT_ID", + "TASKCORE_APPROVAL_ID", + "TASKCORE_APPROVAL_STATUS", + "TASKCORE_LINKED_ISSUE_IDS" + ]; + const envLines = []; + for (const key of orderedKeys) { + const value = taskcoreEnv[key]; + if (!value) continue; + envLines.push(`${key}=${value}`); + } + const issueIdHint = payload2.taskId ?? payload2.issueId ?? ""; + const apiBaseHint = taskcoreEnv.TASKCORE_API_URL ?? ""; + const lines = [ + "Taskcore wake event for a cloud adapter.", + "", + "Run this procedure now. Do not guess undocumented endpoints and do not ask for additional heartbeat docs.", + "", + "Set these values in your run context:", + ...envLines, + `TASKCORE_API_KEY=`, + "", + `Load TASKCORE_API_KEY from ${claimedApiKeyPath} (the token you saved after claim-api-key).`, + "", + `api_base=${apiBaseHint}`, + `task_id=${payload2.taskId ?? ""}`, + `issue_id=${payload2.issueId ?? ""}`, + `wake_reason=${payload2.wakeReason ?? ""}`, + `wake_comment_id=${payload2.wakeCommentId ?? ""}`, + `approval_id=${payload2.approvalId ?? ""}`, + `approval_status=${payload2.approvalStatus ?? ""}`, + `linked_issue_ids=${payload2.issueIds.join(",")}`, + "", + "HTTP rules:", + "- Use Authorization: Bearer $TASKCORE_API_KEY on every API call.", + "- Use X-Taskcore-Run-Id: $TASKCORE_RUN_ID on every mutating API call.", + "- Use only /api endpoints listed below.", + "- Do NOT call guessed endpoints like /api/cloud-adapter/*, /api/cloud-adapters/*, /api/adapters/cloud/*, or /api/heartbeat.", + "", + "Workflow:", + "1) GET /api/agents/me", + `2) Determine issueId: TASKCORE_TASK_ID if present, otherwise issue_id (${issueIdHint}).`, + "3) If issueId exists:", + ' - POST /api/issues/{issueId}/checkout with {"agentId":"$TASKCORE_AGENT_ID","expectedStatuses":["todo","backlog","blocked","in_review"]}', + " - GET /api/issues/{issueId}", + " - GET /api/issues/{issueId}/comments", + " - Execute the issue instructions exactly.", + ' - If instructions require a comment, POST /api/issues/{issueId}/comments with {"body":"..."}.', + ' - PATCH /api/issues/{issueId} with {"status":"done","comment":"what changed and why"}.', + "4) If issueId does not exist:", + " - GET /api/companies/$TASKCORE_COMPANY_ID/issues?assigneeAgentId=$TASKCORE_AGENT_ID&status=todo,in_progress,in_review,blocked", + " - Pick in_progress first, then in_review when you were woken by a comment, then todo, then blocked, then execute step 3.", + "", + "Useful endpoints for issue work:", + "- POST /api/issues/{issueId}/comments", + "- PATCH /api/issues/{issueId}", + "- POST /api/companies/{companyId}/issues (when asked to create a new issue)", + ...structuredWakePrompt ? [ + "", + structuredWakePrompt + ] : [], + "", + "Complete the workflow in this run." + ]; + return lines.join("\n"); +} +function appendWakeText(baseText, wakeText) { + const trimmedBase = baseText.trim(); + return trimmedBase.length > 0 ? `${trimmedBase} + +${wakeText}` : wakeText; +} +function joinWakePayloadSections(structuredWakePrompt, structuredWakeJson) { + const sections = [ + structuredWakePrompt.trim(), + "Structured wake payload JSON:", + "```json", + structuredWakeJson, + "```" + ].filter((entry) => entry.trim().length > 0); + return sections.join("\n"); +} +function buildStandardTaskcorePayload(ctx, wakePayload, taskcoreEnv, payloadTemplate) { + const templateTaskcore = parseObject(payloadTemplate.taskcore); + const workspace = asRecord4(ctx.context.taskcoreWorkspace); + const workspaces = Array.isArray(ctx.context.taskcoreWorkspaces) ? ctx.context.taskcoreWorkspaces.filter((entry) => Boolean(asRecord4(entry))) : []; + const configuredWorkspaceRuntime = parseObject(ctx.config.workspaceRuntime); + const runtimeServiceIntents = Array.isArray(ctx.context.taskcoreRuntimeServiceIntents) ? ctx.context.taskcoreRuntimeServiceIntents.filter( + (entry) => Boolean(asRecord4(entry)) + ) : []; + const standardTaskcore = { + runId: ctx.runId, + companyId: ctx.agent.companyId, + agentId: ctx.agent.id, + agentName: ctx.agent.name, + taskId: wakePayload.taskId, + issueId: wakePayload.issueId, + issueIds: wakePayload.issueIds, + wakeReason: wakePayload.wakeReason, + wakeCommentId: wakePayload.wakeCommentId, + approvalId: wakePayload.approvalId, + approvalStatus: wakePayload.approvalStatus, + apiUrl: taskcoreEnv.TASKCORE_API_URL ?? null + }; + const structuredWake = parseObject(ctx.context.taskcoreWake); + if (Object.keys(structuredWake).length > 0) { + standardTaskcore.wake = structuredWake; + } + if (workspace) { + standardTaskcore.workspace = workspace; + } + if (workspaces.length > 0) { + standardTaskcore.workspaces = workspaces; + } + if (runtimeServiceIntents.length > 0 || Object.keys(configuredWorkspaceRuntime).length > 0) { + standardTaskcore.workspaceRuntime = { + ...configuredWorkspaceRuntime, + ...runtimeServiceIntents.length > 0 ? { services: runtimeServiceIntents } : {} + }; + } + return { + ...templateTaskcore, + ...standardTaskcore + }; +} +function normalizeUrl(input) { + try { + return new URL(input); + } catch { + return null; + } +} +function rawDataToString(data2) { + if (typeof data2 === "string") return data2; + if (Buffer.isBuffer(data2)) return data2.toString("utf8"); + if (data2 instanceof ArrayBuffer) return Buffer.from(data2).toString("utf8"); + if (Array.isArray(data2)) { + return Buffer.concat( + data2.map((entry) => Buffer.isBuffer(entry) ? entry : Buffer.from(String(entry), "utf8")) + ).toString("utf8"); + } + return String(data2 ?? ""); +} +function withTimeout(promise2, timeoutMs, message2) { + if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) return promise2; + return new Promise((resolve4, reject) => { + const timer2 = setTimeout(() => reject(new Error(message2)), timeoutMs); + promise2.then((value) => { + clearTimeout(timer2); + resolve4(value); + }).catch((err) => { + clearTimeout(timer2); + reject(err); + }); + }); +} +function derivePublicKeyRaw(publicKeyPem) { + const key = crypto3.createPublicKey(publicKeyPem); + const spki = key.export({ type: "spki", format: "der" }); + if (spki.length === ED25519_SPKI_PREFIX.length + 32 && spki.subarray(0, ED25519_SPKI_PREFIX.length).equals(ED25519_SPKI_PREFIX)) { + return spki.subarray(ED25519_SPKI_PREFIX.length); + } + return spki; +} +function base64UrlEncode2(buf) { + return buf.toString("base64").replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/g, ""); +} +function signDevicePayload(privateKeyPem, payload2) { + const key = crypto3.createPrivateKey(privateKeyPem); + const sig = crypto3.sign(null, Buffer.from(payload2, "utf8"), key); + return base64UrlEncode2(sig); +} +function buildDeviceAuthPayloadV3(params) { + const scopes = params.scopes.join(","); + const token = params.token ?? ""; + const platform = params.platform?.trim() ?? ""; + const deviceFamily = params.deviceFamily?.trim() ?? ""; + return [ + "v3", + params.deviceId, + params.clientId, + params.clientMode, + params.role, + scopes, + String(params.signedAtMs), + token, + params.nonce, + platform, + deviceFamily + ].join("|"); +} +function resolveDeviceIdentity(config3) { + const configuredPrivateKey = nonEmpty3(config3.devicePrivateKeyPem); + if (configuredPrivateKey) { + const privateKey = crypto3.createPrivateKey(configuredPrivateKey); + const publicKey = crypto3.createPublicKey(privateKey); + const publicKeyPem2 = publicKey.export({ type: "spki", format: "pem" }).toString(); + const raw2 = derivePublicKeyRaw(publicKeyPem2); + return { + deviceId: crypto3.createHash("sha256").update(raw2).digest("hex"), + publicKeyRawBase64Url: base64UrlEncode2(raw2), + privateKeyPem: configuredPrivateKey, + source: "configured" + }; + } + const generated = crypto3.generateKeyPairSync("ed25519"); + const publicKeyPem = generated.publicKey.export({ type: "spki", format: "pem" }).toString(); + const privateKeyPem = generated.privateKey.export({ type: "pkcs8", format: "pem" }).toString(); + const raw = derivePublicKeyRaw(publicKeyPem); + return { + deviceId: crypto3.createHash("sha256").update(raw).digest("hex"), + publicKeyRawBase64Url: base64UrlEncode2(raw), + privateKeyPem, + source: "ephemeral" + }; +} +function isResponseFrame(value) { + const record2 = asRecord4(value); + return Boolean(record2 && record2.type === "res" && typeof record2.id === "string" && typeof record2.ok === "boolean"); +} +function isEventFrame(value) { + const record2 = asRecord4(value); + return Boolean(record2 && record2.type === "event" && typeof record2.event === "string"); +} +var GatewayWsClient = class { + constructor(opts) { + this.opts = opts; + this.challengePromise = new Promise((resolve4, reject) => { + this.resolveChallenge = resolve4; + this.rejectChallenge = reject; + }); + this.challengePromise.catch(() => { + }); + } + opts; + ws = null; + pending = /* @__PURE__ */ new Map(); + challengePromise; + resolveChallenge; + rejectChallenge; + async connect(buildConnectParams, timeoutMs) { + this.ws = new import_websocket.default(this.opts.url, { + headers: this.opts.headers, + maxPayload: 25 * 1024 * 1024 + }); + const ws = this.ws; + ws.on("message", (data2) => { + this.handleMessage(rawDataToString(data2)); + }); + ws.on("close", (code, reason) => { + const reasonText = rawDataToString(reason); + const err = new Error(`gateway closed (${code}): ${reasonText}`); + this.failPending(err); + this.rejectChallenge(err); + }); + ws.on("error", (err) => { + const message2 = err instanceof Error ? err.message : String(err); + void this.opts.onLog("stderr", `[openclaw-gateway] websocket error: ${message2} +`); + }); + await withTimeout( + new Promise((resolve4, reject) => { + const onOpen = () => { + cleanup(); + resolve4(); + }; + const onError = (err) => { + cleanup(); + reject(err); + }; + const onClose = (code, reason) => { + cleanup(); + reject(new Error(`gateway closed before open (${code}): ${rawDataToString(reason)}`)); + }; + const cleanup = () => { + ws.off("open", onOpen); + ws.off("error", onError); + ws.off("close", onClose); + }; + ws.once("open", onOpen); + ws.once("error", onError); + ws.once("close", onClose); + }), + timeoutMs, + "gateway websocket open timeout" + ); + const nonce = await withTimeout(this.challengePromise, timeoutMs, "gateway connect challenge timeout"); + const signedConnectParams = buildConnectParams(nonce); + const hello = await this.request("connect", signedConnectParams, { + timeoutMs + }); + return hello; + } + async request(method, params, opts) { + if (!this.ws || this.ws.readyState !== import_websocket.default.OPEN) { + throw new Error("gateway not connected"); + } + const id = randomUUID(); + const frame = { + type: "req", + id, + method, + params + }; + const payload2 = JSON.stringify(frame); + const requestPromise = new Promise((resolve4, reject) => { + const timer2 = opts.timeoutMs > 0 ? setTimeout(() => { + this.pending.delete(id); + reject(new Error(`gateway request timeout (${method})`)); + }, opts.timeoutMs) : null; + this.pending.set(id, { + resolve: (value) => resolve4(value), + reject, + expectFinal: opts.expectFinal === true, + timer: timer2 + }); + }); + this.ws.send(payload2); + return requestPromise; + } + close() { + if (!this.ws) return; + this.ws.close(1e3, "taskcore-complete"); + this.ws = null; + } + failPending(err) { + for (const [, pending] of this.pending) { + if (pending.timer) clearTimeout(pending.timer); + pending.reject(err); + } + this.pending.clear(); + } + handleMessage(raw) { + let parsed; + try { + parsed = JSON.parse(raw); + } catch { + return; + } + if (isEventFrame(parsed)) { + if (parsed.event === "connect.challenge") { + const payload3 = asRecord4(parsed.payload); + const nonce = nonEmpty3(payload3?.nonce); + if (nonce) { + this.resolveChallenge(nonce); + return; + } + } + void Promise.resolve(this.opts.onEvent(parsed)).catch(() => { + }); + return; + } + if (!isResponseFrame(parsed)) return; + const pending = this.pending.get(parsed.id); + if (!pending) return; + const payload2 = asRecord4(parsed.payload); + const status = nonEmpty3(payload2?.status)?.toLowerCase(); + if (pending.expectFinal && status === "accepted") { + return; + } + if (pending.timer) clearTimeout(pending.timer); + this.pending.delete(parsed.id); + if (parsed.ok) { + pending.resolve(parsed.payload ?? null); + return; + } + const errorRecord = asRecord4(parsed.error); + const message2 = nonEmpty3(errorRecord?.message) ?? nonEmpty3(errorRecord?.code) ?? "gateway request failed"; + const err = new Error(message2); + const code = nonEmpty3(errorRecord?.code); + const details = asRecord4(errorRecord?.details); + if (code) err.gatewayCode = code; + if (details) err.gatewayDetails = details; + pending.reject(err); + } +}; +async function autoApproveDevicePairing(params) { + if (!params.authToken && !params.password) { + return { ok: false, reason: "shared auth token/password is missing" }; + } + const approvalScopes = uniqueScopes([...params.scopes, "operator.pairing"]); + const client2 = new GatewayWsClient({ + url: params.url, + headers: params.headers, + onEvent: () => { + }, + onLog: params.onLog + }); + try { + await params.onLog( + "stdout", + "[openclaw-gateway] pairing required; attempting automatic pairing approval via gateway methods\n" + ); + await client2.connect( + () => ({ + minProtocol: PROTOCOL_VERSION, + maxProtocol: PROTOCOL_VERSION, + client: { + id: params.clientId, + version: params.clientVersion, + platform: process.platform, + mode: params.clientMode + }, + role: params.role, + scopes: approvalScopes, + auth: { + ...params.authToken ? { token: params.authToken } : {}, + ...params.password ? { password: params.password } : {} + } + }), + params.connectTimeoutMs + ); + let requestId = params.requestId; + if (!requestId) { + const listPayload = await client2.request("device.pair.list", {}, { + timeoutMs: params.connectTimeoutMs + }); + const pending = Array.isArray(listPayload.pending) ? listPayload.pending : []; + const pendingRecords = pending.map((entry) => asRecord4(entry)).filter((entry) => Boolean(entry)); + const matching = (params.deviceId ? pendingRecords.find((entry) => nonEmpty3(entry.deviceId) === params.deviceId) : null) ?? pendingRecords[pendingRecords.length - 1]; + requestId = nonEmpty3(matching?.requestId); + } + if (!requestId) { + return { ok: false, reason: "no pending device pairing request found" }; + } + await client2.request( + "device.pair.approve", + { requestId }, + { + timeoutMs: params.connectTimeoutMs + } + ); + return { ok: true, requestId }; + } catch (err) { + return { ok: false, reason: err instanceof Error ? err.message : String(err) }; + } finally { + client2.close(); + } +} +function parseUsage(value) { + const record2 = asRecord4(value); + if (!record2) return void 0; + const inputTokens = asNumber(record2.inputTokens ?? record2.input, 0); + const outputTokens = asNumber(record2.outputTokens ?? record2.output, 0); + const cachedInputTokens = asNumber( + record2.cachedInputTokens ?? record2.cached_input_tokens ?? record2.cacheRead ?? record2.cache_read, + 0 + ); + if (inputTokens <= 0 && outputTokens <= 0 && cachedInputTokens <= 0) { + return void 0; + } + return { + inputTokens, + outputTokens, + ...cachedInputTokens > 0 ? { cachedInputTokens } : {} + }; +} +function extractRuntimeServicesFromMeta(meta3) { + if (!meta3) return []; + const reports = []; + const runtimeServices = Array.isArray(meta3.runtimeServices) ? meta3.runtimeServices.filter((entry) => Boolean(asRecord4(entry))) : []; + for (const entry of runtimeServices) { + const serviceName = nonEmpty3(entry.serviceName) ?? nonEmpty3(entry.name); + if (!serviceName) continue; + const rawStatus = nonEmpty3(entry.status)?.toLowerCase(); + const status = rawStatus === "starting" || rawStatus === "running" || rawStatus === "stopped" || rawStatus === "failed" ? rawStatus : "running"; + const rawLifecycle = nonEmpty3(entry.lifecycle)?.toLowerCase(); + const lifecycle = rawLifecycle === "shared" ? "shared" : "ephemeral"; + const rawScopeType = nonEmpty3(entry.scopeType)?.toLowerCase(); + const scopeType = rawScopeType === "project_workspace" || rawScopeType === "execution_workspace" || rawScopeType === "agent" ? rawScopeType : "run"; + const rawHealth = nonEmpty3(entry.healthStatus)?.toLowerCase(); + const healthStatus = rawHealth === "healthy" || rawHealth === "unhealthy" || rawHealth === "unknown" ? rawHealth : status === "running" ? "healthy" : "unknown"; + reports.push({ + id: nonEmpty3(entry.id), + projectId: nonEmpty3(entry.projectId), + projectWorkspaceId: nonEmpty3(entry.projectWorkspaceId), + issueId: nonEmpty3(entry.issueId), + scopeType, + scopeId: nonEmpty3(entry.scopeId), + serviceName, + status, + lifecycle, + reuseKey: nonEmpty3(entry.reuseKey), + command: nonEmpty3(entry.command), + cwd: nonEmpty3(entry.cwd), + port: parseOptionalPositiveInteger(entry.port), + url: nonEmpty3(entry.url), + providerRef: nonEmpty3(entry.providerRef) ?? nonEmpty3(entry.previewId), + ownerAgentId: nonEmpty3(entry.ownerAgentId), + stopPolicy: asRecord4(entry.stopPolicy), + healthStatus + }); + } + const previewUrl = nonEmpty3(meta3.previewUrl); + if (previewUrl) { + reports.push({ + serviceName: "preview", + status: "running", + lifecycle: "ephemeral", + scopeType: "run", + url: previewUrl, + providerRef: nonEmpty3(meta3.previewId) ?? previewUrl, + healthStatus: "healthy" + }); + } + const previewUrls = Array.isArray(meta3.previewUrls) ? meta3.previewUrls.filter((entry) => typeof entry === "string" && entry.trim().length > 0) : []; + previewUrls.forEach((url2, index2) => { + reports.push({ + serviceName: index2 === 0 ? "preview" : `preview-${index2 + 1}`, + status: "running", + lifecycle: "ephemeral", + scopeType: "run", + url: url2, + providerRef: `${url2}#${index2}`, + healthStatus: "healthy" + }); + }); + return reports; +} +function extractResultText(value) { + const record2 = asRecord4(value); + if (!record2) return null; + const payloads = Array.isArray(record2.payloads) ? record2.payloads : []; + const texts = payloads.map((entry) => { + const payload2 = asRecord4(entry); + return nonEmpty3(payload2?.text); + }).filter((entry) => Boolean(entry)); + if (texts.length > 0) return texts.join("\n\n"); + return nonEmpty3(record2.text) ?? nonEmpty3(record2.summary) ?? null; +} +async function execute6(ctx) { + const urlValue = asString(ctx.config.url, "").trim(); + if (!urlValue) { + return { + exitCode: 1, + signal: null, + timedOut: false, + errorMessage: "OpenClaw gateway adapter missing url", + errorCode: "openclaw_gateway_url_missing" + }; + } + const parsedUrl = normalizeUrl(urlValue); + if (!parsedUrl) { + return { + exitCode: 1, + signal: null, + timedOut: false, + errorMessage: `Invalid gateway URL: ${urlValue}`, + errorCode: "openclaw_gateway_url_invalid" + }; + } + if (parsedUrl.protocol !== "ws:" && parsedUrl.protocol !== "wss:") { + return { + exitCode: 1, + signal: null, + timedOut: false, + errorMessage: `Unsupported gateway URL protocol: ${parsedUrl.protocol}`, + errorCode: "openclaw_gateway_url_protocol" + }; + } + const timeoutSec = Math.max(0, Math.floor(asNumber(ctx.config.timeoutSec, 120))); + const timeoutMs = timeoutSec > 0 ? timeoutSec * 1e3 : 0; + const connectTimeoutMs = timeoutMs > 0 ? Math.min(timeoutMs, 15e3) : 1e4; + const waitTimeoutMs = parseOptionalPositiveInteger(ctx.config.waitTimeoutMs) ?? (timeoutMs > 0 ? timeoutMs : 3e4); + const payloadTemplate = parseObject(ctx.config.payloadTemplate); + const transportHint = nonEmpty3(ctx.config.streamTransport) ?? nonEmpty3(ctx.config.transport); + const headers = toStringRecord(ctx.config.headers); + const authToken = resolveAuthToken(parseObject(ctx.config), headers); + const password = nonEmpty3(ctx.config.password); + const deviceToken = nonEmpty3(ctx.config.deviceToken); + if (authToken && !headerMapHasIgnoreCase(headers, "authorization")) { + headers.authorization = toAuthorizationHeaderValue(authToken); + } + const clientId = nonEmpty3(ctx.config.clientId) ?? DEFAULT_CLIENT_ID; + const clientMode = nonEmpty3(ctx.config.clientMode) ?? DEFAULT_CLIENT_MODE; + const clientVersion = nonEmpty3(ctx.config.clientVersion) ?? DEFAULT_CLIENT_VERSION; + const role = nonEmpty3(ctx.config.role) ?? DEFAULT_ROLE; + const scopes = normalizeScopes(ctx.config.scopes); + const deviceFamily = nonEmpty3(ctx.config.deviceFamily); + const disableDeviceAuth = parseBoolean(ctx.config.disableDeviceAuth, false); + const wakePayload = buildWakePayload(ctx); + const taskcoreEnv = buildTaskcoreEnvForWake(ctx, wakePayload); + const structuredWakePrompt = renderTaskcoreWakePrompt(ctx.context.taskcoreWake); + const structuredWakeJson = stringifyTaskcoreWakePayload(ctx.context.taskcoreWake); + const wakeText = buildWakeText( + wakePayload, + taskcoreEnv, + structuredWakeJson ? joinWakePayloadSections(structuredWakePrompt, structuredWakeJson) : structuredWakePrompt + ); + const sessionKeyStrategy = normalizeSessionKeyStrategy(ctx.config.sessionKeyStrategy); + const configuredSessionKey = nonEmpty3(ctx.config.sessionKey); + const sessionKey = resolveSessionKey({ + strategy: sessionKeyStrategy, + configuredSessionKey, + agentId: nonEmpty3(ctx.config.agentId), + runId: ctx.runId, + issueId: wakePayload.issueId + }); + const templateMessage = nonEmpty3(payloadTemplate.message) ?? nonEmpty3(payloadTemplate.text); + const message2 = templateMessage ? appendWakeText(templateMessage, wakeText) : wakeText; + const taskcorePayload = buildStandardTaskcorePayload(ctx, wakePayload, taskcoreEnv, payloadTemplate); + const agentParams = { + ...payloadTemplate, + message: message2, + sessionKey, + idempotencyKey: ctx.runId + }; + delete agentParams.text; + agentParams.taskcore = taskcorePayload; + const configuredAgentId = nonEmpty3(ctx.config.agentId); + if (configuredAgentId && !nonEmpty3(agentParams.agentId)) { + agentParams.agentId = configuredAgentId; + } + if (typeof agentParams.timeout !== "number") { + agentParams.timeout = waitTimeoutMs; + } + if (ctx.onMeta) { + await ctx.onMeta({ + adapterType: "openclaw_gateway", + command: "gateway", + commandArgs: ["ws", parsedUrl.toString(), "agent"], + context: ctx.context + }); + } + const outboundHeaderKeys = Object.keys(headers).sort(); + await ctx.onLog( + "stdout", + `[openclaw-gateway] outbound headers (redacted): ${stringifyForLog(redactForLog(headers), 4e3)} +` + ); + await ctx.onLog( + "stdout", + `[openclaw-gateway] outbound payload (redacted): ${stringifyForLog(redactForLog(agentParams), 12e3)} +` + ); + await ctx.onLog("stdout", `[openclaw-gateway] outbound header keys: ${outboundHeaderKeys.join(", ")} +`); + if (transportHint) { + await ctx.onLog( + "stdout", + `[openclaw-gateway] ignoring streamTransport=${transportHint}; gateway adapter always uses websocket protocol +` + ); + } + if (parsedUrl.protocol === "ws:" && !isLoopbackHost2(parsedUrl.hostname)) { + await ctx.onLog( + "stdout", + "[openclaw-gateway] warning: using plaintext ws:// to a non-loopback host; prefer wss:// for remote endpoints\n" + ); + } + const autoPairOnFirstConnect = parseBoolean(ctx.config.autoPairOnFirstConnect, true); + let autoPairAttempted = false; + let latestResultPayload = null; + while (true) { + const trackedRunIds = /* @__PURE__ */ new Set([ctx.runId]); + const assistantChunks = []; + let lifecycleError = null; + let deviceIdentity = null; + const onEvent = async (frame) => { + if (frame.event !== "agent") { + if (frame.event === "shutdown") { + await ctx.onLog( + "stdout", + `[openclaw-gateway] gateway shutdown notice: ${stringifyForLog(frame.payload ?? {}, 2e3)} +` + ); + } + return; + } + const payload2 = asRecord4(frame.payload); + if (!payload2) return; + const runId = nonEmpty3(payload2.runId); + if (!runId || !trackedRunIds.has(runId)) return; + const stream = nonEmpty3(payload2.stream) ?? "unknown"; + const data2 = asRecord4(payload2.data) ?? {}; + await ctx.onLog( + "stdout", + `[openclaw-gateway:event] run=${runId} stream=${stream} data=${stringifyForLog(data2, 8e3)} +` + ); + if (stream === "assistant") { + const delta = nonEmpty3(data2.delta); + const text3 = nonEmpty3(data2.text); + if (delta) { + assistantChunks.push(delta); + } else if (text3) { + assistantChunks.push(text3); + } + return; + } + if (stream === "error") { + lifecycleError = nonEmpty3(data2.error) ?? nonEmpty3(data2.message) ?? lifecycleError; + return; + } + if (stream === "lifecycle") { + const phase = nonEmpty3(data2.phase)?.toLowerCase(); + if (phase === "error" || phase === "failed" || phase === "cancelled") { + lifecycleError = nonEmpty3(data2.error) ?? nonEmpty3(data2.message) ?? lifecycleError; + } + } + }; + const client2 = new GatewayWsClient({ + url: parsedUrl.toString(), + headers, + onEvent, + onLog: ctx.onLog + }); + try { + deviceIdentity = disableDeviceAuth ? null : resolveDeviceIdentity(parseObject(ctx.config)); + if (deviceIdentity) { + await ctx.onLog( + "stdout", + `[openclaw-gateway] device auth enabled keySource=${deviceIdentity.source} deviceId=${deviceIdentity.deviceId} +` + ); + } else { + await ctx.onLog("stdout", "[openclaw-gateway] device auth disabled\n"); + } + await ctx.onLog("stdout", `[openclaw-gateway] connecting to ${parsedUrl.toString()} +`); + const hello = await client2.connect((nonce) => { + const signedAtMs = Date.now(); + const connectParams = { + minProtocol: PROTOCOL_VERSION, + maxProtocol: PROTOCOL_VERSION, + client: { + id: clientId, + version: clientVersion, + platform: process.platform, + ...deviceFamily ? { deviceFamily } : {}, + mode: clientMode + }, + role, + scopes, + auth: authToken || password || deviceToken ? { + ...authToken ? { token: authToken } : {}, + ...deviceToken ? { deviceToken } : {}, + ...password ? { password } : {} + } : void 0 + }; + if (deviceIdentity) { + const payload2 = buildDeviceAuthPayloadV3({ + deviceId: deviceIdentity.deviceId, + clientId, + clientMode, + role, + scopes, + signedAtMs, + token: authToken, + nonce, + platform: process.platform, + deviceFamily + }); + connectParams.device = { + id: deviceIdentity.deviceId, + publicKey: deviceIdentity.publicKeyRawBase64Url, + signature: signDevicePayload(deviceIdentity.privateKeyPem, payload2), + signedAt: signedAtMs, + nonce + }; + } + return connectParams; + }, connectTimeoutMs); + await ctx.onLog( + "stdout", + `[openclaw-gateway] connected protocol=${asNumber(asRecord4(hello)?.protocol, PROTOCOL_VERSION)} +` + ); + const acceptedPayload = await client2.request("agent", agentParams, { + timeoutMs: connectTimeoutMs + }); + latestResultPayload = acceptedPayload; + const acceptedStatus = nonEmpty3(acceptedPayload?.status)?.toLowerCase() ?? ""; + const acceptedRunId = nonEmpty3(acceptedPayload?.runId) ?? ctx.runId; + trackedRunIds.add(acceptedRunId); + await ctx.onLog( + "stdout", + `[openclaw-gateway] agent accepted runId=${acceptedRunId} status=${acceptedStatus || "unknown"} +` + ); + if (acceptedStatus === "error") { + const errorMessage = nonEmpty3(acceptedPayload?.summary) ?? lifecycleError ?? "OpenClaw gateway agent request failed"; + return { + exitCode: 1, + signal: null, + timedOut: false, + errorMessage, + errorCode: "openclaw_gateway_agent_error", + resultJson: acceptedPayload + }; + } + if (acceptedStatus !== "ok") { + const waitPayload = await client2.request( + "agent.wait", + { runId: acceptedRunId, timeoutMs: waitTimeoutMs }, + { timeoutMs: waitTimeoutMs + connectTimeoutMs } + ); + latestResultPayload = waitPayload; + const waitStatus = nonEmpty3(waitPayload?.status)?.toLowerCase() ?? ""; + if (waitStatus === "timeout") { + return { + exitCode: 1, + signal: null, + timedOut: true, + errorMessage: `OpenClaw gateway run timed out after ${waitTimeoutMs}ms`, + errorCode: "openclaw_gateway_wait_timeout", + resultJson: waitPayload + }; + } + if (waitStatus === "error") { + return { + exitCode: 1, + signal: null, + timedOut: false, + errorMessage: nonEmpty3(waitPayload?.error) ?? lifecycleError ?? "OpenClaw gateway run failed", + errorCode: "openclaw_gateway_wait_error", + resultJson: waitPayload + }; + } + if (waitStatus && waitStatus !== "ok") { + return { + exitCode: 1, + signal: null, + timedOut: false, + errorMessage: `Unexpected OpenClaw gateway agent.wait status: ${waitStatus}`, + errorCode: "openclaw_gateway_wait_status_unexpected", + resultJson: waitPayload + }; + } + } + const summaryFromEvents = assistantChunks.join("").trim(); + const summaryFromPayload = extractResultText(asRecord4(acceptedPayload?.result)) ?? extractResultText(acceptedPayload) ?? extractResultText(asRecord4(latestResultPayload)) ?? null; + const summary = summaryFromEvents || summaryFromPayload || null; + const acceptedResult = asRecord4(acceptedPayload?.result); + const latestPayload = asRecord4(latestResultPayload); + const latestResult = asRecord4(latestPayload?.result); + const acceptedMeta = asRecord4(acceptedResult?.meta) ?? asRecord4(acceptedPayload?.meta); + const latestMeta = asRecord4(latestResult?.meta) ?? asRecord4(latestPayload?.meta); + const mergedMeta = { + ...acceptedMeta ?? {}, + ...latestMeta ?? {} + }; + const agentMeta = asRecord4(mergedMeta.agentMeta) ?? asRecord4(acceptedMeta?.agentMeta) ?? asRecord4(latestMeta?.agentMeta); + const usage = parseUsage(agentMeta?.usage ?? mergedMeta.usage); + const runtimeServices = extractRuntimeServicesFromMeta(agentMeta ?? mergedMeta); + const provider = nonEmpty3(agentMeta?.provider) ?? nonEmpty3(mergedMeta.provider) ?? "openclaw"; + const model = nonEmpty3(agentMeta?.model) ?? nonEmpty3(mergedMeta.model) ?? null; + const costUsd = asNumber(agentMeta?.costUsd ?? mergedMeta.costUsd, 0); + await ctx.onLog( + "stdout", + `[openclaw-gateway] run completed runId=${Array.from(trackedRunIds).join(",")} status=ok +` + ); + return { + exitCode: 0, + signal: null, + timedOut: false, + provider, + ...model ? { model } : {}, + ...usage ? { usage } : {}, + ...costUsd > 0 ? { costUsd } : {}, + resultJson: asRecord4(latestResultPayload), + ...runtimeServices.length > 0 ? { runtimeServices } : {}, + ...summary ? { summary } : {} + }; + } catch (err) { + const message3 = err instanceof Error ? err.message : String(err); + const lower = message3.toLowerCase(); + const timedOut = lower.includes("timeout"); + const pairingRequired = lower.includes("pairing required"); + if (pairingRequired && !disableDeviceAuth && autoPairOnFirstConnect && !autoPairAttempted && (authToken || password)) { + autoPairAttempted = true; + const pairResult = await autoApproveDevicePairing({ + url: parsedUrl.toString(), + headers, + connectTimeoutMs, + clientId, + clientMode, + clientVersion, + role, + scopes, + authToken, + password, + requestId: extractPairingRequestId(err), + deviceId: deviceIdentity?.deviceId ?? null, + onLog: ctx.onLog + }); + if (pairResult.ok) { + await ctx.onLog( + "stdout", + `[openclaw-gateway] auto-approved pairing request ${pairResult.requestId}; retrying +` + ); + continue; + } + await ctx.onLog( + "stderr", + `[openclaw-gateway] auto-pairing failed: ${pairResult.reason} +` + ); + } + const detailedMessage = pairingRequired ? `${message3}. Approve the pending device in OpenClaw (for example: openclaw devices approve --latest --url --token ) and retry. Ensure this agent has a persisted adapterConfig.devicePrivateKeyPem so approvals are reused.` : message3; + await ctx.onLog("stderr", `[openclaw-gateway] request failed: ${detailedMessage} +`); + return { + exitCode: 1, + signal: null, + timedOut, + errorMessage: detailedMessage, + errorCode: timedOut ? "openclaw_gateway_timeout" : pairingRequired ? "openclaw_gateway_pairing_required" : "openclaw_gateway_request_failed", + resultJson: asRecord4(latestResultPayload) + }; + } finally { + client2.close(); + } + } +} + +// packages/adapters/openclaw-gateway/src/server/test.ts +import { randomUUID as randomUUID2 } from "node:crypto"; +function summarizeStatus6(checks) { + if (checks.some((check3) => check3.level === "error")) return "fail"; + if (checks.some((check3) => check3.level === "warn")) return "warn"; + return "pass"; +} +function nonEmpty4(value) { + return typeof value === "string" && value.trim().length > 0 ? value.trim() : null; +} +function isLoopbackHost3(hostname3) { + const value = hostname3.trim().toLowerCase(); + return value === "localhost" || value === "127.0.0.1" || value === "::1"; +} +function toStringRecord2(value) { + const parsed = parseObject(value); + const out = {}; + for (const [key, entry] of Object.entries(parsed)) { + if (typeof entry === "string") out[key] = entry; + } + return out; +} +function toStringArray2(value) { + if (Array.isArray(value)) { + return value.filter((entry) => typeof entry === "string").map((entry) => entry.trim()).filter(Boolean); + } + if (typeof value === "string") { + return value.split(",").map((entry) => entry.trim()).filter(Boolean); + } + return []; +} +function headerMapGetIgnoreCase2(headers, key) { + const match = Object.entries(headers).find(([entryKey]) => entryKey.toLowerCase() === key.toLowerCase()); + return match ? match[1] : null; +} +function tokenFromAuthHeader2(rawHeader) { + if (!rawHeader) return null; + const trimmed = rawHeader.trim(); + if (!trimmed) return null; + const match = trimmed.match(/^bearer\s+(.+)$/i); + return match ? nonEmpty4(match[1]) : trimmed; +} +function resolveAuthToken2(config3, headers) { + const explicit = nonEmpty4(config3.authToken) ?? nonEmpty4(config3.token); + if (explicit) return explicit; + const tokenHeader = headerMapGetIgnoreCase2(headers, "x-openclaw-token"); + if (nonEmpty4(tokenHeader)) return nonEmpty4(tokenHeader); + const authHeader = headerMapGetIgnoreCase2(headers, "x-openclaw-auth") ?? headerMapGetIgnoreCase2(headers, "authorization"); + return tokenFromAuthHeader2(authHeader); +} +function asRecord5(value) { + if (typeof value !== "object" || value === null || Array.isArray(value)) return null; + return value; +} +function rawDataToString2(data2) { + if (typeof data2 === "string") return data2; + if (Buffer.isBuffer(data2)) return data2.toString("utf8"); + if (data2 instanceof ArrayBuffer) return Buffer.from(data2).toString("utf8"); + if (Array.isArray(data2)) { + return Buffer.concat( + data2.map((entry) => Buffer.isBuffer(entry) ? entry : Buffer.from(String(entry), "utf8")) + ).toString("utf8"); + } + return String(data2 ?? ""); +} +async function probeGateway(input) { + return await new Promise((resolve4) => { + const ws = new import_websocket.default(input.url, { headers: input.headers, maxPayload: 2 * 1024 * 1024 }); + const timeout = setTimeout(() => { + try { + ws.close(); + } catch { + } + resolve4("failed"); + }, input.timeoutMs); + let completed = false; + const finish = (status) => { + if (completed) return; + completed = true; + clearTimeout(timeout); + try { + ws.close(); + } catch { + } + resolve4(status); + }; + ws.on("message", (raw) => { + let parsed; + try { + parsed = JSON.parse(rawDataToString2(raw)); + } catch { + return; + } + const event = asRecord5(parsed); + if (event?.type === "event" && event.event === "connect.challenge") { + const nonce = nonEmpty4(asRecord5(event.payload)?.nonce); + if (!nonce) { + finish("failed"); + return; + } + const connectId = randomUUID2(); + ws.send( + JSON.stringify({ + type: "req", + id: connectId, + method: "connect", + params: { + minProtocol: 3, + maxProtocol: 3, + client: { + id: "gateway-client", + version: "taskcore-probe", + platform: process.platform, + mode: "probe" + }, + role: input.role, + scopes: input.scopes, + ...input.authToken ? { + auth: { + token: input.authToken + } + } : {} + } + }) + ); + return; + } + if (event?.type === "res") { + if (event.ok === true) { + finish("ok"); + } else { + finish("challenge_only"); + } + } + }); + ws.on("error", () => { + finish("failed"); + }); + ws.on("close", () => { + if (!completed) finish("failed"); + }); + }); +} +async function testEnvironment6(ctx) { + const checks = []; + const config3 = parseObject(ctx.config); + const urlValue = asString(config3.url, "").trim(); + if (!urlValue) { + checks.push({ + code: "openclaw_gateway_url_missing", + level: "error", + message: "OpenClaw gateway adapter requires a WebSocket URL.", + hint: "Set adapterConfig.url to ws://host:port (or wss://)." + }); + return { + adapterType: ctx.adapterType, + status: summarizeStatus6(checks), + checks, + testedAt: (/* @__PURE__ */ new Date()).toISOString() + }; + } + let url2 = null; + try { + url2 = new URL(urlValue); + } catch { + checks.push({ + code: "openclaw_gateway_url_invalid", + level: "error", + message: `Invalid URL: ${urlValue}` + }); + } + if (url2 && url2.protocol !== "ws:" && url2.protocol !== "wss:") { + checks.push({ + code: "openclaw_gateway_url_protocol_invalid", + level: "error", + message: `Unsupported URL protocol: ${url2.protocol}`, + hint: "Use ws:// or wss://." + }); + } + if (url2) { + checks.push({ + code: "openclaw_gateway_url_valid", + level: "info", + message: `Configured gateway URL: ${url2.toString()}` + }); + if (url2.protocol === "ws:" && !isLoopbackHost3(url2.hostname)) { + checks.push({ + code: "openclaw_gateway_plaintext_remote_ws", + level: "warn", + message: "Gateway URL uses plaintext ws:// on a non-loopback host.", + hint: "Prefer wss:// for remote gateways." + }); + } + } + const headers = toStringRecord2(config3.headers); + const authToken = resolveAuthToken2(config3, headers); + const password = nonEmpty4(config3.password); + const role = nonEmpty4(config3.role) ?? "operator"; + const scopes = toStringArray2(config3.scopes); + if (authToken || password) { + checks.push({ + code: "openclaw_gateway_auth_present", + level: "info", + message: "Gateway credentials are configured." + }); + } else { + checks.push({ + code: "openclaw_gateway_auth_missing", + level: "warn", + message: "No gateway credentials detected in adapter config.", + hint: "Set authToken/password or headers.x-openclaw-token for authenticated gateways." + }); + } + if (url2 && (url2.protocol === "ws:" || url2.protocol === "wss:")) { + try { + const probeResult = await probeGateway({ + url: url2.toString(), + headers, + authToken, + role, + scopes: scopes.length > 0 ? scopes : ["operator.admin"], + timeoutMs: 3e3 + }); + if (probeResult === "ok") { + checks.push({ + code: "openclaw_gateway_probe_ok", + level: "info", + message: "Gateway connect probe succeeded." + }); + } else if (probeResult === "challenge_only") { + checks.push({ + code: "openclaw_gateway_probe_challenge_only", + level: "warn", + message: "Gateway challenge was received, but connect probe was rejected.", + hint: "Check gateway credentials, scopes, role, and device-auth requirements." + }); + } else { + checks.push({ + code: "openclaw_gateway_probe_failed", + level: "warn", + message: "Gateway probe failed.", + hint: "Verify network reachability and gateway URL from the Taskcore server host." + }); + } + } catch (err) { + checks.push({ + code: "openclaw_gateway_probe_error", + level: "warn", + message: err instanceof Error ? err.message : "Gateway probe failed" + }); + } + } + return { + adapterType: ctx.adapterType, + status: summarizeStatus6(checks), + checks, + testedAt: (/* @__PURE__ */ new Date()).toISOString() + }; +} + +// packages/adapters/openclaw-gateway/src/index.ts +var models6 = []; +var agentConfigurationDoc6 = `# openclaw_gateway agent configuration + +Adapter: openclaw_gateway + +Use when: +- You want Taskcore to invoke OpenClaw over the Gateway WebSocket protocol. +- You want native gateway auth/connect semantics instead of HTTP /v1/responses or /hooks/*. + +Don't use when: +- You only expose OpenClaw HTTP endpoints. +- Your deployment does not permit outbound WebSocket access from the Taskcore server. + +Core fields: +- url (string, required): OpenClaw gateway WebSocket URL (ws:// or wss://) +- headers (object, optional): handshake headers; supports x-openclaw-token / x-openclaw-auth +- authToken (string, optional): shared gateway token override +- password (string, optional): gateway shared password, if configured + +Gateway connect identity fields: +- clientId (string, optional): gateway client id (default gateway-client) +- clientMode (string, optional): gateway client mode (default backend) +- clientVersion (string, optional): client version string +- role (string, optional): gateway role (default operator) +- scopes (string[] | comma string, optional): gateway scopes (default ["operator.admin"]) +- disableDeviceAuth (boolean, optional): disable signed device payload in connect params (default false) + +Request behavior fields: +- payloadTemplate (object, optional): additional fields merged into gateway agent params +- workspaceRuntime (object, optional): reserved workspace runtime metadata; workspace runtime services are manually controlled from the workspace UI and are not auto-started by heartbeats +- timeoutSec (number, optional): adapter timeout in seconds (default 120) +- waitTimeoutMs (number, optional): agent.wait timeout override (default timeoutSec * 1000) +- autoPairOnFirstConnect (boolean, optional): on first "pairing required", attempt device.pair.list/device.pair.approve via shared auth, then retry once (default true) +- taskcoreApiUrl (string, optional): absolute Taskcore base URL advertised in wake text +- claimedApiKeyPath (string, optional): path to the claimed API key JSON file read by the agent at wake time (default ~/.openclaw/workspace/taskcore-claimed-api-key.json) + +Session routing fields: +- sessionKeyStrategy (string, optional): issue (default), fixed, or run +- sessionKey (string, optional): fixed session key when strategy=fixed (default taskcore) + +Standard outbound payload additions: +- taskcore (object): standardized Taskcore context added to every gateway agent request +- taskcore.workspace (object, optional): resolved execution workspace for this run +- taskcore.workspaces (array, optional): additional workspace hints Taskcore exposed to the run +- taskcore.workspaceRuntime (object, optional): reserved workspace runtime metadata when explicitly supplied outside normal heartbeat execution + +Standard result metadata supported: +- meta.runtimeServices (array, optional): normalized adapter-managed runtime service reports +- meta.previewUrl (string, optional): shorthand single preview URL +- meta.previewUrls (string[], optional): shorthand multiple preview URLs +`; + +// server/src/adapters/codex-models.ts +var OPENAI_MODELS_ENDPOINT = "https://api.openai.com/v1/models"; +var OPENAI_MODELS_TIMEOUT_MS = 5e3; +var OPENAI_MODELS_CACHE_TTL_MS = 6e4; +var cached = null; +function fingerprint(apiKey) { + return `${apiKey.length}:${apiKey.slice(-6)}`; +} +function dedupeModels2(models8) { + const seen = /* @__PURE__ */ new Set(); + const deduped = []; + for (const model of models8) { + const id = model.id.trim(); + if (!id || seen.has(id)) continue; + seen.add(id); + deduped.push({ id, label: model.label.trim() || id }); + } + return deduped; +} +function mergedWithFallback(models8) { + return dedupeModels2([ + ...models8, + ...models2 + ]).sort((a5, b6) => a5.id.localeCompare(b6.id, "en", { numeric: true, sensitivity: "base" })); +} +function resolveOpenAiApiKey() { + const envKey = process.env.OPENAI_API_KEY?.trim(); + if (envKey) return envKey; + const config3 = readConfigFile(); + if (config3?.llm?.provider !== "openai") return null; + const configKey = config3.llm.apiKey?.trim(); + return configKey && configKey.length > 0 ? configKey : null; +} +async function fetchOpenAiModels(apiKey) { + const controller = new AbortController(); + const timeout = setTimeout(() => controller.abort(), OPENAI_MODELS_TIMEOUT_MS); + try { + const response = await fetch(OPENAI_MODELS_ENDPOINT, { + headers: { + Authorization: `Bearer ${apiKey}` + }, + signal: controller.signal + }); + if (!response.ok) return []; + const payload2 = await response.json(); + const data2 = Array.isArray(payload2.data) ? payload2.data : []; + const models8 = []; + for (const item of data2) { + if (typeof item !== "object" || item === null) continue; + const id = item.id; + if (typeof id !== "string" || id.trim().length === 0) continue; + models8.push({ id, label: id }); + } + return dedupeModels2(models8); + } catch { + return []; + } finally { + clearTimeout(timeout); + } +} +async function listCodexModels() { + const apiKey = resolveOpenAiApiKey(); + const fallback = dedupeModels2(models2); + if (!apiKey) return fallback; + const now2 = Date.now(); + const keyFingerprint = fingerprint(apiKey); + if (cached && cached.keyFingerprint === keyFingerprint && cached.expiresAt > now2) { + return cached.models; + } + const fetched = await fetchOpenAiModels(apiKey); + if (fetched.length > 0) { + const merged = mergedWithFallback(fetched); + cached = { + keyFingerprint, + expiresAt: now2 + OPENAI_MODELS_CACHE_TTL_MS, + models: merged + }; + return merged; + } + if (cached && cached.keyFingerprint === keyFingerprint && cached.models.length > 0) { + return cached.models; + } + return fallback; +} + +// server/src/adapters/cursor-models.ts +import { spawnSync } from "node:child_process"; +var CURSOR_MODELS_TIMEOUT_MS = 5e3; +var CURSOR_MODELS_CACHE_TTL_MS = 6e4; +var MAX_BUFFER_BYTES = 512 * 1024; +var cached2 = null; +function dedupeModels3(models8) { + const seen = /* @__PURE__ */ new Set(); + const deduped = []; + for (const model of models8) { + const id = model.id.trim(); + if (!id || seen.has(id)) continue; + seen.add(id); + deduped.push({ id, label: model.label.trim() || id }); + } + return deduped; +} +function sanitizeModelId(raw) { + return raw.trim().replace(/^["'`]+|["'`]+$/g, "").replace(/\(.*\)\s*$/g, "").trim(); +} +function isLikelyModelId(raw) { + const value = sanitizeModelId(raw); + if (!value) return false; + return /^[A-Za-z0-9][A-Za-z0-9._/-]*$/.test(value); +} +function pushModelId(target, raw) { + const id = sanitizeModelId(raw); + if (!isLikelyModelId(id)) return; + target.push({ id, label: id }); +} +function collectFromJsonValue(value, target) { + if (typeof value === "string") { + pushModelId(target, value); + return; + } + if (!Array.isArray(value)) return; + for (const item of value) { + if (typeof item === "string") { + pushModelId(target, item); + continue; + } + if (typeof item !== "object" || item === null) continue; + const id = item.id; + if (typeof id === "string") { + pushModelId(target, id); + } + } +} +function parseCursorModelsOutput(stdout, stderr) { + const models8 = []; + const combined = `${stdout} +${stderr}`; + const trimmedStdout = stdout.trim(); + if (trimmedStdout.startsWith("{") || trimmedStdout.startsWith("[")) { + try { + const parsed = JSON.parse(trimmedStdout); + if (Array.isArray(parsed)) { + collectFromJsonValue(parsed, models8); + } else if (typeof parsed === "object" && parsed !== null) { + const rec = parsed; + collectFromJsonValue(rec.models, models8); + collectFromJsonValue(rec.data, models8); + } + } catch { + } + } + for (const match of combined.matchAll(/available models?:\s*([^\n]+)/gi)) { + const list2 = match[1] ?? ""; + for (const token of list2.split(",")) { + pushModelId(models8, token); + } + } + for (const lineRaw of combined.split(/\r?\n/)) { + const line3 = lineRaw.trim(); + if (!line3) continue; + const bullet = line3.replace(/^[-*]\s+/, "").trim(); + if (!bullet || bullet.includes(" ")) continue; + pushModelId(models8, bullet); + } + return dedupeModels3(models8); +} +function mergedWithFallback2(models8) { + return dedupeModels3([...models8, ...models3]); +} +function defaultCursorModelsRunner() { + const result = spawnSync("agent", ["models"], { + encoding: "utf8", + timeout: CURSOR_MODELS_TIMEOUT_MS, + maxBuffer: MAX_BUFFER_BYTES + }); + return { + status: result.status, + stdout: typeof result.stdout === "string" ? result.stdout : "", + stderr: typeof result.stderr === "string" ? result.stderr : "", + hasError: Boolean(result.error) + }; +} +var cursorModelsRunner = defaultCursorModelsRunner; +function fetchCursorModelsFromCli() { + const result = cursorModelsRunner(); + const { stdout, stderr } = result; + if (result.hasError && stdout.trim().length === 0 && stderr.trim().length === 0) { + return []; + } + if ((result.status ?? 1) !== 0 && !/available models?:/i.test(`${stdout} +${stderr}`)) { + return []; + } + return parseCursorModelsOutput(stdout, stderr); +} +async function listCursorModels() { + const now2 = Date.now(); + if (cached2 && cached2.expiresAt > now2) { + return cached2.models; + } + const discovered = fetchCursorModelsFromCli(); + if (discovered.length > 0) { + const merged = mergedWithFallback2(discovered); + cached2 = { + expiresAt: now2 + CURSOR_MODELS_CACHE_TTL_MS, + models: merged + }; + return merged; + } + if (cached2 && cached2.models.length > 0) { + return cached2.models; + } + return dedupeModels3(models3); +} + +// packages/adapters/pi-local/src/server/execute.ts +import fs21 from "node:fs/promises"; +import os18 from "node:os"; +import path27 from "node:path"; +import { fileURLToPath as fileURLToPath12 } from "node:url"; + +// packages/adapters/pi-local/src/server/parse.ts +function asRecord6(value) { + if (typeof value !== "object" || value === null || Array.isArray(value)) return null; + return value; +} +function extractTextContent(content) { + if (typeof content === "string") return content; + if (!Array.isArray(content)) return ""; + return content.filter((c5) => c5.type === "text" && c5.text).map((c5) => c5.text).join(""); +} +function parsePiJsonl(stdout) { + const result = { + sessionId: null, + messages: [], + errors: [], + usage: { + inputTokens: 0, + outputTokens: 0, + cachedInputTokens: 0, + costUsd: 0 + }, + finalMessage: null, + toolCalls: [] + }; + let currentToolCall = null; + for (const rawLine of stdout.split(/\r?\n/)) { + const line3 = rawLine.trim(); + if (!line3) continue; + const event = parseJson2(line3); + if (!event) continue; + const eventType = asString(event.type, ""); + if (eventType === "response" || eventType === "extension_ui_request" || eventType === "extension_ui_response" || eventType === "extension_error") { + continue; + } + if (eventType === "agent_start") { + continue; + } + if (eventType === "agent_end") { + const messages2 = event.messages; + if (messages2 && messages2.length > 0) { + const lastMessage = messages2[messages2.length - 1]; + if (lastMessage?.role === "assistant") { + const content = lastMessage.content; + result.finalMessage = extractTextContent(content); + } + } + continue; + } + if (eventType === "auto_retry_end") { + const succeeded = event.success === true; + if (!succeeded) { + const finalError = asString(event.finalError, "").trim(); + result.errors.push(finalError || "Pi exhausted automatic retries without producing a response."); + } + continue; + } + if (eventType === "turn_start") { + continue; + } + if (eventType === "turn_end") { + const message2 = asRecord6(event.message); + if (message2) { + const content = message2.content; + const text3 = extractTextContent(content); + if (text3) { + result.finalMessage = text3; + result.messages.push(text3); + } + const usage = asRecord6(message2.usage); + if (usage) { + result.usage.inputTokens += asNumber(usage.input, 0); + result.usage.outputTokens += asNumber(usage.output, 0); + result.usage.cachedInputTokens += asNumber(usage.cacheRead, 0); + const cost = asRecord6(usage.cost); + if (cost) { + result.usage.costUsd += asNumber(cost.total, 0); + } + } + } + const toolResults = event.toolResults; + if (toolResults) { + for (const tr of toolResults) { + const toolCallId = asString(tr.toolCallId, ""); + const content = tr.content; + const isError = tr.isError === true; + const existingCall = result.toolCalls.find((tc) => tc.toolCallId === toolCallId); + if (existingCall) { + existingCall.result = typeof content === "string" ? content : JSON.stringify(content); + existingCall.isError = isError; + } + } + } + continue; + } + if (eventType === "message_update") { + const assistantEvent = asRecord6(event.assistantMessageEvent); + if (assistantEvent) { + const msgType = asString(assistantEvent.type, ""); + if (msgType === "text_delta") { + const delta = asString(assistantEvent.delta, ""); + if (delta) { + if (result.messages.length === 0) { + result.messages.push(delta); + } else { + result.messages[result.messages.length - 1] += delta; + } + } + } + } + continue; + } + if (eventType === "error") { + const message2 = asString(event.message, "").trim(); + if (message2) { + result.errors.push(message2); + } + continue; + } + if (eventType === "tool_execution_start") { + const toolCallId = asString(event.toolCallId, ""); + const toolName = asString(event.toolName, ""); + const args = event.args; + currentToolCall = { toolCallId, toolName, args }; + result.toolCalls.push({ + toolCallId, + toolName, + args, + result: null, + isError: false + }); + continue; + } + if (eventType === "tool_execution_end") { + const toolCallId = asString(event.toolCallId, ""); + const toolName = asString(event.toolName, ""); + const toolResult = event.result; + const isError = event.isError === true; + const existingCall = result.toolCalls.find((tc) => tc.toolCallId === toolCallId); + if (existingCall) { + existingCall.result = typeof toolResult === "string" ? toolResult : JSON.stringify(toolResult); + existingCall.isError = isError; + } + currentToolCall = null; + continue; + } + if (eventType === "usage" || event.usage) { + const usage = asRecord6(event.usage); + if (usage) { + result.usage.inputTokens += asNumber(usage.inputTokens ?? usage.input, 0); + result.usage.outputTokens += asNumber(usage.outputTokens ?? usage.output, 0); + result.usage.cachedInputTokens += asNumber(usage.cachedInputTokens ?? usage.cacheRead, 0); + const cost = asRecord6(usage.cost); + if (cost) { + result.usage.costUsd += asNumber(cost.total ?? usage.costUsd, 0); + } else { + result.usage.costUsd += asNumber(usage.costUsd, 0); + } + } + } + } + return result; +} +function isPiUnknownSessionError(stdout, stderr) { + const haystack = `${stdout} +${stderr}`.split(/\r?\n/).map((line3) => line3.trim()).filter(Boolean).join("\n"); + return /unknown\s+session|session\s+not\s+found|session\s+.*\s+not\s+found|no\s+session/i.test(haystack); +} + +// packages/adapters/pi-local/src/server/models.ts +import { createHash as createHash7 } from "node:crypto"; +var MODELS_CACHE_TTL_MS2 = 6e4; +function firstNonEmptyLine10(text3) { + return text3.split(/\r?\n/).map((line3) => line3.trim()).find(Boolean) ?? ""; +} +function parseModelsOutput2(stdout) { + const parsed = []; + const lines = stdout.split(/\r?\n/); + let startIndex = 0; + if (lines.length > 0 && (lines[0].includes("provider") || lines[0].includes("model"))) { + startIndex = 1; + } + for (let i5 = startIndex; i5 < lines.length; i5++) { + const line3 = lines[i5].trim(); + if (!line3) continue; + const parts = line3.split(/\s{2,}/); + if (parts.length < 2) continue; + const provider = parts[0].trim(); + const model = parts[1].trim(); + if (!provider || !model) continue; + if (provider === "provider" && model === "model") continue; + const id = `${provider}/${model}`; + parsed.push({ id, label: id }); + } + return parsed; +} +function dedupeModels4(models8) { + const seen = /* @__PURE__ */ new Set(); + const deduped = []; + for (const model of models8) { + const id = model.id.trim(); + if (!id || seen.has(id)) continue; + seen.add(id); + deduped.push({ id, label: model.label.trim() || id }); + } + return deduped; +} +function sortModels2(models8) { + return [...models8].sort( + (a5, b6) => a5.id.localeCompare(b6.id, "en", { numeric: true, sensitivity: "base" }) + ); +} +function resolvePiCommand(input) { + const envOverride = typeof process.env.TASKCORE_PI_COMMAND === "string" && process.env.TASKCORE_PI_COMMAND.trim().length > 0 ? process.env.TASKCORE_PI_COMMAND.trim() : "pi"; + return asString(input, envOverride); +} +var discoveryCache2 = /* @__PURE__ */ new Map(); +var VOLATILE_ENV_KEY_PREFIXES2 = ["TASKCORE_", "npm_", "NPM_"]; +var VOLATILE_ENV_KEY_EXACT2 = /* @__PURE__ */ new Set(["PWD", "OLDPWD", "SHLVL", "_", "TERM_SESSION_ID"]); +function isVolatileEnvKey2(key) { + if (VOLATILE_ENV_KEY_EXACT2.has(key)) return true; + return VOLATILE_ENV_KEY_PREFIXES2.some((prefix) => key.startsWith(prefix)); +} +function hashValue2(value) { + return createHash7("sha256").update(value).digest("hex"); +} +function discoveryCacheKey2(command, cwd, env2) { + const envKey = Object.entries(env2).filter(([key]) => !isVolatileEnvKey2(key)).sort(([a5], [b6]) => a5.localeCompare(b6)).map(([key, value]) => `${key}=${hashValue2(value)}`).join("\n"); + return `${command} +${cwd} +${envKey}`; +} +function pruneExpiredDiscoveryCache2(now2) { + for (const [key, value] of discoveryCache2.entries()) { + if (value.expiresAt <= now2) discoveryCache2.delete(key); + } +} +async function discoverPiModels(input = {}) { + const command = resolvePiCommand(input.command); + const cwd = asString(input.cwd, process.cwd()); + const env2 = normalizeEnv3(input.env); + const runtimeEnv = normalizeEnv3({ ...process.env, ...env2 }); + const result = await runChildProcess( + `pi-models-${Date.now()}-${Math.random().toString(16).slice(2)}`, + command, + ["--list-models"], + { + cwd, + env: runtimeEnv, + timeoutSec: 20, + graceSec: 3, + onLog: async () => { + } + } + ); + if (result.timedOut) { + throw new Error("`pi --list-models` timed out."); + } + if ((result.exitCode ?? 1) !== 0) { + const detail = firstNonEmptyLine10(result.stderr) || firstNonEmptyLine10(result.stdout); + throw new Error(detail ? `\`pi --list-models\` failed: ${detail}` : "`pi --list-models` failed."); + } + const output = result.stderr || result.stdout; + return sortModels2(dedupeModels4(parseModelsOutput2(output))); +} +function normalizeEnv3(input) { + const envInput = typeof input === "object" && input !== null && !Array.isArray(input) ? input : {}; + const env2 = {}; + for (const [key, value] of Object.entries(envInput)) { + if (typeof value === "string") env2[key] = value; + } + return env2; +} +async function discoverPiModelsCached(input = {}) { + const command = resolvePiCommand(input.command); + const cwd = asString(input.cwd, process.cwd()); + const env2 = normalizeEnv3(input.env); + const key = discoveryCacheKey2(command, cwd, env2); + const now2 = Date.now(); + pruneExpiredDiscoveryCache2(now2); + const cached4 = discoveryCache2.get(key); + if (cached4 && cached4.expiresAt > now2) return cached4.models; + const models8 = await discoverPiModels({ command, cwd, env: env2 }); + discoveryCache2.set(key, { expiresAt: now2 + MODELS_CACHE_TTL_MS2, models: models8 }); + return models8; +} +async function ensurePiModelConfiguredAndAvailable(input) { + const model = asString(input.model, "").trim(); + if (!model) { + throw new Error("Pi requires `adapterConfig.model` in provider/model format."); + } + const models8 = await discoverPiModelsCached({ + command: input.command, + cwd: input.cwd, + env: input.env + }); + if (models8.length === 0) { + throw new Error("Pi returned no models. Run `pi --list-models` and verify provider auth."); + } + if (!models8.some((entry) => entry.id === model)) { + const sample = models8.slice(0, 12).map((entry) => entry.id).join(", "); + throw new Error( + `Configured Pi model is unavailable: ${model}. Available models: ${sample}${models8.length > 12 ? ", ..." : ""}` + ); + } + return models8; +} +async function listPiModels() { + try { + return await discoverPiModelsCached(); + } catch { + return []; + } +} + +// packages/adapters/pi-local/src/server/execute.ts +var __moduleDir11 = path27.dirname(fileURLToPath12(import.meta.url)); +var TASKCORE_SESSIONS_DIR = path27.join(os18.homedir(), ".pi", "taskcores"); +var PI_AGENT_SKILLS_DIR = path27.join(os18.homedir(), ".pi", "agent", "skills"); +function firstNonEmptyLine11(text3) { + return text3.split(/\r?\n/).map((line3) => line3.trim()).find(Boolean) ?? ""; +} +function parseModelProvider2(model) { + if (!model) return null; + const trimmed = model.trim(); + if (!trimmed.includes("/")) return null; + return trimmed.slice(0, trimmed.indexOf("/")).trim() || null; +} +function parseModelId(model) { + if (!model) return null; + const trimmed = model.trim(); + if (!trimmed.includes("/")) return trimmed || null; + return trimmed.slice(trimmed.indexOf("/") + 1).trim() || null; +} +async function ensurePiSkillsInjected(onLog, skillsEntries, desiredSkillNames) { + const desiredSet = new Set(desiredSkillNames ?? skillsEntries.map((entry) => entry.key)); + const selectedEntries = skillsEntries.filter((entry) => desiredSet.has(entry.key)); + if (selectedEntries.length === 0) return; + await fs21.mkdir(PI_AGENT_SKILLS_DIR, { recursive: true }); + const removedSkills = await removeMaintainerOnlySkillSymlinks( + PI_AGENT_SKILLS_DIR, + selectedEntries.map((entry) => entry.runtimeName) + ); + for (const skillName of removedSkills) { + await onLog( + "stderr", + `[taskcore] Removed maintainer-only Pi skill "${skillName}" from ${PI_AGENT_SKILLS_DIR} +` + ); + } + for (const entry of selectedEntries) { + const target = path27.join(PI_AGENT_SKILLS_DIR, entry.runtimeName); + try { + const result = await ensureTaskcoreSkillSymlink(entry.source, target); + if (result === "skipped") continue; + await onLog( + "stderr", + `[taskcore] ${result === "repaired" ? "Repaired" : "Injected"} Pi skill "${entry.runtimeName}" into ${PI_AGENT_SKILLS_DIR} +` + ); + } catch (err) { + await onLog( + "stderr", + `[taskcore] Failed to inject Pi skill "${entry.runtimeName}" into ${PI_AGENT_SKILLS_DIR}: ${err instanceof Error ? err.message : String(err)} +` + ); + } + } +} +function resolvePiBiller(env2, provider) { + return inferOpenAiCompatibleBiller(env2, null) ?? provider ?? "unknown"; +} +async function ensureSessionsDir() { + await fs21.mkdir(TASKCORE_SESSIONS_DIR, { recursive: true }); + return TASKCORE_SESSIONS_DIR; +} +function buildSessionPath(agentId, timestamp2) { + const safeTimestamp = timestamp2.replace(/[:.]/g, "-"); + return path27.join(TASKCORE_SESSIONS_DIR, `${safeTimestamp}-${agentId}.jsonl`); +} +async function execute7(ctx) { + const { runId, agent, runtime, config: config3, context, onLog, onMeta, onSpawn, authToken } = ctx; + const promptTemplate = asString( + config3.promptTemplate, + "You are agent {{agent.id}} ({{agent.name}}). Continue your Taskcore work." + ); + const command = asString(config3.command, "pi"); + const model = asString(config3.model, "").trim(); + const thinking = asString(config3.thinking, "").trim(); + const provider = parseModelProvider2(model); + const modelId = parseModelId(model); + const workspaceContext = parseObject(context.taskcoreWorkspace); + const workspaceCwd = asString(workspaceContext.cwd, ""); + const workspaceSource = asString(workspaceContext.source, ""); + const workspaceId = asString(workspaceContext.workspaceId, ""); + const workspaceRepoUrl = asString(workspaceContext.repoUrl, ""); + const workspaceRepoRef = asString(workspaceContext.repoRef, ""); + const agentHome = asString(workspaceContext.agentHome, ""); + const workspaceHints = Array.isArray(context.taskcoreWorkspaces) ? context.taskcoreWorkspaces.filter( + (value) => typeof value === "object" && value !== null + ) : []; + const configuredCwd = asString(config3.cwd, ""); + const useConfiguredInsteadOfAgentHome = workspaceSource === "agent_home" && configuredCwd.length > 0; + const effectiveWorkspaceCwd = useConfiguredInsteadOfAgentHome ? "" : workspaceCwd; + const cwd = effectiveWorkspaceCwd || configuredCwd || process.cwd(); + await ensureAbsoluteDirectory(cwd, { createIfMissing: true }); + await ensureSessionsDir(); + const piSkillEntries = await readTaskcoreRuntimeSkillEntries(config3, __moduleDir11); + const desiredPiSkillNames = resolveTaskcoreDesiredSkillNames(config3, piSkillEntries); + await ensurePiSkillsInjected(onLog, piSkillEntries, desiredPiSkillNames); + const envConfig = parseObject(config3.env); + const hasExplicitApiKey = typeof envConfig.TASKCORE_API_KEY === "string" && envConfig.TASKCORE_API_KEY.trim().length > 0; + const env2 = { ...buildTaskcoreEnv(agent) }; + env2.TASKCORE_RUN_ID = runId; + const wakeTaskId = typeof context.taskId === "string" && context.taskId.trim().length > 0 && context.taskId.trim() || typeof context.issueId === "string" && context.issueId.trim().length > 0 && context.issueId.trim() || null; + const wakeReason = typeof context.wakeReason === "string" && context.wakeReason.trim().length > 0 ? context.wakeReason.trim() : null; + const wakeCommentId = typeof context.wakeCommentId === "string" && context.wakeCommentId.trim().length > 0 && context.wakeCommentId.trim() || typeof context.commentId === "string" && context.commentId.trim().length > 0 && context.commentId.trim() || null; + const approvalId = typeof context.approvalId === "string" && context.approvalId.trim().length > 0 ? context.approvalId.trim() : null; + const approvalStatus = typeof context.approvalStatus === "string" && context.approvalStatus.trim().length > 0 ? context.approvalStatus.trim() : null; + const linkedIssueIds = Array.isArray(context.issueIds) ? context.issueIds.filter((value) => typeof value === "string" && value.trim().length > 0) : []; + const wakePayloadJson = stringifyTaskcoreWakePayload(context.taskcoreWake); + if (wakeTaskId) env2.TASKCORE_TASK_ID = wakeTaskId; + if (wakeReason) env2.TASKCORE_WAKE_REASON = wakeReason; + if (wakeCommentId) env2.TASKCORE_WAKE_COMMENT_ID = wakeCommentId; + if (approvalId) env2.TASKCORE_APPROVAL_ID = approvalId; + if (approvalStatus) env2.TASKCORE_APPROVAL_STATUS = approvalStatus; + if (linkedIssueIds.length > 0) env2.TASKCORE_LINKED_ISSUE_IDS = linkedIssueIds.join(","); + if (wakePayloadJson) env2.TASKCORE_WAKE_PAYLOAD_JSON = wakePayloadJson; + if (workspaceCwd) env2.TASKCORE_WORKSPACE_CWD = workspaceCwd; + if (workspaceSource) env2.TASKCORE_WORKSPACE_SOURCE = workspaceSource; + if (workspaceId) env2.TASKCORE_WORKSPACE_ID = workspaceId; + if (workspaceRepoUrl) env2.TASKCORE_WORKSPACE_REPO_URL = workspaceRepoUrl; + if (workspaceRepoRef) env2.TASKCORE_WORKSPACE_REPO_REF = workspaceRepoRef; + if (agentHome) env2.AGENT_HOME = agentHome; + if (workspaceHints.length > 0) env2.TASKCORE_WORKSPACES_JSON = JSON.stringify(workspaceHints); + for (const [key, value] of Object.entries(envConfig)) { + if (typeof value === "string") env2[key] = value; + } + if (!hasExplicitApiKey && authToken) { + env2.TASKCORE_API_KEY = authToken; + } + const runtimeEnv = Object.fromEntries( + Object.entries(ensurePathInEnv({ ...process.env, ...env2 })).filter( + (entry) => typeof entry[1] === "string" + ) + ); + await ensureCommandResolvable(command, cwd, runtimeEnv); + const resolvedCommand = await resolveCommandForLogs(command, cwd, runtimeEnv); + const loggedEnv = buildInvocationEnvForLogs(env2, { + runtimeEnv, + includeRuntimeKeys: ["HOME"], + resolvedCommand + }); + await ensurePiModelConfiguredAndAvailable({ + model, + command, + cwd, + env: runtimeEnv + }); + const timeoutSec = asNumber(config3.timeoutSec, 0); + const graceSec = asNumber(config3.graceSec, 20); + const extraArgs = (() => { + const fromExtraArgs = asStringArray(config3.extraArgs); + if (fromExtraArgs.length > 0) return fromExtraArgs; + return asStringArray(config3.args); + })(); + const runtimeSessionParams = parseObject(runtime.sessionParams); + const runtimeSessionId = asString(runtimeSessionParams.sessionId, runtime.sessionId ?? ""); + const runtimeSessionCwd = asString(runtimeSessionParams.cwd, ""); + const canResumeSession = runtimeSessionId.length > 0 && (runtimeSessionCwd.length === 0 || path27.resolve(runtimeSessionCwd) === path27.resolve(cwd)); + const sessionPath = canResumeSession ? runtimeSessionId : buildSessionPath(agent.id, (/* @__PURE__ */ new Date()).toISOString()); + if (runtimeSessionId && !canResumeSession) { + await onLog( + "stdout", + `[taskcore] Pi session "${runtimeSessionId}" was saved for cwd "${runtimeSessionCwd}" and will not be resumed in "${cwd}". +` + ); + } + if (!canResumeSession) { + try { + await fs21.writeFile(sessionPath, "", { flag: "wx" }); + } catch (err) { + if (err.code !== "EEXIST") { + throw err; + } + } + } + const instructionsFilePath = asString(config3.instructionsFilePath, "").trim(); + const resolvedInstructionsFilePath = instructionsFilePath ? path27.resolve(cwd, instructionsFilePath) : ""; + const instructionsFileDir = instructionsFilePath ? `${path27.dirname(instructionsFilePath)}/` : ""; + let systemPromptExtension = ""; + let instructionsReadFailed = false; + if (resolvedInstructionsFilePath) { + try { + const instructionsContents = await fs21.readFile(resolvedInstructionsFilePath, "utf8"); + systemPromptExtension = `${instructionsContents} + +The above agent instructions were loaded from ${resolvedInstructionsFilePath}. Resolve any relative file references from ${instructionsFileDir}. + +You are agent {{agent.id}} ({{agent.name}}). Continue your Taskcore work.`; + } catch (err) { + instructionsReadFailed = true; + const reason = err instanceof Error ? err.message : String(err); + await onLog( + "stdout", + `[taskcore] Warning: could not read agent instructions file "${resolvedInstructionsFilePath}": ${reason} +` + ); + systemPromptExtension = promptTemplate; + } + } else { + systemPromptExtension = promptTemplate; + } + const bootstrapPromptTemplate = asString(config3.bootstrapPromptTemplate, ""); + const templateData = { + agentId: agent.id, + companyId: agent.companyId, + runId, + company: { id: agent.companyId }, + agent, + run: { id: runId, source: "on_demand" }, + context + }; + const renderedSystemPromptExtension = renderTemplate(systemPromptExtension, templateData); + const renderedBootstrapPrompt = !canResumeSession && bootstrapPromptTemplate.trim().length > 0 ? renderTemplate(bootstrapPromptTemplate, templateData).trim() : ""; + const wakePrompt = renderTaskcoreWakePrompt(context.taskcoreWake, { resumedSession: canResumeSession }); + const shouldUseResumeDeltaPrompt = canResumeSession && wakePrompt.length > 0; + const renderedHeartbeatPrompt = shouldUseResumeDeltaPrompt ? "" : renderTemplate(promptTemplate, templateData); + const sessionHandoffNote = asString(context.taskcoreSessionHandoffMarkdown, "").trim(); + const userPrompt = joinPromptSections([ + renderedBootstrapPrompt, + wakePrompt, + sessionHandoffNote, + renderedHeartbeatPrompt + ]); + const promptMetrics = { + systemPromptChars: renderedSystemPromptExtension.length, + promptChars: userPrompt.length, + bootstrapPromptChars: renderedBootstrapPrompt.length, + wakePromptChars: wakePrompt.length, + sessionHandoffChars: sessionHandoffNote.length, + heartbeatPromptChars: renderedHeartbeatPrompt.length + }; + const commandNotes = (() => { + if (!resolvedInstructionsFilePath) return []; + if (instructionsReadFailed) { + return [ + `Configured instructionsFilePath ${resolvedInstructionsFilePath}, but file could not be read; continuing without injected instructions.` + ]; + } + return [ + `Loaded agent instructions from ${resolvedInstructionsFilePath}`, + `Appended instructions + path directive to system prompt (relative references from ${instructionsFileDir}).` + ]; + })(); + const buildArgs = (sessionFile) => { + const args = []; + args.push("--mode", "json"); + args.push("-p"); + args.push("--append-system-prompt", renderedSystemPromptExtension); + if (provider) args.push("--provider", provider); + if (modelId) args.push("--model", modelId); + if (thinking) args.push("--thinking", thinking); + args.push("--tools", "read,bash,edit,write,grep,find,ls"); + args.push("--session", sessionFile); + args.push("--skill", PI_AGENT_SKILLS_DIR); + if (extraArgs.length > 0) args.push(...extraArgs); + args.push(userPrompt); + return args; + }; + const runAttempt = async (sessionFile) => { + const args = buildArgs(sessionFile); + if (onMeta) { + await onMeta({ + adapterType: "pi_local", + command: resolvedCommand, + cwd, + commandNotes, + commandArgs: args, + env: loggedEnv, + prompt: userPrompt, + promptMetrics, + context + }); + } + let stdoutBuffer = ""; + const bufferedOnLog = async (stream, chunk) => { + if (stream === "stderr") { + await onLog(stream, chunk); + return; + } + stdoutBuffer += chunk; + const lines = stdoutBuffer.split("\n"); + stdoutBuffer = lines.pop() || ""; + for (const line3 of lines) { + if (line3) { + await onLog(stream, line3 + "\n"); + } + } + }; + const proc = await runChildProcess(runId, command, args, { + cwd, + env: runtimeEnv, + timeoutSec, + graceSec, + onSpawn, + onLog: bufferedOnLog + }); + if (stdoutBuffer) { + await onLog("stdout", stdoutBuffer); + } + return { + proc, + rawStderr: proc.stderr, + parsed: parsePiJsonl(proc.stdout) + }; + }; + const toResult = (attempt, clearSessionOnMissingSession = false) => { + if (attempt.proc.timedOut) { + return { + exitCode: attempt.proc.exitCode, + signal: attempt.proc.signal, + timedOut: true, + errorMessage: `Timed out after ${timeoutSec}s`, + clearSession: clearSessionOnMissingSession + }; + } + const resolvedSessionId = clearSessionOnMissingSession ? null : sessionPath; + const resolvedSessionParams = resolvedSessionId ? { sessionId: resolvedSessionId, cwd } : null; + const stderrLine = firstNonEmptyLine11(attempt.proc.stderr); + const rawExitCode = attempt.proc.exitCode; + const parsedError = attempt.parsed.errors.find((error50) => error50.trim().length > 0) ?? ""; + const effectiveExitCode = (rawExitCode ?? 0) === 0 && parsedError ? 1 : rawExitCode; + const fallbackErrorMessage = parsedError || stderrLine || `Pi exited with code ${rawExitCode ?? -1}`; + return { + exitCode: effectiveExitCode, + signal: attempt.proc.signal, + timedOut: false, + errorMessage: (effectiveExitCode ?? 0) === 0 ? null : fallbackErrorMessage, + usage: { + inputTokens: attempt.parsed.usage.inputTokens, + outputTokens: attempt.parsed.usage.outputTokens, + cachedInputTokens: attempt.parsed.usage.cachedInputTokens + }, + sessionId: resolvedSessionId, + sessionParams: resolvedSessionParams, + sessionDisplayId: resolvedSessionId, + provider, + biller: resolvePiBiller(runtimeEnv, provider), + model, + billingType: "unknown", + costUsd: attempt.parsed.usage.costUsd, + resultJson: { + stdout: attempt.proc.stdout, + stderr: attempt.proc.stderr + }, + summary: attempt.parsed.finalMessage ?? attempt.parsed.messages.join("\n\n").trim(), + clearSession: Boolean(clearSessionOnMissingSession) + }; + }; + const initial = await runAttempt(sessionPath); + const initialFailed = !initial.proc.timedOut && ((initial.proc.exitCode ?? 0) !== 0 || initial.parsed.errors.length > 0); + if (canResumeSession && initialFailed && isPiUnknownSessionError(initial.proc.stdout, initial.rawStderr)) { + await onLog( + "stdout", + `[taskcore] Pi session "${runtimeSessionId}" is unavailable; retrying with a fresh session. +` + ); + const newSessionPath = buildSessionPath(agent.id, (/* @__PURE__ */ new Date()).toISOString()); + try { + await fs21.writeFile(newSessionPath, "", { flag: "wx" }); + } catch (err) { + if (err.code !== "EEXIST") { + throw err; + } + } + const retry = await runAttempt(newSessionPath); + return toResult(retry, true); + } + return toResult(initial); +} + +// packages/adapters/pi-local/src/server/skills.ts +import fs22 from "node:fs/promises"; +import os19 from "node:os"; +import path28 from "node:path"; +import { fileURLToPath as fileURLToPath13 } from "node:url"; +var __moduleDir12 = path28.dirname(fileURLToPath13(import.meta.url)); +function asString8(value) { + return typeof value === "string" && value.trim().length > 0 ? value.trim() : null; +} +function resolvePiSkillsHome(config3) { + const env2 = typeof config3.env === "object" && config3.env !== null && !Array.isArray(config3.env) ? config3.env : {}; + const configuredHome = asString8(env2.HOME); + const home = configuredHome ? path28.resolve(configuredHome) : os19.homedir(); + return path28.join(home, ".pi", "agent", "skills"); +} +async function buildPiSkillSnapshot(config3) { + const availableEntries = await readTaskcoreRuntimeSkillEntries(config3, __moduleDir12); + const desiredSkills = resolveTaskcoreDesiredSkillNames(config3, availableEntries); + const skillsHome = resolvePiSkillsHome(config3); + const installed = await readInstalledSkillTargets(skillsHome); + return buildPersistentSkillSnapshot({ + adapterType: "pi_local", + availableEntries, + desiredSkills, + installed, + skillsHome, + locationLabel: "~/.pi/agent/skills", + missingDetail: "Configured but not currently linked into the Pi skills home.", + externalConflictDetail: "Skill name is occupied by an external installation.", + externalDetail: "Installed outside Taskcore management." + }); +} +async function listPiSkills(ctx) { + return buildPiSkillSnapshot(ctx.config); +} +async function syncPiSkills(ctx, desiredSkills) { + const availableEntries = await readTaskcoreRuntimeSkillEntries(ctx.config, __moduleDir12); + const desiredSet = /* @__PURE__ */ new Set([ + ...desiredSkills, + ...availableEntries.filter((entry) => entry.required).map((entry) => entry.key) + ]); + const skillsHome = resolvePiSkillsHome(ctx.config); + await fs22.mkdir(skillsHome, { recursive: true }); + const installed = await readInstalledSkillTargets(skillsHome); + const availableByRuntimeName = new Map(availableEntries.map((entry) => [entry.runtimeName, entry])); + for (const available of availableEntries) { + if (!desiredSet.has(available.key)) continue; + const target = path28.join(skillsHome, available.runtimeName); + await ensureTaskcoreSkillSymlink(available.source, target); + } + for (const [name, installedEntry] of installed.entries()) { + const available = availableByRuntimeName.get(name); + if (!available) continue; + if (desiredSet.has(available.key)) continue; + if (installedEntry.targetPath !== available.source) continue; + await fs22.unlink(path28.join(skillsHome, name)).catch(() => { + }); + } + return buildPiSkillSnapshot(ctx.config); +} + +// packages/adapters/pi-local/src/server/test.ts +function summarizeStatus7(checks) { + if (checks.some((check3) => check3.level === "error")) return "fail"; + if (checks.some((check3) => check3.level === "warn")) return "warn"; + return "pass"; +} +function firstNonEmptyLine12(text3) { + return text3.split(/\r?\n/).map((line3) => line3.trim()).find(Boolean) ?? ""; +} +function summarizeProbeDetail6(stdout, stderr, parsedError) { + const raw = parsedError?.trim() || firstNonEmptyLine12(stderr) || firstNonEmptyLine12(stdout); + if (!raw) return null; + const clean3 = raw.replace(/\s+/g, " ").trim(); + const max = 240; + return clean3.length > max ? `${clean3.slice(0, max - 1)}...` : clean3; +} +function normalizeEnv4(input) { + if (typeof input !== "object" || input === null || Array.isArray(input)) return {}; + const env2 = {}; + for (const [key, value] of Object.entries(input)) { + if (typeof value === "string") env2[key] = value; + } + return env2; +} +var PI_AUTH_REQUIRED_RE = /(?:auth(?:entication)?\s+required|api\s*key|invalid\s*api\s*key|not\s+logged\s+in|free\s+usage\s+exceeded)/i; +var PI_STALE_PACKAGE_RE = /pi-driver|npm:\s*pi-driver/i; +function buildPiModelDiscoveryFailureCheck(message2) { + if (PI_STALE_PACKAGE_RE.test(message2)) { + return { + code: "pi_package_install_failed", + level: "warn", + message: "Pi startup failed while installing configured package `npm:pi-driver`.", + detail: message2, + hint: "Remove `npm:pi-driver` from ~/.pi/agent/settings.json or set adapter env HOME to a clean Pi profile, then retry `pi --list-models`." + }; + } + return { + code: "pi_models_discovery_failed", + level: "warn", + message: message2, + hint: "Run `pi --list-models` manually to verify provider auth and config." + }; +} +async function testEnvironment7(ctx) { + const checks = []; + const config3 = parseObject(ctx.config); + const command = asString(config3.command, "pi"); + const cwd = asString(config3.cwd, process.cwd()); + try { + await ensureAbsoluteDirectory(cwd, { createIfMissing: false }); + checks.push({ + code: "pi_cwd_valid", + level: "info", + message: `Working directory is valid: ${cwd}` + }); + } catch (err) { + checks.push({ + code: "pi_cwd_invalid", + level: "error", + message: err instanceof Error ? err.message : "Invalid working directory", + detail: cwd + }); + } + const envConfig = parseObject(config3.env); + const env2 = {}; + for (const [key, value] of Object.entries(envConfig)) { + if (typeof value === "string") env2[key] = value; + } + const runtimeEnv = normalizeEnv4(ensurePathInEnv({ ...process.env, ...env2 })); + const cwdInvalid = checks.some((check3) => check3.code === "pi_cwd_invalid"); + if (cwdInvalid) { + checks.push({ + code: "pi_command_skipped", + level: "warn", + message: "Skipped command check because working directory validation failed.", + detail: command + }); + } else { + try { + await ensureCommandResolvable(command, cwd, runtimeEnv); + checks.push({ + code: "pi_command_resolvable", + level: "info", + message: `Command is executable: ${command}` + }); + } catch (err) { + checks.push({ + code: "pi_command_unresolvable", + level: "error", + message: err instanceof Error ? err.message : "Command is not executable", + detail: command + }); + } + } + const canRunProbe = checks.every((check3) => check3.code !== "pi_cwd_invalid" && check3.code !== "pi_command_unresolvable"); + if (canRunProbe) { + try { + const discovered = await discoverPiModelsCached({ command, cwd, env: runtimeEnv }); + if (discovered.length > 0) { + checks.push({ + code: "pi_models_discovered", + level: "info", + message: `Discovered ${discovered.length} model(s) from Pi.` + }); + } else { + checks.push({ + code: "pi_models_empty", + level: "warn", + message: "Pi returned no models.", + hint: "Run `pi --list-models` and verify provider authentication." + }); + } + } catch (err) { + checks.push( + buildPiModelDiscoveryFailureCheck( + err instanceof Error ? err.message : "Pi model discovery failed." + ) + ); + } + } + const configuredModel = asString(config3.model, "").trim(); + if (!configuredModel) { + checks.push({ + code: "pi_model_required", + level: "error", + message: "Pi requires a configured model in provider/model format.", + hint: "Set adapterConfig.model using an ID from `pi --list-models`." + }); + } else if (canRunProbe) { + try { + const discovered = await discoverPiModelsCached({ command, cwd, env: runtimeEnv }); + const modelExists = discovered.some((m5) => m5.id === configuredModel); + if (modelExists) { + checks.push({ + code: "pi_model_configured", + level: "info", + message: `Configured model: ${configuredModel}` + }); + } else { + checks.push({ + code: "pi_model_not_found", + level: "warn", + message: `Configured model "${configuredModel}" not found in available models.`, + hint: "Run `pi --list-models` and choose a currently available provider/model ID." + }); + } + } catch { + checks.push({ + code: "pi_model_configured", + level: "info", + message: `Configured model: ${configuredModel}` + }); + } + } + if (canRunProbe && configuredModel) { + const provider = configuredModel.includes("/") ? configuredModel.slice(0, configuredModel.indexOf("/")) : ""; + const modelId = configuredModel.includes("/") ? configuredModel.slice(configuredModel.indexOf("/") + 1) : configuredModel; + const thinking = asString(config3.thinking, "").trim(); + const extraArgs = (() => { + const fromExtraArgs = asStringArray(config3.extraArgs); + if (fromExtraArgs.length > 0) return fromExtraArgs; + return asStringArray(config3.args); + })(); + const args = ["-p", "Respond with hello.", "--mode", "json"]; + if (provider) args.push("--provider", provider); + if (modelId) args.push("--model", modelId); + if (thinking) args.push("--thinking", thinking); + args.push("--tools", "read"); + if (extraArgs.length > 0) args.push(...extraArgs); + try { + const probe = await runChildProcess( + `pi-envtest-${Date.now()}-${Math.random().toString(16).slice(2)}`, + command, + args, + { + cwd, + env: runtimeEnv, + timeoutSec: 60, + graceSec: 5, + onLog: async () => { + } + } + ); + const parsed = parsePiJsonl(probe.stdout); + const detail = summarizeProbeDetail6(probe.stdout, probe.stderr, parsed.errors[0] ?? null); + const authEvidence = `${parsed.errors.join("\n")} +${probe.stdout} +${probe.stderr}`.trim(); + if (probe.timedOut) { + checks.push({ + code: "pi_hello_probe_timed_out", + level: "warn", + message: "Pi hello probe timed out.", + hint: "Retry the probe. If this persists, run Pi manually in this working directory." + }); + } else if ((probe.exitCode ?? 1) === 0 && parsed.errors.length === 0) { + const summary = (parsed.finalMessage || parsed.messages.join(" ")).trim(); + const hasHello = /\bhello\b/i.test(summary); + checks.push({ + code: hasHello ? "pi_hello_probe_passed" : "pi_hello_probe_unexpected_output", + level: hasHello ? "info" : "warn", + message: hasHello ? "Pi hello probe succeeded." : "Pi probe ran but did not return `hello` as expected.", + ...summary ? { detail: summary.replace(/\s+/g, " ").trim().slice(0, 240) } : {}, + ...hasHello ? {} : { + hint: "Run `pi --mode json` manually and prompt `Respond with hello` to inspect output." + } + }); + } else if (PI_AUTH_REQUIRED_RE.test(authEvidence)) { + checks.push({ + code: "pi_hello_probe_auth_required", + level: "warn", + message: "Pi is installed, but provider authentication is not ready.", + ...detail ? { detail } : {}, + hint: "Set provider API key environment variable (e.g., ANTHROPIC_API_KEY, XAI_API_KEY) and retry." + }); + } else { + checks.push({ + code: "pi_hello_probe_failed", + level: "error", + message: "Pi hello probe failed.", + ...detail ? { detail } : {}, + hint: "Run `pi --mode json` manually in this working directory to debug." + }); + } + } catch (err) { + checks.push({ + code: "pi_hello_probe_failed", + level: "error", + message: "Pi hello probe failed.", + detail: err instanceof Error ? err.message : String(err), + hint: "Run `pi --mode json` manually in this working directory to debug." + }); + } + } + return { + adapterType: ctx.adapterType, + status: summarizeStatus7(checks), + checks, + testedAt: (/* @__PURE__ */ new Date()).toISOString() + }; +} + +// packages/adapters/pi-local/src/server/index.ts +function readNonEmptyString7(value) { + return typeof value === "string" && value.trim().length > 0 ? value.trim() : null; +} +var sessionCodec6 = { + deserialize(raw) { + if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return null; + const record2 = raw; + const sessionId = readNonEmptyString7(record2.sessionId) ?? readNonEmptyString7(record2.session_id) ?? readNonEmptyString7(record2.session); + if (!sessionId) return null; + const cwd = readNonEmptyString7(record2.cwd) ?? readNonEmptyString7(record2.workdir) ?? readNonEmptyString7(record2.folder); + return { + sessionId, + ...cwd ? { cwd } : {} + }; + }, + serialize(params) { + if (!params) return null; + const sessionId = readNonEmptyString7(params.sessionId) ?? readNonEmptyString7(params.session_id) ?? readNonEmptyString7(params.session); + if (!sessionId) return null; + const cwd = readNonEmptyString7(params.cwd) ?? readNonEmptyString7(params.workdir) ?? readNonEmptyString7(params.folder); + return { + sessionId, + ...cwd ? { cwd } : {} + }; + }, + getDisplayId(params) { + if (!params) return null; + return readNonEmptyString7(params.sessionId) ?? readNonEmptyString7(params.session_id) ?? readNonEmptyString7(params.session); + } +}; + +// packages/adapters/pi-local/src/index.ts +var agentConfigurationDoc7 = `# pi_local agent configuration + +Adapter: pi_local + +Use when: +- You want Taskcore to run Pi (the AI coding agent) locally as the agent runtime +- You want provider/model routing in Pi format (--provider --model ) +- You want Pi session resume across heartbeats via --session +- You need Pi's tool set (read, bash, edit, write, grep, find, ls) + +Don't use when: +- You need webhook-style external invocation (use openclaw_gateway or http) +- You only need one-shot shell commands (use process) +- Pi CLI is not installed on the machine + +Core fields: +- cwd (string, optional): default absolute working directory fallback for the agent process (created if missing when possible) +- instructionsFilePath (string, optional): absolute path to a markdown instructions file appended to system prompt via --append-system-prompt +- promptTemplate (string, optional): user prompt template passed via -p flag +- model (string, required): Pi model id in provider/model format (for example xai/grok-4) +- thinking (string, optional): thinking level (off, minimal, low, medium, high, xhigh) +- command (string, optional): defaults to "pi" +- env (object, optional): KEY=VALUE environment variables + +Operational fields: +- timeoutSec (number, optional): run timeout in seconds +- graceSec (number, optional): SIGTERM grace period in seconds + +Notes: +- Pi supports multiple providers and models. Use \`pi --list-models\` to list available options. +- Taskcore requires an explicit \`model\` value for \`pi_local\` agents. +- Sessions are stored in ~/.pi/taskcores/ and resumed with --session. +- All tools (read, bash, edit, write, grep, find, ls) are enabled by default. +- Agent instructions are appended to Pi's system prompt via --append-system-prompt, while the user task is sent via -p. +`; + +// node_modules/.pnpm/@paperclipai+adapter-utils@2026.403.0/node_modules/@paperclipai/adapter-utils/dist/server-utils.js +import { spawn as spawn3 } from "node:child_process"; +import { constants as fsConstants3, promises as fs23 } from "node:fs"; +import path29 from "node:path"; +var runningProcesses2 = /* @__PURE__ */ new Map(); +var MAX_CAPTURE_BYTES2 = 4 * 1024 * 1024; +var MAX_EXCERPT_BYTES2 = 32 * 1024; +var PAPERCLIP_SKILL_ROOT_RELATIVE_CANDIDATES = [ + "../../skills", + "../../../../../skills" +]; +function parseObject3(value) { + if (typeof value !== "object" || value === null || Array.isArray(value)) { + return {}; + } + return value; +} +function asString9(value, fallback) { + return typeof value === "string" && value.length > 0 ? value : fallback; +} +function asBoolean3(value, fallback) { + return typeof value === "boolean" ? value : fallback; +} +function appendWithCap2(prev, chunk, cap = MAX_CAPTURE_BYTES2) { + const combined = prev + chunk; + return combined.length > cap ? combined.slice(combined.length - cap) : combined; +} +function resolvePathValue2(obj, dottedPath) { + const parts = dottedPath.split("."); + let cursor2 = obj; + for (const part of parts) { + if (typeof cursor2 !== "object" || cursor2 === null || Array.isArray(cursor2)) { + return ""; + } + cursor2 = cursor2[part]; + } + if (cursor2 === null || cursor2 === void 0) + return ""; + if (typeof cursor2 === "string") + return cursor2; + if (typeof cursor2 === "number" || typeof cursor2 === "boolean") + return String(cursor2); + try { + return JSON.stringify(cursor2); + } catch { + return ""; + } +} +function renderTemplate2(template, data2) { + return template.replace(/{{\s*([a-zA-Z0-9_.-]+)\s*}}/g, (_, path53) => resolvePathValue2(data2, path53)); +} +function buildPaperclipEnv(agent) { + const resolveHostForUrl = (rawHost) => { + const host = rawHost.trim(); + if (!host || host === "0.0.0.0" || host === "::") + return "localhost"; + if (host.includes(":") && !host.startsWith("[") && !host.endsWith("]")) + return `[${host}]`; + return host; + }; + const vars = { + PAPERCLIP_AGENT_ID: agent.id, + PAPERCLIP_COMPANY_ID: agent.companyId + }; + const runtimeHost = resolveHostForUrl(process.env.PAPERCLIP_LISTEN_HOST ?? process.env.HOST ?? "localhost"); + const runtimePort = process.env.PAPERCLIP_LISTEN_PORT ?? process.env.PORT ?? "3100"; + const apiUrl = process.env.PAPERCLIP_API_URL ?? `http://${runtimeHost}:${runtimePort}`; + vars.PAPERCLIP_API_URL = apiUrl; + return vars; +} +function defaultPathForPlatform2() { + if (process.platform === "win32") { + return "C:\\Windows\\System32;C:\\Windows;C:\\Windows\\System32\\Wbem"; + } + return "/usr/local/bin:/opt/homebrew/bin:/usr/local/sbin:/usr/bin:/bin:/usr/sbin:/sbin"; +} +function windowsPathExts2(env2) { + return (env2.PATHEXT ?? ".EXE;.CMD;.BAT;.COM").split(";").filter(Boolean); +} +async function pathExists3(candidate) { + try { + await fs23.access(candidate, process.platform === "win32" ? fsConstants3.F_OK : fsConstants3.X_OK); + return true; + } catch { + return false; + } +} +async function resolveCommandPath2(command, cwd, env2) { + const hasPathSeparator = command.includes("/") || command.includes("\\"); + if (hasPathSeparator) { + const absolute = path29.isAbsolute(command) ? command : path29.resolve(cwd, command); + return await pathExists3(absolute) ? absolute : null; + } + const pathValue = env2.PATH ?? env2.Path ?? ""; + const delimiter = process.platform === "win32" ? ";" : ":"; + const dirs = pathValue.split(delimiter).filter(Boolean); + const exts = process.platform === "win32" ? windowsPathExts2(env2) : [""]; + const hasExtension = process.platform === "win32" && path29.extname(command).length > 0; + for (const dir of dirs) { + const candidates = process.platform === "win32" ? hasExtension ? [path29.join(dir, command)] : exts.map((ext) => path29.join(dir, `${command}${ext}`)) : [path29.join(dir, command)]; + for (const candidate of candidates) { + if (await pathExists3(candidate)) + return candidate; + } + } + return null; +} +function quoteForCmd2(arg) { + if (!arg.length) + return '""'; + const escaped = arg.replace(/"/g, '""'); + return /[\s"&<>|^()]/.test(escaped) ? `"${escaped}"` : escaped; +} +async function resolveSpawnTarget2(command, args, cwd, env2) { + const resolved = await resolveCommandPath2(command, cwd, env2); + const executable = resolved ?? command; + if (process.platform !== "win32") { + return { command: executable, args }; + } + if (/\.(cmd|bat)$/i.test(executable)) { + const shell = env2.ComSpec || process.env.ComSpec || "cmd.exe"; + const commandLine = [quoteForCmd2(executable), ...args.map(quoteForCmd2)].join(" "); + return { + command: shell, + args: ["/d", "/s", "/c", commandLine] + }; + } + return { command: executable, args }; +} +function ensurePathInEnv2(env2) { + if (typeof env2.PATH === "string" && env2.PATH.length > 0) + return env2; + if (typeof env2.Path === "string" && env2.Path.length > 0) + return env2; + return { ...env2, PATH: defaultPathForPlatform2() }; +} +async function ensureAbsoluteDirectory2(cwd, opts = {}) { + if (!path29.isAbsolute(cwd)) { + throw new Error(`Working directory must be an absolute path: "${cwd}"`); + } + const assertDirectory = async () => { + const stats = await fs23.stat(cwd); + if (!stats.isDirectory()) { + throw new Error(`Working directory is not a directory: "${cwd}"`); + } + }; + try { + await assertDirectory(); + return; + } catch (err) { + const code = err.code; + if (!opts.createIfMissing || code !== "ENOENT") { + if (code === "ENOENT") { + throw new Error(`Working directory does not exist: "${cwd}"`); + } + throw err instanceof Error ? err : new Error(String(err)); + } + } + try { + await fs23.mkdir(cwd, { recursive: true }); + await assertDirectory(); + } catch (err) { + const reason = err instanceof Error ? err.message : String(err); + throw new Error(`Could not create working directory "${cwd}": ${reason}`); + } +} +async function resolvePaperclipSkillsDir(moduleDir, additionalCandidates = []) { + const candidates = [ + ...PAPERCLIP_SKILL_ROOT_RELATIVE_CANDIDATES.map((relativePath) => path29.resolve(moduleDir, relativePath)), + ...additionalCandidates.map((candidate) => path29.resolve(candidate)) + ]; + const seenRoots = /* @__PURE__ */ new Set(); + for (const root of candidates) { + if (seenRoots.has(root)) + continue; + seenRoots.add(root); + const isDirectory = await fs23.stat(root).then((stats) => stats.isDirectory()).catch(() => false); + if (isDirectory) + return root; + } + return null; +} +async function listPaperclipSkillEntries(moduleDir, additionalCandidates = []) { + const root = await resolvePaperclipSkillsDir(moduleDir, additionalCandidates); + if (!root) + return []; + try { + const entries2 = await fs23.readdir(root, { withFileTypes: true }); + return entries2.filter((entry) => entry.isDirectory()).map((entry) => ({ + key: `paperclipai/paperclip/${entry.name}`, + runtimeName: entry.name, + source: path29.join(root, entry.name), + required: true, + requiredReason: "Bundled Paperclip skills are always available for local adapters." + })); + } catch { + return []; + } +} +function normalizeConfiguredPaperclipRuntimeSkills(value) { + if (!Array.isArray(value)) + return []; + const out = []; + for (const rawEntry of value) { + const entry = parseObject3(rawEntry); + const key = asString9(entry.key, asString9(entry.name, "")).trim(); + const runtimeName = asString9(entry.runtimeName, asString9(entry.name, "")).trim(); + const source = asString9(entry.source, "").trim(); + if (!key || !runtimeName || !source) + continue; + out.push({ + key, + runtimeName, + source, + required: asBoolean3(entry.required, false), + requiredReason: typeof entry.requiredReason === "string" && entry.requiredReason.trim().length > 0 ? entry.requiredReason.trim() : null + }); + } + return out; +} +async function readPaperclipRuntimeSkillEntries(config3, moduleDir, additionalCandidates = []) { + const configuredEntries = normalizeConfiguredPaperclipRuntimeSkills(config3.paperclipRuntimeSkills); + if (configuredEntries.length > 0) + return configuredEntries; + return listPaperclipSkillEntries(moduleDir, additionalCandidates); +} +function readPaperclipSkillSyncPreference(config3) { + const raw = config3.paperclipSkillSync; + if (typeof raw !== "object" || raw === null || Array.isArray(raw)) { + return { explicit: false, desiredSkills: [] }; + } + const syncConfig = raw; + const desiredValues = syncConfig.desiredSkills; + const desired = Array.isArray(desiredValues) ? desiredValues.filter((value) => typeof value === "string").map((value) => value.trim()).filter(Boolean) : []; + return { + explicit: Object.prototype.hasOwnProperty.call(raw, "desiredSkills"), + desiredSkills: Array.from(new Set(desired)) + }; +} +function canonicalizeDesiredPaperclipSkillReference(reference, availableEntries) { + const normalizedReference = reference.trim().toLowerCase(); + if (!normalizedReference) + return ""; + const exactKey = availableEntries.find((entry) => entry.key.trim().toLowerCase() === normalizedReference); + if (exactKey) + return exactKey.key; + const byRuntimeName = availableEntries.filter((entry) => typeof entry.runtimeName === "string" && entry.runtimeName.trim().toLowerCase() === normalizedReference); + if (byRuntimeName.length === 1) + return byRuntimeName[0].key; + const slugMatches = availableEntries.filter((entry) => entry.key.trim().toLowerCase().split("/").pop() === normalizedReference); + if (slugMatches.length === 1) + return slugMatches[0].key; + return normalizedReference; +} +function resolvePaperclipDesiredSkillNames(config3, availableEntries) { + const preference = readPaperclipSkillSyncPreference(config3); + const requiredSkills = availableEntries.filter((entry) => entry.required).map((entry) => entry.key); + if (!preference.explicit) { + return Array.from(new Set(requiredSkills)); + } + const desiredSkills = preference.desiredSkills.map((reference) => canonicalizeDesiredPaperclipSkillReference(reference, availableEntries)).filter(Boolean); + return Array.from(/* @__PURE__ */ new Set([...requiredSkills, ...desiredSkills])); +} +async function runChildProcess2(runId, command, args, opts) { + const onLogError = opts.onLogError ?? ((err, id, msg) => console.warn({ err, runId: id }, msg)); + return new Promise((resolve4, reject) => { + const rawMerged = { ...process.env, ...opts.env }; + const CLAUDE_CODE_NESTING_VARS = [ + "CLAUDECODE", + "CLAUDE_CODE_ENTRYPOINT", + "CLAUDE_CODE_SESSION", + "CLAUDE_CODE_PARENT_SESSION" + ]; + for (const key of CLAUDE_CODE_NESTING_VARS) { + delete rawMerged[key]; + } + const mergedEnv = ensurePathInEnv2(rawMerged); + void resolveSpawnTarget2(command, args, opts.cwd, mergedEnv).then((target) => { + const child = spawn3(target.command, target.args, { + cwd: opts.cwd, + env: mergedEnv, + shell: false, + stdio: [opts.stdin != null ? "pipe" : "ignore", "pipe", "pipe"] + }); + const startedAt = (/* @__PURE__ */ new Date()).toISOString(); + if (opts.stdin != null && child.stdin) { + child.stdin.write(opts.stdin); + child.stdin.end(); + } + if (typeof child.pid === "number" && child.pid > 0 && opts.onSpawn) { + void opts.onSpawn({ pid: child.pid, startedAt }).catch((err) => { + onLogError(err, runId, "failed to record child process metadata"); + }); + } + runningProcesses2.set(runId, { child, graceSec: opts.graceSec }); + let timedOut = false; + let stdout = ""; + let stderr = ""; + let logChain = Promise.resolve(); + const timeout = opts.timeoutSec > 0 ? setTimeout(() => { + timedOut = true; + child.kill("SIGTERM"); + setTimeout(() => { + if (!child.killed) { + child.kill("SIGKILL"); + } + }, Math.max(1, opts.graceSec) * 1e3); + }, opts.timeoutSec * 1e3) : null; + child.stdout?.on("data", (chunk) => { + const text3 = String(chunk); + stdout = appendWithCap2(stdout, text3); + logChain = logChain.then(() => opts.onLog("stdout", text3)).catch((err) => onLogError(err, runId, "failed to append stdout log chunk")); + }); + child.stderr?.on("data", (chunk) => { + const text3 = String(chunk); + stderr = appendWithCap2(stderr, text3); + logChain = logChain.then(() => opts.onLog("stderr", text3)).catch((err) => onLogError(err, runId, "failed to append stderr log chunk")); + }); + child.on("error", (err) => { + if (timeout) + clearTimeout(timeout); + runningProcesses2.delete(runId); + const errno = err.code; + const pathValue = mergedEnv.PATH ?? mergedEnv.Path ?? ""; + const msg = errno === "ENOENT" ? `Failed to start command "${command}" in "${opts.cwd}". Verify adapter command, working directory, and PATH (${pathValue}).` : `Failed to start command "${command}" in "${opts.cwd}": ${err.message}`; + reject(new Error(msg)); + }); + child.on("close", (code, signal) => { + if (timeout) + clearTimeout(timeout); + runningProcesses2.delete(runId); + void logChain.finally(() => { + resolve4({ + exitCode: code, + signal, + timedOut, + stdout, + stderr, + pid: child.pid ?? null, + startedAt + }); + }); + }); + }).catch(reject); + }); +} + +// node_modules/.pnpm/hermes-paperclip-adapter@0.2.1/node_modules/hermes-paperclip-adapter/dist/shared/constants.js +var ADAPTER_TYPE = "hermes_local"; +var HERMES_CLI = "hermes"; +var DEFAULT_TIMEOUT_SEC = 300; +var DEFAULT_GRACE_SEC = 10; +var DEFAULT_MODEL = "anthropic/claude-sonnet-4"; +var VALID_PROVIDERS = [ + "auto", + "openrouter", + "nous", + "openai-codex", + "copilot", + "copilot-acp", + "anthropic", + "huggingface", + "zai", + "kimi-coding", + "minimax", + "minimax-cn", + "kilocode" +]; +var MODEL_PREFIX_PROVIDER_HINTS = [ + // OpenAI-native models + ["gpt-4", "openai-codex"], + ["gpt-5", "copilot"], + ["o1-", "openai-codex"], + ["o3-", "openai-codex"], + ["o4-", "openai-codex"], + // Anthropic models + ["claude", "anthropic"], + // Google models (via openrouter or direct) + ["gemini", "auto"], + // Nous models + ["hermes-", "nous"], + // Z.AI / GLM models + ["glm-", "zai"], + // Kimi / Moonshot + ["moonshot", "kimi-coding"], + ["kimi", "kimi-coding"], + // MiniMax + ["minimax", "minimax"], + // DeepSeek + ["deepseek", "auto"], + // Meta Llama + ["llama", "auto"], + // Qwen + ["qwen", "auto"], + // Mistral + ["mistral", "auto"], + // HuggingFace models (org/model format) + ["huggingface/", "huggingface"] +]; + +// node_modules/.pnpm/hermes-paperclip-adapter@0.2.1/node_modules/hermes-paperclip-adapter/dist/server/detect-model.js +import { readFile as readFile2 } from "node:fs/promises"; +import { join } from "node:path"; +import { homedir } from "node:os"; +async function detectModel(configPath) { + const filePath = configPath ?? join(homedir(), ".hermes", "config.yaml"); + let content; + try { + content = await readFile2(filePath, "utf-8"); + } catch { + return null; + } + return parseModelFromConfig(content); +} +function parseModelFromConfig(content) { + const lines = content.split("\n"); + let model = ""; + let provider = ""; + let baseUrl = ""; + let apiMode = ""; + let inModelSection = false; + let modelSectionIndent = 0; + for (const line3 of lines) { + const trimmed = line3.trimEnd(); + const indent = line3.length - line3.trimStart().length; + if (/^model:\s*$/.test(trimmed) && indent === 0) { + inModelSection = true; + modelSectionIndent = 0; + continue; + } + if (inModelSection && indent <= modelSectionIndent && trimmed && !trimmed.startsWith("#")) { + inModelSection = false; + } + if (inModelSection) { + const match = trimmed.match(/^\s*(\w+)\s*:\s*(.+)$/); + if (match) { + const key = match[1]; + const val = match[2].trim().replace(/#.*$/, "").trim().replace(/^['"]|['"]$/g, ""); + if (key === "default") + model = val; + if (key === "provider") + provider = val; + if (key === "base_url") + baseUrl = val; + if (key === "api_mode") + apiMode = val; + } + } + } + if (!model) + return null; + return { model, provider, baseUrl, apiMode, source: "config" }; +} +function inferProviderFromModel(model) { + const lower = model.toLowerCase(); + const bareName = lower.includes("/") ? lower.split("/").pop() : lower; + for (const [prefix, hint] of MODEL_PREFIX_PROVIDER_HINTS) { + if (bareName.startsWith(prefix)) { + return hint; + } + } + return void 0; +} +function resolveProvider(options) { + const { explicitProvider, detectedProvider, detectedModel, model } = options; + if (explicitProvider && VALID_PROVIDERS.includes(explicitProvider)) { + return { provider: explicitProvider, resolvedFrom: "adapterConfig" }; + } + if (detectedProvider && detectedModel && VALID_PROVIDERS.includes(detectedProvider) && // Config model matches requested model (exact or case-insensitive) + detectedModel.toLowerCase() === model?.toLowerCase()) { + return { provider: detectedProvider, resolvedFrom: "hermesConfig" }; + } + if (model) { + const inferred = inferProviderFromModel(model); + if (inferred) { + return { provider: inferred, resolvedFrom: "modelInference" }; + } + } + return { provider: "auto", resolvedFrom: "auto" }; +} + +// node_modules/.pnpm/hermes-paperclip-adapter@0.2.1/node_modules/hermes-paperclip-adapter/dist/server/execute.js +function cfgString(v5) { + return typeof v5 === "string" && v5.length > 0 ? v5 : void 0; +} +function cfgNumber(v5) { + return typeof v5 === "number" ? v5 : void 0; +} +function cfgBoolean(v5) { + return typeof v5 === "boolean" ? v5 : void 0; +} +function cfgStringArray(v5) { + return Array.isArray(v5) && v5.every((i5) => typeof i5 === "string") ? v5 : void 0; +} +var DEFAULT_PROMPT_TEMPLATE = `You are "{{agentName}}", an AI agent employee in a Paperclip-managed company. + +IMPORTANT: Use \`terminal\` tool with \`curl\` for ALL Paperclip API calls (web_extract and browser cannot access localhost). + +Your Paperclip identity: + Agent ID: {{agentId}} + Company ID: {{companyId}} + API Base: {{paperclipApiUrl}} + +{{#taskId}} +## Assigned Task + +Issue ID: {{taskId}} +Title: {{taskTitle}} + +{{taskBody}} + +## Workflow + +1. Work on the task using your tools +2. When done, mark the issue as completed: + \`curl -s -X PATCH "{{paperclipApiUrl}}/issues/{{taskId}}" -H "Content-Type: application/json" -d '{"status":"done"}'\` +3. Post a completion comment on the issue summarizing what you did: + \`curl -s -X POST "{{paperclipApiUrl}}/issues/{{taskId}}/comments" -H "Content-Type: application/json" -d '{"body":"DONE: "}'\` +4. If this issue has a parent (check the issue body or comments for references like TRA-XX), post a brief notification on the parent issue so the parent owner knows: + \`curl -s -X POST "{{paperclipApiUrl}}/issues/PARENT_ISSUE_ID/comments" -H "Content-Type: application/json" -d '{"body":"{{agentName}} completed {{taskId}}. Summary: "}'\` +{{/taskId}} + +{{#commentId}} +## Comment on This Issue + +Someone commented. Read it: + \`curl -s "{{paperclipApiUrl}}/issues/{{taskId}}/comments/{{commentId}}" | python3 -m json.tool\` + +Address the comment, POST a reply if needed, then continue working. +{{/commentId}} + +{{#noTask}} +## Heartbeat Wake \u2014 Check for Work + +1. List ALL open issues assigned to you (todo, backlog, in_progress): + \`curl -s "{{paperclipApiUrl}}/companies/{{companyId}}/issues?assigneeAgentId={{agentId}}" | python3 -c "import sys,json;issues=json.loads(sys.stdin.read());[print(f'{i["identifier"]} {i["status"]:>12} {i["priority"]:>6} {i["title"]}') for i in issues if i['status'] not in ('done','cancelled')]" \` + +2. If issues found, pick the highest priority one that is not done/cancelled and work on it: + - Read the issue details: \`curl -s "{{paperclipApiUrl}}/issues/ISSUE_ID"\` + - Do the work in the project directory: {{projectName}} + - When done, mark complete and post a comment (see Workflow steps 2-4 above) + +3. If no issues assigned to you, check for unassigned issues: + \`curl -s "{{paperclipApiUrl}}/companies/{{companyId}}/issues?status=backlog" | python3 -c "import sys,json;issues=json.loads(sys.stdin.read());[print(f'{i["identifier"]} {i["title"]}') for i in issues if not i.get('assigneeAgentId')]" \` + If you find a relevant issue, assign it to yourself: + \`curl -s -X PATCH "{{paperclipApiUrl}}/issues/ISSUE_ID" -H "Content-Type: application/json" -d '{"assigneeAgentId":"{{agentId}}","status":"todo"}'\` + +4. If truly nothing to do, report briefly what you checked. +{{/noTask}}`; +function buildPrompt(ctx, config3) { + const template = cfgString(config3.promptTemplate) || DEFAULT_PROMPT_TEMPLATE; + const taskId = cfgString(ctx.config?.taskId); + const taskTitle = cfgString(ctx.config?.taskTitle) || ""; + const taskBody = cfgString(ctx.config?.taskBody) || ""; + const commentId = cfgString(ctx.config?.commentId) || ""; + const wakeReason = cfgString(ctx.config?.wakeReason) || ""; + const agentName = ctx.agent?.name || "Hermes Agent"; + const companyName = cfgString(ctx.config?.companyName) || ""; + const projectName = cfgString(ctx.config?.projectName) || ""; + let paperclipApiUrl = cfgString(config3.paperclipApiUrl) || process.env.PAPERCLIP_API_URL || "http://127.0.0.1:3100/api"; + if (!paperclipApiUrl.endsWith("/api")) { + paperclipApiUrl = paperclipApiUrl.replace(/\/+$/, "") + "/api"; + } + const vars = { + agentId: ctx.agent?.id || "", + agentName, + companyId: ctx.agent?.companyId || "", + companyName, + runId: ctx.runId || "", + taskId: taskId || "", + taskTitle, + taskBody, + commentId, + wakeReason, + projectName, + paperclipApiUrl + }; + let rendered = template; + rendered = rendered.replace(/\{\{#taskId\}\}([\s\S]*?)\{\{\/taskId\}\}/g, taskId ? "$1" : ""); + rendered = rendered.replace(/\{\{#noTask\}\}([\s\S]*?)\{\{\/noTask\}\}/g, taskId ? "" : "$1"); + rendered = rendered.replace(/\{\{#commentId\}\}([\s\S]*?)\{\{\/commentId\}\}/g, commentId ? "$1" : ""); + return renderTemplate2(rendered, vars); +} +var SESSION_ID_REGEX = /^session_id:\s*(\S+)/m; +var SESSION_ID_REGEX_LEGACY = /session[_ ](?:id|saved)[:\s]+([a-zA-Z0-9_-]+)/i; +var TOKEN_USAGE_REGEX = /tokens?[:\s]+(\d+)\s*(?:input|in)\b.*?(\d+)\s*(?:output|out)\b/i; +var COST_REGEX = /(?:cost|spent)[:\s]*\$?([\d.]+)/i; +function cleanResponse(raw) { + return raw.split("\n").filter((line3) => { + const t5 = line3.trim(); + if (!t5) + return true; + if (t5.startsWith("[tool]") || t5.startsWith("[hermes]") || t5.startsWith("[paperclip]")) + return false; + if (t5.startsWith("session_id:")) + return false; + if (/^\[\d{4}-\d{2}-\d{2}T/.test(t5)) + return false; + if (/^\[done\]\s*┊/.test(t5)) + return false; + if (/^┊\s*[\p{Emoji_Presentation}]/u.test(t5) && !/^┊\s*💬/.test(t5)) + return false; + if (new RegExp("^\\p{Emoji_Presentation}\\s*(Completed|Running|Error)?\\s*$", "u").test(t5)) + return false; + return true; + }).map((line3) => { + let t5 = line3.replace(/^[\s]*┊\s*💬\s*/, "").trim(); + t5 = t5.replace(/^\[done\]\s*/, "").trim(); + return t5; + }).join("\n").replace(/\n{3,}/g, "\n\n").trim(); +} +function parseHermesOutput(stdout, stderr) { + const combined = stdout + "\n" + stderr; + const result = {}; + const sessionMatch = stdout.match(SESSION_ID_REGEX); + if (sessionMatch?.[1]) { + result.sessionId = sessionMatch?.[1] ?? null; + const sessionLineIdx = stdout.lastIndexOf("\nsession_id:"); + if (sessionLineIdx > 0) { + result.response = cleanResponse(stdout.slice(0, sessionLineIdx)); + } + } else { + const legacyMatch = combined.match(SESSION_ID_REGEX_LEGACY); + if (legacyMatch?.[1]) { + result.sessionId = legacyMatch?.[1] ?? null; + } + const cleaned = cleanResponse(stdout); + if (cleaned.length > 0) { + result.response = cleaned; + } + } + const usageMatch = combined.match(TOKEN_USAGE_REGEX); + if (usageMatch) { + result.usage = { + inputTokens: parseInt(usageMatch[1], 10) || 0, + outputTokens: parseInt(usageMatch[2], 10) || 0 + }; + } + const costMatch = combined.match(COST_REGEX); + if (costMatch?.[1]) { + result.costUsd = parseFloat(costMatch[1]); + } + if (stderr.trim()) { + const errorLines = stderr.split("\n").filter((line3) => /error|exception|traceback|failed/i.test(line3)).filter((line3) => !/INFO|DEBUG|warn/i.test(line3)); + if (errorLines.length > 0) { + result.errorMessage = errorLines.slice(0, 5).join("\n"); + } + } + return result; +} +async function execute8(ctx) { + const config3 = ctx.agent?.adapterConfig ?? {}; + const hermesCmd = cfgString(config3.hermesCommand) || HERMES_CLI; + const model = cfgString(config3.model) || DEFAULT_MODEL; + const timeoutSec = cfgNumber(config3.timeoutSec) || DEFAULT_TIMEOUT_SEC; + const graceSec = cfgNumber(config3.graceSec) || DEFAULT_GRACE_SEC; + const toolsets = cfgString(config3.toolsets) || cfgStringArray(config3.enabledToolsets)?.join(","); + const extraArgs = cfgStringArray(config3.extraArgs); + const persistSession = cfgBoolean(config3.persistSession) !== false; + const worktreeMode = cfgBoolean(config3.worktreeMode) === true; + const checkpoints = cfgBoolean(config3.checkpoints) === true; + let detectedConfig = null; + const explicitProvider = cfgString(config3.provider); + if (!explicitProvider) { + try { + detectedConfig = await detectModel(); + } catch { + } + } + const { provider: resolvedProvider, resolvedFrom } = resolveProvider({ + explicitProvider, + detectedProvider: detectedConfig?.provider, + detectedModel: detectedConfig?.model, + model + }); + const prompt = buildPrompt(ctx, config3); + const useQuiet = cfgBoolean(config3.quiet) !== false; + const args = ["chat", "-q", prompt]; + if (useQuiet) + args.push("-Q"); + if (model) { + args.push("-m", model); + } + if (resolvedProvider !== "auto") { + args.push("--provider", resolvedProvider); + } + if (toolsets) { + args.push("-t", toolsets); + } + if (worktreeMode) + args.push("-w"); + if (checkpoints) + args.push("--checkpoints"); + if (cfgBoolean(config3.verbose) === true) + args.push("-v"); + args.push("--source", "tool"); + args.push("--yolo"); + const prevSessionId = cfgString(ctx.runtime?.sessionParams?.sessionId); + if (persistSession && prevSessionId) { + args.push("--resume", prevSessionId); + } + if (extraArgs?.length) { + args.push(...extraArgs); + } + const env2 = { + ...process.env, + ...buildPaperclipEnv(ctx.agent) + }; + if (ctx.runId) + env2.PAPERCLIP_RUN_ID = ctx.runId; + const taskId = cfgString(ctx.config?.taskId); + if (taskId) + env2.PAPERCLIP_TASK_ID = taskId; + const userEnv = config3.env; + if (userEnv && typeof userEnv === "object") { + Object.assign(env2, userEnv); + } + const cwd = cfgString(config3.cwd) || cfgString(ctx.config?.workspaceDir) || "."; + try { + await ensureAbsoluteDirectory2(cwd); + } catch { + } + await ctx.onLog("stdout", `[hermes] Starting Hermes Agent (model=${model}, provider=${resolvedProvider} [${resolvedFrom}], timeout=${timeoutSec}s) +`); + if (prevSessionId) { + await ctx.onLog("stdout", `[hermes] Resuming session: ${prevSessionId} +`); + } + const wrappedOnLog = async (stream, chunk) => { + if (stream === "stderr") { + const trimmed = chunk.trimEnd(); + const isBenign = /^\[?\d{4}[-/]\d{2}[-/]\d{2}T/.test(trimmed) || // structured timestamps + /^[A-Z]+:\s+(INFO|DEBUG|WARN|WARNING)\b/.test(trimmed) || // log levels + /Successfully registered all tools/.test(trimmed) || /MCP [Ss]erver/.test(trimmed) || /tool registered successfully/.test(trimmed) || /Application initialized/.test(trimmed); + if (isBenign) { + return ctx.onLog("stdout", chunk); + } + } + return ctx.onLog(stream, chunk); + }; + const result = await runChildProcess2(ctx.runId, hermesCmd, args, { + cwd, + env: env2, + timeoutSec, + graceSec, + onLog: wrappedOnLog + }); + const parsed = parseHermesOutput(result.stdout || "", result.stderr || ""); + await ctx.onLog("stdout", `[hermes] Exit code: ${result.exitCode ?? "null"}, timed out: ${result.timedOut} +`); + if (parsed.sessionId) { + await ctx.onLog("stdout", `[hermes] Session: ${parsed.sessionId} +`); + } + const executionResult = { + exitCode: result.exitCode, + signal: result.signal, + timedOut: result.timedOut, + provider: resolvedProvider, + model + }; + if (parsed.errorMessage) { + executionResult.errorMessage = parsed.errorMessage; + } + if (parsed.usage) { + executionResult.usage = parsed.usage; + } + if (parsed.costUsd !== void 0) { + executionResult.costUsd = parsed.costUsd; + } + if (parsed.response) { + executionResult.summary = parsed.response.slice(0, 2e3); + } + executionResult.resultJson = { + result: parsed.response || "", + session_id: parsed.sessionId || null, + usage: parsed.usage || null, + cost_usd: parsed.costUsd ?? null + }; + if (persistSession && parsed.sessionId) { + executionResult.sessionParams = { sessionId: parsed.sessionId }; + executionResult.sessionDisplayId = parsed.sessionId.slice(0, 16); + } + return executionResult; +} + +// node_modules/.pnpm/hermes-paperclip-adapter@0.2.1/node_modules/hermes-paperclip-adapter/dist/server/test.js +import { execFile as execFile2 } from "node:child_process"; +import { promisify as promisify2 } from "node:util"; +var execFileAsync2 = promisify2(execFile2); +function asString10(v5) { + return typeof v5 === "string" ? v5 : void 0; +} +async function checkCliInstalled(command) { + try { + await execFileAsync2(command, ["--version"], { timeout: 1e4 }); + return null; + } catch (err) { + const e5 = err; + if (e5.code === "ENOENT") { + return { + level: "error", + message: `Hermes CLI "${command}" not found in PATH`, + hint: "Install Hermes Agent: pip install hermes-agent", + code: "hermes_cli_not_found" + }; + } + return null; + } +} +async function checkCliVersion(command) { + try { + const { stdout } = await execFileAsync2(command, ["--version"], { + timeout: 1e4 + }); + const version3 = stdout.trim(); + if (version3) { + return { + level: "info", + message: `Hermes Agent version: ${version3}`, + code: "hermes_version" + }; + } + return { + level: "warn", + message: "Could not determine Hermes Agent version", + code: "hermes_version_unknown" + }; + } catch { + return { + level: "warn", + message: "Could not determine Hermes Agent version (hermes --version failed)", + hint: "Make sure the hermes CLI is properly installed and functional", + code: "hermes_version_failed" + }; + } +} +async function checkPython() { + try { + const { stdout } = await execFileAsync2("python3", ["--version"], { + timeout: 5e3 + }); + const version3 = stdout.trim(); + const match = version3.match(/(\d+)\.(\d+)/); + if (match) { + const major = parseInt(match[1], 10); + const minor = parseInt(match[2], 10); + if (major < 3 || major === 3 && minor < 10) { + return { + level: "error", + message: `Python ${version3} found \u2014 Hermes requires Python 3.10+`, + hint: "Upgrade Python to 3.10 or later", + code: "hermes_python_old" + }; + } + } + return null; + } catch { + return { + level: "warn", + message: "python3 not found in PATH", + hint: "Hermes Agent requires Python 3.10+. Install it from python.org", + code: "hermes_python_missing" + }; + } +} +function checkModel(config3) { + const model = asString10(config3.model); + if (!model) { + return { + level: "info", + message: "No model specified \u2014 Hermes will use its configured default model", + hint: "Set a model explicitly in Paperclip only if you want to override your local Hermes configuration.", + code: "hermes_configured_default_model" + }; + } + return { + level: "info", + message: `Model: ${model}`, + code: "hermes_model_configured" + }; +} +function checkApiKeys(config3) { + const envConfig = config3.env ?? {}; + const resolvedEnv = {}; + for (const [key, value] of Object.entries(envConfig)) { + if (typeof value === "string" && value.length > 0) + resolvedEnv[key] = value; + } + const has = (key) => !!(resolvedEnv[key] ?? process.env[key]); + const hasAnthropic = has("ANTHROPIC_API_KEY"); + const hasOpenRouter = has("OPENROUTER_API_KEY"); + const hasOpenAI = has("OPENAI_API_KEY"); + const hasZai = has("ZAI_API_KEY"); + const hasKimi = has("KIMI_API_KEY"); + const hasMiniMax = has("MINIMAX_API_KEY"); + if (!hasAnthropic && !hasOpenRouter && !hasOpenAI && !hasZai && !hasKimi && !hasMiniMax) { + return { + level: "warn", + message: "No LLM API keys found in environment", + hint: "Set API keys in the agent's env secrets or ~/.hermes/.env. Hermes supports: ANTHROPIC_API_KEY, OPENROUTER_API_KEY, OPENAI_API_KEY, ZAI_API_KEY, KIMI_API_KEY, MINIMAX_API_KEY", + code: "hermes_no_api_keys" + }; + } + const providers2 = []; + if (hasAnthropic) + providers2.push("Anthropic"); + if (hasOpenRouter) + providers2.push("OpenRouter"); + if (hasOpenAI) + providers2.push("OpenAI"); + if (hasZai) + providers2.push("Z.AI"); + if (hasKimi) + providers2.push("Kimi"); + if (hasMiniMax) + providers2.push("MiniMax"); + return { + level: "info", + message: `API keys found: ${providers2.join(", ")}`, + code: "hermes_api_keys_found" + }; +} +async function checkProviderConsistency(config3) { + const model = asString10(config3.model); + if (!model) + return null; + const explicitProvider = asString10(config3.provider); + let detectedConfig = null; + try { + detectedConfig = await detectModel(); + } catch { + } + const { provider: resolved, resolvedFrom } = resolveProvider({ + explicitProvider, + detectedProvider: detectedConfig?.provider, + detectedModel: detectedConfig?.model, + model + }); + if (explicitProvider && detectedConfig?.provider && explicitProvider !== detectedConfig.provider) { + return { + level: "warn", + message: `Provider mismatch: adapterConfig has "${explicitProvider}" but ~/.hermes/config.yaml has "${detectedConfig.provider}". Using adapterConfig value.`, + hint: `Model "${model}" may not work correctly with provider "${explicitProvider}". Consider aligning with your Hermes config or removing the explicit provider to use auto-detection.`, + code: "hermes_provider_mismatch" + }; + } + if (!explicitProvider && resolvedFrom !== "auto") { + return { + level: "info", + message: `Provider auto-detected as "${resolved}" (from ${resolvedFrom}) for model "${model}"`, + code: "hermes_provider_detected" + }; + } + if (resolvedFrom === "auto" && !explicitProvider) { + return { + level: "warn", + message: `Could not determine provider for model "${model}" \u2014 will use Hermes auto-detection`, + hint: "Set an explicit provider in the agent config or ensure ~/.hermes/config.yaml has a matching provider for this model.", + code: "hermes_provider_unknown" + }; + } + return null; +} +async function testEnvironment8(ctx) { + const config3 = ctx.config ?? {}; + const command = asString10(config3.hermesCommand) || HERMES_CLI; + const checks = []; + const cliCheck = await checkCliInstalled(command); + if (cliCheck) { + checks.push(cliCheck); + if (cliCheck.level === "error") { + return { + adapterType: ADAPTER_TYPE, + status: "fail", + checks, + testedAt: (/* @__PURE__ */ new Date()).toISOString() + }; + } + } + const versionCheck = await checkCliVersion(command); + if (versionCheck) + checks.push(versionCheck); + const pythonCheck = await checkPython(); + if (pythonCheck) + checks.push(pythonCheck); + const modelCheck = checkModel(config3); + if (modelCheck) + checks.push(modelCheck); + const apiKeyCheck = checkApiKeys(config3); + if (apiKeyCheck) + checks.push(apiKeyCheck); + const providerCheck = await checkProviderConsistency(config3); + if (providerCheck) + checks.push(providerCheck); + const hasErrors = checks.some((c5) => c5.level === "error"); + const hasWarnings = checks.some((c5) => c5.level === "warn"); + return { + adapterType: ADAPTER_TYPE, + status: hasErrors ? "fail" : hasWarnings ? "warn" : "pass", + checks, + testedAt: (/* @__PURE__ */ new Date()).toISOString() + }; +} + +// node_modules/.pnpm/hermes-paperclip-adapter@0.2.1/node_modules/hermes-paperclip-adapter/dist/server/skills.js +import fs24 from "node:fs/promises"; +import os20 from "node:os"; +import path30 from "node:path"; +import { fileURLToPath as fileURLToPath14 } from "node:url"; +var __moduleDir13 = path30.dirname(fileURLToPath14(import.meta.url)); +function asString11(value) { + return typeof value === "string" && value.trim().length > 0 ? value.trim() : null; +} +function resolveHermesHome(config3) { + const env2 = typeof config3.env === "object" && config3.env !== null && !Array.isArray(config3.env) ? config3.env : {}; + const configuredHome = asString11(env2.HOME); + return configuredHome ? path30.resolve(configuredHome) : os20.homedir(); +} +function parseSkillFrontmatter(content) { + const match = content.match(/^---\s*\n([\s\S]*?)\n---/); + if (!match) + return {}; + const frontmatter = {}; + for (const line3 of match[1].split("\n")) { + const idx = line3.indexOf(":"); + if (idx === -1) + continue; + const key = line3.slice(0, idx).trim(); + let val = line3.slice(idx + 1).trim(); + if (typeof val === "string" && (val.startsWith('"') && val.endsWith('"') || val.startsWith("'") && val.endsWith("'"))) { + val = val.slice(1, -1); + } + frontmatter[key] = val; + } + return frontmatter; +} +async function scanHermesSkills(skillsHome) { + const entries2 = []; + try { + const categories = await fs24.readdir(skillsHome, { withFileTypes: true }); + for (const cat of categories) { + if (!cat.isDirectory()) + continue; + const catPath = path30.join(skillsHome, cat.name); + const topLevelSkillMd = path30.join(catPath, "SKILL.md"); + if (await fs24.stat(topLevelSkillMd).catch(() => null)) { + entries2.push(await buildSkillEntry(cat.name, topLevelSkillMd, cat.name)); + } + const items = await fs24.readdir(catPath, { withFileTypes: true }).catch(() => []); + for (const item of items) { + if (!item.isDirectory()) + continue; + const skillMd = path30.join(catPath, item.name, "SKILL.md"); + if (await fs24.stat(skillMd).catch(() => null)) { + const key = item.name; + entries2.push(await buildSkillEntry(key, skillMd, `${cat.name}/${item.name}`)); + } + } + } + } catch { + } + return entries2.sort((a5, b6) => a5.key.localeCompare(b6.key)); +} +async function buildSkillEntry(key, skillMdPath, categoryPath) { + let description = null; + try { + const content = await fs24.readFile(skillMdPath, "utf8"); + const fm = parseSkillFrontmatter(content); + description = fm.description ?? null; + } catch { + } + return { + key, + runtimeName: key, + desired: true, + // Hermes loads all available skills + managed: false, + state: "installed", + origin: "user_installed", + originLabel: "Hermes skill", + locationLabel: `~/.hermes/skills/${categoryPath}`, + readOnly: true, + // Hermes manages its own skills — Paperclip can't toggle them + sourcePath: skillMdPath, + targetPath: null, + detail: description + }; +} +async function buildHermesSkillSnapshot(config3) { + const home = resolveHermesHome(config3); + const hermesSkillsHome = path30.join(home, ".hermes", "skills"); + const paperclipEntries = await readPaperclipRuntimeSkillEntries(config3, __moduleDir13); + const desiredSkills = resolvePaperclipDesiredSkillNames(config3, paperclipEntries); + const desiredSet = new Set(desiredSkills); + const availableByKey = new Map(paperclipEntries.map((e5) => [e5.key, e5])); + const hermesSkillEntries = await scanHermesSkills(hermesSkillsHome); + const hermesKeys = new Set(hermesSkillEntries.map((e5) => e5.key)); + const entries2 = []; + const warnings = []; + for (const entry of paperclipEntries) { + const desired = desiredSet.has(entry.key); + entries2.push({ + key: entry.key, + runtimeName: entry.runtimeName, + desired, + managed: true, + state: desired ? "configured" : "available", + origin: entry.required ? "paperclip_required" : "company_managed", + originLabel: entry.required ? "Required by Paperclip" : "Managed by Paperclip", + readOnly: false, + sourcePath: entry.source, + targetPath: null, + detail: desired ? "Will be available on the next run via Hermes skill loading." : null, + required: Boolean(entry.required), + requiredReason: entry.requiredReason ?? null + }); + } + for (const entry of hermesSkillEntries) { + if (availableByKey.has(entry.key)) + continue; + entries2.push(entry); + } + for (const desiredSkill of desiredSkills) { + if (availableByKey.has(desiredSkill) || hermesKeys.has(desiredSkill)) + continue; + warnings.push(`Desired skill "${desiredSkill}" is not available in Paperclip or Hermes skills.`); + entries2.push({ + key: desiredSkill, + runtimeName: null, + desired: true, + managed: true, + state: "missing", + origin: "external_unknown", + originLabel: "External or unavailable", + readOnly: false, + sourcePath: null, + targetPath: null, + detail: "Cannot find this skill in Paperclip or ~/.hermes/skills/." + }); + } + return { + adapterType: "hermes_local", + supported: true, + mode: "persistent", + desiredSkills, + entries: entries2, + warnings + }; +} +async function listHermesSkills(ctx) { + return buildHermesSkillSnapshot(ctx.config); +} +async function syncHermesSkills(ctx, _desiredSkills) { + return buildHermesSkillSnapshot(ctx.config); +} + +// node_modules/.pnpm/hermes-paperclip-adapter@0.2.1/node_modules/hermes-paperclip-adapter/dist/server/index.js +function readNonEmptyString8(value) { + return typeof value === "string" && value.trim().length > 0 ? value.trim() : null; +} +var sessionCodec7 = { + deserialize(raw) { + if (typeof raw !== "object" || raw === null || Array.isArray(raw)) + return null; + const record2 = raw; + const sessionId = readNonEmptyString8(record2.sessionId) ?? readNonEmptyString8(record2.session_id); + if (!sessionId) + return null; + return { sessionId }; + }, + serialize(params) { + if (!params) + return null; + const sessionId = readNonEmptyString8(params.sessionId) ?? readNonEmptyString8(params.session_id); + if (!sessionId) + return null; + return { sessionId }; + }, + getDisplayId(params) { + if (!params) + return null; + return readNonEmptyString8(params.sessionId) ?? readNonEmptyString8(params.session_id); + } +}; + +// node_modules/.pnpm/hermes-paperclip-adapter@0.2.1/node_modules/hermes-paperclip-adapter/dist/index.js +var models7 = []; +var agentConfigurationDoc8 = `# Hermes Agent Configuration + +Hermes Agent is a full-featured AI agent by Nous Research with 30+ native +tools, persistent memory, session persistence, skills, and MCP support. + +## Prerequisites + +- Python 3.10+ installed +- Hermes Agent installed: \`pip install hermes-agent\` +- At least one LLM API key configured in ~/.hermes/.env + +## Core Configuration + +| Field | Type | Default | Description | +|-------|------|---------|-------------| +| model | string | (Hermes configured default) | Optional explicit model in provider/model format. Leave blank to use Hermes's configured default model. | +| provider | string | (auto) | API provider: auto, openrouter, nous, openai-codex, zai, kimi-coding, minimax, minimax-cn. Usually not needed \u2014 Hermes auto-detects from model name. | +| timeoutSec | number | 300 | Execution timeout in seconds | +| graceSec | number | 10 | Grace period after SIGTERM before SIGKILL | + +## Tool Configuration + +| Field | Type | Default | Description | +|-------|------|---------|-------------| +| toolsets | string | (all) | Comma-separated toolsets to enable (e.g. "terminal,file,web") | + +## Session & Workspace + +| Field | Type | Default | Description | +|-------|------|---------|-------------| +| persistSession | boolean | true | Resume sessions across heartbeats | +| worktreeMode | boolean | false | Use git worktree for isolated changes | +| checkpoints | boolean | false | Enable filesystem checkpoints | + +## Advanced + +| Field | Type | Default | Description | +|-------|------|---------|-------------| +| hermesCommand | string | hermes | Path to hermes CLI binary | +| verbose | boolean | false | Enable verbose output | +| extraArgs | string[] | [] | Additional CLI arguments | +| env | object | {} | Extra environment variables | +| promptTemplate | string | (default) | Custom prompt template with {{variable}} placeholders | + +## Available Template Variables + +- \`{{agentId}}\` \u2014 Paperclip agent ID +- \`{{agentName}}\` \u2014 Agent display name +- \`{{companyId}}\` \u2014 Paperclip company ID +- \`{{companyName}}\` \u2014 Company display name +- \`{{runId}}\` \u2014 Current heartbeat run ID +- \`{{taskId}}\` \u2014 Current task/issue ID (if assigned) +- \`{{taskTitle}}\` \u2014 Task title (if assigned) +- \`{{taskBody}}\` \u2014 Task description (if assigned) +- \`{{projectName}}\` \u2014 Project name (if scoped to a project) +`; + +// server/src/adapters/builtin-adapter-types.ts +var BUILTIN_ADAPTER_TYPES = /* @__PURE__ */ new Set([ + "claude_local", + "codex_local", + "cursor", + "gemini_local", + "openclaw_gateway", + "opencode_local", + "pi_local", + "hermes_local", + "process", + "http" +]); + +// server/src/adapters/plugin-loader.ts +import fs26 from "node:fs"; +import path32 from "node:path"; + +// server/src/services/adapter-plugin-store.ts +import fs25 from "node:fs"; +import path31 from "node:path"; +import os21 from "node:os"; +var TASKCORE_DIR = path31.join(os21.homedir(), ".taskcore"); +var ADAPTER_PLUGINS_DIR = path31.join(TASKCORE_DIR, "adapter-plugins"); +var ADAPTER_PLUGINS_STORE_PATH = path31.join(TASKCORE_DIR, "adapter-plugins.json"); +var ADAPTER_SETTINGS_PATH = path31.join(TASKCORE_DIR, "adapter-settings.json"); +var storeCache = null; +var settingsCache = null; +function ensureDirs() { + fs25.mkdirSync(ADAPTER_PLUGINS_DIR, { recursive: true }); + const pkgJsonPath = path31.join(ADAPTER_PLUGINS_DIR, "package.json"); + if (!fs25.existsSync(pkgJsonPath)) { + fs25.writeFileSync(pkgJsonPath, JSON.stringify({ + name: "taskcore-adapter-plugins", + version: "0.0.0", + private: true, + description: "Managed directory for Taskcore external adapter plugins. Do not edit manually." + }, null, 2) + "\n"); + } +} +function readStore() { + if (storeCache) return storeCache; + try { + const raw = fs25.readFileSync(ADAPTER_PLUGINS_STORE_PATH, "utf-8"); + const parsed = JSON.parse(raw); + storeCache = Array.isArray(parsed) ? parsed : []; + } catch { + storeCache = []; + } + return storeCache; +} +function writeStore(records) { + ensureDirs(); + fs25.writeFileSync(ADAPTER_PLUGINS_STORE_PATH, JSON.stringify(records, null, 2), "utf-8"); + storeCache = records; +} +function readSettings() { + if (settingsCache) return settingsCache; + try { + const raw = fs25.readFileSync(ADAPTER_SETTINGS_PATH, "utf-8"); + const parsed = JSON.parse(raw); + settingsCache = parsed && Array.isArray(parsed.disabledTypes) ? parsed : { disabledTypes: [] }; + } catch { + settingsCache = { disabledTypes: [] }; + } + return settingsCache; +} +function writeSettings(settings) { + ensureDirs(); + fs25.writeFileSync(ADAPTER_SETTINGS_PATH, JSON.stringify(settings, null, 2), "utf-8"); + settingsCache = settings; +} +function listAdapterPlugins() { + return readStore(); +} +function addAdapterPlugin(record2) { + const store = [...readStore()]; + const idx = store.findIndex((r5) => r5.type === record2.type); + if (idx >= 0) { + store[idx] = record2; + } else { + store.push(record2); + } + writeStore(store); +} +function removeAdapterPlugin(type) { + const store = [...readStore()]; + const idx = store.findIndex((r5) => r5.type === type); + if (idx < 0) return false; + store.splice(idx, 1); + writeStore(store); + return true; +} +function getAdapterPluginByType(type) { + return readStore().find((r5) => r5.type === type); +} +function getAdapterPluginsDir() { + ensureDirs(); + return ADAPTER_PLUGINS_DIR; +} +function getDisabledAdapterTypes() { + return readSettings().disabledTypes; +} +function setAdapterDisabled(type, disabled) { + const settings = { ...readSettings(), disabledTypes: [...readSettings().disabledTypes] }; + const idx = settings.disabledTypes.indexOf(type); + if (disabled && idx < 0) { + settings.disabledTypes.push(type); + writeSettings(settings); + return true; + } + if (!disabled && idx >= 0) { + settings.disabledTypes.splice(idx, 1); + writeSettings(settings); + return true; + } + return false; +} + +// server/src/adapters/plugin-loader.ts +var uiParserCache = /* @__PURE__ */ new Map(); +function getOrExtractUiParserSource(adapterType) { + const cached4 = uiParserCache.get(adapterType); + if (cached4) return cached4; + const record2 = getAdapterPluginByType(adapterType); + if (!record2) return void 0; + const packageDir = resolvePackageDir(record2); + const source = extractUiParserSource(packageDir, record2.packageName); + if (source) { + uiParserCache.set(adapterType, source); + logger.info( + { type: adapterType, packageName: record2.packageName, origin: "lazy" }, + "UI parser extracted on-demand (cache miss)" + ); + } + return source; +} +function resolvePackageDir(record2) { + return record2.localPath ? path32.resolve(record2.localPath) : path32.resolve(getAdapterPluginsDir(), "node_modules", record2.packageName); +} +function resolvePackageEntryPoint(packageDir) { + const pkgJsonPath = path32.join(packageDir, "package.json"); + const pkg2 = JSON.parse(fs26.readFileSync(pkgJsonPath, "utf-8")); + if (pkg2.exports && typeof pkg2.exports === "object" && pkg2.exports["."]) { + const exp = pkg2.exports["."]; + return typeof exp === "string" ? exp : exp.import ?? exp.default ?? "index.js"; + } + return pkg2.main ?? "index.js"; +} +var SUPPORTED_PARSER_CONTRACT = "1"; +function extractUiParserSource(packageDir, packageName) { + const pkgJsonPath = path32.join(packageDir, "package.json"); + const pkg2 = JSON.parse(fs26.readFileSync(pkgJsonPath, "utf-8")); + if (!pkg2.exports || typeof pkg2.exports !== "object" || !pkg2.exports["./ui-parser"]) { + return void 0; + } + const contractVersion = pkg2.taskcore?.adapterUiParser; + if (contractVersion) { + const major = contractVersion.split(".")[0]; + if (major !== SUPPORTED_PARSER_CONTRACT) { + logger.warn( + { packageName, contractVersion, supported: `${SUPPORTED_PARSER_CONTRACT}.x` }, + "Adapter declares unsupported UI parser contract version \u2014 skipping UI parser" + ); + return void 0; + } + } else { + logger.info( + { packageName }, + "Adapter has ./ui-parser export but no taskcore.adapterUiParser version \u2014 loading anyway (future versions may require it)" + ); + } + const uiParserExp = pkg2.exports["./ui-parser"]; + const uiParserFile = typeof uiParserExp === "string" ? uiParserExp : uiParserExp.import ?? uiParserExp.default; + const uiParserPath = path32.resolve(packageDir, uiParserFile); + if (!uiParserPath.startsWith(packageDir + path32.sep) && uiParserPath !== packageDir) { + logger.warn( + { packageName, uiParserFile }, + "UI parser path escapes package directory \u2014 skipping" + ); + return void 0; + } + if (!fs26.existsSync(uiParserPath)) { + return void 0; + } + try { + const source = fs26.readFileSync(uiParserPath, "utf-8"); + logger.info( + { packageName, uiParserFile, size: source.length }, + `Loaded UI parser from adapter package${contractVersion ? "" : " (no version declared)"}` + ); + return source; + } catch (err) { + logger.warn({ err, packageName, uiParserFile }, "Failed to read UI parser from adapter package"); + return void 0; + } +} +function validateAdapterModule(mod, packageName) { + const m5 = mod; + const createServerAdapter = m5.createServerAdapter; + if (typeof createServerAdapter !== "function") { + throw new Error( + `Package "${packageName}" does not export createServerAdapter(). Ensure the package's main entry exports a createServerAdapter function.` + ); + } + const adapterModule = createServerAdapter(); + if (!adapterModule || !adapterModule.type) { + throw new Error( + `createServerAdapter() from "${packageName}" returned an invalid module (missing "type").` + ); + } + return adapterModule; +} +async function loadExternalAdapterPackage(packageName, localPath) { + const packageDir = localPath ? path32.resolve(localPath) : path32.resolve(getAdapterPluginsDir(), "node_modules", packageName); + const entryPoint = resolvePackageEntryPoint(packageDir); + const modulePath = path32.resolve(packageDir, entryPoint); + const uiParserSource = extractUiParserSource(packageDir, packageName); + logger.info({ packageName, packageDir, entryPoint, modulePath, hasUiParser: !!uiParserSource }, "Loading external adapter package"); + const mod = await import(modulePath); + const adapterModule = validateAdapterModule(mod, packageName); + if (uiParserSource) { + uiParserCache.set(adapterModule.type, uiParserSource); + } + return adapterModule; +} +async function loadFromRecord(record2) { + try { + return await loadExternalAdapterPackage(record2.packageName, record2.localPath); + } catch (err) { + logger.warn( + { err, packageName: record2.packageName, type: record2.type }, + "Failed to dynamically load external adapter; skipping" + ); + return null; + } +} +async function reloadExternalAdapter(type) { + const record2 = getAdapterPluginByType(type); + if (!record2) return null; + const packageDir = resolvePackageDir(record2); + const entryPoint = resolvePackageEntryPoint(packageDir); + const modulePath = path32.resolve(packageDir, entryPoint); + const fileUrl = `file://${modulePath}`; + try { + const bunCache = globalThis.Bun?.__moduleCache; + if (bunCache) { + bunCache.delete(fileUrl); + bunCache.delete(modulePath); + } + } catch { + } + const cacheBustUrl = `${fileUrl}?t=${Date.now()}`; + logger.info( + { type, packageName: record2.packageName, modulePath, cacheBustUrl }, + "Reloading external adapter (cache bust)" + ); + const mod = await import(cacheBustUrl); + const adapterModule = validateAdapterModule(mod, record2.packageName); + uiParserCache.delete(type); + const uiParserSource = extractUiParserSource(packageDir, record2.packageName); + if (uiParserSource) { + uiParserCache.set(adapterModule.type, uiParserSource); + } + logger.info( + { type, packageName: record2.packageName, hasUiParser: !!uiParserSource }, + "Successfully reloaded external adapter" + ); + return adapterModule; +} +async function buildExternalAdapters() { + const results = []; + const storeRecords = listAdapterPlugins(); + for (const record2 of storeRecords) { + const adapter = await loadFromRecord(record2); + if (adapter) { + results.push(adapter); + } + } + if (results.length > 0) { + logger.info( + { count: results.length, adapters: results.map((a5) => a5.type) }, + "Loaded external adapters from plugin store" + ); + } + return results; +} + +// server/src/adapters/utils.ts +var runningProcesses3 = runningProcesses; +var MAX_EXCERPT_BYTES3 = MAX_EXCERPT_BYTES; +var parseObject4 = parseObject; +var asString12 = asString; +var asNumber3 = asNumber; +var asBoolean4 = asBoolean; +var asStringArray2 = asStringArray; +var appendWithCap3 = appendWithCap; +var renderTemplate3 = renderTemplate; +var redactEnvForLogs2 = redactEnvForLogs; +var buildTaskcoreEnv2 = buildTaskcoreEnv; +var ensurePathInEnv3 = ensurePathInEnv; +var ensureAbsoluteDirectory3 = ensureAbsoluteDirectory; +var ensureCommandResolvable2 = ensureCommandResolvable; +var resolveCommandForLogs2 = resolveCommandForLogs; +function buildInvocationEnvForLogs2(env2, options = {}) { + const maybeBuildInvocationEnvForLogs = buildInvocationEnvForLogs; + if (typeof maybeBuildInvocationEnvForLogs === "function") { + return maybeBuildInvocationEnvForLogs(env2, options); + } + const merged = { ...env2 }; + const runtimeEnv = options.runtimeEnv ?? {}; + for (const key of options.includeRuntimeKeys ?? []) { + if (key in merged) continue; + const value = runtimeEnv[key]; + if (typeof value !== "string" || value.length === 0) continue; + merged[key] = value; + } + const resolvedCommand = options.resolvedCommand?.trim(); + if (resolvedCommand) { + merged[options.resolvedCommandEnvKey ?? "TASKCORE_RESOLVED_COMMAND"] = resolvedCommand; + } + return redactEnvForLogs2(merged); +} +var _runChildProcess = runChildProcess; +async function runChildProcess3(runId, command, args, opts) { + return _runChildProcess(runId, command, args, { + ...opts, + onLogError: (err, id, msg) => logger.warn({ err, runId: id }, msg) + }); +} + +// server/src/adapters/process/execute.ts +async function execute9(ctx) { + const { runId, agent, config: config3, onLog, onMeta } = ctx; + const command = asString12(config3.command, ""); + if (!command) throw new Error("Process adapter missing command"); + const args = asStringArray2(config3.args); + const cwd = asString12(config3.cwd, process.cwd()); + const envConfig = parseObject4(config3.env); + const env2 = { ...buildTaskcoreEnv2(agent) }; + for (const [k5, v5] of Object.entries(envConfig)) { + if (typeof v5 === "string") env2[k5] = v5; + } + const runtimeEnv = ensurePathInEnv3({ ...process.env, ...env2 }); + const resolvedCommand = await resolveCommandForLogs2(command, cwd, runtimeEnv); + const loggedEnv = buildInvocationEnvForLogs2(env2, { + runtimeEnv, + includeRuntimeKeys: ["HOME"], + resolvedCommand + }); + const timeoutSec = asNumber3(config3.timeoutSec, 0); + const graceSec = asNumber3(config3.graceSec, 15); + if (onMeta) { + await onMeta({ + adapterType: "process", + command: resolvedCommand, + cwd, + commandArgs: args, + env: loggedEnv + }); + } + const proc = await runChildProcess3(runId, command, args, { + cwd, + env: env2, + timeoutSec, + graceSec, + onLog + }); + if (proc.timedOut) { + return { + exitCode: proc.exitCode, + signal: proc.signal, + timedOut: true, + errorMessage: `Timed out after ${timeoutSec}s` + }; + } + if ((proc.exitCode ?? 0) !== 0) { + return { + exitCode: proc.exitCode, + signal: proc.signal, + timedOut: false, + errorMessage: `Process exited with code ${proc.exitCode ?? -1}`, + resultJson: { + stdout: proc.stdout, + stderr: proc.stderr + } + }; + } + return { + exitCode: proc.exitCode, + signal: proc.signal, + timedOut: false, + resultJson: { + stdout: proc.stdout, + stderr: proc.stderr + } + }; +} + +// server/src/adapters/process/test.ts +function summarizeStatus8(checks) { + if (checks.some((check3) => check3.level === "error")) return "fail"; + if (checks.some((check3) => check3.level === "warn")) return "warn"; + return "pass"; +} +async function testEnvironment9(ctx) { + const checks = []; + const config3 = parseObject4(ctx.config); + const command = asString12(config3.command, ""); + const cwd = asString12(config3.cwd, process.cwd()); + if (!command) { + checks.push({ + code: "process_command_missing", + level: "error", + message: "Process adapter requires a command.", + hint: "Set adapterConfig.command to an executable command." + }); + } else { + checks.push({ + code: "process_command_present", + level: "info", + message: `Configured command: ${command}` + }); + } + try { + await ensureAbsoluteDirectory3(cwd); + checks.push({ + code: "process_cwd_valid", + level: "info", + message: `Working directory is valid: ${cwd}` + }); + } catch (err) { + checks.push({ + code: "process_cwd_invalid", + level: "error", + message: err instanceof Error ? err.message : "Invalid working directory", + detail: cwd + }); + } + if (command) { + const envConfig = parseObject4(config3.env); + const env2 = {}; + for (const [key, value] of Object.entries(envConfig)) { + if (typeof value === "string") env2[key] = value; + } + const runtimeEnv = ensurePathInEnv3({ ...process.env, ...env2 }); + try { + await ensureCommandResolvable2(command, cwd, runtimeEnv); + checks.push({ + code: "process_command_resolvable", + level: "info", + message: `Command is executable: ${command}` + }); + } catch (err) { + checks.push({ + code: "process_command_unresolvable", + level: "error", + message: err instanceof Error ? err.message : "Command is not executable", + detail: command + }); + } + } + return { + adapterType: ctx.adapterType, + status: summarizeStatus8(checks), + checks, + testedAt: (/* @__PURE__ */ new Date()).toISOString() + }; +} + +// server/src/adapters/process/index.ts +var processAdapter = { + type: "process", + execute: execute9, + testEnvironment: testEnvironment9, + models: [], + agentConfigurationDoc: `# process agent configuration + +Adapter: process + +Core fields: +- command (string, required): command to execute +- args (string[] | string, optional): command arguments +- cwd (string, optional): absolute working directory +- env (object, optional): KEY=VALUE environment variables + +Operational fields: +- timeoutSec (number, optional): run timeout in seconds +- graceSec (number, optional): SIGTERM grace period in seconds +` +}; + +// server/src/adapters/http/execute.ts +async function execute10(ctx) { + const { config: config3, runId, agent, context } = ctx; + const url2 = asString12(config3.url, ""); + if (!url2) throw new Error("HTTP adapter missing url"); + const method = asString12(config3.method, "POST"); + const timeoutMs = asNumber3(config3.timeoutMs, 0); + const headers = parseObject4(config3.headers); + const payloadTemplate = parseObject4(config3.payloadTemplate); + const body = { ...payloadTemplate, agentId: agent.id, runId, context }; + const controller = new AbortController(); + const timer2 = timeoutMs > 0 ? setTimeout(() => controller.abort(), timeoutMs) : null; + try { + const res = await fetch(url2, { + method, + headers: { + "content-type": "application/json", + ...headers + }, + body: JSON.stringify(body), + ...timer2 ? { signal: controller.signal } : {} + }); + if (!res.ok) { + throw new Error(`HTTP invoke failed with status ${res.status}`); + } + return { + exitCode: 0, + signal: null, + timedOut: false, + summary: `HTTP ${method} ${url2}` + }; + } finally { + if (timer2) clearTimeout(timer2); + } +} + +// server/src/adapters/http/test.ts +function summarizeStatus9(checks) { + if (checks.some((check3) => check3.level === "error")) return "fail"; + if (checks.some((check3) => check3.level === "warn")) return "warn"; + return "pass"; +} +function normalizeMethod(input) { + const trimmed = input.trim(); + return trimmed.length > 0 ? trimmed.toUpperCase() : "POST"; +} +async function testEnvironment10(ctx) { + const checks = []; + const config3 = parseObject4(ctx.config); + const urlValue = asString12(config3.url, ""); + const method = normalizeMethod(asString12(config3.method, "POST")); + if (!urlValue) { + checks.push({ + code: "http_url_missing", + level: "error", + message: "HTTP adapter requires a URL.", + hint: "Set adapterConfig.url to an absolute http(s) endpoint." + }); + return { + adapterType: ctx.adapterType, + status: summarizeStatus9(checks), + checks, + testedAt: (/* @__PURE__ */ new Date()).toISOString() + }; + } + let url2 = null; + try { + url2 = new URL(urlValue); + } catch { + checks.push({ + code: "http_url_invalid", + level: "error", + message: `Invalid URL: ${urlValue}` + }); + } + if (url2 && url2.protocol !== "http:" && url2.protocol !== "https:") { + checks.push({ + code: "http_url_protocol_invalid", + level: "error", + message: `Unsupported URL protocol: ${url2.protocol}`, + hint: "Use an http:// or https:// endpoint." + }); + } + if (url2) { + checks.push({ + code: "http_url_valid", + level: "info", + message: `Configured endpoint: ${url2.toString()}` + }); + } + checks.push({ + code: "http_method_configured", + level: "info", + message: `Configured method: ${method}` + }); + if (url2 && (url2.protocol === "http:" || url2.protocol === "https:")) { + const controller = new AbortController(); + const timeout = setTimeout(() => controller.abort(), 3e3); + try { + const response = await fetch(url2, { + method: "HEAD", + signal: controller.signal + }); + if (!response.ok && response.status !== 405 && response.status !== 501) { + checks.push({ + code: "http_endpoint_probe_unexpected_status", + level: "warn", + message: `Endpoint probe returned HTTP ${response.status}.`, + hint: "Verify the endpoint is reachable from the Taskcore server host." + }); + } else { + checks.push({ + code: "http_endpoint_probe_ok", + level: "info", + message: "Endpoint responded to a HEAD probe." + }); + } + } catch (err) { + checks.push({ + code: "http_endpoint_probe_failed", + level: "warn", + message: err instanceof Error ? err.message : "Endpoint probe failed", + hint: "This may be expected in restricted networks; verify connectivity when invoking runs." + }); + } finally { + clearTimeout(timeout); + } + } + return { + adapterType: ctx.adapterType, + status: summarizeStatus9(checks), + checks, + testedAt: (/* @__PURE__ */ new Date()).toISOString() + }; +} + +// server/src/adapters/http/index.ts +var httpAdapter = { + type: "http", + execute: execute10, + testEnvironment: testEnvironment10, + models: [], + agentConfigurationDoc: `# http agent configuration + +Adapter: http + +Core fields: +- url (string, required): endpoint to invoke +- method (string, optional): HTTP method, default POST +- headers (object, optional): request headers +- payloadTemplate (object, optional): JSON payload template +- timeoutSec (number, optional): request timeout in seconds +` +}; + +// server/src/adapters/registry.ts +var claudeLocalAdapter = { + type: "claude_local", + execute, + testEnvironment, + listSkills: listClaudeSkills, + syncSkills: syncClaudeSkills, + sessionCodec, + sessionManagement: getAdapterSessionManagement("claude_local") ?? void 0, + models, + listModels: listClaudeModels, + supportsLocalAgentJwt: true, + agentConfigurationDoc, + getQuotaWindows +}; +var codexLocalAdapter = { + type: "codex_local", + execute: execute2, + testEnvironment: testEnvironment2, + listSkills: listCodexSkills, + syncSkills: syncCodexSkills, + sessionCodec: sessionCodec2, + sessionManagement: getAdapterSessionManagement("codex_local") ?? void 0, + models: models2, + listModels: listCodexModels, + supportsLocalAgentJwt: true, + agentConfigurationDoc: agentConfigurationDoc2, + getQuotaWindows: getQuotaWindows2 +}; +var cursorLocalAdapter = { + type: "cursor", + execute: execute4, + testEnvironment: testEnvironment4, + listSkills: listCursorSkills, + syncSkills: syncCursorSkills, + sessionCodec: sessionCodec4, + sessionManagement: getAdapterSessionManagement("cursor") ?? void 0, + models: models3, + listModels: listCursorModels, + supportsLocalAgentJwt: true, + agentConfigurationDoc: agentConfigurationDoc3 +}; +var geminiLocalAdapter = { + type: "gemini_local", + execute: execute5, + testEnvironment: testEnvironment5, + listSkills: listGeminiSkills, + syncSkills: syncGeminiSkills, + sessionCodec: sessionCodec5, + sessionManagement: getAdapterSessionManagement("gemini_local") ?? void 0, + models: models4, + supportsLocalAgentJwt: true, + agentConfigurationDoc: agentConfigurationDoc4 +}; +var openclawGatewayAdapter = { + type: "openclaw_gateway", + execute: execute6, + testEnvironment: testEnvironment6, + models: models6, + supportsLocalAgentJwt: false, + agentConfigurationDoc: agentConfigurationDoc6 +}; +var openCodeLocalAdapter = { + type: "opencode_local", + execute: execute3, + testEnvironment: testEnvironment3, + listSkills: listOpenCodeSkills, + syncSkills: syncOpenCodeSkills, + sessionCodec: sessionCodec3, + models: models5, + sessionManagement: getAdapterSessionManagement("opencode_local") ?? void 0, + listModels: listOpenCodeModels, + supportsLocalAgentJwt: true, + agentConfigurationDoc: agentConfigurationDoc5 +}; +var piLocalAdapter = { + type: "pi_local", + execute: execute7, + testEnvironment: testEnvironment7, + listSkills: listPiSkills, + syncSkills: syncPiSkills, + sessionCodec: sessionCodec6, + sessionManagement: getAdapterSessionManagement("pi_local") ?? void 0, + models: [], + listModels: listPiModels, + supportsLocalAgentJwt: true, + agentConfigurationDoc: agentConfigurationDoc7 +}; +var hermesLocalAdapter = { + type: "hermes_local", + execute: execute8, + testEnvironment: testEnvironment8, + sessionCodec: sessionCodec7, + listSkills: listHermesSkills, + syncSkills: syncHermesSkills, + models: models7, + supportsLocalAgentJwt: true, + agentConfigurationDoc: agentConfigurationDoc8, + detectModel: () => detectModel() +}; +var adaptersByType = /* @__PURE__ */ new Map(); +var builtinFallbacks = /* @__PURE__ */ new Map(); +var pausedOverrides = /* @__PURE__ */ new Set(); +function registerBuiltInAdapters() { + for (const adapter of [ + claudeLocalAdapter, + codexLocalAdapter, + openCodeLocalAdapter, + piLocalAdapter, + cursorLocalAdapter, + geminiLocalAdapter, + openclawGatewayAdapter, + hermesLocalAdapter, + processAdapter, + httpAdapter + ]) { + adaptersByType.set(adapter.type, adapter); + } +} +registerBuiltInAdapters(); +var externalAdaptersReady = (async () => { + try { + const externalAdapters = await buildExternalAdapters(); + for (const externalAdapter of externalAdapters) { + const overriding = BUILTIN_ADAPTER_TYPES.has(externalAdapter.type); + if (overriding) { + console.log( + `[taskcore] External adapter "${externalAdapter.type}" overrides built-in adapter` + ); + const existing = adaptersByType.get(externalAdapter.type); + if (existing && !builtinFallbacks.has(externalAdapter.type)) { + builtinFallbacks.set(externalAdapter.type, existing); + } + } + adaptersByType.set( + externalAdapter.type, + { + ...externalAdapter, + sessionManagement: getAdapterSessionManagement(externalAdapter.type) ?? void 0 + } + ); + } + } catch (err) { + console.error("[taskcore] Failed to load external adapters:", err); + } +})(); +function registerServerAdapter(adapter) { + if (BUILTIN_ADAPTER_TYPES.has(adapter.type) && !builtinFallbacks.has(adapter.type)) { + const existing = adaptersByType.get(adapter.type); + if (existing) { + builtinFallbacks.set(adapter.type, existing); + } + } + adaptersByType.set(adapter.type, adapter); +} +function unregisterServerAdapter(type) { + if (type === processAdapter.type || type === httpAdapter.type) return; + if (builtinFallbacks.has(type)) { + pausedOverrides.delete(type); + const fallback = builtinFallbacks.get(type); + if (fallback) { + adaptersByType.set(type, fallback); + } + return; + } + if (BUILTIN_ADAPTER_TYPES.has(type)) { + return; + } + adaptersByType.delete(type); +} +function requireServerAdapter(type) { + const adapter = findActiveServerAdapter(type); + if (!adapter) { + throw new Error(`Unknown adapter type: ${type}`); + } + return adapter; +} +function getServerAdapter(type) { + return findActiveServerAdapter(type) ?? processAdapter; +} +async function listAdapterModels(type) { + const adapter = findActiveServerAdapter(type); + if (!adapter) return []; + if (adapter.listModels) { + const discovered = await adapter.listModels(); + if (discovered.length > 0) return discovered; + } + return adapter.models ?? []; +} +function listServerAdapters() { + return Array.from(adaptersByType.values()); +} +async function detectAdapterModel(type) { + const adapter = findActiveServerAdapter(type); + if (!adapter?.detectModel) return null; + const detected = await adapter.detectModel(); + if (!detected) return null; + return { + model: detected.model, + provider: detected.provider, + source: detected.source, + ...detected.candidates?.length ? { candidates: detected.candidates } : {} + }; +} +function setOverridePaused(type, paused) { + if (!builtinFallbacks.has(type)) return false; + const wasPaused = pausedOverrides.has(type); + if (paused && !wasPaused) { + pausedOverrides.add(type); + console.log(`[taskcore] Override paused for "${type}" \u2014 builtin adapter restored`); + return true; + } + if (!paused && wasPaused) { + pausedOverrides.delete(type); + console.log(`[taskcore] Override resumed for "${type}" \u2014 external adapter active`); + return true; + } + return false; +} +function isOverridePaused(type) { + return pausedOverrides.has(type); +} +function findServerAdapter(type) { + return adaptersByType.get(type) ?? null; +} +function findActiveServerAdapter(type) { + if (pausedOverrides.has(type)) { + const fallback = builtinFallbacks.get(type); + if (fallback) return fallback; + } + return adaptersByType.get(type) ?? null; +} + +// server/src/services/github-fetch.ts +function isGitHubDotCom(hostname3) { + const h5 = hostname3.toLowerCase(); + return h5 === "github.com" || h5 === "www.github.com"; +} +function gitHubApiBase(hostname3) { + return isGitHubDotCom(hostname3) ? "https://api.github.com" : `https://${hostname3}/api/v3`; +} +function resolveRawGitHubUrl(hostname3, owner, repo, ref, filePath) { + const p5 = filePath.replace(/^\/+/, ""); + return isGitHubDotCom(hostname3) ? `https://raw.githubusercontent.com/${owner}/${repo}/${ref}/${p5}` : `https://${hostname3}/raw/${owner}/${repo}/${ref}/${p5}`; +} +async function ghFetch(url2, init2) { + try { + return await fetch(url2, init2); + } catch { + throw unprocessable(`Could not connect to ${new URL(url2).hostname} \u2014 ensure the URL points to a GitHub or GitHub Enterprise instance`); + } +} + +// server/src/services/agents.ts +init_drizzle_orm(); +init_src2(); +import { createHash as createHash8, randomBytes as randomBytes2 } from "node:crypto"; + +// server/src/services/agent-permissions.ts +function defaultPermissionsForRole(role) { + return { + canCreateAgents: role === "ceo" + }; +} +function normalizeAgentPermissions(permissions, role) { + const defaults = defaultPermissionsForRole(role); + if (typeof permissions !== "object" || permissions === null || Array.isArray(permissions)) { + return defaults; + } + const record2 = permissions; + return { + canCreateAgents: typeof record2.canCreateAgents === "boolean" ? record2.canCreateAgents : defaults.canCreateAgents + }; +} + +// server/src/services/agents.ts +function hashToken2(token) { + return createHash8("sha256").update(token).digest("hex"); +} +function createToken() { + return `pcp_${randomBytes2(24).toString("hex")}`; +} +var CONFIG_REVISION_FIELDS = [ + "name", + "role", + "title", + "reportsTo", + "capabilities", + "adapterType", + "adapterConfig", + "runtimeConfig", + "budgetMonthlyCents", + "metadata" +]; +function isPlainRecord2(value) { + return typeof value === "object" && value !== null && !Array.isArray(value); +} +function jsonEqual(left, right) { + return JSON.stringify(left) === JSON.stringify(right); +} +function buildConfigSnapshot(row) { + const adapterConfig = typeof row.adapterConfig === "object" && row.adapterConfig !== null && !Array.isArray(row.adapterConfig) ? sanitizeRecord(row.adapterConfig) : {}; + const runtimeConfig = typeof row.runtimeConfig === "object" && row.runtimeConfig !== null && !Array.isArray(row.runtimeConfig) ? sanitizeRecord(row.runtimeConfig) : {}; + const metadata = typeof row.metadata === "object" && row.metadata !== null && !Array.isArray(row.metadata) ? sanitizeRecord(row.metadata) : row.metadata ?? null; + return { + name: row.name, + role: row.role, + title: row.title, + reportsTo: row.reportsTo, + capabilities: row.capabilities, + adapterType: row.adapterType, + adapterConfig, + runtimeConfig, + budgetMonthlyCents: row.budgetMonthlyCents, + metadata + }; +} +function containsRedactedMarker(value) { + if (value === REDACTED_EVENT_VALUE) return true; + if (Array.isArray(value)) return value.some((item) => containsRedactedMarker(item)); + if (typeof value !== "object" || value === null) return false; + return Object.values(value).some((entry) => containsRedactedMarker(entry)); +} +function hasConfigPatchFields(data2) { + return CONFIG_REVISION_FIELDS.some((field) => Object.prototype.hasOwnProperty.call(data2, field)); +} +function diffConfigSnapshot(before, after) { + return CONFIG_REVISION_FIELDS.filter((field) => !jsonEqual(before[field], after[field])); +} +function configPatchFromSnapshot(snapshot) { + if (!isPlainRecord2(snapshot)) throw unprocessable("Invalid revision snapshot"); + if (typeof snapshot.name !== "string" || snapshot.name.length === 0) { + throw unprocessable("Invalid revision snapshot: name"); + } + if (typeof snapshot.role !== "string" || snapshot.role.length === 0) { + throw unprocessable("Invalid revision snapshot: role"); + } + if (typeof snapshot.adapterType !== "string" || snapshot.adapterType.length === 0) { + throw unprocessable("Invalid revision snapshot: adapterType"); + } + if (typeof snapshot.budgetMonthlyCents !== "number" || !Number.isFinite(snapshot.budgetMonthlyCents)) { + throw unprocessable("Invalid revision snapshot: budgetMonthlyCents"); + } + return { + name: snapshot.name, + role: snapshot.role, + title: typeof snapshot.title === "string" || snapshot.title === null ? snapshot.title : null, + reportsTo: typeof snapshot.reportsTo === "string" || snapshot.reportsTo === null ? snapshot.reportsTo : null, + capabilities: typeof snapshot.capabilities === "string" || snapshot.capabilities === null ? snapshot.capabilities : null, + adapterType: snapshot.adapterType, + adapterConfig: isPlainRecord2(snapshot.adapterConfig) ? snapshot.adapterConfig : {}, + runtimeConfig: isPlainRecord2(snapshot.runtimeConfig) ? snapshot.runtimeConfig : {}, + budgetMonthlyCents: Math.max(0, Math.floor(snapshot.budgetMonthlyCents)), + metadata: isPlainRecord2(snapshot.metadata) || snapshot.metadata === null ? snapshot.metadata : null + }; +} +function hasAgentShortnameCollision(candidateName, existingAgents, options) { + const candidateShortname = normalizeAgentUrlKey(candidateName); + if (!candidateShortname) return false; + return existingAgents.some((agent) => { + if (agent.status === "terminated") return false; + if (options?.excludeAgentId && agent.id === options.excludeAgentId) return false; + return normalizeAgentUrlKey(agent.name) === candidateShortname; + }); +} +function deduplicateAgentName(candidateName, existingAgents) { + if (!hasAgentShortnameCollision(candidateName, existingAgents)) { + return candidateName; + } + for (let i5 = 2; i5 <= 100; i5++) { + const suffixed = `${candidateName} ${i5}`; + if (!hasAgentShortnameCollision(suffixed, existingAgents)) { + return suffixed; + } + } + return `${candidateName} ${Date.now()}`; +} +function agentService(db) { + function currentUtcMonthWindow3(now2 = /* @__PURE__ */ new Date()) { + const year3 = now2.getUTCFullYear(); + const month = now2.getUTCMonth(); + return { + start: new Date(Date.UTC(year3, month, 1, 0, 0, 0, 0)), + end: new Date(Date.UTC(year3, month + 1, 1, 0, 0, 0, 0)) + }; + } + function withUrlKey(row) { + return { + ...row, + urlKey: normalizeAgentUrlKey(row.name) ?? row.id + }; + } + function normalizeAgentRow(row) { + return withUrlKey({ + ...row, + permissions: normalizeAgentPermissions(row.permissions, row.role) + }); + } + async function getMonthlySpendByAgentIds(companyId, agentIds) { + if (agentIds.length === 0) return /* @__PURE__ */ new Map(); + const { start, end } = currentUtcMonthWindow3(); + const rows = await db.select({ + agentId: costEvents.agentId, + spentMonthlyCents: sql`coalesce(sum(${costEvents.costCents}), 0)::int` + }).from(costEvents).where( + and( + eq(costEvents.companyId, companyId), + inArray(costEvents.agentId, agentIds), + gte(costEvents.occurredAt, start), + lt(costEvents.occurredAt, end) + ) + ).groupBy(costEvents.agentId); + return new Map(rows.map((row) => [row.agentId, Number(row.spentMonthlyCents ?? 0)])); + } + async function hydrateAgentSpend(rows) { + const agentIds = rows.map((row) => row.id); + const companyId = rows[0]?.companyId; + if (!companyId || agentIds.length === 0) return rows; + const spendByAgentId = await getMonthlySpendByAgentIds(companyId, agentIds); + return rows.map((row) => ({ + ...row, + spentMonthlyCents: spendByAgentId.get(row.id) ?? 0 + })); + } + async function getById(id) { + const row = await db.select().from(agents).where(eq(agents.id, id)).then((rows) => rows[0] ?? null); + if (!row) return null; + const [hydrated] = await hydrateAgentSpend([row]); + return normalizeAgentRow(hydrated); + } + async function ensureManager(companyId, managerId) { + const manager = await getById(managerId); + if (!manager) throw notFound("Manager not found"); + if (manager.companyId !== companyId) { + throw unprocessable("Manager must belong to same company"); + } + return manager; + } + async function assertNoCycle(agentId, reportsTo) { + if (!reportsTo) return; + if (reportsTo === agentId) throw unprocessable("Agent cannot report to itself"); + let cursor2 = reportsTo; + while (cursor2) { + if (cursor2 === agentId) throw unprocessable("Reporting relationship would create cycle"); + const next = await getById(cursor2); + cursor2 = next?.reportsTo ?? null; + } + } + async function assertCompanyShortnameAvailable(companyId, candidateName, options) { + const candidateShortname = normalizeAgentUrlKey(candidateName); + if (!candidateShortname) return; + const existingAgents = await db.select({ + id: agents.id, + name: agents.name, + status: agents.status + }).from(agents).where(eq(agents.companyId, companyId)); + const hasCollision = hasAgentShortnameCollision(candidateName, existingAgents, options); + if (hasCollision) { + throw conflict( + `Agent shortname '${candidateShortname}' is already in use in this company` + ); + } + } + async function updateAgent(id, data2, options) { + const existing = await getById(id); + if (!existing) return null; + if (existing.status === "terminated" && data2.status && data2.status !== "terminated") { + throw conflict("Terminated agents cannot be resumed"); + } + if (existing.status === "pending_approval" && data2.status && data2.status !== "pending_approval" && data2.status !== "terminated") { + throw conflict("Pending approval agents cannot be activated directly"); + } + if (data2.reportsTo !== void 0) { + if (data2.reportsTo) { + await ensureManager(existing.companyId, data2.reportsTo); + } + await assertNoCycle(id, data2.reportsTo); + } + if (data2.name !== void 0) { + const previousShortname = normalizeAgentUrlKey(existing.name); + const nextShortname = normalizeAgentUrlKey(data2.name); + if (previousShortname !== nextShortname) { + await assertCompanyShortnameAvailable(existing.companyId, data2.name, { excludeAgentId: id }); + } + } + const normalizedPatch = { ...data2 }; + if (data2.permissions !== void 0) { + const role = data2.role ?? existing.role; + normalizedPatch.permissions = normalizeAgentPermissions(data2.permissions, role); + } + const shouldRecordRevision = Boolean(options?.recordRevision) && hasConfigPatchFields(normalizedPatch); + const beforeConfig = shouldRecordRevision ? buildConfigSnapshot(existing) : null; + const updated = await db.update(agents).set({ ...normalizedPatch, updatedAt: /* @__PURE__ */ new Date() }).where(eq(agents.id, id)).returning().then((rows) => rows[0] ?? null); + const normalizedUpdated = updated ? normalizeAgentRow(updated) : null; + if (normalizedUpdated && shouldRecordRevision && beforeConfig) { + const afterConfig = buildConfigSnapshot(normalizedUpdated); + const changedKeys = diffConfigSnapshot(beforeConfig, afterConfig); + if (changedKeys.length > 0) { + await db.insert(agentConfigRevisions).values({ + companyId: normalizedUpdated.companyId, + agentId: normalizedUpdated.id, + createdByAgentId: options?.recordRevision?.createdByAgentId ?? null, + createdByUserId: options?.recordRevision?.createdByUserId ?? null, + source: options?.recordRevision?.source ?? "patch", + rolledBackFromRevisionId: options?.recordRevision?.rolledBackFromRevisionId ?? null, + changedKeys, + beforeConfig, + afterConfig + }); + } + } + return normalizedUpdated; + } + return { + list: async (companyId, options) => { + const conditions = [eq(agents.companyId, companyId)]; + if (!options?.includeTerminated) { + conditions.push(ne(agents.status, "terminated")); + } + const rows = await db.select().from(agents).where(and(...conditions)); + const hydrated = await hydrateAgentSpend(rows); + return hydrated.map(normalizeAgentRow); + }, + getById, + create: async (companyId, data2) => { + if (data2.reportsTo) { + await ensureManager(companyId, data2.reportsTo); + } + const existingAgents = await db.select({ id: agents.id, name: agents.name, status: agents.status }).from(agents).where(eq(agents.companyId, companyId)); + const uniqueName = deduplicateAgentName(data2.name, existingAgents); + const role = data2.role ?? "general"; + const normalizedPermissions = normalizeAgentPermissions(data2.permissions, role); + const created = await db.insert(agents).values({ ...data2, name: uniqueName, companyId, role, permissions: normalizedPermissions }).returning().then((rows) => rows[0]); + return normalizeAgentRow(created); + }, + update: updateAgent, + pause: async (id, reason = "manual") => { + const existing = await getById(id); + if (!existing) return null; + if (existing.status === "terminated") throw conflict("Cannot pause terminated agent"); + const updated = await db.update(agents).set({ + status: "paused", + pauseReason: reason, + pausedAt: /* @__PURE__ */ new Date(), + updatedAt: /* @__PURE__ */ new Date() + }).where(eq(agents.id, id)).returning().then((rows) => rows[0] ?? null); + return updated ? normalizeAgentRow(updated) : null; + }, + resume: async (id) => { + const existing = await getById(id); + if (!existing) return null; + if (existing.status === "terminated") throw conflict("Cannot resume terminated agent"); + if (existing.status === "pending_approval") { + throw conflict("Pending approval agents cannot be resumed"); + } + const updated = await db.update(agents).set({ + status: "idle", + pauseReason: null, + pausedAt: null, + updatedAt: /* @__PURE__ */ new Date() + }).where(eq(agents.id, id)).returning().then((rows) => rows[0] ?? null); + return updated ? normalizeAgentRow(updated) : null; + }, + terminate: async (id) => { + const existing = await getById(id); + if (!existing) return null; + await db.update(agents).set({ + status: "terminated", + pauseReason: null, + pausedAt: null, + updatedAt: /* @__PURE__ */ new Date() + }).where(eq(agents.id, id)); + await db.update(agentApiKeys).set({ revokedAt: /* @__PURE__ */ new Date() }).where(eq(agentApiKeys.agentId, id)); + return getById(id); + }, + remove: async (id) => { + const existing = await getById(id); + if (!existing) return null; + return db.transaction(async (tx) => { + await tx.update(agents).set({ reportsTo: null }).where(eq(agents.reportsTo, id)); + await tx.update(issues).set({ assigneeAgentId: null, createdByAgentId: null }).where(or(eq(issues.assigneeAgentId, id), eq(issues.createdByAgentId, id))); + await tx.delete(heartbeatRunEvents).where(eq(heartbeatRunEvents.agentId, id)); + await tx.delete(agentTaskSessions).where(eq(agentTaskSessions.agentId, id)); + await tx.delete(activityLog).where( + or( + eq(activityLog.agentId, id), + sql`${activityLog.runId} in (select ${heartbeatRuns.id} from ${heartbeatRuns} where ${heartbeatRuns.agentId} = ${id})` + ) + ); + await tx.delete(issueExecutionDecisions).where(eq(issueExecutionDecisions.actorAgentId, id)); + await tx.delete(issueComments).where(eq(issueComments.authorAgentId, id)); + await tx.delete(heartbeatRuns).where(eq(heartbeatRuns.agentId, id)); + await tx.delete(agentWakeupRequests).where(eq(agentWakeupRequests.agentId, id)); + await tx.delete(agentApiKeys).where(eq(agentApiKeys.agentId, id)); + await tx.delete(agentRuntimeState).where(eq(agentRuntimeState.agentId, id)); + const deleted = await tx.delete(agents).where(eq(agents.id, id)).returning().then((rows) => rows[0] ?? null); + return deleted ? normalizeAgentRow(deleted) : null; + }); + }, + activatePendingApproval: async (id) => { + const existing = await getById(id); + if (!existing) return null; + if (existing.status !== "pending_approval") return existing; + const updated = await db.update(agents).set({ status: "idle", updatedAt: /* @__PURE__ */ new Date() }).where(eq(agents.id, id)).returning().then((rows) => rows[0] ?? null); + return updated ? normalizeAgentRow(updated) : null; + }, + updatePermissions: async (id, permissions) => { + const existing = await getById(id); + if (!existing) return null; + const updated = await db.update(agents).set({ + permissions: normalizeAgentPermissions(permissions, existing.role), + updatedAt: /* @__PURE__ */ new Date() + }).where(eq(agents.id, id)).returning().then((rows) => rows[0] ?? null); + return updated ? normalizeAgentRow(updated) : null; + }, + listConfigRevisions: async (id) => db.select().from(agentConfigRevisions).where(eq(agentConfigRevisions.agentId, id)).orderBy(desc(agentConfigRevisions.createdAt)), + getConfigRevision: async (id, revisionId) => db.select().from(agentConfigRevisions).where(and(eq(agentConfigRevisions.agentId, id), eq(agentConfigRevisions.id, revisionId))).then((rows) => rows[0] ?? null), + rollbackConfigRevision: async (id, revisionId, actor) => { + const revision = await db.select().from(agentConfigRevisions).where(and(eq(agentConfigRevisions.agentId, id), eq(agentConfigRevisions.id, revisionId))).then((rows) => rows[0] ?? null); + if (!revision) return null; + if (containsRedactedMarker(revision.afterConfig)) { + throw unprocessable("Cannot roll back a revision that contains redacted secret values"); + } + const patch = configPatchFromSnapshot(revision.afterConfig); + return updateAgent(id, patch, { + recordRevision: { + createdByAgentId: actor.agentId ?? null, + createdByUserId: actor.userId ?? null, + source: "rollback", + rolledBackFromRevisionId: revision.id + } + }); + }, + createApiKey: async (id, name) => { + const existing = await getById(id); + if (!existing) throw notFound("Agent not found"); + if (existing.status === "pending_approval") { + throw conflict("Cannot create keys for pending approval agents"); + } + if (existing.status === "terminated") { + throw conflict("Cannot create keys for terminated agents"); + } + const token = createToken(); + const keyHash = hashToken2(token); + const created = await db.insert(agentApiKeys).values({ + agentId: id, + companyId: existing.companyId, + name, + keyHash + }).returning().then((rows) => rows[0]); + return { + id: created.id, + name: created.name, + token, + createdAt: created.createdAt + }; + }, + listKeys: (id) => db.select({ + id: agentApiKeys.id, + name: agentApiKeys.name, + createdAt: agentApiKeys.createdAt, + revokedAt: agentApiKeys.revokedAt + }).from(agentApiKeys).where(eq(agentApiKeys.agentId, id)), + revokeKey: async (keyId) => { + const rows = await db.update(agentApiKeys).set({ revokedAt: /* @__PURE__ */ new Date() }).where(eq(agentApiKeys.id, keyId)).returning(); + return rows[0] ?? null; + }, + orgForCompany: async (companyId) => { + const rows = await db.select().from(agents).where(and(eq(agents.companyId, companyId), ne(agents.status, "terminated"))); + const normalizedRows = rows.map(normalizeAgentRow); + const byManager = /* @__PURE__ */ new Map(); + for (const row of normalizedRows) { + const key = row.reportsTo ?? null; + const group = byManager.get(key) ?? []; + group.push(row); + byManager.set(key, group); + } + const build = (managerId) => { + const members = byManager.get(managerId) ?? []; + return members.map((member2) => ({ + ...member2, + reports: build(member2.id) + })); + }; + return build(null); + }, + getChainOfCommand: async (agentId) => { + const chain = []; + const visited = /* @__PURE__ */ new Set([agentId]); + const start = await getById(agentId); + let currentId = start?.reportsTo ?? null; + while (currentId && !visited.has(currentId) && chain.length < 50) { + visited.add(currentId); + const mgr = await getById(currentId); + if (!mgr) break; + chain.push({ id: mgr.id, name: mgr.name, role: mgr.role, title: mgr.title ?? null }); + currentId = mgr.reportsTo ?? null; + } + return chain; + }, + runningForAgent: (agentId) => db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.agentId, agentId), inArray(heartbeatRuns.status, ["queued", "running"]))), + resolveByReference: async (companyId, reference) => { + const raw = reference.trim(); + if (raw.length === 0) { + return { agent: null, ambiguous: false }; + } + if (isUuidLike(raw)) { + const byId = await getById(raw); + if (!byId || byId.companyId !== companyId) { + return { agent: null, ambiguous: false }; + } + return { agent: byId, ambiguous: false }; + } + const urlKey = normalizeAgentUrlKey(raw); + if (!urlKey) { + return { agent: null, ambiguous: false }; + } + const rows = await db.select().from(agents).where(eq(agents.companyId, companyId)); + const matches = rows.map(normalizeAgentRow).filter((agent) => agent.urlKey === urlKey && agent.status !== "terminated"); + if (matches.length === 1) { + return { agent: matches[0] ?? null, ambiguous: false }; + } + if (matches.length > 1) { + return { agent: null, ambiguous: true }; + } + return { agent: null, ambiguous: false }; + } + }; +} + +// server/src/services/projects.ts +init_drizzle_orm(); +init_src2(); + +// server/src/services/workspace-runtime-read-model.ts +init_src2(); +init_drizzle_orm(); +function runtimeServiceIdentityKey(row) { + if (row.reuseKey) return row.reuseKey; + return [ + row.scopeType, + row.scopeId ?? "", + row.projectWorkspaceId ?? "", + row.executionWorkspaceId ?? "", + row.serviceName, + row.command ?? "", + row.cwd ?? "" + ].join(":"); +} +function selectCurrentRuntimeServiceRows(rows) { + const current = /* @__PURE__ */ new Map(); + for (const row of rows) { + const identity = runtimeServiceIdentityKey(row); + if (!current.has(identity)) current.set(identity, row); + } + return [...current.values()]; +} +async function listCurrentRuntimeServicesForProjectWorkspaces(db, companyId, projectWorkspaceIds) { + if (projectWorkspaceIds.length === 0) return /* @__PURE__ */ new Map(); + const rows = await db.select().from(workspaceRuntimeServices).where( + and( + eq(workspaceRuntimeServices.companyId, companyId), + inArray(workspaceRuntimeServices.projectWorkspaceId, projectWorkspaceIds), + eq(workspaceRuntimeServices.scopeType, "project_workspace") + ) + ).orderBy(desc(workspaceRuntimeServices.updatedAt), desc(workspaceRuntimeServices.createdAt)); + const grouped = /* @__PURE__ */ new Map(); + for (const row of rows) { + if (!row.projectWorkspaceId) continue; + const existing = grouped.get(row.projectWorkspaceId) ?? []; + existing.push(row); + grouped.set(row.projectWorkspaceId, existing); + } + return new Map( + Array.from(grouped.entries()).map(([workspaceId, workspaceRows]) => [ + workspaceId, + selectCurrentRuntimeServiceRows(workspaceRows) + ]) + ); +} +async function listCurrentRuntimeServicesForExecutionWorkspaces(db, companyId, executionWorkspaceIds) { + if (executionWorkspaceIds.length === 0) return /* @__PURE__ */ new Map(); + const rows = await db.select().from(workspaceRuntimeServices).where( + and( + eq(workspaceRuntimeServices.companyId, companyId), + inArray(workspaceRuntimeServices.executionWorkspaceId, executionWorkspaceIds) + ) + ).orderBy(desc(workspaceRuntimeServices.updatedAt), desc(workspaceRuntimeServices.createdAt)); + const grouped = /* @__PURE__ */ new Map(); + for (const row of rows) { + if (!row.executionWorkspaceId) continue; + const existing = grouped.get(row.executionWorkspaceId) ?? []; + existing.push(row); + grouped.set(row.executionWorkspaceId, existing); + } + return new Map( + Array.from(grouped.entries()).map(([workspaceId, workspaceRows]) => [ + workspaceId, + selectCurrentRuntimeServiceRows(workspaceRows) + ]) + ); +} + +// server/src/services/execution-workspace-policy.ts +function cloneRecord(value) { + if (!value) return null; + return { ...value }; +} +function parseExecutionWorkspaceStrategy(raw) { + const parsed = parseObject4(raw); + const type = asString12(parsed.type, ""); + if (type !== "project_primary" && type !== "git_worktree" && type !== "adapter_managed" && type !== "cloud_sandbox") { + return null; + } + return { + type, + ...typeof parsed.baseRef === "string" ? { baseRef: parsed.baseRef } : {}, + ...typeof parsed.branchTemplate === "string" ? { branchTemplate: parsed.branchTemplate } : {}, + ...typeof parsed.worktreeParentDir === "string" ? { worktreeParentDir: parsed.worktreeParentDir } : {}, + ...typeof parsed.provisionCommand === "string" ? { provisionCommand: parsed.provisionCommand } : {}, + ...typeof parsed.teardownCommand === "string" ? { teardownCommand: parsed.teardownCommand } : {} + }; +} +function parseProjectExecutionWorkspacePolicy(raw) { + const parsed = parseObject4(raw); + if (Object.keys(parsed).length === 0) return null; + const enabled = typeof parsed.enabled === "boolean" ? parsed.enabled : false; + const workspaceStrategy = parseExecutionWorkspaceStrategy(parsed.workspaceStrategy); + const defaultMode = asString12(parsed.defaultMode, ""); + const defaultProjectWorkspaceId = typeof parsed.defaultProjectWorkspaceId === "string" ? parsed.defaultProjectWorkspaceId : void 0; + const allowIssueOverride = typeof parsed.allowIssueOverride === "boolean" ? parsed.allowIssueOverride : void 0; + const normalizedDefaultMode = (() => { + if (defaultMode === "shared_workspace" || defaultMode === "isolated_workspace" || defaultMode === "operator_branch" || defaultMode === "adapter_default") { + return defaultMode; + } + if (defaultMode === "project_primary") return "shared_workspace"; + if (defaultMode === "isolated") return "isolated_workspace"; + return void 0; + })(); + return { + enabled, + ...normalizedDefaultMode ? { defaultMode: normalizedDefaultMode } : {}, + ...allowIssueOverride !== void 0 ? { allowIssueOverride } : {}, + ...defaultProjectWorkspaceId ? { defaultProjectWorkspaceId } : {}, + ...workspaceStrategy ? { workspaceStrategy } : {}, + ...parsed.workspaceRuntime && typeof parsed.workspaceRuntime === "object" && !Array.isArray(parsed.workspaceRuntime) ? { workspaceRuntime: { ...parsed.workspaceRuntime } } : {}, + ...parsed.branchPolicy && typeof parsed.branchPolicy === "object" && !Array.isArray(parsed.branchPolicy) ? { branchPolicy: { ...parsed.branchPolicy } } : {}, + ...parsed.pullRequestPolicy && typeof parsed.pullRequestPolicy === "object" && !Array.isArray(parsed.pullRequestPolicy) ? { pullRequestPolicy: { ...parsed.pullRequestPolicy } } : {}, + ...parsed.runtimePolicy && typeof parsed.runtimePolicy === "object" && !Array.isArray(parsed.runtimePolicy) ? { runtimePolicy: { ...parsed.runtimePolicy } } : {}, + ...parsed.cleanupPolicy && typeof parsed.cleanupPolicy === "object" && !Array.isArray(parsed.cleanupPolicy) ? { cleanupPolicy: { ...parsed.cleanupPolicy } } : {} + }; +} +function gateProjectExecutionWorkspacePolicy(projectPolicy, isolatedWorkspacesEnabled) { + if (!isolatedWorkspacesEnabled) return null; + return projectPolicy; +} +function parseIssueExecutionWorkspaceSettings(raw) { + const parsed = parseObject4(raw); + if (Object.keys(parsed).length === 0) return null; + const workspaceStrategy = parseExecutionWorkspaceStrategy(parsed.workspaceStrategy); + const mode = asString12(parsed.mode, ""); + const normalizedMode = (() => { + if (mode === "inherit" || mode === "shared_workspace" || mode === "isolated_workspace" || mode === "operator_branch" || mode === "reuse_existing" || mode === "agent_default") { + return mode; + } + if (mode === "project_primary") return "shared_workspace"; + if (mode === "isolated") return "isolated_workspace"; + return ""; + })(); + return { + ...normalizedMode ? { mode: normalizedMode } : {}, + ...workspaceStrategy ? { workspaceStrategy } : {}, + ...parsed.workspaceRuntime && typeof parsed.workspaceRuntime === "object" && !Array.isArray(parsed.workspaceRuntime) ? { workspaceRuntime: { ...parsed.workspaceRuntime } } : {} + }; +} +function defaultIssueExecutionWorkspaceSettingsForProject(projectPolicy) { + if (!projectPolicy?.enabled) return null; + return { + mode: projectPolicy.defaultMode === "isolated_workspace" ? "isolated_workspace" : projectPolicy.defaultMode === "operator_branch" ? "operator_branch" : projectPolicy.defaultMode === "adapter_default" ? "agent_default" : "shared_workspace" + }; +} +function issueExecutionWorkspaceModeForPersistedWorkspace(mode) { + if (mode === null || mode === void 0) { + return "agent_default"; + } + if (mode === "isolated_workspace" || mode === "operator_branch" || mode === "shared_workspace") { + return mode; + } + if (mode === "adapter_managed" || mode === "cloud_sandbox") { + return "agent_default"; + } + return "shared_workspace"; +} +function resolveExecutionWorkspaceMode(input) { + const issueMode = input.issueSettings?.mode; + if (issueMode && issueMode !== "inherit" && issueMode !== "reuse_existing") { + return issueMode; + } + if (input.projectPolicy?.enabled) { + if (input.projectPolicy.defaultMode === "isolated_workspace") return "isolated_workspace"; + if (input.projectPolicy.defaultMode === "operator_branch") return "operator_branch"; + if (input.projectPolicy.defaultMode === "adapter_default") return "agent_default"; + return "shared_workspace"; + } + if (input.legacyUseProjectWorkspace === false) { + return "agent_default"; + } + return "shared_workspace"; +} +function buildExecutionWorkspaceAdapterConfig(input) { + const nextConfig = { ...input.agentConfig }; + const projectHasPolicy = Boolean(input.projectPolicy?.enabled); + const issueHasWorkspaceOverrides = Boolean( + input.issueSettings?.mode || input.issueSettings?.workspaceStrategy || input.issueSettings?.workspaceRuntime + ); + const hasWorkspaceControl = projectHasPolicy || issueHasWorkspaceOverrides || input.legacyUseProjectWorkspace === false; + if (hasWorkspaceControl) { + if (input.mode === "isolated_workspace") { + const strategy = input.issueSettings?.workspaceStrategy ?? input.projectPolicy?.workspaceStrategy ?? parseExecutionWorkspaceStrategy(nextConfig.workspaceStrategy) ?? { type: "git_worktree" }; + nextConfig.workspaceStrategy = strategy; + } else { + delete nextConfig.workspaceStrategy; + } + if (input.mode === "agent_default") { + delete nextConfig.workspaceRuntime; + } else if (input.issueSettings?.workspaceRuntime) { + nextConfig.workspaceRuntime = cloneRecord(input.issueSettings.workspaceRuntime) ?? void 0; + } else if (input.projectPolicy?.workspaceRuntime) { + nextConfig.workspaceRuntime = cloneRecord(input.projectPolicy.workspaceRuntime) ?? void 0; + } + } + return nextConfig; +} + +// server/src/services/project-workspace-runtime-config.ts +function isRecord3(value) { + return typeof value === "object" && value !== null && !Array.isArray(value); +} +function cloneRecord2(value) { + return isRecord3(value) ? { ...value } : null; +} +function readDesiredState(value) { + return value === "running" || value === "stopped" ? value : null; +} +function readServiceStates(value) { + if (!isRecord3(value)) return null; + const entries2 = Object.entries(value).filter(([, state2]) => state2 === "running" || state2 === "stopped"); + if (entries2.length === 0) return null; + return Object.fromEntries(entries2); +} +function readProjectWorkspaceRuntimeConfig(metadata) { + const raw = isRecord3(metadata?.runtimeConfig) ? metadata.runtimeConfig : null; + if (!raw) return null; + const config3 = { + workspaceRuntime: cloneRecord2(raw.workspaceRuntime), + desiredState: readDesiredState(raw.desiredState), + serviceStates: readServiceStates(raw.serviceStates) + }; + const hasConfig = config3.workspaceRuntime !== null || config3.desiredState !== null || config3.serviceStates !== null; + return hasConfig ? config3 : null; +} +function mergeProjectWorkspaceRuntimeConfig(metadata, patch) { + const nextMetadata = isRecord3(metadata) ? { ...metadata } : {}; + const current = readProjectWorkspaceRuntimeConfig(metadata) ?? { + workspaceRuntime: null, + desiredState: null, + serviceStates: null + }; + if (patch === null) { + delete nextMetadata.runtimeConfig; + return Object.keys(nextMetadata).length > 0 ? nextMetadata : null; + } + const nextConfig = { + workspaceRuntime: patch.workspaceRuntime !== void 0 ? cloneRecord2(patch.workspaceRuntime) : current.workspaceRuntime, + desiredState: patch.desiredState !== void 0 ? readDesiredState(patch.desiredState) : current.desiredState, + serviceStates: patch.serviceStates !== void 0 ? readServiceStates(patch.serviceStates) : current.serviceStates + }; + if (nextConfig.workspaceRuntime === null && nextConfig.desiredState === null && nextConfig.serviceStates === null) { + delete nextMetadata.runtimeConfig; + } else { + nextMetadata.runtimeConfig = nextConfig; + } + return Object.keys(nextMetadata).length > 0 ? nextMetadata : null; +} + +// server/src/services/projects.ts +var REPO_ONLY_CWD_SENTINEL = "/__taskcore_repo_only__"; +async function attachGoals(db, rows) { + if (rows.length === 0) return []; + const projectIds = rows.map((r5) => r5.id); + const links = await db.select({ + projectId: projectGoals.projectId, + goalId: projectGoals.goalId, + goalTitle: goals.title + }).from(projectGoals).innerJoin(goals, eq(projectGoals.goalId, goals.id)).where(inArray(projectGoals.projectId, projectIds)); + const map4 = /* @__PURE__ */ new Map(); + for (const link of links) { + let arr = map4.get(link.projectId); + if (!arr) { + arr = []; + map4.set(link.projectId, arr); + } + arr.push({ id: link.goalId, title: link.goalTitle }); + } + return rows.map((r5) => { + const g5 = map4.get(r5.id) ?? []; + return { + ...r5, + urlKey: deriveProjectUrlKey(r5.name, r5.id), + goalIds: g5.map((x5) => x5.id), + goals: g5, + executionWorkspacePolicy: parseProjectExecutionWorkspacePolicy(r5.executionWorkspacePolicy) + }; + }); +} +function toRuntimeService(row) { + return { + id: row.id, + companyId: row.companyId, + projectId: row.projectId ?? null, + projectWorkspaceId: row.projectWorkspaceId ?? null, + executionWorkspaceId: row.executionWorkspaceId ?? null, + issueId: row.issueId ?? null, + scopeType: row.scopeType, + scopeId: row.scopeId ?? null, + serviceName: row.serviceName, + status: row.status, + lifecycle: row.lifecycle, + reuseKey: row.reuseKey ?? null, + command: row.command ?? null, + cwd: row.cwd ?? null, + port: row.port ?? null, + url: row.url ?? null, + provider: row.provider, + providerRef: row.providerRef ?? null, + ownerAgentId: row.ownerAgentId ?? null, + startedByRunId: row.startedByRunId ?? null, + lastUsedAt: row.lastUsedAt, + startedAt: row.startedAt, + stoppedAt: row.stoppedAt ?? null, + stopPolicy: row.stopPolicy ?? null, + healthStatus: row.healthStatus, + createdAt: row.createdAt, + updatedAt: row.updatedAt + }; +} +function toWorkspace(row, runtimeServices = []) { + return { + id: row.id, + companyId: row.companyId, + projectId: row.projectId, + name: row.name, + sourceType: row.sourceType, + cwd: normalizeWorkspaceCwd(row.cwd), + repoUrl: row.repoUrl ?? null, + repoRef: row.repoRef ?? null, + defaultRef: row.defaultRef ?? row.repoRef ?? null, + visibility: row.visibility, + setupCommand: row.setupCommand ?? null, + cleanupCommand: row.cleanupCommand ?? null, + remoteProvider: row.remoteProvider ?? null, + remoteWorkspaceRef: row.remoteWorkspaceRef ?? null, + sharedWorkspaceKey: row.sharedWorkspaceKey ?? null, + metadata: row.metadata ?? null, + runtimeConfig: readProjectWorkspaceRuntimeConfig(row.metadata ?? null), + isPrimary: row.isPrimary, + runtimeServices, + createdAt: row.createdAt, + updatedAt: row.updatedAt + }; +} +function deriveRepoNameFromRepoUrl(repoUrl) { + const raw = readNonEmptyString9(repoUrl); + if (!raw) return null; + try { + const parsed = new URL(raw); + const cleanedPath = parsed.pathname.replace(/\/+$/, ""); + const repoName = cleanedPath.split("/").filter(Boolean).pop()?.replace(/\.git$/i, "") ?? ""; + return repoName || null; + } catch { + return null; + } +} +function deriveProjectCodebase(input) { + const primaryWorkspace = input.primaryWorkspace ?? input.fallbackWorkspaces[0] ?? null; + const repoUrl = primaryWorkspace?.repoUrl ?? null; + const repoName = deriveRepoNameFromRepoUrl(repoUrl); + const localFolder = primaryWorkspace?.cwd ?? null; + const managedFolder = resolveManagedProjectWorkspaceDir({ + companyId: input.companyId, + projectId: input.projectId, + repoName + }); + return { + workspaceId: primaryWorkspace?.id ?? null, + repoUrl, + repoRef: primaryWorkspace?.repoRef ?? null, + defaultRef: primaryWorkspace?.defaultRef ?? null, + repoName, + localFolder, + managedFolder, + effectiveLocalFolder: localFolder ?? managedFolder, + origin: localFolder ? "local_folder" : "managed_checkout" + }; +} +function pickPrimaryWorkspace(rows, runtimeServicesByWorkspaceId) { + if (rows.length === 0) return null; + const explicitPrimary = rows.find((row) => row.isPrimary); + const primary = explicitPrimary ?? rows[0]; + return toWorkspace(primary, runtimeServicesByWorkspaceId?.get(primary.id) ?? []); +} +async function attachWorkspaces(db, rows) { + if (rows.length === 0) return []; + const projectIds = rows.map((r5) => r5.id); + const workspaceRows = await db.select().from(projectWorkspaces).where(inArray(projectWorkspaces.projectId, projectIds)).orderBy(desc(projectWorkspaces.isPrimary), asc(projectWorkspaces.createdAt), asc(projectWorkspaces.id)); + const runtimeServicesByWorkspaceId = await listCurrentRuntimeServicesForProjectWorkspaces( + db, + rows[0].companyId, + workspaceRows.map((workspace) => workspace.id) + ); + const sharedRuntimeServicesByWorkspaceId = new Map( + Array.from(runtimeServicesByWorkspaceId.entries()).map(([workspaceId, services]) => [ + workspaceId, + services.map(toRuntimeService) + ]) + ); + const map4 = /* @__PURE__ */ new Map(); + for (const row of workspaceRows) { + let arr = map4.get(row.projectId); + if (!arr) { + arr = []; + map4.set(row.projectId, arr); + } + arr.push(row); + } + return rows.map((row) => { + const projectWorkspaceRows = map4.get(row.id) ?? []; + const workspaces = projectWorkspaceRows.map( + (workspace) => toWorkspace( + workspace, + sharedRuntimeServicesByWorkspaceId.get(workspace.id) ?? [] + ) + ); + const primaryWorkspace = pickPrimaryWorkspace(projectWorkspaceRows, sharedRuntimeServicesByWorkspaceId); + return { + ...row, + codebase: deriveProjectCodebase({ + companyId: row.companyId, + projectId: row.id, + primaryWorkspace, + fallbackWorkspaces: workspaces + }), + workspaces, + primaryWorkspace + }; + }); +} +async function syncGoalLinks(db, projectId, companyId, goalIds) { + await db.delete(projectGoals).where(eq(projectGoals.projectId, projectId)); + if (goalIds.length > 0) { + await db.insert(projectGoals).values( + goalIds.map((goalId) => ({ projectId, goalId, companyId })) + ); + } +} +function resolveGoalIds(data2) { + if (data2.goalIds !== void 0) return data2.goalIds; + if (data2.goalId !== void 0) { + return data2.goalId ? [data2.goalId] : []; + } + return void 0; +} +function readNonEmptyString9(value) { + if (typeof value !== "string") return null; + const trimmed = value.trim(); + return trimmed.length > 0 ? trimmed : null; +} +function normalizeWorkspaceCwd(value) { + const cwd = readNonEmptyString9(value); + if (!cwd) return null; + return cwd === REPO_ONLY_CWD_SENTINEL ? null : cwd; +} +function deriveNameFromCwd(cwd) { + const normalized = cwd.replace(/[\\/]+$/, ""); + const segments = normalized.split(/[\\/]/).filter(Boolean); + return segments[segments.length - 1] ?? "Local folder"; +} +function deriveNameFromRepoUrl(repoUrl) { + try { + const url2 = new URL(repoUrl); + const cleanedPath = url2.pathname.replace(/\/+$/, ""); + const lastSegment = cleanedPath.split("/").filter(Boolean).pop() ?? ""; + const noGitSuffix = lastSegment.replace(/\.git$/i, ""); + return noGitSuffix || repoUrl; + } catch { + return repoUrl; + } +} +function deriveWorkspaceName(input) { + const explicit = readNonEmptyString9(input.name); + if (explicit) return explicit; + const cwd = readNonEmptyString9(input.cwd); + if (cwd) return deriveNameFromCwd(cwd); + const repoUrl = readNonEmptyString9(input.repoUrl); + if (repoUrl) return deriveNameFromRepoUrl(repoUrl); + return "Workspace"; +} +function resolveProjectNameForUniqueShortname(requestedName, existingProjects, options) { + const requestedShortname = normalizeProjectUrlKey(requestedName); + if (!requestedShortname) return requestedName; + if (hasNonAsciiContent(requestedName)) return requestedName; + const usedShortnames = new Set( + existingProjects.filter((project) => !(options?.excludeProjectId && project.id === options.excludeProjectId)).map((project) => normalizeProjectUrlKey(project.name)).filter((value) => value !== null) + ); + if (!usedShortnames.has(requestedShortname)) return requestedName; + for (let suffix = 2; suffix < 1e4; suffix += 1) { + const candidateName = `${requestedName} ${suffix}`; + const candidateShortname = normalizeProjectUrlKey(candidateName); + if (candidateShortname && !usedShortnames.has(candidateShortname)) { + return candidateName; + } + } + return `${requestedName} ${Date.now()}`; +} +async function ensureSinglePrimaryWorkspace(dbOrTx, input) { + await dbOrTx.update(projectWorkspaces).set({ isPrimary: false, updatedAt: /* @__PURE__ */ new Date() }).where( + and( + eq(projectWorkspaces.companyId, input.companyId), + eq(projectWorkspaces.projectId, input.projectId) + ) + ); + await dbOrTx.update(projectWorkspaces).set({ isPrimary: true, updatedAt: /* @__PURE__ */ new Date() }).where( + and( + eq(projectWorkspaces.companyId, input.companyId), + eq(projectWorkspaces.projectId, input.projectId), + eq(projectWorkspaces.id, input.keepWorkspaceId) + ) + ); +} +function projectService(db) { + return { + list: async (companyId) => { + const rows = await db.select().from(projects).where(eq(projects.companyId, companyId)); + const withGoals = await attachGoals(db, rows); + return attachWorkspaces(db, withGoals); + }, + listByIds: async (companyId, ids) => { + const dedupedIds = [...new Set(ids)]; + if (dedupedIds.length === 0) return []; + const rows = await db.select().from(projects).where(and(eq(projects.companyId, companyId), inArray(projects.id, dedupedIds))); + const withGoals = await attachGoals(db, rows); + const withWorkspaces = await attachWorkspaces(db, withGoals); + const byId = new Map(withWorkspaces.map((project) => [project.id, project])); + return dedupedIds.map((id) => byId.get(id)).filter((project) => Boolean(project)); + }, + getById: async (id) => { + const row = await db.select().from(projects).where(eq(projects.id, id)).then((rows) => rows[0] ?? null); + if (!row) return null; + const [withGoals] = await attachGoals(db, [row]); + if (!withGoals) return null; + const [enriched] = await attachWorkspaces(db, [withGoals]); + return enriched ?? null; + }, + create: async (companyId, data2) => { + const { goalIds: inputGoalIds, ...projectData } = data2; + const ids = resolveGoalIds({ goalIds: inputGoalIds, goalId: projectData.goalId }); + if (!projectData.color) { + const existing = await db.select({ color: projects.color }).from(projects).where(eq(projects.companyId, companyId)); + const usedColors = new Set(existing.map((r5) => r5.color).filter(Boolean)); + const nextColor = PROJECT_COLORS.find((c5) => !usedColors.has(c5)) ?? PROJECT_COLORS[existing.length % PROJECT_COLORS.length]; + projectData.color = nextColor; + } + const existingProjects = await db.select({ id: projects.id, name: projects.name }).from(projects).where(eq(projects.companyId, companyId)); + projectData.name = resolveProjectNameForUniqueShortname(projectData.name, existingProjects); + const legacyGoalId = ids && ids.length > 0 ? ids[0] : projectData.goalId ?? null; + const row = await db.insert(projects).values({ ...projectData, goalId: legacyGoalId, companyId }).returning().then((rows) => rows[0]); + if (ids && ids.length > 0) { + await syncGoalLinks(db, row.id, companyId, ids); + } + const [withGoals] = await attachGoals(db, [row]); + const [enriched] = withGoals ? await attachWorkspaces(db, [withGoals]) : []; + return enriched; + }, + update: async (id, data2) => { + const { goalIds: inputGoalIds, ...projectData } = data2; + const ids = resolveGoalIds({ goalIds: inputGoalIds, goalId: projectData.goalId }); + const existingProject = await db.select({ id: projects.id, companyId: projects.companyId, name: projects.name }).from(projects).where(eq(projects.id, id)).then((rows) => rows[0] ?? null); + if (!existingProject) return null; + if (projectData.name !== void 0) { + const existingShortname = normalizeProjectUrlKey(existingProject.name); + const nextShortname = normalizeProjectUrlKey(projectData.name); + if (existingShortname !== nextShortname) { + const existingProjects = await db.select({ id: projects.id, name: projects.name }).from(projects).where(eq(projects.companyId, existingProject.companyId)); + projectData.name = resolveProjectNameForUniqueShortname(projectData.name, existingProjects, { + excludeProjectId: id + }); + } + } + const updates = { + ...projectData, + updatedAt: /* @__PURE__ */ new Date() + }; + if (ids !== void 0) { + updates.goalId = ids.length > 0 ? ids[0] : null; + } + const row = await db.update(projects).set(updates).where(eq(projects.id, id)).returning().then((rows) => rows[0] ?? null); + if (!row) return null; + if (ids !== void 0) { + await syncGoalLinks(db, id, row.companyId, ids); + } + const [withGoals] = await attachGoals(db, [row]); + const [enriched] = withGoals ? await attachWorkspaces(db, [withGoals]) : []; + return enriched ?? null; + }, + remove: (id) => db.delete(projects).where(eq(projects.id, id)).returning().then((rows) => { + const row = rows[0] ?? null; + if (!row) return null; + return { ...row, urlKey: deriveProjectUrlKey(row.name, row.id) }; + }), + listWorkspaces: async (projectId) => { + const rows = await db.select().from(projectWorkspaces).where(eq(projectWorkspaces.projectId, projectId)).orderBy(desc(projectWorkspaces.isPrimary), asc(projectWorkspaces.createdAt), asc(projectWorkspaces.id)); + if (rows.length === 0) return []; + const runtimeServicesByWorkspaceId = await listCurrentRuntimeServicesForProjectWorkspaces( + db, + rows[0].companyId, + rows.map((workspace) => workspace.id) + ); + return rows.map( + (row) => toWorkspace( + row, + (runtimeServicesByWorkspaceId.get(row.id) ?? []).map(toRuntimeService) + ) + ); + }, + createWorkspace: async (projectId, data2) => { + const project = await db.select().from(projects).where(eq(projects.id, projectId)).then((rows) => rows[0] ?? null); + if (!project) return null; + const cwd = normalizeWorkspaceCwd(data2.cwd); + const repoUrl = readNonEmptyString9(data2.repoUrl); + const sourceType = readNonEmptyString9(data2.sourceType) ?? (repoUrl ? "git_repo" : cwd ? "local_path" : "remote_managed"); + const remoteWorkspaceRef = readNonEmptyString9(data2.remoteWorkspaceRef); + if (sourceType === "remote_managed") { + if (!remoteWorkspaceRef && !repoUrl) return null; + } else if (!cwd && !repoUrl) { + return null; + } + const name = deriveWorkspaceName({ + name: data2.name, + cwd, + repoUrl + }); + const existing = await db.select().from(projectWorkspaces).where(eq(projectWorkspaces.projectId, projectId)).orderBy(asc(projectWorkspaces.createdAt)).then((rows) => rows); + const shouldBePrimary = data2.isPrimary === true || existing.length === 0; + const created = await db.transaction(async (tx) => { + if (shouldBePrimary) { + await tx.update(projectWorkspaces).set({ isPrimary: false, updatedAt: /* @__PURE__ */ new Date() }).where( + and( + eq(projectWorkspaces.companyId, project.companyId), + eq(projectWorkspaces.projectId, projectId) + ) + ); + } + const row = await tx.insert(projectWorkspaces).values({ + companyId: project.companyId, + projectId, + name, + sourceType, + cwd: cwd ?? null, + repoUrl: repoUrl ?? null, + repoRef: readNonEmptyString9(data2.repoRef), + defaultRef: readNonEmptyString9(data2.defaultRef) ?? readNonEmptyString9(data2.repoRef), + visibility: readNonEmptyString9(data2.visibility) ?? "default", + setupCommand: readNonEmptyString9(data2.setupCommand), + cleanupCommand: readNonEmptyString9(data2.cleanupCommand), + remoteProvider: readNonEmptyString9(data2.remoteProvider), + remoteWorkspaceRef, + sharedWorkspaceKey: readNonEmptyString9(data2.sharedWorkspaceKey), + metadata: data2.runtimeConfig !== void 0 ? mergeProjectWorkspaceRuntimeConfig( + data2.metadata ?? null, + data2.runtimeConfig ?? null + ) : data2.metadata ?? null, + isPrimary: shouldBePrimary + }).returning().then((rows) => rows[0] ?? null); + return row; + }); + return created ? toWorkspace(created) : null; + }, + updateWorkspace: async (projectId, workspaceId, data2) => { + const existing = await db.select().from(projectWorkspaces).where( + and( + eq(projectWorkspaces.id, workspaceId), + eq(projectWorkspaces.projectId, projectId) + ) + ).then((rows) => rows[0] ?? null); + if (!existing) return null; + const nextCwd = data2.cwd !== void 0 ? normalizeWorkspaceCwd(data2.cwd) : normalizeWorkspaceCwd(existing.cwd); + const nextRepoUrl = data2.repoUrl !== void 0 ? readNonEmptyString9(data2.repoUrl) : readNonEmptyString9(existing.repoUrl); + const nextSourceType = data2.sourceType !== void 0 ? readNonEmptyString9(data2.sourceType) : readNonEmptyString9(existing.sourceType); + const nextRemoteWorkspaceRef = data2.remoteWorkspaceRef !== void 0 ? readNonEmptyString9(data2.remoteWorkspaceRef) : readNonEmptyString9(existing.remoteWorkspaceRef); + if (nextSourceType === "remote_managed") { + if (!nextRemoteWorkspaceRef && !nextRepoUrl) return null; + } else if (!nextCwd && !nextRepoUrl) { + return null; + } + const patch = { + updatedAt: /* @__PURE__ */ new Date() + }; + if (data2.name !== void 0) patch.name = deriveWorkspaceName({ name: data2.name, cwd: nextCwd, repoUrl: nextRepoUrl }); + if (data2.name === void 0 && (data2.cwd !== void 0 || data2.repoUrl !== void 0)) { + patch.name = deriveWorkspaceName({ cwd: nextCwd, repoUrl: nextRepoUrl }); + } + if (data2.cwd !== void 0) patch.cwd = nextCwd ?? null; + if (data2.repoUrl !== void 0) patch.repoUrl = nextRepoUrl ?? null; + if (data2.repoRef !== void 0) patch.repoRef = readNonEmptyString9(data2.repoRef); + if (data2.sourceType !== void 0 && nextSourceType) patch.sourceType = nextSourceType; + if (data2.defaultRef !== void 0) patch.defaultRef = readNonEmptyString9(data2.defaultRef); + if (data2.visibility !== void 0 && readNonEmptyString9(data2.visibility)) { + patch.visibility = readNonEmptyString9(data2.visibility); + } + if (data2.setupCommand !== void 0) patch.setupCommand = readNonEmptyString9(data2.setupCommand); + if (data2.cleanupCommand !== void 0) patch.cleanupCommand = readNonEmptyString9(data2.cleanupCommand); + if (data2.remoteProvider !== void 0) patch.remoteProvider = readNonEmptyString9(data2.remoteProvider); + if (data2.remoteWorkspaceRef !== void 0) patch.remoteWorkspaceRef = nextRemoteWorkspaceRef; + if (data2.sharedWorkspaceKey !== void 0) patch.sharedWorkspaceKey = readNonEmptyString9(data2.sharedWorkspaceKey); + if (data2.metadata !== void 0 || data2.runtimeConfig !== void 0) { + patch.metadata = data2.runtimeConfig !== void 0 ? mergeProjectWorkspaceRuntimeConfig( + data2.metadata !== void 0 ? data2.metadata : existing.metadata ?? null, + data2.runtimeConfig ?? null + ) : data2.metadata; + } + const updated = await db.transaction(async (tx) => { + if (data2.isPrimary === true) { + await tx.update(projectWorkspaces).set({ isPrimary: false, updatedAt: /* @__PURE__ */ new Date() }).where( + and( + eq(projectWorkspaces.companyId, existing.companyId), + eq(projectWorkspaces.projectId, projectId) + ) + ); + patch.isPrimary = true; + } else if (data2.isPrimary === false) { + patch.isPrimary = false; + } + const row = await tx.update(projectWorkspaces).set(patch).where(eq(projectWorkspaces.id, workspaceId)).returning().then((rows) => rows[0] ?? null); + if (!row) return null; + if (row.isPrimary) return row; + const hasPrimary = await tx.select({ id: projectWorkspaces.id }).from(projectWorkspaces).where( + and( + eq(projectWorkspaces.companyId, row.companyId), + eq(projectWorkspaces.projectId, row.projectId), + eq(projectWorkspaces.isPrimary, true) + ) + ).then((rows) => rows[0] ?? null); + if (!hasPrimary) { + const nextPrimaryCandidate = await tx.select({ id: projectWorkspaces.id }).from(projectWorkspaces).where( + and( + eq(projectWorkspaces.companyId, row.companyId), + eq(projectWorkspaces.projectId, row.projectId), + eq(projectWorkspaces.id, row.id) + ) + ).then((rows) => rows[0] ?? null); + const alternateCandidate = await tx.select({ id: projectWorkspaces.id }).from(projectWorkspaces).where( + and( + eq(projectWorkspaces.companyId, row.companyId), + eq(projectWorkspaces.projectId, row.projectId) + ) + ).orderBy(asc(projectWorkspaces.createdAt), asc(projectWorkspaces.id)).then((rows) => rows.find((candidate) => candidate.id !== row.id) ?? null); + await ensureSinglePrimaryWorkspace(tx, { + companyId: row.companyId, + projectId: row.projectId, + keepWorkspaceId: alternateCandidate?.id ?? nextPrimaryCandidate?.id ?? row.id + }); + const refreshed = await tx.select().from(projectWorkspaces).where(eq(projectWorkspaces.id, row.id)).then((rows) => rows[0] ?? row); + return refreshed; + } + return row; + }); + return updated ? toWorkspace(updated) : null; + }, + removeWorkspace: async (projectId, workspaceId) => { + const existing = await db.select().from(projectWorkspaces).where( + and( + eq(projectWorkspaces.id, workspaceId), + eq(projectWorkspaces.projectId, projectId) + ) + ).then((rows) => rows[0] ?? null); + if (!existing) return null; + const removed = await db.transaction(async (tx) => { + const row = await tx.delete(projectWorkspaces).where(eq(projectWorkspaces.id, workspaceId)).returning().then((rows) => rows[0] ?? null); + if (!row) return null; + if (!row.isPrimary) return row; + const next = await tx.select().from(projectWorkspaces).where( + and( + eq(projectWorkspaces.companyId, row.companyId), + eq(projectWorkspaces.projectId, row.projectId) + ) + ).orderBy(asc(projectWorkspaces.createdAt), asc(projectWorkspaces.id)).limit(1).then((rows) => rows[0] ?? null); + if (next) { + await ensureSinglePrimaryWorkspace(tx, { + companyId: row.companyId, + projectId: row.projectId, + keepWorkspaceId: next.id + }); + } + return row; + }); + return removed ? toWorkspace(removed) : null; + }, + resolveByReference: async (companyId, reference) => { + const raw = reference.trim(); + if (raw.length === 0) { + return { project: null, ambiguous: false }; + } + if (isUuidLike(raw)) { + const row = await db.select({ id: projects.id, companyId: projects.companyId, name: projects.name }).from(projects).where(and(eq(projects.id, raw), eq(projects.companyId, companyId))).then((rows2) => rows2[0] ?? null); + if (!row) return { project: null, ambiguous: false }; + return { + project: { id: row.id, companyId: row.companyId, urlKey: deriveProjectUrlKey(row.name, row.id) }, + ambiguous: false + }; + } + const urlKey = normalizeProjectUrlKey(raw); + if (!urlKey) { + return { project: null, ambiguous: false }; + } + const rows = await db.select({ id: projects.id, companyId: projects.companyId, name: projects.name }).from(projects).where(eq(projects.companyId, companyId)); + const matches = rows.filter((row) => deriveProjectUrlKey(row.name, row.id) === urlKey); + if (matches.length === 1) { + const match = matches[0]; + return { + project: { id: match.id, companyId: match.companyId, urlKey: deriveProjectUrlKey(match.name, match.id) }, + ambiguous: false + }; + } + if (matches.length > 1) { + return { project: null, ambiguous: true }; + } + return { project: null, ambiguous: false }; + } + }; +} + +// server/src/services/secrets.ts +init_drizzle_orm(); +init_src2(); + +// server/src/secrets/local-encrypted-provider.ts +import { createCipheriv, createDecipheriv, createHash as createHash9, randomBytes as randomBytes3 } from "node:crypto"; +import { mkdirSync, readFileSync as readFileSync2, writeFileSync, existsSync as existsSync2, chmodSync } from "node:fs"; +import path33 from "node:path"; +function resolveMasterKeyFilePath() { + const fromEnv = process.env.TASKCORE_SECRETS_MASTER_KEY_FILE; + if (fromEnv && fromEnv.trim().length > 0) return path33.resolve(fromEnv.trim()); + return path33.resolve(process.cwd(), "data/secrets/master.key"); +} +function decodeMasterKey(raw) { + const trimmed = raw.trim(); + if (!trimmed) return null; + if (/^[A-Fa-f0-9]{64}$/.test(trimmed)) { + return Buffer.from(trimmed, "hex"); + } + try { + const decoded = Buffer.from(trimmed, "base64"); + if (decoded.length === 32) return decoded; + } catch { + } + if (Buffer.byteLength(trimmed, "utf8") === 32) { + return Buffer.from(trimmed, "utf8"); + } + return null; +} +function loadOrCreateMasterKey() { + const envKeyRaw = process.env.TASKCORE_SECRETS_MASTER_KEY; + if (envKeyRaw && envKeyRaw.trim().length > 0) { + const fromEnv = decodeMasterKey(envKeyRaw); + if (!fromEnv) { + throw badRequest( + "Invalid TASKCORE_SECRETS_MASTER_KEY (expected 32-byte base64, 64-char hex, or raw 32-char string)" + ); + } + return fromEnv; + } + const keyPath = resolveMasterKeyFilePath(); + if (existsSync2(keyPath)) { + const raw = readFileSync2(keyPath, "utf8"); + const decoded = decodeMasterKey(raw); + if (!decoded) { + throw badRequest(`Invalid secrets master key at ${keyPath}`); + } + return decoded; + } + const dir = path33.dirname(keyPath); + mkdirSync(dir, { recursive: true }); + const generated = randomBytes3(32); + writeFileSync(keyPath, generated.toString("base64"), { encoding: "utf8", mode: 384 }); + try { + chmodSync(keyPath, 384); + } catch { + } + return generated; +} +function sha256Hex(value) { + return createHash9("sha256").update(value).digest("hex"); +} +function encryptValue(masterKey, value) { + const iv = randomBytes3(12); + const cipher = createCipheriv("aes-256-gcm", masterKey, iv); + const ciphertext = Buffer.concat([cipher.update(value, "utf8"), cipher.final()]); + const tag3 = cipher.getAuthTag(); + return { + scheme: "local_encrypted_v1", + iv: iv.toString("base64"), + tag: tag3.toString("base64"), + ciphertext: ciphertext.toString("base64") + }; +} +function decryptValue(masterKey, material) { + const iv = Buffer.from(material.iv, "base64"); + const tag3 = Buffer.from(material.tag, "base64"); + const ciphertext = Buffer.from(material.ciphertext, "base64"); + const decipher = createDecipheriv("aes-256-gcm", masterKey, iv); + decipher.setAuthTag(tag3); + const plain = Buffer.concat([decipher.update(ciphertext), decipher.final()]); + return plain.toString("utf8"); +} +function asLocalEncryptedMaterial(value) { + if (value && typeof value === "object" && value.scheme === "local_encrypted_v1" && typeof value.iv === "string" && typeof value.tag === "string" && typeof value.ciphertext === "string") { + return value; + } + throw badRequest("Invalid local_encrypted secret material"); +} +var localEncryptedProvider = { + id: "local_encrypted", + descriptor: { + id: "local_encrypted", + label: "Local encrypted (default)", + requiresExternalRef: false + }, + async createVersion(input) { + const masterKey = loadOrCreateMasterKey(); + return { + material: encryptValue(masterKey, input.value), + valueSha256: sha256Hex(input.value), + externalRef: null + }; + }, + async resolveVersion(input) { + const masterKey = loadOrCreateMasterKey(); + return decryptValue(masterKey, asLocalEncryptedMaterial(input.material)); + } +}; + +// server/src/secrets/external-stub-providers.ts +function unavailableProvider(id, label) { + return { + id, + descriptor: { + id, + label, + requiresExternalRef: true + }, + async createVersion() { + throw unprocessable(`${id} provider is not configured in this deployment`); + }, + async resolveVersion() { + throw unprocessable(`${id} provider is not configured in this deployment`); + } + }; +} +var awsSecretsManagerProvider = unavailableProvider( + "aws_secrets_manager", + "AWS Secrets Manager" +); +var gcpSecretManagerProvider = unavailableProvider( + "gcp_secret_manager", + "GCP Secret Manager" +); +var vaultProvider = unavailableProvider("vault", "HashiCorp Vault"); + +// server/src/secrets/provider-registry.ts +var providers = [ + localEncryptedProvider, + awsSecretsManagerProvider, + gcpSecretManagerProvider, + vaultProvider +]; +var providerById = new Map( + providers.map((provider) => [provider.id, provider]) +); +function getSecretProvider(id) { + const provider = providerById.get(id); + if (!provider) throw unprocessable(`Unsupported secret provider: ${id}`); + return provider; +} +function listSecretProviders() { + return providers.map((provider) => provider.descriptor); +} + +// server/src/services/secrets.ts +var ENV_KEY_RE = /^[A-Za-z_][A-Za-z0-9_]*$/; +var SENSITIVE_ENV_KEY_RE = /(api[-_]?key|access[-_]?token|auth(?:_?token)?|authorization|bearer|secret|passwd|password|credential|jwt|private[-_]?key|cookie|connectionstring)/i; +var REDACTED_SENTINEL = "***REDACTED***"; +function asRecord7(value) { + if (typeof value !== "object" || value === null || Array.isArray(value)) return null; + return value; +} +function isSensitiveEnvKey(key) { + return SENSITIVE_ENV_KEY_RE.test(key); +} +function canonicalizeBinding(binding) { + if (typeof binding === "string") { + return { type: "plain", value: binding }; + } + if (binding.type === "plain") { + return { type: "plain", value: String(binding.value) }; + } + return { + type: "secret_ref", + secretId: binding.secretId, + version: binding.version ?? "latest" + }; +} +function secretService(db) { + async function getById(id) { + return db.select().from(companySecrets).where(eq(companySecrets.id, id)).then((rows) => rows[0] ?? null); + } + async function getByName(companyId, name) { + return db.select().from(companySecrets).where(and(eq(companySecrets.companyId, companyId), eq(companySecrets.name, name))).then((rows) => rows[0] ?? null); + } + async function getSecretVersion(secretId, version3) { + return db.select().from(companySecretVersions).where( + and( + eq(companySecretVersions.secretId, secretId), + eq(companySecretVersions.version, version3) + ) + ).then((rows) => rows[0] ?? null); + } + async function assertSecretInCompany(companyId, secretId) { + const secret = await getById(secretId); + if (!secret) throw notFound("Secret not found"); + if (secret.companyId !== companyId) throw unprocessable("Secret must belong to same company"); + return secret; + } + async function resolveSecretValue(companyId, secretId, version3) { + const secret = await assertSecretInCompany(companyId, secretId); + const resolvedVersion = version3 === "latest" ? secret.latestVersion : version3; + const versionRow = await getSecretVersion(secret.id, resolvedVersion); + if (!versionRow) throw notFound("Secret version not found"); + const provider = getSecretProvider(secret.provider); + return provider.resolveVersion({ + material: versionRow.material, + externalRef: secret.externalRef + }); + } + async function normalizeEnvConfig(companyId, envValue, opts) { + const record2 = asRecord7(envValue); + if (!record2) throw unprocessable(`${opts?.fieldPath ?? "env"} must be an object`); + const normalized = {}; + for (const [key, rawBinding] of Object.entries(record2)) { + if (!ENV_KEY_RE.test(key)) { + throw unprocessable(`Invalid environment variable name: ${key}`); + } + const parsed = envBindingSchema.safeParse(rawBinding); + if (!parsed.success) { + throw unprocessable(`Invalid environment binding for key: ${key}`); + } + const binding = canonicalizeBinding(parsed.data); + if (binding.type === "plain") { + if (opts?.strictMode && isSensitiveEnvKey(key) && binding.value.trim().length > 0) { + throw unprocessable( + `Strict secret mode requires secret references for sensitive key: ${key}` + ); + } + if (binding.value === REDACTED_SENTINEL) { + throw unprocessable(`Refusing to persist redacted placeholder for key: ${key}`); + } + normalized[key] = binding; + continue; + } + await assertSecretInCompany(companyId, binding.secretId); + normalized[key] = { + type: "secret_ref", + secretId: binding.secretId, + version: binding.version + }; + } + return normalized; + } + async function normalizeAdapterConfigForPersistenceInternal(companyId, adapterConfig, opts) { + const normalized = { ...adapterConfig }; + if (!Object.prototype.hasOwnProperty.call(adapterConfig, "env")) { + return normalized; + } + normalized.env = await normalizeEnvConfig(companyId, adapterConfig.env, opts); + return normalized; + } + return { + listProviders: () => listSecretProviders(), + list: (companyId) => db.select().from(companySecrets).where(eq(companySecrets.companyId, companyId)).orderBy(desc(companySecrets.createdAt)), + getById, + getByName, + resolveSecretValue, + create: async (companyId, input, actor) => { + const existing = await getByName(companyId, input.name); + if (existing) throw conflict(`Secret already exists: ${input.name}`); + const provider = getSecretProvider(input.provider); + const prepared = await provider.createVersion({ + value: input.value, + externalRef: input.externalRef ?? null + }); + return db.transaction(async (tx) => { + const secret = await tx.insert(companySecrets).values({ + companyId, + name: input.name, + provider: input.provider, + externalRef: prepared.externalRef, + latestVersion: 1, + description: input.description ?? null, + createdByAgentId: actor?.agentId ?? null, + createdByUserId: actor?.userId ?? null + }).returning().then((rows) => rows[0]); + await tx.insert(companySecretVersions).values({ + secretId: secret.id, + version: 1, + material: prepared.material, + valueSha256: prepared.valueSha256, + createdByAgentId: actor?.agentId ?? null, + createdByUserId: actor?.userId ?? null + }); + return secret; + }); + }, + rotate: async (secretId, input, actor) => { + const secret = await getById(secretId); + if (!secret) throw notFound("Secret not found"); + const provider = getSecretProvider(secret.provider); + const nextVersion = secret.latestVersion + 1; + const prepared = await provider.createVersion({ + value: input.value, + externalRef: input.externalRef ?? secret.externalRef ?? null + }); + return db.transaction(async (tx) => { + await tx.insert(companySecretVersions).values({ + secretId: secret.id, + version: nextVersion, + material: prepared.material, + valueSha256: prepared.valueSha256, + createdByAgentId: actor?.agentId ?? null, + createdByUserId: actor?.userId ?? null + }); + const updated = await tx.update(companySecrets).set({ + latestVersion: nextVersion, + externalRef: prepared.externalRef, + updatedAt: /* @__PURE__ */ new Date() + }).where(eq(companySecrets.id, secret.id)).returning().then((rows) => rows[0] ?? null); + if (!updated) throw notFound("Secret not found"); + return updated; + }); + }, + update: async (secretId, patch) => { + const secret = await getById(secretId); + if (!secret) throw notFound("Secret not found"); + if (patch.name && patch.name !== secret.name) { + const duplicate = await getByName(secret.companyId, patch.name); + if (duplicate && duplicate.id !== secret.id) { + throw conflict(`Secret already exists: ${patch.name}`); + } + } + return db.update(companySecrets).set({ + name: patch.name ?? secret.name, + description: patch.description === void 0 ? secret.description : patch.description, + externalRef: patch.externalRef === void 0 ? secret.externalRef : patch.externalRef, + updatedAt: /* @__PURE__ */ new Date() + }).where(eq(companySecrets.id, secret.id)).returning().then((rows) => rows[0] ?? null); + }, + remove: async (secretId) => { + const secret = await getById(secretId); + if (!secret) return null; + await db.delete(companySecrets).where(eq(companySecrets.id, secretId)); + return secret; + }, + normalizeAdapterConfigForPersistence: async (companyId, adapterConfig, opts) => normalizeAdapterConfigForPersistenceInternal(companyId, adapterConfig, opts), + normalizeEnvBindingsForPersistence: async (companyId, envValue, opts) => normalizeEnvConfig(companyId, envValue, opts), + normalizeHireApprovalPayloadForPersistence: async (companyId, payload2, opts) => { + const normalized = { ...payload2 }; + const adapterConfig = asRecord7(payload2.adapterConfig); + if (adapterConfig) { + normalized.adapterConfig = await normalizeAdapterConfigForPersistenceInternal( + companyId, + adapterConfig, + opts + ); + } + return normalized; + }, + resolveEnvBindings: async (companyId, envValue) => { + const record2 = asRecord7(envValue); + if (!record2) return { env: {}, secretKeys: /* @__PURE__ */ new Set() }; + const resolved = {}; + const secretKeys = /* @__PURE__ */ new Set(); + for (const [key, rawBinding] of Object.entries(record2)) { + if (!ENV_KEY_RE.test(key)) { + throw unprocessable(`Invalid environment variable name: ${key}`); + } + const parsed = envBindingSchema.safeParse(rawBinding); + if (!parsed.success) { + throw unprocessable(`Invalid environment binding for key: ${key}`); + } + const binding = canonicalizeBinding(parsed.data); + if (binding.type === "plain") { + resolved[key] = binding.value; + } else { + resolved[key] = await resolveSecretValue(companyId, binding.secretId, binding.version); + secretKeys.add(key); + } + } + return { env: resolved, secretKeys }; + }, + resolveAdapterConfigForRuntime: async (companyId, adapterConfig) => { + const resolved = { ...adapterConfig }; + const secretKeys = /* @__PURE__ */ new Set(); + if (!Object.prototype.hasOwnProperty.call(adapterConfig, "env")) { + return { config: resolved, secretKeys }; + } + const record2 = asRecord7(adapterConfig.env); + if (!record2) { + resolved.env = {}; + return { config: resolved, secretKeys }; + } + const env2 = {}; + for (const [key, rawBinding] of Object.entries(record2)) { + if (!ENV_KEY_RE.test(key)) { + throw unprocessable(`Invalid environment variable name: ${key}`); + } + const parsed = envBindingSchema.safeParse(rawBinding); + if (!parsed.success) { + throw unprocessable(`Invalid environment binding for key: ${key}`); + } + const binding = canonicalizeBinding(parsed.data); + if (binding.type === "plain") { + env2[key] = binding.value; + } else { + env2[key] = await resolveSecretValue(companyId, binding.secretId, binding.version); + secretKeys.add(key); + } + } + resolved.env = env2; + return { config: resolved, secretKeys }; + } + }; +} + +// server/src/services/company-skills.ts +var skillInventoryRefreshPromises = /* @__PURE__ */ new Map(); +var PROJECT_SCAN_DIRECTORY_ROOTS = [ + "skills", + "skills/.curated", + "skills/.experimental", + "skills/.system", + ".agents/skills", + ".agent/skills", + ".augment/skills", + ".claude/skills", + ".codebuddy/skills", + ".commandcode/skills", + ".continue/skills", + ".cortex/skills", + ".crush/skills", + ".factory/skills", + ".goose/skills", + ".junie/skills", + ".iflow/skills", + ".kilocode/skills", + ".kiro/skills", + ".kode/skills", + ".mcpjam/skills", + ".vibe/skills", + ".mux/skills", + ".openhands/skills", + ".pi/skills", + ".qoder/skills", + ".qwen/skills", + ".roo/skills", + ".trae/skills", + ".windsurf/skills", + ".zencoder/skills", + ".neovate/skills", + ".pochi/skills", + ".adal/skills" +]; +var PROJECT_ROOT_SKILL_SUBDIRECTORIES = [ + "references", + "scripts", + "assets" +]; +function asString13(value) { + if (typeof value !== "string") return null; + const trimmed = value.trim(); + return trimmed.length > 0 ? trimmed : null; +} +function isPlainRecord3(value) { + return typeof value === "object" && value !== null && !Array.isArray(value); +} +function normalizePortablePath(input) { + const parts = []; + for (const segment of input.replace(/\\/g, "/").replace(/^\.\/+/, "").replace(/^\/+/, "").split("/")) { + if (!segment || segment === ".") continue; + if (segment === "..") { + if (parts.length > 0) parts.pop(); + continue; + } + parts.push(segment); + } + return parts.join("/"); +} +function normalizePackageFileMap(files) { + const out = {}; + for (const [rawPath, content] of Object.entries(files)) { + const nextPath = normalizePortablePath(rawPath); + if (!nextPath) continue; + out[nextPath] = content; + } + return out; +} +function normalizeSkillSlug2(value) { + return value ? normalizeAgentUrlKey(value) ?? null : null; +} +function normalizeSkillKey(value) { + if (!value) return null; + const segments = value.split("/").map((segment) => normalizeSkillSlug2(segment)).filter((segment) => Boolean(segment)); + return segments.length > 0 ? segments.join("/") : null; +} +function normalizeGitHubSkillDirectory(value, fallback) { + const normalized = normalizePortablePath(value ?? ""); + if (!normalized) return normalizePortablePath(fallback); + if (path34.posix.basename(normalized).toLowerCase() === "skill.md") { + return normalizePortablePath(path34.posix.dirname(normalized)); + } + return normalized; +} +function hashSkillValue(value) { + return createHash10("sha256").update(value).digest("hex").slice(0, 10); +} +function uniqueSkillSlug(baseSlug, usedSlugs) { + if (!usedSlugs.has(baseSlug)) return baseSlug; + let attempt = 2; + let candidate = `${baseSlug}-${attempt}`; + while (usedSlugs.has(candidate)) { + attempt += 1; + candidate = `${baseSlug}-${attempt}`; + } + return candidate; +} +function uniqueImportedSkillKey(companyId, baseSlug, usedKeys) { + const initial = `company/${companyId}/${baseSlug}`; + if (!usedKeys.has(initial)) return initial; + let attempt = 2; + let candidate = `company/${companyId}/${baseSlug}-${attempt}`; + while (usedKeys.has(candidate)) { + attempt += 1; + candidate = `company/${companyId}/${baseSlug}-${attempt}`; + } + return candidate; +} +function buildSkillRuntimeName(key, slug) { + if (key.startsWith("taskcore/taskcore/")) return slug; + return `${slug}--${hashSkillValue(key)}`; +} +function readCanonicalSkillKey(frontmatter, metadata) { + const direct = normalizeSkillKey( + asString13(frontmatter.key) ?? asString13(frontmatter.skillKey) ?? asString13(metadata?.skillKey) ?? asString13(metadata?.canonicalKey) ?? asString13(metadata?.taskcoreSkillKey) + ); + if (direct) return direct; + const taskcore = isPlainRecord3(metadata?.taskcore) ? metadata?.taskcore : null; + return normalizeSkillKey( + asString13(taskcore?.skillKey) ?? asString13(taskcore?.key) + ); +} +function deriveCanonicalSkillKey(companyId, input) { + const slug = normalizeSkillSlug2(input.slug) ?? "skill"; + const metadata = isPlainRecord3(input.metadata) ? input.metadata : null; + const explicitKey = readCanonicalSkillKey({}, metadata); + if (explicitKey) return explicitKey; + const sourceKind = asString13(metadata?.sourceKind); + if (sourceKind === "taskcore_bundled") { + return `taskcore/taskcore/${slug}`; + } + const owner = normalizeSkillSlug2(asString13(metadata?.owner)); + const repo = normalizeSkillSlug2(asString13(metadata?.repo)); + if ((input.sourceType === "github" || input.sourceType === "skills_sh" || sourceKind === "github" || sourceKind === "skills_sh") && owner && repo) { + return `${owner}/${repo}/${slug}`; + } + if (input.sourceType === "url" || sourceKind === "url") { + const locator = asString13(input.sourceLocator); + if (locator) { + try { + const url2 = new URL(locator); + const host = normalizeSkillSlug2(url2.host) ?? "url"; + return `url/${host}/${hashSkillValue(locator)}/${slug}`; + } catch { + return `url/unknown/${hashSkillValue(locator)}/${slug}`; + } + } + } + if (input.sourceType === "local_path") { + if (sourceKind === "managed_local") { + return `company/${companyId}/${slug}`; + } + const locator = asString13(input.sourceLocator); + if (locator) { + return `local/${hashSkillValue(path34.resolve(locator))}/${slug}`; + } + } + return `company/${companyId}/${slug}`; +} +function classifyInventoryKind(relativePath) { + const normalized = normalizePortablePath(relativePath).toLowerCase(); + if (normalized.endsWith("/skill.md") || normalized === "skill.md") return "skill"; + if (normalized.startsWith("references/")) return "reference"; + if (normalized.startsWith("scripts/")) return "script"; + if (normalized.startsWith("assets/")) return "asset"; + if (normalized.endsWith(".md")) return "markdown"; + const fileName = path34.posix.basename(normalized); + if (fileName.endsWith(".sh") || fileName.endsWith(".js") || fileName.endsWith(".mjs") || fileName.endsWith(".cjs") || fileName.endsWith(".ts") || fileName.endsWith(".py") || fileName.endsWith(".rb") || fileName.endsWith(".bash")) { + return "script"; + } + if (fileName.endsWith(".png") || fileName.endsWith(".jpg") || fileName.endsWith(".jpeg") || fileName.endsWith(".gif") || fileName.endsWith(".svg") || fileName.endsWith(".webp") || fileName.endsWith(".pdf")) { + return "asset"; + } + return "other"; +} +function deriveTrustLevel(fileInventory) { + if (fileInventory.some((entry) => entry.kind === "script")) return "scripts_executables"; + if (fileInventory.some((entry) => entry.kind === "asset" || entry.kind === "other")) return "assets"; + return "markdown_only"; +} +function prepareYamlLines(raw) { + return raw.split("\n").map((line3) => ({ + indent: line3.match(/^ */)?.[0].length ?? 0, + content: line3.trim() + })).filter((line3) => line3.content.length > 0 && !line3.content.startsWith("#")); +} +function parseYamlScalar(rawValue) { + const trimmed = rawValue.trim(); + if (trimmed === "") return ""; + if (trimmed === "null" || trimmed === "~") return null; + if (trimmed === "true") return true; + if (trimmed === "false") return false; + if (trimmed === "[]") return []; + if (trimmed === "{}") return {}; + if (/^-?\d+(\.\d+)?$/.test(trimmed)) return Number(trimmed); + if (trimmed.startsWith('"') || trimmed.startsWith("[") || trimmed.startsWith("{")) { + try { + return JSON.parse(trimmed); + } catch { + return trimmed; + } + } + return trimmed; +} +function parseYamlBlock(lines, startIndex, indentLevel) { + let index2 = startIndex; + while (index2 < lines.length && lines[index2].content.length === 0) index2 += 1; + if (index2 >= lines.length || lines[index2].indent < indentLevel) { + return { value: {}, nextIndex: index2 }; + } + const isArray = lines[index2].indent === indentLevel && lines[index2].content.startsWith("-"); + if (isArray) { + const values2 = []; + while (index2 < lines.length) { + const line3 = lines[index2]; + if (line3.indent < indentLevel) break; + if (line3.indent !== indentLevel || !line3.content.startsWith("-")) break; + const remainder = line3.content.slice(1).trim(); + index2 += 1; + if (!remainder) { + const nested = parseYamlBlock(lines, index2, indentLevel + 2); + values2.push(nested.value); + index2 = nested.nextIndex; + continue; + } + const inlineObjectSeparator = remainder.indexOf(":"); + if (inlineObjectSeparator > 0 && !remainder.startsWith('"') && !remainder.startsWith("{") && !remainder.startsWith("[")) { + const key = remainder.slice(0, inlineObjectSeparator).trim(); + const rawValue = remainder.slice(inlineObjectSeparator + 1).trim(); + const nextObject = { + [key]: parseYamlScalar(rawValue) + }; + if (index2 < lines.length && lines[index2].indent > indentLevel) { + const nested = parseYamlBlock(lines, index2, indentLevel + 2); + if (isPlainRecord3(nested.value)) { + Object.assign(nextObject, nested.value); + } + index2 = nested.nextIndex; + } + values2.push(nextObject); + continue; + } + values2.push(parseYamlScalar(remainder)); + } + return { value: values2, nextIndex: index2 }; + } + const record2 = {}; + while (index2 < lines.length) { + const line3 = lines[index2]; + if (line3.indent < indentLevel) break; + if (line3.indent !== indentLevel) { + index2 += 1; + continue; + } + const separatorIndex = line3.content.indexOf(":"); + if (separatorIndex <= 0) { + index2 += 1; + continue; + } + const key = line3.content.slice(0, separatorIndex).trim(); + const remainder = line3.content.slice(separatorIndex + 1).trim(); + index2 += 1; + if (!remainder) { + const nested = parseYamlBlock(lines, index2, indentLevel + 2); + record2[key] = nested.value; + index2 = nested.nextIndex; + continue; + } + record2[key] = parseYamlScalar(remainder); + } + return { value: record2, nextIndex: index2 }; +} +function parseYamlFrontmatter(raw) { + const prepared = prepareYamlLines(raw); + if (prepared.length === 0) return {}; + const parsed = parseYamlBlock(prepared, 0, prepared[0].indent); + return isPlainRecord3(parsed.value) ? parsed.value : {}; +} +function parseFrontmatterMarkdown(raw) { + const normalized = raw.replace(/\r\n/g, "\n"); + if (!normalized.startsWith("---\n")) { + return { frontmatter: {}, body: normalized.trim() }; + } + const closing = normalized.indexOf("\n---\n", 4); + if (closing < 0) { + return { frontmatter: {}, body: normalized.trim() }; + } + const frontmatterRaw = normalized.slice(4, closing).trim(); + const body = normalized.slice(closing + 5).trim(); + return { + frontmatter: parseYamlFrontmatter(frontmatterRaw), + body + }; +} +async function fetchText(url2) { + const response = await ghFetch(url2); + if (!response.ok) { + throw unprocessable(`Failed to fetch ${url2}: ${response.status}`); + } + return response.text(); +} +async function fetchJson(url2) { + const response = await ghFetch(url2, { + headers: { + accept: "application/vnd.github+json" + } + }); + if (!response.ok) { + throw unprocessable(`Failed to fetch ${url2}: ${response.status}`); + } + return response.json(); +} +async function resolveGitHubDefaultBranch(owner, repo, apiBase) { + const response = await fetchJson( + `${apiBase}/repos/${owner}/${repo}` + ); + return asString13(response.default_branch) ?? "main"; +} +async function resolveGitHubCommitSha(owner, repo, ref, apiBase) { + const response = await fetchJson( + `${apiBase}/repos/${owner}/${repo}/commits/${encodeURIComponent(ref)}` + ); + const sha = asString13(response.sha); + if (!sha) { + throw unprocessable(`Failed to resolve GitHub ref ${ref}`); + } + return sha; +} +function parseGitHubSourceUrl(rawUrl) { + const url2 = new URL(rawUrl); + if (url2.protocol !== "https:") { + throw unprocessable("GitHub source URL must use HTTPS"); + } + const parts = url2.pathname.split("/").filter(Boolean); + if (parts.length < 2) { + throw unprocessable("Invalid GitHub URL"); + } + const owner = parts[0]; + const repo = parts[1].replace(/\.git$/i, ""); + let ref = "main"; + let basePath = ""; + let filePath = null; + let explicitRef = false; + if (parts[2] === "tree") { + ref = parts[3] ?? "main"; + basePath = parts.slice(4).join("/"); + explicitRef = true; + } else if (parts[2] === "blob") { + ref = parts[3] ?? "main"; + filePath = parts.slice(4).join("/"); + basePath = filePath ? path34.posix.dirname(filePath) : ""; + explicitRef = true; + } + return { hostname: url2.hostname, owner, repo, ref, basePath, filePath, explicitRef }; +} +async function resolveGitHubPinnedRef(parsed) { + const apiBase = gitHubApiBase(parsed.hostname); + if (/^[0-9a-f]{40}$/i.test(parsed.ref.trim())) { + return { + pinnedRef: parsed.ref, + trackingRef: parsed.explicitRef ? parsed.ref : null + }; + } + const trackingRef = parsed.explicitRef ? parsed.ref : await resolveGitHubDefaultBranch(parsed.owner, parsed.repo, apiBase); + const pinnedRef = await resolveGitHubCommitSha(parsed.owner, parsed.repo, trackingRef, apiBase); + return { pinnedRef, trackingRef }; +} +function extractCommandTokens(raw) { + const matches = raw.match(/"[^"]*"|'[^']*'|\S+/g) ?? []; + return matches.map((token) => token.replace(/^['"]|['"]$/g, "")); +} +function parseSkillImportSourceInput(rawInput) { + const trimmed = rawInput.trim(); + if (!trimmed) { + throw unprocessable("Skill source is required."); + } + const warnings = []; + let source = trimmed; + let requestedSkillSlug = null; + if (/^npx\s+skills\s+add\s+/i.test(trimmed)) { + const tokens = extractCommandTokens(trimmed); + const addIndex = tokens.findIndex( + (token, index2) => token === "add" && index2 > 0 && tokens[index2 - 1]?.toLowerCase() === "skills" + ); + if (addIndex >= 0) { + source = tokens[addIndex + 1] ?? ""; + for (let index2 = addIndex + 2; index2 < tokens.length; index2 += 1) { + const token = tokens[index2]; + if (token === "--skill") { + requestedSkillSlug = normalizeSkillSlug2(tokens[index2 + 1] ?? null); + index2 += 1; + continue; + } + if (token.startsWith("--skill=")) { + requestedSkillSlug = normalizeSkillSlug2(token.slice("--skill=".length)); + } + } + } + } + const normalizedSource = source.trim(); + if (!normalizedSource) { + throw unprocessable("Skill source is required."); + } + if (!/^https?:\/\//i.test(normalizedSource) && /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(normalizedSource)) { + const [owner, repo, skillSlugRaw] = normalizedSource.split("/"); + return { + resolvedSource: `https://github.com/${owner}/${repo}`, + requestedSkillSlug: normalizeSkillSlug2(skillSlugRaw), + originalSkillsShUrl: `https://skills.sh/${owner}/${repo}/${skillSlugRaw}`, + warnings + }; + } + if (!/^https?:\/\//i.test(normalizedSource) && /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(normalizedSource)) { + return { + resolvedSource: `https://github.com/${normalizedSource}`, + requestedSkillSlug, + originalSkillsShUrl: null, + warnings + }; + } + const skillsShMatch = normalizedSource.match(/^https?:\/\/(?:www\.)?skills\.sh\/([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)(?:\/([A-Za-z0-9_.-]+))?(?:[?#].*)?$/i); + if (skillsShMatch) { + const [, owner, repo, skillSlugRaw] = skillsShMatch; + return { + resolvedSource: `https://github.com/${owner}/${repo}`, + requestedSkillSlug: skillSlugRaw ? normalizeSkillSlug2(skillSlugRaw) : requestedSkillSlug, + originalSkillsShUrl: normalizedSource, + warnings + }; + } + return { + resolvedSource: normalizedSource, + requestedSkillSlug, + originalSkillsShUrl: null, + warnings + }; +} +function resolveBundledSkillsRoot() { + const moduleDir = path34.dirname(fileURLToPath15(import.meta.url)); + return [ + path34.resolve(moduleDir, "../../skills"), + path34.resolve(process.cwd(), "skills"), + path34.resolve(moduleDir, "../../../skills") + ]; +} +function matchesRequestedSkill(relativeSkillPath, requestedSkillSlug) { + if (!requestedSkillSlug) return true; + const skillDir = path34.posix.dirname(relativeSkillPath); + return normalizeSkillSlug2(path34.posix.basename(skillDir)) === requestedSkillSlug; +} +function deriveImportedSkillSlug(frontmatter, fallback) { + return normalizeSkillSlug2(asString13(frontmatter.slug)) ?? normalizeSkillSlug2(asString13(frontmatter.name)) ?? normalizeAgentUrlKey(fallback) ?? "skill"; +} +function deriveImportedSkillSource(frontmatter, fallbackSlug) { + const metadata = isPlainRecord3(frontmatter.metadata) ? frontmatter.metadata : null; + const canonicalKey = readCanonicalSkillKey(frontmatter, metadata); + const rawSources = metadata && Array.isArray(metadata.sources) ? metadata.sources : []; + const sourceEntry = rawSources.find((entry) => isPlainRecord3(entry)); + const kind = asString13(sourceEntry?.kind); + if (kind === "github-dir" || kind === "github-file") { + const repo = asString13(sourceEntry?.repo); + const repoPath = asString13(sourceEntry?.path); + const commit = asString13(sourceEntry?.commit); + const trackingRef = asString13(sourceEntry?.trackingRef); + const sourceHostname = asString13(sourceEntry?.hostname) || "github.com"; + const url2 = asString13(sourceEntry?.url) ?? (repo ? `https://${sourceHostname}/${repo}${repoPath ? `/tree/${trackingRef ?? commit ?? "main"}/${repoPath}` : ""}` : null); + const [owner, repoName] = (repo ?? "").split("/"); + if (repo && owner && repoName) { + return { + sourceType: "github", + sourceLocator: url2, + sourceRef: commit, + metadata: { + ...canonicalKey ? { skillKey: canonicalKey } : {}, + sourceKind: "github", + ...sourceHostname !== "github.com" ? { hostname: sourceHostname } : {}, + owner, + repo: repoName, + ref: commit, + trackingRef, + repoSkillDir: repoPath ?? `skills/${fallbackSlug}` + } + }; + } + } + if (kind === "url") { + const url2 = asString13(sourceEntry?.url) ?? asString13(sourceEntry?.rawUrl); + if (url2) { + return { + sourceType: "url", + sourceLocator: url2, + sourceRef: null, + metadata: { + ...canonicalKey ? { skillKey: canonicalKey } : {}, + sourceKind: "url" + } + }; + } + } + return { + sourceType: "catalog", + sourceLocator: null, + sourceRef: null, + metadata: { + ...canonicalKey ? { skillKey: canonicalKey } : {}, + sourceKind: "catalog" + } + }; +} +function readInlineSkillImports(companyId, files) { + const normalizedFiles = normalizePackageFileMap(files); + const skillPaths = Object.keys(normalizedFiles).filter( + (entry) => path34.posix.basename(entry).toLowerCase() === "skill.md" + ); + const imports = []; + for (const skillPath of skillPaths) { + const dir = path34.posix.dirname(skillPath); + const skillDir = dir === "." ? "" : dir; + const slugFallback = path34.posix.basename(skillDir || path34.posix.dirname(skillPath)); + const markdown = normalizedFiles[skillPath]; + const parsed = parseFrontmatterMarkdown(markdown); + const slug = deriveImportedSkillSlug(parsed.frontmatter, slugFallback); + const source = deriveImportedSkillSource(parsed.frontmatter, slug); + const inventory = Object.keys(normalizedFiles).filter((entry) => entry === skillPath || (skillDir ? entry.startsWith(`${skillDir}/`) : false)).map((entry) => { + const relative3 = entry === skillPath ? "SKILL.md" : entry.slice(skillDir.length + 1); + return { + path: normalizePortablePath(relative3), + kind: classifyInventoryKind(relative3) + }; + }).sort((left, right) => left.path.localeCompare(right.path)); + imports.push({ + key: "", + slug, + name: asString13(parsed.frontmatter.name) ?? slug, + description: asString13(parsed.frontmatter.description), + markdown, + packageDir: skillDir, + sourceType: source.sourceType, + sourceLocator: source.sourceLocator, + sourceRef: source.sourceRef, + trustLevel: deriveTrustLevel(inventory), + compatibility: "compatible", + fileInventory: inventory, + metadata: source.metadata + }); + imports[imports.length - 1].key = deriveCanonicalSkillKey(companyId, imports[imports.length - 1]); + } + return imports; +} +async function walkLocalFiles(root, current, out) { + const entries2 = await fs27.readdir(current, { withFileTypes: true }); + for (const entry of entries2) { + if (entry.name === ".git" || entry.name === "node_modules") continue; + const absolutePath = path34.join(current, entry.name); + if (entry.isDirectory()) { + await walkLocalFiles(root, absolutePath, out); + continue; + } + if (!entry.isFile()) continue; + out.push(normalizePortablePath(path34.relative(root, absolutePath))); + } +} +async function statPath(targetPath) { + return fs27.stat(targetPath).catch(() => null); +} +async function collectLocalSkillInventory(skillDir, mode = "full") { + const skillFilePath = path34.join(skillDir, "SKILL.md"); + const skillFileStat = await statPath(skillFilePath); + if (!skillFileStat?.isFile()) { + throw unprocessable(`No SKILL.md file was found in ${skillDir}.`); + } + const allFiles = /* @__PURE__ */ new Set(["SKILL.md"]); + if (mode === "full") { + const discoveredFiles = []; + await walkLocalFiles(skillDir, skillDir, discoveredFiles); + for (const relativePath of discoveredFiles) { + allFiles.add(relativePath); + } + } else { + for (const relativeDir of PROJECT_ROOT_SKILL_SUBDIRECTORIES) { + const absoluteDir = path34.join(skillDir, relativeDir); + const dirStat = await statPath(absoluteDir); + if (!dirStat?.isDirectory()) continue; + const discoveredFiles = []; + await walkLocalFiles(skillDir, absoluteDir, discoveredFiles); + for (const relativePath of discoveredFiles) { + allFiles.add(relativePath); + } + } + } + return Array.from(allFiles).map((relativePath) => ({ + path: normalizePortablePath(relativePath), + kind: classifyInventoryKind(relativePath) + })).sort((left, right) => left.path.localeCompare(right.path)); +} +async function readLocalSkillImportFromDirectory(companyId, skillDir, options) { + const resolvedSkillDir = path34.resolve(skillDir); + const skillFilePath = path34.join(resolvedSkillDir, "SKILL.md"); + const markdown = await fs27.readFile(skillFilePath, "utf8"); + const parsed = parseFrontmatterMarkdown(markdown); + const slug = deriveImportedSkillSlug(parsed.frontmatter, path34.basename(resolvedSkillDir)); + const parsedMetadata = isPlainRecord3(parsed.frontmatter.metadata) ? parsed.frontmatter.metadata : null; + const skillKey = readCanonicalSkillKey(parsed.frontmatter, parsedMetadata); + const metadata = { + ...skillKey ? { skillKey } : {}, + ...parsedMetadata ?? {}, + sourceKind: "local_path", + ...options?.metadata ?? {} + }; + const inventory = await collectLocalSkillInventory(resolvedSkillDir, options?.inventoryMode ?? "full"); + return { + key: deriveCanonicalSkillKey(companyId, { + slug, + sourceType: "local_path", + sourceLocator: resolvedSkillDir, + metadata + }), + slug, + name: asString13(parsed.frontmatter.name) ?? slug, + description: asString13(parsed.frontmatter.description), + markdown, + packageDir: resolvedSkillDir, + sourceType: "local_path", + sourceLocator: resolvedSkillDir, + sourceRef: null, + trustLevel: deriveTrustLevel(inventory), + compatibility: "compatible", + fileInventory: inventory, + metadata + }; +} +async function discoverProjectWorkspaceSkillDirectories(target) { + const discovered = /* @__PURE__ */ new Map(); + const rootSkillPath = path34.join(target.workspaceCwd, "SKILL.md"); + if ((await statPath(rootSkillPath))?.isFile()) { + discovered.set(path34.resolve(target.workspaceCwd), "project_root"); + } + for (const relativeRoot of PROJECT_SCAN_DIRECTORY_ROOTS) { + const absoluteRoot = path34.join(target.workspaceCwd, relativeRoot); + const rootStat = await statPath(absoluteRoot); + if (!rootStat?.isDirectory()) continue; + const entries2 = await fs27.readdir(absoluteRoot, { withFileTypes: true }).catch(() => []); + for (const entry of entries2) { + if (!entry.isDirectory()) continue; + const absoluteSkillDir = path34.resolve(absoluteRoot, entry.name); + if (!(await statPath(path34.join(absoluteSkillDir, "SKILL.md")))?.isFile()) continue; + discovered.set(absoluteSkillDir, "full"); + } + } + return Array.from(discovered.entries()).map(([skillDir, inventoryMode]) => ({ skillDir, inventoryMode })).sort((left, right) => left.skillDir.localeCompare(right.skillDir)); +} +async function readLocalSkillImports(companyId, sourcePath) { + const resolvedPath2 = path34.resolve(sourcePath); + const stat5 = await fs27.stat(resolvedPath2).catch(() => null); + if (!stat5) { + throw unprocessable(`Skill source path does not exist: ${sourcePath}`); + } + if (stat5.isFile()) { + const markdown = await fs27.readFile(resolvedPath2, "utf8"); + const parsed = parseFrontmatterMarkdown(markdown); + const slug = deriveImportedSkillSlug(parsed.frontmatter, path34.basename(path34.dirname(resolvedPath2))); + const parsedMetadata = isPlainRecord3(parsed.frontmatter.metadata) ? parsed.frontmatter.metadata : null; + const skillKey = readCanonicalSkillKey(parsed.frontmatter, parsedMetadata); + const metadata = { + ...skillKey ? { skillKey } : {}, + ...parsedMetadata ?? {}, + sourceKind: "local_path" + }; + const inventory = [ + { path: "SKILL.md", kind: "skill" } + ]; + return [{ + key: deriveCanonicalSkillKey(companyId, { + slug, + sourceType: "local_path", + sourceLocator: path34.dirname(resolvedPath2), + metadata + }), + slug, + name: asString13(parsed.frontmatter.name) ?? slug, + description: asString13(parsed.frontmatter.description), + markdown, + packageDir: path34.dirname(resolvedPath2), + sourceType: "local_path", + sourceLocator: path34.dirname(resolvedPath2), + sourceRef: null, + trustLevel: deriveTrustLevel(inventory), + compatibility: "compatible", + fileInventory: inventory, + metadata + }]; + } + const root = resolvedPath2; + const allFiles = []; + await walkLocalFiles(root, root, allFiles); + const skillPaths = allFiles.filter((entry) => path34.posix.basename(entry).toLowerCase() === "skill.md"); + if (skillPaths.length === 0) { + throw unprocessable("No SKILL.md files were found in the provided path."); + } + const imports = []; + for (const skillPath of skillPaths) { + const skillDir = path34.posix.dirname(skillPath); + const inventory = allFiles.filter((entry) => entry === skillPath || entry.startsWith(`${skillDir}/`)).map((entry) => { + const relative3 = entry === skillPath ? "SKILL.md" : entry.slice(skillDir.length + 1); + return { + path: normalizePortablePath(relative3), + kind: classifyInventoryKind(relative3) + }; + }).sort((left, right) => left.path.localeCompare(right.path)); + const imported = await readLocalSkillImportFromDirectory(companyId, path34.join(root, skillDir)); + imported.fileInventory = inventory; + imported.trustLevel = deriveTrustLevel(inventory); + imports.push(imported); + } + return imports; +} +async function readUrlSkillImports(companyId, sourceUrl, requestedSkillSlug = null) { + const url2 = sourceUrl.trim(); + const warnings = []; + const looksLikeRepoUrl = (() => { + try { + const parsed = new URL(url2); + if (parsed.protocol !== "https:") return false; + const h5 = parsed.hostname.toLowerCase(); + if (h5.endsWith(".githubusercontent.com") || h5 === "gist.github.com") return false; + const segments = parsed.pathname.split("/").filter(Boolean); + return segments.length >= 2 && !parsed.pathname.endsWith(".md"); + } catch { + return false; + } + })(); + if (looksLikeRepoUrl) { + const parsed = parseGitHubSourceUrl(url2); + const apiBase = gitHubApiBase(parsed.hostname); + const { pinnedRef, trackingRef } = await resolveGitHubPinnedRef(parsed); + let ref = pinnedRef; + const tree = await fetchJson( + `${apiBase}/repos/${parsed.owner}/${parsed.repo}/git/trees/${ref}?recursive=1` + ).catch(() => { + throw unprocessable(`Failed to read GitHub tree for ${url2}`); + }); + const allPaths = (tree.tree ?? []).filter((entry) => entry.type === "blob").map((entry) => entry.path).filter((entry) => typeof entry === "string"); + const basePrefix = parsed.basePath ? `${parsed.basePath.replace(/^\/+|\/+$/g, "")}/` : ""; + const scopedPaths = basePrefix ? allPaths.filter((entry) => entry.startsWith(basePrefix)) : allPaths; + const relativePaths = scopedPaths.map((entry) => basePrefix ? entry.slice(basePrefix.length) : entry); + const filteredPaths = parsed.filePath ? relativePaths.filter((entry) => entry === path34.posix.relative(parsed.basePath || ".", parsed.filePath)) : relativePaths; + const skillPaths = filteredPaths.filter( + (entry) => path34.posix.basename(entry).toLowerCase() === "skill.md" + ); + if (skillPaths.length === 0) { + throw unprocessable( + "No SKILL.md files were found in the provided GitHub source." + ); + } + const skills = []; + for (const relativeSkillPath of skillPaths) { + const repoSkillPath = basePrefix ? `${basePrefix}${relativeSkillPath}` : relativeSkillPath; + const markdown = await fetchText(resolveRawGitHubUrl(parsed.hostname, parsed.owner, parsed.repo, ref, repoSkillPath)); + const parsedMarkdown = parseFrontmatterMarkdown(markdown); + const skillDir = path34.posix.dirname(relativeSkillPath); + const slug = deriveImportedSkillSlug(parsedMarkdown.frontmatter, path34.posix.basename(skillDir)); + const skillKey = readCanonicalSkillKey( + parsedMarkdown.frontmatter, + isPlainRecord3(parsedMarkdown.frontmatter.metadata) ? parsedMarkdown.frontmatter.metadata : null + ); + if (requestedSkillSlug && !matchesRequestedSkill(relativeSkillPath, requestedSkillSlug) && slug !== requestedSkillSlug) { + continue; + } + const metadata = { + ...skillKey ? { skillKey } : {}, + sourceKind: "github", + ...parsed.hostname !== "github.com" ? { hostname: parsed.hostname } : {}, + owner: parsed.owner, + repo: parsed.repo, + ref, + trackingRef, + repoSkillDir: normalizeGitHubSkillDirectory( + basePrefix ? `${basePrefix}${skillDir}` : skillDir, + slug + ) + }; + const inventory = filteredPaths.filter((entry) => entry === relativeSkillPath || entry.startsWith(`${skillDir}/`)).map((entry) => ({ + path: entry === relativeSkillPath ? "SKILL.md" : entry.slice(skillDir.length + 1), + kind: classifyInventoryKind(entry === relativeSkillPath ? "SKILL.md" : entry.slice(skillDir.length + 1)) + })).sort((left, right) => left.path.localeCompare(right.path)); + skills.push({ + key: deriveCanonicalSkillKey(companyId, { + slug, + sourceType: "github", + sourceLocator: sourceUrl, + metadata + }), + slug, + name: asString13(parsedMarkdown.frontmatter.name) ?? slug, + description: asString13(parsedMarkdown.frontmatter.description), + markdown, + sourceType: "github", + sourceLocator: sourceUrl, + sourceRef: ref, + trustLevel: deriveTrustLevel(inventory), + compatibility: "compatible", + fileInventory: inventory, + metadata + }); + } + if (skills.length === 0) { + throw unprocessable( + requestedSkillSlug ? `Skill ${requestedSkillSlug} was not found in the provided GitHub source.` : "No SKILL.md files were found in the provided GitHub source." + ); + } + return { skills, warnings }; + } + if (url2.startsWith("http://") || url2.startsWith("https://")) { + const markdown = await fetchText(url2); + const parsedMarkdown = parseFrontmatterMarkdown(markdown); + const urlObj = new URL(url2); + const fileName = path34.posix.basename(urlObj.pathname); + const slug = deriveImportedSkillSlug(parsedMarkdown.frontmatter, fileName.replace(/\.md$/i, "")); + const skillKey = readCanonicalSkillKey( + parsedMarkdown.frontmatter, + isPlainRecord3(parsedMarkdown.frontmatter.metadata) ? parsedMarkdown.frontmatter.metadata : null + ); + const metadata = { + ...skillKey ? { skillKey } : {}, + sourceKind: "url" + }; + const inventory = [{ path: "SKILL.md", kind: "skill" }]; + return { + skills: [{ + key: deriveCanonicalSkillKey(companyId, { + slug, + sourceType: "url", + sourceLocator: url2, + metadata + }), + slug, + name: asString13(parsedMarkdown.frontmatter.name) ?? slug, + description: asString13(parsedMarkdown.frontmatter.description), + markdown, + sourceType: "url", + sourceLocator: url2, + sourceRef: null, + trustLevel: deriveTrustLevel(inventory), + compatibility: "compatible", + fileInventory: inventory, + metadata + }], + warnings + }; + } + throw unprocessable("Unsupported skill source. Use a local path or URL."); +} +function toCompanySkill(row) { + return { + ...row, + description: row.description ?? null, + sourceType: row.sourceType, + sourceLocator: row.sourceLocator ?? null, + sourceRef: row.sourceRef ?? null, + trustLevel: row.trustLevel, + compatibility: row.compatibility, + fileInventory: Array.isArray(row.fileInventory) ? row.fileInventory.flatMap((entry) => { + if (!isPlainRecord3(entry)) return []; + return [{ + path: String(entry.path ?? ""), + kind: String(entry.kind ?? "other") + }]; + }) : [], + metadata: isPlainRecord3(row.metadata) ? row.metadata : null + }; +} +function serializeFileInventory(fileInventory) { + return fileInventory.map((entry) => ({ + path: entry.path, + kind: entry.kind + })); +} +function getSkillMeta(skill) { + return isPlainRecord3(skill.metadata) ? skill.metadata : {}; +} +function resolveSkillReference(skills, reference) { + const trimmed = reference.trim(); + if (!trimmed) { + return { skill: null, ambiguous: false }; + } + const byId = skills.find((skill) => skill.id === trimmed); + if (byId) { + return { skill: byId, ambiguous: false }; + } + const normalizedKey = normalizeSkillKey(trimmed); + if (normalizedKey) { + const byKey = skills.find((skill) => skill.key === normalizedKey); + if (byKey) { + return { skill: byKey, ambiguous: false }; + } + } + const normalizedSlug = normalizeSkillSlug2(trimmed); + if (!normalizedSlug) { + return { skill: null, ambiguous: false }; + } + const bySlug = skills.filter((skill) => skill.slug === normalizedSlug); + if (bySlug.length === 1) { + return { skill: bySlug[0] ?? null, ambiguous: false }; + } + if (bySlug.length > 1) { + return { skill: null, ambiguous: true }; + } + return { skill: null, ambiguous: false }; +} +function resolveRequestedSkillKeysOrThrow(skills, requestedReferences) { + const missing = /* @__PURE__ */ new Set(); + const ambiguous = /* @__PURE__ */ new Set(); + const resolved = /* @__PURE__ */ new Set(); + for (const reference of requestedReferences) { + const trimmed = reference.trim(); + if (!trimmed) continue; + const match = resolveSkillReference(skills, trimmed); + if (match.skill) { + resolved.add(match.skill.key); + continue; + } + if (match.ambiguous) { + ambiguous.add(trimmed); + continue; + } + missing.add(trimmed); + } + if (ambiguous.size > 0 || missing.size > 0) { + const problems = []; + if (ambiguous.size > 0) { + problems.push(`ambiguous references: ${Array.from(ambiguous).sort().join(", ")}`); + } + if (missing.size > 0) { + problems.push(`unknown references: ${Array.from(missing).sort().join(", ")}`); + } + throw unprocessable(`Invalid company skill selection (${problems.join("; ")}).`); + } + return Array.from(resolved); +} +function resolveDesiredSkillKeys(skills, config3) { + const preference = readTaskcoreSkillSyncPreference(config3); + return Array.from(new Set( + preference.desiredSkills.map((reference) => resolveSkillReference(skills, reference).skill?.key ?? normalizeSkillKey(reference)).filter((value) => Boolean(value)) + )); +} +function normalizeSkillDirectory(skill) { + if (skill.sourceType !== "local_path" && skill.sourceType !== "catalog" || !skill.sourceLocator) return null; + const resolved = path34.resolve(skill.sourceLocator); + if (path34.basename(resolved).toLowerCase() === "skill.md") { + return path34.dirname(resolved); + } + return resolved; +} +function normalizeSourceLocatorDirectory(sourceLocator) { + if (!sourceLocator) return null; + const resolved = path34.resolve(sourceLocator); + return path34.basename(resolved).toLowerCase() === "skill.md" ? path34.dirname(resolved) : resolved; +} +async function findMissingLocalSkillIds(skills) { + const missingIds = []; + for (const skill of skills) { + if (skill.sourceType !== "local_path") continue; + const skillDir = normalizeSourceLocatorDirectory(skill.sourceLocator); + if (!skillDir) { + missingIds.push(skill.id); + continue; + } + const skillDirStat = await statPath(skillDir); + const skillFileStat = await statPath(path34.join(skillDir, "SKILL.md")); + if (!skillDirStat?.isDirectory() || !skillFileStat?.isFile()) { + missingIds.push(skill.id); + } + } + return missingIds; +} +function resolveManagedSkillsRoot(companyId) { + return path34.resolve(resolveTaskcoreInstanceRoot(), "skills", companyId); +} +function resolveLocalSkillFilePath(skill, relativePath) { + const normalized = normalizePortablePath(relativePath); + const skillDir = normalizeSkillDirectory(skill); + if (skillDir) { + return path34.resolve(skillDir, normalized); + } + if (!skill.sourceLocator) return null; + const fallbackRoot = path34.resolve(skill.sourceLocator); + const directPath = path34.resolve(fallbackRoot, normalized); + return directPath; +} +function inferLanguageFromPath(filePath) { + const fileName = path34.posix.basename(filePath).toLowerCase(); + if (fileName === "skill.md" || fileName.endsWith(".md")) return "markdown"; + if (fileName.endsWith(".ts")) return "typescript"; + if (fileName.endsWith(".tsx")) return "tsx"; + if (fileName.endsWith(".js")) return "javascript"; + if (fileName.endsWith(".jsx")) return "jsx"; + if (fileName.endsWith(".json")) return "json"; + if (fileName.endsWith(".yml") || fileName.endsWith(".yaml")) return "yaml"; + if (fileName.endsWith(".sh")) return "bash"; + if (fileName.endsWith(".py")) return "python"; + if (fileName.endsWith(".html")) return "html"; + if (fileName.endsWith(".css")) return "css"; + return null; +} +function isMarkdownPath(filePath) { + const fileName = path34.posix.basename(filePath).toLowerCase(); + return fileName === "skill.md" || fileName.endsWith(".md"); +} +function deriveSkillSourceInfo(skill) { + const metadata = getSkillMeta(skill); + const localSkillDir = normalizeSkillDirectory(skill); + if (metadata.sourceKind === "taskcore_bundled") { + return { + editable: false, + editableReason: "Bundled Taskcore skills are read-only.", + sourceLabel: "Taskcore bundled", + sourceBadge: "taskcore", + sourcePath: null + }; + } + if (skill.sourceType === "skills_sh") { + const owner = asString13(metadata.owner) ?? null; + const repo = asString13(metadata.repo) ?? null; + return { + editable: false, + editableReason: "Skills.sh-managed skills are read-only.", + sourceLabel: skill.sourceLocator ?? (owner && repo ? `${owner}/${repo}` : null), + sourceBadge: "skills_sh", + sourcePath: null + }; + } + if (skill.sourceType === "github") { + const owner = asString13(metadata.owner) ?? null; + const repo = asString13(metadata.repo) ?? null; + return { + editable: false, + editableReason: "Remote GitHub skills are read-only. Fork or import locally to edit them.", + sourceLabel: owner && repo ? `${owner}/${repo}` : skill.sourceLocator, + sourceBadge: "github", + sourcePath: null + }; + } + if (skill.sourceType === "url") { + return { + editable: false, + editableReason: "URL-based skills are read-only. Save them locally to edit them.", + sourceLabel: skill.sourceLocator, + sourceBadge: "url", + sourcePath: null + }; + } + if (skill.sourceType === "local_path") { + const managedRoot = resolveManagedSkillsRoot(skill.companyId); + const projectName = asString13(metadata.projectName); + const workspaceName = asString13(metadata.workspaceName); + const isProjectScan = metadata.sourceKind === "project_scan"; + if (localSkillDir && localSkillDir.startsWith(managedRoot)) { + return { + editable: true, + editableReason: null, + sourceLabel: "Taskcore workspace", + sourceBadge: "taskcore", + sourcePath: managedRoot + }; + } + return { + editable: true, + editableReason: null, + sourceLabel: isProjectScan ? [projectName, workspaceName].filter((value) => Boolean(value)).join(" / ") || skill.sourceLocator : skill.sourceLocator, + sourceBadge: "local", + sourcePath: null + }; + } + return { + editable: false, + editableReason: "This skill source is read-only.", + sourceLabel: skill.sourceLocator, + sourceBadge: "catalog", + sourcePath: null + }; +} +function enrichSkill(skill, attachedAgentCount, usedByAgents = []) { + const source = deriveSkillSourceInfo(skill); + return { + ...skill, + attachedAgentCount, + usedByAgents, + ...source + }; +} +function toCompanySkillListItem(skill, attachedAgentCount) { + const source = deriveSkillSourceInfo(skill); + return { + id: skill.id, + companyId: skill.companyId, + key: skill.key, + slug: skill.slug, + name: skill.name, + description: skill.description, + sourceType: skill.sourceType, + sourceLocator: skill.sourceLocator, + sourceRef: skill.sourceRef, + trustLevel: skill.trustLevel, + compatibility: skill.compatibility, + fileInventory: skill.fileInventory, + createdAt: skill.createdAt, + updatedAt: skill.updatedAt, + attachedAgentCount, + editable: source.editable, + editableReason: source.editableReason, + sourceLabel: source.sourceLabel, + sourceBadge: source.sourceBadge, + sourcePath: source.sourcePath + }; +} +function companySkillService(db) { + const agents2 = agentService(db); + const projects2 = projectService(db); + const secretsSvc = secretService(db); + async function ensureBundledSkills(companyId) { + for (const skillsRoot of resolveBundledSkillsRoot()) { + const stats = await fs27.stat(skillsRoot).catch(() => null); + if (!stats?.isDirectory()) continue; + const bundledSkills = await readLocalSkillImports(companyId, skillsRoot).then((skills) => skills.map((skill) => ({ + ...skill, + key: deriveCanonicalSkillKey(companyId, { + ...skill, + metadata: { + ...skill.metadata ?? {}, + sourceKind: "taskcore_bundled" + } + }), + metadata: { + ...skill.metadata ?? {}, + sourceKind: "taskcore_bundled" + } + }))).catch(() => []); + if (bundledSkills.length === 0) continue; + return upsertImportedSkills(companyId, bundledSkills); + } + return []; + } + async function pruneMissingLocalPathSkills(companyId) { + const rows = await db.select().from(companySkills).where(eq(companySkills.companyId, companyId)); + const skills = rows.map((row) => toCompanySkill(row)); + const missingIds = new Set(await findMissingLocalSkillIds(skills)); + if (missingIds.size === 0) return; + for (const skill of skills) { + if (!missingIds.has(skill.id)) continue; + await db.delete(companySkills).where(eq(companySkills.id, skill.id)); + await fs27.rm(resolveRuntimeSkillMaterializedPath(companyId, skill), { recursive: true, force: true }); + } + } + async function ensureSkillInventoryCurrent(companyId) { + const existingRefresh = skillInventoryRefreshPromises.get(companyId); + if (existingRefresh) { + await existingRefresh; + return; + } + const refreshPromise = (async () => { + await ensureBundledSkills(companyId); + await pruneMissingLocalPathSkills(companyId); + })(); + skillInventoryRefreshPromises.set(companyId, refreshPromise); + try { + await refreshPromise; + } finally { + if (skillInventoryRefreshPromises.get(companyId) === refreshPromise) { + skillInventoryRefreshPromises.delete(companyId); + } + } + } + async function list2(companyId) { + const rows = await listFull(companyId); + const agentRows = await agents2.list(companyId); + return rows.map((skill) => { + const attachedAgentCount = agentRows.filter((agent) => { + const desiredSkills = resolveDesiredSkillKeys(rows, agent.adapterConfig); + return desiredSkills.includes(skill.key); + }).length; + return toCompanySkillListItem(skill, attachedAgentCount); + }); + } + async function listFull(companyId) { + await ensureSkillInventoryCurrent(companyId); + const rows = await db.select().from(companySkills).where(eq(companySkills.companyId, companyId)).orderBy(asc(companySkills.name), asc(companySkills.key)); + return rows.map((row) => toCompanySkill(row)); + } + async function getById(id) { + const row = await db.select().from(companySkills).where(eq(companySkills.id, id)).then((rows) => rows[0] ?? null); + return row ? toCompanySkill(row) : null; + } + async function getByKey(companyId, key) { + const row = await db.select().from(companySkills).where(and(eq(companySkills.companyId, companyId), eq(companySkills.key, key))).then((rows) => rows[0] ?? null); + return row ? toCompanySkill(row) : null; + } + async function usage(companyId, key) { + const skills = await listFull(companyId); + const agentRows = await agents2.list(companyId); + const desiredAgents = agentRows.filter((agent) => { + const desiredSkills = resolveDesiredSkillKeys(skills, agent.adapterConfig); + return desiredSkills.includes(key); + }); + return Promise.all( + desiredAgents.map(async (agent) => { + const adapter = findActiveServerAdapter(agent.adapterType); + let actualState = null; + if (!adapter?.listSkills) { + actualState = "unsupported"; + } else { + try { + const { config: runtimeConfig } = await secretsSvc.resolveAdapterConfigForRuntime( + agent.companyId, + agent.adapterConfig + ); + const runtimeSkillEntries = await listRuntimeSkillEntries(agent.companyId); + const snapshot = await adapter.listSkills({ + agentId: agent.id, + companyId: agent.companyId, + adapterType: agent.adapterType, + config: { + ...runtimeConfig, + taskcoreRuntimeSkills: runtimeSkillEntries + } + }); + actualState = snapshot.entries.find((entry) => entry.key === key)?.state ?? (snapshot.supported ? "missing" : "unsupported"); + } catch { + actualState = "unknown"; + } + } + return { + id: agent.id, + name: agent.name, + urlKey: agent.urlKey, + adapterType: agent.adapterType, + desired: true, + actualState + }; + }) + ); + } + async function detail(companyId, id) { + await ensureSkillInventoryCurrent(companyId); + const skill = await getById(id); + if (!skill || skill.companyId !== companyId) return null; + const usedByAgents = await usage(companyId, skill.key); + return enrichSkill(skill, usedByAgents.length, usedByAgents); + } + async function updateStatus(companyId, skillId) { + await ensureSkillInventoryCurrent(companyId); + const skill = await getById(skillId); + if (!skill || skill.companyId !== companyId) return null; + if (skill.sourceType !== "github" && skill.sourceType !== "skills_sh") { + return { + supported: false, + reason: "Only GitHub-managed skills support update checks.", + trackingRef: null, + currentRef: skill.sourceRef ?? null, + latestRef: null, + hasUpdate: false + }; + } + const metadata = getSkillMeta(skill); + const owner = asString13(metadata.owner); + const repo = asString13(metadata.repo); + const trackingRef = asString13(metadata.trackingRef) ?? asString13(metadata.ref); + if (!owner || !repo || !trackingRef) { + return { + supported: false, + reason: "This GitHub skill does not have enough metadata to track updates.", + trackingRef: trackingRef ?? null, + currentRef: skill.sourceRef ?? null, + latestRef: null, + hasUpdate: false + }; + } + const hostname3 = asString13(metadata.hostname) || "github.com"; + const apiBase = gitHubApiBase(hostname3); + const latestRef = await resolveGitHubCommitSha(owner, repo, trackingRef, apiBase); + return { + supported: true, + reason: null, + trackingRef, + currentRef: skill.sourceRef ?? null, + latestRef, + hasUpdate: latestRef !== (skill.sourceRef ?? null) + }; + } + async function readFile5(companyId, skillId, relativePath) { + await ensureSkillInventoryCurrent(companyId); + const skill = await getById(skillId); + if (!skill || skill.companyId !== companyId) return null; + const normalizedPath = normalizePortablePath(relativePath || "SKILL.md"); + const fileEntry = skill.fileInventory.find((entry) => entry.path === normalizedPath); + if (!fileEntry) { + throw notFound("Skill file not found"); + } + const source = deriveSkillSourceInfo(skill); + let content = ""; + if (skill.sourceType === "local_path" || skill.sourceType === "catalog") { + const absolutePath = resolveLocalSkillFilePath(skill, normalizedPath); + if (absolutePath) { + content = await fs27.readFile(absolutePath, "utf8"); + } else if (normalizedPath === "SKILL.md") { + content = skill.markdown; + } else { + throw notFound("Skill file not found"); + } + } else if (skill.sourceType === "github" || skill.sourceType === "skills_sh") { + const metadata = getSkillMeta(skill); + const owner = asString13(metadata.owner); + const repo = asString13(metadata.repo); + const hostname3 = asString13(metadata.hostname) || "github.com"; + const ref = skill.sourceRef ?? asString13(metadata.ref) ?? "main"; + const repoSkillDir = normalizeGitHubSkillDirectory(asString13(metadata.repoSkillDir), skill.slug); + if (!owner || !repo) { + throw unprocessable("Skill source metadata is incomplete."); + } + const repoPath = normalizePortablePath(path34.posix.join(repoSkillDir, normalizedPath)); + content = await fetchText(resolveRawGitHubUrl(hostname3, owner, repo, ref, repoPath)); + } else if (skill.sourceType === "url") { + if (normalizedPath !== "SKILL.md") { + throw notFound("This skill source only exposes SKILL.md"); + } + content = skill.markdown; + } else { + throw unprocessable("Unsupported skill source."); + } + return { + skillId: skill.id, + path: normalizedPath, + kind: fileEntry.kind, + content, + language: inferLanguageFromPath(normalizedPath), + markdown: isMarkdownPath(normalizedPath), + editable: source.editable + }; + } + async function createLocalSkill(companyId, input) { + const slug = normalizeSkillSlug2(input.slug ?? input.name) ?? "skill"; + const managedRoot = resolveManagedSkillsRoot(companyId); + const skillDir = path34.resolve(managedRoot, slug); + const skillFilePath = path34.resolve(skillDir, "SKILL.md"); + await fs27.mkdir(skillDir, { recursive: true }); + const markdown = input.markdown?.trim().length ? input.markdown : [ + "---", + `name: ${input.name}`, + ...input.description?.trim() ? [`description: ${input.description.trim()}`] : [], + "---", + "", + `# ${input.name}`, + "", + input.description?.trim() ? input.description.trim() : "Describe what this skill does.", + "" + ].join("\n"); + await fs27.writeFile(skillFilePath, markdown, "utf8"); + const parsed = parseFrontmatterMarkdown(markdown); + const imported = await upsertImportedSkills(companyId, [{ + key: `company/${companyId}/${slug}`, + slug, + name: asString13(parsed.frontmatter.name) ?? input.name, + description: asString13(parsed.frontmatter.description) ?? input.description?.trim() ?? null, + markdown, + sourceType: "local_path", + sourceLocator: skillDir, + sourceRef: null, + trustLevel: "markdown_only", + compatibility: "compatible", + fileInventory: [{ path: "SKILL.md", kind: "skill" }], + metadata: { sourceKind: "managed_local" } + }]); + return imported[0]; + } + async function updateFile(companyId, skillId, relativePath, content) { + await ensureSkillInventoryCurrent(companyId); + const skill = await getById(skillId); + if (!skill || skill.companyId !== companyId) throw notFound("Skill not found"); + const source = deriveSkillSourceInfo(skill); + if (!source.editable || skill.sourceType !== "local_path") { + throw unprocessable(source.editableReason ?? "This skill cannot be edited."); + } + const normalizedPath = normalizePortablePath(relativePath); + const absolutePath = resolveLocalSkillFilePath(skill, normalizedPath); + if (!absolutePath) throw notFound("Skill file not found"); + await fs27.mkdir(path34.dirname(absolutePath), { recursive: true }); + await fs27.writeFile(absolutePath, content, "utf8"); + if (normalizedPath === "SKILL.md") { + const parsed = parseFrontmatterMarkdown(content); + await db.update(companySkills).set({ + name: asString13(parsed.frontmatter.name) ?? skill.name, + description: asString13(parsed.frontmatter.description) ?? skill.description, + markdown: content, + updatedAt: /* @__PURE__ */ new Date() + }).where(eq(companySkills.id, skill.id)); + } else { + await db.update(companySkills).set({ updatedAt: /* @__PURE__ */ new Date() }).where(eq(companySkills.id, skill.id)); + } + const detail2 = await readFile5(companyId, skillId, normalizedPath); + if (!detail2) throw notFound("Skill file not found"); + return detail2; + } + async function installUpdate(companyId, skillId) { + await ensureSkillInventoryCurrent(companyId); + const skill = await getById(skillId); + if (!skill || skill.companyId !== companyId) return null; + const status = await updateStatus(companyId, skillId); + if (!status?.supported) { + throw unprocessable(status?.reason ?? "This skill does not support updates."); + } + if (!skill.sourceLocator) { + throw unprocessable("Skill source locator is missing."); + } + const result = await readUrlSkillImports(companyId, skill.sourceLocator, skill.slug); + const matching = result.skills.find((entry) => entry.key === skill.key) ?? result.skills[0] ?? null; + if (!matching) { + throw unprocessable(`Skill ${skill.key} could not be re-imported from its source.`); + } + const imported = await upsertImportedSkills(companyId, [matching]); + return imported[0] ?? null; + } + async function scanProjectWorkspaces(companyId, input = {}) { + await ensureSkillInventoryCurrent(companyId); + const projectRows = input.projectIds?.length ? await projects2.listByIds(companyId, input.projectIds) : await projects2.list(companyId); + const workspaceFilter = new Set(input.workspaceIds ?? []); + const skipped = []; + const conflicts = []; + const warnings = []; + const imported = []; + const updated = []; + const availableSkills = await listFull(companyId); + const acceptedSkills = [...availableSkills]; + const acceptedByKey = new Map(acceptedSkills.map((skill) => [skill.key, skill])); + const scanTargets = []; + const scannedProjectIds = /* @__PURE__ */ new Set(); + let discovered = 0; + const trackWarning = (message2) => { + warnings.push(message2); + return message2; + }; + const upsertAcceptedSkill = (skill) => { + const nextIndex = acceptedSkills.findIndex((entry) => entry.id === skill.id || entry.key === skill.key); + if (nextIndex >= 0) acceptedSkills[nextIndex] = skill; + else acceptedSkills.push(skill); + acceptedByKey.set(skill.key, skill); + }; + for (const project of projectRows) { + for (const workspace of project.workspaces) { + if (workspaceFilter.size > 0 && !workspaceFilter.has(workspace.id)) continue; + const workspaceCwd = asString13(workspace.cwd); + if (!workspaceCwd) { + skipped.push({ + projectId: project.id, + projectName: project.name, + workspaceId: workspace.id, + workspaceName: workspace.name, + path: null, + reason: trackWarning(`Skipped ${project.name} / ${workspace.name}: no local workspace path is configured.`) + }); + continue; + } + const workspaceStat = await statPath(workspaceCwd); + if (!workspaceStat?.isDirectory()) { + skipped.push({ + projectId: project.id, + projectName: project.name, + workspaceId: workspace.id, + workspaceName: workspace.name, + path: workspaceCwd, + reason: trackWarning(`Skipped ${project.name} / ${workspace.name}: local workspace path is not available at ${workspaceCwd}.`) + }); + continue; + } + scanTargets.push({ + projectId: project.id, + projectName: project.name, + workspaceId: workspace.id, + workspaceName: workspace.name, + workspaceCwd + }); + } + } + for (const target of scanTargets) { + scannedProjectIds.add(target.projectId); + const directories = await discoverProjectWorkspaceSkillDirectories(target); + for (const directory of directories) { + discovered += 1; + let nextSkill; + try { + nextSkill = await readLocalSkillImportFromDirectory(companyId, directory.skillDir, { + inventoryMode: directory.inventoryMode, + metadata: { + sourceKind: "project_scan", + projectId: target.projectId, + projectName: target.projectName, + workspaceId: target.workspaceId, + workspaceName: target.workspaceName, + workspaceCwd: target.workspaceCwd + } + }); + } catch (error50) { + const message2 = error50 instanceof Error ? error50.message : String(error50); + skipped.push({ + projectId: target.projectId, + projectName: target.projectName, + workspaceId: target.workspaceId, + workspaceName: target.workspaceName, + path: directory.skillDir, + reason: trackWarning(`Skipped ${directory.skillDir}: ${message2}`) + }); + continue; + } + const normalizedSourceDir = normalizeSourceLocatorDirectory(nextSkill.sourceLocator); + const existingByKey = acceptedByKey.get(nextSkill.key) ?? null; + if (existingByKey) { + const existingSourceDir = normalizeSkillDirectory(existingByKey); + if (existingByKey.sourceType !== "local_path" || !existingSourceDir || !normalizedSourceDir || existingSourceDir !== normalizedSourceDir) { + conflicts.push({ + slug: nextSkill.slug, + key: nextSkill.key, + projectId: target.projectId, + projectName: target.projectName, + workspaceId: target.workspaceId, + workspaceName: target.workspaceName, + path: directory.skillDir, + existingSkillId: existingByKey.id, + existingSkillKey: existingByKey.key, + existingSourceLocator: existingByKey.sourceLocator, + reason: `Skill key ${nextSkill.key} already points at ${existingByKey.sourceLocator ?? "another source"}.` + }); + continue; + } + const persisted2 = (await upsertImportedSkills(companyId, [nextSkill]))[0]; + if (!persisted2) continue; + updated.push(persisted2); + upsertAcceptedSkill(persisted2); + continue; + } + const slugConflict = acceptedSkills.find((skill) => { + if (skill.slug !== nextSkill.slug) return false; + return normalizeSkillDirectory(skill) !== normalizedSourceDir; + }); + if (slugConflict) { + conflicts.push({ + slug: nextSkill.slug, + key: nextSkill.key, + projectId: target.projectId, + projectName: target.projectName, + workspaceId: target.workspaceId, + workspaceName: target.workspaceName, + path: directory.skillDir, + existingSkillId: slugConflict.id, + existingSkillKey: slugConflict.key, + existingSourceLocator: slugConflict.sourceLocator, + reason: `Slug ${nextSkill.slug} is already in use by ${slugConflict.sourceLocator ?? slugConflict.key}.` + }); + continue; + } + const persisted = (await upsertImportedSkills(companyId, [nextSkill]))[0]; + if (!persisted) continue; + imported.push(persisted); + upsertAcceptedSkill(persisted); + } + } + return { + scannedProjects: scannedProjectIds.size, + scannedWorkspaces: scanTargets.length, + discovered, + imported, + updated, + skipped, + conflicts, + warnings + }; + } + async function materializeCatalogSkillFiles(companyId, skill, normalizedFiles) { + const packageDir = skill.packageDir ? normalizePortablePath(skill.packageDir) : null; + if (!packageDir) return null; + const catalogRoot = path34.resolve(resolveManagedSkillsRoot(companyId), "__catalog__"); + const skillDir = path34.resolve(catalogRoot, buildSkillRuntimeName(skill.key, skill.slug)); + await fs27.rm(skillDir, { recursive: true, force: true }); + await fs27.mkdir(skillDir, { recursive: true }); + for (const entry of skill.fileInventory) { + const sourcePath = entry.path === "SKILL.md" ? `${packageDir}/SKILL.md` : `${packageDir}/${entry.path}`; + const content = normalizedFiles[sourcePath]; + if (typeof content !== "string") continue; + const targetPath = path34.resolve(skillDir, entry.path); + await fs27.mkdir(path34.dirname(targetPath), { recursive: true }); + await fs27.writeFile(targetPath, content, "utf8"); + } + return skillDir; + } + async function materializeRuntimeSkillFiles(companyId, skill) { + const runtimeRoot = path34.resolve(resolveManagedSkillsRoot(companyId), "__runtime__"); + const skillDir = path34.resolve(runtimeRoot, buildSkillRuntimeName(skill.key, skill.slug)); + await fs27.rm(skillDir, { recursive: true, force: true }); + await fs27.mkdir(skillDir, { recursive: true }); + for (const entry of skill.fileInventory) { + const detail2 = await readFile5(companyId, skill.id, entry.path).catch(() => null); + if (!detail2) continue; + const targetPath = path34.resolve(skillDir, entry.path); + await fs27.mkdir(path34.dirname(targetPath), { recursive: true }); + await fs27.writeFile(targetPath, detail2.content, "utf8"); + } + return skillDir; + } + function resolveRuntimeSkillMaterializedPath(companyId, skill) { + const runtimeRoot = path34.resolve(resolveManagedSkillsRoot(companyId), "__runtime__"); + return path34.resolve(runtimeRoot, buildSkillRuntimeName(skill.key, skill.slug)); + } + async function listRuntimeSkillEntries(companyId, options = {}) { + const skills = await listFull(companyId); + const out = []; + for (const skill of skills) { + const sourceKind = asString13(getSkillMeta(skill).sourceKind); + let source = normalizeSkillDirectory(skill); + if (!source) { + source = options.materializeMissing === false ? resolveRuntimeSkillMaterializedPath(companyId, skill) : await materializeRuntimeSkillFiles(companyId, skill).catch(() => null); + } + if (!source) continue; + const required2 = sourceKind === "taskcore_bundled"; + out.push({ + key: skill.key, + runtimeName: buildSkillRuntimeName(skill.key, skill.slug), + source, + required: required2, + requiredReason: required2 ? "Bundled Taskcore skills are always available for local adapters." : null + }); + } + out.sort((left, right) => left.key.localeCompare(right.key)); + return out; + } + async function importPackageFiles(companyId, files, options) { + await ensureSkillInventoryCurrent(companyId); + const normalizedFiles = normalizePackageFileMap(files); + const importedSkills = readInlineSkillImports(companyId, normalizedFiles); + if (importedSkills.length === 0) return []; + for (const skill of importedSkills) { + if (skill.sourceType !== "catalog") continue; + const materializedDir = await materializeCatalogSkillFiles(companyId, skill, normalizedFiles); + if (materializedDir) { + skill.sourceLocator = materializedDir; + } + } + const conflictStrategy = options?.onConflict ?? "replace"; + const existingSkills = await listFull(companyId); + const existingByKey = new Map(existingSkills.map((skill) => [skill.key, skill])); + const existingBySlug = new Map( + existingSkills.map((skill) => [normalizeSkillSlug2(skill.slug) ?? skill.slug, skill]) + ); + const usedSlugs = new Set(existingBySlug.keys()); + const usedKeys = new Set(existingByKey.keys()); + const toPersist = []; + const prepared = []; + const out = []; + for (const importedSkill of importedSkills) { + const originalKey = importedSkill.key; + const originalSlug = importedSkill.slug; + const normalizedSlug = normalizeSkillSlug2(importedSkill.slug) ?? importedSkill.slug; + const existingByIncomingKey = existingByKey.get(importedSkill.key) ?? null; + const existingByIncomingSlug = existingBySlug.get(normalizedSlug) ?? null; + const conflict2 = existingByIncomingKey ?? existingByIncomingSlug; + if (!conflict2 || conflictStrategy === "replace") { + toPersist.push(importedSkill); + prepared.push({ + skill: importedSkill, + originalKey, + originalSlug, + existingBefore: existingByIncomingKey, + actionHint: existingByIncomingKey ? "updated" : "created", + reason: existingByIncomingKey ? "Existing skill key matched; replace strategy." : null + }); + usedSlugs.add(normalizedSlug); + usedKeys.add(importedSkill.key); + continue; + } + if (conflictStrategy === "skip") { + out.push({ + skill: conflict2, + action: "skipped", + originalKey, + originalSlug, + requestedRefs: Array.from(/* @__PURE__ */ new Set([originalKey, originalSlug])), + reason: "Existing skill matched; skip strategy." + }); + continue; + } + const renamedSlug = uniqueSkillSlug(normalizedSlug || "skill", usedSlugs); + const renamedKey = uniqueImportedSkillKey(companyId, renamedSlug, usedKeys); + const renamedSkill = { + ...importedSkill, + slug: renamedSlug, + key: renamedKey, + metadata: { + ...importedSkill.metadata ?? {}, + skillKey: renamedKey, + importedFromSkillKey: originalKey, + importedFromSkillSlug: originalSlug + } + }; + toPersist.push(renamedSkill); + prepared.push({ + skill: renamedSkill, + originalKey, + originalSlug, + existingBefore: null, + actionHint: "created", + reason: `Existing skill matched; renamed to ${renamedSlug}.` + }); + usedSlugs.add(renamedSlug); + usedKeys.add(renamedKey); + } + if (toPersist.length === 0) return out; + const persisted = await upsertImportedSkills(companyId, toPersist); + for (let index2 = 0; index2 < prepared.length; index2 += 1) { + const persistedSkill = persisted[index2]; + const preparedSkill = prepared[index2]; + if (!persistedSkill || !preparedSkill) continue; + out.push({ + skill: persistedSkill, + action: preparedSkill.actionHint, + originalKey: preparedSkill.originalKey, + originalSlug: preparedSkill.originalSlug, + requestedRefs: Array.from(/* @__PURE__ */ new Set([preparedSkill.originalKey, preparedSkill.originalSlug])), + reason: preparedSkill.reason + }); + } + return out; + } + async function upsertImportedSkills(companyId, imported) { + const out = []; + for (const skill of imported) { + const existing = await getByKey(companyId, skill.key); + const existingMeta = existing ? getSkillMeta(existing) : {}; + const incomingMeta = skill.metadata && isPlainRecord3(skill.metadata) ? skill.metadata : {}; + const incomingOwner = asString13(incomingMeta.owner); + const incomingRepo = asString13(incomingMeta.repo); + const incomingKind = asString13(incomingMeta.sourceKind); + if (existing && existingMeta.sourceKind === "taskcore_bundled" && incomingKind === "github" && incomingOwner === "taskcore" && incomingRepo === "taskcore") { + out.push(existing); + continue; + } + const metadata = { + ...skill.metadata ?? {}, + skillKey: skill.key + }; + const values2 = { + companyId, + key: skill.key, + slug: skill.slug, + name: skill.name, + description: skill.description, + markdown: skill.markdown, + sourceType: skill.sourceType, + sourceLocator: skill.sourceLocator, + sourceRef: skill.sourceRef, + trustLevel: skill.trustLevel, + compatibility: skill.compatibility, + fileInventory: serializeFileInventory(skill.fileInventory), + metadata, + updatedAt: /* @__PURE__ */ new Date() + }; + const row = existing ? await db.update(companySkills).set(values2).where(eq(companySkills.id, existing.id)).returning().then((rows) => rows[0] ?? null) : await db.insert(companySkills).values(values2).returning().then((rows) => rows[0] ?? null); + if (!row) throw notFound("Failed to persist company skill"); + out.push(toCompanySkill(row)); + } + return out; + } + async function importFromSource(companyId, source) { + await ensureSkillInventoryCurrent(companyId); + const parsed = parseSkillImportSourceInput(source); + const local = !/^https?:\/\//i.test(parsed.resolvedSource); + const { skills, warnings } = local ? { + skills: (await readLocalSkillImports(companyId, parsed.resolvedSource)).filter((skill) => !parsed.requestedSkillSlug || skill.slug === parsed.requestedSkillSlug), + warnings: parsed.warnings + } : await readUrlSkillImports(companyId, parsed.resolvedSource, parsed.requestedSkillSlug).then((result) => ({ + skills: result.skills, + warnings: [...parsed.warnings, ...result.warnings] + })); + const filteredSkills = parsed.requestedSkillSlug ? skills.filter((skill) => skill.slug === parsed.requestedSkillSlug) : skills; + if (filteredSkills.length === 0) { + throw unprocessable( + parsed.requestedSkillSlug ? `Skill ${parsed.requestedSkillSlug} was not found in the provided source.` : "No skills were found in the provided source." + ); + } + if (parsed.originalSkillsShUrl) { + for (const skill of filteredSkills) { + skill.sourceType = "skills_sh"; + skill.sourceLocator = parsed.originalSkillsShUrl; + if (skill.metadata) { + skill.metadata.sourceKind = "skills_sh"; + } + skill.key = deriveCanonicalSkillKey(companyId, skill); + } + } + const imported = await upsertImportedSkills(companyId, filteredSkills); + return { imported, warnings }; + } + async function deleteSkill(companyId, skillId) { + const row = await db.select().from(companySkills).where(and(eq(companySkills.id, skillId), eq(companySkills.companyId, companyId))).then((rows) => rows[0] ?? null); + if (!row) return null; + const skill = toCompanySkill(row); + const usedByAgents = await usage(companyId, skill.key); + if (usedByAgents.length > 0) { + const agentNames = usedByAgents.map((agent) => agent.name).sort((left, right) => left.localeCompare(right)); + throw unprocessable( + `Cannot delete skill "${skill.name}" while it is still used by ${agentNames.join(", ")}. Detach it from those agents first.`, + { + skillId: skill.id, + skillKey: skill.key, + usedByAgents: usedByAgents.map((agent) => ({ + id: agent.id, + name: agent.name, + urlKey: agent.urlKey, + adapterType: agent.adapterType + })) + } + ); + } + await db.delete(companySkills).where(eq(companySkills.id, skillId)); + await fs27.rm(resolveRuntimeSkillMaterializedPath(companyId, skill), { recursive: true, force: true }); + return skill; + } + return { + list: list2, + listFull, + getById, + getByKey, + resolveRequestedSkillKeys: async (companyId, requestedReferences) => { + const skills = await listFull(companyId); + return resolveRequestedSkillKeysOrThrow(skills, requestedReferences); + }, + detail, + updateStatus, + readFile: readFile5, + updateFile, + createLocalSkill, + deleteSkill, + importFromSource, + scanProjectWorkspaces, + importPackageFiles, + installUpdate, + listRuntimeSkillEntries + }; +} + +// server/src/services/assets.ts +init_drizzle_orm(); +init_src2(); +function assetService(db) { + return { + create: (companyId, data2) => db.insert(assets).values({ ...data2, companyId }).returning().then((rows) => rows[0]), + getById: (id) => db.select().from(assets).where(eq(assets.id, id)).then((rows) => rows[0] ?? null) + }; +} + +// server/src/services/documents.ts +init_drizzle_orm(); +init_src2(); +function normalizeDocumentKey(key) { + const normalized = key.trim().toLowerCase(); + const parsed = issueDocumentKeySchema.safeParse(normalized); + if (!parsed.success) { + throw unprocessable("Invalid document key", parsed.error.issues); + } + return parsed.data; +} +function isUniqueViolation(error50) { + return !!error50 && typeof error50 === "object" && "code" in error50 && error50.code === "23505"; +} +function extractLegacyPlanBody(description) { + if (!description) return null; + const match = /\s*([\s\S]*?)\s*<\/plan>/i.exec(description); + if (!match) return null; + const body = match[1]?.trim(); + return body ? body : null; +} +function mapIssueDocumentRow(row, includeBody) { + return { + id: row.id, + companyId: row.companyId, + issueId: row.issueId, + key: row.key, + title: row.title, + format: row.format, + ...includeBody ? { body: row.latestBody } : {}, + latestRevisionId: row.latestRevisionId ?? null, + latestRevisionNumber: row.latestRevisionNumber, + createdByAgentId: row.createdByAgentId, + createdByUserId: row.createdByUserId, + updatedByAgentId: row.updatedByAgentId, + updatedByUserId: row.updatedByUserId, + createdAt: row.createdAt, + updatedAt: row.updatedAt + }; +} +var issueDocumentSelect = { + id: documents.id, + companyId: documents.companyId, + issueId: issueDocuments.issueId, + key: issueDocuments.key, + title: documents.title, + format: documents.format, + latestBody: documents.latestBody, + latestRevisionId: documents.latestRevisionId, + latestRevisionNumber: documents.latestRevisionNumber, + createdByAgentId: documents.createdByAgentId, + createdByUserId: documents.createdByUserId, + updatedByAgentId: documents.updatedByAgentId, + updatedByUserId: documents.updatedByUserId, + createdAt: documents.createdAt, + updatedAt: documents.updatedAt +}; +function documentService(db) { + return { + getIssueDocumentPayload: async (issue2) => { + const [planDocument, documentSummaries] = await Promise.all([ + db.select(issueDocumentSelect).from(issueDocuments).innerJoin(documents, eq(issueDocuments.documentId, documents.id)).where(and(eq(issueDocuments.issueId, issue2.id), eq(issueDocuments.key, "plan"))).then((rows) => rows[0] ?? null), + db.select(issueDocumentSelect).from(issueDocuments).innerJoin(documents, eq(issueDocuments.documentId, documents.id)).where(eq(issueDocuments.issueId, issue2.id)).orderBy(asc(issueDocuments.key), desc(documents.updatedAt)) + ]); + const legacyPlanBody = planDocument ? null : extractLegacyPlanBody(issue2.description); + return { + planDocument: planDocument ? mapIssueDocumentRow(planDocument, true) : null, + documentSummaries: documentSummaries.map((row) => mapIssueDocumentRow(row, false)), + legacyPlanDocument: legacyPlanBody ? { + key: "plan", + body: legacyPlanBody, + source: "issue_description" + } : null + }; + }, + listIssueDocuments: async (issueId) => { + const rows = await db.select(issueDocumentSelect).from(issueDocuments).innerJoin(documents, eq(issueDocuments.documentId, documents.id)).where(eq(issueDocuments.issueId, issueId)).orderBy(asc(issueDocuments.key), desc(documents.updatedAt)); + return rows.map((row) => mapIssueDocumentRow(row, true)); + }, + getIssueDocumentByKey: async (issueId, rawKey) => { + const key = normalizeDocumentKey(rawKey); + const row = await db.select(issueDocumentSelect).from(issueDocuments).innerJoin(documents, eq(issueDocuments.documentId, documents.id)).where(and(eq(issueDocuments.issueId, issueId), eq(issueDocuments.key, key))).then((rows) => rows[0] ?? null); + return row ? mapIssueDocumentRow(row, true) : null; + }, + listIssueDocumentRevisions: async (issueId, rawKey) => { + const key = normalizeDocumentKey(rawKey); + return db.select({ + id: documentRevisions.id, + companyId: documentRevisions.companyId, + documentId: documentRevisions.documentId, + issueId: issueDocuments.issueId, + key: issueDocuments.key, + revisionNumber: documentRevisions.revisionNumber, + title: documentRevisions.title, + format: documentRevisions.format, + body: documentRevisions.body, + changeSummary: documentRevisions.changeSummary, + createdByAgentId: documentRevisions.createdByAgentId, + createdByUserId: documentRevisions.createdByUserId, + createdAt: documentRevisions.createdAt + }).from(issueDocuments).innerJoin(documents, eq(issueDocuments.documentId, documents.id)).innerJoin(documentRevisions, eq(documentRevisions.documentId, documents.id)).where(and(eq(issueDocuments.issueId, issueId), eq(issueDocuments.key, key))).orderBy(desc(documentRevisions.revisionNumber)); + }, + upsertIssueDocument: async (input) => { + const key = normalizeDocumentKey(input.key); + const issue2 = await db.select({ id: issues.id, companyId: issues.companyId }).from(issues).where(eq(issues.id, input.issueId)).then((rows) => rows[0] ?? null); + if (!issue2) throw notFound("Issue not found"); + try { + return await db.transaction(async (tx) => { + const now2 = /* @__PURE__ */ new Date(); + const existing = await tx.select({ + id: documents.id, + companyId: documents.companyId, + issueId: issueDocuments.issueId, + key: issueDocuments.key, + title: documents.title, + format: documents.format, + latestBody: documents.latestBody, + latestRevisionId: documents.latestRevisionId, + latestRevisionNumber: documents.latestRevisionNumber, + createdByAgentId: documents.createdByAgentId, + createdByUserId: documents.createdByUserId, + updatedByAgentId: documents.updatedByAgentId, + updatedByUserId: documents.updatedByUserId, + createdAt: documents.createdAt, + updatedAt: documents.updatedAt + }).from(issueDocuments).innerJoin(documents, eq(issueDocuments.documentId, documents.id)).where(and(eq(issueDocuments.issueId, issue2.id), eq(issueDocuments.key, key))).then((rows) => rows[0] ?? null); + if (existing) { + if (!input.baseRevisionId) { + throw conflict("Document update requires baseRevisionId", { + currentRevisionId: existing.latestRevisionId + }); + } + if (input.baseRevisionId !== existing.latestRevisionId) { + throw conflict("Document was updated by someone else", { + currentRevisionId: existing.latestRevisionId + }); + } + const nextRevisionNumber = existing.latestRevisionNumber + 1; + const [revision2] = await tx.insert(documentRevisions).values({ + companyId: issue2.companyId, + documentId: existing.id, + revisionNumber: nextRevisionNumber, + title: input.title ?? null, + format: input.format, + body: input.body, + changeSummary: input.changeSummary ?? null, + createdByAgentId: input.createdByAgentId ?? null, + createdByUserId: input.createdByUserId ?? null, + createdByRunId: input.createdByRunId ?? null, + createdAt: now2 + }).returning(); + await tx.update(documents).set({ + title: input.title ?? null, + format: input.format, + latestBody: input.body, + latestRevisionId: revision2.id, + latestRevisionNumber: nextRevisionNumber, + updatedByAgentId: input.createdByAgentId ?? null, + updatedByUserId: input.createdByUserId ?? null, + updatedAt: now2 + }).where(eq(documents.id, existing.id)); + await tx.update(issueDocuments).set({ updatedAt: now2 }).where(eq(issueDocuments.documentId, existing.id)); + return { + created: false, + document: { + ...existing, + title: input.title ?? null, + format: input.format, + body: input.body, + latestRevisionId: revision2.id, + latestRevisionNumber: nextRevisionNumber, + updatedByAgentId: input.createdByAgentId ?? null, + updatedByUserId: input.createdByUserId ?? null, + updatedAt: now2 + } + }; + } + if (input.baseRevisionId) { + throw conflict("Document does not exist yet", { key }); + } + const [document2] = await tx.insert(documents).values({ + companyId: issue2.companyId, + title: input.title ?? null, + format: input.format, + latestBody: input.body, + latestRevisionId: null, + latestRevisionNumber: 1, + createdByAgentId: input.createdByAgentId ?? null, + createdByUserId: input.createdByUserId ?? null, + updatedByAgentId: input.createdByAgentId ?? null, + updatedByUserId: input.createdByUserId ?? null, + createdAt: now2, + updatedAt: now2 + }).returning(); + const [revision] = await tx.insert(documentRevisions).values({ + companyId: issue2.companyId, + documentId: document2.id, + revisionNumber: 1, + title: input.title ?? null, + format: input.format, + body: input.body, + changeSummary: input.changeSummary ?? null, + createdByAgentId: input.createdByAgentId ?? null, + createdByUserId: input.createdByUserId ?? null, + createdByRunId: input.createdByRunId ?? null, + createdAt: now2 + }).returning(); + await tx.update(documents).set({ latestRevisionId: revision.id }).where(eq(documents.id, document2.id)); + await tx.insert(issueDocuments).values({ + companyId: issue2.companyId, + issueId: issue2.id, + documentId: document2.id, + key, + createdAt: now2, + updatedAt: now2 + }); + return { + created: true, + document: { + id: document2.id, + companyId: issue2.companyId, + issueId: issue2.id, + key, + title: document2.title, + format: document2.format, + body: document2.latestBody, + latestRevisionId: revision.id, + latestRevisionNumber: 1, + createdByAgentId: document2.createdByAgentId, + createdByUserId: document2.createdByUserId, + updatedByAgentId: document2.updatedByAgentId, + updatedByUserId: document2.updatedByUserId, + createdAt: document2.createdAt, + updatedAt: document2.updatedAt + } + }; + }); + } catch (error50) { + if (isUniqueViolation(error50)) { + throw conflict("Document key already exists on this issue", { key }); + } + throw error50; + } + }, + restoreIssueDocumentRevision: async (input) => { + const key = normalizeDocumentKey(input.key); + return db.transaction(async (tx) => { + const existing = await tx.select(issueDocumentSelect).from(issueDocuments).innerJoin(documents, eq(issueDocuments.documentId, documents.id)).where(and(eq(issueDocuments.issueId, input.issueId), eq(issueDocuments.key, key))).then((rows) => rows[0] ?? null); + if (!existing) throw notFound("Document not found"); + const revision = await tx.select({ + id: documentRevisions.id, + companyId: documentRevisions.companyId, + documentId: documentRevisions.documentId, + revisionNumber: documentRevisions.revisionNumber, + title: documentRevisions.title, + format: documentRevisions.format, + body: documentRevisions.body + }).from(documentRevisions).where(and(eq(documentRevisions.id, input.revisionId), eq(documentRevisions.documentId, existing.id))).then((rows) => rows[0] ?? null); + if (!revision) throw notFound("Document revision not found"); + if (existing.latestRevisionId === revision.id) { + throw conflict("Selected revision is already the latest revision", { + currentRevisionId: existing.latestRevisionId + }); + } + const now2 = /* @__PURE__ */ new Date(); + const nextRevisionNumber = existing.latestRevisionNumber + 1; + const [restoredRevision] = await tx.insert(documentRevisions).values({ + companyId: existing.companyId, + documentId: existing.id, + revisionNumber: nextRevisionNumber, + title: revision.title ?? null, + format: revision.format, + body: revision.body, + changeSummary: `Restored from revision ${revision.revisionNumber}`, + createdByAgentId: input.createdByAgentId ?? null, + createdByUserId: input.createdByUserId ?? null, + createdAt: now2 + }).returning(); + await tx.update(documents).set({ + title: revision.title ?? null, + format: revision.format, + latestBody: revision.body, + latestRevisionId: restoredRevision.id, + latestRevisionNumber: nextRevisionNumber, + updatedByAgentId: input.createdByAgentId ?? null, + updatedByUserId: input.createdByUserId ?? null, + updatedAt: now2 + }).where(eq(documents.id, existing.id)); + await tx.update(issueDocuments).set({ updatedAt: now2 }).where(eq(issueDocuments.documentId, existing.id)); + return { + restoredFromRevisionId: revision.id, + restoredFromRevisionNumber: revision.revisionNumber, + document: { + ...existing, + title: revision.title ?? null, + format: revision.format, + body: revision.body, + latestRevisionId: restoredRevision.id, + latestRevisionNumber: nextRevisionNumber, + updatedByAgentId: input.createdByAgentId ?? null, + updatedByUserId: input.createdByUserId ?? null, + updatedAt: now2 + } + }; + }); + }, + deleteIssueDocument: async (issueId, rawKey) => { + const key = normalizeDocumentKey(rawKey); + return db.transaction(async (tx) => { + const existing = await tx.select(issueDocumentSelect).from(issueDocuments).innerJoin(documents, eq(issueDocuments.documentId, documents.id)).where(and(eq(issueDocuments.issueId, issueId), eq(issueDocuments.key, key))).then((rows) => rows[0] ?? null); + if (!existing) return null; + await tx.delete(issueDocuments).where(eq(issueDocuments.documentId, existing.id)); + await tx.delete(documents).where(eq(documents.id, existing.id)); + return { + ...existing, + body: existing.latestBody, + latestRevisionId: existing.latestRevisionId ?? null + }; + }); + } + }; +} + +// server/src/services/issues.ts +init_drizzle_orm(); +init_src2(); + +// server/src/services/issue-goal-fallback.ts +function resolveIssueGoalId(input) { + if (input.goalId) return input.goalId; + if (input.projectId) return input.projectGoalId ?? null; + return input.defaultGoalId ?? null; +} +function resolveNextIssueGoalId(input) { + const projectId = input.projectId !== void 0 ? input.projectId : input.currentProjectId; + const projectGoalId = input.projectGoalId !== void 0 ? input.projectGoalId : projectId ? input.currentProjectGoalId : null; + const resolveFallbackGoalId = (targetProjectId, targetProjectGoalId) => { + if (targetProjectId) return targetProjectGoalId ?? null; + return input.defaultGoalId ?? null; + }; + if (input.goalId !== void 0) { + return input.goalId ?? resolveFallbackGoalId(projectId, projectGoalId); + } + const currentFallbackGoalId = resolveFallbackGoalId( + input.currentProjectId, + input.currentProjectGoalId + ); + const nextFallbackGoalId = resolveFallbackGoalId(projectId, projectGoalId); + if (!input.currentGoalId) { + return nextFallbackGoalId; + } + if (input.currentGoalId === currentFallbackGoalId) { + return nextFallbackGoalId; + } + return input.currentGoalId; +} + +// server/src/services/goals.ts +init_drizzle_orm(); +init_src2(); +async function getDefaultCompanyGoal(db, companyId) { + const activeRootGoal = await db.select().from(goals).where( + and( + eq(goals.companyId, companyId), + eq(goals.level, "company"), + eq(goals.status, "active"), + isNull(goals.parentId) + ) + ).orderBy(asc(goals.createdAt)).then((rows) => rows[0] ?? null); + if (activeRootGoal) return activeRootGoal; + const anyRootGoal = await db.select().from(goals).where( + and( + eq(goals.companyId, companyId), + eq(goals.level, "company"), + isNull(goals.parentId) + ) + ).orderBy(asc(goals.createdAt)).then((rows) => rows[0] ?? null); + if (anyRootGoal) return anyRootGoal; + return db.select().from(goals).where(and(eq(goals.companyId, companyId), eq(goals.level, "company"))).orderBy(asc(goals.createdAt)).then((rows) => rows[0] ?? null); +} +function goalService(db) { + return { + list: (companyId) => db.select().from(goals).where(eq(goals.companyId, companyId)), + getById: (id) => db.select().from(goals).where(eq(goals.id, id)).then((rows) => rows[0] ?? null), + getDefaultCompanyGoal: (companyId) => getDefaultCompanyGoal(db, companyId), + create: (companyId, data2) => db.insert(goals).values({ ...data2, companyId }).returning().then((rows) => rows[0]), + update: (id, data2) => db.update(goals).set({ ...data2, updatedAt: /* @__PURE__ */ new Date() }).where(eq(goals.id, id)).returning().then((rows) => rows[0] ?? null), + remove: (id) => db.delete(goals).where(eq(goals.id, id)).returning().then((rows) => rows[0] ?? null) + }; +} + +// server/src/services/issues.ts +var ALL_ISSUE_STATUSES = ["backlog", "todo", "in_progress", "in_review", "blocked", "done", "cancelled"]; +var MAX_ISSUE_COMMENT_PAGE_LIMIT = 500; +function assertTransition(from, to) { + if (from === to) return; + if (!ALL_ISSUE_STATUSES.includes(to)) { + throw conflict(`Unknown issue status: ${to}`); + } +} +function applyStatusSideEffects(status, patch) { + if (!status) return patch; + if (status === "in_progress" && !patch.startedAt) { + patch.startedAt = /* @__PURE__ */ new Date(); + } + if (status === "done") { + patch.completedAt = /* @__PURE__ */ new Date(); + } + if (status === "cancelled") { + patch.cancelledAt = /* @__PURE__ */ new Date(); + } + return patch; +} +function sameRunLock(checkoutRunId, actorRunId) { + if (actorRunId) return checkoutRunId === actorRunId; + return checkoutRunId == null; +} +var TERMINAL_HEARTBEAT_RUN_STATUSES = /* @__PURE__ */ new Set(["succeeded", "failed", "cancelled", "timed_out"]); +function escapeLikePattern(value) { + return value.replace(/[\\%_]/g, "\\$&"); +} +async function getProjectDefaultGoalId(db, companyId, projectId) { + if (!projectId) return null; + const row = await db.select({ goalId: projects.goalId }).from(projects).where(and(eq(projects.id, projectId), eq(projects.companyId, companyId))).then((rows) => rows[0] ?? null); + return row?.goalId ?? null; +} +async function getWorkspaceInheritanceIssue(db, companyId, issueId) { + const issue2 = await db.select({ + id: issues.id, + projectId: issues.projectId, + projectWorkspaceId: issues.projectWorkspaceId, + executionWorkspaceId: issues.executionWorkspaceId, + executionWorkspaceSettings: issues.executionWorkspaceSettings + }).from(issues).where(and(eq(issues.id, issueId), eq(issues.companyId, companyId))).then((rows) => rows[0] ?? null); + if (!issue2) { + throw notFound("Workspace inheritance issue not found"); + } + return issue2; +} +function touchedByUserCondition(companyId, userId) { + return sql` + ( + ${issues.createdByUserId} = ${userId} + OR ${issues.assigneeUserId} = ${userId} + OR EXISTS ( + SELECT 1 + FROM ${issueReadStates} + WHERE ${issueReadStates.issueId} = ${issues.id} + AND ${issueReadStates.companyId} = ${companyId} + AND ${issueReadStates.userId} = ${userId} + ) + OR EXISTS ( + SELECT 1 + FROM ${issueComments} + WHERE ${issueComments.issueId} = ${issues.id} + AND ${issueComments.companyId} = ${companyId} + AND ${issueComments.authorUserId} = ${userId} + ) + ) + `; +} +function participatedByAgentCondition(companyId, agentId) { + return sql` + ( + ${issues.createdByAgentId} = ${agentId} + OR ${issues.assigneeAgentId} = ${agentId} + OR EXISTS ( + SELECT 1 + FROM ${issueComments} + WHERE ${issueComments.issueId} = ${issues.id} + AND ${issueComments.companyId} = ${companyId} + AND ${issueComments.authorAgentId} = ${agentId} + ) + OR EXISTS ( + SELECT 1 + FROM ${activityLog} + WHERE ${activityLog.companyId} = ${companyId} + AND ${activityLog.entityType} = 'issue' + AND ${activityLog.entityId} = ${issues.id}::text + AND ${activityLog.agentId} = ${agentId} + ) + ) + `; +} +function myLastCommentAtExpr(companyId, userId) { + return sql` + ( + SELECT MAX(${issueComments.createdAt}) + FROM ${issueComments} + WHERE ${issueComments.issueId} = ${issues.id} + AND ${issueComments.companyId} = ${companyId} + AND ${issueComments.authorUserId} = ${userId} + ) + `; +} +function myLastReadAtExpr(companyId, userId) { + return sql` + ( + SELECT MAX(${issueReadStates.lastReadAt}) + FROM ${issueReadStates} + WHERE ${issueReadStates.issueId} = ${issues.id} + AND ${issueReadStates.companyId} = ${companyId} + AND ${issueReadStates.userId} = ${userId} + ) + `; +} +function myLastTouchAtExpr(companyId, userId) { + const myLastCommentAt = myLastCommentAtExpr(companyId, userId); + const myLastReadAt = myLastReadAtExpr(companyId, userId); + return sql` + GREATEST( + COALESCE(${myLastCommentAt}, to_timestamp(0)), + COALESCE(${myLastReadAt}, to_timestamp(0)), + COALESCE(CASE WHEN ${issues.createdByUserId} = ${userId} THEN ${issues.createdAt} ELSE NULL END, to_timestamp(0)), + COALESCE(CASE WHEN ${issues.assigneeUserId} = ${userId} THEN ${issues.updatedAt} ELSE NULL END, to_timestamp(0)) + ) + `; +} +function lastExternalCommentAtExpr(companyId, userId) { + return sql` + ( + SELECT MAX(${issueComments.createdAt}) + FROM ${issueComments} + WHERE ${issueComments.issueId} = ${issues.id} + AND ${issueComments.companyId} = ${companyId} + AND ( + ${issueComments.authorUserId} IS NULL + OR ${issueComments.authorUserId} <> ${userId} + ) + ) + `; +} +function issueLastActivityAtExpr(companyId, userId) { + const lastExternalCommentAt = lastExternalCommentAtExpr(companyId, userId); + const myLastTouchAt = myLastTouchAtExpr(companyId, userId); + return sql` + GREATEST( + COALESCE(${lastExternalCommentAt}, to_timestamp(0)), + CASE + WHEN ${issues.updatedAt} > COALESCE(${myLastTouchAt}, to_timestamp(0)) + THEN ${issues.updatedAt} + ELSE to_timestamp(0) + END + ) + `; +} +var ISSUE_LOCAL_INBOX_ACTIVITY_ACTIONS = [ + "issue.read_marked", + "issue.read_unmarked", + "issue.inbox_archived", + "issue.inbox_unarchived" +]; +function issueLatestCommentAtExpr(companyId) { + return sql` + ( + SELECT MAX(${issueComments.createdAt}) + FROM ${issueComments} + WHERE ${issueComments.issueId} = ${issues.id} + AND ${issueComments.companyId} = ${companyId} + ) + `; +} +function issueLatestLogAtExpr(companyId) { + return sql` + ( + SELECT MAX(${activityLog.createdAt}) + FROM ${activityLog} + WHERE ${activityLog.companyId} = ${companyId} + AND ${activityLog.entityType} = 'issue' + AND ${activityLog.entityId} = ${issues.id}::text + AND ${activityLog.action} NOT IN (${sql.join( + ISSUE_LOCAL_INBOX_ACTIVITY_ACTIONS.map((action) => sql`${action}`), + sql`, ` + )}) + ) + `; +} +function issueCanonicalLastActivityAtExpr(companyId) { + const latestCommentAt = issueLatestCommentAtExpr(companyId); + const latestLogAt = issueLatestLogAtExpr(companyId); + return sql` + GREATEST( + ${issues.updatedAt}, + COALESCE(${latestCommentAt}, to_timestamp(0)), + COALESCE(${latestLogAt}, to_timestamp(0)) + ) + `; +} +function unreadForUserCondition(companyId, userId) { + const touchedCondition = touchedByUserCondition(companyId, userId); + const myLastTouchAt = myLastTouchAtExpr(companyId, userId); + return sql` + ( + ${touchedCondition} + AND EXISTS ( + SELECT 1 + FROM ${issueComments} + WHERE ${issueComments.issueId} = ${issues.id} + AND ${issueComments.companyId} = ${companyId} + AND ( + ${issueComments.authorUserId} IS NULL + OR ${issueComments.authorUserId} <> ${userId} + ) + AND ${issueComments.createdAt} > ${myLastTouchAt} + ) + ) + `; +} +function inboxVisibleForUserCondition(companyId, userId) { + const issueLastActivityAt = issueLastActivityAtExpr(companyId, userId); + return sql` + NOT EXISTS ( + SELECT 1 + FROM ${issueInboxArchives} + WHERE ${issueInboxArchives.issueId} = ${issues.id} + AND ${issueInboxArchives.companyId} = ${companyId} + AND ${issueInboxArchives.userId} = ${userId} + AND ${issueInboxArchives.archivedAt} >= ${issueLastActivityAt} + ) + `; +} +var WELL_KNOWN_NAMED_HTML_ENTITIES = { + amp: "&", + apos: "'", + copy: "\xA9", + gt: ">", + lt: "<", + nbsp: "\xA0", + quot: '"', + ensp: "\u2002", + emsp: "\u2003", + thinsp: "\u2009" +}; +function decodeNumericHtmlEntity(digits, radix) { + const n5 = Number.parseInt(digits, radix); + if (Number.isNaN(n5) || n5 < 0 || n5 > 1114111) return null; + try { + return String.fromCodePoint(n5); + } catch { + return null; + } +} +function normalizeAgentMentionToken(raw) { + let s5 = raw.replace(/&#x([0-9a-fA-F]+);/gi, (full, hex4) => decodeNumericHtmlEntity(hex4, 16) ?? full); + s5 = s5.replace(/&#([0-9]+);/g, (full, dec) => decodeNumericHtmlEntity(dec, 10) ?? full); + s5 = s5.replace(/&([a-z][a-z0-9]*);/gi, (full, name) => { + const decoded = WELL_KNOWN_NAMED_HTML_ENTITIES[name.toLowerCase()]; + return decoded !== void 0 ? decoded : full; + }); + return s5.trim(); +} +function deriveIssueUserContext(issue2, userId, stats) { + const normalizeDate = (value) => { + if (!value) return null; + if (value instanceof Date) return Number.isNaN(value.getTime()) ? null : value; + const parsed = new Date(value); + return Number.isNaN(parsed.getTime()) ? null : parsed; + }; + const myLastCommentAt = normalizeDate(stats?.myLastCommentAt); + const myLastReadAt = normalizeDate(stats?.myLastReadAt); + const createdTouchAt = issue2.createdByUserId === userId ? normalizeDate(issue2.createdAt) : null; + const assignedTouchAt = issue2.assigneeUserId === userId ? normalizeDate(issue2.updatedAt) : null; + const myLastTouchAt = [myLastCommentAt, myLastReadAt, createdTouchAt, assignedTouchAt].filter((value) => value instanceof Date).sort((a5, b6) => b6.getTime() - a5.getTime())[0] ?? null; + const lastExternalCommentAt = normalizeDate(stats?.lastExternalCommentAt); + const isUnreadForMe = Boolean( + myLastTouchAt && lastExternalCommentAt && lastExternalCommentAt.getTime() > myLastTouchAt.getTime() + ); + return { + myLastTouchAt, + lastExternalCommentAt, + isUnreadForMe + }; +} +function latestIssueActivityAt(...values2) { + const normalized = values2.map((value) => { + if (!value) return null; + if (value instanceof Date) return Number.isNaN(value.getTime()) ? null : value; + const parsed = new Date(value); + return Number.isNaN(parsed.getTime()) ? null : parsed; + }).filter((value) => value instanceof Date).sort((a5, b6) => b6.getTime() - a5.getTime()); + return normalized[0] ?? null; +} +async function labelMapForIssues(dbOrTx, issueIds) { + const map4 = /* @__PURE__ */ new Map(); + if (issueIds.length === 0) return map4; + const rows = await dbOrTx.select({ + issueId: issueLabels.issueId, + label: labels + }).from(issueLabels).innerJoin(labels, eq(issueLabels.labelId, labels.id)).where(inArray(issueLabels.issueId, issueIds)).orderBy(asc(labels.name), asc(labels.id)); + for (const row of rows) { + const existing = map4.get(row.issueId); + if (existing) existing.push(row.label); + else map4.set(row.issueId, [row.label]); + } + return map4; +} +async function withIssueLabels(dbOrTx, rows) { + if (rows.length === 0) return []; + const labelsByIssueId = await labelMapForIssues(dbOrTx, rows.map((row) => row.id)); + return rows.map((row) => { + const issueLabels2 = labelsByIssueId.get(row.id) ?? []; + return { + ...row, + labels: issueLabels2, + labelIds: issueLabels2.map((label) => label.id) + }; + }); +} +var ACTIVE_RUN_STATUSES = ["queued", "running"]; +async function activeRunMapForIssues(dbOrTx, issueRows) { + const map4 = /* @__PURE__ */ new Map(); + const runIds = issueRows.map((row) => row.executionRunId).filter((id) => id != null); + if (runIds.length === 0) return map4; + const rows = await dbOrTx.select({ + id: heartbeatRuns.id, + status: heartbeatRuns.status, + agentId: heartbeatRuns.agentId, + invocationSource: heartbeatRuns.invocationSource, + triggerDetail: heartbeatRuns.triggerDetail, + startedAt: heartbeatRuns.startedAt, + finishedAt: heartbeatRuns.finishedAt, + createdAt: heartbeatRuns.createdAt + }).from(heartbeatRuns).where( + and( + inArray(heartbeatRuns.id, runIds), + inArray(heartbeatRuns.status, ACTIVE_RUN_STATUSES) + ) + ); + for (const row of rows) { + map4.set(row.id, row); + } + return map4; +} +function withActiveRuns(issueRows, runMap) { + return issueRows.map((row) => ({ + ...row, + activeRun: row.executionRunId ? runMap.get(row.executionRunId) ?? null : null + })); +} +function issueService(db) { + const instanceSettings2 = instanceSettingsService(db); + async function getIssueByUuid(id) { + const row = await db.select().from(issues).where(eq(issues.id, id)).then((rows) => rows[0] ?? null); + if (!row) return null; + const [enriched] = await withIssueLabels(db, [row]); + return enriched; + } + async function getIssueByIdentifier(identifier) { + const row = await db.select().from(issues).where(eq(issues.identifier, identifier.toUpperCase())).then((rows) => rows[0] ?? null); + if (!row) return null; + const [enriched] = await withIssueLabels(db, [row]); + return enriched; + } + function redactIssueComment(comment, censorUsernameInLogs) { + return { + ...comment, + body: redactCurrentUserText(comment.body, { enabled: censorUsernameInLogs }) + }; + } + async function assertAssignableAgent(companyId, agentId) { + const assignee = await db.select({ + id: agents.id, + companyId: agents.companyId, + status: agents.status + }).from(agents).where(eq(agents.id, agentId)).then((rows) => rows[0] ?? null); + if (!assignee) throw notFound("Assignee agent not found"); + if (assignee.companyId !== companyId) { + throw unprocessable("Assignee must belong to same company"); + } + if (assignee.status === "pending_approval") { + throw conflict("Cannot assign work to pending approval agents"); + } + if (assignee.status === "terminated") { + throw conflict("Cannot assign work to terminated agents"); + } + } + async function assertAssignableUser(companyId, userId) { + const membership = await db.select({ id: companyMemberships.id }).from(companyMemberships).where( + and( + eq(companyMemberships.companyId, companyId), + eq(companyMemberships.principalType, "user"), + eq(companyMemberships.principalId, userId), + eq(companyMemberships.status, "active") + ) + ).then((rows) => rows[0] ?? null); + if (!membership) { + throw notFound("Assignee user not found"); + } + } + async function assertValidProjectWorkspace(companyId, projectId, projectWorkspaceId, dbOrTx = db) { + const workspace = await dbOrTx.select({ + id: projectWorkspaces.id, + companyId: projectWorkspaces.companyId, + projectId: projectWorkspaces.projectId + }).from(projectWorkspaces).where(eq(projectWorkspaces.id, projectWorkspaceId)).then((rows) => rows[0] ?? null); + if (!workspace) throw notFound("Project workspace not found"); + if (workspace.companyId !== companyId) throw unprocessable("Project workspace must belong to same company"); + if (projectId && workspace.projectId !== projectId) { + throw unprocessable("Project workspace must belong to the selected project"); + } + } + async function assertValidExecutionWorkspace(companyId, projectId, executionWorkspaceId, dbOrTx = db) { + const workspace = await dbOrTx.select({ + id: executionWorkspaces.id, + companyId: executionWorkspaces.companyId, + projectId: executionWorkspaces.projectId + }).from(executionWorkspaces).where(eq(executionWorkspaces.id, executionWorkspaceId)).then((rows) => rows[0] ?? null); + if (!workspace) throw notFound("Execution workspace not found"); + if (workspace.companyId !== companyId) throw unprocessable("Execution workspace must belong to same company"); + if (projectId && workspace.projectId !== projectId) { + throw unprocessable("Execution workspace must belong to the selected project"); + } + } + async function assertValidLabelIds(companyId, labelIds, dbOrTx = db) { + if (labelIds.length === 0) return; + const existing = await dbOrTx.select({ id: labels.id }).from(labels).where(and(eq(labels.companyId, companyId), inArray(labels.id, labelIds))); + if (existing.length !== new Set(labelIds).size) { + throw unprocessable("One or more labels are invalid for this company"); + } + } + async function syncIssueLabels(issueId, companyId, labelIds, dbOrTx = db) { + const deduped = [...new Set(labelIds)]; + await assertValidLabelIds(companyId, deduped, dbOrTx); + await dbOrTx.delete(issueLabels).where(eq(issueLabels.issueId, issueId)); + if (deduped.length === 0) return; + await dbOrTx.insert(issueLabels).values( + deduped.map((labelId) => ({ + issueId, + labelId, + companyId + })) + ); + } + async function getIssueRelationSummaryMap(companyId, issueIds, dbOrTx = db) { + const uniqueIssueIds = [...new Set(issueIds)]; + const empty = /* @__PURE__ */ new Map(); + for (const issueId of uniqueIssueIds) { + empty.set(issueId, { blockedBy: [], blocks: [] }); + } + if (uniqueIssueIds.length === 0) return empty; + const [blockedByRows, blockingRows] = await Promise.all([ + dbOrTx.select({ + currentIssueId: issueRelations.relatedIssueId, + relatedId: issues.id, + identifier: issues.identifier, + title: issues.title, + status: issues.status, + priority: issues.priority, + assigneeAgentId: issues.assigneeAgentId, + assigneeUserId: issues.assigneeUserId + }).from(issueRelations).innerJoin(issues, eq(issueRelations.issueId, issues.id)).where( + and( + eq(issueRelations.companyId, companyId), + eq(issueRelations.type, "blocks"), + inArray(issueRelations.relatedIssueId, uniqueIssueIds) + ) + ), + dbOrTx.select({ + currentIssueId: issueRelations.issueId, + relatedId: issues.id, + identifier: issues.identifier, + title: issues.title, + status: issues.status, + priority: issues.priority, + assigneeAgentId: issues.assigneeAgentId, + assigneeUserId: issues.assigneeUserId + }).from(issueRelations).innerJoin(issues, eq(issueRelations.relatedIssueId, issues.id)).where( + and( + eq(issueRelations.companyId, companyId), + eq(issueRelations.type, "blocks"), + inArray(issueRelations.issueId, uniqueIssueIds) + ) + ) + ]); + for (const row of blockedByRows) { + empty.get(row.currentIssueId)?.blockedBy.push({ + id: row.relatedId, + identifier: row.identifier, + title: row.title, + status: row.status, + priority: row.priority, + assigneeAgentId: row.assigneeAgentId, + assigneeUserId: row.assigneeUserId + }); + } + for (const row of blockingRows) { + empty.get(row.currentIssueId)?.blocks.push({ + id: row.relatedId, + identifier: row.identifier, + title: row.title, + status: row.status, + priority: row.priority, + assigneeAgentId: row.assigneeAgentId, + assigneeUserId: row.assigneeUserId + }); + } + for (const relations of empty.values()) { + relations.blockedBy.sort((a5, b6) => a5.title.localeCompare(b6.title)); + relations.blocks.sort((a5, b6) => a5.title.localeCompare(b6.title)); + } + return empty; + } + async function assertNoBlockingCycles(companyId, issueId, blockerIssueIds, dbOrTx = db) { + if (blockerIssueIds.length === 0) return; + const rows = await dbOrTx.select({ + blockerIssueId: issueRelations.issueId, + blockedIssueId: issueRelations.relatedIssueId + }).from(issueRelations).where(and(eq(issueRelations.companyId, companyId), eq(issueRelations.type, "blocks"))); + const adjacency = /* @__PURE__ */ new Map(); + for (const row of rows) { + const list2 = adjacency.get(row.blockerIssueId) ?? []; + list2.push(row.blockedIssueId); + adjacency.set(row.blockerIssueId, list2); + } + for (const blockerIssueId of blockerIssueIds) { + const queue = [...adjacency.get(issueId) ?? []]; + const visited = /* @__PURE__ */ new Set([issueId]); + while (queue.length > 0) { + const current = queue.shift(); + if (current === blockerIssueId) { + throw unprocessable("Blocking relations cannot contain cycles"); + } + if (visited.has(current)) continue; + visited.add(current); + queue.push(...adjacency.get(current) ?? []); + } + } + } + async function syncBlockedByIssueIds(issueId, companyId, blockedByIssueIds, actor = {}, dbOrTx = db) { + const deduped = [...new Set(blockedByIssueIds)]; + if (deduped.some((candidate) => candidate === issueId)) { + throw unprocessable("Issue cannot be blocked by itself"); + } + if (deduped.length > 0) { + const lockedIssueIds = [issueId, ...deduped].sort(); + await dbOrTx.execute( + sql`SELECT ${issues.id} FROM ${issues} + WHERE ${and(eq(issues.companyId, companyId), inArray(issues.id, lockedIssueIds))} + ORDER BY ${issues.id} + FOR UPDATE` + ); + const relatedIssues = await dbOrTx.select({ id: issues.id }).from(issues).where(and(eq(issues.companyId, companyId), inArray(issues.id, deduped))); + if (relatedIssues.length !== deduped.length) { + throw unprocessable("Blocked-by issues must belong to the same company"); + } + await assertNoBlockingCycles(companyId, issueId, deduped, dbOrTx); + } + await dbOrTx.delete(issueRelations).where( + and( + eq(issueRelations.companyId, companyId), + eq(issueRelations.relatedIssueId, issueId), + eq(issueRelations.type, "blocks") + ) + ); + if (deduped.length === 0) return; + await dbOrTx.insert(issueRelations).values( + deduped.map((blockerIssueId) => ({ + companyId, + issueId: blockerIssueId, + relatedIssueId: issueId, + type: "blocks", + createdByAgentId: actor.agentId ?? null, + createdByUserId: actor.userId ?? null + })) + ); + } + async function isTerminalOrMissingHeartbeatRun(runId) { + const run = await db.select({ status: heartbeatRuns.status }).from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)).then((rows) => rows[0] ?? null); + if (!run) return true; + return TERMINAL_HEARTBEAT_RUN_STATUSES.has(run.status); + } + async function adoptStaleCheckoutRun(input) { + const stale = await isTerminalOrMissingHeartbeatRun(input.expectedCheckoutRunId); + if (!stale) return null; + const now2 = /* @__PURE__ */ new Date(); + const adopted = await db.update(issues).set({ + checkoutRunId: input.actorRunId, + executionRunId: input.actorRunId, + executionLockedAt: now2, + updatedAt: now2 + }).where( + and( + eq(issues.id, input.issueId), + eq(issues.status, "in_progress"), + eq(issues.assigneeAgentId, input.actorAgentId), + eq(issues.checkoutRunId, input.expectedCheckoutRunId) + ) + ).returning({ + id: issues.id, + status: issues.status, + assigneeAgentId: issues.assigneeAgentId, + checkoutRunId: issues.checkoutRunId, + executionRunId: issues.executionRunId + }).then((rows) => rows[0] ?? null); + return adopted; + } + return { + list: async (companyId, filters) => { + const conditions = [eq(issues.companyId, companyId)]; + const limit = typeof filters?.limit === "number" && Number.isFinite(filters.limit) ? Math.max(1, Math.floor(filters.limit)) : void 0; + const touchedByUserId = filters?.touchedByUserId?.trim() || void 0; + const inboxArchivedByUserId = filters?.inboxArchivedByUserId?.trim() || void 0; + const unreadForUserId = filters?.unreadForUserId?.trim() || void 0; + const contextUserId = unreadForUserId ?? touchedByUserId ?? inboxArchivedByUserId; + const rawSearch = filters?.q?.trim() ?? ""; + const hasSearch = rawSearch.length > 0; + const escapedSearch = hasSearch ? escapeLikePattern(rawSearch) : ""; + const startsWithPattern = `${escapedSearch}%`; + const containsPattern = `%${escapedSearch}%`; + const titleStartsWithMatch = sql`${issues.title} ILIKE ${startsWithPattern} ESCAPE '\\'`; + const titleContainsMatch = sql`${issues.title} ILIKE ${containsPattern} ESCAPE '\\'`; + const identifierStartsWithMatch = sql`${issues.identifier} ILIKE ${startsWithPattern} ESCAPE '\\'`; + const identifierContainsMatch = sql`${issues.identifier} ILIKE ${containsPattern} ESCAPE '\\'`; + const descriptionContainsMatch = sql`${issues.description} ILIKE ${containsPattern} ESCAPE '\\'`; + const commentContainsMatch = sql` + EXISTS ( + SELECT 1 + FROM ${issueComments} + WHERE ${issueComments.issueId} = ${issues.id} + AND ${issueComments.companyId} = ${companyId} + AND ${issueComments.body} ILIKE ${containsPattern} ESCAPE '\\' + ) + `; + if (filters?.status) { + const statuses = filters.status.split(",").map((s5) => s5.trim()); + conditions.push(statuses.length === 1 ? eq(issues.status, statuses[0]) : inArray(issues.status, statuses)); + } + if (filters?.assigneeAgentId) { + conditions.push(eq(issues.assigneeAgentId, filters.assigneeAgentId)); + } + if (filters?.participantAgentId) { + conditions.push(participatedByAgentCondition(companyId, filters.participantAgentId)); + } + if (filters?.assigneeUserId) { + conditions.push(eq(issues.assigneeUserId, filters.assigneeUserId)); + } + if (touchedByUserId) { + conditions.push(touchedByUserCondition(companyId, touchedByUserId)); + } + if (inboxArchivedByUserId) { + conditions.push(inboxVisibleForUserCondition(companyId, inboxArchivedByUserId)); + } + if (unreadForUserId) { + conditions.push(unreadForUserCondition(companyId, unreadForUserId)); + } + if (filters?.projectId) conditions.push(eq(issues.projectId, filters.projectId)); + if (filters?.executionWorkspaceId) { + conditions.push(eq(issues.executionWorkspaceId, filters.executionWorkspaceId)); + } + if (filters?.parentId) conditions.push(eq(issues.parentId, filters.parentId)); + if (filters?.originKind) conditions.push(eq(issues.originKind, filters.originKind)); + if (filters?.originId) conditions.push(eq(issues.originId, filters.originId)); + if (filters?.labelId) { + const labeledIssueIds = await db.select({ issueId: issueLabels.issueId }).from(issueLabels).where(and(eq(issueLabels.companyId, companyId), eq(issueLabels.labelId, filters.labelId))); + if (labeledIssueIds.length === 0) return []; + conditions.push(inArray(issues.id, labeledIssueIds.map((row) => row.issueId))); + } + if (hasSearch) { + conditions.push( + or( + titleContainsMatch, + identifierContainsMatch, + descriptionContainsMatch, + commentContainsMatch + ) + ); + } + if (!filters?.includeRoutineExecutions && !filters?.originKind && !filters?.originId) { + conditions.push(ne(issues.originKind, "routine_execution")); + } + conditions.push(isNull(issues.hiddenAt)); + const priorityOrder = sql`CASE ${issues.priority} WHEN 'critical' THEN 0 WHEN 'high' THEN 1 WHEN 'medium' THEN 2 WHEN 'low' THEN 3 ELSE 4 END`; + const searchOrder = sql` + CASE + WHEN ${titleStartsWithMatch} THEN 0 + WHEN ${titleContainsMatch} THEN 1 + WHEN ${identifierStartsWithMatch} THEN 2 + WHEN ${identifierContainsMatch} THEN 3 + WHEN ${commentContainsMatch} THEN 4 + WHEN ${descriptionContainsMatch} THEN 5 + ELSE 6 + END + `; + const canonicalLastActivityAt = issueCanonicalLastActivityAtExpr(companyId); + const baseQuery = db.select().from(issues).where(and(...conditions)).orderBy( + hasSearch ? asc(searchOrder) : asc(priorityOrder), + asc(priorityOrder), + desc(canonicalLastActivityAt), + desc(issues.updatedAt) + ); + const rows = limit === void 0 ? await baseQuery : await baseQuery.limit(limit); + const withLabels = await withIssueLabels(db, rows); + const runMap = await activeRunMapForIssues(db, withLabels); + const withRuns = withActiveRuns(withLabels, runMap); + if (withRuns.length === 0) { + return withRuns; + } + const issueIds = withRuns.map((row) => row.id); + const [statsRows, readRows, lastActivityRows] = await Promise.all([ + contextUserId ? db.select({ + issueId: issueComments.issueId, + myLastCommentAt: sql` + MAX(CASE WHEN ${issueComments.authorUserId} = ${contextUserId} THEN ${issueComments.createdAt} END) + `, + lastExternalCommentAt: sql` + MAX( + CASE + WHEN ${issueComments.authorUserId} IS NULL OR ${issueComments.authorUserId} <> ${contextUserId} + THEN ${issueComments.createdAt} + END + ) + ` + }).from(issueComments).where( + and( + eq(issueComments.companyId, companyId), + inArray(issueComments.issueId, issueIds) + ) + ).groupBy(issueComments.issueId) : Promise.resolve([]), + contextUserId ? db.select({ + issueId: issueReadStates.issueId, + myLastReadAt: issueReadStates.lastReadAt + }).from(issueReadStates).where( + and( + eq(issueReadStates.companyId, companyId), + eq(issueReadStates.userId, contextUserId), + inArray(issueReadStates.issueId, issueIds) + ) + ) : Promise.resolve([]), + Promise.all([ + db.select({ + issueId: issueComments.issueId, + latestCommentAt: sql`MAX(${issueComments.createdAt})` + }).from(issueComments).where( + and( + eq(issueComments.companyId, companyId), + inArray(issueComments.issueId, issueIds) + ) + ).groupBy(issueComments.issueId), + db.select({ + issueId: activityLog.entityId, + latestLogAt: sql`MAX(${activityLog.createdAt})` + }).from(activityLog).where( + and( + eq(activityLog.companyId, companyId), + eq(activityLog.entityType, "issue"), + inArray(activityLog.entityId, issueIds), + sql`${activityLog.action} NOT IN (${sql.join( + ISSUE_LOCAL_INBOX_ACTIVITY_ACTIONS.map((action) => sql`${action}`), + sql`, ` + )})` + ) + ).groupBy(activityLog.entityId) + ]).then(([commentRows, logRows]) => { + const byIssueId = /* @__PURE__ */ new Map(); + for (const row of commentRows) { + byIssueId.set(row.issueId, { + issueId: row.issueId, + latestCommentAt: row.latestCommentAt, + latestLogAt: null + }); + } + for (const row of logRows) { + const existing = byIssueId.get(row.issueId); + if (existing) existing.latestLogAt = row.latestLogAt; + else { + byIssueId.set(row.issueId, { + issueId: row.issueId, + latestCommentAt: null, + latestLogAt: row.latestLogAt + }); + } + } + return [...byIssueId.values()]; + }) + ]); + const statsByIssueId = new Map(statsRows.map((row) => [row.issueId, row])); + const lastActivityByIssueId = new Map(lastActivityRows.map((row) => [row.issueId, row])); + if (!contextUserId) { + return withRuns.map((row) => { + const activity = lastActivityByIssueId.get(row.id); + const lastActivityAt = latestIssueActivityAt( + row.updatedAt, + activity?.latestCommentAt ?? null, + activity?.latestLogAt ?? null + ) ?? row.updatedAt; + return { + ...row, + lastActivityAt + }; + }); + } + const readByIssueId = new Map(readRows.map((row) => [row.issueId, row.myLastReadAt])); + return withRuns.map((row) => { + const activity = lastActivityByIssueId.get(row.id); + const lastActivityAt = latestIssueActivityAt( + row.updatedAt, + activity?.latestCommentAt ?? null, + activity?.latestLogAt ?? null + ) ?? row.updatedAt; + return { + ...row, + lastActivityAt, + ...deriveIssueUserContext(row, contextUserId, { + myLastCommentAt: statsByIssueId.get(row.id)?.myLastCommentAt ?? null, + myLastReadAt: readByIssueId.get(row.id) ?? null, + lastExternalCommentAt: statsByIssueId.get(row.id)?.lastExternalCommentAt ?? null + }) + }; + }); + }, + countUnreadTouchedByUser: async (companyId, userId, status) => { + const conditions = [ + eq(issues.companyId, companyId), + isNull(issues.hiddenAt), + unreadForUserCondition(companyId, userId), + ne(issues.originKind, "routine_execution") + ]; + if (status) { + const statuses = status.split(",").map((s5) => s5.trim()).filter(Boolean); + if (statuses.length === 1) { + conditions.push(eq(issues.status, statuses[0])); + } else if (statuses.length > 1) { + conditions.push(inArray(issues.status, statuses)); + } + } + const [row] = await db.select({ count: sql`count(*)` }).from(issues).where(and(...conditions)); + return Number(row?.count ?? 0); + }, + markRead: async (companyId, issueId, userId, readAt = /* @__PURE__ */ new Date()) => { + const now2 = /* @__PURE__ */ new Date(); + const [row] = await db.insert(issueReadStates).values({ + companyId, + issueId, + userId, + lastReadAt: readAt, + updatedAt: now2 + }).onConflictDoUpdate({ + target: [issueReadStates.companyId, issueReadStates.issueId, issueReadStates.userId], + set: { + lastReadAt: readAt, + updatedAt: now2 + } + }).returning(); + return row; + }, + markUnread: async (companyId, issueId, userId) => { + const deleted = await db.delete(issueReadStates).where( + and( + eq(issueReadStates.companyId, companyId), + eq(issueReadStates.issueId, issueId), + eq(issueReadStates.userId, userId) + ) + ).returning(); + return deleted.length > 0; + }, + archiveInbox: async (companyId, issueId, userId, archivedAt = /* @__PURE__ */ new Date()) => { + const now2 = /* @__PURE__ */ new Date(); + const [row] = await db.insert(issueInboxArchives).values({ + companyId, + issueId, + userId, + archivedAt, + updatedAt: now2 + }).onConflictDoUpdate({ + target: [issueInboxArchives.companyId, issueInboxArchives.issueId, issueInboxArchives.userId], + set: { + archivedAt, + updatedAt: now2 + } + }).returning(); + return row; + }, + unarchiveInbox: async (companyId, issueId, userId) => { + const [row] = await db.delete(issueInboxArchives).where( + and( + eq(issueInboxArchives.companyId, companyId), + eq(issueInboxArchives.issueId, issueId), + eq(issueInboxArchives.userId, userId) + ) + ).returning(); + return row ?? null; + }, + getById: async (raw) => { + const id = raw.trim(); + if (/^[A-Z]+-\d+$/i.test(id)) { + return getIssueByIdentifier(id); + } + if (!isUuidLike(id)) { + return null; + } + return getIssueByUuid(id); + }, + getByIdentifier: async (identifier) => { + return getIssueByIdentifier(identifier); + }, + getRelationSummaries: async (issueId) => { + const issue2 = await db.select({ id: issues.id, companyId: issues.companyId }).from(issues).where(eq(issues.id, issueId)).then((rows) => rows[0] ?? null); + if (!issue2) throw notFound("Issue not found"); + const relations = await getIssueRelationSummaryMap(issue2.companyId, [issueId], db); + return relations.get(issueId) ?? { blockedBy: [], blocks: [] }; + }, + listWakeableBlockedDependents: async (blockerIssueId) => { + const blockerIssue = await db.select({ id: issues.id, companyId: issues.companyId }).from(issues).where(eq(issues.id, blockerIssueId)).then((rows) => rows[0] ?? null); + if (!blockerIssue) return []; + const candidates = await db.select({ + id: issues.id, + assigneeAgentId: issues.assigneeAgentId, + status: issues.status + }).from(issueRelations).innerJoin(issues, eq(issueRelations.relatedIssueId, issues.id)).where( + and( + eq(issueRelations.companyId, blockerIssue.companyId), + eq(issueRelations.type, "blocks"), + eq(issueRelations.issueId, blockerIssueId) + ) + ); + if (candidates.length === 0) return []; + const candidateIds = candidates.map((candidate) => candidate.id); + const blockerRows = await db.select({ + issueId: issueRelations.relatedIssueId, + blockerIssueId: issueRelations.issueId, + blockerStatus: issues.status + }).from(issueRelations).innerJoin(issues, eq(issueRelations.issueId, issues.id)).where( + and( + eq(issueRelations.companyId, blockerIssue.companyId), + eq(issueRelations.type, "blocks"), + inArray(issueRelations.relatedIssueId, candidateIds) + ) + ); + const blockersByIssueId = /* @__PURE__ */ new Map(); + for (const row of blockerRows) { + const list2 = blockersByIssueId.get(row.issueId) ?? []; + list2.push({ blockerIssueId: row.blockerIssueId, blockerStatus: row.blockerStatus }); + blockersByIssueId.set(row.issueId, list2); + } + return candidates.filter((candidate) => candidate.assigneeAgentId && !["backlog", "done", "cancelled"].includes(candidate.status)).map((candidate) => { + const blockers = blockersByIssueId.get(candidate.id) ?? []; + return { + ...candidate, + blockerIssueIds: blockers.map((blocker) => blocker.blockerIssueId), + allBlockersDone: blockers.length > 0 && blockers.every((blocker) => blocker.blockerStatus === "done") + }; + }).filter((candidate) => candidate.allBlockersDone).map((candidate) => ({ + id: candidate.id, + assigneeAgentId: candidate.assigneeAgentId, + blockerIssueIds: candidate.blockerIssueIds + })); + }, + getWakeableParentAfterChildCompletion: async (parentIssueId) => { + const parent = await db.select({ + id: issues.id, + assigneeAgentId: issues.assigneeAgentId, + status: issues.status, + companyId: issues.companyId + }).from(issues).where(eq(issues.id, parentIssueId)).then((rows) => rows[0] ?? null); + if (!parent || !parent.assigneeAgentId || ["backlog", "done", "cancelled"].includes(parent.status)) { + return null; + } + const children = await db.select({ id: issues.id, status: issues.status }).from(issues).where(and(eq(issues.companyId, parent.companyId), eq(issues.parentId, parentIssueId))); + if (children.length === 0) return null; + if (!children.every((child) => child.status === "done" || child.status === "cancelled")) { + return null; + } + return { + id: parent.id, + assigneeAgentId: parent.assigneeAgentId, + childIssueIds: children.map((child) => child.id) + }; + }, + create: async (companyId, data2) => { + const { + labelIds: inputLabelIds, + blockedByIssueIds, + inheritExecutionWorkspaceFromIssueId, + ...issueData + } = data2; + const isolatedWorkspacesEnabled = (await instanceSettings2.getExperimental()).enableIsolatedWorkspaces; + if (!isolatedWorkspacesEnabled) { + delete issueData.executionWorkspaceId; + delete issueData.executionWorkspacePreference; + delete issueData.executionWorkspaceSettings; + } + if (data2.assigneeAgentId && data2.assigneeUserId) { + throw unprocessable("Issue can only have one assignee"); + } + if (data2.assigneeAgentId) { + await assertAssignableAgent(companyId, data2.assigneeAgentId); + } + if (data2.assigneeUserId) { + await assertAssignableUser(companyId, data2.assigneeUserId); + } + if (data2.status === "in_progress" && !data2.assigneeAgentId && !data2.assigneeUserId) { + throw unprocessable("in_progress issues require an assignee"); + } + return db.transaction(async (tx) => { + const defaultCompanyGoal = await getDefaultCompanyGoal(tx, companyId); + const projectGoalId = await getProjectDefaultGoalId(tx, companyId, issueData.projectId); + let projectWorkspaceId = issueData.projectWorkspaceId ?? null; + let executionWorkspaceId = issueData.executionWorkspaceId ?? null; + let executionWorkspacePreference = issueData.executionWorkspacePreference ?? null; + let executionWorkspaceSettings = issueData.executionWorkspaceSettings ?? null; + const workspaceInheritanceIssueId = inheritExecutionWorkspaceFromIssueId ?? issueData.parentId ?? null; + const hasExplicitExecutionWorkspaceOverride = issueData.executionWorkspaceId !== void 0 || issueData.executionWorkspacePreference !== void 0 || issueData.executionWorkspaceSettings !== void 0; + if (workspaceInheritanceIssueId) { + const workspaceSource = await getWorkspaceInheritanceIssue(tx, companyId, workspaceInheritanceIssueId); + if (projectWorkspaceId == null && workspaceSource.projectWorkspaceId) { + projectWorkspaceId = workspaceSource.projectWorkspaceId; + } + if (isolatedWorkspacesEnabled && !hasExplicitExecutionWorkspaceOverride && workspaceSource.executionWorkspaceId) { + const sourceWorkspace = await tx.select({ + id: executionWorkspaces.id, + mode: executionWorkspaces.mode + }).from(executionWorkspaces).where(eq(executionWorkspaces.id, workspaceSource.executionWorkspaceId)).then((rows) => rows[0] ?? null); + if (sourceWorkspace) { + executionWorkspaceId = sourceWorkspace.id; + executionWorkspacePreference = "reuse_existing"; + executionWorkspaceSettings = { + ...workspaceSource.executionWorkspaceSettings ?? {}, + mode: issueExecutionWorkspaceModeForPersistedWorkspace(sourceWorkspace.mode) + }; + } + } + } + if (executionWorkspaceSettings == null && executionWorkspaceId == null && issueData.projectId) { + const project = await tx.select({ executionWorkspacePolicy: projects.executionWorkspacePolicy }).from(projects).where(and(eq(projects.id, issueData.projectId), eq(projects.companyId, companyId))).then((rows) => rows[0] ?? null); + executionWorkspaceSettings = defaultIssueExecutionWorkspaceSettingsForProject( + gateProjectExecutionWorkspacePolicy( + parseProjectExecutionWorkspacePolicy(project?.executionWorkspacePolicy), + isolatedWorkspacesEnabled + ) + ); + } + if (!projectWorkspaceId && issueData.projectId) { + const project = await tx.select({ + executionWorkspacePolicy: projects.executionWorkspacePolicy + }).from(projects).where(and(eq(projects.id, issueData.projectId), eq(projects.companyId, companyId))).then((rows) => rows[0] ?? null); + const projectPolicy = parseProjectExecutionWorkspacePolicy(project?.executionWorkspacePolicy); + projectWorkspaceId = projectPolicy?.defaultProjectWorkspaceId ?? null; + if (!projectWorkspaceId) { + projectWorkspaceId = await tx.select({ id: projectWorkspaces.id }).from(projectWorkspaces).where(and(eq(projectWorkspaces.projectId, issueData.projectId), eq(projectWorkspaces.companyId, companyId))).orderBy(desc(projectWorkspaces.isPrimary), asc(projectWorkspaces.createdAt), asc(projectWorkspaces.id)).then((rows) => rows[0]?.id ?? null); + } + } + if (projectWorkspaceId) { + await assertValidProjectWorkspace(companyId, issueData.projectId, projectWorkspaceId, tx); + } + if (executionWorkspaceId) { + await assertValidExecutionWorkspace(companyId, issueData.projectId, executionWorkspaceId, tx); + } + const [maxRow] = await tx.select({ maxNum: sql`coalesce(max(${issues.issueNumber}), 0)` }).from(issues).where(eq(issues.companyId, companyId)); + const currentMax = maxRow?.maxNum ?? 0; + const [company] = await tx.update(companies).set({ + issueCounter: sql`greatest(${companies.issueCounter}, ${currentMax}) + 1` + }).where(eq(companies.id, companyId)).returning({ issueCounter: companies.issueCounter, issuePrefix: companies.issuePrefix }); + const issueNumber = company.issueCounter; + const identifier = `${company.issuePrefix}-${issueNumber}`; + const values2 = { + ...issueData, + originKind: issueData.originKind ?? "manual", + goalId: resolveIssueGoalId({ + projectId: issueData.projectId, + goalId: issueData.goalId, + projectGoalId, + defaultGoalId: defaultCompanyGoal?.id ?? null + }), + ...projectWorkspaceId ? { projectWorkspaceId } : {}, + ...executionWorkspaceId ? { executionWorkspaceId } : {}, + ...executionWorkspacePreference ? { executionWorkspacePreference } : {}, + ...executionWorkspaceSettings ? { executionWorkspaceSettings } : {}, + companyId, + issueNumber, + identifier + }; + if (values2.status === "in_progress" && !values2.startedAt) { + values2.startedAt = /* @__PURE__ */ new Date(); + } + if (values2.status === "done") { + values2.completedAt = /* @__PURE__ */ new Date(); + } + if (values2.status === "cancelled") { + values2.cancelledAt = /* @__PURE__ */ new Date(); + } + const [issue2] = await tx.insert(issues).values(values2).returning(); + if (inputLabelIds) { + await syncIssueLabels(issue2.id, companyId, inputLabelIds, tx); + } + if (blockedByIssueIds !== void 0) { + await syncBlockedByIssueIds( + issue2.id, + companyId, + blockedByIssueIds, + { + agentId: issueData.createdByAgentId ?? null, + userId: issueData.createdByUserId ?? null + }, + tx + ); + } + const [enriched] = await withIssueLabels(tx, [issue2]); + return enriched; + }); + }, + update: async (id, data2, dbOrTx = db) => { + const existing = await dbOrTx.select().from(issues).where(eq(issues.id, id)).then((rows) => rows[0] ?? null); + if (!existing) return null; + const { + labelIds: nextLabelIds, + blockedByIssueIds, + actorAgentId, + actorUserId, + ...issueData + } = data2; + const isolatedWorkspacesEnabled = (await instanceSettings2.getExperimental()).enableIsolatedWorkspaces; + if (!isolatedWorkspacesEnabled) { + delete issueData.executionWorkspaceId; + delete issueData.executionWorkspacePreference; + delete issueData.executionWorkspaceSettings; + } + if (issueData.status) { + assertTransition(existing.status, issueData.status); + } + const patch = { + ...issueData, + updatedAt: /* @__PURE__ */ new Date() + }; + const nextAssigneeAgentId = issueData.assigneeAgentId !== void 0 ? issueData.assigneeAgentId : existing.assigneeAgentId; + const nextAssigneeUserId = issueData.assigneeUserId !== void 0 ? issueData.assigneeUserId : existing.assigneeUserId; + if (nextAssigneeAgentId && nextAssigneeUserId) { + throw unprocessable("Issue can only have one assignee"); + } + if (patch.status === "in_progress" && !nextAssigneeAgentId && !nextAssigneeUserId) { + throw unprocessable("in_progress issues require an assignee"); + } + if (issueData.assigneeAgentId) { + await assertAssignableAgent(existing.companyId, issueData.assigneeAgentId); + } + if (issueData.assigneeUserId) { + await assertAssignableUser(existing.companyId, issueData.assigneeUserId); + } + const nextProjectId = issueData.projectId !== void 0 ? issueData.projectId : existing.projectId; + const nextProjectWorkspaceId = issueData.projectWorkspaceId !== void 0 ? issueData.projectWorkspaceId : existing.projectWorkspaceId; + const nextExecutionWorkspaceId = issueData.executionWorkspaceId !== void 0 ? issueData.executionWorkspaceId : existing.executionWorkspaceId; + if (nextProjectWorkspaceId) { + await assertValidProjectWorkspace(existing.companyId, nextProjectId, nextProjectWorkspaceId); + } + if (nextExecutionWorkspaceId) { + await assertValidExecutionWorkspace(existing.companyId, nextProjectId, nextExecutionWorkspaceId); + } + applyStatusSideEffects(issueData.status, patch); + if (issueData.status && issueData.status !== "done") { + patch.completedAt = null; + } + if (issueData.status && issueData.status !== "cancelled") { + patch.cancelledAt = null; + } + if (issueData.status && issueData.status !== "in_progress") { + patch.checkoutRunId = null; + patch.executionRunId = null; + patch.executionAgentNameKey = null; + patch.executionLockedAt = null; + } + if (issueData.assigneeAgentId !== void 0 && issueData.assigneeAgentId !== existing.assigneeAgentId || issueData.assigneeUserId !== void 0 && issueData.assigneeUserId !== existing.assigneeUserId) { + patch.checkoutRunId = null; + patch.executionRunId = null; + patch.executionAgentNameKey = null; + patch.executionLockedAt = null; + } + const runUpdate = async (tx) => { + const defaultCompanyGoal = await getDefaultCompanyGoal(tx, existing.companyId); + const [currentProjectGoalId, nextProjectGoalId] = await Promise.all([ + getProjectDefaultGoalId(tx, existing.companyId, existing.projectId), + getProjectDefaultGoalId( + tx, + existing.companyId, + issueData.projectId !== void 0 ? issueData.projectId : existing.projectId + ) + ]); + patch.goalId = resolveNextIssueGoalId({ + currentProjectId: existing.projectId, + currentGoalId: existing.goalId, + currentProjectGoalId, + projectId: issueData.projectId, + goalId: issueData.goalId, + projectGoalId: nextProjectGoalId, + defaultGoalId: defaultCompanyGoal?.id ?? null + }); + const updated = await tx.update(issues).set(patch).where(eq(issues.id, id)).returning().then((rows) => rows[0] ?? null); + if (!updated) return null; + if (nextLabelIds !== void 0) { + await syncIssueLabels(updated.id, existing.companyId, nextLabelIds, tx); + } + if (blockedByIssueIds !== void 0) { + await syncBlockedByIssueIds( + updated.id, + existing.companyId, + blockedByIssueIds, + { + agentId: actorAgentId ?? null, + userId: actorUserId ?? null + }, + tx + ); + } + const [enriched] = await withIssueLabels(tx, [updated]); + return enriched; + }; + return dbOrTx === db ? db.transaction(runUpdate) : runUpdate(dbOrTx); + }, + remove: (id) => db.transaction(async (tx) => { + const attachmentAssetIds = await tx.select({ assetId: issueAttachments.assetId }).from(issueAttachments).where(eq(issueAttachments.issueId, id)); + const issueDocumentIds = await tx.select({ documentId: issueDocuments.documentId }).from(issueDocuments).where(eq(issueDocuments.issueId, id)); + const removedIssue = await tx.delete(issues).where(eq(issues.id, id)).returning().then((rows) => rows[0] ?? null); + if (removedIssue && attachmentAssetIds.length > 0) { + await tx.delete(assets).where(inArray(assets.id, attachmentAssetIds.map((row) => row.assetId))); + } + if (removedIssue && issueDocumentIds.length > 0) { + await tx.delete(documents).where(inArray(documents.id, issueDocumentIds.map((row) => row.documentId))); + } + if (!removedIssue) return null; + const [enriched] = await withIssueLabels(tx, [removedIssue]); + return enriched; + }), + checkout: async (id, agentId, expectedStatuses, checkoutRunId) => { + const issueCompany = await db.select({ companyId: issues.companyId }).from(issues).where(eq(issues.id, id)).then((rows) => rows[0] ?? null); + if (!issueCompany) throw notFound("Issue not found"); + await assertAssignableAgent(issueCompany.companyId, agentId); + const now2 = /* @__PURE__ */ new Date(); + await db.transaction(async (tx) => { + await tx.execute( + sql`select id from issues where id = ${id} for update` + ); + const preCheckRow = await tx.select({ executionRunId: issues.executionRunId }).from(issues).where(eq(issues.id, id)).then((rows) => rows[0] ?? null); + if (!preCheckRow?.executionRunId) return; + const lockRun = await tx.select({ id: heartbeatRuns.id, status: heartbeatRuns.status }).from(heartbeatRuns).where(eq(heartbeatRuns.id, preCheckRow.executionRunId)).then((rows) => rows[0] ?? null); + if (!lockRun || lockRun.status !== "queued" && lockRun.status !== "running") { + await tx.update(issues).set({ executionRunId: null, executionAgentNameKey: null, executionLockedAt: null, updatedAt: now2 }).where( + and( + eq(issues.id, id), + eq(issues.executionRunId, preCheckRow.executionRunId) + ) + ); + } + }); + const sameRunAssigneeCondition = checkoutRunId ? and( + eq(issues.assigneeAgentId, agentId), + or(isNull(issues.checkoutRunId), eq(issues.checkoutRunId, checkoutRunId)) + ) : and(eq(issues.assigneeAgentId, agentId), isNull(issues.checkoutRunId)); + const executionLockCondition = checkoutRunId ? or(isNull(issues.executionRunId), eq(issues.executionRunId, checkoutRunId)) : isNull(issues.executionRunId); + const updated = await db.update(issues).set({ + assigneeAgentId: agentId, + assigneeUserId: null, + checkoutRunId, + executionRunId: checkoutRunId, + status: "in_progress", + startedAt: now2, + updatedAt: now2 + }).where( + and( + eq(issues.id, id), + inArray(issues.status, expectedStatuses), + or(isNull(issues.assigneeAgentId), sameRunAssigneeCondition), + executionLockCondition + ) + ).returning().then((rows) => rows[0] ?? null); + if (updated) { + const [enriched] = await withIssueLabels(db, [updated]); + return enriched; + } + const current = await db.select({ + id: issues.id, + status: issues.status, + assigneeAgentId: issues.assigneeAgentId, + checkoutRunId: issues.checkoutRunId, + executionRunId: issues.executionRunId + }).from(issues).where(eq(issues.id, id)).then((rows) => rows[0] ?? null); + if (!current) throw notFound("Issue not found"); + if (current.assigneeAgentId === agentId && current.status === "in_progress" && current.checkoutRunId == null && (current.executionRunId == null || current.executionRunId === checkoutRunId) && checkoutRunId) { + const adopted = await db.update(issues).set({ + checkoutRunId, + executionRunId: checkoutRunId, + updatedAt: /* @__PURE__ */ new Date() + }).where( + and( + eq(issues.id, id), + eq(issues.status, "in_progress"), + eq(issues.assigneeAgentId, agentId), + isNull(issues.checkoutRunId), + or(isNull(issues.executionRunId), eq(issues.executionRunId, checkoutRunId)) + ) + ).returning().then((rows) => rows[0] ?? null); + if (adopted) return adopted; + } + if (checkoutRunId && current.assigneeAgentId === agentId && current.status === "in_progress" && current.checkoutRunId && current.checkoutRunId !== checkoutRunId) { + const adopted = await adoptStaleCheckoutRun({ + issueId: id, + actorAgentId: agentId, + actorRunId: checkoutRunId, + expectedCheckoutRunId: current.checkoutRunId + }); + if (adopted) { + const row = await db.select().from(issues).where(eq(issues.id, id)).then((rows) => rows[0] ?? null); + if (!row) throw notFound("Issue not found"); + const [enriched] = await withIssueLabels(db, [row]); + return enriched; + } + } + if (current.assigneeAgentId === agentId && current.status === "in_progress" && sameRunLock(current.checkoutRunId, checkoutRunId)) { + const row = await db.select().from(issues).where(eq(issues.id, id)).then((rows) => rows[0] ?? null); + if (!row) throw notFound("Issue not found"); + const [enriched] = await withIssueLabels(db, [row]); + return enriched; + } + throw conflict("Issue checkout conflict", { + issueId: current.id, + status: current.status, + assigneeAgentId: current.assigneeAgentId, + checkoutRunId: current.checkoutRunId, + executionRunId: current.executionRunId + }); + }, + assertCheckoutOwner: async (id, actorAgentId, actorRunId) => { + const current = await db.select({ + id: issues.id, + status: issues.status, + assigneeAgentId: issues.assigneeAgentId, + checkoutRunId: issues.checkoutRunId + }).from(issues).where(eq(issues.id, id)).then((rows) => rows[0] ?? null); + if (!current) throw notFound("Issue not found"); + if (current.status === "in_progress" && current.assigneeAgentId === actorAgentId && sameRunLock(current.checkoutRunId, actorRunId)) { + return { ...current, adoptedFromRunId: null }; + } + if (actorRunId && current.status === "in_progress" && current.assigneeAgentId === actorAgentId && current.checkoutRunId && current.checkoutRunId !== actorRunId) { + const adopted = await adoptStaleCheckoutRun({ + issueId: id, + actorAgentId, + actorRunId, + expectedCheckoutRunId: current.checkoutRunId + }); + if (adopted) { + return { + ...adopted, + adoptedFromRunId: current.checkoutRunId + }; + } + } + throw conflict("Issue run ownership conflict", { + issueId: current.id, + status: current.status, + assigneeAgentId: current.assigneeAgentId, + checkoutRunId: current.checkoutRunId, + actorAgentId, + actorRunId + }); + }, + release: async (id, actorAgentId, actorRunId) => { + const existing = await db.select().from(issues).where(eq(issues.id, id)).then((rows) => rows[0] ?? null); + if (!existing) return null; + if (actorAgentId && existing.assigneeAgentId && existing.assigneeAgentId !== actorAgentId) { + throw conflict("Only assignee can release issue"); + } + if (actorAgentId && existing.status === "in_progress" && existing.assigneeAgentId === actorAgentId && existing.checkoutRunId && !sameRunLock(existing.checkoutRunId, actorRunId ?? null)) { + throw conflict("Only checkout run can release issue", { + issueId: existing.id, + assigneeAgentId: existing.assigneeAgentId, + checkoutRunId: existing.checkoutRunId, + actorRunId: actorRunId ?? null + }); + } + const updated = await db.update(issues).set({ + status: "todo", + assigneeAgentId: null, + checkoutRunId: null, + updatedAt: /* @__PURE__ */ new Date() + }).where(eq(issues.id, id)).returning().then((rows) => rows[0] ?? null); + if (!updated) return null; + const [enriched] = await withIssueLabels(db, [updated]); + return enriched; + }, + listLabels: (companyId) => db.select().from(labels).where(eq(labels.companyId, companyId)).orderBy(asc(labels.name), asc(labels.id)), + getLabelById: (id) => db.select().from(labels).where(eq(labels.id, id)).then((rows) => rows[0] ?? null), + createLabel: async (companyId, data2) => { + const [created] = await db.insert(labels).values({ + companyId, + name: data2.name.trim(), + color: data2.color + }).returning(); + return created; + }, + deleteLabel: async (id) => db.delete(labels).where(eq(labels.id, id)).returning().then((rows) => rows[0] ?? null), + listComments: async (issueId, opts) => { + const order = opts?.order === "asc" ? "asc" : "desc"; + const afterCommentId = opts?.afterCommentId?.trim() || null; + const limit = opts?.limit && opts.limit > 0 ? Math.min(Math.floor(opts.limit), MAX_ISSUE_COMMENT_PAGE_LIMIT) : null; + const conditions = [eq(issueComments.issueId, issueId)]; + if (afterCommentId) { + const anchor = await db.select({ + id: issueComments.id, + createdAt: issueComments.createdAt + }).from(issueComments).where(and(eq(issueComments.issueId, issueId), eq(issueComments.id, afterCommentId))).then((rows) => rows[0] ?? null); + if (!anchor) return []; + conditions.push( + order === "asc" ? sql`( + ${issueComments.createdAt} > ${anchor.createdAt} + OR (${issueComments.createdAt} = ${anchor.createdAt} AND ${issueComments.id} > ${anchor.id}) + )` : sql`( + ${issueComments.createdAt} < ${anchor.createdAt} + OR (${issueComments.createdAt} = ${anchor.createdAt} AND ${issueComments.id} < ${anchor.id}) + )` + ); + } + const query = db.select().from(issueComments).where(and(...conditions)).orderBy( + order === "asc" ? asc(issueComments.createdAt) : desc(issueComments.createdAt), + order === "asc" ? asc(issueComments.id) : desc(issueComments.id) + ); + const comments = limit ? await query.limit(limit) : await query; + const { censorUsernameInLogs } = await instanceSettings2.getGeneral(); + return comments.map((comment) => redactIssueComment(comment, censorUsernameInLogs)); + }, + getCommentCursor: async (issueId) => { + const [latest, countRow] = await Promise.all([ + db.select({ + latestCommentId: issueComments.id, + latestCommentAt: issueComments.createdAt + }).from(issueComments).where(eq(issueComments.issueId, issueId)).orderBy(desc(issueComments.createdAt), desc(issueComments.id)).limit(1).then((rows) => rows[0] ?? null), + db.select({ + totalComments: sql`count(*)::int` + }).from(issueComments).where(eq(issueComments.issueId, issueId)).then((rows) => rows[0] ?? null) + ]); + return { + totalComments: Number(countRow?.totalComments ?? 0), + latestCommentId: latest?.latestCommentId ?? null, + latestCommentAt: latest?.latestCommentAt ?? null + }; + }, + getComment: (commentId) => instanceSettings2.getGeneral().then(({ censorUsernameInLogs }) => db.select().from(issueComments).where(eq(issueComments.id, commentId)).then((rows) => { + const comment = rows[0] ?? null; + return comment ? redactIssueComment(comment, censorUsernameInLogs) : null; + })), + removeComment: async (commentId) => { + const currentUserRedactionOptions = { + enabled: (await instanceSettings2.getGeneral()).censorUsernameInLogs + }; + return db.transaction(async (tx) => { + const [comment] = await tx.delete(issueComments).where(eq(issueComments.id, commentId)).returning(); + if (!comment) return null; + await tx.update(issues).set({ updatedAt: /* @__PURE__ */ new Date() }).where(eq(issues.id, comment.issueId)); + return redactIssueComment(comment, currentUserRedactionOptions.enabled); + }); + }, + addComment: async (issueId, body, actor) => { + const issue2 = await db.select({ companyId: issues.companyId }).from(issues).where(eq(issues.id, issueId)).then((rows) => rows[0] ?? null); + if (!issue2) throw notFound("Issue not found"); + const currentUserRedactionOptions = { + enabled: (await instanceSettings2.getGeneral()).censorUsernameInLogs + }; + const redactedBody = redactCurrentUserText(body, currentUserRedactionOptions); + const [comment] = await db.insert(issueComments).values({ + companyId: issue2.companyId, + issueId, + authorAgentId: actor.agentId ?? null, + authorUserId: actor.userId ?? null, + createdByRunId: actor.runId ?? null, + body: redactedBody + }).returning(); + await db.update(issues).set({ updatedAt: /* @__PURE__ */ new Date() }).where(eq(issues.id, issueId)); + return redactIssueComment(comment, currentUserRedactionOptions.enabled); + }, + createAttachment: async (input) => { + const issue2 = await db.select({ id: issues.id, companyId: issues.companyId }).from(issues).where(eq(issues.id, input.issueId)).then((rows) => rows[0] ?? null); + if (!issue2) throw notFound("Issue not found"); + if (input.issueCommentId) { + const comment = await db.select({ id: issueComments.id, companyId: issueComments.companyId, issueId: issueComments.issueId }).from(issueComments).where(eq(issueComments.id, input.issueCommentId)).then((rows) => rows[0] ?? null); + if (!comment) throw notFound("Issue comment not found"); + if (comment.companyId !== issue2.companyId || comment.issueId !== issue2.id) { + throw unprocessable("Attachment comment must belong to same issue and company"); + } + } + return db.transaction(async (tx) => { + const [asset] = await tx.insert(assets).values({ + companyId: issue2.companyId, + provider: input.provider, + objectKey: input.objectKey, + contentType: input.contentType, + byteSize: input.byteSize, + sha256: input.sha256, + originalFilename: input.originalFilename ?? null, + createdByAgentId: input.createdByAgentId ?? null, + createdByUserId: input.createdByUserId ?? null + }).returning(); + const [attachment] = await tx.insert(issueAttachments).values({ + companyId: issue2.companyId, + issueId: issue2.id, + assetId: asset.id, + issueCommentId: input.issueCommentId ?? null + }).returning(); + return { + id: attachment.id, + companyId: attachment.companyId, + issueId: attachment.issueId, + issueCommentId: attachment.issueCommentId, + assetId: attachment.assetId, + provider: asset.provider, + objectKey: asset.objectKey, + contentType: asset.contentType, + byteSize: asset.byteSize, + sha256: asset.sha256, + originalFilename: asset.originalFilename, + createdByAgentId: asset.createdByAgentId, + createdByUserId: asset.createdByUserId, + createdAt: attachment.createdAt, + updatedAt: attachment.updatedAt + }; + }); + }, + listAttachments: async (issueId) => db.select({ + id: issueAttachments.id, + companyId: issueAttachments.companyId, + issueId: issueAttachments.issueId, + issueCommentId: issueAttachments.issueCommentId, + assetId: issueAttachments.assetId, + provider: assets.provider, + objectKey: assets.objectKey, + contentType: assets.contentType, + byteSize: assets.byteSize, + sha256: assets.sha256, + originalFilename: assets.originalFilename, + createdByAgentId: assets.createdByAgentId, + createdByUserId: assets.createdByUserId, + createdAt: issueAttachments.createdAt, + updatedAt: issueAttachments.updatedAt + }).from(issueAttachments).innerJoin(assets, eq(issueAttachments.assetId, assets.id)).where(eq(issueAttachments.issueId, issueId)).orderBy(desc(issueAttachments.createdAt)), + getAttachmentById: async (id) => db.select({ + id: issueAttachments.id, + companyId: issueAttachments.companyId, + issueId: issueAttachments.issueId, + issueCommentId: issueAttachments.issueCommentId, + assetId: issueAttachments.assetId, + provider: assets.provider, + objectKey: assets.objectKey, + contentType: assets.contentType, + byteSize: assets.byteSize, + sha256: assets.sha256, + originalFilename: assets.originalFilename, + createdByAgentId: assets.createdByAgentId, + createdByUserId: assets.createdByUserId, + createdAt: issueAttachments.createdAt, + updatedAt: issueAttachments.updatedAt + }).from(issueAttachments).innerJoin(assets, eq(issueAttachments.assetId, assets.id)).where(eq(issueAttachments.id, id)).then((rows) => rows[0] ?? null), + removeAttachment: async (id) => db.transaction(async (tx) => { + const existing = await tx.select({ + id: issueAttachments.id, + companyId: issueAttachments.companyId, + issueId: issueAttachments.issueId, + issueCommentId: issueAttachments.issueCommentId, + assetId: issueAttachments.assetId, + provider: assets.provider, + objectKey: assets.objectKey, + contentType: assets.contentType, + byteSize: assets.byteSize, + sha256: assets.sha256, + originalFilename: assets.originalFilename, + createdByAgentId: assets.createdByAgentId, + createdByUserId: assets.createdByUserId, + createdAt: issueAttachments.createdAt, + updatedAt: issueAttachments.updatedAt + }).from(issueAttachments).innerJoin(assets, eq(issueAttachments.assetId, assets.id)).where(eq(issueAttachments.id, id)).then((rows) => rows[0] ?? null); + if (!existing) return null; + await tx.delete(issueAttachments).where(eq(issueAttachments.id, id)); + await tx.delete(assets).where(eq(assets.id, existing.assetId)); + return existing; + }), + findMentionedAgents: async (companyId, body) => { + const re = /\B@([^\s@,!?.]+)/g; + const tokens = /* @__PURE__ */ new Set(); + let m5; + while ((m5 = re.exec(body)) !== null) { + const normalized = normalizeAgentMentionToken(m5[1]); + if (normalized) tokens.add(normalized.toLowerCase()); + } + const explicitAgentMentionIds = extractAgentMentionIds(body); + if (tokens.size === 0 && explicitAgentMentionIds.length === 0) return []; + const rows = await db.select({ id: agents.id, name: agents.name }).from(agents).where(eq(agents.companyId, companyId)); + const resolved = new Set(explicitAgentMentionIds); + for (const agent of rows) { + if (tokens.has(agent.name.toLowerCase())) { + resolved.add(agent.id); + } + } + return [...resolved]; + }, + findMentionedProjectIds: async (issueId) => { + const issue2 = await db.select({ + companyId: issues.companyId, + title: issues.title, + description: issues.description + }).from(issues).where(eq(issues.id, issueId)).then((rows2) => rows2[0] ?? null); + if (!issue2) return []; + const comments = await db.select({ body: issueComments.body }).from(issueComments).where(eq(issueComments.issueId, issueId)); + const mentionedIds = /* @__PURE__ */ new Set(); + for (const source of [ + issue2.title, + issue2.description ?? "", + ...comments.map((comment) => comment.body) + ]) { + for (const projectId of extractProjectMentionIds(source)) { + mentionedIds.add(projectId); + } + } + if (mentionedIds.size === 0) return []; + const rows = await db.select({ id: projects.id }).from(projects).where( + and( + eq(projects.companyId, issue2.companyId), + inArray(projects.id, [...mentionedIds]) + ) + ); + const valid = new Set(rows.map((row) => row.id)); + return [...mentionedIds].filter((projectId) => valid.has(projectId)); + }, + getAncestors: async (issueId) => { + const raw = []; + const visited = /* @__PURE__ */ new Set([issueId]); + const start = await db.select().from(issues).where(eq(issues.id, issueId)).then((r5) => r5[0] ?? null); + let currentId = start?.parentId ?? null; + while (currentId && !visited.has(currentId) && raw.length < 50) { + visited.add(currentId); + const parent = await db.select({ + id: issues.id, + identifier: issues.identifier, + title: issues.title, + description: issues.description, + status: issues.status, + priority: issues.priority, + assigneeAgentId: issues.assigneeAgentId, + projectId: issues.projectId, + goalId: issues.goalId, + parentId: issues.parentId + }).from(issues).where(eq(issues.id, currentId)).then((r5) => r5[0] ?? null); + if (!parent) break; + raw.push({ + id: parent.id, + identifier: parent.identifier ?? null, + title: parent.title, + description: parent.description ?? null, + status: parent.status, + priority: parent.priority, + assigneeAgentId: parent.assigneeAgentId ?? null, + projectId: parent.projectId ?? null, + goalId: parent.goalId ?? null + }); + currentId = parent.parentId ?? null; + } + const projectIds = [...new Set(raw.map((a5) => a5.projectId).filter((id) => id != null))]; + const goalIds = [...new Set(raw.map((a5) => a5.goalId).filter((id) => id != null))]; + const projectMap = /* @__PURE__ */ new Map(); + const goalMap = /* @__PURE__ */ new Map(); + if (projectIds.length > 0) { + const workspaceRows = await db.select().from(projectWorkspaces).where(inArray(projectWorkspaces.projectId, projectIds)).orderBy(desc(projectWorkspaces.isPrimary), asc(projectWorkspaces.createdAt), asc(projectWorkspaces.id)); + const workspaceMap = /* @__PURE__ */ new Map(); + for (const workspace of workspaceRows) { + const existing = workspaceMap.get(workspace.projectId); + if (existing) existing.push(workspace); + else workspaceMap.set(workspace.projectId, [workspace]); + } + const rows = await db.select({ + id: projects.id, + name: projects.name, + description: projects.description, + status: projects.status, + goalId: projects.goalId + }).from(projects).where(inArray(projects.id, projectIds)); + for (const r5 of rows) { + const projectWorkspaceRows = workspaceMap.get(r5.id) ?? []; + const workspaces = projectWorkspaceRows.map((workspace) => ({ + id: workspace.id, + companyId: workspace.companyId, + projectId: workspace.projectId, + name: workspace.name, + cwd: workspace.cwd, + repoUrl: workspace.repoUrl ?? null, + repoRef: workspace.repoRef ?? null, + metadata: workspace.metadata ?? null, + isPrimary: workspace.isPrimary, + createdAt: workspace.createdAt, + updatedAt: workspace.updatedAt + })); + const primaryWorkspace = workspaces.find((workspace) => workspace.isPrimary) ?? workspaces[0] ?? null; + projectMap.set(r5.id, { + ...r5, + workspaces, + primaryWorkspace + }); + if (r5.goalId && !goalIds.includes(r5.goalId)) goalIds.push(r5.goalId); + } + } + if (goalIds.length > 0) { + const rows = await db.select({ + id: goals.id, + title: goals.title, + description: goals.description, + level: goals.level, + status: goals.status + }).from(goals).where(inArray(goals.id, goalIds)); + for (const r5 of rows) goalMap.set(r5.id, r5); + } + return raw.map((a5) => ({ + ...a5, + project: a5.projectId ? projectMap.get(a5.projectId) ?? null : null, + goal: a5.goalId ? goalMap.get(a5.goalId) ?? null : null + })); + } + }; +} + +// server/src/services/issue-approvals.ts +init_drizzle_orm(); +init_src2(); +function issueApprovalService(db) { + async function getIssue(issueId) { + return db.select().from(issues).where(eq(issues.id, issueId)).then((rows) => rows[0] ?? null); + } + async function getApproval(approvalId) { + return db.select().from(approvals).where(eq(approvals.id, approvalId)).then((rows) => rows[0] ?? null); + } + async function assertIssueAndApprovalSameCompany(issueId, approvalId) { + const issue2 = await getIssue(issueId); + if (!issue2) throw notFound("Issue not found"); + const approval = await getApproval(approvalId); + if (!approval) throw notFound("Approval not found"); + if (issue2.companyId !== approval.companyId) { + throw unprocessable("Issue and approval must belong to the same company"); + } + return { issue: issue2, approval }; + } + return { + listApprovalsForIssue: async (issueId) => { + const issue2 = await getIssue(issueId); + if (!issue2) throw notFound("Issue not found"); + const result = await db.select({ + id: approvals.id, + companyId: approvals.companyId, + type: approvals.type, + requestedByAgentId: approvals.requestedByAgentId, + requestedByUserId: approvals.requestedByUserId, + status: approvals.status, + payload: approvals.payload, + decisionNote: approvals.decisionNote, + decidedByUserId: approvals.decidedByUserId, + decidedAt: approvals.decidedAt, + createdAt: approvals.createdAt, + updatedAt: approvals.updatedAt + }).from(issueApprovals).innerJoin(approvals, eq(issueApprovals.approvalId, approvals.id)).where(eq(issueApprovals.issueId, issueId)).orderBy(desc(issueApprovals.createdAt)); + return result.map((approval) => ({ + ...approval, + payload: redactEventPayload(approval.payload) ?? {} + })); + }, + listIssuesForApproval: async (approvalId) => { + const approval = await getApproval(approvalId); + if (!approval) throw notFound("Approval not found"); + return db.select({ + id: issues.id, + companyId: issues.companyId, + projectId: issues.projectId, + goalId: issues.goalId, + parentId: issues.parentId, + title: issues.title, + description: issues.description, + status: issues.status, + priority: issues.priority, + assigneeAgentId: issues.assigneeAgentId, + createdByAgentId: issues.createdByAgentId, + createdByUserId: issues.createdByUserId, + issueNumber: issues.issueNumber, + identifier: issues.identifier, + requestDepth: issues.requestDepth, + billingCode: issues.billingCode, + startedAt: issues.startedAt, + completedAt: issues.completedAt, + cancelledAt: issues.cancelledAt, + createdAt: issues.createdAt, + updatedAt: issues.updatedAt + }).from(issueApprovals).innerJoin(issues, eq(issueApprovals.issueId, issues.id)).where(eq(issueApprovals.approvalId, approvalId)).orderBy(desc(issueApprovals.createdAt)); + }, + link: async (issueId, approvalId, actor) => { + const { issue: issue2 } = await assertIssueAndApprovalSameCompany(issueId, approvalId); + await db.insert(issueApprovals).values({ + companyId: issue2.companyId, + issueId, + approvalId, + linkedByAgentId: actor?.agentId ?? null, + linkedByUserId: actor?.userId ?? null + }).onConflictDoNothing(); + return db.select().from(issueApprovals).where(and(eq(issueApprovals.issueId, issueId), eq(issueApprovals.approvalId, approvalId))).then((rows) => rows[0] ?? null); + }, + unlink: async (issueId, approvalId) => { + await assertIssueAndApprovalSameCompany(issueId, approvalId); + await db.delete(issueApprovals).where(and(eq(issueApprovals.issueId, issueId), eq(issueApprovals.approvalId, approvalId))); + }, + linkManyForApproval: async (approvalId, issueIds, actor) => { + if (issueIds.length === 0) return; + const approval = await getApproval(approvalId); + if (!approval) throw notFound("Approval not found"); + const uniqueIssueIds = Array.from(new Set(issueIds)); + const rows = await db.select({ + id: issues.id, + companyId: issues.companyId + }).from(issues).where(inArray(issues.id, uniqueIssueIds)); + if (rows.length !== uniqueIssueIds.length) { + throw notFound("One or more issues not found"); + } + for (const row of rows) { + if (row.companyId !== approval.companyId) { + throw unprocessable("Issue and approval must belong to the same company"); + } + } + await db.insert(issueApprovals).values( + uniqueIssueIds.map((issueId) => ({ + companyId: approval.companyId, + issueId, + approvalId, + linkedByAgentId: actor?.agentId ?? null, + linkedByUserId: actor?.userId ?? null + })) + ).onConflictDoNothing(); + } + }; +} + +// server/src/services/activity.ts +init_drizzle_orm(); +init_src2(); +function activityService(db) { + const issueIdAsText = sql`${issues.id}::text`; + const summarizedUsageJson = sql` + case + when ${heartbeatRuns.usageJson} is null then null + else jsonb_strip_nulls(jsonb_build_object( + 'inputTokens', coalesce(${heartbeatRuns.usageJson} -> 'inputTokens', ${heartbeatRuns.usageJson} -> 'input_tokens'), + 'input_tokens', coalesce(${heartbeatRuns.usageJson} -> 'input_tokens', ${heartbeatRuns.usageJson} -> 'inputTokens'), + 'outputTokens', coalesce(${heartbeatRuns.usageJson} -> 'outputTokens', ${heartbeatRuns.usageJson} -> 'output_tokens'), + 'output_tokens', coalesce(${heartbeatRuns.usageJson} -> 'output_tokens', ${heartbeatRuns.usageJson} -> 'outputTokens'), + 'cachedInputTokens', coalesce( + ${heartbeatRuns.usageJson} -> 'cachedInputTokens', + ${heartbeatRuns.usageJson} -> 'cached_input_tokens', + ${heartbeatRuns.usageJson} -> 'cache_read_input_tokens' + ), + 'cached_input_tokens', coalesce( + ${heartbeatRuns.usageJson} -> 'cached_input_tokens', + ${heartbeatRuns.usageJson} -> 'cachedInputTokens', + ${heartbeatRuns.usageJson} -> 'cache_read_input_tokens' + ), + 'cache_read_input_tokens', coalesce( + ${heartbeatRuns.usageJson} -> 'cache_read_input_tokens', + ${heartbeatRuns.usageJson} -> 'cached_input_tokens', + ${heartbeatRuns.usageJson} -> 'cachedInputTokens' + ), + 'billingType', coalesce(${heartbeatRuns.usageJson} -> 'billingType', ${heartbeatRuns.usageJson} -> 'billing_type'), + 'billing_type', coalesce(${heartbeatRuns.usageJson} -> 'billing_type', ${heartbeatRuns.usageJson} -> 'billingType'), + 'costUsd', coalesce( + ${heartbeatRuns.usageJson} -> 'costUsd', + ${heartbeatRuns.usageJson} -> 'cost_usd', + ${heartbeatRuns.usageJson} -> 'total_cost_usd' + ), + 'cost_usd', coalesce( + ${heartbeatRuns.usageJson} -> 'cost_usd', + ${heartbeatRuns.usageJson} -> 'costUsd', + ${heartbeatRuns.usageJson} -> 'total_cost_usd' + ), + 'total_cost_usd', coalesce( + ${heartbeatRuns.usageJson} -> 'total_cost_usd', + ${heartbeatRuns.usageJson} -> 'cost_usd', + ${heartbeatRuns.usageJson} -> 'costUsd' + ) + )) + end + `.as("usageJson"); + const summarizedResultJson = sql` + case + when ${heartbeatRuns.resultJson} is null then null + else jsonb_strip_nulls(jsonb_build_object( + 'billingType', coalesce(${heartbeatRuns.resultJson} -> 'billingType', ${heartbeatRuns.resultJson} -> 'billing_type'), + 'billing_type', coalesce(${heartbeatRuns.resultJson} -> 'billing_type', ${heartbeatRuns.resultJson} -> 'billingType'), + 'costUsd', coalesce( + ${heartbeatRuns.resultJson} -> 'costUsd', + ${heartbeatRuns.resultJson} -> 'cost_usd', + ${heartbeatRuns.resultJson} -> 'total_cost_usd' + ), + 'cost_usd', coalesce( + ${heartbeatRuns.resultJson} -> 'cost_usd', + ${heartbeatRuns.resultJson} -> 'costUsd', + ${heartbeatRuns.resultJson} -> 'total_cost_usd' + ), + 'total_cost_usd', coalesce( + ${heartbeatRuns.resultJson} -> 'total_cost_usd', + ${heartbeatRuns.resultJson} -> 'cost_usd', + ${heartbeatRuns.resultJson} -> 'costUsd' + ) + )) + end + `.as("resultJson"); + return { + list: (filters) => { + const conditions = [eq(activityLog.companyId, filters.companyId)]; + if (filters.agentId) { + conditions.push(eq(activityLog.agentId, filters.agentId)); + } + if (filters.entityType) { + conditions.push(eq(activityLog.entityType, filters.entityType)); + } + if (filters.entityId) { + conditions.push(eq(activityLog.entityId, filters.entityId)); + } + return db.select({ activityLog }).from(activityLog).leftJoin( + issues, + and( + eq(activityLog.entityType, sql`'issue'`), + eq(activityLog.entityId, issueIdAsText) + ) + ).where( + and( + ...conditions, + or( + sql`${activityLog.entityType} != 'issue'`, + isNull(issues.hiddenAt) + ) + ) + ).orderBy(desc(activityLog.createdAt)).then((rows) => rows.map((r5) => r5.activityLog)); + }, + forIssue: (issueId) => db.select().from(activityLog).where( + and( + eq(activityLog.entityType, "issue"), + eq(activityLog.entityId, issueId) + ) + ).orderBy(desc(activityLog.createdAt)), + runsForIssue: (companyId, issueId) => db.select({ + runId: heartbeatRuns.id, + status: heartbeatRuns.status, + agentId: heartbeatRuns.agentId, + adapterType: agents.adapterType, + startedAt: heartbeatRuns.startedAt, + finishedAt: heartbeatRuns.finishedAt, + createdAt: heartbeatRuns.createdAt, + invocationSource: heartbeatRuns.invocationSource, + usageJson: summarizedUsageJson, + resultJson: summarizedResultJson, + logBytes: heartbeatRuns.logBytes + }).from(heartbeatRuns).innerJoin( + agents, + and( + eq(agents.id, heartbeatRuns.agentId), + eq(agents.companyId, heartbeatRuns.companyId) + ) + ).where( + and( + eq(heartbeatRuns.companyId, companyId), + or( + sql`${heartbeatRuns.contextSnapshot} ->> 'issueId' = ${issueId}`, + sql`exists ( + select 1 + from ${activityLog} + where ${activityLog.companyId} = ${companyId} + and ${activityLog.entityType} = 'issue' + and ${activityLog.entityId} = ${issueId} + and ${activityLog.runId} = ${heartbeatRuns.id} + )` + ) + ) + ).orderBy(desc(heartbeatRuns.createdAt)), + issuesForRun: async (runId) => { + const run = await db.select({ + companyId: heartbeatRuns.companyId, + contextSnapshot: heartbeatRuns.contextSnapshot + }).from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)).then((rows) => rows[0] ?? null); + if (!run) return []; + const fromActivity = await db.selectDistinctOn([issueIdAsText], { + issueId: issues.id, + identifier: issues.identifier, + title: issues.title, + status: issues.status, + priority: issues.priority + }).from(activityLog).innerJoin(issues, eq(activityLog.entityId, issueIdAsText)).where( + and( + eq(activityLog.companyId, run.companyId), + eq(activityLog.runId, runId), + eq(activityLog.entityType, "issue"), + isNull(issues.hiddenAt) + ) + ).orderBy(issueIdAsText); + const context = run.contextSnapshot; + const contextIssueId = context && typeof context === "object" && typeof context.issueId === "string" ? context.issueId : null; + if (!contextIssueId) return fromActivity; + if (fromActivity.some((issue2) => issue2.issueId === contextIssueId)) return fromActivity; + const fromContext = await db.select({ + issueId: issues.id, + identifier: issues.identifier, + title: issues.title, + status: issues.status, + priority: issues.priority + }).from(issues).where( + and( + eq(issues.companyId, run.companyId), + eq(issues.id, contextIssueId), + isNull(issues.hiddenAt) + ) + ).then((rows) => rows[0] ?? null); + if (!fromContext) return fromActivity; + return [fromContext, ...fromActivity]; + }, + create: (data2) => db.insert(activityLog).values(data2).returning().then((rows) => rows[0]) + }; +} + +// server/src/services/approvals.ts +init_drizzle_orm(); +init_src2(); + +// server/src/services/budgets.ts +init_drizzle_orm(); +init_src2(); + +// server/src/services/activity-log.ts +init_src2(); +import { randomUUID as randomUUID3 } from "node:crypto"; + +// server/src/services/live-events.ts +import { EventEmitter } from "node:events"; +var emitter = new EventEmitter(); +emitter.setMaxListeners(0); +var nextEventId = 0; +function toLiveEvent(input) { + nextEventId += 1; + return { + id: nextEventId, + companyId: input.companyId, + type: input.type, + createdAt: (/* @__PURE__ */ new Date()).toISOString(), + payload: input.payload ?? {} + }; +} +function publishLiveEvent(input) { + const event = toLiveEvent(input); + emitter.emit(input.companyId, event); + return event; +} +function publishGlobalLiveEvent(input) { + const event = toLiveEvent({ companyId: "*", type: input.type, payload: input.payload }); + emitter.emit("*", event); + return event; +} +function subscribeCompanyLiveEvents(companyId, listener) { + emitter.on(companyId, listener); + return () => emitter.off(companyId, listener); +} + +// server/src/services/activity-log.ts +var PLUGIN_EVENT_SET = new Set(PLUGIN_EVENT_TYPES); +var _pluginEventBus = null; +function setPluginEventBus(bus) { + if (_pluginEventBus) { + logger.warn("setPluginEventBus called more than once, replacing existing bus"); + } + _pluginEventBus = bus; +} +async function logActivity(db, input) { + const currentUserRedactionOptions = { + enabled: (await instanceSettingsService(db).getGeneral()).censorUsernameInLogs + }; + const sanitizedDetails = input.details ? sanitizeRecord(input.details) : null; + const redactedDetails = sanitizedDetails ? redactCurrentUserValue(sanitizedDetails, currentUserRedactionOptions) : null; + await db.insert(activityLog).values({ + companyId: input.companyId, + actorType: input.actorType, + actorId: input.actorId, + action: input.action, + entityType: input.entityType, + entityId: input.entityId, + agentId: input.agentId ?? null, + runId: input.runId ?? null, + details: redactedDetails + }); + publishLiveEvent({ + companyId: input.companyId, + type: "activity.logged", + payload: { + actorType: input.actorType, + actorId: input.actorId, + action: input.action, + entityType: input.entityType, + entityId: input.entityId, + agentId: input.agentId ?? null, + runId: input.runId ?? null, + details: redactedDetails + } + }); + if (_pluginEventBus && PLUGIN_EVENT_SET.has(input.action)) { + const event = { + eventId: randomUUID3(), + eventType: input.action, + occurredAt: (/* @__PURE__ */ new Date()).toISOString(), + actorId: input.actorId, + actorType: input.actorType, + entityId: input.entityId, + entityType: input.entityType, + companyId: input.companyId, + payload: { + ...redactedDetails, + agentId: input.agentId ?? null, + runId: input.runId ?? null + } + }; + void _pluginEventBus.emit(event).then(({ errors }) => { + for (const { pluginId, error: error50 } of errors) { + logger.warn({ pluginId, eventType: event.eventType, err: error50 }, "plugin event handler failed"); + } + }).catch(() => { + }); + } +} + +// server/src/services/budgets.ts +function currentUtcMonthWindow(now2 = /* @__PURE__ */ new Date()) { + const year3 = now2.getUTCFullYear(); + const month = now2.getUTCMonth(); + const start = new Date(Date.UTC(year3, month, 1, 0, 0, 0, 0)); + const end = new Date(Date.UTC(year3, month + 1, 1, 0, 0, 0, 0)); + return { start, end }; +} +function resolveWindow(windowKind, now2 = /* @__PURE__ */ new Date()) { + if (windowKind === "lifetime") { + return { + start: new Date(Date.UTC(1970, 0, 1, 0, 0, 0, 0)), + end: new Date(Date.UTC(9999, 0, 1, 0, 0, 0, 0)) + }; + } + return currentUtcMonthWindow(now2); +} +function budgetStatusFromObserved(observedAmount, amount, warnPercent) { + if (amount <= 0) return "ok"; + if (observedAmount >= amount) return "hard_stop"; + if (observedAmount >= Math.ceil(amount * warnPercent / 100)) return "warning"; + return "ok"; +} +function normalizeScopeName(scopeType, name) { + if (scopeType === "company") return name; + return name.trim().length > 0 ? name : scopeType; +} +async function resolveScopeRecord(db, scopeType, scopeId) { + if (scopeType === "company") { + const row2 = await db.select({ + companyId: companies.id, + name: companies.name, + status: companies.status, + pauseReason: companies.pauseReason, + pausedAt: companies.pausedAt + }).from(companies).where(eq(companies.id, scopeId)).then((rows) => rows[0] ?? null); + if (!row2) throw notFound("Company not found"); + return { + companyId: row2.companyId, + name: row2.name, + paused: row2.status === "paused" || Boolean(row2.pausedAt), + pauseReason: row2.pauseReason ?? null + }; + } + if (scopeType === "agent") { + const row2 = await db.select({ + companyId: agents.companyId, + name: agents.name, + status: agents.status, + pauseReason: agents.pauseReason + }).from(agents).where(eq(agents.id, scopeId)).then((rows) => rows[0] ?? null); + if (!row2) throw notFound("Agent not found"); + return { + companyId: row2.companyId, + name: row2.name, + paused: row2.status === "paused", + pauseReason: row2.pauseReason ?? null + }; + } + const row = await db.select({ + companyId: projects.companyId, + name: projects.name, + pauseReason: projects.pauseReason, + pausedAt: projects.pausedAt + }).from(projects).where(eq(projects.id, scopeId)).then((rows) => rows[0] ?? null); + if (!row) throw notFound("Project not found"); + return { + companyId: row.companyId, + name: row.name, + paused: Boolean(row.pausedAt), + pauseReason: row.pauseReason ?? null + }; +} +async function computeObservedAmount(db, policy) { + if (policy.metric !== "billed_cents") return 0; + const conditions = [eq(costEvents.companyId, policy.companyId)]; + if (policy.scopeType === "agent") conditions.push(eq(costEvents.agentId, policy.scopeId)); + if (policy.scopeType === "project") conditions.push(eq(costEvents.projectId, policy.scopeId)); + const { start, end } = resolveWindow(policy.windowKind); + if (policy.windowKind === "calendar_month_utc") { + conditions.push(gte(costEvents.occurredAt, start)); + conditions.push(lt(costEvents.occurredAt, end)); + } + const [row] = await db.select({ + total: sql`coalesce(sum(${costEvents.costCents}), 0)::int` + }).from(costEvents).where(and(...conditions)); + return Number(row?.total ?? 0); +} +function buildApprovalPayload(input) { + return { + scopeType: input.policy.scopeType, + scopeId: input.policy.scopeId, + scopeName: input.scopeName, + metric: input.policy.metric, + windowKind: input.policy.windowKind, + thresholdType: input.thresholdType, + budgetAmount: input.policy.amount, + observedAmount: input.amountObserved, + warnPercent: input.policy.warnPercent, + windowStart: input.windowStart.toISOString(), + windowEnd: input.windowEnd.toISOString(), + policyId: input.policy.id, + guidance: "Raise the budget and resume the scope, or keep the scope paused." + }; +} +async function markApprovalStatus(db, approvalId, status, decisionNote, decidedByUserId) { + if (!approvalId) return; + await db.update(approvals).set({ + status, + decisionNote: decisionNote ?? null, + decidedByUserId, + decidedAt: /* @__PURE__ */ new Date(), + updatedAt: /* @__PURE__ */ new Date() + }).where(eq(approvals.id, approvalId)); +} +function budgetService(db, hooks = {}) { + async function pauseScopeForBudget(policy) { + const now2 = /* @__PURE__ */ new Date(); + if (policy.scopeType === "agent") { + await db.update(agents).set({ + status: "paused", + pauseReason: "budget", + pausedAt: now2, + updatedAt: now2 + }).where(and(eq(agents.id, policy.scopeId), inArray(agents.status, ["active", "idle", "running", "error"]))); + return; + } + if (policy.scopeType === "project") { + await db.update(projects).set({ + pauseReason: "budget", + pausedAt: now2, + updatedAt: now2 + }).where(eq(projects.id, policy.scopeId)); + return; + } + await db.update(companies).set({ + status: "paused", + pauseReason: "budget", + pausedAt: now2, + updatedAt: now2 + }).where(eq(companies.id, policy.scopeId)); + } + async function pauseAndCancelScopeForBudget(policy) { + await pauseScopeForBudget(policy); + await hooks.cancelWorkForScope?.({ + companyId: policy.companyId, + scopeType: policy.scopeType, + scopeId: policy.scopeId + }); + } + async function resumeScopeFromBudget(policy) { + const now2 = /* @__PURE__ */ new Date(); + if (policy.scopeType === "agent") { + await db.update(agents).set({ + status: "idle", + pauseReason: null, + pausedAt: null, + updatedAt: now2 + }).where(and(eq(agents.id, policy.scopeId), eq(agents.pauseReason, "budget"))); + return; + } + if (policy.scopeType === "project") { + await db.update(projects).set({ + pauseReason: null, + pausedAt: null, + updatedAt: now2 + }).where(and(eq(projects.id, policy.scopeId), eq(projects.pauseReason, "budget"))); + return; + } + await db.update(companies).set({ + status: "active", + pauseReason: null, + pausedAt: null, + updatedAt: now2 + }).where(and(eq(companies.id, policy.scopeId), eq(companies.pauseReason, "budget"))); + } + async function getPolicyRow(policyId) { + const policy = await db.select().from(budgetPolicies).where(eq(budgetPolicies.id, policyId)).then((rows) => rows[0] ?? null); + if (!policy) throw notFound("Budget policy not found"); + return policy; + } + async function listPolicyRows(companyId) { + return db.select().from(budgetPolicies).where(eq(budgetPolicies.companyId, companyId)).orderBy(desc(budgetPolicies.updatedAt)); + } + async function buildPolicySummary(policy) { + const scope = await resolveScopeRecord(db, policy.scopeType, policy.scopeId); + const observedAmount = await computeObservedAmount(db, policy); + const { start, end } = resolveWindow(policy.windowKind); + const amount = policy.isActive ? policy.amount : 0; + const utilizationPercent = amount > 0 ? Number((observedAmount / amount * 100).toFixed(2)) : 0; + return { + policyId: policy.id, + companyId: policy.companyId, + scopeType: policy.scopeType, + scopeId: policy.scopeId, + scopeName: normalizeScopeName(policy.scopeType, scope.name), + metric: policy.metric, + windowKind: policy.windowKind, + amount, + observedAmount, + remainingAmount: amount > 0 ? Math.max(0, amount - observedAmount) : 0, + utilizationPercent, + warnPercent: policy.warnPercent, + hardStopEnabled: policy.hardStopEnabled, + notifyEnabled: policy.notifyEnabled, + isActive: policy.isActive, + status: policy.isActive ? budgetStatusFromObserved(observedAmount, amount, policy.warnPercent) : "ok", + paused: scope.paused, + pauseReason: scope.pauseReason, + windowStart: start, + windowEnd: end + }; + } + async function createIncidentIfNeeded(policy, thresholdType, amountObserved) { + const { start, end } = resolveWindow(policy.windowKind); + const existing = await db.select().from(budgetIncidents).where( + and( + eq(budgetIncidents.policyId, policy.id), + eq(budgetIncidents.windowStart, start), + eq(budgetIncidents.thresholdType, thresholdType), + ne(budgetIncidents.status, "dismissed") + ) + ).then((rows) => rows[0] ?? null); + if (existing) return existing; + const scope = await resolveScopeRecord(db, policy.scopeType, policy.scopeId); + const payload2 = buildApprovalPayload({ + policy, + scopeName: normalizeScopeName(policy.scopeType, scope.name), + thresholdType, + amountObserved, + windowStart: start, + windowEnd: end + }); + const approval = thresholdType === "hard" ? await db.insert(approvals).values({ + companyId: policy.companyId, + type: "budget_override_required", + requestedByUserId: null, + requestedByAgentId: null, + status: "pending", + payload: payload2 + }).returning().then((rows) => rows[0] ?? null) : null; + return db.insert(budgetIncidents).values({ + companyId: policy.companyId, + policyId: policy.id, + scopeType: policy.scopeType, + scopeId: policy.scopeId, + metric: policy.metric, + windowKind: policy.windowKind, + windowStart: start, + windowEnd: end, + thresholdType, + amountLimit: policy.amount, + amountObserved, + status: "open", + approvalId: approval?.id ?? null + }).returning().then((rows) => rows[0] ?? null); + } + async function resolveOpenSoftIncidents(policyId) { + await db.update(budgetIncidents).set({ + status: "resolved", + resolvedAt: /* @__PURE__ */ new Date(), + updatedAt: /* @__PURE__ */ new Date() + }).where( + and( + eq(budgetIncidents.policyId, policyId), + eq(budgetIncidents.thresholdType, "soft"), + eq(budgetIncidents.status, "open") + ) + ); + } + async function resolveOpenIncidentsForPolicy(policyId, approvalStatus, decidedByUserId) { + const openRows = await db.select().from(budgetIncidents).where(and(eq(budgetIncidents.policyId, policyId), eq(budgetIncidents.status, "open"))); + await db.update(budgetIncidents).set({ + status: "resolved", + resolvedAt: /* @__PURE__ */ new Date(), + updatedAt: /* @__PURE__ */ new Date() + }).where(and(eq(budgetIncidents.policyId, policyId), eq(budgetIncidents.status, "open"))); + if (!approvalStatus || !decidedByUserId) return; + for (const row of openRows) { + await markApprovalStatus(db, row.approvalId ?? null, approvalStatus, "Resolved via budget update", decidedByUserId); + } + } + async function hydrateIncidentRows(rows) { + const approvalIds = rows.map((row) => row.approvalId).filter((value) => Boolean(value)); + const approvalRows = approvalIds.length > 0 ? await db.select({ id: approvals.id, status: approvals.status }).from(approvals).where(inArray(approvals.id, approvalIds)) : []; + const approvalStatusById = new Map(approvalRows.map((row) => [row.id, row.status])); + return Promise.all( + rows.map(async (row) => { + const scope = await resolveScopeRecord(db, row.scopeType, row.scopeId); + return { + id: row.id, + companyId: row.companyId, + policyId: row.policyId, + scopeType: row.scopeType, + scopeId: row.scopeId, + scopeName: normalizeScopeName(row.scopeType, scope.name), + metric: row.metric, + windowKind: row.windowKind, + windowStart: row.windowStart, + windowEnd: row.windowEnd, + thresholdType: row.thresholdType, + amountLimit: row.amountLimit, + amountObserved: row.amountObserved, + status: row.status, + approvalId: row.approvalId ?? null, + approvalStatus: row.approvalId ? approvalStatusById.get(row.approvalId) ?? null : null, + resolvedAt: row.resolvedAt ?? null, + createdAt: row.createdAt, + updatedAt: row.updatedAt + }; + }) + ); + } + return { + listPolicies: async (companyId) => { + const rows = await listPolicyRows(companyId); + return rows.map((row) => ({ + ...row, + scopeType: row.scopeType, + metric: row.metric, + windowKind: row.windowKind + })); + }, + upsertPolicy: async (companyId, input, actorUserId) => { + const scope = await resolveScopeRecord(db, input.scopeType, input.scopeId); + if (scope.companyId !== companyId) { + throw unprocessable("Budget scope does not belong to company"); + } + const metric = input.metric ?? "billed_cents"; + const windowKind = input.windowKind ?? (input.scopeType === "project" ? "lifetime" : "calendar_month_utc"); + const amount = Math.max(0, Math.floor(input.amount)); + const nextIsActive = amount > 0 && (input.isActive ?? true); + const existing = await db.select().from(budgetPolicies).where( + and( + eq(budgetPolicies.companyId, companyId), + eq(budgetPolicies.scopeType, input.scopeType), + eq(budgetPolicies.scopeId, input.scopeId), + eq(budgetPolicies.metric, metric), + eq(budgetPolicies.windowKind, windowKind) + ) + ).then((rows) => rows[0] ?? null); + const now2 = /* @__PURE__ */ new Date(); + const row = existing ? await db.update(budgetPolicies).set({ + amount, + warnPercent: input.warnPercent ?? existing.warnPercent, + hardStopEnabled: input.hardStopEnabled ?? existing.hardStopEnabled, + notifyEnabled: input.notifyEnabled ?? existing.notifyEnabled, + isActive: nextIsActive, + updatedByUserId: actorUserId, + updatedAt: now2 + }).where(eq(budgetPolicies.id, existing.id)).returning().then((rows) => rows[0]) : await db.insert(budgetPolicies).values({ + companyId, + scopeType: input.scopeType, + scopeId: input.scopeId, + metric, + windowKind, + amount, + warnPercent: input.warnPercent ?? 80, + hardStopEnabled: input.hardStopEnabled ?? true, + notifyEnabled: input.notifyEnabled ?? true, + isActive: nextIsActive, + createdByUserId: actorUserId, + updatedByUserId: actorUserId + }).returning().then((rows) => rows[0]); + if (input.scopeType === "company" && windowKind === "calendar_month_utc") { + await db.update(companies).set({ + budgetMonthlyCents: amount, + updatedAt: now2 + }).where(eq(companies.id, input.scopeId)); + } + if (input.scopeType === "agent" && windowKind === "calendar_month_utc") { + await db.update(agents).set({ + budgetMonthlyCents: amount, + updatedAt: now2 + }).where(eq(agents.id, input.scopeId)); + } + if (amount > 0) { + const observedAmount = await computeObservedAmount(db, row); + if (observedAmount < amount) { + await resumeScopeFromBudget(row); + await resolveOpenIncidentsForPolicy(row.id, actorUserId ? "approved" : null, actorUserId); + } else { + const softThreshold = Math.ceil(row.amount * row.warnPercent / 100); + if (row.notifyEnabled && observedAmount >= softThreshold) { + await createIncidentIfNeeded(row, "soft", observedAmount); + } + if (row.hardStopEnabled && observedAmount >= row.amount) { + await resolveOpenSoftIncidents(row.id); + await createIncidentIfNeeded(row, "hard", observedAmount); + await pauseAndCancelScopeForBudget(row); + } + } + } else { + await resumeScopeFromBudget(row); + await resolveOpenIncidentsForPolicy(row.id, actorUserId ? "approved" : null, actorUserId); + } + await logActivity(db, { + companyId, + actorType: "user", + actorId: actorUserId ?? "board", + action: "budget.policy_upserted", + entityType: "budget_policy", + entityId: row.id, + details: { + scopeType: row.scopeType, + scopeId: row.scopeId, + amount: row.amount, + windowKind: row.windowKind + } + }); + return buildPolicySummary(row); + }, + overview: async (companyId) => { + const rows = await listPolicyRows(companyId); + const policies = await Promise.all(rows.map((row) => buildPolicySummary(row))); + const activeIncidentRows = await db.select().from(budgetIncidents).where(and(eq(budgetIncidents.companyId, companyId), eq(budgetIncidents.status, "open"))).orderBy(desc(budgetIncidents.createdAt)); + const activeIncidents = await hydrateIncidentRows(activeIncidentRows); + return { + companyId, + policies, + activeIncidents, + pausedAgentCount: policies.filter((policy) => policy.scopeType === "agent" && policy.paused).length, + pausedProjectCount: policies.filter((policy) => policy.scopeType === "project" && policy.paused).length, + pendingApprovalCount: activeIncidents.filter((incident) => incident.approvalStatus === "pending").length + }; + }, + evaluateCostEvent: async (event) => { + const candidatePolicies = await db.select().from(budgetPolicies).where( + and( + eq(budgetPolicies.companyId, event.companyId), + eq(budgetPolicies.isActive, true), + inArray(budgetPolicies.scopeType, ["company", "agent", "project"]) + ) + ); + const relevantPolicies = candidatePolicies.filter((policy) => { + if (policy.scopeType === "company") return policy.scopeId === event.companyId; + if (policy.scopeType === "agent") return policy.scopeId === event.agentId; + if (policy.scopeType === "project") return Boolean(event.projectId) && policy.scopeId === event.projectId; + return false; + }); + for (const policy of relevantPolicies) { + if (policy.metric !== "billed_cents" || policy.amount <= 0) continue; + const observedAmount = await computeObservedAmount(db, policy); + const softThreshold = Math.ceil(policy.amount * policy.warnPercent / 100); + if (policy.notifyEnabled && observedAmount >= softThreshold) { + const softIncident = await createIncidentIfNeeded(policy, "soft", observedAmount); + if (softIncident) { + await logActivity(db, { + companyId: policy.companyId, + actorType: "system", + actorId: "budget_service", + action: "budget.soft_threshold_crossed", + entityType: "budget_incident", + entityId: softIncident.id, + details: { + scopeType: policy.scopeType, + scopeId: policy.scopeId, + amountObserved: observedAmount, + amountLimit: policy.amount + } + }); + } + } + if (policy.hardStopEnabled && observedAmount >= policy.amount) { + await resolveOpenSoftIncidents(policy.id); + const hardIncident = await createIncidentIfNeeded(policy, "hard", observedAmount); + await pauseAndCancelScopeForBudget(policy); + if (hardIncident) { + await logActivity(db, { + companyId: policy.companyId, + actorType: "system", + actorId: "budget_service", + action: "budget.hard_threshold_crossed", + entityType: "budget_incident", + entityId: hardIncident.id, + details: { + scopeType: policy.scopeType, + scopeId: policy.scopeId, + amountObserved: observedAmount, + amountLimit: policy.amount, + approvalId: hardIncident.approvalId ?? null + } + }); + } + } + } + }, + getInvocationBlock: async (companyId, agentId, context) => { + const agent = await db.select({ + status: agents.status, + pauseReason: agents.pauseReason, + companyId: agents.companyId, + name: agents.name + }).from(agents).where(eq(agents.id, agentId)).then((rows) => rows[0] ?? null); + if (!agent || agent.companyId !== companyId) throw notFound("Agent not found"); + const company = await db.select({ + status: companies.status, + pauseReason: companies.pauseReason, + name: companies.name + }).from(companies).where(eq(companies.id, companyId)).then((rows) => rows[0] ?? null); + if (!company) throw notFound("Company not found"); + if (company.status === "paused") { + return { + scopeType: "company", + scopeId: companyId, + scopeName: company.name, + reason: company.pauseReason === "budget" ? "Company is paused because its budget hard-stop was reached." : "Company is paused and cannot start new work." + }; + } + const companyPolicy = await db.select().from(budgetPolicies).where( + and( + eq(budgetPolicies.companyId, companyId), + eq(budgetPolicies.scopeType, "company"), + eq(budgetPolicies.scopeId, companyId), + eq(budgetPolicies.isActive, true), + eq(budgetPolicies.metric, "billed_cents") + ) + ).then((rows) => rows[0] ?? null); + if (companyPolicy && companyPolicy.hardStopEnabled && companyPolicy.amount > 0) { + const observed = await computeObservedAmount(db, companyPolicy); + if (observed >= companyPolicy.amount) { + return { + scopeType: "company", + scopeId: companyId, + scopeName: company.name, + reason: "Company cannot start new work because its budget hard-stop is exceeded." + }; + } + } + if (agent.status === "paused" && agent.pauseReason === "budget") { + return { + scopeType: "agent", + scopeId: agentId, + scopeName: agent.name, + reason: "Agent is paused because its budget hard-stop was reached." + }; + } + const agentPolicy = await db.select().from(budgetPolicies).where( + and( + eq(budgetPolicies.companyId, companyId), + eq(budgetPolicies.scopeType, "agent"), + eq(budgetPolicies.scopeId, agentId), + eq(budgetPolicies.isActive, true), + eq(budgetPolicies.metric, "billed_cents") + ) + ).then((rows) => rows[0] ?? null); + if (agentPolicy && agentPolicy.hardStopEnabled && agentPolicy.amount > 0) { + const observed = await computeObservedAmount(db, agentPolicy); + if (observed >= agentPolicy.amount) { + return { + scopeType: "agent", + scopeId: agentId, + scopeName: agent.name, + reason: "Agent cannot start because its budget hard-stop is still exceeded." + }; + } + } + const candidateProjectId = context?.projectId ?? null; + if (!candidateProjectId) return null; + const project = await db.select({ + id: projects.id, + name: projects.name, + companyId: projects.companyId, + pauseReason: projects.pauseReason, + pausedAt: projects.pausedAt + }).from(projects).where(eq(projects.id, candidateProjectId)).then((rows) => rows[0] ?? null); + if (!project || project.companyId !== companyId) return null; + const projectPolicy = await db.select().from(budgetPolicies).where( + and( + eq(budgetPolicies.companyId, companyId), + eq(budgetPolicies.scopeType, "project"), + eq(budgetPolicies.scopeId, project.id), + eq(budgetPolicies.isActive, true), + eq(budgetPolicies.metric, "billed_cents") + ) + ).then((rows) => rows[0] ?? null); + if (projectPolicy && projectPolicy.hardStopEnabled && projectPolicy.amount > 0) { + const observed = await computeObservedAmount(db, projectPolicy); + if (observed >= projectPolicy.amount) { + return { + scopeType: "project", + scopeId: project.id, + scopeName: project.name, + reason: "Project cannot start work because its budget hard-stop is still exceeded." + }; + } + } + if (!project.pausedAt || project.pauseReason !== "budget") return null; + return { + scopeType: "project", + scopeId: project.id, + scopeName: project.name, + reason: "Project is paused because its budget hard-stop was reached." + }; + }, + resolveIncident: async (companyId, incidentId, input, actorUserId) => { + const incident = await db.select().from(budgetIncidents).where(eq(budgetIncidents.id, incidentId)).then((rows) => rows[0] ?? null); + if (!incident) throw notFound("Budget incident not found"); + if (incident.companyId !== companyId) throw notFound("Budget incident not found"); + const policy = await getPolicyRow(incident.policyId); + if (input.action === "raise_budget_and_resume") { + const nextAmount = Math.max(0, Math.floor(input.amount ?? 0)); + const currentObserved = await computeObservedAmount(db, policy); + if (nextAmount <= currentObserved) { + throw unprocessable("New budget must exceed current observed spend"); + } + const now2 = /* @__PURE__ */ new Date(); + await db.update(budgetPolicies).set({ + amount: nextAmount, + isActive: true, + updatedByUserId: actorUserId, + updatedAt: now2 + }).where(eq(budgetPolicies.id, policy.id)); + if (policy.scopeType === "company" && policy.windowKind === "calendar_month_utc") { + await db.update(companies).set({ budgetMonthlyCents: nextAmount, updatedAt: now2 }).where(eq(companies.id, policy.scopeId)); + } + if (policy.scopeType === "agent" && policy.windowKind === "calendar_month_utc") { + await db.update(agents).set({ budgetMonthlyCents: nextAmount, updatedAt: now2 }).where(eq(agents.id, policy.scopeId)); + } + await resumeScopeFromBudget(policy); + await db.update(budgetIncidents).set({ + status: "resolved", + resolvedAt: now2, + updatedAt: now2 + }).where(and(eq(budgetIncidents.policyId, policy.id), eq(budgetIncidents.status, "open"))); + await markApprovalStatus(db, incident.approvalId ?? null, "approved", input.decisionNote, actorUserId); + } else { + await db.update(budgetIncidents).set({ + status: "dismissed", + resolvedAt: /* @__PURE__ */ new Date(), + updatedAt: /* @__PURE__ */ new Date() + }).where(eq(budgetIncidents.id, incident.id)); + await markApprovalStatus(db, incident.approvalId ?? null, "rejected", input.decisionNote, actorUserId); + } + await logActivity(db, { + companyId: incident.companyId, + actorType: "user", + actorId: actorUserId, + action: "budget.incident_resolved", + entityType: "budget_incident", + entityId: incident.id, + details: { + action: input.action, + amount: input.amount ?? null, + scopeType: incident.scopeType, + scopeId: incident.scopeId + } + }); + const [updated] = await hydrateIncidentRows([{ + ...incident, + status: input.action === "raise_budget_and_resume" ? "resolved" : "dismissed", + resolvedAt: /* @__PURE__ */ new Date(), + updatedAt: /* @__PURE__ */ new Date() + }]); + return updated; + } + }; +} + +// server/src/services/hire-hook.ts +init_drizzle_orm(); +init_src2(); +var HIRE_APPROVED_MESSAGE = "Tell your user that your hire was approved, now they should assign you a task in Taskcore or ask you to create issues."; +async function notifyHireApproved(db, input) { + const { companyId, agentId, source, sourceId } = input; + const approvedAt = input.approvedAt ?? /* @__PURE__ */ new Date(); + const row = await db.select().from(agents).where(and(eq(agents.id, agentId), eq(agents.companyId, companyId))).then((rows) => rows[0] ?? null); + if (!row) { + logger.warn({ companyId, agentId, source, sourceId }, "hire hook: agent not found in company, skipping"); + return; + } + const adapterType = row.adapterType ?? "process"; + const adapter = findActiveServerAdapter(adapterType); + const onHireApproved = adapter?.onHireApproved; + if (!onHireApproved) { + return; + } + const payload2 = { + companyId, + agentId, + agentName: row.name, + adapterType, + source, + sourceId, + approvedAt: approvedAt.toISOString(), + message: HIRE_APPROVED_MESSAGE + }; + const adapterConfig = typeof row.adapterConfig === "object" && row.adapterConfig !== null && !Array.isArray(row.adapterConfig) ? row.adapterConfig : {}; + try { + const result = await onHireApproved(payload2, adapterConfig); + if (result.ok) { + await logActivity(db, { + companyId, + actorType: "system", + actorId: "hire_hook", + action: "hire_hook.succeeded", + entityType: "agent", + entityId: agentId, + details: { source, sourceId, adapterType } + }); + return; + } + logger.warn( + { companyId, agentId, adapterType, source, sourceId, error: result.error, detail: result.detail }, + "hire hook: adapter returned failure" + ); + await logActivity(db, { + companyId, + actorType: "system", + actorId: "hire_hook", + action: "hire_hook.failed", + entityType: "agent", + entityId: agentId, + details: { source, sourceId, adapterType, error: result.error, detail: result.detail } + }); + } catch (err) { + logger.error( + { err, companyId, agentId, adapterType, source, sourceId }, + "hire hook: adapter threw" + ); + await logActivity(db, { + companyId, + actorType: "system", + actorId: "hire_hook", + action: "hire_hook.error", + entityType: "agent", + entityId: agentId, + details: { + source, + sourceId, + adapterType, + error: err instanceof Error ? err.message : String(err) + } + }); + } +} + +// server/src/services/approvals.ts +function approvalService(db) { + const agentsSvc = agentService(db); + const budgets = budgetService(db); + const instanceSettings2 = instanceSettingsService(db); + const canResolveStatuses = /* @__PURE__ */ new Set(["pending", "revision_requested"]); + const resolvableStatuses = Array.from(canResolveStatuses); + function redactApprovalComment(comment, censorUsernameInLogs) { + return { + ...comment, + body: redactCurrentUserText(comment.body, { enabled: censorUsernameInLogs }) + }; + } + async function getExistingApproval(id) { + const existing = await db.select().from(approvals).where(eq(approvals.id, id)).then((rows) => rows[0] ?? null); + if (!existing) throw notFound("Approval not found"); + return existing; + } + async function resolveApproval(id, targetStatus, decidedByUserId, decisionNote) { + const existing = await getExistingApproval(id); + if (!canResolveStatuses.has(existing.status)) { + if (existing.status === targetStatus) { + return { approval: existing, applied: false }; + } + throw unprocessable( + `Only pending or revision requested approvals can be ${targetStatus === "approved" ? "approved" : "rejected"}` + ); + } + const now2 = /* @__PURE__ */ new Date(); + const updated = await db.update(approvals).set({ + status: targetStatus, + decidedByUserId, + decisionNote: decisionNote ?? null, + decidedAt: now2, + updatedAt: now2 + }).where(and(eq(approvals.id, id), inArray(approvals.status, resolvableStatuses))).returning().then((rows) => rows[0] ?? null); + if (updated) { + return { approval: updated, applied: true }; + } + const latest = await getExistingApproval(id); + if (latest.status === targetStatus) { + return { approval: latest, applied: false }; + } + throw unprocessable( + `Only pending or revision requested approvals can be ${targetStatus === "approved" ? "approved" : "rejected"}` + ); + } + return { + list: (companyId, status) => { + const conditions = [eq(approvals.companyId, companyId)]; + if (status) conditions.push(eq(approvals.status, status)); + return db.select().from(approvals).where(and(...conditions)); + }, + getById: (id) => db.select().from(approvals).where(eq(approvals.id, id)).then((rows) => rows[0] ?? null), + create: (companyId, data2) => db.insert(approvals).values({ ...data2, companyId }).returning().then((rows) => rows[0]), + approve: async (id, decidedByUserId, decisionNote) => { + const { approval: updated, applied } = await resolveApproval( + id, + "approved", + decidedByUserId, + decisionNote + ); + let hireApprovedAgentId = null; + const now2 = /* @__PURE__ */ new Date(); + if (applied && updated.type === "hire_agent") { + const payload2 = updated.payload; + const payloadAgentId = typeof payload2.agentId === "string" ? payload2.agentId : null; + if (payloadAgentId) { + await agentsSvc.activatePendingApproval(payloadAgentId); + hireApprovedAgentId = payloadAgentId; + } else { + const created = await agentsSvc.create(updated.companyId, { + name: String(payload2.name ?? "New Agent"), + role: String(payload2.role ?? "general"), + title: typeof payload2.title === "string" ? payload2.title : null, + reportsTo: typeof payload2.reportsTo === "string" ? payload2.reportsTo : null, + capabilities: typeof payload2.capabilities === "string" ? payload2.capabilities : null, + adapterType: String(payload2.adapterType ?? "process"), + adapterConfig: typeof payload2.adapterConfig === "object" && payload2.adapterConfig !== null ? payload2.adapterConfig : {}, + budgetMonthlyCents: typeof payload2.budgetMonthlyCents === "number" ? payload2.budgetMonthlyCents : 0, + metadata: typeof payload2.metadata === "object" && payload2.metadata !== null ? payload2.metadata : null, + status: "idle", + spentMonthlyCents: 0, + permissions: void 0, + lastHeartbeatAt: null + }); + hireApprovedAgentId = created?.id ?? null; + } + if (hireApprovedAgentId) { + const budgetMonthlyCents = typeof payload2.budgetMonthlyCents === "number" ? payload2.budgetMonthlyCents : 0; + if (budgetMonthlyCents > 0) { + await budgets.upsertPolicy( + updated.companyId, + { + scopeType: "agent", + scopeId: hireApprovedAgentId, + amount: budgetMonthlyCents, + windowKind: "calendar_month_utc" + }, + decidedByUserId + ); + } + void notifyHireApproved(db, { + companyId: updated.companyId, + agentId: hireApprovedAgentId, + source: "approval", + sourceId: id, + approvedAt: now2 + }).catch(() => { + }); + } + } + return { approval: updated, applied }; + }, + reject: async (id, decidedByUserId, decisionNote) => { + const { approval: updated, applied } = await resolveApproval( + id, + "rejected", + decidedByUserId, + decisionNote + ); + if (applied && updated.type === "hire_agent") { + const payload2 = updated.payload; + const payloadAgentId = typeof payload2.agentId === "string" ? payload2.agentId : null; + if (payloadAgentId) { + await agentsSvc.terminate(payloadAgentId); + } + } + return { approval: updated, applied }; + }, + requestRevision: async (id, decidedByUserId, decisionNote) => { + const existing = await getExistingApproval(id); + if (existing.status !== "pending") { + throw unprocessable("Only pending approvals can request revision"); + } + const now2 = /* @__PURE__ */ new Date(); + return db.update(approvals).set({ + status: "revision_requested", + decidedByUserId, + decisionNote: decisionNote ?? null, + decidedAt: now2, + updatedAt: now2 + }).where(eq(approvals.id, id)).returning().then((rows) => rows[0]); + }, + resubmit: async (id, payload2) => { + const existing = await getExistingApproval(id); + if (existing.status !== "revision_requested") { + throw unprocessable("Only revision requested approvals can be resubmitted"); + } + const now2 = /* @__PURE__ */ new Date(); + return db.update(approvals).set({ + status: "pending", + payload: payload2 ?? existing.payload, + decisionNote: null, + decidedByUserId: null, + decidedAt: null, + updatedAt: now2 + }).where(eq(approvals.id, id)).returning().then((rows) => rows[0]); + }, + listComments: async (approvalId) => { + const existing = await getExistingApproval(approvalId); + const { censorUsernameInLogs } = await instanceSettings2.getGeneral(); + return db.select().from(approvalComments).where( + and( + eq(approvalComments.approvalId, approvalId), + eq(approvalComments.companyId, existing.companyId) + ) + ).orderBy(asc(approvalComments.createdAt)).then((comments) => comments.map((comment) => redactApprovalComment(comment, censorUsernameInLogs))); + }, + addComment: async (approvalId, body, actor) => { + const existing = await getExistingApproval(approvalId); + const currentUserRedactionOptions = { + enabled: (await instanceSettings2.getGeneral()).censorUsernameInLogs + }; + const redactedBody = redactCurrentUserText(body, currentUserRedactionOptions); + return db.insert(approvalComments).values({ + companyId: existing.companyId, + approvalId, + authorAgentId: actor.agentId ?? null, + authorUserId: actor.userId ?? null, + body: redactedBody + }).returning().then((rows) => redactApprovalComment(rows[0], currentUserRedactionOptions.enabled)); + } + }; +} + +// server/src/services/routines.ts +init_drizzle_orm(); +init_src2(); +import crypto4 from "node:crypto"; + +// server/src/services/cron.ts +var FIELD_SPECS = [ + { min: 0, max: 59, name: "minute" }, + { min: 0, max: 23, name: "hour" }, + { min: 1, max: 31, name: "day of month" }, + { min: 1, max: 12, name: "month" }, + { min: 0, max: 6, name: "day of week" } +]; +function parseField(token, spec) { + const values2 = /* @__PURE__ */ new Set(); + const parts = token.split(","); + for (const part of parts) { + const trimmed = part.trim(); + if (trimmed === "") { + throw new Error(`Empty element in cron ${spec.name} field`); + } + const slashIdx = trimmed.indexOf("/"); + if (slashIdx !== -1) { + const base = trimmed.slice(0, slashIdx); + const stepStr = trimmed.slice(slashIdx + 1); + const step = parseInt(stepStr, 10); + if (isNaN(step) || step <= 0) { + throw new Error( + `Invalid step "${stepStr}" in cron ${spec.name} field` + ); + } + let rangeStart = spec.min; + let rangeEnd = spec.max; + if (base === "*") { + } else if (base.includes("-")) { + const [a5, b6] = base.split("-").map((s5) => parseInt(s5, 10)); + if (isNaN(a5) || isNaN(b6)) { + throw new Error( + `Invalid range "${base}" in cron ${spec.name} field` + ); + } + rangeStart = a5; + rangeEnd = b6; + } else { + const start = parseInt(base, 10); + if (isNaN(start)) { + throw new Error( + `Invalid start "${base}" in cron ${spec.name} field` + ); + } + rangeStart = start; + } + validateBounds(rangeStart, spec); + validateBounds(rangeEnd, spec); + for (let i5 = rangeStart; i5 <= rangeEnd; i5 += step) { + values2.add(i5); + } + continue; + } + if (trimmed.includes("-")) { + const [aStr, bStr] = trimmed.split("-"); + const a5 = parseInt(aStr, 10); + const b6 = parseInt(bStr, 10); + if (isNaN(a5) || isNaN(b6)) { + throw new Error( + `Invalid range "${trimmed}" in cron ${spec.name} field` + ); + } + validateBounds(a5, spec); + validateBounds(b6, spec); + if (a5 > b6) { + throw new Error( + `Invalid range ${a5}-${b6} in cron ${spec.name} field (start > end)` + ); + } + for (let i5 = a5; i5 <= b6; i5++) { + values2.add(i5); + } + continue; + } + if (trimmed === "*") { + for (let i5 = spec.min; i5 <= spec.max; i5++) { + values2.add(i5); + } + continue; + } + const val = parseInt(trimmed, 10); + if (isNaN(val)) { + throw new Error( + `Invalid value "${trimmed}" in cron ${spec.name} field` + ); + } + validateBounds(val, spec); + values2.add(val); + } + if (values2.size === 0) { + throw new Error(`Empty result for cron ${spec.name} field`); + } + return [...values2].sort((a5, b6) => a5 - b6); +} +function validateBounds(value, spec) { + if (value < spec.min || value > spec.max) { + throw new Error( + `Value ${value} out of range [${spec.min}\u2013${spec.max}] for cron ${spec.name} field` + ); + } +} +function parseCron(expression) { + const trimmed = expression.trim(); + if (!trimmed) { + throw new Error("Cron expression must not be empty"); + } + const tokens = trimmed.split(/\s+/); + if (tokens.length !== 5) { + throw new Error( + `Cron expression must have exactly 5 fields, got ${tokens.length}: "${trimmed}"` + ); + } + return { + minutes: parseField(tokens[0], FIELD_SPECS[0]), + hours: parseField(tokens[1], FIELD_SPECS[1]), + daysOfMonth: parseField(tokens[2], FIELD_SPECS[2]), + months: parseField(tokens[3], FIELD_SPECS[3]), + daysOfWeek: parseField(tokens[4], FIELD_SPECS[4]) + }; +} +function validateCron(expression) { + try { + parseCron(expression); + return null; + } catch (err) { + return err instanceof Error ? err.message : String(err); + } +} +function nextCronTick(cron, after) { + const d5 = new Date(after.getTime()); + d5.setUTCSeconds(0, 0); + d5.setUTCMinutes(d5.getUTCMinutes() + 1); + const MAX_CRON_SEARCH_YEARS = 4; + const maxIterations = MAX_CRON_SEARCH_YEARS * 366 * 24 * 60; + for (let i5 = 0; i5 < maxIterations; i5++) { + const month = d5.getUTCMonth() + 1; + const dayOfMonth = d5.getUTCDate(); + const dayOfWeek = d5.getUTCDay(); + const hour2 = d5.getUTCHours(); + const minute2 = d5.getUTCMinutes(); + if (!cron.months.includes(month)) { + advanceToNextMonth(d5, cron.months); + continue; + } + if (!cron.daysOfMonth.includes(dayOfMonth) || !cron.daysOfWeek.includes(dayOfWeek)) { + d5.setUTCDate(d5.getUTCDate() + 1); + d5.setUTCHours(0, 0, 0, 0); + continue; + } + if (!cron.hours.includes(hour2)) { + const nextHour = findNext(cron.hours, hour2); + if (nextHour !== null) { + d5.setUTCHours(nextHour, 0, 0, 0); + } else { + d5.setUTCDate(d5.getUTCDate() + 1); + d5.setUTCHours(0, 0, 0, 0); + } + continue; + } + if (!cron.minutes.includes(minute2)) { + const nextMin = findNext(cron.minutes, minute2); + if (nextMin !== null) { + d5.setUTCMinutes(nextMin, 0, 0); + } else { + d5.setUTCHours(d5.getUTCHours() + 1, 0, 0, 0); + } + continue; + } + return new Date(d5.getTime()); + } + return null; +} +function findNext(sortedValues, current) { + for (const v5 of sortedValues) { + if (v5 > current) return v5; + } + return null; +} +function advanceToNextMonth(d5, months2) { + let year3 = d5.getUTCFullYear(); + let month = d5.getUTCMonth() + 1; + for (let i5 = 0; i5 < 48; i5++) { + month++; + if (month > 12) { + month = 1; + year3++; + } + if (months2.includes(month)) { + d5.setUTCFullYear(year3, month - 1, 1); + d5.setUTCHours(0, 0, 0, 0); + return; + } + } +} + +// server/src/services/heartbeat.ts +init_drizzle_orm(); +init_src2(); +import fs32 from "node:fs/promises"; +import path39 from "node:path"; +import { execFile as execFileCallback } from "node:child_process"; +import { promisify as promisify5 } from "node:util"; + +// server/src/services/costs.ts +init_drizzle_orm(); +init_src2(); +var METERED_BILLING_TYPE = "metered_api"; +var SUBSCRIPTION_BILLING_TYPES = ["subscription_included", "subscription_overage"]; +function currentUtcMonthWindow2(now2 = /* @__PURE__ */ new Date()) { + const year3 = now2.getUTCFullYear(); + const month = now2.getUTCMonth(); + return { + start: new Date(Date.UTC(year3, month, 1, 0, 0, 0, 0)), + end: new Date(Date.UTC(year3, month + 1, 1, 0, 0, 0, 0)) + }; +} +async function getMonthlySpendTotal(db, scope) { + const { start, end } = currentUtcMonthWindow2(); + const conditions = [ + eq(costEvents.companyId, scope.companyId), + gte(costEvents.occurredAt, start), + lt(costEvents.occurredAt, end) + ]; + if (scope.agentId) { + conditions.push(eq(costEvents.agentId, scope.agentId)); + } + const [row] = await db.select({ + total: sql`coalesce(sum(${costEvents.costCents}), 0)::int` + }).from(costEvents).where(and(...conditions)); + return Number(row?.total ?? 0); +} +function costService(db, budgetHooks = {}) { + const budgets = budgetService(db, budgetHooks); + return { + createEvent: async (companyId, data2) => { + const agent = await db.select().from(agents).where(eq(agents.id, data2.agentId)).then((rows) => rows[0] ?? null); + if (!agent) throw notFound("Agent not found"); + if (agent.companyId !== companyId) { + throw unprocessable("Agent does not belong to company"); + } + const event = await db.insert(costEvents).values({ + ...data2, + companyId, + biller: data2.biller ?? data2.provider, + billingType: data2.billingType ?? "unknown", + cachedInputTokens: data2.cachedInputTokens ?? 0 + }).returning().then((rows) => rows[0]); + const [agentMonthSpend, companyMonthSpend] = await Promise.all([ + getMonthlySpendTotal(db, { companyId, agentId: event.agentId }), + getMonthlySpendTotal(db, { companyId }) + ]); + await db.update(agents).set({ + spentMonthlyCents: agentMonthSpend, + updatedAt: /* @__PURE__ */ new Date() + }).where(eq(agents.id, event.agentId)); + await db.update(companies).set({ + spentMonthlyCents: companyMonthSpend, + updatedAt: /* @__PURE__ */ new Date() + }).where(eq(companies.id, companyId)); + await budgets.evaluateCostEvent(event); + return event; + }, + summary: async (companyId, range2) => { + const company = await db.select().from(companies).where(eq(companies.id, companyId)).then((rows) => rows[0] ?? null); + if (!company) throw notFound("Company not found"); + const conditions = [eq(costEvents.companyId, companyId)]; + if (range2?.from) conditions.push(gte(costEvents.occurredAt, range2.from)); + if (range2?.to) conditions.push(lte(costEvents.occurredAt, range2.to)); + const [{ total }] = await db.select({ + total: sql`coalesce(sum(${costEvents.costCents}), 0)::int` + }).from(costEvents).where(and(...conditions)); + const spendCents = Number(total); + const utilization = company.budgetMonthlyCents > 0 ? spendCents / company.budgetMonthlyCents * 100 : 0; + return { + companyId, + spendCents, + budgetCents: company.budgetMonthlyCents, + utilizationPercent: Number(utilization.toFixed(2)) + }; + }, + byAgent: async (companyId, range2) => { + const conditions = [eq(costEvents.companyId, companyId)]; + if (range2?.from) conditions.push(gte(costEvents.occurredAt, range2.from)); + if (range2?.to) conditions.push(lte(costEvents.occurredAt, range2.to)); + return db.select({ + agentId: costEvents.agentId, + agentName: agents.name, + agentStatus: agents.status, + costCents: sql`coalesce(sum(${costEvents.costCents}), 0)::int`, + inputTokens: sql`coalesce(sum(${costEvents.inputTokens}), 0)::int`, + cachedInputTokens: sql`coalesce(sum(${costEvents.cachedInputTokens}), 0)::int`, + outputTokens: sql`coalesce(sum(${costEvents.outputTokens}), 0)::int`, + apiRunCount: sql`count(distinct case when ${costEvents.billingType} = ${METERED_BILLING_TYPE} then ${costEvents.heartbeatRunId} end)::int`, + subscriptionRunCount: sql`count(distinct case when ${costEvents.billingType} in (${sql.join(SUBSCRIPTION_BILLING_TYPES.map((value) => sql`${value}`), sql`, `)}) then ${costEvents.heartbeatRunId} end)::int`, + subscriptionCachedInputTokens: sql`coalesce(sum(case when ${costEvents.billingType} in (${sql.join(SUBSCRIPTION_BILLING_TYPES.map((value) => sql`${value}`), sql`, `)}) then ${costEvents.cachedInputTokens} else 0 end), 0)::int`, + subscriptionInputTokens: sql`coalesce(sum(case when ${costEvents.billingType} in (${sql.join(SUBSCRIPTION_BILLING_TYPES.map((value) => sql`${value}`), sql`, `)}) then ${costEvents.inputTokens} else 0 end), 0)::int`, + subscriptionOutputTokens: sql`coalesce(sum(case when ${costEvents.billingType} in (${sql.join(SUBSCRIPTION_BILLING_TYPES.map((value) => sql`${value}`), sql`, `)}) then ${costEvents.outputTokens} else 0 end), 0)::int` + }).from(costEvents).leftJoin(agents, eq(costEvents.agentId, agents.id)).where(and(...conditions)).groupBy(costEvents.agentId, agents.name, agents.status).orderBy(desc(sql`coalesce(sum(${costEvents.costCents}), 0)::int`)); + }, + byProvider: async (companyId, range2) => { + const conditions = [eq(costEvents.companyId, companyId)]; + if (range2?.from) conditions.push(gte(costEvents.occurredAt, range2.from)); + if (range2?.to) conditions.push(lte(costEvents.occurredAt, range2.to)); + return db.select({ + provider: costEvents.provider, + biller: costEvents.biller, + billingType: costEvents.billingType, + model: costEvents.model, + costCents: sql`coalesce(sum(${costEvents.costCents}), 0)::int`, + inputTokens: sql`coalesce(sum(${costEvents.inputTokens}), 0)::int`, + cachedInputTokens: sql`coalesce(sum(${costEvents.cachedInputTokens}), 0)::int`, + outputTokens: sql`coalesce(sum(${costEvents.outputTokens}), 0)::int`, + apiRunCount: sql`count(distinct case when ${costEvents.billingType} = ${METERED_BILLING_TYPE} then ${costEvents.heartbeatRunId} end)::int`, + subscriptionRunCount: sql`count(distinct case when ${costEvents.billingType} in (${sql.join(SUBSCRIPTION_BILLING_TYPES.map((value) => sql`${value}`), sql`, `)}) then ${costEvents.heartbeatRunId} end)::int`, + subscriptionCachedInputTokens: sql`coalesce(sum(case when ${costEvents.billingType} in (${sql.join(SUBSCRIPTION_BILLING_TYPES.map((value) => sql`${value}`), sql`, `)}) then ${costEvents.cachedInputTokens} else 0 end), 0)::int`, + subscriptionInputTokens: sql`coalesce(sum(case when ${costEvents.billingType} in (${sql.join(SUBSCRIPTION_BILLING_TYPES.map((value) => sql`${value}`), sql`, `)}) then ${costEvents.inputTokens} else 0 end), 0)::int`, + subscriptionOutputTokens: sql`coalesce(sum(case when ${costEvents.billingType} in (${sql.join(SUBSCRIPTION_BILLING_TYPES.map((value) => sql`${value}`), sql`, `)}) then ${costEvents.outputTokens} else 0 end), 0)::int` + }).from(costEvents).where(and(...conditions)).groupBy(costEvents.provider, costEvents.biller, costEvents.billingType, costEvents.model).orderBy(desc(sql`coalesce(sum(${costEvents.costCents}), 0)::int`)); + }, + byBiller: async (companyId, range2) => { + const conditions = [eq(costEvents.companyId, companyId)]; + if (range2?.from) conditions.push(gte(costEvents.occurredAt, range2.from)); + if (range2?.to) conditions.push(lte(costEvents.occurredAt, range2.to)); + return db.select({ + biller: costEvents.biller, + costCents: sql`coalesce(sum(${costEvents.costCents}), 0)::int`, + inputTokens: sql`coalesce(sum(${costEvents.inputTokens}), 0)::int`, + cachedInputTokens: sql`coalesce(sum(${costEvents.cachedInputTokens}), 0)::int`, + outputTokens: sql`coalesce(sum(${costEvents.outputTokens}), 0)::int`, + apiRunCount: sql`count(distinct case when ${costEvents.billingType} = ${METERED_BILLING_TYPE} then ${costEvents.heartbeatRunId} end)::int`, + subscriptionRunCount: sql`count(distinct case when ${costEvents.billingType} in (${sql.join(SUBSCRIPTION_BILLING_TYPES.map((value) => sql`${value}`), sql`, `)}) then ${costEvents.heartbeatRunId} end)::int`, + subscriptionCachedInputTokens: sql`coalesce(sum(case when ${costEvents.billingType} in (${sql.join(SUBSCRIPTION_BILLING_TYPES.map((value) => sql`${value}`), sql`, `)}) then ${costEvents.cachedInputTokens} else 0 end), 0)::int`, + subscriptionInputTokens: sql`coalesce(sum(case when ${costEvents.billingType} in (${sql.join(SUBSCRIPTION_BILLING_TYPES.map((value) => sql`${value}`), sql`, `)}) then ${costEvents.inputTokens} else 0 end), 0)::int`, + subscriptionOutputTokens: sql`coalesce(sum(case when ${costEvents.billingType} in (${sql.join(SUBSCRIPTION_BILLING_TYPES.map((value) => sql`${value}`), sql`, `)}) then ${costEvents.outputTokens} else 0 end), 0)::int`, + providerCount: sql`count(distinct ${costEvents.provider})::int`, + modelCount: sql`count(distinct ${costEvents.model})::int` + }).from(costEvents).where(and(...conditions)).groupBy(costEvents.biller).orderBy(desc(sql`coalesce(sum(${costEvents.costCents}), 0)::int`)); + }, + /** + * aggregates cost_events by provider for each of three rolling windows: + * last 5 hours, last 24 hours, last 7 days. + * purely internal consumption data, no external rate-limit sources. + */ + windowSpend: async (companyId) => { + const windows = [ + { label: "5h", hours: 5 }, + { label: "24h", hours: 24 }, + { label: "7d", hours: 168 } + ]; + const results = await Promise.all( + windows.map(async ({ label, hours }) => { + const since = new Date(Date.now() - hours * 60 * 60 * 1e3); + const rows = await db.select({ + provider: costEvents.provider, + biller: sql`case when count(distinct ${costEvents.biller}) = 1 then min(${costEvents.biller}) else 'mixed' end`, + costCents: sql`coalesce(sum(${costEvents.costCents}), 0)::int`, + inputTokens: sql`coalesce(sum(${costEvents.inputTokens}), 0)::int`, + cachedInputTokens: sql`coalesce(sum(${costEvents.cachedInputTokens}), 0)::int`, + outputTokens: sql`coalesce(sum(${costEvents.outputTokens}), 0)::int` + }).from(costEvents).where( + and( + eq(costEvents.companyId, companyId), + gte(costEvents.occurredAt, since) + ) + ).groupBy(costEvents.provider).orderBy(desc(sql`coalesce(sum(${costEvents.costCents}), 0)::int`)); + return rows.map((row) => ({ + provider: row.provider, + biller: row.biller, + window: label, + windowHours: hours, + costCents: row.costCents, + inputTokens: row.inputTokens, + cachedInputTokens: row.cachedInputTokens, + outputTokens: row.outputTokens + })); + }) + ); + return results.flat(); + }, + byAgentModel: async (companyId, range2) => { + const conditions = [eq(costEvents.companyId, companyId)]; + if (range2?.from) conditions.push(gte(costEvents.occurredAt, range2.from)); + if (range2?.to) conditions.push(lte(costEvents.occurredAt, range2.to)); + return db.select({ + agentId: costEvents.agentId, + agentName: agents.name, + provider: costEvents.provider, + biller: costEvents.biller, + billingType: costEvents.billingType, + model: costEvents.model, + costCents: sql`coalesce(sum(${costEvents.costCents}), 0)::int`, + inputTokens: sql`coalesce(sum(${costEvents.inputTokens}), 0)::int`, + cachedInputTokens: sql`coalesce(sum(${costEvents.cachedInputTokens}), 0)::int`, + outputTokens: sql`coalesce(sum(${costEvents.outputTokens}), 0)::int` + }).from(costEvents).leftJoin(agents, eq(costEvents.agentId, agents.id)).where(and(...conditions)).groupBy( + costEvents.agentId, + agents.name, + costEvents.provider, + costEvents.biller, + costEvents.billingType, + costEvents.model + ).orderBy(costEvents.provider, costEvents.biller, costEvents.billingType, costEvents.model); + }, + byProject: async (companyId, range2) => { + const issueIdAsText = sql`${issues.id}::text`; + const runProjectLinks = db.selectDistinctOn([activityLog.runId, issues.projectId], { + runId: activityLog.runId, + projectId: issues.projectId + }).from(activityLog).innerJoin( + issues, + and( + eq(activityLog.entityType, "issue"), + eq(activityLog.entityId, issueIdAsText) + ) + ).where( + and( + eq(activityLog.companyId, companyId), + eq(issues.companyId, companyId), + isNotNull(activityLog.runId), + isNotNull(issues.projectId) + ) + ).orderBy(activityLog.runId, issues.projectId, desc(activityLog.createdAt)).as("run_project_links"); + const effectiveProjectId = sql`coalesce(${costEvents.projectId}, ${runProjectLinks.projectId})`; + const conditions = [eq(costEvents.companyId, companyId)]; + if (range2?.from) conditions.push(gte(costEvents.occurredAt, range2.from)); + if (range2?.to) conditions.push(lte(costEvents.occurredAt, range2.to)); + const costCentsExpr = sql`coalesce(sum(${costEvents.costCents}), 0)::int`; + return db.select({ + projectId: effectiveProjectId, + projectName: projects.name, + costCents: costCentsExpr, + inputTokens: sql`coalesce(sum(${costEvents.inputTokens}), 0)::int`, + cachedInputTokens: sql`coalesce(sum(${costEvents.cachedInputTokens}), 0)::int`, + outputTokens: sql`coalesce(sum(${costEvents.outputTokens}), 0)::int` + }).from(costEvents).leftJoin(runProjectLinks, eq(costEvents.heartbeatRunId, runProjectLinks.runId)).innerJoin(projects, sql`${projects.id} = ${effectiveProjectId}`).where(and(...conditions, sql`${effectiveProjectId} is not null`)).groupBy(effectiveProjectId, projects.name).orderBy(desc(costCentsExpr)); + } + }; +} + +// server/src/services/heartbeat-run-summary.ts +function truncateSummaryText(value, maxLength = 500) { + if (typeof value !== "string") return null; + return value.length > maxLength ? value.slice(0, maxLength) : value; +} +function readNumericField(record2, key) { + return key in record2 ? record2[key] ?? null : void 0; +} +function readCommentText(value) { + if (typeof value !== "string") return null; + const trimmed = value.trim(); + return trimmed.length > 0 ? trimmed : null; +} +function mergeHeartbeatRunResultJson(resultJson, summary) { + const normalizedSummary = readCommentText(summary); + const baseResult = resultJson && typeof resultJson === "object" && !Array.isArray(resultJson) ? resultJson : null; + if (!baseResult) { + return normalizedSummary ? { summary: normalizedSummary } : null; + } + if (!normalizedSummary) { + return baseResult; + } + if (readCommentText(baseResult.summary)) { + return baseResult; + } + return { + ...baseResult, + summary: normalizedSummary + }; +} +function summarizeHeartbeatRunResultJson(resultJson) { + if (!resultJson || typeof resultJson !== "object" || Array.isArray(resultJson)) { + return null; + } + const summary = {}; + const textFields = ["summary", "result", "message", "error"]; + for (const key of textFields) { + const value = truncateSummaryText(resultJson[key]); + if (value !== null) { + summary[key] = value; + } + } + const numericFieldAliases = ["total_cost_usd", "cost_usd", "costUsd"]; + for (const key of numericFieldAliases) { + const value = readNumericField(resultJson, key); + if (value !== void 0 && value !== null) { + summary[key] = value; + } + } + return Object.keys(summary).length > 0 ? summary : null; +} +function buildHeartbeatRunIssueComment(resultJson) { + if (!resultJson || typeof resultJson !== "object" || Array.isArray(resultJson)) { + return null; + } + return readCommentText(resultJson.summary) ?? readCommentText(resultJson.result) ?? readCommentText(resultJson.message) ?? null; +} + +// server/src/services/workspace-runtime.ts +init_src2(); +import { spawn as spawn4 } from "node:child_process"; +import { existsSync as existsSync3, lstatSync, readdirSync, readFileSync as readFileSync3, realpathSync } from "node:fs"; +import fs30 from "node:fs/promises"; +import net2 from "node:net"; +import { createHash as createHash12, randomUUID as randomUUID4 } from "node:crypto"; +import path37 from "node:path"; +import { setTimeout as delay2 } from "node:timers/promises"; +init_drizzle_orm(); + +// server/src/services/local-service-supervisor.ts +import { execFile as execFile3 } from "node:child_process"; +import { createHash as createHash11 } from "node:crypto"; +import fs28 from "node:fs/promises"; +import path35 from "node:path"; +import { setTimeout as delay } from "node:timers/promises"; +import { promisify as promisify3 } from "node:util"; +var execFileAsync3 = promisify3(execFile3); +function stableStringify2(value) { + if (Array.isArray(value)) { + return `[${value.map((entry) => stableStringify2(entry)).join(",")}]`; + } + if (value && typeof value === "object") { + const rec = value; + return `{${Object.keys(rec).sort().map((key) => `${JSON.stringify(key)}:${stableStringify2(rec[key])}`).join(",")}}`; + } + return JSON.stringify(value); +} +function sanitizeServiceKeySegment(value, fallback) { + const normalized = value.trim().toLowerCase().replace(/[^a-z0-9._-]+/g, "-").replace(/-+/g, "-").replace(/^-+|-+$/g, ""); + return normalized || fallback; +} +function getRuntimeServicesDir() { + return path35.resolve(resolveTaskcoreInstanceRoot(), "runtime-services"); +} +function getRuntimeServiceRegistryPath(serviceKey) { + return path35.resolve(getRuntimeServicesDir(), `${serviceKey}.json`); +} +function normalizeRegistryRecord(raw) { + if (!raw || typeof raw !== "object") return null; + const rec = raw; + if (rec.version !== 1 || typeof rec.serviceKey !== "string" || typeof rec.profileKind !== "string" || typeof rec.serviceName !== "string" || typeof rec.command !== "string" || typeof rec.cwd !== "string" || typeof rec.envFingerprint !== "string" || typeof rec.pid !== "number") { + return null; + } + return { + version: 1, + serviceKey: rec.serviceKey, + profileKind: rec.profileKind, + serviceName: rec.serviceName, + command: rec.command, + cwd: rec.cwd, + envFingerprint: rec.envFingerprint, + port: typeof rec.port === "number" ? rec.port : null, + url: typeof rec.url === "string" ? rec.url : null, + pid: rec.pid, + processGroupId: typeof rec.processGroupId === "number" ? rec.processGroupId : null, + provider: "local_process", + runtimeServiceId: typeof rec.runtimeServiceId === "string" ? rec.runtimeServiceId : null, + reuseKey: typeof rec.reuseKey === "string" ? rec.reuseKey : null, + startedAt: typeof rec.startedAt === "string" ? rec.startedAt : (/* @__PURE__ */ new Date()).toISOString(), + lastSeenAt: typeof rec.lastSeenAt === "string" ? rec.lastSeenAt : (/* @__PURE__ */ new Date()).toISOString(), + metadata: rec.metadata && typeof rec.metadata === "object" && !Array.isArray(rec.metadata) ? rec.metadata : null + }; +} +async function safeReadRegistryRecord(filePath) { + try { + const raw = JSON.parse(await fs28.readFile(filePath, "utf8")); + return normalizeRegistryRecord(raw); + } catch { + return null; + } +} +function createLocalServiceKey(input) { + const digest2 = createHash11("sha256").update( + stableStringify2({ + profileKind: input.profileKind, + serviceName: input.serviceName, + cwd: path35.resolve(input.cwd), + command: input.command, + envFingerprint: input.envFingerprint, + port: input.port, + scope: input.scope ?? null + }) + ).digest("hex").slice(0, 24); + return `${sanitizeServiceKeySegment(input.profileKind, "service")}-${sanitizeServiceKeySegment(input.serviceName, "service")}-${digest2}`; +} +async function writeLocalServiceRegistryRecord(record2) { + await fs28.mkdir(getRuntimeServicesDir(), { recursive: true }); + await fs28.writeFile( + getRuntimeServiceRegistryPath(record2.serviceKey), + `${JSON.stringify(record2, null, 2)} +`, + "utf8" + ); +} +async function removeLocalServiceRegistryRecord(serviceKey) { + await fs28.rm(getRuntimeServiceRegistryPath(serviceKey), { force: true }); +} +async function readLocalServiceRegistryRecord(serviceKey) { + return await safeReadRegistryRecord(getRuntimeServiceRegistryPath(serviceKey)); +} +function isPidAlive(pid) { + if (!Number.isInteger(pid) || pid <= 0) return false; + try { + process.kill(pid, 0); + return true; + } catch { + return false; + } +} +function isProcessGroupAlive(processGroupId) { + if (process.platform === "win32") return false; + if (typeof processGroupId !== "number" || !Number.isInteger(processGroupId) || processGroupId <= 0) return false; + try { + process.kill(-processGroupId, 0); + return true; + } catch { + return false; + } +} +async function isLikelyMatchingCommand(record2) { + if (process.platform === "win32") return true; + try { + const { stdout } = await execFileAsync3("ps", ["-o", "command=", "-p", String(record2.pid)]); + const commandLine = stdout.trim(); + if (!commandLine) return false; + const normalize2 = (value) => value.replace(/["']/g, "").replace(/\s+/g, " ").trim(); + const normalizedCommandLine = normalize2(commandLine); + const normalizedRecordedCommand = normalize2(record2.command); + return normalizedCommandLine.includes(normalizedRecordedCommand) || normalizedCommandLine.includes(record2.serviceName); + } catch { + return true; + } +} +async function findAdoptableLocalService(input) { + const record2 = await readLocalServiceRegistryRecord(input.serviceKey); + if (!record2) return null; + if (!isPidAlive(record2.pid)) { + await removeLocalServiceRegistryRecord(input.serviceKey); + return null; + } + if (!await isLikelyMatchingCommand(record2)) { + await removeLocalServiceRegistryRecord(input.serviceKey); + return null; + } + if (input.command && record2.command !== input.command) return null; + if (input.cwd && path35.resolve(record2.cwd) !== path35.resolve(input.cwd)) return null; + if (input.envFingerprint && record2.envFingerprint !== input.envFingerprint) return null; + if (input.port !== void 0 && input.port !== null && record2.port !== input.port) return null; + return record2; +} +async function touchLocalServiceRegistryRecord(serviceKey, patch) { + const existing = await readLocalServiceRegistryRecord(serviceKey); + if (!existing) return null; + const next = { + ...existing, + ...patch, + version: 1, + serviceKey, + lastSeenAt: patch?.lastSeenAt ?? (/* @__PURE__ */ new Date()).toISOString() + }; + await writeLocalServiceRegistryRecord(next); + return next; +} +async function terminateLocalService(record2, opts) { + const signal = opts?.signal ?? "SIGTERM"; + const targetProcessGroup = process.platform !== "win32" && record2.processGroupId && record2.processGroupId > 0; + try { + if (targetProcessGroup) { + process.kill(-record2.processGroupId, signal); + } else { + process.kill(record2.pid, signal); + } + } catch { + return; + } + const deadline = Date.now() + (opts?.forceAfterMs ?? 2e3); + while (Date.now() < deadline) { + const targetAlive = targetProcessGroup ? isProcessGroupAlive(record2.processGroupId) : isPidAlive(record2.pid); + if (!targetAlive) { + return; + } + await delay(100); + } + const stillAlive = targetProcessGroup ? isProcessGroupAlive(record2.processGroupId) : isPidAlive(record2.pid); + if (!stillAlive) return; + try { + if (targetProcessGroup) { + process.kill(-record2.processGroupId, "SIGKILL"); + } else { + process.kill(record2.pid, "SIGKILL"); + } + } catch { + } +} +async function readLocalServicePortOwner(port) { + if (!Number.isInteger(port) || port <= 0 || process.platform === "win32") return null; + try { + const { stdout } = await execFileAsync3("lsof", ["-nPiTCP", `:${port}`, "-sTCP:LISTEN", "-t"]); + const firstPid = stdout.split("\n").map((line3) => Number.parseInt(line3.trim(), 10)).find((value) => Number.isInteger(value) && value > 0); + return firstPid ?? null; + } catch { + return null; + } +} + +// server/src/services/execution-workspaces.ts +init_drizzle_orm(); +init_src2(); +import { execFile as execFile4 } from "node:child_process"; +import fs29 from "node:fs/promises"; +import path36 from "node:path"; +import { promisify as promisify4 } from "node:util"; +var execFileAsync4 = promisify4(execFile4); +var TERMINAL_ISSUE_STATUSES = /* @__PURE__ */ new Set(["done", "cancelled"]); +function isRecord4(value) { + return typeof value === "object" && value !== null && !Array.isArray(value); +} +function readNullableString(value) { + if (typeof value !== "string") return null; + const trimmed = value.trim(); + return trimmed.length > 0 ? trimmed : null; +} +function cloneRecord3(value) { + if (!isRecord4(value)) return null; + return { ...value }; +} +async function pathExists4(value) { + if (!value) return false; + try { + await fs29.access(value); + return true; + } catch { + return false; + } +} +async function runGit(args, cwd) { + return await execFileAsync4("git", ["-C", cwd, ...args], { cwd }); +} +async function inspectGitCloseReadiness(workspace) { + const warnings = []; + const workspacePath = readNullableString(workspace.providerRef) ?? readNullableString(workspace.cwd); + const createdByRuntime = workspace.metadata?.createdByRuntime === true; + const expectsGitInspection = workspace.providerType === "git_worktree" || Boolean(workspace.repoUrl || workspace.baseRef || workspace.branchName || workspacePath); + if (!expectsGitInspection) { + return { git: null, warnings }; + } + if (!workspacePath) { + warnings.push("Workspace has no local path, so Taskcore cannot inspect git status before close."); + return { git: null, warnings }; + } + if (!await pathExists4(workspacePath)) { + warnings.push(`Workspace path "${workspacePath}" does not exist, so Taskcore cannot inspect git status before close.`); + return { + git: { + repoRoot: null, + workspacePath, + branchName: workspace.branchName, + baseRef: workspace.baseRef, + hasDirtyTrackedFiles: false, + hasUntrackedFiles: false, + dirtyEntryCount: 0, + untrackedEntryCount: 0, + aheadCount: null, + behindCount: null, + isMergedIntoBase: null, + createdByRuntime + }, + warnings + }; + } + let repoRoot = null; + try { + repoRoot = (await runGit(["rev-parse", "--show-toplevel"], workspacePath)).stdout.trim() || null; + } catch (error50) { + warnings.push( + `Could not inspect git status for "${workspacePath}": ${error50 instanceof Error ? error50.message : String(error50)}` + ); + } + let branchName = workspace.branchName; + if (repoRoot && !branchName) { + try { + branchName = (await runGit(["rev-parse", "--abbrev-ref", "HEAD"], workspacePath)).stdout.trim() || null; + } catch { + branchName = workspace.branchName; + } + } + let dirtyEntryCount = 0; + let untrackedEntryCount = 0; + if (repoRoot) { + try { + const statusOutput = (await runGit(["status", "--porcelain=v1", "--untracked-files=all"], workspacePath)).stdout; + for (const line3 of statusOutput.split(/\r?\n/)) { + if (!line3) continue; + if (line3.startsWith("??")) { + untrackedEntryCount += 1; + continue; + } + dirtyEntryCount += 1; + } + } catch (error50) { + warnings.push( + `Could not read git working tree status for "${workspacePath}": ${error50 instanceof Error ? error50.message : String(error50)}` + ); + } + } + let aheadCount = null; + let behindCount = null; + let isMergedIntoBase = null; + const baseRef = workspace.baseRef; + if (repoRoot && baseRef) { + try { + const counts = (await runGit(["rev-list", "--left-right", "--count", `${baseRef}...HEAD`], workspacePath)).stdout.trim(); + const [behindRaw, aheadRaw] = counts.split(/\s+/); + behindCount = behindRaw ? Number.parseInt(behindRaw, 10) : 0; + aheadCount = aheadRaw ? Number.parseInt(aheadRaw, 10) : 0; + } catch (error50) { + warnings.push( + `Could not compare this workspace against ${baseRef}: ${error50 instanceof Error ? error50.message : String(error50)}` + ); + } + try { + await runGit(["merge-base", "--is-ancestor", "HEAD", baseRef], workspacePath); + isMergedIntoBase = true; + } catch (error50) { + const code = typeof error50 === "object" && error50 && "code" in error50 ? error50.code : null; + if (code === 1) isMergedIntoBase = false; + else { + warnings.push( + `Could not determine whether this workspace is merged into ${baseRef}: ${error50 instanceof Error ? error50.message : String(error50)}` + ); + } + } + } + return { + git: { + repoRoot, + workspacePath, + branchName, + baseRef, + hasDirtyTrackedFiles: dirtyEntryCount > 0, + hasUntrackedFiles: untrackedEntryCount > 0, + dirtyEntryCount, + untrackedEntryCount, + aheadCount, + behindCount, + isMergedIntoBase, + createdByRuntime + }, + warnings + }; +} +function readExecutionWorkspaceConfig(metadata) { + const raw = isRecord4(metadata?.config) ? metadata.config : null; + if (!raw) return null; + const config3 = { + provisionCommand: readNullableString(raw.provisionCommand), + teardownCommand: readNullableString(raw.teardownCommand), + cleanupCommand: readNullableString(raw.cleanupCommand), + workspaceRuntime: cloneRecord3(raw.workspaceRuntime), + desiredState: raw.desiredState === "running" || raw.desiredState === "stopped" ? raw.desiredState : null, + serviceStates: isRecord4(raw.serviceStates) ? Object.fromEntries( + Object.entries(raw.serviceStates).filter(([, state2]) => state2 === "running" || state2 === "stopped") + ) : null + }; + const hasConfig = Object.values(config3).some((value) => { + if (value === null) return false; + if (typeof value === "object") return Object.keys(value).length > 0; + return true; + }); + return hasConfig ? config3 : null; +} +function mergeExecutionWorkspaceConfig(metadata, patch) { + const nextMetadata = isRecord4(metadata) ? { ...metadata } : {}; + const current = readExecutionWorkspaceConfig(metadata) ?? { + provisionCommand: null, + teardownCommand: null, + cleanupCommand: null, + workspaceRuntime: null, + desiredState: null, + serviceStates: null + }; + if (patch === null) { + delete nextMetadata.config; + return Object.keys(nextMetadata).length > 0 ? nextMetadata : null; + } + const nextConfig = { + provisionCommand: patch.provisionCommand !== void 0 ? readNullableString(patch.provisionCommand) : current.provisionCommand, + teardownCommand: patch.teardownCommand !== void 0 ? readNullableString(patch.teardownCommand) : current.teardownCommand, + cleanupCommand: patch.cleanupCommand !== void 0 ? readNullableString(patch.cleanupCommand) : current.cleanupCommand, + workspaceRuntime: patch.workspaceRuntime !== void 0 ? cloneRecord3(patch.workspaceRuntime) : current.workspaceRuntime, + desiredState: patch.desiredState !== void 0 ? patch.desiredState === "running" || patch.desiredState === "stopped" ? patch.desiredState : null : current.desiredState, + serviceStates: patch.serviceStates !== void 0 && isRecord4(patch.serviceStates) ? Object.fromEntries( + Object.entries(patch.serviceStates).filter(([, state2]) => state2 === "running" || state2 === "stopped") + ) : patch.serviceStates !== void 0 ? null : current.serviceStates + }; + const hasConfig = Object.values(nextConfig).some((value) => { + if (value === null) return false; + if (typeof value === "object") return Object.keys(value).length > 0; + return true; + }); + if (hasConfig) { + nextMetadata.config = { + provisionCommand: nextConfig.provisionCommand, + teardownCommand: nextConfig.teardownCommand, + cleanupCommand: nextConfig.cleanupCommand, + workspaceRuntime: nextConfig.workspaceRuntime, + desiredState: nextConfig.desiredState, + serviceStates: nextConfig.serviceStates ?? null + }; + } else { + delete nextMetadata.config; + } + return Object.keys(nextMetadata).length > 0 ? nextMetadata : null; +} +function toRuntimeService2(row) { + return { + id: row.id, + companyId: row.companyId, + projectId: row.projectId ?? null, + projectWorkspaceId: row.projectWorkspaceId ?? null, + executionWorkspaceId: row.executionWorkspaceId ?? null, + issueId: row.issueId ?? null, + scopeType: row.scopeType, + scopeId: row.scopeId ?? null, + serviceName: row.serviceName, + status: row.status, + lifecycle: row.lifecycle, + reuseKey: row.reuseKey ?? null, + command: row.command ?? null, + cwd: row.cwd ?? null, + port: row.port ?? null, + url: row.url ?? null, + provider: row.provider, + providerRef: row.providerRef ?? null, + ownerAgentId: row.ownerAgentId ?? null, + startedByRunId: row.startedByRunId ?? null, + lastUsedAt: row.lastUsedAt, + startedAt: row.startedAt, + stoppedAt: row.stoppedAt ?? null, + stopPolicy: row.stopPolicy ?? null, + healthStatus: row.healthStatus, + createdAt: row.createdAt, + updatedAt: row.updatedAt + }; +} +function toExecutionWorkspace(row, runtimeServices = []) { + return { + id: row.id, + companyId: row.companyId, + projectId: row.projectId, + projectWorkspaceId: row.projectWorkspaceId ?? null, + sourceIssueId: row.sourceIssueId ?? null, + mode: row.mode, + strategyType: row.strategyType, + name: row.name, + status: row.status, + cwd: row.cwd ?? null, + repoUrl: row.repoUrl ?? null, + baseRef: row.baseRef ?? null, + branchName: row.branchName ?? null, + providerType: row.providerType, + providerRef: row.providerRef ?? null, + derivedFromExecutionWorkspaceId: row.derivedFromExecutionWorkspaceId ?? null, + lastUsedAt: row.lastUsedAt, + openedAt: row.openedAt, + closedAt: row.closedAt ?? null, + cleanupEligibleAt: row.cleanupEligibleAt ?? null, + cleanupReason: row.cleanupReason ?? null, + config: readExecutionWorkspaceConfig(row.metadata ?? null), + metadata: row.metadata ?? null, + runtimeServices, + createdAt: row.createdAt, + updatedAt: row.updatedAt + }; +} +function usesInheritedProjectRuntimeServices(row) { + if (row.mode !== "shared_workspace" || !row.projectWorkspaceId) return false; + return !readExecutionWorkspaceConfig(row.metadata ?? null)?.workspaceRuntime; +} +async function loadEffectiveRuntimeServicesByExecutionWorkspace(db, companyId, rows) { + const executionRuntimeServices = await listCurrentRuntimeServicesForExecutionWorkspaces( + db, + companyId, + rows.map((row) => row.id) + ); + const projectWorkspaceIds = rows.filter((row) => usesInheritedProjectRuntimeServices(row)).map((row) => row.projectWorkspaceId).filter((value) => Boolean(value)); + const projectRuntimeServices = await listCurrentRuntimeServicesForProjectWorkspaces( + db, + companyId, + [...new Set(projectWorkspaceIds)] + ); + return new Map( + rows.map((row) => [ + row.id, + usesInheritedProjectRuntimeServices(row) ? projectRuntimeServices.get(row.projectWorkspaceId) ?? [] : executionRuntimeServices.get(row.id) ?? [] + ]) + ); +} +function executionWorkspaceService(db) { + return { + list: async (companyId, filters) => { + const conditions = [eq(executionWorkspaces.companyId, companyId)]; + if (filters?.projectId) conditions.push(eq(executionWorkspaces.projectId, filters.projectId)); + if (filters?.projectWorkspaceId) { + conditions.push(eq(executionWorkspaces.projectWorkspaceId, filters.projectWorkspaceId)); + } + if (filters?.issueId) conditions.push(eq(executionWorkspaces.sourceIssueId, filters.issueId)); + if (filters?.status) { + const statuses = filters.status.split(",").map((value) => value.trim()).filter(Boolean); + if (statuses.length === 1) conditions.push(eq(executionWorkspaces.status, statuses[0])); + else if (statuses.length > 1) conditions.push(inArray(executionWorkspaces.status, statuses)); + } + if (filters?.reuseEligible) { + conditions.push(inArray(executionWorkspaces.status, ["active", "idle", "in_review"])); + } + const rows = await db.select().from(executionWorkspaces).where(and(...conditions)).orderBy(desc(executionWorkspaces.lastUsedAt), desc(executionWorkspaces.createdAt)); + const runtimeServicesByWorkspaceId = await loadEffectiveRuntimeServicesByExecutionWorkspace(db, companyId, rows); + return rows.map( + (row) => toExecutionWorkspace( + row, + (runtimeServicesByWorkspaceId.get(row.id) ?? []).map(toRuntimeService2) + ) + ); + }, + getById: async (id) => { + const row = await db.select().from(executionWorkspaces).where(eq(executionWorkspaces.id, id)).then((rows) => rows[0] ?? null); + if (!row) return null; + const runtimeServicesByWorkspaceId = await loadEffectiveRuntimeServicesByExecutionWorkspace(db, row.companyId, [row]); + return toExecutionWorkspace( + row, + (runtimeServicesByWorkspaceId.get(row.id) ?? []).map(toRuntimeService2) + ); + }, + getCloseReadiness: async (id) => { + const workspace = await db.select().from(executionWorkspaces).where(eq(executionWorkspaces.id, id)).then((rows) => rows[0] ?? null); + if (!workspace) return null; + const runtimeServicesByWorkspaceId = await loadEffectiveRuntimeServicesByExecutionWorkspace(db, workspace.companyId, [workspace]); + const runtimeServices = (runtimeServicesByWorkspaceId.get(workspace.id) ?? []).map(toRuntimeService2); + const linkedIssues = await db.select({ + id: issues.id, + identifier: issues.identifier, + title: issues.title, + status: issues.status + }).from(issues).where(and(eq(issues.companyId, workspace.companyId), eq(issues.executionWorkspaceId, workspace.id))); + const projectWorkspace = workspace.projectWorkspaceId ? await db.select({ + id: projectWorkspaces.id, + cwd: projectWorkspaces.cwd, + cleanupCommand: projectWorkspaces.cleanupCommand, + isPrimary: projectWorkspaces.isPrimary + }).from(projectWorkspaces).where( + and( + eq(projectWorkspaces.companyId, workspace.companyId), + eq(projectWorkspaces.id, workspace.projectWorkspaceId) + ) + ).then((rows) => rows[0] ?? null) : null; + const primaryProjectWorkspace = workspace.projectId ? await db.select({ + id: projectWorkspaces.id + }).from(projectWorkspaces).where( + and( + eq(projectWorkspaces.companyId, workspace.companyId), + eq(projectWorkspaces.projectId, workspace.projectId), + eq(projectWorkspaces.isPrimary, true) + ) + ).then((rows) => rows[0] ?? null) : null; + const projectPolicy = workspace.projectId ? await db.select({ + executionWorkspacePolicy: projects.executionWorkspacePolicy + }).from(projects).where(and(eq(projects.id, workspace.projectId), eq(projects.companyId, workspace.companyId))).then((rows) => parseProjectExecutionWorkspacePolicy(rows[0]?.executionWorkspacePolicy)) : null; + const executionWorkspace = toExecutionWorkspace(workspace, runtimeServices); + const config3 = readExecutionWorkspaceConfig(workspace.metadata ?? null); + const { git, warnings: gitWarnings } = await inspectGitCloseReadiness(executionWorkspace); + const warnings = [...gitWarnings]; + const blockingReasons = []; + const isSharedWorkspace = executionWorkspace.mode === "shared_workspace"; + const workspacePath = readNullableString(executionWorkspace.providerRef) ?? readNullableString(executionWorkspace.cwd); + const resolvedWorkspacePath = workspacePath ? path36.resolve(workspacePath) : null; + const resolvedPrimaryWorkspacePath = projectWorkspace?.cwd ? path36.resolve(projectWorkspace.cwd) : null; + const isProjectPrimaryWorkspace = workspace.projectWorkspaceId != null && workspace.projectWorkspaceId === primaryProjectWorkspace?.id && resolvedWorkspacePath != null && resolvedPrimaryWorkspacePath != null && resolvedWorkspacePath === resolvedPrimaryWorkspacePath; + const linkedIssueSummaries = linkedIssues.map((issue2) => ({ + ...issue2, + isTerminal: TERMINAL_ISSUE_STATUSES.has(issue2.status) + })); + const blockingIssues = linkedIssueSummaries.filter((issue2) => !issue2.isTerminal); + if (blockingIssues.length > 0) { + const linkedIssueMessage = blockingIssues.length === 1 ? "This workspace is still linked to an open issue." : `This workspace is still linked to ${blockingIssues.length} open issues.`; + if (isSharedWorkspace) { + warnings.push(`${linkedIssueMessage} Archiving it will detach this shared workspace session from those issues, but keep the underlying project workspace available.`); + } else { + blockingReasons.push(linkedIssueMessage); + } + } + if (isSharedWorkspace) { + warnings.push("This shared workspace session points at project workspace infrastructure. Archiving it only removes the session record."); + } + if (runtimeServices.some((service) => service.status !== "stopped")) { + warnings.push( + runtimeServices.length === 1 ? "Closing this workspace will stop 1 attached runtime service." : `Closing this workspace will stop ${runtimeServices.length} attached runtime services.` + ); + } + if (git?.hasDirtyTrackedFiles) { + warnings.push( + git.dirtyEntryCount === 1 ? "The workspace has 1 modified tracked file." : `The workspace has ${git.dirtyEntryCount} modified tracked files.` + ); + } + if (git?.hasUntrackedFiles) { + warnings.push( + git.untrackedEntryCount === 1 ? "The workspace has 1 untracked file." : `The workspace has ${git.untrackedEntryCount} untracked files.` + ); + } + if (git?.aheadCount && git.aheadCount > 0 && git.isMergedIntoBase === false) { + warnings.push( + git.aheadCount === 1 ? `This workspace is 1 commit ahead of ${git.baseRef ?? "the base ref"} and is not merged.` : `This workspace is ${git.aheadCount} commits ahead of ${git.baseRef ?? "the base ref"} and is not merged.` + ); + } + if (git?.behindCount && git.behindCount > 0) { + warnings.push( + git.behindCount === 1 ? `This workspace is 1 commit behind ${git.baseRef ?? "the base ref"}.` : `This workspace is ${git.behindCount} commits behind ${git.baseRef ?? "the base ref"}.` + ); + } + const plannedActions = [ + { + kind: "archive_record", + label: "Archive workspace record", + description: "Keep the execution workspace history and issue linkage, but remove it from active workspace lists.", + command: null + } + ]; + if (runtimeServices.some((service) => service.status !== "stopped")) { + plannedActions.push({ + kind: "stop_runtime_services", + label: runtimeServices.length === 1 ? "Stop attached runtime service" : "Stop attached runtime services", + description: runtimeServices.length === 1 ? `${runtimeServices[0]?.serviceName ?? "A runtime service"} will be stopped before cleanup.` : `${runtimeServices.length} runtime services will be stopped before cleanup.`, + command: null + }); + } + const configuredCleanupCommands = [ + { + kind: "cleanup_command", + label: "Run workspace cleanup command", + description: "Workspace-specific cleanup runs before teardown.", + command: config3?.cleanupCommand ?? null + }, + { + kind: "cleanup_command", + label: "Run project workspace cleanup command", + description: "Project workspace cleanup runs before execution workspace teardown.", + command: projectWorkspace?.cleanupCommand ?? null + } + ]; + for (const action of configuredCleanupCommands) { + if (!action.command) continue; + plannedActions.push(action); + } + const teardownCommand = config3?.teardownCommand ?? projectPolicy?.workspaceStrategy?.teardownCommand ?? null; + if (teardownCommand) { + plannedActions.push({ + kind: "teardown_command", + label: "Run teardown command", + description: "Teardown runs after cleanup commands during workspace close.", + command: teardownCommand + }); + } + if (executionWorkspace.providerType === "git_worktree" && workspacePath) { + plannedActions.push({ + kind: "git_worktree_remove", + label: "Remove git worktree", + description: `Taskcore will run git worktree cleanup for ${workspacePath}.`, + command: `git worktree remove --force ${workspacePath}` + }); + } + if (git?.createdByRuntime && executionWorkspace.branchName) { + plannedActions.push({ + kind: "git_branch_delete", + label: "Delete runtime-created branch", + description: "Taskcore will try to delete the runtime-created branch after removing the worktree.", + command: `git branch -d ${executionWorkspace.branchName}` + }); + } + if (executionWorkspace.providerType === "local_fs" && git?.createdByRuntime && workspacePath) { + const resolvedWorkspacePath2 = path36.resolve(workspacePath); + const resolvedProjectWorkspacePath = projectWorkspace?.cwd ? path36.resolve(projectWorkspace.cwd) : null; + const containsProjectWorkspace = resolvedProjectWorkspacePath ? resolvedWorkspacePath2 === resolvedProjectWorkspacePath || resolvedProjectWorkspacePath.startsWith(`${resolvedWorkspacePath2}${path36.sep}`) : false; + if (containsProjectWorkspace) { + warnings.push(`Taskcore will archive this workspace but keep "${workspacePath}" because it contains the project workspace.`); + } else { + plannedActions.push({ + kind: "remove_local_directory", + label: "Remove runtime-created directory", + description: `Taskcore will remove the runtime-created directory at ${workspacePath}.`, + command: `rm -rf ${workspacePath}` + }); + } + } + const state2 = blockingReasons.length > 0 ? "blocked" : warnings.length > 0 ? "ready_with_warnings" : "ready"; + return { + workspaceId: workspace.id, + state: state2, + blockingReasons, + warnings, + linkedIssues: linkedIssueSummaries, + plannedActions, + isDestructiveCloseAllowed: blockingReasons.length === 0, + isSharedWorkspace, + isProjectPrimaryWorkspace, + git, + runtimeServices + }; + }, + create: async (data2) => { + const row = await db.insert(executionWorkspaces).values(data2).returning().then((rows) => rows[0] ?? null); + return row ? toExecutionWorkspace(row) : null; + }, + update: async (id, patch) => { + const row = await db.update(executionWorkspaces).set({ ...patch, updatedAt: /* @__PURE__ */ new Date() }).where(eq(executionWorkspaces.id, id)).returning().then((rows) => rows[0] ?? null); + return row ? toExecutionWorkspace(row) : null; + } + }; +} + +// server/src/services/workspace-runtime.ts +function resolveShell() { + const fallback = process.platform === "win32" ? "sh" : "/bin/sh"; + const shell = process.env.SHELL?.trim(); + if (!shell) return fallback; + if (path37.isAbsolute(shell) && !existsSync3(shell)) return fallback; + return shell; +} +var runtimeServicesById = /* @__PURE__ */ new Map(); +var runtimeServicesByReuseKey = /* @__PURE__ */ new Map(); +var runtimeServiceLeasesByRun = /* @__PURE__ */ new Map(); +var DEFAULT_EXECUTE_PROCESS_OUTPUT_BYTES = 256 * 1024; +function stableStringify3(value) { + if (Array.isArray(value)) { + return `[${value.map((entry) => stableStringify3(entry)).join(",")}]`; + } + if (value && typeof value === "object") { + const rec = value; + return `{${Object.keys(rec).sort().map((key) => `${JSON.stringify(key)}:${stableStringify3(rec[key])}`).join(",")}}`; + } + return JSON.stringify(value); +} +function readJsonFile(filePath) { + return JSON.parse(readFileSync3(filePath, "utf8")); +} +function findWorkspaceRoot(startCwd) { + let current = path37.resolve(startCwd); + while (true) { + if (existsSync3(path37.join(current, "pnpm-workspace.yaml"))) { + return current; + } + const parent = path37.dirname(current); + if (parent === current) return null; + current = parent; + } +} +function isLinkedGitWorktreeCheckout(rootDir) { + const gitMetadataPath = path37.join(rootDir, ".git"); + if (!existsSync3(gitMetadataPath)) return false; + const stat5 = lstatSync(gitMetadataPath); + if (!stat5.isFile()) return false; + return readFileSync3(gitMetadataPath, "utf8").trimStart().startsWith("gitdir:"); +} +function discoverWorkspacePackagePaths(rootDir) { + const packagePaths = /* @__PURE__ */ new Map(); + const ignoredDirNames = /* @__PURE__ */ new Set([".git", ".taskcore", "dist", "node_modules"]); + function visit(dirPath) { + if (!existsSync3(dirPath)) return; + const packageJsonPath = path37.join(dirPath, "package.json"); + if (existsSync3(packageJsonPath)) { + const packageJson = readJsonFile(packageJsonPath); + if (typeof packageJson.name === "string" && packageJson.name.length > 0) { + packagePaths.set(packageJson.name, dirPath); + } + } + for (const entry of readdirSync(dirPath, { withFileTypes: true })) { + if (!entry.isDirectory()) continue; + if (ignoredDirNames.has(entry.name)) continue; + visit(path37.join(dirPath, entry.name)); + } + } + visit(path37.join(rootDir, "packages")); + visit(path37.join(rootDir, "server")); + visit(path37.join(rootDir, "ui")); + visit(path37.join(rootDir, "cli")); + return packagePaths; +} +function findServerWorkspaceLinkMismatches(rootDir) { + const serverPackageJsonPath = path37.join(rootDir, "server", "package.json"); + if (!existsSync3(serverPackageJsonPath)) return []; + const serverPackageJson = readJsonFile(serverPackageJsonPath); + const dependencies = { + ...serverPackageJson.dependencies, + ...serverPackageJson.devDependencies + }; + const workspacePackagePaths = discoverWorkspacePackagePaths(rootDir); + const mismatches = []; + for (const [packageName, version3] of Object.entries(dependencies)) { + if (typeof version3 !== "string" || !version3.startsWith("workspace:")) continue; + const expectedPath = workspacePackagePaths.get(packageName); + if (!expectedPath) continue; + const normalizedExpectedPath = existsSync3(expectedPath) ? path37.resolve(realpathSync(expectedPath)) : path37.resolve(expectedPath); + const linkPath = path37.join(rootDir, "server", "node_modules", ...packageName.split("/")); + const actualPath = existsSync3(linkPath) ? path37.resolve(realpathSync(linkPath)) : null; + if (actualPath === normalizedExpectedPath) continue; + mismatches.push({ + packageName, + expectedPath: normalizedExpectedPath, + actualPath + }); + } + return mismatches; +} +async function ensureServerWorkspaceLinksCurrent(startCwd, opts) { + const workspaceRoot = findWorkspaceRoot(startCwd); + if (!workspaceRoot) return; + if (!isLinkedGitWorktreeCheckout(workspaceRoot)) return; + const mismatches = findServerWorkspaceLinkMismatches(workspaceRoot); + if (mismatches.length === 0) return; + if (opts?.onLog) { + await opts.onLog("stdout", "[runtime] detected stale workspace package links for server; relinking dependencies...\n"); + for (const mismatch of mismatches) { + await opts.onLog( + "stdout", + `[runtime] ${mismatch.packageName}: ${mismatch.actualPath ?? "missing"} -> ${mismatch.expectedPath} +` + ); + } + } + for (const mismatch of mismatches) { + const linkPath = path37.join(workspaceRoot, "server", "node_modules", ...mismatch.packageName.split("/")); + await fs30.mkdir(path37.dirname(linkPath), { recursive: true }); + await fs30.rm(linkPath, { recursive: true, force: true }); + await fs30.symlink(mismatch.expectedPath, linkPath); + } + const remainingMismatches = findServerWorkspaceLinkMismatches(workspaceRoot); + if (remainingMismatches.length === 0) return; + throw new Error( + `Workspace relink did not repair all server package links: ${remainingMismatches.map((item) => item.packageName).join(", ")}` + ); +} +function sanitizeRuntimeServiceBaseEnv(baseEnv) { + const env2 = { ...baseEnv }; + for (const key of Object.keys(env2)) { + if (key.startsWith("TASKCORE_")) { + delete env2[key]; + } + } + delete env2.DATABASE_URL; + delete env2.npm_config_tailscale_auth; + delete env2.npm_config_authenticated_private; + return env2; +} +function stableRuntimeServiceId(input) { + if (input.reportId) return input.reportId; + const digest2 = createHash12("sha256").update( + stableStringify3({ + adapterType: input.adapterType, + runId: input.runId, + scopeType: input.scopeType, + scopeId: input.scopeId, + serviceName: input.serviceName, + providerRef: input.providerRef, + reuseKey: input.reuseKey + }) + ).digest("hex").slice(0, 32); + return `${input.adapterType}-${digest2}`; +} +function toRuntimeServiceRef(record2, overrides) { + return { + id: record2.id, + companyId: record2.companyId, + projectId: record2.projectId, + projectWorkspaceId: record2.projectWorkspaceId, + executionWorkspaceId: record2.executionWorkspaceId, + issueId: record2.issueId, + serviceName: record2.serviceName, + status: record2.status, + lifecycle: record2.lifecycle, + scopeType: record2.scopeType, + scopeId: record2.scopeId, + reuseKey: record2.reuseKey, + command: record2.command, + cwd: record2.cwd, + port: record2.port, + url: record2.url, + provider: record2.provider, + providerRef: record2.providerRef, + ownerAgentId: record2.ownerAgentId, + startedByRunId: record2.startedByRunId, + lastUsedAt: record2.lastUsedAt, + startedAt: record2.startedAt, + stoppedAt: record2.stoppedAt, + stopPolicy: record2.stopPolicy, + healthStatus: record2.healthStatus, + reused: record2.reused, + ...overrides + }; +} +function sanitizeSlugPart(value, fallback) { + const raw = (value ?? "").trim().toLowerCase(); + const normalized = raw.replace(/[^a-z0-9_-]+/g, "-").replace(/-+/g, "-").replace(/^[-_]+|[-_]+$/g, ""); + return normalized.length > 0 ? normalized : fallback; +} +function renderWorkspaceTemplate(template, input) { + const issueIdentifier = input.issue?.identifier ?? input.issue?.id ?? "issue"; + const slug = sanitizeSlugPart(input.issue?.title, sanitizeSlugPart(issueIdentifier, "issue")); + return renderTemplate3(template, { + issue: { + id: input.issue?.id ?? "", + identifier: input.issue?.identifier ?? "", + title: input.issue?.title ?? "" + }, + agent: { + id: input.agent.id ?? "", + name: input.agent.name + }, + project: { + id: input.projectId ?? "" + }, + workspace: { + repoRef: input.repoRef ?? "" + }, + slug + }); +} +function sanitizeBranchName(value) { + return value.trim().replace(/[^A-Za-z0-9._/-]+/g, "-").replace(/-+/g, "-").replace(/^[-/.]+|[-/.]+$/g, "").slice(0, 120) || "taskcore-work"; +} +function isAbsolutePath(value) { + return path37.isAbsolute(value) || value.startsWith("~"); +} +function resolveConfiguredPath(value, baseDir) { + if (isAbsolutePath(value)) { + return resolveHomeAwarePath(value); + } + return path37.resolve(baseDir, value); +} +function formatCommandForDisplay(command, args) { + return [command, ...args].map((part) => /^[A-Za-z0-9_./:-]+$/.test(part) ? part : JSON.stringify(part)).join(" "); +} +function createProcessOutputCapture(maxBytes) { + const limit = Math.max(1, Math.trunc(maxBytes)); + let chunks = []; + let truncated = false; + let totalBytes = 0; + return { + append(chunk) { + if (!chunk) return; + chunks.push(chunk); + totalBytes += Buffer.byteLength(chunk, "utf8"); + let currentBytes = chunks.reduce((sum, value) => sum + Buffer.byteLength(value, "utf8"), 0); + if (currentBytes <= limit) return; + const combined = Buffer.from(chunks.join(""), "utf8"); + const tail = combined.subarray(Math.max(0, combined.length - limit)).toString("utf8"); + chunks = [tail]; + truncated = true; + currentBytes = Buffer.byteLength(tail, "utf8"); + if (currentBytes > limit) { + chunks = [Buffer.from(tail, "utf8").subarray(Math.max(0, currentBytes - limit)).toString("utf8")]; + } + }, + finish() { + const text3 = chunks.join(""); + if (!truncated) { + return { + text: text3, + truncated: false, + totalBytes + }; + } + return { + text: `[output truncated to last ${limit} bytes; total ${totalBytes} bytes] +${text3}`, + truncated: true, + totalBytes + }; + } + }; +} +async function executeProcess(input) { + const proc = await new Promise((resolve4, reject) => { + const child = spawn4(input.command, input.args, { + cwd: input.cwd, + stdio: ["ignore", "pipe", "pipe"], + env: input.env ?? process.env + }); + const stdout2 = createProcessOutputCapture(input.maxStdoutBytes ?? DEFAULT_EXECUTE_PROCESS_OUTPUT_BYTES); + const stderr2 = createProcessOutputCapture(input.maxStderrBytes ?? DEFAULT_EXECUTE_PROCESS_OUTPUT_BYTES); + child.stdout?.on("data", (chunk) => { + stdout2.append(String(chunk)); + }); + child.stderr?.on("data", (chunk) => { + stderr2.append(String(chunk)); + }); + child.on("error", reject); + child.on("close", (code) => resolve4({ stdout: stdout2, stderr: stderr2, code })); + }); + const stdout = proc.stdout.finish(); + const stderr = proc.stderr.finish(); + return { + stdout: stdout.text, + stderr: stderr.text, + code: proc.code, + stdoutTruncated: stdout.truncated, + stderrTruncated: stderr.truncated, + stdoutBytes: stdout.totalBytes, + stderrBytes: stderr.totalBytes + }; +} +async function runGit2(args, cwd) { + const proc = await executeProcess({ + command: "git", + args, + cwd + }); + if (proc.code !== 0) { + throw new Error(proc.stderr.trim() || proc.stdout.trim() || `git ${args.join(" ")} failed`); + } + return proc.stdout.trim(); +} +function gitErrorIncludes(error50, needle) { + const message2 = error50 instanceof Error ? error50.message : String(error50); + return message2.toLowerCase().includes(needle.toLowerCase()); +} +function parseGitWorktreeListPorcelain(raw) { + const entries2 = []; + let current = {}; + for (const line3 of raw.split(/\r?\n/)) { + if (line3.startsWith("worktree ")) { + current = { worktree: line3.slice("worktree ".length) }; + continue; + } + if (line3.startsWith("branch ")) { + current.branch = line3.slice("branch ".length); + continue; + } + if (line3 === "" && current.worktree) { + entries2.push({ + worktree: current.worktree, + branch: current.branch ?? null + }); + current = {}; + } + } + if (current.worktree) { + entries2.push({ + worktree: current.worktree, + branch: current.branch ?? null + }); + } + return entries2; +} +async function resolveGitOwnerRepoRoot(cwd) { + const checkoutRoot = path37.resolve(await runGit2(["rev-parse", "--show-toplevel"], cwd)); + const commonDir = await runGit2(["rev-parse", "--git-common-dir"], checkoutRoot).catch(() => null); + if (!commonDir) return checkoutRoot; + return path37.dirname(path37.resolve(checkoutRoot, commonDir)); +} +async function findRegisteredGitWorktreeByBranch(repoRoot, branchName) { + const raw = await runGit2(["worktree", "list", "--porcelain"], repoRoot).catch(() => null); + if (!raw) return null; + const expectedBranchRef = `refs/heads/${branchName}`; + for (const entry of parseGitWorktreeListPorcelain(raw)) { + if (entry.branch !== expectedBranchRef) continue; + return path37.resolve(entry.worktree); + } + return null; +} +async function isGitCheckout(cwd) { + return Boolean(await runGit2(["rev-parse", "--git-dir"], cwd).catch(() => null)); +} +async function detectDefaultBranch(repoRoot) { + try { + const remoteHead = await runGit2( + ["symbolic-ref", "--quiet", "--short", "refs/remotes/origin/HEAD"], + repoRoot + ); + const branch = remoteHead?.startsWith("origin/") ? remoteHead.slice("origin/".length) : remoteHead; + if (branch) return branch; + } catch { + } + for (const candidate of ["main", "master"]) { + try { + await runGit2(["rev-parse", "--verify", `refs/remotes/origin/${candidate}`], repoRoot); + return candidate; + } catch { + } + } + return null; +} +async function directoryExists(value) { + return fs30.stat(value).then((stats) => stats.isDirectory()).catch(() => false); +} +async function listLinkedGitWorktreePaths(repoRoot) { + const output = await runGit2(["worktree", "list", "--porcelain"], repoRoot); + const paths2 = /* @__PURE__ */ new Set(); + for (const line3 of output.split("\n")) { + if (!line3.startsWith("worktree ")) continue; + const worktree = line3.slice("worktree ".length).trim(); + if (!worktree) continue; + paths2.add(path37.resolve(worktree)); + } + return paths2; +} +async function validateLinkedGitWorktree(input) { + const resolvedWorktreePath = path37.resolve(input.worktreePath); + const listedWorktrees = await listLinkedGitWorktreePaths(input.repoRoot); + if (!listedWorktrees.has(resolvedWorktreePath)) { + return { + valid: false, + reason: "path is not registered in `git worktree list`" + }; + } + const worktreeTopLevel = await runGit2(["rev-parse", "--show-toplevel"], resolvedWorktreePath).catch(() => null); + if (!worktreeTopLevel || path37.resolve(worktreeTopLevel) !== resolvedWorktreePath) { + return { + valid: false, + reason: "git resolves this path to a different repository root" + }; + } + if (input.expectedBranchName) { + const currentBranch = await runGit2( + ["symbolic-ref", "--quiet", "--short", "HEAD"], + resolvedWorktreePath + ).catch(() => null); + if (currentBranch !== input.expectedBranchName) { + return { + valid: false, + reason: `worktree HEAD is on "${currentBranch ?? ""}" instead of "${input.expectedBranchName}"` + }; + } + } + return { valid: true }; +} +function terminateChildProcess(child) { + if (!child.pid) return; + if (process.platform !== "win32") { + try { + process.kill(-child.pid, "SIGTERM"); + return; + } catch { + } + } + if (!child.killed) { + child.kill("SIGTERM"); + } +} +function buildWorkspaceCommandEnv(input) { + const env2 = { ...process.env }; + env2.TASKCORE_WORKSPACE_CWD = input.worktreePath; + env2.TASKCORE_WORKSPACE_PATH = input.worktreePath; + env2.TASKCORE_WORKSPACE_WORKTREE_PATH = input.worktreePath; + env2.TASKCORE_WORKSPACE_BRANCH = input.branchName; + env2.TASKCORE_WORKSPACE_BASE_CWD = input.base.baseCwd; + env2.TASKCORE_WORKSPACE_REPO_ROOT = input.repoRoot; + env2.TASKCORE_WORKSPACE_SOURCE = input.base.source; + env2.TASKCORE_WORKSPACE_REPO_REF = input.base.repoRef ?? ""; + env2.TASKCORE_WORKSPACE_REPO_URL = input.base.repoUrl ?? ""; + env2.TASKCORE_WORKSPACE_CREATED = input.created ? "true" : "false"; + env2.TASKCORE_PROJECT_ID = input.base.projectId ?? ""; + env2.TASKCORE_PROJECT_WORKSPACE_ID = input.base.workspaceId ?? ""; + env2.TASKCORE_AGENT_ID = input.agent.id ?? ""; + env2.TASKCORE_AGENT_NAME = input.agent.name; + env2.TASKCORE_COMPANY_ID = input.agent.companyId; + env2.TASKCORE_ISSUE_ID = input.issue?.id ?? ""; + env2.TASKCORE_ISSUE_IDENTIFIER = input.issue?.identifier ?? ""; + env2.TASKCORE_ISSUE_TITLE = input.issue?.title ?? ""; + return env2; +} +function quoteShellArg(value) { + return `'${value.replace(/'/g, `'\\''`)}'`; +} +function resolveRepoManagedWorkspaceCommand(command, repoRoot) { + const patterns = [ + /^(?(?:bash|sh|zsh)\s+)(?["']?)(?\.\/[^"'\s]+)\k(?(?:\s.*)?)$/s, + /^(?["']?)(?\.\/[^"'\s]+)\k(?(?:\s.*)?)$/s + ]; + for (const pattern of patterns) { + const match = command.match(pattern); + if (!match?.groups) continue; + const relativePath = match.groups.relative; + const repoManagedPath = path37.join(repoRoot, relativePath.slice(2)); + if (!existsSync3(repoManagedPath)) continue; + const prefix = match.groups.prefix ?? ""; + const suffix = match.groups.suffix ?? ""; + return `${prefix}${quoteShellArg(repoManagedPath)}${suffix}`; + } + return command; +} +async function runWorkspaceCommand(input) { + const shell = resolveShell(); + const proc = await executeProcess({ + command: shell, + args: ["-c", input.resolvedCommand ?? input.command], + cwd: input.cwd, + env: input.env + }); + if (proc.code === 0) return; + const details = [proc.stderr.trim(), proc.stdout.trim()].filter(Boolean).join("\n"); + throw new Error( + details.length > 0 ? `${input.label} failed: ${details}` : `${input.label} failed with exit code ${proc.code ?? -1}` + ); +} +async function recordGitOperation(recorder, input) { + if (!recorder) { + return runGit2(input.args, input.cwd); + } + let stdout = ""; + let stderr = ""; + let code = null; + await recorder.recordOperation({ + phase: input.phase, + command: formatCommandForDisplay("git", input.args), + cwd: input.cwd, + metadata: input.metadata ?? null, + run: async () => { + const result = await executeProcess({ + command: "git", + args: input.args, + cwd: input.cwd + }); + stdout = result.stdout; + stderr = result.stderr; + code = result.code; + return { + status: result.code === 0 ? "succeeded" : "failed", + exitCode: result.code, + stdout: result.stdout, + stderr: result.stderr, + system: result.code === 0 ? input.successMessage ?? null : null, + metadata: result.stdoutTruncated || result.stderrTruncated ? { + stdoutTruncated: result.stdoutTruncated, + stderrTruncated: result.stderrTruncated, + stdoutBytes: result.stdoutBytes, + stderrBytes: result.stderrBytes + } : null + }; + } + }); + if (code !== 0) { + const details = [stderr.trim(), stdout.trim()].filter(Boolean).join("\n"); + throw new Error( + details.length > 0 ? `${input.failureLabel ?? `git ${input.args.join(" ")}`} failed: ${details}` : `${input.failureLabel ?? `git ${input.args.join(" ")}`} failed with exit code ${code ?? -1}` + ); + } + return stdout.trim(); +} +async function recordWorkspaceCommandOperation(recorder, input) { + if (!recorder) { + await runWorkspaceCommand(input); + return null; + } + let stdout = ""; + let stderr = ""; + let code = null; + const operation2 = await recorder.recordOperation({ + phase: input.phase, + command: input.command, + cwd: input.cwd, + metadata: input.metadata ?? null, + run: async () => { + const shell = resolveShell(); + const result = await executeProcess({ + command: shell, + args: ["-c", input.resolvedCommand ?? input.command], + cwd: input.cwd, + env: input.env + }); + stdout = result.stdout; + stderr = result.stderr; + code = result.code; + return { + status: result.code === 0 ? "succeeded" : "failed", + exitCode: result.code, + stdout: result.stdout, + stderr: result.stderr, + system: result.code === 0 ? input.successMessage ?? null : null, + metadata: result.stdoutTruncated || result.stderrTruncated ? { + stdoutTruncated: result.stdoutTruncated, + stderrTruncated: result.stderrTruncated, + stdoutBytes: result.stdoutBytes, + stderrBytes: result.stderrBytes + } : null + }; + } + }); + if (code === 0) return operation2; + const details = [stderr.trim(), stdout.trim()].filter(Boolean).join("\n"); + throw new Error( + details.length > 0 ? `${input.label} failed: ${details}` : `${input.label} failed with exit code ${code ?? -1}` + ); +} +async function provisionExecutionWorktree(input) { + const provisionCommand = asString12(input.strategy.provisionCommand, "").trim(); + if (!provisionCommand) return; + const resolvedProvisionCommand = resolveRepoManagedWorkspaceCommand(provisionCommand, input.repoRoot); + await recordWorkspaceCommandOperation(input.recorder, { + phase: "workspace_provision", + command: provisionCommand, + resolvedCommand: resolvedProvisionCommand, + cwd: input.worktreePath, + env: buildWorkspaceCommandEnv({ + base: input.base, + repoRoot: input.repoRoot, + worktreePath: input.worktreePath, + branchName: input.branchName, + issue: input.issue, + agent: input.agent, + created: input.created + }), + label: `Execution workspace provision command "${provisionCommand}"`, + metadata: { + repoRoot: input.repoRoot, + worktreePath: input.worktreePath, + branchName: input.branchName, + created: input.created, + resolvedCommand: resolvedProvisionCommand === provisionCommand ? null : resolvedProvisionCommand + }, + successMessage: `Provisioned workspace at ${input.worktreePath} +` + }); +} +function buildExecutionWorkspaceCleanupEnv(input) { + const env2 = sanitizeRuntimeServiceBaseEnv(process.env); + env2.TASKCORE_WORKSPACE_CWD = input.workspace.cwd ?? ""; + env2.TASKCORE_WORKSPACE_PATH = input.workspace.cwd ?? ""; + env2.TASKCORE_WORKSPACE_WORKTREE_PATH = input.workspace.providerRef ?? input.workspace.cwd ?? ""; + env2.TASKCORE_WORKSPACE_BRANCH = input.workspace.branchName ?? ""; + env2.TASKCORE_WORKSPACE_BASE_CWD = input.projectWorkspaceCwd ?? ""; + env2.TASKCORE_WORKSPACE_REPO_ROOT = input.projectWorkspaceCwd ?? ""; + env2.TASKCORE_WORKSPACE_REPO_URL = input.workspace.repoUrl ?? ""; + env2.TASKCORE_WORKSPACE_REPO_REF = input.workspace.baseRef ?? ""; + env2.TASKCORE_PROJECT_ID = input.workspace.projectId ?? ""; + env2.TASKCORE_PROJECT_WORKSPACE_ID = input.workspace.projectWorkspaceId ?? ""; + env2.TASKCORE_ISSUE_ID = input.workspace.sourceIssueId ?? ""; + return env2; +} +async function resolveGitRepoRootForWorkspaceCleanup(worktreePath, projectWorkspaceCwd) { + if (projectWorkspaceCwd) { + const resolvedProjectWorkspaceCwd = path37.resolve(projectWorkspaceCwd); + const gitDir2 = await runGit2(["rev-parse", "--git-common-dir"], resolvedProjectWorkspaceCwd).catch(() => null); + if (gitDir2) { + const resolvedGitDir2 = path37.resolve(resolvedProjectWorkspaceCwd, gitDir2); + return path37.dirname(resolvedGitDir2); + } + } + const gitDir = await runGit2(["rev-parse", "--git-common-dir"], worktreePath).catch(() => null); + if (!gitDir) return null; + const resolvedGitDir = path37.resolve(worktreePath, gitDir); + return path37.dirname(resolvedGitDir); +} +async function realizeExecutionWorkspace(input) { + const rawStrategy = parseObject4(input.config.workspaceStrategy); + const strategyType = asString12(rawStrategy.type, "project_primary"); + if (strategyType !== "git_worktree") { + return { + ...input.base, + strategy: "project_primary", + cwd: input.base.baseCwd, + branchName: null, + worktreePath: null, + warnings: [], + created: false + }; + } + const repoRoot = await resolveGitOwnerRepoRoot(input.base.baseCwd); + const branchTemplate = asString12(rawStrategy.branchTemplate, "{{issue.identifier}}-{{slug}}"); + const renderedBranch = renderWorkspaceTemplate(branchTemplate, { + issue: input.issue, + agent: input.agent, + projectId: input.base.projectId, + repoRef: input.base.repoRef + }); + const branchName = sanitizeBranchName(renderedBranch); + const configuredParentDir = asString12(rawStrategy.worktreeParentDir, ""); + const worktreeParentDir = configuredParentDir ? resolveConfiguredPath(configuredParentDir, repoRoot) : path37.join(repoRoot, ".taskcore", "worktrees"); + const worktreePath = path37.join(worktreeParentDir, branchName); + const configuredBaseRef = typeof rawStrategy.baseRef === "string" && rawStrategy.baseRef.length > 0 ? rawStrategy.baseRef : input.base.repoRef ?? null; + const baseRef = configuredBaseRef ?? await detectDefaultBranch(repoRoot) ?? "HEAD"; + await fs30.mkdir(worktreeParentDir, { recursive: true }); + async function reuseExistingWorktree(reusablePath) { + if (input.recorder) { + await input.recorder.recordOperation({ + phase: "worktree_prepare", + cwd: repoRoot, + metadata: { + repoRoot, + worktreePath: reusablePath, + branchName, + baseRef, + created: false, + reused: true + }, + run: async () => ({ + status: "succeeded", + exitCode: 0, + system: `Reused existing git worktree at ${reusablePath} +` + }) + }); + } + await provisionExecutionWorktree({ + strategy: rawStrategy, + base: input.base, + repoRoot, + worktreePath: reusablePath, + branchName, + issue: input.issue, + agent: input.agent, + created: false, + recorder: input.recorder ?? null + }); + return { + ...input.base, + strategy: "git_worktree", + cwd: reusablePath, + branchName, + worktreePath: reusablePath, + warnings: [], + created: false + }; + } + async function validateReusableWorktree(reusablePath) { + return await validateLinkedGitWorktree({ + repoRoot, + worktreePath: reusablePath, + expectedBranchName: branchName + }).catch(() => null); + } + const existingWorktree = await directoryExists(worktreePath); + if (existingWorktree) { + const validation = await validateReusableWorktree(worktreePath); + if (validation?.valid) { + return await reuseExistingWorktree(worktreePath); + } + const reason = validation && !validation.valid ? ` (${validation.reason})` : ""; + throw new Error(`Configured worktree path "${worktreePath}" already exists and is not a reusable git worktree${reason}.`); + } + const registeredBranchWorktree = await findRegisteredGitWorktreeByBranch(repoRoot, branchName); + if (registeredBranchWorktree) { + const validation = await validateReusableWorktree(registeredBranchWorktree); + if (validation?.valid) { + return await reuseExistingWorktree(registeredBranchWorktree); + } + const reason = validation && !validation.valid ? ` (${validation.reason})` : ""; + throw new Error(`Registered worktree for branch "${branchName}" at "${registeredBranchWorktree}" is not reusable${reason}.`); + } + try { + await recordGitOperation(input.recorder, { + phase: "worktree_prepare", + args: ["worktree", "add", "-b", branchName, worktreePath, baseRef], + cwd: repoRoot, + metadata: { + repoRoot, + worktreePath, + branchName, + baseRef, + created: true + }, + successMessage: `Created git worktree at ${worktreePath} +`, + failureLabel: `git worktree add ${worktreePath}` + }); + } catch (error50) { + if (!gitErrorIncludes(error50, "already exists")) { + throw error50; + } + try { + await recordGitOperation(input.recorder, { + phase: "worktree_prepare", + args: ["worktree", "add", worktreePath, branchName], + cwd: repoRoot, + metadata: { + repoRoot, + worktreePath, + branchName, + baseRef, + created: false, + reusedExistingBranch: true + }, + successMessage: `Attached existing branch ${branchName} at ${worktreePath} +`, + failureLabel: `git worktree add ${worktreePath}` + }); + } catch (attachError) { + if (!gitErrorIncludes(attachError, "already checked out")) { + throw attachError; + } + const reusablePath = await findRegisteredGitWorktreeByBranch(repoRoot, branchName); + if (!reusablePath || !await isGitCheckout(reusablePath)) { + throw attachError; + } + return await reuseExistingWorktree(reusablePath); + } + } + await provisionExecutionWorktree({ + strategy: rawStrategy, + base: input.base, + repoRoot, + worktreePath, + branchName, + issue: input.issue, + agent: input.agent, + created: true, + recorder: input.recorder ?? null + }); + return { + ...input.base, + strategy: "git_worktree", + cwd: worktreePath, + branchName, + worktreePath, + warnings: [], + created: true + }; +} +async function ensurePersistedExecutionWorkspaceAvailable(input) { + const cwd = asString12(input.workspace.cwd ?? input.workspace.providerRef, "").trim(); + if (!cwd) return null; + const strategy = input.workspace.strategyType === "git_worktree" ? "git_worktree" : "project_primary"; + const realized = { + baseCwd: input.base.baseCwd, + source: input.workspace.mode === "shared_workspace" ? "project_primary" : "task_session", + projectId: input.workspace.projectId ?? input.base.projectId, + workspaceId: input.workspace.projectWorkspaceId ?? input.base.workspaceId, + repoUrl: input.workspace.repoUrl ?? input.base.repoUrl, + repoRef: input.workspace.baseRef ?? input.base.repoRef, + strategy, + cwd, + branchName: input.workspace.branchName ?? null, + worktreePath: strategy === "git_worktree" ? input.workspace.providerRef ?? cwd : null, + warnings: [], + created: false + }; + const provisionCommand = asString12(input.workspace.config?.provisionCommand, "").trim(); + if (strategy !== "git_worktree") { + return realized; + } + if (await directoryExists(cwd)) { + if (provisionCommand) { + const repoRoot2 = await runGit2(["rev-parse", "--show-toplevel"], input.base.baseCwd); + await provisionExecutionWorktree({ + strategy: { + type: "git_worktree", + provisionCommand + }, + base: input.base, + repoRoot: repoRoot2, + worktreePath: realized.worktreePath ?? cwd, + branchName: realized.branchName ?? "", + issue: input.issue, + agent: input.agent, + created: false, + recorder: input.recorder ?? null + }); + } + return realized; + } + const repoRoot = await runGit2(["rev-parse", "--show-toplevel"], input.base.baseCwd); + const worktreePath = realized.worktreePath ?? cwd; + const branchName = asString12(input.workspace.branchName, "").trim(); + if (!branchName) { + throw new Error(`Execution workspace "${cwd}" is missing and cannot be restored because no branch name is recorded.`); + } + await fs30.mkdir(path37.dirname(worktreePath), { recursive: true }); + await runGit2(["worktree", "prune"], repoRoot).catch(() => { + }); + let created = false; + try { + await recordGitOperation(input.recorder, { + phase: "worktree_prepare", + args: ["worktree", "add", worktreePath, branchName], + cwd: repoRoot, + metadata: { + repoRoot, + worktreePath, + branchName, + baseRef: input.workspace.baseRef ?? input.base.repoRef ?? null, + created: false, + restored: true + }, + successMessage: `Reattached missing git worktree at ${worktreePath} +`, + failureLabel: `git worktree add ${worktreePath}` + }); + } catch (error50) { + if (!gitErrorIncludes(error50, "invalid reference") && !gitErrorIncludes(error50, "not a commit") && !gitErrorIncludes(error50, "unknown revision")) { + throw error50; + } + const baseRef = input.workspace.baseRef ?? await detectDefaultBranch(repoRoot) ?? "HEAD"; + await recordGitOperation(input.recorder, { + phase: "worktree_prepare", + args: ["worktree", "add", "-b", branchName, worktreePath, baseRef], + cwd: repoRoot, + metadata: { + repoRoot, + worktreePath, + branchName, + baseRef, + created: true, + restored: true + }, + successMessage: `Recreated missing git worktree at ${worktreePath} +`, + failureLabel: `git worktree add ${worktreePath}` + }); + created = true; + } + await provisionExecutionWorktree({ + strategy: { + type: "git_worktree", + ...provisionCommand ? { provisionCommand } : {} + }, + base: input.base, + repoRoot, + worktreePath, + branchName, + issue: input.issue, + agent: input.agent, + created, + recorder: input.recorder ?? null + }); + return { + ...realized, + cwd: worktreePath, + worktreePath, + created + }; +} +async function cleanupExecutionWorkspaceArtifacts(input) { + const warnings = []; + const workspacePath = input.workspace.providerRef ?? input.workspace.cwd; + const repoRoot = input.workspace.providerType === "git_worktree" && workspacePath ? await resolveGitRepoRootForWorkspaceCleanup( + workspacePath, + input.projectWorkspace?.cwd ?? null + ) : null; + const cleanupEnv = buildExecutionWorkspaceCleanupEnv({ + workspace: input.workspace, + projectWorkspaceCwd: input.projectWorkspace?.cwd ?? null + }); + const createdByRuntime = input.workspace.metadata?.createdByRuntime === true; + const cleanupCommands = [ + input.cleanupCommand ?? null, + input.projectWorkspace?.cleanupCommand ?? null, + input.teardownCommand ?? null + ].map((value) => asString12(value, "").trim()).filter(Boolean); + for (const command of cleanupCommands) { + try { + const resolvedCommand = repoRoot ? resolveRepoManagedWorkspaceCommand(command, repoRoot) : command; + await recordWorkspaceCommandOperation(input.recorder, { + phase: "workspace_teardown", + command, + resolvedCommand, + cwd: workspacePath ?? input.projectWorkspace?.cwd ?? process.cwd(), + env: cleanupEnv, + label: `Execution workspace cleanup command "${command}"`, + metadata: { + workspaceId: input.workspace.id, + workspacePath, + branchName: input.workspace.branchName, + providerType: input.workspace.providerType, + resolvedCommand: resolvedCommand === command ? null : resolvedCommand + }, + successMessage: `Completed cleanup command "${command}" +` + }); + } catch (err) { + warnings.push(err instanceof Error ? err.message : String(err)); + } + } + if (input.workspace.providerType === "git_worktree" && workspacePath) { + const worktreeExists = await directoryExists(workspacePath); + if (worktreeExists) { + if (!repoRoot) { + warnings.push(`Could not resolve git repo root for "${workspacePath}".`); + } else { + try { + await recordGitOperation(input.recorder, { + phase: "worktree_cleanup", + args: ["worktree", "remove", "--force", workspacePath], + cwd: repoRoot, + metadata: { + workspaceId: input.workspace.id, + workspacePath, + branchName: input.workspace.branchName, + cleanupAction: "worktree_remove" + }, + successMessage: `Removed git worktree ${workspacePath} +`, + failureLabel: `git worktree remove ${workspacePath}` + }); + } catch (err) { + warnings.push(err instanceof Error ? err.message : String(err)); + } + } + } + if (createdByRuntime && input.workspace.branchName) { + if (!repoRoot) { + warnings.push(`Could not resolve git repo root to delete branch "${input.workspace.branchName}".`); + } else { + try { + await recordGitOperation(input.recorder, { + phase: "worktree_cleanup", + args: ["branch", "-d", input.workspace.branchName], + cwd: repoRoot, + metadata: { + workspaceId: input.workspace.id, + workspacePath, + branchName: input.workspace.branchName, + cleanupAction: "branch_delete" + }, + successMessage: `Deleted branch ${input.workspace.branchName} +`, + failureLabel: `git branch -d ${input.workspace.branchName}` + }); + } catch (err) { + const message2 = err instanceof Error ? err.message : String(err); + warnings.push(`Skipped deleting branch "${input.workspace.branchName}": ${message2}`); + } + } + } + } else if (input.workspace.providerType === "local_fs" && createdByRuntime && workspacePath) { + const projectWorkspaceCwd = input.projectWorkspace?.cwd ? path37.resolve(input.projectWorkspace.cwd) : null; + const resolvedWorkspacePath = path37.resolve(workspacePath); + const containsProjectWorkspace = projectWorkspaceCwd ? resolvedWorkspacePath === projectWorkspaceCwd || projectWorkspaceCwd.startsWith(`${resolvedWorkspacePath}${path37.sep}`) : false; + if (containsProjectWorkspace) { + warnings.push(`Refusing to remove path "${workspacePath}" because it contains the project workspace.`); + } else { + await fs30.rm(resolvedWorkspacePath, { recursive: true, force: true }); + if (input.recorder) { + await input.recorder.recordOperation({ + phase: "workspace_teardown", + cwd: projectWorkspaceCwd ?? process.cwd(), + metadata: { + workspaceId: input.workspace.id, + workspacePath: resolvedWorkspacePath, + cleanupAction: "remove_local_fs" + }, + run: async () => ({ + status: "succeeded", + exitCode: 0, + system: `Removed local workspace directory ${resolvedWorkspacePath} +` + }) + }); + } + } + } + const cleaned = !workspacePath || !await directoryExists(workspacePath); + return { + cleanedPath: workspacePath, + cleaned, + warnings + }; +} +async function allocatePort() { + return await new Promise((resolve4, reject) => { + const server = net2.createServer(); + server.listen(0, "127.0.0.1", () => { + const address = server.address(); + server.close((err) => { + if (err) { + reject(err); + return; + } + if (!address || typeof address === "string") { + reject(new Error("Failed to allocate port")); + return; + } + resolve4(address.port); + }); + }); + server.on("error", reject); + }); +} +function buildTemplateData(input) { + return { + workspace: { + cwd: input.workspace.cwd, + branchName: input.workspace.branchName ?? "", + worktreePath: input.workspace.worktreePath ?? "", + repoUrl: input.workspace.repoUrl ?? "", + repoRef: input.workspace.repoRef ?? "", + env: input.adapterEnv + }, + issue: { + id: input.issue?.id ?? "", + identifier: input.issue?.identifier ?? "", + title: input.issue?.title ?? "" + }, + agent: { + id: input.agent.id ?? "", + name: input.agent.name + }, + port: input.port ?? "" + }; +} +function renderRuntimeServiceEnv(input) { + const rendered = {}; + for (const [key, value] of Object.entries(input.envConfig)) { + if (typeof value !== "string") continue; + rendered[key] = renderTemplate3(value, input.templateData); + } + return rendered; +} +function resolveRuntimeServiceReuseIdentity(input) { + const serviceName = asString12(input.service.name, "service"); + const lifecycle = asString12(input.service.lifecycle, "shared") === "ephemeral" ? "ephemeral" : "shared"; + const command = asString12(input.service.command, ""); + const serviceCwdTemplate = asString12(input.service.cwd, "."); + const portConfig = parseObject4(input.service.port); + const envConfig = parseObject4(input.service.env); + const explicitPort = asNumber3(portConfig.value, asNumber3(input.service.port, 0)); + const identityPort = explicitPort > 0 ? explicitPort : null; + const templateData = buildTemplateData({ + workspace: input.workspace, + agent: input.agent, + issue: input.issue, + adapterEnv: input.adapterEnv, + port: identityPort + }); + const serviceCwd = resolveConfiguredPath(renderTemplate3(serviceCwdTemplate, templateData), input.workspace.cwd); + const renderedEnv = renderRuntimeServiceEnv({ + envConfig, + templateData + }); + const envFingerprint = createHash12("sha256").update(stableStringify3(renderedEnv)).digest("hex"); + const reuseKey = lifecycle === "shared" ? createHash12("sha256").update( + stableStringify3({ + scopeType: input.scopeType, + scopeId: input.scopeId, + serviceName, + command, + cwd: serviceCwd, + port: identityPort, + env: renderedEnv + }) + ).digest("hex") : null; + return { + serviceName, + lifecycle, + command, + serviceCwd, + envConfig, + envFingerprint, + explicitPort, + identityPort, + reuseKey + }; +} +function resolveWorkspaceCommandExecution(input) { + const name = asString12(input.command.name, "") || asString12(input.command.label, "") || asString12(input.command.title, "") || "workspace command"; + const command = asString12(input.command.command, ""); + const templateData = buildTemplateData({ + workspace: input.workspace, + agent: input.agent, + issue: input.issue, + adapterEnv: input.adapterEnv, + port: null + }); + const cwd = resolveConfiguredPath( + renderTemplate3(asString12(input.command.cwd, "."), templateData), + input.workspace.cwd + ); + const env2 = { + ...sanitizeRuntimeServiceBaseEnv(process.env), + ...input.adapterEnv, + ...renderRuntimeServiceEnv({ + envConfig: parseObject4(input.command.env), + templateData + }) + }; + return { + name, + command, + cwd, + env: env2 + }; +} +async function runWorkspaceJobForControl(input) { + const resolved = resolveWorkspaceCommandExecution({ + command: input.command, + workspace: input.workspace, + agent: input.actor, + issue: input.issue, + adapterEnv: input.adapterEnv ?? {} + }); + if (!resolved.command) { + throw new Error(`Workspace job "${resolved.name}" is missing command`); + } + await ensureServerWorkspaceLinksCurrent(resolved.cwd); + return await recordWorkspaceCommandOperation(input.recorder, { + phase: "workspace_provision", + command: resolved.command, + cwd: resolved.cwd, + env: resolved.env, + label: `Workspace job "${resolved.name}"`, + metadata: { + workspaceCommandKind: "job", + workspaceCommandName: resolved.name, + ...input.metadata ?? {} + }, + successMessage: `Completed workspace job "${resolved.name}" +` + }); +} +function resolveServiceScopeId(input) { + const scopeTypeRaw = asString12(input.service.reuseScope, input.service.lifecycle === "shared" ? "project_workspace" : "run"); + const scopeType = scopeTypeRaw === "project_workspace" || scopeTypeRaw === "execution_workspace" || scopeTypeRaw === "agent" ? scopeTypeRaw : "run"; + if (scopeType === "project_workspace") return { scopeType, scopeId: input.workspace.workspaceId ?? input.workspace.projectId }; + if (scopeType === "execution_workspace") { + return { scopeType, scopeId: input.executionWorkspaceId ?? input.workspace.cwd }; + } + if (scopeType === "agent") return { scopeType, scopeId: input.agent.id }; + return { scopeType: "run", scopeId: input.runId }; +} +function looksLikeWorkspaceDevServerCommand(command) { + const normalized = command.trim().toLowerCase(); + if (!normalized) return false; + return /(?:^|\s)(?:pnpm|npm|yarn|bun)\s+(?:run\s+)?dev(?:\s|$)/.test(normalized); +} +function resolveWorkspaceRuntimeReadinessTimeoutSec(service) { + const readiness = parseObject4(service.readiness); + const explicitTimeoutSec = asNumber3(readiness.timeoutSec, 0); + if (explicitTimeoutSec > 0) { + return Math.max(1, explicitTimeoutSec); + } + return looksLikeWorkspaceDevServerCommand(asString12(service.command, "")) ? 90 : 30; +} +async function waitForReadiness(input) { + const readiness = parseObject4(input.service.readiness); + const readinessType = asString12(readiness.type, ""); + if (readinessType !== "http" || !input.url) return; + const timeoutSec = resolveWorkspaceRuntimeReadinessTimeoutSec(input.service); + const intervalMs = Math.max(100, asNumber3(readiness.intervalMs, 500)); + const deadline = Date.now() + timeoutSec * 1e3; + let lastError = "service did not become ready"; + while (Date.now() < deadline) { + try { + const response = await fetch(input.url); + if (response.ok) return; + lastError = `received HTTP ${response.status}`; + } catch (err) { + lastError = err instanceof Error ? err.message : String(err); + } + await delay2(intervalMs); + } + throw new Error(`Readiness check failed for ${input.url}: ${lastError}`); +} +function toPersistedWorkspaceRuntimeService(record2) { + return { + id: record2.id, + companyId: record2.companyId, + projectId: record2.projectId, + projectWorkspaceId: record2.projectWorkspaceId, + executionWorkspaceId: record2.executionWorkspaceId, + issueId: record2.issueId, + scopeType: record2.scopeType, + scopeId: record2.scopeId, + serviceName: record2.serviceName, + status: record2.status, + lifecycle: record2.lifecycle, + reuseKey: record2.reuseKey, + command: record2.command, + cwd: record2.cwd, + port: record2.port, + url: record2.url, + provider: record2.provider, + providerRef: record2.providerRef, + ownerAgentId: record2.ownerAgentId, + startedByRunId: record2.startedByRunId, + lastUsedAt: new Date(record2.lastUsedAt), + startedAt: new Date(record2.startedAt), + stoppedAt: record2.stoppedAt ? new Date(record2.stoppedAt) : null, + stopPolicy: record2.stopPolicy, + healthStatus: record2.healthStatus, + updatedAt: /* @__PURE__ */ new Date() + }; +} +async function persistRuntimeServiceRecord(db, record2) { + if (!db) return; + const values2 = toPersistedWorkspaceRuntimeService(record2); + await db.insert(workspaceRuntimeServices).values(values2).onConflictDoUpdate({ + target: workspaceRuntimeServices.id, + set: { + projectId: values2.projectId, + projectWorkspaceId: values2.projectWorkspaceId, + executionWorkspaceId: values2.executionWorkspaceId, + issueId: values2.issueId, + scopeType: values2.scopeType, + scopeId: values2.scopeId, + serviceName: values2.serviceName, + status: values2.status, + lifecycle: values2.lifecycle, + reuseKey: values2.reuseKey, + command: values2.command, + cwd: values2.cwd, + port: values2.port, + url: values2.url, + provider: values2.provider, + providerRef: values2.providerRef, + ownerAgentId: values2.ownerAgentId, + startedByRunId: values2.startedByRunId, + lastUsedAt: values2.lastUsedAt, + startedAt: values2.startedAt, + stoppedAt: values2.stoppedAt, + stopPolicy: values2.stopPolicy, + healthStatus: values2.healthStatus, + updatedAt: values2.updatedAt + } + }); +} +function clearIdleTimer(record2) { + if (!record2.idleTimer) return; + clearTimeout(record2.idleTimer); + record2.idleTimer = null; +} +function normalizeAdapterManagedRuntimeServices(input) { + const nowIso = (input.now ?? /* @__PURE__ */ new Date()).toISOString(); + return input.reports.map((report) => { + const scopeType = report.scopeType ?? "run"; + const scopeId = report.scopeId ?? (scopeType === "project_workspace" ? input.workspace.workspaceId : scopeType === "execution_workspace" ? input.executionWorkspaceId ?? input.workspace.cwd : scopeType === "agent" ? input.agent.id : input.runId) ?? null; + const serviceName = asString12(report.serviceName, "").trim() || "service"; + const status = report.status ?? "running"; + const lifecycle = report.lifecycle ?? "ephemeral"; + const healthStatus = report.healthStatus ?? (status === "running" ? "healthy" : status === "failed" ? "unhealthy" : "unknown"); + return { + id: stableRuntimeServiceId({ + adapterType: input.adapterType, + runId: input.runId, + scopeType, + scopeId, + serviceName, + reportId: report.id ?? null, + providerRef: report.providerRef ?? null, + reuseKey: report.reuseKey ?? null + }), + companyId: input.agent.companyId, + projectId: report.projectId ?? input.workspace.projectId, + projectWorkspaceId: report.projectWorkspaceId ?? input.workspace.workspaceId, + executionWorkspaceId: input.executionWorkspaceId ?? null, + issueId: report.issueId ?? input.issue?.id ?? null, + serviceName, + status, + lifecycle, + scopeType, + scopeId, + reuseKey: report.reuseKey ?? null, + command: report.command ?? null, + cwd: report.cwd ?? null, + port: report.port ?? null, + url: report.url ?? null, + provider: "adapter_managed", + providerRef: report.providerRef ?? null, + ownerAgentId: report.ownerAgentId ?? input.agent.id ?? null, + startedByRunId: input.runId, + lastUsedAt: nowIso, + startedAt: nowIso, + stoppedAt: status === "running" || status === "starting" ? null : nowIso, + stopPolicy: report.stopPolicy ?? null, + healthStatus, + reused: false + }; + }); +} +async function startLocalRuntimeService(input) { + const leaseRunId = input.leaseRunId === void 0 ? input.runId : input.leaseRunId; + const startedByRunId = input.startedByRunId === void 0 ? input.runId : input.startedByRunId; + const identity = resolveRuntimeServiceReuseIdentity({ + service: input.service, + workspace: input.workspace, + agent: input.agent, + issue: input.issue, + adapterEnv: input.adapterEnv, + scopeType: input.scopeType, + scopeId: input.scopeId + }); + const serviceName = identity.serviceName; + const lifecycle = identity.lifecycle; + const command = identity.command; + if (!command) throw new Error(`Runtime service "${serviceName}" is missing command`); + const portConfig = parseObject4(input.service.port); + const envConfig = identity.envConfig; + const envFingerprint = identity.envFingerprint; + const serviceIdentityFingerprint = input.reuseKey ?? envFingerprint; + const explicitPort = identity.explicitPort; + const identityPort = identity.identityPort; + const port = asString12(portConfig.type, "") === "auto" ? await allocatePort() : explicitPort > 0 ? explicitPort : null; + const templateData = buildTemplateData({ + workspace: input.workspace, + agent: input.agent, + issue: input.issue, + adapterEnv: input.adapterEnv, + port + }); + const serviceCwd = port === identityPort ? identity.serviceCwd : resolveConfiguredPath(renderTemplate3(asString12(input.service.cwd, "."), templateData), input.workspace.cwd); + const env2 = { + ...sanitizeRuntimeServiceBaseEnv(process.env), + ...input.adapterEnv + }; + for (const [key, value] of Object.entries(renderRuntimeServiceEnv({ envConfig, templateData }))) { + env2[key] = value; + } + if (port) { + const portEnvKey = asString12(portConfig.envKey, "PORT"); + env2[portEnvKey] = String(port); + } + const expose = parseObject4(input.service.expose); + const readiness = parseObject4(input.service.readiness); + const urlTemplate = asString12(expose.urlTemplate, "") || asString12(readiness.urlTemplate, ""); + const url2 = urlTemplate ? renderTemplate3(urlTemplate, templateData) : null; + const stopPolicy = parseObject4(input.service.stopPolicy); + const serviceKey = createLocalServiceKey({ + profileKind: "workspace-runtime", + serviceName, + cwd: serviceCwd, + command, + envFingerprint: serviceIdentityFingerprint, + port: identityPort, + scope: { + scopeType: input.scopeType, + scopeId: input.scopeId, + executionWorkspaceId: input.executionWorkspaceId ?? null, + reuseKey: input.reuseKey + } + }); + const adoptedRecord = await findAdoptableLocalService({ + serviceKey, + command, + cwd: serviceCwd, + envFingerprint: serviceIdentityFingerprint, + port: identityPort + }); + if (adoptedRecord) { + return { + id: adoptedRecord.runtimeServiceId ?? randomUUID4(), + companyId: input.agent.companyId, + projectId: input.workspace.projectId, + projectWorkspaceId: input.workspace.workspaceId, + executionWorkspaceId: input.executionWorkspaceId ?? null, + issueId: input.issue?.id ?? null, + serviceName, + status: "running", + lifecycle, + scopeType: input.scopeType, + scopeId: input.scopeId, + reuseKey: input.reuseKey, + command, + cwd: serviceCwd, + port: adoptedRecord.port ?? port, + url: adoptedRecord.url ?? url2, + provider: "local_process", + providerRef: String(adoptedRecord.pid), + ownerAgentId: input.agent.id ?? null, + startedByRunId, + lastUsedAt: (/* @__PURE__ */ new Date()).toISOString(), + startedAt: adoptedRecord.startedAt, + stoppedAt: null, + stopPolicy, + healthStatus: "healthy", + reused: true, + db: input.db, + child: null, + leaseRunIds: leaseRunId ? /* @__PURE__ */ new Set([leaseRunId]) : /* @__PURE__ */ new Set(), + idleTimer: null, + envFingerprint, + serviceKey, + profileKind: "workspace-runtime", + processGroupId: adoptedRecord.processGroupId ?? null + }; + } + if (identityPort) { + const ownerPid = await readLocalServicePortOwner(identityPort); + if (ownerPid) { + throw new Error( + `Runtime service "${serviceName}" could not start because port ${identityPort} is already in use by pid ${ownerPid}` + ); + } + } + await ensureServerWorkspaceLinksCurrent(serviceCwd, { + onLog: input.onLog + }); + const shell = resolveShell(); + const child = spawn4(shell, ["-lc", command], { + cwd: serviceCwd, + env: env2, + detached: process.platform !== "win32", + stdio: ["ignore", "pipe", "pipe"] + }); + const spawnErrorPromise = new Promise((_, reject) => { + child.once("error", (err) => { + reject(err); + }); + }); + let stderrExcerpt = ""; + let stdoutExcerpt = ""; + child.stdout?.on("data", async (chunk) => { + const text3 = String(chunk); + stdoutExcerpt = (stdoutExcerpt + text3).slice(-4096); + if (input.onLog) await input.onLog("stdout", `[service:${serviceName}] ${text3}`); + }); + child.stderr?.on("data", async (chunk) => { + const text3 = String(chunk); + stderrExcerpt = (stderrExcerpt + text3).slice(-4096); + if (input.onLog) await input.onLog("stderr", `[service:${serviceName}] ${text3}`); + }); + try { + await Promise.race([ + waitForReadiness({ service: input.service, url: url2 }), + spawnErrorPromise + ]); + } catch (err) { + terminateChildProcess(child); + throw new Error( + `Failed to start runtime service "${serviceName}": ${err instanceof Error ? err.message : String(err)}${stderrExcerpt ? ` | stderr: ${stderrExcerpt.trim()}` : ""}` + ); + } + const record2 = { + id: randomUUID4(), + companyId: input.agent.companyId, + projectId: input.workspace.projectId, + projectWorkspaceId: input.workspace.workspaceId, + executionWorkspaceId: input.executionWorkspaceId ?? null, + issueId: input.issue?.id ?? null, + serviceName, + status: "running", + lifecycle, + scopeType: input.scopeType, + scopeId: input.scopeId, + reuseKey: input.reuseKey, + command, + cwd: serviceCwd, + port, + url: url2, + provider: "local_process", + providerRef: child.pid ? String(child.pid) : null, + ownerAgentId: input.agent.id ?? null, + startedByRunId, + lastUsedAt: (/* @__PURE__ */ new Date()).toISOString(), + startedAt: (/* @__PURE__ */ new Date()).toISOString(), + stoppedAt: null, + stopPolicy, + healthStatus: "healthy", + reused: false, + db: input.db, + child, + leaseRunIds: leaseRunId ? /* @__PURE__ */ new Set([leaseRunId]) : /* @__PURE__ */ new Set(), + idleTimer: null, + envFingerprint, + serviceKey, + profileKind: "workspace-runtime", + processGroupId: child.pid ?? null + }; + if (child.pid) { + await writeLocalServiceRegistryRecord({ + version: 1, + serviceKey, + profileKind: "workspace-runtime", + serviceName, + command, + cwd: serviceCwd, + envFingerprint: serviceIdentityFingerprint, + port, + url: url2, + pid: child.pid, + processGroupId: child.pid, + provider: "local_process", + runtimeServiceId: record2.id, + reuseKey: input.reuseKey, + startedAt: record2.startedAt, + lastSeenAt: record2.lastUsedAt, + metadata: { + projectId: record2.projectId, + projectWorkspaceId: record2.projectWorkspaceId, + executionWorkspaceId: record2.executionWorkspaceId, + issueId: record2.issueId, + scopeType: record2.scopeType, + scopeId: record2.scopeId + } + }); + } + return record2; +} +function scheduleIdleStop(record2) { + clearIdleTimer(record2); + const stopType = asString12(record2.stopPolicy?.type, "manual"); + if (stopType !== "idle_timeout") return; + const idleSeconds = Math.max(1, asNumber3(record2.stopPolicy?.idleSeconds, 1800)); + record2.idleTimer = setTimeout(() => { + stopRuntimeService(record2.id).catch(() => void 0); + }, idleSeconds * 1e3); +} +async function stopRuntimeService(serviceId) { + const record2 = runtimeServicesById.get(serviceId); + if (!record2) return; + clearIdleTimer(record2); + record2.status = "stopped"; + record2.healthStatus = "unknown"; + record2.lastUsedAt = (/* @__PURE__ */ new Date()).toISOString(); + record2.stoppedAt = (/* @__PURE__ */ new Date()).toISOString(); + runtimeServicesById.delete(serviceId); + if (record2.reuseKey && runtimeServicesByReuseKey.get(record2.reuseKey) === record2.id) { + runtimeServicesByReuseKey.delete(record2.reuseKey); + } + if (record2.child && record2.child.pid) { + await terminateLocalService({ + pid: record2.child.pid, + processGroupId: record2.processGroupId ?? record2.child.pid + }); + } else if (record2.providerRef) { + const pid = Number.parseInt(record2.providerRef, 10); + if (Number.isInteger(pid) && pid > 0) { + await terminateLocalService({ + pid, + processGroupId: record2.processGroupId + }); + } + } + await removeLocalServiceRegistryRecord(record2.serviceKey); + await persistRuntimeServiceRecord(record2.db, record2); +} +async function markPersistedRuntimeServicesStoppedForExecutionWorkspace(input) { + const now2 = /* @__PURE__ */ new Date(); + await input.db.update(workspaceRuntimeServices).set({ + status: "stopped", + healthStatus: "unknown", + stoppedAt: now2, + lastUsedAt: now2, + updatedAt: now2 + }).where( + and( + eq(workspaceRuntimeServices.executionWorkspaceId, input.executionWorkspaceId), + inArray(workspaceRuntimeServices.status, ["starting", "running"]) + ) + ); +} +function registerRuntimeService(db, record2) { + record2.db = db; + runtimeServicesById.set(record2.id, record2); + if (record2.reuseKey) { + runtimeServicesByReuseKey.set(record2.reuseKey, record2.id); + } + record2.child?.on("exit", (code, signal) => { + const current = runtimeServicesById.get(record2.id); + if (!current) return; + clearIdleTimer(current); + current.status = code === 0 || signal === "SIGTERM" ? "stopped" : "failed"; + current.healthStatus = current.status === "failed" ? "unhealthy" : "unknown"; + current.lastUsedAt = (/* @__PURE__ */ new Date()).toISOString(); + current.stoppedAt = (/* @__PURE__ */ new Date()).toISOString(); + runtimeServicesById.delete(current.id); + if (current.reuseKey && runtimeServicesByReuseKey.get(current.reuseKey) === current.id) { + runtimeServicesByReuseKey.delete(current.reuseKey); + } + void removeLocalServiceRegistryRecord(current.serviceKey); + void persistRuntimeServiceRecord(db, current); + }); +} +function readRuntimeServiceEntries(config3) { + return listWorkspaceServiceCommandDefinitions(parseObject4(config3.workspaceRuntime)).map((command) => command.rawConfig); +} +function listConfiguredRuntimeServiceEntries(config3) { + return readRuntimeServiceEntries(config3); +} +function readConfiguredServiceStates(config3) { + const raw = parseObject4(config3.serviceStates); + const states = {}; + for (const [key, value] of Object.entries(raw)) { + if (value === "running" || value === "stopped") { + states[key] = value; + } + } + return states; +} +function buildWorkspaceRuntimeDesiredStatePatch(input) { + const configuredServices = listConfiguredRuntimeServiceEntries(input.config); + const fallbackState = input.currentDesiredState === "running" ? "running" : "stopped"; + const nextServiceStates = {}; + for (let index2 = 0; index2 < configuredServices.length; index2 += 1) { + nextServiceStates[String(index2)] = input.currentServiceStates?.[String(index2)] ?? fallbackState; + } + const nextState = input.action === "stop" ? "stopped" : "running"; + if (input.serviceIndex === void 0 || input.serviceIndex === null) { + for (let index2 = 0; index2 < configuredServices.length; index2 += 1) { + nextServiceStates[String(index2)] = nextState; + } + } else if (input.serviceIndex >= 0 && input.serviceIndex < configuredServices.length) { + nextServiceStates[String(input.serviceIndex)] = nextState; + } + const desiredState = Object.values(nextServiceStates).some((state2) => state2 === "running") ? "running" : "stopped"; + return { + desiredState, + serviceStates: Object.keys(nextServiceStates).length > 0 ? nextServiceStates : null + }; +} +function selectRuntimeServiceEntries(input) { + const entries2 = listConfiguredRuntimeServiceEntries(input.config); + const states = input.serviceStates ?? readConfiguredServiceStates(input.config); + const fallbackState = input.defaultDesiredState === "running" ? "running" : "stopped"; + return entries2.filter((_, index2) => { + if (input.serviceIndex !== void 0 && input.serviceIndex !== null) { + return index2 === input.serviceIndex; + } + if (!input.respectDesiredStates) return true; + return (states[String(index2)] ?? fallbackState) === "running"; + }); +} +async function ensureRuntimeServicesForRun(input) { + const rawServices = readRuntimeServiceEntries(input.config); + const acquiredServiceIds = []; + const refs = []; + runtimeServiceLeasesByRun.set(input.runId, acquiredServiceIds); + try { + for (const service of rawServices) { + const { scopeType, scopeId } = resolveServiceScopeId({ + service, + workspace: input.workspace, + executionWorkspaceId: input.executionWorkspaceId, + issue: input.issue, + runId: input.runId, + agent: input.agent + }); + const reuseKey = resolveRuntimeServiceReuseIdentity({ + service, + workspace: input.workspace, + agent: input.agent, + issue: input.issue, + adapterEnv: input.adapterEnv, + scopeType, + scopeId + }).reuseKey; + if (reuseKey) { + const existingId = runtimeServicesByReuseKey.get(reuseKey); + const existing = existingId ? runtimeServicesById.get(existingId) : null; + if (existing && existing.status === "running") { + existing.leaseRunIds.add(input.runId); + existing.lastUsedAt = (/* @__PURE__ */ new Date()).toISOString(); + existing.stoppedAt = null; + clearIdleTimer(existing); + void touchLocalServiceRegistryRecord(existing.serviceKey, { + runtimeServiceId: existing.id, + lastSeenAt: existing.lastUsedAt + }); + await persistRuntimeServiceRecord(input.db, existing); + acquiredServiceIds.push(existing.id); + refs.push(toRuntimeServiceRef(existing, { reused: true })); + continue; + } + } + const record2 = await startLocalRuntimeService({ + db: input.db, + runId: input.runId, + agent: input.agent, + issue: input.issue, + workspace: input.workspace, + executionWorkspaceId: input.executionWorkspaceId, + adapterEnv: input.adapterEnv, + service, + onLog: input.onLog, + reuseKey, + scopeType, + scopeId + }); + registerRuntimeService(input.db, record2); + await persistRuntimeServiceRecord(input.db, record2); + acquiredServiceIds.push(record2.id); + refs.push(toRuntimeServiceRef(record2)); + } + } catch (err) { + await releaseRuntimeServicesForRun(input.runId); + throw err; + } + return refs; +} +async function startRuntimeServicesForWorkspaceControl(input) { + const rawServices = selectRuntimeServiceEntries({ + config: input.config, + serviceIndex: input.serviceIndex, + respectDesiredStates: input.respectDesiredStates, + defaultDesiredState: input.config.desiredState === "running" ? "running" : "stopped", + serviceStates: readConfiguredServiceStates(input.config) + }); + const refs = []; + const invocationId = input.invocationId ?? randomUUID4(); + for (const service of rawServices) { + const { scopeType, scopeId } = resolveServiceScopeId({ + service, + workspace: input.workspace, + executionWorkspaceId: input.executionWorkspaceId, + issue: input.issue, + runId: invocationId, + agent: input.actor + }); + const reuseKey = resolveRuntimeServiceReuseIdentity({ + service, + workspace: input.workspace, + agent: input.actor, + issue: input.issue, + adapterEnv: input.adapterEnv, + scopeType, + scopeId + }).reuseKey; + if (reuseKey) { + const existingId = runtimeServicesByReuseKey.get(reuseKey); + const existing = existingId ? runtimeServicesById.get(existingId) : null; + if (existing && existing.status === "running") { + existing.lastUsedAt = (/* @__PURE__ */ new Date()).toISOString(); + existing.stoppedAt = null; + clearIdleTimer(existing); + void touchLocalServiceRegistryRecord(existing.serviceKey, { + runtimeServiceId: existing.id, + lastSeenAt: existing.lastUsedAt + }); + await persistRuntimeServiceRecord(input.db, existing); + refs.push(toRuntimeServiceRef(existing, { reused: true })); + continue; + } + } + const record2 = await startLocalRuntimeService({ + db: input.db, + runId: invocationId, + leaseRunId: null, + startedByRunId: null, + agent: input.actor, + issue: input.issue, + workspace: input.workspace, + executionWorkspaceId: input.executionWorkspaceId, + adapterEnv: input.adapterEnv, + service, + onLog: input.onLog, + reuseKey, + scopeType, + scopeId + }); + registerRuntimeService(input.db, record2); + await persistRuntimeServiceRecord(input.db, record2); + refs.push(toRuntimeServiceRef(record2)); + } + return refs; +} +async function releaseRuntimeServicesForRun(runId) { + const acquired = runtimeServiceLeasesByRun.get(runId) ?? []; + runtimeServiceLeasesByRun.delete(runId); + for (const serviceId of acquired) { + const record2 = runtimeServicesById.get(serviceId); + if (!record2) continue; + record2.leaseRunIds.delete(runId); + record2.lastUsedAt = (/* @__PURE__ */ new Date()).toISOString(); + const stopType = asString12(record2.stopPolicy?.type, record2.lifecycle === "ephemeral" ? "on_run_finish" : "manual"); + await persistRuntimeServiceRecord(record2.db, record2); + if (record2.leaseRunIds.size === 0) { + if (record2.lifecycle === "ephemeral" || stopType === "on_run_finish") { + await stopRuntimeService(serviceId); + continue; + } + scheduleIdleStop(record2); + } + } +} +async function stopRuntimeServicesForExecutionWorkspace(input) { + const normalizedWorkspaceCwd = input.workspaceCwd ? path37.resolve(input.workspaceCwd) : null; + const matchingServiceIds = Array.from(runtimeServicesById.values()).filter((record2) => { + if (input.runtimeServiceId) return record2.id === input.runtimeServiceId; + if (record2.executionWorkspaceId === input.executionWorkspaceId) return true; + if (!normalizedWorkspaceCwd || !record2.cwd) return false; + const resolvedCwd = path37.resolve(record2.cwd); + return resolvedCwd === normalizedWorkspaceCwd || resolvedCwd.startsWith(`${normalizedWorkspaceCwd}${path37.sep}`); + }).map((record2) => record2.id); + for (const serviceId of matchingServiceIds) { + await stopRuntimeService(serviceId); + } + if (input.db) { + if (input.runtimeServiceId) { + const now2 = /* @__PURE__ */ new Date(); + await input.db.update(workspaceRuntimeServices).set({ + status: "stopped", + healthStatus: "unknown", + stoppedAt: now2, + lastUsedAt: now2, + updatedAt: now2 + }).where(eq(workspaceRuntimeServices.id, input.runtimeServiceId)); + } else { + await markPersistedRuntimeServicesStoppedForExecutionWorkspace({ + db: input.db, + executionWorkspaceId: input.executionWorkspaceId + }); + } + } +} +async function stopRuntimeServicesForProjectWorkspace(input) { + const matchingServiceIds = Array.from(runtimeServicesById.values()).filter((record2) => { + if (input.runtimeServiceId) return record2.id === input.runtimeServiceId; + return record2.projectWorkspaceId === input.projectWorkspaceId && record2.scopeType === "project_workspace"; + }).map((record2) => record2.id); + for (const serviceId of matchingServiceIds) { + await stopRuntimeService(serviceId); + } + if (input.db) { + const now2 = /* @__PURE__ */ new Date(); + await input.db.update(workspaceRuntimeServices).set({ + status: "stopped", + healthStatus: "unknown", + stoppedAt: now2, + lastUsedAt: now2, + updatedAt: now2 + }).where( + input.runtimeServiceId ? eq(workspaceRuntimeServices.id, input.runtimeServiceId) : and( + eq(workspaceRuntimeServices.projectWorkspaceId, input.projectWorkspaceId), + eq(workspaceRuntimeServices.scopeType, "project_workspace"), + inArray(workspaceRuntimeServices.status, ["starting", "running"]) + ) + ); + } +} +async function persistAdapterManagedRuntimeServices(input) { + const refs = normalizeAdapterManagedRuntimeServices(input); + if (refs.length === 0) return refs; + const existingRows = await input.db.select().from(workspaceRuntimeServices).where(inArray(workspaceRuntimeServices.id, refs.map((ref) => ref.id))); + const existingById = new Map(existingRows.map((row) => [row.id, row])); + for (const ref of refs) { + const existing = existingById.get(ref.id); + const startedAt = existing?.startedAt ?? new Date(ref.startedAt); + const createdAt = existing?.createdAt ?? /* @__PURE__ */ new Date(); + await input.db.insert(workspaceRuntimeServices).values({ + id: ref.id, + companyId: ref.companyId, + projectId: ref.projectId, + projectWorkspaceId: ref.projectWorkspaceId, + executionWorkspaceId: ref.executionWorkspaceId, + issueId: ref.issueId, + scopeType: ref.scopeType, + scopeId: ref.scopeId, + serviceName: ref.serviceName, + status: ref.status, + lifecycle: ref.lifecycle, + reuseKey: ref.reuseKey, + command: ref.command, + cwd: ref.cwd, + port: ref.port, + url: ref.url, + provider: ref.provider, + providerRef: ref.providerRef, + ownerAgentId: ref.ownerAgentId, + startedByRunId: ref.startedByRunId, + lastUsedAt: new Date(ref.lastUsedAt), + startedAt, + stoppedAt: ref.stoppedAt ? new Date(ref.stoppedAt) : null, + stopPolicy: ref.stopPolicy, + healthStatus: ref.healthStatus, + createdAt, + updatedAt: /* @__PURE__ */ new Date() + }).onConflictDoUpdate({ + target: workspaceRuntimeServices.id, + set: { + projectId: ref.projectId, + projectWorkspaceId: ref.projectWorkspaceId, + executionWorkspaceId: ref.executionWorkspaceId, + issueId: ref.issueId, + scopeType: ref.scopeType, + scopeId: ref.scopeId, + serviceName: ref.serviceName, + status: ref.status, + lifecycle: ref.lifecycle, + reuseKey: ref.reuseKey, + command: ref.command, + cwd: ref.cwd, + port: ref.port, + url: ref.url, + provider: ref.provider, + providerRef: ref.providerRef, + ownerAgentId: ref.ownerAgentId, + startedByRunId: ref.startedByRunId, + lastUsedAt: new Date(ref.lastUsedAt), + startedAt, + stoppedAt: ref.stoppedAt ? new Date(ref.stoppedAt) : null, + stopPolicy: ref.stopPolicy, + healthStatus: ref.healthStatus, + updatedAt: /* @__PURE__ */ new Date() + } + }); + } + return refs; +} +function buildWorkspaceReadyComment(input) { + const lines = ["## Workspace Ready", ""]; + lines.push(`- Strategy: \`${input.workspace.strategy}\``); + if (input.workspace.branchName) lines.push(`- Branch: \`${input.workspace.branchName}\``); + lines.push(`- CWD: \`${input.workspace.cwd}\``); + if (input.workspace.worktreePath && input.workspace.worktreePath !== input.workspace.cwd) { + lines.push(`- Worktree: \`${input.workspace.worktreePath}\``); + } + for (const service of input.runtimeServices) { + const detail = service.url ? `${service.serviceName}: ${service.url}` : `${service.serviceName}: running`; + const suffix = service.reused ? " (reused)" : ""; + lines.push(`- Service: ${detail}${suffix}`); + } + return lines.join("\n"); +} + +// server/src/services/workspace-operations.ts +init_src2(); +init_drizzle_orm(); +import { randomUUID as randomUUID5 } from "node:crypto"; + +// server/src/services/workspace-operation-log-store.ts +import { createReadStream as createReadStream2, promises as fs31 } from "node:fs"; +import path38 from "node:path"; +import { createHash as createHash13 } from "node:crypto"; +function safeSegments2(...segments) { + return segments.map((segment) => segment.replace(/[^a-zA-Z0-9._-]/g, "_")); +} +function resolveWithin2(basePath, relativePath) { + const resolved = path38.resolve(basePath, relativePath); + const base = path38.resolve(basePath) + path38.sep; + if (!resolved.startsWith(base) && resolved !== path38.resolve(basePath)) { + throw new Error("Invalid log path"); + } + return resolved; +} +function createLocalFileWorkspaceOperationLogStore(basePath) { + async function ensureDir(relativeDir) { + const dir = resolveWithin2(basePath, relativeDir); + await fs31.mkdir(dir, { recursive: true }); + } + async function readFileRange(filePath, offset, limitBytes) { + const stat5 = await fs31.stat(filePath).catch(() => null); + if (!stat5) throw notFound("Workspace operation log not found"); + const start = Math.max(0, Math.min(offset, stat5.size)); + const end = Math.max(start, Math.min(start + limitBytes - 1, stat5.size - 1)); + if (start > end) { + return { content: "", nextOffset: start }; + } + const chunks = []; + await new Promise((resolve4, reject) => { + const stream = createReadStream2(filePath, { start, end }); + stream.on("data", (chunk) => { + chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)); + }); + stream.on("error", reject); + stream.on("end", () => resolve4()); + }); + const content = Buffer.concat(chunks).toString("utf8"); + const nextOffset = end + 1 < stat5.size ? end + 1 : void 0; + return { content, nextOffset }; + } + async function sha256File(filePath) { + return new Promise((resolve4, reject) => { + const hash2 = createHash13("sha256"); + const stream = createReadStream2(filePath); + stream.on("data", (chunk) => hash2.update(chunk)); + stream.on("error", reject); + stream.on("end", () => resolve4(hash2.digest("hex"))); + }); + } + return { + async begin(input) { + const [companyId] = safeSegments2(input.companyId); + const operationId = safeSegments2(input.operationId)[0]; + const relDir = companyId; + const relPath = path38.join(relDir, `${operationId}.ndjson`); + await ensureDir(relDir); + const absPath = resolveWithin2(basePath, relPath); + await fs31.writeFile(absPath, "", "utf8"); + return { store: "local_file", logRef: relPath }; + }, + async append(handle, event) { + if (handle.store !== "local_file") return; + const absPath = resolveWithin2(basePath, handle.logRef); + const line3 = JSON.stringify({ + ts: event.ts, + stream: event.stream, + chunk: event.chunk + }); + await fs31.appendFile(absPath, `${line3} +`, "utf8"); + }, + async finalize(handle) { + if (handle.store !== "local_file") { + return { bytes: 0, compressed: false }; + } + const absPath = resolveWithin2(basePath, handle.logRef); + const stat5 = await fs31.stat(absPath).catch(() => null); + if (!stat5) throw notFound("Workspace operation log not found"); + const hash2 = await sha256File(absPath); + return { + bytes: stat5.size, + sha256: hash2, + compressed: false + }; + }, + async read(handle, opts) { + if (handle.store !== "local_file") { + throw notFound("Workspace operation log not found"); + } + const absPath = resolveWithin2(basePath, handle.logRef); + const offset = opts?.offset ?? 0; + const limitBytes = opts?.limitBytes ?? 256e3; + return readFileRange(absPath, offset, limitBytes); + } + }; +} +var cachedStore2 = null; +function getWorkspaceOperationLogStore() { + if (cachedStore2) return cachedStore2; + const basePath = process.env.WORKSPACE_OPERATION_LOG_BASE_PATH ?? path38.resolve(resolveTaskcoreInstanceRoot(), "data", "workspace-operation-logs"); + cachedStore2 = createLocalFileWorkspaceOperationLogStore(basePath); + return cachedStore2; +} + +// server/src/services/workspace-operations.ts +function toWorkspaceOperation(row) { + return { + id: row.id, + companyId: row.companyId, + executionWorkspaceId: row.executionWorkspaceId ?? null, + heartbeatRunId: row.heartbeatRunId ?? null, + phase: row.phase, + command: row.command ?? null, + cwd: row.cwd ?? null, + status: row.status, + exitCode: row.exitCode ?? null, + logStore: row.logStore ?? null, + logRef: row.logRef ?? null, + logBytes: row.logBytes ?? null, + logSha256: row.logSha256 ?? null, + logCompressed: row.logCompressed, + stdoutExcerpt: row.stdoutExcerpt ?? null, + stderrExcerpt: row.stderrExcerpt ?? null, + metadata: row.metadata ?? null, + startedAt: row.startedAt, + finishedAt: row.finishedAt ?? null, + createdAt: row.createdAt, + updatedAt: row.updatedAt + }; +} +function appendExcerpt(current, chunk) { + return `${current}${chunk}`.slice(-4096); +} +function combineMetadata(base, patch) { + if (!base && !patch) return null; + return { + ...base ?? {}, + ...patch ?? {} + }; +} +function workspaceOperationService(db) { + const instanceSettings2 = instanceSettingsService(db); + const logStore = getWorkspaceOperationLogStore(); + async function getById(id) { + const row = await db.select().from(workspaceOperations).where(eq(workspaceOperations.id, id)).then((rows) => rows[0] ?? null); + return row ? toWorkspaceOperation(row) : null; + } + return { + getById, + createRecorder(input) { + let executionWorkspaceId = input.executionWorkspaceId ?? null; + const createdIds = []; + return { + async attachExecutionWorkspaceId(nextExecutionWorkspaceId) { + executionWorkspaceId = nextExecutionWorkspaceId ?? null; + if (!executionWorkspaceId || createdIds.length === 0) return; + await db.update(workspaceOperations).set({ + executionWorkspaceId, + updatedAt: /* @__PURE__ */ new Date() + }).where(inArray(workspaceOperations.id, createdIds)); + }, + async recordOperation(recordInput) { + const currentUserRedactionOptions = { + enabled: (await instanceSettings2.getGeneral()).censorUsernameInLogs + }; + const startedAt = /* @__PURE__ */ new Date(); + const id = randomUUID5(); + const handle = await logStore.begin({ + companyId: input.companyId, + operationId: id + }); + let stdoutExcerpt = ""; + let stderrExcerpt = ""; + const append = async (stream, chunk) => { + if (!chunk) return; + const sanitizedChunk = redactCurrentUserText(chunk, currentUserRedactionOptions); + if (stream === "stdout") stdoutExcerpt = appendExcerpt(stdoutExcerpt, sanitizedChunk); + if (stream === "stderr") stderrExcerpt = appendExcerpt(stderrExcerpt, sanitizedChunk); + await logStore.append(handle, { + stream, + chunk: sanitizedChunk, + ts: (/* @__PURE__ */ new Date()).toISOString() + }); + }; + await db.insert(workspaceOperations).values({ + id, + companyId: input.companyId, + executionWorkspaceId, + heartbeatRunId: input.heartbeatRunId ?? null, + phase: recordInput.phase, + command: recordInput.command ?? null, + cwd: recordInput.cwd ?? null, + status: "running", + logStore: handle.store, + logRef: handle.logRef, + metadata: redactCurrentUserValue( + recordInput.metadata ?? null, + currentUserRedactionOptions + ), + startedAt + }); + createdIds.push(id); + try { + const result = await recordInput.run(); + await append("system", result.system ?? null); + await append("stdout", result.stdout ?? null); + await append("stderr", result.stderr ?? null); + const finalized = await logStore.finalize(handle); + const finishedAt = /* @__PURE__ */ new Date(); + const row = await db.update(workspaceOperations).set({ + executionWorkspaceId, + status: result.status ?? "succeeded", + exitCode: result.exitCode ?? null, + stdoutExcerpt: stdoutExcerpt || null, + stderrExcerpt: stderrExcerpt || null, + logBytes: finalized.bytes, + logSha256: finalized.sha256, + logCompressed: finalized.compressed, + metadata: redactCurrentUserValue( + combineMetadata(recordInput.metadata, result.metadata), + currentUserRedactionOptions + ), + finishedAt, + updatedAt: finishedAt + }).where(eq(workspaceOperations.id, id)).returning().then((rows) => rows[0] ?? null); + if (!row) throw notFound("Workspace operation not found"); + return toWorkspaceOperation(row); + } catch (error50) { + await append("stderr", error50 instanceof Error ? error50.message : String(error50)); + const finalized = await logStore.finalize(handle).catch(() => null); + const finishedAt = /* @__PURE__ */ new Date(); + await db.update(workspaceOperations).set({ + executionWorkspaceId, + status: "failed", + stdoutExcerpt: stdoutExcerpt || null, + stderrExcerpt: stderrExcerpt || null, + logBytes: finalized?.bytes ?? null, + logSha256: finalized?.sha256 ?? null, + logCompressed: finalized?.compressed ?? false, + finishedAt, + updatedAt: finishedAt + }).where(eq(workspaceOperations.id, id)); + throw error50; + } + } + }; + }, + listForRun: async (runId, executionWorkspaceId) => { + const conditions = [eq(workspaceOperations.heartbeatRunId, runId)]; + if (executionWorkspaceId) { + const cleanupCondition = and( + eq(workspaceOperations.executionWorkspaceId, executionWorkspaceId), + isNull(workspaceOperations.heartbeatRunId) + ); + if (cleanupCondition) conditions.push(cleanupCondition); + } + const rows = await db.select().from(workspaceOperations).where(conditions.length === 1 ? conditions[0] : or(...conditions)).orderBy(asc(workspaceOperations.startedAt), asc(workspaceOperations.createdAt), asc(workspaceOperations.id)); + return rows.map(toWorkspaceOperation); + }, + listForExecutionWorkspace: async (executionWorkspaceId) => { + const rows = await db.select().from(workspaceOperations).where(eq(workspaceOperations.executionWorkspaceId, executionWorkspaceId)).orderBy(desc(workspaceOperations.startedAt), desc(workspaceOperations.createdAt)); + return rows.map(toWorkspaceOperation); + }, + readLog: async (operationId, opts) => { + const operation2 = await getById(operationId); + if (!operation2) throw notFound("Workspace operation not found"); + if (!operation2.logStore || !operation2.logRef) throw notFound("Workspace operation log not found"); + const result = await logStore.read( + { + store: operation2.logStore, + logRef: operation2.logRef + }, + opts + ); + return { + operationId, + store: operation2.logStore, + logRef: operation2.logRef, + ...result, + content: redactCurrentUserText(result.content, { + enabled: (await instanceSettings2.getGeneral()).censorUsernameInLogs + }) + }; + } + }; +} + +// server/src/services/heartbeat.ts +var MAX_LIVE_LOG_CHUNK_BYTES = 8 * 1024; +var MAX_PERSISTED_LOG_CHUNK_CHARS = 64 * 1024; +var HEARTBEAT_MAX_CONCURRENT_RUNS_DEFAULT = 1; +var HEARTBEAT_MAX_CONCURRENT_RUNS_MAX = 10; +var DEFERRED_WAKE_CONTEXT_KEY = "_taskcoreWakeContext"; +var WAKE_COMMENT_IDS_KEY = "wakeCommentIds"; +var TASKCORE_WAKE_PAYLOAD_KEY = "taskcoreWake"; +var TASKCORE_HARNESS_CHECKOUT_KEY = "taskcoreHarnessCheckedOut"; +var DETACHED_PROCESS_ERROR_CODE = "process_detached"; +var startLocksByAgent = /* @__PURE__ */ new Map(); +var REPO_ONLY_CWD_SENTINEL2 = "/__taskcore_repo_only__"; +var MANAGED_WORKSPACE_GIT_CLONE_TIMEOUT_MS = 10 * 60 * 1e3; +var MAX_INLINE_WAKE_COMMENTS = 8; +var MAX_INLINE_WAKE_COMMENT_BODY_CHARS = 4e3; +var MAX_INLINE_WAKE_COMMENT_BODY_TOTAL_CHARS = 12e3; +var execFile5 = promisify5(execFileCallback); +var ACTIVE_HEARTBEAT_RUN_STATUSES = ["queued", "running"]; +var SESSIONED_LOCAL_ADAPTERS = /* @__PURE__ */ new Set([ + "claude_local", + "codex_local", + "cursor", + "gemini_local", + "opencode_local", + "pi_local" +]); +var INLINE_BASE64_IMAGE_DATA_RE = /("type":"image","source":\{"type":"base64","data":")([A-Za-z0-9+/=]{1024,})(")/g; +async function resolveExecutionRunAdapterConfig(input) { + const { config: resolvedConfig, secretKeys } = await input.secretsSvc.resolveAdapterConfigForRuntime( + input.companyId, + input.executionRunConfig + ); + const projectEnvResolution = input.projectEnv ? await input.secretsSvc.resolveEnvBindings(input.companyId, input.projectEnv) : { env: {}, secretKeys: /* @__PURE__ */ new Set() }; + if (Object.keys(projectEnvResolution.env).length > 0) { + resolvedConfig.env = { + ...parseObject4(resolvedConfig.env), + ...projectEnvResolution.env + }; + for (const key of projectEnvResolution.secretKeys) { + secretKeys.add(key); + } + } + return { resolvedConfig, secretKeys }; +} +function extractMentionedSkillIdsFromSources(sources) { + const mentionedIds = /* @__PURE__ */ new Set(); + for (const source of sources) { + if (typeof source !== "string" || source.length === 0) continue; + for (const skillId of extractSkillMentionIds(source)) { + mentionedIds.add(skillId); + } + } + return [...mentionedIds]; +} +function applyRunScopedMentionedSkillKeys(config3, skillKeys) { + const normalizedSkillKeys = Array.from( + new Set( + skillKeys.map((value) => value.trim()).filter(Boolean) + ) + ); + if (normalizedSkillKeys.length === 0) return config3; + const existingPreference = readTaskcoreSkillSyncPreference(config3); + return writeTaskcoreSkillSyncPreference(config3, [ + ...existingPreference.desiredSkills, + ...normalizedSkillKeys + ]); +} +async function resolveRunScopedMentionedSkillKeys(input) { + if (!input.issueId) return []; + const issue2 = await input.db.select({ + title: issues.title, + description: issues.description + }).from(issues).where(and(eq(issues.id, input.issueId), eq(issues.companyId, input.companyId))).then((rows) => rows[0] ?? null); + if (!issue2) return []; + const comments = await input.db.select({ body: issueComments.body }).from(issueComments).where( + and( + eq(issueComments.issueId, input.issueId), + eq(issueComments.companyId, input.companyId) + ) + ); + const mentionedSkillIds = extractMentionedSkillIdsFromSources([ + issue2.title, + issue2.description ?? "", + ...comments.map((comment) => comment.body) + ]); + if (mentionedSkillIds.length === 0) return []; + const skillRows = await input.db.select({ + id: companySkills.id, + key: companySkills.key + }).from(companySkills).where( + and( + eq(companySkills.companyId, input.companyId), + inArray(companySkills.id, mentionedSkillIds) + ) + ); + const skillKeyById = new Map(skillRows.map((row) => [row.id, row.key])); + return mentionedSkillIds.map((skillId) => skillKeyById.get(skillId) ?? null).filter((skillKey) => Boolean(skillKey)); +} +function applyPersistedExecutionWorkspaceConfig(input) { + const nextConfig = { ...input.config }; + if (input.mode !== "agent_default") { + if (input.workspaceConfig?.workspaceRuntime === null) { + delete nextConfig.workspaceRuntime; + } else if (input.workspaceConfig?.workspaceRuntime) { + nextConfig.workspaceRuntime = { ...input.workspaceConfig.workspaceRuntime }; + } + } + if (input.workspaceConfig && input.mode === "isolated_workspace") { + const nextStrategy = parseObject4(nextConfig.workspaceStrategy); + if (input.workspaceConfig.provisionCommand === null) delete nextStrategy.provisionCommand; + else nextStrategy.provisionCommand = input.workspaceConfig.provisionCommand; + if (input.workspaceConfig.teardownCommand === null) delete nextStrategy.teardownCommand; + else nextStrategy.teardownCommand = input.workspaceConfig.teardownCommand; + nextConfig.workspaceStrategy = nextStrategy; + } + return nextConfig; +} +function stripWorkspaceRuntimeFromExecutionRunConfig(config3) { + const nextConfig = { ...config3 }; + delete nextConfig.workspaceRuntime; + return nextConfig; +} +function buildRealizedExecutionWorkspaceFromPersisted(input) { + const cwd = readNonEmptyString10(input.workspace.cwd) ?? readNonEmptyString10(input.workspace.providerRef); + if (!cwd) { + return null; + } + const strategy = input.workspace.strategyType === "git_worktree" ? "git_worktree" : "project_primary"; + return { + baseCwd: input.base.baseCwd, + source: input.workspace.mode === "shared_workspace" ? "project_primary" : "task_session", + projectId: input.workspace.projectId ?? input.base.projectId, + workspaceId: input.workspace.projectWorkspaceId ?? input.base.workspaceId, + repoUrl: input.workspace.repoUrl ?? input.base.repoUrl, + repoRef: input.workspace.baseRef ?? input.base.repoRef, + strategy, + cwd, + branchName: input.workspace.branchName ?? null, + worktreePath: strategy === "git_worktree" ? readNonEmptyString10(input.workspace.providerRef) ?? cwd : null, + warnings: [], + created: false + }; +} +function buildExecutionWorkspaceConfigSnapshot(config3) { + const strategy = parseObject4(config3.workspaceStrategy); + const snapshot = {}; + if ("workspaceStrategy" in config3) { + snapshot.provisionCommand = typeof strategy.provisionCommand === "string" ? strategy.provisionCommand : null; + snapshot.teardownCommand = typeof strategy.teardownCommand === "string" ? strategy.teardownCommand : null; + } + if ("workspaceRuntime" in config3) { + const workspaceRuntime = parseObject4(config3.workspaceRuntime); + snapshot.workspaceRuntime = Object.keys(workspaceRuntime).length > 0 ? workspaceRuntime : null; + } + const hasSnapshot = Object.values(snapshot).some((value) => { + if (value === null) return false; + if (typeof value === "object") return Object.keys(value).length > 0; + return true; + }); + return hasSnapshot ? snapshot : null; +} +function deriveRepoNameFromRepoUrl2(repoUrl) { + const trimmed = repoUrl?.trim() ?? ""; + if (!trimmed) return null; + try { + const parsed = new URL(trimmed); + const cleanedPath = parsed.pathname.replace(/\/+$/, ""); + const repoName = cleanedPath.split("/").filter(Boolean).pop()?.replace(/\.git$/i, "") ?? ""; + return repoName || null; + } catch { + return null; + } +} +async function ensureManagedProjectWorkspace(input) { + const cwd = resolveManagedProjectWorkspaceDir({ + companyId: input.companyId, + projectId: input.projectId, + repoName: deriveRepoNameFromRepoUrl2(input.repoUrl) + }); + await fs32.mkdir(path39.dirname(cwd), { recursive: true }); + const stats = await fs32.stat(cwd).catch(() => null); + if (!input.repoUrl) { + if (!stats) { + await fs32.mkdir(cwd, { recursive: true }); + } + return { cwd, warning: null }; + } + const gitDirExists = await fs32.stat(path39.resolve(cwd, ".git")).then((entry) => entry.isDirectory()).catch(() => false); + if (gitDirExists) { + return { cwd, warning: null }; + } + if (stats) { + const entries2 = await fs32.readdir(cwd).catch(() => []); + if (entries2.length > 0) { + return { + cwd, + warning: `Managed workspace path "${cwd}" already exists but is not a git checkout. Using it as-is.` + }; + } + await fs32.rm(cwd, { recursive: true, force: true }); + } + try { + await execFile5("git", ["clone", input.repoUrl, cwd], { + env: sanitizeRuntimeServiceBaseEnv(process.env), + timeout: MANAGED_WORKSPACE_GIT_CLONE_TIMEOUT_MS + }); + return { cwd, warning: null }; + } catch (error50) { + const reason = error50 instanceof Error ? error50.message : String(error50); + throw new Error(`Failed to prepare managed checkout for "${input.repoUrl}" at "${cwd}": ${reason}`); + } +} +var heartbeatRunProcessGroupIdColumn = heartbeatRuns.processGroupId ?? sql`NULL`.as("processGroupId"); +var heartbeatRunListColumns = { + id: heartbeatRuns.id, + companyId: heartbeatRuns.companyId, + agentId: heartbeatRuns.agentId, + invocationSource: heartbeatRuns.invocationSource, + triggerDetail: heartbeatRuns.triggerDetail, + status: heartbeatRuns.status, + startedAt: heartbeatRuns.startedAt, + finishedAt: heartbeatRuns.finishedAt, + error: heartbeatRuns.error, + wakeupRequestId: heartbeatRuns.wakeupRequestId, + exitCode: heartbeatRuns.exitCode, + signal: heartbeatRuns.signal, + usageJson: heartbeatRuns.usageJson, + resultJson: heartbeatRuns.resultJson, + sessionIdBefore: heartbeatRuns.sessionIdBefore, + sessionIdAfter: heartbeatRuns.sessionIdAfter, + logStore: heartbeatRuns.logStore, + logRef: heartbeatRuns.logRef, + logBytes: heartbeatRuns.logBytes, + logSha256: heartbeatRuns.logSha256, + logCompressed: heartbeatRuns.logCompressed, + stdoutExcerpt: sql`NULL`.as("stdoutExcerpt"), + stderrExcerpt: sql`NULL`.as("stderrExcerpt"), + errorCode: heartbeatRuns.errorCode, + externalRunId: heartbeatRuns.externalRunId, + processPid: heartbeatRuns.processPid, + processGroupId: heartbeatRunProcessGroupIdColumn, + processStartedAt: heartbeatRuns.processStartedAt, + retryOfRunId: heartbeatRuns.retryOfRunId, + processLossRetryCount: heartbeatRuns.processLossRetryCount, + contextSnapshot: heartbeatRuns.contextSnapshot, + createdAt: heartbeatRuns.createdAt, + updatedAt: heartbeatRuns.updatedAt +}; +var heartbeatRunIssueSummaryColumns = { + id: heartbeatRuns.id, + status: heartbeatRuns.status, + invocationSource: heartbeatRuns.invocationSource, + triggerDetail: heartbeatRuns.triggerDetail, + startedAt: heartbeatRuns.startedAt, + finishedAt: heartbeatRuns.finishedAt, + createdAt: heartbeatRuns.createdAt, + agentId: heartbeatRuns.agentId, + issueId: sql`${heartbeatRuns.contextSnapshot} ->> 'issueId'`.as("issueId") +}; +function appendExcerpt2(prev, chunk) { + return appendWithCap3(prev, chunk, MAX_EXCERPT_BYTES3); +} +function redactInlineBase64ImageData(chunk) { + return chunk.replace( + INLINE_BASE64_IMAGE_DATA_RE, + (_match, prefix, data2, suffix) => `${prefix}[omitted base64 image data: ${data2.length} chars]${suffix}` + ); +} +function compactRunLogChunk(chunk, maxChars = MAX_PERSISTED_LOG_CHUNK_CHARS) { + const normalized = redactInlineBase64ImageData(chunk); + if (normalized.length <= maxChars) return normalized; + const headChars = Math.max(0, Math.floor(maxChars * 0.6)); + const tailChars = Math.max(0, Math.floor(maxChars * 0.25)); + const omittedChars = Math.max(0, normalized.length - headChars - tailChars); + const marker = ` +[taskcore truncated run log chunk: omitted ${omittedChars} chars] +`; + return `${normalized.slice(0, headChars)}${marker}${normalized.slice(normalized.length - tailChars)}`; +} +function normalizeMaxConcurrentRuns(value) { + const parsed = Math.floor(asNumber3(value, HEARTBEAT_MAX_CONCURRENT_RUNS_DEFAULT)); + if (!Number.isFinite(parsed)) return HEARTBEAT_MAX_CONCURRENT_RUNS_DEFAULT; + return Math.max(HEARTBEAT_MAX_CONCURRENT_RUNS_DEFAULT, Math.min(HEARTBEAT_MAX_CONCURRENT_RUNS_MAX, parsed)); +} +async function withAgentStartLock(agentId, fn) { + const previous = startLocksByAgent.get(agentId) ?? Promise.resolve(); + const run = previous.then(fn); + const marker = run.then( + () => void 0, + () => void 0 + ); + startLocksByAgent.set(agentId, marker); + try { + return await run; + } finally { + if (startLocksByAgent.get(agentId) === marker) { + startLocksByAgent.delete(agentId); + } + } +} +function prioritizeProjectWorkspaceCandidatesForRun(rows, preferredWorkspaceId) { + if (!preferredWorkspaceId) return rows; + const preferredIndex = rows.findIndex((row) => row.id === preferredWorkspaceId); + if (preferredIndex <= 0) return rows; + return [rows[preferredIndex], ...rows.slice(0, preferredIndex), ...rows.slice(preferredIndex + 1)]; +} +function readNonEmptyString10(value) { + return typeof value === "string" && value.trim().length > 0 ? value : null; +} +function normalizeLedgerBillingType(value) { + const raw = readNonEmptyString10(value); + switch (raw) { + case "api": + case "metered_api": + return "metered_api"; + case "subscription": + case "subscription_included": + return "subscription_included"; + case "subscription_overage": + return "subscription_overage"; + case "credits": + return "credits"; + case "fixed": + return "fixed"; + default: + return "unknown"; + } +} +function resolveLedgerBiller(result) { + return readNonEmptyString10(result.biller) ?? readNonEmptyString10(result.provider) ?? "unknown"; +} +function normalizeBilledCostCents(costUsd, billingType) { + if (billingType === "subscription_included") return 0; + if (typeof costUsd !== "number" || !Number.isFinite(costUsd)) return 0; + return Math.max(0, Math.round(costUsd * 100)); +} +async function resolveLedgerScopeForRun(db, companyId, run) { + const context = parseObject4(run.contextSnapshot); + const contextIssueId = readNonEmptyString10(context.issueId); + const contextProjectId = readNonEmptyString10(context.projectId); + if (!contextIssueId) { + return { + issueId: null, + projectId: contextProjectId + }; + } + const issue2 = await db.select({ + id: issues.id, + projectId: issues.projectId + }).from(issues).where(and(eq(issues.id, contextIssueId), eq(issues.companyId, companyId))).then((rows) => rows[0] ?? null); + return { + issueId: issue2?.id ?? null, + projectId: issue2?.projectId ?? contextProjectId + }; +} +function buildExplicitResumeSessionOverride(input) { + const desiredDisplayId = truncateDisplayId( + input.resumeRunSessionIdAfter ?? input.resumeRunSessionIdBefore + ); + const taskSessionParams = normalizeSessionParams( + input.sessionCodec.deserialize(input.taskSession?.sessionParamsJson ?? null) + ); + const taskSessionDisplayId = truncateDisplayId( + input.taskSession?.sessionDisplayId ?? (input.sessionCodec.getDisplayId ? input.sessionCodec.getDisplayId(taskSessionParams) : null) ?? readNonEmptyString10(taskSessionParams?.sessionId) + ); + const canReuseTaskSessionParams = input.taskSession != null && (input.taskSession.lastRunId === input.resumeFromRunId || !!desiredDisplayId && taskSessionDisplayId === desiredDisplayId); + const sessionParams = canReuseTaskSessionParams ? taskSessionParams : desiredDisplayId ? { sessionId: desiredDisplayId } : null; + const sessionDisplayId = desiredDisplayId ?? (canReuseTaskSessionParams ? taskSessionDisplayId : null); + if (!sessionDisplayId && !sessionParams) return null; + return { + sessionDisplayId, + sessionParams + }; +} +function normalizeUsageTotals(usage) { + if (!usage) return null; + return { + inputTokens: Math.max(0, Math.floor(asNumber3(usage.inputTokens, 0))), + cachedInputTokens: Math.max(0, Math.floor(asNumber3(usage.cachedInputTokens, 0))), + outputTokens: Math.max(0, Math.floor(asNumber3(usage.outputTokens, 0))) + }; +} +function readRawUsageTotals(usageJson) { + const parsed = parseObject4(usageJson); + if (Object.keys(parsed).length === 0) return null; + const inputTokens = Math.max( + 0, + Math.floor(asNumber3(parsed.rawInputTokens, asNumber3(parsed.inputTokens, 0))) + ); + const cachedInputTokens = Math.max( + 0, + Math.floor(asNumber3(parsed.rawCachedInputTokens, asNumber3(parsed.cachedInputTokens, 0))) + ); + const outputTokens = Math.max( + 0, + Math.floor(asNumber3(parsed.rawOutputTokens, asNumber3(parsed.outputTokens, 0))) + ); + if (inputTokens <= 0 && cachedInputTokens <= 0 && outputTokens <= 0) { + return null; + } + return { + inputTokens, + cachedInputTokens, + outputTokens + }; +} +function deriveNormalizedUsageDelta(current, previous) { + if (!current) return null; + if (!previous) return { ...current }; + const inputTokens = current.inputTokens >= previous.inputTokens ? current.inputTokens - previous.inputTokens : current.inputTokens; + const cachedInputTokens = current.cachedInputTokens >= previous.cachedInputTokens ? current.cachedInputTokens - previous.cachedInputTokens : current.cachedInputTokens; + const outputTokens = current.outputTokens >= previous.outputTokens ? current.outputTokens - previous.outputTokens : current.outputTokens; + return { + inputTokens: Math.max(0, inputTokens), + cachedInputTokens: Math.max(0, cachedInputTokens), + outputTokens: Math.max(0, outputTokens) + }; +} +function formatCount(value) { + if (typeof value !== "number" || !Number.isFinite(value)) return "0"; + return value.toLocaleString("en-US"); +} +function parseSessionCompactionPolicy(agent) { + return resolveSessionCompactionPolicy(agent.adapterType, agent.runtimeConfig).policy; +} +function resolveRuntimeSessionParamsForWorkspace(input) { + const { agentId, previousSessionParams, resolvedWorkspace } = input; + const previousSessionId = readNonEmptyString10(previousSessionParams?.sessionId); + const previousCwd = readNonEmptyString10(previousSessionParams?.cwd); + if (!previousSessionId || !previousCwd) { + return { + sessionParams: previousSessionParams, + warning: null + }; + } + if (resolvedWorkspace.source !== "project_primary") { + return { + sessionParams: previousSessionParams, + warning: null + }; + } + const projectCwd = readNonEmptyString10(resolvedWorkspace.cwd); + if (!projectCwd) { + return { + sessionParams: previousSessionParams, + warning: null + }; + } + const fallbackAgentHomeCwd = resolveDefaultAgentWorkspaceDir(agentId); + if (path39.resolve(previousCwd) !== path39.resolve(fallbackAgentHomeCwd)) { + return { + sessionParams: previousSessionParams, + warning: null + }; + } + if (path39.resolve(projectCwd) === path39.resolve(previousCwd)) { + return { + sessionParams: previousSessionParams, + warning: null + }; + } + const previousWorkspaceId = readNonEmptyString10(previousSessionParams?.workspaceId); + if (previousWorkspaceId && resolvedWorkspace.workspaceId && previousWorkspaceId !== resolvedWorkspace.workspaceId) { + return { + sessionParams: previousSessionParams, + warning: null + }; + } + const migratedSessionParams = { + ...previousSessionParams ?? {}, + cwd: projectCwd + }; + if (resolvedWorkspace.workspaceId) migratedSessionParams.workspaceId = resolvedWorkspace.workspaceId; + if (resolvedWorkspace.repoUrl) migratedSessionParams.repoUrl = resolvedWorkspace.repoUrl; + if (resolvedWorkspace.repoRef) migratedSessionParams.repoRef = resolvedWorkspace.repoRef; + return { + sessionParams: migratedSessionParams, + warning: `Project workspace "${projectCwd}" is now available. Attempting to resume session "${previousSessionId}" that was previously saved in fallback workspace "${previousCwd}".` + }; +} +function parseIssueAssigneeAdapterOverrides(raw) { + const parsed = parseObject4(raw); + const parsedAdapterConfig = parseObject4(parsed.adapterConfig); + const adapterConfig = Object.keys(parsedAdapterConfig).length > 0 ? parsedAdapterConfig : null; + const useProjectWorkspace = typeof parsed.useProjectWorkspace === "boolean" ? parsed.useProjectWorkspace : null; + if (!adapterConfig && useProjectWorkspace === null) return null; + return { + adapterConfig, + useProjectWorkspace + }; +} +var HEARTBEAT_TASK_KEY = "__heartbeat__"; +function deriveTaskKey(contextSnapshot, payload2) { + return readNonEmptyString10(contextSnapshot?.taskKey) ?? readNonEmptyString10(contextSnapshot?.taskId) ?? readNonEmptyString10(contextSnapshot?.issueId) ?? readNonEmptyString10(payload2?.taskKey) ?? readNonEmptyString10(payload2?.taskId) ?? readNonEmptyString10(payload2?.issueId) ?? null; +} +function deriveTaskKeyWithHeartbeatFallback(contextSnapshot, payload2) { + const explicit = deriveTaskKey(contextSnapshot, payload2); + if (explicit) return explicit; + const wakeSource = readNonEmptyString10(contextSnapshot?.wakeSource); + if (wakeSource === "timer") return HEARTBEAT_TASK_KEY; + return null; +} +function shouldResetTaskSessionForWake(contextSnapshot) { + if (contextSnapshot?.forceFreshSession === true) return true; + const wakeReason = readNonEmptyString10(contextSnapshot?.wakeReason); + if (wakeReason === "issue_assigned" || wakeReason === "execution_review_requested" || wakeReason === "execution_approval_requested" || wakeReason === "execution_changes_requested") { + return true; + } + return false; +} +function shouldRequireIssueCommentForWake(contextSnapshot) { + const wakeReason = readNonEmptyString10(contextSnapshot?.wakeReason); + return wakeReason === "issue_assigned" || wakeReason === "execution_review_requested" || wakeReason === "execution_approval_requested" || wakeReason === "execution_changes_requested"; +} +function formatRuntimeWorkspaceWarningLog(warning) { + return { + stream: "stdout", + chunk: `[taskcore] ${warning} +` + }; +} +function describeSessionResetReason(contextSnapshot) { + if (contextSnapshot?.forceFreshSession === true) return "forceFreshSession was requested"; + const wakeReason = readNonEmptyString10(contextSnapshot?.wakeReason); + if (wakeReason === "issue_assigned") return "wake reason is issue_assigned"; + if (wakeReason === "execution_review_requested") return "wake reason is execution_review_requested"; + if (wakeReason === "execution_approval_requested") return "wake reason is execution_approval_requested"; + if (wakeReason === "execution_changes_requested") return "wake reason is execution_changes_requested"; + return null; +} +function shouldAutoCheckoutIssueForWake(input) { + if (input.issueAssigneeAgentId !== input.agentId) return false; + const issueStatus = readNonEmptyString10(input.issueStatus); + if (issueStatus !== "todo" && issueStatus !== "backlog" && issueStatus !== "blocked" && issueStatus !== "in_progress") { + return false; + } + const wakeReason = readNonEmptyString10(input.contextSnapshot?.wakeReason); + if (!wakeReason) return false; + if (wakeReason === "issue_comment_mentioned") return false; + if (wakeReason.startsWith("execution_")) return false; + return true; +} +function isCheckoutConflictError(error50) { + return error50 instanceof HttpError && error50.status === 409 && error50.message === "Issue checkout conflict"; +} +function deriveCommentId(contextSnapshot, payload2) { + const batchedCommentId = extractWakeCommentIds(contextSnapshot).at(-1); + return batchedCommentId ?? readNonEmptyString10(contextSnapshot?.wakeCommentId) ?? readNonEmptyString10(contextSnapshot?.commentId) ?? readNonEmptyString10(payload2?.commentId) ?? null; +} +function extractWakeCommentIds(contextSnapshot) { + const raw = contextSnapshot?.[WAKE_COMMENT_IDS_KEY]; + if (!Array.isArray(raw)) return []; + const out = []; + for (const entry of raw) { + const value = readNonEmptyString10(entry); + if (!value || out.includes(value)) continue; + out.push(value); + } + return out; +} +function mergeWakeCommentIds(...values2) { + const merged = []; + const append = (value) => { + const normalized = readNonEmptyString10(value); + if (!normalized || merged.includes(normalized)) return; + merged.push(normalized); + }; + for (const value of values2) { + if (Array.isArray(value)) { + for (const entry of value) append(entry); + continue; + } + if (typeof value === "object" && value !== null) { + const candidate = value; + const batched = extractWakeCommentIds(candidate); + if (batched.length > 0) { + for (const entry of batched) append(entry); + continue; + } + append(candidate.wakeCommentId); + append(candidate.commentId); + continue; + } + append(value); + } + return merged; +} +function enrichWakeContextSnapshot(input) { + const { contextSnapshot, reason, source, triggerDetail, payload: payload2 } = input; + const issueIdFromPayload = readNonEmptyString10(payload2?.["issueId"]); + const commentIdFromPayload = readNonEmptyString10(payload2?.["commentId"]); + const taskKey = deriveTaskKey(contextSnapshot, payload2); + const wakeCommentId = deriveCommentId(contextSnapshot, payload2); + const wakeCommentIds = mergeWakeCommentIds(contextSnapshot, commentIdFromPayload); + if (!readNonEmptyString10(contextSnapshot["wakeReason"]) && reason) { + contextSnapshot.wakeReason = reason; + } + if (!readNonEmptyString10(contextSnapshot["issueId"]) && issueIdFromPayload) { + contextSnapshot.issueId = issueIdFromPayload; + } + if (!readNonEmptyString10(contextSnapshot["taskId"]) && issueIdFromPayload) { + contextSnapshot.taskId = issueIdFromPayload; + } + if (!readNonEmptyString10(contextSnapshot["taskKey"]) && taskKey) { + contextSnapshot.taskKey = taskKey; + } + if (!readNonEmptyString10(contextSnapshot["commentId"]) && commentIdFromPayload) { + contextSnapshot.commentId = commentIdFromPayload; + } + if (wakeCommentIds.length > 0) { + const latestCommentId = wakeCommentIds[wakeCommentIds.length - 1]; + contextSnapshot[WAKE_COMMENT_IDS_KEY] = wakeCommentIds; + contextSnapshot.commentId = latestCommentId; + contextSnapshot.wakeCommentId = latestCommentId; + delete contextSnapshot[TASKCORE_WAKE_PAYLOAD_KEY]; + } else if (!readNonEmptyString10(contextSnapshot["wakeCommentId"]) && wakeCommentId) { + contextSnapshot.wakeCommentId = wakeCommentId; + } + if (!readNonEmptyString10(contextSnapshot["wakeSource"]) && source) { + contextSnapshot.wakeSource = source; + } + if (!readNonEmptyString10(contextSnapshot["wakeTriggerDetail"]) && triggerDetail) { + contextSnapshot.wakeTriggerDetail = triggerDetail; + } + return { + contextSnapshot, + issueIdFromPayload, + commentIdFromPayload, + taskKey, + wakeCommentId + }; +} +function mergeCoalescedContextSnapshot(existingRaw, incoming) { + const existing = parseObject4(existingRaw); + const merged = { + ...existing, + ...incoming + }; + const mergedCommentIds = mergeWakeCommentIds(existing, incoming); + if (mergedCommentIds.length > 0) { + const latestCommentId = mergedCommentIds[mergedCommentIds.length - 1]; + merged[WAKE_COMMENT_IDS_KEY] = mergedCommentIds; + merged.commentId = latestCommentId; + merged.wakeCommentId = latestCommentId; + delete merged[TASKCORE_WAKE_PAYLOAD_KEY]; + } + return merged; +} +async function buildTaskcoreWakePayload(input) { + const executionStage = parseObject4(input.contextSnapshot.executionStage); + const commentIds = extractWakeCommentIds(input.contextSnapshot); + const issueId = readNonEmptyString10(input.contextSnapshot.issueId); + const issueSummary = input.issueSummary ?? (issueId ? await input.db.select({ + id: issues.id, + identifier: issues.identifier, + title: issues.title, + status: issues.status, + priority: issues.priority + }).from(issues).where(and(eq(issues.id, issueId), eq(issues.companyId, input.companyId))).then((rows) => rows[0] ?? null) : null); + if (commentIds.length === 0 && Object.keys(executionStage).length === 0 && !issueSummary) return null; + const commentRows = commentIds.length === 0 ? [] : await input.db.select({ + id: issueComments.id, + issueId: issueComments.issueId, + body: issueComments.body, + authorAgentId: issueComments.authorAgentId, + authorUserId: issueComments.authorUserId, + createdAt: issueComments.createdAt + }).from(issueComments).where( + and( + eq(issueComments.companyId, input.companyId), + inArray(issueComments.id, commentIds) + ) + ); + const commentsById = new Map(commentRows.map((comment) => [comment.id, comment])); + const comments = []; + let remainingBodyChars = MAX_INLINE_WAKE_COMMENT_BODY_TOTAL_CHARS; + let truncated = false; + let missingCommentCount = 0; + for (const commentId of commentIds) { + const row = commentsById.get(commentId); + if (!row) { + truncated = true; + missingCommentCount += 1; + continue; + } + if (comments.length >= MAX_INLINE_WAKE_COMMENTS) { + truncated = true; + break; + } + const fullBody = row.body; + const allowedBodyChars = Math.min(MAX_INLINE_WAKE_COMMENT_BODY_CHARS, remainingBodyChars); + if (allowedBodyChars <= 0) { + truncated = true; + break; + } + const body = fullBody.length > allowedBodyChars ? fullBody.slice(0, allowedBodyChars) : fullBody; + const bodyTruncated = body.length < fullBody.length; + if (bodyTruncated) truncated = true; + remainingBodyChars -= body.length; + comments.push({ + id: row.id, + issueId: row.issueId, + body, + bodyTruncated, + createdAt: row.createdAt.toISOString(), + author: row.authorAgentId ? { type: "agent", id: row.authorAgentId } : row.authorUserId ? { type: "user", id: row.authorUserId } : { type: "system", id: null } + }); + } + return { + reason: readNonEmptyString10(input.contextSnapshot.wakeReason), + issue: issueSummary ? { + id: issueSummary.id, + identifier: issueSummary.identifier, + title: issueSummary.title, + status: issueSummary.status, + priority: issueSummary.priority + } : null, + checkedOutByHarness: input.contextSnapshot[TASKCORE_HARNESS_CHECKOUT_KEY] === true, + executionStage: Object.keys(executionStage).length > 0 ? executionStage : null, + commentIds, + latestCommentId: commentIds[commentIds.length - 1] ?? null, + comments, + commentWindow: { + requestedCount: commentIds.length, + includedCount: comments.length, + missingCount: missingCommentCount + }, + truncated, + fallbackFetchNeeded: truncated || missingCommentCount > 0 + }; +} +function runTaskKey(run) { + return deriveTaskKey(run.contextSnapshot, null); +} +function isSameTaskScope(left, right) { + return (left ?? null) === (right ?? null); +} +function isTrackedLocalChildProcessAdapter(adapterType) { + return SESSIONED_LOCAL_ADAPTERS.has(adapterType); +} +function isProcessAlive(pid) { + if (typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0) return false; + try { + process.kill(pid, 0); + return true; + } catch (error50) { + const code = error50?.code; + if (code === "EPERM") return true; + if (code === "ESRCH") return false; + return false; + } +} +async function terminateHeartbeatRunProcess(input) { + const pid = input.pid ?? null; + const processGroupId = input.processGroupId ?? null; + if (typeof pid !== "number" && typeof processGroupId !== "number") return; + await terminateLocalService( + { + pid: typeof pid === "number" && Number.isInteger(pid) && pid > 0 ? pid : processGroupId ?? 0, + processGroupId: typeof processGroupId === "number" && Number.isInteger(processGroupId) && processGroupId > 0 ? processGroupId : null + }, + input.graceMs ? { forceAfterMs: input.graceMs } : void 0 + ); +} +function buildProcessLossMessage(run, options) { + if (options?.descendantOnly && run.processGroupId) { + return `Process lost -- parent pid ${run.processPid ?? "unknown"} exited, but descendant process group ${run.processGroupId} was still alive and was terminated`; + } + if (run.processPid) { + return `Process lost -- child pid ${run.processPid} is no longer running`; + } + if (run.processGroupId) { + return `Process lost -- process group ${run.processGroupId} is no longer running`; + } + return "Process lost -- server may have restarted"; +} +function truncateDisplayId(value, max = 128) { + if (!value) return null; + return value.length > max ? value.slice(0, max) : value; +} +function normalizeAgentNameKey(value) { + if (typeof value !== "string") return null; + const normalized = value.trim().toLowerCase(); + return normalized.length > 0 ? normalized : null; +} +var defaultSessionCodec = { + deserialize(raw) { + const asObj = parseObject4(raw); + if (Object.keys(asObj).length > 0) return asObj; + const sessionId = readNonEmptyString10(raw?.sessionId); + if (sessionId) return { sessionId }; + return null; + }, + serialize(params) { + if (!params || Object.keys(params).length === 0) return null; + return params; + }, + getDisplayId(params) { + return readNonEmptyString10(params?.sessionId); + } +}; +function getAdapterSessionCodec(adapterType) { + const adapter = getServerAdapter(adapterType); + return adapter.sessionCodec ?? defaultSessionCodec; +} +function normalizeSessionParams(params) { + if (!params) return null; + return Object.keys(params).length > 0 ? params : null; +} +function resolveNextSessionState(input) { + const { codec: codec2, adapterResult, previousParams, previousDisplayId, previousLegacySessionId } = input; + if (adapterResult.clearSession) { + return { + params: null, + displayId: null, + legacySessionId: null + }; + } + const explicitParams = adapterResult.sessionParams; + const hasExplicitParams = adapterResult.sessionParams !== void 0; + const hasExplicitSessionId = adapterResult.sessionId !== void 0; + const explicitSessionId = readNonEmptyString10(adapterResult.sessionId); + const hasExplicitDisplay = adapterResult.sessionDisplayId !== void 0; + const explicitDisplayId = readNonEmptyString10(adapterResult.sessionDisplayId); + const shouldUsePrevious = !hasExplicitParams && !hasExplicitSessionId && !hasExplicitDisplay; + const candidateParams = hasExplicitParams ? explicitParams : hasExplicitSessionId ? explicitSessionId ? { sessionId: explicitSessionId } : null : previousParams; + const serialized = normalizeSessionParams(codec2.serialize(normalizeSessionParams(candidateParams) ?? null)); + const deserialized = normalizeSessionParams(codec2.deserialize(serialized)); + const displayId = truncateDisplayId( + explicitDisplayId ?? (codec2.getDisplayId ? codec2.getDisplayId(deserialized) : null) ?? readNonEmptyString10(deserialized?.sessionId) ?? (shouldUsePrevious ? previousDisplayId : null) ?? explicitSessionId ?? (shouldUsePrevious ? previousLegacySessionId : null) + ); + const legacySessionId = explicitSessionId ?? readNonEmptyString10(deserialized?.sessionId) ?? displayId ?? (shouldUsePrevious ? previousLegacySessionId : null); + return { + params: serialized, + displayId, + legacySessionId + }; +} +function heartbeatService(db) { + const instanceSettings2 = instanceSettingsService(db); + const getCurrentUserRedactionOptions = async () => ({ + enabled: (await instanceSettings2.getGeneral()).censorUsernameInLogs + }); + const runLogStore = getRunLogStore(); + const secretsSvc = secretService(db); + const companySkills2 = companySkillService(db); + const issuesSvc = issueService(db); + const executionWorkspacesSvc = executionWorkspaceService(db); + const workspaceOperationsSvc = workspaceOperationService(db); + const activeRunExecutions = /* @__PURE__ */ new Set(); + const budgetHooks = { + cancelWorkForScope: cancelBudgetScopeWork + }; + const budgets = budgetService(db, budgetHooks); + async function getAgent(agentId) { + return db.select().from(agents).where(eq(agents.id, agentId)).then((rows) => rows[0] ?? null); + } + async function getRun(runId) { + return db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)).then((rows) => rows[0] ?? null); + } + async function getIssueExecutionContext(companyId, issueId) { + return db.select({ + id: issues.id, + identifier: issues.identifier, + title: issues.title, + status: issues.status, + priority: issues.priority, + projectId: issues.projectId, + projectWorkspaceId: issues.projectWorkspaceId, + executionWorkspaceId: issues.executionWorkspaceId, + executionWorkspacePreference: issues.executionWorkspacePreference, + assigneeAgentId: issues.assigneeAgentId, + assigneeAdapterOverrides: issues.assigneeAdapterOverrides, + executionWorkspaceSettings: issues.executionWorkspaceSettings + }).from(issues).where(and(eq(issues.id, issueId), eq(issues.companyId, companyId))).then((rows) => rows[0] ?? null); + } + async function getRuntimeState(agentId) { + return db.select().from(agentRuntimeState).where(eq(agentRuntimeState.agentId, agentId)).then((rows) => rows[0] ?? null); + } + async function getTaskSession(companyId, agentId, adapterType, taskKey) { + return db.select().from(agentTaskSessions).where( + and( + eq(agentTaskSessions.companyId, companyId), + eq(agentTaskSessions.agentId, agentId), + eq(agentTaskSessions.adapterType, adapterType), + eq(agentTaskSessions.taskKey, taskKey) + ) + ).then((rows) => rows[0] ?? null); + } + async function getLatestRunForSession(agentId, sessionId, opts) { + const conditions = [ + eq(heartbeatRuns.agentId, agentId), + eq(heartbeatRuns.sessionIdAfter, sessionId) + ]; + if (opts?.excludeRunId) { + conditions.push(sql`${heartbeatRuns.id} <> ${opts.excludeRunId}`); + } + return db.select().from(heartbeatRuns).where(and(...conditions)).orderBy(desc(heartbeatRuns.createdAt)).limit(1).then((rows) => rows[0] ?? null); + } + async function getOldestRunForSession(agentId, sessionId) { + return db.select({ + id: heartbeatRuns.id, + createdAt: heartbeatRuns.createdAt + }).from(heartbeatRuns).where(and(eq(heartbeatRuns.agentId, agentId), eq(heartbeatRuns.sessionIdAfter, sessionId))).orderBy(asc(heartbeatRuns.createdAt), asc(heartbeatRuns.id)).limit(1).then((rows) => rows[0] ?? null); + } + async function resolveNormalizedUsageForSession(input) { + const { agentId, runId, sessionId, rawUsage } = input; + if (!sessionId || !rawUsage) { + return { + normalizedUsage: rawUsage, + previousRawUsage: null, + derivedFromSessionTotals: false + }; + } + const previousRun = await getLatestRunForSession(agentId, sessionId, { excludeRunId: runId }); + const previousRawUsage = readRawUsageTotals(previousRun?.usageJson); + return { + normalizedUsage: deriveNormalizedUsageDelta(rawUsage, previousRawUsage), + previousRawUsage, + derivedFromSessionTotals: previousRawUsage !== null + }; + } + async function evaluateSessionCompaction(input) { + const { agent, sessionId, issueId } = input; + if (!sessionId) { + return { + rotate: false, + reason: null, + handoffMarkdown: null, + previousRunId: null + }; + } + const policy = parseSessionCompactionPolicy(agent); + if (!policy.enabled || !hasSessionCompactionThresholds(policy)) { + return { + rotate: false, + reason: null, + handoffMarkdown: null, + previousRunId: null + }; + } + const fetchLimit = Math.max(policy.maxSessionRuns > 0 ? policy.maxSessionRuns + 1 : 0, 4); + const runs = await db.select({ + id: heartbeatRuns.id, + createdAt: heartbeatRuns.createdAt, + usageJson: heartbeatRuns.usageJson, + resultJson: heartbeatRuns.resultJson, + error: heartbeatRuns.error + }).from(heartbeatRuns).where(and(eq(heartbeatRuns.agentId, agent.id), eq(heartbeatRuns.sessionIdAfter, sessionId))).orderBy(desc(heartbeatRuns.createdAt)).limit(fetchLimit); + if (runs.length === 0) { + return { + rotate: false, + reason: null, + handoffMarkdown: null, + previousRunId: null + }; + } + const latestRun = runs[0] ?? null; + const oldestRun = policy.maxSessionAgeHours > 0 ? await getOldestRunForSession(agent.id, sessionId) : runs[runs.length - 1] ?? latestRun; + const latestRawUsage = readRawUsageTotals(latestRun?.usageJson); + const sessionAgeHours = latestRun && oldestRun ? Math.max( + 0, + (new Date(latestRun.createdAt).getTime() - new Date(oldestRun.createdAt).getTime()) / (1e3 * 60 * 60) + ) : 0; + let reason = null; + if (policy.maxSessionRuns > 0 && runs.length > policy.maxSessionRuns) { + reason = `session exceeded ${policy.maxSessionRuns} runs`; + } else if (policy.maxRawInputTokens > 0 && latestRawUsage && latestRawUsage.inputTokens >= policy.maxRawInputTokens) { + reason = `session raw input reached ${formatCount(latestRawUsage.inputTokens)} tokens (threshold ${formatCount(policy.maxRawInputTokens)})`; + } else if (policy.maxSessionAgeHours > 0 && sessionAgeHours >= policy.maxSessionAgeHours) { + reason = `session age reached ${Math.floor(sessionAgeHours)} hours`; + } + if (!reason || !latestRun) { + return { + rotate: false, + reason: null, + handoffMarkdown: null, + previousRunId: latestRun?.id ?? null + }; + } + const latestSummary = summarizeHeartbeatRunResultJson(latestRun.resultJson); + const latestTextSummary = readNonEmptyString10(latestSummary?.summary) ?? readNonEmptyString10(latestSummary?.result) ?? readNonEmptyString10(latestSummary?.message) ?? readNonEmptyString10(latestRun.error); + const handoffMarkdown = [ + "Taskcore session handoff:", + `- Previous session: ${sessionId}`, + issueId ? `- Issue: ${issueId}` : "", + `- Rotation reason: ${reason}`, + latestTextSummary ? `- Last run summary: ${latestTextSummary}` : "", + "Continue from the current task state. Rebuild only the minimum context you need." + ].filter(Boolean).join("\n"); + return { + rotate: true, + reason, + handoffMarkdown, + previousRunId: latestRun.id + }; + } + async function resolveSessionBeforeForWakeup(agent, taskKey) { + if (taskKey) { + const codec2 = getAdapterSessionCodec(agent.adapterType); + const existingTaskSession = await getTaskSession( + agent.companyId, + agent.id, + agent.adapterType, + taskKey + ); + const parsedParams = normalizeSessionParams( + codec2.deserialize(existingTaskSession?.sessionParamsJson ?? null) + ); + return truncateDisplayId( + existingTaskSession?.sessionDisplayId ?? (codec2.getDisplayId ? codec2.getDisplayId(parsedParams) : null) ?? readNonEmptyString10(parsedParams?.sessionId) + ); + } + const runtimeForRun = await getRuntimeState(agent.id); + return runtimeForRun?.sessionId ?? null; + } + async function resolveExplicitResumeSessionOverride(agent, payload2, taskKey) { + const resumeFromRunId = readNonEmptyString10(payload2?.resumeFromRunId); + if (!resumeFromRunId) return null; + const resumeRun = await db.select({ + id: heartbeatRuns.id, + contextSnapshot: heartbeatRuns.contextSnapshot, + sessionIdBefore: heartbeatRuns.sessionIdBefore, + sessionIdAfter: heartbeatRuns.sessionIdAfter + }).from(heartbeatRuns).where( + and( + eq(heartbeatRuns.id, resumeFromRunId), + eq(heartbeatRuns.companyId, agent.companyId), + eq(heartbeatRuns.agentId, agent.id) + ) + ).then((rows) => rows[0] ?? null); + if (!resumeRun) return null; + const resumeContext = parseObject4(resumeRun.contextSnapshot); + const resumeTaskKey = deriveTaskKey(resumeContext, null) ?? taskKey; + const resumeTaskSession = resumeTaskKey ? await getTaskSession(agent.companyId, agent.id, agent.adapterType, resumeTaskKey) : null; + const sessionCodec8 = getAdapterSessionCodec(agent.adapterType); + const sessionOverride = buildExplicitResumeSessionOverride({ + resumeFromRunId, + resumeRunSessionIdBefore: resumeRun.sessionIdBefore, + resumeRunSessionIdAfter: resumeRun.sessionIdAfter, + taskSession: resumeTaskSession, + sessionCodec: sessionCodec8 + }); + if (!sessionOverride) return null; + return { + resumeFromRunId, + taskKey: resumeTaskKey, + issueId: readNonEmptyString10(resumeContext.issueId), + taskId: readNonEmptyString10(resumeContext.taskId) ?? readNonEmptyString10(resumeContext.issueId), + sessionDisplayId: sessionOverride.sessionDisplayId, + sessionParams: sessionOverride.sessionParams + }; + } + async function resolveWorkspaceForRun(agent, context, previousSessionParams, opts) { + const issueId = readNonEmptyString10(context.issueId); + const contextProjectId = readNonEmptyString10(context.projectId); + const contextProjectWorkspaceId = readNonEmptyString10(context.projectWorkspaceId); + const issueProjectRef = issueId ? await db.select({ + projectId: issues.projectId, + projectWorkspaceId: issues.projectWorkspaceId + }).from(issues).where(and(eq(issues.id, issueId), eq(issues.companyId, agent.companyId))).then((rows) => rows[0] ?? null) : null; + const issueProjectId = issueProjectRef?.projectId ?? null; + const preferredProjectWorkspaceId = issueProjectRef?.projectWorkspaceId ?? contextProjectWorkspaceId ?? null; + const resolvedProjectId = issueProjectId ?? contextProjectId; + const useProjectWorkspace = opts?.useProjectWorkspace !== false; + const workspaceProjectId = useProjectWorkspace ? resolvedProjectId : null; + const unorderedProjectWorkspaceRows = workspaceProjectId ? await db.select().from(projectWorkspaces).where( + and( + eq(projectWorkspaces.companyId, agent.companyId), + eq(projectWorkspaces.projectId, workspaceProjectId) + ) + ).orderBy(asc(projectWorkspaces.createdAt), asc(projectWorkspaces.id)) : []; + const projectWorkspaceRows = prioritizeProjectWorkspaceCandidatesForRun( + unorderedProjectWorkspaceRows, + preferredProjectWorkspaceId + ); + const workspaceHints = projectWorkspaceRows.map((workspace) => ({ + workspaceId: workspace.id, + cwd: readNonEmptyString10(workspace.cwd), + repoUrl: readNonEmptyString10(workspace.repoUrl), + repoRef: readNonEmptyString10(workspace.repoRef) + })); + if (projectWorkspaceRows.length > 0) { + const preferredWorkspace = preferredProjectWorkspaceId ? projectWorkspaceRows.find((workspace) => workspace.id === preferredProjectWorkspaceId) ?? null : null; + const missingProjectCwds = []; + let hasConfiguredProjectCwd = false; + let preferredWorkspaceWarning = null; + if (preferredProjectWorkspaceId && !preferredWorkspace) { + preferredWorkspaceWarning = `Selected project workspace "${preferredProjectWorkspaceId}" is not available on this project.`; + } + for (const workspace of projectWorkspaceRows) { + let projectCwd = readNonEmptyString10(workspace.cwd); + let managedWorkspaceWarning = null; + if (!projectCwd || projectCwd === REPO_ONLY_CWD_SENTINEL2) { + try { + const managedWorkspace = await ensureManagedProjectWorkspace({ + companyId: agent.companyId, + projectId: workspaceProjectId ?? resolvedProjectId ?? workspace.projectId, + repoUrl: readNonEmptyString10(workspace.repoUrl) + }); + projectCwd = managedWorkspace.cwd; + managedWorkspaceWarning = managedWorkspace.warning; + } catch (error50) { + if (preferredWorkspace?.id === workspace.id) { + preferredWorkspaceWarning = error50 instanceof Error ? error50.message : String(error50); + } + continue; + } + } + hasConfiguredProjectCwd = true; + const projectCwdExists = await fs32.stat(projectCwd).then((stats) => stats.isDirectory()).catch(() => false); + if (projectCwdExists) { + return { + cwd: projectCwd, + source: "project_primary", + projectId: resolvedProjectId, + workspaceId: workspace.id, + repoUrl: workspace.repoUrl, + repoRef: workspace.repoRef, + workspaceHints, + warnings: [preferredWorkspaceWarning, managedWorkspaceWarning].filter( + (value) => Boolean(value) + ) + }; + } + if (preferredWorkspace?.id === workspace.id) { + preferredWorkspaceWarning = `Selected project workspace path "${projectCwd}" is not available yet.`; + } + missingProjectCwds.push(projectCwd); + } + const fallbackCwd = resolveDefaultAgentWorkspaceDir(agent.id); + await fs32.mkdir(fallbackCwd, { recursive: true }); + const warnings2 = []; + if (preferredWorkspaceWarning) { + warnings2.push(preferredWorkspaceWarning); + } + if (missingProjectCwds.length > 0) { + const firstMissing = missingProjectCwds[0]; + const extraMissingCount = Math.max(0, missingProjectCwds.length - 1); + warnings2.push( + extraMissingCount > 0 ? `Project workspace path "${firstMissing}" and ${extraMissingCount} other configured path(s) are not available yet. Using fallback workspace "${fallbackCwd}" for this run.` : `Project workspace path "${firstMissing}" is not available yet. Using fallback workspace "${fallbackCwd}" for this run.` + ); + } else if (!hasConfiguredProjectCwd) { + warnings2.push( + `Project workspace has no local cwd configured. Using fallback workspace "${fallbackCwd}" for this run.` + ); + } + return { + cwd: fallbackCwd, + source: "project_primary", + projectId: resolvedProjectId, + workspaceId: projectWorkspaceRows[0]?.id ?? null, + repoUrl: projectWorkspaceRows[0]?.repoUrl ?? null, + repoRef: projectWorkspaceRows[0]?.repoRef ?? null, + workspaceHints, + warnings: warnings2 + }; + } + if (workspaceProjectId) { + const managedWorkspace = await ensureManagedProjectWorkspace({ + companyId: agent.companyId, + projectId: workspaceProjectId, + repoUrl: null + }); + return { + cwd: managedWorkspace.cwd, + source: "project_primary", + projectId: resolvedProjectId, + workspaceId: null, + repoUrl: null, + repoRef: null, + workspaceHints, + warnings: managedWorkspace.warning ? [managedWorkspace.warning] : [] + }; + } + const sessionCwd = readNonEmptyString10(previousSessionParams?.cwd); + if (sessionCwd) { + const sessionCwdExists = await fs32.stat(sessionCwd).then((stats) => stats.isDirectory()).catch(() => false); + if (sessionCwdExists) { + return { + cwd: sessionCwd, + source: "task_session", + projectId: resolvedProjectId, + workspaceId: readNonEmptyString10(previousSessionParams?.workspaceId), + repoUrl: readNonEmptyString10(previousSessionParams?.repoUrl), + repoRef: readNonEmptyString10(previousSessionParams?.repoRef), + workspaceHints, + warnings: [] + }; + } + } + const cwd = resolveDefaultAgentWorkspaceDir(agent.id); + await fs32.mkdir(cwd, { recursive: true }); + const warnings = []; + if (sessionCwd) { + warnings.push( + `Saved session workspace "${sessionCwd}" is not available. Using fallback workspace "${cwd}" for this run.` + ); + } else if (resolvedProjectId) { + warnings.push( + `No project workspace directory is currently available for this issue. Using fallback workspace "${cwd}" for this run.` + ); + } else { + warnings.push( + `No project or prior session workspace was available. Using fallback workspace "${cwd}" for this run.` + ); + } + return { + cwd, + source: "agent_home", + projectId: resolvedProjectId, + workspaceId: null, + repoUrl: null, + repoRef: null, + workspaceHints, + warnings + }; + } + async function upsertTaskSession(input) { + const existing = await getTaskSession( + input.companyId, + input.agentId, + input.adapterType, + input.taskKey + ); + if (existing) { + return db.update(agentTaskSessions).set({ + sessionParamsJson: input.sessionParamsJson, + sessionDisplayId: input.sessionDisplayId, + lastRunId: input.lastRunId, + lastError: input.lastError, + updatedAt: /* @__PURE__ */ new Date() + }).where(eq(agentTaskSessions.id, existing.id)).returning().then((rows) => rows[0] ?? null); + } + return db.insert(agentTaskSessions).values({ + companyId: input.companyId, + agentId: input.agentId, + adapterType: input.adapterType, + taskKey: input.taskKey, + sessionParamsJson: input.sessionParamsJson, + sessionDisplayId: input.sessionDisplayId, + lastRunId: input.lastRunId, + lastError: input.lastError + }).returning().then((rows) => rows[0] ?? null); + } + async function clearTaskSessions(companyId, agentId, opts) { + const conditions = [ + eq(agentTaskSessions.companyId, companyId), + eq(agentTaskSessions.agentId, agentId) + ]; + if (opts?.taskKey) { + conditions.push(eq(agentTaskSessions.taskKey, opts.taskKey)); + } + if (opts?.adapterType) { + conditions.push(eq(agentTaskSessions.adapterType, opts.adapterType)); + } + return db.delete(agentTaskSessions).where(and(...conditions)).returning().then((rows) => rows.length); + } + async function ensureRuntimeState(agent) { + const existing = await getRuntimeState(agent.id); + if (existing) return existing; + return db.insert(agentRuntimeState).values({ + agentId: agent.id, + companyId: agent.companyId, + adapterType: agent.adapterType, + stateJson: {} + }).returning().then((rows) => rows[0]); + } + async function setRunStatus(runId, status, patch) { + const updated = await db.update(heartbeatRuns).set({ status, ...patch, updatedAt: /* @__PURE__ */ new Date() }).where(eq(heartbeatRuns.id, runId)).returning().then((rows) => rows[0] ?? null); + if (updated) { + publishLiveEvent({ + companyId: updated.companyId, + type: "heartbeat.run.status", + payload: { + runId: updated.id, + agentId: updated.agentId, + status: updated.status, + invocationSource: updated.invocationSource, + triggerDetail: updated.triggerDetail, + error: updated.error ?? null, + errorCode: updated.errorCode ?? null, + startedAt: updated.startedAt ? new Date(updated.startedAt).toISOString() : null, + finishedAt: updated.finishedAt ? new Date(updated.finishedAt).toISOString() : null + } + }); + } + return updated; + } + async function setWakeupStatus(wakeupRequestId, status, patch) { + if (!wakeupRequestId) return; + await db.update(agentWakeupRequests).set({ status, ...patch, updatedAt: /* @__PURE__ */ new Date() }).where(eq(agentWakeupRequests.id, wakeupRequestId)); + } + async function appendRunEvent(run, seq, event) { + const currentUserRedactionOptions = await getCurrentUserRedactionOptions(); + const sanitizedMessage = event.message ? redactCurrentUserText(event.message, currentUserRedactionOptions) : event.message; + const sanitizedPayload = event.payload ? redactCurrentUserValue(event.payload, currentUserRedactionOptions) : event.payload; + await db.insert(heartbeatRunEvents).values({ + companyId: run.companyId, + runId: run.id, + agentId: run.agentId, + seq, + eventType: event.eventType, + stream: event.stream, + level: event.level, + color: event.color, + message: sanitizedMessage, + payload: sanitizedPayload + }); + publishLiveEvent({ + companyId: run.companyId, + type: "heartbeat.run.event", + payload: { + runId: run.id, + agentId: run.agentId, + seq, + eventType: event.eventType, + stream: event.stream ?? null, + level: event.level ?? null, + color: event.color ?? null, + message: sanitizedMessage ?? null, + payload: sanitizedPayload ?? null + } + }); + } + async function nextRunEventSeq(runId) { + const [row] = await db.select({ maxSeq: sql`max(${heartbeatRunEvents.seq})` }).from(heartbeatRunEvents).where(eq(heartbeatRunEvents.runId, runId)); + return Number(row?.maxSeq ?? 0) + 1; + } + async function persistRunProcessMetadata(runId, meta3) { + const startedAt = new Date(meta3.startedAt); + return db.update(heartbeatRuns).set({ + processPid: meta3.pid, + processGroupId: meta3.processGroupId, + processStartedAt: Number.isNaN(startedAt.getTime()) ? /* @__PURE__ */ new Date() : startedAt, + updatedAt: /* @__PURE__ */ new Date() + }).where(eq(heartbeatRuns.id, runId)).returning().then((rows) => rows[0] ?? null); + } + async function clearDetachedRunWarning(runId) { + const updated = await db.update(heartbeatRuns).set({ + error: null, + errorCode: null, + updatedAt: /* @__PURE__ */ new Date() + }).where(and(eq(heartbeatRuns.id, runId), eq(heartbeatRuns.status, "running"), eq(heartbeatRuns.errorCode, DETACHED_PROCESS_ERROR_CODE))).returning().then((rows) => rows[0] ?? null); + if (!updated) return null; + await appendRunEvent(updated, await nextRunEventSeq(updated.id), { + eventType: "lifecycle", + stream: "system", + level: "info", + message: "Detached child process reported activity; cleared detached warning" + }); + return updated; + } + async function patchRunIssueCommentStatus(runId, patch) { + return db.update(heartbeatRuns).set({ ...patch, updatedAt: /* @__PURE__ */ new Date() }).where(eq(heartbeatRuns.id, runId)).returning().then((rows) => rows[0] ?? null); + } + async function findRunIssueComment(runId, companyId, issueId) { + return db.select({ + id: issueComments.id + }).from(issueComments).where( + and( + eq(issueComments.companyId, companyId), + eq(issueComments.issueId, issueId), + eq(issueComments.createdByRunId, runId) + ) + ).orderBy(desc(issueComments.createdAt), desc(issueComments.id)).limit(1).then((rows) => rows[0] ?? null); + } + async function enqueueMissingIssueCommentRetry(run, agent, issueId) { + const contextSnapshot = parseObject4(run.contextSnapshot); + const taskKey = deriveTaskKeyWithHeartbeatFallback(contextSnapshot, null); + const sessionBefore = await resolveSessionBeforeForWakeup(agent, taskKey); + const retryContextSnapshot = { + ...contextSnapshot, + retryOfRunId: run.id, + wakeReason: "missing_issue_comment", + retryReason: "missing_issue_comment", + missingIssueCommentForRunId: run.id + }; + const now2 = /* @__PURE__ */ new Date(); + const retryRun = await db.transaction(async (tx) => { + await tx.execute( + sql`select id from issues where company_id = ${run.companyId} and execution_run_id = ${run.id} for update` + ); + const issue2 = await tx.select({ id: issues.id }).from(issues).where(and(eq(issues.companyId, run.companyId), eq(issues.executionRunId, run.id))).then((rows) => rows[0] ?? null); + if (!issue2) return null; + const wakeupRequest = await tx.insert(agentWakeupRequests).values({ + companyId: run.companyId, + agentId: run.agentId, + source: "automation", + triggerDetail: "system", + reason: "missing_issue_comment", + payload: { + issueId, + retryOfRunId: run.id, + retryReason: "missing_issue_comment" + }, + status: "queued", + requestedByActorType: "system", + requestedByActorId: null, + updatedAt: now2 + }).returning().then((rows) => rows[0]); + const queuedRun = await tx.insert(heartbeatRuns).values({ + companyId: run.companyId, + agentId: run.agentId, + invocationSource: "automation", + triggerDetail: "system", + status: "queued", + wakeupRequestId: wakeupRequest.id, + contextSnapshot: retryContextSnapshot, + sessionIdBefore: sessionBefore, + retryOfRunId: run.id, + issueCommentStatus: "not_applicable", + updatedAt: now2 + }).returning().then((rows) => rows[0]); + await tx.update(agentWakeupRequests).set({ + runId: queuedRun.id, + updatedAt: now2 + }).where(eq(agentWakeupRequests.id, wakeupRequest.id)); + await tx.update(issues).set({ + executionRunId: queuedRun.id, + executionAgentNameKey: normalizeAgentNameKey(agent.name), + executionLockedAt: now2, + updatedAt: now2 + }).where(eq(issues.id, issue2.id)); + await tx.update(heartbeatRuns).set({ + issueCommentStatus: "retry_queued", + issueCommentRetryQueuedAt: now2, + updatedAt: now2 + }).where(eq(heartbeatRuns.id, run.id)); + return queuedRun; + }); + if (!retryRun) return null; + publishLiveEvent({ + companyId: retryRun.companyId, + type: "heartbeat.run.queued", + payload: { + runId: retryRun.id, + agentId: retryRun.agentId, + invocationSource: retryRun.invocationSource, + triggerDetail: retryRun.triggerDetail, + wakeupRequestId: retryRun.wakeupRequestId + } + }); + return retryRun; + } + async function finalizeIssueCommentPolicy(run, agent) { + const contextSnapshot = parseObject4(run.contextSnapshot); + const issueId = readNonEmptyString10(contextSnapshot.issueId); + if (!issueId) { + if (run.issueCommentStatus !== "not_applicable") { + await patchRunIssueCommentStatus(run.id, { + issueCommentStatus: "not_applicable", + issueCommentSatisfiedByCommentId: null, + issueCommentRetryQueuedAt: null + }); + } + return { outcome: "not_applicable", queuedRun: null }; + } + const postedComment = await findRunIssueComment(run.id, run.companyId, issueId); + if (postedComment) { + await patchRunIssueCommentStatus(run.id, { + issueCommentStatus: "satisfied", + issueCommentSatisfiedByCommentId: postedComment.id, + issueCommentRetryQueuedAt: null + }); + return { outcome: "satisfied", queuedRun: null }; + } + if (readNonEmptyString10(contextSnapshot.retryReason) === "missing_issue_comment") { + await patchRunIssueCommentStatus(run.id, { + issueCommentStatus: "retry_exhausted", + issueCommentSatisfiedByCommentId: null + }); + await appendRunEvent(run, await nextRunEventSeq(run.id), { + eventType: "lifecycle", + stream: "system", + level: "warn", + message: "Run ended without an issue comment after one retry; no further comment wake will be queued" + }); + return { outcome: "retry_exhausted", queuedRun: null }; + } + if (!shouldRequireIssueCommentForWake(contextSnapshot)) { + if (run.issueCommentStatus !== "not_applicable") { + await patchRunIssueCommentStatus(run.id, { + issueCommentStatus: "not_applicable", + issueCommentSatisfiedByCommentId: null, + issueCommentRetryQueuedAt: null + }); + } + return { outcome: "not_applicable", queuedRun: null }; + } + const queuedRun = await enqueueMissingIssueCommentRetry(run, agent, issueId); + if (queuedRun) { + await appendRunEvent(run, await nextRunEventSeq(run.id), { + eventType: "lifecycle", + stream: "system", + level: "warn", + message: "Run ended without an issue comment; queued one follow-up wake to require a comment" + }); + return { outcome: "retry_queued", queuedRun }; + } + await patchRunIssueCommentStatus(run.id, { + issueCommentStatus: "retry_exhausted", + issueCommentSatisfiedByCommentId: null + }); + return { outcome: "retry_exhausted", queuedRun: null }; + } + async function enqueueProcessLossRetry(run, agent, now2) { + const contextSnapshot = parseObject4(run.contextSnapshot); + const issueId = readNonEmptyString10(contextSnapshot.issueId); + const taskKey = deriveTaskKeyWithHeartbeatFallback(contextSnapshot, null); + const sessionBefore = await resolveSessionBeforeForWakeup(agent, taskKey); + const retryContextSnapshot = { + ...contextSnapshot, + retryOfRunId: run.id, + wakeReason: "process_lost_retry", + retryReason: "process_lost" + }; + const queued = await db.transaction(async (tx) => { + const wakeupRequest = await tx.insert(agentWakeupRequests).values({ + companyId: run.companyId, + agentId: run.agentId, + source: "automation", + triggerDetail: "system", + reason: "process_lost_retry", + payload: { + ...issueId ? { issueId } : {}, + retryOfRunId: run.id + }, + status: "queued", + requestedByActorType: "system", + requestedByActorId: null, + updatedAt: now2 + }).returning().then((rows) => rows[0]); + const retryRun = await tx.insert(heartbeatRuns).values({ + companyId: run.companyId, + agentId: run.agentId, + invocationSource: "automation", + triggerDetail: "system", + status: "queued", + wakeupRequestId: wakeupRequest.id, + contextSnapshot: retryContextSnapshot, + sessionIdBefore: sessionBefore, + retryOfRunId: run.id, + processLossRetryCount: (run.processLossRetryCount ?? 0) + 1, + updatedAt: now2 + }).returning().then((rows) => rows[0]); + await tx.update(agentWakeupRequests).set({ + runId: retryRun.id, + updatedAt: now2 + }).where(eq(agentWakeupRequests.id, wakeupRequest.id)); + if (issueId) { + await tx.update(issues).set({ + executionRunId: retryRun.id, + executionAgentNameKey: normalizeAgentNameKey(agent.name), + executionLockedAt: now2, + updatedAt: now2 + }).where(and(eq(issues.id, issueId), eq(issues.companyId, run.companyId), eq(issues.executionRunId, run.id))); + } + return retryRun; + }); + publishLiveEvent({ + companyId: queued.companyId, + type: "heartbeat.run.queued", + payload: { + runId: queued.id, + agentId: queued.agentId, + invocationSource: queued.invocationSource, + triggerDetail: queued.triggerDetail, + wakeupRequestId: queued.wakeupRequestId + } + }); + await appendRunEvent(queued, 1, { + eventType: "lifecycle", + stream: "system", + level: "warn", + message: "Queued automatic retry after orphaned child process was confirmed dead", + payload: { + retryOfRunId: run.id + } + }); + return queued; + } + function parseHeartbeatPolicy(agent) { + const runtimeConfig = parseObject4(agent.runtimeConfig); + const heartbeat = parseObject4(runtimeConfig.heartbeat); + return { + enabled: asBoolean4(heartbeat.enabled, false), + intervalSec: Math.max(0, asNumber3(heartbeat.intervalSec, 0)), + wakeOnDemand: asBoolean4(heartbeat.wakeOnDemand ?? heartbeat.wakeOnAssignment ?? heartbeat.wakeOnOnDemand ?? heartbeat.wakeOnAutomation, true), + maxConcurrentRuns: normalizeMaxConcurrentRuns(heartbeat.maxConcurrentRuns) + }; + } + async function countRunningRunsForAgent(agentId) { + const [{ count: count2 }] = await db.select({ count: sql`count(*)` }).from(heartbeatRuns).where(and(eq(heartbeatRuns.agentId, agentId), eq(heartbeatRuns.status, "running"))); + return Number(count2 ?? 0); + } + async function claimQueuedRun(run) { + if (run.status !== "queued") return run; + const agent = await getAgent(run.agentId); + if (!agent) { + await cancelRunInternal(run.id, "Cancelled because the agent no longer exists"); + return null; + } + if (agent.status === "paused" || agent.status === "terminated" || agent.status === "pending_approval") { + await cancelRunInternal(run.id, "Cancelled because the agent is not invokable"); + return null; + } + const context = parseObject4(run.contextSnapshot); + const budgetBlock = await budgets.getInvocationBlock(run.companyId, run.agentId, { + issueId: readNonEmptyString10(context.issueId), + projectId: readNonEmptyString10(context.projectId) + }); + if (budgetBlock) { + await cancelRunInternal(run.id, budgetBlock.reason); + return null; + } + const claimedAt = /* @__PURE__ */ new Date(); + const claimed = await db.update(heartbeatRuns).set({ + status: "running", + startedAt: run.startedAt ?? claimedAt, + updatedAt: claimedAt + }).where(and(eq(heartbeatRuns.id, run.id), eq(heartbeatRuns.status, "queued"))).returning().then((rows) => rows[0] ?? null); + if (!claimed) return null; + publishLiveEvent({ + companyId: claimed.companyId, + type: "heartbeat.run.status", + payload: { + runId: claimed.id, + agentId: claimed.agentId, + status: claimed.status, + invocationSource: claimed.invocationSource, + triggerDetail: claimed.triggerDetail, + error: claimed.error ?? null, + errorCode: claimed.errorCode ?? null, + startedAt: claimed.startedAt ? new Date(claimed.startedAt).toISOString() : null, + finishedAt: claimed.finishedAt ? new Date(claimed.finishedAt).toISOString() : null + } + }); + await setWakeupStatus(claimed.wakeupRequestId, "claimed", { claimedAt }); + const claimedIssueId = readNonEmptyString10(parseObject4(claimed.contextSnapshot).issueId); + if (claimedIssueId) { + const claimedAgent = await getAgent(claimed.agentId); + await db.update(issues).set({ + executionRunId: claimed.id, + executionAgentNameKey: normalizeAgentNameKey(claimedAgent?.name), + executionLockedAt: claimedAt, + updatedAt: claimedAt + }).where( + and( + eq(issues.id, claimedIssueId), + eq(issues.companyId, claimed.companyId), + or(isNull(issues.executionRunId), eq(issues.executionRunId, claimed.id)) + ) + ); + } + return claimed; + } + async function finalizeAgentStatus(agentId, outcome) { + const existing = await getAgent(agentId); + if (!existing) return; + if (existing.status === "paused" || existing.status === "terminated") { + return; + } + const isFirstHeartbeat = !existing.lastHeartbeatAt; + const runningCount = await countRunningRunsForAgent(agentId); + const nextStatus = runningCount > 0 ? "running" : outcome === "succeeded" || outcome === "cancelled" ? "idle" : "error"; + const updated = await db.update(agents).set({ + status: nextStatus, + lastHeartbeatAt: /* @__PURE__ */ new Date(), + updatedAt: /* @__PURE__ */ new Date() + }).where(eq(agents.id, agentId)).returning().then((rows) => rows[0] ?? null); + if (isFirstHeartbeat && updated) { + const tc = getTelemetryClient(); + if (tc) trackAgentFirstHeartbeat(tc, { agentRole: updated.role, agentId: updated.id }); + } + if (updated) { + publishLiveEvent({ + companyId: updated.companyId, + type: "agent.status", + payload: { + agentId: updated.id, + status: updated.status, + lastHeartbeatAt: updated.lastHeartbeatAt ? new Date(updated.lastHeartbeatAt).toISOString() : null, + outcome + } + }); + } + } + async function reapOrphanedRuns(opts) { + const staleThresholdMs = opts?.staleThresholdMs ?? 0; + const now2 = /* @__PURE__ */ new Date(); + const activeRuns = await db.select({ + run: heartbeatRuns, + adapterType: agents.adapterType + }).from(heartbeatRuns).innerJoin(agents, eq(heartbeatRuns.agentId, agents.id)).where(eq(heartbeatRuns.status, "running")); + const reaped = []; + for (const { run, adapterType } of activeRuns) { + if (runningProcesses3.has(run.id) || activeRunExecutions.has(run.id)) continue; + if (staleThresholdMs > 0) { + const refTime = run.updatedAt ? new Date(run.updatedAt).getTime() : 0; + if (now2.getTime() - refTime < staleThresholdMs) continue; + } + const tracksLocalChild = isTrackedLocalChildProcessAdapter(adapterType); + const processPidAlive = tracksLocalChild && run.processPid && isProcessAlive(run.processPid); + const processGroupAlive = tracksLocalChild && run.processGroupId && isProcessGroupAlive(run.processGroupId); + if (processPidAlive) { + if (run.errorCode !== DETACHED_PROCESS_ERROR_CODE) { + const detachedMessage = `Lost in-memory process handle, but child pid ${run.processPid} is still alive`; + const detachedRun = await setRunStatus(run.id, "running", { + error: detachedMessage, + errorCode: DETACHED_PROCESS_ERROR_CODE + }); + if (detachedRun) { + await appendRunEvent(detachedRun, await nextRunEventSeq(detachedRun.id), { + eventType: "lifecycle", + stream: "system", + level: "warn", + message: detachedMessage, + payload: { + processPid: run.processPid + } + }); + } + } + continue; + } + let descendantOnlyCleanup = false; + if (processGroupAlive) { + descendantOnlyCleanup = true; + await terminateHeartbeatRunProcess({ + pid: run.processPid, + processGroupId: run.processGroupId + }); + } + const shouldRetry = tracksLocalChild && (!!run.processPid || !!run.processGroupId) && (run.processLossRetryCount ?? 0) < 1; + const baseMessage = buildProcessLossMessage(run, descendantOnlyCleanup ? { descendantOnly: true } : void 0); + let finalizedRun = await setRunStatus(run.id, "failed", { + error: shouldRetry ? `${baseMessage}; retrying once` : baseMessage, + errorCode: "process_lost", + finishedAt: now2 + }); + await setWakeupStatus(run.wakeupRequestId, "failed", { + finishedAt: now2, + error: shouldRetry ? `${baseMessage}; retrying once` : baseMessage + }); + if (!finalizedRun) finalizedRun = await getRun(run.id); + if (!finalizedRun) continue; + let retriedRun = null; + if (shouldRetry) { + const agent = await getAgent(run.agentId); + if (agent) { + retriedRun = await enqueueProcessLossRetry(finalizedRun, agent, now2); + } + } else { + await releaseIssueExecutionAndPromote(finalizedRun); + } + await appendRunEvent(finalizedRun, await nextRunEventSeq(finalizedRun.id), { + eventType: "lifecycle", + stream: "system", + level: "error", + message: shouldRetry ? `${baseMessage}; queued retry ${retriedRun?.id ?? ""}`.trim() : baseMessage, + payload: { + ...run.processPid ? { processPid: run.processPid } : {}, + ...run.processGroupId ? { processGroupId: run.processGroupId } : {}, + ...descendantOnlyCleanup ? { descendantOnlyCleanup: true } : {}, + ...retriedRun ? { retryRunId: retriedRun.id } : {} + } + }); + await finalizeAgentStatus(run.agentId, "failed"); + await startNextQueuedRunForAgent(run.agentId); + runningProcesses3.delete(run.id); + reaped.push(run.id); + } + if (reaped.length > 0) { + logger.warn({ reapedCount: reaped.length, runIds: reaped }, "reaped orphaned heartbeat runs"); + } + return { reaped: reaped.length, runIds: reaped }; + } + async function resumeQueuedRuns() { + const queuedRuns = await db.select({ agentId: heartbeatRuns.agentId }).from(heartbeatRuns).where(eq(heartbeatRuns.status, "queued")); + const agentIds = [...new Set(queuedRuns.map((r5) => r5.agentId))]; + for (const agentId of agentIds) { + await startNextQueuedRunForAgent(agentId); + } + } + async function getLatestIssueRun(companyId, issueId) { + return db.select().from(heartbeatRuns).where( + and( + eq(heartbeatRuns.companyId, companyId), + sql`${heartbeatRuns.contextSnapshot} ->> 'issueId' = ${issueId}` + ) + ).orderBy(desc(heartbeatRuns.createdAt), desc(heartbeatRuns.id)).limit(1).then((rows) => rows[0] ?? null); + } + async function hasActiveExecutionPath(companyId, issueId) { + const [run, deferredWake] = await Promise.all([ + db.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where( + and( + eq(heartbeatRuns.companyId, companyId), + inArray(heartbeatRuns.status, [...ACTIVE_HEARTBEAT_RUN_STATUSES]), + sql`${heartbeatRuns.contextSnapshot} ->> 'issueId' = ${issueId}` + ) + ).limit(1).then((rows) => rows[0] ?? null), + db.select({ id: agentWakeupRequests.id }).from(agentWakeupRequests).where( + and( + eq(agentWakeupRequests.companyId, companyId), + eq(agentWakeupRequests.status, "deferred_issue_execution"), + sql`${agentWakeupRequests.payload} ->> 'issueId' = ${issueId}` + ) + ).limit(1).then((rows) => rows[0] ?? null) + ]); + return Boolean(run || deferredWake); + } + async function enqueueStrandedIssueRecovery(input) { + const queued = await enqueueWakeup(input.agentId, { + source: "automation", + triggerDetail: "system", + reason: input.reason, + payload: { + issueId: input.issueId, + ...input.retryOfRunId ? { retryOfRunId: input.retryOfRunId } : {} + }, + requestedByActorType: "system", + requestedByActorId: null, + contextSnapshot: { + issueId: input.issueId, + taskId: input.issueId, + wakeReason: input.reason, + retryReason: input.retryReason, + source: input.source, + ...input.retryOfRunId ? { retryOfRunId: input.retryOfRunId } : {} + } + }); + if (queued && input.retryOfRunId) { + return db.update(heartbeatRuns).set({ + retryOfRunId: input.retryOfRunId, + updatedAt: /* @__PURE__ */ new Date() + }).where(eq(heartbeatRuns.id, queued.id)).returning().then((rows) => rows[0] ?? queued); + } + return queued; + } + async function escalateStrandedAssignedIssue(input) { + const updated = await issuesSvc.update(input.issue.id, { + status: "blocked" + }); + if (!updated) return null; + await issuesSvc.addComment(input.issue.id, input.comment, {}); + await logActivity(db, { + companyId: input.issue.companyId, + actorType: "system", + actorId: "system", + agentId: null, + runId: null, + action: "issue.updated", + entityType: "issue", + entityId: input.issue.id, + details: { + identifier: input.issue.identifier, + status: "blocked", + previousStatus: input.previousStatus, + source: "heartbeat.reconcile_stranded_assigned_issue", + latestRunId: input.latestRun?.id ?? null, + latestRunStatus: input.latestRun?.status ?? null, + latestRunErrorCode: input.latestRun?.errorCode ?? null + } + }); + return updated; + } + async function reconcileStrandedAssignedIssues() { + const candidates = await db.select().from(issues).where( + and( + isNull(issues.assigneeUserId), + inArray(issues.status, ["todo", "in_progress"]), + sql`${issues.assigneeAgentId} is not null` + ) + ); + const result = { + dispatchRequeued: 0, + continuationRequeued: 0, + escalated: 0, + skipped: 0, + issueIds: [] + }; + for (const issue2 of candidates) { + const agentId = issue2.assigneeAgentId; + if (!agentId) { + result.skipped += 1; + continue; + } + const agent = await getAgent(agentId); + if (!agent || agent.companyId !== issue2.companyId) { + result.skipped += 1; + continue; + } + if (agent.status === "paused" || agent.status === "terminated" || agent.status === "pending_approval") { + result.skipped += 1; + continue; + } + if (await hasActiveExecutionPath(issue2.companyId, issue2.id)) { + result.skipped += 1; + continue; + } + const latestRun = await getLatestIssueRun(issue2.companyId, issue2.id); + const latestContext = parseObject4(latestRun?.contextSnapshot); + const latestRetryReason = readNonEmptyString10(latestContext.retryReason); + if (issue2.status === "todo") { + if (!latestRun || latestRun.status === "succeeded") { + result.skipped += 1; + continue; + } + if (latestRetryReason === "assignment_recovery") { + const updated = await escalateStrandedAssignedIssue({ + issue: issue2, + previousStatus: "todo", + latestRun, + comment: "Taskcore automatically retried dispatch for this assigned `todo` issue after a lost wake/run, but it still has no live execution path. Moving it to `blocked` so it is visible for intervention." + }); + if (updated) { + result.escalated += 1; + result.issueIds.push(issue2.id); + } else { + result.skipped += 1; + } + continue; + } + const queued2 = await enqueueStrandedIssueRecovery({ + issueId: issue2.id, + agentId, + reason: "issue_assignment_recovery", + retryReason: "assignment_recovery", + source: "issue.assignment_recovery", + retryOfRunId: latestRun.id + }); + if (queued2) { + result.dispatchRequeued += 1; + result.issueIds.push(issue2.id); + } else { + result.skipped += 1; + } + continue; + } + if (latestRetryReason === "issue_continuation_needed") { + const updated = await escalateStrandedAssignedIssue({ + issue: issue2, + previousStatus: "in_progress", + latestRun, + comment: "Taskcore automatically retried continuation for this assigned `in_progress` issue after its live execution disappeared, but it still has no live execution path. Moving it to `blocked` so it is visible for intervention." + }); + if (updated) { + result.escalated += 1; + result.issueIds.push(issue2.id); + } else { + result.skipped += 1; + } + continue; + } + const queued = await enqueueStrandedIssueRecovery({ + issueId: issue2.id, + agentId, + reason: "issue_continuation_needed", + retryReason: "issue_continuation_needed", + source: "issue.continuation_recovery", + retryOfRunId: latestRun?.id ?? issue2.checkoutRunId ?? null + }); + if (queued) { + result.continuationRequeued += 1; + result.issueIds.push(issue2.id); + } else { + result.skipped += 1; + } + } + return result; + } + async function updateRuntimeState(agent, run, result, session, normalizedUsage) { + await ensureRuntimeState(agent); + const usage = normalizedUsage ?? normalizeUsageTotals(result.usage); + const inputTokens = usage?.inputTokens ?? 0; + const outputTokens = usage?.outputTokens ?? 0; + const cachedInputTokens = usage?.cachedInputTokens ?? 0; + const billingType = normalizeLedgerBillingType(result.billingType); + const additionalCostCents = normalizeBilledCostCents(result.costUsd, billingType); + const hasTokenUsage = inputTokens > 0 || outputTokens > 0 || cachedInputTokens > 0; + const provider = result.provider ?? "unknown"; + const biller = resolveLedgerBiller(result); + const ledgerScope = await resolveLedgerScopeForRun(db, agent.companyId, run); + await db.update(agentRuntimeState).set({ + adapterType: agent.adapterType, + sessionId: session.legacySessionId, + lastRunId: run.id, + lastRunStatus: run.status, + lastError: result.errorMessage ?? null, + totalInputTokens: sql`${agentRuntimeState.totalInputTokens} + ${inputTokens}`, + totalOutputTokens: sql`${agentRuntimeState.totalOutputTokens} + ${outputTokens}`, + totalCachedInputTokens: sql`${agentRuntimeState.totalCachedInputTokens} + ${cachedInputTokens}`, + totalCostCents: sql`${agentRuntimeState.totalCostCents} + ${additionalCostCents}`, + updatedAt: /* @__PURE__ */ new Date() + }).where(eq(agentRuntimeState.agentId, agent.id)); + if (additionalCostCents > 0 || hasTokenUsage) { + const costs = costService(db, budgetHooks); + await costs.createEvent(agent.companyId, { + heartbeatRunId: run.id, + agentId: agent.id, + issueId: ledgerScope.issueId, + projectId: ledgerScope.projectId, + provider, + biller, + billingType, + model: result.model ?? "unknown", + inputTokens, + cachedInputTokens, + outputTokens, + costCents: additionalCostCents, + occurredAt: /* @__PURE__ */ new Date() + }); + } + } + async function startNextQueuedRunForAgent(agentId) { + return withAgentStartLock(agentId, async () => { + const agent = await getAgent(agentId); + if (!agent) return []; + if (agent.status === "paused" || agent.status === "terminated" || agent.status === "pending_approval") { + return []; + } + const policy = parseHeartbeatPolicy(agent); + const runningCount = await countRunningRunsForAgent(agentId); + const availableSlots = Math.max(0, policy.maxConcurrentRuns - runningCount); + if (availableSlots <= 0) return []; + const queuedRuns = await db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.agentId, agentId), eq(heartbeatRuns.status, "queued"))).orderBy(asc(heartbeatRuns.createdAt)).limit(availableSlots); + if (queuedRuns.length === 0) return []; + const claimedRuns = []; + for (const queuedRun of queuedRuns) { + const claimed = await claimQueuedRun(queuedRun); + if (claimed) claimedRuns.push(claimed); + } + if (claimedRuns.length === 0) return []; + for (const claimedRun of claimedRuns) { + void executeRun(claimedRun.id).catch((err) => { + logger.error({ err, runId: claimedRun.id }, "queued heartbeat execution failed"); + }); + } + return claimedRuns; + }); + } + async function executeRun(runId) { + let run = await getRun(runId); + if (!run) return; + if (run.status !== "queued" && run.status !== "running") return; + if (run.status === "queued") { + const claimed = await claimQueuedRun(run); + if (!claimed) { + return; + } + run = claimed; + } + activeRunExecutions.add(run.id); + try { + const agent = await getAgent(run.agentId); + if (!agent) { + await setRunStatus(runId, "failed", { + error: "Agent not found", + errorCode: "agent_not_found", + finishedAt: /* @__PURE__ */ new Date() + }); + await setWakeupStatus(run.wakeupRequestId, "failed", { + finishedAt: /* @__PURE__ */ new Date(), + error: "Agent not found" + }); + const failedRun = await getRun(runId); + if (failedRun) await releaseIssueExecutionAndPromote(failedRun); + return; + } + const runtime = await ensureRuntimeState(agent); + const context = parseObject4(run.contextSnapshot); + const taskKey = deriveTaskKeyWithHeartbeatFallback(context, null); + const sessionCodec8 = getAdapterSessionCodec(agent.adapterType); + const issueId = readNonEmptyString10(context.issueId); + let issueContext = issueId ? await getIssueExecutionContext(agent.companyId, issueId) : null; + if (issueId && issueContext && shouldAutoCheckoutIssueForWake({ + contextSnapshot: context, + issueStatus: issueContext.status, + issueAssigneeAgentId: issueContext.assigneeAgentId, + agentId: agent.id + })) { + try { + await issuesSvc.checkout(issueId, agent.id, ["todo", "backlog", "blocked"], run.id); + context[TASKCORE_HARNESS_CHECKOUT_KEY] = true; + } catch (error50) { + if (!isCheckoutConflictError(error50)) throw error50; + context[TASKCORE_HARNESS_CHECKOUT_KEY] = false; + } + issueContext = await getIssueExecutionContext(agent.companyId, issueId); + } + const issueAssigneeOverrides = issueContext && issueContext.assigneeAgentId === agent.id ? parseIssueAssigneeAdapterOverrides( + issueContext.assigneeAdapterOverrides + ) : null; + const isolatedWorkspacesEnabled = (await instanceSettings2.getExperimental()).enableIsolatedWorkspaces; + const issueExecutionWorkspaceSettings = isolatedWorkspacesEnabled ? parseIssueExecutionWorkspaceSettings(issueContext?.executionWorkspaceSettings) : null; + const contextProjectId = readNonEmptyString10(context.projectId); + const executionProjectId = issueContext?.projectId ?? contextProjectId; + const projectContext = executionProjectId ? await db.select({ + executionWorkspacePolicy: projects.executionWorkspacePolicy, + env: projects.env + }).from(projects).where(and(eq(projects.id, executionProjectId), eq(projects.companyId, agent.companyId))).then((rows) => rows[0] ?? null) : null; + const projectExecutionWorkspacePolicy = gateProjectExecutionWorkspacePolicy( + parseProjectExecutionWorkspacePolicy(projectContext?.executionWorkspacePolicy), + isolatedWorkspacesEnabled + ); + const taskSession = taskKey ? await getTaskSession(agent.companyId, agent.id, agent.adapterType, taskKey) : null; + const resetTaskSession = shouldResetTaskSessionForWake(context); + const sessionResetReason = describeSessionResetReason(context); + const taskSessionForRun = resetTaskSession ? null : taskSession; + const explicitResumeSessionParams = normalizeSessionParams( + sessionCodec8.deserialize(parseObject4(context.resumeSessionParams)) + ); + const explicitResumeSessionDisplayId = truncateDisplayId( + readNonEmptyString10(context.resumeSessionDisplayId) ?? (sessionCodec8.getDisplayId ? sessionCodec8.getDisplayId(explicitResumeSessionParams) : null) ?? readNonEmptyString10(explicitResumeSessionParams?.sessionId) + ); + const previousSessionParams = explicitResumeSessionParams ?? (explicitResumeSessionDisplayId ? { sessionId: explicitResumeSessionDisplayId } : null) ?? normalizeSessionParams(sessionCodec8.deserialize(taskSessionForRun?.sessionParamsJson ?? null)); + const config3 = parseObject4(agent.adapterConfig); + const requestedExecutionWorkspaceMode = resolveExecutionWorkspaceMode({ + projectPolicy: projectExecutionWorkspacePolicy, + issueSettings: issueExecutionWorkspaceSettings, + legacyUseProjectWorkspace: issueAssigneeOverrides?.useProjectWorkspace ?? null + }); + const resolvedWorkspace = await resolveWorkspaceForRun( + agent, + context, + previousSessionParams, + { useProjectWorkspace: requestedExecutionWorkspaceMode !== "agent_default" } + ); + const issueRef = issueContext ? { + id: issueContext.id, + identifier: issueContext.identifier, + title: issueContext.title, + status: issueContext.status, + priority: issueContext.priority, + projectId: issueContext.projectId, + projectWorkspaceId: issueContext.projectWorkspaceId, + executionWorkspaceId: issueContext.executionWorkspaceId, + executionWorkspacePreference: issueContext.executionWorkspacePreference + } : null; + const taskcoreWakePayload = await buildTaskcoreWakePayload({ + db, + companyId: agent.companyId, + contextSnapshot: context, + issueSummary: issueRef ? { + id: issueRef.id, + identifier: issueRef.identifier, + title: issueRef.title, + status: issueRef.status, + priority: issueRef.priority + } : null + }); + if (taskcoreWakePayload) { + context[TASKCORE_WAKE_PAYLOAD_KEY] = taskcoreWakePayload; + } else { + delete context[TASKCORE_WAKE_PAYLOAD_KEY]; + } + const existingExecutionWorkspace = issueRef?.executionWorkspaceId ? await executionWorkspacesSvc.getById(issueRef.executionWorkspaceId) : null; + const shouldReuseExisting = issueRef?.executionWorkspacePreference === "reuse_existing" && existingExecutionWorkspace && existingExecutionWorkspace.status !== "archived"; + const persistedExecutionWorkspaceMode = shouldReuseExisting && existingExecutionWorkspace ? issueExecutionWorkspaceModeForPersistedWorkspace(existingExecutionWorkspace.mode) : null; + const effectiveExecutionWorkspaceMode = persistedExecutionWorkspaceMode === "isolated_workspace" || persistedExecutionWorkspaceMode === "operator_branch" || persistedExecutionWorkspaceMode === "agent_default" ? persistedExecutionWorkspaceMode : requestedExecutionWorkspaceMode; + const workspaceManagedConfig = shouldReuseExisting ? { ...config3 } : buildExecutionWorkspaceAdapterConfig({ + agentConfig: config3, + projectPolicy: projectExecutionWorkspacePolicy, + issueSettings: issueExecutionWorkspaceSettings, + mode: requestedExecutionWorkspaceMode, + legacyUseProjectWorkspace: issueAssigneeOverrides?.useProjectWorkspace ?? null + }); + const persistedWorkspaceManagedConfig = applyPersistedExecutionWorkspaceConfig({ + config: workspaceManagedConfig, + workspaceConfig: existingExecutionWorkspace?.config ?? null, + mode: effectiveExecutionWorkspaceMode + }); + const mergedConfig = issueAssigneeOverrides?.adapterConfig ? { ...persistedWorkspaceManagedConfig, ...issueAssigneeOverrides.adapterConfig } : persistedWorkspaceManagedConfig; + const configSnapshot = buildExecutionWorkspaceConfigSnapshot(mergedConfig); + const executionRunConfig = stripWorkspaceRuntimeFromExecutionRunConfig(mergedConfig); + const { resolvedConfig, secretKeys } = await resolveExecutionRunAdapterConfig({ + companyId: agent.companyId, + executionRunConfig, + projectEnv: projectContext?.env ?? null, + secretsSvc + }); + const runScopedMentionedSkillKeys = await resolveRunScopedMentionedSkillKeys({ + db, + companyId: agent.companyId, + issueId + }); + const effectiveResolvedConfig = applyRunScopedMentionedSkillKeys( + resolvedConfig, + runScopedMentionedSkillKeys + ); + const runtimeSkillEntries = await companySkills2.listRuntimeSkillEntries(agent.companyId); + const runtimeConfig = { + ...effectiveResolvedConfig, + taskcoreRuntimeSkills: runtimeSkillEntries + }; + const workspaceOperationRecorder = workspaceOperationsSvc.createRecorder({ + companyId: agent.companyId, + heartbeatRunId: run.id, + executionWorkspaceId: existingExecutionWorkspace?.id ?? null + }); + const executionWorkspaceBase = { + baseCwd: resolvedWorkspace.cwd, + source: resolvedWorkspace.source, + projectId: resolvedWorkspace.projectId, + workspaceId: resolvedWorkspace.workspaceId, + repoUrl: resolvedWorkspace.repoUrl, + repoRef: resolvedWorkspace.repoRef + }; + const reusedExecutionWorkspace = shouldReuseExisting && existingExecutionWorkspace ? buildRealizedExecutionWorkspaceFromPersisted({ + base: executionWorkspaceBase, + workspace: existingExecutionWorkspace + }) : null; + const executionWorkspace = reusedExecutionWorkspace ?? await realizeExecutionWorkspace({ + base: executionWorkspaceBase, + config: runtimeConfig, + issue: issueRef, + agent: { + id: agent.id, + name: agent.name, + companyId: agent.companyId + }, + recorder: workspaceOperationRecorder + }); + const resolvedProjectId = executionWorkspace.projectId ?? issueRef?.projectId ?? executionProjectId ?? null; + const resolvedProjectWorkspaceId = issueRef?.projectWorkspaceId ?? resolvedWorkspace.workspaceId ?? null; + let persistedExecutionWorkspace = null; + const nextExecutionWorkspaceMetadataBase = { + ...existingExecutionWorkspace?.metadata ?? {}, + source: executionWorkspace.source, + createdByRuntime: executionWorkspace.created + }; + const nextExecutionWorkspaceMetadata = shouldReuseExisting ? nextExecutionWorkspaceMetadataBase : configSnapshot ? mergeExecutionWorkspaceConfig(nextExecutionWorkspaceMetadataBase, configSnapshot) : nextExecutionWorkspaceMetadataBase; + try { + persistedExecutionWorkspace = shouldReuseExisting && existingExecutionWorkspace ? await executionWorkspacesSvc.update(existingExecutionWorkspace.id, { + cwd: executionWorkspace.cwd, + repoUrl: executionWorkspace.repoUrl, + baseRef: executionWorkspace.repoRef, + branchName: executionWorkspace.branchName, + providerType: executionWorkspace.strategy === "git_worktree" ? "git_worktree" : "local_fs", + providerRef: executionWorkspace.worktreePath, + status: "active", + lastUsedAt: /* @__PURE__ */ new Date(), + metadata: nextExecutionWorkspaceMetadata + }) : resolvedProjectId ? await executionWorkspacesSvc.create({ + companyId: agent.companyId, + projectId: resolvedProjectId, + projectWorkspaceId: resolvedProjectWorkspaceId, + sourceIssueId: issueRef?.id ?? null, + mode: requestedExecutionWorkspaceMode === "isolated_workspace" ? "isolated_workspace" : requestedExecutionWorkspaceMode === "operator_branch" ? "operator_branch" : requestedExecutionWorkspaceMode === "agent_default" ? "adapter_managed" : "shared_workspace", + strategyType: executionWorkspace.strategy === "git_worktree" ? "git_worktree" : "project_primary", + name: executionWorkspace.branchName ?? issueRef?.identifier ?? `workspace-${agent.id.slice(0, 8)}`, + status: "active", + cwd: executionWorkspace.cwd, + repoUrl: executionWorkspace.repoUrl, + baseRef: executionWorkspace.repoRef, + branchName: executionWorkspace.branchName, + providerType: executionWorkspace.strategy === "git_worktree" ? "git_worktree" : "local_fs", + providerRef: executionWorkspace.worktreePath, + lastUsedAt: /* @__PURE__ */ new Date(), + openedAt: /* @__PURE__ */ new Date(), + metadata: nextExecutionWorkspaceMetadata + }) : null; + } catch (error50) { + if (executionWorkspace.created) { + try { + await cleanupExecutionWorkspaceArtifacts({ + workspace: { + id: existingExecutionWorkspace?.id ?? `transient-${run.id}`, + cwd: executionWorkspace.cwd, + providerType: executionWorkspace.strategy === "git_worktree" ? "git_worktree" : "local_fs", + providerRef: executionWorkspace.worktreePath, + branchName: executionWorkspace.branchName, + repoUrl: executionWorkspace.repoUrl, + baseRef: executionWorkspace.repoRef, + projectId: resolvedProjectId, + projectWorkspaceId: resolvedProjectWorkspaceId, + sourceIssueId: issueRef?.id ?? null, + metadata: { + createdByRuntime: true, + source: executionWorkspace.source + } + }, + projectWorkspace: { + cwd: resolvedWorkspace.cwd, + cleanupCommand: null + }, + cleanupCommand: configSnapshot?.cleanupCommand ?? null, + teardownCommand: configSnapshot?.teardownCommand ?? projectExecutionWorkspacePolicy?.workspaceStrategy?.teardownCommand ?? null, + recorder: workspaceOperationRecorder + }); + } catch (cleanupError) { + logger.warn( + { + runId: run.id, + issueId, + executionWorkspaceCwd: executionWorkspace.cwd, + cleanupError: cleanupError instanceof Error ? cleanupError.message : String(cleanupError) + }, + "Failed to cleanup realized execution workspace after persistence failure" + ); + } + } + throw error50; + } + await workspaceOperationRecorder.attachExecutionWorkspaceId(persistedExecutionWorkspace?.id ?? null); + if (existingExecutionWorkspace && persistedExecutionWorkspace && existingExecutionWorkspace.id !== persistedExecutionWorkspace.id && existingExecutionWorkspace.status === "active") { + await executionWorkspacesSvc.update(existingExecutionWorkspace.id, { + status: "idle", + cleanupReason: null + }); + } + if (issueId && persistedExecutionWorkspace) { + const nextIssueWorkspaceMode = issueExecutionWorkspaceModeForPersistedWorkspace(persistedExecutionWorkspace.mode); + const shouldSwitchIssueToExistingWorkspace = issueRef?.executionWorkspacePreference === "reuse_existing" || requestedExecutionWorkspaceMode === "isolated_workspace" || requestedExecutionWorkspaceMode === "operator_branch"; + const nextIssuePatch = {}; + if (issueRef?.executionWorkspaceId !== persistedExecutionWorkspace.id) { + nextIssuePatch.executionWorkspaceId = persistedExecutionWorkspace.id; + } + if (resolvedProjectWorkspaceId && issueRef?.projectWorkspaceId !== resolvedProjectWorkspaceId) { + nextIssuePatch.projectWorkspaceId = resolvedProjectWorkspaceId; + } + if (shouldSwitchIssueToExistingWorkspace) { + nextIssuePatch.executionWorkspacePreference = "reuse_existing"; + nextIssuePatch.executionWorkspaceSettings = { + ...issueExecutionWorkspaceSettings ?? {}, + mode: nextIssueWorkspaceMode + }; + } + if (Object.keys(nextIssuePatch).length > 0) { + await issuesSvc.update(issueId, nextIssuePatch); + } + } + if (persistedExecutionWorkspace) { + context.executionWorkspaceId = persistedExecutionWorkspace.id; + await db.update(heartbeatRuns).set({ + contextSnapshot: context, + updatedAt: /* @__PURE__ */ new Date() + }).where(eq(heartbeatRuns.id, run.id)); + } + const runtimeSessionResolution = resolveRuntimeSessionParamsForWorkspace({ + agentId: agent.id, + previousSessionParams, + resolvedWorkspace: { + ...resolvedWorkspace, + cwd: executionWorkspace.cwd + } + }); + const runtimeSessionParams = runtimeSessionResolution.sessionParams; + const runtimeWorkspaceWarnings = [ + ...resolvedWorkspace.warnings, + ...executionWorkspace.warnings, + ...runtimeSessionResolution.warning ? [runtimeSessionResolution.warning] : [], + ...resetTaskSession && sessionResetReason ? [ + taskKey ? `Skipping saved session resume for task "${taskKey}" because ${sessionResetReason}.` : `Skipping saved session resume because ${sessionResetReason}.` + ] : [] + ]; + context.taskcoreWorkspace = { + cwd: executionWorkspace.cwd, + source: executionWorkspace.source, + mode: effectiveExecutionWorkspaceMode, + strategy: executionWorkspace.strategy, + projectId: executionWorkspace.projectId, + workspaceId: executionWorkspace.workspaceId, + repoUrl: executionWorkspace.repoUrl, + repoRef: executionWorkspace.repoRef, + branchName: executionWorkspace.branchName, + worktreePath: executionWorkspace.worktreePath, + agentHome: await (async () => { + const home = resolveDefaultAgentWorkspaceDir(agent.id); + await fs32.mkdir(home, { recursive: true }); + return home; + })() + }; + context.taskcoreWorkspaces = resolvedWorkspace.workspaceHints; + const runtimeServiceIntents = (() => { + const runtimeConfig2 = parseObject4(resolvedConfig.workspaceRuntime); + return Array.isArray(runtimeConfig2.services) ? runtimeConfig2.services.filter( + (value) => typeof value === "object" && value !== null + ) : []; + })(); + if (runtimeServiceIntents.length > 0) { + context.taskcoreRuntimeServiceIntents = runtimeServiceIntents; + } else { + delete context.taskcoreRuntimeServiceIntents; + } + if (executionWorkspace.projectId && !readNonEmptyString10(context.projectId)) { + context.projectId = executionWorkspace.projectId; + } + const runtimeSessionFallback = taskKey || resetTaskSession ? null : runtime.sessionId; + let previousSessionDisplayId = truncateDisplayId( + explicitResumeSessionDisplayId ?? taskSessionForRun?.sessionDisplayId ?? (sessionCodec8.getDisplayId ? sessionCodec8.getDisplayId(runtimeSessionParams) : null) ?? readNonEmptyString10(runtimeSessionParams?.sessionId) ?? runtimeSessionFallback + ); + let runtimeSessionIdForAdapter = readNonEmptyString10(runtimeSessionParams?.sessionId) ?? runtimeSessionFallback; + let runtimeSessionParamsForAdapter = runtimeSessionParams; + const sessionCompaction = await evaluateSessionCompaction({ + agent, + sessionId: previousSessionDisplayId ?? runtimeSessionIdForAdapter, + issueId + }); + if (sessionCompaction.rotate) { + context.taskcoreSessionHandoffMarkdown = sessionCompaction.handoffMarkdown; + context.taskcoreSessionRotationReason = sessionCompaction.reason; + context.taskcorePreviousSessionId = previousSessionDisplayId ?? runtimeSessionIdForAdapter; + runtimeSessionIdForAdapter = null; + runtimeSessionParamsForAdapter = null; + previousSessionDisplayId = null; + if (sessionCompaction.reason) { + runtimeWorkspaceWarnings.push( + `Starting a fresh session because ${sessionCompaction.reason}.` + ); + } + } else { + delete context.taskcoreSessionHandoffMarkdown; + delete context.taskcoreSessionRotationReason; + delete context.taskcorePreviousSessionId; + } + const runtimeForAdapter = { + sessionId: runtimeSessionIdForAdapter, + sessionParams: runtimeSessionParamsForAdapter, + sessionDisplayId: previousSessionDisplayId, + taskKey + }; + let seq = 1; + let handle = null; + let stdoutExcerpt = ""; + let stderrExcerpt = ""; + try { + const startedAt = run.startedAt ?? /* @__PURE__ */ new Date(); + const runningWithSession = await db.update(heartbeatRuns).set({ + startedAt, + sessionIdBefore: runtimeForAdapter.sessionDisplayId ?? runtimeForAdapter.sessionId, + contextSnapshot: context, + updatedAt: /* @__PURE__ */ new Date() + }).where(eq(heartbeatRuns.id, run.id)).returning().then((rows) => rows[0] ?? null); + if (runningWithSession) run = runningWithSession; + const runningAgent = await db.update(agents).set({ status: "running", updatedAt: /* @__PURE__ */ new Date() }).where(eq(agents.id, agent.id)).returning().then((rows) => rows[0] ?? null); + if (runningAgent) { + publishLiveEvent({ + companyId: runningAgent.companyId, + type: "agent.status", + payload: { + agentId: runningAgent.id, + status: runningAgent.status, + outcome: "running" + } + }); + } + const currentRun = run; + await appendRunEvent(currentRun, seq++, { + eventType: "lifecycle", + stream: "system", + level: "info", + message: "run started" + }); + handle = await runLogStore.begin({ + companyId: run.companyId, + agentId: run.agentId, + runId + }); + await db.update(heartbeatRuns).set({ + logStore: handle.store, + logRef: handle.logRef, + updatedAt: /* @__PURE__ */ new Date() + }).where(eq(heartbeatRuns.id, runId)); + const currentUserRedactionOptions = await getCurrentUserRedactionOptions(); + const onLog = async (stream, chunk) => { + const sanitizedChunk = compactRunLogChunk( + redactCurrentUserText(chunk, currentUserRedactionOptions) + ); + if (stream === "stdout") stdoutExcerpt = appendExcerpt2(stdoutExcerpt, sanitizedChunk); + if (stream === "stderr") stderrExcerpt = appendExcerpt2(stderrExcerpt, sanitizedChunk); + const ts = (/* @__PURE__ */ new Date()).toISOString(); + if (handle) { + await runLogStore.append(handle, { + stream, + chunk: sanitizedChunk, + ts + }); + } + const payloadChunk = sanitizedChunk.length > MAX_LIVE_LOG_CHUNK_BYTES ? sanitizedChunk.slice(sanitizedChunk.length - MAX_LIVE_LOG_CHUNK_BYTES) : sanitizedChunk; + publishLiveEvent({ + companyId: run.companyId, + type: "heartbeat.run.log", + payload: { + runId: run.id, + agentId: run.agentId, + ts, + stream, + chunk: payloadChunk, + truncated: payloadChunk.length !== sanitizedChunk.length + } + }); + }; + if (runScopedMentionedSkillKeys.length > 0) { + await onLog( + "stdout", + `[taskcore] Enabled run-scoped skills from issue mentions: ${runScopedMentionedSkillKeys.join(", ")} +` + ); + } + for (const warning of runtimeWorkspaceWarnings) { + const logEntry = formatRuntimeWorkspaceWarningLog(warning); + await onLog(logEntry.stream, logEntry.chunk); + } + const adapterEnv = Object.fromEntries( + Object.entries(parseObject4(resolvedConfig.env)).filter( + (entry) => typeof entry[0] === "string" && typeof entry[1] === "string" + ) + ); + const runtimeServices = await ensureRuntimeServicesForRun({ + db, + runId: run.id, + agent: { + id: agent.id, + name: agent.name, + companyId: agent.companyId + }, + issue: issueRef, + workspace: executionWorkspace, + executionWorkspaceId: persistedExecutionWorkspace?.id ?? issueRef?.executionWorkspaceId ?? null, + config: effectiveResolvedConfig, + adapterEnv, + onLog + }); + if (runtimeServices.length > 0) { + context.taskcoreRuntimeServices = runtimeServices; + context.taskcoreRuntimePrimaryUrl = runtimeServices.find((service) => readNonEmptyString10(service.url))?.url ?? null; + await db.update(heartbeatRuns).set({ + contextSnapshot: context, + updatedAt: /* @__PURE__ */ new Date() + }).where(eq(heartbeatRuns.id, run.id)); + } + if (issueId && (executionWorkspace.created || runtimeServices.some((service) => !service.reused))) { + try { + await issuesSvc.addComment( + issueId, + buildWorkspaceReadyComment({ + workspace: executionWorkspace, + runtimeServices + }), + { agentId: agent.id, runId: run.id } + ); + } catch (err) { + await onLog( + "stderr", + `[taskcore] Failed to post workspace-ready comment: ${err instanceof Error ? err.message : String(err)} +` + ); + } + } + const onAdapterMeta = async (meta3) => { + if (meta3.env && secretKeys.size > 0) { + for (const key of secretKeys) { + if (key in meta3.env) meta3.env[key] = "***REDACTED***"; + } + } + await appendRunEvent(currentRun, seq++, { + eventType: "adapter.invoke", + stream: "system", + level: "info", + message: "adapter invocation", + payload: meta3 + }); + }; + const adapter = getServerAdapter(agent.adapterType); + const authToken = adapter.supportsLocalAgentJwt ? createLocalAgentJwt(agent.id, agent.companyId, agent.adapterType, run.id) : null; + if (adapter.supportsLocalAgentJwt && !authToken) { + logger.warn( + { + companyId: agent.companyId, + agentId: agent.id, + runId: run.id, + adapterType: agent.adapterType + }, + "local agent jwt secret missing or invalid; running without injected TASKCORE_API_KEY" + ); + } + const adapterResult = await adapter.execute({ + runId: run.id, + agent, + runtime: runtimeForAdapter, + config: runtimeConfig, + context, + onLog, + onMeta: onAdapterMeta, + onSpawn: async (meta3) => { + await persistRunProcessMetadata(run.id, { + pid: meta3.pid, + processGroupId: "processGroupId" in meta3 && typeof meta3.processGroupId === "number" ? meta3.processGroupId : null, + startedAt: meta3.startedAt + }); + }, + authToken: authToken ?? void 0 + }); + const adapterManagedRuntimeServices = adapterResult.runtimeServices ? await persistAdapterManagedRuntimeServices({ + db, + adapterType: agent.adapterType, + runId: run.id, + agent: { + id: agent.id, + name: agent.name, + companyId: agent.companyId + }, + issue: issueRef, + workspace: executionWorkspace, + reports: adapterResult.runtimeServices + }) : []; + if (adapterManagedRuntimeServices.length > 0) { + const combinedRuntimeServices = [ + ...runtimeServices, + ...adapterManagedRuntimeServices + ]; + context.taskcoreRuntimeServices = combinedRuntimeServices; + context.taskcoreRuntimePrimaryUrl = combinedRuntimeServices.find((service) => readNonEmptyString10(service.url))?.url ?? null; + await db.update(heartbeatRuns).set({ + contextSnapshot: context, + updatedAt: /* @__PURE__ */ new Date() + }).where(eq(heartbeatRuns.id, run.id)); + if (issueId) { + try { + await issuesSvc.addComment( + issueId, + buildWorkspaceReadyComment({ + workspace: executionWorkspace, + runtimeServices: adapterManagedRuntimeServices + }), + { agentId: agent.id, runId: run.id } + ); + } catch (err) { + await onLog( + "stderr", + `[taskcore] Failed to post adapter-managed runtime comment: ${err instanceof Error ? err.message : String(err)} +` + ); + } + } + } + const nextSessionState = resolveNextSessionState({ + codec: sessionCodec8, + adapterResult, + previousParams: previousSessionParams, + previousDisplayId: runtimeForAdapter.sessionDisplayId, + previousLegacySessionId: runtimeForAdapter.sessionId + }); + const rawUsage = normalizeUsageTotals(adapterResult.usage); + const sessionUsageResolution = await resolveNormalizedUsageForSession({ + agentId: agent.id, + runId: run.id, + sessionId: nextSessionState.displayId ?? nextSessionState.legacySessionId, + rawUsage + }); + const normalizedUsage = sessionUsageResolution.normalizedUsage; + let outcome; + const latestRun = await getRun(run.id); + if (latestRun?.status === "cancelled") { + outcome = "cancelled"; + } else if (adapterResult.timedOut) { + outcome = "timed_out"; + } else if ((adapterResult.exitCode ?? 0) === 0 && !adapterResult.errorMessage) { + outcome = "succeeded"; + } else { + outcome = "failed"; + } + let logSummary = null; + if (handle) { + logSummary = await runLogStore.finalize(handle); + } + const status = outcome === "succeeded" ? "succeeded" : outcome === "cancelled" ? "cancelled" : outcome === "timed_out" ? "timed_out" : "failed"; + const usageJson = normalizedUsage || adapterResult.costUsd != null ? { + ...normalizedUsage ?? {}, + ...rawUsage ? { + rawInputTokens: rawUsage.inputTokens, + rawCachedInputTokens: rawUsage.cachedInputTokens, + rawOutputTokens: rawUsage.outputTokens + } : {}, + ...sessionUsageResolution.derivedFromSessionTotals ? { usageSource: "session_delta" } : {}, + ...nextSessionState.displayId ?? nextSessionState.legacySessionId ? { persistedSessionId: nextSessionState.displayId ?? nextSessionState.legacySessionId } : {}, + sessionReused: runtimeForAdapter.sessionId != null || runtimeForAdapter.sessionDisplayId != null, + taskSessionReused: taskSessionForRun != null, + freshSession: runtimeForAdapter.sessionId == null && runtimeForAdapter.sessionDisplayId == null, + sessionRotated: sessionCompaction.rotate, + sessionRotationReason: sessionCompaction.reason, + provider: readNonEmptyString10(adapterResult.provider) ?? "unknown", + biller: resolveLedgerBiller(adapterResult), + model: readNonEmptyString10(adapterResult.model) ?? "unknown", + ...adapterResult.costUsd != null ? { costUsd: adapterResult.costUsd } : {}, + billingType: normalizeLedgerBillingType(adapterResult.billingType) + } : null; + const persistedResultJson = mergeHeartbeatRunResultJson( + adapterResult.resultJson ?? null, + adapterResult.summary ?? null + ); + await setRunStatus(run.id, status, { + finishedAt: /* @__PURE__ */ new Date(), + error: outcome === "succeeded" ? null : redactCurrentUserText( + adapterResult.errorMessage ?? (outcome === "timed_out" ? "Timed out" : "Adapter failed"), + currentUserRedactionOptions + ), + errorCode: outcome === "timed_out" ? "timeout" : outcome === "cancelled" ? "cancelled" : outcome === "failed" ? adapterResult.errorCode ?? "adapter_failed" : null, + exitCode: adapterResult.exitCode, + signal: adapterResult.signal, + usageJson, + resultJson: persistedResultJson, + sessionIdAfter: nextSessionState.displayId ?? nextSessionState.legacySessionId, + stdoutExcerpt, + stderrExcerpt, + logBytes: logSummary?.bytes, + logSha256: logSummary?.sha256, + logCompressed: logSummary?.compressed ?? false + }); + await setWakeupStatus(run.wakeupRequestId, outcome === "succeeded" ? "completed" : status, { + finishedAt: /* @__PURE__ */ new Date(), + error: adapterResult.errorMessage ?? null + }); + const finalizedRun = await getRun(run.id); + if (finalizedRun) { + await appendRunEvent(finalizedRun, seq++, { + eventType: "lifecycle", + stream: "system", + level: outcome === "succeeded" ? "info" : "error", + message: `run ${outcome}`, + payload: { + status, + exitCode: adapterResult.exitCode + } + }); + if (issueId && outcome === "succeeded") { + try { + const existingRunComment = await findRunIssueComment(finalizedRun.id, finalizedRun.companyId, issueId); + if (!existingRunComment) { + const issueComment = buildHeartbeatRunIssueComment(persistedResultJson); + if (issueComment) { + await issuesSvc.addComment(issueId, issueComment, { agentId: agent.id, runId: finalizedRun.id }); + } + } + } catch (err) { + await onLog( + "stderr", + `[taskcore] Failed to post run summary comment: ${err instanceof Error ? err.message : String(err)} +` + ); + } + } + await finalizeIssueCommentPolicy(finalizedRun, agent); + await releaseIssueExecutionAndPromote(finalizedRun); + } + if (finalizedRun) { + await updateRuntimeState(agent, finalizedRun, adapterResult, { + legacySessionId: nextSessionState.legacySessionId + }, normalizedUsage); + if (taskKey) { + if (adapterResult.clearSession || !nextSessionState.params && !nextSessionState.displayId) { + await clearTaskSessions(agent.companyId, agent.id, { + taskKey, + adapterType: agent.adapterType + }); + } else { + await upsertTaskSession({ + companyId: agent.companyId, + agentId: agent.id, + adapterType: agent.adapterType, + taskKey, + sessionParamsJson: nextSessionState.params, + sessionDisplayId: nextSessionState.displayId, + lastRunId: finalizedRun.id, + lastError: outcome === "succeeded" ? null : adapterResult.errorMessage ?? "run_failed" + }); + } + } + } + await finalizeAgentStatus(agent.id, outcome); + } catch (err) { + const message2 = redactCurrentUserText( + err instanceof Error ? err.message : "Unknown adapter failure", + await getCurrentUserRedactionOptions() + ); + logger.error({ err, runId }, "heartbeat execution failed"); + let logSummary = null; + if (handle) { + try { + logSummary = await runLogStore.finalize(handle); + } catch (finalizeErr) { + logger.warn({ err: finalizeErr, runId }, "failed to finalize run log after error"); + } + } + const failedRun = await setRunStatus(run.id, "failed", { + error: message2, + errorCode: "adapter_failed", + finishedAt: /* @__PURE__ */ new Date(), + stdoutExcerpt, + stderrExcerpt, + logBytes: logSummary?.bytes, + logSha256: logSummary?.sha256, + logCompressed: logSummary?.compressed ?? false + }); + await setWakeupStatus(run.wakeupRequestId, "failed", { + finishedAt: /* @__PURE__ */ new Date(), + error: message2 + }); + if (failedRun) { + await appendRunEvent(failedRun, seq++, { + eventType: "error", + stream: "system", + level: "error", + message: message2 + }); + await finalizeIssueCommentPolicy(failedRun, agent); + await releaseIssueExecutionAndPromote(failedRun); + await updateRuntimeState(agent, failedRun, { + exitCode: null, + signal: null, + timedOut: false, + errorMessage: message2 + }, { + legacySessionId: runtimeForAdapter.sessionId + }); + if (taskKey && (previousSessionParams || previousSessionDisplayId || taskSession)) { + await upsertTaskSession({ + companyId: agent.companyId, + agentId: agent.id, + adapterType: agent.adapterType, + taskKey, + sessionParamsJson: previousSessionParams, + sessionDisplayId: previousSessionDisplayId, + lastRunId: failedRun.id, + lastError: message2 + }); + } + } + await finalizeAgentStatus(agent.id, "failed"); + } + } catch (outerErr) { + const message2 = outerErr instanceof Error ? outerErr.message : "Unknown setup failure"; + logger.error({ err: outerErr, runId }, "heartbeat execution setup failed"); + await setRunStatus(runId, "failed", { + error: message2, + errorCode: "adapter_failed", + finishedAt: /* @__PURE__ */ new Date() + }).catch(() => void 0); + await setWakeupStatus(run.wakeupRequestId, "failed", { + finishedAt: /* @__PURE__ */ new Date(), + error: message2 + }).catch(() => void 0); + const failedRun = await getRun(runId).catch(() => null); + if (failedRun) { + await appendRunEvent(failedRun, 1, { + eventType: "error", + stream: "system", + level: "error", + message: message2 + }).catch(() => void 0); + const failedAgent = await getAgent(run.agentId).catch(() => null); + if (failedAgent) { + await finalizeIssueCommentPolicy(failedRun, failedAgent).catch(() => void 0); + } + await releaseIssueExecutionAndPromote(failedRun).catch(() => void 0); + } + await finalizeAgentStatus(run.agentId, "failed").catch(() => void 0); + } finally { + await releaseRuntimeServicesForRun(run.id).catch(() => void 0); + activeRunExecutions.delete(run.id); + await startNextQueuedRunForAgent(run.agentId); + } + } + async function releaseIssueExecutionAndPromote(run) { + const runContext = parseObject4(run.contextSnapshot); + const contextIssueId = readNonEmptyString10(runContext.issueId); + const promotionResult = await db.transaction(async (tx) => { + if (contextIssueId) { + await tx.execute( + sql`select id from issues where company_id = ${run.companyId} and id = ${contextIssueId} for update` + ); + } else { + await tx.execute( + sql`select id from issues where company_id = ${run.companyId} and execution_run_id = ${run.id} for update` + ); + } + let issue2 = await tx.select({ + id: issues.id, + companyId: issues.companyId, + identifier: issues.identifier, + status: issues.status, + executionRunId: issues.executionRunId + }).from(issues).where( + and( + eq(issues.companyId, run.companyId), + contextIssueId ? eq(issues.id, contextIssueId) : eq(issues.executionRunId, run.id) + ) + ).then((rows) => rows[0] ?? null); + if (!issue2) return null; + if (issue2.executionRunId && issue2.executionRunId !== run.id) return null; + if (issue2.executionRunId === run.id) { + await tx.update(issues).set({ + executionRunId: null, + executionAgentNameKey: null, + executionLockedAt: null, + updatedAt: /* @__PURE__ */ new Date() + }).where(eq(issues.id, issue2.id)); + } + while (true) { + const deferred = await tx.select().from(agentWakeupRequests).where( + and( + eq(agentWakeupRequests.companyId, issue2.companyId), + eq(agentWakeupRequests.status, "deferred_issue_execution"), + sql`${agentWakeupRequests.payload} ->> 'issueId' = ${issue2.id}` + ) + ).orderBy(asc(agentWakeupRequests.requestedAt)).limit(1).then((rows) => rows[0] ?? null); + if (!deferred) return null; + const deferredAgent = await tx.select().from(agents).where(eq(agents.id, deferred.agentId)).then((rows) => rows[0] ?? null); + if (!deferredAgent || deferredAgent.companyId !== issue2.companyId || deferredAgent.status === "paused" || deferredAgent.status === "terminated" || deferredAgent.status === "pending_approval") { + await tx.update(agentWakeupRequests).set({ + status: "failed", + finishedAt: /* @__PURE__ */ new Date(), + error: "Deferred wake could not be promoted: agent is not invokable", + updatedAt: /* @__PURE__ */ new Date() + }).where(eq(agentWakeupRequests.id, deferred.id)); + continue; + } + const deferredPayload = parseObject4(deferred.payload); + const deferredContextSeed = parseObject4(deferredPayload[DEFERRED_WAKE_CONTEXT_KEY]); + const promotedContextSeed = { ...deferredContextSeed }; + const deferredCommentIds = extractWakeCommentIds(deferredContextSeed); + const shouldReopenDeferredCommentWake = deferredCommentIds.length > 0 && (issue2.status === "done" || issue2.status === "cancelled"); + let reopenedActivity = null; + if (shouldReopenDeferredCommentWake) { + const reopenedFromStatus = issue2.status; + const reopenedIssue = await issuesSvc.update( + issue2.id, + { + status: "todo", + executionState: null + }, + tx + ); + if (reopenedIssue) { + issue2 = { + ...issue2, + identifier: reopenedIssue.identifier, + status: reopenedIssue.status, + executionRunId: reopenedIssue.executionRunId + }; + if (!readNonEmptyString10(promotedContextSeed.reopenedFrom)) { + promotedContextSeed.reopenedFrom = reopenedFromStatus; + } + reopenedActivity = { + companyId: issue2.companyId, + actorType: "system", + actorId: "heartbeat", + agentId: deferred.agentId, + runId: run.id, + action: "issue.updated", + entityType: "issue", + entityId: issue2.id, + details: { + status: "todo", + reopened: true, + reopenedFrom: reopenedFromStatus, + source: "deferred_comment_wake", + identifier: issue2.identifier + } + }; + } + } + const promotedReason = readNonEmptyString10(deferred.reason) ?? "issue_execution_promoted"; + const promotedSource = readNonEmptyString10(deferred.source) ?? "automation"; + const promotedTriggerDetail = readNonEmptyString10(deferred.triggerDetail) ?? null; + const promotedPayload = deferredPayload; + delete promotedPayload[DEFERRED_WAKE_CONTEXT_KEY]; + const { + contextSnapshot: promotedContextSnapshot, + taskKey: promotedTaskKey + } = enrichWakeContextSnapshot({ + contextSnapshot: promotedContextSeed, + reason: promotedReason, + source: promotedSource, + triggerDetail: promotedTriggerDetail, + payload: promotedPayload + }); + const sessionBefore = readNonEmptyString10(promotedContextSnapshot.resumeSessionDisplayId) ?? await resolveSessionBeforeForWakeup(deferredAgent, promotedTaskKey); + const now2 = /* @__PURE__ */ new Date(); + const newRun = await tx.insert(heartbeatRuns).values({ + companyId: deferredAgent.companyId, + agentId: deferredAgent.id, + invocationSource: promotedSource, + triggerDetail: promotedTriggerDetail, + status: "queued", + wakeupRequestId: deferred.id, + contextSnapshot: promotedContextSnapshot, + sessionIdBefore: sessionBefore + }).returning().then((rows) => rows[0]); + await tx.update(agentWakeupRequests).set({ + status: "queued", + reason: "issue_execution_promoted", + runId: newRun.id, + claimedAt: null, + finishedAt: null, + error: null, + updatedAt: now2 + }).where(eq(agentWakeupRequests.id, deferred.id)); + await tx.update(issues).set({ + executionRunId: newRun.id, + executionAgentNameKey: normalizeAgentNameKey(deferredAgent.name), + executionLockedAt: now2, + updatedAt: now2 + }).where(eq(issues.id, issue2.id)); + return { + run: newRun, + reopenedActivity + }; + } + }); + const promotedRun = promotionResult?.run ?? null; + if (!promotedRun) return; + if (promotionResult?.reopenedActivity) { + await logActivity(db, promotionResult.reopenedActivity); + } + publishLiveEvent({ + companyId: promotedRun.companyId, + type: "heartbeat.run.queued", + payload: { + runId: promotedRun.id, + agentId: promotedRun.agentId, + invocationSource: promotedRun.invocationSource, + triggerDetail: promotedRun.triggerDetail, + wakeupRequestId: promotedRun.wakeupRequestId + } + }); + await startNextQueuedRunForAgent(promotedRun.agentId); + } + async function enqueueWakeup(agentId, opts = {}) { + const source = opts.source ?? "on_demand"; + const triggerDetail = opts.triggerDetail ?? null; + const contextSnapshot = { ...opts.contextSnapshot ?? {} }; + const reason = opts.reason ?? null; + const payload2 = opts.payload ?? null; + const { + contextSnapshot: enrichedContextSnapshot, + issueIdFromPayload, + taskKey, + wakeCommentId + } = enrichWakeContextSnapshot({ + contextSnapshot, + reason, + source, + triggerDetail, + payload: payload2 + }); + let issueId = readNonEmptyString10(enrichedContextSnapshot.issueId) ?? issueIdFromPayload; + const agent = await getAgent(agentId); + if (!agent) throw notFound("Agent not found"); + const explicitResumeSession = await resolveExplicitResumeSessionOverride(agent, payload2, taskKey); + if (explicitResumeSession) { + enrichedContextSnapshot.resumeFromRunId = explicitResumeSession.resumeFromRunId; + enrichedContextSnapshot.resumeSessionDisplayId = explicitResumeSession.sessionDisplayId; + enrichedContextSnapshot.resumeSessionParams = explicitResumeSession.sessionParams; + if (!readNonEmptyString10(enrichedContextSnapshot.issueId) && explicitResumeSession.issueId) { + enrichedContextSnapshot.issueId = explicitResumeSession.issueId; + } + if (!readNonEmptyString10(enrichedContextSnapshot.taskId) && explicitResumeSession.taskId) { + enrichedContextSnapshot.taskId = explicitResumeSession.taskId; + } + if (!readNonEmptyString10(enrichedContextSnapshot.taskKey) && explicitResumeSession.taskKey) { + enrichedContextSnapshot.taskKey = explicitResumeSession.taskKey; + } + issueId = readNonEmptyString10(enrichedContextSnapshot.issueId) ?? issueId; + } + const effectiveTaskKey = readNonEmptyString10(enrichedContextSnapshot.taskKey) ?? taskKey; + const sessionBefore = explicitResumeSession?.sessionDisplayId ?? await resolveSessionBeforeForWakeup(agent, effectiveTaskKey); + const writeSkippedRequest = async (skipReason) => { + await db.insert(agentWakeupRequests).values({ + companyId: agent.companyId, + agentId, + source, + triggerDetail, + reason: skipReason, + payload: payload2, + status: "skipped", + requestedByActorType: opts.requestedByActorType ?? null, + requestedByActorId: opts.requestedByActorId ?? null, + idempotencyKey: opts.idempotencyKey ?? null, + finishedAt: /* @__PURE__ */ new Date() + }); + }; + let projectId = readNonEmptyString10(enrichedContextSnapshot.projectId); + if (!projectId && issueId) { + projectId = await db.select({ projectId: issues.projectId }).from(issues).where(and(eq(issues.id, issueId), eq(issues.companyId, agent.companyId))).then((rows) => rows[0]?.projectId ?? null); + } + const budgetBlock = await budgets.getInvocationBlock(agent.companyId, agentId, { + issueId, + projectId + }); + if (budgetBlock) { + await writeSkippedRequest("budget.blocked"); + throw conflict(budgetBlock.reason, { + scopeType: budgetBlock.scopeType, + scopeId: budgetBlock.scopeId + }); + } + if (agent.status === "paused" || agent.status === "terminated" || agent.status === "pending_approval") { + throw conflict("Agent is not invokable in its current state", { status: agent.status }); + } + const policy = parseHeartbeatPolicy(agent); + if (source === "timer" && !policy.enabled) { + await writeSkippedRequest("heartbeat.disabled"); + return null; + } + if (source !== "timer" && !policy.wakeOnDemand) { + await writeSkippedRequest("heartbeat.wakeOnDemand.disabled"); + return null; + } + if (issueId) { + const agentNameKey = normalizeAgentNameKey(agent.name); + const outcome = await db.transaction(async (tx) => { + await tx.execute( + sql`select id from issues where id = ${issueId} and company_id = ${agent.companyId} for update` + ); + const issue2 = await tx.select({ + id: issues.id, + companyId: issues.companyId, + executionRunId: issues.executionRunId, + executionAgentNameKey: issues.executionAgentNameKey + }).from(issues).where(and(eq(issues.id, issueId), eq(issues.companyId, agent.companyId))).then((rows) => rows[0] ?? null); + if (!issue2) { + await tx.insert(agentWakeupRequests).values({ + companyId: agent.companyId, + agentId, + source, + triggerDetail, + reason: "issue_execution_issue_not_found", + payload: payload2, + status: "skipped", + requestedByActorType: opts.requestedByActorType ?? null, + requestedByActorId: opts.requestedByActorId ?? null, + idempotencyKey: opts.idempotencyKey ?? null, + finishedAt: /* @__PURE__ */ new Date() + }); + return { kind: "skipped" }; + } + let activeExecutionRun = issue2.executionRunId ? await tx.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, issue2.executionRunId)).then((rows) => rows[0] ?? null) : null; + if (activeExecutionRun && activeExecutionRun.status !== "queued" && activeExecutionRun.status !== "running") { + activeExecutionRun = null; + } + if (!activeExecutionRun && issue2.executionRunId) { + await tx.update(issues).set({ + executionRunId: null, + executionAgentNameKey: null, + executionLockedAt: null, + updatedAt: /* @__PURE__ */ new Date() + }).where(eq(issues.id, issue2.id)); + } + if (!activeExecutionRun) { + const legacyRun = await tx.select().from(heartbeatRuns).where( + and( + eq(heartbeatRuns.companyId, issue2.companyId), + inArray(heartbeatRuns.status, ["queued", "running"]), + sql`${heartbeatRuns.contextSnapshot} ->> 'issueId' = ${issue2.id}` + ) + ).orderBy( + sql`case when ${heartbeatRuns.status} = 'running' then 0 else 1 end`, + asc(heartbeatRuns.createdAt) + ).limit(1).then((rows) => rows[0] ?? null); + if (legacyRun) { + activeExecutionRun = legacyRun; + const legacyAgent = await tx.select({ name: agents.name }).from(agents).where(eq(agents.id, legacyRun.agentId)).then((rows) => rows[0] ?? null); + await tx.update(issues).set({ + executionRunId: legacyRun.id, + executionAgentNameKey: normalizeAgentNameKey(legacyAgent?.name), + executionLockedAt: /* @__PURE__ */ new Date(), + updatedAt: /* @__PURE__ */ new Date() + }).where(eq(issues.id, issue2.id)); + } + } + if (activeExecutionRun) { + const executionAgent = await tx.select({ name: agents.name }).from(agents).where(eq(agents.id, activeExecutionRun.agentId)).then((rows) => rows[0] ?? null); + const executionAgentNameKey = normalizeAgentNameKey(issue2.executionAgentNameKey) ?? normalizeAgentNameKey(executionAgent?.name); + const isSameExecutionAgent = Boolean(executionAgentNameKey) && executionAgentNameKey === agentNameKey; + const shouldQueueFollowupForCommentWake2 = Boolean(wakeCommentId) && activeExecutionRun.status === "running" && isSameExecutionAgent; + if (isSameExecutionAgent && !shouldQueueFollowupForCommentWake2) { + const mergedContextSnapshot = mergeCoalescedContextSnapshot( + activeExecutionRun.contextSnapshot, + enrichedContextSnapshot + ); + const mergedRun = await tx.update(heartbeatRuns).set({ + contextSnapshot: mergedContextSnapshot, + updatedAt: /* @__PURE__ */ new Date() + }).where(eq(heartbeatRuns.id, activeExecutionRun.id)).returning().then((rows) => rows[0] ?? activeExecutionRun); + await tx.insert(agentWakeupRequests).values({ + companyId: agent.companyId, + agentId, + source, + triggerDetail, + reason: "issue_execution_same_name", + payload: payload2, + status: "coalesced", + coalescedCount: 1, + requestedByActorType: opts.requestedByActorType ?? null, + requestedByActorId: opts.requestedByActorId ?? null, + idempotencyKey: opts.idempotencyKey ?? null, + runId: mergedRun.id, + finishedAt: /* @__PURE__ */ new Date() + }); + return { kind: "coalesced", run: mergedRun }; + } + const deferredPayload = { + ...payload2 ?? {}, + issueId, + [DEFERRED_WAKE_CONTEXT_KEY]: enrichedContextSnapshot + }; + const existingDeferred = await tx.select().from(agentWakeupRequests).where( + and( + eq(agentWakeupRequests.companyId, agent.companyId), + eq(agentWakeupRequests.agentId, agentId), + eq(agentWakeupRequests.status, "deferred_issue_execution"), + sql`${agentWakeupRequests.payload} ->> 'issueId' = ${issue2.id}` + ) + ).orderBy(asc(agentWakeupRequests.requestedAt)).limit(1).then((rows) => rows[0] ?? null); + if (existingDeferred) { + const existingDeferredPayload = parseObject4(existingDeferred.payload); + const existingDeferredContext = parseObject4(existingDeferredPayload[DEFERRED_WAKE_CONTEXT_KEY]); + const mergedDeferredContext = mergeCoalescedContextSnapshot( + existingDeferredContext, + enrichedContextSnapshot + ); + const mergedDeferredPayload = { + ...existingDeferredPayload, + ...payload2 ?? {}, + issueId, + [DEFERRED_WAKE_CONTEXT_KEY]: mergedDeferredContext + }; + await tx.update(agentWakeupRequests).set({ + payload: mergedDeferredPayload, + coalescedCount: (existingDeferred.coalescedCount ?? 0) + 1, + updatedAt: /* @__PURE__ */ new Date() + }).where(eq(agentWakeupRequests.id, existingDeferred.id)); + return { kind: "deferred" }; + } + await tx.insert(agentWakeupRequests).values({ + companyId: agent.companyId, + agentId, + source, + triggerDetail, + reason: "issue_execution_deferred", + payload: deferredPayload, + status: "deferred_issue_execution", + requestedByActorType: opts.requestedByActorType ?? null, + requestedByActorId: opts.requestedByActorId ?? null, + idempotencyKey: opts.idempotencyKey ?? null + }); + return { kind: "deferred" }; + } + const wakeupRequest2 = await tx.insert(agentWakeupRequests).values({ + companyId: agent.companyId, + agentId, + source, + triggerDetail, + reason, + payload: payload2, + status: "queued", + requestedByActorType: opts.requestedByActorType ?? null, + requestedByActorId: opts.requestedByActorId ?? null, + idempotencyKey: opts.idempotencyKey ?? null + }).returning().then((rows) => rows[0]); + const newRun3 = await tx.insert(heartbeatRuns).values({ + companyId: agent.companyId, + agentId, + invocationSource: source, + triggerDetail, + status: "queued", + wakeupRequestId: wakeupRequest2.id, + contextSnapshot: enrichedContextSnapshot, + sessionIdBefore: sessionBefore + }).returning().then((rows) => rows[0]); + await tx.update(agentWakeupRequests).set({ + runId: newRun3.id, + updatedAt: /* @__PURE__ */ new Date() + }).where(eq(agentWakeupRequests.id, wakeupRequest2.id)); + return { kind: "queued", run: newRun3 }; + }); + if (outcome.kind === "deferred" || outcome.kind === "skipped") return null; + if (outcome.kind === "coalesced") return outcome.run; + const newRun2 = outcome.run; + publishLiveEvent({ + companyId: newRun2.companyId, + type: "heartbeat.run.queued", + payload: { + runId: newRun2.id, + agentId: newRun2.agentId, + invocationSource: newRun2.invocationSource, + triggerDetail: newRun2.triggerDetail, + wakeupRequestId: newRun2.wakeupRequestId + } + }); + await startNextQueuedRunForAgent(agent.id); + return newRun2; + } + const activeRuns = await db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.agentId, agentId), inArray(heartbeatRuns.status, ["queued", "running"]))).orderBy(desc(heartbeatRuns.createdAt)); + const sameScopeQueuedRun = activeRuns.find( + (candidate) => candidate.status === "queued" && isSameTaskScope(runTaskKey(candidate), taskKey) + ); + const sameScopeRunningRun = activeRuns.find( + (candidate) => candidate.status === "running" && isSameTaskScope(runTaskKey(candidate), taskKey) + ); + const shouldQueueFollowupForCommentWake = Boolean(wakeCommentId) && Boolean(sameScopeRunningRun) && !sameScopeQueuedRun; + const coalescedTargetRun = sameScopeQueuedRun ?? (shouldQueueFollowupForCommentWake ? null : sameScopeRunningRun ?? null); + if (coalescedTargetRun) { + const mergedContextSnapshot = mergeCoalescedContextSnapshot( + coalescedTargetRun.contextSnapshot, + contextSnapshot + ); + const mergedRun = await db.update(heartbeatRuns).set({ + contextSnapshot: mergedContextSnapshot, + updatedAt: /* @__PURE__ */ new Date() + }).where(eq(heartbeatRuns.id, coalescedTargetRun.id)).returning().then((rows) => rows[0] ?? coalescedTargetRun); + await db.insert(agentWakeupRequests).values({ + companyId: agent.companyId, + agentId, + source, + triggerDetail, + reason, + payload: payload2, + status: "coalesced", + coalescedCount: 1, + requestedByActorType: opts.requestedByActorType ?? null, + requestedByActorId: opts.requestedByActorId ?? null, + idempotencyKey: opts.idempotencyKey ?? null, + runId: mergedRun.id, + finishedAt: /* @__PURE__ */ new Date() + }); + return mergedRun; + } + const wakeupRequest = await db.insert(agentWakeupRequests).values({ + companyId: agent.companyId, + agentId, + source, + triggerDetail, + reason, + payload: payload2, + status: "queued", + requestedByActorType: opts.requestedByActorType ?? null, + requestedByActorId: opts.requestedByActorId ?? null, + idempotencyKey: opts.idempotencyKey ?? null + }).returning().then((rows) => rows[0]); + const newRun = await db.insert(heartbeatRuns).values({ + companyId: agent.companyId, + agentId, + invocationSource: source, + triggerDetail, + status: "queued", + wakeupRequestId: wakeupRequest.id, + contextSnapshot: enrichedContextSnapshot, + sessionIdBefore: sessionBefore + }).returning().then((rows) => rows[0]); + await db.update(agentWakeupRequests).set({ + runId: newRun.id, + updatedAt: /* @__PURE__ */ new Date() + }).where(eq(agentWakeupRequests.id, wakeupRequest.id)); + publishLiveEvent({ + companyId: newRun.companyId, + type: "heartbeat.run.queued", + payload: { + runId: newRun.id, + agentId: newRun.agentId, + invocationSource: newRun.invocationSource, + triggerDetail: newRun.triggerDetail, + wakeupRequestId: newRun.wakeupRequestId + } + }); + await startNextQueuedRunForAgent(agent.id); + return newRun; + } + async function listProjectScopedRunIds(companyId, projectId) { + const runIssueId = sql`${heartbeatRuns.contextSnapshot} ->> 'issueId'`; + const effectiveProjectId = sql`coalesce(${heartbeatRuns.contextSnapshot} ->> 'projectId', ${issues.projectId}::text)`; + const rows = await db.selectDistinctOn([heartbeatRuns.id], { id: heartbeatRuns.id }).from(heartbeatRuns).leftJoin( + issues, + and( + eq(issues.companyId, companyId), + sql`${issues.id}::text = ${runIssueId}` + ) + ).where( + and( + eq(heartbeatRuns.companyId, companyId), + inArray(heartbeatRuns.status, ["queued", "running"]), + sql`${effectiveProjectId} = ${projectId}` + ) + ); + return rows.map((row) => row.id); + } + async function listProjectScopedWakeupIds(companyId, projectId) { + const wakeIssueId = sql`${agentWakeupRequests.payload} ->> 'issueId'`; + const effectiveProjectId = sql`coalesce(${agentWakeupRequests.payload} ->> 'projectId', ${issues.projectId}::text)`; + const rows = await db.selectDistinctOn([agentWakeupRequests.id], { id: agentWakeupRequests.id }).from(agentWakeupRequests).leftJoin( + issues, + and( + eq(issues.companyId, companyId), + sql`${issues.id}::text = ${wakeIssueId}` + ) + ).where( + and( + eq(agentWakeupRequests.companyId, companyId), + inArray(agentWakeupRequests.status, ["queued", "deferred_issue_execution"]), + sql`${agentWakeupRequests.runId} is null`, + sql`${effectiveProjectId} = ${projectId}` + ) + ); + return rows.map((row) => row.id); + } + async function cancelPendingWakeupsForBudgetScope(scope) { + const now2 = /* @__PURE__ */ new Date(); + let wakeupIds = []; + if (scope.scopeType === "company") { + wakeupIds = await db.select({ id: agentWakeupRequests.id }).from(agentWakeupRequests).where( + and( + eq(agentWakeupRequests.companyId, scope.companyId), + inArray(agentWakeupRequests.status, ["queued", "deferred_issue_execution"]), + sql`${agentWakeupRequests.runId} is null` + ) + ).then((rows) => rows.map((row) => row.id)); + } else if (scope.scopeType === "agent") { + wakeupIds = await db.select({ id: agentWakeupRequests.id }).from(agentWakeupRequests).where( + and( + eq(agentWakeupRequests.companyId, scope.companyId), + eq(agentWakeupRequests.agentId, scope.scopeId), + inArray(agentWakeupRequests.status, ["queued", "deferred_issue_execution"]), + sql`${agentWakeupRequests.runId} is null` + ) + ).then((rows) => rows.map((row) => row.id)); + } else { + wakeupIds = await listProjectScopedWakeupIds(scope.companyId, scope.scopeId); + } + if (wakeupIds.length === 0) return 0; + await db.update(agentWakeupRequests).set({ + status: "cancelled", + finishedAt: now2, + error: "Cancelled due to budget pause", + updatedAt: now2 + }).where(inArray(agentWakeupRequests.id, wakeupIds)); + return wakeupIds.length; + } + async function cancelRunInternal(runId, reason = "Cancelled by control plane") { + const run = await getRun(runId); + if (!run) throw notFound("Heartbeat run not found"); + if (run.status !== "running" && run.status !== "queued") return run; + const running = runningProcesses3.get(run.id); + if (running) { + await terminateHeartbeatRunProcess({ + pid: running.child.pid ?? run.processPid, + processGroupId: running.processGroupId ?? run.processGroupId, + graceMs: Math.max(1, running.graceSec) * 1e3 + }); + } else if (run.processPid || run.processGroupId) { + await terminateHeartbeatRunProcess({ + pid: run.processPid, + processGroupId: run.processGroupId + }); + } + const cancelled = await setRunStatus(run.id, "cancelled", { + finishedAt: /* @__PURE__ */ new Date(), + error: reason, + errorCode: "cancelled" + }); + await setWakeupStatus(run.wakeupRequestId, "cancelled", { + finishedAt: /* @__PURE__ */ new Date(), + error: reason + }); + if (cancelled) { + await appendRunEvent(cancelled, 1, { + eventType: "lifecycle", + stream: "system", + level: "warn", + message: "run cancelled" + }); + await releaseIssueExecutionAndPromote(cancelled); + } + runningProcesses3.delete(run.id); + await finalizeAgentStatus(run.agentId, "cancelled"); + await startNextQueuedRunForAgent(run.agentId); + return cancelled; + } + async function cancelActiveForAgentInternal(agentId, reason = "Cancelled due to agent pause") { + const runs = await db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.agentId, agentId), inArray(heartbeatRuns.status, ["queued", "running"]))); + for (const run of runs) { + await setRunStatus(run.id, "cancelled", { + finishedAt: /* @__PURE__ */ new Date(), + error: reason, + errorCode: "cancelled" + }); + await setWakeupStatus(run.wakeupRequestId, "cancelled", { + finishedAt: /* @__PURE__ */ new Date(), + error: reason + }); + const running = runningProcesses3.get(run.id); + if (running) { + await terminateHeartbeatRunProcess({ + pid: running.child.pid ?? run.processPid, + processGroupId: running.processGroupId ?? run.processGroupId, + graceMs: Math.max(1, running.graceSec) * 1e3 + }); + runningProcesses3.delete(run.id); + } else if (run.processPid || run.processGroupId) { + await terminateHeartbeatRunProcess({ + pid: run.processPid, + processGroupId: run.processGroupId + }); + } + await releaseIssueExecutionAndPromote(run); + } + return runs.length; + } + async function cancelBudgetScopeWork(scope) { + if (scope.scopeType === "agent") { + await cancelActiveForAgentInternal(scope.scopeId, "Cancelled due to budget pause"); + await cancelPendingWakeupsForBudgetScope(scope); + return; + } + const runIds = scope.scopeType === "company" ? await db.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where( + and( + eq(heartbeatRuns.companyId, scope.companyId), + inArray(heartbeatRuns.status, ["queued", "running"]) + ) + ).then((rows) => rows.map((row) => row.id)) : await listProjectScopedRunIds(scope.companyId, scope.scopeId); + for (const runId of runIds) { + await cancelRunInternal(runId, "Cancelled due to budget pause"); + } + await cancelPendingWakeupsForBudgetScope(scope); + } + return { + list: async (companyId, agentId, limit) => { + const query = db.select(heartbeatRunListColumns).from(heartbeatRuns).where( + agentId ? and(eq(heartbeatRuns.companyId, companyId), eq(heartbeatRuns.agentId, agentId)) : eq(heartbeatRuns.companyId, companyId) + ).orderBy(desc(heartbeatRuns.createdAt)); + const rows = limit ? await query.limit(limit) : await query; + return rows.map((row) => ({ + ...row, + resultJson: summarizeHeartbeatRunResultJson(row.resultJson) + })); + }, + getRun, + getRuntimeState: async (agentId) => { + const state2 = await getRuntimeState(agentId); + const agent = await getAgent(agentId); + if (!agent) return null; + const ensured = state2 ?? await ensureRuntimeState(agent); + const latestTaskSession = await db.select().from(agentTaskSessions).where(and(eq(agentTaskSessions.companyId, agent.companyId), eq(agentTaskSessions.agentId, agent.id))).orderBy(desc(agentTaskSessions.updatedAt)).limit(1).then((rows) => rows[0] ?? null); + return { + ...ensured, + sessionDisplayId: latestTaskSession?.sessionDisplayId ?? ensured.sessionId, + sessionParamsJson: latestTaskSession?.sessionParamsJson ?? null + }; + }, + listTaskSessions: async (agentId) => { + const agent = await getAgent(agentId); + if (!agent) throw notFound("Agent not found"); + return db.select().from(agentTaskSessions).where(and(eq(agentTaskSessions.companyId, agent.companyId), eq(agentTaskSessions.agentId, agentId))).orderBy(desc(agentTaskSessions.updatedAt), desc(agentTaskSessions.createdAt)); + }, + resetRuntimeSession: async (agentId, opts) => { + const agent = await getAgent(agentId); + if (!agent) throw notFound("Agent not found"); + await ensureRuntimeState(agent); + const taskKey = readNonEmptyString10(opts?.taskKey); + const clearedTaskSessions = await clearTaskSessions( + agent.companyId, + agent.id, + taskKey ? { taskKey, adapterType: agent.adapterType } : void 0 + ); + const runtimePatch = { + sessionId: null, + lastError: null, + updatedAt: /* @__PURE__ */ new Date() + }; + if (!taskKey) { + runtimePatch.stateJson = {}; + } + const updated = await db.update(agentRuntimeState).set(runtimePatch).where(eq(agentRuntimeState.agentId, agentId)).returning().then((rows) => rows[0] ?? null); + if (!updated) return null; + return { + ...updated, + sessionDisplayId: null, + sessionParamsJson: null, + clearedTaskSessions + }; + }, + listEvents: (runId, afterSeq = 0, limit = 200) => db.select().from(heartbeatRunEvents).where(and(eq(heartbeatRunEvents.runId, runId), gt(heartbeatRunEvents.seq, afterSeq))).orderBy(asc(heartbeatRunEvents.seq)).limit(Math.max(1, Math.min(limit, 1e3))), + readLog: async (runId, opts) => { + const run = await getRun(runId); + if (!run) throw notFound("Heartbeat run not found"); + if (!run.logStore || !run.logRef) throw notFound("Run log not found"); + const result = await runLogStore.read( + { + store: run.logStore, + logRef: run.logRef + }, + opts + ); + return { + runId, + store: run.logStore, + logRef: run.logRef, + ...result, + content: redactCurrentUserText(result.content, await getCurrentUserRedactionOptions()) + }; + }, + invoke: async (agentId, source = "on_demand", contextSnapshot = {}, triggerDetail = "manual", actor) => enqueueWakeup(agentId, { + source, + triggerDetail, + contextSnapshot, + requestedByActorType: actor?.actorType, + requestedByActorId: actor?.actorId ?? null + }), + wakeup: enqueueWakeup, + reportRunActivity: clearDetachedRunWarning, + reapOrphanedRuns, + resumeQueuedRuns, + reconcileStrandedAssignedIssues, + tickTimers: async (now2 = /* @__PURE__ */ new Date()) => { + const allAgents = await db.select().from(agents); + let checked = 0; + let enqueued = 0; + let skipped = 0; + for (const agent of allAgents) { + if (agent.status === "paused" || agent.status === "terminated" || agent.status === "pending_approval") continue; + const policy = parseHeartbeatPolicy(agent); + if (!policy.enabled || policy.intervalSec <= 0) continue; + checked += 1; + const baseline = new Date(agent.lastHeartbeatAt ?? agent.createdAt).getTime(); + const elapsedMs = now2.getTime() - baseline; + if (elapsedMs < policy.intervalSec * 1e3) continue; + const run = await enqueueWakeup(agent.id, { + source: "timer", + triggerDetail: "system", + reason: "heartbeat_timer", + requestedByActorType: "system", + requestedByActorId: "heartbeat_scheduler", + contextSnapshot: { + source: "scheduler", + reason: "interval_elapsed", + now: now2.toISOString() + } + }); + if (run) enqueued += 1; + else skipped += 1; + } + return { checked, enqueued, skipped }; + }, + cancelRun: (runId) => cancelRunInternal(runId), + cancelActiveForAgent: (agentId) => cancelActiveForAgentInternal(agentId), + cancelBudgetScopeWork, + getRunIssueSummary: async (runId) => { + const [run] = await db.select(heartbeatRunIssueSummaryColumns).from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)).limit(1); + return run ?? null; + }, + getActiveRunForAgent: async (agentId) => { + const [run] = await db.select().from(heartbeatRuns).where( + and( + eq(heartbeatRuns.agentId, agentId), + eq(heartbeatRuns.status, "running") + ) + ).orderBy(desc(heartbeatRuns.startedAt)).limit(1); + return run ?? null; + }, + getActiveRunIssueSummaryForAgent: async (agentId) => { + const [run] = await db.select(heartbeatRunIssueSummaryColumns).from(heartbeatRuns).where( + and( + eq(heartbeatRuns.agentId, agentId), + eq(heartbeatRuns.status, "running") + ) + ).orderBy(desc(heartbeatRuns.startedAt)).limit(1); + return run ?? null; + } + }; +} + +// server/src/services/issue-assignment-wakeup.ts +function queueIssueAssignmentWakeup(input) { + if (!input.issue.assigneeAgentId || input.issue.status === "backlog") return; + return input.heartbeat.wakeup(input.issue.assigneeAgentId, { + source: "assignment", + triggerDetail: "system", + reason: input.reason, + payload: { issueId: input.issue.id, mutation: input.mutation }, + requestedByActorType: input.requestedByActorType, + requestedByActorId: input.requestedByActorId ?? null, + contextSnapshot: { issueId: input.issue.id, source: input.contextSource } + }).catch((err) => { + logger.warn({ err, issueId: input.issue.id }, "failed to wake assignee on issue assignment"); + if (input.rethrowOnError) throw err; + return null; + }); +} + +// server/src/services/routines.ts +var OPEN_ISSUE_STATUSES = ["backlog", "todo", "in_progress", "in_review", "blocked"]; +var LIVE_HEARTBEAT_RUN_STATUSES = ["queued", "running"]; +var MAX_CATCH_UP_RUNS = 25; +var WEEKDAY_INDEX = { + Sun: 0, + Mon: 1, + Tue: 2, + Wed: 3, + Thu: 4, + Fri: 5, + Sat: 6 +}; +function assertTimeZone(timeZone) { + try { + new Intl.DateTimeFormat("en-US", { timeZone }).format(/* @__PURE__ */ new Date()); + } catch { + throw unprocessable(`Invalid timezone: ${timeZone}`); + } +} +function floorToMinute(date7) { + const copy = new Date(date7.getTime()); + copy.setUTCSeconds(0, 0); + return copy; +} +function getZonedMinuteParts(date7, timeZone) { + const formatter = new Intl.DateTimeFormat("en-US", { + timeZone, + hour12: false, + year: "numeric", + month: "numeric", + day: "numeric", + hour: "numeric", + minute: "numeric", + weekday: "short" + }); + const parts = formatter.formatToParts(date7); + const map4 = Object.fromEntries(parts.map((part) => [part.type, part.value])); + const weekday = WEEKDAY_INDEX[map4.weekday ?? ""]; + if (weekday == null) { + throw new Error(`Unable to resolve weekday for timezone ${timeZone}`); + } + return { + year: Number(map4.year), + month: Number(map4.month), + day: Number(map4.day), + hour: Number(map4.hour), + minute: Number(map4.minute), + weekday + }; +} +function matchesCronMinute(expression, timeZone, date7) { + const cron = parseCron(expression); + const parts = getZonedMinuteParts(date7, timeZone); + return cron.minutes.includes(parts.minute) && cron.hours.includes(parts.hour) && cron.daysOfMonth.includes(parts.day) && cron.months.includes(parts.month) && cron.daysOfWeek.includes(parts.weekday); +} +function nextCronTickInTimeZone(expression, timeZone, after) { + const trimmed = expression.trim(); + assertTimeZone(timeZone); + const error50 = validateCron(trimmed); + if (error50) { + throw unprocessable(error50); + } + const cursor2 = floorToMinute(after); + cursor2.setUTCMinutes(cursor2.getUTCMinutes() + 1); + const limit = 366 * 24 * 60 * 5; + for (let i5 = 0; i5 < limit; i5 += 1) { + if (matchesCronMinute(trimmed, timeZone, cursor2)) { + return new Date(cursor2.getTime()); + } + cursor2.setUTCMinutes(cursor2.getUTCMinutes() + 1); + } + return null; +} +function nextResultText(status, issueId) { + if (status === "issue_created" && issueId) return `Created execution issue ${issueId}`; + if (status === "coalesced") return "Coalesced into an existing live execution issue"; + if (status === "skipped") return "Skipped because a live execution issue already exists"; + if (status === "completed") return "Execution issue completed"; + if (status === "failed") return "Execution failed"; + return status; +} +function normalizeWebhookTimestampMs(rawTimestamp) { + const parsed = Number(rawTimestamp); + if (!Number.isFinite(parsed)) return null; + return parsed > 1e12 ? parsed : parsed * 1e3; +} +function isPlainRecord4(value) { + return typeof value === "object" && value !== null && !Array.isArray(value); +} +function parseBooleanVariableValue(name, raw) { + if (typeof raw === "boolean") return raw; + if (typeof raw === "number" && (raw === 0 || raw === 1)) return raw === 1; + if (typeof raw === "string") { + const normalized = raw.trim().toLowerCase(); + if (["true", "1", "yes", "y", "on"].includes(normalized)) return true; + if (["false", "0", "no", "n", "off"].includes(normalized)) return false; + } + throw unprocessable(`Variable "${name}" must be a boolean`); +} +function parseNumberVariableValue(name, raw) { + if (typeof raw === "number" && Number.isFinite(raw)) return raw; + if (typeof raw === "string" && raw.trim().length > 0) { + const parsed = Number(raw); + if (Number.isFinite(parsed)) return parsed; + } + throw unprocessable(`Variable "${name}" must be a number`); +} +function normalizeRoutineVariableValue(variable, raw) { + if (raw == null) return null; + if (variable.type === "boolean") return parseBooleanVariableValue(variable.name, raw); + if (variable.type === "number") return parseNumberVariableValue(variable.name, raw); + const normalized = stringifyRoutineVariableValue(raw); + if (variable.type === "select") { + if (!variable.options.includes(normalized)) { + throw unprocessable(`Variable "${variable.name}" must match one of: ${variable.options.join(", ")}`); + } + } + return normalized; +} +function isMissingRoutineVariableValue(value) { + return value == null || typeof value === "string" && value.trim().length === 0; +} +function assertRoutineVariableDefinitions(variables) { + for (const variable of variables) { + if (variable.defaultValue != null) { + normalizeRoutineVariableValue(variable, variable.defaultValue); + } + if (variable.type === "select" && variable.options.length === 0) { + throw unprocessable(`Variable "${variable.name}" must define at least one option`); + } + } +} +function sanitizeRoutineVariableInputs(variables) { + return (variables ?? []).map((variable) => ({ + name: variable.name, + label: variable.label ?? null, + type: variable.type ?? "text", + defaultValue: variable.defaultValue ?? null, + required: variable.required ?? true, + options: variable.options ?? [] + })); +} +function assertScheduleCompatibleVariables(variables) { + const missingDefaults = variables.filter((variable) => variable.required).filter((variable) => { + try { + return isMissingRoutineVariableValue(normalizeRoutineVariableValue(variable, variable.defaultValue)); + } catch { + return true; + } + }).map((variable) => variable.name); + if (missingDefaults.length > 0) { + throw unprocessable( + `Scheduled routines require defaults for required variables: ${missingDefaults.join(", ")}` + ); + } +} +function statusRequiresDefaultAgent(status) { + return status === "active"; +} +function normalizeDraftRoutineStatus(status, assigneeAgentId) { + if (statusRequiresDefaultAgent(status) && !assigneeAgentId) { + return "paused"; + } + return status; +} +function assertRoutineCanEnable(status, assigneeAgentId) { + if (statusRequiresDefaultAgent(status) && !assigneeAgentId) { + throw unprocessable("Default agent required"); + } +} +function collectProvidedRoutineVariables(source, payload2, variables) { + const nestedVariables = isPlainRecord4(payload2) && isPlainRecord4(payload2.variables) ? payload2.variables : {}; + const provided = { + ...source === "webhook" && payload2 ? payload2 : {}, + ...nestedVariables, + ...variables ?? {} + }; + delete provided.variables; + return provided; +} +function resolveRoutineVariableValues(variables, input) { + if (variables.length === 0) return {}; + const provided = collectProvidedRoutineVariables(input.source, input.payload, input.variables); + const resolved = {}; + const missing = []; + for (const variable of variables) { + const candidate = provided[variable.name] !== void 0 ? provided[variable.name] : variable.defaultValue; + const normalized = normalizeRoutineVariableValue(variable, candidate); + if (normalized == null || typeof normalized === "string" && normalized.trim().length === 0) { + if (variable.required) missing.push(variable.name); + continue; + } + resolved[variable.name] = normalized; + } + if (missing.length > 0) { + throw unprocessable(`Missing routine variables: ${missing.join(", ")}`); + } + return resolved; +} +function mergeRoutineRunPayload(payload2, variables) { + if (Object.keys(variables).length === 0) return payload2 ?? null; + if (!payload2) return { variables }; + const existingVariables = isPlainRecord4(payload2.variables) ? payload2.variables : {}; + return { + ...payload2, + variables: { + ...existingVariables, + ...variables + } + }; +} +function routineService(db, deps = {}) { + const issueSvc = issueService(db); + const secretsSvc = secretService(db); + const heartbeat = deps.heartbeat ?? heartbeatService(db); + async function getRoutineById(id) { + return db.select().from(routines).where(eq(routines.id, id)).then((rows) => rows[0] ?? null); + } + async function getTriggerById(id) { + return db.select().from(routineTriggers).where(eq(routineTriggers.id, id)).then((rows) => rows[0] ?? null); + } + async function assertRoutineAccess(companyId, routineId) { + const routine = await getRoutineById(routineId); + if (!routine) throw notFound("Routine not found"); + if (routine.companyId !== companyId) throw forbidden("Routine must belong to same company"); + return routine; + } + async function assertAssignableAgent(companyId, agentId) { + if (!agentId) return; + const agent = await db.select({ id: agents.id, companyId: agents.companyId, status: agents.status }).from(agents).where(eq(agents.id, agentId)).then((rows) => rows[0] ?? null); + if (!agent) throw notFound("Assignee agent not found"); + if (agent.companyId !== companyId) throw unprocessable("Assignee must belong to same company"); + if (agent.status === "pending_approval") throw conflict("Cannot assign routines to pending approval agents"); + if (agent.status === "terminated") throw conflict("Cannot assign routines to terminated agents"); + } + async function assertProject(companyId, projectId) { + if (!projectId) return; + const project = await db.select({ id: projects.id, companyId: projects.companyId }).from(projects).where(eq(projects.id, projectId)).then((rows) => rows[0] ?? null); + if (!project) throw notFound("Project not found"); + if (project.companyId !== companyId) throw unprocessable("Project must belong to same company"); + } + async function assertGoal(companyId, goalId) { + const goal = await db.select({ id: goals.id, companyId: goals.companyId }).from(goals).where(eq(goals.id, goalId)).then((rows) => rows[0] ?? null); + if (!goal) throw notFound("Goal not found"); + if (goal.companyId !== companyId) throw unprocessable("Goal must belong to same company"); + } + async function assertParentIssue(companyId, issueId) { + const parentIssue = await db.select({ id: issues.id, companyId: issues.companyId }).from(issues).where(eq(issues.id, issueId)).then((rows) => rows[0] ?? null); + if (!parentIssue) throw notFound("Parent issue not found"); + if (parentIssue.companyId !== companyId) throw unprocessable("Parent issue must belong to same company"); + } + async function listTriggersForRoutineIds(companyId, routineIds) { + if (routineIds.length === 0) return /* @__PURE__ */ new Map(); + const rows = await db.select().from(routineTriggers).where(and(eq(routineTriggers.companyId, companyId), inArray(routineTriggers.routineId, routineIds))).orderBy(asc(routineTriggers.createdAt), asc(routineTriggers.id)); + const map4 = /* @__PURE__ */ new Map(); + for (const row of rows) { + const list2 = map4.get(row.routineId) ?? []; + list2.push(row); + map4.set(row.routineId, list2); + } + return map4; + } + async function listLatestRunByRoutineIds(companyId, routineIds) { + if (routineIds.length === 0) return /* @__PURE__ */ new Map(); + const rows = await db.selectDistinctOn([routineRuns.routineId], { + id: routineRuns.id, + companyId: routineRuns.companyId, + routineId: routineRuns.routineId, + triggerId: routineRuns.triggerId, + source: routineRuns.source, + status: routineRuns.status, + triggeredAt: routineRuns.triggeredAt, + idempotencyKey: routineRuns.idempotencyKey, + triggerPayload: routineRuns.triggerPayload, + linkedIssueId: routineRuns.linkedIssueId, + coalescedIntoRunId: routineRuns.coalescedIntoRunId, + failureReason: routineRuns.failureReason, + completedAt: routineRuns.completedAt, + createdAt: routineRuns.createdAt, + updatedAt: routineRuns.updatedAt, + triggerKind: routineTriggers.kind, + triggerLabel: routineTriggers.label, + issueIdentifier: issues.identifier, + issueTitle: issues.title, + issueStatus: issues.status, + issuePriority: issues.priority, + issueUpdatedAt: issues.updatedAt + }).from(routineRuns).leftJoin(routineTriggers, eq(routineRuns.triggerId, routineTriggers.id)).leftJoin(issues, eq(routineRuns.linkedIssueId, issues.id)).where(and(eq(routineRuns.companyId, companyId), inArray(routineRuns.routineId, routineIds))).orderBy(routineRuns.routineId, desc(routineRuns.createdAt), desc(routineRuns.id)); + const map4 = /* @__PURE__ */ new Map(); + for (const row of rows) { + map4.set(row.routineId, { + id: row.id, + companyId: row.companyId, + routineId: row.routineId, + triggerId: row.triggerId, + source: row.source, + status: row.status, + triggeredAt: row.triggeredAt, + idempotencyKey: row.idempotencyKey, + triggerPayload: row.triggerPayload, + linkedIssueId: row.linkedIssueId, + coalescedIntoRunId: row.coalescedIntoRunId, + failureReason: row.failureReason, + completedAt: row.completedAt, + createdAt: row.createdAt, + updatedAt: row.updatedAt, + linkedIssue: row.linkedIssueId ? { + id: row.linkedIssueId, + identifier: row.issueIdentifier, + title: row.issueTitle ?? "Routine execution", + status: row.issueStatus ?? "todo", + priority: row.issuePriority ?? "medium", + updatedAt: row.issueUpdatedAt ?? row.updatedAt + } : null, + trigger: row.triggerId ? { + id: row.triggerId, + kind: row.triggerKind, + label: row.triggerLabel + } : null + }); + } + return map4; + } + async function listLiveIssueByRoutineIds(companyId, routineIds) { + if (routineIds.length === 0) return /* @__PURE__ */ new Map(); + const executionBoundRows = await db.selectDistinctOn([issues.originId], { + originId: issues.originId, + id: issues.id, + identifier: issues.identifier, + title: issues.title, + status: issues.status, + priority: issues.priority, + updatedAt: issues.updatedAt + }).from(issues).innerJoin( + heartbeatRuns, + and( + eq(heartbeatRuns.id, issues.executionRunId), + inArray(heartbeatRuns.status, LIVE_HEARTBEAT_RUN_STATUSES) + ) + ).where( + and( + eq(issues.companyId, companyId), + eq(issues.originKind, "routine_execution"), + inArray(issues.originId, routineIds), + inArray(issues.status, OPEN_ISSUE_STATUSES), + isNull(issues.hiddenAt) + ) + ).orderBy(issues.originId, desc(issues.updatedAt), desc(issues.createdAt)); + const rowsByOriginId = /* @__PURE__ */ new Map(); + for (const row of executionBoundRows) { + if (!row.originId) continue; + rowsByOriginId.set(row.originId, row); + } + const missingRoutineIds = routineIds.filter((routineId) => !rowsByOriginId.has(routineId)); + if (missingRoutineIds.length > 0) { + const legacyRows = await db.selectDistinctOn([issues.originId], { + originId: issues.originId, + id: issues.id, + identifier: issues.identifier, + title: issues.title, + status: issues.status, + priority: issues.priority, + updatedAt: issues.updatedAt + }).from(issues).innerJoin( + heartbeatRuns, + and( + eq(heartbeatRuns.companyId, issues.companyId), + inArray(heartbeatRuns.status, LIVE_HEARTBEAT_RUN_STATUSES), + sql`${heartbeatRuns.contextSnapshot} ->> 'issueId' = cast(${issues.id} as text)` + ) + ).where( + and( + eq(issues.companyId, companyId), + eq(issues.originKind, "routine_execution"), + inArray(issues.originId, missingRoutineIds), + inArray(issues.status, OPEN_ISSUE_STATUSES), + isNull(issues.hiddenAt) + ) + ).orderBy(issues.originId, desc(issues.updatedAt), desc(issues.createdAt)); + for (const row of legacyRows) { + if (!row.originId) continue; + rowsByOriginId.set(row.originId, row); + } + } + const map4 = /* @__PURE__ */ new Map(); + for (const row of rowsByOriginId.values()) { + if (!row.originId) continue; + map4.set(row.originId, { + id: row.id, + identifier: row.identifier, + title: row.title, + status: row.status, + priority: row.priority, + updatedAt: row.updatedAt + }); + } + return map4; + } + async function updateRoutineTouchedState(input, executor = db) { + await executor.update(routines).set({ + lastTriggeredAt: input.triggeredAt, + lastEnqueuedAt: input.issueId ? input.triggeredAt : void 0, + updatedAt: /* @__PURE__ */ new Date() + }).where(eq(routines.id, input.routineId)); + if (input.triggerId) { + await executor.update(routineTriggers).set({ + lastFiredAt: input.triggeredAt, + lastResult: nextResultText(input.status, input.issueId), + nextRunAt: input.nextRunAt === void 0 ? void 0 : input.nextRunAt, + updatedAt: /* @__PURE__ */ new Date() + }).where(eq(routineTriggers.id, input.triggerId)); + } + } + async function findLiveExecutionIssue(routine, executor = db) { + const executionBoundIssue = await executor.select().from(issues).innerJoin( + heartbeatRuns, + and( + eq(heartbeatRuns.id, issues.executionRunId), + inArray(heartbeatRuns.status, LIVE_HEARTBEAT_RUN_STATUSES) + ) + ).where( + and( + eq(issues.companyId, routine.companyId), + eq(issues.originKind, "routine_execution"), + eq(issues.originId, routine.id), + inArray(issues.status, OPEN_ISSUE_STATUSES), + isNull(issues.hiddenAt) + ) + ).orderBy(desc(issues.updatedAt), desc(issues.createdAt)).limit(1).then((rows) => rows[0]?.issues ?? null); + if (executionBoundIssue) return executionBoundIssue; + return executor.select().from(issues).innerJoin( + heartbeatRuns, + and( + eq(heartbeatRuns.companyId, issues.companyId), + inArray(heartbeatRuns.status, LIVE_HEARTBEAT_RUN_STATUSES), + sql`${heartbeatRuns.contextSnapshot} ->> 'issueId' = cast(${issues.id} as text)` + ) + ).where( + and( + eq(issues.companyId, routine.companyId), + eq(issues.originKind, "routine_execution"), + eq(issues.originId, routine.id), + inArray(issues.status, OPEN_ISSUE_STATUSES), + isNull(issues.hiddenAt) + ) + ).orderBy(desc(issues.updatedAt), desc(issues.createdAt)).limit(1).then((rows) => rows[0]?.issues ?? null); + } + async function finalizeRun(runId, patch, executor = db) { + return executor.update(routineRuns).set({ + ...patch, + updatedAt: /* @__PURE__ */ new Date() + }).where(eq(routineRuns.id, runId)).returning().then((rows) => rows[0] ?? null); + } + async function createWebhookSecret(companyId, routineId, actor) { + const secretValue = crypto4.randomBytes(24).toString("hex"); + const secret = await secretsSvc.create( + companyId, + { + name: `routine-${routineId}-${crypto4.randomBytes(6).toString("hex")}`, + provider: "local_encrypted", + value: secretValue, + description: `Webhook auth for routine ${routineId}` + }, + actor + ); + return { secret, secretValue }; + } + async function resolveTriggerSecret(trigger, companyId) { + if (!trigger.secretId) throw notFound("Routine trigger secret not found"); + const secret = await db.select().from(companySecrets).where(eq(companySecrets.id, trigger.secretId)).then((rows) => rows[0] ?? null); + if (!secret || secret.companyId !== companyId) throw notFound("Routine trigger secret not found"); + const value = await secretsSvc.resolveSecretValue(companyId, trigger.secretId, "latest"); + return value; + } + async function dispatchRoutineRun(input) { + const projectId = input.projectId ?? input.routine.projectId ?? null; + const assigneeAgentId = input.assigneeAgentId ?? input.routine.assigneeAgentId ?? null; + if (!assigneeAgentId) { + throw unprocessable("Default agent required"); + } + const resolvedVariables = resolveRoutineVariableValues(input.routine.variables ?? [], input); + const allVariables = { ...getBuiltinRoutineVariableValues(), ...resolvedVariables }; + const title = interpolateRoutineTemplate(input.routine.title, allVariables) ?? input.routine.title; + const description = interpolateRoutineTemplate(input.routine.description, allVariables); + const triggerPayload = mergeRoutineRunPayload(input.payload, resolvedVariables); + const run = await db.transaction(async (tx) => { + const txDb = tx; + await tx.execute( + sql`select id from ${routines} where ${routines.id} = ${input.routine.id} and ${routines.companyId} = ${input.routine.companyId} for update` + ); + if (input.idempotencyKey) { + const existing = await txDb.select().from(routineRuns).where( + and( + eq(routineRuns.companyId, input.routine.companyId), + eq(routineRuns.routineId, input.routine.id), + eq(routineRuns.source, input.source), + eq(routineRuns.idempotencyKey, input.idempotencyKey), + input.trigger ? eq(routineRuns.triggerId, input.trigger.id) : isNull(routineRuns.triggerId) + ) + ).orderBy(desc(routineRuns.createdAt)).limit(1).then((rows) => rows[0] ?? null); + if (existing) return existing; + } + const triggeredAt = /* @__PURE__ */ new Date(); + const [createdRun] = await txDb.insert(routineRuns).values({ + companyId: input.routine.companyId, + routineId: input.routine.id, + triggerId: input.trigger?.id ?? null, + source: input.source, + status: "received", + triggeredAt, + idempotencyKey: input.idempotencyKey ?? null, + triggerPayload + }).returning(); + const nextRunAt = input.trigger?.kind === "schedule" && input.trigger.cronExpression && input.trigger.timezone ? nextCronTickInTimeZone(input.trigger.cronExpression, input.trigger.timezone, triggeredAt) : void 0; + let createdIssue = null; + try { + const activeIssue = await findLiveExecutionIssue(input.routine, txDb); + if (activeIssue && input.routine.concurrencyPolicy !== "always_enqueue") { + const status = input.routine.concurrencyPolicy === "skip_if_active" ? "skipped" : "coalesced"; + const updated2 = await finalizeRun(createdRun.id, { + status, + linkedIssueId: activeIssue.id, + coalescedIntoRunId: activeIssue.originRunId, + completedAt: triggeredAt + }, txDb); + await updateRoutineTouchedState({ + routineId: input.routine.id, + triggerId: input.trigger?.id ?? null, + triggeredAt, + status, + issueId: activeIssue.id, + nextRunAt + }, txDb); + return updated2 ?? createdRun; + } + try { + createdIssue = await issueSvc.create(input.routine.companyId, { + projectId, + goalId: input.routine.goalId, + parentId: input.routine.parentIssueId, + title, + description, + status: "todo", + priority: input.routine.priority, + assigneeAgentId, + originKind: "routine_execution", + originId: input.routine.id, + originRunId: createdRun.id, + executionWorkspaceId: input.executionWorkspaceId ?? null, + executionWorkspacePreference: input.executionWorkspacePreference ?? null, + executionWorkspaceSettings: input.executionWorkspaceSettings ?? null + }); + } catch (error50) { + const isOpenExecutionConflict = !!error50 && typeof error50 === "object" && "code" in error50 && error50.code === "23505" && "constraint" in error50 && error50.constraint === "issues_open_routine_execution_uq"; + if (!isOpenExecutionConflict || input.routine.concurrencyPolicy === "always_enqueue") { + throw error50; + } + const existingIssue = await findLiveExecutionIssue(input.routine, txDb); + if (!existingIssue) throw error50; + const status = input.routine.concurrencyPolicy === "skip_if_active" ? "skipped" : "coalesced"; + const updated2 = await finalizeRun(createdRun.id, { + status, + linkedIssueId: existingIssue.id, + coalescedIntoRunId: existingIssue.originRunId, + completedAt: triggeredAt + }, txDb); + await updateRoutineTouchedState({ + routineId: input.routine.id, + triggerId: input.trigger?.id ?? null, + triggeredAt, + status, + issueId: existingIssue.id, + nextRunAt + }, txDb); + return updated2 ?? createdRun; + } + await queueIssueAssignmentWakeup({ + heartbeat, + issue: createdIssue, + reason: "issue_assigned", + mutation: "create", + contextSource: "routine.dispatch", + requestedByActorType: input.source === "schedule" ? "system" : void 0, + rethrowOnError: true + }); + const updated = await finalizeRun(createdRun.id, { + status: "issue_created", + linkedIssueId: createdIssue.id + }, txDb); + await updateRoutineTouchedState({ + routineId: input.routine.id, + triggerId: input.trigger?.id ?? null, + triggeredAt, + status: "issue_created", + issueId: createdIssue.id, + nextRunAt + }, txDb); + return updated ?? createdRun; + } catch (error50) { + if (createdIssue) { + await txDb.delete(issues).where(eq(issues.id, createdIssue.id)); + } + const failureReason = error50 instanceof Error ? error50.message : String(error50); + const failed = await finalizeRun(createdRun.id, { + status: "failed", + failureReason, + completedAt: /* @__PURE__ */ new Date() + }, txDb); + await updateRoutineTouchedState({ + routineId: input.routine.id, + triggerId: input.trigger?.id ?? null, + triggeredAt, + status: "failed", + nextRunAt + }, txDb); + return failed ?? createdRun; + } + }); + if (input.source === "schedule" || input.source === "webhook") { + const actorId = input.source === "schedule" ? "routine-scheduler" : "routine-webhook"; + try { + await logActivity(db, { + companyId: input.routine.companyId, + actorType: "system", + actorId, + action: "routine.run_triggered", + entityType: "routine_run", + entityId: run.id, + details: { + routineId: input.routine.id, + triggerId: input.trigger?.id ?? null, + source: run.source, + status: run.status + } + }); + } catch (err) { + logger.warn({ err, routineId: input.routine.id, runId: run.id }, "failed to log automated routine run"); + } + } + const telemetryClient = getTelemetryClient(); + if (telemetryClient) { + trackRoutineRun(telemetryClient, { + source: run.source, + status: run.status + }); + } + return run; + } + return { + get: getRoutineById, + getTrigger: getTriggerById, + list: async (companyId) => { + const rows = await db.select().from(routines).where(eq(routines.companyId, companyId)).orderBy(desc(routines.updatedAt), asc(routines.title)); + const routineIds = rows.map((row) => row.id); + const [triggersByRoutine, latestRunByRoutine, activeIssueByRoutine] = await Promise.all([ + listTriggersForRoutineIds(companyId, routineIds), + listLatestRunByRoutineIds(companyId, routineIds), + listLiveIssueByRoutineIds(companyId, routineIds) + ]); + return rows.map((row) => ({ + ...row, + triggers: (triggersByRoutine.get(row.id) ?? []).map((trigger) => ({ + id: trigger.id, + kind: trigger.kind, + label: trigger.label, + enabled: trigger.enabled, + nextRunAt: trigger.nextRunAt, + lastFiredAt: trigger.lastFiredAt, + lastResult: trigger.lastResult + })), + lastRun: latestRunByRoutine.get(row.id) ?? null, + activeIssue: activeIssueByRoutine.get(row.id) ?? null + })); + }, + getDetail: async (id) => { + const row = await getRoutineById(id); + if (!row) return null; + const [project, assignee, parentIssue, triggers, recentRuns, activeIssue] = await Promise.all([ + row.projectId ? db.select().from(projects).where(eq(projects.id, row.projectId)).then((rows) => rows[0] ?? null) : null, + row.assigneeAgentId ? db.select().from(agents).where(eq(agents.id, row.assigneeAgentId)).then((rows) => rows[0] ?? null) : null, + row.parentIssueId ? issueSvc.getById(row.parentIssueId) : null, + db.select().from(routineTriggers).where(eq(routineTriggers.routineId, row.id)).orderBy(asc(routineTriggers.createdAt)), + db.select({ + id: routineRuns.id, + companyId: routineRuns.companyId, + routineId: routineRuns.routineId, + triggerId: routineRuns.triggerId, + source: routineRuns.source, + status: routineRuns.status, + triggeredAt: routineRuns.triggeredAt, + idempotencyKey: routineRuns.idempotencyKey, + triggerPayload: routineRuns.triggerPayload, + linkedIssueId: routineRuns.linkedIssueId, + coalescedIntoRunId: routineRuns.coalescedIntoRunId, + failureReason: routineRuns.failureReason, + completedAt: routineRuns.completedAt, + createdAt: routineRuns.createdAt, + updatedAt: routineRuns.updatedAt, + triggerKind: routineTriggers.kind, + triggerLabel: routineTriggers.label, + issueIdentifier: issues.identifier, + issueTitle: issues.title, + issueStatus: issues.status, + issuePriority: issues.priority, + issueUpdatedAt: issues.updatedAt + }).from(routineRuns).leftJoin(routineTriggers, eq(routineRuns.triggerId, routineTriggers.id)).leftJoin(issues, eq(routineRuns.linkedIssueId, issues.id)).where(eq(routineRuns.routineId, row.id)).orderBy(desc(routineRuns.createdAt)).limit(25).then( + (runs) => runs.map((run) => ({ + id: run.id, + companyId: run.companyId, + routineId: run.routineId, + triggerId: run.triggerId, + source: run.source, + status: run.status, + triggeredAt: run.triggeredAt, + idempotencyKey: run.idempotencyKey, + triggerPayload: run.triggerPayload, + linkedIssueId: run.linkedIssueId, + coalescedIntoRunId: run.coalescedIntoRunId, + failureReason: run.failureReason, + completedAt: run.completedAt, + createdAt: run.createdAt, + updatedAt: run.updatedAt, + linkedIssue: run.linkedIssueId ? { + id: run.linkedIssueId, + identifier: run.issueIdentifier, + title: run.issueTitle ?? "Routine execution", + status: run.issueStatus ?? "todo", + priority: run.issuePriority ?? "medium", + updatedAt: run.issueUpdatedAt ?? run.updatedAt + } : null, + trigger: run.triggerId ? { + id: run.triggerId, + kind: run.triggerKind, + label: run.triggerLabel + } : null + })) + ), + findLiveExecutionIssue(row) + ]); + return { + ...row, + project, + assignee, + parentIssue, + triggers, + recentRuns, + activeIssue + }; + }, + create: async (companyId, input, actor) => { + await assertProject(companyId, input.projectId ?? null); + await assertAssignableAgent(companyId, input.assigneeAgentId ?? null); + if (input.goalId) await assertGoal(companyId, input.goalId); + if (input.parentIssueId) await assertParentIssue(companyId, input.parentIssueId); + const variables = syncRoutineVariablesWithTemplate( + [input.title, input.description], + sanitizeRoutineVariableInputs(input.variables) + ); + assertRoutineVariableDefinitions(variables); + const status = normalizeDraftRoutineStatus(input.status, input.assigneeAgentId); + const [created] = await db.insert(routines).values({ + companyId, + projectId: input.projectId ?? null, + goalId: input.goalId ?? null, + parentIssueId: input.parentIssueId ?? null, + title: input.title, + description: input.description ?? null, + assigneeAgentId: input.assigneeAgentId ?? null, + priority: input.priority, + status, + concurrencyPolicy: input.concurrencyPolicy, + catchUpPolicy: input.catchUpPolicy, + variables, + createdByAgentId: actor.agentId ?? null, + createdByUserId: actor.userId ?? null, + updatedByAgentId: actor.agentId ?? null, + updatedByUserId: actor.userId ?? null + }).returning(); + return created; + }, + update: async (id, patch, actor) => { + const existing = await getRoutineById(id); + if (!existing) return null; + const nextProjectId = patch.projectId === void 0 ? existing.projectId : patch.projectId; + const nextAssigneeAgentId = patch.assigneeAgentId === void 0 ? existing.assigneeAgentId : patch.assigneeAgentId; + const nextTitle = patch.title ?? existing.title; + const nextDescription = patch.description === void 0 ? existing.description : patch.description; + const requestedStatus = patch.status ?? existing.status; + if (patch.status === "active") { + assertRoutineCanEnable(patch.status, nextAssigneeAgentId); + } + const nextStatus = patch.assigneeAgentId === void 0 ? requestedStatus : normalizeDraftRoutineStatus(requestedStatus, nextAssigneeAgentId); + const nextVariables = syncRoutineVariablesWithTemplate( + [nextTitle, nextDescription], + patch.variables === void 0 ? existing.variables : sanitizeRoutineVariableInputs(patch.variables) + ); + if (patch.projectId !== void 0) await assertProject(existing.companyId, nextProjectId); + if (patch.assigneeAgentId !== void 0) await assertAssignableAgent(existing.companyId, nextAssigneeAgentId); + if (patch.goalId) await assertGoal(existing.companyId, patch.goalId); + if (patch.parentIssueId) await assertParentIssue(existing.companyId, patch.parentIssueId); + assertRoutineVariableDefinitions(nextVariables); + const enabledScheduleTriggers = await db.select({ id: routineTriggers.id }).from(routineTriggers).where( + and( + eq(routineTriggers.routineId, existing.id), + eq(routineTriggers.kind, "schedule"), + eq(routineTriggers.enabled, true) + ) + ).limit(1).then((rows) => rows.length > 0); + if (enabledScheduleTriggers) { + assertScheduleCompatibleVariables(nextVariables); + } + const [updated] = await db.update(routines).set({ + projectId: nextProjectId, + goalId: patch.goalId === void 0 ? existing.goalId : patch.goalId, + parentIssueId: patch.parentIssueId === void 0 ? existing.parentIssueId : patch.parentIssueId, + title: nextTitle, + description: nextDescription, + assigneeAgentId: nextAssigneeAgentId, + priority: patch.priority ?? existing.priority, + status: nextStatus, + concurrencyPolicy: patch.concurrencyPolicy ?? existing.concurrencyPolicy, + catchUpPolicy: patch.catchUpPolicy ?? existing.catchUpPolicy, + variables: nextVariables, + updatedByAgentId: actor.agentId ?? null, + updatedByUserId: actor.userId ?? null, + updatedAt: /* @__PURE__ */ new Date() + }).where(eq(routines.id, id)).returning(); + return updated ?? null; + }, + createTrigger: async (routineId, input, actor) => { + const routine = await getRoutineById(routineId); + if (!routine) throw notFound("Routine not found"); + let secretMaterial = null; + let secretId = null; + let publicId = null; + let nextRunAt = null; + if (input.kind === "schedule") { + assertScheduleCompatibleVariables(routine.variables ?? []); + const timeZone = input.timezone || "UTC"; + assertTimeZone(timeZone); + const error50 = validateCron(input.cronExpression); + if (error50) throw unprocessable(error50); + nextRunAt = nextCronTickInTimeZone(input.cronExpression, timeZone, /* @__PURE__ */ new Date()); + } + if (input.kind === "webhook") { + publicId = crypto4.randomBytes(12).toString("hex"); + const created = await createWebhookSecret(routine.companyId, routine.id, actor); + secretId = created.secret.id; + secretMaterial = { + webhookUrl: `${process.env.TASKCORE_API_URL}/api/routine-triggers/public/${publicId}/fire`, + webhookSecret: created.secretValue + }; + } + const [trigger] = await db.insert(routineTriggers).values({ + companyId: routine.companyId, + routineId: routine.id, + kind: input.kind, + label: input.label ?? null, + enabled: input.enabled ?? true, + cronExpression: input.kind === "schedule" ? input.cronExpression : null, + timezone: input.kind === "schedule" ? input.timezone || "UTC" : null, + nextRunAt, + publicId, + secretId, + signingMode: input.kind === "webhook" ? input.signingMode : null, + replayWindowSec: input.kind === "webhook" ? input.replayWindowSec : null, + lastRotatedAt: input.kind === "webhook" ? /* @__PURE__ */ new Date() : null, + createdByAgentId: actor.agentId ?? null, + createdByUserId: actor.userId ?? null, + updatedByAgentId: actor.agentId ?? null, + updatedByUserId: actor.userId ?? null + }).returning(); + return { + trigger, + secretMaterial + }; + }, + updateTrigger: async (id, patch, actor) => { + const existing = await getTriggerById(id); + if (!existing) return null; + let nextRunAt = existing.nextRunAt; + let cronExpression = existing.cronExpression; + let timezone = existing.timezone; + if (existing.kind === "schedule") { + const routine = await getRoutineById(existing.routineId); + if (!routine) throw notFound("Routine not found"); + if (patch.cronExpression !== void 0) { + if (patch.cronExpression == null) throw unprocessable("Scheduled triggers require cronExpression"); + const error50 = validateCron(patch.cronExpression); + if (error50) throw unprocessable(error50); + cronExpression = patch.cronExpression; + } + if (patch.timezone !== void 0) { + if (patch.timezone == null) throw unprocessable("Scheduled triggers require timezone"); + assertTimeZone(patch.timezone); + timezone = patch.timezone; + } + if (cronExpression && timezone) { + nextRunAt = nextCronTickInTimeZone(cronExpression, timezone, /* @__PURE__ */ new Date()); + } + if ((patch.enabled ?? existing.enabled) === true) { + assertScheduleCompatibleVariables(routine.variables ?? []); + } + } + const [updated] = await db.update(routineTriggers).set({ + label: patch.label === void 0 ? existing.label : patch.label, + enabled: patch.enabled ?? existing.enabled, + cronExpression, + timezone, + nextRunAt, + signingMode: patch.signingMode === void 0 ? existing.signingMode : patch.signingMode, + replayWindowSec: patch.replayWindowSec === void 0 ? existing.replayWindowSec : patch.replayWindowSec, + updatedByAgentId: actor.agentId ?? null, + updatedByUserId: actor.userId ?? null, + updatedAt: /* @__PURE__ */ new Date() + }).where(eq(routineTriggers.id, id)).returning(); + return updated ?? null; + }, + deleteTrigger: async (id) => { + const existing = await getTriggerById(id); + if (!existing) return false; + await db.delete(routineTriggers).where(eq(routineTriggers.id, id)); + return true; + }, + rotateTriggerSecret: async (id, actor) => { + const existing = await getTriggerById(id); + if (!existing) throw notFound("Routine trigger not found"); + if (existing.kind !== "webhook" || !existing.publicId || !existing.secretId) { + throw unprocessable("Only webhook triggers can rotate secrets"); + } + const secretValue = crypto4.randomBytes(24).toString("hex"); + await secretsSvc.rotate(existing.secretId, { value: secretValue }, actor); + const [updated] = await db.update(routineTriggers).set({ + lastRotatedAt: /* @__PURE__ */ new Date(), + updatedByAgentId: actor.agentId ?? null, + updatedByUserId: actor.userId ?? null, + updatedAt: /* @__PURE__ */ new Date() + }).where(eq(routineTriggers.id, id)).returning(); + return { + trigger: updated, + secretMaterial: { + webhookUrl: `${process.env.TASKCORE_API_URL}/api/routine-triggers/public/${existing.publicId}/fire`, + webhookSecret: secretValue + } + }; + }, + runRoutine: async (id, input) => { + const routine = await getRoutineById(id); + if (!routine) throw notFound("Routine not found"); + if (routine.status === "archived") throw conflict("Routine is archived"); + await assertProject(routine.companyId, input.projectId ?? null); + await assertAssignableAgent(routine.companyId, input.assigneeAgentId ?? null); + const trigger = input.triggerId ? await getTriggerById(input.triggerId) : null; + if (trigger && trigger.routineId !== routine.id) throw forbidden("Trigger does not belong to routine"); + if (trigger && !trigger.enabled) throw conflict("Routine trigger is not active"); + return dispatchRoutineRun({ + routine, + trigger, + source: input.source, + payload: input.payload, + variables: input.variables, + projectId: input.projectId ?? null, + assigneeAgentId: input.assigneeAgentId ?? null, + idempotencyKey: input.idempotencyKey, + executionWorkspaceId: input.executionWorkspaceId ?? null, + executionWorkspacePreference: input.executionWorkspacePreference ?? null, + executionWorkspaceSettings: input.executionWorkspaceSettings ?? null + }); + }, + firePublicTrigger: async (publicId, input) => { + const trigger = await db.select().from(routineTriggers).where(and(eq(routineTriggers.publicId, publicId), eq(routineTriggers.kind, "webhook"))).then((rows) => rows[0] ?? null); + if (!trigger) throw notFound("Routine trigger not found"); + const routine = await getRoutineById(trigger.routineId); + if (!routine) throw notFound("Routine not found"); + if (!trigger.enabled || routine.status !== "active") throw conflict("Routine trigger is not active"); + if (trigger.signingMode === "none") { + } else if (trigger.signingMode === "github_hmac") { + const secretValue = await resolveTriggerSecret(trigger, routine.companyId); + const rawBody = input.rawBody ?? Buffer.from(JSON.stringify(input.payload ?? {})); + const providedSignature = (input.hubSignatureHeader ?? input.signatureHeader)?.trim() ?? ""; + if (!providedSignature) throw unauthorized(); + const expectedHmac = crypto4.createHmac("sha256", secretValue).update(rawBody).digest("hex"); + const normalizedSignature = providedSignature.replace(/^sha256=/, ""); + const normalizedBuf = Buffer.from(normalizedSignature); + const expectedBuf = Buffer.from(expectedHmac); + const valid = normalizedBuf.length === expectedBuf.length && crypto4.timingSafeEqual(normalizedBuf, expectedBuf); + if (!valid) throw unauthorized(); + } else if (trigger.signingMode === "bearer") { + const secretValue = await resolveTriggerSecret(trigger, routine.companyId); + const expected = `Bearer ${secretValue}`; + const provided = input.authorizationHeader?.trim() ?? ""; + const expectedBuf = Buffer.from(expected); + const providedBuf = Buffer.alloc(expectedBuf.length); + providedBuf.write(provided.slice(0, expectedBuf.length)); + const valid = provided.length === expected.length && crypto4.timingSafeEqual(providedBuf, expectedBuf); + if (!valid) { + throw unauthorized(); + } + } else { + const secretValue = await resolveTriggerSecret(trigger, routine.companyId); + const rawBody = input.rawBody ?? Buffer.from(JSON.stringify(input.payload ?? {})); + const providedSignature = input.signatureHeader?.trim() ?? ""; + const providedTimestamp = input.timestampHeader?.trim() ?? ""; + if (!providedSignature || !providedTimestamp) throw unauthorized(); + const tsMillis = normalizeWebhookTimestampMs(providedTimestamp); + if (tsMillis == null) throw unauthorized(); + const replayWindowSec = trigger.replayWindowSec ?? 300; + if (Math.abs(Date.now() - tsMillis) > replayWindowSec * 1e3) { + throw unauthorized(); + } + const expectedHmac = crypto4.createHmac("sha256", secretValue).update(`${providedTimestamp}.`).update(rawBody).digest("hex"); + const normalizedSignature = providedSignature.replace(/^sha256=/, ""); + const valid = normalizedSignature.length === expectedHmac.length && crypto4.timingSafeEqual(Buffer.from(normalizedSignature), Buffer.from(expectedHmac)); + if (!valid) throw unauthorized(); + } + return dispatchRoutineRun({ + routine, + trigger, + source: "webhook", + payload: input.payload, + variables: isPlainRecord4(input.payload) && isPlainRecord4(input.payload.variables) ? input.payload.variables : null, + idempotencyKey: input.idempotencyKey + }); + }, + listRuns: async (routineId, limit = 50) => { + const cappedLimit = Math.max(1, Math.min(limit, 200)); + const rows = await db.select({ + id: routineRuns.id, + companyId: routineRuns.companyId, + routineId: routineRuns.routineId, + triggerId: routineRuns.triggerId, + source: routineRuns.source, + status: routineRuns.status, + triggeredAt: routineRuns.triggeredAt, + idempotencyKey: routineRuns.idempotencyKey, + triggerPayload: routineRuns.triggerPayload, + linkedIssueId: routineRuns.linkedIssueId, + coalescedIntoRunId: routineRuns.coalescedIntoRunId, + failureReason: routineRuns.failureReason, + completedAt: routineRuns.completedAt, + createdAt: routineRuns.createdAt, + updatedAt: routineRuns.updatedAt, + triggerKind: routineTriggers.kind, + triggerLabel: routineTriggers.label, + issueIdentifier: issues.identifier, + issueTitle: issues.title, + issueStatus: issues.status, + issuePriority: issues.priority, + issueUpdatedAt: issues.updatedAt + }).from(routineRuns).leftJoin(routineTriggers, eq(routineRuns.triggerId, routineTriggers.id)).leftJoin(issues, eq(routineRuns.linkedIssueId, issues.id)).where(eq(routineRuns.routineId, routineId)).orderBy(desc(routineRuns.createdAt)).limit(cappedLimit); + return rows.map((row) => ({ + id: row.id, + companyId: row.companyId, + routineId: row.routineId, + triggerId: row.triggerId, + source: row.source, + status: row.status, + triggeredAt: row.triggeredAt, + idempotencyKey: row.idempotencyKey, + triggerPayload: row.triggerPayload, + linkedIssueId: row.linkedIssueId, + coalescedIntoRunId: row.coalescedIntoRunId, + failureReason: row.failureReason, + completedAt: row.completedAt, + createdAt: row.createdAt, + updatedAt: row.updatedAt, + linkedIssue: row.linkedIssueId ? { + id: row.linkedIssueId, + identifier: row.issueIdentifier, + title: row.issueTitle ?? "Routine execution", + status: row.issueStatus ?? "todo", + priority: row.issuePriority ?? "medium", + updatedAt: row.issueUpdatedAt ?? row.updatedAt + } : null, + trigger: row.triggerId ? { + id: row.triggerId, + kind: row.triggerKind, + label: row.triggerLabel + } : null + })); + }, + tickScheduledTriggers: async (now2 = /* @__PURE__ */ new Date()) => { + const due = await db.select({ + trigger: routineTriggers, + routine: routines + }).from(routineTriggers).innerJoin(routines, eq(routineTriggers.routineId, routines.id)).where( + and( + eq(routineTriggers.kind, "schedule"), + eq(routineTriggers.enabled, true), + eq(routines.status, "active"), + isNotNull(routineTriggers.nextRunAt), + lte(routineTriggers.nextRunAt, now2) + ) + ).orderBy(asc(routineTriggers.nextRunAt), asc(routineTriggers.createdAt)); + let triggered = 0; + for (const row of due) { + if (!row.trigger.nextRunAt || !row.trigger.cronExpression || !row.trigger.timezone) continue; + let runCount = 1; + let claimedNextRunAt = nextCronTickInTimeZone(row.trigger.cronExpression, row.trigger.timezone, now2); + if (row.routine.catchUpPolicy === "enqueue_missed_with_cap") { + let cursor2 = row.trigger.nextRunAt; + runCount = 0; + while (cursor2 && cursor2 <= now2 && runCount < MAX_CATCH_UP_RUNS) { + runCount += 1; + claimedNextRunAt = nextCronTickInTimeZone(row.trigger.cronExpression, row.trigger.timezone, cursor2); + cursor2 = claimedNextRunAt; + } + } + const claimed = await db.update(routineTriggers).set({ + nextRunAt: claimedNextRunAt, + updatedAt: /* @__PURE__ */ new Date() + }).where( + and( + eq(routineTriggers.id, row.trigger.id), + eq(routineTriggers.enabled, true), + eq(routineTriggers.nextRunAt, row.trigger.nextRunAt) + ) + ).returning({ id: routineTriggers.id }).then((rows) => rows[0] ?? null); + if (!claimed) continue; + for (let i5 = 0; i5 < runCount; i5 += 1) { + await dispatchRoutineRun({ + routine: row.routine, + trigger: row.trigger, + source: "schedule" + }); + triggered += 1; + } + } + return { triggered }; + }, + syncRunStatusForIssue: async (issueId) => { + const issue2 = await db.select({ + id: issues.id, + status: issues.status, + originKind: issues.originKind, + originRunId: issues.originRunId + }).from(issues).where(eq(issues.id, issueId)).then((rows) => rows[0] ?? null); + if (!issue2 || issue2.originKind !== "routine_execution" || !issue2.originRunId) return null; + if (issue2.status === "done") { + return finalizeRun(issue2.originRunId, { + status: "completed", + completedAt: /* @__PURE__ */ new Date() + }); + } + if (issue2.status === "blocked" || issue2.status === "cancelled") { + return finalizeRun(issue2.originRunId, { + status: "failed", + failureReason: `Execution issue moved to ${issue2.status}`, + completedAt: /* @__PURE__ */ new Date() + }); + } + return null; + } + }; +} + +// server/src/services/finance.ts +init_drizzle_orm(); +init_src2(); +async function assertBelongsToCompany(db, table, id, companyId, label) { + const row = await db.select().from(table).where(eq(table.id, id)).then((rows) => rows[0] ?? null); + if (!row) throw notFound(`${label} not found`); + if (row.companyId !== companyId) { + throw unprocessable(`${label} does not belong to company`); + } +} +function rangeConditions(companyId, range2) { + const conditions = [eq(financeEvents.companyId, companyId)]; + if (range2?.from) conditions.push(gte(financeEvents.occurredAt, range2.from)); + if (range2?.to) conditions.push(lte(financeEvents.occurredAt, range2.to)); + return conditions; +} +function financeService(db) { + const debitExpr = sql`coalesce(sum(case when ${financeEvents.direction} = 'debit' then ${financeEvents.amountCents} else 0 end), 0)::int`; + const creditExpr = sql`coalesce(sum(case when ${financeEvents.direction} = 'credit' then ${financeEvents.amountCents} else 0 end), 0)::int`; + const estimatedDebitExpr = sql`coalesce(sum(case when ${financeEvents.direction} = 'debit' and ${financeEvents.estimated} = true then ${financeEvents.amountCents} else 0 end), 0)::int`; + return { + createEvent: async (companyId, data2) => { + if (data2.agentId) await assertBelongsToCompany(db, agents, data2.agentId, companyId, "Agent"); + if (data2.issueId) await assertBelongsToCompany(db, issues, data2.issueId, companyId, "Issue"); + if (data2.projectId) await assertBelongsToCompany(db, projects, data2.projectId, companyId, "Project"); + if (data2.goalId) await assertBelongsToCompany(db, goals, data2.goalId, companyId, "Goal"); + if (data2.heartbeatRunId) await assertBelongsToCompany(db, heartbeatRuns, data2.heartbeatRunId, companyId, "Heartbeat run"); + if (data2.costEventId) await assertBelongsToCompany(db, costEvents, data2.costEventId, companyId, "Cost event"); + const event = await db.insert(financeEvents).values({ + ...data2, + companyId, + currency: data2.currency ?? "USD", + direction: data2.direction ?? "debit", + estimated: data2.estimated ?? false + }).returning().then((rows) => rows[0]); + return event; + }, + summary: async (companyId, range2) => { + const conditions = rangeConditions(companyId, range2); + const [row] = await db.select({ + debitCents: debitExpr, + creditCents: creditExpr, + estimatedDebitCents: estimatedDebitExpr, + eventCount: sql`count(*)::int` + }).from(financeEvents).where(and(...conditions)); + return { + companyId, + debitCents: Number(row?.debitCents ?? 0), + creditCents: Number(row?.creditCents ?? 0), + netCents: Number(row?.debitCents ?? 0) - Number(row?.creditCents ?? 0), + estimatedDebitCents: Number(row?.estimatedDebitCents ?? 0), + eventCount: Number(row?.eventCount ?? 0) + }; + }, + byBiller: async (companyId, range2) => { + const conditions = rangeConditions(companyId, range2); + return db.select({ + biller: financeEvents.biller, + debitCents: debitExpr, + creditCents: creditExpr, + estimatedDebitCents: estimatedDebitExpr, + eventCount: sql`count(*)::int`, + kindCount: sql`count(distinct ${financeEvents.eventKind})::int`, + netCents: sql`(${debitExpr} - ${creditExpr})::int` + }).from(financeEvents).where(and(...conditions)).groupBy(financeEvents.biller).orderBy(desc(sql`(${debitExpr} - ${creditExpr})::int`), financeEvents.biller); + }, + byKind: async (companyId, range2) => { + const conditions = rangeConditions(companyId, range2); + return db.select({ + eventKind: financeEvents.eventKind, + debitCents: debitExpr, + creditCents: creditExpr, + estimatedDebitCents: estimatedDebitExpr, + eventCount: sql`count(*)::int`, + billerCount: sql`count(distinct ${financeEvents.biller})::int`, + netCents: sql`(${debitExpr} - ${creditExpr})::int` + }).from(financeEvents).where(and(...conditions)).groupBy(financeEvents.eventKind).orderBy(desc(sql`(${debitExpr} - ${creditExpr})::int`), financeEvents.eventKind); + }, + list: async (companyId, range2, limit = 100) => { + const conditions = rangeConditions(companyId, range2); + return db.select().from(financeEvents).where(and(...conditions)).orderBy(desc(financeEvents.occurredAt), desc(financeEvents.createdAt)).limit(limit); + } + }; +} + +// server/src/services/dashboard.ts +init_drizzle_orm(); +init_src2(); +function dashboardService(db) { + const budgets = budgetService(db); + return { + summary: async (companyId) => { + const company = await db.select().from(companies).where(eq(companies.id, companyId)).then((rows) => rows[0] ?? null); + if (!company) throw notFound("Company not found"); + const agentRows = await db.select({ status: agents.status, count: sql`count(*)` }).from(agents).where(eq(agents.companyId, companyId)).groupBy(agents.status); + const taskRows = await db.select({ status: issues.status, count: sql`count(*)` }).from(issues).where(eq(issues.companyId, companyId)).groupBy(issues.status); + const pendingApprovals = await db.select({ count: sql`count(*)` }).from(approvals).where(and(eq(approvals.companyId, companyId), eq(approvals.status, "pending"))).then((rows) => Number(rows[0]?.count ?? 0)); + const agentCounts = { + active: 0, + running: 0, + paused: 0, + error: 0 + }; + for (const row of agentRows) { + const count2 = Number(row.count); + const bucket = row.status === "idle" ? "active" : row.status; + agentCounts[bucket] = (agentCounts[bucket] ?? 0) + count2; + } + const taskCounts = { + open: 0, + inProgress: 0, + blocked: 0, + done: 0 + }; + for (const row of taskRows) { + const count2 = Number(row.count); + if (row.status === "in_progress") taskCounts.inProgress += count2; + if (row.status === "blocked") taskCounts.blocked += count2; + if (row.status === "done") taskCounts.done += count2; + if (row.status !== "done" && row.status !== "cancelled") taskCounts.open += count2; + } + const now2 = /* @__PURE__ */ new Date(); + const monthStart = new Date(now2.getFullYear(), now2.getMonth(), 1); + const [{ monthSpend }] = await db.select({ + monthSpend: sql`coalesce(sum(${costEvents.costCents}), 0)::int` + }).from(costEvents).where( + and( + eq(costEvents.companyId, companyId), + gte(costEvents.occurredAt, monthStart) + ) + ); + const monthSpendCents = Number(monthSpend); + const utilization = company.budgetMonthlyCents > 0 ? monthSpendCents / company.budgetMonthlyCents * 100 : 0; + const budgetOverview = await budgets.overview(companyId); + return { + companyId, + agents: { + active: agentCounts.active, + running: agentCounts.running, + paused: agentCounts.paused, + error: agentCounts.error + }, + tasks: taskCounts, + costs: { + monthSpendCents, + monthBudgetCents: company.budgetMonthlyCents, + monthUtilizationPercent: Number(utilization.toFixed(2)) + }, + pendingApprovals, + budgets: { + activeIncidents: budgetOverview.activeIncidents.length, + pendingApprovals: budgetOverview.pendingApprovalCount, + pausedAgents: budgetOverview.pausedAgentCount, + pausedProjects: budgetOverview.pausedProjectCount + } + }; + } + }; +} + +// server/src/services/sidebar-badges.ts +init_drizzle_orm(); +init_src2(); +var ACTIONABLE_APPROVAL_STATUSES = ["pending", "revision_requested"]; +var FAILED_HEARTBEAT_STATUSES = ["failed", "timed_out"]; +function normalizeTimestamp2(value) { + if (!value) return 0; + const timestamp2 = new Date(value).getTime(); + return Number.isFinite(timestamp2) ? timestamp2 : 0; +} +function isDismissed(dismissedAtByKey, itemKey, activityAt) { + const dismissedAt = dismissedAtByKey.get(itemKey); + if (dismissedAt == null) return false; + return dismissedAt >= normalizeTimestamp2(activityAt); +} +function sidebarBadgeService(db) { + return { + get: async (companyId, extra) => { + const actionableApprovals = await db.select({ id: approvals.id, updatedAt: approvals.updatedAt }).from(approvals).where( + and( + eq(approvals.companyId, companyId), + inArray(approvals.status, ACTIONABLE_APPROVAL_STATUSES) + ) + ).then( + (rows) => rows.filter((row) => !isDismissed(extra?.dismissals ?? /* @__PURE__ */ new Map(), `approval:${row.id}`, row.updatedAt)).length + ); + const latestRunByAgent = await db.selectDistinctOn([heartbeatRuns.agentId], { + id: heartbeatRuns.id, + runStatus: heartbeatRuns.status, + createdAt: heartbeatRuns.createdAt + }).from(heartbeatRuns).innerJoin(agents, eq(heartbeatRuns.agentId, agents.id)).where( + and( + eq(heartbeatRuns.companyId, companyId), + eq(agents.companyId, companyId), + not(eq(agents.status, "terminated")) + ) + ).orderBy(heartbeatRuns.agentId, desc(heartbeatRuns.createdAt)); + const failedRuns = latestRunByAgent.filter( + (row) => FAILED_HEARTBEAT_STATUSES.includes(row.runStatus) && !isDismissed(extra?.dismissals ?? /* @__PURE__ */ new Map(), `run:${row.id}`, row.createdAt) + ).length; + const joinRequests2 = (extra?.joinRequests ?? []).filter( + (row) => !isDismissed( + extra?.dismissals ?? /* @__PURE__ */ new Map(), + `join:${row.id}`, + row.updatedAt ?? row.createdAt + ) + ).length; + const unreadTouchedIssues = extra?.unreadTouchedIssues ?? 0; + return { + inbox: actionableApprovals + failedRuns + joinRequests2 + unreadTouchedIssues, + approvals: actionableApprovals, + failedRuns, + joinRequests: joinRequests2 + }; + } + }; +} + +// server/src/services/sidebar-preferences.ts +init_drizzle_orm(); +init_src2(); +function normalizeOrderedIds(value) { + if (!Array.isArray(value)) return []; + const orderedIds = []; + const seen = /* @__PURE__ */ new Set(); + for (const item of value) { + if (typeof item !== "string") continue; + const trimmed = item.trim(); + if (!trimmed || seen.has(trimmed)) continue; + seen.add(trimmed); + orderedIds.push(trimmed); + } + return orderedIds; +} +function toPreference(orderedIds, updatedAt) { + return { + orderedIds: normalizeOrderedIds(orderedIds), + updatedAt + }; +} +function sidebarPreferenceService(db) { + return { + async getCompanyOrder(userId) { + const row = await db.query.userSidebarPreferences.findFirst({ + where: eq(userSidebarPreferences.userId, userId) + }); + return toPreference(row?.companyOrder ?? [], row?.updatedAt ?? null); + }, + async upsertCompanyOrder(userId, orderedIds) { + const now2 = /* @__PURE__ */ new Date(); + const normalized = normalizeOrderedIds(orderedIds); + const [row] = await db.insert(userSidebarPreferences).values({ + userId, + companyOrder: normalized, + updatedAt: now2 + }).onConflictDoUpdate({ + target: [userSidebarPreferences.userId], + set: { + companyOrder: normalized, + updatedAt: now2 + } + }).returning(); + return toPreference(row?.companyOrder ?? normalized, row?.updatedAt ?? now2); + }, + async getProjectOrder(companyId, userId) { + const row = await db.query.companyUserSidebarPreferences.findFirst({ + where: and( + eq(companyUserSidebarPreferences.companyId, companyId), + eq(companyUserSidebarPreferences.userId, userId) + ) + }); + return toPreference(row?.projectOrder ?? [], row?.updatedAt ?? null); + }, + async upsertProjectOrder(companyId, userId, orderedIds) { + const now2 = /* @__PURE__ */ new Date(); + const normalized = normalizeOrderedIds(orderedIds); + const [row] = await db.insert(companyUserSidebarPreferences).values({ + companyId, + userId, + projectOrder: normalized, + updatedAt: now2 + }).onConflictDoUpdate({ + target: [companyUserSidebarPreferences.companyId, companyUserSidebarPreferences.userId], + set: { + projectOrder: normalized, + updatedAt: now2 + } + }).returning(); + return toPreference(row?.projectOrder ?? normalized, row?.updatedAt ?? now2); + } + }; +} + +// server/src/services/inbox-dismissals.ts +init_drizzle_orm(); +init_src2(); +function inboxDismissalService(db) { + return { + list: async (companyId, userId) => db.select().from(inboxDismissals).where(and(eq(inboxDismissals.companyId, companyId), eq(inboxDismissals.userId, userId))).orderBy(desc(inboxDismissals.updatedAt)), + dismiss: async (companyId, userId, itemKey, dismissedAt = /* @__PURE__ */ new Date()) => { + const now2 = /* @__PURE__ */ new Date(); + const [row] = await db.insert(inboxDismissals).values({ + companyId, + userId, + itemKey, + dismissedAt, + updatedAt: now2 + }).onConflictDoUpdate({ + target: [inboxDismissals.companyId, inboxDismissals.userId, inboxDismissals.itemKey], + set: { + dismissedAt, + updatedAt: now2 + } + }).returning(); + return row; + } + }; +} + +// server/src/services/access.ts +init_drizzle_orm(); +init_src2(); +function accessService(db) { + async function isInstanceAdmin(userId) { + if (!userId) return false; + const row = await db.select({ id: instanceUserRoles.id }).from(instanceUserRoles).where(and(eq(instanceUserRoles.userId, userId), eq(instanceUserRoles.role, "instance_admin"))).then((rows) => rows[0] ?? null); + return Boolean(row); + } + async function getMembership(companyId, principalType, principalId) { + return db.select().from(companyMemberships).where( + and( + eq(companyMemberships.companyId, companyId), + eq(companyMemberships.principalType, principalType), + eq(companyMemberships.principalId, principalId) + ) + ).then((rows) => rows[0] ?? null); + } + async function hasPermission(companyId, principalType, principalId, permissionKey) { + const membership = await getMembership(companyId, principalType, principalId); + if (!membership || membership.status !== "active") return false; + const grant = await db.select({ id: principalPermissionGrants.id }).from(principalPermissionGrants).where( + and( + eq(principalPermissionGrants.companyId, companyId), + eq(principalPermissionGrants.principalType, principalType), + eq(principalPermissionGrants.principalId, principalId), + eq(principalPermissionGrants.permissionKey, permissionKey) + ) + ).then((rows) => rows[0] ?? null); + return Boolean(grant); + } + async function canUser(companyId, userId, permissionKey) { + if (!userId) return false; + if (await isInstanceAdmin(userId)) return true; + return hasPermission(companyId, "user", userId, permissionKey); + } + async function listMembers(companyId) { + return db.select().from(companyMemberships).where(eq(companyMemberships.companyId, companyId)).orderBy(sql`${companyMemberships.createdAt} desc`); + } + async function listActiveUserMemberships(companyId) { + return db.select().from(companyMemberships).where( + and( + eq(companyMemberships.companyId, companyId), + eq(companyMemberships.principalType, "user"), + eq(companyMemberships.status, "active") + ) + ).orderBy(sql`${companyMemberships.createdAt} asc`); + } + async function setMemberPermissions(companyId, memberId, grants, grantedByUserId) { + const member2 = await db.select().from(companyMemberships).where(and(eq(companyMemberships.companyId, companyId), eq(companyMemberships.id, memberId))).then((rows) => rows[0] ?? null); + if (!member2) return null; + await db.transaction(async (tx) => { + await tx.delete(principalPermissionGrants).where( + and( + eq(principalPermissionGrants.companyId, companyId), + eq(principalPermissionGrants.principalType, member2.principalType), + eq(principalPermissionGrants.principalId, member2.principalId) + ) + ); + if (grants.length > 0) { + await tx.insert(principalPermissionGrants).values( + grants.map((grant) => ({ + companyId, + principalType: member2.principalType, + principalId: member2.principalId, + permissionKey: grant.permissionKey, + scope: grant.scope ?? null, + grantedByUserId, + createdAt: /* @__PURE__ */ new Date(), + updatedAt: /* @__PURE__ */ new Date() + })) + ); + } + }); + return member2; + } + async function promoteInstanceAdmin(userId) { + const existing = await db.select().from(instanceUserRoles).where(and(eq(instanceUserRoles.userId, userId), eq(instanceUserRoles.role, "instance_admin"))).then((rows) => rows[0] ?? null); + if (existing) return existing; + return db.insert(instanceUserRoles).values({ + userId, + role: "instance_admin" + }).returning().then((rows) => rows[0]); + } + async function demoteInstanceAdmin(userId) { + return db.delete(instanceUserRoles).where(and(eq(instanceUserRoles.userId, userId), eq(instanceUserRoles.role, "instance_admin"))).returning().then((rows) => rows[0] ?? null); + } + async function listUserCompanyAccess(userId) { + return db.select().from(companyMemberships).where(and(eq(companyMemberships.principalType, "user"), eq(companyMemberships.principalId, userId))).orderBy(sql`${companyMemberships.createdAt} desc`); + } + async function setUserCompanyAccess(userId, companyIds) { + const existing = await listUserCompanyAccess(userId); + const existingByCompany = new Map(existing.map((row) => [row.companyId, row])); + const target = new Set(companyIds); + await db.transaction(async (tx) => { + const toDelete = existing.filter((row) => !target.has(row.companyId)).map((row) => row.id); + if (toDelete.length > 0) { + await tx.delete(companyMemberships).where(inArray(companyMemberships.id, toDelete)); + } + for (const companyId of target) { + if (existingByCompany.has(companyId)) continue; + await tx.insert(companyMemberships).values({ + companyId, + principalType: "user", + principalId: userId, + status: "active", + membershipRole: "member" + }); + } + }); + return listUserCompanyAccess(userId); + } + async function ensureMembership(companyId, principalType, principalId, membershipRole = "member", status = "active") { + const existing = await getMembership(companyId, principalType, principalId); + if (existing) { + if (existing.status !== status || existing.membershipRole !== membershipRole) { + const updated = await db.update(companyMemberships).set({ status, membershipRole, updatedAt: /* @__PURE__ */ new Date() }).where(eq(companyMemberships.id, existing.id)).returning().then((rows) => rows[0] ?? null); + return updated ?? existing; + } + return existing; + } + return db.insert(companyMemberships).values({ + companyId, + principalType, + principalId, + status, + membershipRole + }).returning().then((rows) => rows[0]); + } + async function setPrincipalGrants(companyId, principalType, principalId, grants, grantedByUserId) { + await db.transaction(async (tx) => { + await tx.delete(principalPermissionGrants).where( + and( + eq(principalPermissionGrants.companyId, companyId), + eq(principalPermissionGrants.principalType, principalType), + eq(principalPermissionGrants.principalId, principalId) + ) + ); + if (grants.length === 0) return; + await tx.insert(principalPermissionGrants).values( + grants.map((grant) => ({ + companyId, + principalType, + principalId, + permissionKey: grant.permissionKey, + scope: grant.scope ?? null, + grantedByUserId, + createdAt: /* @__PURE__ */ new Date(), + updatedAt: /* @__PURE__ */ new Date() + })) + ); + }); + } + async function copyActiveUserMemberships(sourceCompanyId, targetCompanyId) { + const sourceMemberships = await listActiveUserMemberships(sourceCompanyId); + for (const membership of sourceMemberships) { + await ensureMembership( + targetCompanyId, + "user", + membership.principalId, + membership.membershipRole, + "active" + ); + } + return sourceMemberships; + } + async function listPrincipalGrants(companyId, principalType, principalId) { + return db.select().from(principalPermissionGrants).where( + and( + eq(principalPermissionGrants.companyId, companyId), + eq(principalPermissionGrants.principalType, principalType), + eq(principalPermissionGrants.principalId, principalId) + ) + ).orderBy(principalPermissionGrants.permissionKey); + } + async function setPrincipalPermission(companyId, principalType, principalId, permissionKey, enabled, grantedByUserId, scope = null) { + if (!enabled) { + await db.delete(principalPermissionGrants).where( + and( + eq(principalPermissionGrants.companyId, companyId), + eq(principalPermissionGrants.principalType, principalType), + eq(principalPermissionGrants.principalId, principalId), + eq(principalPermissionGrants.permissionKey, permissionKey) + ) + ); + return; + } + await ensureMembership(companyId, principalType, principalId, "member", "active"); + const existing = await db.select().from(principalPermissionGrants).where( + and( + eq(principalPermissionGrants.companyId, companyId), + eq(principalPermissionGrants.principalType, principalType), + eq(principalPermissionGrants.principalId, principalId), + eq(principalPermissionGrants.permissionKey, permissionKey) + ) + ).then((rows) => rows[0] ?? null); + if (existing) { + await db.update(principalPermissionGrants).set({ + scope, + grantedByUserId, + updatedAt: /* @__PURE__ */ new Date() + }).where(eq(principalPermissionGrants.id, existing.id)); + return; + } + await db.insert(principalPermissionGrants).values({ + companyId, + principalType, + principalId, + permissionKey, + scope, + grantedByUserId, + createdAt: /* @__PURE__ */ new Date(), + updatedAt: /* @__PURE__ */ new Date() + }); + } + return { + isInstanceAdmin, + canUser, + hasPermission, + getMembership, + ensureMembership, + listMembers, + listActiveUserMemberships, + copyActiveUserMemberships, + setMemberPermissions, + promoteInstanceAdmin, + demoteInstanceAdmin, + listUserCompanyAccess, + setUserCompanyAccess, + setPrincipalGrants, + listPrincipalGrants, + setPrincipalPermission + }; +} + +// server/src/services/company-portability.ts +import { createHash as createHash14 } from "node:crypto"; +import { execFile as execFile6 } from "node:child_process"; +import path40 from "node:path"; +import { promisify as promisify6 } from "node:util"; + +// server/src/services/company-export-readme.ts +var ROLE_LABELS = { + ceo: "CEO", + cto: "CTO", + cmo: "CMO", + cfo: "CFO", + coo: "COO", + vp: "VP", + manager: "Manager", + engineer: "Engineer", + agent: "Agent" +}; +function skillSourceLabel(skill) { + if (skill.sourceLocator) { + if (skill.sourceType === "github" || skill.sourceType === "skills_sh" || skill.sourceType === "url") { + return `[${skill.sourceType}](${skill.sourceLocator})`; + } + return skill.sourceLocator; + } + if (skill.sourceType === "local") return "local"; + return skill.sourceType ?? "\u2014"; +} +function generateReadme(manifest, options) { + const lines = []; + lines.push(`# ${options.companyName}`); + lines.push(""); + if (options.companyDescription) { + lines.push(`> ${options.companyDescription}`); + lines.push(""); + } + if (manifest.agents.length > 0) { + lines.push("![Org Chart](images/org-chart.png)"); + lines.push(""); + } + lines.push("## What's Inside"); + lines.push(""); + lines.push("> This is an [Agent Company](https://agentcompanies.io) package from [Taskcore](https://taskcore.khulnasoft.com)"); + lines.push(""); + const counts = []; + if (manifest.agents.length > 0) counts.push(["Agents", manifest.agents.length]); + if (manifest.projects.length > 0) counts.push(["Projects", manifest.projects.length]); + if (manifest.skills.length > 0) counts.push(["Skills", manifest.skills.length]); + if (manifest.issues.length > 0) counts.push(["Tasks", manifest.issues.length]); + if (counts.length > 0) { + lines.push("| Content | Count |"); + lines.push("|---------|-------|"); + for (const [label, count2] of counts) { + lines.push(`| ${label} | ${count2} |`); + } + lines.push(""); + } + if (manifest.agents.length > 0) { + lines.push("### Agents"); + lines.push(""); + lines.push("| Agent | Role | Reports To |"); + lines.push("|-------|------|------------|"); + for (const agent of manifest.agents) { + const roleLabel = ROLE_LABELS[agent.role] ?? agent.role; + const reportsTo = agent.reportsToSlug ?? "\u2014"; + lines.push(`| ${agent.name} | ${roleLabel} | ${reportsTo} |`); + } + lines.push(""); + } + if (manifest.projects.length > 0) { + lines.push("### Projects"); + lines.push(""); + for (const project of manifest.projects) { + const desc3 = project.description ? ` \u2014 ${project.description}` : ""; + lines.push(`- **${project.name}**${desc3}`); + } + lines.push(""); + } + if (manifest.skills.length > 0) { + lines.push("### Skills"); + lines.push(""); + lines.push("| Skill | Description | Source |"); + lines.push("|-------|-------------|--------|"); + for (const skill of manifest.skills) { + const desc3 = skill.description ?? "\u2014"; + const source = skillSourceLabel(skill); + lines.push(`| ${skill.name} | ${desc3} | ${source} |`); + } + lines.push(""); + } + lines.push("## Getting Started"); + lines.push(""); + lines.push("```bash"); + lines.push("pnpm taskcore company import this-github-url-or-folder"); + lines.push("```"); + lines.push(""); + lines.push("See [Taskcore](https://taskcore.khulnasoft.com) for more information."); + lines.push(""); + lines.push("---"); + lines.push(`Exported from [Taskcore](https://taskcore.khulnasoft.com) on ${(/* @__PURE__ */ new Date()).toISOString().split("T")[0]}`); + lines.push(""); + return lines.join("\n"); +} + +// server/src/routes/org-chart-svg.ts +var ORG_CHART_STYLES = ["monochrome", "nebula", "circuit", "warmth", "schematic"]; +var ROLE_ICONS = { + ceo: { + bg: "#fef3c7", + roleLabel: "Chief Executive", + accentColor: "#f0883e", + iconColor: "#92400e", + iconPath: "M8 1l2.2 4.5L15 6.2l-3.5 3.4.8 4.9L8 12.2 3.7 14.5l.8-4.9L1 6.2l4.8-.7z", + // 👑 Crown + emojiSvg: `` + }, + cto: { + bg: "#dbeafe", + roleLabel: "Technology", + accentColor: "#58a6ff", + iconColor: "#1e40af", + iconPath: "M2 3l5 5-5 5M9 13h5", + // 💻 Laptop + emojiSvg: `` + }, + cmo: { + bg: "#dcfce7", + roleLabel: "Marketing", + accentColor: "#3fb950", + iconColor: "#166534", + iconPath: "M8 1a7 7 0 1 0 0 14A7 7 0 0 0 8 1zM1 8h14M8 1c-2 2-3 4.5-3 7s1 5 3 7c2-2 3-4.5 3-7s-1-5-3-7z", + // 🌐 Globe with meridians + emojiSvg: `` + }, + cfo: { + bg: "#fef3c7", + roleLabel: "Finance", + accentColor: "#f0883e", + iconColor: "#92400e", + iconPath: "M8 1v14M5 4.5C5 3.1 6.3 2 8 2s3 1.1 3 2.5S9.7 7 8 7 5 8.1 5 9.5 6.3 12 8 12s3-1.1 3-2.5", + // 📊 Bar chart + emojiSvg: `` + }, + coo: { + bg: "#e0f2fe", + roleLabel: "Operations", + accentColor: "#58a6ff", + iconColor: "#075985", + iconPath: "M8 5.5a2.5 2.5 0 1 0 0 5 2.5 2.5 0 0 0 0-5z", + // ⚙️ Gear + emojiSvg: `` + }, + engineer: { + bg: "#f3e8ff", + roleLabel: "Engineering", + accentColor: "#bc8cff", + iconColor: "#6b21a8", + iconPath: "M5 3L1 8l4 5M11 3l4 5-4 5", + // ⌨️ Keyboard + emojiSvg: `` + }, + quality: { + bg: "#ffe4e6", + roleLabel: "Quality", + accentColor: "#f778ba", + iconColor: "#9f1239", + iconPath: "M4 8l3 3 5-6M8 1L2 4v4c0 3.5 2.6 6.8 6 8 3.4-1.2 6-4.5 6-8V4z", + // 🔬 Microscope + emojiSvg: `` + }, + design: { + bg: "#fce7f3", + roleLabel: "Design", + accentColor: "#79c0ff", + iconColor: "#9d174d", + iconPath: "M12 2l2 2-9 9H3v-2zM9.5 4.5l2 2", + // 🪄 Magic wand + emojiSvg: `` + }, + finance: { + bg: "#fef3c7", + roleLabel: "Finance", + accentColor: "#f0883e", + iconColor: "#92400e", + iconPath: "M8 1v14M5 4.5C5 3.1 6.3 2 8 2s3 1.1 3 2.5S9.7 7 8 7 5 8.1 5 9.5 6.3 12 8 12s3-1.1 3-2.5", + // 📊 Bar chart (same as CFO) + emojiSvg: `` + }, + operations: { + bg: "#e0f2fe", + roleLabel: "Operations", + accentColor: "#58a6ff", + iconColor: "#075985", + iconPath: "M8 5.5a2.5 2.5 0 1 0 0 5 2.5 2.5 0 0 0 0-5z", + // ⚙️ Gear (same as COO) + emojiSvg: `` + }, + default: { + bg: "#f3e8ff", + roleLabel: "Agent", + accentColor: "#bc8cff", + iconColor: "#6b21a8", + iconPath: "M8 8a3 3 0 1 0 0-6 3 3 0 0 0 0 6zM2 14c0-3.3 2.7-4 6-4s6 .7 6 4", + // 👤 Person silhouette + emojiSvg: `` + } +}; +function guessRoleTag(node) { + const name = node.name.toLowerCase(); + const role = node.role.toLowerCase(); + if (name === "ceo" || role.includes("chief executive")) return "ceo"; + if (name === "cto" || role.includes("chief technology") || role.includes("technology")) return "cto"; + if (name === "cmo" || role.includes("chief marketing") || role.includes("marketing")) return "cmo"; + if (name === "cfo" || role.includes("chief financial")) return "cfo"; + if (name === "coo" || role.includes("chief operating")) return "coo"; + if (role.includes("engineer") || role.includes("eng")) return "engineer"; + if (role.includes("quality") || role.includes("qa")) return "quality"; + if (role.includes("design")) return "design"; + if (role.includes("finance")) return "finance"; + if (role.includes("operations") || role.includes("ops")) return "operations"; + return "default"; +} +function getRoleInfo(node) { + const tag3 = guessRoleTag(node); + return { tag: tag3, ...ROLE_ICONS[tag3] || ROLE_ICONS.default }; +} +var THEMES = { + // 01 — Monochrome (Vercel-inspired, dark minimal) + monochrome: { + bgColor: "#18181b", + cardBg: "#18181b", + cardBorder: "#27272a", + cardRadius: 6, + cardShadow: null, + lineColor: "#3f3f46", + lineWidth: 1.5, + nameColor: "#fafafa", + roleColor: "#71717a", + font: "'Inter', system-ui, sans-serif", + watermarkColor: "rgba(255,255,255,0.25)", + defs: () => "", + bgExtras: () => "", + renderCard: null, + cardAccent: null + }, + // 02 — Nebula (glassmorphism on cosmic gradient) + nebula: { + bgColor: "#0f0c29", + cardBg: "rgba(255,255,255,0.07)", + cardBorder: "rgba(255,255,255,0.12)", + cardRadius: 6, + cardShadow: null, + lineColor: "rgba(255,255,255,0.25)", + lineWidth: 1.5, + nameColor: "#ffffff", + roleColor: "rgba(255,255,255,0.45)", + font: "'Inter', system-ui, sans-serif", + watermarkColor: "rgba(255,255,255,0.2)", + defs: (_w, _h4) => ` + + + + + + + + + + + + + `, + bgExtras: (w5, h5) => ` + + + `, + renderCard: null, + cardAccent: null + }, + // 03 — Circuit (Linear/Raycast — indigo traces, amethyst CEO) + circuit: { + bgColor: "#0c0c0e", + cardBg: "rgba(99,102,241,0.04)", + cardBorder: "rgba(99,102,241,0.18)", + cardRadius: 5, + cardShadow: null, + lineColor: "rgba(99,102,241,0.35)", + lineWidth: 1.5, + nameColor: "#e4e4e7", + roleColor: "#6366f1", + font: "'Inter', system-ui, sans-serif", + watermarkColor: "rgba(99,102,241,0.3)", + defs: () => "", + bgExtras: () => "", + renderCard: (ln, theme) => { + const { tag: tag3, roleLabel, emojiSvg } = getRoleInfo(ln.node); + const cx = ln.x + ln.width / 2; + const isCeo = tag3 === "ceo"; + const borderColor = isCeo ? "rgba(168,85,247,0.35)" : theme.cardBorder; + const bgColor = isCeo ? "rgba(168,85,247,0.06)" : theme.cardBg; + const avatarCY = ln.y + 27; + const nameY = ln.y + 66; + const roleY = ln.y + 82; + return ` + + ${renderEmojiAvatar(cx, avatarCY, 17, "rgba(99,102,241,0.08)", emojiSvg, "rgba(99,102,241,0.15)")} + ${escapeXml(ln.node.name)} + ${escapeXml(roleLabel).toUpperCase()} + `; + }, + cardAccent: null + }, + // 04 — Warmth (Airbnb — light, colored avatars, soft shadows) + warmth: { + bgColor: "#fafaf9", + cardBg: "#ffffff", + cardBorder: "#e7e5e4", + cardRadius: 6, + cardShadow: "rgba(0,0,0,0.05)", + lineColor: "#d6d3d1", + lineWidth: 2, + nameColor: "#1c1917", + roleColor: "#78716c", + font: "'Inter', -apple-system, BlinkMacSystemFont, sans-serif", + watermarkColor: "rgba(0,0,0,0.25)", + defs: () => "", + bgExtras: () => "", + renderCard: null, + cardAccent: null + }, + // 05 — Schematic (Blueprint — grid bg, monospace, colored top-bars) + schematic: { + bgColor: "#0d1117", + cardBg: "rgba(13,17,23,0.92)", + cardBorder: "#30363d", + cardRadius: 4, + cardShadow: null, + lineColor: "#30363d", + lineWidth: 1.5, + nameColor: "#c9d1d9", + roleColor: "#8b949e", + font: "'JetBrains Mono', 'SF Mono', monospace", + watermarkColor: "rgba(139,148,158,0.3)", + defs: (w5, h5) => ` + + + `, + bgExtras: (w5, h5) => ``, + renderCard: (ln, theme) => { + const { tag: tag3, accentColor, emojiSvg } = getRoleInfo(ln.node); + const cx = ln.x + ln.width / 2; + const schemaRoles = { + ceo: "chief_executive", + cto: "chief_technology", + cmo: "chief_marketing", + cfo: "chief_financial", + coo: "chief_operating", + engineer: "engineer", + quality: "quality_assurance", + design: "designer", + finance: "finance", + operations: "operations", + default: "agent" + }; + const roleText = schemaRoles[tag3] || schemaRoles.default; + const avatarCY = ln.y + 27; + const nameY = ln.y + 66; + const roleY = ln.y + 82; + return ` + + + ${renderEmojiAvatar(cx, avatarCY, 17, "rgba(48,54,61,0.3)", emojiSvg, theme.cardBorder)} + ${escapeXml(ln.node.name)} + ${escapeXml(roleText)} + `; + }, + cardAccent: null + } +}; +var CARD_H = 96; +var CARD_MIN_W = 150; +var CARD_PAD_X = 22; +var AVATAR_SIZE = 34; +var GAP_X = 24; +var GAP_Y = 56; +var MINI_AVATAR_SIZE = 14; +var MINI_AVATAR_GAP = 6; +var MINI_AVATAR_PADDING = 10; +var MINI_AVATAR_MAX_COLS = 8; +var PADDING = 48; +var LOGO_PADDING = 16; +function measureText(text3, fontSize) { + return text3.length * fontSize * 0.58; +} +function avatarGridRows(count2) { + return Math.ceil(count2 / MINI_AVATAR_MAX_COLS); +} +function avatarGridWidth(count2) { + const cols = Math.min(count2, MINI_AVATAR_MAX_COLS); + return cols * (MINI_AVATAR_SIZE + MINI_AVATAR_GAP) - MINI_AVATAR_GAP + MINI_AVATAR_PADDING * 2; +} +function avatarGridHeight(count2) { + if (count2 === 0) return 0; + const rows = avatarGridRows(count2); + return rows * (MINI_AVATAR_SIZE + MINI_AVATAR_GAP) - MINI_AVATAR_GAP + MINI_AVATAR_PADDING * 2; +} +function cardWidth(node) { + const { roleLabel: defaultRoleLabel } = getRoleInfo(node); + const roleLabel = node.role.startsWith("\xD7") ? node.role : defaultRoleLabel; + const nameW = measureText(node.name, 14) + CARD_PAD_X * 2; + const roleW = measureText(roleLabel, 11) + CARD_PAD_X * 2; + let w5 = Math.max(CARD_MIN_W, Math.max(nameW, roleW)); + if (node.collapsedReports && node.collapsedReports.length > 0) { + w5 = Math.max(w5, avatarGridWidth(node.collapsedReports.length)); + } + return w5; +} +function cardHeight(node) { + if (node.collapsedReports && node.collapsedReports.length > 0) { + return CARD_H + avatarGridHeight(node.collapsedReports.length); + } + return CARD_H; +} +function subtreeWidth(node) { + const cw = cardWidth(node); + if (!node.reports || node.reports.length === 0) return cw; + const childrenW = node.reports.reduce( + (sum, child, i5) => sum + subtreeWidth(child) + (i5 > 0 ? GAP_X : 0), + 0 + ); + return Math.max(cw, childrenW); +} +function layoutTree(node, x5, y2) { + const w5 = cardWidth(node); + const sw = subtreeWidth(node); + const cardX = x5 + (sw - w5) / 2; + const h5 = cardHeight(node); + const layoutNode = { + node, + x: cardX, + y: y2, + width: w5, + height: h5, + children: [] + }; + if (node.reports && node.reports.length > 0) { + let childX = x5; + const childY = y2 + h5 + GAP_Y; + for (let i5 = 0; i5 < node.reports.length; i5++) { + const child = node.reports[i5]; + const childSW = subtreeWidth(child); + layoutNode.children.push(layoutTree(child, childX, childY)); + childX += childSW + GAP_X; + } + } + return layoutNode; +} +function escapeXml(s5) { + return s5.replace(/&/g, "&").replace(//g, ">").replace(/"/g, """); +} +function renderEmojiAvatar(cx, cy, radius, bgFill, emojiSvg, bgStroke) { + const emojiSize = radius * 1.3; + const emojiX = cx - emojiSize / 2; + const emojiY = cy - emojiSize / 2; + const stroke = bgStroke ? `stroke="${bgStroke}" stroke-width="1"` : ""; + return ` + ${emojiSvg}`; +} +function defaultRenderCard(ln, theme) { + if (ln.node.role === "overflow") { + const cx2 = ln.x + ln.width / 2; + const cy = ln.y + ln.height / 2; + return ` + + ${escapeXml(ln.node.name)} + `; + } + const { roleLabel: defaultRoleLabel, bg, emojiSvg } = getRoleInfo(ln.node); + const roleLabel = ln.node.role.startsWith("\xD7") ? ln.node.role : defaultRoleLabel; + const cx = ln.x + ln.width / 2; + const avatarCY = ln.y + 27; + const nameY = ln.y + 66; + const roleY = ln.y + 82; + const filterId = `shadow-${ln.node.id}`; + const shadowFilter = theme.cardShadow ? `filter="url(#${filterId})"` : ""; + const shadowDef = theme.cardShadow ? ` + + + ` : ""; + const isLight = theme.bgColor === "#fafaf9" || theme.bgColor === "#ffffff"; + const avatarBg = isLight ? bg : "rgba(255,255,255,0.06)"; + const avatarStroke = isLight ? void 0 : "rgba(255,255,255,0.08)"; + let avatarGridSvg = ""; + const collapsed = ln.node.collapsedReports; + if (collapsed && collapsed.length > 0) { + const gridTop = ln.y + CARD_H + MINI_AVATAR_PADDING; + const cols = Math.min(collapsed.length, MINI_AVATAR_MAX_COLS); + const gridTotalW = cols * (MINI_AVATAR_SIZE + MINI_AVATAR_GAP) - MINI_AVATAR_GAP; + const gridStartX = ln.x + (ln.width - gridTotalW) / 2; + for (let i5 = 0; i5 < collapsed.length; i5++) { + const col = i5 % MINI_AVATAR_MAX_COLS; + const row = Math.floor(i5 / MINI_AVATAR_MAX_COLS); + const dotCx = gridStartX + col * (MINI_AVATAR_SIZE + MINI_AVATAR_GAP) + MINI_AVATAR_SIZE / 2; + const dotCy = gridTop + row * (MINI_AVATAR_SIZE + MINI_AVATAR_GAP) + MINI_AVATAR_SIZE / 2; + const { bg: dotBg } = getRoleInfo(collapsed[i5]); + const dotFill = isLight ? dotBg : "rgba(255,255,255,0.1)"; + avatarGridSvg += ``; + } + } + return ` + ${shadowDef} + + ${renderEmojiAvatar(cx, avatarCY, AVATAR_SIZE / 2, avatarBg, emojiSvg, avatarStroke)} + ${escapeXml(ln.node.name)} + ${escapeXml(roleLabel)} + ${avatarGridSvg} + `; +} +function renderConnectors(ln, theme) { + if (ln.children.length === 0) return ""; + const parentCx = ln.x + ln.width / 2; + const parentBottom = ln.y + ln.height; + const midY = parentBottom + GAP_Y / 2; + const lc = theme.lineColor; + const lw = theme.lineWidth; + let svg2 = ""; + svg2 += ``; + if (ln.children.length === 1) { + const childCx = ln.children[0].x + ln.children[0].width / 2; + svg2 += ``; + } else { + const leftCx = ln.children[0].x + ln.children[0].width / 2; + const rightCx = ln.children[ln.children.length - 1].x + ln.children[ln.children.length - 1].width / 2; + svg2 += ``; + for (const child of ln.children) { + const childCx = child.x + child.width / 2; + svg2 += ``; + } + } + for (const child of ln.children) { + svg2 += renderConnectors(child, theme); + } + return svg2; +} +function renderCards(ln, theme) { + const render = theme.renderCard || defaultRenderCard; + let svg2 = render(ln, theme); + for (const child of ln.children) { + svg2 += renderCards(child, theme); + } + return svg2; +} +function treeBounds(ln) { + let minX = ln.x; + let minY = ln.y; + let maxX = ln.x + ln.width; + let maxY = ln.y + ln.height; + for (const child of ln.children) { + const cb = treeBounds(child); + minX = Math.min(minX, cb.minX); + minY = Math.min(minY, cb.minY); + maxX = Math.max(maxX, cb.maxX); + maxY = Math.max(maxY, cb.maxY); + } + return { minX, minY, maxX, maxY }; +} +var TASKCORE_LOGO_SVG = ` + + + + Taskcore +`; +var TARGET_W = 1280; +var TARGET_H = 640; +function countNodes(nodes) { + let count2 = 0; + for (const n5 of nodes) { + count2 += 1 + countNodes(n5.reports ?? []); + } + return count2; +} +var COLLAPSE_THRESHOLD = 20; +var MAX_LEVEL_WIDTH = 8; +var MAX_CHILDREN_SHOWN = 6; +function flattenDescendants(nodes) { + const result = []; + for (const n5 of nodes) { + result.push(n5); + result.push(...flattenDescendants(n5.reports ?? [])); + } + return result; +} +function nodesAtDepth(nodes, depth) { + if (depth === 0) return nodes; + const result = []; + for (const n5 of nodes) { + result.push(...nodesAtDepth(n5.reports ?? [], depth - 1)); + } + return result; +} +function estimateNextLevelWidth(parentNodes) { + let total = 0; + for (const p5 of parentNodes) { + const childCount = (p5.reports ?? []).length; + if (childCount === 0) continue; + total += Math.min(childCount, MAX_CHILDREN_SHOWN + 1); + } + return total; +} +function collapseToAvatars(node) { + const childCount = countNodes(node.reports ?? []); + if (childCount === 0) return node; + return { + ...node, + role: `\xD7${childCount} reports`, + collapsedReports: flattenDescendants(node.reports ?? []), + reports: [] + }; +} +function truncateChildren(node) { + const children = node.reports ?? []; + if (children.length <= MAX_CHILDREN_SHOWN) return node; + const kept = children.slice(0, MAX_CHILDREN_SHOWN); + const hiddenCount = children.length - MAX_CHILDREN_SHOWN; + const placeholder = { + id: `${node.id}-more`, + name: `+${hiddenCount} more`, + role: "overflow", + status: "active", + reports: [] + }; + return { ...node, reports: [...kept, placeholder] }; +} +function smartCollapseTree(roots) { + const clone3 = (nodes) => nodes.map((n5) => ({ ...n5, reports: clone3(n5.reports ?? []) })); + const tree = clone3(roots); + for (let depth = 0; depth < 10; depth++) { + const parents = nodesAtDepth(tree, depth); + const parentsWithChildren = parents.filter((p5) => (p5.reports ?? []).length > 0); + if (parentsWithChildren.length === 0) break; + const nextWidth = estimateNextLevelWidth(parentsWithChildren); + if (nextWidth <= MAX_LEVEL_WIDTH) { + for (const p5 of parentsWithChildren) { + if ((p5.reports ?? []).length > MAX_CHILDREN_SHOWN) { + const truncated = truncateChildren(p5); + p5.reports = truncated.reports; + } + } + continue; + } + for (const p5 of parentsWithChildren) { + const collapsed = collapseToAvatars(p5); + p5.role = collapsed.role; + p5.collapsedReports = collapsed.collapsedReports; + p5.reports = []; + } + break; + } + return tree; +} +function renderOrgChartSvg(orgTree, style = "warmth", overlay) { + const theme = THEMES[style] || THEMES.warmth; + const totalNodes = countNodes(orgTree); + const effectiveTree = totalNodes > COLLAPSE_THRESHOLD ? smartCollapseTree(orgTree) : orgTree; + let root; + if (effectiveTree.length === 1) { + root = effectiveTree[0]; + } else { + root = { + id: "virtual-root", + name: "Organization", + role: "Root", + status: "active", + reports: effectiveTree + }; + } + const layout = layoutTree(root, PADDING, PADDING + 24); + const bounds = treeBounds(layout); + const contentW = bounds.maxX + PADDING; + const contentH = bounds.maxY + PADDING; + const scale = Math.min(TARGET_W / contentW, TARGET_H / contentH, 1); + const scaledW = contentW * scale; + const scaledH = contentH * scale; + const offsetX = (TARGET_W - scaledW) / 2; + const offsetY = (TARGET_H - scaledH) / 2; + const logoX = TARGET_W - 110 - LOGO_PADDING; + const logoY = LOGO_PADDING; + const overlayNameSvg = overlay?.companyName ? `${svgEscape(overlay.companyName)}` : ""; + const overlayStatsSvg = overlay?.stats ? `${svgEscape(overlay.stats)}` : ""; + return ` + ${theme.defs(TARGET_W, TARGET_H)} + + ${theme.bgExtras(TARGET_W, TARGET_H)} + + ${TASKCORE_LOGO_SVG} + + ${overlayNameSvg} + ${overlayStatsSvg} + + ${renderConnectors(layout, theme)} + ${renderCards(layout, theme)} + +`; +} +function svgEscape(s5) { + return s5.replace(/&/g, "&").replace(//g, ">").replace(/"/g, """); +} +async function renderOrgChartPng(orgTree, style = "warmth", overlay) { + const svg2 = renderOrgChartSvg(orgTree, style, overlay); + const sharpModule = await import("sharp"); + const sharp = sharpModule.default; + return sharp(Buffer.from(svg2), { density: 144 }).resize(TARGET_W, TARGET_H).png().toBuffer(); +} + +// server/src/services/company-portability.ts +function buildOrgTreeFromManifest(agents2) { + const ROLE_LABELS2 = { + ceo: "Chief Executive", + cto: "Technology", + cmo: "Marketing", + cfo: "Finance", + coo: "Operations", + vp: "VP", + manager: "Manager", + engineer: "Engineer", + agent: "Agent" + }; + const bySlug = new Map(agents2.map((a5) => [a5.slug, a5])); + const childrenOf = /* @__PURE__ */ new Map(); + for (const a5 of agents2) { + const parent = a5.reportsToSlug ?? null; + const list2 = childrenOf.get(parent) ?? []; + list2.push(a5); + childrenOf.set(parent, list2); + } + const build = (parentSlug) => { + const members = childrenOf.get(parentSlug) ?? []; + return members.map((m5) => ({ + id: m5.slug, + name: m5.name, + role: ROLE_LABELS2[m5.role] ?? m5.role, + status: "active", + reports: build(m5.slug) + })); + }; + const roots = agents2.filter((a5) => !a5.reportsToSlug || !bySlug.has(a5.reportsToSlug)); + const rootSlugs = new Set(roots.map((r5) => r5.slug)); + const tree = build(null); + for (const root of roots) { + if (root.reportsToSlug && !bySlug.has(root.reportsToSlug)) { + tree.push({ + id: root.slug, + name: root.name, + role: ROLE_LABELS2[root.role] ?? root.role, + status: "active", + reports: build(root.slug) + }); + } + } + return tree; +} +var DEFAULT_INCLUDE = { + company: true, + agents: true, + projects: false, + issues: false, + skills: false +}; +var DEFAULT_COLLISION_STRATEGY = "rename"; +var execFileAsync5 = promisify6(execFile6); +var bundledSkillsCommitPromise = null; +function resolveImportMode(options) { + return options?.mode ?? "board_full"; +} +function resolveSkillConflictStrategy(mode, collisionStrategy) { + if (mode === "board_full") return "replace"; + return collisionStrategy === "skip" ? "skip" : "rename"; +} +function classifyPortableFileKind(pathValue) { + const normalized = normalizePortablePath2(pathValue); + if (normalized === "COMPANY.md") return "company"; + if (normalized === ".taskcore.yaml" || normalized === ".taskcore.yml") return "extension"; + if (normalized === "README.md") return "readme"; + if (normalized.startsWith("agents/")) return "agent"; + if (normalized.startsWith("skills/")) return "skill"; + if (normalized.startsWith("projects/")) return "project"; + if (normalized.startsWith("tasks/")) return "issue"; + return "other"; +} +function normalizeSkillSlug3(value) { + return value ? normalizeAgentUrlKey(value) ?? null : null; +} +function normalizeSkillKey2(value) { + if (!value) return null; + const segments = value.split("/").map((segment) => normalizeSkillSlug3(segment)).filter((segment) => Boolean(segment)); + return segments.length > 0 ? segments.join("/") : null; +} +function readSkillKey(frontmatter) { + const metadata = isPlainRecord5(frontmatter.metadata) ? frontmatter.metadata : null; + const taskcore = isPlainRecord5(metadata?.taskcore) ? metadata?.taskcore : null; + return normalizeSkillKey2( + asString14(frontmatter.key) ?? asString14(frontmatter.skillKey) ?? asString14(metadata?.skillKey) ?? asString14(metadata?.canonicalKey) ?? asString14(metadata?.taskcoreSkillKey) ?? asString14(taskcore?.skillKey) ?? asString14(taskcore?.key) + ); +} +function deriveManifestSkillKey(frontmatter, fallbackSlug, metadata, sourceType, sourceLocator) { + const explicit = readSkillKey(frontmatter); + if (explicit) return explicit; + const slug = normalizeSkillSlug3(asString14(frontmatter.slug) ?? fallbackSlug) ?? "skill"; + const sourceKind = asString14(metadata?.sourceKind); + const owner = normalizeSkillSlug3(asString14(metadata?.owner)); + const repo = normalizeSkillSlug3(asString14(metadata?.repo)); + if ((sourceType === "github" || sourceType === "skills_sh" || sourceKind === "github" || sourceKind === "skills_sh") && owner && repo) { + return `${owner}/${repo}/${slug}`; + } + if (sourceKind === "taskcore_bundled") { + return `taskcore/taskcore/${slug}`; + } + if (sourceType === "url" || sourceKind === "url") { + try { + const host = normalizeSkillSlug3(sourceLocator ? new URL(sourceLocator).host : null) ?? "url"; + return `url/${host}/${slug}`; + } catch { + return `url/unknown/${slug}`; + } + } + return slug; +} +function hashSkillValue2(value) { + return createHash14("sha256").update(value).digest("hex").slice(0, 8); +} +function normalizeExportPathSegment(value, preserveCase = false) { + if (!value) return null; + const trimmed = value.trim(); + if (!trimmed) return null; + const normalized = trimmed.replace(/[^A-Za-z0-9._-]+/g, "-").replace(/-+/g, "-").replace(/^-+|-+$/g, ""); + if (!normalized) return null; + return preserveCase ? normalized : normalized.toLowerCase(); +} +function readSkillSourceKind(skill) { + const metadata = isPlainRecord5(skill.metadata) ? skill.metadata : null; + return asString14(metadata?.sourceKind); +} +function deriveLocalExportNamespace(skill, slug) { + const metadata = isPlainRecord5(skill.metadata) ? skill.metadata : null; + const candidates = [ + asString14(metadata?.projectName), + asString14(metadata?.workspaceName) + ]; + if (skill.sourceLocator) { + const basename3 = path40.basename(skill.sourceLocator); + candidates.push(basename3.toLowerCase() === "skill.md" ? path40.basename(path40.dirname(skill.sourceLocator)) : basename3); + } + for (const value of candidates) { + const normalized = normalizeSkillSlug3(value); + if (normalized && normalized !== slug) return normalized; + } + return null; +} +function derivePrimarySkillExportDir(skill, slug, companyIssuePrefix) { + const normalizedKey = normalizeSkillKey2(skill.key); + const keySegments = normalizedKey?.split("/") ?? []; + const primaryNamespace = keySegments[0] ?? null; + if (primaryNamespace === "company") { + const companySegment = normalizeExportPathSegment(companyIssuePrefix, true) ?? normalizeExportPathSegment(keySegments[1], true) ?? "company"; + return `skills/company/${companySegment}/${slug}`; + } + if (primaryNamespace === "local") { + const localNamespace = deriveLocalExportNamespace(skill, slug); + return localNamespace ? `skills/local/${localNamespace}/${slug}` : `skills/local/${slug}`; + } + if (primaryNamespace === "url") { + let derivedHost = keySegments[1] ?? null; + if (!derivedHost) { + try { + derivedHost = normalizeSkillSlug3(skill.sourceLocator ? new URL(skill.sourceLocator).host : null); + } catch { + derivedHost = null; + } + } + const host = derivedHost ?? "url"; + return `skills/url/${host}/${slug}`; + } + if (keySegments.length > 1) { + return `skills/${keySegments.join("/")}`; + } + return `skills/${slug}`; +} +function appendSkillExportDirSuffix(packageDir, suffix) { + const lastSeparator = packageDir.lastIndexOf("/"); + if (lastSeparator < 0) return `${packageDir}--${suffix}`; + return `${packageDir.slice(0, lastSeparator + 1)}${packageDir.slice(lastSeparator + 1)}--${suffix}`; +} +function deriveSkillExportDirCandidates(skill, slug, companyIssuePrefix) { + const primaryDir = derivePrimarySkillExportDir(skill, slug, companyIssuePrefix); + const metadata = isPlainRecord5(skill.metadata) ? skill.metadata : null; + const sourceKind = readSkillSourceKind(skill); + const suffixes = /* @__PURE__ */ new Set(); + const pushSuffix = (value, preserveCase = false) => { + const normalized = normalizeExportPathSegment(value, preserveCase); + if (normalized && normalized !== slug) { + suffixes.add(normalized); + } + }; + if (sourceKind === "taskcore_bundled") { + pushSuffix("taskcore"); + } + if (skill.sourceType === "github" || skill.sourceType === "skills_sh") { + pushSuffix(asString14(metadata?.repo)); + pushSuffix(asString14(metadata?.owner)); + pushSuffix(skill.sourceType === "skills_sh" ? "skills_sh" : "github"); + } else if (skill.sourceType === "url") { + try { + pushSuffix(skill.sourceLocator ? new URL(skill.sourceLocator).host : null); + } catch { + } + pushSuffix("url"); + } else if (skill.sourceType === "local_path") { + pushSuffix(asString14(metadata?.projectName)); + pushSuffix(asString14(metadata?.workspaceName)); + pushSuffix(deriveLocalExportNamespace(skill, slug)); + if (sourceKind === "managed_local") pushSuffix("company"); + if (sourceKind === "project_scan") pushSuffix("project"); + pushSuffix("local"); + } else { + pushSuffix(sourceKind); + pushSuffix("skill"); + } + return [primaryDir, ...Array.from(suffixes, (suffix) => appendSkillExportDirSuffix(primaryDir, suffix))]; +} +function buildSkillExportDirMap(skills, companyIssuePrefix) { + const usedDirs = /* @__PURE__ */ new Set(); + const keyToDir = /* @__PURE__ */ new Map(); + const orderedSkills = [...skills].sort((left, right) => left.key.localeCompare(right.key)); + for (const skill of orderedSkills) { + const slug = normalizeSkillSlug3(skill.slug) ?? "skill"; + const candidates = deriveSkillExportDirCandidates(skill, slug, companyIssuePrefix); + let packageDir = candidates.find((candidate) => !usedDirs.has(candidate)) ?? null; + if (!packageDir) { + packageDir = appendSkillExportDirSuffix(candidates[0] ?? `skills/${slug}`, hashSkillValue2(skill.key)); + while (usedDirs.has(packageDir)) { + packageDir = appendSkillExportDirSuffix( + candidates[0] ?? `skills/${slug}`, + hashSkillValue2(`${skill.key}:${packageDir}`) + ); + } + } + usedDirs.add(packageDir); + keyToDir.set(skill.key, packageDir); + } + return keyToDir; +} +function isSensitiveEnvKey2(key) { + const normalized = key.trim().toLowerCase(); + return normalized === "token" || normalized.endsWith("_token") || normalized.endsWith("-token") || normalized.includes("apikey") || normalized.includes("api_key") || normalized.includes("api-key") || normalized.includes("access_token") || normalized.includes("access-token") || normalized.includes("auth") || normalized.includes("auth_token") || normalized.includes("auth-token") || normalized.includes("authorization") || normalized.includes("bearer") || normalized.includes("secret") || normalized.includes("passwd") || normalized.includes("password") || normalized.includes("credential") || normalized.includes("jwt") || normalized.includes("privatekey") || normalized.includes("private_key") || normalized.includes("private-key") || normalized.includes("cookie") || normalized.includes("connectionstring"); +} +function normalizePortableProjectEnv(value) { + const parsed = envConfigSchema.safeParse(value); + return parsed.success ? parsed.data : null; +} +function extractPortableScopedEnvInputs(scope, envValue, warnings) { + if (!isPlainRecord5(envValue)) return []; + const env2 = envValue; + const inputs = []; + for (const [key, binding] of Object.entries(env2)) { + if (key.toUpperCase() === "PATH") { + warnings.push(`${scope.warningPrefix} PATH override was omitted from export because it is system-dependent.`); + continue; + } + if (isPlainRecord5(binding) && binding.type === "secret_ref") { + inputs.push({ + key, + description: `Provide ${key} for ${scope.label}`, + agentSlug: scope.agentSlug, + projectSlug: scope.projectSlug, + kind: "secret", + requirement: "optional", + defaultValue: "", + portability: "portable" + }); + continue; + } + if (isPlainRecord5(binding) && binding.type === "plain") { + const defaultValue = asString14(binding.value); + const isSensitive = isSensitiveEnvKey2(key); + const portability = defaultValue && isAbsoluteCommand(defaultValue) ? "system_dependent" : "portable"; + if (portability === "system_dependent") { + warnings.push(`${scope.warningPrefix} env ${key} default was exported as system-dependent.`); + } + inputs.push({ + key, + description: `Optional default for ${key} on ${scope.label}`, + agentSlug: scope.agentSlug, + projectSlug: scope.projectSlug, + kind: isSensitive ? "secret" : "plain", + requirement: "optional", + defaultValue: isSensitive ? "" : defaultValue ?? "", + portability + }); + continue; + } + if (typeof binding === "string") { + const portability = isAbsoluteCommand(binding) ? "system_dependent" : "portable"; + if (portability === "system_dependent") { + warnings.push(`${scope.warningPrefix} env ${key} default was exported as system-dependent.`); + } + inputs.push({ + key, + description: `Optional default for ${key} on ${scope.label}`, + agentSlug: scope.agentSlug, + projectSlug: scope.projectSlug, + kind: isSensitiveEnvKey2(key) ? "secret" : "plain", + requirement: "optional", + defaultValue: isSensitiveEnvKey2(key) ? "" : binding, + portability + }); + } + } + return inputs; +} +var COMPANY_LOGO_CONTENT_TYPE_EXTENSIONS = { + "image/gif": ".gif", + "image/jpeg": ".jpg", + "image/png": ".png", + "image/svg+xml": ".svg", + "image/webp": ".webp" +}; +var COMPANY_LOGO_FILE_NAME = "company-logo"; +var RUNTIME_DEFAULT_RULES = [ + { path: ["heartbeat", "cooldownSec"], value: 10 }, + { path: ["heartbeat", "intervalSec"], value: 3600 }, + { path: ["heartbeat", "wakeOnOnDemand"], value: true }, + { path: ["heartbeat", "wakeOnAssignment"], value: true }, + { path: ["heartbeat", "wakeOnAutomation"], value: true }, + { path: ["heartbeat", "wakeOnDemand"], value: true }, + { path: ["heartbeat", "maxConcurrentRuns"], value: 3 } +]; +var ADAPTER_DEFAULT_RULES_BY_TYPE = { + codex_local: [ + { path: ["timeoutSec"], value: 0 }, + { path: ["graceSec"], value: 15 } + ], + gemini_local: [ + { path: ["timeoutSec"], value: 0 }, + { path: ["graceSec"], value: 15 } + ], + opencode_local: [ + { path: ["timeoutSec"], value: 0 }, + { path: ["graceSec"], value: 15 } + ], + cursor: [ + { path: ["timeoutSec"], value: 0 }, + { path: ["graceSec"], value: 15 } + ], + claude_local: [ + { path: ["timeoutSec"], value: 0 }, + { path: ["graceSec"], value: 15 }, + { path: ["maxTurnsPerRun"], value: 1e3 } + ], + openclaw_gateway: [ + { path: ["timeoutSec"], value: 120 }, + { path: ["waitTimeoutMs"], value: 12e4 }, + { path: ["sessionKeyStrategy"], value: "fixed" }, + { path: ["sessionKey"], value: "taskcore" }, + { path: ["role"], value: "operator" }, + { path: ["scopes"], value: ["operator.admin"] } + ] +}; +function isPlainRecord5(value) { + return typeof value === "object" && value !== null && !Array.isArray(value); +} +function asString14(value) { + if (typeof value !== "string") return null; + const trimmed = value.trim(); + return trimmed.length > 0 ? trimmed : null; +} +function asBoolean5(value) { + return typeof value === "boolean" ? value : null; +} +function asInteger(value) { + return typeof value === "number" && Number.isInteger(value) ? value : null; +} +function normalizeRoutineTriggerExtension(value) { + if (!isPlainRecord5(value)) return null; + const kind = asString14(value.kind); + if (!kind) return null; + return { + kind, + label: asString14(value.label), + enabled: asBoolean5(value.enabled) ?? true, + cronExpression: asString14(value.cronExpression), + timezone: asString14(value.timezone), + signingMode: asString14(value.signingMode), + replayWindowSec: asInteger(value.replayWindowSec) + }; +} +function normalizeRoutineVariableExtension(value) { + if (!isPlainRecord5(value)) return null; + const name = asString14(value.name); + if (!name) return null; + const type = asString14(value.type) ?? "text"; + if (!["text", "textarea", "number", "boolean", "select"].includes(type)) return null; + const options = Array.isArray(value.options) ? value.options.map((entry) => asString14(entry)).filter((entry) => Boolean(entry)) : []; + const defaultValue = typeof value.defaultValue === "string" || typeof value.defaultValue === "number" || typeof value.defaultValue === "boolean" ? value.defaultValue : null; + return { + name, + label: asString14(value.label), + type, + defaultValue, + required: asBoolean5(value.required) ?? true, + options + }; +} +function normalizeRoutineExtension(value) { + if (!isPlainRecord5(value)) return null; + const triggers = Array.isArray(value.triggers) ? value.triggers.map((entry) => normalizeRoutineTriggerExtension(entry)).filter((entry) => entry !== null) : []; + const variables = Array.isArray(value.variables) ? value.variables.map((entry) => normalizeRoutineVariableExtension(entry)).filter((entry) => entry !== null) : null; + const routine = { + concurrencyPolicy: asString14(value.concurrencyPolicy), + catchUpPolicy: asString14(value.catchUpPolicy), + variables, + triggers + }; + return stripEmptyValues(routine) ? routine : null; +} +function containsAbsolutePathFragment(value) { + return /(^|\s)(\/[^/\s]|[A-Za-z]:[\\/])/.test(value); +} +function containsSystemDependentPathValue(value) { + if (typeof value === "string") { + return path40.isAbsolute(value) || /^[A-Za-z]:[\\/]/.test(value) || containsAbsolutePathFragment(value); + } + if (Array.isArray(value)) { + return value.some((entry) => containsSystemDependentPathValue(entry)); + } + if (isPlainRecord5(value)) { + return Object.values(value).some((entry) => containsSystemDependentPathValue(entry)); + } + return false; +} +function clonePortableRecord(value) { + if (!isPlainRecord5(value)) return null; + return structuredClone(value); +} +function disableImportedTimerHeartbeat(runtimeConfig) { + const next = clonePortableRecord(runtimeConfig) ?? {}; + const heartbeat = isPlainRecord5(next.heartbeat) ? { ...next.heartbeat } : {}; + heartbeat.enabled = false; + next.heartbeat = heartbeat; + return next; +} +function normalizePortableProjectWorkspaceExtension(workspaceKey, value) { + if (!isPlainRecord5(value)) return null; + const normalizedKey = normalizeAgentUrlKey(workspaceKey) ?? workspaceKey.trim(); + if (!normalizedKey) return null; + return { + key: normalizedKey, + name: asString14(value.name) ?? normalizedKey, + sourceType: asString14(value.sourceType), + repoUrl: asString14(value.repoUrl), + repoRef: asString14(value.repoRef), + defaultRef: asString14(value.defaultRef), + visibility: asString14(value.visibility), + setupCommand: asString14(value.setupCommand), + cleanupCommand: asString14(value.cleanupCommand), + metadata: isPlainRecord5(value.metadata) ? value.metadata : null, + isPrimary: asBoolean5(value.isPrimary) ?? false + }; +} +function derivePortableProjectWorkspaceKey(workspace, usedKeys) { + const baseKey = normalizeAgentUrlKey(workspace.name) ?? normalizeAgentUrlKey(asString14(workspace.repoUrl)?.split("/").pop()?.replace(/\.git$/i, "") ?? "") ?? "workspace"; + return uniqueSlug(baseKey, usedKeys); +} +function exportPortableProjectExecutionWorkspacePolicy(projectSlug, policy, workspaceKeyById, warnings) { + const next = clonePortableRecord(policy); + if (!next) return null; + const defaultWorkspaceId = asString14(next.defaultProjectWorkspaceId); + if (defaultWorkspaceId) { + const defaultWorkspaceKey = workspaceKeyById.get(defaultWorkspaceId); + if (defaultWorkspaceKey) { + next.defaultProjectWorkspaceKey = defaultWorkspaceKey; + } else { + warnings.push(`Project ${projectSlug} default workspace ${defaultWorkspaceId} was omitted from export because that workspace is not portable.`); + } + delete next.defaultProjectWorkspaceId; + } + const cleaned = stripEmptyValues(next); + return isPlainRecord5(cleaned) ? cleaned : null; +} +function importPortableProjectExecutionWorkspacePolicy(projectSlug, policy, workspaceIdByKey, warnings) { + const next = clonePortableRecord(policy); + if (!next) return null; + const defaultWorkspaceKey = asString14(next.defaultProjectWorkspaceKey); + if (defaultWorkspaceKey) { + const defaultWorkspaceId = workspaceIdByKey.get(defaultWorkspaceKey); + if (defaultWorkspaceId) { + next.defaultProjectWorkspaceId = defaultWorkspaceId; + } else { + warnings.push(`Project ${projectSlug} references missing workspace key ${defaultWorkspaceKey}; imported execution workspace policy without a default workspace.`); + } + } + delete next.defaultProjectWorkspaceKey; + const cleaned = stripEmptyValues(next); + return isPlainRecord5(cleaned) ? cleaned : null; +} +function stripPortableProjectExecutionWorkspaceRefs(policy) { + const next = clonePortableRecord(policy); + if (!next) return null; + delete next.defaultProjectWorkspaceId; + delete next.defaultProjectWorkspaceKey; + const cleaned = stripEmptyValues(next); + return isPlainRecord5(cleaned) ? cleaned : null; +} +async function readGitOutput(cwd, args) { + const { stdout } = await execFileAsync5("git", ["-C", cwd, ...args], { cwd }); + const trimmed = stdout.trim(); + return trimmed.length > 0 ? trimmed : null; +} +async function inferPortableWorkspaceGitMetadata(workspace) { + const cwd = asString14(workspace.cwd); + if (!cwd) { + return { + repoUrl: null, + repoRef: null, + defaultRef: null + }; + } + let repoUrl = null; + try { + repoUrl = await readGitOutput(cwd, ["remote", "get-url", "origin"]); + } catch { + try { + const firstRemote = await readGitOutput(cwd, ["remote"]); + const remoteName = firstRemote?.split("\n").map((entry) => entry.trim()).find(Boolean) ?? null; + if (remoteName) { + repoUrl = await readGitOutput(cwd, ["remote", "get-url", remoteName]); + } + } catch { + repoUrl = null; + } + } + let repoRef = null; + try { + repoRef = await readGitOutput(cwd, ["branch", "--show-current"]); + } catch { + repoRef = null; + } + let defaultRef = null; + try { + const remoteHead = await readGitOutput(cwd, ["symbolic-ref", "--quiet", "--short", "refs/remotes/origin/HEAD"]); + defaultRef = remoteHead?.startsWith("origin/") ? remoteHead.slice("origin/".length) : remoteHead; + } catch { + defaultRef = null; + } + return { + repoUrl, + repoRef, + defaultRef + }; +} +async function buildPortableProjectWorkspaces(projectSlug, workspaces, warnings) { + const exportedWorkspaces = {}; + const manifestWorkspaces = []; + const workspaceKeyById = /* @__PURE__ */ new Map(); + const workspaceKeyBySignature = /* @__PURE__ */ new Map(); + const manifestWorkspaceByKey = /* @__PURE__ */ new Map(); + const usedKeys = /* @__PURE__ */ new Set(); + for (const workspace of workspaces ?? []) { + const inferredGitMetadata = !asString14(workspace.repoUrl) || !asString14(workspace.repoRef) || !asString14(workspace.defaultRef) ? await inferPortableWorkspaceGitMetadata(workspace) : { repoUrl: null, repoRef: null, defaultRef: null }; + const repoUrl = asString14(workspace.repoUrl) ?? inferredGitMetadata.repoUrl; + if (!repoUrl) { + warnings.push(`Project ${projectSlug} workspace ${workspace.name} was omitted from export because it does not have a portable repoUrl.`); + continue; + } + const repoRef = asString14(workspace.repoRef) ?? inferredGitMetadata.repoRef; + const defaultRef = asString14(workspace.defaultRef) ?? inferredGitMetadata.defaultRef ?? repoRef; + const workspaceSignature = JSON.stringify({ + name: workspace.name, + repoUrl, + repoRef, + defaultRef + }); + const existingWorkspaceKey = workspaceKeyBySignature.get(workspaceSignature); + if (existingWorkspaceKey) { + workspaceKeyById.set(workspace.id, existingWorkspaceKey); + const existingManifestWorkspace = manifestWorkspaceByKey.get(existingWorkspaceKey); + if (existingManifestWorkspace && workspace.isPrimary) { + existingManifestWorkspace.isPrimary = true; + const existingExtensionWorkspace = exportedWorkspaces[existingWorkspaceKey]; + if (isPlainRecord5(existingExtensionWorkspace)) existingExtensionWorkspace.isPrimary = true; + } + continue; + } + const workspaceKey = derivePortableProjectWorkspaceKey(workspace, usedKeys); + workspaceKeyById.set(workspace.id, workspaceKey); + workspaceKeyBySignature.set(workspaceSignature, workspaceKey); + let setupCommand = asString14(workspace.setupCommand); + if (setupCommand && containsAbsolutePathFragment(setupCommand)) { + warnings.push(`Project ${projectSlug} workspace ${workspaceKey} setupCommand was omitted from export because it is system-dependent.`); + setupCommand = null; + } + let cleanupCommand = asString14(workspace.cleanupCommand); + if (cleanupCommand && containsAbsolutePathFragment(cleanupCommand)) { + warnings.push(`Project ${projectSlug} workspace ${workspaceKey} cleanupCommand was omitted from export because it is system-dependent.`); + cleanupCommand = null; + } + const metadata = isPlainRecord5(workspace.metadata) && !containsSystemDependentPathValue(workspace.metadata) ? workspace.metadata : null; + if (isPlainRecord5(workspace.metadata) && metadata == null) { + warnings.push(`Project ${projectSlug} workspace ${workspaceKey} metadata was omitted from export because it contains system-dependent paths.`); + } + const portableWorkspace = stripEmptyValues({ + name: workspace.name, + sourceType: workspace.sourceType, + repoUrl, + repoRef, + defaultRef, + visibility: asString14(workspace.visibility), + setupCommand, + cleanupCommand, + metadata, + isPrimary: workspace.isPrimary ? true : void 0 + }); + if (!isPlainRecord5(portableWorkspace)) continue; + exportedWorkspaces[workspaceKey] = portableWorkspace; + const manifestWorkspace = { + key: workspaceKey, + name: workspace.name, + sourceType: asString14(workspace.sourceType), + repoUrl, + repoRef, + defaultRef, + visibility: asString14(workspace.visibility), + setupCommand, + cleanupCommand, + metadata, + isPrimary: workspace.isPrimary + }; + manifestWorkspaces.push(manifestWorkspace); + manifestWorkspaceByKey.set(workspaceKey, manifestWorkspace); + } + return { + extension: Object.keys(exportedWorkspaces).length > 0 ? exportedWorkspaces : void 0, + manifest: manifestWorkspaces, + workspaceKeyById + }; +} +var WEEKDAY_TO_CRON = { + sunday: "0", + monday: "1", + tuesday: "2", + wednesday: "3", + thursday: "4", + friday: "5", + saturday: "6" +}; +function readZonedDateParts(startsAt, timeZone) { + try { + const date7 = new Date(startsAt); + if (Number.isNaN(date7.getTime())) return null; + const formatter = new Intl.DateTimeFormat("en-US", { + timeZone, + hour12: false, + weekday: "long", + month: "numeric", + day: "numeric", + hour: "numeric", + minute: "numeric" + }); + const parts = Object.fromEntries( + formatter.formatToParts(date7).filter((entry) => entry.type !== "literal").map((entry) => [entry.type, entry.value]) + ); + const weekday = WEEKDAY_TO_CRON[parts.weekday?.toLowerCase() ?? ""]; + const month = Number(parts.month); + const day2 = Number(parts.day); + const hour2 = Number(parts.hour); + const minute2 = Number(parts.minute); + if (!weekday || !Number.isFinite(month) || !Number.isFinite(day2) || !Number.isFinite(hour2) || !Number.isFinite(minute2)) { + return null; + } + return { weekday, month, day: day2, hour: hour2, minute: minute2 }; + } catch { + return null; + } +} +function normalizeCronList(values2) { + return Array.from(new Set(values2)).sort((left, right) => Number(left) - Number(right)).join(","); +} +function buildLegacyRoutineTriggerFromRecurrence(issue2, scheduleValue) { + const warnings = []; + const errors = []; + if (!issue2.legacyRecurrence || !isPlainRecord5(issue2.legacyRecurrence)) { + return { trigger: null, warnings, errors }; + } + const schedule = isPlainRecord5(scheduleValue) ? scheduleValue : null; + const frequency = asString14(issue2.legacyRecurrence.frequency); + const interval2 = asInteger(issue2.legacyRecurrence.interval) ?? 1; + if (!frequency) { + errors.push(`Recurring task ${issue2.slug} uses legacy recurrence without frequency; add .taskcore.yaml routines.${issue2.slug}.triggers.`); + return { trigger: null, warnings, errors }; + } + if (interval2 < 1) { + errors.push(`Recurring task ${issue2.slug} uses legacy recurrence with an invalid interval; add .taskcore.yaml routines.${issue2.slug}.triggers.`); + return { trigger: null, warnings, errors }; + } + const timezone = asString14(schedule?.timezone) ?? "UTC"; + const startsAt = asString14(schedule?.startsAt); + const zonedStartsAt = startsAt ? readZonedDateParts(startsAt, timezone) : null; + if (startsAt && !zonedStartsAt) { + errors.push(`Recurring task ${issue2.slug} has an invalid legacy startsAt/timezone combination; add .taskcore.yaml routines.${issue2.slug}.triggers.`); + return { trigger: null, warnings, errors }; + } + const time5 = isPlainRecord5(issue2.legacyRecurrence.time) ? issue2.legacyRecurrence.time : null; + const hour2 = asInteger(time5?.hour) ?? zonedStartsAt?.hour ?? 0; + const minute2 = asInteger(time5?.minute) ?? zonedStartsAt?.minute ?? 0; + if (hour2 < 0 || hour2 > 23 || minute2 < 0 || minute2 > 59) { + errors.push(`Recurring task ${issue2.slug} uses legacy recurrence with an invalid time; add .taskcore.yaml routines.${issue2.slug}.triggers.`); + return { trigger: null, warnings, errors }; + } + if (issue2.legacyRecurrence.until != null || issue2.legacyRecurrence.count != null) { + warnings.push(`Recurring task ${issue2.slug} uses legacy recurrence end bounds; Taskcore will import the routine trigger without those limits.`); + } + let cronExpression = null; + if (frequency === "hourly") { + const hourField = interval2 === 1 ? "*" : zonedStartsAt ? `${zonedStartsAt.hour}-23/${interval2}` : `*/${interval2}`; + cronExpression = `${minute2} ${hourField} * * *`; + } else if (frequency === "daily") { + if (Array.isArray(issue2.legacyRecurrence.weekdays) || Array.isArray(issue2.legacyRecurrence.monthDays) || Array.isArray(issue2.legacyRecurrence.months)) { + errors.push(`Recurring task ${issue2.slug} uses unsupported legacy daily recurrence constraints; add .taskcore.yaml routines.${issue2.slug}.triggers.`); + return { trigger: null, warnings, errors }; + } + const dayField = interval2 === 1 ? "*" : `*/${interval2}`; + cronExpression = `${minute2} ${hour2} ${dayField} * *`; + } else if (frequency === "weekly") { + if (interval2 !== 1) { + errors.push(`Recurring task ${issue2.slug} uses legacy weekly recurrence with interval > 1; add .taskcore.yaml routines.${issue2.slug}.triggers.`); + return { trigger: null, warnings, errors }; + } + const weekdays = Array.isArray(issue2.legacyRecurrence.weekdays) ? issue2.legacyRecurrence.weekdays.map((entry) => asString14(entry)).filter((entry) => Boolean(entry)) : []; + const cronWeekdays = weekdays.map((entry) => WEEKDAY_TO_CRON[entry.toLowerCase()]).filter((entry) => Boolean(entry)); + if (cronWeekdays.length === 0 && zonedStartsAt?.weekday) { + cronWeekdays.push(zonedStartsAt.weekday); + } + if (cronWeekdays.length === 0) { + errors.push(`Recurring task ${issue2.slug} uses legacy weekly recurrence without weekdays; add .taskcore.yaml routines.${issue2.slug}.triggers.`); + return { trigger: null, warnings, errors }; + } + cronExpression = `${minute2} ${hour2} * * ${normalizeCronList(cronWeekdays)}`; + } else if (frequency === "monthly") { + if (interval2 !== 1) { + errors.push(`Recurring task ${issue2.slug} uses legacy monthly recurrence with interval > 1; add .taskcore.yaml routines.${issue2.slug}.triggers.`); + return { trigger: null, warnings, errors }; + } + if (Array.isArray(issue2.legacyRecurrence.ordinalWeekdays) && issue2.legacyRecurrence.ordinalWeekdays.length > 0) { + errors.push(`Recurring task ${issue2.slug} uses legacy ordinal monthly recurrence; add .taskcore.yaml routines.${issue2.slug}.triggers.`); + return { trigger: null, warnings, errors }; + } + const monthDays = Array.isArray(issue2.legacyRecurrence.monthDays) ? issue2.legacyRecurrence.monthDays.map((entry) => asInteger(entry)).filter((entry) => entry != null && entry >= 1 && entry <= 31) : []; + if (monthDays.length === 0 && zonedStartsAt?.day) { + monthDays.push(zonedStartsAt.day); + } + if (monthDays.length === 0) { + errors.push(`Recurring task ${issue2.slug} uses legacy monthly recurrence without monthDays; add .taskcore.yaml routines.${issue2.slug}.triggers.`); + return { trigger: null, warnings, errors }; + } + const months2 = Array.isArray(issue2.legacyRecurrence.months) ? issue2.legacyRecurrence.months.map((entry) => asInteger(entry)).filter((entry) => entry != null && entry >= 1 && entry <= 12) : []; + const monthField = months2.length > 0 ? normalizeCronList(months2.map(String)) : "*"; + cronExpression = `${minute2} ${hour2} ${normalizeCronList(monthDays.map(String))} ${monthField} *`; + } else if (frequency === "yearly") { + if (interval2 !== 1) { + errors.push(`Recurring task ${issue2.slug} uses legacy yearly recurrence with interval > 1; add .taskcore.yaml routines.${issue2.slug}.triggers.`); + return { trigger: null, warnings, errors }; + } + const months2 = Array.isArray(issue2.legacyRecurrence.months) ? issue2.legacyRecurrence.months.map((entry) => asInteger(entry)).filter((entry) => entry != null && entry >= 1 && entry <= 12) : []; + if (months2.length === 0 && zonedStartsAt?.month) { + months2.push(zonedStartsAt.month); + } + const monthDays = Array.isArray(issue2.legacyRecurrence.monthDays) ? issue2.legacyRecurrence.monthDays.map((entry) => asInteger(entry)).filter((entry) => entry != null && entry >= 1 && entry <= 31) : []; + if (monthDays.length === 0 && zonedStartsAt?.day) { + monthDays.push(zonedStartsAt.day); + } + if (months2.length === 0 || monthDays.length === 0) { + errors.push(`Recurring task ${issue2.slug} uses legacy yearly recurrence without month/monthDay anchors; add .taskcore.yaml routines.${issue2.slug}.triggers.`); + return { trigger: null, warnings, errors }; + } + cronExpression = `${minute2} ${hour2} ${normalizeCronList(monthDays.map(String))} ${normalizeCronList(months2.map(String))} *`; + } else { + errors.push(`Recurring task ${issue2.slug} uses unsupported legacy recurrence frequency "${frequency}"; add .taskcore.yaml routines.${issue2.slug}.triggers.`); + return { trigger: null, warnings, errors }; + } + return { + trigger: { + kind: "schedule", + label: "Migrated legacy recurrence", + enabled: true, + cronExpression, + timezone, + signingMode: null, + replayWindowSec: null + }, + warnings, + errors + }; +} +function resolvePortableRoutineDefinition(issue2, scheduleValue) { + const warnings = []; + const errors = []; + if (!issue2.recurring) { + return { routine: null, warnings, errors }; + } + const routine = issue2.routine ? { + concurrencyPolicy: issue2.routine.concurrencyPolicy, + catchUpPolicy: issue2.routine.catchUpPolicy, + variables: issue2.routine.variables ?? null, + triggers: [...issue2.routine.triggers] + } : { + concurrencyPolicy: null, + catchUpPolicy: null, + variables: null, + triggers: [] + }; + if (routine.concurrencyPolicy && !ROUTINE_CONCURRENCY_POLICIES.includes(routine.concurrencyPolicy)) { + errors.push(`Recurring task ${issue2.slug} uses unsupported routine concurrencyPolicy "${routine.concurrencyPolicy}".`); + } + if (routine.catchUpPolicy && !ROUTINE_CATCH_UP_POLICIES.includes(routine.catchUpPolicy)) { + errors.push(`Recurring task ${issue2.slug} uses unsupported routine catchUpPolicy "${routine.catchUpPolicy}".`); + } + for (const trigger of routine.triggers) { + if (!ROUTINE_TRIGGER_KINDS.includes(trigger.kind)) { + errors.push(`Recurring task ${issue2.slug} uses unsupported trigger kind "${trigger.kind}".`); + continue; + } + if (trigger.kind === "schedule") { + if (!trigger.cronExpression || !trigger.timezone) { + errors.push(`Recurring task ${issue2.slug} has a schedule trigger missing cronExpression/timezone.`); + continue; + } + const cronError = validateCron(trigger.cronExpression); + if (cronError) { + errors.push(`Recurring task ${issue2.slug} has an invalid schedule trigger: ${cronError}`); + } + continue; + } + if (trigger.kind === "webhook" && trigger.signingMode && !ROUTINE_TRIGGER_SIGNING_MODES.includes(trigger.signingMode)) { + errors.push(`Recurring task ${issue2.slug} uses unsupported webhook signingMode "${trigger.signingMode}".`); + } + } + if (routine.triggers.length === 0 && issue2.legacyRecurrence) { + const migrated = buildLegacyRoutineTriggerFromRecurrence(issue2, scheduleValue); + warnings.push(...migrated.warnings); + errors.push(...migrated.errors); + if (migrated.trigger) { + routine.triggers.push(migrated.trigger); + } + } + return { routine, warnings, errors }; +} +function toSafeSlug(input, fallback) { + return normalizeAgentUrlKey(input) ?? fallback; +} +function uniqueSlug(base, used) { + if (!used.has(base)) { + used.add(base); + return base; + } + let idx = 2; + while (true) { + const candidate = `${base}-${idx}`; + if (!used.has(candidate)) { + used.add(candidate); + return candidate; + } + idx += 1; + } +} +function uniqueNameBySlug(baseName, existingSlugs) { + const baseSlug = normalizeAgentUrlKey(baseName) ?? "agent"; + if (!existingSlugs.has(baseSlug)) return baseName; + let idx = 2; + while (true) { + const candidateName = `${baseName} ${idx}`; + const candidateSlug = normalizeAgentUrlKey(candidateName) ?? `agent-${idx}`; + if (!existingSlugs.has(candidateSlug)) return candidateName; + idx += 1; + } +} +function uniqueProjectName(baseName, existingProjectSlugs) { + const baseSlug = deriveProjectUrlKey(baseName, baseName); + if (!existingProjectSlugs.has(baseSlug)) return baseName; + let idx = 2; + while (true) { + const candidateName = `${baseName} ${idx}`; + const candidateSlug = deriveProjectUrlKey(candidateName, candidateName); + if (!existingProjectSlugs.has(candidateSlug)) return candidateName; + idx += 1; + } +} +function normalizeInclude(input) { + return { + company: input?.company ?? DEFAULT_INCLUDE.company, + agents: input?.agents ?? DEFAULT_INCLUDE.agents, + projects: input?.projects ?? DEFAULT_INCLUDE.projects, + issues: input?.issues ?? DEFAULT_INCLUDE.issues, + skills: input?.skills ?? DEFAULT_INCLUDE.skills + }; +} +function normalizePortablePath2(input) { + const normalized = input.replace(/\\/g, "/").replace(/^\.\/+/, ""); + const parts = []; + for (const segment of normalized.split("/")) { + if (!segment || segment === ".") continue; + if (segment === "..") { + if (parts.length > 0) parts.pop(); + continue; + } + parts.push(segment); + } + return parts.join("/"); +} +function resolvePortablePath(fromPath, targetPath) { + const baseDir = path40.posix.dirname(fromPath.replace(/\\/g, "/")); + return normalizePortablePath2(path40.posix.join(baseDir, targetPath.replace(/\\/g, "/"))); +} +function isPortableBinaryFile(value) { + return typeof value === "object" && value !== null && value.encoding === "base64" && typeof value.data === "string"; +} +function readPortableTextFile(files, filePath) { + const value = files[filePath]; + return typeof value === "string" ? value : null; +} +function inferContentTypeFromPath(filePath) { + const extension2 = path40.posix.extname(filePath).toLowerCase(); + switch (extension2) { + case ".gif": + return "image/gif"; + case ".jpeg": + case ".jpg": + return "image/jpeg"; + case ".png": + return "image/png"; + case ".svg": + return "image/svg+xml"; + case ".webp": + return "image/webp"; + default: + return null; + } +} +function resolveCompanyLogoExtension(contentType, originalFilename) { + const fromContentType = contentType ? COMPANY_LOGO_CONTENT_TYPE_EXTENSIONS[contentType.toLowerCase()] : null; + if (fromContentType) return fromContentType; + const extension2 = originalFilename ? path40.extname(originalFilename).toLowerCase() : ""; + return extension2 || ".png"; +} +function portableBinaryFileToBuffer(entry) { + return Buffer.from(entry.data, "base64"); +} +function portableFileToBuffer(entry, filePath) { + if (typeof entry === "string") { + return Buffer.from(entry, "utf8"); + } + if (isPortableBinaryFile(entry)) { + return portableBinaryFileToBuffer(entry); + } + throw unprocessable(`Unsupported file entry encoding for ${filePath}`); +} +function bufferToPortableBinaryFile(buffer2, contentType) { + return { + encoding: "base64", + data: buffer2.toString("base64"), + contentType + }; +} +async function streamToBuffer(stream) { + const chunks = []; + for await (const chunk of stream) { + chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)); + } + return Buffer.concat(chunks); +} +function normalizeFileMap(files, rootPath) { + const normalizedRoot = rootPath ? normalizePortablePath2(rootPath) : null; + const out = {}; + for (const [rawPath, content] of Object.entries(files)) { + let nextPath = normalizePortablePath2(rawPath); + if (normalizedRoot && nextPath === normalizedRoot) { + continue; + } + if (normalizedRoot && nextPath.startsWith(`${normalizedRoot}/`)) { + nextPath = nextPath.slice(normalizedRoot.length + 1); + } + if (!nextPath) continue; + out[nextPath] = content; + } + return out; +} +function pickTextFiles(files) { + const out = {}; + for (const [filePath, content] of Object.entries(files)) { + if (typeof content === "string") { + out[filePath] = content; + } + } + return out; +} +function collectSelectedExportSlugs(selectedFiles) { + const agents2 = /* @__PURE__ */ new Set(); + const projects2 = /* @__PURE__ */ new Set(); + const tasks = /* @__PURE__ */ new Set(); + for (const filePath of selectedFiles) { + const agentMatch = filePath.match(/^agents\/([^/]+)\//); + if (agentMatch) agents2.add(agentMatch[1]); + const projectMatch = filePath.match(/^projects\/([^/]+)\//); + if (projectMatch) projects2.add(projectMatch[1]); + const taskMatch = filePath.match(/^tasks\/([^/]+)\//); + if (taskMatch) tasks.add(taskMatch[1]); + } + return { agents: agents2, projects: projects2, tasks, routines: new Set(tasks) }; +} +function normalizePortableSlugList(value) { + if (!Array.isArray(value)) return []; + const seen = /* @__PURE__ */ new Set(); + const normalized = []; + for (const entry of value) { + if (typeof entry !== "string") continue; + const trimmed = entry.trim(); + if (!trimmed || seen.has(trimmed)) continue; + seen.add(trimmed); + normalized.push(trimmed); + } + return normalized; +} +function normalizePortableSidebarOrder(value) { + if (!isPlainRecord5(value)) return null; + const sidebar = { + agents: normalizePortableSlugList(value.agents), + projects: normalizePortableSlugList(value.projects) + }; + return sidebar.agents.length > 0 || sidebar.projects.length > 0 ? sidebar : null; +} +function sortAgentsBySidebarOrder(agents2) { + if (agents2.length === 0) return []; + const byId = new Map(agents2.map((agent) => [agent.id, agent])); + const childrenOf = /* @__PURE__ */ new Map(); + for (const agent of agents2) { + const parentId = agent.reportsTo && byId.has(agent.reportsTo) ? agent.reportsTo : null; + const siblings = childrenOf.get(parentId) ?? []; + siblings.push(agent); + childrenOf.set(parentId, siblings); + } + for (const siblings of childrenOf.values()) { + siblings.sort((left, right) => left.name.localeCompare(right.name)); + } + const sorted = []; + const queue = [...childrenOf.get(null) ?? []]; + while (queue.length > 0) { + const agent = queue.shift(); + if (!agent) continue; + sorted.push(agent); + const children = childrenOf.get(agent.id); + if (children) queue.push(...children); + } + return sorted; +} +function filterPortableExtensionYaml(yaml, selectedFiles) { + const selected = collectSelectedExportSlugs(selectedFiles); + const parsed = parseYamlFile(yaml); + for (const section of ["agents", "projects", "tasks", "routines"]) { + const sectionValue = parsed[section]; + if (!isPlainRecord5(sectionValue)) continue; + const sectionSlugs = selected[section]; + const filteredEntries = Object.fromEntries( + Object.entries(sectionValue).filter(([slug]) => sectionSlugs.has(slug)) + ); + if (Object.keys(filteredEntries).length > 0) { + parsed[section] = filteredEntries; + } else { + delete parsed[section]; + } + } + const companySection = parsed.company; + if (isPlainRecord5(companySection)) { + const logoPath = asString14(companySection.logoPath) ?? asString14(companySection.logo); + if (logoPath && !selectedFiles.has(logoPath)) { + delete companySection.logoPath; + delete companySection.logo; + } + } + const sidebarOrder = normalizePortableSidebarOrder(parsed.sidebar); + if (sidebarOrder) { + const filteredSidebar = stripEmptyValues({ + agents: sidebarOrder.agents.filter((slug) => selected.agents.has(slug)), + projects: sidebarOrder.projects.filter((slug) => selected.projects.has(slug)) + }); + if (isPlainRecord5(filteredSidebar)) { + parsed.sidebar = filteredSidebar; + } else { + delete parsed.sidebar; + } + } else { + delete parsed.sidebar; + } + return buildYamlFile(parsed, { preserveEmptyStrings: true }); +} +function filterExportFiles(files, selectedFilesInput, taskcoreExtensionPath) { + if (!selectedFilesInput || selectedFilesInput.length === 0) { + return files; + } + const selectedFiles = new Set( + selectedFilesInput.map((entry) => normalizePortablePath2(entry)).filter((entry) => entry.length > 0) + ); + const filtered = {}; + for (const [filePath, content] of Object.entries(files)) { + if (!selectedFiles.has(filePath)) continue; + filtered[filePath] = content; + } + const extensionEntry = filtered[taskcoreExtensionPath]; + if (selectedFiles.has(taskcoreExtensionPath) && typeof extensionEntry === "string") { + filtered[taskcoreExtensionPath] = filterPortableExtensionYaml(extensionEntry, selectedFiles); + } + return filtered; +} +function findTaskcoreExtensionPath(files) { + if (typeof files[".taskcore.yaml"] === "string") return ".taskcore.yaml"; + if (typeof files[".taskcore.yml"] === "string") return ".taskcore.yml"; + return Object.keys(files).find((entry) => entry.endsWith("/.taskcore.yaml") || entry.endsWith("/.taskcore.yml")) ?? null; +} +function ensureMarkdownPath(pathValue) { + const normalized = pathValue.replace(/\\/g, "/"); + if (!normalized.endsWith(".md")) { + throw unprocessable(`Manifest file path must end in .md: ${pathValue}`); + } + return normalized; +} +function normalizePortableConfig(value) { + if (typeof value !== "object" || value === null || Array.isArray(value)) return {}; + const input = value; + const next = {}; + for (const [key, entry] of Object.entries(input)) { + if (key === "cwd" || key === "instructionsFilePath" || key === "instructionsBundleMode" || key === "instructionsRootPath" || key === "instructionsEntryFile" || key === "promptTemplate" || key === "bootstrapPromptTemplate" || // deprecated — kept for backward compat + key === "taskcoreSkillSync") continue; + if (key === "env") continue; + next[key] = entry; + } + return next; +} +function isAbsoluteCommand(value) { + return path40.isAbsolute(value) || /^[A-Za-z]:[\\/]/.test(value); +} +function extractPortableEnvInputs(agentSlug, envValue, warnings) { + return extractPortableScopedEnvInputs( + { + label: `agent ${agentSlug}`, + warningPrefix: `Agent ${agentSlug}`, + agentSlug, + projectSlug: null + }, + envValue, + warnings + ); +} +function extractPortableProjectEnvInputs(projectSlug, envValue, warnings) { + return extractPortableScopedEnvInputs( + { + label: `project ${projectSlug}`, + warningPrefix: `Project ${projectSlug}`, + agentSlug: null, + projectSlug + }, + envValue, + warnings + ); +} +function jsonEqual2(left, right) { + return JSON.stringify(left) === JSON.stringify(right); +} +function isPathDefault(pathSegments, value, rules) { + return rules.some((rule) => jsonEqual2(rule.path, pathSegments) && jsonEqual2(rule.value, value)); +} +function pruneDefaultLikeValue(value, opts) { + const pathSegments = opts.path ?? []; + if (opts.defaultRules && isPathDefault(pathSegments, value, opts.defaultRules)) { + return void 0; + } + if (Array.isArray(value)) { + return value.map((entry) => pruneDefaultLikeValue(entry, { ...opts, path: pathSegments })); + } + if (isPlainRecord5(value)) { + const out = {}; + for (const [key, entry] of Object.entries(value)) { + const next = pruneDefaultLikeValue(entry, { + ...opts, + path: [...pathSegments, key] + }); + if (next === void 0) continue; + out[key] = next; + } + return out; + } + if (value === void 0) return void 0; + if (opts.dropFalseBooleans && value === false) return void 0; + return value; +} +function renderYamlScalar(value) { + if (value === null) return "null"; + if (typeof value === "boolean" || typeof value === "number") return String(value); + if (typeof value === "string") return JSON.stringify(value); + return JSON.stringify(value); +} +function isEmptyObject(value) { + return isPlainRecord5(value) && Object.keys(value).length === 0; +} +function isEmptyArray(value) { + return Array.isArray(value) && value.length === 0; +} +function stripEmptyValues(value, opts) { + if (Array.isArray(value)) { + const next = value.map((entry) => stripEmptyValues(entry, opts)).filter((entry) => entry !== void 0); + return next.length > 0 ? next : void 0; + } + if (isPlainRecord5(value)) { + const next = {}; + for (const [key, entry] of Object.entries(value)) { + const cleaned = stripEmptyValues(entry, opts); + if (cleaned === void 0) continue; + next[key] = cleaned; + } + return Object.keys(next).length > 0 ? next : void 0; + } + if (value === void 0 || value === null || !opts?.preserveEmptyStrings && value === "" || isEmptyArray(value) || isEmptyObject(value)) { + return void 0; + } + return value; +} +var YAML_KEY_PRIORITY = [ + "name", + "description", + "title", + "schema", + "kind", + "slug", + "reportsTo", + "skills", + "owner", + "assignee", + "project", + "schedule", + "version", + "license", + "authors", + "homepage", + "tags", + "includes", + "requirements", + "role", + "icon", + "capabilities", + "brandColor", + "logoPath", + "adapter", + "runtime", + "permissions", + "budgetMonthlyCents", + "metadata" +]; +var YAML_KEY_PRIORITY_INDEX = new Map( + YAML_KEY_PRIORITY.map((key, index2) => [key, index2]) +); +function compareYamlKeys(left, right) { + const leftPriority = YAML_KEY_PRIORITY_INDEX.get(left); + const rightPriority = YAML_KEY_PRIORITY_INDEX.get(right); + if (leftPriority !== void 0 || rightPriority !== void 0) { + if (leftPriority === void 0) return 1; + if (rightPriority === void 0) return -1; + if (leftPriority !== rightPriority) return leftPriority - rightPriority; + } + return left.localeCompare(right); +} +function orderedYamlEntries(value) { + return Object.entries(value).sort(([leftKey], [rightKey]) => compareYamlKeys(leftKey, rightKey)); +} +function renderYamlBlock(value, indentLevel) { + const indent = " ".repeat(indentLevel); + if (Array.isArray(value)) { + if (value.length === 0) return [`${indent}[]`]; + const lines = []; + for (const entry of value) { + const scalar = entry === null || typeof entry === "string" || typeof entry === "boolean" || typeof entry === "number" || Array.isArray(entry) && entry.length === 0 || isEmptyObject(entry); + if (scalar) { + lines.push(`${indent}- ${renderYamlScalar(entry)}`); + continue; + } + lines.push(`${indent}-`); + lines.push(...renderYamlBlock(entry, indentLevel + 1)); + } + return lines; + } + if (isPlainRecord5(value)) { + const entries2 = orderedYamlEntries(value); + if (entries2.length === 0) return [`${indent}{}`]; + const lines = []; + for (const [key, entry] of entries2) { + const scalar = entry === null || typeof entry === "string" || typeof entry === "boolean" || typeof entry === "number" || Array.isArray(entry) && entry.length === 0 || isEmptyObject(entry); + if (scalar) { + lines.push(`${indent}${key}: ${renderYamlScalar(entry)}`); + continue; + } + lines.push(`${indent}${key}:`); + lines.push(...renderYamlBlock(entry, indentLevel + 1)); + } + return lines; + } + return [`${indent}${renderYamlScalar(value)}`]; +} +function renderFrontmatter(frontmatter) { + const lines = ["---"]; + for (const [key, value] of orderedYamlEntries(frontmatter)) { + if (value === null || value === void 0) continue; + const scalar = typeof value === "string" || typeof value === "boolean" || typeof value === "number" || Array.isArray(value) && value.length === 0 || isEmptyObject(value); + if (scalar) { + lines.push(`${key}: ${renderYamlScalar(value)}`); + continue; + } + lines.push(`${key}:`); + lines.push(...renderYamlBlock(value, 1)); + } + lines.push("---"); + return `${lines.join("\n")} +`; +} +function buildMarkdown(frontmatter, body) { + const cleanBody = body.replace(/\r\n/g, "\n").trim(); + if (!cleanBody) { + return `${renderFrontmatter(frontmatter)} +`; + } + return `${renderFrontmatter(frontmatter)} +${cleanBody} +`; +} +function normalizeSelectedFiles(selectedFiles) { + if (!selectedFiles) return null; + return new Set( + selectedFiles.map((entry) => normalizePortablePath2(entry)).filter((entry) => entry.length > 0) + ); +} +function filterCompanyMarkdownIncludes(companyPath, markdown, selectedFiles) { + const parsed = parseFrontmatterMarkdown2(markdown); + const includeEntries = readIncludeEntries(parsed.frontmatter); + const filteredIncludes = includeEntries.filter( + (entry) => selectedFiles.has(resolvePortablePath(companyPath, entry.path)) + ); + const nextFrontmatter = { ...parsed.frontmatter }; + if (filteredIncludes.length > 0) { + nextFrontmatter.includes = filteredIncludes.map((entry) => entry.path); + } else { + delete nextFrontmatter.includes; + } + return buildMarkdown(nextFrontmatter, parsed.body); +} +function applySelectedFilesToSource(source, selectedFiles) { + const normalizedSelection = normalizeSelectedFiles(selectedFiles); + if (!normalizedSelection) return source; + const companyPath = source.manifest.company ? ensureMarkdownPath(source.manifest.company.path) : Object.keys(source.files).find((entry) => entry.endsWith("/COMPANY.md") || entry === "COMPANY.md") ?? null; + if (!companyPath) { + throw unprocessable("Company package is missing COMPANY.md"); + } + const companyMarkdown = source.files[companyPath]; + if (typeof companyMarkdown !== "string") { + throw unprocessable("Company package is missing COMPANY.md"); + } + const effectiveFiles = {}; + for (const [filePath, content] of Object.entries(source.files)) { + const normalizedPath = normalizePortablePath2(filePath); + if (!normalizedSelection.has(normalizedPath)) continue; + effectiveFiles[normalizedPath] = content; + } + effectiveFiles[companyPath] = filterCompanyMarkdownIncludes( + companyPath, + companyMarkdown, + normalizedSelection + ); + const filtered = buildManifestFromPackageFiles(effectiveFiles, { + sourceLabel: source.manifest.source + }); + if (!normalizedSelection.has(companyPath)) { + filtered.manifest.company = null; + } + filtered.manifest.includes = { + company: filtered.manifest.company !== null, + agents: filtered.manifest.agents.length > 0, + projects: filtered.manifest.projects.length > 0, + issues: filtered.manifest.issues.length > 0, + skills: filtered.manifest.skills.length > 0 + }; + return filtered; +} +async function resolveBundledSkillsCommit() { + if (!bundledSkillsCommitPromise) { + bundledSkillsCommitPromise = execFileAsync5("git", ["rev-parse", "HEAD"], { + cwd: process.cwd(), + encoding: "utf8" + }).then(({ stdout }) => stdout.trim() || null).catch(() => null); + } + return bundledSkillsCommitPromise; +} +async function buildSkillSourceEntry(skill) { + const metadata = isPlainRecord5(skill.metadata) ? skill.metadata : null; + if (asString14(metadata?.sourceKind) === "taskcore_bundled") { + const commit = await resolveBundledSkillsCommit(); + return { + kind: "github-dir", + repo: "khulnasoft/taskcore", + path: `skills/${skill.slug}`, + commit, + trackingRef: "master", + url: `https://github.com/khulnasoft/taskcore/tree/master/skills/${skill.slug}` + }; + } + if (skill.sourceType === "github" || skill.sourceType === "skills_sh") { + const owner = asString14(metadata?.owner); + const repo = asString14(metadata?.repo); + const repoSkillDir = asString14(metadata?.repoSkillDir); + if (!owner || !repo || !repoSkillDir) return null; + return { + kind: "github-dir", + repo: `${owner}/${repo}`, + path: repoSkillDir, + commit: skill.sourceRef ?? null, + trackingRef: asString14(metadata?.trackingRef), + url: skill.sourceLocator + }; + } + if (skill.sourceType === "url" && skill.sourceLocator) { + return { + kind: "url", + url: skill.sourceLocator + }; + } + return null; +} +function shouldReferenceSkillOnExport(skill, expandReferencedSkills) { + if (expandReferencedSkills) return false; + const metadata = isPlainRecord5(skill.metadata) ? skill.metadata : null; + if (asString14(metadata?.sourceKind) === "taskcore_bundled") return true; + return skill.sourceType === "github" || skill.sourceType === "skills_sh" || skill.sourceType === "url"; +} +async function buildReferencedSkillMarkdown(skill) { + const sourceEntry = await buildSkillSourceEntry(skill); + const frontmatter = { + key: skill.key, + slug: skill.slug, + name: skill.name, + description: skill.description ?? null + }; + if (sourceEntry) { + frontmatter.metadata = { + sources: [sourceEntry] + }; + } + return buildMarkdown(frontmatter, ""); +} +async function withSkillSourceMetadata(skill, markdown) { + const sourceEntry = await buildSkillSourceEntry(skill); + const parsed = parseFrontmatterMarkdown2(markdown); + const metadata = isPlainRecord5(parsed.frontmatter.metadata) ? { ...parsed.frontmatter.metadata } : {}; + const existingSources = Array.isArray(metadata.sources) ? metadata.sources.filter((entry) => isPlainRecord5(entry)) : []; + if (sourceEntry) { + metadata.sources = [...existingSources, sourceEntry]; + } + metadata.skillKey = skill.key; + metadata.taskcoreSkillKey = skill.key; + metadata.taskcore = { + ...isPlainRecord5(metadata.taskcore) ? metadata.taskcore : {}, + skillKey: skill.key, + slug: skill.slug + }; + const frontmatter = { + ...parsed.frontmatter, + key: skill.key, + slug: skill.slug, + metadata + }; + return buildMarkdown(frontmatter, parsed.body); +} +function parseYamlScalar2(rawValue) { + const trimmed = rawValue.trim(); + if (trimmed === "") return ""; + if (trimmed === "null" || trimmed === "~") return null; + if (trimmed === "true") return true; + if (trimmed === "false") return false; + if (trimmed === "[]") return []; + if (trimmed === "{}") return {}; + if (/^-?\d+(\.\d+)?$/.test(trimmed)) return Number(trimmed); + if (trimmed.startsWith('"') || trimmed.startsWith("[") || trimmed.startsWith("{")) { + try { + return JSON.parse(trimmed); + } catch { + return trimmed; + } + } + return trimmed; +} +function prepareYamlLines2(raw) { + return raw.split("\n").map((line3) => ({ + indent: line3.match(/^ */)?.[0].length ?? 0, + content: line3.trim() + })).filter((line3) => line3.content.length > 0 && !line3.content.startsWith("#")); +} +function parseYamlBlock2(lines, startIndex, indentLevel) { + let index2 = startIndex; + while (index2 < lines.length && lines[index2].content.length === 0) { + index2 += 1; + } + if (index2 >= lines.length || lines[index2].indent < indentLevel) { + return { value: {}, nextIndex: index2 }; + } + const isArray = lines[index2].indent === indentLevel && lines[index2].content.startsWith("-"); + if (isArray) { + const values2 = []; + while (index2 < lines.length) { + const line3 = lines[index2]; + if (line3.indent < indentLevel) break; + if (line3.indent !== indentLevel || !line3.content.startsWith("-")) break; + const remainder = line3.content.slice(1).trim(); + index2 += 1; + if (!remainder) { + const nested = parseYamlBlock2(lines, index2, indentLevel + 2); + values2.push(nested.value); + index2 = nested.nextIndex; + continue; + } + const inlineObjectSeparator = remainder.indexOf(":"); + if (inlineObjectSeparator > 0 && !remainder.startsWith('"') && !remainder.startsWith("{") && !remainder.startsWith("[")) { + const key = remainder.slice(0, inlineObjectSeparator).trim(); + const rawValue = remainder.slice(inlineObjectSeparator + 1).trim(); + const nextObject = { + [key]: parseYamlScalar2(rawValue) + }; + if (index2 < lines.length && lines[index2].indent > indentLevel) { + const nested = parseYamlBlock2(lines, index2, indentLevel + 2); + if (isPlainRecord5(nested.value)) { + Object.assign(nextObject, nested.value); + } + index2 = nested.nextIndex; + } + values2.push(nextObject); + continue; + } + values2.push(parseYamlScalar2(remainder)); + } + return { value: values2, nextIndex: index2 }; + } + const record2 = {}; + while (index2 < lines.length) { + const line3 = lines[index2]; + if (line3.indent < indentLevel) break; + if (line3.indent !== indentLevel) { + index2 += 1; + continue; + } + const separatorIndex = line3.content.indexOf(":"); + if (separatorIndex <= 0) { + index2 += 1; + continue; + } + const key = line3.content.slice(0, separatorIndex).trim(); + const remainder = line3.content.slice(separatorIndex + 1).trim(); + index2 += 1; + if (!remainder) { + const nested = parseYamlBlock2(lines, index2, indentLevel + 2); + record2[key] = nested.value; + index2 = nested.nextIndex; + continue; + } + record2[key] = parseYamlScalar2(remainder); + } + return { value: record2, nextIndex: index2 }; +} +function parseYamlFrontmatter2(raw) { + const prepared = prepareYamlLines2(raw); + if (prepared.length === 0) return {}; + const parsed = parseYamlBlock2(prepared, 0, prepared[0].indent); + return isPlainRecord5(parsed.value) ? parsed.value : {}; +} +function parseYamlFile(raw) { + return parseYamlFrontmatter2(raw); +} +function buildYamlFile(value, opts) { + const cleaned = stripEmptyValues(value, opts); + if (!isPlainRecord5(cleaned)) return "{}\n"; + return renderYamlBlock(cleaned, 0).join("\n") + "\n"; +} +function parseFrontmatterMarkdown2(raw) { + const normalized = raw.replace(/\r\n/g, "\n"); + if (!normalized.startsWith("---\n")) { + return { frontmatter: {}, body: normalized.trim() }; + } + const closing = normalized.indexOf("\n---\n", 4); + if (closing < 0) { + return { frontmatter: {}, body: normalized.trim() }; + } + const frontmatterRaw = normalized.slice(4, closing).trim(); + const body = normalized.slice(closing + 5).trim(); + return { + frontmatter: parseYamlFrontmatter2(frontmatterRaw), + body + }; +} +async function fetchText2(url2) { + const response = await ghFetch(url2); + if (!response.ok) { + throw unprocessable(`Failed to fetch ${url2}: ${response.status}`); + } + return response.text(); +} +async function fetchOptionalText(url2) { + const response = await ghFetch(url2); + if (response.status === 404) return null; + if (!response.ok) { + throw unprocessable(`Failed to fetch ${url2}: ${response.status}`); + } + return response.text(); +} +async function fetchBinary(url2) { + const response = await ghFetch(url2); + if (!response.ok) { + throw unprocessable(`Failed to fetch ${url2}: ${response.status}`); + } + return Buffer.from(await response.arrayBuffer()); +} +async function fetchJson2(url2) { + const response = await ghFetch(url2, { + headers: { + accept: "application/vnd.github+json" + } + }); + if (!response.ok) { + throw unprocessable(`Failed to fetch ${url2}: ${response.status}`); + } + return response.json(); +} +function dedupeEnvInputs(values2) { + const seen = /* @__PURE__ */ new Set(); + const out = []; + for (const value of values2) { + const key = `${value.agentSlug ?? ""}:${value.projectSlug ?? ""}:${value.key.toUpperCase()}`; + if (seen.has(key)) continue; + seen.add(key); + out.push(value); + } + return out; +} +function buildEnvInputMap(inputs) { + const env2 = {}; + for (const input of inputs) { + const entry = { + kind: input.kind, + requirement: input.requirement + }; + if (input.defaultValue !== null) entry.default = input.defaultValue; + if (input.description) entry.description = input.description; + if (input.portability === "system_dependent") entry.portability = "system_dependent"; + env2[input.key] = entry; + } + return env2; +} +function readCompanyApprovalDefault(_frontmatter) { + return true; +} +function readIncludeEntries(frontmatter) { + const includes = frontmatter.includes; + if (!Array.isArray(includes)) return []; + return includes.flatMap((entry) => { + if (typeof entry === "string") { + return [{ path: entry }]; + } + if (isPlainRecord5(entry)) { + const pathValue = asString14(entry.path); + return pathValue ? [{ path: pathValue }] : []; + } + return []; + }); +} +function readAgentEnvInputs(extension2, agentSlug) { + const inputs = isPlainRecord5(extension2.inputs) ? extension2.inputs : null; + const env2 = inputs && isPlainRecord5(inputs.env) ? inputs.env : null; + if (!env2) return []; + return Object.entries(env2).flatMap(([key, value]) => { + if (!isPlainRecord5(value)) return []; + const record2 = value; + return [{ + key, + description: asString14(record2.description) ?? null, + agentSlug, + projectSlug: null, + kind: record2.kind === "plain" ? "plain" : "secret", + requirement: record2.requirement === "required" ? "required" : "optional", + defaultValue: typeof record2.default === "string" ? record2.default : null, + portability: record2.portability === "system_dependent" ? "system_dependent" : "portable" + }]; + }); +} +function readProjectEnvInputs(extension2, projectSlug) { + const inputs = isPlainRecord5(extension2.inputs) ? extension2.inputs : null; + const env2 = inputs && isPlainRecord5(inputs.env) ? inputs.env : null; + if (!env2) return []; + return Object.entries(env2).flatMap(([key, value]) => { + if (!isPlainRecord5(value)) return []; + const record2 = value; + return [{ + key, + description: asString14(record2.description) ?? null, + agentSlug: null, + projectSlug, + kind: record2.kind === "plain" ? "plain" : "secret", + requirement: record2.requirement === "required" ? "required" : "optional", + defaultValue: typeof record2.default === "string" ? record2.default : null, + portability: record2.portability === "system_dependent" ? "system_dependent" : "portable" + }]; + }); +} +function readAgentSkillRefs(frontmatter) { + const skills = frontmatter.skills; + if (!Array.isArray(skills)) return []; + return Array.from(new Set( + skills.filter((entry) => typeof entry === "string").map((entry) => normalizeSkillKey2(entry) ?? entry.trim()).filter(Boolean) + )); +} +function buildManifestFromPackageFiles(files, opts) { + const normalizedFiles = normalizeFileMap(files); + const companyPath = typeof normalizedFiles["COMPANY.md"] === "string" ? normalizedFiles["COMPANY.md"] : void 0; + const resolvedCompanyPath = companyPath !== void 0 ? "COMPANY.md" : Object.keys(normalizedFiles).find((entry) => entry.endsWith("/COMPANY.md") || entry === "COMPANY.md"); + if (!resolvedCompanyPath) { + throw unprocessable("Company package is missing COMPANY.md"); + } + const companyMarkdown = readPortableTextFile(normalizedFiles, resolvedCompanyPath); + if (typeof companyMarkdown !== "string") { + throw unprocessable(`Company package file is not readable as text: ${resolvedCompanyPath}`); + } + const companyDoc = parseFrontmatterMarkdown2(companyMarkdown); + const companyFrontmatter = companyDoc.frontmatter; + const taskcoreExtensionPath = findTaskcoreExtensionPath(normalizedFiles); + const taskcoreExtension = taskcoreExtensionPath ? parseYamlFile(readPortableTextFile(normalizedFiles, taskcoreExtensionPath) ?? "") : {}; + const taskcoreCompany = isPlainRecord5(taskcoreExtension.company) ? taskcoreExtension.company : {}; + const taskcoreSidebar = normalizePortableSidebarOrder(taskcoreExtension.sidebar); + const taskcoreAgents = isPlainRecord5(taskcoreExtension.agents) ? taskcoreExtension.agents : {}; + const taskcoreProjects = isPlainRecord5(taskcoreExtension.projects) ? taskcoreExtension.projects : {}; + const taskcoreTasks = isPlainRecord5(taskcoreExtension.tasks) ? taskcoreExtension.tasks : {}; + const taskcoreRoutines = isPlainRecord5(taskcoreExtension.routines) ? taskcoreExtension.routines : {}; + const companyName = asString14(companyFrontmatter.name) ?? opts?.sourceLabel?.companyName ?? "Imported Company"; + const companySlug = asString14(companyFrontmatter.slug) ?? normalizeAgentUrlKey(companyName) ?? "company"; + const includeEntries = readIncludeEntries(companyFrontmatter); + const referencedAgentPaths = includeEntries.map((entry) => resolvePortablePath(resolvedCompanyPath, entry.path)).filter((entry) => entry.endsWith("/AGENTS.md") || entry === "AGENTS.md"); + const referencedProjectPaths = includeEntries.map((entry) => resolvePortablePath(resolvedCompanyPath, entry.path)).filter((entry) => entry.endsWith("/PROJECT.md") || entry === "PROJECT.md"); + const referencedTaskPaths = includeEntries.map((entry) => resolvePortablePath(resolvedCompanyPath, entry.path)).filter((entry) => entry.endsWith("/TASK.md") || entry === "TASK.md"); + const referencedSkillPaths = includeEntries.map((entry) => resolvePortablePath(resolvedCompanyPath, entry.path)).filter((entry) => entry.endsWith("/SKILL.md") || entry === "SKILL.md"); + const discoveredAgentPaths = Object.keys(normalizedFiles).filter( + (entry) => entry.endsWith("/AGENTS.md") || entry === "AGENTS.md" + ); + const discoveredProjectPaths = Object.keys(normalizedFiles).filter( + (entry) => entry.endsWith("/PROJECT.md") || entry === "PROJECT.md" + ); + const discoveredTaskPaths = Object.keys(normalizedFiles).filter( + (entry) => entry.endsWith("/TASK.md") || entry === "TASK.md" + ); + const discoveredSkillPaths = Object.keys(normalizedFiles).filter( + (entry) => entry.endsWith("/SKILL.md") || entry === "SKILL.md" + ); + const agentPaths = Array.from(/* @__PURE__ */ new Set([...referencedAgentPaths, ...discoveredAgentPaths])).sort(); + const projectPaths = Array.from(/* @__PURE__ */ new Set([...referencedProjectPaths, ...discoveredProjectPaths])).sort(); + const taskPaths = Array.from(/* @__PURE__ */ new Set([...referencedTaskPaths, ...discoveredTaskPaths])).sort(); + const skillPaths = Array.from(/* @__PURE__ */ new Set([...referencedSkillPaths, ...discoveredSkillPaths])).sort(); + const manifest = { + schemaVersion: 5, + generatedAt: (/* @__PURE__ */ new Date()).toISOString(), + source: opts?.sourceLabel ?? null, + includes: { + company: true, + agents: true, + projects: projectPaths.length > 0, + issues: taskPaths.length > 0, + skills: skillPaths.length > 0 + }, + company: { + path: resolvedCompanyPath, + name: companyName, + description: asString14(companyFrontmatter.description), + brandColor: asString14(taskcoreCompany.brandColor), + logoPath: asString14(taskcoreCompany.logoPath) ?? asString14(taskcoreCompany.logo), + requireBoardApprovalForNewAgents: typeof taskcoreCompany.requireBoardApprovalForNewAgents === "boolean" ? taskcoreCompany.requireBoardApprovalForNewAgents : readCompanyApprovalDefault(companyFrontmatter), + feedbackDataSharingEnabled: typeof taskcoreCompany.feedbackDataSharingEnabled === "boolean" ? taskcoreCompany.feedbackDataSharingEnabled : false, + feedbackDataSharingConsentAt: typeof taskcoreCompany.feedbackDataSharingConsentAt === "string" ? taskcoreCompany.feedbackDataSharingConsentAt : null, + feedbackDataSharingConsentByUserId: asString14(taskcoreCompany.feedbackDataSharingConsentByUserId), + feedbackDataSharingTermsVersion: asString14(taskcoreCompany.feedbackDataSharingTermsVersion) + }, + sidebar: taskcoreSidebar, + agents: [], + skills: [], + projects: [], + issues: [], + envInputs: [] + }; + const warnings = []; + if (manifest.company?.logoPath && !normalizedFiles[manifest.company.logoPath]) { + warnings.push(`Referenced company logo file is missing from package: ${manifest.company.logoPath}`); + } + for (const agentPath of agentPaths) { + const markdownRaw = readPortableTextFile(normalizedFiles, agentPath); + if (typeof markdownRaw !== "string") { + warnings.push(`Referenced agent file is missing from package: ${agentPath}`); + continue; + } + const agentDoc = parseFrontmatterMarkdown2(markdownRaw); + const frontmatter = agentDoc.frontmatter; + const fallbackSlug = normalizeAgentUrlKey(path40.posix.basename(path40.posix.dirname(agentPath))) ?? "agent"; + const slug = asString14(frontmatter.slug) ?? fallbackSlug; + const extension2 = isPlainRecord5(taskcoreAgents[slug]) ? taskcoreAgents[slug] : {}; + const extensionAdapter = isPlainRecord5(extension2.adapter) ? extension2.adapter : null; + const extensionRuntime = isPlainRecord5(extension2.runtime) ? extension2.runtime : null; + const extensionPermissions = isPlainRecord5(extension2.permissions) ? extension2.permissions : null; + const extensionMetadata = isPlainRecord5(extension2.metadata) ? extension2.metadata : null; + const adapterConfig = isPlainRecord5(extensionAdapter?.config) ? extensionAdapter.config : {}; + const runtimeConfig = extensionRuntime ?? {}; + const title = asString14(frontmatter.title); + manifest.agents.push({ + slug, + name: asString14(frontmatter.name) ?? title ?? slug, + path: agentPath, + skills: readAgentSkillRefs(frontmatter), + role: asString14(extension2.role) ?? asString14(frontmatter.role) ?? "agent", + title, + icon: asString14(extension2.icon), + capabilities: asString14(extension2.capabilities), + reportsToSlug: asString14(frontmatter.reportsTo) ?? asString14(extension2.reportsTo), + adapterType: asString14(extensionAdapter?.type) ?? "process", + adapterConfig, + runtimeConfig, + permissions: extensionPermissions ?? {}, + budgetMonthlyCents: typeof extension2.budgetMonthlyCents === "number" && Number.isFinite(extension2.budgetMonthlyCents) ? Math.max(0, Math.floor(extension2.budgetMonthlyCents)) : 0, + metadata: extensionMetadata + }); + manifest.envInputs.push(...readAgentEnvInputs(extension2, slug)); + if (frontmatter.kind && frontmatter.kind !== "agent") { + warnings.push(`Agent markdown ${agentPath} does not declare kind: agent in frontmatter.`); + } + } + for (const skillPath of skillPaths) { + const markdownRaw = readPortableTextFile(normalizedFiles, skillPath); + if (typeof markdownRaw !== "string") { + warnings.push(`Referenced skill file is missing from package: ${skillPath}`); + continue; + } + const skillDoc = parseFrontmatterMarkdown2(markdownRaw); + const frontmatter = skillDoc.frontmatter; + const skillDir = path40.posix.dirname(skillPath); + const fallbackSlug = normalizeAgentUrlKey(path40.posix.basename(skillDir)) ?? "skill"; + const slug = asString14(frontmatter.slug) ?? normalizeAgentUrlKey(asString14(frontmatter.name) ?? "") ?? fallbackSlug; + const inventory = Object.keys(normalizedFiles).filter((entry) => entry === skillPath || entry.startsWith(`${skillDir}/`)).map((entry) => ({ + path: entry === skillPath ? "SKILL.md" : entry.slice(skillDir.length + 1), + kind: entry === skillPath ? "skill" : entry.startsWith(`${skillDir}/references/`) ? "reference" : entry.startsWith(`${skillDir}/scripts/`) ? "script" : entry.startsWith(`${skillDir}/assets/`) ? "asset" : entry.endsWith(".md") ? "markdown" : "other" + })); + const metadata = isPlainRecord5(frontmatter.metadata) ? frontmatter.metadata : null; + const sources = metadata && Array.isArray(metadata.sources) ? metadata.sources : []; + const primarySource = sources.find((entry) => isPlainRecord5(entry)); + const sourceKind = asString14(primarySource?.kind); + let sourceType = "catalog"; + let sourceLocator = null; + let sourceRef = null; + let normalizedMetadata = null; + if (sourceKind === "github-dir" || sourceKind === "github-file") { + const repo = asString14(primarySource?.repo); + const repoPath = asString14(primarySource?.path); + const commit = asString14(primarySource?.commit); + const trackingRef = asString14(primarySource?.trackingRef); + const sourceHostname = asString14(primarySource?.hostname) || "github.com"; + const [owner, repoName] = (repo ?? "").split("/"); + sourceType = "github"; + sourceLocator = asString14(primarySource?.url) ?? (repo ? `https://${sourceHostname}/${repo}${repoPath ? `/tree/${trackingRef ?? commit ?? "main"}/${repoPath}` : ""}` : null); + sourceRef = commit; + normalizedMetadata = owner && repoName ? { + sourceKind: "github", + ...sourceHostname !== "github.com" ? { hostname: sourceHostname } : {}, + owner, + repo: repoName, + ref: commit, + trackingRef, + repoSkillDir: repoPath ?? `skills/${slug}` + } : null; + } else if (sourceKind === "url") { + sourceType = "url"; + sourceLocator = asString14(primarySource?.url) ?? asString14(primarySource?.rawUrl); + normalizedMetadata = { + sourceKind: "url" + }; + } else if (metadata) { + normalizedMetadata = { + sourceKind: "catalog" + }; + } + const key = deriveManifestSkillKey(frontmatter, slug, normalizedMetadata, sourceType, sourceLocator); + manifest.skills.push({ + key, + slug, + name: asString14(frontmatter.name) ?? slug, + path: skillPath, + description: asString14(frontmatter.description), + sourceType, + sourceLocator, + sourceRef, + trustLevel: null, + compatibility: "compatible", + metadata: normalizedMetadata, + fileInventory: inventory + }); + } + for (const projectPath of projectPaths) { + const markdownRaw = readPortableTextFile(normalizedFiles, projectPath); + if (typeof markdownRaw !== "string") { + warnings.push(`Referenced project file is missing from package: ${projectPath}`); + continue; + } + const projectDoc = parseFrontmatterMarkdown2(markdownRaw); + const frontmatter = projectDoc.frontmatter; + const fallbackSlug = deriveProjectUrlKey( + asString14(frontmatter.name) ?? path40.posix.basename(path40.posix.dirname(projectPath)) ?? "project", + projectPath + ); + const slug = asString14(frontmatter.slug) ?? fallbackSlug; + const extension2 = isPlainRecord5(taskcoreProjects[slug]) ? taskcoreProjects[slug] : {}; + const workspaceExtensions = isPlainRecord5(extension2.workspaces) ? extension2.workspaces : {}; + const workspaces = Object.entries(workspaceExtensions).map(([workspaceKey, entry]) => normalizePortableProjectWorkspaceExtension(workspaceKey, entry)).filter((entry) => entry !== null); + manifest.projects.push({ + slug, + name: asString14(frontmatter.name) ?? slug, + path: projectPath, + description: asString14(frontmatter.description), + ownerAgentSlug: asString14(frontmatter.owner), + leadAgentSlug: asString14(extension2.leadAgentSlug), + targetDate: asString14(extension2.targetDate), + color: asString14(extension2.color), + status: asString14(extension2.status), + env: normalizePortableProjectEnv(extension2.env), + executionWorkspacePolicy: isPlainRecord5(extension2.executionWorkspacePolicy) ? extension2.executionWorkspacePolicy : null, + workspaces, + metadata: isPlainRecord5(extension2.metadata) ? extension2.metadata : null + }); + manifest.envInputs.push(...readProjectEnvInputs(extension2, slug)); + if (frontmatter.kind && frontmatter.kind !== "project") { + warnings.push(`Project markdown ${projectPath} does not declare kind: project in frontmatter.`); + } + } + for (const taskPath of taskPaths) { + const markdownRaw = readPortableTextFile(normalizedFiles, taskPath); + if (typeof markdownRaw !== "string") { + warnings.push(`Referenced task file is missing from package: ${taskPath}`); + continue; + } + const taskDoc = parseFrontmatterMarkdown2(markdownRaw); + const frontmatter = taskDoc.frontmatter; + const fallbackSlug = normalizeAgentUrlKey(path40.posix.basename(path40.posix.dirname(taskPath))) ?? "task"; + const slug = asString14(frontmatter.slug) ?? fallbackSlug; + const extension2 = isPlainRecord5(taskcoreTasks[slug]) ? taskcoreTasks[slug] : {}; + const routineExtension = normalizeRoutineExtension(taskcoreRoutines[slug]); + const routineExtensionRaw = isPlainRecord5(taskcoreRoutines[slug]) ? taskcoreRoutines[slug] : {}; + const schedule = isPlainRecord5(frontmatter.schedule) ? frontmatter.schedule : null; + const legacyRecurrence = schedule && isPlainRecord5(schedule.recurrence) ? schedule.recurrence : isPlainRecord5(extension2.recurrence) ? extension2.recurrence : null; + const recurring = asBoolean5(frontmatter.recurring) === true || routineExtension !== null || legacyRecurrence !== null; + manifest.issues.push({ + slug, + identifier: asString14(extension2.identifier), + title: asString14(frontmatter.name) ?? asString14(frontmatter.title) ?? slug, + path: taskPath, + projectSlug: asString14(frontmatter.project), + projectWorkspaceKey: asString14(extension2.projectWorkspaceKey), + assigneeAgentSlug: asString14(frontmatter.assignee), + description: taskDoc.body || asString14(frontmatter.description), + recurring, + routine: routineExtension, + legacyRecurrence, + status: asString14(extension2.status) ?? asString14(routineExtensionRaw.status), + priority: asString14(extension2.priority) ?? asString14(routineExtensionRaw.priority), + labelIds: Array.isArray(extension2.labelIds) ? extension2.labelIds.filter((entry) => typeof entry === "string") : [], + billingCode: asString14(extension2.billingCode), + executionWorkspaceSettings: isPlainRecord5(extension2.executionWorkspaceSettings) ? extension2.executionWorkspaceSettings : null, + assigneeAdapterOverrides: isPlainRecord5(extension2.assigneeAdapterOverrides) ? extension2.assigneeAdapterOverrides : null, + metadata: isPlainRecord5(extension2.metadata) ? extension2.metadata : null + }); + if (frontmatter.kind && frontmatter.kind !== "task") { + warnings.push(`Task markdown ${taskPath} does not declare kind: task in frontmatter.`); + } + } + manifest.envInputs = dedupeEnvInputs(manifest.envInputs); + return { + manifest, + files: normalizedFiles, + warnings + }; +} +function normalizeGitHubSourcePath(value) { + if (!value) return ""; + return value.trim().replace(/\\/g, "/").replace(/^\/+|\/+$/g, ""); +} +function parseGitHubSourceUrl2(rawUrl) { + const url2 = new URL(rawUrl); + if (url2.protocol !== "https:") { + throw unprocessable("GitHub source URL must use HTTPS"); + } + const hostname3 = url2.hostname; + const parts = url2.pathname.split("/").filter(Boolean); + if (parts.length < 2) { + throw unprocessable("Invalid GitHub URL"); + } + const owner = parts[0]; + const repo = parts[1].replace(/\.git$/i, ""); + const queryRef = url2.searchParams.get("ref")?.trim(); + const queryPath = normalizeGitHubSourcePath(url2.searchParams.get("path")); + const queryCompanyPath = normalizeGitHubSourcePath(url2.searchParams.get("companyPath")); + if (queryRef || queryPath || queryCompanyPath) { + const companyPath2 = queryCompanyPath || [queryPath, "COMPANY.md"].filter(Boolean).join("/") || "COMPANY.md"; + let basePath2 = queryPath; + if (!basePath2 && companyPath2 !== "COMPANY.md") { + basePath2 = path40.posix.dirname(companyPath2); + if (basePath2 === ".") basePath2 = ""; + } + return { + hostname: hostname3, + owner, + repo, + ref: queryRef || "main", + basePath: basePath2, + companyPath: companyPath2 + }; + } + let ref = "main"; + let basePath = ""; + let companyPath = "COMPANY.md"; + if (parts[2] === "tree") { + ref = parts[3] ?? "main"; + basePath = parts.slice(4).join("/"); + } else if (parts[2] === "blob") { + ref = parts[3] ?? "main"; + const blobPath = parts.slice(4).join("/"); + if (!blobPath) { + throw unprocessable("Invalid GitHub blob URL"); + } + companyPath = blobPath; + basePath = path40.posix.dirname(blobPath); + if (basePath === ".") basePath = ""; + } + return { hostname: hostname3, owner, repo, ref, basePath, companyPath }; +} +function companyPortabilityService(db, storage) { + const companies2 = companyService(db); + const agents2 = agentService(db); + const assetRecords = assetService(db); + const instructions = agentInstructionsService(); + const access = accessService(db); + const projects2 = projectService(db); + const issues2 = issueService(db); + const companySkills2 = companySkillService(db); + async function resolveSource(source) { + if (source.type === "inline") { + return buildManifestFromPackageFiles( + normalizeFileMap(source.files, source.rootPath) + ); + } + const parsed = parseGitHubSourceUrl2(source.url); + let ref = parsed.ref; + const warnings = []; + const companyRelativePath = parsed.companyPath === "COMPANY.md" ? [parsed.basePath, "COMPANY.md"].filter(Boolean).join("/") : parsed.companyPath; + let companyMarkdown = null; + try { + companyMarkdown = await fetchOptionalText( + resolveRawGitHubUrl(parsed.hostname, parsed.owner, parsed.repo, ref, companyRelativePath) + ); + } catch (err) { + if (ref === "main") { + ref = "master"; + warnings.push("GitHub ref main not found; falling back to master."); + companyMarkdown = await fetchOptionalText( + resolveRawGitHubUrl(parsed.hostname, parsed.owner, parsed.repo, ref, companyRelativePath) + ); + } else { + throw err; + } + } + if (!companyMarkdown) { + throw unprocessable("GitHub company package is missing COMPANY.md"); + } + const companyPath = parsed.companyPath === "COMPANY.md" ? "COMPANY.md" : normalizePortablePath2(path40.posix.relative(parsed.basePath || ".", parsed.companyPath)); + const files = { + [companyPath]: companyMarkdown + }; + const apiBase = gitHubApiBase(parsed.hostname); + const tree = await fetchJson2( + `${apiBase}/repos/${parsed.owner}/${parsed.repo}/git/trees/${ref}?recursive=1` + ).catch(() => ({ tree: [] })); + const basePrefix = parsed.basePath ? `${parsed.basePath.replace(/^\/+|\/+$/g, "")}/` : ""; + const candidatePaths = (tree.tree ?? []).filter((entry) => entry.type === "blob").map((entry) => entry.path).filter((entry) => typeof entry === "string").filter((entry) => { + if (basePrefix && !entry.startsWith(basePrefix)) return false; + const relative3 = basePrefix ? entry.slice(basePrefix.length) : entry; + return relative3.endsWith(".md") || relative3.startsWith("skills/") || relative3 === ".taskcore.yaml" || relative3 === ".taskcore.yml"; + }); + for (const repoPath of candidatePaths) { + const relativePath = basePrefix ? repoPath.slice(basePrefix.length) : repoPath; + if (files[relativePath] !== void 0) continue; + files[normalizePortablePath2(relativePath)] = await fetchText2( + resolveRawGitHubUrl(parsed.hostname, parsed.owner, parsed.repo, ref, repoPath) + ); + } + const companyDoc = parseFrontmatterMarkdown2(companyMarkdown); + const includeEntries = readIncludeEntries(companyDoc.frontmatter); + for (const includeEntry of includeEntries) { + const repoPath = [parsed.basePath, includeEntry.path].filter(Boolean).join("/"); + const relativePath = normalizePortablePath2(includeEntry.path); + if (files[relativePath] !== void 0) continue; + if (!(repoPath.endsWith(".md") || repoPath.endsWith(".yaml") || repoPath.endsWith(".yml"))) continue; + files[relativePath] = await fetchText2( + resolveRawGitHubUrl(parsed.hostname, parsed.owner, parsed.repo, ref, repoPath) + ); + } + const resolved = buildManifestFromPackageFiles(files); + const companyLogoPath = resolved.manifest.company?.logoPath; + if (companyLogoPath && !resolved.files[companyLogoPath]) { + const repoPath = [parsed.basePath, companyLogoPath].filter(Boolean).join("/"); + try { + const binary2 = await fetchBinary( + resolveRawGitHubUrl(parsed.hostname, parsed.owner, parsed.repo, ref, repoPath) + ); + resolved.files[companyLogoPath] = bufferToPortableBinaryFile(binary2, inferContentTypeFromPath(companyLogoPath)); + } catch (err) { + warnings.push(`Failed to fetch company logo ${companyLogoPath} from GitHub: ${err instanceof Error ? err.message : String(err)}`); + } + } + resolved.warnings.unshift(...warnings); + return resolved; + } + async function exportBundle(companyId, input) { + const include = normalizeInclude({ + ...input.include, + agents: input.agents && input.agents.length > 0 ? true : input.include?.agents, + projects: input.projects && input.projects.length > 0 ? true : input.include?.projects, + issues: input.issues && input.issues.length > 0 || input.projectIssues && input.projectIssues.length > 0 ? true : input.include?.issues, + skills: input.skills && input.skills.length > 0 ? true : input.include?.skills + }); + const company = await companies2.getById(companyId); + if (!company) throw notFound("Company not found"); + const files = {}; + const warnings = []; + const envInputs = []; + const requestedSidebarOrder = normalizePortableSidebarOrder(input.sidebarOrder); + const rootPath = normalizeAgentUrlKey(company.name) ?? "company-package"; + let companyLogoPath = null; + const allAgentRows = include.agents ? await agents2.list(companyId, { includeTerminated: true }) : []; + const liveAgentRows = allAgentRows.filter((agent) => agent.status !== "terminated"); + const companySkillRows = include.skills || include.agents ? await companySkills2.listFull(companyId) : []; + if (include.agents) { + const skipped = allAgentRows.length - liveAgentRows.length; + if (skipped > 0) { + warnings.push(`Skipped ${skipped} terminated agent${skipped === 1 ? "" : "s"} from export.`); + } + } + const agentByReference = /* @__PURE__ */ new Map(); + for (const agent of liveAgentRows) { + agentByReference.set(agent.id, agent); + agentByReference.set(agent.name, agent); + const normalizedName = normalizeAgentUrlKey(agent.name); + if (normalizedName) { + agentByReference.set(normalizedName, agent); + } + } + const selectedAgents = /* @__PURE__ */ new Map(); + for (const selector of input.agents ?? []) { + const trimmed = selector.trim(); + if (!trimmed) continue; + const normalized = normalizeAgentUrlKey(trimmed) ?? trimmed; + const match = agentByReference.get(trimmed) ?? agentByReference.get(normalized); + if (!match) { + warnings.push(`Agent selector "${selector}" was not found and was skipped.`); + continue; + } + selectedAgents.set(match.id, match); + } + if (include.agents && selectedAgents.size === 0) { + for (const agent of liveAgentRows) { + selectedAgents.set(agent.id, agent); + } + } + const agentRows = Array.from(selectedAgents.values()).sort((left, right) => left.name.localeCompare(right.name)); + const usedSlugs = /* @__PURE__ */ new Set(); + const idToSlug = /* @__PURE__ */ new Map(); + for (const agent of agentRows) { + const baseSlug = toSafeSlug(agent.name, "agent"); + const slug = uniqueSlug(baseSlug, usedSlugs); + idToSlug.set(agent.id, slug); + } + const projectsSvc = projectService(db); + const issuesSvc = issueService(db); + const routinesSvc = routineService(db); + const allProjectsRaw = include.projects || include.issues ? await projectsSvc.list(companyId) : []; + const allProjects = allProjectsRaw.filter((project) => !project.archivedAt); + const allRoutines = include.issues ? await routinesSvc.list(companyId) : []; + const projectById = new Map(allProjects.map((project) => [project.id, project])); + const projectByReference = /* @__PURE__ */ new Map(); + for (const project of allProjects) { + projectByReference.set(project.id, project); + projectByReference.set(project.urlKey, project); + } + const selectedProjects = /* @__PURE__ */ new Map(); + const normalizeProjectSelector = (selector) => selector.trim().toLowerCase(); + for (const selector of input.projects ?? []) { + const match = projectByReference.get(selector) ?? projectByReference.get(normalizeProjectSelector(selector)); + if (!match) { + warnings.push(`Project selector "${selector}" was not found and was skipped.`); + continue; + } + selectedProjects.set(match.id, match); + } + const selectedIssues = /* @__PURE__ */ new Map(); + const selectedRoutines = /* @__PURE__ */ new Map(); + const routineById = new Map(allRoutines.map((routine) => [routine.id, routine])); + const resolveIssueBySelector = async (selector) => { + const trimmed = selector.trim(); + if (!trimmed) return null; + return trimmed.includes("-") ? issuesSvc.getByIdentifier(trimmed) : issuesSvc.getById(trimmed); + }; + for (const selector of input.issues ?? []) { + const issue2 = await resolveIssueBySelector(selector); + if (!issue2 || issue2.companyId !== companyId) { + const routine = routineById.get(selector.trim()); + if (routine) { + selectedRoutines.set(routine.id, routine); + if (routine.projectId) { + const parentProject = projectById.get(routine.projectId); + if (parentProject) selectedProjects.set(parentProject.id, parentProject); + } + continue; + } + warnings.push(`Issue selector "${selector}" was not found and was skipped.`); + continue; + } + selectedIssues.set(issue2.id, issue2); + if (issue2.projectId) { + const parentProject = projectById.get(issue2.projectId); + if (parentProject) selectedProjects.set(parentProject.id, parentProject); + } + } + for (const selector of input.projectIssues ?? []) { + const match = projectByReference.get(selector) ?? projectByReference.get(normalizeProjectSelector(selector)); + if (!match) { + warnings.push(`Project-issues selector "${selector}" was not found and was skipped.`); + continue; + } + selectedProjects.set(match.id, match); + const projectIssues = await issuesSvc.list(companyId, { projectId: match.id }); + for (const issue2 of projectIssues) { + selectedIssues.set(issue2.id, issue2); + } + for (const routine of allRoutines.filter((entry) => entry.projectId === match.id)) { + selectedRoutines.set(routine.id, routine); + } + } + if (include.projects && selectedProjects.size === 0) { + for (const project of allProjects) { + selectedProjects.set(project.id, project); + } + } + if (include.issues && selectedIssues.size === 0) { + const allIssues = await issuesSvc.list(companyId); + for (const issue2 of allIssues) { + selectedIssues.set(issue2.id, issue2); + if (issue2.projectId) { + const parentProject = projectById.get(issue2.projectId); + if (parentProject) selectedProjects.set(parentProject.id, parentProject); + } + } + if (selectedRoutines.size === 0) { + for (const routine of allRoutines) { + selectedRoutines.set(routine.id, routine); + if (routine.projectId) { + const parentProject = projectById.get(routine.projectId); + if (parentProject) selectedProjects.set(parentProject.id, parentProject); + } + } + } + } + const selectedProjectRows = Array.from(selectedProjects.values()).sort((left, right) => left.name.localeCompare(right.name)); + const selectedIssueRows = Array.from(selectedIssues.values()).filter((issue2) => issue2 != null).sort((left, right) => (left.identifier ?? left.title).localeCompare(right.identifier ?? right.title)); + const selectedRoutineSummaries = Array.from(selectedRoutines.values()).sort((left, right) => left.title.localeCompare(right.title)); + const selectedRoutineRows = (await Promise.all(selectedRoutineSummaries.map((routine) => routinesSvc.getDetail(routine.id)))).filter((routine) => routine !== null); + const taskSlugByIssueId = /* @__PURE__ */ new Map(); + const taskSlugByRoutineId = /* @__PURE__ */ new Map(); + const usedTaskSlugs = /* @__PURE__ */ new Set(); + for (const issue2 of selectedIssueRows) { + const baseSlug = normalizeAgentUrlKey(issue2.identifier ?? issue2.title) ?? "task"; + taskSlugByIssueId.set(issue2.id, uniqueSlug(baseSlug, usedTaskSlugs)); + } + for (const routine of selectedRoutineRows) { + const baseSlug = normalizeAgentUrlKey(routine.title) ?? "task"; + taskSlugByRoutineId.set(routine.id, uniqueSlug(baseSlug, usedTaskSlugs)); + } + const projectSlugById = /* @__PURE__ */ new Map(); + const projectWorkspaceKeyByProjectId = /* @__PURE__ */ new Map(); + const usedProjectSlugs = /* @__PURE__ */ new Set(); + for (const project of selectedProjectRows) { + const baseSlug = deriveProjectUrlKey(project.name, project.name); + projectSlugById.set(project.id, uniqueSlug(baseSlug, usedProjectSlugs)); + } + const sidebarOrder = requestedSidebarOrder ?? stripEmptyValues({ + agents: sortAgentsBySidebarOrder(Array.from(selectedAgents.values())).map((agent) => idToSlug.get(agent.id)).filter((slug) => Boolean(slug)), + projects: selectedProjectRows.map((project) => projectSlugById.get(project.id)).filter((slug) => Boolean(slug)) + }); + const companyPath = "COMPANY.md"; + files[companyPath] = buildMarkdown( + { + name: company.name, + description: company.description ?? null, + schema: "agentcompanies/v1", + slug: rootPath + }, + "" + ); + if (include.company && company.logoAssetId) { + if (!storage) { + warnings.push("Skipped company logo from export because storage is unavailable."); + } else { + const logoAsset = await assetRecords.getById(company.logoAssetId); + if (!logoAsset) { + warnings.push(`Skipped company logo ${company.logoAssetId} because the asset record was not found.`); + } else { + try { + const object2 = await storage.getObject(company.id, logoAsset.objectKey); + const body = await streamToBuffer(object2.stream); + companyLogoPath = `images/${COMPANY_LOGO_FILE_NAME}${resolveCompanyLogoExtension(logoAsset.contentType, logoAsset.originalFilename)}`; + files[companyLogoPath] = bufferToPortableBinaryFile(body, logoAsset.contentType); + } catch (err) { + warnings.push(`Failed to export company logo ${company.logoAssetId}: ${err instanceof Error ? err.message : String(err)}`); + } + } + } + } + const taskcoreAgentsOut = {}; + const taskcoreProjectsOut = {}; + const taskcoreTasksOut = {}; + const unportableTaskWorkspaceRefs = /* @__PURE__ */ new Map(); + const taskcoreRoutinesOut = {}; + const skillByReference = /* @__PURE__ */ new Map(); + for (const skill of companySkillRows) { + skillByReference.set(skill.id, skill); + skillByReference.set(skill.key, skill); + skillByReference.set(skill.slug, skill); + skillByReference.set(skill.name, skill); + } + const selectedSkills = /* @__PURE__ */ new Map(); + for (const selector of input.skills ?? []) { + const trimmed = selector.trim(); + if (!trimmed) continue; + const normalized = normalizeSkillKey2(trimmed) ?? normalizeSkillSlug3(trimmed) ?? trimmed; + const match = skillByReference.get(trimmed) ?? skillByReference.get(normalized); + if (!match) { + warnings.push(`Skill selector "${selector}" was not found and was skipped.`); + continue; + } + selectedSkills.set(match.id, match); + } + if (selectedSkills.size === 0) { + for (const skill of companySkillRows) { + selectedSkills.set(skill.id, skill); + } + } + const selectedSkillRows = Array.from(selectedSkills.values()).sort((left, right) => left.key.localeCompare(right.key)); + const skillExportDirs = buildSkillExportDirMap(selectedSkillRows, company.issuePrefix); + for (const skill of selectedSkillRows) { + const packageDir = skillExportDirs.get(skill.key) ?? `skills/${normalizeSkillSlug3(skill.slug) ?? "skill"}`; + if (shouldReferenceSkillOnExport(skill, Boolean(input.expandReferencedSkills))) { + files[`${packageDir}/SKILL.md`] = await buildReferencedSkillMarkdown(skill); + continue; + } + for (const inventoryEntry of skill.fileInventory) { + const fileDetail = await companySkills2.readFile(companyId, skill.id, inventoryEntry.path).catch(() => null); + if (!fileDetail) continue; + const filePath = `${packageDir}/${inventoryEntry.path}`; + files[filePath] = inventoryEntry.path === "SKILL.md" ? await withSkillSourceMetadata(skill, fileDetail.content) : fileDetail.content; + } + } + if (include.agents) { + for (const agent of agentRows) { + const slug = idToSlug.get(agent.id); + const exportedInstructions = await instructions.exportFiles(agent); + warnings.push(...exportedInstructions.warnings); + const envInputsStart = envInputs.length; + const exportedEnvInputs = extractPortableEnvInputs( + slug, + agent.adapterConfig.env, + warnings + ); + envInputs.push(...exportedEnvInputs); + const adapterDefaultRules = ADAPTER_DEFAULT_RULES_BY_TYPE[agent.adapterType] ?? []; + const portableAdapterConfig = pruneDefaultLikeValue( + normalizePortableConfig(agent.adapterConfig), + { + dropFalseBooleans: true, + defaultRules: adapterDefaultRules + } + ); + const portableRuntimeConfig = pruneDefaultLikeValue( + normalizePortableConfig(agent.runtimeConfig), + { + dropFalseBooleans: true, + defaultRules: RUNTIME_DEFAULT_RULES + } + ); + const portablePermissions = pruneDefaultLikeValue(agent.permissions ?? {}, { dropFalseBooleans: true }); + const agentEnvInputs = dedupeEnvInputs( + envInputs.slice(envInputsStart).filter((inputValue) => inputValue.agentSlug === slug) + ); + const reportsToSlug = agent.reportsTo ? idToSlug.get(agent.reportsTo) ?? null : null; + const desiredSkills = readTaskcoreSkillSyncPreference( + agent.adapterConfig ?? {} + ).desiredSkills; + const commandValue = asString14(portableAdapterConfig.command); + if (commandValue && isAbsoluteCommand(commandValue)) { + warnings.push(`Agent ${slug} command ${commandValue} was omitted from export because it is system-dependent.`); + delete portableAdapterConfig.command; + } + for (const [relativePath, content] of Object.entries(exportedInstructions.files)) { + const targetPath = `agents/${slug}/${relativePath}`; + if (relativePath === exportedInstructions.entryFile) { + files[targetPath] = buildMarkdown( + stripEmptyValues({ + name: agent.name, + title: agent.title ?? null, + reportsTo: reportsToSlug, + skills: desiredSkills.length > 0 ? desiredSkills : void 0 + }), + content + ); + } else { + files[targetPath] = content; + } + } + const extension2 = stripEmptyValues({ + role: agent.role !== "agent" ? agent.role : void 0, + icon: agent.icon ?? null, + capabilities: agent.capabilities ?? null, + adapter: { + type: agent.adapterType, + config: portableAdapterConfig + }, + runtime: portableRuntimeConfig, + permissions: portablePermissions, + budgetMonthlyCents: (agent.budgetMonthlyCents ?? 0) > 0 ? agent.budgetMonthlyCents : void 0, + metadata: agent.metadata ?? null + }); + if (isPlainRecord5(extension2) && agentEnvInputs.length > 0) { + extension2.inputs = { + env: buildEnvInputMap(agentEnvInputs) + }; + } + taskcoreAgentsOut[slug] = isPlainRecord5(extension2) ? extension2 : {}; + } + } + for (const project of selectedProjectRows) { + const slug = projectSlugById.get(project.id); + const projectPath = `projects/${slug}/PROJECT.md`; + const envInputsStart = envInputs.length; + const exportedEnvInputs = extractPortableProjectEnvInputs(slug, project.env, warnings); + envInputs.push(...exportedEnvInputs); + const projectEnvInputs = dedupeEnvInputs( + envInputs.slice(envInputsStart).filter((inputValue) => inputValue.projectSlug === slug) + ); + const portableWorkspaces = await buildPortableProjectWorkspaces(slug, project.workspaces, warnings); + projectWorkspaceKeyByProjectId.set(project.id, portableWorkspaces.workspaceKeyById); + files[projectPath] = buildMarkdown( + { + name: project.name, + description: project.description ?? null, + owner: project.leadAgentId ? idToSlug.get(project.leadAgentId) ?? null : null + }, + project.description ?? "" + ); + const extension2 = stripEmptyValues({ + leadAgentSlug: project.leadAgentId ? idToSlug.get(project.leadAgentId) ?? null : null, + targetDate: project.targetDate ?? null, + color: project.color ?? null, + status: project.status, + executionWorkspacePolicy: exportPortableProjectExecutionWorkspacePolicy( + slug, + project.executionWorkspacePolicy, + portableWorkspaces.workspaceKeyById, + warnings + ) ?? void 0, + workspaces: portableWorkspaces.extension + }); + if (isPlainRecord5(extension2) && projectEnvInputs.length > 0) { + extension2.inputs = { + env: buildEnvInputMap(projectEnvInputs) + }; + } + taskcoreProjectsOut[slug] = isPlainRecord5(extension2) ? extension2 : {}; + } + for (const issue2 of selectedIssueRows) { + const taskSlug = taskSlugByIssueId.get(issue2.id); + const projectSlug = issue2.projectId ? projectSlugById.get(issue2.projectId) ?? null : null; + const taskPath = `tasks/${taskSlug}/TASK.md`; + const assigneeSlug = issue2.assigneeAgentId ? idToSlug.get(issue2.assigneeAgentId) ?? null : null; + const projectWorkspaceKey = issue2.projectId && issue2.projectWorkspaceId ? projectWorkspaceKeyByProjectId.get(issue2.projectId)?.get(issue2.projectWorkspaceId) ?? null : null; + if (issue2.projectWorkspaceId && !projectWorkspaceKey) { + const aggregateKey = `${issue2.projectId ?? "no-project"}:${issue2.projectWorkspaceId}`; + const existing = unportableTaskWorkspaceRefs.get(aggregateKey); + if (existing) { + existing.taskSlugs.push(taskSlug); + } else { + unportableTaskWorkspaceRefs.set(aggregateKey, { + workspaceId: issue2.projectWorkspaceId, + taskSlugs: [taskSlug] + }); + } + } + files[taskPath] = buildMarkdown( + { + name: issue2.title, + project: projectSlug, + assignee: assigneeSlug + }, + issue2.description ?? "" + ); + const extension2 = stripEmptyValues({ + identifier: issue2.identifier, + status: issue2.status, + priority: issue2.priority, + labelIds: issue2.labelIds ?? void 0, + billingCode: issue2.billingCode ?? null, + projectWorkspaceKey: projectWorkspaceKey ?? void 0, + executionWorkspaceSettings: issue2.executionWorkspaceSettings ?? void 0, + assigneeAdapterOverrides: issue2.assigneeAdapterOverrides ?? void 0 + }); + taskcoreTasksOut[taskSlug] = isPlainRecord5(extension2) ? extension2 : {}; + } + for (const { workspaceId, taskSlugs } of unportableTaskWorkspaceRefs.values()) { + const preview = taskSlugs.slice(0, 4).join(", "); + const remainder = taskSlugs.length > 4 ? ` and ${taskSlugs.length - 4} more` : ""; + warnings.push(`Tasks ${preview}${remainder} reference workspace ${workspaceId}, but that workspace could not be exported portably.`); + } + for (const routine of selectedRoutineRows) { + const taskSlug = taskSlugByRoutineId.get(routine.id); + const projectSlug = routine.projectId ? projectSlugById.get(routine.projectId) ?? null : null; + const taskPath = `tasks/${taskSlug}/TASK.md`; + const assigneeSlug = routine.assigneeAgentId ? idToSlug.get(routine.assigneeAgentId) ?? null : null; + files[taskPath] = buildMarkdown( + { + name: routine.title, + project: projectSlug, + assignee: assigneeSlug, + recurring: true + }, + routine.description ?? "" + ); + const extension2 = stripEmptyValues({ + status: routine.status !== "active" ? routine.status : void 0, + priority: routine.priority !== "medium" ? routine.priority : void 0, + concurrencyPolicy: routine.concurrencyPolicy !== "coalesce_if_active" ? routine.concurrencyPolicy : void 0, + catchUpPolicy: routine.catchUpPolicy !== "skip_missed" ? routine.catchUpPolicy : void 0, + variables: (routine.variables ?? []).length > 0 ? routine.variables : void 0, + triggers: routine.triggers.map((trigger) => stripEmptyValues({ + kind: trigger.kind, + label: trigger.label ?? null, + enabled: trigger.enabled ? void 0 : false, + cronExpression: trigger.kind === "schedule" ? trigger.cronExpression ?? null : void 0, + timezone: trigger.kind === "schedule" ? trigger.timezone ?? null : void 0, + signingMode: trigger.kind === "webhook" && trigger.signingMode !== "bearer" ? trigger.signingMode ?? null : void 0, + replayWindowSec: trigger.kind === "webhook" && trigger.replayWindowSec !== 300 ? trigger.replayWindowSec ?? null : void 0 + })) + }); + taskcoreRoutinesOut[taskSlug] = isPlainRecord5(extension2) ? extension2 : {}; + } + const taskcoreExtensionPath = ".taskcore.yaml"; + const taskcoreAgents = Object.fromEntries( + Object.entries(taskcoreAgentsOut).filter(([, value]) => isPlainRecord5(value) && Object.keys(value).length > 0) + ); + const taskcoreProjects = Object.fromEntries( + Object.entries(taskcoreProjectsOut).filter(([, value]) => isPlainRecord5(value) && Object.keys(value).length > 0) + ); + const taskcoreTasks = Object.fromEntries( + Object.entries(taskcoreTasksOut).filter(([, value]) => isPlainRecord5(value) && Object.keys(value).length > 0) + ); + const taskcoreRoutines = Object.fromEntries( + Object.entries(taskcoreRoutinesOut).filter(([, value]) => isPlainRecord5(value) && Object.keys(value).length > 0) + ); + files[taskcoreExtensionPath] = buildYamlFile( + { + schema: "taskcore/v1", + company: stripEmptyValues({ + brandColor: company.brandColor ?? null, + logoPath: companyLogoPath, + requireBoardApprovalForNewAgents: company.requireBoardApprovalForNewAgents ? void 0 : false, + feedbackDataSharingEnabled: company.feedbackDataSharingEnabled ? true : void 0, + feedbackDataSharingConsentAt: company.feedbackDataSharingConsentAt?.toISOString() ?? null, + feedbackDataSharingConsentByUserId: company.feedbackDataSharingConsentByUserId ?? null, + feedbackDataSharingTermsVersion: company.feedbackDataSharingTermsVersion ?? null + }), + sidebar: stripEmptyValues(sidebarOrder), + agents: Object.keys(taskcoreAgents).length > 0 ? taskcoreAgents : void 0, + projects: Object.keys(taskcoreProjects).length > 0 ? taskcoreProjects : void 0, + tasks: Object.keys(taskcoreTasks).length > 0 ? taskcoreTasks : void 0, + routines: Object.keys(taskcoreRoutines).length > 0 ? taskcoreRoutines : void 0 + }, + { preserveEmptyStrings: true } + ); + let finalFiles = filterExportFiles(files, input.selectedFiles, taskcoreExtensionPath); + let resolved = buildManifestFromPackageFiles(finalFiles, { + sourceLabel: { + companyId: company.id, + companyName: company.name + } + }); + resolved.manifest.includes = { + company: resolved.manifest.company !== null, + agents: resolved.manifest.agents.length > 0, + projects: resolved.manifest.projects.length > 0, + issues: resolved.manifest.issues.length > 0, + skills: resolved.manifest.skills.length > 0 + }; + resolved.manifest.envInputs = dedupeEnvInputs(envInputs); + resolved.warnings.unshift(...warnings); + if (resolved.manifest.agents.length > 0) { + try { + const orgNodes = buildOrgTreeFromManifest(resolved.manifest.agents); + const pngBuffer = await renderOrgChartPng(orgNodes); + finalFiles["images/org-chart.png"] = bufferToPortableBinaryFile(pngBuffer, "image/png"); + } catch { + } + } + if (!input.selectedFiles || input.selectedFiles.some((entry) => normalizePortablePath2(entry) === "README.md")) { + finalFiles["README.md"] = generateReadme(resolved.manifest, { + companyName: company.name, + companyDescription: company.description ?? null + }); + } + resolved = buildManifestFromPackageFiles(finalFiles, { + sourceLabel: { + companyId: company.id, + companyName: company.name + } + }); + resolved.manifest.includes = { + company: resolved.manifest.company !== null, + agents: resolved.manifest.agents.length > 0, + projects: resolved.manifest.projects.length > 0, + issues: resolved.manifest.issues.length > 0, + skills: resolved.manifest.skills.length > 0 + }; + resolved.manifest.envInputs = dedupeEnvInputs(envInputs); + resolved.warnings.unshift(...warnings); + return { + rootPath, + manifest: resolved.manifest, + files: finalFiles, + warnings: resolved.warnings, + taskcoreExtensionPath + }; + } + async function previewExport(companyId, input) { + const previewInput = { + ...input, + include: { + ...input.include, + issues: input.include?.issues ?? Boolean(input.issues && input.issues.length > 0 || input.projectIssues && input.projectIssues.length > 0) ?? false + } + }; + if (previewInput.include && previewInput.include.issues === void 0) { + previewInput.include.issues = false; + } + const exported = await exportBundle(companyId, previewInput); + return { + ...exported, + fileInventory: Object.keys(exported.files).sort((left, right) => left.localeCompare(right)).map((filePath) => ({ + path: filePath, + kind: classifyPortableFileKind(filePath) + })), + counts: { + files: Object.keys(exported.files).length, + agents: exported.manifest.agents.length, + skills: exported.manifest.skills.length, + projects: exported.manifest.projects.length, + issues: exported.manifest.issues.length + } + }; + } + async function buildPreview(input, options) { + const mode = resolveImportMode(options); + const requestedInclude = normalizeInclude(input.include); + const source = applySelectedFilesToSource(await resolveSource(input.source), input.selectedFiles); + const manifest = source.manifest; + const include = { + company: requestedInclude.company && manifest.company !== null, + agents: requestedInclude.agents && manifest.agents.length > 0, + projects: requestedInclude.projects && manifest.projects.length > 0, + issues: requestedInclude.issues && manifest.issues.length > 0, + skills: requestedInclude.skills && manifest.skills.length > 0 + }; + const collisionStrategy = input.collisionStrategy ?? DEFAULT_COLLISION_STRATEGY; + if (mode === "agent_safe" && collisionStrategy === "replace") { + throw unprocessable("Safe import routes do not allow replace collision strategy."); + } + const warnings = [...source.warnings]; + const errors = []; + if (include.company && !manifest.company) { + errors.push("Manifest does not include company metadata."); + } + const selectedSlugs = include.agents ? input.agents && input.agents !== "all" ? Array.from(new Set(input.agents)) : manifest.agents.map((agent) => agent.slug) : []; + const selectedAgents = include.agents ? manifest.agents.filter((agent) => selectedSlugs.includes(agent.slug)) : []; + const selectedMissing = selectedSlugs.filter((slug) => !manifest.agents.some((agent) => agent.slug === slug)); + for (const missing of selectedMissing) { + errors.push(`Selected agent slug not found in manifest: ${missing}`); + } + if (include.agents && selectedAgents.length === 0) { + warnings.push("No agents selected for import."); + } + const availableSkillKeys = new Set(source.manifest.skills.map((skill) => skill.key)); + const availableSkillSlugs = /* @__PURE__ */ new Map(); + for (const skill of source.manifest.skills) { + const existing = availableSkillSlugs.get(skill.slug) ?? []; + existing.push(skill); + availableSkillSlugs.set(skill.slug, existing); + } + for (const agent of selectedAgents) { + const filePath = ensureMarkdownPath(agent.path); + const markdown = readPortableTextFile(source.files, filePath); + if (typeof markdown !== "string") { + errors.push(`Missing markdown file for agent ${agent.slug}: ${filePath}`); + continue; + } + const parsed = parseFrontmatterMarkdown2(markdown); + if (parsed.frontmatter.kind && parsed.frontmatter.kind !== "agent") { + warnings.push(`Agent markdown ${filePath} does not declare kind: agent in frontmatter.`); + } + for (const skillRef of agent.skills) { + const slugMatches = availableSkillSlugs.get(skillRef) ?? []; + if (!availableSkillKeys.has(skillRef) && slugMatches.length !== 1) { + warnings.push(`Agent ${agent.slug} references skill ${skillRef}, but that skill is not present in the package.`); + } + } + } + if (include.projects) { + for (const project of manifest.projects) { + const markdown = readPortableTextFile(source.files, ensureMarkdownPath(project.path)); + if (typeof markdown !== "string") { + errors.push(`Missing markdown file for project ${project.slug}: ${project.path}`); + continue; + } + const parsed = parseFrontmatterMarkdown2(markdown); + if (parsed.frontmatter.kind && parsed.frontmatter.kind !== "project") { + warnings.push(`Project markdown ${project.path} does not declare kind: project in frontmatter.`); + } + } + } + if (include.issues) { + const projectBySlug = new Map(manifest.projects.map((project) => [project.slug, project])); + for (const issue2 of manifest.issues) { + const markdown = readPortableTextFile(source.files, ensureMarkdownPath(issue2.path)); + if (typeof markdown !== "string") { + errors.push(`Missing markdown file for task ${issue2.slug}: ${issue2.path}`); + continue; + } + const parsed = parseFrontmatterMarkdown2(markdown); + if (parsed.frontmatter.kind && parsed.frontmatter.kind !== "task") { + warnings.push(`Task markdown ${issue2.path} does not declare kind: task in frontmatter.`); + } + if (issue2.projectWorkspaceKey) { + const project = issue2.projectSlug ? projectBySlug.get(issue2.projectSlug) ?? null : null; + if (!project) { + warnings.push(`Task ${issue2.slug} references workspace key ${issue2.projectWorkspaceKey}, but its project is not present in the package.`); + } else if (!project.workspaces.some((workspace) => workspace.key === issue2.projectWorkspaceKey)) { + warnings.push(`Task ${issue2.slug} references missing project workspace key ${issue2.projectWorkspaceKey}.`); + } + } + if (issue2.recurring) { + if (!issue2.projectSlug) { + errors.push(`Recurring task ${issue2.slug} must declare a project to import as a routine.`); + } + if (!issue2.assigneeAgentSlug) { + errors.push(`Recurring task ${issue2.slug} must declare an assignee to import as a routine.`); + } + const resolvedRoutine = resolvePortableRoutineDefinition(issue2, parsed.frontmatter.schedule); + warnings.push(...resolvedRoutine.warnings); + errors.push(...resolvedRoutine.errors); + } + } + } + for (const envInput of manifest.envInputs) { + if (envInput.portability === "system_dependent") { + const scope = envInput.agentSlug ? ` for agent ${envInput.agentSlug}` : envInput.projectSlug ? ` for project ${envInput.projectSlug}` : ""; + warnings.push(`Environment input ${envInput.key}${scope} is system-dependent and may need manual adjustment after import.`); + } + } + let targetCompanyId = null; + let targetCompanyName = null; + if (input.target.mode === "existing_company") { + const targetCompany = await companies2.getById(input.target.companyId); + if (!targetCompany) throw notFound("Target company not found"); + targetCompanyId = targetCompany.id; + targetCompanyName = targetCompany.name; + } + const agentPlans = []; + const existingSlugToAgent = /* @__PURE__ */ new Map(); + const existingSlugs = /* @__PURE__ */ new Set(); + const projectPlans = []; + const issuePlans = []; + const existingProjectSlugToProject = /* @__PURE__ */ new Map(); + const existingProjectSlugs = /* @__PURE__ */ new Set(); + if (input.target.mode === "existing_company") { + const existingAgents = await agents2.list(input.target.companyId); + for (const existing of existingAgents) { + const slug = normalizeAgentUrlKey(existing.name) ?? existing.id; + if (!existingSlugToAgent.has(slug)) existingSlugToAgent.set(slug, existing); + existingSlugs.add(slug); + } + const existingProjects = await projects2.list(input.target.companyId); + for (const existing of existingProjects) { + if (!existingProjectSlugToProject.has(existing.urlKey)) { + existingProjectSlugToProject.set(existing.urlKey, { id: existing.id, name: existing.name }); + } + existingProjectSlugs.add(existing.urlKey); + } + const existingSkills = await companySkills2.listFull(input.target.companyId); + const existingSkillKeys = new Set(existingSkills.map((skill) => skill.key)); + const existingSkillSlugs = new Set(existingSkills.map((skill) => normalizeSkillSlug3(skill.slug) ?? skill.slug)); + for (const skill of manifest.skills) { + const skillSlug = normalizeSkillSlug3(skill.slug) ?? skill.slug; + if (existingSkillKeys.has(skill.key) || existingSkillSlugs.has(skillSlug)) { + if (mode === "agent_safe") { + warnings.push(`Existing skill "${skill.slug}" matched during safe import and will ${collisionStrategy === "skip" ? "be skipped" : "be renamed"} instead of overwritten.`); + } else if (collisionStrategy === "replace") { + warnings.push(`Existing skill "${skill.slug}" (${skill.key}) will be overwritten by import.`); + } + } + } + } + for (const manifestAgent of selectedAgents) { + const existing = existingSlugToAgent.get(manifestAgent.slug) ?? null; + if (!existing) { + agentPlans.push({ + slug: manifestAgent.slug, + action: "create", + plannedName: manifestAgent.name, + existingAgentId: null, + reason: null + }); + continue; + } + if (mode === "board_full" && collisionStrategy === "replace") { + agentPlans.push({ + slug: manifestAgent.slug, + action: "update", + plannedName: existing.name, + existingAgentId: existing.id, + reason: "Existing slug matched; replace strategy." + }); + continue; + } + if (collisionStrategy === "skip") { + agentPlans.push({ + slug: manifestAgent.slug, + action: "skip", + plannedName: existing.name, + existingAgentId: existing.id, + reason: "Existing slug matched; skip strategy." + }); + continue; + } + const renamed = uniqueNameBySlug(manifestAgent.name, existingSlugs); + existingSlugs.add(normalizeAgentUrlKey(renamed) ?? manifestAgent.slug); + agentPlans.push({ + slug: manifestAgent.slug, + action: "create", + plannedName: renamed, + existingAgentId: existing.id, + reason: "Existing slug matched; rename strategy." + }); + } + if (include.projects) { + for (const manifestProject of manifest.projects) { + const existing = existingProjectSlugToProject.get(manifestProject.slug) ?? null; + if (!existing) { + projectPlans.push({ + slug: manifestProject.slug, + action: "create", + plannedName: manifestProject.name, + existingProjectId: null, + reason: null + }); + continue; + } + if (mode === "board_full" && collisionStrategy === "replace") { + projectPlans.push({ + slug: manifestProject.slug, + action: "update", + plannedName: existing.name, + existingProjectId: existing.id, + reason: "Existing slug matched; replace strategy." + }); + continue; + } + if (collisionStrategy === "skip") { + projectPlans.push({ + slug: manifestProject.slug, + action: "skip", + plannedName: existing.name, + existingProjectId: existing.id, + reason: "Existing slug matched; skip strategy." + }); + continue; + } + const renamed = uniqueProjectName(manifestProject.name, existingProjectSlugs); + existingProjectSlugs.add(deriveProjectUrlKey(renamed, renamed)); + projectPlans.push({ + slug: manifestProject.slug, + action: "create", + plannedName: renamed, + existingProjectId: existing.id, + reason: "Existing slug matched; rename strategy." + }); + } + } + if (input.nameOverrides) { + for (const ap of agentPlans) { + const override = input.nameOverrides[ap.slug]; + if (override) { + ap.plannedName = override; + } + } + for (const pp of projectPlans) { + const override = input.nameOverrides[pp.slug]; + if (override) { + pp.plannedName = override; + } + } + for (const ip of issuePlans) { + const override = input.nameOverrides[ip.slug]; + if (override) { + ip.plannedTitle = override; + } + } + } + for (const ap of agentPlans) { + if (ap.action === "update") { + warnings.push(`Existing agent "${ap.plannedName}" (${ap.slug}) will be overwritten by import.`); + } + } + for (const pp of projectPlans) { + if (pp.action === "update") { + warnings.push(`Existing project "${pp.plannedName}" (${pp.slug}) will be overwritten by import.`); + } + } + if (include.issues) { + for (const manifestIssue of manifest.issues) { + issuePlans.push({ + slug: manifestIssue.slug, + action: "create", + plannedTitle: manifestIssue.title, + reason: manifestIssue.recurring ? "Recurring task will be imported as a routine." : null + }); + } + } + const preview = { + include, + targetCompanyId, + targetCompanyName, + collisionStrategy, + selectedAgentSlugs: selectedAgents.map((agent) => agent.slug), + plan: { + companyAction: input.target.mode === "new_company" ? "create" : include.company && mode === "board_full" ? "update" : "none", + agentPlans, + projectPlans, + issuePlans + }, + manifest, + files: source.files, + envInputs: manifest.envInputs ?? [], + warnings, + errors + }; + return { + preview, + source, + include, + collisionStrategy, + selectedAgents + }; + } + async function previewImport(input, options) { + const plan = await buildPreview(input, options); + return plan.preview; + } + async function importBundle(input, actorUserId, options) { + const mode = resolveImportMode(options); + const plan = await buildPreview(input, options); + if (plan.preview.errors.length > 0) { + throw unprocessable(`Import preview has errors: ${plan.preview.errors.join("; ")}`); + } + if (mode === "agent_safe" && (plan.preview.plan.companyAction === "update" || plan.preview.plan.agentPlans.some((entry) => entry.action === "update") || plan.preview.plan.projectPlans.some((entry) => entry.action === "update"))) { + throw unprocessable("Safe import routes only allow create or skip actions."); + } + const sourceManifest = plan.source.manifest; + const warnings = [...plan.preview.warnings]; + const include = plan.include; + let targetCompany = null; + let companyAction = "unchanged"; + if (input.target.mode === "new_company") { + if (mode === "agent_safe" && !options?.sourceCompanyId) { + throw unprocessable("Safe new-company imports require a source company context."); + } + if (mode === "agent_safe" && options?.sourceCompanyId) { + const sourceMemberships = await access.listActiveUserMemberships(options.sourceCompanyId); + if (sourceMemberships.length === 0) { + throw unprocessable("Safe new-company import requires at least one active user membership on the source company."); + } + } + const companyName = asString14(input.target.newCompanyName) ?? sourceManifest.company?.name ?? sourceManifest.source?.companyName ?? "Imported Company"; + const created = await companies2.create({ + name: companyName, + description: include.company ? sourceManifest.company?.description ?? null : null, + brandColor: include.company ? sourceManifest.company?.brandColor ?? null : null, + requireBoardApprovalForNewAgents: include.company ? sourceManifest.company?.requireBoardApprovalForNewAgents ?? true : true, + feedbackDataSharingEnabled: include.company ? sourceManifest.company?.feedbackDataSharingEnabled ?? false : false, + feedbackDataSharingConsentAt: include.company && sourceManifest.company?.feedbackDataSharingConsentAt ? new Date(sourceManifest.company.feedbackDataSharingConsentAt) : null, + feedbackDataSharingConsentByUserId: include.company ? sourceManifest.company?.feedbackDataSharingConsentByUserId ?? null : null, + feedbackDataSharingTermsVersion: include.company ? sourceManifest.company?.feedbackDataSharingTermsVersion ?? null : null + }); + if (mode === "agent_safe" && options?.sourceCompanyId) { + await access.copyActiveUserMemberships(options.sourceCompanyId, created.id); + } else { + await access.ensureMembership(created.id, "user", actorUserId ?? "board", "owner", "active"); + } + targetCompany = created; + companyAction = "created"; + } else { + targetCompany = await companies2.getById(input.target.companyId); + if (!targetCompany) throw notFound("Target company not found"); + if (include.company && sourceManifest.company && mode === "board_full") { + const updated = await companies2.update(targetCompany.id, { + name: sourceManifest.company.name, + description: sourceManifest.company.description, + brandColor: sourceManifest.company.brandColor, + requireBoardApprovalForNewAgents: sourceManifest.company.requireBoardApprovalForNewAgents, + feedbackDataSharingEnabled: sourceManifest.company.feedbackDataSharingEnabled, + feedbackDataSharingConsentAt: sourceManifest.company.feedbackDataSharingConsentAt ? new Date(sourceManifest.company.feedbackDataSharingConsentAt) : null, + feedbackDataSharingConsentByUserId: sourceManifest.company.feedbackDataSharingConsentByUserId, + feedbackDataSharingTermsVersion: sourceManifest.company.feedbackDataSharingTermsVersion + }); + targetCompany = updated ?? targetCompany; + companyAction = "updated"; + } + } + if (!targetCompany) throw notFound("Target company not found"); + if (include.company) { + const logoPath = sourceManifest.company?.logoPath ?? null; + if (!logoPath) { + const cleared = await companies2.update(targetCompany.id, { logoAssetId: null }); + targetCompany = cleared ?? targetCompany; + } else { + const logoFile = plan.source.files[logoPath]; + if (!logoFile) { + warnings.push(`Skipped company logo import because ${logoPath} is missing from the package.`); + } else if (!storage) { + warnings.push("Skipped company logo import because storage is unavailable."); + } else { + const contentType = isPortableBinaryFile(logoFile) ? logoFile.contentType ?? inferContentTypeFromPath(logoPath) : inferContentTypeFromPath(logoPath); + if (!contentType || !COMPANY_LOGO_CONTENT_TYPE_EXTENSIONS[contentType]) { + warnings.push(`Skipped company logo import for ${logoPath} because the file type is unsupported.`); + } else { + try { + const body = portableFileToBuffer(logoFile, logoPath); + const stored = await storage.putFile({ + companyId: targetCompany.id, + namespace: "assets/companies", + originalFilename: path40.posix.basename(logoPath), + contentType, + body + }); + const createdAsset = await assetRecords.create(targetCompany.id, { + provider: stored.provider, + objectKey: stored.objectKey, + contentType: stored.contentType, + byteSize: stored.byteSize, + sha256: stored.sha256, + originalFilename: stored.originalFilename, + createdByAgentId: null, + createdByUserId: actorUserId ?? null + }); + const updated = await companies2.update(targetCompany.id, { + logoAssetId: createdAsset.id + }); + targetCompany = updated ?? targetCompany; + } catch (err) { + warnings.push(`Failed to import company logo ${logoPath}: ${err instanceof Error ? err.message : String(err)}`); + } + } + } + } + } + const resultAgents = []; + const resultProjects = []; + const importedSlugToAgentId = /* @__PURE__ */ new Map(); + const existingSlugToAgentId = /* @__PURE__ */ new Map(); + const existingAgents = await agents2.list(targetCompany.id); + for (const existing of existingAgents) { + existingSlugToAgentId.set(normalizeAgentUrlKey(existing.name) ?? existing.id, existing.id); + } + const importedSlugToProjectId = /* @__PURE__ */ new Map(); + const importedProjectWorkspaceIdByProjectSlug = /* @__PURE__ */ new Map(); + const existingProjectSlugToId = /* @__PURE__ */ new Map(); + const existingProjects = await projects2.list(targetCompany.id); + for (const existing of existingProjects) { + existingProjectSlugToId.set(existing.urlKey, existing.id); + } + const importedSkills = include.skills || include.agents ? await companySkills2.importPackageFiles(targetCompany.id, pickTextFiles(plan.source.files), { + onConflict: resolveSkillConflictStrategy(mode, plan.collisionStrategy) + }) : []; + const desiredSkillRefMap = /* @__PURE__ */ new Map(); + for (const importedSkill of importedSkills) { + desiredSkillRefMap.set(importedSkill.originalKey, importedSkill.skill.key); + desiredSkillRefMap.set(importedSkill.originalSlug, importedSkill.skill.key); + if (importedSkill.action === "skipped") { + warnings.push(`Skipped skill ${importedSkill.originalSlug}; existing skill ${importedSkill.skill.slug} was kept.`); + } else if (importedSkill.originalKey !== importedSkill.skill.key) { + warnings.push(`Imported skill ${importedSkill.originalSlug} as ${importedSkill.skill.slug} to avoid overwriting an existing skill.`); + } + } + if (include.agents) { + for (const planAgent of plan.preview.plan.agentPlans) { + const manifestAgent = plan.selectedAgents.find((agent) => agent.slug === planAgent.slug); + if (!manifestAgent) continue; + if (planAgent.action === "skip") { + resultAgents.push({ + slug: planAgent.slug, + id: planAgent.existingAgentId, + action: "skipped", + name: planAgent.plannedName, + reason: planAgent.reason + }); + continue; + } + const bundlePrefix = `agents/${manifestAgent.slug}/`; + const bundleFiles = Object.fromEntries( + Object.entries(plan.source.files).filter(([filePath]) => filePath.startsWith(bundlePrefix)).flatMap(([filePath, content]) => typeof content === "string" ? [[normalizePortablePath2(filePath.slice(bundlePrefix.length)), content]] : []) + ); + const markdownRaw = bundleFiles["AGENTS.md"] ?? readPortableTextFile(plan.source.files, manifestAgent.path); + const entryRelativePath = normalizePortablePath2(manifestAgent.path).startsWith(bundlePrefix) ? normalizePortablePath2(manifestAgent.path).slice(bundlePrefix.length) : "AGENTS.md"; + if (typeof markdownRaw === "string") { + const importedInstructionsBody = parseFrontmatterMarkdown2(markdownRaw).body; + bundleFiles[entryRelativePath] = importedInstructionsBody; + if (entryRelativePath !== "AGENTS.md") { + bundleFiles["AGENTS.md"] = importedInstructionsBody; + } + } + const fallbackPromptTemplate = asString14(manifestAgent.adapterConfig.promptTemplate) || ""; + if (!markdownRaw && fallbackPromptTemplate) { + bundleFiles["AGENTS.md"] = fallbackPromptTemplate; + } + if (!markdownRaw && !fallbackPromptTemplate) { + warnings.push(`Missing AGENTS markdown for ${manifestAgent.slug}; imported with an empty managed bundle.`); + } + const adapterOverride = input.adapterOverrides?.[planAgent.slug]; + const effectiveAdapterType = adapterOverride?.adapterType ?? manifestAgent.adapterType; + const baseAdapterConfig = adapterOverride?.adapterConfig ? { ...adapterOverride.adapterConfig } : { ...manifestAgent.adapterConfig }; + const desiredSkills = (manifestAgent.skills ?? []).map((skillRef) => desiredSkillRefMap.get(skillRef) ?? skillRef); + const adapterConfigWithSkills = writeTaskcoreSkillSyncPreference( + baseAdapterConfig, + desiredSkills + ); + delete adapterConfigWithSkills.promptTemplate; + delete adapterConfigWithSkills.bootstrapPromptTemplate; + delete adapterConfigWithSkills.instructionsFilePath; + delete adapterConfigWithSkills.instructionsBundleMode; + delete adapterConfigWithSkills.instructionsRootPath; + delete adapterConfigWithSkills.instructionsEntryFile; + const patch = { + name: planAgent.plannedName, + role: manifestAgent.role, + title: manifestAgent.title, + icon: manifestAgent.icon, + capabilities: manifestAgent.capabilities, + reportsTo: null, + adapterType: effectiveAdapterType, + adapterConfig: adapterConfigWithSkills, + runtimeConfig: disableImportedTimerHeartbeat(manifestAgent.runtimeConfig), + budgetMonthlyCents: manifestAgent.budgetMonthlyCents, + permissions: manifestAgent.permissions, + metadata: manifestAgent.metadata + }; + if (planAgent.action === "update" && planAgent.existingAgentId) { + let updated = await agents2.update(planAgent.existingAgentId, patch); + if (!updated) { + warnings.push(`Skipped update for missing agent ${planAgent.existingAgentId}.`); + resultAgents.push({ + slug: planAgent.slug, + id: null, + action: "skipped", + name: planAgent.plannedName, + reason: "Existing target agent not found." + }); + continue; + } + try { + const materialized = await instructions.materializeManagedBundle(updated, bundleFiles, { + clearLegacyPromptTemplate: true, + replaceExisting: true + }); + updated = await agents2.update(updated.id, { adapterConfig: materialized.adapterConfig }) ?? updated; + } catch (err) { + warnings.push(`Failed to materialize instructions bundle for ${manifestAgent.slug}: ${err instanceof Error ? err.message : String(err)}`); + } + importedSlugToAgentId.set(planAgent.slug, updated.id); + existingSlugToAgentId.set(normalizeAgentUrlKey(updated.name) ?? updated.id, updated.id); + resultAgents.push({ + slug: planAgent.slug, + id: updated.id, + action: "updated", + name: updated.name, + reason: planAgent.reason + }); + continue; + } + let created = await agents2.create(targetCompany.id, patch); + await access.ensureMembership(targetCompany.id, "agent", created.id, "member", "active"); + await access.setPrincipalPermission( + targetCompany.id, + "agent", + created.id, + "tasks:assign", + true, + actorUserId ?? null + ); + try { + const materialized = await instructions.materializeManagedBundle(created, bundleFiles, { + clearLegacyPromptTemplate: true, + replaceExisting: true + }); + created = await agents2.update(created.id, { adapterConfig: materialized.adapterConfig }) ?? created; + } catch (err) { + warnings.push(`Failed to materialize instructions bundle for ${manifestAgent.slug}: ${err instanceof Error ? err.message : String(err)}`); + } + importedSlugToAgentId.set(planAgent.slug, created.id); + existingSlugToAgentId.set(normalizeAgentUrlKey(created.name) ?? created.id, created.id); + resultAgents.push({ + slug: planAgent.slug, + id: created.id, + action: "created", + name: created.name, + reason: planAgent.reason + }); + } + for (const manifestAgent of plan.selectedAgents) { + const agentId = importedSlugToAgentId.get(manifestAgent.slug); + if (!agentId) continue; + const managerSlug = manifestAgent.reportsToSlug; + if (!managerSlug) continue; + const managerId = importedSlugToAgentId.get(managerSlug) ?? existingSlugToAgentId.get(managerSlug) ?? null; + if (!managerId || managerId === agentId) continue; + try { + await agents2.update(agentId, { reportsTo: managerId }); + } catch { + warnings.push(`Could not assign manager ${managerSlug} for imported agent ${manifestAgent.slug}.`); + } + } + } + if (include.projects) { + for (const planProject of plan.preview.plan.projectPlans) { + const manifestProject = sourceManifest.projects.find((project) => project.slug === planProject.slug); + if (!manifestProject) continue; + if (planProject.action === "skip") { + resultProjects.push({ + slug: planProject.slug, + id: planProject.existingProjectId, + action: "skipped", + name: planProject.plannedName, + reason: planProject.reason + }); + continue; + } + const projectLeadAgentId = manifestProject.leadAgentSlug ? importedSlugToAgentId.get(manifestProject.leadAgentSlug) ?? existingSlugToAgentId.get(manifestProject.leadAgentSlug) ?? null : null; + const projectWorkspaceIdByKey = /* @__PURE__ */ new Map(); + const projectPatch = { + name: planProject.plannedName, + description: manifestProject.description, + leadAgentId: projectLeadAgentId, + targetDate: manifestProject.targetDate, + color: manifestProject.color, + status: manifestProject.status && PROJECT_STATUSES.includes(manifestProject.status) ? manifestProject.status : "backlog", + env: manifestProject.env, + executionWorkspacePolicy: stripPortableProjectExecutionWorkspaceRefs(manifestProject.executionWorkspacePolicy) + }; + let projectId = null; + if (planProject.action === "update" && planProject.existingProjectId) { + const updated = await projects2.update(planProject.existingProjectId, projectPatch); + if (!updated) { + warnings.push(`Skipped update for missing project ${planProject.existingProjectId}.`); + resultProjects.push({ + slug: planProject.slug, + id: null, + action: "skipped", + name: planProject.plannedName, + reason: "Existing target project not found." + }); + continue; + } + projectId = updated.id; + importedSlugToProjectId.set(planProject.slug, updated.id); + existingProjectSlugToId.set(updated.urlKey, updated.id); + resultProjects.push({ + slug: planProject.slug, + id: updated.id, + action: "updated", + name: updated.name, + reason: planProject.reason + }); + } else { + const created = await projects2.create(targetCompany.id, projectPatch); + projectId = created.id; + importedSlugToProjectId.set(planProject.slug, created.id); + existingProjectSlugToId.set(created.urlKey, created.id); + resultProjects.push({ + slug: planProject.slug, + id: created.id, + action: "created", + name: created.name, + reason: planProject.reason + }); + } + if (!projectId) continue; + for (const workspace of manifestProject.workspaces) { + const createdWorkspace = await projects2.createWorkspace(projectId, { + name: workspace.name, + sourceType: workspace.sourceType ?? void 0, + repoUrl: workspace.repoUrl ?? void 0, + repoRef: workspace.repoRef ?? void 0, + defaultRef: workspace.defaultRef ?? void 0, + visibility: workspace.visibility ?? void 0, + setupCommand: workspace.setupCommand ?? void 0, + cleanupCommand: workspace.cleanupCommand ?? void 0, + metadata: workspace.metadata ?? void 0, + isPrimary: workspace.isPrimary + }); + if (!createdWorkspace) { + warnings.push(`Project ${planProject.slug} workspace ${workspace.key} could not be created during import.`); + continue; + } + projectWorkspaceIdByKey.set(workspace.key, createdWorkspace.id); + } + importedProjectWorkspaceIdByProjectSlug.set(planProject.slug, projectWorkspaceIdByKey); + const hydratedProjectExecutionWorkspacePolicy = importPortableProjectExecutionWorkspacePolicy( + planProject.slug, + manifestProject.executionWorkspacePolicy, + projectWorkspaceIdByKey, + warnings + ); + if (hydratedProjectExecutionWorkspacePolicy) { + await projects2.update(projectId, { + executionWorkspacePolicy: hydratedProjectExecutionWorkspacePolicy + }); + } + } + } + if (include.issues) { + const routines2 = routineService(db); + for (const manifestIssue of sourceManifest.issues) { + const markdownRaw = readPortableTextFile(plan.source.files, manifestIssue.path); + const parsed = markdownRaw ? parseFrontmatterMarkdown2(markdownRaw) : null; + const description = parsed?.body || manifestIssue.description || null; + const assigneeAgentId = manifestIssue.assigneeAgentSlug ? importedSlugToAgentId.get(manifestIssue.assigneeAgentSlug) ?? existingSlugToAgentId.get(manifestIssue.assigneeAgentSlug) ?? null : null; + const projectId = manifestIssue.projectSlug ? importedSlugToProjectId.get(manifestIssue.projectSlug) ?? existingProjectSlugToId.get(manifestIssue.projectSlug) ?? null : null; + const projectWorkspaceId = manifestIssue.projectSlug && manifestIssue.projectWorkspaceKey ? importedProjectWorkspaceIdByProjectSlug.get(manifestIssue.projectSlug)?.get(manifestIssue.projectWorkspaceKey) ?? null : null; + if (manifestIssue.projectWorkspaceKey && !projectWorkspaceId) { + warnings.push(`Task ${manifestIssue.slug} references workspace key ${manifestIssue.projectWorkspaceKey}, but that workspace was not imported.`); + } + if (manifestIssue.recurring) { + if (!projectId || !assigneeAgentId) { + throw unprocessable(`Recurring task ${manifestIssue.slug} is missing the project or assignee required to create a routine.`); + } + const resolvedRoutine = resolvePortableRoutineDefinition(manifestIssue, parsed?.frontmatter.schedule); + if (resolvedRoutine.errors.length > 0) { + throw unprocessable(`Recurring task ${manifestIssue.slug} could not be imported as a routine: ${resolvedRoutine.errors.join("; ")}`); + } + warnings.push(...resolvedRoutine.warnings); + const routineDefinition = resolvedRoutine.routine ?? { + concurrencyPolicy: null, + catchUpPolicy: null, + variables: null, + triggers: [] + }; + const createdRoutine = await routines2.create(targetCompany.id, { + projectId, + goalId: null, + parentIssueId: null, + title: manifestIssue.title, + description, + assigneeAgentId, + priority: manifestIssue.priority && ISSUE_PRIORITIES.includes(manifestIssue.priority) ? manifestIssue.priority : "medium", + status: manifestIssue.status && ROUTINE_STATUSES.includes(manifestIssue.status) ? manifestIssue.status : "active", + concurrencyPolicy: routineDefinition.concurrencyPolicy && ROUTINE_CONCURRENCY_POLICIES.includes(routineDefinition.concurrencyPolicy) ? routineDefinition.concurrencyPolicy : "coalesce_if_active", + catchUpPolicy: routineDefinition.catchUpPolicy && ROUTINE_CATCH_UP_POLICIES.includes(routineDefinition.catchUpPolicy) ? routineDefinition.catchUpPolicy : "skip_missed", + variables: routineDefinition.variables ?? [] + }, { + agentId: null, + userId: actorUserId ?? null + }); + for (const trigger of routineDefinition.triggers) { + if (trigger.kind === "schedule") { + await routines2.createTrigger(createdRoutine.id, { + kind: "schedule", + label: trigger.label, + enabled: trigger.enabled, + cronExpression: trigger.cronExpression, + timezone: trigger.timezone + }, { + agentId: null, + userId: actorUserId ?? null + }); + continue; + } + if (trigger.kind === "webhook") { + await routines2.createTrigger(createdRoutine.id, { + kind: "webhook", + label: trigger.label, + enabled: trigger.enabled, + signingMode: trigger.signingMode && ROUTINE_TRIGGER_SIGNING_MODES.includes(trigger.signingMode) ? trigger.signingMode : "bearer", + replayWindowSec: trigger.replayWindowSec ?? 300 + }, { + agentId: null, + userId: actorUserId ?? null + }); + continue; + } + await routines2.createTrigger(createdRoutine.id, { + kind: "api", + label: trigger.label, + enabled: trigger.enabled + }, { + agentId: null, + userId: actorUserId ?? null + }); + } + continue; + } + await issues2.create(targetCompany.id, { + projectId, + projectWorkspaceId, + title: manifestIssue.title, + description, + assigneeAgentId, + status: manifestIssue.status && ISSUE_STATUSES.includes(manifestIssue.status) ? manifestIssue.status : "backlog", + priority: manifestIssue.priority && ISSUE_PRIORITIES.includes(manifestIssue.priority) ? manifestIssue.priority : "medium", + billingCode: manifestIssue.billingCode, + assigneeAdapterOverrides: manifestIssue.assigneeAdapterOverrides, + executionWorkspaceSettings: manifestIssue.executionWorkspaceSettings, + labelIds: manifestIssue.labelIds ?? [] + }); + } + } + return { + company: { + id: targetCompany.id, + name: targetCompany.name, + action: companyAction + }, + agents: resultAgents, + projects: resultProjects, + envInputs: sourceManifest.envInputs ?? [], + warnings + }; + } + return { + exportBundle, + previewExport, + previewImport, + importBundle + }; +} + +// server/src/services/work-products.ts +init_drizzle_orm(); +init_src2(); +function toIssueWorkProduct(row) { + return { + id: row.id, + companyId: row.companyId, + projectId: row.projectId ?? null, + issueId: row.issueId, + executionWorkspaceId: row.executionWorkspaceId ?? null, + runtimeServiceId: row.runtimeServiceId ?? null, + type: row.type, + provider: row.provider, + externalId: row.externalId ?? null, + title: row.title, + url: row.url ?? null, + status: row.status, + reviewState: row.reviewState, + isPrimary: row.isPrimary, + healthStatus: row.healthStatus, + summary: row.summary ?? null, + metadata: row.metadata ?? null, + createdByRunId: row.createdByRunId ?? null, + createdAt: row.createdAt, + updatedAt: row.updatedAt + }; +} +function workProductService(db) { + return { + listForIssue: async (issueId) => { + const rows = await db.select().from(issueWorkProducts).where(eq(issueWorkProducts.issueId, issueId)).orderBy(desc(issueWorkProducts.isPrimary), desc(issueWorkProducts.updatedAt)); + return rows.map(toIssueWorkProduct); + }, + getById: async (id) => { + const row = await db.select().from(issueWorkProducts).where(eq(issueWorkProducts.id, id)).then((rows) => rows[0] ?? null); + return row ? toIssueWorkProduct(row) : null; + }, + createForIssue: async (issueId, companyId, data2) => { + const row = await db.transaction(async (tx) => { + if (data2.isPrimary) { + await tx.update(issueWorkProducts).set({ isPrimary: false, updatedAt: /* @__PURE__ */ new Date() }).where( + and( + eq(issueWorkProducts.companyId, companyId), + eq(issueWorkProducts.issueId, issueId), + eq(issueWorkProducts.type, data2.type) + ) + ); + } + return await tx.insert(issueWorkProducts).values({ + ...data2, + companyId, + issueId + }).returning().then((rows) => rows[0] ?? null); + }); + return row ? toIssueWorkProduct(row) : null; + }, + update: async (id, patch) => { + const row = await db.transaction(async (tx) => { + const existing = await tx.select().from(issueWorkProducts).where(eq(issueWorkProducts.id, id)).then((rows) => rows[0] ?? null); + if (!existing) return null; + if (patch.isPrimary === true) { + await tx.update(issueWorkProducts).set({ isPrimary: false, updatedAt: /* @__PURE__ */ new Date() }).where( + and( + eq(issueWorkProducts.companyId, existing.companyId), + eq(issueWorkProducts.issueId, existing.issueId), + eq(issueWorkProducts.type, existing.type) + ) + ); + } + return await tx.update(issueWorkProducts).set({ ...patch, updatedAt: /* @__PURE__ */ new Date() }).where(eq(issueWorkProducts.id, id)).returning().then((rows) => rows[0] ?? null); + }); + return row ? toIssueWorkProduct(row) : null; + }, + remove: async (id) => { + const row = await db.delete(issueWorkProducts).where(eq(issueWorkProducts.id, id)).returning().then((rows) => rows[0] ?? null); + return row ? toIssueWorkProduct(row) : null; + } + }; +} + +// server/src/config.ts +var import_dotenv = __toESM(require_main(), 1); +import { execFileSync } from "node:child_process"; +import { existsSync as existsSync4, realpathSync as realpathSync2 } from "node:fs"; +import { resolve } from "node:path"; + +// server/src/worktree-config.ts +import fs33 from "node:fs"; +import os22 from "node:os"; +import path41 from "node:path"; +function nonEmpty5(value) { + return typeof value === "string" && value.trim().length > 0 ? value.trim() : null; +} +function expandHomePrefix2(value) { + if (value === "~") return os22.homedir(); + if (value.startsWith("~/")) return path41.resolve(os22.homedir(), value.slice(2)); + return value; +} +function resolveHomeAwarePath2(value) { + return path41.resolve(expandHomePrefix2(value)); +} +function sanitizeWorktreeInstanceId(rawValue) { + const trimmed = rawValue.trim().toLowerCase(); + const normalized = trimmed.replace(/[^a-z0-9_-]+/g, "-").replace(/-+/g, "-").replace(/^[-_]+|[-_]+$/g, ""); + return normalized || "worktree"; +} +function isLoopbackHost4(hostname3) { + const value = hostname3.trim().toLowerCase(); + return value === "127.0.0.1" || value === "localhost" || value === "::1"; +} +function rewriteLocalUrlPort(rawUrl, port) { + if (!rawUrl) return void 0; + try { + const parsed = new URL(rawUrl); + if (!isLoopbackHost4(parsed.hostname)) return rawUrl; + parsed.port = String(port); + return parsed.toString(); + } catch { + return rawUrl; + } +} +function parseEnvFile(contents) { + const entries2 = {}; + for (const rawLine of contents.split(/\r?\n/)) { + const line3 = rawLine.trim(); + if (!line3 || line3.startsWith("#")) continue; + const match = rawLine.match(/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)\s*$/); + if (!match) continue; + const [, key, rawValue] = match; + const value = rawValue.trim(); + if (!value) { + entries2[key] = ""; + continue; + } + if (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'")) { + entries2[key] = value.slice(1, -1); + continue; + } + entries2[key] = value.replace(/\s+#.*$/, "").trim(); + } + return entries2; +} +function readEnvEntries(envPath) { + if (!fs33.existsSync(envPath)) return {}; + return parseEnvFile(fs33.readFileSync(envPath, "utf8")); +} +function formatEnvEntries(entries2) { + return [ + "# Taskcore environment variables", + "# Generated by Taskcore worktree repair", + ...Object.entries(entries2).map(([key, value]) => `${key}=${JSON.stringify(value)}`), + "" + ].join("\n"); +} +function isPathInside(candidatePath, rootPath) { + const candidate = path41.resolve(candidatePath); + const root = path41.resolve(rootPath); + return candidate === root || candidate.startsWith(`${root}${path41.sep}`); +} +function resolveWorktreeRuntimeContext(env2, overrideConfigPath) { + if (env2.TASKCORE_IN_WORKTREE !== "true") return null; + const configPath = resolveTaskcoreConfigPath(overrideConfigPath); + const envPath = resolveTaskcoreEnvPath(configPath); + const worktreeRoot = path41.resolve(path41.dirname(configPath), ".."); + const worktreeName = nonEmpty5(env2.TASKCORE_WORKTREE_NAME) ?? path41.basename(worktreeRoot); + const instanceId = nonEmpty5(env2.TASKCORE_INSTANCE_ID) ?? sanitizeWorktreeInstanceId(worktreeName); + const homeDir = resolveHomeAwarePath2( + nonEmpty5(env2.TASKCORE_HOME) ?? nonEmpty5(env2.TASKCORE_WORKTREES_DIR) ?? "~/.taskcore-worktrees" + ); + const instanceRoot = path41.resolve(homeDir, "instances", instanceId); + return { + configPath, + envPath, + worktreeName, + instanceId, + homeDir, + instanceRoot, + contextPath: path41.resolve(homeDir, "context.json"), + embeddedPostgresDataDir: path41.resolve(instanceRoot, "db"), + backupDir: path41.resolve(instanceRoot, "data", "backups"), + logDir: path41.resolve(instanceRoot, "logs"), + storageDir: path41.resolve(instanceRoot, "data", "storage"), + secretsKeyFilePath: path41.resolve(instanceRoot, "secrets", "master.key") + }; +} +function writeConfigFile(configPath, config3) { + fs33.mkdirSync(path41.dirname(configPath), { recursive: true }); + fs33.writeFileSync(configPath, JSON.stringify(config3, null, 2) + "\n", { mode: 384 }); +} +function resolveRepoManagedWorktreesRoot(worktreeRoot) { + const normalized = path41.resolve(worktreeRoot); + const marker = `${path41.sep}.taskcore${path41.sep}worktrees${path41.sep}`; + const index2 = normalized.indexOf(marker); + if (index2 === -1) return null; + const repoRoot = normalized.slice(0, index2); + return path41.resolve(repoRoot, ".taskcore", "worktrees"); +} +function collectSiblingWorktreePorts(context) { + const serverPorts = /* @__PURE__ */ new Set(); + const databasePorts = /* @__PURE__ */ new Set(); + const siblingConfigPaths = /* @__PURE__ */ new Set(); + const instancesDir = path41.resolve(context.homeDir, "instances"); + if (fs33.existsSync(instancesDir)) { + for (const entry of fs33.readdirSync(instancesDir, { withFileTypes: true })) { + if (!entry.isDirectory() || entry.name === context.instanceId) continue; + const siblingConfigPath = path41.resolve(instancesDir, entry.name, "config.json"); + if (fs33.existsSync(siblingConfigPath)) { + siblingConfigPaths.add(siblingConfigPath); + } + } + } + const repoManagedWorktreesRoot = resolveRepoManagedWorktreesRoot(path41.dirname(context.configPath)); + if (repoManagedWorktreesRoot && fs33.existsSync(repoManagedWorktreesRoot)) { + for (const entry of fs33.readdirSync(repoManagedWorktreesRoot, { withFileTypes: true })) { + if (!entry.isDirectory()) continue; + const siblingConfigPath = path41.resolve(repoManagedWorktreesRoot, entry.name, ".taskcore", "config.json"); + if (path41.resolve(siblingConfigPath) === path41.resolve(context.configPath)) continue; + if (fs33.existsSync(siblingConfigPath)) { + siblingConfigPaths.add(siblingConfigPath); + } + } + } + for (const siblingConfigPath of siblingConfigPaths) { + try { + const siblingConfig = JSON.parse(fs33.readFileSync(siblingConfigPath, "utf8")); + if (Number.isInteger(siblingConfig.server.port) && siblingConfig.server.port > 0) { + serverPorts.add(siblingConfig.server.port); + } + if (siblingConfig.database.mode === "embedded-postgres" && Number.isInteger(siblingConfig.database.embeddedPostgresPort) && siblingConfig.database.embeddedPostgresPort > 0) { + databasePorts.add(siblingConfig.database.embeddedPostgresPort); + } + } catch { + } + } + return { serverPorts, databasePorts }; +} +function findNextUnclaimedPort(preferredPort, claimedPorts) { + let port = Math.max(1, Math.trunc(preferredPort)); + while (claimedPorts.has(port)) { + port += 1; + } + return port; +} +function buildIsolatedWorktreeConfig(config3, context, portOverrides) { + const serverPort = portOverrides?.serverPort ?? config3.server.port; + const databasePort = config3.database.mode === "embedded-postgres" ? portOverrides?.databasePort ?? config3.database.embeddedPostgresPort : void 0; + const nextConfig = { + ...config3, + database: { + ...config3.database, + ...config3.database.mode === "embedded-postgres" ? { + embeddedPostgresDataDir: context.embeddedPostgresDataDir, + embeddedPostgresPort: databasePort ?? config3.database.embeddedPostgresPort, + backup: { + ...config3.database.backup, + dir: context.backupDir + } + } : {} + }, + server: { + ...config3.server, + port: serverPort + }, + logging: { + ...config3.logging, + logDir: context.logDir + }, + storage: { + ...config3.storage, + localDisk: { + ...config3.storage.localDisk, + baseDir: context.storageDir + } + }, + secrets: { + ...config3.secrets, + localEncrypted: { + ...config3.secrets.localEncrypted, + keyFilePath: context.secretsKeyFilePath + } + } + }; + if (config3.auth.baseUrlMode === "explicit" && config3.auth.publicBaseUrl) { + nextConfig.auth = { + ...config3.auth, + publicBaseUrl: rewriteLocalUrlPort(config3.auth.publicBaseUrl, serverPort) + }; + } + return nextConfig; +} +function needsWorktreeConfigRepair(config3, context) { + if (config3.database.mode === "embedded-postgres") { + if (!isPathInside(config3.database.embeddedPostgresDataDir, context.instanceRoot)) { + return true; + } + if (!isPathInside(config3.database.backup.dir, context.instanceRoot)) { + return true; + } + } + if (!isPathInside(config3.logging.logDir, context.instanceRoot)) { + return true; + } + if (!isPathInside(config3.storage.localDisk.baseDir, context.instanceRoot)) { + return true; + } + if (!isPathInside(config3.secrets.localEncrypted.keyFilePath, context.instanceRoot)) { + return true; + } + return false; +} +function maybeRepairLegacyWorktreeConfigAndEnvFiles() { + const context = resolveWorktreeRuntimeContext(process.env); + if (!context) { + return { repairedConfig: false, repairedEnv: false }; + } + process.env.TASKCORE_HOME = context.homeDir; + process.env.TASKCORE_INSTANCE_ID = context.instanceId; + process.env.TASKCORE_CONFIG = context.configPath; + process.env.TASKCORE_CONTEXT = context.contextPath; + process.env.TASKCORE_WORKTREE_NAME = context.worktreeName; + let repairedConfig = false; + if (fs33.existsSync(context.configPath)) { + try { + const parsed = JSON.parse(fs33.readFileSync(context.configPath, "utf8")); + const siblingPorts = collectSiblingWorktreePorts(context); + const hasSiblingPortCollision = siblingPorts.serverPorts.has(parsed.server.port) || parsed.database.mode === "embedded-postgres" && siblingPorts.databasePorts.has(parsed.database.embeddedPostgresPort); + if (needsWorktreeConfigRepair(parsed, context) || hasSiblingPortCollision) { + const selectedServerPort = findNextUnclaimedPort( + parsed.server.port === 3100 ? 3101 : parsed.server.port, + siblingPorts.serverPorts + ); + const selectedDatabasePort = parsed.database.mode === "embedded-postgres" ? findNextUnclaimedPort( + parsed.database.embeddedPostgresPort === 54329 ? 54330 : parsed.database.embeddedPostgresPort, + /* @__PURE__ */ new Set([...siblingPorts.databasePorts, selectedServerPort]) + ) : void 0; + writeConfigFile( + context.configPath, + buildIsolatedWorktreeConfig(parsed, context, { + serverPort: selectedServerPort, + databasePort: selectedDatabasePort + }) + ); + repairedConfig = true; + } + } catch { + } + } + const existingEnvEntries = readEnvEntries(context.envPath); + const desiredEnvEntries = { + ...existingEnvEntries, + TASKCORE_HOME: context.homeDir, + TASKCORE_INSTANCE_ID: context.instanceId, + TASKCORE_CONFIG: context.configPath, + TASKCORE_CONTEXT: context.contextPath, + TASKCORE_IN_WORKTREE: "true", + TASKCORE_WORKTREE_NAME: context.worktreeName + }; + const repairedEnv = Object.entries(desiredEnvEntries).some( + ([key, value]) => existingEnvEntries[key] !== value + ); + if (repairedEnv) { + fs33.mkdirSync(path41.dirname(context.envPath), { recursive: true }); + fs33.writeFileSync(context.envPath, formatEnvEntries(desiredEnvEntries), { mode: 384 }); + } + return { repairedConfig, repairedEnv }; +} + +// server/src/config.ts +var TASKCORE_ENV_FILE_PATH = resolveTaskcoreEnvPath(); +if (existsSync4(TASKCORE_ENV_FILE_PATH)) { + (0, import_dotenv.config)({ path: TASKCORE_ENV_FILE_PATH, override: false, quiet: true }); +} +var CWD_ENV_PATH = resolve(process.cwd(), ".env"); +var isSameFile = existsSync4(CWD_ENV_PATH) && existsSync4(TASKCORE_ENV_FILE_PATH) ? realpathSync2(CWD_ENV_PATH) === realpathSync2(TASKCORE_ENV_FILE_PATH) : CWD_ENV_PATH === TASKCORE_ENV_FILE_PATH; +if (!isSameFile && existsSync4(CWD_ENV_PATH)) { + (0, import_dotenv.config)({ path: CWD_ENV_PATH, override: false, quiet: true }); +} +maybeRepairLegacyWorktreeConfigAndEnvFiles(); +var TAILSCALE_DETECT_TIMEOUT_MS = 3e3; +function detectTailnetBindHost() { + const explicit = process.env.TASKCORE_TAILNET_BIND_HOST?.trim(); + if (explicit) return explicit; + try { + const stdout = execFileSync("tailscale", ["ip", "-4"], { + encoding: "utf8", + stdio: ["ignore", "pipe", "ignore"], + timeout: TAILSCALE_DETECT_TIMEOUT_MS + }); + return stdout.split(/\r?\n/).map((line3) => line3.trim()).find(Boolean); + } catch { + return void 0; + } +} +function loadConfig() { + const fileConfig = readConfigFile(); + const fileDatabaseMode = fileConfig?.database.mode === "postgres" ? "postgres" : "embedded-postgres"; + const fileDbUrl = fileDatabaseMode === "postgres" ? fileConfig?.database.connectionString : void 0; + const fileDatabaseBackup = fileConfig?.database.backup; + const fileSecrets = fileConfig?.secrets; + const fileStorage = fileConfig?.storage; + const strictModeFromEnv = process.env.TASKCORE_SECRETS_STRICT_MODE; + const secretsStrictMode = strictModeFromEnv !== void 0 ? strictModeFromEnv === "true" : fileSecrets?.strictMode ?? false; + const providerFromEnvRaw = process.env.TASKCORE_SECRETS_PROVIDER; + const providerFromEnv = providerFromEnvRaw && SECRET_PROVIDERS.includes(providerFromEnvRaw) ? providerFromEnvRaw : null; + const providerFromFile = fileSecrets?.provider; + const secretsProvider = providerFromEnv ?? providerFromFile ?? "local_encrypted"; + const storageProviderFromEnvRaw = process.env.TASKCORE_STORAGE_PROVIDER; + const storageProviderFromEnv = storageProviderFromEnvRaw && STORAGE_PROVIDERS.includes(storageProviderFromEnvRaw) ? storageProviderFromEnvRaw : null; + const storageProvider = storageProviderFromEnv ?? fileStorage?.provider ?? "local_disk"; + const storageLocalDiskBaseDir = resolveHomeAwarePath( + process.env.TASKCORE_STORAGE_LOCAL_DIR ?? fileStorage?.localDisk?.baseDir ?? resolveDefaultStorageDir() + ); + const storageS3Bucket = process.env.TASKCORE_STORAGE_S3_BUCKET ?? fileStorage?.s3?.bucket ?? "taskcore"; + const storageS3Region = process.env.TASKCORE_STORAGE_S3_REGION ?? fileStorage?.s3?.region ?? "us-east-1"; + const storageS3Endpoint = process.env.TASKCORE_STORAGE_S3_ENDPOINT ?? fileStorage?.s3?.endpoint ?? void 0; + const storageS3Prefix = process.env.TASKCORE_STORAGE_S3_PREFIX ?? fileStorage?.s3?.prefix ?? ""; + const storageS3ForcePathStyle = process.env.TASKCORE_STORAGE_S3_FORCE_PATH_STYLE !== void 0 ? process.env.TASKCORE_STORAGE_S3_FORCE_PATH_STYLE === "true" : fileStorage?.s3?.forcePathStyle ?? false; + const feedbackExportBackendUrl = process.env.TASKCORE_FEEDBACK_EXPORT_BACKEND_URL?.trim() || process.env.TASKCORE_TELEMETRY_BACKEND_URL?.trim() || void 0; + const feedbackExportBackendToken = process.env.TASKCORE_FEEDBACK_EXPORT_BACKEND_TOKEN?.trim() || process.env.TASKCORE_TELEMETRY_BACKEND_TOKEN?.trim() || void 0; + const deploymentModeFromEnvRaw = process.env.TASKCORE_DEPLOYMENT_MODE; + const deploymentModeFromEnv = deploymentModeFromEnvRaw && DEPLOYMENT_MODES.includes(deploymentModeFromEnvRaw) ? deploymentModeFromEnvRaw : null; + const deploymentMode = deploymentModeFromEnv ?? fileConfig?.server.deploymentMode ?? "local_trusted"; + const deploymentExposureFromEnvRaw = process.env.TASKCORE_DEPLOYMENT_EXPOSURE; + const deploymentExposureFromEnv = deploymentExposureFromEnvRaw && DEPLOYMENT_EXPOSURES.includes(deploymentExposureFromEnvRaw) ? deploymentExposureFromEnvRaw : null; + const deploymentExposure = deploymentMode === "local_trusted" ? "private" : deploymentExposureFromEnv ?? fileConfig?.server.exposure ?? "private"; + const bindFromEnvRaw = process.env.TASKCORE_BIND; + const bindFromEnv = bindFromEnvRaw && BIND_MODES.includes(bindFromEnvRaw) ? bindFromEnvRaw : null; + const configuredHost = process.env.HOST ?? fileConfig?.server.host ?? "127.0.0.1"; + const tailnetBindHost = detectTailnetBindHost(); + const bind2 = bindFromEnv ?? fileConfig?.server.bind ?? inferBindModeFromHost(configuredHost, { tailnetBindHost }); + const customBindHost = process.env.TASKCORE_BIND_HOST ?? fileConfig?.server.customBindHost; + const authBaseUrlModeFromEnvRaw = process.env.TASKCORE_AUTH_BASE_URL_MODE; + const authBaseUrlModeFromEnv = authBaseUrlModeFromEnvRaw && AUTH_BASE_URL_MODES.includes(authBaseUrlModeFromEnvRaw) ? authBaseUrlModeFromEnvRaw : null; + const publicUrlFromEnv = process.env.TASKCORE_PUBLIC_URL; + const authPublicBaseUrlRaw = process.env.TASKCORE_AUTH_PUBLIC_BASE_URL ?? process.env.BETTER_AUTH_URL ?? process.env.BETTER_AUTH_BASE_URL ?? publicUrlFromEnv ?? fileConfig?.auth?.publicBaseUrl; + const authPublicBaseUrl = authPublicBaseUrlRaw?.trim() || void 0; + const authBaseUrlMode = authBaseUrlModeFromEnv ?? fileConfig?.auth?.baseUrlMode ?? (authPublicBaseUrl ? "explicit" : "auto"); + const disableSignUpFromEnv = process.env.TASKCORE_AUTH_DISABLE_SIGN_UP; + const authDisableSignUp = disableSignUpFromEnv !== void 0 ? disableSignUpFromEnv === "true" : fileConfig?.auth?.disableSignUp ?? false; + const allowedHostnamesFromEnvRaw = process.env.TASKCORE_ALLOWED_HOSTNAMES; + const allowedHostnamesFromEnv = allowedHostnamesFromEnvRaw ? allowedHostnamesFromEnvRaw.split(",").map((value) => value.trim().toLowerCase()).filter((value) => value.length > 0) : null; + const publicUrlHostname = authPublicBaseUrl ? (() => { + try { + return new URL(authPublicBaseUrl).hostname.trim().toLowerCase(); + } catch { + return null; + } + })() : null; + const allowedHostnames = Array.from( + new Set( + [ + ...allowedHostnamesFromEnv ?? fileConfig?.server.allowedHostnames ?? [], + ...publicUrlHostname ? [publicUrlHostname] : [] + ].map((value) => value.trim().toLowerCase()).filter(Boolean) + ) + ); + const companyDeletionEnvRaw = process.env.TASKCORE_ENABLE_COMPANY_DELETION; + const companyDeletionEnabled = companyDeletionEnvRaw !== void 0 ? companyDeletionEnvRaw === "true" : deploymentMode === "local_trusted"; + const databaseBackupEnabled = process.env.TASKCORE_DB_BACKUP_ENABLED !== void 0 ? process.env.TASKCORE_DB_BACKUP_ENABLED === "true" : fileDatabaseBackup?.enabled ?? true; + const databaseBackupIntervalMinutes = Math.max( + 1, + Number(process.env.TASKCORE_DB_BACKUP_INTERVAL_MINUTES) || fileDatabaseBackup?.intervalMinutes || 60 + ); + const databaseBackupRetentionDays = Math.max( + 1, + Number(process.env.TASKCORE_DB_BACKUP_RETENTION_DAYS) || fileDatabaseBackup?.retentionDays || 7 + ); + const databaseBackupDir = resolveHomeAwarePath( + process.env.TASKCORE_DB_BACKUP_DIR ?? fileDatabaseBackup?.dir ?? resolveDefaultBackupDir() + ); + const bindValidationErrors = validateConfiguredBindMode({ + deploymentMode, + deploymentExposure, + bind: bind2, + host: configuredHost, + customBindHost + }); + if (bindValidationErrors.length > 0) { + throw new Error(bindValidationErrors[0]); + } + const resolvedBind = resolveRuntimeBind({ + bind: bind2, + host: configuredHost, + customBindHost, + tailnetBindHost + }); + if (resolvedBind.errors.length > 0) { + throw new Error(resolvedBind.errors[0]); + } + return { + deploymentMode, + deploymentExposure, + bind: resolvedBind.bind, + customBindHost: resolvedBind.customBindHost, + host: resolvedBind.host, + port: Number(process.env.PORT) || fileConfig?.server.port || 3100, + allowedHostnames, + authBaseUrlMode, + authPublicBaseUrl, + authDisableSignUp, + databaseMode: fileDatabaseMode, + databaseUrl: resolvePostgresUrlFromEnv() ?? fileDbUrl, + embeddedPostgresDataDir: resolveHomeAwarePath( + fileConfig?.database.embeddedPostgresDataDir ?? resolveDefaultEmbeddedPostgresDir() + ), + embeddedPostgresPort: fileConfig?.database.embeddedPostgresPort ?? 54329, + databaseBackupEnabled, + databaseBackupIntervalMinutes, + databaseBackupRetentionDays, + databaseBackupDir, + serveUi: process.env.SERVE_UI !== void 0 ? process.env.SERVE_UI === "true" : fileConfig?.server.serveUi ?? true, + uiDevMiddleware: process.env.TASKCORE_UI_DEV_MIDDLEWARE === "true", + secretsProvider, + secretsStrictMode, + secretsMasterKeyFilePath: resolveHomeAwarePath( + process.env.TASKCORE_SECRETS_MASTER_KEY_FILE ?? fileSecrets?.localEncrypted.keyFilePath ?? resolveDefaultSecretsKeyFilePath() + ), + storageProvider, + storageLocalDiskBaseDir, + storageS3Bucket, + storageS3Region, + storageS3Endpoint, + storageS3Prefix, + storageS3ForcePathStyle, + feedbackExportBackendUrl, + feedbackExportBackendToken, + heartbeatSchedulerEnabled: process.env.HEARTBEAT_SCHEDULER_ENABLED !== "false", + heartbeatSchedulerIntervalMs: Math.max(1e4, Number(process.env.HEARTBEAT_SCHEDULER_INTERVAL_MS) || 3e4), + companyDeletionEnabled, + telemetryEnabled: fileConfig?.telemetry?.enabled ?? true + }; +} + +// server/src/storage/local-disk-provider.ts +import { createReadStream as createReadStream3, promises as fs34 } from "node:fs"; +import path42 from "node:path"; +function normalizeObjectKey(objectKey) { + const normalized = objectKey.replace(/\\/g, "/").trim(); + if (!normalized || normalized.startsWith("/")) { + throw badRequest("Invalid object key"); + } + const parts = normalized.split("/").filter((part) => part.length > 0); + if (parts.length === 0 || parts.some((part) => part === "." || part === "..")) { + throw badRequest("Invalid object key"); + } + return parts.join("/"); +} +function resolveWithin3(baseDir, objectKey) { + const normalizedKey = normalizeObjectKey(objectKey); + const resolved = path42.resolve(baseDir, normalizedKey); + const base = path42.resolve(baseDir); + if (resolved !== base && !resolved.startsWith(base + path42.sep)) { + throw badRequest("Invalid object key path"); + } + return resolved; +} +async function statOrNull(filePath) { + try { + return await fs34.stat(filePath); + } catch { + return null; + } +} +function createLocalDiskStorageProvider(baseDir) { + const root = path42.resolve(baseDir); + return { + id: "local_disk", + async putObject(input) { + const targetPath = resolveWithin3(root, input.objectKey); + const dir = path42.dirname(targetPath); + await fs34.mkdir(dir, { recursive: true }); + const tempPath = `${targetPath}.tmp-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`; + await fs34.writeFile(tempPath, input.body); + await fs34.rename(tempPath, targetPath); + }, + async getObject(input) { + const filePath = resolveWithin3(root, input.objectKey); + const stat5 = await statOrNull(filePath); + if (!stat5 || !stat5.isFile()) { + throw notFound("Object not found"); + } + return { + stream: createReadStream3(filePath), + contentLength: stat5.size, + lastModified: stat5.mtime + }; + }, + async headObject(input) { + const filePath = resolveWithin3(root, input.objectKey); + const stat5 = await statOrNull(filePath); + if (!stat5 || !stat5.isFile()) { + return { exists: false }; + } + return { + exists: true, + contentLength: stat5.size, + lastModified: stat5.mtime + }; + }, + async deleteObject(input) { + const filePath = resolveWithin3(root, input.objectKey); + try { + await fs34.unlink(filePath); + } catch { + } + } + }; +} + +// server/src/storage/s3-provider.ts +var import_client_s3 = __toESM(require_dist_cjs71(), 1); +import { Readable } from "node:stream"; +function normalizePrefix(prefix) { + if (!prefix) return ""; + return prefix.trim().replace(/^\/+/, "").replace(/\/+$/, ""); +} +function buildKey(prefix, objectKey) { + if (!prefix) return objectKey; + return `${prefix}/${objectKey}`; +} +async function toReadableStream(body) { + if (!body) throw notFound("Object not found"); + if (body instanceof Readable) return body; + const candidate = body; + if (typeof candidate.transformToWebStream === "function") { + const webStream = candidate.transformToWebStream(); + const reader = webStream.getReader(); + return Readable.from((async function* () { + while (true) { + const { done, value } = await reader.read(); + if (done) break; + if (value) yield value; + } + })()); + } + if (typeof candidate.arrayBuffer === "function") { + const buffer2 = Buffer.from(await candidate.arrayBuffer()); + return Readable.from(buffer2); + } + throw unprocessable("Unsupported S3 body stream type"); +} +function toDate(value) { + return value instanceof Date ? value : void 0; +} +function createS3StorageProvider(config3) { + const bucket = config3.bucket.trim(); + const region = config3.region.trim(); + if (!bucket) throw unprocessable("S3 storage bucket is required"); + if (!region) throw unprocessable("S3 storage region is required"); + const prefix = normalizePrefix(config3.prefix); + const client2 = new import_client_s3.S3Client({ + region, + endpoint: config3.endpoint, + forcePathStyle: Boolean(config3.forcePathStyle) + }); + return { + id: "s3", + async putObject(input) { + const key = buildKey(prefix, input.objectKey); + await client2.send( + new import_client_s3.PutObjectCommand({ + Bucket: bucket, + Key: key, + Body: input.body, + ContentType: input.contentType, + ContentLength: input.contentLength + }) + ); + }, + async getObject(input) { + const key = buildKey(prefix, input.objectKey); + try { + const output = await client2.send( + new import_client_s3.GetObjectCommand({ + Bucket: bucket, + Key: key + }) + ); + return { + stream: await toReadableStream(output.Body), + contentType: output.ContentType, + contentLength: output.ContentLength, + etag: output.ETag, + lastModified: toDate(output.LastModified) + }; + } catch (err) { + const code = err.name; + if (code === "NoSuchKey" || code === "NotFound") throw notFound("Object not found"); + throw err; + } + }, + async headObject(input) { + const key = buildKey(prefix, input.objectKey); + try { + const output = await client2.send( + new import_client_s3.HeadObjectCommand({ + Bucket: bucket, + Key: key + }) + ); + return { + exists: true, + contentType: output.ContentType, + contentLength: output.ContentLength, + etag: output.ETag, + lastModified: toDate(output.LastModified) + }; + } catch (err) { + const code = err.name; + if (code === "NoSuchKey" || code === "NotFound") return { exists: false }; + throw err; + } + }, + async deleteObject(input) { + const key = buildKey(prefix, input.objectKey); + await client2.send( + new import_client_s3.DeleteObjectCommand({ + Bucket: bucket, + Key: key + }) + ); + } + }; +} + +// server/src/storage/provider-registry.ts +function createStorageProviderFromConfig(config3) { + if (config3.storageProvider === "local_disk") { + return createLocalDiskStorageProvider(config3.storageLocalDiskBaseDir); + } + return createS3StorageProvider({ + bucket: config3.storageS3Bucket, + region: config3.storageS3Region, + endpoint: config3.storageS3Endpoint, + prefix: config3.storageS3Prefix, + forcePathStyle: config3.storageS3ForcePathStyle + }); +} + +// server/src/storage/service.ts +import { createHash as createHash15, randomUUID as randomUUID6 } from "node:crypto"; +import path43 from "node:path"; +var MAX_SEGMENT_LENGTH = 120; +function sanitizeSegment(value) { + const cleaned = value.trim().replace(/[^a-zA-Z0-9._-]+/g, "_").replace(/_{2,}/g, "_").replace(/^_+|_+$/g, ""); + if (!cleaned) return "file"; + return cleaned.slice(0, MAX_SEGMENT_LENGTH); +} +function normalizeNamespace(namespace) { + const normalized = namespace.split("/").map((entry) => entry.trim()).filter((entry) => entry.length > 0).map((entry) => sanitizeSegment(entry)); + if (normalized.length === 0) return "misc"; + return normalized.join("/"); +} +function splitFilename(filename) { + if (!filename) return { stem: "file", ext: "" }; + const base = path43.basename(filename).trim(); + if (!base) return { stem: "file", ext: "" }; + const extRaw = path43.extname(base); + const stemRaw = extRaw ? base.slice(0, base.length - extRaw.length) : base; + const stem = sanitizeSegment(stemRaw); + const ext = extRaw.toLowerCase().replace(/[^a-z0-9.]/g, "").slice(0, 16); + return { + stem, + ext + }; +} +function ensureCompanyPrefix(companyId, objectKey) { + const expectedPrefix = `${companyId}/`; + if (!objectKey.startsWith(expectedPrefix)) { + throw forbidden("Object does not belong to company"); + } + if (objectKey.includes("..")) { + throw badRequest("Invalid object key"); + } +} +function hashBuffer(input) { + return createHash15("sha256").update(input).digest("hex"); +} +function buildObjectKey(companyId, namespace, originalFilename) { + const ns = normalizeNamespace(namespace); + const now2 = /* @__PURE__ */ new Date(); + const year3 = String(now2.getUTCFullYear()); + const month = String(now2.getUTCMonth() + 1).padStart(2, "0"); + const day2 = String(now2.getUTCDate()).padStart(2, "0"); + const { stem, ext } = splitFilename(originalFilename); + const suffix = randomUUID6(); + const filename = `${suffix}-${stem}${ext}`; + return `${companyId}/${ns}/${year3}/${month}/${day2}/${filename}`; +} +function assertPutFileInput(input) { + if (!input.companyId || input.companyId.trim().length === 0) { + throw unprocessable("companyId is required"); + } + if (!input.namespace || input.namespace.trim().length === 0) { + throw unprocessable("namespace is required"); + } + if (!input.contentType || input.contentType.trim().length === 0) { + throw unprocessable("contentType is required"); + } + if (!(input.body instanceof Buffer)) { + throw unprocessable("body must be a Buffer"); + } + if (input.body.length <= 0) { + throw unprocessable("File is empty"); + } +} +function createStorageService(provider) { + return { + provider: provider.id, + async putFile(input) { + assertPutFileInput(input); + const objectKey = buildObjectKey(input.companyId, input.namespace, input.originalFilename); + const byteSize = input.body.length; + const contentType = input.contentType.trim().toLowerCase(); + await provider.putObject({ + objectKey, + body: input.body, + contentType, + contentLength: byteSize + }); + return { + provider: provider.id, + objectKey, + contentType, + byteSize, + sha256: hashBuffer(input.body), + originalFilename: input.originalFilename + }; + }, + async getObject(companyId, objectKey) { + ensureCompanyPrefix(companyId, objectKey); + return provider.getObject({ objectKey }); + }, + async headObject(companyId, objectKey) { + ensureCompanyPrefix(companyId, objectKey); + return provider.headObject({ objectKey }); + }, + async deleteObject(companyId, objectKey) { + ensureCompanyPrefix(companyId, objectKey); + await provider.deleteObject({ objectKey }); + } + }; +} + +// server/src/storage/index.ts +function createStorageServiceFromConfig(config3) { + return createStorageService(createStorageProviderFromConfig(config3)); +} + +// server/src/routes/authz.ts +function assertBoard(req) { + if (req.actor.type !== "board") { + throw forbidden("Board access required"); + } +} +function assertInstanceAdmin(req) { + assertBoard(req); + if (req.actor.source === "local_implicit" || req.actor.isInstanceAdmin) { + return; + } + throw forbidden("Instance admin access required"); +} +function assertCompanyAccess(req, companyId) { + if (req.actor.type === "none") { + throw unauthorized(); + } + if (req.actor.type === "agent" && req.actor.companyId !== companyId) { + throw forbidden("Agent key cannot access another company"); + } + if (req.actor.type === "board" && req.actor.source !== "local_implicit" && !req.actor.isInstanceAdmin) { + const allowedCompanies = req.actor.companyIds ?? []; + if (!allowedCompanies.includes(companyId)) { + throw forbidden("User does not have access to this company"); + } + } +} +function getActorInfo(req) { + if (req.actor.type === "none") { + throw unauthorized(); + } + if (req.actor.type === "agent") { + return { + actorType: "agent", + actorId: req.actor.agentId ?? "unknown-agent", + agentId: req.actor.agentId ?? null, + runId: req.actor.runId ?? null + }; + } + return { + actorType: "user", + actorId: req.actor.userId ?? "board", + agentId: null, + runId: req.actor.runId ?? null + }; +} + +// server/src/routes/companies.ts +function companyRoutes(db, storage) { + const router2 = (0, import_express2.Router)(); + const svc = companyService(db); + const agents2 = agentService(db); + const portability = companyPortabilityService(db, storage); + const access = accessService(db); + const budgets = budgetService(db); + const feedback = feedbackService(db); + function parseBooleanQuery(value) { + return value === true || value === "true" || value === "1"; + } + function parseDateQuery(value, field) { + if (typeof value !== "string" || value.trim().length === 0) return void 0; + const parsed = new Date(value); + if (Number.isNaN(parsed.getTime())) { + throw badRequest(`Invalid ${field} query value`); + } + return parsed; + } + function assertImportTargetAccess(req, target) { + if (target.mode === "new_company") { + assertInstanceAdmin(req); + return; + } + assertCompanyAccess(req, target.companyId); + } + async function assertCanUpdateBranding(req, companyId) { + assertCompanyAccess(req, companyId); + if (req.actor.type === "board") return; + if (!req.actor.agentId) throw forbidden("Agent authentication required"); + const actorAgent = await agents2.getById(req.actor.agentId); + if (!actorAgent || actorAgent.companyId !== companyId) { + throw forbidden("Agent key cannot access another company"); + } + if (actorAgent.role !== "ceo") { + throw forbidden("Only CEO agents can update company branding"); + } + } + async function assertCanManagePortability(req, companyId, capability) { + assertCompanyAccess(req, companyId); + if (req.actor.type === "board") return; + if (!req.actor.agentId) throw forbidden("Agent authentication required"); + const actorAgent = await agents2.getById(req.actor.agentId); + if (!actorAgent || actorAgent.companyId !== companyId) { + throw forbidden("Agent key cannot access another company"); + } + if (actorAgent.role !== "ceo") { + throw forbidden(`Only CEO agents can manage company ${capability}`); + } + } + router2.get("/", async (req, res) => { + assertBoard(req); + const result = await svc.list(); + if (req.actor.source === "local_implicit" || req.actor.isInstanceAdmin) { + res.json(result); + return; + } + const allowed2 = new Set(req.actor.companyIds ?? []); + res.json(result.filter((company) => allowed2.has(company.id))); + }); + router2.get("/stats", async (req, res) => { + assertBoard(req); + const allowed2 = req.actor.source === "local_implicit" || req.actor.isInstanceAdmin ? null : new Set(req.actor.companyIds ?? []); + const stats = await svc.stats(); + if (!allowed2) { + res.json(stats); + return; + } + const filtered = Object.fromEntries(Object.entries(stats).filter(([companyId]) => allowed2.has(companyId))); + res.json(filtered); + }); + router2.get("/issues", (_req, res) => { + res.status(400).json({ + error: "Missing companyId in path. Use /api/companies/{companyId}/issues." + }); + }); + router2.get("/:companyId", async (req, res) => { + const companyId = req.params.companyId; + assertCompanyAccess(req, companyId); + if (req.actor.type !== "agent") { + assertBoard(req); + } + const company = await svc.getById(companyId); + if (!company) { + res.status(404).json({ error: "Company not found" }); + return; + } + res.json(company); + }); + router2.get("/:companyId/feedback-traces", async (req, res) => { + const companyId = req.params.companyId; + assertCompanyAccess(req, companyId); + assertBoard(req); + const targetTypeRaw = typeof req.query.targetType === "string" ? req.query.targetType : void 0; + const voteRaw = typeof req.query.vote === "string" ? req.query.vote : void 0; + const statusRaw = typeof req.query.status === "string" ? req.query.status : void 0; + const issueId = typeof req.query.issueId === "string" && req.query.issueId.trim().length > 0 ? req.query.issueId : void 0; + const projectId = typeof req.query.projectId === "string" && req.query.projectId.trim().length > 0 ? req.query.projectId : void 0; + const traces = await feedback.listFeedbackTraces({ + companyId, + issueId, + projectId, + targetType: targetTypeRaw ? feedbackTargetTypeSchema.parse(targetTypeRaw) : void 0, + vote: voteRaw ? feedbackVoteValueSchema.parse(voteRaw) : void 0, + status: statusRaw ? feedbackTraceStatusSchema.parse(statusRaw) : void 0, + from: parseDateQuery(req.query.from, "from"), + to: parseDateQuery(req.query.to, "to"), + sharedOnly: parseBooleanQuery(req.query.sharedOnly), + includePayload: parseBooleanQuery(req.query.includePayload) + }); + res.json(traces); + }); + router2.post("/:companyId/export", validate(companyPortabilityExportSchema), async (req, res) => { + const companyId = req.params.companyId; + assertCompanyAccess(req, companyId); + const result = await portability.exportBundle(companyId, req.body); + res.json(result); + }); + router2.post("/import/preview", validate(companyPortabilityPreviewSchema), async (req, res) => { + assertBoard(req); + assertImportTargetAccess(req, req.body.target); + const preview = await portability.previewImport(req.body); + res.json(preview); + }); + router2.post("/import", validate(companyPortabilityImportSchema), async (req, res) => { + assertBoard(req); + assertImportTargetAccess(req, req.body.target); + const actor = getActorInfo(req); + const result = await portability.importBundle(req.body, req.actor.type === "board" ? req.actor.userId : null); + await logActivity(db, { + companyId: result.company.id, + actorType: actor.actorType, + actorId: actor.actorId, + action: "company.imported", + entityType: "company", + entityId: result.company.id, + agentId: actor.agentId, + runId: actor.runId, + details: { + include: req.body.include ?? null, + agentCount: result.agents.length, + warningCount: result.warnings.length, + companyAction: result.company.action + } + }); + res.json(result); + }); + router2.post("/:companyId/exports/preview", validate(companyPortabilityExportSchema), async (req, res) => { + const companyId = req.params.companyId; + await assertCanManagePortability(req, companyId, "exports"); + const preview = await portability.previewExport(companyId, req.body); + res.json(preview); + }); + router2.post("/:companyId/exports", validate(companyPortabilityExportSchema), async (req, res) => { + const companyId = req.params.companyId; + await assertCanManagePortability(req, companyId, "exports"); + const result = await portability.exportBundle(companyId, req.body); + res.json(result); + }); + router2.post("/:companyId/imports/preview", validate(companyPortabilityPreviewSchema), async (req, res) => { + const companyId = req.params.companyId; + await assertCanManagePortability(req, companyId, "imports"); + if (req.body.target.mode === "existing_company" && req.body.target.companyId !== companyId) { + throw forbidden("Safe import route can only target the route company"); + } + if (req.body.collisionStrategy === "replace") { + throw forbidden("Safe import route does not allow replace collision strategy"); + } + const preview = await portability.previewImport(req.body, { + mode: "agent_safe", + sourceCompanyId: companyId + }); + res.json(preview); + }); + router2.post("/:companyId/imports/apply", validate(companyPortabilityImportSchema), async (req, res) => { + const companyId = req.params.companyId; + await assertCanManagePortability(req, companyId, "imports"); + if (req.body.target.mode === "existing_company" && req.body.target.companyId !== companyId) { + throw forbidden("Safe import route can only target the route company"); + } + if (req.body.collisionStrategy === "replace") { + throw forbidden("Safe import route does not allow replace collision strategy"); + } + const actor = getActorInfo(req); + const result = await portability.importBundle(req.body, req.actor.type === "board" ? req.actor.userId : null, { + mode: "agent_safe", + sourceCompanyId: companyId + }); + await logActivity(db, { + companyId: result.company.id, + actorType: actor.actorType, + actorId: actor.actorId, + entityType: "company", + entityId: result.company.id, + agentId: actor.agentId, + runId: actor.runId, + action: "company.imported", + details: { + include: req.body.include ?? null, + agentCount: result.agents.length, + warningCount: result.warnings.length, + companyAction: result.company.action, + importMode: "agent_safe" + } + }); + res.json(result); + }); + router2.post("/", validate(createCompanySchema), async (req, res) => { + assertBoard(req); + if (!(req.actor.source === "local_implicit" || req.actor.isInstanceAdmin)) { + throw forbidden("Instance admin required"); + } + const company = await svc.create(req.body); + await access.ensureMembership(company.id, "user", req.actor.userId ?? "local-board", "owner", "active"); + await logActivity(db, { + companyId: company.id, + actorType: "user", + actorId: req.actor.userId ?? "board", + action: "company.created", + entityType: "company", + entityId: company.id, + details: { name: company.name } + }); + if (company.budgetMonthlyCents > 0) { + await budgets.upsertPolicy( + company.id, + { + scopeType: "company", + scopeId: company.id, + amount: company.budgetMonthlyCents, + windowKind: "calendar_month_utc" + }, + req.actor.userId ?? "board" + ); + } + res.status(201).json(company); + }); + router2.patch("/:companyId", async (req, res) => { + const companyId = req.params.companyId; + assertCompanyAccess(req, companyId); + const actor = getActorInfo(req); + const existingCompany = await svc.getById(companyId); + if (!existingCompany) { + res.status(404).json({ error: "Company not found" }); + return; + } + let body; + if (req.actor.type === "agent") { + const agentSvc = agentService(db); + const actorAgent = req.actor.agentId ? await agentSvc.getById(req.actor.agentId) : null; + if (!actorAgent || actorAgent.role !== "ceo") { + throw forbidden("Only CEO agents or board users may update company settings"); + } + if (actorAgent.companyId !== companyId) { + throw forbidden("Agent key cannot access another company"); + } + body = updateCompanyBrandingSchema.parse(req.body); + } else { + assertBoard(req); + body = updateCompanySchema.parse(req.body); + if (body.feedbackDataSharingEnabled === true && !existingCompany.feedbackDataSharingEnabled) { + body = { + ...body, + feedbackDataSharingConsentAt: /* @__PURE__ */ new Date(), + feedbackDataSharingConsentByUserId: req.actor.userId ?? "local-board", + feedbackDataSharingTermsVersion: typeof body.feedbackDataSharingTermsVersion === "string" && body.feedbackDataSharingTermsVersion.length > 0 ? body.feedbackDataSharingTermsVersion : DEFAULT_FEEDBACK_DATA_SHARING_TERMS_VERSION + }; + } + } + const company = await svc.update(companyId, body); + if (!company) { + res.status(404).json({ error: "Company not found" }); + return; + } + await logActivity(db, { + companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + runId: actor.runId, + action: "company.updated", + entityType: "company", + entityId: companyId, + details: body + }); + res.json(company); + }); + router2.patch("/:companyId/branding", validate(updateCompanyBrandingSchema), async (req, res) => { + const companyId = req.params.companyId; + await assertCanUpdateBranding(req, companyId); + const company = await svc.update(companyId, req.body); + if (!company) { + res.status(404).json({ error: "Company not found" }); + return; + } + const actor = getActorInfo(req); + await logActivity(db, { + companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + runId: actor.runId, + action: "company.branding_updated", + entityType: "company", + entityId: companyId, + details: req.body + }); + res.json(company); + }); + router2.post("/:companyId/archive", async (req, res) => { + assertBoard(req); + const companyId = req.params.companyId; + assertCompanyAccess(req, companyId); + const company = await svc.archive(companyId); + if (!company) { + res.status(404).json({ error: "Company not found" }); + return; + } + await logActivity(db, { + companyId, + actorType: "user", + actorId: req.actor.userId ?? "board", + action: "company.archived", + entityType: "company", + entityId: companyId + }); + res.json(company); + }); + router2.delete("/:companyId", async (req, res) => { + assertBoard(req); + const companyId = req.params.companyId; + assertCompanyAccess(req, companyId); + const company = await svc.remove(companyId); + if (!company) { + res.status(404).json({ error: "Company not found" }); + return; + } + res.json({ ok: true }); + }); + return router2; +} + +// server/src/routes/company-skills.ts +var import_express3 = __toESM(require_express2(), 1); +function companySkillRoutes(db) { + const router2 = (0, import_express3.Router)(); + const agents2 = agentService(db); + const access = accessService(db); + const svc = companySkillService(db); + function canCreateAgents(agent) { + if (!agent.permissions || typeof agent.permissions !== "object") return false; + return Boolean(agent.permissions.canCreateAgents); + } + function asString15(value) { + if (typeof value !== "string") return null; + const trimmed = value.trim(); + return trimmed.length > 0 ? trimmed : null; + } + function deriveTrackedSkillRef(skill) { + if (skill.sourceType === "skills_sh") { + return skill.key; + } + if (skill.sourceType !== "github") { + return null; + } + const hostname3 = asString15(skill.metadata?.hostname); + if (hostname3 !== "github.com") { + return null; + } + return skill.key; + } + async function assertCanMutateCompanySkills(req, companyId) { + assertCompanyAccess(req, companyId); + if (req.actor.type === "board") { + if (req.actor.source === "local_implicit" || req.actor.isInstanceAdmin) return; + const allowed2 = await access.canUser(companyId, req.actor.userId, "agents:create"); + if (!allowed2) { + throw forbidden("Missing permission: agents:create"); + } + return; + } + if (!req.actor.agentId) { + throw forbidden("Agent authentication required"); + } + const actorAgent = await agents2.getById(req.actor.agentId); + if (!actorAgent || actorAgent.companyId !== companyId) { + throw forbidden("Agent key cannot access another company"); + } + const allowedByGrant = await access.hasPermission(companyId, "agent", actorAgent.id, "agents:create"); + if (allowedByGrant || canCreateAgents(actorAgent)) { + return; + } + throw forbidden("Missing permission: can create agents"); + } + router2.get("/companies/:companyId/skills", async (req, res) => { + const companyId = req.params.companyId; + assertCompanyAccess(req, companyId); + const result = await svc.list(companyId); + res.json(result); + }); + router2.get("/companies/:companyId/skills/:skillId", async (req, res) => { + const companyId = req.params.companyId; + const skillId = req.params.skillId; + assertCompanyAccess(req, companyId); + const result = await svc.detail(companyId, skillId); + if (!result) { + res.status(404).json({ error: "Skill not found" }); + return; + } + res.json(result); + }); + router2.get("/companies/:companyId/skills/:skillId/update-status", async (req, res) => { + const companyId = req.params.companyId; + const skillId = req.params.skillId; + assertCompanyAccess(req, companyId); + const result = await svc.updateStatus(companyId, skillId); + if (!result) { + res.status(404).json({ error: "Skill not found" }); + return; + } + res.json(result); + }); + router2.get("/companies/:companyId/skills/:skillId/files", async (req, res) => { + const companyId = req.params.companyId; + const skillId = req.params.skillId; + const relativePath = String(req.query.path ?? "SKILL.md"); + assertCompanyAccess(req, companyId); + const result = await svc.readFile(companyId, skillId, relativePath); + if (!result) { + res.status(404).json({ error: "Skill not found" }); + return; + } + res.json(result); + }); + router2.post( + "/companies/:companyId/skills", + validate(companySkillCreateSchema), + async (req, res) => { + const companyId = req.params.companyId; + await assertCanMutateCompanySkills(req, companyId); + const result = await svc.createLocalSkill(companyId, req.body); + const actor = getActorInfo(req); + await logActivity(db, { + companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + runId: actor.runId, + action: "company.skill_created", + entityType: "company_skill", + entityId: result.id, + details: { + slug: result.slug, + name: result.name + } + }); + res.status(201).json(result); + } + ); + router2.patch( + "/companies/:companyId/skills/:skillId/files", + validate(companySkillFileUpdateSchema), + async (req, res) => { + const companyId = req.params.companyId; + const skillId = req.params.skillId; + await assertCanMutateCompanySkills(req, companyId); + const result = await svc.updateFile( + companyId, + skillId, + String(req.body.path ?? ""), + String(req.body.content ?? "") + ); + const actor = getActorInfo(req); + await logActivity(db, { + companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + runId: actor.runId, + action: "company.skill_file_updated", + entityType: "company_skill", + entityId: skillId, + details: { + path: result.path, + markdown: result.markdown + } + }); + res.json(result); + } + ); + router2.post( + "/companies/:companyId/skills/import", + validate(companySkillImportSchema), + async (req, res) => { + const companyId = req.params.companyId; + await assertCanMutateCompanySkills(req, companyId); + const source = String(req.body.source ?? ""); + const result = await svc.importFromSource(companyId, source); + const actor = getActorInfo(req); + await logActivity(db, { + companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + runId: actor.runId, + action: "company.skills_imported", + entityType: "company", + entityId: companyId, + details: { + source, + importedCount: result.imported.length, + importedSlugs: result.imported.map((skill) => skill.slug), + warningCount: result.warnings.length + } + }); + const telemetryClient = getTelemetryClient(); + if (telemetryClient) { + for (const skill of result.imported) { + trackSkillImported(telemetryClient, { + sourceType: skill.sourceType, + skillRef: deriveTrackedSkillRef(skill) + }); + } + } + res.status(201).json(result); + } + ); + router2.post( + "/companies/:companyId/skills/scan-projects", + validate(companySkillProjectScanRequestSchema), + async (req, res) => { + const companyId = req.params.companyId; + await assertCanMutateCompanySkills(req, companyId); + const result = await svc.scanProjectWorkspaces(companyId, req.body); + const actor = getActorInfo(req); + await logActivity(db, { + companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + runId: actor.runId, + action: "company.skills_scanned", + entityType: "company", + entityId: companyId, + details: { + scannedProjects: result.scannedProjects, + scannedWorkspaces: result.scannedWorkspaces, + discovered: result.discovered, + importedCount: result.imported.length, + updatedCount: result.updated.length, + conflictCount: result.conflicts.length, + warningCount: result.warnings.length + } + }); + res.json(result); + } + ); + router2.delete("/companies/:companyId/skills/:skillId", async (req, res) => { + const companyId = req.params.companyId; + const skillId = req.params.skillId; + await assertCanMutateCompanySkills(req, companyId); + const result = await svc.deleteSkill(companyId, skillId); + if (!result) { + res.status(404).json({ error: "Skill not found" }); + return; + } + const actor = getActorInfo(req); + await logActivity(db, { + companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + runId: actor.runId, + action: "company.skill_deleted", + entityType: "company_skill", + entityId: result.id, + details: { + slug: result.slug, + name: result.name + } + }); + res.json(result); + }); + router2.post("/companies/:companyId/skills/:skillId/install-update", async (req, res) => { + const companyId = req.params.companyId; + const skillId = req.params.skillId; + await assertCanMutateCompanySkills(req, companyId); + const result = await svc.installUpdate(companyId, skillId); + if (!result) { + res.status(404).json({ error: "Skill not found" }); + return; + } + const actor = getActorInfo(req); + await logActivity(db, { + companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + runId: actor.runId, + action: "company.skill_update_installed", + entityType: "company_skill", + entityId: result.id, + details: { + slug: result.slug, + sourceRef: result.sourceRef + } + }); + res.json(result); + }); + return router2; +} + +// server/src/routes/agents.ts +var import_express4 = __toESM(require_express2(), 1); +init_src2(); +init_drizzle_orm(); +import { generateKeyPairSync, randomUUID as randomUUID7 } from "node:crypto"; +import path44 from "node:path"; + +// server/src/services/default-agent-instructions.ts +import fs35 from "node:fs/promises"; +var DEFAULT_AGENT_BUNDLE_FILES = { + default: ["AGENTS.md"], + ceo: ["AGENTS.md", "HEARTBEAT.md", "SOUL.md", "TOOLS.md"] +}; +function resolveDefaultAgentBundleUrl(role, fileName) { + return new URL(`../onboarding-assets/${role}/${fileName}`, import.meta.url); +} +async function loadDefaultAgentInstructionsBundle(role) { + const fileNames = DEFAULT_AGENT_BUNDLE_FILES[role]; + const entries2 = await Promise.all( + fileNames.map(async (fileName) => { + const content = await fs35.readFile(resolveDefaultAgentBundleUrl(role, fileName), "utf8"); + return [fileName, content]; + }) + ); + return Object.fromEntries(entries2); +} +function resolveDefaultAgentInstructionsBundleRole(role) { + return role === "ceo" ? "ceo" : "default"; +} + +// server/src/routes/agents.ts +function agentRoutes(db) { + const DEFAULT_INSTRUCTIONS_PATH_KEYS = { + claude_local: "instructionsFilePath", + codex_local: "instructionsFilePath", + droid_local: "instructionsFilePath", + gemini_local: "instructionsFilePath", + hermes_local: "instructionsFilePath", + opencode_local: "instructionsFilePath", + cursor: "instructionsFilePath", + pi_local: "instructionsFilePath" + }; + const DEFAULT_MANAGED_INSTRUCTIONS_ADAPTER_TYPES = new Set(Object.keys(DEFAULT_INSTRUCTIONS_PATH_KEYS)); + const KNOWN_INSTRUCTIONS_PATH_KEYS = /* @__PURE__ */ new Set(["instructionsFilePath", "agentsMdPath"]); + const KNOWN_INSTRUCTIONS_BUNDLE_KEYS = [ + "instructionsBundleMode", + "instructionsRootPath", + "instructionsEntryFile", + "instructionsFilePath", + "agentsMdPath" + ]; + const router2 = (0, import_express4.Router)(); + const svc = agentService(db); + const access = accessService(db); + const approvalsSvc = approvalService(db); + const budgets = budgetService(db); + const heartbeat = heartbeatService(db); + const issueApprovalsSvc = issueApprovalService(db); + const secretsSvc = secretService(db); + const instructions = agentInstructionsService(); + const companySkills2 = companySkillService(db); + const workspaceOperations2 = workspaceOperationService(db); + const instanceSettings2 = instanceSettingsService(db); + const strictSecretsMode = process.env.TASKCORE_SECRETS_STRICT_MODE === "true"; + async function getCurrentUserRedactionOptions() { + return { + enabled: (await instanceSettings2.getGeneral()).censorUsernameInLogs + }; + } + function canCreateAgents(agent) { + if (!agent.permissions || typeof agent.permissions !== "object") return false; + return Boolean(agent.permissions.canCreateAgents); + } + async function buildAgentAccessState(agent) { + const membership = await access.getMembership(agent.companyId, "agent", agent.id); + const grants = membership ? await access.listPrincipalGrants(agent.companyId, "agent", agent.id) : []; + const hasExplicitTaskAssignGrant = grants.some((grant) => grant.permissionKey === "tasks:assign"); + if (agent.role === "ceo") { + return { + canAssignTasks: true, + taskAssignSource: "ceo_role", + membership, + grants + }; + } + if (canCreateAgents(agent)) { + return { + canAssignTasks: true, + taskAssignSource: "agent_creator", + membership, + grants + }; + } + if (hasExplicitTaskAssignGrant) { + return { + canAssignTasks: true, + taskAssignSource: "explicit_grant", + membership, + grants + }; + } + return { + canAssignTasks: false, + taskAssignSource: "none", + membership, + grants + }; + } + async function buildAgentDetail(agent, options) { + const [chainOfCommand, accessState] = await Promise.all([ + svc.getChainOfCommand(agent.id), + buildAgentAccessState(agent) + ]); + return { + ...options?.restricted ? redactForRestrictedAgentView(agent) : agent, + chainOfCommand, + access: accessState + }; + } + async function applyDefaultAgentTaskAssignGrant(companyId, agentId, grantedByUserId) { + await access.ensureMembership(companyId, "agent", agentId, "member", "active"); + await access.setPrincipalPermission( + companyId, + "agent", + agentId, + "tasks:assign", + true, + grantedByUserId + ); + } + async function assertCanCreateAgentsForCompany(req, companyId) { + assertCompanyAccess(req, companyId); + if (req.actor.type === "board") { + if (req.actor.source === "local_implicit" || req.actor.isInstanceAdmin) return null; + const allowed2 = await access.canUser(companyId, req.actor.userId, "agents:create"); + if (!allowed2) { + throw forbidden("Missing permission: agents:create"); + } + return null; + } + if (!req.actor.agentId) throw forbidden("Agent authentication required"); + const actorAgent = await svc.getById(req.actor.agentId); + if (!actorAgent || actorAgent.companyId !== companyId) { + throw forbidden("Agent key cannot access another company"); + } + const allowedByGrant = await access.hasPermission(companyId, "agent", actorAgent.id, "agents:create"); + if (!allowedByGrant && !canCreateAgents(actorAgent)) { + throw forbidden("Missing permission: can create agents"); + } + return actorAgent; + } + async function assertCanReadConfigurations(req, companyId) { + return assertCanCreateAgentsForCompany(req, companyId); + } + async function actorCanReadConfigurationsForCompany(req, companyId) { + assertCompanyAccess(req, companyId); + if (req.actor.type === "board") { + if (req.actor.source === "local_implicit" || req.actor.isInstanceAdmin) return true; + return access.canUser(companyId, req.actor.userId, "agents:create"); + } + if (!req.actor.agentId) return false; + const actorAgent = await svc.getById(req.actor.agentId); + if (!actorAgent || actorAgent.companyId !== companyId) return false; + const allowedByGrant = await access.hasPermission(companyId, "agent", actorAgent.id, "agents:create"); + return allowedByGrant || canCreateAgents(actorAgent); + } + async function buildSkippedWakeupResponse(agent, payload2) { + const issueId = typeof payload2?.issueId === "string" && payload2.issueId.trim() ? payload2.issueId : null; + if (!issueId) { + return { + status: "skipped", + reason: "wakeup_skipped", + message: "Wakeup was skipped.", + issueId: null, + executionRunId: null, + executionAgentId: null, + executionAgentName: null + }; + } + const issue2 = await db.select({ + id: issues.id, + executionRunId: issues.executionRunId + }).from(issues).where(and(eq(issues.id, issueId), eq(issues.companyId, agent.companyId))).then((rows) => rows[0] ?? null); + if (!issue2?.executionRunId) { + return { + status: "skipped", + reason: "wakeup_skipped", + message: "Wakeup was skipped.", + issueId, + executionRunId: null, + executionAgentId: null, + executionAgentName: null + }; + } + const executionRun = await heartbeat.getRun(issue2.executionRunId); + if (!executionRun || executionRun.status !== "queued" && executionRun.status !== "running") { + return { + status: "skipped", + reason: "wakeup_skipped", + message: "Wakeup was skipped.", + issueId, + executionRunId: issue2.executionRunId, + executionAgentId: null, + executionAgentName: null + }; + } + const executionAgent = await svc.getById(executionRun.agentId); + const executionAgentName = executionAgent?.name ?? null; + return { + status: "skipped", + reason: "issue_execution_deferred", + message: executionAgentName ? `Wakeup was deferred because this issue is already being executed by ${executionAgentName}.` : "Wakeup was deferred because this issue already has an active execution run.", + issueId, + executionRunId: executionRun.id, + executionAgentId: executionRun.agentId, + executionAgentName + }; + } + async function assertCanUpdateAgent(req, targetAgent) { + assertCompanyAccess(req, targetAgent.companyId); + if (req.actor.type === "board") return; + if (!req.actor.agentId) throw forbidden("Agent authentication required"); + const actorAgent = await svc.getById(req.actor.agentId); + if (!actorAgent || actorAgent.companyId !== targetAgent.companyId) { + throw forbidden("Agent key cannot access another company"); + } + if (actorAgent.id === targetAgent.id) return; + if (actorAgent.role === "ceo") return; + const allowedByGrant = await access.hasPermission( + targetAgent.companyId, + "agent", + actorAgent.id, + "agents:create" + ); + if (allowedByGrant || canCreateAgents(actorAgent)) return; + throw forbidden("Only CEO or agent creators can modify other agents"); + } + async function assertCanReadAgent(req, targetAgent) { + assertCompanyAccess(req, targetAgent.companyId); + if (req.actor.type === "board") return; + if (!req.actor.agentId) throw forbidden("Agent authentication required"); + const actorAgent = await svc.getById(req.actor.agentId); + if (!actorAgent || actorAgent.companyId !== targetAgent.companyId) { + throw forbidden("Agent key cannot access another company"); + } + } + function assertKnownAdapterType(type) { + const adapterType = typeof type === "string" ? type.trim() : ""; + if (!adapterType) { + throw unprocessable("Adapter type is required"); + } + if (!findServerAdapter(adapterType)) { + throw unprocessable(`Unknown adapter type: ${adapterType}`); + } + return adapterType; + } + function hasOwn(value, key) { + return Object.hasOwn(value, key); + } + async function resolveCompanyIdForAgentReference(req) { + const companyIdQuery = req.query.companyId; + const requestedCompanyId = typeof companyIdQuery === "string" && companyIdQuery.trim().length > 0 ? companyIdQuery.trim() : null; + if (requestedCompanyId) { + assertCompanyAccess(req, requestedCompanyId); + return requestedCompanyId; + } + if (req.actor.type === "agent" && req.actor.companyId) { + return req.actor.companyId; + } + return null; + } + async function normalizeAgentReference(req, rawId) { + const raw = rawId.trim(); + if (isUuidLike(raw)) return raw; + const companyId = await resolveCompanyIdForAgentReference(req); + if (!companyId) { + throw unprocessable("Agent shortname lookup requires companyId query parameter"); + } + const resolved = await svc.resolveByReference(companyId, raw); + if (resolved.ambiguous) { + throw conflict("Agent shortname is ambiguous in this company. Use the agent ID."); + } + if (!resolved.agent) { + throw notFound("Agent not found"); + } + return resolved.agent.id; + } + function parseSourceIssueIds(input) { + const values2 = []; + if (Array.isArray(input.sourceIssueIds)) values2.push(...input.sourceIssueIds); + if (typeof input.sourceIssueId === "string" && input.sourceIssueId.length > 0) { + values2.push(input.sourceIssueId); + } + return Array.from(new Set(values2)); + } + function asRecord8(value) { + if (typeof value !== "object" || value === null || Array.isArray(value)) return null; + return value; + } + function asNonEmptyString(value) { + if (typeof value !== "string") return null; + const trimmed = value.trim(); + return trimmed.length > 0 ? trimmed : null; + } + function preserveInstructionsBundleConfig(existingAdapterConfig, nextAdapterConfig) { + const nextKeys = new Set(Object.keys(nextAdapterConfig)); + if (KNOWN_INSTRUCTIONS_BUNDLE_KEYS.some((key) => nextKeys.has(key))) { + return nextAdapterConfig; + } + const merged = { ...nextAdapterConfig }; + for (const key of KNOWN_INSTRUCTIONS_BUNDLE_KEYS) { + if (merged[key] === void 0 && existingAdapterConfig[key] !== void 0) { + merged[key] = existingAdapterConfig[key]; + } + } + return merged; + } + function parseBooleanLike2(value) { + if (typeof value === "boolean") return value; + if (typeof value === "number") { + if (value === 1) return true; + if (value === 0) return false; + return null; + } + if (typeof value !== "string") return null; + const normalized = value.trim().toLowerCase(); + if (normalized === "true" || normalized === "1" || normalized === "yes" || normalized === "on") { + return true; + } + if (normalized === "false" || normalized === "0" || normalized === "no" || normalized === "off") { + return false; + } + return null; + } + function parseNumberLike(value) { + if (typeof value === "number" && Number.isFinite(value)) return value; + if (typeof value !== "string") return null; + const parsed = Number(value.trim()); + return Number.isFinite(parsed) ? parsed : null; + } + function parseSchedulerHeartbeatPolicy(runtimeConfig) { + const heartbeat2 = asRecord8(asRecord8(runtimeConfig)?.heartbeat) ?? {}; + return { + enabled: parseBooleanLike2(heartbeat2.enabled) ?? false, + intervalSec: Math.max(0, parseNumberLike(heartbeat2.intervalSec) ?? 0) + }; + } + function normalizeNewAgentRuntimeConfig(runtimeConfig) { + const parsedRuntimeConfig = asRecord8(runtimeConfig); + const normalizedRuntimeConfig = parsedRuntimeConfig ? { ...parsedRuntimeConfig } : {}; + const parsedHeartbeat = asRecord8(normalizedRuntimeConfig.heartbeat); + const heartbeat2 = parsedHeartbeat ? { ...parsedHeartbeat } : {}; + if (parseBooleanLike2(heartbeat2.enabled) == null) { + heartbeat2.enabled = false; + } + normalizedRuntimeConfig.heartbeat = heartbeat2; + return normalizedRuntimeConfig; + } + function generateEd25519PrivateKeyPem2() { + const { privateKey } = generateKeyPairSync("ed25519"); + return privateKey.export({ type: "pkcs8", format: "pem" }).toString(); + } + function ensureGatewayDeviceKey(adapterType, adapterConfig) { + if (adapterType !== "openclaw_gateway") return adapterConfig; + const disableDeviceAuth = parseBooleanLike2(adapterConfig.disableDeviceAuth) === true; + if (disableDeviceAuth) return adapterConfig; + if (asNonEmptyString(adapterConfig.devicePrivateKeyPem)) return adapterConfig; + return { ...adapterConfig, devicePrivateKeyPem: generateEd25519PrivateKeyPem2() }; + } + function applyCreateDefaultsByAdapterType(adapterType, adapterConfig) { + const next = { ...adapterConfig }; + if (adapterType === "codex_local") { + if (!asNonEmptyString(next.model)) { + next.model = DEFAULT_CODEX_LOCAL_MODEL; + } + const hasBypassFlag = typeof next.dangerouslyBypassApprovalsAndSandbox === "boolean" || typeof next.dangerouslyBypassSandbox === "boolean"; + if (!hasBypassFlag) { + next.dangerouslyBypassApprovalsAndSandbox = DEFAULT_CODEX_LOCAL_BYPASS_APPROVALS_AND_SANDBOX; + } + return ensureGatewayDeviceKey(adapterType, next); + } + if (adapterType === "gemini_local" && !asNonEmptyString(next.model)) { + next.model = DEFAULT_GEMINI_LOCAL_MODEL; + return ensureGatewayDeviceKey(adapterType, next); + } + if (adapterType === "cursor" && !asNonEmptyString(next.model)) { + next.model = DEFAULT_CURSOR_LOCAL_MODEL; + } + return ensureGatewayDeviceKey(adapterType, next); + } + async function assertAdapterConfigConstraints(companyId, adapterType, adapterConfig) { + if (adapterType !== "opencode_local") return; + const { config: runtimeConfig } = await secretsSvc.resolveAdapterConfigForRuntime(companyId, adapterConfig); + const runtimeEnv = asRecord8(runtimeConfig.env) ?? {}; + try { + await ensureOpenCodeModelConfiguredAndAvailable({ + model: runtimeConfig.model, + command: runtimeConfig.command, + cwd: runtimeConfig.cwd, + env: runtimeEnv + }); + } catch (err) { + const reason = err instanceof Error ? err.message : String(err); + throw unprocessable(`Invalid opencode_local adapterConfig: ${reason}`); + } + } + function resolveInstructionsFilePath(candidatePath, adapterConfig) { + const trimmed = candidatePath.trim(); + if (path44.isAbsolute(trimmed)) return trimmed; + const cwd = asNonEmptyString(adapterConfig.cwd); + if (!cwd) { + throw unprocessable( + "Relative instructions path requires adapterConfig.cwd to be set to an absolute path" + ); + } + if (!path44.isAbsolute(cwd)) { + throw unprocessable("adapterConfig.cwd must be an absolute path to resolve relative instructions path"); + } + return path44.resolve(cwd, trimmed); + } + async function materializeDefaultInstructionsBundleForNewAgent(agent) { + if (!DEFAULT_MANAGED_INSTRUCTIONS_ADAPTER_TYPES.has(agent.adapterType)) { + return agent; + } + const adapterConfig = asRecord8(agent.adapterConfig) ?? {}; + const hasExplicitInstructionsBundle = Boolean(asNonEmptyString(adapterConfig.instructionsBundleMode)) || Boolean(asNonEmptyString(adapterConfig.instructionsRootPath)) || Boolean(asNonEmptyString(adapterConfig.instructionsEntryFile)) || Boolean(asNonEmptyString(adapterConfig.instructionsFilePath)) || Boolean(asNonEmptyString(adapterConfig.agentsMdPath)); + if (hasExplicitInstructionsBundle) { + return agent; + } + const promptTemplate = typeof adapterConfig.promptTemplate === "string" ? adapterConfig.promptTemplate : ""; + const files = promptTemplate.trim().length === 0 ? await loadDefaultAgentInstructionsBundle(resolveDefaultAgentInstructionsBundleRole(agent.role)) : { "AGENTS.md": promptTemplate }; + const materialized = await instructions.materializeManagedBundle( + agent, + files, + { entryFile: "AGENTS.md", replaceExisting: false } + ); + const nextAdapterConfig = { ...materialized.adapterConfig }; + delete nextAdapterConfig.promptTemplate; + const updated = await svc.update(agent.id, { adapterConfig: nextAdapterConfig }); + return updated ?? { ...agent, adapterConfig: nextAdapterConfig }; + } + async function assertCanManageInstructionsPath(req, targetAgent) { + assertCompanyAccess(req, targetAgent.companyId); + if (req.actor.type === "board") return; + if (!req.actor.agentId) throw forbidden("Agent authentication required"); + const actorAgent = await svc.getById(req.actor.agentId); + if (!actorAgent || actorAgent.companyId !== targetAgent.companyId) { + throw forbidden("Agent key cannot access another company"); + } + if (actorAgent.id === targetAgent.id) return; + const chainOfCommand = await svc.getChainOfCommand(targetAgent.id); + if (chainOfCommand.some((manager) => manager.id === actorAgent.id)) return; + throw forbidden("Only the target agent or an ancestor manager can update instructions path"); + } + function summarizeAgentUpdateDetails(patch) { + const changedTopLevelKeys = Object.keys(patch).sort(); + const details = { changedTopLevelKeys }; + const adapterConfigPatch = asRecord8(patch.adapterConfig); + if (adapterConfigPatch) { + details.changedAdapterConfigKeys = Object.keys(adapterConfigPatch).sort(); + } + const runtimeConfigPatch = asRecord8(patch.runtimeConfig); + if (runtimeConfigPatch) { + details.changedRuntimeConfigKeys = Object.keys(runtimeConfigPatch).sort(); + } + return details; + } + function buildUnsupportedSkillSnapshot(adapterType, desiredSkills = []) { + return { + adapterType, + supported: false, + mode: "unsupported", + desiredSkills, + entries: [], + warnings: ["This adapter does not implement skill sync yet."] + }; + } + const ADAPTERS_REQUIRING_MATERIALIZED_RUNTIME_SKILLS = /* @__PURE__ */ new Set([ + "cursor", + "gemini_local", + "opencode_local", + "pi_local" + ]); + function shouldMaterializeRuntimeSkillsForAdapter(adapterType) { + return ADAPTERS_REQUIRING_MATERIALIZED_RUNTIME_SKILLS.has(adapterType); + } + async function buildRuntimeSkillConfig(companyId, adapterType, config3) { + const runtimeSkillEntries = await companySkills2.listRuntimeSkillEntries(companyId, { + materializeMissing: shouldMaterializeRuntimeSkillsForAdapter(adapterType) + }); + return { + ...config3, + taskcoreRuntimeSkills: runtimeSkillEntries + }; + } + async function resolveDesiredSkillAssignment(companyId, adapterType, adapterConfig, requestedDesiredSkills) { + if (!requestedDesiredSkills) { + return { + adapterConfig, + desiredSkills: null, + runtimeSkillEntries: null + }; + } + const resolvedRequestedSkills = await companySkills2.resolveRequestedSkillKeys( + companyId, + requestedDesiredSkills + ); + const runtimeSkillEntries = await companySkills2.listRuntimeSkillEntries(companyId, { + materializeMissing: shouldMaterializeRuntimeSkillsForAdapter(adapterType) + }); + const requiredSkills = runtimeSkillEntries.filter((entry) => entry.required).map((entry) => entry.key); + const desiredSkills = Array.from(/* @__PURE__ */ new Set([...requiredSkills, ...resolvedRequestedSkills])); + return { + adapterConfig: writeTaskcoreSkillSyncPreference(adapterConfig, desiredSkills), + desiredSkills, + runtimeSkillEntries + }; + } + function redactForRestrictedAgentView(agent) { + if (!agent) return null; + return { + ...agent, + adapterConfig: {}, + runtimeConfig: {} + }; + } + function redactAgentConfiguration(agent) { + if (!agent) return null; + return { + id: agent.id, + companyId: agent.companyId, + name: agent.name, + role: agent.role, + title: agent.title, + status: agent.status, + reportsTo: agent.reportsTo, + adapterType: agent.adapterType, + adapterConfig: redactEventPayload(agent.adapterConfig), + runtimeConfig: redactEventPayload(agent.runtimeConfig), + permissions: agent.permissions, + updatedAt: agent.updatedAt + }; + } + function redactRevisionSnapshot(snapshot) { + if (!snapshot || typeof snapshot !== "object" || Array.isArray(snapshot)) return {}; + const record2 = snapshot; + return { + ...record2, + adapterConfig: redactEventPayload( + typeof record2.adapterConfig === "object" && record2.adapterConfig !== null ? record2.adapterConfig : {} + ), + runtimeConfig: redactEventPayload( + typeof record2.runtimeConfig === "object" && record2.runtimeConfig !== null ? record2.runtimeConfig : {} + ), + metadata: typeof record2.metadata === "object" && record2.metadata !== null ? redactEventPayload(record2.metadata) : record2.metadata ?? null + }; + } + function redactConfigRevision(revision) { + return { + ...revision, + beforeConfig: redactRevisionSnapshot(revision.beforeConfig), + afterConfig: redactRevisionSnapshot(revision.afterConfig) + }; + } + function toLeanOrgNode(node) { + const reports = Array.isArray(node.reports) ? node.reports.map((report) => toLeanOrgNode(report)) : []; + return { + id: String(node.id), + name: String(node.name), + role: String(node.role), + status: String(node.status), + reports + }; + } + router2.param("id", async (req, _res, next, rawId) => { + try { + req.params.id = await normalizeAgentReference(req, String(rawId)); + next(); + } catch (err) { + next(err); + } + }); + router2.get("/companies/:companyId/adapters/:type/models", async (req, res) => { + const companyId = req.params.companyId; + assertCompanyAccess(req, companyId); + const type = assertKnownAdapterType(req.params.type); + const models8 = await listAdapterModels(type); + res.json(models8); + }); + router2.get("/companies/:companyId/adapters/:type/detect-model", async (req, res) => { + const companyId = req.params.companyId; + assertCompanyAccess(req, companyId); + const type = assertKnownAdapterType(req.params.type); + const detected = await detectAdapterModel(type); + res.json(detected); + }); + router2.post( + "/companies/:companyId/adapters/:type/test-environment", + validate(testAdapterEnvironmentSchema), + async (req, res) => { + const companyId = req.params.companyId; + const type = assertKnownAdapterType(req.params.type); + await assertCanReadConfigurations(req, companyId); + const adapter = requireServerAdapter(type); + const inputAdapterConfig = req.body?.adapterConfig ?? {}; + const normalizedAdapterConfig = await secretsSvc.normalizeAdapterConfigForPersistence( + companyId, + inputAdapterConfig, + { strictMode: strictSecretsMode } + ); + const { config: runtimeAdapterConfig } = await secretsSvc.resolveAdapterConfigForRuntime( + companyId, + normalizedAdapterConfig + ); + const result = await adapter.testEnvironment({ + companyId, + adapterType: type, + config: runtimeAdapterConfig + }); + res.json(result); + } + ); + router2.get("/agents/:id/skills", async (req, res) => { + const id = req.params.id; + const agent = await svc.getById(id); + if (!agent) { + res.status(404).json({ error: "Agent not found" }); + return; + } + await assertCanReadConfigurations(req, agent.companyId); + const adapter = findActiveServerAdapter(agent.adapterType); + if (!adapter?.listSkills) { + const preference = readTaskcoreSkillSyncPreference( + agent.adapterConfig + ); + const runtimeSkillEntries = await companySkills2.listRuntimeSkillEntries(agent.companyId, { + materializeMissing: false + }); + const requiredSkills = runtimeSkillEntries.filter((entry) => entry.required).map((entry) => entry.key); + res.json(buildUnsupportedSkillSnapshot(agent.adapterType, Array.from(/* @__PURE__ */ new Set([...requiredSkills, ...preference.desiredSkills])))); + return; + } + const { config: runtimeConfig } = await secretsSvc.resolveAdapterConfigForRuntime( + agent.companyId, + agent.adapterConfig + ); + const runtimeSkillConfig = await buildRuntimeSkillConfig( + agent.companyId, + agent.adapterType, + runtimeConfig + ); + const snapshot = await adapter.listSkills({ + agentId: agent.id, + companyId: agent.companyId, + adapterType: agent.adapterType, + config: runtimeSkillConfig + }); + res.json(snapshot); + }); + router2.post( + "/agents/:id/skills/sync", + validate(agentSkillSyncSchema), + async (req, res) => { + const id = req.params.id; + const agent = await svc.getById(id); + if (!agent) { + res.status(404).json({ error: "Agent not found" }); + return; + } + await assertCanUpdateAgent(req, agent); + const requestedSkills = Array.from( + new Set( + req.body.desiredSkills.map((value) => value.trim()).filter(Boolean) + ) + ); + const { + adapterConfig: nextAdapterConfig, + desiredSkills, + runtimeSkillEntries + } = await resolveDesiredSkillAssignment( + agent.companyId, + agent.adapterType, + agent.adapterConfig, + requestedSkills + ); + if (!desiredSkills || !runtimeSkillEntries) { + throw unprocessable("Skill sync requires desiredSkills."); + } + const actor = getActorInfo(req); + const updated = await svc.update(agent.id, { + adapterConfig: nextAdapterConfig + }, { + recordRevision: { + createdByAgentId: actor.agentId, + createdByUserId: actor.actorType === "user" ? actor.actorId : null, + source: "skill-sync" + } + }); + if (!updated) { + res.status(404).json({ error: "Agent not found" }); + return; + } + const adapter = findActiveServerAdapter(updated.adapterType); + const { config: runtimeConfig } = await secretsSvc.resolveAdapterConfigForRuntime( + updated.companyId, + updated.adapterConfig + ); + const runtimeSkillConfig = { + ...runtimeConfig, + taskcoreRuntimeSkills: runtimeSkillEntries + }; + const snapshot = adapter?.syncSkills ? await adapter.syncSkills({ + agentId: updated.id, + companyId: updated.companyId, + adapterType: updated.adapterType, + config: runtimeSkillConfig + }, desiredSkills) : adapter?.listSkills ? await adapter.listSkills({ + agentId: updated.id, + companyId: updated.companyId, + adapterType: updated.adapterType, + config: runtimeSkillConfig + }) : buildUnsupportedSkillSnapshot(updated.adapterType, desiredSkills); + await logActivity(db, { + companyId: updated.companyId, + actorType: actor.actorType, + actorId: actor.actorId, + action: "agent.skills_synced", + entityType: "agent", + entityId: updated.id, + agentId: actor.agentId, + runId: actor.runId, + details: { + adapterType: updated.adapterType, + desiredSkills, + mode: snapshot.mode, + supported: snapshot.supported, + entryCount: snapshot.entries.length, + warningCount: snapshot.warnings.length + } + }); + res.json(snapshot); + } + ); + router2.get("/companies/:companyId/agents", async (req, res) => { + const companyId = req.params.companyId; + assertCompanyAccess(req, companyId); + const unsupportedQueryParams = Object.keys(req.query).sort(); + if (unsupportedQueryParams.length > 0) { + res.status(400).json({ + error: `Unsupported query parameter${unsupportedQueryParams.length === 1 ? "" : "s"}: ${unsupportedQueryParams.join(", ")}` + }); + return; + } + const result = await svc.list(companyId); + const canReadConfigs = await actorCanReadConfigurationsForCompany(req, companyId); + if (canReadConfigs || req.actor.type === "board") { + res.json(result); + return; + } + res.json(result.map((agent) => redactForRestrictedAgentView(agent))); + }); + router2.get("/instance/scheduler-heartbeats", async (req, res) => { + assertInstanceAdmin(req); + const rows = await db.select({ + id: agents.id, + companyId: agents.companyId, + agentName: agents.name, + role: agents.role, + title: agents.title, + status: agents.status, + adapterType: agents.adapterType, + runtimeConfig: agents.runtimeConfig, + lastHeartbeatAt: agents.lastHeartbeatAt, + companyName: companies.name, + companyIssuePrefix: companies.issuePrefix + }).from(agents).innerJoin(companies, eq(agents.companyId, companies.id)).orderBy(companies.name, agents.name); + const items = rows.map((row) => { + const policy = parseSchedulerHeartbeatPolicy(row.runtimeConfig); + const statusEligible = row.status !== "paused" && row.status !== "terminated" && row.status !== "pending_approval"; + return { + id: row.id, + companyId: row.companyId, + companyName: row.companyName, + companyIssuePrefix: row.companyIssuePrefix, + agentName: row.agentName, + agentUrlKey: deriveAgentUrlKey(row.agentName, row.id), + role: row.role, + title: row.title, + status: row.status, + adapterType: row.adapterType, + intervalSec: policy.intervalSec, + heartbeatEnabled: policy.enabled, + schedulerActive: statusEligible && policy.enabled && policy.intervalSec > 0, + lastHeartbeatAt: row.lastHeartbeatAt + }; + }).filter( + (item) => item.status !== "paused" && item.status !== "terminated" && item.status !== "pending_approval" + ).sort((left, right) => { + if (left.schedulerActive !== right.schedulerActive) { + return left.schedulerActive ? -1 : 1; + } + const companyOrder = left.companyName.localeCompare(right.companyName); + if (companyOrder !== 0) return companyOrder; + return left.agentName.localeCompare(right.agentName); + }); + res.json(items); + }); + router2.get("/companies/:companyId/org", async (req, res) => { + const companyId = req.params.companyId; + assertCompanyAccess(req, companyId); + const tree = await svc.orgForCompany(companyId); + const leanTree = tree.map((node) => toLeanOrgNode(node)); + res.json(leanTree); + }); + router2.get("/companies/:companyId/org.svg", async (req, res) => { + const companyId = req.params.companyId; + assertCompanyAccess(req, companyId); + const style = ORG_CHART_STYLES.includes(req.query.style) ? req.query.style : "warmth"; + const tree = await svc.orgForCompany(companyId); + const leanTree = tree.map((node) => toLeanOrgNode(node)); + const svg2 = renderOrgChartSvg(leanTree, style); + res.setHeader("Content-Type", "image/svg+xml"); + res.setHeader("Cache-Control", "no-cache"); + res.send(svg2); + }); + router2.get("/companies/:companyId/org.png", async (req, res) => { + const companyId = req.params.companyId; + assertCompanyAccess(req, companyId); + const style = ORG_CHART_STYLES.includes(req.query.style) ? req.query.style : "warmth"; + const tree = await svc.orgForCompany(companyId); + const leanTree = tree.map((node) => toLeanOrgNode(node)); + const png = await renderOrgChartPng(leanTree, style); + res.setHeader("Content-Type", "image/png"); + res.setHeader("Cache-Control", "no-cache"); + res.send(png); + }); + router2.get("/companies/:companyId/agent-configurations", async (req, res) => { + const companyId = req.params.companyId; + await assertCanReadConfigurations(req, companyId); + const rows = await svc.list(companyId); + res.json(rows.map((row) => redactAgentConfiguration(row))); + }); + router2.get("/agents/me", async (req, res) => { + if (req.actor.type !== "agent" || !req.actor.agentId) { + res.status(401).json({ error: "Agent authentication required" }); + return; + } + const agent = await svc.getById(req.actor.agentId); + if (!agent) { + res.status(404).json({ error: "Agent not found" }); + return; + } + res.json(await buildAgentDetail(agent)); + }); + router2.get("/agents/me/inbox-lite", async (req, res) => { + if (req.actor.type !== "agent" || !req.actor.agentId || !req.actor.companyId) { + res.status(401).json({ error: "Agent authentication required" }); + return; + } + const issuesSvc = issueService(db); + const rows = await issuesSvc.list(req.actor.companyId, { + assigneeAgentId: req.actor.agentId, + status: "todo,in_progress,blocked" + }); + res.json( + rows.map((issue2) => ({ + id: issue2.id, + identifier: issue2.identifier, + title: issue2.title, + status: issue2.status, + priority: issue2.priority, + projectId: issue2.projectId, + goalId: issue2.goalId, + parentId: issue2.parentId, + updatedAt: issue2.updatedAt, + activeRun: issue2.activeRun + })) + ); + }); + router2.get("/agents/me/inbox/mine", async (req, res) => { + if (req.actor.type !== "agent" || !req.actor.agentId || !req.actor.companyId) { + res.status(401).json({ error: "Agent authentication required" }); + return; + } + const query = agentMineInboxQuerySchema.parse(req.query); + const issuesSvc = issueService(db); + const rows = await issuesSvc.list(req.actor.companyId, { + touchedByUserId: query.userId, + inboxArchivedByUserId: query.userId, + status: query.status + }); + res.json(rows); + }); + router2.get("/agents/:id", async (req, res) => { + const id = req.params.id; + const agent = await svc.getById(id); + if (!agent) { + res.status(404).json({ error: "Agent not found" }); + return; + } + assertCompanyAccess(req, agent.companyId); + if (req.actor.type === "agent" && req.actor.agentId !== id) { + const canRead = await actorCanReadConfigurationsForCompany(req, agent.companyId); + if (!canRead) { + res.json(await buildAgentDetail(agent, { restricted: true })); + return; + } + } + res.json(await buildAgentDetail(agent)); + }); + router2.get("/agents/:id/configuration", async (req, res) => { + const id = req.params.id; + const agent = await svc.getById(id); + if (!agent) { + res.status(404).json({ error: "Agent not found" }); + return; + } + await assertCanReadConfigurations(req, agent.companyId); + res.json(redactAgentConfiguration(agent)); + }); + router2.get("/agents/:id/config-revisions", async (req, res) => { + const id = req.params.id; + const agent = await svc.getById(id); + if (!agent) { + res.status(404).json({ error: "Agent not found" }); + return; + } + await assertCanReadConfigurations(req, agent.companyId); + const revisions = await svc.listConfigRevisions(id); + res.json(revisions.map((revision) => redactConfigRevision(revision))); + }); + router2.get("/agents/:id/config-revisions/:revisionId", async (req, res) => { + const id = req.params.id; + const revisionId = req.params.revisionId; + const agent = await svc.getById(id); + if (!agent) { + res.status(404).json({ error: "Agent not found" }); + return; + } + await assertCanReadConfigurations(req, agent.companyId); + const revision = await svc.getConfigRevision(id, revisionId); + if (!revision) { + res.status(404).json({ error: "Revision not found" }); + return; + } + res.json(redactConfigRevision(revision)); + }); + router2.post("/agents/:id/config-revisions/:revisionId/rollback", async (req, res) => { + const id = req.params.id; + const revisionId = req.params.revisionId; + const existing = await svc.getById(id); + if (!existing) { + res.status(404).json({ error: "Agent not found" }); + return; + } + await assertCanUpdateAgent(req, existing); + const actor = getActorInfo(req); + const updated = await svc.rollbackConfigRevision(id, revisionId, { + agentId: actor.agentId, + userId: actor.actorType === "user" ? actor.actorId : null + }); + if (!updated) { + res.status(404).json({ error: "Revision not found" }); + return; + } + await logActivity(db, { + companyId: updated.companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + runId: actor.runId, + action: "agent.config_rolled_back", + entityType: "agent", + entityId: updated.id, + details: { revisionId } + }); + res.json(updated); + }); + router2.get("/agents/:id/runtime-state", async (req, res) => { + assertBoard(req); + const id = req.params.id; + const agent = await svc.getById(id); + if (!agent) { + res.status(404).json({ error: "Agent not found" }); + return; + } + assertCompanyAccess(req, agent.companyId); + const state2 = await heartbeat.getRuntimeState(id); + res.json(state2); + }); + router2.get("/agents/:id/task-sessions", async (req, res) => { + assertBoard(req); + const id = req.params.id; + const agent = await svc.getById(id); + if (!agent) { + res.status(404).json({ error: "Agent not found" }); + return; + } + assertCompanyAccess(req, agent.companyId); + const sessions = await heartbeat.listTaskSessions(id); + res.json( + sessions.map((session) => ({ + ...session, + sessionParamsJson: redactEventPayload(session.sessionParamsJson ?? null) + })) + ); + }); + router2.post("/agents/:id/runtime-state/reset-session", validate(resetAgentSessionSchema), async (req, res) => { + assertBoard(req); + const id = req.params.id; + const agent = await svc.getById(id); + if (!agent) { + res.status(404).json({ error: "Agent not found" }); + return; + } + assertCompanyAccess(req, agent.companyId); + const taskKey = typeof req.body.taskKey === "string" && req.body.taskKey.trim().length > 0 ? req.body.taskKey.trim() : null; + const state2 = await heartbeat.resetRuntimeSession(id, { taskKey }); + await logActivity(db, { + companyId: agent.companyId, + actorType: "user", + actorId: req.actor.userId ?? "board", + action: "agent.runtime_session_reset", + entityType: "agent", + entityId: id, + details: { taskKey: taskKey ?? null } + }); + res.json(state2); + }); + router2.post("/companies/:companyId/agent-hires", validate(createAgentHireSchema), async (req, res) => { + const companyId = req.params.companyId; + await assertCanCreateAgentsForCompany(req, companyId); + const sourceIssueIds = parseSourceIssueIds(req.body); + const { + desiredSkills: requestedDesiredSkills, + sourceIssueId: _sourceIssueId, + sourceIssueIds: _sourceIssueIds, + ...hireInput + } = req.body; + hireInput.adapterType = assertKnownAdapterType(hireInput.adapterType); + const requestedAdapterConfig = applyCreateDefaultsByAdapterType( + hireInput.adapterType, + hireInput.adapterConfig ?? {} + ); + const desiredSkillAssignment = await resolveDesiredSkillAssignment( + companyId, + hireInput.adapterType, + requestedAdapterConfig, + Array.isArray(requestedDesiredSkills) ? requestedDesiredSkills : void 0 + ); + const normalizedAdapterConfig = await secretsSvc.normalizeAdapterConfigForPersistence( + companyId, + desiredSkillAssignment.adapterConfig, + { strictMode: strictSecretsMode } + ); + await assertAdapterConfigConstraints( + companyId, + hireInput.adapterType, + normalizedAdapterConfig + ); + const normalizedHireInput = { + ...hireInput, + adapterConfig: normalizedAdapterConfig, + runtimeConfig: normalizeNewAgentRuntimeConfig(hireInput.runtimeConfig) + }; + const company = await db.select().from(companies).where(eq(companies.id, companyId)).then((rows) => rows[0] ?? null); + if (!company) { + res.status(404).json({ error: "Company not found" }); + return; + } + const requiresApproval = company.requireBoardApprovalForNewAgents; + const status = requiresApproval ? "pending_approval" : "idle"; + const createdAgent = await svc.create(companyId, { + ...normalizedHireInput, + status, + spentMonthlyCents: 0, + lastHeartbeatAt: null + }); + const agent = await materializeDefaultInstructionsBundleForNewAgent(createdAgent); + let approval = null; + const actor = getActorInfo(req); + if (requiresApproval) { + const requestedAdapterType = normalizedHireInput.adapterType ?? agent.adapterType; + const requestedAdapterConfig2 = redactEventPayload( + agent.adapterConfig ?? normalizedHireInput.adapterConfig + ) ?? {}; + const requestedRuntimeConfig = redactEventPayload( + normalizedHireInput.runtimeConfig ?? agent.runtimeConfig + ) ?? {}; + const requestedMetadata = redactEventPayload( + normalizedHireInput.metadata ?? agent.metadata ?? {} + ) ?? {}; + approval = await approvalsSvc.create(companyId, { + type: "hire_agent", + requestedByAgentId: actor.actorType === "agent" ? actor.actorId : null, + requestedByUserId: actor.actorType === "user" ? actor.actorId : null, + status: "pending", + payload: { + name: normalizedHireInput.name, + role: normalizedHireInput.role, + title: normalizedHireInput.title ?? null, + icon: normalizedHireInput.icon ?? null, + reportsTo: normalizedHireInput.reportsTo ?? null, + capabilities: normalizedHireInput.capabilities ?? null, + adapterType: requestedAdapterType, + adapterConfig: requestedAdapterConfig2, + runtimeConfig: requestedRuntimeConfig, + budgetMonthlyCents: typeof normalizedHireInput.budgetMonthlyCents === "number" ? normalizedHireInput.budgetMonthlyCents : agent.budgetMonthlyCents, + desiredSkills: desiredSkillAssignment.desiredSkills, + metadata: requestedMetadata, + agentId: agent.id, + requestedByAgentId: actor.actorType === "agent" ? actor.actorId : null, + requestedConfigurationSnapshot: { + adapterType: requestedAdapterType, + adapterConfig: requestedAdapterConfig2, + runtimeConfig: requestedRuntimeConfig, + desiredSkills: desiredSkillAssignment.desiredSkills + } + }, + decisionNote: null, + decidedByUserId: null, + decidedAt: null, + updatedAt: /* @__PURE__ */ new Date() + }); + if (sourceIssueIds.length > 0) { + await issueApprovalsSvc.linkManyForApproval(approval.id, sourceIssueIds, { + agentId: actor.actorType === "agent" ? actor.actorId : null, + userId: actor.actorType === "user" ? actor.actorId : null + }); + } + } + await logActivity(db, { + companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + runId: actor.runId, + action: "agent.hire_created", + entityType: "agent", + entityId: agent.id, + details: { + name: agent.name, + role: agent.role, + requiresApproval, + approvalId: approval?.id ?? null, + issueIds: sourceIssueIds, + desiredSkills: desiredSkillAssignment.desiredSkills + } + }); + const telemetryClient = getTelemetryClient(); + if (telemetryClient) { + trackAgentCreated(telemetryClient, { agentRole: agent.role, agentId: agent.id }); + } + await applyDefaultAgentTaskAssignGrant( + companyId, + agent.id, + actor.actorType === "user" ? actor.actorId : null + ); + if (approval) { + await logActivity(db, { + companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + runId: actor.runId, + action: "approval.created", + entityType: "approval", + entityId: approval.id, + details: { type: approval.type, linkedAgentId: agent.id } + }); + } + res.status(201).json({ agent, approval }); + }); + router2.post("/companies/:companyId/agents", validate(createAgentSchema), async (req, res) => { + const companyId = req.params.companyId; + assertCompanyAccess(req, companyId); + if (req.actor.type === "agent") { + assertBoard(req); + } + const { + desiredSkills: requestedDesiredSkills, + ...createInput + } = req.body; + createInput.adapterType = assertKnownAdapterType(createInput.adapterType); + const requestedAdapterConfig = applyCreateDefaultsByAdapterType( + createInput.adapterType, + createInput.adapterConfig ?? {} + ); + const desiredSkillAssignment = await resolveDesiredSkillAssignment( + companyId, + createInput.adapterType, + requestedAdapterConfig, + Array.isArray(requestedDesiredSkills) ? requestedDesiredSkills : void 0 + ); + const normalizedAdapterConfig = await secretsSvc.normalizeAdapterConfigForPersistence( + companyId, + desiredSkillAssignment.adapterConfig, + { strictMode: strictSecretsMode } + ); + await assertAdapterConfigConstraints( + companyId, + createInput.adapterType, + normalizedAdapterConfig + ); + const createdAgent = await svc.create(companyId, { + ...createInput, + adapterConfig: normalizedAdapterConfig, + runtimeConfig: normalizeNewAgentRuntimeConfig(createInput.runtimeConfig), + status: "idle", + spentMonthlyCents: 0, + lastHeartbeatAt: null + }); + const agent = await materializeDefaultInstructionsBundleForNewAgent(createdAgent); + const actor = getActorInfo(req); + await logActivity(db, { + companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + runId: actor.runId, + action: "agent.created", + entityType: "agent", + entityId: agent.id, + details: { + name: agent.name, + role: agent.role, + desiredSkills: desiredSkillAssignment.desiredSkills + } + }); + const telemetryClient = getTelemetryClient(); + if (telemetryClient) { + trackAgentCreated(telemetryClient, { agentRole: agent.role, agentId: agent.id }); + } + await applyDefaultAgentTaskAssignGrant( + companyId, + agent.id, + req.actor.type === "board" ? req.actor.userId ?? null : null + ); + if (agent.budgetMonthlyCents > 0) { + await budgets.upsertPolicy( + companyId, + { + scopeType: "agent", + scopeId: agent.id, + amount: agent.budgetMonthlyCents, + windowKind: "calendar_month_utc" + }, + actor.actorType === "user" ? actor.actorId : null + ); + } + res.status(201).json(agent); + }); + router2.patch("/agents/:id/permissions", validate(updateAgentPermissionsSchema), async (req, res) => { + const id = req.params.id; + const existing = await svc.getById(id); + if (!existing) { + res.status(404).json({ error: "Agent not found" }); + return; + } + assertCompanyAccess(req, existing.companyId); + if (req.actor.type === "agent") { + const actorAgent = req.actor.agentId ? await svc.getById(req.actor.agentId) : null; + if (!actorAgent || actorAgent.companyId !== existing.companyId) { + res.status(403).json({ error: "Forbidden" }); + return; + } + if (actorAgent.role !== "ceo") { + res.status(403).json({ error: "Only CEO can manage permissions" }); + return; + } + } + const agent = await svc.updatePermissions(id, req.body); + if (!agent) { + res.status(404).json({ error: "Agent not found" }); + return; + } + const effectiveCanAssignTasks = agent.role === "ceo" || Boolean(agent.permissions?.canCreateAgents) || req.body.canAssignTasks; + await access.ensureMembership(agent.companyId, "agent", agent.id, "member", "active"); + await access.setPrincipalPermission( + agent.companyId, + "agent", + agent.id, + "tasks:assign", + effectiveCanAssignTasks, + req.actor.type === "board" ? req.actor.userId ?? null : null + ); + const actor = getActorInfo(req); + await logActivity(db, { + companyId: agent.companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + runId: actor.runId, + action: "agent.permissions_updated", + entityType: "agent", + entityId: agent.id, + details: { + canCreateAgents: agent.permissions?.canCreateAgents ?? false, + canAssignTasks: effectiveCanAssignTasks + } + }); + res.json(await buildAgentDetail(agent)); + }); + router2.patch("/agents/:id/instructions-path", validate(updateAgentInstructionsPathSchema), async (req, res) => { + const id = req.params.id; + const existing = await svc.getById(id); + if (!existing) { + res.status(404).json({ error: "Agent not found" }); + return; + } + await assertCanManageInstructionsPath(req, existing); + const existingAdapterConfig = asRecord8(existing.adapterConfig) ?? {}; + const explicitKey = asNonEmptyString(req.body.adapterConfigKey); + const defaultKey = DEFAULT_INSTRUCTIONS_PATH_KEYS[existing.adapterType] ?? null; + const adapterConfigKey = explicitKey ?? defaultKey; + if (!adapterConfigKey) { + res.status(422).json({ + error: `No default instructions path key for adapter type '${existing.adapterType}'. Provide adapterConfigKey.` + }); + return; + } + const nextAdapterConfig = { ...existingAdapterConfig }; + if (req.body.path === null) { + delete nextAdapterConfig[adapterConfigKey]; + } else { + nextAdapterConfig[adapterConfigKey] = resolveInstructionsFilePath(req.body.path, existingAdapterConfig); + } + const syncedAdapterConfig = syncInstructionsBundleConfigFromFilePath(existing, nextAdapterConfig); + const normalizedAdapterConfig = await secretsSvc.normalizeAdapterConfigForPersistence( + existing.companyId, + syncedAdapterConfig, + { strictMode: strictSecretsMode } + ); + const actor = getActorInfo(req); + const agent = await svc.update( + id, + { adapterConfig: normalizedAdapterConfig }, + { + recordRevision: { + createdByAgentId: actor.agentId, + createdByUserId: actor.actorType === "user" ? actor.actorId : null, + source: "instructions_path_patch" + } + } + ); + if (!agent) { + res.status(404).json({ error: "Agent not found" }); + return; + } + const updatedAdapterConfig = asRecord8(agent.adapterConfig) ?? {}; + const pathValue = asNonEmptyString(updatedAdapterConfig[adapterConfigKey]); + await logActivity(db, { + companyId: agent.companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + runId: actor.runId, + action: "agent.instructions_path_updated", + entityType: "agent", + entityId: agent.id, + details: { + adapterConfigKey, + path: pathValue, + cleared: req.body.path === null + } + }); + res.json({ + agentId: agent.id, + adapterType: agent.adapterType, + adapterConfigKey, + path: pathValue + }); + }); + router2.get("/agents/:id/instructions-bundle", async (req, res) => { + const id = req.params.id; + const existing = await svc.getById(id); + if (!existing) { + res.status(404).json({ error: "Agent not found" }); + return; + } + await assertCanReadAgent(req, existing); + res.json(await instructions.getBundle(existing)); + }); + router2.patch("/agents/:id/instructions-bundle", validate(updateAgentInstructionsBundleSchema), async (req, res) => { + const id = req.params.id; + const existing = await svc.getById(id); + if (!existing) { + res.status(404).json({ error: "Agent not found" }); + return; + } + await assertCanManageInstructionsPath(req, existing); + const actor = getActorInfo(req); + const { bundle, adapterConfig } = await instructions.updateBundle(existing, req.body); + const normalizedAdapterConfig = await secretsSvc.normalizeAdapterConfigForPersistence( + existing.companyId, + adapterConfig, + { strictMode: strictSecretsMode } + ); + await svc.update( + id, + { adapterConfig: normalizedAdapterConfig }, + { + recordRevision: { + createdByAgentId: actor.agentId, + createdByUserId: actor.actorType === "user" ? actor.actorId : null, + source: "instructions_bundle_patch" + } + } + ); + await logActivity(db, { + companyId: existing.companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + runId: actor.runId, + action: "agent.instructions_bundle_updated", + entityType: "agent", + entityId: existing.id, + details: { + mode: bundle.mode, + rootPath: bundle.rootPath, + entryFile: bundle.entryFile, + clearLegacyPromptTemplate: req.body.clearLegacyPromptTemplate === true + } + }); + res.json(bundle); + }); + router2.get("/agents/:id/instructions-bundle/file", async (req, res) => { + const id = req.params.id; + const existing = await svc.getById(id); + if (!existing) { + res.status(404).json({ error: "Agent not found" }); + return; + } + await assertCanReadAgent(req, existing); + const relativePath = typeof req.query.path === "string" ? req.query.path : ""; + if (!relativePath.trim()) { + res.status(422).json({ error: "Query parameter 'path' is required" }); + return; + } + res.json(await instructions.readFile(existing, relativePath)); + }); + router2.put("/agents/:id/instructions-bundle/file", validate(upsertAgentInstructionsFileSchema), async (req, res) => { + const id = req.params.id; + const existing = await svc.getById(id); + if (!existing) { + res.status(404).json({ error: "Agent not found" }); + return; + } + await assertCanManageInstructionsPath(req, existing); + const actor = getActorInfo(req); + const result = await instructions.writeFile(existing, req.body.path, req.body.content, { + clearLegacyPromptTemplate: req.body.clearLegacyPromptTemplate + }); + const normalizedAdapterConfig = await secretsSvc.normalizeAdapterConfigForPersistence( + existing.companyId, + result.adapterConfig, + { strictMode: strictSecretsMode } + ); + await svc.update( + id, + { adapterConfig: normalizedAdapterConfig }, + { + recordRevision: { + createdByAgentId: actor.agentId, + createdByUserId: actor.actorType === "user" ? actor.actorId : null, + source: "instructions_bundle_file_put" + } + } + ); + await logActivity(db, { + companyId: existing.companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + runId: actor.runId, + action: "agent.instructions_file_updated", + entityType: "agent", + entityId: existing.id, + details: { + path: result.file.path, + size: result.file.size, + clearLegacyPromptTemplate: req.body.clearLegacyPromptTemplate === true + } + }); + res.json(result.file); + }); + router2.delete("/agents/:id/instructions-bundle/file", async (req, res) => { + const id = req.params.id; + const existing = await svc.getById(id); + if (!existing) { + res.status(404).json({ error: "Agent not found" }); + return; + } + await assertCanManageInstructionsPath(req, existing); + const relativePath = typeof req.query.path === "string" ? req.query.path : ""; + if (!relativePath.trim()) { + res.status(422).json({ error: "Query parameter 'path' is required" }); + return; + } + const actor = getActorInfo(req); + const result = await instructions.deleteFile(existing, relativePath); + await logActivity(db, { + companyId: existing.companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + runId: actor.runId, + action: "agent.instructions_file_deleted", + entityType: "agent", + entityId: existing.id, + details: { + path: relativePath + } + }); + res.json(result.bundle); + }); + router2.patch("/agents/:id", validate(updateAgentSchema), async (req, res) => { + const id = req.params.id; + const existing = await svc.getById(id); + if (!existing) { + res.status(404).json({ error: "Agent not found" }); + return; + } + await assertCanUpdateAgent(req, existing); + if (hasOwn(req.body, "permissions")) { + res.status(422).json({ error: "Use /api/agents/:id/permissions for permission changes" }); + return; + } + const patchData = { ...req.body }; + const replaceAdapterConfig = patchData.replaceAdapterConfig === true; + delete patchData.replaceAdapterConfig; + if (hasOwn(patchData, "adapterConfig")) { + const adapterConfig = asRecord8(patchData.adapterConfig); + if (!adapterConfig) { + res.status(422).json({ error: "adapterConfig must be an object" }); + return; + } + const changingInstructionsPath = Object.keys(adapterConfig).some( + (key) => KNOWN_INSTRUCTIONS_PATH_KEYS.has(key) + ); + if (changingInstructionsPath) { + await assertCanManageInstructionsPath(req, existing); + } + patchData.adapterConfig = adapterConfig; + } + const requestedAdapterType = hasOwn(patchData, "adapterType") ? assertKnownAdapterType(patchData.adapterType) : existing.adapterType; + const touchesAdapterConfiguration = hasOwn(patchData, "adapterType") || hasOwn(patchData, "adapterConfig"); + if (touchesAdapterConfiguration) { + const existingAdapterConfig = asRecord8(existing.adapterConfig) ?? {}; + const changingAdapterType = typeof patchData.adapterType === "string" && patchData.adapterType !== existing.adapterType; + const requestedAdapterConfig = hasOwn(patchData, "adapterConfig") ? asRecord8(patchData.adapterConfig) ?? {} : null; + if (requestedAdapterConfig && replaceAdapterConfig && KNOWN_INSTRUCTIONS_BUNDLE_KEYS.some( + (key) => existingAdapterConfig[key] !== void 0 && requestedAdapterConfig[key] === void 0 + )) { + await assertCanManageInstructionsPath(req, existing); + } + let rawEffectiveAdapterConfig = requestedAdapterConfig ?? existingAdapterConfig; + if (requestedAdapterConfig && !changingAdapterType && !replaceAdapterConfig) { + rawEffectiveAdapterConfig = { ...existingAdapterConfig, ...requestedAdapterConfig }; + } + if (changingAdapterType) { + const ADAPTER_AGNOSTIC_KEYS = [ + "env", + "cwd", + "timeoutSec", + "graceSec", + "promptTemplate", + "bootstrapPromptTemplate" + ]; + for (const key of ADAPTER_AGNOSTIC_KEYS) { + if (rawEffectiveAdapterConfig[key] === void 0 && existingAdapterConfig[key] !== void 0) { + rawEffectiveAdapterConfig = { ...rawEffectiveAdapterConfig, [key]: existingAdapterConfig[key] }; + } + } + rawEffectiveAdapterConfig = preserveInstructionsBundleConfig( + existingAdapterConfig, + rawEffectiveAdapterConfig + ); + } + const effectiveAdapterConfig = applyCreateDefaultsByAdapterType( + requestedAdapterType, + rawEffectiveAdapterConfig + ); + const normalizedEffectiveAdapterConfig = await secretsSvc.normalizeAdapterConfigForPersistence( + existing.companyId, + effectiveAdapterConfig, + { strictMode: strictSecretsMode } + ); + patchData.adapterConfig = syncInstructionsBundleConfigFromFilePath(existing, normalizedEffectiveAdapterConfig); + } + if (touchesAdapterConfiguration && requestedAdapterType === "opencode_local") { + const effectiveAdapterConfig = asRecord8(patchData.adapterConfig) ?? {}; + await assertAdapterConfigConstraints( + existing.companyId, + requestedAdapterType, + effectiveAdapterConfig + ); + } + const actor = getActorInfo(req); + const agent = await svc.update(id, patchData, { + recordRevision: { + createdByAgentId: actor.agentId, + createdByUserId: actor.actorType === "user" ? actor.actorId : null, + source: "patch" + } + }); + if (!agent) { + res.status(404).json({ error: "Agent not found" }); + return; + } + await logActivity(db, { + companyId: agent.companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + runId: actor.runId, + action: "agent.updated", + entityType: "agent", + entityId: agent.id, + details: summarizeAgentUpdateDetails(patchData) + }); + res.json(agent); + }); + router2.post("/agents/:id/pause", async (req, res) => { + assertBoard(req); + const id = req.params.id; + const agent = await svc.pause(id); + if (!agent) { + res.status(404).json({ error: "Agent not found" }); + return; + } + await heartbeat.cancelActiveForAgent(id); + await logActivity(db, { + companyId: agent.companyId, + actorType: "user", + actorId: req.actor.userId ?? "board", + action: "agent.paused", + entityType: "agent", + entityId: agent.id + }); + res.json(agent); + }); + router2.post("/agents/:id/resume", async (req, res) => { + assertBoard(req); + const id = req.params.id; + const agent = await svc.resume(id); + if (!agent) { + res.status(404).json({ error: "Agent not found" }); + return; + } + await logActivity(db, { + companyId: agent.companyId, + actorType: "user", + actorId: req.actor.userId ?? "board", + action: "agent.resumed", + entityType: "agent", + entityId: agent.id + }); + res.json(agent); + }); + router2.post("/agents/:id/terminate", async (req, res) => { + assertBoard(req); + const id = req.params.id; + const agent = await svc.terminate(id); + if (!agent) { + res.status(404).json({ error: "Agent not found" }); + return; + } + await heartbeat.cancelActiveForAgent(id); + await logActivity(db, { + companyId: agent.companyId, + actorType: "user", + actorId: req.actor.userId ?? "board", + action: "agent.terminated", + entityType: "agent", + entityId: agent.id + }); + res.json(agent); + }); + router2.delete("/agents/:id", async (req, res) => { + assertBoard(req); + const id = req.params.id; + const agent = await svc.remove(id); + if (!agent) { + res.status(404).json({ error: "Agent not found" }); + return; + } + await logActivity(db, { + companyId: agent.companyId, + actorType: "user", + actorId: req.actor.userId ?? "board", + action: "agent.deleted", + entityType: "agent", + entityId: agent.id + }); + res.json({ ok: true }); + }); + router2.get("/agents/:id/keys", async (req, res) => { + assertBoard(req); + const id = req.params.id; + const keys = await svc.listKeys(id); + res.json(keys); + }); + router2.post("/agents/:id/keys", validate(createAgentKeySchema), async (req, res) => { + assertBoard(req); + const id = req.params.id; + const key = await svc.createApiKey(id, req.body.name); + const agent = await svc.getById(id); + if (agent) { + await logActivity(db, { + companyId: agent.companyId, + actorType: "user", + actorId: req.actor.userId ?? "board", + action: "agent.key_created", + entityType: "agent", + entityId: agent.id, + details: { keyId: key.id, name: key.name } + }); + } + res.status(201).json(key); + }); + router2.delete("/agents/:id/keys/:keyId", async (req, res) => { + assertBoard(req); + const keyId = req.params.keyId; + const revoked = await svc.revokeKey(keyId); + if (!revoked) { + res.status(404).json({ error: "Key not found" }); + return; + } + res.json({ ok: true }); + }); + router2.post("/agents/:id/wakeup", validate(wakeAgentSchema), async (req, res) => { + const id = req.params.id; + const agent = await svc.getById(id); + if (!agent) { + res.status(404).json({ error: "Agent not found" }); + return; + } + assertCompanyAccess(req, agent.companyId); + if (req.actor.type === "agent" && req.actor.agentId !== id) { + res.status(403).json({ error: "Agent can only invoke itself" }); + return; + } + const run = await heartbeat.wakeup(id, { + source: req.body.source, + triggerDetail: req.body.triggerDetail ?? "manual", + reason: req.body.reason ?? null, + payload: req.body.payload ?? null, + idempotencyKey: req.body.idempotencyKey ?? null, + requestedByActorType: req.actor.type === "agent" ? "agent" : "user", + requestedByActorId: req.actor.type === "agent" ? req.actor.agentId ?? null : req.actor.userId ?? null, + contextSnapshot: { + triggeredBy: req.actor.type, + actorId: req.actor.type === "agent" ? req.actor.agentId : req.actor.userId, + forceFreshSession: req.body.forceFreshSession === true + } + }); + if (!run) { + res.status(202).json(await buildSkippedWakeupResponse(agent, req.body.payload ?? null)); + return; + } + const actor = getActorInfo(req); + await logActivity(db, { + companyId: agent.companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + runId: actor.runId, + action: "heartbeat.invoked", + entityType: "heartbeat_run", + entityId: run.id, + details: { agentId: id } + }); + res.status(202).json(run); + }); + router2.post("/agents/:id/heartbeat/invoke", async (req, res) => { + const id = req.params.id; + const agent = await svc.getById(id); + if (!agent) { + res.status(404).json({ error: "Agent not found" }); + return; + } + assertCompanyAccess(req, agent.companyId); + if (req.actor.type === "agent" && req.actor.agentId !== id) { + res.status(403).json({ error: "Agent can only invoke itself" }); + return; + } + const run = await heartbeat.invoke( + id, + "on_demand", + { + triggeredBy: req.actor.type, + actorId: req.actor.type === "agent" ? req.actor.agentId : req.actor.userId + }, + "manual", + { + actorType: req.actor.type === "agent" ? "agent" : "user", + actorId: req.actor.type === "agent" ? req.actor.agentId ?? null : req.actor.userId ?? null + } + ); + if (!run) { + res.status(202).json({ status: "skipped" }); + return; + } + const actor = getActorInfo(req); + await logActivity(db, { + companyId: agent.companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + runId: actor.runId, + action: "heartbeat.invoked", + entityType: "heartbeat_run", + entityId: run.id, + details: { agentId: id } + }); + res.status(202).json(run); + }); + router2.post("/agents/:id/claude-login", async (req, res) => { + assertBoard(req); + const id = req.params.id; + const agent = await svc.getById(id); + if (!agent) { + res.status(404).json({ error: "Agent not found" }); + return; + } + assertCompanyAccess(req, agent.companyId); + if (agent.adapterType !== "claude_local") { + res.status(400).json({ error: "Login is only supported for claude_local agents" }); + return; + } + const config3 = asRecord8(agent.adapterConfig) ?? {}; + const { config: runtimeConfig } = await secretsSvc.resolveAdapterConfigForRuntime(agent.companyId, config3); + const result = await runClaudeLogin({ + runId: `claude-login-${randomUUID7()}`, + agent: { + id: agent.id, + companyId: agent.companyId, + name: agent.name, + adapterType: agent.adapterType, + adapterConfig: agent.adapterConfig + }, + config: runtimeConfig + }); + res.json(result); + }); + router2.get("/companies/:companyId/heartbeat-runs", async (req, res) => { + const companyId = req.params.companyId; + assertCompanyAccess(req, companyId); + const agentId = req.query.agentId; + const limitParam = req.query.limit; + const limit = limitParam ? Math.max(1, Math.min(1e3, parseInt(limitParam, 10) || 200)) : void 0; + const runs = await heartbeat.list(companyId, agentId, limit); + res.json(runs); + }); + router2.get("/companies/:companyId/live-runs", async (req, res) => { + const companyId = req.params.companyId; + assertCompanyAccess(req, companyId); + const minCountParam = req.query.minCount; + const minCount = minCountParam ? Math.max(0, Math.min(20, parseInt(minCountParam, 10) || 0)) : 0; + const columns = { + id: heartbeatRuns.id, + status: heartbeatRuns.status, + invocationSource: heartbeatRuns.invocationSource, + triggerDetail: heartbeatRuns.triggerDetail, + startedAt: heartbeatRuns.startedAt, + finishedAt: heartbeatRuns.finishedAt, + createdAt: heartbeatRuns.createdAt, + agentId: heartbeatRuns.agentId, + agentName: agents.name, + adapterType: agents.adapterType, + issueId: sql`${heartbeatRuns.contextSnapshot} ->> 'issueId'`.as("issueId") + }; + const liveRuns = await db.select(columns).from(heartbeatRuns).innerJoin(agents, eq(heartbeatRuns.agentId, agents.id)).where( + and( + eq(heartbeatRuns.companyId, companyId), + inArray(heartbeatRuns.status, ["queued", "running"]) + ) + ).orderBy(desc(heartbeatRuns.createdAt)); + if (minCount > 0 && liveRuns.length < minCount) { + const activeIds = liveRuns.map((r5) => r5.id); + const recentRuns = await db.select(columns).from(heartbeatRuns).innerJoin(agents, eq(heartbeatRuns.agentId, agents.id)).where( + and( + eq(heartbeatRuns.companyId, companyId), + not(inArray(heartbeatRuns.status, ["queued", "running"])), + ...activeIds.length > 0 ? [not(inArray(heartbeatRuns.id, activeIds))] : [] + ) + ).orderBy(desc(heartbeatRuns.createdAt)).limit(minCount - liveRuns.length); + res.json([...liveRuns, ...recentRuns]); + return; + } + res.json(liveRuns); + }); + router2.get("/heartbeat-runs/:runId", async (req, res) => { + const runId = req.params.runId; + const run = await heartbeat.getRun(runId); + if (!run) { + res.status(404).json({ error: "Heartbeat run not found" }); + return; + } + assertCompanyAccess(req, run.companyId); + res.json(redactCurrentUserValue(run, await getCurrentUserRedactionOptions())); + }); + router2.post("/heartbeat-runs/:runId/cancel", async (req, res) => { + assertBoard(req); + const runId = req.params.runId; + const existing = await heartbeat.getRun(runId); + if (existing) { + assertCompanyAccess(req, existing.companyId); + } + const run = await heartbeat.cancelRun(runId); + if (run) { + await logActivity(db, { + companyId: run.companyId, + actorType: "user", + actorId: req.actor.userId ?? "board", + action: "heartbeat.cancelled", + entityType: "heartbeat_run", + entityId: run.id, + details: { agentId: run.agentId } + }); + } + res.json(run); + }); + router2.get("/heartbeat-runs/:runId/events", async (req, res) => { + const runId = req.params.runId; + const run = await heartbeat.getRun(runId); + if (!run) { + res.status(404).json({ error: "Heartbeat run not found" }); + return; + } + assertCompanyAccess(req, run.companyId); + const afterSeq = Number(req.query.afterSeq ?? 0); + const limit = Number(req.query.limit ?? 200); + const events = await heartbeat.listEvents(runId, Number.isFinite(afterSeq) ? afterSeq : 0, Number.isFinite(limit) ? limit : 200); + const currentUserRedactionOptions = await getCurrentUserRedactionOptions(); + const redactedEvents = events.map( + (event) => redactCurrentUserValue({ + ...event, + payload: redactEventPayload(event.payload) + }, currentUserRedactionOptions) + ); + res.json(redactedEvents); + }); + router2.get("/heartbeat-runs/:runId/log", async (req, res) => { + const runId = req.params.runId; + const run = await heartbeat.getRun(runId); + if (!run) { + res.status(404).json({ error: "Heartbeat run not found" }); + return; + } + assertCompanyAccess(req, run.companyId); + const offset = Number(req.query.offset ?? 0); + const limitBytes = Number(req.query.limitBytes ?? 256e3); + const result = await heartbeat.readLog(runId, { + offset: Number.isFinite(offset) ? offset : 0, + limitBytes: Number.isFinite(limitBytes) ? limitBytes : 256e3 + }); + res.json(result); + }); + router2.get("/heartbeat-runs/:runId/workspace-operations", async (req, res) => { + const runId = req.params.runId; + const run = await heartbeat.getRun(runId); + if (!run) { + res.status(404).json({ error: "Heartbeat run not found" }); + return; + } + assertCompanyAccess(req, run.companyId); + const context = asRecord8(run.contextSnapshot); + const executionWorkspaceId = asNonEmptyString(context?.executionWorkspaceId); + const operations = await workspaceOperations2.listForRun(runId, executionWorkspaceId); + res.json(redactCurrentUserValue(operations, await getCurrentUserRedactionOptions())); + }); + router2.get("/workspace-operations/:operationId/log", async (req, res) => { + const operationId = req.params.operationId; + const operation2 = await workspaceOperations2.getById(operationId); + if (!operation2) { + res.status(404).json({ error: "Workspace operation not found" }); + return; + } + assertCompanyAccess(req, operation2.companyId); + const offset = Number(req.query.offset ?? 0); + const limitBytes = Number(req.query.limitBytes ?? 256e3); + const result = await workspaceOperations2.readLog(operationId, { + offset: Number.isFinite(offset) ? offset : 0, + limitBytes: Number.isFinite(limitBytes) ? limitBytes : 256e3 + }); + res.json(result); + }); + router2.get("/issues/:issueId/live-runs", async (req, res) => { + const rawId = req.params.issueId; + const issueSvc = issueService(db); + const isIdentifier = /^[A-Z]+-\d+$/i.test(rawId); + const issue2 = isIdentifier ? await issueSvc.getByIdentifier(rawId) : await issueSvc.getById(rawId); + if (!issue2) { + res.status(404).json({ error: "Issue not found" }); + return; + } + assertCompanyAccess(req, issue2.companyId); + const liveRuns = await db.select({ + id: heartbeatRuns.id, + status: heartbeatRuns.status, + invocationSource: heartbeatRuns.invocationSource, + triggerDetail: heartbeatRuns.triggerDetail, + startedAt: heartbeatRuns.startedAt, + finishedAt: heartbeatRuns.finishedAt, + createdAt: heartbeatRuns.createdAt, + agentId: heartbeatRuns.agentId, + agentName: agents.name, + adapterType: agents.adapterType + }).from(heartbeatRuns).innerJoin(agents, eq(heartbeatRuns.agentId, agents.id)).where( + and( + eq(heartbeatRuns.companyId, issue2.companyId), + inArray(heartbeatRuns.status, ["queued", "running"]), + sql`${heartbeatRuns.contextSnapshot} ->> 'issueId' = ${issue2.id}` + ) + ).orderBy(desc(heartbeatRuns.createdAt)); + res.json(liveRuns); + }); + router2.get("/issues/:issueId/active-run", async (req, res) => { + const rawId = req.params.issueId; + const issueSvc = issueService(db); + const isIdentifier = /^[A-Z]+-\d+$/i.test(rawId); + const issue2 = isIdentifier ? await issueSvc.getByIdentifier(rawId) : await issueSvc.getById(rawId); + if (!issue2) { + res.status(404).json({ error: "Issue not found" }); + return; + } + assertCompanyAccess(req, issue2.companyId); + let run = issue2.executionRunId ? await heartbeat.getRunIssueSummary(issue2.executionRunId) : null; + if (run && (run.status !== "queued" && run.status !== "running" || run.issueId !== issue2.id)) { + run = null; + } + if (!run && issue2.assigneeAgentId && issue2.status === "in_progress") { + const candidateRun = await heartbeat.getActiveRunIssueSummaryForAgent(issue2.assigneeAgentId); + const candidateIssueId = asNonEmptyString(candidateRun?.issueId); + if (candidateRun && candidateIssueId === issue2.id) { + run = candidateRun; + } + } + if (!run) { + res.json(null); + return; + } + const agent = await svc.getById(run.agentId); + if (!agent) { + res.json(null); + return; + } + res.json({ + ...run, + agentId: agent.id, + agentName: agent.name, + adapterType: agent.adapterType + }); + }); + return router2; +} + +// server/src/routes/projects.ts +var import_express5 = __toESM(require_express2(), 1); +function projectRoutes(db) { + const router2 = (0, import_express5.Router)(); + const svc = projectService(db); + const secretsSvc = secretService(db); + const workspaceOperations2 = workspaceOperationService(db); + const strictSecretsMode = process.env.TASKCORE_SECRETS_STRICT_MODE === "true"; + async function resolveCompanyIdForProjectReference(req) { + const companyIdQuery = req.query.companyId; + const requestedCompanyId = typeof companyIdQuery === "string" && companyIdQuery.trim().length > 0 ? companyIdQuery.trim() : null; + if (requestedCompanyId) { + assertCompanyAccess(req, requestedCompanyId); + return requestedCompanyId; + } + if (req.actor.type === "agent" && req.actor.companyId) { + return req.actor.companyId; + } + return null; + } + async function normalizeProjectReference(req, rawId) { + if (isUuidLike(rawId)) return rawId; + const companyId = await resolveCompanyIdForProjectReference(req); + if (!companyId) return rawId; + const resolved = await svc.resolveByReference(companyId, rawId); + if (resolved.ambiguous) { + throw conflict("Project shortname is ambiguous in this company. Use the project ID."); + } + return resolved.project?.id ?? rawId; + } + router2.param("id", async (req, _res, next, rawId) => { + try { + req.params.id = await normalizeProjectReference(req, rawId); + next(); + } catch (err) { + next(err); + } + }); + router2.get("/companies/:companyId/projects", async (req, res) => { + const companyId = req.params.companyId; + assertCompanyAccess(req, companyId); + const result = await svc.list(companyId); + res.json(result); + }); + router2.get("/projects/:id", async (req, res) => { + const id = req.params.id; + const project = await svc.getById(id); + if (!project) { + res.status(404).json({ error: "Project not found" }); + return; + } + assertCompanyAccess(req, project.companyId); + res.json(project); + }); + router2.post("/companies/:companyId/projects", validate(createProjectSchema), async (req, res) => { + const companyId = req.params.companyId; + assertCompanyAccess(req, companyId); + const { workspace, ...projectData } = req.body; + if (projectData.env !== void 0) { + projectData.env = await secretsSvc.normalizeEnvBindingsForPersistence( + companyId, + projectData.env, + { strictMode: strictSecretsMode, fieldPath: "env" } + ); + } + const project = await svc.create(companyId, projectData); + let createdWorkspaceId = null; + if (workspace) { + const createdWorkspace = await svc.createWorkspace(project.id, workspace); + if (!createdWorkspace) { + await svc.remove(project.id); + res.status(422).json({ error: "Invalid project workspace payload" }); + return; + } + createdWorkspaceId = createdWorkspace.id; + } + const hydratedProject = workspace ? await svc.getById(project.id) : project; + const actor = getActorInfo(req); + await logActivity(db, { + companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + action: "project.created", + entityType: "project", + entityId: project.id, + details: { + name: project.name, + workspaceId: createdWorkspaceId, + envKeys: project.env ? Object.keys(project.env).sort() : [] + } + }); + const telemetryClient = getTelemetryClient(); + if (telemetryClient) { + trackProjectCreated(telemetryClient); + } + res.status(201).json(hydratedProject ?? project); + }); + router2.patch("/projects/:id", validate(updateProjectSchema), async (req, res) => { + const id = req.params.id; + const existing = await svc.getById(id); + if (!existing) { + res.status(404).json({ error: "Project not found" }); + return; + } + assertCompanyAccess(req, existing.companyId); + const body = { ...req.body }; + if (typeof body.archivedAt === "string") { + body.archivedAt = new Date(body.archivedAt); + } + if (body.env !== void 0) { + body.env = await secretsSvc.normalizeEnvBindingsForPersistence(existing.companyId, body.env, { + strictMode: strictSecretsMode, + fieldPath: "env" + }); + } + const project = await svc.update(id, body); + if (!project) { + res.status(404).json({ error: "Project not found" }); + return; + } + const actor = getActorInfo(req); + await logActivity(db, { + companyId: project.companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + action: "project.updated", + entityType: "project", + entityId: project.id, + details: { + changedKeys: Object.keys(req.body).sort(), + envKeys: body.env && typeof body.env === "object" && !Array.isArray(body.env) ? Object.keys(body.env).sort() : void 0 + } + }); + res.json(project); + }); + router2.get("/projects/:id/workspaces", async (req, res) => { + const id = req.params.id; + const existing = await svc.getById(id); + if (!existing) { + res.status(404).json({ error: "Project not found" }); + return; + } + assertCompanyAccess(req, existing.companyId); + const workspaces = await svc.listWorkspaces(id); + res.json(workspaces); + }); + router2.post("/projects/:id/workspaces", validate(createProjectWorkspaceSchema), async (req, res) => { + const id = req.params.id; + const existing = await svc.getById(id); + if (!existing) { + res.status(404).json({ error: "Project not found" }); + return; + } + assertCompanyAccess(req, existing.companyId); + const workspace = await svc.createWorkspace(id, req.body); + if (!workspace) { + res.status(422).json({ error: "Invalid project workspace payload" }); + return; + } + const actor = getActorInfo(req); + await logActivity(db, { + companyId: existing.companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + action: "project.workspace_created", + entityType: "project", + entityId: id, + details: { + workspaceId: workspace.id, + name: workspace.name, + cwd: workspace.cwd, + isPrimary: workspace.isPrimary + } + }); + res.status(201).json(workspace); + }); + router2.patch( + "/projects/:id/workspaces/:workspaceId", + validate(updateProjectWorkspaceSchema), + async (req, res) => { + const id = req.params.id; + const workspaceId = req.params.workspaceId; + const existing = await svc.getById(id); + if (!existing) { + res.status(404).json({ error: "Project not found" }); + return; + } + assertCompanyAccess(req, existing.companyId); + const workspaceExists = (await svc.listWorkspaces(id)).some((workspace2) => workspace2.id === workspaceId); + if (!workspaceExists) { + res.status(404).json({ error: "Project workspace not found" }); + return; + } + const workspace = await svc.updateWorkspace(id, workspaceId, req.body); + if (!workspace) { + res.status(422).json({ error: "Invalid project workspace payload" }); + return; + } + const actor = getActorInfo(req); + await logActivity(db, { + companyId: existing.companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + action: "project.workspace_updated", + entityType: "project", + entityId: id, + details: { + workspaceId: workspace.id, + changedKeys: Object.keys(req.body).sort() + } + }); + res.json(workspace); + } + ); + async function handleProjectWorkspaceRuntimeCommand(req, res) { + const id = req.params.id; + const workspaceId = req.params.workspaceId; + const action = String(req.params.action ?? "").trim().toLowerCase(); + if (action !== "start" && action !== "stop" && action !== "restart" && action !== "run") { + res.status(404).json({ error: "Workspace command action not found" }); + return; + } + const project = await svc.getById(id); + if (!project) { + res.status(404).json({ error: "Project not found" }); + return; + } + assertCompanyAccess(req, project.companyId); + const workspace = project.workspaces.find((entry) => entry.id === workspaceId) ?? null; + if (!workspace) { + res.status(404).json({ error: "Project workspace not found" }); + return; + } + const workspaceCwd = workspace.cwd; + if (!workspaceCwd) { + res.status(422).json({ error: "Project workspace needs a local path before Taskcore can run workspace commands" }); + return; + } + const runtimeConfig = workspace.runtimeConfig?.workspaceRuntime ?? null; + const target = req.body; + const configuredServices = runtimeConfig ? listConfiguredRuntimeServiceEntries({ workspaceRuntime: runtimeConfig }) : []; + const workspaceCommand = runtimeConfig ? findWorkspaceCommandDefinition(runtimeConfig, target.workspaceCommandId ?? null) : null; + if (target.workspaceCommandId && !workspaceCommand) { + res.status(404).json({ error: "Workspace command not found for this project workspace" }); + return; + } + if (target.runtimeServiceId && !(workspace.runtimeServices ?? []).some((service) => service.id === target.runtimeServiceId)) { + res.status(404).json({ error: "Runtime service not found for this project workspace" }); + return; + } + const matchedRuntimeService = workspaceCommand?.kind === "service" && !target.runtimeServiceId ? matchWorkspaceRuntimeServiceToCommand(workspaceCommand, workspace.runtimeServices ?? []) : null; + const selectedRuntimeServiceId = target.runtimeServiceId ?? matchedRuntimeService?.id ?? null; + const selectedServiceIndex = workspaceCommand?.kind === "service" ? workspaceCommand.serviceIndex : target.serviceIndex ?? null; + if (selectedServiceIndex !== void 0 && selectedServiceIndex !== null && (selectedServiceIndex < 0 || selectedServiceIndex >= configuredServices.length)) { + res.status(422).json({ error: "Selected runtime service is not defined in this project workspace runtime config" }); + return; + } + if (workspaceCommand?.kind === "job" && action !== "run") { + res.status(422).json({ error: `Workspace job "${workspaceCommand.name}" can only be run` }); + return; + } + if (workspaceCommand?.kind === "service" && action === "run") { + res.status(422).json({ error: `Workspace service "${workspaceCommand.name}" should be started or restarted, not run` }); + return; + } + if (action === "run" && !workspaceCommand) { + res.status(422).json({ error: "Select a workspace job to run" }); + return; + } + if ((action === "start" || action === "restart") && !runtimeConfig) { + res.status(422).json({ error: "Project workspace has no workspace command configuration" }); + return; + } + const actor = getActorInfo(req); + const recorder = workspaceOperations2.createRecorder({ companyId: project.companyId }); + let runtimeServiceCount = workspace.runtimeServices?.length ?? 0; + const stdout = []; + const stderr = []; + const operation2 = await recorder.recordOperation({ + phase: action === "stop" ? "workspace_teardown" : "workspace_provision", + command: workspaceCommand?.command ?? `workspace command ${action}`, + cwd: workspace.cwd, + metadata: { + action, + projectId: project.id, + projectWorkspaceId: workspace.id, + workspaceCommandId: workspaceCommand?.id ?? target.workspaceCommandId ?? null, + workspaceCommandKind: workspaceCommand?.kind ?? null, + workspaceCommandName: workspaceCommand?.name ?? null, + runtimeServiceId: selectedRuntimeServiceId, + serviceIndex: selectedServiceIndex + }, + run: async () => { + if (action === "run") { + if (!workspaceCommand || workspaceCommand.kind !== "job") { + throw new Error("Workspace job selection is required"); + } + return await runWorkspaceJobForControl({ + actor: { + id: actor.agentId ?? null, + name: actor.actorType === "user" ? "Board" : "Agent", + companyId: project.companyId + }, + issue: null, + workspace: { + baseCwd: workspaceCwd, + source: "project_primary", + projectId: project.id, + workspaceId: workspace.id, + repoUrl: workspace.repoUrl, + repoRef: workspace.repoRef, + strategy: "project_primary", + cwd: workspaceCwd, + branchName: workspace.defaultRef ?? workspace.repoRef ?? null, + worktreePath: null, + warnings: [], + created: false + }, + command: workspaceCommand.rawConfig, + adapterEnv: {}, + recorder, + metadata: { + action, + projectId: project.id, + projectWorkspaceId: workspace.id, + workspaceCommandId: workspaceCommand.id + } + }).then((nestedOperation) => ({ + status: "succeeded", + exitCode: 0, + metadata: { + nestedOperationId: nestedOperation?.id ?? null, + runtimeServiceCount + } + })); + } + const onLog = async (stream, chunk) => { + if (stream === "stdout") stdout.push(chunk); + else stderr.push(chunk); + }; + if (action === "stop" || action === "restart") { + await stopRuntimeServicesForProjectWorkspace({ + db, + projectWorkspaceId: workspace.id, + runtimeServiceId: selectedRuntimeServiceId + }); + } + if (action === "start" || action === "restart") { + const startedServices = await startRuntimeServicesForWorkspaceControl({ + db, + actor: { + id: actor.agentId ?? null, + name: actor.actorType === "user" ? "Board" : "Agent", + companyId: project.companyId + }, + issue: null, + workspace: { + baseCwd: workspaceCwd, + source: "project_primary", + projectId: project.id, + workspaceId: workspace.id, + repoUrl: workspace.repoUrl, + repoRef: workspace.repoRef, + strategy: "project_primary", + cwd: workspaceCwd, + branchName: workspace.defaultRef ?? workspace.repoRef ?? null, + worktreePath: null, + warnings: [], + created: false + }, + config: { workspaceRuntime: runtimeConfig }, + adapterEnv: {}, + onLog, + serviceIndex: selectedServiceIndex + }); + runtimeServiceCount = startedServices.length; + } else { + runtimeServiceCount = selectedRuntimeServiceId ? Math.max(0, (workspace.runtimeServices?.length ?? 1) - 1) : 0; + } + const currentDesiredState = workspace.runtimeConfig?.desiredState ?? ((workspace.runtimeServices ?? []).some((service) => service.status === "starting" || service.status === "running") ? "running" : "stopped"); + const nextRuntimeState = selectedRuntimeServiceId && (selectedServiceIndex === void 0 || selectedServiceIndex === null) ? { + desiredState: currentDesiredState, + serviceStates: workspace.runtimeConfig?.serviceStates ?? null + } : buildWorkspaceRuntimeDesiredStatePatch({ + config: { workspaceRuntime: runtimeConfig }, + currentDesiredState, + currentServiceStates: workspace.runtimeConfig?.serviceStates ?? null, + action, + serviceIndex: selectedServiceIndex + }); + await svc.updateWorkspace(project.id, workspace.id, { + runtimeConfig: { + desiredState: nextRuntimeState.desiredState, + serviceStates: nextRuntimeState.serviceStates + } + }); + return { + status: "succeeded", + stdout: stdout.join(""), + stderr: stderr.join(""), + system: action === "stop" ? "Stopped project workspace runtime services.\n" : action === "restart" ? "Restarted project workspace runtime services.\n" : "Started project workspace runtime services.\n", + metadata: { + runtimeServiceCount, + workspaceCommandId: workspaceCommand?.id ?? target.workspaceCommandId ?? null, + runtimeServiceId: selectedRuntimeServiceId, + serviceIndex: selectedServiceIndex + } + }; + } + }); + const updatedWorkspace = (await svc.listWorkspaces(project.id)).find((entry) => entry.id === workspace.id) ?? workspace; + await logActivity(db, { + companyId: project.companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + action: `project.workspace_runtime_${action}`, + entityType: "project", + entityId: project.id, + details: { + projectWorkspaceId: workspace.id, + runtimeServiceCount, + workspaceCommandId: workspaceCommand?.id ?? target.workspaceCommandId ?? null, + workspaceCommandKind: workspaceCommand?.kind ?? null, + workspaceCommandName: workspaceCommand?.name ?? null, + runtimeServiceId: selectedRuntimeServiceId, + serviceIndex: selectedServiceIndex + } + }); + res.json({ + workspace: updatedWorkspace, + operation: operation2 + }); + } + router2.post("/projects/:id/workspaces/:workspaceId/runtime-services/:action", validate(workspaceRuntimeControlTargetSchema), handleProjectWorkspaceRuntimeCommand); + router2.post("/projects/:id/workspaces/:workspaceId/runtime-commands/:action", validate(workspaceRuntimeControlTargetSchema), handleProjectWorkspaceRuntimeCommand); + router2.delete("/projects/:id/workspaces/:workspaceId", async (req, res) => { + const id = req.params.id; + const workspaceId = req.params.workspaceId; + const existing = await svc.getById(id); + if (!existing) { + res.status(404).json({ error: "Project not found" }); + return; + } + assertCompanyAccess(req, existing.companyId); + const workspace = await svc.removeWorkspace(id, workspaceId); + if (!workspace) { + res.status(404).json({ error: "Project workspace not found" }); + return; + } + const actor = getActorInfo(req); + await logActivity(db, { + companyId: existing.companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + action: "project.workspace_deleted", + entityType: "project", + entityId: id, + details: { + workspaceId: workspace.id, + name: workspace.name + } + }); + res.json(workspace); + }); + router2.delete("/projects/:id", async (req, res) => { + const id = req.params.id; + const existing = await svc.getById(id); + if (!existing) { + res.status(404).json({ error: "Project not found" }); + return; + } + assertCompanyAccess(req, existing.companyId); + const project = await svc.remove(id); + if (!project) { + res.status(404).json({ error: "Project not found" }); + return; + } + const actor = getActorInfo(req); + await logActivity(db, { + companyId: project.companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + action: "project.deleted", + entityType: "project", + entityId: project.id + }); + res.json(project); + }); + return router2; +} + +// server/src/routes/issues.ts +var import_express6 = __toESM(require_express2(), 1); +var import_multer = __toESM(require_multer(), 1); +import { randomUUID as randomUUID9 } from "node:crypto"; +init_src2(); + +// server/src/routes/issues-checkout-wakeup.ts +function shouldWakeAssigneeOnCheckout(input) { + if (input.actorType !== "agent") return true; + if (!input.actorAgentId) return true; + if (input.actorAgentId !== input.checkoutAgentId) return true; + if (!input.checkoutRunId) return true; + return false; +} + +// server/src/attachment-types.ts +var DEFAULT_ALLOWED_TYPES = [ + "image/png", + "image/jpeg", + "image/jpg", + "image/webp", + "image/gif", + "application/pdf", + "text/markdown", + "text/plain", + "application/json", + "text/csv", + "text/html" +]; +var DEFAULT_ATTACHMENT_CONTENT_TYPE = "application/octet-stream"; +var SVG_CONTENT_TYPE = "image/svg+xml"; +var INLINE_ATTACHMENT_TYPES = [ + "image/*", + "application/pdf", + "text/plain", + "text/markdown", + "application/json", + "text/csv" +]; +function parseAllowedTypes(raw) { + if (!raw) return [...DEFAULT_ALLOWED_TYPES]; + const parsed = raw.split(",").map((s5) => s5.trim().toLowerCase()).filter((s5) => s5.length > 0); + return parsed.length > 0 ? parsed : [...DEFAULT_ALLOWED_TYPES]; +} +function matchesContentType(contentType, allowedPatterns2) { + const ct = contentType.toLowerCase(); + return allowedPatterns2.some((pattern) => { + if (pattern === "*") return true; + if (pattern.endsWith("/*") || pattern.endsWith(".*")) { + return ct.startsWith(pattern.slice(0, -1)); + } + return ct === pattern; + }); +} +function normalizeContentType(contentType) { + const normalized = (contentType ?? "").trim().toLowerCase(); + return normalized || DEFAULT_ATTACHMENT_CONTENT_TYPE; +} +function isInlineAttachmentContentType(contentType) { + return matchesContentType(contentType, [...INLINE_ATTACHMENT_TYPES]); +} +var allowedPatterns = parseAllowedTypes( + process.env.TASKCORE_ALLOWED_ATTACHMENT_TYPES +); +function isAllowedContentType(contentType) { + return matchesContentType(contentType, allowedPatterns); +} +var MAX_ATTACHMENT_BYTES = Number(process.env.TASKCORE_ATTACHMENT_MAX_BYTES) || 10 * 1024 * 1024; + +// server/src/services/issue-execution-policy.ts +import { randomUUID as randomUUID8 } from "node:crypto"; +var COMPLETED_STATUS = "completed"; +var PENDING_STATUS = "pending"; +var CHANGES_REQUESTED_STATUS = "changes_requested"; +function normalizeIssueExecutionPolicy(input) { + if (input == null) return null; + const parsed = issueExecutionPolicySchema.safeParse(input); + if (!parsed.success) { + throw unprocessable("Invalid execution policy", parsed.error.flatten()); + } + const stages = parsed.data.stages.map((stage) => { + const participants = stage.participants.map((participant) => ({ + id: participant.id ?? randomUUID8(), + type: participant.type, + agentId: participant.type === "agent" ? participant.agentId ?? null : null, + userId: participant.type === "user" ? participant.userId ?? null : null + })).filter((participant) => participant.type === "agent" ? Boolean(participant.agentId) : Boolean(participant.userId)); + const dedupedParticipants = []; + const seen = /* @__PURE__ */ new Set(); + for (const participant of participants) { + const key = participant.type === "agent" ? `agent:${participant.agentId}` : `user:${participant.userId}`; + if (seen.has(key)) continue; + seen.add(key); + dedupedParticipants.push(participant); + } + if (dedupedParticipants.length === 0) return null; + return { + id: stage.id ?? randomUUID8(), + type: stage.type, + approvalsNeeded: 1, + participants: dedupedParticipants + }; + }).filter((stage) => stage !== null); + if (stages.length === 0) return null; + return { + mode: parsed.data.mode ?? "normal", + commentRequired: true, + stages + }; +} +function parseIssueExecutionState(input) { + if (input == null) return null; + const parsed = issueExecutionStateSchema.safeParse(input); + if (!parsed.success) return null; + return parsed.data; +} +function assigneePrincipal(input) { + if (input.assigneeAgentId) { + return { type: "agent", agentId: input.assigneeAgentId, userId: null }; + } + if (input.assigneeUserId) { + return { type: "user", userId: input.assigneeUserId, agentId: null }; + } + return null; +} +function actorPrincipal(actor) { + if (actor.agentId) return { type: "agent", agentId: actor.agentId, userId: null }; + if (actor.userId) return { type: "user", userId: actor.userId, agentId: null }; + return null; +} +function principalsEqual(a5, b6) { + if (!a5 || !b6) return false; + if (a5.type !== b6.type) return false; + return a5.type === "agent" ? a5.agentId === b6.agentId : a5.userId === b6.userId; +} +function findStageById(policy, stageId) { + if (!stageId) return null; + return policy.stages.find((stage) => stage.id === stageId) ?? null; +} +function nextPendingStage(policy, state2) { + const completed = new Set(state2?.completedStageIds ?? []); + return policy.stages.find((stage) => !completed.has(stage.id)) ?? null; +} +function selectStageParticipant(stage, opts) { + const participants = stage.participants.filter((participant) => !principalsEqual(participant, opts?.exclude ?? null)); + if (participants.length === 0) return null; + if (opts?.preferred) { + const preferred = participants.find((participant) => principalsEqual(participant, opts.preferred ?? null)); + if (preferred) return preferred; + } + const first = participants[0]; + return first ? { type: first.type, agentId: first.agentId ?? null, userId: first.userId ?? null } : null; +} +function stageHasParticipant(stage, participant) { + if (!participant) return false; + return stage.participants.some((candidate) => principalsEqual(candidate, participant)); +} +function patchForPrincipal(principal) { + if (!principal) { + return { assigneeAgentId: null, assigneeUserId: null }; + } + return principal.type === "agent" ? { assigneeAgentId: principal.agentId ?? null, assigneeUserId: null } : { assigneeAgentId: null, assigneeUserId: principal.userId ?? null }; +} +function buildCompletedState(previous, currentStage) { + const completedStageIds = Array.from(/* @__PURE__ */ new Set([...previous?.completedStageIds ?? [], currentStage.id])); + return { + status: COMPLETED_STATUS, + currentStageId: null, + currentStageIndex: null, + currentStageType: null, + currentParticipant: null, + returnAssignee: previous?.returnAssignee ?? null, + completedStageIds, + lastDecisionId: previous?.lastDecisionId ?? null, + lastDecisionOutcome: "approved" + }; +} +function buildStateWithCompletedStages(input) { + return { + status: input.previous?.status ?? PENDING_STATUS, + currentStageId: input.previous?.currentStageId ?? null, + currentStageIndex: input.previous?.currentStageIndex ?? null, + currentStageType: input.previous?.currentStageType ?? null, + currentParticipant: input.previous?.currentParticipant ?? null, + returnAssignee: input.previous?.returnAssignee ?? input.returnAssignee, + completedStageIds: input.completedStageIds, + lastDecisionId: input.previous?.lastDecisionId ?? null, + lastDecisionOutcome: input.previous?.lastDecisionOutcome ?? null + }; +} +function buildSkippedStageCompletedState(input) { + return { + status: COMPLETED_STATUS, + currentStageId: null, + currentStageIndex: null, + currentStageType: null, + currentParticipant: null, + returnAssignee: input.previous?.returnAssignee ?? input.returnAssignee, + completedStageIds: input.completedStageIds, + lastDecisionId: input.previous?.lastDecisionId ?? null, + lastDecisionOutcome: input.previous?.lastDecisionOutcome ?? null + }; +} +function buildPendingState(input) { + return { + status: PENDING_STATUS, + currentStageId: input.stage.id, + currentStageIndex: input.stageIndex, + currentStageType: input.stage.type, + currentParticipant: input.participant, + returnAssignee: input.returnAssignee, + completedStageIds: input.previous?.completedStageIds ?? [], + lastDecisionId: input.previous?.lastDecisionId ?? null, + lastDecisionOutcome: input.previous?.lastDecisionOutcome ?? null + }; +} +function buildChangesRequestedState(previous, currentStage) { + return { + ...previous, + status: CHANGES_REQUESTED_STATUS, + currentStageId: currentStage.id, + currentStageType: currentStage.type, + lastDecisionOutcome: "changes_requested" + }; +} +function buildPendingStagePatch(input) { + input.patch.status = "in_review"; + Object.assign(input.patch, patchForPrincipal(input.participant)); + input.patch.executionState = buildPendingState({ + previous: input.previous, + stage: input.stage, + stageIndex: input.policy.stages.findIndex((candidate) => candidate.id === input.stage.id), + participant: input.participant, + returnAssignee: input.returnAssignee + }); +} +function clearExecutionStatePatch(input) { + input.patch.executionState = null; + if (input.requestedStatus === void 0 && input.issueStatus === "in_review" && input.returnAssignee) { + input.patch.status = "in_progress"; + Object.assign(input.patch, patchForPrincipal(input.returnAssignee)); + } +} +function canAutoSkipPendingStage(input) { + if (input.requestedStatus !== "done" || input.stage.type !== "review" || !input.returnAssignee) { + return false; + } + return input.stage.participants.length > 0 && input.stage.participants.every((participant) => principalsEqual(participant, input.returnAssignee)); +} +function applyIssueExecutionPolicyTransition(input) { + const patch = {}; + const existingState = parseIssueExecutionState(input.issue.executionState); + const currentAssignee = assigneePrincipal(input.issue); + const actor = actorPrincipal(input.actor); + const requestedAssigneePatchProvided = input.requestedAssigneePatch.assigneeAgentId !== void 0 || input.requestedAssigneePatch.assigneeUserId !== void 0; + const explicitAssignee = assigneePrincipal(input.requestedAssigneePatch); + const currentStage = input.policy ? findStageById(input.policy, existingState?.currentStageId) : null; + const requestedStatus = input.requestedStatus; + const activeStage = currentStage && existingState?.status === PENDING_STATUS ? currentStage : null; + if (!input.policy) { + if (existingState) { + patch.executionState = null; + if (input.issue.status === "in_review" && existingState.returnAssignee) { + patch.status = "in_progress"; + Object.assign(patch, patchForPrincipal(existingState.returnAssignee)); + } + } + return { patch }; + } + if ((input.issue.status === "done" || input.issue.status === "cancelled") && requestedStatus && requestedStatus !== "done" && requestedStatus !== "cancelled") { + patch.executionState = null; + return { patch }; + } + if (existingState?.currentStageId && !currentStage) { + clearExecutionStatePatch({ + patch, + issueStatus: input.issue.status, + requestedStatus, + returnAssignee: existingState.returnAssignee + }); + return { patch }; + } + if (activeStage) { + const currentParticipant = existingState?.currentParticipant ?? selectStageParticipant(activeStage, { + exclude: existingState?.returnAssignee ?? null + }); + if (!currentParticipant) { + throw unprocessable(`No eligible ${activeStage.type} participant is configured for this issue`); + } + if (!stageHasParticipant(activeStage, currentParticipant)) { + const participant2 = selectStageParticipant(activeStage, { + preferred: explicitAssignee ?? existingState?.currentParticipant ?? null, + exclude: existingState?.returnAssignee ?? null + }); + if (!participant2) { + clearExecutionStatePatch({ + patch, + issueStatus: input.issue.status, + requestedStatus, + returnAssignee: existingState?.returnAssignee ?? null + }); + return { patch }; + } + buildPendingStagePatch({ + patch, + previous: existingState, + policy: input.policy, + stage: activeStage, + participant: participant2, + returnAssignee: existingState?.returnAssignee ?? currentAssignee ?? actor + }); + return { + patch, + workflowControlledAssignment: true + }; + } + if (principalsEqual(currentParticipant, actor)) { + if (requestedStatus === "done") { + if (!input.commentBody?.trim()) { + throw unprocessable("Approving a review or approval stage requires a comment"); + } + const approvedState = buildCompletedState(existingState, activeStage); + const nextStage = nextPendingStage( + input.policy, + { ...approvedState, completedStageIds: approvedState.completedStageIds } + ); + if (!nextStage) { + patch.executionState = approvedState; + return { + patch, + decision: { + stageId: activeStage.id, + stageType: activeStage.type, + outcome: "approved", + body: input.commentBody.trim() + } + }; + } + const participant2 = selectStageParticipant(nextStage, { + preferred: explicitAssignee, + exclude: existingState?.returnAssignee ?? null + }); + if (!participant2) { + throw unprocessable(`No eligible ${nextStage.type} participant is configured for this issue`); + } + buildPendingStagePatch({ + patch, + previous: approvedState, + policy: input.policy, + stage: nextStage, + participant: participant2, + returnAssignee: existingState?.returnAssignee ?? currentAssignee ?? actor + }); + return { + patch, + decision: { + stageId: activeStage.id, + stageType: activeStage.type, + outcome: "approved", + body: input.commentBody.trim() + }, + workflowControlledAssignment: true + }; + } + if (requestedStatus && requestedStatus !== "in_review") { + if (!input.commentBody?.trim()) { + throw unprocessable("Requesting changes requires a comment"); + } + if (!existingState?.returnAssignee) { + throw unprocessable("This execution stage has no return assignee"); + } + patch.status = "in_progress"; + Object.assign(patch, patchForPrincipal(existingState.returnAssignee)); + patch.executionState = buildChangesRequestedState(existingState, activeStage); + return { + patch, + decision: { + stageId: activeStage.id, + stageType: activeStage.type, + outcome: "changes_requested", + body: input.commentBody.trim() + }, + workflowControlledAssignment: true + }; + } + } + const attemptedStageAdvance = requestedStatus !== void 0 && requestedStatus !== "in_review" || requestedAssigneePatchProvided && !principalsEqual(explicitAssignee, currentParticipant); + const stageStateDrifted = input.issue.status !== "in_review" || !principalsEqual(currentAssignee, currentParticipant) || !principalsEqual(existingState?.currentParticipant ?? null, currentParticipant); + if (attemptedStageAdvance && !stageStateDrifted) { + throw unprocessable("Only the active reviewer or approver can advance the current execution stage"); + } + if (stageStateDrifted) { + buildPendingStagePatch({ + patch, + previous: existingState, + policy: input.policy, + stage: activeStage, + participant: currentParticipant, + returnAssignee: existingState?.returnAssignee ?? currentAssignee ?? actor + }); + return { + patch, + workflowControlledAssignment: true + }; + } + return { patch }; + } + const shouldStartWorkflow = requestedStatus === "done" || requestedStatus === "in_review"; + if (!shouldStartWorkflow) { + return { patch }; + } + let pendingStage = existingState?.status === CHANGES_REQUESTED_STATUS && currentStage ? currentStage : nextPendingStage(input.policy, existingState); + if (!pendingStage) return { patch }; + const returnAssignee = existingState?.returnAssignee ?? currentAssignee; + const skippedStageIds = [...existingState?.completedStageIds ?? []]; + let participant = selectStageParticipant(pendingStage, { + preferred: existingState?.status === CHANGES_REQUESTED_STATUS ? explicitAssignee ?? existingState.currentParticipant ?? null : explicitAssignee, + exclude: returnAssignee + }); + while (!participant && canAutoSkipPendingStage({ stage: pendingStage, returnAssignee, requestedStatus })) { + skippedStageIds.push(pendingStage.id); + pendingStage = nextPendingStage( + input.policy, + buildStateWithCompletedStages({ + previous: existingState, + completedStageIds: skippedStageIds, + returnAssignee + }) + ); + if (!pendingStage) { + patch.executionState = buildSkippedStageCompletedState({ + previous: existingState, + completedStageIds: skippedStageIds, + returnAssignee + }); + return { patch }; + } + participant = selectStageParticipant(pendingStage, { + preferred: existingState?.status === CHANGES_REQUESTED_STATUS ? explicitAssignee ?? existingState.currentParticipant ?? null : explicitAssignee, + exclude: returnAssignee + }); + } + if (!participant) { + throw unprocessable(`No eligible ${pendingStage.type} participant is configured for this issue`); + } + buildPendingStagePatch({ + patch, + previous: skippedStageIds.length === (existingState?.completedStageIds ?? []).length ? existingState : buildStateWithCompletedStages({ + previous: existingState, + completedStageIds: skippedStageIds, + returnAssignee + }), + policy: input.policy, + stage: pendingStage, + participant, + returnAssignee + }); + return { + patch, + workflowControlledAssignment: true + }; +} + +// server/src/routes/issues.ts +var MAX_ISSUE_COMMENT_LIMIT = 500; +var updateIssueRouteSchema = updateIssueSchema.extend({ + interrupt: external_exports.boolean().optional() +}); +function executionPrincipalsEqual(left, right) { + if (!left || !right || left.type !== right.type) return false; + return left.type === "agent" ? left.agentId === right.agentId : left.userId === right.userId; +} +function buildExecutionStageWakeContext(input) { + return { + wakeRole: input.wakeRole, + stageId: input.state.currentStageId, + stageType: input.state.currentStageType, + currentParticipant: input.state.currentParticipant, + returnAssignee: input.state.returnAssignee, + lastDecisionOutcome: input.state.lastDecisionOutcome, + allowedActions: input.allowedActions + }; +} +function summarizeIssueRelationForActivity(relation) { + return { + id: relation.id, + identifier: relation.identifier, + title: relation.title + }; +} +function activityExecutionParticipantKey(participant) { + return participant.type === "agent" ? `agent:${participant.agentId}` : `user:${participant.userId}`; +} +function summarizeExecutionParticipants(policy, stageType) { + const stage = policy?.stages.find((candidate) => candidate.type === stageType); + return stage?.participants.map((participant) => ({ + type: participant.type, + agentId: participant.agentId ?? null, + userId: participant.userId ?? null + })) ?? []; +} +function isClosedIssueStatus(status) { + return status === "done" || status === "cancelled"; +} +function shouldImplicitlyReopenCommentForAgent(input) { + if (!isClosedIssueStatus(input.issueStatus)) return false; + if (typeof input.assigneeAgentId !== "string" || input.assigneeAgentId.length === 0) return false; + if (input.actorType === "agent" && input.actorId === input.assigneeAgentId) return false; + return true; +} +function diffExecutionParticipants(previousPolicy, nextPolicy, stageType) { + const previousParticipants = summarizeExecutionParticipants(previousPolicy, stageType); + const nextParticipants = summarizeExecutionParticipants(nextPolicy, stageType); + const previousByKey = new Map(previousParticipants.map((participant) => [ + activityExecutionParticipantKey(participant), + participant + ])); + const nextByKey = new Map(nextParticipants.map((participant) => [ + activityExecutionParticipantKey(participant), + participant + ])); + return { + participants: nextParticipants, + addedParticipants: nextParticipants.filter((participant) => !previousByKey.has(activityExecutionParticipantKey(participant))), + removedParticipants: previousParticipants.filter((participant) => !nextByKey.has(activityExecutionParticipantKey(participant))) + }; +} +function buildExecutionStageWakeup(input) { + const { issueId, previousState, nextState, interruptedRunId } = input; + if (!nextState) return null; + if (nextState.status === "pending") { + const agentId = nextState.currentParticipant?.type === "agent" ? nextState.currentParticipant.agentId ?? null : null; + const stageChanged = previousState?.status !== "pending" || previousState?.currentStageId !== nextState.currentStageId || !executionPrincipalsEqual(previousState?.currentParticipant ?? null, nextState.currentParticipant ?? null); + if (!agentId || !stageChanged) return null; + const reason = nextState.currentStageType === "approval" ? "execution_approval_requested" : "execution_review_requested"; + const executionStage = buildExecutionStageWakeContext({ + state: nextState, + wakeRole: nextState.currentStageType === "approval" ? "approver" : "reviewer", + allowedActions: ["approve", "request_changes"] + }); + return { + agentId, + wakeup: { + source: "assignment", + triggerDetail: "system", + reason, + payload: { + issueId, + mutation: "update", + executionStage, + ...interruptedRunId ? { interruptedRunId } : {} + }, + requestedByActorType: input.requestedByActorType, + requestedByActorId: input.requestedByActorId, + contextSnapshot: { + issueId, + taskId: issueId, + wakeReason: reason, + source: "issue.execution_stage", + executionStage, + ...interruptedRunId ? { interruptedRunId } : {} + } + } + }; + } + if (nextState.status === "changes_requested") { + const agentId = nextState.returnAssignee?.type === "agent" ? nextState.returnAssignee.agentId ?? null : null; + const becameChangesRequested = previousState?.status !== "changes_requested" || previousState?.lastDecisionId !== nextState.lastDecisionId || !executionPrincipalsEqual(previousState?.returnAssignee ?? null, nextState.returnAssignee ?? null); + if (!agentId || !becameChangesRequested) return null; + const executionStage = buildExecutionStageWakeContext({ + state: nextState, + wakeRole: "executor", + allowedActions: ["address_changes", "resubmit"] + }); + return { + agentId, + wakeup: { + source: "assignment", + triggerDetail: "system", + reason: "execution_changes_requested", + payload: { + issueId, + mutation: "update", + executionStage, + ...interruptedRunId ? { interruptedRunId } : {} + }, + requestedByActorType: input.requestedByActorType, + requestedByActorId: input.requestedByActorId, + contextSnapshot: { + issueId, + taskId: issueId, + wakeReason: "execution_changes_requested", + source: "issue.execution_stage", + executionStage, + ...interruptedRunId ? { interruptedRunId } : {} + } + } + }; + } + return null; +} +function issueRoutes(db, storage, opts) { + const router2 = (0, import_express6.Router)(); + const svc = issueService(db); + const access = accessService(db); + const heartbeat = heartbeatService(db); + const feedback = feedbackService(db); + const instanceSettings2 = instanceSettingsService(db); + const agentsSvc = agentService(db); + const projectsSvc = projectService(db); + const goalsSvc = goalService(db); + const issueApprovalsSvc = issueApprovalService(db); + const executionWorkspacesSvc = executionWorkspaceService(db); + const workProductsSvc = workProductService(db); + const documentsSvc = documentService(db); + const routinesSvc = routineService(db); + const feedbackExportService = opts?.feedbackExportService; + const upload = (0, import_multer.default)({ + storage: import_multer.default.memoryStorage(), + limits: { fileSize: MAX_ATTACHMENT_BYTES, files: 1 } + }); + function withContentPath(attachment) { + return { + ...attachment, + contentPath: `/api/attachments/${attachment.id}/content` + }; + } + function parseBooleanQuery(value) { + return value === true || value === "true" || value === "1"; + } + function parseDateQuery(value, field) { + if (typeof value !== "string" || value.trim().length === 0) return void 0; + const parsed = new Date(value); + if (Number.isNaN(parsed.getTime())) { + throw new HttpError(400, `Invalid ${field} query value`); + } + return parsed; + } + async function runSingleFileUpload(req, res) { + await new Promise((resolve4, reject) => { + upload.single("file")(req, res, (err) => { + if (err) reject(err); + else resolve4(); + }); + }); + } + async function assertCanManageIssueApprovalLinks(req, res, companyId) { + assertCompanyAccess(req, companyId); + if (req.actor.type === "board") return true; + if (!req.actor.agentId) { + res.status(403).json({ error: "Agent authentication required" }); + return false; + } + const actorAgent = await agentsSvc.getById(req.actor.agentId); + if (!actorAgent || actorAgent.companyId !== companyId) { + res.status(403).json({ error: "Forbidden" }); + return false; + } + if (actorAgent.role === "ceo" || Boolean(actorAgent.permissions?.canCreateAgents)) return true; + res.status(403).json({ error: "Missing permission to link approvals" }); + return false; + } + function actorCanAccessCompany(req, companyId) { + if (req.actor.type === "none") return false; + if (req.actor.type === "agent") return req.actor.companyId === companyId; + if (req.actor.source === "local_implicit" || req.actor.isInstanceAdmin) return true; + return (req.actor.companyIds ?? []).includes(companyId); + } + function canCreateAgentsLegacy(agent) { + if (agent.role === "ceo") return true; + if (!agent.permissions || typeof agent.permissions !== "object") return false; + return Boolean(agent.permissions.canCreateAgents); + } + async function assertCanAssignTasks(req, companyId) { + assertCompanyAccess(req, companyId); + if (req.actor.type === "board") { + if (req.actor.source === "local_implicit" || req.actor.isInstanceAdmin) return; + const allowed2 = await access.canUser(companyId, req.actor.userId, "tasks:assign"); + if (!allowed2) throw forbidden("Missing permission: tasks:assign"); + return; + } + if (req.actor.type === "agent") { + if (!req.actor.agentId) throw forbidden("Agent authentication required"); + const allowedByGrant = await access.hasPermission(companyId, "agent", req.actor.agentId, "tasks:assign"); + if (allowedByGrant) return; + const actorAgent = await agentsSvc.getById(req.actor.agentId); + if (actorAgent && actorAgent.companyId === companyId && canCreateAgentsLegacy(actorAgent)) return; + throw forbidden("Missing permission: tasks:assign"); + } + throw unauthorized(); + } + function requireAgentRunId(req, res) { + if (req.actor.type !== "agent") return null; + const runId = req.actor.runId?.trim(); + if (runId) return runId; + res.status(401).json({ error: "Agent run id required" }); + return null; + } + async function assertAgentRunCheckoutOwnership(req, res, issue2) { + if (req.actor.type !== "agent") return true; + const actorAgentId = req.actor.agentId; + if (!actorAgentId) { + res.status(403).json({ error: "Agent authentication required" }); + return false; + } + if (issue2.status !== "in_progress" || issue2.assigneeAgentId !== actorAgentId) { + return true; + } + const runId = requireAgentRunId(req, res); + if (!runId) return false; + const ownership = await svc.assertCheckoutOwner(issue2.id, actorAgentId, runId); + if (ownership.adoptedFromRunId) { + const actor = getActorInfo(req); + await logActivity(db, { + companyId: issue2.companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + runId: actor.runId, + action: "issue.checkout_lock_adopted", + entityType: "issue", + entityId: issue2.id, + details: { + previousCheckoutRunId: ownership.adoptedFromRunId, + checkoutRunId: runId, + reason: "stale_checkout_run" + } + }); + } + return true; + } + async function resolveActiveIssueRun(issue2) { + let runToInterrupt = issue2.executionRunId ? await heartbeat.getRun(issue2.executionRunId) : null; + if ((!runToInterrupt || runToInterrupt.status !== "running") && issue2.assigneeAgentId) { + const activeRun = await heartbeat.getActiveRunForAgent(issue2.assigneeAgentId); + const activeIssueId = activeRun && activeRun.contextSnapshot && typeof activeRun.contextSnapshot === "object" && typeof activeRun.contextSnapshot.issueId === "string" ? activeRun.contextSnapshot.issueId : null; + if (activeRun && activeRun.status === "running" && activeIssueId === issue2.id) { + runToInterrupt = activeRun; + } + } + return runToInterrupt?.status === "running" ? runToInterrupt : null; + } + async function normalizeIssueAssigneeAgentReference(companyId, rawAssigneeAgentId) { + if (rawAssigneeAgentId === void 0 || rawAssigneeAgentId === null) { + return rawAssigneeAgentId; + } + const raw = rawAssigneeAgentId.trim(); + if (raw.length === 0) { + return rawAssigneeAgentId; + } + const resolved = await agentsSvc.resolveByReference(companyId, raw); + if (resolved.ambiguous) { + throw conflict("Agent shortname is ambiguous in this company. Use the agent ID."); + } + if (!resolved.agent) { + throw notFound("Agent not found"); + } + return resolved.agent.id; + } + function toValidTimestamp(value) { + if (!value) return null; + const timestamp2 = value instanceof Date ? value.getTime() : new Date(value).getTime(); + return Number.isFinite(timestamp2) ? timestamp2 : null; + } + function isQueuedIssueCommentForActiveRun(params) { + const activeRunStartedAtMs = toValidTimestamp(params.activeRun.startedAt) ?? toValidTimestamp(params.activeRun.createdAt); + const commentCreatedAtMs = toValidTimestamp(params.comment.createdAt); + if (activeRunStartedAtMs === null || commentCreatedAtMs === null) return false; + if (params.comment.authorAgentId && params.comment.authorAgentId === params.activeRun.agentId) return false; + return commentCreatedAtMs >= activeRunStartedAtMs; + } + async function getClosedIssueExecutionWorkspace(issue2) { + if (!issue2.executionWorkspaceId) return null; + const workspace = await executionWorkspacesSvc.getById(issue2.executionWorkspaceId); + if (!workspace || !isClosedIsolatedExecutionWorkspace(workspace)) return null; + return workspace; + } + function respondClosedIssueExecutionWorkspace(res, workspace) { + res.status(409).json({ + error: getClosedIsolatedExecutionWorkspaceMessage(workspace), + executionWorkspace: workspace + }); + } + async function normalizeIssueIdentifier(rawId) { + if (/^[A-Z]+-\d+$/i.test(rawId)) { + const issue2 = await svc.getByIdentifier(rawId); + if (issue2) { + return issue2.id; + } + } + return rawId; + } + async function resolveIssueProjectAndGoal(issue2) { + const projectPromise = issue2.projectId ? projectsSvc.getById(issue2.projectId) : Promise.resolve(null); + const directGoalPromise = issue2.goalId ? goalsSvc.getById(issue2.goalId) : Promise.resolve(null); + const [project, directGoal] = await Promise.all([projectPromise, directGoalPromise]); + if (directGoal) { + return { project, goal: directGoal }; + } + const projectGoalId = project?.goalId ?? project?.goalIds[0] ?? null; + if (projectGoalId) { + const projectGoal = await goalsSvc.getById(projectGoalId); + return { project, goal: projectGoal }; + } + if (!issue2.projectId) { + const defaultGoal = await goalsSvc.getDefaultCompanyGoal(issue2.companyId); + return { project, goal: defaultGoal }; + } + return { project, goal: null }; + } + router2.param("id", async (req, res, next, rawId) => { + try { + req.params.id = await normalizeIssueIdentifier(rawId); + next(); + } catch (err) { + next(err); + } + }); + router2.param("issueId", async (req, res, next, rawId) => { + try { + req.params.issueId = await normalizeIssueIdentifier(rawId); + next(); + } catch (err) { + next(err); + } + }); + router2.get("/issues", (_req, res) => { + res.status(400).json({ + error: "Missing companyId in path. Use /api/companies/{companyId}/issues." + }); + }); + router2.get("/companies/:companyId/issues", async (req, res) => { + const companyId = req.params.companyId; + assertCompanyAccess(req, companyId); + const assigneeUserFilterRaw = req.query.assigneeUserId; + const touchedByUserFilterRaw = req.query.touchedByUserId; + const inboxArchivedByUserFilterRaw = req.query.inboxArchivedByUserId; + const unreadForUserFilterRaw = req.query.unreadForUserId; + const assigneeUserId = assigneeUserFilterRaw === "me" && req.actor.type === "board" ? req.actor.userId : assigneeUserFilterRaw; + const touchedByUserId = touchedByUserFilterRaw === "me" && req.actor.type === "board" ? req.actor.userId : touchedByUserFilterRaw; + const inboxArchivedByUserId = inboxArchivedByUserFilterRaw === "me" && req.actor.type === "board" ? req.actor.userId : inboxArchivedByUserFilterRaw; + const unreadForUserId = unreadForUserFilterRaw === "me" && req.actor.type === "board" ? req.actor.userId : unreadForUserFilterRaw; + const rawLimit = req.query.limit; + const parsedLimit = rawLimit ? Number.parseInt(rawLimit, 10) : null; + const limit = parsedLimit ?? void 0; + if (assigneeUserFilterRaw === "me" && (!assigneeUserId || req.actor.type !== "board")) { + res.status(403).json({ error: "assigneeUserId=me requires board authentication" }); + return; + } + if (touchedByUserFilterRaw === "me" && (!touchedByUserId || req.actor.type !== "board")) { + res.status(403).json({ error: "touchedByUserId=me requires board authentication" }); + return; + } + if (inboxArchivedByUserFilterRaw === "me" && (!inboxArchivedByUserId || req.actor.type !== "board")) { + res.status(403).json({ error: "inboxArchivedByUserId=me requires board authentication" }); + return; + } + if (unreadForUserFilterRaw === "me" && (!unreadForUserId || req.actor.type !== "board")) { + res.status(403).json({ error: "unreadForUserId=me requires board authentication" }); + return; + } + if (rawLimit !== void 0 && (parsedLimit === null || !Number.isInteger(parsedLimit) || parsedLimit <= 0)) { + res.status(400).json({ error: "limit must be a positive integer" }); + return; + } + const result = await svc.list(companyId, { + status: req.query.status, + assigneeAgentId: req.query.assigneeAgentId, + participantAgentId: req.query.participantAgentId, + assigneeUserId, + touchedByUserId, + inboxArchivedByUserId, + unreadForUserId, + projectId: req.query.projectId, + executionWorkspaceId: req.query.executionWorkspaceId, + parentId: req.query.parentId, + labelId: req.query.labelId, + originKind: req.query.originKind, + originId: req.query.originId, + includeRoutineExecutions: req.query.includeRoutineExecutions === "true" || req.query.includeRoutineExecutions === "1", + q: req.query.q, + limit + }); + res.json(result); + }); + router2.get("/companies/:companyId/labels", async (req, res) => { + const companyId = req.params.companyId; + assertCompanyAccess(req, companyId); + const result = await svc.listLabels(companyId); + res.json(result); + }); + router2.post("/companies/:companyId/labels", validate(createIssueLabelSchema), async (req, res) => { + const companyId = req.params.companyId; + assertCompanyAccess(req, companyId); + const label = await svc.createLabel(companyId, req.body); + const actor = getActorInfo(req); + await logActivity(db, { + companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + runId: actor.runId, + action: "label.created", + entityType: "label", + entityId: label.id, + details: { name: label.name, color: label.color } + }); + res.status(201).json(label); + }); + router2.delete("/labels/:labelId", async (req, res) => { + const labelId = req.params.labelId; + const existing = await svc.getLabelById(labelId); + if (!existing) { + res.status(404).json({ error: "Label not found" }); + return; + } + assertCompanyAccess(req, existing.companyId); + const removed = await svc.deleteLabel(labelId); + if (!removed) { + res.status(404).json({ error: "Label not found" }); + return; + } + const actor = getActorInfo(req); + await logActivity(db, { + companyId: removed.companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + runId: actor.runId, + action: "label.deleted", + entityType: "label", + entityId: removed.id, + details: { name: removed.name, color: removed.color } + }); + res.json(removed); + }); + router2.get("/issues/:id", async (req, res) => { + const id = req.params.id; + const issue2 = await svc.getById(id); + if (!issue2) { + res.status(404).json({ error: "Issue not found" }); + return; + } + assertCompanyAccess(req, issue2.companyId); + const [{ project, goal }, ancestors, mentionedProjectIds, documentPayload, relations] = await Promise.all([ + resolveIssueProjectAndGoal(issue2), + svc.getAncestors(issue2.id), + svc.findMentionedProjectIds(issue2.id), + documentsSvc.getIssueDocumentPayload(issue2), + svc.getRelationSummaries(issue2.id) + ]); + const mentionedProjects = mentionedProjectIds.length > 0 ? await projectsSvc.listByIds(issue2.companyId, mentionedProjectIds) : []; + const currentExecutionWorkspace = issue2.executionWorkspaceId ? await executionWorkspacesSvc.getById(issue2.executionWorkspaceId) : null; + const workProducts = await workProductsSvc.listForIssue(issue2.id); + res.json({ + ...issue2, + goalId: goal?.id ?? issue2.goalId, + ancestors, + blockedBy: relations.blockedBy, + blocks: relations.blocks, + ...documentPayload, + project: project ?? null, + goal: goal ?? null, + mentionedProjects, + currentExecutionWorkspace, + workProducts + }); + }); + router2.get("/issues/:id/heartbeat-context", async (req, res) => { + const id = req.params.id; + const issue2 = await svc.getById(id); + if (!issue2) { + res.status(404).json({ error: "Issue not found" }); + return; + } + assertCompanyAccess(req, issue2.companyId); + const wakeCommentId = typeof req.query.wakeCommentId === "string" && req.query.wakeCommentId.trim().length > 0 ? req.query.wakeCommentId.trim() : null; + const [{ project, goal }, ancestors, commentCursor, wakeComment, relations, attachments] = await Promise.all([ + resolveIssueProjectAndGoal(issue2), + svc.getAncestors(issue2.id), + svc.getCommentCursor(issue2.id), + wakeCommentId ? svc.getComment(wakeCommentId) : null, + svc.getRelationSummaries(issue2.id), + svc.listAttachments(issue2.id) + ]); + res.json({ + issue: { + id: issue2.id, + identifier: issue2.identifier, + title: issue2.title, + description: issue2.description, + status: issue2.status, + priority: issue2.priority, + projectId: issue2.projectId, + goalId: goal?.id ?? issue2.goalId, + parentId: issue2.parentId, + blockedBy: relations.blockedBy, + blocks: relations.blocks, + assigneeAgentId: issue2.assigneeAgentId, + assigneeUserId: issue2.assigneeUserId, + updatedAt: issue2.updatedAt + }, + ancestors: ancestors.map((ancestor) => ({ + id: ancestor.id, + identifier: ancestor.identifier, + title: ancestor.title, + status: ancestor.status, + priority: ancestor.priority + })), + project: project ? { + id: project.id, + name: project.name, + status: project.status, + targetDate: project.targetDate + } : null, + goal: goal ? { + id: goal.id, + title: goal.title, + status: goal.status, + level: goal.level, + parentId: goal.parentId + } : null, + commentCursor, + wakeComment: wakeComment && wakeComment.issueId === issue2.id ? wakeComment : null, + attachments: attachments.map((a5) => ({ + id: a5.id, + filename: a5.originalFilename, + contentType: a5.contentType, + byteSize: a5.byteSize, + contentPath: withContentPath(a5).contentPath, + createdAt: a5.createdAt + })) + }); + }); + router2.get("/issues/:id/work-products", async (req, res) => { + const id = req.params.id; + const issue2 = await svc.getById(id); + if (!issue2) { + res.status(404).json({ error: "Issue not found" }); + return; + } + assertCompanyAccess(req, issue2.companyId); + const workProducts = await workProductsSvc.listForIssue(issue2.id); + res.json(workProducts); + }); + router2.get("/issues/:id/documents", async (req, res) => { + const id = req.params.id; + const issue2 = await svc.getById(id); + if (!issue2) { + res.status(404).json({ error: "Issue not found" }); + return; + } + assertCompanyAccess(req, issue2.companyId); + const docs = await documentsSvc.listIssueDocuments(issue2.id); + res.json(docs); + }); + router2.get("/issues/:id/documents/:key", async (req, res) => { + const id = req.params.id; + const issue2 = await svc.getById(id); + if (!issue2) { + res.status(404).json({ error: "Issue not found" }); + return; + } + assertCompanyAccess(req, issue2.companyId); + const keyParsed = issueDocumentKeySchema.safeParse(String(req.params.key ?? "").trim().toLowerCase()); + if (!keyParsed.success) { + res.status(400).json({ error: "Invalid document key", details: keyParsed.error.issues }); + return; + } + const doc = await documentsSvc.getIssueDocumentByKey(issue2.id, keyParsed.data); + if (!doc) { + res.status(404).json({ error: "Document not found" }); + return; + } + res.json(doc); + }); + router2.put("/issues/:id/documents/:key", validate(upsertIssueDocumentSchema), async (req, res) => { + const id = req.params.id; + const issue2 = await svc.getById(id); + if (!issue2) { + res.status(404).json({ error: "Issue not found" }); + return; + } + assertCompanyAccess(req, issue2.companyId); + const keyParsed = issueDocumentKeySchema.safeParse(String(req.params.key ?? "").trim().toLowerCase()); + if (!keyParsed.success) { + res.status(400).json({ error: "Invalid document key", details: keyParsed.error.issues }); + return; + } + const actor = getActorInfo(req); + const result = await documentsSvc.upsertIssueDocument({ + issueId: issue2.id, + key: keyParsed.data, + title: req.body.title ?? null, + format: req.body.format, + body: req.body.body, + changeSummary: req.body.changeSummary ?? null, + baseRevisionId: req.body.baseRevisionId ?? null, + createdByAgentId: actor.agentId ?? null, + createdByUserId: actor.actorType === "user" ? actor.actorId : null, + createdByRunId: actor.runId ?? null + }); + const doc = result.document; + await logActivity(db, { + companyId: issue2.companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + runId: actor.runId, + action: result.created ? "issue.document_created" : "issue.document_updated", + entityType: "issue", + entityId: issue2.id, + details: { + key: doc.key, + documentId: doc.id, + title: doc.title, + format: doc.format, + revisionNumber: doc.latestRevisionNumber + } + }); + res.status(result.created ? 201 : 200).json(doc); + }); + router2.get("/issues/:id/documents/:key/revisions", async (req, res) => { + const id = req.params.id; + const issue2 = await svc.getById(id); + if (!issue2) { + res.status(404).json({ error: "Issue not found" }); + return; + } + assertCompanyAccess(req, issue2.companyId); + const keyParsed = issueDocumentKeySchema.safeParse(String(req.params.key ?? "").trim().toLowerCase()); + if (!keyParsed.success) { + res.status(400).json({ error: "Invalid document key", details: keyParsed.error.issues }); + return; + } + const revisions = await documentsSvc.listIssueDocumentRevisions(issue2.id, keyParsed.data); + res.json(revisions); + }); + router2.post( + "/issues/:id/documents/:key/revisions/:revisionId/restore", + validate(restoreIssueDocumentRevisionSchema), + async (req, res) => { + const id = req.params.id; + const revisionId = req.params.revisionId; + const issue2 = await svc.getById(id); + if (!issue2) { + res.status(404).json({ error: "Issue not found" }); + return; + } + assertCompanyAccess(req, issue2.companyId); + const keyParsed = issueDocumentKeySchema.safeParse(String(req.params.key ?? "").trim().toLowerCase()); + if (!keyParsed.success) { + res.status(400).json({ error: "Invalid document key", details: keyParsed.error.issues }); + return; + } + const actor = getActorInfo(req); + const result = await documentsSvc.restoreIssueDocumentRevision({ + issueId: issue2.id, + key: keyParsed.data, + revisionId, + createdByAgentId: actor.agentId ?? null, + createdByUserId: actor.actorType === "user" ? actor.actorId : null + }); + await logActivity(db, { + companyId: issue2.companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + runId: actor.runId, + action: "issue.document_restored", + entityType: "issue", + entityId: issue2.id, + details: { + key: result.document.key, + documentId: result.document.id, + title: result.document.title, + format: result.document.format, + revisionNumber: result.document.latestRevisionNumber, + restoredFromRevisionId: result.restoredFromRevisionId, + restoredFromRevisionNumber: result.restoredFromRevisionNumber + } + }); + res.json(result.document); + } + ); + router2.delete("/issues/:id/documents/:key", async (req, res) => { + const id = req.params.id; + const issue2 = await svc.getById(id); + if (!issue2) { + res.status(404).json({ error: "Issue not found" }); + return; + } + assertCompanyAccess(req, issue2.companyId); + if (req.actor.type !== "board") { + res.status(403).json({ error: "Board authentication required" }); + return; + } + const keyParsed = issueDocumentKeySchema.safeParse(String(req.params.key ?? "").trim().toLowerCase()); + if (!keyParsed.success) { + res.status(400).json({ error: "Invalid document key", details: keyParsed.error.issues }); + return; + } + const removed = await documentsSvc.deleteIssueDocument(issue2.id, keyParsed.data); + if (!removed) { + res.status(404).json({ error: "Document not found" }); + return; + } + const actor = getActorInfo(req); + await logActivity(db, { + companyId: issue2.companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + runId: actor.runId, + action: "issue.document_deleted", + entityType: "issue", + entityId: issue2.id, + details: { + key: removed.key, + documentId: removed.id, + title: removed.title + } + }); + res.json({ ok: true }); + }); + router2.post("/issues/:id/work-products", validate(createIssueWorkProductSchema), async (req, res) => { + const id = req.params.id; + const issue2 = await svc.getById(id); + if (!issue2) { + res.status(404).json({ error: "Issue not found" }); + return; + } + assertCompanyAccess(req, issue2.companyId); + const product = await workProductsSvc.createForIssue(issue2.id, issue2.companyId, { + ...req.body, + projectId: req.body.projectId ?? issue2.projectId ?? null + }); + if (!product) { + res.status(422).json({ error: "Invalid work product payload" }); + return; + } + const actor = getActorInfo(req); + await logActivity(db, { + companyId: issue2.companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + runId: actor.runId, + action: "issue.work_product_created", + entityType: "issue", + entityId: issue2.id, + details: { workProductId: product.id, type: product.type, provider: product.provider } + }); + res.status(201).json(product); + }); + router2.patch("/work-products/:id", validate(updateIssueWorkProductSchema), async (req, res) => { + const id = req.params.id; + const existing = await workProductsSvc.getById(id); + if (!existing) { + res.status(404).json({ error: "Work product not found" }); + return; + } + assertCompanyAccess(req, existing.companyId); + const product = await workProductsSvc.update(id, req.body); + if (!product) { + res.status(404).json({ error: "Work product not found" }); + return; + } + const actor = getActorInfo(req); + await logActivity(db, { + companyId: existing.companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + runId: actor.runId, + action: "issue.work_product_updated", + entityType: "issue", + entityId: existing.issueId, + details: { workProductId: product.id, changedKeys: Object.keys(req.body).sort() } + }); + res.json(product); + }); + router2.delete("/work-products/:id", async (req, res) => { + const id = req.params.id; + const existing = await workProductsSvc.getById(id); + if (!existing) { + res.status(404).json({ error: "Work product not found" }); + return; + } + assertCompanyAccess(req, existing.companyId); + const removed = await workProductsSvc.remove(id); + if (!removed) { + res.status(404).json({ error: "Work product not found" }); + return; + } + const actor = getActorInfo(req); + await logActivity(db, { + companyId: existing.companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + runId: actor.runId, + action: "issue.work_product_deleted", + entityType: "issue", + entityId: existing.issueId, + details: { workProductId: removed.id, type: removed.type } + }); + res.json(removed); + }); + router2.post("/issues/:id/read", async (req, res) => { + const id = req.params.id; + const issue2 = await svc.getById(id); + if (!issue2) { + res.status(404).json({ error: "Issue not found" }); + return; + } + assertCompanyAccess(req, issue2.companyId); + if (req.actor.type !== "board") { + res.status(403).json({ error: "Board authentication required" }); + return; + } + if (!req.actor.userId) { + res.status(403).json({ error: "Board user context required" }); + return; + } + const readState = await svc.markRead(issue2.companyId, issue2.id, req.actor.userId, /* @__PURE__ */ new Date()); + const actor = getActorInfo(req); + await logActivity(db, { + companyId: issue2.companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + runId: actor.runId, + action: "issue.read_marked", + entityType: "issue", + entityId: issue2.id, + details: { userId: req.actor.userId, lastReadAt: readState.lastReadAt } + }); + res.json(readState); + }); + router2.delete("/issues/:id/read", async (req, res) => { + const id = req.params.id; + const issue2 = await svc.getById(id); + if (!issue2) { + res.status(404).json({ error: "Issue not found" }); + return; + } + assertCompanyAccess(req, issue2.companyId); + if (req.actor.type !== "board") { + res.status(403).json({ error: "Board authentication required" }); + return; + } + if (!req.actor.userId) { + res.status(403).json({ error: "Board user context required" }); + return; + } + const removed = await svc.markUnread(issue2.companyId, issue2.id, req.actor.userId); + const actor = getActorInfo(req); + await logActivity(db, { + companyId: issue2.companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + runId: actor.runId, + action: "issue.read_unmarked", + entityType: "issue", + entityId: issue2.id, + details: { userId: req.actor.userId } + }); + res.json({ id: issue2.id, removed }); + }); + router2.post("/issues/:id/inbox-archive", async (req, res) => { + const id = req.params.id; + const issue2 = await svc.getById(id); + if (!issue2) { + res.status(404).json({ error: "Issue not found" }); + return; + } + assertCompanyAccess(req, issue2.companyId); + if (req.actor.type !== "board") { + res.status(403).json({ error: "Board authentication required" }); + return; + } + if (!req.actor.userId) { + res.status(403).json({ error: "Board user context required" }); + return; + } + const archiveState = await svc.archiveInbox(issue2.companyId, issue2.id, req.actor.userId, /* @__PURE__ */ new Date()); + const actor = getActorInfo(req); + await logActivity(db, { + companyId: issue2.companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + runId: actor.runId, + action: "issue.inbox_archived", + entityType: "issue", + entityId: issue2.id, + details: { userId: req.actor.userId, archivedAt: archiveState.archivedAt } + }); + res.json(archiveState); + }); + router2.delete("/issues/:id/inbox-archive", async (req, res) => { + const id = req.params.id; + const issue2 = await svc.getById(id); + if (!issue2) { + res.status(404).json({ error: "Issue not found" }); + return; + } + assertCompanyAccess(req, issue2.companyId); + if (req.actor.type !== "board") { + res.status(403).json({ error: "Board authentication required" }); + return; + } + if (!req.actor.userId) { + res.status(403).json({ error: "Board user context required" }); + return; + } + const removed = await svc.unarchiveInbox(issue2.companyId, issue2.id, req.actor.userId); + const actor = getActorInfo(req); + await logActivity(db, { + companyId: issue2.companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + runId: actor.runId, + action: "issue.inbox_unarchived", + entityType: "issue", + entityId: issue2.id, + details: { userId: req.actor.userId } + }); + res.json(removed ?? { ok: true }); + }); + router2.get("/issues/:id/approvals", async (req, res) => { + const id = req.params.id; + const issue2 = await svc.getById(id); + if (!issue2) { + res.status(404).json({ error: "Issue not found" }); + return; + } + assertCompanyAccess(req, issue2.companyId); + const approvals2 = await issueApprovalsSvc.listApprovalsForIssue(id); + res.json(approvals2); + }); + router2.post("/issues/:id/approvals", validate(linkIssueApprovalSchema), async (req, res) => { + const id = req.params.id; + const issue2 = await svc.getById(id); + if (!issue2) { + res.status(404).json({ error: "Issue not found" }); + return; + } + if (!await assertCanManageIssueApprovalLinks(req, res, issue2.companyId)) return; + const actor = getActorInfo(req); + await issueApprovalsSvc.link(id, req.body.approvalId, { + agentId: actor.agentId, + userId: actor.actorType === "user" ? actor.actorId : null + }); + await logActivity(db, { + companyId: issue2.companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + runId: actor.runId, + action: "issue.approval_linked", + entityType: "issue", + entityId: issue2.id, + details: { approvalId: req.body.approvalId } + }); + const approvals2 = await issueApprovalsSvc.listApprovalsForIssue(id); + res.status(201).json(approvals2); + }); + router2.delete("/issues/:id/approvals/:approvalId", async (req, res) => { + const id = req.params.id; + const approvalId = req.params.approvalId; + const issue2 = await svc.getById(id); + if (!issue2) { + res.status(404).json({ error: "Issue not found" }); + return; + } + if (!await assertCanManageIssueApprovalLinks(req, res, issue2.companyId)) return; + await issueApprovalsSvc.unlink(id, approvalId); + const actor = getActorInfo(req); + await logActivity(db, { + companyId: issue2.companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + runId: actor.runId, + action: "issue.approval_unlinked", + entityType: "issue", + entityId: issue2.id, + details: { approvalId } + }); + res.json({ ok: true }); + }); + router2.post("/companies/:companyId/issues", validate(createIssueSchema), async (req, res) => { + const companyId = req.params.companyId; + assertCompanyAccess(req, companyId); + if (req.body.assigneeAgentId || req.body.assigneeUserId) { + await assertCanAssignTasks(req, companyId); + } + const actor = getActorInfo(req); + const executionPolicy = normalizeIssueExecutionPolicy(req.body.executionPolicy); + const issue2 = await svc.create(companyId, { + ...req.body, + executionPolicy, + createdByAgentId: actor.agentId, + createdByUserId: actor.actorType === "user" ? actor.actorId : null + }); + await logActivity(db, { + companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + runId: actor.runId, + action: "issue.created", + entityType: "issue", + entityId: issue2.id, + details: { + title: issue2.title, + identifier: issue2.identifier, + ...Array.isArray(req.body.blockedByIssueIds) ? { blockedByIssueIds: req.body.blockedByIssueIds } : {} + } + }); + void queueIssueAssignmentWakeup({ + heartbeat, + issue: issue2, + reason: "issue_assigned", + mutation: "create", + contextSource: "issue.create", + requestedByActorType: actor.actorType, + requestedByActorId: actor.actorId + }); + res.status(201).json(issue2); + }); + router2.patch("/issues/:id", validate(updateIssueRouteSchema), async (req, res) => { + const id = req.params.id; + const existing = await svc.getById(id); + if (!existing) { + res.status(404).json({ error: "Issue not found" }); + return; + } + assertCompanyAccess(req, existing.companyId); + if (!await assertAgentRunCheckoutOwnership(req, res, existing)) return; + const actor = getActorInfo(req); + const isClosed = isClosedIssueStatus(existing.status); + const normalizedAssigneeAgentId = await normalizeIssueAssigneeAgentReference( + existing.companyId, + req.body.assigneeAgentId + ); + const existingRelations = Array.isArray(req.body.blockedByIssueIds) ? await svc.getRelationSummaries(existing.id) : null; + const { + comment: commentBody, + reopen: reopenRequested, + interrupt: interruptRequested, + hiddenAt: hiddenAtRaw, + ...updateFields + } = req.body; + const requestedAssigneeAgentId = normalizedAssigneeAgentId === void 0 ? existing.assigneeAgentId : normalizedAssigneeAgentId; + const effectiveReopenRequested = reopenRequested || !!commentBody && shouldImplicitlyReopenCommentForAgent({ + issueStatus: existing.status, + assigneeAgentId: requestedAssigneeAgentId, + actorType: actor.actorType, + actorId: actor.actorId + }); + let interruptedRunId = null; + const closedExecutionWorkspace = await getClosedIssueExecutionWorkspace(existing); + const isAgentWorkUpdate = req.actor.type === "agent" && Object.keys(updateFields).length > 0; + if (closedExecutionWorkspace && (commentBody || isAgentWorkUpdate)) { + respondClosedIssueExecutionWorkspace(res, closedExecutionWorkspace); + return; + } + if (interruptRequested) { + if (!commentBody) { + res.status(400).json({ error: "Interrupt is only supported when posting a comment" }); + return; + } + if (req.actor.type !== "board") { + res.status(403).json({ error: "Only board users can interrupt active runs from issue comments" }); + return; + } + const runToInterrupt = await resolveActiveIssueRun(existing); + if (runToInterrupt) { + const cancelled = await heartbeat.cancelRun(runToInterrupt.id); + if (cancelled) { + interruptedRunId = cancelled.id; + await logActivity(db, { + companyId: cancelled.companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + runId: actor.runId, + action: "heartbeat.cancelled", + entityType: "heartbeat_run", + entityId: cancelled.id, + details: { agentId: cancelled.agentId, source: "issue_comment_interrupt", issueId: existing.id } + }); + } + } + } + if (hiddenAtRaw !== void 0) { + updateFields.hiddenAt = hiddenAtRaw ? new Date(hiddenAtRaw) : null; + } + if (commentBody && effectiveReopenRequested && isClosed && updateFields.status === void 0) { + updateFields.status = "todo"; + } + if (req.body.executionPolicy !== void 0) { + updateFields.executionPolicy = normalizeIssueExecutionPolicy(req.body.executionPolicy); + } + const previousExecutionPolicy = normalizeIssueExecutionPolicy(existing.executionPolicy ?? null); + const nextExecutionPolicy = updateFields.executionPolicy !== void 0 ? updateFields.executionPolicy : previousExecutionPolicy; + if (normalizedAssigneeAgentId !== void 0) { + updateFields.assigneeAgentId = normalizedAssigneeAgentId; + } + const transition = applyIssueExecutionPolicyTransition({ + issue: existing, + policy: nextExecutionPolicy, + requestedStatus: typeof updateFields.status === "string" ? updateFields.status : void 0, + requestedAssigneePatch: { + assigneeAgentId: normalizedAssigneeAgentId, + assigneeUserId: req.body.assigneeUserId === void 0 ? void 0 : req.body.assigneeUserId + }, + actor: { + agentId: actor.agentId ?? null, + userId: actor.actorType === "user" ? actor.actorId : null + }, + commentBody + }); + const decisionId = transition.decision ? randomUUID9() : null; + if (decisionId) { + const nextExecutionState2 = transition.patch.executionState; + if (!nextExecutionState2 || typeof nextExecutionState2 !== "object") { + throw new Error("Execution policy decision patch is missing executionState"); + } + transition.patch.executionState = { + ...nextExecutionState2, + lastDecisionId: decisionId + }; + } + Object.assign(updateFields, transition.patch); + const nextAssigneeAgentId = updateFields.assigneeAgentId === void 0 ? existing.assigneeAgentId : updateFields.assigneeAgentId; + const nextAssigneeUserId = updateFields.assigneeUserId === void 0 ? existing.assigneeUserId : updateFields.assigneeUserId; + const assigneeWillChange = nextAssigneeAgentId !== existing.assigneeAgentId || nextAssigneeUserId !== existing.assigneeUserId; + const isAgentReturningIssueToCreator = req.actor.type === "agent" && !!req.actor.agentId && existing.assigneeAgentId === req.actor.agentId && nextAssigneeAgentId === null && typeof nextAssigneeUserId === "string" && !!existing.createdByUserId && nextAssigneeUserId === existing.createdByUserId; + if (assigneeWillChange && !transition.workflowControlledAssignment) { + if (!isAgentReturningIssueToCreator) { + await assertCanAssignTasks(req, existing.companyId); + } + } + let issue2; + try { + if (transition.decision && decisionId) { + const decision = transition.decision; + issue2 = await db.transaction(async (tx) => { + const updated = await svc.update( + id, + { + ...updateFields, + actorAgentId: actor.agentId ?? null, + actorUserId: actor.actorType === "user" ? actor.actorId : null + }, + tx + ); + if (!updated) return null; + await tx.insert(issueExecutionDecisions).values({ + id: decisionId, + companyId: updated.companyId, + issueId: updated.id, + stageId: decision.stageId, + stageType: decision.stageType, + actorAgentId: actor.agentId ?? null, + actorUserId: actor.actorType === "user" ? actor.actorId : null, + outcome: decision.outcome, + body: decision.body, + createdByRunId: actor.runId ?? null + }); + return updated; + }); + } else { + issue2 = await svc.update(id, { + ...updateFields, + actorAgentId: actor.agentId ?? null, + actorUserId: actor.actorType === "user" ? actor.actorId : null + }); + } + } catch (err) { + if (err instanceof HttpError && err.status === 422) { + logger.warn( + { + issueId: id, + companyId: existing.companyId, + assigneePatch: { + assigneeAgentId: normalizedAssigneeAgentId === void 0 ? "__omitted__" : normalizedAssigneeAgentId, + assigneeUserId: req.body.assigneeUserId === void 0 ? "__omitted__" : req.body.assigneeUserId + }, + currentAssignee: { + assigneeAgentId: existing.assigneeAgentId, + assigneeUserId: existing.assigneeUserId + }, + error: err.message, + details: err.details + }, + "issue update rejected with 422" + ); + } + throw err; + } + if (!issue2) { + res.status(404).json({ error: "Issue not found" }); + return; + } + let issueResponse = issue2; + let updatedRelations = null; + if (issue2 && Array.isArray(req.body.blockedByIssueIds)) { + updatedRelations = await svc.getRelationSummaries(issue2.id); + issueResponse = { + ...issue2, + blockedBy: updatedRelations.blockedBy, + blocks: updatedRelations.blocks + }; + } + await routinesSvc.syncRunStatusForIssue(issue2.id); + if (actor.runId) { + await heartbeat.reportRunActivity(actor.runId).catch((err) => logger.warn({ err, runId: actor.runId }, "failed to clear detached run warning after issue activity")); + } + const previous = {}; + for (const key of Object.keys(updateFields)) { + if (key in existing && existing[key] !== updateFields[key]) { + previous[key] = existing[key]; + } + } + if (Array.isArray(req.body.blockedByIssueIds)) { + previous.blockedByIssueIds = existingRelations?.blockedBy.map((relation) => relation.id) ?? []; + } + const hasFieldChanges = Object.keys(previous).length > 0; + const reopened = commentBody && effectiveReopenRequested && isClosed && previous.status !== void 0 && issue2.status === "todo"; + const reopenFromStatus = reopened ? existing.status : null; + await logActivity(db, { + companyId: issue2.companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + runId: actor.runId, + action: "issue.updated", + entityType: "issue", + entityId: issue2.id, + details: { + ...updateFields, + identifier: issue2.identifier, + ...commentBody ? { source: "comment" } : {}, + ...reopened ? { reopened: true, reopenedFrom: reopenFromStatus } : {}, + ...interruptedRunId ? { interruptedRunId } : {}, + _previous: hasFieldChanges ? previous : void 0 + } + }); + if (Array.isArray(req.body.blockedByIssueIds)) { + const previousBlockedByIds = new Set((existingRelations?.blockedBy ?? []).map((relation) => relation.id)); + const nextBlockedByIds = new Set(req.body.blockedByIssueIds); + const addedBlockedByIssueIds = [...nextBlockedByIds].filter((candidate) => !previousBlockedByIds.has(candidate)); + const removedBlockedByIssueIds = [...previousBlockedByIds].filter((candidate) => !nextBlockedByIds.has(candidate)); + const nextBlockedByRelations = updatedRelations?.blockedBy ?? []; + const previousBlockedByRelations = existingRelations?.blockedBy ?? []; + if (addedBlockedByIssueIds.length > 0 || removedBlockedByIssueIds.length > 0) { + await logActivity(db, { + companyId: issue2.companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + runId: actor.runId, + action: "issue.blockers_updated", + entityType: "issue", + entityId: issue2.id, + details: { + identifier: issue2.identifier, + blockedByIssueIds: req.body.blockedByIssueIds, + addedBlockedByIssueIds, + removedBlockedByIssueIds, + blockedByIssues: nextBlockedByRelations.map(summarizeIssueRelationForActivity), + addedBlockedByIssues: nextBlockedByRelations.filter((relation) => addedBlockedByIssueIds.includes(relation.id)).map(summarizeIssueRelationForActivity), + removedBlockedByIssues: previousBlockedByRelations.filter((relation) => removedBlockedByIssueIds.includes(relation.id)).map(summarizeIssueRelationForActivity) + } + }); + } + } + const reviewerChanges = diffExecutionParticipants(previousExecutionPolicy, nextExecutionPolicy, "review"); + if (reviewerChanges.addedParticipants.length > 0 || reviewerChanges.removedParticipants.length > 0) { + await logActivity(db, { + companyId: issue2.companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + runId: actor.runId, + action: "issue.reviewers_updated", + entityType: "issue", + entityId: issue2.id, + details: { + identifier: issue2.identifier, + participants: reviewerChanges.participants, + addedParticipants: reviewerChanges.addedParticipants, + removedParticipants: reviewerChanges.removedParticipants + } + }); + } + const approverChanges = diffExecutionParticipants(previousExecutionPolicy, nextExecutionPolicy, "approval"); + if (approverChanges.addedParticipants.length > 0 || approverChanges.removedParticipants.length > 0) { + await logActivity(db, { + companyId: issue2.companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + runId: actor.runId, + action: "issue.approvers_updated", + entityType: "issue", + entityId: issue2.id, + details: { + identifier: issue2.identifier, + participants: approverChanges.participants, + addedParticipants: approverChanges.addedParticipants, + removedParticipants: approverChanges.removedParticipants + } + }); + } + if (issue2.status === "done" && existing.status !== "done") { + const tc = getTelemetryClient(); + if (tc && actor.agentId) { + const actorAgent = await agentsSvc.getById(actor.agentId); + if (actorAgent) { + const model = typeof actorAgent.adapterConfig?.model === "string" ? actorAgent.adapterConfig.model : void 0; + trackAgentTaskCompleted(tc, { + agentRole: actorAgent.role, + agentId: actorAgent.id, + adapterType: actorAgent.adapterType, + model + }); + } + } + } + let comment = null; + if (commentBody) { + comment = await svc.addComment(id, commentBody, { + agentId: actor.agentId ?? void 0, + userId: actor.actorType === "user" ? actor.actorId : void 0, + runId: actor.runId + }); + await logActivity(db, { + companyId: issue2.companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + runId: actor.runId, + action: "issue.comment_added", + entityType: "issue", + entityId: issue2.id, + details: { + commentId: comment.id, + bodySnippet: comment.body.slice(0, 120), + identifier: issue2.identifier, + issueTitle: issue2.title, + ...reopened ? { reopened: true, reopenedFrom: reopenFromStatus, source: "comment" } : {}, + ...interruptedRunId ? { interruptedRunId } : {}, + ...hasFieldChanges ? { updated: true } : {} + } + }); + } + const assigneeChanged = issue2.assigneeAgentId !== existing.assigneeAgentId || issue2.assigneeUserId !== existing.assigneeUserId; + const statusChangedFromBacklog = existing.status === "backlog" && issue2.status !== "backlog" && req.body.status !== void 0; + const statusChangedFromBlockedToTodo = existing.status === "blocked" && issue2.status === "todo" && req.body.status !== void 0; + const previousExecutionState = parseIssueExecutionState(existing.executionState); + const nextExecutionState = parseIssueExecutionState(issue2.executionState); + const executionStageWakeup = buildExecutionStageWakeup({ + issueId: issue2.id, + previousState: previousExecutionState, + nextState: nextExecutionState, + interruptedRunId, + requestedByActorType: actor.actorType, + requestedByActorId: actor.actorId + }); + void (async () => { + const wakeups = /* @__PURE__ */ new Map(); + const addWakeup = (agentId, wakeup) => { + const wakeIssueId = wakeup.payload && typeof wakeup.payload === "object" && typeof wakeup.payload.issueId === "string" ? wakeup.payload.issueId : issue2.id; + wakeups.set(`${agentId}:${wakeIssueId}`, { agentId, wakeup }); + }; + if (executionStageWakeup) { + addWakeup(executionStageWakeup.agentId, executionStageWakeup.wakeup); + } else if (assigneeChanged && issue2.assigneeAgentId && issue2.status !== "backlog") { + addWakeup(issue2.assigneeAgentId, { + source: "assignment", + triggerDetail: "system", + reason: "issue_assigned", + payload: { + issueId: issue2.id, + ...comment ? { commentId: comment.id } : {}, + mutation: "update", + ...interruptedRunId ? { interruptedRunId } : {} + }, + requestedByActorType: actor.actorType, + requestedByActorId: actor.actorId, + contextSnapshot: { + issueId: issue2.id, + ...comment ? { + taskId: issue2.id, + commentId: comment.id, + wakeCommentId: comment.id + } : {}, + source: "issue.update", + ...interruptedRunId ? { interruptedRunId } : {} + } + }); + } + if (!assigneeChanged && (statusChangedFromBacklog || statusChangedFromBlockedToTodo) && issue2.assigneeAgentId) { + addWakeup(issue2.assigneeAgentId, { + source: "automation", + triggerDetail: "system", + reason: "issue_status_changed", + payload: { + issueId: issue2.id, + mutation: "update", + ...interruptedRunId ? { interruptedRunId } : {} + }, + requestedByActorType: actor.actorType, + requestedByActorId: actor.actorId, + contextSnapshot: { + issueId: issue2.id, + source: "issue.status_change", + ...interruptedRunId ? { interruptedRunId } : {} + } + }); + } + if (commentBody && comment) { + const assigneeId = issue2.assigneeAgentId; + const actorIsAgent = actor.actorType === "agent"; + const selfComment = actorIsAgent && actor.actorId === assigneeId; + const skipAssigneeCommentWake = selfComment || isClosed; + if (assigneeId && !assigneeChanged && (reopened || !skipAssigneeCommentWake)) { + addWakeup(assigneeId, { + source: "automation", + triggerDetail: "system", + reason: reopened ? "issue_reopened_via_comment" : "issue_commented", + payload: { + issueId: id, + commentId: comment.id, + mutation: "comment", + ...reopened ? { reopenedFrom: reopenFromStatus } : {}, + ...interruptedRunId ? { interruptedRunId } : {} + }, + requestedByActorType: actor.actorType, + requestedByActorId: actor.actorId, + contextSnapshot: { + issueId: id, + taskId: id, + commentId: comment.id, + wakeCommentId: comment.id, + source: reopened ? "issue.comment.reopen" : "issue.comment", + wakeReason: reopened ? "issue_reopened_via_comment" : "issue_commented", + ...reopened ? { reopenedFrom: reopenFromStatus } : {}, + ...interruptedRunId ? { interruptedRunId } : {} + } + }); + } + let mentionedIds = []; + try { + mentionedIds = await svc.findMentionedAgents(issue2.companyId, commentBody); + } catch (err) { + logger.warn({ err, issueId: id }, "failed to resolve @-mentions"); + } + for (const mentionedId of mentionedIds) { + if (actor.actorType === "agent" && actor.actorId === mentionedId) continue; + addWakeup(mentionedId, { + source: "automation", + triggerDetail: "system", + reason: "issue_comment_mentioned", + payload: { issueId: id, commentId: comment.id }, + requestedByActorType: actor.actorType, + requestedByActorId: actor.actorId, + contextSnapshot: { + issueId: id, + taskId: id, + commentId: comment.id, + wakeCommentId: comment.id, + wakeReason: "issue_comment_mentioned", + source: "comment.mention" + } + }); + } + } + const becameDone = existing.status !== "done" && issue2.status === "done"; + if (becameDone) { + const dependents = await svc.listWakeableBlockedDependents(issue2.id); + for (const dependent of dependents) { + addWakeup(dependent.assigneeAgentId, { + source: "automation", + triggerDetail: "system", + reason: "issue_blockers_resolved", + payload: { + issueId: dependent.id, + resolvedBlockerIssueId: issue2.id, + blockerIssueIds: dependent.blockerIssueIds + }, + requestedByActorType: actor.actorType, + requestedByActorId: actor.actorId, + contextSnapshot: { + issueId: dependent.id, + taskId: dependent.id, + wakeReason: "issue_blockers_resolved", + source: "issue.blockers_resolved", + resolvedBlockerIssueId: issue2.id, + blockerIssueIds: dependent.blockerIssueIds + } + }); + } + } + const becameTerminal = !["done", "cancelled"].includes(existing.status) && ["done", "cancelled"].includes(issue2.status); + if (becameTerminal && issue2.parentId) { + const parent = await svc.getWakeableParentAfterChildCompletion(issue2.parentId); + if (parent) { + addWakeup(parent.assigneeAgentId, { + source: "automation", + triggerDetail: "system", + reason: "issue_children_completed", + payload: { + issueId: parent.id, + completedChildIssueId: issue2.id, + childIssueIds: parent.childIssueIds + }, + requestedByActorType: actor.actorType, + requestedByActorId: actor.actorId, + contextSnapshot: { + issueId: parent.id, + taskId: parent.id, + wakeReason: "issue_children_completed", + source: "issue.children_completed", + completedChildIssueId: issue2.id, + childIssueIds: parent.childIssueIds + } + }); + } + } + for (const { agentId, wakeup } of wakeups.values()) { + heartbeat.wakeup(agentId, wakeup).catch((err) => logger.warn({ err, issueId: issue2.id, agentId }, "failed to wake agent on issue update")); + } + })(); + res.json({ ...issueResponse, comment }); + }); + router2.delete("/issues/:id", async (req, res) => { + const id = req.params.id; + const existing = await svc.getById(id); + if (!existing) { + res.status(404).json({ error: "Issue not found" }); + return; + } + assertCompanyAccess(req, existing.companyId); + const attachments = await svc.listAttachments(id); + const issue2 = await svc.remove(id); + if (!issue2) { + res.status(404).json({ error: "Issue not found" }); + return; + } + for (const attachment of attachments) { + try { + await storage.deleteObject(attachment.companyId, attachment.objectKey); + } catch (err) { + logger.warn({ err, issueId: id, attachmentId: attachment.id }, "failed to delete attachment object during issue delete"); + } + } + const actor = getActorInfo(req); + await logActivity(db, { + companyId: issue2.companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + runId: actor.runId, + action: "issue.deleted", + entityType: "issue", + entityId: issue2.id + }); + res.json(issue2); + }); + router2.post("/issues/:id/checkout", validate(checkoutIssueSchema), async (req, res) => { + const id = req.params.id; + const issue2 = await svc.getById(id); + if (!issue2) { + res.status(404).json({ error: "Issue not found" }); + return; + } + assertCompanyAccess(req, issue2.companyId); + if (issue2.projectId) { + const project = await projectsSvc.getById(issue2.projectId); + if (project?.pausedAt) { + res.status(409).json({ + error: project.pauseReason === "budget" ? "Project is paused because its budget hard-stop was reached" : "Project is paused" + }); + return; + } + } + if (req.actor.type === "agent" && req.actor.agentId !== req.body.agentId) { + res.status(403).json({ error: "Agent can only checkout as itself" }); + return; + } + const closedExecutionWorkspace = await getClosedIssueExecutionWorkspace(issue2); + if (closedExecutionWorkspace) { + respondClosedIssueExecutionWorkspace(res, closedExecutionWorkspace); + return; + } + const checkoutRunId = requireAgentRunId(req, res); + if (req.actor.type === "agent" && !checkoutRunId) return; + const updated = await svc.checkout(id, req.body.agentId, req.body.expectedStatuses, checkoutRunId); + const actor = getActorInfo(req); + await logActivity(db, { + companyId: issue2.companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + runId: actor.runId, + action: "issue.checked_out", + entityType: "issue", + entityId: issue2.id, + details: { agentId: req.body.agentId } + }); + if (shouldWakeAssigneeOnCheckout({ + actorType: req.actor.type, + actorAgentId: req.actor.type === "agent" ? req.actor.agentId ?? null : null, + checkoutAgentId: req.body.agentId, + checkoutRunId + })) { + void heartbeat.wakeup(req.body.agentId, { + source: "assignment", + triggerDetail: "system", + reason: "issue_checked_out", + payload: { issueId: issue2.id, mutation: "checkout" }, + requestedByActorType: actor.actorType, + requestedByActorId: actor.actorId, + contextSnapshot: { issueId: issue2.id, source: "issue.checkout" } + }).catch((err) => logger.warn({ err, issueId: issue2.id }, "failed to wake assignee on issue checkout")); + } + res.json(updated); + }); + router2.post("/issues/:id/release", async (req, res) => { + const id = req.params.id; + const existing = await svc.getById(id); + if (!existing) { + res.status(404).json({ error: "Issue not found" }); + return; + } + assertCompanyAccess(req, existing.companyId); + if (!await assertAgentRunCheckoutOwnership(req, res, existing)) return; + const actorRunId = requireAgentRunId(req, res); + if (req.actor.type === "agent" && !actorRunId) return; + const released = await svc.release( + id, + req.actor.type === "agent" ? req.actor.agentId : void 0, + actorRunId + ); + if (!released) { + res.status(404).json({ error: "Issue not found" }); + return; + } + const actor = getActorInfo(req); + await logActivity(db, { + companyId: released.companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + runId: actor.runId, + action: "issue.released", + entityType: "issue", + entityId: released.id + }); + res.json(released); + }); + router2.get("/issues/:id/comments", async (req, res) => { + const id = req.params.id; + const issue2 = await svc.getById(id); + if (!issue2) { + res.status(404).json({ error: "Issue not found" }); + return; + } + assertCompanyAccess(req, issue2.companyId); + const afterCommentId = typeof req.query.after === "string" && req.query.after.trim().length > 0 ? req.query.after.trim() : typeof req.query.afterCommentId === "string" && req.query.afterCommentId.trim().length > 0 ? req.query.afterCommentId.trim() : null; + const order = typeof req.query.order === "string" && req.query.order.trim().toLowerCase() === "asc" ? "asc" : "desc"; + const limitRaw = typeof req.query.limit === "string" && req.query.limit.trim().length > 0 ? Number(req.query.limit) : null; + const limit = limitRaw && Number.isFinite(limitRaw) && limitRaw > 0 ? Math.min(Math.floor(limitRaw), MAX_ISSUE_COMMENT_LIMIT) : null; + const comments = await svc.listComments(id, { + afterCommentId, + order, + limit + }); + res.json(comments); + }); + router2.get("/issues/:id/comments/:commentId", async (req, res) => { + const id = req.params.id; + const commentId = req.params.commentId; + const issue2 = await svc.getById(id); + if (!issue2) { + res.status(404).json({ error: "Issue not found" }); + return; + } + assertCompanyAccess(req, issue2.companyId); + const comment = await svc.getComment(commentId); + if (!comment || comment.issueId !== id) { + res.status(404).json({ error: "Comment not found" }); + return; + } + res.json(comment); + }); + router2.delete("/issues/:id/comments/:commentId", async (req, res) => { + const id = req.params.id; + const commentId = req.params.commentId; + const issue2 = await svc.getById(id); + if (!issue2) { + res.status(404).json({ error: "Issue not found" }); + return; + } + assertCompanyAccess(req, issue2.companyId); + if (!await assertAgentRunCheckoutOwnership(req, res, issue2)) return; + const comment = await svc.getComment(commentId); + if (!comment || comment.issueId !== id) { + res.status(404).json({ error: "Comment not found" }); + return; + } + const actor = getActorInfo(req); + const actorOwnsComment = actor.actorType === "agent" ? comment.authorAgentId === actor.agentId : comment.authorUserId === actor.actorId; + if (!actorOwnsComment) { + res.status(403).json({ error: "Only the comment author can cancel queued comments" }); + return; + } + const activeRun = await resolveActiveIssueRun(issue2); + if (!activeRun) { + res.status(409).json({ error: "Queued comment can no longer be canceled" }); + return; + } + if (!isQueuedIssueCommentForActiveRun({ comment, activeRun })) { + res.status(409).json({ error: "Only queued comments can be canceled" }); + return; + } + const removed = await svc.removeComment(commentId); + if (!removed) { + res.status(404).json({ error: "Comment not found" }); + return; + } + await logActivity(db, { + companyId: issue2.companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + runId: actor.runId, + action: "issue.comment_cancelled", + entityType: "issue", + entityId: issue2.id, + details: { + commentId: removed.id, + bodySnippet: removed.body.slice(0, 120), + identifier: issue2.identifier, + issueTitle: issue2.title, + source: "queue_cancel", + queueTargetRunId: activeRun.id + } + }); + res.json(removed); + }); + router2.get("/issues/:id/feedback-votes", async (req, res) => { + const id = req.params.id; + const issue2 = await svc.getById(id); + if (!issue2) { + res.status(404).json({ error: "Issue not found" }); + return; + } + assertCompanyAccess(req, issue2.companyId); + if (req.actor.type !== "board") { + res.status(403).json({ error: "Only board users can view feedback votes" }); + return; + } + const votes = await feedback.listIssueVotesForUser(id, req.actor.userId ?? "local-board"); + res.json(votes); + }); + router2.get("/issues/:id/feedback-traces", async (req, res) => { + const id = req.params.id; + const issue2 = await svc.getById(id); + if (!issue2) { + res.status(404).json({ error: "Issue not found" }); + return; + } + assertCompanyAccess(req, issue2.companyId); + if (req.actor.type !== "board") { + res.status(403).json({ error: "Only board users can view feedback traces" }); + return; + } + const targetTypeRaw = typeof req.query.targetType === "string" ? req.query.targetType : void 0; + const voteRaw = typeof req.query.vote === "string" ? req.query.vote : void 0; + const statusRaw = typeof req.query.status === "string" ? req.query.status : void 0; + const targetType = targetTypeRaw ? feedbackTargetTypeSchema.parse(targetTypeRaw) : void 0; + const vote = voteRaw ? feedbackVoteValueSchema.parse(voteRaw) : void 0; + const status = statusRaw ? feedbackTraceStatusSchema.parse(statusRaw) : void 0; + const traces = await feedback.listFeedbackTraces({ + companyId: issue2.companyId, + issueId: issue2.id, + targetType, + vote, + status, + from: parseDateQuery(req.query.from, "from"), + to: parseDateQuery(req.query.to, "to"), + sharedOnly: parseBooleanQuery(req.query.sharedOnly), + includePayload: parseBooleanQuery(req.query.includePayload) + }); + res.json(traces); + }); + router2.get("/feedback-traces/:traceId", async (req, res) => { + const traceId = req.params.traceId; + if (req.actor.type !== "board") { + res.status(403).json({ error: "Only board users can view feedback traces" }); + return; + } + const includePayload = parseBooleanQuery(req.query.includePayload) || req.query.includePayload === void 0; + const trace = await feedback.getFeedbackTraceById(traceId, includePayload); + if (!trace || !actorCanAccessCompany(req, trace.companyId)) { + res.status(404).json({ error: "Feedback trace not found" }); + return; + } + res.json(trace); + }); + router2.get("/feedback-traces/:traceId/bundle", async (req, res) => { + const traceId = req.params.traceId; + if (req.actor.type !== "board") { + res.status(403).json({ error: "Only board users can view feedback trace bundles" }); + return; + } + const bundle = await feedback.getFeedbackTraceBundle(traceId); + if (!bundle || !actorCanAccessCompany(req, bundle.companyId)) { + res.status(404).json({ error: "Feedback trace not found" }); + return; + } + res.json(bundle); + }); + router2.post("/issues/:id/comments", validate(addIssueCommentSchema), async (req, res) => { + const id = req.params.id; + const issue2 = await svc.getById(id); + if (!issue2) { + res.status(404).json({ error: "Issue not found" }); + return; + } + assertCompanyAccess(req, issue2.companyId); + if (!await assertAgentRunCheckoutOwnership(req, res, issue2)) return; + const closedExecutionWorkspace = await getClosedIssueExecutionWorkspace(issue2); + if (closedExecutionWorkspace) { + respondClosedIssueExecutionWorkspace(res, closedExecutionWorkspace); + return; + } + const actor = getActorInfo(req); + const reopenRequested = req.body.reopen === true; + const interruptRequested = req.body.interrupt === true; + const isClosed = isClosedIssueStatus(issue2.status); + const effectiveReopenRequested = reopenRequested || shouldImplicitlyReopenCommentForAgent({ + issueStatus: issue2.status, + assigneeAgentId: issue2.assigneeAgentId, + actorType: actor.actorType, + actorId: actor.actorId + }); + let reopened = false; + let reopenFromStatus = null; + let interruptedRunId = null; + let currentIssue = issue2; + if (effectiveReopenRequested && isClosed) { + const reopenedIssue = await svc.update(id, { status: "todo" }); + if (!reopenedIssue) { + res.status(404).json({ error: "Issue not found" }); + return; + } + reopened = true; + reopenFromStatus = issue2.status; + currentIssue = reopenedIssue; + await logActivity(db, { + companyId: currentIssue.companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + runId: actor.runId, + action: "issue.updated", + entityType: "issue", + entityId: currentIssue.id, + details: { + status: "todo", + reopened: true, + reopenedFrom: reopenFromStatus, + source: "comment", + identifier: currentIssue.identifier + } + }); + } + if (interruptRequested) { + if (req.actor.type !== "board") { + res.status(403).json({ error: "Only board users can interrupt active runs from issue comments" }); + return; + } + const runToInterrupt = await resolveActiveIssueRun(currentIssue); + if (runToInterrupt) { + const cancelled = await heartbeat.cancelRun(runToInterrupt.id); + if (cancelled) { + interruptedRunId = cancelled.id; + await logActivity(db, { + companyId: cancelled.companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + runId: actor.runId, + action: "heartbeat.cancelled", + entityType: "heartbeat_run", + entityId: cancelled.id, + details: { agentId: cancelled.agentId, source: "issue_comment_interrupt", issueId: currentIssue.id } + }); + } + } + } + const comment = await svc.addComment(id, req.body.body, { + agentId: actor.agentId ?? void 0, + userId: actor.actorType === "user" ? actor.actorId : void 0, + runId: actor.runId + }); + if (actor.runId) { + await heartbeat.reportRunActivity(actor.runId).catch((err) => logger.warn({ err, runId: actor.runId }, "failed to clear detached run warning after issue comment")); + } + await logActivity(db, { + companyId: currentIssue.companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + runId: actor.runId, + action: "issue.comment_added", + entityType: "issue", + entityId: currentIssue.id, + details: { + commentId: comment.id, + bodySnippet: comment.body.slice(0, 120), + identifier: currentIssue.identifier, + issueTitle: currentIssue.title, + ...reopened ? { reopened: true, reopenedFrom: reopenFromStatus, source: "comment" } : {}, + ...interruptedRunId ? { interruptedRunId } : {} + } + }); + void (async () => { + const wakeups = /* @__PURE__ */ new Map(); + const assigneeId = currentIssue.assigneeAgentId; + const actorIsAgent = actor.actorType === "agent"; + const selfComment = actorIsAgent && actor.actorId === assigneeId; + const skipWake = selfComment || isClosed; + if (assigneeId && (reopened || !skipWake)) { + if (reopened) { + wakeups.set(assigneeId, { + source: "automation", + triggerDetail: "system", + reason: "issue_reopened_via_comment", + payload: { + issueId: currentIssue.id, + commentId: comment.id, + reopenedFrom: reopenFromStatus, + mutation: "comment", + ...interruptedRunId ? { interruptedRunId } : {} + }, + requestedByActorType: actor.actorType, + requestedByActorId: actor.actorId, + contextSnapshot: { + issueId: currentIssue.id, + taskId: currentIssue.id, + commentId: comment.id, + wakeCommentId: comment.id, + source: "issue.comment.reopen", + wakeReason: "issue_reopened_via_comment", + reopenedFrom: reopenFromStatus, + ...interruptedRunId ? { interruptedRunId } : {} + } + }); + } else { + wakeups.set(assigneeId, { + source: "automation", + triggerDetail: "system", + reason: "issue_commented", + payload: { + issueId: currentIssue.id, + commentId: comment.id, + mutation: "comment", + ...interruptedRunId ? { interruptedRunId } : {} + }, + requestedByActorType: actor.actorType, + requestedByActorId: actor.actorId, + contextSnapshot: { + issueId: currentIssue.id, + taskId: currentIssue.id, + commentId: comment.id, + wakeCommentId: comment.id, + source: "issue.comment", + wakeReason: "issue_commented", + ...interruptedRunId ? { interruptedRunId } : {} + } + }); + } + } + let mentionedIds = []; + try { + mentionedIds = await svc.findMentionedAgents(issue2.companyId, req.body.body); + } catch (err) { + logger.warn({ err, issueId: id }, "failed to resolve @-mentions"); + } + for (const mentionedId of mentionedIds) { + if (wakeups.has(mentionedId)) continue; + if (actorIsAgent && actor.actorId === mentionedId) continue; + wakeups.set(mentionedId, { + source: "automation", + triggerDetail: "system", + reason: "issue_comment_mentioned", + payload: { issueId: id, commentId: comment.id }, + requestedByActorType: actor.actorType, + requestedByActorId: actor.actorId, + contextSnapshot: { + issueId: id, + taskId: id, + commentId: comment.id, + wakeCommentId: comment.id, + wakeReason: "issue_comment_mentioned", + source: "comment.mention" + } + }); + } + for (const [agentId, wakeup] of wakeups.entries()) { + heartbeat.wakeup(agentId, wakeup).catch((err) => logger.warn({ err, issueId: currentIssue.id, agentId }, "failed to wake agent on issue comment")); + } + })(); + res.status(201).json(comment); + }); + router2.post("/issues/:id/feedback-votes", validate(upsertIssueFeedbackVoteSchema), async (req, res) => { + const id = req.params.id; + const issue2 = await svc.getById(id); + if (!issue2) { + res.status(404).json({ error: "Issue not found" }); + return; + } + assertCompanyAccess(req, issue2.companyId); + if (req.actor.type !== "board") { + res.status(403).json({ error: "Only board users can vote on AI feedback" }); + return; + } + const actor = getActorInfo(req); + const result = await feedback.saveIssueVote({ + issueId: id, + targetType: req.body.targetType, + targetId: req.body.targetId, + vote: req.body.vote, + reason: req.body.reason, + authorUserId: req.actor.userId ?? "local-board", + allowSharing: req.body.allowSharing === true + }); + await logActivity(db, { + companyId: issue2.companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + runId: actor.runId, + action: "issue.feedback_vote_saved", + entityType: "issue", + entityId: issue2.id, + details: { + identifier: issue2.identifier, + targetType: result.vote.targetType, + targetId: result.vote.targetId, + vote: result.vote.vote, + hasReason: Boolean(result.vote.reason), + sharingEnabled: result.sharingEnabled + } + }); + if (result.consentEnabledNow) { + await logActivity(db, { + companyId: issue2.companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + runId: actor.runId, + action: "company.feedback_data_sharing_updated", + entityType: "company", + entityId: issue2.companyId, + details: { + feedbackDataSharingEnabled: true, + source: "issue_feedback_vote" + } + }); + } + if (result.persistedSharingPreference) { + const settings = await instanceSettings2.get(); + const companyIds = await instanceSettings2.listCompanyIds(); + await Promise.all( + companyIds.map( + (companyId) => logActivity(db, { + companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + runId: actor.runId, + action: "instance.settings.general_updated", + entityType: "instance_settings", + entityId: settings.id, + details: { + general: settings.general, + changedKeys: ["feedbackDataSharingPreference"], + source: "issue_feedback_vote" + } + }) + ) + ); + } + if (result.sharingEnabled && result.traceId && feedbackExportService) { + try { + await feedbackExportService.flushPendingFeedbackTraces({ + companyId: issue2.companyId, + traceId: result.traceId, + limit: 1 + }); + } catch (err) { + logger.warn({ err, issueId: issue2.id, traceId: result.traceId }, "failed to flush shared feedback trace immediately"); + } + } + res.status(201).json(result.vote); + }); + router2.get("/issues/:id/attachments", async (req, res) => { + const issueId = req.params.id; + const issue2 = await svc.getById(issueId); + if (!issue2) { + res.status(404).json({ error: "Issue not found" }); + return; + } + assertCompanyAccess(req, issue2.companyId); + const attachments = await svc.listAttachments(issueId); + res.json(attachments.map(withContentPath)); + }); + router2.post("/companies/:companyId/issues/:issueId/attachments", async (req, res) => { + const companyId = req.params.companyId; + const issueId = req.params.issueId; + assertCompanyAccess(req, companyId); + const issue2 = await svc.getById(issueId); + if (!issue2) { + res.status(404).json({ error: "Issue not found" }); + return; + } + if (issue2.companyId !== companyId) { + res.status(422).json({ error: "Issue does not belong to company" }); + return; + } + try { + await runSingleFileUpload(req, res); + } catch (err) { + if (err instanceof import_multer.default.MulterError) { + if (err.code === "LIMIT_FILE_SIZE") { + res.status(422).json({ error: `Attachment exceeds ${MAX_ATTACHMENT_BYTES} bytes` }); + return; + } + res.status(400).json({ error: err.message }); + return; + } + throw err; + } + const file2 = req.file; + if (!file2) { + res.status(400).json({ error: "Missing file field 'file'" }); + return; + } + const contentType = normalizeContentType(file2.mimetype); + if (file2.buffer.length <= 0) { + res.status(422).json({ error: "Attachment is empty" }); + return; + } + const parsedMeta = createIssueAttachmentMetadataSchema.safeParse(req.body ?? {}); + if (!parsedMeta.success) { + res.status(400).json({ error: "Invalid attachment metadata", details: parsedMeta.error.issues }); + return; + } + const actor = getActorInfo(req); + const stored = await storage.putFile({ + companyId, + namespace: `issues/${issueId}`, + originalFilename: file2.originalname || null, + contentType, + body: file2.buffer + }); + const attachment = await svc.createAttachment({ + issueId, + issueCommentId: parsedMeta.data.issueCommentId ?? null, + provider: stored.provider, + objectKey: stored.objectKey, + contentType: stored.contentType, + byteSize: stored.byteSize, + sha256: stored.sha256, + originalFilename: stored.originalFilename, + createdByAgentId: actor.agentId, + createdByUserId: actor.actorType === "user" ? actor.actorId : null + }); + await logActivity(db, { + companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + runId: actor.runId, + action: "issue.attachment_added", + entityType: "issue", + entityId: issueId, + details: { + attachmentId: attachment.id, + originalFilename: attachment.originalFilename, + contentType: attachment.contentType, + byteSize: attachment.byteSize + } + }); + res.status(201).json(withContentPath(attachment)); + }); + router2.get("/attachments/:attachmentId/content", async (req, res, next) => { + const attachmentId = req.params.attachmentId; + const attachment = await svc.getAttachmentById(attachmentId); + if (!attachment) { + res.status(404).json({ error: "Attachment not found" }); + return; + } + assertCompanyAccess(req, attachment.companyId); + const object2 = await storage.getObject(attachment.companyId, attachment.objectKey); + const responseContentType = normalizeContentType(attachment.contentType || object2.contentType); + res.setHeader("Content-Type", responseContentType); + res.setHeader("Content-Length", String(attachment.byteSize || object2.contentLength || 0)); + res.setHeader("Cache-Control", "private, max-age=60"); + res.setHeader("X-Content-Type-Options", "nosniff"); + if (responseContentType === SVG_CONTENT_TYPE) { + res.setHeader("Content-Security-Policy", "sandbox; default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'"); + } + const filename = attachment.originalFilename ?? "attachment"; + const disposition = isInlineAttachmentContentType(responseContentType) ? "inline" : "attachment"; + res.setHeader("Content-Disposition", `${disposition}; filename="${filename.replaceAll('"', "")}"`); + object2.stream.on("error", (err) => { + next(err); + }); + object2.stream.pipe(res); + }); + router2.delete("/attachments/:attachmentId", async (req, res) => { + const attachmentId = req.params.attachmentId; + const attachment = await svc.getAttachmentById(attachmentId); + if (!attachment) { + res.status(404).json({ error: "Attachment not found" }); + return; + } + assertCompanyAccess(req, attachment.companyId); + try { + await storage.deleteObject(attachment.companyId, attachment.objectKey); + } catch (err) { + logger.warn({ err, attachmentId }, "storage delete failed while removing attachment"); + } + const removed = await svc.removeAttachment(attachmentId); + if (!removed) { + res.status(404).json({ error: "Attachment not found" }); + return; + } + const actor = getActorInfo(req); + await logActivity(db, { + companyId: removed.companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + runId: actor.runId, + action: "issue.attachment_removed", + entityType: "issue", + entityId: removed.issueId, + details: { + attachmentId: removed.id + } + }); + res.json({ ok: true }); + }); + return router2; +} + +// server/src/routes/routines.ts +var import_express7 = __toESM(require_express2(), 1); +function routineRoutes(db) { + const router2 = (0, import_express7.Router)(); + const svc = routineService(db); + const access = accessService(db); + async function assertBoardCanAssignTasks(req, companyId) { + assertCompanyAccess(req, companyId); + if (req.actor.type !== "board") return; + if (req.actor.source === "local_implicit" || req.actor.isInstanceAdmin) return; + const allowed2 = await access.canUser(companyId, req.actor.userId, "tasks:assign"); + if (!allowed2) { + throw forbidden("Missing permission: tasks:assign"); + } + } + function assertCanManageCompanyRoutine(req, companyId, assigneeAgentId) { + assertCompanyAccess(req, companyId); + if (req.actor.type === "board") return; + if (req.actor.type !== "agent" || !req.actor.agentId) throw unauthorized(); + if (assigneeAgentId !== req.actor.agentId) { + throw forbidden("Agents can only manage routines assigned to themselves"); + } + } + async function assertCanManageExistingRoutine(req, routineId) { + const routine = await svc.get(routineId); + if (!routine) return null; + assertCompanyAccess(req, routine.companyId); + if (req.actor.type === "board") return routine; + if (req.actor.type !== "agent" || !req.actor.agentId) throw unauthorized(); + if (routine.assigneeAgentId !== req.actor.agentId) { + throw forbidden("Agents can only manage routines assigned to themselves"); + } + return routine; + } + router2.get("/companies/:companyId/routines", async (req, res) => { + const companyId = req.params.companyId; + assertCompanyAccess(req, companyId); + const result = await svc.list(companyId); + res.json(result); + }); + router2.post("/companies/:companyId/routines", validate(createRoutineSchema), async (req, res) => { + const companyId = req.params.companyId; + await assertBoardCanAssignTasks(req, companyId); + assertCanManageCompanyRoutine(req, companyId, req.body.assigneeAgentId); + const created = await svc.create(companyId, req.body, { + agentId: req.actor.type === "agent" ? req.actor.agentId : null, + userId: req.actor.type === "board" ? req.actor.userId ?? "board" : null + }); + const actor = getActorInfo(req); + await logActivity(db, { + companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + runId: actor.runId, + action: "routine.created", + entityType: "routine", + entityId: created.id, + details: { title: created.title, assigneeAgentId: created.assigneeAgentId } + }); + const telemetryClient = getTelemetryClient(); + if (telemetryClient) { + trackRoutineCreated(telemetryClient); + } + res.status(201).json(created); + }); + router2.get("/routines/:id", async (req, res) => { + const detail = await svc.getDetail(req.params.id); + if (!detail) { + res.status(404).json({ error: "Routine not found" }); + return; + } + assertCompanyAccess(req, detail.companyId); + res.json(detail); + }); + router2.patch("/routines/:id", validate(updateRoutineSchema), async (req, res) => { + const routine = await assertCanManageExistingRoutine(req, req.params.id); + if (!routine) { + res.status(404).json({ error: "Routine not found" }); + return; + } + const assigneeWillChange = req.body.assigneeAgentId !== void 0 && req.body.assigneeAgentId !== routine.assigneeAgentId; + if (assigneeWillChange) { + await assertBoardCanAssignTasks(req, routine.companyId); + } + const statusWillActivate = req.body.status !== void 0 && req.body.status === "active" && routine.status !== "active"; + if (statusWillActivate) { + await assertBoardCanAssignTasks(req, routine.companyId); + } + if (req.actor.type === "agent" && req.body.assigneeAgentId !== void 0 && req.body.assigneeAgentId !== req.actor.agentId) { + throw forbidden("Agents can only assign routines to themselves"); + } + const updated = await svc.update(routine.id, req.body, { + agentId: req.actor.type === "agent" ? req.actor.agentId : null, + userId: req.actor.type === "board" ? req.actor.userId ?? "board" : null + }); + const actor = getActorInfo(req); + await logActivity(db, { + companyId: routine.companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + runId: actor.runId, + action: "routine.updated", + entityType: "routine", + entityId: routine.id, + details: { title: updated?.title ?? routine.title } + }); + res.json(updated); + }); + router2.get("/routines/:id/runs", async (req, res) => { + const routine = await svc.get(req.params.id); + if (!routine) { + res.status(404).json({ error: "Routine not found" }); + return; + } + assertCompanyAccess(req, routine.companyId); + const limit = Number(req.query.limit ?? 50); + const result = await svc.listRuns(routine.id, Number.isFinite(limit) ? limit : 50); + res.json(result); + }); + router2.post("/routines/:id/triggers", validate(createRoutineTriggerSchema), async (req, res) => { + const routine = await assertCanManageExistingRoutine(req, req.params.id); + if (!routine) { + res.status(404).json({ error: "Routine not found" }); + return; + } + await assertBoardCanAssignTasks(req, routine.companyId); + const created = await svc.createTrigger(routine.id, req.body, { + agentId: req.actor.type === "agent" ? req.actor.agentId : null, + userId: req.actor.type === "board" ? req.actor.userId ?? "board" : null + }); + const actor = getActorInfo(req); + await logActivity(db, { + companyId: routine.companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + runId: actor.runId, + action: "routine.trigger_created", + entityType: "routine_trigger", + entityId: created.trigger.id, + details: { routineId: routine.id, kind: created.trigger.kind } + }); + res.status(201).json(created); + }); + router2.patch("/routine-triggers/:id", validate(updateRoutineTriggerSchema), async (req, res) => { + const trigger = await svc.getTrigger(req.params.id); + if (!trigger) { + res.status(404).json({ error: "Routine trigger not found" }); + return; + } + const routine = await assertCanManageExistingRoutine(req, trigger.routineId); + if (!routine) { + res.status(404).json({ error: "Routine not found" }); + return; + } + await assertBoardCanAssignTasks(req, routine.companyId); + const updated = await svc.updateTrigger(trigger.id, req.body, { + agentId: req.actor.type === "agent" ? req.actor.agentId : null, + userId: req.actor.type === "board" ? req.actor.userId ?? "board" : null + }); + const actor = getActorInfo(req); + await logActivity(db, { + companyId: routine.companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + runId: actor.runId, + action: "routine.trigger_updated", + entityType: "routine_trigger", + entityId: trigger.id, + details: { routineId: routine.id, kind: updated?.kind ?? trigger.kind } + }); + res.json(updated); + }); + router2.delete("/routine-triggers/:id", async (req, res) => { + const trigger = await svc.getTrigger(req.params.id); + if (!trigger) { + res.status(404).json({ error: "Routine trigger not found" }); + return; + } + const routine = await assertCanManageExistingRoutine(req, trigger.routineId); + if (!routine) { + res.status(404).json({ error: "Routine not found" }); + return; + } + await svc.deleteTrigger(trigger.id); + const actor = getActorInfo(req); + await logActivity(db, { + companyId: routine.companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + runId: actor.runId, + action: "routine.trigger_deleted", + entityType: "routine_trigger", + entityId: trigger.id, + details: { routineId: routine.id, kind: trigger.kind } + }); + res.status(204).end(); + }); + router2.post( + "/routine-triggers/:id/rotate-secret", + validate(rotateRoutineTriggerSecretSchema), + async (req, res) => { + const trigger = await svc.getTrigger(req.params.id); + if (!trigger) { + res.status(404).json({ error: "Routine trigger not found" }); + return; + } + const routine = await assertCanManageExistingRoutine(req, trigger.routineId); + if (!routine) { + res.status(404).json({ error: "Routine not found" }); + return; + } + const rotated = await svc.rotateTriggerSecret(trigger.id, { + agentId: req.actor.type === "agent" ? req.actor.agentId : null, + userId: req.actor.type === "board" ? req.actor.userId ?? "board" : null + }); + const actor = getActorInfo(req); + await logActivity(db, { + companyId: routine.companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + runId: actor.runId, + action: "routine.trigger_secret_rotated", + entityType: "routine_trigger", + entityId: trigger.id, + details: { routineId: routine.id } + }); + res.json(rotated); + } + ); + router2.post("/routines/:id/run", validate(runRoutineSchema), async (req, res) => { + const routine = await assertCanManageExistingRoutine(req, req.params.id); + if (!routine) { + res.status(404).json({ error: "Routine not found" }); + return; + } + await assertBoardCanAssignTasks(req, routine.companyId); + const run = await svc.runRoutine(routine.id, req.body); + const actor = getActorInfo(req); + await logActivity(db, { + companyId: routine.companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + runId: actor.runId, + action: "routine.run_triggered", + entityType: "routine_run", + entityId: run.id, + details: { routineId: routine.id, source: run.source, status: run.status } + }); + res.status(202).json(run); + }); + router2.post("/routine-triggers/public/:publicId/fire", async (req, res) => { + const result = await svc.firePublicTrigger(req.params.publicId, { + authorizationHeader: req.header("authorization"), + signatureHeader: req.header("x-taskcore-signature"), + hubSignatureHeader: req.header("x-hub-signature-256"), + timestampHeader: req.header("x-taskcore-timestamp"), + idempotencyKey: req.header("idempotency-key"), + rawBody: req.rawBody ?? null, + payload: typeof req.body === "object" && req.body !== null ? req.body : null + }); + res.status(202).json(result); + }); + return router2; +} + +// server/src/routes/execution-workspaces.ts +init_drizzle_orm(); +var import_express8 = __toESM(require_express2(), 1); +init_src2(); +function executionWorkspaceRoutes(db) { + const router2 = (0, import_express8.Router)(); + const svc = executionWorkspaceService(db); + const workspaceOperationsSvc = workspaceOperationService(db); + router2.get("/companies/:companyId/execution-workspaces", async (req, res) => { + const companyId = req.params.companyId; + assertCompanyAccess(req, companyId); + const workspaces = await svc.list(companyId, { + projectId: req.query.projectId, + projectWorkspaceId: req.query.projectWorkspaceId, + issueId: req.query.issueId, + status: req.query.status, + reuseEligible: req.query.reuseEligible === "true" + }); + res.json(workspaces); + }); + router2.get("/execution-workspaces/:id", async (req, res) => { + const id = req.params.id; + const workspace = await svc.getById(id); + if (!workspace) { + res.status(404).json({ error: "Execution workspace not found" }); + return; + } + assertCompanyAccess(req, workspace.companyId); + res.json(workspace); + }); + router2.get("/execution-workspaces/:id/close-readiness", async (req, res) => { + const id = req.params.id; + const workspace = await svc.getById(id); + if (!workspace) { + res.status(404).json({ error: "Execution workspace not found" }); + return; + } + assertCompanyAccess(req, workspace.companyId); + const readiness = await svc.getCloseReadiness(id); + if (!readiness) { + res.status(404).json({ error: "Execution workspace not found" }); + return; + } + res.json(readiness); + }); + router2.get("/execution-workspaces/:id/workspace-operations", async (req, res) => { + const id = req.params.id; + const workspace = await svc.getById(id); + if (!workspace) { + res.status(404).json({ error: "Execution workspace not found" }); + return; + } + assertCompanyAccess(req, workspace.companyId); + const operations = await workspaceOperationsSvc.listForExecutionWorkspace(id); + res.json(operations); + }); + async function handleExecutionWorkspaceRuntimeCommand(req, res) { + const id = req.params.id; + const action = String(req.params.action ?? "").trim().toLowerCase(); + if (action !== "start" && action !== "stop" && action !== "restart" && action !== "run") { + res.status(404).json({ error: "Workspace command action not found" }); + return; + } + const existing = await svc.getById(id); + if (!existing) { + res.status(404).json({ error: "Execution workspace not found" }); + return; + } + assertCompanyAccess(req, existing.companyId); + const workspaceCwd = existing.cwd; + if (!workspaceCwd) { + res.status(422).json({ error: "Execution workspace needs a local path before Taskcore can run workspace commands" }); + return; + } + const projectWorkspace = existing.projectWorkspaceId ? await db.select({ + id: projectWorkspaces.id, + cwd: projectWorkspaces.cwd, + repoUrl: projectWorkspaces.repoUrl, + repoRef: projectWorkspaces.repoRef, + defaultRef: projectWorkspaces.defaultRef, + metadata: projectWorkspaces.metadata + }).from(projectWorkspaces).where( + and( + eq(projectWorkspaces.id, existing.projectWorkspaceId), + eq(projectWorkspaces.companyId, existing.companyId) + ) + ).then((rows) => rows[0] ?? null) : null; + const projectWorkspaceRuntime = readProjectWorkspaceRuntimeConfig( + projectWorkspace?.metadata ?? null + )?.workspaceRuntime ?? null; + const projectPolicy = existing.projectId ? await db.select({ + executionWorkspacePolicy: projects.executionWorkspacePolicy + }).from(projects).where( + and( + eq(projects.id, existing.projectId), + eq(projects.companyId, existing.companyId) + ) + ).then((rows) => parseProjectExecutionWorkspacePolicy(rows[0]?.executionWorkspacePolicy)) : null; + const effectiveRuntimeConfig = existing.config?.workspaceRuntime ?? projectWorkspaceRuntime ?? null; + const target = req.body; + const configuredServices = effectiveRuntimeConfig ? listConfiguredRuntimeServiceEntries({ workspaceRuntime: effectiveRuntimeConfig }) : []; + const workspaceCommand = effectiveRuntimeConfig ? findWorkspaceCommandDefinition(effectiveRuntimeConfig, target.workspaceCommandId ?? null) : null; + if (target.workspaceCommandId && !workspaceCommand) { + res.status(404).json({ error: "Workspace command not found for this execution workspace" }); + return; + } + if (target.runtimeServiceId && !(existing.runtimeServices ?? []).some((service) => service.id === target.runtimeServiceId)) { + res.status(404).json({ error: "Runtime service not found for this execution workspace" }); + return; + } + const matchedRuntimeService = workspaceCommand?.kind === "service" && !target.runtimeServiceId ? matchWorkspaceRuntimeServiceToCommand(workspaceCommand, existing.runtimeServices ?? []) : null; + const selectedRuntimeServiceId = target.runtimeServiceId ?? matchedRuntimeService?.id ?? null; + const selectedServiceIndex = workspaceCommand?.kind === "service" ? workspaceCommand.serviceIndex : target.serviceIndex ?? null; + if (selectedServiceIndex !== void 0 && selectedServiceIndex !== null && (selectedServiceIndex < 0 || selectedServiceIndex >= configuredServices.length)) { + res.status(422).json({ error: "Selected runtime service is not defined in this execution workspace runtime config" }); + return; + } + if (workspaceCommand?.kind === "job" && action !== "run") { + res.status(422).json({ error: `Workspace job "${workspaceCommand.name}" can only be run` }); + return; + } + if (workspaceCommand?.kind === "service" && action === "run") { + res.status(422).json({ error: `Workspace service "${workspaceCommand.name}" should be started or restarted, not run` }); + return; + } + if (action === "run" && !workspaceCommand) { + res.status(422).json({ error: "Select a workspace job to run" }); + return; + } + if ((action === "start" || action === "restart") && !effectiveRuntimeConfig) { + res.status(422).json({ error: "Execution workspace has no workspace command configuration or inherited project workspace default" }); + return; + } + const actor = getActorInfo(req); + const recorder = workspaceOperationsSvc.createRecorder({ + companyId: existing.companyId, + executionWorkspaceId: existing.id + }); + let runtimeServiceCount = existing.runtimeServices?.length ?? 0; + const stdout = []; + const stderr = []; + const operation2 = await recorder.recordOperation({ + phase: action === "stop" ? "workspace_teardown" : "workspace_provision", + command: workspaceCommand?.command ?? `workspace command ${action}`, + cwd: existing.cwd, + metadata: { + action, + executionWorkspaceId: existing.id, + workspaceCommandId: workspaceCommand?.id ?? target.workspaceCommandId ?? null, + workspaceCommandKind: workspaceCommand?.kind ?? null, + workspaceCommandName: workspaceCommand?.name ?? null, + runtimeServiceId: selectedRuntimeServiceId, + serviceIndex: selectedServiceIndex + }, + run: async () => { + const ensureWorkspaceAvailable = async () => await ensurePersistedExecutionWorkspaceAvailable({ + base: { + baseCwd: projectWorkspace?.cwd ?? workspaceCwd, + source: existing.mode === "shared_workspace" ? "project_primary" : "task_session", + projectId: existing.projectId, + workspaceId: existing.projectWorkspaceId, + repoUrl: existing.repoUrl, + repoRef: existing.baseRef + }, + workspace: { + mode: existing.mode, + strategyType: existing.strategyType, + cwd: existing.cwd, + providerRef: existing.providerRef, + projectId: existing.projectId, + projectWorkspaceId: existing.projectWorkspaceId, + repoUrl: existing.repoUrl, + baseRef: existing.baseRef, + branchName: existing.branchName, + config: { + ...existing.config, + provisionCommand: existing.config?.provisionCommand ?? projectPolicy?.workspaceStrategy?.provisionCommand ?? null + } + }, + issue: existing.sourceIssueId ? { + id: existing.sourceIssueId, + identifier: null, + title: existing.name + } : null, + agent: { + id: actor.agentId ?? null, + name: actor.actorType === "user" ? "Board" : "Agent", + companyId: existing.companyId + }, + recorder + }); + if (action === "run") { + if (!workspaceCommand || workspaceCommand.kind !== "job") { + throw new Error("Workspace job selection is required"); + } + const availableWorkspace = await ensureWorkspaceAvailable(); + if (!availableWorkspace) { + throw new Error("Execution workspace needs a local path before Taskcore can run workspace commands"); + } + return await runWorkspaceJobForControl({ + actor: { + id: actor.agentId ?? null, + name: actor.actorType === "user" ? "Board" : "Agent", + companyId: existing.companyId + }, + issue: existing.sourceIssueId ? { + id: existing.sourceIssueId, + identifier: null, + title: existing.name + } : null, + workspace: availableWorkspace, + command: workspaceCommand.rawConfig, + adapterEnv: {}, + recorder, + metadata: { + action, + executionWorkspaceId: existing.id, + workspaceCommandId: workspaceCommand.id + } + }).then((nestedOperation) => ({ + status: "succeeded", + exitCode: 0, + metadata: { + nestedOperationId: nestedOperation?.id ?? null, + runtimeServiceCount + } + })); + } + const onLog = async (stream, chunk) => { + if (stream === "stdout") stdout.push(chunk); + else stderr.push(chunk); + }; + if (action === "stop" || action === "restart") { + await stopRuntimeServicesForExecutionWorkspace({ + db, + executionWorkspaceId: existing.id, + workspaceCwd, + runtimeServiceId: selectedRuntimeServiceId + }); + } + if (action === "start" || action === "restart") { + const availableWorkspace = await ensureWorkspaceAvailable(); + if (!availableWorkspace) { + throw new Error("Execution workspace needs a local path before Taskcore can manage local runtime services"); + } + const startedServices = await startRuntimeServicesForWorkspaceControl({ + db, + actor: { + id: actor.agentId ?? null, + name: actor.actorType === "user" ? "Board" : "Agent", + companyId: existing.companyId + }, + issue: existing.sourceIssueId ? { + id: existing.sourceIssueId, + identifier: null, + title: existing.name + } : null, + workspace: availableWorkspace, + executionWorkspaceId: existing.id, + config: { workspaceRuntime: effectiveRuntimeConfig }, + adapterEnv: {}, + onLog, + serviceIndex: selectedServiceIndex + }); + runtimeServiceCount = startedServices.length; + } else { + runtimeServiceCount = selectedRuntimeServiceId ? Math.max(0, (existing.runtimeServices?.length ?? 1) - 1) : 0; + } + const currentDesiredState = existing.config?.desiredState ?? ((existing.runtimeServices ?? []).some((service) => service.status === "starting" || service.status === "running") ? "running" : "stopped"); + const nextRuntimeState = selectedRuntimeServiceId && (selectedServiceIndex === void 0 || selectedServiceIndex === null) ? { + desiredState: currentDesiredState, + serviceStates: existing.config?.serviceStates ?? null + } : buildWorkspaceRuntimeDesiredStatePatch({ + config: { workspaceRuntime: effectiveRuntimeConfig }, + currentDesiredState, + currentServiceStates: existing.config?.serviceStates ?? null, + action, + serviceIndex: selectedServiceIndex + }); + const metadata = mergeExecutionWorkspaceConfig(existing.metadata, { + desiredState: nextRuntimeState.desiredState, + serviceStates: nextRuntimeState.serviceStates + }); + await svc.update(existing.id, { metadata }); + return { + status: "succeeded", + stdout: stdout.join(""), + stderr: stderr.join(""), + system: action === "stop" ? "Stopped execution workspace runtime services.\n" : action === "restart" ? "Restarted execution workspace runtime services.\n" : "Started execution workspace runtime services.\n", + metadata: { + runtimeServiceCount, + workspaceCommandId: workspaceCommand?.id ?? target.workspaceCommandId ?? null, + runtimeServiceId: selectedRuntimeServiceId, + serviceIndex: selectedServiceIndex + } + }; + } + }); + const workspace = await svc.getById(id); + if (!workspace) { + res.status(404).json({ error: "Execution workspace not found" }); + return; + } + await logActivity(db, { + companyId: existing.companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + runId: actor.runId, + action: `execution_workspace.runtime_${action}`, + entityType: "execution_workspace", + entityId: existing.id, + details: { + runtimeServiceCount, + workspaceCommandId: workspaceCommand?.id ?? target.workspaceCommandId ?? null, + workspaceCommandKind: workspaceCommand?.kind ?? null, + workspaceCommandName: workspaceCommand?.name ?? null, + runtimeServiceId: selectedRuntimeServiceId, + serviceIndex: selectedServiceIndex + } + }); + res.json({ + workspace, + operation: operation2 + }); + } + router2.post("/execution-workspaces/:id/runtime-services/:action", validate(workspaceRuntimeControlTargetSchema), handleExecutionWorkspaceRuntimeCommand); + router2.post("/execution-workspaces/:id/runtime-commands/:action", validate(workspaceRuntimeControlTargetSchema), handleExecutionWorkspaceRuntimeCommand); + router2.patch("/execution-workspaces/:id", validate(updateExecutionWorkspaceSchema), async (req, res) => { + const id = req.params.id; + const existing = await svc.getById(id); + if (!existing) { + res.status(404).json({ error: "Execution workspace not found" }); + return; + } + assertCompanyAccess(req, existing.companyId); + const patch = { + ...req.body.name === void 0 ? {} : { name: req.body.name }, + ...req.body.cwd === void 0 ? {} : { cwd: req.body.cwd }, + ...req.body.repoUrl === void 0 ? {} : { repoUrl: req.body.repoUrl }, + ...req.body.baseRef === void 0 ? {} : { baseRef: req.body.baseRef }, + ...req.body.branchName === void 0 ? {} : { branchName: req.body.branchName }, + ...req.body.providerRef === void 0 ? {} : { providerRef: req.body.providerRef }, + ...req.body.status === void 0 ? {} : { status: req.body.status }, + ...req.body.cleanupReason === void 0 ? {} : { cleanupReason: req.body.cleanupReason }, + ...req.body.cleanupEligibleAt !== void 0 ? { cleanupEligibleAt: req.body.cleanupEligibleAt ? new Date(req.body.cleanupEligibleAt) : null } : {} + }; + if (req.body.metadata !== void 0 || req.body.config !== void 0) { + const requestedMetadata = req.body.metadata === void 0 ? existing.metadata : req.body.metadata; + patch.metadata = req.body.config === void 0 ? requestedMetadata : mergeExecutionWorkspaceConfig(requestedMetadata, req.body.config ?? null); + } + let workspace = existing; + let cleanupWarnings = []; + const configForCleanup = readExecutionWorkspaceConfig( + patch.metadata ?? existing.metadata ?? null + ); + if (req.body.status === "archived" && existing.status !== "archived") { + const readiness = await svc.getCloseReadiness(existing.id); + if (!readiness) { + res.status(404).json({ error: "Execution workspace not found" }); + return; + } + if (readiness.state === "blocked") { + res.status(409).json({ + error: readiness.blockingReasons[0] ?? "Execution workspace cannot be closed right now", + closeReadiness: readiness + }); + return; + } + const closedAt = /* @__PURE__ */ new Date(); + const archivedWorkspace = await svc.update(id, { + ...patch, + status: "archived", + closedAt, + cleanupReason: null + }); + if (!archivedWorkspace) { + res.status(404).json({ error: "Execution workspace not found" }); + return; + } + workspace = archivedWorkspace; + if (existing.mode === "shared_workspace") { + await db.update(issues).set({ + executionWorkspaceId: null, + updatedAt: /* @__PURE__ */ new Date() + }).where( + and( + eq(issues.companyId, existing.companyId), + eq(issues.executionWorkspaceId, existing.id) + ) + ); + } + try { + await stopRuntimeServicesForExecutionWorkspace({ + db, + executionWorkspaceId: existing.id, + workspaceCwd: existing.cwd + }); + const projectWorkspace = existing.projectWorkspaceId ? await db.select({ + cwd: projectWorkspaces.cwd, + cleanupCommand: projectWorkspaces.cleanupCommand + }).from(projectWorkspaces).where( + and( + eq(projectWorkspaces.id, existing.projectWorkspaceId), + eq(projectWorkspaces.companyId, existing.companyId) + ) + ).then((rows) => rows[0] ?? null) : null; + const projectPolicy = existing.projectId ? await db.select({ + executionWorkspacePolicy: projects.executionWorkspacePolicy + }).from(projects).where(and(eq(projects.id, existing.projectId), eq(projects.companyId, existing.companyId))).then((rows) => parseProjectExecutionWorkspacePolicy(rows[0]?.executionWorkspacePolicy)) : null; + const cleanupResult = await cleanupExecutionWorkspaceArtifacts({ + workspace: existing, + projectWorkspace, + teardownCommand: configForCleanup?.teardownCommand ?? projectPolicy?.workspaceStrategy?.teardownCommand ?? null, + cleanupCommand: configForCleanup?.cleanupCommand ?? null, + recorder: workspaceOperationsSvc.createRecorder({ + companyId: existing.companyId, + executionWorkspaceId: existing.id + }) + }); + cleanupWarnings = cleanupResult.warnings; + const cleanupPatch = { + closedAt, + cleanupReason: cleanupWarnings.length > 0 ? cleanupWarnings.join(" | ") : null + }; + if (!cleanupResult.cleaned) { + cleanupPatch.status = "cleanup_failed"; + } + if (cleanupResult.warnings.length > 0 || !cleanupResult.cleaned) { + workspace = await svc.update(id, cleanupPatch) ?? workspace; + } + } catch (error50) { + const failureReason = error50 instanceof Error ? error50.message : String(error50); + workspace = await svc.update(id, { + status: "cleanup_failed", + closedAt, + cleanupReason: failureReason + }) ?? workspace; + res.status(500).json({ + error: `Failed to archive execution workspace: ${failureReason}` + }); + return; + } + } else { + const updatedWorkspace = await svc.update(id, patch); + if (!updatedWorkspace) { + res.status(404).json({ error: "Execution workspace not found" }); + return; + } + workspace = updatedWorkspace; + } + const actor = getActorInfo(req); + await logActivity(db, { + companyId: existing.companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + runId: actor.runId, + action: "execution_workspace.updated", + entityType: "execution_workspace", + entityId: workspace.id, + details: { + changedKeys: Object.keys(req.body).sort(), + ...cleanupWarnings.length > 0 ? { cleanupWarnings } : {} + } + }); + res.json(workspace); + }); + return router2; +} + +// server/src/routes/goals.ts +var import_express9 = __toESM(require_express2(), 1); +function goalRoutes(db) { + const router2 = (0, import_express9.Router)(); + const svc = goalService(db); + router2.get("/companies/:companyId/goals", async (req, res) => { + const companyId = req.params.companyId; + assertCompanyAccess(req, companyId); + const result = await svc.list(companyId); + res.json(result); + }); + router2.get("/goals/:id", async (req, res) => { + const id = req.params.id; + const goal = await svc.getById(id); + if (!goal) { + res.status(404).json({ error: "Goal not found" }); + return; + } + assertCompanyAccess(req, goal.companyId); + res.json(goal); + }); + router2.post("/companies/:companyId/goals", validate(createGoalSchema), async (req, res) => { + const companyId = req.params.companyId; + assertCompanyAccess(req, companyId); + const goal = await svc.create(companyId, req.body); + const actor = getActorInfo(req); + await logActivity(db, { + companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + action: "goal.created", + entityType: "goal", + entityId: goal.id, + details: { title: goal.title } + }); + const telemetryClient = getTelemetryClient(); + if (telemetryClient) { + trackGoalCreated(telemetryClient, { goalLevel: goal.level }); + } + res.status(201).json(goal); + }); + router2.patch("/goals/:id", validate(updateGoalSchema), async (req, res) => { + const id = req.params.id; + const existing = await svc.getById(id); + if (!existing) { + res.status(404).json({ error: "Goal not found" }); + return; + } + assertCompanyAccess(req, existing.companyId); + const goal = await svc.update(id, req.body); + if (!goal) { + res.status(404).json({ error: "Goal not found" }); + return; + } + const actor = getActorInfo(req); + await logActivity(db, { + companyId: goal.companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + action: "goal.updated", + entityType: "goal", + entityId: goal.id, + details: req.body + }); + res.json(goal); + }); + router2.delete("/goals/:id", async (req, res) => { + const id = req.params.id; + const existing = await svc.getById(id); + if (!existing) { + res.status(404).json({ error: "Goal not found" }); + return; + } + assertCompanyAccess(req, existing.companyId); + const goal = await svc.remove(id); + if (!goal) { + res.status(404).json({ error: "Goal not found" }); + return; + } + const actor = getActorInfo(req); + await logActivity(db, { + companyId: goal.companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + action: "goal.deleted", + entityType: "goal", + entityId: goal.id + }); + res.json(goal); + }); + return router2; +} + +// server/src/routes/approvals.ts +var import_express10 = __toESM(require_express2(), 1); +function redactApprovalPayload(approval) { + return { + ...approval, + payload: redactEventPayload(approval.payload) ?? {} + }; +} +function approvalRoutes(db) { + const router2 = (0, import_express10.Router)(); + const svc = approvalService(db); + const heartbeat = heartbeatService(db); + const issueApprovalsSvc = issueApprovalService(db); + const secretsSvc = secretService(db); + const strictSecretsMode = process.env.TASKCORE_SECRETS_STRICT_MODE === "true"; + async function requireApprovalAccess(req, id) { + const approval = await svc.getById(id); + if (!approval) { + return null; + } + assertCompanyAccess(req, approval.companyId); + return approval; + } + router2.get("/companies/:companyId/approvals", async (req, res) => { + const companyId = req.params.companyId; + assertCompanyAccess(req, companyId); + const status = req.query.status; + const result = await svc.list(companyId, status); + res.json(result.map((approval) => redactApprovalPayload(approval))); + }); + router2.get("/approvals/:id", async (req, res) => { + const id = req.params.id; + const approval = await svc.getById(id); + if (!approval) { + res.status(404).json({ error: "Approval not found" }); + return; + } + assertCompanyAccess(req, approval.companyId); + res.json(redactApprovalPayload(approval)); + }); + router2.post("/companies/:companyId/approvals", validate(createApprovalSchema), async (req, res) => { + const companyId = req.params.companyId; + assertCompanyAccess(req, companyId); + const rawIssueIds = req.body.issueIds; + const issueIds = Array.isArray(rawIssueIds) ? rawIssueIds.filter((value) => typeof value === "string") : []; + const uniqueIssueIds = Array.from(new Set(issueIds)); + const { issueIds: _issueIds, ...approvalInput } = req.body; + const normalizedPayload = approvalInput.type === "hire_agent" ? await secretsSvc.normalizeHireApprovalPayloadForPersistence( + companyId, + approvalInput.payload, + { strictMode: strictSecretsMode } + ) : approvalInput.payload; + const actor = getActorInfo(req); + const approval = await svc.create(companyId, { + ...approvalInput, + payload: normalizedPayload, + requestedByUserId: actor.actorType === "user" ? actor.actorId : null, + requestedByAgentId: approvalInput.requestedByAgentId ?? (actor.actorType === "agent" ? actor.actorId : null), + status: "pending", + decisionNote: null, + decidedByUserId: null, + decidedAt: null, + updatedAt: /* @__PURE__ */ new Date() + }); + if (uniqueIssueIds.length > 0) { + await issueApprovalsSvc.linkManyForApproval(approval.id, uniqueIssueIds, { + agentId: actor.agentId, + userId: actor.actorType === "user" ? actor.actorId : null + }); + } + await logActivity(db, { + companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + action: "approval.created", + entityType: "approval", + entityId: approval.id, + details: { type: approval.type, issueIds: uniqueIssueIds } + }); + res.status(201).json(redactApprovalPayload(approval)); + }); + router2.get("/approvals/:id/issues", async (req, res) => { + const id = req.params.id; + const approval = await svc.getById(id); + if (!approval) { + res.status(404).json({ error: "Approval not found" }); + return; + } + assertCompanyAccess(req, approval.companyId); + const issues2 = await issueApprovalsSvc.listIssuesForApproval(id); + res.json(issues2); + }); + router2.post("/approvals/:id/approve", validate(resolveApprovalSchema), async (req, res) => { + assertBoard(req); + const id = req.params.id; + if (!await requireApprovalAccess(req, id)) { + res.status(404).json({ error: "Approval not found" }); + return; + } + const { approval, applied } = await svc.approve( + id, + req.body.decidedByUserId ?? "board", + req.body.decisionNote + ); + if (applied) { + const linkedIssues = await issueApprovalsSvc.listIssuesForApproval(approval.id); + const linkedIssueIds = linkedIssues.map((issue2) => issue2.id); + const primaryIssueId = linkedIssueIds[0] ?? null; + await logActivity(db, { + companyId: approval.companyId, + actorType: "user", + actorId: req.actor.userId ?? "board", + action: "approval.approved", + entityType: "approval", + entityId: approval.id, + details: { + type: approval.type, + requestedByAgentId: approval.requestedByAgentId, + linkedIssueIds + } + }); + if (approval.requestedByAgentId) { + try { + const wakeRun = await heartbeat.wakeup(approval.requestedByAgentId, { + source: "automation", + triggerDetail: "system", + reason: "approval_approved", + payload: { + approvalId: approval.id, + approvalStatus: approval.status, + issueId: primaryIssueId, + issueIds: linkedIssueIds + }, + requestedByActorType: "user", + requestedByActorId: req.actor.userId ?? "board", + contextSnapshot: { + source: "approval.approved", + approvalId: approval.id, + approvalStatus: approval.status, + issueId: primaryIssueId, + issueIds: linkedIssueIds, + taskId: primaryIssueId, + wakeReason: "approval_approved" + } + }); + await logActivity(db, { + companyId: approval.companyId, + actorType: "user", + actorId: req.actor.userId ?? "board", + action: "approval.requester_wakeup_queued", + entityType: "approval", + entityId: approval.id, + details: { + requesterAgentId: approval.requestedByAgentId, + wakeRunId: wakeRun?.id ?? null, + linkedIssueIds + } + }); + } catch (err) { + logger.warn( + { + err, + approvalId: approval.id, + requestedByAgentId: approval.requestedByAgentId + }, + "failed to queue requester wakeup after approval" + ); + await logActivity(db, { + companyId: approval.companyId, + actorType: "user", + actorId: req.actor.userId ?? "board", + action: "approval.requester_wakeup_failed", + entityType: "approval", + entityId: approval.id, + details: { + requesterAgentId: approval.requestedByAgentId, + linkedIssueIds, + error: err instanceof Error ? err.message : String(err) + } + }); + } + } + } + res.json(redactApprovalPayload(approval)); + }); + router2.post("/approvals/:id/reject", validate(resolveApprovalSchema), async (req, res) => { + assertBoard(req); + const id = req.params.id; + if (!await requireApprovalAccess(req, id)) { + res.status(404).json({ error: "Approval not found" }); + return; + } + const { approval, applied } = await svc.reject( + id, + req.body.decidedByUserId ?? "board", + req.body.decisionNote + ); + if (applied) { + await logActivity(db, { + companyId: approval.companyId, + actorType: "user", + actorId: req.actor.userId ?? "board", + action: "approval.rejected", + entityType: "approval", + entityId: approval.id, + details: { type: approval.type } + }); + } + res.json(redactApprovalPayload(approval)); + }); + router2.post( + "/approvals/:id/request-revision", + validate(requestApprovalRevisionSchema), + async (req, res) => { + assertBoard(req); + const id = req.params.id; + if (!await requireApprovalAccess(req, id)) { + res.status(404).json({ error: "Approval not found" }); + return; + } + const approval = await svc.requestRevision( + id, + req.body.decidedByUserId ?? "board", + req.body.decisionNote + ); + await logActivity(db, { + companyId: approval.companyId, + actorType: "user", + actorId: req.actor.userId ?? "board", + action: "approval.revision_requested", + entityType: "approval", + entityId: approval.id, + details: { type: approval.type } + }); + res.json(redactApprovalPayload(approval)); + } + ); + router2.post("/approvals/:id/resubmit", validate(resubmitApprovalSchema), async (req, res) => { + const id = req.params.id; + const existing = await svc.getById(id); + if (!existing) { + res.status(404).json({ error: "Approval not found" }); + return; + } + assertCompanyAccess(req, existing.companyId); + if (req.actor.type === "agent" && req.actor.agentId !== existing.requestedByAgentId) { + res.status(403).json({ error: "Only requesting agent can resubmit this approval" }); + return; + } + const normalizedPayload = req.body.payload ? existing.type === "hire_agent" ? await secretsSvc.normalizeHireApprovalPayloadForPersistence( + existing.companyId, + req.body.payload, + { strictMode: strictSecretsMode } + ) : req.body.payload : void 0; + const approval = await svc.resubmit(id, normalizedPayload); + const actor = getActorInfo(req); + await logActivity(db, { + companyId: approval.companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + action: "approval.resubmitted", + entityType: "approval", + entityId: approval.id, + details: { type: approval.type } + }); + res.json(redactApprovalPayload(approval)); + }); + router2.get("/approvals/:id/comments", async (req, res) => { + const id = req.params.id; + const approval = await svc.getById(id); + if (!approval) { + res.status(404).json({ error: "Approval not found" }); + return; + } + assertCompanyAccess(req, approval.companyId); + const comments = await svc.listComments(id); + res.json(comments); + }); + router2.post("/approvals/:id/comments", validate(addApprovalCommentSchema), async (req, res) => { + const id = req.params.id; + const approval = await svc.getById(id); + if (!approval) { + res.status(404).json({ error: "Approval not found" }); + return; + } + assertCompanyAccess(req, approval.companyId); + const actor = getActorInfo(req); + const comment = await svc.addComment(id, req.body.body, { + agentId: actor.agentId ?? void 0, + userId: actor.actorType === "user" ? actor.actorId : void 0 + }); + await logActivity(db, { + companyId: approval.companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + action: "approval.comment_added", + entityType: "approval", + entityId: approval.id, + details: { commentId: comment.id } + }); + res.status(201).json(comment); + }); + return router2; +} + +// server/src/routes/secrets.ts +var import_express11 = __toESM(require_express2(), 1); +function secretRoutes(db) { + const router2 = (0, import_express11.Router)(); + const svc = secretService(db); + const configuredDefaultProvider = process.env.TASKCORE_SECRETS_PROVIDER; + const defaultProvider = configuredDefaultProvider && SECRET_PROVIDERS.includes(configuredDefaultProvider) ? configuredDefaultProvider : "local_encrypted"; + router2.get("/companies/:companyId/secret-providers", (req, res) => { + assertBoard(req); + const companyId = req.params.companyId; + assertCompanyAccess(req, companyId); + res.json(svc.listProviders()); + }); + router2.get("/companies/:companyId/secrets", async (req, res) => { + assertBoard(req); + const companyId = req.params.companyId; + assertCompanyAccess(req, companyId); + const secrets = await svc.list(companyId); + res.json(secrets); + }); + router2.post("/companies/:companyId/secrets", validate(createSecretSchema), async (req, res) => { + assertBoard(req); + const companyId = req.params.companyId; + assertCompanyAccess(req, companyId); + const created = await svc.create( + companyId, + { + name: req.body.name, + provider: req.body.provider ?? defaultProvider, + value: req.body.value, + description: req.body.description, + externalRef: req.body.externalRef + }, + { userId: req.actor.userId ?? "board", agentId: null } + ); + await logActivity(db, { + companyId, + actorType: "user", + actorId: req.actor.userId ?? "board", + action: "secret.created", + entityType: "secret", + entityId: created.id, + details: { name: created.name, provider: created.provider } + }); + res.status(201).json(created); + }); + router2.post("/secrets/:id/rotate", validate(rotateSecretSchema), async (req, res) => { + assertBoard(req); + const id = req.params.id; + const existing = await svc.getById(id); + if (!existing) { + res.status(404).json({ error: "Secret not found" }); + return; + } + assertCompanyAccess(req, existing.companyId); + const rotated = await svc.rotate( + id, + { + value: req.body.value, + externalRef: req.body.externalRef + }, + { userId: req.actor.userId ?? "board", agentId: null } + ); + await logActivity(db, { + companyId: rotated.companyId, + actorType: "user", + actorId: req.actor.userId ?? "board", + action: "secret.rotated", + entityType: "secret", + entityId: rotated.id, + details: { version: rotated.latestVersion } + }); + res.json(rotated); + }); + router2.patch("/secrets/:id", validate(updateSecretSchema), async (req, res) => { + assertBoard(req); + const id = req.params.id; + const existing = await svc.getById(id); + if (!existing) { + res.status(404).json({ error: "Secret not found" }); + return; + } + assertCompanyAccess(req, existing.companyId); + const updated = await svc.update(id, { + name: req.body.name, + description: req.body.description, + externalRef: req.body.externalRef + }); + if (!updated) { + res.status(404).json({ error: "Secret not found" }); + return; + } + await logActivity(db, { + companyId: updated.companyId, + actorType: "user", + actorId: req.actor.userId ?? "board", + action: "secret.updated", + entityType: "secret", + entityId: updated.id, + details: { name: updated.name } + }); + res.json(updated); + }); + router2.delete("/secrets/:id", async (req, res) => { + assertBoard(req); + const id = req.params.id; + const existing = await svc.getById(id); + if (!existing) { + res.status(404).json({ error: "Secret not found" }); + return; + } + assertCompanyAccess(req, existing.companyId); + const removed = await svc.remove(id); + if (!removed) { + res.status(404).json({ error: "Secret not found" }); + return; + } + await logActivity(db, { + companyId: removed.companyId, + actorType: "user", + actorId: req.actor.userId ?? "board", + action: "secret.deleted", + entityType: "secret", + entityId: removed.id, + details: { name: removed.name } + }); + res.json({ ok: true }); + }); + return router2; +} + +// server/src/routes/costs.ts +var import_express12 = __toESM(require_express2(), 1); + +// server/src/services/quota-windows.ts +var QUOTA_PROVIDER_TIMEOUT_MS = 2e4; +function providerSlugForAdapterType(type) { + switch (type) { + case "claude_local": + return "anthropic"; + case "codex_local": + return "openai"; + default: + return type; + } +} +async function fetchAllQuotaWindows() { + const adapters = listServerAdapters().filter((a5) => a5.getQuotaWindows != null); + const settled = await Promise.allSettled( + adapters.map((adapter) => withQuotaTimeout(adapter.type, adapter.getQuotaWindows())) + ); + return settled.map((result, i5) => { + if (result.status === "fulfilled") return result.value; + const adapterType = adapters[i5].type; + return { + provider: providerSlugForAdapterType(adapterType), + ok: false, + error: String(result.reason), + windows: [] + }; + }); +} +async function withQuotaTimeout(adapterType, task) { + let timeoutId = null; + try { + return await Promise.race([ + task, + new Promise((resolve4) => { + timeoutId = setTimeout(() => { + resolve4({ + provider: providerSlugForAdapterType(adapterType), + ok: false, + error: `quota polling timed out after ${Math.round(QUOTA_PROVIDER_TIMEOUT_MS / 1e3)}s`, + windows: [] + }); + }, QUOTA_PROVIDER_TIMEOUT_MS); + }) + ]); + } finally { + if (timeoutId) clearTimeout(timeoutId); + } +} + +// server/src/routes/costs.ts +function parseCostDateRange(query) { + const fromRaw = query.from; + const toRaw = query.to; + const from = fromRaw ? new Date(fromRaw) : void 0; + const to = toRaw ? new Date(toRaw) : void 0; + if (from && isNaN(from.getTime())) throw badRequest("invalid 'from' date"); + if (to && isNaN(to.getTime())) throw badRequest("invalid 'to' date"); + return from || to ? { from, to } : void 0; +} +function parseCostLimit(query) { + const raw = Array.isArray(query.limit) ? query.limit[0] : query.limit; + if (raw == null || raw === "") return 100; + const limit = typeof raw === "number" ? raw : Number.parseInt(String(raw), 10); + if (!Number.isFinite(limit) || limit <= 0 || limit > 500) { + throw badRequest("invalid 'limit' value"); + } + return limit; +} +function costRoutes(db) { + const router2 = (0, import_express12.Router)(); + const heartbeat = heartbeatService(db); + const budgetHooks = { + cancelWorkForScope: heartbeat.cancelBudgetScopeWork + }; + const costs = costService(db, budgetHooks); + const finance = financeService(db); + const budgets = budgetService(db, budgetHooks); + const companies2 = companyService(db); + const agents2 = agentService(db); + router2.post("/companies/:companyId/cost-events", validate(createCostEventSchema), async (req, res) => { + const companyId = req.params.companyId; + assertCompanyAccess(req, companyId); + if (req.actor.type === "agent" && req.actor.agentId !== req.body.agentId) { + res.status(403).json({ error: "Agent can only report its own costs" }); + return; + } + const event = await costs.createEvent(companyId, { + ...req.body, + occurredAt: new Date(req.body.occurredAt) + }); + const actor = getActorInfo(req); + await logActivity(db, { + companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + action: "cost.reported", + entityType: "cost_event", + entityId: event.id, + details: { costCents: event.costCents, model: event.model } + }); + res.status(201).json(event); + }); + router2.post("/companies/:companyId/finance-events", validate(createFinanceEventSchema), async (req, res) => { + const companyId = req.params.companyId; + assertCompanyAccess(req, companyId); + assertBoard(req); + const event = await finance.createEvent(companyId, { + ...req.body, + occurredAt: new Date(req.body.occurredAt) + }); + const actor = getActorInfo(req); + await logActivity(db, { + companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + action: "finance_event.reported", + entityType: "finance_event", + entityId: event.id, + details: { + amountCents: event.amountCents, + biller: event.biller, + eventKind: event.eventKind, + direction: event.direction + } + }); + res.status(201).json(event); + }); + router2.get("/companies/:companyId/costs/summary", async (req, res) => { + const companyId = req.params.companyId; + assertCompanyAccess(req, companyId); + const range2 = parseCostDateRange(req.query); + const summary = await costs.summary(companyId, range2); + res.json(summary); + }); + router2.get("/companies/:companyId/costs/by-agent", async (req, res) => { + const companyId = req.params.companyId; + assertCompanyAccess(req, companyId); + const range2 = parseCostDateRange(req.query); + const rows = await costs.byAgent(companyId, range2); + res.json(rows); + }); + router2.get("/companies/:companyId/costs/by-agent-model", async (req, res) => { + const companyId = req.params.companyId; + assertCompanyAccess(req, companyId); + const range2 = parseCostDateRange(req.query); + const rows = await costs.byAgentModel(companyId, range2); + res.json(rows); + }); + router2.get("/companies/:companyId/costs/by-provider", async (req, res) => { + const companyId = req.params.companyId; + assertCompanyAccess(req, companyId); + const range2 = parseCostDateRange(req.query); + const rows = await costs.byProvider(companyId, range2); + res.json(rows); + }); + router2.get("/companies/:companyId/costs/by-biller", async (req, res) => { + const companyId = req.params.companyId; + assertCompanyAccess(req, companyId); + const range2 = parseCostDateRange(req.query); + const rows = await costs.byBiller(companyId, range2); + res.json(rows); + }); + router2.get("/companies/:companyId/costs/finance-summary", async (req, res) => { + const companyId = req.params.companyId; + assertCompanyAccess(req, companyId); + const range2 = parseCostDateRange(req.query); + const summary = await finance.summary(companyId, range2); + res.json(summary); + }); + router2.get("/companies/:companyId/costs/finance-by-biller", async (req, res) => { + const companyId = req.params.companyId; + assertCompanyAccess(req, companyId); + const range2 = parseCostDateRange(req.query); + const rows = await finance.byBiller(companyId, range2); + res.json(rows); + }); + router2.get("/companies/:companyId/costs/finance-by-kind", async (req, res) => { + const companyId = req.params.companyId; + assertCompanyAccess(req, companyId); + const range2 = parseCostDateRange(req.query); + const rows = await finance.byKind(companyId, range2); + res.json(rows); + }); + router2.get("/companies/:companyId/costs/finance-events", async (req, res) => { + const companyId = req.params.companyId; + assertCompanyAccess(req, companyId); + const range2 = parseCostDateRange(req.query); + const limit = parseCostLimit(req.query); + const rows = await finance.list(companyId, range2, limit); + res.json(rows); + }); + router2.get("/companies/:companyId/costs/window-spend", async (req, res) => { + const companyId = req.params.companyId; + assertCompanyAccess(req, companyId); + const rows = await costs.windowSpend(companyId); + res.json(rows); + }); + router2.get("/companies/:companyId/costs/quota-windows", async (req, res) => { + const companyId = req.params.companyId; + assertCompanyAccess(req, companyId); + assertBoard(req); + const company = await companies2.getById(companyId); + if (!company) { + res.status(404).json({ error: "Company not found" }); + return; + } + const results = await fetchAllQuotaWindows(); + res.json(results); + }); + router2.get("/companies/:companyId/budgets/overview", async (req, res) => { + const companyId = req.params.companyId; + assertCompanyAccess(req, companyId); + const overview = await budgets.overview(companyId); + res.json(overview); + }); + router2.post( + "/companies/:companyId/budgets/policies", + validate(upsertBudgetPolicySchema), + async (req, res) => { + assertBoard(req); + const companyId = req.params.companyId; + assertCompanyAccess(req, companyId); + const summary = await budgets.upsertPolicy(companyId, req.body, req.actor.userId ?? "board"); + res.json(summary); + } + ); + router2.post( + "/companies/:companyId/budget-incidents/:incidentId/resolve", + validate(resolveBudgetIncidentSchema), + async (req, res) => { + assertBoard(req); + const companyId = req.params.companyId; + const incidentId = req.params.incidentId; + assertCompanyAccess(req, companyId); + const incident = await budgets.resolveIncident(companyId, incidentId, req.body, req.actor.userId ?? "board"); + res.json(incident); + } + ); + router2.get("/companies/:companyId/costs/by-project", async (req, res) => { + const companyId = req.params.companyId; + assertCompanyAccess(req, companyId); + const range2 = parseCostDateRange(req.query); + const rows = await costs.byProject(companyId, range2); + res.json(rows); + }); + router2.patch("/companies/:companyId/budgets", validate(updateBudgetSchema), async (req, res) => { + assertBoard(req); + const companyId = req.params.companyId; + assertCompanyAccess(req, companyId); + const company = await companies2.update(companyId, { budgetMonthlyCents: req.body.budgetMonthlyCents }); + if (!company) { + res.status(404).json({ error: "Company not found" }); + return; + } + await logActivity(db, { + companyId, + actorType: "user", + actorId: req.actor.userId ?? "board", + action: "company.budget_updated", + entityType: "company", + entityId: companyId, + details: { budgetMonthlyCents: req.body.budgetMonthlyCents } + }); + await budgets.upsertPolicy( + companyId, + { + scopeType: "company", + scopeId: companyId, + amount: req.body.budgetMonthlyCents, + windowKind: "calendar_month_utc" + }, + req.actor.userId ?? "board" + ); + res.json(company); + }); + router2.patch("/agents/:agentId/budgets", validate(updateBudgetSchema), async (req, res) => { + const agentId = req.params.agentId; + const agent = await agents2.getById(agentId); + if (!agent) { + res.status(404).json({ error: "Agent not found" }); + return; + } + assertCompanyAccess(req, agent.companyId); + if (req.actor.type === "agent") { + if (req.actor.agentId !== agentId) { + res.status(403).json({ error: "Agent can only change its own budget" }); + return; + } + } + const updated = await agents2.update(agentId, { budgetMonthlyCents: req.body.budgetMonthlyCents }); + if (!updated) { + res.status(404).json({ error: "Agent not found" }); + return; + } + const actor = getActorInfo(req); + await logActivity(db, { + companyId: updated.companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + action: "agent.budget_updated", + entityType: "agent", + entityId: updated.id, + details: { budgetMonthlyCents: updated.budgetMonthlyCents } + }); + await budgets.upsertPolicy( + updated.companyId, + { + scopeType: "agent", + scopeId: updated.id, + amount: updated.budgetMonthlyCents, + windowKind: "calendar_month_utc" + }, + req.actor.type === "board" ? req.actor.userId ?? "board" : null + ); + res.json(updated); + }); + return router2; +} + +// server/src/routes/activity.ts +var import_express13 = __toESM(require_express2(), 1); +var createActivitySchema = external_exports.object({ + actorType: external_exports.enum(["agent", "user", "system"]).optional().default("system"), + actorId: external_exports.string().min(1), + action: external_exports.string().min(1), + entityType: external_exports.string().min(1), + entityId: external_exports.string().min(1), + agentId: external_exports.string().uuid().optional().nullable(), + details: external_exports.record(external_exports.unknown()).optional().nullable() +}); +function activityRoutes(db) { + const router2 = (0, import_express13.Router)(); + const svc = activityService(db); + const heartbeat = heartbeatService(db); + const issueSvc = issueService(db); + async function resolveIssueByRef(rawId) { + if (/^[A-Z]+-\d+$/i.test(rawId)) { + return issueSvc.getByIdentifier(rawId); + } + return issueSvc.getById(rawId); + } + router2.get("/companies/:companyId/activity", async (req, res) => { + const companyId = req.params.companyId; + assertCompanyAccess(req, companyId); + const filters = { + companyId, + agentId: req.query.agentId, + entityType: req.query.entityType, + entityId: req.query.entityId + }; + const result = await svc.list(filters); + res.json(result); + }); + router2.post("/companies/:companyId/activity", validate(createActivitySchema), async (req, res) => { + assertBoard(req); + const companyId = req.params.companyId; + assertCompanyAccess(req, companyId); + const event = await svc.create({ + companyId, + ...req.body, + details: req.body.details ? sanitizeRecord(req.body.details) : null + }); + res.status(201).json(event); + }); + router2.get("/issues/:id/activity", async (req, res) => { + const rawId = req.params.id; + const issue2 = await resolveIssueByRef(rawId); + if (!issue2) { + res.status(404).json({ error: "Issue not found" }); + return; + } + assertCompanyAccess(req, issue2.companyId); + const result = await svc.forIssue(issue2.id); + res.json(result); + }); + router2.get("/issues/:id/runs", async (req, res) => { + const rawId = req.params.id; + const issue2 = await resolveIssueByRef(rawId); + if (!issue2) { + res.status(404).json({ error: "Issue not found" }); + return; + } + assertCompanyAccess(req, issue2.companyId); + const result = await svc.runsForIssue(issue2.companyId, issue2.id); + res.json(result); + }); + router2.get("/heartbeat-runs/:runId/issues", async (req, res) => { + const runId = req.params.runId; + const run = await heartbeat.getRun(runId); + if (!run) { + res.json([]); + return; + } + assertCompanyAccess(req, run.companyId); + const result = await svc.issuesForRun(runId); + res.json(result); + }); + return router2; +} + +// server/src/routes/dashboard.ts +var import_express14 = __toESM(require_express2(), 1); +function dashboardRoutes(db) { + const router2 = (0, import_express14.Router)(); + const svc = dashboardService(db); + router2.get("/companies/:companyId/dashboard", async (req, res) => { + const companyId = req.params.companyId; + assertCompanyAccess(req, companyId); + const summary = await svc.summary(companyId); + res.json(summary); + }); + return router2; +} + +// server/src/routes/sidebar-badges.ts +var import_express15 = __toESM(require_express2(), 1); +init_drizzle_orm(); +init_src2(); +function buildDismissedAtByKey(dismissals) { + return new Map( + dismissals.map((dismissal) => [dismissal.itemKey, new Date(dismissal.dismissedAt).getTime()]) + ); +} +function sidebarBadgeRoutes(db) { + const router2 = (0, import_express15.Router)(); + const svc = sidebarBadgeService(db); + const access = accessService(db); + const dashboard = dashboardService(db); + router2.get("/companies/:companyId/sidebar-badges", async (req, res) => { + const companyId = req.params.companyId; + assertCompanyAccess(req, companyId); + let canApproveJoins = false; + if (req.actor.type === "board") { + canApproveJoins = req.actor.source === "local_implicit" || Boolean(req.actor.isInstanceAdmin) || await access.canUser(companyId, req.actor.userId, "joins:approve"); + } else if (req.actor.type === "agent" && req.actor.agentId) { + canApproveJoins = await access.hasPermission(companyId, "agent", req.actor.agentId, "joins:approve"); + } + const visibleJoinRequests = canApproveJoins ? await db.select({ + id: joinRequests.id, + updatedAt: joinRequests.updatedAt, + createdAt: joinRequests.createdAt + }).from(joinRequests).where(and(eq(joinRequests.companyId, companyId), eq(joinRequests.status, "pending_approval"))) : []; + const dismissedAtByKey = req.actor.type === "board" && req.actor.userId ? await db.select({ itemKey: inboxDismissals.itemKey, dismissedAt: inboxDismissals.dismissedAt }).from(inboxDismissals).where(and(eq(inboxDismissals.companyId, companyId), eq(inboxDismissals.userId, req.actor.userId))).then(buildDismissedAtByKey) : /* @__PURE__ */ new Map(); + const badges = await svc.get(companyId, { + dismissals: dismissedAtByKey, + joinRequests: visibleJoinRequests + }); + const summary = await dashboard.summary(companyId); + const hasFailedRuns = badges.failedRuns > 0; + const alertsCount = (summary.agents.error > 0 && !hasFailedRuns ? 1 : 0) + (summary.costs.monthBudgetCents > 0 && summary.costs.monthUtilizationPercent >= 80 ? 1 : 0); + badges.inbox = badges.failedRuns + alertsCount + badges.joinRequests + badges.approvals; + res.json(badges); + }); + return router2; +} + +// server/src/routes/sidebar-preferences.ts +var import_express16 = __toESM(require_express2(), 1); +function requireBoardUserId(req, res) { + assertBoard(req); + if (!req.actor.userId) { + res.status(403).json({ error: "Board user context required" }); + return null; + } + return req.actor.userId; +} +function sidebarPreferenceRoutes(db) { + const router2 = (0, import_express16.Router)(); + const svc = sidebarPreferenceService(db); + router2.get("/sidebar-preferences/me", async (req, res) => { + const userId = requireBoardUserId(req, res); + if (!userId) return; + res.json(await svc.getCompanyOrder(userId)); + }); + router2.put("/sidebar-preferences/me", validate(upsertSidebarOrderPreferenceSchema), async (req, res) => { + const userId = requireBoardUserId(req, res); + if (!userId) return; + res.json(await svc.upsertCompanyOrder(userId, req.body.orderedIds)); + }); + router2.get("/companies/:companyId/sidebar-preferences/me", async (req, res) => { + const companyId = req.params.companyId; + assertCompanyAccess(req, companyId); + const userId = requireBoardUserId(req, res); + if (!userId) return; + res.json(await svc.getProjectOrder(companyId, userId)); + }); + router2.put( + "/companies/:companyId/sidebar-preferences/me", + validate(upsertSidebarOrderPreferenceSchema), + async (req, res) => { + const companyId = req.params.companyId; + assertCompanyAccess(req, companyId); + const userId = requireBoardUserId(req, res); + if (!userId) return; + const result = await svc.upsertProjectOrder(companyId, userId, req.body.orderedIds); + const actor = getActorInfo(req); + await logActivity(db, { + companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + runId: actor.runId, + action: "sidebar_preferences.project_order_updated", + entityType: "company", + entityId: companyId, + details: { + userId, + orderedIds: result.orderedIds + } + }); + res.json(result); + } + ); + return router2; +} + +// server/src/routes/inbox-dismissals.ts +var import_express17 = __toESM(require_express2(), 1); +var inboxDismissalSchema = external_exports.object({ + itemKey: external_exports.string().trim().min(1).regex(/^(approval|join|run):.+$/, "Unsupported inbox item key") +}); +function inboxDismissalRoutes(db) { + const router2 = (0, import_express17.Router)(); + const svc = inboxDismissalService(db); + router2.get("/companies/:companyId/inbox-dismissals", async (req, res) => { + const companyId = req.params.companyId; + assertCompanyAccess(req, companyId); + if (req.actor.type !== "board") { + res.status(403).json({ error: "Board authentication required" }); + return; + } + if (!req.actor.userId) { + res.status(403).json({ error: "Board user context required" }); + return; + } + const dismissals = await svc.list(companyId, req.actor.userId); + res.json(dismissals); + }); + router2.post( + "/companies/:companyId/inbox-dismissals", + validate(inboxDismissalSchema), + async (req, res) => { + const companyId = req.params.companyId; + assertCompanyAccess(req, companyId); + if (req.actor.type !== "board") { + res.status(403).json({ error: "Board authentication required" }); + return; + } + if (!req.actor.userId) { + res.status(403).json({ error: "Board user context required" }); + return; + } + const dismissal = await svc.dismiss(companyId, req.actor.userId, req.body.itemKey, /* @__PURE__ */ new Date()); + const actor = getActorInfo(req); + await logActivity(db, { + companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + runId: actor.runId, + action: "inbox.dismissed", + entityType: "company", + entityId: companyId, + details: { + userId: req.actor.userId, + itemKey: dismissal.itemKey, + dismissedAt: dismissal.dismissedAt + } + }); + res.status(201).json(dismissal); + } + ); + return router2; +} + +// server/src/routes/instance-settings.ts +var import_express18 = __toESM(require_express2(), 1); +function assertCanManageInstanceSettings(req) { + if (req.actor.type !== "board") { + throw forbidden("Board access required"); + } + if (req.actor.source === "local_implicit" || req.actor.isInstanceAdmin) { + return; + } + throw forbidden("Instance admin access required"); +} +function instanceSettingsRoutes(db) { + const router2 = (0, import_express18.Router)(); + const svc = instanceSettingsService(db); + router2.get("/instance/settings/general", async (req, res) => { + if (req.actor.type !== "board") { + throw forbidden("Board access required"); + } + res.json(await svc.getGeneral()); + }); + router2.patch( + "/instance/settings/general", + validate(patchInstanceGeneralSettingsSchema), + async (req, res) => { + assertCanManageInstanceSettings(req); + const updated = await svc.updateGeneral(req.body); + const actor = getActorInfo(req); + const companyIds = await svc.listCompanyIds(); + await Promise.all( + companyIds.map( + (companyId) => logActivity(db, { + companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + runId: actor.runId, + action: "instance.settings.general_updated", + entityType: "instance_settings", + entityId: updated.id, + details: { + general: updated.general, + changedKeys: Object.keys(req.body).sort() + } + }) + ) + ); + res.json(updated.general); + } + ); + router2.get("/instance/settings/experimental", async (req, res) => { + if (req.actor.type !== "board") { + throw forbidden("Board access required"); + } + res.json(await svc.getExperimental()); + }); + router2.patch( + "/instance/settings/experimental", + validate(patchInstanceExperimentalSettingsSchema), + async (req, res) => { + assertCanManageInstanceSettings(req); + const updated = await svc.updateExperimental(req.body); + const actor = getActorInfo(req); + const companyIds = await svc.listCompanyIds(); + await Promise.all( + companyIds.map( + (companyId) => logActivity(db, { + companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + runId: actor.runId, + action: "instance.settings.experimental_updated", + entityType: "instance_settings", + entityId: updated.id, + details: { + experimental: updated.experimental, + changedKeys: Object.keys(req.body).sort() + } + }) + ) + ); + res.json(updated.experimental); + } + ); + return router2; +} + +// server/src/routes/llms.ts +var import_express19 = __toESM(require_express2(), 1); +function hasCreatePermission(agent) { + if (!agent.permissions || typeof agent.permissions !== "object") return false; + return Boolean(agent.permissions.canCreateAgents); +} +function llmRoutes(db) { + const router2 = (0, import_express19.Router)(); + const agentsSvc = agentService(db); + async function assertCanRead(req) { + if (req.actor.type === "board") return; + if (req.actor.type !== "agent" || !req.actor.agentId) { + throw forbidden("Board or permitted agent authentication required"); + } + const actorAgent = await agentsSvc.getById(req.actor.agentId); + if (!actorAgent || !hasCreatePermission(actorAgent)) { + throw forbidden("Missing permission to read agent configuration reflection"); + } + } + router2.get("/llms/agent-configuration.txt", async (req, res) => { + await assertCanRead(req); + const adapters = listServerAdapters().sort((a5, b6) => a5.type.localeCompare(b6.type)); + const lines = [ + "# Taskcore Agent Configuration Index", + "", + "Installed adapters:", + ...adapters.map((adapter) => `- ${adapter.type}: /llms/agent-configuration/${adapter.type}.txt`), + "", + "Related API endpoints:", + "- GET /api/companies/:companyId/agent-configurations", + "- GET /api/agents/:id/configuration", + "- POST /api/companies/:companyId/agent-hires", + "", + "Agent identity references:", + "- GET /llms/agent-icons.txt", + "", + "Notes:", + "- Sensitive values are redacted in configuration read APIs.", + "- New hires may be created in pending_approval state depending on company settings.", + "- Timer heartbeats are opt-in for new hires. Leave runtimeConfig.heartbeat.enabled false unless the role truly needs scheduled work or the user explicitly asked for it.", + "" + ]; + res.type("text/plain").send(lines.join("\n")); + }); + router2.get("/llms/agent-icons.txt", async (req, res) => { + await assertCanRead(req); + const lines = [ + "# Taskcore Agent Icon Names", + "", + "Set the `icon` field on hire/create payloads to one of:", + ...AGENT_ICON_NAMES.map((name) => `- ${name}`), + "", + "Example:", + '{ "name": "SearchOps", "role": "researcher", "icon": "search" }', + "" + ]; + res.type("text/plain").send(lines.join("\n")); + }); + router2.get("/llms/agent-configuration/:adapterType.txt", async (req, res) => { + await assertCanRead(req); + const adapterType = req.params.adapterType; + const adapter = listServerAdapters().find((entry) => entry.type === adapterType); + if (!adapter) { + res.status(404).type("text/plain").send(`Unknown adapter type: ${adapterType}`); + return; + } + res.type("text/plain").send( + adapter.agentConfigurationDoc ?? `# ${adapterType} agent configuration + +No adapter-specific documentation registered.` + ); + }); + return router2; +} + +// server/src/routes/assets.ts +var import_express20 = __toESM(require_express2(), 1); +var import_multer2 = __toESM(require_multer(), 1); + +// node_modules/.pnpm/dompurify@3.4.0/node_modules/dompurify/dist/purify.es.mjs +var { + entries, + setPrototypeOf, + isFrozen, + getPrototypeOf, + getOwnPropertyDescriptor +} = Object; +var { + freeze, + seal, + create +} = Object; +var { + apply, + construct: construct2 +} = typeof Reflect !== "undefined" && Reflect; +if (!freeze) { + freeze = function freeze3(x5) { + return x5; + }; +} +if (!seal) { + seal = function seal2(x5) { + return x5; + }; +} +if (!apply) { + apply = function apply2(func, thisArg) { + for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { + args[_key - 2] = arguments[_key]; + } + return func.apply(thisArg, args); + }; +} +if (!construct2) { + construct2 = function construct3(Func) { + for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { + args[_key2 - 1] = arguments[_key2]; + } + return new Func(...args); + }; +} +var arrayForEach = unapply(Array.prototype.forEach); +var arrayLastIndexOf = unapply(Array.prototype.lastIndexOf); +var arrayPop = unapply(Array.prototype.pop); +var arrayPush = unapply(Array.prototype.push); +var arraySplice = unapply(Array.prototype.splice); +var stringToLowerCase = unapply(String.prototype.toLowerCase); +var stringToString = unapply(String.prototype.toString); +var stringMatch = unapply(String.prototype.match); +var stringReplace = unapply(String.prototype.replace); +var stringIndexOf = unapply(String.prototype.indexOf); +var stringTrim = unapply(String.prototype.trim); +var objectHasOwnProperty = unapply(Object.prototype.hasOwnProperty); +var regExpTest = unapply(RegExp.prototype.test); +var typeErrorCreate = unconstruct(TypeError); +function unapply(func) { + return function(thisArg) { + if (thisArg instanceof RegExp) { + thisArg.lastIndex = 0; + } + for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) { + args[_key3 - 1] = arguments[_key3]; + } + return apply(func, thisArg, args); + }; +} +function unconstruct(Func) { + return function() { + for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { + args[_key4] = arguments[_key4]; + } + return construct2(Func, args); + }; +} +function addToSet(set2, array2) { + let transformCaseFunc = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : stringToLowerCase; + if (setPrototypeOf) { + setPrototypeOf(set2, null); + } + let l5 = array2.length; + while (l5--) { + let element = array2[l5]; + if (typeof element === "string") { + const lcElement = transformCaseFunc(element); + if (lcElement !== element) { + if (!isFrozen(array2)) { + array2[l5] = lcElement; + } + element = lcElement; + } + } + set2[element] = true; + } + return set2; +} +function cleanArray(array2) { + for (let index2 = 0; index2 < array2.length; index2++) { + const isPropertyExist = objectHasOwnProperty(array2, index2); + if (!isPropertyExist) { + array2[index2] = null; + } + } + return array2; +} +function clone(object2) { + const newObject = create(null); + for (const [property, value] of entries(object2)) { + const isPropertyExist = objectHasOwnProperty(object2, property); + if (isPropertyExist) { + if (Array.isArray(value)) { + newObject[property] = cleanArray(value); + } else if (value && typeof value === "object" && value.constructor === Object) { + newObject[property] = clone(value); + } else { + newObject[property] = value; + } + } + } + return newObject; +} +function lookupGetter(object2, prop) { + while (object2 !== null) { + const desc3 = getOwnPropertyDescriptor(object2, prop); + if (desc3) { + if (desc3.get) { + return unapply(desc3.get); + } + if (typeof desc3.value === "function") { + return unapply(desc3.value); + } + } + object2 = getPrototypeOf(object2); + } + function fallbackValue() { + return null; + } + return fallbackValue; +} +var html$1 = freeze(["a", "abbr", "acronym", "address", "area", "article", "aside", "audio", "b", "bdi", "bdo", "big", "blink", "blockquote", "body", "br", "button", "canvas", "caption", "center", "cite", "code", "col", "colgroup", "content", "data", "datalist", "dd", "decorator", "del", "details", "dfn", "dialog", "dir", "div", "dl", "dt", "element", "em", "fieldset", "figcaption", "figure", "font", "footer", "form", "h1", "h2", "h3", "h4", "h5", "h6", "head", "header", "hgroup", "hr", "html", "i", "img", "input", "ins", "kbd", "label", "legend", "li", "main", "map", "mark", "marquee", "menu", "menuitem", "meter", "nav", "nobr", "ol", "optgroup", "option", "output", "p", "picture", "pre", "progress", "q", "rp", "rt", "ruby", "s", "samp", "search", "section", "select", "shadow", "slot", "small", "source", "spacer", "span", "strike", "strong", "style", "sub", "summary", "sup", "table", "tbody", "td", "template", "textarea", "tfoot", "th", "thead", "time", "tr", "track", "tt", "u", "ul", "var", "video", "wbr"]); +var svg$1 = freeze(["svg", "a", "altglyph", "altglyphdef", "altglyphitem", "animatecolor", "animatemotion", "animatetransform", "circle", "clippath", "defs", "desc", "ellipse", "enterkeyhint", "exportparts", "filter", "font", "g", "glyph", "glyphref", "hkern", "image", "inputmode", "line", "lineargradient", "marker", "mask", "metadata", "mpath", "part", "path", "pattern", "polygon", "polyline", "radialgradient", "rect", "stop", "style", "switch", "symbol", "text", "textpath", "title", "tref", "tspan", "view", "vkern"]); +var svgFilters = freeze(["feBlend", "feColorMatrix", "feComponentTransfer", "feComposite", "feConvolveMatrix", "feDiffuseLighting", "feDisplacementMap", "feDistantLight", "feDropShadow", "feFlood", "feFuncA", "feFuncB", "feFuncG", "feFuncR", "feGaussianBlur", "feImage", "feMerge", "feMergeNode", "feMorphology", "feOffset", "fePointLight", "feSpecularLighting", "feSpotLight", "feTile", "feTurbulence"]); +var svgDisallowed = freeze(["animate", "color-profile", "cursor", "discard", "font-face", "font-face-format", "font-face-name", "font-face-src", "font-face-uri", "foreignobject", "hatch", "hatchpath", "mesh", "meshgradient", "meshpatch", "meshrow", "missing-glyph", "script", "set", "solidcolor", "unknown", "use"]); +var mathMl$1 = freeze(["math", "menclose", "merror", "mfenced", "mfrac", "mglyph", "mi", "mlabeledtr", "mmultiscripts", "mn", "mo", "mover", "mpadded", "mphantom", "mroot", "mrow", "ms", "mspace", "msqrt", "mstyle", "msub", "msup", "msubsup", "mtable", "mtd", "mtext", "mtr", "munder", "munderover", "mprescripts"]); +var mathMlDisallowed = freeze(["maction", "maligngroup", "malignmark", "mlongdiv", "mscarries", "mscarry", "msgroup", "mstack", "msline", "msrow", "semantics", "annotation", "annotation-xml", "mprescripts", "none"]); +var text2 = freeze(["#text"]); +var html = freeze(["accept", "action", "align", "alt", "autocapitalize", "autocomplete", "autopictureinpicture", "autoplay", "background", "bgcolor", "border", "capture", "cellpadding", "cellspacing", "checked", "cite", "class", "clear", "color", "cols", "colspan", "controls", "controlslist", "coords", "crossorigin", "datetime", "decoding", "default", "dir", "disabled", "disablepictureinpicture", "disableremoteplayback", "download", "draggable", "enctype", "enterkeyhint", "exportparts", "face", "for", "headers", "height", "hidden", "high", "href", "hreflang", "id", "inert", "inputmode", "integrity", "ismap", "kind", "label", "lang", "list", "loading", "loop", "low", "max", "maxlength", "media", "method", "min", "minlength", "multiple", "muted", "name", "nonce", "noshade", "novalidate", "nowrap", "open", "optimum", "part", "pattern", "placeholder", "playsinline", "popover", "popovertarget", "popovertargetaction", "poster", "preload", "pubdate", "radiogroup", "readonly", "rel", "required", "rev", "reversed", "role", "rows", "rowspan", "spellcheck", "scope", "selected", "shape", "size", "sizes", "slot", "span", "srclang", "start", "src", "srcset", "step", "style", "summary", "tabindex", "title", "translate", "type", "usemap", "valign", "value", "width", "wrap", "xmlns", "slot"]); +var svg = freeze(["accent-height", "accumulate", "additive", "alignment-baseline", "amplitude", "ascent", "attributename", "attributetype", "azimuth", "basefrequency", "baseline-shift", "begin", "bias", "by", "class", "clip", "clippathunits", "clip-path", "clip-rule", "color", "color-interpolation", "color-interpolation-filters", "color-profile", "color-rendering", "cx", "cy", "d", "dx", "dy", "diffuseconstant", "direction", "display", "divisor", "dur", "edgemode", "elevation", "end", "exponent", "fill", "fill-opacity", "fill-rule", "filter", "filterunits", "flood-color", "flood-opacity", "font-family", "font-size", "font-size-adjust", "font-stretch", "font-style", "font-variant", "font-weight", "fx", "fy", "g1", "g2", "glyph-name", "glyphref", "gradientunits", "gradienttransform", "height", "href", "id", "image-rendering", "in", "in2", "intercept", "k", "k1", "k2", "k3", "k4", "kerning", "keypoints", "keysplines", "keytimes", "lang", "lengthadjust", "letter-spacing", "kernelmatrix", "kernelunitlength", "lighting-color", "local", "marker-end", "marker-mid", "marker-start", "markerheight", "markerunits", "markerwidth", "maskcontentunits", "maskunits", "max", "mask", "mask-type", "media", "method", "mode", "min", "name", "numoctaves", "offset", "operator", "opacity", "order", "orient", "orientation", "origin", "overflow", "paint-order", "path", "pathlength", "patterncontentunits", "patterntransform", "patternunits", "points", "preservealpha", "preserveaspectratio", "primitiveunits", "r", "rx", "ry", "radius", "refx", "refy", "repeatcount", "repeatdur", "restart", "result", "rotate", "scale", "seed", "shape-rendering", "slope", "specularconstant", "specularexponent", "spreadmethod", "startoffset", "stddeviation", "stitchtiles", "stop-color", "stop-opacity", "stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin", "stroke-miterlimit", "stroke-opacity", "stroke", "stroke-width", "style", "surfacescale", "systemlanguage", "tabindex", "tablevalues", "targetx", "targety", "transform", "transform-origin", "text-anchor", "text-decoration", "text-rendering", "textlength", "type", "u1", "u2", "unicode", "values", "viewbox", "visibility", "version", "vert-adv-y", "vert-origin-x", "vert-origin-y", "width", "word-spacing", "wrap", "writing-mode", "xchannelselector", "ychannelselector", "x", "x1", "x2", "xmlns", "y", "y1", "y2", "z", "zoomandpan"]); +var mathMl = freeze(["accent", "accentunder", "align", "bevelled", "close", "columnalign", "columnlines", "columnspacing", "columnspan", "denomalign", "depth", "dir", "display", "displaystyle", "encoding", "fence", "frame", "height", "href", "id", "largeop", "length", "linethickness", "lquote", "lspace", "mathbackground", "mathcolor", "mathsize", "mathvariant", "maxsize", "minsize", "movablelimits", "notation", "numalign", "open", "rowalign", "rowlines", "rowspacing", "rowspan", "rspace", "rquote", "scriptlevel", "scriptminsize", "scriptsizemultiplier", "selection", "separator", "separators", "stretchy", "subscriptshift", "supscriptshift", "symmetric", "voffset", "width", "xmlns"]); +var xml = freeze(["xlink:href", "xml:id", "xlink:title", "xml:space", "xmlns:xlink"]); +var MUSTACHE_EXPR = seal(/\{\{[\w\W]*|[\w\W]*\}\}/gm); +var ERB_EXPR = seal(/<%[\w\W]*|[\w\W]*%>/gm); +var TMPLIT_EXPR = seal(/\$\{[\w\W]*/gm); +var DATA_ATTR = seal(/^data-[\-\w.\u00B7-\uFFFF]+$/); +var ARIA_ATTR = seal(/^aria-[\-\w]+$/); +var IS_ALLOWED_URI = seal( + /^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i + // eslint-disable-line no-useless-escape +); +var IS_SCRIPT_OR_DATA = seal(/^(?:\w+script|data):/i); +var ATTR_WHITESPACE = seal( + /[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g + // eslint-disable-line no-control-regex +); +var DOCTYPE_NAME = seal(/^html$/i); +var CUSTOM_ELEMENT = seal(/^[a-z][.\w]*(-[.\w]+)+$/i); +var EXPRESSIONS = /* @__PURE__ */ Object.freeze({ + __proto__: null, + ARIA_ATTR, + ATTR_WHITESPACE, + CUSTOM_ELEMENT, + DATA_ATTR, + DOCTYPE_NAME, + ERB_EXPR, + IS_ALLOWED_URI, + IS_SCRIPT_OR_DATA, + MUSTACHE_EXPR, + TMPLIT_EXPR +}); +var NODE_TYPE = { + element: 1, + text: 3, + // Deprecated + progressingInstruction: 7, + comment: 8, + document: 9 +}; +var getGlobal = function getGlobal2() { + return typeof window === "undefined" ? null : window; +}; +var _createTrustedTypesPolicy = function _createTrustedTypesPolicy2(trustedTypes, purifyHostElement) { + if (typeof trustedTypes !== "object" || typeof trustedTypes.createPolicy !== "function") { + return null; + } + let suffix = null; + const ATTR_NAME = "data-tt-policy-suffix"; + if (purifyHostElement && purifyHostElement.hasAttribute(ATTR_NAME)) { + suffix = purifyHostElement.getAttribute(ATTR_NAME); + } + const policyName = "dompurify" + (suffix ? "#" + suffix : ""); + try { + return trustedTypes.createPolicy(policyName, { + createHTML(html3) { + return html3; + }, + createScriptURL(scriptUrl) { + return scriptUrl; + } + }); + } catch (_) { + console.warn("TrustedTypes policy " + policyName + " could not be created."); + return null; + } +}; +var _createHooksMap = function _createHooksMap2() { + return { + afterSanitizeAttributes: [], + afterSanitizeElements: [], + afterSanitizeShadowDOM: [], + beforeSanitizeAttributes: [], + beforeSanitizeElements: [], + beforeSanitizeShadowDOM: [], + uponSanitizeAttribute: [], + uponSanitizeElement: [], + uponSanitizeShadowNode: [] + }; +}; +function createDOMPurify() { + let window2 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : getGlobal(); + const DOMPurify = (root) => createDOMPurify(root); + DOMPurify.version = "3.4.0"; + DOMPurify.removed = []; + if (!window2 || !window2.document || window2.document.nodeType !== NODE_TYPE.document || !window2.Element) { + DOMPurify.isSupported = false; + return DOMPurify; + } + let { + document: document2 + } = window2; + const originalDocument = document2; + const currentScript = originalDocument.currentScript; + const { + DocumentFragment, + HTMLTemplateElement, + Node, + Element, + NodeFilter, + NamedNodeMap = window2.NamedNodeMap || window2.MozNamedAttrMap, + HTMLFormElement, + DOMParser, + trustedTypes + } = window2; + const ElementPrototype = Element.prototype; + const cloneNode = lookupGetter(ElementPrototype, "cloneNode"); + const remove = lookupGetter(ElementPrototype, "remove"); + const getNextSibling = lookupGetter(ElementPrototype, "nextSibling"); + const getChildNodes = lookupGetter(ElementPrototype, "childNodes"); + const getParentNode = lookupGetter(ElementPrototype, "parentNode"); + if (typeof HTMLTemplateElement === "function") { + const template = document2.createElement("template"); + if (template.content && template.content.ownerDocument) { + document2 = template.content.ownerDocument; + } + } + let trustedTypesPolicy; + let emptyHTML = ""; + const { + implementation, + createNodeIterator, + createDocumentFragment, + getElementsByTagName + } = document2; + const { + importNode + } = originalDocument; + let hooks = _createHooksMap(); + DOMPurify.isSupported = typeof entries === "function" && typeof getParentNode === "function" && implementation && implementation.createHTMLDocument !== void 0; + const { + MUSTACHE_EXPR: MUSTACHE_EXPR2, + ERB_EXPR: ERB_EXPR2, + TMPLIT_EXPR: TMPLIT_EXPR2, + DATA_ATTR: DATA_ATTR2, + ARIA_ATTR: ARIA_ATTR2, + IS_SCRIPT_OR_DATA: IS_SCRIPT_OR_DATA2, + ATTR_WHITESPACE: ATTR_WHITESPACE2, + CUSTOM_ELEMENT: CUSTOM_ELEMENT2 + } = EXPRESSIONS; + let { + IS_ALLOWED_URI: IS_ALLOWED_URI$1 + } = EXPRESSIONS; + let ALLOWED_TAGS = null; + const DEFAULT_ALLOWED_TAGS = addToSet({}, [...html$1, ...svg$1, ...svgFilters, ...mathMl$1, ...text2]); + let ALLOWED_ATTR = null; + const DEFAULT_ALLOWED_ATTR = addToSet({}, [...html, ...svg, ...mathMl, ...xml]); + let CUSTOM_ELEMENT_HANDLING = Object.seal(create(null, { + tagNameCheck: { + writable: true, + configurable: false, + enumerable: true, + value: null + }, + attributeNameCheck: { + writable: true, + configurable: false, + enumerable: true, + value: null + }, + allowCustomizedBuiltInElements: { + writable: true, + configurable: false, + enumerable: true, + value: false + } + })); + let FORBID_TAGS = null; + let FORBID_ATTR = null; + const EXTRA_ELEMENT_HANDLING = Object.seal(create(null, { + tagCheck: { + writable: true, + configurable: false, + enumerable: true, + value: null + }, + attributeCheck: { + writable: true, + configurable: false, + enumerable: true, + value: null + } + })); + let ALLOW_ARIA_ATTR = true; + let ALLOW_DATA_ATTR = true; + let ALLOW_UNKNOWN_PROTOCOLS = false; + let ALLOW_SELF_CLOSE_IN_ATTR = true; + let SAFE_FOR_TEMPLATES = false; + let SAFE_FOR_XML = true; + let WHOLE_DOCUMENT = false; + let SET_CONFIG = false; + let FORCE_BODY = false; + let RETURN_DOM = false; + let RETURN_DOM_FRAGMENT = false; + let RETURN_TRUSTED_TYPE = false; + let SANITIZE_DOM = true; + let SANITIZE_NAMED_PROPS = false; + const SANITIZE_NAMED_PROPS_PREFIX = "user-content-"; + let KEEP_CONTENT = true; + let IN_PLACE = false; + let USE_PROFILES = {}; + let FORBID_CONTENTS = null; + const DEFAULT_FORBID_CONTENTS = addToSet({}, ["annotation-xml", "audio", "colgroup", "desc", "foreignobject", "head", "iframe", "math", "mi", "mn", "mo", "ms", "mtext", "noembed", "noframes", "noscript", "plaintext", "script", "style", "svg", "template", "thead", "title", "video", "xmp"]); + let DATA_URI_TAGS = null; + const DEFAULT_DATA_URI_TAGS = addToSet({}, ["audio", "video", "img", "source", "image", "track"]); + let URI_SAFE_ATTRIBUTES = null; + const DEFAULT_URI_SAFE_ATTRIBUTES = addToSet({}, ["alt", "class", "for", "id", "label", "name", "pattern", "placeholder", "role", "summary", "title", "value", "style", "xmlns"]); + const MATHML_NAMESPACE = "http://www.w3.org/1998/Math/MathML"; + const SVG_NAMESPACE = "http://www.w3.org/2000/svg"; + const HTML_NAMESPACE = "http://www.w3.org/1999/xhtml"; + let NAMESPACE = HTML_NAMESPACE; + let IS_EMPTY_INPUT = false; + let ALLOWED_NAMESPACES = null; + const DEFAULT_ALLOWED_NAMESPACES = addToSet({}, [MATHML_NAMESPACE, SVG_NAMESPACE, HTML_NAMESPACE], stringToString); + let MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, ["mi", "mo", "mn", "ms", "mtext"]); + let HTML_INTEGRATION_POINTS = addToSet({}, ["annotation-xml"]); + const COMMON_SVG_AND_HTML_ELEMENTS = addToSet({}, ["title", "style", "font", "a", "script"]); + let PARSER_MEDIA_TYPE = null; + const SUPPORTED_PARSER_MEDIA_TYPES = ["application/xhtml+xml", "text/html"]; + const DEFAULT_PARSER_MEDIA_TYPE = "text/html"; + let transformCaseFunc = null; + let CONFIG = null; + const formElement = document2.createElement("form"); + const isRegexOrFunction = function isRegexOrFunction2(testValue) { + return testValue instanceof RegExp || testValue instanceof Function; + }; + const _parseConfig = function _parseConfig2() { + let cfg = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {}; + if (CONFIG && CONFIG === cfg) { + return; + } + if (!cfg || typeof cfg !== "object") { + cfg = {}; + } + cfg = clone(cfg); + PARSER_MEDIA_TYPE = // eslint-disable-next-line unicorn/prefer-includes + SUPPORTED_PARSER_MEDIA_TYPES.indexOf(cfg.PARSER_MEDIA_TYPE) === -1 ? DEFAULT_PARSER_MEDIA_TYPE : cfg.PARSER_MEDIA_TYPE; + transformCaseFunc = PARSER_MEDIA_TYPE === "application/xhtml+xml" ? stringToString : stringToLowerCase; + ALLOWED_TAGS = objectHasOwnProperty(cfg, "ALLOWED_TAGS") ? addToSet({}, cfg.ALLOWED_TAGS, transformCaseFunc) : DEFAULT_ALLOWED_TAGS; + ALLOWED_ATTR = objectHasOwnProperty(cfg, "ALLOWED_ATTR") ? addToSet({}, cfg.ALLOWED_ATTR, transformCaseFunc) : DEFAULT_ALLOWED_ATTR; + ALLOWED_NAMESPACES = objectHasOwnProperty(cfg, "ALLOWED_NAMESPACES") ? addToSet({}, cfg.ALLOWED_NAMESPACES, stringToString) : DEFAULT_ALLOWED_NAMESPACES; + URI_SAFE_ATTRIBUTES = objectHasOwnProperty(cfg, "ADD_URI_SAFE_ATTR") ? addToSet(clone(DEFAULT_URI_SAFE_ATTRIBUTES), cfg.ADD_URI_SAFE_ATTR, transformCaseFunc) : DEFAULT_URI_SAFE_ATTRIBUTES; + DATA_URI_TAGS = objectHasOwnProperty(cfg, "ADD_DATA_URI_TAGS") ? addToSet(clone(DEFAULT_DATA_URI_TAGS), cfg.ADD_DATA_URI_TAGS, transformCaseFunc) : DEFAULT_DATA_URI_TAGS; + FORBID_CONTENTS = objectHasOwnProperty(cfg, "FORBID_CONTENTS") ? addToSet({}, cfg.FORBID_CONTENTS, transformCaseFunc) : DEFAULT_FORBID_CONTENTS; + FORBID_TAGS = objectHasOwnProperty(cfg, "FORBID_TAGS") ? addToSet({}, cfg.FORBID_TAGS, transformCaseFunc) : clone({}); + FORBID_ATTR = objectHasOwnProperty(cfg, "FORBID_ATTR") ? addToSet({}, cfg.FORBID_ATTR, transformCaseFunc) : clone({}); + USE_PROFILES = objectHasOwnProperty(cfg, "USE_PROFILES") ? cfg.USE_PROFILES : false; + ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false; + ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false; + ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false; + ALLOW_SELF_CLOSE_IN_ATTR = cfg.ALLOW_SELF_CLOSE_IN_ATTR !== false; + SAFE_FOR_TEMPLATES = cfg.SAFE_FOR_TEMPLATES || false; + SAFE_FOR_XML = cfg.SAFE_FOR_XML !== false; + WHOLE_DOCUMENT = cfg.WHOLE_DOCUMENT || false; + RETURN_DOM = cfg.RETURN_DOM || false; + RETURN_DOM_FRAGMENT = cfg.RETURN_DOM_FRAGMENT || false; + RETURN_TRUSTED_TYPE = cfg.RETURN_TRUSTED_TYPE || false; + FORCE_BODY = cfg.FORCE_BODY || false; + SANITIZE_DOM = cfg.SANITIZE_DOM !== false; + SANITIZE_NAMED_PROPS = cfg.SANITIZE_NAMED_PROPS || false; + KEEP_CONTENT = cfg.KEEP_CONTENT !== false; + IN_PLACE = cfg.IN_PLACE || false; + IS_ALLOWED_URI$1 = cfg.ALLOWED_URI_REGEXP || IS_ALLOWED_URI; + NAMESPACE = cfg.NAMESPACE || HTML_NAMESPACE; + MATHML_TEXT_INTEGRATION_POINTS = cfg.MATHML_TEXT_INTEGRATION_POINTS || MATHML_TEXT_INTEGRATION_POINTS; + HTML_INTEGRATION_POINTS = cfg.HTML_INTEGRATION_POINTS || HTML_INTEGRATION_POINTS; + CUSTOM_ELEMENT_HANDLING = cfg.CUSTOM_ELEMENT_HANDLING || create(null); + if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck)) { + CUSTOM_ELEMENT_HANDLING.tagNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck; + } + if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)) { + CUSTOM_ELEMENT_HANDLING.attributeNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck; + } + if (cfg.CUSTOM_ELEMENT_HANDLING && typeof cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements === "boolean") { + CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements = cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements; + } + if (SAFE_FOR_TEMPLATES) { + ALLOW_DATA_ATTR = false; + } + if (RETURN_DOM_FRAGMENT) { + RETURN_DOM = true; + } + if (USE_PROFILES) { + ALLOWED_TAGS = addToSet({}, text2); + ALLOWED_ATTR = create(null); + if (USE_PROFILES.html === true) { + addToSet(ALLOWED_TAGS, html$1); + addToSet(ALLOWED_ATTR, html); + } + if (USE_PROFILES.svg === true) { + addToSet(ALLOWED_TAGS, svg$1); + addToSet(ALLOWED_ATTR, svg); + addToSet(ALLOWED_ATTR, xml); + } + if (USE_PROFILES.svgFilters === true) { + addToSet(ALLOWED_TAGS, svgFilters); + addToSet(ALLOWED_ATTR, svg); + addToSet(ALLOWED_ATTR, xml); + } + if (USE_PROFILES.mathMl === true) { + addToSet(ALLOWED_TAGS, mathMl$1); + addToSet(ALLOWED_ATTR, mathMl); + addToSet(ALLOWED_ATTR, xml); + } + } + EXTRA_ELEMENT_HANDLING.tagCheck = null; + EXTRA_ELEMENT_HANDLING.attributeCheck = null; + if (cfg.ADD_TAGS) { + if (typeof cfg.ADD_TAGS === "function") { + EXTRA_ELEMENT_HANDLING.tagCheck = cfg.ADD_TAGS; + } else { + if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) { + ALLOWED_TAGS = clone(ALLOWED_TAGS); + } + addToSet(ALLOWED_TAGS, cfg.ADD_TAGS, transformCaseFunc); + } + } + if (cfg.ADD_ATTR) { + if (typeof cfg.ADD_ATTR === "function") { + EXTRA_ELEMENT_HANDLING.attributeCheck = cfg.ADD_ATTR; + } else { + if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) { + ALLOWED_ATTR = clone(ALLOWED_ATTR); + } + addToSet(ALLOWED_ATTR, cfg.ADD_ATTR, transformCaseFunc); + } + } + if (cfg.ADD_URI_SAFE_ATTR) { + addToSet(URI_SAFE_ATTRIBUTES, cfg.ADD_URI_SAFE_ATTR, transformCaseFunc); + } + if (cfg.FORBID_CONTENTS) { + if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) { + FORBID_CONTENTS = clone(FORBID_CONTENTS); + } + addToSet(FORBID_CONTENTS, cfg.FORBID_CONTENTS, transformCaseFunc); + } + if (cfg.ADD_FORBID_CONTENTS) { + if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) { + FORBID_CONTENTS = clone(FORBID_CONTENTS); + } + addToSet(FORBID_CONTENTS, cfg.ADD_FORBID_CONTENTS, transformCaseFunc); + } + if (KEEP_CONTENT) { + ALLOWED_TAGS["#text"] = true; + } + if (WHOLE_DOCUMENT) { + addToSet(ALLOWED_TAGS, ["html", "head", "body"]); + } + if (ALLOWED_TAGS.table) { + addToSet(ALLOWED_TAGS, ["tbody"]); + delete FORBID_TAGS.tbody; + } + if (cfg.TRUSTED_TYPES_POLICY) { + if (typeof cfg.TRUSTED_TYPES_POLICY.createHTML !== "function") { + throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.'); + } + if (typeof cfg.TRUSTED_TYPES_POLICY.createScriptURL !== "function") { + throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.'); + } + trustedTypesPolicy = cfg.TRUSTED_TYPES_POLICY; + emptyHTML = trustedTypesPolicy.createHTML(""); + } else { + if (trustedTypesPolicy === void 0) { + trustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, currentScript); + } + if (trustedTypesPolicy !== null && typeof emptyHTML === "string") { + emptyHTML = trustedTypesPolicy.createHTML(""); + } + } + if (freeze) { + freeze(cfg); + } + CONFIG = cfg; + }; + const ALL_SVG_TAGS = addToSet({}, [...svg$1, ...svgFilters, ...svgDisallowed]); + const ALL_MATHML_TAGS = addToSet({}, [...mathMl$1, ...mathMlDisallowed]); + const _checkValidNamespace = function _checkValidNamespace2(element) { + let parent = getParentNode(element); + if (!parent || !parent.tagName) { + parent = { + namespaceURI: NAMESPACE, + tagName: "template" + }; + } + const tagName = stringToLowerCase(element.tagName); + const parentTagName = stringToLowerCase(parent.tagName); + if (!ALLOWED_NAMESPACES[element.namespaceURI]) { + return false; + } + if (element.namespaceURI === SVG_NAMESPACE) { + if (parent.namespaceURI === HTML_NAMESPACE) { + return tagName === "svg"; + } + if (parent.namespaceURI === MATHML_NAMESPACE) { + return tagName === "svg" && (parentTagName === "annotation-xml" || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]); + } + return Boolean(ALL_SVG_TAGS[tagName]); + } + if (element.namespaceURI === MATHML_NAMESPACE) { + if (parent.namespaceURI === HTML_NAMESPACE) { + return tagName === "math"; + } + if (parent.namespaceURI === SVG_NAMESPACE) { + return tagName === "math" && HTML_INTEGRATION_POINTS[parentTagName]; + } + return Boolean(ALL_MATHML_TAGS[tagName]); + } + if (element.namespaceURI === HTML_NAMESPACE) { + if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) { + return false; + } + if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) { + return false; + } + return !ALL_MATHML_TAGS[tagName] && (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName]); + } + if (PARSER_MEDIA_TYPE === "application/xhtml+xml" && ALLOWED_NAMESPACES[element.namespaceURI]) { + return true; + } + return false; + }; + const _forceRemove = function _forceRemove2(node) { + arrayPush(DOMPurify.removed, { + element: node + }); + try { + getParentNode(node).removeChild(node); + } catch (_) { + remove(node); + } + }; + const _removeAttribute = function _removeAttribute2(name, element) { + try { + arrayPush(DOMPurify.removed, { + attribute: element.getAttributeNode(name), + from: element + }); + } catch (_) { + arrayPush(DOMPurify.removed, { + attribute: null, + from: element + }); + } + element.removeAttribute(name); + if (name === "is") { + if (RETURN_DOM || RETURN_DOM_FRAGMENT) { + try { + _forceRemove(element); + } catch (_) { + } + } else { + try { + element.setAttribute(name, ""); + } catch (_) { + } + } + } + }; + const _initDocument = function _initDocument2(dirty) { + let doc = null; + let leadingWhitespace = null; + if (FORCE_BODY) { + dirty = "" + dirty; + } else { + const matches = stringMatch(dirty, /^[\r\n\t ]+/); + leadingWhitespace = matches && matches[0]; + } + if (PARSER_MEDIA_TYPE === "application/xhtml+xml" && NAMESPACE === HTML_NAMESPACE) { + dirty = '' + dirty + ""; + } + const dirtyPayload = trustedTypesPolicy ? trustedTypesPolicy.createHTML(dirty) : dirty; + if (NAMESPACE === HTML_NAMESPACE) { + try { + doc = new DOMParser().parseFromString(dirtyPayload, PARSER_MEDIA_TYPE); + } catch (_) { + } + } + if (!doc || !doc.documentElement) { + doc = implementation.createDocument(NAMESPACE, "template", null); + try { + doc.documentElement.innerHTML = IS_EMPTY_INPUT ? emptyHTML : dirtyPayload; + } catch (_) { + } + } + const body = doc.body || doc.documentElement; + if (dirty && leadingWhitespace) { + body.insertBefore(document2.createTextNode(leadingWhitespace), body.childNodes[0] || null); + } + if (NAMESPACE === HTML_NAMESPACE) { + return getElementsByTagName.call(doc, WHOLE_DOCUMENT ? "html" : "body")[0]; + } + return WHOLE_DOCUMENT ? doc.documentElement : body; + }; + const _createNodeIterator = function _createNodeIterator2(root) { + return createNodeIterator.call( + root.ownerDocument || root, + root, + // eslint-disable-next-line no-bitwise + NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT | NodeFilter.SHOW_PROCESSING_INSTRUCTION | NodeFilter.SHOW_CDATA_SECTION, + null + ); + }; + const _isClobbered = function _isClobbered2(element) { + return element instanceof HTMLFormElement && (typeof element.nodeName !== "string" || typeof element.textContent !== "string" || typeof element.removeChild !== "function" || !(element.attributes instanceof NamedNodeMap) || typeof element.removeAttribute !== "function" || typeof element.setAttribute !== "function" || typeof element.namespaceURI !== "string" || typeof element.insertBefore !== "function" || typeof element.hasChildNodes !== "function"); + }; + const _isNode = function _isNode2(value) { + return typeof Node === "function" && value instanceof Node; + }; + function _executeHooks(hooks2, currentNode, data2) { + arrayForEach(hooks2, (hook) => { + hook.call(DOMPurify, currentNode, data2, CONFIG); + }); + } + const _sanitizeElements = function _sanitizeElements2(currentNode) { + let content = null; + _executeHooks(hooks.beforeSanitizeElements, currentNode, null); + if (_isClobbered(currentNode)) { + _forceRemove(currentNode); + return true; + } + const tagName = transformCaseFunc(currentNode.nodeName); + _executeHooks(hooks.uponSanitizeElement, currentNode, { + tagName, + allowedTags: ALLOWED_TAGS + }); + if (SAFE_FOR_XML && currentNode.hasChildNodes() && !_isNode(currentNode.firstElementChild) && regExpTest(/<[/\w!]/g, currentNode.innerHTML) && regExpTest(/<[/\w!]/g, currentNode.textContent)) { + _forceRemove(currentNode); + return true; + } + if (SAFE_FOR_XML && currentNode.namespaceURI === HTML_NAMESPACE && tagName === "style" && _isNode(currentNode.firstElementChild)) { + _forceRemove(currentNode); + return true; + } + if (currentNode.nodeType === NODE_TYPE.progressingInstruction) { + _forceRemove(currentNode); + return true; + } + if (SAFE_FOR_XML && currentNode.nodeType === NODE_TYPE.comment && regExpTest(/<[/\w]/g, currentNode.data)) { + _forceRemove(currentNode); + return true; + } + if (FORBID_TAGS[tagName] || !(EXTRA_ELEMENT_HANDLING.tagCheck instanceof Function && EXTRA_ELEMENT_HANDLING.tagCheck(tagName)) && !ALLOWED_TAGS[tagName]) { + if (!FORBID_TAGS[tagName] && _isBasicCustomElement(tagName)) { + if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)) { + return false; + } + if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(tagName)) { + return false; + } + } + if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) { + const parentNode = getParentNode(currentNode) || currentNode.parentNode; + const childNodes = getChildNodes(currentNode) || currentNode.childNodes; + if (childNodes && parentNode) { + const childCount = childNodes.length; + for (let i5 = childCount - 1; i5 >= 0; --i5) { + const childClone = cloneNode(childNodes[i5], true); + childClone.__removalCount = (currentNode.__removalCount || 0) + 1; + parentNode.insertBefore(childClone, getNextSibling(currentNode)); + } + } + } + _forceRemove(currentNode); + return true; + } + if (currentNode instanceof Element && !_checkValidNamespace(currentNode)) { + _forceRemove(currentNode); + return true; + } + if ((tagName === "noscript" || tagName === "noembed" || tagName === "noframes") && regExpTest(/<\/no(script|embed|frames)/i, currentNode.innerHTML)) { + _forceRemove(currentNode); + return true; + } + if (SAFE_FOR_TEMPLATES && currentNode.nodeType === NODE_TYPE.text) { + content = currentNode.textContent; + arrayForEach([MUSTACHE_EXPR2, ERB_EXPR2, TMPLIT_EXPR2], (expr) => { + content = stringReplace(content, expr, " "); + }); + if (currentNode.textContent !== content) { + arrayPush(DOMPurify.removed, { + element: currentNode.cloneNode() + }); + currentNode.textContent = content; + } + } + _executeHooks(hooks.afterSanitizeElements, currentNode, null); + return false; + }; + const _isValidAttribute = function _isValidAttribute2(lcTag, lcName, value) { + if (FORBID_ATTR[lcName]) { + return false; + } + if (SANITIZE_DOM && (lcName === "id" || lcName === "name") && (value in document2 || value in formElement)) { + return false; + } + if (ALLOW_DATA_ATTR && !FORBID_ATTR[lcName] && regExpTest(DATA_ATTR2, lcName)) ; + else if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR2, lcName)) ; + else if (EXTRA_ELEMENT_HANDLING.attributeCheck instanceof Function && EXTRA_ELEMENT_HANDLING.attributeCheck(lcName, lcTag)) ; + else if (!ALLOWED_ATTR[lcName] || FORBID_ATTR[lcName]) { + if ( + // First condition does a very basic check if a) it's basically a valid custom element tagname AND + // b) if the tagName passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck + // and c) if the attribute name passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.attributeNameCheck + _isBasicCustomElement(lcTag) && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, lcTag) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(lcTag)) && (CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.attributeNameCheck, lcName) || CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.attributeNameCheck(lcName, lcTag)) || // Alternative, second condition checks if it's an `is`-attribute, AND + // the value passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck + lcName === "is" && CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, value) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(value)) + ) ; + else { + return false; + } + } else if (URI_SAFE_ATTRIBUTES[lcName]) ; + else if (regExpTest(IS_ALLOWED_URI$1, stringReplace(value, ATTR_WHITESPACE2, ""))) ; + else if ((lcName === "src" || lcName === "xlink:href" || lcName === "href") && lcTag !== "script" && stringIndexOf(value, "data:") === 0 && DATA_URI_TAGS[lcTag]) ; + else if (ALLOW_UNKNOWN_PROTOCOLS && !regExpTest(IS_SCRIPT_OR_DATA2, stringReplace(value, ATTR_WHITESPACE2, ""))) ; + else if (value) { + return false; + } else ; + return true; + }; + const _isBasicCustomElement = function _isBasicCustomElement2(tagName) { + return tagName !== "annotation-xml" && stringMatch(tagName, CUSTOM_ELEMENT2); + }; + const _sanitizeAttributes = function _sanitizeAttributes2(currentNode) { + _executeHooks(hooks.beforeSanitizeAttributes, currentNode, null); + const { + attributes + } = currentNode; + if (!attributes || _isClobbered(currentNode)) { + return; + } + const hookEvent = { + attrName: "", + attrValue: "", + keepAttr: true, + allowedAttributes: ALLOWED_ATTR, + forceKeepAttr: void 0 + }; + let l5 = attributes.length; + while (l5--) { + const attr = attributes[l5]; + const { + name, + namespaceURI, + value: attrValue + } = attr; + const lcName = transformCaseFunc(name); + const initValue = attrValue; + let value = name === "value" ? initValue : stringTrim(initValue); + hookEvent.attrName = lcName; + hookEvent.attrValue = value; + hookEvent.keepAttr = true; + hookEvent.forceKeepAttr = void 0; + _executeHooks(hooks.uponSanitizeAttribute, currentNode, hookEvent); + value = hookEvent.attrValue; + if (SANITIZE_NAMED_PROPS && (lcName === "id" || lcName === "name")) { + _removeAttribute(name, currentNode); + value = SANITIZE_NAMED_PROPS_PREFIX + value; + } + if (SAFE_FOR_XML && regExpTest(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i, value)) { + _removeAttribute(name, currentNode); + continue; + } + if (lcName === "attributename" && stringMatch(value, "href")) { + _removeAttribute(name, currentNode); + continue; + } + if (hookEvent.forceKeepAttr) { + continue; + } + if (!hookEvent.keepAttr) { + _removeAttribute(name, currentNode); + continue; + } + if (!ALLOW_SELF_CLOSE_IN_ATTR && regExpTest(/\/>/i, value)) { + _removeAttribute(name, currentNode); + continue; + } + if (SAFE_FOR_TEMPLATES) { + arrayForEach([MUSTACHE_EXPR2, ERB_EXPR2, TMPLIT_EXPR2], (expr) => { + value = stringReplace(value, expr, " "); + }); + } + const lcTag = transformCaseFunc(currentNode.nodeName); + if (!_isValidAttribute(lcTag, lcName, value)) { + _removeAttribute(name, currentNode); + continue; + } + if (trustedTypesPolicy && typeof trustedTypes === "object" && typeof trustedTypes.getAttributeType === "function") { + if (namespaceURI) ; + else { + switch (trustedTypes.getAttributeType(lcTag, lcName)) { + case "TrustedHTML": { + value = trustedTypesPolicy.createHTML(value); + break; + } + case "TrustedScriptURL": { + value = trustedTypesPolicy.createScriptURL(value); + break; + } + } + } + } + if (value !== initValue) { + try { + if (namespaceURI) { + currentNode.setAttributeNS(namespaceURI, name, value); + } else { + currentNode.setAttribute(name, value); + } + if (_isClobbered(currentNode)) { + _forceRemove(currentNode); + } else { + arrayPop(DOMPurify.removed); + } + } catch (_) { + _removeAttribute(name, currentNode); + } + } + } + _executeHooks(hooks.afterSanitizeAttributes, currentNode, null); + }; + const _sanitizeShadowDOM2 = function _sanitizeShadowDOM(fragment2) { + let shadowNode = null; + const shadowIterator = _createNodeIterator(fragment2); + _executeHooks(hooks.beforeSanitizeShadowDOM, fragment2, null); + while (shadowNode = shadowIterator.nextNode()) { + _executeHooks(hooks.uponSanitizeShadowNode, shadowNode, null); + _sanitizeElements(shadowNode); + _sanitizeAttributes(shadowNode); + if (shadowNode.content instanceof DocumentFragment) { + _sanitizeShadowDOM2(shadowNode.content); + } + } + _executeHooks(hooks.afterSanitizeShadowDOM, fragment2, null); + }; + DOMPurify.sanitize = function(dirty) { + let cfg = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}; + let body = null; + let importedNode = null; + let currentNode = null; + let returnNode = null; + IS_EMPTY_INPUT = !dirty; + if (IS_EMPTY_INPUT) { + dirty = ""; + } + if (typeof dirty !== "string" && !_isNode(dirty)) { + if (typeof dirty.toString === "function") { + dirty = dirty.toString(); + if (typeof dirty !== "string") { + throw typeErrorCreate("dirty is not a string, aborting"); + } + } else { + throw typeErrorCreate("toString is not a function"); + } + } + if (!DOMPurify.isSupported) { + return dirty; + } + if (!SET_CONFIG) { + _parseConfig(cfg); + } + DOMPurify.removed = []; + if (typeof dirty === "string") { + IN_PLACE = false; + } + if (IN_PLACE) { + if (dirty.nodeName) { + const tagName = transformCaseFunc(dirty.nodeName); + if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) { + throw typeErrorCreate("root node is forbidden and cannot be sanitized in-place"); + } + } + } else if (dirty instanceof Node) { + body = _initDocument(""); + importedNode = body.ownerDocument.importNode(dirty, true); + if (importedNode.nodeType === NODE_TYPE.element && importedNode.nodeName === "BODY") { + body = importedNode; + } else if (importedNode.nodeName === "HTML") { + body = importedNode; + } else { + body.appendChild(importedNode); + } + } else { + if (!RETURN_DOM && !SAFE_FOR_TEMPLATES && !WHOLE_DOCUMENT && // eslint-disable-next-line unicorn/prefer-includes + dirty.indexOf("<") === -1) { + return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(dirty) : dirty; + } + body = _initDocument(dirty); + if (!body) { + return RETURN_DOM ? null : RETURN_TRUSTED_TYPE ? emptyHTML : ""; + } + } + if (body && FORCE_BODY) { + _forceRemove(body.firstChild); + } + const nodeIterator = _createNodeIterator(IN_PLACE ? dirty : body); + while (currentNode = nodeIterator.nextNode()) { + _sanitizeElements(currentNode); + _sanitizeAttributes(currentNode); + if (currentNode.content instanceof DocumentFragment) { + _sanitizeShadowDOM2(currentNode.content); + } + } + if (IN_PLACE) { + return dirty; + } + if (RETURN_DOM) { + if (SAFE_FOR_TEMPLATES) { + body.normalize(); + let html3 = body.innerHTML; + arrayForEach([MUSTACHE_EXPR2, ERB_EXPR2, TMPLIT_EXPR2], (expr) => { + html3 = stringReplace(html3, expr, " "); + }); + body.innerHTML = html3; + } + if (RETURN_DOM_FRAGMENT) { + returnNode = createDocumentFragment.call(body.ownerDocument); + while (body.firstChild) { + returnNode.appendChild(body.firstChild); + } + } else { + returnNode = body; + } + if (ALLOWED_ATTR.shadowroot || ALLOWED_ATTR.shadowrootmode) { + returnNode = importNode.call(originalDocument, returnNode, true); + } + return returnNode; + } + let serializedHTML = WHOLE_DOCUMENT ? body.outerHTML : body.innerHTML; + if (WHOLE_DOCUMENT && ALLOWED_TAGS["!doctype"] && body.ownerDocument && body.ownerDocument.doctype && body.ownerDocument.doctype.name && regExpTest(DOCTYPE_NAME, body.ownerDocument.doctype.name)) { + serializedHTML = "\n" + serializedHTML; + } + if (SAFE_FOR_TEMPLATES) { + arrayForEach([MUSTACHE_EXPR2, ERB_EXPR2, TMPLIT_EXPR2], (expr) => { + serializedHTML = stringReplace(serializedHTML, expr, " "); + }); + } + return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(serializedHTML) : serializedHTML; + }; + DOMPurify.setConfig = function() { + let cfg = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {}; + _parseConfig(cfg); + SET_CONFIG = true; + }; + DOMPurify.clearConfig = function() { + CONFIG = null; + SET_CONFIG = false; + }; + DOMPurify.isValidAttribute = function(tag3, attr, value) { + if (!CONFIG) { + _parseConfig({}); + } + const lcTag = transformCaseFunc(tag3); + const lcName = transformCaseFunc(attr); + return _isValidAttribute(lcTag, lcName, value); + }; + DOMPurify.addHook = function(entryPoint, hookFunction) { + if (typeof hookFunction !== "function") { + return; + } + arrayPush(hooks[entryPoint], hookFunction); + }; + DOMPurify.removeHook = function(entryPoint, hookFunction) { + if (hookFunction !== void 0) { + const index2 = arrayLastIndexOf(hooks[entryPoint], hookFunction); + return index2 === -1 ? void 0 : arraySplice(hooks[entryPoint], index2, 1)[0]; + } + return arrayPop(hooks[entryPoint]); + }; + DOMPurify.removeHooks = function(entryPoint) { + hooks[entryPoint] = []; + }; + DOMPurify.removeAllHooks = function() { + hooks = _createHooksMap(); + }; + return DOMPurify; +} +var purify = createDOMPurify(); + +// server/src/routes/assets.ts +import { JSDOM } from "jsdom"; +var SVG_CONTENT_TYPE2 = "image/svg+xml"; +var ALLOWED_COMPANY_LOGO_CONTENT_TYPES = /* @__PURE__ */ new Set([ + "image/png", + "image/jpeg", + "image/jpg", + "image/webp", + "image/gif", + SVG_CONTENT_TYPE2 +]); +function sanitizeSvgBuffer(input) { + const raw = input.toString("utf8").trim(); + if (!raw) return null; + const baseDom = new JSDOM(""); + const domPurify = purify( + baseDom.window + ); + domPurify.addHook("uponSanitizeAttribute", (_node, data2) => { + const attrName = data2.attrName.toLowerCase(); + const attrValue = (data2.attrValue ?? "").trim(); + if (attrName.startsWith("on")) { + data2.keepAttr = false; + return; + } + if ((attrName === "href" || attrName === "xlink:href") && attrValue && !attrValue.startsWith("#")) { + data2.keepAttr = false; + } + }); + let parsedDom = null; + try { + const sanitized = domPurify.sanitize(raw, { + USE_PROFILES: { svg: true, svgFilters: true, html: false }, + FORBID_TAGS: ["script", "foreignObject"], + FORBID_CONTENTS: ["script", "foreignObject"], + RETURN_TRUSTED_TYPE: false + }); + parsedDom = new JSDOM(sanitized, { contentType: SVG_CONTENT_TYPE2 }); + const document2 = parsedDom.window.document; + const root = document2.documentElement; + if (!root || root.tagName.toLowerCase() !== "svg") return null; + for (const el of Array.from(root.querySelectorAll("script, foreignObject"))) { + el.remove(); + } + for (const el of Array.from(root.querySelectorAll("*"))) { + for (const attr of Array.from(el.attributes)) { + const attrName = attr.name.toLowerCase(); + const attrValue = attr.value.trim(); + if (attrName.startsWith("on")) { + el.removeAttribute(attr.name); + continue; + } + if ((attrName === "href" || attrName === "xlink:href") && attrValue && !attrValue.startsWith("#")) { + el.removeAttribute(attr.name); + } + } + } + const output = root.outerHTML.trim(); + if (!output || !/^]/i.test(output)) return null; + return Buffer.from(output, "utf8"); + } catch { + return null; + } finally { + parsedDom?.window.close(); + baseDom.window.close(); + } +} +function assetRoutes(db, storage) { + const router2 = (0, import_express20.Router)(); + const svc = assetService(db); + const assetUpload = (0, import_multer2.default)({ + storage: import_multer2.default.memoryStorage(), + limits: { fileSize: MAX_ATTACHMENT_BYTES, files: 1 } + }); + const companyLogoUpload = (0, import_multer2.default)({ + storage: import_multer2.default.memoryStorage(), + limits: { fileSize: MAX_ATTACHMENT_BYTES, files: 1 } + }); + async function runSingleFileUpload(upload, req, res) { + await new Promise((resolve4, reject) => { + upload.single("file")(req, res, (err) => { + if (err) reject(err); + else resolve4(); + }); + }); + } + router2.post("/companies/:companyId/assets/images", async (req, res) => { + const companyId = req.params.companyId; + assertCompanyAccess(req, companyId); + try { + await runSingleFileUpload(assetUpload, req, res); + } catch (err) { + if (err instanceof import_multer2.default.MulterError) { + if (err.code === "LIMIT_FILE_SIZE") { + res.status(422).json({ error: `File exceeds ${MAX_ATTACHMENT_BYTES} bytes` }); + return; + } + res.status(400).json({ error: err.message }); + return; + } + throw err; + } + const file2 = req.file; + if (!file2) { + res.status(400).json({ error: "Missing file field 'file'" }); + return; + } + const parsedMeta = createAssetImageMetadataSchema.safeParse(req.body ?? {}); + if (!parsedMeta.success) { + res.status(400).json({ error: "Invalid image metadata", details: parsedMeta.error.issues }); + return; + } + const namespaceSuffix = parsedMeta.data.namespace ?? "general"; + const contentType = (file2.mimetype || "").toLowerCase(); + if (contentType !== SVG_CONTENT_TYPE2 && !isAllowedContentType(contentType)) { + res.status(422).json({ error: `Unsupported file type: ${contentType || "unknown"}` }); + return; + } + let fileBody = file2.buffer; + if (contentType === SVG_CONTENT_TYPE2) { + const sanitized = sanitizeSvgBuffer(file2.buffer); + if (!sanitized || sanitized.length <= 0) { + res.status(422).json({ error: "SVG could not be sanitized" }); + return; + } + fileBody = sanitized; + } + if (fileBody.length <= 0) { + res.status(422).json({ error: "Image is empty" }); + return; + } + const actor = getActorInfo(req); + const stored = await storage.putFile({ + companyId, + namespace: `assets/${namespaceSuffix}`, + originalFilename: file2.originalname || null, + contentType, + body: fileBody + }); + const asset = await svc.create(companyId, { + provider: stored.provider, + objectKey: stored.objectKey, + contentType: stored.contentType, + byteSize: stored.byteSize, + sha256: stored.sha256, + originalFilename: stored.originalFilename, + createdByAgentId: actor.agentId, + createdByUserId: actor.actorType === "user" ? actor.actorId : null + }); + await logActivity(db, { + companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + runId: actor.runId, + action: "asset.created", + entityType: "asset", + entityId: asset.id, + details: { + originalFilename: asset.originalFilename, + contentType: asset.contentType, + byteSize: asset.byteSize + } + }); + res.status(201).json({ + assetId: asset.id, + companyId: asset.companyId, + provider: asset.provider, + objectKey: asset.objectKey, + contentType: asset.contentType, + byteSize: asset.byteSize, + sha256: asset.sha256, + originalFilename: asset.originalFilename, + createdByAgentId: asset.createdByAgentId, + createdByUserId: asset.createdByUserId, + createdAt: asset.createdAt, + updatedAt: asset.updatedAt, + contentPath: `/api/assets/${asset.id}/content` + }); + }); + router2.post("/companies/:companyId/logo", async (req, res) => { + const companyId = req.params.companyId; + assertCompanyAccess(req, companyId); + try { + await runSingleFileUpload(companyLogoUpload, req, res); + } catch (err) { + if (err instanceof import_multer2.default.MulterError) { + if (err.code === "LIMIT_FILE_SIZE") { + res.status(422).json({ error: `Image exceeds ${MAX_ATTACHMENT_BYTES} bytes` }); + return; + } + res.status(400).json({ error: err.message }); + return; + } + throw err; + } + const file2 = req.file; + if (!file2) { + res.status(400).json({ error: "Missing file field 'file'" }); + return; + } + const contentType = (file2.mimetype || "").toLowerCase(); + if (!ALLOWED_COMPANY_LOGO_CONTENT_TYPES.has(contentType)) { + res.status(422).json({ error: `Unsupported image type: ${contentType || "unknown"}` }); + return; + } + let fileBody = file2.buffer; + if (contentType === SVG_CONTENT_TYPE2) { + const sanitized = sanitizeSvgBuffer(file2.buffer); + if (!sanitized || sanitized.length <= 0) { + res.status(422).json({ error: "SVG could not be sanitized" }); + return; + } + fileBody = sanitized; + } + if (fileBody.length <= 0) { + res.status(422).json({ error: "Image is empty" }); + return; + } + const actor = getActorInfo(req); + const stored = await storage.putFile({ + companyId, + namespace: "assets/companies", + originalFilename: file2.originalname || null, + contentType, + body: fileBody + }); + const asset = await svc.create(companyId, { + provider: stored.provider, + objectKey: stored.objectKey, + contentType: stored.contentType, + byteSize: stored.byteSize, + sha256: stored.sha256, + originalFilename: stored.originalFilename, + createdByAgentId: actor.agentId, + createdByUserId: actor.actorType === "user" ? actor.actorId : null + }); + await logActivity(db, { + companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + runId: actor.runId, + action: "asset.created", + entityType: "asset", + entityId: asset.id, + details: { + originalFilename: asset.originalFilename, + contentType: asset.contentType, + byteSize: asset.byteSize, + namespace: "assets/companies" + } + }); + res.status(201).json({ + assetId: asset.id, + companyId: asset.companyId, + provider: asset.provider, + objectKey: asset.objectKey, + contentType: asset.contentType, + byteSize: asset.byteSize, + sha256: asset.sha256, + originalFilename: asset.originalFilename, + createdByAgentId: asset.createdByAgentId, + createdByUserId: asset.createdByUserId, + createdAt: asset.createdAt, + updatedAt: asset.updatedAt, + contentPath: `/api/assets/${asset.id}/content` + }); + }); + router2.get("/assets/:assetId/content", async (req, res, next) => { + const assetId = req.params.assetId; + const asset = await svc.getById(assetId); + if (!asset) { + res.status(404).json({ error: "Asset not found" }); + return; + } + assertCompanyAccess(req, asset.companyId); + const object2 = await storage.getObject(asset.companyId, asset.objectKey); + const responseContentType = asset.contentType || object2.contentType || "application/octet-stream"; + res.setHeader("Content-Type", responseContentType); + res.setHeader("Content-Length", String(asset.byteSize || object2.contentLength || 0)); + res.setHeader("Cache-Control", "private, max-age=60"); + res.setHeader("X-Content-Type-Options", "nosniff"); + if (responseContentType === SVG_CONTENT_TYPE2) { + res.setHeader("Content-Security-Policy", "sandbox; default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'"); + } + const filename = asset.originalFilename ?? "asset"; + res.setHeader("Content-Disposition", `inline; filename="${filename.replaceAll('"', "")}"`); + object2.stream.on("error", (err) => { + next(err); + }); + object2.stream.pipe(res); + }); + return router2; +} + +// server/src/routes/access.ts +var import_express21 = __toESM(require_express2(), 1); +init_drizzle_orm(); +init_src2(); +import { + createHash as createHash16, + generateKeyPairSync as generateKeyPairSync2, + randomBytes as randomBytes5, + timingSafeEqual as timingSafeEqual3 +} from "node:crypto"; +import fs36 from "node:fs"; +import path45 from "node:path"; +import { fileURLToPath as fileURLToPath16 } from "node:url"; + +// server/src/board-claim.ts +init_drizzle_orm(); +init_src2(); +import { randomBytes as randomBytes4 } from "node:crypto"; +var LOCAL_BOARD_USER_ID = "local-board"; +var CLAIM_TTL_MS = 1e3 * 60 * 60 * 24; +var activeChallenge = null; +function createChallenge(now2 = /* @__PURE__ */ new Date()) { + return { + token: randomBytes4(24).toString("hex"), + code: randomBytes4(12).toString("hex"), + createdAt: now2, + expiresAt: new Date(now2.getTime() + CLAIM_TTL_MS), + claimedAt: null, + claimedByUserId: null + }; +} +function getChallengeStatus(token, code) { + if (!activeChallenge) return "invalid"; + if (activeChallenge.token !== token) return "invalid"; + if (activeChallenge.code !== (code ?? "")) return "invalid"; + if (activeChallenge.claimedAt) return "claimed"; + if (activeChallenge.expiresAt.getTime() <= Date.now()) return "expired"; + return "available"; +} +async function initializeBoardClaimChallenge(db, opts) { + if (opts.deploymentMode !== "authenticated") { + activeChallenge = null; + return; + } + const admins = await db.select({ userId: instanceUserRoles.userId }).from(instanceUserRoles).where(eq(instanceUserRoles.role, "instance_admin")); + const onlyLocalBoardAdmin = admins.length === 1 && admins[0]?.userId === LOCAL_BOARD_USER_ID; + if (!onlyLocalBoardAdmin) { + activeChallenge = null; + return; + } + if (!activeChallenge || activeChallenge.expiresAt.getTime() <= Date.now() || activeChallenge.claimedAt) { + activeChallenge = createChallenge(); + } +} +function inspectBoardClaimChallenge(token, code) { + const status = getChallengeStatus(token, code); + return { + status, + requiresSignIn: true, + expiresAt: activeChallenge?.expiresAt?.toISOString() ?? null, + claimedByUserId: activeChallenge?.claimedByUserId ?? null + }; +} +async function claimBoardOwnership(db, opts) { + const status = getChallengeStatus(opts.token, opts.code); + if (status !== "available") return { status }; + await db.transaction(async (tx) => { + const existingTargetAdmin = await tx.select({ id: instanceUserRoles.id }).from(instanceUserRoles).where(and(eq(instanceUserRoles.userId, opts.userId), eq(instanceUserRoles.role, "instance_admin"))).then((rows) => rows[0] ?? null); + if (!existingTargetAdmin) { + await tx.insert(instanceUserRoles).values({ + userId: opts.userId, + role: "instance_admin" + }); + } + await tx.delete(instanceUserRoles).where(and(eq(instanceUserRoles.userId, LOCAL_BOARD_USER_ID), eq(instanceUserRoles.role, "instance_admin"))); + const allCompanies = await tx.select({ id: companies.id }).from(companies); + for (const company of allCompanies) { + const existing = await tx.select({ id: companyMemberships.id, status: companyMemberships.status }).from(companyMemberships).where( + and( + eq(companyMemberships.companyId, company.id), + eq(companyMemberships.principalType, "user"), + eq(companyMemberships.principalId, opts.userId) + ) + ).then((rows) => rows[0] ?? null); + if (!existing) { + await tx.insert(companyMemberships).values({ + companyId: company.id, + principalType: "user", + principalId: opts.userId, + status: "active", + membershipRole: "owner" + }); + continue; + } + if (existing.status !== "active") { + await tx.update(companyMemberships).set({ status: "active", membershipRole: "owner", updatedAt: /* @__PURE__ */ new Date() }).where(eq(companyMemberships.id, existing.id)); + } + } + }); + if (activeChallenge && activeChallenge.token === opts.token) { + activeChallenge.claimedAt = /* @__PURE__ */ new Date(); + activeChallenge.claimedByUserId = opts.userId; + } + return { status: "claimed", claimedByUserId: opts.userId }; +} + +// server/src/routes/access.ts +function hashToken3(token) { + return createHash16("sha256").update(token).digest("hex"); +} +var INVITE_TOKEN_PREFIX = "pcp_invite_"; +var INVITE_TOKEN_ALPHABET = "abcdefghijklmnopqrstuvwxyz0123456789"; +var INVITE_TOKEN_SUFFIX_LENGTH = 8; +var INVITE_TOKEN_MAX_RETRIES = 5; +var COMPANY_INVITE_TTL_MS = 10 * 60 * 1e3; +function createInviteToken() { + const bytes = randomBytes5(INVITE_TOKEN_SUFFIX_LENGTH); + let suffix = ""; + for (let idx = 0; idx < INVITE_TOKEN_SUFFIX_LENGTH; idx += 1) { + suffix += INVITE_TOKEN_ALPHABET[bytes[idx] % INVITE_TOKEN_ALPHABET.length]; + } + return `${INVITE_TOKEN_PREFIX}${suffix}`; +} +function createClaimSecret() { + return `pcp_claim_${randomBytes5(24).toString("hex")}`; +} +function companyInviteExpiresAt(nowMs = Date.now()) { + return new Date(nowMs + COMPANY_INVITE_TTL_MS); +} +function tokenHashesMatch2(left, right) { + const leftBytes = Buffer.from(left, "utf8"); + const rightBytes = Buffer.from(right, "utf8"); + return leftBytes.length === rightBytes.length && timingSafeEqual3(leftBytes, rightBytes); +} +function requestBaseUrl(req) { + const forwardedProto = req.header("x-forwarded-proto"); + const proto = forwardedProto?.split(",")[0]?.trim() || req.protocol || "http"; + const host = req.header("x-forwarded-host")?.split(",")[0]?.trim() || req.header("host"); + if (!host) return ""; + return `${proto}://${host}`; +} +function buildCliAuthApprovalPath(challengeId, token) { + return `/cli-auth/${challengeId}?token=${encodeURIComponent(token)}`; +} +function readSkillMarkdown(skillName) { + const normalized = skillName.trim().toLowerCase(); + if (normalized !== "taskcore" && normalized !== "taskcore-create-agent" && normalized !== "taskcore-create-plugin" && normalized !== "para-memory-files") + return null; + const moduleDir = path45.dirname(fileURLToPath16(import.meta.url)); + const candidates = [ + path45.resolve(moduleDir, "../../skills", normalized, "SKILL.md"), + // published: dist/routes/ -> /skills/ + path45.resolve(process.cwd(), "skills", normalized, "SKILL.md"), + // cwd (e.g. monorepo root) + path45.resolve(moduleDir, "../../../skills", normalized, "SKILL.md") + // dev: src/routes/ -> repo root/skills/ + ]; + for (const skillPath of candidates) { + try { + return fs36.readFileSync(skillPath, "utf8"); + } catch { + } + } + return null; +} +function resolveTaskcoreSkillsDir2() { + const moduleDir = path45.dirname(fileURLToPath16(import.meta.url)); + const candidates = [ + path45.resolve(moduleDir, "../../skills"), + // published + path45.resolve(process.cwd(), "skills"), + // cwd (monorepo root) + path45.resolve(moduleDir, "../../../skills") + // dev + ]; + for (const candidate of candidates) { + try { + if (fs36.statSync(candidate).isDirectory()) return candidate; + } catch { + } + } + return null; +} +function parseSkillFrontmatter2(markdown) { + const match = markdown.match(/^---\n([\s\S]*?)\n---/); + if (!match) return { description: "" }; + const yaml = match[1]; + const descMatch = yaml.match( + /^description:\s*(?:>\s*\n((?:\s{2,}[^\n]*\n?)+)|[|]\s*\n((?:\s{2,}[^\n]*\n?)+)|["']?(.*?)["']?\s*$)/m + ); + if (!descMatch) return { description: "" }; + const raw = descMatch[1] ?? descMatch[2] ?? descMatch[3] ?? ""; + return { + description: raw.split("\n").map((l5) => l5.trim()).filter(Boolean).join(" ").trim() + }; +} +function listAvailableSkills() { + const homeDir = process.env.HOME || process.env.USERPROFILE || ""; + const claudeSkillsDir = path45.join(homeDir, ".claude", "skills"); + const taskcoreSkillsDir = resolveTaskcoreSkillsDir2(); + const taskcoreSkillNames = /* @__PURE__ */ new Set(); + if (taskcoreSkillsDir) { + try { + for (const entry of fs36.readdirSync(taskcoreSkillsDir, { withFileTypes: true })) { + if (entry.isDirectory()) taskcoreSkillNames.add(entry.name); + } + } catch { + } + } + const skills = []; + try { + const entries2 = fs36.readdirSync(claudeSkillsDir, { withFileTypes: true }); + for (const entry of entries2) { + if (!entry.isDirectory() && !entry.isSymbolicLink()) continue; + if (entry.name.startsWith(".")) continue; + const skillMdPath = path45.join(claudeSkillsDir, entry.name, "SKILL.md"); + let description = ""; + try { + const md = fs36.readFileSync(skillMdPath, "utf8"); + description = parseSkillFrontmatter2(md).description; + } catch { + } + skills.push({ + name: entry.name, + description, + isTaskcoreManaged: taskcoreSkillNames.has(entry.name) + }); + } + } catch { + } + skills.sort((a5, b6) => a5.name.localeCompare(b6.name)); + return skills; +} +function toJoinRequestResponse(row) { + const { claimSecretHash: _claimSecretHash, ...safe } = row; + return safe; +} +function isPlainObject4(value) { + return typeof value === "object" && value !== null && !Array.isArray(value); +} +function isLoopbackHost5(hostname3) { + const value = hostname3.trim().toLowerCase(); + return value === "localhost" || value === "127.0.0.1" || value === "::1"; +} +function normalizeHostname(value) { + if (!value) return null; + const trimmed = value.trim(); + if (!trimmed) return null; + if (trimmed.startsWith("[")) { + const end = trimmed.indexOf("]"); + return end > 1 ? trimmed.slice(1, end).toLowerCase() : trimmed.toLowerCase(); + } + const firstColon = trimmed.indexOf(":"); + if (firstColon > -1) return trimmed.slice(0, firstColon).toLowerCase(); + return trimmed.toLowerCase(); +} +function normalizeHeaderValue(value, depth = 0) { + const direct = nonEmptyTrimmedString(value); + if (direct) return direct; + if (!isPlainObject4(value) || depth >= 3) return null; + const candidateKeys = [ + "value", + "token", + "secret", + "apiKey", + "api_key", + "auth", + "authToken", + "auth_token", + "accessToken", + "access_token", + "authorization", + "bearer", + "header", + "raw", + "text", + "string" + ]; + for (const key of candidateKeys) { + if (!Object.prototype.hasOwnProperty.call(value, key)) continue; + const normalized = normalizeHeaderValue( + value[key], + depth + 1 + ); + if (normalized) return normalized; + } + const entries2 = Object.entries(value); + if (entries2.length === 1) { + const [singleKey, singleValue] = entries2[0]; + const normalizedKey = singleKey.trim().toLowerCase(); + if (normalizedKey !== "type" && normalizedKey !== "version" && normalizedKey !== "secretid" && normalizedKey !== "secret_id") { + const normalized = normalizeHeaderValue(singleValue, depth + 1); + if (normalized) return normalized; + } + } + return null; +} +function extractHeaderEntries(input) { + if (isPlainObject4(input)) { + return Object.entries(input); + } + if (!Array.isArray(input)) { + return []; + } + const entries2 = []; + for (const item of input) { + if (Array.isArray(item)) { + const key = nonEmptyTrimmedString(item[0]); + if (!key) continue; + entries2.push([key, item[1]]); + continue; + } + if (!isPlainObject4(item)) continue; + const mapped = item; + const explicitKey = nonEmptyTrimmedString(mapped.key) ?? nonEmptyTrimmedString(mapped.name) ?? nonEmptyTrimmedString(mapped.header); + if (explicitKey) { + const explicitValue = Object.prototype.hasOwnProperty.call( + mapped, + "value" + ) ? mapped.value : Object.prototype.hasOwnProperty.call(mapped, "token") ? mapped.token : Object.prototype.hasOwnProperty.call(mapped, "secret") ? mapped.secret : mapped; + entries2.push([explicitKey, explicitValue]); + continue; + } + const singleEntry = Object.entries(mapped); + if (singleEntry.length === 1) { + entries2.push(singleEntry[0]); + } + } + return entries2; +} +function normalizeHeaderMap(input) { + const entries2 = extractHeaderEntries(input); + if (entries2.length === 0) return void 0; + const out = {}; + for (const [key, value] of entries2) { + const normalizedValue = normalizeHeaderValue(value); + if (!normalizedValue) continue; + const trimmedKey = key.trim(); + const trimmedValue = normalizedValue.trim(); + if (!trimmedKey || !trimmedValue) continue; + out[trimmedKey] = trimmedValue; + } + return Object.keys(out).length > 0 ? out : void 0; +} +function nonEmptyTrimmedString(value) { + if (typeof value !== "string") return null; + const trimmed = value.trim(); + return trimmed.length > 0 ? trimmed : null; +} +function headerMapHasKeyIgnoreCase(headers, targetKey) { + const normalizedTarget = targetKey.trim().toLowerCase(); + return Object.keys(headers).some( + (key) => key.trim().toLowerCase() === normalizedTarget + ); +} +function headerMapGetIgnoreCase3(headers, targetKey) { + const normalizedTarget = targetKey.trim().toLowerCase(); + const key = Object.keys(headers).find( + (candidate) => candidate.trim().toLowerCase() === normalizedTarget + ); + if (!key) return null; + const value = headers[key]; + return typeof value === "string" ? value : null; +} +function tokenFromAuthorizationHeader(rawHeader) { + const trimmed = nonEmptyTrimmedString(rawHeader); + if (!trimmed) return null; + const bearerMatch = trimmed.match(/^bearer\s+(.+)$/i); + if (bearerMatch?.[1]) { + return nonEmptyTrimmedString(bearerMatch[1]); + } + return trimmed; +} +function parseBooleanLike(value) { + if (typeof value === "boolean") return value; + if (typeof value !== "string") return null; + const normalized = value.trim().toLowerCase(); + if (normalized === "true" || normalized === "1") return true; + if (normalized === "false" || normalized === "0") return false; + return null; +} +function generateEd25519PrivateKeyPem() { + const generated = generateKeyPairSync2("ed25519"); + return generated.privateKey.export({ type: "pkcs8", format: "pem" }).toString(); +} +function buildJoinDefaultsPayloadForAccept(input) { + if (input.adapterType !== "openclaw_gateway") { + return input.defaultsPayload; + } + const merged = isPlainObject4(input.defaultsPayload) ? { ...input.defaultsPayload } : {}; + if (!nonEmptyTrimmedString(merged.taskcoreApiUrl)) { + const legacyTaskcoreApiUrl = nonEmptyTrimmedString(input.taskcoreApiUrl); + if (legacyTaskcoreApiUrl) merged.taskcoreApiUrl = legacyTaskcoreApiUrl; + } + const mergedHeaders = normalizeHeaderMap(merged.headers) ?? {}; + const inboundOpenClawAuthHeader = nonEmptyTrimmedString( + input.inboundOpenClawAuthHeader + ); + const inboundOpenClawTokenHeader = nonEmptyTrimmedString( + input.inboundOpenClawTokenHeader + ); + if (inboundOpenClawTokenHeader && !headerMapHasKeyIgnoreCase(mergedHeaders, "x-openclaw-token")) { + mergedHeaders["x-openclaw-token"] = inboundOpenClawTokenHeader; + } + if (inboundOpenClawAuthHeader && !headerMapHasKeyIgnoreCase(mergedHeaders, "x-openclaw-auth")) { + mergedHeaders["x-openclaw-auth"] = inboundOpenClawAuthHeader; + } + if (Object.keys(mergedHeaders).length > 0) { + merged.headers = mergedHeaders; + } else { + delete merged.headers; + } + const discoveredToken = headerMapGetIgnoreCase3(mergedHeaders, "x-openclaw-token") ?? headerMapGetIgnoreCase3(mergedHeaders, "x-openclaw-auth") ?? tokenFromAuthorizationHeader( + headerMapGetIgnoreCase3(mergedHeaders, "authorization") + ); + if (discoveredToken && !headerMapHasKeyIgnoreCase(mergedHeaders, "x-openclaw-token")) { + mergedHeaders["x-openclaw-token"] = discoveredToken; + } + return Object.keys(merged).length > 0 ? merged : null; +} +function mergeJoinDefaultsPayloadForReplay(existingDefaultsPayload, nextDefaultsPayload) { + if (!isPlainObject4(existingDefaultsPayload) && !isPlainObject4(nextDefaultsPayload)) { + return nextDefaultsPayload ?? existingDefaultsPayload; + } + if (!isPlainObject4(existingDefaultsPayload)) { + return nextDefaultsPayload; + } + if (!isPlainObject4(nextDefaultsPayload)) { + return existingDefaultsPayload; + } + const merged = { + ...existingDefaultsPayload, + ...nextDefaultsPayload + }; + const existingHeaders = normalizeHeaderMap( + existingDefaultsPayload.headers + ); + const nextHeaders = normalizeHeaderMap( + nextDefaultsPayload.headers + ); + if (existingHeaders || nextHeaders) { + merged.headers = { + ...existingHeaders ?? {}, + ...nextHeaders ?? {} + }; + } else if (Object.prototype.hasOwnProperty.call(merged, "headers")) { + delete merged.headers; + } + return merged; +} +function canReplayOpenClawGatewayInviteAccept(input) { + if (input.requestType !== "agent" || input.adapterType !== "openclaw_gateway") { + return false; + } + if (!input.existingJoinRequest) { + return false; + } + if (input.existingJoinRequest.requestType !== "agent" || input.existingJoinRequest.adapterType !== "openclaw_gateway") { + return false; + } + return input.existingJoinRequest.status === "pending_approval" || input.existingJoinRequest.status === "approved"; +} +function summarizeSecretForLog(value) { + const trimmed = nonEmptyTrimmedString(value); + if (!trimmed) return null; + return { + present: true, + length: trimmed.length, + sha256Prefix: hashToken3(trimmed).slice(0, 12) + }; +} +function summarizeOpenClawGatewayDefaultsForLog(defaultsPayload) { + const defaults = isPlainObject4(defaultsPayload) ? defaultsPayload : null; + const headers = defaults ? normalizeHeaderMap(defaults.headers) : void 0; + const gatewayTokenValue = headers ? headerMapGetIgnoreCase3(headers, "x-openclaw-token") ?? headerMapGetIgnoreCase3(headers, "x-openclaw-auth") ?? tokenFromAuthorizationHeader( + headerMapGetIgnoreCase3(headers, "authorization") + ) : null; + return { + present: Boolean(defaults), + keys: defaults ? Object.keys(defaults).sort() : [], + url: defaults ? nonEmptyTrimmedString(defaults.url) : null, + taskcoreApiUrl: defaults ? nonEmptyTrimmedString(defaults.taskcoreApiUrl) : null, + headerKeys: headers ? Object.keys(headers).sort() : [], + sessionKeyStrategy: defaults ? nonEmptyTrimmedString(defaults.sessionKeyStrategy) : null, + disableDeviceAuth: defaults ? parseBooleanLike(defaults.disableDeviceAuth) : null, + waitTimeoutMs: defaults && typeof defaults.waitTimeoutMs === "number" ? defaults.waitTimeoutMs : null, + devicePrivateKeyPem: defaults ? summarizeSecretForLog(defaults.devicePrivateKeyPem) : null, + gatewayToken: summarizeSecretForLog(gatewayTokenValue) + }; +} +function normalizeAgentDefaultsForJoin(input) { + const fatalErrors = []; + const diagnostics = []; + if (input.adapterType !== "openclaw_gateway") { + const normalized2 = isPlainObject4(input.defaultsPayload) ? input.defaultsPayload : null; + return { normalized: normalized2, diagnostics, fatalErrors }; + } + if (!isPlainObject4(input.defaultsPayload)) { + diagnostics.push({ + code: "openclaw_gateway_defaults_missing", + level: "warn", + message: "No OpenClaw gateway config was provided in agentDefaultsPayload.", + hint: "Include agentDefaultsPayload.url and headers.x-openclaw-token for OpenClaw gateway joins." + }); + fatalErrors.push( + "agentDefaultsPayload is required for adapterType=openclaw_gateway" + ); + return { + normalized: null, + diagnostics, + fatalErrors + }; + } + const defaults = input.defaultsPayload; + const normalized = {}; + let gatewayUrl = null; + const rawGatewayUrl = nonEmptyTrimmedString(defaults.url); + if (!rawGatewayUrl) { + diagnostics.push({ + code: "openclaw_gateway_url_missing", + level: "warn", + message: "OpenClaw gateway URL is missing.", + hint: "Set agentDefaultsPayload.url to ws:// or wss:// gateway URL." + }); + fatalErrors.push("agentDefaultsPayload.url is required"); + } else { + try { + gatewayUrl = new URL(rawGatewayUrl); + if (gatewayUrl.protocol !== "ws:" && gatewayUrl.protocol !== "wss:") { + diagnostics.push({ + code: "openclaw_gateway_url_protocol", + level: "warn", + message: `OpenClaw gateway URL must use ws:// or wss:// (got ${gatewayUrl.protocol}).` + }); + fatalErrors.push( + "agentDefaultsPayload.url must use ws:// or wss:// for openclaw_gateway" + ); + } else { + normalized.url = gatewayUrl.toString(); + diagnostics.push({ + code: "openclaw_gateway_url_configured", + level: "info", + message: `Gateway endpoint set to ${gatewayUrl.toString()}` + }); + } + } catch { + diagnostics.push({ + code: "openclaw_gateway_url_invalid", + level: "warn", + message: `Invalid OpenClaw gateway URL: ${rawGatewayUrl}` + }); + fatalErrors.push("agentDefaultsPayload.url is not a valid URL"); + } + } + const headers = normalizeHeaderMap(defaults.headers) ?? {}; + const gatewayToken = headerMapGetIgnoreCase3(headers, "x-openclaw-token") ?? headerMapGetIgnoreCase3(headers, "x-openclaw-auth") ?? tokenFromAuthorizationHeader(headerMapGetIgnoreCase3(headers, "authorization")); + if (gatewayToken && !headerMapHasKeyIgnoreCase(headers, "x-openclaw-token")) { + headers["x-openclaw-token"] = gatewayToken; + } + if (Object.keys(headers).length > 0) { + normalized.headers = headers; + } + if (!gatewayToken) { + diagnostics.push({ + code: "openclaw_gateway_auth_header_missing", + level: "warn", + message: "Gateway auth token is missing from agent defaults.", + hint: "Set agentDefaultsPayload.headers.x-openclaw-token (or legacy x-openclaw-auth)." + }); + fatalErrors.push( + "agentDefaultsPayload.headers.x-openclaw-token (or x-openclaw-auth) is required" + ); + } else if (gatewayToken.trim().length < 16) { + diagnostics.push({ + code: "openclaw_gateway_auth_header_too_short", + level: "warn", + message: `Gateway auth token appears too short (${gatewayToken.trim().length} chars).`, + hint: "Use the full gateway auth token from ~/.openclaw/openclaw.json (typically long random string)." + }); + fatalErrors.push( + "agentDefaultsPayload.headers.x-openclaw-token is too short; expected a full gateway token" + ); + } else { + diagnostics.push({ + code: "openclaw_gateway_auth_header_configured", + level: "info", + message: "Gateway auth token configured." + }); + } + if (isPlainObject4(defaults.payloadTemplate)) { + normalized.payloadTemplate = defaults.payloadTemplate; + } + const parsedDisableDeviceAuth = parseBooleanLike(defaults.disableDeviceAuth); + const disableDeviceAuth = parsedDisableDeviceAuth === true; + if (parsedDisableDeviceAuth !== null) { + normalized.disableDeviceAuth = parsedDisableDeviceAuth; + } + const configuredDevicePrivateKeyPem = nonEmptyTrimmedString( + defaults.devicePrivateKeyPem + ); + if (configuredDevicePrivateKeyPem) { + normalized.devicePrivateKeyPem = configuredDevicePrivateKeyPem; + diagnostics.push({ + code: "openclaw_gateway_device_key_configured", + level: "info", + message: "Gateway device key configured. Pairing approvals should persist for this agent." + }); + } else if (!disableDeviceAuth) { + try { + normalized.devicePrivateKeyPem = generateEd25519PrivateKeyPem(); + diagnostics.push({ + code: "openclaw_gateway_device_key_generated", + level: "info", + message: "Generated persistent gateway device key for this join. Pairing approvals should persist for this agent." + }); + } catch (err) { + diagnostics.push({ + code: "openclaw_gateway_device_key_generate_failed", + level: "warn", + message: `Failed to generate gateway device key: ${err instanceof Error ? err.message : String(err)}`, + hint: "Set agentDefaultsPayload.devicePrivateKeyPem explicitly or set disableDeviceAuth=true." + }); + fatalErrors.push( + "Failed to generate gateway device key. Set devicePrivateKeyPem or disableDeviceAuth=true." + ); + } + } + const waitTimeoutMs = typeof defaults.waitTimeoutMs === "number" && Number.isFinite(defaults.waitTimeoutMs) ? Math.floor(defaults.waitTimeoutMs) : typeof defaults.waitTimeoutMs === "string" ? Number.parseInt(defaults.waitTimeoutMs.trim(), 10) : NaN; + if (Number.isFinite(waitTimeoutMs) && waitTimeoutMs > 0) { + normalized.waitTimeoutMs = waitTimeoutMs; + } + const timeoutSec = typeof defaults.timeoutSec === "number" && Number.isFinite(defaults.timeoutSec) ? Math.floor(defaults.timeoutSec) : typeof defaults.timeoutSec === "string" ? Number.parseInt(defaults.timeoutSec.trim(), 10) : NaN; + if (Number.isFinite(timeoutSec) && timeoutSec > 0) { + normalized.timeoutSec = timeoutSec; + } + const sessionKeyStrategy = nonEmptyTrimmedString(defaults.sessionKeyStrategy); + if (sessionKeyStrategy === "fixed" || sessionKeyStrategy === "issue" || sessionKeyStrategy === "run") { + normalized.sessionKeyStrategy = sessionKeyStrategy; + } + const sessionKey = nonEmptyTrimmedString(defaults.sessionKey); + if (sessionKey) { + normalized.sessionKey = sessionKey; + } + const role = nonEmptyTrimmedString(defaults.role); + if (role) { + normalized.role = role; + } + if (Array.isArray(defaults.scopes)) { + const scopes = defaults.scopes.filter((entry) => typeof entry === "string").map((entry) => entry.trim()).filter(Boolean); + if (scopes.length > 0) { + normalized.scopes = scopes; + } + } + const rawTaskcoreApiUrl = typeof defaults.taskcoreApiUrl === "string" ? defaults.taskcoreApiUrl.trim() : ""; + if (rawTaskcoreApiUrl) { + try { + const parsedTaskcoreApiUrl = new URL(rawTaskcoreApiUrl); + if (parsedTaskcoreApiUrl.protocol !== "http:" && parsedTaskcoreApiUrl.protocol !== "https:") { + diagnostics.push({ + code: "openclaw_gateway_taskcore_api_url_protocol", + level: "warn", + message: `taskcoreApiUrl must use http:// or https:// (got ${parsedTaskcoreApiUrl.protocol}).` + }); + } else { + normalized.taskcoreApiUrl = parsedTaskcoreApiUrl.toString(); + diagnostics.push({ + code: "openclaw_gateway_taskcore_api_url_configured", + level: "info", + message: `taskcoreApiUrl set to ${parsedTaskcoreApiUrl.toString()}` + }); + } + } catch { + diagnostics.push({ + code: "openclaw_gateway_taskcore_api_url_invalid", + level: "warn", + message: `Invalid taskcoreApiUrl: ${rawTaskcoreApiUrl}` + }); + } + } + return { normalized, diagnostics, fatalErrors }; +} +function toInviteSummaryResponse(req, token, invite, companyName = null) { + const baseUrl = requestBaseUrl(req); + const onboardingPath = `/api/invites/${token}/onboarding`; + const onboardingTextPath = `/api/invites/${token}/onboarding.txt`; + const inviteMessage = extractInviteMessage(invite); + return { + id: invite.id, + companyId: invite.companyId, + companyName, + inviteType: invite.inviteType, + allowedJoinTypes: invite.allowedJoinTypes, + expiresAt: invite.expiresAt, + onboardingPath, + onboardingUrl: baseUrl ? `${baseUrl}${onboardingPath}` : onboardingPath, + onboardingTextPath, + onboardingTextUrl: baseUrl ? `${baseUrl}${onboardingTextPath}` : onboardingTextPath, + skillIndexPath: "/api/skills/index", + skillIndexUrl: baseUrl ? `${baseUrl}/api/skills/index` : "/api/skills/index", + inviteMessage + }; +} +function buildOnboardingDiscoveryDiagnostics(input) { + const diagnostics = []; + let apiHost = null; + if (input.apiBaseUrl) { + try { + apiHost = normalizeHostname(new URL(input.apiBaseUrl).hostname); + } catch { + apiHost = null; + } + } + const bindHost = normalizeHostname(input.bindHost); + const allowSet = new Set( + input.allowedHostnames.map((entry) => normalizeHostname(entry)).filter((entry) => Boolean(entry)) + ); + if (apiHost && isLoopbackHost5(apiHost)) { + diagnostics.push({ + code: "openclaw_onboarding_api_loopback", + level: "warn", + message: "Onboarding URL resolves to loopback hostname. Remote OpenClaw agents cannot reach localhost on your Taskcore host.", + hint: "Use a reachable hostname/IP (for example Tailscale hostname, Docker host alias, or public domain)." + }); + } + if (input.deploymentMode === "authenticated" && input.deploymentExposure === "private" && (!bindHost || isLoopbackHost5(bindHost))) { + diagnostics.push({ + code: "openclaw_onboarding_private_loopback_bind", + level: "warn", + message: "Taskcore is bound to loopback in authenticated/private mode.", + hint: "Use a reachable private bind mode such as `pnpm dev --bind lan` or `pnpm dev --bind tailnet` for private-network onboarding." + }); + } + if (input.deploymentMode === "authenticated" && input.deploymentExposure === "private" && apiHost && !isLoopbackHost5(apiHost) && allowSet.size > 0 && !allowSet.has(apiHost)) { + diagnostics.push({ + code: "openclaw_onboarding_private_host_not_allowed", + level: "warn", + message: `Onboarding host "${apiHost}" is not in allowed hostnames for authenticated/private mode.`, + hint: `Run pnpm taskcore allowed-hostname ${apiHost}` + }); + } + return diagnostics; +} +function buildOnboardingConnectionCandidates(input) { + let base = null; + try { + if (input.apiBaseUrl) { + base = new URL(input.apiBaseUrl); + } + } catch { + base = null; + } + const protocol = base?.protocol ?? "http:"; + const port = base?.port ? `:${base.port}` : ""; + const candidates = /* @__PURE__ */ new Set(); + if (base) { + candidates.add(base.origin); + } + const bindHost = normalizeHostname(input.bindHost); + if (bindHost && !isLoopbackHost5(bindHost)) { + candidates.add(`${protocol}//${bindHost}${port}`); + } + for (const rawHost of input.allowedHostnames) { + const host = normalizeHostname(rawHost); + if (!host) continue; + candidates.add(`${protocol}//${host}${port}`); + } + if (base && isLoopbackHost5(base.hostname)) { + candidates.add(`${protocol}//host.docker.internal${port}`); + } + return Array.from(candidates); +} +function buildInviteOnboardingManifest(req, token, invite, opts) { + const baseUrl = requestBaseUrl(req); + const skillPath = "/api/skills/taskcore"; + const skillUrl = baseUrl ? `${baseUrl}${skillPath}` : skillPath; + const registrationEndpointPath = `/api/invites/${token}/accept`; + const registrationEndpointUrl = baseUrl ? `${baseUrl}${registrationEndpointPath}` : registrationEndpointPath; + const onboardingTextPath = `/api/invites/${token}/onboarding.txt`; + const onboardingTextUrl = baseUrl ? `${baseUrl}${onboardingTextPath}` : onboardingTextPath; + const discoveryDiagnostics = buildOnboardingDiscoveryDiagnostics({ + apiBaseUrl: baseUrl, + deploymentMode: opts.deploymentMode, + deploymentExposure: opts.deploymentExposure, + bindHost: opts.bindHost, + allowedHostnames: opts.allowedHostnames + }); + const connectionCandidates = buildOnboardingConnectionCandidates({ + apiBaseUrl: baseUrl, + bindHost: opts.bindHost, + allowedHostnames: opts.allowedHostnames + }); + return { + invite: toInviteSummaryResponse( + req, + token, + invite, + opts.companyName ?? null + ), + onboarding: { + instructions: "Join as an OpenClaw Gateway agent, save your one-time claim secret, wait for board approval, then claim your API key. Save the claim response token to ~/.openclaw/workspace/taskcore-claimed-api-key.json and load TASKCORE_API_KEY from that file before starting heartbeat loops. You MUST submit adapterType='openclaw_gateway', set agentDefaultsPayload.url to your ws:// or wss:// OpenClaw gateway endpoint, and include agentDefaultsPayload.headers.x-openclaw-token (or legacy x-openclaw-auth).", + inviteMessage: extractInviteMessage(invite), + recommendedAdapterType: "openclaw_gateway", + requiredFields: { + requestType: "agent", + agentName: "Display name for this agent", + adapterType: "Use 'openclaw_gateway' for OpenClaw Gateway agents", + capabilities: "Optional capability summary", + agentDefaultsPayload: "Adapter config for OpenClaw gateway. MUST include url (ws:// or wss://) and headers.x-openclaw-token (or legacy x-openclaw-auth). Optional fields: taskcoreApiUrl, waitTimeoutMs, sessionKeyStrategy, sessionKey, role, scopes, disableDeviceAuth, devicePrivateKeyPem." + }, + registrationEndpoint: { + method: "POST", + path: registrationEndpointPath, + url: registrationEndpointUrl + }, + claimEndpointTemplate: { + method: "POST", + path: "/api/join-requests/{requestId}/claim-api-key", + body: { + claimSecret: "one-time claim secret returned when the join request is created" + } + }, + connectivity: { + deploymentMode: opts.deploymentMode, + deploymentExposure: opts.deploymentExposure, + bindHost: opts.bindHost, + allowedHostnames: opts.allowedHostnames, + connectionCandidates, + diagnostics: discoveryDiagnostics, + guidance: opts.deploymentMode === "authenticated" && opts.deploymentExposure === "private" ? "If OpenClaw runs on another machine, ensure the Taskcore hostname is reachable and allowed via `pnpm taskcore allowed-hostname `." : "Ensure OpenClaw can reach this Taskcore API base URL for invite, claim, and skill bootstrap calls." + }, + textInstructions: { + path: onboardingTextPath, + url: onboardingTextUrl, + contentType: "text/plain" + }, + skill: { + name: "taskcore", + path: skillPath, + url: skillUrl, + installPath: "~/.openclaw/skills/taskcore/SKILL.md" + } + } + }; +} +function buildInviteOnboardingTextDocument(req, token, invite, opts) { + const manifest = buildInviteOnboardingManifest(req, token, invite, opts); + const onboarding = manifest.onboarding; + const diagnostics = Array.isArray(onboarding.connectivity?.diagnostics) ? onboarding.connectivity.diagnostics : []; + const lines = []; + const appendBlock = (block) => { + const trimmed = block.replace(/^\n/, "").replace(/\n\s*$/, ""); + const lineIndentation = trimmed.split("\n").filter((line3) => line3.trim().length > 0).map((line3) => line3.match(/^(\s*)/)?.[0].length ?? 0); + const minIndent = lineIndentation.length > 0 ? Math.min(...lineIndentation) : 0; + for (const line3 of trimmed.split("\n")) { + lines.push(line3.slice(minIndent)); + } + }; + appendBlock(` + # Taskcore OpenClaw Gateway Onboarding + + This document is meant to be readable by both humans and agents. + + ## Invite + - inviteType: ${invite.inviteType} + - allowedJoinTypes: ${invite.allowedJoinTypes} + - expiresAt: ${invite.expiresAt.toISOString()} + `); + if (manifest.invite.companyName) { + lines.push(`- companyName: ${manifest.invite.companyName}`); + } + if (onboarding.inviteMessage) { + appendBlock(` + ## Message from inviter + ${onboarding.inviteMessage} + `); + } + appendBlock(` + ## Step 0 + + Get the OpenClaw gateway auth token (THIS MUST BE SENT) + Token lives in: + + ~/.openclaw/openclaw.json -> gateway.auth.token + Extract: + + TOKEN="$(node -p 'require(process.env.HOME+"/.openclaw/openclaw.json").gateway.auth.token')" + test -n "$TOKEN" || (echo "Missing TOKEN" && exit 1) + test "\${#TOKEN}" -ge 16 || (echo "Gateway token unexpectedly short (\${#TOKEN})" && exit 1) + + 3) IMPORTANT: Don't accidentally drop the token when generating JSON + If you build JSON with Node, pass the token explicitly (argv), don't rely on an un-exported env var. + + Safe payload build looks sort of like this (substitute where necessary): + + BODY="$(node -e ' + const token = process.argv[1]; + if (!token) process.exit(2); + const body = { + requestType: "agent", + agentName: "OpenClaw", + adapterType: "openclaw_gateway", + capabilities: "OpenClaw agent adapter", + agentDefaultsPayload: { + url: "ws://127.0.0.1:18789", + taskcoreApiUrl: "http://host.docker.internal:3100", + headers: { "x-openclaw-token": token }, + waitTimeoutMs: 120000, + sessionKeyStrategy: "issue", + role: "operator", + scopes: ["operator.admin"] + } + }; + process.stdout.write(JSON.stringify(body)); + ' "$TOKEN")" + + ## Step 1: Submit agent join request + ${onboarding.registrationEndpoint.method} ${onboarding.registrationEndpoint.url} + + IMPORTANT: You MUST include agentDefaultsPayload.headers.x-openclaw-token with your gateway token. + Legacy x-openclaw-auth is also accepted, but x-openclaw-token is preferred. + Use adapterType "openclaw_gateway" and a ws:// or wss:// gateway URL. + Pairing mode requirement: + - Keep device auth enabled (recommended). If devicePrivateKeyPem is omitted, Taskcore generates and persists one during join so pairing approvals are stable. + - You may set disableDeviceAuth=true only for special environments that cannot support pairing. + - First run may return "pairing required" once; approve the pending pairing request in OpenClaw, then retry. + Do NOT use /v1/responses or /hooks/* in this gateway join flow. + + Body (JSON): + { + "requestType": "agent", + "agentName": "My OpenClaw Agent", + "adapterType": "openclaw_gateway", + "capabilities": "Optional summary", + "agentDefaultsPayload": { + "url": "wss://your-openclaw-gateway.example", + "taskcoreApiUrl": "https://taskcore-hostname-your-agent-can-reach:3100", + "headers": { "x-openclaw-token": "replace-me" }, + "waitTimeoutMs": 120000, + "sessionKeyStrategy": "issue", + "role": "operator", + "scopes": ["operator.admin"] + } + } + + Expected response includes: + - request id + - one-time claimSecret + - claimApiKeyPath + + ## Step 2: Wait for board approval + The board approves the join request in Taskcore before key claim is allowed. + + ## Step 3: Claim API key (one-time) + ${onboarding.claimEndpointTemplate.method} /api/join-requests/{requestId}/claim-api-key + + Body (JSON): + { + "claimSecret": "" + } + + On successful claim, save the full JSON response to: + + - ~/.openclaw/workspace/taskcore-claimed-api-key.json + chmod 600 ~/.openclaw/workspace/taskcore-claimed-api-key.json + + And set the TASKCORE_API_KEY and TASKCORE_API_URL in your environment variables as specified here: + https://docs.openclaw.ai/help/environment + + e.g. + + { + env: { + TASKCORE_API_KEY: "...", + TASKCORE_API_URL: "...", + }, + } + + Then set TASKCORE_API_KEY and TASKCORE_API_URL from the saved token field for every heartbeat run. + + Important: + - claim secrets expire + - claim secrets are single-use + - claim fails before board approval + + ## Step 4: Install Taskcore skill in OpenClaw + GET ${onboarding.skill.url} + Install path: ${onboarding.skill.installPath} + + Be sure to prepend your TASKCORE_API_URL to the top of your skill and note the path to your TASKCORE_API_URL + + ## Text onboarding URL + ${onboarding.textInstructions.url} + + ## Connectivity guidance + ${onboarding.connectivity?.guidance ?? "Ensure Taskcore is reachable from your OpenClaw runtime."} + `); + const connectionCandidates = Array.isArray( + onboarding.connectivity?.connectionCandidates + ) ? onboarding.connectivity.connectionCandidates.filter( + (entry) => Boolean(entry) + ) : []; + if (connectionCandidates.length > 0) { + lines.push("## Suggested Taskcore base URLs to try"); + for (const candidate of connectionCandidates) { + lines.push(`- ${candidate}`); + } + appendBlock(` + + Test each candidate with: + - GET /api/health + - set the first reachable candidate as agentDefaultsPayload.taskcoreApiUrl when submitting your join request + + If none are reachable: ask your human operator for a reachable hostname/address and help them update network configuration. + For authenticated/private mode, they may need: + - pnpm taskcore allowed-hostname + - then restart Taskcore and retry onboarding. + `); + } + if (diagnostics.length > 0) { + lines.push("## Connectivity diagnostics"); + for (const diag of diagnostics) { + lines.push(`- [${diag.level}] ${diag.message}`); + if (diag.hint) lines.push(` hint: ${diag.hint}`); + } + } + appendBlock(` + + ## Helpful endpoints + ${onboarding.registrationEndpoint.path} + ${onboarding.claimEndpointTemplate.path} + ${onboarding.skill.path} + ${manifest.invite.onboardingPath} + `); + return `${lines.join("\n")} +`; +} +function extractInviteMessage(invite) { + const rawDefaults = invite.defaultsPayload; + if (!rawDefaults || typeof rawDefaults !== "object" || Array.isArray(rawDefaults)) { + return null; + } + const rawMessage = rawDefaults.agentMessage; + if (typeof rawMessage !== "string") { + return null; + } + const trimmed = rawMessage.trim(); + return trimmed.length ? trimmed : null; +} +function mergeInviteDefaults(defaultsPayload, agentMessage) { + const merged = defaultsPayload && typeof defaultsPayload === "object" ? { ...defaultsPayload } : {}; + if (agentMessage) { + merged.agentMessage = agentMessage; + } + return Object.keys(merged).length ? merged : null; +} +function requestIp(req) { + const forwarded = req.header("x-forwarded-for"); + if (forwarded) { + const first = forwarded.split(",")[0]?.trim(); + if (first) return first; + } + return req.ip || "unknown"; +} +function inviteExpired(invite) { + return invite.expiresAt.getTime() <= Date.now(); +} +function isLocalImplicit(req) { + return req.actor.type === "board" && req.actor.source === "local_implicit"; +} +async function resolveActorEmail(db, req) { + if (isLocalImplicit(req)) return "local@taskcore.local"; + const userId = req.actor.userId; + if (!userId) return null; + const user = await db.select({ email: authUsers.email }).from(authUsers).where(eq(authUsers.id, userId)).then((rows) => rows[0] ?? null); + return user?.email ?? null; +} +function grantsFromDefaults(defaultsPayload, key) { + if (!defaultsPayload || typeof defaultsPayload !== "object") return []; + const scoped = defaultsPayload[key]; + if (!scoped || typeof scoped !== "object") return []; + const grants = scoped.grants; + if (!Array.isArray(grants)) return []; + const validPermissionKeys = new Set(PERMISSION_KEYS); + const result = []; + for (const item of grants) { + if (!item || typeof item !== "object") continue; + const record2 = item; + if (typeof record2.permissionKey !== "string") continue; + if (!validPermissionKeys.has(record2.permissionKey)) continue; + result.push({ + permissionKey: record2.permissionKey, + scope: record2.scope && typeof record2.scope === "object" && !Array.isArray(record2.scope) ? record2.scope : null + }); + } + return result; +} +function agentJoinGrantsFromDefaults(defaultsPayload) { + const grants = grantsFromDefaults(defaultsPayload, "agent"); + if (grants.some((grant) => grant.permissionKey === "tasks:assign")) { + return grants; + } + return [ + ...grants, + { + permissionKey: "tasks:assign", + scope: null + } + ]; +} +function resolveJoinRequestAgentManagerId(candidates) { + const ceoCandidates = candidates.filter( + (candidate) => candidate.role === "ceo" + ); + if (ceoCandidates.length === 0) return null; + const rootCeo = ceoCandidates.find( + (candidate) => candidate.reportsTo === null + ); + return (rootCeo ?? ceoCandidates[0] ?? null)?.id ?? null; +} +function isInviteTokenHashCollisionError(error50) { + const candidates = [ + error50, + error50?.cause ?? null + ]; + for (const candidate of candidates) { + if (!candidate || typeof candidate !== "object") continue; + const code = "code" in candidate && typeof candidate.code === "string" ? candidate.code : null; + const message2 = "message" in candidate && typeof candidate.message === "string" ? candidate.message : ""; + const constraint = "constraint" in candidate && typeof candidate.constraint === "string" ? candidate.constraint : null; + if (code !== "23505") continue; + if (constraint === "invites_token_hash_unique_idx") return true; + if (message2.includes("invites_token_hash_unique_idx")) return true; + } + return false; +} +function isAbortError(error50) { + return error50 instanceof Error && error50.name === "AbortError"; +} +async function probeInviteResolutionTarget(url2, timeoutMs) { + const startedAt = Date.now(); + const controller = new AbortController(); + const timeout = setTimeout(() => controller.abort(), timeoutMs); + try { + const response = await fetch(url2, { + method: "HEAD", + redirect: "manual", + signal: controller.signal + }); + const durationMs = Date.now() - startedAt; + if (response.ok || response.status === 401 || response.status === 403 || response.status === 404 || response.status === 405 || response.status === 422 || response.status === 500 || response.status === 501) { + return { + status: "reachable", + method: "HEAD", + durationMs, + httpStatus: response.status, + message: `Webhook endpoint responded to HEAD with HTTP ${response.status}.` + }; + } + return { + status: "unreachable", + method: "HEAD", + durationMs, + httpStatus: response.status, + message: `Webhook endpoint probe returned HTTP ${response.status}.` + }; + } catch (error50) { + const durationMs = Date.now() - startedAt; + if (isAbortError(error50)) { + return { + status: "timeout", + method: "HEAD", + durationMs, + httpStatus: null, + message: `Webhook endpoint probe timed out after ${timeoutMs}ms.` + }; + } + return { + status: "unreachable", + method: "HEAD", + durationMs, + httpStatus: null, + message: error50 instanceof Error ? error50.message : "Webhook endpoint probe failed." + }; + } finally { + clearTimeout(timeout); + } +} +function accessRoutes(db, opts) { + const router2 = (0, import_express21.Router)(); + const access = accessService(db); + const boardAuth = boardAuthService(db); + const agents2 = agentService(db); + async function assertInstanceAdmin2(req) { + if (req.actor.type !== "board") throw unauthorized(); + if (isLocalImplicit(req)) return; + const allowed2 = await access.isInstanceAdmin(req.actor.userId); + if (!allowed2) throw forbidden("Instance admin required"); + } + router2.get("/board-claim/:token", async (req, res) => { + const token = req.params.token.trim(); + const code = typeof req.query.code === "string" ? req.query.code.trim() : void 0; + if (!token) throw notFound("Board claim challenge not found"); + const challenge = inspectBoardClaimChallenge(token, code); + if (challenge.status === "invalid") + throw notFound("Board claim challenge not found"); + res.json(challenge); + }); + router2.post("/board-claim/:token/claim", async (req, res) => { + const token = req.params.token.trim(); + const code = typeof req.body?.code === "string" ? req.body.code.trim() : void 0; + if (!token) throw notFound("Board claim challenge not found"); + if (!code) throw badRequest("Claim code is required"); + if (req.actor.type !== "board" || req.actor.source !== "session" || !req.actor.userId) { + throw unauthorized("Sign in before claiming board ownership"); + } + const claimed = await claimBoardOwnership(db, { + token, + code, + userId: req.actor.userId + }); + if (claimed.status === "invalid") + throw notFound("Board claim challenge not found"); + if (claimed.status === "expired") + throw conflict( + "Board claim challenge expired. Restart server to generate a new one." + ); + if (claimed.status === "claimed") { + res.json({ + claimed: true, + userId: claimed.claimedByUserId ?? req.actor.userId + }); + return; + } + throw conflict("Board claim challenge is no longer available"); + }); + router2.post( + "/cli-auth/challenges", + validate(createCliAuthChallengeSchema), + async (req, res) => { + const created = await boardAuth.createCliAuthChallenge(req.body); + const approvalPath = buildCliAuthApprovalPath( + created.challenge.id, + created.challengeSecret + ); + const baseUrl = requestBaseUrl(req); + res.status(201).json({ + id: created.challenge.id, + token: created.challengeSecret, + boardApiToken: created.pendingBoardToken, + approvalPath, + approvalUrl: baseUrl ? `${baseUrl}${approvalPath}` : null, + pollPath: `/cli-auth/challenges/${created.challenge.id}`, + expiresAt: created.challenge.expiresAt.toISOString(), + suggestedPollIntervalMs: 1e3 + }); + } + ); + router2.get("/cli-auth/challenges/:id", async (req, res) => { + const id = req.params.id.trim(); + const token = typeof req.query.token === "string" ? req.query.token.trim() : ""; + if (!id || !token) throw notFound("CLI auth challenge not found"); + const challenge = await boardAuth.describeCliAuthChallenge(id, token); + if (!challenge) throw notFound("CLI auth challenge not found"); + const isSignedInBoardUser = req.actor.type === "board" && (req.actor.source === "session" || isLocalImplicit(req)) && Boolean(req.actor.userId); + const canApprove = isSignedInBoardUser && (challenge.requestedAccess !== "instance_admin_required" || isLocalImplicit(req) || Boolean(req.actor.isInstanceAdmin)); + res.json({ + ...challenge, + requiresSignIn: !isSignedInBoardUser, + canApprove, + currentUserId: req.actor.type === "board" ? req.actor.userId ?? null : null + }); + }); + router2.post( + "/cli-auth/challenges/:id/approve", + validate(resolveCliAuthChallengeSchema), + async (req, res) => { + const id = req.params.id.trim(); + if (req.actor.type !== "board" || !req.actor.userId && !isLocalImplicit(req)) { + throw unauthorized("Sign in before approving CLI access"); + } + const userId = req.actor.userId ?? "local-board"; + const approved = await boardAuth.approveCliAuthChallenge( + id, + req.body.token, + userId + ); + if (approved.status === "approved") { + const companyIds = await boardAuth.resolveBoardActivityCompanyIds({ + userId, + requestedCompanyId: approved.challenge.requestedCompanyId, + boardApiKeyId: approved.challenge.boardApiKeyId + }); + for (const companyId of companyIds) { + await logActivity(db, { + companyId, + actorType: "user", + actorId: userId, + action: "board_api_key.created", + entityType: "user", + entityId: userId, + details: { + boardApiKeyId: approved.challenge.boardApiKeyId, + requestedAccess: approved.challenge.requestedAccess, + requestedCompanyId: approved.challenge.requestedCompanyId, + challengeId: approved.challenge.id + } + }); + } + } + res.json({ + approved: approved.status === "approved", + status: approved.status, + userId, + keyId: approved.challenge.boardApiKeyId ?? null, + expiresAt: approved.challenge.expiresAt.toISOString() + }); + } + ); + router2.post( + "/cli-auth/challenges/:id/cancel", + validate(resolveCliAuthChallengeSchema), + async (req, res) => { + const id = req.params.id.trim(); + const cancelled = await boardAuth.cancelCliAuthChallenge(id, req.body.token); + res.json({ + status: cancelled.status, + cancelled: cancelled.status === "cancelled" + }); + } + ); + router2.get("/cli-auth/me", async (req, res) => { + if (req.actor.type !== "board" || !req.actor.userId) { + throw unauthorized("Board authentication required"); + } + const accessSnapshot = await boardAuth.resolveBoardAccess(req.actor.userId); + res.json({ + user: accessSnapshot.user, + userId: req.actor.userId, + isInstanceAdmin: accessSnapshot.isInstanceAdmin, + companyIds: accessSnapshot.companyIds, + source: req.actor.source ?? "none", + keyId: req.actor.source === "board_key" ? req.actor.keyId ?? null : null + }); + }); + router2.post("/cli-auth/revoke-current", async (req, res) => { + if (req.actor.type !== "board" || req.actor.source !== "board_key") { + throw badRequest("Current board API key context is required"); + } + const key = await boardAuth.assertCurrentBoardKey( + req.actor.keyId, + req.actor.userId + ); + await boardAuth.revokeBoardApiKey(key.id); + const companyIds = await boardAuth.resolveBoardActivityCompanyIds({ + userId: key.userId, + boardApiKeyId: key.id + }); + for (const companyId of companyIds) { + await logActivity(db, { + companyId, + actorType: "user", + actorId: key.userId, + action: "board_api_key.revoked", + entityType: "user", + entityId: key.userId, + details: { + boardApiKeyId: key.id, + revokedVia: "cli_auth_logout" + } + }); + } + res.json({ revoked: true, keyId: key.id }); + }); + async function assertCompanyPermission(req, companyId, permissionKey) { + assertCompanyAccess(req, companyId); + if (req.actor.type === "agent") { + if (!req.actor.agentId) throw forbidden(); + const allowed3 = await access.hasPermission( + companyId, + "agent", + req.actor.agentId, + permissionKey + ); + if (!allowed3) throw forbidden("Permission denied"); + return; + } + if (req.actor.type !== "board") throw unauthorized(); + if (isLocalImplicit(req)) return; + const allowed2 = await access.canUser( + companyId, + req.actor.userId, + permissionKey + ); + if (!allowed2) throw forbidden("Permission denied"); + } + async function assertCanGenerateOpenClawInvitePrompt(req, companyId) { + assertCompanyAccess(req, companyId); + if (req.actor.type === "agent") { + if (!req.actor.agentId) throw forbidden("Agent authentication required"); + const actorAgent = await agents2.getById(req.actor.agentId); + if (!actorAgent || actorAgent.companyId !== companyId) { + throw forbidden("Agent key cannot access another company"); + } + if (actorAgent.role !== "ceo") { + throw forbidden("Only CEO agents can generate OpenClaw invite prompts"); + } + return; + } + if (req.actor.type !== "board") throw unauthorized(); + if (isLocalImplicit(req)) return; + const allowed2 = await access.canUser(companyId, req.actor.userId, "users:invite"); + if (!allowed2) throw forbidden("Permission denied"); + } + async function createCompanyInviteForCompany(input) { + const normalizedAgentMessage = typeof input.agentMessage === "string" ? input.agentMessage.trim() || null : null; + const insertValues = { + companyId: input.companyId, + inviteType: "company_join", + allowedJoinTypes: input.allowedJoinTypes, + defaultsPayload: mergeInviteDefaults( + input.defaultsPayload ?? null, + normalizedAgentMessage + ), + expiresAt: companyInviteExpiresAt(), + invitedByUserId: input.req.actor.userId ?? null + }; + let token = null; + let created = null; + for (let attempt = 0; attempt < INVITE_TOKEN_MAX_RETRIES; attempt += 1) { + const candidateToken = createInviteToken(); + try { + const row = await db.insert(invites).values({ + ...insertValues, + tokenHash: hashToken3(candidateToken) + }).returning().then((rows) => rows[0]); + token = candidateToken; + created = row; + break; + } catch (error50) { + if (!isInviteTokenHashCollisionError(error50)) { + throw error50; + } + } + } + if (!token || !created) { + throw conflict("Failed to generate a unique invite token. Please retry."); + } + return { token, created, normalizedAgentMessage }; + } + async function getInviteCompanyName(companyId) { + if (!companyId) return null; + const company = await db.select({ name: companies.name }).from(companies).where(eq(companies.id, companyId)).then((rows) => rows[0] ?? null); + return company?.name ?? null; + } + router2.get("/skills/available", (_req, res) => { + res.json({ skills: listAvailableSkills() }); + }); + router2.get("/skills/index", (_req, res) => { + res.json({ + skills: [ + { name: "taskcore", path: "/api/skills/taskcore" }, + { + name: "para-memory-files", + path: "/api/skills/para-memory-files" + }, + { + name: "taskcore-create-agent", + path: "/api/skills/taskcore-create-agent" + } + ] + }); + }); + router2.get("/skills/:skillName", (req, res) => { + const skillName = req.params.skillName.trim().toLowerCase(); + const markdown = readSkillMarkdown(skillName); + if (!markdown) throw notFound("Skill not found"); + res.type("text/markdown").send(markdown); + }); + router2.post( + "/companies/:companyId/invites", + validate(createCompanyInviteSchema), + async (req, res) => { + const companyId = req.params.companyId; + await assertCompanyPermission(req, companyId, "users:invite"); + const { token, created, normalizedAgentMessage } = await createCompanyInviteForCompany({ + req, + companyId, + allowedJoinTypes: req.body.allowedJoinTypes, + defaultsPayload: req.body.defaultsPayload ?? null, + agentMessage: req.body.agentMessage ?? null + }); + await logActivity(db, { + companyId, + actorType: req.actor.type === "agent" ? "agent" : "user", + actorId: req.actor.type === "agent" ? req.actor.agentId ?? "unknown-agent" : req.actor.userId ?? "board", + action: "invite.created", + entityType: "invite", + entityId: created.id, + details: { + inviteType: created.inviteType, + allowedJoinTypes: created.allowedJoinTypes, + expiresAt: created.expiresAt.toISOString(), + hasAgentMessage: Boolean(normalizedAgentMessage) + } + }); + const companyName = await getInviteCompanyName(created.companyId); + const inviteSummary = toInviteSummaryResponse( + req, + token, + created, + companyName + ); + res.status(201).json({ + ...created, + token, + inviteUrl: `/invite/${token}`, + companyName, + onboardingTextPath: inviteSummary.onboardingTextPath, + onboardingTextUrl: inviteSummary.onboardingTextUrl, + inviteMessage: inviteSummary.inviteMessage + }); + } + ); + router2.post( + "/companies/:companyId/openclaw/invite-prompt", + validate(createOpenClawInvitePromptSchema), + async (req, res) => { + const companyId = req.params.companyId; + await assertCanGenerateOpenClawInvitePrompt(req, companyId); + const { token, created, normalizedAgentMessage } = await createCompanyInviteForCompany({ + req, + companyId, + allowedJoinTypes: "agent", + defaultsPayload: null, + agentMessage: req.body.agentMessage ?? null + }); + await logActivity(db, { + companyId, + actorType: req.actor.type === "agent" ? "agent" : "user", + actorId: req.actor.type === "agent" ? req.actor.agentId ?? "unknown-agent" : req.actor.userId ?? "board", + action: "invite.openclaw_prompt_created", + entityType: "invite", + entityId: created.id, + details: { + inviteType: created.inviteType, + allowedJoinTypes: created.allowedJoinTypes, + expiresAt: created.expiresAt.toISOString(), + hasAgentMessage: Boolean(normalizedAgentMessage) + } + }); + const companyName = await getInviteCompanyName(created.companyId); + const inviteSummary = toInviteSummaryResponse( + req, + token, + created, + companyName + ); + res.status(201).json({ + ...created, + token, + inviteUrl: `/invite/${token}`, + companyName, + onboardingTextPath: inviteSummary.onboardingTextPath, + onboardingTextUrl: inviteSummary.onboardingTextUrl, + inviteMessage: inviteSummary.inviteMessage + }); + } + ); + router2.get("/invites/:token", async (req, res) => { + const token = req.params.token.trim(); + if (!token) throw notFound("Invite not found"); + const invite = await db.select().from(invites).where(eq(invites.tokenHash, hashToken3(token))).then((rows) => rows[0] ?? null); + if (!invite || invite.revokedAt || invite.acceptedAt || inviteExpired(invite)) { + throw notFound("Invite not found"); + } + const companyName = await getInviteCompanyName(invite.companyId); + res.json(toInviteSummaryResponse(req, token, invite, companyName)); + }); + router2.get("/invites/:token/onboarding", async (req, res) => { + const token = req.params.token.trim(); + if (!token) throw notFound("Invite not found"); + const invite = await db.select().from(invites).where(eq(invites.tokenHash, hashToken3(token))).then((rows) => rows[0] ?? null); + if (!invite || invite.revokedAt || inviteExpired(invite)) { + throw notFound("Invite not found"); + } + const companyName = await getInviteCompanyName(invite.companyId); + res.json(buildInviteOnboardingManifest(req, token, invite, { + ...opts, + companyName + })); + }); + router2.get("/invites/:token/onboarding.txt", async (req, res) => { + const token = req.params.token.trim(); + if (!token) throw notFound("Invite not found"); + const invite = await db.select().from(invites).where(eq(invites.tokenHash, hashToken3(token))).then((rows) => rows[0] ?? null); + if (!invite || invite.revokedAt || inviteExpired(invite)) { + throw notFound("Invite not found"); + } + const companyName = await getInviteCompanyName(invite.companyId); + res.type("text/plain; charset=utf-8").send( + buildInviteOnboardingTextDocument(req, token, invite, { + ...opts, + companyName + }) + ); + }); + router2.get("/invites/:token/test-resolution", async (req, res) => { + const token = req.params.token.trim(); + if (!token) throw notFound("Invite not found"); + const invite = await db.select().from(invites).where(eq(invites.tokenHash, hashToken3(token))).then((rows) => rows[0] ?? null); + if (!invite || invite.revokedAt || inviteExpired(invite)) { + throw notFound("Invite not found"); + } + const rawUrl = typeof req.query.url === "string" ? req.query.url.trim() : ""; + if (!rawUrl) throw badRequest("url query parameter is required"); + let target; + try { + target = new URL(rawUrl); + } catch { + throw badRequest("url must be an absolute http(s) URL"); + } + if (target.protocol !== "http:" && target.protocol !== "https:") { + throw badRequest("url must use http or https"); + } + const parsedTimeoutMs = typeof req.query.timeoutMs === "string" ? Number(req.query.timeoutMs) : NaN; + const timeoutMs = Number.isFinite(parsedTimeoutMs) ? Math.max(1e3, Math.min(15e3, Math.floor(parsedTimeoutMs))) : 5e3; + const probe = await probeInviteResolutionTarget(target, timeoutMs); + res.json({ + inviteId: invite.id, + testResolutionPath: `/api/invites/${token}/test-resolution`, + requestedUrl: target.toString(), + timeoutMs, + ...probe + }); + }); + router2.post( + "/invites/:token/accept", + validate(acceptInviteSchema), + async (req, res) => { + const token = req.params.token.trim(); + if (!token) throw notFound("Invite not found"); + const invite = await db.select().from(invites).where(eq(invites.tokenHash, hashToken3(token))).then((rows) => rows[0] ?? null); + if (!invite || invite.revokedAt || inviteExpired(invite)) { + throw notFound("Invite not found"); + } + const inviteAlreadyAccepted = Boolean(invite.acceptedAt); + const existingJoinRequestForInvite = inviteAlreadyAccepted ? await db.select().from(joinRequests).where(eq(joinRequests.inviteId, invite.id)).then((rows) => rows[0] ?? null) : null; + if (invite.inviteType === "bootstrap_ceo") { + if (inviteAlreadyAccepted) throw notFound("Invite not found"); + if (req.body.requestType !== "human") { + throw badRequest("Bootstrap invite requires human request type"); + } + if (req.actor.type !== "board" || !req.actor.userId && !isLocalImplicit(req)) { + throw unauthorized( + "Authenticated user required for bootstrap acceptance" + ); + } + const userId = req.actor.userId ?? "local-board"; + const existingAdmin = await access.isInstanceAdmin(userId); + if (!existingAdmin) { + await access.promoteInstanceAdmin(userId); + } + const updatedInvite = await db.update(invites).set({ acceptedAt: /* @__PURE__ */ new Date(), updatedAt: /* @__PURE__ */ new Date() }).where(eq(invites.id, invite.id)).returning().then((rows) => rows[0] ?? invite); + res.status(202).json({ + inviteId: updatedInvite.id, + inviteType: updatedInvite.inviteType, + bootstrapAccepted: true, + userId + }); + return; + } + const requestType = req.body.requestType; + const companyId = invite.companyId; + if (!companyId) throw conflict("Invite is missing company scope"); + if (invite.allowedJoinTypes !== "both" && invite.allowedJoinTypes !== requestType) { + throw badRequest(`Invite does not allow ${requestType} joins`); + } + if (requestType === "human" && req.actor.type !== "board") { + throw unauthorized( + "Human invite acceptance requires authenticated user" + ); + } + if (requestType === "human" && !req.actor.userId && !isLocalImplicit(req)) { + throw unauthorized("Authenticated user is required"); + } + if (requestType === "agent" && !req.body.agentName) { + if (!inviteAlreadyAccepted || !existingJoinRequestForInvite?.agentName) { + throw badRequest("agentName is required for agent join requests"); + } + } + const adapterType = req.body.adapterType ?? null; + if (inviteAlreadyAccepted && !canReplayOpenClawGatewayInviteAccept({ + requestType, + adapterType, + existingJoinRequest: existingJoinRequestForInvite + })) { + throw notFound("Invite not found"); + } + const replayJoinRequestId = inviteAlreadyAccepted ? existingJoinRequestForInvite?.id ?? null : null; + if (inviteAlreadyAccepted && !replayJoinRequestId) { + throw conflict("Join request not found"); + } + const replayMergedDefaults = inviteAlreadyAccepted ? mergeJoinDefaultsPayloadForReplay( + existingJoinRequestForInvite?.agentDefaultsPayload ?? null, + req.body.agentDefaultsPayload ?? null + ) : req.body.agentDefaultsPayload ?? null; + const gatewayDefaultsPayload = requestType === "agent" ? buildJoinDefaultsPayloadForAccept({ + adapterType, + defaultsPayload: replayMergedDefaults, + taskcoreApiUrl: req.body.taskcoreApiUrl ?? null, + inboundOpenClawAuthHeader: req.header("x-openclaw-auth") ?? null, + inboundOpenClawTokenHeader: req.header("x-openclaw-token") ?? null + }) : null; + const joinDefaults = requestType === "agent" ? normalizeAgentDefaultsForJoin({ + adapterType, + defaultsPayload: gatewayDefaultsPayload, + deploymentMode: opts.deploymentMode, + deploymentExposure: opts.deploymentExposure, + bindHost: opts.bindHost, + allowedHostnames: opts.allowedHostnames + }) : { + normalized: null, + diagnostics: [], + fatalErrors: [] + }; + if (requestType === "agent" && joinDefaults.fatalErrors.length > 0) { + throw badRequest(joinDefaults.fatalErrors.join("; ")); + } + if (requestType === "agent" && adapterType === "openclaw_gateway") { + logger.info( + { + inviteId: invite.id, + joinRequestDiagnostics: joinDefaults.diagnostics.map((diag) => ({ + code: diag.code, + level: diag.level + })), + normalizedAgentDefaults: summarizeOpenClawGatewayDefaultsForLog( + joinDefaults.normalized + ) + }, + "invite accept normalized OpenClaw gateway defaults" + ); + } + const claimSecret = requestType === "agent" && !inviteAlreadyAccepted ? createClaimSecret() : null; + const claimSecretHash = claimSecret ? hashToken3(claimSecret) : null; + const claimSecretExpiresAt = claimSecret ? new Date(Date.now() + 7 * 24 * 60 * 60 * 1e3) : null; + const actorEmail = requestType === "human" ? await resolveActorEmail(db, req) : null; + const created = !inviteAlreadyAccepted ? await db.transaction(async (tx) => { + await tx.update(invites).set({ acceptedAt: /* @__PURE__ */ new Date(), updatedAt: /* @__PURE__ */ new Date() }).where( + and( + eq(invites.id, invite.id), + isNull(invites.acceptedAt), + isNull(invites.revokedAt) + ) + ); + const row = await tx.insert(joinRequests).values({ + inviteId: invite.id, + companyId, + requestType, + status: "pending_approval", + requestIp: requestIp(req), + requestingUserId: requestType === "human" ? req.actor.userId ?? "local-board" : null, + requestEmailSnapshot: requestType === "human" ? actorEmail : null, + agentName: requestType === "agent" ? req.body.agentName : null, + adapterType: requestType === "agent" ? adapterType : null, + capabilities: requestType === "agent" ? req.body.capabilities ?? null : null, + agentDefaultsPayload: requestType === "agent" ? joinDefaults.normalized : null, + claimSecretHash, + claimSecretExpiresAt + }).returning().then((rows) => rows[0]); + return row; + }) : await db.update(joinRequests).set({ + requestIp: requestIp(req), + agentName: requestType === "agent" ? req.body.agentName ?? existingJoinRequestForInvite?.agentName ?? null : null, + capabilities: requestType === "agent" ? req.body.capabilities ?? existingJoinRequestForInvite?.capabilities ?? null : null, + adapterType: requestType === "agent" ? adapterType : null, + agentDefaultsPayload: requestType === "agent" ? joinDefaults.normalized : null, + updatedAt: /* @__PURE__ */ new Date() + }).where(eq(joinRequests.id, replayJoinRequestId)).returning().then((rows) => rows[0]); + if (!created) { + throw conflict("Join request not found"); + } + if (inviteAlreadyAccepted && requestType === "agent" && adapterType === "openclaw_gateway" && created.status === "approved" && created.createdAgentId) { + const existingAgent = await agents2.getById(created.createdAgentId); + if (!existingAgent) { + throw conflict("Approved join request agent not found"); + } + const existingAdapterConfig = isPlainObject4(existingAgent.adapterConfig) ? existingAgent.adapterConfig : {}; + const nextAdapterConfig = { + ...existingAdapterConfig, + ...joinDefaults.normalized ?? {} + }; + const updatedAgent = await agents2.update(created.createdAgentId, { + adapterType, + adapterConfig: nextAdapterConfig + }); + if (!updatedAgent) { + throw conflict("Approved join request agent not found"); + } + await logActivity(db, { + companyId, + actorType: req.actor.type === "agent" ? "agent" : "user", + actorId: req.actor.type === "agent" ? req.actor.agentId ?? "invite-agent" : req.actor.userId ?? "board", + action: "agent.updated_from_join_replay", + entityType: "agent", + entityId: updatedAgent.id, + details: { inviteId: invite.id, joinRequestId: created.id } + }); + } + if (requestType === "agent" && adapterType === "openclaw_gateway") { + const expectedDefaults = summarizeOpenClawGatewayDefaultsForLog( + joinDefaults.normalized + ); + const persistedDefaults = summarizeOpenClawGatewayDefaultsForLog( + created.agentDefaultsPayload + ); + const missingPersistedFields = []; + if (expectedDefaults.url && !persistedDefaults.url) + missingPersistedFields.push("url"); + if (expectedDefaults.taskcoreApiUrl && !persistedDefaults.taskcoreApiUrl) { + missingPersistedFields.push("taskcoreApiUrl"); + } + if (expectedDefaults.gatewayToken && !persistedDefaults.gatewayToken) { + missingPersistedFields.push("headers.x-openclaw-token"); + } + if (expectedDefaults.devicePrivateKeyPem && !persistedDefaults.devicePrivateKeyPem) { + missingPersistedFields.push("devicePrivateKeyPem"); + } + if (expectedDefaults.headerKeys.length > 0 && persistedDefaults.headerKeys.length === 0) { + missingPersistedFields.push("headers"); + } + logger.info( + { + inviteId: invite.id, + joinRequestId: created.id, + joinRequestStatus: created.status, + expectedDefaults, + persistedDefaults, + diagnostics: joinDefaults.diagnostics.map((diag) => ({ + code: diag.code, + level: diag.level, + message: diag.message, + hint: diag.hint ?? null + })) + }, + "invite accept persisted OpenClaw gateway join request" + ); + if (missingPersistedFields.length > 0) { + logger.warn( + { + inviteId: invite.id, + joinRequestId: created.id, + missingPersistedFields + }, + "invite accept detected missing persisted OpenClaw gateway defaults" + ); + } + } + await logActivity(db, { + companyId, + actorType: req.actor.type === "agent" ? "agent" : "user", + actorId: req.actor.type === "agent" ? req.actor.agentId ?? "invite-agent" : req.actor.userId ?? (requestType === "agent" ? "invite-anon" : "board"), + action: inviteAlreadyAccepted ? "join.request_replayed" : "join.requested", + entityType: "join_request", + entityId: created.id, + details: { + requestType, + requestIp: created.requestIp, + inviteReplay: inviteAlreadyAccepted + } + }); + const response = toJoinRequestResponse(created); + if (claimSecret) { + const companyName = await getInviteCompanyName(invite.companyId); + const onboardingManifest = buildInviteOnboardingManifest( + req, + token, + invite, + { + ...opts, + companyName + } + ); + res.status(202).json({ + ...response, + claimSecret, + claimApiKeyPath: `/api/join-requests/${created.id}/claim-api-key`, + onboarding: onboardingManifest.onboarding, + diagnostics: joinDefaults.diagnostics + }); + return; + } + res.status(202).json({ + ...response, + ...joinDefaults.diagnostics.length > 0 ? { diagnostics: joinDefaults.diagnostics } : {} + }); + } + ); + router2.post("/invites/:inviteId/revoke", async (req, res) => { + const id = req.params.inviteId; + const invite = await db.select().from(invites).where(eq(invites.id, id)).then((rows) => rows[0] ?? null); + if (!invite) throw notFound("Invite not found"); + if (invite.inviteType === "bootstrap_ceo") { + await assertInstanceAdmin2(req); + } else { + if (!invite.companyId) throw conflict("Invite is missing company scope"); + await assertCompanyPermission(req, invite.companyId, "users:invite"); + } + if (invite.acceptedAt) throw conflict("Invite already consumed"); + if (invite.revokedAt) return res.json(invite); + const revoked = await db.update(invites).set({ revokedAt: /* @__PURE__ */ new Date(), updatedAt: /* @__PURE__ */ new Date() }).where(eq(invites.id, id)).returning().then((rows) => rows[0]); + if (invite.companyId) { + await logActivity(db, { + companyId: invite.companyId, + actorType: req.actor.type === "agent" ? "agent" : "user", + actorId: req.actor.type === "agent" ? req.actor.agentId ?? "unknown-agent" : req.actor.userId ?? "board", + action: "invite.revoked", + entityType: "invite", + entityId: id + }); + } + res.json(revoked); + }); + router2.get("/companies/:companyId/join-requests", async (req, res) => { + const companyId = req.params.companyId; + await assertCompanyPermission(req, companyId, "joins:approve"); + const query = listJoinRequestsQuerySchema.parse(req.query); + const all = await db.select().from(joinRequests).where(eq(joinRequests.companyId, companyId)).orderBy(desc(joinRequests.createdAt)); + const filtered = all.filter((row) => { + if (query.status && row.status !== query.status) return false; + if (query.requestType && row.requestType !== query.requestType) + return false; + return true; + }); + res.json(filtered.map(toJoinRequestResponse)); + }); + router2.post( + "/companies/:companyId/join-requests/:requestId/approve", + async (req, res) => { + const companyId = req.params.companyId; + const requestId = req.params.requestId; + await assertCompanyPermission(req, companyId, "joins:approve"); + const existing = await db.select().from(joinRequests).where( + and( + eq(joinRequests.companyId, companyId), + eq(joinRequests.id, requestId) + ) + ).then((rows) => rows[0] ?? null); + if (!existing) throw notFound("Join request not found"); + if (existing.status !== "pending_approval") + throw conflict("Join request is not pending"); + const invite = await db.select().from(invites).where(eq(invites.id, existing.inviteId)).then((rows) => rows[0] ?? null); + if (!invite) throw notFound("Invite not found"); + let createdAgentId = existing.createdAgentId ?? null; + if (existing.requestType === "human") { + if (!existing.requestingUserId) + throw conflict("Join request missing user identity"); + await access.ensureMembership( + companyId, + "user", + existing.requestingUserId, + "member", + "active" + ); + const grants = grantsFromDefaults( + invite.defaultsPayload, + "human" + ); + await access.setPrincipalGrants( + companyId, + "user", + existing.requestingUserId, + grants, + req.actor.userId ?? null + ); + } else { + const existingAgents = await agents2.list(companyId); + const managerId = resolveJoinRequestAgentManagerId(existingAgents); + if (!managerId) { + throw conflict( + "Join request cannot be approved because this company has no active CEO" + ); + } + const agentName = deduplicateAgentName( + existing.agentName ?? "New Agent", + existingAgents.map((a5) => ({ + id: a5.id, + name: a5.name, + status: a5.status + })) + ); + const created = await agents2.create(companyId, { + name: agentName, + role: "general", + title: null, + status: "idle", + reportsTo: managerId, + capabilities: existing.capabilities ?? null, + adapterType: existing.adapterType ?? "process", + adapterConfig: existing.agentDefaultsPayload && typeof existing.agentDefaultsPayload === "object" ? existing.agentDefaultsPayload : {}, + runtimeConfig: {}, + budgetMonthlyCents: 0, + spentMonthlyCents: 0, + permissions: {}, + lastHeartbeatAt: null, + metadata: null + }); + createdAgentId = created.id; + await access.ensureMembership( + companyId, + "agent", + created.id, + "member", + "active" + ); + const grants = agentJoinGrantsFromDefaults( + invite.defaultsPayload + ); + await access.setPrincipalGrants( + companyId, + "agent", + created.id, + grants, + req.actor.userId ?? null + ); + } + const approved = await db.update(joinRequests).set({ + status: "approved", + approvedByUserId: req.actor.userId ?? (isLocalImplicit(req) ? "local-board" : null), + approvedAt: /* @__PURE__ */ new Date(), + createdAgentId, + updatedAt: /* @__PURE__ */ new Date() + }).where(eq(joinRequests.id, requestId)).returning().then((rows) => rows[0]); + await logActivity(db, { + companyId, + actorType: "user", + actorId: req.actor.userId ?? "board", + action: "join.approved", + entityType: "join_request", + entityId: requestId, + details: { requestType: existing.requestType, createdAgentId } + }); + if (createdAgentId) { + void notifyHireApproved(db, { + companyId, + agentId: createdAgentId, + source: "join_request", + sourceId: requestId, + approvedAt: /* @__PURE__ */ new Date() + }).catch(() => { + }); + } + res.json(toJoinRequestResponse(approved)); + } + ); + router2.post( + "/companies/:companyId/join-requests/:requestId/reject", + async (req, res) => { + const companyId = req.params.companyId; + const requestId = req.params.requestId; + await assertCompanyPermission(req, companyId, "joins:approve"); + const existing = await db.select().from(joinRequests).where( + and( + eq(joinRequests.companyId, companyId), + eq(joinRequests.id, requestId) + ) + ).then((rows) => rows[0] ?? null); + if (!existing) throw notFound("Join request not found"); + if (existing.status !== "pending_approval") + throw conflict("Join request is not pending"); + const rejected = await db.update(joinRequests).set({ + status: "rejected", + rejectedByUserId: req.actor.userId ?? (isLocalImplicit(req) ? "local-board" : null), + rejectedAt: /* @__PURE__ */ new Date(), + updatedAt: /* @__PURE__ */ new Date() + }).where(eq(joinRequests.id, requestId)).returning().then((rows) => rows[0]); + await logActivity(db, { + companyId, + actorType: "user", + actorId: req.actor.userId ?? "board", + action: "join.rejected", + entityType: "join_request", + entityId: requestId, + details: { requestType: existing.requestType } + }); + res.json(toJoinRequestResponse(rejected)); + } + ); + router2.post( + "/join-requests/:requestId/claim-api-key", + validate(claimJoinRequestApiKeySchema), + async (req, res) => { + const requestId = req.params.requestId; + const presentedClaimSecretHash = hashToken3(req.body.claimSecret); + const joinRequest = await db.select().from(joinRequests).where(eq(joinRequests.id, requestId)).then((rows) => rows[0] ?? null); + if (!joinRequest) throw notFound("Join request not found"); + if (joinRequest.requestType !== "agent") + throw badRequest("Only agent join requests can claim API keys"); + if (joinRequest.status !== "approved") + throw conflict("Join request must be approved before key claim"); + if (!joinRequest.createdAgentId) + throw conflict("Join request has no created agent"); + if (!joinRequest.claimSecretHash) + throw conflict("Join request is missing claim secret metadata"); + if (!tokenHashesMatch2(joinRequest.claimSecretHash, presentedClaimSecretHash)) { + throw forbidden("Invalid claim secret"); + } + if (joinRequest.claimSecretExpiresAt && joinRequest.claimSecretExpiresAt.getTime() <= Date.now()) { + throw conflict("Claim secret expired"); + } + if (joinRequest.claimSecretConsumedAt) + throw conflict("Claim secret already used"); + const existingKey = await db.select({ id: agentApiKeys.id }).from(agentApiKeys).where(eq(agentApiKeys.agentId, joinRequest.createdAgentId)).then((rows) => rows[0] ?? null); + if (existingKey) throw conflict("API key already claimed"); + const consumed = await db.update(joinRequests).set({ claimSecretConsumedAt: /* @__PURE__ */ new Date(), updatedAt: /* @__PURE__ */ new Date() }).where( + and( + eq(joinRequests.id, requestId), + isNull(joinRequests.claimSecretConsumedAt) + ) + ).returning({ id: joinRequests.id }).then((rows) => rows[0] ?? null); + if (!consumed) throw conflict("Claim secret already used"); + const created = await agents2.createApiKey( + joinRequest.createdAgentId, + "initial-join-key" + ); + await logActivity(db, { + companyId: joinRequest.companyId, + actorType: "system", + actorId: "join-claim", + action: "agent_api_key.claimed", + entityType: "agent_api_key", + entityId: created.id, + details: { + agentId: joinRequest.createdAgentId, + joinRequestId: requestId + } + }); + res.status(201).json({ + keyId: created.id, + token: created.token, + agentId: joinRequest.createdAgentId, + createdAt: created.createdAt + }); + } + ); + router2.get("/companies/:companyId/members", async (req, res) => { + const companyId = req.params.companyId; + await assertCompanyPermission(req, companyId, "users:manage_permissions"); + const members = await access.listMembers(companyId); + res.json(members); + }); + router2.patch( + "/companies/:companyId/members/:memberId/permissions", + validate(updateMemberPermissionsSchema), + async (req, res) => { + const companyId = req.params.companyId; + const memberId = req.params.memberId; + await assertCompanyPermission(req, companyId, "users:manage_permissions"); + const updated = await access.setMemberPermissions( + companyId, + memberId, + req.body.grants ?? [], + req.actor.userId ?? null + ); + if (!updated) throw notFound("Member not found"); + res.json(updated); + } + ); + router2.post( + "/admin/users/:userId/promote-instance-admin", + async (req, res) => { + await assertInstanceAdmin2(req); + const userId = req.params.userId; + const result = await access.promoteInstanceAdmin(userId); + res.status(201).json(result); + } + ); + router2.post( + "/admin/users/:userId/demote-instance-admin", + async (req, res) => { + await assertInstanceAdmin2(req); + const userId = req.params.userId; + const removed = await access.demoteInstanceAdmin(userId); + if (!removed) throw notFound("Instance admin role not found"); + res.json(removed); + } + ); + router2.get("/admin/users/:userId/company-access", async (req, res) => { + await assertInstanceAdmin2(req); + const userId = req.params.userId; + const memberships = await access.listUserCompanyAccess(userId); + res.json(memberships); + }); + router2.put( + "/admin/users/:userId/company-access", + validate(updateUserCompanyAccessSchema), + async (req, res) => { + await assertInstanceAdmin2(req); + const userId = req.params.userId; + const memberships = await access.setUserCompanyAccess( + userId, + req.body.companyIds ?? [] + ); + res.json(memberships); + } + ); + return router2; +} + +// server/src/routes/plugins.ts +var import_express22 = __toESM(require_express2(), 1); +init_drizzle_orm(); +init_src2(); +import { existsSync as existsSync6 } from "node:fs"; +import path47 from "node:path"; +import { randomUUID as randomUUID10 } from "node:crypto"; +import { fileURLToPath as fileURLToPath18 } from "node:url"; + +// server/src/services/plugin-registry.ts +init_drizzle_orm(); +init_src2(); +function isPluginKeyConflict(error50) { + if (typeof error50 !== "object" || error50 === null) return false; + const err = error50; + const constraint = err.constraint ?? err.constraint_name; + return err.code === "23505" && constraint === "plugins_plugin_key_idx"; +} +function pluginRegistryService(db) { + async function getById(id) { + return db.select().from(plugins).where(eq(plugins.id, id)).then((rows) => rows[0] ?? null); + } + async function getByKey(pluginKey) { + return db.select().from(plugins).where(eq(plugins.pluginKey, pluginKey)).then((rows) => rows[0] ?? null); + } + async function nextInstallOrder() { + const result = await db.select({ maxOrder: sql`coalesce(max(${plugins.installOrder}), 0)` }).from(plugins); + return (result[0]?.maxOrder ?? 0) + 1; + } + return { + // ----- Read ----------------------------------------------------------- + /** List all registered plugins ordered by install order. */ + list: () => db.select().from(plugins).orderBy(asc(plugins.installOrder)), + /** + * List installed plugins (excludes soft-deleted/uninstalled). + * Use for Plugin Manager and default API list so uninstalled plugins do not appear. + */ + listInstalled: () => db.select().from(plugins).where(ne(plugins.status, "uninstalled")).orderBy(asc(plugins.installOrder)), + /** List plugins filtered by status. */ + listByStatus: (status) => db.select().from(plugins).where(eq(plugins.status, status)).orderBy(asc(plugins.installOrder)), + /** Get a single plugin by primary key. */ + getById, + /** Get a single plugin by its unique `pluginKey`. */ + getByKey, + // ----- Install / Register -------------------------------------------- + /** + * Register (install) a new plugin. + * + * The caller is expected to have already resolved and validated the + * manifest from the package. This method persists the plugin row and + * assigns the next install order. + */ + install: async (input, manifest) => { + const existing = await getByKey(manifest.id); + if (existing) { + if (existing.status !== "uninstalled") { + throw conflict(`Plugin already installed: ${manifest.id}`); + } + return db.update(plugins).set({ + packageName: input.packageName, + packagePath: input.packagePath ?? null, + version: manifest.version, + apiVersion: manifest.apiVersion, + categories: manifest.categories, + manifestJson: manifest, + status: "installed", + lastError: null, + updatedAt: /* @__PURE__ */ new Date() + }).where(eq(plugins.id, existing.id)).returning().then((rows) => rows[0] ?? null); + } + const installOrder = await nextInstallOrder(); + try { + const rows = await db.insert(plugins).values({ + pluginKey: manifest.id, + packageName: input.packageName, + version: manifest.version, + apiVersion: manifest.apiVersion, + categories: manifest.categories, + manifestJson: manifest, + status: "installed", + installOrder, + packagePath: input.packagePath ?? null + }).returning(); + return rows[0]; + } catch (error50) { + if (isPluginKeyConflict(error50)) { + throw conflict(`Plugin already installed: ${manifest.id}`); + } + throw error50; + } + }, + // ----- Update --------------------------------------------------------- + /** + * Update a plugin's manifest and version (e.g. on upgrade). + * The plugin must already exist. + */ + update: async (id, data2) => { + const plugin = await getById(id); + if (!plugin) throw notFound("Plugin not found"); + const setClause = { + updatedAt: /* @__PURE__ */ new Date() + }; + if (data2.packageName !== void 0) setClause.packageName = data2.packageName; + if (data2.version !== void 0) setClause.version = data2.version; + if (data2.manifest !== void 0) { + setClause.manifestJson = data2.manifest; + setClause.apiVersion = data2.manifest.apiVersion; + setClause.categories = data2.manifest.categories; + } + return db.update(plugins).set(setClause).where(eq(plugins.id, id)).returning().then((rows) => rows[0] ?? null); + }, + // ----- Status --------------------------------------------------------- + /** Update a plugin's lifecycle status and optional error message. */ + updateStatus: async (id, input) => { + const plugin = await getById(id); + if (!plugin) throw notFound("Plugin not found"); + return db.update(plugins).set({ + status: input.status, + lastError: input.lastError ?? null, + updatedAt: /* @__PURE__ */ new Date() + }).where(eq(plugins.id, id)).returning().then((rows) => rows[0] ?? null); + }, + // ----- Uninstall / Remove -------------------------------------------- + /** + * Uninstall a plugin. + * + * When `removeData` is true the plugin row (and cascaded config) is + * hard-deleted. Otherwise the status is set to `"uninstalled"` for + * a soft-delete that preserves the record. + */ + uninstall: async (id, removeData = false) => { + const plugin = await getById(id); + if (!plugin) throw notFound("Plugin not found"); + if (removeData) { + return db.delete(plugins).where(eq(plugins.id, id)).returning().then((rows) => rows[0] ?? null); + } + return db.update(plugins).set({ + status: "uninstalled", + updatedAt: /* @__PURE__ */ new Date() + }).where(eq(plugins.id, id)).returning().then((rows) => rows[0] ?? null); + }, + // ----- Config --------------------------------------------------------- + /** Retrieve a plugin's instance configuration. */ + getConfig: (pluginId) => db.select().from(pluginConfig).where(eq(pluginConfig.pluginId, pluginId)).then((rows) => rows[0] ?? null), + /** + * Create or fully replace a plugin's instance configuration. + * If a config row already exists for the plugin it is replaced; + * otherwise a new row is inserted. + */ + upsertConfig: async (pluginId, input) => { + const plugin = await getById(pluginId); + if (!plugin) throw notFound("Plugin not found"); + const existing = await db.select().from(pluginConfig).where(eq(pluginConfig.pluginId, pluginId)).then((rows) => rows[0] ?? null); + if (existing) { + return db.update(pluginConfig).set({ + configJson: input.configJson, + lastError: null, + updatedAt: /* @__PURE__ */ new Date() + }).where(eq(pluginConfig.pluginId, pluginId)).returning().then((rows) => rows[0]); + } + return db.insert(pluginConfig).values({ + pluginId, + configJson: input.configJson + }).returning().then((rows) => rows[0]); + }, + /** + * Partially update a plugin's instance configuration via shallow merge. + * If no config row exists yet one is created with the supplied values. + */ + patchConfig: async (pluginId, input) => { + const plugin = await getById(pluginId); + if (!plugin) throw notFound("Plugin not found"); + const existing = await db.select().from(pluginConfig).where(eq(pluginConfig.pluginId, pluginId)).then((rows) => rows[0] ?? null); + if (existing) { + const merged = { ...existing.configJson, ...input.configJson }; + return db.update(pluginConfig).set({ + configJson: merged, + lastError: null, + updatedAt: /* @__PURE__ */ new Date() + }).where(eq(pluginConfig.pluginId, pluginId)).returning().then((rows) => rows[0]); + } + return db.insert(pluginConfig).values({ + pluginId, + configJson: input.configJson + }).returning().then((rows) => rows[0]); + }, + /** + * Record an error against a plugin's config (e.g. validation failure + * against the plugin's instanceConfigSchema). + */ + setConfigError: async (pluginId, lastError) => { + const rows = await db.update(pluginConfig).set({ lastError, updatedAt: /* @__PURE__ */ new Date() }).where(eq(pluginConfig.pluginId, pluginId)).returning(); + if (rows.length === 0) throw notFound("Plugin config not found"); + return rows[0]; + }, + /** Delete a plugin's config row. */ + deleteConfig: async (pluginId) => { + const rows = await db.delete(pluginConfig).where(eq(pluginConfig.pluginId, pluginId)).returning(); + return rows[0] ?? null; + }, + // ----- Entities ------------------------------------------------------- + /** + * List persistent entity mappings owned by a specific plugin, with filtering and pagination. + * + * @param pluginId - The UUID of the plugin. + * @param query - Optional filters (type, externalId) and pagination (limit, offset). + * @returns A list of matching `PluginEntityRecord` objects. + */ + listEntities: (pluginId, query) => { + const conditions = [eq(pluginEntities.pluginId, pluginId)]; + if (query?.entityType) conditions.push(eq(pluginEntities.entityType, query.entityType)); + if (query?.externalId) conditions.push(eq(pluginEntities.externalId, query.externalId)); + return db.select().from(pluginEntities).where(and(...conditions)).orderBy(asc(pluginEntities.createdAt)).limit(query?.limit ?? 100).offset(query?.offset ?? 0); + }, + /** + * Look up a plugin-owned entity mapping by its external identifier. + * + * @param pluginId - The UUID of the plugin. + * @param entityType - The type of entity (e.g., 'project', 'issue'). + * @param externalId - The identifier in the external system. + * @returns The matching `PluginEntityRecord` or null. + */ + getEntityByExternalId: (pluginId, entityType, externalId) => db.select().from(pluginEntities).where( + and( + eq(pluginEntities.pluginId, pluginId), + eq(pluginEntities.entityType, entityType), + eq(pluginEntities.externalId, externalId) + ) + ).then((rows) => rows[0] ?? null), + /** + * Create or update a persistent mapping between a Taskcore object and an + * external entity. + * + * @param pluginId - The UUID of the plugin. + * @param input - The entity data to persist. + * @returns The newly created or updated `PluginEntityRecord`. + */ + upsertEntity: async (pluginId, input) => { + const existing = await db.select().from(pluginEntities).where( + and( + eq(pluginEntities.pluginId, pluginId), + eq(pluginEntities.entityType, input.entityType), + eq(pluginEntities.externalId, input.externalId ?? "") + ) + ).then((rows) => rows[0] ?? null); + if (existing) { + return db.update(pluginEntities).set({ + ...input, + updatedAt: /* @__PURE__ */ new Date() + }).where(eq(pluginEntities.id, existing.id)).returning().then((rows) => rows[0]); + } + return db.insert(pluginEntities).values({ + ...input, + pluginId + }).returning().then((rows) => rows[0]); + }, + /** + * Delete a specific plugin-owned entity mapping by its internal UUID. + * + * @param id - The UUID of the entity record. + * @returns The deleted record, or null if not found. + */ + deleteEntity: async (id) => { + const rows = await db.delete(pluginEntities).where(eq(pluginEntities.id, id)).returning(); + return rows[0] ?? null; + }, + // ----- Jobs ----------------------------------------------------------- + /** + * List all scheduled jobs registered for a specific plugin. + * + * @param pluginId - The UUID of the plugin. + * @returns A list of `PluginJobRecord` objects. + */ + listJobs: (pluginId) => db.select().from(pluginJobs).where(eq(pluginJobs.pluginId, pluginId)).orderBy(asc(pluginJobs.jobKey)), + /** + * Look up a plugin job by its unique job key. + * + * @param pluginId - The UUID of the plugin. + * @param jobKey - The key defined in the plugin manifest. + * @returns The matching `PluginJobRecord` or null. + */ + getJobByKey: (pluginId, jobKey) => db.select().from(pluginJobs).where(and(eq(pluginJobs.pluginId, pluginId), eq(pluginJobs.jobKey, jobKey))).then((rows) => rows[0] ?? null), + /** + * Register or update a scheduled job for a plugin. + * + * @param pluginId - The UUID of the plugin. + * @param jobKey - The unique key for the job. + * @param input - The schedule (cron) and optional status. + * @returns The updated or created `PluginJobRecord`. + */ + upsertJob: async (pluginId, jobKey, input) => { + const existing = await db.select().from(pluginJobs).where(and(eq(pluginJobs.pluginId, pluginId), eq(pluginJobs.jobKey, jobKey))).then((rows) => rows[0] ?? null); + if (existing) { + return db.update(pluginJobs).set({ + schedule: input.schedule, + status: input.status ?? existing.status, + updatedAt: /* @__PURE__ */ new Date() + }).where(eq(pluginJobs.id, existing.id)).returning().then((rows) => rows[0]); + } + return db.insert(pluginJobs).values({ + pluginId, + jobKey, + schedule: input.schedule, + status: input.status ?? "active" + }).returning().then((rows) => rows[0]); + }, + /** + * Record the start of a specific job execution. + * + * @param pluginId - The UUID of the plugin. + * @param jobId - The UUID of the parent job record. + * @param trigger - What triggered this run (e.g., 'schedule', 'manual'). + * @returns The newly created `PluginJobRunRecord` in 'pending' status. + */ + createJobRun: async (pluginId, jobId, trigger) => { + return db.insert(pluginJobRuns).values({ + pluginId, + jobId, + trigger, + status: "pending" + }).returning().then((rows) => rows[0]); + }, + /** + * Update the status, duration, and logs of a job execution record. + * + * @param runId - The UUID of the job run. + * @param input - The update fields (status, error, duration, etc.). + * @returns The updated `PluginJobRunRecord`. + */ + updateJobRun: async (runId, input) => { + return db.update(pluginJobRuns).set(input).where(eq(pluginJobRuns.id, runId)).returning().then((rows) => rows[0] ?? null); + }, + // ----- Webhooks ------------------------------------------------------- + /** + * Create a record for an incoming webhook delivery. + * + * @param pluginId - The UUID of the receiving plugin. + * @param webhookKey - The endpoint key defined in the manifest. + * @param input - The payload, headers, and optional external ID. + * @returns The newly created `PluginWebhookDeliveryRecord` in 'pending' status. + */ + createWebhookDelivery: async (pluginId, webhookKey, input) => { + return db.insert(pluginWebhookDeliveries).values({ + pluginId, + webhookKey, + externalId: input.externalId, + payload: input.payload, + headers: input.headers ?? {}, + status: "pending" + }).returning().then((rows) => rows[0]); + }, + /** + * Update the status and processing metrics of a webhook delivery. + * + * @param deliveryId - The UUID of the delivery record. + * @param input - The update fields (status, error, duration, etc.). + * @returns The updated `PluginWebhookDeliveryRecord`. + */ + updateWebhookDelivery: async (deliveryId, input) => { + return db.update(pluginWebhookDeliveries).set(input).where(eq(pluginWebhookDeliveries.id, deliveryId)).returning().then((rows) => rows[0] ?? null); + } + }; +} + +// server/src/services/plugin-lifecycle.ts +import { EventEmitter as EventEmitter2 } from "node:events"; + +// server/src/services/plugin-loader.ts +import { existsSync as existsSync5 } from "node:fs"; +import { readdir as readdir2, readFile as readFile3, rm, stat } from "node:fs/promises"; +import { execFile as execFile7 } from "node:child_process"; +import os23 from "node:os"; +import path46 from "node:path"; +import { fileURLToPath as fileURLToPath17 } from "node:url"; +import { promisify as promisify7 } from "node:util"; + +// server/src/services/plugin-manifest-validator.ts +var SUPPORTED_VERSIONS = [PLUGIN_API_VERSION]; +function pluginManifestValidator() { + return { + parse(input) { + const result = pluginManifestV1Schema.safeParse(input); + if (result.success) { + return { + success: true, + manifest: result.data + }; + } + const details = result.error.errors.map((issue2) => ({ + path: issue2.path, + message: issue2.message + })); + const errors = details.map( + ({ path: path53, message: message2 }) => path53.length > 0 ? `${path53.join(".")}: ${message2}` : message2 + ).join("; "); + return { + success: false, + errors, + details + }; + }, + parseOrThrow(input) { + const result = this.parse(input); + if (!result.success) { + throw badRequest(`Invalid plugin manifest: ${result.errors}`, result.details); + } + return result.manifest; + }, + getSupportedVersions() { + return SUPPORTED_VERSIONS; + } + }; +} + +// server/src/services/plugin-capability-validator.ts +var OPERATION_CAPABILITIES = { + // Data read operations + "companies.list": ["companies.read"], + "companies.get": ["companies.read"], + "projects.list": ["projects.read"], + "projects.get": ["projects.read"], + "project.workspaces.list": ["project.workspaces.read"], + "project.workspaces.get": ["project.workspaces.read"], + "issues.list": ["issues.read"], + "issues.get": ["issues.read"], + "issue.comments.list": ["issue.comments.read"], + "issue.comments.get": ["issue.comments.read"], + "agents.list": ["agents.read"], + "agents.get": ["agents.read"], + "goals.list": ["goals.read"], + "goals.get": ["goals.read"], + "activity.list": ["activity.read"], + "activity.get": ["activity.read"], + "costs.list": ["costs.read"], + "costs.get": ["costs.read"], + // Data write operations + "issues.create": ["issues.create"], + "issues.update": ["issues.update"], + "issue.comments.create": ["issue.comments.create"], + "activity.log": ["activity.log.write"], + "metrics.write": ["metrics.write"], + "telemetry.track": ["telemetry.track"], + // Plugin state operations + "plugin.state.get": ["plugin.state.read"], + "plugin.state.list": ["plugin.state.read"], + "plugin.state.set": ["plugin.state.write"], + "plugin.state.delete": ["plugin.state.write"], + // Runtime / Integration operations + "events.subscribe": ["events.subscribe"], + "events.emit": ["events.emit"], + "jobs.schedule": ["jobs.schedule"], + "jobs.cancel": ["jobs.schedule"], + "webhooks.receive": ["webhooks.receive"], + "http.request": ["http.outbound"], + "secrets.resolve": ["secrets.read-ref"], + // Agent tools + "agent.tools.register": ["agent.tools.register"], + "agent.tools.execute": ["agent.tools.register"] +}; +var UI_SLOT_CAPABILITIES = { + sidebar: "ui.sidebar.register", + sidebarPanel: "ui.sidebar.register", + projectSidebarItem: "ui.sidebar.register", + page: "ui.page.register", + detailTab: "ui.detailTab.register", + taskDetailView: "ui.detailTab.register", + dashboardWidget: "ui.dashboardWidget.register", + globalToolbarButton: "ui.action.register", + toolbarButton: "ui.action.register", + contextMenuItem: "ui.action.register", + commentAnnotation: "ui.commentAnnotation.register", + commentContextMenuItem: "ui.action.register", + settingsPage: "instance.settings.register" +}; +var LAUNCHER_PLACEMENT_CAPABILITIES = { + page: "ui.page.register", + detailTab: "ui.detailTab.register", + taskDetailView: "ui.detailTab.register", + dashboardWidget: "ui.dashboardWidget.register", + sidebar: "ui.sidebar.register", + sidebarPanel: "ui.sidebar.register", + projectSidebarItem: "ui.sidebar.register", + globalToolbarButton: "ui.action.register", + toolbarButton: "ui.action.register", + contextMenuItem: "ui.action.register", + commentAnnotation: "ui.commentAnnotation.register", + commentContextMenuItem: "ui.action.register", + settingsPage: "instance.settings.register" +}; +var FEATURE_CAPABILITIES = { + tools: "agent.tools.register", + jobs: "jobs.schedule", + webhooks: "webhooks.receive" +}; +function pluginCapabilityValidator() { + const log2 = logger.child({ service: "plugin-capability-validator" }); + function capabilitySet(manifest) { + return new Set(manifest.capabilities); + } + function buildForbiddenMessage(manifest, operation2, missing) { + return `Plugin '${manifest.id}' is not allowed to perform '${operation2}'. Missing required capabilities: ${missing.join(", ")}`; + } + return { + hasCapability(manifest, capability) { + return manifest.capabilities.includes(capability); + }, + hasAllCapabilities(manifest, capabilities) { + const declared = capabilitySet(manifest); + const missing = capabilities.filter((cap) => !declared.has(cap)); + return { + allowed: missing.length === 0, + missing, + pluginId: manifest.id + }; + }, + hasAnyCapability(manifest, capabilities) { + const declared = capabilitySet(manifest); + return capabilities.some((cap) => declared.has(cap)); + }, + checkOperation(manifest, operation2) { + const required2 = OPERATION_CAPABILITIES[operation2]; + if (!required2) { + log2.warn( + { pluginId: manifest.id, operation: operation2 }, + "capability check for unknown operation \u2013 rejecting by default" + ); + return { + allowed: false, + missing: [], + operation: operation2, + pluginId: manifest.id + }; + } + const declared = capabilitySet(manifest); + const missing = required2.filter((cap) => !declared.has(cap)); + if (missing.length > 0) { + log2.debug( + { pluginId: manifest.id, operation: operation2, missing }, + "capability check failed" + ); + } + return { + allowed: missing.length === 0, + missing, + operation: operation2, + pluginId: manifest.id + }; + }, + assertOperation(manifest, operation2) { + const result = this.checkOperation(manifest, operation2); + if (!result.allowed) { + const msg = result.missing.length > 0 ? buildForbiddenMessage(manifest, operation2, result.missing) : `Plugin '${manifest.id}' attempted unknown operation '${operation2}'`; + throw forbidden(msg); + } + }, + assertCapability(manifest, capability) { + if (!this.hasCapability(manifest, capability)) { + throw forbidden( + `Plugin '${manifest.id}' lacks required capability '${capability}'` + ); + } + }, + checkUiSlot(manifest, slotType) { + const required2 = UI_SLOT_CAPABILITIES[slotType]; + if (!required2) { + return { + allowed: false, + missing: [], + operation: `ui.${slotType}.register`, + pluginId: manifest.id + }; + } + const has = manifest.capabilities.includes(required2); + return { + allowed: has, + missing: has ? [] : [required2], + operation: `ui.${slotType}.register`, + pluginId: manifest.id + }; + }, + validateManifestCapabilities(manifest) { + const declared = capabilitySet(manifest); + const allMissing = []; + for (const [feature, requiredCap] of Object.entries(FEATURE_CAPABILITIES)) { + const featureValue = manifest[feature]; + if (Array.isArray(featureValue) && featureValue.length > 0) { + if (!declared.has(requiredCap)) { + allMissing.push(requiredCap); + } + } + } + const uiSlots = manifest.ui?.slots ?? []; + if (uiSlots.length > 0) { + for (const slot of uiSlots) { + const requiredCap = UI_SLOT_CAPABILITIES[slot.type]; + if (requiredCap && !declared.has(requiredCap)) { + if (!allMissing.includes(requiredCap)) { + allMissing.push(requiredCap); + } + } + } + } + const launchers = [ + ...manifest.launchers ?? [], + ...manifest.ui?.launchers ?? [] + ]; + if (launchers.length > 0) { + for (const launcher of launchers) { + const requiredCap = LAUNCHER_PLACEMENT_CAPABILITIES[launcher.placementZone]; + if (requiredCap && !declared.has(requiredCap) && !allMissing.includes(requiredCap)) { + allMissing.push(requiredCap); + } + } + } + return { + allowed: allMissing.length === 0, + missing: allMissing, + pluginId: manifest.id + }; + }, + getRequiredCapabilities(operation2) { + return OPERATION_CAPABILITIES[operation2] ?? []; + }, + getUiSlotCapability(slotType) { + return UI_SLOT_CAPABILITIES[slotType]; + } + }; +} + +// server/src/services/plugin-loader.ts +var execFileAsync6 = promisify7(execFile7); +var __dirname2 = path46.dirname(fileURLToPath17(import.meta.url)); +var NPM_PLUGIN_PACKAGE_PREFIX = "taskcore-plugin-"; +var DEFAULT_LOCAL_PLUGIN_DIR = path46.join( + os23.homedir(), + ".taskcore", + "plugins" +); +var DEV_TSX_LOADER_PATH = path46.resolve(__dirname2, "../../../cli/node_modules/tsx/dist/loader.mjs"); +function getDeclaredPageRoutePaths(manifest) { + return (manifest.ui?.slots ?? []).filter((slot) => slot.type === "page" && typeof slot.routePath === "string" && slot.routePath.length > 0).map((slot) => slot.routePath); +} +function isPluginPackageName(name) { + if (name.startsWith(NPM_PLUGIN_PACKAGE_PREFIX)) return true; + if (name.includes("/")) { + const localPart = name.split("/")[1] ?? ""; + return localPart.startsWith("plugin-"); + } + return false; +} +async function readPackageJson(dir) { + const pkgPath = path46.join(dir, "package.json"); + if (!existsSync5(pkgPath)) return null; + try { + const raw = await readFile3(pkgPath, "utf-8"); + return JSON.parse(raw); + } catch { + return null; + } +} +function resolveManifestPath(packageRoot, pkgJson) { + const taskcorePlugin = pkgJson["taskcorePlugin"]; + if (taskcorePlugin !== null && typeof taskcorePlugin === "object" && !Array.isArray(taskcorePlugin)) { + const manifestRelPath = taskcorePlugin["manifest"]; + if (typeof manifestRelPath === "string") { + return path46.resolve(packageRoot, manifestRelPath); + } + } + const conventionalPath = path46.join(packageRoot, "dist", "manifest.js"); + if (existsSync5(conventionalPath)) { + return conventionalPath; + } + const rootManifestPath = path46.join(packageRoot, "manifest.js"); + if (existsSync5(rootManifestPath)) { + return rootManifestPath; + } + return null; +} +function parseSemver(version3) { + const match = version3.match( + /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/ + ); + if (!match) return null; + return { + major: Number(match[1]), + minor: Number(match[2]), + patch: Number(match[3]), + prerelease: match[4] ? match[4].split(".") : [] + }; +} +function compareIdentifiers(left, right) { + const leftIsNumeric = /^\d+$/.test(left); + const rightIsNumeric = /^\d+$/.test(right); + if (leftIsNumeric && rightIsNumeric) { + return Number(left) - Number(right); + } + if (leftIsNumeric) return -1; + if (rightIsNumeric) return 1; + return left.localeCompare(right); +} +function compareSemver(left, right) { + const leftParsed = parseSemver(left); + const rightParsed = parseSemver(right); + if (!leftParsed || !rightParsed) { + throw new Error(`Invalid semver comparison: '${left}' vs '${right}'`); + } + const coreOrder = ["major", "minor", "patch"].map((key) => leftParsed[key] - rightParsed[key]).find((delta) => delta !== 0); + if (coreOrder) { + return coreOrder; + } + if (leftParsed.prerelease.length === 0 && rightParsed.prerelease.length === 0) { + return 0; + } + if (leftParsed.prerelease.length === 0) return 1; + if (rightParsed.prerelease.length === 0) return -1; + const maxLength = Math.max(leftParsed.prerelease.length, rightParsed.prerelease.length); + for (let index2 = 0; index2 < maxLength; index2 += 1) { + const leftId = leftParsed.prerelease[index2]; + const rightId = rightParsed.prerelease[index2]; + if (leftId === void 0) return -1; + if (rightId === void 0) return 1; + const diff = compareIdentifiers(leftId, rightId); + if (diff !== 0) return diff; + } + return 0; +} +function getMinimumHostVersion(manifest) { + return manifest.minimumHostVersion ?? manifest.minimumTaskcoreVersion; +} +function getPluginUiContributionMetadata(manifest) { + const slots = manifest.ui?.slots ?? []; + const launchers = [ + ...manifest.launchers ?? [], + ...manifest.ui?.launchers ?? [] + ]; + if (slots.length === 0 && launchers.length === 0) { + return null; + } + return { + uiEntryFile: "index.js", + slots, + launchers + }; +} +function pluginLoader(db, options = {}, runtimeServices) { + const { + localPluginDir = DEFAULT_LOCAL_PLUGIN_DIR, + enableLocalFilesystem = true, + enableNpmDiscovery = true + } = options; + const registry2 = pluginRegistryService(db); + const manifestValidator = pluginManifestValidator(); + const capabilityValidator = pluginCapabilityValidator(); + const log2 = logger.child({ service: "plugin-loader" }); + const hostVersion = runtimeServices?.instanceInfo.hostVersion; + async function assertPageRoutePathsAvailable(manifest) { + const requestedRoutePaths = getDeclaredPageRoutePaths(manifest); + if (requestedRoutePaths.length === 0) return; + const uniqueRequested = new Set(requestedRoutePaths); + if (uniqueRequested.size !== requestedRoutePaths.length) { + throw new Error(`Plugin ${manifest.id} declares duplicate page routePath values`); + } + const installedPlugins = await registry2.listInstalled(); + for (const plugin of installedPlugins) { + if (plugin.pluginKey === manifest.id) continue; + const installedManifest = plugin.manifestJson; + if (!installedManifest) continue; + const installedRoutePaths = new Set(getDeclaredPageRoutePaths(installedManifest)); + const conflictingRoute = requestedRoutePaths.find((routePath) => installedRoutePaths.has(routePath)); + if (conflictingRoute) { + throw new Error( + `Plugin ${manifest.id} routePath "${conflictingRoute}" conflicts with installed plugin ${plugin.pluginKey}` + ); + } + } + } + async function fetchAndValidate(installOptions) { + const { packageName, localPath, version: version3, installDir } = installOptions; + if (!packageName && !localPath) { + throw new Error("Either packageName or localPath must be provided"); + } + const targetInstallDir = installDir ?? localPluginDir; + let resolvedPackagePath; + let resolvedPackageName; + if (localPath) { + const absLocalPath = path46.resolve(localPath); + if (!existsSync5(absLocalPath)) { + throw new Error(`Local plugin path does not exist: ${absLocalPath}`); + } + resolvedPackagePath = absLocalPath; + const pkgJson2 = await readPackageJson(absLocalPath); + resolvedPackageName = typeof pkgJson2?.["name"] === "string" ? pkgJson2["name"] : path46.basename(absLocalPath); + log2.info( + { localPath: absLocalPath, packageName: resolvedPackageName }, + "plugin-loader: fetching plugin from local path" + ); + } else { + const spec = version3 ? `${packageName}@${version3}` : packageName; + log2.info( + { spec, installDir: targetInstallDir }, + "plugin-loader: fetching plugin from npm" + ); + try { + await execFileAsync6( + "npm", + ["install", spec, "--prefix", targetInstallDir, "--save", "--ignore-scripts"], + { timeout: 12e4 } + // 2 minute timeout for npm install + ); + } catch (err) { + throw new Error(`npm install failed for ${spec}: ${String(err)}`); + } + const nodeModulesPath = path46.join(targetInstallDir, "node_modules"); + resolvedPackageName = packageName; + if (resolvedPackageName.startsWith("@")) { + const [scope, name] = resolvedPackageName.split("/"); + resolvedPackagePath = path46.join(nodeModulesPath, scope, name); + } else { + resolvedPackagePath = path46.join(nodeModulesPath, resolvedPackageName); + } + if (!existsSync5(resolvedPackagePath)) { + throw new Error( + `Package directory not found after installation: ${resolvedPackagePath}` + ); + } + } + const pkgJson = await readPackageJson(resolvedPackagePath); + if (!pkgJson) throw new Error(`Missing package.json at ${resolvedPackagePath}`); + const manifestPath = resolveManifestPath(resolvedPackagePath, pkgJson); + if (!manifestPath || !existsSync5(manifestPath)) { + throw new Error( + `Package ${resolvedPackageName} at ${resolvedPackagePath} does not appear to be a Taskcore plugin (no manifest found).` + ); + } + const manifest = await loadManifestFromPath(manifestPath); + if (!manifestValidator.getSupportedVersions().includes(manifest.apiVersion)) { + throw new Error( + `Plugin ${manifest.id} declares apiVersion ${manifest.apiVersion} which is not supported by this host. Supported versions: ${manifestValidator.getSupportedVersions().join(", ")}` + ); + } + const capResult = capabilityValidator.validateManifestCapabilities(manifest); + if (!capResult.allowed) { + throw new Error( + `Plugin ${manifest.id} manifest has inconsistent capabilities. Missing required capabilities for declared features: ${capResult.missing.join(", ")}` + ); + } + await assertPageRoutePathsAvailable(manifest); + const minimumHostVersion = getMinimumHostVersion(manifest); + if (minimumHostVersion && hostVersion) { + if (compareSemver(hostVersion, minimumHostVersion) < 0) { + throw new Error( + `Plugin ${manifest.id} requires host version ${minimumHostVersion} or newer, but this server is running ${hostVersion}` + ); + } + } + const resolvedVersion = manifest.version; + return { + packagePath: resolvedPackagePath, + packageName: resolvedPackageName, + version: resolvedVersion, + source: localPath ? "local-filesystem" : "npm", + manifest + }; + } + async function loadManifestFromPath(manifestPath) { + let raw; + try { + const mod = await import(manifestPath); + raw = mod["default"] ?? mod; + } catch (err) { + throw new Error( + `Failed to load manifest module at ${manifestPath}: ${String(err)}` + ); + } + return manifestValidator.parseOrThrow(raw); + } + async function buildDiscoveredPlugin(packagePath, source) { + const pkgJson = await readPackageJson(packagePath); + if (!pkgJson) return null; + const packageName = typeof pkgJson["name"] === "string" ? pkgJson["name"] : ""; + const version3 = typeof pkgJson["version"] === "string" ? pkgJson["version"] : "0.0.0"; + const hasTaskcorePlugin = "taskcorePlugin" in pkgJson; + const nameMatchesConvention = isPluginPackageName(packageName); + if (!hasTaskcorePlugin && !nameMatchesConvention) { + return null; + } + const manifestPath = resolveManifestPath(packagePath, pkgJson); + if (!manifestPath || !existsSync5(manifestPath)) { + return { + packagePath, + packageName, + version: version3, + source, + manifest: null + }; + } + try { + const manifest = await loadManifestFromPath(manifestPath); + return { + packagePath, + packageName, + version: version3, + source, + manifest + }; + } catch (err) { + throw new Error( + `Plugin ${packageName}: ${String(err)}` + ); + } + } + return { + // ----------------------------------------------------------------------- + // discoverAll + // ----------------------------------------------------------------------- + async discoverAll(npmSearchDirs) { + const allDiscovered = []; + const allErrors = []; + const sources = []; + if (enableLocalFilesystem) { + sources.push("local-filesystem"); + const fsResult = await this.discoverFromLocalFilesystem(); + allDiscovered.push(...fsResult.discovered); + allErrors.push(...fsResult.errors); + } + if (enableNpmDiscovery) { + sources.push("npm"); + const npmResult = await this.discoverFromNpm(npmSearchDirs); + const existingPaths = new Set(allDiscovered.map((d5) => d5.packagePath)); + for (const plugin of npmResult.discovered) { + if (!existingPaths.has(plugin.packagePath)) { + allDiscovered.push(plugin); + } + } + allErrors.push(...npmResult.errors); + } + if (options.registryUrl) { + sources.push("registry"); + log2.warn( + { registryUrl: options.registryUrl }, + "plugin-loader: remote registry discovery is not yet implemented" + ); + } + log2.info( + { + discovered: allDiscovered.length, + errors: allErrors.length, + sources + }, + "plugin-loader: discovery complete" + ); + return { discovered: allDiscovered, errors: allErrors, sources }; + }, + // ----------------------------------------------------------------------- + // discoverFromLocalFilesystem + // ----------------------------------------------------------------------- + async discoverFromLocalFilesystem(dir) { + const scanDir = dir ?? localPluginDir; + const discovered = []; + const errors = []; + if (!existsSync5(scanDir)) { + log2.debug( + { dir: scanDir }, + "plugin-loader: local plugin directory does not exist, skipping" + ); + return { discovered, errors, sources: ["local-filesystem"] }; + } + let entries2; + try { + entries2 = await readdir2(scanDir); + } catch (err) { + log2.warn({ dir: scanDir, err }, "plugin-loader: failed to read local plugin directory"); + return { discovered, errors, sources: ["local-filesystem"] }; + } + for (const entry of entries2) { + const entryPath = path46.join(scanDir, entry); + let entryStat; + try { + entryStat = await stat(entryPath); + } catch { + continue; + } + if (!entryStat.isDirectory()) continue; + if (entry.startsWith("@")) { + let scopedEntries; + try { + scopedEntries = await readdir2(entryPath); + } catch { + continue; + } + for (const scopedEntry of scopedEntries) { + const scopedPath = path46.join(entryPath, scopedEntry); + try { + const scopedStat = await stat(scopedPath); + if (!scopedStat.isDirectory()) continue; + const plugin = await buildDiscoveredPlugin(scopedPath, "local-filesystem"); + if (plugin) discovered.push(plugin); + } catch (err) { + errors.push({ + packagePath: scopedPath, + packageName: `${entry}/${scopedEntry}`, + error: String(err) + }); + } + } + continue; + } + try { + const plugin = await buildDiscoveredPlugin(entryPath, "local-filesystem"); + if (plugin) discovered.push(plugin); + } catch (err) { + const pkgJson = await readPackageJson(entryPath); + const packageName = typeof pkgJson?.["name"] === "string" ? pkgJson["name"] : entry; + errors.push({ packagePath: entryPath, packageName, error: String(err) }); + } + } + log2.debug( + { dir: scanDir, discovered: discovered.length, errors: errors.length }, + "plugin-loader: local filesystem scan complete" + ); + return { discovered, errors, sources: ["local-filesystem"] }; + }, + // ----------------------------------------------------------------------- + // discoverFromNpm + // ----------------------------------------------------------------------- + async discoverFromNpm(searchDirs) { + const discovered = []; + const errors = []; + const dirsToSearch = searchDirs && searchDirs.length > 0 ? searchDirs : []; + if (dirsToSearch.length === 0) { + const cwdNodeModules = path46.join(process.cwd(), "node_modules"); + const localNodeModules = path46.join(localPluginDir, "node_modules"); + if (existsSync5(cwdNodeModules)) dirsToSearch.push(cwdNodeModules); + if (existsSync5(localNodeModules)) dirsToSearch.push(localNodeModules); + } + for (const nodeModulesDir of dirsToSearch) { + if (!existsSync5(nodeModulesDir)) continue; + let entries2; + try { + entries2 = await readdir2(nodeModulesDir); + } catch { + continue; + } + for (const entry of entries2) { + const entryPath = path46.join(nodeModulesDir, entry); + if (entry.startsWith("@")) { + let scopedEntries; + try { + scopedEntries = await readdir2(entryPath); + } catch { + continue; + } + for (const scopedEntry of scopedEntries) { + const fullName = `${entry}/${scopedEntry}`; + if (!isPluginPackageName(fullName)) continue; + const scopedPath = path46.join(entryPath, scopedEntry); + try { + const plugin = await buildDiscoveredPlugin(scopedPath, "npm"); + if (plugin) discovered.push(plugin); + } catch (err) { + errors.push({ + packagePath: scopedPath, + packageName: fullName, + error: String(err) + }); + } + } + continue; + } + if (!isPluginPackageName(entry)) continue; + let entryStat; + try { + entryStat = await stat(entryPath); + } catch { + continue; + } + if (!entryStat.isDirectory()) continue; + try { + const plugin = await buildDiscoveredPlugin(entryPath, "npm"); + if (plugin) discovered.push(plugin); + } catch (err) { + const pkgJson = await readPackageJson(entryPath); + const packageName = typeof pkgJson?.["name"] === "string" ? pkgJson["name"] : entry; + errors.push({ packagePath: entryPath, packageName, error: String(err) }); + } + } + } + log2.debug( + { searchDirs: dirsToSearch, discovered: discovered.length, errors: errors.length }, + "plugin-loader: npm discovery scan complete" + ); + return { discovered, errors, sources: ["npm"] }; + }, + // ----------------------------------------------------------------------- + // loadManifest + // ----------------------------------------------------------------------- + async loadManifest(packagePath) { + const pkgJson = await readPackageJson(packagePath); + if (!pkgJson) return null; + const hasTaskcorePlugin = "taskcorePlugin" in pkgJson; + const packageName = typeof pkgJson["name"] === "string" ? pkgJson["name"] : ""; + const nameMatchesConvention = isPluginPackageName(packageName); + if (!hasTaskcorePlugin && !nameMatchesConvention) { + return null; + } + const manifestPath = resolveManifestPath(packagePath, pkgJson); + if (!manifestPath || !existsSync5(manifestPath)) return null; + return loadManifestFromPath(manifestPath); + }, + // ----------------------------------------------------------------------- + // installPlugin + // ----------------------------------------------------------------------- + async installPlugin(installOptions) { + const discovered = await fetchAndValidate(installOptions); + await registry2.install( + { + packageName: discovered.packageName, + packagePath: discovered.source === "local-filesystem" ? discovered.packagePath : void 0 + }, + discovered.manifest + ); + log2.info( + { + pluginId: discovered.manifest.id, + packageName: discovered.packageName, + version: discovered.version, + capabilities: discovered.manifest.capabilities + }, + "plugin-loader: plugin installed successfully" + ); + return discovered; + }, + // ----------------------------------------------------------------------- + // upgradePlugin + // ----------------------------------------------------------------------- + /** + * Upgrade an already-installed plugin to a newer version. + * + * This method: + * 1. Fetches and validates the new plugin package using `fetchAndValidate`. + * 2. Ensures the new manifest ID matches the existing plugin ID for safety. + * 3. Updates the plugin record in the registry with the new version and manifest. + * + * @param pluginId - The UUID of the plugin to upgrade. + * @param upgradeOptions - Options for the upgrade (packageName, localPath, version). + * @returns The old and new manifests, along with the discovery metadata. + * @throws {Error} If the plugin is not found or if the new manifest ID differs. + */ + async upgradePlugin(pluginId, upgradeOptions) { + const plugin = await registry2.getById(pluginId); + if (!plugin) throw new Error(`Plugin not found: ${pluginId}`); + const oldManifest = plugin.manifestJson; + const { + packageName = plugin.packageName, + // For local-path installs, fall back to the stored packagePath so + // `upgradePlugin` can re-read the manifest from disk without needing + // the caller to re-supply the path every time. + localPath = plugin.packagePath ?? void 0, + version: version3 + } = upgradeOptions; + log2.info( + { pluginId, packageName, version: version3, localPath }, + "plugin-loader: upgrading plugin" + ); + const discovered = await fetchAndValidate({ + packageName, + localPath, + version: version3, + installDir: localPluginDir + }); + const newManifest = discovered.manifest; + if (newManifest.id !== oldManifest.id) { + throw new Error( + `Upgrade failed: new manifest ID '${newManifest.id}' does not match existing plugin ID '${oldManifest.id}'` + ); + } + const oldCaps = new Set(oldManifest.capabilities ?? []); + const newCaps = newManifest.capabilities ?? []; + const escalated = newCaps.filter((c5) => !oldCaps.has(c5)); + if (escalated.length > 0) { + log2.warn( + { pluginId, escalated, oldVersion: oldManifest.version, newVersion: newManifest.version }, + "plugin-loader: upgrade introduces new capabilities \u2014 requires admin approval" + ); + throw new Error( + `Upgrade for "${pluginId}" introduces new capabilities that require approval: ${escalated.join(", ")}. The previous version declared [${[...oldCaps].join(", ")}]. Please review and approve the capability escalation before upgrading.` + ); + } + await registry2.update(pluginId, { + packageName: discovered.packageName, + version: discovered.version, + manifest: newManifest + }); + return { + oldManifest, + newManifest, + discovered + }; + }, + // ----------------------------------------------------------------------- + // isSupportedApiVersion + // ----------------------------------------------------------------------- + isSupportedApiVersion(apiVersion) { + return manifestValidator.getSupportedVersions().includes(apiVersion); + }, + // ----------------------------------------------------------------------- + // cleanupInstallArtifacts + // ----------------------------------------------------------------------- + async cleanupInstallArtifacts(plugin) { + const managedTargets = /* @__PURE__ */ new Set(); + const managedNodeModulesDir = resolveManagedInstallPackageDir(localPluginDir, plugin.packageName); + const directManagedDir = path46.join(localPluginDir, plugin.packageName); + managedTargets.add(managedNodeModulesDir); + if (isPathInsideDir(directManagedDir, localPluginDir)) { + managedTargets.add(directManagedDir); + } + if (plugin.packagePath && isPathInsideDir(plugin.packagePath, localPluginDir)) { + managedTargets.add(path46.resolve(plugin.packagePath)); + } + const packageJsonPath = path46.join(localPluginDir, "package.json"); + if (existsSync5(packageJsonPath)) { + try { + await execFileAsync6( + "npm", + ["uninstall", plugin.packageName, "--prefix", localPluginDir, "--ignore-scripts"], + { timeout: 12e4 } + ); + } catch (err) { + log2.warn( + { + pluginId: plugin.id, + pluginKey: plugin.pluginKey, + packageName: plugin.packageName, + err: err instanceof Error ? err.message : String(err) + }, + "plugin-loader: npm uninstall failed during cleanup, falling back to direct removal" + ); + } + } + for (const target of managedTargets) { + if (!existsSync5(target)) continue; + await rm(target, { recursive: true, force: true }); + } + }, + // ----------------------------------------------------------------------- + // getLocalPluginDir + // ----------------------------------------------------------------------- + getLocalPluginDir() { + return localPluginDir; + }, + // ----------------------------------------------------------------------- + // hasRuntimeServices + // ----------------------------------------------------------------------- + hasRuntimeServices() { + return runtimeServices !== void 0; + }, + // ----------------------------------------------------------------------- + // ----------------------------------------------------------------------- + // loadAll + // ----------------------------------------------------------------------- + /** + * loadAll — Loads and activates all plugins that are currently in 'ready' status. + * + * This method is typically called during server startup. It fetches all ready + * plugins from the registry and attempts to activate them in parallel using + * Promise.allSettled. Failures in individual plugins do not prevent others from loading. + * + * @returns A promise that resolves with summary statistics of the load operation. + */ + async loadAll() { + if (!runtimeServices) { + throw new Error( + "Cannot loadAll: no PluginRuntimeServices provided. Pass runtime services as the third argument to pluginLoader()." + ); + } + log2.info("plugin-loader: loading all ready plugins"); + const readyPlugins = await registry2.listByStatus("ready"); + if (readyPlugins.length === 0) { + log2.info("plugin-loader: no ready plugins to load"); + return { total: 0, succeeded: 0, failed: 0, results: [] }; + } + log2.info( + { count: readyPlugins.length }, + "plugin-loader: found ready plugins to load" + ); + const results = await Promise.allSettled( + readyPlugins.map((plugin) => activatePlugin(plugin)) + ); + const loadResults = results.map((r5, i5) => { + if (r5.status === "fulfilled") return r5.value; + return { + plugin: readyPlugins[i5], + success: false, + error: String(r5.reason), + registered: { worker: false, eventSubscriptions: 0, jobs: 0, webhooks: 0, tools: 0 } + }; + }); + const succeeded = loadResults.filter((r5) => r5.success).length; + const failed = loadResults.filter((r5) => !r5.success).length; + log2.info( + { + total: readyPlugins.length, + succeeded, + failed + }, + "plugin-loader: loadAll complete" + ); + return { + total: readyPlugins.length, + succeeded, + failed, + results: loadResults + }; + }, + // ----------------------------------------------------------------------- + // loadSingle + // ----------------------------------------------------------------------- + /** + * loadSingle — Loads and activates a single plugin by its ID. + * + * This method retrieves the plugin from the registry, ensures it's in a valid + * state, and then calls activatePlugin to start its worker and register its + * capabilities (tools, jobs, etc.). + * + * @param pluginId - The UUID of the plugin to load. + * @returns A promise that resolves with the result of the activation. + */ + async loadSingle(pluginId) { + if (!runtimeServices) { + throw new Error( + "Cannot loadSingle: no PluginRuntimeServices provided. Pass runtime services as the third argument to pluginLoader()." + ); + } + const plugin = await registry2.getById(pluginId); + if (!plugin) { + throw new Error(`Plugin not found: ${pluginId}`); + } + if (plugin.status === "installed") { + await runtimeServices.lifecycleManager.load(pluginId); + const updated = await registry2.getById(pluginId); + if (!updated) throw new Error(`Plugin not found after status update: ${pluginId}`); + return { + plugin: updated, + success: true, + registered: { worker: true, eventSubscriptions: 0, jobs: 0, webhooks: 0, tools: 0 } + }; + } + if (plugin.status !== "ready") { + throw new Error( + `Cannot load plugin in status '${plugin.status}'. Plugin must be in 'installed' or 'ready' status.` + ); + } + return activatePlugin(plugin); + }, + // ----------------------------------------------------------------------- + // unloadSingle + // ----------------------------------------------------------------------- + async unloadSingle(pluginId, pluginKey) { + if (!runtimeServices) { + throw new Error( + "Cannot unloadSingle: no PluginRuntimeServices provided." + ); + } + log2.info( + { pluginId, pluginKey }, + "plugin-loader: unloading single plugin" + ); + const { + workerManager, + eventBus, + jobScheduler, + toolDispatcher + } = runtimeServices; + try { + await jobScheduler.unregisterPlugin(pluginId); + } catch (err) { + log2.warn( + { pluginId, err: err instanceof Error ? err.message : String(err) }, + "plugin-loader: failed to unregister from job scheduler (best-effort)" + ); + } + eventBus.clearPlugin(pluginKey); + toolDispatcher.unregisterPluginTools(pluginKey); + try { + if (workerManager.isRunning(pluginId)) { + await workerManager.stopWorker(pluginId); + } + } catch (err) { + log2.warn( + { pluginId, err: err instanceof Error ? err.message : String(err) }, + "plugin-loader: failed to stop worker during unload (best-effort)" + ); + } + log2.info( + { pluginId, pluginKey }, + "plugin-loader: plugin unloaded successfully" + ); + }, + // ----------------------------------------------------------------------- + // shutdownAll + // ----------------------------------------------------------------------- + async shutdownAll() { + if (!runtimeServices) { + throw new Error( + "Cannot shutdownAll: no PluginRuntimeServices provided." + ); + } + log2.info("plugin-loader: shutting down all plugins"); + const { workerManager, jobScheduler } = runtimeServices; + jobScheduler.stop(); + await workerManager.stopAll(); + log2.info("plugin-loader: all plugins shut down"); + } + }; + async function activatePlugin(plugin) { + const manifest = plugin.manifestJson; + const pluginId = plugin.id; + const pluginKey = plugin.pluginKey; + const registered = { + worker: false, + eventSubscriptions: 0, + jobs: 0, + webhooks: 0, + tools: 0 + }; + if (!runtimeServices) { + return { + plugin, + success: false, + error: "No runtime services available", + registered + }; + } + const { + workerManager, + eventBus, + jobScheduler, + jobStore, + toolDispatcher, + lifecycleManager, + buildHostHandlers, + instanceInfo + } = runtimeServices; + try { + log2.info( + { pluginId, pluginKey, version: plugin.version }, + "plugin-loader: activating plugin" + ); + const workerEntrypoint = resolveWorkerEntrypoint(plugin, localPluginDir); + const hostHandlers = buildHostHandlers(pluginId, manifest); + let config3 = {}; + try { + const configRow = await registry2.getConfig(pluginId); + if (configRow && typeof configRow === "object" && "configJson" in configRow) { + config3 = configRow.configJson ?? {}; + } + } catch { + log2.debug({ pluginId }, "plugin-loader: no config found, using empty config"); + } + const workerOptions = { + entrypointPath: workerEntrypoint, + manifest, + config: config3, + instanceInfo, + apiVersion: manifest.apiVersion, + hostHandlers, + autoRestart: true + }; + if (plugin.packagePath && existsSync5(DEV_TSX_LOADER_PATH)) { + workerOptions.execArgv = ["--import", DEV_TSX_LOADER_PATH]; + } + await workerManager.startWorker(pluginId, workerOptions); + registered.worker = true; + log2.info( + { pluginId, pluginKey }, + "plugin-loader: worker started" + ); + const jobDeclarations = manifest.jobs ?? []; + if (jobDeclarations.length > 0) { + await jobStore.syncJobDeclarations(pluginId, jobDeclarations); + await jobScheduler.registerPlugin(pluginId); + registered.jobs = jobDeclarations.length; + log2.info( + { pluginId, pluginKey, jobs: jobDeclarations.length }, + "plugin-loader: job declarations synced and plugin registered with scheduler" + ); + } + const _scopedBus = eventBus.forPlugin(pluginKey); + registered.eventSubscriptions = eventBus.subscriptionCount(pluginKey); + log2.debug( + { pluginId, pluginKey }, + "plugin-loader: event bus scoped handle ready" + ); + const webhookDeclarations = manifest.webhooks ?? []; + registered.webhooks = webhookDeclarations.length; + if (webhookDeclarations.length > 0) { + log2.info( + { pluginId, pluginKey, webhooks: webhookDeclarations.length }, + "plugin-loader: webhook endpoints declared in manifest" + ); + } + const toolDeclarations = manifest.tools ?? []; + if (toolDeclarations.length > 0) { + toolDispatcher.registerPluginTools(pluginKey, manifest); + registered.tools = toolDeclarations.length; + log2.info( + { pluginId, pluginKey, tools: toolDeclarations.length }, + "plugin-loader: agent tools registered" + ); + } + log2.info( + { + pluginId, + pluginKey, + version: plugin.version, + registered + }, + "plugin-loader: plugin activated successfully" + ); + return { plugin, success: true, registered }; + } catch (err) { + const errorMessage = err instanceof Error ? err.message : String(err); + log2.error( + { pluginId, pluginKey, err: errorMessage }, + "plugin-loader: failed to activate plugin" + ); + try { + await lifecycleManager.markError(pluginId, `Activation failed: ${errorMessage}`); + } catch (markErr) { + log2.error( + { + pluginId, + err: markErr instanceof Error ? markErr.message : String(markErr) + }, + "plugin-loader: failed to mark plugin as error after activation failure" + ); + } + return { + plugin, + success: false, + error: errorMessage, + registered + }; + } + } +} +function resolveWorkerEntrypoint(plugin, localPluginDir) { + const manifest = plugin.manifestJson; + const workerRelPath = manifest.entrypoints.worker; + if (plugin.packagePath && existsSync5(plugin.packagePath)) { + const entrypoint = path46.resolve(plugin.packagePath, workerRelPath); + if (entrypoint.startsWith(path46.resolve(plugin.packagePath)) && existsSync5(entrypoint)) { + return entrypoint; + } + } + const packageName = plugin.packageName; + let packageDir; + if (packageName.startsWith("@")) { + const [scope, name] = packageName.split("/"); + packageDir = path46.join(localPluginDir, "node_modules", scope, name); + } else { + packageDir = path46.join(localPluginDir, "node_modules", packageName); + } + const directDir = path46.join(localPluginDir, packageName); + for (const dir of [packageDir, directDir]) { + const entrypoint = path46.resolve(dir, workerRelPath); + if (!entrypoint.startsWith(path46.resolve(dir))) { + continue; + } + if (existsSync5(entrypoint)) { + return entrypoint; + } + } + if (path46.isAbsolute(workerRelPath) && existsSync5(workerRelPath)) { + return workerRelPath; + } + throw new Error( + `Worker entrypoint not found for plugin "${plugin.pluginKey}". Checked: ${path46.resolve(packageDir, workerRelPath)}, ${path46.resolve(directDir, workerRelPath)}` + ); +} +function resolveManagedInstallPackageDir(localPluginDir, packageName) { + if (packageName.startsWith("@")) { + return path46.join(localPluginDir, "node_modules", ...packageName.split("/")); + } + return path46.join(localPluginDir, "node_modules", packageName); +} +function isPathInsideDir(candidatePath, parentDir) { + const resolvedCandidate = path46.resolve(candidatePath); + const resolvedParent = path46.resolve(parentDir); + const relative3 = path46.relative(resolvedParent, resolvedCandidate); + return relative3 === "" || !relative3.startsWith("..") && !path46.isAbsolute(relative3); +} + +// server/src/services/plugin-lifecycle.ts +var VALID_TRANSITIONS = { + installed: ["ready", "error", "uninstalled"], + ready: ["ready", "disabled", "error", "upgrade_pending", "uninstalled"], + disabled: ["ready", "uninstalled"], + error: ["ready", "uninstalled"], + upgrade_pending: ["ready", "error", "uninstalled"], + uninstalled: ["installed"] + // reinstall +}; +function isValidTransition(from, to) { + return VALID_TRANSITIONS[from]?.includes(to) ?? false; +} +function pluginLifecycleManager(db, options) { + let loaderArg; + let workerManager; + if (options && typeof options === "object" && "discoverAll" in options) { + loaderArg = options; + } else if (options && typeof options === "object") { + const opts = options; + loaderArg = opts.loader; + workerManager = opts.workerManager; + } + const registry2 = pluginRegistryService(db); + const pluginLoaderInstance = loaderArg ?? pluginLoader(db); + const emitter2 = new EventEmitter2(); + emitter2.setMaxListeners(100); + const log2 = logger.child({ service: "plugin-lifecycle" }); + async function requirePlugin(pluginId) { + const plugin = await registry2.getById(pluginId); + if (!plugin) throw notFound(`Plugin not found: ${pluginId}`); + return plugin; + } + function assertTransition2(plugin, to) { + if (!isValidTransition(plugin.status, to)) { + throw badRequest( + `Invalid lifecycle transition: ${plugin.status} \u2192 ${to} for plugin ${plugin.pluginKey}` + ); + } + } + async function transition(pluginId, to, lastError = null, existingPlugin) { + const plugin = existingPlugin ?? await requirePlugin(pluginId); + assertTransition2(plugin, to); + const previousStatus = plugin.status; + const updated = await registry2.updateStatus(pluginId, { + status: to, + lastError + }); + if (!updated) throw notFound(`Plugin not found after status update: ${pluginId}`); + const result = updated; + log2.info( + { pluginId, pluginKey: result.pluginKey, from: previousStatus, to }, + `plugin lifecycle: ${previousStatus} \u2192 ${to}` + ); + emitter2.emit("plugin.status_changed", { + pluginId, + pluginKey: result.pluginKey, + previousStatus, + newStatus: to + }); + return result; + } + function emitDomain(event, payload2) { + emitter2.emit(event, payload2); + } + async function stopWorkerIfRunning(pluginId, pluginKey) { + if (!workerManager) return; + if (!workerManager.isRunning(pluginId) && !workerManager.getWorker(pluginId)) return; + try { + await workerManager.stopWorker(pluginId); + log2.info({ pluginId, pluginKey }, "plugin lifecycle: worker stopped"); + emitDomain("plugin.worker_stopped", { pluginId, pluginKey }); + } catch (err) { + log2.warn( + { pluginId, pluginKey, err: err instanceof Error ? err.message : String(err) }, + "plugin lifecycle: failed to stop worker (best-effort)" + ); + } + } + async function activateReadyPlugin(pluginId) { + const supportsRuntimeActivation = typeof pluginLoaderInstance.hasRuntimeServices === "function" && typeof pluginLoaderInstance.loadSingle === "function"; + if (!supportsRuntimeActivation || !pluginLoaderInstance.hasRuntimeServices()) { + return; + } + const loadResult = await pluginLoaderInstance.loadSingle(pluginId); + if (!loadResult.success) { + throw new Error( + loadResult.error ?? `Failed to activate plugin ${loadResult.plugin.pluginKey}` + ); + } + } + async function deactivatePluginRuntime(pluginId, pluginKey) { + const supportsRuntimeDeactivation = typeof pluginLoaderInstance.hasRuntimeServices === "function" && typeof pluginLoaderInstance.unloadSingle === "function"; + if (supportsRuntimeDeactivation && pluginLoaderInstance.hasRuntimeServices()) { + await pluginLoaderInstance.unloadSingle(pluginId, pluginKey); + return; + } + await stopWorkerIfRunning(pluginId, pluginKey); + } + return { + // -- load ------------------------------------------------------------- + /** + * load — Transitions a plugin to 'ready' status and starts its worker. + * + * This method is called after a plugin has been successfully installed and + * validated. It marks the plugin as ready in the database and immediately + * triggers the plugin loader to start the worker process. + * + * @param pluginId - The UUID of the plugin to load. + * @returns The updated plugin record. + */ + async load(pluginId) { + const result = await transition(pluginId, "ready"); + await activateReadyPlugin(pluginId); + emitDomain("plugin.loaded", { + pluginId, + pluginKey: result.pluginKey + }); + emitDomain("plugin.enabled", { + pluginId, + pluginKey: result.pluginKey + }); + return result; + }, + // -- enable ----------------------------------------------------------- + /** + * enable — Re-enables a plugin that was previously in an error or upgrade state. + * + * Similar to load(), this method transitions the plugin to 'ready' and starts + * its worker, but it specifically targets plugins that are currently disabled. + * + * @param pluginId - The UUID of the plugin to enable. + * @returns The updated plugin record. + */ + async enable(pluginId) { + const plugin = await requirePlugin(pluginId); + if (plugin.status !== "disabled" && plugin.status !== "error" && plugin.status !== "upgrade_pending") { + throw badRequest( + `Cannot enable plugin in status '${plugin.status}'. Plugin must be in 'disabled', 'error', or 'upgrade_pending' status to be enabled.` + ); + } + const result = await transition(pluginId, "ready", null, plugin); + await activateReadyPlugin(pluginId); + emitDomain("plugin.enabled", { + pluginId, + pluginKey: result.pluginKey + }); + return result; + }, + // -- disable ---------------------------------------------------------- + async disable(pluginId, reason) { + const plugin = await requirePlugin(pluginId); + if (plugin.status !== "ready") { + throw badRequest( + `Cannot disable plugin in status '${plugin.status}'. Plugin must be in 'ready' status to be disabled.` + ); + } + await deactivatePluginRuntime(pluginId, plugin.pluginKey); + const result = await transition(pluginId, "disabled", reason ?? null, plugin); + emitDomain("plugin.disabled", { + pluginId, + pluginKey: result.pluginKey, + reason + }); + return result; + }, + // -- unload ----------------------------------------------------------- + async unload(pluginId, removeData = false) { + const plugin = await requirePlugin(pluginId); + if (plugin.status === "uninstalled") { + if (removeData) { + await pluginLoaderInstance.cleanupInstallArtifacts(plugin); + const deleted = await registry2.uninstall(pluginId, true); + log2.info( + { pluginId, pluginKey: plugin.pluginKey }, + "plugin lifecycle: hard-deleted already-uninstalled plugin" + ); + emitDomain("plugin.unloaded", { + pluginId, + pluginKey: plugin.pluginKey, + removeData: true + }); + return deleted; + } + throw badRequest( + `Plugin ${plugin.pluginKey} is already uninstalled. Use removeData=true to permanently delete it.` + ); + } + await deactivatePluginRuntime(pluginId, plugin.pluginKey); + await pluginLoaderInstance.cleanupInstallArtifacts(plugin); + const result = await registry2.uninstall(pluginId, removeData); + log2.info( + { pluginId, pluginKey: plugin.pluginKey, removeData }, + `plugin lifecycle: ${plugin.status} \u2192 uninstalled${removeData ? " (hard delete)" : ""}` + ); + emitter2.emit("plugin.status_changed", { + pluginId, + pluginKey: plugin.pluginKey, + previousStatus: plugin.status, + newStatus: "uninstalled" + }); + emitDomain("plugin.unloaded", { + pluginId, + pluginKey: plugin.pluginKey, + removeData + }); + return result; + }, + // -- markError -------------------------------------------------------- + async markError(pluginId, error50) { + const plugin = await requirePlugin(pluginId); + await deactivatePluginRuntime(pluginId, plugin.pluginKey); + const result = await transition(pluginId, "error", error50, plugin); + emitDomain("plugin.error", { + pluginId, + pluginKey: result.pluginKey, + error: error50 + }); + return result; + }, + // -- markUpgradePending ----------------------------------------------- + async markUpgradePending(pluginId) { + const plugin = await requirePlugin(pluginId); + await deactivatePluginRuntime(pluginId, plugin.pluginKey); + const result = await transition(pluginId, "upgrade_pending", null, plugin); + emitDomain("plugin.upgrade_pending", { + pluginId, + pluginKey: result.pluginKey + }); + return result; + }, + // -- upgrade ---------------------------------------------------------- + /** + * Upgrade a plugin to a newer version by performing a package update and + * managing the lifecycle state transition. + * + * Following PLUGIN_SPEC.md §25.3, the upgrade process: + * 1. Stops the current worker process (if running). + * 2. Fetches and validates the new plugin package via the `PluginLoader`. + * 3. Compares the capabilities declared in the new manifest against the old one. + * 4. If new capabilities are added, transitions the plugin to `upgrade_pending` + * to await operator approval (worker stays stopped). + * 5. If no new capabilities are added, transitions the plugin back to `ready` + * with the updated version and manifest metadata. + * + * @param pluginId - The UUID of the plugin to upgrade. + * @param version - Optional target version specifier. + * @returns The updated `PluginRecord`. + * @throws {BadRequest} If the plugin is not in a ready or upgrade_pending state. + */ + async upgrade(pluginId, version3) { + const plugin = await requirePlugin(pluginId); + if (plugin.status !== "ready" && plugin.status !== "upgrade_pending") { + throw badRequest( + `Cannot upgrade plugin in status '${plugin.status}'. Plugin must be in 'ready' or 'upgrade_pending' status to be upgraded.` + ); + } + log2.info( + { pluginId, pluginKey: plugin.pluginKey, targetVersion: version3 }, + "plugin lifecycle: upgrade requested" + ); + await deactivatePluginRuntime(pluginId, plugin.pluginKey); + const { oldManifest, newManifest, discovered } = await pluginLoaderInstance.upgradePlugin(pluginId, { version: version3 }); + log2.info( + { + pluginId, + pluginKey: plugin.pluginKey, + oldVersion: oldManifest.version, + newVersion: newManifest.version + }, + "plugin lifecycle: package upgraded on disk" + ); + const addedCaps = newManifest.capabilities.filter( + (cap) => !oldManifest.capabilities.includes(cap) + ); + if (addedCaps.length > 0) { + log2.info( + { pluginId, pluginKey: plugin.pluginKey, addedCaps }, + "plugin lifecycle: new capabilities detected, transitioning to upgrade_pending" + ); + const result = await transition(pluginId, "upgrade_pending", null, plugin); + emitDomain("plugin.upgrade_pending", { + pluginId, + pluginKey: result.pluginKey + }); + return result; + } else { + const result = await transition(pluginId, "ready", null, { + ...plugin, + version: discovered.version, + manifestJson: newManifest + }); + await activateReadyPlugin(pluginId); + emitDomain("plugin.loaded", { + pluginId, + pluginKey: result.pluginKey + }); + emitDomain("plugin.enabled", { + pluginId, + pluginKey: result.pluginKey + }); + return result; + } + }, + // -- startWorker ------------------------------------------------------ + async startWorker(pluginId, options2) { + if (!workerManager) { + throw badRequest( + "Cannot start worker: no PluginWorkerManager is configured. Provide a workerManager option when constructing the lifecycle manager." + ); + } + const plugin = await requirePlugin(pluginId); + if (plugin.status !== "ready") { + throw badRequest( + `Cannot start worker for plugin in status '${plugin.status}'. Plugin must be in 'ready' status.` + ); + } + log2.info( + { pluginId, pluginKey: plugin.pluginKey }, + "plugin lifecycle: starting worker" + ); + await workerManager.startWorker(pluginId, options2); + emitDomain("plugin.worker_started", { + pluginId, + pluginKey: plugin.pluginKey + }); + log2.info( + { pluginId, pluginKey: plugin.pluginKey }, + "plugin lifecycle: worker started" + ); + }, + // -- stopWorker ------------------------------------------------------- + async stopWorker(pluginId) { + if (!workerManager) return; + const plugin = await requirePlugin(pluginId); + await stopWorkerIfRunning(pluginId, plugin.pluginKey); + }, + // -- restartWorker ---------------------------------------------------- + async restartWorker(pluginId) { + if (!workerManager) { + throw badRequest( + "Cannot restart worker: no PluginWorkerManager is configured." + ); + } + const plugin = await requirePlugin(pluginId); + if (plugin.status !== "ready") { + throw badRequest( + `Cannot restart worker for plugin in status '${plugin.status}'. Plugin must be in 'ready' status.` + ); + } + const handle = workerManager.getWorker(pluginId); + if (!handle) { + throw badRequest( + `Cannot restart worker for plugin "${plugin.pluginKey}": no worker is running.` + ); + } + log2.info( + { pluginId, pluginKey: plugin.pluginKey }, + "plugin lifecycle: restarting worker" + ); + await handle.restart(); + emitDomain("plugin.worker_stopped", { pluginId, pluginKey: plugin.pluginKey }); + emitDomain("plugin.worker_started", { pluginId, pluginKey: plugin.pluginKey }); + log2.info( + { pluginId, pluginKey: plugin.pluginKey }, + "plugin lifecycle: worker restarted" + ); + }, + // -- getStatus -------------------------------------------------------- + async getStatus(pluginId) { + const plugin = await registry2.getById(pluginId); + return plugin?.status ?? null; + }, + // -- canTransition ---------------------------------------------------- + async canTransition(pluginId, to) { + const plugin = await registry2.getById(pluginId); + if (!plugin) return false; + return isValidTransition(plugin.status, to); + }, + // -- Event subscriptions ---------------------------------------------- + on(event, listener) { + emitter2.on(event, listener); + }, + off(event, listener) { + emitter2.off(event, listener); + }, + once(event, listener) { + emitter2.once(event, listener); + } + }; +} + +// packages/plugins/sdk/dist/protocol.js +var JSONRPC_VERSION = "2.0"; +var JSONRPC_ERROR_CODES = { + /** Invalid JSON was received by the server. */ + PARSE_ERROR: -32700, + /** The JSON sent is not a valid Request object. */ + INVALID_REQUEST: -32600, + /** The method does not exist or is not available. */ + METHOD_NOT_FOUND: -32601, + /** Invalid method parameter(s). */ + INVALID_PARAMS: -32602, + /** Internal JSON-RPC error. */ + INTERNAL_ERROR: -32603 +}; +var PLUGIN_RPC_ERROR_CODES = { + /** The worker process is not running or not reachable. */ + WORKER_UNAVAILABLE: -32e3, + /** The plugin does not have the required capability for this operation. */ + CAPABILITY_DENIED: -32001, + /** The worker reported an unhandled error during method execution. */ + WORKER_ERROR: -32002, + /** The method call timed out waiting for the worker response. */ + TIMEOUT: -32003, + /** The worker does not implement the requested optional method. */ + METHOD_NOT_IMPLEMENTED: -32004, + /** A catch-all for errors that do not fit other categories. */ + UNKNOWN: -32099 +}; +var _nextId = 1; +var MAX_SAFE_RPC_ID = Number.MAX_SAFE_INTEGER - 1; +function createRequest(method, params, id) { + if (_nextId >= MAX_SAFE_RPC_ID) { + _nextId = 1; + } + return { + jsonrpc: JSONRPC_VERSION, + id: id ?? _nextId++, + method, + params + }; +} +function createErrorResponse(id, code, message2, data2) { + const response = { + jsonrpc: JSONRPC_VERSION, + id, + error: data2 !== void 0 ? { code, message: message2, data: data2 } : { code, message: message2 } + }; + return response; +} +function isJsonRpcRequest(value) { + if (typeof value !== "object" || value === null) + return false; + const obj = value; + return obj.jsonrpc === JSONRPC_VERSION && typeof obj.method === "string" && "id" in obj && obj.id !== void 0 && obj.id !== null; +} +function isJsonRpcNotification(value) { + if (typeof value !== "object" || value === null) + return false; + const obj = value; + return obj.jsonrpc === JSONRPC_VERSION && typeof obj.method === "string" && !("id" in obj); +} +function isJsonRpcResponse(value) { + if (typeof value !== "object" || value === null) + return false; + const obj = value; + return obj.jsonrpc === JSONRPC_VERSION && "id" in obj && ("result" in obj || "error" in obj); +} +function isJsonRpcSuccessResponse(response) { + return "result" in response && !("error" in response && response.error !== void 0); +} +var MESSAGE_DELIMITER = "\n"; +function serializeMessage(message2) { + return JSON.stringify(message2) + MESSAGE_DELIMITER; +} +function parseMessage(line3) { + const trimmed = line3.trim(); + if (trimmed.length === 0) { + throw new JsonRpcParseError("Empty message"); + } + let parsed; + try { + parsed = JSON.parse(trimmed); + } catch { + throw new JsonRpcParseError(`Invalid JSON: ${trimmed.slice(0, 200)}`); + } + if (typeof parsed !== "object" || parsed === null) { + throw new JsonRpcParseError("Message must be a JSON object"); + } + const obj = parsed; + if (obj.jsonrpc !== JSONRPC_VERSION) { + throw new JsonRpcParseError(`Invalid or missing jsonrpc version (expected "${JSONRPC_VERSION}", got ${JSON.stringify(obj.jsonrpc)})`); + } + return parsed; +} +var JsonRpcParseError = class extends Error { + name = "JsonRpcParseError"; + constructor(message2) { + super(message2); + } +}; +var JsonRpcCallError = class extends Error { + name = "JsonRpcCallError"; + /** The JSON-RPC error code. */ + code; + /** Optional structured error data from the response. */ + data; + constructor(error50) { + super(error50.message); + this.code = error50.code; + this.data = error50.data; + } +}; + +// packages/plugins/sdk/dist/host-client-factory.js +var CapabilityDeniedError = class extends Error { + name = "CapabilityDeniedError"; + code = PLUGIN_RPC_ERROR_CODES.CAPABILITY_DENIED; + constructor(pluginId, method, capability) { + super(`Plugin "${pluginId}" is missing required capability "${capability}" for method "${method}"`); + } +}; +var METHOD_CAPABILITY_MAP = { + // Config — always allowed + "config.get": null, + // State + "state.get": "plugin.state.read", + "state.set": "plugin.state.write", + "state.delete": "plugin.state.write", + // Entities — no specific capability required (plugin-scoped by design) + "entities.upsert": null, + "entities.list": null, + // Events + "events.emit": "events.emit", + "events.subscribe": "events.subscribe", + // HTTP + "http.fetch": "http.outbound", + // Secrets + "secrets.resolve": "secrets.read-ref", + // Activity + "activity.log": "activity.log.write", + // Metrics + "metrics.write": "metrics.write", + // Telemetry + "telemetry.track": "telemetry.track", + // Logger — always allowed + "log": null, + // Companies + "companies.list": "companies.read", + "companies.get": "companies.read", + // Projects + "projects.list": "projects.read", + "projects.get": "projects.read", + "projects.listWorkspaces": "project.workspaces.read", + "projects.getPrimaryWorkspace": "project.workspaces.read", + "projects.getWorkspaceForIssue": "project.workspaces.read", + // Issues + "issues.list": "issues.read", + "issues.get": "issues.read", + "issues.create": "issues.create", + "issues.update": "issues.update", + "issues.listComments": "issue.comments.read", + "issues.createComment": "issue.comments.create", + // Issue Documents + "issues.documents.list": "issue.documents.read", + "issues.documents.get": "issue.documents.read", + "issues.documents.upsert": "issue.documents.write", + "issues.documents.delete": "issue.documents.write", + // Agents + "agents.list": "agents.read", + "agents.get": "agents.read", + "agents.pause": "agents.pause", + "agents.resume": "agents.resume", + "agents.invoke": "agents.invoke", + // Agent Sessions + "agents.sessions.create": "agent.sessions.create", + "agents.sessions.list": "agent.sessions.list", + "agents.sessions.sendMessage": "agent.sessions.send", + "agents.sessions.close": "agent.sessions.close", + // Goals + "goals.list": "goals.read", + "goals.get": "goals.read", + "goals.create": "goals.create", + "goals.update": "goals.update" +}; +function createHostClientHandlers(options) { + const { pluginId, services } = options; + const capabilitySet = new Set(options.capabilities); + function requireCapability(method) { + const required2 = METHOD_CAPABILITY_MAP[method]; + if (required2 === null) + return; + if (capabilitySet.has(required2)) + return; + throw new CapabilityDeniedError(pluginId, method, required2); + } + function gated(method, handler) { + return async (params) => { + requireCapability(method); + return handler(params); + }; + } + return { + // Config + "config.get": gated("config.get", async () => { + return services.config.get(); + }), + // State + "state.get": gated("state.get", async (params) => { + return services.state.get(params); + }), + "state.set": gated("state.set", async (params) => { + return services.state.set(params); + }), + "state.delete": gated("state.delete", async (params) => { + return services.state.delete(params); + }), + // Entities + "entities.upsert": gated("entities.upsert", async (params) => { + return services.entities.upsert(params); + }), + "entities.list": gated("entities.list", async (params) => { + return services.entities.list(params); + }), + // Events + "events.emit": gated("events.emit", async (params) => { + return services.events.emit(params); + }), + "events.subscribe": gated("events.subscribe", async (params) => { + return services.events.subscribe(params); + }), + // HTTP + "http.fetch": gated("http.fetch", async (params) => { + return services.http.fetch(params); + }), + // Secrets + "secrets.resolve": gated("secrets.resolve", async (params) => { + return services.secrets.resolve(params); + }), + // Activity + "activity.log": gated("activity.log", async (params) => { + return services.activity.log(params); + }), + // Metrics + "metrics.write": gated("metrics.write", async (params) => { + return services.metrics.write(params); + }), + // Telemetry + "telemetry.track": gated("telemetry.track", async (params) => { + return services.telemetry.track(params); + }), + // Logger + "log": gated("log", async (params) => { + return services.logger.log(params); + }), + // Companies + "companies.list": gated("companies.list", async (params) => { + return services.companies.list(params); + }), + "companies.get": gated("companies.get", async (params) => { + return services.companies.get(params); + }), + // Projects + "projects.list": gated("projects.list", async (params) => { + return services.projects.list(params); + }), + "projects.get": gated("projects.get", async (params) => { + return services.projects.get(params); + }), + "projects.listWorkspaces": gated("projects.listWorkspaces", async (params) => { + return services.projects.listWorkspaces(params); + }), + "projects.getPrimaryWorkspace": gated("projects.getPrimaryWorkspace", async (params) => { + return services.projects.getPrimaryWorkspace(params); + }), + "projects.getWorkspaceForIssue": gated("projects.getWorkspaceForIssue", async (params) => { + return services.projects.getWorkspaceForIssue(params); + }), + // Issues + "issues.list": gated("issues.list", async (params) => { + return services.issues.list(params); + }), + "issues.get": gated("issues.get", async (params) => { + return services.issues.get(params); + }), + "issues.create": gated("issues.create", async (params) => { + return services.issues.create(params); + }), + "issues.update": gated("issues.update", async (params) => { + return services.issues.update(params); + }), + "issues.listComments": gated("issues.listComments", async (params) => { + return services.issues.listComments(params); + }), + "issues.createComment": gated("issues.createComment", async (params) => { + return services.issues.createComment(params); + }), + // Issue Documents + "issues.documents.list": gated("issues.documents.list", async (params) => { + return services.issueDocuments.list(params); + }), + "issues.documents.get": gated("issues.documents.get", async (params) => { + return services.issueDocuments.get(params); + }), + "issues.documents.upsert": gated("issues.documents.upsert", async (params) => { + return services.issueDocuments.upsert(params); + }), + "issues.documents.delete": gated("issues.documents.delete", async (params) => { + return services.issueDocuments.delete(params); + }), + // Agents + "agents.list": gated("agents.list", async (params) => { + return services.agents.list(params); + }), + "agents.get": gated("agents.get", async (params) => { + return services.agents.get(params); + }), + "agents.pause": gated("agents.pause", async (params) => { + return services.agents.pause(params); + }), + "agents.resume": gated("agents.resume", async (params) => { + return services.agents.resume(params); + }), + "agents.invoke": gated("agents.invoke", async (params) => { + return services.agents.invoke(params); + }), + // Agent Sessions + "agents.sessions.create": gated("agents.sessions.create", async (params) => { + return services.agentSessions.create(params); + }), + "agents.sessions.list": gated("agents.sessions.list", async (params) => { + return services.agentSessions.list(params); + }), + "agents.sessions.sendMessage": gated("agents.sessions.sendMessage", async (params) => { + return services.agentSessions.sendMessage(params); + }), + "agents.sessions.close": gated("agents.sessions.close", async (params) => { + return services.agentSessions.close(params); + }), + // Goals + "goals.list": gated("goals.list", async (params) => { + return services.goals.list(params); + }), + "goals.get": gated("goals.get", async (params) => { + return services.goals.get(params); + }), + "goals.create": gated("goals.create", async (params) => { + return services.goals.create(params); + }), + "goals.update": gated("goals.update", async (params) => { + return services.goals.update(params); + }) + }; +} + +// server/src/services/plugin-config-validator.ts +var import_ajv = __toESM(require_ajv(), 1); +var import_ajv_formats = __toESM(require_dist2(), 1); +function validateInstanceConfig(configJson, schema2) { + const AjvCtor = import_ajv.default.default ?? import_ajv.default; + const ajv = new AjvCtor({ allErrors: true }); + const applyFormats = import_ajv_formats.default.default ?? import_ajv_formats.default; + applyFormats(ajv); + ajv.addFormat("secret-ref", { validate: () => true }); + const validate2 = ajv.compile(schema2); + const valid = validate2(configJson); + if (valid) { + return { valid: true }; + } + const errors = (validate2.errors ?? []).map((err) => ({ + field: err.instancePath || "/", + message: err.message ?? "validation failed" + })); + return { valid: false, errors }; +} + +// server/src/routes/plugins.ts +var UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i; +var __dirname3 = path47.dirname(fileURLToPath18(import.meta.url)); +var REPO_ROOT = path47.resolve(__dirname3, "../../.."); +var BUNDLED_PLUGIN_EXAMPLES = [ + { + packageName: "@taskcore/plugin-hello-world-example", + pluginKey: "taskcore.hello-world-example", + displayName: "Hello World Widget (Example)", + description: "Reference UI plugin that adds a simple Hello World widget to the Taskcore dashboard.", + localPath: "packages/plugins/examples/plugin-hello-world-example", + tag: "example" + }, + { + packageName: "@taskcore/plugin-file-browser-example", + pluginKey: "taskcore-file-browser-example", + displayName: "File Browser (Example)", + description: "Example plugin that adds a Files link in project navigation plus a project detail file browser.", + localPath: "packages/plugins/examples/plugin-file-browser-example", + tag: "example" + }, + { + packageName: "@taskcore/plugin-kitchen-sink-example", + pluginKey: "taskcore-kitchen-sink-example", + displayName: "Kitchen Sink (Example)", + description: "Reference plugin that demonstrates the current Taskcore plugin API surface, bridge flows, UI extension surfaces, jobs, webhooks, tools, streams, and trusted local workspace/process demos.", + localPath: "packages/plugins/examples/plugin-kitchen-sink-example", + tag: "example" + } +]; +function listBundledPluginExamples() { + return BUNDLED_PLUGIN_EXAMPLES.flatMap((plugin) => { + const absoluteLocalPath = path47.resolve(REPO_ROOT, plugin.localPath); + if (!existsSync6(absoluteLocalPath)) return []; + return [{ ...plugin, localPath: absoluteLocalPath }]; + }); +} +async function resolvePlugin(registry2, pluginId) { + const isUuid2 = UUID_REGEX.test(pluginId); + const isScopedPackageKey = pluginId.startsWith("@") || pluginId.includes("/"); + if (isScopedPackageKey && !isUuid2) { + return registry2.getByKey(pluginId); + } + try { + const byId = await registry2.getById(pluginId); + if (byId) return byId; + } catch (error50) { + const maybeCode = typeof error50 === "object" && error50 !== null && "code" in error50 ? error50.code : void 0; + if (maybeCode !== "22P02") { + throw error50; + } + } + return registry2.getByKey(pluginId); +} +function pluginRoutes(db, loader, jobDeps, webhookDeps, toolDeps, bridgeDeps) { + const router2 = (0, import_express22.Router)(); + const registry2 = pluginRegistryService(db); + const lifecycle = pluginLifecycleManager(db, { + loader, + workerManager: bridgeDeps?.workerManager ?? webhookDeps?.workerManager + }); + async function resolvePluginAuditCompanyIds(req) { + if (typeof db.select === "function") { + const rows = await db.select({ id: companies.id }).from(companies); + return rows.map((row) => row.id); + } + if (req.actor.type === "agent" && req.actor.companyId) { + return [req.actor.companyId]; + } + if (req.actor.type === "board") { + return req.actor.companyIds ?? []; + } + return []; + } + async function logPluginMutationActivity(req, action, entityId, details) { + const companyIds = await resolvePluginAuditCompanyIds(req); + if (companyIds.length === 0) return; + const actor = getActorInfo(req); + await Promise.all(companyIds.map((companyId) => logActivity(db, { + companyId, + actorType: actor.actorType, + actorId: actor.actorId, + agentId: actor.agentId, + runId: actor.runId, + action, + entityType: "plugin", + entityId, + details + }))); + } + router2.get("/plugins", async (req, res) => { + assertBoard(req); + const rawStatus = req.query.status; + if (rawStatus !== void 0) { + if (typeof rawStatus !== "string" || !PLUGIN_STATUSES.includes(rawStatus)) { + res.status(400).json({ + error: `Invalid status '${String(rawStatus)}'. Must be one of: ${PLUGIN_STATUSES.join(", ")}` + }); + return; + } + } + const status = rawStatus; + const plugins2 = status ? await registry2.listByStatus(status) : await registry2.listInstalled(); + res.json(plugins2); + }); + router2.get("/plugins/examples", async (req, res) => { + assertBoard(req); + res.json(listBundledPluginExamples()); + }); + router2.get("/plugins/ui-contributions", async (req, res) => { + assertBoard(req); + const plugins2 = await registry2.listByStatus("ready"); + const contributions = plugins2.map((plugin) => { + const manifest = plugin.manifestJson; + if (!manifest) return null; + const uiMetadata = getPluginUiContributionMetadata(manifest); + if (!uiMetadata) return null; + return { + pluginId: plugin.id, + pluginKey: plugin.pluginKey, + displayName: manifest.displayName, + version: plugin.version, + updatedAt: plugin.updatedAt.toISOString(), + uiEntryFile: uiMetadata.uiEntryFile, + slots: uiMetadata.slots, + launchers: uiMetadata.launchers + }; + }).filter((item) => item !== null); + res.json(contributions); + }); + router2.get("/plugins/tools", async (req, res) => { + assertBoard(req); + if (!toolDeps) { + res.status(501).json({ error: "Plugin tool dispatch is not enabled" }); + return; + } + const pluginId = req.query.pluginId; + const filter = pluginId ? { pluginId } : void 0; + const tools = toolDeps.toolDispatcher.listToolsForAgent(filter); + res.json(tools); + }); + router2.post("/plugins/tools/execute", async (req, res) => { + assertBoard(req); + if (!toolDeps) { + res.status(501).json({ error: "Plugin tool dispatch is not enabled" }); + return; + } + const body = req.body; + if (!body) { + res.status(400).json({ error: "Request body is required" }); + return; + } + const { tool, parameters, runContext } = body; + if (!tool || typeof tool !== "string") { + res.status(400).json({ error: '"tool" is required and must be a string' }); + return; + } + if (!runContext || typeof runContext !== "object") { + res.status(400).json({ error: '"runContext" is required and must be an object' }); + return; + } + if (!runContext.agentId || !runContext.runId || !runContext.companyId || !runContext.projectId) { + res.status(400).json({ + error: '"runContext" must include agentId, runId, companyId, and projectId' + }); + return; + } + assertCompanyAccess(req, runContext.companyId); + const registeredTool = toolDeps.toolDispatcher.getTool(tool); + if (!registeredTool) { + res.status(404).json({ error: `Tool "${tool}" not found` }); + return; + } + try { + const result = await toolDeps.toolDispatcher.executeTool( + tool, + parameters ?? {}, + runContext + ); + res.json(result); + } catch (err) { + const message2 = err instanceof Error ? err.message : String(err); + if (message2.includes("not running") || message2.includes("worker")) { + res.status(502).json({ error: message2 }); + } else { + res.status(500).json({ error: message2 }); + } + } + }); + router2.post("/plugins/install", async (req, res) => { + assertBoard(req); + const { packageName, version: version3, isLocalPath } = req.body; + if (!packageName || typeof packageName !== "string") { + res.status(400).json({ error: "packageName is required and must be a string" }); + return; + } + if (version3 !== void 0 && typeof version3 !== "string") { + res.status(400).json({ error: "version must be a string if provided" }); + return; + } + if (isLocalPath !== void 0 && typeof isLocalPath !== "boolean") { + res.status(400).json({ error: "isLocalPath must be a boolean if provided" }); + return; + } + const trimmedPackage = packageName.trim(); + if (trimmedPackage.length === 0) { + res.status(400).json({ error: "packageName cannot be empty" }); + return; + } + if (!isLocalPath && /[<>:"|?*]/.test(trimmedPackage)) { + res.status(400).json({ error: "packageName contains invalid characters" }); + return; + } + try { + const installOptions = isLocalPath ? { localPath: trimmedPackage } : { packageName: trimmedPackage, version: version3?.trim() }; + const discovered = await loader.installPlugin(installOptions); + if (!discovered.manifest) { + res.status(500).json({ error: "Plugin installed but manifest is missing" }); + return; + } + const existingPlugin = await registry2.getByKey(discovered.manifest.id); + if (existingPlugin) { + await lifecycle.load(existingPlugin.id); + const updated = await registry2.getById(existingPlugin.id); + await logPluginMutationActivity(req, "plugin.installed", existingPlugin.id, { + pluginId: existingPlugin.id, + pluginKey: existingPlugin.pluginKey, + packageName: updated?.packageName ?? existingPlugin.packageName, + version: updated?.version ?? existingPlugin.version, + source: isLocalPath ? "local_path" : "npm" + }); + publishGlobalLiveEvent({ type: "plugin.ui.updated", payload: { pluginId: existingPlugin.id, action: "installed" } }); + res.json(updated); + } else { + res.status(500).json({ error: "Plugin installed but not found in registry" }); + } + } catch (err) { + const message2 = err instanceof Error ? err.message : String(err); + res.status(400).json({ error: message2 }); + } + }); + function mapRpcErrorToBridgeError(err) { + if (err instanceof JsonRpcCallError) { + switch (err.code) { + case PLUGIN_RPC_ERROR_CODES.WORKER_UNAVAILABLE: + return { + code: "WORKER_UNAVAILABLE", + message: err.message, + details: err.data + }; + case PLUGIN_RPC_ERROR_CODES.CAPABILITY_DENIED: + return { + code: "CAPABILITY_DENIED", + message: err.message, + details: err.data + }; + case PLUGIN_RPC_ERROR_CODES.TIMEOUT: + return { + code: "TIMEOUT", + message: err.message, + details: err.data + }; + case PLUGIN_RPC_ERROR_CODES.WORKER_ERROR: + return { + code: "WORKER_ERROR", + message: err.message, + details: err.data + }; + default: + return { + code: "UNKNOWN", + message: err.message, + details: err.data + }; + } + } + const message2 = err instanceof Error ? err.message : String(err); + if (message2.includes("not running") || message2.includes("not registered")) { + return { + code: "WORKER_UNAVAILABLE", + message: message2 + }; + } + return { + code: "UNKNOWN", + message: message2 + }; + } + router2.post("/plugins/:pluginId/bridge/data", async (req, res) => { + assertBoard(req); + if (!bridgeDeps) { + res.status(501).json({ error: "Plugin bridge is not enabled" }); + return; + } + const { pluginId } = req.params; + const plugin = await resolvePlugin(registry2, pluginId); + if (!plugin) { + res.status(404).json({ error: "Plugin not found" }); + return; + } + if (plugin.status !== "ready") { + const bridgeError = { + code: "WORKER_UNAVAILABLE", + message: `Plugin is not ready (current status: ${plugin.status})` + }; + res.status(502).json(bridgeError); + return; + } + const body = req.body; + if (!body || !body.key || typeof body.key !== "string") { + res.status(400).json({ error: '"key" is required and must be a string' }); + return; + } + if (body.companyId) { + assertCompanyAccess(req, body.companyId); + } + try { + const result = await bridgeDeps.workerManager.call( + plugin.id, + "getData", + { + key: body.key, + params: body.params ?? {}, + renderEnvironment: body.renderEnvironment ?? null + } + ); + res.json({ data: result }); + } catch (err) { + const bridgeError = mapRpcErrorToBridgeError(err); + res.status(502).json(bridgeError); + } + }); + router2.post("/plugins/:pluginId/bridge/action", async (req, res) => { + assertBoard(req); + if (!bridgeDeps) { + res.status(501).json({ error: "Plugin bridge is not enabled" }); + return; + } + const { pluginId } = req.params; + const plugin = await resolvePlugin(registry2, pluginId); + if (!plugin) { + res.status(404).json({ error: "Plugin not found" }); + return; + } + if (plugin.status !== "ready") { + const bridgeError = { + code: "WORKER_UNAVAILABLE", + message: `Plugin is not ready (current status: ${plugin.status})` + }; + res.status(502).json(bridgeError); + return; + } + const body = req.body; + if (!body || !body.key || typeof body.key !== "string") { + res.status(400).json({ error: '"key" is required and must be a string' }); + return; + } + if (body.companyId) { + assertCompanyAccess(req, body.companyId); + } + try { + const result = await bridgeDeps.workerManager.call( + plugin.id, + "performAction", + { + key: body.key, + params: body.params ?? {}, + renderEnvironment: body.renderEnvironment ?? null + } + ); + res.json({ data: result }); + } catch (err) { + const bridgeError = mapRpcErrorToBridgeError(err); + res.status(502).json(bridgeError); + } + }); + router2.post("/plugins/:pluginId/data/:key", async (req, res) => { + assertBoard(req); + if (!bridgeDeps) { + res.status(501).json({ error: "Plugin bridge is not enabled" }); + return; + } + const { pluginId, key } = req.params; + const plugin = await resolvePlugin(registry2, pluginId); + if (!plugin) { + res.status(404).json({ error: "Plugin not found" }); + return; + } + if (plugin.status !== "ready") { + const bridgeError = { + code: "WORKER_UNAVAILABLE", + message: `Plugin is not ready (current status: ${plugin.status})` + }; + res.status(502).json(bridgeError); + return; + } + const body = req.body; + if (body?.companyId) { + assertCompanyAccess(req, body.companyId); + } + try { + const result = await bridgeDeps.workerManager.call( + plugin.id, + "getData", + { + key, + params: body?.params ?? {}, + renderEnvironment: body?.renderEnvironment ?? null + } + ); + res.json({ data: result }); + } catch (err) { + const bridgeError = mapRpcErrorToBridgeError(err); + res.status(502).json(bridgeError); + } + }); + router2.post("/plugins/:pluginId/actions/:key", async (req, res) => { + assertBoard(req); + if (!bridgeDeps) { + res.status(501).json({ error: "Plugin bridge is not enabled" }); + return; + } + const { pluginId, key } = req.params; + const plugin = await resolvePlugin(registry2, pluginId); + if (!plugin) { + res.status(404).json({ error: "Plugin not found" }); + return; + } + if (plugin.status !== "ready") { + const bridgeError = { + code: "WORKER_UNAVAILABLE", + message: `Plugin is not ready (current status: ${plugin.status})` + }; + res.status(502).json(bridgeError); + return; + } + const body = req.body; + if (body?.companyId) { + assertCompanyAccess(req, body.companyId); + } + try { + const result = await bridgeDeps.workerManager.call( + plugin.id, + "performAction", + { + key, + params: body?.params ?? {}, + renderEnvironment: body?.renderEnvironment ?? null + } + ); + res.json({ data: result }); + } catch (err) { + const bridgeError = mapRpcErrorToBridgeError(err); + res.status(502).json(bridgeError); + } + }); + router2.get("/plugins/:pluginId/bridge/stream/:channel", async (req, res) => { + assertBoard(req); + if (!bridgeDeps?.streamBus) { + res.status(501).json({ error: "Plugin stream bridge is not enabled" }); + return; + } + const { pluginId, channel } = req.params; + const companyId = req.query.companyId; + if (!companyId) { + res.status(400).json({ error: '"companyId" query parameter is required' }); + return; + } + const plugin = await resolvePlugin(registry2, pluginId); + if (!plugin) { + res.status(404).json({ error: "Plugin not found" }); + return; + } + assertCompanyAccess(req, companyId); + res.writeHead(200, { + "Content-Type": "text/event-stream", + "Cache-Control": "no-cache", + "Connection": "keep-alive", + "X-Accel-Buffering": "no" + }); + res.flushHeaders(); + res.write(":ok\n\n"); + let unsubscribed = false; + const safeUnsubscribe = () => { + if (!unsubscribed) { + unsubscribed = true; + unsubscribe(); + } + }; + const unsubscribe = bridgeDeps.streamBus.subscribe( + plugin.id, + channel, + companyId, + (event, eventType) => { + if (unsubscribed || !res.writable) return; + try { + if (eventType !== "message") { + res.write(`event: ${eventType} +`); + } + res.write(`data: ${JSON.stringify(event)} + +`); + } catch { + safeUnsubscribe(); + } + } + ); + req.on("close", safeUnsubscribe); + res.on("error", safeUnsubscribe); + }); + router2.get("/plugins/:pluginId", async (req, res) => { + assertBoard(req); + const { pluginId } = req.params; + const plugin = await resolvePlugin(registry2, pluginId); + if (!plugin) { + res.status(404).json({ error: "Plugin not found" }); + return; + } + const worker = bridgeDeps?.workerManager.getWorker(plugin.id); + const supportsConfigTest = worker ? worker.supportedMethods.includes("validateConfig") : false; + res.json({ ...plugin, supportsConfigTest }); + }); + router2.delete("/plugins/:pluginId", async (req, res) => { + assertBoard(req); + const { pluginId } = req.params; + const purge = req.query.purge === "true"; + const plugin = await resolvePlugin(registry2, pluginId); + if (!plugin) { + res.status(404).json({ error: "Plugin not found" }); + return; + } + try { + const result = await lifecycle.unload(plugin.id, purge); + await logPluginMutationActivity(req, "plugin.uninstalled", plugin.id, { + pluginId: plugin.id, + pluginKey: plugin.pluginKey, + purge + }); + publishGlobalLiveEvent({ type: "plugin.ui.updated", payload: { pluginId: plugin.id, action: "uninstalled" } }); + res.json(result); + } catch (err) { + const message2 = err instanceof Error ? err.message : String(err); + res.status(400).json({ error: message2 }); + } + }); + router2.post("/plugins/:pluginId/enable", async (req, res) => { + assertBoard(req); + const { pluginId } = req.params; + const plugin = await resolvePlugin(registry2, pluginId); + if (!plugin) { + res.status(404).json({ error: "Plugin not found" }); + return; + } + try { + const result = await lifecycle.enable(plugin.id); + await logPluginMutationActivity(req, "plugin.enabled", plugin.id, { + pluginId: plugin.id, + pluginKey: plugin.pluginKey, + version: result?.version ?? plugin.version + }); + publishGlobalLiveEvent({ type: "plugin.ui.updated", payload: { pluginId: plugin.id, action: "enabled" } }); + res.json(result); + } catch (err) { + const message2 = err instanceof Error ? err.message : String(err); + res.status(400).json({ error: message2 }); + } + }); + router2.post("/plugins/:pluginId/disable", async (req, res) => { + assertBoard(req); + const { pluginId } = req.params; + const body = req.body; + const reason = body?.reason; + const plugin = await resolvePlugin(registry2, pluginId); + if (!plugin) { + res.status(404).json({ error: "Plugin not found" }); + return; + } + try { + const result = await lifecycle.disable(plugin.id, reason); + await logPluginMutationActivity(req, "plugin.disabled", plugin.id, { + pluginId: plugin.id, + pluginKey: plugin.pluginKey, + reason: reason ?? null + }); + publishGlobalLiveEvent({ type: "plugin.ui.updated", payload: { pluginId: plugin.id, action: "disabled" } }); + res.json(result); + } catch (err) { + const message2 = err instanceof Error ? err.message : String(err); + res.status(400).json({ error: message2 }); + } + }); + router2.get("/plugins/:pluginId/health", async (req, res) => { + assertBoard(req); + const { pluginId } = req.params; + const plugin = await resolvePlugin(registry2, pluginId); + if (!plugin) { + res.status(404).json({ error: "Plugin not found" }); + return; + } + const checks = []; + checks.push({ + name: "registry", + passed: true, + message: "Plugin found in registry" + }); + const hasValidManifest = Boolean(plugin.manifestJson?.id); + checks.push({ + name: "manifest", + passed: hasValidManifest, + message: hasValidManifest ? "Manifest is valid" : "Manifest is invalid or missing" + }); + const isHealthy = plugin.status === "ready"; + checks.push({ + name: "status", + passed: isHealthy, + message: `Current status: ${plugin.status}` + }); + const hasNoError = !plugin.lastError; + if (!hasNoError) { + checks.push({ + name: "error_state", + passed: false, + message: plugin.lastError ?? void 0 + }); + } + const result = { + pluginId: plugin.id, + status: plugin.status, + healthy: isHealthy && hasValidManifest && hasNoError, + checks, + lastError: plugin.lastError ?? void 0 + }; + res.json(result); + }); + router2.get("/plugins/:pluginId/logs", async (req, res) => { + assertBoard(req); + const { pluginId } = req.params; + const plugin = await resolvePlugin(registry2, pluginId); + if (!plugin) { + res.status(404).json({ error: "Plugin not found" }); + return; + } + const limit = Math.min(Math.max(parseInt(req.query.limit, 10) || 25, 1), 500); + const level = req.query.level; + const since = req.query.since; + const conditions = [eq(pluginLogs.pluginId, plugin.id)]; + if (level) { + conditions.push(eq(pluginLogs.level, level)); + } + if (since) { + const sinceDate = new Date(since); + if (!isNaN(sinceDate.getTime())) { + conditions.push(gte(pluginLogs.createdAt, sinceDate)); + } + } + const rows = await db.select().from(pluginLogs).where(and(...conditions)).orderBy(desc(pluginLogs.createdAt)).limit(limit); + res.json(rows); + }); + router2.post("/plugins/:pluginId/upgrade", async (req, res) => { + assertBoard(req); + const { pluginId } = req.params; + const body = req.body; + const version3 = body?.version; + const plugin = await resolvePlugin(registry2, pluginId); + if (!plugin) { + res.status(404).json({ error: "Plugin not found" }); + return; + } + try { + const result = await lifecycle.upgrade(plugin.id, version3); + await logPluginMutationActivity(req, "plugin.upgraded", plugin.id, { + pluginId: plugin.id, + pluginKey: plugin.pluginKey, + previousVersion: plugin.version, + version: result?.version ?? plugin.version, + targetVersion: version3 ?? null + }); + publishGlobalLiveEvent({ type: "plugin.ui.updated", payload: { pluginId: plugin.id, action: "upgraded" } }); + res.json(result); + } catch (err) { + const message2 = err instanceof Error ? err.message : String(err); + res.status(400).json({ error: message2 }); + } + }); + router2.get("/plugins/:pluginId/config", async (req, res) => { + assertBoard(req); + const { pluginId } = req.params; + const plugin = await resolvePlugin(registry2, pluginId); + if (!plugin) { + res.status(404).json({ error: "Plugin not found" }); + return; + } + const config3 = await registry2.getConfig(plugin.id); + res.json(config3); + }); + router2.post("/plugins/:pluginId/config", async (req, res) => { + assertBoard(req); + const { pluginId } = req.params; + const plugin = await resolvePlugin(registry2, pluginId); + if (!plugin) { + res.status(404).json({ error: "Plugin not found" }); + return; + } + const body = req.body; + if (!body?.configJson || typeof body.configJson !== "object") { + res.status(400).json({ error: '"configJson" is required and must be an object' }); + return; + } + if ("devUiUrl" in body.configJson && !(req.actor.type === "board" && req.actor.isInstanceAdmin)) { + delete body.configJson.devUiUrl; + } + const schema2 = plugin.manifestJson?.instanceConfigSchema; + if (schema2 && Object.keys(schema2).length > 0) { + const validation = validateInstanceConfig(body.configJson, schema2); + if (!validation.valid) { + res.status(400).json({ + error: "Configuration does not match the plugin's instanceConfigSchema", + fieldErrors: validation.errors + }); + return; + } + } + try { + const result = await registry2.upsertConfig(plugin.id, { + configJson: body.configJson + }); + await logPluginMutationActivity(req, "plugin.config.updated", plugin.id, { + pluginId: plugin.id, + pluginKey: plugin.pluginKey, + configKeyCount: Object.keys(body.configJson).length + }); + if (bridgeDeps?.workerManager.isRunning(plugin.id)) { + try { + await bridgeDeps.workerManager.call( + plugin.id, + "configChanged", + { config: body.configJson } + ); + } catch (rpcErr) { + if (rpcErr instanceof JsonRpcCallError && rpcErr.code === PLUGIN_RPC_ERROR_CODES.METHOD_NOT_IMPLEMENTED) { + try { + await lifecycle.restartWorker(plugin.id); + } catch { + } + } + } + } + res.json(result); + } catch (err) { + const message2 = err instanceof Error ? err.message : String(err); + res.status(400).json({ error: message2 }); + } + }); + router2.post("/plugins/:pluginId/config/test", async (req, res) => { + assertBoard(req); + if (!bridgeDeps) { + res.status(501).json({ error: "Plugin bridge is not enabled" }); + return; + } + const { pluginId } = req.params; + const plugin = await resolvePlugin(registry2, pluginId); + if (!plugin) { + res.status(404).json({ error: "Plugin not found" }); + return; + } + if (plugin.status !== "ready") { + res.status(400).json({ + error: `Plugin is not ready (current status: ${plugin.status})` + }); + return; + } + const body = req.body; + if (!body?.configJson || typeof body.configJson !== "object") { + res.status(400).json({ error: '"configJson" is required and must be an object' }); + return; + } + const schema2 = plugin.manifestJson?.instanceConfigSchema; + if (schema2 && Object.keys(schema2).length > 0) { + const validation = validateInstanceConfig(body.configJson, schema2); + if (!validation.valid) { + res.status(400).json({ + error: "Configuration does not match the plugin's instanceConfigSchema", + fieldErrors: validation.errors + }); + return; + } + } + try { + const result = await bridgeDeps.workerManager.call( + plugin.id, + "validateConfig", + { config: body.configJson } + ); + if (result.ok) { + const warningText = result.warnings?.length ? `Warnings: ${result.warnings.join("; ")}` : void 0; + res.json({ valid: true, message: warningText }); + } else { + const errorText2 = result.errors?.length ? result.errors.join("; ") : "Configuration validation failed."; + res.json({ valid: false, message: errorText2 }); + } + } catch (err) { + if (err instanceof JsonRpcCallError && err.code === PLUGIN_RPC_ERROR_CODES.METHOD_NOT_IMPLEMENTED) { + res.json({ + valid: false, + supported: false, + message: "This plugin does not support configuration testing." + }); + return; + } + const bridgeError = mapRpcErrorToBridgeError(err); + res.status(502).json(bridgeError); + } + }); + router2.get("/plugins/:pluginId/jobs", async (req, res) => { + assertBoard(req); + if (!jobDeps) { + res.status(501).json({ error: "Job scheduling is not enabled" }); + return; + } + const { pluginId } = req.params; + const plugin = await resolvePlugin(registry2, pluginId); + if (!plugin) { + res.status(404).json({ error: "Plugin not found" }); + return; + } + const rawStatus = req.query.status; + const validStatuses = ["active", "paused", "failed"]; + if (rawStatus !== void 0 && !validStatuses.includes(rawStatus)) { + res.status(400).json({ + error: `Invalid status '${rawStatus}'. Must be one of: ${validStatuses.join(", ")}` + }); + return; + } + try { + const jobs = await jobDeps.jobStore.listJobs( + plugin.id, + rawStatus + ); + res.json(jobs); + } catch (err) { + const message2 = err instanceof Error ? err.message : String(err); + res.status(500).json({ error: message2 }); + } + }); + router2.get("/plugins/:pluginId/jobs/:jobId/runs", async (req, res) => { + assertBoard(req); + if (!jobDeps) { + res.status(501).json({ error: "Job scheduling is not enabled" }); + return; + } + const { pluginId, jobId } = req.params; + const plugin = await resolvePlugin(registry2, pluginId); + if (!plugin) { + res.status(404).json({ error: "Plugin not found" }); + return; + } + const job = await jobDeps.jobStore.getJobByIdForPlugin(plugin.id, jobId); + if (!job) { + res.status(404).json({ error: "Job not found" }); + return; + } + const limit = req.query.limit ? parseInt(req.query.limit, 10) : 25; + if (isNaN(limit) || limit < 1 || limit > 500) { + res.status(400).json({ error: "limit must be a number between 1 and 500" }); + return; + } + try { + const runs = await jobDeps.jobStore.listRunsByJob(jobId, limit); + res.json(runs); + } catch (err) { + const message2 = err instanceof Error ? err.message : String(err); + res.status(500).json({ error: message2 }); + } + }); + router2.post("/plugins/:pluginId/jobs/:jobId/trigger", async (req, res) => { + assertBoard(req); + if (!jobDeps) { + res.status(501).json({ error: "Job scheduling is not enabled" }); + return; + } + const { pluginId, jobId } = req.params; + const plugin = await resolvePlugin(registry2, pluginId); + if (!plugin) { + res.status(404).json({ error: "Plugin not found" }); + return; + } + const job = await jobDeps.jobStore.getJobByIdForPlugin(plugin.id, jobId); + if (!job) { + res.status(404).json({ error: "Job not found" }); + return; + } + try { + const result = await jobDeps.scheduler.triggerJob(jobId, "manual"); + res.json(result); + } catch (err) { + const message2 = err instanceof Error ? err.message : String(err); + res.status(400).json({ error: message2 }); + } + }); + router2.post("/plugins/:pluginId/webhooks/:endpointKey", async (req, res) => { + if (!webhookDeps) { + res.status(501).json({ error: "Webhook ingestion is not enabled" }); + return; + } + const { pluginId, endpointKey } = req.params; + const plugin = await resolvePlugin(registry2, pluginId); + if (!plugin) { + res.status(404).json({ error: "Plugin not found" }); + return; + } + if (plugin.status !== "ready") { + res.status(400).json({ + error: `Plugin is not ready (current status: ${plugin.status})` + }); + return; + } + const manifest = plugin.manifestJson; + if (!manifest) { + res.status(400).json({ error: "Plugin manifest is missing" }); + return; + } + const capabilities = manifest.capabilities ?? []; + if (!capabilities.includes("webhooks.receive")) { + res.status(400).json({ + error: "Plugin does not have the webhooks.receive capability" + }); + return; + } + const declaredWebhooks = manifest.webhooks ?? []; + const webhookDecl = declaredWebhooks.find( + (w5) => w5.endpointKey === endpointKey + ); + if (!webhookDecl) { + res.status(404).json({ + error: `Webhook endpoint '${endpointKey}' is not declared by this plugin` + }); + return; + } + const requestId = randomUUID10(); + const rawHeaders = {}; + for (const [key, value] of Object.entries(req.headers)) { + if (typeof value === "string") { + rawHeaders[key] = value; + } else if (Array.isArray(value)) { + rawHeaders[key] = value.join(", "); + } + } + const stashedRaw = req.rawBody; + const rawBody = stashedRaw ? stashedRaw.toString("utf-8") : ""; + const parsedBody = req.body; + const payload2 = req.body ?? {}; + const startedAt = /* @__PURE__ */ new Date(); + const [delivery] = await db.insert(pluginWebhookDeliveries).values({ + pluginId: plugin.id, + webhookKey: endpointKey, + status: "pending", + payload: payload2, + headers: rawHeaders, + startedAt + }).returning({ id: pluginWebhookDeliveries.id }); + try { + await webhookDeps.workerManager.call(plugin.id, "handleWebhook", { + endpointKey, + headers: req.headers, + rawBody, + parsedBody, + requestId + }); + const finishedAt = /* @__PURE__ */ new Date(); + const durationMs = finishedAt.getTime() - startedAt.getTime(); + await db.update(pluginWebhookDeliveries).set({ + status: "success", + durationMs, + finishedAt + }).where(eq(pluginWebhookDeliveries.id, delivery.id)); + res.status(200).json({ + deliveryId: delivery.id, + status: "success" + }); + } catch (err) { + const finishedAt = /* @__PURE__ */ new Date(); + const durationMs = finishedAt.getTime() - startedAt.getTime(); + const errorMessage = err instanceof Error ? err.message : String(err); + await db.update(pluginWebhookDeliveries).set({ + status: "failed", + durationMs, + error: errorMessage, + finishedAt + }).where(eq(pluginWebhookDeliveries.id, delivery.id)); + res.status(502).json({ + deliveryId: delivery.id, + status: "failed", + error: errorMessage + }); + } + }); + router2.get("/plugins/:pluginId/dashboard", async (req, res) => { + assertBoard(req); + const { pluginId } = req.params; + const plugin = await resolvePlugin(registry2, pluginId); + if (!plugin) { + res.status(404).json({ error: "Plugin not found" }); + return; + } + let worker = null; + const wm = bridgeDeps?.workerManager ?? webhookDeps?.workerManager ?? null; + if (wm) { + const handle = wm.getWorker(plugin.id); + if (handle) { + const diag = handle.diagnostics(); + worker = { + status: diag.status, + pid: diag.pid, + uptime: diag.uptime, + consecutiveCrashes: diag.consecutiveCrashes, + totalCrashes: diag.totalCrashes, + pendingRequests: diag.pendingRequests, + lastCrashAt: diag.lastCrashAt, + nextRestartAt: diag.nextRestartAt + }; + } + } + let recentJobRuns = []; + if (jobDeps) { + try { + const runs = await jobDeps.jobStore.listRunsByPlugin(plugin.id, void 0, 10); + const jobs = await jobDeps.jobStore.listJobs(plugin.id); + const jobKeyMap = new Map(jobs.map((j5) => [j5.id, j5.jobKey])); + recentJobRuns = runs.sort((a5, b6) => new Date(b6.createdAt).getTime() - new Date(a5.createdAt).getTime()).map((r5) => ({ + id: r5.id, + jobId: r5.jobId, + jobKey: jobKeyMap.get(r5.jobId) ?? void 0, + trigger: r5.trigger, + status: r5.status, + durationMs: r5.durationMs, + error: r5.error, + startedAt: r5.startedAt ? new Date(r5.startedAt).toISOString() : null, + finishedAt: r5.finishedAt ? new Date(r5.finishedAt).toISOString() : null, + createdAt: new Date(r5.createdAt).toISOString() + })); + } catch { + } + } + let recentWebhookDeliveries = []; + try { + const deliveries = await db.select({ + id: pluginWebhookDeliveries.id, + webhookKey: pluginWebhookDeliveries.webhookKey, + status: pluginWebhookDeliveries.status, + durationMs: pluginWebhookDeliveries.durationMs, + error: pluginWebhookDeliveries.error, + startedAt: pluginWebhookDeliveries.startedAt, + finishedAt: pluginWebhookDeliveries.finishedAt, + createdAt: pluginWebhookDeliveries.createdAt + }).from(pluginWebhookDeliveries).where(eq(pluginWebhookDeliveries.pluginId, plugin.id)).orderBy(desc(pluginWebhookDeliveries.createdAt)).limit(10); + recentWebhookDeliveries = deliveries.map((d5) => ({ + id: d5.id, + webhookKey: d5.webhookKey, + status: d5.status, + durationMs: d5.durationMs, + error: d5.error, + startedAt: d5.startedAt ? d5.startedAt.toISOString() : null, + finishedAt: d5.finishedAt ? d5.finishedAt.toISOString() : null, + createdAt: d5.createdAt.toISOString() + })); + } catch { + } + const checks = []; + checks.push({ + name: "registry", + passed: true, + message: "Plugin found in registry" + }); + const hasValidManifest = Boolean(plugin.manifestJson?.id); + checks.push({ + name: "manifest", + passed: hasValidManifest, + message: hasValidManifest ? "Manifest is valid" : "Manifest is invalid or missing" + }); + const isHealthy = plugin.status === "ready"; + checks.push({ + name: "status", + passed: isHealthy, + message: `Current status: ${plugin.status}` + }); + const hasNoError = !plugin.lastError; + if (!hasNoError) { + checks.push({ + name: "error_state", + passed: false, + message: plugin.lastError ?? void 0 + }); + } + const health = { + pluginId: plugin.id, + status: plugin.status, + healthy: isHealthy && hasValidManifest && hasNoError, + checks, + lastError: plugin.lastError ?? void 0 + }; + res.json({ + pluginId: plugin.id, + worker, + recentJobRuns, + recentWebhookDeliveries, + health, + checkedAt: (/* @__PURE__ */ new Date()).toISOString() + }); + }); + return router2; +} + +// server/src/routes/adapters.ts +var import_express23 = __toESM(require_express2(), 1); +import { execFile as execFile8 } from "node:child_process"; +import fs37 from "node:fs"; +import { readFile as readFile4 } from "node:fs/promises"; +import path48 from "node:path"; +import { promisify as promisify8 } from "node:util"; +var execFileAsync7 = promisify8(execFile8); +function resolveAdapterPackageDir(record2) { + return record2.localPath ? path48.resolve(record2.localPath) : path48.resolve(getAdapterPluginsDir(), "node_modules", record2.packageName); +} +function readAdapterPackageVersionFromDisk(record2) { + try { + const pkgDir = resolveAdapterPackageDir(record2); + const raw = fs37.readFileSync(path48.join(pkgDir, "package.json"), "utf-8"); + const v5 = JSON.parse(raw).version; + return typeof v5 === "string" && v5.trim().length > 0 ? v5.trim() : void 0; + } catch { + return void 0; + } +} +function buildAdapterInfo(adapter, externalRecord, disabledSet) { + const fromDisk = externalRecord ? readAdapterPackageVersionFromDisk(externalRecord) : void 0; + return { + type: adapter.type, + label: adapter.type, + // ServerAdapterModule doesn't have a separate "label" field; type serves as label + source: externalRecord ? "external" : "builtin", + modelsCount: (adapter.models ?? []).length, + loaded: true, + // If it's in the registry, it's loaded + disabled: disabledSet.has(adapter.type), + overriddenBuiltin: externalRecord ? BUILTIN_ADAPTER_TYPES.has(adapter.type) : void 0, + overridePaused: BUILTIN_ADAPTER_TYPES.has(adapter.type) ? isOverridePaused(adapter.type) : void 0, + // Prefer on-disk package.json so the UI reflects bumps without relying on store-only fields. + version: fromDisk ?? externalRecord?.version, + packageName: externalRecord?.packageName, + isLocalPath: externalRecord?.localPath ? true : void 0 + }; +} +async function normalizeLocalPath(rawPath) { + if (rawPath.startsWith("/")) { + return rawPath; + } + if (/^[A-Za-z]:[\\/]/.test(rawPath)) { + try { + const { stdout } = await execFileAsync7("wslpath", ["-u", rawPath]); + return stdout.trim(); + } catch (err) { + logger.warn({ err, rawPath }, "wslpath conversion failed; using path as-is"); + return rawPath; + } + } + return rawPath; +} +function registerWithSessionManagement(adapter) { + const wrapped = { + ...adapter, + sessionManagement: getAdapterSessionManagement(adapter.type) ?? void 0 + }; + registerServerAdapter(wrapped); +} +function adapterRoutes() { + const router2 = (0, import_express23.Router)(); + router2.get("/adapters", async (_req, res) => { + assertBoard(_req); + const registeredAdapters = listServerAdapters(); + const externalRecords = new Map( + listAdapterPlugins().map((r5) => [r5.type, r5]) + ); + const disabledSet = new Set(getDisabledAdapterTypes()); + const result = registeredAdapters.map( + (adapter) => buildAdapterInfo(adapter, externalRecords.get(adapter.type), disabledSet) + ).sort((a5, b6) => a5.type.localeCompare(b6.type)); + res.json(result); + }); + router2.post("/adapters/install", async (req, res) => { + assertBoard(req); + const { packageName, isLocalPath = false, version: version3 } = req.body; + if (!packageName || typeof packageName !== "string") { + res.status(400).json({ error: "packageName is required and must be a string." }); + return; + } + let canonicalName = packageName; + let explicitVersion = version3; + const versionSuffix = packageName.match(/@(\d+\.\d+\.\d+.*)$/); + if (versionSuffix) { + const lastAtIndex = packageName.lastIndexOf("@"); + if (lastAtIndex > 0 && !explicitVersion) { + canonicalName = packageName.slice(0, lastAtIndex); + explicitVersion = versionSuffix[1]; + } + } + try { + let installedVersion; + let moduleLocalPath; + if (!isLocalPath) { + const pluginsDir = getAdapterPluginsDir(); + const spec = explicitVersion ? `${canonicalName}@${explicitVersion}` : canonicalName; + logger.info({ spec, pluginsDir }, "Installing adapter package via npm"); + await execFileAsync7("npm", ["install", "--no-save", spec], { + cwd: pluginsDir, + timeout: 12e4 + }); + try { + const pkgJsonPath = path48.join(pluginsDir, "node_modules", canonicalName, "package.json"); + const pkgContent = await import("node:fs/promises"); + const pkgRaw = await pkgContent.readFile(pkgJsonPath, "utf-8"); + const pkg2 = JSON.parse(pkgRaw); + const v5 = pkg2.version; + installedVersion = typeof v5 === "string" && v5.trim().length > 0 ? v5.trim() : explicitVersion; + } catch { + installedVersion = explicitVersion; + } + } else { + moduleLocalPath = path48.resolve(await normalizeLocalPath(packageName)); + try { + const pkgRaw = await readFile4(path48.join(moduleLocalPath, "package.json"), "utf-8"); + const v5 = JSON.parse(pkgRaw).version; + if (typeof v5 === "string" && v5.trim().length > 0) { + installedVersion = v5.trim(); + } + } catch { + } + } + const adapterModule = await loadExternalAdapterPackage(canonicalName, moduleLocalPath); + if (BUILTIN_ADAPTER_TYPES.has(adapterModule.type)) { + res.status(409).json({ + error: `Adapter type "${adapterModule.type}" is a built-in adapter and cannot be overwritten.` + }); + return; + } + const existing = findServerAdapter(adapterModule.type); + const isReinstall = existing !== null; + if (existing) { + unregisterServerAdapter(adapterModule.type); + logger.info({ type: adapterModule.type }, "Unregistered existing adapter for replacement"); + } + registerWithSessionManagement(adapterModule); + const record2 = { + packageName: canonicalName, + localPath: moduleLocalPath, + version: installedVersion ?? explicitVersion, + type: adapterModule.type, + installedAt: (/* @__PURE__ */ new Date()).toISOString() + }; + addAdapterPlugin(record2); + logger.info( + { type: adapterModule.type, packageName: canonicalName }, + "External adapter installed and registered" + ); + res.status(201).json({ + type: adapterModule.type, + packageName: canonicalName, + version: installedVersion ?? explicitVersion, + installedAt: record2.installedAt, + requiresRestart: isReinstall + }); + } catch (err) { + const message2 = err instanceof Error ? err.message : String(err); + logger.error({ err, packageName }, "Failed to install external adapter"); + if (message2.includes("npm") || message2.includes("ERR!")) { + res.status(500).json({ error: `npm install failed: ${message2}` }); + } else { + res.status(500).json({ error: `Failed to install adapter: ${message2}` }); + } + } + }); + router2.patch("/adapters/:type", async (req, res) => { + assertBoard(req); + const adapterType = req.params.type; + const { disabled } = req.body; + if (typeof disabled !== "boolean") { + res.status(400).json({ error: 'Request body must include { "disabled": true|false }.' }); + return; + } + const existing = findServerAdapter(adapterType); + if (!existing) { + res.status(404).json({ error: `Adapter "${adapterType}" is not registered.` }); + return; + } + const changed = setAdapterDisabled(adapterType, disabled); + if (changed) { + logger.info({ type: adapterType, disabled }, "Adapter enabled/disabled"); + } + res.json({ type: adapterType, disabled, changed }); + }); + router2.patch("/adapters/:type/override", async (req, res) => { + assertBoard(req); + const adapterType = req.params.type; + const { paused } = req.body; + if (typeof paused !== "boolean") { + res.status(400).json({ error: '"paused" (boolean) is required in request body.' }); + return; + } + if (!BUILTIN_ADAPTER_TYPES.has(adapterType)) { + res.status(400).json({ error: `Type "${adapterType}" is not a builtin adapter.` }); + return; + } + const changed = setOverridePaused(adapterType, paused); + logger.info({ type: adapterType, paused, changed }, "Adapter override toggle"); + res.json({ type: adapterType, paused, changed }); + }); + router2.delete("/adapters/:type", async (req, res) => { + assertBoard(req); + const adapterType = req.params.type; + if (!adapterType) { + res.status(400).json({ error: "Adapter type is required." }); + return; + } + if (BUILTIN_ADAPTER_TYPES.has(adapterType)) { + res.status(403).json({ + error: `Cannot remove built-in adapter "${adapterType}".` + }); + return; + } + const existing = findServerAdapter(adapterType); + if (!existing) { + res.status(404).json({ + error: `Adapter "${adapterType}" is not registered.` + }); + return; + } + const externalRecord = getAdapterPluginByType(adapterType); + if (!externalRecord) { + res.status(404).json({ + error: `Adapter "${adapterType}" is not an externally installed adapter.` + }); + return; + } + if (externalRecord.packageName && !externalRecord.localPath) { + try { + const pluginsDir = getAdapterPluginsDir(); + await execFileAsync7("npm", ["uninstall", externalRecord.packageName], { + cwd: pluginsDir, + timeout: 6e4 + }); + logger.info( + { type: adapterType, packageName: externalRecord.packageName }, + "npm uninstall completed for external adapter" + ); + } catch (err) { + logger.warn( + { err, type: adapterType, packageName: externalRecord.packageName }, + "npm uninstall failed for external adapter; continuing with unregister" + ); + } + } + unregisterServerAdapter(adapterType); + removeAdapterPlugin(adapterType); + logger.info({ type: adapterType }, "External adapter unregistered and removed"); + res.json({ type: adapterType, removed: true }); + }); + router2.post("/adapters/:type/reload", async (req, res) => { + assertBoard(req); + const type = req.params.type; + if (BUILTIN_ADAPTER_TYPES.has(type) && !getAdapterPluginByType(type)) { + res.status(400).json({ error: "Cannot reload built-in adapter." }); + return; + } + try { + const newModule = await reloadExternalAdapter(type); + if (!newModule) { + res.status(404).json({ error: `Adapter "${type}" is not an externally installed adapter.` }); + return; + } + unregisterServerAdapter(type); + registerWithSessionManagement(newModule); + configSchemaCache.delete(type); + const record2 = getAdapterPluginByType(type); + let newVersion; + if (record2) { + newVersion = readAdapterPackageVersionFromDisk(record2); + if (newVersion) { + addAdapterPlugin({ ...record2, version: newVersion }); + } + } + logger.info({ type, version: newVersion }, "External adapter reloaded at runtime"); + res.json({ type, version: newVersion, reloaded: true }); + } catch (err) { + const message2 = err instanceof Error ? err.message : String(err); + logger.error({ err, type }, "Failed to reload external adapter"); + res.status(500).json({ error: `Failed to reload adapter: ${message2}` }); + } + }); + router2.post("/adapters/:type/reinstall", async (req, res) => { + assertBoard(req); + const type = req.params.type; + if (BUILTIN_ADAPTER_TYPES.has(type) && !getAdapterPluginByType(type)) { + res.status(400).json({ error: "Cannot reinstall built-in adapter." }); + return; + } + const record2 = getAdapterPluginByType(type); + if (!record2) { + res.status(404).json({ error: `Adapter "${type}" is not an externally installed adapter.` }); + return; + } + if (record2.localPath) { + res.status(400).json({ error: "Local-path adapters cannot be reinstalled. Use Reload instead." }); + return; + } + try { + const pluginsDir = getAdapterPluginsDir(); + logger.info({ type, packageName: record2.packageName }, "Reinstalling adapter package via npm"); + await execFileAsync7("npm", ["install", "--no-save", record2.packageName], { + cwd: pluginsDir, + timeout: 12e4 + }); + const newModule = await reloadExternalAdapter(type); + if (!newModule) { + res.status(500).json({ error: "npm install succeeded but adapter reload failed." }); + return; + } + unregisterServerAdapter(type); + registerWithSessionManagement(newModule); + configSchemaCache.delete(type); + let newVersion; + const updatedRecord = getAdapterPluginByType(type); + if (updatedRecord) { + newVersion = readAdapterPackageVersionFromDisk(updatedRecord); + if (newVersion) { + addAdapterPlugin({ ...updatedRecord, version: newVersion }); + } + } + logger.info({ type, version: newVersion }, "Adapter reinstalled from npm"); + res.json({ type, version: newVersion, reinstalled: true }); + } catch (err) { + const message2 = err instanceof Error ? err.message : String(err); + logger.error({ err, type }, "Failed to reinstall adapter"); + res.status(500).json({ error: `Reinstall failed: ${message2}` }); + } + }); + const configSchemaCache = /* @__PURE__ */ new Map(); + const CONFIG_SCHEMA_TTL_MS = 3e4; + router2.get("/adapters/:type/config-schema", async (req, res) => { + assertBoard(req); + const { type } = req.params; + const adapter = findActiveServerAdapter(type); + if (!adapter) { + res.status(404).json({ error: `Adapter "${type}" is not registered.` }); + return; + } + if (!adapter.getConfigSchema) { + res.status(404).json({ error: `Adapter "${type}" does not provide a config schema.` }); + return; + } + const cached4 = configSchemaCache.get(type); + if (cached4 && cached4.adapter === adapter && Date.now() - cached4.fetchedAt < CONFIG_SCHEMA_TTL_MS) { + res.json(cached4.schema); + return; + } + try { + const schema2 = await adapter.getConfigSchema(); + configSchemaCache.set(type, { adapter, schema: schema2, fetchedAt: Date.now() }); + res.json(schema2); + } catch (err) { + const message2 = err instanceof Error ? err.message : String(err); + logger.error({ err, type }, "Failed to resolve config schema"); + res.status(500).json({ error: `Failed to resolve config schema: ${message2}` }); + } + }); + router2.get("/adapters/:type/ui-parser.js", (req, res) => { + assertBoard(req); + const { type } = req.params; + const source = getOrExtractUiParserSource(type); + if (!source) { + res.status(404).json({ error: `No UI parser available for adapter "${type}".` }); + return; + } + res.type("application/javascript").send(source); + }); + return router2; +} + +// server/src/routes/plugin-ui-static.ts +var import_express24 = __toESM(require_express2(), 1); +import path49 from "node:path"; +import fs38 from "node:fs"; +import crypto5 from "node:crypto"; +var CONTENT_HASH_PATTERN = /[.-][a-fA-F0-9]{8,}\.\w+$/; +var ONE_YEAR_SECONDS = 365 * 24 * 60 * 60; +var CACHE_CONTROL_IMMUTABLE = `public, max-age=${ONE_YEAR_SECONDS}, immutable`; +var CACHE_CONTROL_REVALIDATE = "public, max-age=0, must-revalidate"; +var MIME_TYPES = { + ".js": "application/javascript; charset=utf-8", + ".mjs": "application/javascript; charset=utf-8", + ".css": "text/css; charset=utf-8", + ".json": "application/json; charset=utf-8", + ".map": "application/json; charset=utf-8", + ".html": "text/html; charset=utf-8", + ".svg": "image/svg+xml", + ".png": "image/png", + ".jpg": "image/jpeg", + ".jpeg": "image/jpeg", + ".gif": "image/gif", + ".webp": "image/webp", + ".woff": "font/woff", + ".woff2": "font/woff2", + ".ttf": "font/ttf", + ".eot": "application/vnd.ms-fontobject", + ".ico": "image/x-icon", + ".txt": "text/plain; charset=utf-8" +}; +function resolvePluginUiDir(localPluginDir, packageName, entrypointsUi, packagePath) { + if (packagePath) { + const resolvedPackagePath = path49.resolve(packagePath); + if (fs38.existsSync(resolvedPackagePath)) { + const uiDirFromPackagePath = path49.resolve(resolvedPackagePath, entrypointsUi); + if (uiDirFromPackagePath.startsWith(resolvedPackagePath) && fs38.existsSync(uiDirFromPackagePath)) { + return uiDirFromPackagePath; + } + } + } + let packageRoot; + if (packageName.startsWith("@")) { + packageRoot = path49.join(localPluginDir, "node_modules", ...packageName.split("/")); + } else { + packageRoot = path49.join(localPluginDir, "node_modules", packageName); + } + if (!fs38.existsSync(packageRoot)) { + const directPath = path49.join(localPluginDir, packageName); + if (fs38.existsSync(directPath)) { + packageRoot = directPath; + } else { + return null; + } + } + const uiDir = path49.resolve(packageRoot, entrypointsUi); + if (!fs38.existsSync(uiDir)) { + return null; + } + return uiDir; +} +function computeETag(size2, mtimeMs) { + const ETAG_VERSION = "v2"; + const hash2 = crypto5.createHash("md5").update(`${ETAG_VERSION}:${size2}-${mtimeMs}`).digest("hex").slice(0, 16); + return `"${hash2}"`; +} +function pluginUiStaticRoutes(db, options) { + const router2 = (0, import_express24.Router)(); + const registry2 = pluginRegistryService(db); + const log2 = logger.child({ service: "plugin-ui-static" }); + router2.get("/_plugins/:pluginId/ui/*filePath", async (req, res) => { + const { pluginId } = req.params; + const rawParam = req.params.filePath; + const rawFilePath = Array.isArray(rawParam) ? rawParam.join("/") : rawParam; + if (!rawFilePath || rawFilePath.length === 0) { + res.status(400).json({ error: "File path is required" }); + return; + } + let plugin = null; + try { + plugin = await registry2.getById(pluginId); + } catch (error50) { + const maybeCode = typeof error50 === "object" && error50 !== null && "code" in error50 ? error50.code : void 0; + if (maybeCode !== "22P02") { + throw error50; + } + } + if (!plugin) { + plugin = await registry2.getByKey(pluginId); + } + if (!plugin) { + res.status(404).json({ error: "Plugin not found" }); + return; + } + if (plugin.status !== "ready") { + res.status(403).json({ + error: `Plugin UI is not available (status: ${plugin.status})` + }); + return; + } + const manifest = plugin.manifestJson; + if (!manifest?.entrypoints?.ui) { + res.status(404).json({ error: "Plugin does not declare a UI bundle" }); + return; + } + try { + const configRow = await registry2.getConfig(plugin.id); + const devUiUrl = configRow && typeof configRow === "object" && "configJson" in configRow && configRow.configJson?.devUiUrl; + if (typeof devUiUrl === "string" && devUiUrl.length > 0) { + if (true) { + log2.warn( + { pluginId: plugin.id }, + "plugin-ui-static: devUiUrl ignored in production" + ); + } else { + let decodedPath; + try { + decodedPath = decodeURIComponent(rawFilePath); + } catch { + res.status(400).json({ error: "Invalid file path" }); + return; + } + if (decodedPath.includes("://") || decodedPath.startsWith("//") || decodedPath.startsWith("\\\\")) { + res.status(400).json({ error: "Invalid file path" }); + return; + } + const targetUrl = new URL(rawFilePath, devUiUrl.endsWith("/") ? devUiUrl : devUiUrl + "/"); + if (targetUrl.protocol !== "http:" && targetUrl.protocol !== "https:") { + res.status(400).json({ error: "devUiUrl must use http or https protocol" }); + return; + } + const devHost = targetUrl.hostname; + const isLoopback = devHost === "localhost" || devHost === "127.0.0.1" || devHost === "::1" || devHost === "[::1]"; + if (!isLoopback) { + log2.warn( + { pluginId: plugin.id, devUiUrl, host: devHost }, + "plugin-ui-static: devUiUrl must target localhost, rejecting proxy" + ); + res.status(400).json({ error: "devUiUrl must target localhost" }); + return; + } + log2.debug( + { pluginId: plugin.id, devUiUrl, targetUrl: targetUrl.href }, + "plugin-ui-static: proxying to devUiUrl" + ); + try { + const controller = new AbortController(); + const timeout = setTimeout(() => controller.abort(), 1e4); + try { + const upstream = await fetch(targetUrl.href, { signal: controller.signal }); + if (!upstream.ok) { + res.status(upstream.status).json({ + error: `Dev server returned ${upstream.status}` + }); + return; + } + const contentType2 = upstream.headers.get("content-type"); + if (contentType2) res.set("Content-Type", contentType2); + res.set("Cache-Control", "no-cache, no-store, must-revalidate"); + const body = await upstream.arrayBuffer(); + res.send(Buffer.from(body)); + return; + } finally { + clearTimeout(timeout); + } + } catch (proxyErr) { + log2.warn( + { + pluginId: plugin.id, + devUiUrl, + err: proxyErr instanceof Error ? proxyErr.message : String(proxyErr) + }, + "plugin-ui-static: failed to proxy to devUiUrl, falling back to static" + ); + } + } + } + } catch { + } + const uiDir = resolvePluginUiDir( + options.localPluginDir, + plugin.packageName, + manifest.entrypoints.ui, + plugin.packagePath + ); + if (!uiDir) { + log2.warn( + { pluginId: plugin.id, pluginKey: plugin.pluginKey, packageName: plugin.packageName }, + "plugin-ui-static: UI directory not found on disk" + ); + res.status(404).json({ error: "Plugin UI directory not found" }); + return; + } + const resolvedFilePath = path49.resolve(uiDir, rawFilePath); + let fileStat; + try { + fileStat = fs38.statSync(resolvedFilePath); + } catch { + res.status(404).json({ error: "File not found" }); + return; + } + let realFilePath; + let realUiDir; + try { + realFilePath = fs38.realpathSync(resolvedFilePath); + realUiDir = fs38.realpathSync(uiDir); + } catch { + res.status(404).json({ error: "File not found" }); + return; + } + const relative3 = path49.relative(realUiDir, realFilePath); + if (relative3.startsWith("..") || path49.isAbsolute(relative3)) { + res.status(403).json({ error: "Access denied" }); + return; + } + if (!fileStat.isFile()) { + res.status(404).json({ error: "File not found" }); + return; + } + const basename3 = path49.basename(resolvedFilePath); + const isContentHashed = CONTENT_HASH_PATTERN.test(basename3); + if (isContentHashed) { + res.set("Cache-Control", CACHE_CONTROL_IMMUTABLE); + } else { + res.set("Cache-Control", CACHE_CONTROL_REVALIDATE); + const etag = computeETag(fileStat.size, fileStat.mtimeMs); + res.set("ETag", etag); + const ifNoneMatch = req.headers["if-none-match"]; + if (ifNoneMatch === etag) { + res.status(304).end(); + return; + } + } + const ext = path49.extname(resolvedFilePath).toLowerCase(); + const contentType = MIME_TYPES[ext]; + if (contentType) { + res.set("Content-Type", contentType); + } + res.set("Access-Control-Allow-Origin", "*"); + res.sendFile(resolvedFilePath, { dotfiles: "allow" }, (err) => { + if (err) { + log2.error( + { err, pluginId: plugin.id, filePath: resolvedFilePath }, + "plugin-ui-static: error sending file" + ); + if (!res.headersSent) { + res.status(500).json({ error: "Failed to serve file" }); + } + } + }); + }); + return router2; +} + +// server/src/ui-branding.ts +var FAVICON_BLOCK_START = ""; +var FAVICON_BLOCK_END = ""; +var RUNTIME_BRANDING_BLOCK_START = ""; +var RUNTIME_BRANDING_BLOCK_END = ""; +var DEFAULT_FAVICON_LINKS = [ + '', + '', + '', + '' +].join("\n"); +function isTruthyEnvValue(value) { + if (!value) return false; + const normalized = value.trim().toLowerCase(); + return normalized === "1" || normalized === "true" || normalized === "yes" || normalized === "on"; +} +function nonEmpty6(value) { + if (typeof value !== "string") return null; + const normalized = value.trim(); + return normalized.length > 0 ? normalized : null; +} +function normalizeHexColor2(value) { + const raw = nonEmpty6(value); + if (!raw) return null; + const hex4 = raw.startsWith("#") ? raw.slice(1) : raw; + if (/^[0-9a-fA-F]{3}$/.test(hex4)) { + return `#${hex4.split("").map((char2) => `${char2}${char2}`).join("").toLowerCase()}`; + } + if (/^[0-9a-fA-F]{6}$/.test(hex4)) { + return `#${hex4.toLowerCase()}`; + } + return null; +} +function hslComponentToHex(n5) { + return Math.round(Math.max(0, Math.min(255, n5))).toString(16).padStart(2, "0"); +} +function hslToHex(hue, saturation, lightness) { + const s5 = Math.max(0, Math.min(100, saturation)) / 100; + const l5 = Math.max(0, Math.min(100, lightness)) / 100; + const c5 = (1 - Math.abs(2 * l5 - 1)) * s5; + const h5 = (hue % 360 + 360) % 360; + const x5 = c5 * (1 - Math.abs(h5 / 60 % 2 - 1)); + const m5 = l5 - c5 / 2; + let r5 = 0; + let g5 = 0; + let b6 = 0; + if (h5 < 60) { + r5 = c5; + g5 = x5; + } else if (h5 < 120) { + r5 = x5; + g5 = c5; + } else if (h5 < 180) { + g5 = c5; + b6 = x5; + } else if (h5 < 240) { + g5 = x5; + b6 = c5; + } else if (h5 < 300) { + r5 = x5; + b6 = c5; + } else { + r5 = c5; + b6 = x5; + } + return `#${hslComponentToHex((r5 + m5) * 255)}${hslComponentToHex((g5 + m5) * 255)}${hslComponentToHex((b6 + m5) * 255)}`; +} +function deriveColorFromSeed(seed) { + let hash2 = 0; + for (const char2 of seed) { + hash2 = hash2 * 33 + char2.charCodeAt(0) >>> 0; + } + return hslToHex(hash2 % 360, 68, 56); +} +function hexToRgb(color) { + const normalized = normalizeHexColor2(color) ?? "#000000"; + return { + r: Number.parseInt(normalized.slice(1, 3), 16), + g: Number.parseInt(normalized.slice(3, 5), 16), + b: Number.parseInt(normalized.slice(5, 7), 16) + }; +} +function relativeLuminanceChannel(value) { + const normalized = value / 255; + return normalized <= 0.03928 ? normalized / 12.92 : ((normalized + 0.055) / 1.055) ** 2.4; +} +function relativeLuminance(color) { + const { r: r5, g: g5, b: b6 } = hexToRgb(color); + return 0.2126 * relativeLuminanceChannel(r5) + 0.7152 * relativeLuminanceChannel(g5) + 0.0722 * relativeLuminanceChannel(b6); +} +function pickReadableTextColor(background) { + const backgroundLuminance = relativeLuminance(background); + const whiteContrast = 1.05 / (backgroundLuminance + 0.05); + const blackContrast = (backgroundLuminance + 0.05) / 0.05; + return whiteContrast >= blackContrast ? "#f8fafc" : "#111827"; +} +function escapeHtmlAttribute(value) { + return value.replaceAll("&", "&").replaceAll('"', """).replaceAll("<", "<").replaceAll(">", ">"); +} +function createFaviconDataUrl(background, foreground) { + const svg2 = [ + '', + ``, + ``, + "" + ].join(""); + return `data:image/svg+xml,${encodeURIComponent(svg2)}`; +} +function isWorktreeUiBrandingEnabled(env2 = process.env) { + return isTruthyEnvValue(env2.TASKCORE_IN_WORKTREE); +} +function getWorktreeUiBranding(env2 = process.env) { + if (!isWorktreeUiBrandingEnabled(env2)) { + return { + enabled: false, + name: null, + color: null, + textColor: null, + faviconHref: null + }; + } + const name = nonEmpty6(env2.TASKCORE_WORKTREE_NAME) ?? nonEmpty6(env2.TASKCORE_INSTANCE_ID) ?? "worktree"; + const color = normalizeHexColor2(env2.TASKCORE_WORKTREE_COLOR) ?? deriveColorFromSeed(name); + const textColor = pickReadableTextColor(color); + return { + enabled: true, + name, + color, + textColor, + faviconHref: createFaviconDataUrl(color, textColor) + }; +} +function renderFaviconLinks(branding) { + if (!branding.enabled || !branding.faviconHref) return DEFAULT_FAVICON_LINKS; + const href = escapeHtmlAttribute(branding.faviconHref); + return [ + ``, + `` + ].join("\n"); +} +function renderRuntimeBrandingMeta(branding) { + if (!branding.enabled || !branding.name || !branding.color || !branding.textColor) return ""; + return [ + '', + ``, + ``, + `` + ].join("\n"); +} +function replaceMarkedBlock(html3, startMarker, endMarker, content) { + const start = html3.indexOf(startMarker); + const end = html3.indexOf(endMarker); + if (start === -1 || end === -1 || end < start) return html3; + const before = html3.slice(0, start + startMarker.length); + const after = html3.slice(end); + const indentedContent = content ? ` +${content.split("\n").map((line3) => ` ${line3}`).join("\n")} + ` : "\n "; + return `${before}${indentedContent}${after}`; +} +function applyUiBranding(html3, env2 = process.env) { + const branding = getWorktreeUiBranding(env2); + const withFavicon = replaceMarkedBlock(html3, FAVICON_BLOCK_START, FAVICON_BLOCK_END, renderFaviconLinks(branding)); + return replaceMarkedBlock( + withFavicon, + RUNTIME_BRANDING_BLOCK_START, + RUNTIME_BRANDING_BLOCK_END, + renderRuntimeBrandingMeta(branding) + ); +} + +// server/src/services/plugin-worker-manager.ts +import { fork } from "node:child_process"; +import { EventEmitter as EventEmitter3 } from "node:events"; +import { createInterface } from "node:readline"; +var DEFAULT_RPC_TIMEOUT_MS = 3e4; +var MAX_RPC_TIMEOUT_MS = 5 * 60 * 1e3; +var INITIALIZE_TIMEOUT_MS = 15e3; +var SHUTDOWN_DRAIN_MS = 1e4; +var SIGTERM_GRACE_MS = 5e3; +var MIN_BACKOFF_MS = 1e3; +var MAX_BACKOFF_MS = 5 * 60 * 1e3; +var BACKOFF_MULTIPLIER = 2; +var MAX_CONSECUTIVE_CRASHES = 10; +var CRASH_WINDOW_MS = 10 * 60 * 1e3; +var MAX_STDERR_EXCERPT_CHARS = 8e3; +function appendStderrExcerpt(current, chunk) { + const next = current ? `${current} +${chunk}` : chunk; + return next.length <= MAX_STDERR_EXCERPT_CHARS ? next : next.slice(-MAX_STDERR_EXCERPT_CHARS); +} +function formatWorkerFailureMessage(message2, stderrExcerpt) { + const excerpt = stderrExcerpt.trim(); + if (!excerpt) return message2; + if (message2.includes(excerpt)) return message2; + return `${message2} + +Worker stderr: +${excerpt}`; +} +function createPluginWorkerHandle(pluginId, options) { + const log2 = logger.child({ service: "plugin-worker", pluginId }); + const emitter2 = new EventEmitter3(); + emitter2.setMaxListeners(50); + let childProcess = null; + let readline = null; + let stderrReadline = null; + let status = "stopped"; + let startedAt = null; + let stderrExcerpt = ""; + const pendingRequests = /* @__PURE__ */ new Map(); + let nextRequestId = 1; + let supportedMethods = []; + let consecutiveCrashes = 0; + let totalCrashes = 0; + let lastCrashAt = null; + let backoffTimer = null; + let nextRestartAt = null; + const openStreamChannels = /* @__PURE__ */ new Map(); + let intentionalStop = false; + const rpcTimeoutMs = options.rpcTimeoutMs ?? DEFAULT_RPC_TIMEOUT_MS; + const autoRestart = options.autoRestart ?? true; + function setStatus(newStatus) { + const prev = status; + if (prev === newStatus) return; + status = newStatus; + log2.debug({ from: prev, to: newStatus }, "worker status change"); + emitter2.emit("status", { pluginId, status: newStatus, previousStatus: prev }); + } + function sendMessage(message2) { + if (!childProcess?.stdin?.writable) { + throw new Error(`Worker process for plugin "${pluginId}" is not writable`); + } + const serialized = serializeMessage(message2); + childProcess.stdin.write(serialized); + } + function handleLine(line3) { + if (!line3.trim()) return; + let message2; + try { + message2 = parseMessage(line3); + } catch (err) { + if (err instanceof JsonRpcParseError) { + log2.warn({ rawLine: line3.slice(0, 200) }, "unparseable message from worker"); + } else { + log2.warn({ err }, "error parsing worker message"); + } + return; + } + if (isJsonRpcResponse(message2)) { + handleResponse(message2); + } else if (isJsonRpcRequest(message2)) { + handleWorkerRequest(message2); + } else if (isJsonRpcNotification(message2)) { + handleWorkerNotification(message2); + } else { + log2.warn("unknown message type from worker"); + } + } + function handleResponse(response) { + const id = response.id; + if (id === null || id === void 0) { + log2.warn("received response with null/undefined id"); + return; + } + const pending = pendingRequests.get(id); + if (!pending) { + log2.warn({ id }, "received response for unknown request id"); + return; + } + clearTimeout(pending.timer); + pendingRequests.delete(id); + pending.resolve(response); + } + async function handleWorkerRequest(request) { + const method = request.method; + const handler = options.hostHandlers[method]; + if (!handler) { + log2.warn({ method }, "worker called unregistered host method"); + try { + sendMessage( + createErrorResponse( + request.id, + JSONRPC_ERROR_CODES.METHOD_NOT_FOUND, + `Host does not handle method "${method}"` + ) + ); + } catch { + } + return; + } + try { + const result = await handler(request.params); + sendMessage({ + jsonrpc: JSONRPC_VERSION, + id: request.id, + result: result ?? null + }); + } catch (err) { + const errorMessage = err instanceof Error ? err.message : String(err); + log2.error({ method, err: errorMessage }, "host handler error"); + try { + sendMessage( + createErrorResponse( + request.id, + JSONRPC_ERROR_CODES.INTERNAL_ERROR, + errorMessage + ) + ); + } catch { + } + } + } + function handleWorkerNotification(notification) { + if (notification.method === "log") { + const params = notification.params; + const level = params?.level ?? "info"; + const msg = params?.message ?? ""; + const meta3 = params?.meta; + const logFields = { + ...meta3, + pluginLogLevel: level, + pluginTimestamp: (/* @__PURE__ */ new Date()).toISOString() + }; + if (level === "error") { + log2.error(logFields, `[plugin] ${msg}`); + } else if (level === "warn") { + log2.warn(logFields, `[plugin] ${msg}`); + } else if (level === "debug") { + log2.debug(logFields, `[plugin] ${msg}`); + } else { + log2.info(logFields, `[plugin] ${msg}`); + } + return; + } + if (notification.method === "streams.open" || notification.method === "streams.emit" || notification.method === "streams.close") { + const params = notification.params ?? {}; + if (notification.method === "streams.open") { + const ch = String(params.channel ?? ""); + const co = String(params.companyId ?? ""); + if (ch) openStreamChannels.set(ch, co); + } else if (notification.method === "streams.close") { + openStreamChannels.delete(String(params.channel ?? "")); + } + if (options.onStreamNotification) { + try { + options.onStreamNotification(notification.method, params); + } catch (err) { + log2.error( + { + method: notification.method, + err: err instanceof Error ? err.message : String(err) + }, + "stream notification handler failed" + ); + } + } + return; + } + log2.debug({ method: notification.method }, "received notification from worker"); + } + function spawnProcess() { + const workerEnv = { + ...options.env, + PATH: process.env.PATH ?? "", + NODE_PATH: process.env.NODE_PATH ?? "", + TASKCORE_PLUGIN_ID: pluginId, + NODE_ENV: "production", + TZ: process.env.TZ ?? "UTC" + }; + const child = fork(options.entrypointPath, [], { + stdio: ["pipe", "pipe", "pipe", "ipc"], + execArgv: options.execArgv ?? [], + env: workerEnv, + // Don't let the child keep the parent alive + detached: false + }); + return child; + } + function attachStdioHandlers(child) { + if (child.stdout) { + readline = createInterface({ input: child.stdout }); + readline.on("line", handleLine); + } + if (child.stderr) { + stderrReadline = createInterface({ input: child.stderr }); + stderrReadline.on("line", (line3) => { + stderrExcerpt = appendStderrExcerpt(stderrExcerpt, line3); + log2.warn({ stream: "stderr" }, `[plugin stderr] ${line3}`); + }); + } + child.on("exit", (code, signal) => { + handleProcessExit(code, signal); + }); + child.on("error", (err) => { + log2.error({ err: err.message }, "worker process error"); + emitter2.emit("error", { pluginId, error: err }); + if (status === "starting") { + setStatus("crashed"); + rejectAllPending( + new Error(formatWorkerFailureMessage( + `Worker process failed to start: ${err.message}`, + stderrExcerpt + )) + ); + } + }); + } + function handleProcessExit(code, signal) { + const wasIntentional = intentionalStop; + if (readline) { + readline.close(); + readline = null; + } + if (stderrReadline) { + stderrReadline.close(); + stderrReadline = null; + } + childProcess = null; + startedAt = null; + rejectAllPending( + new Error(formatWorkerFailureMessage( + `Worker process exited (code=${code}, signal=${signal})`, + stderrExcerpt + )) + ); + if (openStreamChannels.size > 0 && options.onStreamNotification) { + for (const [channel, companyId] of openStreamChannels) { + try { + options.onStreamNotification("streams.close", { channel, companyId }); + } catch { + } + } + openStreamChannels.clear(); + } + emitter2.emit("exit", { pluginId, code, signal }); + if (wasIntentional) { + setStatus("stopped"); + log2.info({ code, signal }, "worker process stopped"); + return; + } + totalCrashes++; + const now2 = Date.now(); + if (lastCrashAt !== null && now2 - lastCrashAt > CRASH_WINDOW_MS) { + consecutiveCrashes = 0; + } + consecutiveCrashes++; + lastCrashAt = now2; + log2.error( + { code, signal, consecutiveCrashes, totalCrashes }, + "worker process crashed" + ); + const willRestart = autoRestart && consecutiveCrashes <= MAX_CONSECUTIVE_CRASHES; + setStatus("crashed"); + emitter2.emit("crash", { pluginId, code, signal, willRestart }); + if (willRestart) { + scheduleRestart(); + } else { + log2.error( + { consecutiveCrashes, maxCrashes: MAX_CONSECUTIVE_CRASHES }, + "max consecutive crashes reached, not restarting" + ); + } + } + function rejectAllPending(error50) { + for (const [id, pending] of pendingRequests) { + clearTimeout(pending.timer); + pending.resolve( + createErrorResponse( + pending.id, + PLUGIN_RPC_ERROR_CODES.WORKER_UNAVAILABLE, + error50.message + ) + ); + } + pendingRequests.clear(); + } + function computeBackoffMs() { + const delay3 = MIN_BACKOFF_MS * Math.pow(BACKOFF_MULTIPLIER, consecutiveCrashes - 1); + const jitter = delay3 * 0.25 * (Math.random() * 2 - 1); + return Math.min(Math.round(delay3 + jitter), MAX_BACKOFF_MS); + } + function scheduleRestart() { + const delay3 = computeBackoffMs(); + nextRestartAt = Date.now() + delay3; + setStatus("backoff"); + log2.info( + { delayMs: delay3, consecutiveCrashes }, + "scheduling restart with backoff" + ); + backoffTimer = setTimeout(async () => { + backoffTimer = null; + nextRestartAt = null; + try { + await startInternal(); + } catch (err) { + log2.error( + { err: err instanceof Error ? err.message : String(err) }, + "restart after backoff failed" + ); + } + }, delay3); + } + function cancelPendingRestart() { + if (backoffTimer !== null) { + clearTimeout(backoffTimer); + backoffTimer = null; + nextRestartAt = null; + } + } + async function startInternal() { + if (status === "running" || status === "starting") { + throw new Error(`Worker for plugin "${pluginId}" is already ${status}`); + } + intentionalStop = false; + setStatus("starting"); + stderrExcerpt = ""; + const child = spawnProcess(); + childProcess = child; + attachStdioHandlers(child); + startedAt = Date.now(); + const initParams = { + manifest: options.manifest, + config: options.config, + instanceInfo: options.instanceInfo, + apiVersion: options.apiVersion + }; + try { + const result = await callInternal( + "initialize", + initParams, + INITIALIZE_TIMEOUT_MS + ); + if (!result || !result.ok) { + throw new Error("Worker initialize returned ok=false"); + } + supportedMethods = result.supportedMethods ?? []; + } catch (err) { + const msg = err instanceof Error ? err.message : String(err); + log2.error({ err: msg }, "worker initialize failed"); + await killProcess(); + setStatus("crashed"); + throw new Error(`Worker initialize failed for "${pluginId}": ${msg}`); + } + consecutiveCrashes = 0; + setStatus("running"); + emitter2.emit("ready", { pluginId }); + log2.info({ pid: child.pid }, "worker process started and initialized"); + } + async function stopInternal() { + cancelPendingRestart(); + if (status === "stopped" || status === "stopping") { + return; + } + intentionalStop = true; + setStatus("stopping"); + if (!childProcess) { + setStatus("stopped"); + return; + } + try { + await Promise.race([ + callInternal("shutdown", {}, SHUTDOWN_DRAIN_MS), + waitForExit(SHUTDOWN_DRAIN_MS) + ]); + } catch { + log2.warn("shutdown RPC failed or timed out, escalating to SIGTERM"); + } + if (childProcess) { + await waitForExit(500); + } + if (!childProcess) { + setStatus("stopped"); + return; + } + log2.info("worker did not exit after shutdown RPC, sending SIGTERM"); + await killWithSignal("SIGTERM", SIGTERM_GRACE_MS); + if (!childProcess) { + setStatus("stopped"); + return; + } + log2.warn("worker did not exit after SIGTERM, sending SIGKILL"); + await killWithSignal("SIGKILL", 2e3); + if (childProcess) { + log2.error("worker process still alive after SIGKILL \u2014 this should not happen"); + } + setStatus("stopped"); + } + function waitForExit(timeoutMs) { + return new Promise((resolve4) => { + if (!childProcess) { + resolve4(); + return; + } + let settled = false; + const timer2 = setTimeout(() => { + if (settled) return; + settled = true; + resolve4(); + }, timeoutMs); + childProcess.once("exit", () => { + if (settled) return; + settled = true; + clearTimeout(timer2); + resolve4(); + }); + }); + } + function killWithSignal(signal, waitMs) { + return new Promise((resolve4) => { + if (!childProcess) { + resolve4(); + return; + } + const timer2 = setTimeout(() => { + resolve4(); + }, waitMs); + childProcess.once("exit", () => { + clearTimeout(timer2); + resolve4(); + }); + try { + childProcess.kill(signal); + } catch { + clearTimeout(timer2); + resolve4(); + } + }); + } + async function killProcess() { + if (!childProcess) return; + intentionalStop = true; + try { + childProcess.kill("SIGKILL"); + } catch { + } + await new Promise((resolve4) => { + if (!childProcess) { + resolve4(); + return; + } + const timer2 = setTimeout(() => { + resolve4(); + }, 1e3); + childProcess.once("exit", () => { + clearTimeout(timer2); + resolve4(); + }); + }); + } + function callInternal(method, params, timeoutMs) { + return new Promise((resolve4, reject) => { + if (!childProcess?.stdin?.writable) { + reject( + new Error( + `Cannot call "${method}" \u2014 worker for "${pluginId}" is not running` + ) + ); + return; + } + const id = nextRequestId++; + const timeout = Math.min(timeoutMs ?? rpcTimeoutMs, MAX_RPC_TIMEOUT_MS); + let settled = false; + const settle = (fn, value) => { + if (settled) return; + settled = true; + clearTimeout(timer2); + pendingRequests.delete(id); + fn(value); + }; + const timer2 = setTimeout(() => { + settle( + reject, + new JsonRpcCallError({ + code: PLUGIN_RPC_ERROR_CODES.TIMEOUT, + message: `RPC call "${method}" timed out after ${timeout}ms` + }) + ); + }, timeout); + const pending = { + id, + method, + resolve: (response) => { + if (isJsonRpcSuccessResponse(response)) { + settle(resolve4, response.result); + } else if ("error" in response && response.error) { + settle(reject, new JsonRpcCallError(response.error)); + } else { + settle(reject, new Error(`Unexpected response format for "${method}"`)); + } + }, + timer: timer2, + sentAt: Date.now() + }; + pendingRequests.set(id, pending); + try { + const request = createRequest(method, params, id); + sendMessage(request); + } catch (err) { + clearTimeout(timer2); + pendingRequests.delete(id); + reject( + new Error( + `Failed to send "${method}" to worker: ${err instanceof Error ? err.message : String(err)}` + ) + ); + } + }); + } + const handle = { + get pluginId() { + return pluginId; + }, + get status() { + return status; + }, + get supportedMethods() { + return supportedMethods; + }, + async start() { + await startInternal(); + }, + async stop() { + await stopInternal(); + }, + async restart() { + await stopInternal(); + await startInternal(); + }, + call(method, params, timeoutMs) { + if (status !== "running" && status !== "starting") { + return Promise.reject( + new Error( + `Cannot call "${method}" \u2014 worker for "${pluginId}" is ${status}` + ) + ); + } + return callInternal(method, params, timeoutMs); + }, + notify(method, params) { + if (status !== "running") return; + try { + sendMessage({ + jsonrpc: JSONRPC_VERSION, + method, + params + }); + } catch { + log2.warn({ method }, "failed to send notification to worker"); + } + }, + on(event, listener) { + emitter2.on(event, listener); + }, + off(event, listener) { + emitter2.off(event, listener); + }, + diagnostics() { + return { + pluginId, + status, + pid: childProcess?.pid ?? null, + uptime: startedAt !== null && status === "running" ? Date.now() - startedAt : null, + consecutiveCrashes, + totalCrashes, + pendingRequests: pendingRequests.size, + lastCrashAt, + nextRestartAt + }; + } + }; + return handle; +} +function createPluginWorkerManager(managerOptions) { + const log2 = logger.child({ service: "plugin-worker-manager" }); + const workers = /* @__PURE__ */ new Map(); + const startupLocks = /* @__PURE__ */ new Map(); + return { + async startWorker(pluginId, options) { + const inFlight = startupLocks.get(pluginId); + if (inFlight) { + log2.warn({ pluginId }, "concurrent startWorker call \u2014 waiting for in-flight start"); + return inFlight; + } + const existing = workers.get(pluginId); + if (existing && existing.status !== "stopped") { + throw new Error( + `Worker already registered for plugin "${pluginId}" (status: ${existing.status})` + ); + } + const handle = createPluginWorkerHandle(pluginId, options); + workers.set(pluginId, handle); + if (managerOptions?.onWorkerEvent) { + const notify = managerOptions.onWorkerEvent; + handle.on("crash", (payload2) => { + notify({ + type: "plugin.worker.crashed", + pluginId: payload2.pluginId, + code: payload2.code, + signal: payload2.signal, + willRestart: payload2.willRestart + }); + }); + handle.on("ready", (payload2) => { + const diag = handle.diagnostics(); + if (diag.totalCrashes > 0) { + notify({ + type: "plugin.worker.restarted", + pluginId: payload2.pluginId + }); + } + }); + } + log2.info({ pluginId }, "starting plugin worker"); + const startPromise = handle.start().then(() => handle).finally(() => { + startupLocks.delete(pluginId); + }); + startupLocks.set(pluginId, startPromise); + return startPromise; + }, + async stopWorker(pluginId) { + const handle = workers.get(pluginId); + if (!handle) { + log2.warn({ pluginId }, "no worker registered for plugin, nothing to stop"); + return; + } + log2.info({ pluginId }, "stopping plugin worker"); + await handle.stop(); + workers.delete(pluginId); + }, + getWorker(pluginId) { + return workers.get(pluginId); + }, + isRunning(pluginId) { + const handle = workers.get(pluginId); + return handle?.status === "running"; + }, + async stopAll() { + log2.info({ count: workers.size }, "stopping all plugin workers"); + const promises = Array.from(workers.values()).map(async (handle) => { + try { + await handle.stop(); + } catch (err) { + log2.error( + { + pluginId: handle.pluginId, + err: err instanceof Error ? err.message : String(err) + }, + "error stopping worker during shutdown" + ); + } + }); + await Promise.all(promises); + workers.clear(); + }, + diagnostics() { + return Array.from(workers.values()).map((h5) => h5.diagnostics()); + }, + call(pluginId, method, params, timeoutMs) { + const handle = workers.get(pluginId); + if (!handle) { + return Promise.reject( + new Error(`No worker registered for plugin "${pluginId}"`) + ); + } + return handle.call(method, params, timeoutMs); + } + }; +} + +// server/src/services/plugin-job-scheduler.ts +init_drizzle_orm(); +init_src2(); +var DEFAULT_TICK_INTERVAL_MS = 3e4; +var DEFAULT_JOB_TIMEOUT_MS = 5 * 60 * 1e3; +var DEFAULT_MAX_CONCURRENT_JOBS = 10; +function createPluginJobScheduler(options) { + const { + db, + jobStore, + workerManager, + tickIntervalMs = DEFAULT_TICK_INTERVAL_MS, + jobTimeoutMs = DEFAULT_JOB_TIMEOUT_MS, + maxConcurrentJobs = DEFAULT_MAX_CONCURRENT_JOBS + } = options; + const log2 = logger.child({ service: "plugin-job-scheduler" }); + let tickTimer = null; + let running = false; + const activeJobs = /* @__PURE__ */ new Set(); + let tickCount = 0; + let lastTickAt = null; + let tickInProgress = false; + async function tick() { + if (tickInProgress) { + log2.debug("skipping tick \u2014 previous tick still in progress"); + return; + } + tickInProgress = true; + tickCount++; + lastTickAt = /* @__PURE__ */ new Date(); + try { + const now2 = /* @__PURE__ */ new Date(); + const dueJobs = await db.select().from(pluginJobs).where( + and( + eq(pluginJobs.status, "active"), + lte(pluginJobs.nextRunAt, now2) + ) + ); + if (dueJobs.length === 0) { + return; + } + log2.debug({ count: dueJobs.length }, "found due jobs"); + const dispatches = []; + for (const job of dueJobs) { + if (activeJobs.size >= maxConcurrentJobs) { + log2.warn( + { maxConcurrentJobs, activeJobCount: activeJobs.size }, + "max concurrent jobs reached, deferring remaining jobs" + ); + break; + } + if (activeJobs.has(job.id)) { + log2.debug( + { jobId: job.id, jobKey: job.jobKey, pluginId: job.pluginId }, + "skipping job \u2014 already running (overlap prevention)" + ); + continue; + } + if (!workerManager.isRunning(job.pluginId)) { + log2.debug( + { jobId: job.id, pluginId: job.pluginId }, + "skipping job \u2014 worker not running" + ); + continue; + } + if (!job.schedule) { + log2.warn( + { jobId: job.id, jobKey: job.jobKey }, + "skipping job \u2014 no schedule defined" + ); + continue; + } + dispatches.push(dispatchJob(job)); + } + if (dispatches.length > 0) { + await Promise.allSettled(dispatches); + } + } catch (err) { + log2.error( + { err: err instanceof Error ? err.message : String(err) }, + "scheduler tick error" + ); + } finally { + tickInProgress = false; + } + } + async function dispatchJob(job) { + const { id: jobId, pluginId, jobKey, schedule } = job; + const jobLog = log2.child({ jobId, pluginId, jobKey }); + activeJobs.add(jobId); + let runId; + const startedAt = Date.now(); + try { + const run = await jobStore.createRun({ + jobId, + pluginId, + trigger: "schedule" + }); + runId = run.id; + jobLog.info({ runId }, "dispatching scheduled job"); + await jobStore.markRunning(runId); + await workerManager.call( + pluginId, + "runJob", + { + job: { + jobKey, + runId, + trigger: "schedule", + scheduledAt: (job.nextRunAt ?? /* @__PURE__ */ new Date()).toISOString() + } + }, + jobTimeoutMs + ); + const durationMs = Date.now() - startedAt; + await jobStore.completeRun(runId, { + status: "succeeded", + durationMs + }); + jobLog.info({ runId, durationMs }, "job completed successfully"); + } catch (err) { + const durationMs = Date.now() - startedAt; + const errorMessage = err instanceof Error ? err.message : String(err); + jobLog.error( + { runId, durationMs, err: errorMessage }, + "job execution failed" + ); + if (runId) { + try { + await jobStore.completeRun(runId, { + status: "failed", + error: errorMessage, + durationMs + }); + } catch (completeErr) { + jobLog.error( + { + runId, + err: completeErr instanceof Error ? completeErr.message : String(completeErr) + }, + "failed to record job failure" + ); + } + } + } finally { + activeJobs.delete(jobId); + try { + await advanceSchedulePointer(job); + } catch (err) { + jobLog.error( + { err: err instanceof Error ? err.message : String(err) }, + "failed to advance schedule pointer" + ); + } + } + } + async function triggerJob(jobId, trigger = "manual") { + const job = await jobStore.getJobById(jobId); + if (!job) { + throw new Error(`Job not found: ${jobId}`); + } + if (job.status !== "active") { + throw new Error( + `Job "${job.jobKey}" is not active (status: ${job.status})` + ); + } + if (activeJobs.has(jobId)) { + throw new Error( + `Job "${job.jobKey}" is already running \u2014 cannot trigger while in progress` + ); + } + const existingRuns = await db.select().from(pluginJobRuns).where( + and( + eq(pluginJobRuns.jobId, jobId), + eq(pluginJobRuns.status, "running") + ) + ); + if (existingRuns.length > 0) { + throw new Error( + `Job "${job.jobKey}" already has a running execution \u2014 cannot trigger while in progress` + ); + } + if (!workerManager.isRunning(job.pluginId)) { + throw new Error( + `Worker for plugin "${job.pluginId}" is not running \u2014 cannot trigger job` + ); + } + const run = await jobStore.createRun({ + jobId, + pluginId: job.pluginId, + trigger + }); + void dispatchManualRun(job, run.id, trigger); + return { runId: run.id, jobId }; + } + async function dispatchManualRun(job, runId, trigger) { + const { id: jobId, pluginId, jobKey } = job; + const jobLog = log2.child({ jobId, pluginId, jobKey, runId, trigger }); + activeJobs.add(jobId); + const startedAt = Date.now(); + try { + await jobStore.markRunning(runId); + await workerManager.call( + pluginId, + "runJob", + { + job: { + jobKey, + runId, + trigger, + scheduledAt: (/* @__PURE__ */ new Date()).toISOString() + } + }, + jobTimeoutMs + ); + const durationMs = Date.now() - startedAt; + await jobStore.completeRun(runId, { + status: "succeeded", + durationMs + }); + jobLog.info({ durationMs }, "manual job completed successfully"); + } catch (err) { + const durationMs = Date.now() - startedAt; + const errorMessage = err instanceof Error ? err.message : String(err); + jobLog.error({ durationMs, err: errorMessage }, "manual job failed"); + try { + await jobStore.completeRun(runId, { + status: "failed", + error: errorMessage, + durationMs + }); + } catch (completeErr) { + jobLog.error( + { + err: completeErr instanceof Error ? completeErr.message : String(completeErr) + }, + "failed to record manual job failure" + ); + } + } finally { + activeJobs.delete(jobId); + } + } + async function advanceSchedulePointer(job) { + const now2 = /* @__PURE__ */ new Date(); + let nextRunAt = null; + if (job.schedule) { + const validationError = validateCron(job.schedule); + if (validationError) { + log2.warn( + { jobId: job.id, schedule: job.schedule, error: validationError }, + "invalid cron schedule \u2014 cannot compute next run" + ); + } else { + const cron = parseCron(job.schedule); + nextRunAt = nextCronTick(cron, now2); + } + } + await jobStore.updateRunTimestamps(job.id, now2, nextRunAt); + } + async function ensureNextRunTimestamps(pluginId) { + const jobs = await jobStore.listJobs(pluginId, "active"); + for (const job of jobs) { + if (job.nextRunAt && job.nextRunAt.getTime() > Date.now()) { + continue; + } + if (!job.schedule) { + continue; + } + const validationError = validateCron(job.schedule); + if (validationError) { + log2.warn( + { jobId: job.id, jobKey: job.jobKey, schedule: job.schedule, error: validationError }, + "skipping job with invalid cron schedule" + ); + continue; + } + const cron = parseCron(job.schedule); + const nextRunAt = nextCronTick(cron, /* @__PURE__ */ new Date()); + if (nextRunAt) { + await jobStore.updateRunTimestamps( + job.id, + job.lastRunAt ?? /* @__PURE__ */ new Date(0), + nextRunAt + ); + log2.debug( + { jobId: job.id, jobKey: job.jobKey, nextRunAt: nextRunAt.toISOString() }, + "computed nextRunAt for job" + ); + } + } + } + async function registerPlugin(pluginId) { + log2.info({ pluginId }, "registering plugin with job scheduler"); + await ensureNextRunTimestamps(pluginId); + } + async function unregisterPlugin(pluginId) { + log2.info({ pluginId }, "unregistering plugin from job scheduler"); + try { + const runningRuns = await db.select().from(pluginJobRuns).where( + and( + eq(pluginJobRuns.pluginId, pluginId), + or( + eq(pluginJobRuns.status, "running"), + eq(pluginJobRuns.status, "queued") + ) + ) + ); + for (const run of runningRuns) { + await jobStore.completeRun(run.id, { + status: "cancelled", + error: "Plugin unregistered", + durationMs: run.startedAt ? Date.now() - run.startedAt.getTime() : null + }); + } + } catch (err) { + log2.error( + { + pluginId, + err: err instanceof Error ? err.message : String(err) + }, + "error cancelling in-flight runs during unregister" + ); + } + const jobs = await jobStore.listJobs(pluginId); + for (const job of jobs) { + activeJobs.delete(job.id); + } + } + function start() { + if (running) { + log2.debug("scheduler already running"); + return; + } + running = true; + tickTimer = setInterval(() => { + void tick(); + }, tickIntervalMs); + log2.info( + { tickIntervalMs, maxConcurrentJobs }, + "plugin job scheduler started" + ); + } + function stop() { + if (tickTimer !== null) { + clearInterval(tickTimer); + tickTimer = null; + } + if (!running) return; + running = false; + log2.info( + { activeJobCount: activeJobs.size }, + "plugin job scheduler stopped" + ); + } + function diagnostics() { + return { + running, + activeJobCount: activeJobs.size, + activeJobIds: [...activeJobs], + tickCount, + lastTickAt: lastTickAt?.toISOString() ?? null + }; + } + return { + start, + stop, + registerPlugin, + unregisterPlugin, + triggerJob, + tick, + diagnostics + }; +} + +// server/src/services/plugin-job-store.ts +init_drizzle_orm(); +init_src2(); +function pluginJobStore(db) { + async function assertPluginExists(pluginId) { + const rows = await db.select({ id: plugins.id }).from(plugins).where(eq(plugins.id, pluginId)); + if (rows.length === 0) { + throw notFound(`Plugin not found: ${pluginId}`); + } + } + return { + // ===================================================================== + // Job declarations (plugin_jobs) + // ===================================================================== + /** + * Sync declared jobs from a plugin manifest into the `plugin_jobs` table. + * + * This is called at plugin install and on each worker startup so the DB + * always reflects the manifest's declared jobs: + * + * - **New jobs** are inserted with status `active`. + * - **Existing jobs** have their `schedule` updated if it changed. + * - **Removed jobs** (present in DB but absent from the manifest) are + * set to `paused` so their history is preserved. + * + * The unique constraint `(pluginId, jobKey)` is used for conflict + * resolution. + * + * @param pluginId - UUID of the owning plugin + * @param declarations - Job declarations from the plugin manifest + */ + async syncJobDeclarations(pluginId, declarations) { + await assertPluginExists(pluginId); + const existingJobs = await db.select().from(pluginJobs).where(eq(pluginJobs.pluginId, pluginId)); + const existingByKey = new Map( + existingJobs.map((j5) => [j5.jobKey, j5]) + ); + const declaredKeys = /* @__PURE__ */ new Set(); + for (const decl of declarations) { + declaredKeys.add(decl.jobKey); + const existing = existingByKey.get(decl.jobKey); + const schedule = decl.schedule ?? ""; + if (existing) { + const updates = { + updatedAt: /* @__PURE__ */ new Date() + }; + if (existing.schedule !== schedule) { + updates.schedule = schedule; + } + if (existing.status === "paused") { + updates.status = "active"; + } + await db.update(pluginJobs).set(updates).where(eq(pluginJobs.id, existing.id)); + } else { + await db.insert(pluginJobs).values({ + pluginId, + jobKey: decl.jobKey, + schedule, + status: "active" + }); + } + } + for (const existing of existingJobs) { + if (!declaredKeys.has(existing.jobKey) && existing.status !== "paused") { + await db.update(pluginJobs).set({ status: "paused", updatedAt: /* @__PURE__ */ new Date() }).where(eq(pluginJobs.id, existing.id)); + } + } + }, + /** + * List all jobs for a plugin, optionally filtered by status. + * + * @param pluginId - UUID of the owning plugin + * @param status - Optional status filter + */ + async listJobs(pluginId, status) { + const conditions = [eq(pluginJobs.pluginId, pluginId)]; + if (status) { + conditions.push(eq(pluginJobs.status, status)); + } + return db.select().from(pluginJobs).where(and(...conditions)); + }, + /** + * Get a single job by its composite key `(pluginId, jobKey)`. + * + * @param pluginId - UUID of the owning plugin + * @param jobKey - Stable job identifier from the manifest + * @returns The job row, or `null` if not found + */ + async getJobByKey(pluginId, jobKey) { + const rows = await db.select().from(pluginJobs).where( + and( + eq(pluginJobs.pluginId, pluginId), + eq(pluginJobs.jobKey, jobKey) + ) + ); + return rows[0] ?? null; + }, + /** + * Get a single job by its primary key (UUID). + * + * @param jobId - UUID of the job row + * @returns The job row, or `null` if not found + */ + async getJobById(jobId) { + const rows = await db.select().from(pluginJobs).where(eq(pluginJobs.id, jobId)); + return rows[0] ?? null; + }, + /** + * Fetch a single job by ID, scoped to a specific plugin. + * + * Returns `null` if the job does not exist or does not belong to the + * given plugin — callers should treat both cases as "not found". + */ + async getJobByIdForPlugin(pluginId, jobId) { + const rows = await db.select().from(pluginJobs).where(and(eq(pluginJobs.id, jobId), eq(pluginJobs.pluginId, pluginId))); + return rows[0] ?? null; + }, + /** + * Update a job's status. + * + * @param jobId - UUID of the job row + * @param status - New status + */ + async updateJobStatus(jobId, status) { + await db.update(pluginJobs).set({ status, updatedAt: /* @__PURE__ */ new Date() }).where(eq(pluginJobs.id, jobId)); + }, + /** + * Update the `lastRunAt` and `nextRunAt` timestamps on a job. + * + * Called by the scheduler after a run completes to advance the + * scheduling pointer. + * + * @param jobId - UUID of the job row + * @param lastRunAt - When the last run started + * @param nextRunAt - When the next run should fire + */ + async updateRunTimestamps(jobId, lastRunAt, nextRunAt) { + await db.update(pluginJobs).set({ + lastRunAt, + nextRunAt, + updatedAt: /* @__PURE__ */ new Date() + }).where(eq(pluginJobs.id, jobId)); + }, + /** + * Delete all jobs (and cascaded runs) owned by a plugin. + * + * Called during plugin uninstall when `removeData = true`. + * + * @param pluginId - UUID of the owning plugin + */ + async deleteAllJobs(pluginId) { + await db.delete(pluginJobs).where(eq(pluginJobs.pluginId, pluginId)); + }, + // ===================================================================== + // Job runs (plugin_job_runs) + // ===================================================================== + /** + * Create a new job run record with status `queued`. + * + * The caller should create the run record *before* dispatching the + * `runJob` RPC to the worker, then update it to `running` once the + * worker begins execution. + * + * @param input - Job run input (jobId, pluginId, trigger) + * @returns The newly created run row + */ + async createRun(input) { + const rows = await db.insert(pluginJobRuns).values({ + jobId: input.jobId, + pluginId: input.pluginId, + trigger: input.trigger, + status: "queued" + }).returning(); + return rows[0]; + }, + /** + * Mark a run as `running` and set its `startedAt` timestamp. + * + * @param runId - UUID of the run row + */ + async markRunning(runId) { + await db.update(pluginJobRuns).set({ + status: "running", + startedAt: /* @__PURE__ */ new Date() + }).where(eq(pluginJobRuns.id, runId)); + }, + /** + * Complete a run — set its final status, error, duration, and + * `finishedAt` timestamp. + * + * @param runId - UUID of the run row + * @param input - Completion details + */ + async completeRun(runId, input) { + await db.update(pluginJobRuns).set({ + status: input.status, + error: input.error ?? null, + durationMs: input.durationMs ?? null, + finishedAt: /* @__PURE__ */ new Date() + }).where(eq(pluginJobRuns.id, runId)); + }, + /** + * Get a run by its primary key. + * + * @param runId - UUID of the run row + * @returns The run row, or `null` if not found + */ + async getRunById(runId) { + const rows = await db.select().from(pluginJobRuns).where(eq(pluginJobRuns.id, runId)); + return rows[0] ?? null; + }, + /** + * List runs for a specific job, ordered by creation time descending. + * + * @param jobId - UUID of the job + * @param limit - Maximum number of rows to return (default: 50) + */ + async listRunsByJob(jobId, limit = 50) { + return db.select().from(pluginJobRuns).where(eq(pluginJobRuns.jobId, jobId)).orderBy(desc(pluginJobRuns.createdAt)).limit(limit); + }, + /** + * List runs for a plugin, optionally filtered by status. + * + * @param pluginId - UUID of the owning plugin + * @param status - Optional status filter + * @param limit - Maximum number of rows to return (default: 50) + */ + async listRunsByPlugin(pluginId, status, limit = 50) { + const conditions = [eq(pluginJobRuns.pluginId, pluginId)]; + if (status) { + conditions.push(eq(pluginJobRuns.status, status)); + } + return db.select().from(pluginJobRuns).where(and(...conditions)).orderBy(desc(pluginJobRuns.createdAt)).limit(limit); + } + }; +} + +// server/src/services/plugin-tool-registry.ts +var TOOL_NAMESPACE_SEPARATOR = ":"; +function createPluginToolRegistry(workerManager) { + const log2 = logger.child({ service: "plugin-tool-registry" }); + const byNamespace = /* @__PURE__ */ new Map(); + const byPlugin = /* @__PURE__ */ new Map(); + function buildName(pluginId, toolName) { + return `${pluginId}${TOOL_NAMESPACE_SEPARATOR}${toolName}`; + } + function parseName(namespacedName) { + const sepIndex = namespacedName.lastIndexOf(TOOL_NAMESPACE_SEPARATOR); + if (sepIndex <= 0 || sepIndex >= namespacedName.length - 1) { + return null; + } + return { + pluginId: namespacedName.slice(0, sepIndex), + toolName: namespacedName.slice(sepIndex + 1) + }; + } + function addTool(pluginId, decl, pluginDbId) { + const namespacedName = buildName(pluginId, decl.name); + const entry = { + pluginId, + pluginDbId, + name: decl.name, + namespacedName, + displayName: decl.displayName, + description: decl.description, + parametersSchema: decl.parametersSchema + }; + byNamespace.set(namespacedName, entry); + let pluginTools = byPlugin.get(pluginId); + if (!pluginTools) { + pluginTools = /* @__PURE__ */ new Set(); + byPlugin.set(pluginId, pluginTools); + } + pluginTools.add(namespacedName); + } + function removePluginTools(pluginId) { + const pluginTools = byPlugin.get(pluginId); + if (!pluginTools) return 0; + const count2 = pluginTools.size; + for (const name of pluginTools) { + byNamespace.delete(name); + } + byPlugin.delete(pluginId); + return count2; + } + return { + registerPlugin(pluginId, manifest, pluginDbId) { + const dbId = pluginDbId ?? pluginId; + const previousCount = removePluginTools(pluginId); + if (previousCount > 0) { + log2.debug( + { pluginId, previousCount }, + "cleared previous tool registrations before re-registering" + ); + } + const tools = manifest.tools ?? []; + if (tools.length === 0) { + log2.debug({ pluginId }, "plugin declares no tools"); + return; + } + for (const decl of tools) { + addTool(pluginId, decl, dbId); + } + log2.info( + { + pluginId, + toolCount: tools.length, + tools: tools.map((t5) => buildName(pluginId, t5.name)) + }, + `registered ${tools.length} tool(s) for plugin` + ); + }, + unregisterPlugin(pluginId) { + const removed = removePluginTools(pluginId); + if (removed > 0) { + log2.info( + { pluginId, removedCount: removed }, + `unregistered ${removed} tool(s) for plugin` + ); + } + }, + getTool(namespacedName) { + return byNamespace.get(namespacedName) ?? null; + }, + getToolByPlugin(pluginId, toolName) { + const namespacedName = buildName(pluginId, toolName); + return byNamespace.get(namespacedName) ?? null; + }, + listTools(filter) { + if (filter?.pluginId) { + const pluginTools = byPlugin.get(filter.pluginId); + if (!pluginTools) return []; + const result = []; + for (const name of pluginTools) { + const tool = byNamespace.get(name); + if (tool) result.push(tool); + } + return result; + } + return Array.from(byNamespace.values()); + }, + parseNamespacedName(namespacedName) { + return parseName(namespacedName); + }, + buildNamespacedName(pluginId, toolName) { + return buildName(pluginId, toolName); + }, + async executeTool(namespacedName, parameters, runContext) { + const parsed = parseName(namespacedName); + if (!parsed) { + throw new Error( + `Invalid tool name "${namespacedName}". Expected format: "${TOOL_NAMESPACE_SEPARATOR}"` + ); + } + const { pluginId, toolName } = parsed; + const tool = byNamespace.get(namespacedName); + if (!tool) { + throw new Error( + `Tool "${namespacedName}" is not registered. The plugin may not be installed or its worker may not be running.` + ); + } + if (!workerManager) { + throw new Error( + `Cannot execute tool "${namespacedName}" \u2014 no worker manager configured. Tool execution requires a PluginWorkerManager.` + ); + } + const dbId = tool.pluginDbId; + if (!workerManager.isRunning(dbId)) { + throw new Error( + `Cannot execute tool "${namespacedName}" \u2014 worker for plugin "${pluginId}" is not running.` + ); + } + log2.debug( + { pluginId, pluginDbId: dbId, toolName, namespacedName, agentId: runContext.agentId, runId: runContext.runId }, + "executing tool via plugin worker" + ); + const rpcParams = { + toolName, + parameters, + runContext + }; + const result = await workerManager.call(dbId, "executeTool", rpcParams); + log2.debug( + { + pluginId, + toolName, + namespacedName, + hasContent: !!result.content, + hasData: result.data !== void 0, + hasError: !!result.error + }, + "tool execution completed" + ); + return { pluginId, toolName, result }; + }, + toolCount(pluginId) { + if (pluginId !== void 0) { + return byPlugin.get(pluginId)?.size ?? 0; + } + return byNamespace.size; + } + }; +} + +// server/src/services/plugin-tool-dispatcher.ts +function createPluginToolDispatcher(options = {}) { + const { workerManager, lifecycleManager, db } = options; + const log2 = logger.child({ service: "plugin-tool-dispatcher" }); + const registry2 = createPluginToolRegistry(workerManager); + let enabledListener = null; + let disabledListener = null; + let unloadedListener = null; + let initialized = false; + async function registerFromDb(pluginId) { + if (!db) { + log2.warn( + { pluginId }, + "cannot register tools from DB \u2014 no database connection configured" + ); + return; + } + const pluginRegistry = pluginRegistryService(db); + const plugin = await pluginRegistry.getById(pluginId); + if (!plugin) { + log2.warn({ pluginId }, "plugin not found in registry, cannot register tools"); + return; + } + const manifest = plugin.manifestJson; + if (!manifest) { + log2.warn({ pluginId }, "plugin has no manifest, cannot register tools"); + return; + } + registry2.registerPlugin(plugin.pluginKey, manifest, plugin.id); + } + function toAgentDescriptor(tool) { + return { + name: tool.namespacedName, + displayName: tool.displayName, + description: tool.description, + parametersSchema: tool.parametersSchema, + pluginId: tool.pluginDbId + }; + } + function handlePluginEnabled(payload2) { + log2.debug({ pluginId: payload2.pluginId, pluginKey: payload2.pluginKey }, "plugin enabled \u2014 registering tools"); + void registerFromDb(payload2.pluginId).catch((err) => { + log2.error( + { pluginId: payload2.pluginId, err: err instanceof Error ? err.message : String(err) }, + "failed to register tools after plugin enabled" + ); + }); + } + function handlePluginDisabled(payload2) { + log2.debug({ pluginId: payload2.pluginId, pluginKey: payload2.pluginKey }, "plugin disabled \u2014 unregistering tools"); + registry2.unregisterPlugin(payload2.pluginKey); + } + function handlePluginUnloaded(payload2) { + log2.debug({ pluginId: payload2.pluginId, pluginKey: payload2.pluginKey }, "plugin unloaded \u2014 unregistering tools"); + registry2.unregisterPlugin(payload2.pluginKey); + } + return { + async initialize() { + if (initialized) { + log2.warn("dispatcher already initialized, skipping"); + return; + } + log2.info("initializing plugin tool dispatcher"); + if (db) { + const pluginRegistry = pluginRegistryService(db); + const readyPlugins = await pluginRegistry.listByStatus("ready"); + let totalTools = 0; + for (const plugin of readyPlugins) { + const manifest = plugin.manifestJson; + if (manifest?.tools && manifest.tools.length > 0) { + registry2.registerPlugin(plugin.pluginKey, manifest, plugin.id); + totalTools += manifest.tools.length; + } + } + log2.info( + { readyPlugins: readyPlugins.length, registeredTools: totalTools }, + "loaded tools from ready plugins" + ); + } + if (lifecycleManager) { + enabledListener = handlePluginEnabled; + disabledListener = handlePluginDisabled; + unloadedListener = handlePluginUnloaded; + lifecycleManager.on("plugin.enabled", enabledListener); + lifecycleManager.on("plugin.disabled", disabledListener); + lifecycleManager.on("plugin.unloaded", unloadedListener); + log2.debug("subscribed to lifecycle events"); + } else { + log2.warn("no lifecycle manager provided \u2014 tools will not auto-update on plugin state changes"); + } + initialized = true; + log2.info( + { totalTools: registry2.toolCount() }, + "plugin tool dispatcher initialized" + ); + }, + teardown() { + if (!initialized) return; + if (lifecycleManager) { + if (enabledListener) lifecycleManager.off("plugin.enabled", enabledListener); + if (disabledListener) lifecycleManager.off("plugin.disabled", disabledListener); + if (unloadedListener) lifecycleManager.off("plugin.unloaded", unloadedListener); + enabledListener = null; + disabledListener = null; + unloadedListener = null; + } + initialized = false; + log2.info("plugin tool dispatcher torn down"); + }, + listToolsForAgent(filter) { + return registry2.listTools(filter).map(toAgentDescriptor); + }, + getTool(namespacedName) { + return registry2.getTool(namespacedName); + }, + async executeTool(namespacedName, parameters, runContext) { + log2.debug( + { + tool: namespacedName, + agentId: runContext.agentId, + runId: runContext.runId + }, + "dispatching tool execution" + ); + const result = await registry2.executeTool( + namespacedName, + parameters, + runContext + ); + log2.debug( + { + tool: namespacedName, + pluginId: result.pluginId, + hasContent: !!result.result.content, + hasError: !!result.result.error + }, + "tool execution completed" + ); + return result; + }, + registerPluginTools(pluginId, manifest) { + registry2.registerPlugin(pluginId, manifest); + }, + unregisterPluginTools(pluginId) { + registry2.unregisterPlugin(pluginId); + }, + toolCount(pluginId) { + return registry2.toolCount(pluginId); + }, + getRegistry() { + return registry2; + } + }; +} + +// server/src/services/plugin-job-coordinator.ts +function createPluginJobCoordinator(options) { + const { db, lifecycle, scheduler, jobStore } = options; + const log2 = logger.child({ service: "plugin-job-coordinator" }); + const registry2 = pluginRegistryService(db); + async function onPluginLoaded(payload2) { + const { pluginId, pluginKey } = payload2; + log2.info({ pluginId, pluginKey }, "plugin loaded \u2014 syncing jobs and registering with scheduler"); + try { + const plugin = await registry2.getById(pluginId); + if (!plugin?.manifestJson) { + log2.warn({ pluginId, pluginKey }, "plugin loaded but no manifest found \u2014 skipping job sync"); + return; + } + const manifest = plugin.manifestJson; + const jobDeclarations = manifest.jobs ?? []; + if (jobDeclarations.length > 0) { + log2.info( + { pluginId, pluginKey, jobCount: jobDeclarations.length }, + "syncing job declarations from manifest" + ); + await jobStore.syncJobDeclarations(pluginId, jobDeclarations); + } + await scheduler.registerPlugin(pluginId); + } catch (err) { + log2.error( + { + pluginId, + pluginKey, + err: err instanceof Error ? err.message : String(err) + }, + "failed to sync jobs or register plugin with scheduler" + ); + } + } + async function onPluginDisabled(payload2) { + const { pluginId, pluginKey, reason } = payload2; + log2.info( + { pluginId, pluginKey, reason }, + "plugin disabled \u2014 unregistering from scheduler" + ); + try { + await scheduler.unregisterPlugin(pluginId); + } catch (err) { + log2.error( + { + pluginId, + pluginKey, + err: err instanceof Error ? err.message : String(err) + }, + "failed to unregister plugin from scheduler" + ); + } + } + async function onPluginUnloaded(payload2) { + const { pluginId, pluginKey, removeData } = payload2; + log2.info( + { pluginId, pluginKey, removeData }, + "plugin unloaded \u2014 unregistering from scheduler" + ); + try { + await scheduler.unregisterPlugin(pluginId); + if (removeData) { + log2.info({ pluginId, pluginKey }, "purging job data for uninstalled plugin"); + await jobStore.deleteAllJobs(pluginId); + } + } catch (err) { + log2.error( + { + pluginId, + pluginKey, + err: err instanceof Error ? err.message : String(err) + }, + "failed to unregister plugin from scheduler during unload" + ); + } + } + let attached = false; + const boundOnLoaded = (payload2) => { + void onPluginLoaded(payload2); + }; + const boundOnDisabled = (payload2) => { + void onPluginDisabled(payload2); + }; + const boundOnUnloaded = (payload2) => { + void onPluginUnloaded(payload2); + }; + return { + start() { + if (attached) return; + attached = true; + lifecycle.on("plugin.loaded", boundOnLoaded); + lifecycle.on("plugin.disabled", boundOnDisabled); + lifecycle.on("plugin.unloaded", boundOnUnloaded); + log2.info("plugin job coordinator started \u2014 listening to lifecycle events"); + }, + stop() { + if (!attached) return; + attached = false; + lifecycle.off("plugin.loaded", boundOnLoaded); + lifecycle.off("plugin.disabled", boundOnDisabled); + lifecycle.off("plugin.unloaded", boundOnUnloaded); + log2.info("plugin job coordinator stopped"); + } + }; +} + +// server/src/services/plugin-host-services.ts +init_src2(); +init_drizzle_orm(); +import { randomUUID as randomUUID11 } from "node:crypto"; + +// server/src/services/plugin-state-store.ts +init_drizzle_orm(); +init_src2(); +var DEFAULT_NAMESPACE = "default"; +function scopeConditions(pluginId, scopeKind, scopeId, namespace, stateKey) { + const conditions = [ + eq(pluginState.pluginId, pluginId), + eq(pluginState.scopeKind, scopeKind), + eq(pluginState.namespace, namespace), + eq(pluginState.stateKey, stateKey) + ]; + if (scopeId != null && scopeId !== "") { + conditions.push(eq(pluginState.scopeId, scopeId)); + } else { + conditions.push(isNull(pluginState.scopeId)); + } + return and(...conditions); +} +function pluginStateStore(db) { + async function assertPluginExists(pluginId) { + const rows = await db.select({ id: plugins.id }).from(plugins).where(eq(plugins.id, pluginId)); + if (rows.length === 0) { + throw notFound(`Plugin not found: ${pluginId}`); + } + } + return { + /** + * Read a state value. + * + * Returns the stored JSON value, or `null` if no entry exists for the + * given scope and key. + * + * Requires `plugin.state.read` capability (enforced by the caller). + * + * @param pluginId - UUID of the owning plugin + * @param scopeKind - Granularity of the scope + * @param scopeId - Identifier for the scoped entity (null for `instance` scope) + * @param stateKey - The key to read + * @param namespace - Sub-namespace (defaults to `"default"`) + */ + get: async (pluginId, scopeKind, stateKey, { + scopeId, + namespace = DEFAULT_NAMESPACE + } = {}) => { + const rows = await db.select().from(pluginState).where(scopeConditions(pluginId, scopeKind, scopeId, namespace, stateKey)); + return rows[0]?.valueJson ?? null; + }, + /** + * Write (create or replace) a state value. + * + * Uses an upsert so the caller does not need to check for prior existence. + * On conflict (same composite key) the existing row's `value_json` and + * `updated_at` are overwritten. + * + * Requires `plugin.state.write` capability (enforced by the caller). + * + * @param pluginId - UUID of the owning plugin + * @param input - Scope key and value to store + */ + set: async (pluginId, input) => { + await assertPluginExists(pluginId); + const namespace = input.namespace ?? DEFAULT_NAMESPACE; + const scopeId = input.scopeId ?? null; + await db.insert(pluginState).values({ + pluginId, + scopeKind: input.scopeKind, + scopeId, + namespace, + stateKey: input.stateKey, + valueJson: input.value, + updatedAt: /* @__PURE__ */ new Date() + }).onConflictDoUpdate({ + target: [ + pluginState.pluginId, + pluginState.scopeKind, + pluginState.scopeId, + pluginState.namespace, + pluginState.stateKey + ], + set: { + valueJson: input.value, + updatedAt: /* @__PURE__ */ new Date() + } + }); + }, + /** + * Delete a state value. + * + * No-ops silently if the entry does not exist (idempotent by design). + * + * Requires `plugin.state.write` capability (enforced by the caller). + * + * @param pluginId - UUID of the owning plugin + * @param scopeKind - Granularity of the scope + * @param stateKey - The key to delete + * @param scopeId - Identifier for the scoped entity (null for `instance` scope) + * @param namespace - Sub-namespace (defaults to `"default"`) + */ + delete: async (pluginId, scopeKind, stateKey, { + scopeId, + namespace = DEFAULT_NAMESPACE + } = {}) => { + await db.delete(pluginState).where(scopeConditions(pluginId, scopeKind, scopeId, namespace, stateKey)); + }, + /** + * List all state entries for a plugin, optionally filtered by scope. + * + * Returns all matching rows as `PluginStateRecord`-shaped objects. + * The `valueJson` field contains the stored value. + * + * Requires `plugin.state.read` capability (enforced by the caller). + * + * @param pluginId - UUID of the owning plugin + * @param filter - Optional scope filters (scopeKind, scopeId, namespace) + */ + list: async (pluginId, filter = {}) => { + const conditions = [eq(pluginState.pluginId, pluginId)]; + if (filter.scopeKind !== void 0) { + conditions.push(eq(pluginState.scopeKind, filter.scopeKind)); + } + if (filter.scopeId !== void 0) { + conditions.push(eq(pluginState.scopeId, filter.scopeId)); + } + if (filter.namespace !== void 0) { + conditions.push(eq(pluginState.namespace, filter.namespace)); + } + return db.select().from(pluginState).where(and(...conditions)); + }, + /** + * Delete all state entries owned by a plugin. + * + * Called during plugin uninstall when `removeData = true`. Also useful + * for resetting a plugin's state during testing. + * + * @param pluginId - UUID of the owning plugin + */ + deleteAll: async (pluginId) => { + await db.delete(pluginState).where(eq(pluginState.pluginId, pluginId)); + } + }; +} + +// server/src/services/plugin-secrets-handler.ts +init_drizzle_orm(); +init_src2(); +function secretNotFound(secretRef) { + const err = new Error(`Secret not found: ${secretRef}`); + err.name = "SecretNotFoundError"; + return err; +} +function secretVersionNotFound(secretRef) { + const err = new Error(`No version found for secret: ${secretRef}`); + err.name = "SecretVersionNotFoundError"; + return err; +} +function invalidSecretRef(secretRef) { + const err = new Error(`Invalid secret reference: ${secretRef}`); + err.name = "InvalidSecretRefError"; + return err; +} +var UUID_RE3 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; +function isUuid(value) { + return UUID_RE3.test(value); +} +function collectSecretRefPaths(schema2) { + const paths2 = /* @__PURE__ */ new Set(); + if (!schema2 || typeof schema2 !== "object") return paths2; + function walk(node, prefix) { + const props = node.properties; + if (!props || typeof props !== "object") return; + for (const [key, propSchema] of Object.entries(props)) { + if (!propSchema || typeof propSchema !== "object") continue; + const path53 = prefix ? `${prefix}.${key}` : key; + if (propSchema.format === "secret-ref") { + paths2.add(path53); + } + if (propSchema.type === "object") { + walk(propSchema, path53); + } + } + } + walk(schema2, ""); + return paths2; +} +function extractSecretRefsFromConfig(configJson, schema2) { + const refs = /* @__PURE__ */ new Set(); + if (configJson == null || typeof configJson !== "object") return refs; + const secretPaths = collectSecretRefPaths(schema2); + if (secretPaths.size > 0) { + for (const dotPath of secretPaths) { + const keys = dotPath.split("."); + let current = configJson; + for (const k5 of keys) { + if (current == null || typeof current !== "object") { + current = void 0; + break; + } + current = current[k5]; + } + if (typeof current === "string" && isUuid(current)) { + refs.add(current); + } + } + return refs; + } + function walkAll(value) { + if (typeof value === "string") { + if (isUuid(value)) refs.add(value); + } else if (Array.isArray(value)) { + for (const item of value) walkAll(item); + } else if (value !== null && typeof value === "object") { + for (const v5 of Object.values(value)) walkAll(v5); + } + } + walkAll(configJson); + return refs; +} +function createRateLimiter(maxAttempts, windowMs) { + const attempts = /* @__PURE__ */ new Map(); + return { + check(key) { + const now2 = Date.now(); + const windowStart = now2 - windowMs; + const existing = (attempts.get(key) ?? []).filter((ts) => ts > windowStart); + if (existing.length >= maxAttempts) return false; + existing.push(now2); + attempts.set(key, existing); + return true; + } + }; +} +function createPluginSecretsHandler(options) { + const { db, pluginId } = options; + const registry2 = pluginRegistryService(db); + const rateLimiter = createRateLimiter(30, 6e4); + let cachedAllowedRefs = null; + let cachedAllowedRefsExpiry = 0; + const CONFIG_CACHE_TTL_MS = 3e4; + return { + async resolve(params) { + const { secretRef } = params; + if (!rateLimiter.check(pluginId)) { + const err = new Error("Rate limit exceeded for secret resolution"); + err.name = "RateLimitExceededError"; + throw err; + } + if (!secretRef || typeof secretRef !== "string" || secretRef.trim().length === 0) { + throw invalidSecretRef(secretRef ?? ""); + } + const trimmedRef = secretRef.trim(); + if (!isUuid(trimmedRef)) { + throw invalidSecretRef(trimmedRef); + } + const now2 = Date.now(); + if (!cachedAllowedRefs || now2 > cachedAllowedRefsExpiry) { + const [configRow, plugin] = await Promise.all([ + db.select().from(pluginConfig).where(eq(pluginConfig.pluginId, pluginId)).then((rows) => rows[0] ?? null), + registry2.getById(pluginId) + ]); + const schema2 = plugin?.manifestJson?.instanceConfigSchema; + cachedAllowedRefs = extractSecretRefsFromConfig(configRow?.configJson, schema2); + cachedAllowedRefsExpiry = now2 + CONFIG_CACHE_TTL_MS; + } + if (!cachedAllowedRefs.has(trimmedRef)) { + throw secretNotFound(trimmedRef); + } + const secret = await db.select().from(companySecrets).where(eq(companySecrets.id, trimmedRef)).then((rows) => rows[0] ?? null); + if (!secret) { + throw secretNotFound(trimmedRef); + } + const versionRow = await db.select().from(companySecretVersions).where( + and( + eq(companySecretVersions.secretId, secret.id), + eq(companySecretVersions.version, secret.latestVersion) + ) + ).then((rows) => rows[0] ?? null); + if (!versionRow) { + throw secretVersionNotFound(trimmedRef); + } + const provider = getSecretProvider(secret.provider); + const resolved = await provider.resolveVersion({ + material: versionRow.material, + externalRef: secret.externalRef + }); + return resolved; + } + }; +} + +// server/src/services/plugin-host-services.ts +import { lookup as dnsLookup } from "node:dns/promises"; +import { request as httpRequest } from "node:http"; +import { request as httpsRequest } from "node:https"; +import { isIP } from "node:net"; +var PLUGIN_FETCH_TIMEOUT_MS = 3e4; +var DNS_LOOKUP_TIMEOUT_MS = 5e3; +var ALLOWED_PROTOCOLS = /* @__PURE__ */ new Set(["http:", "https:"]); +var TELEMETRY_EVENT_NAME_REGEX = /^[a-z0-9][a-z0-9_-]*$/; +function isPrivateIP(ip) { + const lower = ip.toLowerCase(); + const v4MappedMatch = lower.match(/^::ffff:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/); + if (v4MappedMatch && v4MappedMatch[1]) return isPrivateIP(v4MappedMatch[1]); + if (ip.startsWith("10.")) return true; + if (ip.startsWith("172.")) { + const second = parseInt(ip.split(".")[1], 10); + if (second >= 16 && second <= 31) return true; + } + if (ip.startsWith("192.168.")) return true; + if (ip.startsWith("127.")) return true; + if (ip.startsWith("169.254.")) return true; + if (ip === "0.0.0.0") return true; + if (lower === "::1") return true; + if (lower.startsWith("fc") || lower.startsWith("fd")) return true; + if (lower.startsWith("fe80")) return true; + if (lower === "::") return true; + return false; +} +async function validateAndResolveFetchUrl(urlString) { + let parsed; + try { + parsed = new URL(urlString); + } catch { + throw new Error(`Invalid URL: ${urlString}`); + } + if (!ALLOWED_PROTOCOLS.has(parsed.protocol)) { + throw new Error( + `Disallowed protocol "${parsed.protocol}" \u2014 only http: and https: are permitted` + ); + } + const originalHostname = parsed.hostname.replace(/^\[|\]$/g, ""); + const hostHeader = parsed.host; + const dnsPromise = dnsLookup(originalHostname, { all: true }); + const timeoutPromise = new Promise((_, reject) => { + setTimeout( + () => reject(new Error(`DNS lookup timed out after ${DNS_LOOKUP_TIMEOUT_MS}ms for ${originalHostname}`)), + DNS_LOOKUP_TIMEOUT_MS + ); + }); + try { + const results = await Promise.race([dnsPromise, timeoutPromise]); + if (results.length === 0) { + throw new Error(`DNS resolution returned no results for ${originalHostname}`); + } + const safeResults = results.filter((entry) => !isPrivateIP(entry.address)); + if (safeResults.length === 0) { + throw new Error( + `All resolved IPs for ${originalHostname} are in private/reserved ranges` + ); + } + const resolved = safeResults[0]; + return { + parsedUrl: parsed, + resolvedAddress: resolved.address, + hostHeader, + tlsServername: parsed.protocol === "https:" && isIP(originalHostname) === 0 ? originalHostname : void 0, + useTls: parsed.protocol === "https:" + }; + } catch (err) { + if (err instanceof Error && (err.message.startsWith("All resolved IPs") || err.message.startsWith("DNS resolution returned") || err.message.startsWith("DNS lookup timed out"))) throw err; + throw new Error(`DNS resolution failed for ${originalHostname}: ${err.message}`); + } +} +function buildPinnedRequestOptions(target, init2) { + const headers = new Headers(init2?.headers); + const method = init2?.method ?? "GET"; + const body = init2?.body === void 0 || init2?.body === null ? void 0 : typeof init2.body === "string" ? init2.body : String(init2.body); + headers.set("Host", target.hostHeader); + if (body !== void 0 && !headers.has("content-length") && !headers.has("transfer-encoding")) { + headers.set("content-length", String(Buffer.byteLength(body))); + } + const pathname = `${target.parsedUrl.pathname}${target.parsedUrl.search}`; + const auth = target.parsedUrl.username || target.parsedUrl.password ? `${decodeURIComponent(target.parsedUrl.username)}:${decodeURIComponent(target.parsedUrl.password)}` : void 0; + return { + options: { + protocol: target.parsedUrl.protocol, + host: target.resolvedAddress, + port: target.parsedUrl.port ? Number(target.parsedUrl.port) : target.useTls ? 443 : 80, + path: pathname, + method, + headers: Object.fromEntries(headers.entries()), + auth, + servername: target.tlsServername + }, + body + }; +} +async function executePinnedHttpRequest(target, init2, signal) { + const { options, body } = buildPinnedRequestOptions(target, init2); + const response = await new Promise((resolve4, reject) => { + const requestFn = target.useTls ? httpsRequest : httpRequest; + const req = requestFn({ ...options, signal }, resolve4); + req.on("error", reject); + if (body !== void 0) { + req.write(body); + } + req.end(); + }); + const MAX_RESPONSE_BODY_BYTES = 200 * 1024 * 1024; + const chunks = []; + let totalBytes = 0; + await new Promise((resolve4, reject) => { + response.on("data", (chunk) => { + const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk); + totalBytes += buf.length; + if (totalBytes > MAX_RESPONSE_BODY_BYTES) { + chunks.length = 0; + response.destroy(new Error(`Response body exceeded ${MAX_RESPONSE_BODY_BYTES} bytes`)); + return; + } + chunks.push(buf); + }); + response.on("end", resolve4); + response.on("error", reject); + }); + const headers = {}; + for (const [key, value] of Object.entries(response.headers)) { + if (Array.isArray(value)) { + headers[key] = value.join(", "); + } else if (value !== void 0) { + headers[key] = value; + } + } + return { + status: response.statusCode ?? 500, + statusText: response.statusMessage ?? "", + headers, + body: Buffer.concat(chunks).toString("utf8") + }; +} +var UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i; +var PATH_LIKE_PATTERN = /[\\/]/; +var WINDOWS_DRIVE_PATH_PATTERN = /^[A-Za-z]:[\\/]/; +function looksLikePath(value) { + const normalized = value.trim(); + return (PATH_LIKE_PATTERN.test(normalized) || WINDOWS_DRIVE_PATH_PATTERN.test(normalized)) && !UUID_PATTERN.test(normalized); +} +function sanitizeWorkspaceText(value) { + const trimmed = value.trim(); + if (!trimmed || UUID_PATTERN.test(trimmed)) return ""; + return trimmed; +} +function sanitizeWorkspacePath(cwd) { + if (!cwd) return ""; + return looksLikePath(cwd) ? cwd.trim() : ""; +} +function sanitizeWorkspaceName(name, fallbackPath) { + const safeName = sanitizeWorkspaceText(name); + if (safeName && !looksLikePath(safeName)) { + return safeName; + } + const normalized = fallbackPath.trim().replace(/[\\/]+$/, ""); + const segments = normalized.split(/[\\/]/).filter(Boolean); + return segments[segments.length - 1] ?? "Workspace"; +} +var LOG_BUFFER_FLUSH_SIZE = 100; +var LOG_BUFFER_FLUSH_INTERVAL_MS = 5e3; +var MAX_LOG_MESSAGE_LENGTH = 1e4; +var MAX_LOG_META_JSON_LENGTH = 5e4; +var MAX_METRIC_NAME_LENGTH = 500; +var PINO_RESERVED_KEYS = /* @__PURE__ */ new Set([ + "level", + "time", + "pid", + "hostname", + "msg", + "v" +]); +function truncStr(s5, max) { + if (s5.length <= max) return s5; + return s5.slice(0, max) + "...[truncated]"; +} +function sanitiseMeta(meta3) { + if (meta3 == null) return null; + const cleaned = {}; + for (const [k5, v5] of Object.entries(meta3)) { + if (!PINO_RESERVED_KEYS.has(k5)) { + cleaned[k5] = v5; + } + } + let json3; + try { + json3 = JSON.stringify(cleaned); + } catch { + return { _sanitised: true, _error: "meta was not JSON-serialisable" }; + } + if (json3.length > MAX_LOG_META_JSON_LENGTH) { + return { _sanitised: true, _error: `meta exceeded ${MAX_LOG_META_JSON_LENGTH} chars` }; + } + return cleaned; +} +var _logBuffer = []; +async function flushPluginLogBuffer() { + if (_logBuffer.length === 0) return; + const entries2 = _logBuffer.splice(0, _logBuffer.length); + const byDb = /* @__PURE__ */ new Map(); + for (const entry of entries2) { + const group = byDb.get(entry.db); + if (group) { + group.push(entry); + } else { + byDb.set(entry.db, [entry]); + } + } + for (const [dbInstance, group] of byDb) { + const values2 = group.map((e5) => ({ + pluginId: e5.pluginId, + level: e5.level, + message: e5.message, + meta: e5.meta + })); + try { + await dbInstance.insert(pluginLogs).values(values2); + } catch (err) { + try { + logger.warn({ err, count: values2.length }, "Failed to batch-persist plugin logs to DB"); + } catch { + console.error("[plugin-host-services] Batch log flush failed:", err); + } + } + } +} +var _logFlushInterval = setInterval(() => { + flushPluginLogBuffer().catch((err) => { + console.error("[plugin-host-services] Periodic log flush error:", err); + }); +}, LOG_BUFFER_FLUSH_INTERVAL_MS); +if (_logFlushInterval.unref) _logFlushInterval.unref(); +var SESSION_EVENT_SUBSCRIPTION_TIMEOUT_MS = 30 * 60 * 1e3; +function buildHostServices(db, pluginId, pluginKey, eventBus, notifyWorker) { + const registry2 = pluginRegistryService(db); + const stateStore = pluginStateStore(db); + const secretsHandler = createPluginSecretsHandler({ db, pluginId }); + const companies2 = companyService(db); + const agents2 = agentService(db); + const heartbeat = heartbeatService(db); + const projects2 = projectService(db); + const issues2 = issueService(db); + const documents2 = documentService(db); + const goals2 = goalService(db); + const activity = activityService(db); + const costs = costService(db); + const assets2 = assetService(db); + const scopedBus = eventBus.forPlugin(pluginKey); + const activeSubscriptions = /* @__PURE__ */ new Set(); + let disposed = false; + const ensureCompanyId = (companyId) => { + if (!companyId) throw new Error("companyId is required for this operation"); + return companyId; + }; + const parseWindowValue = (value) => { + if (typeof value === "number" && Number.isFinite(value)) { + return Math.max(0, Math.floor(value)); + } + if (typeof value === "string" && value.trim().length > 0) { + const parsed = Number(value); + if (Number.isFinite(parsed)) { + return Math.max(0, Math.floor(parsed)); + } + } + return null; + }; + const applyWindow = (rows, params) => { + const offset = parseWindowValue(params?.offset) ?? 0; + const limit = parseWindowValue(params?.limit); + if (limit == null) return rows.slice(offset); + return rows.slice(offset, offset + limit); + }; + const ensurePluginAvailableForCompany = async (_companyId) => { + }; + const inCompany = (record2, companyId) => Boolean(record2 && record2.companyId === companyId); + const requireInCompany = (entityName, record2, companyId) => { + if (!inCompany(record2, companyId)) { + throw new Error(`${entityName} not found`); + } + return record2; + }; + return { + config: { + async get() { + const configRow = await registry2.getConfig(pluginId); + return configRow?.configJson ?? {}; + } + }, + state: { + async get(params) { + return stateStore.get(pluginId, params.scopeKind, params.stateKey, { + scopeId: params.scopeId, + namespace: params.namespace + }); + }, + async set(params) { + await stateStore.set(pluginId, { + scopeKind: params.scopeKind, + scopeId: params.scopeId, + namespace: params.namespace, + stateKey: params.stateKey, + value: params.value + }); + }, + async delete(params) { + await stateStore.delete(pluginId, params.scopeKind, params.stateKey, { + scopeId: params.scopeId, + namespace: params.namespace + }); + } + }, + entities: { + async upsert(params) { + return registry2.upsertEntity(pluginId, params); + }, + async list(params) { + return registry2.listEntities(pluginId, params); + } + }, + events: { + async emit(params) { + if (params.companyId) { + await ensurePluginAvailableForCompany(params.companyId); + } + await scopedBus.emit(params.name, params.companyId, params.payload); + }, + async subscribe(params) { + const handler = async (event) => { + if (notifyWorker) { + notifyWorker("onEvent", { event }); + } + }; + if (params.filter) { + scopedBus.subscribe(params.eventPattern, params.filter, handler); + } else { + scopedBus.subscribe(params.eventPattern, handler); + } + } + }, + http: { + async fetch(params) { + const target = await validateAndResolveFetchUrl(params.url); + const controller = new AbortController(); + const timeout = setTimeout(() => controller.abort(), PLUGIN_FETCH_TIMEOUT_MS); + try { + const init2 = params.init; + return await executePinnedHttpRequest(target, init2, controller.signal); + } finally { + clearTimeout(timeout); + } + } + }, + secrets: { + async resolve(params) { + return secretsHandler.resolve(params); + } + }, + activity: { + async log(params) { + const companyId = ensureCompanyId(params.companyId); + await ensurePluginAvailableForCompany(companyId); + await logActivity(db, { + companyId, + actorType: "system", + actorId: pluginId, + action: params.message, + entityType: params.entityType ?? "plugin", + entityId: params.entityId ?? pluginId, + details: params.metadata + }); + } + }, + metrics: { + async write(params) { + const safeName = truncStr(String(params.name ?? ""), MAX_METRIC_NAME_LENGTH); + logger.debug({ pluginId, name: safeName, value: params.value, tags: params.tags }, "Plugin metric write"); + _logBuffer.push({ + db, + pluginId, + level: "metric", + message: safeName, + meta: sanitiseMeta({ value: params.value, tags: params.tags ?? null }) + }); + if (_logBuffer.length >= LOG_BUFFER_FLUSH_SIZE) { + flushPluginLogBuffer().catch((err) => { + console.error("[plugin-host-services] Triggered metric flush failed:", err); + }); + } + } + }, + telemetry: { + async track(params) { + const eventName = String(params.eventName ?? "").trim(); + if (!TELEMETRY_EVENT_NAME_REGEX.test(eventName)) { + throw new Error( + 'Plugin telemetry event names must be lowercase slugs using letters, numbers, "_" or "-".' + ); + } + const telemetryClient = getTelemetryClient(); + if (!telemetryClient) return; + telemetryClient.track(`plugin.${pluginKey}.${eventName}`, params.dimensions); + } + }, + logger: { + async log(params) { + const { level, meta: meta3 } = params; + const safeMessage = truncStr(String(params.message ?? ""), MAX_LOG_MESSAGE_LENGTH); + const safeMeta = sanitiseMeta(meta3); + const pluginLogger = logger.child({ service: "plugin-worker", pluginId }); + const logFields = { + ...safeMeta, + pluginLogLevel: level, + pluginTimestamp: (/* @__PURE__ */ new Date()).toISOString() + }; + if (level === "error") pluginLogger.error(logFields, `[plugin] ${safeMessage}`); + else if (level === "warn") pluginLogger.warn(logFields, `[plugin] ${safeMessage}`); + else if (level === "debug") pluginLogger.debug(logFields, `[plugin] ${safeMessage}`); + else pluginLogger.info(logFields, `[plugin] ${safeMessage}`); + _logBuffer.push({ + db, + pluginId, + level: level ?? "info", + message: safeMessage, + meta: safeMeta + }); + if (_logBuffer.length >= LOG_BUFFER_FLUSH_SIZE) { + flushPluginLogBuffer().catch((err) => { + console.error("[plugin-host-services] Triggered log flush failed:", err); + }); + } + } + }, + companies: { + async list(params) { + return applyWindow(await companies2.list(), params); + }, + async get(params) { + await ensurePluginAvailableForCompany(params.companyId); + return await companies2.getById(params.companyId); + } + }, + projects: { + async list(params) { + const companyId = ensureCompanyId(params.companyId); + await ensurePluginAvailableForCompany(companyId); + return applyWindow(await projects2.list(companyId), params); + }, + async get(params) { + const companyId = ensureCompanyId(params.companyId); + await ensurePluginAvailableForCompany(companyId); + const project = await projects2.getById(params.projectId); + return inCompany(project, companyId) ? project : null; + }, + async listWorkspaces(params) { + const companyId = ensureCompanyId(params.companyId); + await ensurePluginAvailableForCompany(companyId); + const project = await projects2.getById(params.projectId); + if (!inCompany(project, companyId)) return []; + const rows = await projects2.listWorkspaces(params.projectId); + return rows.map((row) => { + const path53 = sanitizeWorkspacePath(row.cwd); + const name = sanitizeWorkspaceName(row.name, path53); + return { + id: row.id, + projectId: row.projectId, + name, + path: path53, + isPrimary: row.isPrimary, + createdAt: row.createdAt.toISOString(), + updatedAt: row.updatedAt.toISOString() + }; + }); + }, + async getPrimaryWorkspace(params) { + const companyId = ensureCompanyId(params.companyId); + await ensurePluginAvailableForCompany(companyId); + const project = await projects2.getById(params.projectId); + if (!inCompany(project, companyId)) return null; + const row = project.primaryWorkspace; + const path53 = sanitizeWorkspacePath(project.codebase.effectiveLocalFolder); + const name = sanitizeWorkspaceName(row?.name ?? project.name, path53); + return { + id: row?.id ?? `${project.id}:managed`, + projectId: project.id, + name, + path: path53, + isPrimary: true, + createdAt: (row?.createdAt ?? project.createdAt).toISOString(), + updatedAt: (row?.updatedAt ?? project.updatedAt).toISOString() + }; + }, + async getWorkspaceForIssue(params) { + const companyId = ensureCompanyId(params.companyId); + await ensurePluginAvailableForCompany(companyId); + const issue2 = await issues2.getById(params.issueId); + if (!inCompany(issue2, companyId)) return null; + const projectId = issue2.projectId; + if (!projectId) return null; + const project = await projects2.getById(projectId); + if (!inCompany(project, companyId)) return null; + const row = project.primaryWorkspace; + const path53 = sanitizeWorkspacePath(project.codebase.effectiveLocalFolder); + const name = sanitizeWorkspaceName(row?.name ?? project.name, path53); + return { + id: row?.id ?? `${project.id}:managed`, + projectId: project.id, + name, + path: path53, + isPrimary: true, + createdAt: (row?.createdAt ?? project.createdAt).toISOString(), + updatedAt: (row?.updatedAt ?? project.updatedAt).toISOString() + }; + } + }, + issues: { + async list(params) { + const companyId = ensureCompanyId(params.companyId); + await ensurePluginAvailableForCompany(companyId); + return applyWindow(await issues2.list(companyId, params), params); + }, + async get(params) { + const companyId = ensureCompanyId(params.companyId); + await ensurePluginAvailableForCompany(companyId); + const issue2 = await issues2.getById(params.issueId); + return inCompany(issue2, companyId) ? issue2 : null; + }, + async create(params) { + const companyId = ensureCompanyId(params.companyId); + await ensurePluginAvailableForCompany(companyId); + return await issues2.create(companyId, params); + }, + async update(params) { + const companyId = ensureCompanyId(params.companyId); + await ensurePluginAvailableForCompany(companyId); + requireInCompany("Issue", await issues2.getById(params.issueId), companyId); + return await issues2.update(params.issueId, params.patch); + }, + async listComments(params) { + const companyId = ensureCompanyId(params.companyId); + await ensurePluginAvailableForCompany(companyId); + if (!inCompany(await issues2.getById(params.issueId), companyId)) return []; + return await issues2.listComments(params.issueId); + }, + async createComment(params) { + const companyId = ensureCompanyId(params.companyId); + await ensurePluginAvailableForCompany(companyId); + requireInCompany("Issue", await issues2.getById(params.issueId), companyId); + return await issues2.addComment( + params.issueId, + params.body, + { agentId: params.authorAgentId } + ); + } + }, + issueDocuments: { + async list(params) { + const companyId = ensureCompanyId(params.companyId); + await ensurePluginAvailableForCompany(companyId); + requireInCompany("Issue", await issues2.getById(params.issueId), companyId); + const rows = await documents2.listIssueDocuments(params.issueId); + return rows; + }, + async get(params) { + const companyId = ensureCompanyId(params.companyId); + await ensurePluginAvailableForCompany(companyId); + requireInCompany("Issue", await issues2.getById(params.issueId), companyId); + const doc = await documents2.getIssueDocumentByKey(params.issueId, params.key); + return doc ?? null; + }, + async upsert(params) { + const companyId = ensureCompanyId(params.companyId); + await ensurePluginAvailableForCompany(companyId); + requireInCompany("Issue", await issues2.getById(params.issueId), companyId); + const result = await documents2.upsertIssueDocument({ + issueId: params.issueId, + key: params.key, + body: params.body, + title: params.title ?? null, + format: params.format ?? "markdown", + changeSummary: params.changeSummary ?? null + }); + return result.document; + }, + async delete(params) { + const companyId = ensureCompanyId(params.companyId); + await ensurePluginAvailableForCompany(companyId); + requireInCompany("Issue", await issues2.getById(params.issueId), companyId); + await documents2.deleteIssueDocument(params.issueId, params.key); + } + }, + agents: { + async list(params) { + const companyId = ensureCompanyId(params.companyId); + await ensurePluginAvailableForCompany(companyId); + const rows = await agents2.list(companyId); + return applyWindow( + rows.filter((agent) => !params.status || agent.status === params.status), + params + ); + }, + async get(params) { + const companyId = ensureCompanyId(params.companyId); + await ensurePluginAvailableForCompany(companyId); + const agent = await agents2.getById(params.agentId); + return inCompany(agent, companyId) ? agent : null; + }, + async pause(params) { + const companyId = ensureCompanyId(params.companyId); + await ensurePluginAvailableForCompany(companyId); + const agent = await agents2.getById(params.agentId); + requireInCompany("Agent", agent, companyId); + return await agents2.pause(params.agentId); + }, + async resume(params) { + const companyId = ensureCompanyId(params.companyId); + await ensurePluginAvailableForCompany(companyId); + const agent = await agents2.getById(params.agentId); + requireInCompany("Agent", agent, companyId); + return await agents2.resume(params.agentId); + }, + async invoke(params) { + const companyId = ensureCompanyId(params.companyId); + await ensurePluginAvailableForCompany(companyId); + const agent = await agents2.getById(params.agentId); + requireInCompany("Agent", agent, companyId); + const run = await heartbeat.wakeup(params.agentId, { + source: "automation", + triggerDetail: "system", + reason: params.reason ?? null, + payload: { prompt: params.prompt }, + requestedByActorType: "system", + requestedByActorId: pluginId + }); + if (!run) throw new Error("Agent wakeup was skipped by heartbeat policy"); + return { runId: run.id }; + } + }, + goals: { + async list(params) { + const companyId = ensureCompanyId(params.companyId); + await ensurePluginAvailableForCompany(companyId); + const rows = await goals2.list(companyId); + return applyWindow( + rows.filter( + (goal) => (!params.level || goal.level === params.level) && (!params.status || goal.status === params.status) + ), + params + ); + }, + async get(params) { + const companyId = ensureCompanyId(params.companyId); + await ensurePluginAvailableForCompany(companyId); + const goal = await goals2.getById(params.goalId); + return inCompany(goal, companyId) ? goal : null; + }, + async create(params) { + const companyId = ensureCompanyId(params.companyId); + await ensurePluginAvailableForCompany(companyId); + return await goals2.create(companyId, { + title: params.title, + description: params.description, + level: params.level, + status: params.status, + parentId: params.parentId, + ownerAgentId: params.ownerAgentId + }); + }, + async update(params) { + const companyId = ensureCompanyId(params.companyId); + await ensurePluginAvailableForCompany(companyId); + requireInCompany("Goal", await goals2.getById(params.goalId), companyId); + return await goals2.update(params.goalId, params.patch); + } + }, + agentSessions: { + async create(params) { + const companyId = ensureCompanyId(params.companyId); + await ensurePluginAvailableForCompany(companyId); + const agent = await agents2.getById(params.agentId); + requireInCompany("Agent", agent, companyId); + const taskKey = params.taskKey ?? `plugin:${pluginKey}:session:${randomUUID11()}`; + const row = await db.insert(agentTaskSessions).values({ + companyId, + agentId: params.agentId, + adapterType: agent.adapterType, + taskKey, + sessionParamsJson: null, + sessionDisplayId: null, + lastRunId: null, + lastError: null + }).returning().then((rows) => rows[0]); + return { + sessionId: row.id, + agentId: params.agentId, + companyId, + status: "active", + createdAt: row.createdAt.toISOString() + }; + }, + async list(params) { + const companyId = ensureCompanyId(params.companyId); + await ensurePluginAvailableForCompany(companyId); + const rows = await db.select().from(agentTaskSessions).where( + and( + eq(agentTaskSessions.agentId, params.agentId), + eq(agentTaskSessions.companyId, companyId), + like(agentTaskSessions.taskKey, `plugin:${pluginKey}:session:%`) + ) + ).orderBy(desc(agentTaskSessions.createdAt)); + return rows.map((row) => ({ + sessionId: row.id, + agentId: row.agentId, + companyId: row.companyId, + status: "active", + createdAt: row.createdAt.toISOString() + })); + }, + async sendMessage(params) { + if (disposed) { + throw new Error("Host services have been disposed"); + } + const companyId = ensureCompanyId(params.companyId); + await ensurePluginAvailableForCompany(companyId); + const session = await db.select().from(agentTaskSessions).where( + and( + eq(agentTaskSessions.id, params.sessionId), + eq(agentTaskSessions.companyId, companyId), + like(agentTaskSessions.taskKey, `plugin:${pluginKey}:session:%`) + ) + ).then((rows) => rows[0] ?? null); + if (!session) throw new Error(`Session not found: ${params.sessionId}`); + const run = await heartbeat.wakeup(session.agentId, { + source: "automation", + triggerDetail: "system", + reason: params.reason ?? null, + payload: { prompt: params.prompt }, + contextSnapshot: { + taskKey: session.taskKey, + wakeSource: "automation", + wakeTriggerDetail: "system" + }, + requestedByActorType: "system", + requestedByActorId: pluginId + }); + if (!run) throw new Error("Agent wakeup was skipped by heartbeat policy"); + if (notifyWorker) { + const TERMINAL_STATUSES = /* @__PURE__ */ new Set(["succeeded", "failed", "cancelled", "timed_out"]); + const cleanup = () => { + unsubscribe(); + clearTimeout(timeoutTimer); + activeSubscriptions.delete(entry); + }; + const unsubscribe = subscribeCompanyLiveEvents(companyId, (event) => { + const payload2 = event.payload; + if (!payload2 || payload2.runId !== run.id) return; + if (event.type === "heartbeat.run.log" || event.type === "heartbeat.run.event") { + notifyWorker("agents.sessions.event", { + sessionId: params.sessionId, + runId: run.id, + seq: payload2.seq ?? 0, + eventType: "chunk", + stream: payload2.stream ?? null, + message: payload2.chunk ?? payload2.message ?? null, + payload: payload2 + }); + } else if (event.type === "heartbeat.run.status") { + const status = payload2.status; + if (TERMINAL_STATUSES.has(status)) { + notifyWorker("agents.sessions.event", { + sessionId: params.sessionId, + runId: run.id, + seq: 0, + eventType: status === "succeeded" ? "done" : "error", + stream: "system", + message: status === "succeeded" ? "Run completed" : `Run ${status}`, + payload: payload2 + }); + cleanup(); + } else { + notifyWorker("agents.sessions.event", { + sessionId: params.sessionId, + runId: run.id, + seq: 0, + eventType: "status", + stream: "system", + message: `Run status: ${status}`, + payload: payload2 + }); + } + } + }); + const timeoutTimer = setTimeout(() => { + logger.warn( + { pluginId, pluginKey, runId: run.id }, + "session event subscription timed out \u2014 forcing cleanup" + ); + cleanup(); + }, SESSION_EVENT_SUBSCRIPTION_TIMEOUT_MS); + const entry = { unsubscribe, timer: timeoutTimer }; + activeSubscriptions.add(entry); + } + return { runId: run.id }; + }, + async close(params) { + const companyId = ensureCompanyId(params.companyId); + await ensurePluginAvailableForCompany(companyId); + const deleted = await db.delete(agentTaskSessions).where( + and( + eq(agentTaskSessions.id, params.sessionId), + eq(agentTaskSessions.companyId, companyId), + like(agentTaskSessions.taskKey, `plugin:${pluginKey}:session:%`) + ) + ).returning().then((rows) => rows.length); + if (deleted === 0) throw new Error(`Session not found: ${params.sessionId}`); + } + }, + /** + * Clean up all active session event subscriptions and flush any buffered + * log entries. Must be called when the plugin worker is stopped, crashed, + * or unloaded to prevent leaked listeners and lost log entries. + */ + dispose() { + disposed = true; + scopedBus.clear(); + const snapshot = Array.from(activeSubscriptions); + activeSubscriptions.clear(); + for (const entry of snapshot) { + clearTimeout(entry.timer); + entry.unsubscribe(); + } + flushPluginLogBuffer().catch((err) => { + console.error("[plugin-host-services] dispose() log flush failed:", err); + }); + } + }; +} + +// server/src/services/plugin-event-bus.ts +function matchesPattern(eventType, pattern) { + if (pattern === eventType) return true; + if (pattern.endsWith(".*")) { + const prefix = pattern.slice(0, -1); + return eventType.startsWith(prefix); + } + return false; +} +function passesFilter(event, filter) { + if (!filter) return true; + const payload2 = event.payload; + if (filter.projectId !== void 0) { + const projectId = event.entityType === "project" ? event.entityId : typeof payload2?.projectId === "string" ? payload2.projectId : void 0; + if (projectId !== filter.projectId) return false; + } + if (filter.companyId !== void 0) { + if (event.companyId !== filter.companyId) return false; + } + if (filter.agentId !== void 0) { + const agentId = event.entityType === "agent" ? event.entityId : typeof payload2?.agentId === "string" ? payload2.agentId : void 0; + if (agentId !== filter.agentId) return false; + } + return true; +} +function createPluginEventBus() { + const registry2 = /* @__PURE__ */ new Map(); + function subsFor(pluginId) { + let subs = registry2.get(pluginId); + if (!subs) { + subs = []; + registry2.set(pluginId, subs); + } + return subs; + } + async function emit(event) { + const errors = []; + const promises = []; + for (const [pluginId, subs] of registry2) { + for (const sub of subs) { + if (!matchesPattern(event.eventType, sub.eventPattern)) continue; + if (!passesFilter(event, sub.filter)) continue; + promises.push( + Promise.resolve().then(() => sub.handler(event)).catch((error50) => { + errors.push({ pluginId, error: error50 }); + }) + ); + } + } + await Promise.all(promises); + return { errors }; + } + function clearPlugin(pluginId) { + registry2.delete(pluginId); + } + function forPlugin(pluginId) { + return { + /** + * Subscribe to a core domain event or a plugin-namespaced event. + * + * For wildcard subscriptions use a trailing `.*` pattern, e.g. + * `"plugin.acme.linear.*"`. + * + * Requires the `events.subscribe` capability (capability enforcement is + * done by the host layer before calling this method). + */ + subscribe(eventPattern, fnOrFilter, maybeFn) { + let filter = null; + let handler; + if (typeof fnOrFilter === "function") { + handler = fnOrFilter; + } else { + filter = fnOrFilter; + if (!maybeFn) throw new Error("Handler function is required when a filter is provided"); + handler = maybeFn; + } + subsFor(pluginId).push({ eventPattern, filter, handler }); + }, + /** + * Emit a plugin-namespaced event. The event type is automatically + * prefixed with `plugin..` so: + * - `emit("sync-done", payload)` becomes `"plugin.acme.linear.sync-done"`. + * + * Requires the `events.emit` capability (enforced by the host layer). + * + * @throws {Error} if `name` already contains the `plugin.` prefix + * (prevents cross-namespace spoofing). + */ + async emit(name, companyId, payload2) { + if (!name || name.trim() === "") { + throw new Error(`Plugin "${pluginId}" must provide a non-empty event name.`); + } + if (!companyId || companyId.trim() === "") { + throw new Error(`Plugin "${pluginId}" must provide a companyId when emitting events.`); + } + if (name.startsWith("plugin.")) { + throw new Error( + `Plugin "${pluginId}" must not include the "plugin." prefix when emitting events. Emit the bare event name (e.g. "sync-done") and the bus will namespace it automatically.` + ); + } + const eventType = `plugin.${pluginId}.${name}`; + const event = { + eventId: crypto.randomUUID(), + eventType, + companyId, + occurredAt: (/* @__PURE__ */ new Date()).toISOString(), + actorType: "plugin", + actorId: pluginId, + payload: payload2 + }; + return emit(event); + }, + /** Remove all subscriptions registered by this plugin. */ + clear() { + clearPlugin(pluginId); + } + }; + } + return { + emit, + forPlugin, + clearPlugin, + /** Expose subscription count for a plugin (useful for tests and diagnostics). */ + subscriptionCount(pluginId) { + if (pluginId !== void 0) { + return registry2.get(pluginId)?.length ?? 0; + } + let total = 0; + for (const subs of registry2.values()) total += subs.length; + return total; + } + }; +} + +// node_modules/.pnpm/chokidar@4.0.3/node_modules/chokidar/esm/index.js +import { stat as statcb } from "fs"; +import { stat as stat4, readdir as readdir4 } from "fs/promises"; +import { EventEmitter as EventEmitter4 } from "events"; +import * as sysPath2 from "path"; + +// node_modules/.pnpm/readdirp@4.1.2/node_modules/readdirp/esm/index.js +import { stat as stat2, lstat, readdir as readdir3, realpath } from "node:fs/promises"; +import { Readable as Readable2 } from "node:stream"; +import { resolve as presolve, relative as prelative, join as pjoin, sep as psep } from "node:path"; +var EntryTypes = { + FILE_TYPE: "files", + DIR_TYPE: "directories", + FILE_DIR_TYPE: "files_directories", + EVERYTHING_TYPE: "all" +}; +var defaultOptions = { + root: ".", + fileFilter: (_entryInfo) => true, + directoryFilter: (_entryInfo) => true, + type: EntryTypes.FILE_TYPE, + lstat: false, + depth: 2147483648, + alwaysStat: false, + highWaterMark: 4096 +}; +Object.freeze(defaultOptions); +var RECURSIVE_ERROR_CODE = "READDIRP_RECURSIVE_ERROR"; +var NORMAL_FLOW_ERRORS = /* @__PURE__ */ new Set(["ENOENT", "EPERM", "EACCES", "ELOOP", RECURSIVE_ERROR_CODE]); +var ALL_TYPES = [ + EntryTypes.DIR_TYPE, + EntryTypes.EVERYTHING_TYPE, + EntryTypes.FILE_DIR_TYPE, + EntryTypes.FILE_TYPE +]; +var DIR_TYPES = /* @__PURE__ */ new Set([ + EntryTypes.DIR_TYPE, + EntryTypes.EVERYTHING_TYPE, + EntryTypes.FILE_DIR_TYPE +]); +var FILE_TYPES = /* @__PURE__ */ new Set([ + EntryTypes.EVERYTHING_TYPE, + EntryTypes.FILE_DIR_TYPE, + EntryTypes.FILE_TYPE +]); +var isNormalFlowError = (error50) => NORMAL_FLOW_ERRORS.has(error50.code); +var wantBigintFsStats = process.platform === "win32"; +var emptyFn = (_entryInfo) => true; +var normalizeFilter = (filter) => { + if (filter === void 0) + return emptyFn; + if (typeof filter === "function") + return filter; + if (typeof filter === "string") { + const fl = filter.trim(); + return (entry) => entry.basename === fl; + } + if (Array.isArray(filter)) { + const trItems = filter.map((item) => item.trim()); + return (entry) => trItems.some((f5) => entry.basename === f5); + } + return emptyFn; +}; +var ReaddirpStream = class extends Readable2 { + constructor(options = {}) { + super({ + objectMode: true, + autoDestroy: true, + highWaterMark: options.highWaterMark + }); + const opts = { ...defaultOptions, ...options }; + const { root, type } = opts; + this._fileFilter = normalizeFilter(opts.fileFilter); + this._directoryFilter = normalizeFilter(opts.directoryFilter); + const statMethod = opts.lstat ? lstat : stat2; + if (wantBigintFsStats) { + this._stat = (path53) => statMethod(path53, { bigint: true }); + } else { + this._stat = statMethod; + } + this._maxDepth = opts.depth ?? defaultOptions.depth; + this._wantsDir = type ? DIR_TYPES.has(type) : false; + this._wantsFile = type ? FILE_TYPES.has(type) : false; + this._wantsEverything = type === EntryTypes.EVERYTHING_TYPE; + this._root = presolve(root); + this._isDirent = !opts.alwaysStat; + this._statsProp = this._isDirent ? "dirent" : "stats"; + this._rdOptions = { encoding: "utf8", withFileTypes: this._isDirent }; + this.parents = [this._exploreDir(root, 1)]; + this.reading = false; + this.parent = void 0; + } + async _read(batch) { + if (this.reading) + return; + this.reading = true; + try { + while (!this.destroyed && batch > 0) { + const par = this.parent; + const fil = par && par.files; + if (fil && fil.length > 0) { + const { path: path53, depth } = par; + const slice = fil.splice(0, batch).map((dirent) => this._formatEntry(dirent, path53)); + const awaited = await Promise.all(slice); + for (const entry of awaited) { + if (!entry) + continue; + if (this.destroyed) + return; + const entryType = await this._getEntryType(entry); + if (entryType === "directory" && this._directoryFilter(entry)) { + if (depth <= this._maxDepth) { + this.parents.push(this._exploreDir(entry.fullPath, depth + 1)); + } + if (this._wantsDir) { + this.push(entry); + batch--; + } + } else if ((entryType === "file" || this._includeAsFile(entry)) && this._fileFilter(entry)) { + if (this._wantsFile) { + this.push(entry); + batch--; + } + } + } + } else { + const parent = this.parents.pop(); + if (!parent) { + this.push(null); + break; + } + this.parent = await parent; + if (this.destroyed) + return; + } + } + } catch (error50) { + this.destroy(error50); + } finally { + this.reading = false; + } + } + async _exploreDir(path53, depth) { + let files; + try { + files = await readdir3(path53, this._rdOptions); + } catch (error50) { + this._onError(error50); + } + return { files, depth, path: path53 }; + } + async _formatEntry(dirent, path53) { + let entry; + const basename3 = this._isDirent ? dirent.name : dirent; + try { + const fullPath = presolve(pjoin(path53, basename3)); + entry = { path: prelative(this._root, fullPath), fullPath, basename: basename3 }; + entry[this._statsProp] = this._isDirent ? dirent : await this._stat(fullPath); + } catch (err) { + this._onError(err); + return; + } + return entry; + } + _onError(err) { + if (isNormalFlowError(err) && !this.destroyed) { + this.emit("warn", err); + } else { + this.destroy(err); + } + } + async _getEntryType(entry) { + if (!entry && this._statsProp in entry) { + return ""; + } + const stats = entry[this._statsProp]; + if (stats.isFile()) + return "file"; + if (stats.isDirectory()) + return "directory"; + if (stats && stats.isSymbolicLink()) { + const full = entry.fullPath; + try { + const entryRealPath = await realpath(full); + const entryRealPathStats = await lstat(entryRealPath); + if (entryRealPathStats.isFile()) { + return "file"; + } + if (entryRealPathStats.isDirectory()) { + const len = entryRealPath.length; + if (full.startsWith(entryRealPath) && full.substr(len, 1) === psep) { + const recursiveError = new Error(`Circular symlink detected: "${full}" points to "${entryRealPath}"`); + recursiveError.code = RECURSIVE_ERROR_CODE; + return this._onError(recursiveError); + } + return "directory"; + } + } catch (error50) { + this._onError(error50); + return ""; + } + } + } + _includeAsFile(entry) { + const stats = entry && entry[this._statsProp]; + return stats && this._wantsEverything && !stats.isDirectory(); + } +}; +function readdirp(root, options = {}) { + let type = options.entryType || options.type; + if (type === "both") + type = EntryTypes.FILE_DIR_TYPE; + if (type) + options.type = type; + if (!root) { + throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)"); + } else if (typeof root !== "string") { + throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)"); + } else if (type && !ALL_TYPES.includes(type)) { + throw new Error(`readdirp: Invalid type passed. Use one of ${ALL_TYPES.join(", ")}`); + } + options.root = root; + return new ReaddirpStream(options); +} + +// node_modules/.pnpm/chokidar@4.0.3/node_modules/chokidar/esm/handler.js +import { watchFile, unwatchFile, watch as fs_watch } from "fs"; +import { open, stat as stat3, lstat as lstat2, realpath as fsrealpath } from "fs/promises"; +import * as sysPath from "path"; +import { type as osType } from "os"; +var STR_DATA = "data"; +var STR_END = "end"; +var STR_CLOSE = "close"; +var EMPTY_FN = () => { +}; +var pl = process.platform; +var isWindows = pl === "win32"; +var isMacos = pl === "darwin"; +var isLinux = pl === "linux"; +var isFreeBSD = pl === "freebsd"; +var isIBMi = osType() === "OS400"; +var EVENTS = { + ALL: "all", + READY: "ready", + ADD: "add", + CHANGE: "change", + ADD_DIR: "addDir", + UNLINK: "unlink", + UNLINK_DIR: "unlinkDir", + RAW: "raw", + ERROR: "error" +}; +var EV = EVENTS; +var THROTTLE_MODE_WATCH = "watch"; +var statMethods = { lstat: lstat2, stat: stat3 }; +var KEY_LISTENERS = "listeners"; +var KEY_ERR = "errHandlers"; +var KEY_RAW = "rawEmitters"; +var HANDLER_KEYS = [KEY_LISTENERS, KEY_ERR, KEY_RAW]; +var binaryExtensions = /* @__PURE__ */ new Set([ + "3dm", + "3ds", + "3g2", + "3gp", + "7z", + "a", + "aac", + "adp", + "afdesign", + "afphoto", + "afpub", + "ai", + "aif", + "aiff", + "alz", + "ape", + "apk", + "appimage", + "ar", + "arj", + "asf", + "au", + "avi", + "bak", + "baml", + "bh", + "bin", + "bk", + "bmp", + "btif", + "bz2", + "bzip2", + "cab", + "caf", + "cgm", + "class", + "cmx", + "cpio", + "cr2", + "cur", + "dat", + "dcm", + "deb", + "dex", + "djvu", + "dll", + "dmg", + "dng", + "doc", + "docm", + "docx", + "dot", + "dotm", + "dra", + "DS_Store", + "dsk", + "dts", + "dtshd", + "dvb", + "dwg", + "dxf", + "ecelp4800", + "ecelp7470", + "ecelp9600", + "egg", + "eol", + "eot", + "epub", + "exe", + "f4v", + "fbs", + "fh", + "fla", + "flac", + "flatpak", + "fli", + "flv", + "fpx", + "fst", + "fvt", + "g3", + "gh", + "gif", + "graffle", + "gz", + "gzip", + "h261", + "h263", + "h264", + "icns", + "ico", + "ief", + "img", + "ipa", + "iso", + "jar", + "jpeg", + "jpg", + "jpgv", + "jpm", + "jxr", + "key", + "ktx", + "lha", + "lib", + "lvp", + "lz", + "lzh", + "lzma", + "lzo", + "m3u", + "m4a", + "m4v", + "mar", + "mdi", + "mht", + "mid", + "midi", + "mj2", + "mka", + "mkv", + "mmr", + "mng", + "mobi", + "mov", + "movie", + "mp3", + "mp4", + "mp4a", + "mpeg", + "mpg", + "mpga", + "mxu", + "nef", + "npx", + "numbers", + "nupkg", + "o", + "odp", + "ods", + "odt", + "oga", + "ogg", + "ogv", + "otf", + "ott", + "pages", + "pbm", + "pcx", + "pdb", + "pdf", + "pea", + "pgm", + "pic", + "png", + "pnm", + "pot", + "potm", + "potx", + "ppa", + "ppam", + "ppm", + "pps", + "ppsm", + "ppsx", + "ppt", + "pptm", + "pptx", + "psd", + "pya", + "pyc", + "pyo", + "pyv", + "qt", + "rar", + "ras", + "raw", + "resources", + "rgb", + "rip", + "rlc", + "rmf", + "rmvb", + "rpm", + "rtf", + "rz", + "s3m", + "s7z", + "scpt", + "sgi", + "shar", + "snap", + "sil", + "sketch", + "slk", + "smv", + "snk", + "so", + "stl", + "suo", + "sub", + "swf", + "tar", + "tbz", + "tbz2", + "tga", + "tgz", + "thmx", + "tif", + "tiff", + "tlz", + "ttc", + "ttf", + "txz", + "udf", + "uvh", + "uvi", + "uvm", + "uvp", + "uvs", + "uvu", + "viv", + "vob", + "war", + "wav", + "wax", + "wbmp", + "wdp", + "weba", + "webm", + "webp", + "whl", + "wim", + "wm", + "wma", + "wmv", + "wmx", + "woff", + "woff2", + "wrm", + "wvx", + "xbm", + "xif", + "xla", + "xlam", + "xls", + "xlsb", + "xlsm", + "xlsx", + "xlt", + "xltm", + "xltx", + "xm", + "xmind", + "xpi", + "xpm", + "xwd", + "xz", + "z", + "zip", + "zipx" +]); +var isBinaryPath = (filePath) => binaryExtensions.has(sysPath.extname(filePath).slice(1).toLowerCase()); +var foreach = (val, fn) => { + if (val instanceof Set) { + val.forEach(fn); + } else { + fn(val); + } +}; +var addAndConvert = (main, prop, item) => { + let container = main[prop]; + if (!(container instanceof Set)) { + main[prop] = container = /* @__PURE__ */ new Set([container]); + } + container.add(item); +}; +var clearItem = (cont) => (key) => { + const set2 = cont[key]; + if (set2 instanceof Set) { + set2.clear(); + } else { + delete cont[key]; + } +}; +var delFromSet = (main, prop, item) => { + const container = main[prop]; + if (container instanceof Set) { + container.delete(item); + } else if (container === item) { + delete main[prop]; + } +}; +var isEmptySet = (val) => val instanceof Set ? val.size === 0 : !val; +var FsWatchInstances = /* @__PURE__ */ new Map(); +function createFsWatchInstance(path53, options, listener, errHandler, emitRaw) { + const handleEvent = (rawEvent, evPath) => { + listener(path53); + emitRaw(rawEvent, evPath, { watchedPath: path53 }); + if (evPath && path53 !== evPath) { + fsWatchBroadcast(sysPath.resolve(path53, evPath), KEY_LISTENERS, sysPath.join(path53, evPath)); + } + }; + try { + return fs_watch(path53, { + persistent: options.persistent + }, handleEvent); + } catch (error50) { + errHandler(error50); + return void 0; + } +} +var fsWatchBroadcast = (fullPath, listenerType, val1, val2, val3) => { + const cont = FsWatchInstances.get(fullPath); + if (!cont) + return; + foreach(cont[listenerType], (listener) => { + listener(val1, val2, val3); + }); +}; +var setFsWatchListener = (path53, fullPath, options, handlers) => { + const { listener, errHandler, rawEmitter } = handlers; + let cont = FsWatchInstances.get(fullPath); + let watcher; + if (!options.persistent) { + watcher = createFsWatchInstance(path53, options, listener, errHandler, rawEmitter); + if (!watcher) + return; + return watcher.close.bind(watcher); + } + if (cont) { + addAndConvert(cont, KEY_LISTENERS, listener); + addAndConvert(cont, KEY_ERR, errHandler); + addAndConvert(cont, KEY_RAW, rawEmitter); + } else { + watcher = createFsWatchInstance( + path53, + options, + fsWatchBroadcast.bind(null, fullPath, KEY_LISTENERS), + errHandler, + // no need to use broadcast here + fsWatchBroadcast.bind(null, fullPath, KEY_RAW) + ); + if (!watcher) + return; + watcher.on(EV.ERROR, async (error50) => { + const broadcastErr = fsWatchBroadcast.bind(null, fullPath, KEY_ERR); + if (cont) + cont.watcherUnusable = true; + if (isWindows && error50.code === "EPERM") { + try { + const fd = await open(path53, "r"); + await fd.close(); + broadcastErr(error50); + } catch (err) { + } + } else { + broadcastErr(error50); + } + }); + cont = { + listeners: listener, + errHandlers: errHandler, + rawEmitters: rawEmitter, + watcher + }; + FsWatchInstances.set(fullPath, cont); + } + return () => { + delFromSet(cont, KEY_LISTENERS, listener); + delFromSet(cont, KEY_ERR, errHandler); + delFromSet(cont, KEY_RAW, rawEmitter); + if (isEmptySet(cont.listeners)) { + cont.watcher.close(); + FsWatchInstances.delete(fullPath); + HANDLER_KEYS.forEach(clearItem(cont)); + cont.watcher = void 0; + Object.freeze(cont); + } + }; +}; +var FsWatchFileInstances = /* @__PURE__ */ new Map(); +var setFsWatchFileListener = (path53, fullPath, options, handlers) => { + const { listener, rawEmitter } = handlers; + let cont = FsWatchFileInstances.get(fullPath); + const copts = cont && cont.options; + if (copts && (copts.persistent < options.persistent || copts.interval > options.interval)) { + unwatchFile(fullPath); + cont = void 0; + } + if (cont) { + addAndConvert(cont, KEY_LISTENERS, listener); + addAndConvert(cont, KEY_RAW, rawEmitter); + } else { + cont = { + listeners: listener, + rawEmitters: rawEmitter, + options, + watcher: watchFile(fullPath, options, (curr, prev) => { + foreach(cont.rawEmitters, (rawEmitter2) => { + rawEmitter2(EV.CHANGE, fullPath, { curr, prev }); + }); + const currmtime = curr.mtimeMs; + if (curr.size !== prev.size || currmtime > prev.mtimeMs || currmtime === 0) { + foreach(cont.listeners, (listener2) => listener2(path53, curr)); + } + }) + }; + FsWatchFileInstances.set(fullPath, cont); + } + return () => { + delFromSet(cont, KEY_LISTENERS, listener); + delFromSet(cont, KEY_RAW, rawEmitter); + if (isEmptySet(cont.listeners)) { + FsWatchFileInstances.delete(fullPath); + unwatchFile(fullPath); + cont.options = cont.watcher = void 0; + Object.freeze(cont); + } + }; +}; +var NodeFsHandler = class { + constructor(fsW) { + this.fsw = fsW; + this._boundHandleError = (error50) => fsW._handleError(error50); + } + /** + * Watch file for changes with fs_watchFile or fs_watch. + * @param path to file or dir + * @param listener on fs change + * @returns closer for the watcher instance + */ + _watchWithNodeFs(path53, listener) { + const opts = this.fsw.options; + const directory = sysPath.dirname(path53); + const basename3 = sysPath.basename(path53); + const parent = this.fsw._getWatchedDir(directory); + parent.add(basename3); + const absolutePath = sysPath.resolve(path53); + const options = { + persistent: opts.persistent + }; + if (!listener) + listener = EMPTY_FN; + let closer; + if (opts.usePolling) { + const enableBin = opts.interval !== opts.binaryInterval; + options.interval = enableBin && isBinaryPath(basename3) ? opts.binaryInterval : opts.interval; + closer = setFsWatchFileListener(path53, absolutePath, options, { + listener, + rawEmitter: this.fsw._emitRaw + }); + } else { + closer = setFsWatchListener(path53, absolutePath, options, { + listener, + errHandler: this._boundHandleError, + rawEmitter: this.fsw._emitRaw + }); + } + return closer; + } + /** + * Watch a file and emit add event if warranted. + * @returns closer for the watcher instance + */ + _handleFile(file2, stats, initialAdd) { + if (this.fsw.closed) { + return; + } + const dirname3 = sysPath.dirname(file2); + const basename3 = sysPath.basename(file2); + const parent = this.fsw._getWatchedDir(dirname3); + let prevStats = stats; + if (parent.has(basename3)) + return; + const listener = async (path53, newStats) => { + if (!this.fsw._throttle(THROTTLE_MODE_WATCH, file2, 5)) + return; + if (!newStats || newStats.mtimeMs === 0) { + try { + const newStats2 = await stat3(file2); + if (this.fsw.closed) + return; + const at = newStats2.atimeMs; + const mt = newStats2.mtimeMs; + if (!at || at <= mt || mt !== prevStats.mtimeMs) { + this.fsw._emit(EV.CHANGE, file2, newStats2); + } + if ((isMacos || isLinux || isFreeBSD) && prevStats.ino !== newStats2.ino) { + this.fsw._closeFile(path53); + prevStats = newStats2; + const closer2 = this._watchWithNodeFs(file2, listener); + if (closer2) + this.fsw._addPathCloser(path53, closer2); + } else { + prevStats = newStats2; + } + } catch (error50) { + this.fsw._remove(dirname3, basename3); + } + } else if (parent.has(basename3)) { + const at = newStats.atimeMs; + const mt = newStats.mtimeMs; + if (!at || at <= mt || mt !== prevStats.mtimeMs) { + this.fsw._emit(EV.CHANGE, file2, newStats); + } + prevStats = newStats; + } + }; + const closer = this._watchWithNodeFs(file2, listener); + if (!(initialAdd && this.fsw.options.ignoreInitial) && this.fsw._isntIgnored(file2)) { + if (!this.fsw._throttle(EV.ADD, file2, 0)) + return; + this.fsw._emit(EV.ADD, file2, stats); + } + return closer; + } + /** + * Handle symlinks encountered while reading a dir. + * @param entry returned by readdirp + * @param directory path of dir being read + * @param path of this item + * @param item basename of this item + * @returns true if no more processing is needed for this entry. + */ + async _handleSymlink(entry, directory, path53, item) { + if (this.fsw.closed) { + return; + } + const full = entry.fullPath; + const dir = this.fsw._getWatchedDir(directory); + if (!this.fsw.options.followSymlinks) { + this.fsw._incrReadyCount(); + let linkPath; + try { + linkPath = await fsrealpath(path53); + } catch (e5) { + this.fsw._emitReady(); + return true; + } + if (this.fsw.closed) + return; + if (dir.has(item)) { + if (this.fsw._symlinkPaths.get(full) !== linkPath) { + this.fsw._symlinkPaths.set(full, linkPath); + this.fsw._emit(EV.CHANGE, path53, entry.stats); + } + } else { + dir.add(item); + this.fsw._symlinkPaths.set(full, linkPath); + this.fsw._emit(EV.ADD, path53, entry.stats); + } + this.fsw._emitReady(); + return true; + } + if (this.fsw._symlinkPaths.has(full)) { + return true; + } + this.fsw._symlinkPaths.set(full, true); + } + _handleRead(directory, initialAdd, wh, target, dir, depth, throttler) { + directory = sysPath.join(directory, ""); + throttler = this.fsw._throttle("readdir", directory, 1e3); + if (!throttler) + return; + const previous = this.fsw._getWatchedDir(wh.path); + const current = /* @__PURE__ */ new Set(); + let stream = this.fsw._readdirp(directory, { + fileFilter: (entry) => wh.filterPath(entry), + directoryFilter: (entry) => wh.filterDir(entry) + }); + if (!stream) + return; + stream.on(STR_DATA, async (entry) => { + if (this.fsw.closed) { + stream = void 0; + return; + } + const item = entry.path; + let path53 = sysPath.join(directory, item); + current.add(item); + if (entry.stats.isSymbolicLink() && await this._handleSymlink(entry, directory, path53, item)) { + return; + } + if (this.fsw.closed) { + stream = void 0; + return; + } + if (item === target || !target && !previous.has(item)) { + this.fsw._incrReadyCount(); + path53 = sysPath.join(dir, sysPath.relative(dir, path53)); + this._addToNodeFs(path53, initialAdd, wh, depth + 1); + } + }).on(EV.ERROR, this._boundHandleError); + return new Promise((resolve4, reject) => { + if (!stream) + return reject(); + stream.once(STR_END, () => { + if (this.fsw.closed) { + stream = void 0; + return; + } + const wasThrottled = throttler ? throttler.clear() : false; + resolve4(void 0); + previous.getChildren().filter((item) => { + return item !== directory && !current.has(item); + }).forEach((item) => { + this.fsw._remove(directory, item); + }); + stream = void 0; + if (wasThrottled) + this._handleRead(directory, false, wh, target, dir, depth, throttler); + }); + }); + } + /** + * Read directory to add / remove files from `@watched` list and re-read it on change. + * @param dir fs path + * @param stats + * @param initialAdd + * @param depth relative to user-supplied path + * @param target child path targeted for watch + * @param wh Common watch helpers for this path + * @param realpath + * @returns closer for the watcher instance. + */ + async _handleDir(dir, stats, initialAdd, depth, target, wh, realpath2) { + const parentDir = this.fsw._getWatchedDir(sysPath.dirname(dir)); + const tracked = parentDir.has(sysPath.basename(dir)); + if (!(initialAdd && this.fsw.options.ignoreInitial) && !target && !tracked) { + this.fsw._emit(EV.ADD_DIR, dir, stats); + } + parentDir.add(sysPath.basename(dir)); + this.fsw._getWatchedDir(dir); + let throttler; + let closer; + const oDepth = this.fsw.options.depth; + if ((oDepth == null || depth <= oDepth) && !this.fsw._symlinkPaths.has(realpath2)) { + if (!target) { + await this._handleRead(dir, initialAdd, wh, target, dir, depth, throttler); + if (this.fsw.closed) + return; + } + closer = this._watchWithNodeFs(dir, (dirPath, stats2) => { + if (stats2 && stats2.mtimeMs === 0) + return; + this._handleRead(dirPath, false, wh, target, dir, depth, throttler); + }); + } + return closer; + } + /** + * Handle added file, directory, or glob pattern. + * Delegates call to _handleFile / _handleDir after checks. + * @param path to file or ir + * @param initialAdd was the file added at watch instantiation? + * @param priorWh depth relative to user-supplied path + * @param depth Child path actually targeted for watch + * @param target Child path actually targeted for watch + */ + async _addToNodeFs(path53, initialAdd, priorWh, depth, target) { + const ready = this.fsw._emitReady; + if (this.fsw._isIgnored(path53) || this.fsw.closed) { + ready(); + return false; + } + const wh = this.fsw._getWatchHelpers(path53); + if (priorWh) { + wh.filterPath = (entry) => priorWh.filterPath(entry); + wh.filterDir = (entry) => priorWh.filterDir(entry); + } + try { + const stats = await statMethods[wh.statMethod](wh.watchPath); + if (this.fsw.closed) + return; + if (this.fsw._isIgnored(wh.watchPath, stats)) { + ready(); + return false; + } + const follow = this.fsw.options.followSymlinks; + let closer; + if (stats.isDirectory()) { + const absPath = sysPath.resolve(path53); + const targetPath = follow ? await fsrealpath(path53) : path53; + if (this.fsw.closed) + return; + closer = await this._handleDir(wh.watchPath, stats, initialAdd, depth, target, wh, targetPath); + if (this.fsw.closed) + return; + if (absPath !== targetPath && targetPath !== void 0) { + this.fsw._symlinkPaths.set(absPath, targetPath); + } + } else if (stats.isSymbolicLink()) { + const targetPath = follow ? await fsrealpath(path53) : path53; + if (this.fsw.closed) + return; + const parent = sysPath.dirname(wh.watchPath); + this.fsw._getWatchedDir(parent).add(wh.watchPath); + this.fsw._emit(EV.ADD, wh.watchPath, stats); + closer = await this._handleDir(parent, stats, initialAdd, depth, path53, wh, targetPath); + if (this.fsw.closed) + return; + if (targetPath !== void 0) { + this.fsw._symlinkPaths.set(sysPath.resolve(path53), targetPath); + } + } else { + closer = this._handleFile(wh.watchPath, stats, initialAdd); + } + ready(); + if (closer) + this.fsw._addPathCloser(path53, closer); + return false; + } catch (error50) { + if (this.fsw._handleError(error50)) { + ready(); + return path53; + } + } + } +}; + +// node_modules/.pnpm/chokidar@4.0.3/node_modules/chokidar/esm/index.js +var SLASH = "/"; +var SLASH_SLASH = "//"; +var ONE_DOT = "."; +var TWO_DOTS = ".."; +var STRING_TYPE = "string"; +var BACK_SLASH_RE = /\\/g; +var DOUBLE_SLASH_RE = /\/\//; +var DOT_RE = /\..*\.(sw[px])$|~$|\.subl.*\.tmp/; +var REPLACER_RE = /^\.[/\\]/; +function arrify(item) { + return Array.isArray(item) ? item : [item]; +} +var isMatcherObject = (matcher) => typeof matcher === "object" && matcher !== null && !(matcher instanceof RegExp); +function createPattern(matcher) { + if (typeof matcher === "function") + return matcher; + if (typeof matcher === "string") + return (string4) => matcher === string4; + if (matcher instanceof RegExp) + return (string4) => matcher.test(string4); + if (typeof matcher === "object" && matcher !== null) { + return (string4) => { + if (matcher.path === string4) + return true; + if (matcher.recursive) { + const relative3 = sysPath2.relative(matcher.path, string4); + if (!relative3) { + return false; + } + return !relative3.startsWith("..") && !sysPath2.isAbsolute(relative3); + } + return false; + }; + } + return () => false; +} +function normalizePath2(path53) { + if (typeof path53 !== "string") + throw new Error("string expected"); + path53 = sysPath2.normalize(path53); + path53 = path53.replace(/\\/g, "/"); + let prepend = false; + if (path53.startsWith("//")) + prepend = true; + const DOUBLE_SLASH_RE2 = /\/\//; + while (path53.match(DOUBLE_SLASH_RE2)) + path53 = path53.replace(DOUBLE_SLASH_RE2, "/"); + if (prepend) + path53 = "/" + path53; + return path53; +} +function matchPatterns(patterns, testString, stats) { + const path53 = normalizePath2(testString); + for (let index2 = 0; index2 < patterns.length; index2++) { + const pattern = patterns[index2]; + if (pattern(path53, stats)) { + return true; + } + } + return false; +} +function anymatch(matchers, testString) { + if (matchers == null) { + throw new TypeError("anymatch: specify first argument"); + } + const matchersArray = arrify(matchers); + const patterns = matchersArray.map((matcher) => createPattern(matcher)); + if (testString == null) { + return (testString2, stats) => { + return matchPatterns(patterns, testString2, stats); + }; + } + return matchPatterns(patterns, testString); +} +var unifyPaths = (paths_) => { + const paths2 = arrify(paths_).flat(); + if (!paths2.every((p5) => typeof p5 === STRING_TYPE)) { + throw new TypeError(`Non-string provided as watch path: ${paths2}`); + } + return paths2.map(normalizePathToUnix); +}; +var toUnix = (string4) => { + let str = string4.replace(BACK_SLASH_RE, SLASH); + let prepend = false; + if (str.startsWith(SLASH_SLASH)) { + prepend = true; + } + while (str.match(DOUBLE_SLASH_RE)) { + str = str.replace(DOUBLE_SLASH_RE, SLASH); + } + if (prepend) { + str = SLASH + str; + } + return str; +}; +var normalizePathToUnix = (path53) => toUnix(sysPath2.normalize(toUnix(path53))); +var normalizeIgnored = (cwd = "") => (path53) => { + if (typeof path53 === "string") { + return normalizePathToUnix(sysPath2.isAbsolute(path53) ? path53 : sysPath2.join(cwd, path53)); + } else { + return path53; + } +}; +var getAbsolutePath = (path53, cwd) => { + if (sysPath2.isAbsolute(path53)) { + return path53; + } + return sysPath2.join(cwd, path53); +}; +var EMPTY_SET = Object.freeze(/* @__PURE__ */ new Set()); +var DirEntry = class { + constructor(dir, removeWatcher) { + this.path = dir; + this._removeWatcher = removeWatcher; + this.items = /* @__PURE__ */ new Set(); + } + add(item) { + const { items } = this; + if (!items) + return; + if (item !== ONE_DOT && item !== TWO_DOTS) + items.add(item); + } + async remove(item) { + const { items } = this; + if (!items) + return; + items.delete(item); + if (items.size > 0) + return; + const dir = this.path; + try { + await readdir4(dir); + } catch (err) { + if (this._removeWatcher) { + this._removeWatcher(sysPath2.dirname(dir), sysPath2.basename(dir)); + } + } + } + has(item) { + const { items } = this; + if (!items) + return; + return items.has(item); + } + getChildren() { + const { items } = this; + if (!items) + return []; + return [...items.values()]; + } + dispose() { + this.items.clear(); + this.path = ""; + this._removeWatcher = EMPTY_FN; + this.items = EMPTY_SET; + Object.freeze(this); + } +}; +var STAT_METHOD_F = "stat"; +var STAT_METHOD_L = "lstat"; +var WatchHelper = class { + constructor(path53, follow, fsw) { + this.fsw = fsw; + const watchPath = path53; + this.path = path53 = path53.replace(REPLACER_RE, ""); + this.watchPath = watchPath; + this.fullWatchPath = sysPath2.resolve(watchPath); + this.dirParts = []; + this.dirParts.forEach((parts) => { + if (parts.length > 1) + parts.pop(); + }); + this.followSymlinks = follow; + this.statMethod = follow ? STAT_METHOD_F : STAT_METHOD_L; + } + entryPath(entry) { + return sysPath2.join(this.watchPath, sysPath2.relative(this.watchPath, entry.fullPath)); + } + filterPath(entry) { + const { stats } = entry; + if (stats && stats.isSymbolicLink()) + return this.filterDir(entry); + const resolvedPath2 = this.entryPath(entry); + return this.fsw._isntIgnored(resolvedPath2, stats) && this.fsw._hasReadPermissions(stats); + } + filterDir(entry) { + return this.fsw._isntIgnored(this.entryPath(entry), entry.stats); + } +}; +var FSWatcher = class extends EventEmitter4 { + // Not indenting methods for history sake; for now. + constructor(_opts = {}) { + super(); + this.closed = false; + this._closers = /* @__PURE__ */ new Map(); + this._ignoredPaths = /* @__PURE__ */ new Set(); + this._throttled = /* @__PURE__ */ new Map(); + this._streams = /* @__PURE__ */ new Set(); + this._symlinkPaths = /* @__PURE__ */ new Map(); + this._watched = /* @__PURE__ */ new Map(); + this._pendingWrites = /* @__PURE__ */ new Map(); + this._pendingUnlinks = /* @__PURE__ */ new Map(); + this._readyCount = 0; + this._readyEmitted = false; + const awf = _opts.awaitWriteFinish; + const DEF_AWF = { stabilityThreshold: 2e3, pollInterval: 100 }; + const opts = { + // Defaults + persistent: true, + ignoreInitial: false, + ignorePermissionErrors: false, + interval: 100, + binaryInterval: 300, + followSymlinks: true, + usePolling: false, + // useAsync: false, + atomic: true, + // NOTE: overwritten later (depends on usePolling) + ..._opts, + // Change format + ignored: _opts.ignored ? arrify(_opts.ignored) : arrify([]), + awaitWriteFinish: awf === true ? DEF_AWF : typeof awf === "object" ? { ...DEF_AWF, ...awf } : false + }; + if (isIBMi) + opts.usePolling = true; + if (opts.atomic === void 0) + opts.atomic = !opts.usePolling; + const envPoll = process.env.CHOKIDAR_USEPOLLING; + if (envPoll !== void 0) { + const envLower = envPoll.toLowerCase(); + if (envLower === "false" || envLower === "0") + opts.usePolling = false; + else if (envLower === "true" || envLower === "1") + opts.usePolling = true; + else + opts.usePolling = !!envLower; + } + const envInterval = process.env.CHOKIDAR_INTERVAL; + if (envInterval) + opts.interval = Number.parseInt(envInterval, 10); + let readyCalls = 0; + this._emitReady = () => { + readyCalls++; + if (readyCalls >= this._readyCount) { + this._emitReady = EMPTY_FN; + this._readyEmitted = true; + process.nextTick(() => this.emit(EVENTS.READY)); + } + }; + this._emitRaw = (...args) => this.emit(EVENTS.RAW, ...args); + this._boundRemove = this._remove.bind(this); + this.options = opts; + this._nodeFsHandler = new NodeFsHandler(this); + Object.freeze(opts); + } + _addIgnoredPath(matcher) { + if (isMatcherObject(matcher)) { + for (const ignored of this._ignoredPaths) { + if (isMatcherObject(ignored) && ignored.path === matcher.path && ignored.recursive === matcher.recursive) { + return; + } + } + } + this._ignoredPaths.add(matcher); + } + _removeIgnoredPath(matcher) { + this._ignoredPaths.delete(matcher); + if (typeof matcher === "string") { + for (const ignored of this._ignoredPaths) { + if (isMatcherObject(ignored) && ignored.path === matcher) { + this._ignoredPaths.delete(ignored); + } + } + } + } + // Public methods + /** + * Adds paths to be watched on an existing FSWatcher instance. + * @param paths_ file or file list. Other arguments are unused + */ + add(paths_, _origAdd, _internal) { + const { cwd } = this.options; + this.closed = false; + this._closePromise = void 0; + let paths2 = unifyPaths(paths_); + if (cwd) { + paths2 = paths2.map((path53) => { + const absPath = getAbsolutePath(path53, cwd); + return absPath; + }); + } + paths2.forEach((path53) => { + this._removeIgnoredPath(path53); + }); + this._userIgnored = void 0; + if (!this._readyCount) + this._readyCount = 0; + this._readyCount += paths2.length; + Promise.all(paths2.map(async (path53) => { + const res = await this._nodeFsHandler._addToNodeFs(path53, !_internal, void 0, 0, _origAdd); + if (res) + this._emitReady(); + return res; + })).then((results) => { + if (this.closed) + return; + results.forEach((item) => { + if (item) + this.add(sysPath2.dirname(item), sysPath2.basename(_origAdd || item)); + }); + }); + return this; + } + /** + * Close watchers or start ignoring events from specified paths. + */ + unwatch(paths_) { + if (this.closed) + return this; + const paths2 = unifyPaths(paths_); + const { cwd } = this.options; + paths2.forEach((path53) => { + if (!sysPath2.isAbsolute(path53) && !this._closers.has(path53)) { + if (cwd) + path53 = sysPath2.join(cwd, path53); + path53 = sysPath2.resolve(path53); + } + this._closePath(path53); + this._addIgnoredPath(path53); + if (this._watched.has(path53)) { + this._addIgnoredPath({ + path: path53, + recursive: true + }); + } + this._userIgnored = void 0; + }); + return this; + } + /** + * Close watchers and remove all listeners from watched paths. + */ + close() { + if (this._closePromise) { + return this._closePromise; + } + this.closed = true; + this.removeAllListeners(); + const closers = []; + this._closers.forEach((closerList) => closerList.forEach((closer) => { + const promise2 = closer(); + if (promise2 instanceof Promise) + closers.push(promise2); + })); + this._streams.forEach((stream) => stream.destroy()); + this._userIgnored = void 0; + this._readyCount = 0; + this._readyEmitted = false; + this._watched.forEach((dirent) => dirent.dispose()); + this._closers.clear(); + this._watched.clear(); + this._streams.clear(); + this._symlinkPaths.clear(); + this._throttled.clear(); + this._closePromise = closers.length ? Promise.all(closers).then(() => void 0) : Promise.resolve(); + return this._closePromise; + } + /** + * Expose list of watched paths + * @returns for chaining + */ + getWatched() { + const watchList = {}; + this._watched.forEach((entry, dir) => { + const key = this.options.cwd ? sysPath2.relative(this.options.cwd, dir) : dir; + const index2 = key || ONE_DOT; + watchList[index2] = entry.getChildren().sort(); + }); + return watchList; + } + emitWithAll(event, args) { + this.emit(event, ...args); + if (event !== EVENTS.ERROR) + this.emit(EVENTS.ALL, event, ...args); + } + // Common helpers + // -------------- + /** + * Normalize and emit events. + * Calling _emit DOES NOT MEAN emit() would be called! + * @param event Type of event + * @param path File or directory path + * @param stats arguments to be passed with event + * @returns the error if defined, otherwise the value of the FSWatcher instance's `closed` flag + */ + async _emit(event, path53, stats) { + if (this.closed) + return; + const opts = this.options; + if (isWindows) + path53 = sysPath2.normalize(path53); + if (opts.cwd) + path53 = sysPath2.relative(opts.cwd, path53); + const args = [path53]; + if (stats != null) + args.push(stats); + const awf = opts.awaitWriteFinish; + let pw; + if (awf && (pw = this._pendingWrites.get(path53))) { + pw.lastChange = /* @__PURE__ */ new Date(); + return this; + } + if (opts.atomic) { + if (event === EVENTS.UNLINK) { + this._pendingUnlinks.set(path53, [event, ...args]); + setTimeout(() => { + this._pendingUnlinks.forEach((entry, path54) => { + this.emit(...entry); + this.emit(EVENTS.ALL, ...entry); + this._pendingUnlinks.delete(path54); + }); + }, typeof opts.atomic === "number" ? opts.atomic : 100); + return this; + } + if (event === EVENTS.ADD && this._pendingUnlinks.has(path53)) { + event = EVENTS.CHANGE; + this._pendingUnlinks.delete(path53); + } + } + if (awf && (event === EVENTS.ADD || event === EVENTS.CHANGE) && this._readyEmitted) { + const awfEmit = (err, stats2) => { + if (err) { + event = EVENTS.ERROR; + args[0] = err; + this.emitWithAll(event, args); + } else if (stats2) { + if (args.length > 1) { + args[1] = stats2; + } else { + args.push(stats2); + } + this.emitWithAll(event, args); + } + }; + this._awaitWriteFinish(path53, awf.stabilityThreshold, event, awfEmit); + return this; + } + if (event === EVENTS.CHANGE) { + const isThrottled = !this._throttle(EVENTS.CHANGE, path53, 50); + if (isThrottled) + return this; + } + if (opts.alwaysStat && stats === void 0 && (event === EVENTS.ADD || event === EVENTS.ADD_DIR || event === EVENTS.CHANGE)) { + const fullPath = opts.cwd ? sysPath2.join(opts.cwd, path53) : path53; + let stats2; + try { + stats2 = await stat4(fullPath); + } catch (err) { + } + if (!stats2 || this.closed) + return; + args.push(stats2); + } + this.emitWithAll(event, args); + return this; + } + /** + * Common handler for errors + * @returns The error if defined, otherwise the value of the FSWatcher instance's `closed` flag + */ + _handleError(error50) { + const code = error50 && error50.code; + if (error50 && code !== "ENOENT" && code !== "ENOTDIR" && (!this.options.ignorePermissionErrors || code !== "EPERM" && code !== "EACCES")) { + this.emit(EVENTS.ERROR, error50); + } + return error50 || this.closed; + } + /** + * Helper utility for throttling + * @param actionType type being throttled + * @param path being acted upon + * @param timeout duration of time to suppress duplicate actions + * @returns tracking object or false if action should be suppressed + */ + _throttle(actionType, path53, timeout) { + if (!this._throttled.has(actionType)) { + this._throttled.set(actionType, /* @__PURE__ */ new Map()); + } + const action = this._throttled.get(actionType); + if (!action) + throw new Error("invalid throttle"); + const actionPath = action.get(path53); + if (actionPath) { + actionPath.count++; + return false; + } + let timeoutObject; + const clear = () => { + const item = action.get(path53); + const count2 = item ? item.count : 0; + action.delete(path53); + clearTimeout(timeoutObject); + if (item) + clearTimeout(item.timeoutObject); + return count2; + }; + timeoutObject = setTimeout(clear, timeout); + const thr = { timeoutObject, clear, count: 0 }; + action.set(path53, thr); + return thr; + } + _incrReadyCount() { + return this._readyCount++; + } + /** + * Awaits write operation to finish. + * Polls a newly created file for size variations. When files size does not change for 'threshold' milliseconds calls callback. + * @param path being acted upon + * @param threshold Time in milliseconds a file size must be fixed before acknowledging write OP is finished + * @param event + * @param awfEmit Callback to be called when ready for event to be emitted. + */ + _awaitWriteFinish(path53, threshold, event, awfEmit) { + const awf = this.options.awaitWriteFinish; + if (typeof awf !== "object") + return; + const pollInterval = awf.pollInterval; + let timeoutHandler; + let fullPath = path53; + if (this.options.cwd && !sysPath2.isAbsolute(path53)) { + fullPath = sysPath2.join(this.options.cwd, path53); + } + const now2 = /* @__PURE__ */ new Date(); + const writes = this._pendingWrites; + function awaitWriteFinishFn(prevStat) { + statcb(fullPath, (err, curStat) => { + if (err || !writes.has(path53)) { + if (err && err.code !== "ENOENT") + awfEmit(err); + return; + } + const now3 = Number(/* @__PURE__ */ new Date()); + if (prevStat && curStat.size !== prevStat.size) { + writes.get(path53).lastChange = now3; + } + const pw = writes.get(path53); + const df = now3 - pw.lastChange; + if (df >= threshold) { + writes.delete(path53); + awfEmit(void 0, curStat); + } else { + timeoutHandler = setTimeout(awaitWriteFinishFn, pollInterval, curStat); + } + }); + } + if (!writes.has(path53)) { + writes.set(path53, { + lastChange: now2, + cancelWait: () => { + writes.delete(path53); + clearTimeout(timeoutHandler); + return event; + } + }); + timeoutHandler = setTimeout(awaitWriteFinishFn, pollInterval); + } + } + /** + * Determines whether user has asked to ignore this path. + */ + _isIgnored(path53, stats) { + if (this.options.atomic && DOT_RE.test(path53)) + return true; + if (!this._userIgnored) { + const { cwd } = this.options; + const ign = this.options.ignored; + const ignored = (ign || []).map(normalizeIgnored(cwd)); + const ignoredPaths = [...this._ignoredPaths]; + const list2 = [...ignoredPaths.map(normalizeIgnored(cwd)), ...ignored]; + this._userIgnored = anymatch(list2, void 0); + } + return this._userIgnored(path53, stats); + } + _isntIgnored(path53, stat5) { + return !this._isIgnored(path53, stat5); + } + /** + * Provides a set of common helpers and properties relating to symlink handling. + * @param path file or directory pattern being watched + */ + _getWatchHelpers(path53) { + return new WatchHelper(path53, this.options.followSymlinks, this); + } + // Directory helpers + // ----------------- + /** + * Provides directory tracking objects + * @param directory path of the directory + */ + _getWatchedDir(directory) { + const dir = sysPath2.resolve(directory); + if (!this._watched.has(dir)) + this._watched.set(dir, new DirEntry(dir, this._boundRemove)); + return this._watched.get(dir); + } + // File helpers + // ------------ + /** + * Check for read permissions: https://stackoverflow.com/a/11781404/1358405 + */ + _hasReadPermissions(stats) { + if (this.options.ignorePermissionErrors) + return true; + return Boolean(Number(stats.mode) & 256); + } + /** + * Handles emitting unlink events for + * files and directories, and via recursion, for + * files and directories within directories that are unlinked + * @param directory within which the following item is located + * @param item base path of item/directory + */ + _remove(directory, item, isDirectory) { + const path53 = sysPath2.join(directory, item); + const fullPath = sysPath2.resolve(path53); + isDirectory = isDirectory != null ? isDirectory : this._watched.has(path53) || this._watched.has(fullPath); + if (!this._throttle("remove", path53, 100)) + return; + if (!isDirectory && this._watched.size === 1) { + this.add(directory, item, true); + } + const wp = this._getWatchedDir(path53); + const nestedDirectoryChildren = wp.getChildren(); + nestedDirectoryChildren.forEach((nested) => this._remove(path53, nested)); + const parent = this._getWatchedDir(directory); + const wasTracked = parent.has(item); + parent.remove(item); + if (this._symlinkPaths.has(fullPath)) { + this._symlinkPaths.delete(fullPath); + } + let relPath = path53; + if (this.options.cwd) + relPath = sysPath2.relative(this.options.cwd, path53); + if (this.options.awaitWriteFinish && this._pendingWrites.has(relPath)) { + const event = this._pendingWrites.get(relPath).cancelWait(); + if (event === EVENTS.ADD) + return; + } + this._watched.delete(path53); + this._watched.delete(fullPath); + const eventName = isDirectory ? EVENTS.UNLINK_DIR : EVENTS.UNLINK; + if (wasTracked && !this._isIgnored(path53)) + this._emit(eventName, path53); + this._closePath(path53); + } + /** + * Closes all watchers for a path + */ + _closePath(path53) { + this._closeFile(path53); + const dir = sysPath2.dirname(path53); + this._getWatchedDir(dir).remove(sysPath2.basename(path53)); + } + /** + * Closes only file-specific watchers + */ + _closeFile(path53) { + const closers = this._closers.get(path53); + if (!closers) + return; + closers.forEach((closer) => closer()); + this._closers.delete(path53); + } + _addPathCloser(path53, closer) { + if (!closer) + return; + let list2 = this._closers.get(path53); + if (!list2) { + list2 = []; + this._closers.set(path53, list2); + } + list2.push(closer); + } + _readdirp(root, opts) { + if (this.closed) + return; + const options = { type: EVENTS.ALL, alwaysStat: true, lstat: true, ...opts, depth: 0 }; + let stream = readdirp(root, options); + this._streams.add(stream); + stream.once(STR_CLOSE, () => { + stream = void 0; + }); + stream.once(STR_END, () => { + if (stream) { + this._streams.delete(stream); + stream = void 0; + } + }); + return stream; + } +}; +function watch(paths2, options = {}) { + const watcher = new FSWatcher(options); + watcher.add(paths2); + return watcher; +} +var esm_default = { watch, FSWatcher }; + +// server/src/services/plugin-dev-watcher.ts +import { existsSync as existsSync7, readFileSync as readFileSync4, readdirSync as readdirSync2, statSync as statSync2 } from "node:fs"; +import path50 from "node:path"; +var log = logger.child({ service: "plugin-dev-watcher" }); +var DEBOUNCE_MS = 500; +function shouldIgnorePath(filename) { + if (!filename) return false; + const normalized = filename.replace(/\\/g, "/"); + const segments = normalized.split("/").filter(Boolean); + return segments.some( + (segment) => segment === "node_modules" || segment === ".git" || segment === ".vite" || segment === ".taskcore-sdk" || segment.startsWith(".") + ); +} +function resolvePluginWatchTargets(packagePath, fsDeps) { + const fileExists = fsDeps?.existsSync ?? existsSync7; + const readFile5 = fsDeps?.readFileSync ?? readFileSync4; + const readDir = fsDeps?.readdirSync ?? readdirSync2; + const statFile = fsDeps?.statSync ?? statSync2; + const absPath = path50.resolve(packagePath); + const targets = /* @__PURE__ */ new Map(); + function addWatchTarget(targetPath, recursive, kind) { + const resolved = path50.resolve(targetPath); + if (!fileExists(resolved)) return; + const inferredKind = kind ?? (statFile(resolved).isDirectory() ? "dir" : "file"); + const existing = targets.get(resolved); + if (existing) { + existing.recursive = existing.recursive || recursive; + return; + } + targets.set(resolved, { path: resolved, recursive, kind: inferredKind }); + } + function addRuntimeFilesFromDir(dirPath) { + if (!fileExists(dirPath)) return; + for (const entry of readDir(dirPath, { withFileTypes: true })) { + const entryPath = path50.join(dirPath, entry.name); + if (entry.isDirectory()) { + addRuntimeFilesFromDir(entryPath); + continue; + } + if (!entry.isFile()) continue; + if (!entry.name.endsWith(".js") && !entry.name.endsWith(".css")) continue; + addWatchTarget(entryPath, false, "file"); + } + } + const packageJsonPath = path50.join(absPath, "package.json"); + addWatchTarget(packageJsonPath, false, "file"); + if (!fileExists(packageJsonPath)) { + return [...targets.values()]; + } + let packageJson = null; + try { + packageJson = JSON.parse(readFile5(packageJsonPath, "utf8")); + } catch { + packageJson = null; + } + const entrypointPaths = [ + packageJson?.taskcorePlugin?.manifest, + packageJson?.taskcorePlugin?.worker, + packageJson?.taskcorePlugin?.ui + ].filter((value) => typeof value === "string" && value.length > 0); + if (entrypointPaths.length === 0) { + addRuntimeFilesFromDir(path50.join(absPath, "dist")); + return [...targets.values()]; + } + for (const relativeEntrypoint of entrypointPaths) { + const resolvedEntrypoint = path50.resolve(absPath, relativeEntrypoint); + if (!fileExists(resolvedEntrypoint)) continue; + const stat5 = statFile(resolvedEntrypoint); + if (stat5.isDirectory()) { + addRuntimeFilesFromDir(resolvedEntrypoint); + } else { + addWatchTarget(resolvedEntrypoint, false, "file"); + } + } + return [...targets.values()].sort((a5, b6) => a5.path.localeCompare(b6.path)); +} +function createPluginDevWatcher(lifecycle, resolvePluginPackagePath, fsDeps) { + const watchers = /* @__PURE__ */ new Map(); + const debounceTimers = /* @__PURE__ */ new Map(); + const fileExists = fsDeps?.existsSync ?? existsSync7; + function watchPlugin(pluginId, packagePath) { + if (watchers.has(pluginId)) return; + const absPath = path50.resolve(packagePath); + if (!fileExists(absPath)) { + log.warn( + { pluginId, packagePath: absPath }, + "plugin-dev-watcher: package path does not exist, skipping watch" + ); + return; + } + try { + const watcherTargets = resolvePluginWatchTargets(absPath, fsDeps); + if (watcherTargets.length === 0) { + log.warn( + { pluginId, packagePath: absPath }, + "plugin-dev-watcher: no valid watch targets found, skipping watch" + ); + return; + } + const watcher = esm_default.watch( + watcherTargets.map((target) => target.path), + { + ignoreInitial: true, + awaitWriteFinish: { + stabilityThreshold: 200, + pollInterval: 100 + }, + ignored: (watchedPath) => { + const relativePath = path50.relative(absPath, watchedPath); + return shouldIgnorePath(relativePath); + } + } + ); + watcher.on("all", (_eventName, changedPath) => { + const relativePath = path50.relative(absPath, changedPath); + if (shouldIgnorePath(relativePath)) return; + const existing = debounceTimers.get(pluginId); + if (existing) clearTimeout(existing); + debounceTimers.set( + pluginId, + setTimeout(() => { + debounceTimers.delete(pluginId); + log.info( + { pluginId, changedFile: relativePath || path50.basename(changedPath) }, + "plugin-dev-watcher: file change detected, restarting worker" + ); + lifecycle.restartWorker(pluginId).catch((err) => { + log.warn( + { + pluginId, + err: err instanceof Error ? err.message : String(err) + }, + "plugin-dev-watcher: failed to restart worker after file change" + ); + }); + }, DEBOUNCE_MS) + ); + }); + watcher.on("error", (err) => { + log.warn( + { + pluginId, + packagePath: absPath, + err: err instanceof Error ? err.message : String(err) + }, + "plugin-dev-watcher: watcher error, stopping watch for this plugin" + ); + unwatchPlugin(pluginId); + }); + watchers.set(pluginId, watcher); + log.info( + { + pluginId, + packagePath: absPath, + watchTargets: watcherTargets.map((target) => ({ + path: target.path, + kind: target.kind + })) + }, + "plugin-dev-watcher: watching local plugin for changes" + ); + } catch (err) { + log.warn( + { + pluginId, + packagePath: absPath, + err: err instanceof Error ? err.message : String(err) + }, + "plugin-dev-watcher: failed to start file watcher" + ); + } + } + function unwatchPlugin(pluginId) { + const pluginWatcher = watchers.get(pluginId); + if (pluginWatcher) { + void pluginWatcher.close(); + watchers.delete(pluginId); + } + const timer2 = debounceTimers.get(pluginId); + if (timer2) { + clearTimeout(timer2); + debounceTimers.delete(pluginId); + } + } + function close() { + lifecycle.off("plugin.loaded", handlePluginLoaded); + lifecycle.off("plugin.enabled", handlePluginEnabled); + lifecycle.off("plugin.disabled", handlePluginDisabled); + lifecycle.off("plugin.unloaded", handlePluginUnloaded); + for (const [pluginId] of watchers) { + unwatchPlugin(pluginId); + } + } + async function watchLocalPluginById(pluginId) { + if (!resolvePluginPackagePath) return; + try { + const packagePath = await resolvePluginPackagePath(pluginId); + if (!packagePath) return; + watchPlugin(pluginId, packagePath); + } catch (err) { + log.warn( + { + pluginId, + err: err instanceof Error ? err.message : String(err) + }, + "plugin-dev-watcher: failed to resolve plugin package path" + ); + } + } + function handlePluginLoaded(payload2) { + void watchLocalPluginById(payload2.pluginId); + } + function handlePluginEnabled(payload2) { + void watchLocalPluginById(payload2.pluginId); + } + function handlePluginDisabled(payload2) { + unwatchPlugin(payload2.pluginId); + } + function handlePluginUnloaded(payload2) { + unwatchPlugin(payload2.pluginId); + } + lifecycle.on("plugin.loaded", handlePluginLoaded); + lifecycle.on("plugin.enabled", handlePluginEnabled); + lifecycle.on("plugin.disabled", handlePluginDisabled); + lifecycle.on("plugin.unloaded", handlePluginUnloaded); + return { + watch: watchPlugin, + unwatch: unwatchPlugin, + close + }; +} + +// server/src/services/plugin-host-service-cleanup.ts +function createPluginHostServiceCleanup(lifecycle, disposers) { + const runDispose = (pluginId, remove = false) => { + const dispose = disposers.get(pluginId); + if (!dispose) return; + dispose(); + if (remove) { + disposers.delete(pluginId); + } + }; + const handleWorkerStopped = ({ pluginId }) => { + runDispose(pluginId); + }; + const handlePluginUnloaded = ({ pluginId }) => { + runDispose(pluginId, true); + }; + lifecycle.on("plugin.worker_stopped", handleWorkerStopped); + lifecycle.on("plugin.unloaded", handlePluginUnloaded); + return { + handleWorkerEvent(event) { + if (event.type === "plugin.worker.crashed") { + runDispose(event.pluginId); + } + }, + disposeAll() { + for (const dispose of disposers.values()) { + dispose(); + } + disposers.clear(); + }, + teardown() { + lifecycle.off("plugin.worker_stopped", handleWorkerStopped); + lifecycle.off("plugin.unloaded", handlePluginUnloaded); + } + }; +} + +// server/src/vite-html-renderer.ts +import fs39 from "node:fs"; +import path51 from "node:path"; +var WATCHER_EVENTS = ["add", "change", "unlink"]; +var MAIN_ENTRY_TAG = ''; +var VITE_CLIENT_TAG = ''; +var REACT_REFRESH_PREAMBLE = ``; +function injectViteDevPreamble(html3) { + let injectedHtml = html3; + if (!injectedHtml.includes('"/@react-refresh"') && !injectedHtml.includes("'/@react-refresh'")) { + injectedHtml = injectedHtml.includes("") ? injectedHtml.replace("", ` ${REACT_REFRESH_PREAMBLE} + `) : `${REACT_REFRESH_PREAMBLE} +${injectedHtml}`; + } + if (injectedHtml.includes(VITE_CLIENT_TAG)) return injectedHtml; + if (injectedHtml.includes(MAIN_ENTRY_TAG)) { + return injectedHtml.replace(MAIN_ENTRY_TAG, `${VITE_CLIENT_TAG} + ${MAIN_ENTRY_TAG}`); + } + return injectedHtml.replace("", ` ${VITE_CLIENT_TAG} + `); +} +function createCachedViteHtmlRenderer(opts) { + const uiRoot = path51.resolve(opts.uiRoot); + const templatePath = path51.resolve(uiRoot, "index.html"); + const brandHtml = opts.brandHtml ?? ((html3) => html3); + let cachedHtml = null; + function loadHtml() { + if (cachedHtml === null) { + const rawTemplate = fs39.readFileSync(templatePath, "utf-8"); + cachedHtml = injectViteDevPreamble(brandHtml(rawTemplate)); + } + return cachedHtml; + } + function invalidate() { + cachedHtml = null; + } + function onWatchEvent(filePath) { + const resolvedPath2 = path51.resolve(filePath); + if (resolvedPath2 === templatePath || resolvedPath2.startsWith(`${uiRoot}${path51.sep}`)) { + invalidate(); + } + } + for (const eventName of WATCHER_EVENTS) { + opts.vite.watcher?.on?.(eventName, onWatchEvent); + } + return { + render() { + return Promise.resolve(loadHtml()); + }, + dispose() { + for (const eventName of WATCHER_EVENTS) { + opts.vite.watcher?.off?.(eventName, onWatchEvent); + } + } + }; +} + +// server/src/app.ts +var FEEDBACK_EXPORT_FLUSH_INTERVAL_MS = 5e3; +var VITE_DEV_ASSET_PREFIXES = [ + "/@fs/", + "/@id/", + "/@react-refresh", + "/@vite/", + "/assets/", + "/node_modules/", + "/src/" +]; +var VITE_DEV_STATIC_PATHS = /* @__PURE__ */ new Set([ + "/apple-touch-icon.png", + "/favicon-16x16.png", + "/favicon-32x32.png", + "/favicon.ico", + "/favicon.svg", + "/site.webmanifest" +]); +function resolveViteHmrPort(serverPort) { + if (serverPort <= 55535) { + return serverPort + 1e4; + } + return Math.max(1024, serverPort - 1e4); +} +function shouldServeViteDevHtml(req) { + const pathname = req.path; + if (VITE_DEV_STATIC_PATHS.has(pathname)) return false; + if (VITE_DEV_ASSET_PREFIXES.some((prefix) => pathname.startsWith(prefix))) return false; + return req.accepts(["html"]) === "html"; +} +async function createApp(db, opts) { + const app = (0, import_express25.default)(); + const pluginsEnabled = process.env.TASKCORE_PLUGINS_ENABLED !== "false"; + app.use(import_express25.default.json({ + // Company import/export payloads can inline full portable packages. + limit: "10mb", + verify: (req, _res, buf) => { + req.rawBody = buf; + } + })); + app.use(httpLogger); + const privateHostnameGateEnabled = opts.deploymentMode === "authenticated" && opts.deploymentExposure === "private"; + const privateHostnameAllowSet = resolvePrivateHostnameAllowSet({ + allowedHostnames: opts.allowedHostnames, + bindHost: opts.bindHost + }); + app.use( + privateHostnameGuard({ + enabled: privateHostnameGateEnabled, + allowedHostnames: opts.allowedHostnames, + bindHost: opts.bindHost + }) + ); + app.use( + actorMiddleware(db, { + deploymentMode: opts.deploymentMode, + resolveSession: opts.resolveSession + }) + ); + app.get("/api/auth/get-session", (req, res) => { + if (req.actor.type !== "board" || !req.actor.userId) { + res.status(401).json({ error: "Unauthorized" }); + return; + } + res.json({ + session: { + id: `taskcore:${req.actor.source}:${req.actor.userId}`, + userId: req.actor.userId + }, + user: { + id: req.actor.userId, + email: null, + name: req.actor.source === "local_implicit" ? "Local Board" : null + } + }); + }); + if (opts.betterAuthHandler) { + app.all("/api/auth/{*authPath}", opts.betterAuthHandler); + } + app.use(llmRoutes(db)); + const api = (0, import_express25.Router)(); + api.use(boardMutationGuard()); + api.use( + "/health", + healthRoutes(db, { + deploymentMode: opts.deploymentMode, + deploymentExposure: opts.deploymentExposure, + authReady: opts.authReady, + companyDeletionEnabled: opts.companyDeletionEnabled + }) + ); + api.use("/companies", companyRoutes(db, opts.storageService)); + api.use(companySkillRoutes(db)); + api.use(agentRoutes(db)); + api.use(assetRoutes(db, opts.storageService)); + api.use(projectRoutes(db)); + api.use(issueRoutes(db, opts.storageService, { + feedbackExportService: opts.feedbackExportService + })); + api.use(routineRoutes(db)); + api.use(executionWorkspaceRoutes(db)); + api.use(goalRoutes(db)); + api.use(approvalRoutes(db)); + api.use(secretRoutes(db)); + api.use(costRoutes(db)); + api.use(activityRoutes(db)); + api.use(dashboardRoutes(db)); + api.use(sidebarBadgeRoutes(db)); + api.use(sidebarPreferenceRoutes(db)); + api.use(inboxDismissalRoutes(db)); + api.use(instanceSettingsRoutes(db)); + const hostServicesDisposers = /* @__PURE__ */ new Map(); + const workerManager = createPluginWorkerManager(); + const pluginRegistry = pluginRegistryService(db); + const eventBus = createPluginEventBus(); + setPluginEventBus(eventBus); + const jobStore = pluginJobStore(db); + const lifecycle = pluginLifecycleManager(db, { workerManager }); + const scheduler = createPluginJobScheduler({ + db, + jobStore, + workerManager + }); + const toolDispatcher = createPluginToolDispatcher({ + workerManager, + lifecycleManager: lifecycle, + db + }); + const jobCoordinator = createPluginJobCoordinator({ + db, + lifecycle, + scheduler, + jobStore + }); + const hostServiceCleanup = createPluginHostServiceCleanup(lifecycle, hostServicesDisposers); + let viteHtmlRenderer = null; + const loader = pluginLoader( + db, + { localPluginDir: opts.localPluginDir ?? DEFAULT_LOCAL_PLUGIN_DIR }, + { + workerManager, + eventBus, + jobScheduler: scheduler, + jobStore, + toolDispatcher, + lifecycleManager: lifecycle, + instanceInfo: { + instanceId: opts.instanceId ?? "default", + hostVersion: opts.hostVersion ?? "0.0.0" + }, + buildHostHandlers: (pluginId, manifest) => { + const notifyWorker = (method, params) => { + const handle = workerManager.getWorker(pluginId); + if (handle) handle.notify(method, params); + }; + const services = buildHostServices(db, pluginId, manifest.id, eventBus, notifyWorker); + hostServicesDisposers.set(pluginId, () => services.dispose()); + return createHostClientHandlers({ + pluginId, + capabilities: manifest.capabilities, + services + }); + } + } + ); + api.use( + pluginRoutes( + db, + loader, + { scheduler, jobStore }, + { workerManager }, + { toolDispatcher }, + { workerManager } + ) + ); + api.use(adapterRoutes()); + api.use( + accessRoutes(db, { + deploymentMode: opts.deploymentMode, + deploymentExposure: opts.deploymentExposure, + bindHost: opts.bindHost, + allowedHostnames: opts.allowedHostnames + }) + ); + app.use("/api", api); + app.use("/api", (_req, res) => { + res.status(404).json({ error: "API route not found" }); + }); + app.use(pluginUiStaticRoutes(db, { + localPluginDir: opts.localPluginDir ?? DEFAULT_LOCAL_PLUGIN_DIR + })); + const __dirname4 = path52.dirname(fileURLToPath19(import.meta.url)); + if (opts.uiMode === "static") { + const candidates = [ + path52.resolve(__dirname4, "../ui-dist"), + path52.resolve(__dirname4, "../../ui/dist") + ]; + const uiDist = candidates.find((p5) => fs40.existsSync(path52.join(p5, "index.html"))); + if (uiDist) { + const indexHtml = applyUiBranding(fs40.readFileSync(path52.join(uiDist, "index.html"), "utf-8")); + app.use(import_express25.default.static(uiDist)); + app.get(/.*/, (_req, res) => { + res.status(200).set("Content-Type", "text/html").end(indexHtml); + }); + } else { + console.warn("[taskcore] UI dist not found; running in API-only mode"); + } + } + if (opts.uiMode === "vite-dev") { + const uiRoot = path52.resolve(__dirname4, "../../ui"); + const hmrPort = resolveViteHmrPort(opts.serverPort); + const { createServer: createViteServer } = await import("vite"); + const vite = await createViteServer({ + root: uiRoot, + appType: "custom", + server: { + middlewareMode: true, + hmr: { + host: opts.bindHost, + port: hmrPort, + clientPort: hmrPort + }, + allowedHosts: privateHostnameGateEnabled ? Array.from(privateHostnameAllowSet) : void 0 + } + }); + viteHtmlRenderer = createCachedViteHtmlRenderer({ + vite, + uiRoot, + brandHtml: applyUiBranding + }); + const renderViteHtml = viteHtmlRenderer; + app.get(/.*/, async (req, res, next) => { + if (!shouldServeViteDevHtml(req)) { + next(); + return; + } + try { + const html3 = await renderViteHtml.render(req.originalUrl); + res.status(200).set({ "Content-Type": "text/html" }).end(html3); + } catch (err) { + next(err); + } + }); + app.use(vite.middlewares); + } + app.use(errorHandler); + if (pluginsEnabled) { + jobCoordinator.start(); + scheduler.start(); + void toolDispatcher.initialize().catch((err) => { + logger.error({ err }, "Failed to initialize plugin tool dispatcher"); + }); + } + const feedbackExportTimer = opts.feedbackExportService ? setInterval(() => { + void opts.feedbackExportService?.flushPendingFeedbackTraces().catch((err) => { + logger.error({ err }, "Failed to flush pending feedback exports"); + }); + }, FEEDBACK_EXPORT_FLUSH_INTERVAL_MS) : null; + feedbackExportTimer?.unref?.(); + if (opts.feedbackExportService) { + void opts.feedbackExportService.flushPendingFeedbackTraces().catch((err) => { + logger.error({ err }, "Failed to flush pending feedback exports"); + }); + } + const devWatcher = pluginsEnabled && opts.uiMode === "vite-dev" ? createPluginDevWatcher( + lifecycle, + async (pluginId) => (await pluginRegistry.getById(pluginId))?.packagePath ?? null + ) : null; + if (pluginsEnabled) { + void loader.loadAll().then((result) => { + if (!result) return; + for (const loaded of result.results) { + if (devWatcher && loaded.success && loaded.plugin.packagePath) { + devWatcher.watch(loaded.plugin.id, loaded.plugin.packagePath); + } + } + }).catch((err) => { + logger.error({ err }, "Failed to load ready plugins on startup"); + }); + } + process.once("exit", () => { + if (feedbackExportTimer) clearInterval(feedbackExportTimer); + devWatcher?.close(); + viteHtmlRenderer?.dispose(); + hostServiceCleanup.disposeAll(); + hostServiceCleanup.teardown(); + }); + process.once("beforeExit", () => { + void flushPluginLogBuffer(); + }); + return app; +} + +// server/src/services/feedback-share-client.ts +import { gzipSync } from "node:zlib"; +var DEFAULT_FEEDBACK_EXPORT_BACKEND_URL = "https://telemetry.taskcore.ing"; +function buildFeedbackShareObjectKey(bundle, exportedAt) { + const year3 = String(exportedAt.getUTCFullYear()); + const month = String(exportedAt.getUTCMonth() + 1).padStart(2, "0"); + const day2 = String(exportedAt.getUTCDate()).padStart(2, "0"); + return `feedback-traces/${bundle.companyId}/${year3}/${month}/${day2}/${bundle.exportId ?? bundle.traceId}.json`; +} +function createFeedbackTraceShareClientFromConfig(config3) { + const baseUrl = config3.feedbackExportBackendUrl?.trim() || DEFAULT_FEEDBACK_EXPORT_BACKEND_URL; + const token = config3.feedbackExportBackendToken?.trim(); + const endpoint = new URL("/feedback-traces", baseUrl).toString(); + return { + async uploadTraceBundle(bundle) { + const exportedAt = /* @__PURE__ */ new Date(); + const objectKey = buildFeedbackShareObjectKey(bundle, exportedAt); + const requestBody = JSON.stringify({ + objectKey, + exportedAt: exportedAt.toISOString(), + bundle + }); + const response = await fetch(endpoint, { + method: "POST", + headers: { + "content-type": "application/json", + ...token ? { authorization: `Bearer ${token}` } : {} + }, + body: JSON.stringify({ + encoding: "gzip+base64+json", + payload: gzipSync(requestBody).toString("base64") + }) + }); + if (!response.ok) { + const detail = await response.text().catch(() => ""); + throw new Error(detail.trim() || `Feedback trace upload failed with HTTP ${response.status}`); + } + const payload2 = await response.json().catch(() => null); + return { + objectKey: typeof payload2?.objectKey === "string" && payload2.objectKey.trim().length > 0 ? payload2.objectKey : objectKey + }; + } + }; +} + +// server/src/vercel.ts +function isVercelRuntime() { + return process.env.VERCEL === "1" || process.env.NOW === "1"; +} +function applyVercelDefaults() { + if (!isVercelRuntime()) return; + const defaults = { + TASKCORE_DEPLOYMENT_MODE: "authenticated", + TASKCORE_DEPLOYMENT_EXPOSURE: "public", + SERVE_UI: "false", + TASKCORE_PLUGINS_ENABLED: "false", + TASKCORE_DB_BACKUP_ENABLED: "false", + HEARTBEAT_SCHEDULER_ENABLED: "false", + TASKCORE_STORAGE_LOCAL_DIR: "/tmp/taskcore-storage", + TASKCORE_LOG_DIR: "/tmp/taskcore-logs", + TASKCORE_PG_MAX_CONNECTIONS: "5" + }; + for (const [key, value] of Object.entries(defaults)) { + if (process.env[key] === void 0) { + process.env[key] = value; + } + } +} +function assertVercelConfig(config3) { + if (isVercelRuntime() && config3.deploymentMode !== "authenticated") { + throw new Error( + "Taskcore on Vercel requires TASKCORE_DEPLOYMENT_MODE=authenticated (a public, unauthenticated board is not allowed)." + ); + } + if (isVercelRuntime() && config3.deploymentExposure !== "public") { + throw new Error( + "Taskcore on Vercel requires TASKCORE_DEPLOYMENT_EXPOSURE=public." + ); + } + if (config3.deploymentMode === "authenticated" && config3.deploymentExposure === "public") { + if (config3.authBaseUrlMode !== "explicit" || !config3.authPublicBaseUrl) { + throw new Error( + "Authenticated public exposure requires auth.baseUrlMode=explicit and a public URL. Set TASKCORE_AUTH_PUBLIC_BASE_URL (or BETTER_AUTH_URL) to the deployment URL (e.g. https://taskcore-.vercel.app)." + ); + } + } +} +async function createAppForServerless(config3, db) { + let authReady = config3.deploymentMode === "local_trusted"; + let betterAuthHandler; + let resolveSession; + if (config3.deploymentMode === "authenticated") { + const { + createBetterAuthHandler: createBetterAuthHandler2, + createBetterAuthInstance: createBetterAuthInstance2, + deriveAuthTrustedOrigins: deriveAuthTrustedOrigins2, + resolveBetterAuthSession: resolveBetterAuthSession2 + } = await Promise.resolve().then(() => (init_better_auth(), better_auth_exports)); + const derivedTrustedOrigins = deriveAuthTrustedOrigins2(config3); + const envTrustedOrigins = (process.env.BETTER_AUTH_TRUSTED_ORIGINS ?? "").split(",").map((value) => value.trim()).filter((value) => value.length > 0); + const effectiveTrustedOrigins = Array.from(/* @__PURE__ */ new Set([...derivedTrustedOrigins, ...envTrustedOrigins])); + logger.info( + { + authBaseUrlMode: config3.authBaseUrlMode, + authPublicBaseUrl: config3.authPublicBaseUrl ?? null, + trustedOrigins: effectiveTrustedOrigins + }, + "Authenticated mode auth origin configuration (serverless)" + ); + const auth = createBetterAuthInstance2(db, config3, effectiveTrustedOrigins); + betterAuthHandler = createBetterAuthHandler2(auth); + resolveSession = (req) => resolveBetterAuthSession2(auth, req); + await initializeBoardClaimChallenge(db, { deploymentMode: config3.deploymentMode }); + authReady = true; + } + const storageService = createStorageServiceFromConfig(config3); + const feedback = feedbackService(db, { + shareClient: createFeedbackTraceShareClientFromConfig(config3) + }); + return createApp(db, { + uiMode: "none", + serverPort: 3e3, + storageService, + feedbackExportService: feedback, + deploymentMode: config3.deploymentMode, + deploymentExposure: config3.deploymentExposure, + allowedHostnames: config3.allowedHostnames, + bindHost: config3.host, + authReady, + companyDeletionEnabled: config3.companyDeletionEnabled, + betterAuthHandler, + resolveSession + }); +} +async function boot() { + applyVercelDefaults(); + const config3 = loadConfig(); + if (!config3.databaseUrl) { + throw new Error( + "Taskcore on Vercel requires an external PostgreSQL connection. Set DATABASE_URL (or the Vercel Postgres / RDS environment: POSTGRES_URL or PGHOST/PGDATABASE/PGUSER/PGPASSWORD)." + ); + } + assertVercelConfig(config3); + const maxConnections = Math.max(1, Number(process.env.TASKCORE_PG_MAX_CONNECTIONS) || 10); + const prepareDisabled = process.env.TASKCORE_PG_PREPARE !== void 0 ? process.env.TASKCORE_PG_PREPARE === "true" : isVercelRuntime(); + const db = createDb(config3.databaseUrl, { + max: maxConnections, + ...prepareDisabled ? { prepare: false } : {} + }); + logger.info( + { + deploymentMode: config3.deploymentMode, + deploymentExposure: config3.deploymentExposure, + storageProvider: config3.storageProvider, + databaseConfigured: true + }, + "Booting Taskcore serverless app" + ); + return createAppForServerless(config3, db); +} +var appPromise = null; +async function taskcoreVercelHandler(req, res) { + const app = await (appPromise ??= boot().catch((err) => { + appPromise = null; + throw err; + })); + app(req, res); +} +export { + taskcoreVercelHandler as default +}; diff --git a/packages/db/src/client.ts b/packages/db/src/client.ts index 2b1949a..d351e67 100644 --- a/packages/db/src/client.ts +++ b/packages/db/src/client.ts @@ -45,8 +45,16 @@ export type MigrationState = reason: "no-migration-journal-empty-db" | "no-migration-journal-non-empty-db" | "pending-migrations"; }; -export function createDb(url: string) { - const sql = postgres(url); +export type CreateDbOptions = { + max?: number; + prepare?: boolean; +}; + +export function createDb(url: string, options?: CreateDbOptions) { + const opts: Record = {}; + if (options?.max !== undefined) opts.max = options.max; + if (options?.prepare !== undefined) opts.prepare = options.prepare; + const sql = postgres(url, opts); return drizzlePg(sql, { schema }); } diff --git a/packages/db/src/runtime-config.ts b/packages/db/src/runtime-config.ts index 3527d74..6ccd056 100644 --- a/packages/db/src/runtime-config.ts +++ b/packages/db/src/runtime-config.ts @@ -1,6 +1,7 @@ import { existsSync, readFileSync } from "node:fs"; import os from "node:os"; import path from "node:path"; +import { resolvePostgresUrlFromEnv } from "@taskcore/shared"; const DEFAULT_INSTANCE_ID = "default"; const CONFIG_BASENAME = "config.json"; @@ -217,7 +218,7 @@ export function resolveDatabaseTarget(): ResolvedDatabaseTarget { const envPath = resolveTaskcoreEnvPath(configPath); const envEntries = readEnvEntries(envPath); - const envUrl = process.env.DATABASE_URL?.trim(); + const envUrl = resolvePostgresUrlFromEnv(); if (envUrl) { return { mode: "postgres", diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts index 5912ea5..1b34e13 100644 --- a/packages/shared/src/index.ts +++ b/packages/shared/src/index.ts @@ -1,4 +1,5 @@ export { agentAdapterTypeSchema, optionalAgentAdapterTypeSchema } from "./adapter-type.js"; +export { resolvePostgresUrlFromEnv } from "./vercel-postgres.js"; export { COMPANY_STATUSES, DEPLOYMENT_MODES, diff --git a/packages/shared/src/vercel-postgres.ts b/packages/shared/src/vercel-postgres.ts new file mode 100644 index 0000000..2326df9 --- /dev/null +++ b/packages/shared/src/vercel-postgres.ts @@ -0,0 +1,38 @@ +/** + * Resolve a PostgreSQL connection URL from the environment. + * + * Vercel exposes the database connection through several conventions: + * - `DATABASE_URL` (explicit; always wins) + * - `POSTGRES_URL` / `POSTGRES_URL_NON_POOLING` (Vercel Postgres) + * - `PGHOST`/`PGPORT`/`PGUSER`/`PGPASSWORD`/`PGDATABASE`/`PGSSLMODE` (AWS RDS integration) + * + * Returns `undefined` when no usable connection is configured. + */ +export function resolvePostgresUrlFromEnv(): string | undefined { + const direct = process.env.DATABASE_URL?.trim(); + if (direct) return direct; + + const pooled = process.env.POSTGRES_URL?.trim(); + if (pooled) return pooled; + + const nonPooling = process.env.POSTGRES_URL_NON_POOLING?.trim(); + if (nonPooling) return nonPooling; + + const host = process.env.PGHOST?.trim(); + const database = process.env.PGDATABASE?.trim(); + if (!host || !database) return undefined; + + const user = encodeURIComponent(process.env.PGUSER?.trim() || "postgres"); + const password = process.env.PGPASSWORD ? encodeURIComponent(process.env.PGPASSWORD) : ""; + const port = process.env.PGPORT?.trim() || "5432"; + + const auth = `${user}${password ? `:${password}` : ""}`; + let url = `postgres://${auth}@${host}:${port}/${database}`; + + const sslMode = process.env.PGSSLMODE?.trim(); + if (sslMode && sslMode !== "disable") { + url += "?sslmode=require"; + } + + return url; +} diff --git a/scripts/build-vercel-function.mjs b/scripts/build-vercel-function.mjs new file mode 100644 index 0000000..74522a4 --- /dev/null +++ b/scripts/build-vercel-function.mjs @@ -0,0 +1,69 @@ +#!/usr/bin/env node +/** + * Builds the Vercel serverless function bundle. + * + * The Taskcore control plane runs as a long-lived Express server locally. For + * Vercel we compile the server into a single self-contained ESM module that + * exports a `(req, res)` handler and place it at `api/index.js`, which Vercel + * deploys as a Node.js Function. The static UI is deployed separately from + * `ui/dist` (see `vercel.json`). + * + * Workspace packages (`@taskcore/*`) export TypeScript source, so they must be + * bundled rather than resolved at runtime. npm dependencies stay external so + * Vercel's file tracer can include them from `node_modules`. + */ +import { build } from "esbuild"; +import { existsSync, readFileSync } from "node:fs"; +import { mkdir } from "node:fs/promises"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); +const entry = path.join(repoRoot, "server/src/vercel.ts"); +const outfile = path.join(repoRoot, "api/index.js"); + +if (!existsSync(entry)) { + console.error(`[vercel] entry not found: ${entry}`); + process.exit(1); +} + +await mkdir(path.dirname(outfile), { recursive: true }); + +const serverPkg = JSON.parse( + readFileSync(path.join(repoRoot, "server/package.json"), "utf8"), +) as { version?: string }; + +const nativeExternal = [ + "sharp", + "@img/*", + "embedded-postgres", + "@vercel/node", + "pg-native", + "vite", + "jsdom", +]; + +try { + await build({ + entryPoints: [entry], + outfile, + bundle: true, + platform: "node", + format: "esm", + target: "node20", + external: nativeExternal, + logLevel: "info", + legalComments: "none", + define: { + "process.env.NODE_ENV": JSON.stringify("production"), + "process.env.TASKCORE_SERVER_VERSION": JSON.stringify(serverPkg.version ?? "0.0.0"), + }, + banner: { + js: "/* Taskcore Vercel serverless bundle. Generated by scripts/build-vercel-function.mjs - do not edit. */", + }, + }); + console.log(`[vercel] serverless bundle written to ${outfile}`); +} catch (err) { + console.error("[vercel] failed to build serverless bundle:", err); + process.exit(1); +} diff --git a/server/src/app.ts b/server/src/app.ts index 87235a5..c68ec6b 100644 --- a/server/src/app.ts +++ b/server/src/app.ts @@ -114,6 +114,7 @@ export async function createApp( }, ) { const app = express(); + const pluginsEnabled = process.env.TASKCORE_PLUGINS_ENABLED !== "false"; app.use(express.json({ // Company import/export payloads can inline full portable packages. @@ -337,8 +338,13 @@ export async function createApp( app.use(errorHandler); - jobCoordinator.start(); - scheduler.start(); + if (pluginsEnabled) { + jobCoordinator.start(); + scheduler.start(); + void toolDispatcher.initialize().catch((err) => { + logger.error({ err }, "Failed to initialize plugin tool dispatcher"); + }); + } const feedbackExportTimer = opts.feedbackExportService ? setInterval(() => { void opts.feedbackExportService?.flushPendingFeedbackTraces().catch((err) => { @@ -352,25 +358,24 @@ export async function createApp( logger.error({ err }, "Failed to flush pending feedback exports"); }); } - void toolDispatcher.initialize().catch((err) => { - logger.error({ err }, "Failed to initialize plugin tool dispatcher"); - }); - const devWatcher = opts.uiMode === "vite-dev" + const devWatcher = pluginsEnabled && opts.uiMode === "vite-dev" ? createPluginDevWatcher( lifecycle, async (pluginId) => (await pluginRegistry.getById(pluginId))?.packagePath ?? null, ) : null; - void loader.loadAll().then((result) => { - if (!result) return; - for (const loaded of result.results) { - if (devWatcher && loaded.success && loaded.plugin.packagePath) { - devWatcher.watch(loaded.plugin.id, loaded.plugin.packagePath); + if (pluginsEnabled) { + void loader.loadAll().then((result) => { + if (!result) return; + for (const loaded of result.results) { + if (devWatcher && loaded.success && loaded.plugin.packagePath) { + devWatcher.watch(loaded.plugin.id, loaded.plugin.packagePath); + } } - } - }).catch((err) => { - logger.error({ err }, "Failed to load ready plugins on startup"); - }); + }).catch((err) => { + logger.error({ err }, "Failed to load ready plugins on startup"); + }); + } process.once("exit", () => { if (feedbackExportTimer) clearInterval(feedbackExportTimer); devWatcher?.close(); diff --git a/server/src/config.ts b/server/src/config.ts index a7fd68e..739b5b4 100644 --- a/server/src/config.ts +++ b/server/src/config.ts @@ -12,6 +12,7 @@ import { DEPLOYMENT_MODES, SECRET_PROVIDERS, STORAGE_PROVIDERS, + resolvePostgresUrlFromEnv, type BindMode, type AuthBaseUrlMode, type DeploymentExposure, @@ -296,7 +297,7 @@ export function loadConfig(): Config { authPublicBaseUrl, authDisableSignUp, databaseMode: fileDatabaseMode, - databaseUrl: process.env.DATABASE_URL ?? fileDbUrl, + databaseUrl: resolvePostgresUrlFromEnv() ?? fileDbUrl, embeddedPostgresDataDir: resolveHomeAwarePath( fileConfig?.database.embeddedPostgresDataDir ?? resolveDefaultEmbeddedPostgresDir(), ), diff --git a/server/src/middleware/logger.ts b/server/src/middleware/logger.ts index b8738c7..867236f 100644 --- a/server/src/middleware/logger.ts +++ b/server/src/middleware/logger.ts @@ -1,11 +1,14 @@ import path from "node:path"; -import fs from "node:fs"; import pino from "pino"; import { pinoHttp } from "pino-http"; import { readConfigFile } from "../config-file.js"; import { resolveDefaultLogsDir, resolveHomeAwarePath } from "../home-paths.js"; import { shouldSilenceHttpSuccessLog } from "./http-log-policy.js"; +function isServerlessRuntime(): boolean { + return process.env.VERCEL === "1" || process.env.NOW === "1"; +} + function resolveServerLogDir(): string { const envOverride = process.env.TASKCORE_LOG_DIR?.trim(); if (envOverride) return resolveHomeAwarePath(envOverride); @@ -17,9 +20,6 @@ function resolveServerLogDir(): string { } const logDir = resolveServerLogDir(); -fs.mkdirSync(logDir, { recursive: true }); - -const logFile = path.join(logDir, "server.log"); const sharedOpts = { translateTime: "SYS:HH:MM:ss", @@ -27,23 +27,30 @@ const sharedOpts = { singleLine: true, }; -export const logger = pino({ - level: "debug", - redact: ["req.headers.authorization"], -}, pino.transport({ - targets: [ - { - target: "pino-pretty", - options: { ...sharedOpts, ignore: "pid,hostname,req,res,responseTime", colorize: true, destination: 1 }, - level: "info", - }, - { - target: "pino-pretty", - options: { ...sharedOpts, colorize: false, destination: logFile, mkdir: true }, +// Serverless runtimes (e.g. Vercel Functions) have read-only filesystems and +// cannot run pino worker transports. Log to stdout only in that case. +export const logger = isServerlessRuntime() + ? pino({ + level: process.env.LOG_LEVEL?.trim() || "info", + redact: ["req.headers.authorization"], + }) + : pino({ level: "debug", - }, - ], -})); + redact: ["req.headers.authorization"], + }, pino.transport({ + targets: [ + { + target: "pino-pretty", + options: { ...sharedOpts, ignore: "pid,hostname,req,res,responseTime", colorize: true, destination: 1 }, + level: "info", + }, + { + target: "pino-pretty", + options: { ...sharedOpts, colorize: false, destination: path.join(logDir, "server.log"), mkdir: true }, + level: "debug", + }, + ], + })); export const httpLogger = pinoHttp({ logger, diff --git a/server/src/vercel.ts b/server/src/vercel.ts new file mode 100644 index 0000000..d341bb4 --- /dev/null +++ b/server/src/vercel.ts @@ -0,0 +1,164 @@ +/// +import type { Request as ExpressRequest, RequestHandler, Response as ExpressResponse } from "express"; +import { createDb, type Db } from "@taskcore/db"; +import { createApp } from "./app.js"; +import { loadConfig, type Config } from "./config.js"; +import { logger } from "./middleware/logger.js"; +import { initializeBoardClaimChallenge } from "./board-claim.js"; +import { feedbackService } from "./services/index.js"; +import { createFeedbackTraceShareClientFromConfig } from "./services/feedback-share-client.js"; +import { createStorageServiceFromConfig } from "./storage/index.js"; +import type { BetterAuthSessionResult } from "./auth/better-auth.js"; + +type ExpressApp = Awaited>; +type ExpressRequestHandler = (req: ExpressRequest, res: ExpressResponse) => void; + +function isVercelRuntime(): boolean { + return process.env.VERCEL === "1" || process.env.NOW === "1"; +} + +function applyVercelDefaults(): void { + if (!isVercelRuntime()) return; + const defaults: Record = { + TASKCORE_DEPLOYMENT_MODE: "authenticated", + TASKCORE_DEPLOYMENT_EXPOSURE: "public", + SERVE_UI: "false", + TASKCORE_PLUGINS_ENABLED: "false", + TASKCORE_DB_BACKUP_ENABLED: "false", + HEARTBEAT_SCHEDULER_ENABLED: "false", + TASKCORE_STORAGE_LOCAL_DIR: "/tmp/taskcore-storage", + TASKCORE_LOG_DIR: "/tmp/taskcore-logs", + TASKCORE_PG_MAX_CONNECTIONS: "5", + }; + for (const [key, value] of Object.entries(defaults)) { + if (process.env[key] === undefined) { + process.env[key] = value; + } + } +} + +function assertVercelConfig(config: Config): void { + if (isVercelRuntime() && config.deploymentMode !== "authenticated") { + throw new Error( + "Taskcore on Vercel requires TASKCORE_DEPLOYMENT_MODE=authenticated " + + "(a public, unauthenticated board is not allowed).", + ); + } + if (isVercelRuntime() && config.deploymentExposure !== "public") { + throw new Error( + "Taskcore on Vercel requires TASKCORE_DEPLOYMENT_EXPOSURE=public.", + ); + } + if (config.deploymentMode === "authenticated" && config.deploymentExposure === "public") { + if (config.authBaseUrlMode !== "explicit" || !config.authPublicBaseUrl) { + throw new Error( + "Authenticated public exposure requires auth.baseUrlMode=explicit and a public URL. " + + "Set TASKCORE_AUTH_PUBLIC_BASE_URL (or BETTER_AUTH_URL) to the deployment URL " + + "(e.g. https://taskcore-.vercel.app).", + ); + } + } +} + +async function createAppForServerless(config: Config, db: Db): Promise { + let authReady = config.deploymentMode === "local_trusted"; + let betterAuthHandler: RequestHandler | undefined; + let resolveSession: + | ((req: ExpressRequest) => Promise) + | undefined; + + if (config.deploymentMode === "authenticated") { + const { + createBetterAuthHandler, + createBetterAuthInstance, + deriveAuthTrustedOrigins, + resolveBetterAuthSession, + } = await import("./auth/better-auth.js"); + const derivedTrustedOrigins = deriveAuthTrustedOrigins(config); + const envTrustedOrigins = (process.env.BETTER_AUTH_TRUSTED_ORIGINS ?? "") + .split(",") + .map((value) => value.trim()) + .filter((value) => value.length > 0); + const effectiveTrustedOrigins = Array.from(new Set([...derivedTrustedOrigins, ...envTrustedOrigins])); + logger.info( + { + authBaseUrlMode: config.authBaseUrlMode, + authPublicBaseUrl: config.authPublicBaseUrl ?? null, + trustedOrigins: effectiveTrustedOrigins, + }, + "Authenticated mode auth origin configuration (serverless)", + ); + const auth = createBetterAuthInstance(db, config, effectiveTrustedOrigins); + betterAuthHandler = createBetterAuthHandler(auth); + resolveSession = (req) => resolveBetterAuthSession(auth, req); + await initializeBoardClaimChallenge(db, { deploymentMode: config.deploymentMode }); + authReady = true; + } + + const storageService = createStorageServiceFromConfig(config); + const feedback = feedbackService(db, { + shareClient: createFeedbackTraceShareClientFromConfig(config), + }); + + return createApp(db, { + uiMode: "none", + serverPort: 3000, + storageService, + feedbackExportService: feedback, + deploymentMode: config.deploymentMode, + deploymentExposure: config.deploymentExposure, + allowedHostnames: config.allowedHostnames, + bindHost: config.host, + authReady, + companyDeletionEnabled: config.companyDeletionEnabled, + betterAuthHandler, + resolveSession, + }); +} + +async function boot(): Promise { + applyVercelDefaults(); + + const config = loadConfig(); + if (!config.databaseUrl) { + throw new Error( + "Taskcore on Vercel requires an external PostgreSQL connection. " + + "Set DATABASE_URL (or the Vercel Postgres / RDS environment: POSTGRES_URL or PGHOST/PGDATABASE/PGUSER/PGPASSWORD).", + ); + } + assertVercelConfig(config); + + const maxConnections = Math.max(1, Number(process.env.TASKCORE_PG_MAX_CONNECTIONS) || 10); + const prepareDisabled = process.env.TASKCORE_PG_PREPARE !== undefined + ? process.env.TASKCORE_PG_PREPARE === "true" + : isVercelRuntime(); + const db = createDb(config.databaseUrl, { + max: maxConnections, + ...(prepareDisabled ? { prepare: false } : {}), + }); + + logger.info( + { + deploymentMode: config.deploymentMode, + deploymentExposure: config.deploymentExposure, + storageProvider: config.storageProvider, + databaseConfigured: true, + }, + "Booting Taskcore serverless app", + ); + + return createAppForServerless(config, db); +} + +let appPromise: Promise | null = null; + +export default async function taskcoreVercelHandler( + req: ExpressRequest, + res: ExpressResponse, +): Promise { + const app = await (appPromise ??= boot().catch((err) => { + appPromise = null; + throw err; + })); + (app as unknown as ExpressRequestHandler)(req, res); +} diff --git a/server/src/version.ts b/server/src/version.ts index 39a16a4..d30b829 100644 --- a/server/src/version.ts +++ b/server/src/version.ts @@ -4,7 +4,16 @@ type PackageJson = { version?: string; }; -const require = createRequire(import.meta.url); -const pkg = require("../package.json") as PackageJson; +function loadServerVersion(): string { + const fromEnv = process.env.TASKCORE_SERVER_VERSION; + if (fromEnv) return fromEnv; + try { + const require = createRequire(import.meta.url); + const pkg = require("../package.json") as PackageJson; + return pkg.version ?? "0.0.0"; + } catch { + return "0.0.0"; + } +} -export const serverVersion = pkg.version ?? "0.0.0"; +export const serverVersion = loadServerVersion(); From e2717ce0f5a60062f6782789fa9b62fdb661e1ea Mon Sep 17 00:00:00 2001 From: v0 Date: Fri, 31 Jul 2026 20:37:02 +0000 Subject: [PATCH 3/3] =?UTF-8?q?=F0=9F=9A=80=20feat:=20add=20Vercel=20serve?= =?UTF-8?q?rless=20deployment=20support?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 4 + api/index.js | 220289 --------------------------- doc/DEPLOYMENT-MODES.md | 2 + doc/VERCEL.md | 97 + package.json | 1 + scripts/build-vercel-function.mjs | 42 +- vercel.json | 17 + 7 files changed, 162 insertions(+), 220290 deletions(-) delete mode 100644 api/index.js create mode 100644 doc/VERCEL.md create mode 100644 vercel.json diff --git a/.gitignore b/.gitignore index 507c082..da7e382 100644 --- a/.gitignore +++ b/.gitignore @@ -51,3 +51,7 @@ tests/release-smoke/test-results/ tests/release-smoke/playwright-report/ .superset/ .claude/worktrees/ + +# Vercel +.vercel/ +api/index.js diff --git a/api/index.js b/api/index.js deleted file mode 100644 index 4bdd72c..0000000 --- a/api/index.js +++ /dev/null @@ -1,220289 +0,0 @@ -/* Taskcore Vercel serverless bundle. Generated by scripts/build-vercel-function.mjs - do not edit. */ -var __create = Object.create; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __require = /* @__PURE__ */ ((x5) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x5, { - get: (a5, b6) => (typeof require !== "undefined" ? require : a5)[b6] -}) : x5)(function(x5) { - if (typeof require !== "undefined") return require.apply(this, arguments); - throw Error('Dynamic require of "' + x5 + '" is not supported'); -}); -var __esm = (fn, res) => function __init() { - return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res; -}; -var __commonJS = (cb, mod) => function __require2() { - return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; -}; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except2, desc3) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except2) - __defProp(to, key, { get: () => from[key], enumerable: !(desc3 = __getOwnPropDesc(from, key)) || desc3.enumerable }); - } - return to; -}; -var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( - // If the importer is in node compatibility mode or this is not an ESM - // file that has been converted to a CommonJS file using a Babel- - // compatible transform (i.e. "__esModule" has not been set), then set - // "default" to the CommonJS "module.exports" for node compatibility. - isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, - mod -)); -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// node_modules/.pnpm/postgres@3.4.9/node_modules/postgres/src/query.js -function cachedError(xs) { - if (originCache.has(xs)) - return originCache.get(xs); - const x5 = Error.stackTraceLimit; - Error.stackTraceLimit = 4; - originCache.set(xs, new Error()); - Error.stackTraceLimit = x5; - return originCache.get(xs); -} -var originCache, originStackCache, originError, CLOSE, Query; -var init_query = __esm({ - "node_modules/.pnpm/postgres@3.4.9/node_modules/postgres/src/query.js"() { - originCache = /* @__PURE__ */ new Map(); - originStackCache = /* @__PURE__ */ new Map(); - originError = /* @__PURE__ */ Symbol("OriginError"); - CLOSE = {}; - Query = class extends Promise { - constructor(strings, args, handler, canceller, options = {}) { - let resolve4, reject; - super((a5, b6) => { - resolve4 = a5; - reject = b6; - }); - this.tagged = Array.isArray(strings.raw); - this.strings = strings; - this.args = args; - this.handler = handler; - this.canceller = canceller; - this.options = options; - this.state = null; - this.statement = null; - this.resolve = (x5) => (this.active = false, resolve4(x5)); - this.reject = (x5) => (this.active = false, reject(x5)); - this.active = false; - this.cancelled = null; - this.executed = false; - this.signature = ""; - this[originError] = this.handler.debug ? new Error() : this.tagged && cachedError(this.strings); - } - get origin() { - return (this.handler.debug ? this[originError].stack : this.tagged && originStackCache.has(this.strings) ? originStackCache.get(this.strings) : originStackCache.set(this.strings, this[originError].stack).get(this.strings)) || ""; - } - static get [Symbol.species]() { - return Promise; - } - cancel() { - return this.canceller && (this.canceller(this), this.canceller = null); - } - simple() { - this.options.simple = true; - this.options.prepare = false; - return this; - } - async readable() { - this.simple(); - this.streaming = true; - return this; - } - async writable() { - this.simple(); - this.streaming = true; - return this; - } - cursor(rows = 1, fn) { - this.options.simple = false; - if (typeof rows === "function") { - fn = rows; - rows = 1; - } - this.cursorRows = rows; - if (typeof fn === "function") - return this.cursorFn = fn, this; - let prev; - return { - [Symbol.asyncIterator]: () => ({ - next: () => { - if (this.executed && !this.active) - return { done: true }; - prev && prev(); - const promise2 = new Promise((resolve4, reject) => { - this.cursorFn = (value) => { - resolve4({ value, done: false }); - return new Promise((r5) => prev = r5); - }; - this.resolve = () => (this.active = false, resolve4({ done: true })); - this.reject = (x5) => (this.active = false, reject(x5)); - }); - this.execute(); - return promise2; - }, - return() { - prev && prev(CLOSE); - return { done: true }; - } - }) - }; - } - describe() { - this.options.simple = false; - this.onlyDescribe = this.options.prepare = true; - return this; - } - stream() { - throw new Error(".stream has been renamed to .forEach"); - } - forEach(fn) { - this.forEachFn = fn; - this.handle(); - return this; - } - raw() { - this.isRaw = true; - return this; - } - values() { - this.isRaw = "values"; - return this; - } - async handle() { - !this.executed && (this.executed = true) && await 1 && this.handler(this); - } - execute() { - this.handle(); - return this; - } - then() { - this.handle(); - return super.then.apply(this, arguments); - } - catch() { - this.handle(); - return super.catch.apply(this, arguments); - } - finally() { - this.handle(); - return super.finally.apply(this, arguments); - } - }; - } -}); - -// node_modules/.pnpm/postgres@3.4.9/node_modules/postgres/src/errors.js -function connection(x5, options, socket) { - const { host, port } = socket || options; - const error50 = Object.assign( - new Error("write " + x5 + " " + (options.path || host + ":" + port)), - { - code: x5, - errno: x5, - address: options.path || host - }, - options.path ? {} : { port } - ); - Error.captureStackTrace(error50, connection); - return error50; -} -function postgres(x5) { - const error50 = new PostgresError(x5); - Error.captureStackTrace(error50, postgres); - return error50; -} -function generic(code, message2) { - const error50 = Object.assign(new Error(code + ": " + message2), { code }); - Error.captureStackTrace(error50, generic); - return error50; -} -function notSupported(x5) { - const error50 = Object.assign( - new Error(x5 + " (B) is not supported"), - { - code: "MESSAGE_NOT_SUPPORTED", - name: x5 - } - ); - Error.captureStackTrace(error50, notSupported); - return error50; -} -var PostgresError, Errors; -var init_errors = __esm({ - "node_modules/.pnpm/postgres@3.4.9/node_modules/postgres/src/errors.js"() { - PostgresError = class extends Error { - constructor(x5) { - super(x5.message); - this.name = this.constructor.name; - Object.assign(this, x5); - } - }; - Errors = { - connection, - postgres, - generic, - notSupported - }; - } -}); - -// node_modules/.pnpm/postgres@3.4.9/node_modules/postgres/src/types.js -function handleValue(x5, parameters, types2, options) { - let value = x5 instanceof Parameter ? x5.value : x5; - if (value === void 0) { - x5 instanceof Parameter ? x5.value = options.transform.undefined : value = x5 = options.transform.undefined; - if (value === void 0) - throw Errors.generic("UNDEFINED_VALUE", "Undefined values are not allowed"); - } - return "$" + types2.push( - x5 instanceof Parameter ? (parameters.push(x5.value), x5.array ? x5.array[x5.type || inferType(x5.value)] || x5.type || firstIsString(x5.value) : x5.type) : (parameters.push(x5), inferType(x5)) - ); -} -function stringify(q5, string4, value, parameters, types2, options) { - for (let i5 = 1; i5 < q5.strings.length; i5++) { - string4 += stringifyValue(string4, value, parameters, types2, options) + q5.strings[i5]; - value = q5.args[i5]; - } - return string4; -} -function stringifyValue(string4, value, parameters, types2, o5) { - return value instanceof Builder ? value.build(string4, parameters, types2, o5) : value instanceof Query ? fragment(value, parameters, types2, o5) : value instanceof Identifier ? value.value : value && value[0] instanceof Query ? value.reduce((acc, x5) => acc + " " + fragment(x5, parameters, types2, o5), "") : handleValue(value, parameters, types2, o5); -} -function fragment(q5, parameters, types2, options) { - q5.fragment = true; - return stringify(q5, q5.strings[0], q5.args[0], parameters, types2, options); -} -function valuesBuilder(first, parameters, types2, columns, options) { - return first.map( - (row) => "(" + columns.map( - (column) => stringifyValue("values", row[column], parameters, types2, options) - ).join(",") + ")" - ).join(","); -} -function values(first, rest, parameters, types2, options) { - const multi = Array.isArray(first[0]); - const columns = rest.length ? rest.flat() : Object.keys(multi ? first[0] : first); - return valuesBuilder(multi ? first : [first], parameters, types2, columns, options); -} -function select(first, rest, parameters, types2, options) { - typeof first === "string" && (first = [first].concat(rest)); - if (Array.isArray(first)) - return escapeIdentifiers(first, options); - let value; - const columns = rest.length ? rest.flat() : Object.keys(first); - return columns.map((x5) => { - value = first[x5]; - return (value instanceof Query ? fragment(value, parameters, types2, options) : value instanceof Identifier ? value.value : handleValue(value, parameters, types2, options)) + " as " + escapeIdentifier(options.transform.column.to ? options.transform.column.to(x5) : x5); - }).join(","); -} -function notTagged() { - throw Errors.generic("NOT_TAGGED_CALL", "Query not called as a tagged template literal"); -} -function firstIsString(x5) { - if (Array.isArray(x5)) - return firstIsString(x5[0]); - return typeof x5 === "string" ? 1009 : 0; -} -function typeHandlers(types2) { - return Object.keys(types2).reduce((acc, k5) => { - types2[k5].from && [].concat(types2[k5].from).forEach((x5) => acc.parsers[x5] = types2[k5].parse); - if (types2[k5].serialize) { - acc.serializers[types2[k5].to] = types2[k5].serialize; - types2[k5].from && [].concat(types2[k5].from).forEach((x5) => acc.serializers[x5] = types2[k5].serialize); - } - return acc; - }, { parsers: {}, serializers: {} }); -} -function escapeIdentifiers(xs, { transform: { column } }) { - return xs.map((x5) => escapeIdentifier(column.to ? column.to(x5) : x5)).join(","); -} -function arrayEscape(x5) { - return x5.replace(escapeBackslash, "\\\\").replace(escapeQuote, '\\"'); -} -function arrayParserLoop(s5, x5, parser, typarray) { - const xs = []; - const delimiter = typarray === 1020 ? ";" : ","; - for (; s5.i < x5.length; s5.i++) { - s5.char = x5[s5.i]; - if (s5.quoted) { - if (s5.char === "\\") { - s5.str += x5[++s5.i]; - } else if (s5.char === '"') { - xs.push(parser ? parser(s5.str) : s5.str); - s5.str = ""; - s5.quoted = x5[s5.i + 1] === '"'; - s5.last = s5.i + 2; - } else { - s5.str += s5.char; - } - } else if (s5.char === '"') { - s5.quoted = true; - } else if (s5.char === "{") { - s5.last = ++s5.i; - xs.push(arrayParserLoop(s5, x5, parser, typarray)); - } else if (s5.char === "}") { - s5.quoted = false; - s5.last < s5.i && xs.push(parser ? parser(x5.slice(s5.last, s5.i)) : x5.slice(s5.last, s5.i)); - s5.last = s5.i + 1; - break; - } else if (s5.char === delimiter && s5.p !== "}" && s5.p !== '"') { - xs.push(parser ? parser(x5.slice(s5.last, s5.i)) : x5.slice(s5.last, s5.i)); - s5.last = s5.i + 1; - } - s5.p = s5.char; - } - s5.last < s5.i && xs.push(parser ? parser(x5.slice(s5.last, s5.i + 1)) : x5.slice(s5.last, s5.i + 1)); - return xs; -} -function createJsonTransform(fn) { - return function jsonTransform(x5, column) { - return typeof x5 === "object" && x5 !== null && (column.type === 114 || column.type === 3802) ? Array.isArray(x5) ? x5.map((x6) => jsonTransform(x6, column)) : Object.entries(x5).reduce((acc, [k5, v5]) => Object.assign(acc, { [fn(k5)]: jsonTransform(v5, column) }), {}) : x5; - }; -} -var types, NotTagged, Identifier, Parameter, Builder, defaultHandlers, builders, serializers, parsers, mergeUserTypes, escapeIdentifier, inferType, escapeBackslash, escapeQuote, arraySerializer, arrayParserState, arrayParser, toCamel, toPascal, toKebab, fromCamel, fromPascal, fromKebab, camel, pascal, kebab; -var init_types = __esm({ - "node_modules/.pnpm/postgres@3.4.9/node_modules/postgres/src/types.js"() { - init_query(); - init_errors(); - types = { - string: { - to: 25, - from: null, - // defaults to string - serialize: (x5) => "" + x5 - }, - number: { - to: 0, - from: [21, 23, 26, 700, 701], - serialize: (x5) => "" + x5, - parse: (x5) => +x5 - }, - json: { - to: 114, - from: [114, 3802], - serialize: (x5) => JSON.stringify(x5), - parse: (x5) => JSON.parse(x5) - }, - boolean: { - to: 16, - from: 16, - serialize: (x5) => x5 === true ? "t" : "f", - parse: (x5) => x5 === "t" - }, - date: { - to: 1184, - from: [1082, 1114, 1184], - serialize: (x5) => (x5 instanceof Date ? x5 : new Date(x5)).toISOString(), - parse: (x5) => new Date(x5) - }, - bytea: { - to: 17, - from: 17, - serialize: (x5) => "\\x" + Buffer.from(x5).toString("hex"), - parse: (x5) => Buffer.from(x5.slice(2), "hex") - } - }; - NotTagged = class { - then() { - notTagged(); - } - catch() { - notTagged(); - } - finally() { - notTagged(); - } - }; - Identifier = class extends NotTagged { - constructor(value) { - super(); - this.value = escapeIdentifier(value); - } - }; - Parameter = class extends NotTagged { - constructor(value, type, array2) { - super(); - this.value = value; - this.type = type; - this.array = array2; - } - }; - Builder = class extends NotTagged { - constructor(first, rest) { - super(); - this.first = first; - this.rest = rest; - } - build(before, parameters, types2, options) { - const keyword = builders.map(([x5, fn]) => ({ fn, i: before.search(x5) })).sort((a5, b6) => a5.i - b6.i).pop(); - return keyword.i === -1 ? escapeIdentifiers(this.first, options) : keyword.fn(this.first, this.rest, parameters, types2, options); - } - }; - defaultHandlers = typeHandlers(types); - builders = Object.entries({ - values, - in: (...xs) => { - const x5 = values(...xs); - return x5 === "()" ? "(null)" : x5; - }, - select, - as: select, - returning: select, - "\\(": select, - update(first, rest, parameters, types2, options) { - return (rest.length ? rest.flat() : Object.keys(first)).map( - (x5) => escapeIdentifier(options.transform.column.to ? options.transform.column.to(x5) : x5) + "=" + stringifyValue("values", first[x5], parameters, types2, options) - ); - }, - insert(first, rest, parameters, types2, options) { - const columns = rest.length ? rest.flat() : Object.keys(Array.isArray(first) ? first[0] : first); - return "(" + escapeIdentifiers(columns, options) + ")values" + valuesBuilder(Array.isArray(first) ? first : [first], parameters, types2, columns, options); - } - }).map(([x5, fn]) => [new RegExp("((?:^|[\\s(])" + x5 + "(?:$|[\\s(]))(?![\\s\\S]*\\1)", "i"), fn]); - serializers = defaultHandlers.serializers; - parsers = defaultHandlers.parsers; - mergeUserTypes = function(types2) { - const user = typeHandlers(types2 || {}); - return { - serializers: Object.assign({}, serializers, user.serializers), - parsers: Object.assign({}, parsers, user.parsers) - }; - }; - escapeIdentifier = function escape2(str) { - return '"' + str.replace(/"/g, '""').replace(/\./g, '"."') + '"'; - }; - inferType = function inferType2(x5) { - return x5 instanceof Parameter ? x5.type : x5 instanceof Date ? 1184 : x5 instanceof Uint8Array ? 17 : x5 === true || x5 === false ? 16 : typeof x5 === "bigint" ? 20 : Array.isArray(x5) ? inferType2(x5[0]) : 0; - }; - escapeBackslash = /\\/g; - escapeQuote = /"/g; - arraySerializer = function arraySerializer2(xs, serializer, options, typarray) { - if (Array.isArray(xs) === false) - return xs; - if (!xs.length) - return "{}"; - const first = xs[0]; - const delimiter = typarray === 1020 ? ";" : ","; - if (Array.isArray(first) && !first.type) - return "{" + xs.map((x5) => arraySerializer2(x5, serializer, options, typarray)).join(delimiter) + "}"; - return "{" + xs.map((x5) => { - if (x5 === void 0) { - x5 = options.transform.undefined; - if (x5 === void 0) - throw Errors.generic("UNDEFINED_VALUE", "Undefined values are not allowed"); - } - return x5 === null ? "null" : '"' + arrayEscape(serializer ? serializer(x5.type ? x5.value : x5) : "" + x5) + '"'; - }).join(delimiter) + "}"; - }; - arrayParserState = { - i: 0, - char: null, - str: "", - quoted: false, - last: 0 - }; - arrayParser = function arrayParser2(x5, parser, typarray) { - arrayParserState.i = arrayParserState.last = 0; - return arrayParserLoop(arrayParserState, x5, parser, typarray); - }; - toCamel = (x5) => { - let str = x5[0]; - for (let i5 = 1; i5 < x5.length; i5++) - str += x5[i5] === "_" ? x5[++i5].toUpperCase() : x5[i5]; - return str; - }; - toPascal = (x5) => { - let str = x5[0].toUpperCase(); - for (let i5 = 1; i5 < x5.length; i5++) - str += x5[i5] === "_" ? x5[++i5].toUpperCase() : x5[i5]; - return str; - }; - toKebab = (x5) => x5.replace(/_/g, "-"); - fromCamel = (x5) => x5.replace(/([A-Z])/g, "_$1").toLowerCase(); - fromPascal = (x5) => (x5.slice(0, 1) + x5.slice(1).replace(/([A-Z])/g, "_$1")).toLowerCase(); - fromKebab = (x5) => x5.replace(/-/g, "_"); - toCamel.column = { from: toCamel }; - toCamel.value = { from: createJsonTransform(toCamel) }; - fromCamel.column = { to: fromCamel }; - camel = { ...toCamel }; - camel.column.to = fromCamel; - toPascal.column = { from: toPascal }; - toPascal.value = { from: createJsonTransform(toPascal) }; - fromPascal.column = { to: fromPascal }; - pascal = { ...toPascal }; - pascal.column.to = fromPascal; - toKebab.column = { from: toKebab }; - toKebab.value = { from: createJsonTransform(toKebab) }; - fromKebab.column = { to: fromKebab }; - kebab = { ...toKebab }; - kebab.column.to = fromKebab; - } -}); - -// node_modules/.pnpm/postgres@3.4.9/node_modules/postgres/src/result.js -var Result; -var init_result = __esm({ - "node_modules/.pnpm/postgres@3.4.9/node_modules/postgres/src/result.js"() { - Result = class extends Array { - constructor() { - super(); - Object.defineProperties(this, { - count: { value: null, writable: true }, - state: { value: null, writable: true }, - command: { value: null, writable: true }, - columns: { value: null, writable: true }, - statement: { value: null, writable: true } - }); - } - static get [Symbol.species]() { - return Array; - } - }; - } -}); - -// node_modules/.pnpm/postgres@3.4.9/node_modules/postgres/src/queue.js -function Queue(initial = []) { - let xs = initial.slice(); - let index2 = 0; - return { - get length() { - return xs.length - index2; - }, - remove: (x5) => { - const index3 = xs.indexOf(x5); - return index3 === -1 ? null : (xs.splice(index3, 1), x5); - }, - push: (x5) => (xs.push(x5), x5), - shift: () => { - const out = xs[index2++]; - if (index2 === xs.length) { - index2 = 0; - xs = []; - } else { - xs[index2 - 1] = void 0; - } - return out; - } - }; -} -var queue_default; -var init_queue = __esm({ - "node_modules/.pnpm/postgres@3.4.9/node_modules/postgres/src/queue.js"() { - queue_default = Queue; - } -}); - -// node_modules/.pnpm/postgres@3.4.9/node_modules/postgres/src/bytes.js -function fit(x5) { - if (buffer.length - b.i < x5) { - const prev = buffer, length = prev.length; - buffer = Buffer.allocUnsafe(length + (length >> 1) + x5); - prev.copy(buffer); - } -} -function reset() { - b.i = 0; - return b; -} -var size, buffer, messages, b, bytes_default; -var init_bytes = __esm({ - "node_modules/.pnpm/postgres@3.4.9/node_modules/postgres/src/bytes.js"() { - size = 256; - buffer = Buffer.allocUnsafe(size); - messages = "BCcDdEFfHPpQSX".split("").reduce((acc, x5) => { - const v5 = x5.charCodeAt(0); - acc[x5] = () => { - buffer[0] = v5; - b.i = 5; - return b; - }; - return acc; - }, {}); - b = Object.assign(reset, messages, { - N: String.fromCharCode(0), - i: 0, - inc(x5) { - b.i += x5; - return b; - }, - str(x5) { - const length = Buffer.byteLength(x5); - fit(length); - b.i += buffer.write(x5, b.i, length, "utf8"); - return b; - }, - i16(x5) { - fit(2); - buffer.writeUInt16BE(x5, b.i); - b.i += 2; - return b; - }, - i32(x5, i5) { - if (i5 || i5 === 0) { - buffer.writeUInt32BE(x5, i5); - return b; - } - fit(4); - buffer.writeUInt32BE(x5, b.i); - b.i += 4; - return b; - }, - z(x5) { - fit(x5); - buffer.fill(0, b.i, b.i + x5); - b.i += x5; - return b; - }, - raw(x5) { - buffer = Buffer.concat([buffer.subarray(0, b.i), x5]); - b.i = buffer.length; - return b; - }, - end(at = 1) { - buffer.writeUInt32BE(b.i - at, at); - const out = buffer.subarray(0, b.i); - b.i = 0; - buffer = Buffer.allocUnsafe(size); - return out; - } - }); - bytes_default = b; - } -}); - -// node_modules/.pnpm/postgres@3.4.9/node_modules/postgres/src/connection.js -import net from "net"; -import tls from "tls"; -import crypto2 from "crypto"; -import Stream from "stream"; -import { performance as performance2 } from "perf_hooks"; -function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose = noop } = {}) { - const { - sslnegotiation, - ssl, - max, - user, - host, - port, - database, - parsers: parsers2, - transform: transform3, - onnotice, - onnotify, - onparameter, - max_pipeline, - keep_alive, - backoff: backoff2, - target_session_attrs - } = options; - const sent = queue_default(), id = uid++, backend = { pid: null, secret: null }, idleTimer = timer(end, options.idle_timeout), lifeTimer = timer(end, options.max_lifetime), connectTimer = timer(connectTimedOut, options.connect_timeout); - let socket = null, cancelMessage, errorResponse = null, result = new Result(), incoming = Buffer.alloc(0), needsTypes = options.fetch_types, backendParameters = {}, statements = {}, statementId = Math.random().toString(36).slice(2), statementCount = 1, closedTime = 0, remaining = 0, hostIndex = 0, retries = 0, length = 0, delay3 = 0, rows = 0, serverSignature = null, nextWriteTimer = null, terminated = false, incomings = null, results = null, initial = null, ending = null, stream = null, chunk = null, ended = null, nonce = null, query = null, final = null; - const connection2 = { - queue: queues.closed, - idleTimer, - connect(query2) { - initial = query2; - reconnect(); - }, - terminate, - execute: execute11, - cancel, - end, - count: 0, - id - }; - queues.closed && queues.closed.push(connection2); - return connection2; - async function createSocket() { - let x5; - try { - x5 = options.socket ? await Promise.resolve(options.socket(options)) : new net.Socket(); - } catch (e5) { - error50(e5); - return; - } - x5.on("error", error50); - x5.on("close", closed); - x5.on("drain", drain); - return x5; - } - async function cancel({ pid, secret }, resolve4, reject) { - try { - cancelMessage = bytes_default().i32(16).i32(80877102).i32(pid).i32(secret).end(16); - await connect(); - socket.once("error", reject); - socket.once("close", resolve4); - } catch (error51) { - reject(error51); - } - } - function execute11(q5) { - if (terminated) - return queryError(q5, Errors.connection("CONNECTION_DESTROYED", options)); - if (stream) - return queryError(q5, Errors.generic("COPY_IN_PROGRESS", "You cannot execute queries during copy")); - if (q5.cancelled) - return; - try { - q5.state = backend; - query ? sent.push(q5) : (query = q5, query.active = true); - build(q5); - return write(toBuffer(q5)) && !q5.describeFirst && !q5.cursorFn && sent.length < max_pipeline && (!q5.options.onexecute || q5.options.onexecute(connection2)); - } catch (error51) { - sent.length === 0 && write(Sync); - errored(error51); - return true; - } - } - function toBuffer(q5) { - if (q5.parameters.length >= 65534) - throw Errors.generic("MAX_PARAMETERS_EXCEEDED", "Max number of parameters (65534) exceeded"); - return q5.options.simple ? bytes_default().Q().str(q5.statement.string + bytes_default.N).end() : q5.describeFirst ? Buffer.concat([describe3(q5), Flush]) : q5.prepare ? q5.prepared ? prepared(q5) : Buffer.concat([describe3(q5), prepared(q5)]) : unnamed(q5); - } - function describe3(q5) { - return Buffer.concat([ - Parse(q5.statement.string, q5.parameters, q5.statement.types, q5.statement.name), - Describe("S", q5.statement.name) - ]); - } - function prepared(q5) { - return Buffer.concat([ - Bind(q5.parameters, q5.statement.types, q5.statement.name, q5.cursorName), - q5.cursorFn ? Execute("", q5.cursorRows) : ExecuteUnnamed - ]); - } - function unnamed(q5) { - return Buffer.concat([ - Parse(q5.statement.string, q5.parameters, q5.statement.types), - DescribeUnnamed, - prepared(q5) - ]); - } - function build(q5) { - const parameters = [], types2 = []; - const string4 = stringify(q5, q5.strings[0], q5.args[0], parameters, types2, options); - !q5.tagged && q5.args.forEach((x5) => handleValue(x5, parameters, types2, options)); - q5.prepare = options.prepare && ("prepare" in q5.options ? q5.options.prepare : true); - q5.string = string4; - q5.signature = q5.prepare && types2 + string4; - q5.onlyDescribe && delete statements[q5.signature]; - q5.parameters = q5.parameters || parameters; - q5.prepared = q5.prepare && q5.signature in statements; - q5.describeFirst = q5.onlyDescribe || parameters.length && !q5.prepared; - q5.statement = q5.prepared ? statements[q5.signature] : { string: string4, types: types2, name: q5.prepare ? statementId + statementCount++ : "" }; - typeof options.debug === "function" && options.debug(id, string4, parameters, types2); - } - function write(x5, fn) { - chunk = chunk ? Buffer.concat([chunk, x5]) : Buffer.from(x5); - if (fn || chunk.length >= 1024) - return nextWrite(fn); - nextWriteTimer === null && (nextWriteTimer = setImmediate(nextWrite)); - return true; - } - function nextWrite(fn) { - const x5 = socket.write(chunk, fn); - nextWriteTimer !== null && clearImmediate(nextWriteTimer); - chunk = nextWriteTimer = null; - return x5; - } - function connectTimedOut() { - errored(Errors.connection("CONNECT_TIMEOUT", options, socket)); - socket.destroy(); - } - async function secure() { - if (sslnegotiation !== "direct") { - write(SSLRequest); - const canSSL = await new Promise((r5) => socket.once("data", (x5) => r5(x5[0] === 83))); - if (!canSSL && ssl === "prefer") - return connected(); - } - const options2 = { - socket, - servername: net.isIP(socket.host) ? void 0 : socket.host - }; - if (sslnegotiation === "direct") - options2.ALPNProtocols = ["postgresql"]; - if (ssl === "require" || ssl === "allow" || ssl === "prefer") - options2.rejectUnauthorized = false; - else if (typeof ssl === "object") - Object.assign(options2, ssl); - socket.removeAllListeners(); - socket = tls.connect(options2); - socket.on("secureConnect", connected); - socket.on("error", error50); - socket.on("close", closed); - socket.on("drain", drain); - } - function drain() { - !query && onopen(connection2); - } - function data2(x5) { - if (incomings) { - incomings.push(x5); - remaining -= x5.length; - if (remaining > 0) - return; - } - incoming = incomings ? Buffer.concat(incomings, length - remaining) : incoming.length === 0 ? x5 : Buffer.concat([incoming, x5], incoming.length + x5.length); - while (incoming.length > 4) { - length = incoming.readUInt32BE(1); - if (length >= incoming.length) { - remaining = length - incoming.length; - incomings = [incoming]; - break; - } - try { - handle(incoming.subarray(0, length + 1)); - } catch (e5) { - query && (query.cursorFn || query.describeFirst) && write(Sync); - errored(e5); - } - incoming = incoming.subarray(length + 1); - remaining = 0; - incomings = null; - } - } - async function connect() { - terminated = false; - backendParameters = {}; - socket || (socket = await createSocket()); - if (!socket) - return; - connectTimer.start(); - if (options.socket) - return ssl ? secure() : connected(); - socket.on("connect", ssl ? secure : connected); - if (options.path) - return socket.connect(options.path); - socket.ssl = ssl; - socket.connect(port[hostIndex], host[hostIndex]); - socket.host = host[hostIndex]; - socket.port = port[hostIndex]; - hostIndex = (hostIndex + 1) % port.length; - } - function reconnect() { - setTimeout(connect, closedTime ? Math.max(0, closedTime + delay3 - performance2.now()) : 0); - } - function connected() { - try { - statements = {}; - needsTypes = options.fetch_types; - statementId = Math.random().toString(36).slice(2); - statementCount = 1; - lifeTimer.start(); - socket.on("data", data2); - keep_alive && socket.setKeepAlive && socket.setKeepAlive(true, 1e3 * keep_alive); - const s5 = StartupMessage(); - write(s5); - } catch (err) { - error50(err); - } - } - function error50(err) { - if (connection2.queue === queues.connecting && options.host[retries + 1]) - return; - errored(err); - while (sent.length) - queryError(sent.shift(), err); - } - function errored(err) { - stream && (stream.destroy(err), stream = null); - query && queryError(query, err); - initial && (queryError(initial, err), initial = null); - } - function queryError(query2, err) { - if (query2.reserve) - return query2.reject(err); - if (!err || typeof err !== "object") - err = new Error(err); - "query" in err || "parameters" in err || Object.defineProperties(err, { - stack: { value: err.stack + query2.origin.replace(/.*\n/, "\n"), enumerable: options.debug }, - query: { value: query2.string, enumerable: options.debug }, - parameters: { value: query2.parameters, enumerable: options.debug }, - args: { value: query2.args, enumerable: options.debug }, - types: { value: query2.statement && query2.statement.types, enumerable: options.debug } - }); - query2.reject(err); - } - function end() { - return ending || (!connection2.reserved && onend(connection2), !connection2.reserved && !initial && !query && sent.length === 0 ? (terminate(), new Promise((r5) => socket && socket.readyState !== "closed" ? socket.once("close", r5) : r5())) : ending = new Promise((r5) => ended = r5)); - } - function terminate() { - terminated = true; - if (stream || query || initial || sent.length) - error50(Errors.connection("CONNECTION_DESTROYED", options)); - clearImmediate(nextWriteTimer); - if (socket) { - socket.removeListener("data", data2); - socket.removeListener("connect", connected); - socket.readyState === "open" && socket.end(bytes_default().X().end()); - } - ended && (ended(), ending = ended = null); - } - async function closed(hadError) { - incoming = Buffer.alloc(0); - remaining = 0; - incomings = null; - clearImmediate(nextWriteTimer); - socket.removeListener("data", data2); - socket.removeListener("connect", connected); - idleTimer.cancel(); - lifeTimer.cancel(); - connectTimer.cancel(); - socket.removeAllListeners(); - socket = null; - if (initial) - return reconnect(); - !hadError && (query || sent.length) && error50(Errors.connection("CONNECTION_CLOSED", options, socket)); - closedTime = performance2.now(); - hadError && options.shared.retries++; - delay3 = (typeof backoff2 === "function" ? backoff2(options.shared.retries) : backoff2) * 1e3; - onclose(connection2, Errors.connection("CONNECTION_CLOSED", options, socket)); - } - function handle(xs, x5 = xs[0]) { - (x5 === 68 ? DataRow : ( - // D - x5 === 100 ? CopyData : ( - // d - x5 === 65 ? NotificationResponse : ( - // A - x5 === 83 ? ParameterStatus : ( - // S - x5 === 90 ? ReadyForQuery : ( - // Z - x5 === 67 ? CommandComplete : ( - // C - x5 === 50 ? BindComplete : ( - // 2 - x5 === 49 ? ParseComplete : ( - // 1 - x5 === 116 ? ParameterDescription : ( - // t - x5 === 84 ? RowDescription : ( - // T - x5 === 82 ? Authentication : ( - // R - x5 === 110 ? NoData : ( - // n - x5 === 75 ? BackendKeyData : ( - // K - x5 === 69 ? ErrorResponse : ( - // E - x5 === 115 ? PortalSuspended : ( - // s - x5 === 51 ? CloseComplete : ( - // 3 - x5 === 71 ? CopyInResponse : ( - // G - x5 === 78 ? NoticeResponse : ( - // N - x5 === 72 ? CopyOutResponse : ( - // H - x5 === 99 ? CopyDone : ( - // c - x5 === 73 ? EmptyQueryResponse : ( - // I - x5 === 86 ? FunctionCallResponse : ( - // V - x5 === 118 ? NegotiateProtocolVersion : ( - // v - x5 === 87 ? CopyBothResponse : ( - // W - /* c8 ignore next */ - UnknownMessage - ) - ) - ) - ) - ) - ) - ) - ) - ) - ) - ) - ) - ) - ) - ) - ) - ) - ) - ) - ) - ) - ) - ) - ))(xs); - } - function DataRow(x5) { - let index2 = 7; - let length2; - let column; - let value; - const row = query.isRaw ? new Array(query.statement.columns.length) : {}; - for (let i5 = 0; i5 < query.statement.columns.length; i5++) { - column = query.statement.columns[i5]; - length2 = x5.readInt32BE(index2); - index2 += 4; - value = length2 === -1 ? null : query.isRaw === true ? x5.subarray(index2, index2 += length2) : column.parser === void 0 ? x5.toString("utf8", index2, index2 += length2) : column.parser.array === true ? column.parser(x5.toString("utf8", index2 + 1, index2 += length2)) : column.parser(x5.toString("utf8", index2, index2 += length2)); - query.isRaw ? row[i5] = query.isRaw === true ? value : transform3.value.from ? transform3.value.from(value, column) : value : row[column.name] = transform3.value.from ? transform3.value.from(value, column) : value; - } - query.forEachFn ? query.forEachFn(transform3.row.from ? transform3.row.from(row) : row, result) : result[rows++] = transform3.row.from ? transform3.row.from(row) : row; - } - function ParameterStatus(x5) { - const [k5, v5] = x5.toString("utf8", 5, x5.length - 1).split(bytes_default.N); - backendParameters[k5] = v5; - if (options.parameters[k5] !== v5) { - options.parameters[k5] = v5; - onparameter && onparameter(k5, v5); - } - } - function ReadyForQuery(x5) { - if (query) { - if (errorResponse) { - query.retried ? errored(query.retried) : query.prepared && retryRoutines.has(errorResponse.routine) ? retry(query, errorResponse) : errored(errorResponse); - } else { - query.resolve(results || result); - } - } else if (errorResponse) { - errored(errorResponse); - } - query = results = errorResponse = null; - result = new Result(); - connectTimer.cancel(); - if (initial) { - if (target_session_attrs) { - if (!backendParameters.in_hot_standby || !backendParameters.default_transaction_read_only) - return fetchState(); - else if (tryNext(target_session_attrs, backendParameters)) - return terminate(); - } - if (needsTypes) { - initial.reserve && (initial = null); - return fetchArrayTypes(); - } - initial && !initial.reserve && execute11(initial); - options.shared.retries = retries = 0; - initial = null; - return; - } - while (sent.length && (query = sent.shift()) && (query.active = true, query.cancelled)) - Connection(options).cancel(query.state, query.cancelled.resolve, query.cancelled.reject); - if (query) - return; - connection2.reserved ? !connection2.reserved.release && x5[5] === 73 ? ending ? terminate() : (connection2.reserved = null, onopen(connection2)) : connection2.reserved() : ending ? terminate() : onopen(connection2); - } - function CommandComplete(x5) { - rows = 0; - for (let i5 = x5.length - 1; i5 > 0; i5--) { - if (x5[i5] === 32 && x5[i5 + 1] < 58 && result.count === null) - result.count = +x5.toString("utf8", i5 + 1, x5.length - 1); - if (x5[i5 - 1] >= 65) { - result.command = x5.toString("utf8", 5, i5); - result.state = backend; - break; - } - } - final && (final(), final = null); - if (result.command === "BEGIN" && max !== 1 && !connection2.reserved) - return errored(Errors.generic("UNSAFE_TRANSACTION", "Only use sql.begin, sql.reserved or max: 1")); - if (query.options.simple) - return BindComplete(); - if (query.cursorFn) { - result.count && query.cursorFn(result); - write(Sync); - } - } - function ParseComplete() { - query.parsing = false; - } - function BindComplete() { - !result.statement && (result.statement = query.statement); - result.columns = query.statement.columns; - } - function ParameterDescription(x5) { - const length2 = x5.readUInt16BE(5); - for (let i5 = 0; i5 < length2; ++i5) - !query.statement.types[i5] && (query.statement.types[i5] = x5.readUInt32BE(7 + i5 * 4)); - query.prepare && (statements[query.signature] = query.statement); - query.describeFirst && !query.onlyDescribe && (write(prepared(query)), query.describeFirst = false); - } - function RowDescription(x5) { - if (result.command) { - results = results || [result]; - results.push(result = new Result()); - result.count = null; - query.statement.columns = null; - } - const length2 = x5.readUInt16BE(5); - let index2 = 7; - let start; - query.statement.columns = Array(length2); - for (let i5 = 0; i5 < length2; ++i5) { - start = index2; - while (x5[index2++] !== 0) ; - const table = x5.readUInt32BE(index2); - const number4 = x5.readUInt16BE(index2 + 4); - const type = x5.readUInt32BE(index2 + 6); - query.statement.columns[i5] = { - name: transform3.column.from ? transform3.column.from(x5.toString("utf8", start, index2 - 1)) : x5.toString("utf8", start, index2 - 1), - parser: parsers2[type], - table, - number: number4, - type - }; - index2 += 18; - } - result.statement = query.statement; - if (query.onlyDescribe) - return query.resolve(query.statement), write(Sync); - } - async function Authentication(x5, type = x5.readUInt32BE(5)) { - (type === 3 ? AuthenticationCleartextPassword : type === 5 ? AuthenticationMD5Password : type === 10 ? SASL : type === 11 ? SASLContinue : type === 12 ? SASLFinal : type !== 0 ? UnknownAuth : noop)(x5, type); - } - async function AuthenticationCleartextPassword() { - const payload2 = await Pass(); - write( - bytes_default().p().str(payload2).z(1).end() - ); - } - async function AuthenticationMD5Password(x5) { - const payload2 = "md5" + await md5( - Buffer.concat([ - Buffer.from(await md5(await Pass() + user)), - x5.subarray(9) - ]) - ); - write( - bytes_default().p().str(payload2).z(1).end() - ); - } - async function SASL() { - nonce = (await crypto2.randomBytes(18)).toString("base64"); - bytes_default().p().str("SCRAM-SHA-256" + bytes_default.N); - const i5 = bytes_default.i; - write(bytes_default.inc(4).str("n,,n=*,r=" + nonce).i32(bytes_default.i - i5 - 4, i5).end()); - } - async function SASLContinue(x5) { - const res = x5.toString("utf8", 9).split(",").reduce((acc, x6) => (acc[x6[0]] = x6.slice(2), acc), {}); - const saltedPassword = await crypto2.pbkdf2Sync( - await Pass(), - Buffer.from(res.s, "base64"), - parseInt(res.i), - 32, - "sha256" - ); - const clientKey = await hmac(saltedPassword, "Client Key"); - const auth = "n=*,r=" + nonce + ",r=" + res.r + ",s=" + res.s + ",i=" + res.i + ",c=biws,r=" + res.r; - serverSignature = (await hmac(await hmac(saltedPassword, "Server Key"), auth)).toString("base64"); - const payload2 = "c=biws,r=" + res.r + ",p=" + xor( - clientKey, - Buffer.from(await hmac(await sha256(clientKey), auth)) - ).toString("base64"); - write( - bytes_default().p().str(payload2).end() - ); - } - function SASLFinal(x5) { - if (x5.toString("utf8", 9).split(bytes_default.N, 1)[0].slice(2) === serverSignature) - return; - errored(Errors.generic("SASL_SIGNATURE_MISMATCH", "The server did not return the correct signature")); - socket.destroy(); - } - function Pass() { - return Promise.resolve( - typeof options.pass === "function" ? options.pass() : options.pass - ); - } - function NoData() { - result.statement = query.statement; - result.statement.columns = []; - if (query.onlyDescribe) - return query.resolve(query.statement), write(Sync); - } - function BackendKeyData(x5) { - backend.pid = x5.readUInt32BE(5); - backend.secret = x5.readUInt32BE(9); - } - async function fetchArrayTypes() { - needsTypes = false; - const types2 = await new Query([` - select b.oid, b.typarray - from pg_catalog.pg_type a - left join pg_catalog.pg_type b on b.oid = a.typelem - where a.typcategory = 'A' - group by b.oid, b.typarray - order by b.oid - `], [], execute11); - types2.forEach(({ oid, typarray }) => addArrayType(oid, typarray)); - } - function addArrayType(oid, typarray) { - if (!!options.parsers[typarray] && !!options.serializers[typarray]) return; - const parser = options.parsers[oid]; - options.shared.typeArrayMap[oid] = typarray; - options.parsers[typarray] = (xs) => arrayParser(xs, parser, typarray); - options.parsers[typarray].array = true; - options.serializers[typarray] = (xs) => arraySerializer(xs, options.serializers[oid], options, typarray); - } - function tryNext(x5, xs) { - return x5 === "read-write" && xs.default_transaction_read_only === "on" || x5 === "read-only" && xs.default_transaction_read_only === "off" || x5 === "primary" && xs.in_hot_standby === "on" || x5 === "standby" && xs.in_hot_standby === "off" || x5 === "prefer-standby" && xs.in_hot_standby === "off" && options.host[retries]; - } - function fetchState() { - const query2 = new Query([` - show transaction_read_only; - select pg_catalog.pg_is_in_recovery() - `], [], execute11, null, { simple: true }); - query2.resolve = ([[a5], [b6]]) => { - backendParameters.default_transaction_read_only = a5.transaction_read_only; - backendParameters.in_hot_standby = b6.pg_is_in_recovery ? "on" : "off"; - }; - query2.execute(); - } - function ErrorResponse(x5) { - if (query) { - (query.cursorFn || query.describeFirst) && write(Sync); - errorResponse = Errors.postgres(parseError(x5)); - } else { - errored(Errors.postgres(parseError(x5))); - } - } - function retry(q5, error51) { - delete statements[q5.signature]; - q5.retried = error51; - execute11(q5); - } - function NotificationResponse(x5) { - if (!onnotify) - return; - let index2 = 9; - while (x5[index2++] !== 0) ; - onnotify( - x5.toString("utf8", 9, index2 - 1), - x5.toString("utf8", index2, x5.length - 1) - ); - } - async function PortalSuspended() { - try { - const x5 = await Promise.resolve(query.cursorFn(result)); - rows = 0; - x5 === CLOSE ? write(Close(query.portal)) : (result = new Result(), write(Execute("", query.cursorRows))); - } catch (err) { - write(Sync); - query.reject(err); - } - } - function CloseComplete() { - result.count && query.cursorFn(result); - query.resolve(result); - } - function CopyInResponse() { - stream = new Stream.Writable({ - autoDestroy: true, - write(chunk2, encoding, callback) { - socket.write(bytes_default().d().raw(chunk2).end(), callback); - }, - destroy(error51, callback) { - callback(error51); - socket.write(bytes_default().f().str(error51 + bytes_default.N).end()); - stream = null; - }, - final(callback) { - socket.write(bytes_default().c().end()); - final = callback; - stream = null; - } - }); - query.resolve(stream); - } - function CopyOutResponse() { - stream = new Stream.Readable({ - read() { - socket.resume(); - } - }); - query.resolve(stream); - } - function CopyBothResponse() { - stream = new Stream.Duplex({ - autoDestroy: true, - read() { - socket.resume(); - }, - /* c8 ignore next 11 */ - write(chunk2, encoding, callback) { - socket.write(bytes_default().d().raw(chunk2).end(), callback); - }, - destroy(error51, callback) { - callback(error51); - socket.write(bytes_default().f().str(error51 + bytes_default.N).end()); - stream = null; - }, - final(callback) { - socket.write(bytes_default().c().end()); - final = callback; - } - }); - query.resolve(stream); - } - function CopyData(x5) { - stream && (stream.push(x5.subarray(5)) || socket.pause()); - } - function CopyDone() { - stream && stream.push(null); - stream = null; - } - function NoticeResponse(x5) { - onnotice ? onnotice(parseError(x5)) : console.log(parseError(x5)); - } - function EmptyQueryResponse() { - } - function FunctionCallResponse() { - errored(Errors.notSupported("FunctionCallResponse")); - } - function NegotiateProtocolVersion() { - errored(Errors.notSupported("NegotiateProtocolVersion")); - } - function UnknownMessage(x5) { - console.error("Postgres.js : Unknown Message:", x5[0]); - } - function UnknownAuth(x5, type) { - console.error("Postgres.js : Unknown Auth:", type); - } - function Bind(parameters, types2, statement = "", portal = "") { - let prev, type; - bytes_default().B().str(portal + bytes_default.N).str(statement + bytes_default.N).i16(0).i16(parameters.length); - parameters.forEach((x5, i5) => { - if (x5 === null) - return bytes_default.i32(4294967295); - type = types2[i5]; - parameters[i5] = x5 = type in options.serializers ? options.serializers[type](x5) : "" + x5; - prev = bytes_default.i; - bytes_default.inc(4).str(x5).i32(bytes_default.i - prev - 4, prev); - }); - bytes_default.i16(0); - return bytes_default.end(); - } - function Parse(str, parameters, types2, name = "") { - bytes_default().P().str(name + bytes_default.N).str(str + bytes_default.N).i16(parameters.length); - parameters.forEach((x5, i5) => bytes_default.i32(types2[i5] || 0)); - return bytes_default.end(); - } - function Describe(x5, name = "") { - return bytes_default().D().str(x5).str(name + bytes_default.N).end(); - } - function Execute(portal = "", rows2 = 0) { - return Buffer.concat([ - bytes_default().E().str(portal + bytes_default.N).i32(rows2).end(), - Flush - ]); - } - function Close(portal = "") { - return Buffer.concat([ - bytes_default().C().str("P").str(portal + bytes_default.N).end(), - bytes_default().S().end() - ]); - } - function StartupMessage() { - return cancelMessage || bytes_default().inc(4).i16(3).z(2).str( - Object.entries(Object.assign( - { - user, - database, - client_encoding: "UTF8" - }, - options.connection - )).filter(([, v5]) => v5).map(([k5, v5]) => k5 + bytes_default.N + v5).join(bytes_default.N) - ).z(2).end(0); - } -} -function parseError(x5) { - const error50 = {}; - let start = 5; - for (let i5 = 5; i5 < x5.length - 1; i5++) { - if (x5[i5] === 0) { - error50[errorFields[x5[start]]] = x5.toString("utf8", start + 1, i5); - start = i5 + 1; - } - } - return error50; -} -function md5(x5) { - return crypto2.createHash("md5").update(x5).digest("hex"); -} -function hmac(key, x5) { - return crypto2.createHmac("sha256", key).update(x5).digest(); -} -function sha256(x5) { - return crypto2.createHash("sha256").update(x5).digest(); -} -function xor(a5, b6) { - const length = Math.max(a5.length, b6.length); - const buffer2 = Buffer.allocUnsafe(length); - for (let i5 = 0; i5 < length; i5++) - buffer2[i5] = a5[i5] ^ b6[i5]; - return buffer2; -} -function timer(fn, seconds) { - seconds = typeof seconds === "function" ? seconds() : seconds; - if (!seconds) - return { cancel: noop, start: noop }; - let timer2; - return { - cancel() { - timer2 && (clearTimeout(timer2), timer2 = null); - }, - start() { - timer2 && clearTimeout(timer2); - timer2 = setTimeout(done, seconds * 1e3, arguments); - } - }; - function done(args) { - fn.apply(null, args); - timer2 = null; - } -} -var connection_default, uid, Sync, Flush, SSLRequest, ExecuteUnnamed, DescribeUnnamed, noop, retryRoutines, errorFields; -var init_connection = __esm({ - "node_modules/.pnpm/postgres@3.4.9/node_modules/postgres/src/connection.js"() { - init_types(); - init_errors(); - init_result(); - init_queue(); - init_query(); - init_bytes(); - connection_default = Connection; - uid = 1; - Sync = bytes_default().S().end(); - Flush = bytes_default().H().end(); - SSLRequest = bytes_default().i32(8).i32(80877103).end(8); - ExecuteUnnamed = Buffer.concat([bytes_default().E().str(bytes_default.N).i32(0).end(), Sync]); - DescribeUnnamed = bytes_default().D().str("S").str(bytes_default.N).end(); - noop = () => { - }; - retryRoutines = /* @__PURE__ */ new Set([ - "FetchPreparedStatement", - "RevalidateCachedQuery", - "transformAssignedExpr" - ]); - errorFields = { - 83: "severity_local", - // S - 86: "severity", - // V - 67: "code", - // C - 77: "message", - // M - 68: "detail", - // D - 72: "hint", - // H - 80: "position", - // P - 112: "internal_position", - // p - 113: "internal_query", - // q - 87: "where", - // W - 115: "schema_name", - // s - 116: "table_name", - // t - 99: "column_name", - // c - 100: "data type_name", - // d - 110: "constraint_name", - // n - 70: "file", - // F - 76: "line", - // L - 82: "routine" - // R - }; - } -}); - -// node_modules/.pnpm/postgres@3.4.9/node_modules/postgres/src/subscribe.js -function Subscribe(postgres2, options) { - const subscribers = /* @__PURE__ */ new Map(), slot = "postgresjs_" + Math.random().toString(36).slice(2), state2 = {}; - let connection2, stream, ended = false; - const sql3 = subscribe.sql = postgres2({ - ...options, - transform: { column: {}, value: {}, row: {} }, - max: 1, - fetch_types: false, - idle_timeout: null, - max_lifetime: null, - connection: { - ...options.connection, - replication: "database" - }, - onclose: async function() { - if (ended) - return; - stream = null; - state2.pid = state2.secret = void 0; - connected(await init2(sql3, slot, options.publications)); - subscribers.forEach((event) => event.forEach(({ onsubscribe }) => onsubscribe())); - }, - no_subscribe: true - }); - const end = sql3.end, close = sql3.close; - sql3.end = async () => { - ended = true; - stream && await new Promise((r5) => (stream.once("close", r5), stream.end())); - return end(); - }; - sql3.close = async () => { - stream && await new Promise((r5) => (stream.once("close", r5), stream.end())); - return close(); - }; - return subscribe; - async function subscribe(event, fn, onsubscribe = noop2, onerror = noop2) { - event = parseEvent(event); - if (!connection2) - connection2 = init2(sql3, slot, options.publications); - const subscriber = { fn, onsubscribe }; - const fns = subscribers.has(event) ? subscribers.get(event).add(subscriber) : subscribers.set(event, /* @__PURE__ */ new Set([subscriber])).get(event); - const unsubscribe = () => { - fns.delete(subscriber); - fns.size === 0 && subscribers.delete(event); - }; - return connection2.then((x5) => { - connected(x5); - onsubscribe(); - stream && stream.on("error", onerror); - return { unsubscribe, state: state2, sql: sql3 }; - }); - } - function connected(x5) { - stream = x5.stream; - state2.pid = x5.state.pid; - state2.secret = x5.state.secret; - } - async function init2(sql4, slot2, publications) { - if (!publications) - throw new Error("Missing publication names"); - const xs = await sql4.unsafe( - `CREATE_REPLICATION_SLOT ${slot2} TEMPORARY LOGICAL pgoutput NOEXPORT_SNAPSHOT` - ); - const [x5] = xs; - const stream2 = await sql4.unsafe( - `START_REPLICATION SLOT ${slot2} LOGICAL ${x5.consistent_point} (proto_version '1', publication_names '${publications}')` - ).writable(); - const state3 = { - lsn: Buffer.concat(x5.consistent_point.split("/").map((x6) => Buffer.from(("00000000" + x6).slice(-8), "hex"))) - }; - stream2.on("data", data2); - stream2.on("error", error50); - stream2.on("close", sql4.close); - return { stream: stream2, state: xs.state }; - function error50(e5) { - console.error("Unexpected error during logical streaming - reconnecting", e5); - } - function data2(x6) { - if (x6[0] === 119) { - parse(x6.subarray(25), state3, sql4.options.parsers, handle, options.transform); - } else if (x6[0] === 107 && x6[17]) { - state3.lsn = x6.subarray(1, 9); - pong(); - } - } - function handle(a5, b6) { - const path53 = b6.relation.schema + "." + b6.relation.table; - call("*", a5, b6); - call("*:" + path53, a5, b6); - b6.relation.keys.length && call("*:" + path53 + "=" + b6.relation.keys.map((x6) => a5[x6.name]), a5, b6); - call(b6.command, a5, b6); - call(b6.command + ":" + path53, a5, b6); - b6.relation.keys.length && call(b6.command + ":" + path53 + "=" + b6.relation.keys.map((x6) => a5[x6.name]), a5, b6); - } - function pong() { - const x6 = Buffer.alloc(34); - x6[0] = "r".charCodeAt(0); - x6.fill(state3.lsn, 1); - x6.writeBigInt64BE(BigInt(Date.now() - Date.UTC(2e3, 0, 1)) * BigInt(1e3), 25); - stream2.write(x6); - } - } - function call(x5, a5, b6) { - subscribers.has(x5) && subscribers.get(x5).forEach(({ fn }) => fn(a5, b6, x5)); - } -} -function Time(x5) { - return new Date(Date.UTC(2e3, 0, 1) + Number(x5 / BigInt(1e3))); -} -function parse(x5, state2, parsers2, handle, transform3) { - const char2 = (acc, [k5, v5]) => (acc[k5.charCodeAt(0)] = v5, acc); - Object.entries({ - R: (x6) => { - let i5 = 1; - const r5 = state2[x6.readUInt32BE(i5)] = { - schema: x6.toString("utf8", i5 += 4, i5 = x6.indexOf(0, i5)) || "pg_catalog", - table: x6.toString("utf8", i5 + 1, i5 = x6.indexOf(0, i5 + 1)), - columns: Array(x6.readUInt16BE(i5 += 2)), - keys: [] - }; - i5 += 2; - let columnIndex = 0, column; - while (i5 < x6.length) { - column = r5.columns[columnIndex++] = { - key: x6[i5++], - name: transform3.column.from ? transform3.column.from(x6.toString("utf8", i5, i5 = x6.indexOf(0, i5))) : x6.toString("utf8", i5, i5 = x6.indexOf(0, i5)), - type: x6.readUInt32BE(i5 += 1), - parser: parsers2[x6.readUInt32BE(i5)], - atttypmod: x6.readUInt32BE(i5 += 4) - }; - column.key && r5.keys.push(column); - i5 += 4; - } - }, - Y: () => { - }, - // Type - O: () => { - }, - // Origin - B: (x6) => { - state2.date = Time(x6.readBigInt64BE(9)); - state2.lsn = x6.subarray(1, 9); - }, - I: (x6) => { - let i5 = 1; - const relation = state2[x6.readUInt32BE(i5)]; - const { row } = tuples(x6, relation.columns, i5 += 7, transform3); - handle(row, { - command: "insert", - relation - }); - }, - D: (x6) => { - let i5 = 1; - const relation = state2[x6.readUInt32BE(i5)]; - i5 += 4; - const key = x6[i5] === 75; - handle( - key || x6[i5] === 79 ? tuples(x6, relation.columns, i5 += 3, transform3).row : null, - { - command: "delete", - relation, - key - } - ); - }, - U: (x6) => { - let i5 = 1; - const relation = state2[x6.readUInt32BE(i5)]; - i5 += 4; - const key = x6[i5] === 75; - const xs = key || x6[i5] === 79 ? tuples(x6, relation.columns, i5 += 3, transform3) : null; - xs && (i5 = xs.i); - const { row } = tuples(x6, relation.columns, i5 + 3, transform3); - handle(row, { - command: "update", - relation, - key, - old: xs && xs.row - }); - }, - T: () => { - }, - // Truncate, - C: () => { - } - // Commit - }).reduce(char2, {})[x5[0]](x5); -} -function tuples(x5, columns, xi, transform3) { - let type, column, value; - const row = transform3.raw ? new Array(columns.length) : {}; - for (let i5 = 0; i5 < columns.length; i5++) { - type = x5[xi++]; - column = columns[i5]; - value = type === 110 ? null : type === 117 ? void 0 : column.parser === void 0 ? x5.toString("utf8", xi + 4, xi += 4 + x5.readUInt32BE(xi)) : column.parser.array === true ? column.parser(x5.toString("utf8", xi + 5, xi += 4 + x5.readUInt32BE(xi))) : column.parser(x5.toString("utf8", xi + 4, xi += 4 + x5.readUInt32BE(xi))); - transform3.raw ? row[i5] = transform3.raw === true ? value : transform3.value.from ? transform3.value.from(value, column) : value : row[column.name] = transform3.value.from ? transform3.value.from(value, column) : value; - } - return { i: xi, row: transform3.row.from ? transform3.row.from(row) : row }; -} -function parseEvent(x5) { - const xs = x5.match(/^(\*|insert|update|delete)?:?([^.]+?\.?[^=]+)?=?(.+)?/i) || []; - if (!xs) - throw new Error("Malformed subscribe pattern: " + x5); - const [, command, path53, key] = xs; - return (command || "*") + (path53 ? ":" + (path53.indexOf(".") === -1 ? "public." + path53 : path53) : "") + (key ? "=" + key : ""); -} -var noop2; -var init_subscribe = __esm({ - "node_modules/.pnpm/postgres@3.4.9/node_modules/postgres/src/subscribe.js"() { - noop2 = () => { - }; - } -}); - -// node_modules/.pnpm/postgres@3.4.9/node_modules/postgres/src/large.js -import Stream2 from "stream"; -function largeObject(sql3, oid, mode = 131072 | 262144) { - return new Promise(async (resolve4, reject) => { - await sql3.begin(async (sql4) => { - let finish; - !oid && ([{ oid }] = await sql4`select lo_creat(-1) as oid`); - const [{ fd }] = await sql4`select lo_open(${oid}, ${mode}) as fd`; - const lo = { - writable, - readable, - close: () => sql4`select lo_close(${fd})`.then(finish), - tell: () => sql4`select lo_tell64(${fd})`, - read: (x5) => sql4`select loread(${fd}, ${x5}) as data`, - write: (x5) => sql4`select lowrite(${fd}, ${x5})`, - truncate: (x5) => sql4`select lo_truncate64(${fd}, ${x5})`, - seek: (x5, whence = 0) => sql4`select lo_lseek64(${fd}, ${x5}, ${whence})`, - size: () => sql4` - select - lo_lseek64(${fd}, location, 0) as position, - seek.size - from ( - select - lo_lseek64($1, 0, 2) as size, - tell.location - from (select lo_tell64($1) as location) tell - ) seek - ` - }; - resolve4(lo); - return new Promise(async (r5) => finish = r5); - async function readable({ - highWaterMark = 2048 * 8, - start = 0, - end = Infinity - } = {}) { - let max = end - start; - start && await lo.seek(start); - return new Stream2.Readable({ - highWaterMark, - async read(size2) { - const l5 = size2 > max ? size2 - max : size2; - max -= size2; - const [{ data: data2 }] = await lo.read(l5); - this.push(data2); - if (data2.length < size2) - this.push(null); - } - }); - } - async function writable({ - highWaterMark = 2048 * 8, - start = 0 - } = {}) { - start && await lo.seek(start); - return new Stream2.Writable({ - highWaterMark, - write(chunk, encoding, callback) { - lo.write(chunk).then(() => callback(), callback); - } - }); - } - }).catch(reject); - }); -} -var init_large = __esm({ - "node_modules/.pnpm/postgres@3.4.9/node_modules/postgres/src/large.js"() { - } -}); - -// node_modules/.pnpm/postgres@3.4.9/node_modules/postgres/src/index.js -import os from "os"; -import fs from "fs"; -function Postgres(a5, b6) { - const options = parseOptions(a5, b6), subscribe = options.no_subscribe || Subscribe(Postgres, { ...options }); - let ending = false; - const queries = queue_default(), connecting = queue_default(), reserved = queue_default(), closed = queue_default(), ended = queue_default(), open2 = queue_default(), busy = queue_default(), full = queue_default(), queues = { connecting, reserved, closed, ended, open: open2, busy, full }; - const connections = [...Array(options.max)].map(() => connection_default(options, queues, { onopen, onend, onclose })); - const sql3 = Sql(handler); - Object.assign(sql3, { - get parameters() { - return options.parameters; - }, - largeObject: largeObject.bind(null, sql3), - subscribe, - CLOSE, - END: CLOSE, - PostgresError, - options, - reserve, - listen, - begin, - close, - end - }); - return sql3; - function Sql(handler2) { - handler2.debug = options.debug; - Object.entries(options.types).reduce((acc, [name, type]) => { - acc[name] = (x5) => new Parameter(x5, type.to); - return acc; - }, typed); - Object.assign(sql4, { - types: typed, - typed, - unsafe, - notify, - array: array2, - json: json3, - file: file2 - }); - return sql4; - function typed(value, type) { - return new Parameter(value, type); - } - function sql4(strings, ...args) { - const query = strings && Array.isArray(strings.raw) ? new Query(strings, args, handler2, cancel) : typeof strings === "string" && !args.length ? new Identifier(options.transform.column.to ? options.transform.column.to(strings) : strings) : new Builder(strings, args); - return query; - } - function unsafe(string4, args = [], options2 = {}) { - arguments.length === 2 && !Array.isArray(args) && (options2 = args, args = []); - const query = new Query([string4], args, handler2, cancel, { - prepare: false, - ...options2, - simple: "simple" in options2 ? options2.simple : args.length === 0 - }); - return query; - } - function file2(path53, args = [], options2 = {}) { - arguments.length === 2 && !Array.isArray(args) && (options2 = args, args = []); - const query = new Query([], args, (query2) => { - fs.readFile(path53, "utf8", (err, string4) => { - if (err) - return query2.reject(err); - query2.strings = [string4]; - handler2(query2); - }); - }, cancel, { - ...options2, - simple: "simple" in options2 ? options2.simple : args.length === 0 - }); - return query; - } - } - async function listen(name, fn, onlisten) { - const listener = { fn, onlisten }; - const sql4 = listen.sql || (listen.sql = Postgres({ - ...options, - max: 1, - idle_timeout: null, - max_lifetime: null, - fetch_types: false, - onclose() { - Object.entries(listen.channels).forEach(([name2, { listeners }]) => { - delete listen.channels[name2]; - Promise.all(listeners.map((l5) => listen(name2, l5.fn, l5.onlisten).catch(() => { - }))); - }); - }, - onnotify(c5, x5) { - c5 in listen.channels && listen.channels[c5].listeners.forEach((l5) => l5.fn(x5)); - } - })); - const channels = listen.channels || (listen.channels = {}), exists2 = name in channels; - if (exists2) { - channels[name].listeners.push(listener); - const result2 = await channels[name].result; - listener.onlisten && listener.onlisten(); - return { state: result2.state, unlisten }; - } - channels[name] = { result: sql4`listen ${sql4.unsafe('"' + name.replace(/"/g, '""') + '"')}`, listeners: [listener] }; - const result = await channels[name].result; - listener.onlisten && listener.onlisten(); - return { state: result.state, unlisten }; - async function unlisten() { - if (name in channels === false) - return; - channels[name].listeners = channels[name].listeners.filter((x5) => x5 !== listener); - if (channels[name].listeners.length) - return; - delete channels[name]; - return sql4`unlisten ${sql4.unsafe('"' + name.replace(/"/g, '""') + '"')}`; - } - } - async function notify(channel, payload2) { - return await sql3`select pg_notify(${channel}, ${"" + payload2})`; - } - async function reserve() { - const queue = queue_default(); - const c5 = open2.length ? open2.shift() : await new Promise((resolve4, reject) => { - const query = { reserve: resolve4, reject }; - queries.push(query); - closed.length && connect(closed.shift(), query); - }); - move(c5, reserved); - c5.reserved = () => queue.length ? c5.execute(queue.shift()) : move(c5, reserved); - c5.reserved.release = true; - const sql4 = Sql(handler2); - sql4.release = () => { - c5.reserved = null; - onopen(c5); - }; - return sql4; - function handler2(q5) { - c5.queue === full ? queue.push(q5) : c5.execute(q5) || move(c5, full); - } - } - async function begin(options2, fn) { - !fn && (fn = options2, options2 = ""); - const queries2 = queue_default(); - let savepoints = 0, connection2, prepare = null; - try { - await sql3.unsafe("begin " + options2.replace(/[^a-z ]/ig, ""), [], { onexecute }).execute(); - return await Promise.race([ - scope(connection2, fn), - new Promise((_, reject) => connection2.onclose = reject) - ]); - } catch (error50) { - throw error50; - } - async function scope(c5, fn2, name) { - const sql4 = Sql(handler2); - sql4.savepoint = savepoint; - sql4.prepare = (x5) => prepare = x5.replace(/[^a-z0-9$-_. ]/gi); - let uncaughtError, result; - name && await sql4`savepoint ${sql4(name)}`; - try { - result = await new Promise((resolve4, reject) => { - const x5 = fn2(sql4); - Promise.resolve(Array.isArray(x5) ? Promise.all(x5) : x5).then(resolve4, reject); - }); - if (uncaughtError) - throw uncaughtError; - } catch (e5) { - await (name ? sql4`rollback to ${sql4(name)}` : sql4`rollback`); - throw e5 instanceof PostgresError && e5.code === "25P02" && uncaughtError || e5; - } - if (!name) { - prepare ? await sql4`prepare transaction '${sql4.unsafe(prepare)}'` : await sql4`commit`; - } - return result; - function savepoint(name2, fn3) { - if (name2 && Array.isArray(name2.raw)) - return savepoint((sql5) => sql5.apply(sql5, arguments)); - arguments.length === 1 && (fn3 = name2, name2 = null); - return scope(c5, fn3, "s" + savepoints++ + (name2 ? "_" + name2 : "")); - } - function handler2(q5) { - q5.catch((e5) => uncaughtError || (uncaughtError = e5)); - c5.queue === full ? queries2.push(q5) : c5.execute(q5) || move(c5, full); - } - } - function onexecute(c5) { - connection2 = c5; - move(c5, reserved); - c5.reserved = () => queries2.length ? c5.execute(queries2.shift()) : move(c5, reserved); - } - } - function move(c5, queue) { - c5.queue.remove(c5); - queue.push(c5); - c5.queue = queue; - queue === open2 ? c5.idleTimer.start() : c5.idleTimer.cancel(); - return c5; - } - function json3(x5) { - return new Parameter(x5, 3802); - } - function array2(x5, type) { - if (!Array.isArray(x5)) - return array2(Array.from(arguments)); - return new Parameter(x5, type || (x5.length ? inferType(x5) || 25 : 0), options.shared.typeArrayMap); - } - function handler(query) { - if (ending) - return query.reject(Errors.connection("CONNECTION_ENDED", options, options)); - if (open2.length) - return go(open2.shift(), query); - if (closed.length) - return connect(closed.shift(), query); - busy.length ? go(busy.shift(), query) : queries.push(query); - } - function go(c5, query) { - return c5.execute(query) ? move(c5, busy) : move(c5, full); - } - function cancel(query) { - return new Promise((resolve4, reject) => { - query.state ? query.active ? connection_default(options).cancel(query.state, resolve4, reject) : query.cancelled = { resolve: resolve4, reject } : (queries.remove(query), query.cancelled = true, query.reject(Errors.generic("57014", "canceling statement due to user request")), resolve4()); - }); - } - async function end({ timeout = null } = {}) { - if (ending) - return ending; - await 1; - let timer2; - return ending = Promise.race([ - new Promise((r5) => timeout !== null && (timer2 = setTimeout(destroy, timeout * 1e3, r5))), - Promise.all(connections.map((c5) => c5.end()).concat( - listen.sql ? listen.sql.end({ timeout: 0 }) : [], - subscribe.sql ? subscribe.sql.end({ timeout: 0 }) : [] - )) - ]).then(() => clearTimeout(timer2)); - } - async function close() { - await Promise.all(connections.map((c5) => c5.end())); - } - async function destroy(resolve4) { - await Promise.all(connections.map((c5) => c5.terminate())); - while (queries.length) - queries.shift().reject(Errors.connection("CONNECTION_DESTROYED", options)); - resolve4(); - } - function connect(c5, query) { - move(c5, connecting); - c5.connect(query); - return c5; - } - function onend(c5) { - move(c5, ended); - } - function onopen(c5) { - if (queries.length === 0) - return move(c5, open2); - let max = Math.ceil(queries.length / (connecting.length + 1)), ready = true; - while (ready && queries.length && max-- > 0) { - const query = queries.shift(); - if (query.reserve) - return query.reserve(c5); - ready = c5.execute(query); - } - ready ? move(c5, busy) : move(c5, full); - } - function onclose(c5, e5) { - move(c5, closed); - c5.reserved = null; - c5.onclose && (c5.onclose(e5), c5.onclose = null); - options.onclose && options.onclose(c5.id); - queries.length && connect(c5, queries.shift()); - } -} -function parseOptions(a5, b6) { - if (a5 && a5.shared) - return a5; - const env2 = process.env, o5 = (!a5 || typeof a5 === "string" ? b6 : a5) || {}, { url: url2, multihost } = parseUrl(a5), query = [...url2.searchParams].reduce((a6, [b7, c5]) => (a6[b7] = c5, a6), {}), host = o5.hostname || o5.host || multihost || url2.hostname || env2.PGHOST || "localhost", port = o5.port || url2.port || env2.PGPORT || 5432, user = o5.user || o5.username || url2.username || env2.PGUSERNAME || env2.PGUSER || osUsername(); - o5.no_prepare && (o5.prepare = false); - query.sslmode && (query.ssl = query.sslmode, delete query.sslmode); - "timeout" in o5 && (console.log("The timeout option is deprecated, use idle_timeout instead"), o5.idle_timeout = o5.timeout); - query.sslrootcert === "system" && (query.ssl = "verify-full"); - const ints = ["idle_timeout", "connect_timeout", "max_lifetime", "max_pipeline", "backoff", "keep_alive"]; - const defaults = { - max: globalThis.Cloudflare ? 3 : 10, - ssl: false, - sslnegotiation: null, - idle_timeout: null, - connect_timeout: 30, - max_lifetime, - max_pipeline: 100, - backoff, - keep_alive: 60, - prepare: true, - debug: false, - fetch_types: true, - publications: "alltables", - target_session_attrs: null - }; - return { - host: Array.isArray(host) ? host : host.split(",").map((x5) => x5.split(":")[0]), - port: Array.isArray(port) ? port : host.split(",").map((x5) => parseInt(x5.split(":")[1] || port)), - path: o5.path || host.indexOf("/") > -1 && host + "/.s.PGSQL." + port, - database: o5.database || o5.db || (url2.pathname || "").slice(1) || env2.PGDATABASE || user, - user, - pass: o5.pass || o5.password || url2.password || env2.PGPASSWORD || "", - ...Object.entries(defaults).reduce( - (acc, [k5, d5]) => { - const value = k5 in o5 ? o5[k5] : k5 in query ? query[k5] === "disable" || query[k5] === "false" ? false : query[k5] : env2["PG" + k5.toUpperCase()] || d5; - acc[k5] = typeof value === "string" && ints.includes(k5) ? +value : value; - return acc; - }, - {} - ), - connection: { - application_name: env2.PGAPPNAME || "postgres.js", - ...o5.connection, - ...Object.entries(query).reduce((acc, [k5, v5]) => (k5 in defaults || (acc[k5] = v5), acc), {}) - }, - types: o5.types || {}, - target_session_attrs: tsa(o5, url2, env2), - onnotice: o5.onnotice, - onnotify: o5.onnotify, - onclose: o5.onclose, - onparameter: o5.onparameter, - socket: o5.socket, - transform: parseTransform(o5.transform || { undefined: void 0 }), - parameters: {}, - shared: { retries: 0, typeArrayMap: {} }, - ...mergeUserTypes(o5.types) - }; -} -function tsa(o5, url2, env2) { - const x5 = o5.target_session_attrs || url2.searchParams.get("target_session_attrs") || env2.PGTARGETSESSIONATTRS; - if (!x5 || ["read-write", "read-only", "primary", "standby", "prefer-standby"].includes(x5)) - return x5; - throw new Error("target_session_attrs " + x5 + " is not supported"); -} -function backoff(retries) { - return (0.5 + Math.random() / 2) * Math.min(3 ** retries / 100, 20); -} -function max_lifetime() { - return 60 * (30 + Math.random() * 30); -} -function parseTransform(x5) { - return { - undefined: x5.undefined, - column: { - from: typeof x5.column === "function" ? x5.column : x5.column && x5.column.from, - to: x5.column && x5.column.to - }, - value: { - from: typeof x5.value === "function" ? x5.value : x5.value && x5.value.from, - to: x5.value && x5.value.to - }, - row: { - from: typeof x5.row === "function" ? x5.row : x5.row && x5.row.from, - to: x5.row && x5.row.to - } - }; -} -function parseUrl(url2) { - if (!url2 || typeof url2 !== "string") - return { url: { searchParams: /* @__PURE__ */ new Map() } }; - let host = url2; - host = host.slice(host.indexOf("://") + 3).split(/[?/]/)[0]; - host = decodeURIComponent(host.slice(host.indexOf("@") + 1)); - const urlObj = new URL(url2.replace(host, host.split(",")[0])); - return { - url: { - username: decodeURIComponent(urlObj.username), - password: decodeURIComponent(urlObj.password), - host: urlObj.host, - hostname: urlObj.hostname, - port: urlObj.port, - pathname: urlObj.pathname, - searchParams: urlObj.searchParams - }, - multihost: host.indexOf(",") > -1 && host - }; -} -function osUsername() { - try { - return os.userInfo().username; - } catch (_) { - return process.env.USERNAME || process.env.USER || process.env.LOGNAME; - } -} -var src_default; -var init_src = __esm({ - "node_modules/.pnpm/postgres@3.4.9/node_modules/postgres/src/index.js"() { - init_types(); - init_connection(); - init_query(); - init_queue(); - init_errors(); - init_subscribe(); - init_large(); - Object.assign(Postgres, { - PostgresError, - toPascal, - pascal, - toCamel, - camel, - toKebab, - kebab, - fromPascal, - fromCamel, - fromKebab, - BigInt: { - to: 20, - from: [20], - parse: (x5) => BigInt(x5), - // eslint-disable-line - serialize: (x5) => x5.toString() - } - }); - src_default = Postgres; - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/entity.js -function is(value, type) { - if (!value || typeof value !== "object") { - return false; - } - if (value instanceof type) { - return true; - } - if (!Object.prototype.hasOwnProperty.call(type, entityKind)) { - throw new Error( - `Class "${type.name ?? ""}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.` - ); - } - let cls = Object.getPrototypeOf(value).constructor; - if (cls) { - while (cls) { - if (entityKind in cls && cls[entityKind] === type[entityKind]) { - return true; - } - cls = Object.getPrototypeOf(cls); - } - } - return false; -} -var entityKind; -var init_entity = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/entity.js"() { - entityKind = /* @__PURE__ */ Symbol.for("drizzle:entityKind"); - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/logger.js -var ConsoleLogWriter, DefaultLogger, NoopLogger; -var init_logger = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/logger.js"() { - init_entity(); - ConsoleLogWriter = class { - static [entityKind] = "ConsoleLogWriter"; - write(message2) { - console.log(message2); - } - }; - DefaultLogger = class { - static [entityKind] = "DefaultLogger"; - writer; - constructor(config3) { - this.writer = config3?.writer ?? new ConsoleLogWriter(); - } - logQuery(query, params) { - const stringifiedParams = params.map((p5) => { - try { - return JSON.stringify(p5); - } catch { - return String(p5); - } - }); - const paramsStr = stringifiedParams.length ? ` -- params: [${stringifiedParams.join(", ")}]` : ""; - this.writer.write(`Query: ${query}${paramsStr}`); - } - }; - NoopLogger = class { - static [entityKind] = "NoopLogger"; - logQuery() { - } - }; - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/query-promise.js -var QueryPromise; -var init_query_promise = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/query-promise.js"() { - init_entity(); - QueryPromise = class { - static [entityKind] = "QueryPromise"; - [Symbol.toStringTag] = "QueryPromise"; - catch(onRejected) { - return this.then(void 0, onRejected); - } - finally(onFinally) { - return this.then( - (value) => { - onFinally?.(); - return value; - }, - (reason) => { - onFinally?.(); - throw reason; - } - ); - } - then(onFulfilled, onRejected) { - return this.execute().then(onFulfilled, onRejected); - } - }; - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/table.utils.js -var TableName; -var init_table_utils = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/table.utils.js"() { - TableName = /* @__PURE__ */ Symbol.for("drizzle:Name"); - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/table.js -function getTableName(table) { - return table[TableName]; -} -function getTableUniqueName(table) { - return `${table[Schema] ?? "public"}.${table[TableName]}`; -} -var Schema, Columns, ExtraConfigColumns, OriginalName, BaseName, IsAlias, ExtraConfigBuilder, IsDrizzleTable, Table; -var init_table = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/table.js"() { - init_entity(); - init_table_utils(); - Schema = /* @__PURE__ */ Symbol.for("drizzle:Schema"); - Columns = /* @__PURE__ */ Symbol.for("drizzle:Columns"); - ExtraConfigColumns = /* @__PURE__ */ Symbol.for("drizzle:ExtraConfigColumns"); - OriginalName = /* @__PURE__ */ Symbol.for("drizzle:OriginalName"); - BaseName = /* @__PURE__ */ Symbol.for("drizzle:BaseName"); - IsAlias = /* @__PURE__ */ Symbol.for("drizzle:IsAlias"); - ExtraConfigBuilder = /* @__PURE__ */ Symbol.for("drizzle:ExtraConfigBuilder"); - IsDrizzleTable = /* @__PURE__ */ Symbol.for("drizzle:IsDrizzleTable"); - Table = class { - static [entityKind] = "Table"; - /** @internal */ - static Symbol = { - Name: TableName, - Schema, - OriginalName, - Columns, - ExtraConfigColumns, - BaseName, - IsAlias, - ExtraConfigBuilder - }; - /** - * @internal - * Can be changed if the table is aliased. - */ - [TableName]; - /** - * @internal - * Used to store the original name of the table, before any aliasing. - */ - [OriginalName]; - /** @internal */ - [Schema]; - /** @internal */ - [Columns]; - /** @internal */ - [ExtraConfigColumns]; - /** - * @internal - * Used to store the table name before the transformation via the `tableCreator` functions. - */ - [BaseName]; - /** @internal */ - [IsAlias] = false; - /** @internal */ - [IsDrizzleTable] = true; - /** @internal */ - [ExtraConfigBuilder] = void 0; - constructor(name, schema2, baseName) { - this[TableName] = this[OriginalName] = name; - this[Schema] = schema2; - this[BaseName] = baseName; - } - }; - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/tracing-utils.js -function iife(fn, ...args) { - return fn(...args); -} -var init_tracing_utils = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/tracing-utils.js"() { - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/version.js -var version; -var init_version = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/version.js"() { - version = "0.38.4"; - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/tracing.js -var otel, rawTracer, tracer; -var init_tracing = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/tracing.js"() { - init_tracing_utils(); - init_version(); - tracer = { - startActiveSpan(name, fn) { - if (!otel) { - return fn(); - } - if (!rawTracer) { - rawTracer = otel.trace.getTracer("drizzle-orm", version); - } - return iife( - (otel2, rawTracer2) => rawTracer2.startActiveSpan( - name, - (span) => { - try { - return fn(span); - } catch (e5) { - span.setStatus({ - code: otel2.SpanStatusCode.ERROR, - message: e5 instanceof Error ? e5.message : "Unknown error" - // eslint-disable-line no-instanceof/no-instanceof - }); - throw e5; - } finally { - span.end(); - } - } - ), - otel, - rawTracer - ); - } - }; - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/column.js -var Column; -var init_column = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/column.js"() { - init_entity(); - Column = class { - constructor(table, config3) { - this.table = table; - this.config = config3; - this.name = config3.name; - this.keyAsName = config3.keyAsName; - this.notNull = config3.notNull; - this.default = config3.default; - this.defaultFn = config3.defaultFn; - this.onUpdateFn = config3.onUpdateFn; - this.hasDefault = config3.hasDefault; - this.primary = config3.primaryKey; - this.isUnique = config3.isUnique; - this.uniqueName = config3.uniqueName; - this.uniqueType = config3.uniqueType; - this.dataType = config3.dataType; - this.columnType = config3.columnType; - this.generated = config3.generated; - this.generatedIdentity = config3.generatedIdentity; - } - static [entityKind] = "Column"; - name; - keyAsName; - primary; - notNull; - default; - defaultFn; - onUpdateFn; - hasDefault; - isUnique; - uniqueName; - uniqueType; - dataType; - columnType; - enumValues = void 0; - generated = void 0; - generatedIdentity = void 0; - config; - mapFromDriverValue(value) { - return value; - } - mapToDriverValue(value) { - return value; - } - // ** @internal */ - shouldDisableInsert() { - return this.config.generated !== void 0 && this.config.generated.type !== "byDefault"; - } - }; - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/column-builder.js -var ColumnBuilder; -var init_column_builder = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/column-builder.js"() { - init_entity(); - ColumnBuilder = class { - static [entityKind] = "ColumnBuilder"; - config; - constructor(name, dataType, columnType) { - this.config = { - name, - keyAsName: name === "", - notNull: false, - default: void 0, - hasDefault: false, - primaryKey: false, - isUnique: false, - uniqueName: void 0, - uniqueType: void 0, - dataType, - columnType, - generated: void 0 - }; - } - /** - * Changes the data type of the column. Commonly used with `json` columns. Also, useful for branded types. - * - * @example - * ```ts - * const users = pgTable('users', { - * id: integer('id').$type().primaryKey(), - * details: json('details').$type().notNull(), - * }); - * ``` - */ - $type() { - return this; - } - /** - * Adds a `not null` clause to the column definition. - * - * Affects the `select` model of the table - columns *without* `not null` will be nullable on select. - */ - notNull() { - this.config.notNull = true; - return this; - } - /** - * Adds a `default ` clause to the column definition. - * - * Affects the `insert` model of the table - columns *with* `default` are optional on insert. - * - * If you need to set a dynamic default value, use {@link $defaultFn} instead. - */ - default(value) { - this.config.default = value; - this.config.hasDefault = true; - return this; - } - /** - * Adds a dynamic default value to the column. - * The function will be called when the row is inserted, and the returned value will be used as the column value. - * - * **Note:** This value does not affect the `drizzle-kit` behavior, it is only used at runtime in `drizzle-orm`. - */ - $defaultFn(fn) { - this.config.defaultFn = fn; - this.config.hasDefault = true; - return this; - } - /** - * Alias for {@link $defaultFn}. - */ - $default = this.$defaultFn; - /** - * Adds a dynamic update value to the column. - * The function will be called when the row is updated, and the returned value will be used as the column value if none is provided. - * If no `default` (or `$defaultFn`) value is provided, the function will be called when the row is inserted as well, and the returned value will be used as the column value. - * - * **Note:** This value does not affect the `drizzle-kit` behavior, it is only used at runtime in `drizzle-orm`. - */ - $onUpdateFn(fn) { - this.config.onUpdateFn = fn; - this.config.hasDefault = true; - return this; - } - /** - * Alias for {@link $onUpdateFn}. - */ - $onUpdate = this.$onUpdateFn; - /** - * Adds a `primary key` clause to the column definition. This implicitly makes the column `not null`. - * - * In SQLite, `integer primary key` implicitly makes the column auto-incrementing. - */ - primaryKey() { - this.config.primaryKey = true; - this.config.notNull = true; - return this; - } - /** @internal Sets the name of the column to the key within the table definition if a name was not given. */ - setName(name) { - if (this.config.name !== "") - return; - this.config.name = name; - } - }; - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/foreign-keys.js -var ForeignKeyBuilder, ForeignKey; -var init_foreign_keys = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/foreign-keys.js"() { - init_entity(); - init_table_utils(); - ForeignKeyBuilder = class { - static [entityKind] = "PgForeignKeyBuilder"; - /** @internal */ - reference; - /** @internal */ - _onUpdate = "no action"; - /** @internal */ - _onDelete = "no action"; - constructor(config3, actions) { - this.reference = () => { - const { name, columns, foreignColumns } = config3(); - return { name, columns, foreignTable: foreignColumns[0].table, foreignColumns }; - }; - if (actions) { - this._onUpdate = actions.onUpdate; - this._onDelete = actions.onDelete; - } - } - onUpdate(action) { - this._onUpdate = action === void 0 ? "no action" : action; - return this; - } - onDelete(action) { - this._onDelete = action === void 0 ? "no action" : action; - return this; - } - /** @internal */ - build(table) { - return new ForeignKey(table, this); - } - }; - ForeignKey = class { - constructor(table, builder) { - this.table = table; - this.reference = builder.reference; - this.onUpdate = builder._onUpdate; - this.onDelete = builder._onDelete; - } - static [entityKind] = "PgForeignKey"; - reference; - onUpdate; - onDelete; - getName() { - const { name, columns, foreignColumns } = this.reference(); - const columnNames = columns.map((column) => column.name); - const foreignColumnNames = foreignColumns.map((column) => column.name); - const chunks = [ - this.table[TableName], - ...columnNames, - foreignColumns[0].table[TableName], - ...foreignColumnNames - ]; - return name ?? `${chunks.join("_")}_fk`; - } - }; - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/unique-constraint.js -function unique(name) { - return new UniqueOnConstraintBuilder(name); -} -function uniqueKeyName(table, columns) { - return `${table[TableName]}_${columns.join("_")}_unique`; -} -var UniqueConstraintBuilder, UniqueOnConstraintBuilder, UniqueConstraint; -var init_unique_constraint = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/unique-constraint.js"() { - init_entity(); - init_table_utils(); - UniqueConstraintBuilder = class { - constructor(columns, name) { - this.name = name; - this.columns = columns; - } - static [entityKind] = "PgUniqueConstraintBuilder"; - /** @internal */ - columns; - /** @internal */ - nullsNotDistinctConfig = false; - nullsNotDistinct() { - this.nullsNotDistinctConfig = true; - return this; - } - /** @internal */ - build(table) { - return new UniqueConstraint(table, this.columns, this.nullsNotDistinctConfig, this.name); - } - }; - UniqueOnConstraintBuilder = class { - static [entityKind] = "PgUniqueOnConstraintBuilder"; - /** @internal */ - name; - constructor(name) { - this.name = name; - } - on(...columns) { - return new UniqueConstraintBuilder(columns, this.name); - } - }; - UniqueConstraint = class { - constructor(table, columns, nullsNotDistinct, name) { - this.table = table; - this.columns = columns; - this.name = name ?? uniqueKeyName(this.table, this.columns.map((column) => column.name)); - this.nullsNotDistinct = nullsNotDistinct; - } - static [entityKind] = "PgUniqueConstraint"; - columns; - name; - nullsNotDistinct = false; - getName() { - return this.name; - } - }; - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/utils/array.js -function parsePgArrayValue(arrayString, startFrom, inQuotes) { - for (let i5 = startFrom; i5 < arrayString.length; i5++) { - const char2 = arrayString[i5]; - if (char2 === "\\") { - i5++; - continue; - } - if (char2 === '"') { - return [arrayString.slice(startFrom, i5).replace(/\\/g, ""), i5 + 1]; - } - if (inQuotes) { - continue; - } - if (char2 === "," || char2 === "}") { - return [arrayString.slice(startFrom, i5).replace(/\\/g, ""), i5]; - } - } - return [arrayString.slice(startFrom).replace(/\\/g, ""), arrayString.length]; -} -function parsePgNestedArray(arrayString, startFrom = 0) { - const result = []; - let i5 = startFrom; - let lastCharIsComma = false; - while (i5 < arrayString.length) { - const char2 = arrayString[i5]; - if (char2 === ",") { - if (lastCharIsComma || i5 === startFrom) { - result.push(""); - } - lastCharIsComma = true; - i5++; - continue; - } - lastCharIsComma = false; - if (char2 === "\\") { - i5 += 2; - continue; - } - if (char2 === '"') { - const [value2, startFrom2] = parsePgArrayValue(arrayString, i5 + 1, true); - result.push(value2); - i5 = startFrom2; - continue; - } - if (char2 === "}") { - return [result, i5 + 1]; - } - if (char2 === "{") { - const [value2, startFrom2] = parsePgNestedArray(arrayString, i5 + 1); - result.push(value2); - i5 = startFrom2; - continue; - } - const [value, newStartFrom] = parsePgArrayValue(arrayString, i5, false); - result.push(value); - i5 = newStartFrom; - } - return [result, i5]; -} -function parsePgArray(arrayString) { - const [result] = parsePgNestedArray(arrayString, 1); - return result; -} -function makePgArray(array2) { - return `{${array2.map((item) => { - if (Array.isArray(item)) { - return makePgArray(item); - } - if (typeof item === "string") { - return `"${item.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`; - } - return `${item}`; - }).join(",")}}`; -} -var init_array = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/utils/array.js"() { - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/common.js -var PgColumnBuilder, PgColumn, ExtraConfigColumn, IndexedColumn, PgArrayBuilder, PgArray; -var init_common = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/common.js"() { - init_column_builder(); - init_column(); - init_entity(); - init_foreign_keys(); - init_tracing_utils(); - init_unique_constraint(); - init_array(); - PgColumnBuilder = class extends ColumnBuilder { - foreignKeyConfigs = []; - static [entityKind] = "PgColumnBuilder"; - array(size2) { - return new PgArrayBuilder(this.config.name, this, size2); - } - references(ref, actions = {}) { - this.foreignKeyConfigs.push({ ref, actions }); - return this; - } - unique(name, config3) { - this.config.isUnique = true; - this.config.uniqueName = name; - this.config.uniqueType = config3?.nulls; - return this; - } - generatedAlwaysAs(as) { - this.config.generated = { - as, - type: "always", - mode: "stored" - }; - return this; - } - /** @internal */ - buildForeignKeys(column, table) { - return this.foreignKeyConfigs.map(({ ref, actions }) => { - return iife( - (ref2, actions2) => { - const builder = new ForeignKeyBuilder(() => { - const foreignColumn = ref2(); - return { columns: [column], foreignColumns: [foreignColumn] }; - }); - if (actions2.onUpdate) { - builder.onUpdate(actions2.onUpdate); - } - if (actions2.onDelete) { - builder.onDelete(actions2.onDelete); - } - return builder.build(table); - }, - ref, - actions - ); - }); - } - /** @internal */ - buildExtraConfigColumn(table) { - return new ExtraConfigColumn(table, this.config); - } - }; - PgColumn = class extends Column { - constructor(table, config3) { - if (!config3.uniqueName) { - config3.uniqueName = uniqueKeyName(table, [config3.name]); - } - super(table, config3); - this.table = table; - } - static [entityKind] = "PgColumn"; - }; - ExtraConfigColumn = class extends PgColumn { - static [entityKind] = "ExtraConfigColumn"; - getSQLType() { - return this.getSQLType(); - } - indexConfig = { - order: this.config.order ?? "asc", - nulls: this.config.nulls ?? "last", - opClass: this.config.opClass - }; - defaultConfig = { - order: "asc", - nulls: "last", - opClass: void 0 - }; - asc() { - this.indexConfig.order = "asc"; - return this; - } - desc() { - this.indexConfig.order = "desc"; - return this; - } - nullsFirst() { - this.indexConfig.nulls = "first"; - return this; - } - nullsLast() { - this.indexConfig.nulls = "last"; - return this; - } - /** - * ### PostgreSQL documentation quote - * - * > An operator class with optional parameters can be specified for each column of an index. - * The operator class identifies the operators to be used by the index for that column. - * For example, a B-tree index on four-byte integers would use the int4_ops class; - * this operator class includes comparison functions for four-byte integers. - * In practice the default operator class for the column's data type is usually sufficient. - * The main point of having operator classes is that for some data types, there could be more than one meaningful ordering. - * For example, we might want to sort a complex-number data type either by absolute value or by real part. - * We could do this by defining two operator classes for the data type and then selecting the proper class when creating an index. - * More information about operator classes check: - * - * ### Useful links - * https://www.postgresql.org/docs/current/sql-createindex.html - * - * https://www.postgresql.org/docs/current/indexes-opclass.html - * - * https://www.postgresql.org/docs/current/xindex.html - * - * ### Additional types - * If you have the `pg_vector` extension installed in your database, you can use the - * `vector_l2_ops`, `vector_ip_ops`, `vector_cosine_ops`, `vector_l1_ops`, `bit_hamming_ops`, `bit_jaccard_ops`, `halfvec_l2_ops`, `sparsevec_l2_ops` options, which are predefined types. - * - * **You can always specify any string you want in the operator class, in case Drizzle doesn't have it natively in its types** - * - * @param opClass - * @returns - */ - op(opClass) { - this.indexConfig.opClass = opClass; - return this; - } - }; - IndexedColumn = class { - static [entityKind] = "IndexedColumn"; - constructor(name, keyAsName, type, indexConfig) { - this.name = name; - this.keyAsName = keyAsName; - this.type = type; - this.indexConfig = indexConfig; - } - name; - keyAsName; - type; - indexConfig; - }; - PgArrayBuilder = class extends PgColumnBuilder { - static [entityKind] = "PgArrayBuilder"; - constructor(name, baseBuilder, size2) { - super(name, "array", "PgArray"); - this.config.baseBuilder = baseBuilder; - this.config.size = size2; - } - /** @internal */ - build(table) { - const baseColumn = this.config.baseBuilder.build(table); - return new PgArray( - table, - this.config, - baseColumn - ); - } - }; - PgArray = class _PgArray extends PgColumn { - constructor(table, config3, baseColumn, range2) { - super(table, config3); - this.baseColumn = baseColumn; - this.range = range2; - this.size = config3.size; - } - size; - static [entityKind] = "PgArray"; - getSQLType() { - return `${this.baseColumn.getSQLType()}[${typeof this.size === "number" ? this.size : ""}]`; - } - mapFromDriverValue(value) { - if (typeof value === "string") { - value = parsePgArray(value); - } - return value.map((v5) => this.baseColumn.mapFromDriverValue(v5)); - } - mapToDriverValue(value, isNestedArray = false) { - const a5 = value.map( - (v5) => v5 === null ? null : is(this.baseColumn, _PgArray) ? this.baseColumn.mapToDriverValue(v5, true) : this.baseColumn.mapToDriverValue(v5) - ); - if (isNestedArray) - return a5; - return makePgArray(a5); - } - }; - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/enum.js -function isPgEnum(obj) { - return !!obj && typeof obj === "function" && isPgEnumSym in obj && obj[isPgEnumSym] === true; -} -function pgEnumWithSchema(enumName, values2, schema2) { - const enumInstance = Object.assign( - (name) => new PgEnumColumnBuilder(name ?? "", enumInstance), - { - enumName, - enumValues: values2, - schema: schema2, - [isPgEnumSym]: true - } - ); - return enumInstance; -} -var isPgEnumSym, PgEnumColumnBuilder, PgEnumColumn; -var init_enum = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/enum.js"() { - init_entity(); - init_common(); - isPgEnumSym = /* @__PURE__ */ Symbol.for("drizzle:isPgEnum"); - PgEnumColumnBuilder = class extends PgColumnBuilder { - static [entityKind] = "PgEnumColumnBuilder"; - constructor(name, enumInstance) { - super(name, "string", "PgEnumColumn"); - this.config.enum = enumInstance; - } - /** @internal */ - build(table) { - return new PgEnumColumn( - table, - this.config - ); - } - }; - PgEnumColumn = class extends PgColumn { - static [entityKind] = "PgEnumColumn"; - enum = this.config.enum; - enumValues = this.config.enum.enumValues; - constructor(table, config3) { - super(table, config3); - this.enum = config3.enum; - } - getSQLType() { - return this.enum.enumName; - } - }; - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/subquery.js -var Subquery, WithSubquery; -var init_subquery = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/subquery.js"() { - init_entity(); - Subquery = class { - static [entityKind] = "Subquery"; - constructor(sql3, selection, alias, isWith = false) { - this._ = { - brand: "Subquery", - sql: sql3, - selectedFields: selection, - alias, - isWith - }; - } - // getSQL(): SQL { - // return new SQL([this]); - // } - }; - WithSubquery = class extends Subquery { - static [entityKind] = "WithSubquery"; - }; - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/view-common.js -var ViewBaseConfig; -var init_view_common = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/view-common.js"() { - ViewBaseConfig = /* @__PURE__ */ Symbol.for("drizzle:ViewBaseConfig"); - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/sql/sql.js -function isSQLWrapper(value) { - return value !== null && value !== void 0 && typeof value.getSQL === "function"; -} -function mergeQueries(queries) { - const result = { sql: "", params: [] }; - for (const query of queries) { - result.sql += query.sql; - result.params.push(...query.params); - if (query.typings?.length) { - if (!result.typings) { - result.typings = []; - } - result.typings.push(...query.typings); - } - } - return result; -} -function isDriverValueEncoder(value) { - return typeof value === "object" && value !== null && "mapToDriverValue" in value && typeof value.mapToDriverValue === "function"; -} -function sql(strings, ...params) { - const queryChunks = []; - if (params.length > 0 || strings.length > 0 && strings[0] !== "") { - queryChunks.push(new StringChunk(strings[0])); - } - for (const [paramIndex, param2] of params.entries()) { - queryChunks.push(param2, new StringChunk(strings[paramIndex + 1])); - } - return new SQL(queryChunks); -} -function fillPlaceholders(params, values2) { - return params.map((p5) => { - if (is(p5, Placeholder)) { - if (!(p5.name in values2)) { - throw new Error(`No value for placeholder "${p5.name}" was provided`); - } - return values2[p5.name]; - } - if (is(p5, Param) && is(p5.value, Placeholder)) { - if (!(p5.value.name in values2)) { - throw new Error(`No value for placeholder "${p5.value.name}" was provided`); - } - return p5.encoder.mapToDriverValue(values2[p5.value.name]); - } - return p5; - }); -} -var FakePrimitiveParam, StringChunk, SQL, Name, noopDecoder, noopEncoder, noopMapper, Param, Placeholder, IsDrizzleView, View; -var init_sql = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/sql/sql.js"() { - init_entity(); - init_enum(); - init_subquery(); - init_tracing(); - init_view_common(); - init_column(); - init_table(); - FakePrimitiveParam = class { - static [entityKind] = "FakePrimitiveParam"; - }; - StringChunk = class { - static [entityKind] = "StringChunk"; - value; - constructor(value) { - this.value = Array.isArray(value) ? value : [value]; - } - getSQL() { - return new SQL([this]); - } - }; - SQL = class _SQL { - constructor(queryChunks) { - this.queryChunks = queryChunks; - } - static [entityKind] = "SQL"; - /** @internal */ - decoder = noopDecoder; - shouldInlineParams = false; - append(query) { - this.queryChunks.push(...query.queryChunks); - return this; - } - toQuery(config3) { - return tracer.startActiveSpan("drizzle.buildSQL", (span) => { - const query = this.buildQueryFromSourceParams(this.queryChunks, config3); - span?.setAttributes({ - "drizzle.query.text": query.sql, - "drizzle.query.params": JSON.stringify(query.params) - }); - return query; - }); - } - buildQueryFromSourceParams(chunks, _config) { - const config3 = Object.assign({}, _config, { - inlineParams: _config.inlineParams || this.shouldInlineParams, - paramStartIndex: _config.paramStartIndex || { value: 0 } - }); - const { - casing, - escapeName, - escapeParam, - prepareTyping, - inlineParams, - paramStartIndex - } = config3; - return mergeQueries(chunks.map((chunk) => { - if (is(chunk, StringChunk)) { - return { sql: chunk.value.join(""), params: [] }; - } - if (is(chunk, Name)) { - return { sql: escapeName(chunk.value), params: [] }; - } - if (chunk === void 0) { - return { sql: "", params: [] }; - } - if (Array.isArray(chunk)) { - const result = [new StringChunk("(")]; - for (const [i5, p5] of chunk.entries()) { - result.push(p5); - if (i5 < chunk.length - 1) { - result.push(new StringChunk(", ")); - } - } - result.push(new StringChunk(")")); - return this.buildQueryFromSourceParams(result, config3); - } - if (is(chunk, _SQL)) { - return this.buildQueryFromSourceParams(chunk.queryChunks, { - ...config3, - inlineParams: inlineParams || chunk.shouldInlineParams - }); - } - if (is(chunk, Table)) { - const schemaName = chunk[Table.Symbol.Schema]; - const tableName = chunk[Table.Symbol.Name]; - return { - sql: schemaName === void 0 ? escapeName(tableName) : escapeName(schemaName) + "." + escapeName(tableName), - params: [] - }; - } - if (is(chunk, Column)) { - const columnName = casing.getColumnCasing(chunk); - if (_config.invokeSource === "indexes") { - return { sql: escapeName(columnName), params: [] }; - } - const schemaName = chunk.table[Table.Symbol.Schema]; - return { - sql: chunk.table[IsAlias] || schemaName === void 0 ? escapeName(chunk.table[Table.Symbol.Name]) + "." + escapeName(columnName) : escapeName(schemaName) + "." + escapeName(chunk.table[Table.Symbol.Name]) + "." + escapeName(columnName), - params: [] - }; - } - if (is(chunk, View)) { - const schemaName = chunk[ViewBaseConfig].schema; - const viewName = chunk[ViewBaseConfig].name; - return { - sql: schemaName === void 0 ? escapeName(viewName) : escapeName(schemaName) + "." + escapeName(viewName), - params: [] - }; - } - if (is(chunk, Param)) { - if (is(chunk.value, Placeholder)) { - return { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: ["none"] }; - } - const mappedValue = chunk.value === null ? null : chunk.encoder.mapToDriverValue(chunk.value); - if (is(mappedValue, _SQL)) { - return this.buildQueryFromSourceParams([mappedValue], config3); - } - if (inlineParams) { - return { sql: this.mapInlineParam(mappedValue, config3), params: [] }; - } - let typings = ["none"]; - if (prepareTyping) { - typings = [prepareTyping(chunk.encoder)]; - } - return { sql: escapeParam(paramStartIndex.value++, mappedValue), params: [mappedValue], typings }; - } - if (is(chunk, Placeholder)) { - return { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: ["none"] }; - } - if (is(chunk, _SQL.Aliased) && chunk.fieldAlias !== void 0) { - return { sql: escapeName(chunk.fieldAlias), params: [] }; - } - if (is(chunk, Subquery)) { - if (chunk._.isWith) { - return { sql: escapeName(chunk._.alias), params: [] }; - } - return this.buildQueryFromSourceParams([ - new StringChunk("("), - chunk._.sql, - new StringChunk(") "), - new Name(chunk._.alias) - ], config3); - } - if (isPgEnum(chunk)) { - if (chunk.schema) { - return { sql: escapeName(chunk.schema) + "." + escapeName(chunk.enumName), params: [] }; - } - return { sql: escapeName(chunk.enumName), params: [] }; - } - if (isSQLWrapper(chunk)) { - if (chunk.shouldOmitSQLParens?.()) { - return this.buildQueryFromSourceParams([chunk.getSQL()], config3); - } - return this.buildQueryFromSourceParams([ - new StringChunk("("), - chunk.getSQL(), - new StringChunk(")") - ], config3); - } - if (inlineParams) { - return { sql: this.mapInlineParam(chunk, config3), params: [] }; - } - return { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: ["none"] }; - })); - } - mapInlineParam(chunk, { escapeString }) { - if (chunk === null) { - return "null"; - } - if (typeof chunk === "number" || typeof chunk === "boolean") { - return chunk.toString(); - } - if (typeof chunk === "string") { - return escapeString(chunk); - } - if (typeof chunk === "object") { - const mappedValueAsString = chunk.toString(); - if (mappedValueAsString === "[object Object]") { - return escapeString(JSON.stringify(chunk)); - } - return escapeString(mappedValueAsString); - } - throw new Error("Unexpected param value: " + chunk); - } - getSQL() { - return this; - } - as(alias) { - if (alias === void 0) { - return this; - } - return new _SQL.Aliased(this, alias); - } - mapWith(decoder2) { - this.decoder = typeof decoder2 === "function" ? { mapFromDriverValue: decoder2 } : decoder2; - return this; - } - inlineParams() { - this.shouldInlineParams = true; - return this; - } - /** - * This method is used to conditionally include a part of the query. - * - * @param condition - Condition to check - * @returns itself if the condition is `true`, otherwise `undefined` - */ - if(condition) { - return condition ? this : void 0; - } - }; - Name = class { - constructor(value) { - this.value = value; - } - static [entityKind] = "Name"; - brand; - getSQL() { - return new SQL([this]); - } - }; - noopDecoder = { - mapFromDriverValue: (value) => value - }; - noopEncoder = { - mapToDriverValue: (value) => value - }; - noopMapper = { - ...noopDecoder, - ...noopEncoder - }; - Param = class { - /** - * @param value - Parameter value - * @param encoder - Encoder to convert the value to a driver parameter - */ - constructor(value, encoder3 = noopEncoder) { - this.value = value; - this.encoder = encoder3; - } - static [entityKind] = "Param"; - brand; - getSQL() { - return new SQL([this]); - } - }; - ((sql22) => { - function empty() { - return new SQL([]); - } - sql22.empty = empty; - function fromList(list2) { - return new SQL(list2); - } - sql22.fromList = fromList; - function raw(str) { - return new SQL([new StringChunk(str)]); - } - sql22.raw = raw; - function join4(chunks, separator) { - const result = []; - for (const [i5, chunk] of chunks.entries()) { - if (i5 > 0 && separator !== void 0) { - result.push(separator); - } - result.push(chunk); - } - return new SQL(result); - } - sql22.join = join4; - function identifier(value) { - return new Name(value); - } - sql22.identifier = identifier; - function placeholder2(name2) { - return new Placeholder(name2); - } - sql22.placeholder = placeholder2; - function param2(value, encoder3) { - return new Param(value, encoder3); - } - sql22.param = param2; - })(sql || (sql = {})); - ((SQL2) => { - class Aliased { - constructor(sql22, fieldAlias) { - this.sql = sql22; - this.fieldAlias = fieldAlias; - } - static [entityKind] = "SQL.Aliased"; - /** @internal */ - isSelectionField = false; - getSQL() { - return this.sql; - } - /** @internal */ - clone() { - return new Aliased(this.sql, this.fieldAlias); - } - } - SQL2.Aliased = Aliased; - })(SQL || (SQL = {})); - Placeholder = class { - constructor(name2) { - this.name = name2; - } - static [entityKind] = "Placeholder"; - getSQL() { - return new SQL([this]); - } - }; - IsDrizzleView = /* @__PURE__ */ Symbol.for("drizzle:IsDrizzleView"); - View = class { - static [entityKind] = "View"; - /** @internal */ - [ViewBaseConfig]; - /** @internal */ - [IsDrizzleView] = true; - constructor({ name: name2, schema: schema2, selectedFields, query }) { - this[ViewBaseConfig] = { - name: name2, - originalName: name2, - schema: schema2, - selectedFields, - query, - isExisting: !query, - isAlias: false - }; - } - getSQL() { - return new SQL([this]); - } - }; - Column.prototype.getSQL = function() { - return new SQL([this]); - }; - Table.prototype.getSQL = function() { - return new SQL([this]); - }; - Subquery.prototype.getSQL = function() { - return new SQL([this]); - }; - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/utils.js -function mapResultRow(columns, row, joinsNotNullableMap) { - const nullifyMap = {}; - const result = columns.reduce( - (result2, { path: path53, field }, columnIndex) => { - let decoder2; - if (is(field, Column)) { - decoder2 = field; - } else if (is(field, SQL)) { - decoder2 = field.decoder; - } else { - decoder2 = field.sql.decoder; - } - let node = result2; - for (const [pathChunkIndex, pathChunk] of path53.entries()) { - if (pathChunkIndex < path53.length - 1) { - if (!(pathChunk in node)) { - node[pathChunk] = {}; - } - node = node[pathChunk]; - } else { - const rawValue = row[columnIndex]; - const value = node[pathChunk] = rawValue === null ? null : decoder2.mapFromDriverValue(rawValue); - if (joinsNotNullableMap && is(field, Column) && path53.length === 2) { - const objectName = path53[0]; - if (!(objectName in nullifyMap)) { - nullifyMap[objectName] = value === null ? getTableName(field.table) : false; - } else if (typeof nullifyMap[objectName] === "string" && nullifyMap[objectName] !== getTableName(field.table)) { - nullifyMap[objectName] = false; - } - } - } - } - return result2; - }, - {} - ); - if (joinsNotNullableMap && Object.keys(nullifyMap).length > 0) { - for (const [objectName, tableName] of Object.entries(nullifyMap)) { - if (typeof tableName === "string" && !joinsNotNullableMap[tableName]) { - result[objectName] = null; - } - } - } - return result; -} -function orderSelectedFields(fields, pathPrefix) { - return Object.entries(fields).reduce((result, [name, field]) => { - if (typeof name !== "string") { - return result; - } - const newPath = pathPrefix ? [...pathPrefix, name] : [name]; - if (is(field, Column) || is(field, SQL) || is(field, SQL.Aliased)) { - result.push({ path: newPath, field }); - } else if (is(field, Table)) { - result.push(...orderSelectedFields(field[Table.Symbol.Columns], newPath)); - } else { - result.push(...orderSelectedFields(field, newPath)); - } - return result; - }, []); -} -function haveSameKeys(left, right) { - const leftKeys = Object.keys(left); - const rightKeys = Object.keys(right); - if (leftKeys.length !== rightKeys.length) { - return false; - } - for (const [index2, key] of leftKeys.entries()) { - if (key !== rightKeys[index2]) { - return false; - } - } - return true; -} -function mapUpdateSet(table, values2) { - const entries2 = Object.entries(values2).filter(([, value]) => value !== void 0).map(([key, value]) => { - if (is(value, SQL) || is(value, Column)) { - return [key, value]; - } else { - return [key, new Param(value, table[Table.Symbol.Columns][key])]; - } - }); - if (entries2.length === 0) { - throw new Error("No values to set"); - } - return Object.fromEntries(entries2); -} -function applyMixins(baseClass, extendedClasses) { - for (const extendedClass of extendedClasses) { - for (const name of Object.getOwnPropertyNames(extendedClass.prototype)) { - if (name === "constructor") - continue; - Object.defineProperty( - baseClass.prototype, - name, - Object.getOwnPropertyDescriptor(extendedClass.prototype, name) || /* @__PURE__ */ Object.create(null) - ); - } - } -} -function getTableColumns(table) { - return table[Table.Symbol.Columns]; -} -function getTableLikeName(table) { - return is(table, Subquery) ? table._.alias : is(table, View) ? table[ViewBaseConfig].name : is(table, SQL) ? void 0 : table[Table.Symbol.IsAlias] ? table[Table.Symbol.Name] : table[Table.Symbol.BaseName]; -} -function getColumnNameAndConfig(a5, b6) { - return { - name: typeof a5 === "string" && a5.length > 0 ? a5 : "", - config: typeof a5 === "object" ? a5 : b6 - }; -} -function isConfig(data2) { - if (typeof data2 !== "object" || data2 === null) - return false; - if (data2.constructor.name !== "Object") - return false; - if ("logger" in data2) { - const type = typeof data2["logger"]; - if (type !== "boolean" && (type !== "object" || typeof data2["logger"]["logQuery"] !== "function") && type !== "undefined") - return false; - return true; - } - if ("schema" in data2) { - const type = typeof data2["logger"]; - if (type !== "object" && type !== "undefined") - return false; - return true; - } - if ("casing" in data2) { - const type = typeof data2["logger"]; - if (type !== "string" && type !== "undefined") - return false; - return true; - } - if ("mode" in data2) { - if (data2["mode"] !== "default" || data2["mode"] !== "planetscale" || data2["mode"] !== void 0) - return false; - return true; - } - if ("connection" in data2) { - const type = typeof data2["connection"]; - if (type !== "string" && type !== "object" && type !== "undefined") - return false; - return true; - } - if ("client" in data2) { - const type = typeof data2["client"]; - if (type !== "object" && type !== "function" && type !== "undefined") - return false; - return true; - } - if (Object.keys(data2).length === 0) - return true; - return false; -} -var init_utils = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/utils.js"() { - init_column(); - init_entity(); - init_sql(); - init_subquery(); - init_table(); - init_view_common(); - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/query-builders/delete.js -var PgDeleteBase; -var init_delete = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/query-builders/delete.js"() { - init_entity(); - init_query_promise(); - init_table(); - init_tracing(); - init_utils(); - PgDeleteBase = class extends QueryPromise { - constructor(table, session, dialect, withList) { - super(); - this.session = session; - this.dialect = dialect; - this.config = { table, withList }; - } - static [entityKind] = "PgDelete"; - config; - /** - * Adds a `where` clause to the query. - * - * Calling this method will delete only those rows that fulfill a specified condition. - * - * See docs: {@link https://orm.drizzle.team/docs/delete} - * - * @param where the `where` clause. - * - * @example - * You can use conditional operators and `sql function` to filter the rows to be deleted. - * - * ```ts - * // Delete all cars with green color - * await db.delete(cars).where(eq(cars.color, 'green')); - * // or - * await db.delete(cars).where(sql`${cars.color} = 'green'`) - * ``` - * - * You can logically combine conditional operators with `and()` and `or()` operators: - * - * ```ts - * // Delete all BMW cars with a green color - * await db.delete(cars).where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW'))); - * - * // Delete all cars with the green or blue color - * await db.delete(cars).where(or(eq(cars.color, 'green'), eq(cars.color, 'blue'))); - * ``` - */ - where(where) { - this.config.where = where; - return this; - } - returning(fields = this.config.table[Table.Symbol.Columns]) { - this.config.returning = orderSelectedFields(fields); - return this; - } - /** @internal */ - getSQL() { - return this.dialect.buildDeleteQuery(this.config); - } - toSQL() { - const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL()); - return rest; - } - /** @internal */ - _prepare(name) { - return tracer.startActiveSpan("drizzle.prepareQuery", () => { - return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), this.config.returning, name, true); - }); - } - prepare(name) { - return this._prepare(name); - } - authToken; - /** @internal */ - setToken(token) { - this.authToken = token; - return this; - } - execute = (placeholderValues) => { - return tracer.startActiveSpan("drizzle.operation", () => { - return this._prepare().execute(placeholderValues, this.authToken); - }); - }; - $dynamic() { - return this; - } - }; - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/alias.js -function aliasedTable(table, tableAlias) { - return new Proxy(table, new TableAliasProxyHandler(tableAlias, false)); -} -function aliasedTableColumn(column, tableAlias) { - return new Proxy( - column, - new ColumnAliasProxyHandler(new Proxy(column.table, new TableAliasProxyHandler(tableAlias, false))) - ); -} -function mapColumnsInAliasedSQLToAlias(query, alias) { - return new SQL.Aliased(mapColumnsInSQLToAlias(query.sql, alias), query.fieldAlias); -} -function mapColumnsInSQLToAlias(query, alias) { - return sql.join(query.queryChunks.map((c5) => { - if (is(c5, Column)) { - return aliasedTableColumn(c5, alias); - } - if (is(c5, SQL)) { - return mapColumnsInSQLToAlias(c5, alias); - } - if (is(c5, SQL.Aliased)) { - return mapColumnsInAliasedSQLToAlias(c5, alias); - } - return c5; - })); -} -var ColumnAliasProxyHandler, TableAliasProxyHandler, RelationTableAliasProxyHandler; -var init_alias = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/alias.js"() { - init_column(); - init_entity(); - init_sql(); - init_table(); - init_view_common(); - ColumnAliasProxyHandler = class { - constructor(table) { - this.table = table; - } - static [entityKind] = "ColumnAliasProxyHandler"; - get(columnObj, prop) { - if (prop === "table") { - return this.table; - } - return columnObj[prop]; - } - }; - TableAliasProxyHandler = class { - constructor(alias, replaceOriginalName) { - this.alias = alias; - this.replaceOriginalName = replaceOriginalName; - } - static [entityKind] = "TableAliasProxyHandler"; - get(target, prop) { - if (prop === Table.Symbol.IsAlias) { - return true; - } - if (prop === Table.Symbol.Name) { - return this.alias; - } - if (this.replaceOriginalName && prop === Table.Symbol.OriginalName) { - return this.alias; - } - if (prop === ViewBaseConfig) { - return { - ...target[ViewBaseConfig], - name: this.alias, - isAlias: true - }; - } - if (prop === Table.Symbol.Columns) { - const columns = target[Table.Symbol.Columns]; - if (!columns) { - return columns; - } - const proxiedColumns = {}; - Object.keys(columns).map((key) => { - proxiedColumns[key] = new Proxy( - columns[key], - new ColumnAliasProxyHandler(new Proxy(target, this)) - ); - }); - return proxiedColumns; - } - const value = target[prop]; - if (is(value, Column)) { - return new Proxy(value, new ColumnAliasProxyHandler(new Proxy(target, this))); - } - return value; - } - }; - RelationTableAliasProxyHandler = class { - constructor(alias) { - this.alias = alias; - } - static [entityKind] = "RelationTableAliasProxyHandler"; - get(target, prop) { - if (prop === "sourceTable") { - return aliasedTable(target.sourceTable, this.alias); - } - return target[prop]; - } - }; - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/casing.js -function toSnakeCase(input) { - const words = input.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? []; - return words.map((word) => word.toLowerCase()).join("_"); -} -function toCamelCase(input) { - const words = input.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? []; - return words.reduce((acc, word, i5) => { - const formattedWord = i5 === 0 ? word.toLowerCase() : `${word[0].toUpperCase()}${word.slice(1)}`; - return acc + formattedWord; - }, ""); -} -function noopCase(input) { - return input; -} -var CasingCache; -var init_casing = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/casing.js"() { - init_entity(); - init_table(); - CasingCache = class { - static [entityKind] = "CasingCache"; - /** @internal */ - cache = {}; - cachedTables = {}; - convert; - constructor(casing) { - this.convert = casing === "snake_case" ? toSnakeCase : casing === "camelCase" ? toCamelCase : noopCase; - } - getColumnCasing(column) { - if (!column.keyAsName) - return column.name; - const schema2 = column.table[Table.Symbol.Schema] ?? "public"; - const tableName = column.table[Table.Symbol.OriginalName]; - const key = `${schema2}.${tableName}.${column.name}`; - if (!this.cache[key]) { - this.cacheTable(column.table); - } - return this.cache[key]; - } - cacheTable(table) { - const schema2 = table[Table.Symbol.Schema] ?? "public"; - const tableName = table[Table.Symbol.OriginalName]; - const tableKey = `${schema2}.${tableName}`; - if (!this.cachedTables[tableKey]) { - for (const column of Object.values(table[Table.Symbol.Columns])) { - const columnKey = `${tableKey}.${column.name}`; - this.cache[columnKey] = this.convert(column.name); - } - this.cachedTables[tableKey] = true; - } - } - clearCache() { - this.cache = {}; - this.cachedTables = {}; - } - }; - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/errors.js -var DrizzleError, TransactionRollbackError; -var init_errors2 = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/errors.js"() { - init_entity(); - DrizzleError = class extends Error { - static [entityKind] = "DrizzleError"; - constructor({ message: message2, cause }) { - super(message2); - this.name = "DrizzleError"; - this.cause = cause; - } - }; - TransactionRollbackError = class extends DrizzleError { - static [entityKind] = "TransactionRollbackError"; - constructor() { - super({ message: "Rollback" }); - } - }; - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/int.common.js -var PgIntColumnBaseBuilder; -var init_int_common = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/int.common.js"() { - init_entity(); - init_common(); - PgIntColumnBaseBuilder = class extends PgColumnBuilder { - static [entityKind] = "PgIntColumnBaseBuilder"; - generatedAlwaysAsIdentity(sequence) { - if (sequence) { - const { name, ...options } = sequence; - this.config.generatedIdentity = { - type: "always", - sequenceName: name, - sequenceOptions: options - }; - } else { - this.config.generatedIdentity = { - type: "always" - }; - } - this.config.hasDefault = true; - this.config.notNull = true; - return this; - } - generatedByDefaultAsIdentity(sequence) { - if (sequence) { - const { name, ...options } = sequence; - this.config.generatedIdentity = { - type: "byDefault", - sequenceName: name, - sequenceOptions: options - }; - } else { - this.config.generatedIdentity = { - type: "byDefault" - }; - } - this.config.hasDefault = true; - this.config.notNull = true; - return this; - } - }; - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/bigint.js -function bigint(a5, b6) { - const { name, config: config3 } = getColumnNameAndConfig(a5, b6); - if (config3.mode === "number") { - return new PgBigInt53Builder(name); - } - return new PgBigInt64Builder(name); -} -var PgBigInt53Builder, PgBigInt53, PgBigInt64Builder, PgBigInt64; -var init_bigint = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/bigint.js"() { - init_entity(); - init_utils(); - init_common(); - init_int_common(); - PgBigInt53Builder = class extends PgIntColumnBaseBuilder { - static [entityKind] = "PgBigInt53Builder"; - constructor(name) { - super(name, "number", "PgBigInt53"); - } - /** @internal */ - build(table) { - return new PgBigInt53(table, this.config); - } - }; - PgBigInt53 = class extends PgColumn { - static [entityKind] = "PgBigInt53"; - getSQLType() { - return "bigint"; - } - mapFromDriverValue(value) { - if (typeof value === "number") { - return value; - } - return Number(value); - } - }; - PgBigInt64Builder = class extends PgIntColumnBaseBuilder { - static [entityKind] = "PgBigInt64Builder"; - constructor(name) { - super(name, "bigint", "PgBigInt64"); - } - /** @internal */ - build(table) { - return new PgBigInt64( - table, - this.config - ); - } - }; - PgBigInt64 = class extends PgColumn { - static [entityKind] = "PgBigInt64"; - getSQLType() { - return "bigint"; - } - // eslint-disable-next-line unicorn/prefer-native-coercion-functions - mapFromDriverValue(value) { - return BigInt(value); - } - }; - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/bigserial.js -function bigserial(a5, b6) { - const { name, config: config3 } = getColumnNameAndConfig(a5, b6); - if (config3.mode === "number") { - return new PgBigSerial53Builder(name); - } - return new PgBigSerial64Builder(name); -} -var PgBigSerial53Builder, PgBigSerial53, PgBigSerial64Builder, PgBigSerial64; -var init_bigserial = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/bigserial.js"() { - init_entity(); - init_utils(); - init_common(); - PgBigSerial53Builder = class extends PgColumnBuilder { - static [entityKind] = "PgBigSerial53Builder"; - constructor(name) { - super(name, "number", "PgBigSerial53"); - this.config.hasDefault = true; - this.config.notNull = true; - } - /** @internal */ - build(table) { - return new PgBigSerial53( - table, - this.config - ); - } - }; - PgBigSerial53 = class extends PgColumn { - static [entityKind] = "PgBigSerial53"; - getSQLType() { - return "bigserial"; - } - mapFromDriverValue(value) { - if (typeof value === "number") { - return value; - } - return Number(value); - } - }; - PgBigSerial64Builder = class extends PgColumnBuilder { - static [entityKind] = "PgBigSerial64Builder"; - constructor(name) { - super(name, "bigint", "PgBigSerial64"); - this.config.hasDefault = true; - } - /** @internal */ - build(table) { - return new PgBigSerial64( - table, - this.config - ); - } - }; - PgBigSerial64 = class extends PgColumn { - static [entityKind] = "PgBigSerial64"; - getSQLType() { - return "bigserial"; - } - // eslint-disable-next-line unicorn/prefer-native-coercion-functions - mapFromDriverValue(value) { - return BigInt(value); - } - }; - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/boolean.js -function boolean(name) { - return new PgBooleanBuilder(name ?? ""); -} -var PgBooleanBuilder, PgBoolean; -var init_boolean = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/boolean.js"() { - init_entity(); - init_common(); - PgBooleanBuilder = class extends PgColumnBuilder { - static [entityKind] = "PgBooleanBuilder"; - constructor(name) { - super(name, "boolean", "PgBoolean"); - } - /** @internal */ - build(table) { - return new PgBoolean(table, this.config); - } - }; - PgBoolean = class extends PgColumn { - static [entityKind] = "PgBoolean"; - getSQLType() { - return "boolean"; - } - }; - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/char.js -function char(a5, b6 = {}) { - const { name, config: config3 } = getColumnNameAndConfig(a5, b6); - return new PgCharBuilder(name, config3); -} -var PgCharBuilder, PgChar; -var init_char = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/char.js"() { - init_entity(); - init_utils(); - init_common(); - PgCharBuilder = class extends PgColumnBuilder { - static [entityKind] = "PgCharBuilder"; - constructor(name, config3) { - super(name, "string", "PgChar"); - this.config.length = config3.length; - this.config.enumValues = config3.enum; - } - /** @internal */ - build(table) { - return new PgChar( - table, - this.config - ); - } - }; - PgChar = class extends PgColumn { - static [entityKind] = "PgChar"; - length = this.config.length; - enumValues = this.config.enumValues; - getSQLType() { - return this.length === void 0 ? `char` : `char(${this.length})`; - } - }; - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/cidr.js -function cidr(name) { - return new PgCidrBuilder(name ?? ""); -} -var PgCidrBuilder, PgCidr; -var init_cidr = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/cidr.js"() { - init_entity(); - init_common(); - PgCidrBuilder = class extends PgColumnBuilder { - static [entityKind] = "PgCidrBuilder"; - constructor(name) { - super(name, "string", "PgCidr"); - } - /** @internal */ - build(table) { - return new PgCidr(table, this.config); - } - }; - PgCidr = class extends PgColumn { - static [entityKind] = "PgCidr"; - getSQLType() { - return "cidr"; - } - }; - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/custom.js -function customType(customTypeParams) { - return (a5, b6) => { - const { name, config: config3 } = getColumnNameAndConfig(a5, b6); - return new PgCustomColumnBuilder(name, config3, customTypeParams); - }; -} -var PgCustomColumnBuilder, PgCustomColumn; -var init_custom = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/custom.js"() { - init_entity(); - init_utils(); - init_common(); - PgCustomColumnBuilder = class extends PgColumnBuilder { - static [entityKind] = "PgCustomColumnBuilder"; - constructor(name, fieldConfig, customTypeParams) { - super(name, "custom", "PgCustomColumn"); - this.config.fieldConfig = fieldConfig; - this.config.customTypeParams = customTypeParams; - } - /** @internal */ - build(table) { - return new PgCustomColumn( - table, - this.config - ); - } - }; - PgCustomColumn = class extends PgColumn { - static [entityKind] = "PgCustomColumn"; - sqlName; - mapTo; - mapFrom; - constructor(table, config3) { - super(table, config3); - this.sqlName = config3.customTypeParams.dataType(config3.fieldConfig); - this.mapTo = config3.customTypeParams.toDriver; - this.mapFrom = config3.customTypeParams.fromDriver; - } - getSQLType() { - return this.sqlName; - } - mapFromDriverValue(value) { - return typeof this.mapFrom === "function" ? this.mapFrom(value) : value; - } - mapToDriverValue(value) { - return typeof this.mapTo === "function" ? this.mapTo(value) : value; - } - }; - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/date.common.js -var PgDateColumnBaseBuilder; -var init_date_common = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/date.common.js"() { - init_entity(); - init_sql(); - init_common(); - PgDateColumnBaseBuilder = class extends PgColumnBuilder { - static [entityKind] = "PgDateColumnBaseBuilder"; - defaultNow() { - return this.default(sql`now()`); - } - }; - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/date.js -function date(a5, b6) { - const { name, config: config3 } = getColumnNameAndConfig(a5, b6); - if (config3?.mode === "date") { - return new PgDateBuilder(name); - } - return new PgDateStringBuilder(name); -} -var PgDateBuilder, PgDate, PgDateStringBuilder, PgDateString; -var init_date = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/date.js"() { - init_entity(); - init_utils(); - init_common(); - init_date_common(); - PgDateBuilder = class extends PgDateColumnBaseBuilder { - static [entityKind] = "PgDateBuilder"; - constructor(name) { - super(name, "date", "PgDate"); - } - /** @internal */ - build(table) { - return new PgDate(table, this.config); - } - }; - PgDate = class extends PgColumn { - static [entityKind] = "PgDate"; - getSQLType() { - return "date"; - } - mapFromDriverValue(value) { - return new Date(value); - } - mapToDriverValue(value) { - return value.toISOString(); - } - }; - PgDateStringBuilder = class extends PgDateColumnBaseBuilder { - static [entityKind] = "PgDateStringBuilder"; - constructor(name) { - super(name, "string", "PgDateString"); - } - /** @internal */ - build(table) { - return new PgDateString( - table, - this.config - ); - } - }; - PgDateString = class extends PgColumn { - static [entityKind] = "PgDateString"; - getSQLType() { - return "date"; - } - }; - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/double-precision.js -function doublePrecision(name) { - return new PgDoublePrecisionBuilder(name ?? ""); -} -var PgDoublePrecisionBuilder, PgDoublePrecision; -var init_double_precision = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/double-precision.js"() { - init_entity(); - init_common(); - PgDoublePrecisionBuilder = class extends PgColumnBuilder { - static [entityKind] = "PgDoublePrecisionBuilder"; - constructor(name) { - super(name, "number", "PgDoublePrecision"); - } - /** @internal */ - build(table) { - return new PgDoublePrecision( - table, - this.config - ); - } - }; - PgDoublePrecision = class extends PgColumn { - static [entityKind] = "PgDoublePrecision"; - getSQLType() { - return "double precision"; - } - mapFromDriverValue(value) { - if (typeof value === "string") { - return Number.parseFloat(value); - } - return value; - } - }; - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/inet.js -function inet(name) { - return new PgInetBuilder(name ?? ""); -} -var PgInetBuilder, PgInet; -var init_inet = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/inet.js"() { - init_entity(); - init_common(); - PgInetBuilder = class extends PgColumnBuilder { - static [entityKind] = "PgInetBuilder"; - constructor(name) { - super(name, "string", "PgInet"); - } - /** @internal */ - build(table) { - return new PgInet(table, this.config); - } - }; - PgInet = class extends PgColumn { - static [entityKind] = "PgInet"; - getSQLType() { - return "inet"; - } - }; - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/integer.js -function integer(name) { - return new PgIntegerBuilder(name ?? ""); -} -var PgIntegerBuilder, PgInteger; -var init_integer = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/integer.js"() { - init_entity(); - init_common(); - init_int_common(); - PgIntegerBuilder = class extends PgIntColumnBaseBuilder { - static [entityKind] = "PgIntegerBuilder"; - constructor(name) { - super(name, "number", "PgInteger"); - } - /** @internal */ - build(table) { - return new PgInteger(table, this.config); - } - }; - PgInteger = class extends PgColumn { - static [entityKind] = "PgInteger"; - getSQLType() { - return "integer"; - } - mapFromDriverValue(value) { - if (typeof value === "string") { - return Number.parseInt(value); - } - return value; - } - }; - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/interval.js -function interval(a5, b6 = {}) { - const { name, config: config3 } = getColumnNameAndConfig(a5, b6); - return new PgIntervalBuilder(name, config3); -} -var PgIntervalBuilder, PgInterval; -var init_interval = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/interval.js"() { - init_entity(); - init_utils(); - init_common(); - PgIntervalBuilder = class extends PgColumnBuilder { - static [entityKind] = "PgIntervalBuilder"; - constructor(name, intervalConfig) { - super(name, "string", "PgInterval"); - this.config.intervalConfig = intervalConfig; - } - /** @internal */ - build(table) { - return new PgInterval(table, this.config); - } - }; - PgInterval = class extends PgColumn { - static [entityKind] = "PgInterval"; - fields = this.config.intervalConfig.fields; - precision = this.config.intervalConfig.precision; - getSQLType() { - const fields = this.fields ? ` ${this.fields}` : ""; - const precision = this.precision ? `(${this.precision})` : ""; - return `interval${fields}${precision}`; - } - }; - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/json.js -function json(name) { - return new PgJsonBuilder(name ?? ""); -} -var PgJsonBuilder, PgJson; -var init_json = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/json.js"() { - init_entity(); - init_common(); - PgJsonBuilder = class extends PgColumnBuilder { - static [entityKind] = "PgJsonBuilder"; - constructor(name) { - super(name, "json", "PgJson"); - } - /** @internal */ - build(table) { - return new PgJson(table, this.config); - } - }; - PgJson = class extends PgColumn { - static [entityKind] = "PgJson"; - constructor(table, config3) { - super(table, config3); - } - getSQLType() { - return "json"; - } - mapToDriverValue(value) { - return JSON.stringify(value); - } - mapFromDriverValue(value) { - if (typeof value === "string") { - try { - return JSON.parse(value); - } catch { - return value; - } - } - return value; - } - }; - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/jsonb.js -function jsonb(name) { - return new PgJsonbBuilder(name ?? ""); -} -var PgJsonbBuilder, PgJsonb; -var init_jsonb = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/jsonb.js"() { - init_entity(); - init_common(); - PgJsonbBuilder = class extends PgColumnBuilder { - static [entityKind] = "PgJsonbBuilder"; - constructor(name) { - super(name, "json", "PgJsonb"); - } - /** @internal */ - build(table) { - return new PgJsonb(table, this.config); - } - }; - PgJsonb = class extends PgColumn { - static [entityKind] = "PgJsonb"; - constructor(table, config3) { - super(table, config3); - } - getSQLType() { - return "jsonb"; - } - mapToDriverValue(value) { - return JSON.stringify(value); - } - mapFromDriverValue(value) { - if (typeof value === "string") { - try { - return JSON.parse(value); - } catch { - return value; - } - } - return value; - } - }; - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/line.js -function line(a5, b6) { - const { name, config: config3 } = getColumnNameAndConfig(a5, b6); - if (!config3?.mode || config3.mode === "tuple") { - return new PgLineBuilder(name); - } - return new PgLineABCBuilder(name); -} -var PgLineBuilder, PgLineTuple, PgLineABCBuilder, PgLineABC; -var init_line = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/line.js"() { - init_entity(); - init_utils(); - init_common(); - PgLineBuilder = class extends PgColumnBuilder { - static [entityKind] = "PgLineBuilder"; - constructor(name) { - super(name, "array", "PgLine"); - } - /** @internal */ - build(table) { - return new PgLineTuple( - table, - this.config - ); - } - }; - PgLineTuple = class extends PgColumn { - static [entityKind] = "PgLine"; - getSQLType() { - return "line"; - } - mapFromDriverValue(value) { - const [a5, b6, c5] = value.slice(1, -1).split(","); - return [Number.parseFloat(a5), Number.parseFloat(b6), Number.parseFloat(c5)]; - } - mapToDriverValue(value) { - return `{${value[0]},${value[1]},${value[2]}}`; - } - }; - PgLineABCBuilder = class extends PgColumnBuilder { - static [entityKind] = "PgLineABCBuilder"; - constructor(name) { - super(name, "json", "PgLineABC"); - } - /** @internal */ - build(table) { - return new PgLineABC( - table, - this.config - ); - } - }; - PgLineABC = class extends PgColumn { - static [entityKind] = "PgLineABC"; - getSQLType() { - return "line"; - } - mapFromDriverValue(value) { - const [a5, b6, c5] = value.slice(1, -1).split(","); - return { a: Number.parseFloat(a5), b: Number.parseFloat(b6), c: Number.parseFloat(c5) }; - } - mapToDriverValue(value) { - return `{${value.a},${value.b},${value.c}}`; - } - }; - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/macaddr.js -function macaddr(name) { - return new PgMacaddrBuilder(name ?? ""); -} -var PgMacaddrBuilder, PgMacaddr; -var init_macaddr = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/macaddr.js"() { - init_entity(); - init_common(); - PgMacaddrBuilder = class extends PgColumnBuilder { - static [entityKind] = "PgMacaddrBuilder"; - constructor(name) { - super(name, "string", "PgMacaddr"); - } - /** @internal */ - build(table) { - return new PgMacaddr(table, this.config); - } - }; - PgMacaddr = class extends PgColumn { - static [entityKind] = "PgMacaddr"; - getSQLType() { - return "macaddr"; - } - }; - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/macaddr8.js -function macaddr8(name) { - return new PgMacaddr8Builder(name ?? ""); -} -var PgMacaddr8Builder, PgMacaddr8; -var init_macaddr8 = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/macaddr8.js"() { - init_entity(); - init_common(); - PgMacaddr8Builder = class extends PgColumnBuilder { - static [entityKind] = "PgMacaddr8Builder"; - constructor(name) { - super(name, "string", "PgMacaddr8"); - } - /** @internal */ - build(table) { - return new PgMacaddr8(table, this.config); - } - }; - PgMacaddr8 = class extends PgColumn { - static [entityKind] = "PgMacaddr8"; - getSQLType() { - return "macaddr8"; - } - }; - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/numeric.js -function numeric(a5, b6) { - const { name, config: config3 } = getColumnNameAndConfig(a5, b6); - return new PgNumericBuilder(name, config3?.precision, config3?.scale); -} -var PgNumericBuilder, PgNumeric; -var init_numeric = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/numeric.js"() { - init_entity(); - init_utils(); - init_common(); - PgNumericBuilder = class extends PgColumnBuilder { - static [entityKind] = "PgNumericBuilder"; - constructor(name, precision, scale) { - super(name, "string", "PgNumeric"); - this.config.precision = precision; - this.config.scale = scale; - } - /** @internal */ - build(table) { - return new PgNumeric(table, this.config); - } - }; - PgNumeric = class extends PgColumn { - static [entityKind] = "PgNumeric"; - precision; - scale; - constructor(table, config3) { - super(table, config3); - this.precision = config3.precision; - this.scale = config3.scale; - } - getSQLType() { - if (this.precision !== void 0 && this.scale !== void 0) { - return `numeric(${this.precision}, ${this.scale})`; - } else if (this.precision === void 0) { - return "numeric"; - } else { - return `numeric(${this.precision})`; - } - } - }; - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/point.js -function point(a5, b6) { - const { name, config: config3 } = getColumnNameAndConfig(a5, b6); - if (!config3?.mode || config3.mode === "tuple") { - return new PgPointTupleBuilder(name); - } - return new PgPointObjectBuilder(name); -} -var PgPointTupleBuilder, PgPointTuple, PgPointObjectBuilder, PgPointObject; -var init_point = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/point.js"() { - init_entity(); - init_utils(); - init_common(); - PgPointTupleBuilder = class extends PgColumnBuilder { - static [entityKind] = "PgPointTupleBuilder"; - constructor(name) { - super(name, "array", "PgPointTuple"); - } - /** @internal */ - build(table) { - return new PgPointTuple( - table, - this.config - ); - } - }; - PgPointTuple = class extends PgColumn { - static [entityKind] = "PgPointTuple"; - getSQLType() { - return "point"; - } - mapFromDriverValue(value) { - if (typeof value === "string") { - const [x5, y2] = value.slice(1, -1).split(","); - return [Number.parseFloat(x5), Number.parseFloat(y2)]; - } - return [value.x, value.y]; - } - mapToDriverValue(value) { - return `(${value[0]},${value[1]})`; - } - }; - PgPointObjectBuilder = class extends PgColumnBuilder { - static [entityKind] = "PgPointObjectBuilder"; - constructor(name) { - super(name, "json", "PgPointObject"); - } - /** @internal */ - build(table) { - return new PgPointObject( - table, - this.config - ); - } - }; - PgPointObject = class extends PgColumn { - static [entityKind] = "PgPointObject"; - getSQLType() { - return "point"; - } - mapFromDriverValue(value) { - if (typeof value === "string") { - const [x5, y2] = value.slice(1, -1).split(","); - return { x: Number.parseFloat(x5), y: Number.parseFloat(y2) }; - } - return value; - } - mapToDriverValue(value) { - return `(${value.x},${value.y})`; - } - }; - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/postgis_extension/utils.js -function hexToBytes(hex4) { - const bytes = []; - for (let c5 = 0; c5 < hex4.length; c5 += 2) { - bytes.push(Number.parseInt(hex4.slice(c5, c5 + 2), 16)); - } - return new Uint8Array(bytes); -} -function bytesToFloat64(bytes, offset) { - const buffer2 = new ArrayBuffer(8); - const view = new DataView(buffer2); - for (let i5 = 0; i5 < 8; i5++) { - view.setUint8(i5, bytes[offset + i5]); - } - return view.getFloat64(0, true); -} -function parseEWKB(hex4) { - const bytes = hexToBytes(hex4); - let offset = 0; - const byteOrder = bytes[offset]; - offset += 1; - const view = new DataView(bytes.buffer); - const geomType = view.getUint32(offset, byteOrder === 1); - offset += 4; - let _srid; - if (geomType & 536870912) { - _srid = view.getUint32(offset, byteOrder === 1); - offset += 4; - } - if ((geomType & 65535) === 1) { - const x5 = bytesToFloat64(bytes, offset); - offset += 8; - const y2 = bytesToFloat64(bytes, offset); - offset += 8; - return [x5, y2]; - } - throw new Error("Unsupported geometry type"); -} -var init_utils2 = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/postgis_extension/utils.js"() { - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/postgis_extension/geometry.js -function geometry(a5, b6) { - const { name, config: config3 } = getColumnNameAndConfig(a5, b6); - if (!config3?.mode || config3.mode === "tuple") { - return new PgGeometryBuilder(name); - } - return new PgGeometryObjectBuilder(name); -} -var PgGeometryBuilder, PgGeometry, PgGeometryObjectBuilder, PgGeometryObject; -var init_geometry = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/postgis_extension/geometry.js"() { - init_entity(); - init_utils(); - init_common(); - init_utils2(); - PgGeometryBuilder = class extends PgColumnBuilder { - static [entityKind] = "PgGeometryBuilder"; - constructor(name) { - super(name, "array", "PgGeometry"); - } - /** @internal */ - build(table) { - return new PgGeometry( - table, - this.config - ); - } - }; - PgGeometry = class extends PgColumn { - static [entityKind] = "PgGeometry"; - getSQLType() { - return "geometry(point)"; - } - mapFromDriverValue(value) { - return parseEWKB(value); - } - mapToDriverValue(value) { - return `point(${value[0]} ${value[1]})`; - } - }; - PgGeometryObjectBuilder = class extends PgColumnBuilder { - static [entityKind] = "PgGeometryObjectBuilder"; - constructor(name) { - super(name, "json", "PgGeometryObject"); - } - /** @internal */ - build(table) { - return new PgGeometryObject( - table, - this.config - ); - } - }; - PgGeometryObject = class extends PgColumn { - static [entityKind] = "PgGeometryObject"; - getSQLType() { - return "geometry(point)"; - } - mapFromDriverValue(value) { - const parsed = parseEWKB(value); - return { x: parsed[0], y: parsed[1] }; - } - mapToDriverValue(value) { - return `point(${value.x} ${value.y})`; - } - }; - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/real.js -function real(name) { - return new PgRealBuilder(name ?? ""); -} -var PgRealBuilder, PgReal; -var init_real = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/real.js"() { - init_entity(); - init_common(); - PgRealBuilder = class extends PgColumnBuilder { - static [entityKind] = "PgRealBuilder"; - constructor(name, length) { - super(name, "number", "PgReal"); - this.config.length = length; - } - /** @internal */ - build(table) { - return new PgReal(table, this.config); - } - }; - PgReal = class extends PgColumn { - static [entityKind] = "PgReal"; - constructor(table, config3) { - super(table, config3); - } - getSQLType() { - return "real"; - } - mapFromDriverValue = (value) => { - if (typeof value === "string") { - return Number.parseFloat(value); - } - return value; - }; - }; - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/serial.js -function serial(name) { - return new PgSerialBuilder(name ?? ""); -} -var PgSerialBuilder, PgSerial; -var init_serial = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/serial.js"() { - init_entity(); - init_common(); - PgSerialBuilder = class extends PgColumnBuilder { - static [entityKind] = "PgSerialBuilder"; - constructor(name) { - super(name, "number", "PgSerial"); - this.config.hasDefault = true; - this.config.notNull = true; - } - /** @internal */ - build(table) { - return new PgSerial(table, this.config); - } - }; - PgSerial = class extends PgColumn { - static [entityKind] = "PgSerial"; - getSQLType() { - return "serial"; - } - }; - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/smallint.js -function smallint(name) { - return new PgSmallIntBuilder(name ?? ""); -} -var PgSmallIntBuilder, PgSmallInt; -var init_smallint = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/smallint.js"() { - init_entity(); - init_common(); - init_int_common(); - PgSmallIntBuilder = class extends PgIntColumnBaseBuilder { - static [entityKind] = "PgSmallIntBuilder"; - constructor(name) { - super(name, "number", "PgSmallInt"); - } - /** @internal */ - build(table) { - return new PgSmallInt(table, this.config); - } - }; - PgSmallInt = class extends PgColumn { - static [entityKind] = "PgSmallInt"; - getSQLType() { - return "smallint"; - } - mapFromDriverValue = (value) => { - if (typeof value === "string") { - return Number(value); - } - return value; - }; - }; - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/smallserial.js -function smallserial(name) { - return new PgSmallSerialBuilder(name ?? ""); -} -var PgSmallSerialBuilder, PgSmallSerial; -var init_smallserial = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/smallserial.js"() { - init_entity(); - init_common(); - PgSmallSerialBuilder = class extends PgColumnBuilder { - static [entityKind] = "PgSmallSerialBuilder"; - constructor(name) { - super(name, "number", "PgSmallSerial"); - this.config.hasDefault = true; - this.config.notNull = true; - } - /** @internal */ - build(table) { - return new PgSmallSerial( - table, - this.config - ); - } - }; - PgSmallSerial = class extends PgColumn { - static [entityKind] = "PgSmallSerial"; - getSQLType() { - return "smallserial"; - } - }; - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/text.js -function text(a5, b6 = {}) { - const { name, config: config3 } = getColumnNameAndConfig(a5, b6); - return new PgTextBuilder(name, config3); -} -var PgTextBuilder, PgText; -var init_text = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/text.js"() { - init_entity(); - init_utils(); - init_common(); - PgTextBuilder = class extends PgColumnBuilder { - static [entityKind] = "PgTextBuilder"; - constructor(name, config3) { - super(name, "string", "PgText"); - this.config.enumValues = config3.enum; - } - /** @internal */ - build(table) { - return new PgText(table, this.config); - } - }; - PgText = class extends PgColumn { - static [entityKind] = "PgText"; - enumValues = this.config.enumValues; - getSQLType() { - return "text"; - } - }; - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/time.js -function time(a5, b6 = {}) { - const { name, config: config3 } = getColumnNameAndConfig(a5, b6); - return new PgTimeBuilder(name, config3.withTimezone ?? false, config3.precision); -} -var PgTimeBuilder, PgTime; -var init_time = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/time.js"() { - init_entity(); - init_utils(); - init_common(); - init_date_common(); - PgTimeBuilder = class extends PgDateColumnBaseBuilder { - constructor(name, withTimezone, precision) { - super(name, "string", "PgTime"); - this.withTimezone = withTimezone; - this.precision = precision; - this.config.withTimezone = withTimezone; - this.config.precision = precision; - } - static [entityKind] = "PgTimeBuilder"; - /** @internal */ - build(table) { - return new PgTime(table, this.config); - } - }; - PgTime = class extends PgColumn { - static [entityKind] = "PgTime"; - withTimezone; - precision; - constructor(table, config3) { - super(table, config3); - this.withTimezone = config3.withTimezone; - this.precision = config3.precision; - } - getSQLType() { - const precision = this.precision === void 0 ? "" : `(${this.precision})`; - return `time${precision}${this.withTimezone ? " with time zone" : ""}`; - } - }; - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/timestamp.js -function timestamp(a5, b6 = {}) { - const { name, config: config3 } = getColumnNameAndConfig(a5, b6); - if (config3?.mode === "string") { - return new PgTimestampStringBuilder(name, config3.withTimezone ?? false, config3.precision); - } - return new PgTimestampBuilder(name, config3?.withTimezone ?? false, config3?.precision); -} -var PgTimestampBuilder, PgTimestamp, PgTimestampStringBuilder, PgTimestampString; -var init_timestamp = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/timestamp.js"() { - init_entity(); - init_utils(); - init_common(); - init_date_common(); - PgTimestampBuilder = class extends PgDateColumnBaseBuilder { - static [entityKind] = "PgTimestampBuilder"; - constructor(name, withTimezone, precision) { - super(name, "date", "PgTimestamp"); - this.config.withTimezone = withTimezone; - this.config.precision = precision; - } - /** @internal */ - build(table) { - return new PgTimestamp(table, this.config); - } - }; - PgTimestamp = class extends PgColumn { - static [entityKind] = "PgTimestamp"; - withTimezone; - precision; - constructor(table, config3) { - super(table, config3); - this.withTimezone = config3.withTimezone; - this.precision = config3.precision; - } - getSQLType() { - const precision = this.precision === void 0 ? "" : ` (${this.precision})`; - return `timestamp${precision}${this.withTimezone ? " with time zone" : ""}`; - } - mapFromDriverValue = (value) => { - return new Date(this.withTimezone ? value : value + "+0000"); - }; - mapToDriverValue = (value) => { - return value.toISOString(); - }; - }; - PgTimestampStringBuilder = class extends PgDateColumnBaseBuilder { - static [entityKind] = "PgTimestampStringBuilder"; - constructor(name, withTimezone, precision) { - super(name, "string", "PgTimestampString"); - this.config.withTimezone = withTimezone; - this.config.precision = precision; - } - /** @internal */ - build(table) { - return new PgTimestampString( - table, - this.config - ); - } - }; - PgTimestampString = class extends PgColumn { - static [entityKind] = "PgTimestampString"; - withTimezone; - precision; - constructor(table, config3) { - super(table, config3); - this.withTimezone = config3.withTimezone; - this.precision = config3.precision; - } - getSQLType() { - const precision = this.precision === void 0 ? "" : `(${this.precision})`; - return `timestamp${precision}${this.withTimezone ? " with time zone" : ""}`; - } - }; - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/uuid.js -function uuid(name) { - return new PgUUIDBuilder(name ?? ""); -} -var PgUUIDBuilder, PgUUID; -var init_uuid = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/uuid.js"() { - init_entity(); - init_sql(); - init_common(); - PgUUIDBuilder = class extends PgColumnBuilder { - static [entityKind] = "PgUUIDBuilder"; - constructor(name) { - super(name, "string", "PgUUID"); - } - /** - * Adds `default gen_random_uuid()` to the column definition. - */ - defaultRandom() { - return this.default(sql`gen_random_uuid()`); - } - /** @internal */ - build(table) { - return new PgUUID(table, this.config); - } - }; - PgUUID = class extends PgColumn { - static [entityKind] = "PgUUID"; - getSQLType() { - return "uuid"; - } - }; - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/varchar.js -function varchar(a5, b6 = {}) { - const { name, config: config3 } = getColumnNameAndConfig(a5, b6); - return new PgVarcharBuilder(name, config3); -} -var PgVarcharBuilder, PgVarchar; -var init_varchar = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/varchar.js"() { - init_entity(); - init_utils(); - init_common(); - PgVarcharBuilder = class extends PgColumnBuilder { - static [entityKind] = "PgVarcharBuilder"; - constructor(name, config3) { - super(name, "string", "PgVarchar"); - this.config.length = config3.length; - this.config.enumValues = config3.enum; - } - /** @internal */ - build(table) { - return new PgVarchar( - table, - this.config - ); - } - }; - PgVarchar = class extends PgColumn { - static [entityKind] = "PgVarchar"; - length = this.config.length; - enumValues = this.config.enumValues; - getSQLType() { - return this.length === void 0 ? `varchar` : `varchar(${this.length})`; - } - }; - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/vector_extension/bit.js -function bit(a5, b6) { - const { name, config: config3 } = getColumnNameAndConfig(a5, b6); - return new PgBinaryVectorBuilder(name, config3); -} -var PgBinaryVectorBuilder, PgBinaryVector; -var init_bit = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/vector_extension/bit.js"() { - init_entity(); - init_utils(); - init_common(); - PgBinaryVectorBuilder = class extends PgColumnBuilder { - static [entityKind] = "PgBinaryVectorBuilder"; - constructor(name, config3) { - super(name, "string", "PgBinaryVector"); - this.config.dimensions = config3.dimensions; - } - /** @internal */ - build(table) { - return new PgBinaryVector( - table, - this.config - ); - } - }; - PgBinaryVector = class extends PgColumn { - static [entityKind] = "PgBinaryVector"; - dimensions = this.config.dimensions; - getSQLType() { - return `bit(${this.dimensions})`; - } - }; - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/vector_extension/halfvec.js -function halfvec(a5, b6) { - const { name, config: config3 } = getColumnNameAndConfig(a5, b6); - return new PgHalfVectorBuilder(name, config3); -} -var PgHalfVectorBuilder, PgHalfVector; -var init_halfvec = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/vector_extension/halfvec.js"() { - init_entity(); - init_utils(); - init_common(); - PgHalfVectorBuilder = class extends PgColumnBuilder { - static [entityKind] = "PgHalfVectorBuilder"; - constructor(name, config3) { - super(name, "array", "PgHalfVector"); - this.config.dimensions = config3.dimensions; - } - /** @internal */ - build(table) { - return new PgHalfVector( - table, - this.config - ); - } - }; - PgHalfVector = class extends PgColumn { - static [entityKind] = "PgHalfVector"; - dimensions = this.config.dimensions; - getSQLType() { - return `halfvec(${this.dimensions})`; - } - mapToDriverValue(value) { - return JSON.stringify(value); - } - mapFromDriverValue(value) { - return value.slice(1, -1).split(",").map((v5) => Number.parseFloat(v5)); - } - }; - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/vector_extension/sparsevec.js -function sparsevec(a5, b6) { - const { name, config: config3 } = getColumnNameAndConfig(a5, b6); - return new PgSparseVectorBuilder(name, config3); -} -var PgSparseVectorBuilder, PgSparseVector; -var init_sparsevec = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/vector_extension/sparsevec.js"() { - init_entity(); - init_utils(); - init_common(); - PgSparseVectorBuilder = class extends PgColumnBuilder { - static [entityKind] = "PgSparseVectorBuilder"; - constructor(name, config3) { - super(name, "string", "PgSparseVector"); - this.config.dimensions = config3.dimensions; - } - /** @internal */ - build(table) { - return new PgSparseVector( - table, - this.config - ); - } - }; - PgSparseVector = class extends PgColumn { - static [entityKind] = "PgSparseVector"; - dimensions = this.config.dimensions; - getSQLType() { - return `sparsevec(${this.dimensions})`; - } - }; - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/vector_extension/vector.js -function vector(a5, b6) { - const { name, config: config3 } = getColumnNameAndConfig(a5, b6); - return new PgVectorBuilder(name, config3); -} -var PgVectorBuilder, PgVector; -var init_vector = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/vector_extension/vector.js"() { - init_entity(); - init_utils(); - init_common(); - PgVectorBuilder = class extends PgColumnBuilder { - static [entityKind] = "PgVectorBuilder"; - constructor(name, config3) { - super(name, "array", "PgVector"); - this.config.dimensions = config3.dimensions; - } - /** @internal */ - build(table) { - return new PgVector( - table, - this.config - ); - } - }; - PgVector = class extends PgColumn { - static [entityKind] = "PgVector"; - dimensions = this.config.dimensions; - getSQLType() { - return `vector(${this.dimensions})`; - } - mapToDriverValue(value) { - return JSON.stringify(value); - } - mapFromDriverValue(value) { - return value.slice(1, -1).split(",").map((v5) => Number.parseFloat(v5)); - } - }; - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/index.js -var init_columns = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/index.js"() { - init_bigint(); - init_bigserial(); - init_boolean(); - init_char(); - init_cidr(); - init_common(); - init_custom(); - init_date(); - init_double_precision(); - init_enum(); - init_inet(); - init_int_common(); - init_integer(); - init_interval(); - init_json(); - init_jsonb(); - init_line(); - init_macaddr(); - init_macaddr8(); - init_numeric(); - init_point(); - init_geometry(); - init_real(); - init_serial(); - init_smallint(); - init_smallserial(); - init_text(); - init_time(); - init_timestamp(); - init_uuid(); - init_varchar(); - init_bit(); - init_halfvec(); - init_sparsevec(); - init_vector(); - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/all.js -function getPgColumnBuilders() { - return { - bigint, - bigserial, - boolean, - char, - cidr, - customType, - date, - doublePrecision, - inet, - integer, - interval, - json, - jsonb, - line, - macaddr, - macaddr8, - numeric, - point, - geometry, - real, - serial, - smallint, - smallserial, - text, - time, - timestamp, - uuid, - varchar, - bit, - halfvec, - sparsevec, - vector - }; -} -var init_all = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/columns/all.js"() { - init_bigint(); - init_bigserial(); - init_boolean(); - init_char(); - init_cidr(); - init_custom(); - init_date(); - init_double_precision(); - init_inet(); - init_integer(); - init_interval(); - init_json(); - init_jsonb(); - init_line(); - init_macaddr(); - init_macaddr8(); - init_numeric(); - init_point(); - init_geometry(); - init_real(); - init_serial(); - init_smallint(); - init_smallserial(); - init_text(); - init_time(); - init_timestamp(); - init_uuid(); - init_varchar(); - init_bit(); - init_halfvec(); - init_sparsevec(); - init_vector(); - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/table.js -function pgTableWithSchema(name, columns, extraConfig, schema2, baseName = name) { - const rawTable = new PgTable(name, schema2, baseName); - const parsedColumns = typeof columns === "function" ? columns(getPgColumnBuilders()) : columns; - const builtColumns = Object.fromEntries( - Object.entries(parsedColumns).map(([name2, colBuilderBase]) => { - const colBuilder = colBuilderBase; - colBuilder.setName(name2); - const column = colBuilder.build(rawTable); - rawTable[InlineForeignKeys].push(...colBuilder.buildForeignKeys(column, rawTable)); - return [name2, column]; - }) - ); - const builtColumnsForExtraConfig = Object.fromEntries( - Object.entries(parsedColumns).map(([name2, colBuilderBase]) => { - const colBuilder = colBuilderBase; - colBuilder.setName(name2); - const column = colBuilder.buildExtraConfigColumn(rawTable); - return [name2, column]; - }) - ); - const table = Object.assign(rawTable, builtColumns); - table[Table.Symbol.Columns] = builtColumns; - table[Table.Symbol.ExtraConfigColumns] = builtColumnsForExtraConfig; - if (extraConfig) { - table[PgTable.Symbol.ExtraConfigBuilder] = extraConfig; - } - return Object.assign(table, { - enableRLS: () => { - table[PgTable.Symbol.EnableRLS] = true; - return table; - } - }); -} -var InlineForeignKeys, EnableRLS, PgTable, pgTable; -var init_table2 = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/table.js"() { - init_entity(); - init_table(); - init_all(); - InlineForeignKeys = /* @__PURE__ */ Symbol.for("drizzle:PgInlineForeignKeys"); - EnableRLS = /* @__PURE__ */ Symbol.for("drizzle:EnableRLS"); - PgTable = class extends Table { - static [entityKind] = "PgTable"; - /** @internal */ - static Symbol = Object.assign({}, Table.Symbol, { - InlineForeignKeys, - EnableRLS - }); - /**@internal */ - [InlineForeignKeys] = []; - /** @internal */ - [EnableRLS] = false; - /** @internal */ - [Table.Symbol.ExtraConfigBuilder] = void 0; - }; - pgTable = (name, columns, extraConfig) => { - return pgTableWithSchema(name, columns, extraConfig, void 0); - }; - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/primary-keys.js -function primaryKey(...config3) { - if (config3[0].columns) { - return new PrimaryKeyBuilder(config3[0].columns, config3[0].name); - } - return new PrimaryKeyBuilder(config3); -} -var PrimaryKeyBuilder, PrimaryKey; -var init_primary_keys = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/primary-keys.js"() { - init_entity(); - init_table2(); - PrimaryKeyBuilder = class { - static [entityKind] = "PgPrimaryKeyBuilder"; - /** @internal */ - columns; - /** @internal */ - name; - constructor(columns, name) { - this.columns = columns; - this.name = name; - } - /** @internal */ - build(table) { - return new PrimaryKey(table, this.columns, this.name); - } - }; - PrimaryKey = class { - constructor(table, columns, name) { - this.table = table; - this.columns = columns; - this.name = name; - } - static [entityKind] = "PgPrimaryKey"; - columns; - name; - getName() { - return this.name ?? `${this.table[PgTable.Symbol.Name]}_${this.columns.map((column) => column.name).join("_")}_pk`; - } - }; - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/sql/expressions/conditions.js -function bindIfParam(value, column) { - if (isDriverValueEncoder(column) && !isSQLWrapper(value) && !is(value, Param) && !is(value, Placeholder) && !is(value, Column) && !is(value, Table) && !is(value, View)) { - return new Param(value, column); - } - return value; -} -function and(...unfilteredConditions) { - const conditions = unfilteredConditions.filter( - (c5) => c5 !== void 0 - ); - if (conditions.length === 0) { - return void 0; - } - if (conditions.length === 1) { - return new SQL(conditions); - } - return new SQL([ - new StringChunk("("), - sql.join(conditions, new StringChunk(" and ")), - new StringChunk(")") - ]); -} -function or(...unfilteredConditions) { - const conditions = unfilteredConditions.filter( - (c5) => c5 !== void 0 - ); - if (conditions.length === 0) { - return void 0; - } - if (conditions.length === 1) { - return new SQL(conditions); - } - return new SQL([ - new StringChunk("("), - sql.join(conditions, new StringChunk(" or ")), - new StringChunk(")") - ]); -} -function not(condition) { - return sql`not ${condition}`; -} -function inArray(column, values2) { - if (Array.isArray(values2)) { - if (values2.length === 0) { - return sql`false`; - } - return sql`${column} in ${values2.map((v5) => bindIfParam(v5, column))}`; - } - return sql`${column} in ${bindIfParam(values2, column)}`; -} -function notInArray(column, values2) { - if (Array.isArray(values2)) { - if (values2.length === 0) { - return sql`true`; - } - return sql`${column} not in ${values2.map((v5) => bindIfParam(v5, column))}`; - } - return sql`${column} not in ${bindIfParam(values2, column)}`; -} -function isNull(value) { - return sql`${value} is null`; -} -function isNotNull(value) { - return sql`${value} is not null`; -} -function exists(subquery) { - return sql`exists ${subquery}`; -} -function notExists(subquery) { - return sql`not exists ${subquery}`; -} -function between(column, min, max) { - return sql`${column} between ${bindIfParam(min, column)} and ${bindIfParam( - max, - column - )}`; -} -function notBetween(column, min, max) { - return sql`${column} not between ${bindIfParam( - min, - column - )} and ${bindIfParam(max, column)}`; -} -function like(column, value) { - return sql`${column} like ${value}`; -} -function notLike(column, value) { - return sql`${column} not like ${value}`; -} -function ilike(column, value) { - return sql`${column} ilike ${value}`; -} -function notIlike(column, value) { - return sql`${column} not ilike ${value}`; -} -var eq, ne, gt, gte, lt, lte; -var init_conditions = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/sql/expressions/conditions.js"() { - init_column(); - init_entity(); - init_table(); - init_sql(); - eq = (left, right) => { - return sql`${left} = ${bindIfParam(right, left)}`; - }; - ne = (left, right) => { - return sql`${left} <> ${bindIfParam(right, left)}`; - }; - gt = (left, right) => { - return sql`${left} > ${bindIfParam(right, left)}`; - }; - gte = (left, right) => { - return sql`${left} >= ${bindIfParam(right, left)}`; - }; - lt = (left, right) => { - return sql`${left} < ${bindIfParam(right, left)}`; - }; - lte = (left, right) => { - return sql`${left} <= ${bindIfParam(right, left)}`; - }; - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/sql/expressions/select.js -function asc(column) { - return sql`${column} asc`; -} -function desc(column) { - return sql`${column} desc`; -} -var init_select = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/sql/expressions/select.js"() { - init_sql(); - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/sql/expressions/index.js -var init_expressions = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/sql/expressions/index.js"() { - init_conditions(); - init_select(); - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/relations.js -function getOperators() { - return { - and, - between, - eq, - exists, - gt, - gte, - ilike, - inArray, - isNull, - isNotNull, - like, - lt, - lte, - ne, - not, - notBetween, - notExists, - notLike, - notIlike, - notInArray, - or, - sql - }; -} -function getOrderByOperators() { - return { - sql, - asc, - desc - }; -} -function extractTablesRelationalConfig(schema2, configHelpers) { - if (Object.keys(schema2).length === 1 && "default" in schema2 && !is(schema2["default"], Table)) { - schema2 = schema2["default"]; - } - const tableNamesMap = {}; - const relationsBuffer = {}; - const tablesConfig = {}; - for (const [key, value] of Object.entries(schema2)) { - if (is(value, Table)) { - const dbName = getTableUniqueName(value); - const bufferedRelations = relationsBuffer[dbName]; - tableNamesMap[dbName] = key; - tablesConfig[key] = { - tsName: key, - dbName: value[Table.Symbol.Name], - schema: value[Table.Symbol.Schema], - columns: value[Table.Symbol.Columns], - relations: bufferedRelations?.relations ?? {}, - primaryKey: bufferedRelations?.primaryKey ?? [] - }; - for (const column of Object.values( - value[Table.Symbol.Columns] - )) { - if (column.primary) { - tablesConfig[key].primaryKey.push(column); - } - } - const extraConfig = value[Table.Symbol.ExtraConfigBuilder]?.(value[Table.Symbol.ExtraConfigColumns]); - if (extraConfig) { - for (const configEntry of Object.values(extraConfig)) { - if (is(configEntry, PrimaryKeyBuilder)) { - tablesConfig[key].primaryKey.push(...configEntry.columns); - } - } - } - } else if (is(value, Relations)) { - const dbName = getTableUniqueName(value.table); - const tableName = tableNamesMap[dbName]; - const relations2 = value.config( - configHelpers(value.table) - ); - let primaryKey2; - for (const [relationName, relation] of Object.entries(relations2)) { - if (tableName) { - const tableConfig = tablesConfig[tableName]; - tableConfig.relations[relationName] = relation; - if (primaryKey2) { - tableConfig.primaryKey.push(...primaryKey2); - } - } else { - if (!(dbName in relationsBuffer)) { - relationsBuffer[dbName] = { - relations: {}, - primaryKey: primaryKey2 - }; - } - relationsBuffer[dbName].relations[relationName] = relation; - } - } - } - } - return { tables: tablesConfig, tableNamesMap }; -} -function createOne(sourceTable) { - return function one(table, config3) { - return new One( - sourceTable, - table, - config3, - config3?.fields.reduce((res, f5) => res && f5.notNull, true) ?? false - ); - }; -} -function createMany(sourceTable) { - return function many(referencedTable, config3) { - return new Many(sourceTable, referencedTable, config3); - }; -} -function normalizeRelation(schema2, tableNamesMap, relation) { - if (is(relation, One) && relation.config) { - return { - fields: relation.config.fields, - references: relation.config.references - }; - } - const referencedTableTsName = tableNamesMap[getTableUniqueName(relation.referencedTable)]; - if (!referencedTableTsName) { - throw new Error( - `Table "${relation.referencedTable[Table.Symbol.Name]}" not found in schema` - ); - } - const referencedTableConfig = schema2[referencedTableTsName]; - if (!referencedTableConfig) { - throw new Error(`Table "${referencedTableTsName}" not found in schema`); - } - const sourceTable = relation.sourceTable; - const sourceTableTsName = tableNamesMap[getTableUniqueName(sourceTable)]; - if (!sourceTableTsName) { - throw new Error( - `Table "${sourceTable[Table.Symbol.Name]}" not found in schema` - ); - } - const reverseRelations = []; - for (const referencedTableRelation of Object.values( - referencedTableConfig.relations - )) { - if (relation.relationName && relation !== referencedTableRelation && referencedTableRelation.relationName === relation.relationName || !relation.relationName && referencedTableRelation.referencedTable === relation.sourceTable) { - reverseRelations.push(referencedTableRelation); - } - } - if (reverseRelations.length > 1) { - throw relation.relationName ? new Error( - `There are multiple relations with name "${relation.relationName}" in table "${referencedTableTsName}"` - ) : new Error( - `There are multiple relations between "${referencedTableTsName}" and "${relation.sourceTable[Table.Symbol.Name]}". Please specify relation name` - ); - } - if (reverseRelations[0] && is(reverseRelations[0], One) && reverseRelations[0].config) { - return { - fields: reverseRelations[0].config.references, - references: reverseRelations[0].config.fields - }; - } - throw new Error( - `There is not enough information to infer relation "${sourceTableTsName}.${relation.fieldName}"` - ); -} -function createTableRelationsHelpers(sourceTable) { - return { - one: createOne(sourceTable), - many: createMany(sourceTable) - }; -} -function mapRelationalRow(tablesConfig, tableConfig, row, buildQueryResultSelection, mapColumnValue = (value) => value) { - const result = {}; - for (const [ - selectionItemIndex, - selectionItem - ] of buildQueryResultSelection.entries()) { - if (selectionItem.isJson) { - const relation = tableConfig.relations[selectionItem.tsKey]; - const rawSubRows = row[selectionItemIndex]; - const subRows = typeof rawSubRows === "string" ? JSON.parse(rawSubRows) : rawSubRows; - result[selectionItem.tsKey] = is(relation, One) ? subRows && mapRelationalRow( - tablesConfig, - tablesConfig[selectionItem.relationTableTsKey], - subRows, - selectionItem.selection, - mapColumnValue - ) : subRows.map( - (subRow) => mapRelationalRow( - tablesConfig, - tablesConfig[selectionItem.relationTableTsKey], - subRow, - selectionItem.selection, - mapColumnValue - ) - ); - } else { - const value = mapColumnValue(row[selectionItemIndex]); - const field = selectionItem.field; - let decoder2; - if (is(field, Column)) { - decoder2 = field; - } else if (is(field, SQL)) { - decoder2 = field.decoder; - } else { - decoder2 = field.sql.decoder; - } - result[selectionItem.tsKey] = value === null ? null : decoder2.mapFromDriverValue(value); - } - } - return result; -} -var Relation, Relations, One, Many; -var init_relations = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/relations.js"() { - init_table(); - init_column(); - init_entity(); - init_primary_keys(); - init_expressions(); - init_sql(); - Relation = class { - constructor(sourceTable, referencedTable, relationName) { - this.sourceTable = sourceTable; - this.referencedTable = referencedTable; - this.relationName = relationName; - this.referencedTableName = referencedTable[Table.Symbol.Name]; - } - static [entityKind] = "Relation"; - referencedTableName; - fieldName; - }; - Relations = class { - constructor(table, config3) { - this.table = table; - this.config = config3; - } - static [entityKind] = "Relations"; - }; - One = class _One extends Relation { - constructor(sourceTable, referencedTable, config3, isNullable) { - super(sourceTable, referencedTable, config3?.relationName); - this.config = config3; - this.isNullable = isNullable; - } - static [entityKind] = "One"; - withFieldName(fieldName) { - const relation = new _One( - this.sourceTable, - this.referencedTable, - this.config, - this.isNullable - ); - relation.fieldName = fieldName; - return relation; - } - }; - Many = class _Many extends Relation { - constructor(sourceTable, referencedTable, config3) { - super(sourceTable, referencedTable, config3?.relationName); - this.config = config3; - } - static [entityKind] = "Many"; - withFieldName(fieldName) { - const relation = new _Many( - this.sourceTable, - this.referencedTable, - this.config - ); - relation.fieldName = fieldName; - return relation; - } - }; - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/sql/functions/aggregate.js -function count(expression) { - return sql`count(${expression || sql.raw("*")})`.mapWith(Number); -} -var init_aggregate = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/sql/functions/aggregate.js"() { - init_sql(); - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/sql/functions/vector.js -var init_vector2 = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/sql/functions/vector.js"() { - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/sql/functions/index.js -var init_functions = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/sql/functions/index.js"() { - init_aggregate(); - init_vector2(); - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/sql/index.js -var init_sql2 = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/sql/index.js"() { - init_expressions(); - init_functions(); - init_sql(); - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/view-base.js -var PgViewBase; -var init_view_base = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/view-base.js"() { - init_entity(); - init_sql(); - PgViewBase = class extends View { - static [entityKind] = "PgViewBase"; - }; - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/dialect.js -var PgDialect; -var init_dialect = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/dialect.js"() { - init_alias(); - init_casing(); - init_column(); - init_entity(); - init_errors2(); - init_columns(); - init_table2(); - init_relations(); - init_sql2(); - init_sql(); - init_subquery(); - init_table(); - init_utils(); - init_view_common(); - init_view_base(); - PgDialect = class { - static [entityKind] = "PgDialect"; - /** @internal */ - casing; - constructor(config3) { - this.casing = new CasingCache(config3?.casing); - } - async migrate(migrations, session, config3) { - const migrationsTable = typeof config3 === "string" ? "__drizzle_migrations" : config3.migrationsTable ?? "__drizzle_migrations"; - const migrationsSchema = typeof config3 === "string" ? "drizzle" : config3.migrationsSchema ?? "drizzle"; - const migrationTableCreate = sql` - CREATE TABLE IF NOT EXISTS ${sql.identifier(migrationsSchema)}.${sql.identifier(migrationsTable)} ( - id SERIAL PRIMARY KEY, - hash text NOT NULL, - created_at bigint - ) - `; - await session.execute(sql`CREATE SCHEMA IF NOT EXISTS ${sql.identifier(migrationsSchema)}`); - await session.execute(migrationTableCreate); - const dbMigrations = await session.all( - sql`select id, hash, created_at from ${sql.identifier(migrationsSchema)}.${sql.identifier(migrationsTable)} order by created_at desc limit 1` - ); - const lastDbMigration = dbMigrations[0]; - await session.transaction(async (tx) => { - for await (const migration of migrations) { - if (!lastDbMigration || Number(lastDbMigration.created_at) < migration.folderMillis) { - for (const stmt of migration.sql) { - await tx.execute(sql.raw(stmt)); - } - await tx.execute( - sql`insert into ${sql.identifier(migrationsSchema)}.${sql.identifier(migrationsTable)} ("hash", "created_at") values(${migration.hash}, ${migration.folderMillis})` - ); - } - } - }); - } - escapeName(name) { - return `"${name}"`; - } - escapeParam(num) { - return `$${num + 1}`; - } - escapeString(str) { - return `'${str.replace(/'/g, "''")}'`; - } - buildWithCTE(queries) { - if (!queries?.length) - return void 0; - const withSqlChunks = [sql`with `]; - for (const [i5, w5] of queries.entries()) { - withSqlChunks.push(sql`${sql.identifier(w5._.alias)} as (${w5._.sql})`); - if (i5 < queries.length - 1) { - withSqlChunks.push(sql`, `); - } - } - withSqlChunks.push(sql` `); - return sql.join(withSqlChunks); - } - buildDeleteQuery({ table, where, returning, withList }) { - const withSql = this.buildWithCTE(withList); - const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : void 0; - const whereSql = where ? sql` where ${where}` : void 0; - return sql`${withSql}delete from ${table}${whereSql}${returningSql}`; - } - buildUpdateSet(table, set2) { - const tableColumns = table[Table.Symbol.Columns]; - const columnNames = Object.keys(tableColumns).filter( - (colName) => set2[colName] !== void 0 || tableColumns[colName]?.onUpdateFn !== void 0 - ); - const setSize = columnNames.length; - return sql.join(columnNames.flatMap((colName, i5) => { - const col = tableColumns[colName]; - const value = set2[colName] ?? sql.param(col.onUpdateFn(), col); - const res = sql`${sql.identifier(this.casing.getColumnCasing(col))} = ${value}`; - if (i5 < setSize - 1) { - return [res, sql.raw(", ")]; - } - return [res]; - })); - } - buildUpdateQuery({ table, set: set2, where, returning, withList, from, joins }) { - const withSql = this.buildWithCTE(withList); - const tableName = table[PgTable.Symbol.Name]; - const tableSchema = table[PgTable.Symbol.Schema]; - const origTableName = table[PgTable.Symbol.OriginalName]; - const alias = tableName === origTableName ? void 0 : tableName; - const tableSql = sql`${tableSchema ? sql`${sql.identifier(tableSchema)}.` : void 0}${sql.identifier(origTableName)}${alias && sql` ${sql.identifier(alias)}`}`; - const setSql = this.buildUpdateSet(table, set2); - const fromSql = from && sql.join([sql.raw(" from "), this.buildFromTable(from)]); - const joinsSql = this.buildJoins(joins); - const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: !from })}` : void 0; - const whereSql = where ? sql` where ${where}` : void 0; - return sql`${withSql}update ${tableSql} set ${setSql}${fromSql}${joinsSql}${whereSql}${returningSql}`; - } - /** - * Builds selection SQL with provided fields/expressions - * - * Examples: - * - * `select from` - * - * `insert ... returning ` - * - * If `isSingleTable` is true, then columns won't be prefixed with table name - */ - buildSelection(fields, { isSingleTable = false } = {}) { - const columnsLen = fields.length; - const chunks = fields.flatMap(({ field }, i5) => { - const chunk = []; - if (is(field, SQL.Aliased) && field.isSelectionField) { - chunk.push(sql.identifier(field.fieldAlias)); - } else if (is(field, SQL.Aliased) || is(field, SQL)) { - const query = is(field, SQL.Aliased) ? field.sql : field; - if (isSingleTable) { - chunk.push( - new SQL( - query.queryChunks.map((c5) => { - if (is(c5, PgColumn)) { - return sql.identifier(this.casing.getColumnCasing(c5)); - } - return c5; - }) - ) - ); - } else { - chunk.push(query); - } - if (is(field, SQL.Aliased)) { - chunk.push(sql` as ${sql.identifier(field.fieldAlias)}`); - } - } else if (is(field, Column)) { - if (isSingleTable) { - chunk.push(sql.identifier(this.casing.getColumnCasing(field))); - } else { - chunk.push(field); - } - } - if (i5 < columnsLen - 1) { - chunk.push(sql`, `); - } - return chunk; - }); - return sql.join(chunks); - } - buildJoins(joins) { - if (!joins || joins.length === 0) { - return void 0; - } - const joinsArray = []; - for (const [index2, joinMeta] of joins.entries()) { - if (index2 === 0) { - joinsArray.push(sql` `); - } - const table = joinMeta.table; - const lateralSql = joinMeta.lateral ? sql` lateral` : void 0; - if (is(table, PgTable)) { - const tableName = table[PgTable.Symbol.Name]; - const tableSchema = table[PgTable.Symbol.Schema]; - const origTableName = table[PgTable.Symbol.OriginalName]; - const alias = tableName === origTableName ? void 0 : joinMeta.alias; - joinsArray.push( - sql`${sql.raw(joinMeta.joinType)} join${lateralSql} ${tableSchema ? sql`${sql.identifier(tableSchema)}.` : void 0}${sql.identifier(origTableName)}${alias && sql` ${sql.identifier(alias)}`} on ${joinMeta.on}` - ); - } else if (is(table, View)) { - const viewName = table[ViewBaseConfig].name; - const viewSchema = table[ViewBaseConfig].schema; - const origViewName = table[ViewBaseConfig].originalName; - const alias = viewName === origViewName ? void 0 : joinMeta.alias; - joinsArray.push( - sql`${sql.raw(joinMeta.joinType)} join${lateralSql} ${viewSchema ? sql`${sql.identifier(viewSchema)}.` : void 0}${sql.identifier(origViewName)}${alias && sql` ${sql.identifier(alias)}`} on ${joinMeta.on}` - ); - } else { - joinsArray.push( - sql`${sql.raw(joinMeta.joinType)} join${lateralSql} ${table} on ${joinMeta.on}` - ); - } - if (index2 < joins.length - 1) { - joinsArray.push(sql` `); - } - } - return sql.join(joinsArray); - } - buildFromTable(table) { - if (is(table, Table) && table[Table.Symbol.OriginalName] !== table[Table.Symbol.Name]) { - let fullName = sql`${sql.identifier(table[Table.Symbol.OriginalName])}`; - if (table[Table.Symbol.Schema]) { - fullName = sql`${sql.identifier(table[Table.Symbol.Schema])}.${fullName}`; - } - return sql`${fullName} ${sql.identifier(table[Table.Symbol.Name])}`; - } - return table; - } - buildSelectQuery({ - withList, - fields, - fieldsFlat, - where, - having, - table, - joins, - orderBy, - groupBy, - limit, - offset, - lockingClause, - distinct, - setOperators - }) { - const fieldsList = fieldsFlat ?? orderSelectedFields(fields); - for (const f5 of fieldsList) { - if (is(f5.field, Column) && getTableName(f5.field.table) !== (is(table, Subquery) ? table._.alias : is(table, PgViewBase) ? table[ViewBaseConfig].name : is(table, SQL) ? void 0 : getTableName(table)) && !((table2) => joins?.some( - ({ alias }) => alias === (table2[Table.Symbol.IsAlias] ? getTableName(table2) : table2[Table.Symbol.BaseName]) - ))(f5.field.table)) { - const tableName = getTableName(f5.field.table); - throw new Error( - `Your "${f5.path.join("->")}" field references a column "${tableName}"."${f5.field.name}", but the table "${tableName}" is not part of the query! Did you forget to join it?` - ); - } - } - const isSingleTable = !joins || joins.length === 0; - const withSql = this.buildWithCTE(withList); - let distinctSql; - if (distinct) { - distinctSql = distinct === true ? sql` distinct` : sql` distinct on (${sql.join(distinct.on, sql`, `)})`; - } - const selection = this.buildSelection(fieldsList, { isSingleTable }); - const tableSql = this.buildFromTable(table); - const joinsSql = this.buildJoins(joins); - const whereSql = where ? sql` where ${where}` : void 0; - const havingSql = having ? sql` having ${having}` : void 0; - let orderBySql; - if (orderBy && orderBy.length > 0) { - orderBySql = sql` order by ${sql.join(orderBy, sql`, `)}`; - } - let groupBySql; - if (groupBy && groupBy.length > 0) { - groupBySql = sql` group by ${sql.join(groupBy, sql`, `)}`; - } - const limitSql = typeof limit === "object" || typeof limit === "number" && limit >= 0 ? sql` limit ${limit}` : void 0; - const offsetSql = offset ? sql` offset ${offset}` : void 0; - const lockingClauseSql = sql.empty(); - if (lockingClause) { - const clauseSql = sql` for ${sql.raw(lockingClause.strength)}`; - if (lockingClause.config.of) { - clauseSql.append( - sql` of ${sql.join( - Array.isArray(lockingClause.config.of) ? lockingClause.config.of : [lockingClause.config.of], - sql`, ` - )}` - ); - } - if (lockingClause.config.noWait) { - clauseSql.append(sql` no wait`); - } else if (lockingClause.config.skipLocked) { - clauseSql.append(sql` skip locked`); - } - lockingClauseSql.append(clauseSql); - } - const finalQuery = sql`${withSql}select${distinctSql} ${selection} from ${tableSql}${joinsSql}${whereSql}${groupBySql}${havingSql}${orderBySql}${limitSql}${offsetSql}${lockingClauseSql}`; - if (setOperators.length > 0) { - return this.buildSetOperations(finalQuery, setOperators); - } - return finalQuery; - } - buildSetOperations(leftSelect, setOperators) { - const [setOperator, ...rest] = setOperators; - if (!setOperator) { - throw new Error("Cannot pass undefined values to any set operator"); - } - if (rest.length === 0) { - return this.buildSetOperationQuery({ leftSelect, setOperator }); - } - return this.buildSetOperations( - this.buildSetOperationQuery({ leftSelect, setOperator }), - rest - ); - } - buildSetOperationQuery({ - leftSelect, - setOperator: { type, isAll, rightSelect, limit, orderBy, offset } - }) { - const leftChunk = sql`(${leftSelect.getSQL()}) `; - const rightChunk = sql`(${rightSelect.getSQL()})`; - let orderBySql; - if (orderBy && orderBy.length > 0) { - const orderByValues = []; - for (const singleOrderBy of orderBy) { - if (is(singleOrderBy, PgColumn)) { - orderByValues.push(sql.identifier(singleOrderBy.name)); - } else if (is(singleOrderBy, SQL)) { - for (let i5 = 0; i5 < singleOrderBy.queryChunks.length; i5++) { - const chunk = singleOrderBy.queryChunks[i5]; - if (is(chunk, PgColumn)) { - singleOrderBy.queryChunks[i5] = sql.identifier(chunk.name); - } - } - orderByValues.push(sql`${singleOrderBy}`); - } else { - orderByValues.push(sql`${singleOrderBy}`); - } - } - orderBySql = sql` order by ${sql.join(orderByValues, sql`, `)} `; - } - const limitSql = typeof limit === "object" || typeof limit === "number" && limit >= 0 ? sql` limit ${limit}` : void 0; - const operatorChunk = sql.raw(`${type} ${isAll ? "all " : ""}`); - const offsetSql = offset ? sql` offset ${offset}` : void 0; - return sql`${leftChunk}${operatorChunk}${rightChunk}${orderBySql}${limitSql}${offsetSql}`; - } - buildInsertQuery({ table, values: valuesOrSelect, onConflict, returning, withList, select: select2, overridingSystemValue_ }) { - const valuesSqlList = []; - const columns = table[Table.Symbol.Columns]; - const colEntries = Object.entries(columns).filter(([_, col]) => !col.shouldDisableInsert()); - const insertOrder = colEntries.map( - ([, column]) => sql.identifier(this.casing.getColumnCasing(column)) - ); - if (select2) { - const select22 = valuesOrSelect; - if (is(select22, SQL)) { - valuesSqlList.push(select22); - } else { - valuesSqlList.push(select22.getSQL()); - } - } else { - const values2 = valuesOrSelect; - valuesSqlList.push(sql.raw("values ")); - for (const [valueIndex, value] of values2.entries()) { - const valueList = []; - for (const [fieldName, col] of colEntries) { - const colValue = value[fieldName]; - if (colValue === void 0 || is(colValue, Param) && colValue.value === void 0) { - if (col.defaultFn !== void 0) { - const defaultFnResult = col.defaultFn(); - const defaultValue = is(defaultFnResult, SQL) ? defaultFnResult : sql.param(defaultFnResult, col); - valueList.push(defaultValue); - } else if (!col.default && col.onUpdateFn !== void 0) { - const onUpdateFnResult = col.onUpdateFn(); - const newValue = is(onUpdateFnResult, SQL) ? onUpdateFnResult : sql.param(onUpdateFnResult, col); - valueList.push(newValue); - } else { - valueList.push(sql`default`); - } - } else { - valueList.push(colValue); - } - } - valuesSqlList.push(valueList); - if (valueIndex < values2.length - 1) { - valuesSqlList.push(sql`, `); - } - } - } - const withSql = this.buildWithCTE(withList); - const valuesSql = sql.join(valuesSqlList); - const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : void 0; - const onConflictSql = onConflict ? sql` on conflict ${onConflict}` : void 0; - const overridingSql = overridingSystemValue_ === true ? sql`overriding system value ` : void 0; - return sql`${withSql}insert into ${table} ${insertOrder} ${overridingSql}${valuesSql}${onConflictSql}${returningSql}`; - } - buildRefreshMaterializedViewQuery({ view, concurrently, withNoData }) { - const concurrentlySql = concurrently ? sql` concurrently` : void 0; - const withNoDataSql = withNoData ? sql` with no data` : void 0; - return sql`refresh materialized view${concurrentlySql} ${view}${withNoDataSql}`; - } - prepareTyping(encoder3) { - if (is(encoder3, PgJsonb) || is(encoder3, PgJson)) { - return "json"; - } else if (is(encoder3, PgNumeric)) { - return "decimal"; - } else if (is(encoder3, PgTime)) { - return "time"; - } else if (is(encoder3, PgTimestamp) || is(encoder3, PgTimestampString)) { - return "timestamp"; - } else if (is(encoder3, PgDate) || is(encoder3, PgDateString)) { - return "date"; - } else if (is(encoder3, PgUUID)) { - return "uuid"; - } else { - return "none"; - } - } - sqlToQuery(sql22, invokeSource) { - return sql22.toQuery({ - casing: this.casing, - escapeName: this.escapeName, - escapeParam: this.escapeParam, - escapeString: this.escapeString, - prepareTyping: this.prepareTyping, - invokeSource - }); - } - // buildRelationalQueryWithPK({ - // fullSchema, - // schema, - // tableNamesMap, - // table, - // tableConfig, - // queryConfig: config, - // tableAlias, - // isRoot = false, - // joinOn, - // }: { - // fullSchema: Record; - // schema: TablesRelationalConfig; - // tableNamesMap: Record; - // table: PgTable; - // tableConfig: TableRelationalConfig; - // queryConfig: true | DBQueryConfig<'many', true>; - // tableAlias: string; - // isRoot?: boolean; - // joinOn?: SQL; - // }): BuildRelationalQueryResult { - // // For { "": true }, return a table with selection of all columns - // if (config === true) { - // const selectionEntries = Object.entries(tableConfig.columns); - // const selection: BuildRelationalQueryResult['selection'] = selectionEntries.map(( - // [key, value], - // ) => ({ - // dbKey: value.name, - // tsKey: key, - // field: value as PgColumn, - // relationTableTsKey: undefined, - // isJson: false, - // selection: [], - // })); - // return { - // tableTsKey: tableConfig.tsName, - // sql: table, - // selection, - // }; - // } - // // let selection: BuildRelationalQueryResult['selection'] = []; - // // let selectionForBuild = selection; - // const aliasedColumns = Object.fromEntries( - // Object.entries(tableConfig.columns).map(([key, value]) => [key, aliasedTableColumn(value, tableAlias)]), - // ); - // const aliasedRelations = Object.fromEntries( - // Object.entries(tableConfig.relations).map(([key, value]) => [key, aliasedRelation(value, tableAlias)]), - // ); - // const aliasedFields = Object.assign({}, aliasedColumns, aliasedRelations); - // let where, hasUserDefinedWhere; - // if (config.where) { - // const whereSql = typeof config.where === 'function' ? config.where(aliasedFields, operators) : config.where; - // where = whereSql && mapColumnsInSQLToAlias(whereSql, tableAlias); - // hasUserDefinedWhere = !!where; - // } - // where = and(joinOn, where); - // // const fieldsSelection: { tsKey: string; value: PgColumn | SQL.Aliased; isExtra?: boolean }[] = []; - // let joins: Join[] = []; - // let selectedColumns: string[] = []; - // // Figure out which columns to select - // if (config.columns) { - // let isIncludeMode = false; - // for (const [field, value] of Object.entries(config.columns)) { - // if (value === undefined) { - // continue; - // } - // if (field in tableConfig.columns) { - // if (!isIncludeMode && value === true) { - // isIncludeMode = true; - // } - // selectedColumns.push(field); - // } - // } - // if (selectedColumns.length > 0) { - // selectedColumns = isIncludeMode - // ? selectedColumns.filter((c) => config.columns?.[c] === true) - // : Object.keys(tableConfig.columns).filter((key) => !selectedColumns.includes(key)); - // } - // } else { - // // Select all columns if selection is not specified - // selectedColumns = Object.keys(tableConfig.columns); - // } - // // for (const field of selectedColumns) { - // // const column = tableConfig.columns[field]! as PgColumn; - // // fieldsSelection.push({ tsKey: field, value: column }); - // // } - // let initiallySelectedRelations: { - // tsKey: string; - // queryConfig: true | DBQueryConfig<'many', false>; - // relation: Relation; - // }[] = []; - // // let selectedRelations: BuildRelationalQueryResult['selection'] = []; - // // Figure out which relations to select - // if (config.with) { - // initiallySelectedRelations = Object.entries(config.with) - // .filter((entry): entry is [typeof entry[0], NonNullable] => !!entry[1]) - // .map(([tsKey, queryConfig]) => ({ tsKey, queryConfig, relation: tableConfig.relations[tsKey]! })); - // } - // const manyRelations = initiallySelectedRelations.filter((r) => - // is(r.relation, Many) - // && (schema[tableNamesMap[r.relation.referencedTable[Table.Symbol.Name]]!]?.primaryKey.length ?? 0) > 0 - // ); - // // If this is the last Many relation (or there are no Many relations), we are on the innermost subquery level - // const isInnermostQuery = manyRelations.length < 2; - // const selectedExtras: { - // tsKey: string; - // value: SQL.Aliased; - // }[] = []; - // // Figure out which extras to select - // if (isInnermostQuery && config.extras) { - // const extras = typeof config.extras === 'function' - // ? config.extras(aliasedFields, { sql }) - // : config.extras; - // for (const [tsKey, value] of Object.entries(extras)) { - // selectedExtras.push({ - // tsKey, - // value: mapColumnsInAliasedSQLToAlias(value, tableAlias), - // }); - // } - // } - // // Transform `fieldsSelection` into `selection` - // // `fieldsSelection` shouldn't be used after this point - // // for (const { tsKey, value, isExtra } of fieldsSelection) { - // // selection.push({ - // // dbKey: is(value, SQL.Aliased) ? value.fieldAlias : tableConfig.columns[tsKey]!.name, - // // tsKey, - // // field: is(value, Column) ? aliasedTableColumn(value, tableAlias) : value, - // // relationTableTsKey: undefined, - // // isJson: false, - // // isExtra, - // // selection: [], - // // }); - // // } - // let orderByOrig = typeof config.orderBy === 'function' - // ? config.orderBy(aliasedFields, orderByOperators) - // : config.orderBy ?? []; - // if (!Array.isArray(orderByOrig)) { - // orderByOrig = [orderByOrig]; - // } - // const orderBy = orderByOrig.map((orderByValue) => { - // if (is(orderByValue, Column)) { - // return aliasedTableColumn(orderByValue, tableAlias) as PgColumn; - // } - // return mapColumnsInSQLToAlias(orderByValue, tableAlias); - // }); - // const limit = isInnermostQuery ? config.limit : undefined; - // const offset = isInnermostQuery ? config.offset : undefined; - // // For non-root queries without additional config except columns, return a table with selection - // if ( - // !isRoot - // && initiallySelectedRelations.length === 0 - // && selectedExtras.length === 0 - // && !where - // && orderBy.length === 0 - // && limit === undefined - // && offset === undefined - // ) { - // return { - // tableTsKey: tableConfig.tsName, - // sql: table, - // selection: selectedColumns.map((key) => ({ - // dbKey: tableConfig.columns[key]!.name, - // tsKey: key, - // field: tableConfig.columns[key] as PgColumn, - // relationTableTsKey: undefined, - // isJson: false, - // selection: [], - // })), - // }; - // } - // const selectedRelationsWithoutPK: - // // Process all relations without primary keys, because they need to be joined differently and will all be on the same query level - // for ( - // const { - // tsKey: selectedRelationTsKey, - // queryConfig: selectedRelationConfigValue, - // relation, - // } of initiallySelectedRelations - // ) { - // const normalizedRelation = normalizeRelation(schema, tableNamesMap, relation); - // const relationTableName = relation.referencedTable[Table.Symbol.Name]; - // const relationTableTsName = tableNamesMap[relationTableName]!; - // const relationTable = schema[relationTableTsName]!; - // if (relationTable.primaryKey.length > 0) { - // continue; - // } - // const relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`; - // const joinOn = and( - // ...normalizedRelation.fields.map((field, i) => - // eq( - // aliasedTableColumn(normalizedRelation.references[i]!, relationTableAlias), - // aliasedTableColumn(field, tableAlias), - // ) - // ), - // ); - // const builtRelation = this.buildRelationalQueryWithoutPK({ - // fullSchema, - // schema, - // tableNamesMap, - // table: fullSchema[relationTableTsName] as PgTable, - // tableConfig: schema[relationTableTsName]!, - // queryConfig: selectedRelationConfigValue, - // tableAlias: relationTableAlias, - // joinOn, - // nestedQueryRelation: relation, - // }); - // const field = sql`${sql.identifier(relationTableAlias)}.${sql.identifier('data')}`.as(selectedRelationTsKey); - // joins.push({ - // on: sql`true`, - // table: new Subquery(builtRelation.sql as SQL, {}, relationTableAlias), - // alias: relationTableAlias, - // joinType: 'left', - // lateral: true, - // }); - // selectedRelations.push({ - // dbKey: selectedRelationTsKey, - // tsKey: selectedRelationTsKey, - // field, - // relationTableTsKey: relationTableTsName, - // isJson: true, - // selection: builtRelation.selection, - // }); - // } - // const oneRelations = initiallySelectedRelations.filter((r): r is typeof r & { relation: One } => - // is(r.relation, One) - // ); - // // Process all One relations with PKs, because they can all be joined on the same level - // for ( - // const { - // tsKey: selectedRelationTsKey, - // queryConfig: selectedRelationConfigValue, - // relation, - // } of oneRelations - // ) { - // const normalizedRelation = normalizeRelation(schema, tableNamesMap, relation); - // const relationTableName = relation.referencedTable[Table.Symbol.Name]; - // const relationTableTsName = tableNamesMap[relationTableName]!; - // const relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`; - // const relationTable = schema[relationTableTsName]!; - // if (relationTable.primaryKey.length === 0) { - // continue; - // } - // const joinOn = and( - // ...normalizedRelation.fields.map((field, i) => - // eq( - // aliasedTableColumn(normalizedRelation.references[i]!, relationTableAlias), - // aliasedTableColumn(field, tableAlias), - // ) - // ), - // ); - // const builtRelation = this.buildRelationalQueryWithPK({ - // fullSchema, - // schema, - // tableNamesMap, - // table: fullSchema[relationTableTsName] as PgTable, - // tableConfig: schema[relationTableTsName]!, - // queryConfig: selectedRelationConfigValue, - // tableAlias: relationTableAlias, - // joinOn, - // }); - // const field = sql`case when ${sql.identifier(relationTableAlias)} is null then null else json_build_array(${ - // sql.join( - // builtRelation.selection.map(({ field }) => - // is(field, SQL.Aliased) - // ? sql`${sql.identifier(relationTableAlias)}.${sql.identifier(field.fieldAlias)}` - // : is(field, Column) - // ? aliasedTableColumn(field, relationTableAlias) - // : field - // ), - // sql`, `, - // ) - // }) end`.as(selectedRelationTsKey); - // const isLateralJoin = is(builtRelation.sql, SQL); - // joins.push({ - // on: isLateralJoin ? sql`true` : joinOn, - // table: is(builtRelation.sql, SQL) - // ? new Subquery(builtRelation.sql, {}, relationTableAlias) - // : aliasedTable(builtRelation.sql, relationTableAlias), - // alias: relationTableAlias, - // joinType: 'left', - // lateral: is(builtRelation.sql, SQL), - // }); - // selectedRelations.push({ - // dbKey: selectedRelationTsKey, - // tsKey: selectedRelationTsKey, - // field, - // relationTableTsKey: relationTableTsName, - // isJson: true, - // selection: builtRelation.selection, - // }); - // } - // let distinct: PgSelectConfig['distinct']; - // let tableFrom: PgTable | Subquery = table; - // // Process first Many relation - each one requires a nested subquery - // const manyRelation = manyRelations[0]; - // if (manyRelation) { - // const { - // tsKey: selectedRelationTsKey, - // queryConfig: selectedRelationQueryConfig, - // relation, - // } = manyRelation; - // distinct = { - // on: tableConfig.primaryKey.map((c) => aliasedTableColumn(c as PgColumn, tableAlias)), - // }; - // const normalizedRelation = normalizeRelation(schema, tableNamesMap, relation); - // const relationTableName = relation.referencedTable[Table.Symbol.Name]; - // const relationTableTsName = tableNamesMap[relationTableName]!; - // const relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`; - // const joinOn = and( - // ...normalizedRelation.fields.map((field, i) => - // eq( - // aliasedTableColumn(normalizedRelation.references[i]!, relationTableAlias), - // aliasedTableColumn(field, tableAlias), - // ) - // ), - // ); - // const builtRelationJoin = this.buildRelationalQueryWithPK({ - // fullSchema, - // schema, - // tableNamesMap, - // table: fullSchema[relationTableTsName] as PgTable, - // tableConfig: schema[relationTableTsName]!, - // queryConfig: selectedRelationQueryConfig, - // tableAlias: relationTableAlias, - // joinOn, - // }); - // const builtRelationSelectionField = sql`case when ${ - // sql.identifier(relationTableAlias) - // } is null then '[]' else json_agg(json_build_array(${ - // sql.join( - // builtRelationJoin.selection.map(({ field }) => - // is(field, SQL.Aliased) - // ? sql`${sql.identifier(relationTableAlias)}.${sql.identifier(field.fieldAlias)}` - // : is(field, Column) - // ? aliasedTableColumn(field, relationTableAlias) - // : field - // ), - // sql`, `, - // ) - // })) over (partition by ${sql.join(distinct.on, sql`, `)}) end`.as(selectedRelationTsKey); - // const isLateralJoin = is(builtRelationJoin.sql, SQL); - // joins.push({ - // on: isLateralJoin ? sql`true` : joinOn, - // table: isLateralJoin - // ? new Subquery(builtRelationJoin.sql as SQL, {}, relationTableAlias) - // : aliasedTable(builtRelationJoin.sql as PgTable, relationTableAlias), - // alias: relationTableAlias, - // joinType: 'left', - // lateral: isLateralJoin, - // }); - // // Build the "from" subquery with the remaining Many relations - // const builtTableFrom = this.buildRelationalQueryWithPK({ - // fullSchema, - // schema, - // tableNamesMap, - // table, - // tableConfig, - // queryConfig: { - // ...config, - // where: undefined, - // orderBy: undefined, - // limit: undefined, - // offset: undefined, - // with: manyRelations.slice(1).reduce>( - // (result, { tsKey, queryConfig: configValue }) => { - // result[tsKey] = configValue; - // return result; - // }, - // {}, - // ), - // }, - // tableAlias, - // }); - // selectedRelations.push({ - // dbKey: selectedRelationTsKey, - // tsKey: selectedRelationTsKey, - // field: builtRelationSelectionField, - // relationTableTsKey: relationTableTsName, - // isJson: true, - // selection: builtRelationJoin.selection, - // }); - // // selection = builtTableFrom.selection.map((item) => - // // is(item.field, SQL.Aliased) - // // ? { ...item, field: sql`${sql.identifier(tableAlias)}.${sql.identifier(item.field.fieldAlias)}` } - // // : item - // // ); - // // selectionForBuild = [{ - // // dbKey: '*', - // // tsKey: '*', - // // field: sql`${sql.identifier(tableAlias)}.*`, - // // selection: [], - // // isJson: false, - // // relationTableTsKey: undefined, - // // }]; - // // const newSelectionItem: (typeof selection)[number] = { - // // dbKey: selectedRelationTsKey, - // // tsKey: selectedRelationTsKey, - // // field, - // // relationTableTsKey: relationTableTsName, - // // isJson: true, - // // selection: builtRelationJoin.selection, - // // }; - // // selection.push(newSelectionItem); - // // selectionForBuild.push(newSelectionItem); - // tableFrom = is(builtTableFrom.sql, PgTable) - // ? builtTableFrom.sql - // : new Subquery(builtTableFrom.sql, {}, tableAlias); - // } - // if (selectedColumns.length === 0 && selectedRelations.length === 0 && selectedExtras.length === 0) { - // throw new DrizzleError(`No fields selected for table "${tableConfig.tsName}" ("${tableAlias}")`); - // } - // let selection: BuildRelationalQueryResult['selection']; - // function prepareSelectedColumns() { - // return selectedColumns.map((key) => ({ - // dbKey: tableConfig.columns[key]!.name, - // tsKey: key, - // field: tableConfig.columns[key] as PgColumn, - // relationTableTsKey: undefined, - // isJson: false, - // selection: [], - // })); - // } - // function prepareSelectedExtras() { - // return selectedExtras.map((item) => ({ - // dbKey: item.value.fieldAlias, - // tsKey: item.tsKey, - // field: item.value, - // relationTableTsKey: undefined, - // isJson: false, - // selection: [], - // })); - // } - // if (isRoot) { - // selection = [ - // ...prepareSelectedColumns(), - // ...prepareSelectedExtras(), - // ]; - // } - // if (hasUserDefinedWhere || orderBy.length > 0) { - // tableFrom = new Subquery( - // this.buildSelectQuery({ - // table: is(tableFrom, PgTable) ? aliasedTable(tableFrom, tableAlias) : tableFrom, - // fields: {}, - // fieldsFlat: selectionForBuild.map(({ field }) => ({ - // path: [], - // field: is(field, Column) ? aliasedTableColumn(field, tableAlias) : field, - // })), - // joins, - // distinct, - // }), - // {}, - // tableAlias, - // ); - // selectionForBuild = selection.map((item) => - // is(item.field, SQL.Aliased) - // ? { ...item, field: sql`${sql.identifier(tableAlias)}.${sql.identifier(item.field.fieldAlias)}` } - // : item - // ); - // joins = []; - // distinct = undefined; - // } - // const result = this.buildSelectQuery({ - // table: is(tableFrom, PgTable) ? aliasedTable(tableFrom, tableAlias) : tableFrom, - // fields: {}, - // fieldsFlat: selectionForBuild.map(({ field }) => ({ - // path: [], - // field: is(field, Column) ? aliasedTableColumn(field, tableAlias) : field, - // })), - // where, - // limit, - // offset, - // joins, - // orderBy, - // distinct, - // }); - // return { - // tableTsKey: tableConfig.tsName, - // sql: result, - // selection, - // }; - // } - buildRelationalQueryWithoutPK({ - fullSchema, - schema: schema2, - tableNamesMap, - table, - tableConfig, - queryConfig: config3, - tableAlias, - nestedQueryRelation, - joinOn - }) { - let selection = []; - let limit, offset, orderBy = [], where; - const joins = []; - if (config3 === true) { - const selectionEntries = Object.entries(tableConfig.columns); - selection = selectionEntries.map(([key, value]) => ({ - dbKey: value.name, - tsKey: key, - field: aliasedTableColumn(value, tableAlias), - relationTableTsKey: void 0, - isJson: false, - selection: [] - })); - } else { - const aliasedColumns = Object.fromEntries( - Object.entries(tableConfig.columns).map(([key, value]) => [key, aliasedTableColumn(value, tableAlias)]) - ); - if (config3.where) { - const whereSql = typeof config3.where === "function" ? config3.where(aliasedColumns, getOperators()) : config3.where; - where = whereSql && mapColumnsInSQLToAlias(whereSql, tableAlias); - } - const fieldsSelection = []; - let selectedColumns = []; - if (config3.columns) { - let isIncludeMode = false; - for (const [field, value] of Object.entries(config3.columns)) { - if (value === void 0) { - continue; - } - if (field in tableConfig.columns) { - if (!isIncludeMode && value === true) { - isIncludeMode = true; - } - selectedColumns.push(field); - } - } - if (selectedColumns.length > 0) { - selectedColumns = isIncludeMode ? selectedColumns.filter((c5) => config3.columns?.[c5] === true) : Object.keys(tableConfig.columns).filter((key) => !selectedColumns.includes(key)); - } - } else { - selectedColumns = Object.keys(tableConfig.columns); - } - for (const field of selectedColumns) { - const column = tableConfig.columns[field]; - fieldsSelection.push({ tsKey: field, value: column }); - } - let selectedRelations = []; - if (config3.with) { - selectedRelations = Object.entries(config3.with).filter((entry) => !!entry[1]).map(([tsKey, queryConfig]) => ({ tsKey, queryConfig, relation: tableConfig.relations[tsKey] })); - } - let extras; - if (config3.extras) { - extras = typeof config3.extras === "function" ? config3.extras(aliasedColumns, { sql }) : config3.extras; - for (const [tsKey, value] of Object.entries(extras)) { - fieldsSelection.push({ - tsKey, - value: mapColumnsInAliasedSQLToAlias(value, tableAlias) - }); - } - } - for (const { tsKey, value } of fieldsSelection) { - selection.push({ - dbKey: is(value, SQL.Aliased) ? value.fieldAlias : tableConfig.columns[tsKey].name, - tsKey, - field: is(value, Column) ? aliasedTableColumn(value, tableAlias) : value, - relationTableTsKey: void 0, - isJson: false, - selection: [] - }); - } - let orderByOrig = typeof config3.orderBy === "function" ? config3.orderBy(aliasedColumns, getOrderByOperators()) : config3.orderBy ?? []; - if (!Array.isArray(orderByOrig)) { - orderByOrig = [orderByOrig]; - } - orderBy = orderByOrig.map((orderByValue) => { - if (is(orderByValue, Column)) { - return aliasedTableColumn(orderByValue, tableAlias); - } - return mapColumnsInSQLToAlias(orderByValue, tableAlias); - }); - limit = config3.limit; - offset = config3.offset; - for (const { - tsKey: selectedRelationTsKey, - queryConfig: selectedRelationConfigValue, - relation - } of selectedRelations) { - const normalizedRelation = normalizeRelation(schema2, tableNamesMap, relation); - const relationTableName = getTableUniqueName(relation.referencedTable); - const relationTableTsName = tableNamesMap[relationTableName]; - const relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`; - const joinOn2 = and( - ...normalizedRelation.fields.map( - (field2, i5) => eq( - aliasedTableColumn(normalizedRelation.references[i5], relationTableAlias), - aliasedTableColumn(field2, tableAlias) - ) - ) - ); - const builtRelation = this.buildRelationalQueryWithoutPK({ - fullSchema, - schema: schema2, - tableNamesMap, - table: fullSchema[relationTableTsName], - tableConfig: schema2[relationTableTsName], - queryConfig: is(relation, One) ? selectedRelationConfigValue === true ? { limit: 1 } : { ...selectedRelationConfigValue, limit: 1 } : selectedRelationConfigValue, - tableAlias: relationTableAlias, - joinOn: joinOn2, - nestedQueryRelation: relation - }); - const field = sql`${sql.identifier(relationTableAlias)}.${sql.identifier("data")}`.as(selectedRelationTsKey); - joins.push({ - on: sql`true`, - table: new Subquery(builtRelation.sql, {}, relationTableAlias), - alias: relationTableAlias, - joinType: "left", - lateral: true - }); - selection.push({ - dbKey: selectedRelationTsKey, - tsKey: selectedRelationTsKey, - field, - relationTableTsKey: relationTableTsName, - isJson: true, - selection: builtRelation.selection - }); - } - } - if (selection.length === 0) { - throw new DrizzleError({ message: `No fields selected for table "${tableConfig.tsName}" ("${tableAlias}")` }); - } - let result; - where = and(joinOn, where); - if (nestedQueryRelation) { - let field = sql`json_build_array(${sql.join( - selection.map( - ({ field: field2, tsKey, isJson }) => isJson ? sql`${sql.identifier(`${tableAlias}_${tsKey}`)}.${sql.identifier("data")}` : is(field2, SQL.Aliased) ? field2.sql : field2 - ), - sql`, ` - )})`; - if (is(nestedQueryRelation, Many)) { - field = sql`coalesce(json_agg(${field}${orderBy.length > 0 ? sql` order by ${sql.join(orderBy, sql`, `)}` : void 0}), '[]'::json)`; - } - const nestedSelection = [{ - dbKey: "data", - tsKey: "data", - field: field.as("data"), - isJson: true, - relationTableTsKey: tableConfig.tsName, - selection - }]; - const needsSubquery = limit !== void 0 || offset !== void 0 || orderBy.length > 0; - if (needsSubquery) { - result = this.buildSelectQuery({ - table: aliasedTable(table, tableAlias), - fields: {}, - fieldsFlat: [{ - path: [], - field: sql.raw("*") - }], - where, - limit, - offset, - orderBy, - setOperators: [] - }); - where = void 0; - limit = void 0; - offset = void 0; - orderBy = []; - } else { - result = aliasedTable(table, tableAlias); - } - result = this.buildSelectQuery({ - table: is(result, PgTable) ? result : new Subquery(result, {}, tableAlias), - fields: {}, - fieldsFlat: nestedSelection.map(({ field: field2 }) => ({ - path: [], - field: is(field2, Column) ? aliasedTableColumn(field2, tableAlias) : field2 - })), - joins, - where, - limit, - offset, - orderBy, - setOperators: [] - }); - } else { - result = this.buildSelectQuery({ - table: aliasedTable(table, tableAlias), - fields: {}, - fieldsFlat: selection.map(({ field }) => ({ - path: [], - field: is(field, Column) ? aliasedTableColumn(field, tableAlias) : field - })), - joins, - where, - limit, - offset, - orderBy, - setOperators: [] - }); - } - return { - tableTsKey: tableConfig.tsName, - sql: result, - selection - }; - } - }; - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/selection-proxy.js -var SelectionProxyHandler; -var init_selection_proxy = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/selection-proxy.js"() { - init_alias(); - init_column(); - init_entity(); - init_sql(); - init_subquery(); - init_view_common(); - SelectionProxyHandler = class _SelectionProxyHandler { - static [entityKind] = "SelectionProxyHandler"; - config; - constructor(config3) { - this.config = { ...config3 }; - } - get(subquery, prop) { - if (prop === "_") { - return { - ...subquery["_"], - selectedFields: new Proxy( - subquery._.selectedFields, - this - ) - }; - } - if (prop === ViewBaseConfig) { - return { - ...subquery[ViewBaseConfig], - selectedFields: new Proxy( - subquery[ViewBaseConfig].selectedFields, - this - ) - }; - } - if (typeof prop === "symbol") { - return subquery[prop]; - } - const columns = is(subquery, Subquery) ? subquery._.selectedFields : is(subquery, View) ? subquery[ViewBaseConfig].selectedFields : subquery; - const value = columns[prop]; - if (is(value, SQL.Aliased)) { - if (this.config.sqlAliasedBehavior === "sql" && !value.isSelectionField) { - return value.sql; - } - const newValue = value.clone(); - newValue.isSelectionField = true; - return newValue; - } - if (is(value, SQL)) { - if (this.config.sqlBehavior === "sql") { - return value; - } - throw new Error( - `You tried to reference "${prop}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.` - ); - } - if (is(value, Column)) { - if (this.config.alias) { - return new Proxy( - value, - new ColumnAliasProxyHandler( - new Proxy( - value.table, - new TableAliasProxyHandler(this.config.alias, this.config.replaceOriginalName ?? false) - ) - ) - ); - } - return value; - } - if (typeof value !== "object" || value === null) { - return value; - } - return new Proxy(value, new _SelectionProxyHandler(this.config)); - } - }; - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/query-builders/query-builder.js -var TypedQueryBuilder; -var init_query_builder = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/query-builders/query-builder.js"() { - init_entity(); - TypedQueryBuilder = class { - static [entityKind] = "TypedQueryBuilder"; - /** @internal */ - getSelectedFields() { - return this._.selectedFields; - } - }; - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/query-builders/select.js -function createSetOperator(type, isAll) { - return (leftSelect, rightSelect, ...restSelects) => { - const setOperators = [rightSelect, ...restSelects].map((select2) => ({ - type, - isAll, - rightSelect: select2 - })); - for (const setOperator of setOperators) { - if (!haveSameKeys(leftSelect.getSelectedFields(), setOperator.rightSelect.getSelectedFields())) { - throw new Error( - "Set operator error (union / intersect / except): selected fields are not the same or are in a different order" - ); - } - } - return leftSelect.addSetOperators(setOperators); - }; -} -var PgSelectBuilder, PgSelectQueryBuilderBase, PgSelectBase, getPgSetOperators, union, unionAll, intersect, intersectAll, except, exceptAll; -var init_select2 = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/query-builders/select.js"() { - init_entity(); - init_view_base(); - init_query_builder(); - init_query_promise(); - init_selection_proxy(); - init_sql(); - init_subquery(); - init_table(); - init_tracing(); - init_utils(); - init_utils(); - init_view_common(); - PgSelectBuilder = class { - static [entityKind] = "PgSelectBuilder"; - fields; - session; - dialect; - withList = []; - distinct; - constructor(config3) { - this.fields = config3.fields; - this.session = config3.session; - this.dialect = config3.dialect; - if (config3.withList) { - this.withList = config3.withList; - } - this.distinct = config3.distinct; - } - authToken; - /** @internal */ - setToken(token) { - this.authToken = token; - return this; - } - /** - * Specify the table, subquery, or other target that you're - * building a select query against. - * - * {@link https://www.postgresql.org/docs/current/sql-select.html#SQL-FROM | Postgres from documentation} - */ - from(source) { - const isPartialSelect = !!this.fields; - let fields; - if (this.fields) { - fields = this.fields; - } else if (is(source, Subquery)) { - fields = Object.fromEntries( - Object.keys(source._.selectedFields).map((key) => [key, source[key]]) - ); - } else if (is(source, PgViewBase)) { - fields = source[ViewBaseConfig].selectedFields; - } else if (is(source, SQL)) { - fields = {}; - } else { - fields = getTableColumns(source); - } - return new PgSelectBase({ - table: source, - fields, - isPartialSelect, - session: this.session, - dialect: this.dialect, - withList: this.withList, - distinct: this.distinct - }).setToken(this.authToken); - } - }; - PgSelectQueryBuilderBase = class extends TypedQueryBuilder { - static [entityKind] = "PgSelectQueryBuilder"; - _; - config; - joinsNotNullableMap; - tableName; - isPartialSelect; - session; - dialect; - constructor({ table, fields, isPartialSelect, session, dialect, withList, distinct }) { - super(); - this.config = { - withList, - table, - fields: { ...fields }, - distinct, - setOperators: [] - }; - this.isPartialSelect = isPartialSelect; - this.session = session; - this.dialect = dialect; - this._ = { - selectedFields: fields - }; - this.tableName = getTableLikeName(table); - this.joinsNotNullableMap = typeof this.tableName === "string" ? { [this.tableName]: true } : {}; - } - createJoin(joinType) { - return (table, on) => { - const baseTableName = this.tableName; - const tableName = getTableLikeName(table); - if (typeof tableName === "string" && this.config.joins?.some((join4) => join4.alias === tableName)) { - throw new Error(`Alias "${tableName}" is already used in this query`); - } - if (!this.isPartialSelect) { - if (Object.keys(this.joinsNotNullableMap).length === 1 && typeof baseTableName === "string") { - this.config.fields = { - [baseTableName]: this.config.fields - }; - } - if (typeof tableName === "string" && !is(table, SQL)) { - const selection = is(table, Subquery) ? table._.selectedFields : is(table, View) ? table[ViewBaseConfig].selectedFields : table[Table.Symbol.Columns]; - this.config.fields[tableName] = selection; - } - } - if (typeof on === "function") { - on = on( - new Proxy( - this.config.fields, - new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" }) - ) - ); - } - if (!this.config.joins) { - this.config.joins = []; - } - this.config.joins.push({ on, table, joinType, alias: tableName }); - if (typeof tableName === "string") { - switch (joinType) { - case "left": { - this.joinsNotNullableMap[tableName] = false; - break; - } - case "right": { - this.joinsNotNullableMap = Object.fromEntries( - Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false]) - ); - this.joinsNotNullableMap[tableName] = true; - break; - } - case "inner": { - this.joinsNotNullableMap[tableName] = true; - break; - } - case "full": { - this.joinsNotNullableMap = Object.fromEntries( - Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false]) - ); - this.joinsNotNullableMap[tableName] = false; - break; - } - } - } - return this; - }; - } - /** - * Executes a `left join` operation by adding another table to the current query. - * - * Calling this method associates each row of the table with the corresponding row from the joined table, if a match is found. If no matching row exists, it sets all columns of the joined table to null. - * - * See docs: {@link https://orm.drizzle.team/docs/joins#left-join} - * - * @param table the table to join. - * @param on the `on` clause. - * - * @example - * - * ```ts - * // Select all users and their pets - * const usersWithPets: { user: User; pets: Pet | null }[] = await db.select() - * .from(users) - * .leftJoin(pets, eq(users.id, pets.ownerId)) - * - * // Select userId and petId - * const usersIdsAndPetIds: { userId: number; petId: number | null }[] = await db.select({ - * userId: users.id, - * petId: pets.id, - * }) - * .from(users) - * .leftJoin(pets, eq(users.id, pets.ownerId)) - * ``` - */ - leftJoin = this.createJoin("left"); - /** - * Executes a `right join` operation by adding another table to the current query. - * - * Calling this method associates each row of the joined table with the corresponding row from the main table, if a match is found. If no matching row exists, it sets all columns of the main table to null. - * - * See docs: {@link https://orm.drizzle.team/docs/joins#right-join} - * - * @param table the table to join. - * @param on the `on` clause. - * - * @example - * - * ```ts - * // Select all users and their pets - * const usersWithPets: { user: User | null; pets: Pet }[] = await db.select() - * .from(users) - * .rightJoin(pets, eq(users.id, pets.ownerId)) - * - * // Select userId and petId - * const usersIdsAndPetIds: { userId: number | null; petId: number }[] = await db.select({ - * userId: users.id, - * petId: pets.id, - * }) - * .from(users) - * .rightJoin(pets, eq(users.id, pets.ownerId)) - * ``` - */ - rightJoin = this.createJoin("right"); - /** - * Executes an `inner join` operation, creating a new table by combining rows from two tables that have matching values. - * - * Calling this method retrieves rows that have corresponding entries in both joined tables. Rows without matching entries in either table are excluded, resulting in a table that includes only matching pairs. - * - * See docs: {@link https://orm.drizzle.team/docs/joins#inner-join} - * - * @param table the table to join. - * @param on the `on` clause. - * - * @example - * - * ```ts - * // Select all users and their pets - * const usersWithPets: { user: User; pets: Pet }[] = await db.select() - * .from(users) - * .innerJoin(pets, eq(users.id, pets.ownerId)) - * - * // Select userId and petId - * const usersIdsAndPetIds: { userId: number; petId: number }[] = await db.select({ - * userId: users.id, - * petId: pets.id, - * }) - * .from(users) - * .innerJoin(pets, eq(users.id, pets.ownerId)) - * ``` - */ - innerJoin = this.createJoin("inner"); - /** - * Executes a `full join` operation by combining rows from two tables into a new table. - * - * Calling this method retrieves all rows from both main and joined tables, merging rows with matching values and filling in `null` for non-matching columns. - * - * See docs: {@link https://orm.drizzle.team/docs/joins#full-join} - * - * @param table the table to join. - * @param on the `on` clause. - * - * @example - * - * ```ts - * // Select all users and their pets - * const usersWithPets: { user: User | null; pets: Pet | null }[] = await db.select() - * .from(users) - * .fullJoin(pets, eq(users.id, pets.ownerId)) - * - * // Select userId and petId - * const usersIdsAndPetIds: { userId: number | null; petId: number | null }[] = await db.select({ - * userId: users.id, - * petId: pets.id, - * }) - * .from(users) - * .fullJoin(pets, eq(users.id, pets.ownerId)) - * ``` - */ - fullJoin = this.createJoin("full"); - createSetOperator(type, isAll) { - return (rightSelection) => { - const rightSelect = typeof rightSelection === "function" ? rightSelection(getPgSetOperators()) : rightSelection; - if (!haveSameKeys(this.getSelectedFields(), rightSelect.getSelectedFields())) { - throw new Error( - "Set operator error (union / intersect / except): selected fields are not the same or are in a different order" - ); - } - this.config.setOperators.push({ type, isAll, rightSelect }); - return this; - }; - } - /** - * Adds `union` set operator to the query. - * - * Calling this method will combine the result sets of the `select` statements and remove any duplicate rows that appear across them. - * - * See docs: {@link https://orm.drizzle.team/docs/set-operations#union} - * - * @example - * - * ```ts - * // Select all unique names from customers and users tables - * await db.select({ name: users.name }) - * .from(users) - * .union( - * db.select({ name: customers.name }).from(customers) - * ); - * // or - * import { union } from 'drizzle-orm/pg-core' - * - * await union( - * db.select({ name: users.name }).from(users), - * db.select({ name: customers.name }).from(customers) - * ); - * ``` - */ - union = this.createSetOperator("union", false); - /** - * Adds `union all` set operator to the query. - * - * Calling this method will combine the result-set of the `select` statements and keep all duplicate rows that appear across them. - * - * See docs: {@link https://orm.drizzle.team/docs/set-operations#union-all} - * - * @example - * - * ```ts - * // Select all transaction ids from both online and in-store sales - * await db.select({ transaction: onlineSales.transactionId }) - * .from(onlineSales) - * .unionAll( - * db.select({ transaction: inStoreSales.transactionId }).from(inStoreSales) - * ); - * // or - * import { unionAll } from 'drizzle-orm/pg-core' - * - * await unionAll( - * db.select({ transaction: onlineSales.transactionId }).from(onlineSales), - * db.select({ transaction: inStoreSales.transactionId }).from(inStoreSales) - * ); - * ``` - */ - unionAll = this.createSetOperator("union", true); - /** - * Adds `intersect` set operator to the query. - * - * Calling this method will retain only the rows that are present in both result sets and eliminate duplicates. - * - * See docs: {@link https://orm.drizzle.team/docs/set-operations#intersect} - * - * @example - * - * ```ts - * // Select course names that are offered in both departments A and B - * await db.select({ courseName: depA.courseName }) - * .from(depA) - * .intersect( - * db.select({ courseName: depB.courseName }).from(depB) - * ); - * // or - * import { intersect } from 'drizzle-orm/pg-core' - * - * await intersect( - * db.select({ courseName: depA.courseName }).from(depA), - * db.select({ courseName: depB.courseName }).from(depB) - * ); - * ``` - */ - intersect = this.createSetOperator("intersect", false); - /** - * Adds `intersect all` set operator to the query. - * - * Calling this method will retain only the rows that are present in both result sets including all duplicates. - * - * See docs: {@link https://orm.drizzle.team/docs/set-operations#intersect-all} - * - * @example - * - * ```ts - * // Select all products and quantities that are ordered by both regular and VIP customers - * await db.select({ - * productId: regularCustomerOrders.productId, - * quantityOrdered: regularCustomerOrders.quantityOrdered - * }) - * .from(regularCustomerOrders) - * .intersectAll( - * db.select({ - * productId: vipCustomerOrders.productId, - * quantityOrdered: vipCustomerOrders.quantityOrdered - * }) - * .from(vipCustomerOrders) - * ); - * // or - * import { intersectAll } from 'drizzle-orm/pg-core' - * - * await intersectAll( - * db.select({ - * productId: regularCustomerOrders.productId, - * quantityOrdered: regularCustomerOrders.quantityOrdered - * }) - * .from(regularCustomerOrders), - * db.select({ - * productId: vipCustomerOrders.productId, - * quantityOrdered: vipCustomerOrders.quantityOrdered - * }) - * .from(vipCustomerOrders) - * ); - * ``` - */ - intersectAll = this.createSetOperator("intersect", true); - /** - * Adds `except` set operator to the query. - * - * Calling this method will retrieve all unique rows from the left query, except for the rows that are present in the result set of the right query. - * - * See docs: {@link https://orm.drizzle.team/docs/set-operations#except} - * - * @example - * - * ```ts - * // Select all courses offered in department A but not in department B - * await db.select({ courseName: depA.courseName }) - * .from(depA) - * .except( - * db.select({ courseName: depB.courseName }).from(depB) - * ); - * // or - * import { except } from 'drizzle-orm/pg-core' - * - * await except( - * db.select({ courseName: depA.courseName }).from(depA), - * db.select({ courseName: depB.courseName }).from(depB) - * ); - * ``` - */ - except = this.createSetOperator("except", false); - /** - * Adds `except all` set operator to the query. - * - * Calling this method will retrieve all rows from the left query, except for the rows that are present in the result set of the right query. - * - * See docs: {@link https://orm.drizzle.team/docs/set-operations#except-all} - * - * @example - * - * ```ts - * // Select all products that are ordered by regular customers but not by VIP customers - * await db.select({ - * productId: regularCustomerOrders.productId, - * quantityOrdered: regularCustomerOrders.quantityOrdered, - * }) - * .from(regularCustomerOrders) - * .exceptAll( - * db.select({ - * productId: vipCustomerOrders.productId, - * quantityOrdered: vipCustomerOrders.quantityOrdered, - * }) - * .from(vipCustomerOrders) - * ); - * // or - * import { exceptAll } from 'drizzle-orm/pg-core' - * - * await exceptAll( - * db.select({ - * productId: regularCustomerOrders.productId, - * quantityOrdered: regularCustomerOrders.quantityOrdered - * }) - * .from(regularCustomerOrders), - * db.select({ - * productId: vipCustomerOrders.productId, - * quantityOrdered: vipCustomerOrders.quantityOrdered - * }) - * .from(vipCustomerOrders) - * ); - * ``` - */ - exceptAll = this.createSetOperator("except", true); - /** @internal */ - addSetOperators(setOperators) { - this.config.setOperators.push(...setOperators); - return this; - } - /** - * Adds a `where` clause to the query. - * - * Calling this method will select only those rows that fulfill a specified condition. - * - * See docs: {@link https://orm.drizzle.team/docs/select#filtering} - * - * @param where the `where` clause. - * - * @example - * You can use conditional operators and `sql function` to filter the rows to be selected. - * - * ```ts - * // Select all cars with green color - * await db.select().from(cars).where(eq(cars.color, 'green')); - * // or - * await db.select().from(cars).where(sql`${cars.color} = 'green'`) - * ``` - * - * You can logically combine conditional operators with `and()` and `or()` operators: - * - * ```ts - * // Select all BMW cars with a green color - * await db.select().from(cars).where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW'))); - * - * // Select all cars with the green or blue color - * await db.select().from(cars).where(or(eq(cars.color, 'green'), eq(cars.color, 'blue'))); - * ``` - */ - where(where) { - if (typeof where === "function") { - where = where( - new Proxy( - this.config.fields, - new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" }) - ) - ); - } - this.config.where = where; - return this; - } - /** - * Adds a `having` clause to the query. - * - * Calling this method will select only those rows that fulfill a specified condition. It is typically used with aggregate functions to filter the aggregated data based on a specified condition. - * - * See docs: {@link https://orm.drizzle.team/docs/select#aggregations} - * - * @param having the `having` clause. - * - * @example - * - * ```ts - * // Select all brands with more than one car - * await db.select({ - * brand: cars.brand, - * count: sql`cast(count(${cars.id}) as int)`, - * }) - * .from(cars) - * .groupBy(cars.brand) - * .having(({ count }) => gt(count, 1)); - * ``` - */ - having(having) { - if (typeof having === "function") { - having = having( - new Proxy( - this.config.fields, - new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" }) - ) - ); - } - this.config.having = having; - return this; - } - groupBy(...columns) { - if (typeof columns[0] === "function") { - const groupBy = columns[0]( - new Proxy( - this.config.fields, - new SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" }) - ) - ); - this.config.groupBy = Array.isArray(groupBy) ? groupBy : [groupBy]; - } else { - this.config.groupBy = columns; - } - return this; - } - orderBy(...columns) { - if (typeof columns[0] === "function") { - const orderBy = columns[0]( - new Proxy( - this.config.fields, - new SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" }) - ) - ); - const orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy]; - if (this.config.setOperators.length > 0) { - this.config.setOperators.at(-1).orderBy = orderByArray; - } else { - this.config.orderBy = orderByArray; - } - } else { - const orderByArray = columns; - if (this.config.setOperators.length > 0) { - this.config.setOperators.at(-1).orderBy = orderByArray; - } else { - this.config.orderBy = orderByArray; - } - } - return this; - } - /** - * Adds a `limit` clause to the query. - * - * Calling this method will set the maximum number of rows that will be returned by this query. - * - * See docs: {@link https://orm.drizzle.team/docs/select#limit--offset} - * - * @param limit the `limit` clause. - * - * @example - * - * ```ts - * // Get the first 10 people from this query. - * await db.select().from(people).limit(10); - * ``` - */ - limit(limit) { - if (this.config.setOperators.length > 0) { - this.config.setOperators.at(-1).limit = limit; - } else { - this.config.limit = limit; - } - return this; - } - /** - * Adds an `offset` clause to the query. - * - * Calling this method will skip a number of rows when returning results from this query. - * - * See docs: {@link https://orm.drizzle.team/docs/select#limit--offset} - * - * @param offset the `offset` clause. - * - * @example - * - * ```ts - * // Get the 10th-20th people from this query. - * await db.select().from(people).offset(10).limit(10); - * ``` - */ - offset(offset) { - if (this.config.setOperators.length > 0) { - this.config.setOperators.at(-1).offset = offset; - } else { - this.config.offset = offset; - } - return this; - } - /** - * Adds a `for` clause to the query. - * - * Calling this method will specify a lock strength for this query that controls how strictly it acquires exclusive access to the rows being queried. - * - * See docs: {@link https://www.postgresql.org/docs/current/sql-select.html#SQL-FOR-UPDATE-SHARE} - * - * @param strength the lock strength. - * @param config the lock configuration. - */ - for(strength, config3 = {}) { - this.config.lockingClause = { strength, config: config3 }; - return this; - } - /** @internal */ - getSQL() { - return this.dialect.buildSelectQuery(this.config); - } - toSQL() { - const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL()); - return rest; - } - as(alias) { - return new Proxy( - new Subquery(this.getSQL(), this.config.fields, alias), - new SelectionProxyHandler({ alias, sqlAliasedBehavior: "alias", sqlBehavior: "error" }) - ); - } - /** @internal */ - getSelectedFields() { - return new Proxy( - this.config.fields, - new SelectionProxyHandler({ alias: this.tableName, sqlAliasedBehavior: "alias", sqlBehavior: "error" }) - ); - } - $dynamic() { - return this; - } - }; - PgSelectBase = class extends PgSelectQueryBuilderBase { - static [entityKind] = "PgSelect"; - /** @internal */ - _prepare(name) { - const { session, config: config3, dialect, joinsNotNullableMap, authToken } = this; - if (!session) { - throw new Error("Cannot execute a query on a query builder. Please use a database instance instead."); - } - return tracer.startActiveSpan("drizzle.prepareQuery", () => { - const fieldsList = orderSelectedFields(config3.fields); - const query = session.prepareQuery(dialect.sqlToQuery(this.getSQL()), fieldsList, name, true); - query.joinsNotNullableMap = joinsNotNullableMap; - return query.setToken(authToken); - }); - } - /** - * Create a prepared statement for this query. This allows - * the database to remember this query for the given session - * and call it by name, rather than specifying the full query. - * - * {@link https://www.postgresql.org/docs/current/sql-prepare.html | Postgres prepare documentation} - */ - prepare(name) { - return this._prepare(name); - } - authToken; - /** @internal */ - setToken(token) { - this.authToken = token; - return this; - } - execute = (placeholderValues) => { - return tracer.startActiveSpan("drizzle.operation", () => { - return this._prepare().execute(placeholderValues, this.authToken); - }); - }; - }; - applyMixins(PgSelectBase, [QueryPromise]); - getPgSetOperators = () => ({ - union, - unionAll, - intersect, - intersectAll, - except, - exceptAll - }); - union = createSetOperator("union", false); - unionAll = createSetOperator("union", true); - intersect = createSetOperator("intersect", false); - intersectAll = createSetOperator("intersect", true); - except = createSetOperator("except", false); - exceptAll = createSetOperator("except", true); - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/query-builders/query-builder.js -var QueryBuilder; -var init_query_builder2 = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/query-builders/query-builder.js"() { - init_entity(); - init_dialect(); - init_selection_proxy(); - init_subquery(); - init_select2(); - QueryBuilder = class { - static [entityKind] = "PgQueryBuilder"; - dialect; - dialectConfig; - constructor(dialect) { - this.dialect = is(dialect, PgDialect) ? dialect : void 0; - this.dialectConfig = is(dialect, PgDialect) ? void 0 : dialect; - } - $with(alias) { - const queryBuilder = this; - return { - as(qb) { - if (typeof qb === "function") { - qb = qb(queryBuilder); - } - return new Proxy( - new WithSubquery(qb.getSQL(), qb.getSelectedFields(), alias, true), - new SelectionProxyHandler({ alias, sqlAliasedBehavior: "alias", sqlBehavior: "error" }) - ); - } - }; - } - with(...queries) { - const self2 = this; - function select2(fields) { - return new PgSelectBuilder({ - fields: fields ?? void 0, - session: void 0, - dialect: self2.getDialect(), - withList: queries - }); - } - function selectDistinct(fields) { - return new PgSelectBuilder({ - fields: fields ?? void 0, - session: void 0, - dialect: self2.getDialect(), - distinct: true - }); - } - function selectDistinctOn(on, fields) { - return new PgSelectBuilder({ - fields: fields ?? void 0, - session: void 0, - dialect: self2.getDialect(), - distinct: { on } - }); - } - return { select: select2, selectDistinct, selectDistinctOn }; - } - select(fields) { - return new PgSelectBuilder({ - fields: fields ?? void 0, - session: void 0, - dialect: this.getDialect() - }); - } - selectDistinct(fields) { - return new PgSelectBuilder({ - fields: fields ?? void 0, - session: void 0, - dialect: this.getDialect(), - distinct: true - }); - } - selectDistinctOn(on, fields) { - return new PgSelectBuilder({ - fields: fields ?? void 0, - session: void 0, - dialect: this.getDialect(), - distinct: { on } - }); - } - // Lazy load dialect to avoid circular dependency - getDialect() { - if (!this.dialect) { - this.dialect = new PgDialect(this.dialectConfig); - } - return this.dialect; - } - }; - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/query-builders/insert.js -var PgInsertBuilder, PgInsertBase; -var init_insert = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/query-builders/insert.js"() { - init_entity(); - init_query_promise(); - init_sql(); - init_table(); - init_tracing(); - init_utils(); - init_query_builder2(); - PgInsertBuilder = class { - constructor(table, session, dialect, withList, overridingSystemValue_) { - this.table = table; - this.session = session; - this.dialect = dialect; - this.withList = withList; - this.overridingSystemValue_ = overridingSystemValue_; - } - static [entityKind] = "PgInsertBuilder"; - authToken; - /** @internal */ - setToken(token) { - this.authToken = token; - return this; - } - overridingSystemValue() { - this.overridingSystemValue_ = true; - return this; - } - values(values2) { - values2 = Array.isArray(values2) ? values2 : [values2]; - if (values2.length === 0) { - throw new Error("values() must be called with at least one value"); - } - const mappedValues = values2.map((entry) => { - const result = {}; - const cols = this.table[Table.Symbol.Columns]; - for (const colKey of Object.keys(entry)) { - const colValue = entry[colKey]; - result[colKey] = is(colValue, SQL) ? colValue : new Param(colValue, cols[colKey]); - } - return result; - }); - return new PgInsertBase( - this.table, - mappedValues, - this.session, - this.dialect, - this.withList, - false, - this.overridingSystemValue_ - ).setToken(this.authToken); - } - select(selectQuery) { - const select2 = typeof selectQuery === "function" ? selectQuery(new QueryBuilder()) : selectQuery; - if (!is(select2, SQL) && !haveSameKeys(this.table[Columns], select2._.selectedFields)) { - throw new Error( - "Insert select error: selected fields are not the same or are in a different order compared to the table definition" - ); - } - return new PgInsertBase(this.table, select2, this.session, this.dialect, this.withList, true); - } - }; - PgInsertBase = class extends QueryPromise { - constructor(table, values2, session, dialect, withList, select2, overridingSystemValue_) { - super(); - this.session = session; - this.dialect = dialect; - this.config = { table, values: values2, withList, select: select2, overridingSystemValue_ }; - } - static [entityKind] = "PgInsert"; - config; - returning(fields = this.config.table[Table.Symbol.Columns]) { - this.config.returning = orderSelectedFields(fields); - return this; - } - /** - * Adds an `on conflict do nothing` clause to the query. - * - * Calling this method simply avoids inserting a row as its alternative action. - * - * See docs: {@link https://orm.drizzle.team/docs/insert#on-conflict-do-nothing} - * - * @param config The `target` and `where` clauses. - * - * @example - * ```ts - * // Insert one row and cancel the insert if there's a conflict - * await db.insert(cars) - * .values({ id: 1, brand: 'BMW' }) - * .onConflictDoNothing(); - * - * // Explicitly specify conflict target - * await db.insert(cars) - * .values({ id: 1, brand: 'BMW' }) - * .onConflictDoNothing({ target: cars.id }); - * ``` - */ - onConflictDoNothing(config3 = {}) { - if (config3.target === void 0) { - this.config.onConflict = sql`do nothing`; - } else { - let targetColumn = ""; - targetColumn = Array.isArray(config3.target) ? config3.target.map((it) => this.dialect.escapeName(this.dialect.casing.getColumnCasing(it))).join(",") : this.dialect.escapeName(this.dialect.casing.getColumnCasing(config3.target)); - const whereSql = config3.where ? sql` where ${config3.where}` : void 0; - this.config.onConflict = sql`(${sql.raw(targetColumn)})${whereSql} do nothing`; - } - return this; - } - /** - * Adds an `on conflict do update` clause to the query. - * - * Calling this method will update the existing row that conflicts with the row proposed for insertion as its alternative action. - * - * See docs: {@link https://orm.drizzle.team/docs/insert#upserts-and-conflicts} - * - * @param config The `target`, `set` and `where` clauses. - * - * @example - * ```ts - * // Update the row if there's a conflict - * await db.insert(cars) - * .values({ id: 1, brand: 'BMW' }) - * .onConflictDoUpdate({ - * target: cars.id, - * set: { brand: 'Porsche' } - * }); - * - * // Upsert with 'where' clause - * await db.insert(cars) - * .values({ id: 1, brand: 'BMW' }) - * .onConflictDoUpdate({ - * target: cars.id, - * set: { brand: 'newBMW' }, - * targetWhere: sql`${cars.createdAt} > '2023-01-01'::date`, - * }); - * ``` - */ - onConflictDoUpdate(config3) { - if (config3.where && (config3.targetWhere || config3.setWhere)) { - throw new Error( - 'You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.' - ); - } - const whereSql = config3.where ? sql` where ${config3.where}` : void 0; - const targetWhereSql = config3.targetWhere ? sql` where ${config3.targetWhere}` : void 0; - const setWhereSql = config3.setWhere ? sql` where ${config3.setWhere}` : void 0; - const setSql = this.dialect.buildUpdateSet(this.config.table, mapUpdateSet(this.config.table, config3.set)); - let targetColumn = ""; - targetColumn = Array.isArray(config3.target) ? config3.target.map((it) => this.dialect.escapeName(this.dialect.casing.getColumnCasing(it))).join(",") : this.dialect.escapeName(this.dialect.casing.getColumnCasing(config3.target)); - this.config.onConflict = sql`(${sql.raw(targetColumn)})${targetWhereSql} do update set ${setSql}${whereSql}${setWhereSql}`; - return this; - } - /** @internal */ - getSQL() { - return this.dialect.buildInsertQuery(this.config); - } - toSQL() { - const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL()); - return rest; - } - /** @internal */ - _prepare(name) { - return tracer.startActiveSpan("drizzle.prepareQuery", () => { - return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), this.config.returning, name, true); - }); - } - prepare(name) { - return this._prepare(name); - } - authToken; - /** @internal */ - setToken(token) { - this.authToken = token; - return this; - } - execute = (placeholderValues) => { - return tracer.startActiveSpan("drizzle.operation", () => { - return this._prepare().execute(placeholderValues, this.authToken); - }); - }; - $dynamic() { - return this; - } - }; - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/query-builders/refresh-materialized-view.js -var PgRefreshMaterializedView; -var init_refresh_materialized_view = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/query-builders/refresh-materialized-view.js"() { - init_entity(); - init_query_promise(); - init_tracing(); - PgRefreshMaterializedView = class extends QueryPromise { - constructor(view, session, dialect) { - super(); - this.session = session; - this.dialect = dialect; - this.config = { view }; - } - static [entityKind] = "PgRefreshMaterializedView"; - config; - concurrently() { - if (this.config.withNoData !== void 0) { - throw new Error("Cannot use concurrently and withNoData together"); - } - this.config.concurrently = true; - return this; - } - withNoData() { - if (this.config.concurrently !== void 0) { - throw new Error("Cannot use concurrently and withNoData together"); - } - this.config.withNoData = true; - return this; - } - /** @internal */ - getSQL() { - return this.dialect.buildRefreshMaterializedViewQuery(this.config); - } - toSQL() { - const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL()); - return rest; - } - /** @internal */ - _prepare(name) { - return tracer.startActiveSpan("drizzle.prepareQuery", () => { - return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), void 0, name, true); - }); - } - prepare(name) { - return this._prepare(name); - } - authToken; - /** @internal */ - setToken(token) { - this.authToken = token; - return this; - } - execute = (placeholderValues) => { - return tracer.startActiveSpan("drizzle.operation", () => { - return this._prepare().execute(placeholderValues, this.authToken); - }); - }; - }; - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/query-builders/select.types.js -var init_select_types = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/query-builders/select.types.js"() { - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/query-builders/update.js -var PgUpdateBuilder, PgUpdateBase; -var init_update = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/query-builders/update.js"() { - init_entity(); - init_table2(); - init_query_promise(); - init_selection_proxy(); - init_sql(); - init_subquery(); - init_table(); - init_utils(); - init_view_common(); - PgUpdateBuilder = class { - constructor(table, session, dialect, withList) { - this.table = table; - this.session = session; - this.dialect = dialect; - this.withList = withList; - } - static [entityKind] = "PgUpdateBuilder"; - authToken; - setToken(token) { - this.authToken = token; - return this; - } - set(values2) { - return new PgUpdateBase( - this.table, - mapUpdateSet(this.table, values2), - this.session, - this.dialect, - this.withList - ).setToken(this.authToken); - } - }; - PgUpdateBase = class extends QueryPromise { - constructor(table, set2, session, dialect, withList) { - super(); - this.session = session; - this.dialect = dialect; - this.config = { set: set2, table, withList, joins: [] }; - this.tableName = getTableLikeName(table); - this.joinsNotNullableMap = typeof this.tableName === "string" ? { [this.tableName]: true } : {}; - } - static [entityKind] = "PgUpdate"; - config; - tableName; - joinsNotNullableMap; - from(source) { - const tableName = getTableLikeName(source); - if (typeof tableName === "string") { - this.joinsNotNullableMap[tableName] = true; - } - this.config.from = source; - return this; - } - getTableLikeFields(table) { - if (is(table, PgTable)) { - return table[Table.Symbol.Columns]; - } else if (is(table, Subquery)) { - return table._.selectedFields; - } - return table[ViewBaseConfig].selectedFields; - } - createJoin(joinType) { - return (table, on) => { - const tableName = getTableLikeName(table); - if (typeof tableName === "string" && this.config.joins.some((join4) => join4.alias === tableName)) { - throw new Error(`Alias "${tableName}" is already used in this query`); - } - if (typeof on === "function") { - const from = this.config.from && !is(this.config.from, SQL) ? this.getTableLikeFields(this.config.from) : void 0; - on = on( - new Proxy( - this.config.table[Table.Symbol.Columns], - new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" }) - ), - from && new Proxy( - from, - new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" }) - ) - ); - } - this.config.joins.push({ on, table, joinType, alias: tableName }); - if (typeof tableName === "string") { - switch (joinType) { - case "left": { - this.joinsNotNullableMap[tableName] = false; - break; - } - case "right": { - this.joinsNotNullableMap = Object.fromEntries( - Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false]) - ); - this.joinsNotNullableMap[tableName] = true; - break; - } - case "inner": { - this.joinsNotNullableMap[tableName] = true; - break; - } - case "full": { - this.joinsNotNullableMap = Object.fromEntries( - Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false]) - ); - this.joinsNotNullableMap[tableName] = false; - break; - } - } - } - return this; - }; - } - leftJoin = this.createJoin("left"); - rightJoin = this.createJoin("right"); - innerJoin = this.createJoin("inner"); - fullJoin = this.createJoin("full"); - /** - * Adds a 'where' clause to the query. - * - * Calling this method will update only those rows that fulfill a specified condition. - * - * See docs: {@link https://orm.drizzle.team/docs/update} - * - * @param where the 'where' clause. - * - * @example - * You can use conditional operators and `sql function` to filter the rows to be updated. - * - * ```ts - * // Update all cars with green color - * await db.update(cars).set({ color: 'red' }) - * .where(eq(cars.color, 'green')); - * // or - * await db.update(cars).set({ color: 'red' }) - * .where(sql`${cars.color} = 'green'`) - * ``` - * - * You can logically combine conditional operators with `and()` and `or()` operators: - * - * ```ts - * // Update all BMW cars with a green color - * await db.update(cars).set({ color: 'red' }) - * .where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW'))); - * - * // Update all cars with the green or blue color - * await db.update(cars).set({ color: 'red' }) - * .where(or(eq(cars.color, 'green'), eq(cars.color, 'blue'))); - * ``` - */ - where(where) { - this.config.where = where; - return this; - } - returning(fields) { - if (!fields) { - fields = Object.assign({}, this.config.table[Table.Symbol.Columns]); - if (this.config.from) { - const tableName = getTableLikeName(this.config.from); - if (typeof tableName === "string" && this.config.from && !is(this.config.from, SQL)) { - const fromFields = this.getTableLikeFields(this.config.from); - fields[tableName] = fromFields; - } - for (const join4 of this.config.joins) { - const tableName2 = getTableLikeName(join4.table); - if (typeof tableName2 === "string" && !is(join4.table, SQL)) { - const fromFields = this.getTableLikeFields(join4.table); - fields[tableName2] = fromFields; - } - } - } - } - this.config.returning = orderSelectedFields(fields); - return this; - } - /** @internal */ - getSQL() { - return this.dialect.buildUpdateQuery(this.config); - } - toSQL() { - const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL()); - return rest; - } - /** @internal */ - _prepare(name) { - const query = this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), this.config.returning, name, true); - query.joinsNotNullableMap = this.joinsNotNullableMap; - return query; - } - prepare(name) { - return this._prepare(name); - } - authToken; - /** @internal */ - setToken(token) { - this.authToken = token; - return this; - } - execute = (placeholderValues) => { - return this._prepare().execute(placeholderValues, this.authToken); - }; - $dynamic() { - return this; - } - }; - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/query-builders/index.js -var init_query_builders = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/query-builders/index.js"() { - init_delete(); - init_insert(); - init_query_builder2(); - init_refresh_materialized_view(); - init_select2(); - init_select_types(); - init_update(); - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/query-builders/count.js -var PgCountBuilder; -var init_count = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/query-builders/count.js"() { - init_entity(); - init_sql(); - PgCountBuilder = class _PgCountBuilder extends SQL { - constructor(params) { - super(_PgCountBuilder.buildEmbeddedCount(params.source, params.filters).queryChunks); - this.params = params; - this.mapWith(Number); - this.session = params.session; - this.sql = _PgCountBuilder.buildCount( - params.source, - params.filters - ); - } - sql; - token; - static [entityKind] = "PgCountBuilder"; - [Symbol.toStringTag] = "PgCountBuilder"; - session; - static buildEmbeddedCount(source, filters) { - return sql`(select count(*) from ${source}${sql.raw(" where ").if(filters)}${filters})`; - } - static buildCount(source, filters) { - return sql`select count(*) as count from ${source}${sql.raw(" where ").if(filters)}${filters};`; - } - /** @intrnal */ - setToken(token) { - this.token = token; - return this; - } - then(onfulfilled, onrejected) { - return Promise.resolve(this.session.count(this.sql, this.token)).then( - onfulfilled, - onrejected - ); - } - catch(onRejected) { - return this.then(void 0, onRejected); - } - finally(onFinally) { - return this.then( - (value) => { - onFinally?.(); - return value; - }, - (reason) => { - onFinally?.(); - throw reason; - } - ); - } - }; - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/query-builders/query.js -var RelationalQueryBuilder, PgRelationalQuery; -var init_query2 = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/query-builders/query.js"() { - init_entity(); - init_query_promise(); - init_relations(); - init_tracing(); - RelationalQueryBuilder = class { - constructor(fullSchema, schema2, tableNamesMap, table, tableConfig, dialect, session) { - this.fullSchema = fullSchema; - this.schema = schema2; - this.tableNamesMap = tableNamesMap; - this.table = table; - this.tableConfig = tableConfig; - this.dialect = dialect; - this.session = session; - } - static [entityKind] = "PgRelationalQueryBuilder"; - findMany(config3) { - return new PgRelationalQuery( - this.fullSchema, - this.schema, - this.tableNamesMap, - this.table, - this.tableConfig, - this.dialect, - this.session, - config3 ? config3 : {}, - "many" - ); - } - findFirst(config3) { - return new PgRelationalQuery( - this.fullSchema, - this.schema, - this.tableNamesMap, - this.table, - this.tableConfig, - this.dialect, - this.session, - config3 ? { ...config3, limit: 1 } : { limit: 1 }, - "first" - ); - } - }; - PgRelationalQuery = class extends QueryPromise { - constructor(fullSchema, schema2, tableNamesMap, table, tableConfig, dialect, session, config3, mode) { - super(); - this.fullSchema = fullSchema; - this.schema = schema2; - this.tableNamesMap = tableNamesMap; - this.table = table; - this.tableConfig = tableConfig; - this.dialect = dialect; - this.session = session; - this.config = config3; - this.mode = mode; - } - static [entityKind] = "PgRelationalQuery"; - /** @internal */ - _prepare(name) { - return tracer.startActiveSpan("drizzle.prepareQuery", () => { - const { query, builtQuery } = this._toSQL(); - return this.session.prepareQuery( - builtQuery, - void 0, - name, - true, - (rawRows, mapColumnValue) => { - const rows = rawRows.map( - (row) => mapRelationalRow(this.schema, this.tableConfig, row, query.selection, mapColumnValue) - ); - if (this.mode === "first") { - return rows[0]; - } - return rows; - } - ); - }); - } - prepare(name) { - return this._prepare(name); - } - _getQuery() { - return this.dialect.buildRelationalQueryWithoutPK({ - fullSchema: this.fullSchema, - schema: this.schema, - tableNamesMap: this.tableNamesMap, - table: this.table, - tableConfig: this.tableConfig, - queryConfig: this.config, - tableAlias: this.tableConfig.tsName - }); - } - /** @internal */ - getSQL() { - return this._getQuery().sql; - } - _toSQL() { - const query = this._getQuery(); - const builtQuery = this.dialect.sqlToQuery(query.sql); - return { query, builtQuery }; - } - toSQL() { - return this._toSQL().builtQuery; - } - authToken; - /** @internal */ - setToken(token) { - this.authToken = token; - return this; - } - execute() { - return tracer.startActiveSpan("drizzle.operation", () => { - return this._prepare().execute(void 0, this.authToken); - }); - } - }; - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/query-builders/raw.js -var PgRaw; -var init_raw = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/query-builders/raw.js"() { - init_entity(); - init_query_promise(); - PgRaw = class extends QueryPromise { - constructor(execute11, sql3, query, mapBatchResult) { - super(); - this.execute = execute11; - this.sql = sql3; - this.query = query; - this.mapBatchResult = mapBatchResult; - } - static [entityKind] = "PgRaw"; - /** @internal */ - getSQL() { - return this.sql; - } - getQuery() { - return this.query; - } - mapResult(result, isFromBatch) { - return isFromBatch ? this.mapBatchResult(result) : result; - } - _prepare() { - return this; - } - /** @internal */ - isResponseInArrayMode() { - return false; - } - }; - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/db.js -var PgDatabase; -var init_db = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/db.js"() { - init_entity(); - init_query_builders(); - init_selection_proxy(); - init_sql(); - init_subquery(); - init_count(); - init_query2(); - init_raw(); - init_refresh_materialized_view(); - PgDatabase = class { - constructor(dialect, session, schema2) { - this.dialect = dialect; - this.session = session; - this._ = schema2 ? { - schema: schema2.schema, - fullSchema: schema2.fullSchema, - tableNamesMap: schema2.tableNamesMap, - session - } : { - schema: void 0, - fullSchema: {}, - tableNamesMap: {}, - session - }; - this.query = {}; - if (this._.schema) { - for (const [tableName, columns] of Object.entries(this._.schema)) { - this.query[tableName] = new RelationalQueryBuilder( - schema2.fullSchema, - this._.schema, - this._.tableNamesMap, - schema2.fullSchema[tableName], - columns, - dialect, - session - ); - } - } - } - static [entityKind] = "PgDatabase"; - query; - /** - * Creates a subquery that defines a temporary named result set as a CTE. - * - * It is useful for breaking down complex queries into simpler parts and for reusing the result set in subsequent parts of the query. - * - * See docs: {@link https://orm.drizzle.team/docs/select#with-clause} - * - * @param alias The alias for the subquery. - * - * Failure to provide an alias will result in a DrizzleTypeError, preventing the subquery from being referenced in other queries. - * - * @example - * - * ```ts - * // Create a subquery with alias 'sq' and use it in the select query - * const sq = db.$with('sq').as(db.select().from(users).where(eq(users.id, 42))); - * - * const result = await db.with(sq).select().from(sq); - * ``` - * - * To select arbitrary SQL values as fields in a CTE and reference them in other CTEs or in the main query, you need to add aliases to them: - * - * ```ts - * // Select an arbitrary SQL value as a field in a CTE and reference it in the main query - * const sq = db.$with('sq').as(db.select({ - * name: sql`upper(${users.name})`.as('name'), - * }) - * .from(users)); - * - * const result = await db.with(sq).select({ name: sq.name }).from(sq); - * ``` - */ - $with(alias) { - const self2 = this; - return { - as(qb) { - if (typeof qb === "function") { - qb = qb(new QueryBuilder(self2.dialect)); - } - return new Proxy( - new WithSubquery(qb.getSQL(), qb.getSelectedFields(), alias, true), - new SelectionProxyHandler({ alias, sqlAliasedBehavior: "alias", sqlBehavior: "error" }) - ); - } - }; - } - $count(source, filters) { - return new PgCountBuilder({ source, filters, session: this.session }); - } - /** - * Incorporates a previously defined CTE (using `$with`) into the main query. - * - * This method allows the main query to reference a temporary named result set. - * - * See docs: {@link https://orm.drizzle.team/docs/select#with-clause} - * - * @param queries The CTEs to incorporate into the main query. - * - * @example - * - * ```ts - * // Define a subquery 'sq' as a CTE using $with - * const sq = db.$with('sq').as(db.select().from(users).where(eq(users.id, 42))); - * - * // Incorporate the CTE 'sq' into the main query and select from it - * const result = await db.with(sq).select().from(sq); - * ``` - */ - with(...queries) { - const self2 = this; - function select2(fields) { - return new PgSelectBuilder({ - fields: fields ?? void 0, - session: self2.session, - dialect: self2.dialect, - withList: queries - }); - } - function selectDistinct(fields) { - return new PgSelectBuilder({ - fields: fields ?? void 0, - session: self2.session, - dialect: self2.dialect, - withList: queries, - distinct: true - }); - } - function selectDistinctOn(on, fields) { - return new PgSelectBuilder({ - fields: fields ?? void 0, - session: self2.session, - dialect: self2.dialect, - withList: queries, - distinct: { on } - }); - } - function update(table) { - return new PgUpdateBuilder(table, self2.session, self2.dialect, queries); - } - function insert(table) { - return new PgInsertBuilder(table, self2.session, self2.dialect, queries); - } - function delete_(table) { - return new PgDeleteBase(table, self2.session, self2.dialect, queries); - } - return { select: select2, selectDistinct, selectDistinctOn, update, insert, delete: delete_ }; - } - select(fields) { - return new PgSelectBuilder({ - fields: fields ?? void 0, - session: this.session, - dialect: this.dialect - }); - } - selectDistinct(fields) { - return new PgSelectBuilder({ - fields: fields ?? void 0, - session: this.session, - dialect: this.dialect, - distinct: true - }); - } - selectDistinctOn(on, fields) { - return new PgSelectBuilder({ - fields: fields ?? void 0, - session: this.session, - dialect: this.dialect, - distinct: { on } - }); - } - /** - * Creates an update query. - * - * Calling this method without `.where()` clause will update all rows in a table. The `.where()` clause specifies which rows should be updated. - * - * Use `.set()` method to specify which values to update. - * - * See docs: {@link https://orm.drizzle.team/docs/update} - * - * @param table The table to update. - * - * @example - * - * ```ts - * // Update all rows in the 'cars' table - * await db.update(cars).set({ color: 'red' }); - * - * // Update rows with filters and conditions - * await db.update(cars).set({ color: 'red' }).where(eq(cars.brand, 'BMW')); - * - * // Update with returning clause - * const updatedCar: Car[] = await db.update(cars) - * .set({ color: 'red' }) - * .where(eq(cars.id, 1)) - * .returning(); - * ``` - */ - update(table) { - return new PgUpdateBuilder(table, this.session, this.dialect); - } - /** - * Creates an insert query. - * - * Calling this method will create new rows in a table. Use `.values()` method to specify which values to insert. - * - * See docs: {@link https://orm.drizzle.team/docs/insert} - * - * @param table The table to insert into. - * - * @example - * - * ```ts - * // Insert one row - * await db.insert(cars).values({ brand: 'BMW' }); - * - * // Insert multiple rows - * await db.insert(cars).values([{ brand: 'BMW' }, { brand: 'Porsche' }]); - * - * // Insert with returning clause - * const insertedCar: Car[] = await db.insert(cars) - * .values({ brand: 'BMW' }) - * .returning(); - * ``` - */ - insert(table) { - return new PgInsertBuilder(table, this.session, this.dialect); - } - /** - * Creates a delete query. - * - * Calling this method without `.where()` clause will delete all rows in a table. The `.where()` clause specifies which rows should be deleted. - * - * See docs: {@link https://orm.drizzle.team/docs/delete} - * - * @param table The table to delete from. - * - * @example - * - * ```ts - * // Delete all rows in the 'cars' table - * await db.delete(cars); - * - * // Delete rows with filters and conditions - * await db.delete(cars).where(eq(cars.color, 'green')); - * - * // Delete with returning clause - * const deletedCar: Car[] = await db.delete(cars) - * .where(eq(cars.id, 1)) - * .returning(); - * ``` - */ - delete(table) { - return new PgDeleteBase(table, this.session, this.dialect); - } - refreshMaterializedView(view) { - return new PgRefreshMaterializedView(view, this.session, this.dialect); - } - authToken; - execute(query) { - const sequel = typeof query === "string" ? sql.raw(query) : query.getSQL(); - const builtQuery = this.dialect.sqlToQuery(sequel); - const prepared = this.session.prepareQuery( - builtQuery, - void 0, - void 0, - false - ); - return new PgRaw( - () => prepared.execute(void 0, this.authToken), - sequel, - builtQuery, - (result) => prepared.mapResult(result, true) - ); - } - transaction(transaction, config3) { - return this.session.transaction(transaction, config3); - } - }; - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/alias.js -var init_alias2 = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/alias.js"() { - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/checks.js -var CheckBuilder, Check; -var init_checks = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/checks.js"() { - init_entity(); - CheckBuilder = class { - constructor(name, value) { - this.name = name; - this.value = value; - } - static [entityKind] = "PgCheckBuilder"; - brand; - /** @internal */ - build(table) { - return new Check(table, this); - } - }; - Check = class { - constructor(table, builder) { - this.table = table; - this.name = builder.name; - this.value = builder.value; - } - static [entityKind] = "PgCheck"; - name; - value; - }; - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/indexes.js -function index(name) { - return new IndexBuilderOn(false, name); -} -function uniqueIndex(name) { - return new IndexBuilderOn(true, name); -} -var IndexBuilderOn, IndexBuilder, Index; -var init_indexes = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/indexes.js"() { - init_sql(); - init_entity(); - init_columns(); - IndexBuilderOn = class { - constructor(unique2, name) { - this.unique = unique2; - this.name = name; - } - static [entityKind] = "PgIndexBuilderOn"; - on(...columns) { - return new IndexBuilder( - columns.map((it) => { - if (is(it, SQL)) { - return it; - } - it = it; - const clonedIndexedColumn = new IndexedColumn(it.name, !!it.keyAsName, it.columnType, it.indexConfig); - it.indexConfig = JSON.parse(JSON.stringify(it.defaultConfig)); - return clonedIndexedColumn; - }), - this.unique, - false, - this.name - ); - } - onOnly(...columns) { - return new IndexBuilder( - columns.map((it) => { - if (is(it, SQL)) { - return it; - } - it = it; - const clonedIndexedColumn = new IndexedColumn(it.name, !!it.keyAsName, it.columnType, it.indexConfig); - it.indexConfig = it.defaultConfig; - return clonedIndexedColumn; - }), - this.unique, - true, - this.name - ); - } - /** - * Specify what index method to use. Choices are `btree`, `hash`, `gist`, `spgist`, `gin`, `brin`, or user-installed access methods like `bloom`. The default method is `btree. - * - * If you have the `pg_vector` extension installed in your database, you can use the `hnsw` and `ivfflat` options, which are predefined types. - * - * **You can always specify any string you want in the method, in case Drizzle doesn't have it natively in its types** - * - * @param method The name of the index method to be used - * @param columns - * @returns - */ - using(method, ...columns) { - return new IndexBuilder( - columns.map((it) => { - if (is(it, SQL)) { - return it; - } - it = it; - const clonedIndexedColumn = new IndexedColumn(it.name, !!it.keyAsName, it.columnType, it.indexConfig); - it.indexConfig = JSON.parse(JSON.stringify(it.defaultConfig)); - return clonedIndexedColumn; - }), - this.unique, - true, - this.name, - method - ); - } - }; - IndexBuilder = class { - static [entityKind] = "PgIndexBuilder"; - /** @internal */ - config; - constructor(columns, unique2, only, name, method = "btree") { - this.config = { - name, - columns, - unique: unique2, - only, - method - }; - } - concurrently() { - this.config.concurrently = true; - return this; - } - with(obj) { - this.config.with = obj; - return this; - } - where(condition) { - this.config.where = condition; - return this; - } - /** @internal */ - build(table) { - return new Index(this.config, table); - } - }; - Index = class { - static [entityKind] = "PgIndex"; - config; - constructor(config3, table) { - this.config = { ...config3, table }; - } - }; - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/policies.js -var PgPolicy; -var init_policies = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/policies.js"() { - init_entity(); - PgPolicy = class { - constructor(name, config3) { - this.name = name; - if (config3) { - this.as = config3.as; - this.for = config3.for; - this.to = config3.to; - this.using = config3.using; - this.withCheck = config3.withCheck; - } - } - static [entityKind] = "PgPolicy"; - as; - for; - to; - using; - withCheck; - /** @internal */ - _linkedTable; - link(table) { - this._linkedTable = table; - return this; - } - }; - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/roles.js -var PgRole; -var init_roles = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/roles.js"() { - init_entity(); - PgRole = class { - constructor(name, config3) { - this.name = name; - if (config3) { - this.createDb = config3.createDb; - this.createRole = config3.createRole; - this.inherit = config3.inherit; - } - } - static [entityKind] = "PgRole"; - /** @internal */ - _existing; - /** @internal */ - createDb; - /** @internal */ - createRole; - /** @internal */ - inherit; - existing() { - this._existing = true; - return this; - } - }; - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/sequence.js -function pgSequenceWithSchema(name, options, schema2) { - return new PgSequence(name, options, schema2); -} -var PgSequence; -var init_sequence = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/sequence.js"() { - init_entity(); - PgSequence = class { - constructor(seqName, seqOptions, schema2) { - this.seqName = seqName; - this.seqOptions = seqOptions; - this.schema = schema2; - } - static [entityKind] = "PgSequence"; - }; - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/view-common.js -var PgViewConfig; -var init_view_common2 = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/view-common.js"() { - PgViewConfig = /* @__PURE__ */ Symbol.for("drizzle:PgViewConfig"); - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/view.js -function pgViewWithSchema(name, selection, schema2) { - if (selection) { - return new ManualViewBuilder(name, selection, schema2); - } - return new ViewBuilder(name, schema2); -} -function pgMaterializedViewWithSchema(name, selection, schema2) { - if (selection) { - return new ManualMaterializedViewBuilder(name, selection, schema2); - } - return new MaterializedViewBuilder(name, schema2); -} -var DefaultViewBuilderCore, ViewBuilder, ManualViewBuilder, MaterializedViewBuilderCore, MaterializedViewBuilder, ManualMaterializedViewBuilder, PgView, PgMaterializedViewConfig, PgMaterializedView; -var init_view = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/view.js"() { - init_entity(); - init_selection_proxy(); - init_utils(); - init_query_builder2(); - init_table2(); - init_view_base(); - init_view_common2(); - DefaultViewBuilderCore = class { - constructor(name, schema2) { - this.name = name; - this.schema = schema2; - } - static [entityKind] = "PgDefaultViewBuilderCore"; - config = {}; - with(config3) { - this.config.with = config3; - return this; - } - }; - ViewBuilder = class extends DefaultViewBuilderCore { - static [entityKind] = "PgViewBuilder"; - as(qb) { - if (typeof qb === "function") { - qb = qb(new QueryBuilder()); - } - const selectionProxy = new SelectionProxyHandler({ - alias: this.name, - sqlBehavior: "error", - sqlAliasedBehavior: "alias", - replaceOriginalName: true - }); - const aliasedSelection = new Proxy(qb.getSelectedFields(), selectionProxy); - return new Proxy( - new PgView({ - pgConfig: this.config, - config: { - name: this.name, - schema: this.schema, - selectedFields: aliasedSelection, - query: qb.getSQL().inlineParams() - } - }), - selectionProxy - ); - } - }; - ManualViewBuilder = class extends DefaultViewBuilderCore { - static [entityKind] = "PgManualViewBuilder"; - columns; - constructor(name, columns, schema2) { - super(name, schema2); - this.columns = getTableColumns(pgTable(name, columns)); - } - existing() { - return new Proxy( - new PgView({ - pgConfig: void 0, - config: { - name: this.name, - schema: this.schema, - selectedFields: this.columns, - query: void 0 - } - }), - new SelectionProxyHandler({ - alias: this.name, - sqlBehavior: "error", - sqlAliasedBehavior: "alias", - replaceOriginalName: true - }) - ); - } - as(query) { - return new Proxy( - new PgView({ - pgConfig: this.config, - config: { - name: this.name, - schema: this.schema, - selectedFields: this.columns, - query: query.inlineParams() - } - }), - new SelectionProxyHandler({ - alias: this.name, - sqlBehavior: "error", - sqlAliasedBehavior: "alias", - replaceOriginalName: true - }) - ); - } - }; - MaterializedViewBuilderCore = class { - constructor(name, schema2) { - this.name = name; - this.schema = schema2; - } - static [entityKind] = "PgMaterializedViewBuilderCore"; - config = {}; - using(using) { - this.config.using = using; - return this; - } - with(config3) { - this.config.with = config3; - return this; - } - tablespace(tablespace) { - this.config.tablespace = tablespace; - return this; - } - withNoData() { - this.config.withNoData = true; - return this; - } - }; - MaterializedViewBuilder = class extends MaterializedViewBuilderCore { - static [entityKind] = "PgMaterializedViewBuilder"; - as(qb) { - if (typeof qb === "function") { - qb = qb(new QueryBuilder()); - } - const selectionProxy = new SelectionProxyHandler({ - alias: this.name, - sqlBehavior: "error", - sqlAliasedBehavior: "alias", - replaceOriginalName: true - }); - const aliasedSelection = new Proxy(qb.getSelectedFields(), selectionProxy); - return new Proxy( - new PgMaterializedView({ - pgConfig: { - with: this.config.with, - using: this.config.using, - tablespace: this.config.tablespace, - withNoData: this.config.withNoData - }, - config: { - name: this.name, - schema: this.schema, - selectedFields: aliasedSelection, - query: qb.getSQL().inlineParams() - } - }), - selectionProxy - ); - } - }; - ManualMaterializedViewBuilder = class extends MaterializedViewBuilderCore { - static [entityKind] = "PgManualMaterializedViewBuilder"; - columns; - constructor(name, columns, schema2) { - super(name, schema2); - this.columns = getTableColumns(pgTable(name, columns)); - } - existing() { - return new Proxy( - new PgMaterializedView({ - pgConfig: { - tablespace: this.config.tablespace, - using: this.config.using, - with: this.config.with, - withNoData: this.config.withNoData - }, - config: { - name: this.name, - schema: this.schema, - selectedFields: this.columns, - query: void 0 - } - }), - new SelectionProxyHandler({ - alias: this.name, - sqlBehavior: "error", - sqlAliasedBehavior: "alias", - replaceOriginalName: true - }) - ); - } - as(query) { - return new Proxy( - new PgMaterializedView({ - pgConfig: { - tablespace: this.config.tablespace, - using: this.config.using, - with: this.config.with, - withNoData: this.config.withNoData - }, - config: { - name: this.name, - schema: this.schema, - selectedFields: this.columns, - query: query.inlineParams() - } - }), - new SelectionProxyHandler({ - alias: this.name, - sqlBehavior: "error", - sqlAliasedBehavior: "alias", - replaceOriginalName: true - }) - ); - } - }; - PgView = class extends PgViewBase { - static [entityKind] = "PgView"; - [PgViewConfig]; - constructor({ pgConfig, config: config3 }) { - super(config3); - if (pgConfig) { - this[PgViewConfig] = { - with: pgConfig.with - }; - } - } - }; - PgMaterializedViewConfig = /* @__PURE__ */ Symbol.for("drizzle:PgMaterializedViewConfig"); - PgMaterializedView = class extends PgViewBase { - static [entityKind] = "PgMaterializedView"; - [PgMaterializedViewConfig]; - constructor({ pgConfig, config: config3 }) { - super(config3); - this[PgMaterializedViewConfig] = { - with: pgConfig?.with, - using: pgConfig?.using, - tablespace: pgConfig?.tablespace, - withNoData: pgConfig?.withNoData - }; - } - }; - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/schema.js -var PgSchema; -var init_schema = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/schema.js"() { - init_entity(); - init_sql(); - init_enum(); - init_sequence(); - init_table2(); - init_view(); - PgSchema = class { - constructor(schemaName) { - this.schemaName = schemaName; - } - static [entityKind] = "PgSchema"; - table = (name, columns, extraConfig) => { - return pgTableWithSchema(name, columns, extraConfig, this.schemaName); - }; - view = (name, columns) => { - return pgViewWithSchema(name, columns, this.schemaName); - }; - materializedView = (name, columns) => { - return pgMaterializedViewWithSchema(name, columns, this.schemaName); - }; - enum = (name, values2) => { - return pgEnumWithSchema(name, values2, this.schemaName); - }; - sequence = (name, options) => { - return pgSequenceWithSchema(name, options, this.schemaName); - }; - getSQL() { - return new SQL([sql.identifier(this.schemaName)]); - } - shouldOmitSQLParens() { - return true; - } - }; - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/session.js -var PgPreparedQuery, PgSession, PgTransaction; -var init_session = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/session.js"() { - init_entity(); - init_errors2(); - init_sql2(); - init_tracing(); - init_db(); - PgPreparedQuery = class { - constructor(query) { - this.query = query; - } - authToken; - getQuery() { - return this.query; - } - mapResult(response, _isFromBatch) { - return response; - } - /** @internal */ - setToken(token) { - this.authToken = token; - return this; - } - static [entityKind] = "PgPreparedQuery"; - /** @internal */ - joinsNotNullableMap; - }; - PgSession = class { - constructor(dialect) { - this.dialect = dialect; - } - static [entityKind] = "PgSession"; - /** @internal */ - execute(query, token) { - return tracer.startActiveSpan("drizzle.operation", () => { - const prepared = tracer.startActiveSpan("drizzle.prepareQuery", () => { - return this.prepareQuery( - this.dialect.sqlToQuery(query), - void 0, - void 0, - false - ); - }); - return prepared.setToken(token).execute(void 0, token); - }); - } - all(query) { - return this.prepareQuery( - this.dialect.sqlToQuery(query), - void 0, - void 0, - false - ).all(); - } - /** @internal */ - async count(sql22, token) { - const res = await this.execute(sql22, token); - return Number( - res[0]["count"] - ); - } - }; - PgTransaction = class extends PgDatabase { - constructor(dialect, session, schema2, nestedIndex = 0) { - super(dialect, session, schema2); - this.schema = schema2; - this.nestedIndex = nestedIndex; - } - static [entityKind] = "PgTransaction"; - rollback() { - throw new TransactionRollbackError(); - } - /** @internal */ - getTransactionConfigSQL(config3) { - const chunks = []; - if (config3.isolationLevel) { - chunks.push(`isolation level ${config3.isolationLevel}`); - } - if (config3.accessMode) { - chunks.push(config3.accessMode); - } - if (typeof config3.deferrable === "boolean") { - chunks.push(config3.deferrable ? "deferrable" : "not deferrable"); - } - return sql.raw(chunks.join(" ")); - } - setTransaction(config3) { - return this.session.execute(sql`set transaction ${this.getTransactionConfigSQL(config3)}`); - } - }; - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/subquery.js -var init_subquery2 = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/subquery.js"() { - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/utils.js -var init_utils3 = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/utils.js"() { - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/utils/index.js -var init_utils4 = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/utils/index.js"() { - init_array(); - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/index.js -var init_pg_core = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/pg-core/index.js"() { - init_alias2(); - init_checks(); - init_columns(); - init_db(); - init_dialect(); - init_foreign_keys(); - init_indexes(); - init_policies(); - init_primary_keys(); - init_query_builders(); - init_roles(); - init_schema(); - init_sequence(); - init_session(); - init_subquery2(); - init_table2(); - init_unique_constraint(); - init_utils3(); - init_utils4(); - init_view_common2(); - init_view(); - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/postgres-js/session.js -var PostgresJsPreparedQuery, PostgresJsSession, PostgresJsTransaction; -var init_session2 = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/postgres-js/session.js"() { - init_entity(); - init_logger(); - init_pg_core(); - init_session(); - init_sql(); - init_tracing(); - init_utils(); - PostgresJsPreparedQuery = class extends PgPreparedQuery { - constructor(client2, queryString, params, logger4, fields, _isResponseInArrayMode, customResultMapper) { - super({ sql: queryString, params }); - this.client = client2; - this.queryString = queryString; - this.params = params; - this.logger = logger4; - this.fields = fields; - this._isResponseInArrayMode = _isResponseInArrayMode; - this.customResultMapper = customResultMapper; - } - static [entityKind] = "PostgresJsPreparedQuery"; - async execute(placeholderValues = {}) { - return tracer.startActiveSpan("drizzle.execute", async (span) => { - const params = fillPlaceholders(this.params, placeholderValues); - span?.setAttributes({ - "drizzle.query.text": this.queryString, - "drizzle.query.params": JSON.stringify(params) - }); - this.logger.logQuery(this.queryString, params); - const { fields, queryString: query, client: client2, joinsNotNullableMap, customResultMapper } = this; - if (!fields && !customResultMapper) { - return tracer.startActiveSpan("drizzle.driver.execute", () => { - return client2.unsafe(query, params); - }); - } - const rows = await tracer.startActiveSpan("drizzle.driver.execute", () => { - span?.setAttributes({ - "drizzle.query.text": query, - "drizzle.query.params": JSON.stringify(params) - }); - return client2.unsafe(query, params).values(); - }); - return tracer.startActiveSpan("drizzle.mapResponse", () => { - return customResultMapper ? customResultMapper(rows) : rows.map((row) => mapResultRow(fields, row, joinsNotNullableMap)); - }); - }); - } - all(placeholderValues = {}) { - return tracer.startActiveSpan("drizzle.execute", async (span) => { - const params = fillPlaceholders(this.params, placeholderValues); - span?.setAttributes({ - "drizzle.query.text": this.queryString, - "drizzle.query.params": JSON.stringify(params) - }); - this.logger.logQuery(this.queryString, params); - return tracer.startActiveSpan("drizzle.driver.execute", () => { - span?.setAttributes({ - "drizzle.query.text": this.queryString, - "drizzle.query.params": JSON.stringify(params) - }); - return this.client.unsafe(this.queryString, params); - }); - }); - } - /** @internal */ - isResponseInArrayMode() { - return this._isResponseInArrayMode; - } - }; - PostgresJsSession = class _PostgresJsSession extends PgSession { - constructor(client2, dialect, schema2, options = {}) { - super(dialect); - this.client = client2; - this.schema = schema2; - this.options = options; - this.logger = options.logger ?? new NoopLogger(); - } - static [entityKind] = "PostgresJsSession"; - logger; - prepareQuery(query, fields, name, isResponseInArrayMode, customResultMapper) { - return new PostgresJsPreparedQuery( - this.client, - query.sql, - query.params, - this.logger, - fields, - isResponseInArrayMode, - customResultMapper - ); - } - query(query, params) { - this.logger.logQuery(query, params); - return this.client.unsafe(query, params).values(); - } - queryObjects(query, params) { - return this.client.unsafe(query, params); - } - transaction(transaction, config3) { - return this.client.begin(async (client2) => { - const session = new _PostgresJsSession( - client2, - this.dialect, - this.schema, - this.options - ); - const tx = new PostgresJsTransaction(this.dialect, session, this.schema); - if (config3) { - await tx.setTransaction(config3); - } - return transaction(tx); - }); - } - }; - PostgresJsTransaction = class _PostgresJsTransaction extends PgTransaction { - constructor(dialect, session, schema2, nestedIndex = 0) { - super(dialect, session, schema2, nestedIndex); - this.session = session; - } - static [entityKind] = "PostgresJsTransaction"; - transaction(transaction) { - return this.session.client.savepoint((client2) => { - const session = new PostgresJsSession( - client2, - this.dialect, - this.schema, - this.session.options - ); - const tx = new _PostgresJsTransaction(this.dialect, session, this.schema); - return transaction(tx); - }); - } - }; - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/postgres-js/driver.js -function construct(client2, config3 = {}) { - const transparentParser = (val) => val; - for (const type of ["1184", "1082", "1083", "1114"]) { - client2.options.parsers[type] = transparentParser; - client2.options.serializers[type] = transparentParser; - } - client2.options.serializers["114"] = transparentParser; - client2.options.serializers["3802"] = transparentParser; - const dialect = new PgDialect({ casing: config3.casing }); - let logger4; - if (config3.logger === true) { - logger4 = new DefaultLogger(); - } else if (config3.logger !== false) { - logger4 = config3.logger; - } - let schema2; - if (config3.schema) { - const tablesConfig = extractTablesRelationalConfig( - config3.schema, - createTableRelationsHelpers - ); - schema2 = { - fullSchema: config3.schema, - schema: tablesConfig.tables, - tableNamesMap: tablesConfig.tableNamesMap - }; - } - const session = new PostgresJsSession(client2, dialect, schema2, { logger: logger4 }); - const db = new PostgresJsDatabase(dialect, session, schema2); - db.$client = client2; - return db; -} -function drizzle(...params) { - if (typeof params[0] === "string") { - const instance = src_default(params[0]); - return construct(instance, params[1]); - } - if (isConfig(params[0])) { - const { connection: connection2, client: client2, ...drizzleConfig } = params[0]; - if (client2) - return construct(client2, drizzleConfig); - if (typeof connection2 === "object" && connection2.url !== void 0) { - const { url: url2, ...config3 } = connection2; - const instance2 = src_default(url2, config3); - return construct(instance2, drizzleConfig); - } - const instance = src_default(connection2); - return construct(instance, drizzleConfig); - } - return construct(params[0], params[1]); -} -var PostgresJsDatabase; -var init_driver = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/postgres-js/driver.js"() { - init_src(); - init_entity(); - init_logger(); - init_db(); - init_dialect(); - init_relations(); - init_utils(); - init_session2(); - PostgresJsDatabase = class extends PgDatabase { - static [entityKind] = "PostgresJsDatabase"; - }; - ((drizzle2) => { - function mock(config3) { - return construct({ - options: { - parsers: {}, - serializers: {} - } - }, config3); - } - drizzle2.mock = mock; - })(drizzle || (drizzle = {})); - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/postgres-js/index.js -var init_postgres_js = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/postgres-js/index.js"() { - init_driver(); - init_session2(); - } -}); - -// packages/db/src/schema/companies.ts -var companies; -var init_companies = __esm({ - "packages/db/src/schema/companies.ts"() { - "use strict"; - init_pg_core(); - companies = pgTable( - "companies", - { - id: uuid("id").primaryKey().defaultRandom(), - name: text("name").notNull(), - description: text("description"), - status: text("status").notNull().default("active"), - pauseReason: text("pause_reason"), - pausedAt: timestamp("paused_at", { withTimezone: true }), - issuePrefix: text("issue_prefix").notNull().default("PAP"), - issueCounter: integer("issue_counter").notNull().default(0), - budgetMonthlyCents: integer("budget_monthly_cents").notNull().default(0), - spentMonthlyCents: integer("spent_monthly_cents").notNull().default(0), - requireBoardApprovalForNewAgents: boolean("require_board_approval_for_new_agents").notNull().default(true), - feedbackDataSharingEnabled: boolean("feedback_data_sharing_enabled").notNull().default(false), - feedbackDataSharingConsentAt: timestamp("feedback_data_sharing_consent_at", { withTimezone: true }), - feedbackDataSharingConsentByUserId: text("feedback_data_sharing_consent_by_user_id"), - feedbackDataSharingTermsVersion: text("feedback_data_sharing_terms_version"), - brandColor: text("brand_color"), - createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), - updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() - }, - (table) => ({ - issuePrefixUniqueIdx: uniqueIndex("companies_issue_prefix_idx").on(table.issuePrefix) - }) - ); - } -}); - -// packages/db/src/schema/agents.ts -var agents; -var init_agents = __esm({ - "packages/db/src/schema/agents.ts"() { - "use strict"; - init_pg_core(); - init_companies(); - agents = pgTable( - "agents", - { - id: uuid("id").primaryKey().defaultRandom(), - companyId: uuid("company_id").notNull().references(() => companies.id), - name: text("name").notNull(), - role: text("role").notNull().default("general"), - title: text("title"), - icon: text("icon"), - status: text("status").notNull().default("idle"), - reportsTo: uuid("reports_to").references(() => agents.id), - capabilities: text("capabilities"), - adapterType: text("adapter_type").notNull().default("process"), - adapterConfig: jsonb("adapter_config").$type().notNull().default({}), - runtimeConfig: jsonb("runtime_config").$type().notNull().default({}), - budgetMonthlyCents: integer("budget_monthly_cents").notNull().default(0), - spentMonthlyCents: integer("spent_monthly_cents").notNull().default(0), - pauseReason: text("pause_reason"), - pausedAt: timestamp("paused_at", { withTimezone: true }), - permissions: jsonb("permissions").$type().notNull().default({}), - lastHeartbeatAt: timestamp("last_heartbeat_at", { withTimezone: true }), - metadata: jsonb("metadata").$type(), - createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), - updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() - }, - (table) => ({ - companyStatusIdx: index("agents_company_status_idx").on(table.companyId, table.status), - companyReportsToIdx: index("agents_company_reports_to_idx").on(table.companyId, table.reportsTo) - }) - ); - } -}); - -// packages/db/src/schema/assets.ts -var assets; -var init_assets = __esm({ - "packages/db/src/schema/assets.ts"() { - "use strict"; - init_pg_core(); - init_companies(); - init_agents(); - assets = pgTable( - "assets", - { - id: uuid("id").primaryKey().defaultRandom(), - companyId: uuid("company_id").notNull().references(() => companies.id), - provider: text("provider").notNull(), - objectKey: text("object_key").notNull(), - contentType: text("content_type").notNull(), - byteSize: integer("byte_size").notNull(), - sha256: text("sha256").notNull(), - originalFilename: text("original_filename"), - createdByAgentId: uuid("created_by_agent_id").references(() => agents.id), - createdByUserId: text("created_by_user_id"), - createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), - updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() - }, - (table) => ({ - companyCreatedIdx: index("assets_company_created_idx").on(table.companyId, table.createdAt), - companyProviderIdx: index("assets_company_provider_idx").on(table.companyId, table.provider), - companyObjectKeyUq: uniqueIndex("assets_company_object_key_uq").on(table.companyId, table.objectKey) - }) - ); - } -}); - -// packages/db/src/schema/company_logos.ts -var companyLogos; -var init_company_logos = __esm({ - "packages/db/src/schema/company_logos.ts"() { - "use strict"; - init_pg_core(); - init_companies(); - init_assets(); - companyLogos = pgTable( - "company_logos", - { - id: uuid("id").primaryKey().defaultRandom(), - companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }), - assetId: uuid("asset_id").notNull().references(() => assets.id, { onDelete: "cascade" }), - createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), - updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() - }, - (table) => ({ - companyUq: uniqueIndex("company_logos_company_uq").on(table.companyId), - assetUq: uniqueIndex("company_logos_asset_uq").on(table.assetId) - }) - ); - } -}); - -// packages/db/src/schema/auth.ts -var authUsers, authSessions, authAccounts, authVerifications; -var init_auth = __esm({ - "packages/db/src/schema/auth.ts"() { - "use strict"; - init_pg_core(); - authUsers = pgTable("user", { - id: text("id").primaryKey(), - name: text("name").notNull(), - email: text("email").notNull(), - emailVerified: boolean("email_verified").notNull().default(false), - image: text("image"), - createdAt: timestamp("created_at", { withTimezone: true }).notNull(), - updatedAt: timestamp("updated_at", { withTimezone: true }).notNull() - }); - authSessions = pgTable("session", { - id: text("id").primaryKey(), - expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(), - token: text("token").notNull(), - createdAt: timestamp("created_at", { withTimezone: true }).notNull(), - updatedAt: timestamp("updated_at", { withTimezone: true }).notNull(), - ipAddress: text("ip_address"), - userAgent: text("user_agent"), - userId: text("user_id").notNull().references(() => authUsers.id, { onDelete: "cascade" }) - }); - authAccounts = pgTable("account", { - id: text("id").primaryKey(), - accountId: text("account_id").notNull(), - providerId: text("provider_id").notNull(), - userId: text("user_id").notNull().references(() => authUsers.id, { onDelete: "cascade" }), - accessToken: text("access_token"), - refreshToken: text("refresh_token"), - idToken: text("id_token"), - accessTokenExpiresAt: timestamp("access_token_expires_at", { withTimezone: true }), - refreshTokenExpiresAt: timestamp("refresh_token_expires_at", { withTimezone: true }), - scope: text("scope"), - password: text("password"), - createdAt: timestamp("created_at", { withTimezone: true }).notNull(), - updatedAt: timestamp("updated_at", { withTimezone: true }).notNull() - }); - authVerifications = pgTable("verification", { - id: text("id").primaryKey(), - identifier: text("identifier").notNull(), - value: text("value").notNull(), - expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(), - createdAt: timestamp("created_at", { withTimezone: true }), - updatedAt: timestamp("updated_at", { withTimezone: true }) - }); - } -}); - -// packages/db/src/schema/instance_settings.ts -var instanceSettings; -var init_instance_settings = __esm({ - "packages/db/src/schema/instance_settings.ts"() { - "use strict"; - init_pg_core(); - instanceSettings = pgTable( - "instance_settings", - { - id: uuid("id").primaryKey().defaultRandom(), - singletonKey: text("singleton_key").notNull().default("default"), - general: jsonb("general").$type().notNull().default({}), - experimental: jsonb("experimental").$type().notNull().default({}), - createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), - updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() - }, - (table) => ({ - singletonKeyIdx: uniqueIndex("instance_settings_singleton_key_idx").on(table.singletonKey) - }) - ); - } -}); - -// packages/db/src/schema/instance_user_roles.ts -var instanceUserRoles; -var init_instance_user_roles = __esm({ - "packages/db/src/schema/instance_user_roles.ts"() { - "use strict"; - init_pg_core(); - instanceUserRoles = pgTable( - "instance_user_roles", - { - id: uuid("id").primaryKey().defaultRandom(), - userId: text("user_id").notNull(), - role: text("role").notNull().default("instance_admin"), - createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), - updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() - }, - (table) => ({ - userRoleUniqueIdx: uniqueIndex("instance_user_roles_user_role_unique_idx").on(table.userId, table.role), - roleIdx: index("instance_user_roles_role_idx").on(table.role) - }) - ); - } -}); - -// packages/db/src/schema/user_sidebar_preferences.ts -var userSidebarPreferences; -var init_user_sidebar_preferences = __esm({ - "packages/db/src/schema/user_sidebar_preferences.ts"() { - "use strict"; - init_pg_core(); - userSidebarPreferences = pgTable( - "user_sidebar_preferences", - { - id: uuid("id").primaryKey().defaultRandom(), - userId: text("user_id").notNull(), - companyOrder: jsonb("company_order").$type().notNull().default([]), - createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), - updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() - }, - (table) => ({ - userUq: uniqueIndex("user_sidebar_preferences_user_uq").on(table.userId) - }) - ); - } -}); - -// packages/db/src/schema/board_api_keys.ts -var boardApiKeys; -var init_board_api_keys = __esm({ - "packages/db/src/schema/board_api_keys.ts"() { - "use strict"; - init_pg_core(); - init_auth(); - boardApiKeys = pgTable( - "board_api_keys", - { - id: uuid("id").primaryKey().defaultRandom(), - userId: text("user_id").notNull().references(() => authUsers.id, { onDelete: "cascade" }), - name: text("name").notNull(), - keyHash: text("key_hash").notNull(), - lastUsedAt: timestamp("last_used_at", { withTimezone: true }), - revokedAt: timestamp("revoked_at", { withTimezone: true }), - expiresAt: timestamp("expires_at", { withTimezone: true }), - createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow() - }, - (table) => ({ - keyHashIdx: uniqueIndex("board_api_keys_key_hash_idx").on(table.keyHash), - userIdx: index("board_api_keys_user_idx").on(table.userId) - }) - ); - } -}); - -// packages/db/src/schema/cli_auth_challenges.ts -var cliAuthChallenges; -var init_cli_auth_challenges = __esm({ - "packages/db/src/schema/cli_auth_challenges.ts"() { - "use strict"; - init_pg_core(); - init_auth(); - init_companies(); - init_board_api_keys(); - cliAuthChallenges = pgTable( - "cli_auth_challenges", - { - id: uuid("id").primaryKey().defaultRandom(), - secretHash: text("secret_hash").notNull(), - command: text("command").notNull(), - clientName: text("client_name"), - requestedAccess: text("requested_access").notNull().default("board"), - requestedCompanyId: uuid("requested_company_id").references(() => companies.id, { onDelete: "set null" }), - pendingKeyHash: text("pending_key_hash").notNull(), - pendingKeyName: text("pending_key_name").notNull(), - approvedByUserId: text("approved_by_user_id").references(() => authUsers.id, { onDelete: "set null" }), - boardApiKeyId: uuid("board_api_key_id").references(() => boardApiKeys.id, { onDelete: "set null" }), - approvedAt: timestamp("approved_at", { withTimezone: true }), - cancelledAt: timestamp("cancelled_at", { withTimezone: true }), - expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(), - createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), - updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() - }, - (table) => ({ - secretHashIdx: index("cli_auth_challenges_secret_hash_idx").on(table.secretHash), - approvedByIdx: index("cli_auth_challenges_approved_by_idx").on(table.approvedByUserId), - requestedCompanyIdx: index("cli_auth_challenges_requested_company_idx").on(table.requestedCompanyId) - }) - ); - } -}); - -// packages/db/src/schema/company_memberships.ts -var companyMemberships; -var init_company_memberships = __esm({ - "packages/db/src/schema/company_memberships.ts"() { - "use strict"; - init_pg_core(); - init_companies(); - companyMemberships = pgTable( - "company_memberships", - { - id: uuid("id").primaryKey().defaultRandom(), - companyId: uuid("company_id").notNull().references(() => companies.id), - principalType: text("principal_type").notNull(), - principalId: text("principal_id").notNull(), - status: text("status").notNull().default("active"), - membershipRole: text("membership_role"), - createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), - updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() - }, - (table) => ({ - companyPrincipalUniqueIdx: uniqueIndex("company_memberships_company_principal_unique_idx").on( - table.companyId, - table.principalType, - table.principalId - ), - principalStatusIdx: index("company_memberships_principal_status_idx").on( - table.principalType, - table.principalId, - table.status - ), - companyStatusIdx: index("company_memberships_company_status_idx").on(table.companyId, table.status) - }) - ); - } -}); - -// packages/db/src/schema/company_user_sidebar_preferences.ts -var companyUserSidebarPreferences; -var init_company_user_sidebar_preferences = __esm({ - "packages/db/src/schema/company_user_sidebar_preferences.ts"() { - "use strict"; - init_pg_core(); - init_companies(); - companyUserSidebarPreferences = pgTable( - "company_user_sidebar_preferences", - { - id: uuid("id").primaryKey().defaultRandom(), - companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }), - userId: text("user_id").notNull(), - projectOrder: jsonb("project_order").$type().notNull().default([]), - createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), - updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() - }, - (table) => ({ - companyIdx: index("company_user_sidebar_preferences_company_idx").on(table.companyId), - userIdx: index("company_user_sidebar_preferences_user_idx").on(table.userId), - companyUserUq: uniqueIndex("company_user_sidebar_preferences_company_user_uq").on( - table.companyId, - table.userId - ) - }) - ); - } -}); - -// packages/db/src/schema/principal_permission_grants.ts -var principalPermissionGrants; -var init_principal_permission_grants = __esm({ - "packages/db/src/schema/principal_permission_grants.ts"() { - "use strict"; - init_pg_core(); - init_companies(); - principalPermissionGrants = pgTable( - "principal_permission_grants", - { - id: uuid("id").primaryKey().defaultRandom(), - companyId: uuid("company_id").notNull().references(() => companies.id), - principalType: text("principal_type").notNull(), - principalId: text("principal_id").notNull(), - permissionKey: text("permission_key").notNull(), - scope: jsonb("scope").$type(), - grantedByUserId: text("granted_by_user_id"), - createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), - updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() - }, - (table) => ({ - uniqueGrantIdx: uniqueIndex("principal_permission_grants_unique_idx").on( - table.companyId, - table.principalType, - table.principalId, - table.permissionKey - ), - companyPermissionIdx: index("principal_permission_grants_company_permission_idx").on( - table.companyId, - table.permissionKey - ) - }) - ); - } -}); - -// packages/db/src/schema/invites.ts -var invites; -var init_invites = __esm({ - "packages/db/src/schema/invites.ts"() { - "use strict"; - init_pg_core(); - init_companies(); - invites = pgTable( - "invites", - { - id: uuid("id").primaryKey().defaultRandom(), - companyId: uuid("company_id").references(() => companies.id), - inviteType: text("invite_type").notNull().default("company_join"), - tokenHash: text("token_hash").notNull(), - allowedJoinTypes: text("allowed_join_types").notNull().default("both"), - defaultsPayload: jsonb("defaults_payload").$type(), - expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(), - invitedByUserId: text("invited_by_user_id"), - revokedAt: timestamp("revoked_at", { withTimezone: true }), - acceptedAt: timestamp("accepted_at", { withTimezone: true }), - createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), - updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() - }, - (table) => ({ - tokenHashUniqueIdx: uniqueIndex("invites_token_hash_unique_idx").on(table.tokenHash), - companyInviteStateIdx: index("invites_company_invite_state_idx").on( - table.companyId, - table.inviteType, - table.revokedAt, - table.expiresAt - ) - }) - ); - } -}); - -// packages/db/src/schema/join_requests.ts -var joinRequests; -var init_join_requests = __esm({ - "packages/db/src/schema/join_requests.ts"() { - "use strict"; - init_pg_core(); - init_companies(); - init_invites(); - init_agents(); - joinRequests = pgTable( - "join_requests", - { - id: uuid("id").primaryKey().defaultRandom(), - inviteId: uuid("invite_id").notNull().references(() => invites.id), - companyId: uuid("company_id").notNull().references(() => companies.id), - requestType: text("request_type").notNull(), - status: text("status").notNull().default("pending_approval"), - requestIp: text("request_ip").notNull(), - requestingUserId: text("requesting_user_id"), - requestEmailSnapshot: text("request_email_snapshot"), - agentName: text("agent_name"), - adapterType: text("adapter_type"), - capabilities: text("capabilities"), - agentDefaultsPayload: jsonb("agent_defaults_payload").$type(), - claimSecretHash: text("claim_secret_hash"), - claimSecretExpiresAt: timestamp("claim_secret_expires_at", { withTimezone: true }), - claimSecretConsumedAt: timestamp("claim_secret_consumed_at", { withTimezone: true }), - createdAgentId: uuid("created_agent_id").references(() => agents.id), - approvedByUserId: text("approved_by_user_id"), - approvedAt: timestamp("approved_at", { withTimezone: true }), - rejectedByUserId: text("rejected_by_user_id"), - rejectedAt: timestamp("rejected_at", { withTimezone: true }), - createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), - updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() - }, - (table) => ({ - inviteUniqueIdx: uniqueIndex("join_requests_invite_unique_idx").on(table.inviteId), - companyStatusTypeCreatedIdx: index("join_requests_company_status_type_created_idx").on( - table.companyId, - table.status, - table.requestType, - table.createdAt - ) - }) - ); - } -}); - -// packages/db/src/schema/budget_policies.ts -var budgetPolicies; -var init_budget_policies = __esm({ - "packages/db/src/schema/budget_policies.ts"() { - "use strict"; - init_pg_core(); - init_companies(); - budgetPolicies = pgTable( - "budget_policies", - { - id: uuid("id").primaryKey().defaultRandom(), - companyId: uuid("company_id").notNull().references(() => companies.id), - scopeType: text("scope_type").notNull(), - scopeId: uuid("scope_id").notNull(), - metric: text("metric").notNull().default("billed_cents"), - windowKind: text("window_kind").notNull(), - amount: integer("amount").notNull().default(0), - warnPercent: integer("warn_percent").notNull().default(80), - hardStopEnabled: boolean("hard_stop_enabled").notNull().default(true), - notifyEnabled: boolean("notify_enabled").notNull().default(true), - isActive: boolean("is_active").notNull().default(true), - createdByUserId: text("created_by_user_id"), - updatedByUserId: text("updated_by_user_id"), - createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), - updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() - }, - (table) => ({ - companyScopeActiveIdx: index("budget_policies_company_scope_active_idx").on( - table.companyId, - table.scopeType, - table.scopeId, - table.isActive - ), - companyWindowIdx: index("budget_policies_company_window_idx").on( - table.companyId, - table.windowKind, - table.metric - ), - companyScopeMetricUniqueIdx: uniqueIndex("budget_policies_company_scope_metric_unique_idx").on( - table.companyId, - table.scopeType, - table.scopeId, - table.metric, - table.windowKind - ) - }) - ); - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/expressions.js -var init_expressions2 = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/expressions.js"() { - init_expressions(); - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/operations.js -var init_operations = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/operations.js"() { - } -}); - -// node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/index.js -var init_drizzle_orm = __esm({ - "node_modules/.pnpm/drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_pg@8.20.0_postgres@3.4.9_react@19.2.5/node_modules/drizzle-orm/index.js"() { - init_alias(); - init_column_builder(); - init_column(); - init_entity(); - init_errors2(); - init_expressions2(); - init_logger(); - init_operations(); - init_query_promise(); - init_relations(); - init_sql2(); - init_subquery(); - init_table(); - init_utils(); - init_view_common(); - } -}); - -// packages/db/src/schema/approvals.ts -var approvals; -var init_approvals = __esm({ - "packages/db/src/schema/approvals.ts"() { - "use strict"; - init_pg_core(); - init_companies(); - init_agents(); - approvals = pgTable( - "approvals", - { - id: uuid("id").primaryKey().defaultRandom(), - companyId: uuid("company_id").notNull().references(() => companies.id), - type: text("type").notNull(), - requestedByAgentId: uuid("requested_by_agent_id").references(() => agents.id), - requestedByUserId: text("requested_by_user_id"), - status: text("status").notNull().default("pending"), - payload: jsonb("payload").$type().notNull(), - decisionNote: text("decision_note"), - decidedByUserId: text("decided_by_user_id"), - decidedAt: timestamp("decided_at", { withTimezone: true }), - createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), - updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() - }, - (table) => ({ - companyStatusTypeIdx: index("approvals_company_status_type_idx").on( - table.companyId, - table.status, - table.type - ) - }) - ); - } -}); - -// packages/db/src/schema/budget_incidents.ts -var budgetIncidents; -var init_budget_incidents = __esm({ - "packages/db/src/schema/budget_incidents.ts"() { - "use strict"; - init_drizzle_orm(); - init_pg_core(); - init_approvals(); - init_budget_policies(); - init_companies(); - budgetIncidents = pgTable( - "budget_incidents", - { - id: uuid("id").primaryKey().defaultRandom(), - companyId: uuid("company_id").notNull().references(() => companies.id), - policyId: uuid("policy_id").notNull().references(() => budgetPolicies.id), - scopeType: text("scope_type").notNull(), - scopeId: uuid("scope_id").notNull(), - metric: text("metric").notNull(), - windowKind: text("window_kind").notNull(), - windowStart: timestamp("window_start", { withTimezone: true }).notNull(), - windowEnd: timestamp("window_end", { withTimezone: true }).notNull(), - thresholdType: text("threshold_type").notNull(), - amountLimit: integer("amount_limit").notNull(), - amountObserved: integer("amount_observed").notNull(), - status: text("status").notNull().default("open"), - approvalId: uuid("approval_id").references(() => approvals.id), - resolvedAt: timestamp("resolved_at", { withTimezone: true }), - createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), - updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() - }, - (table) => ({ - companyStatusIdx: index("budget_incidents_company_status_idx").on(table.companyId, table.status), - companyScopeIdx: index("budget_incidents_company_scope_idx").on( - table.companyId, - table.scopeType, - table.scopeId, - table.status - ), - policyWindowIdx: uniqueIndex("budget_incidents_policy_window_threshold_idx").on( - table.policyId, - table.windowStart, - table.thresholdType - ).where(sql`${table.status} <> 'dismissed'`) - }) - ); - } -}); - -// packages/db/src/schema/agent_config_revisions.ts -var agentConfigRevisions; -var init_agent_config_revisions = __esm({ - "packages/db/src/schema/agent_config_revisions.ts"() { - "use strict"; - init_pg_core(); - init_companies(); - init_agents(); - agentConfigRevisions = pgTable( - "agent_config_revisions", - { - id: uuid("id").primaryKey().defaultRandom(), - companyId: uuid("company_id").notNull().references(() => companies.id), - agentId: uuid("agent_id").notNull().references(() => agents.id, { onDelete: "cascade" }), - createdByAgentId: uuid("created_by_agent_id").references(() => agents.id, { onDelete: "set null" }), - createdByUserId: text("created_by_user_id"), - source: text("source").notNull().default("patch"), - rolledBackFromRevisionId: uuid("rolled_back_from_revision_id"), - changedKeys: jsonb("changed_keys").$type().notNull().default([]), - beforeConfig: jsonb("before_config").$type().notNull(), - afterConfig: jsonb("after_config").$type().notNull(), - createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow() - }, - (table) => ({ - companyAgentCreatedIdx: index("agent_config_revisions_company_agent_created_idx").on( - table.companyId, - table.agentId, - table.createdAt - ), - agentCreatedIdx: index("agent_config_revisions_agent_created_idx").on(table.agentId, table.createdAt) - }) - ); - } -}); - -// packages/db/src/schema/agent_api_keys.ts -var agentApiKeys; -var init_agent_api_keys = __esm({ - "packages/db/src/schema/agent_api_keys.ts"() { - "use strict"; - init_pg_core(); - init_agents(); - init_companies(); - agentApiKeys = pgTable( - "agent_api_keys", - { - id: uuid("id").primaryKey().defaultRandom(), - agentId: uuid("agent_id").notNull().references(() => agents.id), - companyId: uuid("company_id").notNull().references(() => companies.id), - name: text("name").notNull(), - keyHash: text("key_hash").notNull(), - lastUsedAt: timestamp("last_used_at", { withTimezone: true }), - revokedAt: timestamp("revoked_at", { withTimezone: true }), - createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow() - }, - (table) => ({ - keyHashIdx: index("agent_api_keys_key_hash_idx").on(table.keyHash), - companyAgentIdx: index("agent_api_keys_company_agent_idx").on(table.companyId, table.agentId) - }) - ); - } -}); - -// packages/db/src/schema/agent_runtime_state.ts -var agentRuntimeState; -var init_agent_runtime_state = __esm({ - "packages/db/src/schema/agent_runtime_state.ts"() { - "use strict"; - init_pg_core(); - init_agents(); - init_companies(); - agentRuntimeState = pgTable( - "agent_runtime_state", - { - agentId: uuid("agent_id").primaryKey().references(() => agents.id), - companyId: uuid("company_id").notNull().references(() => companies.id), - adapterType: text("adapter_type").notNull(), - sessionId: text("session_id"), - stateJson: jsonb("state_json").$type().notNull().default({}), - lastRunId: uuid("last_run_id"), - lastRunStatus: text("last_run_status"), - totalInputTokens: bigint("total_input_tokens", { mode: "number" }).notNull().default(0), - totalOutputTokens: bigint("total_output_tokens", { mode: "number" }).notNull().default(0), - totalCachedInputTokens: bigint("total_cached_input_tokens", { mode: "number" }).notNull().default(0), - totalCostCents: bigint("total_cost_cents", { mode: "number" }).notNull().default(0), - lastError: text("last_error"), - createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), - updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() - }, - (table) => ({ - companyAgentIdx: index("agent_runtime_state_company_agent_idx").on(table.companyId, table.agentId), - companyUpdatedIdx: index("agent_runtime_state_company_updated_idx").on(table.companyId, table.updatedAt) - }) - ); - } -}); - -// packages/db/src/schema/agent_wakeup_requests.ts -var agentWakeupRequests; -var init_agent_wakeup_requests = __esm({ - "packages/db/src/schema/agent_wakeup_requests.ts"() { - "use strict"; - init_pg_core(); - init_companies(); - init_agents(); - agentWakeupRequests = pgTable( - "agent_wakeup_requests", - { - id: uuid("id").primaryKey().defaultRandom(), - companyId: uuid("company_id").notNull().references(() => companies.id), - agentId: uuid("agent_id").notNull().references(() => agents.id), - source: text("source").notNull(), - triggerDetail: text("trigger_detail"), - reason: text("reason"), - payload: jsonb("payload").$type(), - status: text("status").notNull().default("queued"), - coalescedCount: integer("coalesced_count").notNull().default(0), - requestedByActorType: text("requested_by_actor_type"), - requestedByActorId: text("requested_by_actor_id"), - idempotencyKey: text("idempotency_key"), - runId: uuid("run_id"), - requestedAt: timestamp("requested_at", { withTimezone: true }).notNull().defaultNow(), - claimedAt: timestamp("claimed_at", { withTimezone: true }), - finishedAt: timestamp("finished_at", { withTimezone: true }), - error: text("error"), - createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), - updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() - }, - (table) => ({ - companyAgentStatusIdx: index("agent_wakeup_requests_company_agent_status_idx").on( - table.companyId, - table.agentId, - table.status - ), - companyRequestedIdx: index("agent_wakeup_requests_company_requested_idx").on( - table.companyId, - table.requestedAt - ), - agentRequestedIdx: index("agent_wakeup_requests_agent_requested_idx").on(table.agentId, table.requestedAt) - }) - ); - } -}); - -// packages/db/src/schema/heartbeat_runs.ts -var heartbeatRuns; -var init_heartbeat_runs = __esm({ - "packages/db/src/schema/heartbeat_runs.ts"() { - "use strict"; - init_pg_core(); - init_companies(); - init_agents(); - init_agent_wakeup_requests(); - heartbeatRuns = pgTable( - "heartbeat_runs", - { - id: uuid("id").primaryKey().defaultRandom(), - companyId: uuid("company_id").notNull().references(() => companies.id), - agentId: uuid("agent_id").notNull().references(() => agents.id), - invocationSource: text("invocation_source").notNull().default("on_demand"), - triggerDetail: text("trigger_detail"), - status: text("status").notNull().default("queued"), - startedAt: timestamp("started_at", { withTimezone: true }), - finishedAt: timestamp("finished_at", { withTimezone: true }), - error: text("error"), - wakeupRequestId: uuid("wakeup_request_id").references(() => agentWakeupRequests.id), - exitCode: integer("exit_code"), - signal: text("signal"), - usageJson: jsonb("usage_json").$type(), - resultJson: jsonb("result_json").$type(), - sessionIdBefore: text("session_id_before"), - sessionIdAfter: text("session_id_after"), - logStore: text("log_store"), - logRef: text("log_ref"), - logBytes: bigint("log_bytes", { mode: "number" }), - logSha256: text("log_sha256"), - logCompressed: boolean("log_compressed").notNull().default(false), - stdoutExcerpt: text("stdout_excerpt"), - stderrExcerpt: text("stderr_excerpt"), - errorCode: text("error_code"), - externalRunId: text("external_run_id"), - processPid: integer("process_pid"), - processGroupId: integer("process_group_id"), - processStartedAt: timestamp("process_started_at", { withTimezone: true }), - retryOfRunId: uuid("retry_of_run_id").references(() => heartbeatRuns.id, { - onDelete: "set null" - }), - processLossRetryCount: integer("process_loss_retry_count").notNull().default(0), - issueCommentStatus: text("issue_comment_status").notNull().default("not_applicable"), - issueCommentSatisfiedByCommentId: uuid("issue_comment_satisfied_by_comment_id"), - issueCommentRetryQueuedAt: timestamp("issue_comment_retry_queued_at", { withTimezone: true }), - contextSnapshot: jsonb("context_snapshot").$type(), - createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), - updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() - }, - (table) => ({ - companyAgentStartedIdx: index("heartbeat_runs_company_agent_started_idx").on( - table.companyId, - table.agentId, - table.startedAt - ) - }) - ); - } -}); - -// packages/db/src/schema/agent_task_sessions.ts -var agentTaskSessions; -var init_agent_task_sessions = __esm({ - "packages/db/src/schema/agent_task_sessions.ts"() { - "use strict"; - init_pg_core(); - init_companies(); - init_agents(); - init_heartbeat_runs(); - agentTaskSessions = pgTable( - "agent_task_sessions", - { - id: uuid("id").primaryKey().defaultRandom(), - companyId: uuid("company_id").notNull().references(() => companies.id), - agentId: uuid("agent_id").notNull().references(() => agents.id), - adapterType: text("adapter_type").notNull(), - taskKey: text("task_key").notNull(), - sessionParamsJson: jsonb("session_params_json").$type(), - sessionDisplayId: text("session_display_id"), - lastRunId: uuid("last_run_id").references(() => heartbeatRuns.id), - lastError: text("last_error"), - createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), - updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() - }, - (table) => ({ - companyAgentTaskUniqueIdx: uniqueIndex("agent_task_sessions_company_agent_adapter_task_uniq").on( - table.companyId, - table.agentId, - table.adapterType, - table.taskKey - ), - companyAgentUpdatedIdx: index("agent_task_sessions_company_agent_updated_idx").on( - table.companyId, - table.agentId, - table.updatedAt - ), - companyTaskUpdatedIdx: index("agent_task_sessions_company_task_updated_idx").on( - table.companyId, - table.taskKey, - table.updatedAt - ) - }) - ); - } -}); - -// packages/db/src/schema/goals.ts -var goals; -var init_goals = __esm({ - "packages/db/src/schema/goals.ts"() { - "use strict"; - init_pg_core(); - init_agents(); - init_companies(); - goals = pgTable( - "goals", - { - id: uuid("id").primaryKey().defaultRandom(), - companyId: uuid("company_id").notNull().references(() => companies.id), - title: text("title").notNull(), - description: text("description"), - level: text("level").notNull().default("task"), - status: text("status").notNull().default("planned"), - parentId: uuid("parent_id").references(() => goals.id), - ownerAgentId: uuid("owner_agent_id").references(() => agents.id), - createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), - updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() - }, - (table) => ({ - companyIdx: index("goals_company_idx").on(table.companyId) - }) - ); - } -}); - -// packages/db/src/schema/projects.ts -var projects; -var init_projects = __esm({ - "packages/db/src/schema/projects.ts"() { - "use strict"; - init_pg_core(); - init_companies(); - init_goals(); - init_agents(); - projects = pgTable( - "projects", - { - id: uuid("id").primaryKey().defaultRandom(), - companyId: uuid("company_id").notNull().references(() => companies.id), - goalId: uuid("goal_id").references(() => goals.id), - name: text("name").notNull(), - description: text("description"), - status: text("status").notNull().default("backlog"), - leadAgentId: uuid("lead_agent_id").references(() => agents.id), - targetDate: date("target_date"), - color: text("color"), - env: jsonb("env").$type(), - pauseReason: text("pause_reason"), - pausedAt: timestamp("paused_at", { withTimezone: true }), - executionWorkspacePolicy: jsonb("execution_workspace_policy").$type(), - archivedAt: timestamp("archived_at", { withTimezone: true }), - createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), - updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() - }, - (table) => ({ - companyIdx: index("projects_company_idx").on(table.companyId) - }) - ); - } -}); - -// packages/db/src/schema/project_workspaces.ts -var projectWorkspaces; -var init_project_workspaces = __esm({ - "packages/db/src/schema/project_workspaces.ts"() { - "use strict"; - init_pg_core(); - init_companies(); - init_projects(); - projectWorkspaces = pgTable( - "project_workspaces", - { - id: uuid("id").primaryKey().defaultRandom(), - companyId: uuid("company_id").notNull().references(() => companies.id), - projectId: uuid("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }), - name: text("name").notNull(), - sourceType: text("source_type").notNull().default("local_path"), - cwd: text("cwd"), - repoUrl: text("repo_url"), - repoRef: text("repo_ref"), - defaultRef: text("default_ref"), - visibility: text("visibility").notNull().default("default"), - setupCommand: text("setup_command"), - cleanupCommand: text("cleanup_command"), - remoteProvider: text("remote_provider"), - remoteWorkspaceRef: text("remote_workspace_ref"), - sharedWorkspaceKey: text("shared_workspace_key"), - metadata: jsonb("metadata").$type(), - isPrimary: boolean("is_primary").notNull().default(false), - createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), - updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() - }, - (table) => ({ - companyProjectIdx: index("project_workspaces_company_project_idx").on(table.companyId, table.projectId), - projectPrimaryIdx: index("project_workspaces_project_primary_idx").on(table.projectId, table.isPrimary), - projectSourceTypeIdx: index("project_workspaces_project_source_type_idx").on(table.projectId, table.sourceType), - companySharedKeyIdx: index("project_workspaces_company_shared_key_idx").on(table.companyId, table.sharedWorkspaceKey), - projectRemoteRefIdx: uniqueIndex("project_workspaces_project_remote_ref_idx").on(table.projectId, table.remoteProvider, table.remoteWorkspaceRef) - }) - ); - } -}); - -// packages/db/src/schema/issues.ts -var issues; -var init_issues = __esm({ - "packages/db/src/schema/issues.ts"() { - "use strict"; - init_drizzle_orm(); - init_pg_core(); - init_agents(); - init_projects(); - init_goals(); - init_companies(); - init_heartbeat_runs(); - init_project_workspaces(); - init_execution_workspaces(); - issues = pgTable( - "issues", - { - id: uuid("id").primaryKey().defaultRandom(), - companyId: uuid("company_id").notNull().references(() => companies.id), - projectId: uuid("project_id").references(() => projects.id), - projectWorkspaceId: uuid("project_workspace_id").references(() => projectWorkspaces.id, { onDelete: "set null" }), - goalId: uuid("goal_id").references(() => goals.id), - parentId: uuid("parent_id").references(() => issues.id), - title: text("title").notNull(), - description: text("description"), - status: text("status").notNull().default("backlog"), - priority: text("priority").notNull().default("medium"), - assigneeAgentId: uuid("assignee_agent_id").references(() => agents.id), - assigneeUserId: text("assignee_user_id"), - checkoutRunId: uuid("checkout_run_id").references(() => heartbeatRuns.id, { onDelete: "set null" }), - executionRunId: uuid("execution_run_id").references(() => heartbeatRuns.id, { onDelete: "set null" }), - executionAgentNameKey: text("execution_agent_name_key"), - executionLockedAt: timestamp("execution_locked_at", { withTimezone: true }), - createdByAgentId: uuid("created_by_agent_id").references(() => agents.id), - createdByUserId: text("created_by_user_id"), - issueNumber: integer("issue_number"), - identifier: text("identifier"), - originKind: text("origin_kind").notNull().default("manual"), - originId: text("origin_id"), - originRunId: text("origin_run_id"), - requestDepth: integer("request_depth").notNull().default(0), - billingCode: text("billing_code"), - assigneeAdapterOverrides: jsonb("assignee_adapter_overrides").$type(), - executionPolicy: jsonb("execution_policy").$type(), - executionState: jsonb("execution_state").$type(), - executionWorkspaceId: uuid("execution_workspace_id").references(() => executionWorkspaces.id, { onDelete: "set null" }), - executionWorkspacePreference: text("execution_workspace_preference"), - executionWorkspaceSettings: jsonb("execution_workspace_settings").$type(), - startedAt: timestamp("started_at", { withTimezone: true }), - completedAt: timestamp("completed_at", { withTimezone: true }), - cancelledAt: timestamp("cancelled_at", { withTimezone: true }), - hiddenAt: timestamp("hidden_at", { withTimezone: true }), - createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), - updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() - }, - (table) => ({ - companyStatusIdx: index("issues_company_status_idx").on(table.companyId, table.status), - assigneeStatusIdx: index("issues_company_assignee_status_idx").on( - table.companyId, - table.assigneeAgentId, - table.status - ), - assigneeUserStatusIdx: index("issues_company_assignee_user_status_idx").on( - table.companyId, - table.assigneeUserId, - table.status - ), - parentIdx: index("issues_company_parent_idx").on(table.companyId, table.parentId), - projectIdx: index("issues_company_project_idx").on(table.companyId, table.projectId), - originIdx: index("issues_company_origin_idx").on(table.companyId, table.originKind, table.originId), - projectWorkspaceIdx: index("issues_company_project_workspace_idx").on(table.companyId, table.projectWorkspaceId), - executionWorkspaceIdx: index("issues_company_execution_workspace_idx").on(table.companyId, table.executionWorkspaceId), - identifierIdx: uniqueIndex("issues_identifier_idx").on(table.identifier), - titleSearchIdx: index("issues_title_search_idx").using("gin", table.title.op("gin_trgm_ops")), - identifierSearchIdx: index("issues_identifier_search_idx").using("gin", table.identifier.op("gin_trgm_ops")), - descriptionSearchIdx: index("issues_description_search_idx").using("gin", table.description.op("gin_trgm_ops")), - openRoutineExecutionIdx: uniqueIndex("issues_open_routine_execution_uq").on(table.companyId, table.originKind, table.originId).where( - sql`${table.originKind} = 'routine_execution' - and ${table.originId} is not null - and ${table.hiddenAt} is null - and ${table.executionRunId} is not null - and ${table.status} in ('backlog', 'todo', 'in_progress', 'in_review', 'blocked')` - ) - }) - ); - } -}); - -// packages/db/src/schema/execution_workspaces.ts -var executionWorkspaces; -var init_execution_workspaces = __esm({ - "packages/db/src/schema/execution_workspaces.ts"() { - "use strict"; - init_pg_core(); - init_companies(); - init_issues(); - init_project_workspaces(); - init_projects(); - executionWorkspaces = pgTable( - "execution_workspaces", - { - id: uuid("id").primaryKey().defaultRandom(), - companyId: uuid("company_id").notNull().references(() => companies.id), - projectId: uuid("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }), - projectWorkspaceId: uuid("project_workspace_id").references(() => projectWorkspaces.id, { onDelete: "set null" }), - sourceIssueId: uuid("source_issue_id").references(() => issues.id, { onDelete: "set null" }), - mode: text("mode").notNull(), - strategyType: text("strategy_type").notNull(), - name: text("name").notNull(), - status: text("status").notNull().default("active"), - cwd: text("cwd"), - repoUrl: text("repo_url"), - baseRef: text("base_ref"), - branchName: text("branch_name"), - providerType: text("provider_type").notNull().default("local_fs"), - providerRef: text("provider_ref"), - derivedFromExecutionWorkspaceId: uuid("derived_from_execution_workspace_id").references(() => executionWorkspaces.id, { onDelete: "set null" }), - lastUsedAt: timestamp("last_used_at", { withTimezone: true }).notNull().defaultNow(), - openedAt: timestamp("opened_at", { withTimezone: true }).notNull().defaultNow(), - closedAt: timestamp("closed_at", { withTimezone: true }), - cleanupEligibleAt: timestamp("cleanup_eligible_at", { withTimezone: true }), - cleanupReason: text("cleanup_reason"), - metadata: jsonb("metadata").$type(), - createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), - updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() - }, - (table) => ({ - companyProjectStatusIdx: index("execution_workspaces_company_project_status_idx").on( - table.companyId, - table.projectId, - table.status - ), - companyProjectWorkspaceStatusIdx: index("execution_workspaces_company_project_workspace_status_idx").on( - table.companyId, - table.projectWorkspaceId, - table.status - ), - companySourceIssueIdx: index("execution_workspaces_company_source_issue_idx").on( - table.companyId, - table.sourceIssueId - ), - companyLastUsedIdx: index("execution_workspaces_company_last_used_idx").on( - table.companyId, - table.lastUsedAt - ), - companyBranchIdx: index("execution_workspaces_company_branch_idx").on( - table.companyId, - table.branchName - ) - }) - ); - } -}); - -// packages/db/src/schema/workspace_operations.ts -var workspaceOperations; -var init_workspace_operations = __esm({ - "packages/db/src/schema/workspace_operations.ts"() { - "use strict"; - init_pg_core(); - init_companies(); - init_execution_workspaces(); - init_heartbeat_runs(); - workspaceOperations = pgTable( - "workspace_operations", - { - id: uuid("id").primaryKey().defaultRandom(), - companyId: uuid("company_id").notNull().references(() => companies.id), - executionWorkspaceId: uuid("execution_workspace_id").references(() => executionWorkspaces.id, { - onDelete: "set null" - }), - heartbeatRunId: uuid("heartbeat_run_id").references(() => heartbeatRuns.id, { - onDelete: "set null" - }), - phase: text("phase").notNull(), - command: text("command"), - cwd: text("cwd"), - status: text("status").notNull().default("running"), - exitCode: integer("exit_code"), - logStore: text("log_store"), - logRef: text("log_ref"), - logBytes: bigint("log_bytes", { mode: "number" }), - logSha256: text("log_sha256"), - logCompressed: boolean("log_compressed").notNull().default(false), - stdoutExcerpt: text("stdout_excerpt"), - stderrExcerpt: text("stderr_excerpt"), - metadata: jsonb("metadata").$type(), - startedAt: timestamp("started_at", { withTimezone: true }).notNull().defaultNow(), - finishedAt: timestamp("finished_at", { withTimezone: true }), - createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), - updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() - }, - (table) => ({ - companyRunStartedIdx: index("workspace_operations_company_run_started_idx").on( - table.companyId, - table.heartbeatRunId, - table.startedAt - ), - companyWorkspaceStartedIdx: index("workspace_operations_company_workspace_started_idx").on( - table.companyId, - table.executionWorkspaceId, - table.startedAt - ) - }) - ); - } -}); - -// packages/db/src/schema/workspace_runtime_services.ts -var workspaceRuntimeServices; -var init_workspace_runtime_services = __esm({ - "packages/db/src/schema/workspace_runtime_services.ts"() { - "use strict"; - init_pg_core(); - init_companies(); - init_projects(); - init_project_workspaces(); - init_execution_workspaces(); - init_issues(); - init_agents(); - init_heartbeat_runs(); - workspaceRuntimeServices = pgTable( - "workspace_runtime_services", - { - id: uuid("id").primaryKey(), - companyId: uuid("company_id").notNull().references(() => companies.id), - projectId: uuid("project_id").references(() => projects.id, { onDelete: "set null" }), - projectWorkspaceId: uuid("project_workspace_id").references(() => projectWorkspaces.id, { onDelete: "set null" }), - executionWorkspaceId: uuid("execution_workspace_id").references(() => executionWorkspaces.id, { onDelete: "set null" }), - issueId: uuid("issue_id").references(() => issues.id, { onDelete: "set null" }), - scopeType: text("scope_type").notNull(), - scopeId: text("scope_id"), - serviceName: text("service_name").notNull(), - status: text("status").notNull(), - lifecycle: text("lifecycle").notNull(), - reuseKey: text("reuse_key"), - command: text("command"), - cwd: text("cwd"), - port: integer("port"), - url: text("url"), - provider: text("provider").notNull(), - providerRef: text("provider_ref"), - ownerAgentId: uuid("owner_agent_id").references(() => agents.id, { onDelete: "set null" }), - startedByRunId: uuid("started_by_run_id").references(() => heartbeatRuns.id, { onDelete: "set null" }), - lastUsedAt: timestamp("last_used_at", { withTimezone: true }).notNull().defaultNow(), - startedAt: timestamp("started_at", { withTimezone: true }).notNull().defaultNow(), - stoppedAt: timestamp("stopped_at", { withTimezone: true }), - stopPolicy: jsonb("stop_policy").$type(), - healthStatus: text("health_status").notNull().default("unknown"), - createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), - updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() - }, - (table) => ({ - companyWorkspaceStatusIdx: index("workspace_runtime_services_company_workspace_status_idx").on( - table.companyId, - table.projectWorkspaceId, - table.status - ), - companyExecutionWorkspaceStatusIdx: index("workspace_runtime_services_company_execution_workspace_status_idx").on( - table.companyId, - table.executionWorkspaceId, - table.status - ), - companyProjectStatusIdx: index("workspace_runtime_services_company_project_status_idx").on( - table.companyId, - table.projectId, - table.status - ), - runIdx: index("workspace_runtime_services_run_idx").on(table.startedByRunId), - companyUpdatedIdx: index("workspace_runtime_services_company_updated_idx").on( - table.companyId, - table.updatedAt - ) - }) - ); - } -}); - -// packages/db/src/schema/project_goals.ts -var projectGoals; -var init_project_goals = __esm({ - "packages/db/src/schema/project_goals.ts"() { - "use strict"; - init_pg_core(); - init_companies(); - init_projects(); - init_goals(); - projectGoals = pgTable( - "project_goals", - { - projectId: uuid("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }), - goalId: uuid("goal_id").notNull().references(() => goals.id, { onDelete: "cascade" }), - companyId: uuid("company_id").notNull().references(() => companies.id), - createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), - updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() - }, - (table) => ({ - pk: primaryKey({ columns: [table.projectId, table.goalId] }), - projectIdx: index("project_goals_project_idx").on(table.projectId), - goalIdx: index("project_goals_goal_idx").on(table.goalId), - companyIdx: index("project_goals_company_idx").on(table.companyId) - }) - ); - } -}); - -// packages/db/src/schema/issue_relations.ts -var issueRelations; -var init_issue_relations = __esm({ - "packages/db/src/schema/issue_relations.ts"() { - "use strict"; - init_pg_core(); - init_agents(); - init_companies(); - init_issues(); - issueRelations = pgTable( - "issue_relations", - { - id: uuid("id").primaryKey().defaultRandom(), - companyId: uuid("company_id").notNull().references(() => companies.id), - issueId: uuid("issue_id").notNull().references(() => issues.id, { onDelete: "cascade" }), - relatedIssueId: uuid("related_issue_id").notNull().references(() => issues.id, { onDelete: "cascade" }), - type: text("type").$type().notNull(), - createdByAgentId: uuid("created_by_agent_id").references(() => agents.id, { onDelete: "set null" }), - createdByUserId: text("created_by_user_id"), - createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), - updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() - }, - (table) => ({ - companyIssueIdx: index("issue_relations_company_issue_idx").on(table.companyId, table.issueId), - companyRelatedIssueIdx: index("issue_relations_company_related_issue_idx").on(table.companyId, table.relatedIssueId), - companyTypeIdx: index("issue_relations_company_type_idx").on(table.companyId, table.type), - companyEdgeUq: uniqueIndex("issue_relations_company_edge_uq").on( - table.companyId, - table.issueId, - table.relatedIssueId, - table.type - ) - }) - ); - } -}); - -// packages/db/src/schema/company_secrets.ts -var companySecrets; -var init_company_secrets = __esm({ - "packages/db/src/schema/company_secrets.ts"() { - "use strict"; - init_pg_core(); - init_companies(); - init_agents(); - companySecrets = pgTable( - "company_secrets", - { - id: uuid("id").primaryKey().defaultRandom(), - companyId: uuid("company_id").notNull().references(() => companies.id), - name: text("name").notNull(), - provider: text("provider").notNull().default("local_encrypted"), - externalRef: text("external_ref"), - latestVersion: integer("latest_version").notNull().default(1), - description: text("description"), - createdByAgentId: uuid("created_by_agent_id").references(() => agents.id, { onDelete: "set null" }), - createdByUserId: text("created_by_user_id"), - createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), - updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() - }, - (table) => ({ - companyIdx: index("company_secrets_company_idx").on(table.companyId), - companyProviderIdx: index("company_secrets_company_provider_idx").on(table.companyId, table.provider), - companyNameUq: uniqueIndex("company_secrets_company_name_uq").on(table.companyId, table.name) - }) - ); - } -}); - -// packages/db/src/schema/routines.ts -var routines, routineTriggers, routineRuns; -var init_routines = __esm({ - "packages/db/src/schema/routines.ts"() { - "use strict"; - init_pg_core(); - init_agents(); - init_companies(); - init_company_secrets(); - init_issues(); - init_projects(); - init_goals(); - routines = pgTable( - "routines", - { - id: uuid("id").primaryKey().defaultRandom(), - companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }), - projectId: uuid("project_id").references(() => projects.id, { onDelete: "cascade" }), - goalId: uuid("goal_id").references(() => goals.id, { onDelete: "set null" }), - parentIssueId: uuid("parent_issue_id").references(() => issues.id, { onDelete: "set null" }), - title: text("title").notNull(), - description: text("description"), - assigneeAgentId: uuid("assignee_agent_id").references(() => agents.id), - priority: text("priority").notNull().default("medium"), - status: text("status").notNull().default("active"), - concurrencyPolicy: text("concurrency_policy").notNull().default("coalesce_if_active"), - catchUpPolicy: text("catch_up_policy").notNull().default("skip_missed"), - variables: jsonb("variables").$type().notNull().default([]), - createdByAgentId: uuid("created_by_agent_id").references(() => agents.id, { onDelete: "set null" }), - createdByUserId: text("created_by_user_id"), - updatedByAgentId: uuid("updated_by_agent_id").references(() => agents.id, { onDelete: "set null" }), - updatedByUserId: text("updated_by_user_id"), - lastTriggeredAt: timestamp("last_triggered_at", { withTimezone: true }), - lastEnqueuedAt: timestamp("last_enqueued_at", { withTimezone: true }), - createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), - updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() - }, - (table) => ({ - companyStatusIdx: index("routines_company_status_idx").on(table.companyId, table.status), - companyAssigneeIdx: index("routines_company_assignee_idx").on(table.companyId, table.assigneeAgentId), - companyProjectIdx: index("routines_company_project_idx").on(table.companyId, table.projectId) - }) - ); - routineTriggers = pgTable( - "routine_triggers", - { - id: uuid("id").primaryKey().defaultRandom(), - companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }), - routineId: uuid("routine_id").notNull().references(() => routines.id, { onDelete: "cascade" }), - kind: text("kind").notNull(), - label: text("label"), - enabled: boolean("enabled").notNull().default(true), - cronExpression: text("cron_expression"), - timezone: text("timezone"), - nextRunAt: timestamp("next_run_at", { withTimezone: true }), - lastFiredAt: timestamp("last_fired_at", { withTimezone: true }), - publicId: text("public_id"), - secretId: uuid("secret_id").references(() => companySecrets.id, { onDelete: "set null" }), - signingMode: text("signing_mode"), - replayWindowSec: integer("replay_window_sec"), - lastRotatedAt: timestamp("last_rotated_at", { withTimezone: true }), - lastResult: text("last_result"), - createdByAgentId: uuid("created_by_agent_id").references(() => agents.id, { onDelete: "set null" }), - createdByUserId: text("created_by_user_id"), - updatedByAgentId: uuid("updated_by_agent_id").references(() => agents.id, { onDelete: "set null" }), - updatedByUserId: text("updated_by_user_id"), - createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), - updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() - }, - (table) => ({ - companyRoutineIdx: index("routine_triggers_company_routine_idx").on(table.companyId, table.routineId), - companyKindIdx: index("routine_triggers_company_kind_idx").on(table.companyId, table.kind), - nextRunIdx: index("routine_triggers_next_run_idx").on(table.nextRunAt), - publicIdIdx: index("routine_triggers_public_id_idx").on(table.publicId), - publicIdUq: uniqueIndex("routine_triggers_public_id_uq").on(table.publicId) - }) - ); - routineRuns = pgTable( - "routine_runs", - { - id: uuid("id").primaryKey().defaultRandom(), - companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }), - routineId: uuid("routine_id").notNull().references(() => routines.id, { onDelete: "cascade" }), - triggerId: uuid("trigger_id").references(() => routineTriggers.id, { onDelete: "set null" }), - source: text("source").notNull(), - status: text("status").notNull().default("received"), - triggeredAt: timestamp("triggered_at", { withTimezone: true }).notNull().defaultNow(), - idempotencyKey: text("idempotency_key"), - triggerPayload: jsonb("trigger_payload").$type(), - linkedIssueId: uuid("linked_issue_id").references(() => issues.id, { onDelete: "set null" }), - coalescedIntoRunId: uuid("coalesced_into_run_id"), - failureReason: text("failure_reason"), - completedAt: timestamp("completed_at", { withTimezone: true }), - createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), - updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() - }, - (table) => ({ - companyRoutineIdx: index("routine_runs_company_routine_idx").on(table.companyId, table.routineId, table.createdAt), - triggerIdx: index("routine_runs_trigger_idx").on(table.triggerId, table.createdAt), - linkedIssueIdx: index("routine_runs_linked_issue_idx").on(table.linkedIssueId), - idempotencyIdx: index("routine_runs_trigger_idempotency_idx").on(table.triggerId, table.idempotencyKey) - }) - ); - } -}); - -// packages/db/src/schema/issue_work_products.ts -var issueWorkProducts; -var init_issue_work_products = __esm({ - "packages/db/src/schema/issue_work_products.ts"() { - "use strict"; - init_pg_core(); - init_companies(); - init_execution_workspaces(); - init_heartbeat_runs(); - init_issues(); - init_projects(); - init_workspace_runtime_services(); - issueWorkProducts = pgTable( - "issue_work_products", - { - id: uuid("id").primaryKey().defaultRandom(), - companyId: uuid("company_id").notNull().references(() => companies.id), - projectId: uuid("project_id").references(() => projects.id, { onDelete: "set null" }), - issueId: uuid("issue_id").notNull().references(() => issues.id, { onDelete: "cascade" }), - executionWorkspaceId: uuid("execution_workspace_id").references(() => executionWorkspaces.id, { onDelete: "set null" }), - runtimeServiceId: uuid("runtime_service_id").references(() => workspaceRuntimeServices.id, { onDelete: "set null" }), - type: text("type").notNull(), - provider: text("provider").notNull(), - externalId: text("external_id"), - title: text("title").notNull(), - url: text("url"), - status: text("status").notNull(), - reviewState: text("review_state").notNull().default("none"), - isPrimary: boolean("is_primary").notNull().default(false), - healthStatus: text("health_status").notNull().default("unknown"), - summary: text("summary"), - metadata: jsonb("metadata").$type(), - createdByRunId: uuid("created_by_run_id").references(() => heartbeatRuns.id, { onDelete: "set null" }), - createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), - updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() - }, - (table) => ({ - companyIssueTypeIdx: index("issue_work_products_company_issue_type_idx").on( - table.companyId, - table.issueId, - table.type - ), - companyExecutionWorkspaceTypeIdx: index("issue_work_products_company_execution_workspace_type_idx").on( - table.companyId, - table.executionWorkspaceId, - table.type - ), - companyProviderExternalIdIdx: index("issue_work_products_company_provider_external_id_idx").on( - table.companyId, - table.provider, - table.externalId - ), - companyUpdatedIdx: index("issue_work_products_company_updated_idx").on( - table.companyId, - table.updatedAt - ) - }) - ); - } -}); - -// packages/db/src/schema/labels.ts -var labels; -var init_labels = __esm({ - "packages/db/src/schema/labels.ts"() { - "use strict"; - init_pg_core(); - init_companies(); - labels = pgTable( - "labels", - { - id: uuid("id").primaryKey().defaultRandom(), - companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }), - name: text("name").notNull(), - color: text("color").notNull(), - createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), - updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() - }, - (table) => ({ - companyIdx: index("labels_company_idx").on(table.companyId), - companyNameIdx: uniqueIndex("labels_company_name_idx").on(table.companyId, table.name) - }) - ); - } -}); - -// packages/db/src/schema/issue_labels.ts -var issueLabels; -var init_issue_labels = __esm({ - "packages/db/src/schema/issue_labels.ts"() { - "use strict"; - init_pg_core(); - init_companies(); - init_issues(); - init_labels(); - issueLabels = pgTable( - "issue_labels", - { - issueId: uuid("issue_id").notNull().references(() => issues.id, { onDelete: "cascade" }), - labelId: uuid("label_id").notNull().references(() => labels.id, { onDelete: "cascade" }), - companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }), - createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow() - }, - (table) => ({ - pk: primaryKey({ columns: [table.issueId, table.labelId], name: "issue_labels_pk" }), - issueIdx: index("issue_labels_issue_idx").on(table.issueId), - labelIdx: index("issue_labels_label_idx").on(table.labelId), - companyIdx: index("issue_labels_company_idx").on(table.companyId) - }) - ); - } -}); - -// packages/db/src/schema/issue_approvals.ts -var issueApprovals; -var init_issue_approvals = __esm({ - "packages/db/src/schema/issue_approvals.ts"() { - "use strict"; - init_pg_core(); - init_companies(); - init_issues(); - init_approvals(); - init_agents(); - issueApprovals = pgTable( - "issue_approvals", - { - companyId: uuid("company_id").notNull().references(() => companies.id), - issueId: uuid("issue_id").notNull().references(() => issues.id, { onDelete: "cascade" }), - approvalId: uuid("approval_id").notNull().references(() => approvals.id, { onDelete: "cascade" }), - linkedByAgentId: uuid("linked_by_agent_id").references(() => agents.id, { onDelete: "set null" }), - linkedByUserId: text("linked_by_user_id"), - createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow() - }, - (table) => ({ - pk: primaryKey({ columns: [table.issueId, table.approvalId], name: "issue_approvals_pk" }), - issueIdx: index("issue_approvals_issue_idx").on(table.issueId), - approvalIdx: index("issue_approvals_approval_idx").on(table.approvalId), - companyIdx: index("issue_approvals_company_idx").on(table.companyId) - }) - ); - } -}); - -// packages/db/src/schema/issue_comments.ts -var issueComments; -var init_issue_comments = __esm({ - "packages/db/src/schema/issue_comments.ts"() { - "use strict"; - init_pg_core(); - init_companies(); - init_issues(); - init_agents(); - init_heartbeat_runs(); - issueComments = pgTable( - "issue_comments", - { - id: uuid("id").primaryKey().defaultRandom(), - companyId: uuid("company_id").notNull().references(() => companies.id), - issueId: uuid("issue_id").notNull().references(() => issues.id), - authorAgentId: uuid("author_agent_id").references(() => agents.id), - authorUserId: text("author_user_id"), - createdByRunId: uuid("created_by_run_id").references(() => heartbeatRuns.id, { onDelete: "set null" }), - body: text("body").notNull(), - createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), - updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() - }, - (table) => ({ - issueIdx: index("issue_comments_issue_idx").on(table.issueId), - companyIdx: index("issue_comments_company_idx").on(table.companyId), - companyIssueCreatedAtIdx: index("issue_comments_company_issue_created_at_idx").on( - table.companyId, - table.issueId, - table.createdAt - ), - companyAuthorIssueCreatedAtIdx: index("issue_comments_company_author_issue_created_at_idx").on( - table.companyId, - table.authorUserId, - table.issueId, - table.createdAt - ), - bodySearchIdx: index("issue_comments_body_search_idx").using("gin", table.body.op("gin_trgm_ops")) - }) - ); - } -}); - -// packages/db/src/schema/issue_execution_decisions.ts -var issueExecutionDecisions; -var init_issue_execution_decisions = __esm({ - "packages/db/src/schema/issue_execution_decisions.ts"() { - "use strict"; - init_pg_core(); - init_companies(); - init_issues(); - init_agents(); - init_heartbeat_runs(); - issueExecutionDecisions = pgTable( - "issue_execution_decisions", - { - id: uuid("id").primaryKey().defaultRandom(), - companyId: uuid("company_id").notNull().references(() => companies.id), - issueId: uuid("issue_id").notNull().references(() => issues.id, { onDelete: "cascade" }), - stageId: uuid("stage_id").notNull(), - stageType: text("stage_type").notNull(), - actorAgentId: uuid("actor_agent_id").references(() => agents.id), - actorUserId: text("actor_user_id"), - outcome: text("outcome").notNull(), - body: text("body").notNull(), - createdByRunId: uuid("created_by_run_id").references(() => heartbeatRuns.id, { onDelete: "set null" }), - createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), - updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() - }, - (table) => ({ - companyIssueIdx: index("issue_execution_decisions_company_issue_idx").on(table.companyId, table.issueId), - stageIdx: index("issue_execution_decisions_stage_idx").on(table.issueId, table.stageId, table.createdAt) - }) - ); - } -}); - -// packages/db/src/schema/issue_inbox_archives.ts -var issueInboxArchives; -var init_issue_inbox_archives = __esm({ - "packages/db/src/schema/issue_inbox_archives.ts"() { - "use strict"; - init_pg_core(); - init_companies(); - init_issues(); - issueInboxArchives = pgTable( - "issue_inbox_archives", - { - id: uuid("id").primaryKey().defaultRandom(), - companyId: uuid("company_id").notNull().references(() => companies.id), - issueId: uuid("issue_id").notNull().references(() => issues.id), - userId: text("user_id").notNull(), - archivedAt: timestamp("archived_at", { withTimezone: true }).notNull().defaultNow(), - createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), - updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() - }, - (table) => ({ - companyIssueIdx: index("issue_inbox_archives_company_issue_idx").on(table.companyId, table.issueId), - companyUserIdx: index("issue_inbox_archives_company_user_idx").on(table.companyId, table.userId), - companyIssueUserUnique: uniqueIndex("issue_inbox_archives_company_issue_user_idx").on( - table.companyId, - table.issueId, - table.userId - ) - }) - ); - } -}); - -// packages/db/src/schema/inbox_dismissals.ts -var inboxDismissals; -var init_inbox_dismissals = __esm({ - "packages/db/src/schema/inbox_dismissals.ts"() { - "use strict"; - init_pg_core(); - init_companies(); - inboxDismissals = pgTable( - "inbox_dismissals", - { - id: uuid("id").primaryKey().defaultRandom(), - companyId: uuid("company_id").notNull().references(() => companies.id), - userId: text("user_id").notNull(), - itemKey: text("item_key").notNull(), - dismissedAt: timestamp("dismissed_at", { withTimezone: true }).notNull().defaultNow(), - createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), - updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() - }, - (table) => ({ - companyUserIdx: index("inbox_dismissals_company_user_idx").on(table.companyId, table.userId), - companyItemIdx: index("inbox_dismissals_company_item_idx").on(table.companyId, table.itemKey), - companyUserItemUnique: uniqueIndex("inbox_dismissals_company_user_item_idx").on( - table.companyId, - table.userId, - table.itemKey - ) - }) - ); - } -}); - -// packages/db/src/schema/feedback_votes.ts -var feedbackVotes; -var init_feedback_votes = __esm({ - "packages/db/src/schema/feedback_votes.ts"() { - "use strict"; - init_pg_core(); - init_companies(); - init_issues(); - feedbackVotes = pgTable( - "feedback_votes", - { - id: uuid("id").primaryKey().defaultRandom(), - companyId: uuid("company_id").notNull().references(() => companies.id), - issueId: uuid("issue_id").notNull().references(() => issues.id), - targetType: text("target_type").notNull(), - targetId: text("target_id").notNull(), - authorUserId: text("author_user_id").notNull(), - vote: text("vote").notNull(), - reason: text("reason"), - sharedWithLabs: boolean("shared_with_labs").notNull().default(false), - sharedAt: timestamp("shared_at", { withTimezone: true }), - consentVersion: text("consent_version"), - redactionSummary: jsonb("redaction_summary"), - createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), - updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() - }, - (table) => ({ - companyIssueIdx: index("feedback_votes_company_issue_idx").on(table.companyId, table.issueId), - issueTargetIdx: index("feedback_votes_issue_target_idx").on(table.issueId, table.targetType, table.targetId), - authorIdx: index("feedback_votes_author_idx").on(table.authorUserId, table.createdAt), - companyTargetAuthorUniqueIdx: uniqueIndex("feedback_votes_company_target_author_idx").on( - table.companyId, - table.targetType, - table.targetId, - table.authorUserId - ) - }) - ); - } -}); - -// packages/db/src/schema/feedback_exports.ts -var feedbackExports; -var init_feedback_exports = __esm({ - "packages/db/src/schema/feedback_exports.ts"() { - "use strict"; - init_pg_core(); - init_companies(); - init_feedback_votes(); - init_issues(); - init_projects(); - feedbackExports = pgTable( - "feedback_exports", - { - id: uuid("id").primaryKey().defaultRandom(), - companyId: uuid("company_id").notNull().references(() => companies.id), - feedbackVoteId: uuid("feedback_vote_id").notNull().references(() => feedbackVotes.id, { onDelete: "cascade" }), - issueId: uuid("issue_id").notNull().references(() => issues.id, { onDelete: "cascade" }), - projectId: uuid("project_id").references(() => projects.id, { onDelete: "set null" }), - authorUserId: text("author_user_id").notNull(), - targetType: text("target_type").notNull(), - targetId: text("target_id").notNull(), - vote: text("vote").notNull(), - status: text("status").notNull().default("local_only"), - destination: text("destination"), - exportId: text("export_id"), - consentVersion: text("consent_version"), - schemaVersion: text("schema_version").notNull().default("taskcore-feedback-envelope-v2"), - bundleVersion: text("bundle_version").notNull().default("taskcore-feedback-bundle-v2"), - payloadVersion: text("payload_version").notNull().default("taskcore-feedback-v1"), - payloadDigest: text("payload_digest"), - payloadSnapshot: jsonb("payload_snapshot"), - targetSummary: jsonb("target_summary").notNull(), - redactionSummary: jsonb("redaction_summary"), - attemptCount: integer("attempt_count").notNull().default(0), - lastAttemptedAt: timestamp("last_attempted_at", { withTimezone: true }), - exportedAt: timestamp("exported_at", { withTimezone: true }), - failureReason: text("failure_reason"), - createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), - updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() - }, - (table) => ({ - voteUniqueIdx: uniqueIndex("feedback_exports_feedback_vote_idx").on(table.feedbackVoteId), - companyCreatedIdx: index("feedback_exports_company_created_idx").on(table.companyId, table.createdAt), - companyStatusIdx: index("feedback_exports_company_status_idx").on(table.companyId, table.status, table.createdAt), - companyIssueIdx: index("feedback_exports_company_issue_idx").on(table.companyId, table.issueId, table.createdAt), - companyProjectIdx: index("feedback_exports_company_project_idx").on(table.companyId, table.projectId, table.createdAt), - companyAuthorIdx: index("feedback_exports_company_author_idx").on(table.companyId, table.authorUserId, table.createdAt) - }) - ); - } -}); - -// packages/db/src/schema/issue_read_states.ts -var issueReadStates; -var init_issue_read_states = __esm({ - "packages/db/src/schema/issue_read_states.ts"() { - "use strict"; - init_pg_core(); - init_companies(); - init_issues(); - issueReadStates = pgTable( - "issue_read_states", - { - id: uuid("id").primaryKey().defaultRandom(), - companyId: uuid("company_id").notNull().references(() => companies.id), - issueId: uuid("issue_id").notNull().references(() => issues.id), - userId: text("user_id").notNull(), - lastReadAt: timestamp("last_read_at", { withTimezone: true }).notNull().defaultNow(), - createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), - updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() - }, - (table) => ({ - companyIssueIdx: index("issue_read_states_company_issue_idx").on(table.companyId, table.issueId), - companyUserIdx: index("issue_read_states_company_user_idx").on(table.companyId, table.userId), - companyIssueUserUnique: uniqueIndex("issue_read_states_company_issue_user_idx").on( - table.companyId, - table.issueId, - table.userId - ) - }) - ); - } -}); - -// packages/db/src/schema/issue_attachments.ts -var issueAttachments; -var init_issue_attachments = __esm({ - "packages/db/src/schema/issue_attachments.ts"() { - "use strict"; - init_pg_core(); - init_companies(); - init_issues(); - init_assets(); - init_issue_comments(); - issueAttachments = pgTable( - "issue_attachments", - { - id: uuid("id").primaryKey().defaultRandom(), - companyId: uuid("company_id").notNull().references(() => companies.id), - issueId: uuid("issue_id").notNull().references(() => issues.id, { onDelete: "cascade" }), - assetId: uuid("asset_id").notNull().references(() => assets.id, { onDelete: "cascade" }), - issueCommentId: uuid("issue_comment_id").references(() => issueComments.id, { onDelete: "set null" }), - createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), - updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() - }, - (table) => ({ - companyIssueIdx: index("issue_attachments_company_issue_idx").on(table.companyId, table.issueId), - issueCommentIdx: index("issue_attachments_issue_comment_idx").on(table.issueCommentId), - assetUq: uniqueIndex("issue_attachments_asset_uq").on(table.assetId) - }) - ); - } -}); - -// packages/db/src/schema/documents.ts -var documents; -var init_documents = __esm({ - "packages/db/src/schema/documents.ts"() { - "use strict"; - init_pg_core(); - init_companies(); - init_agents(); - documents = pgTable( - "documents", - { - id: uuid("id").primaryKey().defaultRandom(), - companyId: uuid("company_id").notNull().references(() => companies.id), - title: text("title"), - format: text("format").notNull().default("markdown"), - latestBody: text("latest_body").notNull(), - latestRevisionId: uuid("latest_revision_id"), - latestRevisionNumber: integer("latest_revision_number").notNull().default(1), - createdByAgentId: uuid("created_by_agent_id").references(() => agents.id, { onDelete: "set null" }), - createdByUserId: text("created_by_user_id"), - updatedByAgentId: uuid("updated_by_agent_id").references(() => agents.id, { onDelete: "set null" }), - updatedByUserId: text("updated_by_user_id"), - createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), - updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() - }, - (table) => ({ - companyUpdatedIdx: index("documents_company_updated_idx").on(table.companyId, table.updatedAt), - companyCreatedIdx: index("documents_company_created_idx").on(table.companyId, table.createdAt) - }) - ); - } -}); - -// packages/db/src/schema/document_revisions.ts -var documentRevisions; -var init_document_revisions = __esm({ - "packages/db/src/schema/document_revisions.ts"() { - "use strict"; - init_pg_core(); - init_companies(); - init_agents(); - init_documents(); - init_heartbeat_runs(); - documentRevisions = pgTable( - "document_revisions", - { - id: uuid("id").primaryKey().defaultRandom(), - companyId: uuid("company_id").notNull().references(() => companies.id), - documentId: uuid("document_id").notNull().references(() => documents.id, { onDelete: "cascade" }), - revisionNumber: integer("revision_number").notNull(), - title: text("title"), - format: text("format").notNull().default("markdown"), - body: text("body").notNull(), - changeSummary: text("change_summary"), - createdByAgentId: uuid("created_by_agent_id").references(() => agents.id, { onDelete: "set null" }), - createdByUserId: text("created_by_user_id"), - createdByRunId: uuid("created_by_run_id").references(() => heartbeatRuns.id, { onDelete: "set null" }), - createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow() - }, - (table) => ({ - documentRevisionUq: uniqueIndex("document_revisions_document_revision_uq").on( - table.documentId, - table.revisionNumber - ), - companyDocumentCreatedIdx: index("document_revisions_company_document_created_idx").on( - table.companyId, - table.documentId, - table.createdAt - ) - }) - ); - } -}); - -// packages/db/src/schema/issue_documents.ts -var issueDocuments; -var init_issue_documents = __esm({ - "packages/db/src/schema/issue_documents.ts"() { - "use strict"; - init_pg_core(); - init_companies(); - init_issues(); - init_documents(); - issueDocuments = pgTable( - "issue_documents", - { - id: uuid("id").primaryKey().defaultRandom(), - companyId: uuid("company_id").notNull().references(() => companies.id), - issueId: uuid("issue_id").notNull().references(() => issues.id, { onDelete: "cascade" }), - documentId: uuid("document_id").notNull().references(() => documents.id, { onDelete: "cascade" }), - key: text("key").notNull(), - createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), - updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() - }, - (table) => ({ - companyIssueKeyUq: uniqueIndex("issue_documents_company_issue_key_uq").on( - table.companyId, - table.issueId, - table.key - ), - documentUq: uniqueIndex("issue_documents_document_uq").on(table.documentId), - companyIssueUpdatedIdx: index("issue_documents_company_issue_updated_idx").on( - table.companyId, - table.issueId, - table.updatedAt - ) - }) - ); - } -}); - -// packages/db/src/schema/heartbeat_run_events.ts -var heartbeatRunEvents; -var init_heartbeat_run_events = __esm({ - "packages/db/src/schema/heartbeat_run_events.ts"() { - "use strict"; - init_pg_core(); - init_companies(); - init_agents(); - init_heartbeat_runs(); - heartbeatRunEvents = pgTable( - "heartbeat_run_events", - { - id: bigserial("id", { mode: "number" }).primaryKey(), - companyId: uuid("company_id").notNull().references(() => companies.id), - runId: uuid("run_id").notNull().references(() => heartbeatRuns.id), - agentId: uuid("agent_id").notNull().references(() => agents.id), - seq: integer("seq").notNull(), - eventType: text("event_type").notNull(), - stream: text("stream"), - level: text("level"), - color: text("color"), - message: text("message"), - payload: jsonb("payload").$type(), - createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow() - }, - (table) => ({ - runSeqIdx: index("heartbeat_run_events_run_seq_idx").on(table.runId, table.seq), - companyRunIdx: index("heartbeat_run_events_company_run_idx").on(table.companyId, table.runId), - companyCreatedIdx: index("heartbeat_run_events_company_created_idx").on(table.companyId, table.createdAt) - }) - ); - } -}); - -// packages/db/src/schema/cost_events.ts -var costEvents; -var init_cost_events = __esm({ - "packages/db/src/schema/cost_events.ts"() { - "use strict"; - init_pg_core(); - init_companies(); - init_agents(); - init_issues(); - init_projects(); - init_goals(); - init_heartbeat_runs(); - costEvents = pgTable( - "cost_events", - { - id: uuid("id").primaryKey().defaultRandom(), - companyId: uuid("company_id").notNull().references(() => companies.id), - agentId: uuid("agent_id").notNull().references(() => agents.id), - issueId: uuid("issue_id").references(() => issues.id), - projectId: uuid("project_id").references(() => projects.id), - goalId: uuid("goal_id").references(() => goals.id), - heartbeatRunId: uuid("heartbeat_run_id").references(() => heartbeatRuns.id), - billingCode: text("billing_code"), - provider: text("provider").notNull(), - biller: text("biller").notNull().default("unknown"), - billingType: text("billing_type").notNull().default("unknown"), - model: text("model").notNull(), - inputTokens: integer("input_tokens").notNull().default(0), - cachedInputTokens: integer("cached_input_tokens").notNull().default(0), - outputTokens: integer("output_tokens").notNull().default(0), - costCents: integer("cost_cents").notNull(), - occurredAt: timestamp("occurred_at", { withTimezone: true }).notNull(), - createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow() - }, - (table) => ({ - companyOccurredIdx: index("cost_events_company_occurred_idx").on(table.companyId, table.occurredAt), - companyAgentOccurredIdx: index("cost_events_company_agent_occurred_idx").on( - table.companyId, - table.agentId, - table.occurredAt - ), - companyProviderOccurredIdx: index("cost_events_company_provider_occurred_idx").on( - table.companyId, - table.provider, - table.occurredAt - ), - companyBillerOccurredIdx: index("cost_events_company_biller_occurred_idx").on( - table.companyId, - table.biller, - table.occurredAt - ), - companyHeartbeatRunIdx: index("cost_events_company_heartbeat_run_idx").on( - table.companyId, - table.heartbeatRunId - ) - }) - ); - } -}); - -// packages/db/src/schema/finance_events.ts -var financeEvents; -var init_finance_events = __esm({ - "packages/db/src/schema/finance_events.ts"() { - "use strict"; - init_pg_core(); - init_companies(); - init_agents(); - init_issues(); - init_projects(); - init_goals(); - init_heartbeat_runs(); - init_cost_events(); - financeEvents = pgTable( - "finance_events", - { - id: uuid("id").primaryKey().defaultRandom(), - companyId: uuid("company_id").notNull().references(() => companies.id), - agentId: uuid("agent_id").references(() => agents.id), - issueId: uuid("issue_id").references(() => issues.id), - projectId: uuid("project_id").references(() => projects.id), - goalId: uuid("goal_id").references(() => goals.id), - heartbeatRunId: uuid("heartbeat_run_id").references(() => heartbeatRuns.id), - costEventId: uuid("cost_event_id").references(() => costEvents.id), - billingCode: text("billing_code"), - description: text("description"), - eventKind: text("event_kind").notNull(), - direction: text("direction").notNull().default("debit"), - biller: text("biller").notNull(), - provider: text("provider"), - executionAdapterType: text("execution_adapter_type"), - pricingTier: text("pricing_tier"), - region: text("region"), - model: text("model"), - quantity: integer("quantity"), - unit: text("unit"), - amountCents: integer("amount_cents").notNull(), - currency: text("currency").notNull().default("USD"), - estimated: boolean("estimated").notNull().default(false), - externalInvoiceId: text("external_invoice_id"), - metadataJson: jsonb("metadata_json").$type(), - occurredAt: timestamp("occurred_at", { withTimezone: true }).notNull(), - createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow() - }, - (table) => ({ - companyOccurredIdx: index("finance_events_company_occurred_idx").on(table.companyId, table.occurredAt), - companyBillerOccurredIdx: index("finance_events_company_biller_occurred_idx").on( - table.companyId, - table.biller, - table.occurredAt - ), - companyKindOccurredIdx: index("finance_events_company_kind_occurred_idx").on( - table.companyId, - table.eventKind, - table.occurredAt - ), - companyDirectionOccurredIdx: index("finance_events_company_direction_occurred_idx").on( - table.companyId, - table.direction, - table.occurredAt - ), - companyHeartbeatRunIdx: index("finance_events_company_heartbeat_run_idx").on( - table.companyId, - table.heartbeatRunId - ), - companyCostEventIdx: index("finance_events_company_cost_event_idx").on( - table.companyId, - table.costEventId - ) - }) - ); - } -}); - -// packages/db/src/schema/approval_comments.ts -var approvalComments; -var init_approval_comments = __esm({ - "packages/db/src/schema/approval_comments.ts"() { - "use strict"; - init_pg_core(); - init_companies(); - init_approvals(); - init_agents(); - approvalComments = pgTable( - "approval_comments", - { - id: uuid("id").primaryKey().defaultRandom(), - companyId: uuid("company_id").notNull().references(() => companies.id), - approvalId: uuid("approval_id").notNull().references(() => approvals.id), - authorAgentId: uuid("author_agent_id").references(() => agents.id), - authorUserId: text("author_user_id"), - body: text("body").notNull(), - createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), - updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() - }, - (table) => ({ - companyIdx: index("approval_comments_company_idx").on(table.companyId), - approvalIdx: index("approval_comments_approval_idx").on(table.approvalId), - approvalCreatedIdx: index("approval_comments_approval_created_idx").on( - table.approvalId, - table.createdAt - ) - }) - ); - } -}); - -// packages/db/src/schema/activity_log.ts -var activityLog; -var init_activity_log = __esm({ - "packages/db/src/schema/activity_log.ts"() { - "use strict"; - init_pg_core(); - init_companies(); - init_agents(); - init_heartbeat_runs(); - activityLog = pgTable( - "activity_log", - { - id: uuid("id").primaryKey().defaultRandom(), - companyId: uuid("company_id").notNull().references(() => companies.id), - actorType: text("actor_type").notNull().default("system"), - actorId: text("actor_id").notNull(), - action: text("action").notNull(), - entityType: text("entity_type").notNull(), - entityId: text("entity_id").notNull(), - agentId: uuid("agent_id").references(() => agents.id), - runId: uuid("run_id").references(() => heartbeatRuns.id), - details: jsonb("details").$type(), - createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow() - }, - (table) => ({ - companyCreatedIdx: index("activity_log_company_created_idx").on(table.companyId, table.createdAt), - runIdIdx: index("activity_log_run_id_idx").on(table.runId), - entityIdx: index("activity_log_entity_type_id_idx").on(table.entityType, table.entityId) - }) - ); - } -}); - -// packages/db/src/schema/company_secret_versions.ts -var companySecretVersions; -var init_company_secret_versions = __esm({ - "packages/db/src/schema/company_secret_versions.ts"() { - "use strict"; - init_pg_core(); - init_agents(); - init_company_secrets(); - companySecretVersions = pgTable( - "company_secret_versions", - { - id: uuid("id").primaryKey().defaultRandom(), - secretId: uuid("secret_id").notNull().references(() => companySecrets.id, { onDelete: "cascade" }), - version: integer("version").notNull(), - material: jsonb("material").$type().notNull(), - valueSha256: text("value_sha256").notNull(), - createdByAgentId: uuid("created_by_agent_id").references(() => agents.id, { onDelete: "set null" }), - createdByUserId: text("created_by_user_id"), - createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), - revokedAt: timestamp("revoked_at", { withTimezone: true }) - }, - (table) => ({ - secretIdx: index("company_secret_versions_secret_idx").on(table.secretId, table.createdAt), - valueHashIdx: index("company_secret_versions_value_sha256_idx").on(table.valueSha256), - secretVersionUq: uniqueIndex("company_secret_versions_secret_version_uq").on(table.secretId, table.version) - }) - ); - } -}); - -// packages/db/src/schema/company_skills.ts -var companySkills; -var init_company_skills = __esm({ - "packages/db/src/schema/company_skills.ts"() { - "use strict"; - init_pg_core(); - init_companies(); - companySkills = pgTable( - "company_skills", - { - id: uuid("id").primaryKey().defaultRandom(), - companyId: uuid("company_id").notNull().references(() => companies.id), - key: text("key").notNull(), - slug: text("slug").notNull(), - name: text("name").notNull(), - description: text("description"), - markdown: text("markdown").notNull(), - sourceType: text("source_type").notNull().default("local_path"), - sourceLocator: text("source_locator"), - sourceRef: text("source_ref"), - trustLevel: text("trust_level").notNull().default("markdown_only"), - compatibility: text("compatibility").notNull().default("compatible"), - fileInventory: jsonb("file_inventory").$type().notNull().default([]), - metadata: jsonb("metadata").$type(), - createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), - updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() - }, - (table) => ({ - companyKeyUniqueIdx: uniqueIndex("company_skills_company_key_idx").on(table.companyId, table.key), - companyNameIdx: index("company_skills_company_name_idx").on(table.companyId, table.name) - }) - ); - } -}); - -// packages/db/src/schema/plugins.ts -var plugins; -var init_plugins = __esm({ - "packages/db/src/schema/plugins.ts"() { - "use strict"; - init_pg_core(); - plugins = pgTable( - "plugins", - { - id: uuid("id").primaryKey().defaultRandom(), - pluginKey: text("plugin_key").notNull(), - packageName: text("package_name").notNull(), - version: text("version").notNull(), - apiVersion: integer("api_version").notNull().default(1), - categories: jsonb("categories").$type().notNull().default([]), - manifestJson: jsonb("manifest_json").$type().notNull(), - status: text("status").$type().notNull().default("installed"), - installOrder: integer("install_order"), - /** Resolved package path for local-path installs; used to find worker entrypoint. */ - packagePath: text("package_path"), - lastError: text("last_error"), - installedAt: timestamp("installed_at", { withTimezone: true }).notNull().defaultNow(), - updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() - }, - (table) => ({ - pluginKeyIdx: uniqueIndex("plugins_plugin_key_idx").on(table.pluginKey), - statusIdx: index("plugins_status_idx").on(table.status) - }) - ); - } -}); - -// packages/db/src/schema/plugin_config.ts -var pluginConfig; -var init_plugin_config = __esm({ - "packages/db/src/schema/plugin_config.ts"() { - "use strict"; - init_pg_core(); - init_plugins(); - pluginConfig = pgTable( - "plugin_config", - { - id: uuid("id").primaryKey().defaultRandom(), - pluginId: uuid("plugin_id").notNull().references(() => plugins.id, { onDelete: "cascade" }), - configJson: jsonb("config_json").$type().notNull().default({}), - lastError: text("last_error"), - createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), - updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() - }, - (table) => ({ - pluginIdIdx: uniqueIndex("plugin_config_plugin_id_idx").on(table.pluginId) - }) - ); - } -}); - -// packages/db/src/schema/plugin_company_settings.ts -var pluginCompanySettings; -var init_plugin_company_settings = __esm({ - "packages/db/src/schema/plugin_company_settings.ts"() { - "use strict"; - init_pg_core(); - init_companies(); - init_plugins(); - pluginCompanySettings = pgTable( - "plugin_company_settings", - { - id: uuid("id").primaryKey().defaultRandom(), - companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }), - pluginId: uuid("plugin_id").notNull().references(() => plugins.id, { onDelete: "cascade" }), - enabled: boolean("enabled").notNull().default(true), - settingsJson: jsonb("settings_json").$type().notNull().default({}), - lastError: text("last_error"), - createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), - updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() - }, - (table) => ({ - companyIdx: index("plugin_company_settings_company_idx").on(table.companyId), - pluginIdx: index("plugin_company_settings_plugin_idx").on(table.pluginId), - companyPluginUq: uniqueIndex("plugin_company_settings_company_plugin_uq").on( - table.companyId, - table.pluginId - ) - }) - ); - } -}); - -// packages/db/src/schema/plugin_state.ts -var pluginState; -var init_plugin_state = __esm({ - "packages/db/src/schema/plugin_state.ts"() { - "use strict"; - init_pg_core(); - init_plugins(); - pluginState = pgTable( - "plugin_state", - { - id: uuid("id").primaryKey().defaultRandom(), - /** FK to the owning plugin. Cascades on delete. */ - pluginId: uuid("plugin_id").notNull().references(() => plugins.id, { onDelete: "cascade" }), - /** Granularity of the scope (e.g. `"instance"`, `"project"`, `"issue"`). */ - scopeKind: text("scope_kind").$type().notNull(), - /** - * UUID or text identifier for the scoped object. - * Null for `instance` scope (which has no associated entity). - */ - scopeId: text("scope_id"), - /** - * Sub-namespace to avoid key collisions within a scope. - * Defaults to `"default"` if the plugin does not specify one. - */ - namespace: text("namespace").notNull().default("default"), - /** The key identifying this state entry within the namespace. */ - stateKey: text("state_key").notNull(), - /** JSON-serializable value stored by the plugin. */ - valueJson: jsonb("value_json").notNull(), - /** Timestamp of the most recent write. */ - updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() - }, - (table) => ({ - /** - * Unique constraint enforces that there is at most one value per - * (plugin, scope kind, scope id, namespace, key) tuple. - * - * `nullsNotDistinct()` is required so that `scope_id IS NULL` entries - * (used by `instance` scope) are treated as equal by PostgreSQL rather - * than as distinct nulls — otherwise the upsert target in `set()` would - * fail to match existing rows and create duplicates. - * - * Requires PostgreSQL 15+. - */ - uniqueEntry: unique("plugin_state_unique_entry_idx").on( - table.pluginId, - table.scopeKind, - table.scopeId, - table.namespace, - table.stateKey - ).nullsNotDistinct(), - /** Speed up lookups by plugin + scope kind (most common access pattern). */ - pluginScopeIdx: index("plugin_state_plugin_scope_idx").on( - table.pluginId, - table.scopeKind - ) - }) - ); - } -}); - -// packages/db/src/schema/plugin_entities.ts -var pluginEntities; -var init_plugin_entities = __esm({ - "packages/db/src/schema/plugin_entities.ts"() { - "use strict"; - init_pg_core(); - init_plugins(); - pluginEntities = pgTable( - "plugin_entities", - { - id: uuid("id").primaryKey().defaultRandom(), - pluginId: uuid("plugin_id").notNull().references(() => plugins.id, { onDelete: "cascade" }), - entityType: text("entity_type").notNull(), - scopeKind: text("scope_kind").$type().notNull(), - scopeId: text("scope_id"), - // NULL for global scope (text to match plugin_state.scope_id) - externalId: text("external_id"), - // ID in the external system - title: text("title"), - status: text("status"), - data: jsonb("data").$type().notNull().default({}), - createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), - updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() - }, - (table) => ({ - pluginIdx: index("plugin_entities_plugin_idx").on(table.pluginId), - typeIdx: index("plugin_entities_type_idx").on(table.entityType), - scopeIdx: index("plugin_entities_scope_idx").on(table.scopeKind, table.scopeId), - externalIdx: uniqueIndex("plugin_entities_external_idx").on( - table.pluginId, - table.entityType, - table.externalId - ) - }) - ); - } -}); - -// packages/db/src/schema/plugin_jobs.ts -var pluginJobs, pluginJobRuns; -var init_plugin_jobs = __esm({ - "packages/db/src/schema/plugin_jobs.ts"() { - "use strict"; - init_pg_core(); - init_plugins(); - pluginJobs = pgTable( - "plugin_jobs", - { - id: uuid("id").primaryKey().defaultRandom(), - /** FK to the owning plugin. Cascades on delete. */ - pluginId: uuid("plugin_id").notNull().references(() => plugins.id, { onDelete: "cascade" }), - /** Identifier matching the key in the plugin manifest's `jobs` array. */ - jobKey: text("job_key").notNull(), - /** Cron expression (e.g. `"0 * * * *"`) or interval string. */ - schedule: text("schedule").notNull(), - /** Current scheduling state. */ - status: text("status").$type().notNull().default("active"), - /** Timestamp of the most recent successful execution. */ - lastRunAt: timestamp("last_run_at", { withTimezone: true }), - /** Pre-computed timestamp of the next scheduled execution. */ - nextRunAt: timestamp("next_run_at", { withTimezone: true }), - createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), - updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow() - }, - (table) => ({ - pluginIdx: index("plugin_jobs_plugin_idx").on(table.pluginId), - nextRunIdx: index("plugin_jobs_next_run_idx").on(table.nextRunAt), - uniqueJobIdx: uniqueIndex("plugin_jobs_unique_idx").on(table.pluginId, table.jobKey) - }) - ); - pluginJobRuns = pgTable( - "plugin_job_runs", - { - id: uuid("id").primaryKey().defaultRandom(), - /** FK to the parent job definition. Cascades on delete. */ - jobId: uuid("job_id").notNull().references(() => pluginJobs.id, { onDelete: "cascade" }), - /** Denormalized FK to the owning plugin for efficient querying. Cascades on delete. */ - pluginId: uuid("plugin_id").notNull().references(() => plugins.id, { onDelete: "cascade" }), - /** What caused this run to start (`"scheduled"` or `"manual"`). */ - trigger: text("trigger").$type().notNull(), - /** Current lifecycle state of this run. */ - status: text("status").$type().notNull().default("pending"), - /** Wall-clock duration in milliseconds. Null until the run finishes. */ - durationMs: integer("duration_ms"), - /** Error message if `status === "failed"`. */ - error: text("error"), - /** Ordered list of log lines emitted during this run. */ - logs: jsonb("logs").$type().notNull().default([]), - startedAt: timestamp("started_at", { withTimezone: true }), - finishedAt: timestamp("finished_at", { withTimezone: true }), - createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow() - }, - (table) => ({ - jobIdx: index("plugin_job_runs_job_idx").on(table.jobId), - pluginIdx: index("plugin_job_runs_plugin_idx").on(table.pluginId), - statusIdx: index("plugin_job_runs_status_idx").on(table.status) - }) - ); - } -}); - -// packages/db/src/schema/plugin_webhooks.ts -var pluginWebhookDeliveries; -var init_plugin_webhooks = __esm({ - "packages/db/src/schema/plugin_webhooks.ts"() { - "use strict"; - init_pg_core(); - init_plugins(); - pluginWebhookDeliveries = pgTable( - "plugin_webhook_deliveries", - { - id: uuid("id").primaryKey().defaultRandom(), - /** FK to the owning plugin. Cascades on delete. */ - pluginId: uuid("plugin_id").notNull().references(() => plugins.id, { onDelete: "cascade" }), - /** Identifier matching the key in the plugin manifest's `webhooks` array. */ - webhookKey: text("webhook_key").notNull(), - /** Optional de-duplication ID provided by the external system. */ - externalId: text("external_id"), - /** Current delivery state. */ - status: text("status").$type().notNull().default("pending"), - /** Wall-clock processing duration in milliseconds. Null until delivery finishes. */ - durationMs: integer("duration_ms"), - /** Error message if `status === "failed"`. */ - error: text("error"), - /** Raw JSON body of the inbound HTTP request. */ - payload: jsonb("payload").$type().notNull(), - /** Relevant HTTP headers from the inbound request (e.g. signature headers). */ - headers: jsonb("headers").$type().notNull().default({}), - startedAt: timestamp("started_at", { withTimezone: true }), - finishedAt: timestamp("finished_at", { withTimezone: true }), - createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow() - }, - (table) => ({ - pluginIdx: index("plugin_webhook_deliveries_plugin_idx").on(table.pluginId), - statusIdx: index("plugin_webhook_deliveries_status_idx").on(table.status), - keyIdx: index("plugin_webhook_deliveries_key_idx").on(table.webhookKey) - }) - ); - } -}); - -// packages/db/src/schema/plugin_logs.ts -var pluginLogs; -var init_plugin_logs = __esm({ - "packages/db/src/schema/plugin_logs.ts"() { - "use strict"; - init_pg_core(); - init_plugins(); - pluginLogs = pgTable( - "plugin_logs", - { - id: uuid("id").primaryKey().defaultRandom(), - pluginId: uuid("plugin_id").notNull().references(() => plugins.id, { onDelete: "cascade" }), - level: text("level").notNull().default("info"), - message: text("message").notNull(), - meta: jsonb("meta").$type(), - createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow() - }, - (table) => ({ - pluginTimeIdx: index("plugin_logs_plugin_time_idx").on( - table.pluginId, - table.createdAt - ), - levelIdx: index("plugin_logs_level_idx").on(table.level) - }) - ); - } -}); - -// packages/db/src/schema/index.ts -var schema_exports = {}; -__export(schema_exports, { - activityLog: () => activityLog, - agentApiKeys: () => agentApiKeys, - agentConfigRevisions: () => agentConfigRevisions, - agentRuntimeState: () => agentRuntimeState, - agentTaskSessions: () => agentTaskSessions, - agentWakeupRequests: () => agentWakeupRequests, - agents: () => agents, - approvalComments: () => approvalComments, - approvals: () => approvals, - assets: () => assets, - authAccounts: () => authAccounts, - authSessions: () => authSessions, - authUsers: () => authUsers, - authVerifications: () => authVerifications, - boardApiKeys: () => boardApiKeys, - budgetIncidents: () => budgetIncidents, - budgetPolicies: () => budgetPolicies, - cliAuthChallenges: () => cliAuthChallenges, - companies: () => companies, - companyLogos: () => companyLogos, - companyMemberships: () => companyMemberships, - companySecretVersions: () => companySecretVersions, - companySecrets: () => companySecrets, - companySkills: () => companySkills, - companyUserSidebarPreferences: () => companyUserSidebarPreferences, - costEvents: () => costEvents, - documentRevisions: () => documentRevisions, - documents: () => documents, - executionWorkspaces: () => executionWorkspaces, - feedbackExports: () => feedbackExports, - feedbackVotes: () => feedbackVotes, - financeEvents: () => financeEvents, - goals: () => goals, - heartbeatRunEvents: () => heartbeatRunEvents, - heartbeatRuns: () => heartbeatRuns, - inboxDismissals: () => inboxDismissals, - instanceSettings: () => instanceSettings, - instanceUserRoles: () => instanceUserRoles, - invites: () => invites, - issueApprovals: () => issueApprovals, - issueAttachments: () => issueAttachments, - issueComments: () => issueComments, - issueDocuments: () => issueDocuments, - issueExecutionDecisions: () => issueExecutionDecisions, - issueInboxArchives: () => issueInboxArchives, - issueLabels: () => issueLabels, - issueReadStates: () => issueReadStates, - issueRelations: () => issueRelations, - issueWorkProducts: () => issueWorkProducts, - issues: () => issues, - joinRequests: () => joinRequests, - labels: () => labels, - pluginCompanySettings: () => pluginCompanySettings, - pluginConfig: () => pluginConfig, - pluginEntities: () => pluginEntities, - pluginJobRuns: () => pluginJobRuns, - pluginJobs: () => pluginJobs, - pluginLogs: () => pluginLogs, - pluginState: () => pluginState, - pluginWebhookDeliveries: () => pluginWebhookDeliveries, - plugins: () => plugins, - principalPermissionGrants: () => principalPermissionGrants, - projectGoals: () => projectGoals, - projectWorkspaces: () => projectWorkspaces, - projects: () => projects, - routineRuns: () => routineRuns, - routineTriggers: () => routineTriggers, - routines: () => routines, - userSidebarPreferences: () => userSidebarPreferences, - workspaceOperations: () => workspaceOperations, - workspaceRuntimeServices: () => workspaceRuntimeServices -}); -var init_schema2 = __esm({ - "packages/db/src/schema/index.ts"() { - "use strict"; - init_companies(); - init_company_logos(); - init_auth(); - init_instance_settings(); - init_instance_user_roles(); - init_user_sidebar_preferences(); - init_agents(); - init_board_api_keys(); - init_cli_auth_challenges(); - init_company_memberships(); - init_company_user_sidebar_preferences(); - init_principal_permission_grants(); - init_invites(); - init_join_requests(); - init_budget_policies(); - init_budget_incidents(); - init_agent_config_revisions(); - init_agent_api_keys(); - init_agent_runtime_state(); - init_agent_task_sessions(); - init_agent_wakeup_requests(); - init_projects(); - init_project_workspaces(); - init_execution_workspaces(); - init_workspace_operations(); - init_workspace_runtime_services(); - init_project_goals(); - init_goals(); - init_issues(); - init_issue_relations(); - init_routines(); - init_issue_work_products(); - init_labels(); - init_issue_labels(); - init_issue_approvals(); - init_issue_comments(); - init_issue_execution_decisions(); - init_issue_inbox_archives(); - init_inbox_dismissals(); - init_feedback_votes(); - init_feedback_exports(); - init_issue_read_states(); - init_assets(); - init_issue_attachments(); - init_documents(); - init_document_revisions(); - init_issue_documents(); - init_heartbeat_runs(); - init_heartbeat_run_events(); - init_cost_events(); - init_finance_events(); - init_approvals(); - init_approval_comments(); - init_activity_log(); - init_company_secrets(); - init_company_secret_versions(); - init_company_skills(); - init_plugins(); - init_plugin_config(); - init_plugin_company_settings(); - init_plugin_state(); - init_plugin_entities(); - init_plugin_jobs(); - init_plugin_webhooks(); - init_plugin_logs(); - } -}); - -// packages/db/src/client.ts -import { fileURLToPath } from "node:url"; -function createDb(url2, options) { - const opts = {}; - if (options?.max !== void 0) opts.max = options.max; - if (options?.prepare !== void 0) opts.prepare = options.prepare; - const sql3 = src_default(url2, opts); - return drizzle(sql3, { schema: schema_exports }); -} -var MIGRATIONS_FOLDER, MIGRATIONS_JOURNAL_JSON; -var init_client = __esm({ - "packages/db/src/client.ts"() { - "use strict"; - init_postgres_js(); - init_src(); - init_schema2(); - MIGRATIONS_FOLDER = fileURLToPath(new URL("./migrations", import.meta.url)); - MIGRATIONS_JOURNAL_JSON = fileURLToPath(new URL("./migrations/meta/_journal.json", import.meta.url)); - } -}); - -// packages/db/src/test-embedded-postgres.ts -var init_test_embedded_postgres = __esm({ - "packages/db/src/test-embedded-postgres.ts"() { - "use strict"; - init_client(); - } -}); - -// packages/db/src/backup-lib.ts -var DEFAULT_BACKUP_WRITE_BUFFER_BYTES; -var init_backup_lib = __esm({ - "packages/db/src/backup-lib.ts"() { - "use strict"; - init_src(); - DEFAULT_BACKUP_WRITE_BUFFER_BYTES = 1024 * 1024; - } -}); - -// packages/db/src/embedded-postgres-error.ts -var init_embedded_postgres_error = __esm({ - "packages/db/src/embedded-postgres-error.ts"() { - "use strict"; - } -}); - -// packages/db/src/index.ts -var init_src2 = __esm({ - "packages/db/src/index.ts"() { - "use strict"; - init_client(); - init_test_embedded_postgres(); - init_backup_lib(); - init_embedded_postgres_error(); - init_issue_relations(); - init_schema2(); - } -}); - -// node_modules/.pnpm/ms@2.1.3/node_modules/ms/index.js -var require_ms = __commonJS({ - "node_modules/.pnpm/ms@2.1.3/node_modules/ms/index.js"(exports, module) { - var s5 = 1e3; - var m5 = s5 * 60; - var h5 = m5 * 60; - var d5 = h5 * 24; - var w5 = d5 * 7; - var y2 = d5 * 365.25; - module.exports = function(val, options) { - options = options || {}; - var type = typeof val; - if (type === "string" && val.length > 0) { - return parse5(val); - } else if (type === "number" && isFinite(val)) { - return options.long ? fmtLong(val) : fmtShort(val); - } - throw new Error( - "val is not a non-empty string or a valid number. val=" + JSON.stringify(val) - ); - }; - function parse5(str) { - str = String(str); - if (str.length > 100) { - return; - } - var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( - str - ); - if (!match) { - return; - } - var n5 = parseFloat(match[1]); - var type = (match[2] || "ms").toLowerCase(); - switch (type) { - case "years": - case "year": - case "yrs": - case "yr": - case "y": - return n5 * y2; - case "weeks": - case "week": - case "w": - return n5 * w5; - case "days": - case "day": - case "d": - return n5 * d5; - case "hours": - case "hour": - case "hrs": - case "hr": - case "h": - return n5 * h5; - case "minutes": - case "minute": - case "mins": - case "min": - case "m": - return n5 * m5; - case "seconds": - case "second": - case "secs": - case "sec": - case "s": - return n5 * s5; - case "milliseconds": - case "millisecond": - case "msecs": - case "msec": - case "ms": - return n5; - default: - return void 0; - } - } - function fmtShort(ms) { - var msAbs = Math.abs(ms); - if (msAbs >= d5) { - return Math.round(ms / d5) + "d"; - } - if (msAbs >= h5) { - return Math.round(ms / h5) + "h"; - } - if (msAbs >= m5) { - return Math.round(ms / m5) + "m"; - } - if (msAbs >= s5) { - return Math.round(ms / s5) + "s"; - } - return ms + "ms"; - } - function fmtLong(ms) { - var msAbs = Math.abs(ms); - if (msAbs >= d5) { - return plural(ms, msAbs, d5, "day"); - } - if (msAbs >= h5) { - return plural(ms, msAbs, h5, "hour"); - } - if (msAbs >= m5) { - return plural(ms, msAbs, m5, "minute"); - } - if (msAbs >= s5) { - return plural(ms, msAbs, s5, "second"); - } - return ms + " ms"; - } - function plural(ms, msAbs, n5, name) { - var isPlural = msAbs >= n5 * 1.5; - return Math.round(ms / n5) + " " + name + (isPlural ? "s" : ""); - } - } -}); - -// node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/common.js -var require_common = __commonJS({ - "node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/common.js"(exports, module) { - function setup(env2) { - createDebug.debug = createDebug; - createDebug.default = createDebug; - createDebug.coerce = coerce2; - createDebug.disable = disable; - createDebug.enable = enable; - createDebug.enabled = enabled; - createDebug.humanize = require_ms(); - createDebug.destroy = destroy; - Object.keys(env2).forEach((key) => { - createDebug[key] = env2[key]; - }); - createDebug.names = []; - createDebug.skips = []; - createDebug.formatters = {}; - function selectColor(namespace) { - let hash2 = 0; - for (let i5 = 0; i5 < namespace.length; i5++) { - hash2 = (hash2 << 5) - hash2 + namespace.charCodeAt(i5); - hash2 |= 0; - } - return createDebug.colors[Math.abs(hash2) % createDebug.colors.length]; - } - createDebug.selectColor = selectColor; - function createDebug(namespace) { - let prevTime; - let enableOverride = null; - let namespacesCache; - let enabledCache; - function debug(...args) { - if (!debug.enabled) { - return; - } - const self2 = debug; - const curr = Number(/* @__PURE__ */ new Date()); - const ms = curr - (prevTime || curr); - self2.diff = ms; - self2.prev = prevTime; - self2.curr = curr; - prevTime = curr; - args[0] = createDebug.coerce(args[0]); - if (typeof args[0] !== "string") { - args.unshift("%O"); - } - let index2 = 0; - args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format2) => { - if (match === "%%") { - return "%"; - } - index2++; - const formatter = createDebug.formatters[format2]; - if (typeof formatter === "function") { - const val = args[index2]; - match = formatter.call(self2, val); - args.splice(index2, 1); - index2--; - } - return match; - }); - createDebug.formatArgs.call(self2, args); - const logFn = self2.log || createDebug.log; - logFn.apply(self2, args); - } - debug.namespace = namespace; - debug.useColors = createDebug.useColors(); - debug.color = createDebug.selectColor(namespace); - debug.extend = extend2; - debug.destroy = createDebug.destroy; - Object.defineProperty(debug, "enabled", { - enumerable: true, - configurable: false, - get: () => { - if (enableOverride !== null) { - return enableOverride; - } - if (namespacesCache !== createDebug.namespaces) { - namespacesCache = createDebug.namespaces; - enabledCache = createDebug.enabled(namespace); - } - return enabledCache; - }, - set: (v5) => { - enableOverride = v5; - } - }); - if (typeof createDebug.init === "function") { - createDebug.init(debug); - } - return debug; - } - function extend2(namespace, delimiter) { - const newDebug = createDebug(this.namespace + (typeof delimiter === "undefined" ? ":" : delimiter) + namespace); - newDebug.log = this.log; - return newDebug; - } - function enable(namespaces) { - createDebug.save(namespaces); - createDebug.namespaces = namespaces; - createDebug.names = []; - createDebug.skips = []; - const split = (typeof namespaces === "string" ? namespaces : "").trim().replace(/\s+/g, ",").split(",").filter(Boolean); - for (const ns of split) { - if (ns[0] === "-") { - createDebug.skips.push(ns.slice(1)); - } else { - createDebug.names.push(ns); - } - } - } - function matchesTemplate(search, template) { - let searchIndex = 0; - let templateIndex = 0; - let starIndex = -1; - let matchIndex = 0; - while (searchIndex < search.length) { - if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === "*")) { - if (template[templateIndex] === "*") { - starIndex = templateIndex; - matchIndex = searchIndex; - templateIndex++; - } else { - searchIndex++; - templateIndex++; - } - } else if (starIndex !== -1) { - templateIndex = starIndex + 1; - matchIndex++; - searchIndex = matchIndex; - } else { - return false; - } - } - while (templateIndex < template.length && template[templateIndex] === "*") { - templateIndex++; - } - return templateIndex === template.length; - } - function disable() { - const namespaces = [ - ...createDebug.names, - ...createDebug.skips.map((namespace) => "-" + namespace) - ].join(","); - createDebug.enable(""); - return namespaces; - } - function enabled(name) { - for (const skip of createDebug.skips) { - if (matchesTemplate(name, skip)) { - return false; - } - } - for (const ns of createDebug.names) { - if (matchesTemplate(name, ns)) { - return true; - } - } - return false; - } - function coerce2(val) { - if (val instanceof Error) { - return val.stack || val.message; - } - return val; - } - function destroy() { - console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."); - } - createDebug.enable(createDebug.load()); - return createDebug; - } - module.exports = setup; - } -}); - -// node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/browser.js -var require_browser = __commonJS({ - "node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/browser.js"(exports, module) { - exports.formatArgs = formatArgs; - exports.save = save; - exports.load = load; - exports.useColors = useColors; - exports.storage = localstorage(); - exports.destroy = /* @__PURE__ */ (() => { - let warned = false; - return () => { - if (!warned) { - warned = true; - console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."); - } - }; - })(); - exports.colors = [ - "#0000CC", - "#0000FF", - "#0033CC", - "#0033FF", - "#0066CC", - "#0066FF", - "#0099CC", - "#0099FF", - "#00CC00", - "#00CC33", - "#00CC66", - "#00CC99", - "#00CCCC", - "#00CCFF", - "#3300CC", - "#3300FF", - "#3333CC", - "#3333FF", - "#3366CC", - "#3366FF", - "#3399CC", - "#3399FF", - "#33CC00", - "#33CC33", - "#33CC66", - "#33CC99", - "#33CCCC", - "#33CCFF", - "#6600CC", - "#6600FF", - "#6633CC", - "#6633FF", - "#66CC00", - "#66CC33", - "#9900CC", - "#9900FF", - "#9933CC", - "#9933FF", - "#99CC00", - "#99CC33", - "#CC0000", - "#CC0033", - "#CC0066", - "#CC0099", - "#CC00CC", - "#CC00FF", - "#CC3300", - "#CC3333", - "#CC3366", - "#CC3399", - "#CC33CC", - "#CC33FF", - "#CC6600", - "#CC6633", - "#CC9900", - "#CC9933", - "#CCCC00", - "#CCCC33", - "#FF0000", - "#FF0033", - "#FF0066", - "#FF0099", - "#FF00CC", - "#FF00FF", - "#FF3300", - "#FF3333", - "#FF3366", - "#FF3399", - "#FF33CC", - "#FF33FF", - "#FF6600", - "#FF6633", - "#FF9900", - "#FF9933", - "#FFCC00", - "#FFCC33" - ]; - function useColors() { - if (typeof window !== "undefined" && window.process && (window.process.type === "renderer" || window.process.__nwjs)) { - return true; - } - if (typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { - return false; - } - let m5; - return typeof document !== "undefined" && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773 - typeof window !== "undefined" && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31? - // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages - typeof navigator !== "undefined" && navigator.userAgent && (m5 = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m5[1], 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker - typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/); - } - function formatArgs(args) { - args[0] = (this.useColors ? "%c" : "") + this.namespace + (this.useColors ? " %c" : " ") + args[0] + (this.useColors ? "%c " : " ") + "+" + module.exports.humanize(this.diff); - if (!this.useColors) { - return; - } - const c5 = "color: " + this.color; - args.splice(1, 0, c5, "color: inherit"); - let index2 = 0; - let lastC = 0; - args[0].replace(/%[a-zA-Z%]/g, (match) => { - if (match === "%%") { - return; - } - index2++; - if (match === "%c") { - lastC = index2; - } - }); - args.splice(lastC, 0, c5); - } - exports.log = console.debug || console.log || (() => { - }); - function save(namespaces) { - try { - if (namespaces) { - exports.storage.setItem("debug", namespaces); - } else { - exports.storage.removeItem("debug"); - } - } catch (error50) { - } - } - function load() { - let r5; - try { - r5 = exports.storage.getItem("debug") || exports.storage.getItem("DEBUG"); - } catch (error50) { - } - if (!r5 && typeof process !== "undefined" && "env" in process) { - r5 = process.env.DEBUG; - } - return r5; - } - function localstorage() { - try { - return localStorage; - } catch (error50) { - } - } - module.exports = require_common()(exports); - var { formatters } = module.exports; - formatters.j = function(v5) { - try { - return JSON.stringify(v5); - } catch (error50) { - return "[UnexpectedJSONParseError]: " + error50.message; - } - }; - } -}); - -// node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/node.js -var require_node = __commonJS({ - "node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/node.js"(exports, module) { - var tty = __require("tty"); - var util2 = __require("util"); - exports.init = init2; - exports.log = log2; - exports.formatArgs = formatArgs; - exports.save = save; - exports.load = load; - exports.useColors = useColors; - exports.destroy = util2.deprecate( - () => { - }, - "Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`." - ); - exports.colors = [6, 2, 3, 4, 5, 1]; - try { - const supportsColor = __require("supports-color"); - if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { - exports.colors = [ - 20, - 21, - 26, - 27, - 32, - 33, - 38, - 39, - 40, - 41, - 42, - 43, - 44, - 45, - 56, - 57, - 62, - 63, - 68, - 69, - 74, - 75, - 76, - 77, - 78, - 79, - 80, - 81, - 92, - 93, - 98, - 99, - 112, - 113, - 128, - 129, - 134, - 135, - 148, - 149, - 160, - 161, - 162, - 163, - 164, - 165, - 166, - 167, - 168, - 169, - 170, - 171, - 172, - 173, - 178, - 179, - 184, - 185, - 196, - 197, - 198, - 199, - 200, - 201, - 202, - 203, - 204, - 205, - 206, - 207, - 208, - 209, - 214, - 215, - 220, - 221 - ]; - } - } catch (error50) { - } - exports.inspectOpts = Object.keys(process.env).filter((key) => { - return /^debug_/i.test(key); - }).reduce((obj, key) => { - const prop = key.substring(6).toLowerCase().replace(/_([a-z])/g, (_, k5) => { - return k5.toUpperCase(); - }); - let val = process.env[key]; - if (/^(yes|on|true|enabled)$/i.test(val)) { - val = true; - } else if (/^(no|off|false|disabled)$/i.test(val)) { - val = false; - } else if (val === "null") { - val = null; - } else { - val = Number(val); - } - obj[prop] = val; - return obj; - }, {}); - function useColors() { - return "colors" in exports.inspectOpts ? Boolean(exports.inspectOpts.colors) : tty.isatty(process.stderr.fd); - } - function formatArgs(args) { - const { namespace: name, useColors: useColors2 } = this; - if (useColors2) { - const c5 = this.color; - const colorCode = "\x1B[3" + (c5 < 8 ? c5 : "8;5;" + c5); - const prefix = ` ${colorCode};1m${name} \x1B[0m`; - args[0] = prefix + args[0].split("\n").join("\n" + prefix); - args.push(colorCode + "m+" + module.exports.humanize(this.diff) + "\x1B[0m"); - } else { - args[0] = getDate2() + name + " " + args[0]; - } - } - function getDate2() { - if (exports.inspectOpts.hideDate) { - return ""; - } - return (/* @__PURE__ */ new Date()).toISOString() + " "; - } - function log2(...args) { - return process.stderr.write(util2.formatWithOptions(exports.inspectOpts, ...args) + "\n"); - } - function save(namespaces) { - if (namespaces) { - process.env.DEBUG = namespaces; - } else { - delete process.env.DEBUG; - } - } - function load() { - return process.env.DEBUG; - } - function init2(debug) { - debug.inspectOpts = {}; - const keys = Object.keys(exports.inspectOpts); - for (let i5 = 0; i5 < keys.length; i5++) { - debug.inspectOpts[keys[i5]] = exports.inspectOpts[keys[i5]]; - } - } - module.exports = require_common()(exports); - var { formatters } = module.exports; - formatters.o = function(v5) { - this.inspectOpts.colors = this.useColors; - return util2.inspect(v5, this.inspectOpts).split("\n").map((str) => str.trim()).join(" "); - }; - formatters.O = function(v5) { - this.inspectOpts.colors = this.useColors; - return util2.inspect(v5, this.inspectOpts); - }; - } -}); - -// node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/index.js -var require_src = __commonJS({ - "node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/index.js"(exports, module) { - if (typeof process === "undefined" || process.type === "renderer" || process.browser === true || process.__nwjs) { - module.exports = require_browser(); - } else { - module.exports = require_node(); - } - } -}); - -// node_modules/.pnpm/depd@2.0.0/node_modules/depd/index.js -var require_depd = __commonJS({ - "node_modules/.pnpm/depd@2.0.0/node_modules/depd/index.js"(exports, module) { - var relative3 = __require("path").relative; - module.exports = depd; - var basePath = process.cwd(); - function containsNamespace(str, namespace) { - var vals = str.split(/[ ,]+/); - var ns = String(namespace).toLowerCase(); - for (var i5 = 0; i5 < vals.length; i5++) { - var val = vals[i5]; - if (val && (val === "*" || val.toLowerCase() === ns)) { - return true; - } - } - return false; - } - function convertDataDescriptorToAccessor(obj, prop, message2) { - var descriptor = Object.getOwnPropertyDescriptor(obj, prop); - var value = descriptor.value; - descriptor.get = function getter() { - return value; - }; - if (descriptor.writable) { - descriptor.set = function setter(val) { - return value = val; - }; - } - delete descriptor.value; - delete descriptor.writable; - Object.defineProperty(obj, prop, descriptor); - return descriptor; - } - function createArgumentsString(arity) { - var str = ""; - for (var i5 = 0; i5 < arity; i5++) { - str += ", arg" + i5; - } - return str.substr(2); - } - function createStackString(stack) { - var str = this.name + ": " + this.namespace; - if (this.message) { - str += " deprecated " + this.message; - } - for (var i5 = 0; i5 < stack.length; i5++) { - str += "\n at " + stack[i5].toString(); - } - return str; - } - function depd(namespace) { - if (!namespace) { - throw new TypeError("argument namespace is required"); - } - var stack = getStack(); - var site = callSiteLocation(stack[1]); - var file2 = site[0]; - function deprecate2(message2) { - log2.call(deprecate2, message2); - } - deprecate2._file = file2; - deprecate2._ignored = isignored(namespace); - deprecate2._namespace = namespace; - deprecate2._traced = istraced(namespace); - deprecate2._warned = /* @__PURE__ */ Object.create(null); - deprecate2.function = wrapfunction; - deprecate2.property = wrapproperty; - return deprecate2; - } - function eehaslisteners(emitter2, type) { - var count2 = typeof emitter2.listenerCount !== "function" ? emitter2.listeners(type).length : emitter2.listenerCount(type); - return count2 > 0; - } - function isignored(namespace) { - if (process.noDeprecation) { - return true; - } - var str = process.env.NO_DEPRECATION || ""; - return containsNamespace(str, namespace); - } - function istraced(namespace) { - if (process.traceDeprecation) { - return true; - } - var str = process.env.TRACE_DEPRECATION || ""; - return containsNamespace(str, namespace); - } - function log2(message2, site) { - var haslisteners = eehaslisteners(process, "deprecation"); - if (!haslisteners && this._ignored) { - return; - } - var caller; - var callFile; - var callSite; - var depSite; - var i5 = 0; - var seen = false; - var stack = getStack(); - var file2 = this._file; - if (site) { - depSite = site; - callSite = callSiteLocation(stack[1]); - callSite.name = depSite.name; - file2 = callSite[0]; - } else { - i5 = 2; - depSite = callSiteLocation(stack[i5]); - callSite = depSite; - } - for (; i5 < stack.length; i5++) { - caller = callSiteLocation(stack[i5]); - callFile = caller[0]; - if (callFile === file2) { - seen = true; - } else if (callFile === this._file) { - file2 = this._file; - } else if (seen) { - break; - } - } - var key = caller ? depSite.join(":") + "__" + caller.join(":") : void 0; - if (key !== void 0 && key in this._warned) { - return; - } - this._warned[key] = true; - var msg = message2; - if (!msg) { - msg = callSite === depSite || !callSite.name ? defaultMessage(depSite) : defaultMessage(callSite); - } - if (haslisteners) { - var err = DeprecationError(this._namespace, msg, stack.slice(i5)); - process.emit("deprecation", err); - return; - } - var format2 = process.stderr.isTTY ? formatColor : formatPlain; - var output = format2.call(this, msg, caller, stack.slice(i5)); - process.stderr.write(output + "\n", "utf8"); - } - function callSiteLocation(callSite) { - var file2 = callSite.getFileName() || ""; - var line3 = callSite.getLineNumber(); - var colm = callSite.getColumnNumber(); - if (callSite.isEval()) { - file2 = callSite.getEvalOrigin() + ", " + file2; - } - var site = [file2, line3, colm]; - site.callSite = callSite; - site.name = callSite.getFunctionName(); - return site; - } - function defaultMessage(site) { - var callSite = site.callSite; - var funcName = site.name; - if (!funcName) { - funcName = ""; - } - var context = callSite.getThis(); - var typeName = context && callSite.getTypeName(); - if (typeName === "Object") { - typeName = void 0; - } - if (typeName === "Function") { - typeName = context.name || typeName; - } - return typeName && callSite.getMethodName() ? typeName + "." + funcName : funcName; - } - function formatPlain(msg, caller, stack) { - var timestamp2 = (/* @__PURE__ */ new Date()).toUTCString(); - var formatted = timestamp2 + " " + this._namespace + " deprecated " + msg; - if (this._traced) { - for (var i5 = 0; i5 < stack.length; i5++) { - formatted += "\n at " + stack[i5].toString(); - } - return formatted; - } - if (caller) { - formatted += " at " + formatLocation(caller); - } - return formatted; - } - function formatColor(msg, caller, stack) { - var formatted = "\x1B[36;1m" + this._namespace + "\x1B[22;39m \x1B[33;1mdeprecated\x1B[22;39m \x1B[0m" + msg + "\x1B[39m"; - if (this._traced) { - for (var i5 = 0; i5 < stack.length; i5++) { - formatted += "\n \x1B[36mat " + stack[i5].toString() + "\x1B[39m"; - } - return formatted; - } - if (caller) { - formatted += " \x1B[36m" + formatLocation(caller) + "\x1B[39m"; - } - return formatted; - } - function formatLocation(callSite) { - return relative3(basePath, callSite[0]) + ":" + callSite[1] + ":" + callSite[2]; - } - function getStack() { - var limit = Error.stackTraceLimit; - var obj = {}; - var prep = Error.prepareStackTrace; - Error.prepareStackTrace = prepareObjectStackTrace; - Error.stackTraceLimit = Math.max(10, limit); - Error.captureStackTrace(obj); - var stack = obj.stack.slice(1); - Error.prepareStackTrace = prep; - Error.stackTraceLimit = limit; - return stack; - } - function prepareObjectStackTrace(obj, stack) { - return stack; - } - function wrapfunction(fn, message2) { - if (typeof fn !== "function") { - throw new TypeError("argument fn must be a function"); - } - var args = createArgumentsString(fn.length); - var stack = getStack(); - var site = callSiteLocation(stack[1]); - site.name = fn.name; - var deprecatedfn = new Function( - "fn", - "log", - "deprecate", - "message", - "site", - '"use strict"\nreturn function (' + args + ") {log.call(deprecate, message, site)\nreturn fn.apply(this, arguments)\n}" - )(fn, log2, this, message2, site); - return deprecatedfn; - } - function wrapproperty(obj, prop, message2) { - if (!obj || typeof obj !== "object" && typeof obj !== "function") { - throw new TypeError("argument obj must be object"); - } - var descriptor = Object.getOwnPropertyDescriptor(obj, prop); - if (!descriptor) { - throw new TypeError("must call property on owner object"); - } - if (!descriptor.configurable) { - throw new TypeError("property must be configurable"); - } - var deprecate2 = this; - var stack = getStack(); - var site = callSiteLocation(stack[1]); - site.name = prop; - if ("value" in descriptor) { - descriptor = convertDataDescriptorToAccessor(obj, prop, message2); - } - var get2 = descriptor.get; - var set2 = descriptor.set; - if (typeof get2 === "function") { - descriptor.get = function getter() { - log2.call(deprecate2, message2, site); - return get2.apply(this, arguments); - }; - } - if (typeof set2 === "function") { - descriptor.set = function setter() { - log2.call(deprecate2, message2, site); - return set2.apply(this, arguments); - }; - } - Object.defineProperty(obj, prop, descriptor); - } - function DeprecationError(namespace, message2, stack) { - var error50 = new Error(); - var stackString; - Object.defineProperty(error50, "constructor", { - value: DeprecationError - }); - Object.defineProperty(error50, "message", { - configurable: true, - enumerable: false, - value: message2, - writable: true - }); - Object.defineProperty(error50, "name", { - enumerable: false, - configurable: true, - value: "DeprecationError", - writable: true - }); - Object.defineProperty(error50, "namespace", { - configurable: true, - enumerable: false, - value: namespace, - writable: true - }); - Object.defineProperty(error50, "stack", { - configurable: true, - enumerable: false, - get: function() { - if (stackString !== void 0) { - return stackString; - } - return stackString = createStackString.call(this, stack); - }, - set: function setter(val) { - stackString = val; - } - }); - return error50; - } - } -}); - -// node_modules/.pnpm/setprototypeof@1.2.0/node_modules/setprototypeof/index.js -var require_setprototypeof = __commonJS({ - "node_modules/.pnpm/setprototypeof@1.2.0/node_modules/setprototypeof/index.js"(exports, module) { - "use strict"; - module.exports = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array ? setProtoOf : mixinProperties); - function setProtoOf(obj, proto) { - obj.__proto__ = proto; - return obj; - } - function mixinProperties(obj, proto) { - for (var prop in proto) { - if (!Object.prototype.hasOwnProperty.call(obj, prop)) { - obj[prop] = proto[prop]; - } - } - return obj; - } - } -}); - -// node_modules/.pnpm/statuses@2.0.2/node_modules/statuses/codes.json -var require_codes = __commonJS({ - "node_modules/.pnpm/statuses@2.0.2/node_modules/statuses/codes.json"(exports, module) { - module.exports = { - "100": "Continue", - "101": "Switching Protocols", - "102": "Processing", - "103": "Early Hints", - "200": "OK", - "201": "Created", - "202": "Accepted", - "203": "Non-Authoritative Information", - "204": "No Content", - "205": "Reset Content", - "206": "Partial Content", - "207": "Multi-Status", - "208": "Already Reported", - "226": "IM Used", - "300": "Multiple Choices", - "301": "Moved Permanently", - "302": "Found", - "303": "See Other", - "304": "Not Modified", - "305": "Use Proxy", - "307": "Temporary Redirect", - "308": "Permanent Redirect", - "400": "Bad Request", - "401": "Unauthorized", - "402": "Payment Required", - "403": "Forbidden", - "404": "Not Found", - "405": "Method Not Allowed", - "406": "Not Acceptable", - "407": "Proxy Authentication Required", - "408": "Request Timeout", - "409": "Conflict", - "410": "Gone", - "411": "Length Required", - "412": "Precondition Failed", - "413": "Payload Too Large", - "414": "URI Too Long", - "415": "Unsupported Media Type", - "416": "Range Not Satisfiable", - "417": "Expectation Failed", - "418": "I'm a Teapot", - "421": "Misdirected Request", - "422": "Unprocessable Entity", - "423": "Locked", - "424": "Failed Dependency", - "425": "Too Early", - "426": "Upgrade Required", - "428": "Precondition Required", - "429": "Too Many Requests", - "431": "Request Header Fields Too Large", - "451": "Unavailable For Legal Reasons", - "500": "Internal Server Error", - "501": "Not Implemented", - "502": "Bad Gateway", - "503": "Service Unavailable", - "504": "Gateway Timeout", - "505": "HTTP Version Not Supported", - "506": "Variant Also Negotiates", - "507": "Insufficient Storage", - "508": "Loop Detected", - "509": "Bandwidth Limit Exceeded", - "510": "Not Extended", - "511": "Network Authentication Required" - }; - } -}); - -// node_modules/.pnpm/statuses@2.0.2/node_modules/statuses/index.js -var require_statuses = __commonJS({ - "node_modules/.pnpm/statuses@2.0.2/node_modules/statuses/index.js"(exports, module) { - "use strict"; - var codes = require_codes(); - module.exports = status; - status.message = codes; - status.code = createMessageToStatusCodeMap(codes); - status.codes = createStatusCodeList(codes); - status.redirect = { - 300: true, - 301: true, - 302: true, - 303: true, - 305: true, - 307: true, - 308: true - }; - status.empty = { - 204: true, - 205: true, - 304: true - }; - status.retry = { - 502: true, - 503: true, - 504: true - }; - function createMessageToStatusCodeMap(codes2) { - var map4 = {}; - Object.keys(codes2).forEach(function forEachCode(code) { - var message2 = codes2[code]; - var status2 = Number(code); - map4[message2.toLowerCase()] = status2; - }); - return map4; - } - function createStatusCodeList(codes2) { - return Object.keys(codes2).map(function mapCode(code) { - return Number(code); - }); - } - function getStatusCode(message2) { - var msg = message2.toLowerCase(); - if (!Object.prototype.hasOwnProperty.call(status.code, msg)) { - throw new Error('invalid status message: "' + message2 + '"'); - } - return status.code[msg]; - } - function getStatusMessage(code) { - if (!Object.prototype.hasOwnProperty.call(status.message, code)) { - throw new Error("invalid status code: " + code); - } - return status.message[code]; - } - function status(code) { - if (typeof code === "number") { - return getStatusMessage(code); - } - if (typeof code !== "string") { - throw new TypeError("code must be a number or string"); - } - var n5 = parseInt(code, 10); - if (!isNaN(n5)) { - return getStatusMessage(n5); - } - return getStatusCode(code); - } - } -}); - -// node_modules/.pnpm/inherits@2.0.4/node_modules/inherits/inherits_browser.js -var require_inherits_browser = __commonJS({ - "node_modules/.pnpm/inherits@2.0.4/node_modules/inherits/inherits_browser.js"(exports, module) { - if (typeof Object.create === "function") { - module.exports = function inherits(ctor, superCtor) { - if (superCtor) { - ctor.super_ = superCtor; - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }); - } - }; - } else { - module.exports = function inherits(ctor, superCtor) { - if (superCtor) { - ctor.super_ = superCtor; - var TempCtor = function() { - }; - TempCtor.prototype = superCtor.prototype; - ctor.prototype = new TempCtor(); - ctor.prototype.constructor = ctor; - } - }; - } - } -}); - -// node_modules/.pnpm/inherits@2.0.4/node_modules/inherits/inherits.js -var require_inherits = __commonJS({ - "node_modules/.pnpm/inherits@2.0.4/node_modules/inherits/inherits.js"(exports, module) { - try { - util2 = __require("util"); - if (typeof util2.inherits !== "function") throw ""; - module.exports = util2.inherits; - } catch (e5) { - module.exports = require_inherits_browser(); - } - var util2; - } -}); - -// node_modules/.pnpm/toidentifier@1.0.1/node_modules/toidentifier/index.js -var require_toidentifier = __commonJS({ - "node_modules/.pnpm/toidentifier@1.0.1/node_modules/toidentifier/index.js"(exports, module) { - "use strict"; - module.exports = toIdentifier; - function toIdentifier(str) { - return str.split(" ").map(function(token) { - return token.slice(0, 1).toUpperCase() + token.slice(1); - }).join("").replace(/[^ _0-9a-z]/gi, ""); - } - } -}); - -// node_modules/.pnpm/http-errors@2.0.1/node_modules/http-errors/index.js -var require_http_errors = __commonJS({ - "node_modules/.pnpm/http-errors@2.0.1/node_modules/http-errors/index.js"(exports, module) { - "use strict"; - var deprecate2 = require_depd()("http-errors"); - var setPrototypeOf2 = require_setprototypeof(); - var statuses = require_statuses(); - var inherits = require_inherits(); - var toIdentifier = require_toidentifier(); - module.exports = createError; - module.exports.HttpError = createHttpErrorConstructor(); - module.exports.isHttpError = createIsHttpErrorFunction(module.exports.HttpError); - populateConstructorExports(module.exports, statuses.codes, module.exports.HttpError); - function codeClass(status) { - return Number(String(status).charAt(0) + "00"); - } - function createError() { - var err; - var msg; - var status = 500; - var props = {}; - for (var i5 = 0; i5 < arguments.length; i5++) { - var arg = arguments[i5]; - var type = typeof arg; - if (type === "object" && arg instanceof Error) { - err = arg; - status = err.status || err.statusCode || status; - } else if (type === "number" && i5 === 0) { - status = arg; - } else if (type === "string") { - msg = arg; - } else if (type === "object") { - props = arg; - } else { - throw new TypeError("argument #" + (i5 + 1) + " unsupported type " + type); - } - } - if (typeof status === "number" && (status < 400 || status >= 600)) { - deprecate2("non-error status code; use only 4xx or 5xx status codes"); - } - if (typeof status !== "number" || !statuses.message[status] && (status < 400 || status >= 600)) { - status = 500; - } - var HttpError2 = createError[status] || createError[codeClass(status)]; - if (!err) { - err = HttpError2 ? new HttpError2(msg) : new Error(msg || statuses.message[status]); - Error.captureStackTrace(err, createError); - } - if (!HttpError2 || !(err instanceof HttpError2) || err.status !== status) { - err.expose = status < 500; - err.status = err.statusCode = status; - } - for (var key in props) { - if (key !== "status" && key !== "statusCode") { - err[key] = props[key]; - } - } - return err; - } - function createHttpErrorConstructor() { - function HttpError2() { - throw new TypeError("cannot construct abstract class"); - } - inherits(HttpError2, Error); - return HttpError2; - } - function createClientErrorConstructor(HttpError2, name, code) { - var className = toClassName(name); - function ClientError(message2) { - var msg = message2 != null ? message2 : statuses.message[code]; - var err = new Error(msg); - Error.captureStackTrace(err, ClientError); - setPrototypeOf2(err, ClientError.prototype); - Object.defineProperty(err, "message", { - enumerable: true, - configurable: true, - value: msg, - writable: true - }); - Object.defineProperty(err, "name", { - enumerable: false, - configurable: true, - value: className, - writable: true - }); - return err; - } - inherits(ClientError, HttpError2); - nameFunc(ClientError, className); - ClientError.prototype.status = code; - ClientError.prototype.statusCode = code; - ClientError.prototype.expose = true; - return ClientError; - } - function createIsHttpErrorFunction(HttpError2) { - return function isHttpError(val) { - if (!val || typeof val !== "object") { - return false; - } - if (val instanceof HttpError2) { - return true; - } - return val instanceof Error && typeof val.expose === "boolean" && typeof val.statusCode === "number" && val.status === val.statusCode; - }; - } - function createServerErrorConstructor(HttpError2, name, code) { - var className = toClassName(name); - function ServerError(message2) { - var msg = message2 != null ? message2 : statuses.message[code]; - var err = new Error(msg); - Error.captureStackTrace(err, ServerError); - setPrototypeOf2(err, ServerError.prototype); - Object.defineProperty(err, "message", { - enumerable: true, - configurable: true, - value: msg, - writable: true - }); - Object.defineProperty(err, "name", { - enumerable: false, - configurable: true, - value: className, - writable: true - }); - return err; - } - inherits(ServerError, HttpError2); - nameFunc(ServerError, className); - ServerError.prototype.status = code; - ServerError.prototype.statusCode = code; - ServerError.prototype.expose = false; - return ServerError; - } - function nameFunc(func, name) { - var desc3 = Object.getOwnPropertyDescriptor(func, "name"); - if (desc3 && desc3.configurable) { - desc3.value = name; - Object.defineProperty(func, "name", desc3); - } - } - function populateConstructorExports(exports2, codes, HttpError2) { - codes.forEach(function forEachCode(code) { - var CodeError; - var name = toIdentifier(statuses.message[code]); - switch (codeClass(code)) { - case 400: - CodeError = createClientErrorConstructor(HttpError2, name, code); - break; - case 500: - CodeError = createServerErrorConstructor(HttpError2, name, code); - break; - } - if (CodeError) { - exports2[code] = CodeError; - exports2[name] = CodeError; - } - }); - } - function toClassName(name) { - return name.slice(-5) === "Error" ? name : name + "Error"; - } - } -}); - -// node_modules/.pnpm/bytes@3.1.2/node_modules/bytes/index.js -var require_bytes = __commonJS({ - "node_modules/.pnpm/bytes@3.1.2/node_modules/bytes/index.js"(exports, module) { - "use strict"; - module.exports = bytes; - module.exports.format = format2; - module.exports.parse = parse5; - var formatThousandsRegExp = /\B(?=(\d{3})+(?!\d))/g; - var formatDecimalsRegExp = /(?:\.0*|(\.[^0]+)0+)$/; - var map4 = { - b: 1, - kb: 1 << 10, - mb: 1 << 20, - gb: 1 << 30, - tb: Math.pow(1024, 4), - pb: Math.pow(1024, 5) - }; - var parseRegExp = /^((-|\+)?(\d+(?:\.\d+)?)) *(kb|mb|gb|tb|pb)$/i; - function bytes(value, options) { - if (typeof value === "string") { - return parse5(value); - } - if (typeof value === "number") { - return format2(value, options); - } - return null; - } - function format2(value, options) { - if (!Number.isFinite(value)) { - return null; - } - var mag = Math.abs(value); - var thousandsSeparator = options && options.thousandsSeparator || ""; - var unitSeparator = options && options.unitSeparator || ""; - var decimalPlaces = options && options.decimalPlaces !== void 0 ? options.decimalPlaces : 2; - var fixedDecimals = Boolean(options && options.fixedDecimals); - var unit = options && options.unit || ""; - if (!unit || !map4[unit.toLowerCase()]) { - if (mag >= map4.pb) { - unit = "PB"; - } else if (mag >= map4.tb) { - unit = "TB"; - } else if (mag >= map4.gb) { - unit = "GB"; - } else if (mag >= map4.mb) { - unit = "MB"; - } else if (mag >= map4.kb) { - unit = "KB"; - } else { - unit = "B"; - } - } - var val = value / map4[unit.toLowerCase()]; - var str = val.toFixed(decimalPlaces); - if (!fixedDecimals) { - str = str.replace(formatDecimalsRegExp, "$1"); - } - if (thousandsSeparator) { - str = str.split(".").map(function(s5, i5) { - return i5 === 0 ? s5.replace(formatThousandsRegExp, thousandsSeparator) : s5; - }).join("."); - } - return str + unitSeparator + unit; - } - function parse5(val) { - if (typeof val === "number" && !isNaN(val)) { - return val; - } - if (typeof val !== "string") { - return null; - } - var results = parseRegExp.exec(val); - var floatValue; - var unit = "b"; - if (!results) { - floatValue = parseInt(val, 10); - unit = "b"; - } else { - floatValue = parseFloat(results[1]); - unit = results[4].toLowerCase(); - } - if (isNaN(floatValue)) { - return null; - } - return Math.floor(map4[unit] * floatValue); - } - } -}); - -// node_modules/.pnpm/safer-buffer@2.1.2/node_modules/safer-buffer/safer.js -var require_safer = __commonJS({ - "node_modules/.pnpm/safer-buffer@2.1.2/node_modules/safer-buffer/safer.js"(exports, module) { - "use strict"; - var buffer2 = __require("buffer"); - var Buffer2 = buffer2.Buffer; - var safer = {}; - var key; - for (key in buffer2) { - if (!buffer2.hasOwnProperty(key)) continue; - if (key === "SlowBuffer" || key === "Buffer") continue; - safer[key] = buffer2[key]; - } - var Safer = safer.Buffer = {}; - for (key in Buffer2) { - if (!Buffer2.hasOwnProperty(key)) continue; - if (key === "allocUnsafe" || key === "allocUnsafeSlow") continue; - Safer[key] = Buffer2[key]; - } - safer.Buffer.prototype = Buffer2.prototype; - if (!Safer.from || Safer.from === Uint8Array.from) { - Safer.from = function(value, encodingOrOffset, length) { - if (typeof value === "number") { - throw new TypeError('The "value" argument must not be of type number. Received type ' + typeof value); - } - if (value && typeof value.length === "undefined") { - throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value); - } - return Buffer2(value, encodingOrOffset, length); - }; - } - if (!Safer.alloc) { - Safer.alloc = function(size2, fill, encoding) { - if (typeof size2 !== "number") { - throw new TypeError('The "size" argument must be of type number. Received type ' + typeof size2); - } - if (size2 < 0 || size2 >= 2 * (1 << 30)) { - throw new RangeError('The value "' + size2 + '" is invalid for option "size"'); - } - var buf = Buffer2(size2); - if (!fill || fill.length === 0) { - buf.fill(0); - } else if (typeof encoding === "string") { - buf.fill(fill, encoding); - } else { - buf.fill(fill); - } - return buf; - }; - } - if (!safer.kStringMaxLength) { - try { - safer.kStringMaxLength = process.binding("buffer").kStringMaxLength; - } catch (e5) { - } - } - if (!safer.constants) { - safer.constants = { - MAX_LENGTH: safer.kMaxLength - }; - if (safer.kStringMaxLength) { - safer.constants.MAX_STRING_LENGTH = safer.kStringMaxLength; - } - } - module.exports = safer; - } -}); - -// node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/lib/bom-handling.js -var require_bom_handling = __commonJS({ - "node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/lib/bom-handling.js"(exports) { - "use strict"; - var BOMChar = "\uFEFF"; - exports.PrependBOM = PrependBOMWrapper; - function PrependBOMWrapper(encoder3, options) { - this.encoder = encoder3; - this.addBOM = true; - } - PrependBOMWrapper.prototype.write = function(str) { - if (this.addBOM) { - str = BOMChar + str; - this.addBOM = false; - } - return this.encoder.write(str); - }; - PrependBOMWrapper.prototype.end = function() { - return this.encoder.end(); - }; - exports.StripBOM = StripBOMWrapper; - function StripBOMWrapper(decoder2, options) { - this.decoder = decoder2; - this.pass = false; - this.options = options || {}; - } - StripBOMWrapper.prototype.write = function(buf) { - var res = this.decoder.write(buf); - if (this.pass || !res) { - return res; - } - if (res[0] === BOMChar) { - res = res.slice(1); - if (typeof this.options.stripBOM === "function") { - this.options.stripBOM(); - } - } - this.pass = true; - return res; - }; - StripBOMWrapper.prototype.end = function() { - return this.decoder.end(); - }; - } -}); - -// node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/lib/helpers/merge-exports.js -var require_merge_exports = __commonJS({ - "node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/lib/helpers/merge-exports.js"(exports, module) { - "use strict"; - var hasOwn = typeof Object.hasOwn === "undefined" ? Function.call.bind(Object.prototype.hasOwnProperty) : Object.hasOwn; - function mergeModules(target, module2) { - for (var key in module2) { - if (hasOwn(module2, key)) { - target[key] = module2[key]; - } - } - } - module.exports = mergeModules; - } -}); - -// node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/encodings/internal.js -var require_internal = __commonJS({ - "node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/encodings/internal.js"(exports, module) { - "use strict"; - var Buffer2 = require_safer().Buffer; - module.exports = { - // Encodings - utf8: { type: "_internal", bomAware: true }, - cesu8: { type: "_internal", bomAware: true }, - unicode11utf8: "utf8", - ucs2: { type: "_internal", bomAware: true }, - utf16le: "ucs2", - binary: { type: "_internal" }, - base64: { type: "_internal" }, - hex: { type: "_internal" }, - // Codec. - _internal: InternalCodec - }; - function InternalCodec(codecOptions, iconv) { - this.enc = codecOptions.encodingName; - this.bomAware = codecOptions.bomAware; - if (this.enc === "base64") { - this.encoder = InternalEncoderBase64; - } else if (this.enc === "utf8") { - this.encoder = InternalEncoderUtf8; - } else if (this.enc === "cesu8") { - this.enc = "utf8"; - this.encoder = InternalEncoderCesu8; - if (Buffer2.from("eda0bdedb2a9", "hex").toString() !== "\u{1F4A9}") { - this.decoder = InternalDecoderCesu8; - this.defaultCharUnicode = iconv.defaultCharUnicode; - } - } - } - InternalCodec.prototype.encoder = InternalEncoder; - InternalCodec.prototype.decoder = InternalDecoder; - var StringDecoder = __require("string_decoder").StringDecoder; - function InternalDecoder(options, codec2) { - this.decoder = new StringDecoder(codec2.enc); - } - InternalDecoder.prototype.write = function(buf) { - if (!Buffer2.isBuffer(buf)) { - buf = Buffer2.from(buf); - } - return this.decoder.write(buf); - }; - InternalDecoder.prototype.end = function() { - return this.decoder.end(); - }; - function InternalEncoder(options, codec2) { - this.enc = codec2.enc; - } - InternalEncoder.prototype.write = function(str) { - return Buffer2.from(str, this.enc); - }; - InternalEncoder.prototype.end = function() { - }; - function InternalEncoderBase64(options, codec2) { - this.prevStr = ""; - } - InternalEncoderBase64.prototype.write = function(str) { - str = this.prevStr + str; - var completeQuads = str.length - str.length % 4; - this.prevStr = str.slice(completeQuads); - str = str.slice(0, completeQuads); - return Buffer2.from(str, "base64"); - }; - InternalEncoderBase64.prototype.end = function() { - return Buffer2.from(this.prevStr, "base64"); - }; - function InternalEncoderCesu8(options, codec2) { - } - InternalEncoderCesu8.prototype.write = function(str) { - var buf = Buffer2.alloc(str.length * 3); - var bufIdx = 0; - for (var i5 = 0; i5 < str.length; i5++) { - var charCode = str.charCodeAt(i5); - if (charCode < 128) { - buf[bufIdx++] = charCode; - } else if (charCode < 2048) { - buf[bufIdx++] = 192 + (charCode >>> 6); - buf[bufIdx++] = 128 + (charCode & 63); - } else { - buf[bufIdx++] = 224 + (charCode >>> 12); - buf[bufIdx++] = 128 + (charCode >>> 6 & 63); - buf[bufIdx++] = 128 + (charCode & 63); - } - } - return buf.slice(0, bufIdx); - }; - InternalEncoderCesu8.prototype.end = function() { - }; - function InternalDecoderCesu8(options, codec2) { - this.acc = 0; - this.contBytes = 0; - this.accBytes = 0; - this.defaultCharUnicode = codec2.defaultCharUnicode; - } - InternalDecoderCesu8.prototype.write = function(buf) { - var acc = this.acc; - var contBytes = this.contBytes; - var accBytes = this.accBytes; - var res = ""; - for (var i5 = 0; i5 < buf.length; i5++) { - var curByte = buf[i5]; - if ((curByte & 192) !== 128) { - if (contBytes > 0) { - res += this.defaultCharUnicode; - contBytes = 0; - } - if (curByte < 128) { - res += String.fromCharCode(curByte); - } else if (curByte < 224) { - acc = curByte & 31; - contBytes = 1; - accBytes = 1; - } else if (curByte < 240) { - acc = curByte & 15; - contBytes = 2; - accBytes = 1; - } else { - res += this.defaultCharUnicode; - } - } else { - if (contBytes > 0) { - acc = acc << 6 | curByte & 63; - contBytes--; - accBytes++; - if (contBytes === 0) { - if (accBytes === 2 && acc < 128 && acc > 0) { - res += this.defaultCharUnicode; - } else if (accBytes === 3 && acc < 2048) { - res += this.defaultCharUnicode; - } else { - res += String.fromCharCode(acc); - } - } - } else { - res += this.defaultCharUnicode; - } - } - } - this.acc = acc; - this.contBytes = contBytes; - this.accBytes = accBytes; - return res; - }; - InternalDecoderCesu8.prototype.end = function() { - var res = 0; - if (this.contBytes > 0) { - res += this.defaultCharUnicode; - } - return res; - }; - function InternalEncoderUtf8(options, codec2) { - this.highSurrogate = ""; - } - InternalEncoderUtf8.prototype.write = function(str) { - if (this.highSurrogate) { - str = this.highSurrogate + str; - this.highSurrogate = ""; - } - if (str.length > 0) { - var charCode = str.charCodeAt(str.length - 1); - if (charCode >= 55296 && charCode < 56320) { - this.highSurrogate = str[str.length - 1]; - str = str.slice(0, str.length - 1); - } - } - return Buffer2.from(str, this.enc); - }; - InternalEncoderUtf8.prototype.end = function() { - if (this.highSurrogate) { - var str = this.highSurrogate; - this.highSurrogate = ""; - return Buffer2.from(str, this.enc); - } - }; - } -}); - -// node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/encodings/utf32.js -var require_utf32 = __commonJS({ - "node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/encodings/utf32.js"(exports) { - "use strict"; - var Buffer2 = require_safer().Buffer; - exports._utf32 = Utf32Codec; - function Utf32Codec(codecOptions, iconv) { - this.iconv = iconv; - this.bomAware = true; - this.isLE = codecOptions.isLE; - } - exports.utf32le = { type: "_utf32", isLE: true }; - exports.utf32be = { type: "_utf32", isLE: false }; - exports.ucs4le = "utf32le"; - exports.ucs4be = "utf32be"; - Utf32Codec.prototype.encoder = Utf32Encoder; - Utf32Codec.prototype.decoder = Utf32Decoder; - function Utf32Encoder(options, codec2) { - this.isLE = codec2.isLE; - this.highSurrogate = 0; - } - Utf32Encoder.prototype.write = function(str) { - var src = Buffer2.from(str, "ucs2"); - var dst = Buffer2.alloc(src.length * 2); - var write32 = this.isLE ? dst.writeUInt32LE : dst.writeUInt32BE; - var offset = 0; - for (var i5 = 0; i5 < src.length; i5 += 2) { - var code = src.readUInt16LE(i5); - var isHighSurrogate = code >= 55296 && code < 56320; - var isLowSurrogate = code >= 56320 && code < 57344; - if (this.highSurrogate) { - if (isHighSurrogate || !isLowSurrogate) { - write32.call(dst, this.highSurrogate, offset); - offset += 4; - } else { - var codepoint = (this.highSurrogate - 55296 << 10 | code - 56320) + 65536; - write32.call(dst, codepoint, offset); - offset += 4; - this.highSurrogate = 0; - continue; - } - } - if (isHighSurrogate) { - this.highSurrogate = code; - } else { - write32.call(dst, code, offset); - offset += 4; - this.highSurrogate = 0; - } - } - if (offset < dst.length) { - dst = dst.slice(0, offset); - } - return dst; - }; - Utf32Encoder.prototype.end = function() { - if (!this.highSurrogate) { - return; - } - var buf = Buffer2.alloc(4); - if (this.isLE) { - buf.writeUInt32LE(this.highSurrogate, 0); - } else { - buf.writeUInt32BE(this.highSurrogate, 0); - } - this.highSurrogate = 0; - return buf; - }; - function Utf32Decoder(options, codec2) { - this.isLE = codec2.isLE; - this.badChar = codec2.iconv.defaultCharUnicode.charCodeAt(0); - this.overflow = []; - } - Utf32Decoder.prototype.write = function(src) { - if (src.length === 0) { - return ""; - } - var i5 = 0; - var codepoint = 0; - var dst = Buffer2.alloc(src.length + 4); - var offset = 0; - var isLE3 = this.isLE; - var overflow = this.overflow; - var badChar = this.badChar; - if (overflow.length > 0) { - for (; i5 < src.length && overflow.length < 4; i5++) { - overflow.push(src[i5]); - } - if (overflow.length === 4) { - if (isLE3) { - codepoint = overflow[i5] | overflow[i5 + 1] << 8 | overflow[i5 + 2] << 16 | overflow[i5 + 3] << 24; - } else { - codepoint = overflow[i5 + 3] | overflow[i5 + 2] << 8 | overflow[i5 + 1] << 16 | overflow[i5] << 24; - } - overflow.length = 0; - offset = _writeCodepoint(dst, offset, codepoint, badChar); - } - } - for (; i5 < src.length - 3; i5 += 4) { - if (isLE3) { - codepoint = src[i5] | src[i5 + 1] << 8 | src[i5 + 2] << 16 | src[i5 + 3] << 24; - } else { - codepoint = src[i5 + 3] | src[i5 + 2] << 8 | src[i5 + 1] << 16 | src[i5] << 24; - } - offset = _writeCodepoint(dst, offset, codepoint, badChar); - } - for (; i5 < src.length; i5++) { - overflow.push(src[i5]); - } - return dst.slice(0, offset).toString("ucs2"); - }; - function _writeCodepoint(dst, offset, codepoint, badChar) { - if (codepoint < 0 || codepoint > 1114111) { - codepoint = badChar; - } - if (codepoint >= 65536) { - codepoint -= 65536; - var high = 55296 | codepoint >> 10; - dst[offset++] = high & 255; - dst[offset++] = high >> 8; - var codepoint = 56320 | codepoint & 1023; - } - dst[offset++] = codepoint & 255; - dst[offset++] = codepoint >> 8; - return offset; - } - Utf32Decoder.prototype.end = function() { - this.overflow.length = 0; - }; - exports.utf32 = Utf32AutoCodec; - exports.ucs4 = "utf32"; - function Utf32AutoCodec(options, iconv) { - this.iconv = iconv; - } - Utf32AutoCodec.prototype.encoder = Utf32AutoEncoder; - Utf32AutoCodec.prototype.decoder = Utf32AutoDecoder; - function Utf32AutoEncoder(options, codec2) { - options = options || {}; - if (options.addBOM === void 0) { - options.addBOM = true; - } - this.encoder = codec2.iconv.getEncoder(options.defaultEncoding || "utf-32le", options); - } - Utf32AutoEncoder.prototype.write = function(str) { - return this.encoder.write(str); - }; - Utf32AutoEncoder.prototype.end = function() { - return this.encoder.end(); - }; - function Utf32AutoDecoder(options, codec2) { - this.decoder = null; - this.initialBufs = []; - this.initialBufsLen = 0; - this.options = options || {}; - this.iconv = codec2.iconv; - } - Utf32AutoDecoder.prototype.write = function(buf) { - if (!this.decoder) { - this.initialBufs.push(buf); - this.initialBufsLen += buf.length; - if (this.initialBufsLen < 32) { - return ""; - } - var encoding = detectEncoding(this.initialBufs, this.options.defaultEncoding); - this.decoder = this.iconv.getDecoder(encoding, this.options); - var resStr = ""; - for (var i5 = 0; i5 < this.initialBufs.length; i5++) { - resStr += this.decoder.write(this.initialBufs[i5]); - } - this.initialBufs.length = this.initialBufsLen = 0; - return resStr; - } - return this.decoder.write(buf); - }; - Utf32AutoDecoder.prototype.end = function() { - if (!this.decoder) { - var encoding = detectEncoding(this.initialBufs, this.options.defaultEncoding); - this.decoder = this.iconv.getDecoder(encoding, this.options); - var resStr = ""; - for (var i5 = 0; i5 < this.initialBufs.length; i5++) { - resStr += this.decoder.write(this.initialBufs[i5]); - } - var trail = this.decoder.end(); - if (trail) { - resStr += trail; - } - this.initialBufs.length = this.initialBufsLen = 0; - return resStr; - } - return this.decoder.end(); - }; - function detectEncoding(bufs, defaultEncoding) { - var b6 = []; - var charsProcessed = 0; - var invalidLE = 0; - var invalidBE = 0; - var bmpCharsLE = 0; - var bmpCharsBE = 0; - outerLoop: - for (var i5 = 0; i5 < bufs.length; i5++) { - var buf = bufs[i5]; - for (var j5 = 0; j5 < buf.length; j5++) { - b6.push(buf[j5]); - if (b6.length === 4) { - if (charsProcessed === 0) { - if (b6[0] === 255 && b6[1] === 254 && b6[2] === 0 && b6[3] === 0) { - return "utf-32le"; - } - if (b6[0] === 0 && b6[1] === 0 && b6[2] === 254 && b6[3] === 255) { - return "utf-32be"; - } - } - if (b6[0] !== 0 || b6[1] > 16) invalidBE++; - if (b6[3] !== 0 || b6[2] > 16) invalidLE++; - if (b6[0] === 0 && b6[1] === 0 && (b6[2] !== 0 || b6[3] !== 0)) bmpCharsBE++; - if ((b6[0] !== 0 || b6[1] !== 0) && b6[2] === 0 && b6[3] === 0) bmpCharsLE++; - b6.length = 0; - charsProcessed++; - if (charsProcessed >= 100) { - break outerLoop; - } - } - } - } - if (bmpCharsBE - invalidBE > bmpCharsLE - invalidLE) return "utf-32be"; - if (bmpCharsBE - invalidBE < bmpCharsLE - invalidLE) return "utf-32le"; - return defaultEncoding || "utf-32le"; - } - } -}); - -// node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/encodings/utf16.js -var require_utf16 = __commonJS({ - "node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/encodings/utf16.js"(exports) { - "use strict"; - var Buffer2 = require_safer().Buffer; - exports.utf16be = Utf16BECodec; - function Utf16BECodec() { - } - Utf16BECodec.prototype.encoder = Utf16BEEncoder; - Utf16BECodec.prototype.decoder = Utf16BEDecoder; - Utf16BECodec.prototype.bomAware = true; - function Utf16BEEncoder() { - } - Utf16BEEncoder.prototype.write = function(str) { - var buf = Buffer2.from(str, "ucs2"); - for (var i5 = 0; i5 < buf.length; i5 += 2) { - var tmp = buf[i5]; - buf[i5] = buf[i5 + 1]; - buf[i5 + 1] = tmp; - } - return buf; - }; - Utf16BEEncoder.prototype.end = function() { - }; - function Utf16BEDecoder() { - this.overflowByte = -1; - } - Utf16BEDecoder.prototype.write = function(buf) { - if (buf.length == 0) { - return ""; - } - var buf2 = Buffer2.alloc(buf.length + 1); - var i5 = 0; - var j5 = 0; - if (this.overflowByte !== -1) { - buf2[0] = buf[0]; - buf2[1] = this.overflowByte; - i5 = 1; - j5 = 2; - } - for (; i5 < buf.length - 1; i5 += 2, j5 += 2) { - buf2[j5] = buf[i5 + 1]; - buf2[j5 + 1] = buf[i5]; - } - this.overflowByte = i5 == buf.length - 1 ? buf[buf.length - 1] : -1; - return buf2.slice(0, j5).toString("ucs2"); - }; - Utf16BEDecoder.prototype.end = function() { - this.overflowByte = -1; - }; - exports.utf16 = Utf16Codec; - function Utf16Codec(codecOptions, iconv) { - this.iconv = iconv; - } - Utf16Codec.prototype.encoder = Utf16Encoder; - Utf16Codec.prototype.decoder = Utf16Decoder; - function Utf16Encoder(options, codec2) { - options = options || {}; - if (options.addBOM === void 0) { - options.addBOM = true; - } - this.encoder = codec2.iconv.getEncoder("utf-16le", options); - } - Utf16Encoder.prototype.write = function(str) { - return this.encoder.write(str); - }; - Utf16Encoder.prototype.end = function() { - return this.encoder.end(); - }; - function Utf16Decoder(options, codec2) { - this.decoder = null; - this.initialBufs = []; - this.initialBufsLen = 0; - this.options = options || {}; - this.iconv = codec2.iconv; - } - Utf16Decoder.prototype.write = function(buf) { - if (!this.decoder) { - this.initialBufs.push(buf); - this.initialBufsLen += buf.length; - if (this.initialBufsLen < 16) { - return ""; - } - var encoding = detectEncoding(this.initialBufs, this.options.defaultEncoding); - this.decoder = this.iconv.getDecoder(encoding, this.options); - var resStr = ""; - for (var i5 = 0; i5 < this.initialBufs.length; i5++) { - resStr += this.decoder.write(this.initialBufs[i5]); - } - this.initialBufs.length = this.initialBufsLen = 0; - return resStr; - } - return this.decoder.write(buf); - }; - Utf16Decoder.prototype.end = function() { - if (!this.decoder) { - var encoding = detectEncoding(this.initialBufs, this.options.defaultEncoding); - this.decoder = this.iconv.getDecoder(encoding, this.options); - var resStr = ""; - for (var i5 = 0; i5 < this.initialBufs.length; i5++) { - resStr += this.decoder.write(this.initialBufs[i5]); - } - var trail = this.decoder.end(); - if (trail) { - resStr += trail; - } - this.initialBufs.length = this.initialBufsLen = 0; - return resStr; - } - return this.decoder.end(); - }; - function detectEncoding(bufs, defaultEncoding) { - var b6 = []; - var charsProcessed = 0; - var asciiCharsLE = 0; - var asciiCharsBE = 0; - outerLoop: - for (var i5 = 0; i5 < bufs.length; i5++) { - var buf = bufs[i5]; - for (var j5 = 0; j5 < buf.length; j5++) { - b6.push(buf[j5]); - if (b6.length === 2) { - if (charsProcessed === 0) { - if (b6[0] === 255 && b6[1] === 254) return "utf-16le"; - if (b6[0] === 254 && b6[1] === 255) return "utf-16be"; - } - if (b6[0] === 0 && b6[1] !== 0) asciiCharsBE++; - if (b6[0] !== 0 && b6[1] === 0) asciiCharsLE++; - b6.length = 0; - charsProcessed++; - if (charsProcessed >= 100) { - break outerLoop; - } - } - } - } - if (asciiCharsBE > asciiCharsLE) return "utf-16be"; - if (asciiCharsBE < asciiCharsLE) return "utf-16le"; - return defaultEncoding || "utf-16le"; - } - } -}); - -// node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/encodings/utf7.js -var require_utf7 = __commonJS({ - "node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/encodings/utf7.js"(exports) { - "use strict"; - var Buffer2 = require_safer().Buffer; - exports.utf7 = Utf7Codec; - exports.unicode11utf7 = "utf7"; - function Utf7Codec(codecOptions, iconv) { - this.iconv = iconv; - } - Utf7Codec.prototype.encoder = Utf7Encoder; - Utf7Codec.prototype.decoder = Utf7Decoder; - Utf7Codec.prototype.bomAware = true; - var nonDirectChars = /[^A-Za-z0-9'\(\),-\.\/:\? \n\r\t]+/g; - function Utf7Encoder(options, codec2) { - this.iconv = codec2.iconv; - } - Utf7Encoder.prototype.write = function(str) { - return Buffer2.from(str.replace(nonDirectChars, function(chunk) { - return "+" + (chunk === "+" ? "" : this.iconv.encode(chunk, "utf16-be").toString("base64").replace(/=+$/, "")) + "-"; - }.bind(this))); - }; - Utf7Encoder.prototype.end = function() { - }; - function Utf7Decoder(options, codec2) { - this.iconv = codec2.iconv; - this.inBase64 = false; - this.base64Accum = ""; - } - var base64Regex2 = /[A-Za-z0-9\/+]/; - var base64Chars = []; - for (i5 = 0; i5 < 256; i5++) { - base64Chars[i5] = base64Regex2.test(String.fromCharCode(i5)); - } - var i5; - var plusChar = "+".charCodeAt(0); - var minusChar = "-".charCodeAt(0); - var andChar = "&".charCodeAt(0); - Utf7Decoder.prototype.write = function(buf) { - var res = ""; - var lastI = 0; - var inBase64 = this.inBase64; - var base64Accum = this.base64Accum; - for (var i6 = 0; i6 < buf.length; i6++) { - if (!inBase64) { - if (buf[i6] == plusChar) { - res += this.iconv.decode(buf.slice(lastI, i6), "ascii"); - lastI = i6 + 1; - inBase64 = true; - } - } else { - if (!base64Chars[buf[i6]]) { - if (i6 == lastI && buf[i6] == minusChar) { - res += "+"; - } else { - var b64str = base64Accum + this.iconv.decode(buf.slice(lastI, i6), "ascii"); - res += this.iconv.decode(Buffer2.from(b64str, "base64"), "utf16-be"); - } - if (buf[i6] != minusChar) { - i6--; - } - lastI = i6 + 1; - inBase64 = false; - base64Accum = ""; - } - } - } - if (!inBase64) { - res += this.iconv.decode(buf.slice(lastI), "ascii"); - } else { - var b64str = base64Accum + this.iconv.decode(buf.slice(lastI), "ascii"); - var canBeDecoded = b64str.length - b64str.length % 8; - base64Accum = b64str.slice(canBeDecoded); - b64str = b64str.slice(0, canBeDecoded); - res += this.iconv.decode(Buffer2.from(b64str, "base64"), "utf16-be"); - } - this.inBase64 = inBase64; - this.base64Accum = base64Accum; - return res; - }; - Utf7Decoder.prototype.end = function() { - var res = ""; - if (this.inBase64 && this.base64Accum.length > 0) { - res = this.iconv.decode(Buffer2.from(this.base64Accum, "base64"), "utf16-be"); - } - this.inBase64 = false; - this.base64Accum = ""; - return res; - }; - exports.utf7imap = Utf7IMAPCodec; - function Utf7IMAPCodec(codecOptions, iconv) { - this.iconv = iconv; - } - Utf7IMAPCodec.prototype.encoder = Utf7IMAPEncoder; - Utf7IMAPCodec.prototype.decoder = Utf7IMAPDecoder; - Utf7IMAPCodec.prototype.bomAware = true; - function Utf7IMAPEncoder(options, codec2) { - this.iconv = codec2.iconv; - this.inBase64 = false; - this.base64Accum = Buffer2.alloc(6); - this.base64AccumIdx = 0; - } - Utf7IMAPEncoder.prototype.write = function(str) { - var inBase64 = this.inBase64; - var base64Accum = this.base64Accum; - var base64AccumIdx = this.base64AccumIdx; - var buf = Buffer2.alloc(str.length * 5 + 10); - var bufIdx = 0; - for (var i6 = 0; i6 < str.length; i6++) { - var uChar = str.charCodeAt(i6); - if (uChar >= 32 && uChar <= 126) { - if (inBase64) { - if (base64AccumIdx > 0) { - bufIdx += buf.write(base64Accum.slice(0, base64AccumIdx).toString("base64").replace(/\//g, ",").replace(/=+$/, ""), bufIdx); - base64AccumIdx = 0; - } - buf[bufIdx++] = minusChar; - inBase64 = false; - } - if (!inBase64) { - buf[bufIdx++] = uChar; - if (uChar === andChar) { - buf[bufIdx++] = minusChar; - } - } - } else { - if (!inBase64) { - buf[bufIdx++] = andChar; - inBase64 = true; - } - if (inBase64) { - base64Accum[base64AccumIdx++] = uChar >> 8; - base64Accum[base64AccumIdx++] = uChar & 255; - if (base64AccumIdx == base64Accum.length) { - bufIdx += buf.write(base64Accum.toString("base64").replace(/\//g, ","), bufIdx); - base64AccumIdx = 0; - } - } - } - } - this.inBase64 = inBase64; - this.base64AccumIdx = base64AccumIdx; - return buf.slice(0, bufIdx); - }; - Utf7IMAPEncoder.prototype.end = function() { - var buf = Buffer2.alloc(10); - var bufIdx = 0; - if (this.inBase64) { - if (this.base64AccumIdx > 0) { - bufIdx += buf.write(this.base64Accum.slice(0, this.base64AccumIdx).toString("base64").replace(/\//g, ",").replace(/=+$/, ""), bufIdx); - this.base64AccumIdx = 0; - } - buf[bufIdx++] = minusChar; - this.inBase64 = false; - } - return buf.slice(0, bufIdx); - }; - function Utf7IMAPDecoder(options, codec2) { - this.iconv = codec2.iconv; - this.inBase64 = false; - this.base64Accum = ""; - } - var base64IMAPChars = base64Chars.slice(); - base64IMAPChars[",".charCodeAt(0)] = true; - Utf7IMAPDecoder.prototype.write = function(buf) { - var res = ""; - var lastI = 0; - var inBase64 = this.inBase64; - var base64Accum = this.base64Accum; - for (var i6 = 0; i6 < buf.length; i6++) { - if (!inBase64) { - if (buf[i6] == andChar) { - res += this.iconv.decode(buf.slice(lastI, i6), "ascii"); - lastI = i6 + 1; - inBase64 = true; - } - } else { - if (!base64IMAPChars[buf[i6]]) { - if (i6 == lastI && buf[i6] == minusChar) { - res += "&"; - } else { - var b64str = base64Accum + this.iconv.decode(buf.slice(lastI, i6), "ascii").replace(/,/g, "/"); - res += this.iconv.decode(Buffer2.from(b64str, "base64"), "utf16-be"); - } - if (buf[i6] != minusChar) { - i6--; - } - lastI = i6 + 1; - inBase64 = false; - base64Accum = ""; - } - } - } - if (!inBase64) { - res += this.iconv.decode(buf.slice(lastI), "ascii"); - } else { - var b64str = base64Accum + this.iconv.decode(buf.slice(lastI), "ascii").replace(/,/g, "/"); - var canBeDecoded = b64str.length - b64str.length % 8; - base64Accum = b64str.slice(canBeDecoded); - b64str = b64str.slice(0, canBeDecoded); - res += this.iconv.decode(Buffer2.from(b64str, "base64"), "utf16-be"); - } - this.inBase64 = inBase64; - this.base64Accum = base64Accum; - return res; - }; - Utf7IMAPDecoder.prototype.end = function() { - var res = ""; - if (this.inBase64 && this.base64Accum.length > 0) { - res = this.iconv.decode(Buffer2.from(this.base64Accum, "base64"), "utf16-be"); - } - this.inBase64 = false; - this.base64Accum = ""; - return res; - }; - } -}); - -// node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/encodings/sbcs-codec.js -var require_sbcs_codec = __commonJS({ - "node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/encodings/sbcs-codec.js"(exports) { - "use strict"; - var Buffer2 = require_safer().Buffer; - exports._sbcs = SBCSCodec; - function SBCSCodec(codecOptions, iconv) { - if (!codecOptions) { - throw new Error("SBCS codec is called without the data."); - } - if (!codecOptions.chars || codecOptions.chars.length !== 128 && codecOptions.chars.length !== 256) { - throw new Error("Encoding '" + codecOptions.type + "' has incorrect 'chars' (must be of len 128 or 256)"); - } - if (codecOptions.chars.length === 128) { - var asciiString = ""; - for (var i5 = 0; i5 < 128; i5++) { - asciiString += String.fromCharCode(i5); - } - codecOptions.chars = asciiString + codecOptions.chars; - } - this.decodeBuf = Buffer2.from(codecOptions.chars, "ucs2"); - var encodeBuf = Buffer2.alloc(65536, iconv.defaultCharSingleByte.charCodeAt(0)); - for (var i5 = 0; i5 < codecOptions.chars.length; i5++) { - encodeBuf[codecOptions.chars.charCodeAt(i5)] = i5; - } - this.encodeBuf = encodeBuf; - } - SBCSCodec.prototype.encoder = SBCSEncoder; - SBCSCodec.prototype.decoder = SBCSDecoder; - function SBCSEncoder(options, codec2) { - this.encodeBuf = codec2.encodeBuf; - } - SBCSEncoder.prototype.write = function(str) { - var buf = Buffer2.alloc(str.length); - for (var i5 = 0; i5 < str.length; i5++) { - buf[i5] = this.encodeBuf[str.charCodeAt(i5)]; - } - return buf; - }; - SBCSEncoder.prototype.end = function() { - }; - function SBCSDecoder(options, codec2) { - this.decodeBuf = codec2.decodeBuf; - } - SBCSDecoder.prototype.write = function(buf) { - var decodeBuf = this.decodeBuf; - var newBuf = Buffer2.alloc(buf.length * 2); - var idx1 = 0; - var idx2 = 0; - for (var i5 = 0; i5 < buf.length; i5++) { - idx1 = buf[i5] * 2; - idx2 = i5 * 2; - newBuf[idx2] = decodeBuf[idx1]; - newBuf[idx2 + 1] = decodeBuf[idx1 + 1]; - } - return newBuf.toString("ucs2"); - }; - SBCSDecoder.prototype.end = function() { - }; - } -}); - -// node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/encodings/sbcs-data.js -var require_sbcs_data = __commonJS({ - "node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/encodings/sbcs-data.js"(exports, module) { - "use strict"; - module.exports = { - // Not supported by iconv, not sure why. - 10029: "maccenteuro", - maccenteuro: { - type: "_sbcs", - chars: "\xC4\u0100\u0101\xC9\u0104\xD6\xDC\xE1\u0105\u010C\xE4\u010D\u0106\u0107\xE9\u0179\u017A\u010E\xED\u010F\u0112\u0113\u0116\xF3\u0117\xF4\xF6\xF5\xFA\u011A\u011B\xFC\u2020\xB0\u0118\xA3\xA7\u2022\xB6\xDF\xAE\xA9\u2122\u0119\xA8\u2260\u0123\u012E\u012F\u012A\u2264\u2265\u012B\u0136\u2202\u2211\u0142\u013B\u013C\u013D\u013E\u0139\u013A\u0145\u0146\u0143\xAC\u221A\u0144\u0147\u2206\xAB\xBB\u2026\xA0\u0148\u0150\xD5\u0151\u014C\u2013\u2014\u201C\u201D\u2018\u2019\xF7\u25CA\u014D\u0154\u0155\u0158\u2039\u203A\u0159\u0156\u0157\u0160\u201A\u201E\u0161\u015A\u015B\xC1\u0164\u0165\xCD\u017D\u017E\u016A\xD3\xD4\u016B\u016E\xDA\u016F\u0170\u0171\u0172\u0173\xDD\xFD\u0137\u017B\u0141\u017C\u0122\u02C7" - }, - 808: "cp808", - ibm808: "cp808", - cp808: { - type: "_sbcs", - chars: "\u0410\u0411\u0412\u0413\u0414\u0415\u0416\u0417\u0418\u0419\u041A\u041B\u041C\u041D\u041E\u041F\u0420\u0421\u0422\u0423\u0424\u0425\u0426\u0427\u0428\u0429\u042A\u042B\u042C\u042D\u042E\u042F\u0430\u0431\u0432\u0433\u0434\u0435\u0436\u0437\u0438\u0439\u043A\u043B\u043C\u043D\u043E\u043F\u2591\u2592\u2593\u2502\u2524\u2561\u2562\u2556\u2555\u2563\u2551\u2557\u255D\u255C\u255B\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u255E\u255F\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u2567\u2568\u2564\u2565\u2559\u2558\u2552\u2553\u256B\u256A\u2518\u250C\u2588\u2584\u258C\u2590\u2580\u0440\u0441\u0442\u0443\u0444\u0445\u0446\u0447\u0448\u0449\u044A\u044B\u044C\u044D\u044E\u044F\u0401\u0451\u0404\u0454\u0407\u0457\u040E\u045E\xB0\u2219\xB7\u221A\u2116\u20AC\u25A0\xA0" - }, - mik: { - type: "_sbcs", - chars: "\u0410\u0411\u0412\u0413\u0414\u0415\u0416\u0417\u0418\u0419\u041A\u041B\u041C\u041D\u041E\u041F\u0420\u0421\u0422\u0423\u0424\u0425\u0426\u0427\u0428\u0429\u042A\u042B\u042C\u042D\u042E\u042F\u0430\u0431\u0432\u0433\u0434\u0435\u0436\u0437\u0438\u0439\u043A\u043B\u043C\u043D\u043E\u043F\u0440\u0441\u0442\u0443\u0444\u0445\u0446\u0447\u0448\u0449\u044A\u044B\u044C\u044D\u044E\u044F\u2514\u2534\u252C\u251C\u2500\u253C\u2563\u2551\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u2510\u2591\u2592\u2593\u2502\u2524\u2116\xA7\u2557\u255D\u2518\u250C\u2588\u2584\u258C\u2590\u2580\u03B1\xDF\u0393\u03C0\u03A3\u03C3\xB5\u03C4\u03A6\u0398\u03A9\u03B4\u221E\u03C6\u03B5\u2229\u2261\xB1\u2265\u2264\u2320\u2321\xF7\u2248\xB0\u2219\xB7\u221A\u207F\xB2\u25A0\xA0" - }, - cp720: { - type: "_sbcs", - chars: "\x80\x81\xE9\xE2\x84\xE0\x86\xE7\xEA\xEB\xE8\xEF\xEE\x8D\x8E\x8F\x90\u0651\u0652\xF4\xA4\u0640\xFB\xF9\u0621\u0622\u0623\u0624\xA3\u0625\u0626\u0627\u0628\u0629\u062A\u062B\u062C\u062D\u062E\u062F\u0630\u0631\u0632\u0633\u0634\u0635\xAB\xBB\u2591\u2592\u2593\u2502\u2524\u2561\u2562\u2556\u2555\u2563\u2551\u2557\u255D\u255C\u255B\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u255E\u255F\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u2567\u2568\u2564\u2565\u2559\u2558\u2552\u2553\u256B\u256A\u2518\u250C\u2588\u2584\u258C\u2590\u2580\u0636\u0637\u0638\u0639\u063A\u0641\xB5\u0642\u0643\u0644\u0645\u0646\u0647\u0648\u0649\u064A\u2261\u064B\u064C\u064D\u064E\u064F\u0650\u2248\xB0\u2219\xB7\u221A\u207F\xB2\u25A0\xA0" - }, - // Aliases of generated encodings. - ascii8bit: "ascii", - usascii: "ascii", - ansix34: "ascii", - ansix341968: "ascii", - ansix341986: "ascii", - csascii: "ascii", - cp367: "ascii", - ibm367: "ascii", - isoir6: "ascii", - iso646us: "ascii", - iso646irv: "ascii", - us: "ascii", - latin1: "iso88591", - latin2: "iso88592", - latin3: "iso88593", - latin4: "iso88594", - latin5: "iso88599", - latin6: "iso885910", - latin7: "iso885913", - latin8: "iso885914", - latin9: "iso885915", - latin10: "iso885916", - csisolatin1: "iso88591", - csisolatin2: "iso88592", - csisolatin3: "iso88593", - csisolatin4: "iso88594", - csisolatincyrillic: "iso88595", - csisolatinarabic: "iso88596", - csisolatingreek: "iso88597", - csisolatinhebrew: "iso88598", - csisolatin5: "iso88599", - csisolatin6: "iso885910", - l1: "iso88591", - l2: "iso88592", - l3: "iso88593", - l4: "iso88594", - l5: "iso88599", - l6: "iso885910", - l7: "iso885913", - l8: "iso885914", - l9: "iso885915", - l10: "iso885916", - isoir14: "iso646jp", - isoir57: "iso646cn", - isoir100: "iso88591", - isoir101: "iso88592", - isoir109: "iso88593", - isoir110: "iso88594", - isoir144: "iso88595", - isoir127: "iso88596", - isoir126: "iso88597", - isoir138: "iso88598", - isoir148: "iso88599", - isoir157: "iso885910", - isoir166: "tis620", - isoir179: "iso885913", - isoir199: "iso885914", - isoir203: "iso885915", - isoir226: "iso885916", - cp819: "iso88591", - ibm819: "iso88591", - cyrillic: "iso88595", - arabic: "iso88596", - arabic8: "iso88596", - ecma114: "iso88596", - asmo708: "iso88596", - greek: "iso88597", - greek8: "iso88597", - ecma118: "iso88597", - elot928: "iso88597", - hebrew: "iso88598", - hebrew8: "iso88598", - turkish: "iso88599", - turkish8: "iso88599", - thai: "iso885911", - thai8: "iso885911", - celtic: "iso885914", - celtic8: "iso885914", - isoceltic: "iso885914", - tis6200: "tis620", - tis62025291: "tis620", - tis62025330: "tis620", - 1e4: "macroman", - 10006: "macgreek", - 10007: "maccyrillic", - 10079: "maciceland", - 10081: "macturkish", - cspc8codepage437: "cp437", - cspc775baltic: "cp775", - cspc850multilingual: "cp850", - cspcp852: "cp852", - cspc862latinhebrew: "cp862", - cpgr: "cp869", - msee: "cp1250", - mscyrl: "cp1251", - msansi: "cp1252", - msgreek: "cp1253", - msturk: "cp1254", - mshebr: "cp1255", - msarab: "cp1256", - winbaltrim: "cp1257", - cp20866: "koi8r", - 20866: "koi8r", - ibm878: "koi8r", - cskoi8r: "koi8r", - cp21866: "koi8u", - 21866: "koi8u", - ibm1168: "koi8u", - strk10482002: "rk1048", - tcvn5712: "tcvn", - tcvn57121: "tcvn", - gb198880: "iso646cn", - cn: "iso646cn", - csiso14jisc6220ro: "iso646jp", - jisc62201969ro: "iso646jp", - jp: "iso646jp", - cshproman8: "hproman8", - r8: "hproman8", - roman8: "hproman8", - xroman8: "hproman8", - ibm1051: "hproman8", - mac: "macintosh", - csmacintosh: "macintosh" - }; - } -}); - -// node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/encodings/sbcs-data-generated.js -var require_sbcs_data_generated = __commonJS({ - "node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/encodings/sbcs-data-generated.js"(exports, module) { - "use strict"; - module.exports = { - "437": "cp437", - "737": "cp737", - "775": "cp775", - "850": "cp850", - "852": "cp852", - "855": "cp855", - "856": "cp856", - "857": "cp857", - "858": "cp858", - "860": "cp860", - "861": "cp861", - "862": "cp862", - "863": "cp863", - "864": "cp864", - "865": "cp865", - "866": "cp866", - "869": "cp869", - "874": "windows874", - "922": "cp922", - "1046": "cp1046", - "1124": "cp1124", - "1125": "cp1125", - "1129": "cp1129", - "1133": "cp1133", - "1161": "cp1161", - "1162": "cp1162", - "1163": "cp1163", - "1250": "windows1250", - "1251": "windows1251", - "1252": "windows1252", - "1253": "windows1253", - "1254": "windows1254", - "1255": "windows1255", - "1256": "windows1256", - "1257": "windows1257", - "1258": "windows1258", - "28591": "iso88591", - "28592": "iso88592", - "28593": "iso88593", - "28594": "iso88594", - "28595": "iso88595", - "28596": "iso88596", - "28597": "iso88597", - "28598": "iso88598", - "28599": "iso88599", - "28600": "iso885910", - "28601": "iso885911", - "28603": "iso885913", - "28604": "iso885914", - "28605": "iso885915", - "28606": "iso885916", - "windows874": { - "type": "_sbcs", - "chars": "\u20AC\uFFFD\uFFFD\uFFFD\uFFFD\u2026\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u2018\u2019\u201C\u201D\u2022\u2013\u2014\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\xA0\u0E01\u0E02\u0E03\u0E04\u0E05\u0E06\u0E07\u0E08\u0E09\u0E0A\u0E0B\u0E0C\u0E0D\u0E0E\u0E0F\u0E10\u0E11\u0E12\u0E13\u0E14\u0E15\u0E16\u0E17\u0E18\u0E19\u0E1A\u0E1B\u0E1C\u0E1D\u0E1E\u0E1F\u0E20\u0E21\u0E22\u0E23\u0E24\u0E25\u0E26\u0E27\u0E28\u0E29\u0E2A\u0E2B\u0E2C\u0E2D\u0E2E\u0E2F\u0E30\u0E31\u0E32\u0E33\u0E34\u0E35\u0E36\u0E37\u0E38\u0E39\u0E3A\uFFFD\uFFFD\uFFFD\uFFFD\u0E3F\u0E40\u0E41\u0E42\u0E43\u0E44\u0E45\u0E46\u0E47\u0E48\u0E49\u0E4A\u0E4B\u0E4C\u0E4D\u0E4E\u0E4F\u0E50\u0E51\u0E52\u0E53\u0E54\u0E55\u0E56\u0E57\u0E58\u0E59\u0E5A\u0E5B\uFFFD\uFFFD\uFFFD\uFFFD" - }, - "win874": "windows874", - "cp874": "windows874", - "windows1250": { - "type": "_sbcs", - "chars": "\u20AC\uFFFD\u201A\uFFFD\u201E\u2026\u2020\u2021\uFFFD\u2030\u0160\u2039\u015A\u0164\u017D\u0179\uFFFD\u2018\u2019\u201C\u201D\u2022\u2013\u2014\uFFFD\u2122\u0161\u203A\u015B\u0165\u017E\u017A\xA0\u02C7\u02D8\u0141\xA4\u0104\xA6\xA7\xA8\xA9\u015E\xAB\xAC\xAD\xAE\u017B\xB0\xB1\u02DB\u0142\xB4\xB5\xB6\xB7\xB8\u0105\u015F\xBB\u013D\u02DD\u013E\u017C\u0154\xC1\xC2\u0102\xC4\u0139\u0106\xC7\u010C\xC9\u0118\xCB\u011A\xCD\xCE\u010E\u0110\u0143\u0147\xD3\xD4\u0150\xD6\xD7\u0158\u016E\xDA\u0170\xDC\xDD\u0162\xDF\u0155\xE1\xE2\u0103\xE4\u013A\u0107\xE7\u010D\xE9\u0119\xEB\u011B\xED\xEE\u010F\u0111\u0144\u0148\xF3\xF4\u0151\xF6\xF7\u0159\u016F\xFA\u0171\xFC\xFD\u0163\u02D9" - }, - "win1250": "windows1250", - "cp1250": "windows1250", - "windows1251": { - "type": "_sbcs", - "chars": "\u0402\u0403\u201A\u0453\u201E\u2026\u2020\u2021\u20AC\u2030\u0409\u2039\u040A\u040C\u040B\u040F\u0452\u2018\u2019\u201C\u201D\u2022\u2013\u2014\uFFFD\u2122\u0459\u203A\u045A\u045C\u045B\u045F\xA0\u040E\u045E\u0408\xA4\u0490\xA6\xA7\u0401\xA9\u0404\xAB\xAC\xAD\xAE\u0407\xB0\xB1\u0406\u0456\u0491\xB5\xB6\xB7\u0451\u2116\u0454\xBB\u0458\u0405\u0455\u0457\u0410\u0411\u0412\u0413\u0414\u0415\u0416\u0417\u0418\u0419\u041A\u041B\u041C\u041D\u041E\u041F\u0420\u0421\u0422\u0423\u0424\u0425\u0426\u0427\u0428\u0429\u042A\u042B\u042C\u042D\u042E\u042F\u0430\u0431\u0432\u0433\u0434\u0435\u0436\u0437\u0438\u0439\u043A\u043B\u043C\u043D\u043E\u043F\u0440\u0441\u0442\u0443\u0444\u0445\u0446\u0447\u0448\u0449\u044A\u044B\u044C\u044D\u044E\u044F" - }, - "win1251": "windows1251", - "cp1251": "windows1251", - "windows1252": { - "type": "_sbcs", - "chars": "\u20AC\uFFFD\u201A\u0192\u201E\u2026\u2020\u2021\u02C6\u2030\u0160\u2039\u0152\uFFFD\u017D\uFFFD\uFFFD\u2018\u2019\u201C\u201D\u2022\u2013\u2014\u02DC\u2122\u0161\u203A\u0153\uFFFD\u017E\u0178\xA0\xA1\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xAA\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xBA\xBB\xBC\xBD\xBE\xBF\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1\xD2\xD3\xD4\xD5\xD6\xD7\xD8\xD9\xDA\xDB\xDC\xDD\xDE\xDF\xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\xFA\xFB\xFC\xFD\xFE\xFF" - }, - "win1252": "windows1252", - "cp1252": "windows1252", - "windows1253": { - "type": "_sbcs", - "chars": "\u20AC\uFFFD\u201A\u0192\u201E\u2026\u2020\u2021\uFFFD\u2030\uFFFD\u2039\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u2018\u2019\u201C\u201D\u2022\u2013\u2014\uFFFD\u2122\uFFFD\u203A\uFFFD\uFFFD\uFFFD\uFFFD\xA0\u0385\u0386\xA3\xA4\xA5\xA6\xA7\xA8\xA9\uFFFD\xAB\xAC\xAD\xAE\u2015\xB0\xB1\xB2\xB3\u0384\xB5\xB6\xB7\u0388\u0389\u038A\xBB\u038C\xBD\u038E\u038F\u0390\u0391\u0392\u0393\u0394\u0395\u0396\u0397\u0398\u0399\u039A\u039B\u039C\u039D\u039E\u039F\u03A0\u03A1\uFFFD\u03A3\u03A4\u03A5\u03A6\u03A7\u03A8\u03A9\u03AA\u03AB\u03AC\u03AD\u03AE\u03AF\u03B0\u03B1\u03B2\u03B3\u03B4\u03B5\u03B6\u03B7\u03B8\u03B9\u03BA\u03BB\u03BC\u03BD\u03BE\u03BF\u03C0\u03C1\u03C2\u03C3\u03C4\u03C5\u03C6\u03C7\u03C8\u03C9\u03CA\u03CB\u03CC\u03CD\u03CE\uFFFD" - }, - "win1253": "windows1253", - "cp1253": "windows1253", - "windows1254": { - "type": "_sbcs", - "chars": "\u20AC\uFFFD\u201A\u0192\u201E\u2026\u2020\u2021\u02C6\u2030\u0160\u2039\u0152\uFFFD\uFFFD\uFFFD\uFFFD\u2018\u2019\u201C\u201D\u2022\u2013\u2014\u02DC\u2122\u0161\u203A\u0153\uFFFD\uFFFD\u0178\xA0\xA1\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xAA\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xBA\xBB\xBC\xBD\xBE\xBF\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\u011E\xD1\xD2\xD3\xD4\xD5\xD6\xD7\xD8\xD9\xDA\xDB\xDC\u0130\u015E\xDF\xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\u011F\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\xFA\xFB\xFC\u0131\u015F\xFF" - }, - "win1254": "windows1254", - "cp1254": "windows1254", - "windows1255": { - "type": "_sbcs", - "chars": "\u20AC\uFFFD\u201A\u0192\u201E\u2026\u2020\u2021\u02C6\u2030\uFFFD\u2039\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u2018\u2019\u201C\u201D\u2022\u2013\u2014\u02DC\u2122\uFFFD\u203A\uFFFD\uFFFD\uFFFD\uFFFD\xA0\xA1\xA2\xA3\u20AA\xA5\xA6\xA7\xA8\xA9\xD7\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xF7\xBB\xBC\xBD\xBE\xBF\u05B0\u05B1\u05B2\u05B3\u05B4\u05B5\u05B6\u05B7\u05B8\u05B9\u05BA\u05BB\u05BC\u05BD\u05BE\u05BF\u05C0\u05C1\u05C2\u05C3\u05F0\u05F1\u05F2\u05F3\u05F4\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u05D0\u05D1\u05D2\u05D3\u05D4\u05D5\u05D6\u05D7\u05D8\u05D9\u05DA\u05DB\u05DC\u05DD\u05DE\u05DF\u05E0\u05E1\u05E2\u05E3\u05E4\u05E5\u05E6\u05E7\u05E8\u05E9\u05EA\uFFFD\uFFFD\u200E\u200F\uFFFD" - }, - "win1255": "windows1255", - "cp1255": "windows1255", - "windows1256": { - "type": "_sbcs", - "chars": "\u20AC\u067E\u201A\u0192\u201E\u2026\u2020\u2021\u02C6\u2030\u0679\u2039\u0152\u0686\u0698\u0688\u06AF\u2018\u2019\u201C\u201D\u2022\u2013\u2014\u06A9\u2122\u0691\u203A\u0153\u200C\u200D\u06BA\xA0\u060C\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\u06BE\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\u061B\xBB\xBC\xBD\xBE\u061F\u06C1\u0621\u0622\u0623\u0624\u0625\u0626\u0627\u0628\u0629\u062A\u062B\u062C\u062D\u062E\u062F\u0630\u0631\u0632\u0633\u0634\u0635\u0636\xD7\u0637\u0638\u0639\u063A\u0640\u0641\u0642\u0643\xE0\u0644\xE2\u0645\u0646\u0647\u0648\xE7\xE8\xE9\xEA\xEB\u0649\u064A\xEE\xEF\u064B\u064C\u064D\u064E\xF4\u064F\u0650\xF7\u0651\xF9\u0652\xFB\xFC\u200E\u200F\u06D2" - }, - "win1256": "windows1256", - "cp1256": "windows1256", - "windows1257": { - "type": "_sbcs", - "chars": "\u20AC\uFFFD\u201A\uFFFD\u201E\u2026\u2020\u2021\uFFFD\u2030\uFFFD\u2039\uFFFD\xA8\u02C7\xB8\uFFFD\u2018\u2019\u201C\u201D\u2022\u2013\u2014\uFFFD\u2122\uFFFD\u203A\uFFFD\xAF\u02DB\uFFFD\xA0\uFFFD\xA2\xA3\xA4\uFFFD\xA6\xA7\xD8\xA9\u0156\xAB\xAC\xAD\xAE\xC6\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xF8\xB9\u0157\xBB\xBC\xBD\xBE\xE6\u0104\u012E\u0100\u0106\xC4\xC5\u0118\u0112\u010C\xC9\u0179\u0116\u0122\u0136\u012A\u013B\u0160\u0143\u0145\xD3\u014C\xD5\xD6\xD7\u0172\u0141\u015A\u016A\xDC\u017B\u017D\xDF\u0105\u012F\u0101\u0107\xE4\xE5\u0119\u0113\u010D\xE9\u017A\u0117\u0123\u0137\u012B\u013C\u0161\u0144\u0146\xF3\u014D\xF5\xF6\xF7\u0173\u0142\u015B\u016B\xFC\u017C\u017E\u02D9" - }, - "win1257": "windows1257", - "cp1257": "windows1257", - "windows1258": { - "type": "_sbcs", - "chars": "\u20AC\uFFFD\u201A\u0192\u201E\u2026\u2020\u2021\u02C6\u2030\uFFFD\u2039\u0152\uFFFD\uFFFD\uFFFD\uFFFD\u2018\u2019\u201C\u201D\u2022\u2013\u2014\u02DC\u2122\uFFFD\u203A\u0153\uFFFD\uFFFD\u0178\xA0\xA1\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xAA\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xBA\xBB\xBC\xBD\xBE\xBF\xC0\xC1\xC2\u0102\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\u0300\xCD\xCE\xCF\u0110\xD1\u0309\xD3\xD4\u01A0\xD6\xD7\xD8\xD9\xDA\xDB\xDC\u01AF\u0303\xDF\xE0\xE1\xE2\u0103\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\u0301\xED\xEE\xEF\u0111\xF1\u0323\xF3\xF4\u01A1\xF6\xF7\xF8\xF9\xFA\xFB\xFC\u01B0\u20AB\xFF" - }, - "win1258": "windows1258", - "cp1258": "windows1258", - "iso88591": { - "type": "_sbcs", - "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\xA1\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xAA\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xBA\xBB\xBC\xBD\xBE\xBF\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1\xD2\xD3\xD4\xD5\xD6\xD7\xD8\xD9\xDA\xDB\xDC\xDD\xDE\xDF\xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\xFA\xFB\xFC\xFD\xFE\xFF" - }, - "cp28591": "iso88591", - "iso88592": { - "type": "_sbcs", - "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\u0104\u02D8\u0141\xA4\u013D\u015A\xA7\xA8\u0160\u015E\u0164\u0179\xAD\u017D\u017B\xB0\u0105\u02DB\u0142\xB4\u013E\u015B\u02C7\xB8\u0161\u015F\u0165\u017A\u02DD\u017E\u017C\u0154\xC1\xC2\u0102\xC4\u0139\u0106\xC7\u010C\xC9\u0118\xCB\u011A\xCD\xCE\u010E\u0110\u0143\u0147\xD3\xD4\u0150\xD6\xD7\u0158\u016E\xDA\u0170\xDC\xDD\u0162\xDF\u0155\xE1\xE2\u0103\xE4\u013A\u0107\xE7\u010D\xE9\u0119\xEB\u011B\xED\xEE\u010F\u0111\u0144\u0148\xF3\xF4\u0151\xF6\xF7\u0159\u016F\xFA\u0171\xFC\xFD\u0163\u02D9" - }, - "cp28592": "iso88592", - "iso88593": { - "type": "_sbcs", - "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\u0126\u02D8\xA3\xA4\uFFFD\u0124\xA7\xA8\u0130\u015E\u011E\u0134\xAD\uFFFD\u017B\xB0\u0127\xB2\xB3\xB4\xB5\u0125\xB7\xB8\u0131\u015F\u011F\u0135\xBD\uFFFD\u017C\xC0\xC1\xC2\uFFFD\xC4\u010A\u0108\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\uFFFD\xD1\xD2\xD3\xD4\u0120\xD6\xD7\u011C\xD9\xDA\xDB\xDC\u016C\u015C\xDF\xE0\xE1\xE2\uFFFD\xE4\u010B\u0109\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\uFFFD\xF1\xF2\xF3\xF4\u0121\xF6\xF7\u011D\xF9\xFA\xFB\xFC\u016D\u015D\u02D9" - }, - "cp28593": "iso88593", - "iso88594": { - "type": "_sbcs", - "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\u0104\u0138\u0156\xA4\u0128\u013B\xA7\xA8\u0160\u0112\u0122\u0166\xAD\u017D\xAF\xB0\u0105\u02DB\u0157\xB4\u0129\u013C\u02C7\xB8\u0161\u0113\u0123\u0167\u014A\u017E\u014B\u0100\xC1\xC2\xC3\xC4\xC5\xC6\u012E\u010C\xC9\u0118\xCB\u0116\xCD\xCE\u012A\u0110\u0145\u014C\u0136\xD4\xD5\xD6\xD7\xD8\u0172\xDA\xDB\xDC\u0168\u016A\xDF\u0101\xE1\xE2\xE3\xE4\xE5\xE6\u012F\u010D\xE9\u0119\xEB\u0117\xED\xEE\u012B\u0111\u0146\u014D\u0137\xF4\xF5\xF6\xF7\xF8\u0173\xFA\xFB\xFC\u0169\u016B\u02D9" - }, - "cp28594": "iso88594", - "iso88595": { - "type": "_sbcs", - "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\u0401\u0402\u0403\u0404\u0405\u0406\u0407\u0408\u0409\u040A\u040B\u040C\xAD\u040E\u040F\u0410\u0411\u0412\u0413\u0414\u0415\u0416\u0417\u0418\u0419\u041A\u041B\u041C\u041D\u041E\u041F\u0420\u0421\u0422\u0423\u0424\u0425\u0426\u0427\u0428\u0429\u042A\u042B\u042C\u042D\u042E\u042F\u0430\u0431\u0432\u0433\u0434\u0435\u0436\u0437\u0438\u0439\u043A\u043B\u043C\u043D\u043E\u043F\u0440\u0441\u0442\u0443\u0444\u0445\u0446\u0447\u0448\u0449\u044A\u044B\u044C\u044D\u044E\u044F\u2116\u0451\u0452\u0453\u0454\u0455\u0456\u0457\u0458\u0459\u045A\u045B\u045C\xA7\u045E\u045F" - }, - "cp28595": "iso88595", - "iso88596": { - "type": "_sbcs", - "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\uFFFD\uFFFD\uFFFD\xA4\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u060C\xAD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u061B\uFFFD\uFFFD\uFFFD\u061F\uFFFD\u0621\u0622\u0623\u0624\u0625\u0626\u0627\u0628\u0629\u062A\u062B\u062C\u062D\u062E\u062F\u0630\u0631\u0632\u0633\u0634\u0635\u0636\u0637\u0638\u0639\u063A\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u0640\u0641\u0642\u0643\u0644\u0645\u0646\u0647\u0648\u0649\u064A\u064B\u064C\u064D\u064E\u064F\u0650\u0651\u0652\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD" - }, - "cp28596": "iso88596", - "iso88597": { - "type": "_sbcs", - "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\u2018\u2019\xA3\u20AC\u20AF\xA6\xA7\xA8\xA9\u037A\xAB\xAC\xAD\uFFFD\u2015\xB0\xB1\xB2\xB3\u0384\u0385\u0386\xB7\u0388\u0389\u038A\xBB\u038C\xBD\u038E\u038F\u0390\u0391\u0392\u0393\u0394\u0395\u0396\u0397\u0398\u0399\u039A\u039B\u039C\u039D\u039E\u039F\u03A0\u03A1\uFFFD\u03A3\u03A4\u03A5\u03A6\u03A7\u03A8\u03A9\u03AA\u03AB\u03AC\u03AD\u03AE\u03AF\u03B0\u03B1\u03B2\u03B3\u03B4\u03B5\u03B6\u03B7\u03B8\u03B9\u03BA\u03BB\u03BC\u03BD\u03BE\u03BF\u03C0\u03C1\u03C2\u03C3\u03C4\u03C5\u03C6\u03C7\u03C8\u03C9\u03CA\u03CB\u03CC\u03CD\u03CE\uFFFD" - }, - "cp28597": "iso88597", - "iso88598": { - "type": "_sbcs", - "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\uFFFD\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xD7\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xF7\xBB\xBC\xBD\xBE\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u2017\u05D0\u05D1\u05D2\u05D3\u05D4\u05D5\u05D6\u05D7\u05D8\u05D9\u05DA\u05DB\u05DC\u05DD\u05DE\u05DF\u05E0\u05E1\u05E2\u05E3\u05E4\u05E5\u05E6\u05E7\u05E8\u05E9\u05EA\uFFFD\uFFFD\u200E\u200F\uFFFD" - }, - "cp28598": "iso88598", - "iso88599": { - "type": "_sbcs", - "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\xA1\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xAA\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xBA\xBB\xBC\xBD\xBE\xBF\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\u011E\xD1\xD2\xD3\xD4\xD5\xD6\xD7\xD8\xD9\xDA\xDB\xDC\u0130\u015E\xDF\xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\u011F\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\xFA\xFB\xFC\u0131\u015F\xFF" - }, - "cp28599": "iso88599", - "iso885910": { - "type": "_sbcs", - "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\u0104\u0112\u0122\u012A\u0128\u0136\xA7\u013B\u0110\u0160\u0166\u017D\xAD\u016A\u014A\xB0\u0105\u0113\u0123\u012B\u0129\u0137\xB7\u013C\u0111\u0161\u0167\u017E\u2015\u016B\u014B\u0100\xC1\xC2\xC3\xC4\xC5\xC6\u012E\u010C\xC9\u0118\xCB\u0116\xCD\xCE\xCF\xD0\u0145\u014C\xD3\xD4\xD5\xD6\u0168\xD8\u0172\xDA\xDB\xDC\xDD\xDE\xDF\u0101\xE1\xE2\xE3\xE4\xE5\xE6\u012F\u010D\xE9\u0119\xEB\u0117\xED\xEE\xEF\xF0\u0146\u014D\xF3\xF4\xF5\xF6\u0169\xF8\u0173\xFA\xFB\xFC\xFD\xFE\u0138" - }, - "cp28600": "iso885910", - "iso885911": { - "type": "_sbcs", - "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\u0E01\u0E02\u0E03\u0E04\u0E05\u0E06\u0E07\u0E08\u0E09\u0E0A\u0E0B\u0E0C\u0E0D\u0E0E\u0E0F\u0E10\u0E11\u0E12\u0E13\u0E14\u0E15\u0E16\u0E17\u0E18\u0E19\u0E1A\u0E1B\u0E1C\u0E1D\u0E1E\u0E1F\u0E20\u0E21\u0E22\u0E23\u0E24\u0E25\u0E26\u0E27\u0E28\u0E29\u0E2A\u0E2B\u0E2C\u0E2D\u0E2E\u0E2F\u0E30\u0E31\u0E32\u0E33\u0E34\u0E35\u0E36\u0E37\u0E38\u0E39\u0E3A\uFFFD\uFFFD\uFFFD\uFFFD\u0E3F\u0E40\u0E41\u0E42\u0E43\u0E44\u0E45\u0E46\u0E47\u0E48\u0E49\u0E4A\u0E4B\u0E4C\u0E4D\u0E4E\u0E4F\u0E50\u0E51\u0E52\u0E53\u0E54\u0E55\u0E56\u0E57\u0E58\u0E59\u0E5A\u0E5B\uFFFD\uFFFD\uFFFD\uFFFD" - }, - "cp28601": "iso885911", - "iso885913": { - "type": "_sbcs", - "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\u201D\xA2\xA3\xA4\u201E\xA6\xA7\xD8\xA9\u0156\xAB\xAC\xAD\xAE\xC6\xB0\xB1\xB2\xB3\u201C\xB5\xB6\xB7\xF8\xB9\u0157\xBB\xBC\xBD\xBE\xE6\u0104\u012E\u0100\u0106\xC4\xC5\u0118\u0112\u010C\xC9\u0179\u0116\u0122\u0136\u012A\u013B\u0160\u0143\u0145\xD3\u014C\xD5\xD6\xD7\u0172\u0141\u015A\u016A\xDC\u017B\u017D\xDF\u0105\u012F\u0101\u0107\xE4\xE5\u0119\u0113\u010D\xE9\u017A\u0117\u0123\u0137\u012B\u013C\u0161\u0144\u0146\xF3\u014D\xF5\xF6\xF7\u0173\u0142\u015B\u016B\xFC\u017C\u017E\u2019" - }, - "cp28603": "iso885913", - "iso885914": { - "type": "_sbcs", - "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\u1E02\u1E03\xA3\u010A\u010B\u1E0A\xA7\u1E80\xA9\u1E82\u1E0B\u1EF2\xAD\xAE\u0178\u1E1E\u1E1F\u0120\u0121\u1E40\u1E41\xB6\u1E56\u1E81\u1E57\u1E83\u1E60\u1EF3\u1E84\u1E85\u1E61\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\u0174\xD1\xD2\xD3\xD4\xD5\xD6\u1E6A\xD8\xD9\xDA\xDB\xDC\xDD\u0176\xDF\xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\u0175\xF1\xF2\xF3\xF4\xF5\xF6\u1E6B\xF8\xF9\xFA\xFB\xFC\xFD\u0177\xFF" - }, - "cp28604": "iso885914", - "iso885915": { - "type": "_sbcs", - "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\xA1\xA2\xA3\u20AC\xA5\u0160\xA7\u0161\xA9\xAA\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\u017D\xB5\xB6\xB7\u017E\xB9\xBA\xBB\u0152\u0153\u0178\xBF\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1\xD2\xD3\xD4\xD5\xD6\xD7\xD8\xD9\xDA\xDB\xDC\xDD\xDE\xDF\xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\xFA\xFB\xFC\xFD\xFE\xFF" - }, - "cp28605": "iso885915", - "iso885916": { - "type": "_sbcs", - "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\u0104\u0105\u0141\u20AC\u201E\u0160\xA7\u0161\xA9\u0218\xAB\u0179\xAD\u017A\u017B\xB0\xB1\u010C\u0142\u017D\u201D\xB6\xB7\u017E\u010D\u0219\xBB\u0152\u0153\u0178\u017C\xC0\xC1\xC2\u0102\xC4\u0106\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\u0110\u0143\xD2\xD3\xD4\u0150\xD6\u015A\u0170\xD9\xDA\xDB\xDC\u0118\u021A\xDF\xE0\xE1\xE2\u0103\xE4\u0107\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\u0111\u0144\xF2\xF3\xF4\u0151\xF6\u015B\u0171\xF9\xFA\xFB\xFC\u0119\u021B\xFF" - }, - "cp28606": "iso885916", - "cp437": { - "type": "_sbcs", - "chars": "\xC7\xFC\xE9\xE2\xE4\xE0\xE5\xE7\xEA\xEB\xE8\xEF\xEE\xEC\xC4\xC5\xC9\xE6\xC6\xF4\xF6\xF2\xFB\xF9\xFF\xD6\xDC\xA2\xA3\xA5\u20A7\u0192\xE1\xED\xF3\xFA\xF1\xD1\xAA\xBA\xBF\u2310\xAC\xBD\xBC\xA1\xAB\xBB\u2591\u2592\u2593\u2502\u2524\u2561\u2562\u2556\u2555\u2563\u2551\u2557\u255D\u255C\u255B\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u255E\u255F\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u2567\u2568\u2564\u2565\u2559\u2558\u2552\u2553\u256B\u256A\u2518\u250C\u2588\u2584\u258C\u2590\u2580\u03B1\xDF\u0393\u03C0\u03A3\u03C3\xB5\u03C4\u03A6\u0398\u03A9\u03B4\u221E\u03C6\u03B5\u2229\u2261\xB1\u2265\u2264\u2320\u2321\xF7\u2248\xB0\u2219\xB7\u221A\u207F\xB2\u25A0\xA0" - }, - "ibm437": "cp437", - "csibm437": "cp437", - "cp737": { - "type": "_sbcs", - "chars": "\u0391\u0392\u0393\u0394\u0395\u0396\u0397\u0398\u0399\u039A\u039B\u039C\u039D\u039E\u039F\u03A0\u03A1\u03A3\u03A4\u03A5\u03A6\u03A7\u03A8\u03A9\u03B1\u03B2\u03B3\u03B4\u03B5\u03B6\u03B7\u03B8\u03B9\u03BA\u03BB\u03BC\u03BD\u03BE\u03BF\u03C0\u03C1\u03C3\u03C2\u03C4\u03C5\u03C6\u03C7\u03C8\u2591\u2592\u2593\u2502\u2524\u2561\u2562\u2556\u2555\u2563\u2551\u2557\u255D\u255C\u255B\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u255E\u255F\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u2567\u2568\u2564\u2565\u2559\u2558\u2552\u2553\u256B\u256A\u2518\u250C\u2588\u2584\u258C\u2590\u2580\u03C9\u03AC\u03AD\u03AE\u03CA\u03AF\u03CC\u03CD\u03CB\u03CE\u0386\u0388\u0389\u038A\u038C\u038E\u038F\xB1\u2265\u2264\u03AA\u03AB\xF7\u2248\xB0\u2219\xB7\u221A\u207F\xB2\u25A0\xA0" - }, - "ibm737": "cp737", - "csibm737": "cp737", - "cp775": { - "type": "_sbcs", - "chars": "\u0106\xFC\xE9\u0101\xE4\u0123\xE5\u0107\u0142\u0113\u0156\u0157\u012B\u0179\xC4\xC5\xC9\xE6\xC6\u014D\xF6\u0122\xA2\u015A\u015B\xD6\xDC\xF8\xA3\xD8\xD7\xA4\u0100\u012A\xF3\u017B\u017C\u017A\u201D\xA6\xA9\xAE\xAC\xBD\xBC\u0141\xAB\xBB\u2591\u2592\u2593\u2502\u2524\u0104\u010C\u0118\u0116\u2563\u2551\u2557\u255D\u012E\u0160\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u0172\u016A\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u017D\u0105\u010D\u0119\u0117\u012F\u0161\u0173\u016B\u017E\u2518\u250C\u2588\u2584\u258C\u2590\u2580\xD3\xDF\u014C\u0143\xF5\xD5\xB5\u0144\u0136\u0137\u013B\u013C\u0146\u0112\u0145\u2019\xAD\xB1\u201C\xBE\xB6\xA7\xF7\u201E\xB0\u2219\xB7\xB9\xB3\xB2\u25A0\xA0" - }, - "ibm775": "cp775", - "csibm775": "cp775", - "cp850": { - "type": "_sbcs", - "chars": "\xC7\xFC\xE9\xE2\xE4\xE0\xE5\xE7\xEA\xEB\xE8\xEF\xEE\xEC\xC4\xC5\xC9\xE6\xC6\xF4\xF6\xF2\xFB\xF9\xFF\xD6\xDC\xF8\xA3\xD8\xD7\u0192\xE1\xED\xF3\xFA\xF1\xD1\xAA\xBA\xBF\xAE\xAC\xBD\xBC\xA1\xAB\xBB\u2591\u2592\u2593\u2502\u2524\xC1\xC2\xC0\xA9\u2563\u2551\u2557\u255D\xA2\xA5\u2510\u2514\u2534\u252C\u251C\u2500\u253C\xE3\xC3\u255A\u2554\u2569\u2566\u2560\u2550\u256C\xA4\xF0\xD0\xCA\xCB\xC8\u0131\xCD\xCE\xCF\u2518\u250C\u2588\u2584\xA6\xCC\u2580\xD3\xDF\xD4\xD2\xF5\xD5\xB5\xFE\xDE\xDA\xDB\xD9\xFD\xDD\xAF\xB4\xAD\xB1\u2017\xBE\xB6\xA7\xF7\xB8\xB0\xA8\xB7\xB9\xB3\xB2\u25A0\xA0" - }, - "ibm850": "cp850", - "csibm850": "cp850", - "cp852": { - "type": "_sbcs", - "chars": "\xC7\xFC\xE9\xE2\xE4\u016F\u0107\xE7\u0142\xEB\u0150\u0151\xEE\u0179\xC4\u0106\xC9\u0139\u013A\xF4\xF6\u013D\u013E\u015A\u015B\xD6\xDC\u0164\u0165\u0141\xD7\u010D\xE1\xED\xF3\xFA\u0104\u0105\u017D\u017E\u0118\u0119\xAC\u017A\u010C\u015F\xAB\xBB\u2591\u2592\u2593\u2502\u2524\xC1\xC2\u011A\u015E\u2563\u2551\u2557\u255D\u017B\u017C\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u0102\u0103\u255A\u2554\u2569\u2566\u2560\u2550\u256C\xA4\u0111\u0110\u010E\xCB\u010F\u0147\xCD\xCE\u011B\u2518\u250C\u2588\u2584\u0162\u016E\u2580\xD3\xDF\xD4\u0143\u0144\u0148\u0160\u0161\u0154\xDA\u0155\u0170\xFD\xDD\u0163\xB4\xAD\u02DD\u02DB\u02C7\u02D8\xA7\xF7\xB8\xB0\xA8\u02D9\u0171\u0158\u0159\u25A0\xA0" - }, - "ibm852": "cp852", - "csibm852": "cp852", - "cp855": { - "type": "_sbcs", - "chars": "\u0452\u0402\u0453\u0403\u0451\u0401\u0454\u0404\u0455\u0405\u0456\u0406\u0457\u0407\u0458\u0408\u0459\u0409\u045A\u040A\u045B\u040B\u045C\u040C\u045E\u040E\u045F\u040F\u044E\u042E\u044A\u042A\u0430\u0410\u0431\u0411\u0446\u0426\u0434\u0414\u0435\u0415\u0444\u0424\u0433\u0413\xAB\xBB\u2591\u2592\u2593\u2502\u2524\u0445\u0425\u0438\u0418\u2563\u2551\u2557\u255D\u0439\u0419\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u043A\u041A\u255A\u2554\u2569\u2566\u2560\u2550\u256C\xA4\u043B\u041B\u043C\u041C\u043D\u041D\u043E\u041E\u043F\u2518\u250C\u2588\u2584\u041F\u044F\u2580\u042F\u0440\u0420\u0441\u0421\u0442\u0422\u0443\u0423\u0436\u0416\u0432\u0412\u044C\u042C\u2116\xAD\u044B\u042B\u0437\u0417\u0448\u0428\u044D\u042D\u0449\u0429\u0447\u0427\xA7\u25A0\xA0" - }, - "ibm855": "cp855", - "csibm855": "cp855", - "cp856": { - "type": "_sbcs", - "chars": "\u05D0\u05D1\u05D2\u05D3\u05D4\u05D5\u05D6\u05D7\u05D8\u05D9\u05DA\u05DB\u05DC\u05DD\u05DE\u05DF\u05E0\u05E1\u05E2\u05E3\u05E4\u05E5\u05E6\u05E7\u05E8\u05E9\u05EA\uFFFD\xA3\uFFFD\xD7\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\xAE\xAC\xBD\xBC\uFFFD\xAB\xBB\u2591\u2592\u2593\u2502\u2524\uFFFD\uFFFD\uFFFD\xA9\u2563\u2551\u2557\u255D\xA2\xA5\u2510\u2514\u2534\u252C\u251C\u2500\u253C\uFFFD\uFFFD\u255A\u2554\u2569\u2566\u2560\u2550\u256C\xA4\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u2518\u250C\u2588\u2584\xA6\uFFFD\u2580\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\xB5\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\xAF\xB4\xAD\xB1\u2017\xBE\xB6\xA7\xF7\xB8\xB0\xA8\xB7\xB9\xB3\xB2\u25A0\xA0" - }, - "ibm856": "cp856", - "csibm856": "cp856", - "cp857": { - "type": "_sbcs", - "chars": "\xC7\xFC\xE9\xE2\xE4\xE0\xE5\xE7\xEA\xEB\xE8\xEF\xEE\u0131\xC4\xC5\xC9\xE6\xC6\xF4\xF6\xF2\xFB\xF9\u0130\xD6\xDC\xF8\xA3\xD8\u015E\u015F\xE1\xED\xF3\xFA\xF1\xD1\u011E\u011F\xBF\xAE\xAC\xBD\xBC\xA1\xAB\xBB\u2591\u2592\u2593\u2502\u2524\xC1\xC2\xC0\xA9\u2563\u2551\u2557\u255D\xA2\xA5\u2510\u2514\u2534\u252C\u251C\u2500\u253C\xE3\xC3\u255A\u2554\u2569\u2566\u2560\u2550\u256C\xA4\xBA\xAA\xCA\xCB\xC8\uFFFD\xCD\xCE\xCF\u2518\u250C\u2588\u2584\xA6\xCC\u2580\xD3\xDF\xD4\xD2\xF5\xD5\xB5\uFFFD\xD7\xDA\xDB\xD9\xEC\xFF\xAF\xB4\xAD\xB1\uFFFD\xBE\xB6\xA7\xF7\xB8\xB0\xA8\xB7\xB9\xB3\xB2\u25A0\xA0" - }, - "ibm857": "cp857", - "csibm857": "cp857", - "cp858": { - "type": "_sbcs", - "chars": "\xC7\xFC\xE9\xE2\xE4\xE0\xE5\xE7\xEA\xEB\xE8\xEF\xEE\xEC\xC4\xC5\xC9\xE6\xC6\xF4\xF6\xF2\xFB\xF9\xFF\xD6\xDC\xF8\xA3\xD8\xD7\u0192\xE1\xED\xF3\xFA\xF1\xD1\xAA\xBA\xBF\xAE\xAC\xBD\xBC\xA1\xAB\xBB\u2591\u2592\u2593\u2502\u2524\xC1\xC2\xC0\xA9\u2563\u2551\u2557\u255D\xA2\xA5\u2510\u2514\u2534\u252C\u251C\u2500\u253C\xE3\xC3\u255A\u2554\u2569\u2566\u2560\u2550\u256C\xA4\xF0\xD0\xCA\xCB\xC8\u20AC\xCD\xCE\xCF\u2518\u250C\u2588\u2584\xA6\xCC\u2580\xD3\xDF\xD4\xD2\xF5\xD5\xB5\xFE\xDE\xDA\xDB\xD9\xFD\xDD\xAF\xB4\xAD\xB1\u2017\xBE\xB6\xA7\xF7\xB8\xB0\xA8\xB7\xB9\xB3\xB2\u25A0\xA0" - }, - "ibm858": "cp858", - "csibm858": "cp858", - "cp860": { - "type": "_sbcs", - "chars": "\xC7\xFC\xE9\xE2\xE3\xE0\xC1\xE7\xEA\xCA\xE8\xCD\xD4\xEC\xC3\xC2\xC9\xC0\xC8\xF4\xF5\xF2\xDA\xF9\xCC\xD5\xDC\xA2\xA3\xD9\u20A7\xD3\xE1\xED\xF3\xFA\xF1\xD1\xAA\xBA\xBF\xD2\xAC\xBD\xBC\xA1\xAB\xBB\u2591\u2592\u2593\u2502\u2524\u2561\u2562\u2556\u2555\u2563\u2551\u2557\u255D\u255C\u255B\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u255E\u255F\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u2567\u2568\u2564\u2565\u2559\u2558\u2552\u2553\u256B\u256A\u2518\u250C\u2588\u2584\u258C\u2590\u2580\u03B1\xDF\u0393\u03C0\u03A3\u03C3\xB5\u03C4\u03A6\u0398\u03A9\u03B4\u221E\u03C6\u03B5\u2229\u2261\xB1\u2265\u2264\u2320\u2321\xF7\u2248\xB0\u2219\xB7\u221A\u207F\xB2\u25A0\xA0" - }, - "ibm860": "cp860", - "csibm860": "cp860", - "cp861": { - "type": "_sbcs", - "chars": "\xC7\xFC\xE9\xE2\xE4\xE0\xE5\xE7\xEA\xEB\xE8\xD0\xF0\xDE\xC4\xC5\xC9\xE6\xC6\xF4\xF6\xFE\xFB\xDD\xFD\xD6\xDC\xF8\xA3\xD8\u20A7\u0192\xE1\xED\xF3\xFA\xC1\xCD\xD3\xDA\xBF\u2310\xAC\xBD\xBC\xA1\xAB\xBB\u2591\u2592\u2593\u2502\u2524\u2561\u2562\u2556\u2555\u2563\u2551\u2557\u255D\u255C\u255B\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u255E\u255F\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u2567\u2568\u2564\u2565\u2559\u2558\u2552\u2553\u256B\u256A\u2518\u250C\u2588\u2584\u258C\u2590\u2580\u03B1\xDF\u0393\u03C0\u03A3\u03C3\xB5\u03C4\u03A6\u0398\u03A9\u03B4\u221E\u03C6\u03B5\u2229\u2261\xB1\u2265\u2264\u2320\u2321\xF7\u2248\xB0\u2219\xB7\u221A\u207F\xB2\u25A0\xA0" - }, - "ibm861": "cp861", - "csibm861": "cp861", - "cp862": { - "type": "_sbcs", - "chars": "\u05D0\u05D1\u05D2\u05D3\u05D4\u05D5\u05D6\u05D7\u05D8\u05D9\u05DA\u05DB\u05DC\u05DD\u05DE\u05DF\u05E0\u05E1\u05E2\u05E3\u05E4\u05E5\u05E6\u05E7\u05E8\u05E9\u05EA\xA2\xA3\xA5\u20A7\u0192\xE1\xED\xF3\xFA\xF1\xD1\xAA\xBA\xBF\u2310\xAC\xBD\xBC\xA1\xAB\xBB\u2591\u2592\u2593\u2502\u2524\u2561\u2562\u2556\u2555\u2563\u2551\u2557\u255D\u255C\u255B\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u255E\u255F\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u2567\u2568\u2564\u2565\u2559\u2558\u2552\u2553\u256B\u256A\u2518\u250C\u2588\u2584\u258C\u2590\u2580\u03B1\xDF\u0393\u03C0\u03A3\u03C3\xB5\u03C4\u03A6\u0398\u03A9\u03B4\u221E\u03C6\u03B5\u2229\u2261\xB1\u2265\u2264\u2320\u2321\xF7\u2248\xB0\u2219\xB7\u221A\u207F\xB2\u25A0\xA0" - }, - "ibm862": "cp862", - "csibm862": "cp862", - "cp863": { - "type": "_sbcs", - "chars": "\xC7\xFC\xE9\xE2\xC2\xE0\xB6\xE7\xEA\xEB\xE8\xEF\xEE\u2017\xC0\xA7\xC9\xC8\xCA\xF4\xCB\xCF\xFB\xF9\xA4\xD4\xDC\xA2\xA3\xD9\xDB\u0192\xA6\xB4\xF3\xFA\xA8\xB8\xB3\xAF\xCE\u2310\xAC\xBD\xBC\xBE\xAB\xBB\u2591\u2592\u2593\u2502\u2524\u2561\u2562\u2556\u2555\u2563\u2551\u2557\u255D\u255C\u255B\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u255E\u255F\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u2567\u2568\u2564\u2565\u2559\u2558\u2552\u2553\u256B\u256A\u2518\u250C\u2588\u2584\u258C\u2590\u2580\u03B1\xDF\u0393\u03C0\u03A3\u03C3\xB5\u03C4\u03A6\u0398\u03A9\u03B4\u221E\u03C6\u03B5\u2229\u2261\xB1\u2265\u2264\u2320\u2321\xF7\u2248\xB0\u2219\xB7\u221A\u207F\xB2\u25A0\xA0" - }, - "ibm863": "cp863", - "csibm863": "cp863", - "cp864": { - "type": "_sbcs", - "chars": "\0\x07\b \n\v\f\r\x1B !\"#$\u066A&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7F\xB0\xB7\u2219\u221A\u2592\u2500\u2502\u253C\u2524\u252C\u251C\u2534\u2510\u250C\u2514\u2518\u03B2\u221E\u03C6\xB1\xBD\xBC\u2248\xAB\xBB\uFEF7\uFEF8\uFFFD\uFFFD\uFEFB\uFEFC\uFFFD\xA0\xAD\uFE82\xA3\xA4\uFE84\uFFFD\uFFFD\uFE8E\uFE8F\uFE95\uFE99\u060C\uFE9D\uFEA1\uFEA5\u0660\u0661\u0662\u0663\u0664\u0665\u0666\u0667\u0668\u0669\uFED1\u061B\uFEB1\uFEB5\uFEB9\u061F\xA2\uFE80\uFE81\uFE83\uFE85\uFECA\uFE8B\uFE8D\uFE91\uFE93\uFE97\uFE9B\uFE9F\uFEA3\uFEA7\uFEA9\uFEAB\uFEAD\uFEAF\uFEB3\uFEB7\uFEBB\uFEBF\uFEC1\uFEC5\uFECB\uFECF\xA6\xAC\xF7\xD7\uFEC9\u0640\uFED3\uFED7\uFEDB\uFEDF\uFEE3\uFEE7\uFEEB\uFEED\uFEEF\uFEF3\uFEBD\uFECC\uFECE\uFECD\uFEE1\uFE7D\u0651\uFEE5\uFEE9\uFEEC\uFEF0\uFEF2\uFED0\uFED5\uFEF5\uFEF6\uFEDD\uFED9\uFEF1\u25A0\uFFFD" - }, - "ibm864": "cp864", - "csibm864": "cp864", - "cp865": { - "type": "_sbcs", - "chars": "\xC7\xFC\xE9\xE2\xE4\xE0\xE5\xE7\xEA\xEB\xE8\xEF\xEE\xEC\xC4\xC5\xC9\xE6\xC6\xF4\xF6\xF2\xFB\xF9\xFF\xD6\xDC\xF8\xA3\xD8\u20A7\u0192\xE1\xED\xF3\xFA\xF1\xD1\xAA\xBA\xBF\u2310\xAC\xBD\xBC\xA1\xAB\xA4\u2591\u2592\u2593\u2502\u2524\u2561\u2562\u2556\u2555\u2563\u2551\u2557\u255D\u255C\u255B\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u255E\u255F\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u2567\u2568\u2564\u2565\u2559\u2558\u2552\u2553\u256B\u256A\u2518\u250C\u2588\u2584\u258C\u2590\u2580\u03B1\xDF\u0393\u03C0\u03A3\u03C3\xB5\u03C4\u03A6\u0398\u03A9\u03B4\u221E\u03C6\u03B5\u2229\u2261\xB1\u2265\u2264\u2320\u2321\xF7\u2248\xB0\u2219\xB7\u221A\u207F\xB2\u25A0\xA0" - }, - "ibm865": "cp865", - "csibm865": "cp865", - "cp866": { - "type": "_sbcs", - "chars": "\u0410\u0411\u0412\u0413\u0414\u0415\u0416\u0417\u0418\u0419\u041A\u041B\u041C\u041D\u041E\u041F\u0420\u0421\u0422\u0423\u0424\u0425\u0426\u0427\u0428\u0429\u042A\u042B\u042C\u042D\u042E\u042F\u0430\u0431\u0432\u0433\u0434\u0435\u0436\u0437\u0438\u0439\u043A\u043B\u043C\u043D\u043E\u043F\u2591\u2592\u2593\u2502\u2524\u2561\u2562\u2556\u2555\u2563\u2551\u2557\u255D\u255C\u255B\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u255E\u255F\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u2567\u2568\u2564\u2565\u2559\u2558\u2552\u2553\u256B\u256A\u2518\u250C\u2588\u2584\u258C\u2590\u2580\u0440\u0441\u0442\u0443\u0444\u0445\u0446\u0447\u0448\u0449\u044A\u044B\u044C\u044D\u044E\u044F\u0401\u0451\u0404\u0454\u0407\u0457\u040E\u045E\xB0\u2219\xB7\u221A\u2116\xA4\u25A0\xA0" - }, - "ibm866": "cp866", - "csibm866": "cp866", - "cp869": { - "type": "_sbcs", - "chars": "\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u0386\uFFFD\xB7\xAC\xA6\u2018\u2019\u0388\u2015\u0389\u038A\u03AA\u038C\uFFFD\uFFFD\u038E\u03AB\xA9\u038F\xB2\xB3\u03AC\xA3\u03AD\u03AE\u03AF\u03CA\u0390\u03CC\u03CD\u0391\u0392\u0393\u0394\u0395\u0396\u0397\xBD\u0398\u0399\xAB\xBB\u2591\u2592\u2593\u2502\u2524\u039A\u039B\u039C\u039D\u2563\u2551\u2557\u255D\u039E\u039F\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u03A0\u03A1\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u03A3\u03A4\u03A5\u03A6\u03A7\u03A8\u03A9\u03B1\u03B2\u03B3\u2518\u250C\u2588\u2584\u03B4\u03B5\u2580\u03B6\u03B7\u03B8\u03B9\u03BA\u03BB\u03BC\u03BD\u03BE\u03BF\u03C0\u03C1\u03C3\u03C2\u03C4\u0384\xAD\xB1\u03C5\u03C6\u03C7\xA7\u03C8\u0385\xB0\xA8\u03C9\u03CB\u03B0\u03CE\u25A0\xA0" - }, - "ibm869": "cp869", - "csibm869": "cp869", - "cp922": { - "type": "_sbcs", - "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\xA1\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xAA\xAB\xAC\xAD\xAE\u203E\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xBA\xBB\xBC\xBD\xBE\xBF\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\u0160\xD1\xD2\xD3\xD4\xD5\xD6\xD7\xD8\xD9\xDA\xDB\xDC\xDD\u017D\xDF\xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\u0161\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\xFA\xFB\xFC\xFD\u017E\xFF" - }, - "ibm922": "cp922", - "csibm922": "cp922", - "cp1046": { - "type": "_sbcs", - "chars": "\uFE88\xD7\xF7\uF8F6\uF8F5\uF8F4\uF8F7\uFE71\x88\u25A0\u2502\u2500\u2510\u250C\u2514\u2518\uFE79\uFE7B\uFE7D\uFE7F\uFE77\uFE8A\uFEF0\uFEF3\uFEF2\uFECE\uFECF\uFED0\uFEF6\uFEF8\uFEFA\uFEFC\xA0\uF8FA\uF8F9\uF8F8\xA4\uF8FB\uFE8B\uFE91\uFE97\uFE9B\uFE9F\uFEA3\u060C\xAD\uFEA7\uFEB3\u0660\u0661\u0662\u0663\u0664\u0665\u0666\u0667\u0668\u0669\uFEB7\u061B\uFEBB\uFEBF\uFECA\u061F\uFECB\u0621\u0622\u0623\u0624\u0625\u0626\u0627\u0628\u0629\u062A\u062B\u062C\u062D\u062E\u062F\u0630\u0631\u0632\u0633\u0634\u0635\u0636\u0637\uFEC7\u0639\u063A\uFECC\uFE82\uFE84\uFE8E\uFED3\u0640\u0641\u0642\u0643\u0644\u0645\u0646\u0647\u0648\u0649\u064A\u064B\u064C\u064D\u064E\u064F\u0650\u0651\u0652\uFED7\uFEDB\uFEDF\uF8FC\uFEF5\uFEF7\uFEF9\uFEFB\uFEE3\uFEE7\uFEEC\uFEE9\uFFFD" - }, - "ibm1046": "cp1046", - "csibm1046": "cp1046", - "cp1124": { - "type": "_sbcs", - "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\u0401\u0402\u0490\u0404\u0405\u0406\u0407\u0408\u0409\u040A\u040B\u040C\xAD\u040E\u040F\u0410\u0411\u0412\u0413\u0414\u0415\u0416\u0417\u0418\u0419\u041A\u041B\u041C\u041D\u041E\u041F\u0420\u0421\u0422\u0423\u0424\u0425\u0426\u0427\u0428\u0429\u042A\u042B\u042C\u042D\u042E\u042F\u0430\u0431\u0432\u0433\u0434\u0435\u0436\u0437\u0438\u0439\u043A\u043B\u043C\u043D\u043E\u043F\u0440\u0441\u0442\u0443\u0444\u0445\u0446\u0447\u0448\u0449\u044A\u044B\u044C\u044D\u044E\u044F\u2116\u0451\u0452\u0491\u0454\u0455\u0456\u0457\u0458\u0459\u045A\u045B\u045C\xA7\u045E\u045F" - }, - "ibm1124": "cp1124", - "csibm1124": "cp1124", - "cp1125": { - "type": "_sbcs", - "chars": "\u0410\u0411\u0412\u0413\u0414\u0415\u0416\u0417\u0418\u0419\u041A\u041B\u041C\u041D\u041E\u041F\u0420\u0421\u0422\u0423\u0424\u0425\u0426\u0427\u0428\u0429\u042A\u042B\u042C\u042D\u042E\u042F\u0430\u0431\u0432\u0433\u0434\u0435\u0436\u0437\u0438\u0439\u043A\u043B\u043C\u043D\u043E\u043F\u2591\u2592\u2593\u2502\u2524\u2561\u2562\u2556\u2555\u2563\u2551\u2557\u255D\u255C\u255B\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u255E\u255F\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u2567\u2568\u2564\u2565\u2559\u2558\u2552\u2553\u256B\u256A\u2518\u250C\u2588\u2584\u258C\u2590\u2580\u0440\u0441\u0442\u0443\u0444\u0445\u0446\u0447\u0448\u0449\u044A\u044B\u044C\u044D\u044E\u044F\u0401\u0451\u0490\u0491\u0404\u0454\u0406\u0456\u0407\u0457\xB7\u221A\u2116\xA4\u25A0\xA0" - }, - "ibm1125": "cp1125", - "csibm1125": "cp1125", - "cp1129": { - "type": "_sbcs", - "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\xA1\xA2\xA3\xA4\xA5\xA6\xA7\u0153\xA9\xAA\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\u0178\xB5\xB6\xB7\u0152\xB9\xBA\xBB\xBC\xBD\xBE\xBF\xC0\xC1\xC2\u0102\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\u0300\xCD\xCE\xCF\u0110\xD1\u0309\xD3\xD4\u01A0\xD6\xD7\xD8\xD9\xDA\xDB\xDC\u01AF\u0303\xDF\xE0\xE1\xE2\u0103\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\u0301\xED\xEE\xEF\u0111\xF1\u0323\xF3\xF4\u01A1\xF6\xF7\xF8\xF9\xFA\xFB\xFC\u01B0\u20AB\xFF" - }, - "ibm1129": "cp1129", - "csibm1129": "cp1129", - "cp1133": { - "type": "_sbcs", - "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\u0E81\u0E82\u0E84\u0E87\u0E88\u0EAA\u0E8A\u0E8D\u0E94\u0E95\u0E96\u0E97\u0E99\u0E9A\u0E9B\u0E9C\u0E9D\u0E9E\u0E9F\u0EA1\u0EA2\u0EA3\u0EA5\u0EA7\u0EAB\u0EAD\u0EAE\uFFFD\uFFFD\uFFFD\u0EAF\u0EB0\u0EB2\u0EB3\u0EB4\u0EB5\u0EB6\u0EB7\u0EB8\u0EB9\u0EBC\u0EB1\u0EBB\u0EBD\uFFFD\uFFFD\uFFFD\u0EC0\u0EC1\u0EC2\u0EC3\u0EC4\u0EC8\u0EC9\u0ECA\u0ECB\u0ECC\u0ECD\u0EC6\uFFFD\u0EDC\u0EDD\u20AD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u0ED0\u0ED1\u0ED2\u0ED3\u0ED4\u0ED5\u0ED6\u0ED7\u0ED8\u0ED9\uFFFD\uFFFD\xA2\xAC\xA6\uFFFD" - }, - "ibm1133": "cp1133", - "csibm1133": "cp1133", - "cp1161": { - "type": "_sbcs", - "chars": "\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u0E48\u0E01\u0E02\u0E03\u0E04\u0E05\u0E06\u0E07\u0E08\u0E09\u0E0A\u0E0B\u0E0C\u0E0D\u0E0E\u0E0F\u0E10\u0E11\u0E12\u0E13\u0E14\u0E15\u0E16\u0E17\u0E18\u0E19\u0E1A\u0E1B\u0E1C\u0E1D\u0E1E\u0E1F\u0E20\u0E21\u0E22\u0E23\u0E24\u0E25\u0E26\u0E27\u0E28\u0E29\u0E2A\u0E2B\u0E2C\u0E2D\u0E2E\u0E2F\u0E30\u0E31\u0E32\u0E33\u0E34\u0E35\u0E36\u0E37\u0E38\u0E39\u0E3A\u0E49\u0E4A\u0E4B\u20AC\u0E3F\u0E40\u0E41\u0E42\u0E43\u0E44\u0E45\u0E46\u0E47\u0E48\u0E49\u0E4A\u0E4B\u0E4C\u0E4D\u0E4E\u0E4F\u0E50\u0E51\u0E52\u0E53\u0E54\u0E55\u0E56\u0E57\u0E58\u0E59\u0E5A\u0E5B\xA2\xAC\xA6\xA0" - }, - "ibm1161": "cp1161", - "csibm1161": "cp1161", - "cp1162": { - "type": "_sbcs", - "chars": "\u20AC\x81\x82\x83\x84\u2026\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\u2018\u2019\u201C\u201D\u2022\u2013\u2014\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\u0E01\u0E02\u0E03\u0E04\u0E05\u0E06\u0E07\u0E08\u0E09\u0E0A\u0E0B\u0E0C\u0E0D\u0E0E\u0E0F\u0E10\u0E11\u0E12\u0E13\u0E14\u0E15\u0E16\u0E17\u0E18\u0E19\u0E1A\u0E1B\u0E1C\u0E1D\u0E1E\u0E1F\u0E20\u0E21\u0E22\u0E23\u0E24\u0E25\u0E26\u0E27\u0E28\u0E29\u0E2A\u0E2B\u0E2C\u0E2D\u0E2E\u0E2F\u0E30\u0E31\u0E32\u0E33\u0E34\u0E35\u0E36\u0E37\u0E38\u0E39\u0E3A\uFFFD\uFFFD\uFFFD\uFFFD\u0E3F\u0E40\u0E41\u0E42\u0E43\u0E44\u0E45\u0E46\u0E47\u0E48\u0E49\u0E4A\u0E4B\u0E4C\u0E4D\u0E4E\u0E4F\u0E50\u0E51\u0E52\u0E53\u0E54\u0E55\u0E56\u0E57\u0E58\u0E59\u0E5A\u0E5B\uFFFD\uFFFD\uFFFD\uFFFD" - }, - "ibm1162": "cp1162", - "csibm1162": "cp1162", - "cp1163": { - "type": "_sbcs", - "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\xA1\xA2\xA3\u20AC\xA5\xA6\xA7\u0153\xA9\xAA\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\u0178\xB5\xB6\xB7\u0152\xB9\xBA\xBB\xBC\xBD\xBE\xBF\xC0\xC1\xC2\u0102\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\u0300\xCD\xCE\xCF\u0110\xD1\u0309\xD3\xD4\u01A0\xD6\xD7\xD8\xD9\xDA\xDB\xDC\u01AF\u0303\xDF\xE0\xE1\xE2\u0103\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\u0301\xED\xEE\xEF\u0111\xF1\u0323\xF3\xF4\u01A1\xF6\xF7\xF8\xF9\xFA\xFB\xFC\u01B0\u20AB\xFF" - }, - "ibm1163": "cp1163", - "csibm1163": "cp1163", - "maccroatian": { - "type": "_sbcs", - "chars": "\xC4\xC5\xC7\xC9\xD1\xD6\xDC\xE1\xE0\xE2\xE4\xE3\xE5\xE7\xE9\xE8\xEA\xEB\xED\xEC\xEE\xEF\xF1\xF3\xF2\xF4\xF6\xF5\xFA\xF9\xFB\xFC\u2020\xB0\xA2\xA3\xA7\u2022\xB6\xDF\xAE\u0160\u2122\xB4\xA8\u2260\u017D\xD8\u221E\xB1\u2264\u2265\u2206\xB5\u2202\u2211\u220F\u0161\u222B\xAA\xBA\u2126\u017E\xF8\xBF\xA1\xAC\u221A\u0192\u2248\u0106\xAB\u010C\u2026\xA0\xC0\xC3\xD5\u0152\u0153\u0110\u2014\u201C\u201D\u2018\u2019\xF7\u25CA\uFFFD\xA9\u2044\xA4\u2039\u203A\xC6\xBB\u2013\xB7\u201A\u201E\u2030\xC2\u0107\xC1\u010D\xC8\xCD\xCE\xCF\xCC\xD3\xD4\u0111\xD2\xDA\xDB\xD9\u0131\u02C6\u02DC\xAF\u03C0\xCB\u02DA\xB8\xCA\xE6\u02C7" - }, - "maccyrillic": { - "type": "_sbcs", - "chars": "\u0410\u0411\u0412\u0413\u0414\u0415\u0416\u0417\u0418\u0419\u041A\u041B\u041C\u041D\u041E\u041F\u0420\u0421\u0422\u0423\u0424\u0425\u0426\u0427\u0428\u0429\u042A\u042B\u042C\u042D\u042E\u042F\u2020\xB0\xA2\xA3\xA7\u2022\xB6\u0406\xAE\xA9\u2122\u0402\u0452\u2260\u0403\u0453\u221E\xB1\u2264\u2265\u0456\xB5\u2202\u0408\u0404\u0454\u0407\u0457\u0409\u0459\u040A\u045A\u0458\u0405\xAC\u221A\u0192\u2248\u2206\xAB\xBB\u2026\xA0\u040B\u045B\u040C\u045C\u0455\u2013\u2014\u201C\u201D\u2018\u2019\xF7\u201E\u040E\u045E\u040F\u045F\u2116\u0401\u0451\u044F\u0430\u0431\u0432\u0433\u0434\u0435\u0436\u0437\u0438\u0439\u043A\u043B\u043C\u043D\u043E\u043F\u0440\u0441\u0442\u0443\u0444\u0445\u0446\u0447\u0448\u0449\u044A\u044B\u044C\u044D\u044E\xA4" - }, - "macgreek": { - "type": "_sbcs", - "chars": "\xC4\xB9\xB2\xC9\xB3\xD6\xDC\u0385\xE0\xE2\xE4\u0384\xA8\xE7\xE9\xE8\xEA\xEB\xA3\u2122\xEE\xEF\u2022\xBD\u2030\xF4\xF6\xA6\xAD\xF9\xFB\xFC\u2020\u0393\u0394\u0398\u039B\u039E\u03A0\xDF\xAE\xA9\u03A3\u03AA\xA7\u2260\xB0\u0387\u0391\xB1\u2264\u2265\xA5\u0392\u0395\u0396\u0397\u0399\u039A\u039C\u03A6\u03AB\u03A8\u03A9\u03AC\u039D\xAC\u039F\u03A1\u2248\u03A4\xAB\xBB\u2026\xA0\u03A5\u03A7\u0386\u0388\u0153\u2013\u2015\u201C\u201D\u2018\u2019\xF7\u0389\u038A\u038C\u038E\u03AD\u03AE\u03AF\u03CC\u038F\u03CD\u03B1\u03B2\u03C8\u03B4\u03B5\u03C6\u03B3\u03B7\u03B9\u03BE\u03BA\u03BB\u03BC\u03BD\u03BF\u03C0\u03CE\u03C1\u03C3\u03C4\u03B8\u03C9\u03C2\u03C7\u03C5\u03B6\u03CA\u03CB\u0390\u03B0\uFFFD" - }, - "maciceland": { - "type": "_sbcs", - "chars": "\xC4\xC5\xC7\xC9\xD1\xD6\xDC\xE1\xE0\xE2\xE4\xE3\xE5\xE7\xE9\xE8\xEA\xEB\xED\xEC\xEE\xEF\xF1\xF3\xF2\xF4\xF6\xF5\xFA\xF9\xFB\xFC\xDD\xB0\xA2\xA3\xA7\u2022\xB6\xDF\xAE\xA9\u2122\xB4\xA8\u2260\xC6\xD8\u221E\xB1\u2264\u2265\xA5\xB5\u2202\u2211\u220F\u03C0\u222B\xAA\xBA\u2126\xE6\xF8\xBF\xA1\xAC\u221A\u0192\u2248\u2206\xAB\xBB\u2026\xA0\xC0\xC3\xD5\u0152\u0153\u2013\u2014\u201C\u201D\u2018\u2019\xF7\u25CA\xFF\u0178\u2044\xA4\xD0\xF0\xDE\xFE\xFD\xB7\u201A\u201E\u2030\xC2\xCA\xC1\xCB\xC8\xCD\xCE\xCF\xCC\xD3\xD4\uFFFD\xD2\xDA\xDB\xD9\u0131\u02C6\u02DC\xAF\u02D8\u02D9\u02DA\xB8\u02DD\u02DB\u02C7" - }, - "macroman": { - "type": "_sbcs", - "chars": "\xC4\xC5\xC7\xC9\xD1\xD6\xDC\xE1\xE0\xE2\xE4\xE3\xE5\xE7\xE9\xE8\xEA\xEB\xED\xEC\xEE\xEF\xF1\xF3\xF2\xF4\xF6\xF5\xFA\xF9\xFB\xFC\u2020\xB0\xA2\xA3\xA7\u2022\xB6\xDF\xAE\xA9\u2122\xB4\xA8\u2260\xC6\xD8\u221E\xB1\u2264\u2265\xA5\xB5\u2202\u2211\u220F\u03C0\u222B\xAA\xBA\u2126\xE6\xF8\xBF\xA1\xAC\u221A\u0192\u2248\u2206\xAB\xBB\u2026\xA0\xC0\xC3\xD5\u0152\u0153\u2013\u2014\u201C\u201D\u2018\u2019\xF7\u25CA\xFF\u0178\u2044\xA4\u2039\u203A\uFB01\uFB02\u2021\xB7\u201A\u201E\u2030\xC2\xCA\xC1\xCB\xC8\xCD\xCE\xCF\xCC\xD3\xD4\uFFFD\xD2\xDA\xDB\xD9\u0131\u02C6\u02DC\xAF\u02D8\u02D9\u02DA\xB8\u02DD\u02DB\u02C7" - }, - "macromania": { - "type": "_sbcs", - "chars": "\xC4\xC5\xC7\xC9\xD1\xD6\xDC\xE1\xE0\xE2\xE4\xE3\xE5\xE7\xE9\xE8\xEA\xEB\xED\xEC\xEE\xEF\xF1\xF3\xF2\xF4\xF6\xF5\xFA\xF9\xFB\xFC\u2020\xB0\xA2\xA3\xA7\u2022\xB6\xDF\xAE\xA9\u2122\xB4\xA8\u2260\u0102\u015E\u221E\xB1\u2264\u2265\xA5\xB5\u2202\u2211\u220F\u03C0\u222B\xAA\xBA\u2126\u0103\u015F\xBF\xA1\xAC\u221A\u0192\u2248\u2206\xAB\xBB\u2026\xA0\xC0\xC3\xD5\u0152\u0153\u2013\u2014\u201C\u201D\u2018\u2019\xF7\u25CA\xFF\u0178\u2044\xA4\u2039\u203A\u0162\u0163\u2021\xB7\u201A\u201E\u2030\xC2\xCA\xC1\xCB\xC8\xCD\xCE\xCF\xCC\xD3\xD4\uFFFD\xD2\xDA\xDB\xD9\u0131\u02C6\u02DC\xAF\u02D8\u02D9\u02DA\xB8\u02DD\u02DB\u02C7" - }, - "macthai": { - "type": "_sbcs", - "chars": "\xAB\xBB\u2026\uF88C\uF88F\uF892\uF895\uF898\uF88B\uF88E\uF891\uF894\uF897\u201C\u201D\uF899\uFFFD\u2022\uF884\uF889\uF885\uF886\uF887\uF888\uF88A\uF88D\uF890\uF893\uF896\u2018\u2019\uFFFD\xA0\u0E01\u0E02\u0E03\u0E04\u0E05\u0E06\u0E07\u0E08\u0E09\u0E0A\u0E0B\u0E0C\u0E0D\u0E0E\u0E0F\u0E10\u0E11\u0E12\u0E13\u0E14\u0E15\u0E16\u0E17\u0E18\u0E19\u0E1A\u0E1B\u0E1C\u0E1D\u0E1E\u0E1F\u0E20\u0E21\u0E22\u0E23\u0E24\u0E25\u0E26\u0E27\u0E28\u0E29\u0E2A\u0E2B\u0E2C\u0E2D\u0E2E\u0E2F\u0E30\u0E31\u0E32\u0E33\u0E34\u0E35\u0E36\u0E37\u0E38\u0E39\u0E3A\uFEFF\u200B\u2013\u2014\u0E3F\u0E40\u0E41\u0E42\u0E43\u0E44\u0E45\u0E46\u0E47\u0E48\u0E49\u0E4A\u0E4B\u0E4C\u0E4D\u2122\u0E4F\u0E50\u0E51\u0E52\u0E53\u0E54\u0E55\u0E56\u0E57\u0E58\u0E59\xAE\xA9\uFFFD\uFFFD\uFFFD\uFFFD" - }, - "macturkish": { - "type": "_sbcs", - "chars": "\xC4\xC5\xC7\xC9\xD1\xD6\xDC\xE1\xE0\xE2\xE4\xE3\xE5\xE7\xE9\xE8\xEA\xEB\xED\xEC\xEE\xEF\xF1\xF3\xF2\xF4\xF6\xF5\xFA\xF9\xFB\xFC\u2020\xB0\xA2\xA3\xA7\u2022\xB6\xDF\xAE\xA9\u2122\xB4\xA8\u2260\xC6\xD8\u221E\xB1\u2264\u2265\xA5\xB5\u2202\u2211\u220F\u03C0\u222B\xAA\xBA\u2126\xE6\xF8\xBF\xA1\xAC\u221A\u0192\u2248\u2206\xAB\xBB\u2026\xA0\xC0\xC3\xD5\u0152\u0153\u2013\u2014\u201C\u201D\u2018\u2019\xF7\u25CA\xFF\u0178\u011E\u011F\u0130\u0131\u015E\u015F\u2021\xB7\u201A\u201E\u2030\xC2\xCA\xC1\xCB\xC8\xCD\xCE\xCF\xCC\xD3\xD4\uFFFD\xD2\xDA\xDB\xD9\uFFFD\u02C6\u02DC\xAF\u02D8\u02D9\u02DA\xB8\u02DD\u02DB\u02C7" - }, - "macukraine": { - "type": "_sbcs", - "chars": "\u0410\u0411\u0412\u0413\u0414\u0415\u0416\u0417\u0418\u0419\u041A\u041B\u041C\u041D\u041E\u041F\u0420\u0421\u0422\u0423\u0424\u0425\u0426\u0427\u0428\u0429\u042A\u042B\u042C\u042D\u042E\u042F\u2020\xB0\u0490\xA3\xA7\u2022\xB6\u0406\xAE\xA9\u2122\u0402\u0452\u2260\u0403\u0453\u221E\xB1\u2264\u2265\u0456\xB5\u0491\u0408\u0404\u0454\u0407\u0457\u0409\u0459\u040A\u045A\u0458\u0405\xAC\u221A\u0192\u2248\u2206\xAB\xBB\u2026\xA0\u040B\u045B\u040C\u045C\u0455\u2013\u2014\u201C\u201D\u2018\u2019\xF7\u201E\u040E\u045E\u040F\u045F\u2116\u0401\u0451\u044F\u0430\u0431\u0432\u0433\u0434\u0435\u0436\u0437\u0438\u0439\u043A\u043B\u043C\u043D\u043E\u043F\u0440\u0441\u0442\u0443\u0444\u0445\u0446\u0447\u0448\u0449\u044A\u044B\u044C\u044D\u044E\xA4" - }, - "koi8r": { - "type": "_sbcs", - "chars": "\u2500\u2502\u250C\u2510\u2514\u2518\u251C\u2524\u252C\u2534\u253C\u2580\u2584\u2588\u258C\u2590\u2591\u2592\u2593\u2320\u25A0\u2219\u221A\u2248\u2264\u2265\xA0\u2321\xB0\xB2\xB7\xF7\u2550\u2551\u2552\u0451\u2553\u2554\u2555\u2556\u2557\u2558\u2559\u255A\u255B\u255C\u255D\u255E\u255F\u2560\u2561\u0401\u2562\u2563\u2564\u2565\u2566\u2567\u2568\u2569\u256A\u256B\u256C\xA9\u044E\u0430\u0431\u0446\u0434\u0435\u0444\u0433\u0445\u0438\u0439\u043A\u043B\u043C\u043D\u043E\u043F\u044F\u0440\u0441\u0442\u0443\u0436\u0432\u044C\u044B\u0437\u0448\u044D\u0449\u0447\u044A\u042E\u0410\u0411\u0426\u0414\u0415\u0424\u0413\u0425\u0418\u0419\u041A\u041B\u041C\u041D\u041E\u041F\u042F\u0420\u0421\u0422\u0423\u0416\u0412\u042C\u042B\u0417\u0428\u042D\u0429\u0427\u042A" - }, - "koi8u": { - "type": "_sbcs", - "chars": "\u2500\u2502\u250C\u2510\u2514\u2518\u251C\u2524\u252C\u2534\u253C\u2580\u2584\u2588\u258C\u2590\u2591\u2592\u2593\u2320\u25A0\u2219\u221A\u2248\u2264\u2265\xA0\u2321\xB0\xB2\xB7\xF7\u2550\u2551\u2552\u0451\u0454\u2554\u0456\u0457\u2557\u2558\u2559\u255A\u255B\u0491\u255D\u255E\u255F\u2560\u2561\u0401\u0404\u2563\u0406\u0407\u2566\u2567\u2568\u2569\u256A\u0490\u256C\xA9\u044E\u0430\u0431\u0446\u0434\u0435\u0444\u0433\u0445\u0438\u0439\u043A\u043B\u043C\u043D\u043E\u043F\u044F\u0440\u0441\u0442\u0443\u0436\u0432\u044C\u044B\u0437\u0448\u044D\u0449\u0447\u044A\u042E\u0410\u0411\u0426\u0414\u0415\u0424\u0413\u0425\u0418\u0419\u041A\u041B\u041C\u041D\u041E\u041F\u042F\u0420\u0421\u0422\u0423\u0416\u0412\u042C\u042B\u0417\u0428\u042D\u0429\u0427\u042A" - }, - "koi8ru": { - "type": "_sbcs", - "chars": "\u2500\u2502\u250C\u2510\u2514\u2518\u251C\u2524\u252C\u2534\u253C\u2580\u2584\u2588\u258C\u2590\u2591\u2592\u2593\u2320\u25A0\u2219\u221A\u2248\u2264\u2265\xA0\u2321\xB0\xB2\xB7\xF7\u2550\u2551\u2552\u0451\u0454\u2554\u0456\u0457\u2557\u2558\u2559\u255A\u255B\u0491\u045E\u255E\u255F\u2560\u2561\u0401\u0404\u2563\u0406\u0407\u2566\u2567\u2568\u2569\u256A\u0490\u040E\xA9\u044E\u0430\u0431\u0446\u0434\u0435\u0444\u0433\u0445\u0438\u0439\u043A\u043B\u043C\u043D\u043E\u043F\u044F\u0440\u0441\u0442\u0443\u0436\u0432\u044C\u044B\u0437\u0448\u044D\u0449\u0447\u044A\u042E\u0410\u0411\u0426\u0414\u0415\u0424\u0413\u0425\u0418\u0419\u041A\u041B\u041C\u041D\u041E\u041F\u042F\u0420\u0421\u0422\u0423\u0416\u0412\u042C\u042B\u0417\u0428\u042D\u0429\u0427\u042A" - }, - "koi8t": { - "type": "_sbcs", - "chars": "\u049B\u0493\u201A\u0492\u201E\u2026\u2020\u2021\uFFFD\u2030\u04B3\u2039\u04B2\u04B7\u04B6\uFFFD\u049A\u2018\u2019\u201C\u201D\u2022\u2013\u2014\uFFFD\u2122\uFFFD\u203A\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u04EF\u04EE\u0451\xA4\u04E3\xA6\xA7\uFFFD\uFFFD\uFFFD\xAB\xAC\xAD\xAE\uFFFD\xB0\xB1\xB2\u0401\uFFFD\u04E2\xB6\xB7\uFFFD\u2116\uFFFD\xBB\uFFFD\uFFFD\uFFFD\xA9\u044E\u0430\u0431\u0446\u0434\u0435\u0444\u0433\u0445\u0438\u0439\u043A\u043B\u043C\u043D\u043E\u043F\u044F\u0440\u0441\u0442\u0443\u0436\u0432\u044C\u044B\u0437\u0448\u044D\u0449\u0447\u044A\u042E\u0410\u0411\u0426\u0414\u0415\u0424\u0413\u0425\u0418\u0419\u041A\u041B\u041C\u041D\u041E\u041F\u042F\u0420\u0421\u0422\u0423\u0416\u0412\u042C\u042B\u0417\u0428\u042D\u0429\u0427\u042A" - }, - "armscii8": { - "type": "_sbcs", - "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\uFFFD\u0587\u0589)(\xBB\xAB\u2014.\u055D,-\u058A\u2026\u055C\u055B\u055E\u0531\u0561\u0532\u0562\u0533\u0563\u0534\u0564\u0535\u0565\u0536\u0566\u0537\u0567\u0538\u0568\u0539\u0569\u053A\u056A\u053B\u056B\u053C\u056C\u053D\u056D\u053E\u056E\u053F\u056F\u0540\u0570\u0541\u0571\u0542\u0572\u0543\u0573\u0544\u0574\u0545\u0575\u0546\u0576\u0547\u0577\u0548\u0578\u0549\u0579\u054A\u057A\u054B\u057B\u054C\u057C\u054D\u057D\u054E\u057E\u054F\u057F\u0550\u0580\u0551\u0581\u0552\u0582\u0553\u0583\u0554\u0584\u0555\u0585\u0556\u0586\u055A\uFFFD" - }, - "rk1048": { - "type": "_sbcs", - "chars": "\u0402\u0403\u201A\u0453\u201E\u2026\u2020\u2021\u20AC\u2030\u0409\u2039\u040A\u049A\u04BA\u040F\u0452\u2018\u2019\u201C\u201D\u2022\u2013\u2014\uFFFD\u2122\u0459\u203A\u045A\u049B\u04BB\u045F\xA0\u04B0\u04B1\u04D8\xA4\u04E8\xA6\xA7\u0401\xA9\u0492\xAB\xAC\xAD\xAE\u04AE\xB0\xB1\u0406\u0456\u04E9\xB5\xB6\xB7\u0451\u2116\u0493\xBB\u04D9\u04A2\u04A3\u04AF\u0410\u0411\u0412\u0413\u0414\u0415\u0416\u0417\u0418\u0419\u041A\u041B\u041C\u041D\u041E\u041F\u0420\u0421\u0422\u0423\u0424\u0425\u0426\u0427\u0428\u0429\u042A\u042B\u042C\u042D\u042E\u042F\u0430\u0431\u0432\u0433\u0434\u0435\u0436\u0437\u0438\u0439\u043A\u043B\u043C\u043D\u043E\u043F\u0440\u0441\u0442\u0443\u0444\u0445\u0446\u0447\u0448\u0449\u044A\u044B\u044C\u044D\u044E\u044F" - }, - "tcvn": { - "type": "_sbcs", - "chars": "\0\xDA\u1EE4\u1EEA\u1EEC\u1EEE\x07\b \n\v\f\r\u1EE8\u1EF0\u1EF2\u1EF6\u1EF8\xDD\u1EF4\x1B !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7F\xC0\u1EA2\xC3\xC1\u1EA0\u1EB6\u1EAC\xC8\u1EBA\u1EBC\xC9\u1EB8\u1EC6\xCC\u1EC8\u0128\xCD\u1ECA\xD2\u1ECE\xD5\xD3\u1ECC\u1ED8\u1EDC\u1EDE\u1EE0\u1EDA\u1EE2\xD9\u1EE6\u0168\xA0\u0102\xC2\xCA\xD4\u01A0\u01AF\u0110\u0103\xE2\xEA\xF4\u01A1\u01B0\u0111\u1EB0\u0300\u0309\u0303\u0301\u0323\xE0\u1EA3\xE3\xE1\u1EA1\u1EB2\u1EB1\u1EB3\u1EB5\u1EAF\u1EB4\u1EAE\u1EA6\u1EA8\u1EAA\u1EA4\u1EC0\u1EB7\u1EA7\u1EA9\u1EAB\u1EA5\u1EAD\xE8\u1EC2\u1EBB\u1EBD\xE9\u1EB9\u1EC1\u1EC3\u1EC5\u1EBF\u1EC7\xEC\u1EC9\u1EC4\u1EBE\u1ED2\u0129\xED\u1ECB\xF2\u1ED4\u1ECF\xF5\xF3\u1ECD\u1ED3\u1ED5\u1ED7\u1ED1\u1ED9\u1EDD\u1EDF\u1EE1\u1EDB\u1EE3\xF9\u1ED6\u1EE7\u0169\xFA\u1EE5\u1EEB\u1EED\u1EEF\u1EE9\u1EF1\u1EF3\u1EF7\u1EF9\xFD\u1EF5\u1ED0" - }, - "georgianacademy": { - "type": "_sbcs", - "chars": "\x80\x81\u201A\u0192\u201E\u2026\u2020\u2021\u02C6\u2030\u0160\u2039\u0152\x8D\x8E\x8F\x90\u2018\u2019\u201C\u201D\u2022\u2013\u2014\u02DC\u2122\u0161\u203A\u0153\x9D\x9E\u0178\xA0\xA1\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xAA\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xBA\xBB\xBC\xBD\xBE\xBF\u10D0\u10D1\u10D2\u10D3\u10D4\u10D5\u10D6\u10D7\u10D8\u10D9\u10DA\u10DB\u10DC\u10DD\u10DE\u10DF\u10E0\u10E1\u10E2\u10E3\u10E4\u10E5\u10E6\u10E7\u10E8\u10E9\u10EA\u10EB\u10EC\u10ED\u10EE\u10EF\u10F0\u10F1\u10F2\u10F3\u10F4\u10F5\u10F6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\xFA\xFB\xFC\xFD\xFE\xFF" - }, - "georgianps": { - "type": "_sbcs", - "chars": "\x80\x81\u201A\u0192\u201E\u2026\u2020\u2021\u02C6\u2030\u0160\u2039\u0152\x8D\x8E\x8F\x90\u2018\u2019\u201C\u201D\u2022\u2013\u2014\u02DC\u2122\u0161\u203A\u0153\x9D\x9E\u0178\xA0\xA1\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xAA\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xBA\xBB\xBC\xBD\xBE\xBF\u10D0\u10D1\u10D2\u10D3\u10D4\u10D5\u10D6\u10F1\u10D7\u10D8\u10D9\u10DA\u10DB\u10DC\u10F2\u10DD\u10DE\u10DF\u10E0\u10E1\u10E2\u10F3\u10E3\u10E4\u10E5\u10E6\u10E7\u10E8\u10E9\u10EA\u10EB\u10EC\u10ED\u10EE\u10F4\u10EF\u10F0\u10F5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\xFA\xFB\xFC\xFD\xFE\xFF" - }, - "pt154": { - "type": "_sbcs", - "chars": "\u0496\u0492\u04EE\u0493\u201E\u2026\u04B6\u04AE\u04B2\u04AF\u04A0\u04E2\u04A2\u049A\u04BA\u04B8\u0497\u2018\u2019\u201C\u201D\u2022\u2013\u2014\u04B3\u04B7\u04A1\u04E3\u04A3\u049B\u04BB\u04B9\xA0\u040E\u045E\u0408\u04E8\u0498\u04B0\xA7\u0401\xA9\u04D8\xAB\xAC\u04EF\xAE\u049C\xB0\u04B1\u0406\u0456\u0499\u04E9\xB6\xB7\u0451\u2116\u04D9\xBB\u0458\u04AA\u04AB\u049D\u0410\u0411\u0412\u0413\u0414\u0415\u0416\u0417\u0418\u0419\u041A\u041B\u041C\u041D\u041E\u041F\u0420\u0421\u0422\u0423\u0424\u0425\u0426\u0427\u0428\u0429\u042A\u042B\u042C\u042D\u042E\u042F\u0430\u0431\u0432\u0433\u0434\u0435\u0436\u0437\u0438\u0439\u043A\u043B\u043C\u043D\u043E\u043F\u0440\u0441\u0442\u0443\u0444\u0445\u0446\u0447\u0448\u0449\u044A\u044B\u044C\u044D\u044E\u044F" - }, - "viscii": { - "type": "_sbcs", - "chars": "\0\u1EB2\u1EB4\u1EAA\x07\b \n\v\f\r\u1EF6\u1EF8\x1B\u1EF4 !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7F\u1EA0\u1EAE\u1EB0\u1EB6\u1EA4\u1EA6\u1EA8\u1EAC\u1EBC\u1EB8\u1EBE\u1EC0\u1EC2\u1EC4\u1EC6\u1ED0\u1ED2\u1ED4\u1ED6\u1ED8\u1EE2\u1EDA\u1EDC\u1EDE\u1ECA\u1ECE\u1ECC\u1EC8\u1EE6\u0168\u1EE4\u1EF2\xD5\u1EAF\u1EB1\u1EB7\u1EA5\u1EA7\u1EA9\u1EAD\u1EBD\u1EB9\u1EBF\u1EC1\u1EC3\u1EC5\u1EC7\u1ED1\u1ED3\u1ED5\u1ED7\u1EE0\u01A0\u1ED9\u1EDD\u1EDF\u1ECB\u1EF0\u1EE8\u1EEA\u1EEC\u01A1\u1EDB\u01AF\xC0\xC1\xC2\xC3\u1EA2\u0102\u1EB3\u1EB5\xC8\xC9\xCA\u1EBA\xCC\xCD\u0128\u1EF3\u0110\u1EE9\xD2\xD3\xD4\u1EA1\u1EF7\u1EEB\u1EED\xD9\xDA\u1EF9\u1EF5\xDD\u1EE1\u01B0\xE0\xE1\xE2\xE3\u1EA3\u0103\u1EEF\u1EAB\xE8\xE9\xEA\u1EBB\xEC\xED\u0129\u1EC9\u0111\u1EF1\xF2\xF3\xF4\xF5\u1ECF\u1ECD\u1EE5\xF9\xFA\u0169\u1EE7\xFD\u1EE3\u1EEE" - }, - "iso646cn": { - "type": "_sbcs", - "chars": "\0\x07\b \n\v\f\r\x1B !\"#\xA5%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}\u203E\x7F\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD" - }, - "iso646jp": { - "type": "_sbcs", - "chars": "\0\x07\b \n\v\f\r\x1B !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\xA5]^_`abcdefghijklmnopqrstuvwxyz{|}\u203E\x7F\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD" - }, - "hproman8": { - "type": "_sbcs", - "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\xC0\xC2\xC8\xCA\xCB\xCE\xCF\xB4\u02CB\u02C6\xA8\u02DC\xD9\xDB\u20A4\xAF\xDD\xFD\xB0\xC7\xE7\xD1\xF1\xA1\xBF\xA4\xA3\xA5\xA7\u0192\xA2\xE2\xEA\xF4\xFB\xE1\xE9\xF3\xFA\xE0\xE8\xF2\xF9\xE4\xEB\xF6\xFC\xC5\xEE\xD8\xC6\xE5\xED\xF8\xE6\xC4\xEC\xD6\xDC\xC9\xEF\xDF\xD4\xC1\xC3\xE3\xD0\xF0\xCD\xCC\xD3\xD2\xD5\xF5\u0160\u0161\xDA\u0178\xFF\xDE\xFE\xB7\xB5\xB6\xBE\u2014\xBC\xBD\xAA\xBA\xAB\u25A0\xBB\xB1\uFFFD" - }, - "macintosh": { - "type": "_sbcs", - "chars": "\xC4\xC5\xC7\xC9\xD1\xD6\xDC\xE1\xE0\xE2\xE4\xE3\xE5\xE7\xE9\xE8\xEA\xEB\xED\xEC\xEE\xEF\xF1\xF3\xF2\xF4\xF6\xF5\xFA\xF9\xFB\xFC\u2020\xB0\xA2\xA3\xA7\u2022\xB6\xDF\xAE\xA9\u2122\xB4\xA8\u2260\xC6\xD8\u221E\xB1\u2264\u2265\xA5\xB5\u2202\u2211\u220F\u03C0\u222B\xAA\xBA\u2126\xE6\xF8\xBF\xA1\xAC\u221A\u0192\u2248\u2206\xAB\xBB\u2026\xA0\xC0\xC3\xD5\u0152\u0153\u2013\u2014\u201C\u201D\u2018\u2019\xF7\u25CA\xFF\u0178\u2044\xA4\u2039\u203A\uFB01\uFB02\u2021\xB7\u201A\u201E\u2030\xC2\xCA\xC1\xCB\xC8\xCD\xCE\xCF\xCC\xD3\xD4\uFFFD\xD2\xDA\xDB\xD9\u0131\u02C6\u02DC\xAF\u02D8\u02D9\u02DA\xB8\u02DD\u02DB\u02C7" - }, - "ascii": { - "type": "_sbcs", - "chars": "\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD" - }, - "tis620": { - "type": "_sbcs", - "chars": "\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u0E01\u0E02\u0E03\u0E04\u0E05\u0E06\u0E07\u0E08\u0E09\u0E0A\u0E0B\u0E0C\u0E0D\u0E0E\u0E0F\u0E10\u0E11\u0E12\u0E13\u0E14\u0E15\u0E16\u0E17\u0E18\u0E19\u0E1A\u0E1B\u0E1C\u0E1D\u0E1E\u0E1F\u0E20\u0E21\u0E22\u0E23\u0E24\u0E25\u0E26\u0E27\u0E28\u0E29\u0E2A\u0E2B\u0E2C\u0E2D\u0E2E\u0E2F\u0E30\u0E31\u0E32\u0E33\u0E34\u0E35\u0E36\u0E37\u0E38\u0E39\u0E3A\uFFFD\uFFFD\uFFFD\uFFFD\u0E3F\u0E40\u0E41\u0E42\u0E43\u0E44\u0E45\u0E46\u0E47\u0E48\u0E49\u0E4A\u0E4B\u0E4C\u0E4D\u0E4E\u0E4F\u0E50\u0E51\u0E52\u0E53\u0E54\u0E55\u0E56\u0E57\u0E58\u0E59\u0E5A\u0E5B\uFFFD\uFFFD\uFFFD\uFFFD" - } - }; - } -}); - -// node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/encodings/dbcs-codec.js -var require_dbcs_codec = __commonJS({ - "node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/encodings/dbcs-codec.js"(exports) { - "use strict"; - var Buffer2 = require_safer().Buffer; - exports._dbcs = DBCSCodec; - var UNASSIGNED = -1; - var GB18030_CODE = -2; - var SEQ_START = -10; - var NODE_START = -1e3; - var UNASSIGNED_NODE = new Array(256); - var DEF_CHAR = -1; - for (i5 = 0; i5 < 256; i5++) { - UNASSIGNED_NODE[i5] = UNASSIGNED; - } - var i5; - function DBCSCodec(codecOptions, iconv) { - this.encodingName = codecOptions.encodingName; - if (!codecOptions) { - throw new Error("DBCS codec is called without the data."); - } - if (!codecOptions.table) { - throw new Error("Encoding '" + this.encodingName + "' has no data."); - } - var mappingTable = codecOptions.table(); - this.decodeTables = []; - this.decodeTables[0] = UNASSIGNED_NODE.slice(0); - this.decodeTableSeq = []; - for (var i6 = 0; i6 < mappingTable.length; i6++) { - this._addDecodeChunk(mappingTable[i6]); - } - if (typeof codecOptions.gb18030 === "function") { - this.gb18030 = codecOptions.gb18030(); - var commonThirdByteNodeIdx = this.decodeTables.length; - this.decodeTables.push(UNASSIGNED_NODE.slice(0)); - var commonFourthByteNodeIdx = this.decodeTables.length; - this.decodeTables.push(UNASSIGNED_NODE.slice(0)); - var firstByteNode = this.decodeTables[0]; - for (var i6 = 129; i6 <= 254; i6++) { - var secondByteNode = this.decodeTables[NODE_START - firstByteNode[i6]]; - for (var j5 = 48; j5 <= 57; j5++) { - if (secondByteNode[j5] === UNASSIGNED) { - secondByteNode[j5] = NODE_START - commonThirdByteNodeIdx; - } else if (secondByteNode[j5] > NODE_START) { - throw new Error("gb18030 decode tables conflict at byte 2"); - } - var thirdByteNode = this.decodeTables[NODE_START - secondByteNode[j5]]; - for (var k5 = 129; k5 <= 254; k5++) { - if (thirdByteNode[k5] === UNASSIGNED) { - thirdByteNode[k5] = NODE_START - commonFourthByteNodeIdx; - } else if (thirdByteNode[k5] === NODE_START - commonFourthByteNodeIdx) { - continue; - } else if (thirdByteNode[k5] > NODE_START) { - throw new Error("gb18030 decode tables conflict at byte 3"); - } - var fourthByteNode = this.decodeTables[NODE_START - thirdByteNode[k5]]; - for (var l5 = 48; l5 <= 57; l5++) { - if (fourthByteNode[l5] === UNASSIGNED) { - fourthByteNode[l5] = GB18030_CODE; - } - } - } - } - } - } - this.defaultCharUnicode = iconv.defaultCharUnicode; - this.encodeTable = []; - this.encodeTableSeq = []; - var skipEncodeChars = {}; - if (codecOptions.encodeSkipVals) { - for (var i6 = 0; i6 < codecOptions.encodeSkipVals.length; i6++) { - var val = codecOptions.encodeSkipVals[i6]; - if (typeof val === "number") { - skipEncodeChars[val] = true; - } else { - for (var j5 = val.from; j5 <= val.to; j5++) { - skipEncodeChars[j5] = true; - } - } - } - } - this._fillEncodeTable(0, 0, skipEncodeChars); - if (codecOptions.encodeAdd) { - for (var uChar in codecOptions.encodeAdd) { - if (Object.prototype.hasOwnProperty.call(codecOptions.encodeAdd, uChar)) { - this._setEncodeChar(uChar.charCodeAt(0), codecOptions.encodeAdd[uChar]); - } - } - } - this.defCharSB = this.encodeTable[0][iconv.defaultCharSingleByte.charCodeAt(0)]; - if (this.defCharSB === UNASSIGNED) this.defCharSB = this.encodeTable[0]["?"]; - if (this.defCharSB === UNASSIGNED) this.defCharSB = "?".charCodeAt(0); - } - DBCSCodec.prototype.encoder = DBCSEncoder; - DBCSCodec.prototype.decoder = DBCSDecoder; - DBCSCodec.prototype._getDecodeTrieNode = function(addr) { - var bytes = []; - for (; addr > 0; addr >>>= 8) { - bytes.push(addr & 255); - } - if (bytes.length == 0) { - bytes.push(0); - } - var node = this.decodeTables[0]; - for (var i6 = bytes.length - 1; i6 > 0; i6--) { - var val = node[bytes[i6]]; - if (val == UNASSIGNED) { - node[bytes[i6]] = NODE_START - this.decodeTables.length; - this.decodeTables.push(node = UNASSIGNED_NODE.slice(0)); - } else if (val <= NODE_START) { - node = this.decodeTables[NODE_START - val]; - } else { - throw new Error("Overwrite byte in " + this.encodingName + ", addr: " + addr.toString(16)); - } - } - return node; - }; - DBCSCodec.prototype._addDecodeChunk = function(chunk) { - var curAddr = parseInt(chunk[0], 16); - var writeTable = this._getDecodeTrieNode(curAddr); - curAddr = curAddr & 255; - for (var k5 = 1; k5 < chunk.length; k5++) { - var part = chunk[k5]; - if (typeof part === "string") { - for (var l5 = 0; l5 < part.length; ) { - var code = part.charCodeAt(l5++); - if (code >= 55296 && code < 56320) { - var codeTrail = part.charCodeAt(l5++); - if (codeTrail >= 56320 && codeTrail < 57344) { - writeTable[curAddr++] = 65536 + (code - 55296) * 1024 + (codeTrail - 56320); - } else { - throw new Error("Incorrect surrogate pair in " + this.encodingName + " at chunk " + chunk[0]); - } - } else if (code > 4080 && code <= 4095) { - var len = 4095 - code + 2; - var seq = []; - for (var m5 = 0; m5 < len; m5++) { - seq.push(part.charCodeAt(l5++)); - } - writeTable[curAddr++] = SEQ_START - this.decodeTableSeq.length; - this.decodeTableSeq.push(seq); - } else { - writeTable[curAddr++] = code; - } - } - } else if (typeof part === "number") { - var charCode = writeTable[curAddr - 1] + 1; - for (var l5 = 0; l5 < part; l5++) { - writeTable[curAddr++] = charCode++; - } - } else { - throw new Error("Incorrect type '" + typeof part + "' given in " + this.encodingName + " at chunk " + chunk[0]); - } - } - if (curAddr > 255) { - throw new Error("Incorrect chunk in " + this.encodingName + " at addr " + chunk[0] + ": too long" + curAddr); - } - }; - DBCSCodec.prototype._getEncodeBucket = function(uCode) { - var high = uCode >> 8; - if (this.encodeTable[high] === void 0) { - this.encodeTable[high] = UNASSIGNED_NODE.slice(0); - } - return this.encodeTable[high]; - }; - DBCSCodec.prototype._setEncodeChar = function(uCode, dbcsCode) { - var bucket = this._getEncodeBucket(uCode); - var low = uCode & 255; - if (bucket[low] <= SEQ_START) { - this.encodeTableSeq[SEQ_START - bucket[low]][DEF_CHAR] = dbcsCode; - } else if (bucket[low] == UNASSIGNED) { - bucket[low] = dbcsCode; - } - }; - DBCSCodec.prototype._setEncodeSequence = function(seq, dbcsCode) { - var uCode = seq[0]; - var bucket = this._getEncodeBucket(uCode); - var low = uCode & 255; - var node; - if (bucket[low] <= SEQ_START) { - node = this.encodeTableSeq[SEQ_START - bucket[low]]; - } else { - node = {}; - if (bucket[low] !== UNASSIGNED) node[DEF_CHAR] = bucket[low]; - bucket[low] = SEQ_START - this.encodeTableSeq.length; - this.encodeTableSeq.push(node); - } - for (var j5 = 1; j5 < seq.length - 1; j5++) { - var oldVal = node[uCode]; - if (typeof oldVal === "object") { - node = oldVal; - } else { - node = node[uCode] = {}; - if (oldVal !== void 0) { - node[DEF_CHAR] = oldVal; - } - } - } - uCode = seq[seq.length - 1]; - node[uCode] = dbcsCode; - }; - DBCSCodec.prototype._fillEncodeTable = function(nodeIdx, prefix, skipEncodeChars) { - var node = this.decodeTables[nodeIdx]; - var hasValues = false; - var subNodeEmpty = {}; - for (var i6 = 0; i6 < 256; i6++) { - var uCode = node[i6]; - var mbCode = prefix + i6; - if (skipEncodeChars[mbCode]) { - continue; - } - if (uCode >= 0) { - this._setEncodeChar(uCode, mbCode); - hasValues = true; - } else if (uCode <= NODE_START) { - var subNodeIdx = NODE_START - uCode; - if (!subNodeEmpty[subNodeIdx]) { - var newPrefix = mbCode << 8 >>> 0; - if (this._fillEncodeTable(subNodeIdx, newPrefix, skipEncodeChars)) { - hasValues = true; - } else { - subNodeEmpty[subNodeIdx] = true; - } - } - } else if (uCode <= SEQ_START) { - this._setEncodeSequence(this.decodeTableSeq[SEQ_START - uCode], mbCode); - hasValues = true; - } - } - return hasValues; - }; - function DBCSEncoder(options, codec2) { - this.leadSurrogate = -1; - this.seqObj = void 0; - this.encodeTable = codec2.encodeTable; - this.encodeTableSeq = codec2.encodeTableSeq; - this.defaultCharSingleByte = codec2.defCharSB; - this.gb18030 = codec2.gb18030; - } - DBCSEncoder.prototype.write = function(str) { - var newBuf = Buffer2.alloc(str.length * (this.gb18030 ? 4 : 3)); - var leadSurrogate = this.leadSurrogate; - var seqObj = this.seqObj; - var nextChar = -1; - var i6 = 0; - var j5 = 0; - while (true) { - if (nextChar === -1) { - if (i6 == str.length) break; - var uCode = str.charCodeAt(i6++); - } else { - var uCode = nextChar; - nextChar = -1; - } - if (uCode >= 55296 && uCode < 57344) { - if (uCode < 56320) { - if (leadSurrogate === -1) { - leadSurrogate = uCode; - continue; - } else { - leadSurrogate = uCode; - uCode = UNASSIGNED; - } - } else { - if (leadSurrogate !== -1) { - uCode = 65536 + (leadSurrogate - 55296) * 1024 + (uCode - 56320); - leadSurrogate = -1; - } else { - uCode = UNASSIGNED; - } - } - } else if (leadSurrogate !== -1) { - nextChar = uCode; - uCode = UNASSIGNED; - leadSurrogate = -1; - } - var dbcsCode = UNASSIGNED; - if (seqObj !== void 0 && uCode != UNASSIGNED) { - var resCode = seqObj[uCode]; - if (typeof resCode === "object") { - seqObj = resCode; - continue; - } else if (typeof resCode === "number") { - dbcsCode = resCode; - } else if (resCode == void 0) { - resCode = seqObj[DEF_CHAR]; - if (resCode !== void 0) { - dbcsCode = resCode; - nextChar = uCode; - } else { - } - } - seqObj = void 0; - } else if (uCode >= 0) { - var subtable = this.encodeTable[uCode >> 8]; - if (subtable !== void 0) { - dbcsCode = subtable[uCode & 255]; - } - if (dbcsCode <= SEQ_START) { - seqObj = this.encodeTableSeq[SEQ_START - dbcsCode]; - continue; - } - if (dbcsCode == UNASSIGNED && this.gb18030) { - var idx = findIdx(this.gb18030.uChars, uCode); - if (idx != -1) { - var dbcsCode = this.gb18030.gbChars[idx] + (uCode - this.gb18030.uChars[idx]); - newBuf[j5++] = 129 + Math.floor(dbcsCode / 12600); - dbcsCode = dbcsCode % 12600; - newBuf[j5++] = 48 + Math.floor(dbcsCode / 1260); - dbcsCode = dbcsCode % 1260; - newBuf[j5++] = 129 + Math.floor(dbcsCode / 10); - dbcsCode = dbcsCode % 10; - newBuf[j5++] = 48 + dbcsCode; - continue; - } - } - } - if (dbcsCode === UNASSIGNED) { - dbcsCode = this.defaultCharSingleByte; - } - if (dbcsCode < 256) { - newBuf[j5++] = dbcsCode; - } else if (dbcsCode < 65536) { - newBuf[j5++] = dbcsCode >> 8; - newBuf[j5++] = dbcsCode & 255; - } else if (dbcsCode < 16777216) { - newBuf[j5++] = dbcsCode >> 16; - newBuf[j5++] = dbcsCode >> 8 & 255; - newBuf[j5++] = dbcsCode & 255; - } else { - newBuf[j5++] = dbcsCode >>> 24; - newBuf[j5++] = dbcsCode >>> 16 & 255; - newBuf[j5++] = dbcsCode >>> 8 & 255; - newBuf[j5++] = dbcsCode & 255; - } - } - this.seqObj = seqObj; - this.leadSurrogate = leadSurrogate; - return newBuf.slice(0, j5); - }; - DBCSEncoder.prototype.end = function() { - if (this.leadSurrogate === -1 && this.seqObj === void 0) { - return; - } - var newBuf = Buffer2.alloc(10); - var j5 = 0; - if (this.seqObj) { - var dbcsCode = this.seqObj[DEF_CHAR]; - if (dbcsCode !== void 0) { - if (dbcsCode < 256) { - newBuf[j5++] = dbcsCode; - } else { - newBuf[j5++] = dbcsCode >> 8; - newBuf[j5++] = dbcsCode & 255; - } - } else { - } - this.seqObj = void 0; - } - if (this.leadSurrogate !== -1) { - newBuf[j5++] = this.defaultCharSingleByte; - this.leadSurrogate = -1; - } - return newBuf.slice(0, j5); - }; - DBCSEncoder.prototype.findIdx = findIdx; - function DBCSDecoder(options, codec2) { - this.nodeIdx = 0; - this.prevBytes = []; - this.decodeTables = codec2.decodeTables; - this.decodeTableSeq = codec2.decodeTableSeq; - this.defaultCharUnicode = codec2.defaultCharUnicode; - this.gb18030 = codec2.gb18030; - } - DBCSDecoder.prototype.write = function(buf) { - var newBuf = Buffer2.alloc(buf.length * 2); - var nodeIdx = this.nodeIdx; - var prevBytes = this.prevBytes; - var prevOffset = this.prevBytes.length; - var seqStart = -this.prevBytes.length; - var uCode; - for (var i6 = 0, j5 = 0; i6 < buf.length; i6++) { - var curByte = i6 >= 0 ? buf[i6] : prevBytes[i6 + prevOffset]; - var uCode = this.decodeTables[nodeIdx][curByte]; - if (uCode >= 0) { - } else if (uCode === UNASSIGNED) { - uCode = this.defaultCharUnicode.charCodeAt(0); - i6 = seqStart; - } else if (uCode === GB18030_CODE) { - if (i6 >= 3) { - var ptr = (buf[i6 - 3] - 129) * 12600 + (buf[i6 - 2] - 48) * 1260 + (buf[i6 - 1] - 129) * 10 + (curByte - 48); - } else { - var ptr = (prevBytes[i6 - 3 + prevOffset] - 129) * 12600 + ((i6 - 2 >= 0 ? buf[i6 - 2] : prevBytes[i6 - 2 + prevOffset]) - 48) * 1260 + ((i6 - 1 >= 0 ? buf[i6 - 1] : prevBytes[i6 - 1 + prevOffset]) - 129) * 10 + (curByte - 48); - } - var idx = findIdx(this.gb18030.gbChars, ptr); - uCode = this.gb18030.uChars[idx] + ptr - this.gb18030.gbChars[idx]; - } else if (uCode <= NODE_START) { - nodeIdx = NODE_START - uCode; - continue; - } else if (uCode <= SEQ_START) { - var seq = this.decodeTableSeq[SEQ_START - uCode]; - for (var k5 = 0; k5 < seq.length - 1; k5++) { - uCode = seq[k5]; - newBuf[j5++] = uCode & 255; - newBuf[j5++] = uCode >> 8; - } - uCode = seq[seq.length - 1]; - } else { - throw new Error("iconv-lite internal error: invalid decoding table value " + uCode + " at " + nodeIdx + "/" + curByte); - } - if (uCode >= 65536) { - uCode -= 65536; - var uCodeLead = 55296 | uCode >> 10; - newBuf[j5++] = uCodeLead & 255; - newBuf[j5++] = uCodeLead >> 8; - uCode = 56320 | uCode & 1023; - } - newBuf[j5++] = uCode & 255; - newBuf[j5++] = uCode >> 8; - nodeIdx = 0; - seqStart = i6 + 1; - } - this.nodeIdx = nodeIdx; - this.prevBytes = seqStart >= 0 ? Array.prototype.slice.call(buf, seqStart) : prevBytes.slice(seqStart + prevOffset).concat(Array.prototype.slice.call(buf)); - return newBuf.slice(0, j5).toString("ucs2"); - }; - DBCSDecoder.prototype.end = function() { - var ret = ""; - while (this.prevBytes.length > 0) { - ret += this.defaultCharUnicode; - var bytesArr = this.prevBytes.slice(1); - this.prevBytes = []; - this.nodeIdx = 0; - if (bytesArr.length > 0) { - ret += this.write(bytesArr); - } - } - this.prevBytes = []; - this.nodeIdx = 0; - return ret; - }; - function findIdx(table, val) { - if (table[0] > val) { - return -1; - } - var l5 = 0; - var r5 = table.length; - while (l5 < r5 - 1) { - var mid = l5 + (r5 - l5 + 1 >> 1); - if (table[mid] <= val) { - l5 = mid; - } else { - r5 = mid; - } - } - return l5; - } - } -}); - -// node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/encodings/tables/shiftjis.json -var require_shiftjis = __commonJS({ - "node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/encodings/tables/shiftjis.json"(exports, module) { - module.exports = [ - ["0", "\0", 128], - ["a1", "\uFF61", 62], - ["8140", "\u3000\u3001\u3002\uFF0C\uFF0E\u30FB\uFF1A\uFF1B\uFF1F\uFF01\u309B\u309C\xB4\uFF40\xA8\uFF3E\uFFE3\uFF3F\u30FD\u30FE\u309D\u309E\u3003\u4EDD\u3005\u3006\u3007\u30FC\u2015\u2010\uFF0F\uFF3C\uFF5E\u2225\uFF5C\u2026\u2025\u2018\u2019\u201C\u201D\uFF08\uFF09\u3014\u3015\uFF3B\uFF3D\uFF5B\uFF5D\u3008", 9, "\uFF0B\uFF0D\xB1\xD7"], - ["8180", "\xF7\uFF1D\u2260\uFF1C\uFF1E\u2266\u2267\u221E\u2234\u2642\u2640\xB0\u2032\u2033\u2103\uFFE5\uFF04\uFFE0\uFFE1\uFF05\uFF03\uFF06\uFF0A\uFF20\xA7\u2606\u2605\u25CB\u25CF\u25CE\u25C7\u25C6\u25A1\u25A0\u25B3\u25B2\u25BD\u25BC\u203B\u3012\u2192\u2190\u2191\u2193\u3013"], - ["81b8", "\u2208\u220B\u2286\u2287\u2282\u2283\u222A\u2229"], - ["81c8", "\u2227\u2228\uFFE2\u21D2\u21D4\u2200\u2203"], - ["81da", "\u2220\u22A5\u2312\u2202\u2207\u2261\u2252\u226A\u226B\u221A\u223D\u221D\u2235\u222B\u222C"], - ["81f0", "\u212B\u2030\u266F\u266D\u266A\u2020\u2021\xB6"], - ["81fc", "\u25EF"], - ["824f", "\uFF10", 9], - ["8260", "\uFF21", 25], - ["8281", "\uFF41", 25], - ["829f", "\u3041", 82], - ["8340", "\u30A1", 62], - ["8380", "\u30E0", 22], - ["839f", "\u0391", 16, "\u03A3", 6], - ["83bf", "\u03B1", 16, "\u03C3", 6], - ["8440", "\u0410", 5, "\u0401\u0416", 25], - ["8470", "\u0430", 5, "\u0451\u0436", 7], - ["8480", "\u043E", 17], - ["849f", "\u2500\u2502\u250C\u2510\u2518\u2514\u251C\u252C\u2524\u2534\u253C\u2501\u2503\u250F\u2513\u251B\u2517\u2523\u2533\u252B\u253B\u254B\u2520\u252F\u2528\u2537\u253F\u251D\u2530\u2525\u2538\u2542"], - ["8740", "\u2460", 19, "\u2160", 9], - ["875f", "\u3349\u3314\u3322\u334D\u3318\u3327\u3303\u3336\u3351\u3357\u330D\u3326\u3323\u332B\u334A\u333B\u339C\u339D\u339E\u338E\u338F\u33C4\u33A1"], - ["877e", "\u337B"], - ["8780", "\u301D\u301F\u2116\u33CD\u2121\u32A4", 4, "\u3231\u3232\u3239\u337E\u337D\u337C\u2252\u2261\u222B\u222E\u2211\u221A\u22A5\u2220\u221F\u22BF\u2235\u2229\u222A"], - ["889f", "\u4E9C\u5516\u5A03\u963F\u54C0\u611B\u6328\u59F6\u9022\u8475\u831C\u7A50\u60AA\u63E1\u6E25\u65ED\u8466\u82A6\u9BF5\u6893\u5727\u65A1\u6271\u5B9B\u59D0\u867B\u98F4\u7D62\u7DBE\u9B8E\u6216\u7C9F\u88B7\u5B89\u5EB5\u6309\u6697\u6848\u95C7\u978D\u674F\u4EE5\u4F0A\u4F4D\u4F9D\u5049\u56F2\u5937\u59D4\u5A01\u5C09\u60DF\u610F\u6170\u6613\u6905\u70BA\u754F\u7570\u79FB\u7DAD\u7DEF\u80C3\u840E\u8863\u8B02\u9055\u907A\u533B\u4E95\u4EA5\u57DF\u80B2\u90C1\u78EF\u4E00\u58F1\u6EA2\u9038\u7A32\u8328\u828B\u9C2F\u5141\u5370\u54BD\u54E1\u56E0\u59FB\u5F15\u98F2\u6DEB\u80E4\u852D"], - ["8940", "\u9662\u9670\u96A0\u97FB\u540B\u53F3\u5B87\u70CF\u7FBD\u8FC2\u96E8\u536F\u9D5C\u7ABA\u4E11\u7893\u81FC\u6E26\u5618\u5504\u6B1D\u851A\u9C3B\u59E5\u53A9\u6D66\u74DC\u958F\u5642\u4E91\u904B\u96F2\u834F\u990C\u53E1\u55B6\u5B30\u5F71\u6620\u66F3\u6804\u6C38\u6CF3\u6D29\u745B\u76C8\u7A4E\u9834\u82F1\u885B\u8A60\u92ED\u6DB2\u75AB\u76CA\u99C5\u60A6\u8B01\u8D8A\u95B2\u698E\u53AD\u5186"], - ["8980", "\u5712\u5830\u5944\u5BB4\u5EF6\u6028\u63A9\u63F4\u6CBF\u6F14\u708E\u7114\u7159\u71D5\u733F\u7E01\u8276\u82D1\u8597\u9060\u925B\u9D1B\u5869\u65BC\u6C5A\u7525\u51F9\u592E\u5965\u5F80\u5FDC\u62BC\u65FA\u6A2A\u6B27\u6BB4\u738B\u7FC1\u8956\u9D2C\u9D0E\u9EC4\u5CA1\u6C96\u837B\u5104\u5C4B\u61B6\u81C6\u6876\u7261\u4E59\u4FFA\u5378\u6069\u6E29\u7A4F\u97F3\u4E0B\u5316\u4EEE\u4F55\u4F3D\u4FA1\u4F73\u52A0\u53EF\u5609\u590F\u5AC1\u5BB6\u5BE1\u79D1\u6687\u679C\u67B6\u6B4C\u6CB3\u706B\u73C2\u798D\u79BE\u7A3C\u7B87\u82B1\u82DB\u8304\u8377\u83EF\u83D3\u8766\u8AB2\u5629\u8CA8\u8FE6\u904E\u971E\u868A\u4FC4\u5CE8\u6211\u7259\u753B\u81E5\u82BD\u86FE\u8CC0\u96C5\u9913\u99D5\u4ECB\u4F1A\u89E3\u56DE\u584A\u58CA\u5EFB\u5FEB\u602A\u6094\u6062\u61D0\u6212\u62D0\u6539"], - ["8a40", "\u9B41\u6666\u68B0\u6D77\u7070\u754C\u7686\u7D75\u82A5\u87F9\u958B\u968E\u8C9D\u51F1\u52BE\u5916\u54B3\u5BB3\u5D16\u6168\u6982\u6DAF\u788D\u84CB\u8857\u8A72\u93A7\u9AB8\u6D6C\u99A8\u86D9\u57A3\u67FF\u86CE\u920E\u5283\u5687\u5404\u5ED3\u62E1\u64B9\u683C\u6838\u6BBB\u7372\u78BA\u7A6B\u899A\u89D2\u8D6B\u8F03\u90ED\u95A3\u9694\u9769\u5B66\u5CB3\u697D\u984D\u984E\u639B\u7B20\u6A2B"], - ["8a80", "\u6A7F\u68B6\u9C0D\u6F5F\u5272\u559D\u6070\u62EC\u6D3B\u6E07\u6ED1\u845B\u8910\u8F44\u4E14\u9C39\u53F6\u691B\u6A3A\u9784\u682A\u515C\u7AC3\u84B2\u91DC\u938C\u565B\u9D28\u6822\u8305\u8431\u7CA5\u5208\u82C5\u74E6\u4E7E\u4F83\u51A0\u5BD2\u520A\u52D8\u52E7\u5DFB\u559A\u582A\u59E6\u5B8C\u5B98\u5BDB\u5E72\u5E79\u60A3\u611F\u6163\u61BE\u63DB\u6562\u67D1\u6853\u68FA\u6B3E\u6B53\u6C57\u6F22\u6F97\u6F45\u74B0\u7518\u76E3\u770B\u7AFF\u7BA1\u7C21\u7DE9\u7F36\u7FF0\u809D\u8266\u839E\u89B3\u8ACC\u8CAB\u9084\u9451\u9593\u9591\u95A2\u9665\u97D3\u9928\u8218\u4E38\u542B\u5CB8\u5DCC\u73A9\u764C\u773C\u5CA9\u7FEB\u8D0B\u96C1\u9811\u9854\u9858\u4F01\u4F0E\u5371\u559C\u5668\u57FA\u5947\u5B09\u5BC4\u5C90\u5E0C\u5E7E\u5FCC\u63EE\u673A\u65D7\u65E2\u671F\u68CB\u68C4"], - ["8b40", "\u6A5F\u5E30\u6BC5\u6C17\u6C7D\u757F\u7948\u5B63\u7A00\u7D00\u5FBD\u898F\u8A18\u8CB4\u8D77\u8ECC\u8F1D\u98E2\u9A0E\u9B3C\u4E80\u507D\u5100\u5993\u5B9C\u622F\u6280\u64EC\u6B3A\u72A0\u7591\u7947\u7FA9\u87FB\u8ABC\u8B70\u63AC\u83CA\u97A0\u5409\u5403\u55AB\u6854\u6A58\u8A70\u7827\u6775\u9ECD\u5374\u5BA2\u811A\u8650\u9006\u4E18\u4E45\u4EC7\u4F11\u53CA\u5438\u5BAE\u5F13\u6025\u6551"], - ["8b80", "\u673D\u6C42\u6C72\u6CE3\u7078\u7403\u7A76\u7AAE\u7B08\u7D1A\u7CFE\u7D66\u65E7\u725B\u53BB\u5C45\u5DE8\u62D2\u62E0\u6319\u6E20\u865A\u8A31\u8DDD\u92F8\u6F01\u79A6\u9B5A\u4EA8\u4EAB\u4EAC\u4F9B\u4FA0\u50D1\u5147\u7AF6\u5171\u51F6\u5354\u5321\u537F\u53EB\u55AC\u5883\u5CE1\u5F37\u5F4A\u602F\u6050\u606D\u631F\u6559\u6A4B\u6CC1\u72C2\u72ED\u77EF\u80F8\u8105\u8208\u854E\u90F7\u93E1\u97FF\u9957\u9A5A\u4EF0\u51DD\u5C2D\u6681\u696D\u5C40\u66F2\u6975\u7389\u6850\u7C81\u50C5\u52E4\u5747\u5DFE\u9326\u65A4\u6B23\u6B3D\u7434\u7981\u79BD\u7B4B\u7DCA\u82B9\u83CC\u887F\u895F\u8B39\u8FD1\u91D1\u541F\u9280\u4E5D\u5036\u53E5\u533A\u72D7\u7396\u77E9\u82E6\u8EAF\u99C6\u99C8\u99D2\u5177\u611A\u865E\u55B0\u7A7A\u5076\u5BD3\u9047\u9685\u4E32\u6ADB\u91E7\u5C51\u5C48"], - ["8c40", "\u6398\u7A9F\u6C93\u9774\u8F61\u7AAA\u718A\u9688\u7C82\u6817\u7E70\u6851\u936C\u52F2\u541B\u85AB\u8A13\u7FA4\u8ECD\u90E1\u5366\u8888\u7941\u4FC2\u50BE\u5211\u5144\u5553\u572D\u73EA\u578B\u5951\u5F62\u5F84\u6075\u6176\u6167\u61A9\u63B2\u643A\u656C\u666F\u6842\u6E13\u7566\u7A3D\u7CFB\u7D4C\u7D99\u7E4B\u7F6B\u830E\u834A\u86CD\u8A08\u8A63\u8B66\u8EFD\u981A\u9D8F\u82B8\u8FCE\u9BE8"], - ["8c80", "\u5287\u621F\u6483\u6FC0\u9699\u6841\u5091\u6B20\u6C7A\u6F54\u7A74\u7D50\u8840\u8A23\u6708\u4EF6\u5039\u5026\u5065\u517C\u5238\u5263\u55A7\u570F\u5805\u5ACC\u5EFA\u61B2\u61F8\u62F3\u6372\u691C\u6A29\u727D\u72AC\u732E\u7814\u786F\u7D79\u770C\u80A9\u898B\u8B19\u8CE2\u8ED2\u9063\u9375\u967A\u9855\u9A13\u9E78\u5143\u539F\u53B3\u5E7B\u5F26\u6E1B\u6E90\u7384\u73FE\u7D43\u8237\u8A00\u8AFA\u9650\u4E4E\u500B\u53E4\u547C\u56FA\u59D1\u5B64\u5DF1\u5EAB\u5F27\u6238\u6545\u67AF\u6E56\u72D0\u7CCA\u88B4\u80A1\u80E1\u83F0\u864E\u8A87\u8DE8\u9237\u96C7\u9867\u9F13\u4E94\u4E92\u4F0D\u5348\u5449\u543E\u5A2F\u5F8C\u5FA1\u609F\u68A7\u6A8E\u745A\u7881\u8A9E\u8AA4\u8B77\u9190\u4E5E\u9BC9\u4EA4\u4F7C\u4FAF\u5019\u5016\u5149\u516C\u529F\u52B9\u52FE\u539A\u53E3\u5411"], - ["8d40", "\u540E\u5589\u5751\u57A2\u597D\u5B54\u5B5D\u5B8F\u5DE5\u5DE7\u5DF7\u5E78\u5E83\u5E9A\u5EB7\u5F18\u6052\u614C\u6297\u62D8\u63A7\u653B\u6602\u6643\u66F4\u676D\u6821\u6897\u69CB\u6C5F\u6D2A\u6D69\u6E2F\u6E9D\u7532\u7687\u786C\u7A3F\u7CE0\u7D05\u7D18\u7D5E\u7DB1\u8015\u8003\u80AF\u80B1\u8154\u818F\u822A\u8352\u884C\u8861\u8B1B\u8CA2\u8CFC\u90CA\u9175\u9271\u783F\u92FC\u95A4\u964D"], - ["8d80", "\u9805\u9999\u9AD8\u9D3B\u525B\u52AB\u53F7\u5408\u58D5\u62F7\u6FE0\u8C6A\u8F5F\u9EB9\u514B\u523B\u544A\u56FD\u7A40\u9177\u9D60\u9ED2\u7344\u6F09\u8170\u7511\u5FFD\u60DA\u9AA8\u72DB\u8FBC\u6B64\u9803\u4ECA\u56F0\u5764\u58BE\u5A5A\u6068\u61C7\u660F\u6606\u6839\u68B1\u6DF7\u75D5\u7D3A\u826E\u9B42\u4E9B\u4F50\u53C9\u5506\u5D6F\u5DE6\u5DEE\u67FB\u6C99\u7473\u7802\u8A50\u9396\u88DF\u5750\u5EA7\u632B\u50B5\u50AC\u518D\u6700\u54C9\u585E\u59BB\u5BB0\u5F69\u624D\u63A1\u683D\u6B73\u6E08\u707D\u91C7\u7280\u7815\u7826\u796D\u658E\u7D30\u83DC\u88C1\u8F09\u969B\u5264\u5728\u6750\u7F6A\u8CA1\u51B4\u5742\u962A\u583A\u698A\u80B4\u54B2\u5D0E\u57FC\u7895\u9DFA\u4F5C\u524A\u548B\u643E\u6628\u6714\u67F5\u7A84\u7B56\u7D22\u932F\u685C\u9BAD\u7B39\u5319\u518A\u5237"], - ["8e40", "\u5BDF\u62F6\u64AE\u64E6\u672D\u6BBA\u85A9\u96D1\u7690\u9BD6\u634C\u9306\u9BAB\u76BF\u6652\u4E09\u5098\u53C2\u5C71\u60E8\u6492\u6563\u685F\u71E6\u73CA\u7523\u7B97\u7E82\u8695\u8B83\u8CDB\u9178\u9910\u65AC\u66AB\u6B8B\u4ED5\u4ED4\u4F3A\u4F7F\u523A\u53F8\u53F2\u55E3\u56DB\u58EB\u59CB\u59C9\u59FF\u5B50\u5C4D\u5E02\u5E2B\u5FD7\u601D\u6307\u652F\u5B5C\u65AF\u65BD\u65E8\u679D\u6B62"], - ["8e80", "\u6B7B\u6C0F\u7345\u7949\u79C1\u7CF8\u7D19\u7D2B\u80A2\u8102\u81F3\u8996\u8A5E\u8A69\u8A66\u8A8C\u8AEE\u8CC7\u8CDC\u96CC\u98FC\u6B6F\u4E8B\u4F3C\u4F8D\u5150\u5B57\u5BFA\u6148\u6301\u6642\u6B21\u6ECB\u6CBB\u723E\u74BD\u75D4\u78C1\u793A\u800C\u8033\u81EA\u8494\u8F9E\u6C50\u9E7F\u5F0F\u8B58\u9D2B\u7AFA\u8EF8\u5B8D\u96EB\u4E03\u53F1\u57F7\u5931\u5AC9\u5BA4\u6089\u6E7F\u6F06\u75BE\u8CEA\u5B9F\u8500\u7BE0\u5072\u67F4\u829D\u5C61\u854A\u7E1E\u820E\u5199\u5C04\u6368\u8D66\u659C\u716E\u793E\u7D17\u8005\u8B1D\u8ECA\u906E\u86C7\u90AA\u501F\u52FA\u5C3A\u6753\u707C\u7235\u914C\u91C8\u932B\u82E5\u5BC2\u5F31\u60F9\u4E3B\u53D6\u5B88\u624B\u6731\u6B8A\u72E9\u73E0\u7A2E\u816B\u8DA3\u9152\u9996\u5112\u53D7\u546A\u5BFF\u6388\u6A39\u7DAC\u9700\u56DA\u53CE\u5468"], - ["8f40", "\u5B97\u5C31\u5DDE\u4FEE\u6101\u62FE\u6D32\u79C0\u79CB\u7D42\u7E4D\u7FD2\u81ED\u821F\u8490\u8846\u8972\u8B90\u8E74\u8F2F\u9031\u914B\u916C\u96C6\u919C\u4EC0\u4F4F\u5145\u5341\u5F93\u620E\u67D4\u6C41\u6E0B\u7363\u7E26\u91CD\u9283\u53D4\u5919\u5BBF\u6DD1\u795D\u7E2E\u7C9B\u587E\u719F\u51FA\u8853\u8FF0\u4FCA\u5CFB\u6625\u77AC\u7AE3\u821C\u99FF\u51C6\u5FAA\u65EC\u696F\u6B89\u6DF3"], - ["8f80", "\u6E96\u6F64\u76FE\u7D14\u5DE1\u9075\u9187\u9806\u51E6\u521D\u6240\u6691\u66D9\u6E1A\u5EB6\u7DD2\u7F72\u66F8\u85AF\u85F7\u8AF8\u52A9\u53D9\u5973\u5E8F\u5F90\u6055\u92E4\u9664\u50B7\u511F\u52DD\u5320\u5347\u53EC\u54E8\u5546\u5531\u5617\u5968\u59BE\u5A3C\u5BB5\u5C06\u5C0F\u5C11\u5C1A\u5E84\u5E8A\u5EE0\u5F70\u627F\u6284\u62DB\u638C\u6377\u6607\u660C\u662D\u6676\u677E\u68A2\u6A1F\u6A35\u6CBC\u6D88\u6E09\u6E58\u713C\u7126\u7167\u75C7\u7701\u785D\u7901\u7965\u79F0\u7AE0\u7B11\u7CA7\u7D39\u8096\u83D6\u848B\u8549\u885D\u88F3\u8A1F\u8A3C\u8A54\u8A73\u8C61\u8CDE\u91A4\u9266\u937E\u9418\u969C\u9798\u4E0A\u4E08\u4E1E\u4E57\u5197\u5270\u57CE\u5834\u58CC\u5B22\u5E38\u60C5\u64FE\u6761\u6756\u6D44\u72B6\u7573\u7A63\u84B8\u8B72\u91B8\u9320\u5631\u57F4\u98FE"], - ["9040", "\u62ED\u690D\u6B96\u71ED\u7E54\u8077\u8272\u89E6\u98DF\u8755\u8FB1\u5C3B\u4F38\u4FE1\u4FB5\u5507\u5A20\u5BDD\u5BE9\u5FC3\u614E\u632F\u65B0\u664B\u68EE\u699B\u6D78\u6DF1\u7533\u75B9\u771F\u795E\u79E6\u7D33\u81E3\u82AF\u85AA\u89AA\u8A3A\u8EAB\u8F9B\u9032\u91DD\u9707\u4EBA\u4EC1\u5203\u5875\u58EC\u5C0B\u751A\u5C3D\u814E\u8A0A\u8FC5\u9663\u976D\u7B25\u8ACF\u9808\u9162\u56F3\u53A8"], - ["9080", "\u9017\u5439\u5782\u5E25\u63A8\u6C34\u708A\u7761\u7C8B\u7FE0\u8870\u9042\u9154\u9310\u9318\u968F\u745E\u9AC4\u5D07\u5D69\u6570\u67A2\u8DA8\u96DB\u636E\u6749\u6919\u83C5\u9817\u96C0\u88FE\u6F84\u647A\u5BF8\u4E16\u702C\u755D\u662F\u51C4\u5236\u52E2\u59D3\u5F81\u6027\u6210\u653F\u6574\u661F\u6674\u68F2\u6816\u6B63\u6E05\u7272\u751F\u76DB\u7CBE\u8056\u58F0\u88FD\u897F\u8AA0\u8A93\u8ACB\u901D\u9192\u9752\u9759\u6589\u7A0E\u8106\u96BB\u5E2D\u60DC\u621A\u65A5\u6614\u6790\u77F3\u7A4D\u7C4D\u7E3E\u810A\u8CAC\u8D64\u8DE1\u8E5F\u78A9\u5207\u62D9\u63A5\u6442\u6298\u8A2D\u7A83\u7BC0\u8AAC\u96EA\u7D76\u820C\u8749\u4ED9\u5148\u5343\u5360\u5BA3\u5C02\u5C16\u5DDD\u6226\u6247\u64B0\u6813\u6834\u6CC9\u6D45\u6D17\u67D3\u6F5C\u714E\u717D\u65CB\u7A7F\u7BAD\u7DDA"], - ["9140", "\u7E4A\u7FA8\u817A\u821B\u8239\u85A6\u8A6E\u8CCE\u8DF5\u9078\u9077\u92AD\u9291\u9583\u9BAE\u524D\u5584\u6F38\u7136\u5168\u7985\u7E55\u81B3\u7CCE\u564C\u5851\u5CA8\u63AA\u66FE\u66FD\u695A\u72D9\u758F\u758E\u790E\u7956\u79DF\u7C97\u7D20\u7D44\u8607\u8A34\u963B\u9061\u9F20\u50E7\u5275\u53CC\u53E2\u5009\u55AA\u58EE\u594F\u723D\u5B8B\u5C64\u531D\u60E3\u60F3\u635C\u6383\u633F\u63BB"], - ["9180", "\u64CD\u65E9\u66F9\u5DE3\u69CD\u69FD\u6F15\u71E5\u4E89\u75E9\u76F8\u7A93\u7CDF\u7DCF\u7D9C\u8061\u8349\u8358\u846C\u84BC\u85FB\u88C5\u8D70\u9001\u906D\u9397\u971C\u9A12\u50CF\u5897\u618E\u81D3\u8535\u8D08\u9020\u4FC3\u5074\u5247\u5373\u606F\u6349\u675F\u6E2C\u8DB3\u901F\u4FD7\u5C5E\u8CCA\u65CF\u7D9A\u5352\u8896\u5176\u63C3\u5B58\u5B6B\u5C0A\u640D\u6751\u905C\u4ED6\u591A\u592A\u6C70\u8A51\u553E\u5815\u59A5\u60F0\u6253\u67C1\u8235\u6955\u9640\u99C4\u9A28\u4F53\u5806\u5BFE\u8010\u5CB1\u5E2F\u5F85\u6020\u614B\u6234\u66FF\u6CF0\u6EDE\u80CE\u817F\u82D4\u888B\u8CB8\u9000\u902E\u968A\u9EDB\u9BDB\u4EE3\u53F0\u5927\u7B2C\u918D\u984C\u9DF9\u6EDD\u7027\u5353\u5544\u5B85\u6258\u629E\u62D3\u6CA2\u6FEF\u7422\u8A17\u9438\u6FC1\u8AFE\u8338\u51E7\u86F8\u53EA"], - ["9240", "\u53E9\u4F46\u9054\u8FB0\u596A\u8131\u5DFD\u7AEA\u8FBF\u68DA\u8C37\u72F8\u9C48\u6A3D\u8AB0\u4E39\u5358\u5606\u5766\u62C5\u63A2\u65E6\u6B4E\u6DE1\u6E5B\u70AD\u77ED\u7AEF\u7BAA\u7DBB\u803D\u80C6\u86CB\u8A95\u935B\u56E3\u58C7\u5F3E\u65AD\u6696\u6A80\u6BB5\u7537\u8AC7\u5024\u77E5\u5730\u5F1B\u6065\u667A\u6C60\u75F4\u7A1A\u7F6E\u81F4\u8718\u9045\u99B3\u7BC9\u755C\u7AF9\u7B51\u84C4"], - ["9280", "\u9010\u79E9\u7A92\u8336\u5AE1\u7740\u4E2D\u4EF2\u5B99\u5FE0\u62BD\u663C\u67F1\u6CE8\u866B\u8877\u8A3B\u914E\u92F3\u99D0\u6A17\u7026\u732A\u82E7\u8457\u8CAF\u4E01\u5146\u51CB\u558B\u5BF5\u5E16\u5E33\u5E81\u5F14\u5F35\u5F6B\u5FB4\u61F2\u6311\u66A2\u671D\u6F6E\u7252\u753A\u773A\u8074\u8139\u8178\u8776\u8ABF\u8ADC\u8D85\u8DF3\u929A\u9577\u9802\u9CE5\u52C5\u6357\u76F4\u6715\u6C88\u73CD\u8CC3\u93AE\u9673\u6D25\u589C\u690E\u69CC\u8FFD\u939A\u75DB\u901A\u585A\u6802\u63B4\u69FB\u4F43\u6F2C\u67D8\u8FBB\u8526\u7DB4\u9354\u693F\u6F70\u576A\u58F7\u5B2C\u7D2C\u722A\u540A\u91E3\u9DB4\u4EAD\u4F4E\u505C\u5075\u5243\u8C9E\u5448\u5824\u5B9A\u5E1D\u5E95\u5EAD\u5EF7\u5F1F\u608C\u62B5\u633A\u63D0\u68AF\u6C40\u7887\u798E\u7A0B\u7DE0\u8247\u8A02\u8AE6\u8E44\u9013"], - ["9340", "\u90B8\u912D\u91D8\u9F0E\u6CE5\u6458\u64E2\u6575\u6EF4\u7684\u7B1B\u9069\u93D1\u6EBA\u54F2\u5FB9\u64A4\u8F4D\u8FED\u9244\u5178\u586B\u5929\u5C55\u5E97\u6DFB\u7E8F\u751C\u8CBC\u8EE2\u985B\u70B9\u4F1D\u6BBF\u6FB1\u7530\u96FB\u514E\u5410\u5835\u5857\u59AC\u5C60\u5F92\u6597\u675C\u6E21\u767B\u83DF\u8CED\u9014\u90FD\u934D\u7825\u783A\u52AA\u5EA6\u571F\u5974\u6012\u5012\u515A\u51AC"], - ["9380", "\u51CD\u5200\u5510\u5854\u5858\u5957\u5B95\u5CF6\u5D8B\u60BC\u6295\u642D\u6771\u6843\u68BC\u68DF\u76D7\u6DD8\u6E6F\u6D9B\u706F\u71C8\u5F53\u75D8\u7977\u7B49\u7B54\u7B52\u7CD6\u7D71\u5230\u8463\u8569\u85E4\u8A0E\u8B04\u8C46\u8E0F\u9003\u900F\u9419\u9676\u982D\u9A30\u95D8\u50CD\u52D5\u540C\u5802\u5C0E\u61A7\u649E\u6D1E\u77B3\u7AE5\u80F4\u8404\u9053\u9285\u5CE0\u9D07\u533F\u5F97\u5FB3\u6D9C\u7279\u7763\u79BF\u7BE4\u6BD2\u72EC\u8AAD\u6803\u6A61\u51F8\u7A81\u6934\u5C4A\u9CF6\u82EB\u5BC5\u9149\u701E\u5678\u5C6F\u60C7\u6566\u6C8C\u8C5A\u9041\u9813\u5451\u66C7\u920D\u5948\u90A3\u5185\u4E4D\u51EA\u8599\u8B0E\u7058\u637A\u934B\u6962\u99B4\u7E04\u7577\u5357\u6960\u8EDF\u96E3\u6C5D\u4E8C\u5C3C\u5F10\u8FE9\u5302\u8CD1\u8089\u8679\u5EFF\u65E5\u4E73\u5165"], - ["9440", "\u5982\u5C3F\u97EE\u4EFB\u598A\u5FCD\u8A8D\u6FE1\u79B0\u7962\u5BE7\u8471\u732B\u71B1\u5E74\u5FF5\u637B\u649A\u71C3\u7C98\u4E43\u5EFC\u4E4B\u57DC\u56A2\u60A9\u6FC3\u7D0D\u80FD\u8133\u81BF\u8FB2\u8997\u86A4\u5DF4\u628A\u64AD\u8987\u6777\u6CE2\u6D3E\u7436\u7834\u5A46\u7F75\u82AD\u99AC\u4FF3\u5EC3\u62DD\u6392\u6557\u676F\u76C3\u724C\u80CC\u80BA\u8F29\u914D\u500D\u57F9\u5A92\u6885"], - ["9480", "\u6973\u7164\u72FD\u8CB7\u58F2\u8CE0\u966A\u9019\u877F\u79E4\u77E7\u8429\u4F2F\u5265\u535A\u62CD\u67CF\u6CCA\u767D\u7B94\u7C95\u8236\u8584\u8FEB\u66DD\u6F20\u7206\u7E1B\u83AB\u99C1\u9EA6\u51FD\u7BB1\u7872\u7BB8\u8087\u7B48\u6AE8\u5E61\u808C\u7551\u7560\u516B\u9262\u6E8C\u767A\u9197\u9AEA\u4F10\u7F70\u629C\u7B4F\u95A5\u9CE9\u567A\u5859\u86E4\u96BC\u4F34\u5224\u534A\u53CD\u53DB\u5E06\u642C\u6591\u677F\u6C3E\u6C4E\u7248\u72AF\u73ED\u7554\u7E41\u822C\u85E9\u8CA9\u7BC4\u91C6\u7169\u9812\u98EF\u633D\u6669\u756A\u76E4\u78D0\u8543\u86EE\u532A\u5351\u5426\u5983\u5E87\u5F7C\u60B2\u6249\u6279\u62AB\u6590\u6BD4\u6CCC\u75B2\u76AE\u7891\u79D8\u7DCB\u7F77\u80A5\u88AB\u8AB9\u8CBB\u907F\u975E\u98DB\u6A0B\u7C38\u5099\u5C3E\u5FAE\u6787\u6BD8\u7435\u7709\u7F8E"], - ["9540", "\u9F3B\u67CA\u7A17\u5339\u758B\u9AED\u5F66\u819D\u83F1\u8098\u5F3C\u5FC5\u7562\u7B46\u903C\u6867\u59EB\u5A9B\u7D10\u767E\u8B2C\u4FF5\u5F6A\u6A19\u6C37\u6F02\u74E2\u7968\u8868\u8A55\u8C79\u5EDF\u63CF\u75C5\u79D2\u82D7\u9328\u92F2\u849C\u86ED\u9C2D\u54C1\u5F6C\u658C\u6D5C\u7015\u8CA7\u8CD3\u983B\u654F\u74F6\u4E0D\u4ED8\u57E0\u592B\u5A66\u5BCC\u51A8\u5E03\u5E9C\u6016\u6276\u6577"], - ["9580", "\u65A7\u666E\u6D6E\u7236\u7B26\u8150\u819A\u8299\u8B5C\u8CA0\u8CE6\u8D74\u961C\u9644\u4FAE\u64AB\u6B66\u821E\u8461\u856A\u90E8\u5C01\u6953\u98A8\u847A\u8557\u4F0F\u526F\u5FA9\u5E45\u670D\u798F\u8179\u8907\u8986\u6DF5\u5F17\u6255\u6CB8\u4ECF\u7269\u9B92\u5206\u543B\u5674\u58B3\u61A4\u626E\u711A\u596E\u7C89\u7CDE\u7D1B\u96F0\u6587\u805E\u4E19\u4F75\u5175\u5840\u5E63\u5E73\u5F0A\u67C4\u4E26\u853D\u9589\u965B\u7C73\u9801\u50FB\u58C1\u7656\u78A7\u5225\u77A5\u8511\u7B86\u504F\u5909\u7247\u7BC7\u7DE8\u8FBA\u8FD4\u904D\u4FBF\u52C9\u5A29\u5F01\u97AD\u4FDD\u8217\u92EA\u5703\u6355\u6B69\u752B\u88DC\u8F14\u7A42\u52DF\u5893\u6155\u620A\u66AE\u6BCD\u7C3F\u83E9\u5023\u4FF8\u5305\u5446\u5831\u5949\u5B9D\u5CF0\u5CEF\u5D29\u5E96\u62B1\u6367\u653E\u65B9\u670B"], - ["9640", "\u6CD5\u6CE1\u70F9\u7832\u7E2B\u80DE\u82B3\u840C\u84EC\u8702\u8912\u8A2A\u8C4A\u90A6\u92D2\u98FD\u9CF3\u9D6C\u4E4F\u4EA1\u508D\u5256\u574A\u59A8\u5E3D\u5FD8\u5FD9\u623F\u66B4\u671B\u67D0\u68D2\u5192\u7D21\u80AA\u81A8\u8B00\u8C8C\u8CBF\u927E\u9632\u5420\u982C\u5317\u50D5\u535C\u58A8\u64B2\u6734\u7267\u7766\u7A46\u91E6\u52C3\u6CA1\u6B86\u5800\u5E4C\u5954\u672C\u7FFB\u51E1\u76C6"], - ["9680", "\u6469\u78E8\u9B54\u9EBB\u57CB\u59B9\u6627\u679A\u6BCE\u54E9\u69D9\u5E55\u819C\u6795\u9BAA\u67FE\u9C52\u685D\u4EA6\u4FE3\u53C8\u62B9\u672B\u6CAB\u8FC4\u4FAD\u7E6D\u9EBF\u4E07\u6162\u6E80\u6F2B\u8513\u5473\u672A\u9B45\u5DF3\u7B95\u5CAC\u5BC6\u871C\u6E4A\u84D1\u7A14\u8108\u5999\u7C8D\u6C11\u7720\u52D9\u5922\u7121\u725F\u77DB\u9727\u9D61\u690B\u5A7F\u5A18\u51A5\u540D\u547D\u660E\u76DF\u8FF7\u9298\u9CF4\u59EA\u725D\u6EC5\u514D\u68C9\u7DBF\u7DEC\u9762\u9EBA\u6478\u6A21\u8302\u5984\u5B5F\u6BDB\u731B\u76F2\u7DB2\u8017\u8499\u5132\u6728\u9ED9\u76EE\u6762\u52FF\u9905\u5C24\u623B\u7C7E\u8CB0\u554F\u60B6\u7D0B\u9580\u5301\u4E5F\u51B6\u591C\u723A\u8036\u91CE\u5F25\u77E2\u5384\u5F79\u7D04\u85AC\u8A33\u8E8D\u9756\u67F3\u85AE\u9453\u6109\u6108\u6CB9\u7652"], - ["9740", "\u8AED\u8F38\u552F\u4F51\u512A\u52C7\u53CB\u5BA5\u5E7D\u60A0\u6182\u63D6\u6709\u67DA\u6E67\u6D8C\u7336\u7337\u7531\u7950\u88D5\u8A98\u904A\u9091\u90F5\u96C4\u878D\u5915\u4E88\u4F59\u4E0E\u8A89\u8F3F\u9810\u50AD\u5E7C\u5996\u5BB9\u5EB8\u63DA\u63FA\u64C1\u66DC\u694A\u69D8\u6D0B\u6EB6\u7194\u7528\u7AAF\u7F8A\u8000\u8449\u84C9\u8981\u8B21\u8E0A\u9065\u967D\u990A\u617E\u6291\u6B32"], - ["9780", "\u6C83\u6D74\u7FCC\u7FFC\u6DC0\u7F85\u87BA\u88F8\u6765\u83B1\u983C\u96F7\u6D1B\u7D61\u843D\u916A\u4E71\u5375\u5D50\u6B04\u6FEB\u85CD\u862D\u89A7\u5229\u540F\u5C65\u674E\u68A8\u7406\u7483\u75E2\u88CF\u88E1\u91CC\u96E2\u9678\u5F8B\u7387\u7ACB\u844E\u63A0\u7565\u5289\u6D41\u6E9C\u7409\u7559\u786B\u7C92\u9686\u7ADC\u9F8D\u4FB6\u616E\u65C5\u865C\u4E86\u4EAE\u50DA\u4E21\u51CC\u5BEE\u6599\u6881\u6DBC\u731F\u7642\u77AD\u7A1C\u7CE7\u826F\u8AD2\u907C\u91CF\u9675\u9818\u529B\u7DD1\u502B\u5398\u6797\u6DCB\u71D0\u7433\u81E8\u8F2A\u96A3\u9C57\u9E9F\u7460\u5841\u6D99\u7D2F\u985E\u4EE4\u4F36\u4F8B\u51B7\u52B1\u5DBA\u601C\u73B2\u793C\u82D3\u9234\u96B7\u96F6\u970A\u9E97\u9F62\u66A6\u6B74\u5217\u52A3\u70C8\u88C2\u5EC9\u604B\u6190\u6F23\u7149\u7C3E\u7DF4\u806F"], - ["9840", "\u84EE\u9023\u932C\u5442\u9B6F\u6AD3\u7089\u8CC2\u8DEF\u9732\u52B4\u5A41\u5ECA\u5F04\u6717\u697C\u6994\u6D6A\u6F0F\u7262\u72FC\u7BED\u8001\u807E\u874B\u90CE\u516D\u9E93\u7984\u808B\u9332\u8AD6\u502D\u548C\u8A71\u6B6A\u8CC4\u8107\u60D1\u67A0\u9DF2\u4E99\u4E98\u9C10\u8A6B\u85C1\u8568\u6900\u6E7E\u7897\u8155"], - ["989f", "\u5F0C\u4E10\u4E15\u4E2A\u4E31\u4E36\u4E3C\u4E3F\u4E42\u4E56\u4E58\u4E82\u4E85\u8C6B\u4E8A\u8212\u5F0D\u4E8E\u4E9E\u4E9F\u4EA0\u4EA2\u4EB0\u4EB3\u4EB6\u4ECE\u4ECD\u4EC4\u4EC6\u4EC2\u4ED7\u4EDE\u4EED\u4EDF\u4EF7\u4F09\u4F5A\u4F30\u4F5B\u4F5D\u4F57\u4F47\u4F76\u4F88\u4F8F\u4F98\u4F7B\u4F69\u4F70\u4F91\u4F6F\u4F86\u4F96\u5118\u4FD4\u4FDF\u4FCE\u4FD8\u4FDB\u4FD1\u4FDA\u4FD0\u4FE4\u4FE5\u501A\u5028\u5014\u502A\u5025\u5005\u4F1C\u4FF6\u5021\u5029\u502C\u4FFE\u4FEF\u5011\u5006\u5043\u5047\u6703\u5055\u5050\u5048\u505A\u5056\u506C\u5078\u5080\u509A\u5085\u50B4\u50B2"], - ["9940", "\u50C9\u50CA\u50B3\u50C2\u50D6\u50DE\u50E5\u50ED\u50E3\u50EE\u50F9\u50F5\u5109\u5101\u5102\u5116\u5115\u5114\u511A\u5121\u513A\u5137\u513C\u513B\u513F\u5140\u5152\u514C\u5154\u5162\u7AF8\u5169\u516A\u516E\u5180\u5182\u56D8\u518C\u5189\u518F\u5191\u5193\u5195\u5196\u51A4\u51A6\u51A2\u51A9\u51AA\u51AB\u51B3\u51B1\u51B2\u51B0\u51B5\u51BD\u51C5\u51C9\u51DB\u51E0\u8655\u51E9\u51ED"], - ["9980", "\u51F0\u51F5\u51FE\u5204\u520B\u5214\u520E\u5227\u522A\u522E\u5233\u5239\u524F\u5244\u524B\u524C\u525E\u5254\u526A\u5274\u5269\u5273\u527F\u527D\u528D\u5294\u5292\u5271\u5288\u5291\u8FA8\u8FA7\u52AC\u52AD\u52BC\u52B5\u52C1\u52CD\u52D7\u52DE\u52E3\u52E6\u98ED\u52E0\u52F3\u52F5\u52F8\u52F9\u5306\u5308\u7538\u530D\u5310\u530F\u5315\u531A\u5323\u532F\u5331\u5333\u5338\u5340\u5346\u5345\u4E17\u5349\u534D\u51D6\u535E\u5369\u536E\u5918\u537B\u5377\u5382\u5396\u53A0\u53A6\u53A5\u53AE\u53B0\u53B6\u53C3\u7C12\u96D9\u53DF\u66FC\u71EE\u53EE\u53E8\u53ED\u53FA\u5401\u543D\u5440\u542C\u542D\u543C\u542E\u5436\u5429\u541D\u544E\u548F\u5475\u548E\u545F\u5471\u5477\u5470\u5492\u547B\u5480\u5476\u5484\u5490\u5486\u54C7\u54A2\u54B8\u54A5\u54AC\u54C4\u54C8\u54A8"], - ["9a40", "\u54AB\u54C2\u54A4\u54BE\u54BC\u54D8\u54E5\u54E6\u550F\u5514\u54FD\u54EE\u54ED\u54FA\u54E2\u5539\u5540\u5563\u554C\u552E\u555C\u5545\u5556\u5557\u5538\u5533\u555D\u5599\u5580\u54AF\u558A\u559F\u557B\u557E\u5598\u559E\u55AE\u557C\u5583\u55A9\u5587\u55A8\u55DA\u55C5\u55DF\u55C4\u55DC\u55E4\u55D4\u5614\u55F7\u5616\u55FE\u55FD\u561B\u55F9\u564E\u5650\u71DF\u5634\u5636\u5632\u5638"], - ["9a80", "\u566B\u5664\u562F\u566C\u566A\u5686\u5680\u568A\u56A0\u5694\u568F\u56A5\u56AE\u56B6\u56B4\u56C2\u56BC\u56C1\u56C3\u56C0\u56C8\u56CE\u56D1\u56D3\u56D7\u56EE\u56F9\u5700\u56FF\u5704\u5709\u5708\u570B\u570D\u5713\u5718\u5716\u55C7\u571C\u5726\u5737\u5738\u574E\u573B\u5740\u574F\u5769\u57C0\u5788\u5761\u577F\u5789\u5793\u57A0\u57B3\u57A4\u57AA\u57B0\u57C3\u57C6\u57D4\u57D2\u57D3\u580A\u57D6\u57E3\u580B\u5819\u581D\u5872\u5821\u5862\u584B\u5870\u6BC0\u5852\u583D\u5879\u5885\u58B9\u589F\u58AB\u58BA\u58DE\u58BB\u58B8\u58AE\u58C5\u58D3\u58D1\u58D7\u58D9\u58D8\u58E5\u58DC\u58E4\u58DF\u58EF\u58FA\u58F9\u58FB\u58FC\u58FD\u5902\u590A\u5910\u591B\u68A6\u5925\u592C\u592D\u5932\u5938\u593E\u7AD2\u5955\u5950\u594E\u595A\u5958\u5962\u5960\u5967\u596C\u5969"], - ["9b40", "\u5978\u5981\u599D\u4F5E\u4FAB\u59A3\u59B2\u59C6\u59E8\u59DC\u598D\u59D9\u59DA\u5A25\u5A1F\u5A11\u5A1C\u5A09\u5A1A\u5A40\u5A6C\u5A49\u5A35\u5A36\u5A62\u5A6A\u5A9A\u5ABC\u5ABE\u5ACB\u5AC2\u5ABD\u5AE3\u5AD7\u5AE6\u5AE9\u5AD6\u5AFA\u5AFB\u5B0C\u5B0B\u5B16\u5B32\u5AD0\u5B2A\u5B36\u5B3E\u5B43\u5B45\u5B40\u5B51\u5B55\u5B5A\u5B5B\u5B65\u5B69\u5B70\u5B73\u5B75\u5B78\u6588\u5B7A\u5B80"], - ["9b80", "\u5B83\u5BA6\u5BB8\u5BC3\u5BC7\u5BC9\u5BD4\u5BD0\u5BE4\u5BE6\u5BE2\u5BDE\u5BE5\u5BEB\u5BF0\u5BF6\u5BF3\u5C05\u5C07\u5C08\u5C0D\u5C13\u5C20\u5C22\u5C28\u5C38\u5C39\u5C41\u5C46\u5C4E\u5C53\u5C50\u5C4F\u5B71\u5C6C\u5C6E\u4E62\u5C76\u5C79\u5C8C\u5C91\u5C94\u599B\u5CAB\u5CBB\u5CB6\u5CBC\u5CB7\u5CC5\u5CBE\u5CC7\u5CD9\u5CE9\u5CFD\u5CFA\u5CED\u5D8C\u5CEA\u5D0B\u5D15\u5D17\u5D5C\u5D1F\u5D1B\u5D11\u5D14\u5D22\u5D1A\u5D19\u5D18\u5D4C\u5D52\u5D4E\u5D4B\u5D6C\u5D73\u5D76\u5D87\u5D84\u5D82\u5DA2\u5D9D\u5DAC\u5DAE\u5DBD\u5D90\u5DB7\u5DBC\u5DC9\u5DCD\u5DD3\u5DD2\u5DD6\u5DDB\u5DEB\u5DF2\u5DF5\u5E0B\u5E1A\u5E19\u5E11\u5E1B\u5E36\u5E37\u5E44\u5E43\u5E40\u5E4E\u5E57\u5E54\u5E5F\u5E62\u5E64\u5E47\u5E75\u5E76\u5E7A\u9EBC\u5E7F\u5EA0\u5EC1\u5EC2\u5EC8\u5ED0\u5ECF"], - ["9c40", "\u5ED6\u5EE3\u5EDD\u5EDA\u5EDB\u5EE2\u5EE1\u5EE8\u5EE9\u5EEC\u5EF1\u5EF3\u5EF0\u5EF4\u5EF8\u5EFE\u5F03\u5F09\u5F5D\u5F5C\u5F0B\u5F11\u5F16\u5F29\u5F2D\u5F38\u5F41\u5F48\u5F4C\u5F4E\u5F2F\u5F51\u5F56\u5F57\u5F59\u5F61\u5F6D\u5F73\u5F77\u5F83\u5F82\u5F7F\u5F8A\u5F88\u5F91\u5F87\u5F9E\u5F99\u5F98\u5FA0\u5FA8\u5FAD\u5FBC\u5FD6\u5FFB\u5FE4\u5FF8\u5FF1\u5FDD\u60B3\u5FFF\u6021\u6060"], - ["9c80", "\u6019\u6010\u6029\u600E\u6031\u601B\u6015\u602B\u6026\u600F\u603A\u605A\u6041\u606A\u6077\u605F\u604A\u6046\u604D\u6063\u6043\u6064\u6042\u606C\u606B\u6059\u6081\u608D\u60E7\u6083\u609A\u6084\u609B\u6096\u6097\u6092\u60A7\u608B\u60E1\u60B8\u60E0\u60D3\u60B4\u5FF0\u60BD\u60C6\u60B5\u60D8\u614D\u6115\u6106\u60F6\u60F7\u6100\u60F4\u60FA\u6103\u6121\u60FB\u60F1\u610D\u610E\u6147\u613E\u6128\u6127\u614A\u613F\u613C\u612C\u6134\u613D\u6142\u6144\u6173\u6177\u6158\u6159\u615A\u616B\u6174\u616F\u6165\u6171\u615F\u615D\u6153\u6175\u6199\u6196\u6187\u61AC\u6194\u619A\u618A\u6191\u61AB\u61AE\u61CC\u61CA\u61C9\u61F7\u61C8\u61C3\u61C6\u61BA\u61CB\u7F79\u61CD\u61E6\u61E3\u61F6\u61FA\u61F4\u61FF\u61FD\u61FC\u61FE\u6200\u6208\u6209\u620D\u620C\u6214\u621B"], - ["9d40", "\u621E\u6221\u622A\u622E\u6230\u6232\u6233\u6241\u624E\u625E\u6263\u625B\u6260\u6268\u627C\u6282\u6289\u627E\u6292\u6293\u6296\u62D4\u6283\u6294\u62D7\u62D1\u62BB\u62CF\u62FF\u62C6\u64D4\u62C8\u62DC\u62CC\u62CA\u62C2\u62C7\u629B\u62C9\u630C\u62EE\u62F1\u6327\u6302\u6308\u62EF\u62F5\u6350\u633E\u634D\u641C\u634F\u6396\u638E\u6380\u63AB\u6376\u63A3\u638F\u6389\u639F\u63B5\u636B"], - ["9d80", "\u6369\u63BE\u63E9\u63C0\u63C6\u63E3\u63C9\u63D2\u63F6\u63C4\u6416\u6434\u6406\u6413\u6426\u6436\u651D\u6417\u6428\u640F\u6467\u646F\u6476\u644E\u652A\u6495\u6493\u64A5\u64A9\u6488\u64BC\u64DA\u64D2\u64C5\u64C7\u64BB\u64D8\u64C2\u64F1\u64E7\u8209\u64E0\u64E1\u62AC\u64E3\u64EF\u652C\u64F6\u64F4\u64F2\u64FA\u6500\u64FD\u6518\u651C\u6505\u6524\u6523\u652B\u6534\u6535\u6537\u6536\u6538\u754B\u6548\u6556\u6555\u654D\u6558\u655E\u655D\u6572\u6578\u6582\u6583\u8B8A\u659B\u659F\u65AB\u65B7\u65C3\u65C6\u65C1\u65C4\u65CC\u65D2\u65DB\u65D9\u65E0\u65E1\u65F1\u6772\u660A\u6603\u65FB\u6773\u6635\u6636\u6634\u661C\u664F\u6644\u6649\u6641\u665E\u665D\u6664\u6667\u6668\u665F\u6662\u6670\u6683\u6688\u668E\u6689\u6684\u6698\u669D\u66C1\u66B9\u66C9\u66BE\u66BC"], - ["9e40", "\u66C4\u66B8\u66D6\u66DA\u66E0\u663F\u66E6\u66E9\u66F0\u66F5\u66F7\u670F\u6716\u671E\u6726\u6727\u9738\u672E\u673F\u6736\u6741\u6738\u6737\u6746\u675E\u6760\u6759\u6763\u6764\u6789\u6770\u67A9\u677C\u676A\u678C\u678B\u67A6\u67A1\u6785\u67B7\u67EF\u67B4\u67EC\u67B3\u67E9\u67B8\u67E4\u67DE\u67DD\u67E2\u67EE\u67B9\u67CE\u67C6\u67E7\u6A9C\u681E\u6846\u6829\u6840\u684D\u6832\u684E"], - ["9e80", "\u68B3\u682B\u6859\u6863\u6877\u687F\u689F\u688F\u68AD\u6894\u689D\u689B\u6883\u6AAE\u68B9\u6874\u68B5\u68A0\u68BA\u690F\u688D\u687E\u6901\u68CA\u6908\u68D8\u6922\u6926\u68E1\u690C\u68CD\u68D4\u68E7\u68D5\u6936\u6912\u6904\u68D7\u68E3\u6925\u68F9\u68E0\u68EF\u6928\u692A\u691A\u6923\u6921\u68C6\u6979\u6977\u695C\u6978\u696B\u6954\u697E\u696E\u6939\u6974\u693D\u6959\u6930\u6961\u695E\u695D\u6981\u696A\u69B2\u69AE\u69D0\u69BF\u69C1\u69D3\u69BE\u69CE\u5BE8\u69CA\u69DD\u69BB\u69C3\u69A7\u6A2E\u6991\u69A0\u699C\u6995\u69B4\u69DE\u69E8\u6A02\u6A1B\u69FF\u6B0A\u69F9\u69F2\u69E7\u6A05\u69B1\u6A1E\u69ED\u6A14\u69EB\u6A0A\u6A12\u6AC1\u6A23\u6A13\u6A44\u6A0C\u6A72\u6A36\u6A78\u6A47\u6A62\u6A59\u6A66\u6A48\u6A38\u6A22\u6A90\u6A8D\u6AA0\u6A84\u6AA2\u6AA3"], - ["9f40", "\u6A97\u8617\u6ABB\u6AC3\u6AC2\u6AB8\u6AB3\u6AAC\u6ADE\u6AD1\u6ADF\u6AAA\u6ADA\u6AEA\u6AFB\u6B05\u8616\u6AFA\u6B12\u6B16\u9B31\u6B1F\u6B38\u6B37\u76DC\u6B39\u98EE\u6B47\u6B43\u6B49\u6B50\u6B59\u6B54\u6B5B\u6B5F\u6B61\u6B78\u6B79\u6B7F\u6B80\u6B84\u6B83\u6B8D\u6B98\u6B95\u6B9E\u6BA4\u6BAA\u6BAB\u6BAF\u6BB2\u6BB1\u6BB3\u6BB7\u6BBC\u6BC6\u6BCB\u6BD3\u6BDF\u6BEC\u6BEB\u6BF3\u6BEF"], - ["9f80", "\u9EBE\u6C08\u6C13\u6C14\u6C1B\u6C24\u6C23\u6C5E\u6C55\u6C62\u6C6A\u6C82\u6C8D\u6C9A\u6C81\u6C9B\u6C7E\u6C68\u6C73\u6C92\u6C90\u6CC4\u6CF1\u6CD3\u6CBD\u6CD7\u6CC5\u6CDD\u6CAE\u6CB1\u6CBE\u6CBA\u6CDB\u6CEF\u6CD9\u6CEA\u6D1F\u884D\u6D36\u6D2B\u6D3D\u6D38\u6D19\u6D35\u6D33\u6D12\u6D0C\u6D63\u6D93\u6D64\u6D5A\u6D79\u6D59\u6D8E\u6D95\u6FE4\u6D85\u6DF9\u6E15\u6E0A\u6DB5\u6DC7\u6DE6\u6DB8\u6DC6\u6DEC\u6DDE\u6DCC\u6DE8\u6DD2\u6DC5\u6DFA\u6DD9\u6DE4\u6DD5\u6DEA\u6DEE\u6E2D\u6E6E\u6E2E\u6E19\u6E72\u6E5F\u6E3E\u6E23\u6E6B\u6E2B\u6E76\u6E4D\u6E1F\u6E43\u6E3A\u6E4E\u6E24\u6EFF\u6E1D\u6E38\u6E82\u6EAA\u6E98\u6EC9\u6EB7\u6ED3\u6EBD\u6EAF\u6EC4\u6EB2\u6ED4\u6ED5\u6E8F\u6EA5\u6EC2\u6E9F\u6F41\u6F11\u704C\u6EEC\u6EF8\u6EFE\u6F3F\u6EF2\u6F31\u6EEF\u6F32\u6ECC"], - ["e040", "\u6F3E\u6F13\u6EF7\u6F86\u6F7A\u6F78\u6F81\u6F80\u6F6F\u6F5B\u6FF3\u6F6D\u6F82\u6F7C\u6F58\u6F8E\u6F91\u6FC2\u6F66\u6FB3\u6FA3\u6FA1\u6FA4\u6FB9\u6FC6\u6FAA\u6FDF\u6FD5\u6FEC\u6FD4\u6FD8\u6FF1\u6FEE\u6FDB\u7009\u700B\u6FFA\u7011\u7001\u700F\u6FFE\u701B\u701A\u6F74\u701D\u7018\u701F\u7030\u703E\u7032\u7051\u7063\u7099\u7092\u70AF\u70F1\u70AC\u70B8\u70B3\u70AE\u70DF\u70CB\u70DD"], - ["e080", "\u70D9\u7109\u70FD\u711C\u7119\u7165\u7155\u7188\u7166\u7162\u714C\u7156\u716C\u718F\u71FB\u7184\u7195\u71A8\u71AC\u71D7\u71B9\u71BE\u71D2\u71C9\u71D4\u71CE\u71E0\u71EC\u71E7\u71F5\u71FC\u71F9\u71FF\u720D\u7210\u721B\u7228\u722D\u722C\u7230\u7232\u723B\u723C\u723F\u7240\u7246\u724B\u7258\u7274\u727E\u7282\u7281\u7287\u7292\u7296\u72A2\u72A7\u72B9\u72B2\u72C3\u72C6\u72C4\u72CE\u72D2\u72E2\u72E0\u72E1\u72F9\u72F7\u500F\u7317\u730A\u731C\u7316\u731D\u7334\u732F\u7329\u7325\u733E\u734E\u734F\u9ED8\u7357\u736A\u7368\u7370\u7378\u7375\u737B\u737A\u73C8\u73B3\u73CE\u73BB\u73C0\u73E5\u73EE\u73DE\u74A2\u7405\u746F\u7425\u73F8\u7432\u743A\u7455\u743F\u745F\u7459\u7441\u745C\u7469\u7470\u7463\u746A\u7476\u747E\u748B\u749E\u74A7\u74CA\u74CF\u74D4\u73F1"], - ["e140", "\u74E0\u74E3\u74E7\u74E9\u74EE\u74F2\u74F0\u74F1\u74F8\u74F7\u7504\u7503\u7505\u750C\u750E\u750D\u7515\u7513\u751E\u7526\u752C\u753C\u7544\u754D\u754A\u7549\u755B\u7546\u755A\u7569\u7564\u7567\u756B\u756D\u7578\u7576\u7586\u7587\u7574\u758A\u7589\u7582\u7594\u759A\u759D\u75A5\u75A3\u75C2\u75B3\u75C3\u75B5\u75BD\u75B8\u75BC\u75B1\u75CD\u75CA\u75D2\u75D9\u75E3\u75DE\u75FE\u75FF"], - ["e180", "\u75FC\u7601\u75F0\u75FA\u75F2\u75F3\u760B\u760D\u7609\u761F\u7627\u7620\u7621\u7622\u7624\u7634\u7630\u763B\u7647\u7648\u7646\u765C\u7658\u7661\u7662\u7668\u7669\u766A\u7667\u766C\u7670\u7672\u7676\u7678\u767C\u7680\u7683\u7688\u768B\u768E\u7696\u7693\u7699\u769A\u76B0\u76B4\u76B8\u76B9\u76BA\u76C2\u76CD\u76D6\u76D2\u76DE\u76E1\u76E5\u76E7\u76EA\u862F\u76FB\u7708\u7707\u7704\u7729\u7724\u771E\u7725\u7726\u771B\u7737\u7738\u7747\u775A\u7768\u776B\u775B\u7765\u777F\u777E\u7779\u778E\u778B\u7791\u77A0\u779E\u77B0\u77B6\u77B9\u77BF\u77BC\u77BD\u77BB\u77C7\u77CD\u77D7\u77DA\u77DC\u77E3\u77EE\u77FC\u780C\u7812\u7926\u7820\u792A\u7845\u788E\u7874\u7886\u787C\u789A\u788C\u78A3\u78B5\u78AA\u78AF\u78D1\u78C6\u78CB\u78D4\u78BE\u78BC\u78C5\u78CA\u78EC"], - ["e240", "\u78E7\u78DA\u78FD\u78F4\u7907\u7912\u7911\u7919\u792C\u792B\u7940\u7960\u7957\u795F\u795A\u7955\u7953\u797A\u797F\u798A\u799D\u79A7\u9F4B\u79AA\u79AE\u79B3\u79B9\u79BA\u79C9\u79D5\u79E7\u79EC\u79E1\u79E3\u7A08\u7A0D\u7A18\u7A19\u7A20\u7A1F\u7980\u7A31\u7A3B\u7A3E\u7A37\u7A43\u7A57\u7A49\u7A61\u7A62\u7A69\u9F9D\u7A70\u7A79\u7A7D\u7A88\u7A97\u7A95\u7A98\u7A96\u7AA9\u7AC8\u7AB0"], - ["e280", "\u7AB6\u7AC5\u7AC4\u7ABF\u9083\u7AC7\u7ACA\u7ACD\u7ACF\u7AD5\u7AD3\u7AD9\u7ADA\u7ADD\u7AE1\u7AE2\u7AE6\u7AED\u7AF0\u7B02\u7B0F\u7B0A\u7B06\u7B33\u7B18\u7B19\u7B1E\u7B35\u7B28\u7B36\u7B50\u7B7A\u7B04\u7B4D\u7B0B\u7B4C\u7B45\u7B75\u7B65\u7B74\u7B67\u7B70\u7B71\u7B6C\u7B6E\u7B9D\u7B98\u7B9F\u7B8D\u7B9C\u7B9A\u7B8B\u7B92\u7B8F\u7B5D\u7B99\u7BCB\u7BC1\u7BCC\u7BCF\u7BB4\u7BC6\u7BDD\u7BE9\u7C11\u7C14\u7BE6\u7BE5\u7C60\u7C00\u7C07\u7C13\u7BF3\u7BF7\u7C17\u7C0D\u7BF6\u7C23\u7C27\u7C2A\u7C1F\u7C37\u7C2B\u7C3D\u7C4C\u7C43\u7C54\u7C4F\u7C40\u7C50\u7C58\u7C5F\u7C64\u7C56\u7C65\u7C6C\u7C75\u7C83\u7C90\u7CA4\u7CAD\u7CA2\u7CAB\u7CA1\u7CA8\u7CB3\u7CB2\u7CB1\u7CAE\u7CB9\u7CBD\u7CC0\u7CC5\u7CC2\u7CD8\u7CD2\u7CDC\u7CE2\u9B3B\u7CEF\u7CF2\u7CF4\u7CF6\u7CFA\u7D06"], - ["e340", "\u7D02\u7D1C\u7D15\u7D0A\u7D45\u7D4B\u7D2E\u7D32\u7D3F\u7D35\u7D46\u7D73\u7D56\u7D4E\u7D72\u7D68\u7D6E\u7D4F\u7D63\u7D93\u7D89\u7D5B\u7D8F\u7D7D\u7D9B\u7DBA\u7DAE\u7DA3\u7DB5\u7DC7\u7DBD\u7DAB\u7E3D\u7DA2\u7DAF\u7DDC\u7DB8\u7D9F\u7DB0\u7DD8\u7DDD\u7DE4\u7DDE\u7DFB\u7DF2\u7DE1\u7E05\u7E0A\u7E23\u7E21\u7E12\u7E31\u7E1F\u7E09\u7E0B\u7E22\u7E46\u7E66\u7E3B\u7E35\u7E39\u7E43\u7E37"], - ["e380", "\u7E32\u7E3A\u7E67\u7E5D\u7E56\u7E5E\u7E59\u7E5A\u7E79\u7E6A\u7E69\u7E7C\u7E7B\u7E83\u7DD5\u7E7D\u8FAE\u7E7F\u7E88\u7E89\u7E8C\u7E92\u7E90\u7E93\u7E94\u7E96\u7E8E\u7E9B\u7E9C\u7F38\u7F3A\u7F45\u7F4C\u7F4D\u7F4E\u7F50\u7F51\u7F55\u7F54\u7F58\u7F5F\u7F60\u7F68\u7F69\u7F67\u7F78\u7F82\u7F86\u7F83\u7F88\u7F87\u7F8C\u7F94\u7F9E\u7F9D\u7F9A\u7FA3\u7FAF\u7FB2\u7FB9\u7FAE\u7FB6\u7FB8\u8B71\u7FC5\u7FC6\u7FCA\u7FD5\u7FD4\u7FE1\u7FE6\u7FE9\u7FF3\u7FF9\u98DC\u8006\u8004\u800B\u8012\u8018\u8019\u801C\u8021\u8028\u803F\u803B\u804A\u8046\u8052\u8058\u805A\u805F\u8062\u8068\u8073\u8072\u8070\u8076\u8079\u807D\u807F\u8084\u8086\u8085\u809B\u8093\u809A\u80AD\u5190\u80AC\u80DB\u80E5\u80D9\u80DD\u80C4\u80DA\u80D6\u8109\u80EF\u80F1\u811B\u8129\u8123\u812F\u814B"], - ["e440", "\u968B\u8146\u813E\u8153\u8151\u80FC\u8171\u816E\u8165\u8166\u8174\u8183\u8188\u818A\u8180\u8182\u81A0\u8195\u81A4\u81A3\u815F\u8193\u81A9\u81B0\u81B5\u81BE\u81B8\u81BD\u81C0\u81C2\u81BA\u81C9\u81CD\u81D1\u81D9\u81D8\u81C8\u81DA\u81DF\u81E0\u81E7\u81FA\u81FB\u81FE\u8201\u8202\u8205\u8207\u820A\u820D\u8210\u8216\u8229\u822B\u8238\u8233\u8240\u8259\u8258\u825D\u825A\u825F\u8264"], - ["e480", "\u8262\u8268\u826A\u826B\u822E\u8271\u8277\u8278\u827E\u828D\u8292\u82AB\u829F\u82BB\u82AC\u82E1\u82E3\u82DF\u82D2\u82F4\u82F3\u82FA\u8393\u8303\u82FB\u82F9\u82DE\u8306\u82DC\u8309\u82D9\u8335\u8334\u8316\u8332\u8331\u8340\u8339\u8350\u8345\u832F\u832B\u8317\u8318\u8385\u839A\u83AA\u839F\u83A2\u8396\u8323\u838E\u8387\u838A\u837C\u83B5\u8373\u8375\u83A0\u8389\u83A8\u83F4\u8413\u83EB\u83CE\u83FD\u8403\u83D8\u840B\u83C1\u83F7\u8407\u83E0\u83F2\u840D\u8422\u8420\u83BD\u8438\u8506\u83FB\u846D\u842A\u843C\u855A\u8484\u8477\u846B\u84AD\u846E\u8482\u8469\u8446\u842C\u846F\u8479\u8435\u84CA\u8462\u84B9\u84BF\u849F\u84D9\u84CD\u84BB\u84DA\u84D0\u84C1\u84C6\u84D6\u84A1\u8521\u84FF\u84F4\u8517\u8518\u852C\u851F\u8515\u8514\u84FC\u8540\u8563\u8558\u8548"], - ["e540", "\u8541\u8602\u854B\u8555\u8580\u85A4\u8588\u8591\u858A\u85A8\u856D\u8594\u859B\u85EA\u8587\u859C\u8577\u857E\u8590\u85C9\u85BA\u85CF\u85B9\u85D0\u85D5\u85DD\u85E5\u85DC\u85F9\u860A\u8613\u860B\u85FE\u85FA\u8606\u8622\u861A\u8630\u863F\u864D\u4E55\u8654\u865F\u8667\u8671\u8693\u86A3\u86A9\u86AA\u868B\u868C\u86B6\u86AF\u86C4\u86C6\u86B0\u86C9\u8823\u86AB\u86D4\u86DE\u86E9\u86EC"], - ["e580", "\u86DF\u86DB\u86EF\u8712\u8706\u8708\u8700\u8703\u86FB\u8711\u8709\u870D\u86F9\u870A\u8734\u873F\u8737\u873B\u8725\u8729\u871A\u8760\u875F\u8778\u874C\u874E\u8774\u8757\u8768\u876E\u8759\u8753\u8763\u876A\u8805\u87A2\u879F\u8782\u87AF\u87CB\u87BD\u87C0\u87D0\u96D6\u87AB\u87C4\u87B3\u87C7\u87C6\u87BB\u87EF\u87F2\u87E0\u880F\u880D\u87FE\u87F6\u87F7\u880E\u87D2\u8811\u8816\u8815\u8822\u8821\u8831\u8836\u8839\u8827\u883B\u8844\u8842\u8852\u8859\u885E\u8862\u886B\u8881\u887E\u889E\u8875\u887D\u88B5\u8872\u8882\u8897\u8892\u88AE\u8899\u88A2\u888D\u88A4\u88B0\u88BF\u88B1\u88C3\u88C4\u88D4\u88D8\u88D9\u88DD\u88F9\u8902\u88FC\u88F4\u88E8\u88F2\u8904\u890C\u890A\u8913\u8943\u891E\u8925\u892A\u892B\u8941\u8944\u893B\u8936\u8938\u894C\u891D\u8960\u895E"], - ["e640", "\u8966\u8964\u896D\u896A\u896F\u8974\u8977\u897E\u8983\u8988\u898A\u8993\u8998\u89A1\u89A9\u89A6\u89AC\u89AF\u89B2\u89BA\u89BD\u89BF\u89C0\u89DA\u89DC\u89DD\u89E7\u89F4\u89F8\u8A03\u8A16\u8A10\u8A0C\u8A1B\u8A1D\u8A25\u8A36\u8A41\u8A5B\u8A52\u8A46\u8A48\u8A7C\u8A6D\u8A6C\u8A62\u8A85\u8A82\u8A84\u8AA8\u8AA1\u8A91\u8AA5\u8AA6\u8A9A\u8AA3\u8AC4\u8ACD\u8AC2\u8ADA\u8AEB\u8AF3\u8AE7"], - ["e680", "\u8AE4\u8AF1\u8B14\u8AE0\u8AE2\u8AF7\u8ADE\u8ADB\u8B0C\u8B07\u8B1A\u8AE1\u8B16\u8B10\u8B17\u8B20\u8B33\u97AB\u8B26\u8B2B\u8B3E\u8B28\u8B41\u8B4C\u8B4F\u8B4E\u8B49\u8B56\u8B5B\u8B5A\u8B6B\u8B5F\u8B6C\u8B6F\u8B74\u8B7D\u8B80\u8B8C\u8B8E\u8B92\u8B93\u8B96\u8B99\u8B9A\u8C3A\u8C41\u8C3F\u8C48\u8C4C\u8C4E\u8C50\u8C55\u8C62\u8C6C\u8C78\u8C7A\u8C82\u8C89\u8C85\u8C8A\u8C8D\u8C8E\u8C94\u8C7C\u8C98\u621D\u8CAD\u8CAA\u8CBD\u8CB2\u8CB3\u8CAE\u8CB6\u8CC8\u8CC1\u8CE4\u8CE3\u8CDA\u8CFD\u8CFA\u8CFB\u8D04\u8D05\u8D0A\u8D07\u8D0F\u8D0D\u8D10\u9F4E\u8D13\u8CCD\u8D14\u8D16\u8D67\u8D6D\u8D71\u8D73\u8D81\u8D99\u8DC2\u8DBE\u8DBA\u8DCF\u8DDA\u8DD6\u8DCC\u8DDB\u8DCB\u8DEA\u8DEB\u8DDF\u8DE3\u8DFC\u8E08\u8E09\u8DFF\u8E1D\u8E1E\u8E10\u8E1F\u8E42\u8E35\u8E30\u8E34\u8E4A"], - ["e740", "\u8E47\u8E49\u8E4C\u8E50\u8E48\u8E59\u8E64\u8E60\u8E2A\u8E63\u8E55\u8E76\u8E72\u8E7C\u8E81\u8E87\u8E85\u8E84\u8E8B\u8E8A\u8E93\u8E91\u8E94\u8E99\u8EAA\u8EA1\u8EAC\u8EB0\u8EC6\u8EB1\u8EBE\u8EC5\u8EC8\u8ECB\u8EDB\u8EE3\u8EFC\u8EFB\u8EEB\u8EFE\u8F0A\u8F05\u8F15\u8F12\u8F19\u8F13\u8F1C\u8F1F\u8F1B\u8F0C\u8F26\u8F33\u8F3B\u8F39\u8F45\u8F42\u8F3E\u8F4C\u8F49\u8F46\u8F4E\u8F57\u8F5C"], - ["e780", "\u8F62\u8F63\u8F64\u8F9C\u8F9F\u8FA3\u8FAD\u8FAF\u8FB7\u8FDA\u8FE5\u8FE2\u8FEA\u8FEF\u9087\u8FF4\u9005\u8FF9\u8FFA\u9011\u9015\u9021\u900D\u901E\u9016\u900B\u9027\u9036\u9035\u9039\u8FF8\u904F\u9050\u9051\u9052\u900E\u9049\u903E\u9056\u9058\u905E\u9068\u906F\u9076\u96A8\u9072\u9082\u907D\u9081\u9080\u908A\u9089\u908F\u90A8\u90AF\u90B1\u90B5\u90E2\u90E4\u6248\u90DB\u9102\u9112\u9119\u9132\u9130\u914A\u9156\u9158\u9163\u9165\u9169\u9173\u9172\u918B\u9189\u9182\u91A2\u91AB\u91AF\u91AA\u91B5\u91B4\u91BA\u91C0\u91C1\u91C9\u91CB\u91D0\u91D6\u91DF\u91E1\u91DB\u91FC\u91F5\u91F6\u921E\u91FF\u9214\u922C\u9215\u9211\u925E\u9257\u9245\u9249\u9264\u9248\u9295\u923F\u924B\u9250\u929C\u9296\u9293\u929B\u925A\u92CF\u92B9\u92B7\u92E9\u930F\u92FA\u9344\u932E"], - ["e840", "\u9319\u9322\u931A\u9323\u933A\u9335\u933B\u935C\u9360\u937C\u936E\u9356\u93B0\u93AC\u93AD\u9394\u93B9\u93D6\u93D7\u93E8\u93E5\u93D8\u93C3\u93DD\u93D0\u93C8\u93E4\u941A\u9414\u9413\u9403\u9407\u9410\u9436\u942B\u9435\u9421\u943A\u9441\u9452\u9444\u945B\u9460\u9462\u945E\u946A\u9229\u9470\u9475\u9477\u947D\u945A\u947C\u947E\u9481\u947F\u9582\u9587\u958A\u9594\u9596\u9598\u9599"], - ["e880", "\u95A0\u95A8\u95A7\u95AD\u95BC\u95BB\u95B9\u95BE\u95CA\u6FF6\u95C3\u95CD\u95CC\u95D5\u95D4\u95D6\u95DC\u95E1\u95E5\u95E2\u9621\u9628\u962E\u962F\u9642\u964C\u964F\u964B\u9677\u965C\u965E\u965D\u965F\u9666\u9672\u966C\u968D\u9698\u9695\u9697\u96AA\u96A7\u96B1\u96B2\u96B0\u96B4\u96B6\u96B8\u96B9\u96CE\u96CB\u96C9\u96CD\u894D\u96DC\u970D\u96D5\u96F9\u9704\u9706\u9708\u9713\u970E\u9711\u970F\u9716\u9719\u9724\u972A\u9730\u9739\u973D\u973E\u9744\u9746\u9748\u9742\u9749\u975C\u9760\u9764\u9766\u9768\u52D2\u976B\u9771\u9779\u9785\u977C\u9781\u977A\u9786\u978B\u978F\u9790\u979C\u97A8\u97A6\u97A3\u97B3\u97B4\u97C3\u97C6\u97C8\u97CB\u97DC\u97ED\u9F4F\u97F2\u7ADF\u97F6\u97F5\u980F\u980C\u9838\u9824\u9821\u9837\u983D\u9846\u984F\u984B\u986B\u986F\u9870"], - ["e940", "\u9871\u9874\u9873\u98AA\u98AF\u98B1\u98B6\u98C4\u98C3\u98C6\u98E9\u98EB\u9903\u9909\u9912\u9914\u9918\u9921\u991D\u991E\u9924\u9920\u992C\u992E\u993D\u993E\u9942\u9949\u9945\u9950\u994B\u9951\u9952\u994C\u9955\u9997\u9998\u99A5\u99AD\u99AE\u99BC\u99DF\u99DB\u99DD\u99D8\u99D1\u99ED\u99EE\u99F1\u99F2\u99FB\u99F8\u9A01\u9A0F\u9A05\u99E2\u9A19\u9A2B\u9A37\u9A45\u9A42\u9A40\u9A43"], - ["e980", "\u9A3E\u9A55\u9A4D\u9A5B\u9A57\u9A5F\u9A62\u9A65\u9A64\u9A69\u9A6B\u9A6A\u9AAD\u9AB0\u9ABC\u9AC0\u9ACF\u9AD1\u9AD3\u9AD4\u9ADE\u9ADF\u9AE2\u9AE3\u9AE6\u9AEF\u9AEB\u9AEE\u9AF4\u9AF1\u9AF7\u9AFB\u9B06\u9B18\u9B1A\u9B1F\u9B22\u9B23\u9B25\u9B27\u9B28\u9B29\u9B2A\u9B2E\u9B2F\u9B32\u9B44\u9B43\u9B4F\u9B4D\u9B4E\u9B51\u9B58\u9B74\u9B93\u9B83\u9B91\u9B96\u9B97\u9B9F\u9BA0\u9BA8\u9BB4\u9BC0\u9BCA\u9BB9\u9BC6\u9BCF\u9BD1\u9BD2\u9BE3\u9BE2\u9BE4\u9BD4\u9BE1\u9C3A\u9BF2\u9BF1\u9BF0\u9C15\u9C14\u9C09\u9C13\u9C0C\u9C06\u9C08\u9C12\u9C0A\u9C04\u9C2E\u9C1B\u9C25\u9C24\u9C21\u9C30\u9C47\u9C32\u9C46\u9C3E\u9C5A\u9C60\u9C67\u9C76\u9C78\u9CE7\u9CEC\u9CF0\u9D09\u9D08\u9CEB\u9D03\u9D06\u9D2A\u9D26\u9DAF\u9D23\u9D1F\u9D44\u9D15\u9D12\u9D41\u9D3F\u9D3E\u9D46\u9D48"], - ["ea40", "\u9D5D\u9D5E\u9D64\u9D51\u9D50\u9D59\u9D72\u9D89\u9D87\u9DAB\u9D6F\u9D7A\u9D9A\u9DA4\u9DA9\u9DB2\u9DC4\u9DC1\u9DBB\u9DB8\u9DBA\u9DC6\u9DCF\u9DC2\u9DD9\u9DD3\u9DF8\u9DE6\u9DED\u9DEF\u9DFD\u9E1A\u9E1B\u9E1E\u9E75\u9E79\u9E7D\u9E81\u9E88\u9E8B\u9E8C\u9E92\u9E95\u9E91\u9E9D\u9EA5\u9EA9\u9EB8\u9EAA\u9EAD\u9761\u9ECC\u9ECE\u9ECF\u9ED0\u9ED4\u9EDC\u9EDE\u9EDD\u9EE0\u9EE5\u9EE8\u9EEF"], - ["ea80", "\u9EF4\u9EF6\u9EF7\u9EF9\u9EFB\u9EFC\u9EFD\u9F07\u9F08\u76B7\u9F15\u9F21\u9F2C\u9F3E\u9F4A\u9F52\u9F54\u9F63\u9F5F\u9F60\u9F61\u9F66\u9F67\u9F6C\u9F6A\u9F77\u9F72\u9F76\u9F95\u9F9C\u9FA0\u582F\u69C7\u9059\u7464\u51DC\u7199"], - ["ed40", "\u7E8A\u891C\u9348\u9288\u84DC\u4FC9\u70BB\u6631\u68C8\u92F9\u66FB\u5F45\u4E28\u4EE1\u4EFC\u4F00\u4F03\u4F39\u4F56\u4F92\u4F8A\u4F9A\u4F94\u4FCD\u5040\u5022\u4FFF\u501E\u5046\u5070\u5042\u5094\u50F4\u50D8\u514A\u5164\u519D\u51BE\u51EC\u5215\u529C\u52A6\u52C0\u52DB\u5300\u5307\u5324\u5372\u5393\u53B2\u53DD\uFA0E\u549C\u548A\u54A9\u54FF\u5586\u5759\u5765\u57AC\u57C8\u57C7\uFA0F"], - ["ed80", "\uFA10\u589E\u58B2\u590B\u5953\u595B\u595D\u5963\u59A4\u59BA\u5B56\u5BC0\u752F\u5BD8\u5BEC\u5C1E\u5CA6\u5CBA\u5CF5\u5D27\u5D53\uFA11\u5D42\u5D6D\u5DB8\u5DB9\u5DD0\u5F21\u5F34\u5F67\u5FB7\u5FDE\u605D\u6085\u608A\u60DE\u60D5\u6120\u60F2\u6111\u6137\u6130\u6198\u6213\u62A6\u63F5\u6460\u649D\u64CE\u654E\u6600\u6615\u663B\u6609\u662E\u661E\u6624\u6665\u6657\u6659\uFA12\u6673\u6699\u66A0\u66B2\u66BF\u66FA\u670E\uF929\u6766\u67BB\u6852\u67C0\u6801\u6844\u68CF\uFA13\u6968\uFA14\u6998\u69E2\u6A30\u6A6B\u6A46\u6A73\u6A7E\u6AE2\u6AE4\u6BD6\u6C3F\u6C5C\u6C86\u6C6F\u6CDA\u6D04\u6D87\u6D6F\u6D96\u6DAC\u6DCF\u6DF8\u6DF2\u6DFC\u6E39\u6E5C\u6E27\u6E3C\u6EBF\u6F88\u6FB5\u6FF5\u7005\u7007\u7028\u7085\u70AB\u710F\u7104\u715C\u7146\u7147\uFA15\u71C1\u71FE\u72B1"], - ["ee40", "\u72BE\u7324\uFA16\u7377\u73BD\u73C9\u73D6\u73E3\u73D2\u7407\u73F5\u7426\u742A\u7429\u742E\u7462\u7489\u749F\u7501\u756F\u7682\u769C\u769E\u769B\u76A6\uFA17\u7746\u52AF\u7821\u784E\u7864\u787A\u7930\uFA18\uFA19\uFA1A\u7994\uFA1B\u799B\u7AD1\u7AE7\uFA1C\u7AEB\u7B9E\uFA1D\u7D48\u7D5C\u7DB7\u7DA0\u7DD6\u7E52\u7F47\u7FA1\uFA1E\u8301\u8362\u837F\u83C7\u83F6\u8448\u84B4\u8553\u8559"], - ["ee80", "\u856B\uFA1F\u85B0\uFA20\uFA21\u8807\u88F5\u8A12\u8A37\u8A79\u8AA7\u8ABE\u8ADF\uFA22\u8AF6\u8B53\u8B7F\u8CF0\u8CF4\u8D12\u8D76\uFA23\u8ECF\uFA24\uFA25\u9067\u90DE\uFA26\u9115\u9127\u91DA\u91D7\u91DE\u91ED\u91EE\u91E4\u91E5\u9206\u9210\u920A\u923A\u9240\u923C\u924E\u9259\u9251\u9239\u9267\u92A7\u9277\u9278\u92E7\u92D7\u92D9\u92D0\uFA27\u92D5\u92E0\u92D3\u9325\u9321\u92FB\uFA28\u931E\u92FF\u931D\u9302\u9370\u9357\u93A4\u93C6\u93DE\u93F8\u9431\u9445\u9448\u9592\uF9DC\uFA29\u969D\u96AF\u9733\u973B\u9743\u974D\u974F\u9751\u9755\u9857\u9865\uFA2A\uFA2B\u9927\uFA2C\u999E\u9A4E\u9AD9\u9ADC\u9B75\u9B72\u9B8F\u9BB1\u9BBB\u9C00\u9D70\u9D6B\uFA2D\u9E19\u9ED1"], - ["eeef", "\u2170", 9, "\uFFE2\uFFE4\uFF07\uFF02"], - ["f040", "\uE000", 62], - ["f080", "\uE03F", 124], - ["f140", "\uE0BC", 62], - ["f180", "\uE0FB", 124], - ["f240", "\uE178", 62], - ["f280", "\uE1B7", 124], - ["f340", "\uE234", 62], - ["f380", "\uE273", 124], - ["f440", "\uE2F0", 62], - ["f480", "\uE32F", 124], - ["f540", "\uE3AC", 62], - ["f580", "\uE3EB", 124], - ["f640", "\uE468", 62], - ["f680", "\uE4A7", 124], - ["f740", "\uE524", 62], - ["f780", "\uE563", 124], - ["f840", "\uE5E0", 62], - ["f880", "\uE61F", 124], - ["f940", "\uE69C"], - ["fa40", "\u2170", 9, "\u2160", 9, "\uFFE2\uFFE4\uFF07\uFF02\u3231\u2116\u2121\u2235\u7E8A\u891C\u9348\u9288\u84DC\u4FC9\u70BB\u6631\u68C8\u92F9\u66FB\u5F45\u4E28\u4EE1\u4EFC\u4F00\u4F03\u4F39\u4F56\u4F92\u4F8A\u4F9A\u4F94\u4FCD\u5040\u5022\u4FFF\u501E\u5046\u5070\u5042\u5094\u50F4\u50D8\u514A"], - ["fa80", "\u5164\u519D\u51BE\u51EC\u5215\u529C\u52A6\u52C0\u52DB\u5300\u5307\u5324\u5372\u5393\u53B2\u53DD\uFA0E\u549C\u548A\u54A9\u54FF\u5586\u5759\u5765\u57AC\u57C8\u57C7\uFA0F\uFA10\u589E\u58B2\u590B\u5953\u595B\u595D\u5963\u59A4\u59BA\u5B56\u5BC0\u752F\u5BD8\u5BEC\u5C1E\u5CA6\u5CBA\u5CF5\u5D27\u5D53\uFA11\u5D42\u5D6D\u5DB8\u5DB9\u5DD0\u5F21\u5F34\u5F67\u5FB7\u5FDE\u605D\u6085\u608A\u60DE\u60D5\u6120\u60F2\u6111\u6137\u6130\u6198\u6213\u62A6\u63F5\u6460\u649D\u64CE\u654E\u6600\u6615\u663B\u6609\u662E\u661E\u6624\u6665\u6657\u6659\uFA12\u6673\u6699\u66A0\u66B2\u66BF\u66FA\u670E\uF929\u6766\u67BB\u6852\u67C0\u6801\u6844\u68CF\uFA13\u6968\uFA14\u6998\u69E2\u6A30\u6A6B\u6A46\u6A73\u6A7E\u6AE2\u6AE4\u6BD6\u6C3F\u6C5C\u6C86\u6C6F\u6CDA\u6D04\u6D87\u6D6F"], - ["fb40", "\u6D96\u6DAC\u6DCF\u6DF8\u6DF2\u6DFC\u6E39\u6E5C\u6E27\u6E3C\u6EBF\u6F88\u6FB5\u6FF5\u7005\u7007\u7028\u7085\u70AB\u710F\u7104\u715C\u7146\u7147\uFA15\u71C1\u71FE\u72B1\u72BE\u7324\uFA16\u7377\u73BD\u73C9\u73D6\u73E3\u73D2\u7407\u73F5\u7426\u742A\u7429\u742E\u7462\u7489\u749F\u7501\u756F\u7682\u769C\u769E\u769B\u76A6\uFA17\u7746\u52AF\u7821\u784E\u7864\u787A\u7930\uFA18\uFA19"], - ["fb80", "\uFA1A\u7994\uFA1B\u799B\u7AD1\u7AE7\uFA1C\u7AEB\u7B9E\uFA1D\u7D48\u7D5C\u7DB7\u7DA0\u7DD6\u7E52\u7F47\u7FA1\uFA1E\u8301\u8362\u837F\u83C7\u83F6\u8448\u84B4\u8553\u8559\u856B\uFA1F\u85B0\uFA20\uFA21\u8807\u88F5\u8A12\u8A37\u8A79\u8AA7\u8ABE\u8ADF\uFA22\u8AF6\u8B53\u8B7F\u8CF0\u8CF4\u8D12\u8D76\uFA23\u8ECF\uFA24\uFA25\u9067\u90DE\uFA26\u9115\u9127\u91DA\u91D7\u91DE\u91ED\u91EE\u91E4\u91E5\u9206\u9210\u920A\u923A\u9240\u923C\u924E\u9259\u9251\u9239\u9267\u92A7\u9277\u9278\u92E7\u92D7\u92D9\u92D0\uFA27\u92D5\u92E0\u92D3\u9325\u9321\u92FB\uFA28\u931E\u92FF\u931D\u9302\u9370\u9357\u93A4\u93C6\u93DE\u93F8\u9431\u9445\u9448\u9592\uF9DC\uFA29\u969D\u96AF\u9733\u973B\u9743\u974D\u974F\u9751\u9755\u9857\u9865\uFA2A\uFA2B\u9927\uFA2C\u999E\u9A4E\u9AD9"], - ["fc40", "\u9ADC\u9B75\u9B72\u9B8F\u9BB1\u9BBB\u9C00\u9D70\u9D6B\uFA2D\u9E19\u9ED1"] - ]; - } -}); - -// node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/encodings/tables/eucjp.json -var require_eucjp = __commonJS({ - "node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/encodings/tables/eucjp.json"(exports, module) { - module.exports = [ - ["0", "\0", 127], - ["8ea1", "\uFF61", 62], - ["a1a1", "\u3000\u3001\u3002\uFF0C\uFF0E\u30FB\uFF1A\uFF1B\uFF1F\uFF01\u309B\u309C\xB4\uFF40\xA8\uFF3E\uFFE3\uFF3F\u30FD\u30FE\u309D\u309E\u3003\u4EDD\u3005\u3006\u3007\u30FC\u2015\u2010\uFF0F\uFF3C\uFF5E\u2225\uFF5C\u2026\u2025\u2018\u2019\u201C\u201D\uFF08\uFF09\u3014\u3015\uFF3B\uFF3D\uFF5B\uFF5D\u3008", 9, "\uFF0B\uFF0D\xB1\xD7\xF7\uFF1D\u2260\uFF1C\uFF1E\u2266\u2267\u221E\u2234\u2642\u2640\xB0\u2032\u2033\u2103\uFFE5\uFF04\uFFE0\uFFE1\uFF05\uFF03\uFF06\uFF0A\uFF20\xA7\u2606\u2605\u25CB\u25CF\u25CE\u25C7"], - ["a2a1", "\u25C6\u25A1\u25A0\u25B3\u25B2\u25BD\u25BC\u203B\u3012\u2192\u2190\u2191\u2193\u3013"], - ["a2ba", "\u2208\u220B\u2286\u2287\u2282\u2283\u222A\u2229"], - ["a2ca", "\u2227\u2228\uFFE2\u21D2\u21D4\u2200\u2203"], - ["a2dc", "\u2220\u22A5\u2312\u2202\u2207\u2261\u2252\u226A\u226B\u221A\u223D\u221D\u2235\u222B\u222C"], - ["a2f2", "\u212B\u2030\u266F\u266D\u266A\u2020\u2021\xB6"], - ["a2fe", "\u25EF"], - ["a3b0", "\uFF10", 9], - ["a3c1", "\uFF21", 25], - ["a3e1", "\uFF41", 25], - ["a4a1", "\u3041", 82], - ["a5a1", "\u30A1", 85], - ["a6a1", "\u0391", 16, "\u03A3", 6], - ["a6c1", "\u03B1", 16, "\u03C3", 6], - ["a7a1", "\u0410", 5, "\u0401\u0416", 25], - ["a7d1", "\u0430", 5, "\u0451\u0436", 25], - ["a8a1", "\u2500\u2502\u250C\u2510\u2518\u2514\u251C\u252C\u2524\u2534\u253C\u2501\u2503\u250F\u2513\u251B\u2517\u2523\u2533\u252B\u253B\u254B\u2520\u252F\u2528\u2537\u253F\u251D\u2530\u2525\u2538\u2542"], - ["ada1", "\u2460", 19, "\u2160", 9], - ["adc0", "\u3349\u3314\u3322\u334D\u3318\u3327\u3303\u3336\u3351\u3357\u330D\u3326\u3323\u332B\u334A\u333B\u339C\u339D\u339E\u338E\u338F\u33C4\u33A1"], - ["addf", "\u337B\u301D\u301F\u2116\u33CD\u2121\u32A4", 4, "\u3231\u3232\u3239\u337E\u337D\u337C\u2252\u2261\u222B\u222E\u2211\u221A\u22A5\u2220\u221F\u22BF\u2235\u2229\u222A"], - ["b0a1", "\u4E9C\u5516\u5A03\u963F\u54C0\u611B\u6328\u59F6\u9022\u8475\u831C\u7A50\u60AA\u63E1\u6E25\u65ED\u8466\u82A6\u9BF5\u6893\u5727\u65A1\u6271\u5B9B\u59D0\u867B\u98F4\u7D62\u7DBE\u9B8E\u6216\u7C9F\u88B7\u5B89\u5EB5\u6309\u6697\u6848\u95C7\u978D\u674F\u4EE5\u4F0A\u4F4D\u4F9D\u5049\u56F2\u5937\u59D4\u5A01\u5C09\u60DF\u610F\u6170\u6613\u6905\u70BA\u754F\u7570\u79FB\u7DAD\u7DEF\u80C3\u840E\u8863\u8B02\u9055\u907A\u533B\u4E95\u4EA5\u57DF\u80B2\u90C1\u78EF\u4E00\u58F1\u6EA2\u9038\u7A32\u8328\u828B\u9C2F\u5141\u5370\u54BD\u54E1\u56E0\u59FB\u5F15\u98F2\u6DEB\u80E4\u852D"], - ["b1a1", "\u9662\u9670\u96A0\u97FB\u540B\u53F3\u5B87\u70CF\u7FBD\u8FC2\u96E8\u536F\u9D5C\u7ABA\u4E11\u7893\u81FC\u6E26\u5618\u5504\u6B1D\u851A\u9C3B\u59E5\u53A9\u6D66\u74DC\u958F\u5642\u4E91\u904B\u96F2\u834F\u990C\u53E1\u55B6\u5B30\u5F71\u6620\u66F3\u6804\u6C38\u6CF3\u6D29\u745B\u76C8\u7A4E\u9834\u82F1\u885B\u8A60\u92ED\u6DB2\u75AB\u76CA\u99C5\u60A6\u8B01\u8D8A\u95B2\u698E\u53AD\u5186\u5712\u5830\u5944\u5BB4\u5EF6\u6028\u63A9\u63F4\u6CBF\u6F14\u708E\u7114\u7159\u71D5\u733F\u7E01\u8276\u82D1\u8597\u9060\u925B\u9D1B\u5869\u65BC\u6C5A\u7525\u51F9\u592E\u5965\u5F80\u5FDC"], - ["b2a1", "\u62BC\u65FA\u6A2A\u6B27\u6BB4\u738B\u7FC1\u8956\u9D2C\u9D0E\u9EC4\u5CA1\u6C96\u837B\u5104\u5C4B\u61B6\u81C6\u6876\u7261\u4E59\u4FFA\u5378\u6069\u6E29\u7A4F\u97F3\u4E0B\u5316\u4EEE\u4F55\u4F3D\u4FA1\u4F73\u52A0\u53EF\u5609\u590F\u5AC1\u5BB6\u5BE1\u79D1\u6687\u679C\u67B6\u6B4C\u6CB3\u706B\u73C2\u798D\u79BE\u7A3C\u7B87\u82B1\u82DB\u8304\u8377\u83EF\u83D3\u8766\u8AB2\u5629\u8CA8\u8FE6\u904E\u971E\u868A\u4FC4\u5CE8\u6211\u7259\u753B\u81E5\u82BD\u86FE\u8CC0\u96C5\u9913\u99D5\u4ECB\u4F1A\u89E3\u56DE\u584A\u58CA\u5EFB\u5FEB\u602A\u6094\u6062\u61D0\u6212\u62D0\u6539"], - ["b3a1", "\u9B41\u6666\u68B0\u6D77\u7070\u754C\u7686\u7D75\u82A5\u87F9\u958B\u968E\u8C9D\u51F1\u52BE\u5916\u54B3\u5BB3\u5D16\u6168\u6982\u6DAF\u788D\u84CB\u8857\u8A72\u93A7\u9AB8\u6D6C\u99A8\u86D9\u57A3\u67FF\u86CE\u920E\u5283\u5687\u5404\u5ED3\u62E1\u64B9\u683C\u6838\u6BBB\u7372\u78BA\u7A6B\u899A\u89D2\u8D6B\u8F03\u90ED\u95A3\u9694\u9769\u5B66\u5CB3\u697D\u984D\u984E\u639B\u7B20\u6A2B\u6A7F\u68B6\u9C0D\u6F5F\u5272\u559D\u6070\u62EC\u6D3B\u6E07\u6ED1\u845B\u8910\u8F44\u4E14\u9C39\u53F6\u691B\u6A3A\u9784\u682A\u515C\u7AC3\u84B2\u91DC\u938C\u565B\u9D28\u6822\u8305\u8431"], - ["b4a1", "\u7CA5\u5208\u82C5\u74E6\u4E7E\u4F83\u51A0\u5BD2\u520A\u52D8\u52E7\u5DFB\u559A\u582A\u59E6\u5B8C\u5B98\u5BDB\u5E72\u5E79\u60A3\u611F\u6163\u61BE\u63DB\u6562\u67D1\u6853\u68FA\u6B3E\u6B53\u6C57\u6F22\u6F97\u6F45\u74B0\u7518\u76E3\u770B\u7AFF\u7BA1\u7C21\u7DE9\u7F36\u7FF0\u809D\u8266\u839E\u89B3\u8ACC\u8CAB\u9084\u9451\u9593\u9591\u95A2\u9665\u97D3\u9928\u8218\u4E38\u542B\u5CB8\u5DCC\u73A9\u764C\u773C\u5CA9\u7FEB\u8D0B\u96C1\u9811\u9854\u9858\u4F01\u4F0E\u5371\u559C\u5668\u57FA\u5947\u5B09\u5BC4\u5C90\u5E0C\u5E7E\u5FCC\u63EE\u673A\u65D7\u65E2\u671F\u68CB\u68C4"], - ["b5a1", "\u6A5F\u5E30\u6BC5\u6C17\u6C7D\u757F\u7948\u5B63\u7A00\u7D00\u5FBD\u898F\u8A18\u8CB4\u8D77\u8ECC\u8F1D\u98E2\u9A0E\u9B3C\u4E80\u507D\u5100\u5993\u5B9C\u622F\u6280\u64EC\u6B3A\u72A0\u7591\u7947\u7FA9\u87FB\u8ABC\u8B70\u63AC\u83CA\u97A0\u5409\u5403\u55AB\u6854\u6A58\u8A70\u7827\u6775\u9ECD\u5374\u5BA2\u811A\u8650\u9006\u4E18\u4E45\u4EC7\u4F11\u53CA\u5438\u5BAE\u5F13\u6025\u6551\u673D\u6C42\u6C72\u6CE3\u7078\u7403\u7A76\u7AAE\u7B08\u7D1A\u7CFE\u7D66\u65E7\u725B\u53BB\u5C45\u5DE8\u62D2\u62E0\u6319\u6E20\u865A\u8A31\u8DDD\u92F8\u6F01\u79A6\u9B5A\u4EA8\u4EAB\u4EAC"], - ["b6a1", "\u4F9B\u4FA0\u50D1\u5147\u7AF6\u5171\u51F6\u5354\u5321\u537F\u53EB\u55AC\u5883\u5CE1\u5F37\u5F4A\u602F\u6050\u606D\u631F\u6559\u6A4B\u6CC1\u72C2\u72ED\u77EF\u80F8\u8105\u8208\u854E\u90F7\u93E1\u97FF\u9957\u9A5A\u4EF0\u51DD\u5C2D\u6681\u696D\u5C40\u66F2\u6975\u7389\u6850\u7C81\u50C5\u52E4\u5747\u5DFE\u9326\u65A4\u6B23\u6B3D\u7434\u7981\u79BD\u7B4B\u7DCA\u82B9\u83CC\u887F\u895F\u8B39\u8FD1\u91D1\u541F\u9280\u4E5D\u5036\u53E5\u533A\u72D7\u7396\u77E9\u82E6\u8EAF\u99C6\u99C8\u99D2\u5177\u611A\u865E\u55B0\u7A7A\u5076\u5BD3\u9047\u9685\u4E32\u6ADB\u91E7\u5C51\u5C48"], - ["b7a1", "\u6398\u7A9F\u6C93\u9774\u8F61\u7AAA\u718A\u9688\u7C82\u6817\u7E70\u6851\u936C\u52F2\u541B\u85AB\u8A13\u7FA4\u8ECD\u90E1\u5366\u8888\u7941\u4FC2\u50BE\u5211\u5144\u5553\u572D\u73EA\u578B\u5951\u5F62\u5F84\u6075\u6176\u6167\u61A9\u63B2\u643A\u656C\u666F\u6842\u6E13\u7566\u7A3D\u7CFB\u7D4C\u7D99\u7E4B\u7F6B\u830E\u834A\u86CD\u8A08\u8A63\u8B66\u8EFD\u981A\u9D8F\u82B8\u8FCE\u9BE8\u5287\u621F\u6483\u6FC0\u9699\u6841\u5091\u6B20\u6C7A\u6F54\u7A74\u7D50\u8840\u8A23\u6708\u4EF6\u5039\u5026\u5065\u517C\u5238\u5263\u55A7\u570F\u5805\u5ACC\u5EFA\u61B2\u61F8\u62F3\u6372"], - ["b8a1", "\u691C\u6A29\u727D\u72AC\u732E\u7814\u786F\u7D79\u770C\u80A9\u898B\u8B19\u8CE2\u8ED2\u9063\u9375\u967A\u9855\u9A13\u9E78\u5143\u539F\u53B3\u5E7B\u5F26\u6E1B\u6E90\u7384\u73FE\u7D43\u8237\u8A00\u8AFA\u9650\u4E4E\u500B\u53E4\u547C\u56FA\u59D1\u5B64\u5DF1\u5EAB\u5F27\u6238\u6545\u67AF\u6E56\u72D0\u7CCA\u88B4\u80A1\u80E1\u83F0\u864E\u8A87\u8DE8\u9237\u96C7\u9867\u9F13\u4E94\u4E92\u4F0D\u5348\u5449\u543E\u5A2F\u5F8C\u5FA1\u609F\u68A7\u6A8E\u745A\u7881\u8A9E\u8AA4\u8B77\u9190\u4E5E\u9BC9\u4EA4\u4F7C\u4FAF\u5019\u5016\u5149\u516C\u529F\u52B9\u52FE\u539A\u53E3\u5411"], - ["b9a1", "\u540E\u5589\u5751\u57A2\u597D\u5B54\u5B5D\u5B8F\u5DE5\u5DE7\u5DF7\u5E78\u5E83\u5E9A\u5EB7\u5F18\u6052\u614C\u6297\u62D8\u63A7\u653B\u6602\u6643\u66F4\u676D\u6821\u6897\u69CB\u6C5F\u6D2A\u6D69\u6E2F\u6E9D\u7532\u7687\u786C\u7A3F\u7CE0\u7D05\u7D18\u7D5E\u7DB1\u8015\u8003\u80AF\u80B1\u8154\u818F\u822A\u8352\u884C\u8861\u8B1B\u8CA2\u8CFC\u90CA\u9175\u9271\u783F\u92FC\u95A4\u964D\u9805\u9999\u9AD8\u9D3B\u525B\u52AB\u53F7\u5408\u58D5\u62F7\u6FE0\u8C6A\u8F5F\u9EB9\u514B\u523B\u544A\u56FD\u7A40\u9177\u9D60\u9ED2\u7344\u6F09\u8170\u7511\u5FFD\u60DA\u9AA8\u72DB\u8FBC"], - ["baa1", "\u6B64\u9803\u4ECA\u56F0\u5764\u58BE\u5A5A\u6068\u61C7\u660F\u6606\u6839\u68B1\u6DF7\u75D5\u7D3A\u826E\u9B42\u4E9B\u4F50\u53C9\u5506\u5D6F\u5DE6\u5DEE\u67FB\u6C99\u7473\u7802\u8A50\u9396\u88DF\u5750\u5EA7\u632B\u50B5\u50AC\u518D\u6700\u54C9\u585E\u59BB\u5BB0\u5F69\u624D\u63A1\u683D\u6B73\u6E08\u707D\u91C7\u7280\u7815\u7826\u796D\u658E\u7D30\u83DC\u88C1\u8F09\u969B\u5264\u5728\u6750\u7F6A\u8CA1\u51B4\u5742\u962A\u583A\u698A\u80B4\u54B2\u5D0E\u57FC\u7895\u9DFA\u4F5C\u524A\u548B\u643E\u6628\u6714\u67F5\u7A84\u7B56\u7D22\u932F\u685C\u9BAD\u7B39\u5319\u518A\u5237"], - ["bba1", "\u5BDF\u62F6\u64AE\u64E6\u672D\u6BBA\u85A9\u96D1\u7690\u9BD6\u634C\u9306\u9BAB\u76BF\u6652\u4E09\u5098\u53C2\u5C71\u60E8\u6492\u6563\u685F\u71E6\u73CA\u7523\u7B97\u7E82\u8695\u8B83\u8CDB\u9178\u9910\u65AC\u66AB\u6B8B\u4ED5\u4ED4\u4F3A\u4F7F\u523A\u53F8\u53F2\u55E3\u56DB\u58EB\u59CB\u59C9\u59FF\u5B50\u5C4D\u5E02\u5E2B\u5FD7\u601D\u6307\u652F\u5B5C\u65AF\u65BD\u65E8\u679D\u6B62\u6B7B\u6C0F\u7345\u7949\u79C1\u7CF8\u7D19\u7D2B\u80A2\u8102\u81F3\u8996\u8A5E\u8A69\u8A66\u8A8C\u8AEE\u8CC7\u8CDC\u96CC\u98FC\u6B6F\u4E8B\u4F3C\u4F8D\u5150\u5B57\u5BFA\u6148\u6301\u6642"], - ["bca1", "\u6B21\u6ECB\u6CBB\u723E\u74BD\u75D4\u78C1\u793A\u800C\u8033\u81EA\u8494\u8F9E\u6C50\u9E7F\u5F0F\u8B58\u9D2B\u7AFA\u8EF8\u5B8D\u96EB\u4E03\u53F1\u57F7\u5931\u5AC9\u5BA4\u6089\u6E7F\u6F06\u75BE\u8CEA\u5B9F\u8500\u7BE0\u5072\u67F4\u829D\u5C61\u854A\u7E1E\u820E\u5199\u5C04\u6368\u8D66\u659C\u716E\u793E\u7D17\u8005\u8B1D\u8ECA\u906E\u86C7\u90AA\u501F\u52FA\u5C3A\u6753\u707C\u7235\u914C\u91C8\u932B\u82E5\u5BC2\u5F31\u60F9\u4E3B\u53D6\u5B88\u624B\u6731\u6B8A\u72E9\u73E0\u7A2E\u816B\u8DA3\u9152\u9996\u5112\u53D7\u546A\u5BFF\u6388\u6A39\u7DAC\u9700\u56DA\u53CE\u5468"], - ["bda1", "\u5B97\u5C31\u5DDE\u4FEE\u6101\u62FE\u6D32\u79C0\u79CB\u7D42\u7E4D\u7FD2\u81ED\u821F\u8490\u8846\u8972\u8B90\u8E74\u8F2F\u9031\u914B\u916C\u96C6\u919C\u4EC0\u4F4F\u5145\u5341\u5F93\u620E\u67D4\u6C41\u6E0B\u7363\u7E26\u91CD\u9283\u53D4\u5919\u5BBF\u6DD1\u795D\u7E2E\u7C9B\u587E\u719F\u51FA\u8853\u8FF0\u4FCA\u5CFB\u6625\u77AC\u7AE3\u821C\u99FF\u51C6\u5FAA\u65EC\u696F\u6B89\u6DF3\u6E96\u6F64\u76FE\u7D14\u5DE1\u9075\u9187\u9806\u51E6\u521D\u6240\u6691\u66D9\u6E1A\u5EB6\u7DD2\u7F72\u66F8\u85AF\u85F7\u8AF8\u52A9\u53D9\u5973\u5E8F\u5F90\u6055\u92E4\u9664\u50B7\u511F"], - ["bea1", "\u52DD\u5320\u5347\u53EC\u54E8\u5546\u5531\u5617\u5968\u59BE\u5A3C\u5BB5\u5C06\u5C0F\u5C11\u5C1A\u5E84\u5E8A\u5EE0\u5F70\u627F\u6284\u62DB\u638C\u6377\u6607\u660C\u662D\u6676\u677E\u68A2\u6A1F\u6A35\u6CBC\u6D88\u6E09\u6E58\u713C\u7126\u7167\u75C7\u7701\u785D\u7901\u7965\u79F0\u7AE0\u7B11\u7CA7\u7D39\u8096\u83D6\u848B\u8549\u885D\u88F3\u8A1F\u8A3C\u8A54\u8A73\u8C61\u8CDE\u91A4\u9266\u937E\u9418\u969C\u9798\u4E0A\u4E08\u4E1E\u4E57\u5197\u5270\u57CE\u5834\u58CC\u5B22\u5E38\u60C5\u64FE\u6761\u6756\u6D44\u72B6\u7573\u7A63\u84B8\u8B72\u91B8\u9320\u5631\u57F4\u98FE"], - ["bfa1", "\u62ED\u690D\u6B96\u71ED\u7E54\u8077\u8272\u89E6\u98DF\u8755\u8FB1\u5C3B\u4F38\u4FE1\u4FB5\u5507\u5A20\u5BDD\u5BE9\u5FC3\u614E\u632F\u65B0\u664B\u68EE\u699B\u6D78\u6DF1\u7533\u75B9\u771F\u795E\u79E6\u7D33\u81E3\u82AF\u85AA\u89AA\u8A3A\u8EAB\u8F9B\u9032\u91DD\u9707\u4EBA\u4EC1\u5203\u5875\u58EC\u5C0B\u751A\u5C3D\u814E\u8A0A\u8FC5\u9663\u976D\u7B25\u8ACF\u9808\u9162\u56F3\u53A8\u9017\u5439\u5782\u5E25\u63A8\u6C34\u708A\u7761\u7C8B\u7FE0\u8870\u9042\u9154\u9310\u9318\u968F\u745E\u9AC4\u5D07\u5D69\u6570\u67A2\u8DA8\u96DB\u636E\u6749\u6919\u83C5\u9817\u96C0\u88FE"], - ["c0a1", "\u6F84\u647A\u5BF8\u4E16\u702C\u755D\u662F\u51C4\u5236\u52E2\u59D3\u5F81\u6027\u6210\u653F\u6574\u661F\u6674\u68F2\u6816\u6B63\u6E05\u7272\u751F\u76DB\u7CBE\u8056\u58F0\u88FD\u897F\u8AA0\u8A93\u8ACB\u901D\u9192\u9752\u9759\u6589\u7A0E\u8106\u96BB\u5E2D\u60DC\u621A\u65A5\u6614\u6790\u77F3\u7A4D\u7C4D\u7E3E\u810A\u8CAC\u8D64\u8DE1\u8E5F\u78A9\u5207\u62D9\u63A5\u6442\u6298\u8A2D\u7A83\u7BC0\u8AAC\u96EA\u7D76\u820C\u8749\u4ED9\u5148\u5343\u5360\u5BA3\u5C02\u5C16\u5DDD\u6226\u6247\u64B0\u6813\u6834\u6CC9\u6D45\u6D17\u67D3\u6F5C\u714E\u717D\u65CB\u7A7F\u7BAD\u7DDA"], - ["c1a1", "\u7E4A\u7FA8\u817A\u821B\u8239\u85A6\u8A6E\u8CCE\u8DF5\u9078\u9077\u92AD\u9291\u9583\u9BAE\u524D\u5584\u6F38\u7136\u5168\u7985\u7E55\u81B3\u7CCE\u564C\u5851\u5CA8\u63AA\u66FE\u66FD\u695A\u72D9\u758F\u758E\u790E\u7956\u79DF\u7C97\u7D20\u7D44\u8607\u8A34\u963B\u9061\u9F20\u50E7\u5275\u53CC\u53E2\u5009\u55AA\u58EE\u594F\u723D\u5B8B\u5C64\u531D\u60E3\u60F3\u635C\u6383\u633F\u63BB\u64CD\u65E9\u66F9\u5DE3\u69CD\u69FD\u6F15\u71E5\u4E89\u75E9\u76F8\u7A93\u7CDF\u7DCF\u7D9C\u8061\u8349\u8358\u846C\u84BC\u85FB\u88C5\u8D70\u9001\u906D\u9397\u971C\u9A12\u50CF\u5897\u618E"], - ["c2a1", "\u81D3\u8535\u8D08\u9020\u4FC3\u5074\u5247\u5373\u606F\u6349\u675F\u6E2C\u8DB3\u901F\u4FD7\u5C5E\u8CCA\u65CF\u7D9A\u5352\u8896\u5176\u63C3\u5B58\u5B6B\u5C0A\u640D\u6751\u905C\u4ED6\u591A\u592A\u6C70\u8A51\u553E\u5815\u59A5\u60F0\u6253\u67C1\u8235\u6955\u9640\u99C4\u9A28\u4F53\u5806\u5BFE\u8010\u5CB1\u5E2F\u5F85\u6020\u614B\u6234\u66FF\u6CF0\u6EDE\u80CE\u817F\u82D4\u888B\u8CB8\u9000\u902E\u968A\u9EDB\u9BDB\u4EE3\u53F0\u5927\u7B2C\u918D\u984C\u9DF9\u6EDD\u7027\u5353\u5544\u5B85\u6258\u629E\u62D3\u6CA2\u6FEF\u7422\u8A17\u9438\u6FC1\u8AFE\u8338\u51E7\u86F8\u53EA"], - ["c3a1", "\u53E9\u4F46\u9054\u8FB0\u596A\u8131\u5DFD\u7AEA\u8FBF\u68DA\u8C37\u72F8\u9C48\u6A3D\u8AB0\u4E39\u5358\u5606\u5766\u62C5\u63A2\u65E6\u6B4E\u6DE1\u6E5B\u70AD\u77ED\u7AEF\u7BAA\u7DBB\u803D\u80C6\u86CB\u8A95\u935B\u56E3\u58C7\u5F3E\u65AD\u6696\u6A80\u6BB5\u7537\u8AC7\u5024\u77E5\u5730\u5F1B\u6065\u667A\u6C60\u75F4\u7A1A\u7F6E\u81F4\u8718\u9045\u99B3\u7BC9\u755C\u7AF9\u7B51\u84C4\u9010\u79E9\u7A92\u8336\u5AE1\u7740\u4E2D\u4EF2\u5B99\u5FE0\u62BD\u663C\u67F1\u6CE8\u866B\u8877\u8A3B\u914E\u92F3\u99D0\u6A17\u7026\u732A\u82E7\u8457\u8CAF\u4E01\u5146\u51CB\u558B\u5BF5"], - ["c4a1", "\u5E16\u5E33\u5E81\u5F14\u5F35\u5F6B\u5FB4\u61F2\u6311\u66A2\u671D\u6F6E\u7252\u753A\u773A\u8074\u8139\u8178\u8776\u8ABF\u8ADC\u8D85\u8DF3\u929A\u9577\u9802\u9CE5\u52C5\u6357\u76F4\u6715\u6C88\u73CD\u8CC3\u93AE\u9673\u6D25\u589C\u690E\u69CC\u8FFD\u939A\u75DB\u901A\u585A\u6802\u63B4\u69FB\u4F43\u6F2C\u67D8\u8FBB\u8526\u7DB4\u9354\u693F\u6F70\u576A\u58F7\u5B2C\u7D2C\u722A\u540A\u91E3\u9DB4\u4EAD\u4F4E\u505C\u5075\u5243\u8C9E\u5448\u5824\u5B9A\u5E1D\u5E95\u5EAD\u5EF7\u5F1F\u608C\u62B5\u633A\u63D0\u68AF\u6C40\u7887\u798E\u7A0B\u7DE0\u8247\u8A02\u8AE6\u8E44\u9013"], - ["c5a1", "\u90B8\u912D\u91D8\u9F0E\u6CE5\u6458\u64E2\u6575\u6EF4\u7684\u7B1B\u9069\u93D1\u6EBA\u54F2\u5FB9\u64A4\u8F4D\u8FED\u9244\u5178\u586B\u5929\u5C55\u5E97\u6DFB\u7E8F\u751C\u8CBC\u8EE2\u985B\u70B9\u4F1D\u6BBF\u6FB1\u7530\u96FB\u514E\u5410\u5835\u5857\u59AC\u5C60\u5F92\u6597\u675C\u6E21\u767B\u83DF\u8CED\u9014\u90FD\u934D\u7825\u783A\u52AA\u5EA6\u571F\u5974\u6012\u5012\u515A\u51AC\u51CD\u5200\u5510\u5854\u5858\u5957\u5B95\u5CF6\u5D8B\u60BC\u6295\u642D\u6771\u6843\u68BC\u68DF\u76D7\u6DD8\u6E6F\u6D9B\u706F\u71C8\u5F53\u75D8\u7977\u7B49\u7B54\u7B52\u7CD6\u7D71\u5230"], - ["c6a1", "\u8463\u8569\u85E4\u8A0E\u8B04\u8C46\u8E0F\u9003\u900F\u9419\u9676\u982D\u9A30\u95D8\u50CD\u52D5\u540C\u5802\u5C0E\u61A7\u649E\u6D1E\u77B3\u7AE5\u80F4\u8404\u9053\u9285\u5CE0\u9D07\u533F\u5F97\u5FB3\u6D9C\u7279\u7763\u79BF\u7BE4\u6BD2\u72EC\u8AAD\u6803\u6A61\u51F8\u7A81\u6934\u5C4A\u9CF6\u82EB\u5BC5\u9149\u701E\u5678\u5C6F\u60C7\u6566\u6C8C\u8C5A\u9041\u9813\u5451\u66C7\u920D\u5948\u90A3\u5185\u4E4D\u51EA\u8599\u8B0E\u7058\u637A\u934B\u6962\u99B4\u7E04\u7577\u5357\u6960\u8EDF\u96E3\u6C5D\u4E8C\u5C3C\u5F10\u8FE9\u5302\u8CD1\u8089\u8679\u5EFF\u65E5\u4E73\u5165"], - ["c7a1", "\u5982\u5C3F\u97EE\u4EFB\u598A\u5FCD\u8A8D\u6FE1\u79B0\u7962\u5BE7\u8471\u732B\u71B1\u5E74\u5FF5\u637B\u649A\u71C3\u7C98\u4E43\u5EFC\u4E4B\u57DC\u56A2\u60A9\u6FC3\u7D0D\u80FD\u8133\u81BF\u8FB2\u8997\u86A4\u5DF4\u628A\u64AD\u8987\u6777\u6CE2\u6D3E\u7436\u7834\u5A46\u7F75\u82AD\u99AC\u4FF3\u5EC3\u62DD\u6392\u6557\u676F\u76C3\u724C\u80CC\u80BA\u8F29\u914D\u500D\u57F9\u5A92\u6885\u6973\u7164\u72FD\u8CB7\u58F2\u8CE0\u966A\u9019\u877F\u79E4\u77E7\u8429\u4F2F\u5265\u535A\u62CD\u67CF\u6CCA\u767D\u7B94\u7C95\u8236\u8584\u8FEB\u66DD\u6F20\u7206\u7E1B\u83AB\u99C1\u9EA6"], - ["c8a1", "\u51FD\u7BB1\u7872\u7BB8\u8087\u7B48\u6AE8\u5E61\u808C\u7551\u7560\u516B\u9262\u6E8C\u767A\u9197\u9AEA\u4F10\u7F70\u629C\u7B4F\u95A5\u9CE9\u567A\u5859\u86E4\u96BC\u4F34\u5224\u534A\u53CD\u53DB\u5E06\u642C\u6591\u677F\u6C3E\u6C4E\u7248\u72AF\u73ED\u7554\u7E41\u822C\u85E9\u8CA9\u7BC4\u91C6\u7169\u9812\u98EF\u633D\u6669\u756A\u76E4\u78D0\u8543\u86EE\u532A\u5351\u5426\u5983\u5E87\u5F7C\u60B2\u6249\u6279\u62AB\u6590\u6BD4\u6CCC\u75B2\u76AE\u7891\u79D8\u7DCB\u7F77\u80A5\u88AB\u8AB9\u8CBB\u907F\u975E\u98DB\u6A0B\u7C38\u5099\u5C3E\u5FAE\u6787\u6BD8\u7435\u7709\u7F8E"], - ["c9a1", "\u9F3B\u67CA\u7A17\u5339\u758B\u9AED\u5F66\u819D\u83F1\u8098\u5F3C\u5FC5\u7562\u7B46\u903C\u6867\u59EB\u5A9B\u7D10\u767E\u8B2C\u4FF5\u5F6A\u6A19\u6C37\u6F02\u74E2\u7968\u8868\u8A55\u8C79\u5EDF\u63CF\u75C5\u79D2\u82D7\u9328\u92F2\u849C\u86ED\u9C2D\u54C1\u5F6C\u658C\u6D5C\u7015\u8CA7\u8CD3\u983B\u654F\u74F6\u4E0D\u4ED8\u57E0\u592B\u5A66\u5BCC\u51A8\u5E03\u5E9C\u6016\u6276\u6577\u65A7\u666E\u6D6E\u7236\u7B26\u8150\u819A\u8299\u8B5C\u8CA0\u8CE6\u8D74\u961C\u9644\u4FAE\u64AB\u6B66\u821E\u8461\u856A\u90E8\u5C01\u6953\u98A8\u847A\u8557\u4F0F\u526F\u5FA9\u5E45\u670D"], - ["caa1", "\u798F\u8179\u8907\u8986\u6DF5\u5F17\u6255\u6CB8\u4ECF\u7269\u9B92\u5206\u543B\u5674\u58B3\u61A4\u626E\u711A\u596E\u7C89\u7CDE\u7D1B\u96F0\u6587\u805E\u4E19\u4F75\u5175\u5840\u5E63\u5E73\u5F0A\u67C4\u4E26\u853D\u9589\u965B\u7C73\u9801\u50FB\u58C1\u7656\u78A7\u5225\u77A5\u8511\u7B86\u504F\u5909\u7247\u7BC7\u7DE8\u8FBA\u8FD4\u904D\u4FBF\u52C9\u5A29\u5F01\u97AD\u4FDD\u8217\u92EA\u5703\u6355\u6B69\u752B\u88DC\u8F14\u7A42\u52DF\u5893\u6155\u620A\u66AE\u6BCD\u7C3F\u83E9\u5023\u4FF8\u5305\u5446\u5831\u5949\u5B9D\u5CF0\u5CEF\u5D29\u5E96\u62B1\u6367\u653E\u65B9\u670B"], - ["cba1", "\u6CD5\u6CE1\u70F9\u7832\u7E2B\u80DE\u82B3\u840C\u84EC\u8702\u8912\u8A2A\u8C4A\u90A6\u92D2\u98FD\u9CF3\u9D6C\u4E4F\u4EA1\u508D\u5256\u574A\u59A8\u5E3D\u5FD8\u5FD9\u623F\u66B4\u671B\u67D0\u68D2\u5192\u7D21\u80AA\u81A8\u8B00\u8C8C\u8CBF\u927E\u9632\u5420\u982C\u5317\u50D5\u535C\u58A8\u64B2\u6734\u7267\u7766\u7A46\u91E6\u52C3\u6CA1\u6B86\u5800\u5E4C\u5954\u672C\u7FFB\u51E1\u76C6\u6469\u78E8\u9B54\u9EBB\u57CB\u59B9\u6627\u679A\u6BCE\u54E9\u69D9\u5E55\u819C\u6795\u9BAA\u67FE\u9C52\u685D\u4EA6\u4FE3\u53C8\u62B9\u672B\u6CAB\u8FC4\u4FAD\u7E6D\u9EBF\u4E07\u6162\u6E80"], - ["cca1", "\u6F2B\u8513\u5473\u672A\u9B45\u5DF3\u7B95\u5CAC\u5BC6\u871C\u6E4A\u84D1\u7A14\u8108\u5999\u7C8D\u6C11\u7720\u52D9\u5922\u7121\u725F\u77DB\u9727\u9D61\u690B\u5A7F\u5A18\u51A5\u540D\u547D\u660E\u76DF\u8FF7\u9298\u9CF4\u59EA\u725D\u6EC5\u514D\u68C9\u7DBF\u7DEC\u9762\u9EBA\u6478\u6A21\u8302\u5984\u5B5F\u6BDB\u731B\u76F2\u7DB2\u8017\u8499\u5132\u6728\u9ED9\u76EE\u6762\u52FF\u9905\u5C24\u623B\u7C7E\u8CB0\u554F\u60B6\u7D0B\u9580\u5301\u4E5F\u51B6\u591C\u723A\u8036\u91CE\u5F25\u77E2\u5384\u5F79\u7D04\u85AC\u8A33\u8E8D\u9756\u67F3\u85AE\u9453\u6109\u6108\u6CB9\u7652"], - ["cda1", "\u8AED\u8F38\u552F\u4F51\u512A\u52C7\u53CB\u5BA5\u5E7D\u60A0\u6182\u63D6\u6709\u67DA\u6E67\u6D8C\u7336\u7337\u7531\u7950\u88D5\u8A98\u904A\u9091\u90F5\u96C4\u878D\u5915\u4E88\u4F59\u4E0E\u8A89\u8F3F\u9810\u50AD\u5E7C\u5996\u5BB9\u5EB8\u63DA\u63FA\u64C1\u66DC\u694A\u69D8\u6D0B\u6EB6\u7194\u7528\u7AAF\u7F8A\u8000\u8449\u84C9\u8981\u8B21\u8E0A\u9065\u967D\u990A\u617E\u6291\u6B32\u6C83\u6D74\u7FCC\u7FFC\u6DC0\u7F85\u87BA\u88F8\u6765\u83B1\u983C\u96F7\u6D1B\u7D61\u843D\u916A\u4E71\u5375\u5D50\u6B04\u6FEB\u85CD\u862D\u89A7\u5229\u540F\u5C65\u674E\u68A8\u7406\u7483"], - ["cea1", "\u75E2\u88CF\u88E1\u91CC\u96E2\u9678\u5F8B\u7387\u7ACB\u844E\u63A0\u7565\u5289\u6D41\u6E9C\u7409\u7559\u786B\u7C92\u9686\u7ADC\u9F8D\u4FB6\u616E\u65C5\u865C\u4E86\u4EAE\u50DA\u4E21\u51CC\u5BEE\u6599\u6881\u6DBC\u731F\u7642\u77AD\u7A1C\u7CE7\u826F\u8AD2\u907C\u91CF\u9675\u9818\u529B\u7DD1\u502B\u5398\u6797\u6DCB\u71D0\u7433\u81E8\u8F2A\u96A3\u9C57\u9E9F\u7460\u5841\u6D99\u7D2F\u985E\u4EE4\u4F36\u4F8B\u51B7\u52B1\u5DBA\u601C\u73B2\u793C\u82D3\u9234\u96B7\u96F6\u970A\u9E97\u9F62\u66A6\u6B74\u5217\u52A3\u70C8\u88C2\u5EC9\u604B\u6190\u6F23\u7149\u7C3E\u7DF4\u806F"], - ["cfa1", "\u84EE\u9023\u932C\u5442\u9B6F\u6AD3\u7089\u8CC2\u8DEF\u9732\u52B4\u5A41\u5ECA\u5F04\u6717\u697C\u6994\u6D6A\u6F0F\u7262\u72FC\u7BED\u8001\u807E\u874B\u90CE\u516D\u9E93\u7984\u808B\u9332\u8AD6\u502D\u548C\u8A71\u6B6A\u8CC4\u8107\u60D1\u67A0\u9DF2\u4E99\u4E98\u9C10\u8A6B\u85C1\u8568\u6900\u6E7E\u7897\u8155"], - ["d0a1", "\u5F0C\u4E10\u4E15\u4E2A\u4E31\u4E36\u4E3C\u4E3F\u4E42\u4E56\u4E58\u4E82\u4E85\u8C6B\u4E8A\u8212\u5F0D\u4E8E\u4E9E\u4E9F\u4EA0\u4EA2\u4EB0\u4EB3\u4EB6\u4ECE\u4ECD\u4EC4\u4EC6\u4EC2\u4ED7\u4EDE\u4EED\u4EDF\u4EF7\u4F09\u4F5A\u4F30\u4F5B\u4F5D\u4F57\u4F47\u4F76\u4F88\u4F8F\u4F98\u4F7B\u4F69\u4F70\u4F91\u4F6F\u4F86\u4F96\u5118\u4FD4\u4FDF\u4FCE\u4FD8\u4FDB\u4FD1\u4FDA\u4FD0\u4FE4\u4FE5\u501A\u5028\u5014\u502A\u5025\u5005\u4F1C\u4FF6\u5021\u5029\u502C\u4FFE\u4FEF\u5011\u5006\u5043\u5047\u6703\u5055\u5050\u5048\u505A\u5056\u506C\u5078\u5080\u509A\u5085\u50B4\u50B2"], - ["d1a1", "\u50C9\u50CA\u50B3\u50C2\u50D6\u50DE\u50E5\u50ED\u50E3\u50EE\u50F9\u50F5\u5109\u5101\u5102\u5116\u5115\u5114\u511A\u5121\u513A\u5137\u513C\u513B\u513F\u5140\u5152\u514C\u5154\u5162\u7AF8\u5169\u516A\u516E\u5180\u5182\u56D8\u518C\u5189\u518F\u5191\u5193\u5195\u5196\u51A4\u51A6\u51A2\u51A9\u51AA\u51AB\u51B3\u51B1\u51B2\u51B0\u51B5\u51BD\u51C5\u51C9\u51DB\u51E0\u8655\u51E9\u51ED\u51F0\u51F5\u51FE\u5204\u520B\u5214\u520E\u5227\u522A\u522E\u5233\u5239\u524F\u5244\u524B\u524C\u525E\u5254\u526A\u5274\u5269\u5273\u527F\u527D\u528D\u5294\u5292\u5271\u5288\u5291\u8FA8"], - ["d2a1", "\u8FA7\u52AC\u52AD\u52BC\u52B5\u52C1\u52CD\u52D7\u52DE\u52E3\u52E6\u98ED\u52E0\u52F3\u52F5\u52F8\u52F9\u5306\u5308\u7538\u530D\u5310\u530F\u5315\u531A\u5323\u532F\u5331\u5333\u5338\u5340\u5346\u5345\u4E17\u5349\u534D\u51D6\u535E\u5369\u536E\u5918\u537B\u5377\u5382\u5396\u53A0\u53A6\u53A5\u53AE\u53B0\u53B6\u53C3\u7C12\u96D9\u53DF\u66FC\u71EE\u53EE\u53E8\u53ED\u53FA\u5401\u543D\u5440\u542C\u542D\u543C\u542E\u5436\u5429\u541D\u544E\u548F\u5475\u548E\u545F\u5471\u5477\u5470\u5492\u547B\u5480\u5476\u5484\u5490\u5486\u54C7\u54A2\u54B8\u54A5\u54AC\u54C4\u54C8\u54A8"], - ["d3a1", "\u54AB\u54C2\u54A4\u54BE\u54BC\u54D8\u54E5\u54E6\u550F\u5514\u54FD\u54EE\u54ED\u54FA\u54E2\u5539\u5540\u5563\u554C\u552E\u555C\u5545\u5556\u5557\u5538\u5533\u555D\u5599\u5580\u54AF\u558A\u559F\u557B\u557E\u5598\u559E\u55AE\u557C\u5583\u55A9\u5587\u55A8\u55DA\u55C5\u55DF\u55C4\u55DC\u55E4\u55D4\u5614\u55F7\u5616\u55FE\u55FD\u561B\u55F9\u564E\u5650\u71DF\u5634\u5636\u5632\u5638\u566B\u5664\u562F\u566C\u566A\u5686\u5680\u568A\u56A0\u5694\u568F\u56A5\u56AE\u56B6\u56B4\u56C2\u56BC\u56C1\u56C3\u56C0\u56C8\u56CE\u56D1\u56D3\u56D7\u56EE\u56F9\u5700\u56FF\u5704\u5709"], - ["d4a1", "\u5708\u570B\u570D\u5713\u5718\u5716\u55C7\u571C\u5726\u5737\u5738\u574E\u573B\u5740\u574F\u5769\u57C0\u5788\u5761\u577F\u5789\u5793\u57A0\u57B3\u57A4\u57AA\u57B0\u57C3\u57C6\u57D4\u57D2\u57D3\u580A\u57D6\u57E3\u580B\u5819\u581D\u5872\u5821\u5862\u584B\u5870\u6BC0\u5852\u583D\u5879\u5885\u58B9\u589F\u58AB\u58BA\u58DE\u58BB\u58B8\u58AE\u58C5\u58D3\u58D1\u58D7\u58D9\u58D8\u58E5\u58DC\u58E4\u58DF\u58EF\u58FA\u58F9\u58FB\u58FC\u58FD\u5902\u590A\u5910\u591B\u68A6\u5925\u592C\u592D\u5932\u5938\u593E\u7AD2\u5955\u5950\u594E\u595A\u5958\u5962\u5960\u5967\u596C\u5969"], - ["d5a1", "\u5978\u5981\u599D\u4F5E\u4FAB\u59A3\u59B2\u59C6\u59E8\u59DC\u598D\u59D9\u59DA\u5A25\u5A1F\u5A11\u5A1C\u5A09\u5A1A\u5A40\u5A6C\u5A49\u5A35\u5A36\u5A62\u5A6A\u5A9A\u5ABC\u5ABE\u5ACB\u5AC2\u5ABD\u5AE3\u5AD7\u5AE6\u5AE9\u5AD6\u5AFA\u5AFB\u5B0C\u5B0B\u5B16\u5B32\u5AD0\u5B2A\u5B36\u5B3E\u5B43\u5B45\u5B40\u5B51\u5B55\u5B5A\u5B5B\u5B65\u5B69\u5B70\u5B73\u5B75\u5B78\u6588\u5B7A\u5B80\u5B83\u5BA6\u5BB8\u5BC3\u5BC7\u5BC9\u5BD4\u5BD0\u5BE4\u5BE6\u5BE2\u5BDE\u5BE5\u5BEB\u5BF0\u5BF6\u5BF3\u5C05\u5C07\u5C08\u5C0D\u5C13\u5C20\u5C22\u5C28\u5C38\u5C39\u5C41\u5C46\u5C4E\u5C53"], - ["d6a1", "\u5C50\u5C4F\u5B71\u5C6C\u5C6E\u4E62\u5C76\u5C79\u5C8C\u5C91\u5C94\u599B\u5CAB\u5CBB\u5CB6\u5CBC\u5CB7\u5CC5\u5CBE\u5CC7\u5CD9\u5CE9\u5CFD\u5CFA\u5CED\u5D8C\u5CEA\u5D0B\u5D15\u5D17\u5D5C\u5D1F\u5D1B\u5D11\u5D14\u5D22\u5D1A\u5D19\u5D18\u5D4C\u5D52\u5D4E\u5D4B\u5D6C\u5D73\u5D76\u5D87\u5D84\u5D82\u5DA2\u5D9D\u5DAC\u5DAE\u5DBD\u5D90\u5DB7\u5DBC\u5DC9\u5DCD\u5DD3\u5DD2\u5DD6\u5DDB\u5DEB\u5DF2\u5DF5\u5E0B\u5E1A\u5E19\u5E11\u5E1B\u5E36\u5E37\u5E44\u5E43\u5E40\u5E4E\u5E57\u5E54\u5E5F\u5E62\u5E64\u5E47\u5E75\u5E76\u5E7A\u9EBC\u5E7F\u5EA0\u5EC1\u5EC2\u5EC8\u5ED0\u5ECF"], - ["d7a1", "\u5ED6\u5EE3\u5EDD\u5EDA\u5EDB\u5EE2\u5EE1\u5EE8\u5EE9\u5EEC\u5EF1\u5EF3\u5EF0\u5EF4\u5EF8\u5EFE\u5F03\u5F09\u5F5D\u5F5C\u5F0B\u5F11\u5F16\u5F29\u5F2D\u5F38\u5F41\u5F48\u5F4C\u5F4E\u5F2F\u5F51\u5F56\u5F57\u5F59\u5F61\u5F6D\u5F73\u5F77\u5F83\u5F82\u5F7F\u5F8A\u5F88\u5F91\u5F87\u5F9E\u5F99\u5F98\u5FA0\u5FA8\u5FAD\u5FBC\u5FD6\u5FFB\u5FE4\u5FF8\u5FF1\u5FDD\u60B3\u5FFF\u6021\u6060\u6019\u6010\u6029\u600E\u6031\u601B\u6015\u602B\u6026\u600F\u603A\u605A\u6041\u606A\u6077\u605F\u604A\u6046\u604D\u6063\u6043\u6064\u6042\u606C\u606B\u6059\u6081\u608D\u60E7\u6083\u609A"], - ["d8a1", "\u6084\u609B\u6096\u6097\u6092\u60A7\u608B\u60E1\u60B8\u60E0\u60D3\u60B4\u5FF0\u60BD\u60C6\u60B5\u60D8\u614D\u6115\u6106\u60F6\u60F7\u6100\u60F4\u60FA\u6103\u6121\u60FB\u60F1\u610D\u610E\u6147\u613E\u6128\u6127\u614A\u613F\u613C\u612C\u6134\u613D\u6142\u6144\u6173\u6177\u6158\u6159\u615A\u616B\u6174\u616F\u6165\u6171\u615F\u615D\u6153\u6175\u6199\u6196\u6187\u61AC\u6194\u619A\u618A\u6191\u61AB\u61AE\u61CC\u61CA\u61C9\u61F7\u61C8\u61C3\u61C6\u61BA\u61CB\u7F79\u61CD\u61E6\u61E3\u61F6\u61FA\u61F4\u61FF\u61FD\u61FC\u61FE\u6200\u6208\u6209\u620D\u620C\u6214\u621B"], - ["d9a1", "\u621E\u6221\u622A\u622E\u6230\u6232\u6233\u6241\u624E\u625E\u6263\u625B\u6260\u6268\u627C\u6282\u6289\u627E\u6292\u6293\u6296\u62D4\u6283\u6294\u62D7\u62D1\u62BB\u62CF\u62FF\u62C6\u64D4\u62C8\u62DC\u62CC\u62CA\u62C2\u62C7\u629B\u62C9\u630C\u62EE\u62F1\u6327\u6302\u6308\u62EF\u62F5\u6350\u633E\u634D\u641C\u634F\u6396\u638E\u6380\u63AB\u6376\u63A3\u638F\u6389\u639F\u63B5\u636B\u6369\u63BE\u63E9\u63C0\u63C6\u63E3\u63C9\u63D2\u63F6\u63C4\u6416\u6434\u6406\u6413\u6426\u6436\u651D\u6417\u6428\u640F\u6467\u646F\u6476\u644E\u652A\u6495\u6493\u64A5\u64A9\u6488\u64BC"], - ["daa1", "\u64DA\u64D2\u64C5\u64C7\u64BB\u64D8\u64C2\u64F1\u64E7\u8209\u64E0\u64E1\u62AC\u64E3\u64EF\u652C\u64F6\u64F4\u64F2\u64FA\u6500\u64FD\u6518\u651C\u6505\u6524\u6523\u652B\u6534\u6535\u6537\u6536\u6538\u754B\u6548\u6556\u6555\u654D\u6558\u655E\u655D\u6572\u6578\u6582\u6583\u8B8A\u659B\u659F\u65AB\u65B7\u65C3\u65C6\u65C1\u65C4\u65CC\u65D2\u65DB\u65D9\u65E0\u65E1\u65F1\u6772\u660A\u6603\u65FB\u6773\u6635\u6636\u6634\u661C\u664F\u6644\u6649\u6641\u665E\u665D\u6664\u6667\u6668\u665F\u6662\u6670\u6683\u6688\u668E\u6689\u6684\u6698\u669D\u66C1\u66B9\u66C9\u66BE\u66BC"], - ["dba1", "\u66C4\u66B8\u66D6\u66DA\u66E0\u663F\u66E6\u66E9\u66F0\u66F5\u66F7\u670F\u6716\u671E\u6726\u6727\u9738\u672E\u673F\u6736\u6741\u6738\u6737\u6746\u675E\u6760\u6759\u6763\u6764\u6789\u6770\u67A9\u677C\u676A\u678C\u678B\u67A6\u67A1\u6785\u67B7\u67EF\u67B4\u67EC\u67B3\u67E9\u67B8\u67E4\u67DE\u67DD\u67E2\u67EE\u67B9\u67CE\u67C6\u67E7\u6A9C\u681E\u6846\u6829\u6840\u684D\u6832\u684E\u68B3\u682B\u6859\u6863\u6877\u687F\u689F\u688F\u68AD\u6894\u689D\u689B\u6883\u6AAE\u68B9\u6874\u68B5\u68A0\u68BA\u690F\u688D\u687E\u6901\u68CA\u6908\u68D8\u6922\u6926\u68E1\u690C\u68CD"], - ["dca1", "\u68D4\u68E7\u68D5\u6936\u6912\u6904\u68D7\u68E3\u6925\u68F9\u68E0\u68EF\u6928\u692A\u691A\u6923\u6921\u68C6\u6979\u6977\u695C\u6978\u696B\u6954\u697E\u696E\u6939\u6974\u693D\u6959\u6930\u6961\u695E\u695D\u6981\u696A\u69B2\u69AE\u69D0\u69BF\u69C1\u69D3\u69BE\u69CE\u5BE8\u69CA\u69DD\u69BB\u69C3\u69A7\u6A2E\u6991\u69A0\u699C\u6995\u69B4\u69DE\u69E8\u6A02\u6A1B\u69FF\u6B0A\u69F9\u69F2\u69E7\u6A05\u69B1\u6A1E\u69ED\u6A14\u69EB\u6A0A\u6A12\u6AC1\u6A23\u6A13\u6A44\u6A0C\u6A72\u6A36\u6A78\u6A47\u6A62\u6A59\u6A66\u6A48\u6A38\u6A22\u6A90\u6A8D\u6AA0\u6A84\u6AA2\u6AA3"], - ["dda1", "\u6A97\u8617\u6ABB\u6AC3\u6AC2\u6AB8\u6AB3\u6AAC\u6ADE\u6AD1\u6ADF\u6AAA\u6ADA\u6AEA\u6AFB\u6B05\u8616\u6AFA\u6B12\u6B16\u9B31\u6B1F\u6B38\u6B37\u76DC\u6B39\u98EE\u6B47\u6B43\u6B49\u6B50\u6B59\u6B54\u6B5B\u6B5F\u6B61\u6B78\u6B79\u6B7F\u6B80\u6B84\u6B83\u6B8D\u6B98\u6B95\u6B9E\u6BA4\u6BAA\u6BAB\u6BAF\u6BB2\u6BB1\u6BB3\u6BB7\u6BBC\u6BC6\u6BCB\u6BD3\u6BDF\u6BEC\u6BEB\u6BF3\u6BEF\u9EBE\u6C08\u6C13\u6C14\u6C1B\u6C24\u6C23\u6C5E\u6C55\u6C62\u6C6A\u6C82\u6C8D\u6C9A\u6C81\u6C9B\u6C7E\u6C68\u6C73\u6C92\u6C90\u6CC4\u6CF1\u6CD3\u6CBD\u6CD7\u6CC5\u6CDD\u6CAE\u6CB1\u6CBE"], - ["dea1", "\u6CBA\u6CDB\u6CEF\u6CD9\u6CEA\u6D1F\u884D\u6D36\u6D2B\u6D3D\u6D38\u6D19\u6D35\u6D33\u6D12\u6D0C\u6D63\u6D93\u6D64\u6D5A\u6D79\u6D59\u6D8E\u6D95\u6FE4\u6D85\u6DF9\u6E15\u6E0A\u6DB5\u6DC7\u6DE6\u6DB8\u6DC6\u6DEC\u6DDE\u6DCC\u6DE8\u6DD2\u6DC5\u6DFA\u6DD9\u6DE4\u6DD5\u6DEA\u6DEE\u6E2D\u6E6E\u6E2E\u6E19\u6E72\u6E5F\u6E3E\u6E23\u6E6B\u6E2B\u6E76\u6E4D\u6E1F\u6E43\u6E3A\u6E4E\u6E24\u6EFF\u6E1D\u6E38\u6E82\u6EAA\u6E98\u6EC9\u6EB7\u6ED3\u6EBD\u6EAF\u6EC4\u6EB2\u6ED4\u6ED5\u6E8F\u6EA5\u6EC2\u6E9F\u6F41\u6F11\u704C\u6EEC\u6EF8\u6EFE\u6F3F\u6EF2\u6F31\u6EEF\u6F32\u6ECC"], - ["dfa1", "\u6F3E\u6F13\u6EF7\u6F86\u6F7A\u6F78\u6F81\u6F80\u6F6F\u6F5B\u6FF3\u6F6D\u6F82\u6F7C\u6F58\u6F8E\u6F91\u6FC2\u6F66\u6FB3\u6FA3\u6FA1\u6FA4\u6FB9\u6FC6\u6FAA\u6FDF\u6FD5\u6FEC\u6FD4\u6FD8\u6FF1\u6FEE\u6FDB\u7009\u700B\u6FFA\u7011\u7001\u700F\u6FFE\u701B\u701A\u6F74\u701D\u7018\u701F\u7030\u703E\u7032\u7051\u7063\u7099\u7092\u70AF\u70F1\u70AC\u70B8\u70B3\u70AE\u70DF\u70CB\u70DD\u70D9\u7109\u70FD\u711C\u7119\u7165\u7155\u7188\u7166\u7162\u714C\u7156\u716C\u718F\u71FB\u7184\u7195\u71A8\u71AC\u71D7\u71B9\u71BE\u71D2\u71C9\u71D4\u71CE\u71E0\u71EC\u71E7\u71F5\u71FC"], - ["e0a1", "\u71F9\u71FF\u720D\u7210\u721B\u7228\u722D\u722C\u7230\u7232\u723B\u723C\u723F\u7240\u7246\u724B\u7258\u7274\u727E\u7282\u7281\u7287\u7292\u7296\u72A2\u72A7\u72B9\u72B2\u72C3\u72C6\u72C4\u72CE\u72D2\u72E2\u72E0\u72E1\u72F9\u72F7\u500F\u7317\u730A\u731C\u7316\u731D\u7334\u732F\u7329\u7325\u733E\u734E\u734F\u9ED8\u7357\u736A\u7368\u7370\u7378\u7375\u737B\u737A\u73C8\u73B3\u73CE\u73BB\u73C0\u73E5\u73EE\u73DE\u74A2\u7405\u746F\u7425\u73F8\u7432\u743A\u7455\u743F\u745F\u7459\u7441\u745C\u7469\u7470\u7463\u746A\u7476\u747E\u748B\u749E\u74A7\u74CA\u74CF\u74D4\u73F1"], - ["e1a1", "\u74E0\u74E3\u74E7\u74E9\u74EE\u74F2\u74F0\u74F1\u74F8\u74F7\u7504\u7503\u7505\u750C\u750E\u750D\u7515\u7513\u751E\u7526\u752C\u753C\u7544\u754D\u754A\u7549\u755B\u7546\u755A\u7569\u7564\u7567\u756B\u756D\u7578\u7576\u7586\u7587\u7574\u758A\u7589\u7582\u7594\u759A\u759D\u75A5\u75A3\u75C2\u75B3\u75C3\u75B5\u75BD\u75B8\u75BC\u75B1\u75CD\u75CA\u75D2\u75D9\u75E3\u75DE\u75FE\u75FF\u75FC\u7601\u75F0\u75FA\u75F2\u75F3\u760B\u760D\u7609\u761F\u7627\u7620\u7621\u7622\u7624\u7634\u7630\u763B\u7647\u7648\u7646\u765C\u7658\u7661\u7662\u7668\u7669\u766A\u7667\u766C\u7670"], - ["e2a1", "\u7672\u7676\u7678\u767C\u7680\u7683\u7688\u768B\u768E\u7696\u7693\u7699\u769A\u76B0\u76B4\u76B8\u76B9\u76BA\u76C2\u76CD\u76D6\u76D2\u76DE\u76E1\u76E5\u76E7\u76EA\u862F\u76FB\u7708\u7707\u7704\u7729\u7724\u771E\u7725\u7726\u771B\u7737\u7738\u7747\u775A\u7768\u776B\u775B\u7765\u777F\u777E\u7779\u778E\u778B\u7791\u77A0\u779E\u77B0\u77B6\u77B9\u77BF\u77BC\u77BD\u77BB\u77C7\u77CD\u77D7\u77DA\u77DC\u77E3\u77EE\u77FC\u780C\u7812\u7926\u7820\u792A\u7845\u788E\u7874\u7886\u787C\u789A\u788C\u78A3\u78B5\u78AA\u78AF\u78D1\u78C6\u78CB\u78D4\u78BE\u78BC\u78C5\u78CA\u78EC"], - ["e3a1", "\u78E7\u78DA\u78FD\u78F4\u7907\u7912\u7911\u7919\u792C\u792B\u7940\u7960\u7957\u795F\u795A\u7955\u7953\u797A\u797F\u798A\u799D\u79A7\u9F4B\u79AA\u79AE\u79B3\u79B9\u79BA\u79C9\u79D5\u79E7\u79EC\u79E1\u79E3\u7A08\u7A0D\u7A18\u7A19\u7A20\u7A1F\u7980\u7A31\u7A3B\u7A3E\u7A37\u7A43\u7A57\u7A49\u7A61\u7A62\u7A69\u9F9D\u7A70\u7A79\u7A7D\u7A88\u7A97\u7A95\u7A98\u7A96\u7AA9\u7AC8\u7AB0\u7AB6\u7AC5\u7AC4\u7ABF\u9083\u7AC7\u7ACA\u7ACD\u7ACF\u7AD5\u7AD3\u7AD9\u7ADA\u7ADD\u7AE1\u7AE2\u7AE6\u7AED\u7AF0\u7B02\u7B0F\u7B0A\u7B06\u7B33\u7B18\u7B19\u7B1E\u7B35\u7B28\u7B36\u7B50"], - ["e4a1", "\u7B7A\u7B04\u7B4D\u7B0B\u7B4C\u7B45\u7B75\u7B65\u7B74\u7B67\u7B70\u7B71\u7B6C\u7B6E\u7B9D\u7B98\u7B9F\u7B8D\u7B9C\u7B9A\u7B8B\u7B92\u7B8F\u7B5D\u7B99\u7BCB\u7BC1\u7BCC\u7BCF\u7BB4\u7BC6\u7BDD\u7BE9\u7C11\u7C14\u7BE6\u7BE5\u7C60\u7C00\u7C07\u7C13\u7BF3\u7BF7\u7C17\u7C0D\u7BF6\u7C23\u7C27\u7C2A\u7C1F\u7C37\u7C2B\u7C3D\u7C4C\u7C43\u7C54\u7C4F\u7C40\u7C50\u7C58\u7C5F\u7C64\u7C56\u7C65\u7C6C\u7C75\u7C83\u7C90\u7CA4\u7CAD\u7CA2\u7CAB\u7CA1\u7CA8\u7CB3\u7CB2\u7CB1\u7CAE\u7CB9\u7CBD\u7CC0\u7CC5\u7CC2\u7CD8\u7CD2\u7CDC\u7CE2\u9B3B\u7CEF\u7CF2\u7CF4\u7CF6\u7CFA\u7D06"], - ["e5a1", "\u7D02\u7D1C\u7D15\u7D0A\u7D45\u7D4B\u7D2E\u7D32\u7D3F\u7D35\u7D46\u7D73\u7D56\u7D4E\u7D72\u7D68\u7D6E\u7D4F\u7D63\u7D93\u7D89\u7D5B\u7D8F\u7D7D\u7D9B\u7DBA\u7DAE\u7DA3\u7DB5\u7DC7\u7DBD\u7DAB\u7E3D\u7DA2\u7DAF\u7DDC\u7DB8\u7D9F\u7DB0\u7DD8\u7DDD\u7DE4\u7DDE\u7DFB\u7DF2\u7DE1\u7E05\u7E0A\u7E23\u7E21\u7E12\u7E31\u7E1F\u7E09\u7E0B\u7E22\u7E46\u7E66\u7E3B\u7E35\u7E39\u7E43\u7E37\u7E32\u7E3A\u7E67\u7E5D\u7E56\u7E5E\u7E59\u7E5A\u7E79\u7E6A\u7E69\u7E7C\u7E7B\u7E83\u7DD5\u7E7D\u8FAE\u7E7F\u7E88\u7E89\u7E8C\u7E92\u7E90\u7E93\u7E94\u7E96\u7E8E\u7E9B\u7E9C\u7F38\u7F3A"], - ["e6a1", "\u7F45\u7F4C\u7F4D\u7F4E\u7F50\u7F51\u7F55\u7F54\u7F58\u7F5F\u7F60\u7F68\u7F69\u7F67\u7F78\u7F82\u7F86\u7F83\u7F88\u7F87\u7F8C\u7F94\u7F9E\u7F9D\u7F9A\u7FA3\u7FAF\u7FB2\u7FB9\u7FAE\u7FB6\u7FB8\u8B71\u7FC5\u7FC6\u7FCA\u7FD5\u7FD4\u7FE1\u7FE6\u7FE9\u7FF3\u7FF9\u98DC\u8006\u8004\u800B\u8012\u8018\u8019\u801C\u8021\u8028\u803F\u803B\u804A\u8046\u8052\u8058\u805A\u805F\u8062\u8068\u8073\u8072\u8070\u8076\u8079\u807D\u807F\u8084\u8086\u8085\u809B\u8093\u809A\u80AD\u5190\u80AC\u80DB\u80E5\u80D9\u80DD\u80C4\u80DA\u80D6\u8109\u80EF\u80F1\u811B\u8129\u8123\u812F\u814B"], - ["e7a1", "\u968B\u8146\u813E\u8153\u8151\u80FC\u8171\u816E\u8165\u8166\u8174\u8183\u8188\u818A\u8180\u8182\u81A0\u8195\u81A4\u81A3\u815F\u8193\u81A9\u81B0\u81B5\u81BE\u81B8\u81BD\u81C0\u81C2\u81BA\u81C9\u81CD\u81D1\u81D9\u81D8\u81C8\u81DA\u81DF\u81E0\u81E7\u81FA\u81FB\u81FE\u8201\u8202\u8205\u8207\u820A\u820D\u8210\u8216\u8229\u822B\u8238\u8233\u8240\u8259\u8258\u825D\u825A\u825F\u8264\u8262\u8268\u826A\u826B\u822E\u8271\u8277\u8278\u827E\u828D\u8292\u82AB\u829F\u82BB\u82AC\u82E1\u82E3\u82DF\u82D2\u82F4\u82F3\u82FA\u8393\u8303\u82FB\u82F9\u82DE\u8306\u82DC\u8309\u82D9"], - ["e8a1", "\u8335\u8334\u8316\u8332\u8331\u8340\u8339\u8350\u8345\u832F\u832B\u8317\u8318\u8385\u839A\u83AA\u839F\u83A2\u8396\u8323\u838E\u8387\u838A\u837C\u83B5\u8373\u8375\u83A0\u8389\u83A8\u83F4\u8413\u83EB\u83CE\u83FD\u8403\u83D8\u840B\u83C1\u83F7\u8407\u83E0\u83F2\u840D\u8422\u8420\u83BD\u8438\u8506\u83FB\u846D\u842A\u843C\u855A\u8484\u8477\u846B\u84AD\u846E\u8482\u8469\u8446\u842C\u846F\u8479\u8435\u84CA\u8462\u84B9\u84BF\u849F\u84D9\u84CD\u84BB\u84DA\u84D0\u84C1\u84C6\u84D6\u84A1\u8521\u84FF\u84F4\u8517\u8518\u852C\u851F\u8515\u8514\u84FC\u8540\u8563\u8558\u8548"], - ["e9a1", "\u8541\u8602\u854B\u8555\u8580\u85A4\u8588\u8591\u858A\u85A8\u856D\u8594\u859B\u85EA\u8587\u859C\u8577\u857E\u8590\u85C9\u85BA\u85CF\u85B9\u85D0\u85D5\u85DD\u85E5\u85DC\u85F9\u860A\u8613\u860B\u85FE\u85FA\u8606\u8622\u861A\u8630\u863F\u864D\u4E55\u8654\u865F\u8667\u8671\u8693\u86A3\u86A9\u86AA\u868B\u868C\u86B6\u86AF\u86C4\u86C6\u86B0\u86C9\u8823\u86AB\u86D4\u86DE\u86E9\u86EC\u86DF\u86DB\u86EF\u8712\u8706\u8708\u8700\u8703\u86FB\u8711\u8709\u870D\u86F9\u870A\u8734\u873F\u8737\u873B\u8725\u8729\u871A\u8760\u875F\u8778\u874C\u874E\u8774\u8757\u8768\u876E\u8759"], - ["eaa1", "\u8753\u8763\u876A\u8805\u87A2\u879F\u8782\u87AF\u87CB\u87BD\u87C0\u87D0\u96D6\u87AB\u87C4\u87B3\u87C7\u87C6\u87BB\u87EF\u87F2\u87E0\u880F\u880D\u87FE\u87F6\u87F7\u880E\u87D2\u8811\u8816\u8815\u8822\u8821\u8831\u8836\u8839\u8827\u883B\u8844\u8842\u8852\u8859\u885E\u8862\u886B\u8881\u887E\u889E\u8875\u887D\u88B5\u8872\u8882\u8897\u8892\u88AE\u8899\u88A2\u888D\u88A4\u88B0\u88BF\u88B1\u88C3\u88C4\u88D4\u88D8\u88D9\u88DD\u88F9\u8902\u88FC\u88F4\u88E8\u88F2\u8904\u890C\u890A\u8913\u8943\u891E\u8925\u892A\u892B\u8941\u8944\u893B\u8936\u8938\u894C\u891D\u8960\u895E"], - ["eba1", "\u8966\u8964\u896D\u896A\u896F\u8974\u8977\u897E\u8983\u8988\u898A\u8993\u8998\u89A1\u89A9\u89A6\u89AC\u89AF\u89B2\u89BA\u89BD\u89BF\u89C0\u89DA\u89DC\u89DD\u89E7\u89F4\u89F8\u8A03\u8A16\u8A10\u8A0C\u8A1B\u8A1D\u8A25\u8A36\u8A41\u8A5B\u8A52\u8A46\u8A48\u8A7C\u8A6D\u8A6C\u8A62\u8A85\u8A82\u8A84\u8AA8\u8AA1\u8A91\u8AA5\u8AA6\u8A9A\u8AA3\u8AC4\u8ACD\u8AC2\u8ADA\u8AEB\u8AF3\u8AE7\u8AE4\u8AF1\u8B14\u8AE0\u8AE2\u8AF7\u8ADE\u8ADB\u8B0C\u8B07\u8B1A\u8AE1\u8B16\u8B10\u8B17\u8B20\u8B33\u97AB\u8B26\u8B2B\u8B3E\u8B28\u8B41\u8B4C\u8B4F\u8B4E\u8B49\u8B56\u8B5B\u8B5A\u8B6B"], - ["eca1", "\u8B5F\u8B6C\u8B6F\u8B74\u8B7D\u8B80\u8B8C\u8B8E\u8B92\u8B93\u8B96\u8B99\u8B9A\u8C3A\u8C41\u8C3F\u8C48\u8C4C\u8C4E\u8C50\u8C55\u8C62\u8C6C\u8C78\u8C7A\u8C82\u8C89\u8C85\u8C8A\u8C8D\u8C8E\u8C94\u8C7C\u8C98\u621D\u8CAD\u8CAA\u8CBD\u8CB2\u8CB3\u8CAE\u8CB6\u8CC8\u8CC1\u8CE4\u8CE3\u8CDA\u8CFD\u8CFA\u8CFB\u8D04\u8D05\u8D0A\u8D07\u8D0F\u8D0D\u8D10\u9F4E\u8D13\u8CCD\u8D14\u8D16\u8D67\u8D6D\u8D71\u8D73\u8D81\u8D99\u8DC2\u8DBE\u8DBA\u8DCF\u8DDA\u8DD6\u8DCC\u8DDB\u8DCB\u8DEA\u8DEB\u8DDF\u8DE3\u8DFC\u8E08\u8E09\u8DFF\u8E1D\u8E1E\u8E10\u8E1F\u8E42\u8E35\u8E30\u8E34\u8E4A"], - ["eda1", "\u8E47\u8E49\u8E4C\u8E50\u8E48\u8E59\u8E64\u8E60\u8E2A\u8E63\u8E55\u8E76\u8E72\u8E7C\u8E81\u8E87\u8E85\u8E84\u8E8B\u8E8A\u8E93\u8E91\u8E94\u8E99\u8EAA\u8EA1\u8EAC\u8EB0\u8EC6\u8EB1\u8EBE\u8EC5\u8EC8\u8ECB\u8EDB\u8EE3\u8EFC\u8EFB\u8EEB\u8EFE\u8F0A\u8F05\u8F15\u8F12\u8F19\u8F13\u8F1C\u8F1F\u8F1B\u8F0C\u8F26\u8F33\u8F3B\u8F39\u8F45\u8F42\u8F3E\u8F4C\u8F49\u8F46\u8F4E\u8F57\u8F5C\u8F62\u8F63\u8F64\u8F9C\u8F9F\u8FA3\u8FAD\u8FAF\u8FB7\u8FDA\u8FE5\u8FE2\u8FEA\u8FEF\u9087\u8FF4\u9005\u8FF9\u8FFA\u9011\u9015\u9021\u900D\u901E\u9016\u900B\u9027\u9036\u9035\u9039\u8FF8"], - ["eea1", "\u904F\u9050\u9051\u9052\u900E\u9049\u903E\u9056\u9058\u905E\u9068\u906F\u9076\u96A8\u9072\u9082\u907D\u9081\u9080\u908A\u9089\u908F\u90A8\u90AF\u90B1\u90B5\u90E2\u90E4\u6248\u90DB\u9102\u9112\u9119\u9132\u9130\u914A\u9156\u9158\u9163\u9165\u9169\u9173\u9172\u918B\u9189\u9182\u91A2\u91AB\u91AF\u91AA\u91B5\u91B4\u91BA\u91C0\u91C1\u91C9\u91CB\u91D0\u91D6\u91DF\u91E1\u91DB\u91FC\u91F5\u91F6\u921E\u91FF\u9214\u922C\u9215\u9211\u925E\u9257\u9245\u9249\u9264\u9248\u9295\u923F\u924B\u9250\u929C\u9296\u9293\u929B\u925A\u92CF\u92B9\u92B7\u92E9\u930F\u92FA\u9344\u932E"], - ["efa1", "\u9319\u9322\u931A\u9323\u933A\u9335\u933B\u935C\u9360\u937C\u936E\u9356\u93B0\u93AC\u93AD\u9394\u93B9\u93D6\u93D7\u93E8\u93E5\u93D8\u93C3\u93DD\u93D0\u93C8\u93E4\u941A\u9414\u9413\u9403\u9407\u9410\u9436\u942B\u9435\u9421\u943A\u9441\u9452\u9444\u945B\u9460\u9462\u945E\u946A\u9229\u9470\u9475\u9477\u947D\u945A\u947C\u947E\u9481\u947F\u9582\u9587\u958A\u9594\u9596\u9598\u9599\u95A0\u95A8\u95A7\u95AD\u95BC\u95BB\u95B9\u95BE\u95CA\u6FF6\u95C3\u95CD\u95CC\u95D5\u95D4\u95D6\u95DC\u95E1\u95E5\u95E2\u9621\u9628\u962E\u962F\u9642\u964C\u964F\u964B\u9677\u965C\u965E"], - ["f0a1", "\u965D\u965F\u9666\u9672\u966C\u968D\u9698\u9695\u9697\u96AA\u96A7\u96B1\u96B2\u96B0\u96B4\u96B6\u96B8\u96B9\u96CE\u96CB\u96C9\u96CD\u894D\u96DC\u970D\u96D5\u96F9\u9704\u9706\u9708\u9713\u970E\u9711\u970F\u9716\u9719\u9724\u972A\u9730\u9739\u973D\u973E\u9744\u9746\u9748\u9742\u9749\u975C\u9760\u9764\u9766\u9768\u52D2\u976B\u9771\u9779\u9785\u977C\u9781\u977A\u9786\u978B\u978F\u9790\u979C\u97A8\u97A6\u97A3\u97B3\u97B4\u97C3\u97C6\u97C8\u97CB\u97DC\u97ED\u9F4F\u97F2\u7ADF\u97F6\u97F5\u980F\u980C\u9838\u9824\u9821\u9837\u983D\u9846\u984F\u984B\u986B\u986F\u9870"], - ["f1a1", "\u9871\u9874\u9873\u98AA\u98AF\u98B1\u98B6\u98C4\u98C3\u98C6\u98E9\u98EB\u9903\u9909\u9912\u9914\u9918\u9921\u991D\u991E\u9924\u9920\u992C\u992E\u993D\u993E\u9942\u9949\u9945\u9950\u994B\u9951\u9952\u994C\u9955\u9997\u9998\u99A5\u99AD\u99AE\u99BC\u99DF\u99DB\u99DD\u99D8\u99D1\u99ED\u99EE\u99F1\u99F2\u99FB\u99F8\u9A01\u9A0F\u9A05\u99E2\u9A19\u9A2B\u9A37\u9A45\u9A42\u9A40\u9A43\u9A3E\u9A55\u9A4D\u9A5B\u9A57\u9A5F\u9A62\u9A65\u9A64\u9A69\u9A6B\u9A6A\u9AAD\u9AB0\u9ABC\u9AC0\u9ACF\u9AD1\u9AD3\u9AD4\u9ADE\u9ADF\u9AE2\u9AE3\u9AE6\u9AEF\u9AEB\u9AEE\u9AF4\u9AF1\u9AF7"], - ["f2a1", "\u9AFB\u9B06\u9B18\u9B1A\u9B1F\u9B22\u9B23\u9B25\u9B27\u9B28\u9B29\u9B2A\u9B2E\u9B2F\u9B32\u9B44\u9B43\u9B4F\u9B4D\u9B4E\u9B51\u9B58\u9B74\u9B93\u9B83\u9B91\u9B96\u9B97\u9B9F\u9BA0\u9BA8\u9BB4\u9BC0\u9BCA\u9BB9\u9BC6\u9BCF\u9BD1\u9BD2\u9BE3\u9BE2\u9BE4\u9BD4\u9BE1\u9C3A\u9BF2\u9BF1\u9BF0\u9C15\u9C14\u9C09\u9C13\u9C0C\u9C06\u9C08\u9C12\u9C0A\u9C04\u9C2E\u9C1B\u9C25\u9C24\u9C21\u9C30\u9C47\u9C32\u9C46\u9C3E\u9C5A\u9C60\u9C67\u9C76\u9C78\u9CE7\u9CEC\u9CF0\u9D09\u9D08\u9CEB\u9D03\u9D06\u9D2A\u9D26\u9DAF\u9D23\u9D1F\u9D44\u9D15\u9D12\u9D41\u9D3F\u9D3E\u9D46\u9D48"], - ["f3a1", "\u9D5D\u9D5E\u9D64\u9D51\u9D50\u9D59\u9D72\u9D89\u9D87\u9DAB\u9D6F\u9D7A\u9D9A\u9DA4\u9DA9\u9DB2\u9DC4\u9DC1\u9DBB\u9DB8\u9DBA\u9DC6\u9DCF\u9DC2\u9DD9\u9DD3\u9DF8\u9DE6\u9DED\u9DEF\u9DFD\u9E1A\u9E1B\u9E1E\u9E75\u9E79\u9E7D\u9E81\u9E88\u9E8B\u9E8C\u9E92\u9E95\u9E91\u9E9D\u9EA5\u9EA9\u9EB8\u9EAA\u9EAD\u9761\u9ECC\u9ECE\u9ECF\u9ED0\u9ED4\u9EDC\u9EDE\u9EDD\u9EE0\u9EE5\u9EE8\u9EEF\u9EF4\u9EF6\u9EF7\u9EF9\u9EFB\u9EFC\u9EFD\u9F07\u9F08\u76B7\u9F15\u9F21\u9F2C\u9F3E\u9F4A\u9F52\u9F54\u9F63\u9F5F\u9F60\u9F61\u9F66\u9F67\u9F6C\u9F6A\u9F77\u9F72\u9F76\u9F95\u9F9C\u9FA0"], - ["f4a1", "\u582F\u69C7\u9059\u7464\u51DC\u7199"], - ["f9a1", "\u7E8A\u891C\u9348\u9288\u84DC\u4FC9\u70BB\u6631\u68C8\u92F9\u66FB\u5F45\u4E28\u4EE1\u4EFC\u4F00\u4F03\u4F39\u4F56\u4F92\u4F8A\u4F9A\u4F94\u4FCD\u5040\u5022\u4FFF\u501E\u5046\u5070\u5042\u5094\u50F4\u50D8\u514A\u5164\u519D\u51BE\u51EC\u5215\u529C\u52A6\u52C0\u52DB\u5300\u5307\u5324\u5372\u5393\u53B2\u53DD\uFA0E\u549C\u548A\u54A9\u54FF\u5586\u5759\u5765\u57AC\u57C8\u57C7\uFA0F\uFA10\u589E\u58B2\u590B\u5953\u595B\u595D\u5963\u59A4\u59BA\u5B56\u5BC0\u752F\u5BD8\u5BEC\u5C1E\u5CA6\u5CBA\u5CF5\u5D27\u5D53\uFA11\u5D42\u5D6D\u5DB8\u5DB9\u5DD0\u5F21\u5F34\u5F67\u5FB7"], - ["faa1", "\u5FDE\u605D\u6085\u608A\u60DE\u60D5\u6120\u60F2\u6111\u6137\u6130\u6198\u6213\u62A6\u63F5\u6460\u649D\u64CE\u654E\u6600\u6615\u663B\u6609\u662E\u661E\u6624\u6665\u6657\u6659\uFA12\u6673\u6699\u66A0\u66B2\u66BF\u66FA\u670E\uF929\u6766\u67BB\u6852\u67C0\u6801\u6844\u68CF\uFA13\u6968\uFA14\u6998\u69E2\u6A30\u6A6B\u6A46\u6A73\u6A7E\u6AE2\u6AE4\u6BD6\u6C3F\u6C5C\u6C86\u6C6F\u6CDA\u6D04\u6D87\u6D6F\u6D96\u6DAC\u6DCF\u6DF8\u6DF2\u6DFC\u6E39\u6E5C\u6E27\u6E3C\u6EBF\u6F88\u6FB5\u6FF5\u7005\u7007\u7028\u7085\u70AB\u710F\u7104\u715C\u7146\u7147\uFA15\u71C1\u71FE\u72B1"], - ["fba1", "\u72BE\u7324\uFA16\u7377\u73BD\u73C9\u73D6\u73E3\u73D2\u7407\u73F5\u7426\u742A\u7429\u742E\u7462\u7489\u749F\u7501\u756F\u7682\u769C\u769E\u769B\u76A6\uFA17\u7746\u52AF\u7821\u784E\u7864\u787A\u7930\uFA18\uFA19\uFA1A\u7994\uFA1B\u799B\u7AD1\u7AE7\uFA1C\u7AEB\u7B9E\uFA1D\u7D48\u7D5C\u7DB7\u7DA0\u7DD6\u7E52\u7F47\u7FA1\uFA1E\u8301\u8362\u837F\u83C7\u83F6\u8448\u84B4\u8553\u8559\u856B\uFA1F\u85B0\uFA20\uFA21\u8807\u88F5\u8A12\u8A37\u8A79\u8AA7\u8ABE\u8ADF\uFA22\u8AF6\u8B53\u8B7F\u8CF0\u8CF4\u8D12\u8D76\uFA23\u8ECF\uFA24\uFA25\u9067\u90DE\uFA26\u9115\u9127\u91DA"], - ["fca1", "\u91D7\u91DE\u91ED\u91EE\u91E4\u91E5\u9206\u9210\u920A\u923A\u9240\u923C\u924E\u9259\u9251\u9239\u9267\u92A7\u9277\u9278\u92E7\u92D7\u92D9\u92D0\uFA27\u92D5\u92E0\u92D3\u9325\u9321\u92FB\uFA28\u931E\u92FF\u931D\u9302\u9370\u9357\u93A4\u93C6\u93DE\u93F8\u9431\u9445\u9448\u9592\uF9DC\uFA29\u969D\u96AF\u9733\u973B\u9743\u974D\u974F\u9751\u9755\u9857\u9865\uFA2A\uFA2B\u9927\uFA2C\u999E\u9A4E\u9AD9\u9ADC\u9B75\u9B72\u9B8F\u9BB1\u9BBB\u9C00\u9D70\u9D6B\uFA2D\u9E19\u9ED1"], - ["fcf1", "\u2170", 9, "\uFFE2\uFFE4\uFF07\uFF02"], - ["8fa2af", "\u02D8\u02C7\xB8\u02D9\u02DD\xAF\u02DB\u02DA\uFF5E\u0384\u0385"], - ["8fa2c2", "\xA1\xA6\xBF"], - ["8fa2eb", "\xBA\xAA\xA9\xAE\u2122\xA4\u2116"], - ["8fa6e1", "\u0386\u0388\u0389\u038A\u03AA"], - ["8fa6e7", "\u038C"], - ["8fa6e9", "\u038E\u03AB"], - ["8fa6ec", "\u038F"], - ["8fa6f1", "\u03AC\u03AD\u03AE\u03AF\u03CA\u0390\u03CC\u03C2\u03CD\u03CB\u03B0\u03CE"], - ["8fa7c2", "\u0402", 10, "\u040E\u040F"], - ["8fa7f2", "\u0452", 10, "\u045E\u045F"], - ["8fa9a1", "\xC6\u0110"], - ["8fa9a4", "\u0126"], - ["8fa9a6", "\u0132"], - ["8fa9a8", "\u0141\u013F"], - ["8fa9ab", "\u014A\xD8\u0152"], - ["8fa9af", "\u0166\xDE"], - ["8fa9c1", "\xE6\u0111\xF0\u0127\u0131\u0133\u0138\u0142\u0140\u0149\u014B\xF8\u0153\xDF\u0167\xFE"], - ["8faaa1", "\xC1\xC0\xC4\xC2\u0102\u01CD\u0100\u0104\xC5\xC3\u0106\u0108\u010C\xC7\u010A\u010E\xC9\xC8\xCB\xCA\u011A\u0116\u0112\u0118"], - ["8faaba", "\u011C\u011E\u0122\u0120\u0124\xCD\xCC\xCF\xCE\u01CF\u0130\u012A\u012E\u0128\u0134\u0136\u0139\u013D\u013B\u0143\u0147\u0145\xD1\xD3\xD2\xD6\xD4\u01D1\u0150\u014C\xD5\u0154\u0158\u0156\u015A\u015C\u0160\u015E\u0164\u0162\xDA\xD9\xDC\xDB\u016C\u01D3\u0170\u016A\u0172\u016E\u0168\u01D7\u01DB\u01D9\u01D5\u0174\xDD\u0178\u0176\u0179\u017D\u017B"], - ["8faba1", "\xE1\xE0\xE4\xE2\u0103\u01CE\u0101\u0105\xE5\xE3\u0107\u0109\u010D\xE7\u010B\u010F\xE9\xE8\xEB\xEA\u011B\u0117\u0113\u0119\u01F5\u011D\u011F"], - ["8fabbd", "\u0121\u0125\xED\xEC\xEF\xEE\u01D0"], - ["8fabc5", "\u012B\u012F\u0129\u0135\u0137\u013A\u013E\u013C\u0144\u0148\u0146\xF1\xF3\xF2\xF6\xF4\u01D2\u0151\u014D\xF5\u0155\u0159\u0157\u015B\u015D\u0161\u015F\u0165\u0163\xFA\xF9\xFC\xFB\u016D\u01D4\u0171\u016B\u0173\u016F\u0169\u01D8\u01DC\u01DA\u01D6\u0175\xFD\xFF\u0177\u017A\u017E\u017C"], - ["8fb0a1", "\u4E02\u4E04\u4E05\u4E0C\u4E12\u4E1F\u4E23\u4E24\u4E28\u4E2B\u4E2E\u4E2F\u4E30\u4E35\u4E40\u4E41\u4E44\u4E47\u4E51\u4E5A\u4E5C\u4E63\u4E68\u4E69\u4E74\u4E75\u4E79\u4E7F\u4E8D\u4E96\u4E97\u4E9D\u4EAF\u4EB9\u4EC3\u4ED0\u4EDA\u4EDB\u4EE0\u4EE1\u4EE2\u4EE8\u4EEF\u4EF1\u4EF3\u4EF5\u4EFD\u4EFE\u4EFF\u4F00\u4F02\u4F03\u4F08\u4F0B\u4F0C\u4F12\u4F15\u4F16\u4F17\u4F19\u4F2E\u4F31\u4F60\u4F33\u4F35\u4F37\u4F39\u4F3B\u4F3E\u4F40\u4F42\u4F48\u4F49\u4F4B\u4F4C\u4F52\u4F54\u4F56\u4F58\u4F5F\u4F63\u4F6A\u4F6C\u4F6E\u4F71\u4F77\u4F78\u4F79\u4F7A\u4F7D\u4F7E\u4F81\u4F82\u4F84"], - ["8fb1a1", "\u4F85\u4F89\u4F8A\u4F8C\u4F8E\u4F90\u4F92\u4F93\u4F94\u4F97\u4F99\u4F9A\u4F9E\u4F9F\u4FB2\u4FB7\u4FB9\u4FBB\u4FBC\u4FBD\u4FBE\u4FC0\u4FC1\u4FC5\u4FC6\u4FC8\u4FC9\u4FCB\u4FCC\u4FCD\u4FCF\u4FD2\u4FDC\u4FE0\u4FE2\u4FF0\u4FF2\u4FFC\u4FFD\u4FFF\u5000\u5001\u5004\u5007\u500A\u500C\u500E\u5010\u5013\u5017\u5018\u501B\u501C\u501D\u501E\u5022\u5027\u502E\u5030\u5032\u5033\u5035\u5040\u5041\u5042\u5045\u5046\u504A\u504C\u504E\u5051\u5052\u5053\u5057\u5059\u505F\u5060\u5062\u5063\u5066\u5067\u506A\u506D\u5070\u5071\u503B\u5081\u5083\u5084\u5086\u508A\u508E\u508F\u5090"], - ["8fb2a1", "\u5092\u5093\u5094\u5096\u509B\u509C\u509E", 4, "\u50AA\u50AF\u50B0\u50B9\u50BA\u50BD\u50C0\u50C3\u50C4\u50C7\u50CC\u50CE\u50D0\u50D3\u50D4\u50D8\u50DC\u50DD\u50DF\u50E2\u50E4\u50E6\u50E8\u50E9\u50EF\u50F1\u50F6\u50FA\u50FE\u5103\u5106\u5107\u5108\u510B\u510C\u510D\u510E\u50F2\u5110\u5117\u5119\u511B\u511C\u511D\u511E\u5123\u5127\u5128\u512C\u512D\u512F\u5131\u5133\u5134\u5135\u5138\u5139\u5142\u514A\u514F\u5153\u5155\u5157\u5158\u515F\u5164\u5166\u517E\u5183\u5184\u518B\u518E\u5198\u519D\u51A1\u51A3\u51AD\u51B8\u51BA\u51BC\u51BE\u51BF\u51C2"], - ["8fb3a1", "\u51C8\u51CF\u51D1\u51D2\u51D3\u51D5\u51D8\u51DE\u51E2\u51E5\u51EE\u51F2\u51F3\u51F4\u51F7\u5201\u5202\u5205\u5212\u5213\u5215\u5216\u5218\u5222\u5228\u5231\u5232\u5235\u523C\u5245\u5249\u5255\u5257\u5258\u525A\u525C\u525F\u5260\u5261\u5266\u526E\u5277\u5278\u5279\u5280\u5282\u5285\u528A\u528C\u5293\u5295\u5296\u5297\u5298\u529A\u529C\u52A4\u52A5\u52A6\u52A7\u52AF\u52B0\u52B6\u52B7\u52B8\u52BA\u52BB\u52BD\u52C0\u52C4\u52C6\u52C8\u52CC\u52CF\u52D1\u52D4\u52D6\u52DB\u52DC\u52E1\u52E5\u52E8\u52E9\u52EA\u52EC\u52F0\u52F1\u52F4\u52F6\u52F7\u5300\u5303\u530A\u530B"], - ["8fb4a1", "\u530C\u5311\u5313\u5318\u531B\u531C\u531E\u531F\u5325\u5327\u5328\u5329\u532B\u532C\u532D\u5330\u5332\u5335\u533C\u533D\u533E\u5342\u534C\u534B\u5359\u535B\u5361\u5363\u5365\u536C\u536D\u5372\u5379\u537E\u5383\u5387\u5388\u538E\u5393\u5394\u5399\u539D\u53A1\u53A4\u53AA\u53AB\u53AF\u53B2\u53B4\u53B5\u53B7\u53B8\u53BA\u53BD\u53C0\u53C5\u53CF\u53D2\u53D3\u53D5\u53DA\u53DD\u53DE\u53E0\u53E6\u53E7\u53F5\u5402\u5413\u541A\u5421\u5427\u5428\u542A\u542F\u5431\u5434\u5435\u5443\u5444\u5447\u544D\u544F\u545E\u5462\u5464\u5466\u5467\u5469\u546B\u546D\u546E\u5474\u547F"], - ["8fb5a1", "\u5481\u5483\u5485\u5488\u5489\u548D\u5491\u5495\u5496\u549C\u549F\u54A1\u54A6\u54A7\u54A9\u54AA\u54AD\u54AE\u54B1\u54B7\u54B9\u54BA\u54BB\u54BF\u54C6\u54CA\u54CD\u54CE\u54E0\u54EA\u54EC\u54EF\u54F6\u54FC\u54FE\u54FF\u5500\u5501\u5505\u5508\u5509\u550C\u550D\u550E\u5515\u552A\u552B\u5532\u5535\u5536\u553B\u553C\u553D\u5541\u5547\u5549\u554A\u554D\u5550\u5551\u5558\u555A\u555B\u555E\u5560\u5561\u5564\u5566\u557F\u5581\u5582\u5586\u5588\u558E\u558F\u5591\u5592\u5593\u5594\u5597\u55A3\u55A4\u55AD\u55B2\u55BF\u55C1\u55C3\u55C6\u55C9\u55CB\u55CC\u55CE\u55D1\u55D2"], - ["8fb6a1", "\u55D3\u55D7\u55D8\u55DB\u55DE\u55E2\u55E9\u55F6\u55FF\u5605\u5608\u560A\u560D", 5, "\u5619\u562C\u5630\u5633\u5635\u5637\u5639\u563B\u563C\u563D\u563F\u5640\u5641\u5643\u5644\u5646\u5649\u564B\u564D\u564F\u5654\u565E\u5660\u5661\u5662\u5663\u5666\u5669\u566D\u566F\u5671\u5672\u5675\u5684\u5685\u5688\u568B\u568C\u5695\u5699\u569A\u569D\u569E\u569F\u56A6\u56A7\u56A8\u56A9\u56AB\u56AC\u56AD\u56B1\u56B3\u56B7\u56BE\u56C5\u56C9\u56CA\u56CB\u56CF\u56D0\u56CC\u56CD\u56D9\u56DC\u56DD\u56DF\u56E1\u56E4", 4, "\u56F1\u56EB\u56ED"], - ["8fb7a1", "\u56F6\u56F7\u5701\u5702\u5707\u570A\u570C\u5711\u5715\u571A\u571B\u571D\u5720\u5722\u5723\u5724\u5725\u5729\u572A\u572C\u572E\u572F\u5733\u5734\u573D\u573E\u573F\u5745\u5746\u574C\u574D\u5752\u5762\u5765\u5767\u5768\u576B\u576D", 4, "\u5773\u5774\u5775\u5777\u5779\u577A\u577B\u577C\u577E\u5781\u5783\u578C\u5794\u5797\u5799\u579A\u579C\u579D\u579E\u579F\u57A1\u5795\u57A7\u57A8\u57A9\u57AC\u57B8\u57BD\u57C7\u57C8\u57CC\u57CF\u57D5\u57DD\u57DE\u57E4\u57E6\u57E7\u57E9\u57ED\u57F0\u57F5\u57F6\u57F8\u57FD\u57FE\u57FF\u5803\u5804\u5808\u5809\u57E1"], - ["8fb8a1", "\u580C\u580D\u581B\u581E\u581F\u5820\u5826\u5827\u582D\u5832\u5839\u583F\u5849\u584C\u584D\u584F\u5850\u5855\u585F\u5861\u5864\u5867\u5868\u5878\u587C\u587F\u5880\u5881\u5887\u5888\u5889\u588A\u588C\u588D\u588F\u5890\u5894\u5896\u589D\u58A0\u58A1\u58A2\u58A6\u58A9\u58B1\u58B2\u58C4\u58BC\u58C2\u58C8\u58CD\u58CE\u58D0\u58D2\u58D4\u58D6\u58DA\u58DD\u58E1\u58E2\u58E9\u58F3\u5905\u5906\u590B\u590C\u5912\u5913\u5914\u8641\u591D\u5921\u5923\u5924\u5928\u592F\u5930\u5933\u5935\u5936\u593F\u5943\u5946\u5952\u5953\u5959\u595B\u595D\u595E\u595F\u5961\u5963\u596B\u596D"], - ["8fb9a1", "\u596F\u5972\u5975\u5976\u5979\u597B\u597C\u598B\u598C\u598E\u5992\u5995\u5997\u599F\u59A4\u59A7\u59AD\u59AE\u59AF\u59B0\u59B3\u59B7\u59BA\u59BC\u59C1\u59C3\u59C4\u59C8\u59CA\u59CD\u59D2\u59DD\u59DE\u59DF\u59E3\u59E4\u59E7\u59EE\u59EF\u59F1\u59F2\u59F4\u59F7\u5A00\u5A04\u5A0C\u5A0D\u5A0E\u5A12\u5A13\u5A1E\u5A23\u5A24\u5A27\u5A28\u5A2A\u5A2D\u5A30\u5A44\u5A45\u5A47\u5A48\u5A4C\u5A50\u5A55\u5A5E\u5A63\u5A65\u5A67\u5A6D\u5A77\u5A7A\u5A7B\u5A7E\u5A8B\u5A90\u5A93\u5A96\u5A99\u5A9C\u5A9E\u5A9F\u5AA0\u5AA2\u5AA7\u5AAC\u5AB1\u5AB2\u5AB3\u5AB5\u5AB8\u5ABA\u5ABB\u5ABF"], - ["8fbaa1", "\u5AC4\u5AC6\u5AC8\u5ACF\u5ADA\u5ADC\u5AE0\u5AE5\u5AEA\u5AEE\u5AF5\u5AF6\u5AFD\u5B00\u5B01\u5B08\u5B17\u5B34\u5B19\u5B1B\u5B1D\u5B21\u5B25\u5B2D\u5B38\u5B41\u5B4B\u5B4C\u5B52\u5B56\u5B5E\u5B68\u5B6E\u5B6F\u5B7C\u5B7D\u5B7E\u5B7F\u5B81\u5B84\u5B86\u5B8A\u5B8E\u5B90\u5B91\u5B93\u5B94\u5B96\u5BA8\u5BA9\u5BAC\u5BAD\u5BAF\u5BB1\u5BB2\u5BB7\u5BBA\u5BBC\u5BC0\u5BC1\u5BCD\u5BCF\u5BD6", 4, "\u5BE0\u5BEF\u5BF1\u5BF4\u5BFD\u5C0C\u5C17\u5C1E\u5C1F\u5C23\u5C26\u5C29\u5C2B\u5C2C\u5C2E\u5C30\u5C32\u5C35\u5C36\u5C59\u5C5A\u5C5C\u5C62\u5C63\u5C67\u5C68\u5C69"], - ["8fbba1", "\u5C6D\u5C70\u5C74\u5C75\u5C7A\u5C7B\u5C7C\u5C7D\u5C87\u5C88\u5C8A\u5C8F\u5C92\u5C9D\u5C9F\u5CA0\u5CA2\u5CA3\u5CA6\u5CAA\u5CB2\u5CB4\u5CB5\u5CBA\u5CC9\u5CCB\u5CD2\u5CDD\u5CD7\u5CEE\u5CF1\u5CF2\u5CF4\u5D01\u5D06\u5D0D\u5D12\u5D2B\u5D23\u5D24\u5D26\u5D27\u5D31\u5D34\u5D39\u5D3D\u5D3F\u5D42\u5D43\u5D46\u5D48\u5D55\u5D51\u5D59\u5D4A\u5D5F\u5D60\u5D61\u5D62\u5D64\u5D6A\u5D6D\u5D70\u5D79\u5D7A\u5D7E\u5D7F\u5D81\u5D83\u5D88\u5D8A\u5D92\u5D93\u5D94\u5D95\u5D99\u5D9B\u5D9F\u5DA0\u5DA7\u5DAB\u5DB0\u5DB4\u5DB8\u5DB9\u5DC3\u5DC7\u5DCB\u5DD0\u5DCE\u5DD8\u5DD9\u5DE0\u5DE4"], - ["8fbca1", "\u5DE9\u5DF8\u5DF9\u5E00\u5E07\u5E0D\u5E12\u5E14\u5E15\u5E18\u5E1F\u5E20\u5E2E\u5E28\u5E32\u5E35\u5E3E\u5E4B\u5E50\u5E49\u5E51\u5E56\u5E58\u5E5B\u5E5C\u5E5E\u5E68\u5E6A", 4, "\u5E70\u5E80\u5E8B\u5E8E\u5EA2\u5EA4\u5EA5\u5EA8\u5EAA\u5EAC\u5EB1\u5EB3\u5EBD\u5EBE\u5EBF\u5EC6\u5ECC\u5ECB\u5ECE\u5ED1\u5ED2\u5ED4\u5ED5\u5EDC\u5EDE\u5EE5\u5EEB\u5F02\u5F06\u5F07\u5F08\u5F0E\u5F19\u5F1C\u5F1D\u5F21\u5F22\u5F23\u5F24\u5F28\u5F2B\u5F2C\u5F2E\u5F30\u5F34\u5F36\u5F3B\u5F3D\u5F3F\u5F40\u5F44\u5F45\u5F47\u5F4D\u5F50\u5F54\u5F58\u5F5B\u5F60\u5F63\u5F64\u5F67"], - ["8fbda1", "\u5F6F\u5F72\u5F74\u5F75\u5F78\u5F7A\u5F7D\u5F7E\u5F89\u5F8D\u5F8F\u5F96\u5F9C\u5F9D\u5FA2\u5FA7\u5FAB\u5FA4\u5FAC\u5FAF\u5FB0\u5FB1\u5FB8\u5FC4\u5FC7\u5FC8\u5FC9\u5FCB\u5FD0", 4, "\u5FDE\u5FE1\u5FE2\u5FE8\u5FE9\u5FEA\u5FEC\u5FED\u5FEE\u5FEF\u5FF2\u5FF3\u5FF6\u5FFA\u5FFC\u6007\u600A\u600D\u6013\u6014\u6017\u6018\u601A\u601F\u6024\u602D\u6033\u6035\u6040\u6047\u6048\u6049\u604C\u6051\u6054\u6056\u6057\u605D\u6061\u6067\u6071\u607E\u607F\u6082\u6086\u6088\u608A\u608E\u6091\u6093\u6095\u6098\u609D\u609E\u60A2\u60A4\u60A5\u60A8\u60B0\u60B1\u60B7"], - ["8fbea1", "\u60BB\u60BE\u60C2\u60C4\u60C8\u60C9\u60CA\u60CB\u60CE\u60CF\u60D4\u60D5\u60D9\u60DB\u60DD\u60DE\u60E2\u60E5\u60F2\u60F5\u60F8\u60FC\u60FD\u6102\u6107\u610A\u610C\u6110", 4, "\u6116\u6117\u6119\u611C\u611E\u6122\u612A\u612B\u6130\u6131\u6135\u6136\u6137\u6139\u6141\u6145\u6146\u6149\u615E\u6160\u616C\u6172\u6178\u617B\u617C\u617F\u6180\u6181\u6183\u6184\u618B\u618D\u6192\u6193\u6197\u6198\u619C\u619D\u619F\u61A0\u61A5\u61A8\u61AA\u61AD\u61B8\u61B9\u61BC\u61C0\u61C1\u61C2\u61CE\u61CF\u61D5\u61DC\u61DD\u61DE\u61DF\u61E1\u61E2\u61E7\u61E9\u61E5"], - ["8fbfa1", "\u61EC\u61ED\u61EF\u6201\u6203\u6204\u6207\u6213\u6215\u621C\u6220\u6222\u6223\u6227\u6229\u622B\u6239\u623D\u6242\u6243\u6244\u6246\u624C\u6250\u6251\u6252\u6254\u6256\u625A\u625C\u6264\u626D\u626F\u6273\u627A\u627D\u628D\u628E\u628F\u6290\u62A6\u62A8\u62B3\u62B6\u62B7\u62BA\u62BE\u62BF\u62C4\u62CE\u62D5\u62D6\u62DA\u62EA\u62F2\u62F4\u62FC\u62FD\u6303\u6304\u630A\u630B\u630D\u6310\u6313\u6316\u6318\u6329\u632A\u632D\u6335\u6336\u6339\u633C\u6341\u6342\u6343\u6344\u6346\u634A\u634B\u634E\u6352\u6353\u6354\u6358\u635B\u6365\u6366\u636C\u636D\u6371\u6374\u6375"], - ["8fc0a1", "\u6378\u637C\u637D\u637F\u6382\u6384\u6387\u638A\u6390\u6394\u6395\u6399\u639A\u639E\u63A4\u63A6\u63AD\u63AE\u63AF\u63BD\u63C1\u63C5\u63C8\u63CE\u63D1\u63D3\u63D4\u63D5\u63DC\u63E0\u63E5\u63EA\u63EC\u63F2\u63F3\u63F5\u63F8\u63F9\u6409\u640A\u6410\u6412\u6414\u6418\u641E\u6420\u6422\u6424\u6425\u6429\u642A\u642F\u6430\u6435\u643D\u643F\u644B\u644F\u6451\u6452\u6453\u6454\u645A\u645B\u645C\u645D\u645F\u6460\u6461\u6463\u646D\u6473\u6474\u647B\u647D\u6485\u6487\u648F\u6490\u6491\u6498\u6499\u649B\u649D\u649F\u64A1\u64A3\u64A6\u64A8\u64AC\u64B3\u64BD\u64BE\u64BF"], - ["8fc1a1", "\u64C4\u64C9\u64CA\u64CB\u64CC\u64CE\u64D0\u64D1\u64D5\u64D7\u64E4\u64E5\u64E9\u64EA\u64ED\u64F0\u64F5\u64F7\u64FB\u64FF\u6501\u6504\u6508\u6509\u650A\u650F\u6513\u6514\u6516\u6519\u651B\u651E\u651F\u6522\u6526\u6529\u652E\u6531\u653A\u653C\u653D\u6543\u6547\u6549\u6550\u6552\u6554\u655F\u6560\u6567\u656B\u657A\u657D\u6581\u6585\u658A\u6592\u6595\u6598\u659D\u65A0\u65A3\u65A6\u65AE\u65B2\u65B3\u65B4\u65BF\u65C2\u65C8\u65C9\u65CE\u65D0\u65D4\u65D6\u65D8\u65DF\u65F0\u65F2\u65F4\u65F5\u65F9\u65FE\u65FF\u6600\u6604\u6608\u6609\u660D\u6611\u6612\u6615\u6616\u661D"], - ["8fc2a1", "\u661E\u6621\u6622\u6623\u6624\u6626\u6629\u662A\u662B\u662C\u662E\u6630\u6631\u6633\u6639\u6637\u6640\u6645\u6646\u664A\u664C\u6651\u664E\u6657\u6658\u6659\u665B\u665C\u6660\u6661\u66FB\u666A\u666B\u666C\u667E\u6673\u6675\u667F\u6677\u6678\u6679\u667B\u6680\u667C\u668B\u668C\u668D\u6690\u6692\u6699\u669A\u669B\u669C\u669F\u66A0\u66A4\u66AD\u66B1\u66B2\u66B5\u66BB\u66BF\u66C0\u66C2\u66C3\u66C8\u66CC\u66CE\u66CF\u66D4\u66DB\u66DF\u66E8\u66EB\u66EC\u66EE\u66FA\u6705\u6707\u670E\u6713\u6719\u671C\u6720\u6722\u6733\u673E\u6745\u6747\u6748\u674C\u6754\u6755\u675D"], - ["8fc3a1", "\u6766\u676C\u676E\u6774\u6776\u677B\u6781\u6784\u678E\u678F\u6791\u6793\u6796\u6798\u6799\u679B\u67B0\u67B1\u67B2\u67B5\u67BB\u67BC\u67BD\u67F9\u67C0\u67C2\u67C3\u67C5\u67C8\u67C9\u67D2\u67D7\u67D9\u67DC\u67E1\u67E6\u67F0\u67F2\u67F6\u67F7\u6852\u6814\u6819\u681D\u681F\u6828\u6827\u682C\u682D\u682F\u6830\u6831\u6833\u683B\u683F\u6844\u6845\u684A\u684C\u6855\u6857\u6858\u685B\u686B\u686E", 4, "\u6875\u6879\u687A\u687B\u687C\u6882\u6884\u6886\u6888\u6896\u6898\u689A\u689C\u68A1\u68A3\u68A5\u68A9\u68AA\u68AE\u68B2\u68BB\u68C5\u68C8\u68CC\u68CF"], - ["8fc4a1", "\u68D0\u68D1\u68D3\u68D6\u68D9\u68DC\u68DD\u68E5\u68E8\u68EA\u68EB\u68EC\u68ED\u68F0\u68F1\u68F5\u68F6\u68FB\u68FC\u68FD\u6906\u6909\u690A\u6910\u6911\u6913\u6916\u6917\u6931\u6933\u6935\u6938\u693B\u6942\u6945\u6949\u694E\u6957\u695B\u6963\u6964\u6965\u6966\u6968\u6969\u696C\u6970\u6971\u6972\u697A\u697B\u697F\u6980\u698D\u6992\u6996\u6998\u69A1\u69A5\u69A6\u69A8\u69AB\u69AD\u69AF\u69B7\u69B8\u69BA\u69BC\u69C5\u69C8\u69D1\u69D6\u69D7\u69E2\u69E5\u69EE\u69EF\u69F1\u69F3\u69F5\u69FE\u6A00\u6A01\u6A03\u6A0F\u6A11\u6A15\u6A1A\u6A1D\u6A20\u6A24\u6A28\u6A30\u6A32"], - ["8fc5a1", "\u6A34\u6A37\u6A3B\u6A3E\u6A3F\u6A45\u6A46\u6A49\u6A4A\u6A4E\u6A50\u6A51\u6A52\u6A55\u6A56\u6A5B\u6A64\u6A67\u6A6A\u6A71\u6A73\u6A7E\u6A81\u6A83\u6A86\u6A87\u6A89\u6A8B\u6A91\u6A9B\u6A9D\u6A9E\u6A9F\u6AA5\u6AAB\u6AAF\u6AB0\u6AB1\u6AB4\u6ABD\u6ABE\u6ABF\u6AC6\u6AC9\u6AC8\u6ACC\u6AD0\u6AD4\u6AD5\u6AD6\u6ADC\u6ADD\u6AE4\u6AE7\u6AEC\u6AF0\u6AF1\u6AF2\u6AFC\u6AFD\u6B02\u6B03\u6B06\u6B07\u6B09\u6B0F\u6B10\u6B11\u6B17\u6B1B\u6B1E\u6B24\u6B28\u6B2B\u6B2C\u6B2F\u6B35\u6B36\u6B3B\u6B3F\u6B46\u6B4A\u6B4D\u6B52\u6B56\u6B58\u6B5D\u6B60\u6B67\u6B6B\u6B6E\u6B70\u6B75\u6B7D"], - ["8fc6a1", "\u6B7E\u6B82\u6B85\u6B97\u6B9B\u6B9F\u6BA0\u6BA2\u6BA3\u6BA8\u6BA9\u6BAC\u6BAD\u6BAE\u6BB0\u6BB8\u6BB9\u6BBD\u6BBE\u6BC3\u6BC4\u6BC9\u6BCC\u6BD6\u6BDA\u6BE1\u6BE3\u6BE6\u6BE7\u6BEE\u6BF1\u6BF7\u6BF9\u6BFF\u6C02\u6C04\u6C05\u6C09\u6C0D\u6C0E\u6C10\u6C12\u6C19\u6C1F\u6C26\u6C27\u6C28\u6C2C\u6C2E\u6C33\u6C35\u6C36\u6C3A\u6C3B\u6C3F\u6C4A\u6C4B\u6C4D\u6C4F\u6C52\u6C54\u6C59\u6C5B\u6C5C\u6C6B\u6C6D\u6C6F\u6C74\u6C76\u6C78\u6C79\u6C7B\u6C85\u6C86\u6C87\u6C89\u6C94\u6C95\u6C97\u6C98\u6C9C\u6C9F\u6CB0\u6CB2\u6CB4\u6CC2\u6CC6\u6CCD\u6CCF\u6CD0\u6CD1\u6CD2\u6CD4\u6CD6"], - ["8fc7a1", "\u6CDA\u6CDC\u6CE0\u6CE7\u6CE9\u6CEB\u6CEC\u6CEE\u6CF2\u6CF4\u6D04\u6D07\u6D0A\u6D0E\u6D0F\u6D11\u6D13\u6D1A\u6D26\u6D27\u6D28\u6C67\u6D2E\u6D2F\u6D31\u6D39\u6D3C\u6D3F\u6D57\u6D5E\u6D5F\u6D61\u6D65\u6D67\u6D6F\u6D70\u6D7C\u6D82\u6D87\u6D91\u6D92\u6D94\u6D96\u6D97\u6D98\u6DAA\u6DAC\u6DB4\u6DB7\u6DB9\u6DBD\u6DBF\u6DC4\u6DC8\u6DCA\u6DCE\u6DCF\u6DD6\u6DDB\u6DDD\u6DDF\u6DE0\u6DE2\u6DE5\u6DE9\u6DEF\u6DF0\u6DF4\u6DF6\u6DFC\u6E00\u6E04\u6E1E\u6E22\u6E27\u6E32\u6E36\u6E39\u6E3B\u6E3C\u6E44\u6E45\u6E48\u6E49\u6E4B\u6E4F\u6E51\u6E52\u6E53\u6E54\u6E57\u6E5C\u6E5D\u6E5E"], - ["8fc8a1", "\u6E62\u6E63\u6E68\u6E73\u6E7B\u6E7D\u6E8D\u6E93\u6E99\u6EA0\u6EA7\u6EAD\u6EAE\u6EB1\u6EB3\u6EBB\u6EBF\u6EC0\u6EC1\u6EC3\u6EC7\u6EC8\u6ECA\u6ECD\u6ECE\u6ECF\u6EEB\u6EED\u6EEE\u6EF9\u6EFB\u6EFD\u6F04\u6F08\u6F0A\u6F0C\u6F0D\u6F16\u6F18\u6F1A\u6F1B\u6F26\u6F29\u6F2A\u6F2F\u6F30\u6F33\u6F36\u6F3B\u6F3C\u6F2D\u6F4F\u6F51\u6F52\u6F53\u6F57\u6F59\u6F5A\u6F5D\u6F5E\u6F61\u6F62\u6F68\u6F6C\u6F7D\u6F7E\u6F83\u6F87\u6F88\u6F8B\u6F8C\u6F8D\u6F90\u6F92\u6F93\u6F94\u6F96\u6F9A\u6F9F\u6FA0\u6FA5\u6FA6\u6FA7\u6FA8\u6FAE\u6FAF\u6FB0\u6FB5\u6FB6\u6FBC\u6FC5\u6FC7\u6FC8\u6FCA"], - ["8fc9a1", "\u6FDA\u6FDE\u6FE8\u6FE9\u6FF0\u6FF5\u6FF9\u6FFC\u6FFD\u7000\u7005\u7006\u7007\u700D\u7017\u7020\u7023\u702F\u7034\u7037\u7039\u703C\u7043\u7044\u7048\u7049\u704A\u704B\u7054\u7055\u705D\u705E\u704E\u7064\u7065\u706C\u706E\u7075\u7076\u707E\u7081\u7085\u7086\u7094", 4, "\u709B\u70A4\u70AB\u70B0\u70B1\u70B4\u70B7\u70CA\u70D1\u70D3\u70D4\u70D5\u70D6\u70D8\u70DC\u70E4\u70FA\u7103", 4, "\u710B\u710C\u710F\u711E\u7120\u712B\u712D\u712F\u7130\u7131\u7138\u7141\u7145\u7146\u7147\u714A\u714B\u7150\u7152\u7157\u715A\u715C\u715E\u7160"], - ["8fcaa1", "\u7168\u7179\u7180\u7185\u7187\u718C\u7192\u719A\u719B\u71A0\u71A2\u71AF\u71B0\u71B2\u71B3\u71BA\u71BF\u71C0\u71C1\u71C4\u71CB\u71CC\u71D3\u71D6\u71D9\u71DA\u71DC\u71F8\u71FE\u7200\u7207\u7208\u7209\u7213\u7217\u721A\u721D\u721F\u7224\u722B\u722F\u7234\u7238\u7239\u7241\u7242\u7243\u7245\u724E\u724F\u7250\u7253\u7255\u7256\u725A\u725C\u725E\u7260\u7263\u7268\u726B\u726E\u726F\u7271\u7277\u7278\u727B\u727C\u727F\u7284\u7289\u728D\u728E\u7293\u729B\u72A8\u72AD\u72AE\u72B1\u72B4\u72BE\u72C1\u72C7\u72C9\u72CC\u72D5\u72D6\u72D8\u72DF\u72E5\u72F3\u72F4\u72FA\u72FB"], - ["8fcba1", "\u72FE\u7302\u7304\u7305\u7307\u730B\u730D\u7312\u7313\u7318\u7319\u731E\u7322\u7324\u7327\u7328\u732C\u7331\u7332\u7335\u733A\u733B\u733D\u7343\u734D\u7350\u7352\u7356\u7358\u735D\u735E\u735F\u7360\u7366\u7367\u7369\u736B\u736C\u736E\u736F\u7371\u7377\u7379\u737C\u7380\u7381\u7383\u7385\u7386\u738E\u7390\u7393\u7395\u7397\u7398\u739C\u739E\u739F\u73A0\u73A2\u73A5\u73A6\u73AA\u73AB\u73AD\u73B5\u73B7\u73B9\u73BC\u73BD\u73BF\u73C5\u73C6\u73C9\u73CB\u73CC\u73CF\u73D2\u73D3\u73D6\u73D9\u73DD\u73E1\u73E3\u73E6\u73E7\u73E9\u73F4\u73F5\u73F7\u73F9\u73FA\u73FB\u73FD"], - ["8fcca1", "\u73FF\u7400\u7401\u7404\u7407\u740A\u7411\u741A\u741B\u7424\u7426\u7428", 9, "\u7439\u7440\u7443\u7444\u7446\u7447\u744B\u744D\u7451\u7452\u7457\u745D\u7462\u7466\u7467\u7468\u746B\u746D\u746E\u7471\u7472\u7480\u7481\u7485\u7486\u7487\u7489\u748F\u7490\u7491\u7492\u7498\u7499\u749A\u749C\u749F\u74A0\u74A1\u74A3\u74A6\u74A8\u74A9\u74AA\u74AB\u74AE\u74AF\u74B1\u74B2\u74B5\u74B9\u74BB\u74BF\u74C8\u74C9\u74CC\u74D0\u74D3\u74D8\u74DA\u74DB\u74DE\u74DF\u74E4\u74E8\u74EA\u74EB\u74EF\u74F4\u74FA\u74FB\u74FC\u74FF\u7506"], - ["8fcda1", "\u7512\u7516\u7517\u7520\u7521\u7524\u7527\u7529\u752A\u752F\u7536\u7539\u753D\u753E\u753F\u7540\u7543\u7547\u7548\u754E\u7550\u7552\u7557\u755E\u755F\u7561\u756F\u7571\u7579", 5, "\u7581\u7585\u7590\u7592\u7593\u7595\u7599\u759C\u75A2\u75A4\u75B4\u75BA\u75BF\u75C0\u75C1\u75C4\u75C6\u75CC\u75CE\u75CF\u75D7\u75DC\u75DF\u75E0\u75E1\u75E4\u75E7\u75EC\u75EE\u75EF\u75F1\u75F9\u7600\u7602\u7603\u7604\u7607\u7608\u760A\u760C\u760F\u7612\u7613\u7615\u7616\u7619\u761B\u761C\u761D\u761E\u7623\u7625\u7626\u7629\u762D\u7632\u7633\u7635\u7638\u7639"], - ["8fcea1", "\u763A\u763C\u764A\u7640\u7641\u7643\u7644\u7645\u7649\u764B\u7655\u7659\u765F\u7664\u7665\u766D\u766E\u766F\u7671\u7674\u7681\u7685\u768C\u768D\u7695\u769B\u769C\u769D\u769F\u76A0\u76A2", 6, "\u76AA\u76AD\u76BD\u76C1\u76C5\u76C9\u76CB\u76CC\u76CE\u76D4\u76D9\u76E0\u76E6\u76E8\u76EC\u76F0\u76F1\u76F6\u76F9\u76FC\u7700\u7706\u770A\u770E\u7712\u7714\u7715\u7717\u7719\u771A\u771C\u7722\u7728\u772D\u772E\u772F\u7734\u7735\u7736\u7739\u773D\u773E\u7742\u7745\u7746\u774A\u774D\u774E\u774F\u7752\u7756\u7757\u775C\u775E\u775F\u7760\u7762"], - ["8fcfa1", "\u7764\u7767\u776A\u776C\u7770\u7772\u7773\u7774\u777A\u777D\u7780\u7784\u778C\u778D\u7794\u7795\u7796\u779A\u779F\u77A2\u77A7\u77AA\u77AE\u77AF\u77B1\u77B5\u77BE\u77C3\u77C9\u77D1\u77D2\u77D5\u77D9\u77DE\u77DF\u77E0\u77E4\u77E6\u77EA\u77EC\u77F0\u77F1\u77F4\u77F8\u77FB\u7805\u7806\u7809\u780D\u780E\u7811\u781D\u7821\u7822\u7823\u782D\u782E\u7830\u7835\u7837\u7843\u7844\u7847\u7848\u784C\u784E\u7852\u785C\u785E\u7860\u7861\u7863\u7864\u7868\u786A\u786E\u787A\u787E\u788A\u788F\u7894\u7898\u78A1\u789D\u789E\u789F\u78A4\u78A8\u78AC\u78AD\u78B0\u78B1\u78B2\u78B3"], - ["8fd0a1", "\u78BB\u78BD\u78BF\u78C7\u78C8\u78C9\u78CC\u78CE\u78D2\u78D3\u78D5\u78D6\u78E4\u78DB\u78DF\u78E0\u78E1\u78E6\u78EA\u78F2\u78F3\u7900\u78F6\u78F7\u78FA\u78FB\u78FF\u7906\u790C\u7910\u791A\u791C\u791E\u791F\u7920\u7925\u7927\u7929\u792D\u7931\u7934\u7935\u793B\u793D\u793F\u7944\u7945\u7946\u794A\u794B\u794F\u7951\u7954\u7958\u795B\u795C\u7967\u7969\u796B\u7972\u7979\u797B\u797C\u797E\u798B\u798C\u7991\u7993\u7994\u7995\u7996\u7998\u799B\u799C\u79A1\u79A8\u79A9\u79AB\u79AF\u79B1\u79B4\u79B8\u79BB\u79C2\u79C4\u79C7\u79C8\u79CA\u79CF\u79D4\u79D6\u79DA\u79DD\u79DE"], - ["8fd1a1", "\u79E0\u79E2\u79E5\u79EA\u79EB\u79ED\u79F1\u79F8\u79FC\u7A02\u7A03\u7A07\u7A09\u7A0A\u7A0C\u7A11\u7A15\u7A1B\u7A1E\u7A21\u7A27\u7A2B\u7A2D\u7A2F\u7A30\u7A34\u7A35\u7A38\u7A39\u7A3A\u7A44\u7A45\u7A47\u7A48\u7A4C\u7A55\u7A56\u7A59\u7A5C\u7A5D\u7A5F\u7A60\u7A65\u7A67\u7A6A\u7A6D\u7A75\u7A78\u7A7E\u7A80\u7A82\u7A85\u7A86\u7A8A\u7A8B\u7A90\u7A91\u7A94\u7A9E\u7AA0\u7AA3\u7AAC\u7AB3\u7AB5\u7AB9\u7ABB\u7ABC\u7AC6\u7AC9\u7ACC\u7ACE\u7AD1\u7ADB\u7AE8\u7AE9\u7AEB\u7AEC\u7AF1\u7AF4\u7AFB\u7AFD\u7AFE\u7B07\u7B14\u7B1F\u7B23\u7B27\u7B29\u7B2A\u7B2B\u7B2D\u7B2E\u7B2F\u7B30"], - ["8fd2a1", "\u7B31\u7B34\u7B3D\u7B3F\u7B40\u7B41\u7B47\u7B4E\u7B55\u7B60\u7B64\u7B66\u7B69\u7B6A\u7B6D\u7B6F\u7B72\u7B73\u7B77\u7B84\u7B89\u7B8E\u7B90\u7B91\u7B96\u7B9B\u7B9E\u7BA0\u7BA5\u7BAC\u7BAF\u7BB0\u7BB2\u7BB5\u7BB6\u7BBA\u7BBB\u7BBC\u7BBD\u7BC2\u7BC5\u7BC8\u7BCA\u7BD4\u7BD6\u7BD7\u7BD9\u7BDA\u7BDB\u7BE8\u7BEA\u7BF2\u7BF4\u7BF5\u7BF8\u7BF9\u7BFA\u7BFC\u7BFE\u7C01\u7C02\u7C03\u7C04\u7C06\u7C09\u7C0B\u7C0C\u7C0E\u7C0F\u7C19\u7C1B\u7C20\u7C25\u7C26\u7C28\u7C2C\u7C31\u7C33\u7C34\u7C36\u7C39\u7C3A\u7C46\u7C4A\u7C55\u7C51\u7C52\u7C53\u7C59", 5], - ["8fd3a1", "\u7C61\u7C63\u7C67\u7C69\u7C6D\u7C6E\u7C70\u7C72\u7C79\u7C7C\u7C7D\u7C86\u7C87\u7C8F\u7C94\u7C9E\u7CA0\u7CA6\u7CB0\u7CB6\u7CB7\u7CBA\u7CBB\u7CBC\u7CBF\u7CC4\u7CC7\u7CC8\u7CC9\u7CCD\u7CCF\u7CD3\u7CD4\u7CD5\u7CD7\u7CD9\u7CDA\u7CDD\u7CE6\u7CE9\u7CEB\u7CF5\u7D03\u7D07\u7D08\u7D09\u7D0F\u7D11\u7D12\u7D13\u7D16\u7D1D\u7D1E\u7D23\u7D26\u7D2A\u7D2D\u7D31\u7D3C\u7D3D\u7D3E\u7D40\u7D41\u7D47\u7D48\u7D4D\u7D51\u7D53\u7D57\u7D59\u7D5A\u7D5C\u7D5D\u7D65\u7D67\u7D6A\u7D70\u7D78\u7D7A\u7D7B\u7D7F\u7D81\u7D82\u7D83\u7D85\u7D86\u7D88\u7D8B\u7D8C\u7D8D\u7D91\u7D96\u7D97\u7D9D"], - ["8fd4a1", "\u7D9E\u7DA6\u7DA7\u7DAA\u7DB3\u7DB6\u7DB7\u7DB9\u7DC2", 4, "\u7DCC\u7DCD\u7DCE\u7DD7\u7DD9\u7E00\u7DE2\u7DE5\u7DE6\u7DEA\u7DEB\u7DED\u7DF1\u7DF5\u7DF6\u7DF9\u7DFA\u7E08\u7E10\u7E11\u7E15\u7E17\u7E1C\u7E1D\u7E20\u7E27\u7E28\u7E2C\u7E2D\u7E2F\u7E33\u7E36\u7E3F\u7E44\u7E45\u7E47\u7E4E\u7E50\u7E52\u7E58\u7E5F\u7E61\u7E62\u7E65\u7E6B\u7E6E\u7E6F\u7E73\u7E78\u7E7E\u7E81\u7E86\u7E87\u7E8A\u7E8D\u7E91\u7E95\u7E98\u7E9A\u7E9D\u7E9E\u7F3C\u7F3B\u7F3D\u7F3E\u7F3F\u7F43\u7F44\u7F47\u7F4F\u7F52\u7F53\u7F5B\u7F5C\u7F5D\u7F61\u7F63\u7F64\u7F65\u7F66\u7F6D"], - ["8fd5a1", "\u7F71\u7F7D\u7F7E\u7F7F\u7F80\u7F8B\u7F8D\u7F8F\u7F90\u7F91\u7F96\u7F97\u7F9C\u7FA1\u7FA2\u7FA6\u7FAA\u7FAD\u7FB4\u7FBC\u7FBF\u7FC0\u7FC3\u7FC8\u7FCE\u7FCF\u7FDB\u7FDF\u7FE3\u7FE5\u7FE8\u7FEC\u7FEE\u7FEF\u7FF2\u7FFA\u7FFD\u7FFE\u7FFF\u8007\u8008\u800A\u800D\u800E\u800F\u8011\u8013\u8014\u8016\u801D\u801E\u801F\u8020\u8024\u8026\u802C\u802E\u8030\u8034\u8035\u8037\u8039\u803A\u803C\u803E\u8040\u8044\u8060\u8064\u8066\u806D\u8071\u8075\u8081\u8088\u808E\u809C\u809E\u80A6\u80A7\u80AB\u80B8\u80B9\u80C8\u80CD\u80CF\u80D2\u80D4\u80D5\u80D7\u80D8\u80E0\u80ED\u80EE"], - ["8fd6a1", "\u80F0\u80F2\u80F3\u80F6\u80F9\u80FA\u80FE\u8103\u810B\u8116\u8117\u8118\u811C\u811E\u8120\u8124\u8127\u812C\u8130\u8135\u813A\u813C\u8145\u8147\u814A\u814C\u8152\u8157\u8160\u8161\u8167\u8168\u8169\u816D\u816F\u8177\u8181\u8190\u8184\u8185\u8186\u818B\u818E\u8196\u8198\u819B\u819E\u81A2\u81AE\u81B2\u81B4\u81BB\u81CB\u81C3\u81C5\u81CA\u81CE\u81CF\u81D5\u81D7\u81DB\u81DD\u81DE\u81E1\u81E4\u81EB\u81EC\u81F0\u81F1\u81F2\u81F5\u81F6\u81F8\u81F9\u81FD\u81FF\u8200\u8203\u820F\u8213\u8214\u8219\u821A\u821D\u8221\u8222\u8228\u8232\u8234\u823A\u8243\u8244\u8245\u8246"], - ["8fd7a1", "\u824B\u824E\u824F\u8251\u8256\u825C\u8260\u8263\u8267\u826D\u8274\u827B\u827D\u827F\u8280\u8281\u8283\u8284\u8287\u8289\u828A\u828E\u8291\u8294\u8296\u8298\u829A\u829B\u82A0\u82A1\u82A3\u82A4\u82A7\u82A8\u82A9\u82AA\u82AE\u82B0\u82B2\u82B4\u82B7\u82BA\u82BC\u82BE\u82BF\u82C6\u82D0\u82D5\u82DA\u82E0\u82E2\u82E4\u82E8\u82EA\u82ED\u82EF\u82F6\u82F7\u82FD\u82FE\u8300\u8301\u8307\u8308\u830A\u830B\u8354\u831B\u831D\u831E\u831F\u8321\u8322\u832C\u832D\u832E\u8330\u8333\u8337\u833A\u833C\u833D\u8342\u8343\u8344\u8347\u834D\u834E\u8351\u8355\u8356\u8357\u8370\u8378"], - ["8fd8a1", "\u837D\u837F\u8380\u8382\u8384\u8386\u838D\u8392\u8394\u8395\u8398\u8399\u839B\u839C\u839D\u83A6\u83A7\u83A9\u83AC\u83BE\u83BF\u83C0\u83C7\u83C9\u83CF\u83D0\u83D1\u83D4\u83DD\u8353\u83E8\u83EA\u83F6\u83F8\u83F9\u83FC\u8401\u8406\u840A\u840F\u8411\u8415\u8419\u83AD\u842F\u8439\u8445\u8447\u8448\u844A\u844D\u844F\u8451\u8452\u8456\u8458\u8459\u845A\u845C\u8460\u8464\u8465\u8467\u846A\u8470\u8473\u8474\u8476\u8478\u847C\u847D\u8481\u8485\u8492\u8493\u8495\u849E\u84A6\u84A8\u84A9\u84AA\u84AF\u84B1\u84B4\u84BA\u84BD\u84BE\u84C0\u84C2\u84C7\u84C8\u84CC\u84CF\u84D3"], - ["8fd9a1", "\u84DC\u84E7\u84EA\u84EF\u84F0\u84F1\u84F2\u84F7\u8532\u84FA\u84FB\u84FD\u8502\u8503\u8507\u850C\u850E\u8510\u851C\u851E\u8522\u8523\u8524\u8525\u8527\u852A\u852B\u852F\u8533\u8534\u8536\u853F\u8546\u854F", 4, "\u8556\u8559\u855C", 6, "\u8564\u856B\u856F\u8579\u857A\u857B\u857D\u857F\u8581\u8585\u8586\u8589\u858B\u858C\u858F\u8593\u8598\u859D\u859F\u85A0\u85A2\u85A5\u85A7\u85B4\u85B6\u85B7\u85B8\u85BC\u85BD\u85BE\u85BF\u85C2\u85C7\u85CA\u85CB\u85CE\u85AD\u85D8\u85DA\u85DF\u85E0\u85E6\u85E8\u85ED\u85F3\u85F6\u85FC"], - ["8fdaa1", "\u85FF\u8600\u8604\u8605\u860D\u860E\u8610\u8611\u8612\u8618\u8619\u861B\u861E\u8621\u8627\u8629\u8636\u8638\u863A\u863C\u863D\u8640\u8642\u8646\u8652\u8653\u8656\u8657\u8658\u8659\u865D\u8660", 4, "\u8669\u866C\u866F\u8675\u8676\u8677\u867A\u868D\u8691\u8696\u8698\u869A\u869C\u86A1\u86A6\u86A7\u86A8\u86AD\u86B1\u86B3\u86B4\u86B5\u86B7\u86B8\u86B9\u86BF\u86C0\u86C1\u86C3\u86C5\u86D1\u86D2\u86D5\u86D7\u86DA\u86DC\u86E0\u86E3\u86E5\u86E7\u8688\u86FA\u86FC\u86FD\u8704\u8705\u8707\u870B\u870E\u870F\u8710\u8713\u8714\u8719\u871E\u871F\u8721\u8723"], - ["8fdba1", "\u8728\u872E\u872F\u8731\u8732\u8739\u873A\u873C\u873D\u873E\u8740\u8743\u8745\u874D\u8758\u875D\u8761\u8764\u8765\u876F\u8771\u8772\u877B\u8783", 6, "\u878B\u878C\u8790\u8793\u8795\u8797\u8798\u8799\u879E\u87A0\u87A3\u87A7\u87AC\u87AD\u87AE\u87B1\u87B5\u87BE\u87BF\u87C1\u87C8\u87C9\u87CA\u87CE\u87D5\u87D6\u87D9\u87DA\u87DC\u87DF\u87E2\u87E3\u87E4\u87EA\u87EB\u87ED\u87F1\u87F3\u87F8\u87FA\u87FF\u8801\u8803\u8806\u8809\u880A\u880B\u8810\u8819\u8812\u8813\u8814\u8818\u881A\u881B\u881C\u881E\u881F\u8828\u882D\u882E\u8830\u8832\u8835"], - ["8fdca1", "\u883A\u883C\u8841\u8843\u8845\u8848\u8849\u884A\u884B\u884E\u8851\u8855\u8856\u8858\u885A\u885C\u885F\u8860\u8864\u8869\u8871\u8879\u887B\u8880\u8898\u889A\u889B\u889C\u889F\u88A0\u88A8\u88AA\u88BA\u88BD\u88BE\u88C0\u88CA", 4, "\u88D1\u88D2\u88D3\u88DB\u88DE\u88E7\u88EF\u88F0\u88F1\u88F5\u88F7\u8901\u8906\u890D\u890E\u890F\u8915\u8916\u8918\u8919\u891A\u891C\u8920\u8926\u8927\u8928\u8930\u8931\u8932\u8935\u8939\u893A\u893E\u8940\u8942\u8945\u8946\u8949\u894F\u8952\u8957\u895A\u895B\u895C\u8961\u8962\u8963\u896B\u896E\u8970\u8973\u8975\u897A"], - ["8fdda1", "\u897B\u897C\u897D\u8989\u898D\u8990\u8994\u8995\u899B\u899C\u899F\u89A0\u89A5\u89B0\u89B4\u89B5\u89B6\u89B7\u89BC\u89D4", 4, "\u89E5\u89E9\u89EB\u89ED\u89F1\u89F3\u89F6\u89F9\u89FD\u89FF\u8A04\u8A05\u8A07\u8A0F\u8A11\u8A12\u8A14\u8A15\u8A1E\u8A20\u8A22\u8A24\u8A26\u8A2B\u8A2C\u8A2F\u8A35\u8A37\u8A3D\u8A3E\u8A40\u8A43\u8A45\u8A47\u8A49\u8A4D\u8A4E\u8A53\u8A56\u8A57\u8A58\u8A5C\u8A5D\u8A61\u8A65\u8A67\u8A75\u8A76\u8A77\u8A79\u8A7A\u8A7B\u8A7E\u8A7F\u8A80\u8A83\u8A86\u8A8B\u8A8F\u8A90\u8A92\u8A96\u8A97\u8A99\u8A9F\u8AA7\u8AA9\u8AAE\u8AAF\u8AB3"], - ["8fdea1", "\u8AB6\u8AB7\u8ABB\u8ABE\u8AC3\u8AC6\u8AC8\u8AC9\u8ACA\u8AD1\u8AD3\u8AD4\u8AD5\u8AD7\u8ADD\u8ADF\u8AEC\u8AF0\u8AF4\u8AF5\u8AF6\u8AFC\u8AFF\u8B05\u8B06\u8B0B\u8B11\u8B1C\u8B1E\u8B1F\u8B0A\u8B2D\u8B30\u8B37\u8B3C\u8B42", 4, "\u8B48\u8B52\u8B53\u8B54\u8B59\u8B4D\u8B5E\u8B63\u8B6D\u8B76\u8B78\u8B79\u8B7C\u8B7E\u8B81\u8B84\u8B85\u8B8B\u8B8D\u8B8F\u8B94\u8B95\u8B9C\u8B9E\u8B9F\u8C38\u8C39\u8C3D\u8C3E\u8C45\u8C47\u8C49\u8C4B\u8C4F\u8C51\u8C53\u8C54\u8C57\u8C58\u8C5B\u8C5D\u8C59\u8C63\u8C64\u8C66\u8C68\u8C69\u8C6D\u8C73\u8C75\u8C76\u8C7B\u8C7E\u8C86"], - ["8fdfa1", "\u8C87\u8C8B\u8C90\u8C92\u8C93\u8C99\u8C9B\u8C9C\u8CA4\u8CB9\u8CBA\u8CC5\u8CC6\u8CC9\u8CCB\u8CCF\u8CD6\u8CD5\u8CD9\u8CDD\u8CE1\u8CE8\u8CEC\u8CEF\u8CF0\u8CF2\u8CF5\u8CF7\u8CF8\u8CFE\u8CFF\u8D01\u8D03\u8D09\u8D12\u8D17\u8D1B\u8D65\u8D69\u8D6C\u8D6E\u8D7F\u8D82\u8D84\u8D88\u8D8D\u8D90\u8D91\u8D95\u8D9E\u8D9F\u8DA0\u8DA6\u8DAB\u8DAC\u8DAF\u8DB2\u8DB5\u8DB7\u8DB9\u8DBB\u8DC0\u8DC5\u8DC6\u8DC7\u8DC8\u8DCA\u8DCE\u8DD1\u8DD4\u8DD5\u8DD7\u8DD9\u8DE4\u8DE5\u8DE7\u8DEC\u8DF0\u8DBC\u8DF1\u8DF2\u8DF4\u8DFD\u8E01\u8E04\u8E05\u8E06\u8E0B\u8E11\u8E14\u8E16\u8E20\u8E21\u8E22"], - ["8fe0a1", "\u8E23\u8E26\u8E27\u8E31\u8E33\u8E36\u8E37\u8E38\u8E39\u8E3D\u8E40\u8E41\u8E4B\u8E4D\u8E4E\u8E4F\u8E54\u8E5B\u8E5C\u8E5D\u8E5E\u8E61\u8E62\u8E69\u8E6C\u8E6D\u8E6F\u8E70\u8E71\u8E79\u8E7A\u8E7B\u8E82\u8E83\u8E89\u8E90\u8E92\u8E95\u8E9A\u8E9B\u8E9D\u8E9E\u8EA2\u8EA7\u8EA9\u8EAD\u8EAE\u8EB3\u8EB5\u8EBA\u8EBB\u8EC0\u8EC1\u8EC3\u8EC4\u8EC7\u8ECF\u8ED1\u8ED4\u8EDC\u8EE8\u8EEE\u8EF0\u8EF1\u8EF7\u8EF9\u8EFA\u8EED\u8F00\u8F02\u8F07\u8F08\u8F0F\u8F10\u8F16\u8F17\u8F18\u8F1E\u8F20\u8F21\u8F23\u8F25\u8F27\u8F28\u8F2C\u8F2D\u8F2E\u8F34\u8F35\u8F36\u8F37\u8F3A\u8F40\u8F41"], - ["8fe1a1", "\u8F43\u8F47\u8F4F\u8F51", 4, "\u8F58\u8F5D\u8F5E\u8F65\u8F9D\u8FA0\u8FA1\u8FA4\u8FA5\u8FA6\u8FB5\u8FB6\u8FB8\u8FBE\u8FC0\u8FC1\u8FC6\u8FCA\u8FCB\u8FCD\u8FD0\u8FD2\u8FD3\u8FD5\u8FE0\u8FE3\u8FE4\u8FE8\u8FEE\u8FF1\u8FF5\u8FF6\u8FFB\u8FFE\u9002\u9004\u9008\u900C\u9018\u901B\u9028\u9029\u902F\u902A\u902C\u902D\u9033\u9034\u9037\u903F\u9043\u9044\u904C\u905B\u905D\u9062\u9066\u9067\u906C\u9070\u9074\u9079\u9085\u9088\u908B\u908C\u908E\u9090\u9095\u9097\u9098\u9099\u909B\u90A0\u90A1\u90A2\u90A5\u90B0\u90B2\u90B3\u90B4\u90B6\u90BD\u90CC\u90BE\u90C3"], - ["8fe2a1", "\u90C4\u90C5\u90C7\u90C8\u90D5\u90D7\u90D8\u90D9\u90DC\u90DD\u90DF\u90E5\u90D2\u90F6\u90EB\u90EF\u90F0\u90F4\u90FE\u90FF\u9100\u9104\u9105\u9106\u9108\u910D\u9110\u9114\u9116\u9117\u9118\u911A\u911C\u911E\u9120\u9125\u9122\u9123\u9127\u9129\u912E\u912F\u9131\u9134\u9136\u9137\u9139\u913A\u913C\u913D\u9143\u9147\u9148\u914F\u9153\u9157\u9159\u915A\u915B\u9161\u9164\u9167\u916D\u9174\u9179\u917A\u917B\u9181\u9183\u9185\u9186\u918A\u918E\u9191\u9193\u9194\u9195\u9198\u919E\u91A1\u91A6\u91A8\u91AC\u91AD\u91AE\u91B0\u91B1\u91B2\u91B3\u91B6\u91BB\u91BC\u91BD\u91BF"], - ["8fe3a1", "\u91C2\u91C3\u91C5\u91D3\u91D4\u91D7\u91D9\u91DA\u91DE\u91E4\u91E5\u91E9\u91EA\u91EC", 5, "\u91F7\u91F9\u91FB\u91FD\u9200\u9201\u9204\u9205\u9206\u9207\u9209\u920A\u920C\u9210\u9212\u9213\u9216\u9218\u921C\u921D\u9223\u9224\u9225\u9226\u9228\u922E\u922F\u9230\u9233\u9235\u9236\u9238\u9239\u923A\u923C\u923E\u9240\u9242\u9243\u9246\u9247\u924A\u924D\u924E\u924F\u9251\u9258\u9259\u925C\u925D\u9260\u9261\u9265\u9267\u9268\u9269\u926E\u926F\u9270\u9275", 4, "\u927B\u927C\u927D\u927F\u9288\u9289\u928A\u928D\u928E\u9292\u9297"], - ["8fe4a1", "\u9299\u929F\u92A0\u92A4\u92A5\u92A7\u92A8\u92AB\u92AF\u92B2\u92B6\u92B8\u92BA\u92BB\u92BC\u92BD\u92BF", 4, "\u92C5\u92C6\u92C7\u92C8\u92CB\u92CC\u92CD\u92CE\u92D0\u92D3\u92D5\u92D7\u92D8\u92D9\u92DC\u92DD\u92DF\u92E0\u92E1\u92E3\u92E5\u92E7\u92E8\u92EC\u92EE\u92F0\u92F9\u92FB\u92FF\u9300\u9302\u9308\u930D\u9311\u9314\u9315\u931C\u931D\u931E\u931F\u9321\u9324\u9325\u9327\u9329\u932A\u9333\u9334\u9336\u9337\u9347\u9348\u9349\u9350\u9351\u9352\u9355\u9357\u9358\u935A\u935E\u9364\u9365\u9367\u9369\u936A\u936D\u936F\u9370\u9371\u9373\u9374\u9376"], - ["8fe5a1", "\u937A\u937D\u937F\u9380\u9381\u9382\u9388\u938A\u938B\u938D\u938F\u9392\u9395\u9398\u939B\u939E\u93A1\u93A3\u93A4\u93A6\u93A8\u93AB\u93B4\u93B5\u93B6\u93BA\u93A9\u93C1\u93C4\u93C5\u93C6\u93C7\u93C9", 4, "\u93D3\u93D9\u93DC\u93DE\u93DF\u93E2\u93E6\u93E7\u93F9\u93F7\u93F8\u93FA\u93FB\u93FD\u9401\u9402\u9404\u9408\u9409\u940D\u940E\u940F\u9415\u9416\u9417\u941F\u942E\u942F\u9431\u9432\u9433\u9434\u943B\u943F\u943D\u9443\u9445\u9448\u944A\u944C\u9455\u9459\u945C\u945F\u9461\u9463\u9468\u946B\u946D\u946E\u946F\u9471\u9472\u9484\u9483\u9578\u9579"], - ["8fe6a1", "\u957E\u9584\u9588\u958C\u958D\u958E\u959D\u959E\u959F\u95A1\u95A6\u95A9\u95AB\u95AC\u95B4\u95B6\u95BA\u95BD\u95BF\u95C6\u95C8\u95C9\u95CB\u95D0\u95D1\u95D2\u95D3\u95D9\u95DA\u95DD\u95DE\u95DF\u95E0\u95E4\u95E6\u961D\u961E\u9622\u9624\u9625\u9626\u962C\u9631\u9633\u9637\u9638\u9639\u963A\u963C\u963D\u9641\u9652\u9654\u9656\u9657\u9658\u9661\u966E\u9674\u967B\u967C\u967E\u967F\u9681\u9682\u9683\u9684\u9689\u9691\u9696\u969A\u969D\u969F\u96A4\u96A5\u96A6\u96A9\u96AE\u96AF\u96B3\u96BA\u96CA\u96D2\u5DB2\u96D8\u96DA\u96DD\u96DE\u96DF\u96E9\u96EF\u96F1\u96FA\u9702"], - ["8fe7a1", "\u9703\u9705\u9709\u971A\u971B\u971D\u9721\u9722\u9723\u9728\u9731\u9733\u9741\u9743\u974A\u974E\u974F\u9755\u9757\u9758\u975A\u975B\u9763\u9767\u976A\u976E\u9773\u9776\u9777\u9778\u977B\u977D\u977F\u9780\u9789\u9795\u9796\u9797\u9799\u979A\u979E\u979F\u97A2\u97AC\u97AE\u97B1\u97B2\u97B5\u97B6\u97B8\u97B9\u97BA\u97BC\u97BE\u97BF\u97C1\u97C4\u97C5\u97C7\u97C9\u97CA\u97CC\u97CD\u97CE\u97D0\u97D1\u97D4\u97D7\u97D8\u97D9\u97DD\u97DE\u97E0\u97DB\u97E1\u97E4\u97EF\u97F1\u97F4\u97F7\u97F8\u97FA\u9807\u980A\u9819\u980D\u980E\u9814\u9816\u981C\u981E\u9820\u9823\u9826"], - ["8fe8a1", "\u982B\u982E\u982F\u9830\u9832\u9833\u9835\u9825\u983E\u9844\u9847\u984A\u9851\u9852\u9853\u9856\u9857\u9859\u985A\u9862\u9863\u9865\u9866\u986A\u986C\u98AB\u98AD\u98AE\u98B0\u98B4\u98B7\u98B8\u98BA\u98BB\u98BF\u98C2\u98C5\u98C8\u98CC\u98E1\u98E3\u98E5\u98E6\u98E7\u98EA\u98F3\u98F6\u9902\u9907\u9908\u9911\u9915\u9916\u9917\u991A\u991B\u991C\u991F\u9922\u9926\u9927\u992B\u9931", 4, "\u9939\u993A\u993B\u993C\u9940\u9941\u9946\u9947\u9948\u994D\u994E\u9954\u9958\u9959\u995B\u995C\u995E\u995F\u9960\u999B\u999D\u999F\u99A6\u99B0\u99B1\u99B2\u99B5"], - ["8fe9a1", "\u99B9\u99BA\u99BD\u99BF\u99C3\u99C9\u99D3\u99D4\u99D9\u99DA\u99DC\u99DE\u99E7\u99EA\u99EB\u99EC\u99F0\u99F4\u99F5\u99F9\u99FD\u99FE\u9A02\u9A03\u9A04\u9A0B\u9A0C\u9A10\u9A11\u9A16\u9A1E\u9A20\u9A22\u9A23\u9A24\u9A27\u9A2D\u9A2E\u9A33\u9A35\u9A36\u9A38\u9A47\u9A41\u9A44\u9A4A\u9A4B\u9A4C\u9A4E\u9A51\u9A54\u9A56\u9A5D\u9AAA\u9AAC\u9AAE\u9AAF\u9AB2\u9AB4\u9AB5\u9AB6\u9AB9\u9ABB\u9ABE\u9ABF\u9AC1\u9AC3\u9AC6\u9AC8\u9ACE\u9AD0\u9AD2\u9AD5\u9AD6\u9AD7\u9ADB\u9ADC\u9AE0\u9AE4\u9AE5\u9AE7\u9AE9\u9AEC\u9AF2\u9AF3\u9AF5\u9AF9\u9AFA\u9AFD\u9AFF", 4], - ["8feaa1", "\u9B04\u9B05\u9B08\u9B09\u9B0B\u9B0C\u9B0D\u9B0E\u9B10\u9B12\u9B16\u9B19\u9B1B\u9B1C\u9B20\u9B26\u9B2B\u9B2D\u9B33\u9B34\u9B35\u9B37\u9B39\u9B3A\u9B3D\u9B48\u9B4B\u9B4C\u9B55\u9B56\u9B57\u9B5B\u9B5E\u9B61\u9B63\u9B65\u9B66\u9B68\u9B6A", 4, "\u9B73\u9B75\u9B77\u9B78\u9B79\u9B7F\u9B80\u9B84\u9B85\u9B86\u9B87\u9B89\u9B8A\u9B8B\u9B8D\u9B8F\u9B90\u9B94\u9B9A\u9B9D\u9B9E\u9BA6\u9BA7\u9BA9\u9BAC\u9BB0\u9BB1\u9BB2\u9BB7\u9BB8\u9BBB\u9BBC\u9BBE\u9BBF\u9BC1\u9BC7\u9BC8\u9BCE\u9BD0\u9BD7\u9BD8\u9BDD\u9BDF\u9BE5\u9BE7\u9BEA\u9BEB\u9BEF\u9BF3\u9BF7\u9BF8"], - ["8feba1", "\u9BF9\u9BFA\u9BFD\u9BFF\u9C00\u9C02\u9C0B\u9C0F\u9C11\u9C16\u9C18\u9C19\u9C1A\u9C1C\u9C1E\u9C22\u9C23\u9C26", 4, "\u9C31\u9C35\u9C36\u9C37\u9C3D\u9C41\u9C43\u9C44\u9C45\u9C49\u9C4A\u9C4E\u9C4F\u9C50\u9C53\u9C54\u9C56\u9C58\u9C5B\u9C5D\u9C5E\u9C5F\u9C63\u9C69\u9C6A\u9C5C\u9C6B\u9C68\u9C6E\u9C70\u9C72\u9C75\u9C77\u9C7B\u9CE6\u9CF2\u9CF7\u9CF9\u9D0B\u9D02\u9D11\u9D17\u9D18\u9D1C\u9D1D\u9D1E\u9D2F\u9D30\u9D32\u9D33\u9D34\u9D3A\u9D3C\u9D45\u9D3D\u9D42\u9D43\u9D47\u9D4A\u9D53\u9D54\u9D5F\u9D63\u9D62\u9D65\u9D69\u9D6A\u9D6B\u9D70\u9D76\u9D77\u9D7B"], - ["8feca1", "\u9D7C\u9D7E\u9D83\u9D84\u9D86\u9D8A\u9D8D\u9D8E\u9D92\u9D93\u9D95\u9D96\u9D97\u9D98\u9DA1\u9DAA\u9DAC\u9DAE\u9DB1\u9DB5\u9DB9\u9DBC\u9DBF\u9DC3\u9DC7\u9DC9\u9DCA\u9DD4\u9DD5\u9DD6\u9DD7\u9DDA\u9DDE\u9DDF\u9DE0\u9DE5\u9DE7\u9DE9\u9DEB\u9DEE\u9DF0\u9DF3\u9DF4\u9DFE\u9E0A\u9E02\u9E07\u9E0E\u9E10\u9E11\u9E12\u9E15\u9E16\u9E19\u9E1C\u9E1D\u9E7A\u9E7B\u9E7C\u9E80\u9E82\u9E83\u9E84\u9E85\u9E87\u9E8E\u9E8F\u9E96\u9E98\u9E9B\u9E9E\u9EA4\u9EA8\u9EAC\u9EAE\u9EAF\u9EB0\u9EB3\u9EB4\u9EB5\u9EC6\u9EC8\u9ECB\u9ED5\u9EDF\u9EE4\u9EE7\u9EEC\u9EED\u9EEE\u9EF0\u9EF1\u9EF2\u9EF5"], - ["8feda1", "\u9EF8\u9EFF\u9F02\u9F03\u9F09\u9F0F\u9F10\u9F11\u9F12\u9F14\u9F16\u9F17\u9F19\u9F1A\u9F1B\u9F1F\u9F22\u9F26\u9F2A\u9F2B\u9F2F\u9F31\u9F32\u9F34\u9F37\u9F39\u9F3A\u9F3C\u9F3D\u9F3F\u9F41\u9F43", 4, "\u9F53\u9F55\u9F56\u9F57\u9F58\u9F5A\u9F5D\u9F5E\u9F68\u9F69\u9F6D", 4, "\u9F73\u9F75\u9F7A\u9F7D\u9F8F\u9F90\u9F91\u9F92\u9F94\u9F96\u9F97\u9F9E\u9FA1\u9FA2\u9FA3\u9FA5"] - ]; - } -}); - -// node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/encodings/tables/cp936.json -var require_cp936 = __commonJS({ - "node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/encodings/tables/cp936.json"(exports, module) { - module.exports = [ - ["0", "\0", 127, "\u20AC"], - ["8140", "\u4E02\u4E04\u4E05\u4E06\u4E0F\u4E12\u4E17\u4E1F\u4E20\u4E21\u4E23\u4E26\u4E29\u4E2E\u4E2F\u4E31\u4E33\u4E35\u4E37\u4E3C\u4E40\u4E41\u4E42\u4E44\u4E46\u4E4A\u4E51\u4E55\u4E57\u4E5A\u4E5B\u4E62\u4E63\u4E64\u4E65\u4E67\u4E68\u4E6A", 5, "\u4E72\u4E74", 9, "\u4E7F", 6, "\u4E87\u4E8A"], - ["8180", "\u4E90\u4E96\u4E97\u4E99\u4E9C\u4E9D\u4E9E\u4EA3\u4EAA\u4EAF\u4EB0\u4EB1\u4EB4\u4EB6\u4EB7\u4EB8\u4EB9\u4EBC\u4EBD\u4EBE\u4EC8\u4ECC\u4ECF\u4ED0\u4ED2\u4EDA\u4EDB\u4EDC\u4EE0\u4EE2\u4EE6\u4EE7\u4EE9\u4EED\u4EEE\u4EEF\u4EF1\u4EF4\u4EF8\u4EF9\u4EFA\u4EFC\u4EFE\u4F00\u4F02", 6, "\u4F0B\u4F0C\u4F12", 4, "\u4F1C\u4F1D\u4F21\u4F23\u4F28\u4F29\u4F2C\u4F2D\u4F2E\u4F31\u4F33\u4F35\u4F37\u4F39\u4F3B\u4F3E", 4, "\u4F44\u4F45\u4F47", 5, "\u4F52\u4F54\u4F56\u4F61\u4F62\u4F66\u4F68\u4F6A\u4F6B\u4F6D\u4F6E\u4F71\u4F72\u4F75\u4F77\u4F78\u4F79\u4F7A\u4F7D\u4F80\u4F81\u4F82\u4F85\u4F86\u4F87\u4F8A\u4F8C\u4F8E\u4F90\u4F92\u4F93\u4F95\u4F96\u4F98\u4F99\u4F9A\u4F9C\u4F9E\u4F9F\u4FA1\u4FA2"], - ["8240", "\u4FA4\u4FAB\u4FAD\u4FB0", 4, "\u4FB6", 8, "\u4FC0\u4FC1\u4FC2\u4FC6\u4FC7\u4FC8\u4FC9\u4FCB\u4FCC\u4FCD\u4FD2", 4, "\u4FD9\u4FDB\u4FE0\u4FE2\u4FE4\u4FE5\u4FE7\u4FEB\u4FEC\u4FF0\u4FF2\u4FF4\u4FF5\u4FF6\u4FF7\u4FF9\u4FFB\u4FFC\u4FFD\u4FFF", 11], - ["8280", "\u500B\u500E\u5010\u5011\u5013\u5015\u5016\u5017\u501B\u501D\u501E\u5020\u5022\u5023\u5024\u5027\u502B\u502F", 10, "\u503B\u503D\u503F\u5040\u5041\u5042\u5044\u5045\u5046\u5049\u504A\u504B\u504D\u5050", 4, "\u5056\u5057\u5058\u5059\u505B\u505D", 7, "\u5066", 5, "\u506D", 8, "\u5078\u5079\u507A\u507C\u507D\u5081\u5082\u5083\u5084\u5086\u5087\u5089\u508A\u508B\u508C\u508E", 20, "\u50A4\u50A6\u50AA\u50AB\u50AD", 4, "\u50B3", 6, "\u50BC"], - ["8340", "\u50BD", 17, "\u50D0", 5, "\u50D7\u50D8\u50D9\u50DB", 10, "\u50E8\u50E9\u50EA\u50EB\u50EF\u50F0\u50F1\u50F2\u50F4\u50F6", 4, "\u50FC", 9, "\u5108"], - ["8380", "\u5109\u510A\u510C", 5, "\u5113", 13, "\u5122", 28, "\u5142\u5147\u514A\u514C\u514E\u514F\u5150\u5152\u5153\u5157\u5158\u5159\u515B\u515D", 4, "\u5163\u5164\u5166\u5167\u5169\u516A\u516F\u5172\u517A\u517E\u517F\u5183\u5184\u5186\u5187\u518A\u518B\u518E\u518F\u5190\u5191\u5193\u5194\u5198\u519A\u519D\u519E\u519F\u51A1\u51A3\u51A6", 4, "\u51AD\u51AE\u51B4\u51B8\u51B9\u51BA\u51BE\u51BF\u51C1\u51C2\u51C3\u51C5\u51C8\u51CA\u51CD\u51CE\u51D0\u51D2", 5], - ["8440", "\u51D8\u51D9\u51DA\u51DC\u51DE\u51DF\u51E2\u51E3\u51E5", 5, "\u51EC\u51EE\u51F1\u51F2\u51F4\u51F7\u51FE\u5204\u5205\u5209\u520B\u520C\u520F\u5210\u5213\u5214\u5215\u521C\u521E\u521F\u5221\u5222\u5223\u5225\u5226\u5227\u522A\u522C\u522F\u5231\u5232\u5234\u5235\u523C\u523E\u5244", 5, "\u524B\u524E\u524F\u5252\u5253\u5255\u5257\u5258"], - ["8480", "\u5259\u525A\u525B\u525D\u525F\u5260\u5262\u5263\u5264\u5266\u5268\u526B\u526C\u526D\u526E\u5270\u5271\u5273", 9, "\u527E\u5280\u5283", 4, "\u5289", 6, "\u5291\u5292\u5294", 6, "\u529C\u52A4\u52A5\u52A6\u52A7\u52AE\u52AF\u52B0\u52B4", 9, "\u52C0\u52C1\u52C2\u52C4\u52C5\u52C6\u52C8\u52CA\u52CC\u52CD\u52CE\u52CF\u52D1\u52D3\u52D4\u52D5\u52D7\u52D9", 5, "\u52E0\u52E1\u52E2\u52E3\u52E5", 10, "\u52F1", 7, "\u52FB\u52FC\u52FD\u5301\u5302\u5303\u5304\u5307\u5309\u530A\u530B\u530C\u530E"], - ["8540", "\u5311\u5312\u5313\u5314\u5318\u531B\u531C\u531E\u531F\u5322\u5324\u5325\u5327\u5328\u5329\u532B\u532C\u532D\u532F", 9, "\u533C\u533D\u5340\u5342\u5344\u5346\u534B\u534C\u534D\u5350\u5354\u5358\u5359\u535B\u535D\u5365\u5368\u536A\u536C\u536D\u5372\u5376\u5379\u537B\u537C\u537D\u537E\u5380\u5381\u5383\u5387\u5388\u538A\u538E\u538F"], - ["8580", "\u5390", 4, "\u5396\u5397\u5399\u539B\u539C\u539E\u53A0\u53A1\u53A4\u53A7\u53AA\u53AB\u53AC\u53AD\u53AF", 6, "\u53B7\u53B8\u53B9\u53BA\u53BC\u53BD\u53BE\u53C0\u53C3", 4, "\u53CE\u53CF\u53D0\u53D2\u53D3\u53D5\u53DA\u53DC\u53DD\u53DE\u53E1\u53E2\u53E7\u53F4\u53FA\u53FE\u53FF\u5400\u5402\u5405\u5407\u540B\u5414\u5418\u5419\u541A\u541C\u5422\u5424\u5425\u542A\u5430\u5433\u5436\u5437\u543A\u543D\u543F\u5441\u5442\u5444\u5445\u5447\u5449\u544C\u544D\u544E\u544F\u5451\u545A\u545D", 4, "\u5463\u5465\u5467\u5469", 7, "\u5474\u5479\u547A\u547E\u547F\u5481\u5483\u5485\u5487\u5488\u5489\u548A\u548D\u5491\u5493\u5497\u5498\u549C\u549E\u549F\u54A0\u54A1"], - ["8640", "\u54A2\u54A5\u54AE\u54B0\u54B2\u54B5\u54B6\u54B7\u54B9\u54BA\u54BC\u54BE\u54C3\u54C5\u54CA\u54CB\u54D6\u54D8\u54DB\u54E0", 4, "\u54EB\u54EC\u54EF\u54F0\u54F1\u54F4", 5, "\u54FB\u54FE\u5500\u5502\u5503\u5504\u5505\u5508\u550A", 4, "\u5512\u5513\u5515", 5, "\u551C\u551D\u551E\u551F\u5521\u5525\u5526"], - ["8680", "\u5528\u5529\u552B\u552D\u5532\u5534\u5535\u5536\u5538\u5539\u553A\u553B\u553D\u5540\u5542\u5545\u5547\u5548\u554B", 4, "\u5551\u5552\u5553\u5554\u5557", 4, "\u555D\u555E\u555F\u5560\u5562\u5563\u5568\u5569\u556B\u556F", 5, "\u5579\u557A\u557D\u557F\u5585\u5586\u558C\u558D\u558E\u5590\u5592\u5593\u5595\u5596\u5597\u559A\u559B\u559E\u55A0", 6, "\u55A8", 8, "\u55B2\u55B4\u55B6\u55B8\u55BA\u55BC\u55BF", 4, "\u55C6\u55C7\u55C8\u55CA\u55CB\u55CE\u55CF\u55D0\u55D5\u55D7", 4, "\u55DE\u55E0\u55E2\u55E7\u55E9\u55ED\u55EE\u55F0\u55F1\u55F4\u55F6\u55F8", 4, "\u55FF\u5602\u5603\u5604\u5605"], - ["8740", "\u5606\u5607\u560A\u560B\u560D\u5610", 7, "\u5619\u561A\u561C\u561D\u5620\u5621\u5622\u5625\u5626\u5628\u5629\u562A\u562B\u562E\u562F\u5630\u5633\u5635\u5637\u5638\u563A\u563C\u563D\u563E\u5640", 11, "\u564F", 4, "\u5655\u5656\u565A\u565B\u565D", 4], - ["8780", "\u5663\u5665\u5666\u5667\u566D\u566E\u566F\u5670\u5672\u5673\u5674\u5675\u5677\u5678\u5679\u567A\u567D", 7, "\u5687", 6, "\u5690\u5691\u5692\u5694", 14, "\u56A4", 10, "\u56B0", 6, "\u56B8\u56B9\u56BA\u56BB\u56BD", 12, "\u56CB", 8, "\u56D5\u56D6\u56D8\u56D9\u56DC\u56E3\u56E5", 5, "\u56EC\u56EE\u56EF\u56F2\u56F3\u56F6\u56F7\u56F8\u56FB\u56FC\u5700\u5701\u5702\u5705\u5707\u570B", 6], - ["8840", "\u5712", 9, "\u571D\u571E\u5720\u5721\u5722\u5724\u5725\u5726\u5727\u572B\u5731\u5732\u5734", 4, "\u573C\u573D\u573F\u5741\u5743\u5744\u5745\u5746\u5748\u5749\u574B\u5752", 4, "\u5758\u5759\u5762\u5763\u5765\u5767\u576C\u576E\u5770\u5771\u5772\u5774\u5775\u5778\u5779\u577A\u577D\u577E\u577F\u5780"], - ["8880", "\u5781\u5787\u5788\u5789\u578A\u578D", 4, "\u5794", 6, "\u579C\u579D\u579E\u579F\u57A5\u57A8\u57AA\u57AC\u57AF\u57B0\u57B1\u57B3\u57B5\u57B6\u57B7\u57B9", 8, "\u57C4", 6, "\u57CC\u57CD\u57D0\u57D1\u57D3\u57D6\u57D7\u57DB\u57DC\u57DE\u57E1\u57E2\u57E3\u57E5", 7, "\u57EE\u57F0\u57F1\u57F2\u57F3\u57F5\u57F6\u57F7\u57FB\u57FC\u57FE\u57FF\u5801\u5803\u5804\u5805\u5808\u5809\u580A\u580C\u580E\u580F\u5810\u5812\u5813\u5814\u5816\u5817\u5818\u581A\u581B\u581C\u581D\u581F\u5822\u5823\u5825", 4, "\u582B", 4, "\u5831\u5832\u5833\u5834\u5836", 7], - ["8940", "\u583E", 5, "\u5845", 6, "\u584E\u584F\u5850\u5852\u5853\u5855\u5856\u5857\u5859", 4, "\u585F", 5, "\u5866", 4, "\u586D", 16, "\u587F\u5882\u5884\u5886\u5887\u5888\u588A\u588B\u588C"], - ["8980", "\u588D", 4, "\u5894", 4, "\u589B\u589C\u589D\u58A0", 7, "\u58AA", 17, "\u58BD\u58BE\u58BF\u58C0\u58C2\u58C3\u58C4\u58C6", 10, "\u58D2\u58D3\u58D4\u58D6", 13, "\u58E5", 5, "\u58ED\u58EF\u58F1\u58F2\u58F4\u58F5\u58F7\u58F8\u58FA", 7, "\u5903\u5905\u5906\u5908", 4, "\u590E\u5910\u5911\u5912\u5913\u5917\u5918\u591B\u591D\u591E\u5920\u5921\u5922\u5923\u5926\u5928\u592C\u5930\u5932\u5933\u5935\u5936\u593B"], - ["8a40", "\u593D\u593E\u593F\u5940\u5943\u5945\u5946\u594A\u594C\u594D\u5950\u5952\u5953\u5959\u595B", 4, "\u5961\u5963\u5964\u5966", 12, "\u5975\u5977\u597A\u597B\u597C\u597E\u597F\u5980\u5985\u5989\u598B\u598C\u598E\u598F\u5990\u5991\u5994\u5995\u5998\u599A\u599B\u599C\u599D\u599F\u59A0\u59A1\u59A2\u59A6"], - ["8a80", "\u59A7\u59AC\u59AD\u59B0\u59B1\u59B3", 5, "\u59BA\u59BC\u59BD\u59BF", 6, "\u59C7\u59C8\u59C9\u59CC\u59CD\u59CE\u59CF\u59D5\u59D6\u59D9\u59DB\u59DE", 4, "\u59E4\u59E6\u59E7\u59E9\u59EA\u59EB\u59ED", 11, "\u59FA\u59FC\u59FD\u59FE\u5A00\u5A02\u5A0A\u5A0B\u5A0D\u5A0E\u5A0F\u5A10\u5A12\u5A14\u5A15\u5A16\u5A17\u5A19\u5A1A\u5A1B\u5A1D\u5A1E\u5A21\u5A22\u5A24\u5A26\u5A27\u5A28\u5A2A", 6, "\u5A33\u5A35\u5A37", 4, "\u5A3D\u5A3E\u5A3F\u5A41", 4, "\u5A47\u5A48\u5A4B", 9, "\u5A56\u5A57\u5A58\u5A59\u5A5B", 5], - ["8b40", "\u5A61\u5A63\u5A64\u5A65\u5A66\u5A68\u5A69\u5A6B", 8, "\u5A78\u5A79\u5A7B\u5A7C\u5A7D\u5A7E\u5A80", 17, "\u5A93", 6, "\u5A9C", 13, "\u5AAB\u5AAC"], - ["8b80", "\u5AAD", 4, "\u5AB4\u5AB6\u5AB7\u5AB9", 4, "\u5ABF\u5AC0\u5AC3", 5, "\u5ACA\u5ACB\u5ACD", 4, "\u5AD3\u5AD5\u5AD7\u5AD9\u5ADA\u5ADB\u5ADD\u5ADE\u5ADF\u5AE2\u5AE4\u5AE5\u5AE7\u5AE8\u5AEA\u5AEC", 4, "\u5AF2", 22, "\u5B0A", 11, "\u5B18", 25, "\u5B33\u5B35\u5B36\u5B38", 7, "\u5B41", 6], - ["8c40", "\u5B48", 7, "\u5B52\u5B56\u5B5E\u5B60\u5B61\u5B67\u5B68\u5B6B\u5B6D\u5B6E\u5B6F\u5B72\u5B74\u5B76\u5B77\u5B78\u5B79\u5B7B\u5B7C\u5B7E\u5B7F\u5B82\u5B86\u5B8A\u5B8D\u5B8E\u5B90\u5B91\u5B92\u5B94\u5B96\u5B9F\u5BA7\u5BA8\u5BA9\u5BAC\u5BAD\u5BAE\u5BAF\u5BB1\u5BB2\u5BB7\u5BBA\u5BBB\u5BBC\u5BC0\u5BC1\u5BC3\u5BC8\u5BC9\u5BCA\u5BCB\u5BCD\u5BCE\u5BCF"], - ["8c80", "\u5BD1\u5BD4", 8, "\u5BE0\u5BE2\u5BE3\u5BE6\u5BE7\u5BE9", 4, "\u5BEF\u5BF1", 6, "\u5BFD\u5BFE\u5C00\u5C02\u5C03\u5C05\u5C07\u5C08\u5C0B\u5C0C\u5C0D\u5C0E\u5C10\u5C12\u5C13\u5C17\u5C19\u5C1B\u5C1E\u5C1F\u5C20\u5C21\u5C23\u5C26\u5C28\u5C29\u5C2A\u5C2B\u5C2D\u5C2E\u5C2F\u5C30\u5C32\u5C33\u5C35\u5C36\u5C37\u5C43\u5C44\u5C46\u5C47\u5C4C\u5C4D\u5C52\u5C53\u5C54\u5C56\u5C57\u5C58\u5C5A\u5C5B\u5C5C\u5C5D\u5C5F\u5C62\u5C64\u5C67", 6, "\u5C70\u5C72", 6, "\u5C7B\u5C7C\u5C7D\u5C7E\u5C80\u5C83", 4, "\u5C89\u5C8A\u5C8B\u5C8E\u5C8F\u5C92\u5C93\u5C95\u5C9D", 4, "\u5CA4", 4], - ["8d40", "\u5CAA\u5CAE\u5CAF\u5CB0\u5CB2\u5CB4\u5CB6\u5CB9\u5CBA\u5CBB\u5CBC\u5CBE\u5CC0\u5CC2\u5CC3\u5CC5", 5, "\u5CCC", 5, "\u5CD3", 5, "\u5CDA", 6, "\u5CE2\u5CE3\u5CE7\u5CE9\u5CEB\u5CEC\u5CEE\u5CEF\u5CF1", 9, "\u5CFC", 4], - ["8d80", "\u5D01\u5D04\u5D05\u5D08", 5, "\u5D0F", 4, "\u5D15\u5D17\u5D18\u5D19\u5D1A\u5D1C\u5D1D\u5D1F", 4, "\u5D25\u5D28\u5D2A\u5D2B\u5D2C\u5D2F", 4, "\u5D35", 7, "\u5D3F", 7, "\u5D48\u5D49\u5D4D", 10, "\u5D59\u5D5A\u5D5C\u5D5E", 10, "\u5D6A\u5D6D\u5D6E\u5D70\u5D71\u5D72\u5D73\u5D75", 12, "\u5D83", 21, "\u5D9A\u5D9B\u5D9C\u5D9E\u5D9F\u5DA0"], - ["8e40", "\u5DA1", 21, "\u5DB8", 12, "\u5DC6", 6, "\u5DCE", 12, "\u5DDC\u5DDF\u5DE0\u5DE3\u5DE4\u5DEA\u5DEC\u5DED"], - ["8e80", "\u5DF0\u5DF5\u5DF6\u5DF8", 4, "\u5DFF\u5E00\u5E04\u5E07\u5E09\u5E0A\u5E0B\u5E0D\u5E0E\u5E12\u5E13\u5E17\u5E1E", 7, "\u5E28", 4, "\u5E2F\u5E30\u5E32", 4, "\u5E39\u5E3A\u5E3E\u5E3F\u5E40\u5E41\u5E43\u5E46", 5, "\u5E4D", 6, "\u5E56", 4, "\u5E5C\u5E5D\u5E5F\u5E60\u5E63", 14, "\u5E75\u5E77\u5E79\u5E7E\u5E81\u5E82\u5E83\u5E85\u5E88\u5E89\u5E8C\u5E8D\u5E8E\u5E92\u5E98\u5E9B\u5E9D\u5EA1\u5EA2\u5EA3\u5EA4\u5EA8", 4, "\u5EAE", 4, "\u5EB4\u5EBA\u5EBB\u5EBC\u5EBD\u5EBF", 6], - ["8f40", "\u5EC6\u5EC7\u5EC8\u5ECB", 5, "\u5ED4\u5ED5\u5ED7\u5ED8\u5ED9\u5EDA\u5EDC", 11, "\u5EE9\u5EEB", 8, "\u5EF5\u5EF8\u5EF9\u5EFB\u5EFC\u5EFD\u5F05\u5F06\u5F07\u5F09\u5F0C\u5F0D\u5F0E\u5F10\u5F12\u5F14\u5F16\u5F19\u5F1A\u5F1C\u5F1D\u5F1E\u5F21\u5F22\u5F23\u5F24"], - ["8f80", "\u5F28\u5F2B\u5F2C\u5F2E\u5F30\u5F32", 6, "\u5F3B\u5F3D\u5F3E\u5F3F\u5F41", 14, "\u5F51\u5F54\u5F59\u5F5A\u5F5B\u5F5C\u5F5E\u5F5F\u5F60\u5F63\u5F65\u5F67\u5F68\u5F6B\u5F6E\u5F6F\u5F72\u5F74\u5F75\u5F76\u5F78\u5F7A\u5F7D\u5F7E\u5F7F\u5F83\u5F86\u5F8D\u5F8E\u5F8F\u5F91\u5F93\u5F94\u5F96\u5F9A\u5F9B\u5F9D\u5F9E\u5F9F\u5FA0\u5FA2", 5, "\u5FA9\u5FAB\u5FAC\u5FAF", 5, "\u5FB6\u5FB8\u5FB9\u5FBA\u5FBB\u5FBE", 4, "\u5FC7\u5FC8\u5FCA\u5FCB\u5FCE\u5FD3\u5FD4\u5FD5\u5FDA\u5FDB\u5FDC\u5FDE\u5FDF\u5FE2\u5FE3\u5FE5\u5FE6\u5FE8\u5FE9\u5FEC\u5FEF\u5FF0\u5FF2\u5FF3\u5FF4\u5FF6\u5FF7\u5FF9\u5FFA\u5FFC\u6007"], - ["9040", "\u6008\u6009\u600B\u600C\u6010\u6011\u6013\u6017\u6018\u601A\u601E\u601F\u6022\u6023\u6024\u602C\u602D\u602E\u6030", 4, "\u6036", 4, "\u603D\u603E\u6040\u6044", 6, "\u604C\u604E\u604F\u6051\u6053\u6054\u6056\u6057\u6058\u605B\u605C\u605E\u605F\u6060\u6061\u6065\u6066\u606E\u6071\u6072\u6074\u6075\u6077\u607E\u6080"], - ["9080", "\u6081\u6082\u6085\u6086\u6087\u6088\u608A\u608B\u608E\u608F\u6090\u6091\u6093\u6095\u6097\u6098\u6099\u609C\u609E\u60A1\u60A2\u60A4\u60A5\u60A7\u60A9\u60AA\u60AE\u60B0\u60B3\u60B5\u60B6\u60B7\u60B9\u60BA\u60BD", 7, "\u60C7\u60C8\u60C9\u60CC", 4, "\u60D2\u60D3\u60D4\u60D6\u60D7\u60D9\u60DB\u60DE\u60E1", 4, "\u60EA\u60F1\u60F2\u60F5\u60F7\u60F8\u60FB", 4, "\u6102\u6103\u6104\u6105\u6107\u610A\u610B\u610C\u6110", 4, "\u6116\u6117\u6118\u6119\u611B\u611C\u611D\u611E\u6121\u6122\u6125\u6128\u6129\u612A\u612C", 18, "\u6140", 6], - ["9140", "\u6147\u6149\u614B\u614D\u614F\u6150\u6152\u6153\u6154\u6156", 6, "\u615E\u615F\u6160\u6161\u6163\u6164\u6165\u6166\u6169", 6, "\u6171\u6172\u6173\u6174\u6176\u6178", 18, "\u618C\u618D\u618F", 4, "\u6195"], - ["9180", "\u6196", 6, "\u619E", 8, "\u61AA\u61AB\u61AD", 9, "\u61B8", 5, "\u61BF\u61C0\u61C1\u61C3", 4, "\u61C9\u61CC", 4, "\u61D3\u61D5", 16, "\u61E7", 13, "\u61F6", 8, "\u6200", 5, "\u6207\u6209\u6213\u6214\u6219\u621C\u621D\u621E\u6220\u6223\u6226\u6227\u6228\u6229\u622B\u622D\u622F\u6230\u6231\u6232\u6235\u6236\u6238", 4, "\u6242\u6244\u6245\u6246\u624A"], - ["9240", "\u624F\u6250\u6255\u6256\u6257\u6259\u625A\u625C", 6, "\u6264\u6265\u6268\u6271\u6272\u6274\u6275\u6277\u6278\u627A\u627B\u627D\u6281\u6282\u6283\u6285\u6286\u6287\u6288\u628B", 5, "\u6294\u6299\u629C\u629D\u629E\u62A3\u62A6\u62A7\u62A9\u62AA\u62AD\u62AE\u62AF\u62B0\u62B2\u62B3\u62B4\u62B6\u62B7\u62B8\u62BA\u62BE\u62C0\u62C1"], - ["9280", "\u62C3\u62CB\u62CF\u62D1\u62D5\u62DD\u62DE\u62E0\u62E1\u62E4\u62EA\u62EB\u62F0\u62F2\u62F5\u62F8\u62F9\u62FA\u62FB\u6300\u6303\u6304\u6305\u6306\u630A\u630B\u630C\u630D\u630F\u6310\u6312\u6313\u6314\u6315\u6317\u6318\u6319\u631C\u6326\u6327\u6329\u632C\u632D\u632E\u6330\u6331\u6333", 5, "\u633B\u633C\u633E\u633F\u6340\u6341\u6344\u6347\u6348\u634A\u6351\u6352\u6353\u6354\u6356", 7, "\u6360\u6364\u6365\u6366\u6368\u636A\u636B\u636C\u636F\u6370\u6372\u6373\u6374\u6375\u6378\u6379\u637C\u637D\u637E\u637F\u6381\u6383\u6384\u6385\u6386\u638B\u638D\u6391\u6393\u6394\u6395\u6397\u6399", 6, "\u63A1\u63A4\u63A6\u63AB\u63AF\u63B1\u63B2\u63B5\u63B6\u63B9\u63BB\u63BD\u63BF\u63C0"], - ["9340", "\u63C1\u63C2\u63C3\u63C5\u63C7\u63C8\u63CA\u63CB\u63CC\u63D1\u63D3\u63D4\u63D5\u63D7", 6, "\u63DF\u63E2\u63E4", 4, "\u63EB\u63EC\u63EE\u63EF\u63F0\u63F1\u63F3\u63F5\u63F7\u63F9\u63FA\u63FB\u63FC\u63FE\u6403\u6404\u6406", 4, "\u640D\u640E\u6411\u6412\u6415", 5, "\u641D\u641F\u6422\u6423\u6424"], - ["9380", "\u6425\u6427\u6428\u6429\u642B\u642E", 5, "\u6435", 4, "\u643B\u643C\u643E\u6440\u6442\u6443\u6449\u644B", 6, "\u6453\u6455\u6456\u6457\u6459", 4, "\u645F", 7, "\u6468\u646A\u646B\u646C\u646E", 9, "\u647B", 6, "\u6483\u6486\u6488", 8, "\u6493\u6494\u6497\u6498\u649A\u649B\u649C\u649D\u649F", 4, "\u64A5\u64A6\u64A7\u64A8\u64AA\u64AB\u64AF\u64B1\u64B2\u64B3\u64B4\u64B6\u64B9\u64BB\u64BD\u64BE\u64BF\u64C1\u64C3\u64C4\u64C6", 6, "\u64CF\u64D1\u64D3\u64D4\u64D5\u64D6\u64D9\u64DA"], - ["9440", "\u64DB\u64DC\u64DD\u64DF\u64E0\u64E1\u64E3\u64E5\u64E7", 24, "\u6501", 7, "\u650A", 7, "\u6513", 4, "\u6519", 8], - ["9480", "\u6522\u6523\u6524\u6526", 4, "\u652C\u652D\u6530\u6531\u6532\u6533\u6537\u653A\u653C\u653D\u6540", 4, "\u6546\u6547\u654A\u654B\u654D\u654E\u6550\u6552\u6553\u6554\u6557\u6558\u655A\u655C\u655F\u6560\u6561\u6564\u6565\u6567\u6568\u6569\u656A\u656D\u656E\u656F\u6571\u6573\u6575\u6576\u6578", 14, "\u6588\u6589\u658A\u658D\u658E\u658F\u6592\u6594\u6595\u6596\u6598\u659A\u659D\u659E\u65A0\u65A2\u65A3\u65A6\u65A8\u65AA\u65AC\u65AE\u65B1", 7, "\u65BA\u65BB\u65BE\u65BF\u65C0\u65C2\u65C7\u65C8\u65C9\u65CA\u65CD\u65D0\u65D1\u65D3\u65D4\u65D5\u65D8", 7, "\u65E1\u65E3\u65E4\u65EA\u65EB"], - ["9540", "\u65F2\u65F3\u65F4\u65F5\u65F8\u65F9\u65FB", 4, "\u6601\u6604\u6605\u6607\u6608\u6609\u660B\u660D\u6610\u6611\u6612\u6616\u6617\u6618\u661A\u661B\u661C\u661E\u6621\u6622\u6623\u6624\u6626\u6629\u662A\u662B\u662C\u662E\u6630\u6632\u6633\u6637", 4, "\u663D\u663F\u6640\u6642\u6644", 6, "\u664D\u664E\u6650\u6651\u6658"], - ["9580", "\u6659\u665B\u665C\u665D\u665E\u6660\u6662\u6663\u6665\u6667\u6669", 4, "\u6671\u6672\u6673\u6675\u6678\u6679\u667B\u667C\u667D\u667F\u6680\u6681\u6683\u6685\u6686\u6688\u6689\u668A\u668B\u668D\u668E\u668F\u6690\u6692\u6693\u6694\u6695\u6698", 4, "\u669E", 8, "\u66A9", 4, "\u66AF", 4, "\u66B5\u66B6\u66B7\u66B8\u66BA\u66BB\u66BC\u66BD\u66BF", 25, "\u66DA\u66DE", 7, "\u66E7\u66E8\u66EA", 5, "\u66F1\u66F5\u66F6\u66F8\u66FA\u66FB\u66FD\u6701\u6702\u6703"], - ["9640", "\u6704\u6705\u6706\u6707\u670C\u670E\u670F\u6711\u6712\u6713\u6716\u6718\u6719\u671A\u671C\u671E\u6720", 5, "\u6727\u6729\u672E\u6730\u6732\u6733\u6736\u6737\u6738\u6739\u673B\u673C\u673E\u673F\u6741\u6744\u6745\u6747\u674A\u674B\u674D\u6752\u6754\u6755\u6757", 4, "\u675D\u6762\u6763\u6764\u6766\u6767\u676B\u676C\u676E\u6771\u6774\u6776"], - ["9680", "\u6778\u6779\u677A\u677B\u677D\u6780\u6782\u6783\u6785\u6786\u6788\u678A\u678C\u678D\u678E\u678F\u6791\u6792\u6793\u6794\u6796\u6799\u679B\u679F\u67A0\u67A1\u67A4\u67A6\u67A9\u67AC\u67AE\u67B1\u67B2\u67B4\u67B9", 7, "\u67C2\u67C5", 9, "\u67D5\u67D6\u67D7\u67DB\u67DF\u67E1\u67E3\u67E4\u67E6\u67E7\u67E8\u67EA\u67EB\u67ED\u67EE\u67F2\u67F5", 7, "\u67FE\u6801\u6802\u6803\u6804\u6806\u680D\u6810\u6812\u6814\u6815\u6818", 4, "\u681E\u681F\u6820\u6822", 6, "\u682B", 6, "\u6834\u6835\u6836\u683A\u683B\u683F\u6847\u684B\u684D\u684F\u6852\u6856", 5], - ["9740", "\u685C\u685D\u685E\u685F\u686A\u686C", 7, "\u6875\u6878", 8, "\u6882\u6884\u6887", 7, "\u6890\u6891\u6892\u6894\u6895\u6896\u6898", 9, "\u68A3\u68A4\u68A5\u68A9\u68AA\u68AB\u68AC\u68AE\u68B1\u68B2\u68B4\u68B6\u68B7\u68B8"], - ["9780", "\u68B9", 6, "\u68C1\u68C3", 5, "\u68CA\u68CC\u68CE\u68CF\u68D0\u68D1\u68D3\u68D4\u68D6\u68D7\u68D9\u68DB", 4, "\u68E1\u68E2\u68E4", 9, "\u68EF\u68F2\u68F3\u68F4\u68F6\u68F7\u68F8\u68FB\u68FD\u68FE\u68FF\u6900\u6902\u6903\u6904\u6906", 4, "\u690C\u690F\u6911\u6913", 11, "\u6921\u6922\u6923\u6925", 7, "\u692E\u692F\u6931\u6932\u6933\u6935\u6936\u6937\u6938\u693A\u693B\u693C\u693E\u6940\u6941\u6943", 16, "\u6955\u6956\u6958\u6959\u695B\u695C\u695F"], - ["9840", "\u6961\u6962\u6964\u6965\u6967\u6968\u6969\u696A\u696C\u696D\u696F\u6970\u6972", 4, "\u697A\u697B\u697D\u697E\u697F\u6981\u6983\u6985\u698A\u698B\u698C\u698E", 5, "\u6996\u6997\u6999\u699A\u699D", 9, "\u69A9\u69AA\u69AC\u69AE\u69AF\u69B0\u69B2\u69B3\u69B5\u69B6\u69B8\u69B9\u69BA\u69BC\u69BD"], - ["9880", "\u69BE\u69BF\u69C0\u69C2", 7, "\u69CB\u69CD\u69CF\u69D1\u69D2\u69D3\u69D5", 5, "\u69DC\u69DD\u69DE\u69E1", 11, "\u69EE\u69EF\u69F0\u69F1\u69F3", 9, "\u69FE\u6A00", 9, "\u6A0B", 11, "\u6A19", 5, "\u6A20\u6A22", 5, "\u6A29\u6A2B\u6A2C\u6A2D\u6A2E\u6A30\u6A32\u6A33\u6A34\u6A36", 6, "\u6A3F", 4, "\u6A45\u6A46\u6A48", 7, "\u6A51", 6, "\u6A5A"], - ["9940", "\u6A5C", 4, "\u6A62\u6A63\u6A64\u6A66", 10, "\u6A72", 6, "\u6A7A\u6A7B\u6A7D\u6A7E\u6A7F\u6A81\u6A82\u6A83\u6A85", 8, "\u6A8F\u6A92", 4, "\u6A98", 7, "\u6AA1", 5], - ["9980", "\u6AA7\u6AA8\u6AAA\u6AAD", 114, "\u6B25\u6B26\u6B28", 6], - ["9a40", "\u6B2F\u6B30\u6B31\u6B33\u6B34\u6B35\u6B36\u6B38\u6B3B\u6B3C\u6B3D\u6B3F\u6B40\u6B41\u6B42\u6B44\u6B45\u6B48\u6B4A\u6B4B\u6B4D", 11, "\u6B5A", 7, "\u6B68\u6B69\u6B6B", 13, "\u6B7A\u6B7D\u6B7E\u6B7F\u6B80\u6B85\u6B88"], - ["9a80", "\u6B8C\u6B8E\u6B8F\u6B90\u6B91\u6B94\u6B95\u6B97\u6B98\u6B99\u6B9C", 4, "\u6BA2", 7, "\u6BAB", 7, "\u6BB6\u6BB8", 6, "\u6BC0\u6BC3\u6BC4\u6BC6", 4, "\u6BCC\u6BCE\u6BD0\u6BD1\u6BD8\u6BDA\u6BDC", 4, "\u6BE2", 7, "\u6BEC\u6BED\u6BEE\u6BF0\u6BF1\u6BF2\u6BF4\u6BF6\u6BF7\u6BF8\u6BFA\u6BFB\u6BFC\u6BFE", 6, "\u6C08", 4, "\u6C0E\u6C12\u6C17\u6C1C\u6C1D\u6C1E\u6C20\u6C23\u6C25\u6C2B\u6C2C\u6C2D\u6C31\u6C33\u6C36\u6C37\u6C39\u6C3A\u6C3B\u6C3C\u6C3E\u6C3F\u6C43\u6C44\u6C45\u6C48\u6C4B", 4, "\u6C51\u6C52\u6C53\u6C56\u6C58"], - ["9b40", "\u6C59\u6C5A\u6C62\u6C63\u6C65\u6C66\u6C67\u6C6B", 4, "\u6C71\u6C73\u6C75\u6C77\u6C78\u6C7A\u6C7B\u6C7C\u6C7F\u6C80\u6C84\u6C87\u6C8A\u6C8B\u6C8D\u6C8E\u6C91\u6C92\u6C95\u6C96\u6C97\u6C98\u6C9A\u6C9C\u6C9D\u6C9E\u6CA0\u6CA2\u6CA8\u6CAC\u6CAF\u6CB0\u6CB4\u6CB5\u6CB6\u6CB7\u6CBA\u6CC0\u6CC1\u6CC2\u6CC3\u6CC6\u6CC7\u6CC8\u6CCB\u6CCD\u6CCE\u6CCF\u6CD1\u6CD2\u6CD8"], - ["9b80", "\u6CD9\u6CDA\u6CDC\u6CDD\u6CDF\u6CE4\u6CE6\u6CE7\u6CE9\u6CEC\u6CED\u6CF2\u6CF4\u6CF9\u6CFF\u6D00\u6D02\u6D03\u6D05\u6D06\u6D08\u6D09\u6D0A\u6D0D\u6D0F\u6D10\u6D11\u6D13\u6D14\u6D15\u6D16\u6D18\u6D1C\u6D1D\u6D1F", 5, "\u6D26\u6D28\u6D29\u6D2C\u6D2D\u6D2F\u6D30\u6D34\u6D36\u6D37\u6D38\u6D3A\u6D3F\u6D40\u6D42\u6D44\u6D49\u6D4C\u6D50\u6D55\u6D56\u6D57\u6D58\u6D5B\u6D5D\u6D5F\u6D61\u6D62\u6D64\u6D65\u6D67\u6D68\u6D6B\u6D6C\u6D6D\u6D70\u6D71\u6D72\u6D73\u6D75\u6D76\u6D79\u6D7A\u6D7B\u6D7D", 4, "\u6D83\u6D84\u6D86\u6D87\u6D8A\u6D8B\u6D8D\u6D8F\u6D90\u6D92\u6D96", 4, "\u6D9C\u6DA2\u6DA5\u6DAC\u6DAD\u6DB0\u6DB1\u6DB3\u6DB4\u6DB6\u6DB7\u6DB9", 5, "\u6DC1\u6DC2\u6DC3\u6DC8\u6DC9\u6DCA"], - ["9c40", "\u6DCD\u6DCE\u6DCF\u6DD0\u6DD2\u6DD3\u6DD4\u6DD5\u6DD7\u6DDA\u6DDB\u6DDC\u6DDF\u6DE2\u6DE3\u6DE5\u6DE7\u6DE8\u6DE9\u6DEA\u6DED\u6DEF\u6DF0\u6DF2\u6DF4\u6DF5\u6DF6\u6DF8\u6DFA\u6DFD", 7, "\u6E06\u6E07\u6E08\u6E09\u6E0B\u6E0F\u6E12\u6E13\u6E15\u6E18\u6E19\u6E1B\u6E1C\u6E1E\u6E1F\u6E22\u6E26\u6E27\u6E28\u6E2A\u6E2C\u6E2E\u6E30\u6E31\u6E33\u6E35"], - ["9c80", "\u6E36\u6E37\u6E39\u6E3B", 7, "\u6E45", 7, "\u6E4F\u6E50\u6E51\u6E52\u6E55\u6E57\u6E59\u6E5A\u6E5C\u6E5D\u6E5E\u6E60", 10, "\u6E6C\u6E6D\u6E6F", 14, "\u6E80\u6E81\u6E82\u6E84\u6E87\u6E88\u6E8A", 4, "\u6E91", 6, "\u6E99\u6E9A\u6E9B\u6E9D\u6E9E\u6EA0\u6EA1\u6EA3\u6EA4\u6EA6\u6EA8\u6EA9\u6EAB\u6EAC\u6EAD\u6EAE\u6EB0\u6EB3\u6EB5\u6EB8\u6EB9\u6EBC\u6EBE\u6EBF\u6EC0\u6EC3\u6EC4\u6EC5\u6EC6\u6EC8\u6EC9\u6ECA\u6ECC\u6ECD\u6ECE\u6ED0\u6ED2\u6ED6\u6ED8\u6ED9\u6EDB\u6EDC\u6EDD\u6EE3\u6EE7\u6EEA", 5], - ["9d40", "\u6EF0\u6EF1\u6EF2\u6EF3\u6EF5\u6EF6\u6EF7\u6EF8\u6EFA", 7, "\u6F03\u6F04\u6F05\u6F07\u6F08\u6F0A", 4, "\u6F10\u6F11\u6F12\u6F16", 9, "\u6F21\u6F22\u6F23\u6F25\u6F26\u6F27\u6F28\u6F2C\u6F2E\u6F30\u6F32\u6F34\u6F35\u6F37", 6, "\u6F3F\u6F40\u6F41\u6F42"], - ["9d80", "\u6F43\u6F44\u6F45\u6F48\u6F49\u6F4A\u6F4C\u6F4E", 9, "\u6F59\u6F5A\u6F5B\u6F5D\u6F5F\u6F60\u6F61\u6F63\u6F64\u6F65\u6F67", 5, "\u6F6F\u6F70\u6F71\u6F73\u6F75\u6F76\u6F77\u6F79\u6F7B\u6F7D", 6, "\u6F85\u6F86\u6F87\u6F8A\u6F8B\u6F8F", 12, "\u6F9D\u6F9E\u6F9F\u6FA0\u6FA2", 4, "\u6FA8", 10, "\u6FB4\u6FB5\u6FB7\u6FB8\u6FBA", 5, "\u6FC1\u6FC3", 5, "\u6FCA", 6, "\u6FD3", 10, "\u6FDF\u6FE2\u6FE3\u6FE4\u6FE5"], - ["9e40", "\u6FE6", 7, "\u6FF0", 32, "\u7012", 7, "\u701C", 6, "\u7024", 6], - ["9e80", "\u702B", 9, "\u7036\u7037\u7038\u703A", 17, "\u704D\u704E\u7050", 13, "\u705F", 11, "\u706E\u7071\u7072\u7073\u7074\u7077\u7079\u707A\u707B\u707D\u7081\u7082\u7083\u7084\u7086\u7087\u7088\u708B\u708C\u708D\u708F\u7090\u7091\u7093\u7097\u7098\u709A\u709B\u709E", 12, "\u70B0\u70B2\u70B4\u70B5\u70B6\u70BA\u70BE\u70BF\u70C4\u70C5\u70C6\u70C7\u70C9\u70CB", 12, "\u70DA"], - ["9f40", "\u70DC\u70DD\u70DE\u70E0\u70E1\u70E2\u70E3\u70E5\u70EA\u70EE\u70F0", 6, "\u70F8\u70FA\u70FB\u70FC\u70FE", 10, "\u710B", 4, "\u7111\u7112\u7114\u7117\u711B", 10, "\u7127", 7, "\u7132\u7133\u7134"], - ["9f80", "\u7135\u7137", 13, "\u7146\u7147\u7148\u7149\u714B\u714D\u714F", 12, "\u715D\u715F", 4, "\u7165\u7169", 4, "\u716F\u7170\u7171\u7174\u7175\u7176\u7177\u7179\u717B\u717C\u717E", 5, "\u7185", 4, "\u718B\u718C\u718D\u718E\u7190\u7191\u7192\u7193\u7195\u7196\u7197\u719A", 4, "\u71A1", 6, "\u71A9\u71AA\u71AB\u71AD", 5, "\u71B4\u71B6\u71B7\u71B8\u71BA", 8, "\u71C4", 9, "\u71CF", 4], - ["a040", "\u71D6", 9, "\u71E1\u71E2\u71E3\u71E4\u71E6\u71E8", 5, "\u71EF", 9, "\u71FA", 11, "\u7207", 19], - ["a080", "\u721B\u721C\u721E", 9, "\u7229\u722B\u722D\u722E\u722F\u7232\u7233\u7234\u723A\u723C\u723E\u7240", 6, "\u7249\u724A\u724B\u724E\u724F\u7250\u7251\u7253\u7254\u7255\u7257\u7258\u725A\u725C\u725E\u7260\u7263\u7264\u7265\u7268\u726A\u726B\u726C\u726D\u7270\u7271\u7273\u7274\u7276\u7277\u7278\u727B\u727C\u727D\u7282\u7283\u7285", 4, "\u728C\u728E\u7290\u7291\u7293", 11, "\u72A0", 11, "\u72AE\u72B1\u72B2\u72B3\u72B5\u72BA", 6, "\u72C5\u72C6\u72C7\u72C9\u72CA\u72CB\u72CC\u72CF\u72D1\u72D3\u72D4\u72D5\u72D6\u72D8\u72DA\u72DB"], - ["a1a1", "\u3000\u3001\u3002\xB7\u02C9\u02C7\xA8\u3003\u3005\u2014\uFF5E\u2016\u2026\u2018\u2019\u201C\u201D\u3014\u3015\u3008", 7, "\u3016\u3017\u3010\u3011\xB1\xD7\xF7\u2236\u2227\u2228\u2211\u220F\u222A\u2229\u2208\u2237\u221A\u22A5\u2225\u2220\u2312\u2299\u222B\u222E\u2261\u224C\u2248\u223D\u221D\u2260\u226E\u226F\u2264\u2265\u221E\u2235\u2234\u2642\u2640\xB0\u2032\u2033\u2103\uFF04\xA4\uFFE0\uFFE1\u2030\xA7\u2116\u2606\u2605\u25CB\u25CF\u25CE\u25C7\u25C6\u25A1\u25A0\u25B3\u25B2\u203B\u2192\u2190\u2191\u2193\u3013"], - ["a2a1", "\u2170", 9], - ["a2b1", "\u2488", 19, "\u2474", 19, "\u2460", 9], - ["a2e5", "\u3220", 9], - ["a2f1", "\u2160", 11], - ["a3a1", "\uFF01\uFF02\uFF03\uFFE5\uFF05", 88, "\uFFE3"], - ["a4a1", "\u3041", 82], - ["a5a1", "\u30A1", 85], - ["a6a1", "\u0391", 16, "\u03A3", 6], - ["a6c1", "\u03B1", 16, "\u03C3", 6], - ["a6e0", "\uFE35\uFE36\uFE39\uFE3A\uFE3F\uFE40\uFE3D\uFE3E\uFE41\uFE42\uFE43\uFE44"], - ["a6ee", "\uFE3B\uFE3C\uFE37\uFE38\uFE31"], - ["a6f4", "\uFE33\uFE34"], - ["a7a1", "\u0410", 5, "\u0401\u0416", 25], - ["a7d1", "\u0430", 5, "\u0451\u0436", 25], - ["a840", "\u02CA\u02CB\u02D9\u2013\u2015\u2025\u2035\u2105\u2109\u2196\u2197\u2198\u2199\u2215\u221F\u2223\u2252\u2266\u2267\u22BF\u2550", 35, "\u2581", 6], - ["a880", "\u2588", 7, "\u2593\u2594\u2595\u25BC\u25BD\u25E2\u25E3\u25E4\u25E5\u2609\u2295\u3012\u301D\u301E"], - ["a8a1", "\u0101\xE1\u01CE\xE0\u0113\xE9\u011B\xE8\u012B\xED\u01D0\xEC\u014D\xF3\u01D2\xF2\u016B\xFA\u01D4\xF9\u01D6\u01D8\u01DA\u01DC\xFC\xEA\u0251"], - ["a8bd", "\u0144\u0148"], - ["a8c0", "\u0261"], - ["a8c5", "\u3105", 36], - ["a940", "\u3021", 8, "\u32A3\u338E\u338F\u339C\u339D\u339E\u33A1\u33C4\u33CE\u33D1\u33D2\u33D5\uFE30\uFFE2\uFFE4"], - ["a959", "\u2121\u3231"], - ["a95c", "\u2010"], - ["a960", "\u30FC\u309B\u309C\u30FD\u30FE\u3006\u309D\u309E\uFE49", 9, "\uFE54\uFE55\uFE56\uFE57\uFE59", 8], - ["a980", "\uFE62", 4, "\uFE68\uFE69\uFE6A\uFE6B"], - ["a996", "\u3007"], - ["a9a4", "\u2500", 75], - ["aa40", "\u72DC\u72DD\u72DF\u72E2", 5, "\u72EA\u72EB\u72F5\u72F6\u72F9\u72FD\u72FE\u72FF\u7300\u7302\u7304", 5, "\u730B\u730C\u730D\u730F\u7310\u7311\u7312\u7314\u7318\u7319\u731A\u731F\u7320\u7323\u7324\u7326\u7327\u7328\u732D\u732F\u7330\u7332\u7333\u7335\u7336\u733A\u733B\u733C\u733D\u7340", 8], - ["aa80", "\u7349\u734A\u734B\u734C\u734E\u734F\u7351\u7353\u7354\u7355\u7356\u7358", 7, "\u7361", 10, "\u736E\u7370\u7371"], - ["ab40", "\u7372", 11, "\u737F", 4, "\u7385\u7386\u7388\u738A\u738C\u738D\u738F\u7390\u7392\u7393\u7394\u7395\u7397\u7398\u7399\u739A\u739C\u739D\u739E\u73A0\u73A1\u73A3", 5, "\u73AA\u73AC\u73AD\u73B1\u73B4\u73B5\u73B6\u73B8\u73B9\u73BC\u73BD\u73BE\u73BF\u73C1\u73C3", 4], - ["ab80", "\u73CB\u73CC\u73CE\u73D2", 6, "\u73DA\u73DB\u73DC\u73DD\u73DF\u73E1\u73E2\u73E3\u73E4\u73E6\u73E8\u73EA\u73EB\u73EC\u73EE\u73EF\u73F0\u73F1\u73F3", 4], - ["ac40", "\u73F8", 10, "\u7404\u7407\u7408\u740B\u740C\u740D\u740E\u7411", 8, "\u741C", 5, "\u7423\u7424\u7427\u7429\u742B\u742D\u742F\u7431\u7432\u7437", 4, "\u743D\u743E\u743F\u7440\u7442", 11], - ["ac80", "\u744E", 6, "\u7456\u7458\u745D\u7460", 12, "\u746E\u746F\u7471", 4, "\u7478\u7479\u747A"], - ["ad40", "\u747B\u747C\u747D\u747F\u7482\u7484\u7485\u7486\u7488\u7489\u748A\u748C\u748D\u748F\u7491", 10, "\u749D\u749F", 7, "\u74AA", 15, "\u74BB", 12], - ["ad80", "\u74C8", 9, "\u74D3", 8, "\u74DD\u74DF\u74E1\u74E5\u74E7", 6, "\u74F0\u74F1\u74F2"], - ["ae40", "\u74F3\u74F5\u74F8", 6, "\u7500\u7501\u7502\u7503\u7505", 7, "\u750E\u7510\u7512\u7514\u7515\u7516\u7517\u751B\u751D\u751E\u7520", 4, "\u7526\u7527\u752A\u752E\u7534\u7536\u7539\u753C\u753D\u753F\u7541\u7542\u7543\u7544\u7546\u7547\u7549\u754A\u754D\u7550\u7551\u7552\u7553\u7555\u7556\u7557\u7558"], - ["ae80", "\u755D", 7, "\u7567\u7568\u7569\u756B", 6, "\u7573\u7575\u7576\u7577\u757A", 4, "\u7580\u7581\u7582\u7584\u7585\u7587"], - ["af40", "\u7588\u7589\u758A\u758C\u758D\u758E\u7590\u7593\u7595\u7598\u759B\u759C\u759E\u75A2\u75A6", 4, "\u75AD\u75B6\u75B7\u75BA\u75BB\u75BF\u75C0\u75C1\u75C6\u75CB\u75CC\u75CE\u75CF\u75D0\u75D1\u75D3\u75D7\u75D9\u75DA\u75DC\u75DD\u75DF\u75E0\u75E1\u75E5\u75E9\u75EC\u75ED\u75EE\u75EF\u75F2\u75F3\u75F5\u75F6\u75F7\u75F8\u75FA\u75FB\u75FD\u75FE\u7602\u7604\u7606\u7607"], - ["af80", "\u7608\u7609\u760B\u760D\u760E\u760F\u7611\u7612\u7613\u7614\u7616\u761A\u761C\u761D\u761E\u7621\u7623\u7627\u7628\u762C\u762E\u762F\u7631\u7632\u7636\u7637\u7639\u763A\u763B\u763D\u7641\u7642\u7644"], - ["b040", "\u7645", 6, "\u764E", 5, "\u7655\u7657", 4, "\u765D\u765F\u7660\u7661\u7662\u7664", 6, "\u766C\u766D\u766E\u7670", 7, "\u7679\u767A\u767C\u767F\u7680\u7681\u7683\u7685\u7689\u768A\u768C\u768D\u768F\u7690\u7692\u7694\u7695\u7697\u7698\u769A\u769B"], - ["b080", "\u769C", 7, "\u76A5", 8, "\u76AF\u76B0\u76B3\u76B5", 9, "\u76C0\u76C1\u76C3\u554A\u963F\u57C3\u6328\u54CE\u5509\u54C0\u7691\u764C\u853C\u77EE\u827E\u788D\u7231\u9698\u978D\u6C28\u5B89\u4FFA\u6309\u6697\u5CB8\u80FA\u6848\u80AE\u6602\u76CE\u51F9\u6556\u71AC\u7FF1\u8884\u50B2\u5965\u61CA\u6FB3\u82AD\u634C\u6252\u53ED\u5427\u7B06\u516B\u75A4\u5DF4\u62D4\u8DCB\u9776\u628A\u8019\u575D\u9738\u7F62\u7238\u767D\u67CF\u767E\u6446\u4F70\u8D25\u62DC\u7A17\u6591\u73ED\u642C\u6273\u822C\u9881\u677F\u7248\u626E\u62CC\u4F34\u74E3\u534A\u529E\u7ECA\u90A6\u5E2E\u6886\u699C\u8180\u7ED1\u68D2\u78C5\u868C\u9551\u508D\u8C24\u82DE\u80DE\u5305\u8912\u5265"], - ["b140", "\u76C4\u76C7\u76C9\u76CB\u76CC\u76D3\u76D5\u76D9\u76DA\u76DC\u76DD\u76DE\u76E0", 4, "\u76E6", 7, "\u76F0\u76F3\u76F5\u76F6\u76F7\u76FA\u76FB\u76FD\u76FF\u7700\u7702\u7703\u7705\u7706\u770A\u770C\u770E", 10, "\u771B\u771C\u771D\u771E\u7721\u7723\u7724\u7725\u7727\u772A\u772B"], - ["b180", "\u772C\u772E\u7730", 4, "\u7739\u773B\u773D\u773E\u773F\u7742\u7744\u7745\u7746\u7748", 7, "\u7752", 7, "\u775C\u8584\u96F9\u4FDD\u5821\u9971\u5B9D\u62B1\u62A5\u66B4\u8C79\u9C8D\u7206\u676F\u7891\u60B2\u5351\u5317\u8F88\u80CC\u8D1D\u94A1\u500D\u72C8\u5907\u60EB\u7119\u88AB\u5954\u82EF\u672C\u7B28\u5D29\u7EF7\u752D\u6CF5\u8E66\u8FF8\u903C\u9F3B\u6BD4\u9119\u7B14\u5F7C\u78A7\u84D6\u853D\u6BD5\u6BD9\u6BD6\u5E01\u5E87\u75F9\u95ED\u655D\u5F0A\u5FC5\u8F9F\u58C1\u81C2\u907F\u965B\u97AD\u8FB9\u7F16\u8D2C\u6241\u4FBF\u53D8\u535E\u8FA8\u8FA9\u8FAB\u904D\u6807\u5F6A\u8198\u8868\u9CD6\u618B\u522B\u762A\u5F6C\u658C\u6FD2\u6EE8\u5BBE\u6448\u5175\u51B0\u67C4\u4E19\u79C9\u997C\u70B3"], - ["b240", "\u775D\u775E\u775F\u7760\u7764\u7767\u7769\u776A\u776D", 11, "\u777A\u777B\u777C\u7781\u7782\u7783\u7786", 5, "\u778F\u7790\u7793", 11, "\u77A1\u77A3\u77A4\u77A6\u77A8\u77AB\u77AD\u77AE\u77AF\u77B1\u77B2\u77B4\u77B6", 4], - ["b280", "\u77BC\u77BE\u77C0", 12, "\u77CE", 8, "\u77D8\u77D9\u77DA\u77DD", 4, "\u77E4\u75C5\u5E76\u73BB\u83E0\u64AD\u62E8\u94B5\u6CE2\u535A\u52C3\u640F\u94C2\u7B94\u4F2F\u5E1B\u8236\u8116\u818A\u6E24\u6CCA\u9A73\u6355\u535C\u54FA\u8865\u57E0\u4E0D\u5E03\u6B65\u7C3F\u90E8\u6016\u64E6\u731C\u88C1\u6750\u624D\u8D22\u776C\u8E29\u91C7\u5F69\u83DC\u8521\u9910\u53C2\u8695\u6B8B\u60ED\u60E8\u707F\u82CD\u8231\u4ED3\u6CA7\u85CF\u64CD\u7CD9\u69FD\u66F9\u8349\u5395\u7B56\u4FA7\u518C\u6D4B\u5C42\u8E6D\u63D2\u53C9\u832C\u8336\u67E5\u78B4\u643D\u5BDF\u5C94\u5DEE\u8BE7\u62C6\u67F4\u8C7A\u6400\u63BA\u8749\u998B\u8C17\u7F20\u94F2\u4EA7\u9610\u98A4\u660C\u7316"], - ["b340", "\u77E6\u77E8\u77EA\u77EF\u77F0\u77F1\u77F2\u77F4\u77F5\u77F7\u77F9\u77FA\u77FB\u77FC\u7803", 5, "\u780A\u780B\u780E\u780F\u7810\u7813\u7815\u7819\u781B\u781E\u7820\u7821\u7822\u7824\u7828\u782A\u782B\u782E\u782F\u7831\u7832\u7833\u7835\u7836\u783D\u783F\u7841\u7842\u7843\u7844\u7846\u7848\u7849\u784A\u784B\u784D\u784F\u7851\u7853\u7854\u7858\u7859\u785A"], - ["b380", "\u785B\u785C\u785E", 11, "\u786F", 7, "\u7878\u7879\u787A\u787B\u787D", 6, "\u573A\u5C1D\u5E38\u957F\u507F\u80A0\u5382\u655E\u7545\u5531\u5021\u8D85\u6284\u949E\u671D\u5632\u6F6E\u5DE2\u5435\u7092\u8F66\u626F\u64A4\u63A3\u5F7B\u6F88\u90F4\u81E3\u8FB0\u5C18\u6668\u5FF1\u6C89\u9648\u8D81\u886C\u6491\u79F0\u57CE\u6A59\u6210\u5448\u4E58\u7A0B\u60E9\u6F84\u8BDA\u627F\u901E\u9A8B\u79E4\u5403\u75F4\u6301\u5319\u6C60\u8FDF\u5F1B\u9A70\u803B\u9F7F\u4F88\u5C3A\u8D64\u7FC5\u65A5\u70BD\u5145\u51B2\u866B\u5D07\u5BA0\u62BD\u916C\u7574\u8E0C\u7A20\u6101\u7B79\u4EC7\u7EF8\u7785\u4E11\u81ED\u521D\u51FA\u6A71\u53A8\u8E87\u9504\u96CF\u6EC1\u9664\u695A"], - ["b440", "\u7884\u7885\u7886\u7888\u788A\u788B\u788F\u7890\u7892\u7894\u7895\u7896\u7899\u789D\u789E\u78A0\u78A2\u78A4\u78A6\u78A8", 7, "\u78B5\u78B6\u78B7\u78B8\u78BA\u78BB\u78BC\u78BD\u78BF\u78C0\u78C2\u78C3\u78C4\u78C6\u78C7\u78C8\u78CC\u78CD\u78CE\u78CF\u78D1\u78D2\u78D3\u78D6\u78D7\u78D8\u78DA", 9], - ["b480", "\u78E4\u78E5\u78E6\u78E7\u78E9\u78EA\u78EB\u78ED", 4, "\u78F3\u78F5\u78F6\u78F8\u78F9\u78FB", 5, "\u7902\u7903\u7904\u7906", 6, "\u7840\u50A8\u77D7\u6410\u89E6\u5904\u63E3\u5DDD\u7A7F\u693D\u4F20\u8239\u5598\u4E32\u75AE\u7A97\u5E62\u5E8A\u95EF\u521B\u5439\u708A\u6376\u9524\u5782\u6625\u693F\u9187\u5507\u6DF3\u7EAF\u8822\u6233\u7EF0\u75B5\u8328\u78C1\u96CC\u8F9E\u6148\u74F7\u8BCD\u6B64\u523A\u8D50\u6B21\u806A\u8471\u56F1\u5306\u4ECE\u4E1B\u51D1\u7C97\u918B\u7C07\u4FC3\u8E7F\u7BE1\u7A9C\u6467\u5D14\u50AC\u8106\u7601\u7CB9\u6DEC\u7FE0\u6751\u5B58\u5BF8\u78CB\u64AE\u6413\u63AA\u632B\u9519\u642D\u8FBE\u7B54\u7629\u6253\u5927\u5446\u6B79\u50A3\u6234\u5E26\u6B86\u4EE3\u8D37\u888B\u5F85\u902E"], - ["b540", "\u790D", 5, "\u7914", 9, "\u791F", 4, "\u7925", 14, "\u7935", 4, "\u793D\u793F\u7942\u7943\u7944\u7945\u7947\u794A", 8, "\u7954\u7955\u7958\u7959\u7961\u7963"], - ["b580", "\u7964\u7966\u7969\u796A\u796B\u796C\u796E\u7970", 6, "\u7979\u797B", 4, "\u7982\u7983\u7986\u7987\u7988\u7989\u798B\u798C\u798D\u798E\u7990\u7991\u7992\u6020\u803D\u62C5\u4E39\u5355\u90F8\u63B8\u80C6\u65E6\u6C2E\u4F46\u60EE\u6DE1\u8BDE\u5F39\u86CB\u5F53\u6321\u515A\u8361\u6863\u5200\u6363\u8E48\u5012\u5C9B\u7977\u5BFC\u5230\u7A3B\u60BC\u9053\u76D7\u5FB7\u5F97\u7684\u8E6C\u706F\u767B\u7B49\u77AA\u51F3\u9093\u5824\u4F4E\u6EF4\u8FEA\u654C\u7B1B\u72C4\u6DA4\u7FDF\u5AE1\u62B5\u5E95\u5730\u8482\u7B2C\u5E1D\u5F1F\u9012\u7F14\u98A0\u6382\u6EC7\u7898\u70B9\u5178\u975B\u57AB\u7535\u4F43\u7538\u5E97\u60E6\u5960\u6DC0\u6BBF\u7889\u53FC\u96D5\u51CB\u5201\u6389\u540A\u9493\u8C03\u8DCC\u7239\u789F\u8776\u8FED\u8C0D\u53E0"], - ["b640", "\u7993", 6, "\u799B", 11, "\u79A8", 10, "\u79B4", 4, "\u79BC\u79BF\u79C2\u79C4\u79C5\u79C7\u79C8\u79CA\u79CC\u79CE\u79CF\u79D0\u79D3\u79D4\u79D6\u79D7\u79D9", 5, "\u79E0\u79E1\u79E2\u79E5\u79E8\u79EA"], - ["b680", "\u79EC\u79EE\u79F1", 6, "\u79F9\u79FA\u79FC\u79FE\u79FF\u7A01\u7A04\u7A05\u7A07\u7A08\u7A09\u7A0A\u7A0C\u7A0F", 4, "\u7A15\u7A16\u7A18\u7A19\u7A1B\u7A1C\u4E01\u76EF\u53EE\u9489\u9876\u9F0E\u952D\u5B9A\u8BA2\u4E22\u4E1C\u51AC\u8463\u61C2\u52A8\u680B\u4F97\u606B\u51BB\u6D1E\u515C\u6296\u6597\u9661\u8C46\u9017\u75D8\u90FD\u7763\u6BD2\u728A\u72EC\u8BFB\u5835\u7779\u8D4C\u675C\u9540\u809A\u5EA6\u6E21\u5992\u7AEF\u77ED\u953B\u6BB5\u65AD\u7F0E\u5806\u5151\u961F\u5BF9\u58A9\u5428\u8E72\u6566\u987F\u56E4\u949D\u76FE\u9041\u6387\u54C6\u591A\u593A\u579B\u8EB2\u6735\u8DFA\u8235\u5241\u60F0\u5815\u86FE\u5CE8\u9E45\u4FC4\u989D\u8BB9\u5A25\u6076\u5384\u627C\u904F\u9102\u997F\u6069\u800C\u513F\u8033\u5C14\u9975\u6D31\u4E8C"], - ["b740", "\u7A1D\u7A1F\u7A21\u7A22\u7A24", 14, "\u7A34\u7A35\u7A36\u7A38\u7A3A\u7A3E\u7A40", 5, "\u7A47", 9, "\u7A52", 4, "\u7A58", 16], - ["b780", "\u7A69", 6, "\u7A71\u7A72\u7A73\u7A75\u7A7B\u7A7C\u7A7D\u7A7E\u7A82\u7A85\u7A87\u7A89\u7A8A\u7A8B\u7A8C\u7A8E\u7A8F\u7A90\u7A93\u7A94\u7A99\u7A9A\u7A9B\u7A9E\u7AA1\u7AA2\u8D30\u53D1\u7F5A\u7B4F\u4F10\u4E4F\u9600\u6CD5\u73D0\u85E9\u5E06\u756A\u7FFB\u6A0A\u77FE\u9492\u7E41\u51E1\u70E6\u53CD\u8FD4\u8303\u8D29\u72AF\u996D\u6CDB\u574A\u82B3\u65B9\u80AA\u623F\u9632\u59A8\u4EFF\u8BBF\u7EBA\u653E\u83F2\u975E\u5561\u98DE\u80A5\u532A\u8BFD\u5420\u80BA\u5E9F\u6CB8\u8D39\u82AC\u915A\u5429\u6C1B\u5206\u7EB7\u575F\u711A\u6C7E\u7C89\u594B\u4EFD\u5FFF\u6124\u7CAA\u4E30\u5C01\u67AB\u8702\u5CF0\u950B\u98CE\u75AF\u70FD\u9022\u51AF\u7F1D\u8BBD\u5949\u51E4\u4F5B\u5426\u592B\u6577\u80A4\u5B75\u6276\u62C2\u8F90\u5E45\u6C1F\u7B26\u4F0F\u4FD8\u670D"], - ["b840", "\u7AA3\u7AA4\u7AA7\u7AA9\u7AAA\u7AAB\u7AAE", 4, "\u7AB4", 10, "\u7AC0", 10, "\u7ACC", 9, "\u7AD7\u7AD8\u7ADA\u7ADB\u7ADC\u7ADD\u7AE1\u7AE2\u7AE4\u7AE7", 5, "\u7AEE\u7AF0\u7AF1\u7AF2\u7AF3"], - ["b880", "\u7AF4", 4, "\u7AFB\u7AFC\u7AFE\u7B00\u7B01\u7B02\u7B05\u7B07\u7B09\u7B0C\u7B0D\u7B0E\u7B10\u7B12\u7B13\u7B16\u7B17\u7B18\u7B1A\u7B1C\u7B1D\u7B1F\u7B21\u7B22\u7B23\u7B27\u7B29\u7B2D\u6D6E\u6DAA\u798F\u88B1\u5F17\u752B\u629A\u8F85\u4FEF\u91DC\u65A7\u812F\u8151\u5E9C\u8150\u8D74\u526F\u8986\u8D4B\u590D\u5085\u4ED8\u961C\u7236\u8179\u8D1F\u5BCC\u8BA3\u9644\u5987\u7F1A\u5490\u5676\u560E\u8BE5\u6539\u6982\u9499\u76D6\u6E89\u5E72\u7518\u6746\u67D1\u7AFF\u809D\u8D76\u611F\u79C6\u6562\u8D63\u5188\u521A\u94A2\u7F38\u809B\u7EB2\u5C97\u6E2F\u6760\u7BD9\u768B\u9AD8\u818F\u7F94\u7CD5\u641E\u9550\u7A3F\u544A\u54E5\u6B4C\u6401\u6208\u9E3D\u80F3\u7599\u5272\u9769\u845B\u683C\u86E4\u9601\u9694\u94EC\u4E2A\u5404\u7ED9\u6839\u8DDF\u8015\u66F4\u5E9A\u7FB9"], - ["b940", "\u7B2F\u7B30\u7B32\u7B34\u7B35\u7B36\u7B37\u7B39\u7B3B\u7B3D\u7B3F", 5, "\u7B46\u7B48\u7B4A\u7B4D\u7B4E\u7B53\u7B55\u7B57\u7B59\u7B5C\u7B5E\u7B5F\u7B61\u7B63", 10, "\u7B6F\u7B70\u7B73\u7B74\u7B76\u7B78\u7B7A\u7B7C\u7B7D\u7B7F\u7B81\u7B82\u7B83\u7B84\u7B86", 6, "\u7B8E\u7B8F"], - ["b980", "\u7B91\u7B92\u7B93\u7B96\u7B98\u7B99\u7B9A\u7B9B\u7B9E\u7B9F\u7BA0\u7BA3\u7BA4\u7BA5\u7BAE\u7BAF\u7BB0\u7BB2\u7BB3\u7BB5\u7BB6\u7BB7\u7BB9", 7, "\u7BC2\u7BC3\u7BC4\u57C2\u803F\u6897\u5DE5\u653B\u529F\u606D\u9F9A\u4F9B\u8EAC\u516C\u5BAB\u5F13\u5DE9\u6C5E\u62F1\u8D21\u5171\u94A9\u52FE\u6C9F\u82DF\u72D7\u57A2\u6784\u8D2D\u591F\u8F9C\u83C7\u5495\u7B8D\u4F30\u6CBD\u5B64\u59D1\u9F13\u53E4\u86CA\u9AA8\u8C37\u80A1\u6545\u987E\u56FA\u96C7\u522E\u74DC\u5250\u5BE1\u6302\u8902\u4E56\u62D0\u602A\u68FA\u5173\u5B98\u51A0\u89C2\u7BA1\u9986\u7F50\u60EF\u704C\u8D2F\u5149\u5E7F\u901B\u7470\u89C4\u572D\u7845\u5F52\u9F9F\u95FA\u8F68\u9B3C\u8BE1\u7678\u6842\u67DC\u8DEA\u8D35\u523D\u8F8A\u6EDA\u68CD\u9505\u90ED\u56FD\u679C\u88F9\u8FC7\u54C8"], - ["ba40", "\u7BC5\u7BC8\u7BC9\u7BCA\u7BCB\u7BCD\u7BCE\u7BCF\u7BD0\u7BD2\u7BD4", 4, "\u7BDB\u7BDC\u7BDE\u7BDF\u7BE0\u7BE2\u7BE3\u7BE4\u7BE7\u7BE8\u7BE9\u7BEB\u7BEC\u7BED\u7BEF\u7BF0\u7BF2", 4, "\u7BF8\u7BF9\u7BFA\u7BFB\u7BFD\u7BFF", 7, "\u7C08\u7C09\u7C0A\u7C0D\u7C0E\u7C10", 5, "\u7C17\u7C18\u7C19"], - ["ba80", "\u7C1A", 4, "\u7C20", 5, "\u7C28\u7C29\u7C2B", 12, "\u7C39", 5, "\u7C42\u9AB8\u5B69\u6D77\u6C26\u4EA5\u5BB3\u9A87\u9163\u61A8\u90AF\u97E9\u542B\u6DB5\u5BD2\u51FD\u558A\u7F55\u7FF0\u64BC\u634D\u65F1\u61BE\u608D\u710A\u6C57\u6C49\u592F\u676D\u822A\u58D5\u568E\u8C6A\u6BEB\u90DD\u597D\u8017\u53F7\u6D69\u5475\u559D\u8377\u83CF\u6838\u79BE\u548C\u4F55\u5408\u76D2\u8C89\u9602\u6CB3\u6DB8\u8D6B\u8910\u9E64\u8D3A\u563F\u9ED1\u75D5\u5F88\u72E0\u6068\u54FC\u4EA8\u6A2A\u8861\u6052\u8F70\u54C4\u70D8\u8679\u9E3F\u6D2A\u5B8F\u5F18\u7EA2\u5589\u4FAF\u7334\u543C\u539A\u5019\u540E\u547C\u4E4E\u5FFD\u745A\u58F6\u846B\u80E1\u8774\u72D0\u7CCA\u6E56"], - ["bb40", "\u7C43", 9, "\u7C4E", 36, "\u7C75", 5, "\u7C7E", 9], - ["bb80", "\u7C88\u7C8A", 6, "\u7C93\u7C94\u7C96\u7C99\u7C9A\u7C9B\u7CA0\u7CA1\u7CA3\u7CA6\u7CA7\u7CA8\u7CA9\u7CAB\u7CAC\u7CAD\u7CAF\u7CB0\u7CB4", 4, "\u7CBA\u7CBB\u5F27\u864E\u552C\u62A4\u4E92\u6CAA\u6237\u82B1\u54D7\u534E\u733E\u6ED1\u753B\u5212\u5316\u8BDD\u69D0\u5F8A\u6000\u6DEE\u574F\u6B22\u73AF\u6853\u8FD8\u7F13\u6362\u60A3\u5524\u75EA\u8C62\u7115\u6DA3\u5BA6\u5E7B\u8352\u614C\u9EC4\u78FA\u8757\u7C27\u7687\u51F0\u60F6\u714C\u6643\u5E4C\u604D\u8C0E\u7070\u6325\u8F89\u5FBD\u6062\u86D4\u56DE\u6BC1\u6094\u6167\u5349\u60E0\u6666\u8D3F\u79FD\u4F1A\u70E9\u6C47\u8BB3\u8BF2\u7ED8\u8364\u660F\u5A5A\u9B42\u6D51\u6DF7\u8C41\u6D3B\u4F19\u706B\u83B7\u6216\u60D1\u970D\u8D27\u7978\u51FB\u573E\u57FA\u673A\u7578\u7A3D\u79EF\u7B95"], - ["bc40", "\u7CBF\u7CC0\u7CC2\u7CC3\u7CC4\u7CC6\u7CC9\u7CCB\u7CCE", 6, "\u7CD8\u7CDA\u7CDB\u7CDD\u7CDE\u7CE1", 6, "\u7CE9", 5, "\u7CF0", 7, "\u7CF9\u7CFA\u7CFC", 13, "\u7D0B", 5], - ["bc80", "\u7D11", 14, "\u7D21\u7D23\u7D24\u7D25\u7D26\u7D28\u7D29\u7D2A\u7D2C\u7D2D\u7D2E\u7D30", 6, "\u808C\u9965\u8FF9\u6FC0\u8BA5\u9E21\u59EC\u7EE9\u7F09\u5409\u6781\u68D8\u8F91\u7C4D\u96C6\u53CA\u6025\u75BE\u6C72\u5373\u5AC9\u7EA7\u6324\u51E0\u810A\u5DF1\u84DF\u6280\u5180\u5B63\u4F0E\u796D\u5242\u60B8\u6D4E\u5BC4\u5BC2\u8BA1\u8BB0\u65E2\u5FCC\u9645\u5993\u7EE7\u7EAA\u5609\u67B7\u5939\u4F73\u5BB6\u52A0\u835A\u988A\u8D3E\u7532\u94BE\u5047\u7A3C\u4EF7\u67B6\u9A7E\u5AC1\u6B7C\u76D1\u575A\u5C16\u7B3A\u95F4\u714E\u517C\u80A9\u8270\u5978\u7F04\u8327\u68C0\u67EC\u78B1\u7877\u62E3\u6361\u7B80\u4FED\u526A\u51CF\u8350\u69DB\u9274\u8DF5\u8D31\u89C1\u952E\u7BAD\u4EF6"], - ["bd40", "\u7D37", 54, "\u7D6F", 7], - ["bd80", "\u7D78", 32, "\u5065\u8230\u5251\u996F\u6E10\u6E85\u6DA7\u5EFA\u50F5\u59DC\u5C06\u6D46\u6C5F\u7586\u848B\u6868\u5956\u8BB2\u5320\u9171\u964D\u8549\u6912\u7901\u7126\u80F6\u4EA4\u90CA\u6D47\u9A84\u5A07\u56BC\u6405\u94F0\u77EB\u4FA5\u811A\u72E1\u89D2\u997A\u7F34\u7EDE\u527F\u6559\u9175\u8F7F\u8F83\u53EB\u7A96\u63ED\u63A5\u7686\u79F8\u8857\u9636\u622A\u52AB\u8282\u6854\u6770\u6377\u776B\u7AED\u6D01\u7ED3\u89E3\u59D0\u6212\u85C9\u82A5\u754C\u501F\u4ECB\u75A5\u8BEB\u5C4A\u5DFE\u7B4B\u65A4\u91D1\u4ECA\u6D25\u895F\u7D27\u9526\u4EC5\u8C28\u8FDB\u9773\u664B\u7981\u8FD1\u70EC\u6D78"], - ["be40", "\u7D99", 12, "\u7DA7", 6, "\u7DAF", 42], - ["be80", "\u7DDA", 32, "\u5C3D\u52B2\u8346\u5162\u830E\u775B\u6676\u9CB8\u4EAC\u60CA\u7CBE\u7CB3\u7ECF\u4E95\u8B66\u666F\u9888\u9759\u5883\u656C\u955C\u5F84\u75C9\u9756\u7ADF\u7ADE\u51C0\u70AF\u7A98\u63EA\u7A76\u7EA0\u7396\u97ED\u4E45\u7078\u4E5D\u9152\u53A9\u6551\u65E7\u81FC\u8205\u548E\u5C31\u759A\u97A0\u62D8\u72D9\u75BD\u5C45\u9A79\u83CA\u5C40\u5480\u77E9\u4E3E\u6CAE\u805A\u62D2\u636E\u5DE8\u5177\u8DDD\u8E1E\u952F\u4FF1\u53E5\u60E7\u70AC\u5267\u6350\u9E43\u5A1F\u5026\u7737\u5377\u7EE2\u6485\u652B\u6289\u6398\u5014\u7235\u89C9\u51B3\u8BC0\u7EDD\u5747\u83CC\u94A7\u519B\u541B\u5CFB"], - ["bf40", "\u7DFB", 62], - ["bf80", "\u7E3A\u7E3C", 4, "\u7E42", 4, "\u7E48", 21, "\u4FCA\u7AE3\u6D5A\u90E1\u9A8F\u5580\u5496\u5361\u54AF\u5F00\u63E9\u6977\u51EF\u6168\u520A\u582A\u52D8\u574E\u780D\u770B\u5EB7\u6177\u7CE0\u625B\u6297\u4EA2\u7095\u8003\u62F7\u70E4\u9760\u5777\u82DB\u67EF\u68F5\u78D5\u9897\u79D1\u58F3\u54B3\u53EF\u6E34\u514B\u523B\u5BA2\u8BFE\u80AF\u5543\u57A6\u6073\u5751\u542D\u7A7A\u6050\u5B54\u63A7\u62A0\u53E3\u6263\u5BC7\u67AF\u54ED\u7A9F\u82E6\u9177\u5E93\u88E4\u5938\u57AE\u630E\u8DE8\u80EF\u5757\u7B77\u4FA9\u5FEB\u5BBD\u6B3E\u5321\u7B50\u72C2\u6846\u77FF\u7736\u65F7\u51B5\u4E8F\u76D4\u5CBF\u7AA5\u8475\u594E\u9B41\u5080"], - ["c040", "\u7E5E", 35, "\u7E83", 23, "\u7E9C\u7E9D\u7E9E"], - ["c080", "\u7EAE\u7EB4\u7EBB\u7EBC\u7ED6\u7EE4\u7EEC\u7EF9\u7F0A\u7F10\u7F1E\u7F37\u7F39\u7F3B", 6, "\u7F43\u7F46", 9, "\u7F52\u7F53\u9988\u6127\u6E83\u5764\u6606\u6346\u56F0\u62EC\u6269\u5ED3\u9614\u5783\u62C9\u5587\u8721\u814A\u8FA3\u5566\u83B1\u6765\u8D56\u84DD\u5A6A\u680F\u62E6\u7BEE\u9611\u5170\u6F9C\u8C30\u63FD\u89C8\u61D2\u7F06\u70C2\u6EE5\u7405\u6994\u72FC\u5ECA\u90CE\u6717\u6D6A\u635E\u52B3\u7262\u8001\u4F6C\u59E5\u916A\u70D9\u6D9D\u52D2\u4E50\u96F7\u956D\u857E\u78CA\u7D2F\u5121\u5792\u64C2\u808B\u7C7B\u6CEA\u68F1\u695E\u51B7\u5398\u68A8\u7281\u9ECE\u7BF1\u72F8\u79BB\u6F13\u7406\u674E\u91CC\u9CA4\u793C\u8389\u8354\u540F\u6817\u4E3D\u5389\u52B1\u783E\u5386\u5229\u5088\u4F8B\u4FD0"], - ["c140", "\u7F56\u7F59\u7F5B\u7F5C\u7F5D\u7F5E\u7F60\u7F63", 4, "\u7F6B\u7F6C\u7F6D\u7F6F\u7F70\u7F73\u7F75\u7F76\u7F77\u7F78\u7F7A\u7F7B\u7F7C\u7F7D\u7F7F\u7F80\u7F82", 7, "\u7F8B\u7F8D\u7F8F", 4, "\u7F95", 4, "\u7F9B\u7F9C\u7FA0\u7FA2\u7FA3\u7FA5\u7FA6\u7FA8", 6, "\u7FB1"], - ["c180", "\u7FB3", 4, "\u7FBA\u7FBB\u7FBE\u7FC0\u7FC2\u7FC3\u7FC4\u7FC6\u7FC7\u7FC8\u7FC9\u7FCB\u7FCD\u7FCF", 4, "\u7FD6\u7FD7\u7FD9", 5, "\u7FE2\u7FE3\u75E2\u7ACB\u7C92\u6CA5\u96B6\u529B\u7483\u54E9\u4FE9\u8054\u83B2\u8FDE\u9570\u5EC9\u601C\u6D9F\u5E18\u655B\u8138\u94FE\u604B\u70BC\u7EC3\u7CAE\u51C9\u6881\u7CB1\u826F\u4E24\u8F86\u91CF\u667E\u4EAE\u8C05\u64A9\u804A\u50DA\u7597\u71CE\u5BE5\u8FBD\u6F66\u4E86\u6482\u9563\u5ED6\u6599\u5217\u88C2\u70C8\u52A3\u730E\u7433\u6797\u78F7\u9716\u4E34\u90BB\u9CDE\u6DCB\u51DB\u8D41\u541D\u62CE\u73B2\u83F1\u96F6\u9F84\u94C3\u4F36\u7F9A\u51CC\u7075\u9675\u5CAD\u9886\u53E6\u4EE4\u6E9C\u7409\u69B4\u786B\u998F\u7559\u5218\u7624\u6D41\u67F3\u516D\u9F99\u804B\u5499\u7B3C\u7ABF"], - ["c240", "\u7FE4\u7FE7\u7FE8\u7FEA\u7FEB\u7FEC\u7FED\u7FEF\u7FF2\u7FF4", 6, "\u7FFD\u7FFE\u7FFF\u8002\u8007\u8008\u8009\u800A\u800E\u800F\u8011\u8013\u801A\u801B\u801D\u801E\u801F\u8021\u8023\u8024\u802B", 5, "\u8032\u8034\u8039\u803A\u803C\u803E\u8040\u8041\u8044\u8045\u8047\u8048\u8049\u804E\u804F\u8050\u8051\u8053\u8055\u8056\u8057"], - ["c280", "\u8059\u805B", 13, "\u806B", 5, "\u8072", 11, "\u9686\u5784\u62E2\u9647\u697C\u5A04\u6402\u7BD3\u6F0F\u964B\u82A6\u5362\u9885\u5E90\u7089\u63B3\u5364\u864F\u9C81\u9E93\u788C\u9732\u8DEF\u8D42\u9E7F\u6F5E\u7984\u5F55\u9646\u622E\u9A74\u5415\u94DD\u4FA3\u65C5\u5C65\u5C61\u7F15\u8651\u6C2F\u5F8B\u7387\u6EE4\u7EFF\u5CE6\u631B\u5B6A\u6EE6\u5375\u4E71\u63A0\u7565\u62A1\u8F6E\u4F26\u4ED1\u6CA6\u7EB6\u8BBA\u841D\u87BA\u7F57\u903B\u9523\u7BA9\u9AA1\u88F8\u843D\u6D1B\u9A86\u7EDC\u5988\u9EBB\u739B\u7801\u8682\u9A6C\u9A82\u561B\u5417\u57CB\u4E70\u9EA6\u5356\u8FC8\u8109\u7792\u9992\u86EE\u6EE1\u8513\u66FC\u6162\u6F2B"], - ["c340", "\u807E\u8081\u8082\u8085\u8088\u808A\u808D", 5, "\u8094\u8095\u8097\u8099\u809E\u80A3\u80A6\u80A7\u80A8\u80AC\u80B0\u80B3\u80B5\u80B6\u80B8\u80B9\u80BB\u80C5\u80C7", 4, "\u80CF", 6, "\u80D8\u80DF\u80E0\u80E2\u80E3\u80E6\u80EE\u80F5\u80F7\u80F9\u80FB\u80FE\u80FF\u8100\u8101\u8103\u8104\u8105\u8107\u8108\u810B"], - ["c380", "\u810C\u8115\u8117\u8119\u811B\u811C\u811D\u811F", 12, "\u812D\u812E\u8130\u8133\u8134\u8135\u8137\u8139", 4, "\u813F\u8C29\u8292\u832B\u76F2\u6C13\u5FD9\u83BD\u732B\u8305\u951A\u6BDB\u77DB\u94C6\u536F\u8302\u5192\u5E3D\u8C8C\u8D38\u4E48\u73AB\u679A\u6885\u9176\u9709\u7164\u6CA1\u7709\u5A92\u9541\u6BCF\u7F8E\u6627\u5BD0\u59B9\u5A9A\u95E8\u95F7\u4EEC\u840C\u8499\u6AAC\u76DF\u9530\u731B\u68A6\u5B5F\u772F\u919A\u9761\u7CDC\u8FF7\u8C1C\u5F25\u7C73\u79D8\u89C5\u6CCC\u871C\u5BC6\u5E42\u68C9\u7720\u7EF5\u5195\u514D\u52C9\u5A29\u7F05\u9762\u82D7\u63CF\u7784\u85D0\u79D2\u6E3A\u5E99\u5999\u8511\u706D\u6C11\u62BF\u76BF\u654F\u60AF\u95FD\u660E\u879F\u9E23\u94ED\u540D\u547D\u8C2C\u6478"], - ["c440", "\u8140", 5, "\u8147\u8149\u814D\u814E\u814F\u8152\u8156\u8157\u8158\u815B", 4, "\u8161\u8162\u8163\u8164\u8166\u8168\u816A\u816B\u816C\u816F\u8172\u8173\u8175\u8176\u8177\u8178\u8181\u8183", 4, "\u8189\u818B\u818C\u818D\u818E\u8190\u8192", 5, "\u8199\u819A\u819E", 4, "\u81A4\u81A5"], - ["c480", "\u81A7\u81A9\u81AB", 7, "\u81B4", 5, "\u81BC\u81BD\u81BE\u81BF\u81C4\u81C5\u81C7\u81C8\u81C9\u81CB\u81CD", 6, "\u6479\u8611\u6A21\u819C\u78E8\u6469\u9B54\u62B9\u672B\u83AB\u58A8\u9ED8\u6CAB\u6F20\u5BDE\u964C\u8C0B\u725F\u67D0\u62C7\u7261\u4EA9\u59C6\u6BCD\u5893\u66AE\u5E55\u52DF\u6155\u6728\u76EE\u7766\u7267\u7A46\u62FF\u54EA\u5450\u94A0\u90A3\u5A1C\u7EB3\u6C16\u4E43\u5976\u8010\u5948\u5357\u7537\u96BE\u56CA\u6320\u8111\u607C\u95F9\u6DD6\u5462\u9981\u5185\u5AE9\u80FD\u59AE\u9713\u502A\u6CE5\u5C3C\u62DF\u4F60\u533F\u817B\u9006\u6EBA\u852B\u62C8\u5E74\u78BE\u64B5\u637B\u5FF5\u5A18\u917F\u9E1F\u5C3F\u634F\u8042\u5B7D\u556E\u954A\u954D\u6D85\u60A8\u67E0\u72DE\u51DD\u5B81"], - ["c540", "\u81D4", 14, "\u81E4\u81E5\u81E6\u81E8\u81E9\u81EB\u81EE", 4, "\u81F5", 5, "\u81FD\u81FF\u8203\u8207", 4, "\u820E\u820F\u8211\u8213\u8215", 5, "\u821D\u8220\u8224\u8225\u8226\u8227\u8229\u822E\u8232\u823A\u823C\u823D\u823F"], - ["c580", "\u8240\u8241\u8242\u8243\u8245\u8246\u8248\u824A\u824C\u824D\u824E\u8250", 7, "\u8259\u825B\u825C\u825D\u825E\u8260", 7, "\u8269\u62E7\u6CDE\u725B\u626D\u94AE\u7EBD\u8113\u6D53\u519C\u5F04\u5974\u52AA\u6012\u5973\u6696\u8650\u759F\u632A\u61E6\u7CEF\u8BFA\u54E6\u6B27\u9E25\u6BB4\u85D5\u5455\u5076\u6CA4\u556A\u8DB4\u722C\u5E15\u6015\u7436\u62CD\u6392\u724C\u5F98\u6E43\u6D3E\u6500\u6F58\u76D8\u78D0\u76FC\u7554\u5224\u53DB\u4E53\u5E9E\u65C1\u802A\u80D6\u629B\u5486\u5228\u70AE\u888D\u8DD1\u6CE1\u5478\u80DA\u57F9\u88F4\u8D54\u966A\u914D\u4F69\u6C9B\u55B7\u76C6\u7830\u62A8\u70F9\u6F8E\u5F6D\u84EC\u68DA\u787C\u7BF7\u81A8\u670B\u9E4F\u6367\u78B0\u576F\u7812\u9739\u6279\u62AB\u5288\u7435\u6BD7"], - ["c640", "\u826A\u826B\u826C\u826D\u8271\u8275\u8276\u8277\u8278\u827B\u827C\u8280\u8281\u8283\u8285\u8286\u8287\u8289\u828C\u8290\u8293\u8294\u8295\u8296\u829A\u829B\u829E\u82A0\u82A2\u82A3\u82A7\u82B2\u82B5\u82B6\u82BA\u82BB\u82BC\u82BF\u82C0\u82C2\u82C3\u82C5\u82C6\u82C9\u82D0\u82D6\u82D9\u82DA\u82DD\u82E2\u82E7\u82E8\u82E9\u82EA\u82EC\u82ED\u82EE\u82F0\u82F2\u82F3\u82F5\u82F6\u82F8"], - ["c680", "\u82FA\u82FC", 4, "\u830A\u830B\u830D\u8310\u8312\u8313\u8316\u8318\u8319\u831D", 9, "\u8329\u832A\u832E\u8330\u8332\u8337\u833B\u833D\u5564\u813E\u75B2\u76AE\u5339\u75DE\u50FB\u5C41\u8B6C\u7BC7\u504F\u7247\u9A97\u98D8\u6F02\u74E2\u7968\u6487\u77A5\u62FC\u9891\u8D2B\u54C1\u8058\u4E52\u576A\u82F9\u840D\u5E73\u51ED\u74F6\u8BC4\u5C4F\u5761\u6CFC\u9887\u5A46\u7834\u9B44\u8FEB\u7C95\u5256\u6251\u94FA\u4EC6\u8386\u8461\u83E9\u84B2\u57D4\u6734\u5703\u666E\u6D66\u8C31\u66DD\u7011\u671F\u6B3A\u6816\u621A\u59BB\u4E03\u51C4\u6F06\u67D2\u6C8F\u5176\u68CB\u5947\u6B67\u7566\u5D0E\u8110\u9F50\u65D7\u7948\u7941\u9A91\u8D77\u5C82\u4E5E\u4F01\u542F\u5951\u780C\u5668\u6C14\u8FC4\u5F03\u6C7D\u6CE3\u8BAB\u6390"], - ["c740", "\u833E\u833F\u8341\u8342\u8344\u8345\u8348\u834A", 4, "\u8353\u8355", 4, "\u835D\u8362\u8370", 6, "\u8379\u837A\u837E", 6, "\u8387\u8388\u838A\u838B\u838C\u838D\u838F\u8390\u8391\u8394\u8395\u8396\u8397\u8399\u839A\u839D\u839F\u83A1", 6, "\u83AC\u83AD\u83AE"], - ["c780", "\u83AF\u83B5\u83BB\u83BE\u83BF\u83C2\u83C3\u83C4\u83C6\u83C8\u83C9\u83CB\u83CD\u83CE\u83D0\u83D1\u83D2\u83D3\u83D5\u83D7\u83D9\u83DA\u83DB\u83DE\u83E2\u83E3\u83E4\u83E6\u83E7\u83E8\u83EB\u83EC\u83ED\u6070\u6D3D\u7275\u6266\u948E\u94C5\u5343\u8FC1\u7B7E\u4EDF\u8C26\u4E7E\u9ED4\u94B1\u94B3\u524D\u6F5C\u9063\u6D45\u8C34\u5811\u5D4C\u6B20\u6B49\u67AA\u545B\u8154\u7F8C\u5899\u8537\u5F3A\u62A2\u6A47\u9539\u6572\u6084\u6865\u77A7\u4E54\u4FA8\u5DE7\u9798\u64AC\u7FD8\u5CED\u4FCF\u7A8D\u5207\u8304\u4E14\u602F\u7A83\u94A6\u4FB5\u4EB2\u79E6\u7434\u52E4\u82B9\u64D2\u79BD\u5BDD\u6C81\u9752\u8F7B\u6C22\u503E\u537F\u6E05\u64CE\u6674\u6C30\u60C5\u9877\u8BF7\u5E86\u743C\u7A77\u79CB\u4E18\u90B1\u7403\u6C42\u56DA\u914B\u6CC5\u8D8B\u533A\u86C6\u66F2\u8EAF\u5C48\u9A71\u6E20"], - ["c840", "\u83EE\u83EF\u83F3", 4, "\u83FA\u83FB\u83FC\u83FE\u83FF\u8400\u8402\u8405\u8407\u8408\u8409\u840A\u8410\u8412", 5, "\u8419\u841A\u841B\u841E", 5, "\u8429", 7, "\u8432", 5, "\u8439\u843A\u843B\u843E", 7, "\u8447\u8448\u8449"], - ["c880", "\u844A", 6, "\u8452", 4, "\u8458\u845D\u845E\u845F\u8460\u8462\u8464", 4, "\u846A\u846E\u846F\u8470\u8472\u8474\u8477\u8479\u847B\u847C\u53D6\u5A36\u9F8B\u8DA3\u53BB\u5708\u98A7\u6743\u919B\u6CC9\u5168\u75CA\u62F3\u72AC\u5238\u529D\u7F3A\u7094\u7638\u5374\u9E4A\u69B7\u786E\u96C0\u88D9\u7FA4\u7136\u71C3\u5189\u67D3\u74E4\u58E4\u6518\u56B7\u8BA9\u9976\u6270\u7ED5\u60F9\u70ED\u58EC\u4EC1\u4EBA\u5FCD\u97E7\u4EFB\u8BA4\u5203\u598A\u7EAB\u6254\u4ECD\u65E5\u620E\u8338\u84C9\u8363\u878D\u7194\u6EB6\u5BB9\u7ED2\u5197\u63C9\u67D4\u8089\u8339\u8815\u5112\u5B7A\u5982\u8FB1\u4E73\u6C5D\u5165\u8925\u8F6F\u962E\u854A\u745E\u9510\u95F0\u6DA6\u82E5\u5F31\u6492\u6D12\u8428\u816E\u9CC3\u585E\u8D5B\u4E09\u53C1"], - ["c940", "\u847D", 4, "\u8483\u8484\u8485\u8486\u848A\u848D\u848F", 7, "\u8498\u849A\u849B\u849D\u849E\u849F\u84A0\u84A2", 12, "\u84B0\u84B1\u84B3\u84B5\u84B6\u84B7\u84BB\u84BC\u84BE\u84C0\u84C2\u84C3\u84C5\u84C6\u84C7\u84C8\u84CB\u84CC\u84CE\u84CF\u84D2\u84D4\u84D5\u84D7"], - ["c980", "\u84D8", 4, "\u84DE\u84E1\u84E2\u84E4\u84E7", 4, "\u84ED\u84EE\u84EF\u84F1", 10, "\u84FD\u84FE\u8500\u8501\u8502\u4F1E\u6563\u6851\u55D3\u4E27\u6414\u9A9A\u626B\u5AC2\u745F\u8272\u6DA9\u68EE\u50E7\u838E\u7802\u6740\u5239\u6C99\u7EB1\u50BB\u5565\u715E\u7B5B\u6652\u73CA\u82EB\u6749\u5C71\u5220\u717D\u886B\u95EA\u9655\u64C5\u8D61\u81B3\u5584\u6C55\u6247\u7F2E\u5892\u4F24\u5546\u8D4F\u664C\u4E0A\u5C1A\u88F3\u68A2\u634E\u7A0D\u70E7\u828D\u52FA\u97F6\u5C11\u54E8\u90B5\u7ECD\u5962\u8D4A\u86C7\u820C\u820D\u8D66\u6444\u5C04\u6151\u6D89\u793E\u8BBE\u7837\u7533\u547B\u4F38\u8EAB\u6DF1\u5A20\u7EC5\u795E\u6C88\u5BA1\u5A76\u751A\u80BE\u614E\u6E17\u58F0\u751F\u7525\u7272\u5347\u7EF3"], - ["ca40", "\u8503", 8, "\u850D\u850E\u850F\u8510\u8512\u8514\u8515\u8516\u8518\u8519\u851B\u851C\u851D\u851E\u8520\u8522", 8, "\u852D", 9, "\u853E", 4, "\u8544\u8545\u8546\u8547\u854B", 10], - ["ca80", "\u8557\u8558\u855A\u855B\u855C\u855D\u855F", 4, "\u8565\u8566\u8567\u8569", 8, "\u8573\u8575\u8576\u8577\u8578\u857C\u857D\u857F\u8580\u8581\u7701\u76DB\u5269\u80DC\u5723\u5E08\u5931\u72EE\u65BD\u6E7F\u8BD7\u5C38\u8671\u5341\u77F3\u62FE\u65F6\u4EC0\u98DF\u8680\u5B9E\u8BC6\u53F2\u77E2\u4F7F\u5C4E\u9A76\u59CB\u5F0F\u793A\u58EB\u4E16\u67FF\u4E8B\u62ED\u8A93\u901D\u52BF\u662F\u55DC\u566C\u9002\u4ED5\u4F8D\u91CA\u9970\u6C0F\u5E02\u6043\u5BA4\u89C6\u8BD5\u6536\u624B\u9996\u5B88\u5BFF\u6388\u552E\u53D7\u7626\u517D\u852C\u67A2\u68B3\u6B8A\u6292\u8F93\u53D4\u8212\u6DD1\u758F\u4E66\u8D4E\u5B70\u719F\u85AF\u6691\u66D9\u7F72\u8700\u9ECD\u9F20\u5C5E\u672F\u8FF0\u6811\u675F\u620D\u7AD6\u5885\u5EB6\u6570\u6F31"], - ["cb40", "\u8582\u8583\u8586\u8588", 6, "\u8590", 10, "\u859D", 6, "\u85A5\u85A6\u85A7\u85A9\u85AB\u85AC\u85AD\u85B1", 5, "\u85B8\u85BA", 6, "\u85C2", 6, "\u85CA", 4, "\u85D1\u85D2"], - ["cb80", "\u85D4\u85D6", 5, "\u85DD", 6, "\u85E5\u85E6\u85E7\u85E8\u85EA", 14, "\u6055\u5237\u800D\u6454\u8870\u7529\u5E05\u6813\u62F4\u971C\u53CC\u723D\u8C01\u6C34\u7761\u7A0E\u542E\u77AC\u987A\u821C\u8BF4\u7855\u6714\u70C1\u65AF\u6495\u5636\u601D\u79C1\u53F8\u4E1D\u6B7B\u8086\u5BFA\u55E3\u56DB\u4F3A\u4F3C\u9972\u5DF3\u677E\u8038\u6002\u9882\u9001\u5B8B\u8BBC\u8BF5\u641C\u8258\u64DE\u55FD\u82CF\u9165\u4FD7\u7D20\u901F\u7C9F\u50F3\u5851\u6EAF\u5BBF\u8BC9\u8083\u9178\u849C\u7B97\u867D\u968B\u968F\u7EE5\u9AD3\u788E\u5C81\u7A57\u9042\u96A7\u795F\u5B59\u635F\u7B0B\u84D1\u68AD\u5506\u7F29\u7410\u7D22\u9501\u6240\u584C\u4ED6\u5B83\u5979\u5854"], - ["cc40", "\u85F9\u85FA\u85FC\u85FD\u85FE\u8600", 4, "\u8606", 10, "\u8612\u8613\u8614\u8615\u8617", 15, "\u8628\u862A", 13, "\u8639\u863A\u863B\u863D\u863E\u863F\u8640"], - ["cc80", "\u8641", 11, "\u8652\u8653\u8655", 4, "\u865B\u865C\u865D\u865F\u8660\u8661\u8663", 7, "\u736D\u631E\u8E4B\u8E0F\u80CE\u82D4\u62AC\u53F0\u6CF0\u915E\u592A\u6001\u6C70\u574D\u644A\u8D2A\u762B\u6EE9\u575B\u6A80\u75F0\u6F6D\u8C2D\u8C08\u5766\u6BEF\u8892\u78B3\u63A2\u53F9\u70AD\u6C64\u5858\u642A\u5802\u68E0\u819B\u5510\u7CD6\u5018\u8EBA\u6DCC\u8D9F\u70EB\u638F\u6D9B\u6ED4\u7EE6\u8404\u6843\u9003\u6DD8\u9676\u8BA8\u5957\u7279\u85E4\u817E\u75BC\u8A8A\u68AF\u5254\u8E22\u9511\u63D0\u9898\u8E44\u557C\u4F53\u66FF\u568F\u60D5\u6D95\u5243\u5C49\u5929\u6DFB\u586B\u7530\u751C\u606C\u8214\u8146\u6311\u6761\u8FE2\u773A\u8DF3\u8D34\u94C1\u5E16\u5385\u542C\u70C3"], - ["cd40", "\u866D\u866F\u8670\u8672", 6, "\u8683", 6, "\u868E", 4, "\u8694\u8696", 5, "\u869E", 4, "\u86A5\u86A6\u86AB\u86AD\u86AE\u86B2\u86B3\u86B7\u86B8\u86B9\u86BB", 4, "\u86C1\u86C2\u86C3\u86C5\u86C8\u86CC\u86CD\u86D2\u86D3\u86D5\u86D6\u86D7\u86DA\u86DC"], - ["cd80", "\u86DD\u86E0\u86E1\u86E2\u86E3\u86E5\u86E6\u86E7\u86E8\u86EA\u86EB\u86EC\u86EF\u86F5\u86F6\u86F7\u86FA\u86FB\u86FC\u86FD\u86FF\u8701\u8704\u8705\u8706\u870B\u870C\u870E\u870F\u8710\u8711\u8714\u8716\u6C40\u5EF7\u505C\u4EAD\u5EAD\u633A\u8247\u901A\u6850\u916E\u77B3\u540C\u94DC\u5F64\u7AE5\u6876\u6345\u7B52\u7EDF\u75DB\u5077\u6295\u5934\u900F\u51F8\u79C3\u7A81\u56FE\u5F92\u9014\u6D82\u5C60\u571F\u5410\u5154\u6E4D\u56E2\u63A8\u9893\u817F\u8715\u892A\u9000\u541E\u5C6F\u81C0\u62D6\u6258\u8131\u9E35\u9640\u9A6E\u9A7C\u692D\u59A5\u62D3\u553E\u6316\u54C7\u86D9\u6D3C\u5A03\u74E6\u889C\u6B6A\u5916\u8C4C\u5F2F\u6E7E\u73A9\u987D\u4E38\u70F7\u5B8C\u7897\u633D\u665A\u7696\u60CB\u5B9B\u5A49\u4E07\u8155\u6C6A\u738B\u4EA1\u6789\u7F51\u5F80\u65FA\u671B\u5FD8\u5984\u5A01"], - ["ce40", "\u8719\u871B\u871D\u871F\u8720\u8724\u8726\u8727\u8728\u872A\u872B\u872C\u872D\u872F\u8730\u8732\u8733\u8735\u8736\u8738\u8739\u873A\u873C\u873D\u8740", 6, "\u874A\u874B\u874D\u874F\u8750\u8751\u8752\u8754\u8755\u8756\u8758\u875A", 5, "\u8761\u8762\u8766", 7, "\u876F\u8771\u8772\u8773\u8775"], - ["ce80", "\u8777\u8778\u8779\u877A\u877F\u8780\u8781\u8784\u8786\u8787\u8789\u878A\u878C\u878E", 4, "\u8794\u8795\u8796\u8798", 6, "\u87A0", 4, "\u5DCD\u5FAE\u5371\u97E6\u8FDD\u6845\u56F4\u552F\u60DF\u4E3A\u6F4D\u7EF4\u82C7\u840E\u59D4\u4F1F\u4F2A\u5C3E\u7EAC\u672A\u851A\u5473\u754F\u80C3\u5582\u9B4F\u4F4D\u6E2D\u8C13\u5C09\u6170\u536B\u761F\u6E29\u868A\u6587\u95FB\u7EB9\u543B\u7A33\u7D0A\u95EE\u55E1\u7FC1\u74EE\u631D\u8717\u6DA1\u7A9D\u6211\u65A1\u5367\u63E1\u6C83\u5DEB\u545C\u94A8\u4E4C\u6C61\u8BEC\u5C4B\u65E0\u829C\u68A7\u543E\u5434\u6BCB\u6B66\u4E94\u6342\u5348\u821E\u4F0D\u4FAE\u575E\u620A\u96FE\u6664\u7269\u52FF\u52A1\u609F\u8BEF\u6614\u7199\u6790\u897F\u7852\u77FD\u6670\u563B\u5438\u9521\u727A"], - ["cf40", "\u87A5\u87A6\u87A7\u87A9\u87AA\u87AE\u87B0\u87B1\u87B2\u87B4\u87B6\u87B7\u87B8\u87B9\u87BB\u87BC\u87BE\u87BF\u87C1", 4, "\u87C7\u87C8\u87C9\u87CC", 4, "\u87D4", 6, "\u87DC\u87DD\u87DE\u87DF\u87E1\u87E2\u87E3\u87E4\u87E6\u87E7\u87E8\u87E9\u87EB\u87EC\u87ED\u87EF", 9], - ["cf80", "\u87FA\u87FB\u87FC\u87FD\u87FF\u8800\u8801\u8802\u8804", 5, "\u880B", 7, "\u8814\u8817\u8818\u8819\u881A\u881C", 4, "\u8823\u7A00\u606F\u5E0C\u6089\u819D\u5915\u60DC\u7184\u70EF\u6EAA\u6C50\u7280\u6A84\u88AD\u5E2D\u4E60\u5AB3\u559C\u94E3\u6D17\u7CFB\u9699\u620F\u7EC6\u778E\u867E\u5323\u971E\u8F96\u6687\u5CE1\u4FA0\u72ED\u4E0B\u53A6\u590F\u5413\u6380\u9528\u5148\u4ED9\u9C9C\u7EA4\u54B8\u8D24\u8854\u8237\u95F2\u6D8E\u5F26\u5ACC\u663E\u9669\u73B0\u732E\u53BF\u817A\u9985\u7FA1\u5BAA\u9677\u9650\u7EBF\u76F8\u53A2\u9576\u9999\u7BB1\u8944\u6E58\u4E61\u7FD4\u7965\u8BE6\u60F3\u54CD\u4EAB\u9879\u5DF7\u6A61\u50CF\u5411\u8C61\u8427\u785D\u9704\u524A\u54EE\u56A3\u9500\u6D88\u5BB5\u6DC6\u6653"], - ["d040", "\u8824", 13, "\u8833", 5, "\u883A\u883B\u883D\u883E\u883F\u8841\u8842\u8843\u8846", 5, "\u884E", 5, "\u8855\u8856\u8858\u885A", 6, "\u8866\u8867\u886A\u886D\u886F\u8871\u8873\u8874\u8875\u8876\u8878\u8879\u887A"], - ["d080", "\u887B\u887C\u8880\u8883\u8886\u8887\u8889\u888A\u888C\u888E\u888F\u8890\u8891\u8893\u8894\u8895\u8897", 4, "\u889D", 4, "\u88A3\u88A5", 5, "\u5C0F\u5B5D\u6821\u8096\u5578\u7B11\u6548\u6954\u4E9B\u6B47\u874E\u978B\u534F\u631F\u643A\u90AA\u659C\u80C1\u8C10\u5199\u68B0\u5378\u87F9\u61C8\u6CC4\u6CFB\u8C22\u5C51\u85AA\u82AF\u950C\u6B23\u8F9B\u65B0\u5FFB\u5FC3\u4FE1\u8845\u661F\u8165\u7329\u60FA\u5174\u5211\u578B\u5F62\u90A2\u884C\u9192\u5E78\u674F\u6027\u59D3\u5144\u51F6\u80F8\u5308\u6C79\u96C4\u718A\u4F11\u4FEE\u7F9E\u673D\u55C5\u9508\u79C0\u8896\u7EE3\u589F\u620C\u9700\u865A\u5618\u987B\u5F90\u8BB8\u84C4\u9157\u53D9\u65ED\u5E8F\u755C\u6064\u7D6E\u5A7F\u7EEA\u7EED\u8F69\u55A7\u5BA3\u60AC\u65CB\u7384"], - ["d140", "\u88AC\u88AE\u88AF\u88B0\u88B2", 4, "\u88B8\u88B9\u88BA\u88BB\u88BD\u88BE\u88BF\u88C0\u88C3\u88C4\u88C7\u88C8\u88CA\u88CB\u88CC\u88CD\u88CF\u88D0\u88D1\u88D3\u88D6\u88D7\u88DA", 4, "\u88E0\u88E1\u88E6\u88E7\u88E9", 6, "\u88F2\u88F5\u88F6\u88F7\u88FA\u88FB\u88FD\u88FF\u8900\u8901\u8903", 5], - ["d180", "\u8909\u890B", 4, "\u8911\u8914", 4, "\u891C", 4, "\u8922\u8923\u8924\u8926\u8927\u8928\u8929\u892C\u892D\u892E\u892F\u8931\u8932\u8933\u8935\u8937\u9009\u7663\u7729\u7EDA\u9774\u859B\u5B66\u7A74\u96EA\u8840\u52CB\u718F\u5FAA\u65EC\u8BE2\u5BFB\u9A6F\u5DE1\u6B89\u6C5B\u8BAD\u8BAF\u900A\u8FC5\u538B\u62BC\u9E26\u9E2D\u5440\u4E2B\u82BD\u7259\u869C\u5D16\u8859\u6DAF\u96C5\u54D1\u4E9A\u8BB6\u7109\u54BD\u9609\u70DF\u6DF9\u76D0\u4E25\u7814\u8712\u5CA9\u5EF6\u8A00\u989C\u960E\u708E\u6CBF\u5944\u63A9\u773C\u884D\u6F14\u8273\u5830\u71D5\u538C\u781A\u96C1\u5501\u5F66\u7130\u5BB4\u8C1A\u9A8C\u6B83\u592E\u9E2F\u79E7\u6768\u626C\u4F6F\u75A1\u7F8A\u6D0B\u9633\u6C27\u4EF0\u75D2\u517B\u6837\u6F3E\u9080\u8170\u5996\u7476"], - ["d240", "\u8938", 8, "\u8942\u8943\u8945", 24, "\u8960", 5, "\u8967", 19, "\u897C"], - ["d280", "\u897D\u897E\u8980\u8982\u8984\u8985\u8987", 26, "\u6447\u5C27\u9065\u7A91\u8C23\u59DA\u54AC\u8200\u836F\u8981\u8000\u6930\u564E\u8036\u7237\u91CE\u51B6\u4E5F\u9875\u6396\u4E1A\u53F6\u66F3\u814B\u591C\u6DB2\u4E00\u58F9\u533B\u63D6\u94F1\u4F9D\u4F0A\u8863\u9890\u5937\u9057\u79FB\u4EEA\u80F0\u7591\u6C82\u5B9C\u59E8\u5F5D\u6905\u8681\u501A\u5DF2\u4E59\u77E3\u4EE5\u827A\u6291\u6613\u9091\u5C79\u4EBF\u5F79\u81C6\u9038\u8084\u75AB\u4EA6\u88D4\u610F\u6BC5\u5FC6\u4E49\u76CA\u6EA2\u8BE3\u8BAE\u8C0A\u8BD1\u5F02\u7FFC\u7FCC\u7ECE\u8335\u836B\u56E0\u6BB7\u97F3\u9634\u59FB\u541F\u94F6\u6DEB\u5BC5\u996E\u5C39\u5F15\u9690"], - ["d340", "\u89A2", 30, "\u89C3\u89CD\u89D3\u89D4\u89D5\u89D7\u89D8\u89D9\u89DB\u89DD\u89DF\u89E0\u89E1\u89E2\u89E4\u89E7\u89E8\u89E9\u89EA\u89EC\u89ED\u89EE\u89F0\u89F1\u89F2\u89F4", 6], - ["d380", "\u89FB", 4, "\u8A01", 5, "\u8A08", 21, "\u5370\u82F1\u6A31\u5A74\u9E70\u5E94\u7F28\u83B9\u8424\u8425\u8367\u8747\u8FCE\u8D62\u76C8\u5F71\u9896\u786C\u6620\u54DF\u62E5\u4F63\u81C3\u75C8\u5EB8\u96CD\u8E0A\u86F9\u548F\u6CF3\u6D8C\u6C38\u607F\u52C7\u7528\u5E7D\u4F18\u60A0\u5FE7\u5C24\u7531\u90AE\u94C0\u72B9\u6CB9\u6E38\u9149\u6709\u53CB\u53F3\u4F51\u91C9\u8BF1\u53C8\u5E7C\u8FC2\u6DE4\u4E8E\u76C2\u6986\u865E\u611A\u8206\u4F59\u4FDE\u903E\u9C7C\u6109\u6E1D\u6E14\u9685\u4E88\u5A31\u96E8\u4E0E\u5C7F\u79B9\u5B87\u8BED\u7FBD\u7389\u57DF\u828B\u90C1\u5401\u9047\u55BB\u5CEA\u5FA1\u6108\u6B32\u72F1\u80B2\u8A89"], - ["d440", "\u8A1E", 31, "\u8A3F", 8, "\u8A49", 21], - ["d480", "\u8A5F", 25, "\u8A7A", 6, "\u6D74\u5BD3\u88D5\u9884\u8C6B\u9A6D\u9E33\u6E0A\u51A4\u5143\u57A3\u8881\u539F\u63F4\u8F95\u56ED\u5458\u5706\u733F\u6E90\u7F18\u8FDC\u82D1\u613F\u6028\u9662\u66F0\u7EA6\u8D8A\u8DC3\u94A5\u5CB3\u7CA4\u6708\u60A6\u9605\u8018\u4E91\u90E7\u5300\u9668\u5141\u8FD0\u8574\u915D\u6655\u97F5\u5B55\u531D\u7838\u6742\u683D\u54C9\u707E\u5BB0\u8F7D\u518D\u5728\u54B1\u6512\u6682\u8D5E\u8D43\u810F\u846C\u906D\u7CDF\u51FF\u85FB\u67A3\u65E9\u6FA1\u86A4\u8E81\u566A\u9020\u7682\u7076\u71E5\u8D23\u62E9\u5219\u6CFD\u8D3C\u600E\u589E\u618E\u66FE\u8D60\u624E\u55B3\u6E23\u672D\u8F67"], - ["d540", "\u8A81", 7, "\u8A8B", 7, "\u8A94", 46], - ["d580", "\u8AC3", 32, "\u94E1\u95F8\u7728\u6805\u69A8\u548B\u4E4D\u70B8\u8BC8\u6458\u658B\u5B85\u7A84\u503A\u5BE8\u77BB\u6BE1\u8A79\u7C98\u6CBE\u76CF\u65A9\u8F97\u5D2D\u5C55\u8638\u6808\u5360\u6218\u7AD9\u6E5B\u7EFD\u6A1F\u7AE0\u5F70\u6F33\u5F20\u638C\u6DA8\u6756\u4E08\u5E10\u8D26\u4ED7\u80C0\u7634\u969C\u62DB\u662D\u627E\u6CBC\u8D75\u7167\u7F69\u5146\u8087\u53EC\u906E\u6298\u54F2\u86F0\u8F99\u8005\u9517\u8517\u8FD9\u6D59\u73CD\u659F\u771F\u7504\u7827\u81FB\u8D1E\u9488\u4FA6\u6795\u75B9\u8BCA\u9707\u632F\u9547\u9635\u84B8\u6323\u7741\u5F81\u72F0\u4E89\u6014\u6574\u62EF\u6B63\u653F"], - ["d640", "\u8AE4", 34, "\u8B08", 27], - ["d680", "\u8B24\u8B25\u8B27", 30, "\u5E27\u75C7\u90D1\u8BC1\u829D\u679D\u652F\u5431\u8718\u77E5\u80A2\u8102\u6C41\u4E4B\u7EC7\u804C\u76F4\u690D\u6B96\u6267\u503C\u4F84\u5740\u6307\u6B62\u8DBE\u53EA\u65E8\u7EB8\u5FD7\u631A\u63B7\u81F3\u81F4\u7F6E\u5E1C\u5CD9\u5236\u667A\u79E9\u7A1A\u8D28\u7099\u75D4\u6EDE\u6CBB\u7A92\u4E2D\u76C5\u5FE0\u949F\u8877\u7EC8\u79CD\u80BF\u91CD\u4EF2\u4F17\u821F\u5468\u5DDE\u6D32\u8BCC\u7CA5\u8F74\u8098\u5E1A\u5492\u76B1\u5B99\u663C\u9AA4\u73E0\u682A\u86DB\u6731\u732A\u8BF8\u8BDB\u9010\u7AF9\u70DB\u716E\u62C4\u77A9\u5631\u4E3B\u8457\u67F1\u52A9\u86C0\u8D2E\u94F8\u7B51"], - ["d740", "\u8B46", 31, "\u8B67", 4, "\u8B6D", 25], - ["d780", "\u8B87", 24, "\u8BAC\u8BB1\u8BBB\u8BC7\u8BD0\u8BEA\u8C09\u8C1E\u4F4F\u6CE8\u795D\u9A7B\u6293\u722A\u62FD\u4E13\u7816\u8F6C\u64B0\u8D5A\u7BC6\u6869\u5E84\u88C5\u5986\u649E\u58EE\u72B6\u690E\u9525\u8FFD\u8D58\u5760\u7F00\u8C06\u51C6\u6349\u62D9\u5353\u684C\u7422\u8301\u914C\u5544\u7740\u707C\u6D4A\u5179\u54A8\u8D44\u59FF\u6ECB\u6DC4\u5B5C\u7D2B\u4ED4\u7C7D\u6ED3\u5B50\u81EA\u6E0D\u5B57\u9B03\u68D5\u8E2A\u5B97\u7EFC\u603B\u7EB5\u90B9\u8D70\u594F\u63CD\u79DF\u8DB3\u5352\u65CF\u7956\u8BC5\u963B\u7EC4\u94BB\u7E82\u5634\u9189\u6700\u7F6A\u5C0A\u9075\u6628\u5DE6\u4F50\u67DE\u505A\u4F5C\u5750\u5EA7"], - ["d840", "\u8C38", 8, "\u8C42\u8C43\u8C44\u8C45\u8C48\u8C4A\u8C4B\u8C4D", 7, "\u8C56\u8C57\u8C58\u8C59\u8C5B", 5, "\u8C63", 6, "\u8C6C", 6, "\u8C74\u8C75\u8C76\u8C77\u8C7B", 6, "\u8C83\u8C84\u8C86\u8C87"], - ["d880", "\u8C88\u8C8B\u8C8D", 6, "\u8C95\u8C96\u8C97\u8C99", 20, "\u4E8D\u4E0C\u5140\u4E10\u5EFF\u5345\u4E15\u4E98\u4E1E\u9B32\u5B6C\u5669\u4E28\u79BA\u4E3F\u5315\u4E47\u592D\u723B\u536E\u6C10\u56DF\u80E4\u9997\u6BD3\u777E\u9F17\u4E36\u4E9F\u9F10\u4E5C\u4E69\u4E93\u8288\u5B5B\u556C\u560F\u4EC4\u538D\u539D\u53A3\u53A5\u53AE\u9765\u8D5D\u531A\u53F5\u5326\u532E\u533E\u8D5C\u5366\u5363\u5202\u5208\u520E\u522D\u5233\u523F\u5240\u524C\u525E\u5261\u525C\u84AF\u527D\u5282\u5281\u5290\u5293\u5182\u7F54\u4EBB\u4EC3\u4EC9\u4EC2\u4EE8\u4EE1\u4EEB\u4EDE\u4F1B\u4EF3\u4F22\u4F64\u4EF5\u4F25\u4F27\u4F09\u4F2B\u4F5E\u4F67\u6538\u4F5A\u4F5D"], - ["d940", "\u8CAE", 62], - ["d980", "\u8CED", 32, "\u4F5F\u4F57\u4F32\u4F3D\u4F76\u4F74\u4F91\u4F89\u4F83\u4F8F\u4F7E\u4F7B\u4FAA\u4F7C\u4FAC\u4F94\u4FE6\u4FE8\u4FEA\u4FC5\u4FDA\u4FE3\u4FDC\u4FD1\u4FDF\u4FF8\u5029\u504C\u4FF3\u502C\u500F\u502E\u502D\u4FFE\u501C\u500C\u5025\u5028\u507E\u5043\u5055\u5048\u504E\u506C\u507B\u50A5\u50A7\u50A9\u50BA\u50D6\u5106\u50ED\u50EC\u50E6\u50EE\u5107\u510B\u4EDD\u6C3D\u4F58\u4F65\u4FCE\u9FA0\u6C46\u7C74\u516E\u5DFD\u9EC9\u9998\u5181\u5914\u52F9\u530D\u8A07\u5310\u51EB\u5919\u5155\u4EA0\u5156\u4EB3\u886E\u88A4\u4EB5\u8114\u88D2\u7980\u5B34\u8803\u7FB8\u51AB\u51B1\u51BD\u51BC"], - ["da40", "\u8D0E", 14, "\u8D20\u8D51\u8D52\u8D57\u8D5F\u8D65\u8D68\u8D69\u8D6A\u8D6C\u8D6E\u8D6F\u8D71\u8D72\u8D78", 8, "\u8D82\u8D83\u8D86\u8D87\u8D88\u8D89\u8D8C", 4, "\u8D92\u8D93\u8D95", 9, "\u8DA0\u8DA1"], - ["da80", "\u8DA2\u8DA4", 12, "\u8DB2\u8DB6\u8DB7\u8DB9\u8DBB\u8DBD\u8DC0\u8DC1\u8DC2\u8DC5\u8DC7\u8DC8\u8DC9\u8DCA\u8DCD\u8DD0\u8DD2\u8DD3\u8DD4\u51C7\u5196\u51A2\u51A5\u8BA0\u8BA6\u8BA7\u8BAA\u8BB4\u8BB5\u8BB7\u8BC2\u8BC3\u8BCB\u8BCF\u8BCE\u8BD2\u8BD3\u8BD4\u8BD6\u8BD8\u8BD9\u8BDC\u8BDF\u8BE0\u8BE4\u8BE8\u8BE9\u8BEE\u8BF0\u8BF3\u8BF6\u8BF9\u8BFC\u8BFF\u8C00\u8C02\u8C04\u8C07\u8C0C\u8C0F\u8C11\u8C12\u8C14\u8C15\u8C16\u8C19\u8C1B\u8C18\u8C1D\u8C1F\u8C20\u8C21\u8C25\u8C27\u8C2A\u8C2B\u8C2E\u8C2F\u8C32\u8C33\u8C35\u8C36\u5369\u537A\u961D\u9622\u9621\u9631\u962A\u963D\u963C\u9642\u9649\u9654\u965F\u9667\u966C\u9672\u9674\u9688\u968D\u9697\u96B0\u9097\u909B\u909D\u9099\u90AC\u90A1\u90B4\u90B3\u90B6\u90BA"], - ["db40", "\u8DD5\u8DD8\u8DD9\u8DDC\u8DE0\u8DE1\u8DE2\u8DE5\u8DE6\u8DE7\u8DE9\u8DED\u8DEE\u8DF0\u8DF1\u8DF2\u8DF4\u8DF6\u8DFC\u8DFE", 6, "\u8E06\u8E07\u8E08\u8E0B\u8E0D\u8E0E\u8E10\u8E11\u8E12\u8E13\u8E15", 7, "\u8E20\u8E21\u8E24", 4, "\u8E2B\u8E2D\u8E30\u8E32\u8E33\u8E34\u8E36\u8E37\u8E38\u8E3B\u8E3C\u8E3E"], - ["db80", "\u8E3F\u8E43\u8E45\u8E46\u8E4C", 4, "\u8E53", 5, "\u8E5A", 11, "\u8E67\u8E68\u8E6A\u8E6B\u8E6E\u8E71\u90B8\u90B0\u90CF\u90C5\u90BE\u90D0\u90C4\u90C7\u90D3\u90E6\u90E2\u90DC\u90D7\u90DB\u90EB\u90EF\u90FE\u9104\u9122\u911E\u9123\u9131\u912F\u9139\u9143\u9146\u520D\u5942\u52A2\u52AC\u52AD\u52BE\u54FF\u52D0\u52D6\u52F0\u53DF\u71EE\u77CD\u5EF4\u51F5\u51FC\u9B2F\u53B6\u5F01\u755A\u5DEF\u574C\u57A9\u57A1\u587E\u58BC\u58C5\u58D1\u5729\u572C\u572A\u5733\u5739\u572E\u572F\u575C\u573B\u5742\u5769\u5785\u576B\u5786\u577C\u577B\u5768\u576D\u5776\u5773\u57AD\u57A4\u578C\u57B2\u57CF\u57A7\u57B4\u5793\u57A0\u57D5\u57D8\u57DA\u57D9\u57D2\u57B8\u57F4\u57EF\u57F8\u57E4\u57DD"], - ["dc40", "\u8E73\u8E75\u8E77", 4, "\u8E7D\u8E7E\u8E80\u8E82\u8E83\u8E84\u8E86\u8E88", 6, "\u8E91\u8E92\u8E93\u8E95", 6, "\u8E9D\u8E9F", 11, "\u8EAD\u8EAE\u8EB0\u8EB1\u8EB3", 6, "\u8EBB", 7], - ["dc80", "\u8EC3", 10, "\u8ECF", 21, "\u580B\u580D\u57FD\u57ED\u5800\u581E\u5819\u5844\u5820\u5865\u586C\u5881\u5889\u589A\u5880\u99A8\u9F19\u61FF\u8279\u827D\u827F\u828F\u828A\u82A8\u8284\u828E\u8291\u8297\u8299\u82AB\u82B8\u82BE\u82B0\u82C8\u82CA\u82E3\u8298\u82B7\u82AE\u82CB\u82CC\u82C1\u82A9\u82B4\u82A1\u82AA\u829F\u82C4\u82CE\u82A4\u82E1\u8309\u82F7\u82E4\u830F\u8307\u82DC\u82F4\u82D2\u82D8\u830C\u82FB\u82D3\u8311\u831A\u8306\u8314\u8315\u82E0\u82D5\u831C\u8351\u835B\u835C\u8308\u8392\u833C\u8334\u8331\u839B\u835E\u832F\u834F\u8347\u8343\u835F\u8340\u8317\u8360\u832D\u833A\u8333\u8366\u8365"], - ["dd40", "\u8EE5", 62], - ["dd80", "\u8F24", 32, "\u8368\u831B\u8369\u836C\u836A\u836D\u836E\u83B0\u8378\u83B3\u83B4\u83A0\u83AA\u8393\u839C\u8385\u837C\u83B6\u83A9\u837D\u83B8\u837B\u8398\u839E\u83A8\u83BA\u83BC\u83C1\u8401\u83E5\u83D8\u5807\u8418\u840B\u83DD\u83FD\u83D6\u841C\u8438\u8411\u8406\u83D4\u83DF\u840F\u8403\u83F8\u83F9\u83EA\u83C5\u83C0\u8426\u83F0\u83E1\u845C\u8451\u845A\u8459\u8473\u8487\u8488\u847A\u8489\u8478\u843C\u8446\u8469\u8476\u848C\u848E\u8431\u846D\u84C1\u84CD\u84D0\u84E6\u84BD\u84D3\u84CA\u84BF\u84BA\u84E0\u84A1\u84B9\u84B4\u8497\u84E5\u84E3\u850C\u750D\u8538\u84F0\u8539\u851F\u853A"], - ["de40", "\u8F45", 32, "\u8F6A\u8F80\u8F8C\u8F92\u8F9D\u8FA0\u8FA1\u8FA2\u8FA4\u8FA5\u8FA6\u8FA7\u8FAA\u8FAC\u8FAD\u8FAE\u8FAF\u8FB2\u8FB3\u8FB4\u8FB5\u8FB7\u8FB8\u8FBA\u8FBB\u8FBC\u8FBF\u8FC0\u8FC3\u8FC6"], - ["de80", "\u8FC9", 4, "\u8FCF\u8FD2\u8FD6\u8FD7\u8FDA\u8FE0\u8FE1\u8FE3\u8FE7\u8FEC\u8FEF\u8FF1\u8FF2\u8FF4\u8FF5\u8FF6\u8FFA\u8FFB\u8FFC\u8FFE\u8FFF\u9007\u9008\u900C\u900E\u9013\u9015\u9018\u8556\u853B\u84FF\u84FC\u8559\u8548\u8568\u8564\u855E\u857A\u77A2\u8543\u8572\u857B\u85A4\u85A8\u8587\u858F\u8579\u85AE\u859C\u8585\u85B9\u85B7\u85B0\u85D3\u85C1\u85DC\u85FF\u8627\u8605\u8629\u8616\u863C\u5EFE\u5F08\u593C\u5941\u8037\u5955\u595A\u5958\u530F\u5C22\u5C25\u5C2C\u5C34\u624C\u626A\u629F\u62BB\u62CA\u62DA\u62D7\u62EE\u6322\u62F6\u6339\u634B\u6343\u63AD\u63F6\u6371\u637A\u638E\u63B4\u636D\u63AC\u638A\u6369\u63AE\u63BC\u63F2\u63F8\u63E0\u63FF\u63C4\u63DE\u63CE\u6452\u63C6\u63BE\u6445\u6441\u640B\u641B\u6420\u640C\u6426\u6421\u645E\u6484\u646D\u6496"], - ["df40", "\u9019\u901C\u9023\u9024\u9025\u9027", 5, "\u9030", 4, "\u9037\u9039\u903A\u903D\u903F\u9040\u9043\u9045\u9046\u9048", 4, "\u904E\u9054\u9055\u9056\u9059\u905A\u905C", 5, "\u9064\u9066\u9067\u9069\u906A\u906B\u906C\u906F", 4, "\u9076", 6, "\u907E\u9081"], - ["df80", "\u9084\u9085\u9086\u9087\u9089\u908A\u908C", 4, "\u9092\u9094\u9096\u9098\u909A\u909C\u909E\u909F\u90A0\u90A4\u90A5\u90A7\u90A8\u90A9\u90AB\u90AD\u90B2\u90B7\u90BC\u90BD\u90BF\u90C0\u647A\u64B7\u64B8\u6499\u64BA\u64C0\u64D0\u64D7\u64E4\u64E2\u6509\u6525\u652E\u5F0B\u5FD2\u7519\u5F11\u535F\u53F1\u53FD\u53E9\u53E8\u53FB\u5412\u5416\u5406\u544B\u5452\u5453\u5454\u5456\u5443\u5421\u5457\u5459\u5423\u5432\u5482\u5494\u5477\u5471\u5464\u549A\u549B\u5484\u5476\u5466\u549D\u54D0\u54AD\u54C2\u54B4\u54D2\u54A7\u54A6\u54D3\u54D4\u5472\u54A3\u54D5\u54BB\u54BF\u54CC\u54D9\u54DA\u54DC\u54A9\u54AA\u54A4\u54DD\u54CF\u54DE\u551B\u54E7\u5520\u54FD\u5514\u54F3\u5522\u5523\u550F\u5511\u5527\u552A\u5567\u558F\u55B5\u5549\u556D\u5541\u5555\u553F\u5550\u553C"], - ["e040", "\u90C2\u90C3\u90C6\u90C8\u90C9\u90CB\u90CC\u90CD\u90D2\u90D4\u90D5\u90D6\u90D8\u90D9\u90DA\u90DE\u90DF\u90E0\u90E3\u90E4\u90E5\u90E9\u90EA\u90EC\u90EE\u90F0\u90F1\u90F2\u90F3\u90F5\u90F6\u90F7\u90F9\u90FA\u90FB\u90FC\u90FF\u9100\u9101\u9103\u9105", 19, "\u911A\u911B\u911C"], - ["e080", "\u911D\u911F\u9120\u9121\u9124", 10, "\u9130\u9132", 6, "\u913A", 8, "\u9144\u5537\u5556\u5575\u5576\u5577\u5533\u5530\u555C\u558B\u55D2\u5583\u55B1\u55B9\u5588\u5581\u559F\u557E\u55D6\u5591\u557B\u55DF\u55BD\u55BE\u5594\u5599\u55EA\u55F7\u55C9\u561F\u55D1\u55EB\u55EC\u55D4\u55E6\u55DD\u55C4\u55EF\u55E5\u55F2\u55F3\u55CC\u55CD\u55E8\u55F5\u55E4\u8F94\u561E\u5608\u560C\u5601\u5624\u5623\u55FE\u5600\u5627\u562D\u5658\u5639\u5657\u562C\u564D\u5662\u5659\u565C\u564C\u5654\u5686\u5664\u5671\u566B\u567B\u567C\u5685\u5693\u56AF\u56D4\u56D7\u56DD\u56E1\u56F5\u56EB\u56F9\u56FF\u5704\u570A\u5709\u571C\u5E0F\u5E19\u5E14\u5E11\u5E31\u5E3B\u5E3C"], - ["e140", "\u9145\u9147\u9148\u9151\u9153\u9154\u9155\u9156\u9158\u9159\u915B\u915C\u915F\u9160\u9166\u9167\u9168\u916B\u916D\u9173\u917A\u917B\u917C\u9180", 4, "\u9186\u9188\u918A\u918E\u918F\u9193", 6, "\u919C", 5, "\u91A4", 5, "\u91AB\u91AC\u91B0\u91B1\u91B2\u91B3\u91B6\u91B7\u91B8\u91B9\u91BB"], - ["e180", "\u91BC", 10, "\u91C8\u91CB\u91D0\u91D2", 9, "\u91DD", 8, "\u5E37\u5E44\u5E54\u5E5B\u5E5E\u5E61\u5C8C\u5C7A\u5C8D\u5C90\u5C96\u5C88\u5C98\u5C99\u5C91\u5C9A\u5C9C\u5CB5\u5CA2\u5CBD\u5CAC\u5CAB\u5CB1\u5CA3\u5CC1\u5CB7\u5CC4\u5CD2\u5CE4\u5CCB\u5CE5\u5D02\u5D03\u5D27\u5D26\u5D2E\u5D24\u5D1E\u5D06\u5D1B\u5D58\u5D3E\u5D34\u5D3D\u5D6C\u5D5B\u5D6F\u5D5D\u5D6B\u5D4B\u5D4A\u5D69\u5D74\u5D82\u5D99\u5D9D\u8C73\u5DB7\u5DC5\u5F73\u5F77\u5F82\u5F87\u5F89\u5F8C\u5F95\u5F99\u5F9C\u5FA8\u5FAD\u5FB5\u5FBC\u8862\u5F61\u72AD\u72B0\u72B4\u72B7\u72B8\u72C3\u72C1\u72CE\u72CD\u72D2\u72E8\u72EF\u72E9\u72F2\u72F4\u72F7\u7301\u72F3\u7303\u72FA"], - ["e240", "\u91E6", 62], - ["e280", "\u9225", 32, "\u72FB\u7317\u7313\u7321\u730A\u731E\u731D\u7315\u7322\u7339\u7325\u732C\u7338\u7331\u7350\u734D\u7357\u7360\u736C\u736F\u737E\u821B\u5925\u98E7\u5924\u5902\u9963\u9967", 5, "\u9974\u9977\u997D\u9980\u9984\u9987\u998A\u998D\u9990\u9991\u9993\u9994\u9995\u5E80\u5E91\u5E8B\u5E96\u5EA5\u5EA0\u5EB9\u5EB5\u5EBE\u5EB3\u8D53\u5ED2\u5ED1\u5EDB\u5EE8\u5EEA\u81BA\u5FC4\u5FC9\u5FD6\u5FCF\u6003\u5FEE\u6004\u5FE1\u5FE4\u5FFE\u6005\u6006\u5FEA\u5FED\u5FF8\u6019\u6035\u6026\u601B\u600F\u600D\u6029\u602B\u600A\u603F\u6021\u6078\u6079\u607B\u607A\u6042"], - ["e340", "\u9246", 45, "\u9275", 16], - ["e380", "\u9286", 7, "\u928F", 24, "\u606A\u607D\u6096\u609A\u60AD\u609D\u6083\u6092\u608C\u609B\u60EC\u60BB\u60B1\u60DD\u60D8\u60C6\u60DA\u60B4\u6120\u6126\u6115\u6123\u60F4\u6100\u610E\u612B\u614A\u6175\u61AC\u6194\u61A7\u61B7\u61D4\u61F5\u5FDD\u96B3\u95E9\u95EB\u95F1\u95F3\u95F5\u95F6\u95FC\u95FE\u9603\u9604\u9606\u9608\u960A\u960B\u960C\u960D\u960F\u9612\u9615\u9616\u9617\u9619\u961A\u4E2C\u723F\u6215\u6C35\u6C54\u6C5C\u6C4A\u6CA3\u6C85\u6C90\u6C94\u6C8C\u6C68\u6C69\u6C74\u6C76\u6C86\u6CA9\u6CD0\u6CD4\u6CAD\u6CF7\u6CF8\u6CF1\u6CD7\u6CB2\u6CE0\u6CD6\u6CFA\u6CEB\u6CEE\u6CB1\u6CD3\u6CEF\u6CFE"], - ["e440", "\u92A8", 5, "\u92AF", 24, "\u92C9", 31], - ["e480", "\u92E9", 32, "\u6D39\u6D27\u6D0C\u6D43\u6D48\u6D07\u6D04\u6D19\u6D0E\u6D2B\u6D4D\u6D2E\u6D35\u6D1A\u6D4F\u6D52\u6D54\u6D33\u6D91\u6D6F\u6D9E\u6DA0\u6D5E\u6D93\u6D94\u6D5C\u6D60\u6D7C\u6D63\u6E1A\u6DC7\u6DC5\u6DDE\u6E0E\u6DBF\u6DE0\u6E11\u6DE6\u6DDD\u6DD9\u6E16\u6DAB\u6E0C\u6DAE\u6E2B\u6E6E\u6E4E\u6E6B\u6EB2\u6E5F\u6E86\u6E53\u6E54\u6E32\u6E25\u6E44\u6EDF\u6EB1\u6E98\u6EE0\u6F2D\u6EE2\u6EA5\u6EA7\u6EBD\u6EBB\u6EB7\u6ED7\u6EB4\u6ECF\u6E8F\u6EC2\u6E9F\u6F62\u6F46\u6F47\u6F24\u6F15\u6EF9\u6F2F\u6F36\u6F4B\u6F74\u6F2A\u6F09\u6F29\u6F89\u6F8D\u6F8C\u6F78\u6F72\u6F7C\u6F7A\u6FD1"], - ["e540", "\u930A", 51, "\u933F", 10], - ["e580", "\u934A", 31, "\u936B\u6FC9\u6FA7\u6FB9\u6FB6\u6FC2\u6FE1\u6FEE\u6FDE\u6FE0\u6FEF\u701A\u7023\u701B\u7039\u7035\u704F\u705E\u5B80\u5B84\u5B95\u5B93\u5BA5\u5BB8\u752F\u9A9E\u6434\u5BE4\u5BEE\u8930\u5BF0\u8E47\u8B07\u8FB6\u8FD3\u8FD5\u8FE5\u8FEE\u8FE4\u8FE9\u8FE6\u8FF3\u8FE8\u9005\u9004\u900B\u9026\u9011\u900D\u9016\u9021\u9035\u9036\u902D\u902F\u9044\u9051\u9052\u9050\u9068\u9058\u9062\u905B\u66B9\u9074\u907D\u9082\u9088\u9083\u908B\u5F50\u5F57\u5F56\u5F58\u5C3B\u54AB\u5C50\u5C59\u5B71\u5C63\u5C66\u7FBC\u5F2A\u5F29\u5F2D\u8274\u5F3C\u9B3B\u5C6E\u5981\u5983\u598D\u59A9\u59AA\u59A3"], - ["e640", "\u936C", 34, "\u9390", 27], - ["e680", "\u93AC", 29, "\u93CB\u93CC\u93CD\u5997\u59CA\u59AB\u599E\u59A4\u59D2\u59B2\u59AF\u59D7\u59BE\u5A05\u5A06\u59DD\u5A08\u59E3\u59D8\u59F9\u5A0C\u5A09\u5A32\u5A34\u5A11\u5A23\u5A13\u5A40\u5A67\u5A4A\u5A55\u5A3C\u5A62\u5A75\u80EC\u5AAA\u5A9B\u5A77\u5A7A\u5ABE\u5AEB\u5AB2\u5AD2\u5AD4\u5AB8\u5AE0\u5AE3\u5AF1\u5AD6\u5AE6\u5AD8\u5ADC\u5B09\u5B17\u5B16\u5B32\u5B37\u5B40\u5C15\u5C1C\u5B5A\u5B65\u5B73\u5B51\u5B53\u5B62\u9A75\u9A77\u9A78\u9A7A\u9A7F\u9A7D\u9A80\u9A81\u9A85\u9A88\u9A8A\u9A90\u9A92\u9A93\u9A96\u9A98\u9A9B\u9A9C\u9A9D\u9A9F\u9AA0\u9AA2\u9AA3\u9AA5\u9AA7\u7E9F\u7EA1\u7EA3\u7EA5\u7EA8\u7EA9"], - ["e740", "\u93CE", 7, "\u93D7", 54], - ["e780", "\u940E", 32, "\u7EAD\u7EB0\u7EBE\u7EC0\u7EC1\u7EC2\u7EC9\u7ECB\u7ECC\u7ED0\u7ED4\u7ED7\u7EDB\u7EE0\u7EE1\u7EE8\u7EEB\u7EEE\u7EEF\u7EF1\u7EF2\u7F0D\u7EF6\u7EFA\u7EFB\u7EFE\u7F01\u7F02\u7F03\u7F07\u7F08\u7F0B\u7F0C\u7F0F\u7F11\u7F12\u7F17\u7F19\u7F1C\u7F1B\u7F1F\u7F21", 6, "\u7F2A\u7F2B\u7F2C\u7F2D\u7F2F", 4, "\u7F35\u5E7A\u757F\u5DDB\u753E\u9095\u738E\u7391\u73AE\u73A2\u739F\u73CF\u73C2\u73D1\u73B7\u73B3\u73C0\u73C9\u73C8\u73E5\u73D9\u987C\u740A\u73E9\u73E7\u73DE\u73BA\u73F2\u740F\u742A\u745B\u7426\u7425\u7428\u7430\u742E\u742C"], - ["e840", "\u942F", 14, "\u943F", 43, "\u946C\u946D\u946E\u946F"], - ["e880", "\u9470", 20, "\u9491\u9496\u9498\u94C7\u94CF\u94D3\u94D4\u94DA\u94E6\u94FB\u951C\u9520\u741B\u741A\u7441\u745C\u7457\u7455\u7459\u7477\u746D\u747E\u749C\u748E\u7480\u7481\u7487\u748B\u749E\u74A8\u74A9\u7490\u74A7\u74D2\u74BA\u97EA\u97EB\u97EC\u674C\u6753\u675E\u6748\u6769\u67A5\u6787\u676A\u6773\u6798\u67A7\u6775\u67A8\u679E\u67AD\u678B\u6777\u677C\u67F0\u6809\u67D8\u680A\u67E9\u67B0\u680C\u67D9\u67B5\u67DA\u67B3\u67DD\u6800\u67C3\u67B8\u67E2\u680E\u67C1\u67FD\u6832\u6833\u6860\u6861\u684E\u6862\u6844\u6864\u6883\u681D\u6855\u6866\u6841\u6867\u6840\u683E\u684A\u6849\u6829\u68B5\u688F\u6874\u6877\u6893\u686B\u68C2\u696E\u68FC\u691F\u6920\u68F9"], - ["e940", "\u9527\u9533\u953D\u9543\u9548\u954B\u9555\u955A\u9560\u956E\u9574\u9575\u9577", 7, "\u9580", 42], - ["e980", "\u95AB", 32, "\u6924\u68F0\u690B\u6901\u6957\u68E3\u6910\u6971\u6939\u6960\u6942\u695D\u6984\u696B\u6980\u6998\u6978\u6934\u69CC\u6987\u6988\u69CE\u6989\u6966\u6963\u6979\u699B\u69A7\u69BB\u69AB\u69AD\u69D4\u69B1\u69C1\u69CA\u69DF\u6995\u69E0\u698D\u69FF\u6A2F\u69ED\u6A17\u6A18\u6A65\u69F2\u6A44\u6A3E\u6AA0\u6A50\u6A5B\u6A35\u6A8E\u6A79\u6A3D\u6A28\u6A58\u6A7C\u6A91\u6A90\u6AA9\u6A97\u6AAB\u7337\u7352\u6B81\u6B82\u6B87\u6B84\u6B92\u6B93\u6B8D\u6B9A\u6B9B\u6BA1\u6BAA\u8F6B\u8F6D\u8F71\u8F72\u8F73\u8F75\u8F76\u8F78\u8F77\u8F79\u8F7A\u8F7C\u8F7E\u8F81\u8F82\u8F84\u8F87\u8F8B"], - ["ea40", "\u95CC", 27, "\u95EC\u95FF\u9607\u9613\u9618\u961B\u961E\u9620\u9623", 6, "\u962B\u962C\u962D\u962F\u9630\u9637\u9638\u9639\u963A\u963E\u9641\u9643\u964A\u964E\u964F\u9651\u9652\u9653\u9656\u9657"], - ["ea80", "\u9658\u9659\u965A\u965C\u965D\u965E\u9660\u9663\u9665\u9666\u966B\u966D", 4, "\u9673\u9678", 12, "\u9687\u9689\u968A\u8F8D\u8F8E\u8F8F\u8F98\u8F9A\u8ECE\u620B\u6217\u621B\u621F\u6222\u6221\u6225\u6224\u622C\u81E7\u74EF\u74F4\u74FF\u750F\u7511\u7513\u6534\u65EE\u65EF\u65F0\u660A\u6619\u6772\u6603\u6615\u6600\u7085\u66F7\u661D\u6634\u6631\u6636\u6635\u8006\u665F\u6654\u6641\u664F\u6656\u6661\u6657\u6677\u6684\u668C\u66A7\u669D\u66BE\u66DB\u66DC\u66E6\u66E9\u8D32\u8D33\u8D36\u8D3B\u8D3D\u8D40\u8D45\u8D46\u8D48\u8D49\u8D47\u8D4D\u8D55\u8D59\u89C7\u89CA\u89CB\u89CC\u89CE\u89CF\u89D0\u89D1\u726E\u729F\u725D\u7266\u726F\u727E\u727F\u7284\u728B\u728D\u728F\u7292\u6308\u6332\u63B0"], - ["eb40", "\u968C\u968E\u9691\u9692\u9693\u9695\u9696\u969A\u969B\u969D", 9, "\u96A8", 7, "\u96B1\u96B2\u96B4\u96B5\u96B7\u96B8\u96BA\u96BB\u96BF\u96C2\u96C3\u96C8\u96CA\u96CB\u96D0\u96D1\u96D3\u96D4\u96D6", 9, "\u96E1", 6, "\u96EB"], - ["eb80", "\u96EC\u96ED\u96EE\u96F0\u96F1\u96F2\u96F4\u96F5\u96F8\u96FA\u96FB\u96FC\u96FD\u96FF\u9702\u9703\u9705\u970A\u970B\u970C\u9710\u9711\u9712\u9714\u9715\u9717", 4, "\u971D\u971F\u9720\u643F\u64D8\u8004\u6BEA\u6BF3\u6BFD\u6BF5\u6BF9\u6C05\u6C07\u6C06\u6C0D\u6C15\u6C18\u6C19\u6C1A\u6C21\u6C29\u6C24\u6C2A\u6C32\u6535\u6555\u656B\u724D\u7252\u7256\u7230\u8662\u5216\u809F\u809C\u8093\u80BC\u670A\u80BD\u80B1\u80AB\u80AD\u80B4\u80B7\u80E7\u80E8\u80E9\u80EA\u80DB\u80C2\u80C4\u80D9\u80CD\u80D7\u6710\u80DD\u80EB\u80F1\u80F4\u80ED\u810D\u810E\u80F2\u80FC\u6715\u8112\u8C5A\u8136\u811E\u812C\u8118\u8132\u8148\u814C\u8153\u8174\u8159\u815A\u8171\u8160\u8169\u817C\u817D\u816D\u8167\u584D\u5AB5\u8188\u8182\u8191\u6ED5\u81A3\u81AA\u81CC\u6726\u81CA\u81BB"], - ["ec40", "\u9721", 8, "\u972B\u972C\u972E\u972F\u9731\u9733", 4, "\u973A\u973B\u973C\u973D\u973F", 18, "\u9754\u9755\u9757\u9758\u975A\u975C\u975D\u975F\u9763\u9764\u9766\u9767\u9768\u976A", 7], - ["ec80", "\u9772\u9775\u9777", 4, "\u977D", 7, "\u9786", 4, "\u978C\u978E\u978F\u9790\u9793\u9795\u9796\u9797\u9799", 4, "\u81C1\u81A6\u6B24\u6B37\u6B39\u6B43\u6B46\u6B59\u98D1\u98D2\u98D3\u98D5\u98D9\u98DA\u6BB3\u5F40\u6BC2\u89F3\u6590\u9F51\u6593\u65BC\u65C6\u65C4\u65C3\u65CC\u65CE\u65D2\u65D6\u7080\u709C\u7096\u709D\u70BB\u70C0\u70B7\u70AB\u70B1\u70E8\u70CA\u7110\u7113\u7116\u712F\u7131\u7173\u715C\u7168\u7145\u7172\u714A\u7178\u717A\u7198\u71B3\u71B5\u71A8\u71A0\u71E0\u71D4\u71E7\u71F9\u721D\u7228\u706C\u7118\u7166\u71B9\u623E\u623D\u6243\u6248\u6249\u793B\u7940\u7946\u7949\u795B\u795C\u7953\u795A\u7962\u7957\u7960\u796F\u7967\u797A\u7985\u798A\u799A\u79A7\u79B3\u5FD1\u5FD0"], - ["ed40", "\u979E\u979F\u97A1\u97A2\u97A4", 6, "\u97AC\u97AE\u97B0\u97B1\u97B3\u97B5", 46], - ["ed80", "\u97E4\u97E5\u97E8\u97EE", 4, "\u97F4\u97F7", 23, "\u603C\u605D\u605A\u6067\u6041\u6059\u6063\u60AB\u6106\u610D\u615D\u61A9\u619D\u61CB\u61D1\u6206\u8080\u807F\u6C93\u6CF6\u6DFC\u77F6\u77F8\u7800\u7809\u7817\u7818\u7811\u65AB\u782D\u781C\u781D\u7839\u783A\u783B\u781F\u783C\u7825\u782C\u7823\u7829\u784E\u786D\u7856\u7857\u7826\u7850\u7847\u784C\u786A\u789B\u7893\u789A\u7887\u789C\u78A1\u78A3\u78B2\u78B9\u78A5\u78D4\u78D9\u78C9\u78EC\u78F2\u7905\u78F4\u7913\u7924\u791E\u7934\u9F9B\u9EF9\u9EFB\u9EFC\u76F1\u7704\u770D\u76F9\u7707\u7708\u771A\u7722\u7719\u772D\u7726\u7735\u7738\u7750\u7751\u7747\u7743\u775A\u7768"], - ["ee40", "\u980F", 62], - ["ee80", "\u984E", 32, "\u7762\u7765\u777F\u778D\u777D\u7780\u778C\u7791\u779F\u77A0\u77B0\u77B5\u77BD\u753A\u7540\u754E\u754B\u7548\u755B\u7572\u7579\u7583\u7F58\u7F61\u7F5F\u8A48\u7F68\u7F74\u7F71\u7F79\u7F81\u7F7E\u76CD\u76E5\u8832\u9485\u9486\u9487\u948B\u948A\u948C\u948D\u948F\u9490\u9494\u9497\u9495\u949A\u949B\u949C\u94A3\u94A4\u94AB\u94AA\u94AD\u94AC\u94AF\u94B0\u94B2\u94B4\u94B6", 4, "\u94BC\u94BD\u94BF\u94C4\u94C8", 6, "\u94D0\u94D1\u94D2\u94D5\u94D6\u94D7\u94D9\u94D8\u94DB\u94DE\u94DF\u94E0\u94E2\u94E4\u94E5\u94E7\u94E8\u94EA"], - ["ef40", "\u986F", 5, "\u988B\u988E\u9892\u9895\u9899\u98A3\u98A8", 37, "\u98CF\u98D0\u98D4\u98D6\u98D7\u98DB\u98DC\u98DD\u98E0", 4], - ["ef80", "\u98E5\u98E6\u98E9", 30, "\u94E9\u94EB\u94EE\u94EF\u94F3\u94F4\u94F5\u94F7\u94F9\u94FC\u94FD\u94FF\u9503\u9502\u9506\u9507\u9509\u950A\u950D\u950E\u950F\u9512", 4, "\u9518\u951B\u951D\u951E\u951F\u9522\u952A\u952B\u9529\u952C\u9531\u9532\u9534\u9536\u9537\u9538\u953C\u953E\u953F\u9542\u9535\u9544\u9545\u9546\u9549\u954C\u954E\u954F\u9552\u9553\u9554\u9556\u9557\u9558\u9559\u955B\u955E\u955F\u955D\u9561\u9562\u9564", 8, "\u956F\u9571\u9572\u9573\u953A\u77E7\u77EC\u96C9\u79D5\u79ED\u79E3\u79EB\u7A06\u5D47\u7A03\u7A02\u7A1E\u7A14"], - ["f040", "\u9908", 4, "\u990E\u990F\u9911", 28, "\u992F", 26], - ["f080", "\u994A", 9, "\u9956", 12, "\u9964\u9966\u9973\u9978\u9979\u997B\u997E\u9982\u9983\u9989\u7A39\u7A37\u7A51\u9ECF\u99A5\u7A70\u7688\u768E\u7693\u7699\u76A4\u74DE\u74E0\u752C\u9E20\u9E22\u9E28", 4, "\u9E32\u9E31\u9E36\u9E38\u9E37\u9E39\u9E3A\u9E3E\u9E41\u9E42\u9E44\u9E46\u9E47\u9E48\u9E49\u9E4B\u9E4C\u9E4E\u9E51\u9E55\u9E57\u9E5A\u9E5B\u9E5C\u9E5E\u9E63\u9E66", 6, "\u9E71\u9E6D\u9E73\u7592\u7594\u7596\u75A0\u759D\u75AC\u75A3\u75B3\u75B4\u75B8\u75C4\u75B1\u75B0\u75C3\u75C2\u75D6\u75CD\u75E3\u75E8\u75E6\u75E4\u75EB\u75E7\u7603\u75F1\u75FC\u75FF\u7610\u7600\u7605\u760C\u7617\u760A\u7625\u7618\u7615\u7619"], - ["f140", "\u998C\u998E\u999A", 10, "\u99A6\u99A7\u99A9", 47], - ["f180", "\u99D9", 32, "\u761B\u763C\u7622\u7620\u7640\u762D\u7630\u763F\u7635\u7643\u763E\u7633\u764D\u765E\u7654\u765C\u7656\u766B\u766F\u7FCA\u7AE6\u7A78\u7A79\u7A80\u7A86\u7A88\u7A95\u7AA6\u7AA0\u7AAC\u7AA8\u7AAD\u7AB3\u8864\u8869\u8872\u887D\u887F\u8882\u88A2\u88C6\u88B7\u88BC\u88C9\u88E2\u88CE\u88E3\u88E5\u88F1\u891A\u88FC\u88E8\u88FE\u88F0\u8921\u8919\u8913\u891B\u890A\u8934\u892B\u8936\u8941\u8966\u897B\u758B\u80E5\u76B2\u76B4\u77DC\u8012\u8014\u8016\u801C\u8020\u8022\u8025\u8026\u8027\u8029\u8028\u8031\u800B\u8035\u8043\u8046\u804D\u8052\u8069\u8071\u8983\u9878\u9880\u9883"], - ["f240", "\u99FA", 62], - ["f280", "\u9A39", 32, "\u9889\u988C\u988D\u988F\u9894\u989A\u989B\u989E\u989F\u98A1\u98A2\u98A5\u98A6\u864D\u8654\u866C\u866E\u867F\u867A\u867C\u867B\u86A8\u868D\u868B\u86AC\u869D\u86A7\u86A3\u86AA\u8693\u86A9\u86B6\u86C4\u86B5\u86CE\u86B0\u86BA\u86B1\u86AF\u86C9\u86CF\u86B4\u86E9\u86F1\u86F2\u86ED\u86F3\u86D0\u8713\u86DE\u86F4\u86DF\u86D8\u86D1\u8703\u8707\u86F8\u8708\u870A\u870D\u8709\u8723\u873B\u871E\u8725\u872E\u871A\u873E\u8748\u8734\u8731\u8729\u8737\u873F\u8782\u8722\u877D\u877E\u877B\u8760\u8770\u874C\u876E\u878B\u8753\u8763\u877C\u8764\u8759\u8765\u8793\u87AF\u87A8\u87D2"], - ["f340", "\u9A5A", 17, "\u9A72\u9A83\u9A89\u9A8D\u9A8E\u9A94\u9A95\u9A99\u9AA6\u9AA9", 6, "\u9AB2\u9AB3\u9AB4\u9AB5\u9AB9\u9ABB\u9ABD\u9ABE\u9ABF\u9AC3\u9AC4\u9AC6", 4, "\u9ACD\u9ACE\u9ACF\u9AD0\u9AD2\u9AD4\u9AD5\u9AD6\u9AD7\u9AD9\u9ADA\u9ADB\u9ADC"], - ["f380", "\u9ADD\u9ADE\u9AE0\u9AE2\u9AE3\u9AE4\u9AE5\u9AE7\u9AE8\u9AE9\u9AEA\u9AEC\u9AEE\u9AF0", 8, "\u9AFA\u9AFC", 6, "\u9B04\u9B05\u9B06\u87C6\u8788\u8785\u87AD\u8797\u8783\u87AB\u87E5\u87AC\u87B5\u87B3\u87CB\u87D3\u87BD\u87D1\u87C0\u87CA\u87DB\u87EA\u87E0\u87EE\u8816\u8813\u87FE\u880A\u881B\u8821\u8839\u883C\u7F36\u7F42\u7F44\u7F45\u8210\u7AFA\u7AFD\u7B08\u7B03\u7B04\u7B15\u7B0A\u7B2B\u7B0F\u7B47\u7B38\u7B2A\u7B19\u7B2E\u7B31\u7B20\u7B25\u7B24\u7B33\u7B3E\u7B1E\u7B58\u7B5A\u7B45\u7B75\u7B4C\u7B5D\u7B60\u7B6E\u7B7B\u7B62\u7B72\u7B71\u7B90\u7BA6\u7BA7\u7BB8\u7BAC\u7B9D\u7BA8\u7B85\u7BAA\u7B9C\u7BA2\u7BAB\u7BB4\u7BD1\u7BC1\u7BCC\u7BDD\u7BDA\u7BE5\u7BE6\u7BEA\u7C0C\u7BFE\u7BFC\u7C0F\u7C16\u7C0B"], - ["f440", "\u9B07\u9B09", 5, "\u9B10\u9B11\u9B12\u9B14", 10, "\u9B20\u9B21\u9B22\u9B24", 10, "\u9B30\u9B31\u9B33", 7, "\u9B3D\u9B3E\u9B3F\u9B40\u9B46\u9B4A\u9B4B\u9B4C\u9B4E\u9B50\u9B52\u9B53\u9B55", 5], - ["f480", "\u9B5B", 32, "\u7C1F\u7C2A\u7C26\u7C38\u7C41\u7C40\u81FE\u8201\u8202\u8204\u81EC\u8844\u8221\u8222\u8223\u822D\u822F\u8228\u822B\u8238\u823B\u8233\u8234\u823E\u8244\u8249\u824B\u824F\u825A\u825F\u8268\u887E\u8885\u8888\u88D8\u88DF\u895E\u7F9D\u7F9F\u7FA7\u7FAF\u7FB0\u7FB2\u7C7C\u6549\u7C91\u7C9D\u7C9C\u7C9E\u7CA2\u7CB2\u7CBC\u7CBD\u7CC1\u7CC7\u7CCC\u7CCD\u7CC8\u7CC5\u7CD7\u7CE8\u826E\u66A8\u7FBF\u7FCE\u7FD5\u7FE5\u7FE1\u7FE6\u7FE9\u7FEE\u7FF3\u7CF8\u7D77\u7DA6\u7DAE\u7E47\u7E9B\u9EB8\u9EB4\u8D73\u8D84\u8D94\u8D91\u8DB1\u8D67\u8D6D\u8C47\u8C49\u914A\u9150\u914E\u914F\u9164"], - ["f540", "\u9B7C", 62], - ["f580", "\u9BBB", 32, "\u9162\u9161\u9170\u9169\u916F\u917D\u917E\u9172\u9174\u9179\u918C\u9185\u9190\u918D\u9191\u91A2\u91A3\u91AA\u91AD\u91AE\u91AF\u91B5\u91B4\u91BA\u8C55\u9E7E\u8DB8\u8DEB\u8E05\u8E59\u8E69\u8DB5\u8DBF\u8DBC\u8DBA\u8DC4\u8DD6\u8DD7\u8DDA\u8DDE\u8DCE\u8DCF\u8DDB\u8DC6\u8DEC\u8DF7\u8DF8\u8DE3\u8DF9\u8DFB\u8DE4\u8E09\u8DFD\u8E14\u8E1D\u8E1F\u8E2C\u8E2E\u8E23\u8E2F\u8E3A\u8E40\u8E39\u8E35\u8E3D\u8E31\u8E49\u8E41\u8E42\u8E51\u8E52\u8E4A\u8E70\u8E76\u8E7C\u8E6F\u8E74\u8E85\u8E8F\u8E94\u8E90\u8E9C\u8E9E\u8C78\u8C82\u8C8A\u8C85\u8C98\u8C94\u659B\u89D6\u89DE\u89DA\u89DC"], - ["f640", "\u9BDC", 62], - ["f680", "\u9C1B", 32, "\u89E5\u89EB\u89EF\u8A3E\u8B26\u9753\u96E9\u96F3\u96EF\u9706\u9701\u9708\u970F\u970E\u972A\u972D\u9730\u973E\u9F80\u9F83\u9F85", 5, "\u9F8C\u9EFE\u9F0B\u9F0D\u96B9\u96BC\u96BD\u96CE\u96D2\u77BF\u96E0\u928E\u92AE\u92C8\u933E\u936A\u93CA\u938F\u943E\u946B\u9C7F\u9C82\u9C85\u9C86\u9C87\u9C88\u7A23\u9C8B\u9C8E\u9C90\u9C91\u9C92\u9C94\u9C95\u9C9A\u9C9B\u9C9E", 5, "\u9CA5", 4, "\u9CAB\u9CAD\u9CAE\u9CB0", 7, "\u9CBA\u9CBB\u9CBC\u9CBD\u9CC4\u9CC5\u9CC6\u9CC7\u9CCA\u9CCB"], - ["f740", "\u9C3C", 62], - ["f780", "\u9C7B\u9C7D\u9C7E\u9C80\u9C83\u9C84\u9C89\u9C8A\u9C8C\u9C8F\u9C93\u9C96\u9C97\u9C98\u9C99\u9C9D\u9CAA\u9CAC\u9CAF\u9CB9\u9CBE", 4, "\u9CC8\u9CC9\u9CD1\u9CD2\u9CDA\u9CDB\u9CE0\u9CE1\u9CCC", 4, "\u9CD3\u9CD4\u9CD5\u9CD7\u9CD8\u9CD9\u9CDC\u9CDD\u9CDF\u9CE2\u977C\u9785\u9791\u9792\u9794\u97AF\u97AB\u97A3\u97B2\u97B4\u9AB1\u9AB0\u9AB7\u9E58\u9AB6\u9ABA\u9ABC\u9AC1\u9AC0\u9AC5\u9AC2\u9ACB\u9ACC\u9AD1\u9B45\u9B43\u9B47\u9B49\u9B48\u9B4D\u9B51\u98E8\u990D\u992E\u9955\u9954\u9ADF\u9AE1\u9AE6\u9AEF\u9AEB\u9AFB\u9AED\u9AF9\u9B08\u9B0F\u9B13\u9B1F\u9B23\u9EBD\u9EBE\u7E3B\u9E82\u9E87\u9E88\u9E8B\u9E92\u93D6\u9E9D\u9E9F\u9EDB\u9EDC\u9EDD\u9EE0\u9EDF\u9EE2\u9EE9\u9EE7\u9EE5\u9EEA\u9EEF\u9F22\u9F2C\u9F2F\u9F39\u9F37\u9F3D\u9F3E\u9F44"], - ["f840", "\u9CE3", 62], - ["f880", "\u9D22", 32], - ["f940", "\u9D43", 62], - ["f980", "\u9D82", 32], - ["fa40", "\u9DA3", 62], - ["fa80", "\u9DE2", 32], - ["fb40", "\u9E03", 27, "\u9E24\u9E27\u9E2E\u9E30\u9E34\u9E3B\u9E3C\u9E40\u9E4D\u9E50\u9E52\u9E53\u9E54\u9E56\u9E59\u9E5D\u9E5F\u9E60\u9E61\u9E62\u9E65\u9E6E\u9E6F\u9E72\u9E74", 9, "\u9E80"], - ["fb80", "\u9E81\u9E83\u9E84\u9E85\u9E86\u9E89\u9E8A\u9E8C", 5, "\u9E94", 8, "\u9E9E\u9EA0", 5, "\u9EA7\u9EA8\u9EA9\u9EAA"], - ["fc40", "\u9EAB", 8, "\u9EB5\u9EB6\u9EB7\u9EB9\u9EBA\u9EBC\u9EBF", 4, "\u9EC5\u9EC6\u9EC7\u9EC8\u9ECA\u9ECB\u9ECC\u9ED0\u9ED2\u9ED3\u9ED5\u9ED6\u9ED7\u9ED9\u9EDA\u9EDE\u9EE1\u9EE3\u9EE4\u9EE6\u9EE8\u9EEB\u9EEC\u9EED\u9EEE\u9EF0", 8, "\u9EFA\u9EFD\u9EFF", 6], - ["fc80", "\u9F06", 4, "\u9F0C\u9F0F\u9F11\u9F12\u9F14\u9F15\u9F16\u9F18\u9F1A", 5, "\u9F21\u9F23", 8, "\u9F2D\u9F2E\u9F30\u9F31"], - ["fd40", "\u9F32", 4, "\u9F38\u9F3A\u9F3C\u9F3F", 4, "\u9F45", 10, "\u9F52", 38], - ["fd80", "\u9F79", 5, "\u9F81\u9F82\u9F8D", 11, "\u9F9C\u9F9D\u9F9E\u9FA1", 4, "\uF92C\uF979\uF995\uF9E7\uF9F1"], - ["fe40", "\uFA0C\uFA0D\uFA0E\uFA0F\uFA11\uFA13\uFA14\uFA18\uFA1F\uFA20\uFA21\uFA23\uFA24\uFA27\uFA28\uFA29"] - ]; - } -}); - -// node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/encodings/tables/gbk-added.json -var require_gbk_added = __commonJS({ - "node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/encodings/tables/gbk-added.json"(exports, module) { - module.exports = [ - ["a140", "\uE4C6", 62], - ["a180", "\uE505", 32], - ["a240", "\uE526", 62], - ["a280", "\uE565", 32], - ["a2ab", "\uE766", 5], - ["a2e3", "\u20AC\uE76D"], - ["a2ef", "\uE76E\uE76F"], - ["a2fd", "\uE770\uE771"], - ["a340", "\uE586", 62], - ["a380", "\uE5C5", 31, "\u3000"], - ["a440", "\uE5E6", 62], - ["a480", "\uE625", 32], - ["a4f4", "\uE772", 10], - ["a540", "\uE646", 62], - ["a580", "\uE685", 32], - ["a5f7", "\uE77D", 7], - ["a640", "\uE6A6", 62], - ["a680", "\uE6E5", 32], - ["a6b9", "\uE785", 7], - ["a6d9", "\uE78D", 6], - ["a6ec", "\uE794\uE795"], - ["a6f3", "\uE796"], - ["a6f6", "\uE797", 8], - ["a740", "\uE706", 62], - ["a780", "\uE745", 32], - ["a7c2", "\uE7A0", 14], - ["a7f2", "\uE7AF", 12], - ["a896", "\uE7BC", 10], - ["a8bc", "\u1E3F"], - ["a8bf", "\u01F9"], - ["a8c1", "\uE7C9\uE7CA\uE7CB\uE7CC"], - ["a8ea", "\uE7CD", 20], - ["a958", "\uE7E2"], - ["a95b", "\uE7E3"], - ["a95d", "\uE7E4\uE7E5\uE7E6"], - ["a989", "\u303E\u2FF0", 11], - ["a997", "\uE7F4", 12], - ["a9f0", "\uE801", 14], - ["aaa1", "\uE000", 93], - ["aba1", "\uE05E", 93], - ["aca1", "\uE0BC", 93], - ["ada1", "\uE11A", 93], - ["aea1", "\uE178", 93], - ["afa1", "\uE1D6", 93], - ["d7fa", "\uE810", 4], - ["f8a1", "\uE234", 93], - ["f9a1", "\uE292", 93], - ["faa1", "\uE2F0", 93], - ["fba1", "\uE34E", 93], - ["fca1", "\uE3AC", 93], - ["fda1", "\uE40A", 93], - ["fe50", "\u2E81\uE816\uE817\uE818\u2E84\u3473\u3447\u2E88\u2E8B\uE81E\u359E\u361A\u360E\u2E8C\u2E97\u396E\u3918\uE826\u39CF\u39DF\u3A73\u39D0\uE82B\uE82C\u3B4E\u3C6E\u3CE0\u2EA7\uE831\uE832\u2EAA\u4056\u415F\u2EAE\u4337\u2EB3\u2EB6\u2EB7\uE83B\u43B1\u43AC\u2EBB\u43DD\u44D6\u4661\u464C\uE843"], - ["fe80", "\u4723\u4729\u477C\u478D\u2ECA\u4947\u497A\u497D\u4982\u4983\u4985\u4986\u499F\u499B\u49B7\u49B6\uE854\uE855\u4CA3\u4C9F\u4CA0\u4CA1\u4C77\u4CA2\u4D13", 6, "\u4DAE\uE864\uE468", 93], - ["8135f437", "\uE7C7"] - ]; - } -}); - -// node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/encodings/tables/gb18030-ranges.json -var require_gb18030_ranges = __commonJS({ - "node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/encodings/tables/gb18030-ranges.json"(exports, module) { - module.exports = { uChars: [128, 165, 169, 178, 184, 216, 226, 235, 238, 244, 248, 251, 253, 258, 276, 284, 300, 325, 329, 334, 364, 463, 465, 467, 469, 471, 473, 475, 477, 506, 594, 610, 712, 716, 730, 930, 938, 962, 970, 1026, 1104, 1106, 8209, 8215, 8218, 8222, 8231, 8241, 8244, 8246, 8252, 8365, 8452, 8454, 8458, 8471, 8482, 8556, 8570, 8596, 8602, 8713, 8720, 8722, 8726, 8731, 8737, 8740, 8742, 8748, 8751, 8760, 8766, 8777, 8781, 8787, 8802, 8808, 8816, 8854, 8858, 8870, 8896, 8979, 9322, 9372, 9548, 9588, 9616, 9622, 9634, 9652, 9662, 9672, 9676, 9680, 9702, 9735, 9738, 9793, 9795, 11906, 11909, 11913, 11917, 11928, 11944, 11947, 11951, 11956, 11960, 11964, 11979, 12284, 12292, 12312, 12319, 12330, 12351, 12436, 12447, 12535, 12543, 12586, 12842, 12850, 12964, 13200, 13215, 13218, 13253, 13263, 13267, 13270, 13384, 13428, 13727, 13839, 13851, 14617, 14703, 14801, 14816, 14964, 15183, 15471, 15585, 16471, 16736, 17208, 17325, 17330, 17374, 17623, 17997, 18018, 18212, 18218, 18301, 18318, 18760, 18811, 18814, 18820, 18823, 18844, 18848, 18872, 19576, 19620, 19738, 19887, 40870, 59244, 59336, 59367, 59413, 59417, 59423, 59431, 59437, 59443, 59452, 59460, 59478, 59493, 63789, 63866, 63894, 63976, 63986, 64016, 64018, 64021, 64025, 64034, 64037, 64042, 65074, 65093, 65107, 65112, 65127, 65132, 65375, 65510, 65536], gbChars: [0, 36, 38, 45, 50, 81, 89, 95, 96, 100, 103, 104, 105, 109, 126, 133, 148, 172, 175, 179, 208, 306, 307, 308, 309, 310, 311, 312, 313, 341, 428, 443, 544, 545, 558, 741, 742, 749, 750, 805, 819, 820, 7922, 7924, 7925, 7927, 7934, 7943, 7944, 7945, 7950, 8062, 8148, 8149, 8152, 8164, 8174, 8236, 8240, 8262, 8264, 8374, 8380, 8381, 8384, 8388, 8390, 8392, 8393, 8394, 8396, 8401, 8406, 8416, 8419, 8424, 8437, 8439, 8445, 8482, 8485, 8496, 8521, 8603, 8936, 8946, 9046, 9050, 9063, 9066, 9076, 9092, 9100, 9108, 9111, 9113, 9131, 9162, 9164, 9218, 9219, 11329, 11331, 11334, 11336, 11346, 11361, 11363, 11366, 11370, 11372, 11375, 11389, 11682, 11686, 11687, 11692, 11694, 11714, 11716, 11723, 11725, 11730, 11736, 11982, 11989, 12102, 12336, 12348, 12350, 12384, 12393, 12395, 12397, 12510, 12553, 12851, 12962, 12973, 13738, 13823, 13919, 13933, 14080, 14298, 14585, 14698, 15583, 15847, 16318, 16434, 16438, 16481, 16729, 17102, 17122, 17315, 17320, 17402, 17418, 17859, 17909, 17911, 17915, 17916, 17936, 17939, 17961, 18664, 18703, 18814, 18962, 19043, 33469, 33470, 33471, 33484, 33485, 33490, 33497, 33501, 33505, 33513, 33520, 33536, 33550, 37845, 37921, 37948, 38029, 38038, 38064, 38065, 38066, 38069, 38075, 38076, 38078, 39108, 39109, 39113, 39114, 39115, 39116, 39265, 39394, 189e3] }; - } -}); - -// node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/encodings/tables/cp949.json -var require_cp949 = __commonJS({ - "node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/encodings/tables/cp949.json"(exports, module) { - module.exports = [ - ["0", "\0", 127], - ["8141", "\uAC02\uAC03\uAC05\uAC06\uAC0B", 4, "\uAC18\uAC1E\uAC1F\uAC21\uAC22\uAC23\uAC25", 6, "\uAC2E\uAC32\uAC33\uAC34"], - ["8161", "\uAC35\uAC36\uAC37\uAC3A\uAC3B\uAC3D\uAC3E\uAC3F\uAC41", 9, "\uAC4C\uAC4E", 5, "\uAC55"], - ["8181", "\uAC56\uAC57\uAC59\uAC5A\uAC5B\uAC5D", 18, "\uAC72\uAC73\uAC75\uAC76\uAC79\uAC7B", 4, "\uAC82\uAC87\uAC88\uAC8D\uAC8E\uAC8F\uAC91\uAC92\uAC93\uAC95", 6, "\uAC9E\uACA2", 5, "\uACAB\uACAD\uACAE\uACB1", 6, "\uACBA\uACBE\uACBF\uACC0\uACC2\uACC3\uACC5\uACC6\uACC7\uACC9\uACCA\uACCB\uACCD", 7, "\uACD6\uACD8", 7, "\uACE2\uACE3\uACE5\uACE6\uACE9\uACEB\uACED\uACEE\uACF2\uACF4\uACF7", 4, "\uACFE\uACFF\uAD01\uAD02\uAD03\uAD05\uAD07", 4, "\uAD0E\uAD10\uAD12\uAD13"], - ["8241", "\uAD14\uAD15\uAD16\uAD17\uAD19\uAD1A\uAD1B\uAD1D\uAD1E\uAD1F\uAD21", 7, "\uAD2A\uAD2B\uAD2E", 5], - ["8261", "\uAD36\uAD37\uAD39\uAD3A\uAD3B\uAD3D", 6, "\uAD46\uAD48\uAD4A", 5, "\uAD51\uAD52\uAD53\uAD55\uAD56\uAD57"], - ["8281", "\uAD59", 7, "\uAD62\uAD64", 7, "\uAD6E\uAD6F\uAD71\uAD72\uAD77\uAD78\uAD79\uAD7A\uAD7E\uAD80\uAD83", 4, "\uAD8A\uAD8B\uAD8D\uAD8E\uAD8F\uAD91", 10, "\uAD9E", 5, "\uADA5", 17, "\uADB8", 7, "\uADC2\uADC3\uADC5\uADC6\uADC7\uADC9", 6, "\uADD2\uADD4", 7, "\uADDD\uADDE\uADDF\uADE1\uADE2\uADE3\uADE5", 18], - ["8341", "\uADFA\uADFB\uADFD\uADFE\uAE02", 5, "\uAE0A\uAE0C\uAE0E", 5, "\uAE15", 7], - ["8361", "\uAE1D", 18, "\uAE32\uAE33\uAE35\uAE36\uAE39\uAE3B\uAE3C"], - ["8381", "\uAE3D\uAE3E\uAE3F\uAE42\uAE44\uAE47\uAE48\uAE49\uAE4B\uAE4F\uAE51\uAE52\uAE53\uAE55\uAE57", 4, "\uAE5E\uAE62\uAE63\uAE64\uAE66\uAE67\uAE6A\uAE6B\uAE6D\uAE6E\uAE6F\uAE71", 6, "\uAE7A\uAE7E", 5, "\uAE86", 5, "\uAE8D", 46, "\uAEBF\uAEC1\uAEC2\uAEC3\uAEC5", 6, "\uAECE\uAED2", 5, "\uAEDA\uAEDB\uAEDD", 8], - ["8441", "\uAEE6\uAEE7\uAEE9\uAEEA\uAEEC\uAEEE", 5, "\uAEF5\uAEF6\uAEF7\uAEF9\uAEFA\uAEFB\uAEFD", 8], - ["8461", "\uAF06\uAF09\uAF0A\uAF0B\uAF0C\uAF0E\uAF0F\uAF11", 18], - ["8481", "\uAF24", 7, "\uAF2E\uAF2F\uAF31\uAF33\uAF35", 6, "\uAF3E\uAF40\uAF44\uAF45\uAF46\uAF47\uAF4A", 5, "\uAF51", 10, "\uAF5E", 5, "\uAF66", 18, "\uAF7A", 5, "\uAF81\uAF82\uAF83\uAF85\uAF86\uAF87\uAF89", 6, "\uAF92\uAF93\uAF94\uAF96", 5, "\uAF9D", 26, "\uAFBA\uAFBB\uAFBD\uAFBE"], - ["8541", "\uAFBF\uAFC1", 5, "\uAFCA\uAFCC\uAFCF", 4, "\uAFD5", 6, "\uAFDD", 4], - ["8561", "\uAFE2", 5, "\uAFEA", 5, "\uAFF2\uAFF3\uAFF5\uAFF6\uAFF7\uAFF9", 6, "\uB002\uB003"], - ["8581", "\uB005", 6, "\uB00D\uB00E\uB00F\uB011\uB012\uB013\uB015", 6, "\uB01E", 9, "\uB029", 26, "\uB046\uB047\uB049\uB04B\uB04D\uB04F\uB050\uB051\uB052\uB056\uB058\uB05A\uB05B\uB05C\uB05E", 29, "\uB07E\uB07F\uB081\uB082\uB083\uB085", 6, "\uB08E\uB090\uB092", 5, "\uB09B\uB09D\uB09E\uB0A3\uB0A4"], - ["8641", "\uB0A5\uB0A6\uB0A7\uB0AA\uB0B0\uB0B2\uB0B6\uB0B7\uB0B9\uB0BA\uB0BB\uB0BD", 6, "\uB0C6\uB0CA", 5, "\uB0D2"], - ["8661", "\uB0D3\uB0D5\uB0D6\uB0D7\uB0D9", 6, "\uB0E1\uB0E2\uB0E3\uB0E4\uB0E6", 10], - ["8681", "\uB0F1", 22, "\uB10A\uB10D\uB10E\uB10F\uB111\uB114\uB115\uB116\uB117\uB11A\uB11E", 4, "\uB126\uB127\uB129\uB12A\uB12B\uB12D", 6, "\uB136\uB13A", 5, "\uB142\uB143\uB145\uB146\uB147\uB149", 6, "\uB152\uB153\uB156\uB157\uB159\uB15A\uB15B\uB15D\uB15E\uB15F\uB161", 22, "\uB17A\uB17B\uB17D\uB17E\uB17F\uB181\uB183", 4, "\uB18A\uB18C\uB18E\uB18F\uB190\uB191\uB195\uB196\uB197\uB199\uB19A\uB19B\uB19D"], - ["8741", "\uB19E", 9, "\uB1A9", 15], - ["8761", "\uB1B9", 18, "\uB1CD\uB1CE\uB1CF\uB1D1\uB1D2\uB1D3\uB1D5"], - ["8781", "\uB1D6", 5, "\uB1DE\uB1E0", 7, "\uB1EA\uB1EB\uB1ED\uB1EE\uB1EF\uB1F1", 7, "\uB1FA\uB1FC\uB1FE", 5, "\uB206\uB207\uB209\uB20A\uB20D", 6, "\uB216\uB218\uB21A", 5, "\uB221", 18, "\uB235", 6, "\uB23D", 26, "\uB259\uB25A\uB25B\uB25D\uB25E\uB25F\uB261", 6, "\uB26A", 4], - ["8841", "\uB26F", 4, "\uB276", 5, "\uB27D", 6, "\uB286\uB287\uB288\uB28A", 4], - ["8861", "\uB28F\uB292\uB293\uB295\uB296\uB297\uB29B", 4, "\uB2A2\uB2A4\uB2A7\uB2A8\uB2A9\uB2AB\uB2AD\uB2AE\uB2AF\uB2B1\uB2B2\uB2B3\uB2B5\uB2B6\uB2B7"], - ["8881", "\uB2B8", 15, "\uB2CA\uB2CB\uB2CD\uB2CE\uB2CF\uB2D1\uB2D3", 4, "\uB2DA\uB2DC\uB2DE\uB2DF\uB2E0\uB2E1\uB2E3\uB2E7\uB2E9\uB2EA\uB2F0\uB2F1\uB2F2\uB2F6\uB2FC\uB2FD\uB2FE\uB302\uB303\uB305\uB306\uB307\uB309", 6, "\uB312\uB316", 5, "\uB31D", 54, "\uB357\uB359\uB35A\uB35D\uB360\uB361\uB362\uB363"], - ["8941", "\uB366\uB368\uB36A\uB36C\uB36D\uB36F\uB372\uB373\uB375\uB376\uB377\uB379", 6, "\uB382\uB386", 5, "\uB38D"], - ["8961", "\uB38E\uB38F\uB391\uB392\uB393\uB395", 10, "\uB3A2", 5, "\uB3A9\uB3AA\uB3AB\uB3AD"], - ["8981", "\uB3AE", 21, "\uB3C6\uB3C7\uB3C9\uB3CA\uB3CD\uB3CF\uB3D1\uB3D2\uB3D3\uB3D6\uB3D8\uB3DA\uB3DC\uB3DE\uB3DF\uB3E1\uB3E2\uB3E3\uB3E5\uB3E6\uB3E7\uB3E9", 18, "\uB3FD", 18, "\uB411", 6, "\uB419\uB41A\uB41B\uB41D\uB41E\uB41F\uB421", 6, "\uB42A\uB42C", 7, "\uB435", 15], - ["8a41", "\uB445", 10, "\uB452\uB453\uB455\uB456\uB457\uB459", 6, "\uB462\uB464\uB466"], - ["8a61", "\uB467", 4, "\uB46D", 18, "\uB481\uB482"], - ["8a81", "\uB483", 4, "\uB489", 19, "\uB49E", 5, "\uB4A5\uB4A6\uB4A7\uB4A9\uB4AA\uB4AB\uB4AD", 7, "\uB4B6\uB4B8\uB4BA", 5, "\uB4C1\uB4C2\uB4C3\uB4C5\uB4C6\uB4C7\uB4C9", 6, "\uB4D1\uB4D2\uB4D3\uB4D4\uB4D6", 5, "\uB4DE\uB4DF\uB4E1\uB4E2\uB4E5\uB4E7", 4, "\uB4EE\uB4F0\uB4F2", 5, "\uB4F9", 26, "\uB516\uB517\uB519\uB51A\uB51D"], - ["8b41", "\uB51E", 5, "\uB526\uB52B", 4, "\uB532\uB533\uB535\uB536\uB537\uB539", 6, "\uB542\uB546"], - ["8b61", "\uB547\uB548\uB549\uB54A\uB54E\uB54F\uB551\uB552\uB553\uB555", 6, "\uB55E\uB562", 8], - ["8b81", "\uB56B", 52, "\uB5A2\uB5A3\uB5A5\uB5A6\uB5A7\uB5A9\uB5AC\uB5AD\uB5AE\uB5AF\uB5B2\uB5B6", 4, "\uB5BE\uB5BF\uB5C1\uB5C2\uB5C3\uB5C5", 6, "\uB5CE\uB5D2", 5, "\uB5D9", 18, "\uB5ED", 18], - ["8c41", "\uB600", 15, "\uB612\uB613\uB615\uB616\uB617\uB619", 4], - ["8c61", "\uB61E", 6, "\uB626", 5, "\uB62D", 6, "\uB635", 5], - ["8c81", "\uB63B", 12, "\uB649", 26, "\uB665\uB666\uB667\uB669", 50, "\uB69E\uB69F\uB6A1\uB6A2\uB6A3\uB6A5", 5, "\uB6AD\uB6AE\uB6AF\uB6B0\uB6B2", 16], - ["8d41", "\uB6C3", 16, "\uB6D5", 8], - ["8d61", "\uB6DE", 17, "\uB6F1\uB6F2\uB6F3\uB6F5\uB6F6\uB6F7\uB6F9\uB6FA"], - ["8d81", "\uB6FB", 4, "\uB702\uB703\uB704\uB706", 33, "\uB72A\uB72B\uB72D\uB72E\uB731", 6, "\uB73A\uB73C", 7, "\uB745\uB746\uB747\uB749\uB74A\uB74B\uB74D", 6, "\uB756", 9, "\uB761\uB762\uB763\uB765\uB766\uB767\uB769", 6, "\uB772\uB774\uB776", 5, "\uB77E\uB77F\uB781\uB782\uB783\uB785", 6, "\uB78E\uB793\uB794\uB795\uB79A\uB79B\uB79D\uB79E"], - ["8e41", "\uB79F\uB7A1", 6, "\uB7AA\uB7AE", 5, "\uB7B6\uB7B7\uB7B9", 8], - ["8e61", "\uB7C2", 4, "\uB7C8\uB7CA", 19], - ["8e81", "\uB7DE", 13, "\uB7EE\uB7EF\uB7F1\uB7F2\uB7F3\uB7F5", 6, "\uB7FE\uB802", 4, "\uB80A\uB80B\uB80D\uB80E\uB80F\uB811", 6, "\uB81A\uB81C\uB81E", 5, "\uB826\uB827\uB829\uB82A\uB82B\uB82D", 6, "\uB836\uB83A", 5, "\uB841\uB842\uB843\uB845", 11, "\uB852\uB854", 7, "\uB85E\uB85F\uB861\uB862\uB863\uB865", 6, "\uB86E\uB870\uB872", 5, "\uB879\uB87A\uB87B\uB87D", 7], - ["8f41", "\uB885", 7, "\uB88E", 17], - ["8f61", "\uB8A0", 7, "\uB8A9", 6, "\uB8B1\uB8B2\uB8B3\uB8B5\uB8B6\uB8B7\uB8B9", 4], - ["8f81", "\uB8BE\uB8BF\uB8C2\uB8C4\uB8C6", 5, "\uB8CD\uB8CE\uB8CF\uB8D1\uB8D2\uB8D3\uB8D5", 7, "\uB8DE\uB8E0\uB8E2", 5, "\uB8EA\uB8EB\uB8ED\uB8EE\uB8EF\uB8F1", 6, "\uB8FA\uB8FC\uB8FE", 5, "\uB905", 18, "\uB919", 6, "\uB921", 26, "\uB93E\uB93F\uB941\uB942\uB943\uB945", 6, "\uB94D\uB94E\uB950\uB952", 5], - ["9041", "\uB95A\uB95B\uB95D\uB95E\uB95F\uB961", 6, "\uB96A\uB96C\uB96E", 5, "\uB976\uB977\uB979\uB97A\uB97B\uB97D"], - ["9061", "\uB97E", 5, "\uB986\uB988\uB98B\uB98C\uB98F", 15], - ["9081", "\uB99F", 12, "\uB9AE\uB9AF\uB9B1\uB9B2\uB9B3\uB9B5", 6, "\uB9BE\uB9C0\uB9C2", 5, "\uB9CA\uB9CB\uB9CD\uB9D3", 4, "\uB9DA\uB9DC\uB9DF\uB9E0\uB9E2\uB9E6\uB9E7\uB9E9\uB9EA\uB9EB\uB9ED", 6, "\uB9F6\uB9FB", 4, "\uBA02", 5, "\uBA09", 11, "\uBA16", 33, "\uBA3A\uBA3B\uBA3D\uBA3E\uBA3F\uBA41\uBA43\uBA44\uBA45\uBA46"], - ["9141", "\uBA47\uBA4A\uBA4C\uBA4F\uBA50\uBA51\uBA52\uBA56\uBA57\uBA59\uBA5A\uBA5B\uBA5D", 6, "\uBA66\uBA6A", 5], - ["9161", "\uBA72\uBA73\uBA75\uBA76\uBA77\uBA79", 9, "\uBA86\uBA88\uBA89\uBA8A\uBA8B\uBA8D", 5], - ["9181", "\uBA93", 20, "\uBAAA\uBAAD\uBAAE\uBAAF\uBAB1\uBAB3", 4, "\uBABA\uBABC\uBABE", 5, "\uBAC5\uBAC6\uBAC7\uBAC9", 14, "\uBADA", 33, "\uBAFD\uBAFE\uBAFF\uBB01\uBB02\uBB03\uBB05", 7, "\uBB0E\uBB10\uBB12", 5, "\uBB19\uBB1A\uBB1B\uBB1D\uBB1E\uBB1F\uBB21", 6], - ["9241", "\uBB28\uBB2A\uBB2C", 7, "\uBB37\uBB39\uBB3A\uBB3F", 4, "\uBB46\uBB48\uBB4A\uBB4B\uBB4C\uBB4E\uBB51\uBB52"], - ["9261", "\uBB53\uBB55\uBB56\uBB57\uBB59", 7, "\uBB62\uBB64", 7, "\uBB6D", 4], - ["9281", "\uBB72", 21, "\uBB89\uBB8A\uBB8B\uBB8D\uBB8E\uBB8F\uBB91", 18, "\uBBA5\uBBA6\uBBA7\uBBA9\uBBAA\uBBAB\uBBAD", 6, "\uBBB5\uBBB6\uBBB8", 7, "\uBBC1\uBBC2\uBBC3\uBBC5\uBBC6\uBBC7\uBBC9", 6, "\uBBD1\uBBD2\uBBD4", 35, "\uBBFA\uBBFB\uBBFD\uBBFE\uBC01"], - ["9341", "\uBC03", 4, "\uBC0A\uBC0E\uBC10\uBC12\uBC13\uBC19\uBC1A\uBC20\uBC21\uBC22\uBC23\uBC26\uBC28\uBC2A\uBC2B\uBC2C\uBC2E\uBC2F\uBC32\uBC33\uBC35"], - ["9361", "\uBC36\uBC37\uBC39", 6, "\uBC42\uBC46\uBC47\uBC48\uBC4A\uBC4B\uBC4E\uBC4F\uBC51", 8], - ["9381", "\uBC5A\uBC5B\uBC5C\uBC5E", 37, "\uBC86\uBC87\uBC89\uBC8A\uBC8D\uBC8F", 4, "\uBC96\uBC98\uBC9B", 4, "\uBCA2\uBCA3\uBCA5\uBCA6\uBCA9", 6, "\uBCB2\uBCB6", 5, "\uBCBE\uBCBF\uBCC1\uBCC2\uBCC3\uBCC5", 7, "\uBCCE\uBCD2\uBCD3\uBCD4\uBCD6\uBCD7\uBCD9\uBCDA\uBCDB\uBCDD", 22, "\uBCF7\uBCF9\uBCFA\uBCFB\uBCFD"], - ["9441", "\uBCFE", 5, "\uBD06\uBD08\uBD0A", 5, "\uBD11\uBD12\uBD13\uBD15", 8], - ["9461", "\uBD1E", 5, "\uBD25", 6, "\uBD2D", 12], - ["9481", "\uBD3A", 5, "\uBD41", 6, "\uBD4A\uBD4B\uBD4D\uBD4E\uBD4F\uBD51", 6, "\uBD5A", 9, "\uBD65\uBD66\uBD67\uBD69", 22, "\uBD82\uBD83\uBD85\uBD86\uBD8B", 4, "\uBD92\uBD94\uBD96\uBD97\uBD98\uBD9B\uBD9D", 6, "\uBDA5", 10, "\uBDB1", 6, "\uBDB9", 24], - ["9541", "\uBDD2\uBDD3\uBDD6\uBDD7\uBDD9\uBDDA\uBDDB\uBDDD", 11, "\uBDEA", 5, "\uBDF1"], - ["9561", "\uBDF2\uBDF3\uBDF5\uBDF6\uBDF7\uBDF9", 6, "\uBE01\uBE02\uBE04\uBE06", 5, "\uBE0E\uBE0F\uBE11\uBE12\uBE13"], - ["9581", "\uBE15", 6, "\uBE1E\uBE20", 35, "\uBE46\uBE47\uBE49\uBE4A\uBE4B\uBE4D\uBE4F", 4, "\uBE56\uBE58\uBE5C\uBE5D\uBE5E\uBE5F\uBE62\uBE63\uBE65\uBE66\uBE67\uBE69\uBE6B", 4, "\uBE72\uBE76", 4, "\uBE7E\uBE7F\uBE81\uBE82\uBE83\uBE85", 6, "\uBE8E\uBE92", 5, "\uBE9A", 13, "\uBEA9", 14], - ["9641", "\uBEB8", 23, "\uBED2\uBED3"], - ["9661", "\uBED5\uBED6\uBED9", 6, "\uBEE1\uBEE2\uBEE6", 5, "\uBEED", 8], - ["9681", "\uBEF6", 10, "\uBF02", 5, "\uBF0A", 13, "\uBF1A\uBF1E", 33, "\uBF42\uBF43\uBF45\uBF46\uBF47\uBF49", 6, "\uBF52\uBF53\uBF54\uBF56", 44], - ["9741", "\uBF83", 16, "\uBF95", 8], - ["9761", "\uBF9E", 17, "\uBFB1", 7], - ["9781", "\uBFB9", 11, "\uBFC6", 5, "\uBFCE\uBFCF\uBFD1\uBFD2\uBFD3\uBFD5", 6, "\uBFDD\uBFDE\uBFE0\uBFE2", 89, "\uC03D\uC03E\uC03F"], - ["9841", "\uC040", 16, "\uC052", 5, "\uC059\uC05A\uC05B"], - ["9861", "\uC05D\uC05E\uC05F\uC061", 6, "\uC06A", 15], - ["9881", "\uC07A", 21, "\uC092\uC093\uC095\uC096\uC097\uC099", 6, "\uC0A2\uC0A4\uC0A6", 5, "\uC0AE\uC0B1\uC0B2\uC0B7", 4, "\uC0BE\uC0C2\uC0C3\uC0C4\uC0C6\uC0C7\uC0CA\uC0CB\uC0CD\uC0CE\uC0CF\uC0D1", 6, "\uC0DA\uC0DE", 5, "\uC0E6\uC0E7\uC0E9\uC0EA\uC0EB\uC0ED", 6, "\uC0F6\uC0F8\uC0FA", 5, "\uC101\uC102\uC103\uC105\uC106\uC107\uC109", 6, "\uC111\uC112\uC113\uC114\uC116", 5, "\uC121\uC122\uC125\uC128\uC129\uC12A\uC12B\uC12E"], - ["9941", "\uC132\uC133\uC134\uC135\uC137\uC13A\uC13B\uC13D\uC13E\uC13F\uC141", 6, "\uC14A\uC14E", 5, "\uC156\uC157"], - ["9961", "\uC159\uC15A\uC15B\uC15D", 6, "\uC166\uC16A", 5, "\uC171\uC172\uC173\uC175\uC176\uC177\uC179\uC17A\uC17B"], - ["9981", "\uC17C", 8, "\uC186", 5, "\uC18F\uC191\uC192\uC193\uC195\uC197", 4, "\uC19E\uC1A0\uC1A2\uC1A3\uC1A4\uC1A6\uC1A7\uC1AA\uC1AB\uC1AD\uC1AE\uC1AF\uC1B1", 11, "\uC1BE", 5, "\uC1C5\uC1C6\uC1C7\uC1C9\uC1CA\uC1CB\uC1CD", 6, "\uC1D5\uC1D6\uC1D9", 6, "\uC1E1\uC1E2\uC1E3\uC1E5\uC1E6\uC1E7\uC1E9", 6, "\uC1F2\uC1F4", 7, "\uC1FE\uC1FF\uC201\uC202\uC203\uC205", 6, "\uC20E\uC210\uC212", 5, "\uC21A\uC21B\uC21D\uC21E\uC221\uC222\uC223"], - ["9a41", "\uC224\uC225\uC226\uC227\uC22A\uC22C\uC22E\uC230\uC233\uC235", 16], - ["9a61", "\uC246\uC247\uC249", 6, "\uC252\uC253\uC255\uC256\uC257\uC259", 6, "\uC261\uC262\uC263\uC264\uC266"], - ["9a81", "\uC267", 4, "\uC26E\uC26F\uC271\uC272\uC273\uC275", 6, "\uC27E\uC280\uC282", 5, "\uC28A", 5, "\uC291", 6, "\uC299\uC29A\uC29C\uC29E", 5, "\uC2A6\uC2A7\uC2A9\uC2AA\uC2AB\uC2AE", 5, "\uC2B6\uC2B8\uC2BA", 33, "\uC2DE\uC2DF\uC2E1\uC2E2\uC2E5", 5, "\uC2EE\uC2F0\uC2F2\uC2F3\uC2F4\uC2F5\uC2F7\uC2FA\uC2FD\uC2FE\uC2FF\uC301", 6, "\uC30A\uC30B\uC30E\uC30F"], - ["9b41", "\uC310\uC311\uC312\uC316\uC317\uC319\uC31A\uC31B\uC31D", 6, "\uC326\uC327\uC32A", 8], - ["9b61", "\uC333", 17, "\uC346", 7], - ["9b81", "\uC34E", 25, "\uC36A\uC36B\uC36D\uC36E\uC36F\uC371\uC373", 4, "\uC37A\uC37B\uC37E", 5, "\uC385\uC386\uC387\uC389\uC38A\uC38B\uC38D", 50, "\uC3C1", 22, "\uC3DA"], - ["9c41", "\uC3DB\uC3DD\uC3DE\uC3E1\uC3E3", 4, "\uC3EA\uC3EB\uC3EC\uC3EE", 5, "\uC3F6\uC3F7\uC3F9", 5], - ["9c61", "\uC3FF", 8, "\uC409", 6, "\uC411", 9], - ["9c81", "\uC41B", 8, "\uC425", 6, "\uC42D\uC42E\uC42F\uC431\uC432\uC433\uC435", 6, "\uC43E", 9, "\uC449", 26, "\uC466\uC467\uC469\uC46A\uC46B\uC46D", 6, "\uC476\uC477\uC478\uC47A", 5, "\uC481", 18, "\uC495", 6, "\uC49D", 12], - ["9d41", "\uC4AA", 13, "\uC4B9\uC4BA\uC4BB\uC4BD", 8], - ["9d61", "\uC4C6", 25], - ["9d81", "\uC4E0", 8, "\uC4EA", 5, "\uC4F2\uC4F3\uC4F5\uC4F6\uC4F7\uC4F9\uC4FB\uC4FC\uC4FD\uC4FE\uC502", 9, "\uC50D\uC50E\uC50F\uC511\uC512\uC513\uC515", 6, "\uC51D", 10, "\uC52A\uC52B\uC52D\uC52E\uC52F\uC531", 6, "\uC53A\uC53C\uC53E", 5, "\uC546\uC547\uC54B\uC54F\uC550\uC551\uC552\uC556\uC55A\uC55B\uC55C\uC55F\uC562\uC563\uC565\uC566\uC567\uC569", 6, "\uC572\uC576", 5, "\uC57E\uC57F\uC581\uC582\uC583\uC585\uC586\uC588\uC589\uC58A\uC58B\uC58E\uC590\uC592\uC593\uC594"], - ["9e41", "\uC596\uC599\uC59A\uC59B\uC59D\uC59E\uC59F\uC5A1", 7, "\uC5AA", 9, "\uC5B6"], - ["9e61", "\uC5B7\uC5BA\uC5BF", 4, "\uC5CB\uC5CD\uC5CF\uC5D2\uC5D3\uC5D5\uC5D6\uC5D7\uC5D9", 6, "\uC5E2\uC5E4\uC5E6\uC5E7"], - ["9e81", "\uC5E8\uC5E9\uC5EA\uC5EB\uC5EF\uC5F1\uC5F2\uC5F3\uC5F5\uC5F8\uC5F9\uC5FA\uC5FB\uC602\uC603\uC604\uC609\uC60A\uC60B\uC60D\uC60E\uC60F\uC611", 6, "\uC61A\uC61D", 6, "\uC626\uC627\uC629\uC62A\uC62B\uC62F\uC631\uC632\uC636\uC638\uC63A\uC63C\uC63D\uC63E\uC63F\uC642\uC643\uC645\uC646\uC647\uC649", 6, "\uC652\uC656", 5, "\uC65E\uC65F\uC661", 10, "\uC66D\uC66E\uC670\uC672", 5, "\uC67A\uC67B\uC67D\uC67E\uC67F\uC681", 6, "\uC68A\uC68C\uC68E", 5, "\uC696\uC697\uC699\uC69A\uC69B\uC69D", 6, "\uC6A6"], - ["9f41", "\uC6A8\uC6AA", 5, "\uC6B2\uC6B3\uC6B5\uC6B6\uC6B7\uC6BB", 4, "\uC6C2\uC6C4\uC6C6", 5, "\uC6CE"], - ["9f61", "\uC6CF\uC6D1\uC6D2\uC6D3\uC6D5", 6, "\uC6DE\uC6DF\uC6E2", 5, "\uC6EA\uC6EB\uC6ED\uC6EE\uC6EF\uC6F1\uC6F2"], - ["9f81", "\uC6F3", 4, "\uC6FA\uC6FB\uC6FC\uC6FE", 5, "\uC706\uC707\uC709\uC70A\uC70B\uC70D", 6, "\uC716\uC718\uC71A", 5, "\uC722\uC723\uC725\uC726\uC727\uC729", 6, "\uC732\uC734\uC736\uC738\uC739\uC73A\uC73B\uC73E\uC73F\uC741\uC742\uC743\uC745", 4, "\uC74B\uC74E\uC750\uC759\uC75A\uC75B\uC75D\uC75E\uC75F\uC761", 6, "\uC769\uC76A\uC76C", 7, "\uC776\uC777\uC779\uC77A\uC77B\uC77F\uC780\uC781\uC782\uC786\uC78B\uC78C\uC78D\uC78F\uC792\uC793\uC795\uC799\uC79B", 4, "\uC7A2\uC7A7", 4, "\uC7AE\uC7AF\uC7B1\uC7B2\uC7B3\uC7B5\uC7B6\uC7B7"], - ["a041", "\uC7B8\uC7B9\uC7BA\uC7BB\uC7BE\uC7C2", 5, "\uC7CA\uC7CB\uC7CD\uC7CF\uC7D1", 6, "\uC7D9\uC7DA\uC7DB\uC7DC"], - ["a061", "\uC7DE", 5, "\uC7E5\uC7E6\uC7E7\uC7E9\uC7EA\uC7EB\uC7ED", 13], - ["a081", "\uC7FB", 4, "\uC802\uC803\uC805\uC806\uC807\uC809\uC80B", 4, "\uC812\uC814\uC817", 4, "\uC81E\uC81F\uC821\uC822\uC823\uC825", 6, "\uC82E\uC830\uC832", 5, "\uC839\uC83A\uC83B\uC83D\uC83E\uC83F\uC841", 6, "\uC84A\uC84B\uC84E", 5, "\uC855", 26, "\uC872\uC873\uC875\uC876\uC877\uC879\uC87B", 4, "\uC882\uC884\uC888\uC889\uC88A\uC88E", 5, "\uC895", 7, "\uC89E\uC8A0\uC8A2\uC8A3\uC8A4"], - ["a141", "\uC8A5\uC8A6\uC8A7\uC8A9", 18, "\uC8BE\uC8BF\uC8C0\uC8C1"], - ["a161", "\uC8C2\uC8C3\uC8C5\uC8C6\uC8C7\uC8C9\uC8CA\uC8CB\uC8CD", 6, "\uC8D6\uC8D8\uC8DA", 5, "\uC8E2\uC8E3\uC8E5"], - ["a181", "\uC8E6", 14, "\uC8F6", 5, "\uC8FE\uC8FF\uC901\uC902\uC903\uC907", 4, "\uC90E\u3000\u3001\u3002\xB7\u2025\u2026\xA8\u3003\xAD\u2015\u2225\uFF3C\u223C\u2018\u2019\u201C\u201D\u3014\u3015\u3008", 9, "\xB1\xD7\xF7\u2260\u2264\u2265\u221E\u2234\xB0\u2032\u2033\u2103\u212B\uFFE0\uFFE1\uFFE5\u2642\u2640\u2220\u22A5\u2312\u2202\u2207\u2261\u2252\xA7\u203B\u2606\u2605\u25CB\u25CF\u25CE\u25C7\u25C6\u25A1\u25A0\u25B3\u25B2\u25BD\u25BC\u2192\u2190\u2191\u2193\u2194\u3013\u226A\u226B\u221A\u223D\u221D\u2235\u222B\u222C\u2208\u220B\u2286\u2287\u2282\u2283\u222A\u2229\u2227\u2228\uFFE2"], - ["a241", "\uC910\uC912", 5, "\uC919", 18], - ["a261", "\uC92D", 6, "\uC935", 18], - ["a281", "\uC948", 7, "\uC952\uC953\uC955\uC956\uC957\uC959", 6, "\uC962\uC964", 7, "\uC96D\uC96E\uC96F\u21D2\u21D4\u2200\u2203\xB4\uFF5E\u02C7\u02D8\u02DD\u02DA\u02D9\xB8\u02DB\xA1\xBF\u02D0\u222E\u2211\u220F\xA4\u2109\u2030\u25C1\u25C0\u25B7\u25B6\u2664\u2660\u2661\u2665\u2667\u2663\u2299\u25C8\u25A3\u25D0\u25D1\u2592\u25A4\u25A5\u25A8\u25A7\u25A6\u25A9\u2668\u260F\u260E\u261C\u261E\xB6\u2020\u2021\u2195\u2197\u2199\u2196\u2198\u266D\u2669\u266A\u266C\u327F\u321C\u2116\u33C7\u2122\u33C2\u33D8\u2121\u20AC\xAE"], - ["a341", "\uC971\uC972\uC973\uC975", 6, "\uC97D", 10, "\uC98A\uC98B\uC98D\uC98E\uC98F"], - ["a361", "\uC991", 6, "\uC99A\uC99C\uC99E", 16], - ["a381", "\uC9AF", 16, "\uC9C2\uC9C3\uC9C5\uC9C6\uC9C9\uC9CB", 4, "\uC9D2\uC9D4\uC9D7\uC9D8\uC9DB\uFF01", 58, "\uFFE6\uFF3D", 32, "\uFFE3"], - ["a441", "\uC9DE\uC9DF\uC9E1\uC9E3\uC9E5\uC9E6\uC9E8\uC9E9\uC9EA\uC9EB\uC9EE\uC9F2", 5, "\uC9FA\uC9FB\uC9FD\uC9FE\uC9FF\uCA01\uCA02\uCA03\uCA04"], - ["a461", "\uCA05\uCA06\uCA07\uCA0A\uCA0E", 5, "\uCA15\uCA16\uCA17\uCA19", 12], - ["a481", "\uCA26\uCA27\uCA28\uCA2A", 28, "\u3131", 93], - ["a541", "\uCA47", 4, "\uCA4E\uCA4F\uCA51\uCA52\uCA53\uCA55", 6, "\uCA5E\uCA62", 5, "\uCA69\uCA6A"], - ["a561", "\uCA6B", 17, "\uCA7E", 5, "\uCA85\uCA86"], - ["a581", "\uCA87", 16, "\uCA99", 14, "\u2170", 9], - ["a5b0", "\u2160", 9], - ["a5c1", "\u0391", 16, "\u03A3", 6], - ["a5e1", "\u03B1", 16, "\u03C3", 6], - ["a641", "\uCAA8", 19, "\uCABE\uCABF\uCAC1\uCAC2\uCAC3\uCAC5"], - ["a661", "\uCAC6", 5, "\uCACE\uCAD0\uCAD2\uCAD4\uCAD5\uCAD6\uCAD7\uCADA", 5, "\uCAE1", 6], - ["a681", "\uCAE8\uCAE9\uCAEA\uCAEB\uCAED", 6, "\uCAF5", 18, "\uCB09\uCB0A\u2500\u2502\u250C\u2510\u2518\u2514\u251C\u252C\u2524\u2534\u253C\u2501\u2503\u250F\u2513\u251B\u2517\u2523\u2533\u252B\u253B\u254B\u2520\u252F\u2528\u2537\u253F\u251D\u2530\u2525\u2538\u2542\u2512\u2511\u251A\u2519\u2516\u2515\u250E\u250D\u251E\u251F\u2521\u2522\u2526\u2527\u2529\u252A\u252D\u252E\u2531\u2532\u2535\u2536\u2539\u253A\u253D\u253E\u2540\u2541\u2543", 7], - ["a741", "\uCB0B", 4, "\uCB11\uCB12\uCB13\uCB15\uCB16\uCB17\uCB19", 6, "\uCB22", 7], - ["a761", "\uCB2A", 22, "\uCB42\uCB43\uCB44"], - ["a781", "\uCB45\uCB46\uCB47\uCB4A\uCB4B\uCB4D\uCB4E\uCB4F\uCB51", 6, "\uCB5A\uCB5B\uCB5C\uCB5E", 5, "\uCB65", 7, "\u3395\u3396\u3397\u2113\u3398\u33C4\u33A3\u33A4\u33A5\u33A6\u3399", 9, "\u33CA\u338D\u338E\u338F\u33CF\u3388\u3389\u33C8\u33A7\u33A8\u33B0", 9, "\u3380", 4, "\u33BA", 5, "\u3390", 4, "\u2126\u33C0\u33C1\u338A\u338B\u338C\u33D6\u33C5\u33AD\u33AE\u33AF\u33DB\u33A9\u33AA\u33AB\u33AC\u33DD\u33D0\u33D3\u33C3\u33C9\u33DC\u33C6"], - ["a841", "\uCB6D", 10, "\uCB7A", 14], - ["a861", "\uCB89", 18, "\uCB9D", 6], - ["a881", "\uCBA4", 19, "\uCBB9", 11, "\xC6\xD0\xAA\u0126"], - ["a8a6", "\u0132"], - ["a8a8", "\u013F\u0141\xD8\u0152\xBA\xDE\u0166\u014A"], - ["a8b1", "\u3260", 27, "\u24D0", 25, "\u2460", 14, "\xBD\u2153\u2154\xBC\xBE\u215B\u215C\u215D\u215E"], - ["a941", "\uCBC5", 14, "\uCBD5", 10], - ["a961", "\uCBE0\uCBE1\uCBE2\uCBE3\uCBE5\uCBE6\uCBE8\uCBEA", 18], - ["a981", "\uCBFD", 14, "\uCC0E\uCC0F\uCC11\uCC12\uCC13\uCC15", 6, "\uCC1E\uCC1F\uCC20\uCC23\uCC24\xE6\u0111\xF0\u0127\u0131\u0133\u0138\u0140\u0142\xF8\u0153\xDF\xFE\u0167\u014B\u0149\u3200", 27, "\u249C", 25, "\u2474", 14, "\xB9\xB2\xB3\u2074\u207F\u2081\u2082\u2083\u2084"], - ["aa41", "\uCC25\uCC26\uCC2A\uCC2B\uCC2D\uCC2F\uCC31", 6, "\uCC3A\uCC3F", 4, "\uCC46\uCC47\uCC49\uCC4A\uCC4B\uCC4D\uCC4E"], - ["aa61", "\uCC4F", 4, "\uCC56\uCC5A", 5, "\uCC61\uCC62\uCC63\uCC65\uCC67\uCC69", 6, "\uCC71\uCC72"], - ["aa81", "\uCC73\uCC74\uCC76", 29, "\u3041", 82], - ["ab41", "\uCC94\uCC95\uCC96\uCC97\uCC9A\uCC9B\uCC9D\uCC9E\uCC9F\uCCA1", 6, "\uCCAA\uCCAE", 5, "\uCCB6\uCCB7\uCCB9"], - ["ab61", "\uCCBA\uCCBB\uCCBD", 6, "\uCCC6\uCCC8\uCCCA", 5, "\uCCD1\uCCD2\uCCD3\uCCD5", 5], - ["ab81", "\uCCDB", 8, "\uCCE5", 6, "\uCCED\uCCEE\uCCEF\uCCF1", 12, "\u30A1", 85], - ["ac41", "\uCCFE\uCCFF\uCD00\uCD02", 5, "\uCD0A\uCD0B\uCD0D\uCD0E\uCD0F\uCD11", 6, "\uCD1A\uCD1C\uCD1E\uCD1F\uCD20"], - ["ac61", "\uCD21\uCD22\uCD23\uCD25\uCD26\uCD27\uCD29\uCD2A\uCD2B\uCD2D", 11, "\uCD3A", 4], - ["ac81", "\uCD3F", 28, "\uCD5D\uCD5E\uCD5F\u0410", 5, "\u0401\u0416", 25], - ["acd1", "\u0430", 5, "\u0451\u0436", 25], - ["ad41", "\uCD61\uCD62\uCD63\uCD65", 6, "\uCD6E\uCD70\uCD72", 5, "\uCD79", 7], - ["ad61", "\uCD81", 6, "\uCD89", 10, "\uCD96\uCD97\uCD99\uCD9A\uCD9B\uCD9D\uCD9E\uCD9F"], - ["ad81", "\uCDA0\uCDA1\uCDA2\uCDA3\uCDA6\uCDA8\uCDAA", 5, "\uCDB1", 18, "\uCDC5"], - ["ae41", "\uCDC6", 5, "\uCDCD\uCDCE\uCDCF\uCDD1", 16], - ["ae61", "\uCDE2", 5, "\uCDE9\uCDEA\uCDEB\uCDED\uCDEE\uCDEF\uCDF1", 6, "\uCDFA\uCDFC\uCDFE", 4], - ["ae81", "\uCE03\uCE05\uCE06\uCE07\uCE09\uCE0A\uCE0B\uCE0D", 6, "\uCE15\uCE16\uCE17\uCE18\uCE1A", 5, "\uCE22\uCE23\uCE25\uCE26\uCE27\uCE29\uCE2A\uCE2B"], - ["af41", "\uCE2C\uCE2D\uCE2E\uCE2F\uCE32\uCE34\uCE36", 19], - ["af61", "\uCE4A", 13, "\uCE5A\uCE5B\uCE5D\uCE5E\uCE62", 5, "\uCE6A\uCE6C"], - ["af81", "\uCE6E", 5, "\uCE76\uCE77\uCE79\uCE7A\uCE7B\uCE7D", 6, "\uCE86\uCE88\uCE8A", 5, "\uCE92\uCE93\uCE95\uCE96\uCE97\uCE99"], - ["b041", "\uCE9A", 5, "\uCEA2\uCEA6", 5, "\uCEAE", 12], - ["b061", "\uCEBB", 5, "\uCEC2", 19], - ["b081", "\uCED6", 13, "\uCEE6\uCEE7\uCEE9\uCEEA\uCEED", 6, "\uCEF6\uCEFA", 5, "\uAC00\uAC01\uAC04\uAC07\uAC08\uAC09\uAC0A\uAC10", 7, "\uAC19", 4, "\uAC20\uAC24\uAC2C\uAC2D\uAC2F\uAC30\uAC31\uAC38\uAC39\uAC3C\uAC40\uAC4B\uAC4D\uAC54\uAC58\uAC5C\uAC70\uAC71\uAC74\uAC77\uAC78\uAC7A\uAC80\uAC81\uAC83\uAC84\uAC85\uAC86\uAC89\uAC8A\uAC8B\uAC8C\uAC90\uAC94\uAC9C\uAC9D\uAC9F\uACA0\uACA1\uACA8\uACA9\uACAA\uACAC\uACAF\uACB0\uACB8\uACB9\uACBB\uACBC\uACBD\uACC1\uACC4\uACC8\uACCC\uACD5\uACD7\uACE0\uACE1\uACE4\uACE7\uACE8\uACEA\uACEC\uACEF\uACF0\uACF1\uACF3\uACF5\uACF6\uACFC\uACFD\uAD00\uAD04\uAD06"], - ["b141", "\uCF02\uCF03\uCF05\uCF06\uCF07\uCF09", 6, "\uCF12\uCF14\uCF16", 5, "\uCF1D\uCF1E\uCF1F\uCF21\uCF22\uCF23"], - ["b161", "\uCF25", 6, "\uCF2E\uCF32", 5, "\uCF39", 11], - ["b181", "\uCF45", 14, "\uCF56\uCF57\uCF59\uCF5A\uCF5B\uCF5D", 6, "\uCF66\uCF68\uCF6A\uCF6B\uCF6C\uAD0C\uAD0D\uAD0F\uAD11\uAD18\uAD1C\uAD20\uAD29\uAD2C\uAD2D\uAD34\uAD35\uAD38\uAD3C\uAD44\uAD45\uAD47\uAD49\uAD50\uAD54\uAD58\uAD61\uAD63\uAD6C\uAD6D\uAD70\uAD73\uAD74\uAD75\uAD76\uAD7B\uAD7C\uAD7D\uAD7F\uAD81\uAD82\uAD88\uAD89\uAD8C\uAD90\uAD9C\uAD9D\uADA4\uADB7\uADC0\uADC1\uADC4\uADC8\uADD0\uADD1\uADD3\uADDC\uADE0\uADE4\uADF8\uADF9\uADFC\uADFF\uAE00\uAE01\uAE08\uAE09\uAE0B\uAE0D\uAE14\uAE30\uAE31\uAE34\uAE37\uAE38\uAE3A\uAE40\uAE41\uAE43\uAE45\uAE46\uAE4A\uAE4C\uAE4D\uAE4E\uAE50\uAE54\uAE56\uAE5C\uAE5D\uAE5F\uAE60\uAE61\uAE65\uAE68\uAE69\uAE6C\uAE70\uAE78"], - ["b241", "\uCF6D\uCF6E\uCF6F\uCF72\uCF73\uCF75\uCF76\uCF77\uCF79", 6, "\uCF81\uCF82\uCF83\uCF84\uCF86", 5, "\uCF8D"], - ["b261", "\uCF8E", 18, "\uCFA2", 5, "\uCFA9"], - ["b281", "\uCFAA", 5, "\uCFB1", 18, "\uCFC5", 6, "\uAE79\uAE7B\uAE7C\uAE7D\uAE84\uAE85\uAE8C\uAEBC\uAEBD\uAEBE\uAEC0\uAEC4\uAECC\uAECD\uAECF\uAED0\uAED1\uAED8\uAED9\uAEDC\uAEE8\uAEEB\uAEED\uAEF4\uAEF8\uAEFC\uAF07\uAF08\uAF0D\uAF10\uAF2C\uAF2D\uAF30\uAF32\uAF34\uAF3C\uAF3D\uAF3F\uAF41\uAF42\uAF43\uAF48\uAF49\uAF50\uAF5C\uAF5D\uAF64\uAF65\uAF79\uAF80\uAF84\uAF88\uAF90\uAF91\uAF95\uAF9C\uAFB8\uAFB9\uAFBC\uAFC0\uAFC7\uAFC8\uAFC9\uAFCB\uAFCD\uAFCE\uAFD4\uAFDC\uAFE8\uAFE9\uAFF0\uAFF1\uAFF4\uAFF8\uB000\uB001\uB004\uB00C\uB010\uB014\uB01C\uB01D\uB028\uB044\uB045\uB048\uB04A\uB04C\uB04E\uB053\uB054\uB055\uB057\uB059"], - ["b341", "\uCFCC", 19, "\uCFE2\uCFE3\uCFE5\uCFE6\uCFE7\uCFE9"], - ["b361", "\uCFEA", 5, "\uCFF2\uCFF4\uCFF6", 5, "\uCFFD\uCFFE\uCFFF\uD001\uD002\uD003\uD005", 5], - ["b381", "\uD00B", 5, "\uD012", 5, "\uD019", 19, "\uB05D\uB07C\uB07D\uB080\uB084\uB08C\uB08D\uB08F\uB091\uB098\uB099\uB09A\uB09C\uB09F\uB0A0\uB0A1\uB0A2\uB0A8\uB0A9\uB0AB", 4, "\uB0B1\uB0B3\uB0B4\uB0B5\uB0B8\uB0BC\uB0C4\uB0C5\uB0C7\uB0C8\uB0C9\uB0D0\uB0D1\uB0D4\uB0D8\uB0E0\uB0E5\uB108\uB109\uB10B\uB10C\uB110\uB112\uB113\uB118\uB119\uB11B\uB11C\uB11D\uB123\uB124\uB125\uB128\uB12C\uB134\uB135\uB137\uB138\uB139\uB140\uB141\uB144\uB148\uB150\uB151\uB154\uB155\uB158\uB15C\uB160\uB178\uB179\uB17C\uB180\uB182\uB188\uB189\uB18B\uB18D\uB192\uB193\uB194\uB198\uB19C\uB1A8\uB1CC\uB1D0\uB1D4\uB1DC\uB1DD"], - ["b441", "\uD02E", 5, "\uD036\uD037\uD039\uD03A\uD03B\uD03D", 6, "\uD046\uD048\uD04A", 5], - ["b461", "\uD051\uD052\uD053\uD055\uD056\uD057\uD059", 6, "\uD061", 10, "\uD06E\uD06F"], - ["b481", "\uD071\uD072\uD073\uD075", 6, "\uD07E\uD07F\uD080\uD082", 18, "\uB1DF\uB1E8\uB1E9\uB1EC\uB1F0\uB1F9\uB1FB\uB1FD\uB204\uB205\uB208\uB20B\uB20C\uB214\uB215\uB217\uB219\uB220\uB234\uB23C\uB258\uB25C\uB260\uB268\uB269\uB274\uB275\uB27C\uB284\uB285\uB289\uB290\uB291\uB294\uB298\uB299\uB29A\uB2A0\uB2A1\uB2A3\uB2A5\uB2A6\uB2AA\uB2AC\uB2B0\uB2B4\uB2C8\uB2C9\uB2CC\uB2D0\uB2D2\uB2D8\uB2D9\uB2DB\uB2DD\uB2E2\uB2E4\uB2E5\uB2E6\uB2E8\uB2EB", 4, "\uB2F3\uB2F4\uB2F5\uB2F7", 4, "\uB2FF\uB300\uB301\uB304\uB308\uB310\uB311\uB313\uB314\uB315\uB31C\uB354\uB355\uB356\uB358\uB35B\uB35C\uB35E\uB35F\uB364\uB365"], - ["b541", "\uD095", 14, "\uD0A6\uD0A7\uD0A9\uD0AA\uD0AB\uD0AD", 5], - ["b561", "\uD0B3\uD0B6\uD0B8\uD0BA", 5, "\uD0C2\uD0C3\uD0C5\uD0C6\uD0C7\uD0CA", 5, "\uD0D2\uD0D6", 4], - ["b581", "\uD0DB\uD0DE\uD0DF\uD0E1\uD0E2\uD0E3\uD0E5", 6, "\uD0EE\uD0F2", 5, "\uD0F9", 11, "\uB367\uB369\uB36B\uB36E\uB370\uB371\uB374\uB378\uB380\uB381\uB383\uB384\uB385\uB38C\uB390\uB394\uB3A0\uB3A1\uB3A8\uB3AC\uB3C4\uB3C5\uB3C8\uB3CB\uB3CC\uB3CE\uB3D0\uB3D4\uB3D5\uB3D7\uB3D9\uB3DB\uB3DD\uB3E0\uB3E4\uB3E8\uB3FC\uB410\uB418\uB41C\uB420\uB428\uB429\uB42B\uB434\uB450\uB451\uB454\uB458\uB460\uB461\uB463\uB465\uB46C\uB480\uB488\uB49D\uB4A4\uB4A8\uB4AC\uB4B5\uB4B7\uB4B9\uB4C0\uB4C4\uB4C8\uB4D0\uB4D5\uB4DC\uB4DD\uB4E0\uB4E3\uB4E4\uB4E6\uB4EC\uB4ED\uB4EF\uB4F1\uB4F8\uB514\uB515\uB518\uB51B\uB51C\uB524\uB525\uB527\uB528\uB529\uB52A\uB530\uB531\uB534\uB538"], - ["b641", "\uD105", 7, "\uD10E", 17], - ["b661", "\uD120", 15, "\uD132\uD133\uD135\uD136\uD137\uD139\uD13B\uD13C\uD13D\uD13E"], - ["b681", "\uD13F\uD142\uD146", 5, "\uD14E\uD14F\uD151\uD152\uD153\uD155", 6, "\uD15E\uD160\uD162", 5, "\uD169\uD16A\uD16B\uD16D\uB540\uB541\uB543\uB544\uB545\uB54B\uB54C\uB54D\uB550\uB554\uB55C\uB55D\uB55F\uB560\uB561\uB5A0\uB5A1\uB5A4\uB5A8\uB5AA\uB5AB\uB5B0\uB5B1\uB5B3\uB5B4\uB5B5\uB5BB\uB5BC\uB5BD\uB5C0\uB5C4\uB5CC\uB5CD\uB5CF\uB5D0\uB5D1\uB5D8\uB5EC\uB610\uB611\uB614\uB618\uB625\uB62C\uB634\uB648\uB664\uB668\uB69C\uB69D\uB6A0\uB6A4\uB6AB\uB6AC\uB6B1\uB6D4\uB6F0\uB6F4\uB6F8\uB700\uB701\uB705\uB728\uB729\uB72C\uB72F\uB730\uB738\uB739\uB73B\uB744\uB748\uB74C\uB754\uB755\uB760\uB764\uB768\uB770\uB771\uB773\uB775\uB77C\uB77D\uB780\uB784\uB78C\uB78D\uB78F\uB790\uB791\uB792\uB796\uB797"], - ["b741", "\uD16E", 13, "\uD17D", 6, "\uD185\uD186\uD187\uD189\uD18A"], - ["b761", "\uD18B", 20, "\uD1A2\uD1A3\uD1A5\uD1A6\uD1A7"], - ["b781", "\uD1A9", 6, "\uD1B2\uD1B4\uD1B6\uD1B7\uD1B8\uD1B9\uD1BB\uD1BD\uD1BE\uD1BF\uD1C1", 14, "\uB798\uB799\uB79C\uB7A0\uB7A8\uB7A9\uB7AB\uB7AC\uB7AD\uB7B4\uB7B5\uB7B8\uB7C7\uB7C9\uB7EC\uB7ED\uB7F0\uB7F4\uB7FC\uB7FD\uB7FF\uB800\uB801\uB807\uB808\uB809\uB80C\uB810\uB818\uB819\uB81B\uB81D\uB824\uB825\uB828\uB82C\uB834\uB835\uB837\uB838\uB839\uB840\uB844\uB851\uB853\uB85C\uB85D\uB860\uB864\uB86C\uB86D\uB86F\uB871\uB878\uB87C\uB88D\uB8A8\uB8B0\uB8B4\uB8B8\uB8C0\uB8C1\uB8C3\uB8C5\uB8CC\uB8D0\uB8D4\uB8DD\uB8DF\uB8E1\uB8E8\uB8E9\uB8EC\uB8F0\uB8F8\uB8F9\uB8FB\uB8FD\uB904\uB918\uB920\uB93C\uB93D\uB940\uB944\uB94C\uB94F\uB951\uB958\uB959\uB95C\uB960\uB968\uB969"], - ["b841", "\uD1D0", 7, "\uD1D9", 17], - ["b861", "\uD1EB", 8, "\uD1F5\uD1F6\uD1F7\uD1F9", 13], - ["b881", "\uD208\uD20A", 5, "\uD211", 24, "\uB96B\uB96D\uB974\uB975\uB978\uB97C\uB984\uB985\uB987\uB989\uB98A\uB98D\uB98E\uB9AC\uB9AD\uB9B0\uB9B4\uB9BC\uB9BD\uB9BF\uB9C1\uB9C8\uB9C9\uB9CC\uB9CE", 4, "\uB9D8\uB9D9\uB9DB\uB9DD\uB9DE\uB9E1\uB9E3\uB9E4\uB9E5\uB9E8\uB9EC\uB9F4\uB9F5\uB9F7\uB9F8\uB9F9\uB9FA\uBA00\uBA01\uBA08\uBA15\uBA38\uBA39\uBA3C\uBA40\uBA42\uBA48\uBA49\uBA4B\uBA4D\uBA4E\uBA53\uBA54\uBA55\uBA58\uBA5C\uBA64\uBA65\uBA67\uBA68\uBA69\uBA70\uBA71\uBA74\uBA78\uBA83\uBA84\uBA85\uBA87\uBA8C\uBAA8\uBAA9\uBAAB\uBAAC\uBAB0\uBAB2\uBAB8\uBAB9\uBABB\uBABD\uBAC4\uBAC8\uBAD8\uBAD9\uBAFC"], - ["b941", "\uD22A\uD22B\uD22E\uD22F\uD231\uD232\uD233\uD235", 6, "\uD23E\uD240\uD242", 5, "\uD249\uD24A\uD24B\uD24C"], - ["b961", "\uD24D", 14, "\uD25D", 6, "\uD265\uD266\uD267\uD268"], - ["b981", "\uD269", 22, "\uD282\uD283\uD285\uD286\uD287\uD289\uD28A\uD28B\uD28C\uBB00\uBB04\uBB0D\uBB0F\uBB11\uBB18\uBB1C\uBB20\uBB29\uBB2B\uBB34\uBB35\uBB36\uBB38\uBB3B\uBB3C\uBB3D\uBB3E\uBB44\uBB45\uBB47\uBB49\uBB4D\uBB4F\uBB50\uBB54\uBB58\uBB61\uBB63\uBB6C\uBB88\uBB8C\uBB90\uBBA4\uBBA8\uBBAC\uBBB4\uBBB7\uBBC0\uBBC4\uBBC8\uBBD0\uBBD3\uBBF8\uBBF9\uBBFC\uBBFF\uBC00\uBC02\uBC08\uBC09\uBC0B\uBC0C\uBC0D\uBC0F\uBC11\uBC14", 4, "\uBC1B", 4, "\uBC24\uBC25\uBC27\uBC29\uBC2D\uBC30\uBC31\uBC34\uBC38\uBC40\uBC41\uBC43\uBC44\uBC45\uBC49\uBC4C\uBC4D\uBC50\uBC5D\uBC84\uBC85\uBC88\uBC8B\uBC8C\uBC8E\uBC94\uBC95\uBC97"], - ["ba41", "\uD28D\uD28E\uD28F\uD292\uD293\uD294\uD296", 5, "\uD29D\uD29E\uD29F\uD2A1\uD2A2\uD2A3\uD2A5", 6, "\uD2AD"], - ["ba61", "\uD2AE\uD2AF\uD2B0\uD2B2", 5, "\uD2BA\uD2BB\uD2BD\uD2BE\uD2C1\uD2C3", 4, "\uD2CA\uD2CC", 5], - ["ba81", "\uD2D2\uD2D3\uD2D5\uD2D6\uD2D7\uD2D9\uD2DA\uD2DB\uD2DD", 6, "\uD2E6", 9, "\uD2F2\uD2F3\uD2F5\uD2F6\uD2F7\uD2F9\uD2FA\uBC99\uBC9A\uBCA0\uBCA1\uBCA4\uBCA7\uBCA8\uBCB0\uBCB1\uBCB3\uBCB4\uBCB5\uBCBC\uBCBD\uBCC0\uBCC4\uBCCD\uBCCF\uBCD0\uBCD1\uBCD5\uBCD8\uBCDC\uBCF4\uBCF5\uBCF6\uBCF8\uBCFC\uBD04\uBD05\uBD07\uBD09\uBD10\uBD14\uBD24\uBD2C\uBD40\uBD48\uBD49\uBD4C\uBD50\uBD58\uBD59\uBD64\uBD68\uBD80\uBD81\uBD84\uBD87\uBD88\uBD89\uBD8A\uBD90\uBD91\uBD93\uBD95\uBD99\uBD9A\uBD9C\uBDA4\uBDB0\uBDB8\uBDD4\uBDD5\uBDD8\uBDDC\uBDE9\uBDF0\uBDF4\uBDF8\uBE00\uBE03\uBE05\uBE0C\uBE0D\uBE10\uBE14\uBE1C\uBE1D\uBE1F\uBE44\uBE45\uBE48\uBE4C\uBE4E\uBE54\uBE55\uBE57\uBE59\uBE5A\uBE5B\uBE60\uBE61\uBE64"], - ["bb41", "\uD2FB", 4, "\uD302\uD304\uD306", 5, "\uD30F\uD311\uD312\uD313\uD315\uD317", 4, "\uD31E\uD322\uD323"], - ["bb61", "\uD324\uD326\uD327\uD32A\uD32B\uD32D\uD32E\uD32F\uD331", 6, "\uD33A\uD33E", 5, "\uD346\uD347\uD348\uD349"], - ["bb81", "\uD34A", 31, "\uBE68\uBE6A\uBE70\uBE71\uBE73\uBE74\uBE75\uBE7B\uBE7C\uBE7D\uBE80\uBE84\uBE8C\uBE8D\uBE8F\uBE90\uBE91\uBE98\uBE99\uBEA8\uBED0\uBED1\uBED4\uBED7\uBED8\uBEE0\uBEE3\uBEE4\uBEE5\uBEEC\uBF01\uBF08\uBF09\uBF18\uBF19\uBF1B\uBF1C\uBF1D\uBF40\uBF41\uBF44\uBF48\uBF50\uBF51\uBF55\uBF94\uBFB0\uBFC5\uBFCC\uBFCD\uBFD0\uBFD4\uBFDC\uBFDF\uBFE1\uC03C\uC051\uC058\uC05C\uC060\uC068\uC069\uC090\uC091\uC094\uC098\uC0A0\uC0A1\uC0A3\uC0A5\uC0AC\uC0AD\uC0AF\uC0B0\uC0B3\uC0B4\uC0B5\uC0B6\uC0BC\uC0BD\uC0BF\uC0C0\uC0C1\uC0C5\uC0C8\uC0C9\uC0CC\uC0D0\uC0D8\uC0D9\uC0DB\uC0DC\uC0DD\uC0E4"], - ["bc41", "\uD36A", 17, "\uD37E\uD37F\uD381\uD382\uD383\uD385\uD386\uD387"], - ["bc61", "\uD388\uD389\uD38A\uD38B\uD38E\uD392", 5, "\uD39A\uD39B\uD39D\uD39E\uD39F\uD3A1", 6, "\uD3AA\uD3AC\uD3AE"], - ["bc81", "\uD3AF", 4, "\uD3B5\uD3B6\uD3B7\uD3B9\uD3BA\uD3BB\uD3BD", 6, "\uD3C6\uD3C7\uD3CA", 5, "\uD3D1", 5, "\uC0E5\uC0E8\uC0EC\uC0F4\uC0F5\uC0F7\uC0F9\uC100\uC104\uC108\uC110\uC115\uC11C", 4, "\uC123\uC124\uC126\uC127\uC12C\uC12D\uC12F\uC130\uC131\uC136\uC138\uC139\uC13C\uC140\uC148\uC149\uC14B\uC14C\uC14D\uC154\uC155\uC158\uC15C\uC164\uC165\uC167\uC168\uC169\uC170\uC174\uC178\uC185\uC18C\uC18D\uC18E\uC190\uC194\uC196\uC19C\uC19D\uC19F\uC1A1\uC1A5\uC1A8\uC1A9\uC1AC\uC1B0\uC1BD\uC1C4\uC1C8\uC1CC\uC1D4\uC1D7\uC1D8\uC1E0\uC1E4\uC1E8\uC1F0\uC1F1\uC1F3\uC1FC\uC1FD\uC200\uC204\uC20C\uC20D\uC20F\uC211\uC218\uC219\uC21C\uC21F\uC220\uC228\uC229\uC22B\uC22D"], - ["bd41", "\uD3D7\uD3D9", 7, "\uD3E2\uD3E4", 7, "\uD3EE\uD3EF\uD3F1\uD3F2\uD3F3\uD3F5\uD3F6\uD3F7"], - ["bd61", "\uD3F8\uD3F9\uD3FA\uD3FB\uD3FE\uD400\uD402", 5, "\uD409", 13], - ["bd81", "\uD417", 5, "\uD41E", 25, "\uC22F\uC231\uC232\uC234\uC248\uC250\uC251\uC254\uC258\uC260\uC265\uC26C\uC26D\uC270\uC274\uC27C\uC27D\uC27F\uC281\uC288\uC289\uC290\uC298\uC29B\uC29D\uC2A4\uC2A5\uC2A8\uC2AC\uC2AD\uC2B4\uC2B5\uC2B7\uC2B9\uC2DC\uC2DD\uC2E0\uC2E3\uC2E4\uC2EB\uC2EC\uC2ED\uC2EF\uC2F1\uC2F6\uC2F8\uC2F9\uC2FB\uC2FC\uC300\uC308\uC309\uC30C\uC30D\uC313\uC314\uC315\uC318\uC31C\uC324\uC325\uC328\uC329\uC345\uC368\uC369\uC36C\uC370\uC372\uC378\uC379\uC37C\uC37D\uC384\uC388\uC38C\uC3C0\uC3D8\uC3D9\uC3DC\uC3DF\uC3E0\uC3E2\uC3E8\uC3E9\uC3ED\uC3F4\uC3F5\uC3F8\uC408\uC410\uC424\uC42C\uC430"], - ["be41", "\uD438", 7, "\uD441\uD442\uD443\uD445", 14], - ["be61", "\uD454", 7, "\uD45D\uD45E\uD45F\uD461\uD462\uD463\uD465", 7, "\uD46E\uD470\uD471\uD472"], - ["be81", "\uD473", 4, "\uD47A\uD47B\uD47D\uD47E\uD481\uD483", 4, "\uD48A\uD48C\uD48E", 5, "\uD495", 8, "\uC434\uC43C\uC43D\uC448\uC464\uC465\uC468\uC46C\uC474\uC475\uC479\uC480\uC494\uC49C\uC4B8\uC4BC\uC4E9\uC4F0\uC4F1\uC4F4\uC4F8\uC4FA\uC4FF\uC500\uC501\uC50C\uC510\uC514\uC51C\uC528\uC529\uC52C\uC530\uC538\uC539\uC53B\uC53D\uC544\uC545\uC548\uC549\uC54A\uC54C\uC54D\uC54E\uC553\uC554\uC555\uC557\uC558\uC559\uC55D\uC55E\uC560\uC561\uC564\uC568\uC570\uC571\uC573\uC574\uC575\uC57C\uC57D\uC580\uC584\uC587\uC58C\uC58D\uC58F\uC591\uC595\uC597\uC598\uC59C\uC5A0\uC5A9\uC5B4\uC5B5\uC5B8\uC5B9\uC5BB\uC5BC\uC5BD\uC5BE\uC5C4", 6, "\uC5CC\uC5CE"], - ["bf41", "\uD49E", 10, "\uD4AA", 14], - ["bf61", "\uD4B9", 18, "\uD4CD\uD4CE\uD4CF\uD4D1\uD4D2\uD4D3\uD4D5"], - ["bf81", "\uD4D6", 5, "\uD4DD\uD4DE\uD4E0", 7, "\uD4E9\uD4EA\uD4EB\uD4ED\uD4EE\uD4EF\uD4F1", 6, "\uD4F9\uD4FA\uD4FC\uC5D0\uC5D1\uC5D4\uC5D8\uC5E0\uC5E1\uC5E3\uC5E5\uC5EC\uC5ED\uC5EE\uC5F0\uC5F4\uC5F6\uC5F7\uC5FC", 5, "\uC605\uC606\uC607\uC608\uC60C\uC610\uC618\uC619\uC61B\uC61C\uC624\uC625\uC628\uC62C\uC62D\uC62E\uC630\uC633\uC634\uC635\uC637\uC639\uC63B\uC640\uC641\uC644\uC648\uC650\uC651\uC653\uC654\uC655\uC65C\uC65D\uC660\uC66C\uC66F\uC671\uC678\uC679\uC67C\uC680\uC688\uC689\uC68B\uC68D\uC694\uC695\uC698\uC69C\uC6A4\uC6A5\uC6A7\uC6A9\uC6B0\uC6B1\uC6B4\uC6B8\uC6B9\uC6BA\uC6C0\uC6C1\uC6C3\uC6C5\uC6CC\uC6CD\uC6D0\uC6D4\uC6DC\uC6DD\uC6E0\uC6E1\uC6E8"], - ["c041", "\uD4FE", 5, "\uD505\uD506\uD507\uD509\uD50A\uD50B\uD50D", 6, "\uD516\uD518", 5], - ["c061", "\uD51E", 25], - ["c081", "\uD538\uD539\uD53A\uD53B\uD53E\uD53F\uD541\uD542\uD543\uD545", 6, "\uD54E\uD550\uD552", 5, "\uD55A\uD55B\uD55D\uD55E\uD55F\uD561\uD562\uD563\uC6E9\uC6EC\uC6F0\uC6F8\uC6F9\uC6FD\uC704\uC705\uC708\uC70C\uC714\uC715\uC717\uC719\uC720\uC721\uC724\uC728\uC730\uC731\uC733\uC735\uC737\uC73C\uC73D\uC740\uC744\uC74A\uC74C\uC74D\uC74F\uC751", 7, "\uC75C\uC760\uC768\uC76B\uC774\uC775\uC778\uC77C\uC77D\uC77E\uC783\uC784\uC785\uC787\uC788\uC789\uC78A\uC78E\uC790\uC791\uC794\uC796\uC797\uC798\uC79A\uC7A0\uC7A1\uC7A3\uC7A4\uC7A5\uC7A6\uC7AC\uC7AD\uC7B0\uC7B4\uC7BC\uC7BD\uC7BF\uC7C0\uC7C1\uC7C8\uC7C9\uC7CC\uC7CE\uC7D0\uC7D8\uC7DD\uC7E4\uC7E8\uC7EC\uC800\uC801\uC804\uC808\uC80A"], - ["c141", "\uD564\uD566\uD567\uD56A\uD56C\uD56E", 5, "\uD576\uD577\uD579\uD57A\uD57B\uD57D", 6, "\uD586\uD58A\uD58B"], - ["c161", "\uD58C\uD58D\uD58E\uD58F\uD591", 19, "\uD5A6\uD5A7"], - ["c181", "\uD5A8", 31, "\uC810\uC811\uC813\uC815\uC816\uC81C\uC81D\uC820\uC824\uC82C\uC82D\uC82F\uC831\uC838\uC83C\uC840\uC848\uC849\uC84C\uC84D\uC854\uC870\uC871\uC874\uC878\uC87A\uC880\uC881\uC883\uC885\uC886\uC887\uC88B\uC88C\uC88D\uC894\uC89D\uC89F\uC8A1\uC8A8\uC8BC\uC8BD\uC8C4\uC8C8\uC8CC\uC8D4\uC8D5\uC8D7\uC8D9\uC8E0\uC8E1\uC8E4\uC8F5\uC8FC\uC8FD\uC900\uC904\uC905\uC906\uC90C\uC90D\uC90F\uC911\uC918\uC92C\uC934\uC950\uC951\uC954\uC958\uC960\uC961\uC963\uC96C\uC970\uC974\uC97C\uC988\uC989\uC98C\uC990\uC998\uC999\uC99B\uC99D\uC9C0\uC9C1\uC9C4\uC9C7\uC9C8\uC9CA\uC9D0\uC9D1\uC9D3"], - ["c241", "\uD5CA\uD5CB\uD5CD\uD5CE\uD5CF\uD5D1\uD5D3", 4, "\uD5DA\uD5DC\uD5DE", 5, "\uD5E6\uD5E7\uD5E9\uD5EA\uD5EB\uD5ED\uD5EE"], - ["c261", "\uD5EF", 4, "\uD5F6\uD5F8\uD5FA", 5, "\uD602\uD603\uD605\uD606\uD607\uD609", 6, "\uD612"], - ["c281", "\uD616", 5, "\uD61D\uD61E\uD61F\uD621\uD622\uD623\uD625", 7, "\uD62E", 9, "\uD63A\uD63B\uC9D5\uC9D6\uC9D9\uC9DA\uC9DC\uC9DD\uC9E0\uC9E2\uC9E4\uC9E7\uC9EC\uC9ED\uC9EF\uC9F0\uC9F1\uC9F8\uC9F9\uC9FC\uCA00\uCA08\uCA09\uCA0B\uCA0C\uCA0D\uCA14\uCA18\uCA29\uCA4C\uCA4D\uCA50\uCA54\uCA5C\uCA5D\uCA5F\uCA60\uCA61\uCA68\uCA7D\uCA84\uCA98\uCABC\uCABD\uCAC0\uCAC4\uCACC\uCACD\uCACF\uCAD1\uCAD3\uCAD8\uCAD9\uCAE0\uCAEC\uCAF4\uCB08\uCB10\uCB14\uCB18\uCB20\uCB21\uCB41\uCB48\uCB49\uCB4C\uCB50\uCB58\uCB59\uCB5D\uCB64\uCB78\uCB79\uCB9C\uCBB8\uCBD4\uCBE4\uCBE7\uCBE9\uCC0C\uCC0D\uCC10\uCC14\uCC1C\uCC1D\uCC21\uCC22\uCC27\uCC28\uCC29\uCC2C\uCC2E\uCC30\uCC38\uCC39\uCC3B"], - ["c341", "\uD63D\uD63E\uD63F\uD641\uD642\uD643\uD644\uD646\uD647\uD64A\uD64C\uD64E\uD64F\uD650\uD652\uD653\uD656\uD657\uD659\uD65A\uD65B\uD65D", 4], - ["c361", "\uD662", 4, "\uD668\uD66A", 5, "\uD672\uD673\uD675", 11], - ["c381", "\uD681\uD682\uD684\uD686", 5, "\uD68E\uD68F\uD691\uD692\uD693\uD695", 7, "\uD69E\uD6A0\uD6A2", 5, "\uD6A9\uD6AA\uCC3C\uCC3D\uCC3E\uCC44\uCC45\uCC48\uCC4C\uCC54\uCC55\uCC57\uCC58\uCC59\uCC60\uCC64\uCC66\uCC68\uCC70\uCC75\uCC98\uCC99\uCC9C\uCCA0\uCCA8\uCCA9\uCCAB\uCCAC\uCCAD\uCCB4\uCCB5\uCCB8\uCCBC\uCCC4\uCCC5\uCCC7\uCCC9\uCCD0\uCCD4\uCCE4\uCCEC\uCCF0\uCD01\uCD08\uCD09\uCD0C\uCD10\uCD18\uCD19\uCD1B\uCD1D\uCD24\uCD28\uCD2C\uCD39\uCD5C\uCD60\uCD64\uCD6C\uCD6D\uCD6F\uCD71\uCD78\uCD88\uCD94\uCD95\uCD98\uCD9C\uCDA4\uCDA5\uCDA7\uCDA9\uCDB0\uCDC4\uCDCC\uCDD0\uCDE8\uCDEC\uCDF0\uCDF8\uCDF9\uCDFB\uCDFD\uCE04\uCE08\uCE0C\uCE14\uCE19\uCE20\uCE21\uCE24\uCE28\uCE30\uCE31\uCE33\uCE35"], - ["c441", "\uD6AB\uD6AD\uD6AE\uD6AF\uD6B1", 7, "\uD6BA\uD6BC", 7, "\uD6C6\uD6C7\uD6C9\uD6CA\uD6CB"], - ["c461", "\uD6CD\uD6CE\uD6CF\uD6D0\uD6D2\uD6D3\uD6D5\uD6D6\uD6D8\uD6DA", 5, "\uD6E1\uD6E2\uD6E3\uD6E5\uD6E6\uD6E7\uD6E9", 4], - ["c481", "\uD6EE\uD6EF\uD6F1\uD6F2\uD6F3\uD6F4\uD6F6", 5, "\uD6FE\uD6FF\uD701\uD702\uD703\uD705", 11, "\uD712\uD713\uD714\uCE58\uCE59\uCE5C\uCE5F\uCE60\uCE61\uCE68\uCE69\uCE6B\uCE6D\uCE74\uCE75\uCE78\uCE7C\uCE84\uCE85\uCE87\uCE89\uCE90\uCE91\uCE94\uCE98\uCEA0\uCEA1\uCEA3\uCEA4\uCEA5\uCEAC\uCEAD\uCEC1\uCEE4\uCEE5\uCEE8\uCEEB\uCEEC\uCEF4\uCEF5\uCEF7\uCEF8\uCEF9\uCF00\uCF01\uCF04\uCF08\uCF10\uCF11\uCF13\uCF15\uCF1C\uCF20\uCF24\uCF2C\uCF2D\uCF2F\uCF30\uCF31\uCF38\uCF54\uCF55\uCF58\uCF5C\uCF64\uCF65\uCF67\uCF69\uCF70\uCF71\uCF74\uCF78\uCF80\uCF85\uCF8C\uCFA1\uCFA8\uCFB0\uCFC4\uCFE0\uCFE1\uCFE4\uCFE8\uCFF0\uCFF1\uCFF3\uCFF5\uCFFC\uD000\uD004\uD011\uD018\uD02D\uD034\uD035\uD038\uD03C"], - ["c541", "\uD715\uD716\uD717\uD71A\uD71B\uD71D\uD71E\uD71F\uD721", 6, "\uD72A\uD72C\uD72E", 5, "\uD736\uD737\uD739"], - ["c561", "\uD73A\uD73B\uD73D", 6, "\uD745\uD746\uD748\uD74A", 5, "\uD752\uD753\uD755\uD75A", 4], - ["c581", "\uD75F\uD762\uD764\uD766\uD767\uD768\uD76A\uD76B\uD76D\uD76E\uD76F\uD771\uD772\uD773\uD775", 6, "\uD77E\uD77F\uD780\uD782", 5, "\uD78A\uD78B\uD044\uD045\uD047\uD049\uD050\uD054\uD058\uD060\uD06C\uD06D\uD070\uD074\uD07C\uD07D\uD081\uD0A4\uD0A5\uD0A8\uD0AC\uD0B4\uD0B5\uD0B7\uD0B9\uD0C0\uD0C1\uD0C4\uD0C8\uD0C9\uD0D0\uD0D1\uD0D3\uD0D4\uD0D5\uD0DC\uD0DD\uD0E0\uD0E4\uD0EC\uD0ED\uD0EF\uD0F0\uD0F1\uD0F8\uD10D\uD130\uD131\uD134\uD138\uD13A\uD140\uD141\uD143\uD144\uD145\uD14C\uD14D\uD150\uD154\uD15C\uD15D\uD15F\uD161\uD168\uD16C\uD17C\uD184\uD188\uD1A0\uD1A1\uD1A4\uD1A8\uD1B0\uD1B1\uD1B3\uD1B5\uD1BA\uD1BC\uD1C0\uD1D8\uD1F4\uD1F8\uD207\uD209\uD210\uD22C\uD22D\uD230\uD234\uD23C\uD23D\uD23F\uD241\uD248\uD25C"], - ["c641", "\uD78D\uD78E\uD78F\uD791", 6, "\uD79A\uD79C\uD79E", 5], - ["c6a1", "\uD264\uD280\uD281\uD284\uD288\uD290\uD291\uD295\uD29C\uD2A0\uD2A4\uD2AC\uD2B1\uD2B8\uD2B9\uD2BC\uD2BF\uD2C0\uD2C2\uD2C8\uD2C9\uD2CB\uD2D4\uD2D8\uD2DC\uD2E4\uD2E5\uD2F0\uD2F1\uD2F4\uD2F8\uD300\uD301\uD303\uD305\uD30C\uD30D\uD30E\uD310\uD314\uD316\uD31C\uD31D\uD31F\uD320\uD321\uD325\uD328\uD329\uD32C\uD330\uD338\uD339\uD33B\uD33C\uD33D\uD344\uD345\uD37C\uD37D\uD380\uD384\uD38C\uD38D\uD38F\uD390\uD391\uD398\uD399\uD39C\uD3A0\uD3A8\uD3A9\uD3AB\uD3AD\uD3B4\uD3B8\uD3BC\uD3C4\uD3C5\uD3C8\uD3C9\uD3D0\uD3D8\uD3E1\uD3E3\uD3EC\uD3ED\uD3F0\uD3F4\uD3FC\uD3FD\uD3FF\uD401"], - ["c7a1", "\uD408\uD41D\uD440\uD444\uD45C\uD460\uD464\uD46D\uD46F\uD478\uD479\uD47C\uD47F\uD480\uD482\uD488\uD489\uD48B\uD48D\uD494\uD4A9\uD4CC\uD4D0\uD4D4\uD4DC\uD4DF\uD4E8\uD4EC\uD4F0\uD4F8\uD4FB\uD4FD\uD504\uD508\uD50C\uD514\uD515\uD517\uD53C\uD53D\uD540\uD544\uD54C\uD54D\uD54F\uD551\uD558\uD559\uD55C\uD560\uD565\uD568\uD569\uD56B\uD56D\uD574\uD575\uD578\uD57C\uD584\uD585\uD587\uD588\uD589\uD590\uD5A5\uD5C8\uD5C9\uD5CC\uD5D0\uD5D2\uD5D8\uD5D9\uD5DB\uD5DD\uD5E4\uD5E5\uD5E8\uD5EC\uD5F4\uD5F5\uD5F7\uD5F9\uD600\uD601\uD604\uD608\uD610\uD611\uD613\uD614\uD615\uD61C\uD620"], - ["c8a1", "\uD624\uD62D\uD638\uD639\uD63C\uD640\uD645\uD648\uD649\uD64B\uD64D\uD651\uD654\uD655\uD658\uD65C\uD667\uD669\uD670\uD671\uD674\uD683\uD685\uD68C\uD68D\uD690\uD694\uD69D\uD69F\uD6A1\uD6A8\uD6AC\uD6B0\uD6B9\uD6BB\uD6C4\uD6C5\uD6C8\uD6CC\uD6D1\uD6D4\uD6D7\uD6D9\uD6E0\uD6E4\uD6E8\uD6F0\uD6F5\uD6FC\uD6FD\uD700\uD704\uD711\uD718\uD719\uD71C\uD720\uD728\uD729\uD72B\uD72D\uD734\uD735\uD738\uD73C\uD744\uD747\uD749\uD750\uD751\uD754\uD756\uD757\uD758\uD759\uD760\uD761\uD763\uD765\uD769\uD76C\uD770\uD774\uD77C\uD77D\uD781\uD788\uD789\uD78C\uD790\uD798\uD799\uD79B\uD79D"], - ["caa1", "\u4F3D\u4F73\u5047\u50F9\u52A0\u53EF\u5475\u54E5\u5609\u5AC1\u5BB6\u6687\u67B6\u67B7\u67EF\u6B4C\u73C2\u75C2\u7A3C\u82DB\u8304\u8857\u8888\u8A36\u8CC8\u8DCF\u8EFB\u8FE6\u99D5\u523B\u5374\u5404\u606A\u6164\u6BBC\u73CF\u811A\u89BA\u89D2\u95A3\u4F83\u520A\u58BE\u5978\u59E6\u5E72\u5E79\u61C7\u63C0\u6746\u67EC\u687F\u6F97\u764E\u770B\u78F5\u7A08\u7AFF\u7C21\u809D\u826E\u8271\u8AEB\u9593\u4E6B\u559D\u66F7\u6E34\u78A3\u7AED\u845B\u8910\u874E\u97A8\u52D8\u574E\u582A\u5D4C\u611F\u61BE\u6221\u6562\u67D1\u6A44\u6E1B\u7518\u75B3\u76E3\u77B0\u7D3A\u90AF\u9451\u9452\u9F95"], - ["cba1", "\u5323\u5CAC\u7532\u80DB\u9240\u9598\u525B\u5808\u59DC\u5CA1\u5D17\u5EB7\u5F3A\u5F4A\u6177\u6C5F\u757A\u7586\u7CE0\u7D73\u7DB1\u7F8C\u8154\u8221\u8591\u8941\u8B1B\u92FC\u964D\u9C47\u4ECB\u4EF7\u500B\u51F1\u584F\u6137\u613E\u6168\u6539\u69EA\u6F11\u75A5\u7686\u76D6\u7B87\u82A5\u84CB\uF900\u93A7\u958B\u5580\u5BA2\u5751\uF901\u7CB3\u7FB9\u91B5\u5028\u53BB\u5C45\u5DE8\u62D2\u636E\u64DA\u64E7\u6E20\u70AC\u795B\u8DDD\u8E1E\uF902\u907D\u9245\u92F8\u4E7E\u4EF6\u5065\u5DFE\u5EFA\u6106\u6957\u8171\u8654\u8E47\u9375\u9A2B\u4E5E\u5091\u6770\u6840\u5109\u528D\u5292\u6AA2"], - ["cca1", "\u77BC\u9210\u9ED4\u52AB\u602F\u8FF2\u5048\u61A9\u63ED\u64CA\u683C\u6A84\u6FC0\u8188\u89A1\u9694\u5805\u727D\u72AC\u7504\u7D79\u7E6D\u80A9\u898B\u8B74\u9063\u9D51\u6289\u6C7A\u6F54\u7D50\u7F3A\u8A23\u517C\u614A\u7B9D\u8B19\u9257\u938C\u4EAC\u4FD3\u501E\u50BE\u5106\u52C1\u52CD\u537F\u5770\u5883\u5E9A\u5F91\u6176\u61AC\u64CE\u656C\u666F\u66BB\u66F4\u6897\u6D87\u7085\u70F1\u749F\u74A5\u74CA\u75D9\u786C\u78EC\u7ADF\u7AF6\u7D45\u7D93\u8015\u803F\u811B\u8396\u8B66\u8F15\u9015\u93E1\u9803\u9838\u9A5A\u9BE8\u4FC2\u5553\u583A\u5951\u5B63\u5C46\u60B8\u6212\u6842\u68B0"], - ["cda1", "\u68E8\u6EAA\u754C\u7678\u78CE\u7A3D\u7CFB\u7E6B\u7E7C\u8A08\u8AA1\u8C3F\u968E\u9DC4\u53E4\u53E9\u544A\u5471\u56FA\u59D1\u5B64\u5C3B\u5EAB\u62F7\u6537\u6545\u6572\u66A0\u67AF\u69C1\u6CBD\u75FC\u7690\u777E\u7A3F\u7F94\u8003\u80A1\u818F\u82E6\u82FD\u83F0\u85C1\u8831\u88B4\u8AA5\uF903\u8F9C\u932E\u96C7\u9867\u9AD8\u9F13\u54ED\u659B\u66F2\u688F\u7A40\u8C37\u9D60\u56F0\u5764\u5D11\u6606\u68B1\u68CD\u6EFE\u7428\u889E\u9BE4\u6C68\uF904\u9AA8\u4F9B\u516C\u5171\u529F\u5B54\u5DE5\u6050\u606D\u62F1\u63A7\u653B\u73D9\u7A7A\u86A3\u8CA2\u978F\u4E32\u5BE1\u6208\u679C\u74DC"], - ["cea1", "\u79D1\u83D3\u8A87\u8AB2\u8DE8\u904E\u934B\u9846\u5ED3\u69E8\u85FF\u90ED\uF905\u51A0\u5B98\u5BEC\u6163\u68FA\u6B3E\u704C\u742F\u74D8\u7BA1\u7F50\u83C5\u89C0\u8CAB\u95DC\u9928\u522E\u605D\u62EC\u9002\u4F8A\u5149\u5321\u58D9\u5EE3\u66E0\u6D38\u709A\u72C2\u73D6\u7B50\u80F1\u945B\u5366\u639B\u7F6B\u4E56\u5080\u584A\u58DE\u602A\u6127\u62D0\u69D0\u9B41\u5B8F\u7D18\u80B1\u8F5F\u4EA4\u50D1\u54AC\u55AC\u5B0C\u5DA0\u5DE7\u652A\u654E\u6821\u6A4B\u72E1\u768E\u77EF\u7D5E\u7FF9\u81A0\u854E\u86DF\u8F03\u8F4E\u90CA\u9903\u9A55\u9BAB\u4E18\u4E45\u4E5D\u4EC7\u4FF1\u5177\u52FE"], - ["cfa1", "\u5340\u53E3\u53E5\u548E\u5614\u5775\u57A2\u5BC7\u5D87\u5ED0\u61FC\u62D8\u6551\u67B8\u67E9\u69CB\u6B50\u6BC6\u6BEC\u6C42\u6E9D\u7078\u72D7\u7396\u7403\u77BF\u77E9\u7A76\u7D7F\u8009\u81FC\u8205\u820A\u82DF\u8862\u8B33\u8CFC\u8EC0\u9011\u90B1\u9264\u92B6\u99D2\u9A45\u9CE9\u9DD7\u9F9C\u570B\u5C40\u83CA\u97A0\u97AB\u9EB4\u541B\u7A98\u7FA4\u88D9\u8ECD\u90E1\u5800\u5C48\u6398\u7A9F\u5BAE\u5F13\u7A79\u7AAE\u828E\u8EAC\u5026\u5238\u52F8\u5377\u5708\u62F3\u6372\u6B0A\u6DC3\u7737\u53A5\u7357\u8568\u8E76\u95D5\u673A\u6AC3\u6F70\u8A6D\u8ECC\u994B\uF906\u6677\u6B78\u8CB4"], - ["d0a1", "\u9B3C\uF907\u53EB\u572D\u594E\u63C6\u69FB\u73EA\u7845\u7ABA\u7AC5\u7CFE\u8475\u898F\u8D73\u9035\u95A8\u52FB\u5747\u7547\u7B60\u83CC\u921E\uF908\u6A58\u514B\u524B\u5287\u621F\u68D8\u6975\u9699\u50C5\u52A4\u52E4\u61C3\u65A4\u6839\u69FF\u747E\u7B4B\u82B9\u83EB\u89B2\u8B39\u8FD1\u9949\uF909\u4ECA\u5997\u64D2\u6611\u6A8E\u7434\u7981\u79BD\u82A9\u887E\u887F\u895F\uF90A\u9326\u4F0B\u53CA\u6025\u6271\u6C72\u7D1A\u7D66\u4E98\u5162\u77DC\u80AF\u4F01\u4F0E\u5176\u5180\u55DC\u5668\u573B\u57FA\u57FC\u5914\u5947\u5993\u5BC4\u5C90\u5D0E\u5DF1\u5E7E\u5FCC\u6280\u65D7\u65E3"], - ["d1a1", "\u671E\u671F\u675E\u68CB\u68C4\u6A5F\u6B3A\u6C23\u6C7D\u6C82\u6DC7\u7398\u7426\u742A\u7482\u74A3\u7578\u757F\u7881\u78EF\u7941\u7947\u7948\u797A\u7B95\u7D00\u7DBA\u7F88\u8006\u802D\u808C\u8A18\u8B4F\u8C48\u8D77\u9321\u9324\u98E2\u9951\u9A0E\u9A0F\u9A65\u9E92\u7DCA\u4F76\u5409\u62EE\u6854\u91D1\u55AB\u513A\uF90B\uF90C\u5A1C\u61E6\uF90D\u62CF\u62FF\uF90E", 5, "\u90A3\uF914", 4, "\u8AFE\uF919\uF91A\uF91B\uF91C\u6696\uF91D\u7156\uF91E\uF91F\u96E3\uF920\u634F\u637A\u5357\uF921\u678F\u6960\u6E73\uF922\u7537\uF923\uF924\uF925"], - ["d2a1", "\u7D0D\uF926\uF927\u8872\u56CA\u5A18\uF928", 4, "\u4E43\uF92D\u5167\u5948\u67F0\u8010\uF92E\u5973\u5E74\u649A\u79CA\u5FF5\u606C\u62C8\u637B\u5BE7\u5BD7\u52AA\uF92F\u5974\u5F29\u6012\uF930\uF931\uF932\u7459\uF933", 5, "\u99D1\uF939", 10, "\u6FC3\uF944\uF945\u81BF\u8FB2\u60F1\uF946\uF947\u8166\uF948\uF949\u5C3F\uF94A", 7, "\u5AE9\u8A25\u677B\u7D10\uF952", 5, "\u80FD\uF958\uF959\u5C3C\u6CE5\u533F\u6EBA\u591A\u8336"], - ["d3a1", "\u4E39\u4EB6\u4F46\u55AE\u5718\u58C7\u5F56\u65B7\u65E6\u6A80\u6BB5\u6E4D\u77ED\u7AEF\u7C1E\u7DDE\u86CB\u8892\u9132\u935B\u64BB\u6FBE\u737A\u75B8\u9054\u5556\u574D\u61BA\u64D4\u66C7\u6DE1\u6E5B\u6F6D\u6FB9\u75F0\u8043\u81BD\u8541\u8983\u8AC7\u8B5A\u931F\u6C93\u7553\u7B54\u8E0F\u905D\u5510\u5802\u5858\u5E62\u6207\u649E\u68E0\u7576\u7CD6\u87B3\u9EE8\u4EE3\u5788\u576E\u5927\u5C0D\u5CB1\u5E36\u5F85\u6234\u64E1\u73B3\u81FA\u888B\u8CB8\u968A\u9EDB\u5B85\u5FB7\u60B3\u5012\u5200\u5230\u5716\u5835\u5857\u5C0E\u5C60\u5CF6\u5D8B\u5EA6\u5F92\u60BC\u6311\u6389\u6417\u6843"], - ["d4a1", "\u68F9\u6AC2\u6DD8\u6E21\u6ED4\u6FE4\u71FE\u76DC\u7779\u79B1\u7A3B\u8404\u89A9\u8CED\u8DF3\u8E48\u9003\u9014\u9053\u90FD\u934D\u9676\u97DC\u6BD2\u7006\u7258\u72A2\u7368\u7763\u79BF\u7BE4\u7E9B\u8B80\u58A9\u60C7\u6566\u65FD\u66BE\u6C8C\u711E\u71C9\u8C5A\u9813\u4E6D\u7A81\u4EDD\u51AC\u51CD\u52D5\u540C\u61A7\u6771\u6850\u68DF\u6D1E\u6F7C\u75BC\u77B3\u7AE5\u80F4\u8463\u9285\u515C\u6597\u675C\u6793\u75D8\u7AC7\u8373\uF95A\u8C46\u9017\u982D\u5C6F\u81C0\u829A\u9041\u906F\u920D\u5F97\u5D9D\u6A59\u71C8\u767B\u7B49\u85E4\u8B04\u9127\u9A30\u5587\u61F6\uF95B\u7669\u7F85"], - ["d5a1", "\u863F\u87BA\u88F8\u908F\uF95C\u6D1B\u70D9\u73DE\u7D61\u843D\uF95D\u916A\u99F1\uF95E\u4E82\u5375\u6B04\u6B12\u703E\u721B\u862D\u9E1E\u524C\u8FA3\u5D50\u64E5\u652C\u6B16\u6FEB\u7C43\u7E9C\u85CD\u8964\u89BD\u62C9\u81D8\u881F\u5ECA\u6717\u6D6A\u72FC\u7405\u746F\u8782\u90DE\u4F86\u5D0D\u5FA0\u840A\u51B7\u63A0\u7565\u4EAE\u5006\u5169\u51C9\u6881\u6A11\u7CAE\u7CB1\u7CE7\u826F\u8AD2\u8F1B\u91CF\u4FB6\u5137\u52F5\u5442\u5EEC\u616E\u623E\u65C5\u6ADA\u6FFE\u792A\u85DC\u8823\u95AD\u9A62\u9A6A\u9E97\u9ECE\u529B\u66C6\u6B77\u701D\u792B\u8F62\u9742\u6190\u6200\u6523\u6F23"], - ["d6a1", "\u7149\u7489\u7DF4\u806F\u84EE\u8F26\u9023\u934A\u51BD\u5217\u52A3\u6D0C\u70C8\u88C2\u5EC9\u6582\u6BAE\u6FC2\u7C3E\u7375\u4EE4\u4F36\u56F9\uF95F\u5CBA\u5DBA\u601C\u73B2\u7B2D\u7F9A\u7FCE\u8046\u901E\u9234\u96F6\u9748\u9818\u9F61\u4F8B\u6FA7\u79AE\u91B4\u96B7\u52DE\uF960\u6488\u64C4\u6AD3\u6F5E\u7018\u7210\u76E7\u8001\u8606\u865C\u8DEF\u8F05\u9732\u9B6F\u9DFA\u9E75\u788C\u797F\u7DA0\u83C9\u9304\u9E7F\u9E93\u8AD6\u58DF\u5F04\u6727\u7027\u74CF\u7C60\u807E\u5121\u7028\u7262\u78CA\u8CC2\u8CDA\u8CF4\u96F7\u4E86\u50DA\u5BEE\u5ED6\u6599\u71CE\u7642\u77AD\u804A\u84FC"], - ["d7a1", "\u907C\u9B27\u9F8D\u58D8\u5A41\u5C62\u6A13\u6DDA\u6F0F\u763B\u7D2F\u7E37\u851E\u8938\u93E4\u964B\u5289\u65D2\u67F3\u69B4\u6D41\u6E9C\u700F\u7409\u7460\u7559\u7624\u786B\u8B2C\u985E\u516D\u622E\u9678\u4F96\u502B\u5D19\u6DEA\u7DB8\u8F2A\u5F8B\u6144\u6817\uF961\u9686\u52D2\u808B\u51DC\u51CC\u695E\u7A1C\u7DBE\u83F1\u9675\u4FDA\u5229\u5398\u540F\u550E\u5C65\u60A7\u674E\u68A8\u6D6C\u7281\u72F8\u7406\u7483\uF962\u75E2\u7C6C\u7F79\u7FB8\u8389\u88CF\u88E1\u91CC\u91D0\u96E2\u9BC9\u541D\u6F7E\u71D0\u7498\u85FA\u8EAA\u96A3\u9C57\u9E9F\u6797\u6DCB\u7433\u81E8\u9716\u782C"], - ["d8a1", "\u7ACB\u7B20\u7C92\u6469\u746A\u75F2\u78BC\u78E8\u99AC\u9B54\u9EBB\u5BDE\u5E55\u6F20\u819C\u83AB\u9088\u4E07\u534D\u5A29\u5DD2\u5F4E\u6162\u633D\u6669\u66FC\u6EFF\u6F2B\u7063\u779E\u842C\u8513\u883B\u8F13\u9945\u9C3B\u551C\u62B9\u672B\u6CAB\u8309\u896A\u977A\u4EA1\u5984\u5FD8\u5FD9\u671B\u7DB2\u7F54\u8292\u832B\u83BD\u8F1E\u9099\u57CB\u59B9\u5A92\u5BD0\u6627\u679A\u6885\u6BCF\u7164\u7F75\u8CB7\u8CE3\u9081\u9B45\u8108\u8C8A\u964C\u9A40\u9EA5\u5B5F\u6C13\u731B\u76F2\u76DF\u840C\u51AA\u8993\u514D\u5195\u52C9\u68C9\u6C94\u7704\u7720\u7DBF\u7DEC\u9762\u9EB5\u6EC5"], - ["d9a1", "\u8511\u51A5\u540D\u547D\u660E\u669D\u6927\u6E9F\u76BF\u7791\u8317\u84C2\u879F\u9169\u9298\u9CF4\u8882\u4FAE\u5192\u52DF\u59C6\u5E3D\u6155\u6478\u6479\u66AE\u67D0\u6A21\u6BCD\u6BDB\u725F\u7261\u7441\u7738\u77DB\u8017\u82BC\u8305\u8B00\u8B28\u8C8C\u6728\u6C90\u7267\u76EE\u7766\u7A46\u9DA9\u6B7F\u6C92\u5922\u6726\u8499\u536F\u5893\u5999\u5EDF\u63CF\u6634\u6773\u6E3A\u732B\u7AD7\u82D7\u9328\u52D9\u5DEB\u61AE\u61CB\u620A\u62C7\u64AB\u65E0\u6959\u6B66\u6BCB\u7121\u73F7\u755D\u7E46\u821E\u8302\u856A\u8AA3\u8CBF\u9727\u9D61\u58A8\u9ED8\u5011\u520E\u543B\u554F\u6587"], - ["daa1", "\u6C76\u7D0A\u7D0B\u805E\u868A\u9580\u96EF\u52FF\u6C95\u7269\u5473\u5A9A\u5C3E\u5D4B\u5F4C\u5FAE\u672A\u68B6\u6963\u6E3C\u6E44\u7709\u7C73\u7F8E\u8587\u8B0E\u8FF7\u9761\u9EF4\u5CB7\u60B6\u610D\u61AB\u654F\u65FB\u65FC\u6C11\u6CEF\u739F\u73C9\u7DE1\u9594\u5BC6\u871C\u8B10\u525D\u535A\u62CD\u640F\u64B2\u6734\u6A38\u6CCA\u73C0\u749E\u7B94\u7C95\u7E1B\u818A\u8236\u8584\u8FEB\u96F9\u99C1\u4F34\u534A\u53CD\u53DB\u62CC\u642C\u6500\u6591\u69C3\u6CEE\u6F58\u73ED\u7554\u7622\u76E4\u76FC\u78D0\u78FB\u792C\u7D46\u822C\u87E0\u8FD4\u9812\u98EF\u52C3\u62D4\u64A5\u6E24\u6F51"], - ["dba1", "\u767C\u8DCB\u91B1\u9262\u9AEE\u9B43\u5023\u508D\u574A\u59A8\u5C28\u5E47\u5F77\u623F\u653E\u65B9\u65C1\u6609\u678B\u699C\u6EC2\u78C5\u7D21\u80AA\u8180\u822B\u82B3\u84A1\u868C\u8A2A\u8B17\u90A6\u9632\u9F90\u500D\u4FF3\uF963\u57F9\u5F98\u62DC\u6392\u676F\u6E43\u7119\u76C3\u80CC\u80DA\u88F4\u88F5\u8919\u8CE0\u8F29\u914D\u966A\u4F2F\u4F70\u5E1B\u67CF\u6822\u767D\u767E\u9B44\u5E61\u6A0A\u7169\u71D4\u756A\uF964\u7E41\u8543\u85E9\u98DC\u4F10\u7B4F\u7F70\u95A5\u51E1\u5E06\u68B5\u6C3E\u6C4E\u6CDB\u72AF\u7BC4\u8303\u6CD5\u743A\u50FB\u5288\u58C1\u64D8\u6A97\u74A7\u7656"], - ["dca1", "\u78A7\u8617\u95E2\u9739\uF965\u535E\u5F01\u8B8A\u8FA8\u8FAF\u908A\u5225\u77A5\u9C49\u9F08\u4E19\u5002\u5175\u5C5B\u5E77\u661E\u663A\u67C4\u68C5\u70B3\u7501\u75C5\u79C9\u7ADD\u8F27\u9920\u9A08\u4FDD\u5821\u5831\u5BF6\u666E\u6B65\u6D11\u6E7A\u6F7D\u73E4\u752B\u83E9\u88DC\u8913\u8B5C\u8F14\u4F0F\u50D5\u5310\u535C\u5B93\u5FA9\u670D\u798F\u8179\u832F\u8514\u8907\u8986\u8F39\u8F3B\u99A5\u9C12\u672C\u4E76\u4FF8\u5949\u5C01\u5CEF\u5CF0\u6367\u68D2\u70FD\u71A2\u742B\u7E2B\u84EC\u8702\u9022\u92D2\u9CF3\u4E0D\u4ED8\u4FEF\u5085\u5256\u526F\u5426\u5490\u57E0\u592B\u5A66"], - ["dda1", "\u5B5A\u5B75\u5BCC\u5E9C\uF966\u6276\u6577\u65A7\u6D6E\u6EA5\u7236\u7B26\u7C3F\u7F36\u8150\u8151\u819A\u8240\u8299\u83A9\u8A03\u8CA0\u8CE6\u8CFB\u8D74\u8DBA\u90E8\u91DC\u961C\u9644\u99D9\u9CE7\u5317\u5206\u5429\u5674\u58B3\u5954\u596E\u5FFF\u61A4\u626E\u6610\u6C7E\u711A\u76C6\u7C89\u7CDE\u7D1B\u82AC\u8CC1\u96F0\uF967\u4F5B\u5F17\u5F7F\u62C2\u5D29\u670B\u68DA\u787C\u7E43\u9D6C\u4E15\u5099\u5315\u532A\u5351\u5983\u5A62\u5E87\u60B2\u618A\u6249\u6279\u6590\u6787\u69A7\u6BD4\u6BD6\u6BD7\u6BD8\u6CB8\uF968\u7435\u75FA\u7812\u7891\u79D5\u79D8\u7C83\u7DCB\u7FE1\u80A5"], - ["dea1", "\u813E\u81C2\u83F2\u871A\u88E8\u8AB9\u8B6C\u8CBB\u9119\u975E\u98DB\u9F3B\u56AC\u5B2A\u5F6C\u658C\u6AB3\u6BAF\u6D5C\u6FF1\u7015\u725D\u73AD\u8CA7\u8CD3\u983B\u6191\u6C37\u8058\u9A01\u4E4D\u4E8B\u4E9B\u4ED5\u4F3A\u4F3C\u4F7F\u4FDF\u50FF\u53F2\u53F8\u5506\u55E3\u56DB\u58EB\u5962\u5A11\u5BEB\u5BFA\u5C04\u5DF3\u5E2B\u5F99\u601D\u6368\u659C\u65AF\u67F6\u67FB\u68AD\u6B7B\u6C99\u6CD7\u6E23\u7009\u7345\u7802\u793E\u7940\u7960\u79C1\u7BE9\u7D17\u7D72\u8086\u820D\u838E\u84D1\u86C7\u88DF\u8A50\u8A5E\u8B1D\u8CDC\u8D66\u8FAD\u90AA\u98FC\u99DF\u9E9D\u524A\uF969\u6714\uF96A"], - ["dfa1", "\u5098\u522A\u5C71\u6563\u6C55\u73CA\u7523\u759D\u7B97\u849C\u9178\u9730\u4E77\u6492\u6BBA\u715E\u85A9\u4E09\uF96B\u6749\u68EE\u6E17\u829F\u8518\u886B\u63F7\u6F81\u9212\u98AF\u4E0A\u50B7\u50CF\u511F\u5546\u55AA\u5617\u5B40\u5C19\u5CE0\u5E38\u5E8A\u5EA0\u5EC2\u60F3\u6851\u6A61\u6E58\u723D\u7240\u72C0\u76F8\u7965\u7BB1\u7FD4\u88F3\u89F4\u8A73\u8C61\u8CDE\u971C\u585E\u74BD\u8CFD\u55C7\uF96C\u7A61\u7D22\u8272\u7272\u751F\u7525\uF96D\u7B19\u5885\u58FB\u5DBC\u5E8F\u5EB6\u5F90\u6055\u6292\u637F\u654D\u6691\u66D9\u66F8\u6816\u68F2\u7280\u745E\u7B6E\u7D6E\u7DD6\u7F72"], - ["e0a1", "\u80E5\u8212\u85AF\u897F\u8A93\u901D\u92E4\u9ECD\u9F20\u5915\u596D\u5E2D\u60DC\u6614\u6673\u6790\u6C50\u6DC5\u6F5F\u77F3\u78A9\u84C6\u91CB\u932B\u4ED9\u50CA\u5148\u5584\u5B0B\u5BA3\u6247\u657E\u65CB\u6E32\u717D\u7401\u7444\u7487\u74BF\u766C\u79AA\u7DDA\u7E55\u7FA8\u817A\u81B3\u8239\u861A\u87EC\u8A75\u8DE3\u9078\u9291\u9425\u994D\u9BAE\u5368\u5C51\u6954\u6CC4\u6D29\u6E2B\u820C\u859B\u893B\u8A2D\u8AAA\u96EA\u9F67\u5261\u66B9\u6BB2\u7E96\u87FE\u8D0D\u9583\u965D\u651D\u6D89\u71EE\uF96E\u57CE\u59D3\u5BAC\u6027\u60FA\u6210\u661F\u665F\u7329\u73F9\u76DB\u7701\u7B6C"], - ["e1a1", "\u8056\u8072\u8165\u8AA0\u9192\u4E16\u52E2\u6B72\u6D17\u7A05\u7B39\u7D30\uF96F\u8CB0\u53EC\u562F\u5851\u5BB5\u5C0F\u5C11\u5DE2\u6240\u6383\u6414\u662D\u68B3\u6CBC\u6D88\u6EAF\u701F\u70A4\u71D2\u7526\u758F\u758E\u7619\u7B11\u7BE0\u7C2B\u7D20\u7D39\u852C\u856D\u8607\u8A34\u900D\u9061\u90B5\u92B7\u97F6\u9A37\u4FD7\u5C6C\u675F\u6D91\u7C9F\u7E8C\u8B16\u8D16\u901F\u5B6B\u5DFD\u640D\u84C0\u905C\u98E1\u7387\u5B8B\u609A\u677E\u6DDE\u8A1F\u8AA6\u9001\u980C\u5237\uF970\u7051\u788E\u9396\u8870\u91D7\u4FEE\u53D7\u55FD\u56DA\u5782\u58FD\u5AC2\u5B88\u5CAB\u5CC0\u5E25\u6101"], - ["e2a1", "\u620D\u624B\u6388\u641C\u6536\u6578\u6A39\u6B8A\u6C34\u6D19\u6F31\u71E7\u72E9\u7378\u7407\u74B2\u7626\u7761\u79C0\u7A57\u7AEA\u7CB9\u7D8F\u7DAC\u7E61\u7F9E\u8129\u8331\u8490\u84DA\u85EA\u8896\u8AB0\u8B90\u8F38\u9042\u9083\u916C\u9296\u92B9\u968B\u96A7\u96A8\u96D6\u9700\u9808\u9996\u9AD3\u9B1A\u53D4\u587E\u5919\u5B70\u5BBF\u6DD1\u6F5A\u719F\u7421\u74B9\u8085\u83FD\u5DE1\u5F87\u5FAA\u6042\u65EC\u6812\u696F\u6A53\u6B89\u6D35\u6DF3\u73E3\u76FE\u77AC\u7B4D\u7D14\u8123\u821C\u8340\u84F4\u8563\u8A62\u8AC4\u9187\u931E\u9806\u99B4\u620C\u8853\u8FF0\u9265\u5D07\u5D27"], - ["e3a1", "\u5D69\u745F\u819D\u8768\u6FD5\u62FE\u7FD2\u8936\u8972\u4E1E\u4E58\u50E7\u52DD\u5347\u627F\u6607\u7E69\u8805\u965E\u4F8D\u5319\u5636\u59CB\u5AA4\u5C38\u5C4E\u5C4D\u5E02\u5F11\u6043\u65BD\u662F\u6642\u67BE\u67F4\u731C\u77E2\u793A\u7FC5\u8494\u84CD\u8996\u8A66\u8A69\u8AE1\u8C55\u8C7A\u57F4\u5BD4\u5F0F\u606F\u62ED\u690D\u6B96\u6E5C\u7184\u7BD2\u8755\u8B58\u8EFE\u98DF\u98FE\u4F38\u4F81\u4FE1\u547B\u5A20\u5BB8\u613C\u65B0\u6668\u71FC\u7533\u795E\u7D33\u814E\u81E3\u8398\u85AA\u85CE\u8703\u8A0A\u8EAB\u8F9B\uF971\u8FC5\u5931\u5BA4\u5BE6\u6089\u5BE9\u5C0B\u5FC3\u6C81"], - ["e4a1", "\uF972\u6DF1\u700B\u751A\u82AF\u8AF6\u4EC0\u5341\uF973\u96D9\u6C0F\u4E9E\u4FC4\u5152\u555E\u5A25\u5CE8\u6211\u7259\u82BD\u83AA\u86FE\u8859\u8A1D\u963F\u96C5\u9913\u9D09\u9D5D\u580A\u5CB3\u5DBD\u5E44\u60E1\u6115\u63E1\u6A02\u6E25\u9102\u9354\u984E\u9C10\u9F77\u5B89\u5CB8\u6309\u664F\u6848\u773C\u96C1\u978D\u9854\u9B9F\u65A1\u8B01\u8ECB\u95BC\u5535\u5CA9\u5DD6\u5EB5\u6697\u764C\u83F4\u95C7\u58D3\u62BC\u72CE\u9D28\u4EF0\u592E\u600F\u663B\u6B83\u79E7\u9D26\u5393\u54C0\u57C3\u5D16\u611B\u66D6\u6DAF\u788D\u827E\u9698\u9744\u5384\u627C\u6396\u6DB2\u7E0A\u814B\u984D"], - ["e5a1", "\u6AFB\u7F4C\u9DAF\u9E1A\u4E5F\u503B\u51B6\u591C\u60F9\u63F6\u6930\u723A\u8036\uF974\u91CE\u5F31\uF975\uF976\u7D04\u82E5\u846F\u84BB\u85E5\u8E8D\uF977\u4F6F\uF978\uF979\u58E4\u5B43\u6059\u63DA\u6518\u656D\u6698\uF97A\u694A\u6A23\u6D0B\u7001\u716C\u75D2\u760D\u79B3\u7A70\uF97B\u7F8A\uF97C\u8944\uF97D\u8B93\u91C0\u967D\uF97E\u990A\u5704\u5FA1\u65BC\u6F01\u7600\u79A6\u8A9E\u99AD\u9B5A\u9F6C\u5104\u61B6\u6291\u6A8D\u81C6\u5043\u5830\u5F66\u7109\u8A00\u8AFA\u5B7C\u8616\u4FFA\u513C\u56B4\u5944\u63A9\u6DF9\u5DAA\u696D\u5186\u4E88\u4F59\uF97F\uF980\uF981\u5982\uF982"], - ["e6a1", "\uF983\u6B5F\u6C5D\uF984\u74B5\u7916\uF985\u8207\u8245\u8339\u8F3F\u8F5D\uF986\u9918\uF987\uF988\uF989\u4EA6\uF98A\u57DF\u5F79\u6613\uF98B\uF98C\u75AB\u7E79\u8B6F\uF98D\u9006\u9A5B\u56A5\u5827\u59F8\u5A1F\u5BB4\uF98E\u5EF6\uF98F\uF990\u6350\u633B\uF991\u693D\u6C87\u6CBF\u6D8E\u6D93\u6DF5\u6F14\uF992\u70DF\u7136\u7159\uF993\u71C3\u71D5\uF994\u784F\u786F\uF995\u7B75\u7DE3\uF996\u7E2F\uF997\u884D\u8EDF\uF998\uF999\uF99A\u925B\uF99B\u9CF6\uF99C\uF99D\uF99E\u6085\u6D85\uF99F\u71B1\uF9A0\uF9A1\u95B1\u53AD\uF9A2\uF9A3\uF9A4\u67D3\uF9A5\u708E\u7130\u7430\u8276\u82D2"], - ["e7a1", "\uF9A6\u95BB\u9AE5\u9E7D\u66C4\uF9A7\u71C1\u8449\uF9A8\uF9A9\u584B\uF9AA\uF9AB\u5DB8\u5F71\uF9AC\u6620\u668E\u6979\u69AE\u6C38\u6CF3\u6E36\u6F41\u6FDA\u701B\u702F\u7150\u71DF\u7370\uF9AD\u745B\uF9AE\u74D4\u76C8\u7A4E\u7E93\uF9AF\uF9B0\u82F1\u8A60\u8FCE\uF9B1\u9348\uF9B2\u9719\uF9B3\uF9B4\u4E42\u502A\uF9B5\u5208\u53E1\u66F3\u6C6D\u6FCA\u730A\u777F\u7A62\u82AE\u85DD\u8602\uF9B6\u88D4\u8A63\u8B7D\u8C6B\uF9B7\u92B3\uF9B8\u9713\u9810\u4E94\u4F0D\u4FC9\u50B2\u5348\u543E\u5433\u55DA\u5862\u58BA\u5967\u5A1B\u5BE4\u609F\uF9B9\u61CA\u6556\u65FF\u6664\u68A7\u6C5A\u6FB3"], - ["e8a1", "\u70CF\u71AC\u7352\u7B7D\u8708\u8AA4\u9C32\u9F07\u5C4B\u6C83\u7344\u7389\u923A\u6EAB\u7465\u761F\u7A69\u7E15\u860A\u5140\u58C5\u64C1\u74EE\u7515\u7670\u7FC1\u9095\u96CD\u9954\u6E26\u74E6\u7AA9\u7AAA\u81E5\u86D9\u8778\u8A1B\u5A49\u5B8C\u5B9B\u68A1\u6900\u6D63\u73A9\u7413\u742C\u7897\u7DE9\u7FEB\u8118\u8155\u839E\u8C4C\u962E\u9811\u66F0\u5F80\u65FA\u6789\u6C6A\u738B\u502D\u5A03\u6B6A\u77EE\u5916\u5D6C\u5DCD\u7325\u754F\uF9BA\uF9BB\u50E5\u51F9\u582F\u592D\u5996\u59DA\u5BE5\uF9BC\uF9BD\u5DA2\u62D7\u6416\u6493\u64FE\uF9BE\u66DC\uF9BF\u6A48\uF9C0\u71FF\u7464\uF9C1"], - ["e9a1", "\u7A88\u7AAF\u7E47\u7E5E\u8000\u8170\uF9C2\u87EF\u8981\u8B20\u9059\uF9C3\u9080\u9952\u617E\u6B32\u6D74\u7E1F\u8925\u8FB1\u4FD1\u50AD\u5197\u52C7\u57C7\u5889\u5BB9\u5EB8\u6142\u6995\u6D8C\u6E67\u6EB6\u7194\u7462\u7528\u752C\u8073\u8338\u84C9\u8E0A\u9394\u93DE\uF9C4\u4E8E\u4F51\u5076\u512A\u53C8\u53CB\u53F3\u5B87\u5BD3\u5C24\u611A\u6182\u65F4\u725B\u7397\u7440\u76C2\u7950\u7991\u79B9\u7D06\u7FBD\u828B\u85D5\u865E\u8FC2\u9047\u90F5\u91EA\u9685\u96E8\u96E9\u52D6\u5F67\u65ED\u6631\u682F\u715C\u7A36\u90C1\u980A\u4E91\uF9C5\u6A52\u6B9E\u6F90\u7189\u8018\u82B8\u8553"], - ["eaa1", "\u904B\u9695\u96F2\u97FB\u851A\u9B31\u4E90\u718A\u96C4\u5143\u539F\u54E1\u5713\u5712\u57A3\u5A9B\u5AC4\u5BC3\u6028\u613F\u63F4\u6C85\u6D39\u6E72\u6E90\u7230\u733F\u7457\u82D1\u8881\u8F45\u9060\uF9C6\u9662\u9858\u9D1B\u6708\u8D8A\u925E\u4F4D\u5049\u50DE\u5371\u570D\u59D4\u5A01\u5C09\u6170\u6690\u6E2D\u7232\u744B\u7DEF\u80C3\u840E\u8466\u853F\u875F\u885B\u8918\u8B02\u9055\u97CB\u9B4F\u4E73\u4F91\u5112\u516A\uF9C7\u552F\u55A9\u5B7A\u5BA5\u5E7C\u5E7D\u5EBE\u60A0\u60DF\u6108\u6109\u63C4\u6538\u6709\uF9C8\u67D4\u67DA\uF9C9\u6961\u6962\u6CB9\u6D27\uF9CA\u6E38\uF9CB"], - ["eba1", "\u6FE1\u7336\u7337\uF9CC\u745C\u7531\uF9CD\u7652\uF9CE\uF9CF\u7DAD\u81FE\u8438\u88D5\u8A98\u8ADB\u8AED\u8E30\u8E42\u904A\u903E\u907A\u9149\u91C9\u936E\uF9D0\uF9D1\u5809\uF9D2\u6BD3\u8089\u80B2\uF9D3\uF9D4\u5141\u596B\u5C39\uF9D5\uF9D6\u6F64\u73A7\u80E4\u8D07\uF9D7\u9217\u958F\uF9D8\uF9D9\uF9DA\uF9DB\u807F\u620E\u701C\u7D68\u878D\uF9DC\u57A0\u6069\u6147\u6BB7\u8ABE\u9280\u96B1\u4E59\u541F\u6DEB\u852D\u9670\u97F3\u98EE\u63D6\u6CE3\u9091\u51DD\u61C9\u81BA\u9DF9\u4F9D\u501A\u5100\u5B9C\u610F\u61FF\u64EC\u6905\u6BC5\u7591\u77E3\u7FA9\u8264\u858F\u87FB\u8863\u8ABC"], - ["eca1", "\u8B70\u91AB\u4E8C\u4EE5\u4F0A\uF9DD\uF9DE\u5937\u59E8\uF9DF\u5DF2\u5F1B\u5F5B\u6021\uF9E0\uF9E1\uF9E2\uF9E3\u723E\u73E5\uF9E4\u7570\u75CD\uF9E5\u79FB\uF9E6\u800C\u8033\u8084\u82E1\u8351\uF9E7\uF9E8\u8CBD\u8CB3\u9087\uF9E9\uF9EA\u98F4\u990C\uF9EB\uF9EC\u7037\u76CA\u7FCA\u7FCC\u7FFC\u8B1A\u4EBA\u4EC1\u5203\u5370\uF9ED\u54BD\u56E0\u59FB\u5BC5\u5F15\u5FCD\u6E6E\uF9EE\uF9EF\u7D6A\u8335\uF9F0\u8693\u8A8D\uF9F1\u976D\u9777\uF9F2\uF9F3\u4E00\u4F5A\u4F7E\u58F9\u65E5\u6EA2\u9038\u93B0\u99B9\u4EFB\u58EC\u598A\u59D9\u6041\uF9F4\uF9F5\u7A14\uF9F6\u834F\u8CC3\u5165\u5344"], - ["eda1", "\uF9F7\uF9F8\uF9F9\u4ECD\u5269\u5B55\u82BF\u4ED4\u523A\u54A8\u59C9\u59FF\u5B50\u5B57\u5B5C\u6063\u6148\u6ECB\u7099\u716E\u7386\u74F7\u75B5\u78C1\u7D2B\u8005\u81EA\u8328\u8517\u85C9\u8AEE\u8CC7\u96CC\u4F5C\u52FA\u56BC\u65AB\u6628\u707C\u70B8\u7235\u7DBD\u828D\u914C\u96C0\u9D72\u5B71\u68E7\u6B98\u6F7A\u76DE\u5C91\u66AB\u6F5B\u7BB4\u7C2A\u8836\u96DC\u4E08\u4ED7\u5320\u5834\u58BB\u58EF\u596C\u5C07\u5E33\u5E84\u5F35\u638C\u66B2\u6756\u6A1F\u6AA3\u6B0C\u6F3F\u7246\uF9FA\u7350\u748B\u7AE0\u7CA7\u8178\u81DF\u81E7\u838A\u846C\u8523\u8594\u85CF\u88DD\u8D13\u91AC\u9577"], - ["eea1", "\u969C\u518D\u54C9\u5728\u5BB0\u624D\u6750\u683D\u6893\u6E3D\u6ED3\u707D\u7E21\u88C1\u8CA1\u8F09\u9F4B\u9F4E\u722D\u7B8F\u8ACD\u931A\u4F47\u4F4E\u5132\u5480\u59D0\u5E95\u62B5\u6775\u696E\u6A17\u6CAE\u6E1A\u72D9\u732A\u75BD\u7BB8\u7D35\u82E7\u83F9\u8457\u85F7\u8A5B\u8CAF\u8E87\u9019\u90B8\u96CE\u9F5F\u52E3\u540A\u5AE1\u5BC2\u6458\u6575\u6EF4\u72C4\uF9FB\u7684\u7A4D\u7B1B\u7C4D\u7E3E\u7FDF\u837B\u8B2B\u8CCA\u8D64\u8DE1\u8E5F\u8FEA\u8FF9\u9069\u93D1\u4F43\u4F7A\u50B3\u5168\u5178\u524D\u526A\u5861\u587C\u5960\u5C08\u5C55\u5EDB\u609B\u6230\u6813\u6BBF\u6C08\u6FB1"], - ["efa1", "\u714E\u7420\u7530\u7538\u7551\u7672\u7B4C\u7B8B\u7BAD\u7BC6\u7E8F\u8A6E\u8F3E\u8F49\u923F\u9293\u9322\u942B\u96FB\u985A\u986B\u991E\u5207\u622A\u6298\u6D59\u7664\u7ACA\u7BC0\u7D76\u5360\u5CBE\u5E97\u6F38\u70B9\u7C98\u9711\u9B8E\u9EDE\u63A5\u647A\u8776\u4E01\u4E95\u4EAD\u505C\u5075\u5448\u59C3\u5B9A\u5E40\u5EAD\u5EF7\u5F81\u60C5\u633A\u653F\u6574\u65CC\u6676\u6678\u67FE\u6968\u6A89\u6B63\u6C40\u6DC0\u6DE8\u6E1F\u6E5E\u701E\u70A1\u738E\u73FD\u753A\u775B\u7887\u798E\u7A0B\u7A7D\u7CBE\u7D8E\u8247\u8A02\u8AEA\u8C9E\u912D\u914A\u91D8\u9266\u92CC\u9320\u9706\u9756"], - ["f0a1", "\u975C\u9802\u9F0E\u5236\u5291\u557C\u5824\u5E1D\u5F1F\u608C\u63D0\u68AF\u6FDF\u796D\u7B2C\u81CD\u85BA\u88FD\u8AF8\u8E44\u918D\u9664\u969B\u973D\u984C\u9F4A\u4FCE\u5146\u51CB\u52A9\u5632\u5F14\u5F6B\u63AA\u64CD\u65E9\u6641\u66FA\u66F9\u671D\u689D\u68D7\u69FD\u6F15\u6F6E\u7167\u71E5\u722A\u74AA\u773A\u7956\u795A\u79DF\u7A20\u7A95\u7C97\u7CDF\u7D44\u7E70\u8087\u85FB\u86A4\u8A54\u8ABF\u8D99\u8E81\u9020\u906D\u91E3\u963B\u96D5\u9CE5\u65CF\u7C07\u8DB3\u93C3\u5B58\u5C0A\u5352\u62D9\u731D\u5027\u5B97\u5F9E\u60B0\u616B\u68D5\u6DD9\u742E\u7A2E\u7D42\u7D9C\u7E31\u816B"], - ["f1a1", "\u8E2A\u8E35\u937E\u9418\u4F50\u5750\u5DE6\u5EA7\u632B\u7F6A\u4E3B\u4F4F\u4F8F\u505A\u59DD\u80C4\u546A\u5468\u55FE\u594F\u5B99\u5DDE\u5EDA\u665D\u6731\u67F1\u682A\u6CE8\u6D32\u6E4A\u6F8D\u70B7\u73E0\u7587\u7C4C\u7D02\u7D2C\u7DA2\u821F\u86DB\u8A3B\u8A85\u8D70\u8E8A\u8F33\u9031\u914E\u9152\u9444\u99D0\u7AF9\u7CA5\u4FCA\u5101\u51C6\u57C8\u5BEF\u5CFB\u6659\u6A3D\u6D5A\u6E96\u6FEC\u710C\u756F\u7AE3\u8822\u9021\u9075\u96CB\u99FF\u8301\u4E2D\u4EF2\u8846\u91CD\u537D\u6ADB\u696B\u6C41\u847A\u589E\u618E\u66FE\u62EF\u70DD\u7511\u75C7\u7E52\u84B8\u8B49\u8D08\u4E4B\u53EA"], - ["f2a1", "\u54AB\u5730\u5740\u5FD7\u6301\u6307\u646F\u652F\u65E8\u667A\u679D\u67B3\u6B62\u6C60\u6C9A\u6F2C\u77E5\u7825\u7949\u7957\u7D19\u80A2\u8102\u81F3\u829D\u82B7\u8718\u8A8C\uF9FC\u8D04\u8DBE\u9072\u76F4\u7A19\u7A37\u7E54\u8077\u5507\u55D4\u5875\u632F\u6422\u6649\u664B\u686D\u699B\u6B84\u6D25\u6EB1\u73CD\u7468\u74A1\u755B\u75B9\u76E1\u771E\u778B\u79E6\u7E09\u7E1D\u81FB\u852F\u8897\u8A3A\u8CD1\u8EEB\u8FB0\u9032\u93AD\u9663\u9673\u9707\u4F84\u53F1\u59EA\u5AC9\u5E19\u684E\u74C6\u75BE\u79E9\u7A92\u81A3\u86ED\u8CEA\u8DCC\u8FED\u659F\u6715\uF9FD\u57F7\u6F57\u7DDD\u8F2F"], - ["f3a1", "\u93F6\u96C6\u5FB5\u61F2\u6F84\u4E14\u4F98\u501F\u53C9\u55DF\u5D6F\u5DEE\u6B21\u6B64\u78CB\u7B9A\uF9FE\u8E49\u8ECA\u906E\u6349\u643E\u7740\u7A84\u932F\u947F\u9F6A\u64B0\u6FAF\u71E6\u74A8\u74DA\u7AC4\u7C12\u7E82\u7CB2\u7E98\u8B9A\u8D0A\u947D\u9910\u994C\u5239\u5BDF\u64E6\u672D\u7D2E\u50ED\u53C3\u5879\u6158\u6159\u61FA\u65AC\u7AD9\u8B92\u8B96\u5009\u5021\u5275\u5531\u5A3C\u5EE0\u5F70\u6134\u655E\u660C\u6636\u66A2\u69CD\u6EC4\u6F32\u7316\u7621\u7A93\u8139\u8259\u83D6\u84BC\u50B5\u57F0\u5BC0\u5BE8\u5F69\u63A1\u7826\u7DB5\u83DC\u8521\u91C7\u91F5\u518A\u67F5\u7B56"], - ["f4a1", "\u8CAC\u51C4\u59BB\u60BD\u8655\u501C\uF9FF\u5254\u5C3A\u617D\u621A\u62D3\u64F2\u65A5\u6ECC\u7620\u810A\u8E60\u965F\u96BB\u4EDF\u5343\u5598\u5929\u5DDD\u64C5\u6CC9\u6DFA\u7394\u7A7F\u821B\u85A6\u8CE4\u8E10\u9077\u91E7\u95E1\u9621\u97C6\u51F8\u54F2\u5586\u5FB9\u64A4\u6F88\u7DB4\u8F1F\u8F4D\u9435\u50C9\u5C16\u6CBE\u6DFB\u751B\u77BB\u7C3D\u7C64\u8A79\u8AC2\u581E\u59BE\u5E16\u6377\u7252\u758A\u776B\u8ADC\u8CBC\u8F12\u5EF3\u6674\u6DF8\u807D\u83C1\u8ACB\u9751\u9BD6\uFA00\u5243\u66FF\u6D95\u6EEF\u7DE0\u8AE6\u902E\u905E\u9AD4\u521D\u527F\u54E8\u6194\u6284\u62DB\u68A2"], - ["f5a1", "\u6912\u695A\u6A35\u7092\u7126\u785D\u7901\u790E\u79D2\u7A0D\u8096\u8278\u82D5\u8349\u8549\u8C82\u8D85\u9162\u918B\u91AE\u4FC3\u56D1\u71ED\u77D7\u8700\u89F8\u5BF8\u5FD6\u6751\u90A8\u53E2\u585A\u5BF5\u60A4\u6181\u6460\u7E3D\u8070\u8525\u9283\u64AE\u50AC\u5D14\u6700\u589C\u62BD\u63A8\u690E\u6978\u6A1E\u6E6B\u76BA\u79CB\u82BB\u8429\u8ACF\u8DA8\u8FFD\u9112\u914B\u919C\u9310\u9318\u939A\u96DB\u9A36\u9C0D\u4E11\u755C\u795D\u7AFA\u7B51\u7BC9\u7E2E\u84C4\u8E59\u8E74\u8EF8\u9010\u6625\u693F\u7443\u51FA\u672E\u9EDC\u5145\u5FE0\u6C96\u87F2\u885D\u8877\u60B4\u81B5\u8403"], - ["f6a1", "\u8D05\u53D6\u5439\u5634\u5A36\u5C31\u708A\u7FE0\u805A\u8106\u81ED\u8DA3\u9189\u9A5F\u9DF2\u5074\u4EC4\u53A0\u60FB\u6E2C\u5C64\u4F88\u5024\u55E4\u5CD9\u5E5F\u6065\u6894\u6CBB\u6DC4\u71BE\u75D4\u75F4\u7661\u7A1A\u7A49\u7DC7\u7DFB\u7F6E\u81F4\u86A9\u8F1C\u96C9\u99B3\u9F52\u5247\u52C5\u98ED\u89AA\u4E03\u67D2\u6F06\u4FB5\u5BE2\u6795\u6C88\u6D78\u741B\u7827\u91DD\u937C\u87C4\u79E4\u7A31\u5FEB\u4ED6\u54A4\u553E\u58AE\u59A5\u60F0\u6253\u62D6\u6736\u6955\u8235\u9640\u99B1\u99DD\u502C\u5353\u5544\u577C\uFA01\u6258\uFA02\u64E2\u666B\u67DD\u6FC1\u6FEF\u7422\u7438\u8A17"], - ["f7a1", "\u9438\u5451\u5606\u5766\u5F48\u619A\u6B4E\u7058\u70AD\u7DBB\u8A95\u596A\u812B\u63A2\u7708\u803D\u8CAA\u5854\u642D\u69BB\u5B95\u5E11\u6E6F\uFA03\u8569\u514C\u53F0\u592A\u6020\u614B\u6B86\u6C70\u6CF0\u7B1E\u80CE\u82D4\u8DC6\u90B0\u98B1\uFA04\u64C7\u6FA4\u6491\u6504\u514E\u5410\u571F\u8A0E\u615F\u6876\uFA05\u75DB\u7B52\u7D71\u901A\u5806\u69CC\u817F\u892A\u9000\u9839\u5078\u5957\u59AC\u6295\u900F\u9B2A\u615D\u7279\u95D6\u5761\u5A46\u5DF4\u628A\u64AD\u64FA\u6777\u6CE2\u6D3E\u722C\u7436\u7834\u7F77\u82AD\u8DDB\u9817\u5224\u5742\u677F\u7248\u74E3\u8CA9\u8FA6\u9211"], - ["f8a1", "\u962A\u516B\u53ED\u634C\u4F69\u5504\u6096\u6557\u6C9B\u6D7F\u724C\u72FD\u7A17\u8987\u8C9D\u5F6D\u6F8E\u70F9\u81A8\u610E\u4FBF\u504F\u6241\u7247\u7BC7\u7DE8\u7FE9\u904D\u97AD\u9A19\u8CB6\u576A\u5E73\u67B0\u840D\u8A55\u5420\u5B16\u5E63\u5EE2\u5F0A\u6583\u80BA\u853D\u9589\u965B\u4F48\u5305\u530D\u530F\u5486\u54FA\u5703\u5E03\u6016\u629B\u62B1\u6355\uFA06\u6CE1\u6D66\u75B1\u7832\u80DE\u812F\u82DE\u8461\u84B2\u888D\u8912\u900B\u92EA\u98FD\u9B91\u5E45\u66B4\u66DD\u7011\u7206\uFA07\u4FF5\u527D\u5F6A\u6153\u6753\u6A19\u6F02\u74E2\u7968\u8868\u8C79\u98C7\u98C4\u9A43"], - ["f9a1", "\u54C1\u7A1F\u6953\u8AF7\u8C4A\u98A8\u99AE\u5F7C\u62AB\u75B2\u76AE\u88AB\u907F\u9642\u5339\u5F3C\u5FC5\u6CCC\u73CC\u7562\u758B\u7B46\u82FE\u999D\u4E4F\u903C\u4E0B\u4F55\u53A6\u590F\u5EC8\u6630\u6CB3\u7455\u8377\u8766\u8CC0\u9050\u971E\u9C15\u58D1\u5B78\u8650\u8B14\u9DB4\u5BD2\u6068\u608D\u65F1\u6C57\u6F22\u6FA3\u701A\u7F55\u7FF0\u9591\u9592\u9650\u97D3\u5272\u8F44\u51FD\u542B\u54B8\u5563\u558A\u6ABB\u6DB5\u7DD8\u8266\u929C\u9677\u9E79\u5408\u54C8\u76D2\u86E4\u95A4\u95D4\u965C\u4EA2\u4F09\u59EE\u5AE6\u5DF7\u6052\u6297\u676D\u6841\u6C86\u6E2F\u7F38\u809B\u822A"], - ["faa1", "\uFA08\uFA09\u9805\u4EA5\u5055\u54B3\u5793\u595A\u5B69\u5BB3\u61C8\u6977\u6D77\u7023\u87F9\u89E3\u8A72\u8AE7\u9082\u99ED\u9AB8\u52BE\u6838\u5016\u5E78\u674F\u8347\u884C\u4EAB\u5411\u56AE\u73E6\u9115\u97FF\u9909\u9957\u9999\u5653\u589F\u865B\u8A31\u61B2\u6AF6\u737B\u8ED2\u6B47\u96AA\u9A57\u5955\u7200\u8D6B\u9769\u4FD4\u5CF4\u5F26\u61F8\u665B\u6CEB\u70AB\u7384\u73B9\u73FE\u7729\u774D\u7D43\u7D62\u7E23\u8237\u8852\uFA0A\u8CE2\u9249\u986F\u5B51\u7A74\u8840\u9801\u5ACC\u4FE0\u5354\u593E\u5CFD\u633E\u6D79\u72F9\u8105\u8107\u83A2\u92CF\u9830\u4EA8\u5144\u5211\u578B"], - ["fba1", "\u5F62\u6CC2\u6ECE\u7005\u7050\u70AF\u7192\u73E9\u7469\u834A\u87A2\u8861\u9008\u90A2\u93A3\u99A8\u516E\u5F57\u60E0\u6167\u66B3\u8559\u8E4A\u91AF\u978B\u4E4E\u4E92\u547C\u58D5\u58FA\u597D\u5CB5\u5F27\u6236\u6248\u660A\u6667\u6BEB\u6D69\u6DCF\u6E56\u6EF8\u6F94\u6FE0\u6FE9\u705D\u72D0\u7425\u745A\u74E0\u7693\u795C\u7CCA\u7E1E\u80E1\u82A6\u846B\u84BF\u864E\u865F\u8774\u8B77\u8C6A\u93AC\u9800\u9865\u60D1\u6216\u9177\u5A5A\u660F\u6DF7\u6E3E\u743F\u9B42\u5FFD\u60DA\u7B0F\u54C4\u5F18\u6C5E\u6CD3\u6D2A\u70D8\u7D05\u8679\u8A0C\u9D3B\u5316\u548C\u5B05\u6A3A\u706B\u7575"], - ["fca1", "\u798D\u79BE\u82B1\u83EF\u8A71\u8B41\u8CA8\u9774\uFA0B\u64F4\u652B\u78BA\u78BB\u7A6B\u4E38\u559A\u5950\u5BA6\u5E7B\u60A3\u63DB\u6B61\u6665\u6853\u6E19\u7165\u74B0\u7D08\u9084\u9A69\u9C25\u6D3B\u6ED1\u733E\u8C41\u95CA\u51F0\u5E4C\u5FA8\u604D\u60F6\u6130\u614C\u6643\u6644\u69A5\u6CC1\u6E5F\u6EC9\u6F62\u714C\u749C\u7687\u7BC1\u7C27\u8352\u8757\u9051\u968D\u9EC3\u532F\u56DE\u5EFB\u5F8A\u6062\u6094\u61F7\u6666\u6703\u6A9C\u6DEE\u6FAE\u7070\u736A\u7E6A\u81BE\u8334\u86D4\u8AA8\u8CC4\u5283\u7372\u5B96\u6A6B\u9404\u54EE\u5686\u5B5D\u6548\u6585\u66C9\u689F\u6D8D\u6DC6"], - ["fda1", "\u723B\u80B4\u9175\u9A4D\u4FAF\u5019\u539A\u540E\u543C\u5589\u55C5\u5E3F\u5F8C\u673D\u7166\u73DD\u9005\u52DB\u52F3\u5864\u58CE\u7104\u718F\u71FB\u85B0\u8A13\u6688\u85A8\u55A7\u6684\u714A\u8431\u5349\u5599\u6BC1\u5F59\u5FBD\u63EE\u6689\u7147\u8AF1\u8F1D\u9EBE\u4F11\u643A\u70CB\u7566\u8667\u6064\u8B4E\u9DF8\u5147\u51F6\u5308\u6D36\u80F8\u9ED1\u6615\u6B23\u7098\u75D5\u5403\u5C79\u7D07\u8A16\u6B20\u6B3D\u6B46\u5438\u6070\u6D3D\u7FD5\u8208\u50D6\u51DE\u559C\u566B\u56CD\u59EC\u5B09\u5E0C\u6199\u6198\u6231\u665E\u66E6\u7199\u71B9\u71BA\u72A7\u79A7\u7A00\u7FB2\u8A70"] - ]; - } -}); - -// node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/encodings/tables/cp950.json -var require_cp950 = __commonJS({ - "node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/encodings/tables/cp950.json"(exports, module) { - module.exports = [ - ["0", "\0", 127], - ["a140", "\u3000\uFF0C\u3001\u3002\uFF0E\u2027\uFF1B\uFF1A\uFF1F\uFF01\uFE30\u2026\u2025\uFE50\uFE51\uFE52\xB7\uFE54\uFE55\uFE56\uFE57\uFF5C\u2013\uFE31\u2014\uFE33\u2574\uFE34\uFE4F\uFF08\uFF09\uFE35\uFE36\uFF5B\uFF5D\uFE37\uFE38\u3014\u3015\uFE39\uFE3A\u3010\u3011\uFE3B\uFE3C\u300A\u300B\uFE3D\uFE3E\u3008\u3009\uFE3F\uFE40\u300C\u300D\uFE41\uFE42\u300E\u300F\uFE43\uFE44\uFE59\uFE5A"], - ["a1a1", "\uFE5B\uFE5C\uFE5D\uFE5E\u2018\u2019\u201C\u201D\u301D\u301E\u2035\u2032\uFF03\uFF06\uFF0A\u203B\xA7\u3003\u25CB\u25CF\u25B3\u25B2\u25CE\u2606\u2605\u25C7\u25C6\u25A1\u25A0\u25BD\u25BC\u32A3\u2105\xAF\uFFE3\uFF3F\u02CD\uFE49\uFE4A\uFE4D\uFE4E\uFE4B\uFE4C\uFE5F\uFE60\uFE61\uFF0B\uFF0D\xD7\xF7\xB1\u221A\uFF1C\uFF1E\uFF1D\u2266\u2267\u2260\u221E\u2252\u2261\uFE62", 4, "\uFF5E\u2229\u222A\u22A5\u2220\u221F\u22BF\u33D2\u33D1\u222B\u222E\u2235\u2234\u2640\u2642\u2295\u2299\u2191\u2193\u2190\u2192\u2196\u2197\u2199\u2198\u2225\u2223\uFF0F"], - ["a240", "\uFF3C\u2215\uFE68\uFF04\uFFE5\u3012\uFFE0\uFFE1\uFF05\uFF20\u2103\u2109\uFE69\uFE6A\uFE6B\u33D5\u339C\u339D\u339E\u33CE\u33A1\u338E\u338F\u33C4\xB0\u5159\u515B\u515E\u515D\u5161\u5163\u55E7\u74E9\u7CCE\u2581", 7, "\u258F\u258E\u258D\u258C\u258B\u258A\u2589\u253C\u2534\u252C\u2524\u251C\u2594\u2500\u2502\u2595\u250C\u2510\u2514\u2518\u256D"], - ["a2a1", "\u256E\u2570\u256F\u2550\u255E\u256A\u2561\u25E2\u25E3\u25E5\u25E4\u2571\u2572\u2573\uFF10", 9, "\u2160", 9, "\u3021", 8, "\u5341\u5344\u5345\uFF21", 25, "\uFF41", 21], - ["a340", "\uFF57\uFF58\uFF59\uFF5A\u0391", 16, "\u03A3", 6, "\u03B1", 16, "\u03C3", 6, "\u3105", 10], - ["a3a1", "\u3110", 25, "\u02D9\u02C9\u02CA\u02C7\u02CB"], - ["a3e1", "\u20AC"], - ["a440", "\u4E00\u4E59\u4E01\u4E03\u4E43\u4E5D\u4E86\u4E8C\u4EBA\u513F\u5165\u516B\u51E0\u5200\u5201\u529B\u5315\u5341\u535C\u53C8\u4E09\u4E0B\u4E08\u4E0A\u4E2B\u4E38\u51E1\u4E45\u4E48\u4E5F\u4E5E\u4E8E\u4EA1\u5140\u5203\u52FA\u5343\u53C9\u53E3\u571F\u58EB\u5915\u5927\u5973\u5B50\u5B51\u5B53\u5BF8\u5C0F\u5C22\u5C38\u5C71\u5DDD\u5DE5\u5DF1\u5DF2\u5DF3\u5DFE\u5E72\u5EFE\u5F0B\u5F13\u624D"], - ["a4a1", "\u4E11\u4E10\u4E0D\u4E2D\u4E30\u4E39\u4E4B\u5C39\u4E88\u4E91\u4E95\u4E92\u4E94\u4EA2\u4EC1\u4EC0\u4EC3\u4EC6\u4EC7\u4ECD\u4ECA\u4ECB\u4EC4\u5143\u5141\u5167\u516D\u516E\u516C\u5197\u51F6\u5206\u5207\u5208\u52FB\u52FE\u52FF\u5316\u5339\u5348\u5347\u5345\u535E\u5384\u53CB\u53CA\u53CD\u58EC\u5929\u592B\u592A\u592D\u5B54\u5C11\u5C24\u5C3A\u5C6F\u5DF4\u5E7B\u5EFF\u5F14\u5F15\u5FC3\u6208\u6236\u624B\u624E\u652F\u6587\u6597\u65A4\u65B9\u65E5\u66F0\u6708\u6728\u6B20\u6B62\u6B79\u6BCB\u6BD4\u6BDB\u6C0F\u6C34\u706B\u722A\u7236\u723B\u7247\u7259\u725B\u72AC\u738B\u4E19"], - ["a540", "\u4E16\u4E15\u4E14\u4E18\u4E3B\u4E4D\u4E4F\u4E4E\u4EE5\u4ED8\u4ED4\u4ED5\u4ED6\u4ED7\u4EE3\u4EE4\u4ED9\u4EDE\u5145\u5144\u5189\u518A\u51AC\u51F9\u51FA\u51F8\u520A\u52A0\u529F\u5305\u5306\u5317\u531D\u4EDF\u534A\u5349\u5361\u5360\u536F\u536E\u53BB\u53EF\u53E4\u53F3\u53EC\u53EE\u53E9\u53E8\u53FC\u53F8\u53F5\u53EB\u53E6\u53EA\u53F2\u53F1\u53F0\u53E5\u53ED\u53FB\u56DB\u56DA\u5916"], - ["a5a1", "\u592E\u5931\u5974\u5976\u5B55\u5B83\u5C3C\u5DE8\u5DE7\u5DE6\u5E02\u5E03\u5E73\u5E7C\u5F01\u5F18\u5F17\u5FC5\u620A\u6253\u6254\u6252\u6251\u65A5\u65E6\u672E\u672C\u672A\u672B\u672D\u6B63\u6BCD\u6C11\u6C10\u6C38\u6C41\u6C40\u6C3E\u72AF\u7384\u7389\u74DC\u74E6\u7518\u751F\u7528\u7529\u7530\u7531\u7532\u7533\u758B\u767D\u76AE\u76BF\u76EE\u77DB\u77E2\u77F3\u793A\u79BE\u7A74\u7ACB\u4E1E\u4E1F\u4E52\u4E53\u4E69\u4E99\u4EA4\u4EA6\u4EA5\u4EFF\u4F09\u4F19\u4F0A\u4F15\u4F0D\u4F10\u4F11\u4F0F\u4EF2\u4EF6\u4EFB\u4EF0\u4EF3\u4EFD\u4F01\u4F0B\u5149\u5147\u5146\u5148\u5168"], - ["a640", "\u5171\u518D\u51B0\u5217\u5211\u5212\u520E\u5216\u52A3\u5308\u5321\u5320\u5370\u5371\u5409\u540F\u540C\u540A\u5410\u5401\u540B\u5404\u5411\u540D\u5408\u5403\u540E\u5406\u5412\u56E0\u56DE\u56DD\u5733\u5730\u5728\u572D\u572C\u572F\u5729\u5919\u591A\u5937\u5938\u5984\u5978\u5983\u597D\u5979\u5982\u5981\u5B57\u5B58\u5B87\u5B88\u5B85\u5B89\u5BFA\u5C16\u5C79\u5DDE\u5E06\u5E76\u5E74"], - ["a6a1", "\u5F0F\u5F1B\u5FD9\u5FD6\u620E\u620C\u620D\u6210\u6263\u625B\u6258\u6536\u65E9\u65E8\u65EC\u65ED\u66F2\u66F3\u6709\u673D\u6734\u6731\u6735\u6B21\u6B64\u6B7B\u6C16\u6C5D\u6C57\u6C59\u6C5F\u6C60\u6C50\u6C55\u6C61\u6C5B\u6C4D\u6C4E\u7070\u725F\u725D\u767E\u7AF9\u7C73\u7CF8\u7F36\u7F8A\u7FBD\u8001\u8003\u800C\u8012\u8033\u807F\u8089\u808B\u808C\u81E3\u81EA\u81F3\u81FC\u820C\u821B\u821F\u826E\u8272\u827E\u866B\u8840\u884C\u8863\u897F\u9621\u4E32\u4EA8\u4F4D\u4F4F\u4F47\u4F57\u4F5E\u4F34\u4F5B\u4F55\u4F30\u4F50\u4F51\u4F3D\u4F3A\u4F38\u4F43\u4F54\u4F3C\u4F46\u4F63"], - ["a740", "\u4F5C\u4F60\u4F2F\u4F4E\u4F36\u4F59\u4F5D\u4F48\u4F5A\u514C\u514B\u514D\u5175\u51B6\u51B7\u5225\u5224\u5229\u522A\u5228\u52AB\u52A9\u52AA\u52AC\u5323\u5373\u5375\u541D\u542D\u541E\u543E\u5426\u544E\u5427\u5446\u5443\u5433\u5448\u5442\u541B\u5429\u544A\u5439\u543B\u5438\u542E\u5435\u5436\u5420\u543C\u5440\u5431\u542B\u541F\u542C\u56EA\u56F0\u56E4\u56EB\u574A\u5751\u5740\u574D"], - ["a7a1", "\u5747\u574E\u573E\u5750\u574F\u573B\u58EF\u593E\u599D\u5992\u59A8\u599E\u59A3\u5999\u5996\u598D\u59A4\u5993\u598A\u59A5\u5B5D\u5B5C\u5B5A\u5B5B\u5B8C\u5B8B\u5B8F\u5C2C\u5C40\u5C41\u5C3F\u5C3E\u5C90\u5C91\u5C94\u5C8C\u5DEB\u5E0C\u5E8F\u5E87\u5E8A\u5EF7\u5F04\u5F1F\u5F64\u5F62\u5F77\u5F79\u5FD8\u5FCC\u5FD7\u5FCD\u5FF1\u5FEB\u5FF8\u5FEA\u6212\u6211\u6284\u6297\u6296\u6280\u6276\u6289\u626D\u628A\u627C\u627E\u6279\u6273\u6292\u626F\u6298\u626E\u6295\u6293\u6291\u6286\u6539\u653B\u6538\u65F1\u66F4\u675F\u674E\u674F\u6750\u6751\u675C\u6756\u675E\u6749\u6746\u6760"], - ["a840", "\u6753\u6757\u6B65\u6BCF\u6C42\u6C5E\u6C99\u6C81\u6C88\u6C89\u6C85\u6C9B\u6C6A\u6C7A\u6C90\u6C70\u6C8C\u6C68\u6C96\u6C92\u6C7D\u6C83\u6C72\u6C7E\u6C74\u6C86\u6C76\u6C8D\u6C94\u6C98\u6C82\u7076\u707C\u707D\u7078\u7262\u7261\u7260\u72C4\u72C2\u7396\u752C\u752B\u7537\u7538\u7682\u76EF\u77E3\u79C1\u79C0\u79BF\u7A76\u7CFB\u7F55\u8096\u8093\u809D\u8098\u809B\u809A\u80B2\u826F\u8292"], - ["a8a1", "\u828B\u828D\u898B\u89D2\u8A00\u8C37\u8C46\u8C55\u8C9D\u8D64\u8D70\u8DB3\u8EAB\u8ECA\u8F9B\u8FB0\u8FC2\u8FC6\u8FC5\u8FC4\u5DE1\u9091\u90A2\u90AA\u90A6\u90A3\u9149\u91C6\u91CC\u9632\u962E\u9631\u962A\u962C\u4E26\u4E56\u4E73\u4E8B\u4E9B\u4E9E\u4EAB\u4EAC\u4F6F\u4F9D\u4F8D\u4F73\u4F7F\u4F6C\u4F9B\u4F8B\u4F86\u4F83\u4F70\u4F75\u4F88\u4F69\u4F7B\u4F96\u4F7E\u4F8F\u4F91\u4F7A\u5154\u5152\u5155\u5169\u5177\u5176\u5178\u51BD\u51FD\u523B\u5238\u5237\u523A\u5230\u522E\u5236\u5241\u52BE\u52BB\u5352\u5354\u5353\u5351\u5366\u5377\u5378\u5379\u53D6\u53D4\u53D7\u5473\u5475"], - ["a940", "\u5496\u5478\u5495\u5480\u547B\u5477\u5484\u5492\u5486\u547C\u5490\u5471\u5476\u548C\u549A\u5462\u5468\u548B\u547D\u548E\u56FA\u5783\u5777\u576A\u5769\u5761\u5766\u5764\u577C\u591C\u5949\u5947\u5948\u5944\u5954\u59BE\u59BB\u59D4\u59B9\u59AE\u59D1\u59C6\u59D0\u59CD\u59CB\u59D3\u59CA\u59AF\u59B3\u59D2\u59C5\u5B5F\u5B64\u5B63\u5B97\u5B9A\u5B98\u5B9C\u5B99\u5B9B\u5C1A\u5C48\u5C45"], - ["a9a1", "\u5C46\u5CB7\u5CA1\u5CB8\u5CA9\u5CAB\u5CB1\u5CB3\u5E18\u5E1A\u5E16\u5E15\u5E1B\u5E11\u5E78\u5E9A\u5E97\u5E9C\u5E95\u5E96\u5EF6\u5F26\u5F27\u5F29\u5F80\u5F81\u5F7F\u5F7C\u5FDD\u5FE0\u5FFD\u5FF5\u5FFF\u600F\u6014\u602F\u6035\u6016\u602A\u6015\u6021\u6027\u6029\u602B\u601B\u6216\u6215\u623F\u623E\u6240\u627F\u62C9\u62CC\u62C4\u62BF\u62C2\u62B9\u62D2\u62DB\u62AB\u62D3\u62D4\u62CB\u62C8\u62A8\u62BD\u62BC\u62D0\u62D9\u62C7\u62CD\u62B5\u62DA\u62B1\u62D8\u62D6\u62D7\u62C6\u62AC\u62CE\u653E\u65A7\u65BC\u65FA\u6614\u6613\u660C\u6606\u6602\u660E\u6600\u660F\u6615\u660A"], - ["aa40", "\u6607\u670D\u670B\u676D\u678B\u6795\u6771\u679C\u6773\u6777\u6787\u679D\u6797\u676F\u6770\u677F\u6789\u677E\u6790\u6775\u679A\u6793\u677C\u676A\u6772\u6B23\u6B66\u6B67\u6B7F\u6C13\u6C1B\u6CE3\u6CE8\u6CF3\u6CB1\u6CCC\u6CE5\u6CB3\u6CBD\u6CBE\u6CBC\u6CE2\u6CAB\u6CD5\u6CD3\u6CB8\u6CC4\u6CB9\u6CC1\u6CAE\u6CD7\u6CC5\u6CF1\u6CBF\u6CBB\u6CE1\u6CDB\u6CCA\u6CAC\u6CEF\u6CDC\u6CD6\u6CE0"], - ["aaa1", "\u7095\u708E\u7092\u708A\u7099\u722C\u722D\u7238\u7248\u7267\u7269\u72C0\u72CE\u72D9\u72D7\u72D0\u73A9\u73A8\u739F\u73AB\u73A5\u753D\u759D\u7599\u759A\u7684\u76C2\u76F2\u76F4\u77E5\u77FD\u793E\u7940\u7941\u79C9\u79C8\u7A7A\u7A79\u7AFA\u7CFE\u7F54\u7F8C\u7F8B\u8005\u80BA\u80A5\u80A2\u80B1\u80A1\u80AB\u80A9\u80B4\u80AA\u80AF\u81E5\u81FE\u820D\u82B3\u829D\u8299\u82AD\u82BD\u829F\u82B9\u82B1\u82AC\u82A5\u82AF\u82B8\u82A3\u82B0\u82BE\u82B7\u864E\u8671\u521D\u8868\u8ECB\u8FCE\u8FD4\u8FD1\u90B5\u90B8\u90B1\u90B6\u91C7\u91D1\u9577\u9580\u961C\u9640\u963F\u963B\u9644"], - ["ab40", "\u9642\u96B9\u96E8\u9752\u975E\u4E9F\u4EAD\u4EAE\u4FE1\u4FB5\u4FAF\u4FBF\u4FE0\u4FD1\u4FCF\u4FDD\u4FC3\u4FB6\u4FD8\u4FDF\u4FCA\u4FD7\u4FAE\u4FD0\u4FC4\u4FC2\u4FDA\u4FCE\u4FDE\u4FB7\u5157\u5192\u5191\u51A0\u524E\u5243\u524A\u524D\u524C\u524B\u5247\u52C7\u52C9\u52C3\u52C1\u530D\u5357\u537B\u539A\u53DB\u54AC\u54C0\u54A8\u54CE\u54C9\u54B8\u54A6\u54B3\u54C7\u54C2\u54BD\u54AA\u54C1"], - ["aba1", "\u54C4\u54C8\u54AF\u54AB\u54B1\u54BB\u54A9\u54A7\u54BF\u56FF\u5782\u578B\u57A0\u57A3\u57A2\u57CE\u57AE\u5793\u5955\u5951\u594F\u594E\u5950\u59DC\u59D8\u59FF\u59E3\u59E8\u5A03\u59E5\u59EA\u59DA\u59E6\u5A01\u59FB\u5B69\u5BA3\u5BA6\u5BA4\u5BA2\u5BA5\u5C01\u5C4E\u5C4F\u5C4D\u5C4B\u5CD9\u5CD2\u5DF7\u5E1D\u5E25\u5E1F\u5E7D\u5EA0\u5EA6\u5EFA\u5F08\u5F2D\u5F65\u5F88\u5F85\u5F8A\u5F8B\u5F87\u5F8C\u5F89\u6012\u601D\u6020\u6025\u600E\u6028\u604D\u6070\u6068\u6062\u6046\u6043\u606C\u606B\u606A\u6064\u6241\u62DC\u6316\u6309\u62FC\u62ED\u6301\u62EE\u62FD\u6307\u62F1\u62F7"], - ["ac40", "\u62EF\u62EC\u62FE\u62F4\u6311\u6302\u653F\u6545\u65AB\u65BD\u65E2\u6625\u662D\u6620\u6627\u662F\u661F\u6628\u6631\u6624\u66F7\u67FF\u67D3\u67F1\u67D4\u67D0\u67EC\u67B6\u67AF\u67F5\u67E9\u67EF\u67C4\u67D1\u67B4\u67DA\u67E5\u67B8\u67CF\u67DE\u67F3\u67B0\u67D9\u67E2\u67DD\u67D2\u6B6A\u6B83\u6B86\u6BB5\u6BD2\u6BD7\u6C1F\u6CC9\u6D0B\u6D32\u6D2A\u6D41\u6D25\u6D0C\u6D31\u6D1E\u6D17"], - ["aca1", "\u6D3B\u6D3D\u6D3E\u6D36\u6D1B\u6CF5\u6D39\u6D27\u6D38\u6D29\u6D2E\u6D35\u6D0E\u6D2B\u70AB\u70BA\u70B3\u70AC\u70AF\u70AD\u70B8\u70AE\u70A4\u7230\u7272\u726F\u7274\u72E9\u72E0\u72E1\u73B7\u73CA\u73BB\u73B2\u73CD\u73C0\u73B3\u751A\u752D\u754F\u754C\u754E\u754B\u75AB\u75A4\u75A5\u75A2\u75A3\u7678\u7686\u7687\u7688\u76C8\u76C6\u76C3\u76C5\u7701\u76F9\u76F8\u7709\u770B\u76FE\u76FC\u7707\u77DC\u7802\u7814\u780C\u780D\u7946\u7949\u7948\u7947\u79B9\u79BA\u79D1\u79D2\u79CB\u7A7F\u7A81\u7AFF\u7AFD\u7C7D\u7D02\u7D05\u7D00\u7D09\u7D07\u7D04\u7D06\u7F38\u7F8E\u7FBF\u8004"], - ["ad40", "\u8010\u800D\u8011\u8036\u80D6\u80E5\u80DA\u80C3\u80C4\u80CC\u80E1\u80DB\u80CE\u80DE\u80E4\u80DD\u81F4\u8222\u82E7\u8303\u8305\u82E3\u82DB\u82E6\u8304\u82E5\u8302\u8309\u82D2\u82D7\u82F1\u8301\u82DC\u82D4\u82D1\u82DE\u82D3\u82DF\u82EF\u8306\u8650\u8679\u867B\u867A\u884D\u886B\u8981\u89D4\u8A08\u8A02\u8A03\u8C9E\u8CA0\u8D74\u8D73\u8DB4\u8ECD\u8ECC\u8FF0\u8FE6\u8FE2\u8FEA\u8FE5"], - ["ada1", "\u8FED\u8FEB\u8FE4\u8FE8\u90CA\u90CE\u90C1\u90C3\u914B\u914A\u91CD\u9582\u9650\u964B\u964C\u964D\u9762\u9769\u97CB\u97ED\u97F3\u9801\u98A8\u98DB\u98DF\u9996\u9999\u4E58\u4EB3\u500C\u500D\u5023\u4FEF\u5026\u5025\u4FF8\u5029\u5016\u5006\u503C\u501F\u501A\u5012\u5011\u4FFA\u5000\u5014\u5028\u4FF1\u5021\u500B\u5019\u5018\u4FF3\u4FEE\u502D\u502A\u4FFE\u502B\u5009\u517C\u51A4\u51A5\u51A2\u51CD\u51CC\u51C6\u51CB\u5256\u525C\u5254\u525B\u525D\u532A\u537F\u539F\u539D\u53DF\u54E8\u5510\u5501\u5537\u54FC\u54E5\u54F2\u5506\u54FA\u5514\u54E9\u54ED\u54E1\u5509\u54EE\u54EA"], - ["ae40", "\u54E6\u5527\u5507\u54FD\u550F\u5703\u5704\u57C2\u57D4\u57CB\u57C3\u5809\u590F\u5957\u5958\u595A\u5A11\u5A18\u5A1C\u5A1F\u5A1B\u5A13\u59EC\u5A20\u5A23\u5A29\u5A25\u5A0C\u5A09\u5B6B\u5C58\u5BB0\u5BB3\u5BB6\u5BB4\u5BAE\u5BB5\u5BB9\u5BB8\u5C04\u5C51\u5C55\u5C50\u5CED\u5CFD\u5CFB\u5CEA\u5CE8\u5CF0\u5CF6\u5D01\u5CF4\u5DEE\u5E2D\u5E2B\u5EAB\u5EAD\u5EA7\u5F31\u5F92\u5F91\u5F90\u6059"], - ["aea1", "\u6063\u6065\u6050\u6055\u606D\u6069\u606F\u6084\u609F\u609A\u608D\u6094\u608C\u6085\u6096\u6247\u62F3\u6308\u62FF\u634E\u633E\u632F\u6355\u6342\u6346\u634F\u6349\u633A\u6350\u633D\u632A\u632B\u6328\u634D\u634C\u6548\u6549\u6599\u65C1\u65C5\u6642\u6649\u664F\u6643\u6652\u664C\u6645\u6641\u66F8\u6714\u6715\u6717\u6821\u6838\u6848\u6846\u6853\u6839\u6842\u6854\u6829\u68B3\u6817\u684C\u6851\u683D\u67F4\u6850\u6840\u683C\u6843\u682A\u6845\u6813\u6818\u6841\u6B8A\u6B89\u6BB7\u6C23\u6C27\u6C28\u6C26\u6C24\u6CF0\u6D6A\u6D95\u6D88\u6D87\u6D66\u6D78\u6D77\u6D59\u6D93"], - ["af40", "\u6D6C\u6D89\u6D6E\u6D5A\u6D74\u6D69\u6D8C\u6D8A\u6D79\u6D85\u6D65\u6D94\u70CA\u70D8\u70E4\u70D9\u70C8\u70CF\u7239\u7279\u72FC\u72F9\u72FD\u72F8\u72F7\u7386\u73ED\u7409\u73EE\u73E0\u73EA\u73DE\u7554\u755D\u755C\u755A\u7559\u75BE\u75C5\u75C7\u75B2\u75B3\u75BD\u75BC\u75B9\u75C2\u75B8\u768B\u76B0\u76CA\u76CD\u76CE\u7729\u771F\u7720\u7728\u77E9\u7830\u7827\u7838\u781D\u7834\u7837"], - ["afa1", "\u7825\u782D\u7820\u781F\u7832\u7955\u7950\u7960\u795F\u7956\u795E\u795D\u7957\u795A\u79E4\u79E3\u79E7\u79DF\u79E6\u79E9\u79D8\u7A84\u7A88\u7AD9\u7B06\u7B11\u7C89\u7D21\u7D17\u7D0B\u7D0A\u7D20\u7D22\u7D14\u7D10\u7D15\u7D1A\u7D1C\u7D0D\u7D19\u7D1B\u7F3A\u7F5F\u7F94\u7FC5\u7FC1\u8006\u8018\u8015\u8019\u8017\u803D\u803F\u80F1\u8102\u80F0\u8105\u80ED\u80F4\u8106\u80F8\u80F3\u8108\u80FD\u810A\u80FC\u80EF\u81ED\u81EC\u8200\u8210\u822A\u822B\u8228\u822C\u82BB\u832B\u8352\u8354\u834A\u8338\u8350\u8349\u8335\u8334\u834F\u8332\u8339\u8336\u8317\u8340\u8331\u8328\u8343"], - ["b040", "\u8654\u868A\u86AA\u8693\u86A4\u86A9\u868C\u86A3\u869C\u8870\u8877\u8881\u8882\u887D\u8879\u8A18\u8A10\u8A0E\u8A0C\u8A15\u8A0A\u8A17\u8A13\u8A16\u8A0F\u8A11\u8C48\u8C7A\u8C79\u8CA1\u8CA2\u8D77\u8EAC\u8ED2\u8ED4\u8ECF\u8FB1\u9001\u9006\u8FF7\u9000\u8FFA\u8FF4\u9003\u8FFD\u9005\u8FF8\u9095\u90E1\u90DD\u90E2\u9152\u914D\u914C\u91D8\u91DD\u91D7\u91DC\u91D9\u9583\u9662\u9663\u9661"], - ["b0a1", "\u965B\u965D\u9664\u9658\u965E\u96BB\u98E2\u99AC\u9AA8\u9AD8\u9B25\u9B32\u9B3C\u4E7E\u507A\u507D\u505C\u5047\u5043\u504C\u505A\u5049\u5065\u5076\u504E\u5055\u5075\u5074\u5077\u504F\u500F\u506F\u506D\u515C\u5195\u51F0\u526A\u526F\u52D2\u52D9\u52D8\u52D5\u5310\u530F\u5319\u533F\u5340\u533E\u53C3\u66FC\u5546\u556A\u5566\u5544\u555E\u5561\u5543\u554A\u5531\u5556\u554F\u5555\u552F\u5564\u5538\u552E\u555C\u552C\u5563\u5533\u5541\u5557\u5708\u570B\u5709\u57DF\u5805\u580A\u5806\u57E0\u57E4\u57FA\u5802\u5835\u57F7\u57F9\u5920\u5962\u5A36\u5A41\u5A49\u5A66\u5A6A\u5A40"], - ["b140", "\u5A3C\u5A62\u5A5A\u5A46\u5A4A\u5B70\u5BC7\u5BC5\u5BC4\u5BC2\u5BBF\u5BC6\u5C09\u5C08\u5C07\u5C60\u5C5C\u5C5D\u5D07\u5D06\u5D0E\u5D1B\u5D16\u5D22\u5D11\u5D29\u5D14\u5D19\u5D24\u5D27\u5D17\u5DE2\u5E38\u5E36\u5E33\u5E37\u5EB7\u5EB8\u5EB6\u5EB5\u5EBE\u5F35\u5F37\u5F57\u5F6C\u5F69\u5F6B\u5F97\u5F99\u5F9E\u5F98\u5FA1\u5FA0\u5F9C\u607F\u60A3\u6089\u60A0\u60A8\u60CB\u60B4\u60E6\u60BD"], - ["b1a1", "\u60C5\u60BB\u60B5\u60DC\u60BC\u60D8\u60D5\u60C6\u60DF\u60B8\u60DA\u60C7\u621A\u621B\u6248\u63A0\u63A7\u6372\u6396\u63A2\u63A5\u6377\u6367\u6398\u63AA\u6371\u63A9\u6389\u6383\u639B\u636B\u63A8\u6384\u6388\u6399\u63A1\u63AC\u6392\u638F\u6380\u637B\u6369\u6368\u637A\u655D\u6556\u6551\u6559\u6557\u555F\u654F\u6558\u6555\u6554\u659C\u659B\u65AC\u65CF\u65CB\u65CC\u65CE\u665D\u665A\u6664\u6668\u6666\u665E\u66F9\u52D7\u671B\u6881\u68AF\u68A2\u6893\u68B5\u687F\u6876\u68B1\u68A7\u6897\u68B0\u6883\u68C4\u68AD\u6886\u6885\u6894\u689D\u68A8\u689F\u68A1\u6882\u6B32\u6BBA"], - ["b240", "\u6BEB\u6BEC\u6C2B\u6D8E\u6DBC\u6DF3\u6DD9\u6DB2\u6DE1\u6DCC\u6DE4\u6DFB\u6DFA\u6E05\u6DC7\u6DCB\u6DAF\u6DD1\u6DAE\u6DDE\u6DF9\u6DB8\u6DF7\u6DF5\u6DC5\u6DD2\u6E1A\u6DB5\u6DDA\u6DEB\u6DD8\u6DEA\u6DF1\u6DEE\u6DE8\u6DC6\u6DC4\u6DAA\u6DEC\u6DBF\u6DE6\u70F9\u7109\u710A\u70FD\u70EF\u723D\u727D\u7281\u731C\u731B\u7316\u7313\u7319\u7387\u7405\u740A\u7403\u7406\u73FE\u740D\u74E0\u74F6"], - ["b2a1", "\u74F7\u751C\u7522\u7565\u7566\u7562\u7570\u758F\u75D4\u75D5\u75B5\u75CA\u75CD\u768E\u76D4\u76D2\u76DB\u7737\u773E\u773C\u7736\u7738\u773A\u786B\u7843\u784E\u7965\u7968\u796D\u79FB\u7A92\u7A95\u7B20\u7B28\u7B1B\u7B2C\u7B26\u7B19\u7B1E\u7B2E\u7C92\u7C97\u7C95\u7D46\u7D43\u7D71\u7D2E\u7D39\u7D3C\u7D40\u7D30\u7D33\u7D44\u7D2F\u7D42\u7D32\u7D31\u7F3D\u7F9E\u7F9A\u7FCC\u7FCE\u7FD2\u801C\u804A\u8046\u812F\u8116\u8123\u812B\u8129\u8130\u8124\u8202\u8235\u8237\u8236\u8239\u838E\u839E\u8398\u8378\u83A2\u8396\u83BD\u83AB\u8392\u838A\u8393\u8389\u83A0\u8377\u837B\u837C"], - ["b340", "\u8386\u83A7\u8655\u5F6A\u86C7\u86C0\u86B6\u86C4\u86B5\u86C6\u86CB\u86B1\u86AF\u86C9\u8853\u889E\u8888\u88AB\u8892\u8896\u888D\u888B\u8993\u898F\u8A2A\u8A1D\u8A23\u8A25\u8A31\u8A2D\u8A1F\u8A1B\u8A22\u8C49\u8C5A\u8CA9\u8CAC\u8CAB\u8CA8\u8CAA\u8CA7\u8D67\u8D66\u8DBE\u8DBA\u8EDB\u8EDF\u9019\u900D\u901A\u9017\u9023\u901F\u901D\u9010\u9015\u901E\u9020\u900F\u9022\u9016\u901B\u9014"], - ["b3a1", "\u90E8\u90ED\u90FD\u9157\u91CE\u91F5\u91E6\u91E3\u91E7\u91ED\u91E9\u9589\u966A\u9675\u9673\u9678\u9670\u9674\u9676\u9677\u966C\u96C0\u96EA\u96E9\u7AE0\u7ADF\u9802\u9803\u9B5A\u9CE5\u9E75\u9E7F\u9EA5\u9EBB\u50A2\u508D\u5085\u5099\u5091\u5080\u5096\u5098\u509A\u6700\u51F1\u5272\u5274\u5275\u5269\u52DE\u52DD\u52DB\u535A\u53A5\u557B\u5580\u55A7\u557C\u558A\u559D\u5598\u5582\u559C\u55AA\u5594\u5587\u558B\u5583\u55B3\u55AE\u559F\u553E\u55B2\u559A\u55BB\u55AC\u55B1\u557E\u5589\u55AB\u5599\u570D\u582F\u582A\u5834\u5824\u5830\u5831\u5821\u581D\u5820\u58F9\u58FA\u5960"], - ["b440", "\u5A77\u5A9A\u5A7F\u5A92\u5A9B\u5AA7\u5B73\u5B71\u5BD2\u5BCC\u5BD3\u5BD0\u5C0A\u5C0B\u5C31\u5D4C\u5D50\u5D34\u5D47\u5DFD\u5E45\u5E3D\u5E40\u5E43\u5E7E\u5ECA\u5EC1\u5EC2\u5EC4\u5F3C\u5F6D\u5FA9\u5FAA\u5FA8\u60D1\u60E1\u60B2\u60B6\u60E0\u611C\u6123\u60FA\u6115\u60F0\u60FB\u60F4\u6168\u60F1\u610E\u60F6\u6109\u6100\u6112\u621F\u6249\u63A3\u638C\u63CF\u63C0\u63E9\u63C9\u63C6\u63CD"], - ["b4a1", "\u63D2\u63E3\u63D0\u63E1\u63D6\u63ED\u63EE\u6376\u63F4\u63EA\u63DB\u6452\u63DA\u63F9\u655E\u6566\u6562\u6563\u6591\u6590\u65AF\u666E\u6670\u6674\u6676\u666F\u6691\u667A\u667E\u6677\u66FE\u66FF\u671F\u671D\u68FA\u68D5\u68E0\u68D8\u68D7\u6905\u68DF\u68F5\u68EE\u68E7\u68F9\u68D2\u68F2\u68E3\u68CB\u68CD\u690D\u6912\u690E\u68C9\u68DA\u696E\u68FB\u6B3E\u6B3A\u6B3D\u6B98\u6B96\u6BBC\u6BEF\u6C2E\u6C2F\u6C2C\u6E2F\u6E38\u6E54\u6E21\u6E32\u6E67\u6E4A\u6E20\u6E25\u6E23\u6E1B\u6E5B\u6E58\u6E24\u6E56\u6E6E\u6E2D\u6E26\u6E6F\u6E34\u6E4D\u6E3A\u6E2C\u6E43\u6E1D\u6E3E\u6ECB"], - ["b540", "\u6E89\u6E19\u6E4E\u6E63\u6E44\u6E72\u6E69\u6E5F\u7119\u711A\u7126\u7130\u7121\u7136\u716E\u711C\u724C\u7284\u7280\u7336\u7325\u7334\u7329\u743A\u742A\u7433\u7422\u7425\u7435\u7436\u7434\u742F\u741B\u7426\u7428\u7525\u7526\u756B\u756A\u75E2\u75DB\u75E3\u75D9\u75D8\u75DE\u75E0\u767B\u767C\u7696\u7693\u76B4\u76DC\u774F\u77ED\u785D\u786C\u786F\u7A0D\u7A08\u7A0B\u7A05\u7A00\u7A98"], - ["b5a1", "\u7A97\u7A96\u7AE5\u7AE3\u7B49\u7B56\u7B46\u7B50\u7B52\u7B54\u7B4D\u7B4B\u7B4F\u7B51\u7C9F\u7CA5\u7D5E\u7D50\u7D68\u7D55\u7D2B\u7D6E\u7D72\u7D61\u7D66\u7D62\u7D70\u7D73\u5584\u7FD4\u7FD5\u800B\u8052\u8085\u8155\u8154\u814B\u8151\u814E\u8139\u8146\u813E\u814C\u8153\u8174\u8212\u821C\u83E9\u8403\u83F8\u840D\u83E0\u83C5\u840B\u83C1\u83EF\u83F1\u83F4\u8457\u840A\u83F0\u840C\u83CC\u83FD\u83F2\u83CA\u8438\u840E\u8404\u83DC\u8407\u83D4\u83DF\u865B\u86DF\u86D9\u86ED\u86D4\u86DB\u86E4\u86D0\u86DE\u8857\u88C1\u88C2\u88B1\u8983\u8996\u8A3B\u8A60\u8A55\u8A5E\u8A3C\u8A41"], - ["b640", "\u8A54\u8A5B\u8A50\u8A46\u8A34\u8A3A\u8A36\u8A56\u8C61\u8C82\u8CAF\u8CBC\u8CB3\u8CBD\u8CC1\u8CBB\u8CC0\u8CB4\u8CB7\u8CB6\u8CBF\u8CB8\u8D8A\u8D85\u8D81\u8DCE\u8DDD\u8DCB\u8DDA\u8DD1\u8DCC\u8DDB\u8DC6\u8EFB\u8EF8\u8EFC\u8F9C\u902E\u9035\u9031\u9038\u9032\u9036\u9102\u90F5\u9109\u90FE\u9163\u9165\u91CF\u9214\u9215\u9223\u9209\u921E\u920D\u9210\u9207\u9211\u9594\u958F\u958B\u9591"], - ["b6a1", "\u9593\u9592\u958E\u968A\u968E\u968B\u967D\u9685\u9686\u968D\u9672\u9684\u96C1\u96C5\u96C4\u96C6\u96C7\u96EF\u96F2\u97CC\u9805\u9806\u9808\u98E7\u98EA\u98EF\u98E9\u98F2\u98ED\u99AE\u99AD\u9EC3\u9ECD\u9ED1\u4E82\u50AD\u50B5\u50B2\u50B3\u50C5\u50BE\u50AC\u50B7\u50BB\u50AF\u50C7\u527F\u5277\u527D\u52DF\u52E6\u52E4\u52E2\u52E3\u532F\u55DF\u55E8\u55D3\u55E6\u55CE\u55DC\u55C7\u55D1\u55E3\u55E4\u55EF\u55DA\u55E1\u55C5\u55C6\u55E5\u55C9\u5712\u5713\u585E\u5851\u5858\u5857\u585A\u5854\u586B\u584C\u586D\u584A\u5862\u5852\u584B\u5967\u5AC1\u5AC9\u5ACC\u5ABE\u5ABD\u5ABC"], - ["b740", "\u5AB3\u5AC2\u5AB2\u5D69\u5D6F\u5E4C\u5E79\u5EC9\u5EC8\u5F12\u5F59\u5FAC\u5FAE\u611A\u610F\u6148\u611F\u60F3\u611B\u60F9\u6101\u6108\u614E\u614C\u6144\u614D\u613E\u6134\u6127\u610D\u6106\u6137\u6221\u6222\u6413\u643E\u641E\u642A\u642D\u643D\u642C\u640F\u641C\u6414\u640D\u6436\u6416\u6417\u6406\u656C\u659F\u65B0\u6697\u6689\u6687\u6688\u6696\u6684\u6698\u668D\u6703\u6994\u696D"], - ["b7a1", "\u695A\u6977\u6960\u6954\u6975\u6930\u6982\u694A\u6968\u696B\u695E\u6953\u6979\u6986\u695D\u6963\u695B\u6B47\u6B72\u6BC0\u6BBF\u6BD3\u6BFD\u6EA2\u6EAF\u6ED3\u6EB6\u6EC2\u6E90\u6E9D\u6EC7\u6EC5\u6EA5\u6E98\u6EBC\u6EBA\u6EAB\u6ED1\u6E96\u6E9C\u6EC4\u6ED4\u6EAA\u6EA7\u6EB4\u714E\u7159\u7169\u7164\u7149\u7167\u715C\u716C\u7166\u714C\u7165\u715E\u7146\u7168\u7156\u723A\u7252\u7337\u7345\u733F\u733E\u746F\u745A\u7455\u745F\u745E\u7441\u743F\u7459\u745B\u745C\u7576\u7578\u7600\u75F0\u7601\u75F2\u75F1\u75FA\u75FF\u75F4\u75F3\u76DE\u76DF\u775B\u776B\u7766\u775E\u7763"], - ["b840", "\u7779\u776A\u776C\u775C\u7765\u7768\u7762\u77EE\u788E\u78B0\u7897\u7898\u788C\u7889\u787C\u7891\u7893\u787F\u797A\u797F\u7981\u842C\u79BD\u7A1C\u7A1A\u7A20\u7A14\u7A1F\u7A1E\u7A9F\u7AA0\u7B77\u7BC0\u7B60\u7B6E\u7B67\u7CB1\u7CB3\u7CB5\u7D93\u7D79\u7D91\u7D81\u7D8F\u7D5B\u7F6E\u7F69\u7F6A\u7F72\u7FA9\u7FA8\u7FA4\u8056\u8058\u8086\u8084\u8171\u8170\u8178\u8165\u816E\u8173\u816B"], - ["b8a1", "\u8179\u817A\u8166\u8205\u8247\u8482\u8477\u843D\u8431\u8475\u8466\u846B\u8449\u846C\u845B\u843C\u8435\u8461\u8463\u8469\u846D\u8446\u865E\u865C\u865F\u86F9\u8713\u8708\u8707\u8700\u86FE\u86FB\u8702\u8703\u8706\u870A\u8859\u88DF\u88D4\u88D9\u88DC\u88D8\u88DD\u88E1\u88CA\u88D5\u88D2\u899C\u89E3\u8A6B\u8A72\u8A73\u8A66\u8A69\u8A70\u8A87\u8A7C\u8A63\u8AA0\u8A71\u8A85\u8A6D\u8A62\u8A6E\u8A6C\u8A79\u8A7B\u8A3E\u8A68\u8C62\u8C8A\u8C89\u8CCA\u8CC7\u8CC8\u8CC4\u8CB2\u8CC3\u8CC2\u8CC5\u8DE1\u8DDF\u8DE8\u8DEF\u8DF3\u8DFA\u8DEA\u8DE4\u8DE6\u8EB2\u8F03\u8F09\u8EFE\u8F0A"], - ["b940", "\u8F9F\u8FB2\u904B\u904A\u9053\u9042\u9054\u903C\u9055\u9050\u9047\u904F\u904E\u904D\u9051\u903E\u9041\u9112\u9117\u916C\u916A\u9169\u91C9\u9237\u9257\u9238\u923D\u9240\u923E\u925B\u924B\u9264\u9251\u9234\u9249\u924D\u9245\u9239\u923F\u925A\u9598\u9698\u9694\u9695\u96CD\u96CB\u96C9\u96CA\u96F7\u96FB\u96F9\u96F6\u9756\u9774\u9776\u9810\u9811\u9813\u980A\u9812\u980C\u98FC\u98F4"], - ["b9a1", "\u98FD\u98FE\u99B3\u99B1\u99B4\u9AE1\u9CE9\u9E82\u9F0E\u9F13\u9F20\u50E7\u50EE\u50E5\u50D6\u50ED\u50DA\u50D5\u50CF\u50D1\u50F1\u50CE\u50E9\u5162\u51F3\u5283\u5282\u5331\u53AD\u55FE\u5600\u561B\u5617\u55FD\u5614\u5606\u5609\u560D\u560E\u55F7\u5616\u561F\u5608\u5610\u55F6\u5718\u5716\u5875\u587E\u5883\u5893\u588A\u5879\u5885\u587D\u58FD\u5925\u5922\u5924\u596A\u5969\u5AE1\u5AE6\u5AE9\u5AD7\u5AD6\u5AD8\u5AE3\u5B75\u5BDE\u5BE7\u5BE1\u5BE5\u5BE6\u5BE8\u5BE2\u5BE4\u5BDF\u5C0D\u5C62\u5D84\u5D87\u5E5B\u5E63\u5E55\u5E57\u5E54\u5ED3\u5ED6\u5F0A\u5F46\u5F70\u5FB9\u6147"], - ["ba40", "\u613F\u614B\u6177\u6162\u6163\u615F\u615A\u6158\u6175\u622A\u6487\u6458\u6454\u64A4\u6478\u645F\u647A\u6451\u6467\u6434\u646D\u647B\u6572\u65A1\u65D7\u65D6\u66A2\u66A8\u669D\u699C\u69A8\u6995\u69C1\u69AE\u69D3\u69CB\u699B\u69B7\u69BB\u69AB\u69B4\u69D0\u69CD\u69AD\u69CC\u69A6\u69C3\u69A3\u6B49\u6B4C\u6C33\u6F33\u6F14\u6EFE\u6F13\u6EF4\u6F29\u6F3E\u6F20\u6F2C\u6F0F\u6F02\u6F22"], - ["baa1", "\u6EFF\u6EEF\u6F06\u6F31\u6F38\u6F32\u6F23\u6F15\u6F2B\u6F2F\u6F88\u6F2A\u6EEC\u6F01\u6EF2\u6ECC\u6EF7\u7194\u7199\u717D\u718A\u7184\u7192\u723E\u7292\u7296\u7344\u7350\u7464\u7463\u746A\u7470\u746D\u7504\u7591\u7627\u760D\u760B\u7609\u7613\u76E1\u76E3\u7784\u777D\u777F\u7761\u78C1\u789F\u78A7\u78B3\u78A9\u78A3\u798E\u798F\u798D\u7A2E\u7A31\u7AAA\u7AA9\u7AED\u7AEF\u7BA1\u7B95\u7B8B\u7B75\u7B97\u7B9D\u7B94\u7B8F\u7BB8\u7B87\u7B84\u7CB9\u7CBD\u7CBE\u7DBB\u7DB0\u7D9C\u7DBD\u7DBE\u7DA0\u7DCA\u7DB4\u7DB2\u7DB1\u7DBA\u7DA2\u7DBF\u7DB5\u7DB8\u7DAD\u7DD2\u7DC7\u7DAC"], - ["bb40", "\u7F70\u7FE0\u7FE1\u7FDF\u805E\u805A\u8087\u8150\u8180\u818F\u8188\u818A\u817F\u8182\u81E7\u81FA\u8207\u8214\u821E\u824B\u84C9\u84BF\u84C6\u84C4\u8499\u849E\u84B2\u849C\u84CB\u84B8\u84C0\u84D3\u8490\u84BC\u84D1\u84CA\u873F\u871C\u873B\u8722\u8725\u8734\u8718\u8755\u8737\u8729\u88F3\u8902\u88F4\u88F9\u88F8\u88FD\u88E8\u891A\u88EF\u8AA6\u8A8C\u8A9E\u8AA3\u8A8D\u8AA1\u8A93\u8AA4"], - ["bba1", "\u8AAA\u8AA5\u8AA8\u8A98\u8A91\u8A9A\u8AA7\u8C6A\u8C8D\u8C8C\u8CD3\u8CD1\u8CD2\u8D6B\u8D99\u8D95\u8DFC\u8F14\u8F12\u8F15\u8F13\u8FA3\u9060\u9058\u905C\u9063\u9059\u905E\u9062\u905D\u905B\u9119\u9118\u911E\u9175\u9178\u9177\u9174\u9278\u9280\u9285\u9298\u9296\u927B\u9293\u929C\u92A8\u927C\u9291\u95A1\u95A8\u95A9\u95A3\u95A5\u95A4\u9699\u969C\u969B\u96CC\u96D2\u9700\u977C\u9785\u97F6\u9817\u9818\u98AF\u98B1\u9903\u9905\u990C\u9909\u99C1\u9AAF\u9AB0\u9AE6\u9B41\u9B42\u9CF4\u9CF6\u9CF3\u9EBC\u9F3B\u9F4A\u5104\u5100\u50FB\u50F5\u50F9\u5102\u5108\u5109\u5105\u51DC"], - ["bc40", "\u5287\u5288\u5289\u528D\u528A\u52F0\u53B2\u562E\u563B\u5639\u5632\u563F\u5634\u5629\u5653\u564E\u5657\u5674\u5636\u562F\u5630\u5880\u589F\u589E\u58B3\u589C\u58AE\u58A9\u58A6\u596D\u5B09\u5AFB\u5B0B\u5AF5\u5B0C\u5B08\u5BEE\u5BEC\u5BE9\u5BEB\u5C64\u5C65\u5D9D\u5D94\u5E62\u5E5F\u5E61\u5EE2\u5EDA\u5EDF\u5EDD\u5EE3\u5EE0\u5F48\u5F71\u5FB7\u5FB5\u6176\u6167\u616E\u615D\u6155\u6182"], - ["bca1", "\u617C\u6170\u616B\u617E\u61A7\u6190\u61AB\u618E\u61AC\u619A\u61A4\u6194\u61AE\u622E\u6469\u646F\u6479\u649E\u64B2\u6488\u6490\u64B0\u64A5\u6493\u6495\u64A9\u6492\u64AE\u64AD\u64AB\u649A\u64AC\u6499\u64A2\u64B3\u6575\u6577\u6578\u66AE\u66AB\u66B4\u66B1\u6A23\u6A1F\u69E8\u6A01\u6A1E\u6A19\u69FD\u6A21\u6A13\u6A0A\u69F3\u6A02\u6A05\u69ED\u6A11\u6B50\u6B4E\u6BA4\u6BC5\u6BC6\u6F3F\u6F7C\u6F84\u6F51\u6F66\u6F54\u6F86\u6F6D\u6F5B\u6F78\u6F6E\u6F8E\u6F7A\u6F70\u6F64\u6F97\u6F58\u6ED5\u6F6F\u6F60\u6F5F\u719F\u71AC\u71B1\u71A8\u7256\u729B\u734E\u7357\u7469\u748B\u7483"], - ["bd40", "\u747E\u7480\u757F\u7620\u7629\u761F\u7624\u7626\u7621\u7622\u769A\u76BA\u76E4\u778E\u7787\u778C\u7791\u778B\u78CB\u78C5\u78BA\u78CA\u78BE\u78D5\u78BC\u78D0\u7A3F\u7A3C\u7A40\u7A3D\u7A37\u7A3B\u7AAF\u7AAE\u7BAD\u7BB1\u7BC4\u7BB4\u7BC6\u7BC7\u7BC1\u7BA0\u7BCC\u7CCA\u7DE0\u7DF4\u7DEF\u7DFB\u7DD8\u7DEC\u7DDD\u7DE8\u7DE3\u7DDA\u7DDE\u7DE9\u7D9E\u7DD9\u7DF2\u7DF9\u7F75\u7F77\u7FAF"], - ["bda1", "\u7FE9\u8026\u819B\u819C\u819D\u81A0\u819A\u8198\u8517\u853D\u851A\u84EE\u852C\u852D\u8513\u8511\u8523\u8521\u8514\u84EC\u8525\u84FF\u8506\u8782\u8774\u8776\u8760\u8766\u8778\u8768\u8759\u8757\u874C\u8753\u885B\u885D\u8910\u8907\u8912\u8913\u8915\u890A\u8ABC\u8AD2\u8AC7\u8AC4\u8A95\u8ACB\u8AF8\u8AB2\u8AC9\u8AC2\u8ABF\u8AB0\u8AD6\u8ACD\u8AB6\u8AB9\u8ADB\u8C4C\u8C4E\u8C6C\u8CE0\u8CDE\u8CE6\u8CE4\u8CEC\u8CED\u8CE2\u8CE3\u8CDC\u8CEA\u8CE1\u8D6D\u8D9F\u8DA3\u8E2B\u8E10\u8E1D\u8E22\u8E0F\u8E29\u8E1F\u8E21\u8E1E\u8EBA\u8F1D\u8F1B\u8F1F\u8F29\u8F26\u8F2A\u8F1C\u8F1E"], - ["be40", "\u8F25\u9069\u906E\u9068\u906D\u9077\u9130\u912D\u9127\u9131\u9187\u9189\u918B\u9183\u92C5\u92BB\u92B7\u92EA\u92AC\u92E4\u92C1\u92B3\u92BC\u92D2\u92C7\u92F0\u92B2\u95AD\u95B1\u9704\u9706\u9707\u9709\u9760\u978D\u978B\u978F\u9821\u982B\u981C\u98B3\u990A\u9913\u9912\u9918\u99DD\u99D0\u99DF\u99DB\u99D1\u99D5\u99D2\u99D9\u9AB7\u9AEE\u9AEF\u9B27\u9B45\u9B44\u9B77\u9B6F\u9D06\u9D09"], - ["bea1", "\u9D03\u9EA9\u9EBE\u9ECE\u58A8\u9F52\u5112\u5118\u5114\u5110\u5115\u5180\u51AA\u51DD\u5291\u5293\u52F3\u5659\u566B\u5679\u5669\u5664\u5678\u566A\u5668\u5665\u5671\u566F\u566C\u5662\u5676\u58C1\u58BE\u58C7\u58C5\u596E\u5B1D\u5B34\u5B78\u5BF0\u5C0E\u5F4A\u61B2\u6191\u61A9\u618A\u61CD\u61B6\u61BE\u61CA\u61C8\u6230\u64C5\u64C1\u64CB\u64BB\u64BC\u64DA\u64C4\u64C7\u64C2\u64CD\u64BF\u64D2\u64D4\u64BE\u6574\u66C6\u66C9\u66B9\u66C4\u66C7\u66B8\u6A3D\u6A38\u6A3A\u6A59\u6A6B\u6A58\u6A39\u6A44\u6A62\u6A61\u6A4B\u6A47\u6A35\u6A5F\u6A48\u6B59\u6B77\u6C05\u6FC2\u6FB1\u6FA1"], - ["bf40", "\u6FC3\u6FA4\u6FC1\u6FA7\u6FB3\u6FC0\u6FB9\u6FB6\u6FA6\u6FA0\u6FB4\u71BE\u71C9\u71D0\u71D2\u71C8\u71D5\u71B9\u71CE\u71D9\u71DC\u71C3\u71C4\u7368\u749C\u74A3\u7498\u749F\u749E\u74E2\u750C\u750D\u7634\u7638\u763A\u76E7\u76E5\u77A0\u779E\u779F\u77A5\u78E8\u78DA\u78EC\u78E7\u79A6\u7A4D\u7A4E\u7A46\u7A4C\u7A4B\u7ABA\u7BD9\u7C11\u7BC9\u7BE4\u7BDB\u7BE1\u7BE9\u7BE6\u7CD5\u7CD6\u7E0A"], - ["bfa1", "\u7E11\u7E08\u7E1B\u7E23\u7E1E\u7E1D\u7E09\u7E10\u7F79\u7FB2\u7FF0\u7FF1\u7FEE\u8028\u81B3\u81A9\u81A8\u81FB\u8208\u8258\u8259\u854A\u8559\u8548\u8568\u8569\u8543\u8549\u856D\u856A\u855E\u8783\u879F\u879E\u87A2\u878D\u8861\u892A\u8932\u8925\u892B\u8921\u89AA\u89A6\u8AE6\u8AFA\u8AEB\u8AF1\u8B00\u8ADC\u8AE7\u8AEE\u8AFE\u8B01\u8B02\u8AF7\u8AED\u8AF3\u8AF6\u8AFC\u8C6B\u8C6D\u8C93\u8CF4\u8E44\u8E31\u8E34\u8E42\u8E39\u8E35\u8F3B\u8F2F\u8F38\u8F33\u8FA8\u8FA6\u9075\u9074\u9078\u9072\u907C\u907A\u9134\u9192\u9320\u9336\u92F8\u9333\u932F\u9322\u92FC\u932B\u9304\u931A"], - ["c040", "\u9310\u9326\u9321\u9315\u932E\u9319\u95BB\u96A7\u96A8\u96AA\u96D5\u970E\u9711\u9716\u970D\u9713\u970F\u975B\u975C\u9766\u9798\u9830\u9838\u983B\u9837\u982D\u9839\u9824\u9910\u9928\u991E\u991B\u9921\u991A\u99ED\u99E2\u99F1\u9AB8\u9ABC\u9AFB\u9AED\u9B28\u9B91\u9D15\u9D23\u9D26\u9D28\u9D12\u9D1B\u9ED8\u9ED4\u9F8D\u9F9C\u512A\u511F\u5121\u5132\u52F5\u568E\u5680\u5690\u5685\u5687"], - ["c0a1", "\u568F\u58D5\u58D3\u58D1\u58CE\u5B30\u5B2A\u5B24\u5B7A\u5C37\u5C68\u5DBC\u5DBA\u5DBD\u5DB8\u5E6B\u5F4C\u5FBD\u61C9\u61C2\u61C7\u61E6\u61CB\u6232\u6234\u64CE\u64CA\u64D8\u64E0\u64F0\u64E6\u64EC\u64F1\u64E2\u64ED\u6582\u6583\u66D9\u66D6\u6A80\u6A94\u6A84\u6AA2\u6A9C\u6ADB\u6AA3\u6A7E\u6A97\u6A90\u6AA0\u6B5C\u6BAE\u6BDA\u6C08\u6FD8\u6FF1\u6FDF\u6FE0\u6FDB\u6FE4\u6FEB\u6FEF\u6F80\u6FEC\u6FE1\u6FE9\u6FD5\u6FEE\u6FF0\u71E7\u71DF\u71EE\u71E6\u71E5\u71ED\u71EC\u71F4\u71E0\u7235\u7246\u7370\u7372\u74A9\u74B0\u74A6\u74A8\u7646\u7642\u764C\u76EA\u77B3\u77AA\u77B0\u77AC"], - ["c140", "\u77A7\u77AD\u77EF\u78F7\u78FA\u78F4\u78EF\u7901\u79A7\u79AA\u7A57\u7ABF\u7C07\u7C0D\u7BFE\u7BF7\u7C0C\u7BE0\u7CE0\u7CDC\u7CDE\u7CE2\u7CDF\u7CD9\u7CDD\u7E2E\u7E3E\u7E46\u7E37\u7E32\u7E43\u7E2B\u7E3D\u7E31\u7E45\u7E41\u7E34\u7E39\u7E48\u7E35\u7E3F\u7E2F\u7F44\u7FF3\u7FFC\u8071\u8072\u8070\u806F\u8073\u81C6\u81C3\u81BA\u81C2\u81C0\u81BF\u81BD\u81C9\u81BE\u81E8\u8209\u8271\u85AA"], - ["c1a1", "\u8584\u857E\u859C\u8591\u8594\u85AF\u859B\u8587\u85A8\u858A\u8667\u87C0\u87D1\u87B3\u87D2\u87C6\u87AB\u87BB\u87BA\u87C8\u87CB\u893B\u8936\u8944\u8938\u893D\u89AC\u8B0E\u8B17\u8B19\u8B1B\u8B0A\u8B20\u8B1D\u8B04\u8B10\u8C41\u8C3F\u8C73\u8CFA\u8CFD\u8CFC\u8CF8\u8CFB\u8DA8\u8E49\u8E4B\u8E48\u8E4A\u8F44\u8F3E\u8F42\u8F45\u8F3F\u907F\u907D\u9084\u9081\u9082\u9080\u9139\u91A3\u919E\u919C\u934D\u9382\u9328\u9375\u934A\u9365\u934B\u9318\u937E\u936C\u935B\u9370\u935A\u9354\u95CA\u95CB\u95CC\u95C8\u95C6\u96B1\u96B8\u96D6\u971C\u971E\u97A0\u97D3\u9846\u98B6\u9935\u9A01"], - ["c240", "\u99FF\u9BAE\u9BAB\u9BAA\u9BAD\u9D3B\u9D3F\u9E8B\u9ECF\u9EDE\u9EDC\u9EDD\u9EDB\u9F3E\u9F4B\u53E2\u5695\u56AE\u58D9\u58D8\u5B38\u5F5D\u61E3\u6233\u64F4\u64F2\u64FE\u6506\u64FA\u64FB\u64F7\u65B7\u66DC\u6726\u6AB3\u6AAC\u6AC3\u6ABB\u6AB8\u6AC2\u6AAE\u6AAF\u6B5F\u6B78\u6BAF\u7009\u700B\u6FFE\u7006\u6FFA\u7011\u700F\u71FB\u71FC\u71FE\u71F8\u7377\u7375\u74A7\u74BF\u7515\u7656\u7658"], - ["c2a1", "\u7652\u77BD\u77BF\u77BB\u77BC\u790E\u79AE\u7A61\u7A62\u7A60\u7AC4\u7AC5\u7C2B\u7C27\u7C2A\u7C1E\u7C23\u7C21\u7CE7\u7E54\u7E55\u7E5E\u7E5A\u7E61\u7E52\u7E59\u7F48\u7FF9\u7FFB\u8077\u8076\u81CD\u81CF\u820A\u85CF\u85A9\u85CD\u85D0\u85C9\u85B0\u85BA\u85B9\u85A6\u87EF\u87EC\u87F2\u87E0\u8986\u89B2\u89F4\u8B28\u8B39\u8B2C\u8B2B\u8C50\u8D05\u8E59\u8E63\u8E66\u8E64\u8E5F\u8E55\u8EC0\u8F49\u8F4D\u9087\u9083\u9088\u91AB\u91AC\u91D0\u9394\u938A\u9396\u93A2\u93B3\u93AE\u93AC\u93B0\u9398\u939A\u9397\u95D4\u95D6\u95D0\u95D5\u96E2\u96DC\u96D9\u96DB\u96DE\u9724\u97A3\u97A6"], - ["c340", "\u97AD\u97F9\u984D\u984F\u984C\u984E\u9853\u98BA\u993E\u993F\u993D\u992E\u99A5\u9A0E\u9AC1\u9B03\u9B06\u9B4F\u9B4E\u9B4D\u9BCA\u9BC9\u9BFD\u9BC8\u9BC0\u9D51\u9D5D\u9D60\u9EE0\u9F15\u9F2C\u5133\u56A5\u58DE\u58DF\u58E2\u5BF5\u9F90\u5EEC\u61F2\u61F7\u61F6\u61F5\u6500\u650F\u66E0\u66DD\u6AE5\u6ADD\u6ADA\u6AD3\u701B\u701F\u7028\u701A\u701D\u7015\u7018\u7206\u720D\u7258\u72A2\u7378"], - ["c3a1", "\u737A\u74BD\u74CA\u74E3\u7587\u7586\u765F\u7661\u77C7\u7919\u79B1\u7A6B\u7A69\u7C3E\u7C3F\u7C38\u7C3D\u7C37\u7C40\u7E6B\u7E6D\u7E79\u7E69\u7E6A\u7F85\u7E73\u7FB6\u7FB9\u7FB8\u81D8\u85E9\u85DD\u85EA\u85D5\u85E4\u85E5\u85F7\u87FB\u8805\u880D\u87F9\u87FE\u8960\u895F\u8956\u895E\u8B41\u8B5C\u8B58\u8B49\u8B5A\u8B4E\u8B4F\u8B46\u8B59\u8D08\u8D0A\u8E7C\u8E72\u8E87\u8E76\u8E6C\u8E7A\u8E74\u8F54\u8F4E\u8FAD\u908A\u908B\u91B1\u91AE\u93E1\u93D1\u93DF\u93C3\u93C8\u93DC\u93DD\u93D6\u93E2\u93CD\u93D8\u93E4\u93D7\u93E8\u95DC\u96B4\u96E3\u972A\u9727\u9761\u97DC\u97FB\u985E"], - ["c440", "\u9858\u985B\u98BC\u9945\u9949\u9A16\u9A19\u9B0D\u9BE8\u9BE7\u9BD6\u9BDB\u9D89\u9D61\u9D72\u9D6A\u9D6C\u9E92\u9E97\u9E93\u9EB4\u52F8\u56A8\u56B7\u56B6\u56B4\u56BC\u58E4\u5B40\u5B43\u5B7D\u5BF6\u5DC9\u61F8\u61FA\u6518\u6514\u6519\u66E6\u6727\u6AEC\u703E\u7030\u7032\u7210\u737B\u74CF\u7662\u7665\u7926\u792A\u792C\u792B\u7AC7\u7AF6\u7C4C\u7C43\u7C4D\u7CEF\u7CF0\u8FAE\u7E7D\u7E7C"], - ["c4a1", "\u7E82\u7F4C\u8000\u81DA\u8266\u85FB\u85F9\u8611\u85FA\u8606\u860B\u8607\u860A\u8814\u8815\u8964\u89BA\u89F8\u8B70\u8B6C\u8B66\u8B6F\u8B5F\u8B6B\u8D0F\u8D0D\u8E89\u8E81\u8E85\u8E82\u91B4\u91CB\u9418\u9403\u93FD\u95E1\u9730\u98C4\u9952\u9951\u99A8\u9A2B\u9A30\u9A37\u9A35\u9C13\u9C0D\u9E79\u9EB5\u9EE8\u9F2F\u9F5F\u9F63\u9F61\u5137\u5138\u56C1\u56C0\u56C2\u5914\u5C6C\u5DCD\u61FC\u61FE\u651D\u651C\u6595\u66E9\u6AFB\u6B04\u6AFA\u6BB2\u704C\u721B\u72A7\u74D6\u74D4\u7669\u77D3\u7C50\u7E8F\u7E8C\u7FBC\u8617\u862D\u861A\u8823\u8822\u8821\u881F\u896A\u896C\u89BD\u8B74"], - ["c540", "\u8B77\u8B7D\u8D13\u8E8A\u8E8D\u8E8B\u8F5F\u8FAF\u91BA\u942E\u9433\u9435\u943A\u9438\u9432\u942B\u95E2\u9738\u9739\u9732\u97FF\u9867\u9865\u9957\u9A45\u9A43\u9A40\u9A3E\u9ACF\u9B54\u9B51\u9C2D\u9C25\u9DAF\u9DB4\u9DC2\u9DB8\u9E9D\u9EEF\u9F19\u9F5C\u9F66\u9F67\u513C\u513B\u56C8\u56CA\u56C9\u5B7F\u5DD4\u5DD2\u5F4E\u61FF\u6524\u6B0A\u6B61\u7051\u7058\u7380\u74E4\u758A\u766E\u766C"], - ["c5a1", "\u79B3\u7C60\u7C5F\u807E\u807D\u81DF\u8972\u896F\u89FC\u8B80\u8D16\u8D17\u8E91\u8E93\u8F61\u9148\u9444\u9451\u9452\u973D\u973E\u97C3\u97C1\u986B\u9955\u9A55\u9A4D\u9AD2\u9B1A\u9C49\u9C31\u9C3E\u9C3B\u9DD3\u9DD7\u9F34\u9F6C\u9F6A\u9F94\u56CC\u5DD6\u6200\u6523\u652B\u652A\u66EC\u6B10\u74DA\u7ACA\u7C64\u7C63\u7C65\u7E93\u7E96\u7E94\u81E2\u8638\u863F\u8831\u8B8A\u9090\u908F\u9463\u9460\u9464\u9768\u986F\u995C\u9A5A\u9A5B\u9A57\u9AD3\u9AD4\u9AD1\u9C54\u9C57\u9C56\u9DE5\u9E9F\u9EF4\u56D1\u58E9\u652C\u705E\u7671\u7672\u77D7\u7F50\u7F88\u8836\u8839\u8862\u8B93\u8B92"], - ["c640", "\u8B96\u8277\u8D1B\u91C0\u946A\u9742\u9748\u9744\u97C6\u9870\u9A5F\u9B22\u9B58\u9C5F\u9DF9\u9DFA\u9E7C\u9E7D\u9F07\u9F77\u9F72\u5EF3\u6B16\u7063\u7C6C\u7C6E\u883B\u89C0\u8EA1\u91C1\u9472\u9470\u9871\u995E\u9AD6\u9B23\u9ECC\u7064\u77DA\u8B9A\u9477\u97C9\u9A62\u9A65\u7E9C\u8B9C\u8EAA\u91C5\u947D\u947E\u947C\u9C77\u9C78\u9EF7\u8C54\u947F\u9E1A\u7228\u9A6A\u9B31\u9E1B\u9E1E\u7C72"], - ["c940", "\u4E42\u4E5C\u51F5\u531A\u5382\u4E07\u4E0C\u4E47\u4E8D\u56D7\uFA0C\u5C6E\u5F73\u4E0F\u5187\u4E0E\u4E2E\u4E93\u4EC2\u4EC9\u4EC8\u5198\u52FC\u536C\u53B9\u5720\u5903\u592C\u5C10\u5DFF\u65E1\u6BB3\u6BCC\u6C14\u723F\u4E31\u4E3C\u4EE8\u4EDC\u4EE9\u4EE1\u4EDD\u4EDA\u520C\u531C\u534C\u5722\u5723\u5917\u592F\u5B81\u5B84\u5C12\u5C3B\u5C74\u5C73\u5E04\u5E80\u5E82\u5FC9\u6209\u6250\u6C15"], - ["c9a1", "\u6C36\u6C43\u6C3F\u6C3B\u72AE\u72B0\u738A\u79B8\u808A\u961E\u4F0E\u4F18\u4F2C\u4EF5\u4F14\u4EF1\u4F00\u4EF7\u4F08\u4F1D\u4F02\u4F05\u4F22\u4F13\u4F04\u4EF4\u4F12\u51B1\u5213\u5209\u5210\u52A6\u5322\u531F\u534D\u538A\u5407\u56E1\u56DF\u572E\u572A\u5734\u593C\u5980\u597C\u5985\u597B\u597E\u5977\u597F\u5B56\u5C15\u5C25\u5C7C\u5C7A\u5C7B\u5C7E\u5DDF\u5E75\u5E84\u5F02\u5F1A\u5F74\u5FD5\u5FD4\u5FCF\u625C\u625E\u6264\u6261\u6266\u6262\u6259\u6260\u625A\u6265\u65EF\u65EE\u673E\u6739\u6738\u673B\u673A\u673F\u673C\u6733\u6C18\u6C46\u6C52\u6C5C\u6C4F\u6C4A\u6C54\u6C4B"], - ["ca40", "\u6C4C\u7071\u725E\u72B4\u72B5\u738E\u752A\u767F\u7A75\u7F51\u8278\u827C\u8280\u827D\u827F\u864D\u897E\u9099\u9097\u9098\u909B\u9094\u9622\u9624\u9620\u9623\u4F56\u4F3B\u4F62\u4F49\u4F53\u4F64\u4F3E\u4F67\u4F52\u4F5F\u4F41\u4F58\u4F2D\u4F33\u4F3F\u4F61\u518F\u51B9\u521C\u521E\u5221\u52AD\u52AE\u5309\u5363\u5372\u538E\u538F\u5430\u5437\u542A\u5454\u5445\u5419\u541C\u5425\u5418"], - ["caa1", "\u543D\u544F\u5441\u5428\u5424\u5447\u56EE\u56E7\u56E5\u5741\u5745\u574C\u5749\u574B\u5752\u5906\u5940\u59A6\u5998\u59A0\u5997\u598E\u59A2\u5990\u598F\u59A7\u59A1\u5B8E\u5B92\u5C28\u5C2A\u5C8D\u5C8F\u5C88\u5C8B\u5C89\u5C92\u5C8A\u5C86\u5C93\u5C95\u5DE0\u5E0A\u5E0E\u5E8B\u5E89\u5E8C\u5E88\u5E8D\u5F05\u5F1D\u5F78\u5F76\u5FD2\u5FD1\u5FD0\u5FED\u5FE8\u5FEE\u5FF3\u5FE1\u5FE4\u5FE3\u5FFA\u5FEF\u5FF7\u5FFB\u6000\u5FF4\u623A\u6283\u628C\u628E\u628F\u6294\u6287\u6271\u627B\u627A\u6270\u6281\u6288\u6277\u627D\u6272\u6274\u6537\u65F0\u65F4\u65F3\u65F2\u65F5\u6745\u6747"], - ["cb40", "\u6759\u6755\u674C\u6748\u675D\u674D\u675A\u674B\u6BD0\u6C19\u6C1A\u6C78\u6C67\u6C6B\u6C84\u6C8B\u6C8F\u6C71\u6C6F\u6C69\u6C9A\u6C6D\u6C87\u6C95\u6C9C\u6C66\u6C73\u6C65\u6C7B\u6C8E\u7074\u707A\u7263\u72BF\u72BD\u72C3\u72C6\u72C1\u72BA\u72C5\u7395\u7397\u7393\u7394\u7392\u753A\u7539\u7594\u7595\u7681\u793D\u8034\u8095\u8099\u8090\u8092\u809C\u8290\u828F\u8285\u828E\u8291\u8293"], - ["cba1", "\u828A\u8283\u8284\u8C78\u8FC9\u8FBF\u909F\u90A1\u90A5\u909E\u90A7\u90A0\u9630\u9628\u962F\u962D\u4E33\u4F98\u4F7C\u4F85\u4F7D\u4F80\u4F87\u4F76\u4F74\u4F89\u4F84\u4F77\u4F4C\u4F97\u4F6A\u4F9A\u4F79\u4F81\u4F78\u4F90\u4F9C\u4F94\u4F9E\u4F92\u4F82\u4F95\u4F6B\u4F6E\u519E\u51BC\u51BE\u5235\u5232\u5233\u5246\u5231\u52BC\u530A\u530B\u533C\u5392\u5394\u5487\u547F\u5481\u5491\u5482\u5488\u546B\u547A\u547E\u5465\u546C\u5474\u5466\u548D\u546F\u5461\u5460\u5498\u5463\u5467\u5464\u56F7\u56F9\u576F\u5772\u576D\u576B\u5771\u5770\u5776\u5780\u5775\u577B\u5773\u5774\u5762"], - ["cc40", "\u5768\u577D\u590C\u5945\u59B5\u59BA\u59CF\u59CE\u59B2\u59CC\u59C1\u59B6\u59BC\u59C3\u59D6\u59B1\u59BD\u59C0\u59C8\u59B4\u59C7\u5B62\u5B65\u5B93\u5B95\u5C44\u5C47\u5CAE\u5CA4\u5CA0\u5CB5\u5CAF\u5CA8\u5CAC\u5C9F\u5CA3\u5CAD\u5CA2\u5CAA\u5CA7\u5C9D\u5CA5\u5CB6\u5CB0\u5CA6\u5E17\u5E14\u5E19\u5F28\u5F22\u5F23\u5F24\u5F54\u5F82\u5F7E\u5F7D\u5FDE\u5FE5\u602D\u6026\u6019\u6032\u600B"], - ["cca1", "\u6034\u600A\u6017\u6033\u601A\u601E\u602C\u6022\u600D\u6010\u602E\u6013\u6011\u600C\u6009\u601C\u6214\u623D\u62AD\u62B4\u62D1\u62BE\u62AA\u62B6\u62CA\u62AE\u62B3\u62AF\u62BB\u62A9\u62B0\u62B8\u653D\u65A8\u65BB\u6609\u65FC\u6604\u6612\u6608\u65FB\u6603\u660B\u660D\u6605\u65FD\u6611\u6610\u66F6\u670A\u6785\u676C\u678E\u6792\u6776\u677B\u6798\u6786\u6784\u6774\u678D\u678C\u677A\u679F\u6791\u6799\u6783\u677D\u6781\u6778\u6779\u6794\u6B25\u6B80\u6B7E\u6BDE\u6C1D\u6C93\u6CEC\u6CEB\u6CEE\u6CD9\u6CB6\u6CD4\u6CAD\u6CE7\u6CB7\u6CD0\u6CC2\u6CBA\u6CC3\u6CC6\u6CED\u6CF2"], - ["cd40", "\u6CD2\u6CDD\u6CB4\u6C8A\u6C9D\u6C80\u6CDE\u6CC0\u6D30\u6CCD\u6CC7\u6CB0\u6CF9\u6CCF\u6CE9\u6CD1\u7094\u7098\u7085\u7093\u7086\u7084\u7091\u7096\u7082\u709A\u7083\u726A\u72D6\u72CB\u72D8\u72C9\u72DC\u72D2\u72D4\u72DA\u72CC\u72D1\u73A4\u73A1\u73AD\u73A6\u73A2\u73A0\u73AC\u739D\u74DD\u74E8\u753F\u7540\u753E\u758C\u7598\u76AF\u76F3\u76F1\u76F0\u76F5\u77F8\u77FC\u77F9\u77FB\u77FA"], - ["cda1", "\u77F7\u7942\u793F\u79C5\u7A78\u7A7B\u7AFB\u7C75\u7CFD\u8035\u808F\u80AE\u80A3\u80B8\u80B5\u80AD\u8220\u82A0\u82C0\u82AB\u829A\u8298\u829B\u82B5\u82A7\u82AE\u82BC\u829E\u82BA\u82B4\u82A8\u82A1\u82A9\u82C2\u82A4\u82C3\u82B6\u82A2\u8670\u866F\u866D\u866E\u8C56\u8FD2\u8FCB\u8FD3\u8FCD\u8FD6\u8FD5\u8FD7\u90B2\u90B4\u90AF\u90B3\u90B0\u9639\u963D\u963C\u963A\u9643\u4FCD\u4FC5\u4FD3\u4FB2\u4FC9\u4FCB\u4FC1\u4FD4\u4FDC\u4FD9\u4FBB\u4FB3\u4FDB\u4FC7\u4FD6\u4FBA\u4FC0\u4FB9\u4FEC\u5244\u5249\u52C0\u52C2\u533D\u537C\u5397\u5396\u5399\u5398\u54BA\u54A1\u54AD\u54A5\u54CF"], - ["ce40", "\u54C3\u830D\u54B7\u54AE\u54D6\u54B6\u54C5\u54C6\u54A0\u5470\u54BC\u54A2\u54BE\u5472\u54DE\u54B0\u57B5\u579E\u579F\u57A4\u578C\u5797\u579D\u579B\u5794\u5798\u578F\u5799\u57A5\u579A\u5795\u58F4\u590D\u5953\u59E1\u59DE\u59EE\u5A00\u59F1\u59DD\u59FA\u59FD\u59FC\u59F6\u59E4\u59F2\u59F7\u59DB\u59E9\u59F3\u59F5\u59E0\u59FE\u59F4\u59ED\u5BA8\u5C4C\u5CD0\u5CD8\u5CCC\u5CD7\u5CCB\u5CDB"], - ["cea1", "\u5CDE\u5CDA\u5CC9\u5CC7\u5CCA\u5CD6\u5CD3\u5CD4\u5CCF\u5CC8\u5CC6\u5CCE\u5CDF\u5CF8\u5DF9\u5E21\u5E22\u5E23\u5E20\u5E24\u5EB0\u5EA4\u5EA2\u5E9B\u5EA3\u5EA5\u5F07\u5F2E\u5F56\u5F86\u6037\u6039\u6054\u6072\u605E\u6045\u6053\u6047\u6049\u605B\u604C\u6040\u6042\u605F\u6024\u6044\u6058\u6066\u606E\u6242\u6243\u62CF\u630D\u630B\u62F5\u630E\u6303\u62EB\u62F9\u630F\u630C\u62F8\u62F6\u6300\u6313\u6314\u62FA\u6315\u62FB\u62F0\u6541\u6543\u65AA\u65BF\u6636\u6621\u6632\u6635\u661C\u6626\u6622\u6633\u662B\u663A\u661D\u6634\u6639\u662E\u670F\u6710\u67C1\u67F2\u67C8\u67BA"], - ["cf40", "\u67DC\u67BB\u67F8\u67D8\u67C0\u67B7\u67C5\u67EB\u67E4\u67DF\u67B5\u67CD\u67B3\u67F7\u67F6\u67EE\u67E3\u67C2\u67B9\u67CE\u67E7\u67F0\u67B2\u67FC\u67C6\u67ED\u67CC\u67AE\u67E6\u67DB\u67FA\u67C9\u67CA\u67C3\u67EA\u67CB\u6B28\u6B82\u6B84\u6BB6\u6BD6\u6BD8\u6BE0\u6C20\u6C21\u6D28\u6D34\u6D2D\u6D1F\u6D3C\u6D3F\u6D12\u6D0A\u6CDA\u6D33\u6D04\u6D19\u6D3A\u6D1A\u6D11\u6D00\u6D1D\u6D42"], - ["cfa1", "\u6D01\u6D18\u6D37\u6D03\u6D0F\u6D40\u6D07\u6D20\u6D2C\u6D08\u6D22\u6D09\u6D10\u70B7\u709F\u70BE\u70B1\u70B0\u70A1\u70B4\u70B5\u70A9\u7241\u7249\u724A\u726C\u7270\u7273\u726E\u72CA\u72E4\u72E8\u72EB\u72DF\u72EA\u72E6\u72E3\u7385\u73CC\u73C2\u73C8\u73C5\u73B9\u73B6\u73B5\u73B4\u73EB\u73BF\u73C7\u73BE\u73C3\u73C6\u73B8\u73CB\u74EC\u74EE\u752E\u7547\u7548\u75A7\u75AA\u7679\u76C4\u7708\u7703\u7704\u7705\u770A\u76F7\u76FB\u76FA\u77E7\u77E8\u7806\u7811\u7812\u7805\u7810\u780F\u780E\u7809\u7803\u7813\u794A\u794C\u794B\u7945\u7944\u79D5\u79CD\u79CF\u79D6\u79CE\u7A80"], - ["d040", "\u7A7E\u7AD1\u7B00\u7B01\u7C7A\u7C78\u7C79\u7C7F\u7C80\u7C81\u7D03\u7D08\u7D01\u7F58\u7F91\u7F8D\u7FBE\u8007\u800E\u800F\u8014\u8037\u80D8\u80C7\u80E0\u80D1\u80C8\u80C2\u80D0\u80C5\u80E3\u80D9\u80DC\u80CA\u80D5\u80C9\u80CF\u80D7\u80E6\u80CD\u81FF\u8221\u8294\u82D9\u82FE\u82F9\u8307\u82E8\u8300\u82D5\u833A\u82EB\u82D6\u82F4\u82EC\u82E1\u82F2\u82F5\u830C\u82FB\u82F6\u82F0\u82EA"], - ["d0a1", "\u82E4\u82E0\u82FA\u82F3\u82ED\u8677\u8674\u867C\u8673\u8841\u884E\u8867\u886A\u8869\u89D3\u8A04\u8A07\u8D72\u8FE3\u8FE1\u8FEE\u8FE0\u90F1\u90BD\u90BF\u90D5\u90C5\u90BE\u90C7\u90CB\u90C8\u91D4\u91D3\u9654\u964F\u9651\u9653\u964A\u964E\u501E\u5005\u5007\u5013\u5022\u5030\u501B\u4FF5\u4FF4\u5033\u5037\u502C\u4FF6\u4FF7\u5017\u501C\u5020\u5027\u5035\u502F\u5031\u500E\u515A\u5194\u5193\u51CA\u51C4\u51C5\u51C8\u51CE\u5261\u525A\u5252\u525E\u525F\u5255\u5262\u52CD\u530E\u539E\u5526\u54E2\u5517\u5512\u54E7\u54F3\u54E4\u551A\u54FF\u5504\u5508\u54EB\u5511\u5505\u54F1"], - ["d140", "\u550A\u54FB\u54F7\u54F8\u54E0\u550E\u5503\u550B\u5701\u5702\u57CC\u5832\u57D5\u57D2\u57BA\u57C6\u57BD\u57BC\u57B8\u57B6\u57BF\u57C7\u57D0\u57B9\u57C1\u590E\u594A\u5A19\u5A16\u5A2D\u5A2E\u5A15\u5A0F\u5A17\u5A0A\u5A1E\u5A33\u5B6C\u5BA7\u5BAD\u5BAC\u5C03\u5C56\u5C54\u5CEC\u5CFF\u5CEE\u5CF1\u5CF7\u5D00\u5CF9\u5E29\u5E28\u5EA8\u5EAE\u5EAA\u5EAC\u5F33\u5F30\u5F67\u605D\u605A\u6067"], - ["d1a1", "\u6041\u60A2\u6088\u6080\u6092\u6081\u609D\u6083\u6095\u609B\u6097\u6087\u609C\u608E\u6219\u6246\u62F2\u6310\u6356\u632C\u6344\u6345\u6336\u6343\u63E4\u6339\u634B\u634A\u633C\u6329\u6341\u6334\u6358\u6354\u6359\u632D\u6347\u6333\u635A\u6351\u6338\u6357\u6340\u6348\u654A\u6546\u65C6\u65C3\u65C4\u65C2\u664A\u665F\u6647\u6651\u6712\u6713\u681F\u681A\u6849\u6832\u6833\u683B\u684B\u684F\u6816\u6831\u681C\u6835\u682B\u682D\u682F\u684E\u6844\u6834\u681D\u6812\u6814\u6826\u6828\u682E\u684D\u683A\u6825\u6820\u6B2C\u6B2F\u6B2D\u6B31\u6B34\u6B6D\u8082\u6B88\u6BE6\u6BE4"], - ["d240", "\u6BE8\u6BE3\u6BE2\u6BE7\u6C25\u6D7A\u6D63\u6D64\u6D76\u6D0D\u6D61\u6D92\u6D58\u6D62\u6D6D\u6D6F\u6D91\u6D8D\u6DEF\u6D7F\u6D86\u6D5E\u6D67\u6D60\u6D97\u6D70\u6D7C\u6D5F\u6D82\u6D98\u6D2F\u6D68\u6D8B\u6D7E\u6D80\u6D84\u6D16\u6D83\u6D7B\u6D7D\u6D75\u6D90\u70DC\u70D3\u70D1\u70DD\u70CB\u7F39\u70E2\u70D7\u70D2\u70DE\u70E0\u70D4\u70CD\u70C5\u70C6\u70C7\u70DA\u70CE\u70E1\u7242\u7278"], - ["d2a1", "\u7277\u7276\u7300\u72FA\u72F4\u72FE\u72F6\u72F3\u72FB\u7301\u73D3\u73D9\u73E5\u73D6\u73BC\u73E7\u73E3\u73E9\u73DC\u73D2\u73DB\u73D4\u73DD\u73DA\u73D7\u73D8\u73E8\u74DE\u74DF\u74F4\u74F5\u7521\u755B\u755F\u75B0\u75C1\u75BB\u75C4\u75C0\u75BF\u75B6\u75BA\u768A\u76C9\u771D\u771B\u7710\u7713\u7712\u7723\u7711\u7715\u7719\u771A\u7722\u7727\u7823\u782C\u7822\u7835\u782F\u7828\u782E\u782B\u7821\u7829\u7833\u782A\u7831\u7954\u795B\u794F\u795C\u7953\u7952\u7951\u79EB\u79EC\u79E0\u79EE\u79ED\u79EA\u79DC\u79DE\u79DD\u7A86\u7A89\u7A85\u7A8B\u7A8C\u7A8A\u7A87\u7AD8\u7B10"], - ["d340", "\u7B04\u7B13\u7B05\u7B0F\u7B08\u7B0A\u7B0E\u7B09\u7B12\u7C84\u7C91\u7C8A\u7C8C\u7C88\u7C8D\u7C85\u7D1E\u7D1D\u7D11\u7D0E\u7D18\u7D16\u7D13\u7D1F\u7D12\u7D0F\u7D0C\u7F5C\u7F61\u7F5E\u7F60\u7F5D\u7F5B\u7F96\u7F92\u7FC3\u7FC2\u7FC0\u8016\u803E\u8039\u80FA\u80F2\u80F9\u80F5\u8101\u80FB\u8100\u8201\u822F\u8225\u8333\u832D\u8344\u8319\u8351\u8325\u8356\u833F\u8341\u8326\u831C\u8322"], - ["d3a1", "\u8342\u834E\u831B\u832A\u8308\u833C\u834D\u8316\u8324\u8320\u8337\u832F\u8329\u8347\u8345\u834C\u8353\u831E\u832C\u834B\u8327\u8348\u8653\u8652\u86A2\u86A8\u8696\u868D\u8691\u869E\u8687\u8697\u8686\u868B\u869A\u8685\u86A5\u8699\u86A1\u86A7\u8695\u8698\u868E\u869D\u8690\u8694\u8843\u8844\u886D\u8875\u8876\u8872\u8880\u8871\u887F\u886F\u8883\u887E\u8874\u887C\u8A12\u8C47\u8C57\u8C7B\u8CA4\u8CA3\u8D76\u8D78\u8DB5\u8DB7\u8DB6\u8ED1\u8ED3\u8FFE\u8FF5\u9002\u8FFF\u8FFB\u9004\u8FFC\u8FF6\u90D6\u90E0\u90D9\u90DA\u90E3\u90DF\u90E5\u90D8\u90DB\u90D7\u90DC\u90E4\u9150"], - ["d440", "\u914E\u914F\u91D5\u91E2\u91DA\u965C\u965F\u96BC\u98E3\u9ADF\u9B2F\u4E7F\u5070\u506A\u5061\u505E\u5060\u5053\u504B\u505D\u5072\u5048\u504D\u5041\u505B\u504A\u5062\u5015\u5045\u505F\u5069\u506B\u5063\u5064\u5046\u5040\u506E\u5073\u5057\u5051\u51D0\u526B\u526D\u526C\u526E\u52D6\u52D3\u532D\u539C\u5575\u5576\u553C\u554D\u5550\u5534\u552A\u5551\u5562\u5536\u5535\u5530\u5552\u5545"], - ["d4a1", "\u550C\u5532\u5565\u554E\u5539\u5548\u552D\u553B\u5540\u554B\u570A\u5707\u57FB\u5814\u57E2\u57F6\u57DC\u57F4\u5800\u57ED\u57FD\u5808\u57F8\u580B\u57F3\u57CF\u5807\u57EE\u57E3\u57F2\u57E5\u57EC\u57E1\u580E\u57FC\u5810\u57E7\u5801\u580C\u57F1\u57E9\u57F0\u580D\u5804\u595C\u5A60\u5A58\u5A55\u5A67\u5A5E\u5A38\u5A35\u5A6D\u5A50\u5A5F\u5A65\u5A6C\u5A53\u5A64\u5A57\u5A43\u5A5D\u5A52\u5A44\u5A5B\u5A48\u5A8E\u5A3E\u5A4D\u5A39\u5A4C\u5A70\u5A69\u5A47\u5A51\u5A56\u5A42\u5A5C\u5B72\u5B6E\u5BC1\u5BC0\u5C59\u5D1E\u5D0B\u5D1D\u5D1A\u5D20\u5D0C\u5D28\u5D0D\u5D26\u5D25\u5D0F"], - ["d540", "\u5D30\u5D12\u5D23\u5D1F\u5D2E\u5E3E\u5E34\u5EB1\u5EB4\u5EB9\u5EB2\u5EB3\u5F36\u5F38\u5F9B\u5F96\u5F9F\u608A\u6090\u6086\u60BE\u60B0\u60BA\u60D3\u60D4\u60CF\u60E4\u60D9\u60DD\u60C8\u60B1\u60DB\u60B7\u60CA\u60BF\u60C3\u60CD\u60C0\u6332\u6365\u638A\u6382\u637D\u63BD\u639E\u63AD\u639D\u6397\u63AB\u638E\u636F\u6387\u6390\u636E\u63AF\u6375\u639C\u636D\u63AE\u637C\u63A4\u633B\u639F"], - ["d5a1", "\u6378\u6385\u6381\u6391\u638D\u6370\u6553\u65CD\u6665\u6661\u665B\u6659\u665C\u6662\u6718\u6879\u6887\u6890\u689C\u686D\u686E\u68AE\u68AB\u6956\u686F\u68A3\u68AC\u68A9\u6875\u6874\u68B2\u688F\u6877\u6892\u687C\u686B\u6872\u68AA\u6880\u6871\u687E\u689B\u6896\u688B\u68A0\u6889\u68A4\u6878\u687B\u6891\u688C\u688A\u687D\u6B36\u6B33\u6B37\u6B38\u6B91\u6B8F\u6B8D\u6B8E\u6B8C\u6C2A\u6DC0\u6DAB\u6DB4\u6DB3\u6E74\u6DAC\u6DE9\u6DE2\u6DB7\u6DF6\u6DD4\u6E00\u6DC8\u6DE0\u6DDF\u6DD6\u6DBE\u6DE5\u6DDC\u6DDD\u6DDB\u6DF4\u6DCA\u6DBD\u6DED\u6DF0\u6DBA\u6DD5\u6DC2\u6DCF\u6DC9"], - ["d640", "\u6DD0\u6DF2\u6DD3\u6DFD\u6DD7\u6DCD\u6DE3\u6DBB\u70FA\u710D\u70F7\u7117\u70F4\u710C\u70F0\u7104\u70F3\u7110\u70FC\u70FF\u7106\u7113\u7100\u70F8\u70F6\u710B\u7102\u710E\u727E\u727B\u727C\u727F\u731D\u7317\u7307\u7311\u7318\u730A\u7308\u72FF\u730F\u731E\u7388\u73F6\u73F8\u73F5\u7404\u7401\u73FD\u7407\u7400\u73FA\u73FC\u73FF\u740C\u740B\u73F4\u7408\u7564\u7563\u75CE\u75D2\u75CF"], - ["d6a1", "\u75CB\u75CC\u75D1\u75D0\u768F\u7689\u76D3\u7739\u772F\u772D\u7731\u7732\u7734\u7733\u773D\u7725\u773B\u7735\u7848\u7852\u7849\u784D\u784A\u784C\u7826\u7845\u7850\u7964\u7967\u7969\u796A\u7963\u796B\u7961\u79BB\u79FA\u79F8\u79F6\u79F7\u7A8F\u7A94\u7A90\u7B35\u7B47\u7B34\u7B25\u7B30\u7B22\u7B24\u7B33\u7B18\u7B2A\u7B1D\u7B31\u7B2B\u7B2D\u7B2F\u7B32\u7B38\u7B1A\u7B23\u7C94\u7C98\u7C96\u7CA3\u7D35\u7D3D\u7D38\u7D36\u7D3A\u7D45\u7D2C\u7D29\u7D41\u7D47\u7D3E\u7D3F\u7D4A\u7D3B\u7D28\u7F63\u7F95\u7F9C\u7F9D\u7F9B\u7FCA\u7FCB\u7FCD\u7FD0\u7FD1\u7FC7\u7FCF\u7FC9\u801F"], - ["d740", "\u801E\u801B\u8047\u8043\u8048\u8118\u8125\u8119\u811B\u812D\u811F\u812C\u811E\u8121\u8115\u8127\u811D\u8122\u8211\u8238\u8233\u823A\u8234\u8232\u8274\u8390\u83A3\u83A8\u838D\u837A\u8373\u83A4\u8374\u838F\u8381\u8395\u8399\u8375\u8394\u83A9\u837D\u8383\u838C\u839D\u839B\u83AA\u838B\u837E\u83A5\u83AF\u8388\u8397\u83B0\u837F\u83A6\u8387\u83AE\u8376\u839A\u8659\u8656\u86BF\u86B7"], - ["d7a1", "\u86C2\u86C1\u86C5\u86BA\u86B0\u86C8\u86B9\u86B3\u86B8\u86CC\u86B4\u86BB\u86BC\u86C3\u86BD\u86BE\u8852\u8889\u8895\u88A8\u88A2\u88AA\u889A\u8891\u88A1\u889F\u8898\u88A7\u8899\u889B\u8897\u88A4\u88AC\u888C\u8893\u888E\u8982\u89D6\u89D9\u89D5\u8A30\u8A27\u8A2C\u8A1E\u8C39\u8C3B\u8C5C\u8C5D\u8C7D\u8CA5\u8D7D\u8D7B\u8D79\u8DBC\u8DC2\u8DB9\u8DBF\u8DC1\u8ED8\u8EDE\u8EDD\u8EDC\u8ED7\u8EE0\u8EE1\u9024\u900B\u9011\u901C\u900C\u9021\u90EF\u90EA\u90F0\u90F4\u90F2\u90F3\u90D4\u90EB\u90EC\u90E9\u9156\u9158\u915A\u9153\u9155\u91EC\u91F4\u91F1\u91F3\u91F8\u91E4\u91F9\u91EA"], - ["d840", "\u91EB\u91F7\u91E8\u91EE\u957A\u9586\u9588\u967C\u966D\u966B\u9671\u966F\u96BF\u976A\u9804\u98E5\u9997\u509B\u5095\u5094\u509E\u508B\u50A3\u5083\u508C\u508E\u509D\u5068\u509C\u5092\u5082\u5087\u515F\u51D4\u5312\u5311\u53A4\u53A7\u5591\u55A8\u55A5\u55AD\u5577\u5645\u55A2\u5593\u5588\u558F\u55B5\u5581\u55A3\u5592\u55A4\u557D\u558C\u55A6\u557F\u5595\u55A1\u558E\u570C\u5829\u5837"], - ["d8a1", "\u5819\u581E\u5827\u5823\u5828\u57F5\u5848\u5825\u581C\u581B\u5833\u583F\u5836\u582E\u5839\u5838\u582D\u582C\u583B\u5961\u5AAF\u5A94\u5A9F\u5A7A\u5AA2\u5A9E\u5A78\u5AA6\u5A7C\u5AA5\u5AAC\u5A95\u5AAE\u5A37\u5A84\u5A8A\u5A97\u5A83\u5A8B\u5AA9\u5A7B\u5A7D\u5A8C\u5A9C\u5A8F\u5A93\u5A9D\u5BEA\u5BCD\u5BCB\u5BD4\u5BD1\u5BCA\u5BCE\u5C0C\u5C30\u5D37\u5D43\u5D6B\u5D41\u5D4B\u5D3F\u5D35\u5D51\u5D4E\u5D55\u5D33\u5D3A\u5D52\u5D3D\u5D31\u5D59\u5D42\u5D39\u5D49\u5D38\u5D3C\u5D32\u5D36\u5D40\u5D45\u5E44\u5E41\u5F58\u5FA6\u5FA5\u5FAB\u60C9\u60B9\u60CC\u60E2\u60CE\u60C4\u6114"], - ["d940", "\u60F2\u610A\u6116\u6105\u60F5\u6113\u60F8\u60FC\u60FE\u60C1\u6103\u6118\u611D\u6110\u60FF\u6104\u610B\u624A\u6394\u63B1\u63B0\u63CE\u63E5\u63E8\u63EF\u63C3\u649D\u63F3\u63CA\u63E0\u63F6\u63D5\u63F2\u63F5\u6461\u63DF\u63BE\u63DD\u63DC\u63C4\u63D8\u63D3\u63C2\u63C7\u63CC\u63CB\u63C8\u63F0\u63D7\u63D9\u6532\u6567\u656A\u6564\u655C\u6568\u6565\u658C\u659D\u659E\u65AE\u65D0\u65D2"], - ["d9a1", "\u667C\u666C\u667B\u6680\u6671\u6679\u666A\u6672\u6701\u690C\u68D3\u6904\u68DC\u692A\u68EC\u68EA\u68F1\u690F\u68D6\u68F7\u68EB\u68E4\u68F6\u6913\u6910\u68F3\u68E1\u6907\u68CC\u6908\u6970\u68B4\u6911\u68EF\u68C6\u6914\u68F8\u68D0\u68FD\u68FC\u68E8\u690B\u690A\u6917\u68CE\u68C8\u68DD\u68DE\u68E6\u68F4\u68D1\u6906\u68D4\u68E9\u6915\u6925\u68C7\u6B39\u6B3B\u6B3F\u6B3C\u6B94\u6B97\u6B99\u6B95\u6BBD\u6BF0\u6BF2\u6BF3\u6C30\u6DFC\u6E46\u6E47\u6E1F\u6E49\u6E88\u6E3C\u6E3D\u6E45\u6E62\u6E2B\u6E3F\u6E41\u6E5D\u6E73\u6E1C\u6E33\u6E4B\u6E40\u6E51\u6E3B\u6E03\u6E2E\u6E5E"], - ["da40", "\u6E68\u6E5C\u6E61\u6E31\u6E28\u6E60\u6E71\u6E6B\u6E39\u6E22\u6E30\u6E53\u6E65\u6E27\u6E78\u6E64\u6E77\u6E55\u6E79\u6E52\u6E66\u6E35\u6E36\u6E5A\u7120\u711E\u712F\u70FB\u712E\u7131\u7123\u7125\u7122\u7132\u711F\u7128\u713A\u711B\u724B\u725A\u7288\u7289\u7286\u7285\u728B\u7312\u730B\u7330\u7322\u7331\u7333\u7327\u7332\u732D\u7326\u7323\u7335\u730C\u742E\u742C\u7430\u742B\u7416"], - ["daa1", "\u741A\u7421\u742D\u7431\u7424\u7423\u741D\u7429\u7420\u7432\u74FB\u752F\u756F\u756C\u75E7\u75DA\u75E1\u75E6\u75DD\u75DF\u75E4\u75D7\u7695\u7692\u76DA\u7746\u7747\u7744\u774D\u7745\u774A\u774E\u774B\u774C\u77DE\u77EC\u7860\u7864\u7865\u785C\u786D\u7871\u786A\u786E\u7870\u7869\u7868\u785E\u7862\u7974\u7973\u7972\u7970\u7A02\u7A0A\u7A03\u7A0C\u7A04\u7A99\u7AE6\u7AE4\u7B4A\u7B3B\u7B44\u7B48\u7B4C\u7B4E\u7B40\u7B58\u7B45\u7CA2\u7C9E\u7CA8\u7CA1\u7D58\u7D6F\u7D63\u7D53\u7D56\u7D67\u7D6A\u7D4F\u7D6D\u7D5C\u7D6B\u7D52\u7D54\u7D69\u7D51\u7D5F\u7D4E\u7F3E\u7F3F\u7F65"], - ["db40", "\u7F66\u7FA2\u7FA0\u7FA1\u7FD7\u8051\u804F\u8050\u80FE\u80D4\u8143\u814A\u8152\u814F\u8147\u813D\u814D\u813A\u81E6\u81EE\u81F7\u81F8\u81F9\u8204\u823C\u823D\u823F\u8275\u833B\u83CF\u83F9\u8423\u83C0\u83E8\u8412\u83E7\u83E4\u83FC\u83F6\u8410\u83C6\u83C8\u83EB\u83E3\u83BF\u8401\u83DD\u83E5\u83D8\u83FF\u83E1\u83CB\u83CE\u83D6\u83F5\u83C9\u8409\u840F\u83DE\u8411\u8406\u83C2\u83F3"], - ["dba1", "\u83D5\u83FA\u83C7\u83D1\u83EA\u8413\u83C3\u83EC\u83EE\u83C4\u83FB\u83D7\u83E2\u841B\u83DB\u83FE\u86D8\u86E2\u86E6\u86D3\u86E3\u86DA\u86EA\u86DD\u86EB\u86DC\u86EC\u86E9\u86D7\u86E8\u86D1\u8848\u8856\u8855\u88BA\u88D7\u88B9\u88B8\u88C0\u88BE\u88B6\u88BC\u88B7\u88BD\u88B2\u8901\u88C9\u8995\u8998\u8997\u89DD\u89DA\u89DB\u8A4E\u8A4D\u8A39\u8A59\u8A40\u8A57\u8A58\u8A44\u8A45\u8A52\u8A48\u8A51\u8A4A\u8A4C\u8A4F\u8C5F\u8C81\u8C80\u8CBA\u8CBE\u8CB0\u8CB9\u8CB5\u8D84\u8D80\u8D89\u8DD8\u8DD3\u8DCD\u8DC7\u8DD6\u8DDC\u8DCF\u8DD5\u8DD9\u8DC8\u8DD7\u8DC5\u8EEF\u8EF7\u8EFA"], - ["dc40", "\u8EF9\u8EE6\u8EEE\u8EE5\u8EF5\u8EE7\u8EE8\u8EF6\u8EEB\u8EF1\u8EEC\u8EF4\u8EE9\u902D\u9034\u902F\u9106\u912C\u9104\u90FF\u90FC\u9108\u90F9\u90FB\u9101\u9100\u9107\u9105\u9103\u9161\u9164\u915F\u9162\u9160\u9201\u920A\u9225\u9203\u921A\u9226\u920F\u920C\u9200\u9212\u91FF\u91FD\u9206\u9204\u9227\u9202\u921C\u9224\u9219\u9217\u9205\u9216\u957B\u958D\u958C\u9590\u9687\u967E\u9688"], - ["dca1", "\u9689\u9683\u9680\u96C2\u96C8\u96C3\u96F1\u96F0\u976C\u9770\u976E\u9807\u98A9\u98EB\u9CE6\u9EF9\u4E83\u4E84\u4EB6\u50BD\u50BF\u50C6\u50AE\u50C4\u50CA\u50B4\u50C8\u50C2\u50B0\u50C1\u50BA\u50B1\u50CB\u50C9\u50B6\u50B8\u51D7\u527A\u5278\u527B\u527C\u55C3\u55DB\u55CC\u55D0\u55CB\u55CA\u55DD\u55C0\u55D4\u55C4\u55E9\u55BF\u55D2\u558D\u55CF\u55D5\u55E2\u55D6\u55C8\u55F2\u55CD\u55D9\u55C2\u5714\u5853\u5868\u5864\u584F\u584D\u5849\u586F\u5855\u584E\u585D\u5859\u5865\u585B\u583D\u5863\u5871\u58FC\u5AC7\u5AC4\u5ACB\u5ABA\u5AB8\u5AB1\u5AB5\u5AB0\u5ABF\u5AC8\u5ABB\u5AC6"], - ["dd40", "\u5AB7\u5AC0\u5ACA\u5AB4\u5AB6\u5ACD\u5AB9\u5A90\u5BD6\u5BD8\u5BD9\u5C1F\u5C33\u5D71\u5D63\u5D4A\u5D65\u5D72\u5D6C\u5D5E\u5D68\u5D67\u5D62\u5DF0\u5E4F\u5E4E\u5E4A\u5E4D\u5E4B\u5EC5\u5ECC\u5EC6\u5ECB\u5EC7\u5F40\u5FAF\u5FAD\u60F7\u6149\u614A\u612B\u6145\u6136\u6132\u612E\u6146\u612F\u614F\u6129\u6140\u6220\u9168\u6223\u6225\u6224\u63C5\u63F1\u63EB\u6410\u6412\u6409\u6420\u6424"], - ["dda1", "\u6433\u6443\u641F\u6415\u6418\u6439\u6437\u6422\u6423\u640C\u6426\u6430\u6428\u6441\u6435\u642F\u640A\u641A\u6440\u6425\u6427\u640B\u63E7\u641B\u642E\u6421\u640E\u656F\u6592\u65D3\u6686\u668C\u6695\u6690\u668B\u668A\u6699\u6694\u6678\u6720\u6966\u695F\u6938\u694E\u6962\u6971\u693F\u6945\u696A\u6939\u6942\u6957\u6959\u697A\u6948\u6949\u6935\u696C\u6933\u693D\u6965\u68F0\u6978\u6934\u6969\u6940\u696F\u6944\u6976\u6958\u6941\u6974\u694C\u693B\u694B\u6937\u695C\u694F\u6951\u6932\u6952\u692F\u697B\u693C\u6B46\u6B45\u6B43\u6B42\u6B48\u6B41\u6B9B\uFA0D\u6BFB\u6BFC"], - ["de40", "\u6BF9\u6BF7\u6BF8\u6E9B\u6ED6\u6EC8\u6E8F\u6EC0\u6E9F\u6E93\u6E94\u6EA0\u6EB1\u6EB9\u6EC6\u6ED2\u6EBD\u6EC1\u6E9E\u6EC9\u6EB7\u6EB0\u6ECD\u6EA6\u6ECF\u6EB2\u6EBE\u6EC3\u6EDC\u6ED8\u6E99\u6E92\u6E8E\u6E8D\u6EA4\u6EA1\u6EBF\u6EB3\u6ED0\u6ECA\u6E97\u6EAE\u6EA3\u7147\u7154\u7152\u7163\u7160\u7141\u715D\u7162\u7172\u7178\u716A\u7161\u7142\u7158\u7143\u714B\u7170\u715F\u7150\u7153"], - ["dea1", "\u7144\u714D\u715A\u724F\u728D\u728C\u7291\u7290\u728E\u733C\u7342\u733B\u733A\u7340\u734A\u7349\u7444\u744A\u744B\u7452\u7451\u7457\u7440\u744F\u7450\u744E\u7442\u7446\u744D\u7454\u74E1\u74FF\u74FE\u74FD\u751D\u7579\u7577\u6983\u75EF\u760F\u7603\u75F7\u75FE\u75FC\u75F9\u75F8\u7610\u75FB\u75F6\u75ED\u75F5\u75FD\u7699\u76B5\u76DD\u7755\u775F\u7760\u7752\u7756\u775A\u7769\u7767\u7754\u7759\u776D\u77E0\u7887\u789A\u7894\u788F\u7884\u7895\u7885\u7886\u78A1\u7883\u7879\u7899\u7880\u7896\u787B\u797C\u7982\u797D\u7979\u7A11\u7A18\u7A19\u7A12\u7A17\u7A15\u7A22\u7A13"], - ["df40", "\u7A1B\u7A10\u7AA3\u7AA2\u7A9E\u7AEB\u7B66\u7B64\u7B6D\u7B74\u7B69\u7B72\u7B65\u7B73\u7B71\u7B70\u7B61\u7B78\u7B76\u7B63\u7CB2\u7CB4\u7CAF\u7D88\u7D86\u7D80\u7D8D\u7D7F\u7D85\u7D7A\u7D8E\u7D7B\u7D83\u7D7C\u7D8C\u7D94\u7D84\u7D7D\u7D92\u7F6D\u7F6B\u7F67\u7F68\u7F6C\u7FA6\u7FA5\u7FA7\u7FDB\u7FDC\u8021\u8164\u8160\u8177\u815C\u8169\u815B\u8162\u8172\u6721\u815E\u8176\u8167\u816F"], - ["dfa1", "\u8144\u8161\u821D\u8249\u8244\u8240\u8242\u8245\u84F1\u843F\u8456\u8476\u8479\u848F\u848D\u8465\u8451\u8440\u8486\u8467\u8430\u844D\u847D\u845A\u8459\u8474\u8473\u845D\u8507\u845E\u8437\u843A\u8434\u847A\u8443\u8478\u8432\u8445\u8429\u83D9\u844B\u842F\u8442\u842D\u845F\u8470\u8439\u844E\u844C\u8452\u846F\u84C5\u848E\u843B\u8447\u8436\u8433\u8468\u847E\u8444\u842B\u8460\u8454\u846E\u8450\u870B\u8704\u86F7\u870C\u86FA\u86D6\u86F5\u874D\u86F8\u870E\u8709\u8701\u86F6\u870D\u8705\u88D6\u88CB\u88CD\u88CE\u88DE\u88DB\u88DA\u88CC\u88D0\u8985\u899B\u89DF\u89E5\u89E4"], - ["e040", "\u89E1\u89E0\u89E2\u89DC\u89E6\u8A76\u8A86\u8A7F\u8A61\u8A3F\u8A77\u8A82\u8A84\u8A75\u8A83\u8A81\u8A74\u8A7A\u8C3C\u8C4B\u8C4A\u8C65\u8C64\u8C66\u8C86\u8C84\u8C85\u8CCC\u8D68\u8D69\u8D91\u8D8C\u8D8E\u8D8F\u8D8D\u8D93\u8D94\u8D90\u8D92\u8DF0\u8DE0\u8DEC\u8DF1\u8DEE\u8DD0\u8DE9\u8DE3\u8DE2\u8DE7\u8DF2\u8DEB\u8DF4\u8F06\u8EFF\u8F01\u8F00\u8F05\u8F07\u8F08\u8F02\u8F0B\u9052\u903F"], - ["e0a1", "\u9044\u9049\u903D\u9110\u910D\u910F\u9111\u9116\u9114\u910B\u910E\u916E\u916F\u9248\u9252\u9230\u923A\u9266\u9233\u9265\u925E\u9283\u922E\u924A\u9246\u926D\u926C\u924F\u9260\u9267\u926F\u9236\u9261\u9270\u9231\u9254\u9263\u9250\u9272\u924E\u9253\u924C\u9256\u9232\u959F\u959C\u959E\u959B\u9692\u9693\u9691\u9697\u96CE\u96FA\u96FD\u96F8\u96F5\u9773\u9777\u9778\u9772\u980F\u980D\u980E\u98AC\u98F6\u98F9\u99AF\u99B2\u99B0\u99B5\u9AAD\u9AAB\u9B5B\u9CEA\u9CED\u9CE7\u9E80\u9EFD\u50E6\u50D4\u50D7\u50E8\u50F3\u50DB\u50EA\u50DD\u50E4\u50D3\u50EC\u50F0\u50EF\u50E3\u50E0"], - ["e140", "\u51D8\u5280\u5281\u52E9\u52EB\u5330\u53AC\u5627\u5615\u560C\u5612\u55FC\u560F\u561C\u5601\u5613\u5602\u55FA\u561D\u5604\u55FF\u55F9\u5889\u587C\u5890\u5898\u5886\u5881\u587F\u5874\u588B\u587A\u5887\u5891\u588E\u5876\u5882\u5888\u587B\u5894\u588F\u58FE\u596B\u5ADC\u5AEE\u5AE5\u5AD5\u5AEA\u5ADA\u5AED\u5AEB\u5AF3\u5AE2\u5AE0\u5ADB\u5AEC\u5ADE\u5ADD\u5AD9\u5AE8\u5ADF\u5B77\u5BE0"], - ["e1a1", "\u5BE3\u5C63\u5D82\u5D80\u5D7D\u5D86\u5D7A\u5D81\u5D77\u5D8A\u5D89\u5D88\u5D7E\u5D7C\u5D8D\u5D79\u5D7F\u5E58\u5E59\u5E53\u5ED8\u5ED1\u5ED7\u5ECE\u5EDC\u5ED5\u5ED9\u5ED2\u5ED4\u5F44\u5F43\u5F6F\u5FB6\u612C\u6128\u6141\u615E\u6171\u6173\u6152\u6153\u6172\u616C\u6180\u6174\u6154\u617A\u615B\u6165\u613B\u616A\u6161\u6156\u6229\u6227\u622B\u642B\u644D\u645B\u645D\u6474\u6476\u6472\u6473\u647D\u6475\u6466\u64A6\u644E\u6482\u645E\u645C\u644B\u6453\u6460\u6450\u647F\u643F\u646C\u646B\u6459\u6465\u6477\u6573\u65A0\u66A1\u66A0\u669F\u6705\u6704\u6722\u69B1\u69B6\u69C9"], - ["e240", "\u69A0\u69CE\u6996\u69B0\u69AC\u69BC\u6991\u6999\u698E\u69A7\u698D\u69A9\u69BE\u69AF\u69BF\u69C4\u69BD\u69A4\u69D4\u69B9\u69CA\u699A\u69CF\u69B3\u6993\u69AA\u69A1\u699E\u69D9\u6997\u6990\u69C2\u69B5\u69A5\u69C6\u6B4A\u6B4D\u6B4B\u6B9E\u6B9F\u6BA0\u6BC3\u6BC4\u6BFE\u6ECE\u6EF5\u6EF1\u6F03\u6F25\u6EF8\u6F37\u6EFB\u6F2E\u6F09\u6F4E\u6F19\u6F1A\u6F27\u6F18\u6F3B\u6F12\u6EED\u6F0A"], - ["e2a1", "\u6F36\u6F73\u6EF9\u6EEE\u6F2D\u6F40\u6F30\u6F3C\u6F35\u6EEB\u6F07\u6F0E\u6F43\u6F05\u6EFD\u6EF6\u6F39\u6F1C\u6EFC\u6F3A\u6F1F\u6F0D\u6F1E\u6F08\u6F21\u7187\u7190\u7189\u7180\u7185\u7182\u718F\u717B\u7186\u7181\u7197\u7244\u7253\u7297\u7295\u7293\u7343\u734D\u7351\u734C\u7462\u7473\u7471\u7475\u7472\u7467\u746E\u7500\u7502\u7503\u757D\u7590\u7616\u7608\u760C\u7615\u7611\u760A\u7614\u76B8\u7781\u777C\u7785\u7782\u776E\u7780\u776F\u777E\u7783\u78B2\u78AA\u78B4\u78AD\u78A8\u787E\u78AB\u789E\u78A5\u78A0\u78AC\u78A2\u78A4\u7998\u798A\u798B\u7996\u7995\u7994\u7993"], - ["e340", "\u7997\u7988\u7992\u7990\u7A2B\u7A4A\u7A30\u7A2F\u7A28\u7A26\u7AA8\u7AAB\u7AAC\u7AEE\u7B88\u7B9C\u7B8A\u7B91\u7B90\u7B96\u7B8D\u7B8C\u7B9B\u7B8E\u7B85\u7B98\u5284\u7B99\u7BA4\u7B82\u7CBB\u7CBF\u7CBC\u7CBA\u7DA7\u7DB7\u7DC2\u7DA3\u7DAA\u7DC1\u7DC0\u7DC5\u7D9D\u7DCE\u7DC4\u7DC6\u7DCB\u7DCC\u7DAF\u7DB9\u7D96\u7DBC\u7D9F\u7DA6\u7DAE\u7DA9\u7DA1\u7DC9\u7F73\u7FE2\u7FE3\u7FE5\u7FDE"], - ["e3a1", "\u8024\u805D\u805C\u8189\u8186\u8183\u8187\u818D\u818C\u818B\u8215\u8497\u84A4\u84A1\u849F\u84BA\u84CE\u84C2\u84AC\u84AE\u84AB\u84B9\u84B4\u84C1\u84CD\u84AA\u849A\u84B1\u84D0\u849D\u84A7\u84BB\u84A2\u8494\u84C7\u84CC\u849B\u84A9\u84AF\u84A8\u84D6\u8498\u84B6\u84CF\u84A0\u84D7\u84D4\u84D2\u84DB\u84B0\u8491\u8661\u8733\u8723\u8728\u876B\u8740\u872E\u871E\u8721\u8719\u871B\u8743\u872C\u8741\u873E\u8746\u8720\u8732\u872A\u872D\u873C\u8712\u873A\u8731\u8735\u8742\u8726\u8727\u8738\u8724\u871A\u8730\u8711\u88F7\u88E7\u88F1\u88F2\u88FA\u88FE\u88EE\u88FC\u88F6\u88FB"], - ["e440", "\u88F0\u88EC\u88EB\u899D\u89A1\u899F\u899E\u89E9\u89EB\u89E8\u8AAB\u8A99\u8A8B\u8A92\u8A8F\u8A96\u8C3D\u8C68\u8C69\u8CD5\u8CCF\u8CD7\u8D96\u8E09\u8E02\u8DFF\u8E0D\u8DFD\u8E0A\u8E03\u8E07\u8E06\u8E05\u8DFE\u8E00\u8E04\u8F10\u8F11\u8F0E\u8F0D\u9123\u911C\u9120\u9122\u911F\u911D\u911A\u9124\u9121\u911B\u917A\u9172\u9179\u9173\u92A5\u92A4\u9276\u929B\u927A\u92A0\u9294\u92AA\u928D"], - ["e4a1", "\u92A6\u929A\u92AB\u9279\u9297\u927F\u92A3\u92EE\u928E\u9282\u9295\u92A2\u927D\u9288\u92A1\u928A\u9286\u928C\u9299\u92A7\u927E\u9287\u92A9\u929D\u928B\u922D\u969E\u96A1\u96FF\u9758\u977D\u977A\u977E\u9783\u9780\u9782\u977B\u9784\u9781\u977F\u97CE\u97CD\u9816\u98AD\u98AE\u9902\u9900\u9907\u999D\u999C\u99C3\u99B9\u99BB\u99BA\u99C2\u99BD\u99C7\u9AB1\u9AE3\u9AE7\u9B3E\u9B3F\u9B60\u9B61\u9B5F\u9CF1\u9CF2\u9CF5\u9EA7\u50FF\u5103\u5130\u50F8\u5106\u5107\u50F6\u50FE\u510B\u510C\u50FD\u510A\u528B\u528C\u52F1\u52EF\u5648\u5642\u564C\u5635\u5641\u564A\u5649\u5646\u5658"], - ["e540", "\u565A\u5640\u5633\u563D\u562C\u563E\u5638\u562A\u563A\u571A\u58AB\u589D\u58B1\u58A0\u58A3\u58AF\u58AC\u58A5\u58A1\u58FF\u5AFF\u5AF4\u5AFD\u5AF7\u5AF6\u5B03\u5AF8\u5B02\u5AF9\u5B01\u5B07\u5B05\u5B0F\u5C67\u5D99\u5D97\u5D9F\u5D92\u5DA2\u5D93\u5D95\u5DA0\u5D9C\u5DA1\u5D9A\u5D9E\u5E69\u5E5D\u5E60\u5E5C\u7DF3\u5EDB\u5EDE\u5EE1\u5F49\u5FB2\u618B\u6183\u6179\u61B1\u61B0\u61A2\u6189"], - ["e5a1", "\u619B\u6193\u61AF\u61AD\u619F\u6192\u61AA\u61A1\u618D\u6166\u61B3\u622D\u646E\u6470\u6496\u64A0\u6485\u6497\u649C\u648F\u648B\u648A\u648C\u64A3\u649F\u6468\u64B1\u6498\u6576\u657A\u6579\u657B\u65B2\u65B3\u66B5\u66B0\u66A9\u66B2\u66B7\u66AA\u66AF\u6A00\u6A06\u6A17\u69E5\u69F8\u6A15\u69F1\u69E4\u6A20\u69FF\u69EC\u69E2\u6A1B\u6A1D\u69FE\u6A27\u69F2\u69EE\u6A14\u69F7\u69E7\u6A40\u6A08\u69E6\u69FB\u6A0D\u69FC\u69EB\u6A09\u6A04\u6A18\u6A25\u6A0F\u69F6\u6A26\u6A07\u69F4\u6A16\u6B51\u6BA5\u6BA3\u6BA2\u6BA6\u6C01\u6C00\u6BFF\u6C02\u6F41\u6F26\u6F7E\u6F87\u6FC6\u6F92"], - ["e640", "\u6F8D\u6F89\u6F8C\u6F62\u6F4F\u6F85\u6F5A\u6F96\u6F76\u6F6C\u6F82\u6F55\u6F72\u6F52\u6F50\u6F57\u6F94\u6F93\u6F5D\u6F00\u6F61\u6F6B\u6F7D\u6F67\u6F90\u6F53\u6F8B\u6F69\u6F7F\u6F95\u6F63\u6F77\u6F6A\u6F7B\u71B2\u71AF\u719B\u71B0\u71A0\u719A\u71A9\u71B5\u719D\u71A5\u719E\u71A4\u71A1\u71AA\u719C\u71A7\u71B3\u7298\u729A\u7358\u7352\u735E\u735F\u7360\u735D\u735B\u7361\u735A\u7359"], - ["e6a1", "\u7362\u7487\u7489\u748A\u7486\u7481\u747D\u7485\u7488\u747C\u7479\u7508\u7507\u757E\u7625\u761E\u7619\u761D\u761C\u7623\u761A\u7628\u761B\u769C\u769D\u769E\u769B\u778D\u778F\u7789\u7788\u78CD\u78BB\u78CF\u78CC\u78D1\u78CE\u78D4\u78C8\u78C3\u78C4\u78C9\u799A\u79A1\u79A0\u799C\u79A2\u799B\u6B76\u7A39\u7AB2\u7AB4\u7AB3\u7BB7\u7BCB\u7BBE\u7BAC\u7BCE\u7BAF\u7BB9\u7BCA\u7BB5\u7CC5\u7CC8\u7CCC\u7CCB\u7DF7\u7DDB\u7DEA\u7DE7\u7DD7\u7DE1\u7E03\u7DFA\u7DE6\u7DF6\u7DF1\u7DF0\u7DEE\u7DDF\u7F76\u7FAC\u7FB0\u7FAD\u7FED\u7FEB\u7FEA\u7FEC\u7FE6\u7FE8\u8064\u8067\u81A3\u819F"], - ["e740", "\u819E\u8195\u81A2\u8199\u8197\u8216\u824F\u8253\u8252\u8250\u824E\u8251\u8524\u853B\u850F\u8500\u8529\u850E\u8509\u850D\u851F\u850A\u8527\u851C\u84FB\u852B\u84FA\u8508\u850C\u84F4\u852A\u84F2\u8515\u84F7\u84EB\u84F3\u84FC\u8512\u84EA\u84E9\u8516\u84FE\u8528\u851D\u852E\u8502\u84FD\u851E\u84F6\u8531\u8526\u84E7\u84E8\u84F0\u84EF\u84F9\u8518\u8520\u8530\u850B\u8519\u852F\u8662"], - ["e7a1", "\u8756\u8763\u8764\u8777\u87E1\u8773\u8758\u8754\u875B\u8752\u8761\u875A\u8751\u875E\u876D\u876A\u8750\u874E\u875F\u875D\u876F\u876C\u877A\u876E\u875C\u8765\u874F\u877B\u8775\u8762\u8767\u8769\u885A\u8905\u890C\u8914\u890B\u8917\u8918\u8919\u8906\u8916\u8911\u890E\u8909\u89A2\u89A4\u89A3\u89ED\u89F0\u89EC\u8ACF\u8AC6\u8AB8\u8AD3\u8AD1\u8AD4\u8AD5\u8ABB\u8AD7\u8ABE\u8AC0\u8AC5\u8AD8\u8AC3\u8ABA\u8ABD\u8AD9\u8C3E\u8C4D\u8C8F\u8CE5\u8CDF\u8CD9\u8CE8\u8CDA\u8CDD\u8CE7\u8DA0\u8D9C\u8DA1\u8D9B\u8E20\u8E23\u8E25\u8E24\u8E2E\u8E15\u8E1B\u8E16\u8E11\u8E19\u8E26\u8E27"], - ["e840", "\u8E14\u8E12\u8E18\u8E13\u8E1C\u8E17\u8E1A\u8F2C\u8F24\u8F18\u8F1A\u8F20\u8F23\u8F16\u8F17\u9073\u9070\u906F\u9067\u906B\u912F\u912B\u9129\u912A\u9132\u9126\u912E\u9185\u9186\u918A\u9181\u9182\u9184\u9180\u92D0\u92C3\u92C4\u92C0\u92D9\u92B6\u92CF\u92F1\u92DF\u92D8\u92E9\u92D7\u92DD\u92CC\u92EF\u92C2\u92E8\u92CA\u92C8\u92CE\u92E6\u92CD\u92D5\u92C9\u92E0\u92DE\u92E7\u92D1\u92D3"], - ["e8a1", "\u92B5\u92E1\u92C6\u92B4\u957C\u95AC\u95AB\u95AE\u95B0\u96A4\u96A2\u96D3\u9705\u9708\u9702\u975A\u978A\u978E\u9788\u97D0\u97CF\u981E\u981D\u9826\u9829\u9828\u9820\u981B\u9827\u98B2\u9908\u98FA\u9911\u9914\u9916\u9917\u9915\u99DC\u99CD\u99CF\u99D3\u99D4\u99CE\u99C9\u99D6\u99D8\u99CB\u99D7\u99CC\u9AB3\u9AEC\u9AEB\u9AF3\u9AF2\u9AF1\u9B46\u9B43\u9B67\u9B74\u9B71\u9B66\u9B76\u9B75\u9B70\u9B68\u9B64\u9B6C\u9CFC\u9CFA\u9CFD\u9CFF\u9CF7\u9D07\u9D00\u9CF9\u9CFB\u9D08\u9D05\u9D04\u9E83\u9ED3\u9F0F\u9F10\u511C\u5113\u5117\u511A\u5111\u51DE\u5334\u53E1\u5670\u5660\u566E"], - ["e940", "\u5673\u5666\u5663\u566D\u5672\u565E\u5677\u571C\u571B\u58C8\u58BD\u58C9\u58BF\u58BA\u58C2\u58BC\u58C6\u5B17\u5B19\u5B1B\u5B21\u5B14\u5B13\u5B10\u5B16\u5B28\u5B1A\u5B20\u5B1E\u5BEF\u5DAC\u5DB1\u5DA9\u5DA7\u5DB5\u5DB0\u5DAE\u5DAA\u5DA8\u5DB2\u5DAD\u5DAF\u5DB4\u5E67\u5E68\u5E66\u5E6F\u5EE9\u5EE7\u5EE6\u5EE8\u5EE5\u5F4B\u5FBC\u619D\u61A8\u6196\u61C5\u61B4\u61C6\u61C1\u61CC\u61BA"], - ["e9a1", "\u61BF\u61B8\u618C\u64D7\u64D6\u64D0\u64CF\u64C9\u64BD\u6489\u64C3\u64DB\u64F3\u64D9\u6533\u657F\u657C\u65A2\u66C8\u66BE\u66C0\u66CA\u66CB\u66CF\u66BD\u66BB\u66BA\u66CC\u6723\u6A34\u6A66\u6A49\u6A67\u6A32\u6A68\u6A3E\u6A5D\u6A6D\u6A76\u6A5B\u6A51\u6A28\u6A5A\u6A3B\u6A3F\u6A41\u6A6A\u6A64\u6A50\u6A4F\u6A54\u6A6F\u6A69\u6A60\u6A3C\u6A5E\u6A56\u6A55\u6A4D\u6A4E\u6A46\u6B55\u6B54\u6B56\u6BA7\u6BAA\u6BAB\u6BC8\u6BC7\u6C04\u6C03\u6C06\u6FAD\u6FCB\u6FA3\u6FC7\u6FBC\u6FCE\u6FC8\u6F5E\u6FC4\u6FBD\u6F9E\u6FCA\u6FA8\u7004\u6FA5\u6FAE\u6FBA\u6FAC\u6FAA\u6FCF\u6FBF\u6FB8"], - ["ea40", "\u6FA2\u6FC9\u6FAB\u6FCD\u6FAF\u6FB2\u6FB0\u71C5\u71C2\u71BF\u71B8\u71D6\u71C0\u71C1\u71CB\u71D4\u71CA\u71C7\u71CF\u71BD\u71D8\u71BC\u71C6\u71DA\u71DB\u729D\u729E\u7369\u7366\u7367\u736C\u7365\u736B\u736A\u747F\u749A\u74A0\u7494\u7492\u7495\u74A1\u750B\u7580\u762F\u762D\u7631\u763D\u7633\u763C\u7635\u7632\u7630\u76BB\u76E6\u779A\u779D\u77A1\u779C\u779B\u77A2\u77A3\u7795\u7799"], - ["eaa1", "\u7797\u78DD\u78E9\u78E5\u78EA\u78DE\u78E3\u78DB\u78E1\u78E2\u78ED\u78DF\u78E0\u79A4\u7A44\u7A48\u7A47\u7AB6\u7AB8\u7AB5\u7AB1\u7AB7\u7BDE\u7BE3\u7BE7\u7BDD\u7BD5\u7BE5\u7BDA\u7BE8\u7BF9\u7BD4\u7BEA\u7BE2\u7BDC\u7BEB\u7BD8\u7BDF\u7CD2\u7CD4\u7CD7\u7CD0\u7CD1\u7E12\u7E21\u7E17\u7E0C\u7E1F\u7E20\u7E13\u7E0E\u7E1C\u7E15\u7E1A\u7E22\u7E0B\u7E0F\u7E16\u7E0D\u7E14\u7E25\u7E24\u7F43\u7F7B\u7F7C\u7F7A\u7FB1\u7FEF\u802A\u8029\u806C\u81B1\u81A6\u81AE\u81B9\u81B5\u81AB\u81B0\u81AC\u81B4\u81B2\u81B7\u81A7\u81F2\u8255\u8256\u8257\u8556\u8545\u856B\u854D\u8553\u8561\u8558"], - ["eb40", "\u8540\u8546\u8564\u8541\u8562\u8544\u8551\u8547\u8563\u853E\u855B\u8571\u854E\u856E\u8575\u8555\u8567\u8560\u858C\u8566\u855D\u8554\u8565\u856C\u8663\u8665\u8664\u879B\u878F\u8797\u8793\u8792\u8788\u8781\u8796\u8798\u8779\u8787\u87A3\u8785\u8790\u8791\u879D\u8784\u8794\u879C\u879A\u8789\u891E\u8926\u8930\u892D\u892E\u8927\u8931\u8922\u8929\u8923\u892F\u892C\u891F\u89F1\u8AE0"], - ["eba1", "\u8AE2\u8AF2\u8AF4\u8AF5\u8ADD\u8B14\u8AE4\u8ADF\u8AF0\u8AC8\u8ADE\u8AE1\u8AE8\u8AFF\u8AEF\u8AFB\u8C91\u8C92\u8C90\u8CF5\u8CEE\u8CF1\u8CF0\u8CF3\u8D6C\u8D6E\u8DA5\u8DA7\u8E33\u8E3E\u8E38\u8E40\u8E45\u8E36\u8E3C\u8E3D\u8E41\u8E30\u8E3F\u8EBD\u8F36\u8F2E\u8F35\u8F32\u8F39\u8F37\u8F34\u9076\u9079\u907B\u9086\u90FA\u9133\u9135\u9136\u9193\u9190\u9191\u918D\u918F\u9327\u931E\u9308\u931F\u9306\u930F\u937A\u9338\u933C\u931B\u9323\u9312\u9301\u9346\u932D\u930E\u930D\u92CB\u931D\u92FA\u9325\u9313\u92F9\u92F7\u9334\u9302\u9324\u92FF\u9329\u9339\u9335\u932A\u9314\u930C"], - ["ec40", "\u930B\u92FE\u9309\u9300\u92FB\u9316\u95BC\u95CD\u95BE\u95B9\u95BA\u95B6\u95BF\u95B5\u95BD\u96A9\u96D4\u970B\u9712\u9710\u9799\u9797\u9794\u97F0\u97F8\u9835\u982F\u9832\u9924\u991F\u9927\u9929\u999E\u99EE\u99EC\u99E5\u99E4\u99F0\u99E3\u99EA\u99E9\u99E7\u9AB9\u9ABF\u9AB4\u9ABB\u9AF6\u9AFA\u9AF9\u9AF7\u9B33\u9B80\u9B85\u9B87\u9B7C\u9B7E\u9B7B\u9B82\u9B93\u9B92\u9B90\u9B7A\u9B95"], - ["eca1", "\u9B7D\u9B88\u9D25\u9D17\u9D20\u9D1E\u9D14\u9D29\u9D1D\u9D18\u9D22\u9D10\u9D19\u9D1F\u9E88\u9E86\u9E87\u9EAE\u9EAD\u9ED5\u9ED6\u9EFA\u9F12\u9F3D\u5126\u5125\u5122\u5124\u5120\u5129\u52F4\u5693\u568C\u568D\u5686\u5684\u5683\u567E\u5682\u567F\u5681\u58D6\u58D4\u58CF\u58D2\u5B2D\u5B25\u5B32\u5B23\u5B2C\u5B27\u5B26\u5B2F\u5B2E\u5B7B\u5BF1\u5BF2\u5DB7\u5E6C\u5E6A\u5FBE\u5FBB\u61C3\u61B5\u61BC\u61E7\u61E0\u61E5\u61E4\u61E8\u61DE\u64EF\u64E9\u64E3\u64EB\u64E4\u64E8\u6581\u6580\u65B6\u65DA\u66D2\u6A8D\u6A96\u6A81\u6AA5\u6A89\u6A9F\u6A9B\u6AA1\u6A9E\u6A87\u6A93\u6A8E"], - ["ed40", "\u6A95\u6A83\u6AA8\u6AA4\u6A91\u6A7F\u6AA6\u6A9A\u6A85\u6A8C\u6A92\u6B5B\u6BAD\u6C09\u6FCC\u6FA9\u6FF4\u6FD4\u6FE3\u6FDC\u6FED\u6FE7\u6FE6\u6FDE\u6FF2\u6FDD\u6FE2\u6FE8\u71E1\u71F1\u71E8\u71F2\u71E4\u71F0\u71E2\u7373\u736E\u736F\u7497\u74B2\u74AB\u7490\u74AA\u74AD\u74B1\u74A5\u74AF\u7510\u7511\u7512\u750F\u7584\u7643\u7648\u7649\u7647\u76A4\u76E9\u77B5\u77AB\u77B2\u77B7\u77B6"], - ["eda1", "\u77B4\u77B1\u77A8\u77F0\u78F3\u78FD\u7902\u78FB\u78FC\u78F2\u7905\u78F9\u78FE\u7904\u79AB\u79A8\u7A5C\u7A5B\u7A56\u7A58\u7A54\u7A5A\u7ABE\u7AC0\u7AC1\u7C05\u7C0F\u7BF2\u7C00\u7BFF\u7BFB\u7C0E\u7BF4\u7C0B\u7BF3\u7C02\u7C09\u7C03\u7C01\u7BF8\u7BFD\u7C06\u7BF0\u7BF1\u7C10\u7C0A\u7CE8\u7E2D\u7E3C\u7E42\u7E33\u9848\u7E38\u7E2A\u7E49\u7E40\u7E47\u7E29\u7E4C\u7E30\u7E3B\u7E36\u7E44\u7E3A\u7F45\u7F7F\u7F7E\u7F7D\u7FF4\u7FF2\u802C\u81BB\u81C4\u81CC\u81CA\u81C5\u81C7\u81BC\u81E9\u825B\u825A\u825C\u8583\u8580\u858F\u85A7\u8595\u85A0\u858B\u85A3\u857B\u85A4\u859A\u859E"], - ["ee40", "\u8577\u857C\u8589\u85A1\u857A\u8578\u8557\u858E\u8596\u8586\u858D\u8599\u859D\u8581\u85A2\u8582\u8588\u8585\u8579\u8576\u8598\u8590\u859F\u8668\u87BE\u87AA\u87AD\u87C5\u87B0\u87AC\u87B9\u87B5\u87BC\u87AE\u87C9\u87C3\u87C2\u87CC\u87B7\u87AF\u87C4\u87CA\u87B4\u87B6\u87BF\u87B8\u87BD\u87DE\u87B2\u8935\u8933\u893C\u893E\u8941\u8952\u8937\u8942\u89AD\u89AF\u89AE\u89F2\u89F3\u8B1E"], - ["eea1", "\u8B18\u8B16\u8B11\u8B05\u8B0B\u8B22\u8B0F\u8B12\u8B15\u8B07\u8B0D\u8B08\u8B06\u8B1C\u8B13\u8B1A\u8C4F\u8C70\u8C72\u8C71\u8C6F\u8C95\u8C94\u8CF9\u8D6F\u8E4E\u8E4D\u8E53\u8E50\u8E4C\u8E47\u8F43\u8F40\u9085\u907E\u9138\u919A\u91A2\u919B\u9199\u919F\u91A1\u919D\u91A0\u93A1\u9383\u93AF\u9364\u9356\u9347\u937C\u9358\u935C\u9376\u9349\u9350\u9351\u9360\u936D\u938F\u934C\u936A\u9379\u9357\u9355\u9352\u934F\u9371\u9377\u937B\u9361\u935E\u9363\u9367\u9380\u934E\u9359\u95C7\u95C0\u95C9\u95C3\u95C5\u95B7\u96AE\u96B0\u96AC\u9720\u971F\u9718\u971D\u9719\u979A\u97A1\u979C"], - ["ef40", "\u979E\u979D\u97D5\u97D4\u97F1\u9841\u9844\u984A\u9849\u9845\u9843\u9925\u992B\u992C\u992A\u9933\u9932\u992F\u992D\u9931\u9930\u9998\u99A3\u99A1\u9A02\u99FA\u99F4\u99F7\u99F9\u99F8\u99F6\u99FB\u99FD\u99FE\u99FC\u9A03\u9ABE\u9AFE\u9AFD\u9B01\u9AFC\u9B48\u9B9A\u9BA8\u9B9E\u9B9B\u9BA6\u9BA1\u9BA5\u9BA4\u9B86\u9BA2\u9BA0\u9BAF\u9D33\u9D41\u9D67\u9D36\u9D2E\u9D2F\u9D31\u9D38\u9D30"], - ["efa1", "\u9D45\u9D42\u9D43\u9D3E\u9D37\u9D40\u9D3D\u7FF5\u9D2D\u9E8A\u9E89\u9E8D\u9EB0\u9EC8\u9EDA\u9EFB\u9EFF\u9F24\u9F23\u9F22\u9F54\u9FA0\u5131\u512D\u512E\u5698\u569C\u5697\u569A\u569D\u5699\u5970\u5B3C\u5C69\u5C6A\u5DC0\u5E6D\u5E6E\u61D8\u61DF\u61ED\u61EE\u61F1\u61EA\u61F0\u61EB\u61D6\u61E9\u64FF\u6504\u64FD\u64F8\u6501\u6503\u64FC\u6594\u65DB\u66DA\u66DB\u66D8\u6AC5\u6AB9\u6ABD\u6AE1\u6AC6\u6ABA\u6AB6\u6AB7\u6AC7\u6AB4\u6AAD\u6B5E\u6BC9\u6C0B\u7007\u700C\u700D\u7001\u7005\u7014\u700E\u6FFF\u7000\u6FFB\u7026\u6FFC\u6FF7\u700A\u7201\u71FF\u71F9\u7203\u71FD\u7376"], - ["f040", "\u74B8\u74C0\u74B5\u74C1\u74BE\u74B6\u74BB\u74C2\u7514\u7513\u765C\u7664\u7659\u7650\u7653\u7657\u765A\u76A6\u76BD\u76EC\u77C2\u77BA\u78FF\u790C\u7913\u7914\u7909\u7910\u7912\u7911\u79AD\u79AC\u7A5F\u7C1C\u7C29\u7C19\u7C20\u7C1F\u7C2D\u7C1D\u7C26\u7C28\u7C22\u7C25\u7C30\u7E5C\u7E50\u7E56\u7E63\u7E58\u7E62\u7E5F\u7E51\u7E60\u7E57\u7E53\u7FB5\u7FB3\u7FF7\u7FF8\u8075\u81D1\u81D2"], - ["f0a1", "\u81D0\u825F\u825E\u85B4\u85C6\u85C0\u85C3\u85C2\u85B3\u85B5\u85BD\u85C7\u85C4\u85BF\u85CB\u85CE\u85C8\u85C5\u85B1\u85B6\u85D2\u8624\u85B8\u85B7\u85BE\u8669\u87E7\u87E6\u87E2\u87DB\u87EB\u87EA\u87E5\u87DF\u87F3\u87E4\u87D4\u87DC\u87D3\u87ED\u87D8\u87E3\u87A4\u87D7\u87D9\u8801\u87F4\u87E8\u87DD\u8953\u894B\u894F\u894C\u8946\u8950\u8951\u8949\u8B2A\u8B27\u8B23\u8B33\u8B30\u8B35\u8B47\u8B2F\u8B3C\u8B3E\u8B31\u8B25\u8B37\u8B26\u8B36\u8B2E\u8B24\u8B3B\u8B3D\u8B3A\u8C42\u8C75\u8C99\u8C98\u8C97\u8CFE\u8D04\u8D02\u8D00\u8E5C\u8E62\u8E60\u8E57\u8E56\u8E5E\u8E65\u8E67"], - ["f140", "\u8E5B\u8E5A\u8E61\u8E5D\u8E69\u8E54\u8F46\u8F47\u8F48\u8F4B\u9128\u913A\u913B\u913E\u91A8\u91A5\u91A7\u91AF\u91AA\u93B5\u938C\u9392\u93B7\u939B\u939D\u9389\u93A7\u938E\u93AA\u939E\u93A6\u9395\u9388\u9399\u939F\u938D\u93B1\u9391\u93B2\u93A4\u93A8\u93B4\u93A3\u93A5\u95D2\u95D3\u95D1\u96B3\u96D7\u96DA\u5DC2\u96DF\u96D8\u96DD\u9723\u9722\u9725\u97AC\u97AE\u97A8\u97AB\u97A4\u97AA"], - ["f1a1", "\u97A2\u97A5\u97D7\u97D9\u97D6\u97D8\u97FA\u9850\u9851\u9852\u98B8\u9941\u993C\u993A\u9A0F\u9A0B\u9A09\u9A0D\u9A04\u9A11\u9A0A\u9A05\u9A07\u9A06\u9AC0\u9ADC\u9B08\u9B04\u9B05\u9B29\u9B35\u9B4A\u9B4C\u9B4B\u9BC7\u9BC6\u9BC3\u9BBF\u9BC1\u9BB5\u9BB8\u9BD3\u9BB6\u9BC4\u9BB9\u9BBD\u9D5C\u9D53\u9D4F\u9D4A\u9D5B\u9D4B\u9D59\u9D56\u9D4C\u9D57\u9D52\u9D54\u9D5F\u9D58\u9D5A\u9E8E\u9E8C\u9EDF\u9F01\u9F00\u9F16\u9F25\u9F2B\u9F2A\u9F29\u9F28\u9F4C\u9F55\u5134\u5135\u5296\u52F7\u53B4\u56AB\u56AD\u56A6\u56A7\u56AA\u56AC\u58DA\u58DD\u58DB\u5912\u5B3D\u5B3E\u5B3F\u5DC3\u5E70"], - ["f240", "\u5FBF\u61FB\u6507\u6510\u650D\u6509\u650C\u650E\u6584\u65DE\u65DD\u66DE\u6AE7\u6AE0\u6ACC\u6AD1\u6AD9\u6ACB\u6ADF\u6ADC\u6AD0\u6AEB\u6ACF\u6ACD\u6ADE\u6B60\u6BB0\u6C0C\u7019\u7027\u7020\u7016\u702B\u7021\u7022\u7023\u7029\u7017\u7024\u701C\u702A\u720C\u720A\u7207\u7202\u7205\u72A5\u72A6\u72A4\u72A3\u72A1\u74CB\u74C5\u74B7\u74C3\u7516\u7660\u77C9\u77CA\u77C4\u77F1\u791D\u791B"], - ["f2a1", "\u7921\u791C\u7917\u791E\u79B0\u7A67\u7A68\u7C33\u7C3C\u7C39\u7C2C\u7C3B\u7CEC\u7CEA\u7E76\u7E75\u7E78\u7E70\u7E77\u7E6F\u7E7A\u7E72\u7E74\u7E68\u7F4B\u7F4A\u7F83\u7F86\u7FB7\u7FFD\u7FFE\u8078\u81D7\u81D5\u8264\u8261\u8263\u85EB\u85F1\u85ED\u85D9\u85E1\u85E8\u85DA\u85D7\u85EC\u85F2\u85F8\u85D8\u85DF\u85E3\u85DC\u85D1\u85F0\u85E6\u85EF\u85DE\u85E2\u8800\u87FA\u8803\u87F6\u87F7\u8809\u880C\u880B\u8806\u87FC\u8808\u87FF\u880A\u8802\u8962\u895A\u895B\u8957\u8961\u895C\u8958\u895D\u8959\u8988\u89B7\u89B6\u89F6\u8B50\u8B48\u8B4A\u8B40\u8B53\u8B56\u8B54\u8B4B\u8B55"], - ["f340", "\u8B51\u8B42\u8B52\u8B57\u8C43\u8C77\u8C76\u8C9A\u8D06\u8D07\u8D09\u8DAC\u8DAA\u8DAD\u8DAB\u8E6D\u8E78\u8E73\u8E6A\u8E6F\u8E7B\u8EC2\u8F52\u8F51\u8F4F\u8F50\u8F53\u8FB4\u9140\u913F\u91B0\u91AD\u93DE\u93C7\u93CF\u93C2\u93DA\u93D0\u93F9\u93EC\u93CC\u93D9\u93A9\u93E6\u93CA\u93D4\u93EE\u93E3\u93D5\u93C4\u93CE\u93C0\u93D2\u93E7\u957D\u95DA\u95DB\u96E1\u9729\u972B\u972C\u9728\u9726"], - ["f3a1", "\u97B3\u97B7\u97B6\u97DD\u97DE\u97DF\u985C\u9859\u985D\u9857\u98BF\u98BD\u98BB\u98BE\u9948\u9947\u9943\u99A6\u99A7\u9A1A\u9A15\u9A25\u9A1D\u9A24\u9A1B\u9A22\u9A20\u9A27\u9A23\u9A1E\u9A1C\u9A14\u9AC2\u9B0B\u9B0A\u9B0E\u9B0C\u9B37\u9BEA\u9BEB\u9BE0\u9BDE\u9BE4\u9BE6\u9BE2\u9BF0\u9BD4\u9BD7\u9BEC\u9BDC\u9BD9\u9BE5\u9BD5\u9BE1\u9BDA\u9D77\u9D81\u9D8A\u9D84\u9D88\u9D71\u9D80\u9D78\u9D86\u9D8B\u9D8C\u9D7D\u9D6B\u9D74\u9D75\u9D70\u9D69\u9D85\u9D73\u9D7B\u9D82\u9D6F\u9D79\u9D7F\u9D87\u9D68\u9E94\u9E91\u9EC0\u9EFC\u9F2D\u9F40\u9F41\u9F4D\u9F56\u9F57\u9F58\u5337\u56B2"], - ["f440", "\u56B5\u56B3\u58E3\u5B45\u5DC6\u5DC7\u5EEE\u5EEF\u5FC0\u5FC1\u61F9\u6517\u6516\u6515\u6513\u65DF\u66E8\u66E3\u66E4\u6AF3\u6AF0\u6AEA\u6AE8\u6AF9\u6AF1\u6AEE\u6AEF\u703C\u7035\u702F\u7037\u7034\u7031\u7042\u7038\u703F\u703A\u7039\u7040\u703B\u7033\u7041\u7213\u7214\u72A8\u737D\u737C\u74BA\u76AB\u76AA\u76BE\u76ED\u77CC\u77CE\u77CF\u77CD\u77F2\u7925\u7923\u7927\u7928\u7924\u7929"], - ["f4a1", "\u79B2\u7A6E\u7A6C\u7A6D\u7AF7\u7C49\u7C48\u7C4A\u7C47\u7C45\u7CEE\u7E7B\u7E7E\u7E81\u7E80\u7FBA\u7FFF\u8079\u81DB\u81D9\u820B\u8268\u8269\u8622\u85FF\u8601\u85FE\u861B\u8600\u85F6\u8604\u8609\u8605\u860C\u85FD\u8819\u8810\u8811\u8817\u8813\u8816\u8963\u8966\u89B9\u89F7\u8B60\u8B6A\u8B5D\u8B68\u8B63\u8B65\u8B67\u8B6D\u8DAE\u8E86\u8E88\u8E84\u8F59\u8F56\u8F57\u8F55\u8F58\u8F5A\u908D\u9143\u9141\u91B7\u91B5\u91B2\u91B3\u940B\u9413\u93FB\u9420\u940F\u9414\u93FE\u9415\u9410\u9428\u9419\u940D\u93F5\u9400\u93F7\u9407\u940E\u9416\u9412\u93FA\u9409\u93F8\u940A\u93FF"], - ["f540", "\u93FC\u940C\u93F6\u9411\u9406\u95DE\u95E0\u95DF\u972E\u972F\u97B9\u97BB\u97FD\u97FE\u9860\u9862\u9863\u985F\u98C1\u98C2\u9950\u994E\u9959\u994C\u994B\u9953\u9A32\u9A34\u9A31\u9A2C\u9A2A\u9A36\u9A29\u9A2E\u9A38\u9A2D\u9AC7\u9ACA\u9AC6\u9B10\u9B12\u9B11\u9C0B\u9C08\u9BF7\u9C05\u9C12\u9BF8\u9C40\u9C07\u9C0E\u9C06\u9C17\u9C14\u9C09\u9D9F\u9D99\u9DA4\u9D9D\u9D92\u9D98\u9D90\u9D9B"], - ["f5a1", "\u9DA0\u9D94\u9D9C\u9DAA\u9D97\u9DA1\u9D9A\u9DA2\u9DA8\u9D9E\u9DA3\u9DBF\u9DA9\u9D96\u9DA6\u9DA7\u9E99\u9E9B\u9E9A\u9EE5\u9EE4\u9EE7\u9EE6\u9F30\u9F2E\u9F5B\u9F60\u9F5E\u9F5D\u9F59\u9F91\u513A\u5139\u5298\u5297\u56C3\u56BD\u56BE\u5B48\u5B47\u5DCB\u5DCF\u5EF1\u61FD\u651B\u6B02\u6AFC\u6B03\u6AF8\u6B00\u7043\u7044\u704A\u7048\u7049\u7045\u7046\u721D\u721A\u7219\u737E\u7517\u766A\u77D0\u792D\u7931\u792F\u7C54\u7C53\u7CF2\u7E8A\u7E87\u7E88\u7E8B\u7E86\u7E8D\u7F4D\u7FBB\u8030\u81DD\u8618\u862A\u8626\u861F\u8623\u861C\u8619\u8627\u862E\u8621\u8620\u8629\u861E\u8625"], - ["f640", "\u8829\u881D\u881B\u8820\u8824\u881C\u882B\u884A\u896D\u8969\u896E\u896B\u89FA\u8B79\u8B78\u8B45\u8B7A\u8B7B\u8D10\u8D14\u8DAF\u8E8E\u8E8C\u8F5E\u8F5B\u8F5D\u9146\u9144\u9145\u91B9\u943F\u943B\u9436\u9429\u943D\u943C\u9430\u9439\u942A\u9437\u942C\u9440\u9431\u95E5\u95E4\u95E3\u9735\u973A\u97BF\u97E1\u9864\u98C9\u98C6\u98C0\u9958\u9956\u9A39\u9A3D\u9A46\u9A44\u9A42\u9A41\u9A3A"], - ["f6a1", "\u9A3F\u9ACD\u9B15\u9B17\u9B18\u9B16\u9B3A\u9B52\u9C2B\u9C1D\u9C1C\u9C2C\u9C23\u9C28\u9C29\u9C24\u9C21\u9DB7\u9DB6\u9DBC\u9DC1\u9DC7\u9DCA\u9DCF\u9DBE\u9DC5\u9DC3\u9DBB\u9DB5\u9DCE\u9DB9\u9DBA\u9DAC\u9DC8\u9DB1\u9DAD\u9DCC\u9DB3\u9DCD\u9DB2\u9E7A\u9E9C\u9EEB\u9EEE\u9EED\u9F1B\u9F18\u9F1A\u9F31\u9F4E\u9F65\u9F64\u9F92\u4EB9\u56C6\u56C5\u56CB\u5971\u5B4B\u5B4C\u5DD5\u5DD1\u5EF2\u6521\u6520\u6526\u6522\u6B0B\u6B08\u6B09\u6C0D\u7055\u7056\u7057\u7052\u721E\u721F\u72A9\u737F\u74D8\u74D5\u74D9\u74D7\u766D\u76AD\u7935\u79B4\u7A70\u7A71\u7C57\u7C5C\u7C59\u7C5B\u7C5A"], - ["f740", "\u7CF4\u7CF1\u7E91\u7F4F\u7F87\u81DE\u826B\u8634\u8635\u8633\u862C\u8632\u8636\u882C\u8828\u8826\u882A\u8825\u8971\u89BF\u89BE\u89FB\u8B7E\u8B84\u8B82\u8B86\u8B85\u8B7F\u8D15\u8E95\u8E94\u8E9A\u8E92\u8E90\u8E96\u8E97\u8F60\u8F62\u9147\u944C\u9450\u944A\u944B\u944F\u9447\u9445\u9448\u9449\u9446\u973F\u97E3\u986A\u9869\u98CB\u9954\u995B\u9A4E\u9A53\u9A54\u9A4C\u9A4F\u9A48\u9A4A"], - ["f7a1", "\u9A49\u9A52\u9A50\u9AD0\u9B19\u9B2B\u9B3B\u9B56\u9B55\u9C46\u9C48\u9C3F\u9C44\u9C39\u9C33\u9C41\u9C3C\u9C37\u9C34\u9C32\u9C3D\u9C36\u9DDB\u9DD2\u9DDE\u9DDA\u9DCB\u9DD0\u9DDC\u9DD1\u9DDF\u9DE9\u9DD9\u9DD8\u9DD6\u9DF5\u9DD5\u9DDD\u9EB6\u9EF0\u9F35\u9F33\u9F32\u9F42\u9F6B\u9F95\u9FA2\u513D\u5299\u58E8\u58E7\u5972\u5B4D\u5DD8\u882F\u5F4F\u6201\u6203\u6204\u6529\u6525\u6596\u66EB\u6B11\u6B12\u6B0F\u6BCA\u705B\u705A\u7222\u7382\u7381\u7383\u7670\u77D4\u7C67\u7C66\u7E95\u826C\u863A\u8640\u8639\u863C\u8631\u863B\u863E\u8830\u8832\u882E\u8833\u8976\u8974\u8973\u89FE"], - ["f840", "\u8B8C\u8B8E\u8B8B\u8B88\u8C45\u8D19\u8E98\u8F64\u8F63\u91BC\u9462\u9455\u945D\u9457\u945E\u97C4\u97C5\u9800\u9A56\u9A59\u9B1E\u9B1F\u9B20\u9C52\u9C58\u9C50\u9C4A\u9C4D\u9C4B\u9C55\u9C59\u9C4C\u9C4E\u9DFB\u9DF7\u9DEF\u9DE3\u9DEB\u9DF8\u9DE4\u9DF6\u9DE1\u9DEE\u9DE6\u9DF2\u9DF0\u9DE2\u9DEC\u9DF4\u9DF3\u9DE8\u9DED\u9EC2\u9ED0\u9EF2\u9EF3\u9F06\u9F1C\u9F38\u9F37\u9F36\u9F43\u9F4F"], - ["f8a1", "\u9F71\u9F70\u9F6E\u9F6F\u56D3\u56CD\u5B4E\u5C6D\u652D\u66ED\u66EE\u6B13\u705F\u7061\u705D\u7060\u7223\u74DB\u74E5\u77D5\u7938\u79B7\u79B6\u7C6A\u7E97\u7F89\u826D\u8643\u8838\u8837\u8835\u884B\u8B94\u8B95\u8E9E\u8E9F\u8EA0\u8E9D\u91BE\u91BD\u91C2\u946B\u9468\u9469\u96E5\u9746\u9743\u9747\u97C7\u97E5\u9A5E\u9AD5\u9B59\u9C63\u9C67\u9C66\u9C62\u9C5E\u9C60\u9E02\u9DFE\u9E07\u9E03\u9E06\u9E05\u9E00\u9E01\u9E09\u9DFF\u9DFD\u9E04\u9EA0\u9F1E\u9F46\u9F74\u9F75\u9F76\u56D4\u652E\u65B8\u6B18\u6B19\u6B17\u6B1A\u7062\u7226\u72AA\u77D8\u77D9\u7939\u7C69\u7C6B\u7CF6\u7E9A"], - ["f940", "\u7E98\u7E9B\u7E99\u81E0\u81E1\u8646\u8647\u8648\u8979\u897A\u897C\u897B\u89FF\u8B98\u8B99\u8EA5\u8EA4\u8EA3\u946E\u946D\u946F\u9471\u9473\u9749\u9872\u995F\u9C68\u9C6E\u9C6D\u9E0B\u9E0D\u9E10\u9E0F\u9E12\u9E11\u9EA1\u9EF5\u9F09\u9F47\u9F78\u9F7B\u9F7A\u9F79\u571E\u7066\u7C6F\u883C\u8DB2\u8EA6\u91C3\u9474\u9478\u9476\u9475\u9A60\u9C74\u9C73\u9C71\u9C75\u9E14\u9E13\u9EF6\u9F0A"], - ["f9a1", "\u9FA4\u7068\u7065\u7CF7\u866A\u883E\u883D\u883F\u8B9E\u8C9C\u8EA9\u8EC9\u974B\u9873\u9874\u98CC\u9961\u99AB\u9A64\u9A66\u9A67\u9B24\u9E15\u9E17\u9F48\u6207\u6B1E\u7227\u864C\u8EA8\u9482\u9480\u9481\u9A69\u9A68\u9B2E\u9E19\u7229\u864B\u8B9F\u9483\u9C79\u9EB7\u7675\u9A6B\u9C7A\u9E1D\u7069\u706A\u9EA4\u9F7E\u9F49\u9F98\u7881\u92B9\u88CF\u58BB\u6052\u7CA7\u5AFA\u2554\u2566\u2557\u2560\u256C\u2563\u255A\u2569\u255D\u2552\u2564\u2555\u255E\u256A\u2561\u2558\u2567\u255B\u2553\u2565\u2556\u255F\u256B\u2562\u2559\u2568\u255C\u2551\u2550\u256D\u256E\u2570\u256F\u2593"] - ]; - } -}); - -// node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/encodings/tables/big5-added.json -var require_big5_added = __commonJS({ - "node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/encodings/tables/big5-added.json"(exports, module) { - module.exports = [ - ["8740", "\u43F0\u4C32\u4603\u45A6\u4578\u{27267}\u4D77\u45B3\u{27CB1}\u4CE2\u{27CC5}\u3B95\u4736\u4744\u4C47\u4C40\u{242BF}\u{23617}\u{27352}\u{26E8B}\u{270D2}\u4C57\u{2A351}\u474F\u45DA\u4C85\u{27C6C}\u4D07\u4AA4\u46A1\u{26B23}\u7225\u{25A54}\u{21A63}\u{23E06}\u{23F61}\u664D\u56FB"], - ["8767", "\u7D95\u591D\u{28BB9}\u3DF4\u9734\u{27BEF}\u5BDB\u{21D5E}\u5AA4\u3625\u{29EB0}\u5AD1\u5BB7\u5CFC\u676E\u8593\u{29945}\u7461\u749D\u3875\u{21D53}\u{2369E}\u{26021}\u3EEC"], - ["87a1", "\u{258DE}\u3AF5\u7AFC\u9F97\u{24161}\u{2890D}\u{231EA}\u{20A8A}\u{2325E}\u430A\u8484\u9F96\u942F\u4930\u8613\u5896\u974A\u9218\u79D0\u7A32\u6660\u6A29\u889D\u744C\u7BC5\u6782\u7A2C\u524F\u9046\u34E6\u73C4\u{25DB9}\u74C6\u9FC7\u57B3\u492F\u544C\u4131\u{2368E}\u5818\u7A72\u{27B65}\u8B8F\u46AE\u{26E88}\u4181\u{25D99}\u7BAE\u{224BC}\u9FC8\u{224C1}\u{224C9}\u{224CC}\u9FC9\u8504\u{235BB}\u40B4\u9FCA\u44E1\u{2ADFF}\u62C1\u706E\u9FCB"], - ["8840", "\u31C0", 4, "\u{2010C}\u31C5\u{200D1}\u{200CD}\u31C6\u31C7\u{200CB}\u{21FE8}\u31C8\u{200CA}\u31C9\u31CA\u31CB\u31CC\u{2010E}\u31CD\u31CE\u0100\xC1\u01CD\xC0\u0112\xC9\u011A\xC8\u014C\xD3\u01D1\xD2\u0FFF\xCA\u0304\u1EBE\u0FFF\xCA\u030C\u1EC0\xCA\u0101\xE1\u01CE\xE0\u0251\u0113\xE9\u011B\xE8\u012B\xED\u01D0\xEC\u014D\xF3\u01D2\xF2\u016B\xFA\u01D4\xF9\u01D6\u01D8\u01DA"], - ["88a1", "\u01DC\xFC\u0FFF\xEA\u0304\u1EBF\u0FFF\xEA\u030C\u1EC1\xEA\u0261\u23DA\u23DB"], - ["8940", "\u{2A3A9}\u{21145}"], - ["8943", "\u650A"], - ["8946", "\u4E3D\u6EDD\u9D4E\u91DF"], - ["894c", "\u{27735}\u6491\u4F1A\u4F28\u4FA8\u5156\u5174\u519C\u51E4\u52A1\u52A8\u533B\u534E\u53D1\u53D8\u56E2\u58F0\u5904\u5907\u5932\u5934\u5B66\u5B9E\u5B9F\u5C9A\u5E86\u603B\u6589\u67FE\u6804\u6865\u6D4E\u70BC\u7535\u7EA4\u7EAC\u7EBA\u7EC7\u7ECF\u7EDF\u7F06\u7F37\u827A\u82CF\u836F\u89C6\u8BBE\u8BE2\u8F66\u8F67\u8F6E"], - ["89a1", "\u7411\u7CFC\u7DCD\u6946\u7AC9\u5227"], - ["89ab", "\u918C\u78B8\u915E\u80BC"], - ["89b0", "\u8D0B\u80F6\u{209E7}"], - ["89b5", "\u809F\u9EC7\u4CCD\u9DC9\u9E0C\u4C3E\u{29DF6}\u{2700E}\u9E0A\u{2A133}\u35C1"], - ["89c1", "\u6E9A\u823E\u7519"], - ["89c5", "\u4911\u9A6C\u9A8F\u9F99\u7987\u{2846C}\u{21DCA}\u{205D0}\u{22AE6}\u4E24\u4E81\u4E80\u4E87\u4EBF\u4EEB\u4F37\u344C\u4FBD\u3E48\u5003\u5088\u347D\u3493\u34A5\u5186\u5905\u51DB\u51FC\u5205\u4E89\u5279\u5290\u5327\u35C7\u53A9\u3551\u53B0\u3553\u53C2\u5423\u356D\u3572\u3681\u5493\u54A3\u54B4\u54B9\u54D0\u54EF\u5518\u5523\u5528\u3598\u553F\u35A5\u35BF\u55D7\u35C5"], - ["8a40", "\u{27D84}\u5525"], - ["8a43", "\u{20C42}\u{20D15}\u{2512B}\u5590\u{22CC6}\u39EC\u{20341}\u8E46\u{24DB8}\u{294E5}\u4053\u{280BE}\u777A\u{22C38}\u3A34\u47D5\u{2815D}\u{269F2}\u{24DEA}\u64DD\u{20D7C}\u{20FB4}\u{20CD5}\u{210F4}\u648D\u8E7E\u{20E96}\u{20C0B}\u{20F64}\u{22CA9}\u{28256}\u{244D3}"], - ["8a64", "\u{20D46}\u{29A4D}\u{280E9}\u47F4\u{24EA7}\u{22CC2}\u9AB2\u3A67\u{295F4}\u3FED\u3506\u{252C7}\u{297D4}\u{278C8}\u{22D44}\u9D6E\u9815"], - ["8a76", "\u43D9\u{260A5}\u64B4\u54E3\u{22D4C}\u{22BCA}\u{21077}\u39FB\u{2106F}"], - ["8aa1", "\u{266DA}\u{26716}\u{279A0}\u64EA\u{25052}\u{20C43}\u8E68\u{221A1}\u{28B4C}\u{20731}"], - ["8aac", "\u480B\u{201A9}\u3FFA\u5873\u{22D8D}"], - ["8ab2", "\u{245C8}\u{204FC}\u{26097}\u{20F4C}\u{20D96}\u5579\u40BB\u43BA"], - ["8abb", "\u4AB4\u{22A66}\u{2109D}\u81AA\u98F5\u{20D9C}\u6379\u39FE\u{22775}\u8DC0\u56A1\u647C\u3E43"], - ["8ac9", "\u{2A601}\u{20E09}\u{22ACF}\u{22CC9}"], - ["8ace", "\u{210C8}\u{239C2}\u3992\u3A06\u{2829B}\u3578\u{25E49}\u{220C7}\u5652\u{20F31}\u{22CB2}\u{29720}\u34BC\u6C3D\u{24E3B}"], - ["8adf", "\u{27574}\u{22E8B}\u{22208}\u{2A65B}\u{28CCD}\u{20E7A}\u{20C34}\u{2681C}\u7F93\u{210CF}\u{22803}\u{22939}\u35FB\u{251E3}\u{20E8C}\u{20F8D}\u{20EAA}\u3F93\u{20F30}\u{20D47}\u{2114F}\u{20E4C}"], - ["8af6", "\u{20EAB}\u{20BA9}\u{20D48}\u{210C0}\u{2113D}\u3FF9\u{22696}\u6432\u{20FAD}"], - ["8b40", "\u{233F4}\u{27639}\u{22BCE}\u{20D7E}\u{20D7F}\u{22C51}\u{22C55}\u3A18\u{20E98}\u{210C7}\u{20F2E}\u{2A632}\u{26B50}\u{28CD2}\u{28D99}\u{28CCA}\u95AA\u54CC\u82C4\u55B9"], - ["8b55", "\u{29EC3}\u9C26\u9AB6\u{2775E}\u{22DEE}\u7140\u816D\u80EC\u5C1C\u{26572}\u8134\u3797\u535F\u{280BD}\u91B6\u{20EFA}\u{20E0F}\u{20E77}\u{20EFB}\u35DD\u{24DEB}\u3609\u{20CD6}\u56AF\u{227B5}\u{210C9}\u{20E10}\u{20E78}\u{21078}\u{21148}\u{28207}\u{21455}\u{20E79}\u{24E50}\u{22DA4}\u5A54\u{2101D}\u{2101E}\u{210F5}\u{210F6}\u579C\u{20E11}"], - ["8ba1", "\u{27694}\u{282CD}\u{20FB5}\u{20E7B}\u{2517E}\u3703\u{20FB6}\u{21180}\u{252D8}\u{2A2BD}\u{249DA}\u{2183A}\u{24177}\u{2827C}\u5899\u5268\u361A\u{2573D}\u7BB2\u5B68\u4800\u4B2C\u9F27\u49E7\u9C1F\u9B8D\u{25B74}\u{2313D}\u55FB\u35F2\u5689\u4E28\u5902\u{21BC1}\u{2F878}\u9751\u{20086}\u4E5B\u4EBB\u353E\u5C23\u5F51\u5FC4\u38FA\u624C\u6535\u6B7A\u6C35\u6C3A\u706C\u722B\u4E2C\u72AD\u{248E9}\u7F52\u793B\u7CF9\u7F53\u{2626A}\u34C1"], - ["8bde", "\u{2634B}\u8002\u8080\u{26612}\u{26951}\u535D\u8864\u89C1\u{278B2}\u8BA0\u8D1D\u9485\u9578\u957F\u95E8\u{28E0F}\u97E6\u9875\u98CE\u98DE\u9963\u{29810}\u9C7C\u9E1F\u9EC4\u6B6F\uF907\u4E37\u{20087}\u961D\u6237\u94A2"], - ["8c40", "\u503B\u6DFE\u{29C73}\u9FA6\u3DC9\u888F\u{2414E}\u7077\u5CF5\u4B20\u{251CD}\u3559\u{25D30}\u6122\u{28A32}\u8FA7\u91F6\u7191\u6719\u73BA\u{23281}\u{2A107}\u3C8B\u{21980}\u4B10\u78E4\u7402\u51AE\u{2870F}\u4009\u6A63\u{2A2BA}\u4223\u860F\u{20A6F}\u7A2A\u{29947}\u{28AEA}\u9755\u704D\u5324\u{2207E}\u93F4\u76D9\u{289E3}\u9FA7\u77DD\u4EA3\u4FF0\u50BC\u4E2F\u4F17\u9FA8\u5434\u7D8B\u5892\u58D0\u{21DB6}\u5E92\u5E99\u5FC2\u{22712}\u658B"], - ["8ca1", "\u{233F9}\u6919\u6A43\u{23C63}\u6CFF"], - ["8ca7", "\u7200\u{24505}\u738C\u3EDB\u{24A13}\u5B15\u74B9\u8B83\u{25CA4}\u{25695}\u7A93\u7BEC\u7CC3\u7E6C\u82F8\u8597\u9FA9\u8890\u9FAA\u8EB9\u9FAB\u8FCF\u855F\u99E0\u9221\u9FAC\u{28DB9}\u{2143F}\u4071\u42A2\u5A1A"], - ["8cc9", "\u9868\u676B\u4276\u573D"], - ["8cce", "\u85D6\u{2497B}\u82BF\u{2710D}\u4C81\u{26D74}\u5D7B\u{26B15}\u{26FBE}\u9FAD\u9FAE\u5B96\u9FAF\u66E7\u7E5B\u6E57\u79CA\u3D88\u44C3\u{23256}\u{22796}\u439A\u4536"], - ["8ce6", "\u5CD5\u{23B1A}\u8AF9\u5C78\u3D12\u{23551}\u5D78\u9FB2\u7157\u4558\u{240EC}\u{21E23}\u4C77\u3978\u344A\u{201A4}\u{26C41}\u8ACC\u4FB4\u{20239}\u59BF\u816C\u9856\u{298FA}\u5F3B"], - ["8d40", "\u{20B9F}"], - ["8d42", "\u{221C1}\u{2896D}\u4102\u46BB\u{29079}\u3F07\u9FB3\u{2A1B5}\u40F8\u37D6\u46F7\u{26C46}\u417C\u{286B2}\u{273FF}\u456D\u38D4\u{2549A}\u4561\u451B\u4D89\u4C7B\u4D76\u45EA\u3FC8\u{24B0F}\u3661\u44DE\u44BD\u41ED\u5D3E\u5D48\u5D56\u3DFC\u380F\u5DA4\u5DB9\u3820\u3838\u5E42\u5EBD\u5F25\u5F83\u3908\u3914\u393F\u394D\u60D7\u613D\u5CE5\u3989\u61B7\u61B9\u61CF\u39B8\u622C\u6290\u62E5\u6318\u39F8\u56B1"], - ["8da1", "\u3A03\u63E2\u63FB\u6407\u645A\u3A4B\u64C0\u5D15\u5621\u9F9F\u3A97\u6586\u3ABD\u65FF\u6653\u3AF2\u6692\u3B22\u6716\u3B42\u67A4\u6800\u3B58\u684A\u6884\u3B72\u3B71\u3B7B\u6909\u6943\u725C\u6964\u699F\u6985\u3BBC\u69D6\u3BDD\u6A65\u6A74\u6A71\u6A82\u3BEC\u6A99\u3BF2\u6AAB\u6AB5\u6AD4\u6AF6\u6B81\u6BC1\u6BEA\u6C75\u6CAA\u3CCB\u6D02\u6D06\u6D26\u6D81\u3CEF\u6DA4\u6DB1\u6E15\u6E18\u6E29\u6E86\u{289C0}\u6EBB\u6EE2\u6EDA\u9F7F\u6EE8\u6EE9\u6F24\u6F34\u3D46\u{23F41}\u6F81\u6FBE\u3D6A\u3D75\u71B7\u5C99\u3D8A\u702C\u3D91\u7050\u7054\u706F\u707F\u7089\u{20325}\u43C1\u35F1\u{20ED8}"], - ["8e40", "\u{23ED7}\u57BE\u{26ED3}\u713E\u{257E0}\u364E\u69A2\u{28BE9}\u5B74\u7A49\u{258E1}\u{294D9}\u7A65\u7A7D\u{259AC}\u7ABB\u7AB0\u7AC2\u7AC3\u71D1\u{2648D}\u41CA\u7ADA\u7ADD\u7AEA\u41EF\u54B2\u{25C01}\u7B0B\u7B55\u7B29\u{2530E}\u{25CFE}\u7BA2\u7B6F\u839C\u{25BB4}\u{26C7F}\u7BD0\u8421\u7B92\u7BB8\u{25D20}\u3DAD\u{25C65}\u8492\u7BFA\u7C06\u7C35\u{25CC1}\u7C44\u7C83\u{24882}\u7CA6\u667D\u{24578}\u7CC9\u7CC7\u7CE6\u7C74\u7CF3\u7CF5\u7CCE"], - ["8ea1", "\u7E67\u451D\u{26E44}\u7D5D\u{26ED6}\u748D\u7D89\u7DAB\u7135\u7DB3\u7DD2\u{24057}\u{26029}\u7DE4\u3D13\u7DF5\u{217F9}\u7DE5\u{2836D}\u7E1D\u{26121}\u{2615A}\u7E6E\u7E92\u432B\u946C\u7E27\u7F40\u7F41\u7F47\u7936\u{262D0}\u99E1\u7F97\u{26351}\u7FA3\u{21661}\u{20068}\u455C\u{23766}\u4503\u{2833A}\u7FFA\u{26489}\u8005\u8008\u801D\u8028\u802F\u{2A087}\u{26CC3}\u803B\u803C\u8061\u{22714}\u4989\u{26626}\u{23DE3}\u{266E8}\u6725\u80A7\u{28A48}\u8107\u811A\u58B0\u{226F6}\u6C7F\u{26498}\u{24FB8}\u64E7\u{2148A}\u8218\u{2185E}\u6A53\u{24A65}\u{24A95}\u447A\u8229\u{20B0D}\u{26A52}\u{23D7E}\u4FF9\u{214FD}\u84E2\u8362\u{26B0A}\u{249A7}\u{23530}\u{21773}\u{23DF8}\u82AA\u691B\u{2F994}\u41DB"], - ["8f40", "\u854B\u82D0\u831A\u{20E16}\u{217B4}\u36C1\u{2317D}\u{2355A}\u827B\u82E2\u8318\u{23E8B}\u{26DA3}\u{26B05}\u{26B97}\u{235CE}\u3DBF\u831D\u55EC\u8385\u450B\u{26DA5}\u83AC\u83C1\u83D3\u347E\u{26ED4}\u6A57\u855A\u3496\u{26E42}\u{22EEF}\u8458\u{25BE4}\u8471\u3DD3\u44E4\u6AA7\u844A\u{23CB5}\u7958\u84A8\u{26B96}\u{26E77}\u{26E43}\u84DE\u840F\u8391\u44A0\u8493\u84E4\u{25C91}\u4240\u{25CC0}\u4543\u8534\u5AF2\u{26E99}\u4527\u8573\u4516\u67BF\u8616"], - ["8fa1", "\u{28625}\u{2863B}\u85C1\u{27088}\u8602\u{21582}\u{270CD}\u{2F9B2}\u456A\u8628\u3648\u{218A2}\u53F7\u{2739A}\u867E\u8771\u{2A0F8}\u87EE\u{22C27}\u87B1\u87DA\u880F\u5661\u866C\u6856\u460F\u8845\u8846\u{275E0}\u{23DB9}\u{275E4}\u885E\u889C\u465B\u88B4\u88B5\u63C1\u88C5\u7777\u{2770F}\u8987\u898A\u89A6\u89A9\u89A7\u89BC\u{28A25}\u89E7\u{27924}\u{27ABD}\u8A9C\u7793\u91FE\u8A90\u{27A59}\u7AE9\u{27B3A}\u{23F8F}\u4713\u{27B38}\u717C\u8B0C\u8B1F\u{25430}\u{25565}\u8B3F\u8B4C\u8B4D\u8AA9\u{24A7A}\u8B90\u8B9B\u8AAF\u{216DF}\u4615\u884F\u8C9B\u{27D54}\u{27D8F}\u{2F9D4}\u3725\u{27D53}\u8CD6\u{27D98}\u{27DBD}\u8D12\u8D03\u{21910}\u8CDB\u705C\u8D11\u{24CC9}\u3ED0\u8D77"], - ["9040", "\u8DA9\u{28002}\u{21014}\u{2498A}\u3B7C\u{281BC}\u{2710C}\u7AE7\u8EAD\u8EB6\u8EC3\u92D4\u8F19\u8F2D\u{28365}\u{28412}\u8FA5\u9303\u{2A29F}\u{20A50}\u8FB3\u492A\u{289DE}\u{2853D}\u{23DBB}\u5EF8\u{23262}\u8FF9\u{2A014}\u{286BC}\u{28501}\u{22325}\u3980\u{26ED7}\u9037\u{2853C}\u{27ABE}\u9061\u{2856C}\u{2860B}\u90A8\u{28713}\u90C4\u{286E6}\u90AE\u90FD\u9167\u3AF0\u91A9\u91C4\u7CAC\u{28933}\u{21E89}\u920E\u6C9F\u9241\u9262\u{255B9}\u92B9\u{28AC6}\u{23C9B}\u{28B0C}\u{255DB}"], - ["90a1", "\u{20D31}\u932C\u936B\u{28AE1}\u{28BEB}\u708F\u5AC3\u{28AE2}\u{28AE5}\u4965\u9244\u{28BEC}\u{28C39}\u{28BFF}\u9373\u945B\u8EBC\u9585\u95A6\u9426\u95A0\u6FF6\u42B9\u{2267A}\u{286D8}\u{2127C}\u{23E2E}\u49DF\u6C1C\u967B\u9696\u416C\u96A3\u{26ED5}\u61DA\u96B6\u78F5\u{28AE0}\u96BD\u53CC\u49A1\u{26CB8}\u{20274}\u{26410}\u{290AF}\u{290E5}\u{24AD1}\u{21915}\u{2330A}\u9731\u8642\u9736\u4A0F\u453D\u4585\u{24AE9}\u7075\u5B41\u971B\u975C\u{291D5}\u9757\u5B4A\u{291EB}\u975F\u9425\u50D0\u{230B7}\u{230BC}\u9789\u979F\u97B1\u97BE\u97C0\u97D2\u97E0\u{2546C}\u97EE\u741C\u{29433}\u97FF\u97F5\u{2941D}\u{2797A}\u4AD1\u9834\u9833\u984B\u9866\u3B0E\u{27175}\u3D51\u{20630}\u{2415C}"], - ["9140", "\u{25706}\u98CA\u98B7\u98C8\u98C7\u4AFF\u{26D27}\u{216D3}\u55B0\u98E1\u98E6\u98EC\u9378\u9939\u{24A29}\u4B72\u{29857}\u{29905}\u99F5\u9A0C\u9A3B\u9A10\u9A58\u{25725}\u36C4\u{290B1}\u{29BD5}\u9AE0\u9AE2\u{29B05}\u9AF4\u4C0E\u9B14\u9B2D\u{28600}\u5034\u9B34\u{269A8}\u38C3\u{2307D}\u9B50\u9B40\u{29D3E}\u5A45\u{21863}\u9B8E\u{2424B}\u9C02\u9BFF\u9C0C\u{29E68}\u9DD4\u{29FB7}\u{2A192}\u{2A1AB}\u{2A0E1}\u{2A123}\u{2A1DF}\u9D7E\u9D83\u{2A134}\u9E0E\u6888"], - ["91a1", "\u9DC4\u{2215B}\u{2A193}\u{2A220}\u{2193B}\u{2A233}\u9D39\u{2A0B9}\u{2A2B4}\u9E90\u9E95\u9E9E\u9EA2\u4D34\u9EAA\u9EAF\u{24364}\u9EC1\u3B60\u39E5\u3D1D\u4F32\u37BE\u{28C2B}\u9F02\u9F08\u4B96\u9424\u{26DA2}\u9F17\u9F16\u9F39\u569F\u568A\u9F45\u99B8\u{2908B}\u97F2\u847F\u9F62\u9F69\u7ADC\u9F8E\u7216\u4BBE\u{24975}\u{249BB}\u7177\u{249F8}\u{24348}\u{24A51}\u739E\u{28BDA}\u{218FA}\u799F\u{2897E}\u{28E36}\u9369\u93F3\u{28A44}\u92EC\u9381\u93CB\u{2896C}\u{244B9}\u7217\u3EEB\u7772\u7A43\u70D0\u{24473}\u{243F8}\u717E\u{217EF}\u70A3\u{218BE}\u{23599}\u3EC7\u{21885}\u{2542F}\u{217F8}\u3722\u{216FB}\u{21839}\u36E1\u{21774}\u{218D1}\u{25F4B}\u3723\u{216C0}\u575B\u{24A25}\u{213FE}\u{212A8}"], - ["9240", "\u{213C6}\u{214B6}\u8503\u{236A6}\u8503\u8455\u{24994}\u{27165}\u{23E31}\u{2555C}\u{23EFB}\u{27052}\u44F4\u{236EE}\u{2999D}\u{26F26}\u67F9\u3733\u3C15\u3DE7\u586C\u{21922}\u6810\u4057\u{2373F}\u{240E1}\u{2408B}\u{2410F}\u{26C21}\u54CB\u569E\u{266B1}\u5692\u{20FDF}\u{20BA8}\u{20E0D}\u93C6\u{28B13}\u939C\u4EF8\u512B\u3819\u{24436}\u4EBC\u{20465}\u{2037F}\u4F4B\u4F8A\u{25651}\u5A68\u{201AB}\u{203CB}\u3999\u{2030A}\u{20414}\u3435\u4F29\u{202C0}\u{28EB3}\u{20275}\u8ADA\u{2020C}\u4E98"], - ["92a1", "\u50CD\u510D\u4FA2\u4F03\u{24A0E}\u{23E8A}\u4F42\u502E\u506C\u5081\u4FCC\u4FE5\u5058\u50FC\u5159\u515B\u515D\u515E\u6E76\u{23595}\u{23E39}\u{23EBF}\u6D72\u{21884}\u{23E89}\u51A8\u51C3\u{205E0}\u44DD\u{204A3}\u{20492}\u{20491}\u8D7A\u{28A9C}\u{2070E}\u5259\u52A4\u{20873}\u52E1\u936E\u467A\u718C\u{2438C}\u{20C20}\u{249AC}\u{210E4}\u69D1\u{20E1D}\u7479\u3EDE\u7499\u7414\u7456\u7398\u4B8E\u{24ABC}\u{2408D}\u53D0\u3584\u720F\u{240C9}\u55B4\u{20345}\u54CD\u{20BC6}\u571D\u925D\u96F4\u9366\u57DD\u578D\u577F\u363E\u58CB\u5A99\u{28A46}\u{216FA}\u{2176F}\u{21710}\u5A2C\u59B8\u928F\u5A7E\u5ACF\u5A12\u{25946}\u{219F3}\u{21861}\u{24295}\u36F5\u6D05\u7443\u5A21\u{25E83}"], - ["9340", "\u5A81\u{28BD7}\u{20413}\u93E0\u748C\u{21303}\u7105\u4972\u9408\u{289FB}\u93BD\u37A0\u5C1E\u5C9E\u5E5E\u5E48\u{21996}\u{2197C}\u{23AEE}\u5ECD\u5B4F\u{21903}\u{21904}\u3701\u{218A0}\u36DD\u{216FE}\u36D3\u812A\u{28A47}\u{21DBA}\u{23472}\u{289A8}\u5F0C\u5F0E\u{21927}\u{217AB}\u5A6B\u{2173B}\u5B44\u8614\u{275FD}\u8860\u607E\u{22860}\u{2262B}\u5FDB\u3EB8\u{225AF}\u{225BE}\u{29088}\u{26F73}\u61C0\u{2003E}\u{20046}\u{2261B}\u6199\u6198\u6075\u{22C9B}\u{22D07}\u{246D4}\u{2914D}"], - ["93a1", "\u6471\u{24665}\u{22B6A}\u3A29\u{22B22}\u{23450}\u{298EA}\u{22E78}\u6337\u{2A45B}\u64B6\u6331\u63D1\u{249E3}\u{22D67}\u62A4\u{22CA1}\u643B\u656B\u6972\u3BF4\u{2308E}\u{232AD}\u{24989}\u{232AB}\u550D\u{232E0}\u{218D9}\u{2943F}\u66CE\u{23289}\u{231B3}\u3AE0\u4190\u{25584}\u{28B22}\u{2558F}\u{216FC}\u{2555B}\u{25425}\u78EE\u{23103}\u{2182A}\u{23234}\u3464\u{2320F}\u{23182}\u{242C9}\u668E\u{26D24}\u666B\u4B93\u6630\u{27870}\u{21DEB}\u6663\u{232D2}\u{232E1}\u661E\u{25872}\u38D1\u{2383A}\u{237BC}\u3B99\u{237A2}\u{233FE}\u74D0\u3B96\u678F\u{2462A}\u68B6\u681E\u3BC4\u6ABE\u3863\u{237D5}\u{24487}\u6A33\u6A52\u6AC9\u6B05\u{21912}\u6511\u6898\u6A4C\u3BD7\u6A7A\u6B57\u{23FC0}\u{23C9A}\u93A0\u92F2\u{28BEA}\u{28ACB}"], - ["9440", "\u9289\u{2801E}\u{289DC}\u9467\u6DA5\u6F0B\u{249EC}\u6D67\u{23F7F}\u3D8F\u6E04\u{2403C}\u5A3D\u6E0A\u5847\u6D24\u7842\u713B\u{2431A}\u{24276}\u70F1\u7250\u7287\u7294\u{2478F}\u{24725}\u5179\u{24AA4}\u{205EB}\u747A\u{23EF8}\u{2365F}\u{24A4A}\u{24917}\u{25FE1}\u3F06\u3EB1\u{24ADF}\u{28C23}\u{23F35}\u60A7\u3EF3\u74CC\u743C\u9387\u7437\u449F\u{26DEA}\u4551\u7583\u3F63\u{24CD9}\u{24D06}\u3F58\u7555\u7673\u{2A5C6}\u3B19\u7468\u{28ACC}\u{249AB}\u{2498E}\u3AFB"], - ["94a1", "\u3DCD\u{24A4E}\u3EFF\u{249C5}\u{248F3}\u91FA\u5732\u9342\u{28AE3}\u{21864}\u50DF\u{25221}\u{251E7}\u7778\u{23232}\u770E\u770F\u777B\u{24697}\u{23781}\u3A5E\u{248F0}\u7438\u749B\u3EBF\u{24ABA}\u{24AC7}\u40C8\u{24A96}\u{261AE}\u9307\u{25581}\u781E\u788D\u7888\u78D2\u73D0\u7959\u{27741}\u{256E3}\u410E\u799B\u8496\u79A5\u6A2D\u{23EFA}\u7A3A\u79F4\u416E\u{216E6}\u4132\u9235\u79F1\u{20D4C}\u{2498C}\u{20299}\u{23DBA}\u{2176E}\u3597\u556B\u3570\u36AA\u{201D4}\u{20C0D}\u7AE2\u5A59\u{226F5}\u{25AAF}\u{25A9C}\u5A0D\u{2025B}\u78F0\u5A2A\u{25BC6}\u7AFE\u41F9\u7C5D\u7C6D\u4211\u{25BB3}\u{25EBC}\u{25EA6}\u7CCD\u{249F9}\u{217B0}\u7C8E\u7C7C\u7CAE\u6AB2\u7DDC\u7E07\u7DD3\u7F4E\u{26261}"], - ["9540", "\u{2615C}\u{27B48}\u7D97\u{25E82}\u426A\u{26B75}\u{20916}\u67D6\u{2004E}\u{235CF}\u57C4\u{26412}\u{263F8}\u{24962}\u7FDD\u7B27\u{2082C}\u{25AE9}\u{25D43}\u7B0C\u{25E0E}\u99E6\u8645\u9A63\u6A1C\u{2343F}\u39E2\u{249F7}\u{265AD}\u9A1F\u{265A0}\u8480\u{27127}\u{26CD1}\u44EA\u8137\u4402\u80C6\u8109\u8142\u{267B4}\u98C3\u{26A42}\u8262\u8265\u{26A51}\u8453\u{26DA7}\u8610\u{2721B}\u5A86\u417F\u{21840}\u5B2B\u{218A1}\u5AE4\u{218D8}\u86A0\u{2F9BC}\u{23D8F}\u882D\u{27422}\u5A02"], - ["95a1", "\u886E\u4F45\u8887\u88BF\u88E6\u8965\u894D\u{25683}\u8954\u{27785}\u{27784}\u{28BF5}\u{28BD9}\u{28B9C}\u{289F9}\u3EAD\u84A3\u46F5\u46CF\u37F2\u8A3D\u8A1C\u{29448}\u5F4D\u922B\u{24284}\u65D4\u7129\u70C4\u{21845}\u9D6D\u8C9F\u8CE9\u{27DDC}\u599A\u77C3\u59F0\u436E\u36D4\u8E2A\u8EA7\u{24C09}\u8F30\u8F4A\u42F4\u6C58\u6FBB\u{22321}\u489B\u6F79\u6E8B\u{217DA}\u9BE9\u36B5\u{2492F}\u90BB\u9097\u5571\u4906\u91BB\u9404\u{28A4B}\u4062\u{28AFC}\u9427\u{28C1D}\u{28C3B}\u84E5\u8A2B\u9599\u95A7\u9597\u9596\u{28D34}\u7445\u3EC2\u{248FF}\u{24A42}\u{243EA}\u3EE7\u{23225}\u968F\u{28EE7}\u{28E66}\u{28E65}\u3ECC\u{249ED}\u{24A78}\u{23FEE}\u7412\u746B\u3EFC\u9741\u{290B0}"], - ["9640", "\u6847\u4A1D\u{29093}\u{257DF}\u975D\u9368\u{28989}\u{28C26}\u{28B2F}\u{263BE}\u92BA\u5B11\u8B69\u493C\u73F9\u{2421B}\u979B\u9771\u9938\u{20F26}\u5DC1\u{28BC5}\u{24AB2}\u981F\u{294DA}\u92F6\u{295D7}\u91E5\u44C0\u{28B50}\u{24A67}\u{28B64}\u98DC\u{28A45}\u3F00\u922A\u4925\u8414\u993B\u994D\u{27B06}\u3DFD\u999B\u4B6F\u99AA\u9A5C\u{28B65}\u{258C8}\u6A8F\u9A21\u5AFE\u9A2F\u{298F1}\u4B90\u{29948}\u99BC\u4BBD\u4B97\u937D\u5872\u{21302}\u5822\u{249B8}"], - ["96a1", "\u{214E8}\u7844\u{2271F}\u{23DB8}\u68C5\u3D7D\u9458\u3927\u6150\u{22781}\u{2296B}\u6107\u9C4F\u9C53\u9C7B\u9C35\u9C10\u9B7F\u9BCF\u{29E2D}\u9B9F\u{2A1F5}\u{2A0FE}\u9D21\u4CAE\u{24104}\u9E18\u4CB0\u9D0C\u{2A1B4}\u{2A0ED}\u{2A0F3}\u{2992F}\u9DA5\u84BD\u{26E12}\u{26FDF}\u{26B82}\u85FC\u4533\u{26DA4}\u{26E84}\u{26DF0}\u8420\u85EE\u{26E00}\u{237D7}\u{26064}\u79E2\u{2359C}\u{23640}\u492D\u{249DE}\u3D62\u93DB\u92BE\u9348\u{202BF}\u78B9\u9277\u944D\u4FE4\u3440\u9064\u{2555D}\u783D\u7854\u78B6\u784B\u{21757}\u{231C9}\u{24941}\u369A\u4F72\u6FDA\u6FD9\u701E\u701E\u5414\u{241B5}\u57BB\u58F3\u578A\u9D16\u57D7\u7134\u34AF\u{241AC}\u71EB\u{26C40}\u{24F97}\u5B28\u{217B5}\u{28A49}"], - ["9740", "\u610C\u5ACE\u5A0B\u42BC\u{24488}\u372C\u4B7B\u{289FC}\u93BB\u93B8\u{218D6}\u{20F1D}\u8472\u{26CC0}\u{21413}\u{242FA}\u{22C26}\u{243C1}\u5994\u{23DB7}\u{26741}\u7DA8\u{2615B}\u{260A4}\u{249B9}\u{2498B}\u{289FA}\u92E5\u73E2\u3EE9\u74B4\u{28B63}\u{2189F}\u3EE1\u{24AB3}\u6AD8\u73F3\u73FB\u3ED6\u{24A3E}\u{24A94}\u{217D9}\u{24A66}\u{203A7}\u{21424}\u{249E5}\u7448\u{24916}\u70A5\u{24976}\u9284\u73E6\u935F\u{204FE}\u9331\u{28ACE}\u{28A16}\u9386\u{28BE7}\u{255D5}\u4935\u{28A82}\u716B"], - ["97a1", "\u{24943}\u{20CFF}\u56A4\u{2061A}\u{20BEB}\u{20CB8}\u5502\u79C4\u{217FA}\u7DFE\u{216C2}\u{24A50}\u{21852}\u452E\u9401\u370A\u{28AC0}\u{249AD}\u59B0\u{218BF}\u{21883}\u{27484}\u5AA1\u36E2\u{23D5B}\u36B0\u925F\u5A79\u{28A81}\u{21862}\u9374\u3CCD\u{20AB4}\u4A96\u398A\u50F4\u3D69\u3D4C\u{2139C}\u7175\u42FB\u{28218}\u6E0F\u{290E4}\u44EB\u6D57\u{27E4F}\u7067\u6CAF\u3CD6\u{23FED}\u{23E2D}\u6E02\u6F0C\u3D6F\u{203F5}\u7551\u36BC\u34C8\u4680\u3EDA\u4871\u59C4\u926E\u493E\u8F41\u{28C1C}\u{26BC0}\u5812\u57C8\u36D6\u{21452}\u70FE\u{24362}\u{24A71}\u{22FE3}\u{212B0}\u{223BD}\u68B9\u6967\u{21398}\u{234E5}\u{27BF4}\u{236DF}\u{28A83}\u{237D6}\u{233FA}\u{24C9F}\u6A1A\u{236AD}\u{26CB7}\u843E\u44DF\u44CE"], - ["9840", "\u{26D26}\u{26D51}\u{26C82}\u{26FDE}\u6F17\u{27109}\u833D\u{2173A}\u83ED\u{26C80}\u{27053}\u{217DB}\u5989\u5A82\u{217B3}\u5A61\u5A71\u{21905}\u{241FC}\u372D\u59EF\u{2173C}\u36C7\u718E\u9390\u669A\u{242A5}\u5A6E\u5A2B\u{24293}\u6A2B\u{23EF9}\u{27736}\u{2445B}\u{242CA}\u711D\u{24259}\u{289E1}\u4FB0\u{26D28}\u5CC2\u{244CE}\u{27E4D}\u{243BD}\u6A0C\u{24256}\u{21304}\u70A6\u7133\u{243E9}\u3DA5\u6CDF\u{2F825}\u{24A4F}\u7E65\u59EB\u5D2F\u3DF3\u5F5C\u{24A5D}\u{217DF}\u7DA4\u8426"], - ["98a1", "\u5485\u{23AFA}\u{23300}\u{20214}\u577E\u{208D5}\u{20619}\u3FE5\u{21F9E}\u{2A2B6}\u7003\u{2915B}\u5D70\u738F\u7CD3\u{28A59}\u{29420}\u4FC8\u7FE7\u72CD\u7310\u{27AF4}\u7338\u7339\u{256F6}\u7341\u7348\u3EA9\u{27B18}\u906C\u71F5\u{248F2}\u73E1\u81F6\u3ECA\u770C\u3ED1\u6CA2\u56FD\u7419\u741E\u741F\u3EE2\u3EF0\u3EF4\u3EFA\u74D3\u3F0E\u3F53\u7542\u756D\u7572\u758D\u3F7C\u75C8\u75DC\u3FC0\u764D\u3FD7\u7674\u3FDC\u767A\u{24F5C}\u7188\u5623\u8980\u5869\u401D\u7743\u4039\u6761\u4045\u35DB\u7798\u406A\u406F\u5C5E\u77BE\u77CB\u58F2\u7818\u70B9\u781C\u40A8\u7839\u7847\u7851\u7866\u8448\u{25535}\u7933\u6803\u7932\u4103"], - ["9940", "\u4109\u7991\u7999\u8FBB\u7A06\u8FBC\u4167\u7A91\u41B2\u7ABC\u8279\u41C4\u7ACF\u7ADB\u41CF\u4E21\u7B62\u7B6C\u7B7B\u7C12\u7C1B\u4260\u427A\u7C7B\u7C9C\u428C\u7CB8\u4294\u7CED\u8F93\u70C0\u{20CCF}\u7DCF\u7DD4\u7DD0\u7DFD\u7FAE\u7FB4\u729F\u4397\u8020\u8025\u7B39\u802E\u8031\u8054\u3DCC\u57B4\u70A0\u80B7\u80E9\u43ED\u810C\u732A\u810E\u8112\u7560\u8114\u4401\u3B39\u8156\u8159\u815A"], - ["99a1", "\u4413\u583A\u817C\u8184\u4425\u8193\u442D\u81A5\u57EF\u81C1\u81E4\u8254\u448F\u82A6\u8276\u82CA\u82D8\u82FF\u44B0\u8357\u9669\u698A\u8405\u70F5\u8464\u60E3\u8488\u4504\u84BE\u84E1\u84F8\u8510\u8538\u8552\u453B\u856F\u8570\u85E0\u4577\u8672\u8692\u86B2\u86EF\u9645\u878B\u4606\u4617\u88AE\u88FF\u8924\u8947\u8991\u{27967}\u8A29\u8A38\u8A94\u8AB4\u8C51\u8CD4\u8CF2\u8D1C\u4798\u585F\u8DC3\u47ED\u4EEE\u8E3A\u55D8\u5754\u8E71\u55F5\u8EB0\u4837\u8ECE\u8EE2\u8EE4\u8EED\u8EF2\u8FB7\u8FC1\u8FCA\u8FCC\u9033\u99C4\u48AD\u98E0\u9213\u491E\u9228\u9258\u926B\u92B1\u92AE\u92BF"], - ["9a40", "\u92E3\u92EB\u92F3\u92F4\u92FD\u9343\u9384\u93AD\u4945\u4951\u9EBF\u9417\u5301\u941D\u942D\u943E\u496A\u9454\u9479\u952D\u95A2\u49A7\u95F4\u9633\u49E5\u67A0\u4A24\u9740\u4A35\u97B2\u97C2\u5654\u4AE4\u60E8\u98B9\u4B19\u98F1\u5844\u990E\u9919\u51B4\u991C\u9937\u9942\u995D\u9962\u4B70\u99C5\u4B9D\u9A3C\u9B0F\u7A83\u9B69\u9B81\u9BDD\u9BF1\u9BF4\u4C6D\u9C20\u376F\u{21BC2}\u9D49\u9C3A"], - ["9aa1", "\u9EFE\u5650\u9D93\u9DBD\u9DC0\u9DFC\u94F6\u8FB6\u9E7B\u9EAC\u9EB1\u9EBD\u9EC6\u94DC\u9EE2\u9EF1\u9EF8\u7AC8\u9F44\u{20094}\u{202B7}\u{203A0}\u691A\u94C3\u59AC\u{204D7}\u5840\u94C1\u37B9\u{205D5}\u{20615}\u{20676}\u{216BA}\u5757\u7173\u{20AC2}\u{20ACD}\u{20BBF}\u546A\u{2F83B}\u{20BCB}\u549E\u{20BFB}\u{20C3B}\u{20C53}\u{20C65}\u{20C7C}\u60E7\u{20C8D}\u567A\u{20CB5}\u{20CDD}\u{20CED}\u{20D6F}\u{20DB2}\u{20DC8}\u6955\u9C2F\u87A5\u{20E04}\u{20E0E}\u{20ED7}\u{20F90}\u{20F2D}\u{20E73}\u5C20\u{20FBC}\u5E0B\u{2105C}\u{2104F}\u{21076}\u671E\u{2107B}\u{21088}\u{21096}\u3647\u{210BF}\u{210D3}\u{2112F}\u{2113B}\u5364\u84AD\u{212E3}\u{21375}\u{21336}\u8B81\u{21577}\u{21619}\u{217C3}\u{217C7}\u4E78\u70BB\u{2182D}\u{2196A}"], - ["9b40", "\u{21A2D}\u{21A45}\u{21C2A}\u{21C70}\u{21CAC}\u{21EC8}\u62C3\u{21ED5}\u{21F15}\u7198\u6855\u{22045}\u69E9\u36C8\u{2227C}\u{223D7}\u{223FA}\u{2272A}\u{22871}\u{2294F}\u82FD\u{22967}\u{22993}\u{22AD5}\u89A5\u{22AE8}\u8FA0\u{22B0E}\u97B8\u{22B3F}\u9847\u9ABD\u{22C4C}"], - ["9b62", "\u{22C88}\u{22CB7}\u{25BE8}\u{22D08}\u{22D12}\u{22DB7}\u{22D95}\u{22E42}\u{22F74}\u{22FCC}\u{23033}\u{23066}\u{2331F}\u{233DE}\u5FB1\u6648\u66BF\u{27A79}\u{23567}\u{235F3}\u7201\u{249BA}\u77D7\u{2361A}\u{23716}\u7E87\u{20346}\u58B5\u670E"], - ["9ba1", "\u6918\u{23AA7}\u{27657}\u{25FE2}\u{23E11}\u{23EB9}\u{275FE}\u{2209A}\u48D0\u4AB8\u{24119}\u{28A9A}\u{242EE}\u{2430D}\u{2403B}\u{24334}\u{24396}\u{24A45}\u{205CA}\u51D2\u{20611}\u599F\u{21EA8}\u3BBE\u{23CFF}\u{24404}\u{244D6}\u5788\u{24674}\u399B\u{2472F}\u{285E8}\u{299C9}\u3762\u{221C3}\u8B5E\u{28B4E}\u99D6\u{24812}\u{248FB}\u{24A15}\u7209\u{24AC0}\u{20C78}\u5965\u{24EA5}\u{24F86}\u{20779}\u8EDA\u{2502C}\u528F\u573F\u7171\u{25299}\u{25419}\u{23F4A}\u{24AA7}\u55BC\u{25446}\u{2546E}\u{26B52}\u91D4\u3473\u{2553F}\u{27632}\u{2555E}\u4718\u{25562}\u{25566}\u{257C7}\u{2493F}\u{2585D}\u5066\u34FB\u{233CC}\u60DE\u{25903}\u477C\u{28948}\u{25AAE}\u{25B89}\u{25C06}\u{21D90}\u57A1\u7151\u6FB6\u{26102}\u{27C12}\u9056\u{261B2}\u{24F9A}\u8B62\u{26402}\u{2644A}"], - ["9c40", "\u5D5B\u{26BF7}\u8F36\u{26484}\u{2191C}\u8AEA\u{249F6}\u{26488}\u{23FEF}\u{26512}\u4BC0\u{265BF}\u{266B5}\u{2271B}\u9465\u{257E1}\u6195\u5A27\u{2F8CD}\u4FBB\u56B9\u{24521}\u{266FC}\u4E6A\u{24934}\u9656\u6D8F\u{26CBD}\u3618\u8977\u{26799}\u{2686E}\u{26411}\u{2685E}\u71DF\u{268C7}\u7B42\u{290C0}\u{20A11}\u{26926}\u9104\u{26939}\u7A45\u9DF0\u{269FA}\u9A26\u{26A2D}\u365F\u{26469}\u{20021}\u7983\u{26A34}\u{26B5B}\u5D2C\u{23519}\u83CF\u{26B9D}\u46D0\u{26CA4}\u753B\u8865\u{26DAE}\u58B6"], - ["9ca1", "\u371C\u{2258D}\u{2704B}\u{271CD}\u3C54\u{27280}\u{27285}\u9281\u{2217A}\u{2728B}\u9330\u{272E6}\u{249D0}\u6C39\u949F\u{27450}\u{20EF8}\u8827\u88F5\u{22926}\u{28473}\u{217B1}\u6EB8\u{24A2A}\u{21820}\u39A4\u36B9\u5C10\u79E3\u453F\u66B6\u{29CAD}\u{298A4}\u8943\u{277CC}\u{27858}\u56D6\u40DF\u{2160A}\u39A1\u{2372F}\u{280E8}\u{213C5}\u71AD\u8366\u{279DD}\u{291A8}\u5A67\u4CB7\u{270AF}\u{289AB}\u{279FD}\u{27A0A}\u{27B0B}\u{27D66}\u{2417A}\u7B43\u797E\u{28009}\u6FB5\u{2A2DF}\u6A03\u{28318}\u53A2\u{26E07}\u93BF\u6836\u975D\u{2816F}\u{28023}\u{269B5}\u{213ED}\u{2322F}\u{28048}\u5D85\u{28C30}\u{28083}\u5715\u9823\u{28949}\u5DAB\u{24988}\u65BE\u69D5\u53D2\u{24AA5}\u{23F81}\u3C11\u6736\u{28090}\u{280F4}\u{2812E}\u{21FA1}\u{2814F}"], - ["9d40", "\u{28189}\u{281AF}\u{2821A}\u{28306}\u{2832F}\u{2838A}\u35CA\u{28468}\u{286AA}\u48FA\u63E6\u{28956}\u7808\u9255\u{289B8}\u43F2\u{289E7}\u43DF\u{289E8}\u{28B46}\u{28BD4}\u59F8\u{28C09}\u8F0B\u{28FC5}\u{290EC}\u7B51\u{29110}\u{2913C}\u3DF7\u{2915E}\u{24ACA}\u8FD0\u728F\u568B\u{294E7}\u{295E9}\u{295B0}\u{295B8}\u{29732}\u{298D1}\u{29949}\u{2996A}\u{299C3}\u{29A28}\u{29B0E}\u{29D5A}\u{29D9B}\u7E9F\u{29EF8}\u{29F23}\u4CA4\u9547\u{2A293}\u71A2\u{2A2FF}\u4D91\u9012\u{2A5CB}\u4D9C\u{20C9C}\u8FBE\u55C1"], - ["9da1", "\u8FBA\u{224B0}\u8FB9\u{24A93}\u4509\u7E7F\u6F56\u6AB1\u4EEA\u34E4\u{28B2C}\u{2789D}\u373A\u8E80\u{217F5}\u{28024}\u{28B6C}\u{28B99}\u{27A3E}\u{266AF}\u3DEB\u{27655}\u{23CB7}\u{25635}\u{25956}\u4E9A\u{25E81}\u{26258}\u56BF\u{20E6D}\u8E0E\u5B6D\u{23E88}\u{24C9E}\u63DE\u62D0\u{217F6}\u{2187B}\u6530\u562D\u{25C4A}\u541A\u{25311}\u3DC6\u{29D98}\u4C7D\u5622\u561E\u7F49\u{25ED8}\u5975\u{23D40}\u8770\u4E1C\u{20FEA}\u{20D49}\u{236BA}\u8117\u9D5E\u8D18\u763B\u9C45\u764E\u77B9\u9345\u5432\u8148\u82F7\u5625\u8132\u8418\u80BD\u55EA\u7962\u5643\u5416\u{20E9D}\u35CE\u5605\u55F1\u66F1\u{282E2}\u362D\u7534\u55F0\u55BA\u5497\u5572\u{20C41}\u{20C96}\u5ED0\u{25148}\u{20E76}\u{22C62}"], - ["9e40", "\u{20EA2}\u9EAB\u7D5A\u55DE\u{21075}\u629D\u976D\u5494\u8CCD\u71F6\u9176\u63FC\u63B9\u63FE\u5569\u{22B43}\u9C72\u{22EB3}\u519A\u34DF\u{20DA7}\u51A7\u544D\u551E\u5513\u7666\u8E2D\u{2688A}\u75B1\u80B6\u8804\u8786\u88C7\u81B6\u841C\u{210C1}\u44EC\u7304\u{24706}\u5B90\u830B\u{26893}\u567B\u{226F4}\u{27D2F}\u{241A3}\u{27D73}\u{26ED0}\u{272B6}\u9170\u{211D9}\u9208\u{23CFC}\u{2A6A9}\u{20EAC}\u{20EF9}\u7266\u{21CA2}\u474E\u{24FC2}\u{27FF9}\u{20FEB}\u40FA"], - ["9ea1", "\u9C5D\u651F\u{22DA0}\u48F3\u{247E0}\u{29D7C}\u{20FEC}\u{20E0A}\u6062\u{275A3}\u{20FED}"], - ["9ead", "\u{26048}\u{21187}\u71A3\u7E8E\u9D50\u4E1A\u4E04\u3577\u5B0D\u6CB2\u5367\u36AC\u39DC\u537D\u36A5\u{24618}\u589A\u{24B6E}\u822D\u544B\u57AA\u{25A95}\u{20979}"], - ["9ec5", "\u3A52\u{22465}\u7374\u{29EAC}\u4D09\u9BED\u{23CFE}\u{29F30}\u4C5B\u{24FA9}\u{2959E}\u{29FDE}\u845C\u{23DB6}\u{272B2}\u{267B3}\u{23720}\u632E\u7D25\u{23EF7}\u{23E2C}\u3A2A\u9008\u52CC\u3E74\u367A\u45E9\u{2048E}\u7640\u5AF0\u{20EB6}\u787A\u{27F2E}\u58A7\u40BF\u567C\u9B8B\u5D74\u7654\u{2A434}\u9E85\u4CE1\u75F9\u37FB\u6119\u{230DA}\u{243F2}"], - ["9ef5", "\u565D\u{212A9}\u57A7\u{24963}\u{29E06}\u5234\u{270AE}\u35AD\u6C4A\u9D7C"], - ["9f40", "\u7C56\u9B39\u57DE\u{2176C}\u5C53\u64D3\u{294D0}\u{26335}\u{27164}\u86AD\u{20D28}\u{26D22}\u{24AE2}\u{20D71}"], - ["9f4f", "\u51FE\u{21F0F}\u5D8E\u9703\u{21DD1}\u9E81\u904C\u7B1F\u9B02\u5CD1\u7BA3\u6268\u6335\u9AFF\u7BCF\u9B2A\u7C7E\u9B2E\u7C42\u7C86\u9C15\u7BFC\u9B09\u9F17\u9C1B\u{2493E}\u9F5A\u5573\u5BC3\u4FFD\u9E98\u4FF2\u5260\u3E06\u52D1\u5767\u5056\u59B7\u5E12\u97C8\u9DAB\u8F5C\u5469\u97B4\u9940\u97BA\u532C\u6130"], - ["9fa1", "\u692C\u53DA\u9C0A\u9D02\u4C3B\u9641\u6980\u50A6\u7546\u{2176D}\u99DA\u5273"], - ["9fae", "\u9159\u9681\u915C"], - ["9fb2", "\u9151\u{28E97}\u637F\u{26D23}\u6ACA\u5611\u918E\u757A\u6285\u{203FC}\u734F\u7C70\u{25C21}\u{23CFD}"], - ["9fc1", "\u{24919}\u76D6\u9B9D\u4E2A\u{20CD4}\u83BE\u8842"], - ["9fc9", "\u5C4A\u69C0\u50ED\u577A\u521F\u5DF5\u4ECE\u6C31\u{201F2}\u4F39\u549C\u54DA\u529A\u8D82\u35FE\u5F0C\u35F3"], - ["9fdb", "\u6B52\u917C\u9FA5\u9B97\u982E\u98B4\u9ABA\u9EA8\u9E84\u717A\u7B14"], - ["9fe7", "\u6BFA\u8818\u7F78"], - ["9feb", "\u5620\u{2A64A}\u8E77\u9F53"], - ["9ff0", "\u8DD4\u8E4F\u9E1C\u8E01\u6282\u{2837D}\u8E28\u8E75\u7AD3\u{24A77}\u7A3E\u78D8\u6CEA\u8A67\u7607"], - ["a040", "\u{28A5A}\u9F26\u6CCE\u87D6\u75C3\u{2A2B2}\u7853\u{2F840}\u8D0C\u72E2\u7371\u8B2D\u7302\u74F1\u8CEB\u{24ABB}\u862F\u5FBA\u88A0\u44B7"], - ["a055", "\u{2183B}\u{26E05}"], - ["a058", "\u8A7E\u{2251B}"], - ["a05b", "\u60FD\u7667\u9AD7\u9D44\u936E\u9B8F\u87F5"], - ["a063", "\u880F\u8CF7\u732C\u9721\u9BB0\u35D6\u72B2\u4C07\u7C51\u994A\u{26159}\u6159\u4C04\u9E96\u617D"], - ["a073", "\u575F\u616F\u62A6\u6239\u62CE\u3A5C\u61E2\u53AA\u{233F5}\u6364\u6802\u35D2"], - ["a0a1", "\u5D57\u{28BC2}\u8FDA\u{28E39}"], - ["a0a6", "\u50D9\u{21D46}\u7906\u5332\u9638\u{20F3B}\u4065"], - ["a0ae", "\u77FE"], - ["a0b0", "\u7CC2\u{25F1A}\u7CDA\u7A2D\u8066\u8063\u7D4D\u7505\u74F2\u8994\u821A\u670C\u8062\u{27486}\u805B\u74F0\u8103\u7724\u8989\u{267CC}\u7553\u{26ED1}\u87A9\u87CE\u81C8\u878C\u8A49\u8CAD\u8B43\u772B\u74F8\u84DA\u3635\u69B2\u8DA6"], - ["a0d4", "\u89A9\u7468\u6DB9\u87C1\u{24011}\u74E7\u3DDB\u7176\u60A4\u619C\u3CD1\u7162\u6077"], - ["a0e2", "\u7F71\u{28B2D}\u7250\u60E9\u4B7E\u5220\u3C18\u{23CC7}\u{25ED7}\u{27656}\u{25531}\u{21944}\u{212FE}\u{29903}\u{26DDC}\u{270AD}\u5CC1\u{261AD}\u{28A0F}\u{23677}\u{200EE}\u{26846}\u{24F0E}\u4562\u5B1F\u{2634C}\u9F50\u9EA6\u{2626B}"], - ["a3c0", "\u2400", 31, "\u2421"], - ["c6a1", "\u2460", 9, "\u2474", 9, "\u2170", 9, "\u4E36\u4E3F\u4E85\u4EA0\u5182\u5196\u51AB\u52F9\u5338\u5369\u53B6\u590A\u5B80\u5DDB\u2F33\u5E7F\u5EF4\u5F50\u5F61\u6534\u65E0\u7592\u7676\u8FB5\u96B6\xA8\u02C6\u30FD\u30FE\u309D\u309E\u3003\u4EDD\u3005\u3006\u3007\u30FC\uFF3B\uFF3D\u273D\u3041", 23], - ["c740", "\u3059", 58, "\u30A1\u30A2\u30A3\u30A4"], - ["c7a1", "\u30A5", 81, "\u0410", 5, "\u0401\u0416", 4], - ["c840", "\u041B", 26, "\u0451\u0436", 25, "\u21E7\u21B8\u21B9\u31CF\u{200CC}\u4E5A\u{2008A}\u5202\u4491"], - ["c8a1", "\u9FB0\u5188\u9FB1\u{27607}"], - ["c8cd", "\uFFE2\uFFE4\uFF07\uFF02\u3231\u2116\u2121\u309B\u309C\u2E80\u2E84\u2E86\u2E87\u2E88\u2E8A\u2E8C\u2E8D\u2E95\u2E9C\u2E9D\u2EA5\u2EA7\u2EAA\u2EAC\u2EAE\u2EB6\u2EBC\u2EBE\u2EC6\u2ECA\u2ECC\u2ECD\u2ECF\u2ED6\u2ED7\u2EDE\u2EE3"], - ["c8f5", "\u0283\u0250\u025B\u0254\u0275\u0153\xF8\u014B\u028A\u026A"], - ["f9fe", "\uFFED"], - ["fa40", "\u{20547}\u92DB\u{205DF}\u{23FC5}\u854C\u42B5\u73EF\u51B5\u3649\u{24942}\u{289E4}\u9344\u{219DB}\u82EE\u{23CC8}\u783C\u6744\u62DF\u{24933}\u{289AA}\u{202A0}\u{26BB3}\u{21305}\u4FAB\u{224ED}\u5008\u{26D29}\u{27A84}\u{23600}\u{24AB1}\u{22513}\u5029\u{2037E}\u5FA4\u{20380}\u{20347}\u6EDB\u{2041F}\u507D\u5101\u347A\u510E\u986C\u3743\u8416\u{249A4}\u{20487}\u5160\u{233B4}\u516A\u{20BFF}\u{220FC}\u{202E5}\u{22530}\u{2058E}\u{23233}\u{21983}\u5B82\u877D\u{205B3}\u{23C99}\u51B2\u51B8"], - ["faa1", "\u9D34\u51C9\u51CF\u51D1\u3CDC\u51D3\u{24AA6}\u51B3\u51E2\u5342\u51ED\u83CD\u693E\u{2372D}\u5F7B\u520B\u5226\u523C\u52B5\u5257\u5294\u52B9\u52C5\u7C15\u8542\u52E0\u860D\u{26B13}\u5305\u{28ADE}\u5549\u6ED9\u{23F80}\u{20954}\u{23FEC}\u5333\u5344\u{20BE2}\u6CCB\u{21726}\u681B\u73D5\u604A\u3EAA\u38CC\u{216E8}\u71DD\u44A2\u536D\u5374\u{286AB}\u537E\u537F\u{21596}\u{21613}\u77E6\u5393\u{28A9B}\u53A0\u53AB\u53AE\u73A7\u{25772}\u3F59\u739C\u53C1\u53C5\u6C49\u4E49\u57FE\u53D9\u3AAB\u{20B8F}\u53E0\u{23FEB}\u{22DA3}\u53F6\u{20C77}\u5413\u7079\u552B\u6657\u6D5B\u546D\u{26B53}\u{20D74}\u555D\u548F\u54A4\u47A6\u{2170D}\u{20EDD}\u3DB4\u{20D4D}"], - ["fb40", "\u{289BC}\u{22698}\u5547\u4CED\u542F\u7417\u5586\u55A9\u5605\u{218D7}\u{2403A}\u4552\u{24435}\u66B3\u{210B4}\u5637\u66CD\u{2328A}\u66A4\u66AD\u564D\u564F\u78F1\u56F1\u9787\u53FE\u5700\u56EF\u56ED\u{28B66}\u3623\u{2124F}\u5746\u{241A5}\u6C6E\u708B\u5742\u36B1\u{26C7E}\u57E6\u{21416}\u5803\u{21454}\u{24363}\u5826\u{24BF5}\u585C\u58AA\u3561\u58E0\u58DC\u{2123C}\u58FB\u5BFF\u5743\u{2A150}\u{24278}\u93D3\u35A1\u591F\u68A6\u36C3\u6E59"], - ["fba1", "\u{2163E}\u5A24\u5553\u{21692}\u8505\u59C9\u{20D4E}\u{26C81}\u{26D2A}\u{217DC}\u59D9\u{217FB}\u{217B2}\u{26DA6}\u6D71\u{21828}\u{216D5}\u59F9\u{26E45}\u5AAB\u5A63\u36E6\u{249A9}\u5A77\u3708\u5A96\u7465\u5AD3\u{26FA1}\u{22554}\u3D85\u{21911}\u3732\u{216B8}\u5E83\u52D0\u5B76\u6588\u5B7C\u{27A0E}\u4004\u485D\u{20204}\u5BD5\u6160\u{21A34}\u{259CC}\u{205A5}\u5BF3\u5B9D\u4D10\u5C05\u{21B44}\u5C13\u73CE\u5C14\u{21CA5}\u{26B28}\u5C49\u48DD\u5C85\u5CE9\u5CEF\u5D8B\u{21DF9}\u{21E37}\u5D10\u5D18\u5D46\u{21EA4}\u5CBA\u5DD7\u82FC\u382D\u{24901}\u{22049}\u{22173}\u8287\u3836\u3BC2\u5E2E\u6A8A\u5E75\u5E7A\u{244BC}\u{20CD3}\u53A6\u4EB7\u5ED0\u53A8\u{21771}\u5E09\u5EF4\u{28482}"], - ["fc40", "\u5EF9\u5EFB\u38A0\u5EFC\u683E\u941B\u5F0D\u{201C1}\u{2F894}\u3ADE\u48AE\u{2133A}\u5F3A\u{26888}\u{223D0}\u5F58\u{22471}\u5F63\u97BD\u{26E6E}\u5F72\u9340\u{28A36}\u5FA7\u5DB6\u3D5F\u{25250}\u{21F6A}\u{270F8}\u{22668}\u91D6\u{2029E}\u{28A29}\u6031\u6685\u{21877}\u3963\u3DC7\u3639\u5790\u{227B4}\u7971\u3E40\u609E\u60A4\u60B3\u{24982}\u{2498F}\u{27A53}\u74A4\u50E1\u5AA0\u6164\u8424\u6142\u{2F8A6}\u{26ED2}\u6181\u51F4\u{20656}\u6187\u5BAA\u{23FB7}"], - ["fca1", "\u{2285F}\u61D3\u{28B9D}\u{2995D}\u61D0\u3932\u{22980}\u{228C1}\u6023\u615C\u651E\u638B\u{20118}\u62C5\u{21770}\u62D5\u{22E0D}\u636C\u{249DF}\u3A17\u6438\u63F8\u{2138E}\u{217FC}\u6490\u6F8A\u{22E36}\u9814\u{2408C}\u{2571D}\u64E1\u64E5\u947B\u3A66\u643A\u3A57\u654D\u6F16\u{24A28}\u{24A23}\u6585\u656D\u655F\u{2307E}\u65B5\u{24940}\u4B37\u65D1\u40D8\u{21829}\u65E0\u65E3\u5FDF\u{23400}\u6618\u{231F7}\u{231F8}\u6644\u{231A4}\u{231A5}\u664B\u{20E75}\u6667\u{251E6}\u6673\u6674\u{21E3D}\u{23231}\u{285F4}\u{231C8}\u{25313}\u77C5\u{228F7}\u99A4\u6702\u{2439C}\u{24A21}\u3B2B\u69FA\u{237C2}\u675E\u6767\u6762\u{241CD}\u{290ED}\u67D7\u44E9\u6822\u6E50\u923C\u6801\u{233E6}\u{26DA0}\u685D"], - ["fd40", "\u{2346F}\u69E1\u6A0B\u{28ADF}\u6973\u68C3\u{235CD}\u6901\u6900\u3D32\u3A01\u{2363C}\u3B80\u67AC\u6961\u{28A4A}\u42FC\u6936\u6998\u3BA1\u{203C9}\u8363\u5090\u69F9\u{23659}\u{2212A}\u6A45\u{23703}\u6A9D\u3BF3\u67B1\u6AC8\u{2919C}\u3C0D\u6B1D\u{20923}\u60DE\u6B35\u6B74\u{227CD}\u6EB5\u{23ADB}\u{203B5}\u{21958}\u3740\u5421\u{23B5A}\u6BE1\u{23EFC}\u6BDC\u6C37\u{2248B}\u{248F1}\u{26B51}\u6C5A\u8226\u6C79\u{23DBC}\u44C5\u{23DBD}\u{241A4}\u{2490C}\u{24900}"], - ["fda1", "\u{23CC9}\u36E5\u3CEB\u{20D32}\u9B83\u{231F9}\u{22491}\u7F8F\u6837\u{26D25}\u{26DA1}\u{26DEB}\u6D96\u6D5C\u6E7C\u6F04\u{2497F}\u{24085}\u{26E72}\u8533\u{26F74}\u51C7\u6C9C\u6E1D\u842E\u{28B21}\u6E2F\u{23E2F}\u7453\u{23F82}\u79CC\u6E4F\u5A91\u{2304B}\u6FF8\u370D\u6F9D\u{23E30}\u6EFA\u{21497}\u{2403D}\u4555\u93F0\u6F44\u6F5C\u3D4E\u6F74\u{29170}\u3D3B\u6F9F\u{24144}\u6FD3\u{24091}\u{24155}\u{24039}\u{23FF0}\u{23FB4}\u{2413F}\u51DF\u{24156}\u{24157}\u{24140}\u{261DD}\u704B\u707E\u70A7\u7081\u70CC\u70D5\u70D6\u70DF\u4104\u3DE8\u71B4\u7196\u{24277}\u712B\u7145\u5A88\u714A\u716E\u5C9C\u{24365}\u714F\u9362\u{242C1}\u712C\u{2445A}\u{24A27}\u{24A22}\u71BA\u{28BE8}\u70BD\u720E"], - ["fe40", "\u9442\u7215\u5911\u9443\u7224\u9341\u{25605}\u722E\u7240\u{24974}\u68BD\u7255\u7257\u3E55\u{23044}\u680D\u6F3D\u7282\u732A\u732B\u{24823}\u{2882B}\u48ED\u{28804}\u7328\u732E\u73CF\u73AA\u{20C3A}\u{26A2E}\u73C9\u7449\u{241E2}\u{216E7}\u{24A24}\u6623\u36C5\u{249B7}\u{2498D}\u{249FB}\u73F7\u7415\u6903\u{24A26}\u7439\u{205C3}\u3ED7\u745C\u{228AD}\u7460\u{28EB2}\u7447\u73E4\u7476\u83B9\u746C\u3730\u7474\u93F1\u6A2C\u7482\u4953\u{24A8C}"], - ["fea1", "\u{2415F}\u{24A79}\u{28B8F}\u5B46\u{28C03}\u{2189E}\u74C8\u{21988}\u750E\u74E9\u751E\u{28ED9}\u{21A4B}\u5BD7\u{28EAC}\u9385\u754D\u754A\u7567\u756E\u{24F82}\u3F04\u{24D13}\u758E\u745D\u759E\u75B4\u7602\u762C\u7651\u764F\u766F\u7676\u{263F5}\u7690\u81EF\u37F8\u{26911}\u{2690E}\u76A1\u76A5\u76B7\u76CC\u{26F9F}\u8462\u{2509D}\u{2517D}\u{21E1C}\u771E\u7726\u7740\u64AF\u{25220}\u7758\u{232AC}\u77AF\u{28964}\u{28968}\u{216C1}\u77F4\u7809\u{21376}\u{24A12}\u68CA\u78AF\u78C7\u78D3\u96A5\u792E\u{255E0}\u78D7\u7934\u78B1\u{2760C}\u8FB8\u8884\u{28B2B}\u{26083}\u{2261C}\u7986\u8900\u6902\u7980\u{25857}\u799D\u{27B39}\u793C\u79A9\u6E2A\u{27126}\u3EA8\u79C6\u{2910D}\u79D4"] - ]; - } -}); - -// node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/encodings/dbcs-data.js -var require_dbcs_data = __commonJS({ - "node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/encodings/dbcs-data.js"(exports, module) { - "use strict"; - module.exports = { - // == Japanese/ShiftJIS ==================================================== - // All japanese encodings are based on JIS X set of standards: - // JIS X 0201 - Single-byte encoding of ASCII + ¥ + Kana chars at 0xA1-0xDF. - // JIS X 0208 - Main set of 6879 characters, placed in 94x94 plane, to be encoded by 2 bytes. - // Has several variations in 1978, 1983, 1990 and 1997. - // JIS X 0212 - Supplementary plane of 6067 chars in 94x94 plane. 1990. Effectively dead. - // JIS X 0213 - Extension and modern replacement of 0208 and 0212. Total chars: 11233. - // 2 planes, first is superset of 0208, second - revised 0212. - // Introduced in 2000, revised 2004. Some characters are in Unicode Plane 2 (0x2xxxx) - // Byte encodings are: - // * Shift_JIS: Compatible with 0201, uses not defined chars in top half as lead bytes for double-byte - // encoding of 0208. Lead byte ranges: 0x81-0x9F, 0xE0-0xEF; Trail byte ranges: 0x40-0x7E, 0x80-0x9E, 0x9F-0xFC. - // Windows CP932 is a superset of Shift_JIS. Some companies added more chars, notably KDDI. - // * EUC-JP: Up to 3 bytes per character. Used mostly on *nixes. - // 0x00-0x7F - lower part of 0201 - // 0x8E, 0xA1-0xDF - upper part of 0201 - // (0xA1-0xFE)x2 - 0208 plane (94x94). - // 0x8F, (0xA1-0xFE)x2 - 0212 plane (94x94). - // * JIS X 208: 7-bit, direct encoding of 0208. Byte ranges: 0x21-0x7E (94 values). Uncommon. - // Used as-is in ISO2022 family. - // * ISO2022-JP: Stateful encoding, with escape sequences to switch between ASCII, - // 0201-1976 Roman, 0208-1978, 0208-1983. - // * ISO2022-JP-1: Adds esc seq for 0212-1990. - // * ISO2022-JP-2: Adds esc seq for GB2313-1980, KSX1001-1992, ISO8859-1, ISO8859-7. - // * ISO2022-JP-3: Adds esc seq for 0201-1976 Kana set, 0213-2000 Planes 1, 2. - // * ISO2022-JP-2004: Adds 0213-2004 Plane 1. - // - // After JIS X 0213 appeared, Shift_JIS-2004, EUC-JISX0213 and ISO2022-JP-2004 followed, with just changing the planes. - // - // Overall, it seems that it's a mess :( http://www8.plala.or.jp/tkubota1/unicode-symbols-map2.html - shiftjis: { - type: "_dbcs", - table: function() { - return require_shiftjis(); - }, - encodeAdd: { "\xA5": 92, "\u203E": 126 }, - encodeSkipVals: [{ from: 60736, to: 63808 }] - }, - csshiftjis: "shiftjis", - mskanji: "shiftjis", - sjis: "shiftjis", - windows31j: "shiftjis", - ms31j: "shiftjis", - xsjis: "shiftjis", - windows932: "shiftjis", - ms932: "shiftjis", - 932: "shiftjis", - cp932: "shiftjis", - eucjp: { - type: "_dbcs", - table: function() { - return require_eucjp(); - }, - encodeAdd: { "\xA5": 92, "\u203E": 126 } - }, - // TODO: KDDI extension to Shift_JIS - // TODO: IBM CCSID 942 = CP932, but F0-F9 custom chars and other char changes. - // TODO: IBM CCSID 943 = Shift_JIS = CP932 with original Shift_JIS lower 128 chars. - // == Chinese/GBK ========================================================== - // http://en.wikipedia.org/wiki/GBK - // We mostly implement W3C recommendation: https://www.w3.org/TR/encoding/#gbk-encoder - // Oldest GB2312 (1981, ~7600 chars) is a subset of CP936 - gb2312: "cp936", - gb231280: "cp936", - gb23121980: "cp936", - csgb2312: "cp936", - csiso58gb231280: "cp936", - euccn: "cp936", - // Microsoft's CP936 is a subset and approximation of GBK. - windows936: "cp936", - ms936: "cp936", - 936: "cp936", - cp936: { - type: "_dbcs", - table: function() { - return require_cp936(); - } - }, - // GBK (~22000 chars) is an extension of CP936 that added user-mapped chars and some other. - gbk: { - type: "_dbcs", - table: function() { - return require_cp936().concat(require_gbk_added()); - } - }, - xgbk: "gbk", - isoir58: "gbk", - // GB18030 is an algorithmic extension of GBK. - // Main source: https://www.w3.org/TR/encoding/#gbk-encoder - // http://icu-project.org/docs/papers/gb18030.html - // http://source.icu-project.org/repos/icu/data/trunk/charset/data/xml/gb-18030-2000.xml - // http://www.khngai.com/chinese/charmap/tblgbk.php?page=0 - gb18030: { - type: "_dbcs", - table: function() { - return require_cp936().concat(require_gbk_added()); - }, - gb18030: function() { - return require_gb18030_ranges(); - }, - encodeSkipVals: [128], - encodeAdd: { "\u20AC": 41699 } - }, - chinese: "gb18030", - // == Korean =============================================================== - // EUC-KR, KS_C_5601 and KS X 1001 are exactly the same. - windows949: "cp949", - ms949: "cp949", - 949: "cp949", - cp949: { - type: "_dbcs", - table: function() { - return require_cp949(); - } - }, - cseuckr: "cp949", - csksc56011987: "cp949", - euckr: "cp949", - isoir149: "cp949", - korean: "cp949", - ksc56011987: "cp949", - ksc56011989: "cp949", - ksc5601: "cp949", - // == Big5/Taiwan/Hong Kong ================================================ - // There are lots of tables for Big5 and cp950. Please see the following links for history: - // http://moztw.org/docs/big5/ http://www.haible.de/bruno/charsets/conversion-tables/Big5.html - // Variations, in roughly number of defined chars: - // * Windows CP 950: Microsoft variant of Big5. Canonical: http://www.unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WINDOWS/CP950.TXT - // * Windows CP 951: Microsoft variant of Big5-HKSCS-2001. Seems to be never public. http://me.abelcheung.org/articles/research/what-is-cp951/ - // * Big5-2003 (Taiwan standard) almost superset of cp950. - // * Unicode-at-on (UAO) / Mozilla 1.8. Falling out of use on the Web. Not supported by other browsers. - // * Big5-HKSCS (-2001, -2004, -2008). Hong Kong standard. - // many unicode code points moved from PUA to Supplementary plane (U+2XXXX) over the years. - // Plus, it has 4 combining sequences. - // Seems that Mozilla refused to support it for 10 yrs. https://bugzilla.mozilla.org/show_bug.cgi?id=162431 https://bugzilla.mozilla.org/show_bug.cgi?id=310299 - // because big5-hkscs is the only encoding to include astral characters in non-algorithmic way. - // Implementations are not consistent within browsers; sometimes labeled as just big5. - // MS Internet Explorer switches from big5 to big5-hkscs when a patch applied. - // Great discussion & recap of what's going on https://bugzilla.mozilla.org/show_bug.cgi?id=912470#c31 - // In the encoder, it might make sense to support encoding old PUA mappings to Big5 bytes seq-s. - // Official spec: http://www.ogcio.gov.hk/en/business/tech_promotion/ccli/terms/doc/2003cmp_2008.txt - // http://www.ogcio.gov.hk/tc/business/tech_promotion/ccli/terms/doc/hkscs-2008-big5-iso.txt - // - // Current understanding of how to deal with Big5(-HKSCS) is in the Encoding Standard, http://encoding.spec.whatwg.org/#big5-encoder - // Unicode mapping (http://www.unicode.org/Public/MAPPINGS/OBSOLETE/EASTASIA/OTHER/BIG5.TXT) is said to be wrong. - windows950: "cp950", - ms950: "cp950", - 950: "cp950", - cp950: { - type: "_dbcs", - table: function() { - return require_cp950(); - } - }, - // Big5 has many variations and is an extension of cp950. We use Encoding Standard's as a consensus. - big5: "big5hkscs", - big5hkscs: { - type: "_dbcs", - table: function() { - return require_cp950().concat(require_big5_added()); - }, - encodeSkipVals: [ - // Although Encoding Standard says we should avoid encoding to HKSCS area (See Step 1 of - // https://encoding.spec.whatwg.org/#index-big5-pointer), we still do it to increase compatibility with ICU. - // But if a single unicode point can be encoded both as HKSCS and regular Big5, we prefer the latter. - 36457, - 36463, - 36478, - 36523, - 36532, - 36557, - 36560, - 36695, - 36713, - 36718, - 36811, - 36862, - 36973, - 36986, - 37060, - 37084, - 37105, - 37311, - 37551, - 37552, - 37553, - 37554, - 37585, - 37959, - 38090, - 38361, - 38652, - 39285, - 39798, - 39800, - 39803, - 39878, - 39902, - 39916, - 39926, - 40002, - 40019, - 40034, - 40040, - 40043, - 40055, - 40124, - 40125, - 40144, - 40279, - 40282, - 40388, - 40431, - 40443, - 40617, - 40687, - 40701, - 40800, - 40907, - 41079, - 41180, - 41183, - 36812, - 37576, - 38468, - 38637, - // Step 2 of https://encoding.spec.whatwg.org/#index-big5-pointer: Use last pointer for U+2550, U+255E, U+2561, U+256A, U+5341, or U+5345 - 41636, - 41637, - 41639, - 41638, - 41676, - 41678 - ] - }, - cnbig5: "big5hkscs", - csbig5: "big5hkscs", - xxbig5: "big5hkscs" - }; - } -}); - -// node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/encodings/index.js -var require_encodings = __commonJS({ - "node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/encodings/index.js"(exports, module) { - "use strict"; - var mergeModules = require_merge_exports(); - var modules = [ - require_internal(), - require_utf32(), - require_utf16(), - require_utf7(), - require_sbcs_codec(), - require_sbcs_data(), - require_sbcs_data_generated(), - require_dbcs_codec(), - require_dbcs_data() - ]; - for (i5 = 0; i5 < modules.length; i5++) { - module = modules[i5]; - mergeModules(exports, module); - } - var module; - var i5; - } -}); - -// node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/lib/streams.js -var require_streams = __commonJS({ - "node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/lib/streams.js"(exports, module) { - "use strict"; - var Buffer2 = require_safer().Buffer; - module.exports = function(streamModule) { - var Transform = streamModule.Transform; - function IconvLiteEncoderStream(conv, options) { - this.conv = conv; - options = options || {}; - options.decodeStrings = false; - Transform.call(this, options); - } - IconvLiteEncoderStream.prototype = Object.create(Transform.prototype, { - constructor: { value: IconvLiteEncoderStream } - }); - IconvLiteEncoderStream.prototype._transform = function(chunk, encoding, done) { - if (typeof chunk !== "string") { - return done(new Error("Iconv encoding stream needs strings as its input.")); - } - try { - var res = this.conv.write(chunk); - if (res && res.length) this.push(res); - done(); - } catch (e5) { - done(e5); - } - }; - IconvLiteEncoderStream.prototype._flush = function(done) { - try { - var res = this.conv.end(); - if (res && res.length) this.push(res); - done(); - } catch (e5) { - done(e5); - } - }; - IconvLiteEncoderStream.prototype.collect = function(cb) { - var chunks = []; - this.on("error", cb); - this.on("data", function(chunk) { - chunks.push(chunk); - }); - this.on("end", function() { - cb(null, Buffer2.concat(chunks)); - }); - return this; - }; - function IconvLiteDecoderStream(conv, options) { - this.conv = conv; - options = options || {}; - options.encoding = this.encoding = "utf8"; - Transform.call(this, options); - } - IconvLiteDecoderStream.prototype = Object.create(Transform.prototype, { - constructor: { value: IconvLiteDecoderStream } - }); - IconvLiteDecoderStream.prototype._transform = function(chunk, encoding, done) { - if (!Buffer2.isBuffer(chunk) && !(chunk instanceof Uint8Array)) { - return done(new Error("Iconv decoding stream needs buffers as its input.")); - } - try { - var res = this.conv.write(chunk); - if (res && res.length) this.push(res, this.encoding); - done(); - } catch (e5) { - done(e5); - } - }; - IconvLiteDecoderStream.prototype._flush = function(done) { - try { - var res = this.conv.end(); - if (res && res.length) this.push(res, this.encoding); - done(); - } catch (e5) { - done(e5); - } - }; - IconvLiteDecoderStream.prototype.collect = function(cb) { - var res = ""; - this.on("error", cb); - this.on("data", function(chunk) { - res += chunk; - }); - this.on("end", function() { - cb(null, res); - }); - return this; - }; - return { - IconvLiteEncoderStream, - IconvLiteDecoderStream - }; - }; - } -}); - -// node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/lib/index.js -var require_lib = __commonJS({ - "node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/lib/index.js"(exports, module) { - "use strict"; - var Buffer2 = require_safer().Buffer; - var bomHandling = require_bom_handling(); - var mergeModules = require_merge_exports(); - module.exports.encodings = null; - module.exports.defaultCharUnicode = "\uFFFD"; - module.exports.defaultCharSingleByte = "?"; - module.exports.encode = function encode6(str, encoding, options) { - str = "" + (str || ""); - var encoder3 = module.exports.getEncoder(encoding, options); - var res = encoder3.write(str); - var trail = encoder3.end(); - return trail && trail.length > 0 ? Buffer2.concat([res, trail]) : res; - }; - module.exports.decode = function decode5(buf, encoding, options) { - if (typeof buf === "string") { - if (!module.exports.skipDecodeWarning) { - console.error("Iconv-lite warning: decode()-ing strings is deprecated. Refer to https://github.com/ashtuchkin/iconv-lite/wiki/Use-Buffers-when-decoding"); - module.exports.skipDecodeWarning = true; - } - buf = Buffer2.from("" + (buf || ""), "binary"); - } - var decoder2 = module.exports.getDecoder(encoding, options); - var res = decoder2.write(buf); - var trail = decoder2.end(); - return trail ? res + trail : res; - }; - module.exports.encodingExists = function encodingExists(enc2) { - try { - module.exports.getCodec(enc2); - return true; - } catch (e5) { - return false; - } - }; - module.exports.toEncoding = module.exports.encode; - module.exports.fromEncoding = module.exports.decode; - module.exports._codecDataCache = { __proto__: null }; - module.exports.getCodec = function getCodec(encoding) { - if (!module.exports.encodings) { - var raw = require_encodings(); - module.exports.encodings = { __proto__: null }; - mergeModules(module.exports.encodings, raw); - } - var enc2 = module.exports._canonicalizeEncoding(encoding); - var codecOptions = {}; - while (true) { - var codec2 = module.exports._codecDataCache[enc2]; - if (codec2) { - return codec2; - } - var codecDef = module.exports.encodings[enc2]; - switch (typeof codecDef) { - case "string": - enc2 = codecDef; - break; - case "object": - for (var key in codecDef) { - codecOptions[key] = codecDef[key]; - } - if (!codecOptions.encodingName) { - codecOptions.encodingName = enc2; - } - enc2 = codecDef.type; - break; - case "function": - if (!codecOptions.encodingName) { - codecOptions.encodingName = enc2; - } - codec2 = new codecDef(codecOptions, module.exports); - module.exports._codecDataCache[codecOptions.encodingName] = codec2; - return codec2; - default: - throw new Error("Encoding not recognized: '" + encoding + "' (searched as: '" + enc2 + "')"); - } - } - }; - module.exports._canonicalizeEncoding = function(encoding) { - return ("" + encoding).toLowerCase().replace(/:\d{4}$|[^0-9a-z]/g, ""); - }; - module.exports.getEncoder = function getEncoder(encoding, options) { - var codec2 = module.exports.getCodec(encoding); - var encoder3 = new codec2.encoder(options, codec2); - if (codec2.bomAware && options && options.addBOM) { - encoder3 = new bomHandling.PrependBOM(encoder3, options); - } - return encoder3; - }; - module.exports.getDecoder = function getDecoder(encoding, options) { - var codec2 = module.exports.getCodec(encoding); - var decoder2 = new codec2.decoder(options, codec2); - if (codec2.bomAware && !(options && options.stripBOM === false)) { - decoder2 = new bomHandling.StripBOM(decoder2, options); - } - return decoder2; - }; - module.exports.enableStreamingAPI = function enableStreamingAPI(streamModule2) { - if (module.exports.supportsStreams) { - return; - } - var streams = require_streams()(streamModule2); - module.exports.IconvLiteEncoderStream = streams.IconvLiteEncoderStream; - module.exports.IconvLiteDecoderStream = streams.IconvLiteDecoderStream; - module.exports.encodeStream = function encodeStream(encoding, options) { - return new module.exports.IconvLiteEncoderStream(module.exports.getEncoder(encoding, options), options); - }; - module.exports.decodeStream = function decodeStream(encoding, options) { - return new module.exports.IconvLiteDecoderStream(module.exports.getDecoder(encoding, options), options); - }; - module.exports.supportsStreams = true; - }; - var streamModule; - try { - streamModule = __require("stream"); - } catch (e5) { - } - if (streamModule && streamModule.Transform) { - module.exports.enableStreamingAPI(streamModule); - } else { - module.exports.encodeStream = module.exports.decodeStream = function() { - throw new Error("iconv-lite Streaming API is not enabled. Use iconv.enableStreamingAPI(require('stream')); to enable it."); - }; - } - if (false) { - console.error("iconv-lite warning: js files use non-utf8 encoding. See https://github.com/ashtuchkin/iconv-lite/wiki/Javascript-source-file-encodings for more info."); - } - } -}); - -// node_modules/.pnpm/unpipe@1.0.0/node_modules/unpipe/index.js -var require_unpipe = __commonJS({ - "node_modules/.pnpm/unpipe@1.0.0/node_modules/unpipe/index.js"(exports, module) { - "use strict"; - module.exports = unpipe; - function hasPipeDataListeners(stream) { - var listeners = stream.listeners("data"); - for (var i5 = 0; i5 < listeners.length; i5++) { - if (listeners[i5].name === "ondata") { - return true; - } - } - return false; - } - function unpipe(stream) { - if (!stream) { - throw new TypeError("argument stream is required"); - } - if (typeof stream.unpipe === "function") { - stream.unpipe(); - return; - } - if (!hasPipeDataListeners(stream)) { - return; - } - var listener; - var listeners = stream.listeners("close"); - for (var i5 = 0; i5 < listeners.length; i5++) { - listener = listeners[i5]; - if (listener.name !== "cleanup" && listener.name !== "onclose") { - continue; - } - listener.call(stream); - } - } - } -}); - -// node_modules/.pnpm/raw-body@3.0.2/node_modules/raw-body/index.js -var require_raw_body = __commonJS({ - "node_modules/.pnpm/raw-body@3.0.2/node_modules/raw-body/index.js"(exports, module) { - "use strict"; - var asyncHooks = tryRequireAsyncHooks(); - var bytes = require_bytes(); - var createError = require_http_errors(); - var iconv = require_lib(); - var unpipe = require_unpipe(); - module.exports = getRawBody; - var ICONV_ENCODING_MESSAGE_REGEXP = /^Encoding not recognized: /; - function getDecoder(encoding) { - if (!encoding) return null; - try { - return iconv.getDecoder(encoding); - } catch (e5) { - if (!ICONV_ENCODING_MESSAGE_REGEXP.test(e5.message)) throw e5; - throw createError(415, "specified encoding unsupported", { - encoding, - type: "encoding.unsupported" - }); - } - } - function getRawBody(stream, options, callback) { - var done = callback; - var opts = options || {}; - if (stream === void 0) { - throw new TypeError("argument stream is required"); - } else if (typeof stream !== "object" || stream === null || typeof stream.on !== "function") { - throw new TypeError("argument stream must be a stream"); - } - if (options === true || typeof options === "string") { - opts = { - encoding: options - }; - } - if (typeof options === "function") { - done = options; - opts = {}; - } - if (done !== void 0 && typeof done !== "function") { - throw new TypeError("argument callback must be a function"); - } - if (!done && !global.Promise) { - throw new TypeError("argument callback is required"); - } - var encoding = opts.encoding !== true ? opts.encoding : "utf-8"; - var limit = bytes.parse(opts.limit); - var length = opts.length != null && !isNaN(opts.length) ? parseInt(opts.length, 10) : null; - if (done) { - return readStream(stream, encoding, length, limit, wrap4(done)); - } - return new Promise(function executor(resolve4, reject) { - readStream(stream, encoding, length, limit, function onRead(err, buf) { - if (err) return reject(err); - resolve4(buf); - }); - }); - } - function halt(stream) { - unpipe(stream); - if (typeof stream.pause === "function") { - stream.pause(); - } - } - function readStream(stream, encoding, length, limit, callback) { - var complete = false; - var sync = true; - if (limit !== null && length !== null && length > limit) { - return done(createError(413, "request entity too large", { - expected: length, - length, - limit, - type: "entity.too.large" - })); - } - var state2 = stream._readableState; - if (stream._decoder || state2 && (state2.encoding || state2.decoder)) { - return done(createError(500, "stream encoding should not be set", { - type: "stream.encoding.set" - })); - } - if (typeof stream.readable !== "undefined" && !stream.readable) { - return done(createError(500, "stream is not readable", { - type: "stream.not.readable" - })); - } - var received = 0; - var decoder2; - try { - decoder2 = getDecoder(encoding); - } catch (err) { - return done(err); - } - var buffer2 = decoder2 ? "" : []; - stream.on("aborted", onAborted); - stream.on("close", cleanup); - stream.on("data", onData); - stream.on("end", onEnd); - stream.on("error", onEnd); - sync = false; - function done() { - var args = new Array(arguments.length); - for (var i5 = 0; i5 < args.length; i5++) { - args[i5] = arguments[i5]; - } - complete = true; - if (sync) { - process.nextTick(invokeCallback); - } else { - invokeCallback(); - } - function invokeCallback() { - cleanup(); - if (args[0]) { - halt(stream); - } - callback.apply(null, args); - } - } - function onAborted() { - if (complete) return; - done(createError(400, "request aborted", { - code: "ECONNABORTED", - expected: length, - length, - received, - type: "request.aborted" - })); - } - function onData(chunk) { - if (complete) return; - received += chunk.length; - if (limit !== null && received > limit) { - done(createError(413, "request entity too large", { - limit, - received, - type: "entity.too.large" - })); - } else if (decoder2) { - buffer2 += decoder2.write(chunk); - } else { - buffer2.push(chunk); - } - } - function onEnd(err) { - if (complete) return; - if (err) return done(err); - if (length !== null && received !== length) { - done(createError(400, "request size did not match content length", { - expected: length, - length, - received, - type: "request.size.invalid" - })); - } else { - var string4 = decoder2 ? buffer2 + (decoder2.end() || "") : Buffer.concat(buffer2); - done(null, string4); - } - } - function cleanup() { - buffer2 = null; - stream.removeListener("aborted", onAborted); - stream.removeListener("data", onData); - stream.removeListener("end", onEnd); - stream.removeListener("error", onEnd); - stream.removeListener("close", cleanup); - } - } - function tryRequireAsyncHooks() { - try { - return __require("async_hooks"); - } catch (e5) { - return {}; - } - } - function wrap4(fn) { - var res; - if (asyncHooks.AsyncResource) { - res = new asyncHooks.AsyncResource(fn.name || "bound-anonymous-fn"); - } - if (!res || !res.runInAsyncScope) { - return fn; - } - return res.runInAsyncScope.bind(res, fn, null); - } - } -}); - -// node_modules/.pnpm/ee-first@1.1.1/node_modules/ee-first/index.js -var require_ee_first = __commonJS({ - "node_modules/.pnpm/ee-first@1.1.1/node_modules/ee-first/index.js"(exports, module) { - "use strict"; - module.exports = first; - function first(stuff, done) { - if (!Array.isArray(stuff)) - throw new TypeError("arg must be an array of [ee, events...] arrays"); - var cleanups = []; - for (var i5 = 0; i5 < stuff.length; i5++) { - var arr = stuff[i5]; - if (!Array.isArray(arr) || arr.length < 2) - throw new TypeError("each array member must be [ee, events...]"); - var ee = arr[0]; - for (var j5 = 1; j5 < arr.length; j5++) { - var event = arr[j5]; - var fn = listener(event, callback); - ee.on(event, fn); - cleanups.push({ - ee, - event, - fn - }); - } - } - function callback() { - cleanup(); - done.apply(null, arguments); - } - function cleanup() { - var x5; - for (var i6 = 0; i6 < cleanups.length; i6++) { - x5 = cleanups[i6]; - x5.ee.removeListener(x5.event, x5.fn); - } - } - function thunk(fn2) { - done = fn2; - } - thunk.cancel = cleanup; - return thunk; - } - function listener(event, done) { - return function onevent(arg1) { - var args = new Array(arguments.length); - var ee = this; - var err = event === "error" ? arg1 : null; - for (var i5 = 0; i5 < args.length; i5++) { - args[i5] = arguments[i5]; - } - done(err, ee, event, args); - }; - } - } -}); - -// node_modules/.pnpm/on-finished@2.4.1/node_modules/on-finished/index.js -var require_on_finished = __commonJS({ - "node_modules/.pnpm/on-finished@2.4.1/node_modules/on-finished/index.js"(exports, module) { - "use strict"; - module.exports = onFinished; - module.exports.isFinished = isFinished; - var asyncHooks = tryRequireAsyncHooks(); - var first = require_ee_first(); - var defer = typeof setImmediate === "function" ? setImmediate : function(fn) { - process.nextTick(fn.bind.apply(fn, arguments)); - }; - function onFinished(msg, listener) { - if (isFinished(msg) !== false) { - defer(listener, null, msg); - return msg; - } - attachListener(msg, wrap4(listener)); - return msg; - } - function isFinished(msg) { - var socket = msg.socket; - if (typeof msg.finished === "boolean") { - return Boolean(msg.finished || socket && !socket.writable); - } - if (typeof msg.complete === "boolean") { - return Boolean(msg.upgrade || !socket || !socket.readable || msg.complete && !msg.readable); - } - return void 0; - } - function attachFinishedListener(msg, callback) { - var eeMsg; - var eeSocket; - var finished = false; - function onFinish(error50) { - eeMsg.cancel(); - eeSocket.cancel(); - finished = true; - callback(error50); - } - eeMsg = eeSocket = first([[msg, "end", "finish"]], onFinish); - function onSocket(socket) { - msg.removeListener("socket", onSocket); - if (finished) return; - if (eeMsg !== eeSocket) return; - eeSocket = first([[socket, "error", "close"]], onFinish); - } - if (msg.socket) { - onSocket(msg.socket); - return; - } - msg.on("socket", onSocket); - if (msg.socket === void 0) { - patchAssignSocket(msg, onSocket); - } - } - function attachListener(msg, listener) { - var attached = msg.__onFinished; - if (!attached || !attached.queue) { - attached = msg.__onFinished = createListener(msg); - attachFinishedListener(msg, attached); - } - attached.queue.push(listener); - } - function createListener(msg) { - function listener(err) { - if (msg.__onFinished === listener) msg.__onFinished = null; - if (!listener.queue) return; - var queue = listener.queue; - listener.queue = null; - for (var i5 = 0; i5 < queue.length; i5++) { - queue[i5](err, msg); - } - } - listener.queue = []; - return listener; - } - function patchAssignSocket(res, callback) { - var assignSocket = res.assignSocket; - if (typeof assignSocket !== "function") return; - res.assignSocket = function _assignSocket(socket) { - assignSocket.call(this, socket); - callback(socket); - }; - } - function tryRequireAsyncHooks() { - try { - return __require("async_hooks"); - } catch (e5) { - return {}; - } - } - function wrap4(fn) { - var res; - if (asyncHooks.AsyncResource) { - res = new asyncHooks.AsyncResource(fn.name || "bound-anonymous-fn"); - } - if (!res || !res.runInAsyncScope) { - return fn; - } - return res.runInAsyncScope.bind(res, fn, null); - } - } -}); - -// node_modules/.pnpm/content-type@1.0.5/node_modules/content-type/index.js -var require_content_type = __commonJS({ - "node_modules/.pnpm/content-type@1.0.5/node_modules/content-type/index.js"(exports) { - "use strict"; - var PARAM_REGEXP = /; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g; - var TEXT_REGEXP = /^[\u000b\u0020-\u007e\u0080-\u00ff]+$/; - var TOKEN_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/; - var QESC_REGEXP = /\\([\u000b\u0020-\u00ff])/g; - var QUOTE_REGEXP = /([\\"])/g; - var TYPE_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/; - exports.format = format2; - exports.parse = parse5; - function format2(obj) { - if (!obj || typeof obj !== "object") { - throw new TypeError("argument obj is required"); - } - var parameters = obj.parameters; - var type = obj.type; - if (!type || !TYPE_REGEXP.test(type)) { - throw new TypeError("invalid type"); - } - var string4 = type; - if (parameters && typeof parameters === "object") { - var param; - var params = Object.keys(parameters).sort(); - for (var i5 = 0; i5 < params.length; i5++) { - param = params[i5]; - if (!TOKEN_REGEXP.test(param)) { - throw new TypeError("invalid parameter name"); - } - string4 += "; " + param + "=" + qstring(parameters[param]); - } - } - return string4; - } - function parse5(string4) { - if (!string4) { - throw new TypeError("argument string is required"); - } - var header = typeof string4 === "object" ? getcontenttype(string4) : string4; - if (typeof header !== "string") { - throw new TypeError("argument string is required to be a string"); - } - var index2 = header.indexOf(";"); - var type = index2 !== -1 ? header.slice(0, index2).trim() : header.trim(); - if (!TYPE_REGEXP.test(type)) { - throw new TypeError("invalid media type"); - } - var obj = new ContentType(type.toLowerCase()); - if (index2 !== -1) { - var key; - var match; - var value; - PARAM_REGEXP.lastIndex = index2; - while (match = PARAM_REGEXP.exec(header)) { - if (match.index !== index2) { - throw new TypeError("invalid parameter format"); - } - index2 += match[0].length; - key = match[1].toLowerCase(); - value = match[2]; - if (value.charCodeAt(0) === 34) { - value = value.slice(1, -1); - if (value.indexOf("\\") !== -1) { - value = value.replace(QESC_REGEXP, "$1"); - } - } - obj.parameters[key] = value; - } - if (index2 !== header.length) { - throw new TypeError("invalid parameter format"); - } - } - return obj; - } - function getcontenttype(obj) { - var header; - if (typeof obj.getHeader === "function") { - header = obj.getHeader("content-type"); - } else if (typeof obj.headers === "object") { - header = obj.headers && obj.headers["content-type"]; - } - if (typeof header !== "string") { - throw new TypeError("content-type header is missing from object"); - } - return header; - } - function qstring(val) { - var str = String(val); - if (TOKEN_REGEXP.test(str)) { - return str; - } - if (str.length > 0 && !TEXT_REGEXP.test(str)) { - throw new TypeError("invalid parameter value"); - } - return '"' + str.replace(QUOTE_REGEXP, "\\$1") + '"'; - } - function ContentType(type) { - this.parameters = /* @__PURE__ */ Object.create(null); - this.type = type; - } - } -}); - -// node_modules/.pnpm/mime-db@1.54.0/node_modules/mime-db/db.json -var require_db = __commonJS({ - "node_modules/.pnpm/mime-db@1.54.0/node_modules/mime-db/db.json"(exports, module) { - module.exports = { - "application/1d-interleaved-parityfec": { - source: "iana" - }, - "application/3gpdash-qoe-report+xml": { - source: "iana", - charset: "UTF-8", - compressible: true - }, - "application/3gpp-ims+xml": { - source: "iana", - compressible: true - }, - "application/3gpphal+json": { - source: "iana", - compressible: true - }, - "application/3gpphalforms+json": { - source: "iana", - compressible: true - }, - "application/a2l": { - source: "iana" - }, - "application/ace+cbor": { - source: "iana" - }, - "application/ace+json": { - source: "iana", - compressible: true - }, - "application/ace-groupcomm+cbor": { - source: "iana" - }, - "application/ace-trl+cbor": { - source: "iana" - }, - "application/activemessage": { - source: "iana" - }, - "application/activity+json": { - source: "iana", - compressible: true - }, - "application/aif+cbor": { - source: "iana" - }, - "application/aif+json": { - source: "iana", - compressible: true - }, - "application/alto-cdni+json": { - source: "iana", - compressible: true - }, - "application/alto-cdnifilter+json": { - source: "iana", - compressible: true - }, - "application/alto-costmap+json": { - source: "iana", - compressible: true - }, - "application/alto-costmapfilter+json": { - source: "iana", - compressible: true - }, - "application/alto-directory+json": { - source: "iana", - compressible: true - }, - "application/alto-endpointcost+json": { - source: "iana", - compressible: true - }, - "application/alto-endpointcostparams+json": { - source: "iana", - compressible: true - }, - "application/alto-endpointprop+json": { - source: "iana", - compressible: true - }, - "application/alto-endpointpropparams+json": { - source: "iana", - compressible: true - }, - "application/alto-error+json": { - source: "iana", - compressible: true - }, - "application/alto-networkmap+json": { - source: "iana", - compressible: true - }, - "application/alto-networkmapfilter+json": { - source: "iana", - compressible: true - }, - "application/alto-propmap+json": { - source: "iana", - compressible: true - }, - "application/alto-propmapparams+json": { - source: "iana", - compressible: true - }, - "application/alto-tips+json": { - source: "iana", - compressible: true - }, - "application/alto-tipsparams+json": { - source: "iana", - compressible: true - }, - "application/alto-updatestreamcontrol+json": { - source: "iana", - compressible: true - }, - "application/alto-updatestreamparams+json": { - source: "iana", - compressible: true - }, - "application/aml": { - source: "iana" - }, - "application/andrew-inset": { - source: "iana", - extensions: ["ez"] - }, - "application/appinstaller": { - compressible: false, - extensions: ["appinstaller"] - }, - "application/applefile": { - source: "iana" - }, - "application/applixware": { - source: "apache", - extensions: ["aw"] - }, - "application/appx": { - compressible: false, - extensions: ["appx"] - }, - "application/appxbundle": { - compressible: false, - extensions: ["appxbundle"] - }, - "application/at+jwt": { - source: "iana" - }, - "application/atf": { - source: "iana" - }, - "application/atfx": { - source: "iana" - }, - "application/atom+xml": { - source: "iana", - compressible: true, - extensions: ["atom"] - }, - "application/atomcat+xml": { - source: "iana", - compressible: true, - extensions: ["atomcat"] - }, - "application/atomdeleted+xml": { - source: "iana", - compressible: true, - extensions: ["atomdeleted"] - }, - "application/atomicmail": { - source: "iana" - }, - "application/atomsvc+xml": { - source: "iana", - compressible: true, - extensions: ["atomsvc"] - }, - "application/atsc-dwd+xml": { - source: "iana", - compressible: true, - extensions: ["dwd"] - }, - "application/atsc-dynamic-event-message": { - source: "iana" - }, - "application/atsc-held+xml": { - source: "iana", - compressible: true, - extensions: ["held"] - }, - "application/atsc-rdt+json": { - source: "iana", - compressible: true - }, - "application/atsc-rsat+xml": { - source: "iana", - compressible: true, - extensions: ["rsat"] - }, - "application/atxml": { - source: "iana" - }, - "application/auth-policy+xml": { - source: "iana", - compressible: true - }, - "application/automationml-aml+xml": { - source: "iana", - compressible: true, - extensions: ["aml"] - }, - "application/automationml-amlx+zip": { - source: "iana", - compressible: false, - extensions: ["amlx"] - }, - "application/bacnet-xdd+zip": { - source: "iana", - compressible: false - }, - "application/batch-smtp": { - source: "iana" - }, - "application/bdoc": { - compressible: false, - extensions: ["bdoc"] - }, - "application/beep+xml": { - source: "iana", - charset: "UTF-8", - compressible: true - }, - "application/bufr": { - source: "iana" - }, - "application/c2pa": { - source: "iana" - }, - "application/calendar+json": { - source: "iana", - compressible: true - }, - "application/calendar+xml": { - source: "iana", - compressible: true, - extensions: ["xcs"] - }, - "application/call-completion": { - source: "iana" - }, - "application/cals-1840": { - source: "iana" - }, - "application/captive+json": { - source: "iana", - compressible: true - }, - "application/cbor": { - source: "iana" - }, - "application/cbor-seq": { - source: "iana" - }, - "application/cccex": { - source: "iana" - }, - "application/ccmp+xml": { - source: "iana", - compressible: true - }, - "application/ccxml+xml": { - source: "iana", - compressible: true, - extensions: ["ccxml"] - }, - "application/cda+xml": { - source: "iana", - charset: "UTF-8", - compressible: true - }, - "application/cdfx+xml": { - source: "iana", - compressible: true, - extensions: ["cdfx"] - }, - "application/cdmi-capability": { - source: "iana", - extensions: ["cdmia"] - }, - "application/cdmi-container": { - source: "iana", - extensions: ["cdmic"] - }, - "application/cdmi-domain": { - source: "iana", - extensions: ["cdmid"] - }, - "application/cdmi-object": { - source: "iana", - extensions: ["cdmio"] - }, - "application/cdmi-queue": { - source: "iana", - extensions: ["cdmiq"] - }, - "application/cdni": { - source: "iana" - }, - "application/ce+cbor": { - source: "iana" - }, - "application/cea": { - source: "iana" - }, - "application/cea-2018+xml": { - source: "iana", - compressible: true - }, - "application/cellml+xml": { - source: "iana", - compressible: true - }, - "application/cfw": { - source: "iana" - }, - "application/cid-edhoc+cbor-seq": { - source: "iana" - }, - "application/city+json": { - source: "iana", - compressible: true - }, - "application/city+json-seq": { - source: "iana" - }, - "application/clr": { - source: "iana" - }, - "application/clue+xml": { - source: "iana", - compressible: true - }, - "application/clue_info+xml": { - source: "iana", - compressible: true - }, - "application/cms": { - source: "iana" - }, - "application/cnrp+xml": { - source: "iana", - compressible: true - }, - "application/coap-eap": { - source: "iana" - }, - "application/coap-group+json": { - source: "iana", - compressible: true - }, - "application/coap-payload": { - source: "iana" - }, - "application/commonground": { - source: "iana" - }, - "application/concise-problem-details+cbor": { - source: "iana" - }, - "application/conference-info+xml": { - source: "iana", - compressible: true - }, - "application/cose": { - source: "iana" - }, - "application/cose-key": { - source: "iana" - }, - "application/cose-key-set": { - source: "iana" - }, - "application/cose-x509": { - source: "iana" - }, - "application/cpl+xml": { - source: "iana", - compressible: true, - extensions: ["cpl"] - }, - "application/csrattrs": { - source: "iana" - }, - "application/csta+xml": { - source: "iana", - compressible: true - }, - "application/cstadata+xml": { - source: "iana", - compressible: true - }, - "application/csvm+json": { - source: "iana", - compressible: true - }, - "application/cu-seeme": { - source: "apache", - extensions: ["cu"] - }, - "application/cwl": { - source: "iana", - extensions: ["cwl"] - }, - "application/cwl+json": { - source: "iana", - compressible: true - }, - "application/cwl+yaml": { - source: "iana" - }, - "application/cwt": { - source: "iana" - }, - "application/cybercash": { - source: "iana" - }, - "application/dart": { - compressible: true - }, - "application/dash+xml": { - source: "iana", - compressible: true, - extensions: ["mpd"] - }, - "application/dash-patch+xml": { - source: "iana", - compressible: true, - extensions: ["mpp"] - }, - "application/dashdelta": { - source: "iana" - }, - "application/davmount+xml": { - source: "iana", - compressible: true, - extensions: ["davmount"] - }, - "application/dca-rft": { - source: "iana" - }, - "application/dcd": { - source: "iana" - }, - "application/dec-dx": { - source: "iana" - }, - "application/dialog-info+xml": { - source: "iana", - compressible: true - }, - "application/dicom": { - source: "iana", - extensions: ["dcm"] - }, - "application/dicom+json": { - source: "iana", - compressible: true - }, - "application/dicom+xml": { - source: "iana", - compressible: true - }, - "application/dii": { - source: "iana" - }, - "application/dit": { - source: "iana" - }, - "application/dns": { - source: "iana" - }, - "application/dns+json": { - source: "iana", - compressible: true - }, - "application/dns-message": { - source: "iana" - }, - "application/docbook+xml": { - source: "apache", - compressible: true, - extensions: ["dbk"] - }, - "application/dots+cbor": { - source: "iana" - }, - "application/dpop+jwt": { - source: "iana" - }, - "application/dskpp+xml": { - source: "iana", - compressible: true - }, - "application/dssc+der": { - source: "iana", - extensions: ["dssc"] - }, - "application/dssc+xml": { - source: "iana", - compressible: true, - extensions: ["xdssc"] - }, - "application/dvcs": { - source: "iana" - }, - "application/eat+cwt": { - source: "iana" - }, - "application/eat+jwt": { - source: "iana" - }, - "application/eat-bun+cbor": { - source: "iana" - }, - "application/eat-bun+json": { - source: "iana", - compressible: true - }, - "application/eat-ucs+cbor": { - source: "iana" - }, - "application/eat-ucs+json": { - source: "iana", - compressible: true - }, - "application/ecmascript": { - source: "apache", - compressible: true, - extensions: ["ecma"] - }, - "application/edhoc+cbor-seq": { - source: "iana" - }, - "application/edi-consent": { - source: "iana" - }, - "application/edi-x12": { - source: "iana", - compressible: false - }, - "application/edifact": { - source: "iana", - compressible: false - }, - "application/efi": { - source: "iana" - }, - "application/elm+json": { - source: "iana", - charset: "UTF-8", - compressible: true - }, - "application/elm+xml": { - source: "iana", - compressible: true - }, - "application/emergencycalldata.cap+xml": { - source: "iana", - charset: "UTF-8", - compressible: true - }, - "application/emergencycalldata.comment+xml": { - source: "iana", - compressible: true - }, - "application/emergencycalldata.control+xml": { - source: "iana", - compressible: true - }, - "application/emergencycalldata.deviceinfo+xml": { - source: "iana", - compressible: true - }, - "application/emergencycalldata.ecall.msd": { - source: "iana" - }, - "application/emergencycalldata.legacyesn+json": { - source: "iana", - compressible: true - }, - "application/emergencycalldata.providerinfo+xml": { - source: "iana", - compressible: true - }, - "application/emergencycalldata.serviceinfo+xml": { - source: "iana", - compressible: true - }, - "application/emergencycalldata.subscriberinfo+xml": { - source: "iana", - compressible: true - }, - "application/emergencycalldata.veds+xml": { - source: "iana", - compressible: true - }, - "application/emma+xml": { - source: "iana", - compressible: true, - extensions: ["emma"] - }, - "application/emotionml+xml": { - source: "iana", - compressible: true, - extensions: ["emotionml"] - }, - "application/encaprtp": { - source: "iana" - }, - "application/entity-statement+jwt": { - source: "iana" - }, - "application/epp+xml": { - source: "iana", - compressible: true - }, - "application/epub+zip": { - source: "iana", - compressible: false, - extensions: ["epub"] - }, - "application/eshop": { - source: "iana" - }, - "application/exi": { - source: "iana", - extensions: ["exi"] - }, - "application/expect-ct-report+json": { - source: "iana", - compressible: true - }, - "application/express": { - source: "iana", - extensions: ["exp"] - }, - "application/fastinfoset": { - source: "iana" - }, - "application/fastsoap": { - source: "iana" - }, - "application/fdf": { - source: "iana", - extensions: ["fdf"] - }, - "application/fdt+xml": { - source: "iana", - compressible: true, - extensions: ["fdt"] - }, - "application/fhir+json": { - source: "iana", - charset: "UTF-8", - compressible: true - }, - "application/fhir+xml": { - source: "iana", - charset: "UTF-8", - compressible: true - }, - "application/fido.trusted-apps+json": { - compressible: true - }, - "application/fits": { - source: "iana" - }, - "application/flexfec": { - source: "iana" - }, - "application/font-sfnt": { - source: "iana" - }, - "application/font-tdpfr": { - source: "iana", - extensions: ["pfr"] - }, - "application/font-woff": { - source: "iana", - compressible: false - }, - "application/framework-attributes+xml": { - source: "iana", - compressible: true - }, - "application/geo+json": { - source: "iana", - compressible: true, - extensions: ["geojson"] - }, - "application/geo+json-seq": { - source: "iana" - }, - "application/geopackage+sqlite3": { - source: "iana" - }, - "application/geopose+json": { - source: "iana", - compressible: true - }, - "application/geoxacml+json": { - source: "iana", - compressible: true - }, - "application/geoxacml+xml": { - source: "iana", - compressible: true - }, - "application/gltf-buffer": { - source: "iana" - }, - "application/gml+xml": { - source: "iana", - compressible: true, - extensions: ["gml"] - }, - "application/gnap-binding-jws": { - source: "iana" - }, - "application/gnap-binding-jwsd": { - source: "iana" - }, - "application/gnap-binding-rotation-jws": { - source: "iana" - }, - "application/gnap-binding-rotation-jwsd": { - source: "iana" - }, - "application/gpx+xml": { - source: "apache", - compressible: true, - extensions: ["gpx"] - }, - "application/grib": { - source: "iana" - }, - "application/gxf": { - source: "apache", - extensions: ["gxf"] - }, - "application/gzip": { - source: "iana", - compressible: false, - extensions: ["gz"] - }, - "application/h224": { - source: "iana" - }, - "application/held+xml": { - source: "iana", - compressible: true - }, - "application/hjson": { - extensions: ["hjson"] - }, - "application/hl7v2+xml": { - source: "iana", - charset: "UTF-8", - compressible: true - }, - "application/http": { - source: "iana" - }, - "application/hyperstudio": { - source: "iana", - extensions: ["stk"] - }, - "application/ibe-key-request+xml": { - source: "iana", - compressible: true - }, - "application/ibe-pkg-reply+xml": { - source: "iana", - compressible: true - }, - "application/ibe-pp-data": { - source: "iana" - }, - "application/iges": { - source: "iana" - }, - "application/im-iscomposing+xml": { - source: "iana", - charset: "UTF-8", - compressible: true - }, - "application/index": { - source: "iana" - }, - "application/index.cmd": { - source: "iana" - }, - "application/index.obj": { - source: "iana" - }, - "application/index.response": { - source: "iana" - }, - "application/index.vnd": { - source: "iana" - }, - "application/inkml+xml": { - source: "iana", - compressible: true, - extensions: ["ink", "inkml"] - }, - "application/iotp": { - source: "iana" - }, - "application/ipfix": { - source: "iana", - extensions: ["ipfix"] - }, - "application/ipp": { - source: "iana" - }, - "application/isup": { - source: "iana" - }, - "application/its+xml": { - source: "iana", - compressible: true, - extensions: ["its"] - }, - "application/java-archive": { - source: "iana", - compressible: false, - extensions: ["jar", "war", "ear"] - }, - "application/java-serialized-object": { - source: "apache", - compressible: false, - extensions: ["ser"] - }, - "application/java-vm": { - source: "apache", - compressible: false, - extensions: ["class"] - }, - "application/javascript": { - source: "apache", - charset: "UTF-8", - compressible: true, - extensions: ["js"] - }, - "application/jf2feed+json": { - source: "iana", - compressible: true - }, - "application/jose": { - source: "iana" - }, - "application/jose+json": { - source: "iana", - compressible: true - }, - "application/jrd+json": { - source: "iana", - compressible: true - }, - "application/jscalendar+json": { - source: "iana", - compressible: true - }, - "application/jscontact+json": { - source: "iana", - compressible: true - }, - "application/json": { - source: "iana", - charset: "UTF-8", - compressible: true, - extensions: ["json", "map"] - }, - "application/json-patch+json": { - source: "iana", - compressible: true - }, - "application/json-seq": { - source: "iana" - }, - "application/json5": { - extensions: ["json5"] - }, - "application/jsonml+json": { - source: "apache", - compressible: true, - extensions: ["jsonml"] - }, - "application/jsonpath": { - source: "iana" - }, - "application/jwk+json": { - source: "iana", - compressible: true - }, - "application/jwk-set+json": { - source: "iana", - compressible: true - }, - "application/jwk-set+jwt": { - source: "iana" - }, - "application/jwt": { - source: "iana" - }, - "application/kpml-request+xml": { - source: "iana", - compressible: true - }, - "application/kpml-response+xml": { - source: "iana", - compressible: true - }, - "application/ld+json": { - source: "iana", - compressible: true, - extensions: ["jsonld"] - }, - "application/lgr+xml": { - source: "iana", - compressible: true, - extensions: ["lgr"] - }, - "application/link-format": { - source: "iana" - }, - "application/linkset": { - source: "iana" - }, - "application/linkset+json": { - source: "iana", - compressible: true - }, - "application/load-control+xml": { - source: "iana", - compressible: true - }, - "application/logout+jwt": { - source: "iana" - }, - "application/lost+xml": { - source: "iana", - compressible: true, - extensions: ["lostxml"] - }, - "application/lostsync+xml": { - source: "iana", - compressible: true - }, - "application/lpf+zip": { - source: "iana", - compressible: false - }, - "application/lxf": { - source: "iana" - }, - "application/mac-binhex40": { - source: "iana", - extensions: ["hqx"] - }, - "application/mac-compactpro": { - source: "apache", - extensions: ["cpt"] - }, - "application/macwriteii": { - source: "iana" - }, - "application/mads+xml": { - source: "iana", - compressible: true, - extensions: ["mads"] - }, - "application/manifest+json": { - source: "iana", - charset: "UTF-8", - compressible: true, - extensions: ["webmanifest"] - }, - "application/marc": { - source: "iana", - extensions: ["mrc"] - }, - "application/marcxml+xml": { - source: "iana", - compressible: true, - extensions: ["mrcx"] - }, - "application/mathematica": { - source: "iana", - extensions: ["ma", "nb", "mb"] - }, - "application/mathml+xml": { - source: "iana", - compressible: true, - extensions: ["mathml"] - }, - "application/mathml-content+xml": { - source: "iana", - compressible: true - }, - "application/mathml-presentation+xml": { - source: "iana", - compressible: true - }, - "application/mbms-associated-procedure-description+xml": { - source: "iana", - compressible: true - }, - "application/mbms-deregister+xml": { - source: "iana", - compressible: true - }, - "application/mbms-envelope+xml": { - source: "iana", - compressible: true - }, - "application/mbms-msk+xml": { - source: "iana", - compressible: true - }, - "application/mbms-msk-response+xml": { - source: "iana", - compressible: true - }, - "application/mbms-protection-description+xml": { - source: "iana", - compressible: true - }, - "application/mbms-reception-report+xml": { - source: "iana", - compressible: true - }, - "application/mbms-register+xml": { - source: "iana", - compressible: true - }, - "application/mbms-register-response+xml": { - source: "iana", - compressible: true - }, - "application/mbms-schedule+xml": { - source: "iana", - compressible: true - }, - "application/mbms-user-service-description+xml": { - source: "iana", - compressible: true - }, - "application/mbox": { - source: "iana", - extensions: ["mbox"] - }, - "application/media-policy-dataset+xml": { - source: "iana", - compressible: true, - extensions: ["mpf"] - }, - "application/media_control+xml": { - source: "iana", - compressible: true - }, - "application/mediaservercontrol+xml": { - source: "iana", - compressible: true, - extensions: ["mscml"] - }, - "application/merge-patch+json": { - source: "iana", - compressible: true - }, - "application/metalink+xml": { - source: "apache", - compressible: true, - extensions: ["metalink"] - }, - "application/metalink4+xml": { - source: "iana", - compressible: true, - extensions: ["meta4"] - }, - "application/mets+xml": { - source: "iana", - compressible: true, - extensions: ["mets"] - }, - "application/mf4": { - source: "iana" - }, - "application/mikey": { - source: "iana" - }, - "application/mipc": { - source: "iana" - }, - "application/missing-blocks+cbor-seq": { - source: "iana" - }, - "application/mmt-aei+xml": { - source: "iana", - compressible: true, - extensions: ["maei"] - }, - "application/mmt-usd+xml": { - source: "iana", - compressible: true, - extensions: ["musd"] - }, - "application/mods+xml": { - source: "iana", - compressible: true, - extensions: ["mods"] - }, - "application/moss-keys": { - source: "iana" - }, - "application/moss-signature": { - source: "iana" - }, - "application/mosskey-data": { - source: "iana" - }, - "application/mosskey-request": { - source: "iana" - }, - "application/mp21": { - source: "iana", - extensions: ["m21", "mp21"] - }, - "application/mp4": { - source: "iana", - extensions: ["mp4", "mpg4", "mp4s", "m4p"] - }, - "application/mpeg4-generic": { - source: "iana" - }, - "application/mpeg4-iod": { - source: "iana" - }, - "application/mpeg4-iod-xmt": { - source: "iana" - }, - "application/mrb-consumer+xml": { - source: "iana", - compressible: true - }, - "application/mrb-publish+xml": { - source: "iana", - compressible: true - }, - "application/msc-ivr+xml": { - source: "iana", - charset: "UTF-8", - compressible: true - }, - "application/msc-mixer+xml": { - source: "iana", - charset: "UTF-8", - compressible: true - }, - "application/msix": { - compressible: false, - extensions: ["msix"] - }, - "application/msixbundle": { - compressible: false, - extensions: ["msixbundle"] - }, - "application/msword": { - source: "iana", - compressible: false, - extensions: ["doc", "dot"] - }, - "application/mud+json": { - source: "iana", - compressible: true - }, - "application/multipart-core": { - source: "iana" - }, - "application/mxf": { - source: "iana", - extensions: ["mxf"] - }, - "application/n-quads": { - source: "iana", - extensions: ["nq"] - }, - "application/n-triples": { - source: "iana", - extensions: ["nt"] - }, - "application/nasdata": { - source: "iana" - }, - "application/news-checkgroups": { - source: "iana", - charset: "US-ASCII" - }, - "application/news-groupinfo": { - source: "iana", - charset: "US-ASCII" - }, - "application/news-transmission": { - source: "iana" - }, - "application/nlsml+xml": { - source: "iana", - compressible: true - }, - "application/node": { - source: "iana", - extensions: ["cjs"] - }, - "application/nss": { - source: "iana" - }, - "application/oauth-authz-req+jwt": { - source: "iana" - }, - "application/oblivious-dns-message": { - source: "iana" - }, - "application/ocsp-request": { - source: "iana" - }, - "application/ocsp-response": { - source: "iana" - }, - "application/octet-stream": { - source: "iana", - compressible: true, - extensions: ["bin", "dms", "lrf", "mar", "so", "dist", "distz", "pkg", "bpk", "dump", "elc", "deploy", "exe", "dll", "deb", "dmg", "iso", "img", "msi", "msp", "msm", "buffer"] - }, - "application/oda": { - source: "iana", - extensions: ["oda"] - }, - "application/odm+xml": { - source: "iana", - compressible: true - }, - "application/odx": { - source: "iana" - }, - "application/oebps-package+xml": { - source: "iana", - compressible: true, - extensions: ["opf"] - }, - "application/ogg": { - source: "iana", - compressible: false, - extensions: ["ogx"] - }, - "application/ohttp-keys": { - source: "iana" - }, - "application/omdoc+xml": { - source: "apache", - compressible: true, - extensions: ["omdoc"] - }, - "application/onenote": { - source: "apache", - extensions: ["onetoc", "onetoc2", "onetmp", "onepkg", "one", "onea"] - }, - "application/opc-nodeset+xml": { - source: "iana", - compressible: true - }, - "application/oscore": { - source: "iana" - }, - "application/oxps": { - source: "iana", - extensions: ["oxps"] - }, - "application/p21": { - source: "iana" - }, - "application/p21+zip": { - source: "iana", - compressible: false - }, - "application/p2p-overlay+xml": { - source: "iana", - compressible: true, - extensions: ["relo"] - }, - "application/parityfec": { - source: "iana" - }, - "application/passport": { - source: "iana" - }, - "application/patch-ops-error+xml": { - source: "iana", - compressible: true, - extensions: ["xer"] - }, - "application/pdf": { - source: "iana", - compressible: false, - extensions: ["pdf"] - }, - "application/pdx": { - source: "iana" - }, - "application/pem-certificate-chain": { - source: "iana" - }, - "application/pgp-encrypted": { - source: "iana", - compressible: false, - extensions: ["pgp"] - }, - "application/pgp-keys": { - source: "iana", - extensions: ["asc"] - }, - "application/pgp-signature": { - source: "iana", - extensions: ["sig", "asc"] - }, - "application/pics-rules": { - source: "apache", - extensions: ["prf"] - }, - "application/pidf+xml": { - source: "iana", - charset: "UTF-8", - compressible: true - }, - "application/pidf-diff+xml": { - source: "iana", - charset: "UTF-8", - compressible: true - }, - "application/pkcs10": { - source: "iana", - extensions: ["p10"] - }, - "application/pkcs12": { - source: "iana" - }, - "application/pkcs7-mime": { - source: "iana", - extensions: ["p7m", "p7c"] - }, - "application/pkcs7-signature": { - source: "iana", - extensions: ["p7s"] - }, - "application/pkcs8": { - source: "iana", - extensions: ["p8"] - }, - "application/pkcs8-encrypted": { - source: "iana" - }, - "application/pkix-attr-cert": { - source: "iana", - extensions: ["ac"] - }, - "application/pkix-cert": { - source: "iana", - extensions: ["cer"] - }, - "application/pkix-crl": { - source: "iana", - extensions: ["crl"] - }, - "application/pkix-pkipath": { - source: "iana", - extensions: ["pkipath"] - }, - "application/pkixcmp": { - source: "iana", - extensions: ["pki"] - }, - "application/pls+xml": { - source: "iana", - compressible: true, - extensions: ["pls"] - }, - "application/poc-settings+xml": { - source: "iana", - charset: "UTF-8", - compressible: true - }, - "application/postscript": { - source: "iana", - compressible: true, - extensions: ["ai", "eps", "ps"] - }, - "application/ppsp-tracker+json": { - source: "iana", - compressible: true - }, - "application/private-token-issuer-directory": { - source: "iana" - }, - "application/private-token-request": { - source: "iana" - }, - "application/private-token-response": { - source: "iana" - }, - "application/problem+json": { - source: "iana", - compressible: true - }, - "application/problem+xml": { - source: "iana", - compressible: true - }, - "application/provenance+xml": { - source: "iana", - compressible: true, - extensions: ["provx"] - }, - "application/provided-claims+jwt": { - source: "iana" - }, - "application/prs.alvestrand.titrax-sheet": { - source: "iana" - }, - "application/prs.cww": { - source: "iana", - extensions: ["cww"] - }, - "application/prs.cyn": { - source: "iana", - charset: "7-BIT" - }, - "application/prs.hpub+zip": { - source: "iana", - compressible: false - }, - "application/prs.implied-document+xml": { - source: "iana", - compressible: true - }, - "application/prs.implied-executable": { - source: "iana" - }, - "application/prs.implied-object+json": { - source: "iana", - compressible: true - }, - "application/prs.implied-object+json-seq": { - source: "iana" - }, - "application/prs.implied-object+yaml": { - source: "iana" - }, - "application/prs.implied-structure": { - source: "iana" - }, - "application/prs.mayfile": { - source: "iana" - }, - "application/prs.nprend": { - source: "iana" - }, - "application/prs.plucker": { - source: "iana" - }, - "application/prs.rdf-xml-crypt": { - source: "iana" - }, - "application/prs.vcfbzip2": { - source: "iana" - }, - "application/prs.xsf+xml": { - source: "iana", - compressible: true, - extensions: ["xsf"] - }, - "application/pskc+xml": { - source: "iana", - compressible: true, - extensions: ["pskcxml"] - }, - "application/pvd+json": { - source: "iana", - compressible: true - }, - "application/qsig": { - source: "iana" - }, - "application/raml+yaml": { - compressible: true, - extensions: ["raml"] - }, - "application/raptorfec": { - source: "iana" - }, - "application/rdap+json": { - source: "iana", - compressible: true - }, - "application/rdf+xml": { - source: "iana", - compressible: true, - extensions: ["rdf", "owl"] - }, - "application/reginfo+xml": { - source: "iana", - compressible: true, - extensions: ["rif"] - }, - "application/relax-ng-compact-syntax": { - source: "iana", - extensions: ["rnc"] - }, - "application/remote-printing": { - source: "apache" - }, - "application/reputon+json": { - source: "iana", - compressible: true - }, - "application/resolve-response+jwt": { - source: "iana" - }, - "application/resource-lists+xml": { - source: "iana", - compressible: true, - extensions: ["rl"] - }, - "application/resource-lists-diff+xml": { - source: "iana", - compressible: true, - extensions: ["rld"] - }, - "application/rfc+xml": { - source: "iana", - compressible: true - }, - "application/riscos": { - source: "iana" - }, - "application/rlmi+xml": { - source: "iana", - compressible: true - }, - "application/rls-services+xml": { - source: "iana", - compressible: true, - extensions: ["rs"] - }, - "application/route-apd+xml": { - source: "iana", - compressible: true, - extensions: ["rapd"] - }, - "application/route-s-tsid+xml": { - source: "iana", - compressible: true, - extensions: ["sls"] - }, - "application/route-usd+xml": { - source: "iana", - compressible: true, - extensions: ["rusd"] - }, - "application/rpki-checklist": { - source: "iana" - }, - "application/rpki-ghostbusters": { - source: "iana", - extensions: ["gbr"] - }, - "application/rpki-manifest": { - source: "iana", - extensions: ["mft"] - }, - "application/rpki-publication": { - source: "iana" - }, - "application/rpki-roa": { - source: "iana", - extensions: ["roa"] - }, - "application/rpki-signed-tal": { - source: "iana" - }, - "application/rpki-updown": { - source: "iana" - }, - "application/rsd+xml": { - source: "apache", - compressible: true, - extensions: ["rsd"] - }, - "application/rss+xml": { - source: "apache", - compressible: true, - extensions: ["rss"] - }, - "application/rtf": { - source: "iana", - compressible: true, - extensions: ["rtf"] - }, - "application/rtploopback": { - source: "iana" - }, - "application/rtx": { - source: "iana" - }, - "application/samlassertion+xml": { - source: "iana", - compressible: true - }, - "application/samlmetadata+xml": { - source: "iana", - compressible: true - }, - "application/sarif+json": { - source: "iana", - compressible: true - }, - "application/sarif-external-properties+json": { - source: "iana", - compressible: true - }, - "application/sbe": { - source: "iana" - }, - "application/sbml+xml": { - source: "iana", - compressible: true, - extensions: ["sbml"] - }, - "application/scaip+xml": { - source: "iana", - compressible: true - }, - "application/scim+json": { - source: "iana", - compressible: true - }, - "application/scvp-cv-request": { - source: "iana", - extensions: ["scq"] - }, - "application/scvp-cv-response": { - source: "iana", - extensions: ["scs"] - }, - "application/scvp-vp-request": { - source: "iana", - extensions: ["spq"] - }, - "application/scvp-vp-response": { - source: "iana", - extensions: ["spp"] - }, - "application/sdp": { - source: "iana", - extensions: ["sdp"] - }, - "application/secevent+jwt": { - source: "iana" - }, - "application/senml+cbor": { - source: "iana" - }, - "application/senml+json": { - source: "iana", - compressible: true - }, - "application/senml+xml": { - source: "iana", - compressible: true, - extensions: ["senmlx"] - }, - "application/senml-etch+cbor": { - source: "iana" - }, - "application/senml-etch+json": { - source: "iana", - compressible: true - }, - "application/senml-exi": { - source: "iana" - }, - "application/sensml+cbor": { - source: "iana" - }, - "application/sensml+json": { - source: "iana", - compressible: true - }, - "application/sensml+xml": { - source: "iana", - compressible: true, - extensions: ["sensmlx"] - }, - "application/sensml-exi": { - source: "iana" - }, - "application/sep+xml": { - source: "iana", - compressible: true - }, - "application/sep-exi": { - source: "iana" - }, - "application/session-info": { - source: "iana" - }, - "application/set-payment": { - source: "iana" - }, - "application/set-payment-initiation": { - source: "iana", - extensions: ["setpay"] - }, - "application/set-registration": { - source: "iana" - }, - "application/set-registration-initiation": { - source: "iana", - extensions: ["setreg"] - }, - "application/sgml": { - source: "iana" - }, - "application/sgml-open-catalog": { - source: "iana" - }, - "application/shf+xml": { - source: "iana", - compressible: true, - extensions: ["shf"] - }, - "application/sieve": { - source: "iana", - extensions: ["siv", "sieve"] - }, - "application/simple-filter+xml": { - source: "iana", - compressible: true - }, - "application/simple-message-summary": { - source: "iana" - }, - "application/simplesymbolcontainer": { - source: "iana" - }, - "application/sipc": { - source: "iana" - }, - "application/slate": { - source: "iana" - }, - "application/smil": { - source: "apache" - }, - "application/smil+xml": { - source: "iana", - compressible: true, - extensions: ["smi", "smil"] - }, - "application/smpte336m": { - source: "iana" - }, - "application/soap+fastinfoset": { - source: "iana" - }, - "application/soap+xml": { - source: "iana", - compressible: true - }, - "application/sparql-query": { - source: "iana", - extensions: ["rq"] - }, - "application/sparql-results+xml": { - source: "iana", - compressible: true, - extensions: ["srx"] - }, - "application/spdx+json": { - source: "iana", - compressible: true - }, - "application/spirits-event+xml": { - source: "iana", - compressible: true - }, - "application/sql": { - source: "iana", - extensions: ["sql"] - }, - "application/srgs": { - source: "iana", - extensions: ["gram"] - }, - "application/srgs+xml": { - source: "iana", - compressible: true, - extensions: ["grxml"] - }, - "application/sru+xml": { - source: "iana", - compressible: true, - extensions: ["sru"] - }, - "application/ssdl+xml": { - source: "apache", - compressible: true, - extensions: ["ssdl"] - }, - "application/sslkeylogfile": { - source: "iana" - }, - "application/ssml+xml": { - source: "iana", - compressible: true, - extensions: ["ssml"] - }, - "application/st2110-41": { - source: "iana" - }, - "application/stix+json": { - source: "iana", - compressible: true - }, - "application/stratum": { - source: "iana" - }, - "application/swid+cbor": { - source: "iana" - }, - "application/swid+xml": { - source: "iana", - compressible: true, - extensions: ["swidtag"] - }, - "application/tamp-apex-update": { - source: "iana" - }, - "application/tamp-apex-update-confirm": { - source: "iana" - }, - "application/tamp-community-update": { - source: "iana" - }, - "application/tamp-community-update-confirm": { - source: "iana" - }, - "application/tamp-error": { - source: "iana" - }, - "application/tamp-sequence-adjust": { - source: "iana" - }, - "application/tamp-sequence-adjust-confirm": { - source: "iana" - }, - "application/tamp-status-query": { - source: "iana" - }, - "application/tamp-status-response": { - source: "iana" - }, - "application/tamp-update": { - source: "iana" - }, - "application/tamp-update-confirm": { - source: "iana" - }, - "application/tar": { - compressible: true - }, - "application/taxii+json": { - source: "iana", - compressible: true - }, - "application/td+json": { - source: "iana", - compressible: true - }, - "application/tei+xml": { - source: "iana", - compressible: true, - extensions: ["tei", "teicorpus"] - }, - "application/tetra_isi": { - source: "iana" - }, - "application/thraud+xml": { - source: "iana", - compressible: true, - extensions: ["tfi"] - }, - "application/timestamp-query": { - source: "iana" - }, - "application/timestamp-reply": { - source: "iana" - }, - "application/timestamped-data": { - source: "iana", - extensions: ["tsd"] - }, - "application/tlsrpt+gzip": { - source: "iana" - }, - "application/tlsrpt+json": { - source: "iana", - compressible: true - }, - "application/tm+json": { - source: "iana", - compressible: true - }, - "application/tnauthlist": { - source: "iana" - }, - "application/toc+cbor": { - source: "iana" - }, - "application/token-introspection+jwt": { - source: "iana" - }, - "application/toml": { - source: "iana", - compressible: true, - extensions: ["toml"] - }, - "application/trickle-ice-sdpfrag": { - source: "iana" - }, - "application/trig": { - source: "iana", - extensions: ["trig"] - }, - "application/trust-chain+json": { - source: "iana", - compressible: true - }, - "application/trust-mark+jwt": { - source: "iana" - }, - "application/trust-mark-delegation+jwt": { - source: "iana" - }, - "application/ttml+xml": { - source: "iana", - compressible: true, - extensions: ["ttml"] - }, - "application/tve-trigger": { - source: "iana" - }, - "application/tzif": { - source: "iana" - }, - "application/tzif-leap": { - source: "iana" - }, - "application/ubjson": { - compressible: false, - extensions: ["ubj"] - }, - "application/uccs+cbor": { - source: "iana" - }, - "application/ujcs+json": { - source: "iana", - compressible: true - }, - "application/ulpfec": { - source: "iana" - }, - "application/urc-grpsheet+xml": { - source: "iana", - compressible: true - }, - "application/urc-ressheet+xml": { - source: "iana", - compressible: true, - extensions: ["rsheet"] - }, - "application/urc-targetdesc+xml": { - source: "iana", - compressible: true, - extensions: ["td"] - }, - "application/urc-uisocketdesc+xml": { - source: "iana", - compressible: true - }, - "application/vc": { - source: "iana" - }, - "application/vc+cose": { - source: "iana" - }, - "application/vc+jwt": { - source: "iana" - }, - "application/vcard+json": { - source: "iana", - compressible: true - }, - "application/vcard+xml": { - source: "iana", - compressible: true - }, - "application/vemmi": { - source: "iana" - }, - "application/vividence.scriptfile": { - source: "apache" - }, - "application/vnd.1000minds.decision-model+xml": { - source: "iana", - compressible: true, - extensions: ["1km"] - }, - "application/vnd.1ob": { - source: "iana" - }, - "application/vnd.3gpp-prose+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp-prose-pc3a+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp-prose-pc3ach+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp-prose-pc3ch+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp-prose-pc8+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp-v2x-local-service-information": { - source: "iana" - }, - "application/vnd.3gpp.5gnas": { - source: "iana" - }, - "application/vnd.3gpp.5gsa2x": { - source: "iana" - }, - "application/vnd.3gpp.5gsa2x-local-service-information": { - source: "iana" - }, - "application/vnd.3gpp.5gsv2x": { - source: "iana" - }, - "application/vnd.3gpp.5gsv2x-local-service-information": { - source: "iana" - }, - "application/vnd.3gpp.access-transfer-events+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.bsf+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.crs+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.current-location-discovery+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.gmop+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.gtpc": { - source: "iana" - }, - "application/vnd.3gpp.interworking-data": { - source: "iana" - }, - "application/vnd.3gpp.lpp": { - source: "iana" - }, - "application/vnd.3gpp.mc-signalling-ear": { - source: "iana" - }, - "application/vnd.3gpp.mcdata-affiliation-command+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.mcdata-info+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.mcdata-msgstore-ctrl-request+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.mcdata-payload": { - source: "iana" - }, - "application/vnd.3gpp.mcdata-regroup+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.mcdata-service-config+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.mcdata-signalling": { - source: "iana" - }, - "application/vnd.3gpp.mcdata-ue-config+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.mcdata-user-profile+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.mcptt-affiliation-command+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.mcptt-floor-request+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.mcptt-info+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.mcptt-location-info+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.mcptt-mbms-usage-info+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.mcptt-regroup+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.mcptt-service-config+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.mcptt-signed+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.mcptt-ue-config+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.mcptt-ue-init-config+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.mcptt-user-profile+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.mcvideo-affiliation-command+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.mcvideo-info+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.mcvideo-location-info+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.mcvideo-mbms-usage-info+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.mcvideo-regroup+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.mcvideo-service-config+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.mcvideo-transmission-request+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.mcvideo-ue-config+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.mcvideo-user-profile+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.mid-call+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.ngap": { - source: "iana" - }, - "application/vnd.3gpp.pfcp": { - source: "iana" - }, - "application/vnd.3gpp.pic-bw-large": { - source: "iana", - extensions: ["plb"] - }, - "application/vnd.3gpp.pic-bw-small": { - source: "iana", - extensions: ["psb"] - }, - "application/vnd.3gpp.pic-bw-var": { - source: "iana", - extensions: ["pvb"] - }, - "application/vnd.3gpp.pinapp-info+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.s1ap": { - source: "iana" - }, - "application/vnd.3gpp.seal-group-doc+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.seal-info+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.seal-location-info+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.seal-mbms-usage-info+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.seal-network-qos-management-info+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.seal-ue-config-info+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.seal-unicast-info+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.seal-user-profile-info+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.sms": { - source: "iana" - }, - "application/vnd.3gpp.sms+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.srvcc-ext+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.srvcc-info+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.state-and-event-info+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.ussd+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.v2x": { - source: "iana" - }, - "application/vnd.3gpp.vae-info+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp2.bcmcsinfo+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp2.sms": { - source: "iana" - }, - "application/vnd.3gpp2.tcap": { - source: "iana", - extensions: ["tcap"] - }, - "application/vnd.3lightssoftware.imagescal": { - source: "iana" - }, - "application/vnd.3m.post-it-notes": { - source: "iana", - extensions: ["pwn"] - }, - "application/vnd.accpac.simply.aso": { - source: "iana", - extensions: ["aso"] - }, - "application/vnd.accpac.simply.imp": { - source: "iana", - extensions: ["imp"] - }, - "application/vnd.acm.addressxfer+json": { - source: "iana", - compressible: true - }, - "application/vnd.acm.chatbot+json": { - source: "iana", - compressible: true - }, - "application/vnd.acucobol": { - source: "iana", - extensions: ["acu"] - }, - "application/vnd.acucorp": { - source: "iana", - extensions: ["atc", "acutc"] - }, - "application/vnd.adobe.air-application-installer-package+zip": { - source: "apache", - compressible: false, - extensions: ["air"] - }, - "application/vnd.adobe.flash.movie": { - source: "iana" - }, - "application/vnd.adobe.formscentral.fcdt": { - source: "iana", - extensions: ["fcdt"] - }, - "application/vnd.adobe.fxp": { - source: "iana", - extensions: ["fxp", "fxpl"] - }, - "application/vnd.adobe.partial-upload": { - source: "iana" - }, - "application/vnd.adobe.xdp+xml": { - source: "iana", - compressible: true, - extensions: ["xdp"] - }, - "application/vnd.adobe.xfdf": { - source: "apache", - extensions: ["xfdf"] - }, - "application/vnd.aether.imp": { - source: "iana" - }, - "application/vnd.afpc.afplinedata": { - source: "iana" - }, - "application/vnd.afpc.afplinedata-pagedef": { - source: "iana" - }, - "application/vnd.afpc.cmoca-cmresource": { - source: "iana" - }, - "application/vnd.afpc.foca-charset": { - source: "iana" - }, - "application/vnd.afpc.foca-codedfont": { - source: "iana" - }, - "application/vnd.afpc.foca-codepage": { - source: "iana" - }, - "application/vnd.afpc.modca": { - source: "iana" - }, - "application/vnd.afpc.modca-cmtable": { - source: "iana" - }, - "application/vnd.afpc.modca-formdef": { - source: "iana" - }, - "application/vnd.afpc.modca-mediummap": { - source: "iana" - }, - "application/vnd.afpc.modca-objectcontainer": { - source: "iana" - }, - "application/vnd.afpc.modca-overlay": { - source: "iana" - }, - "application/vnd.afpc.modca-pagesegment": { - source: "iana" - }, - "application/vnd.age": { - source: "iana", - extensions: ["age"] - }, - "application/vnd.ah-barcode": { - source: "apache" - }, - "application/vnd.ahead.space": { - source: "iana", - extensions: ["ahead"] - }, - "application/vnd.airzip.filesecure.azf": { - source: "iana", - extensions: ["azf"] - }, - "application/vnd.airzip.filesecure.azs": { - source: "iana", - extensions: ["azs"] - }, - "application/vnd.amadeus+json": { - source: "iana", - compressible: true - }, - "application/vnd.amazon.ebook": { - source: "apache", - extensions: ["azw"] - }, - "application/vnd.amazon.mobi8-ebook": { - source: "iana" - }, - "application/vnd.americandynamics.acc": { - source: "iana", - extensions: ["acc"] - }, - "application/vnd.amiga.ami": { - source: "iana", - extensions: ["ami"] - }, - "application/vnd.amundsen.maze+xml": { - source: "iana", - compressible: true - }, - "application/vnd.android.ota": { - source: "iana" - }, - "application/vnd.android.package-archive": { - source: "apache", - compressible: false, - extensions: ["apk"] - }, - "application/vnd.anki": { - source: "iana" - }, - "application/vnd.anser-web-certificate-issue-initiation": { - source: "iana", - extensions: ["cii"] - }, - "application/vnd.anser-web-funds-transfer-initiation": { - source: "apache", - extensions: ["fti"] - }, - "application/vnd.antix.game-component": { - source: "iana", - extensions: ["atx"] - }, - "application/vnd.apache.arrow.file": { - source: "iana" - }, - "application/vnd.apache.arrow.stream": { - source: "iana" - }, - "application/vnd.apache.parquet": { - source: "iana" - }, - "application/vnd.apache.thrift.binary": { - source: "iana" - }, - "application/vnd.apache.thrift.compact": { - source: "iana" - }, - "application/vnd.apache.thrift.json": { - source: "iana" - }, - "application/vnd.apexlang": { - source: "iana" - }, - "application/vnd.api+json": { - source: "iana", - compressible: true - }, - "application/vnd.aplextor.warrp+json": { - source: "iana", - compressible: true - }, - "application/vnd.apothekende.reservation+json": { - source: "iana", - compressible: true - }, - "application/vnd.apple.installer+xml": { - source: "iana", - compressible: true, - extensions: ["mpkg"] - }, - "application/vnd.apple.keynote": { - source: "iana", - extensions: ["key"] - }, - "application/vnd.apple.mpegurl": { - source: "iana", - extensions: ["m3u8"] - }, - "application/vnd.apple.numbers": { - source: "iana", - extensions: ["numbers"] - }, - "application/vnd.apple.pages": { - source: "iana", - extensions: ["pages"] - }, - "application/vnd.apple.pkpass": { - compressible: false, - extensions: ["pkpass"] - }, - "application/vnd.arastra.swi": { - source: "apache" - }, - "application/vnd.aristanetworks.swi": { - source: "iana", - extensions: ["swi"] - }, - "application/vnd.artisan+json": { - source: "iana", - compressible: true - }, - "application/vnd.artsquare": { - source: "iana" - }, - "application/vnd.astraea-software.iota": { - source: "iana", - extensions: ["iota"] - }, - "application/vnd.audiograph": { - source: "iana", - extensions: ["aep"] - }, - "application/vnd.autodesk.fbx": { - extensions: ["fbx"] - }, - "application/vnd.autopackage": { - source: "iana" - }, - "application/vnd.avalon+json": { - source: "iana", - compressible: true - }, - "application/vnd.avistar+xml": { - source: "iana", - compressible: true - }, - "application/vnd.balsamiq.bmml+xml": { - source: "iana", - compressible: true, - extensions: ["bmml"] - }, - "application/vnd.balsamiq.bmpr": { - source: "iana" - }, - "application/vnd.banana-accounting": { - source: "iana" - }, - "application/vnd.bbf.usp.error": { - source: "iana" - }, - "application/vnd.bbf.usp.msg": { - source: "iana" - }, - "application/vnd.bbf.usp.msg+json": { - source: "iana", - compressible: true - }, - "application/vnd.bekitzur-stech+json": { - source: "iana", - compressible: true - }, - "application/vnd.belightsoft.lhzd+zip": { - source: "iana", - compressible: false - }, - "application/vnd.belightsoft.lhzl+zip": { - source: "iana", - compressible: false - }, - "application/vnd.bint.med-content": { - source: "iana" - }, - "application/vnd.biopax.rdf+xml": { - source: "iana", - compressible: true - }, - "application/vnd.blink-idb-value-wrapper": { - source: "iana" - }, - "application/vnd.blueice.multipass": { - source: "iana", - extensions: ["mpm"] - }, - "application/vnd.bluetooth.ep.oob": { - source: "iana" - }, - "application/vnd.bluetooth.le.oob": { - source: "iana" - }, - "application/vnd.bmi": { - source: "iana", - extensions: ["bmi"] - }, - "application/vnd.bpf": { - source: "iana" - }, - "application/vnd.bpf3": { - source: "iana" - }, - "application/vnd.businessobjects": { - source: "iana", - extensions: ["rep"] - }, - "application/vnd.byu.uapi+json": { - source: "iana", - compressible: true - }, - "application/vnd.bzip3": { - source: "iana" - }, - "application/vnd.c3voc.schedule+xml": { - source: "iana", - compressible: true - }, - "application/vnd.cab-jscript": { - source: "iana" - }, - "application/vnd.canon-cpdl": { - source: "iana" - }, - "application/vnd.canon-lips": { - source: "iana" - }, - "application/vnd.capasystems-pg+json": { - source: "iana", - compressible: true - }, - "application/vnd.cendio.thinlinc.clientconf": { - source: "iana" - }, - "application/vnd.century-systems.tcp_stream": { - source: "iana" - }, - "application/vnd.chemdraw+xml": { - source: "iana", - compressible: true, - extensions: ["cdxml"] - }, - "application/vnd.chess-pgn": { - source: "iana" - }, - "application/vnd.chipnuts.karaoke-mmd": { - source: "iana", - extensions: ["mmd"] - }, - "application/vnd.ciedi": { - source: "iana" - }, - "application/vnd.cinderella": { - source: "iana", - extensions: ["cdy"] - }, - "application/vnd.cirpack.isdn-ext": { - source: "iana" - }, - "application/vnd.citationstyles.style+xml": { - source: "iana", - compressible: true, - extensions: ["csl"] - }, - "application/vnd.claymore": { - source: "iana", - extensions: ["cla"] - }, - "application/vnd.cloanto.rp9": { - source: "iana", - extensions: ["rp9"] - }, - "application/vnd.clonk.c4group": { - source: "iana", - extensions: ["c4g", "c4d", "c4f", "c4p", "c4u"] - }, - "application/vnd.cluetrust.cartomobile-config": { - source: "iana", - extensions: ["c11amc"] - }, - "application/vnd.cluetrust.cartomobile-config-pkg": { - source: "iana", - extensions: ["c11amz"] - }, - "application/vnd.cncf.helm.chart.content.v1.tar+gzip": { - source: "iana" - }, - "application/vnd.cncf.helm.chart.provenance.v1.prov": { - source: "iana" - }, - "application/vnd.cncf.helm.config.v1+json": { - source: "iana", - compressible: true - }, - "application/vnd.coffeescript": { - source: "iana" - }, - "application/vnd.collabio.xodocuments.document": { - source: "iana" - }, - "application/vnd.collabio.xodocuments.document-template": { - source: "iana" - }, - "application/vnd.collabio.xodocuments.presentation": { - source: "iana" - }, - "application/vnd.collabio.xodocuments.presentation-template": { - source: "iana" - }, - "application/vnd.collabio.xodocuments.spreadsheet": { - source: "iana" - }, - "application/vnd.collabio.xodocuments.spreadsheet-template": { - source: "iana" - }, - "application/vnd.collection+json": { - source: "iana", - compressible: true - }, - "application/vnd.collection.doc+json": { - source: "iana", - compressible: true - }, - "application/vnd.collection.next+json": { - source: "iana", - compressible: true - }, - "application/vnd.comicbook+zip": { - source: "iana", - compressible: false - }, - "application/vnd.comicbook-rar": { - source: "iana" - }, - "application/vnd.commerce-battelle": { - source: "iana" - }, - "application/vnd.commonspace": { - source: "iana", - extensions: ["csp"] - }, - "application/vnd.contact.cmsg": { - source: "iana", - extensions: ["cdbcmsg"] - }, - "application/vnd.coreos.ignition+json": { - source: "iana", - compressible: true - }, - "application/vnd.cosmocaller": { - source: "iana", - extensions: ["cmc"] - }, - "application/vnd.crick.clicker": { - source: "iana", - extensions: ["clkx"] - }, - "application/vnd.crick.clicker.keyboard": { - source: "iana", - extensions: ["clkk"] - }, - "application/vnd.crick.clicker.palette": { - source: "iana", - extensions: ["clkp"] - }, - "application/vnd.crick.clicker.template": { - source: "iana", - extensions: ["clkt"] - }, - "application/vnd.crick.clicker.wordbank": { - source: "iana", - extensions: ["clkw"] - }, - "application/vnd.criticaltools.wbs+xml": { - source: "iana", - compressible: true, - extensions: ["wbs"] - }, - "application/vnd.cryptii.pipe+json": { - source: "iana", - compressible: true - }, - "application/vnd.crypto-shade-file": { - source: "iana" - }, - "application/vnd.cryptomator.encrypted": { - source: "iana" - }, - "application/vnd.cryptomator.vault": { - source: "iana" - }, - "application/vnd.ctc-posml": { - source: "iana", - extensions: ["pml"] - }, - "application/vnd.ctct.ws+xml": { - source: "iana", - compressible: true - }, - "application/vnd.cups-pdf": { - source: "iana" - }, - "application/vnd.cups-postscript": { - source: "iana" - }, - "application/vnd.cups-ppd": { - source: "iana", - extensions: ["ppd"] - }, - "application/vnd.cups-raster": { - source: "iana" - }, - "application/vnd.cups-raw": { - source: "iana" - }, - "application/vnd.curl": { - source: "iana" - }, - "application/vnd.curl.car": { - source: "apache", - extensions: ["car"] - }, - "application/vnd.curl.pcurl": { - source: "apache", - extensions: ["pcurl"] - }, - "application/vnd.cyan.dean.root+xml": { - source: "iana", - compressible: true - }, - "application/vnd.cybank": { - source: "iana" - }, - "application/vnd.cyclonedx+json": { - source: "iana", - compressible: true - }, - "application/vnd.cyclonedx+xml": { - source: "iana", - compressible: true - }, - "application/vnd.d2l.coursepackage1p0+zip": { - source: "iana", - compressible: false - }, - "application/vnd.d3m-dataset": { - source: "iana" - }, - "application/vnd.d3m-problem": { - source: "iana" - }, - "application/vnd.dart": { - source: "iana", - compressible: true, - extensions: ["dart"] - }, - "application/vnd.data-vision.rdz": { - source: "iana", - extensions: ["rdz"] - }, - "application/vnd.datalog": { - source: "iana" - }, - "application/vnd.datapackage+json": { - source: "iana", - compressible: true - }, - "application/vnd.dataresource+json": { - source: "iana", - compressible: true - }, - "application/vnd.dbf": { - source: "iana", - extensions: ["dbf"] - }, - "application/vnd.dcmp+xml": { - source: "iana", - compressible: true, - extensions: ["dcmp"] - }, - "application/vnd.debian.binary-package": { - source: "iana" - }, - "application/vnd.dece.data": { - source: "iana", - extensions: ["uvf", "uvvf", "uvd", "uvvd"] - }, - "application/vnd.dece.ttml+xml": { - source: "iana", - compressible: true, - extensions: ["uvt", "uvvt"] - }, - "application/vnd.dece.unspecified": { - source: "iana", - extensions: ["uvx", "uvvx"] - }, - "application/vnd.dece.zip": { - source: "iana", - extensions: ["uvz", "uvvz"] - }, - "application/vnd.denovo.fcselayout-link": { - source: "iana", - extensions: ["fe_launch"] - }, - "application/vnd.desmume.movie": { - source: "iana" - }, - "application/vnd.dir-bi.plate-dl-nosuffix": { - source: "iana" - }, - "application/vnd.dm.delegation+xml": { - source: "iana", - compressible: true - }, - "application/vnd.dna": { - source: "iana", - extensions: ["dna"] - }, - "application/vnd.document+json": { - source: "iana", - compressible: true - }, - "application/vnd.dolby.mlp": { - source: "apache", - extensions: ["mlp"] - }, - "application/vnd.dolby.mobile.1": { - source: "iana" - }, - "application/vnd.dolby.mobile.2": { - source: "iana" - }, - "application/vnd.doremir.scorecloud-binary-document": { - source: "iana" - }, - "application/vnd.dpgraph": { - source: "iana", - extensions: ["dpg"] - }, - "application/vnd.dreamfactory": { - source: "iana", - extensions: ["dfac"] - }, - "application/vnd.drive+json": { - source: "iana", - compressible: true - }, - "application/vnd.ds-keypoint": { - source: "apache", - extensions: ["kpxx"] - }, - "application/vnd.dtg.local": { - source: "iana" - }, - "application/vnd.dtg.local.flash": { - source: "iana" - }, - "application/vnd.dtg.local.html": { - source: "iana" - }, - "application/vnd.dvb.ait": { - source: "iana", - extensions: ["ait"] - }, - "application/vnd.dvb.dvbisl+xml": { - source: "iana", - compressible: true - }, - "application/vnd.dvb.dvbj": { - source: "iana" - }, - "application/vnd.dvb.esgcontainer": { - source: "iana" - }, - "application/vnd.dvb.ipdcdftnotifaccess": { - source: "iana" - }, - "application/vnd.dvb.ipdcesgaccess": { - source: "iana" - }, - "application/vnd.dvb.ipdcesgaccess2": { - source: "iana" - }, - "application/vnd.dvb.ipdcesgpdd": { - source: "iana" - }, - "application/vnd.dvb.ipdcroaming": { - source: "iana" - }, - "application/vnd.dvb.iptv.alfec-base": { - source: "iana" - }, - "application/vnd.dvb.iptv.alfec-enhancement": { - source: "iana" - }, - "application/vnd.dvb.notif-aggregate-root+xml": { - source: "iana", - compressible: true - }, - "application/vnd.dvb.notif-container+xml": { - source: "iana", - compressible: true - }, - "application/vnd.dvb.notif-generic+xml": { - source: "iana", - compressible: true - }, - "application/vnd.dvb.notif-ia-msglist+xml": { - source: "iana", - compressible: true - }, - "application/vnd.dvb.notif-ia-registration-request+xml": { - source: "iana", - compressible: true - }, - "application/vnd.dvb.notif-ia-registration-response+xml": { - source: "iana", - compressible: true - }, - "application/vnd.dvb.notif-init+xml": { - source: "iana", - compressible: true - }, - "application/vnd.dvb.pfr": { - source: "iana" - }, - "application/vnd.dvb.service": { - source: "iana", - extensions: ["svc"] - }, - "application/vnd.dxr": { - source: "iana" - }, - "application/vnd.dynageo": { - source: "iana", - extensions: ["geo"] - }, - "application/vnd.dzr": { - source: "iana" - }, - "application/vnd.easykaraoke.cdgdownload": { - source: "iana" - }, - "application/vnd.ecdis-update": { - source: "iana" - }, - "application/vnd.ecip.rlp": { - source: "iana" - }, - "application/vnd.eclipse.ditto+json": { - source: "iana", - compressible: true - }, - "application/vnd.ecowin.chart": { - source: "iana", - extensions: ["mag"] - }, - "application/vnd.ecowin.filerequest": { - source: "iana" - }, - "application/vnd.ecowin.fileupdate": { - source: "iana" - }, - "application/vnd.ecowin.series": { - source: "iana" - }, - "application/vnd.ecowin.seriesrequest": { - source: "iana" - }, - "application/vnd.ecowin.seriesupdate": { - source: "iana" - }, - "application/vnd.efi.img": { - source: "iana" - }, - "application/vnd.efi.iso": { - source: "iana" - }, - "application/vnd.eln+zip": { - source: "iana", - compressible: false - }, - "application/vnd.emclient.accessrequest+xml": { - source: "iana", - compressible: true - }, - "application/vnd.enliven": { - source: "iana", - extensions: ["nml"] - }, - "application/vnd.enphase.envoy": { - source: "iana" - }, - "application/vnd.eprints.data+xml": { - source: "iana", - compressible: true - }, - "application/vnd.epson.esf": { - source: "iana", - extensions: ["esf"] - }, - "application/vnd.epson.msf": { - source: "iana", - extensions: ["msf"] - }, - "application/vnd.epson.quickanime": { - source: "iana", - extensions: ["qam"] - }, - "application/vnd.epson.salt": { - source: "iana", - extensions: ["slt"] - }, - "application/vnd.epson.ssf": { - source: "iana", - extensions: ["ssf"] - }, - "application/vnd.ericsson.quickcall": { - source: "iana" - }, - "application/vnd.erofs": { - source: "iana" - }, - "application/vnd.espass-espass+zip": { - source: "iana", - compressible: false - }, - "application/vnd.eszigno3+xml": { - source: "iana", - compressible: true, - extensions: ["es3", "et3"] - }, - "application/vnd.etsi.aoc+xml": { - source: "iana", - compressible: true - }, - "application/vnd.etsi.asic-e+zip": { - source: "iana", - compressible: false - }, - "application/vnd.etsi.asic-s+zip": { - source: "iana", - compressible: false - }, - "application/vnd.etsi.cug+xml": { - source: "iana", - compressible: true - }, - "application/vnd.etsi.iptvcommand+xml": { - source: "iana", - compressible: true - }, - "application/vnd.etsi.iptvdiscovery+xml": { - source: "iana", - compressible: true - }, - "application/vnd.etsi.iptvprofile+xml": { - source: "iana", - compressible: true - }, - "application/vnd.etsi.iptvsad-bc+xml": { - source: "iana", - compressible: true - }, - "application/vnd.etsi.iptvsad-cod+xml": { - source: "iana", - compressible: true - }, - "application/vnd.etsi.iptvsad-npvr+xml": { - source: "iana", - compressible: true - }, - "application/vnd.etsi.iptvservice+xml": { - source: "iana", - compressible: true - }, - "application/vnd.etsi.iptvsync+xml": { - source: "iana", - compressible: true - }, - "application/vnd.etsi.iptvueprofile+xml": { - source: "iana", - compressible: true - }, - "application/vnd.etsi.mcid+xml": { - source: "iana", - compressible: true - }, - "application/vnd.etsi.mheg5": { - source: "iana" - }, - "application/vnd.etsi.overload-control-policy-dataset+xml": { - source: "iana", - compressible: true - }, - "application/vnd.etsi.pstn+xml": { - source: "iana", - compressible: true - }, - "application/vnd.etsi.sci+xml": { - source: "iana", - compressible: true - }, - "application/vnd.etsi.simservs+xml": { - source: "iana", - compressible: true - }, - "application/vnd.etsi.timestamp-token": { - source: "iana" - }, - "application/vnd.etsi.tsl+xml": { - source: "iana", - compressible: true - }, - "application/vnd.etsi.tsl.der": { - source: "iana" - }, - "application/vnd.eu.kasparian.car+json": { - source: "iana", - compressible: true - }, - "application/vnd.eudora.data": { - source: "iana" - }, - "application/vnd.evolv.ecig.profile": { - source: "iana" - }, - "application/vnd.evolv.ecig.settings": { - source: "iana" - }, - "application/vnd.evolv.ecig.theme": { - source: "iana" - }, - "application/vnd.exstream-empower+zip": { - source: "iana", - compressible: false - }, - "application/vnd.exstream-package": { - source: "iana" - }, - "application/vnd.ezpix-album": { - source: "iana", - extensions: ["ez2"] - }, - "application/vnd.ezpix-package": { - source: "iana", - extensions: ["ez3"] - }, - "application/vnd.f-secure.mobile": { - source: "iana" - }, - "application/vnd.familysearch.gedcom+zip": { - source: "iana", - compressible: false - }, - "application/vnd.fastcopy-disk-image": { - source: "iana" - }, - "application/vnd.fdf": { - source: "apache", - extensions: ["fdf"] - }, - "application/vnd.fdsn.mseed": { - source: "iana", - extensions: ["mseed"] - }, - "application/vnd.fdsn.seed": { - source: "iana", - extensions: ["seed", "dataless"] - }, - "application/vnd.fdsn.stationxml+xml": { - source: "iana", - charset: "XML-BASED", - compressible: true - }, - "application/vnd.ffsns": { - source: "iana" - }, - "application/vnd.ficlab.flb+zip": { - source: "iana", - compressible: false - }, - "application/vnd.filmit.zfc": { - source: "iana" - }, - "application/vnd.fints": { - source: "iana" - }, - "application/vnd.firemonkeys.cloudcell": { - source: "iana" - }, - "application/vnd.flographit": { - source: "iana", - extensions: ["gph"] - }, - "application/vnd.fluxtime.clip": { - source: "iana", - extensions: ["ftc"] - }, - "application/vnd.font-fontforge-sfd": { - source: "iana" - }, - "application/vnd.framemaker": { - source: "iana", - extensions: ["fm", "frame", "maker", "book"] - }, - "application/vnd.freelog.comic": { - source: "iana" - }, - "application/vnd.frogans.fnc": { - source: "apache", - extensions: ["fnc"] - }, - "application/vnd.frogans.ltf": { - source: "apache", - extensions: ["ltf"] - }, - "application/vnd.fsc.weblaunch": { - source: "iana", - extensions: ["fsc"] - }, - "application/vnd.fujifilm.fb.docuworks": { - source: "iana" - }, - "application/vnd.fujifilm.fb.docuworks.binder": { - source: "iana" - }, - "application/vnd.fujifilm.fb.docuworks.container": { - source: "iana" - }, - "application/vnd.fujifilm.fb.jfi+xml": { - source: "iana", - compressible: true - }, - "application/vnd.fujitsu.oasys": { - source: "iana", - extensions: ["oas"] - }, - "application/vnd.fujitsu.oasys2": { - source: "iana", - extensions: ["oa2"] - }, - "application/vnd.fujitsu.oasys3": { - source: "iana", - extensions: ["oa3"] - }, - "application/vnd.fujitsu.oasysgp": { - source: "iana", - extensions: ["fg5"] - }, - "application/vnd.fujitsu.oasysprs": { - source: "iana", - extensions: ["bh2"] - }, - "application/vnd.fujixerox.art-ex": { - source: "iana" - }, - "application/vnd.fujixerox.art4": { - source: "iana" - }, - "application/vnd.fujixerox.ddd": { - source: "iana", - extensions: ["ddd"] - }, - "application/vnd.fujixerox.docuworks": { - source: "iana", - extensions: ["xdw"] - }, - "application/vnd.fujixerox.docuworks.binder": { - source: "iana", - extensions: ["xbd"] - }, - "application/vnd.fujixerox.docuworks.container": { - source: "iana" - }, - "application/vnd.fujixerox.hbpl": { - source: "iana" - }, - "application/vnd.fut-misnet": { - source: "iana" - }, - "application/vnd.futoin+cbor": { - source: "iana" - }, - "application/vnd.futoin+json": { - source: "iana", - compressible: true - }, - "application/vnd.fuzzysheet": { - source: "iana", - extensions: ["fzs"] - }, - "application/vnd.ga4gh.passport+jwt": { - source: "iana" - }, - "application/vnd.genomatix.tuxedo": { - source: "iana", - extensions: ["txd"] - }, - "application/vnd.genozip": { - source: "iana" - }, - "application/vnd.gentics.grd+json": { - source: "iana", - compressible: true - }, - "application/vnd.gentoo.catmetadata+xml": { - source: "iana", - compressible: true - }, - "application/vnd.gentoo.ebuild": { - source: "iana" - }, - "application/vnd.gentoo.eclass": { - source: "iana" - }, - "application/vnd.gentoo.gpkg": { - source: "iana" - }, - "application/vnd.gentoo.manifest": { - source: "iana" - }, - "application/vnd.gentoo.pkgmetadata+xml": { - source: "iana", - compressible: true - }, - "application/vnd.gentoo.xpak": { - source: "iana" - }, - "application/vnd.geo+json": { - source: "apache", - compressible: true - }, - "application/vnd.geocube+xml": { - source: "apache", - compressible: true - }, - "application/vnd.geogebra.file": { - source: "iana", - extensions: ["ggb"] - }, - "application/vnd.geogebra.pinboard": { - source: "iana" - }, - "application/vnd.geogebra.slides": { - source: "iana", - extensions: ["ggs"] - }, - "application/vnd.geogebra.tool": { - source: "iana", - extensions: ["ggt"] - }, - "application/vnd.geometry-explorer": { - source: "iana", - extensions: ["gex", "gre"] - }, - "application/vnd.geonext": { - source: "iana", - extensions: ["gxt"] - }, - "application/vnd.geoplan": { - source: "iana", - extensions: ["g2w"] - }, - "application/vnd.geospace": { - source: "iana", - extensions: ["g3w"] - }, - "application/vnd.gerber": { - source: "iana" - }, - "application/vnd.globalplatform.card-content-mgt": { - source: "iana" - }, - "application/vnd.globalplatform.card-content-mgt-response": { - source: "iana" - }, - "application/vnd.gmx": { - source: "iana", - extensions: ["gmx"] - }, - "application/vnd.gnu.taler.exchange+json": { - source: "iana", - compressible: true - }, - "application/vnd.gnu.taler.merchant+json": { - source: "iana", - compressible: true - }, - "application/vnd.google-apps.audio": {}, - "application/vnd.google-apps.document": { - compressible: false, - extensions: ["gdoc"] - }, - "application/vnd.google-apps.drawing": { - compressible: false, - extensions: ["gdraw"] - }, - "application/vnd.google-apps.drive-sdk": { - compressible: false - }, - "application/vnd.google-apps.file": {}, - "application/vnd.google-apps.folder": { - compressible: false - }, - "application/vnd.google-apps.form": { - compressible: false, - extensions: ["gform"] - }, - "application/vnd.google-apps.fusiontable": {}, - "application/vnd.google-apps.jam": { - compressible: false, - extensions: ["gjam"] - }, - "application/vnd.google-apps.mail-layout": {}, - "application/vnd.google-apps.map": { - compressible: false, - extensions: ["gmap"] - }, - "application/vnd.google-apps.photo": {}, - "application/vnd.google-apps.presentation": { - compressible: false, - extensions: ["gslides"] - }, - "application/vnd.google-apps.script": { - compressible: false, - extensions: ["gscript"] - }, - "application/vnd.google-apps.shortcut": {}, - "application/vnd.google-apps.site": { - compressible: false, - extensions: ["gsite"] - }, - "application/vnd.google-apps.spreadsheet": { - compressible: false, - extensions: ["gsheet"] - }, - "application/vnd.google-apps.unknown": {}, - "application/vnd.google-apps.video": {}, - "application/vnd.google-earth.kml+xml": { - source: "iana", - compressible: true, - extensions: ["kml"] - }, - "application/vnd.google-earth.kmz": { - source: "iana", - compressible: false, - extensions: ["kmz"] - }, - "application/vnd.gov.sk.e-form+xml": { - source: "apache", - compressible: true - }, - "application/vnd.gov.sk.e-form+zip": { - source: "iana", - compressible: false - }, - "application/vnd.gov.sk.xmldatacontainer+xml": { - source: "iana", - compressible: true, - extensions: ["xdcf"] - }, - "application/vnd.gpxsee.map+xml": { - source: "iana", - compressible: true - }, - "application/vnd.grafeq": { - source: "iana", - extensions: ["gqf", "gqs"] - }, - "application/vnd.gridmp": { - source: "iana" - }, - "application/vnd.groove-account": { - source: "iana", - extensions: ["gac"] - }, - "application/vnd.groove-help": { - source: "iana", - extensions: ["ghf"] - }, - "application/vnd.groove-identity-message": { - source: "iana", - extensions: ["gim"] - }, - "application/vnd.groove-injector": { - source: "iana", - extensions: ["grv"] - }, - "application/vnd.groove-tool-message": { - source: "iana", - extensions: ["gtm"] - }, - "application/vnd.groove-tool-template": { - source: "iana", - extensions: ["tpl"] - }, - "application/vnd.groove-vcard": { - source: "iana", - extensions: ["vcg"] - }, - "application/vnd.hal+json": { - source: "iana", - compressible: true - }, - "application/vnd.hal+xml": { - source: "iana", - compressible: true, - extensions: ["hal"] - }, - "application/vnd.handheld-entertainment+xml": { - source: "iana", - compressible: true, - extensions: ["zmm"] - }, - "application/vnd.hbci": { - source: "iana", - extensions: ["hbci"] - }, - "application/vnd.hc+json": { - source: "iana", - compressible: true - }, - "application/vnd.hcl-bireports": { - source: "iana" - }, - "application/vnd.hdt": { - source: "iana" - }, - "application/vnd.heroku+json": { - source: "iana", - compressible: true - }, - "application/vnd.hhe.lesson-player": { - source: "iana", - extensions: ["les"] - }, - "application/vnd.hp-hpgl": { - source: "iana", - extensions: ["hpgl"] - }, - "application/vnd.hp-hpid": { - source: "iana", - extensions: ["hpid"] - }, - "application/vnd.hp-hps": { - source: "iana", - extensions: ["hps"] - }, - "application/vnd.hp-jlyt": { - source: "iana", - extensions: ["jlt"] - }, - "application/vnd.hp-pcl": { - source: "iana", - extensions: ["pcl"] - }, - "application/vnd.hp-pclxl": { - source: "iana", - extensions: ["pclxl"] - }, - "application/vnd.hsl": { - source: "iana" - }, - "application/vnd.httphone": { - source: "iana" - }, - "application/vnd.hydrostatix.sof-data": { - source: "iana", - extensions: ["sfd-hdstx"] - }, - "application/vnd.hyper+json": { - source: "iana", - compressible: true - }, - "application/vnd.hyper-item+json": { - source: "iana", - compressible: true - }, - "application/vnd.hyperdrive+json": { - source: "iana", - compressible: true - }, - "application/vnd.hzn-3d-crossword": { - source: "iana" - }, - "application/vnd.ibm.afplinedata": { - source: "apache" - }, - "application/vnd.ibm.electronic-media": { - source: "iana" - }, - "application/vnd.ibm.minipay": { - source: "iana", - extensions: ["mpy"] - }, - "application/vnd.ibm.modcap": { - source: "apache", - extensions: ["afp", "listafp", "list3820"] - }, - "application/vnd.ibm.rights-management": { - source: "iana", - extensions: ["irm"] - }, - "application/vnd.ibm.secure-container": { - source: "iana", - extensions: ["sc"] - }, - "application/vnd.iccprofile": { - source: "iana", - extensions: ["icc", "icm"] - }, - "application/vnd.ieee.1905": { - source: "iana" - }, - "application/vnd.igloader": { - source: "iana", - extensions: ["igl"] - }, - "application/vnd.imagemeter.folder+zip": { - source: "iana", - compressible: false - }, - "application/vnd.imagemeter.image+zip": { - source: "iana", - compressible: false - }, - "application/vnd.immervision-ivp": { - source: "iana", - extensions: ["ivp"] - }, - "application/vnd.immervision-ivu": { - source: "iana", - extensions: ["ivu"] - }, - "application/vnd.ims.imsccv1p1": { - source: "iana" - }, - "application/vnd.ims.imsccv1p2": { - source: "iana" - }, - "application/vnd.ims.imsccv1p3": { - source: "iana" - }, - "application/vnd.ims.lis.v2.result+json": { - source: "iana", - compressible: true - }, - "application/vnd.ims.lti.v2.toolconsumerprofile+json": { - source: "iana", - compressible: true - }, - "application/vnd.ims.lti.v2.toolproxy+json": { - source: "iana", - compressible: true - }, - "application/vnd.ims.lti.v2.toolproxy.id+json": { - source: "iana", - compressible: true - }, - "application/vnd.ims.lti.v2.toolsettings+json": { - source: "iana", - compressible: true - }, - "application/vnd.ims.lti.v2.toolsettings.simple+json": { - source: "iana", - compressible: true - }, - "application/vnd.informedcontrol.rms+xml": { - source: "iana", - compressible: true - }, - "application/vnd.informix-visionary": { - source: "apache" - }, - "application/vnd.infotech.project": { - source: "iana" - }, - "application/vnd.infotech.project+xml": { - source: "iana", - compressible: true - }, - "application/vnd.innopath.wamp.notification": { - source: "iana" - }, - "application/vnd.insors.igm": { - source: "iana", - extensions: ["igm"] - }, - "application/vnd.intercon.formnet": { - source: "iana", - extensions: ["xpw", "xpx"] - }, - "application/vnd.intergeo": { - source: "iana", - extensions: ["i2g"] - }, - "application/vnd.intertrust.digibox": { - source: "iana" - }, - "application/vnd.intertrust.nncp": { - source: "iana" - }, - "application/vnd.intu.qbo": { - source: "iana", - extensions: ["qbo"] - }, - "application/vnd.intu.qfx": { - source: "iana", - extensions: ["qfx"] - }, - "application/vnd.ipfs.ipns-record": { - source: "iana" - }, - "application/vnd.ipld.car": { - source: "iana" - }, - "application/vnd.ipld.dag-cbor": { - source: "iana" - }, - "application/vnd.ipld.dag-json": { - source: "iana" - }, - "application/vnd.ipld.raw": { - source: "iana" - }, - "application/vnd.iptc.g2.catalogitem+xml": { - source: "iana", - compressible: true - }, - "application/vnd.iptc.g2.conceptitem+xml": { - source: "iana", - compressible: true - }, - "application/vnd.iptc.g2.knowledgeitem+xml": { - source: "iana", - compressible: true - }, - "application/vnd.iptc.g2.newsitem+xml": { - source: "iana", - compressible: true - }, - "application/vnd.iptc.g2.newsmessage+xml": { - source: "iana", - compressible: true - }, - "application/vnd.iptc.g2.packageitem+xml": { - source: "iana", - compressible: true - }, - "application/vnd.iptc.g2.planningitem+xml": { - source: "iana", - compressible: true - }, - "application/vnd.ipunplugged.rcprofile": { - source: "iana", - extensions: ["rcprofile"] - }, - "application/vnd.irepository.package+xml": { - source: "iana", - compressible: true, - extensions: ["irp"] - }, - "application/vnd.is-xpr": { - source: "iana", - extensions: ["xpr"] - }, - "application/vnd.isac.fcs": { - source: "iana", - extensions: ["fcs"] - }, - "application/vnd.iso11783-10+zip": { - source: "iana", - compressible: false - }, - "application/vnd.jam": { - source: "iana", - extensions: ["jam"] - }, - "application/vnd.japannet-directory-service": { - source: "iana" - }, - "application/vnd.japannet-jpnstore-wakeup": { - source: "iana" - }, - "application/vnd.japannet-payment-wakeup": { - source: "iana" - }, - "application/vnd.japannet-registration": { - source: "iana" - }, - "application/vnd.japannet-registration-wakeup": { - source: "iana" - }, - "application/vnd.japannet-setstore-wakeup": { - source: "iana" - }, - "application/vnd.japannet-verification": { - source: "iana" - }, - "application/vnd.japannet-verification-wakeup": { - source: "iana" - }, - "application/vnd.jcp.javame.midlet-rms": { - source: "iana", - extensions: ["rms"] - }, - "application/vnd.jisp": { - source: "iana", - extensions: ["jisp"] - }, - "application/vnd.joost.joda-archive": { - source: "iana", - extensions: ["joda"] - }, - "application/vnd.jsk.isdn-ngn": { - source: "iana" - }, - "application/vnd.kahootz": { - source: "iana", - extensions: ["ktz", "ktr"] - }, - "application/vnd.kde.karbon": { - source: "iana", - extensions: ["karbon"] - }, - "application/vnd.kde.kchart": { - source: "iana", - extensions: ["chrt"] - }, - "application/vnd.kde.kformula": { - source: "iana", - extensions: ["kfo"] - }, - "application/vnd.kde.kivio": { - source: "iana", - extensions: ["flw"] - }, - "application/vnd.kde.kontour": { - source: "iana", - extensions: ["kon"] - }, - "application/vnd.kde.kpresenter": { - source: "iana", - extensions: ["kpr", "kpt"] - }, - "application/vnd.kde.kspread": { - source: "iana", - extensions: ["ksp"] - }, - "application/vnd.kde.kword": { - source: "iana", - extensions: ["kwd", "kwt"] - }, - "application/vnd.kdl": { - source: "iana" - }, - "application/vnd.kenameaapp": { - source: "iana", - extensions: ["htke"] - }, - "application/vnd.keyman.kmp+zip": { - source: "iana", - compressible: false - }, - "application/vnd.keyman.kmx": { - source: "iana" - }, - "application/vnd.kidspiration": { - source: "iana", - extensions: ["kia"] - }, - "application/vnd.kinar": { - source: "iana", - extensions: ["kne", "knp"] - }, - "application/vnd.koan": { - source: "iana", - extensions: ["skp", "skd", "skt", "skm"] - }, - "application/vnd.kodak-descriptor": { - source: "iana", - extensions: ["sse"] - }, - "application/vnd.las": { - source: "iana" - }, - "application/vnd.las.las+json": { - source: "iana", - compressible: true - }, - "application/vnd.las.las+xml": { - source: "iana", - compressible: true, - extensions: ["lasxml"] - }, - "application/vnd.laszip": { - source: "iana" - }, - "application/vnd.ldev.productlicensing": { - source: "iana" - }, - "application/vnd.leap+json": { - source: "iana", - compressible: true - }, - "application/vnd.liberty-request+xml": { - source: "iana", - compressible: true - }, - "application/vnd.llamagraphics.life-balance.desktop": { - source: "iana", - extensions: ["lbd"] - }, - "application/vnd.llamagraphics.life-balance.exchange+xml": { - source: "iana", - compressible: true, - extensions: ["lbe"] - }, - "application/vnd.logipipe.circuit+zip": { - source: "iana", - compressible: false - }, - "application/vnd.loom": { - source: "iana" - }, - "application/vnd.lotus-1-2-3": { - source: "iana", - extensions: ["123"] - }, - "application/vnd.lotus-approach": { - source: "iana", - extensions: ["apr"] - }, - "application/vnd.lotus-freelance": { - source: "iana", - extensions: ["pre"] - }, - "application/vnd.lotus-notes": { - source: "iana", - extensions: ["nsf"] - }, - "application/vnd.lotus-organizer": { - source: "iana", - extensions: ["org"] - }, - "application/vnd.lotus-screencam": { - source: "iana", - extensions: ["scm"] - }, - "application/vnd.lotus-wordpro": { - source: "iana", - extensions: ["lwp"] - }, - "application/vnd.macports.portpkg": { - source: "iana", - extensions: ["portpkg"] - }, - "application/vnd.mapbox-vector-tile": { - source: "iana", - extensions: ["mvt"] - }, - "application/vnd.marlin.drm.actiontoken+xml": { - source: "iana", - compressible: true - }, - "application/vnd.marlin.drm.conftoken+xml": { - source: "iana", - compressible: true - }, - "application/vnd.marlin.drm.license+xml": { - source: "iana", - compressible: true - }, - "application/vnd.marlin.drm.mdcf": { - source: "iana" - }, - "application/vnd.mason+json": { - source: "iana", - compressible: true - }, - "application/vnd.maxar.archive.3tz+zip": { - source: "iana", - compressible: false - }, - "application/vnd.maxmind.maxmind-db": { - source: "iana" - }, - "application/vnd.mcd": { - source: "iana", - extensions: ["mcd"] - }, - "application/vnd.mdl": { - source: "iana" - }, - "application/vnd.mdl-mbsdf": { - source: "iana" - }, - "application/vnd.medcalcdata": { - source: "iana", - extensions: ["mc1"] - }, - "application/vnd.mediastation.cdkey": { - source: "iana", - extensions: ["cdkey"] - }, - "application/vnd.medicalholodeck.recordxr": { - source: "iana" - }, - "application/vnd.meridian-slingshot": { - source: "iana" - }, - "application/vnd.mermaid": { - source: "iana" - }, - "application/vnd.mfer": { - source: "iana", - extensions: ["mwf"] - }, - "application/vnd.mfmp": { - source: "iana", - extensions: ["mfm"] - }, - "application/vnd.micro+json": { - source: "iana", - compressible: true - }, - "application/vnd.micrografx.flo": { - source: "iana", - extensions: ["flo"] - }, - "application/vnd.micrografx.igx": { - source: "iana", - extensions: ["igx"] - }, - "application/vnd.microsoft.portable-executable": { - source: "iana" - }, - "application/vnd.microsoft.windows.thumbnail-cache": { - source: "iana" - }, - "application/vnd.miele+json": { - source: "iana", - compressible: true - }, - "application/vnd.mif": { - source: "iana", - extensions: ["mif"] - }, - "application/vnd.minisoft-hp3000-save": { - source: "iana" - }, - "application/vnd.mitsubishi.misty-guard.trustweb": { - source: "iana" - }, - "application/vnd.mobius.daf": { - source: "iana", - extensions: ["daf"] - }, - "application/vnd.mobius.dis": { - source: "iana", - extensions: ["dis"] - }, - "application/vnd.mobius.mbk": { - source: "iana", - extensions: ["mbk"] - }, - "application/vnd.mobius.mqy": { - source: "iana", - extensions: ["mqy"] - }, - "application/vnd.mobius.msl": { - source: "iana", - extensions: ["msl"] - }, - "application/vnd.mobius.plc": { - source: "iana", - extensions: ["plc"] - }, - "application/vnd.mobius.txf": { - source: "iana", - extensions: ["txf"] - }, - "application/vnd.modl": { - source: "iana" - }, - "application/vnd.mophun.application": { - source: "iana", - extensions: ["mpn"] - }, - "application/vnd.mophun.certificate": { - source: "iana", - extensions: ["mpc"] - }, - "application/vnd.motorola.flexsuite": { - source: "iana" - }, - "application/vnd.motorola.flexsuite.adsi": { - source: "iana" - }, - "application/vnd.motorola.flexsuite.fis": { - source: "iana" - }, - "application/vnd.motorola.flexsuite.gotap": { - source: "iana" - }, - "application/vnd.motorola.flexsuite.kmr": { - source: "iana" - }, - "application/vnd.motorola.flexsuite.ttc": { - source: "iana" - }, - "application/vnd.motorola.flexsuite.wem": { - source: "iana" - }, - "application/vnd.motorola.iprm": { - source: "iana" - }, - "application/vnd.mozilla.xul+xml": { - source: "iana", - compressible: true, - extensions: ["xul"] - }, - "application/vnd.ms-3mfdocument": { - source: "iana" - }, - "application/vnd.ms-artgalry": { - source: "iana", - extensions: ["cil"] - }, - "application/vnd.ms-asf": { - source: "iana" - }, - "application/vnd.ms-cab-compressed": { - source: "iana", - extensions: ["cab"] - }, - "application/vnd.ms-color.iccprofile": { - source: "apache" - }, - "application/vnd.ms-excel": { - source: "iana", - compressible: false, - extensions: ["xls", "xlm", "xla", "xlc", "xlt", "xlw"] - }, - "application/vnd.ms-excel.addin.macroenabled.12": { - source: "iana", - extensions: ["xlam"] - }, - "application/vnd.ms-excel.sheet.binary.macroenabled.12": { - source: "iana", - extensions: ["xlsb"] - }, - "application/vnd.ms-excel.sheet.macroenabled.12": { - source: "iana", - extensions: ["xlsm"] - }, - "application/vnd.ms-excel.template.macroenabled.12": { - source: "iana", - extensions: ["xltm"] - }, - "application/vnd.ms-fontobject": { - source: "iana", - compressible: true, - extensions: ["eot"] - }, - "application/vnd.ms-htmlhelp": { - source: "iana", - extensions: ["chm"] - }, - "application/vnd.ms-ims": { - source: "iana", - extensions: ["ims"] - }, - "application/vnd.ms-lrm": { - source: "iana", - extensions: ["lrm"] - }, - "application/vnd.ms-office.activex+xml": { - source: "iana", - compressible: true - }, - "application/vnd.ms-officetheme": { - source: "iana", - extensions: ["thmx"] - }, - "application/vnd.ms-opentype": { - source: "apache", - compressible: true - }, - "application/vnd.ms-outlook": { - compressible: false, - extensions: ["msg"] - }, - "application/vnd.ms-package.obfuscated-opentype": { - source: "apache" - }, - "application/vnd.ms-pki.seccat": { - source: "apache", - extensions: ["cat"] - }, - "application/vnd.ms-pki.stl": { - source: "apache", - extensions: ["stl"] - }, - "application/vnd.ms-playready.initiator+xml": { - source: "iana", - compressible: true - }, - "application/vnd.ms-powerpoint": { - source: "iana", - compressible: false, - extensions: ["ppt", "pps", "pot"] - }, - "application/vnd.ms-powerpoint.addin.macroenabled.12": { - source: "iana", - extensions: ["ppam"] - }, - "application/vnd.ms-powerpoint.presentation.macroenabled.12": { - source: "iana", - extensions: ["pptm"] - }, - "application/vnd.ms-powerpoint.slide.macroenabled.12": { - source: "iana", - extensions: ["sldm"] - }, - "application/vnd.ms-powerpoint.slideshow.macroenabled.12": { - source: "iana", - extensions: ["ppsm"] - }, - "application/vnd.ms-powerpoint.template.macroenabled.12": { - source: "iana", - extensions: ["potm"] - }, - "application/vnd.ms-printdevicecapabilities+xml": { - source: "iana", - compressible: true - }, - "application/vnd.ms-printing.printticket+xml": { - source: "apache", - compressible: true - }, - "application/vnd.ms-printschematicket+xml": { - source: "iana", - compressible: true - }, - "application/vnd.ms-project": { - source: "iana", - extensions: ["mpp", "mpt"] - }, - "application/vnd.ms-tnef": { - source: "iana" - }, - "application/vnd.ms-visio.viewer": { - extensions: ["vdx"] - }, - "application/vnd.ms-windows.devicepairing": { - source: "iana" - }, - "application/vnd.ms-windows.nwprinting.oob": { - source: "iana" - }, - "application/vnd.ms-windows.printerpairing": { - source: "iana" - }, - "application/vnd.ms-windows.wsd.oob": { - source: "iana" - }, - "application/vnd.ms-wmdrm.lic-chlg-req": { - source: "iana" - }, - "application/vnd.ms-wmdrm.lic-resp": { - source: "iana" - }, - "application/vnd.ms-wmdrm.meter-chlg-req": { - source: "iana" - }, - "application/vnd.ms-wmdrm.meter-resp": { - source: "iana" - }, - "application/vnd.ms-word.document.macroenabled.12": { - source: "iana", - extensions: ["docm"] - }, - "application/vnd.ms-word.template.macroenabled.12": { - source: "iana", - extensions: ["dotm"] - }, - "application/vnd.ms-works": { - source: "iana", - extensions: ["wps", "wks", "wcm", "wdb"] - }, - "application/vnd.ms-wpl": { - source: "iana", - extensions: ["wpl"] - }, - "application/vnd.ms-xpsdocument": { - source: "iana", - compressible: false, - extensions: ["xps"] - }, - "application/vnd.msa-disk-image": { - source: "iana" - }, - "application/vnd.mseq": { - source: "iana", - extensions: ["mseq"] - }, - "application/vnd.msgpack": { - source: "iana" - }, - "application/vnd.msign": { - source: "iana" - }, - "application/vnd.multiad.creator": { - source: "iana" - }, - "application/vnd.multiad.creator.cif": { - source: "iana" - }, - "application/vnd.music-niff": { - source: "iana" - }, - "application/vnd.musician": { - source: "iana", - extensions: ["mus"] - }, - "application/vnd.muvee.style": { - source: "iana", - extensions: ["msty"] - }, - "application/vnd.mynfc": { - source: "iana", - extensions: ["taglet"] - }, - "application/vnd.nacamar.ybrid+json": { - source: "iana", - compressible: true - }, - "application/vnd.nato.bindingdataobject+cbor": { - source: "iana" - }, - "application/vnd.nato.bindingdataobject+json": { - source: "iana", - compressible: true - }, - "application/vnd.nato.bindingdataobject+xml": { - source: "iana", - compressible: true, - extensions: ["bdo"] - }, - "application/vnd.nato.openxmlformats-package.iepd+zip": { - source: "iana", - compressible: false - }, - "application/vnd.ncd.control": { - source: "iana" - }, - "application/vnd.ncd.reference": { - source: "iana" - }, - "application/vnd.nearst.inv+json": { - source: "iana", - compressible: true - }, - "application/vnd.nebumind.line": { - source: "iana" - }, - "application/vnd.nervana": { - source: "iana" - }, - "application/vnd.netfpx": { - source: "iana" - }, - "application/vnd.neurolanguage.nlu": { - source: "iana", - extensions: ["nlu"] - }, - "application/vnd.nimn": { - source: "iana" - }, - "application/vnd.nintendo.nitro.rom": { - source: "iana" - }, - "application/vnd.nintendo.snes.rom": { - source: "iana" - }, - "application/vnd.nitf": { - source: "iana", - extensions: ["ntf", "nitf"] - }, - "application/vnd.noblenet-directory": { - source: "iana", - extensions: ["nnd"] - }, - "application/vnd.noblenet-sealer": { - source: "iana", - extensions: ["nns"] - }, - "application/vnd.noblenet-web": { - source: "iana", - extensions: ["nnw"] - }, - "application/vnd.nokia.catalogs": { - source: "iana" - }, - "application/vnd.nokia.conml+wbxml": { - source: "iana" - }, - "application/vnd.nokia.conml+xml": { - source: "iana", - compressible: true - }, - "application/vnd.nokia.iptv.config+xml": { - source: "iana", - compressible: true - }, - "application/vnd.nokia.isds-radio-presets": { - source: "iana" - }, - "application/vnd.nokia.landmark+wbxml": { - source: "iana" - }, - "application/vnd.nokia.landmark+xml": { - source: "iana", - compressible: true - }, - "application/vnd.nokia.landmarkcollection+xml": { - source: "iana", - compressible: true - }, - "application/vnd.nokia.n-gage.ac+xml": { - source: "iana", - compressible: true, - extensions: ["ac"] - }, - "application/vnd.nokia.n-gage.data": { - source: "iana", - extensions: ["ngdat"] - }, - "application/vnd.nokia.n-gage.symbian.install": { - source: "apache", - extensions: ["n-gage"] - }, - "application/vnd.nokia.ncd": { - source: "iana" - }, - "application/vnd.nokia.pcd+wbxml": { - source: "iana" - }, - "application/vnd.nokia.pcd+xml": { - source: "iana", - compressible: true - }, - "application/vnd.nokia.radio-preset": { - source: "iana", - extensions: ["rpst"] - }, - "application/vnd.nokia.radio-presets": { - source: "iana", - extensions: ["rpss"] - }, - "application/vnd.novadigm.edm": { - source: "iana", - extensions: ["edm"] - }, - "application/vnd.novadigm.edx": { - source: "iana", - extensions: ["edx"] - }, - "application/vnd.novadigm.ext": { - source: "iana", - extensions: ["ext"] - }, - "application/vnd.ntt-local.content-share": { - source: "iana" - }, - "application/vnd.ntt-local.file-transfer": { - source: "iana" - }, - "application/vnd.ntt-local.ogw_remote-access": { - source: "iana" - }, - "application/vnd.ntt-local.sip-ta_remote": { - source: "iana" - }, - "application/vnd.ntt-local.sip-ta_tcp_stream": { - source: "iana" - }, - "application/vnd.oai.workflows": { - source: "iana" - }, - "application/vnd.oai.workflows+json": { - source: "iana", - compressible: true - }, - "application/vnd.oai.workflows+yaml": { - source: "iana" - }, - "application/vnd.oasis.opendocument.base": { - source: "iana" - }, - "application/vnd.oasis.opendocument.chart": { - source: "iana", - extensions: ["odc"] - }, - "application/vnd.oasis.opendocument.chart-template": { - source: "iana", - extensions: ["otc"] - }, - "application/vnd.oasis.opendocument.database": { - source: "apache", - extensions: ["odb"] - }, - "application/vnd.oasis.opendocument.formula": { - source: "iana", - extensions: ["odf"] - }, - "application/vnd.oasis.opendocument.formula-template": { - source: "iana", - extensions: ["odft"] - }, - "application/vnd.oasis.opendocument.graphics": { - source: "iana", - compressible: false, - extensions: ["odg"] - }, - "application/vnd.oasis.opendocument.graphics-template": { - source: "iana", - extensions: ["otg"] - }, - "application/vnd.oasis.opendocument.image": { - source: "iana", - extensions: ["odi"] - }, - "application/vnd.oasis.opendocument.image-template": { - source: "iana", - extensions: ["oti"] - }, - "application/vnd.oasis.opendocument.presentation": { - source: "iana", - compressible: false, - extensions: ["odp"] - }, - "application/vnd.oasis.opendocument.presentation-template": { - source: "iana", - extensions: ["otp"] - }, - "application/vnd.oasis.opendocument.spreadsheet": { - source: "iana", - compressible: false, - extensions: ["ods"] - }, - "application/vnd.oasis.opendocument.spreadsheet-template": { - source: "iana", - extensions: ["ots"] - }, - "application/vnd.oasis.opendocument.text": { - source: "iana", - compressible: false, - extensions: ["odt"] - }, - "application/vnd.oasis.opendocument.text-master": { - source: "iana", - extensions: ["odm"] - }, - "application/vnd.oasis.opendocument.text-master-template": { - source: "iana" - }, - "application/vnd.oasis.opendocument.text-template": { - source: "iana", - extensions: ["ott"] - }, - "application/vnd.oasis.opendocument.text-web": { - source: "iana", - extensions: ["oth"] - }, - "application/vnd.obn": { - source: "iana" - }, - "application/vnd.ocf+cbor": { - source: "iana" - }, - "application/vnd.oci.image.manifest.v1+json": { - source: "iana", - compressible: true - }, - "application/vnd.oftn.l10n+json": { - source: "iana", - compressible: true - }, - "application/vnd.oipf.contentaccessdownload+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oipf.contentaccessstreaming+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oipf.cspg-hexbinary": { - source: "iana" - }, - "application/vnd.oipf.dae.svg+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oipf.dae.xhtml+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oipf.mippvcontrolmessage+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oipf.pae.gem": { - source: "iana" - }, - "application/vnd.oipf.spdiscovery+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oipf.spdlist+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oipf.ueprofile+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oipf.userprofile+xml": { - source: "iana", - compressible: true - }, - "application/vnd.olpc-sugar": { - source: "iana", - extensions: ["xo"] - }, - "application/vnd.oma-scws-config": { - source: "iana" - }, - "application/vnd.oma-scws-http-request": { - source: "iana" - }, - "application/vnd.oma-scws-http-response": { - source: "iana" - }, - "application/vnd.oma.bcast.associated-procedure-parameter+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oma.bcast.drm-trigger+xml": { - source: "apache", - compressible: true - }, - "application/vnd.oma.bcast.imd+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oma.bcast.ltkm": { - source: "iana" - }, - "application/vnd.oma.bcast.notification+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oma.bcast.provisioningtrigger": { - source: "iana" - }, - "application/vnd.oma.bcast.sgboot": { - source: "iana" - }, - "application/vnd.oma.bcast.sgdd+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oma.bcast.sgdu": { - source: "iana" - }, - "application/vnd.oma.bcast.simple-symbol-container": { - source: "iana" - }, - "application/vnd.oma.bcast.smartcard-trigger+xml": { - source: "apache", - compressible: true - }, - "application/vnd.oma.bcast.sprov+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oma.bcast.stkm": { - source: "iana" - }, - "application/vnd.oma.cab-address-book+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oma.cab-feature-handler+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oma.cab-pcc+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oma.cab-subs-invite+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oma.cab-user-prefs+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oma.dcd": { - source: "iana" - }, - "application/vnd.oma.dcdc": { - source: "iana" - }, - "application/vnd.oma.dd2+xml": { - source: "iana", - compressible: true, - extensions: ["dd2"] - }, - "application/vnd.oma.drm.risd+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oma.group-usage-list+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oma.lwm2m+cbor": { - source: "iana" - }, - "application/vnd.oma.lwm2m+json": { - source: "iana", - compressible: true - }, - "application/vnd.oma.lwm2m+tlv": { - source: "iana" - }, - "application/vnd.oma.pal+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oma.poc.detailed-progress-report+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oma.poc.final-report+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oma.poc.groups+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oma.poc.invocation-descriptor+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oma.poc.optimized-progress-report+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oma.push": { - source: "iana" - }, - "application/vnd.oma.scidm.messages+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oma.xcap-directory+xml": { - source: "iana", - compressible: true - }, - "application/vnd.omads-email+xml": { - source: "iana", - charset: "UTF-8", - compressible: true - }, - "application/vnd.omads-file+xml": { - source: "iana", - charset: "UTF-8", - compressible: true - }, - "application/vnd.omads-folder+xml": { - source: "iana", - charset: "UTF-8", - compressible: true - }, - "application/vnd.omaloc-supl-init": { - source: "iana" - }, - "application/vnd.onepager": { - source: "iana" - }, - "application/vnd.onepagertamp": { - source: "iana" - }, - "application/vnd.onepagertamx": { - source: "iana" - }, - "application/vnd.onepagertat": { - source: "iana" - }, - "application/vnd.onepagertatp": { - source: "iana" - }, - "application/vnd.onepagertatx": { - source: "iana" - }, - "application/vnd.onvif.metadata": { - source: "iana" - }, - "application/vnd.openblox.game+xml": { - source: "iana", - compressible: true, - extensions: ["obgx"] - }, - "application/vnd.openblox.game-binary": { - source: "iana" - }, - "application/vnd.openeye.oeb": { - source: "iana" - }, - "application/vnd.openofficeorg.extension": { - source: "apache", - extensions: ["oxt"] - }, - "application/vnd.openstreetmap.data+xml": { - source: "iana", - compressible: true, - extensions: ["osm"] - }, - "application/vnd.opentimestamps.ots": { - source: "iana" - }, - "application/vnd.openvpi.dspx+json": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.custom-properties+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.customxmlproperties+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.drawing+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.drawingml.chart+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.drawingml.diagramcolors+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.drawingml.diagramdata+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.drawingml.diagramlayout+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.drawingml.diagramstyle+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.extended-properties+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.presentationml.commentauthors+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.presentationml.comments+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.presentationml.handoutmaster+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.presentationml.notesmaster+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.presentationml.notesslide+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.presentationml.presentation": { - source: "iana", - compressible: false, - extensions: ["pptx"] - }, - "application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.presentationml.presprops+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.presentationml.slide": { - source: "iana", - extensions: ["sldx"] - }, - "application/vnd.openxmlformats-officedocument.presentationml.slide+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.presentationml.slidelayout+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.presentationml.slidemaster+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.presentationml.slideshow": { - source: "iana", - extensions: ["ppsx"] - }, - "application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.presentationml.slideupdateinfo+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.presentationml.tablestyles+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.presentationml.tags+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.presentationml.template": { - source: "iana", - extensions: ["potx"] - }, - "application/vnd.openxmlformats-officedocument.presentationml.template.main+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.presentationml.viewprops+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.calcchain+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.externallink+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcachedefinition+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcacherecords+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.pivottable+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.querytable+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionheaders+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionlog+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedstrings+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": { - source: "iana", - compressible: false, - extensions: ["xlsx"] - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.sheetmetadata+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.tablesinglecells+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.template": { - source: "iana", - extensions: ["xltx"] - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.usernames+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.volatiledependencies+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.theme+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.themeoverride+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.vmldrawing": { - source: "iana" - }, - "application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.wordprocessingml.document": { - source: "iana", - compressible: false, - extensions: ["docx"] - }, - "application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.wordprocessingml.fonttable+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.wordprocessingml.template": { - source: "iana", - extensions: ["dotx"] - }, - "application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.wordprocessingml.websettings+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-package.core-properties+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-package.relationships+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oracle.resource+json": { - source: "iana", - compressible: true - }, - "application/vnd.orange.indata": { - source: "iana" - }, - "application/vnd.osa.netdeploy": { - source: "iana" - }, - "application/vnd.osgeo.mapguide.package": { - source: "iana", - extensions: ["mgp"] - }, - "application/vnd.osgi.bundle": { - source: "iana" - }, - "application/vnd.osgi.dp": { - source: "iana", - extensions: ["dp"] - }, - "application/vnd.osgi.subsystem": { - source: "iana", - extensions: ["esa"] - }, - "application/vnd.otps.ct-kip+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oxli.countgraph": { - source: "iana" - }, - "application/vnd.pagerduty+json": { - source: "iana", - compressible: true - }, - "application/vnd.palm": { - source: "iana", - extensions: ["pdb", "pqa", "oprc"] - }, - "application/vnd.panoply": { - source: "iana" - }, - "application/vnd.paos.xml": { - source: "iana" - }, - "application/vnd.patentdive": { - source: "iana" - }, - "application/vnd.patientecommsdoc": { - source: "iana" - }, - "application/vnd.pawaafile": { - source: "iana", - extensions: ["paw"] - }, - "application/vnd.pcos": { - source: "iana" - }, - "application/vnd.pg.format": { - source: "iana", - extensions: ["str"] - }, - "application/vnd.pg.osasli": { - source: "iana", - extensions: ["ei6"] - }, - "application/vnd.piaccess.application-licence": { - source: "iana" - }, - "application/vnd.picsel": { - source: "iana", - extensions: ["efif"] - }, - "application/vnd.pmi.widget": { - source: "iana", - extensions: ["wg"] - }, - "application/vnd.poc.group-advertisement+xml": { - source: "iana", - compressible: true - }, - "application/vnd.pocketlearn": { - source: "iana", - extensions: ["plf"] - }, - "application/vnd.powerbuilder6": { - source: "iana", - extensions: ["pbd"] - }, - "application/vnd.powerbuilder6-s": { - source: "iana" - }, - "application/vnd.powerbuilder7": { - source: "iana" - }, - "application/vnd.powerbuilder7-s": { - source: "iana" - }, - "application/vnd.powerbuilder75": { - source: "iana" - }, - "application/vnd.powerbuilder75-s": { - source: "iana" - }, - "application/vnd.preminet": { - source: "iana" - }, - "application/vnd.previewsystems.box": { - source: "iana", - extensions: ["box"] - }, - "application/vnd.procrate.brushset": { - extensions: ["brushset"] - }, - "application/vnd.procreate.brush": { - extensions: ["brush"] - }, - "application/vnd.procreate.dream": { - extensions: ["drm"] - }, - "application/vnd.proteus.magazine": { - source: "iana", - extensions: ["mgz"] - }, - "application/vnd.psfs": { - source: "iana" - }, - "application/vnd.pt.mundusmundi": { - source: "iana" - }, - "application/vnd.publishare-delta-tree": { - source: "iana", - extensions: ["qps"] - }, - "application/vnd.pvi.ptid1": { - source: "iana", - extensions: ["ptid"] - }, - "application/vnd.pwg-multiplexed": { - source: "iana" - }, - "application/vnd.pwg-xhtml-print+xml": { - source: "iana", - compressible: true, - extensions: ["xhtm"] - }, - "application/vnd.qualcomm.brew-app-res": { - source: "iana" - }, - "application/vnd.quarantainenet": { - source: "iana" - }, - "application/vnd.quark.quarkxpress": { - source: "iana", - extensions: ["qxd", "qxt", "qwd", "qwt", "qxl", "qxb"] - }, - "application/vnd.quobject-quoxdocument": { - source: "iana" - }, - "application/vnd.radisys.moml+xml": { - source: "iana", - compressible: true - }, - "application/vnd.radisys.msml+xml": { - source: "iana", - compressible: true - }, - "application/vnd.radisys.msml-audit+xml": { - source: "iana", - compressible: true - }, - "application/vnd.radisys.msml-audit-conf+xml": { - source: "iana", - compressible: true - }, - "application/vnd.radisys.msml-audit-conn+xml": { - source: "iana", - compressible: true - }, - "application/vnd.radisys.msml-audit-dialog+xml": { - source: "iana", - compressible: true - }, - "application/vnd.radisys.msml-audit-stream+xml": { - source: "iana", - compressible: true - }, - "application/vnd.radisys.msml-conf+xml": { - source: "iana", - compressible: true - }, - "application/vnd.radisys.msml-dialog+xml": { - source: "iana", - compressible: true - }, - "application/vnd.radisys.msml-dialog-base+xml": { - source: "iana", - compressible: true - }, - "application/vnd.radisys.msml-dialog-fax-detect+xml": { - source: "iana", - compressible: true - }, - "application/vnd.radisys.msml-dialog-fax-sendrecv+xml": { - source: "iana", - compressible: true - }, - "application/vnd.radisys.msml-dialog-group+xml": { - source: "iana", - compressible: true - }, - "application/vnd.radisys.msml-dialog-speech+xml": { - source: "iana", - compressible: true - }, - "application/vnd.radisys.msml-dialog-transform+xml": { - source: "iana", - compressible: true - }, - "application/vnd.rainstor.data": { - source: "iana" - }, - "application/vnd.rapid": { - source: "iana" - }, - "application/vnd.rar": { - source: "iana", - extensions: ["rar"] - }, - "application/vnd.realvnc.bed": { - source: "iana", - extensions: ["bed"] - }, - "application/vnd.recordare.musicxml": { - source: "iana", - extensions: ["mxl"] - }, - "application/vnd.recordare.musicxml+xml": { - source: "iana", - compressible: true, - extensions: ["musicxml"] - }, - "application/vnd.relpipe": { - source: "iana" - }, - "application/vnd.renlearn.rlprint": { - source: "iana" - }, - "application/vnd.resilient.logic": { - source: "iana" - }, - "application/vnd.restful+json": { - source: "iana", - compressible: true - }, - "application/vnd.rig.cryptonote": { - source: "iana", - extensions: ["cryptonote"] - }, - "application/vnd.rim.cod": { - source: "apache", - extensions: ["cod"] - }, - "application/vnd.rn-realmedia": { - source: "apache", - extensions: ["rm"] - }, - "application/vnd.rn-realmedia-vbr": { - source: "apache", - extensions: ["rmvb"] - }, - "application/vnd.route66.link66+xml": { - source: "iana", - compressible: true, - extensions: ["link66"] - }, - "application/vnd.rs-274x": { - source: "iana" - }, - "application/vnd.ruckus.download": { - source: "iana" - }, - "application/vnd.s3sms": { - source: "iana" - }, - "application/vnd.sailingtracker.track": { - source: "iana", - extensions: ["st"] - }, - "application/vnd.sar": { - source: "iana" - }, - "application/vnd.sbm.cid": { - source: "iana" - }, - "application/vnd.sbm.mid2": { - source: "iana" - }, - "application/vnd.scribus": { - source: "iana" - }, - "application/vnd.sealed.3df": { - source: "iana" - }, - "application/vnd.sealed.csf": { - source: "iana" - }, - "application/vnd.sealed.doc": { - source: "iana" - }, - "application/vnd.sealed.eml": { - source: "iana" - }, - "application/vnd.sealed.mht": { - source: "iana" - }, - "application/vnd.sealed.net": { - source: "iana" - }, - "application/vnd.sealed.ppt": { - source: "iana" - }, - "application/vnd.sealed.tiff": { - source: "iana" - }, - "application/vnd.sealed.xls": { - source: "iana" - }, - "application/vnd.sealedmedia.softseal.html": { - source: "iana" - }, - "application/vnd.sealedmedia.softseal.pdf": { - source: "iana" - }, - "application/vnd.seemail": { - source: "iana", - extensions: ["see"] - }, - "application/vnd.seis+json": { - source: "iana", - compressible: true - }, - "application/vnd.sema": { - source: "iana", - extensions: ["sema"] - }, - "application/vnd.semd": { - source: "iana", - extensions: ["semd"] - }, - "application/vnd.semf": { - source: "iana", - extensions: ["semf"] - }, - "application/vnd.shade-save-file": { - source: "iana" - }, - "application/vnd.shana.informed.formdata": { - source: "iana", - extensions: ["ifm"] - }, - "application/vnd.shana.informed.formtemplate": { - source: "iana", - extensions: ["itp"] - }, - "application/vnd.shana.informed.interchange": { - source: "iana", - extensions: ["iif"] - }, - "application/vnd.shana.informed.package": { - source: "iana", - extensions: ["ipk"] - }, - "application/vnd.shootproof+json": { - source: "iana", - compressible: true - }, - "application/vnd.shopkick+json": { - source: "iana", - compressible: true - }, - "application/vnd.shp": { - source: "iana" - }, - "application/vnd.shx": { - source: "iana" - }, - "application/vnd.sigrok.session": { - source: "iana" - }, - "application/vnd.simtech-mindmapper": { - source: "iana", - extensions: ["twd", "twds"] - }, - "application/vnd.siren+json": { - source: "iana", - compressible: true - }, - "application/vnd.sketchometry": { - source: "iana" - }, - "application/vnd.smaf": { - source: "iana", - extensions: ["mmf"] - }, - "application/vnd.smart.notebook": { - source: "iana" - }, - "application/vnd.smart.teacher": { - source: "iana", - extensions: ["teacher"] - }, - "application/vnd.smintio.portals.archive": { - source: "iana" - }, - "application/vnd.snesdev-page-table": { - source: "iana" - }, - "application/vnd.software602.filler.form+xml": { - source: "iana", - compressible: true, - extensions: ["fo"] - }, - "application/vnd.software602.filler.form-xml-zip": { - source: "iana" - }, - "application/vnd.solent.sdkm+xml": { - source: "iana", - compressible: true, - extensions: ["sdkm", "sdkd"] - }, - "application/vnd.spotfire.dxp": { - source: "iana", - extensions: ["dxp"] - }, - "application/vnd.spotfire.sfs": { - source: "iana", - extensions: ["sfs"] - }, - "application/vnd.sqlite3": { - source: "iana" - }, - "application/vnd.sss-cod": { - source: "iana" - }, - "application/vnd.sss-dtf": { - source: "iana" - }, - "application/vnd.sss-ntf": { - source: "iana" - }, - "application/vnd.stardivision.calc": { - source: "apache", - extensions: ["sdc"] - }, - "application/vnd.stardivision.draw": { - source: "apache", - extensions: ["sda"] - }, - "application/vnd.stardivision.impress": { - source: "apache", - extensions: ["sdd"] - }, - "application/vnd.stardivision.math": { - source: "apache", - extensions: ["smf"] - }, - "application/vnd.stardivision.writer": { - source: "apache", - extensions: ["sdw", "vor"] - }, - "application/vnd.stardivision.writer-global": { - source: "apache", - extensions: ["sgl"] - }, - "application/vnd.stepmania.package": { - source: "iana", - extensions: ["smzip"] - }, - "application/vnd.stepmania.stepchart": { - source: "iana", - extensions: ["sm"] - }, - "application/vnd.street-stream": { - source: "iana" - }, - "application/vnd.sun.wadl+xml": { - source: "iana", - compressible: true, - extensions: ["wadl"] - }, - "application/vnd.sun.xml.calc": { - source: "apache", - extensions: ["sxc"] - }, - "application/vnd.sun.xml.calc.template": { - source: "apache", - extensions: ["stc"] - }, - "application/vnd.sun.xml.draw": { - source: "apache", - extensions: ["sxd"] - }, - "application/vnd.sun.xml.draw.template": { - source: "apache", - extensions: ["std"] - }, - "application/vnd.sun.xml.impress": { - source: "apache", - extensions: ["sxi"] - }, - "application/vnd.sun.xml.impress.template": { - source: "apache", - extensions: ["sti"] - }, - "application/vnd.sun.xml.math": { - source: "apache", - extensions: ["sxm"] - }, - "application/vnd.sun.xml.writer": { - source: "apache", - extensions: ["sxw"] - }, - "application/vnd.sun.xml.writer.global": { - source: "apache", - extensions: ["sxg"] - }, - "application/vnd.sun.xml.writer.template": { - source: "apache", - extensions: ["stw"] - }, - "application/vnd.sus-calendar": { - source: "iana", - extensions: ["sus", "susp"] - }, - "application/vnd.svd": { - source: "iana", - extensions: ["svd"] - }, - "application/vnd.swiftview-ics": { - source: "iana" - }, - "application/vnd.sybyl.mol2": { - source: "iana" - }, - "application/vnd.sycle+xml": { - source: "iana", - compressible: true - }, - "application/vnd.syft+json": { - source: "iana", - compressible: true - }, - "application/vnd.symbian.install": { - source: "apache", - extensions: ["sis", "sisx"] - }, - "application/vnd.syncml+xml": { - source: "iana", - charset: "UTF-8", - compressible: true, - extensions: ["xsm"] - }, - "application/vnd.syncml.dm+wbxml": { - source: "iana", - charset: "UTF-8", - extensions: ["bdm"] - }, - "application/vnd.syncml.dm+xml": { - source: "iana", - charset: "UTF-8", - compressible: true, - extensions: ["xdm"] - }, - "application/vnd.syncml.dm.notification": { - source: "iana" - }, - "application/vnd.syncml.dmddf+wbxml": { - source: "iana" - }, - "application/vnd.syncml.dmddf+xml": { - source: "iana", - charset: "UTF-8", - compressible: true, - extensions: ["ddf"] - }, - "application/vnd.syncml.dmtnds+wbxml": { - source: "iana" - }, - "application/vnd.syncml.dmtnds+xml": { - source: "iana", - charset: "UTF-8", - compressible: true - }, - "application/vnd.syncml.ds.notification": { - source: "iana" - }, - "application/vnd.tableschema+json": { - source: "iana", - compressible: true - }, - "application/vnd.tao.intent-module-archive": { - source: "iana", - extensions: ["tao"] - }, - "application/vnd.tcpdump.pcap": { - source: "iana", - extensions: ["pcap", "cap", "dmp"] - }, - "application/vnd.think-cell.ppttc+json": { - source: "iana", - compressible: true - }, - "application/vnd.tmd.mediaflex.api+xml": { - source: "iana", - compressible: true - }, - "application/vnd.tml": { - source: "iana" - }, - "application/vnd.tmobile-livetv": { - source: "iana", - extensions: ["tmo"] - }, - "application/vnd.tri.onesource": { - source: "iana" - }, - "application/vnd.trid.tpt": { - source: "iana", - extensions: ["tpt"] - }, - "application/vnd.triscape.mxs": { - source: "iana", - extensions: ["mxs"] - }, - "application/vnd.trueapp": { - source: "iana", - extensions: ["tra"] - }, - "application/vnd.truedoc": { - source: "iana" - }, - "application/vnd.ubisoft.webplayer": { - source: "iana" - }, - "application/vnd.ufdl": { - source: "iana", - extensions: ["ufd", "ufdl"] - }, - "application/vnd.uic.osdm+json": { - source: "iana", - compressible: true - }, - "application/vnd.uiq.theme": { - source: "iana", - extensions: ["utz"] - }, - "application/vnd.umajin": { - source: "iana", - extensions: ["umj"] - }, - "application/vnd.unity": { - source: "iana", - extensions: ["unityweb"] - }, - "application/vnd.uoml+xml": { - source: "iana", - compressible: true, - extensions: ["uoml", "uo"] - }, - "application/vnd.uplanet.alert": { - source: "iana" - }, - "application/vnd.uplanet.alert-wbxml": { - source: "iana" - }, - "application/vnd.uplanet.bearer-choice": { - source: "iana" - }, - "application/vnd.uplanet.bearer-choice-wbxml": { - source: "iana" - }, - "application/vnd.uplanet.cacheop": { - source: "iana" - }, - "application/vnd.uplanet.cacheop-wbxml": { - source: "iana" - }, - "application/vnd.uplanet.channel": { - source: "iana" - }, - "application/vnd.uplanet.channel-wbxml": { - source: "iana" - }, - "application/vnd.uplanet.list": { - source: "iana" - }, - "application/vnd.uplanet.list-wbxml": { - source: "iana" - }, - "application/vnd.uplanet.listcmd": { - source: "iana" - }, - "application/vnd.uplanet.listcmd-wbxml": { - source: "iana" - }, - "application/vnd.uplanet.signal": { - source: "iana" - }, - "application/vnd.uri-map": { - source: "iana" - }, - "application/vnd.valve.source.material": { - source: "iana" - }, - "application/vnd.vcx": { - source: "iana", - extensions: ["vcx"] - }, - "application/vnd.vd-study": { - source: "iana" - }, - "application/vnd.vectorworks": { - source: "iana" - }, - "application/vnd.vel+json": { - source: "iana", - compressible: true - }, - "application/vnd.veraison.tsm-report+cbor": { - source: "iana" - }, - "application/vnd.veraison.tsm-report+json": { - source: "iana", - compressible: true - }, - "application/vnd.verimatrix.vcas": { - source: "iana" - }, - "application/vnd.veritone.aion+json": { - source: "iana", - compressible: true - }, - "application/vnd.veryant.thin": { - source: "iana" - }, - "application/vnd.ves.encrypted": { - source: "iana" - }, - "application/vnd.vidsoft.vidconference": { - source: "iana" - }, - "application/vnd.visio": { - source: "iana", - extensions: ["vsd", "vst", "vss", "vsw", "vsdx", "vtx"] - }, - "application/vnd.visionary": { - source: "iana", - extensions: ["vis"] - }, - "application/vnd.vividence.scriptfile": { - source: "iana" - }, - "application/vnd.vocalshaper.vsp4": { - source: "iana" - }, - "application/vnd.vsf": { - source: "iana", - extensions: ["vsf"] - }, - "application/vnd.wap.sic": { - source: "iana" - }, - "application/vnd.wap.slc": { - source: "iana" - }, - "application/vnd.wap.wbxml": { - source: "iana", - charset: "UTF-8", - extensions: ["wbxml"] - }, - "application/vnd.wap.wmlc": { - source: "iana", - extensions: ["wmlc"] - }, - "application/vnd.wap.wmlscriptc": { - source: "iana", - extensions: ["wmlsc"] - }, - "application/vnd.wasmflow.wafl": { - source: "iana" - }, - "application/vnd.webturbo": { - source: "iana", - extensions: ["wtb"] - }, - "application/vnd.wfa.dpp": { - source: "iana" - }, - "application/vnd.wfa.p2p": { - source: "iana" - }, - "application/vnd.wfa.wsc": { - source: "iana" - }, - "application/vnd.windows.devicepairing": { - source: "iana" - }, - "application/vnd.wmc": { - source: "iana" - }, - "application/vnd.wmf.bootstrap": { - source: "iana" - }, - "application/vnd.wolfram.mathematica": { - source: "iana" - }, - "application/vnd.wolfram.mathematica.package": { - source: "iana" - }, - "application/vnd.wolfram.player": { - source: "iana", - extensions: ["nbp"] - }, - "application/vnd.wordlift": { - source: "iana" - }, - "application/vnd.wordperfect": { - source: "iana", - extensions: ["wpd"] - }, - "application/vnd.wqd": { - source: "iana", - extensions: ["wqd"] - }, - "application/vnd.wrq-hp3000-labelled": { - source: "iana" - }, - "application/vnd.wt.stf": { - source: "iana", - extensions: ["stf"] - }, - "application/vnd.wv.csp+wbxml": { - source: "iana" - }, - "application/vnd.wv.csp+xml": { - source: "iana", - compressible: true - }, - "application/vnd.wv.ssp+xml": { - source: "iana", - compressible: true - }, - "application/vnd.xacml+json": { - source: "iana", - compressible: true - }, - "application/vnd.xara": { - source: "iana", - extensions: ["xar"] - }, - "application/vnd.xarin.cpj": { - source: "iana" - }, - "application/vnd.xecrets-encrypted": { - source: "iana" - }, - "application/vnd.xfdl": { - source: "iana", - extensions: ["xfdl"] - }, - "application/vnd.xfdl.webform": { - source: "iana" - }, - "application/vnd.xmi+xml": { - source: "iana", - compressible: true - }, - "application/vnd.xmpie.cpkg": { - source: "iana" - }, - "application/vnd.xmpie.dpkg": { - source: "iana" - }, - "application/vnd.xmpie.plan": { - source: "iana" - }, - "application/vnd.xmpie.ppkg": { - source: "iana" - }, - "application/vnd.xmpie.xlim": { - source: "iana" - }, - "application/vnd.yamaha.hv-dic": { - source: "iana", - extensions: ["hvd"] - }, - "application/vnd.yamaha.hv-script": { - source: "iana", - extensions: ["hvs"] - }, - "application/vnd.yamaha.hv-voice": { - source: "iana", - extensions: ["hvp"] - }, - "application/vnd.yamaha.openscoreformat": { - source: "iana", - extensions: ["osf"] - }, - "application/vnd.yamaha.openscoreformat.osfpvg+xml": { - source: "iana", - compressible: true, - extensions: ["osfpvg"] - }, - "application/vnd.yamaha.remote-setup": { - source: "iana" - }, - "application/vnd.yamaha.smaf-audio": { - source: "iana", - extensions: ["saf"] - }, - "application/vnd.yamaha.smaf-phrase": { - source: "iana", - extensions: ["spf"] - }, - "application/vnd.yamaha.through-ngn": { - source: "iana" - }, - "application/vnd.yamaha.tunnel-udpencap": { - source: "iana" - }, - "application/vnd.yaoweme": { - source: "iana" - }, - "application/vnd.yellowriver-custom-menu": { - source: "iana", - extensions: ["cmp"] - }, - "application/vnd.zul": { - source: "iana", - extensions: ["zir", "zirz"] - }, - "application/vnd.zzazz.deck+xml": { - source: "iana", - compressible: true, - extensions: ["zaz"] - }, - "application/voicexml+xml": { - source: "iana", - compressible: true, - extensions: ["vxml"] - }, - "application/voucher-cms+json": { - source: "iana", - compressible: true - }, - "application/voucher-jws+json": { - source: "iana", - compressible: true - }, - "application/vp": { - source: "iana" - }, - "application/vp+cose": { - source: "iana" - }, - "application/vp+jwt": { - source: "iana" - }, - "application/vq-rtcpxr": { - source: "iana" - }, - "application/wasm": { - source: "iana", - compressible: true, - extensions: ["wasm"] - }, - "application/watcherinfo+xml": { - source: "iana", - compressible: true, - extensions: ["wif"] - }, - "application/webpush-options+json": { - source: "iana", - compressible: true - }, - "application/whoispp-query": { - source: "iana" - }, - "application/whoispp-response": { - source: "iana" - }, - "application/widget": { - source: "iana", - extensions: ["wgt"] - }, - "application/winhlp": { - source: "apache", - extensions: ["hlp"] - }, - "application/wita": { - source: "iana" - }, - "application/wordperfect5.1": { - source: "iana" - }, - "application/wsdl+xml": { - source: "iana", - compressible: true, - extensions: ["wsdl"] - }, - "application/wspolicy+xml": { - source: "iana", - compressible: true, - extensions: ["wspolicy"] - }, - "application/x-7z-compressed": { - source: "apache", - compressible: false, - extensions: ["7z"] - }, - "application/x-abiword": { - source: "apache", - extensions: ["abw"] - }, - "application/x-ace-compressed": { - source: "apache", - extensions: ["ace"] - }, - "application/x-amf": { - source: "apache" - }, - "application/x-apple-diskimage": { - source: "apache", - extensions: ["dmg"] - }, - "application/x-arj": { - compressible: false, - extensions: ["arj"] - }, - "application/x-authorware-bin": { - source: "apache", - extensions: ["aab", "x32", "u32", "vox"] - }, - "application/x-authorware-map": { - source: "apache", - extensions: ["aam"] - }, - "application/x-authorware-seg": { - source: "apache", - extensions: ["aas"] - }, - "application/x-bcpio": { - source: "apache", - extensions: ["bcpio"] - }, - "application/x-bdoc": { - compressible: false, - extensions: ["bdoc"] - }, - "application/x-bittorrent": { - source: "apache", - extensions: ["torrent"] - }, - "application/x-blender": { - extensions: ["blend"] - }, - "application/x-blorb": { - source: "apache", - extensions: ["blb", "blorb"] - }, - "application/x-bzip": { - source: "apache", - compressible: false, - extensions: ["bz"] - }, - "application/x-bzip2": { - source: "apache", - compressible: false, - extensions: ["bz2", "boz"] - }, - "application/x-cbr": { - source: "apache", - extensions: ["cbr", "cba", "cbt", "cbz", "cb7"] - }, - "application/x-cdlink": { - source: "apache", - extensions: ["vcd"] - }, - "application/x-cfs-compressed": { - source: "apache", - extensions: ["cfs"] - }, - "application/x-chat": { - source: "apache", - extensions: ["chat"] - }, - "application/x-chess-pgn": { - source: "apache", - extensions: ["pgn"] - }, - "application/x-chrome-extension": { - extensions: ["crx"] - }, - "application/x-cocoa": { - source: "nginx", - extensions: ["cco"] - }, - "application/x-compress": { - source: "apache" - }, - "application/x-compressed": { - extensions: ["rar"] - }, - "application/x-conference": { - source: "apache", - extensions: ["nsc"] - }, - "application/x-cpio": { - source: "apache", - extensions: ["cpio"] - }, - "application/x-csh": { - source: "apache", - extensions: ["csh"] - }, - "application/x-deb": { - compressible: false - }, - "application/x-debian-package": { - source: "apache", - extensions: ["deb", "udeb"] - }, - "application/x-dgc-compressed": { - source: "apache", - extensions: ["dgc"] - }, - "application/x-director": { - source: "apache", - extensions: ["dir", "dcr", "dxr", "cst", "cct", "cxt", "w3d", "fgd", "swa"] - }, - "application/x-doom": { - source: "apache", - extensions: ["wad"] - }, - "application/x-dtbncx+xml": { - source: "apache", - compressible: true, - extensions: ["ncx"] - }, - "application/x-dtbook+xml": { - source: "apache", - compressible: true, - extensions: ["dtb"] - }, - "application/x-dtbresource+xml": { - source: "apache", - compressible: true, - extensions: ["res"] - }, - "application/x-dvi": { - source: "apache", - compressible: false, - extensions: ["dvi"] - }, - "application/x-envoy": { - source: "apache", - extensions: ["evy"] - }, - "application/x-eva": { - source: "apache", - extensions: ["eva"] - }, - "application/x-font-bdf": { - source: "apache", - extensions: ["bdf"] - }, - "application/x-font-dos": { - source: "apache" - }, - "application/x-font-framemaker": { - source: "apache" - }, - "application/x-font-ghostscript": { - source: "apache", - extensions: ["gsf"] - }, - "application/x-font-libgrx": { - source: "apache" - }, - "application/x-font-linux-psf": { - source: "apache", - extensions: ["psf"] - }, - "application/x-font-pcf": { - source: "apache", - extensions: ["pcf"] - }, - "application/x-font-snf": { - source: "apache", - extensions: ["snf"] - }, - "application/x-font-speedo": { - source: "apache" - }, - "application/x-font-sunos-news": { - source: "apache" - }, - "application/x-font-type1": { - source: "apache", - extensions: ["pfa", "pfb", "pfm", "afm"] - }, - "application/x-font-vfont": { - source: "apache" - }, - "application/x-freearc": { - source: "apache", - extensions: ["arc"] - }, - "application/x-futuresplash": { - source: "apache", - extensions: ["spl"] - }, - "application/x-gca-compressed": { - source: "apache", - extensions: ["gca"] - }, - "application/x-glulx": { - source: "apache", - extensions: ["ulx"] - }, - "application/x-gnumeric": { - source: "apache", - extensions: ["gnumeric"] - }, - "application/x-gramps-xml": { - source: "apache", - extensions: ["gramps"] - }, - "application/x-gtar": { - source: "apache", - extensions: ["gtar"] - }, - "application/x-gzip": { - source: "apache" - }, - "application/x-hdf": { - source: "apache", - extensions: ["hdf"] - }, - "application/x-httpd-php": { - compressible: true, - extensions: ["php"] - }, - "application/x-install-instructions": { - source: "apache", - extensions: ["install"] - }, - "application/x-ipynb+json": { - compressible: true, - extensions: ["ipynb"] - }, - "application/x-iso9660-image": { - source: "apache", - extensions: ["iso"] - }, - "application/x-iwork-keynote-sffkey": { - extensions: ["key"] - }, - "application/x-iwork-numbers-sffnumbers": { - extensions: ["numbers"] - }, - "application/x-iwork-pages-sffpages": { - extensions: ["pages"] - }, - "application/x-java-archive-diff": { - source: "nginx", - extensions: ["jardiff"] - }, - "application/x-java-jnlp-file": { - source: "apache", - compressible: false, - extensions: ["jnlp"] - }, - "application/x-javascript": { - compressible: true - }, - "application/x-keepass2": { - extensions: ["kdbx"] - }, - "application/x-latex": { - source: "apache", - compressible: false, - extensions: ["latex"] - }, - "application/x-lua-bytecode": { - extensions: ["luac"] - }, - "application/x-lzh-compressed": { - source: "apache", - extensions: ["lzh", "lha"] - }, - "application/x-makeself": { - source: "nginx", - extensions: ["run"] - }, - "application/x-mie": { - source: "apache", - extensions: ["mie"] - }, - "application/x-mobipocket-ebook": { - source: "apache", - extensions: ["prc", "mobi"] - }, - "application/x-mpegurl": { - compressible: false - }, - "application/x-ms-application": { - source: "apache", - extensions: ["application"] - }, - "application/x-ms-shortcut": { - source: "apache", - extensions: ["lnk"] - }, - "application/x-ms-wmd": { - source: "apache", - extensions: ["wmd"] - }, - "application/x-ms-wmz": { - source: "apache", - extensions: ["wmz"] - }, - "application/x-ms-xbap": { - source: "apache", - extensions: ["xbap"] - }, - "application/x-msaccess": { - source: "apache", - extensions: ["mdb"] - }, - "application/x-msbinder": { - source: "apache", - extensions: ["obd"] - }, - "application/x-mscardfile": { - source: "apache", - extensions: ["crd"] - }, - "application/x-msclip": { - source: "apache", - extensions: ["clp"] - }, - "application/x-msdos-program": { - extensions: ["exe"] - }, - "application/x-msdownload": { - source: "apache", - extensions: ["exe", "dll", "com", "bat", "msi"] - }, - "application/x-msmediaview": { - source: "apache", - extensions: ["mvb", "m13", "m14"] - }, - "application/x-msmetafile": { - source: "apache", - extensions: ["wmf", "wmz", "emf", "emz"] - }, - "application/x-msmoney": { - source: "apache", - extensions: ["mny"] - }, - "application/x-mspublisher": { - source: "apache", - extensions: ["pub"] - }, - "application/x-msschedule": { - source: "apache", - extensions: ["scd"] - }, - "application/x-msterminal": { - source: "apache", - extensions: ["trm"] - }, - "application/x-mswrite": { - source: "apache", - extensions: ["wri"] - }, - "application/x-netcdf": { - source: "apache", - extensions: ["nc", "cdf"] - }, - "application/x-ns-proxy-autoconfig": { - compressible: true, - extensions: ["pac"] - }, - "application/x-nzb": { - source: "apache", - extensions: ["nzb"] - }, - "application/x-perl": { - source: "nginx", - extensions: ["pl", "pm"] - }, - "application/x-pilot": { - source: "nginx", - extensions: ["prc", "pdb"] - }, - "application/x-pkcs12": { - source: "apache", - compressible: false, - extensions: ["p12", "pfx"] - }, - "application/x-pkcs7-certificates": { - source: "apache", - extensions: ["p7b", "spc"] - }, - "application/x-pkcs7-certreqresp": { - source: "apache", - extensions: ["p7r"] - }, - "application/x-pki-message": { - source: "iana" - }, - "application/x-rar-compressed": { - source: "apache", - compressible: false, - extensions: ["rar"] - }, - "application/x-redhat-package-manager": { - source: "nginx", - extensions: ["rpm"] - }, - "application/x-research-info-systems": { - source: "apache", - extensions: ["ris"] - }, - "application/x-sea": { - source: "nginx", - extensions: ["sea"] - }, - "application/x-sh": { - source: "apache", - compressible: true, - extensions: ["sh"] - }, - "application/x-shar": { - source: "apache", - extensions: ["shar"] - }, - "application/x-shockwave-flash": { - source: "apache", - compressible: false, - extensions: ["swf"] - }, - "application/x-silverlight-app": { - source: "apache", - extensions: ["xap"] - }, - "application/x-sql": { - source: "apache", - extensions: ["sql"] - }, - "application/x-stuffit": { - source: "apache", - compressible: false, - extensions: ["sit"] - }, - "application/x-stuffitx": { - source: "apache", - extensions: ["sitx"] - }, - "application/x-subrip": { - source: "apache", - extensions: ["srt"] - }, - "application/x-sv4cpio": { - source: "apache", - extensions: ["sv4cpio"] - }, - "application/x-sv4crc": { - source: "apache", - extensions: ["sv4crc"] - }, - "application/x-t3vm-image": { - source: "apache", - extensions: ["t3"] - }, - "application/x-tads": { - source: "apache", - extensions: ["gam"] - }, - "application/x-tar": { - source: "apache", - compressible: true, - extensions: ["tar"] - }, - "application/x-tcl": { - source: "apache", - extensions: ["tcl", "tk"] - }, - "application/x-tex": { - source: "apache", - extensions: ["tex"] - }, - "application/x-tex-tfm": { - source: "apache", - extensions: ["tfm"] - }, - "application/x-texinfo": { - source: "apache", - extensions: ["texinfo", "texi"] - }, - "application/x-tgif": { - source: "apache", - extensions: ["obj"] - }, - "application/x-ustar": { - source: "apache", - extensions: ["ustar"] - }, - "application/x-virtualbox-hdd": { - compressible: true, - extensions: ["hdd"] - }, - "application/x-virtualbox-ova": { - compressible: true, - extensions: ["ova"] - }, - "application/x-virtualbox-ovf": { - compressible: true, - extensions: ["ovf"] - }, - "application/x-virtualbox-vbox": { - compressible: true, - extensions: ["vbox"] - }, - "application/x-virtualbox-vbox-extpack": { - compressible: false, - extensions: ["vbox-extpack"] - }, - "application/x-virtualbox-vdi": { - compressible: true, - extensions: ["vdi"] - }, - "application/x-virtualbox-vhd": { - compressible: true, - extensions: ["vhd"] - }, - "application/x-virtualbox-vmdk": { - compressible: true, - extensions: ["vmdk"] - }, - "application/x-wais-source": { - source: "apache", - extensions: ["src"] - }, - "application/x-web-app-manifest+json": { - compressible: true, - extensions: ["webapp"] - }, - "application/x-www-form-urlencoded": { - source: "iana", - compressible: true - }, - "application/x-x509-ca-cert": { - source: "iana", - extensions: ["der", "crt", "pem"] - }, - "application/x-x509-ca-ra-cert": { - source: "iana" - }, - "application/x-x509-next-ca-cert": { - source: "iana" - }, - "application/x-xfig": { - source: "apache", - extensions: ["fig"] - }, - "application/x-xliff+xml": { - source: "apache", - compressible: true, - extensions: ["xlf"] - }, - "application/x-xpinstall": { - source: "apache", - compressible: false, - extensions: ["xpi"] - }, - "application/x-xz": { - source: "apache", - extensions: ["xz"] - }, - "application/x-zip-compressed": { - extensions: ["zip"] - }, - "application/x-zmachine": { - source: "apache", - extensions: ["z1", "z2", "z3", "z4", "z5", "z6", "z7", "z8"] - }, - "application/x400-bp": { - source: "iana" - }, - "application/xacml+xml": { - source: "iana", - compressible: true - }, - "application/xaml+xml": { - source: "apache", - compressible: true, - extensions: ["xaml"] - }, - "application/xcap-att+xml": { - source: "iana", - compressible: true, - extensions: ["xav"] - }, - "application/xcap-caps+xml": { - source: "iana", - compressible: true, - extensions: ["xca"] - }, - "application/xcap-diff+xml": { - source: "iana", - compressible: true, - extensions: ["xdf"] - }, - "application/xcap-el+xml": { - source: "iana", - compressible: true, - extensions: ["xel"] - }, - "application/xcap-error+xml": { - source: "iana", - compressible: true - }, - "application/xcap-ns+xml": { - source: "iana", - compressible: true, - extensions: ["xns"] - }, - "application/xcon-conference-info+xml": { - source: "iana", - compressible: true - }, - "application/xcon-conference-info-diff+xml": { - source: "iana", - compressible: true - }, - "application/xenc+xml": { - source: "iana", - compressible: true, - extensions: ["xenc"] - }, - "application/xfdf": { - source: "iana", - extensions: ["xfdf"] - }, - "application/xhtml+xml": { - source: "iana", - compressible: true, - extensions: ["xhtml", "xht"] - }, - "application/xhtml-voice+xml": { - source: "apache", - compressible: true - }, - "application/xliff+xml": { - source: "iana", - compressible: true, - extensions: ["xlf"] - }, - "application/xml": { - source: "iana", - compressible: true, - extensions: ["xml", "xsl", "xsd", "rng"] - }, - "application/xml-dtd": { - source: "iana", - compressible: true, - extensions: ["dtd"] - }, - "application/xml-external-parsed-entity": { - source: "iana" - }, - "application/xml-patch+xml": { - source: "iana", - compressible: true - }, - "application/xmpp+xml": { - source: "iana", - compressible: true - }, - "application/xop+xml": { - source: "iana", - compressible: true, - extensions: ["xop"] - }, - "application/xproc+xml": { - source: "apache", - compressible: true, - extensions: ["xpl"] - }, - "application/xslt+xml": { - source: "iana", - compressible: true, - extensions: ["xsl", "xslt"] - }, - "application/xspf+xml": { - source: "apache", - compressible: true, - extensions: ["xspf"] - }, - "application/xv+xml": { - source: "iana", - compressible: true, - extensions: ["mxml", "xhvml", "xvml", "xvm"] - }, - "application/yaml": { - source: "iana" - }, - "application/yang": { - source: "iana", - extensions: ["yang"] - }, - "application/yang-data+cbor": { - source: "iana" - }, - "application/yang-data+json": { - source: "iana", - compressible: true - }, - "application/yang-data+xml": { - source: "iana", - compressible: true - }, - "application/yang-patch+json": { - source: "iana", - compressible: true - }, - "application/yang-patch+xml": { - source: "iana", - compressible: true - }, - "application/yang-sid+json": { - source: "iana", - compressible: true - }, - "application/yin+xml": { - source: "iana", - compressible: true, - extensions: ["yin"] - }, - "application/zip": { - source: "iana", - compressible: false, - extensions: ["zip"] - }, - "application/zip+dotlottie": { - extensions: ["lottie"] - }, - "application/zlib": { - source: "iana" - }, - "application/zstd": { - source: "iana" - }, - "audio/1d-interleaved-parityfec": { - source: "iana" - }, - "audio/32kadpcm": { - source: "iana" - }, - "audio/3gpp": { - source: "iana", - compressible: false, - extensions: ["3gpp"] - }, - "audio/3gpp2": { - source: "iana" - }, - "audio/aac": { - source: "iana", - extensions: ["adts", "aac"] - }, - "audio/ac3": { - source: "iana" - }, - "audio/adpcm": { - source: "apache", - extensions: ["adp"] - }, - "audio/amr": { - source: "iana", - extensions: ["amr"] - }, - "audio/amr-wb": { - source: "iana" - }, - "audio/amr-wb+": { - source: "iana" - }, - "audio/aptx": { - source: "iana" - }, - "audio/asc": { - source: "iana" - }, - "audio/atrac-advanced-lossless": { - source: "iana" - }, - "audio/atrac-x": { - source: "iana" - }, - "audio/atrac3": { - source: "iana" - }, - "audio/basic": { - source: "iana", - compressible: false, - extensions: ["au", "snd"] - }, - "audio/bv16": { - source: "iana" - }, - "audio/bv32": { - source: "iana" - }, - "audio/clearmode": { - source: "iana" - }, - "audio/cn": { - source: "iana" - }, - "audio/dat12": { - source: "iana" - }, - "audio/dls": { - source: "iana" - }, - "audio/dsr-es201108": { - source: "iana" - }, - "audio/dsr-es202050": { - source: "iana" - }, - "audio/dsr-es202211": { - source: "iana" - }, - "audio/dsr-es202212": { - source: "iana" - }, - "audio/dv": { - source: "iana" - }, - "audio/dvi4": { - source: "iana" - }, - "audio/eac3": { - source: "iana" - }, - "audio/encaprtp": { - source: "iana" - }, - "audio/evrc": { - source: "iana" - }, - "audio/evrc-qcp": { - source: "iana" - }, - "audio/evrc0": { - source: "iana" - }, - "audio/evrc1": { - source: "iana" - }, - "audio/evrcb": { - source: "iana" - }, - "audio/evrcb0": { - source: "iana" - }, - "audio/evrcb1": { - source: "iana" - }, - "audio/evrcnw": { - source: "iana" - }, - "audio/evrcnw0": { - source: "iana" - }, - "audio/evrcnw1": { - source: "iana" - }, - "audio/evrcwb": { - source: "iana" - }, - "audio/evrcwb0": { - source: "iana" - }, - "audio/evrcwb1": { - source: "iana" - }, - "audio/evs": { - source: "iana" - }, - "audio/flac": { - source: "iana" - }, - "audio/flexfec": { - source: "iana" - }, - "audio/fwdred": { - source: "iana" - }, - "audio/g711-0": { - source: "iana" - }, - "audio/g719": { - source: "iana" - }, - "audio/g722": { - source: "iana" - }, - "audio/g7221": { - source: "iana" - }, - "audio/g723": { - source: "iana" - }, - "audio/g726-16": { - source: "iana" - }, - "audio/g726-24": { - source: "iana" - }, - "audio/g726-32": { - source: "iana" - }, - "audio/g726-40": { - source: "iana" - }, - "audio/g728": { - source: "iana" - }, - "audio/g729": { - source: "iana" - }, - "audio/g7291": { - source: "iana" - }, - "audio/g729d": { - source: "iana" - }, - "audio/g729e": { - source: "iana" - }, - "audio/gsm": { - source: "iana" - }, - "audio/gsm-efr": { - source: "iana" - }, - "audio/gsm-hr-08": { - source: "iana" - }, - "audio/ilbc": { - source: "iana" - }, - "audio/ip-mr_v2.5": { - source: "iana" - }, - "audio/isac": { - source: "apache" - }, - "audio/l16": { - source: "iana" - }, - "audio/l20": { - source: "iana" - }, - "audio/l24": { - source: "iana", - compressible: false - }, - "audio/l8": { - source: "iana" - }, - "audio/lpc": { - source: "iana" - }, - "audio/matroska": { - source: "iana" - }, - "audio/melp": { - source: "iana" - }, - "audio/melp1200": { - source: "iana" - }, - "audio/melp2400": { - source: "iana" - }, - "audio/melp600": { - source: "iana" - }, - "audio/mhas": { - source: "iana" - }, - "audio/midi": { - source: "apache", - extensions: ["mid", "midi", "kar", "rmi"] - }, - "audio/midi-clip": { - source: "iana" - }, - "audio/mobile-xmf": { - source: "iana", - extensions: ["mxmf"] - }, - "audio/mp3": { - compressible: false, - extensions: ["mp3"] - }, - "audio/mp4": { - source: "iana", - compressible: false, - extensions: ["m4a", "mp4a", "m4b"] - }, - "audio/mp4a-latm": { - source: "iana" - }, - "audio/mpa": { - source: "iana" - }, - "audio/mpa-robust": { - source: "iana" - }, - "audio/mpeg": { - source: "iana", - compressible: false, - extensions: ["mpga", "mp2", "mp2a", "mp3", "m2a", "m3a"] - }, - "audio/mpeg4-generic": { - source: "iana" - }, - "audio/musepack": { - source: "apache" - }, - "audio/ogg": { - source: "iana", - compressible: false, - extensions: ["oga", "ogg", "spx", "opus"] - }, - "audio/opus": { - source: "iana" - }, - "audio/parityfec": { - source: "iana" - }, - "audio/pcma": { - source: "iana" - }, - "audio/pcma-wb": { - source: "iana" - }, - "audio/pcmu": { - source: "iana" - }, - "audio/pcmu-wb": { - source: "iana" - }, - "audio/prs.sid": { - source: "iana" - }, - "audio/qcelp": { - source: "iana" - }, - "audio/raptorfec": { - source: "iana" - }, - "audio/red": { - source: "iana" - }, - "audio/rtp-enc-aescm128": { - source: "iana" - }, - "audio/rtp-midi": { - source: "iana" - }, - "audio/rtploopback": { - source: "iana" - }, - "audio/rtx": { - source: "iana" - }, - "audio/s3m": { - source: "apache", - extensions: ["s3m"] - }, - "audio/scip": { - source: "iana" - }, - "audio/silk": { - source: "apache", - extensions: ["sil"] - }, - "audio/smv": { - source: "iana" - }, - "audio/smv-qcp": { - source: "iana" - }, - "audio/smv0": { - source: "iana" - }, - "audio/sofa": { - source: "iana" - }, - "audio/sp-midi": { - source: "iana" - }, - "audio/speex": { - source: "iana" - }, - "audio/t140c": { - source: "iana" - }, - "audio/t38": { - source: "iana" - }, - "audio/telephone-event": { - source: "iana" - }, - "audio/tetra_acelp": { - source: "iana" - }, - "audio/tetra_acelp_bb": { - source: "iana" - }, - "audio/tone": { - source: "iana" - }, - "audio/tsvcis": { - source: "iana" - }, - "audio/uemclip": { - source: "iana" - }, - "audio/ulpfec": { - source: "iana" - }, - "audio/usac": { - source: "iana" - }, - "audio/vdvi": { - source: "iana" - }, - "audio/vmr-wb": { - source: "iana" - }, - "audio/vnd.3gpp.iufp": { - source: "iana" - }, - "audio/vnd.4sb": { - source: "iana" - }, - "audio/vnd.audiokoz": { - source: "iana" - }, - "audio/vnd.celp": { - source: "iana" - }, - "audio/vnd.cisco.nse": { - source: "iana" - }, - "audio/vnd.cmles.radio-events": { - source: "iana" - }, - "audio/vnd.cns.anp1": { - source: "iana" - }, - "audio/vnd.cns.inf1": { - source: "iana" - }, - "audio/vnd.dece.audio": { - source: "iana", - extensions: ["uva", "uvva"] - }, - "audio/vnd.digital-winds": { - source: "iana", - extensions: ["eol"] - }, - "audio/vnd.dlna.adts": { - source: "iana" - }, - "audio/vnd.dolby.heaac.1": { - source: "iana" - }, - "audio/vnd.dolby.heaac.2": { - source: "iana" - }, - "audio/vnd.dolby.mlp": { - source: "iana" - }, - "audio/vnd.dolby.mps": { - source: "iana" - }, - "audio/vnd.dolby.pl2": { - source: "iana" - }, - "audio/vnd.dolby.pl2x": { - source: "iana" - }, - "audio/vnd.dolby.pl2z": { - source: "iana" - }, - "audio/vnd.dolby.pulse.1": { - source: "iana" - }, - "audio/vnd.dra": { - source: "iana", - extensions: ["dra"] - }, - "audio/vnd.dts": { - source: "iana", - extensions: ["dts"] - }, - "audio/vnd.dts.hd": { - source: "iana", - extensions: ["dtshd"] - }, - "audio/vnd.dts.uhd": { - source: "iana" - }, - "audio/vnd.dvb.file": { - source: "iana" - }, - "audio/vnd.everad.plj": { - source: "iana" - }, - "audio/vnd.hns.audio": { - source: "iana" - }, - "audio/vnd.lucent.voice": { - source: "iana", - extensions: ["lvp"] - }, - "audio/vnd.ms-playready.media.pya": { - source: "iana", - extensions: ["pya"] - }, - "audio/vnd.nokia.mobile-xmf": { - source: "iana" - }, - "audio/vnd.nortel.vbk": { - source: "iana" - }, - "audio/vnd.nuera.ecelp4800": { - source: "iana", - extensions: ["ecelp4800"] - }, - "audio/vnd.nuera.ecelp7470": { - source: "iana", - extensions: ["ecelp7470"] - }, - "audio/vnd.nuera.ecelp9600": { - source: "iana", - extensions: ["ecelp9600"] - }, - "audio/vnd.octel.sbc": { - source: "iana" - }, - "audio/vnd.presonus.multitrack": { - source: "iana" - }, - "audio/vnd.qcelp": { - source: "apache" - }, - "audio/vnd.rhetorex.32kadpcm": { - source: "iana" - }, - "audio/vnd.rip": { - source: "iana", - extensions: ["rip"] - }, - "audio/vnd.rn-realaudio": { - compressible: false - }, - "audio/vnd.sealedmedia.softseal.mpeg": { - source: "iana" - }, - "audio/vnd.vmx.cvsd": { - source: "iana" - }, - "audio/vnd.wave": { - compressible: false - }, - "audio/vorbis": { - source: "iana", - compressible: false - }, - "audio/vorbis-config": { - source: "iana" - }, - "audio/wav": { - compressible: false, - extensions: ["wav"] - }, - "audio/wave": { - compressible: false, - extensions: ["wav"] - }, - "audio/webm": { - source: "apache", - compressible: false, - extensions: ["weba"] - }, - "audio/x-aac": { - source: "apache", - compressible: false, - extensions: ["aac"] - }, - "audio/x-aiff": { - source: "apache", - extensions: ["aif", "aiff", "aifc"] - }, - "audio/x-caf": { - source: "apache", - compressible: false, - extensions: ["caf"] - }, - "audio/x-flac": { - source: "apache", - extensions: ["flac"] - }, - "audio/x-m4a": { - source: "nginx", - extensions: ["m4a"] - }, - "audio/x-matroska": { - source: "apache", - extensions: ["mka"] - }, - "audio/x-mpegurl": { - source: "apache", - extensions: ["m3u"] - }, - "audio/x-ms-wax": { - source: "apache", - extensions: ["wax"] - }, - "audio/x-ms-wma": { - source: "apache", - extensions: ["wma"] - }, - "audio/x-pn-realaudio": { - source: "apache", - extensions: ["ram", "ra"] - }, - "audio/x-pn-realaudio-plugin": { - source: "apache", - extensions: ["rmp"] - }, - "audio/x-realaudio": { - source: "nginx", - extensions: ["ra"] - }, - "audio/x-tta": { - source: "apache" - }, - "audio/x-wav": { - source: "apache", - extensions: ["wav"] - }, - "audio/xm": { - source: "apache", - extensions: ["xm"] - }, - "chemical/x-cdx": { - source: "apache", - extensions: ["cdx"] - }, - "chemical/x-cif": { - source: "apache", - extensions: ["cif"] - }, - "chemical/x-cmdf": { - source: "apache", - extensions: ["cmdf"] - }, - "chemical/x-cml": { - source: "apache", - extensions: ["cml"] - }, - "chemical/x-csml": { - source: "apache", - extensions: ["csml"] - }, - "chemical/x-pdb": { - source: "apache" - }, - "chemical/x-xyz": { - source: "apache", - extensions: ["xyz"] - }, - "font/collection": { - source: "iana", - extensions: ["ttc"] - }, - "font/otf": { - source: "iana", - compressible: true, - extensions: ["otf"] - }, - "font/sfnt": { - source: "iana" - }, - "font/ttf": { - source: "iana", - compressible: true, - extensions: ["ttf"] - }, - "font/woff": { - source: "iana", - extensions: ["woff"] - }, - "font/woff2": { - source: "iana", - extensions: ["woff2"] - }, - "image/aces": { - source: "iana", - extensions: ["exr"] - }, - "image/apng": { - source: "iana", - compressible: false, - extensions: ["apng"] - }, - "image/avci": { - source: "iana", - extensions: ["avci"] - }, - "image/avcs": { - source: "iana", - extensions: ["avcs"] - }, - "image/avif": { - source: "iana", - compressible: false, - extensions: ["avif"] - }, - "image/bmp": { - source: "iana", - compressible: true, - extensions: ["bmp", "dib"] - }, - "image/cgm": { - source: "iana", - extensions: ["cgm"] - }, - "image/dicom-rle": { - source: "iana", - extensions: ["drle"] - }, - "image/dpx": { - source: "iana", - extensions: ["dpx"] - }, - "image/emf": { - source: "iana", - extensions: ["emf"] - }, - "image/fits": { - source: "iana", - extensions: ["fits"] - }, - "image/g3fax": { - source: "iana", - extensions: ["g3"] - }, - "image/gif": { - source: "iana", - compressible: false, - extensions: ["gif"] - }, - "image/heic": { - source: "iana", - extensions: ["heic"] - }, - "image/heic-sequence": { - source: "iana", - extensions: ["heics"] - }, - "image/heif": { - source: "iana", - extensions: ["heif"] - }, - "image/heif-sequence": { - source: "iana", - extensions: ["heifs"] - }, - "image/hej2k": { - source: "iana", - extensions: ["hej2"] - }, - "image/ief": { - source: "iana", - extensions: ["ief"] - }, - "image/j2c": { - source: "iana" - }, - "image/jaii": { - source: "iana", - extensions: ["jaii"] - }, - "image/jais": { - source: "iana", - extensions: ["jais"] - }, - "image/jls": { - source: "iana", - extensions: ["jls"] - }, - "image/jp2": { - source: "iana", - compressible: false, - extensions: ["jp2", "jpg2"] - }, - "image/jpeg": { - source: "iana", - compressible: false, - extensions: ["jpg", "jpeg", "jpe"] - }, - "image/jph": { - source: "iana", - extensions: ["jph"] - }, - "image/jphc": { - source: "iana", - extensions: ["jhc"] - }, - "image/jpm": { - source: "iana", - compressible: false, - extensions: ["jpm", "jpgm"] - }, - "image/jpx": { - source: "iana", - compressible: false, - extensions: ["jpx", "jpf"] - }, - "image/jxl": { - source: "iana", - extensions: ["jxl"] - }, - "image/jxr": { - source: "iana", - extensions: ["jxr"] - }, - "image/jxra": { - source: "iana", - extensions: ["jxra"] - }, - "image/jxrs": { - source: "iana", - extensions: ["jxrs"] - }, - "image/jxs": { - source: "iana", - extensions: ["jxs"] - }, - "image/jxsc": { - source: "iana", - extensions: ["jxsc"] - }, - "image/jxsi": { - source: "iana", - extensions: ["jxsi"] - }, - "image/jxss": { - source: "iana", - extensions: ["jxss"] - }, - "image/ktx": { - source: "iana", - extensions: ["ktx"] - }, - "image/ktx2": { - source: "iana", - extensions: ["ktx2"] - }, - "image/naplps": { - source: "iana" - }, - "image/pjpeg": { - compressible: false, - extensions: ["jfif"] - }, - "image/png": { - source: "iana", - compressible: false, - extensions: ["png"] - }, - "image/prs.btif": { - source: "iana", - extensions: ["btif", "btf"] - }, - "image/prs.pti": { - source: "iana", - extensions: ["pti"] - }, - "image/pwg-raster": { - source: "iana" - }, - "image/sgi": { - source: "apache", - extensions: ["sgi"] - }, - "image/svg+xml": { - source: "iana", - compressible: true, - extensions: ["svg", "svgz"] - }, - "image/t38": { - source: "iana", - extensions: ["t38"] - }, - "image/tiff": { - source: "iana", - compressible: false, - extensions: ["tif", "tiff"] - }, - "image/tiff-fx": { - source: "iana", - extensions: ["tfx"] - }, - "image/vnd.adobe.photoshop": { - source: "iana", - compressible: true, - extensions: ["psd"] - }, - "image/vnd.airzip.accelerator.azv": { - source: "iana", - extensions: ["azv"] - }, - "image/vnd.clip": { - source: "iana" - }, - "image/vnd.cns.inf2": { - source: "iana" - }, - "image/vnd.dece.graphic": { - source: "iana", - extensions: ["uvi", "uvvi", "uvg", "uvvg"] - }, - "image/vnd.djvu": { - source: "iana", - extensions: ["djvu", "djv"] - }, - "image/vnd.dvb.subtitle": { - source: "iana", - extensions: ["sub"] - }, - "image/vnd.dwg": { - source: "iana", - extensions: ["dwg"] - }, - "image/vnd.dxf": { - source: "iana", - extensions: ["dxf"] - }, - "image/vnd.fastbidsheet": { - source: "iana", - extensions: ["fbs"] - }, - "image/vnd.fpx": { - source: "iana", - extensions: ["fpx"] - }, - "image/vnd.fst": { - source: "iana", - extensions: ["fst"] - }, - "image/vnd.fujixerox.edmics-mmr": { - source: "iana", - extensions: ["mmr"] - }, - "image/vnd.fujixerox.edmics-rlc": { - source: "iana", - extensions: ["rlc"] - }, - "image/vnd.globalgraphics.pgb": { - source: "iana" - }, - "image/vnd.microsoft.icon": { - source: "iana", - compressible: true, - extensions: ["ico"] - }, - "image/vnd.mix": { - source: "iana" - }, - "image/vnd.mozilla.apng": { - source: "iana" - }, - "image/vnd.ms-dds": { - compressible: true, - extensions: ["dds"] - }, - "image/vnd.ms-modi": { - source: "iana", - extensions: ["mdi"] - }, - "image/vnd.ms-photo": { - source: "apache", - extensions: ["wdp"] - }, - "image/vnd.net-fpx": { - source: "iana", - extensions: ["npx"] - }, - "image/vnd.pco.b16": { - source: "iana", - extensions: ["b16"] - }, - "image/vnd.radiance": { - source: "iana" - }, - "image/vnd.sealed.png": { - source: "iana" - }, - "image/vnd.sealedmedia.softseal.gif": { - source: "iana" - }, - "image/vnd.sealedmedia.softseal.jpg": { - source: "iana" - }, - "image/vnd.svf": { - source: "iana" - }, - "image/vnd.tencent.tap": { - source: "iana", - extensions: ["tap"] - }, - "image/vnd.valve.source.texture": { - source: "iana", - extensions: ["vtf"] - }, - "image/vnd.wap.wbmp": { - source: "iana", - extensions: ["wbmp"] - }, - "image/vnd.xiff": { - source: "iana", - extensions: ["xif"] - }, - "image/vnd.zbrush.pcx": { - source: "iana", - extensions: ["pcx"] - }, - "image/webp": { - source: "iana", - extensions: ["webp"] - }, - "image/wmf": { - source: "iana", - extensions: ["wmf"] - }, - "image/x-3ds": { - source: "apache", - extensions: ["3ds"] - }, - "image/x-adobe-dng": { - extensions: ["dng"] - }, - "image/x-cmu-raster": { - source: "apache", - extensions: ["ras"] - }, - "image/x-cmx": { - source: "apache", - extensions: ["cmx"] - }, - "image/x-emf": { - source: "iana" - }, - "image/x-freehand": { - source: "apache", - extensions: ["fh", "fhc", "fh4", "fh5", "fh7"] - }, - "image/x-icon": { - source: "apache", - compressible: true, - extensions: ["ico"] - }, - "image/x-jng": { - source: "nginx", - extensions: ["jng"] - }, - "image/x-mrsid-image": { - source: "apache", - extensions: ["sid"] - }, - "image/x-ms-bmp": { - source: "nginx", - compressible: true, - extensions: ["bmp"] - }, - "image/x-pcx": { - source: "apache", - extensions: ["pcx"] - }, - "image/x-pict": { - source: "apache", - extensions: ["pic", "pct"] - }, - "image/x-portable-anymap": { - source: "apache", - extensions: ["pnm"] - }, - "image/x-portable-bitmap": { - source: "apache", - extensions: ["pbm"] - }, - "image/x-portable-graymap": { - source: "apache", - extensions: ["pgm"] - }, - "image/x-portable-pixmap": { - source: "apache", - extensions: ["ppm"] - }, - "image/x-rgb": { - source: "apache", - extensions: ["rgb"] - }, - "image/x-tga": { - source: "apache", - extensions: ["tga"] - }, - "image/x-wmf": { - source: "iana" - }, - "image/x-xbitmap": { - source: "apache", - extensions: ["xbm"] - }, - "image/x-xcf": { - compressible: false - }, - "image/x-xpixmap": { - source: "apache", - extensions: ["xpm"] - }, - "image/x-xwindowdump": { - source: "apache", - extensions: ["xwd"] - }, - "message/bhttp": { - source: "iana" - }, - "message/cpim": { - source: "iana" - }, - "message/delivery-status": { - source: "iana" - }, - "message/disposition-notification": { - source: "iana", - extensions: [ - "disposition-notification" - ] - }, - "message/external-body": { - source: "iana" - }, - "message/feedback-report": { - source: "iana" - }, - "message/global": { - source: "iana", - extensions: ["u8msg"] - }, - "message/global-delivery-status": { - source: "iana", - extensions: ["u8dsn"] - }, - "message/global-disposition-notification": { - source: "iana", - extensions: ["u8mdn"] - }, - "message/global-headers": { - source: "iana", - extensions: ["u8hdr"] - }, - "message/http": { - source: "iana", - compressible: false - }, - "message/imdn+xml": { - source: "iana", - compressible: true - }, - "message/mls": { - source: "iana" - }, - "message/news": { - source: "apache" - }, - "message/ohttp-req": { - source: "iana" - }, - "message/ohttp-res": { - source: "iana" - }, - "message/partial": { - source: "iana", - compressible: false - }, - "message/rfc822": { - source: "iana", - compressible: true, - extensions: ["eml", "mime", "mht", "mhtml"] - }, - "message/s-http": { - source: "apache" - }, - "message/sip": { - source: "iana" - }, - "message/sipfrag": { - source: "iana" - }, - "message/tracking-status": { - source: "iana" - }, - "message/vnd.si.simp": { - source: "apache" - }, - "message/vnd.wfa.wsc": { - source: "iana", - extensions: ["wsc"] - }, - "model/3mf": { - source: "iana", - extensions: ["3mf"] - }, - "model/e57": { - source: "iana" - }, - "model/gltf+json": { - source: "iana", - compressible: true, - extensions: ["gltf"] - }, - "model/gltf-binary": { - source: "iana", - compressible: true, - extensions: ["glb"] - }, - "model/iges": { - source: "iana", - compressible: false, - extensions: ["igs", "iges"] - }, - "model/jt": { - source: "iana", - extensions: ["jt"] - }, - "model/mesh": { - source: "iana", - compressible: false, - extensions: ["msh", "mesh", "silo"] - }, - "model/mtl": { - source: "iana", - extensions: ["mtl"] - }, - "model/obj": { - source: "iana", - extensions: ["obj"] - }, - "model/prc": { - source: "iana", - extensions: ["prc"] - }, - "model/step": { - source: "iana", - extensions: ["step", "stp", "stpnc", "p21", "210"] - }, - "model/step+xml": { - source: "iana", - compressible: true, - extensions: ["stpx"] - }, - "model/step+zip": { - source: "iana", - compressible: false, - extensions: ["stpz"] - }, - "model/step-xml+zip": { - source: "iana", - compressible: false, - extensions: ["stpxz"] - }, - "model/stl": { - source: "iana", - extensions: ["stl"] - }, - "model/u3d": { - source: "iana", - extensions: ["u3d"] - }, - "model/vnd.bary": { - source: "iana", - extensions: ["bary"] - }, - "model/vnd.cld": { - source: "iana", - extensions: ["cld"] - }, - "model/vnd.collada+xml": { - source: "iana", - compressible: true, - extensions: ["dae"] - }, - "model/vnd.dwf": { - source: "iana", - extensions: ["dwf"] - }, - "model/vnd.flatland.3dml": { - source: "iana" - }, - "model/vnd.gdl": { - source: "iana", - extensions: ["gdl"] - }, - "model/vnd.gs-gdl": { - source: "apache" - }, - "model/vnd.gs.gdl": { - source: "iana" - }, - "model/vnd.gtw": { - source: "iana", - extensions: ["gtw"] - }, - "model/vnd.moml+xml": { - source: "iana", - compressible: true - }, - "model/vnd.mts": { - source: "iana", - extensions: ["mts"] - }, - "model/vnd.opengex": { - source: "iana", - extensions: ["ogex"] - }, - "model/vnd.parasolid.transmit.binary": { - source: "iana", - extensions: ["x_b"] - }, - "model/vnd.parasolid.transmit.text": { - source: "iana", - extensions: ["x_t"] - }, - "model/vnd.pytha.pyox": { - source: "iana", - extensions: ["pyo", "pyox"] - }, - "model/vnd.rosette.annotated-data-model": { - source: "iana" - }, - "model/vnd.sap.vds": { - source: "iana", - extensions: ["vds"] - }, - "model/vnd.usda": { - source: "iana", - extensions: ["usda"] - }, - "model/vnd.usdz+zip": { - source: "iana", - compressible: false, - extensions: ["usdz"] - }, - "model/vnd.valve.source.compiled-map": { - source: "iana", - extensions: ["bsp"] - }, - "model/vnd.vtu": { - source: "iana", - extensions: ["vtu"] - }, - "model/vrml": { - source: "iana", - compressible: false, - extensions: ["wrl", "vrml"] - }, - "model/x3d+binary": { - source: "apache", - compressible: false, - extensions: ["x3db", "x3dbz"] - }, - "model/x3d+fastinfoset": { - source: "iana", - extensions: ["x3db"] - }, - "model/x3d+vrml": { - source: "apache", - compressible: false, - extensions: ["x3dv", "x3dvz"] - }, - "model/x3d+xml": { - source: "iana", - compressible: true, - extensions: ["x3d", "x3dz"] - }, - "model/x3d-vrml": { - source: "iana", - extensions: ["x3dv"] - }, - "multipart/alternative": { - source: "iana", - compressible: false - }, - "multipart/appledouble": { - source: "iana" - }, - "multipart/byteranges": { - source: "iana" - }, - "multipart/digest": { - source: "iana" - }, - "multipart/encrypted": { - source: "iana", - compressible: false - }, - "multipart/form-data": { - source: "iana", - compressible: false - }, - "multipart/header-set": { - source: "iana" - }, - "multipart/mixed": { - source: "iana" - }, - "multipart/multilingual": { - source: "iana" - }, - "multipart/parallel": { - source: "iana" - }, - "multipart/related": { - source: "iana", - compressible: false - }, - "multipart/report": { - source: "iana" - }, - "multipart/signed": { - source: "iana", - compressible: false - }, - "multipart/vnd.bint.med-plus": { - source: "iana" - }, - "multipart/voice-message": { - source: "iana" - }, - "multipart/x-mixed-replace": { - source: "iana" - }, - "text/1d-interleaved-parityfec": { - source: "iana" - }, - "text/cache-manifest": { - source: "iana", - compressible: true, - extensions: ["appcache", "manifest"] - }, - "text/calendar": { - source: "iana", - extensions: ["ics", "ifb"] - }, - "text/calender": { - compressible: true - }, - "text/cmd": { - compressible: true - }, - "text/coffeescript": { - extensions: ["coffee", "litcoffee"] - }, - "text/cql": { - source: "iana" - }, - "text/cql-expression": { - source: "iana" - }, - "text/cql-identifier": { - source: "iana" - }, - "text/css": { - source: "iana", - charset: "UTF-8", - compressible: true, - extensions: ["css"] - }, - "text/csv": { - source: "iana", - compressible: true, - extensions: ["csv"] - }, - "text/csv-schema": { - source: "iana" - }, - "text/directory": { - source: "iana" - }, - "text/dns": { - source: "iana" - }, - "text/ecmascript": { - source: "apache" - }, - "text/encaprtp": { - source: "iana" - }, - "text/enriched": { - source: "iana" - }, - "text/fhirpath": { - source: "iana" - }, - "text/flexfec": { - source: "iana" - }, - "text/fwdred": { - source: "iana" - }, - "text/gff3": { - source: "iana" - }, - "text/grammar-ref-list": { - source: "iana" - }, - "text/hl7v2": { - source: "iana" - }, - "text/html": { - source: "iana", - compressible: true, - extensions: ["html", "htm", "shtml"] - }, - "text/jade": { - extensions: ["jade"] - }, - "text/javascript": { - source: "iana", - charset: "UTF-8", - compressible: true, - extensions: ["js", "mjs"] - }, - "text/jcr-cnd": { - source: "iana" - }, - "text/jsx": { - compressible: true, - extensions: ["jsx"] - }, - "text/less": { - compressible: true, - extensions: ["less"] - }, - "text/markdown": { - source: "iana", - compressible: true, - extensions: ["md", "markdown"] - }, - "text/mathml": { - source: "nginx", - extensions: ["mml"] - }, - "text/mdx": { - compressible: true, - extensions: ["mdx"] - }, - "text/mizar": { - source: "iana" - }, - "text/n3": { - source: "iana", - charset: "UTF-8", - compressible: true, - extensions: ["n3"] - }, - "text/parameters": { - source: "iana", - charset: "UTF-8" - }, - "text/parityfec": { - source: "iana" - }, - "text/plain": { - source: "iana", - compressible: true, - extensions: ["txt", "text", "conf", "def", "list", "log", "in", "ini"] - }, - "text/provenance-notation": { - source: "iana", - charset: "UTF-8" - }, - "text/prs.fallenstein.rst": { - source: "iana" - }, - "text/prs.lines.tag": { - source: "iana", - extensions: ["dsc"] - }, - "text/prs.prop.logic": { - source: "iana" - }, - "text/prs.texi": { - source: "iana" - }, - "text/raptorfec": { - source: "iana" - }, - "text/red": { - source: "iana" - }, - "text/rfc822-headers": { - source: "iana" - }, - "text/richtext": { - source: "iana", - compressible: true, - extensions: ["rtx"] - }, - "text/rtf": { - source: "iana", - compressible: true, - extensions: ["rtf"] - }, - "text/rtp-enc-aescm128": { - source: "iana" - }, - "text/rtploopback": { - source: "iana" - }, - "text/rtx": { - source: "iana" - }, - "text/sgml": { - source: "iana", - extensions: ["sgml", "sgm"] - }, - "text/shaclc": { - source: "iana" - }, - "text/shex": { - source: "iana", - extensions: ["shex"] - }, - "text/slim": { - extensions: ["slim", "slm"] - }, - "text/spdx": { - source: "iana", - extensions: ["spdx"] - }, - "text/strings": { - source: "iana" - }, - "text/stylus": { - extensions: ["stylus", "styl"] - }, - "text/t140": { - source: "iana" - }, - "text/tab-separated-values": { - source: "iana", - compressible: true, - extensions: ["tsv"] - }, - "text/troff": { - source: "iana", - extensions: ["t", "tr", "roff", "man", "me", "ms"] - }, - "text/turtle": { - source: "iana", - charset: "UTF-8", - extensions: ["ttl"] - }, - "text/ulpfec": { - source: "iana" - }, - "text/uri-list": { - source: "iana", - compressible: true, - extensions: ["uri", "uris", "urls"] - }, - "text/vcard": { - source: "iana", - compressible: true, - extensions: ["vcard"] - }, - "text/vnd.a": { - source: "iana" - }, - "text/vnd.abc": { - source: "iana" - }, - "text/vnd.ascii-art": { - source: "iana" - }, - "text/vnd.curl": { - source: "iana", - extensions: ["curl"] - }, - "text/vnd.curl.dcurl": { - source: "apache", - extensions: ["dcurl"] - }, - "text/vnd.curl.mcurl": { - source: "apache", - extensions: ["mcurl"] - }, - "text/vnd.curl.scurl": { - source: "apache", - extensions: ["scurl"] - }, - "text/vnd.debian.copyright": { - source: "iana", - charset: "UTF-8" - }, - "text/vnd.dmclientscript": { - source: "iana" - }, - "text/vnd.dvb.subtitle": { - source: "iana", - extensions: ["sub"] - }, - "text/vnd.esmertec.theme-descriptor": { - source: "iana", - charset: "UTF-8" - }, - "text/vnd.exchangeable": { - source: "iana" - }, - "text/vnd.familysearch.gedcom": { - source: "iana", - extensions: ["ged"] - }, - "text/vnd.ficlab.flt": { - source: "iana" - }, - "text/vnd.fly": { - source: "iana", - extensions: ["fly"] - }, - "text/vnd.fmi.flexstor": { - source: "iana", - extensions: ["flx"] - }, - "text/vnd.gml": { - source: "iana" - }, - "text/vnd.graphviz": { - source: "iana", - extensions: ["gv"] - }, - "text/vnd.hans": { - source: "iana" - }, - "text/vnd.hgl": { - source: "iana" - }, - "text/vnd.in3d.3dml": { - source: "iana", - extensions: ["3dml"] - }, - "text/vnd.in3d.spot": { - source: "iana", - extensions: ["spot"] - }, - "text/vnd.iptc.newsml": { - source: "iana" - }, - "text/vnd.iptc.nitf": { - source: "iana" - }, - "text/vnd.latex-z": { - source: "iana" - }, - "text/vnd.motorola.reflex": { - source: "iana" - }, - "text/vnd.ms-mediapackage": { - source: "iana" - }, - "text/vnd.net2phone.commcenter.command": { - source: "iana" - }, - "text/vnd.radisys.msml-basic-layout": { - source: "iana" - }, - "text/vnd.senx.warpscript": { - source: "iana" - }, - "text/vnd.si.uricatalogue": { - source: "apache" - }, - "text/vnd.sosi": { - source: "iana" - }, - "text/vnd.sun.j2me.app-descriptor": { - source: "iana", - charset: "UTF-8", - extensions: ["jad"] - }, - "text/vnd.trolltech.linguist": { - source: "iana", - charset: "UTF-8" - }, - "text/vnd.vcf": { - source: "iana" - }, - "text/vnd.wap.si": { - source: "iana" - }, - "text/vnd.wap.sl": { - source: "iana" - }, - "text/vnd.wap.wml": { - source: "iana", - extensions: ["wml"] - }, - "text/vnd.wap.wmlscript": { - source: "iana", - extensions: ["wmls"] - }, - "text/vnd.zoo.kcl": { - source: "iana" - }, - "text/vtt": { - source: "iana", - charset: "UTF-8", - compressible: true, - extensions: ["vtt"] - }, - "text/wgsl": { - source: "iana", - extensions: ["wgsl"] - }, - "text/x-asm": { - source: "apache", - extensions: ["s", "asm"] - }, - "text/x-c": { - source: "apache", - extensions: ["c", "cc", "cxx", "cpp", "h", "hh", "dic"] - }, - "text/x-component": { - source: "nginx", - extensions: ["htc"] - }, - "text/x-fortran": { - source: "apache", - extensions: ["f", "for", "f77", "f90"] - }, - "text/x-gwt-rpc": { - compressible: true - }, - "text/x-handlebars-template": { - extensions: ["hbs"] - }, - "text/x-java-source": { - source: "apache", - extensions: ["java"] - }, - "text/x-jquery-tmpl": { - compressible: true - }, - "text/x-lua": { - extensions: ["lua"] - }, - "text/x-markdown": { - compressible: true, - extensions: ["mkd"] - }, - "text/x-nfo": { - source: "apache", - extensions: ["nfo"] - }, - "text/x-opml": { - source: "apache", - extensions: ["opml"] - }, - "text/x-org": { - compressible: true, - extensions: ["org"] - }, - "text/x-pascal": { - source: "apache", - extensions: ["p", "pas"] - }, - "text/x-processing": { - compressible: true, - extensions: ["pde"] - }, - "text/x-sass": { - extensions: ["sass"] - }, - "text/x-scss": { - extensions: ["scss"] - }, - "text/x-setext": { - source: "apache", - extensions: ["etx"] - }, - "text/x-sfv": { - source: "apache", - extensions: ["sfv"] - }, - "text/x-suse-ymp": { - compressible: true, - extensions: ["ymp"] - }, - "text/x-uuencode": { - source: "apache", - extensions: ["uu"] - }, - "text/x-vcalendar": { - source: "apache", - extensions: ["vcs"] - }, - "text/x-vcard": { - source: "apache", - extensions: ["vcf"] - }, - "text/xml": { - source: "iana", - compressible: true, - extensions: ["xml"] - }, - "text/xml-external-parsed-entity": { - source: "iana" - }, - "text/yaml": { - compressible: true, - extensions: ["yaml", "yml"] - }, - "video/1d-interleaved-parityfec": { - source: "iana" - }, - "video/3gpp": { - source: "iana", - extensions: ["3gp", "3gpp"] - }, - "video/3gpp-tt": { - source: "iana" - }, - "video/3gpp2": { - source: "iana", - extensions: ["3g2"] - }, - "video/av1": { - source: "iana" - }, - "video/bmpeg": { - source: "iana" - }, - "video/bt656": { - source: "iana" - }, - "video/celb": { - source: "iana" - }, - "video/dv": { - source: "iana" - }, - "video/encaprtp": { - source: "iana" - }, - "video/evc": { - source: "iana" - }, - "video/ffv1": { - source: "iana" - }, - "video/flexfec": { - source: "iana" - }, - "video/h261": { - source: "iana", - extensions: ["h261"] - }, - "video/h263": { - source: "iana", - extensions: ["h263"] - }, - "video/h263-1998": { - source: "iana" - }, - "video/h263-2000": { - source: "iana" - }, - "video/h264": { - source: "iana", - extensions: ["h264"] - }, - "video/h264-rcdo": { - source: "iana" - }, - "video/h264-svc": { - source: "iana" - }, - "video/h265": { - source: "iana" - }, - "video/h266": { - source: "iana" - }, - "video/iso.segment": { - source: "iana", - extensions: ["m4s"] - }, - "video/jpeg": { - source: "iana", - extensions: ["jpgv"] - }, - "video/jpeg2000": { - source: "iana" - }, - "video/jpm": { - source: "apache", - extensions: ["jpm", "jpgm"] - }, - "video/jxsv": { - source: "iana" - }, - "video/lottie+json": { - source: "iana", - compressible: true - }, - "video/matroska": { - source: "iana" - }, - "video/matroska-3d": { - source: "iana" - }, - "video/mj2": { - source: "iana", - extensions: ["mj2", "mjp2"] - }, - "video/mp1s": { - source: "iana" - }, - "video/mp2p": { - source: "iana" - }, - "video/mp2t": { - source: "iana", - extensions: ["ts", "m2t", "m2ts", "mts"] - }, - "video/mp4": { - source: "iana", - compressible: false, - extensions: ["mp4", "mp4v", "mpg4"] - }, - "video/mp4v-es": { - source: "iana" - }, - "video/mpeg": { - source: "iana", - compressible: false, - extensions: ["mpeg", "mpg", "mpe", "m1v", "m2v"] - }, - "video/mpeg4-generic": { - source: "iana" - }, - "video/mpv": { - source: "iana" - }, - "video/nv": { - source: "iana" - }, - "video/ogg": { - source: "iana", - compressible: false, - extensions: ["ogv"] - }, - "video/parityfec": { - source: "iana" - }, - "video/pointer": { - source: "iana" - }, - "video/quicktime": { - source: "iana", - compressible: false, - extensions: ["qt", "mov"] - }, - "video/raptorfec": { - source: "iana" - }, - "video/raw": { - source: "iana" - }, - "video/rtp-enc-aescm128": { - source: "iana" - }, - "video/rtploopback": { - source: "iana" - }, - "video/rtx": { - source: "iana" - }, - "video/scip": { - source: "iana" - }, - "video/smpte291": { - source: "iana" - }, - "video/smpte292m": { - source: "iana" - }, - "video/ulpfec": { - source: "iana" - }, - "video/vc1": { - source: "iana" - }, - "video/vc2": { - source: "iana" - }, - "video/vnd.cctv": { - source: "iana" - }, - "video/vnd.dece.hd": { - source: "iana", - extensions: ["uvh", "uvvh"] - }, - "video/vnd.dece.mobile": { - source: "iana", - extensions: ["uvm", "uvvm"] - }, - "video/vnd.dece.mp4": { - source: "iana" - }, - "video/vnd.dece.pd": { - source: "iana", - extensions: ["uvp", "uvvp"] - }, - "video/vnd.dece.sd": { - source: "iana", - extensions: ["uvs", "uvvs"] - }, - "video/vnd.dece.video": { - source: "iana", - extensions: ["uvv", "uvvv"] - }, - "video/vnd.directv.mpeg": { - source: "iana" - }, - "video/vnd.directv.mpeg-tts": { - source: "iana" - }, - "video/vnd.dlna.mpeg-tts": { - source: "iana" - }, - "video/vnd.dvb.file": { - source: "iana", - extensions: ["dvb"] - }, - "video/vnd.fvt": { - source: "iana", - extensions: ["fvt"] - }, - "video/vnd.hns.video": { - source: "iana" - }, - "video/vnd.iptvforum.1dparityfec-1010": { - source: "iana" - }, - "video/vnd.iptvforum.1dparityfec-2005": { - source: "iana" - }, - "video/vnd.iptvforum.2dparityfec-1010": { - source: "iana" - }, - "video/vnd.iptvforum.2dparityfec-2005": { - source: "iana" - }, - "video/vnd.iptvforum.ttsavc": { - source: "iana" - }, - "video/vnd.iptvforum.ttsmpeg2": { - source: "iana" - }, - "video/vnd.motorola.video": { - source: "iana" - }, - "video/vnd.motorola.videop": { - source: "iana" - }, - "video/vnd.mpegurl": { - source: "iana", - extensions: ["mxu", "m4u"] - }, - "video/vnd.ms-playready.media.pyv": { - source: "iana", - extensions: ["pyv"] - }, - "video/vnd.nokia.interleaved-multimedia": { - source: "iana" - }, - "video/vnd.nokia.mp4vr": { - source: "iana" - }, - "video/vnd.nokia.videovoip": { - source: "iana" - }, - "video/vnd.objectvideo": { - source: "iana" - }, - "video/vnd.planar": { - source: "iana" - }, - "video/vnd.radgamettools.bink": { - source: "iana" - }, - "video/vnd.radgamettools.smacker": { - source: "apache" - }, - "video/vnd.sealed.mpeg1": { - source: "iana" - }, - "video/vnd.sealed.mpeg4": { - source: "iana" - }, - "video/vnd.sealed.swf": { - source: "iana" - }, - "video/vnd.sealedmedia.softseal.mov": { - source: "iana" - }, - "video/vnd.uvvu.mp4": { - source: "iana", - extensions: ["uvu", "uvvu"] - }, - "video/vnd.vivo": { - source: "iana", - extensions: ["viv"] - }, - "video/vnd.youtube.yt": { - source: "iana" - }, - "video/vp8": { - source: "iana" - }, - "video/vp9": { - source: "iana" - }, - "video/webm": { - source: "apache", - compressible: false, - extensions: ["webm"] - }, - "video/x-f4v": { - source: "apache", - extensions: ["f4v"] - }, - "video/x-fli": { - source: "apache", - extensions: ["fli"] - }, - "video/x-flv": { - source: "apache", - compressible: false, - extensions: ["flv"] - }, - "video/x-m4v": { - source: "apache", - extensions: ["m4v"] - }, - "video/x-matroska": { - source: "apache", - compressible: false, - extensions: ["mkv", "mk3d", "mks"] - }, - "video/x-mng": { - source: "apache", - extensions: ["mng"] - }, - "video/x-ms-asf": { - source: "apache", - extensions: ["asf", "asx"] - }, - "video/x-ms-vob": { - source: "apache", - extensions: ["vob"] - }, - "video/x-ms-wm": { - source: "apache", - extensions: ["wm"] - }, - "video/x-ms-wmv": { - source: "apache", - compressible: false, - extensions: ["wmv"] - }, - "video/x-ms-wmx": { - source: "apache", - extensions: ["wmx"] - }, - "video/x-ms-wvx": { - source: "apache", - extensions: ["wvx"] - }, - "video/x-msvideo": { - source: "apache", - extensions: ["avi"] - }, - "video/x-sgi-movie": { - source: "apache", - extensions: ["movie"] - }, - "video/x-smv": { - source: "apache", - extensions: ["smv"] - }, - "x-conference/x-cooltalk": { - source: "apache", - extensions: ["ice"] - }, - "x-shader/x-fragment": { - compressible: true - }, - "x-shader/x-vertex": { - compressible: true - } - }; - } -}); - -// node_modules/.pnpm/mime-db@1.54.0/node_modules/mime-db/index.js -var require_mime_db = __commonJS({ - "node_modules/.pnpm/mime-db@1.54.0/node_modules/mime-db/index.js"(exports, module) { - module.exports = require_db(); - } -}); - -// node_modules/.pnpm/mime-types@3.0.2/node_modules/mime-types/mimeScore.js -var require_mimeScore = __commonJS({ - "node_modules/.pnpm/mime-types@3.0.2/node_modules/mime-types/mimeScore.js"(exports, module) { - var FACET_SCORES = { - "prs.": 100, - "x-": 200, - "x.": 300, - "vnd.": 400, - default: 900 - }; - var SOURCE_SCORES = { - nginx: 10, - apache: 20, - iana: 40, - default: 30 - // definitions added by `jshttp/mime-db` project? - }; - var TYPE_SCORES = { - // prefer application/xml over text/xml - // prefer application/rtf over text/rtf - application: 1, - // prefer font/woff over application/font-woff - font: 2, - // prefer video/mp4 over audio/mp4 over application/mp4 - // See https://www.rfc-editor.org/rfc/rfc4337.html#section-2 - audio: 2, - video: 3, - default: 0 - }; - module.exports = function mimeScore(mimeType, source = "default") { - if (mimeType === "application/octet-stream") { - return 0; - } - const [type, subtype] = mimeType.split("/"); - const facet = subtype.replace(/(\.|x-).*/, "$1"); - const facetScore = FACET_SCORES[facet] || FACET_SCORES.default; - const sourceScore = SOURCE_SCORES[source] || SOURCE_SCORES.default; - const typeScore = TYPE_SCORES[type] || TYPE_SCORES.default; - const lengthScore = 1 - mimeType.length / 100; - return facetScore + sourceScore + typeScore + lengthScore; - }; - } -}); - -// node_modules/.pnpm/mime-types@3.0.2/node_modules/mime-types/index.js -var require_mime_types = __commonJS({ - "node_modules/.pnpm/mime-types@3.0.2/node_modules/mime-types/index.js"(exports) { - "use strict"; - var db = require_mime_db(); - var extname2 = __require("path").extname; - var mimeScore = require_mimeScore(); - var EXTRACT_TYPE_REGEXP = /^\s*([^;\s]*)(?:;|\s|$)/; - var TEXT_TYPE_REGEXP = /^text\//i; - exports.charset = charset; - exports.charsets = { lookup: charset }; - exports.contentType = contentType; - exports.extension = extension2; - exports.extensions = /* @__PURE__ */ Object.create(null); - exports.lookup = lookup; - exports.types = /* @__PURE__ */ Object.create(null); - exports._extensionConflicts = []; - populateMaps(exports.extensions, exports.types); - function charset(type) { - if (!type || typeof type !== "string") { - return false; - } - var match = EXTRACT_TYPE_REGEXP.exec(type); - var mime = match && db[match[1].toLowerCase()]; - if (mime && mime.charset) { - return mime.charset; - } - if (match && TEXT_TYPE_REGEXP.test(match[1])) { - return "UTF-8"; - } - return false; - } - function contentType(str) { - if (!str || typeof str !== "string") { - return false; - } - var mime = str.indexOf("/") === -1 ? exports.lookup(str) : str; - if (!mime) { - return false; - } - if (mime.indexOf("charset") === -1) { - var charset2 = exports.charset(mime); - if (charset2) mime += "; charset=" + charset2.toLowerCase(); - } - return mime; - } - function extension2(type) { - if (!type || typeof type !== "string") { - return false; - } - var match = EXTRACT_TYPE_REGEXP.exec(type); - var exts = match && exports.extensions[match[1].toLowerCase()]; - if (!exts || !exts.length) { - return false; - } - return exts[0]; - } - function lookup(path53) { - if (!path53 || typeof path53 !== "string") { - return false; - } - var extension3 = extname2("x." + path53).toLowerCase().slice(1); - if (!extension3) { - return false; - } - return exports.types[extension3] || false; - } - function populateMaps(extensions, types2) { - Object.keys(db).forEach(function forEachMimeType(type) { - var mime = db[type]; - var exts = mime.extensions; - if (!exts || !exts.length) { - return; - } - extensions[type] = exts; - for (var i5 = 0; i5 < exts.length; i5++) { - var extension3 = exts[i5]; - types2[extension3] = _preferredType(extension3, types2[extension3], type); - const legacyType = _preferredTypeLegacy( - extension3, - types2[extension3], - type - ); - if (legacyType !== types2[extension3]) { - exports._extensionConflicts.push([extension3, legacyType, types2[extension3]]); - } - } - }); - } - function _preferredType(ext, type0, type1) { - var score0 = type0 ? mimeScore(type0, db[type0].source) : 0; - var score1 = type1 ? mimeScore(type1, db[type1].source) : 0; - return score0 > score1 ? type0 : type1; - } - function _preferredTypeLegacy(ext, type0, type1) { - var SOURCE_RANK = ["nginx", "apache", void 0, "iana"]; - var score0 = type0 ? SOURCE_RANK.indexOf(db[type0].source) : 0; - var score1 = type1 ? SOURCE_RANK.indexOf(db[type1].source) : 0; - if (exports.types[extension2] !== "application/octet-stream" && (score0 > score1 || score0 === score1 && exports.types[extension2]?.slice(0, 12) === "application/")) { - return type0; - } - return score0 > score1 ? type0 : type1; - } - } -}); - -// node_modules/.pnpm/media-typer@1.1.0/node_modules/media-typer/index.js -var require_media_typer = __commonJS({ - "node_modules/.pnpm/media-typer@1.1.0/node_modules/media-typer/index.js"(exports) { - "use strict"; - var SUBTYPE_NAME_REGEXP = /^[A-Za-z0-9][A-Za-z0-9!#$&^_.-]{0,126}$/; - var TYPE_NAME_REGEXP = /^[A-Za-z0-9][A-Za-z0-9!#$&^_-]{0,126}$/; - var TYPE_REGEXP = /^ *([A-Za-z0-9][A-Za-z0-9!#$&^_-]{0,126})\/([A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}) *$/; - exports.format = format2; - exports.parse = parse5; - exports.test = test; - function format2(obj) { - if (!obj || typeof obj !== "object") { - throw new TypeError("argument obj is required"); - } - var subtype = obj.subtype; - var suffix = obj.suffix; - var type = obj.type; - if (!type || !TYPE_NAME_REGEXP.test(type)) { - throw new TypeError("invalid type"); - } - if (!subtype || !SUBTYPE_NAME_REGEXP.test(subtype)) { - throw new TypeError("invalid subtype"); - } - var string4 = type + "/" + subtype; - if (suffix) { - if (!TYPE_NAME_REGEXP.test(suffix)) { - throw new TypeError("invalid suffix"); - } - string4 += "+" + suffix; - } - return string4; - } - function test(string4) { - if (!string4) { - throw new TypeError("argument string is required"); - } - if (typeof string4 !== "string") { - throw new TypeError("argument string is required to be a string"); - } - return TYPE_REGEXP.test(string4.toLowerCase()); - } - function parse5(string4) { - if (!string4) { - throw new TypeError("argument string is required"); - } - if (typeof string4 !== "string") { - throw new TypeError("argument string is required to be a string"); - } - var match = TYPE_REGEXP.exec(string4.toLowerCase()); - if (!match) { - throw new TypeError("invalid media type"); - } - var type = match[1]; - var subtype = match[2]; - var suffix; - var index2 = subtype.lastIndexOf("+"); - if (index2 !== -1) { - suffix = subtype.substr(index2 + 1); - subtype = subtype.substr(0, index2); - } - return new MediaType(type, subtype, suffix); - } - function MediaType(type, subtype, suffix) { - this.type = type; - this.subtype = subtype; - this.suffix = suffix; - } - } -}); - -// node_modules/.pnpm/type-is@2.0.1/node_modules/type-is/index.js -var require_type_is = __commonJS({ - "node_modules/.pnpm/type-is@2.0.1/node_modules/type-is/index.js"(exports, module) { - "use strict"; - var contentType = require_content_type(); - var mime = require_mime_types(); - var typer = require_media_typer(); - module.exports = typeofrequest; - module.exports.is = typeis; - module.exports.hasBody = hasbody; - module.exports.normalize = normalize2; - module.exports.match = mimeMatch; - function typeis(value, types_) { - var i5; - var types2 = types_; - var val = tryNormalizeType(value); - if (!val) { - return false; - } - if (types2 && !Array.isArray(types2)) { - types2 = new Array(arguments.length - 1); - for (i5 = 0; i5 < types2.length; i5++) { - types2[i5] = arguments[i5 + 1]; - } - } - if (!types2 || !types2.length) { - return val; - } - var type; - for (i5 = 0; i5 < types2.length; i5++) { - if (mimeMatch(normalize2(type = types2[i5]), val)) { - return type[0] === "+" || type.indexOf("*") !== -1 ? val : type; - } - } - return false; - } - function hasbody(req) { - return req.headers["transfer-encoding"] !== void 0 || !isNaN(req.headers["content-length"]); - } - function typeofrequest(req, types_) { - if (!hasbody(req)) return null; - var types2 = arguments.length > 2 ? Array.prototype.slice.call(arguments, 1) : types_; - var value = req.headers["content-type"]; - return typeis(value, types2); - } - function normalize2(type) { - if (typeof type !== "string") { - return false; - } - switch (type) { - case "urlencoded": - return "application/x-www-form-urlencoded"; - case "multipart": - return "multipart/*"; - } - if (type[0] === "+") { - return "*/*" + type; - } - return type.indexOf("/") === -1 ? mime.lookup(type) : type; - } - function mimeMatch(expected, actual) { - if (expected === false) { - return false; - } - var actualParts = actual.split("/"); - var expectedParts = expected.split("/"); - if (actualParts.length !== 2 || expectedParts.length !== 2) { - return false; - } - if (expectedParts[0] !== "*" && expectedParts[0] !== actualParts[0]) { - return false; - } - if (expectedParts[1].slice(0, 2) === "*+") { - return expectedParts[1].length <= actualParts[1].length + 1 && expectedParts[1].slice(1) === actualParts[1].slice(1 - expectedParts[1].length); - } - if (expectedParts[1] !== "*" && expectedParts[1] !== actualParts[1]) { - return false; - } - return true; - } - function normalizeType(value) { - var type = contentType.parse(value).type; - return typer.test(type) ? type : null; - } - function tryNormalizeType(value) { - try { - return value ? normalizeType(value) : null; - } catch (err) { - return null; - } - } - } -}); - -// node_modules/.pnpm/body-parser@2.2.2/node_modules/body-parser/lib/utils.js -var require_utils = __commonJS({ - "node_modules/.pnpm/body-parser@2.2.2/node_modules/body-parser/lib/utils.js"(exports, module) { - "use strict"; - var bytes = require_bytes(); - var contentType = require_content_type(); - var typeis = require_type_is(); - module.exports = { - getCharset, - normalizeOptions, - passthrough - }; - function getCharset(req) { - try { - return (contentType.parse(req).parameters.charset || "").toLowerCase(); - } catch { - return void 0; - } - } - function typeChecker(type) { - return function checkType(req) { - return Boolean(typeis(req, type)); - }; - } - function normalizeOptions(options, defaultType) { - if (!defaultType) { - throw new TypeError("defaultType must be provided"); - } - var inflate = options?.inflate !== false; - var limit = typeof options?.limit !== "number" ? bytes.parse(options?.limit || "100kb") : options?.limit; - var type = options?.type || defaultType; - var verify2 = options?.verify || false; - var defaultCharset = options?.defaultCharset || "utf-8"; - if (verify2 !== false && typeof verify2 !== "function") { - throw new TypeError("option verify must be function"); - } - var shouldParse = typeof type !== "function" ? typeChecker(type) : type; - return { - inflate, - limit, - verify: verify2, - defaultCharset, - shouldParse - }; - } - function passthrough(value) { - return value; - } - } -}); - -// node_modules/.pnpm/body-parser@2.2.2/node_modules/body-parser/lib/read.js -var require_read = __commonJS({ - "node_modules/.pnpm/body-parser@2.2.2/node_modules/body-parser/lib/read.js"(exports, module) { - "use strict"; - var createError = require_http_errors(); - var getBody3 = require_raw_body(); - var iconv = require_lib(); - var onFinished = require_on_finished(); - var zlib = __require("node:zlib"); - var hasBody = require_type_is().hasBody; - var { getCharset } = require_utils(); - module.exports = read; - function read(req, res, next, parse5, debug, options) { - if (onFinished.isFinished(req)) { - debug("body already parsed"); - next(); - return; - } - if (!("body" in req)) { - req.body = void 0; - } - if (!hasBody(req)) { - debug("skip empty body"); - next(); - return; - } - debug("content-type %j", req.headers["content-type"]); - if (!options.shouldParse(req)) { - debug("skip parsing"); - next(); - return; - } - var encoding = null; - if (options?.skipCharset !== true) { - encoding = getCharset(req) || options.defaultCharset; - if (!!options?.isValidCharset && !options.isValidCharset(encoding)) { - debug("invalid charset"); - next(createError(415, 'unsupported charset "' + encoding.toUpperCase() + '"', { - charset: encoding, - type: "charset.unsupported" - })); - return; - } - } - var length; - var opts = options; - var stream; - var verify2 = opts.verify; - try { - stream = contentstream(req, debug, opts.inflate); - length = stream.length; - stream.length = void 0; - } catch (err) { - return next(err); - } - opts.length = length; - opts.encoding = verify2 ? null : encoding; - if (opts.encoding === null && encoding !== null && !iconv.encodingExists(encoding)) { - return next(createError(415, 'unsupported charset "' + encoding.toUpperCase() + '"', { - charset: encoding.toLowerCase(), - type: "charset.unsupported" - })); - } - debug("read body"); - getBody3(stream, opts, function(error50, body) { - if (error50) { - var _error; - if (error50.type === "encoding.unsupported") { - _error = createError(415, 'unsupported charset "' + encoding.toUpperCase() + '"', { - charset: encoding.toLowerCase(), - type: "charset.unsupported" - }); - } else { - _error = createError(400, error50); - } - if (stream !== req) { - req.unpipe(); - stream.destroy(); - } - dump(req, function onfinished() { - next(createError(400, _error)); - }); - return; - } - if (verify2) { - try { - debug("verify body"); - verify2(req, res, body, encoding); - } catch (err) { - next(createError(403, err, { - body, - type: err.type || "entity.verify.failed" - })); - return; - } - } - var str = body; - try { - debug("parse body"); - str = typeof body !== "string" && encoding !== null ? iconv.decode(body, encoding) : body; - req.body = parse5(str, encoding); - } catch (err) { - next(createError(400, err, { - body: str, - type: err.type || "entity.parse.failed" - })); - return; - } - next(); - }); - } - function contentstream(req, debug, inflate) { - var encoding = (req.headers["content-encoding"] || "identity").toLowerCase(); - var length = req.headers["content-length"]; - debug('content-encoding "%s"', encoding); - if (inflate === false && encoding !== "identity") { - throw createError(415, "content encoding unsupported", { - encoding, - type: "encoding.unsupported" - }); - } - if (encoding === "identity") { - req.length = length; - return req; - } - var stream = createDecompressionStream(encoding, debug); - req.pipe(stream); - return stream; - } - function createDecompressionStream(encoding, debug) { - switch (encoding) { - case "deflate": - debug("inflate body"); - return zlib.createInflate(); - case "gzip": - debug("gunzip body"); - return zlib.createGunzip(); - case "br": - debug("brotli decompress body"); - return zlib.createBrotliDecompress(); - default: - throw createError(415, 'unsupported content encoding "' + encoding + '"', { - encoding, - type: "encoding.unsupported" - }); - } - } - function dump(req, callback) { - if (onFinished.isFinished(req)) { - callback(null); - } else { - onFinished(req, callback); - req.resume(); - } - } - } -}); - -// node_modules/.pnpm/body-parser@2.2.2/node_modules/body-parser/lib/types/json.js -var require_json = __commonJS({ - "node_modules/.pnpm/body-parser@2.2.2/node_modules/body-parser/lib/types/json.js"(exports, module) { - "use strict"; - var debug = require_src()("body-parser:json"); - var read = require_read(); - var { normalizeOptions } = require_utils(); - module.exports = json3; - var FIRST_CHAR_REGEXP = /^[\x20\x09\x0a\x0d]*([^\x20\x09\x0a\x0d])/; - var JSON_SYNTAX_CHAR = "#"; - var JSON_SYNTAX_REGEXP = /#+/g; - function json3(options) { - const normalizedOptions = normalizeOptions(options, "application/json"); - var reviver = options?.reviver; - var strict = options?.strict !== false; - function parse5(body) { - if (body.length === 0) { - return {}; - } - if (strict) { - var first = firstchar(body); - if (first !== "{" && first !== "[") { - debug("strict violation"); - throw createStrictSyntaxError(body, first); - } - } - try { - debug("parse json"); - return JSON.parse(body, reviver); - } catch (e5) { - throw normalizeJsonSyntaxError(e5, { - message: e5.message, - stack: e5.stack - }); - } - } - const readOptions = { - ...normalizedOptions, - // assert charset per RFC 7159 sec 8.1 - isValidCharset: (charset) => charset.slice(0, 4) === "utf-" - }; - return function jsonParser(req, res, next) { - read(req, res, next, parse5, debug, readOptions); - }; - } - function createStrictSyntaxError(str, char2) { - var index2 = str.indexOf(char2); - var partial2 = ""; - if (index2 !== -1) { - partial2 = str.substring(0, index2) + JSON_SYNTAX_CHAR.repeat(str.length - index2); - } - try { - JSON.parse(partial2); - throw new SyntaxError("strict violation"); - } catch (e5) { - return normalizeJsonSyntaxError(e5, { - message: e5.message.replace(JSON_SYNTAX_REGEXP, function(placeholder) { - return str.substring(index2, index2 + placeholder.length); - }), - stack: e5.stack - }); - } - } - function firstchar(str) { - var match = FIRST_CHAR_REGEXP.exec(str); - return match ? match[1] : void 0; - } - function normalizeJsonSyntaxError(error50, obj) { - var keys = Object.getOwnPropertyNames(error50); - for (var i5 = 0; i5 < keys.length; i5++) { - var key = keys[i5]; - if (key !== "stack" && key !== "message") { - delete error50[key]; - } - } - error50.stack = obj.stack.replace(error50.message, obj.message); - error50.message = obj.message; - return error50; - } - } -}); - -// node_modules/.pnpm/body-parser@2.2.2/node_modules/body-parser/lib/types/raw.js -var require_raw = __commonJS({ - "node_modules/.pnpm/body-parser@2.2.2/node_modules/body-parser/lib/types/raw.js"(exports, module) { - "use strict"; - var debug = require_src()("body-parser:raw"); - var read = require_read(); - var { normalizeOptions, passthrough } = require_utils(); - module.exports = raw; - function raw(options) { - const normalizedOptions = normalizeOptions(options, "application/octet-stream"); - const readOptions = { - ...normalizedOptions, - // Skip charset validation and parse the body as is - skipCharset: true - }; - return function rawParser(req, res, next) { - read(req, res, next, passthrough, debug, readOptions); - }; - } - } -}); - -// node_modules/.pnpm/body-parser@2.2.2/node_modules/body-parser/lib/types/text.js -var require_text = __commonJS({ - "node_modules/.pnpm/body-parser@2.2.2/node_modules/body-parser/lib/types/text.js"(exports, module) { - "use strict"; - var debug = require_src()("body-parser:text"); - var read = require_read(); - var { normalizeOptions, passthrough } = require_utils(); - module.exports = text3; - function text3(options) { - const normalizedOptions = normalizeOptions(options, "text/plain"); - return function textParser(req, res, next) { - read(req, res, next, passthrough, debug, normalizedOptions); - }; - } - } -}); - -// node_modules/.pnpm/es-errors@1.3.0/node_modules/es-errors/type.js -var require_type = __commonJS({ - "node_modules/.pnpm/es-errors@1.3.0/node_modules/es-errors/type.js"(exports, module) { - "use strict"; - module.exports = TypeError; - } -}); - -// node_modules/.pnpm/object-inspect@1.13.4/node_modules/object-inspect/util.inspect.js -var require_util_inspect = __commonJS({ - "node_modules/.pnpm/object-inspect@1.13.4/node_modules/object-inspect/util.inspect.js"(exports, module) { - module.exports = __require("util").inspect; - } -}); - -// node_modules/.pnpm/object-inspect@1.13.4/node_modules/object-inspect/index.js -var require_object_inspect = __commonJS({ - "node_modules/.pnpm/object-inspect@1.13.4/node_modules/object-inspect/index.js"(exports, module) { - var hasMap = typeof Map === "function" && Map.prototype; - var mapSizeDescriptor = Object.getOwnPropertyDescriptor && hasMap ? Object.getOwnPropertyDescriptor(Map.prototype, "size") : null; - var mapSize = hasMap && mapSizeDescriptor && typeof mapSizeDescriptor.get === "function" ? mapSizeDescriptor.get : null; - var mapForEach = hasMap && Map.prototype.forEach; - var hasSet = typeof Set === "function" && Set.prototype; - var setSizeDescriptor = Object.getOwnPropertyDescriptor && hasSet ? Object.getOwnPropertyDescriptor(Set.prototype, "size") : null; - var setSize = hasSet && setSizeDescriptor && typeof setSizeDescriptor.get === "function" ? setSizeDescriptor.get : null; - var setForEach = hasSet && Set.prototype.forEach; - var hasWeakMap = typeof WeakMap === "function" && WeakMap.prototype; - var weakMapHas = hasWeakMap ? WeakMap.prototype.has : null; - var hasWeakSet = typeof WeakSet === "function" && WeakSet.prototype; - var weakSetHas = hasWeakSet ? WeakSet.prototype.has : null; - var hasWeakRef = typeof WeakRef === "function" && WeakRef.prototype; - var weakRefDeref = hasWeakRef ? WeakRef.prototype.deref : null; - var booleanValueOf = Boolean.prototype.valueOf; - var objectToString = Object.prototype.toString; - var functionToString = Function.prototype.toString; - var $match = String.prototype.match; - var $slice = String.prototype.slice; - var $replace = String.prototype.replace; - var $toUpperCase = String.prototype.toUpperCase; - var $toLowerCase = String.prototype.toLowerCase; - var $test = RegExp.prototype.test; - var $concat = Array.prototype.concat; - var $join = Array.prototype.join; - var $arrSlice = Array.prototype.slice; - var $floor = Math.floor; - var bigIntValueOf = typeof BigInt === "function" ? BigInt.prototype.valueOf : null; - var gOPS = Object.getOwnPropertySymbols; - var symToString = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? Symbol.prototype.toString : null; - var hasShammedSymbols = typeof Symbol === "function" && typeof Symbol.iterator === "object"; - var toStringTag = typeof Symbol === "function" && Symbol.toStringTag && (typeof Symbol.toStringTag === hasShammedSymbols ? "object" : "symbol") ? Symbol.toStringTag : null; - var isEnumerable = Object.prototype.propertyIsEnumerable; - var gPO = (typeof Reflect === "function" ? Reflect.getPrototypeOf : Object.getPrototypeOf) || ([].__proto__ === Array.prototype ? function(O) { - return O.__proto__; - } : null); - function addNumericSeparator(num, str) { - if (num === Infinity || num === -Infinity || num !== num || num && num > -1e3 && num < 1e3 || $test.call(/e/, str)) { - return str; - } - var sepRegex = /[0-9](?=(?:[0-9]{3})+(?![0-9]))/g; - if (typeof num === "number") { - var int2 = num < 0 ? -$floor(-num) : $floor(num); - if (int2 !== num) { - var intStr = String(int2); - var dec = $slice.call(str, intStr.length + 1); - return $replace.call(intStr, sepRegex, "$&_") + "." + $replace.call($replace.call(dec, /([0-9]{3})/g, "$&_"), /_$/, ""); - } - } - return $replace.call(str, sepRegex, "$&_"); - } - var utilInspect = require_util_inspect(); - var inspectCustom = utilInspect.custom; - var inspectSymbol = isSymbol(inspectCustom) ? inspectCustom : null; - var quotes = { - __proto__: null, - "double": '"', - single: "'" - }; - var quoteREs = { - __proto__: null, - "double": /(["\\])/g, - single: /(['\\])/g - }; - module.exports = function inspect_(obj, options, depth, seen) { - var opts = options || {}; - if (has(opts, "quoteStyle") && !has(quotes, opts.quoteStyle)) { - throw new TypeError('option "quoteStyle" must be "single" or "double"'); - } - if (has(opts, "maxStringLength") && (typeof opts.maxStringLength === "number" ? opts.maxStringLength < 0 && opts.maxStringLength !== Infinity : opts.maxStringLength !== null)) { - throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`'); - } - var customInspect = has(opts, "customInspect") ? opts.customInspect : true; - if (typeof customInspect !== "boolean" && customInspect !== "symbol") { - throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`"); - } - if (has(opts, "indent") && opts.indent !== null && opts.indent !== " " && !(parseInt(opts.indent, 10) === opts.indent && opts.indent > 0)) { - throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`'); - } - if (has(opts, "numericSeparator") && typeof opts.numericSeparator !== "boolean") { - throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`'); - } - var numericSeparator = opts.numericSeparator; - if (typeof obj === "undefined") { - return "undefined"; - } - if (obj === null) { - return "null"; - } - if (typeof obj === "boolean") { - return obj ? "true" : "false"; - } - if (typeof obj === "string") { - return inspectString(obj, opts); - } - if (typeof obj === "number") { - if (obj === 0) { - return Infinity / obj > 0 ? "0" : "-0"; - } - var str = String(obj); - return numericSeparator ? addNumericSeparator(obj, str) : str; - } - if (typeof obj === "bigint") { - var bigIntStr = String(obj) + "n"; - return numericSeparator ? addNumericSeparator(obj, bigIntStr) : bigIntStr; - } - var maxDepth = typeof opts.depth === "undefined" ? 5 : opts.depth; - if (typeof depth === "undefined") { - depth = 0; - } - if (depth >= maxDepth && maxDepth > 0 && typeof obj === "object") { - return isArray(obj) ? "[Array]" : "[Object]"; - } - var indent = getIndent(opts, depth); - if (typeof seen === "undefined") { - seen = []; - } else if (indexOf(seen, obj) >= 0) { - return "[Circular]"; - } - function inspect(value, from, noIndent) { - if (from) { - seen = $arrSlice.call(seen); - seen.push(from); - } - if (noIndent) { - var newOpts = { - depth: opts.depth - }; - if (has(opts, "quoteStyle")) { - newOpts.quoteStyle = opts.quoteStyle; - } - return inspect_(value, newOpts, depth + 1, seen); - } - return inspect_(value, opts, depth + 1, seen); - } - if (typeof obj === "function" && !isRegExp(obj)) { - var name = nameOf(obj); - var keys = arrObjKeys(obj, inspect); - return "[Function" + (name ? ": " + name : " (anonymous)") + "]" + (keys.length > 0 ? " { " + $join.call(keys, ", ") + " }" : ""); - } - if (isSymbol(obj)) { - var symString = hasShammedSymbols ? $replace.call(String(obj), /^(Symbol\(.*\))_[^)]*$/, "$1") : symToString.call(obj); - return typeof obj === "object" && !hasShammedSymbols ? markBoxed(symString) : symString; - } - if (isElement(obj)) { - var s5 = "<" + $toLowerCase.call(String(obj.nodeName)); - var attrs = obj.attributes || []; - for (var i5 = 0; i5 < attrs.length; i5++) { - s5 += " " + attrs[i5].name + "=" + wrapQuotes(quote(attrs[i5].value), "double", opts); - } - s5 += ">"; - if (obj.childNodes && obj.childNodes.length) { - s5 += "..."; - } - s5 += ""; - return s5; - } - if (isArray(obj)) { - if (obj.length === 0) { - return "[]"; - } - var xs = arrObjKeys(obj, inspect); - if (indent && !singleLineValues(xs)) { - return "[" + indentedJoin(xs, indent) + "]"; - } - return "[ " + $join.call(xs, ", ") + " ]"; - } - if (isError(obj)) { - var parts = arrObjKeys(obj, inspect); - if (!("cause" in Error.prototype) && "cause" in obj && !isEnumerable.call(obj, "cause")) { - return "{ [" + String(obj) + "] " + $join.call($concat.call("[cause]: " + inspect(obj.cause), parts), ", ") + " }"; - } - if (parts.length === 0) { - return "[" + String(obj) + "]"; - } - return "{ [" + String(obj) + "] " + $join.call(parts, ", ") + " }"; - } - if (typeof obj === "object" && customInspect) { - if (inspectSymbol && typeof obj[inspectSymbol] === "function" && utilInspect) { - return utilInspect(obj, { depth: maxDepth - depth }); - } else if (customInspect !== "symbol" && typeof obj.inspect === "function") { - return obj.inspect(); - } - } - if (isMap(obj)) { - var mapParts = []; - if (mapForEach) { - mapForEach.call(obj, function(value, key) { - mapParts.push(inspect(key, obj, true) + " => " + inspect(value, obj)); - }); - } - return collectionOf("Map", mapSize.call(obj), mapParts, indent); - } - if (isSet(obj)) { - var setParts = []; - if (setForEach) { - setForEach.call(obj, function(value) { - setParts.push(inspect(value, obj)); - }); - } - return collectionOf("Set", setSize.call(obj), setParts, indent); - } - if (isWeakMap(obj)) { - return weakCollectionOf("WeakMap"); - } - if (isWeakSet(obj)) { - return weakCollectionOf("WeakSet"); - } - if (isWeakRef(obj)) { - return weakCollectionOf("WeakRef"); - } - if (isNumber2(obj)) { - return markBoxed(inspect(Number(obj))); - } - if (isBigInt2(obj)) { - return markBoxed(inspect(bigIntValueOf.call(obj))); - } - if (isBoolean2(obj)) { - return markBoxed(booleanValueOf.call(obj)); - } - if (isString2(obj)) { - return markBoxed(inspect(String(obj))); - } - if (typeof window !== "undefined" && obj === window) { - return "{ [object Window] }"; - } - if (typeof globalThis !== "undefined" && obj === globalThis || typeof global !== "undefined" && obj === global) { - return "{ [object globalThis] }"; - } - if (!isDate2(obj) && !isRegExp(obj)) { - var ys = arrObjKeys(obj, inspect); - var isPlainObject7 = gPO ? gPO(obj) === Object.prototype : obj instanceof Object || obj.constructor === Object; - var protoTag = obj instanceof Object ? "" : "null prototype"; - var stringTag = !isPlainObject7 && toStringTag && Object(obj) === obj && toStringTag in obj ? $slice.call(toStr(obj), 8, -1) : protoTag ? "Object" : ""; - var constructorTag = isPlainObject7 || typeof obj.constructor !== "function" ? "" : obj.constructor.name ? obj.constructor.name + " " : ""; - var tag3 = constructorTag + (stringTag || protoTag ? "[" + $join.call($concat.call([], stringTag || [], protoTag || []), ": ") + "] " : ""); - if (ys.length === 0) { - return tag3 + "{}"; - } - if (indent) { - return tag3 + "{" + indentedJoin(ys, indent) + "}"; - } - return tag3 + "{ " + $join.call(ys, ", ") + " }"; - } - return String(obj); - }; - function wrapQuotes(s5, defaultStyle, opts) { - var style = opts.quoteStyle || defaultStyle; - var quoteChar = quotes[style]; - return quoteChar + s5 + quoteChar; - } - function quote(s5) { - return $replace.call(String(s5), /"/g, """); - } - function canTrustToString(obj) { - return !toStringTag || !(typeof obj === "object" && (toStringTag in obj || typeof obj[toStringTag] !== "undefined")); - } - function isArray(obj) { - return toStr(obj) === "[object Array]" && canTrustToString(obj); - } - function isDate2(obj) { - return toStr(obj) === "[object Date]" && canTrustToString(obj); - } - function isRegExp(obj) { - return toStr(obj) === "[object RegExp]" && canTrustToString(obj); - } - function isError(obj) { - return toStr(obj) === "[object Error]" && canTrustToString(obj); - } - function isString2(obj) { - return toStr(obj) === "[object String]" && canTrustToString(obj); - } - function isNumber2(obj) { - return toStr(obj) === "[object Number]" && canTrustToString(obj); - } - function isBoolean2(obj) { - return toStr(obj) === "[object Boolean]" && canTrustToString(obj); - } - function isSymbol(obj) { - if (hasShammedSymbols) { - return obj && typeof obj === "object" && obj instanceof Symbol; - } - if (typeof obj === "symbol") { - return true; - } - if (!obj || typeof obj !== "object" || !symToString) { - return false; - } - try { - symToString.call(obj); - return true; - } catch (e5) { - } - return false; - } - function isBigInt2(obj) { - if (!obj || typeof obj !== "object" || !bigIntValueOf) { - return false; - } - try { - bigIntValueOf.call(obj); - return true; - } catch (e5) { - } - return false; - } - var hasOwn = Object.prototype.hasOwnProperty || function(key) { - return key in this; - }; - function has(obj, key) { - return hasOwn.call(obj, key); - } - function toStr(obj) { - return objectToString.call(obj); - } - function nameOf(f5) { - if (f5.name) { - return f5.name; - } - var m5 = $match.call(functionToString.call(f5), /^function\s*([\w$]+)/); - if (m5) { - return m5[1]; - } - return null; - } - function indexOf(xs, x5) { - if (xs.indexOf) { - return xs.indexOf(x5); - } - for (var i5 = 0, l5 = xs.length; i5 < l5; i5++) { - if (xs[i5] === x5) { - return i5; - } - } - return -1; - } - function isMap(x5) { - if (!mapSize || !x5 || typeof x5 !== "object") { - return false; - } - try { - mapSize.call(x5); - try { - setSize.call(x5); - } catch (s5) { - return true; - } - return x5 instanceof Map; - } catch (e5) { - } - return false; - } - function isWeakMap(x5) { - if (!weakMapHas || !x5 || typeof x5 !== "object") { - return false; - } - try { - weakMapHas.call(x5, weakMapHas); - try { - weakSetHas.call(x5, weakSetHas); - } catch (s5) { - return true; - } - return x5 instanceof WeakMap; - } catch (e5) { - } - return false; - } - function isWeakRef(x5) { - if (!weakRefDeref || !x5 || typeof x5 !== "object") { - return false; - } - try { - weakRefDeref.call(x5); - return true; - } catch (e5) { - } - return false; - } - function isSet(x5) { - if (!setSize || !x5 || typeof x5 !== "object") { - return false; - } - try { - setSize.call(x5); - try { - mapSize.call(x5); - } catch (m5) { - return true; - } - return x5 instanceof Set; - } catch (e5) { - } - return false; - } - function isWeakSet(x5) { - if (!weakSetHas || !x5 || typeof x5 !== "object") { - return false; - } - try { - weakSetHas.call(x5, weakSetHas); - try { - weakMapHas.call(x5, weakMapHas); - } catch (s5) { - return true; - } - return x5 instanceof WeakSet; - } catch (e5) { - } - return false; - } - function isElement(x5) { - if (!x5 || typeof x5 !== "object") { - return false; - } - if (typeof HTMLElement !== "undefined" && x5 instanceof HTMLElement) { - return true; - } - return typeof x5.nodeName === "string" && typeof x5.getAttribute === "function"; - } - function inspectString(str, opts) { - if (str.length > opts.maxStringLength) { - var remaining = str.length - opts.maxStringLength; - var trailer = "... " + remaining + " more character" + (remaining > 1 ? "s" : ""); - return inspectString($slice.call(str, 0, opts.maxStringLength), opts) + trailer; - } - var quoteRE = quoteREs[opts.quoteStyle || "single"]; - quoteRE.lastIndex = 0; - var s5 = $replace.call($replace.call(str, quoteRE, "\\$1"), /[\x00-\x1f]/g, lowbyte); - return wrapQuotes(s5, "single", opts); - } - function lowbyte(c5) { - var n5 = c5.charCodeAt(0); - var x5 = { - 8: "b", - 9: "t", - 10: "n", - 12: "f", - 13: "r" - }[n5]; - if (x5) { - return "\\" + x5; - } - return "\\x" + (n5 < 16 ? "0" : "") + $toUpperCase.call(n5.toString(16)); - } - function markBoxed(str) { - return "Object(" + str + ")"; - } - function weakCollectionOf(type) { - return type + " { ? }"; - } - function collectionOf(type, size2, entries2, indent) { - var joinedEntries = indent ? indentedJoin(entries2, indent) : $join.call(entries2, ", "); - return type + " (" + size2 + ") {" + joinedEntries + "}"; - } - function singleLineValues(xs) { - for (var i5 = 0; i5 < xs.length; i5++) { - if (indexOf(xs[i5], "\n") >= 0) { - return false; - } - } - return true; - } - function getIndent(opts, depth) { - var baseIndent; - if (opts.indent === " ") { - baseIndent = " "; - } else if (typeof opts.indent === "number" && opts.indent > 0) { - baseIndent = $join.call(Array(opts.indent + 1), " "); - } else { - return null; - } - return { - base: baseIndent, - prev: $join.call(Array(depth + 1), baseIndent) - }; - } - function indentedJoin(xs, indent) { - if (xs.length === 0) { - return ""; - } - var lineJoiner = "\n" + indent.prev + indent.base; - return lineJoiner + $join.call(xs, "," + lineJoiner) + "\n" + indent.prev; - } - function arrObjKeys(obj, inspect) { - var isArr = isArray(obj); - var xs = []; - if (isArr) { - xs.length = obj.length; - for (var i5 = 0; i5 < obj.length; i5++) { - xs[i5] = has(obj, i5) ? inspect(obj[i5], obj) : ""; - } - } - var syms = typeof gOPS === "function" ? gOPS(obj) : []; - var symMap; - if (hasShammedSymbols) { - symMap = {}; - for (var k5 = 0; k5 < syms.length; k5++) { - symMap["$" + syms[k5]] = syms[k5]; - } - } - for (var key in obj) { - if (!has(obj, key)) { - continue; - } - if (isArr && String(Number(key)) === key && key < obj.length) { - continue; - } - if (hasShammedSymbols && symMap["$" + key] instanceof Symbol) { - continue; - } else if ($test.call(/[^\w$]/, key)) { - xs.push(inspect(key, obj) + ": " + inspect(obj[key], obj)); - } else { - xs.push(key + ": " + inspect(obj[key], obj)); - } - } - if (typeof gOPS === "function") { - for (var j5 = 0; j5 < syms.length; j5++) { - if (isEnumerable.call(obj, syms[j5])) { - xs.push("[" + inspect(syms[j5]) + "]: " + inspect(obj[syms[j5]], obj)); - } - } - } - return xs; - } - } -}); - -// node_modules/.pnpm/side-channel-list@1.0.1/node_modules/side-channel-list/index.js -var require_side_channel_list = __commonJS({ - "node_modules/.pnpm/side-channel-list@1.0.1/node_modules/side-channel-list/index.js"(exports, module) { - "use strict"; - var inspect = require_object_inspect(); - var $TypeError = require_type(); - var listGetNode = function(list2, key, isDelete) { - var prev = list2; - var curr; - for (; (curr = prev.next) != null; prev = curr) { - if (curr.key === key) { - prev.next = curr.next; - if (!isDelete) { - curr.next = /** @type {NonNullable} */ - list2.next; - list2.next = curr; - } - return curr; - } - } - }; - var listGet = function(objects, key) { - if (!objects) { - return void 0; - } - var node = listGetNode(objects, key); - return node && node.value; - }; - var listSet = function(objects, key, value) { - var node = listGetNode(objects, key); - if (node) { - node.value = value; - } else { - objects.next = /** @type {import('./list.d.ts').ListNode} */ - { - // eslint-disable-line no-param-reassign, no-extra-parens - key, - next: objects.next, - value - }; - } - }; - var listHas = function(objects, key) { - if (!objects) { - return false; - } - return !!listGetNode(objects, key); - }; - var listDelete = function(objects, key) { - if (objects) { - return listGetNode(objects, key, true); - } - }; - module.exports = function getSideChannelList() { - var $o; - var channel = { - assert: function(key) { - if (!channel.has(key)) { - throw new $TypeError("Side channel does not contain " + inspect(key)); - } - }, - "delete": function(key) { - var deletedNode = listDelete($o, key); - if (deletedNode && $o && !$o.next) { - $o = void 0; - } - return !!deletedNode; - }, - get: function(key) { - return listGet($o, key); - }, - has: function(key) { - return listHas($o, key); - }, - set: function(key, value) { - if (!$o) { - $o = { - next: void 0 - }; - } - listSet( - /** @type {NonNullable} */ - $o, - key, - value - ); - } - }; - return channel; - }; - } -}); - -// node_modules/.pnpm/es-object-atoms@1.1.1/node_modules/es-object-atoms/index.js -var require_es_object_atoms = __commonJS({ - "node_modules/.pnpm/es-object-atoms@1.1.1/node_modules/es-object-atoms/index.js"(exports, module) { - "use strict"; - module.exports = Object; - } -}); - -// node_modules/.pnpm/es-errors@1.3.0/node_modules/es-errors/index.js -var require_es_errors = __commonJS({ - "node_modules/.pnpm/es-errors@1.3.0/node_modules/es-errors/index.js"(exports, module) { - "use strict"; - module.exports = Error; - } -}); - -// node_modules/.pnpm/es-errors@1.3.0/node_modules/es-errors/eval.js -var require_eval = __commonJS({ - "node_modules/.pnpm/es-errors@1.3.0/node_modules/es-errors/eval.js"(exports, module) { - "use strict"; - module.exports = EvalError; - } -}); - -// node_modules/.pnpm/es-errors@1.3.0/node_modules/es-errors/range.js -var require_range = __commonJS({ - "node_modules/.pnpm/es-errors@1.3.0/node_modules/es-errors/range.js"(exports, module) { - "use strict"; - module.exports = RangeError; - } -}); - -// node_modules/.pnpm/es-errors@1.3.0/node_modules/es-errors/ref.js -var require_ref = __commonJS({ - "node_modules/.pnpm/es-errors@1.3.0/node_modules/es-errors/ref.js"(exports, module) { - "use strict"; - module.exports = ReferenceError; - } -}); - -// node_modules/.pnpm/es-errors@1.3.0/node_modules/es-errors/syntax.js -var require_syntax = __commonJS({ - "node_modules/.pnpm/es-errors@1.3.0/node_modules/es-errors/syntax.js"(exports, module) { - "use strict"; - module.exports = SyntaxError; - } -}); - -// node_modules/.pnpm/es-errors@1.3.0/node_modules/es-errors/uri.js -var require_uri = __commonJS({ - "node_modules/.pnpm/es-errors@1.3.0/node_modules/es-errors/uri.js"(exports, module) { - "use strict"; - module.exports = URIError; - } -}); - -// node_modules/.pnpm/math-intrinsics@1.1.0/node_modules/math-intrinsics/abs.js -var require_abs = __commonJS({ - "node_modules/.pnpm/math-intrinsics@1.1.0/node_modules/math-intrinsics/abs.js"(exports, module) { - "use strict"; - module.exports = Math.abs; - } -}); - -// node_modules/.pnpm/math-intrinsics@1.1.0/node_modules/math-intrinsics/floor.js -var require_floor = __commonJS({ - "node_modules/.pnpm/math-intrinsics@1.1.0/node_modules/math-intrinsics/floor.js"(exports, module) { - "use strict"; - module.exports = Math.floor; - } -}); - -// node_modules/.pnpm/math-intrinsics@1.1.0/node_modules/math-intrinsics/max.js -var require_max = __commonJS({ - "node_modules/.pnpm/math-intrinsics@1.1.0/node_modules/math-intrinsics/max.js"(exports, module) { - "use strict"; - module.exports = Math.max; - } -}); - -// node_modules/.pnpm/math-intrinsics@1.1.0/node_modules/math-intrinsics/min.js -var require_min = __commonJS({ - "node_modules/.pnpm/math-intrinsics@1.1.0/node_modules/math-intrinsics/min.js"(exports, module) { - "use strict"; - module.exports = Math.min; - } -}); - -// node_modules/.pnpm/math-intrinsics@1.1.0/node_modules/math-intrinsics/pow.js -var require_pow = __commonJS({ - "node_modules/.pnpm/math-intrinsics@1.1.0/node_modules/math-intrinsics/pow.js"(exports, module) { - "use strict"; - module.exports = Math.pow; - } -}); - -// node_modules/.pnpm/math-intrinsics@1.1.0/node_modules/math-intrinsics/round.js -var require_round = __commonJS({ - "node_modules/.pnpm/math-intrinsics@1.1.0/node_modules/math-intrinsics/round.js"(exports, module) { - "use strict"; - module.exports = Math.round; - } -}); - -// node_modules/.pnpm/math-intrinsics@1.1.0/node_modules/math-intrinsics/isNaN.js -var require_isNaN = __commonJS({ - "node_modules/.pnpm/math-intrinsics@1.1.0/node_modules/math-intrinsics/isNaN.js"(exports, module) { - "use strict"; - module.exports = Number.isNaN || function isNaN2(a5) { - return a5 !== a5; - }; - } -}); - -// node_modules/.pnpm/math-intrinsics@1.1.0/node_modules/math-intrinsics/sign.js -var require_sign = __commonJS({ - "node_modules/.pnpm/math-intrinsics@1.1.0/node_modules/math-intrinsics/sign.js"(exports, module) { - "use strict"; - var $isNaN = require_isNaN(); - module.exports = function sign2(number4) { - if ($isNaN(number4) || number4 === 0) { - return number4; - } - return number4 < 0 ? -1 : 1; - }; - } -}); - -// node_modules/.pnpm/gopd@1.2.0/node_modules/gopd/gOPD.js -var require_gOPD = __commonJS({ - "node_modules/.pnpm/gopd@1.2.0/node_modules/gopd/gOPD.js"(exports, module) { - "use strict"; - module.exports = Object.getOwnPropertyDescriptor; - } -}); - -// node_modules/.pnpm/gopd@1.2.0/node_modules/gopd/index.js -var require_gopd = __commonJS({ - "node_modules/.pnpm/gopd@1.2.0/node_modules/gopd/index.js"(exports, module) { - "use strict"; - var $gOPD = require_gOPD(); - if ($gOPD) { - try { - $gOPD([], "length"); - } catch (e5) { - $gOPD = null; - } - } - module.exports = $gOPD; - } -}); - -// node_modules/.pnpm/es-define-property@1.0.1/node_modules/es-define-property/index.js -var require_es_define_property = __commonJS({ - "node_modules/.pnpm/es-define-property@1.0.1/node_modules/es-define-property/index.js"(exports, module) { - "use strict"; - var $defineProperty = Object.defineProperty || false; - if ($defineProperty) { - try { - $defineProperty({}, "a", { value: 1 }); - } catch (e5) { - $defineProperty = false; - } - } - module.exports = $defineProperty; - } -}); - -// node_modules/.pnpm/has-symbols@1.1.0/node_modules/has-symbols/shams.js -var require_shams = __commonJS({ - "node_modules/.pnpm/has-symbols@1.1.0/node_modules/has-symbols/shams.js"(exports, module) { - "use strict"; - module.exports = function hasSymbols() { - if (typeof Symbol !== "function" || typeof Object.getOwnPropertySymbols !== "function") { - return false; - } - if (typeof Symbol.iterator === "symbol") { - return true; - } - var obj = {}; - var sym = /* @__PURE__ */ Symbol("test"); - var symObj = Object(sym); - if (typeof sym === "string") { - return false; - } - if (Object.prototype.toString.call(sym) !== "[object Symbol]") { - return false; - } - if (Object.prototype.toString.call(symObj) !== "[object Symbol]") { - return false; - } - var symVal = 42; - obj[sym] = symVal; - for (var _ in obj) { - return false; - } - if (typeof Object.keys === "function" && Object.keys(obj).length !== 0) { - return false; - } - if (typeof Object.getOwnPropertyNames === "function" && Object.getOwnPropertyNames(obj).length !== 0) { - return false; - } - var syms = Object.getOwnPropertySymbols(obj); - if (syms.length !== 1 || syms[0] !== sym) { - return false; - } - if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { - return false; - } - if (typeof Object.getOwnPropertyDescriptor === "function") { - var descriptor = ( - /** @type {PropertyDescriptor} */ - Object.getOwnPropertyDescriptor(obj, sym) - ); - if (descriptor.value !== symVal || descriptor.enumerable !== true) { - return false; - } - } - return true; - }; - } -}); - -// node_modules/.pnpm/has-symbols@1.1.0/node_modules/has-symbols/index.js -var require_has_symbols = __commonJS({ - "node_modules/.pnpm/has-symbols@1.1.0/node_modules/has-symbols/index.js"(exports, module) { - "use strict"; - var origSymbol = typeof Symbol !== "undefined" && Symbol; - var hasSymbolSham = require_shams(); - module.exports = function hasNativeSymbols() { - if (typeof origSymbol !== "function") { - return false; - } - if (typeof Symbol !== "function") { - return false; - } - if (typeof origSymbol("foo") !== "symbol") { - return false; - } - if (typeof /* @__PURE__ */ Symbol("bar") !== "symbol") { - return false; - } - return hasSymbolSham(); - }; - } -}); - -// node_modules/.pnpm/get-proto@1.0.1/node_modules/get-proto/Reflect.getPrototypeOf.js -var require_Reflect_getPrototypeOf = __commonJS({ - "node_modules/.pnpm/get-proto@1.0.1/node_modules/get-proto/Reflect.getPrototypeOf.js"(exports, module) { - "use strict"; - module.exports = typeof Reflect !== "undefined" && Reflect.getPrototypeOf || null; - } -}); - -// node_modules/.pnpm/get-proto@1.0.1/node_modules/get-proto/Object.getPrototypeOf.js -var require_Object_getPrototypeOf = __commonJS({ - "node_modules/.pnpm/get-proto@1.0.1/node_modules/get-proto/Object.getPrototypeOf.js"(exports, module) { - "use strict"; - var $Object = require_es_object_atoms(); - module.exports = $Object.getPrototypeOf || null; - } -}); - -// node_modules/.pnpm/function-bind@1.1.2/node_modules/function-bind/implementation.js -var require_implementation = __commonJS({ - "node_modules/.pnpm/function-bind@1.1.2/node_modules/function-bind/implementation.js"(exports, module) { - "use strict"; - var ERROR_MESSAGE = "Function.prototype.bind called on incompatible "; - var toStr = Object.prototype.toString; - var max = Math.max; - var funcType = "[object Function]"; - var concatty = function concatty2(a5, b6) { - var arr = []; - for (var i5 = 0; i5 < a5.length; i5 += 1) { - arr[i5] = a5[i5]; - } - for (var j5 = 0; j5 < b6.length; j5 += 1) { - arr[j5 + a5.length] = b6[j5]; - } - return arr; - }; - var slicy = function slicy2(arrLike, offset) { - var arr = []; - for (var i5 = offset || 0, j5 = 0; i5 < arrLike.length; i5 += 1, j5 += 1) { - arr[j5] = arrLike[i5]; - } - return arr; - }; - var joiny = function(arr, joiner) { - var str = ""; - for (var i5 = 0; i5 < arr.length; i5 += 1) { - str += arr[i5]; - if (i5 + 1 < arr.length) { - str += joiner; - } - } - return str; - }; - module.exports = function bind2(that) { - var target = this; - if (typeof target !== "function" || toStr.apply(target) !== funcType) { - throw new TypeError(ERROR_MESSAGE + target); - } - var args = slicy(arguments, 1); - var bound; - var binder = function() { - if (this instanceof bound) { - var result = target.apply( - this, - concatty(args, arguments) - ); - if (Object(result) === result) { - return result; - } - return this; - } - return target.apply( - that, - concatty(args, arguments) - ); - }; - var boundLength = max(0, target.length - args.length); - var boundArgs = []; - for (var i5 = 0; i5 < boundLength; i5++) { - boundArgs[i5] = "$" + i5; - } - bound = Function("binder", "return function (" + joiny(boundArgs, ",") + "){ return binder.apply(this,arguments); }")(binder); - if (target.prototype) { - var Empty = function Empty2() { - }; - Empty.prototype = target.prototype; - bound.prototype = new Empty(); - Empty.prototype = null; - } - return bound; - }; - } -}); - -// node_modules/.pnpm/function-bind@1.1.2/node_modules/function-bind/index.js -var require_function_bind = __commonJS({ - "node_modules/.pnpm/function-bind@1.1.2/node_modules/function-bind/index.js"(exports, module) { - "use strict"; - var implementation = require_implementation(); - module.exports = Function.prototype.bind || implementation; - } -}); - -// node_modules/.pnpm/call-bind-apply-helpers@1.0.2/node_modules/call-bind-apply-helpers/functionCall.js -var require_functionCall = __commonJS({ - "node_modules/.pnpm/call-bind-apply-helpers@1.0.2/node_modules/call-bind-apply-helpers/functionCall.js"(exports, module) { - "use strict"; - module.exports = Function.prototype.call; - } -}); - -// node_modules/.pnpm/call-bind-apply-helpers@1.0.2/node_modules/call-bind-apply-helpers/functionApply.js -var require_functionApply = __commonJS({ - "node_modules/.pnpm/call-bind-apply-helpers@1.0.2/node_modules/call-bind-apply-helpers/functionApply.js"(exports, module) { - "use strict"; - module.exports = Function.prototype.apply; - } -}); - -// node_modules/.pnpm/call-bind-apply-helpers@1.0.2/node_modules/call-bind-apply-helpers/reflectApply.js -var require_reflectApply = __commonJS({ - "node_modules/.pnpm/call-bind-apply-helpers@1.0.2/node_modules/call-bind-apply-helpers/reflectApply.js"(exports, module) { - "use strict"; - module.exports = typeof Reflect !== "undefined" && Reflect && Reflect.apply; - } -}); - -// node_modules/.pnpm/call-bind-apply-helpers@1.0.2/node_modules/call-bind-apply-helpers/actualApply.js -var require_actualApply = __commonJS({ - "node_modules/.pnpm/call-bind-apply-helpers@1.0.2/node_modules/call-bind-apply-helpers/actualApply.js"(exports, module) { - "use strict"; - var bind2 = require_function_bind(); - var $apply = require_functionApply(); - var $call = require_functionCall(); - var $reflectApply = require_reflectApply(); - module.exports = $reflectApply || bind2.call($call, $apply); - } -}); - -// node_modules/.pnpm/call-bind-apply-helpers@1.0.2/node_modules/call-bind-apply-helpers/index.js -var require_call_bind_apply_helpers = __commonJS({ - "node_modules/.pnpm/call-bind-apply-helpers@1.0.2/node_modules/call-bind-apply-helpers/index.js"(exports, module) { - "use strict"; - var bind2 = require_function_bind(); - var $TypeError = require_type(); - var $call = require_functionCall(); - var $actualApply = require_actualApply(); - module.exports = function callBindBasic(args) { - if (args.length < 1 || typeof args[0] !== "function") { - throw new $TypeError("a function is required"); - } - return $actualApply(bind2, $call, args); - }; - } -}); - -// node_modules/.pnpm/dunder-proto@1.0.1/node_modules/dunder-proto/get.js -var require_get = __commonJS({ - "node_modules/.pnpm/dunder-proto@1.0.1/node_modules/dunder-proto/get.js"(exports, module) { - "use strict"; - var callBind = require_call_bind_apply_helpers(); - var gOPD = require_gopd(); - var hasProtoAccessor; - try { - hasProtoAccessor = /** @type {{ __proto__?: typeof Array.prototype }} */ - [].__proto__ === Array.prototype; - } catch (e5) { - if (!e5 || typeof e5 !== "object" || !("code" in e5) || e5.code !== "ERR_PROTO_ACCESS") { - throw e5; - } - } - var desc3 = !!hasProtoAccessor && gOPD && gOPD( - Object.prototype, - /** @type {keyof typeof Object.prototype} */ - "__proto__" - ); - var $Object = Object; - var $getPrototypeOf = $Object.getPrototypeOf; - module.exports = desc3 && typeof desc3.get === "function" ? callBind([desc3.get]) : typeof $getPrototypeOf === "function" ? ( - /** @type {import('./get')} */ - function getDunder(value) { - return $getPrototypeOf(value == null ? value : $Object(value)); - } - ) : false; - } -}); - -// node_modules/.pnpm/get-proto@1.0.1/node_modules/get-proto/index.js -var require_get_proto = __commonJS({ - "node_modules/.pnpm/get-proto@1.0.1/node_modules/get-proto/index.js"(exports, module) { - "use strict"; - var reflectGetProto = require_Reflect_getPrototypeOf(); - var originalGetProto = require_Object_getPrototypeOf(); - var getDunderProto = require_get(); - module.exports = reflectGetProto ? function getProto(O) { - return reflectGetProto(O); - } : originalGetProto ? function getProto(O) { - if (!O || typeof O !== "object" && typeof O !== "function") { - throw new TypeError("getProto: not an object"); - } - return originalGetProto(O); - } : getDunderProto ? function getProto(O) { - return getDunderProto(O); - } : null; - } -}); - -// node_modules/.pnpm/hasown@2.0.2/node_modules/hasown/index.js -var require_hasown = __commonJS({ - "node_modules/.pnpm/hasown@2.0.2/node_modules/hasown/index.js"(exports, module) { - "use strict"; - var call = Function.prototype.call; - var $hasOwn = Object.prototype.hasOwnProperty; - var bind2 = require_function_bind(); - module.exports = bind2.call(call, $hasOwn); - } -}); - -// node_modules/.pnpm/get-intrinsic@1.3.0/node_modules/get-intrinsic/index.js -var require_get_intrinsic = __commonJS({ - "node_modules/.pnpm/get-intrinsic@1.3.0/node_modules/get-intrinsic/index.js"(exports, module) { - "use strict"; - var undefined2; - var $Object = require_es_object_atoms(); - var $Error = require_es_errors(); - var $EvalError = require_eval(); - var $RangeError = require_range(); - var $ReferenceError = require_ref(); - var $SyntaxError = require_syntax(); - var $TypeError = require_type(); - var $URIError = require_uri(); - var abs = require_abs(); - var floor = require_floor(); - var max = require_max(); - var min = require_min(); - var pow = require_pow(); - var round = require_round(); - var sign2 = require_sign(); - var $Function = Function; - var getEvalledConstructor = function(expressionSyntax) { - try { - return $Function('"use strict"; return (' + expressionSyntax + ").constructor;")(); - } catch (e5) { - } - }; - var $gOPD = require_gopd(); - var $defineProperty = require_es_define_property(); - var throwTypeError = function() { - throw new $TypeError(); - }; - var ThrowTypeError = $gOPD ? (function() { - try { - arguments.callee; - return throwTypeError; - } catch (calleeThrows) { - try { - return $gOPD(arguments, "callee").get; - } catch (gOPDthrows) { - return throwTypeError; - } - } - })() : throwTypeError; - var hasSymbols = require_has_symbols()(); - var getProto = require_get_proto(); - var $ObjectGPO = require_Object_getPrototypeOf(); - var $ReflectGPO = require_Reflect_getPrototypeOf(); - var $apply = require_functionApply(); - var $call = require_functionCall(); - var needsEval = {}; - var TypedArray = typeof Uint8Array === "undefined" || !getProto ? undefined2 : getProto(Uint8Array); - var INTRINSICS = { - __proto__: null, - "%AggregateError%": typeof AggregateError === "undefined" ? undefined2 : AggregateError, - "%Array%": Array, - "%ArrayBuffer%": typeof ArrayBuffer === "undefined" ? undefined2 : ArrayBuffer, - "%ArrayIteratorPrototype%": hasSymbols && getProto ? getProto([][Symbol.iterator]()) : undefined2, - "%AsyncFromSyncIteratorPrototype%": undefined2, - "%AsyncFunction%": needsEval, - "%AsyncGenerator%": needsEval, - "%AsyncGeneratorFunction%": needsEval, - "%AsyncIteratorPrototype%": needsEval, - "%Atomics%": typeof Atomics === "undefined" ? undefined2 : Atomics, - "%BigInt%": typeof BigInt === "undefined" ? undefined2 : BigInt, - "%BigInt64Array%": typeof BigInt64Array === "undefined" ? undefined2 : BigInt64Array, - "%BigUint64Array%": typeof BigUint64Array === "undefined" ? undefined2 : BigUint64Array, - "%Boolean%": Boolean, - "%DataView%": typeof DataView === "undefined" ? undefined2 : DataView, - "%Date%": Date, - "%decodeURI%": decodeURI, - "%decodeURIComponent%": decodeURIComponent, - "%encodeURI%": encodeURI, - "%encodeURIComponent%": encodeURIComponent, - "%Error%": $Error, - "%eval%": eval, - // eslint-disable-line no-eval - "%EvalError%": $EvalError, - "%Float16Array%": typeof Float16Array === "undefined" ? undefined2 : Float16Array, - "%Float32Array%": typeof Float32Array === "undefined" ? undefined2 : Float32Array, - "%Float64Array%": typeof Float64Array === "undefined" ? undefined2 : Float64Array, - "%FinalizationRegistry%": typeof FinalizationRegistry === "undefined" ? undefined2 : FinalizationRegistry, - "%Function%": $Function, - "%GeneratorFunction%": needsEval, - "%Int8Array%": typeof Int8Array === "undefined" ? undefined2 : Int8Array, - "%Int16Array%": typeof Int16Array === "undefined" ? undefined2 : Int16Array, - "%Int32Array%": typeof Int32Array === "undefined" ? undefined2 : Int32Array, - "%isFinite%": isFinite, - "%isNaN%": isNaN, - "%IteratorPrototype%": hasSymbols && getProto ? getProto(getProto([][Symbol.iterator]())) : undefined2, - "%JSON%": typeof JSON === "object" ? JSON : undefined2, - "%Map%": typeof Map === "undefined" ? undefined2 : Map, - "%MapIteratorPrototype%": typeof Map === "undefined" || !hasSymbols || !getProto ? undefined2 : getProto((/* @__PURE__ */ new Map())[Symbol.iterator]()), - "%Math%": Math, - "%Number%": Number, - "%Object%": $Object, - "%Object.getOwnPropertyDescriptor%": $gOPD, - "%parseFloat%": parseFloat, - "%parseInt%": parseInt, - "%Promise%": typeof Promise === "undefined" ? undefined2 : Promise, - "%Proxy%": typeof Proxy === "undefined" ? undefined2 : Proxy, - "%RangeError%": $RangeError, - "%ReferenceError%": $ReferenceError, - "%Reflect%": typeof Reflect === "undefined" ? undefined2 : Reflect, - "%RegExp%": RegExp, - "%Set%": typeof Set === "undefined" ? undefined2 : Set, - "%SetIteratorPrototype%": typeof Set === "undefined" || !hasSymbols || !getProto ? undefined2 : getProto((/* @__PURE__ */ new Set())[Symbol.iterator]()), - "%SharedArrayBuffer%": typeof SharedArrayBuffer === "undefined" ? undefined2 : SharedArrayBuffer, - "%String%": String, - "%StringIteratorPrototype%": hasSymbols && getProto ? getProto(""[Symbol.iterator]()) : undefined2, - "%Symbol%": hasSymbols ? Symbol : undefined2, - "%SyntaxError%": $SyntaxError, - "%ThrowTypeError%": ThrowTypeError, - "%TypedArray%": TypedArray, - "%TypeError%": $TypeError, - "%Uint8Array%": typeof Uint8Array === "undefined" ? undefined2 : Uint8Array, - "%Uint8ClampedArray%": typeof Uint8ClampedArray === "undefined" ? undefined2 : Uint8ClampedArray, - "%Uint16Array%": typeof Uint16Array === "undefined" ? undefined2 : Uint16Array, - "%Uint32Array%": typeof Uint32Array === "undefined" ? undefined2 : Uint32Array, - "%URIError%": $URIError, - "%WeakMap%": typeof WeakMap === "undefined" ? undefined2 : WeakMap, - "%WeakRef%": typeof WeakRef === "undefined" ? undefined2 : WeakRef, - "%WeakSet%": typeof WeakSet === "undefined" ? undefined2 : WeakSet, - "%Function.prototype.call%": $call, - "%Function.prototype.apply%": $apply, - "%Object.defineProperty%": $defineProperty, - "%Object.getPrototypeOf%": $ObjectGPO, - "%Math.abs%": abs, - "%Math.floor%": floor, - "%Math.max%": max, - "%Math.min%": min, - "%Math.pow%": pow, - "%Math.round%": round, - "%Math.sign%": sign2, - "%Reflect.getPrototypeOf%": $ReflectGPO - }; - if (getProto) { - try { - null.error; - } catch (e5) { - errorProto = getProto(getProto(e5)); - INTRINSICS["%Error.prototype%"] = errorProto; - } - } - var errorProto; - var doEval = function doEval2(name) { - var value; - if (name === "%AsyncFunction%") { - value = getEvalledConstructor("async function () {}"); - } else if (name === "%GeneratorFunction%") { - value = getEvalledConstructor("function* () {}"); - } else if (name === "%AsyncGeneratorFunction%") { - value = getEvalledConstructor("async function* () {}"); - } else if (name === "%AsyncGenerator%") { - var fn = doEval2("%AsyncGeneratorFunction%"); - if (fn) { - value = fn.prototype; - } - } else if (name === "%AsyncIteratorPrototype%") { - var gen = doEval2("%AsyncGenerator%"); - if (gen && getProto) { - value = getProto(gen.prototype); - } - } - INTRINSICS[name] = value; - return value; - }; - var LEGACY_ALIASES = { - __proto__: null, - "%ArrayBufferPrototype%": ["ArrayBuffer", "prototype"], - "%ArrayPrototype%": ["Array", "prototype"], - "%ArrayProto_entries%": ["Array", "prototype", "entries"], - "%ArrayProto_forEach%": ["Array", "prototype", "forEach"], - "%ArrayProto_keys%": ["Array", "prototype", "keys"], - "%ArrayProto_values%": ["Array", "prototype", "values"], - "%AsyncFunctionPrototype%": ["AsyncFunction", "prototype"], - "%AsyncGenerator%": ["AsyncGeneratorFunction", "prototype"], - "%AsyncGeneratorPrototype%": ["AsyncGeneratorFunction", "prototype", "prototype"], - "%BooleanPrototype%": ["Boolean", "prototype"], - "%DataViewPrototype%": ["DataView", "prototype"], - "%DatePrototype%": ["Date", "prototype"], - "%ErrorPrototype%": ["Error", "prototype"], - "%EvalErrorPrototype%": ["EvalError", "prototype"], - "%Float32ArrayPrototype%": ["Float32Array", "prototype"], - "%Float64ArrayPrototype%": ["Float64Array", "prototype"], - "%FunctionPrototype%": ["Function", "prototype"], - "%Generator%": ["GeneratorFunction", "prototype"], - "%GeneratorPrototype%": ["GeneratorFunction", "prototype", "prototype"], - "%Int8ArrayPrototype%": ["Int8Array", "prototype"], - "%Int16ArrayPrototype%": ["Int16Array", "prototype"], - "%Int32ArrayPrototype%": ["Int32Array", "prototype"], - "%JSONParse%": ["JSON", "parse"], - "%JSONStringify%": ["JSON", "stringify"], - "%MapPrototype%": ["Map", "prototype"], - "%NumberPrototype%": ["Number", "prototype"], - "%ObjectPrototype%": ["Object", "prototype"], - "%ObjProto_toString%": ["Object", "prototype", "toString"], - "%ObjProto_valueOf%": ["Object", "prototype", "valueOf"], - "%PromisePrototype%": ["Promise", "prototype"], - "%PromiseProto_then%": ["Promise", "prototype", "then"], - "%Promise_all%": ["Promise", "all"], - "%Promise_reject%": ["Promise", "reject"], - "%Promise_resolve%": ["Promise", "resolve"], - "%RangeErrorPrototype%": ["RangeError", "prototype"], - "%ReferenceErrorPrototype%": ["ReferenceError", "prototype"], - "%RegExpPrototype%": ["RegExp", "prototype"], - "%SetPrototype%": ["Set", "prototype"], - "%SharedArrayBufferPrototype%": ["SharedArrayBuffer", "prototype"], - "%StringPrototype%": ["String", "prototype"], - "%SymbolPrototype%": ["Symbol", "prototype"], - "%SyntaxErrorPrototype%": ["SyntaxError", "prototype"], - "%TypedArrayPrototype%": ["TypedArray", "prototype"], - "%TypeErrorPrototype%": ["TypeError", "prototype"], - "%Uint8ArrayPrototype%": ["Uint8Array", "prototype"], - "%Uint8ClampedArrayPrototype%": ["Uint8ClampedArray", "prototype"], - "%Uint16ArrayPrototype%": ["Uint16Array", "prototype"], - "%Uint32ArrayPrototype%": ["Uint32Array", "prototype"], - "%URIErrorPrototype%": ["URIError", "prototype"], - "%WeakMapPrototype%": ["WeakMap", "prototype"], - "%WeakSetPrototype%": ["WeakSet", "prototype"] - }; - var bind2 = require_function_bind(); - var hasOwn = require_hasown(); - var $concat = bind2.call($call, Array.prototype.concat); - var $spliceApply = bind2.call($apply, Array.prototype.splice); - var $replace = bind2.call($call, String.prototype.replace); - var $strSlice = bind2.call($call, String.prototype.slice); - var $exec = bind2.call($call, RegExp.prototype.exec); - var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g; - var reEscapeChar = /\\(\\)?/g; - var stringToPath = function stringToPath2(string4) { - var first = $strSlice(string4, 0, 1); - var last = $strSlice(string4, -1); - if (first === "%" && last !== "%") { - throw new $SyntaxError("invalid intrinsic syntax, expected closing `%`"); - } else if (last === "%" && first !== "%") { - throw new $SyntaxError("invalid intrinsic syntax, expected opening `%`"); - } - var result = []; - $replace(string4, rePropName, function(match, number4, quote, subString) { - result[result.length] = quote ? $replace(subString, reEscapeChar, "$1") : number4 || match; - }); - return result; - }; - var getBaseIntrinsic = function getBaseIntrinsic2(name, allowMissing) { - var intrinsicName = name; - var alias; - if (hasOwn(LEGACY_ALIASES, intrinsicName)) { - alias = LEGACY_ALIASES[intrinsicName]; - intrinsicName = "%" + alias[0] + "%"; - } - if (hasOwn(INTRINSICS, intrinsicName)) { - var value = INTRINSICS[intrinsicName]; - if (value === needsEval) { - value = doEval(intrinsicName); - } - if (typeof value === "undefined" && !allowMissing) { - throw new $TypeError("intrinsic " + name + " exists, but is not available. Please file an issue!"); - } - return { - alias, - name: intrinsicName, - value - }; - } - throw new $SyntaxError("intrinsic " + name + " does not exist!"); - }; - module.exports = function GetIntrinsic(name, allowMissing) { - if (typeof name !== "string" || name.length === 0) { - throw new $TypeError("intrinsic name must be a non-empty string"); - } - if (arguments.length > 1 && typeof allowMissing !== "boolean") { - throw new $TypeError('"allowMissing" argument must be a boolean'); - } - if ($exec(/^%?[^%]*%?$/, name) === null) { - throw new $SyntaxError("`%` may not be present anywhere but at the beginning and end of the intrinsic name"); - } - var parts = stringToPath(name); - var intrinsicBaseName = parts.length > 0 ? parts[0] : ""; - var intrinsic = getBaseIntrinsic("%" + intrinsicBaseName + "%", allowMissing); - var intrinsicRealName = intrinsic.name; - var value = intrinsic.value; - var skipFurtherCaching = false; - var alias = intrinsic.alias; - if (alias) { - intrinsicBaseName = alias[0]; - $spliceApply(parts, $concat([0, 1], alias)); - } - for (var i5 = 1, isOwn = true; i5 < parts.length; i5 += 1) { - var part = parts[i5]; - var first = $strSlice(part, 0, 1); - var last = $strSlice(part, -1); - if ((first === '"' || first === "'" || first === "`" || (last === '"' || last === "'" || last === "`")) && first !== last) { - throw new $SyntaxError("property names with quotes must have matching quotes"); - } - if (part === "constructor" || !isOwn) { - skipFurtherCaching = true; - } - intrinsicBaseName += "." + part; - intrinsicRealName = "%" + intrinsicBaseName + "%"; - if (hasOwn(INTRINSICS, intrinsicRealName)) { - value = INTRINSICS[intrinsicRealName]; - } else if (value != null) { - if (!(part in value)) { - if (!allowMissing) { - throw new $TypeError("base intrinsic for " + name + " exists, but the property is not available."); - } - return void undefined2; - } - if ($gOPD && i5 + 1 >= parts.length) { - var desc3 = $gOPD(value, part); - isOwn = !!desc3; - if (isOwn && "get" in desc3 && !("originalValue" in desc3.get)) { - value = desc3.get; - } else { - value = value[part]; - } - } else { - isOwn = hasOwn(value, part); - value = value[part]; - } - if (isOwn && !skipFurtherCaching) { - INTRINSICS[intrinsicRealName] = value; - } - } - } - return value; - }; - } -}); - -// node_modules/.pnpm/call-bound@1.0.4/node_modules/call-bound/index.js -var require_call_bound = __commonJS({ - "node_modules/.pnpm/call-bound@1.0.4/node_modules/call-bound/index.js"(exports, module) { - "use strict"; - var GetIntrinsic = require_get_intrinsic(); - var callBindBasic = require_call_bind_apply_helpers(); - var $indexOf = callBindBasic([GetIntrinsic("%String.prototype.indexOf%")]); - module.exports = function callBoundIntrinsic(name, allowMissing) { - var intrinsic = ( - /** @type {(this: unknown, ...args: unknown[]) => unknown} */ - GetIntrinsic(name, !!allowMissing) - ); - if (typeof intrinsic === "function" && $indexOf(name, ".prototype.") > -1) { - return callBindBasic( - /** @type {const} */ - [intrinsic] - ); - } - return intrinsic; - }; - } -}); - -// node_modules/.pnpm/side-channel-map@1.0.1/node_modules/side-channel-map/index.js -var require_side_channel_map = __commonJS({ - "node_modules/.pnpm/side-channel-map@1.0.1/node_modules/side-channel-map/index.js"(exports, module) { - "use strict"; - var GetIntrinsic = require_get_intrinsic(); - var callBound = require_call_bound(); - var inspect = require_object_inspect(); - var $TypeError = require_type(); - var $Map = GetIntrinsic("%Map%", true); - var $mapGet = callBound("Map.prototype.get", true); - var $mapSet = callBound("Map.prototype.set", true); - var $mapHas = callBound("Map.prototype.has", true); - var $mapDelete = callBound("Map.prototype.delete", true); - var $mapSize = callBound("Map.prototype.size", true); - module.exports = !!$Map && /** @type {Exclude} */ - function getSideChannelMap() { - var $m; - var channel = { - assert: function(key) { - if (!channel.has(key)) { - throw new $TypeError("Side channel does not contain " + inspect(key)); - } - }, - "delete": function(key) { - if ($m) { - var result = $mapDelete($m, key); - if ($mapSize($m) === 0) { - $m = void 0; - } - return result; - } - return false; - }, - get: function(key) { - if ($m) { - return $mapGet($m, key); - } - }, - has: function(key) { - if ($m) { - return $mapHas($m, key); - } - return false; - }, - set: function(key, value) { - if (!$m) { - $m = new $Map(); - } - $mapSet($m, key, value); - } - }; - return channel; - }; - } -}); - -// node_modules/.pnpm/side-channel-weakmap@1.0.2/node_modules/side-channel-weakmap/index.js -var require_side_channel_weakmap = __commonJS({ - "node_modules/.pnpm/side-channel-weakmap@1.0.2/node_modules/side-channel-weakmap/index.js"(exports, module) { - "use strict"; - var GetIntrinsic = require_get_intrinsic(); - var callBound = require_call_bound(); - var inspect = require_object_inspect(); - var getSideChannelMap = require_side_channel_map(); - var $TypeError = require_type(); - var $WeakMap = GetIntrinsic("%WeakMap%", true); - var $weakMapGet = callBound("WeakMap.prototype.get", true); - var $weakMapSet = callBound("WeakMap.prototype.set", true); - var $weakMapHas = callBound("WeakMap.prototype.has", true); - var $weakMapDelete = callBound("WeakMap.prototype.delete", true); - module.exports = $WeakMap ? ( - /** @type {Exclude} */ - function getSideChannelWeakMap() { - var $wm; - var $m; - var channel = { - assert: function(key) { - if (!channel.has(key)) { - throw new $TypeError("Side channel does not contain " + inspect(key)); - } - }, - "delete": function(key) { - if ($WeakMap && key && (typeof key === "object" || typeof key === "function")) { - if ($wm) { - return $weakMapDelete($wm, key); - } - } else if (getSideChannelMap) { - if ($m) { - return $m["delete"](key); - } - } - return false; - }, - get: function(key) { - if ($WeakMap && key && (typeof key === "object" || typeof key === "function")) { - if ($wm) { - return $weakMapGet($wm, key); - } - } - return $m && $m.get(key); - }, - has: function(key) { - if ($WeakMap && key && (typeof key === "object" || typeof key === "function")) { - if ($wm) { - return $weakMapHas($wm, key); - } - } - return !!$m && $m.has(key); - }, - set: function(key, value) { - if ($WeakMap && key && (typeof key === "object" || typeof key === "function")) { - if (!$wm) { - $wm = new $WeakMap(); - } - $weakMapSet($wm, key, value); - } else if (getSideChannelMap) { - if (!$m) { - $m = getSideChannelMap(); - } - $m.set(key, value); - } - } - }; - return channel; - } - ) : getSideChannelMap; - } -}); - -// node_modules/.pnpm/side-channel@1.1.0/node_modules/side-channel/index.js -var require_side_channel = __commonJS({ - "node_modules/.pnpm/side-channel@1.1.0/node_modules/side-channel/index.js"(exports, module) { - "use strict"; - var $TypeError = require_type(); - var inspect = require_object_inspect(); - var getSideChannelList = require_side_channel_list(); - var getSideChannelMap = require_side_channel_map(); - var getSideChannelWeakMap = require_side_channel_weakmap(); - var makeChannel = getSideChannelWeakMap || getSideChannelMap || getSideChannelList; - module.exports = function getSideChannel() { - var $channelData; - var channel = { - assert: function(key) { - if (!channel.has(key)) { - throw new $TypeError("Side channel does not contain " + inspect(key)); - } - }, - "delete": function(key) { - return !!$channelData && $channelData["delete"](key); - }, - get: function(key) { - return $channelData && $channelData.get(key); - }, - has: function(key) { - return !!$channelData && $channelData.has(key); - }, - set: function(key, value) { - if (!$channelData) { - $channelData = makeChannel(); - } - $channelData.set(key, value); - } - }; - return channel; - }; - } -}); - -// node_modules/.pnpm/qs@6.15.1/node_modules/qs/lib/formats.js -var require_formats = __commonJS({ - "node_modules/.pnpm/qs@6.15.1/node_modules/qs/lib/formats.js"(exports, module) { - "use strict"; - var replace = String.prototype.replace; - var percentTwenties = /%20/g; - var Format = { - RFC1738: "RFC1738", - RFC3986: "RFC3986" - }; - module.exports = { - "default": Format.RFC3986, - formatters: { - RFC1738: function(value) { - return replace.call(value, percentTwenties, "+"); - }, - RFC3986: function(value) { - return String(value); - } - }, - RFC1738: Format.RFC1738, - RFC3986: Format.RFC3986 - }; - } -}); - -// node_modules/.pnpm/qs@6.15.1/node_modules/qs/lib/utils.js -var require_utils2 = __commonJS({ - "node_modules/.pnpm/qs@6.15.1/node_modules/qs/lib/utils.js"(exports, module) { - "use strict"; - var formats = require_formats(); - var getSideChannel = require_side_channel(); - var has = Object.prototype.hasOwnProperty; - var isArray = Array.isArray; - var overflowChannel = getSideChannel(); - var markOverflow = function markOverflow2(obj, maxIndex) { - overflowChannel.set(obj, maxIndex); - return obj; - }; - var isOverflow = function isOverflow2(obj) { - return overflowChannel.has(obj); - }; - var getMaxIndex = function getMaxIndex2(obj) { - return overflowChannel.get(obj); - }; - var setMaxIndex = function setMaxIndex2(obj, maxIndex) { - overflowChannel.set(obj, maxIndex); - }; - var hexTable = (function() { - var array2 = []; - for (var i5 = 0; i5 < 256; ++i5) { - array2[array2.length] = "%" + ((i5 < 16 ? "0" : "") + i5.toString(16)).toUpperCase(); - } - return array2; - })(); - var compactQueue = function compactQueue2(queue) { - while (queue.length > 1) { - var item = queue.pop(); - var obj = item.obj[item.prop]; - if (isArray(obj)) { - var compacted = []; - for (var j5 = 0; j5 < obj.length; ++j5) { - if (typeof obj[j5] !== "undefined") { - compacted[compacted.length] = obj[j5]; - } - } - item.obj[item.prop] = compacted; - } - } - }; - var arrayToObject = function arrayToObject2(source, options) { - var obj = options && options.plainObjects ? { __proto__: null } : {}; - for (var i5 = 0; i5 < source.length; ++i5) { - if (typeof source[i5] !== "undefined") { - obj[i5] = source[i5]; - } - } - return obj; - }; - var merge2 = function merge3(target, source, options) { - if (!source) { - return target; - } - if (typeof source !== "object" && typeof source !== "function") { - if (isArray(target)) { - var nextIndex = target.length; - if (options && typeof options.arrayLimit === "number" && nextIndex > options.arrayLimit) { - return markOverflow(arrayToObject(target.concat(source), options), nextIndex); - } - target[nextIndex] = source; - } else if (target && typeof target === "object") { - if (isOverflow(target)) { - var newIndex = getMaxIndex(target) + 1; - target[newIndex] = source; - setMaxIndex(target, newIndex); - } else if (options && options.strictMerge) { - return [target, source]; - } else if (options && (options.plainObjects || options.allowPrototypes) || !has.call(Object.prototype, source)) { - target[source] = true; - } - } else { - return [target, source]; - } - return target; - } - if (!target || typeof target !== "object") { - if (isOverflow(source)) { - var sourceKeys = Object.keys(source); - var result = options && options.plainObjects ? { __proto__: null, 0: target } : { 0: target }; - for (var m5 = 0; m5 < sourceKeys.length; m5++) { - var oldKey = parseInt(sourceKeys[m5], 10); - result[oldKey + 1] = source[sourceKeys[m5]]; - } - return markOverflow(result, getMaxIndex(source) + 1); - } - var combined = [target].concat(source); - if (options && typeof options.arrayLimit === "number" && combined.length > options.arrayLimit) { - return markOverflow(arrayToObject(combined, options), combined.length - 1); - } - return combined; - } - var mergeTarget = target; - if (isArray(target) && !isArray(source)) { - mergeTarget = arrayToObject(target, options); - } - if (isArray(target) && isArray(source)) { - source.forEach(function(item, i5) { - if (has.call(target, i5)) { - var targetItem = target[i5]; - if (targetItem && typeof targetItem === "object" && item && typeof item === "object") { - target[i5] = merge3(targetItem, item, options); - } else { - target[target.length] = item; - } - } else { - target[i5] = item; - } - }); - return target; - } - return Object.keys(source).reduce(function(acc, key) { - var value = source[key]; - if (has.call(acc, key)) { - acc[key] = merge3(acc[key], value, options); - } else { - acc[key] = value; - } - if (isOverflow(source) && !isOverflow(acc)) { - markOverflow(acc, getMaxIndex(source)); - } - if (isOverflow(acc)) { - var keyNum = parseInt(key, 10); - if (String(keyNum) === key && keyNum >= 0 && keyNum > getMaxIndex(acc)) { - setMaxIndex(acc, keyNum); - } - } - return acc; - }, mergeTarget); - }; - var assign = function assignSingleSource(target, source) { - return Object.keys(source).reduce(function(acc, key) { - acc[key] = source[key]; - return acc; - }, target); - }; - var decode5 = function(str, defaultDecoder, charset) { - var strWithoutPlus = str.replace(/\+/g, " "); - if (charset === "iso-8859-1") { - return strWithoutPlus.replace(/%[0-9a-f]{2}/gi, unescape); - } - try { - return decodeURIComponent(strWithoutPlus); - } catch (e5) { - return strWithoutPlus; - } - }; - var limit = 1024; - var encode6 = function encode7(str, defaultEncoder, charset, kind, format2) { - if (str.length === 0) { - return str; - } - var string4 = str; - if (typeof str === "symbol") { - string4 = Symbol.prototype.toString.call(str); - } else if (typeof str !== "string") { - string4 = String(str); - } - if (charset === "iso-8859-1") { - return escape(string4).replace(/%u[0-9a-f]{4}/gi, function($0) { - return "%26%23" + parseInt($0.slice(2), 16) + "%3B"; - }); - } - var out = ""; - for (var j5 = 0; j5 < string4.length; j5 += limit) { - var segment = string4.length >= limit ? string4.slice(j5, j5 + limit) : string4; - var arr = []; - for (var i5 = 0; i5 < segment.length; ++i5) { - var c5 = segment.charCodeAt(i5); - if (c5 === 45 || c5 === 46 || c5 === 95 || c5 === 126 || c5 >= 48 && c5 <= 57 || c5 >= 65 && c5 <= 90 || c5 >= 97 && c5 <= 122 || format2 === formats.RFC1738 && (c5 === 40 || c5 === 41)) { - arr[arr.length] = segment.charAt(i5); - continue; - } - if (c5 < 128) { - arr[arr.length] = hexTable[c5]; - continue; - } - if (c5 < 2048) { - arr[arr.length] = hexTable[192 | c5 >> 6] + hexTable[128 | c5 & 63]; - continue; - } - if (c5 < 55296 || c5 >= 57344) { - arr[arr.length] = hexTable[224 | c5 >> 12] + hexTable[128 | c5 >> 6 & 63] + hexTable[128 | c5 & 63]; - continue; - } - i5 += 1; - c5 = 65536 + ((c5 & 1023) << 10 | segment.charCodeAt(i5) & 1023); - arr[arr.length] = hexTable[240 | c5 >> 18] + hexTable[128 | c5 >> 12 & 63] + hexTable[128 | c5 >> 6 & 63] + hexTable[128 | c5 & 63]; - } - out += arr.join(""); - } - return out; - }; - var compact = function compact2(value) { - var queue = [{ obj: { o: value }, prop: "o" }]; - var refs = []; - for (var i5 = 0; i5 < queue.length; ++i5) { - var item = queue[i5]; - var obj = item.obj[item.prop]; - var keys = Object.keys(obj); - for (var j5 = 0; j5 < keys.length; ++j5) { - var key = keys[j5]; - var val = obj[key]; - if (typeof val === "object" && val !== null && refs.indexOf(val) === -1) { - queue[queue.length] = { obj, prop: key }; - refs[refs.length] = val; - } - } - } - compactQueue(queue); - return value; - }; - var isRegExp = function isRegExp2(obj) { - return Object.prototype.toString.call(obj) === "[object RegExp]"; - }; - var isBuffer2 = function isBuffer3(obj) { - if (!obj || typeof obj !== "object") { - return false; - } - return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); - }; - var combine = function combine2(a5, b6, arrayLimit, plainObjects) { - if (isOverflow(a5)) { - var newIndex = getMaxIndex(a5) + 1; - a5[newIndex] = b6; - setMaxIndex(a5, newIndex); - return a5; - } - var result = [].concat(a5, b6); - if (result.length > arrayLimit) { - return markOverflow(arrayToObject(result, { plainObjects }), result.length - 1); - } - return result; - }; - var maybeMap = function maybeMap2(val, fn) { - if (isArray(val)) { - var mapped = []; - for (var i5 = 0; i5 < val.length; i5 += 1) { - mapped[mapped.length] = fn(val[i5]); - } - return mapped; - } - return fn(val); - }; - module.exports = { - arrayToObject, - assign, - combine, - compact, - decode: decode5, - encode: encode6, - isBuffer: isBuffer2, - isOverflow, - isRegExp, - markOverflow, - maybeMap, - merge: merge2 - }; - } -}); - -// node_modules/.pnpm/qs@6.15.1/node_modules/qs/lib/stringify.js -var require_stringify = __commonJS({ - "node_modules/.pnpm/qs@6.15.1/node_modules/qs/lib/stringify.js"(exports, module) { - "use strict"; - var getSideChannel = require_side_channel(); - var utils = require_utils2(); - var formats = require_formats(); - var has = Object.prototype.hasOwnProperty; - var arrayPrefixGenerators = { - brackets: function brackets(prefix) { - return prefix + "[]"; - }, - comma: "comma", - indices: function indices(prefix, key) { - return prefix + "[" + key + "]"; - }, - repeat: function repeat(prefix) { - return prefix; - } - }; - var isArray = Array.isArray; - var push = Array.prototype.push; - var pushToArray = function(arr, valueOrArray) { - push.apply(arr, isArray(valueOrArray) ? valueOrArray : [valueOrArray]); - }; - var toISO = Date.prototype.toISOString; - var defaultFormat = formats["default"]; - var defaults = { - addQueryPrefix: false, - allowDots: false, - allowEmptyArrays: false, - arrayFormat: "indices", - charset: "utf-8", - charsetSentinel: false, - commaRoundTrip: false, - delimiter: "&", - encode: true, - encodeDotInKeys: false, - encoder: utils.encode, - encodeValuesOnly: false, - filter: void 0, - format: defaultFormat, - formatter: formats.formatters[defaultFormat], - // deprecated - indices: false, - serializeDate: function serializeDate(date7) { - return toISO.call(date7); - }, - skipNulls: false, - strictNullHandling: false - }; - var isNonNullishPrimitive = function isNonNullishPrimitive2(v5) { - return typeof v5 === "string" || typeof v5 === "number" || typeof v5 === "boolean" || typeof v5 === "symbol" || typeof v5 === "bigint"; - }; - var sentinel = {}; - var stringify2 = function stringify3(object2, prefix, generateArrayPrefix, commaRoundTrip, allowEmptyArrays, strictNullHandling, skipNulls, encodeDotInKeys, encoder3, filter, sort, allowDots, serializeDate, format2, formatter, encodeValuesOnly, charset, sideChannel) { - var obj = object2; - var tmpSc = sideChannel; - var step = 0; - var findFlag = false; - while ((tmpSc = tmpSc.get(sentinel)) !== void 0 && !findFlag) { - var pos = tmpSc.get(object2); - step += 1; - if (typeof pos !== "undefined") { - if (pos === step) { - throw new RangeError("Cyclic object value"); - } else { - findFlag = true; - } - } - if (typeof tmpSc.get(sentinel) === "undefined") { - step = 0; - } - } - if (typeof filter === "function") { - obj = filter(prefix, obj); - } else if (obj instanceof Date) { - obj = serializeDate(obj); - } else if (generateArrayPrefix === "comma" && isArray(obj)) { - obj = utils.maybeMap(obj, function(value2) { - if (value2 instanceof Date) { - return serializeDate(value2); - } - return value2; - }); - } - if (obj === null) { - if (strictNullHandling) { - return encoder3 && !encodeValuesOnly ? encoder3(prefix, defaults.encoder, charset, "key", format2) : prefix; - } - obj = ""; - } - if (isNonNullishPrimitive(obj) || utils.isBuffer(obj)) { - if (encoder3) { - var keyValue = encodeValuesOnly ? prefix : encoder3(prefix, defaults.encoder, charset, "key", format2); - return [formatter(keyValue) + "=" + formatter(encoder3(obj, defaults.encoder, charset, "value", format2))]; - } - return [formatter(prefix) + "=" + formatter(String(obj))]; - } - var values2 = []; - if (typeof obj === "undefined") { - return values2; - } - var objKeys; - if (generateArrayPrefix === "comma" && isArray(obj)) { - if (encodeValuesOnly && encoder3) { - obj = utils.maybeMap(obj, encoder3); - } - objKeys = [{ value: obj.length > 0 ? obj.join(",") || null : void 0 }]; - } else if (isArray(filter)) { - objKeys = filter; - } else { - var keys = Object.keys(obj); - objKeys = sort ? keys.sort(sort) : keys; - } - var encodedPrefix = encodeDotInKeys ? String(prefix).replace(/\./g, "%2E") : String(prefix); - var adjustedPrefix = commaRoundTrip && isArray(obj) && obj.length === 1 ? encodedPrefix + "[]" : encodedPrefix; - if (allowEmptyArrays && isArray(obj) && obj.length === 0) { - return adjustedPrefix + "[]"; - } - for (var j5 = 0; j5 < objKeys.length; ++j5) { - var key = objKeys[j5]; - var value = typeof key === "object" && key && typeof key.value !== "undefined" ? key.value : obj[key]; - if (skipNulls && value === null) { - continue; - } - var encodedKey = allowDots && encodeDotInKeys ? String(key).replace(/\./g, "%2E") : String(key); - var keyPrefix = isArray(obj) ? typeof generateArrayPrefix === "function" ? generateArrayPrefix(adjustedPrefix, encodedKey) : adjustedPrefix : adjustedPrefix + (allowDots ? "." + encodedKey : "[" + encodedKey + "]"); - sideChannel.set(object2, step); - var valueSideChannel = getSideChannel(); - valueSideChannel.set(sentinel, sideChannel); - pushToArray(values2, stringify3( - value, - keyPrefix, - generateArrayPrefix, - commaRoundTrip, - allowEmptyArrays, - strictNullHandling, - skipNulls, - encodeDotInKeys, - generateArrayPrefix === "comma" && encodeValuesOnly && isArray(obj) ? null : encoder3, - filter, - sort, - allowDots, - serializeDate, - format2, - formatter, - encodeValuesOnly, - charset, - valueSideChannel - )); - } - return values2; - }; - var normalizeStringifyOptions = function normalizeStringifyOptions2(opts) { - if (!opts) { - return defaults; - } - if (typeof opts.allowEmptyArrays !== "undefined" && typeof opts.allowEmptyArrays !== "boolean") { - throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided"); - } - if (typeof opts.encodeDotInKeys !== "undefined" && typeof opts.encodeDotInKeys !== "boolean") { - throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided"); - } - if (opts.encoder !== null && typeof opts.encoder !== "undefined" && typeof opts.encoder !== "function") { - throw new TypeError("Encoder has to be a function."); - } - var charset = opts.charset || defaults.charset; - if (typeof opts.charset !== "undefined" && opts.charset !== "utf-8" && opts.charset !== "iso-8859-1") { - throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined"); - } - var format2 = formats["default"]; - if (typeof opts.format !== "undefined") { - if (!has.call(formats.formatters, opts.format)) { - throw new TypeError("Unknown format option provided."); - } - format2 = opts.format; - } - var formatter = formats.formatters[format2]; - var filter = defaults.filter; - if (typeof opts.filter === "function" || isArray(opts.filter)) { - filter = opts.filter; - } - var arrayFormat; - if (opts.arrayFormat in arrayPrefixGenerators) { - arrayFormat = opts.arrayFormat; - } else if ("indices" in opts) { - arrayFormat = opts.indices ? "indices" : "repeat"; - } else { - arrayFormat = defaults.arrayFormat; - } - if ("commaRoundTrip" in opts && typeof opts.commaRoundTrip !== "boolean") { - throw new TypeError("`commaRoundTrip` must be a boolean, or absent"); - } - var allowDots = typeof opts.allowDots === "undefined" ? opts.encodeDotInKeys === true ? true : defaults.allowDots : !!opts.allowDots; - return { - addQueryPrefix: typeof opts.addQueryPrefix === "boolean" ? opts.addQueryPrefix : defaults.addQueryPrefix, - allowDots, - allowEmptyArrays: typeof opts.allowEmptyArrays === "boolean" ? !!opts.allowEmptyArrays : defaults.allowEmptyArrays, - arrayFormat, - charset, - charsetSentinel: typeof opts.charsetSentinel === "boolean" ? opts.charsetSentinel : defaults.charsetSentinel, - commaRoundTrip: !!opts.commaRoundTrip, - delimiter: typeof opts.delimiter === "undefined" ? defaults.delimiter : opts.delimiter, - encode: typeof opts.encode === "boolean" ? opts.encode : defaults.encode, - encodeDotInKeys: typeof opts.encodeDotInKeys === "boolean" ? opts.encodeDotInKeys : defaults.encodeDotInKeys, - encoder: typeof opts.encoder === "function" ? opts.encoder : defaults.encoder, - encodeValuesOnly: typeof opts.encodeValuesOnly === "boolean" ? opts.encodeValuesOnly : defaults.encodeValuesOnly, - filter, - format: format2, - formatter, - serializeDate: typeof opts.serializeDate === "function" ? opts.serializeDate : defaults.serializeDate, - skipNulls: typeof opts.skipNulls === "boolean" ? opts.skipNulls : defaults.skipNulls, - sort: typeof opts.sort === "function" ? opts.sort : null, - strictNullHandling: typeof opts.strictNullHandling === "boolean" ? opts.strictNullHandling : defaults.strictNullHandling - }; - }; - module.exports = function(object2, opts) { - var obj = object2; - var options = normalizeStringifyOptions(opts); - var objKeys; - var filter; - if (typeof options.filter === "function") { - filter = options.filter; - obj = filter("", obj); - } else if (isArray(options.filter)) { - filter = options.filter; - objKeys = filter; - } - var keys = []; - if (typeof obj !== "object" || obj === null) { - return ""; - } - var generateArrayPrefix = arrayPrefixGenerators[options.arrayFormat]; - var commaRoundTrip = generateArrayPrefix === "comma" && options.commaRoundTrip; - if (!objKeys) { - objKeys = Object.keys(obj); - } - if (options.sort) { - objKeys.sort(options.sort); - } - var sideChannel = getSideChannel(); - for (var i5 = 0; i5 < objKeys.length; ++i5) { - var key = objKeys[i5]; - var value = obj[key]; - if (options.skipNulls && value === null) { - continue; - } - pushToArray(keys, stringify2( - value, - key, - generateArrayPrefix, - commaRoundTrip, - options.allowEmptyArrays, - options.strictNullHandling, - options.skipNulls, - options.encodeDotInKeys, - options.encode ? options.encoder : null, - options.filter, - options.sort, - options.allowDots, - options.serializeDate, - options.format, - options.formatter, - options.encodeValuesOnly, - options.charset, - sideChannel - )); - } - var joined = keys.join(options.delimiter); - var prefix = options.addQueryPrefix === true ? "?" : ""; - if (options.charsetSentinel) { - if (options.charset === "iso-8859-1") { - prefix += "utf8=%26%2310003%3B&"; - } else { - prefix += "utf8=%E2%9C%93&"; - } - } - return joined.length > 0 ? prefix + joined : ""; - }; - } -}); - -// node_modules/.pnpm/qs@6.15.1/node_modules/qs/lib/parse.js -var require_parse = __commonJS({ - "node_modules/.pnpm/qs@6.15.1/node_modules/qs/lib/parse.js"(exports, module) { - "use strict"; - var utils = require_utils2(); - var has = Object.prototype.hasOwnProperty; - var isArray = Array.isArray; - var defaults = { - allowDots: false, - allowEmptyArrays: false, - allowPrototypes: false, - allowSparse: false, - arrayLimit: 20, - charset: "utf-8", - charsetSentinel: false, - comma: false, - decodeDotInKeys: false, - decoder: utils.decode, - delimiter: "&", - depth: 5, - duplicates: "combine", - ignoreQueryPrefix: false, - interpretNumericEntities: false, - parameterLimit: 1e3, - parseArrays: true, - plainObjects: false, - strictDepth: false, - strictMerge: true, - strictNullHandling: false, - throwOnLimitExceeded: false - }; - var interpretNumericEntities = function(str) { - return str.replace(/&#(\d+);/g, function($0, numberStr) { - return String.fromCharCode(parseInt(numberStr, 10)); - }); - }; - var parseArrayValue = function(val, options, currentArrayLength) { - if (val && typeof val === "string" && options.comma && val.indexOf(",") > -1) { - return val.split(","); - } - if (options.throwOnLimitExceeded && currentArrayLength >= options.arrayLimit) { - throw new RangeError("Array limit exceeded. Only " + options.arrayLimit + " element" + (options.arrayLimit === 1 ? "" : "s") + " allowed in an array."); - } - return val; - }; - var isoSentinel = "utf8=%26%2310003%3B"; - var charsetSentinel = "utf8=%E2%9C%93"; - var parseValues = function parseQueryStringValues(str, options) { - var obj = { __proto__: null }; - var cleanStr = options.ignoreQueryPrefix ? str.replace(/^\?/, "") : str; - cleanStr = cleanStr.replace(/%5B/gi, "[").replace(/%5D/gi, "]"); - var limit = options.parameterLimit === Infinity ? void 0 : options.parameterLimit; - var parts = cleanStr.split( - options.delimiter, - options.throwOnLimitExceeded && typeof limit !== "undefined" ? limit + 1 : limit - ); - if (options.throwOnLimitExceeded && typeof limit !== "undefined" && parts.length > limit) { - throw new RangeError("Parameter limit exceeded. Only " + limit + " parameter" + (limit === 1 ? "" : "s") + " allowed."); - } - var skipIndex = -1; - var i5; - var charset = options.charset; - if (options.charsetSentinel) { - for (i5 = 0; i5 < parts.length; ++i5) { - if (parts[i5].indexOf("utf8=") === 0) { - if (parts[i5] === charsetSentinel) { - charset = "utf-8"; - } else if (parts[i5] === isoSentinel) { - charset = "iso-8859-1"; - } - skipIndex = i5; - i5 = parts.length; - } - } - } - for (i5 = 0; i5 < parts.length; ++i5) { - if (i5 === skipIndex) { - continue; - } - var part = parts[i5]; - var bracketEqualsPos = part.indexOf("]="); - var pos = bracketEqualsPos === -1 ? part.indexOf("=") : bracketEqualsPos + 1; - var key; - var val; - if (pos === -1) { - key = options.decoder(part, defaults.decoder, charset, "key"); - val = options.strictNullHandling ? null : ""; - } else { - key = options.decoder(part.slice(0, pos), defaults.decoder, charset, "key"); - if (key !== null) { - val = utils.maybeMap( - parseArrayValue( - part.slice(pos + 1), - options, - isArray(obj[key]) ? obj[key].length : 0 - ), - function(encodedVal) { - return options.decoder(encodedVal, defaults.decoder, charset, "value"); - } - ); - } - } - if (val && options.interpretNumericEntities && charset === "iso-8859-1") { - val = interpretNumericEntities(String(val)); - } - if (part.indexOf("[]=") > -1) { - val = isArray(val) ? [val] : val; - } - if (options.comma && isArray(val) && val.length > options.arrayLimit) { - if (options.throwOnLimitExceeded) { - throw new RangeError("Array limit exceeded. Only " + options.arrayLimit + " element" + (options.arrayLimit === 1 ? "" : "s") + " allowed in an array."); - } - val = utils.combine([], val, options.arrayLimit, options.plainObjects); - } - if (key !== null) { - var existing = has.call(obj, key); - if (existing && (options.duplicates === "combine" || part.indexOf("[]=") > -1)) { - obj[key] = utils.combine( - obj[key], - val, - options.arrayLimit, - options.plainObjects - ); - } else if (!existing || options.duplicates === "last") { - obj[key] = val; - } - } - } - return obj; - }; - var parseObject5 = function(chain, val, options, valuesParsed) { - var currentArrayLength = 0; - if (chain.length > 0 && chain[chain.length - 1] === "[]") { - var parentKey = chain.slice(0, -1).join(""); - currentArrayLength = Array.isArray(val) && val[parentKey] ? val[parentKey].length : 0; - } - var leaf = valuesParsed ? val : parseArrayValue(val, options, currentArrayLength); - for (var i5 = chain.length - 1; i5 >= 0; --i5) { - var obj; - var root = chain[i5]; - if (root === "[]" && options.parseArrays) { - if (utils.isOverflow(leaf)) { - obj = leaf; - } else { - obj = options.allowEmptyArrays && (leaf === "" || options.strictNullHandling && leaf === null) ? [] : utils.combine( - [], - leaf, - options.arrayLimit, - options.plainObjects - ); - } - } else { - obj = options.plainObjects ? { __proto__: null } : {}; - var cleanRoot = root.charAt(0) === "[" && root.charAt(root.length - 1) === "]" ? root.slice(1, -1) : root; - var decodedRoot = options.decodeDotInKeys ? cleanRoot.replace(/%2E/g, ".") : cleanRoot; - var index2 = parseInt(decodedRoot, 10); - var isValidArrayIndex = !isNaN(index2) && root !== decodedRoot && String(index2) === decodedRoot && index2 >= 0 && options.parseArrays; - if (!options.parseArrays && decodedRoot === "") { - obj = { 0: leaf }; - } else if (isValidArrayIndex && index2 < options.arrayLimit) { - obj = []; - obj[index2] = leaf; - } else if (isValidArrayIndex && options.throwOnLimitExceeded) { - throw new RangeError("Array limit exceeded. Only " + options.arrayLimit + " element" + (options.arrayLimit === 1 ? "" : "s") + " allowed in an array."); - } else if (isValidArrayIndex) { - obj[index2] = leaf; - utils.markOverflow(obj, index2); - } else if (decodedRoot !== "__proto__") { - obj[decodedRoot] = leaf; - } - } - leaf = obj; - } - return leaf; - }; - var splitKeyIntoSegments = function splitKeyIntoSegments2(givenKey, options) { - var key = options.allowDots ? givenKey.replace(/\.([^.[]+)/g, "[$1]") : givenKey; - if (options.depth <= 0) { - if (!options.plainObjects && has.call(Object.prototype, key)) { - if (!options.allowPrototypes) { - return; - } - } - return [key]; - } - var brackets = /(\[[^[\]]*])/; - var child = /(\[[^[\]]*])/g; - var segment = brackets.exec(key); - var parent = segment ? key.slice(0, segment.index) : key; - var keys = []; - if (parent) { - if (!options.plainObjects && has.call(Object.prototype, parent)) { - if (!options.allowPrototypes) { - return; - } - } - keys[keys.length] = parent; - } - var i5 = 0; - while ((segment = child.exec(key)) !== null && i5 < options.depth) { - i5 += 1; - var segmentContent = segment[1].slice(1, -1); - if (!options.plainObjects && has.call(Object.prototype, segmentContent)) { - if (!options.allowPrototypes) { - return; - } - } - keys[keys.length] = segment[1]; - } - if (segment) { - if (options.strictDepth === true) { - throw new RangeError("Input depth exceeded depth option of " + options.depth + " and strictDepth is true"); - } - keys[keys.length] = "[" + key.slice(segment.index) + "]"; - } - return keys; - }; - var parseKeys = function parseQueryStringKeys(givenKey, val, options, valuesParsed) { - if (!givenKey) { - return; - } - var keys = splitKeyIntoSegments(givenKey, options); - if (!keys) { - return; - } - return parseObject5(keys, val, options, valuesParsed); - }; - var normalizeParseOptions = function normalizeParseOptions2(opts) { - if (!opts) { - return defaults; - } - if (typeof opts.allowEmptyArrays !== "undefined" && typeof opts.allowEmptyArrays !== "boolean") { - throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided"); - } - if (typeof opts.decodeDotInKeys !== "undefined" && typeof opts.decodeDotInKeys !== "boolean") { - throw new TypeError("`decodeDotInKeys` option can only be `true` or `false`, when provided"); - } - if (opts.decoder !== null && typeof opts.decoder !== "undefined" && typeof opts.decoder !== "function") { - throw new TypeError("Decoder has to be a function."); - } - if (typeof opts.charset !== "undefined" && opts.charset !== "utf-8" && opts.charset !== "iso-8859-1") { - throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined"); - } - if (typeof opts.throwOnLimitExceeded !== "undefined" && typeof opts.throwOnLimitExceeded !== "boolean") { - throw new TypeError("`throwOnLimitExceeded` option must be a boolean"); - } - var charset = typeof opts.charset === "undefined" ? defaults.charset : opts.charset; - var duplicates = typeof opts.duplicates === "undefined" ? defaults.duplicates : opts.duplicates; - if (duplicates !== "combine" && duplicates !== "first" && duplicates !== "last") { - throw new TypeError("The duplicates option must be either combine, first, or last"); - } - var allowDots = typeof opts.allowDots === "undefined" ? opts.decodeDotInKeys === true ? true : defaults.allowDots : !!opts.allowDots; - return { - allowDots, - allowEmptyArrays: typeof opts.allowEmptyArrays === "boolean" ? !!opts.allowEmptyArrays : defaults.allowEmptyArrays, - allowPrototypes: typeof opts.allowPrototypes === "boolean" ? opts.allowPrototypes : defaults.allowPrototypes, - allowSparse: typeof opts.allowSparse === "boolean" ? opts.allowSparse : defaults.allowSparse, - arrayLimit: typeof opts.arrayLimit === "number" ? opts.arrayLimit : defaults.arrayLimit, - charset, - charsetSentinel: typeof opts.charsetSentinel === "boolean" ? opts.charsetSentinel : defaults.charsetSentinel, - comma: typeof opts.comma === "boolean" ? opts.comma : defaults.comma, - decodeDotInKeys: typeof opts.decodeDotInKeys === "boolean" ? opts.decodeDotInKeys : defaults.decodeDotInKeys, - decoder: typeof opts.decoder === "function" ? opts.decoder : defaults.decoder, - delimiter: typeof opts.delimiter === "string" || utils.isRegExp(opts.delimiter) ? opts.delimiter : defaults.delimiter, - // eslint-disable-next-line no-implicit-coercion, no-extra-parens - depth: typeof opts.depth === "number" || opts.depth === false ? +opts.depth : defaults.depth, - duplicates, - ignoreQueryPrefix: opts.ignoreQueryPrefix === true, - interpretNumericEntities: typeof opts.interpretNumericEntities === "boolean" ? opts.interpretNumericEntities : defaults.interpretNumericEntities, - parameterLimit: typeof opts.parameterLimit === "number" ? opts.parameterLimit : defaults.parameterLimit, - parseArrays: opts.parseArrays !== false, - plainObjects: typeof opts.plainObjects === "boolean" ? opts.plainObjects : defaults.plainObjects, - strictDepth: typeof opts.strictDepth === "boolean" ? !!opts.strictDepth : defaults.strictDepth, - strictMerge: typeof opts.strictMerge === "boolean" ? !!opts.strictMerge : defaults.strictMerge, - strictNullHandling: typeof opts.strictNullHandling === "boolean" ? opts.strictNullHandling : defaults.strictNullHandling, - throwOnLimitExceeded: typeof opts.throwOnLimitExceeded === "boolean" ? opts.throwOnLimitExceeded : false - }; - }; - module.exports = function(str, opts) { - var options = normalizeParseOptions(opts); - if (str === "" || str === null || typeof str === "undefined") { - return options.plainObjects ? { __proto__: null } : {}; - } - var tempObj = typeof str === "string" ? parseValues(str, options) : str; - var obj = options.plainObjects ? { __proto__: null } : {}; - var keys = Object.keys(tempObj); - for (var i5 = 0; i5 < keys.length; ++i5) { - var key = keys[i5]; - var newObj = parseKeys(key, tempObj[key], options, typeof str === "string"); - obj = utils.merge(obj, newObj, options); - } - if (options.allowSparse === true) { - return obj; - } - return utils.compact(obj); - }; - } -}); - -// node_modules/.pnpm/qs@6.15.1/node_modules/qs/lib/index.js -var require_lib2 = __commonJS({ - "node_modules/.pnpm/qs@6.15.1/node_modules/qs/lib/index.js"(exports, module) { - "use strict"; - var stringify2 = require_stringify(); - var parse5 = require_parse(); - var formats = require_formats(); - module.exports = { - formats, - parse: parse5, - stringify: stringify2 - }; - } -}); - -// node_modules/.pnpm/body-parser@2.2.2/node_modules/body-parser/lib/types/urlencoded.js -var require_urlencoded = __commonJS({ - "node_modules/.pnpm/body-parser@2.2.2/node_modules/body-parser/lib/types/urlencoded.js"(exports, module) { - "use strict"; - var createError = require_http_errors(); - var debug = require_src()("body-parser:urlencoded"); - var read = require_read(); - var qs = require_lib2(); - var { normalizeOptions } = require_utils(); - module.exports = urlencoded; - function urlencoded(options) { - const normalizedOptions = normalizeOptions(options, "application/x-www-form-urlencoded"); - if (normalizedOptions.defaultCharset !== "utf-8" && normalizedOptions.defaultCharset !== "iso-8859-1") { - throw new TypeError("option defaultCharset must be either utf-8 or iso-8859-1"); - } - var queryparse = createQueryParser(options); - function parse5(body, encoding) { - return body.length ? queryparse(body, encoding) : {}; - } - const readOptions = { - ...normalizedOptions, - // assert charset - isValidCharset: (charset) => charset === "utf-8" || charset === "iso-8859-1" - }; - return function urlencodedParser(req, res, next) { - read(req, res, next, parse5, debug, readOptions); - }; - } - function createQueryParser(options) { - var extended = Boolean(options?.extended); - var parameterLimit = options?.parameterLimit !== void 0 ? options?.parameterLimit : 1e3; - var charsetSentinel = options?.charsetSentinel; - var interpretNumericEntities = options?.interpretNumericEntities; - var depth = extended ? options?.depth !== void 0 ? options?.depth : 32 : 0; - if (isNaN(parameterLimit) || parameterLimit < 1) { - throw new TypeError("option parameterLimit must be a positive number"); - } - if (isNaN(depth) || depth < 0) { - throw new TypeError("option depth must be a zero or a positive number"); - } - if (isFinite(parameterLimit)) { - parameterLimit = parameterLimit | 0; - } - return function queryparse(body, encoding) { - var paramCount = parameterCount(body, parameterLimit); - if (paramCount === void 0) { - debug("too many parameters"); - throw createError(413, "too many parameters", { - type: "parameters.too.many" - }); - } - var arrayLimit = extended ? Math.max(100, paramCount) : paramCount; - debug("parse " + (extended ? "extended " : "") + "urlencoding"); - try { - return qs.parse(body, { - allowPrototypes: true, - arrayLimit, - depth, - charsetSentinel, - interpretNumericEntities, - charset: encoding, - parameterLimit, - strictDepth: true - }); - } catch (err) { - if (err instanceof RangeError) { - throw createError(400, "The input exceeded the depth", { - type: "querystring.parse.rangeError" - }); - } else { - throw err; - } - } - }; - } - function parameterCount(body, limit) { - let count2 = 0; - let index2 = -1; - do { - count2++; - if (count2 > limit) return void 0; - index2 = body.indexOf("&", index2 + 1); - } while (index2 !== -1); - return count2; - } - } -}); - -// node_modules/.pnpm/body-parser@2.2.2/node_modules/body-parser/index.js -var require_body_parser = __commonJS({ - "node_modules/.pnpm/body-parser@2.2.2/node_modules/body-parser/index.js"(exports, module) { - "use strict"; - exports = module.exports = bodyParser; - Object.defineProperty(exports, "json", { - configurable: true, - enumerable: true, - get: () => require_json() - }); - Object.defineProperty(exports, "raw", { - configurable: true, - enumerable: true, - get: () => require_raw() - }); - Object.defineProperty(exports, "text", { - configurable: true, - enumerable: true, - get: () => require_text() - }); - Object.defineProperty(exports, "urlencoded", { - configurable: true, - enumerable: true, - get: () => require_urlencoded() - }); - function bodyParser() { - throw new Error("The bodyParser() generic has been split into individual middleware to use instead."); - } - } -}); - -// node_modules/.pnpm/merge-descriptors@2.0.0/node_modules/merge-descriptors/index.js -var require_merge_descriptors = __commonJS({ - "node_modules/.pnpm/merge-descriptors@2.0.0/node_modules/merge-descriptors/index.js"(exports, module) { - "use strict"; - function mergeDescriptors(destination, source, overwrite = true) { - if (!destination) { - throw new TypeError("The `destination` argument is required."); - } - if (!source) { - throw new TypeError("The `source` argument is required."); - } - for (const name of Object.getOwnPropertyNames(source)) { - if (!overwrite && Object.hasOwn(destination, name)) { - continue; - } - const descriptor = Object.getOwnPropertyDescriptor(source, name); - Object.defineProperty(destination, name, descriptor); - } - return destination; - } - module.exports = mergeDescriptors; - } -}); - -// node_modules/.pnpm/encodeurl@2.0.0/node_modules/encodeurl/index.js -var require_encodeurl = __commonJS({ - "node_modules/.pnpm/encodeurl@2.0.0/node_modules/encodeurl/index.js"(exports, module) { - "use strict"; - module.exports = encodeUrl; - var ENCODE_CHARS_REGEXP = /(?:[^\x21\x23-\x3B\x3D\x3F-\x5F\x61-\x7A\x7C\x7E]|%(?:[^0-9A-Fa-f]|[0-9A-Fa-f][^0-9A-Fa-f]|$))+/g; - var UNMATCHED_SURROGATE_PAIR_REGEXP = /(^|[^\uD800-\uDBFF])[\uDC00-\uDFFF]|[\uD800-\uDBFF]([^\uDC00-\uDFFF]|$)/g; - var UNMATCHED_SURROGATE_PAIR_REPLACE = "$1\uFFFD$2"; - function encodeUrl(url2) { - return String(url2).replace(UNMATCHED_SURROGATE_PAIR_REGEXP, UNMATCHED_SURROGATE_PAIR_REPLACE).replace(ENCODE_CHARS_REGEXP, encodeURI); - } - } -}); - -// node_modules/.pnpm/escape-html@1.0.3/node_modules/escape-html/index.js -var require_escape_html = __commonJS({ - "node_modules/.pnpm/escape-html@1.0.3/node_modules/escape-html/index.js"(exports, module) { - "use strict"; - var matchHtmlRegExp = /["'&<>]/; - module.exports = escapeHtml; - function escapeHtml(string4) { - var str = "" + string4; - var match = matchHtmlRegExp.exec(str); - if (!match) { - return str; - } - var escape3; - var html3 = ""; - var index2 = 0; - var lastIndex = 0; - for (index2 = match.index; index2 < str.length; index2++) { - switch (str.charCodeAt(index2)) { - case 34: - escape3 = """; - break; - case 38: - escape3 = "&"; - break; - case 39: - escape3 = "'"; - break; - case 60: - escape3 = "<"; - break; - case 62: - escape3 = ">"; - break; - default: - continue; - } - if (lastIndex !== index2) { - html3 += str.substring(lastIndex, index2); - } - lastIndex = index2 + 1; - html3 += escape3; - } - return lastIndex !== index2 ? html3 + str.substring(lastIndex, index2) : html3; - } - } -}); - -// node_modules/.pnpm/parseurl@1.3.3/node_modules/parseurl/index.js -var require_parseurl = __commonJS({ - "node_modules/.pnpm/parseurl@1.3.3/node_modules/parseurl/index.js"(exports, module) { - "use strict"; - var url2 = __require("url"); - var parse5 = url2.parse; - var Url = url2.Url; - module.exports = parseurl; - module.exports.original = originalurl; - function parseurl(req) { - var url3 = req.url; - if (url3 === void 0) { - return void 0; - } - var parsed = req._parsedUrl; - if (fresh(url3, parsed)) { - return parsed; - } - parsed = fastparse(url3); - parsed._raw = url3; - return req._parsedUrl = parsed; - } - function originalurl(req) { - var url3 = req.originalUrl; - if (typeof url3 !== "string") { - return parseurl(req); - } - var parsed = req._parsedOriginalUrl; - if (fresh(url3, parsed)) { - return parsed; - } - parsed = fastparse(url3); - parsed._raw = url3; - return req._parsedOriginalUrl = parsed; - } - function fastparse(str) { - if (typeof str !== "string" || str.charCodeAt(0) !== 47) { - return parse5(str); - } - var pathname = str; - var query = null; - var search = null; - for (var i5 = 1; i5 < str.length; i5++) { - switch (str.charCodeAt(i5)) { - case 63: - if (search === null) { - pathname = str.substring(0, i5); - query = str.substring(i5 + 1); - search = str.substring(i5); - } - break; - case 9: - /* \t */ - case 10: - /* \n */ - case 12: - /* \f */ - case 13: - /* \r */ - case 32: - /* */ - case 35: - /* # */ - case 160: - case 65279: - return parse5(str); - } - } - var url3 = Url !== void 0 ? new Url() : {}; - url3.path = str; - url3.href = str; - url3.pathname = pathname; - if (search !== null) { - url3.query = query; - url3.search = search; - } - return url3; - } - function fresh(url3, parsedUrl) { - return typeof parsedUrl === "object" && parsedUrl !== null && (Url === void 0 || parsedUrl instanceof Url) && parsedUrl._raw === url3; - } - } -}); - -// node_modules/.pnpm/finalhandler@2.1.1/node_modules/finalhandler/index.js -var require_finalhandler = __commonJS({ - "node_modules/.pnpm/finalhandler@2.1.1/node_modules/finalhandler/index.js"(exports, module) { - "use strict"; - var debug = require_src()("finalhandler"); - var encodeUrl = require_encodeurl(); - var escapeHtml = require_escape_html(); - var onFinished = require_on_finished(); - var parseUrl7 = require_parseurl(); - var statuses = require_statuses(); - var isFinished = onFinished.isFinished; - function createHtmlDocument(message2) { - var body = escapeHtml(message2).replaceAll("\n", "
").replaceAll(" ", "  "); - return '\n\n\n\nError\n\n\n
' + body + "
\n\n\n"; - } - module.exports = finalhandler; - function finalhandler(req, res, options) { - var opts = options || {}; - var env2 = opts.env || "production"; - var onerror = opts.onerror; - return function(err) { - var headers; - var msg; - var status; - if (!err && res.headersSent) { - debug("cannot 404 after headers sent"); - return; - } - if (err) { - status = getErrorStatusCode(err); - if (status === void 0) { - status = getResponseStatusCode(res); - } else { - headers = getErrorHeaders(err); - } - msg = getErrorMessage(err, status, env2); - } else { - status = 404; - msg = "Cannot " + req.method + " " + encodeUrl(getResourceName(req)); - } - debug("default %s", status); - if (err && onerror) { - setImmediate(onerror, err, req, res); - } - if (res.headersSent) { - debug("cannot %d after headers sent", status); - if (req.socket) { - req.socket.destroy(); - } - return; - } - send(req, res, status, headers, msg); - }; - } - function getErrorHeaders(err) { - if (!err.headers || typeof err.headers !== "object") { - return void 0; - } - return { ...err.headers }; - } - function getErrorMessage(err, status, env2) { - var msg; - if (env2 !== "production") { - msg = err.stack; - if (!msg && typeof err.toString === "function") { - msg = err.toString(); - } - } - return msg || statuses.message[status]; - } - function getErrorStatusCode(err) { - if (typeof err.status === "number" && err.status >= 400 && err.status < 600) { - return err.status; - } - if (typeof err.statusCode === "number" && err.statusCode >= 400 && err.statusCode < 600) { - return err.statusCode; - } - return void 0; - } - function getResourceName(req) { - try { - return parseUrl7.original(req).pathname; - } catch (e5) { - return "resource"; - } - } - function getResponseStatusCode(res) { - var status = res.statusCode; - if (typeof status !== "number" || status < 400 || status > 599) { - status = 500; - } - return status; - } - function send(req, res, status, headers, message2) { - function write() { - var body = createHtmlDocument(message2); - res.statusCode = status; - if (req.httpVersionMajor < 2) { - res.statusMessage = statuses.message[status]; - } - res.removeHeader("Content-Encoding"); - res.removeHeader("Content-Language"); - res.removeHeader("Content-Range"); - for (const [key, value] of Object.entries(headers ?? {})) { - res.setHeader(key, value); - } - res.setHeader("Content-Security-Policy", "default-src 'none'"); - res.setHeader("X-Content-Type-Options", "nosniff"); - res.setHeader("Content-Type", "text/html; charset=utf-8"); - res.setHeader("Content-Length", Buffer.byteLength(body, "utf8")); - if (req.method === "HEAD") { - res.end(); - return; - } - res.end(body, "utf8"); - } - if (isFinished(req)) { - write(); - return; - } - req.unpipe(); - onFinished(req, write); - req.resume(); - } - } -}); - -// node_modules/.pnpm/express@5.2.1/node_modules/express/lib/view.js -var require_view = __commonJS({ - "node_modules/.pnpm/express@5.2.1/node_modules/express/lib/view.js"(exports, module) { - "use strict"; - var debug = require_src()("express:view"); - var path53 = __require("node:path"); - var fs41 = __require("node:fs"); - var dirname3 = path53.dirname; - var basename3 = path53.basename; - var extname2 = path53.extname; - var join4 = path53.join; - var resolve4 = path53.resolve; - module.exports = View2; - function View2(name, options) { - var opts = options || {}; - this.defaultEngine = opts.defaultEngine; - this.ext = extname2(name); - this.name = name; - this.root = opts.root; - if (!this.ext && !this.defaultEngine) { - throw new Error("No default engine was specified and no extension was provided."); - } - var fileName = name; - if (!this.ext) { - this.ext = this.defaultEngine[0] !== "." ? "." + this.defaultEngine : this.defaultEngine; - fileName += this.ext; - } - if (!opts.engines[this.ext]) { - var mod = this.ext.slice(1); - debug('require "%s"', mod); - var fn = __require(mod).__express; - if (typeof fn !== "function") { - throw new Error('Module "' + mod + '" does not provide a view engine.'); - } - opts.engines[this.ext] = fn; - } - this.engine = opts.engines[this.ext]; - this.path = this.lookup(fileName); - } - View2.prototype.lookup = function lookup(name) { - var path54; - var roots = [].concat(this.root); - debug('lookup "%s"', name); - for (var i5 = 0; i5 < roots.length && !path54; i5++) { - var root = roots[i5]; - var loc = resolve4(root, name); - var dir = dirname3(loc); - var file2 = basename3(loc); - path54 = this.resolve(dir, file2); - } - return path54; - }; - View2.prototype.render = function render(options, callback) { - var sync = true; - debug('render "%s"', this.path); - this.engine(this.path, options, function onRender() { - if (!sync) { - return callback.apply(this, arguments); - } - var args = new Array(arguments.length); - var cntx = this; - for (var i5 = 0; i5 < arguments.length; i5++) { - args[i5] = arguments[i5]; - } - return process.nextTick(function renderTick() { - return callback.apply(cntx, args); - }); - }); - sync = false; - }; - View2.prototype.resolve = function resolve5(dir, file2) { - var ext = this.ext; - var path54 = join4(dir, file2); - var stat5 = tryStat(path54); - if (stat5 && stat5.isFile()) { - return path54; - } - path54 = join4(dir, basename3(file2, ext), "index" + ext); - stat5 = tryStat(path54); - if (stat5 && stat5.isFile()) { - return path54; - } - }; - function tryStat(path54) { - debug('stat "%s"', path54); - try { - return fs41.statSync(path54); - } catch (e5) { - return void 0; - } - } - } -}); - -// node_modules/.pnpm/etag@1.8.1/node_modules/etag/index.js -var require_etag = __commonJS({ - "node_modules/.pnpm/etag@1.8.1/node_modules/etag/index.js"(exports, module) { - "use strict"; - module.exports = etag; - var crypto6 = __require("crypto"); - var Stats = __require("fs").Stats; - var toString = Object.prototype.toString; - function entitytag(entity) { - if (entity.length === 0) { - return '"0-2jmj7l5rSw0yVb/vlWAYkK/YBwk"'; - } - var hash2 = crypto6.createHash("sha1").update(entity, "utf8").digest("base64").substring(0, 27); - var len = typeof entity === "string" ? Buffer.byteLength(entity, "utf8") : entity.length; - return '"' + len.toString(16) + "-" + hash2 + '"'; - } - function etag(entity, options) { - if (entity == null) { - throw new TypeError("argument entity is required"); - } - var isStats = isstats(entity); - var weak = options && typeof options.weak === "boolean" ? options.weak : isStats; - if (!isStats && typeof entity !== "string" && !Buffer.isBuffer(entity)) { - throw new TypeError("argument entity must be string, Buffer, or fs.Stats"); - } - var tag3 = isStats ? stattag(entity) : entitytag(entity); - return weak ? "W/" + tag3 : tag3; - } - function isstats(obj) { - if (typeof Stats === "function" && obj instanceof Stats) { - return true; - } - return obj && typeof obj === "object" && "ctime" in obj && toString.call(obj.ctime) === "[object Date]" && "mtime" in obj && toString.call(obj.mtime) === "[object Date]" && "ino" in obj && typeof obj.ino === "number" && "size" in obj && typeof obj.size === "number"; - } - function stattag(stat5) { - var mtime = stat5.mtime.getTime().toString(16); - var size2 = stat5.size.toString(16); - return '"' + size2 + "-" + mtime + '"'; - } - } -}); - -// node_modules/.pnpm/forwarded@0.2.0/node_modules/forwarded/index.js -var require_forwarded = __commonJS({ - "node_modules/.pnpm/forwarded@0.2.0/node_modules/forwarded/index.js"(exports, module) { - "use strict"; - module.exports = forwarded; - function forwarded(req) { - if (!req) { - throw new TypeError("argument req is required"); - } - var proxyAddrs = parse5(req.headers["x-forwarded-for"] || ""); - var socketAddr = getSocketAddr(req); - var addrs = [socketAddr].concat(proxyAddrs); - return addrs; - } - function getSocketAddr(req) { - return req.socket ? req.socket.remoteAddress : req.connection.remoteAddress; - } - function parse5(header) { - var end = header.length; - var list2 = []; - var start = header.length; - for (var i5 = header.length - 1; i5 >= 0; i5--) { - switch (header.charCodeAt(i5)) { - case 32: - if (start === end) { - start = end = i5; - } - break; - case 44: - if (start !== end) { - list2.push(header.substring(start, end)); - } - start = end = i5; - break; - default: - start = i5; - break; - } - } - if (start !== end) { - list2.push(header.substring(start, end)); - } - return list2; - } - } -}); - -// node_modules/.pnpm/ipaddr.js@1.9.1/node_modules/ipaddr.js/lib/ipaddr.js -var require_ipaddr = __commonJS({ - "node_modules/.pnpm/ipaddr.js@1.9.1/node_modules/ipaddr.js/lib/ipaddr.js"(exports, module) { - (function() { - var expandIPv62, ipaddr, ipv4Part, ipv4Regexes, ipv6Part, ipv6Regexes, matchCIDR, root, zoneIndex; - ipaddr = {}; - root = this; - if (typeof module !== "undefined" && module !== null && module.exports) { - module.exports = ipaddr; - } else { - root["ipaddr"] = ipaddr; - } - matchCIDR = function(first, second, partSize, cidrBits) { - var part, shift; - if (first.length !== second.length) { - throw new Error("ipaddr: cannot match CIDR for objects with different lengths"); - } - part = 0; - while (cidrBits > 0) { - shift = partSize - cidrBits; - if (shift < 0) { - shift = 0; - } - if (first[part] >> shift !== second[part] >> shift) { - return false; - } - cidrBits -= partSize; - part += 1; - } - return true; - }; - ipaddr.subnetMatch = function(address, rangeList, defaultName) { - var k5, len, rangeName, rangeSubnets, subnet; - if (defaultName == null) { - defaultName = "unicast"; - } - for (rangeName in rangeList) { - rangeSubnets = rangeList[rangeName]; - if (rangeSubnets[0] && !(rangeSubnets[0] instanceof Array)) { - rangeSubnets = [rangeSubnets]; - } - for (k5 = 0, len = rangeSubnets.length; k5 < len; k5++) { - subnet = rangeSubnets[k5]; - if (address.kind() === subnet[0].kind()) { - if (address.match.apply(address, subnet)) { - return rangeName; - } - } - } - } - return defaultName; - }; - ipaddr.IPv4 = (function() { - function IPv4(octets) { - var k5, len, octet; - if (octets.length !== 4) { - throw new Error("ipaddr: ipv4 octet count should be 4"); - } - for (k5 = 0, len = octets.length; k5 < len; k5++) { - octet = octets[k5]; - if (!(0 <= octet && octet <= 255)) { - throw new Error("ipaddr: ipv4 octet should fit in 8 bits"); - } - } - this.octets = octets; - } - IPv4.prototype.kind = function() { - return "ipv4"; - }; - IPv4.prototype.toString = function() { - return this.octets.join("."); - }; - IPv4.prototype.toNormalizedString = function() { - return this.toString(); - }; - IPv4.prototype.toByteArray = function() { - return this.octets.slice(0); - }; - IPv4.prototype.match = function(other, cidrRange) { - var ref; - if (cidrRange === void 0) { - ref = other, other = ref[0], cidrRange = ref[1]; - } - if (other.kind() !== "ipv4") { - throw new Error("ipaddr: cannot match ipv4 address with non-ipv4 one"); - } - return matchCIDR(this.octets, other.octets, 8, cidrRange); - }; - IPv4.prototype.SpecialRanges = { - unspecified: [[new IPv4([0, 0, 0, 0]), 8]], - broadcast: [[new IPv4([255, 255, 255, 255]), 32]], - multicast: [[new IPv4([224, 0, 0, 0]), 4]], - linkLocal: [[new IPv4([169, 254, 0, 0]), 16]], - loopback: [[new IPv4([127, 0, 0, 0]), 8]], - carrierGradeNat: [[new IPv4([100, 64, 0, 0]), 10]], - "private": [[new IPv4([10, 0, 0, 0]), 8], [new IPv4([172, 16, 0, 0]), 12], [new IPv4([192, 168, 0, 0]), 16]], - reserved: [[new IPv4([192, 0, 0, 0]), 24], [new IPv4([192, 0, 2, 0]), 24], [new IPv4([192, 88, 99, 0]), 24], [new IPv4([198, 51, 100, 0]), 24], [new IPv4([203, 0, 113, 0]), 24], [new IPv4([240, 0, 0, 0]), 4]] - }; - IPv4.prototype.range = function() { - return ipaddr.subnetMatch(this, this.SpecialRanges); - }; - IPv4.prototype.toIPv4MappedAddress = function() { - return ipaddr.IPv6.parse("::ffff:" + this.toString()); - }; - IPv4.prototype.prefixLengthFromSubnetMask = function() { - var cidr2, i5, k5, octet, stop, zeros, zerotable; - zerotable = { - 0: 8, - 128: 7, - 192: 6, - 224: 5, - 240: 4, - 248: 3, - 252: 2, - 254: 1, - 255: 0 - }; - cidr2 = 0; - stop = false; - for (i5 = k5 = 3; k5 >= 0; i5 = k5 += -1) { - octet = this.octets[i5]; - if (octet in zerotable) { - zeros = zerotable[octet]; - if (stop && zeros !== 0) { - return null; - } - if (zeros !== 8) { - stop = true; - } - cidr2 += zeros; - } else { - return null; - } - } - return 32 - cidr2; - }; - return IPv4; - })(); - ipv4Part = "(0?\\d+|0x[a-f0-9]+)"; - ipv4Regexes = { - fourOctet: new RegExp("^" + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "$", "i"), - longValue: new RegExp("^" + ipv4Part + "$", "i") - }; - ipaddr.IPv4.parser = function(string4) { - var match, parseIntAuto, part, shift, value; - parseIntAuto = function(string5) { - if (string5[0] === "0" && string5[1] !== "x") { - return parseInt(string5, 8); - } else { - return parseInt(string5); - } - }; - if (match = string4.match(ipv4Regexes.fourOctet)) { - return (function() { - var k5, len, ref, results; - ref = match.slice(1, 6); - results = []; - for (k5 = 0, len = ref.length; k5 < len; k5++) { - part = ref[k5]; - results.push(parseIntAuto(part)); - } - return results; - })(); - } else if (match = string4.match(ipv4Regexes.longValue)) { - value = parseIntAuto(match[1]); - if (value > 4294967295 || value < 0) { - throw new Error("ipaddr: address outside defined range"); - } - return (function() { - var k5, results; - results = []; - for (shift = k5 = 0; k5 <= 24; shift = k5 += 8) { - results.push(value >> shift & 255); - } - return results; - })().reverse(); - } else { - return null; - } - }; - ipaddr.IPv6 = (function() { - function IPv6(parts, zoneId) { - var i5, k5, l5, len, part, ref; - if (parts.length === 16) { - this.parts = []; - for (i5 = k5 = 0; k5 <= 14; i5 = k5 += 2) { - this.parts.push(parts[i5] << 8 | parts[i5 + 1]); - } - } else if (parts.length === 8) { - this.parts = parts; - } else { - throw new Error("ipaddr: ipv6 part count should be 8 or 16"); - } - ref = this.parts; - for (l5 = 0, len = ref.length; l5 < len; l5++) { - part = ref[l5]; - if (!(0 <= part && part <= 65535)) { - throw new Error("ipaddr: ipv6 part should fit in 16 bits"); - } - } - if (zoneId) { - this.zoneId = zoneId; - } - } - IPv6.prototype.kind = function() { - return "ipv6"; - }; - IPv6.prototype.toString = function() { - return this.toNormalizedString().replace(/((^|:)(0(:|$))+)/, "::"); - }; - IPv6.prototype.toRFC5952String = function() { - var bestMatchIndex, bestMatchLength, match, regex, string4; - regex = /((^|:)(0(:|$)){2,})/g; - string4 = this.toNormalizedString(); - bestMatchIndex = 0; - bestMatchLength = -1; - while (match = regex.exec(string4)) { - if (match[0].length > bestMatchLength) { - bestMatchIndex = match.index; - bestMatchLength = match[0].length; - } - } - if (bestMatchLength < 0) { - return string4; - } - return string4.substring(0, bestMatchIndex) + "::" + string4.substring(bestMatchIndex + bestMatchLength); - }; - IPv6.prototype.toByteArray = function() { - var bytes, k5, len, part, ref; - bytes = []; - ref = this.parts; - for (k5 = 0, len = ref.length; k5 < len; k5++) { - part = ref[k5]; - bytes.push(part >> 8); - bytes.push(part & 255); - } - return bytes; - }; - IPv6.prototype.toNormalizedString = function() { - var addr, part, suffix; - addr = (function() { - var k5, len, ref, results; - ref = this.parts; - results = []; - for (k5 = 0, len = ref.length; k5 < len; k5++) { - part = ref[k5]; - results.push(part.toString(16)); - } - return results; - }).call(this).join(":"); - suffix = ""; - if (this.zoneId) { - suffix = "%" + this.zoneId; - } - return addr + suffix; - }; - IPv6.prototype.toFixedLengthString = function() { - var addr, part, suffix; - addr = (function() { - var k5, len, ref, results; - ref = this.parts; - results = []; - for (k5 = 0, len = ref.length; k5 < len; k5++) { - part = ref[k5]; - results.push(part.toString(16).padStart(4, "0")); - } - return results; - }).call(this).join(":"); - suffix = ""; - if (this.zoneId) { - suffix = "%" + this.zoneId; - } - return addr + suffix; - }; - IPv6.prototype.match = function(other, cidrRange) { - var ref; - if (cidrRange === void 0) { - ref = other, other = ref[0], cidrRange = ref[1]; - } - if (other.kind() !== "ipv6") { - throw new Error("ipaddr: cannot match ipv6 address with non-ipv6 one"); - } - return matchCIDR(this.parts, other.parts, 16, cidrRange); - }; - IPv6.prototype.SpecialRanges = { - unspecified: [new IPv6([0, 0, 0, 0, 0, 0, 0, 0]), 128], - linkLocal: [new IPv6([65152, 0, 0, 0, 0, 0, 0, 0]), 10], - multicast: [new IPv6([65280, 0, 0, 0, 0, 0, 0, 0]), 8], - loopback: [new IPv6([0, 0, 0, 0, 0, 0, 0, 1]), 128], - uniqueLocal: [new IPv6([64512, 0, 0, 0, 0, 0, 0, 0]), 7], - ipv4Mapped: [new IPv6([0, 0, 0, 0, 0, 65535, 0, 0]), 96], - rfc6145: [new IPv6([0, 0, 0, 0, 65535, 0, 0, 0]), 96], - rfc6052: [new IPv6([100, 65435, 0, 0, 0, 0, 0, 0]), 96], - "6to4": [new IPv6([8194, 0, 0, 0, 0, 0, 0, 0]), 16], - teredo: [new IPv6([8193, 0, 0, 0, 0, 0, 0, 0]), 32], - reserved: [[new IPv6([8193, 3512, 0, 0, 0, 0, 0, 0]), 32]] - }; - IPv6.prototype.range = function() { - return ipaddr.subnetMatch(this, this.SpecialRanges); - }; - IPv6.prototype.isIPv4MappedAddress = function() { - return this.range() === "ipv4Mapped"; - }; - IPv6.prototype.toIPv4Address = function() { - var high, low, ref; - if (!this.isIPv4MappedAddress()) { - throw new Error("ipaddr: trying to convert a generic ipv6 address to ipv4"); - } - ref = this.parts.slice(-2), high = ref[0], low = ref[1]; - return new ipaddr.IPv4([high >> 8, high & 255, low >> 8, low & 255]); - }; - IPv6.prototype.prefixLengthFromSubnetMask = function() { - var cidr2, i5, k5, part, stop, zeros, zerotable; - zerotable = { - 0: 16, - 32768: 15, - 49152: 14, - 57344: 13, - 61440: 12, - 63488: 11, - 64512: 10, - 65024: 9, - 65280: 8, - 65408: 7, - 65472: 6, - 65504: 5, - 65520: 4, - 65528: 3, - 65532: 2, - 65534: 1, - 65535: 0 - }; - cidr2 = 0; - stop = false; - for (i5 = k5 = 7; k5 >= 0; i5 = k5 += -1) { - part = this.parts[i5]; - if (part in zerotable) { - zeros = zerotable[part]; - if (stop && zeros !== 0) { - return null; - } - if (zeros !== 16) { - stop = true; - } - cidr2 += zeros; - } else { - return null; - } - } - return 128 - cidr2; - }; - return IPv6; - })(); - ipv6Part = "(?:[0-9a-f]+::?)+"; - zoneIndex = "%[0-9a-z]{1,}"; - ipv6Regexes = { - zoneIndex: new RegExp(zoneIndex, "i"), - "native": new RegExp("^(::)?(" + ipv6Part + ")?([0-9a-f]+)?(::)?(" + zoneIndex + ")?$", "i"), - transitional: new RegExp("^((?:" + ipv6Part + ")|(?:::)(?:" + ipv6Part + ")?)" + (ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part) + ("(" + zoneIndex + ")?$"), "i") - }; - expandIPv62 = function(string4, parts) { - var colonCount, lastColon, part, replacement, replacementCount, zoneId; - if (string4.indexOf("::") !== string4.lastIndexOf("::")) { - return null; - } - zoneId = (string4.match(ipv6Regexes["zoneIndex"]) || [])[0]; - if (zoneId) { - zoneId = zoneId.substring(1); - string4 = string4.replace(/%.+$/, ""); - } - colonCount = 0; - lastColon = -1; - while ((lastColon = string4.indexOf(":", lastColon + 1)) >= 0) { - colonCount++; - } - if (string4.substr(0, 2) === "::") { - colonCount--; - } - if (string4.substr(-2, 2) === "::") { - colonCount--; - } - if (colonCount > parts) { - return null; - } - replacementCount = parts - colonCount; - replacement = ":"; - while (replacementCount--) { - replacement += "0:"; - } - string4 = string4.replace("::", replacement); - if (string4[0] === ":") { - string4 = string4.slice(1); - } - if (string4[string4.length - 1] === ":") { - string4 = string4.slice(0, -1); - } - parts = (function() { - var k5, len, ref, results; - ref = string4.split(":"); - results = []; - for (k5 = 0, len = ref.length; k5 < len; k5++) { - part = ref[k5]; - results.push(parseInt(part, 16)); - } - return results; - })(); - return { - parts, - zoneId - }; - }; - ipaddr.IPv6.parser = function(string4) { - var addr, k5, len, match, octet, octets, zoneId; - if (ipv6Regexes["native"].test(string4)) { - return expandIPv62(string4, 8); - } else if (match = string4.match(ipv6Regexes["transitional"])) { - zoneId = match[6] || ""; - addr = expandIPv62(match[1].slice(0, -1) + zoneId, 6); - if (addr.parts) { - octets = [parseInt(match[2]), parseInt(match[3]), parseInt(match[4]), parseInt(match[5])]; - for (k5 = 0, len = octets.length; k5 < len; k5++) { - octet = octets[k5]; - if (!(0 <= octet && octet <= 255)) { - return null; - } - } - addr.parts.push(octets[0] << 8 | octets[1]); - addr.parts.push(octets[2] << 8 | octets[3]); - return { - parts: addr.parts, - zoneId: addr.zoneId - }; - } - } - return null; - }; - ipaddr.IPv4.isIPv4 = ipaddr.IPv6.isIPv6 = function(string4) { - return this.parser(string4) !== null; - }; - ipaddr.IPv4.isValid = function(string4) { - var e5; - try { - new this(this.parser(string4)); - return true; - } catch (error1) { - e5 = error1; - return false; - } - }; - ipaddr.IPv4.isValidFourPartDecimal = function(string4) { - if (ipaddr.IPv4.isValid(string4) && string4.match(/^(0|[1-9]\d*)(\.(0|[1-9]\d*)){3}$/)) { - return true; - } else { - return false; - } - }; - ipaddr.IPv6.isValid = function(string4) { - var addr, e5; - if (typeof string4 === "string" && string4.indexOf(":") === -1) { - return false; - } - try { - addr = this.parser(string4); - new this(addr.parts, addr.zoneId); - return true; - } catch (error1) { - e5 = error1; - return false; - } - }; - ipaddr.IPv4.parse = function(string4) { - var parts; - parts = this.parser(string4); - if (parts === null) { - throw new Error("ipaddr: string is not formatted like ip address"); - } - return new this(parts); - }; - ipaddr.IPv6.parse = function(string4) { - var addr; - addr = this.parser(string4); - if (addr.parts === null) { - throw new Error("ipaddr: string is not formatted like ip address"); - } - return new this(addr.parts, addr.zoneId); - }; - ipaddr.IPv4.parseCIDR = function(string4) { - var maskLength, match, parsed; - if (match = string4.match(/^(.+)\/(\d+)$/)) { - maskLength = parseInt(match[2]); - if (maskLength >= 0 && maskLength <= 32) { - parsed = [this.parse(match[1]), maskLength]; - Object.defineProperty(parsed, "toString", { - value: function() { - return this.join("/"); - } - }); - return parsed; - } - } - throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range"); - }; - ipaddr.IPv4.subnetMaskFromPrefixLength = function(prefix) { - var filledOctetCount, j5, octets; - prefix = parseInt(prefix); - if (prefix < 0 || prefix > 32) { - throw new Error("ipaddr: invalid IPv4 prefix length"); - } - octets = [0, 0, 0, 0]; - j5 = 0; - filledOctetCount = Math.floor(prefix / 8); - while (j5 < filledOctetCount) { - octets[j5] = 255; - j5++; - } - if (filledOctetCount < 4) { - octets[filledOctetCount] = Math.pow(2, prefix % 8) - 1 << 8 - prefix % 8; - } - return new this(octets); - }; - ipaddr.IPv4.broadcastAddressFromCIDR = function(string4) { - var cidr2, error50, i5, ipInterfaceOctets, octets, subnetMaskOctets; - try { - cidr2 = this.parseCIDR(string4); - ipInterfaceOctets = cidr2[0].toByteArray(); - subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr2[1]).toByteArray(); - octets = []; - i5 = 0; - while (i5 < 4) { - octets.push(parseInt(ipInterfaceOctets[i5], 10) | parseInt(subnetMaskOctets[i5], 10) ^ 255); - i5++; - } - return new this(octets); - } catch (error1) { - error50 = error1; - throw new Error("ipaddr: the address does not have IPv4 CIDR format"); - } - }; - ipaddr.IPv4.networkAddressFromCIDR = function(string4) { - var cidr2, error50, i5, ipInterfaceOctets, octets, subnetMaskOctets; - try { - cidr2 = this.parseCIDR(string4); - ipInterfaceOctets = cidr2[0].toByteArray(); - subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr2[1]).toByteArray(); - octets = []; - i5 = 0; - while (i5 < 4) { - octets.push(parseInt(ipInterfaceOctets[i5], 10) & parseInt(subnetMaskOctets[i5], 10)); - i5++; - } - return new this(octets); - } catch (error1) { - error50 = error1; - throw new Error("ipaddr: the address does not have IPv4 CIDR format"); - } - }; - ipaddr.IPv6.parseCIDR = function(string4) { - var maskLength, match, parsed; - if (match = string4.match(/^(.+)\/(\d+)$/)) { - maskLength = parseInt(match[2]); - if (maskLength >= 0 && maskLength <= 128) { - parsed = [this.parse(match[1]), maskLength]; - Object.defineProperty(parsed, "toString", { - value: function() { - return this.join("/"); - } - }); - return parsed; - } - } - throw new Error("ipaddr: string is not formatted like an IPv6 CIDR range"); - }; - ipaddr.isValid = function(string4) { - return ipaddr.IPv6.isValid(string4) || ipaddr.IPv4.isValid(string4); - }; - ipaddr.parse = function(string4) { - if (ipaddr.IPv6.isValid(string4)) { - return ipaddr.IPv6.parse(string4); - } else if (ipaddr.IPv4.isValid(string4)) { - return ipaddr.IPv4.parse(string4); - } else { - throw new Error("ipaddr: the address has neither IPv6 nor IPv4 format"); - } - }; - ipaddr.parseCIDR = function(string4) { - var e5; - try { - return ipaddr.IPv6.parseCIDR(string4); - } catch (error1) { - e5 = error1; - try { - return ipaddr.IPv4.parseCIDR(string4); - } catch (error110) { - e5 = error110; - throw new Error("ipaddr: the address has neither IPv6 nor IPv4 CIDR format"); - } - } - }; - ipaddr.fromByteArray = function(bytes) { - var length; - length = bytes.length; - if (length === 4) { - return new ipaddr.IPv4(bytes); - } else if (length === 16) { - return new ipaddr.IPv6(bytes); - } else { - throw new Error("ipaddr: the binary input is neither an IPv6 nor IPv4 address"); - } - }; - ipaddr.process = function(string4) { - var addr; - addr = this.parse(string4); - if (addr.kind() === "ipv6" && addr.isIPv4MappedAddress()) { - return addr.toIPv4Address(); - } else { - return addr; - } - }; - }).call(exports); - } -}); - -// node_modules/.pnpm/proxy-addr@2.0.7/node_modules/proxy-addr/index.js -var require_proxy_addr = __commonJS({ - "node_modules/.pnpm/proxy-addr@2.0.7/node_modules/proxy-addr/index.js"(exports, module) { - "use strict"; - module.exports = proxyaddr; - module.exports.all = alladdrs; - module.exports.compile = compile; - var forwarded = require_forwarded(); - var ipaddr = require_ipaddr(); - var DIGIT_REGEXP = /^[0-9]+$/; - var isip = ipaddr.isValid; - var parseip = ipaddr.parse; - var IP_RANGES = { - linklocal: ["169.254.0.0/16", "fe80::/10"], - loopback: ["127.0.0.1/8", "::1/128"], - uniquelocal: ["10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "fc00::/7"] - }; - function alladdrs(req, trust) { - var addrs = forwarded(req); - if (!trust) { - return addrs; - } - if (typeof trust !== "function") { - trust = compile(trust); - } - for (var i5 = 0; i5 < addrs.length - 1; i5++) { - if (trust(addrs[i5], i5)) continue; - addrs.length = i5 + 1; - } - return addrs; - } - function compile(val) { - if (!val) { - throw new TypeError("argument is required"); - } - var trust; - if (typeof val === "string") { - trust = [val]; - } else if (Array.isArray(val)) { - trust = val.slice(); - } else { - throw new TypeError("unsupported trust argument"); - } - for (var i5 = 0; i5 < trust.length; i5++) { - val = trust[i5]; - if (!Object.prototype.hasOwnProperty.call(IP_RANGES, val)) { - continue; - } - val = IP_RANGES[val]; - trust.splice.apply(trust, [i5, 1].concat(val)); - i5 += val.length - 1; - } - return compileTrust(compileRangeSubnets(trust)); - } - function compileRangeSubnets(arr) { - var rangeSubnets = new Array(arr.length); - for (var i5 = 0; i5 < arr.length; i5++) { - rangeSubnets[i5] = parseipNotation(arr[i5]); - } - return rangeSubnets; - } - function compileTrust(rangeSubnets) { - var len = rangeSubnets.length; - return len === 0 ? trustNone : len === 1 ? trustSingle(rangeSubnets[0]) : trustMulti(rangeSubnets); - } - function parseipNotation(note) { - var pos = note.lastIndexOf("/"); - var str = pos !== -1 ? note.substring(0, pos) : note; - if (!isip(str)) { - throw new TypeError("invalid IP address: " + str); - } - var ip = parseip(str); - if (pos === -1 && ip.kind() === "ipv6" && ip.isIPv4MappedAddress()) { - ip = ip.toIPv4Address(); - } - var max = ip.kind() === "ipv6" ? 128 : 32; - var range2 = pos !== -1 ? note.substring(pos + 1, note.length) : null; - if (range2 === null) { - range2 = max; - } else if (DIGIT_REGEXP.test(range2)) { - range2 = parseInt(range2, 10); - } else if (ip.kind() === "ipv4" && isip(range2)) { - range2 = parseNetmask(range2); - } else { - range2 = null; - } - if (range2 <= 0 || range2 > max) { - throw new TypeError("invalid range on address: " + note); - } - return [ip, range2]; - } - function parseNetmask(netmask) { - var ip = parseip(netmask); - var kind = ip.kind(); - return kind === "ipv4" ? ip.prefixLengthFromSubnetMask() : null; - } - function proxyaddr(req, trust) { - if (!req) { - throw new TypeError("req argument is required"); - } - if (!trust) { - throw new TypeError("trust argument is required"); - } - var addrs = alladdrs(req, trust); - var addr = addrs[addrs.length - 1]; - return addr; - } - function trustNone() { - return false; - } - function trustMulti(subnets) { - return function trust(addr) { - if (!isip(addr)) return false; - var ip = parseip(addr); - var ipconv; - var kind = ip.kind(); - for (var i5 = 0; i5 < subnets.length; i5++) { - var subnet = subnets[i5]; - var subnetip = subnet[0]; - var subnetkind = subnetip.kind(); - var subnetrange = subnet[1]; - var trusted = ip; - if (kind !== subnetkind) { - if (subnetkind === "ipv4" && !ip.isIPv4MappedAddress()) { - continue; - } - if (!ipconv) { - ipconv = subnetkind === "ipv4" ? ip.toIPv4Address() : ip.toIPv4MappedAddress(); - } - trusted = ipconv; - } - if (trusted.match(subnetip, subnetrange)) { - return true; - } - } - return false; - }; - } - function trustSingle(subnet) { - var subnetip = subnet[0]; - var subnetkind = subnetip.kind(); - var subnetisipv4 = subnetkind === "ipv4"; - var subnetrange = subnet[1]; - return function trust(addr) { - if (!isip(addr)) return false; - var ip = parseip(addr); - var kind = ip.kind(); - if (kind !== subnetkind) { - if (subnetisipv4 && !ip.isIPv4MappedAddress()) { - return false; - } - ip = subnetisipv4 ? ip.toIPv4Address() : ip.toIPv4MappedAddress(); - } - return ip.match(subnetip, subnetrange); - }; - } - } -}); - -// node_modules/.pnpm/express@5.2.1/node_modules/express/lib/utils.js -var require_utils3 = __commonJS({ - "node_modules/.pnpm/express@5.2.1/node_modules/express/lib/utils.js"(exports) { - "use strict"; - var { METHODS } = __require("node:http"); - var contentType = require_content_type(); - var etag = require_etag(); - var mime = require_mime_types(); - var proxyaddr = require_proxy_addr(); - var qs = require_lib2(); - var querystring = __require("node:querystring"); - var { Buffer: Buffer2 } = __require("node:buffer"); - exports.methods = METHODS.map((method) => method.toLowerCase()); - exports.etag = createETagGenerator({ weak: false }); - exports.wetag = createETagGenerator({ weak: true }); - exports.normalizeType = function(type) { - return ~type.indexOf("/") ? acceptParams(type) : { value: mime.lookup(type) || "application/octet-stream", params: {} }; - }; - exports.normalizeTypes = function(types2) { - return types2.map(exports.normalizeType); - }; - function acceptParams(str) { - var length = str.length; - var colonIndex = str.indexOf(";"); - var index2 = colonIndex === -1 ? length : colonIndex; - var ret = { value: str.slice(0, index2).trim(), quality: 1, params: {} }; - while (index2 < length) { - var splitIndex = str.indexOf("=", index2); - if (splitIndex === -1) break; - var colonIndex = str.indexOf(";", index2); - var endIndex = colonIndex === -1 ? length : colonIndex; - if (splitIndex > endIndex) { - index2 = str.lastIndexOf(";", splitIndex - 1) + 1; - continue; - } - var key = str.slice(index2, splitIndex).trim(); - var value = str.slice(splitIndex + 1, endIndex).trim(); - if (key === "q") { - ret.quality = parseFloat(value); - } else { - ret.params[key] = value; - } - index2 = endIndex + 1; - } - return ret; - } - exports.compileETag = function(val) { - var fn; - if (typeof val === "function") { - return val; - } - switch (val) { - case true: - case "weak": - fn = exports.wetag; - break; - case false: - break; - case "strong": - fn = exports.etag; - break; - default: - throw new TypeError("unknown value for etag function: " + val); - } - return fn; - }; - exports.compileQueryParser = function compileQueryParser(val) { - var fn; - if (typeof val === "function") { - return val; - } - switch (val) { - case true: - case "simple": - fn = querystring.parse; - break; - case false: - break; - case "extended": - fn = parseExtendedQueryString; - break; - default: - throw new TypeError("unknown value for query parser function: " + val); - } - return fn; - }; - exports.compileTrust = function(val) { - if (typeof val === "function") return val; - if (val === true) { - return function() { - return true; - }; - } - if (typeof val === "number") { - return function(a5, i5) { - return i5 < val; - }; - } - if (typeof val === "string") { - val = val.split(",").map(function(v5) { - return v5.trim(); - }); - } - return proxyaddr.compile(val || []); - }; - exports.setCharset = function setCharset(type, charset) { - if (!type || !charset) { - return type; - } - var parsed = contentType.parse(type); - parsed.parameters.charset = charset; - return contentType.format(parsed); - }; - function createETagGenerator(options) { - return function generateETag(body, encoding) { - var buf = !Buffer2.isBuffer(body) ? Buffer2.from(body, encoding) : body; - return etag(buf, options); - }; - } - function parseExtendedQueryString(str) { - return qs.parse(str, { - allowPrototypes: true - }); - } - } -}); - -// node_modules/.pnpm/wrappy@1.0.2/node_modules/wrappy/wrappy.js -var require_wrappy = __commonJS({ - "node_modules/.pnpm/wrappy@1.0.2/node_modules/wrappy/wrappy.js"(exports, module) { - module.exports = wrappy; - function wrappy(fn, cb) { - if (fn && cb) return wrappy(fn)(cb); - if (typeof fn !== "function") - throw new TypeError("need wrapper function"); - Object.keys(fn).forEach(function(k5) { - wrapper[k5] = fn[k5]; - }); - return wrapper; - function wrapper() { - var args = new Array(arguments.length); - for (var i5 = 0; i5 < args.length; i5++) { - args[i5] = arguments[i5]; - } - var ret = fn.apply(this, args); - var cb2 = args[args.length - 1]; - if (typeof ret === "function" && ret !== cb2) { - Object.keys(cb2).forEach(function(k5) { - ret[k5] = cb2[k5]; - }); - } - return ret; - } - } - } -}); - -// node_modules/.pnpm/once@1.4.0/node_modules/once/once.js -var require_once = __commonJS({ - "node_modules/.pnpm/once@1.4.0/node_modules/once/once.js"(exports, module) { - var wrappy = require_wrappy(); - module.exports = wrappy(once); - module.exports.strict = wrappy(onceStrict); - once.proto = once(function() { - Object.defineProperty(Function.prototype, "once", { - value: function() { - return once(this); - }, - configurable: true - }); - Object.defineProperty(Function.prototype, "onceStrict", { - value: function() { - return onceStrict(this); - }, - configurable: true - }); - }); - function once(fn) { - var f5 = function() { - if (f5.called) return f5.value; - f5.called = true; - return f5.value = fn.apply(this, arguments); - }; - f5.called = false; - return f5; - } - function onceStrict(fn) { - var f5 = function() { - if (f5.called) - throw new Error(f5.onceError); - f5.called = true; - return f5.value = fn.apply(this, arguments); - }; - var name = fn.name || "Function wrapped with `once`"; - f5.onceError = name + " shouldn't be called more than once"; - f5.called = false; - return f5; - } - } -}); - -// node_modules/.pnpm/is-promise@4.0.0/node_modules/is-promise/index.js -var require_is_promise = __commonJS({ - "node_modules/.pnpm/is-promise@4.0.0/node_modules/is-promise/index.js"(exports, module) { - module.exports = isPromise2; - module.exports.default = isPromise2; - function isPromise2(obj) { - return !!obj && (typeof obj === "object" || typeof obj === "function") && typeof obj.then === "function"; - } - } -}); - -// node_modules/.pnpm/path-to-regexp@8.4.2/node_modules/path-to-regexp/dist/index.js -var require_dist = __commonJS({ - "node_modules/.pnpm/path-to-regexp@8.4.2/node_modules/path-to-regexp/dist/index.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.PathError = exports.TokenData = void 0; - exports.parse = parse5; - exports.compile = compile; - exports.match = match; - exports.pathToRegexp = pathToRegexp; - exports.stringify = stringify2; - var DEFAULT_DELIMITER = "/"; - var NOOP_VALUE = (value) => value; - var ID_START = /^[$_\p{ID_Start}]$/u; - var ID_CONTINUE = /^[$\u200c\u200d\p{ID_Continue}]$/u; - var ID = /^[$_\p{ID_Start}][$\u200c\u200d\p{ID_Continue}]*$/u; - function escapeText(str) { - return str.replace(/[{}()\[\]+?!:*\\]/g, "\\$&"); - } - function escape3(str) { - return str.replace(/[.+*?^${}()[\]|/\\]/g, "\\$&"); - } - var TokenData = class { - constructor(tokens, originalPath) { - this.tokens = tokens; - this.originalPath = originalPath; - } - }; - exports.TokenData = TokenData; - var PathError = class extends TypeError { - constructor(message2, originalPath) { - let text3 = message2; - if (originalPath) - text3 += `: ${originalPath}`; - text3 += `; visit https://git.new/pathToRegexpError for info`; - super(text3); - this.originalPath = originalPath; - } - }; - exports.PathError = PathError; - function parse5(str, options = {}) { - const { encodePath = NOOP_VALUE } = options; - const chars = [...str]; - let index2 = 0; - function consumeUntil(end) { - const output = []; - let path53 = ""; - function writePath() { - if (!path53) - return; - output.push({ - type: "text", - value: encodePath(path53) - }); - path53 = ""; - } - while (index2 < chars.length) { - const value = chars[index2++]; - if (value === end) { - writePath(); - return output; - } - if (value === "\\") { - if (index2 === chars.length) { - throw new PathError(`Unexpected end after \\ at index ${index2}`, str); - } - path53 += chars[index2++]; - continue; - } - if (value === ":" || value === "*") { - const type = value === ":" ? "param" : "wildcard"; - let name = ""; - if (ID_START.test(chars[index2])) { - do { - name += chars[index2++]; - } while (ID_CONTINUE.test(chars[index2])); - } else if (chars[index2] === '"') { - let quoteStart = index2; - while (index2 < chars.length) { - if (chars[++index2] === '"') { - index2++; - quoteStart = 0; - break; - } - if (chars[index2] === "\\") - index2++; - name += chars[index2]; - } - if (quoteStart) { - throw new PathError(`Unterminated quote at index ${quoteStart}`, str); - } - } - if (!name) { - throw new PathError(`Missing parameter name at index ${index2}`, str); - } - writePath(); - output.push({ type, name }); - continue; - } - if (value === "{") { - writePath(); - output.push({ - type: "group", - tokens: consumeUntil("}") - }); - continue; - } - if (value === "}" || value === "(" || value === ")" || value === "[" || value === "]" || value === "+" || value === "?" || value === "!") { - throw new PathError(`Unexpected ${value} at index ${index2 - 1}`, str); - } - path53 += value; - } - if (end) { - throw new PathError(`Unexpected end at index ${index2}, expected ${end}`, str); - } - writePath(); - return output; - } - return new TokenData(consumeUntil(""), str); - } - function compile(path53, options = {}) { - const { encode: encode6 = encodeURIComponent, delimiter = DEFAULT_DELIMITER } = options; - const data2 = typeof path53 === "object" ? path53 : parse5(path53, options); - const fn = tokensToFunction(data2.tokens, delimiter, encode6); - return function path54(params = {}) { - const missing = []; - const path55 = fn(params, missing); - if (missing.length) { - throw new TypeError(`Missing parameters: ${missing.join(", ")}`); - } - return path55; - }; - } - function tokensToFunction(tokens, delimiter, encode6) { - const encoders = tokens.map((token) => tokenToFunction(token, delimiter, encode6)); - return (data2, missing) => { - let result = ""; - for (const encoder3 of encoders) { - result += encoder3(data2, missing); - } - return result; - }; - } - function tokenToFunction(token, delimiter, encode6) { - if (token.type === "text") - return () => token.value; - if (token.type === "group") { - const fn = tokensToFunction(token.tokens, delimiter, encode6); - return (data2, missing) => { - const len = missing.length; - const value = fn(data2, missing); - if (missing.length === len) - return value; - missing.length = len; - return ""; - }; - } - const encodeValue = encode6 || NOOP_VALUE; - if (token.type === "wildcard" && encode6 !== false) { - return (data2, missing) => { - const value = data2[token.name]; - if (value == null) { - missing.push(token.name); - return ""; - } - if (!Array.isArray(value) || value.length === 0) { - throw new TypeError(`Expected "${token.name}" to be a non-empty array`); - } - let result = ""; - for (let i5 = 0; i5 < value.length; i5++) { - if (typeof value[i5] !== "string") { - throw new TypeError(`Expected "${token.name}/${i5}" to be a string`); - } - if (i5 > 0) - result += delimiter; - result += encodeValue(value[i5]); - } - return result; - }; - } - return (data2, missing) => { - const value = data2[token.name]; - if (value == null) { - missing.push(token.name); - return ""; - } - if (typeof value !== "string") { - throw new TypeError(`Expected "${token.name}" to be a string`); - } - return encodeValue(value); - }; - } - function match(path53, options = {}) { - const { decode: decode5 = decodeURIComponent, delimiter = DEFAULT_DELIMITER } = options; - const { regexp, keys } = pathToRegexp(path53, options); - const decoders2 = keys.map((key) => { - if (decode5 === false) - return NOOP_VALUE; - if (key.type === "param") - return decode5; - return (value) => value.split(delimiter).map(decode5); - }); - return function match2(input) { - const m5 = regexp.exec(input); - if (!m5) - return false; - const path54 = m5[0]; - const params = /* @__PURE__ */ Object.create(null); - for (let i5 = 1; i5 < m5.length; i5++) { - if (m5[i5] === void 0) - continue; - const key = keys[i5 - 1]; - const decoder2 = decoders2[i5 - 1]; - params[key.name] = decoder2(m5[i5]); - } - return { path: path54, params }; - }; - } - function pathToRegexp(path53, options = {}) { - const { delimiter = DEFAULT_DELIMITER, end = true, sensitive = false, trailing = true } = options; - const keys = []; - let source = ""; - let combinations = 0; - function process3(path54) { - if (Array.isArray(path54)) { - for (const p5 of path54) - process3(p5); - return; - } - const data2 = typeof path54 === "object" ? path54 : parse5(path54, options); - flatten(data2.tokens, 0, [], (tokens) => { - if (combinations >= 256) { - throw new PathError("Too many path combinations", data2.originalPath); - } - if (combinations > 0) - source += "|"; - source += toRegExpSource(tokens, delimiter, keys, data2.originalPath); - combinations++; - }); - } - process3(path53); - let pattern = `^(?:${source})`; - if (trailing) - pattern += "(?:" + escape3(delimiter) + "$)?"; - pattern += end ? "$" : "(?=" + escape3(delimiter) + "|$)"; - return { regexp: new RegExp(pattern, sensitive ? "" : "i"), keys }; - } - function flatten(tokens, index2, result, callback) { - while (index2 < tokens.length) { - const token = tokens[index2++]; - if (token.type === "group") { - const len = result.length; - flatten(token.tokens, 0, result, (seq) => flatten(tokens, index2, seq, callback)); - result.length = len; - continue; - } - result.push(token); - } - callback(result); - } - function toRegExpSource(tokens, delimiter, keys, originalPath) { - let result = ""; - let backtrack = ""; - let wildcardBacktrack = ""; - let prevCaptureType = 0; - let hasSegmentCapture = 0; - let index2 = 0; - function hasInSegment(index3, type) { - while (index3 < tokens.length) { - const token = tokens[index3++]; - if (token.type === type) - return true; - if (token.type === "text") { - if (token.value.includes(delimiter)) - break; - } - } - return false; - } - function peekText(index3) { - let result2 = ""; - while (index3 < tokens.length) { - const token = tokens[index3++]; - if (token.type !== "text") - break; - result2 += token.value; - } - return result2; - } - while (index2 < tokens.length) { - const token = tokens[index2++]; - if (token.type === "text") { - result += escape3(token.value); - backtrack += token.value; - if (prevCaptureType === 2) - wildcardBacktrack += token.value; - if (token.value.includes(delimiter)) - hasSegmentCapture = 0; - continue; - } - if (token.type === "param" || token.type === "wildcard") { - if (prevCaptureType && !backtrack) { - throw new PathError(`Missing text before "${token.name}" ${token.type}`, originalPath); - } - if (token.type === "param") { - result += hasSegmentCapture & 2 ? `(${negate(delimiter, backtrack)}+)` : hasInSegment(index2, "wildcard") ? `(${negate(delimiter, peekText(index2))}+)` : hasSegmentCapture & 1 ? `(${negate(delimiter, backtrack)}+|${escape3(backtrack)})` : `(${negate(delimiter, "")}+)`; - hasSegmentCapture |= prevCaptureType = 1; - } else { - result += hasSegmentCapture & 2 ? `(${negate(backtrack, "")}+)` : wildcardBacktrack ? `(${negate(wildcardBacktrack, "")}+|${negate(delimiter, "")}+)` : `([^]+)`; - wildcardBacktrack = ""; - hasSegmentCapture |= prevCaptureType = 2; - } - keys.push(token); - backtrack = ""; - continue; - } - throw new TypeError(`Unknown token type: ${token.type}`); - } - return result; - } - function negate(a5, b6) { - if (b6.length > a5.length) - return negate(b6, a5); - if (a5 === b6) - b6 = ""; - if (b6.length > 1) - return `(?:(?!${escape3(a5)}|${escape3(b6)})[^])`; - if (a5.length > 1) - return `(?:(?!${escape3(a5)})[^${escape3(b6)}])`; - return `[^${escape3(a5 + b6)}]`; - } - function stringifyTokens(tokens, index2) { - let value = ""; - while (index2 < tokens.length) { - const token = tokens[index2++]; - if (token.type === "text") { - value += escapeText(token.value); - continue; - } - if (token.type === "group") { - value += "{" + stringifyTokens(token.tokens, 0) + "}"; - continue; - } - if (token.type === "param") { - value += ":" + stringifyName(token.name, tokens[index2]); - continue; - } - if (token.type === "wildcard") { - value += "*" + stringifyName(token.name, tokens[index2]); - continue; - } - throw new TypeError(`Unknown token type: ${token.type}`); - } - return value; - } - function stringify2(data2) { - return stringifyTokens(data2.tokens, 0); - } - function stringifyName(name, next) { - if (!ID.test(name)) - return JSON.stringify(name); - if ((next === null || next === void 0 ? void 0 : next.type) === "text" && ID_CONTINUE.test(next.value[0])) { - return JSON.stringify(name); - } - return name; - } - } -}); - -// node_modules/.pnpm/router@2.2.0/node_modules/router/lib/layer.js -var require_layer = __commonJS({ - "node_modules/.pnpm/router@2.2.0/node_modules/router/lib/layer.js"(exports, module) { - "use strict"; - var isPromise2 = require_is_promise(); - var pathRegexp = require_dist(); - var debug = require_src()("router:layer"); - var deprecate2 = require_depd()("router"); - var TRAILING_SLASH_REGEXP = /\/+$/; - var MATCHING_GROUP_REGEXP = /\((?:\?<(.*?)>)?(?!\?)/g; - module.exports = Layer; - function Layer(path53, options, fn) { - if (!(this instanceof Layer)) { - return new Layer(path53, options, fn); - } - debug("new %o", path53); - const opts = options || {}; - this.handle = fn; - this.keys = []; - this.name = fn.name || ""; - this.params = void 0; - this.path = void 0; - this.slash = path53 === "/" && opts.end === false; - function matcher(_path) { - if (_path instanceof RegExp) { - const keys = []; - let name = 0; - let m5; - while (m5 = MATCHING_GROUP_REGEXP.exec(_path.source)) { - keys.push({ - name: m5[1] || name++, - offset: m5.index - }); - } - return function regexpMatcher(p5) { - const match = _path.exec(p5); - if (!match) { - return false; - } - const params = {}; - for (let i5 = 1; i5 < match.length; i5++) { - const key = keys[i5 - 1]; - const prop = key.name; - const val = decodeParam(match[i5]); - if (val !== void 0) { - params[prop] = val; - } - } - return { - params, - path: match[0] - }; - }; - } - return pathRegexp.match(opts.strict ? _path : loosen(_path), { - sensitive: opts.sensitive, - end: opts.end, - trailing: !opts.strict, - decode: decodeParam - }); - } - this.matchers = Array.isArray(path53) ? path53.map(matcher) : [matcher(path53)]; - } - Layer.prototype.handleError = function handleError(error50, req, res, next) { - const fn = this.handle; - if (fn.length !== 4) { - return next(error50); - } - try { - const ret = fn(error50, req, res, next); - if (isPromise2(ret)) { - if (!(ret instanceof Promise)) { - deprecate2("handlers that are Promise-like are deprecated, use a native Promise instead"); - } - ret.then(null, function(error51) { - next(error51 || new Error("Rejected promise")); - }); - } - } catch (err) { - next(err); - } - }; - Layer.prototype.handleRequest = function handleRequest(req, res, next) { - const fn = this.handle; - if (fn.length > 3) { - return next(); - } - try { - const ret = fn(req, res, next); - if (isPromise2(ret)) { - if (!(ret instanceof Promise)) { - deprecate2("handlers that are Promise-like are deprecated, use a native Promise instead"); - } - ret.then(null, function(error50) { - next(error50 || new Error("Rejected promise")); - }); - } - } catch (err) { - next(err); - } - }; - Layer.prototype.match = function match(path53) { - let match2; - if (path53 != null) { - if (this.slash) { - this.params = {}; - this.path = ""; - return true; - } - let i5 = 0; - while (!match2 && i5 < this.matchers.length) { - match2 = this.matchers[i5](path53); - i5++; - } - } - if (!match2) { - this.params = void 0; - this.path = void 0; - return false; - } - this.params = match2.params; - this.path = match2.path; - this.keys = Object.keys(match2.params); - return true; - }; - function decodeParam(val) { - if (typeof val !== "string" || val.length === 0) { - return val; - } - try { - return decodeURIComponent(val); - } catch (err) { - if (err instanceof URIError) { - err.message = "Failed to decode param '" + val + "'"; - err.status = 400; - } - throw err; - } - } - function loosen(path53) { - if (path53 instanceof RegExp || path53 === "/") { - return path53; - } - return Array.isArray(path53) ? path53.map(function(p5) { - return loosen(p5); - }) : String(path53).replace(TRAILING_SLASH_REGEXP, ""); - } - } -}); - -// node_modules/.pnpm/router@2.2.0/node_modules/router/lib/route.js -var require_route = __commonJS({ - "node_modules/.pnpm/router@2.2.0/node_modules/router/lib/route.js"(exports, module) { - "use strict"; - var debug = require_src()("router:route"); - var Layer = require_layer(); - var { METHODS } = __require("node:http"); - var slice = Array.prototype.slice; - var flatten = Array.prototype.flat; - var methods2 = METHODS.map((method) => method.toLowerCase()); - module.exports = Route; - function Route(path53) { - debug("new %o", path53); - this.path = path53; - this.stack = []; - this.methods = /* @__PURE__ */ Object.create(null); - } - Route.prototype._handlesMethod = function _handlesMethod(method) { - if (this.methods._all) { - return true; - } - let name = typeof method === "string" ? method.toLowerCase() : method; - if (name === "head" && !this.methods.head) { - name = "get"; - } - return Boolean(this.methods[name]); - }; - Route.prototype._methods = function _methods() { - const methods3 = Object.keys(this.methods); - if (this.methods.get && !this.methods.head) { - methods3.push("head"); - } - for (let i5 = 0; i5 < methods3.length; i5++) { - methods3[i5] = methods3[i5].toUpperCase(); - } - return methods3; - }; - Route.prototype.dispatch = function dispatch(req, res, done) { - let idx = 0; - const stack = this.stack; - let sync = 0; - if (stack.length === 0) { - return done(); - } - let method = typeof req.method === "string" ? req.method.toLowerCase() : req.method; - if (method === "head" && !this.methods.head) { - method = "get"; - } - req.route = this; - next(); - function next(err) { - if (err && err === "route") { - return done(); - } - if (err && err === "router") { - return done(err); - } - if (idx >= stack.length) { - return done(err); - } - if (++sync > 100) { - return setImmediate(next, err); - } - let layer; - let match; - while (match !== true && idx < stack.length) { - layer = stack[idx++]; - match = !layer.method || layer.method === method; - } - if (match !== true) { - return done(err); - } - if (err) { - layer.handleError(err, req, res, next); - } else { - layer.handleRequest(req, res, next); - } - sync = 0; - } - }; - Route.prototype.all = function all(handler) { - const callbacks = flatten.call(slice.call(arguments), Infinity); - if (callbacks.length === 0) { - throw new TypeError("argument handler is required"); - } - for (let i5 = 0; i5 < callbacks.length; i5++) { - const fn = callbacks[i5]; - if (typeof fn !== "function") { - throw new TypeError("argument handler must be a function"); - } - const layer = Layer("/", {}, fn); - layer.method = void 0; - this.methods._all = true; - this.stack.push(layer); - } - return this; - }; - methods2.forEach(function(method) { - Route.prototype[method] = function(handler) { - const callbacks = flatten.call(slice.call(arguments), Infinity); - if (callbacks.length === 0) { - throw new TypeError("argument handler is required"); - } - for (let i5 = 0; i5 < callbacks.length; i5++) { - const fn = callbacks[i5]; - if (typeof fn !== "function") { - throw new TypeError("argument handler must be a function"); - } - debug("%s %s", method, this.path); - const layer = Layer("/", {}, fn); - layer.method = method; - this.methods[method] = true; - this.stack.push(layer); - } - return this; - }; - }); - } -}); - -// node_modules/.pnpm/router@2.2.0/node_modules/router/index.js -var require_router = __commonJS({ - "node_modules/.pnpm/router@2.2.0/node_modules/router/index.js"(exports, module) { - "use strict"; - var isPromise2 = require_is_promise(); - var Layer = require_layer(); - var { METHODS } = __require("node:http"); - var parseUrl7 = require_parseurl(); - var Route = require_route(); - var debug = require_src()("router"); - var deprecate2 = require_depd()("router"); - var slice = Array.prototype.slice; - var flatten = Array.prototype.flat; - var methods2 = METHODS.map((method) => method.toLowerCase()); - module.exports = Router26; - module.exports.Route = Route; - function Router26(options) { - if (!(this instanceof Router26)) { - return new Router26(options); - } - const opts = options || {}; - function router2(req, res, next) { - router2.handle(req, res, next); - } - Object.setPrototypeOf(router2, this); - router2.caseSensitive = opts.caseSensitive; - router2.mergeParams = opts.mergeParams; - router2.params = {}; - router2.strict = opts.strict; - router2.stack = []; - return router2; - } - Router26.prototype = function() { - }; - Router26.prototype.param = function param(name, fn) { - if (!name) { - throw new TypeError("argument name is required"); - } - if (typeof name !== "string") { - throw new TypeError("argument name must be a string"); - } - if (!fn) { - throw new TypeError("argument fn is required"); - } - if (typeof fn !== "function") { - throw new TypeError("argument fn must be a function"); - } - let params = this.params[name]; - if (!params) { - params = this.params[name] = []; - } - params.push(fn); - return this; - }; - Router26.prototype.handle = function handle(req, res, callback) { - if (!callback) { - throw new TypeError("argument callback is required"); - } - debug("dispatching %s %s", req.method, req.url); - let idx = 0; - let methods3; - const protohost = getProtohost(req.url) || ""; - let removed = ""; - const self2 = this; - let slashAdded = false; - let sync = 0; - const paramcalled = {}; - const stack = this.stack; - const parentParams = req.params; - const parentUrl = req.baseUrl || ""; - let done = restore(callback, req, "baseUrl", "next", "params"); - req.next = next; - if (req.method === "OPTIONS") { - methods3 = []; - done = wrap4(done, generateOptionsResponder(res, methods3)); - } - req.baseUrl = parentUrl; - req.originalUrl = req.originalUrl || req.url; - next(); - function next(err) { - let layerError = err === "route" ? null : err; - if (slashAdded) { - req.url = req.url.slice(1); - slashAdded = false; - } - if (removed.length !== 0) { - req.baseUrl = parentUrl; - req.url = protohost + removed + req.url.slice(protohost.length); - removed = ""; - } - if (layerError === "router") { - setImmediate(done, null); - return; - } - if (idx >= stack.length) { - setImmediate(done, layerError); - return; - } - if (++sync > 100) { - return setImmediate(next, err); - } - const path53 = getPathname(req); - if (path53 == null) { - return done(layerError); - } - let layer; - let match; - let route; - while (match !== true && idx < stack.length) { - layer = stack[idx++]; - match = matchLayer(layer, path53); - route = layer.route; - if (typeof match !== "boolean") { - layerError = layerError || match; - } - if (match !== true) { - continue; - } - if (!route) { - continue; - } - if (layerError) { - match = false; - continue; - } - const method = req.method; - const hasMethod = route._handlesMethod(method); - if (!hasMethod && method === "OPTIONS" && methods3) { - methods3.push.apply(methods3, route._methods()); - } - if (!hasMethod && method !== "HEAD") { - match = false; - } - } - if (match !== true) { - return done(layerError); - } - if (route) { - req.route = route; - } - req.params = self2.mergeParams ? mergeParams(layer.params, parentParams) : layer.params; - const layerPath = layer.path; - processParams(self2.params, layer, paramcalled, req, res, function(err2) { - if (err2) { - next(layerError || err2); - } else if (route) { - layer.handleRequest(req, res, next); - } else { - trimPrefix(layer, layerError, layerPath, path53); - } - sync = 0; - }); - } - function trimPrefix(layer, layerError, layerPath, path53) { - if (layerPath.length !== 0) { - if (layerPath !== path53.substring(0, layerPath.length)) { - next(layerError); - return; - } - const c5 = path53[layerPath.length]; - if (c5 && c5 !== "/") { - next(layerError); - return; - } - debug("trim prefix (%s) from url %s", layerPath, req.url); - removed = layerPath; - req.url = protohost + req.url.slice(protohost.length + removed.length); - if (!protohost && req.url[0] !== "/") { - req.url = "/" + req.url; - slashAdded = true; - } - req.baseUrl = parentUrl + (removed[removed.length - 1] === "/" ? removed.substring(0, removed.length - 1) : removed); - } - debug("%s %s : %s", layer.name, layerPath, req.originalUrl); - if (layerError) { - layer.handleError(layerError, req, res, next); - } else { - layer.handleRequest(req, res, next); - } - } - }; - Router26.prototype.use = function use2(handler) { - let offset = 0; - let path53 = "/"; - if (typeof handler !== "function") { - let arg = handler; - while (Array.isArray(arg) && arg.length !== 0) { - arg = arg[0]; - } - if (typeof arg !== "function") { - offset = 1; - path53 = handler; - } - } - const callbacks = flatten.call(slice.call(arguments, offset), Infinity); - if (callbacks.length === 0) { - throw new TypeError("argument handler is required"); - } - for (let i5 = 0; i5 < callbacks.length; i5++) { - const fn = callbacks[i5]; - if (typeof fn !== "function") { - throw new TypeError("argument handler must be a function"); - } - debug("use %o %s", path53, fn.name || ""); - const layer = new Layer(path53, { - sensitive: this.caseSensitive, - strict: false, - end: false - }, fn); - layer.route = void 0; - this.stack.push(layer); - } - return this; - }; - Router26.prototype.route = function route(path53) { - const route2 = new Route(path53); - const layer = new Layer(path53, { - sensitive: this.caseSensitive, - strict: this.strict, - end: true - }, handle); - function handle(req, res, next) { - route2.dispatch(req, res, next); - } - layer.route = route2; - this.stack.push(layer); - return route2; - }; - methods2.concat("all").forEach(function(method) { - Router26.prototype[method] = function(path53) { - const route = this.route(path53); - route[method].apply(route, slice.call(arguments, 1)); - return this; - }; - }); - function generateOptionsResponder(res, methods3) { - return function onDone(fn, err) { - if (err || methods3.length === 0) { - return fn(err); - } - trySendOptionsResponse(res, methods3, fn); - }; - } - function getPathname(req) { - try { - return parseUrl7(req).pathname; - } catch (err) { - return void 0; - } - } - function getProtohost(url2) { - if (typeof url2 !== "string" || url2.length === 0 || url2[0] === "/") { - return void 0; - } - const searchIndex = url2.indexOf("?"); - const pathLength = searchIndex !== -1 ? searchIndex : url2.length; - const fqdnIndex = url2.substring(0, pathLength).indexOf("://"); - return fqdnIndex !== -1 ? url2.substring(0, url2.indexOf("/", 3 + fqdnIndex)) : void 0; - } - function matchLayer(layer, path53) { - try { - return layer.match(path53); - } catch (err) { - return err; - } - } - function mergeParams(params, parent) { - if (typeof parent !== "object" || !parent) { - return params; - } - const obj = Object.assign({}, parent); - if (!(0 in params) || !(0 in parent)) { - return Object.assign(obj, params); - } - let i5 = 0; - let o5 = 0; - while (i5 in params) { - i5++; - } - while (o5 in parent) { - o5++; - } - for (i5--; i5 >= 0; i5--) { - params[i5 + o5] = params[i5]; - if (i5 < o5) { - delete params[i5]; - } - } - return Object.assign(obj, params); - } - function processParams(params, layer, called, req, res, done) { - const keys = layer.keys; - if (!keys || keys.length === 0) { - return done(); - } - let i5 = 0; - let paramIndex = 0; - let key; - let paramVal; - let paramCallbacks; - let paramCalled; - function param(err) { - if (err) { - return done(err); - } - if (i5 >= keys.length) { - return done(); - } - paramIndex = 0; - key = keys[i5++]; - paramVal = req.params[key]; - paramCallbacks = params[key]; - paramCalled = called[key]; - if (paramVal === void 0 || !paramCallbacks) { - return param(); - } - if (paramCalled && (paramCalled.match === paramVal || paramCalled.error && paramCalled.error !== "route")) { - req.params[key] = paramCalled.value; - return param(paramCalled.error); - } - called[key] = paramCalled = { - error: null, - match: paramVal, - value: paramVal - }; - paramCallback(); - } - function paramCallback(err) { - const fn = paramCallbacks[paramIndex++]; - paramCalled.value = req.params[key]; - if (err) { - paramCalled.error = err; - param(err); - return; - } - if (!fn) return param(); - try { - const ret = fn(req, res, paramCallback, paramVal, key); - if (isPromise2(ret)) { - if (!(ret instanceof Promise)) { - deprecate2("parameters that are Promise-like are deprecated, use a native Promise instead"); - } - ret.then(null, function(error50) { - paramCallback(error50 || new Error("Rejected promise")); - }); - } - } catch (e5) { - paramCallback(e5); - } - } - param(); - } - function restore(fn, obj) { - const props = new Array(arguments.length - 2); - const vals = new Array(arguments.length - 2); - for (let i5 = 0; i5 < props.length; i5++) { - props[i5] = arguments[i5 + 2]; - vals[i5] = obj[props[i5]]; - } - return function() { - for (let i5 = 0; i5 < props.length; i5++) { - obj[props[i5]] = vals[i5]; - } - return fn.apply(this, arguments); - }; - } - function sendOptionsResponse(res, methods3) { - const options = /* @__PURE__ */ Object.create(null); - for (let i5 = 0; i5 < methods3.length; i5++) { - options[methods3[i5]] = true; - } - const allow = Object.keys(options).sort().join(", "); - res.setHeader("Allow", allow); - res.setHeader("Content-Length", Buffer.byteLength(allow)); - res.setHeader("Content-Type", "text/plain"); - res.setHeader("X-Content-Type-Options", "nosniff"); - res.end(allow); - } - function trySendOptionsResponse(res, methods3, next) { - try { - sendOptionsResponse(res, methods3); - } catch (err) { - next(err); - } - } - function wrap4(old, fn) { - return function proxy() { - const args = new Array(arguments.length + 1); - args[0] = old; - for (let i5 = 0, len = arguments.length; i5 < len; i5++) { - args[i5 + 1] = arguments[i5]; - } - fn.apply(this, args); - }; - } - } -}); - -// node_modules/.pnpm/express@5.2.1/node_modules/express/lib/application.js -var require_application = __commonJS({ - "node_modules/.pnpm/express@5.2.1/node_modules/express/lib/application.js"(exports, module) { - "use strict"; - var finalhandler = require_finalhandler(); - var debug = require_src()("express:application"); - var View2 = require_view(); - var http = __require("node:http"); - var methods2 = require_utils3().methods; - var compileETag = require_utils3().compileETag; - var compileQueryParser = require_utils3().compileQueryParser; - var compileTrust = require_utils3().compileTrust; - var resolve4 = __require("node:path").resolve; - var once = require_once(); - var Router26 = require_router(); - var slice = Array.prototype.slice; - var flatten = Array.prototype.flat; - var app = exports = module.exports = {}; - var trustProxyDefaultSymbol = "@@symbol:trust_proxy_default"; - app.init = function init2() { - var router2 = null; - this.cache = /* @__PURE__ */ Object.create(null); - this.engines = /* @__PURE__ */ Object.create(null); - this.settings = /* @__PURE__ */ Object.create(null); - this.defaultConfiguration(); - Object.defineProperty(this, "router", { - configurable: true, - enumerable: true, - get: function getrouter() { - if (router2 === null) { - router2 = new Router26({ - caseSensitive: this.enabled("case sensitive routing"), - strict: this.enabled("strict routing") - }); - } - return router2; - } - }); - }; - app.defaultConfiguration = function defaultConfiguration() { - var env2 = "production"; - this.enable("x-powered-by"); - this.set("etag", "weak"); - this.set("env", env2); - this.set("query parser", "simple"); - this.set("subdomain offset", 2); - this.set("trust proxy", false); - Object.defineProperty(this.settings, trustProxyDefaultSymbol, { - configurable: true, - value: true - }); - debug("booting in %s mode", env2); - this.on("mount", function onmount(parent) { - if (this.settings[trustProxyDefaultSymbol] === true && typeof parent.settings["trust proxy fn"] === "function") { - delete this.settings["trust proxy"]; - delete this.settings["trust proxy fn"]; - } - Object.setPrototypeOf(this.request, parent.request); - Object.setPrototypeOf(this.response, parent.response); - Object.setPrototypeOf(this.engines, parent.engines); - Object.setPrototypeOf(this.settings, parent.settings); - }); - this.locals = /* @__PURE__ */ Object.create(null); - this.mountpath = "/"; - this.locals.settings = this.settings; - this.set("view", View2); - this.set("views", resolve4("views")); - this.set("jsonp callback name", "callback"); - if (env2 === "production") { - this.enable("view cache"); - } - }; - app.handle = function handle(req, res, callback) { - var done = callback || finalhandler(req, res, { - env: this.get("env"), - onerror: logerror.bind(this) - }); - if (this.enabled("x-powered-by")) { - res.setHeader("X-Powered-By", "Express"); - } - req.res = res; - res.req = req; - Object.setPrototypeOf(req, this.request); - Object.setPrototypeOf(res, this.response); - if (!res.locals) { - res.locals = /* @__PURE__ */ Object.create(null); - } - this.router.handle(req, res, done); - }; - app.use = function use2(fn) { - var offset = 0; - var path53 = "/"; - if (typeof fn !== "function") { - var arg = fn; - while (Array.isArray(arg) && arg.length !== 0) { - arg = arg[0]; - } - if (typeof arg !== "function") { - offset = 1; - path53 = fn; - } - } - var fns = flatten.call(slice.call(arguments, offset), Infinity); - if (fns.length === 0) { - throw new TypeError("app.use() requires a middleware function"); - } - var router2 = this.router; - fns.forEach(function(fn2) { - if (!fn2 || !fn2.handle || !fn2.set) { - return router2.use(path53, fn2); - } - debug(".use app under %s", path53); - fn2.mountpath = path53; - fn2.parent = this; - router2.use(path53, function mounted_app(req, res, next) { - var orig = req.app; - fn2.handle(req, res, function(err) { - Object.setPrototypeOf(req, orig.request); - Object.setPrototypeOf(res, orig.response); - next(err); - }); - }); - fn2.emit("mount", this); - }, this); - return this; - }; - app.route = function route(path53) { - return this.router.route(path53); - }; - app.engine = function engine(ext, fn) { - if (typeof fn !== "function") { - throw new Error("callback function required"); - } - var extension2 = ext[0] !== "." ? "." + ext : ext; - this.engines[extension2] = fn; - return this; - }; - app.param = function param(name, fn) { - if (Array.isArray(name)) { - for (var i5 = 0; i5 < name.length; i5++) { - this.param(name[i5], fn); - } - return this; - } - this.router.param(name, fn); - return this; - }; - app.set = function set2(setting, val) { - if (arguments.length === 1) { - return this.settings[setting]; - } - debug('set "%s" to %o', setting, val); - this.settings[setting] = val; - switch (setting) { - case "etag": - this.set("etag fn", compileETag(val)); - break; - case "query parser": - this.set("query parser fn", compileQueryParser(val)); - break; - case "trust proxy": - this.set("trust proxy fn", compileTrust(val)); - Object.defineProperty(this.settings, trustProxyDefaultSymbol, { - configurable: true, - value: false - }); - break; - } - return this; - }; - app.path = function path53() { - return this.parent ? this.parent.path() + this.mountpath : ""; - }; - app.enabled = function enabled(setting) { - return Boolean(this.set(setting)); - }; - app.disabled = function disabled(setting) { - return !this.set(setting); - }; - app.enable = function enable(setting) { - return this.set(setting, true); - }; - app.disable = function disable(setting) { - return this.set(setting, false); - }; - methods2.forEach(function(method) { - app[method] = function(path53) { - if (method === "get" && arguments.length === 1) { - return this.set(path53); - } - var route = this.route(path53); - route[method].apply(route, slice.call(arguments, 1)); - return this; - }; - }); - app.all = function all(path53) { - var route = this.route(path53); - var args = slice.call(arguments, 1); - for (var i5 = 0; i5 < methods2.length; i5++) { - route[methods2[i5]].apply(route, args); - } - return this; - }; - app.render = function render(name, options, callback) { - var cache7 = this.cache; - var done = callback; - var engines = this.engines; - var opts = options; - var view; - if (typeof options === "function") { - done = options; - opts = {}; - } - var renderOptions = { ...this.locals, ...opts._locals, ...opts }; - if (renderOptions.cache == null) { - renderOptions.cache = this.enabled("view cache"); - } - if (renderOptions.cache) { - view = cache7[name]; - } - if (!view) { - var View3 = this.get("view"); - view = new View3(name, { - defaultEngine: this.get("view engine"), - root: this.get("views"), - engines - }); - if (!view.path) { - var dirs = Array.isArray(view.root) && view.root.length > 1 ? 'directories "' + view.root.slice(0, -1).join('", "') + '" or "' + view.root[view.root.length - 1] + '"' : 'directory "' + view.root + '"'; - var err = new Error('Failed to lookup view "' + name + '" in views ' + dirs); - err.view = view; - return done(err); - } - if (renderOptions.cache) { - cache7[name] = view; - } - } - tryRender(view, renderOptions, done); - }; - app.listen = function listen() { - var server = http.createServer(this); - var args = slice.call(arguments); - if (typeof args[args.length - 1] === "function") { - var done = args[args.length - 1] = once(args[args.length - 1]); - server.once("error", done); - } - return server.listen.apply(server, args); - }; - function logerror(err) { - if (this.get("env") !== "test") console.error(err.stack || err.toString()); - } - function tryRender(view, options, callback) { - try { - view.render(options, callback); - } catch (err) { - callback(err); - } - } - } -}); - -// node_modules/.pnpm/negotiator@1.0.0/node_modules/negotiator/lib/charset.js -var require_charset = __commonJS({ - "node_modules/.pnpm/negotiator@1.0.0/node_modules/negotiator/lib/charset.js"(exports, module) { - "use strict"; - module.exports = preferredCharsets; - module.exports.preferredCharsets = preferredCharsets; - var simpleCharsetRegExp = /^\s*([^\s;]+)\s*(?:;(.*))?$/; - function parseAcceptCharset(accept) { - var accepts = accept.split(","); - for (var i5 = 0, j5 = 0; i5 < accepts.length; i5++) { - var charset = parseCharset(accepts[i5].trim(), i5); - if (charset) { - accepts[j5++] = charset; - } - } - accepts.length = j5; - return accepts; - } - function parseCharset(str, i5) { - var match = simpleCharsetRegExp.exec(str); - if (!match) return null; - var charset = match[1]; - var q5 = 1; - if (match[2]) { - var params = match[2].split(";"); - for (var j5 = 0; j5 < params.length; j5++) { - var p5 = params[j5].trim().split("="); - if (p5[0] === "q") { - q5 = parseFloat(p5[1]); - break; - } - } - } - return { - charset, - q: q5, - i: i5 - }; - } - function getCharsetPriority(charset, accepted, index2) { - var priority = { o: -1, q: 0, s: 0 }; - for (var i5 = 0; i5 < accepted.length; i5++) { - var spec = specify(charset, accepted[i5], index2); - if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { - priority = spec; - } - } - return priority; - } - function specify(charset, spec, index2) { - var s5 = 0; - if (spec.charset.toLowerCase() === charset.toLowerCase()) { - s5 |= 1; - } else if (spec.charset !== "*") { - return null; - } - return { - i: index2, - o: spec.i, - q: spec.q, - s: s5 - }; - } - function preferredCharsets(accept, provided) { - var accepts = parseAcceptCharset(accept === void 0 ? "*" : accept || ""); - if (!provided) { - return accepts.filter(isQuality).sort(compareSpecs).map(getFullCharset); - } - var priorities = provided.map(function getPriority(type, index2) { - return getCharsetPriority(type, accepts, index2); - }); - return priorities.filter(isQuality).sort(compareSpecs).map(function getCharset(priority) { - return provided[priorities.indexOf(priority)]; - }); - } - function compareSpecs(a5, b6) { - return b6.q - a5.q || b6.s - a5.s || a5.o - b6.o || a5.i - b6.i || 0; - } - function getFullCharset(spec) { - return spec.charset; - } - function isQuality(spec) { - return spec.q > 0; - } - } -}); - -// node_modules/.pnpm/negotiator@1.0.0/node_modules/negotiator/lib/encoding.js -var require_encoding = __commonJS({ - "node_modules/.pnpm/negotiator@1.0.0/node_modules/negotiator/lib/encoding.js"(exports, module) { - "use strict"; - module.exports = preferredEncodings; - module.exports.preferredEncodings = preferredEncodings; - var simpleEncodingRegExp = /^\s*([^\s;]+)\s*(?:;(.*))?$/; - function parseAcceptEncoding(accept) { - var accepts = accept.split(","); - var hasIdentity = false; - var minQuality = 1; - for (var i5 = 0, j5 = 0; i5 < accepts.length; i5++) { - var encoding = parseEncoding(accepts[i5].trim(), i5); - if (encoding) { - accepts[j5++] = encoding; - hasIdentity = hasIdentity || specify("identity", encoding); - minQuality = Math.min(minQuality, encoding.q || 1); - } - } - if (!hasIdentity) { - accepts[j5++] = { - encoding: "identity", - q: minQuality, - i: i5 - }; - } - accepts.length = j5; - return accepts; - } - function parseEncoding(str, i5) { - var match = simpleEncodingRegExp.exec(str); - if (!match) return null; - var encoding = match[1]; - var q5 = 1; - if (match[2]) { - var params = match[2].split(";"); - for (var j5 = 0; j5 < params.length; j5++) { - var p5 = params[j5].trim().split("="); - if (p5[0] === "q") { - q5 = parseFloat(p5[1]); - break; - } - } - } - return { - encoding, - q: q5, - i: i5 - }; - } - function getEncodingPriority(encoding, accepted, index2) { - var priority = { encoding, o: -1, q: 0, s: 0 }; - for (var i5 = 0; i5 < accepted.length; i5++) { - var spec = specify(encoding, accepted[i5], index2); - if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { - priority = spec; - } - } - return priority; - } - function specify(encoding, spec, index2) { - var s5 = 0; - if (spec.encoding.toLowerCase() === encoding.toLowerCase()) { - s5 |= 1; - } else if (spec.encoding !== "*") { - return null; - } - return { - encoding, - i: index2, - o: spec.i, - q: spec.q, - s: s5 - }; - } - function preferredEncodings(accept, provided, preferred) { - var accepts = parseAcceptEncoding(accept || ""); - var comparator = preferred ? function comparator2(a5, b6) { - if (a5.q !== b6.q) { - return b6.q - a5.q; - } - var aPreferred = preferred.indexOf(a5.encoding); - var bPreferred = preferred.indexOf(b6.encoding); - if (aPreferred === -1 && bPreferred === -1) { - return b6.s - a5.s || a5.o - b6.o || a5.i - b6.i; - } - if (aPreferred !== -1 && bPreferred !== -1) { - return aPreferred - bPreferred; - } - return aPreferred === -1 ? 1 : -1; - } : compareSpecs; - if (!provided) { - return accepts.filter(isQuality).sort(comparator).map(getFullEncoding); - } - var priorities = provided.map(function getPriority(type, index2) { - return getEncodingPriority(type, accepts, index2); - }); - return priorities.filter(isQuality).sort(comparator).map(function getEncoding(priority) { - return provided[priorities.indexOf(priority)]; - }); - } - function compareSpecs(a5, b6) { - return b6.q - a5.q || b6.s - a5.s || a5.o - b6.o || a5.i - b6.i; - } - function getFullEncoding(spec) { - return spec.encoding; - } - function isQuality(spec) { - return spec.q > 0; - } - } -}); - -// node_modules/.pnpm/negotiator@1.0.0/node_modules/negotiator/lib/language.js -var require_language = __commonJS({ - "node_modules/.pnpm/negotiator@1.0.0/node_modules/negotiator/lib/language.js"(exports, module) { - "use strict"; - module.exports = preferredLanguages; - module.exports.preferredLanguages = preferredLanguages; - var simpleLanguageRegExp = /^\s*([^\s\-;]+)(?:-([^\s;]+))?\s*(?:;(.*))?$/; - function parseAcceptLanguage(accept) { - var accepts = accept.split(","); - for (var i5 = 0, j5 = 0; i5 < accepts.length; i5++) { - var language = parseLanguage(accepts[i5].trim(), i5); - if (language) { - accepts[j5++] = language; - } - } - accepts.length = j5; - return accepts; - } - function parseLanguage(str, i5) { - var match = simpleLanguageRegExp.exec(str); - if (!match) return null; - var prefix = match[1]; - var suffix = match[2]; - var full = prefix; - if (suffix) full += "-" + suffix; - var q5 = 1; - if (match[3]) { - var params = match[3].split(";"); - for (var j5 = 0; j5 < params.length; j5++) { - var p5 = params[j5].split("="); - if (p5[0] === "q") q5 = parseFloat(p5[1]); - } - } - return { - prefix, - suffix, - q: q5, - i: i5, - full - }; - } - function getLanguagePriority(language, accepted, index2) { - var priority = { o: -1, q: 0, s: 0 }; - for (var i5 = 0; i5 < accepted.length; i5++) { - var spec = specify(language, accepted[i5], index2); - if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { - priority = spec; - } - } - return priority; - } - function specify(language, spec, index2) { - var p5 = parseLanguage(language); - if (!p5) return null; - var s5 = 0; - if (spec.full.toLowerCase() === p5.full.toLowerCase()) { - s5 |= 4; - } else if (spec.prefix.toLowerCase() === p5.full.toLowerCase()) { - s5 |= 2; - } else if (spec.full.toLowerCase() === p5.prefix.toLowerCase()) { - s5 |= 1; - } else if (spec.full !== "*") { - return null; - } - return { - i: index2, - o: spec.i, - q: spec.q, - s: s5 - }; - } - function preferredLanguages(accept, provided) { - var accepts = parseAcceptLanguage(accept === void 0 ? "*" : accept || ""); - if (!provided) { - return accepts.filter(isQuality).sort(compareSpecs).map(getFullLanguage); - } - var priorities = provided.map(function getPriority(type, index2) { - return getLanguagePriority(type, accepts, index2); - }); - return priorities.filter(isQuality).sort(compareSpecs).map(function getLanguage(priority) { - return provided[priorities.indexOf(priority)]; - }); - } - function compareSpecs(a5, b6) { - return b6.q - a5.q || b6.s - a5.s || a5.o - b6.o || a5.i - b6.i || 0; - } - function getFullLanguage(spec) { - return spec.full; - } - function isQuality(spec) { - return spec.q > 0; - } - } -}); - -// node_modules/.pnpm/negotiator@1.0.0/node_modules/negotiator/lib/mediaType.js -var require_mediaType = __commonJS({ - "node_modules/.pnpm/negotiator@1.0.0/node_modules/negotiator/lib/mediaType.js"(exports, module) { - "use strict"; - module.exports = preferredMediaTypes; - module.exports.preferredMediaTypes = preferredMediaTypes; - var simpleMediaTypeRegExp = /^\s*([^\s\/;]+)\/([^;\s]+)\s*(?:;(.*))?$/; - function parseAccept(accept) { - var accepts = splitMediaTypes(accept); - for (var i5 = 0, j5 = 0; i5 < accepts.length; i5++) { - var mediaType = parseMediaType(accepts[i5].trim(), i5); - if (mediaType) { - accepts[j5++] = mediaType; - } - } - accepts.length = j5; - return accepts; - } - function parseMediaType(str, i5) { - var match = simpleMediaTypeRegExp.exec(str); - if (!match) return null; - var params = /* @__PURE__ */ Object.create(null); - var q5 = 1; - var subtype = match[2]; - var type = match[1]; - if (match[3]) { - var kvps = splitParameters(match[3]).map(splitKeyValuePair); - for (var j5 = 0; j5 < kvps.length; j5++) { - var pair = kvps[j5]; - var key = pair[0].toLowerCase(); - var val = pair[1]; - var value = val && val[0] === '"' && val[val.length - 1] === '"' ? val.slice(1, -1) : val; - if (key === "q") { - q5 = parseFloat(value); - break; - } - params[key] = value; - } - } - return { - type, - subtype, - params, - q: q5, - i: i5 - }; - } - function getMediaTypePriority(type, accepted, index2) { - var priority = { o: -1, q: 0, s: 0 }; - for (var i5 = 0; i5 < accepted.length; i5++) { - var spec = specify(type, accepted[i5], index2); - if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { - priority = spec; - } - } - return priority; - } - function specify(type, spec, index2) { - var p5 = parseMediaType(type); - var s5 = 0; - if (!p5) { - return null; - } - if (spec.type.toLowerCase() == p5.type.toLowerCase()) { - s5 |= 4; - } else if (spec.type != "*") { - return null; - } - if (spec.subtype.toLowerCase() == p5.subtype.toLowerCase()) { - s5 |= 2; - } else if (spec.subtype != "*") { - return null; - } - var keys = Object.keys(spec.params); - if (keys.length > 0) { - if (keys.every(function(k5) { - return spec.params[k5] == "*" || (spec.params[k5] || "").toLowerCase() == (p5.params[k5] || "").toLowerCase(); - })) { - s5 |= 1; - } else { - return null; - } - } - return { - i: index2, - o: spec.i, - q: spec.q, - s: s5 - }; - } - function preferredMediaTypes(accept, provided) { - var accepts = parseAccept(accept === void 0 ? "*/*" : accept || ""); - if (!provided) { - return accepts.filter(isQuality).sort(compareSpecs).map(getFullType); - } - var priorities = provided.map(function getPriority(type, index2) { - return getMediaTypePriority(type, accepts, index2); - }); - return priorities.filter(isQuality).sort(compareSpecs).map(function getType(priority) { - return provided[priorities.indexOf(priority)]; - }); - } - function compareSpecs(a5, b6) { - return b6.q - a5.q || b6.s - a5.s || a5.o - b6.o || a5.i - b6.i || 0; - } - function getFullType(spec) { - return spec.type + "/" + spec.subtype; - } - function isQuality(spec) { - return spec.q > 0; - } - function quoteCount(string4) { - var count2 = 0; - var index2 = 0; - while ((index2 = string4.indexOf('"', index2)) !== -1) { - count2++; - index2++; - } - return count2; - } - function splitKeyValuePair(str) { - var index2 = str.indexOf("="); - var key; - var val; - if (index2 === -1) { - key = str; - } else { - key = str.slice(0, index2); - val = str.slice(index2 + 1); - } - return [key, val]; - } - function splitMediaTypes(accept) { - var accepts = accept.split(","); - for (var i5 = 1, j5 = 0; i5 < accepts.length; i5++) { - if (quoteCount(accepts[j5]) % 2 == 0) { - accepts[++j5] = accepts[i5]; - } else { - accepts[j5] += "," + accepts[i5]; - } - } - accepts.length = j5 + 1; - return accepts; - } - function splitParameters(str) { - var parameters = str.split(";"); - for (var i5 = 1, j5 = 0; i5 < parameters.length; i5++) { - if (quoteCount(parameters[j5]) % 2 == 0) { - parameters[++j5] = parameters[i5]; - } else { - parameters[j5] += ";" + parameters[i5]; - } - } - parameters.length = j5 + 1; - for (var i5 = 0; i5 < parameters.length; i5++) { - parameters[i5] = parameters[i5].trim(); - } - return parameters; - } - } -}); - -// node_modules/.pnpm/negotiator@1.0.0/node_modules/negotiator/index.js -var require_negotiator = __commonJS({ - "node_modules/.pnpm/negotiator@1.0.0/node_modules/negotiator/index.js"(exports, module) { - "use strict"; - var preferredCharsets = require_charset(); - var preferredEncodings = require_encoding(); - var preferredLanguages = require_language(); - var preferredMediaTypes = require_mediaType(); - module.exports = Negotiator; - module.exports.Negotiator = Negotiator; - function Negotiator(request) { - if (!(this instanceof Negotiator)) { - return new Negotiator(request); - } - this.request = request; - } - Negotiator.prototype.charset = function charset(available) { - var set2 = this.charsets(available); - return set2 && set2[0]; - }; - Negotiator.prototype.charsets = function charsets(available) { - return preferredCharsets(this.request.headers["accept-charset"], available); - }; - Negotiator.prototype.encoding = function encoding(available, opts) { - var set2 = this.encodings(available, opts); - return set2 && set2[0]; - }; - Negotiator.prototype.encodings = function encodings(available, options) { - var opts = options || {}; - return preferredEncodings(this.request.headers["accept-encoding"], available, opts.preferred); - }; - Negotiator.prototype.language = function language(available) { - var set2 = this.languages(available); - return set2 && set2[0]; - }; - Negotiator.prototype.languages = function languages(available) { - return preferredLanguages(this.request.headers["accept-language"], available); - }; - Negotiator.prototype.mediaType = function mediaType(available) { - var set2 = this.mediaTypes(available); - return set2 && set2[0]; - }; - Negotiator.prototype.mediaTypes = function mediaTypes(available) { - return preferredMediaTypes(this.request.headers.accept, available); - }; - Negotiator.prototype.preferredCharset = Negotiator.prototype.charset; - Negotiator.prototype.preferredCharsets = Negotiator.prototype.charsets; - Negotiator.prototype.preferredEncoding = Negotiator.prototype.encoding; - Negotiator.prototype.preferredEncodings = Negotiator.prototype.encodings; - Negotiator.prototype.preferredLanguage = Negotiator.prototype.language; - Negotiator.prototype.preferredLanguages = Negotiator.prototype.languages; - Negotiator.prototype.preferredMediaType = Negotiator.prototype.mediaType; - Negotiator.prototype.preferredMediaTypes = Negotiator.prototype.mediaTypes; - } -}); - -// node_modules/.pnpm/accepts@2.0.0/node_modules/accepts/index.js -var require_accepts = __commonJS({ - "node_modules/.pnpm/accepts@2.0.0/node_modules/accepts/index.js"(exports, module) { - "use strict"; - var Negotiator = require_negotiator(); - var mime = require_mime_types(); - module.exports = Accepts; - function Accepts(req) { - if (!(this instanceof Accepts)) { - return new Accepts(req); - } - this.headers = req.headers; - this.negotiator = new Negotiator(req); - } - Accepts.prototype.type = Accepts.prototype.types = function(types_) { - var types2 = types_; - if (types2 && !Array.isArray(types2)) { - types2 = new Array(arguments.length); - for (var i5 = 0; i5 < types2.length; i5++) { - types2[i5] = arguments[i5]; - } - } - if (!types2 || types2.length === 0) { - return this.negotiator.mediaTypes(); - } - if (!this.headers.accept) { - return types2[0]; - } - var mimes = types2.map(extToMime); - var accepts = this.negotiator.mediaTypes(mimes.filter(validMime)); - var first = accepts[0]; - return first ? types2[mimes.indexOf(first)] : false; - }; - Accepts.prototype.encoding = Accepts.prototype.encodings = function(encodings_) { - var encodings = encodings_; - if (encodings && !Array.isArray(encodings)) { - encodings = new Array(arguments.length); - for (var i5 = 0; i5 < encodings.length; i5++) { - encodings[i5] = arguments[i5]; - } - } - if (!encodings || encodings.length === 0) { - return this.negotiator.encodings(); - } - return this.negotiator.encodings(encodings)[0] || false; - }; - Accepts.prototype.charset = Accepts.prototype.charsets = function(charsets_) { - var charsets = charsets_; - if (charsets && !Array.isArray(charsets)) { - charsets = new Array(arguments.length); - for (var i5 = 0; i5 < charsets.length; i5++) { - charsets[i5] = arguments[i5]; - } - } - if (!charsets || charsets.length === 0) { - return this.negotiator.charsets(); - } - return this.negotiator.charsets(charsets)[0] || false; - }; - Accepts.prototype.lang = Accepts.prototype.langs = Accepts.prototype.language = Accepts.prototype.languages = function(languages_) { - var languages = languages_; - if (languages && !Array.isArray(languages)) { - languages = new Array(arguments.length); - for (var i5 = 0; i5 < languages.length; i5++) { - languages[i5] = arguments[i5]; - } - } - if (!languages || languages.length === 0) { - return this.negotiator.languages(); - } - return this.negotiator.languages(languages)[0] || false; - }; - function extToMime(type) { - return type.indexOf("/") === -1 ? mime.lookup(type) : type; - } - function validMime(type) { - return typeof type === "string"; - } - } -}); - -// node_modules/.pnpm/fresh@2.0.0/node_modules/fresh/index.js -var require_fresh = __commonJS({ - "node_modules/.pnpm/fresh@2.0.0/node_modules/fresh/index.js"(exports, module) { - "use strict"; - var CACHE_CONTROL_NO_CACHE_REGEXP = /(?:^|,)\s*?no-cache\s*?(?:,|$)/; - module.exports = fresh; - function fresh(reqHeaders, resHeaders) { - var modifiedSince = reqHeaders["if-modified-since"]; - var noneMatch = reqHeaders["if-none-match"]; - if (!modifiedSince && !noneMatch) { - return false; - } - var cacheControl = reqHeaders["cache-control"]; - if (cacheControl && CACHE_CONTROL_NO_CACHE_REGEXP.test(cacheControl)) { - return false; - } - if (noneMatch) { - if (noneMatch === "*") { - return true; - } - var etag = resHeaders.etag; - if (!etag) { - return false; - } - var matches = parseTokenList(noneMatch); - for (var i5 = 0; i5 < matches.length; i5++) { - var match = matches[i5]; - if (match === etag || match === "W/" + etag || "W/" + match === etag) { - return true; - } - } - return false; - } - if (modifiedSince) { - var lastModified = resHeaders["last-modified"]; - var modifiedStale = !lastModified || !(parseHttpDate(lastModified) <= parseHttpDate(modifiedSince)); - if (modifiedStale) { - return false; - } - } - return true; - } - function parseHttpDate(date7) { - var timestamp2 = date7 && Date.parse(date7); - return typeof timestamp2 === "number" ? timestamp2 : NaN; - } - function parseTokenList(str) { - var end = 0; - var list2 = []; - var start = 0; - for (var i5 = 0, len = str.length; i5 < len; i5++) { - switch (str.charCodeAt(i5)) { - case 32: - if (start === end) { - start = end = i5 + 1; - } - break; - case 44: - list2.push(str.substring(start, end)); - start = end = i5 + 1; - break; - default: - end = i5 + 1; - break; - } - } - list2.push(str.substring(start, end)); - return list2; - } - } -}); - -// node_modules/.pnpm/range-parser@1.2.1/node_modules/range-parser/index.js -var require_range_parser = __commonJS({ - "node_modules/.pnpm/range-parser@1.2.1/node_modules/range-parser/index.js"(exports, module) { - "use strict"; - module.exports = rangeParser; - function rangeParser(size2, str, options) { - if (typeof str !== "string") { - throw new TypeError("argument str must be a string"); - } - var index2 = str.indexOf("="); - if (index2 === -1) { - return -2; - } - var arr = str.slice(index2 + 1).split(","); - var ranges = []; - ranges.type = str.slice(0, index2); - for (var i5 = 0; i5 < arr.length; i5++) { - var range2 = arr[i5].split("-"); - var start = parseInt(range2[0], 10); - var end = parseInt(range2[1], 10); - if (isNaN(start)) { - start = size2 - end; - end = size2 - 1; - } else if (isNaN(end)) { - end = size2 - 1; - } - if (end > size2 - 1) { - end = size2 - 1; - } - if (isNaN(start) || isNaN(end) || start > end || start < 0) { - continue; - } - ranges.push({ - start, - end - }); - } - if (ranges.length < 1) { - return -1; - } - return options && options.combine ? combineRanges(ranges) : ranges; - } - function combineRanges(ranges) { - var ordered = ranges.map(mapWithIndex).sort(sortByRangeStart); - for (var j5 = 0, i5 = 1; i5 < ordered.length; i5++) { - var range2 = ordered[i5]; - var current = ordered[j5]; - if (range2.start > current.end + 1) { - ordered[++j5] = range2; - } else if (range2.end > current.end) { - current.end = range2.end; - current.index = Math.min(current.index, range2.index); - } - } - ordered.length = j5 + 1; - var combined = ordered.sort(sortByRangeIndex).map(mapWithoutIndex); - combined.type = ranges.type; - return combined; - } - function mapWithIndex(range2, index2) { - return { - start: range2.start, - end: range2.end, - index: index2 - }; - } - function mapWithoutIndex(range2) { - return { - start: range2.start, - end: range2.end - }; - } - function sortByRangeIndex(a5, b6) { - return a5.index - b6.index; - } - function sortByRangeStart(a5, b6) { - return a5.start - b6.start; - } - } -}); - -// node_modules/.pnpm/express@5.2.1/node_modules/express/lib/request.js -var require_request = __commonJS({ - "node_modules/.pnpm/express@5.2.1/node_modules/express/lib/request.js"(exports, module) { - "use strict"; - var accepts = require_accepts(); - var isIP2 = __require("node:net").isIP; - var typeis = require_type_is(); - var http = __require("node:http"); - var fresh = require_fresh(); - var parseRange = require_range_parser(); - var parse5 = require_parseurl(); - var proxyaddr = require_proxy_addr(); - var req = Object.create(http.IncomingMessage.prototype); - module.exports = req; - req.get = req.header = function header(name) { - if (!name) { - throw new TypeError("name argument is required to req.get"); - } - if (typeof name !== "string") { - throw new TypeError("name must be a string to req.get"); - } - var lc = name.toLowerCase(); - switch (lc) { - case "referer": - case "referrer": - return this.headers.referrer || this.headers.referer; - default: - return this.headers[lc]; - } - }; - req.accepts = function() { - var accept = accepts(this); - return accept.types.apply(accept, arguments); - }; - req.acceptsEncodings = function() { - var accept = accepts(this); - return accept.encodings.apply(accept, arguments); - }; - req.acceptsCharsets = function() { - var accept = accepts(this); - return accept.charsets.apply(accept, arguments); - }; - req.acceptsLanguages = function(...languages) { - return accepts(this).languages(...languages); - }; - req.range = function range2(size2, options) { - var range3 = this.get("Range"); - if (!range3) return; - return parseRange(size2, range3, options); - }; - defineGetter(req, "query", function query() { - var queryparse = this.app.get("query parser fn"); - if (!queryparse) { - return /* @__PURE__ */ Object.create(null); - } - var querystring = parse5(this).query; - return queryparse(querystring); - }); - req.is = function is2(types2) { - var arr = types2; - if (!Array.isArray(types2)) { - arr = new Array(arguments.length); - for (var i5 = 0; i5 < arr.length; i5++) { - arr[i5] = arguments[i5]; - } - } - return typeis(this, arr); - }; - defineGetter(req, "protocol", function protocol() { - var proto = this.socket.encrypted ? "https" : "http"; - var trust = this.app.get("trust proxy fn"); - if (!trust(this.socket.remoteAddress, 0)) { - return proto; - } - var header = this.get("X-Forwarded-Proto") || proto; - var index2 = header.indexOf(","); - return index2 !== -1 ? header.substring(0, index2).trim() : header.trim(); - }); - defineGetter(req, "secure", function secure() { - return this.protocol === "https"; - }); - defineGetter(req, "ip", function ip() { - var trust = this.app.get("trust proxy fn"); - return proxyaddr(this, trust); - }); - defineGetter(req, "ips", function ips() { - var trust = this.app.get("trust proxy fn"); - var addrs = proxyaddr.all(this, trust); - addrs.reverse().pop(); - return addrs; - }); - defineGetter(req, "subdomains", function subdomains() { - var hostname3 = this.hostname; - if (!hostname3) return []; - var offset = this.app.get("subdomain offset"); - var subdomains2 = !isIP2(hostname3) ? hostname3.split(".").reverse() : [hostname3]; - return subdomains2.slice(offset); - }); - defineGetter(req, "path", function path53() { - return parse5(this).pathname; - }); - defineGetter(req, "host", function host() { - var trust = this.app.get("trust proxy fn"); - var val = this.get("X-Forwarded-Host"); - if (!val || !trust(this.socket.remoteAddress, 0)) { - val = this.get("Host"); - } else if (val.indexOf(",") !== -1) { - val = val.substring(0, val.indexOf(",")).trimRight(); - } - return val || void 0; - }); - defineGetter(req, "hostname", function hostname3() { - var host = this.host; - if (!host) return; - var offset = host[0] === "[" ? host.indexOf("]") + 1 : 0; - var index2 = host.indexOf(":", offset); - return index2 !== -1 ? host.substring(0, index2) : host; - }); - defineGetter(req, "fresh", function() { - var method = this.method; - var res = this.res; - var status = res.statusCode; - if ("GET" !== method && "HEAD" !== method) return false; - if (status >= 200 && status < 300 || 304 === status) { - return fresh(this.headers, { - "etag": res.get("ETag"), - "last-modified": res.get("Last-Modified") - }); - } - return false; - }); - defineGetter(req, "stale", function stale() { - return !this.fresh; - }); - defineGetter(req, "xhr", function xhr() { - var val = this.get("X-Requested-With") || ""; - return val.toLowerCase() === "xmlhttprequest"; - }); - function defineGetter(obj, name, getter) { - Object.defineProperty(obj, name, { - configurable: true, - enumerable: true, - get: getter - }); - } - } -}); - -// node_modules/.pnpm/content-disposition@1.1.0/node_modules/content-disposition/index.js -var require_content_disposition = __commonJS({ - "node_modules/.pnpm/content-disposition@1.1.0/node_modules/content-disposition/index.js"(exports, module) { - "use strict"; - module.exports = contentDisposition; - module.exports.parse = parse5; - var utf8Decoder = new TextDecoder("utf-8"); - var ENCODE_URL_ATTR_CHAR_REGEXP = /[\x00-\x20"'()*,/:;<=>?@[\\\]{}\x7f]/g; - var NON_LATIN1_REGEXP = /[^\x20-\x7e\xa0-\xff]/g; - var QESC_REGEXP = /\\([\u0000-\u007f])/g; - var QUOTE_REGEXP = /([\\"])/g; - var PARAM_REGEXP = /;[\x09\x20]*([!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*=[\x09\x20]*("(?:[\x20!\x23-\x5b\x5d-\x7e\x80-\xff]|\\[\x20-\x7e])*"|[!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*/g; - var TEXT_REGEXP = /^[\x20-\x7e\x80-\xff]+$/; - var TOKEN_REGEXP = /^[!#$%&'*+.0-9A-Z^_`a-z|~-]+$/; - var EXT_VALUE_REGEXP = /^([A-Za-z0-9!#$%&+\-^_`{}~]+)'(?:[A-Za-z]{2,3}(?:-[A-Za-z]{3}){0,3}|[A-Za-z]{4,8}|)'((?:%[0-9A-Fa-f]{2}|[A-Za-z0-9!#$&+.^_`|~-])+)$/; - var DISPOSITION_TYPE_REGEXP = /^([!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*(?:$|;)/; - function contentDisposition(filename, options) { - var opts = options || {}; - var type = opts.type || "attachment"; - var params = createparams(filename, opts.fallback); - return format2(new ContentDisposition(type, params)); - } - function createparams(filename, fallback) { - if (filename === void 0) { - return; - } - var params = {}; - if (typeof filename !== "string") { - throw new TypeError("filename must be a string"); - } - if (fallback === void 0) { - fallback = true; - } - if (typeof fallback !== "string" && typeof fallback !== "boolean") { - throw new TypeError("fallback must be a string or boolean"); - } - if (typeof fallback === "string" && NON_LATIN1_REGEXP.test(fallback)) { - throw new TypeError("fallback must be ISO-8859-1 string"); - } - var name = basename3(filename); - var isQuotedString = TEXT_REGEXP.test(name); - var fallbackName = typeof fallback !== "string" ? fallback && getlatin1(name) : basename3(fallback); - var hasFallback = typeof fallbackName === "string" && fallbackName !== name; - if (hasFallback || !isQuotedString || hasHexEscape(name)) { - params["filename*"] = name; - } - if (isQuotedString || hasFallback) { - params.filename = hasFallback ? fallbackName : name; - } - return params; - } - function format2(obj) { - var parameters = obj.parameters; - var type = obj.type; - if (!type || typeof type !== "string" || !TOKEN_REGEXP.test(type)) { - throw new TypeError("invalid type"); - } - var string4 = String(type).toLowerCase(); - if (parameters && typeof parameters === "object") { - var param; - var params = Object.keys(parameters).sort(); - for (var i5 = 0; i5 < params.length; i5++) { - param = params[i5]; - var val = param.slice(-1) === "*" ? ustring(parameters[param]) : qstring(parameters[param]); - string4 += "; " + param + "=" + val; - } - } - return string4; - } - function decodefield(str) { - const match = EXT_VALUE_REGEXP.exec(str); - if (!match) { - throw new TypeError("invalid extended field value"); - } - const charset = match[1].toLowerCase(); - const encoded = match[2]; - switch (charset) { - case "iso-8859-1": { - const binary2 = decodeHexEscapes(encoded); - return getlatin1(binary2); - } - case "utf-8": - case "utf8": { - try { - return decodeURIComponent(encoded); - } catch { - const binary2 = decodeHexEscapes(encoded); - const bytes = new Uint8Array(binary2.length); - for (let idx = 0; idx < binary2.length; idx++) { - bytes[idx] = binary2.charCodeAt(idx); - } - return utf8Decoder.decode(bytes); - } - } - } - throw new TypeError("unsupported charset in extended field"); - } - function getlatin1(val) { - return String(val).replace(NON_LATIN1_REGEXP, "?"); - } - function parse5(string4) { - if (!string4 || typeof string4 !== "string") { - throw new TypeError("argument string is required"); - } - var match = DISPOSITION_TYPE_REGEXP.exec(string4); - if (!match) { - throw new TypeError("invalid type format"); - } - var index2 = match[0].length; - var type = match[1].toLowerCase(); - var key; - var names = []; - var params = {}; - var value; - index2 = PARAM_REGEXP.lastIndex = match[0].slice(-1) === ";" ? index2 - 1 : index2; - while (match = PARAM_REGEXP.exec(string4)) { - if (match.index !== index2) { - throw new TypeError("invalid parameter format"); - } - index2 += match[0].length; - key = match[1].toLowerCase(); - value = match[2]; - if (names.indexOf(key) !== -1) { - throw new TypeError("invalid duplicate parameter"); - } - names.push(key); - if (key.indexOf("*") + 1 === key.length) { - key = key.slice(0, -1); - value = decodefield(value); - params[key] = value; - continue; - } - if (typeof params[key] === "string") { - continue; - } - if (value[0] === '"') { - value = value.slice(1, -1).replace(QESC_REGEXP, "$1"); - } - params[key] = value; - } - if (index2 !== -1 && index2 !== string4.length) { - throw new TypeError("invalid parameter format"); - } - return new ContentDisposition(type, params); - } - function pencode(char2) { - return "%" + String(char2).charCodeAt(0).toString(16).toUpperCase(); - } - function qstring(val) { - var str = String(val); - return '"' + str.replace(QUOTE_REGEXP, "\\$1") + '"'; - } - function ustring(val) { - var str = String(val); - var encoded = encodeURIComponent(str).replace(ENCODE_URL_ATTR_CHAR_REGEXP, pencode); - return "UTF-8''" + encoded; - } - function ContentDisposition(type, parameters) { - this.type = type; - this.parameters = parameters; - } - function basename3(path53) { - const normalized = path53.replaceAll("\\", "/"); - let end = normalized.length; - while (end > 0 && normalized[end - 1] === "/") { - end--; - } - if (end === 0) { - return ""; - } - let start = end - 1; - while (start >= 0 && normalized[start] !== "/") { - start--; - } - return normalized.slice(start + 1, end); - } - function isHexDigit(char2) { - const code = char2.charCodeAt(0); - return code >= 48 && code <= 57 || // 0-9 - code >= 65 && code <= 70 || // A-F - code >= 97 && code <= 102; - } - function hasHexEscape(str) { - const maxIndex = str.length - 3; - let lastIndex = -1; - while ((lastIndex = str.indexOf("%", lastIndex + 1)) !== -1 && lastIndex <= maxIndex) { - if (isHexDigit(str[lastIndex + 1]) && isHexDigit(str[lastIndex + 2])) { - return true; - } - } - return false; - } - function decodeHexEscapes(str) { - const firstEscape = str.indexOf("%"); - if (firstEscape === -1) return str; - let result = str.slice(0, firstEscape); - for (let idx = firstEscape; idx < str.length; idx++) { - if (str[idx] === "%" && idx + 2 < str.length && isHexDigit(str[idx + 1]) && isHexDigit(str[idx + 2])) { - result += String.fromCharCode(Number.parseInt(str[idx + 1] + str[idx + 2], 16)); - idx += 2; - } else { - result += str[idx]; - } - } - return result; - } - } -}); - -// node_modules/.pnpm/cookie-signature@1.2.2/node_modules/cookie-signature/index.js -var require_cookie_signature = __commonJS({ - "node_modules/.pnpm/cookie-signature@1.2.2/node_modules/cookie-signature/index.js"(exports) { - var crypto6 = __require("crypto"); - exports.sign = function(val, secret) { - if ("string" != typeof val) throw new TypeError("Cookie value must be provided as a string."); - if (null == secret) throw new TypeError("Secret key must be provided."); - return val + "." + crypto6.createHmac("sha256", secret).update(val).digest("base64").replace(/\=+$/, ""); - }; - exports.unsign = function(input, secret) { - if ("string" != typeof input) throw new TypeError("Signed cookie string must be provided."); - if (null == secret) throw new TypeError("Secret key must be provided."); - var tentativeValue = input.slice(0, input.lastIndexOf(".")), expectedInput = exports.sign(tentativeValue, secret), expectedBuffer = Buffer.from(expectedInput), inputBuffer = Buffer.from(input); - return expectedBuffer.length === inputBuffer.length && crypto6.timingSafeEqual(expectedBuffer, inputBuffer) ? tentativeValue : false; - }; - } -}); - -// node_modules/.pnpm/cookie@0.7.2/node_modules/cookie/index.js -var require_cookie = __commonJS({ - "node_modules/.pnpm/cookie@0.7.2/node_modules/cookie/index.js"(exports) { - "use strict"; - exports.parse = parse5; - exports.serialize = serialize; - var __toString = Object.prototype.toString; - var __hasOwnProperty = Object.prototype.hasOwnProperty; - var cookieNameRegExp = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/; - var cookieValueRegExp = /^("?)[\u0021\u0023-\u002B\u002D-\u003A\u003C-\u005B\u005D-\u007E]*\1$/; - var domainValueRegExp = /^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i; - var pathValueRegExp = /^[\u0020-\u003A\u003D-\u007E]*$/; - function parse5(str, opt) { - if (typeof str !== "string") { - throw new TypeError("argument str must be a string"); - } - var obj = {}; - var len = str.length; - if (len < 2) return obj; - var dec = opt && opt.decode || decode5; - var index2 = 0; - var eqIdx = 0; - var endIdx = 0; - do { - eqIdx = str.indexOf("=", index2); - if (eqIdx === -1) break; - endIdx = str.indexOf(";", index2); - if (endIdx === -1) { - endIdx = len; - } else if (eqIdx > endIdx) { - index2 = str.lastIndexOf(";", eqIdx - 1) + 1; - continue; - } - var keyStartIdx = startIndex(str, index2, eqIdx); - var keyEndIdx = endIndex(str, eqIdx, keyStartIdx); - var key = str.slice(keyStartIdx, keyEndIdx); - if (!__hasOwnProperty.call(obj, key)) { - var valStartIdx = startIndex(str, eqIdx + 1, endIdx); - var valEndIdx = endIndex(str, endIdx, valStartIdx); - if (str.charCodeAt(valStartIdx) === 34 && str.charCodeAt(valEndIdx - 1) === 34) { - valStartIdx++; - valEndIdx--; - } - var val = str.slice(valStartIdx, valEndIdx); - obj[key] = tryDecode2(val, dec); - } - index2 = endIdx + 1; - } while (index2 < len); - return obj; - } - function startIndex(str, index2, max) { - do { - var code = str.charCodeAt(index2); - if (code !== 32 && code !== 9) return index2; - } while (++index2 < max); - return max; - } - function endIndex(str, index2, min) { - while (index2 > min) { - var code = str.charCodeAt(--index2); - if (code !== 32 && code !== 9) return index2 + 1; - } - return min; - } - function serialize(name, val, opt) { - var enc2 = opt && opt.encode || encodeURIComponent; - if (typeof enc2 !== "function") { - throw new TypeError("option encode is invalid"); - } - if (!cookieNameRegExp.test(name)) { - throw new TypeError("argument name is invalid"); - } - var value = enc2(val); - if (!cookieValueRegExp.test(value)) { - throw new TypeError("argument val is invalid"); - } - var str = name + "=" + value; - if (!opt) return str; - if (null != opt.maxAge) { - var maxAge = Math.floor(opt.maxAge); - if (!isFinite(maxAge)) { - throw new TypeError("option maxAge is invalid"); - } - str += "; Max-Age=" + maxAge; - } - if (opt.domain) { - if (!domainValueRegExp.test(opt.domain)) { - throw new TypeError("option domain is invalid"); - } - str += "; Domain=" + opt.domain; - } - if (opt.path) { - if (!pathValueRegExp.test(opt.path)) { - throw new TypeError("option path is invalid"); - } - str += "; Path=" + opt.path; - } - if (opt.expires) { - var expires = opt.expires; - if (!isDate2(expires) || isNaN(expires.valueOf())) { - throw new TypeError("option expires is invalid"); - } - str += "; Expires=" + expires.toUTCString(); - } - if (opt.httpOnly) { - str += "; HttpOnly"; - } - if (opt.secure) { - str += "; Secure"; - } - if (opt.partitioned) { - str += "; Partitioned"; - } - if (opt.priority) { - var priority = typeof opt.priority === "string" ? opt.priority.toLowerCase() : opt.priority; - switch (priority) { - case "low": - str += "; Priority=Low"; - break; - case "medium": - str += "; Priority=Medium"; - break; - case "high": - str += "; Priority=High"; - break; - default: - throw new TypeError("option priority is invalid"); - } - } - if (opt.sameSite) { - var sameSite = typeof opt.sameSite === "string" ? opt.sameSite.toLowerCase() : opt.sameSite; - switch (sameSite) { - case true: - str += "; SameSite=Strict"; - break; - case "lax": - str += "; SameSite=Lax"; - break; - case "strict": - str += "; SameSite=Strict"; - break; - case "none": - str += "; SameSite=None"; - break; - default: - throw new TypeError("option sameSite is invalid"); - } - } - return str; - } - function decode5(str) { - return str.indexOf("%") !== -1 ? decodeURIComponent(str) : str; - } - function isDate2(val) { - return __toString.call(val) === "[object Date]"; - } - function tryDecode2(str, decode6) { - try { - return decode6(str); - } catch (e5) { - return str; - } - } - } -}); - -// node_modules/.pnpm/send@1.2.1/node_modules/send/index.js -var require_send = __commonJS({ - "node_modules/.pnpm/send@1.2.1/node_modules/send/index.js"(exports, module) { - "use strict"; - var createError = require_http_errors(); - var debug = require_src()("send"); - var encodeUrl = require_encodeurl(); - var escapeHtml = require_escape_html(); - var etag = require_etag(); - var fresh = require_fresh(); - var fs41 = __require("fs"); - var mime = require_mime_types(); - var ms = require_ms(); - var onFinished = require_on_finished(); - var parseRange = require_range_parser(); - var path53 = __require("path"); - var statuses = require_statuses(); - var Stream3 = __require("stream"); - var util2 = __require("util"); - var extname2 = path53.extname; - var join4 = path53.join; - var normalize2 = path53.normalize; - var resolve4 = path53.resolve; - var sep = path53.sep; - var BYTES_RANGE_REGEXP = /^ *bytes=/; - var MAX_MAXAGE = 60 * 60 * 24 * 365 * 1e3; - var UP_PATH_REGEXP = /(?:^|[\\/])\.\.(?:[\\/]|$)/; - module.exports = send; - function send(req, path54, options) { - return new SendStream(req, path54, options); - } - function SendStream(req, path54, options) { - Stream3.call(this); - var opts = options || {}; - this.options = opts; - this.path = path54; - this.req = req; - this._acceptRanges = opts.acceptRanges !== void 0 ? Boolean(opts.acceptRanges) : true; - this._cacheControl = opts.cacheControl !== void 0 ? Boolean(opts.cacheControl) : true; - this._etag = opts.etag !== void 0 ? Boolean(opts.etag) : true; - this._dotfiles = opts.dotfiles !== void 0 ? opts.dotfiles : "ignore"; - if (this._dotfiles !== "ignore" && this._dotfiles !== "allow" && this._dotfiles !== "deny") { - throw new TypeError('dotfiles option must be "allow", "deny", or "ignore"'); - } - this._extensions = opts.extensions !== void 0 ? normalizeList(opts.extensions, "extensions option") : []; - this._immutable = opts.immutable !== void 0 ? Boolean(opts.immutable) : false; - this._index = opts.index !== void 0 ? normalizeList(opts.index, "index option") : ["index.html"]; - this._lastModified = opts.lastModified !== void 0 ? Boolean(opts.lastModified) : true; - this._maxage = opts.maxAge || opts.maxage; - this._maxage = typeof this._maxage === "string" ? ms(this._maxage) : Number(this._maxage); - this._maxage = !isNaN(this._maxage) ? Math.min(Math.max(0, this._maxage), MAX_MAXAGE) : 0; - this._root = opts.root ? resolve4(opts.root) : null; - } - util2.inherits(SendStream, Stream3); - SendStream.prototype.error = function error50(status, err) { - if (hasListeners(this, "error")) { - return this.emit("error", createHttpError(status, err)); - } - var res = this.res; - var msg = statuses.message[status] || String(status); - var doc = createHtmlDocument("Error", escapeHtml(msg)); - clearHeaders(res); - if (err && err.headers) { - setHeaders(res, err.headers); - } - res.statusCode = status; - res.setHeader("Content-Type", "text/html; charset=UTF-8"); - res.setHeader("Content-Length", Buffer.byteLength(doc)); - res.setHeader("Content-Security-Policy", "default-src 'none'"); - res.setHeader("X-Content-Type-Options", "nosniff"); - res.end(doc); - }; - SendStream.prototype.hasTrailingSlash = function hasTrailingSlash() { - return this.path[this.path.length - 1] === "/"; - }; - SendStream.prototype.isConditionalGET = function isConditionalGET() { - return this.req.headers["if-match"] || this.req.headers["if-unmodified-since"] || this.req.headers["if-none-match"] || this.req.headers["if-modified-since"]; - }; - SendStream.prototype.isPreconditionFailure = function isPreconditionFailure() { - var req = this.req; - var res = this.res; - var match = req.headers["if-match"]; - if (match) { - var etag2 = res.getHeader("ETag"); - return !etag2 || match !== "*" && parseTokenList(match).every(function(match2) { - return match2 !== etag2 && match2 !== "W/" + etag2 && "W/" + match2 !== etag2; - }); - } - var unmodifiedSince = parseHttpDate(req.headers["if-unmodified-since"]); - if (!isNaN(unmodifiedSince)) { - var lastModified = parseHttpDate(res.getHeader("Last-Modified")); - return isNaN(lastModified) || lastModified > unmodifiedSince; - } - return false; - }; - SendStream.prototype.removeContentHeaderFields = function removeContentHeaderFields() { - var res = this.res; - res.removeHeader("Content-Encoding"); - res.removeHeader("Content-Language"); - res.removeHeader("Content-Length"); - res.removeHeader("Content-Range"); - res.removeHeader("Content-Type"); - }; - SendStream.prototype.notModified = function notModified() { - var res = this.res; - debug("not modified"); - this.removeContentHeaderFields(); - res.statusCode = 304; - res.end(); - }; - SendStream.prototype.headersAlreadySent = function headersAlreadySent() { - var err = new Error("Can't set headers after they are sent."); - debug("headers already sent"); - this.error(500, err); - }; - SendStream.prototype.isCachable = function isCachable() { - var statusCode = this.res.statusCode; - return statusCode >= 200 && statusCode < 300 || statusCode === 304; - }; - SendStream.prototype.onStatError = function onStatError(error50) { - switch (error50.code) { - case "ENAMETOOLONG": - case "ENOENT": - case "ENOTDIR": - this.error(404, error50); - break; - default: - this.error(500, error50); - break; - } - }; - SendStream.prototype.isFresh = function isFresh() { - return fresh(this.req.headers, { - etag: this.res.getHeader("ETag"), - "last-modified": this.res.getHeader("Last-Modified") - }); - }; - SendStream.prototype.isRangeFresh = function isRangeFresh() { - var ifRange = this.req.headers["if-range"]; - if (!ifRange) { - return true; - } - if (ifRange.indexOf('"') !== -1) { - var etag2 = this.res.getHeader("ETag"); - return Boolean(etag2 && ifRange.indexOf(etag2) !== -1); - } - var lastModified = this.res.getHeader("Last-Modified"); - return parseHttpDate(lastModified) <= parseHttpDate(ifRange); - }; - SendStream.prototype.redirect = function redirect(path54) { - var res = this.res; - if (hasListeners(this, "directory")) { - this.emit("directory", res, path54); - return; - } - if (this.hasTrailingSlash()) { - this.error(403); - return; - } - var loc = encodeUrl(collapseLeadingSlashes(this.path + "/")); - var doc = createHtmlDocument("Redirecting", "Redirecting to " + escapeHtml(loc)); - res.statusCode = 301; - res.setHeader("Content-Type", "text/html; charset=UTF-8"); - res.setHeader("Content-Length", Buffer.byteLength(doc)); - res.setHeader("Content-Security-Policy", "default-src 'none'"); - res.setHeader("X-Content-Type-Options", "nosniff"); - res.setHeader("Location", loc); - res.end(doc); - }; - SendStream.prototype.pipe = function pipe2(res) { - var root = this._root; - this.res = res; - var path54 = decode5(this.path); - if (path54 === -1) { - this.error(400); - return res; - } - if (~path54.indexOf("\0")) { - this.error(400); - return res; - } - var parts; - if (root !== null) { - if (path54) { - path54 = normalize2("." + sep + path54); - } - if (UP_PATH_REGEXP.test(path54)) { - debug('malicious path "%s"', path54); - this.error(403); - return res; - } - parts = path54.split(sep); - path54 = normalize2(join4(root, path54)); - } else { - if (UP_PATH_REGEXP.test(path54)) { - debug('malicious path "%s"', path54); - this.error(403); - return res; - } - parts = normalize2(path54).split(sep); - path54 = resolve4(path54); - } - if (containsDotFile(parts)) { - debug('%s dotfile "%s"', this._dotfiles, path54); - switch (this._dotfiles) { - case "allow": - break; - case "deny": - this.error(403); - return res; - case "ignore": - default: - this.error(404); - return res; - } - } - if (this._index.length && this.hasTrailingSlash()) { - this.sendIndex(path54); - return res; - } - this.sendFile(path54); - return res; - }; - SendStream.prototype.send = function send2(path54, stat5) { - var len = stat5.size; - var options = this.options; - var opts = {}; - var res = this.res; - var req = this.req; - var ranges = req.headers.range; - var offset = options.start || 0; - if (res.headersSent) { - this.headersAlreadySent(); - return; - } - debug('pipe "%s"', path54); - this.setHeader(path54, stat5); - this.type(path54); - if (this.isConditionalGET()) { - if (this.isPreconditionFailure()) { - this.error(412); - return; - } - if (this.isCachable() && this.isFresh()) { - this.notModified(); - return; - } - } - len = Math.max(0, len - offset); - if (options.end !== void 0) { - var bytes = options.end - offset + 1; - if (len > bytes) len = bytes; - } - if (this._acceptRanges && BYTES_RANGE_REGEXP.test(ranges)) { - ranges = parseRange(len, ranges, { - combine: true - }); - if (!this.isRangeFresh()) { - debug("range stale"); - ranges = -2; - } - if (ranges === -1) { - debug("range unsatisfiable"); - res.setHeader("Content-Range", contentRange("bytes", len)); - return this.error(416, { - headers: { "Content-Range": res.getHeader("Content-Range") } - }); - } - if (ranges !== -2 && ranges.length === 1) { - debug("range %j", ranges); - res.statusCode = 206; - res.setHeader("Content-Range", contentRange("bytes", len, ranges[0])); - offset += ranges[0].start; - len = ranges[0].end - ranges[0].start + 1; - } - } - for (var prop in options) { - opts[prop] = options[prop]; - } - opts.start = offset; - opts.end = Math.max(offset, offset + len - 1); - res.setHeader("Content-Length", len); - if (req.method === "HEAD") { - res.end(); - return; - } - this.stream(path54, opts); - }; - SendStream.prototype.sendFile = function sendFile(path54) { - var i5 = 0; - var self2 = this; - debug('stat "%s"', path54); - fs41.stat(path54, function onstat(err, stat5) { - var pathEndsWithSep = path54[path54.length - 1] === sep; - if (err && err.code === "ENOENT" && !extname2(path54) && !pathEndsWithSep) { - return next(err); - } - if (err) return self2.onStatError(err); - if (stat5.isDirectory()) return self2.redirect(path54); - if (pathEndsWithSep) return self2.error(404); - self2.emit("file", path54, stat5); - self2.send(path54, stat5); - }); - function next(err) { - if (self2._extensions.length <= i5) { - return err ? self2.onStatError(err) : self2.error(404); - } - var p5 = path54 + "." + self2._extensions[i5++]; - debug('stat "%s"', p5); - fs41.stat(p5, function(err2, stat5) { - if (err2) return next(err2); - if (stat5.isDirectory()) return next(); - self2.emit("file", p5, stat5); - self2.send(p5, stat5); - }); - } - }; - SendStream.prototype.sendIndex = function sendIndex(path54) { - var i5 = -1; - var self2 = this; - function next(err) { - if (++i5 >= self2._index.length) { - if (err) return self2.onStatError(err); - return self2.error(404); - } - var p5 = join4(path54, self2._index[i5]); - debug('stat "%s"', p5); - fs41.stat(p5, function(err2, stat5) { - if (err2) return next(err2); - if (stat5.isDirectory()) return next(); - self2.emit("file", p5, stat5); - self2.send(p5, stat5); - }); - } - next(); - }; - SendStream.prototype.stream = function stream(path54, options) { - var self2 = this; - var res = this.res; - var stream2 = fs41.createReadStream(path54, options); - this.emit("stream", stream2); - stream2.pipe(res); - function cleanup() { - stream2.destroy(); - } - onFinished(res, cleanup); - stream2.on("error", function onerror(err) { - cleanup(); - self2.onStatError(err); - }); - stream2.on("end", function onend() { - self2.emit("end"); - }); - }; - SendStream.prototype.type = function type(path54) { - var res = this.res; - if (res.getHeader("Content-Type")) return; - var ext = extname2(path54); - var type2 = mime.contentType(ext) || "application/octet-stream"; - debug("content-type %s", type2); - res.setHeader("Content-Type", type2); - }; - SendStream.prototype.setHeader = function setHeader(path54, stat5) { - var res = this.res; - this.emit("headers", res, path54, stat5); - if (this._acceptRanges && !res.getHeader("Accept-Ranges")) { - debug("accept ranges"); - res.setHeader("Accept-Ranges", "bytes"); - } - if (this._cacheControl && !res.getHeader("Cache-Control")) { - var cacheControl = "public, max-age=" + Math.floor(this._maxage / 1e3); - if (this._immutable) { - cacheControl += ", immutable"; - } - debug("cache-control %s", cacheControl); - res.setHeader("Cache-Control", cacheControl); - } - if (this._lastModified && !res.getHeader("Last-Modified")) { - var modified = stat5.mtime.toUTCString(); - debug("modified %s", modified); - res.setHeader("Last-Modified", modified); - } - if (this._etag && !res.getHeader("ETag")) { - var val = etag(stat5); - debug("etag %s", val); - res.setHeader("ETag", val); - } - }; - function clearHeaders(res) { - for (const header of res.getHeaderNames()) { - res.removeHeader(header); - } - } - function collapseLeadingSlashes(str) { - for (var i5 = 0; i5 < str.length; i5++) { - if (str[i5] !== "/") { - break; - } - } - return i5 > 1 ? "/" + str.substr(i5) : str; - } - function containsDotFile(parts) { - for (var i5 = 0; i5 < parts.length; i5++) { - var part = parts[i5]; - if (part.length > 1 && part[0] === ".") { - return true; - } - } - return false; - } - function contentRange(type, size2, range2) { - return type + " " + (range2 ? range2.start + "-" + range2.end : "*") + "/" + size2; - } - function createHtmlDocument(title, body) { - return '\n\n\n\n' + title + "\n\n\n
" + body + "
\n\n\n"; - } - function createHttpError(status, err) { - if (!err) { - return createError(status); - } - return err instanceof Error ? createError(status, err, { expose: false }) : createError(status, err); - } - function decode5(path54) { - try { - return decodeURIComponent(path54); - } catch (err) { - return -1; - } - } - function hasListeners(emitter2, type) { - var count2 = typeof emitter2.listenerCount !== "function" ? emitter2.listeners(type).length : emitter2.listenerCount(type); - return count2 > 0; - } - function normalizeList(val, name) { - var list2 = [].concat(val || []); - for (var i5 = 0; i5 < list2.length; i5++) { - if (typeof list2[i5] !== "string") { - throw new TypeError(name + " must be array of strings or false"); - } - } - return list2; - } - function parseHttpDate(date7) { - var timestamp2 = date7 && Date.parse(date7); - return typeof timestamp2 === "number" ? timestamp2 : NaN; - } - function parseTokenList(str) { - var end = 0; - var list2 = []; - var start = 0; - for (var i5 = 0, len = str.length; i5 < len; i5++) { - switch (str.charCodeAt(i5)) { - case 32: - if (start === end) { - start = end = i5 + 1; - } - break; - case 44: - if (start !== end) { - list2.push(str.substring(start, end)); - } - start = end = i5 + 1; - break; - default: - end = i5 + 1; - break; - } - } - if (start !== end) { - list2.push(str.substring(start, end)); - } - return list2; - } - function setHeaders(res, headers) { - var keys = Object.keys(headers); - for (var i5 = 0; i5 < keys.length; i5++) { - var key = keys[i5]; - res.setHeader(key, headers[key]); - } - } - } -}); - -// node_modules/.pnpm/vary@1.1.2/node_modules/vary/index.js -var require_vary = __commonJS({ - "node_modules/.pnpm/vary@1.1.2/node_modules/vary/index.js"(exports, module) { - "use strict"; - module.exports = vary; - module.exports.append = append; - var FIELD_NAME_REGEXP = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/; - function append(header, field) { - if (typeof header !== "string") { - throw new TypeError("header argument is required"); - } - if (!field) { - throw new TypeError("field argument is required"); - } - var fields = !Array.isArray(field) ? parse5(String(field)) : field; - for (var j5 = 0; j5 < fields.length; j5++) { - if (!FIELD_NAME_REGEXP.test(fields[j5])) { - throw new TypeError("field argument contains an invalid header name"); - } - } - if (header === "*") { - return header; - } - var val = header; - var vals = parse5(header.toLowerCase()); - if (fields.indexOf("*") !== -1 || vals.indexOf("*") !== -1) { - return "*"; - } - for (var i5 = 0; i5 < fields.length; i5++) { - var fld = fields[i5].toLowerCase(); - if (vals.indexOf(fld) === -1) { - vals.push(fld); - val = val ? val + ", " + fields[i5] : fields[i5]; - } - } - return val; - } - function parse5(header) { - var end = 0; - var list2 = []; - var start = 0; - for (var i5 = 0, len = header.length; i5 < len; i5++) { - switch (header.charCodeAt(i5)) { - case 32: - if (start === end) { - start = end = i5 + 1; - } - break; - case 44: - list2.push(header.substring(start, end)); - start = end = i5 + 1; - break; - default: - end = i5 + 1; - break; - } - } - list2.push(header.substring(start, end)); - return list2; - } - function vary(res, field) { - if (!res || !res.getHeader || !res.setHeader) { - throw new TypeError("res argument is required"); - } - var val = res.getHeader("Vary") || ""; - var header = Array.isArray(val) ? val.join(", ") : String(val); - if (val = append(header, field)) { - res.setHeader("Vary", val); - } - } - } -}); - -// node_modules/.pnpm/express@5.2.1/node_modules/express/lib/response.js -var require_response = __commonJS({ - "node_modules/.pnpm/express@5.2.1/node_modules/express/lib/response.js"(exports, module) { - "use strict"; - var contentDisposition = require_content_disposition(); - var createError = require_http_errors(); - var deprecate2 = require_depd()("express"); - var encodeUrl = require_encodeurl(); - var escapeHtml = require_escape_html(); - var http = __require("node:http"); - var onFinished = require_on_finished(); - var mime = require_mime_types(); - var path53 = __require("node:path"); - var pathIsAbsolute = __require("node:path").isAbsolute; - var statuses = require_statuses(); - var sign2 = require_cookie_signature().sign; - var normalizeType = require_utils3().normalizeType; - var normalizeTypes = require_utils3().normalizeTypes; - var setCharset = require_utils3().setCharset; - var cookie = require_cookie(); - var send = require_send(); - var extname2 = path53.extname; - var resolve4 = path53.resolve; - var vary = require_vary(); - var { Buffer: Buffer2 } = __require("node:buffer"); - var res = Object.create(http.ServerResponse.prototype); - module.exports = res; - res.status = function status(code) { - if (!Number.isInteger(code)) { - throw new TypeError(`Invalid status code: ${JSON.stringify(code)}. Status code must be an integer.`); - } - if (code < 100 || code > 999) { - throw new RangeError(`Invalid status code: ${JSON.stringify(code)}. Status code must be greater than 99 and less than 1000.`); - } - this.statusCode = code; - return this; - }; - res.links = function(links) { - var link = this.get("Link") || ""; - if (link) link += ", "; - return this.set("Link", link + Object.keys(links).map(function(rel) { - if (Array.isArray(links[rel])) { - return links[rel].map(function(singleLink) { - return `<${singleLink}>; rel="${rel}"`; - }).join(", "); - } else { - return `<${links[rel]}>; rel="${rel}"`; - } - }).join(", ")); - }; - res.send = function send2(body) { - var chunk = body; - var encoding; - var req = this.req; - var type; - var app = this.app; - switch (typeof chunk) { - // string defaulting to html - case "string": - if (!this.get("Content-Type")) { - this.type("html"); - } - break; - case "boolean": - case "number": - case "object": - if (chunk === null) { - chunk = ""; - } else if (ArrayBuffer.isView(chunk)) { - if (!this.get("Content-Type")) { - this.type("bin"); - } - } else { - return this.json(chunk); - } - break; - } - if (typeof chunk === "string") { - encoding = "utf8"; - type = this.get("Content-Type"); - if (typeof type === "string") { - this.set("Content-Type", setCharset(type, "utf-8")); - } - } - var etagFn = app.get("etag fn"); - var generateETag = !this.get("ETag") && typeof etagFn === "function"; - var len; - if (chunk !== void 0) { - if (Buffer2.isBuffer(chunk)) { - len = chunk.length; - } else if (!generateETag && chunk.length < 1e3) { - len = Buffer2.byteLength(chunk, encoding); - } else { - chunk = Buffer2.from(chunk, encoding); - encoding = void 0; - len = chunk.length; - } - this.set("Content-Length", len); - } - var etag; - if (generateETag && len !== void 0) { - if (etag = etagFn(chunk, encoding)) { - this.set("ETag", etag); - } - } - if (req.fresh) this.status(304); - if (204 === this.statusCode || 304 === this.statusCode) { - this.removeHeader("Content-Type"); - this.removeHeader("Content-Length"); - this.removeHeader("Transfer-Encoding"); - chunk = ""; - } - if (this.statusCode === 205) { - this.set("Content-Length", "0"); - this.removeHeader("Transfer-Encoding"); - chunk = ""; - } - if (req.method === "HEAD") { - this.end(); - } else { - this.end(chunk, encoding); - } - return this; - }; - res.json = function json3(obj) { - var app = this.app; - var escape3 = app.get("json escape"); - var replacer = app.get("json replacer"); - var spaces = app.get("json spaces"); - var body = stringify2(obj, replacer, spaces, escape3); - if (!this.get("Content-Type")) { - this.set("Content-Type", "application/json"); - } - return this.send(body); - }; - res.jsonp = function jsonp(obj) { - var app = this.app; - var escape3 = app.get("json escape"); - var replacer = app.get("json replacer"); - var spaces = app.get("json spaces"); - var body = stringify2(obj, replacer, spaces, escape3); - var callback = this.req.query[app.get("jsonp callback name")]; - if (!this.get("Content-Type")) { - this.set("X-Content-Type-Options", "nosniff"); - this.set("Content-Type", "application/json"); - } - if (Array.isArray(callback)) { - callback = callback[0]; - } - if (typeof callback === "string" && callback.length !== 0) { - this.set("X-Content-Type-Options", "nosniff"); - this.set("Content-Type", "text/javascript"); - callback = callback.replace(/[^\[\]\w$.]/g, ""); - if (body === void 0) { - body = ""; - } else if (typeof body === "string") { - body = body.replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029"); - } - body = "/**/ typeof " + callback + " === 'function' && " + callback + "(" + body + ");"; - } - return this.send(body); - }; - res.sendStatus = function sendStatus(statusCode) { - var body = statuses.message[statusCode] || String(statusCode); - this.status(statusCode); - this.type("txt"); - return this.send(body); - }; - res.sendFile = function sendFile(path54, options, callback) { - var done = callback; - var req = this.req; - var res2 = this; - var next = req.next; - var opts = options || {}; - if (!path54) { - throw new TypeError("path argument is required to res.sendFile"); - } - if (typeof path54 !== "string") { - throw new TypeError("path must be a string to res.sendFile"); - } - if (typeof options === "function") { - done = options; - opts = {}; - } - if (!opts.root && !pathIsAbsolute(path54)) { - throw new TypeError("path must be absolute or specify root to res.sendFile"); - } - var pathname = encodeURI(path54); - opts.etag = this.app.enabled("etag"); - var file2 = send(req, pathname, opts); - sendfile(res2, file2, opts, function(err) { - if (done) return done(err); - if (err && err.code === "EISDIR") return next(); - if (err && err.code !== "ECONNABORTED" && err.syscall !== "write") { - next(err); - } - }); - }; - res.download = function download(path54, filename, options, callback) { - var done = callback; - var name = filename; - var opts = options || null; - if (typeof filename === "function") { - done = filename; - name = null; - opts = null; - } else if (typeof options === "function") { - done = options; - opts = null; - } - if (typeof filename === "object" && (typeof options === "function" || options === void 0)) { - name = null; - opts = filename; - } - var headers = { - "Content-Disposition": contentDisposition(name || path54) - }; - if (opts && opts.headers) { - var keys = Object.keys(opts.headers); - for (var i5 = 0; i5 < keys.length; i5++) { - var key = keys[i5]; - if (key.toLowerCase() !== "content-disposition") { - headers[key] = opts.headers[key]; - } - } - } - opts = Object.create(opts); - opts.headers = headers; - var fullPath = !opts.root ? resolve4(path54) : path54; - return this.sendFile(fullPath, opts, done); - }; - res.contentType = res.type = function contentType(type) { - var ct = type.indexOf("/") === -1 ? mime.contentType(type) || "application/octet-stream" : type; - return this.set("Content-Type", ct); - }; - res.format = function(obj) { - var req = this.req; - var next = req.next; - var keys = Object.keys(obj).filter(function(v5) { - return v5 !== "default"; - }); - var key = keys.length > 0 ? req.accepts(keys) : false; - this.vary("Accept"); - if (key) { - this.set("Content-Type", normalizeType(key).value); - obj[key](req, this, next); - } else if (obj.default) { - obj.default(req, this, next); - } else { - next(createError(406, { - types: normalizeTypes(keys).map(function(o5) { - return o5.value; - }) - })); - } - return this; - }; - res.attachment = function attachment(filename) { - if (filename) { - this.type(extname2(filename)); - } - this.set("Content-Disposition", contentDisposition(filename)); - return this; - }; - res.append = function append(field, val) { - var prev = this.get(field); - var value = val; - if (prev) { - value = Array.isArray(prev) ? prev.concat(val) : Array.isArray(val) ? [prev].concat(val) : [prev, val]; - } - return this.set(field, value); - }; - res.set = res.header = function header(field, val) { - if (arguments.length === 2) { - var value = Array.isArray(val) ? val.map(String) : String(val); - if (field.toLowerCase() === "content-type") { - if (Array.isArray(value)) { - throw new TypeError("Content-Type cannot be set to an Array"); - } - value = mime.contentType(value); - } - this.setHeader(field, value); - } else { - for (var key in field) { - this.set(key, field[key]); - } - } - return this; - }; - res.get = function(field) { - return this.getHeader(field); - }; - res.clearCookie = function clearCookie(name, options) { - const opts = { path: "/", ...options, expires: /* @__PURE__ */ new Date(1) }; - delete opts.maxAge; - return this.cookie(name, "", opts); - }; - res.cookie = function(name, value, options) { - var opts = { ...options }; - var secret = this.req.secret; - var signed = opts.signed; - if (signed && !secret) { - throw new Error('cookieParser("secret") required for signed cookies'); - } - var val = typeof value === "object" ? "j:" + JSON.stringify(value) : String(value); - if (signed) { - val = "s:" + sign2(val, secret); - } - if (opts.maxAge != null) { - var maxAge = opts.maxAge - 0; - if (!isNaN(maxAge)) { - opts.expires = new Date(Date.now() + maxAge); - opts.maxAge = Math.floor(maxAge / 1e3); - } - } - if (opts.path == null) { - opts.path = "/"; - } - this.append("Set-Cookie", cookie.serialize(name, String(val), opts)); - return this; - }; - res.location = function location(url2) { - return this.set("Location", encodeUrl(url2)); - }; - res.redirect = function redirect(url2) { - var address = url2; - var body; - var status = 302; - if (arguments.length === 2) { - status = arguments[0]; - address = arguments[1]; - } - if (!address) { - deprecate2("Provide a url argument"); - } - if (typeof address !== "string") { - deprecate2("Url must be a string"); - } - if (typeof status !== "number") { - deprecate2("Status must be a number"); - } - address = this.location(address).get("Location"); - this.format({ - text: function() { - body = statuses.message[status] + ". Redirecting to " + address; - }, - html: function() { - var u5 = escapeHtml(address); - body = "

" + statuses.message[status] + ". Redirecting to " + u5 + "

"; - }, - default: function() { - body = ""; - } - }); - this.status(status); - this.set("Content-Length", Buffer2.byteLength(body)); - if (this.req.method === "HEAD") { - this.end(); - } else { - this.end(body); - } - }; - res.vary = function(field) { - vary(this, field); - return this; - }; - res.render = function render(view, options, callback) { - var app = this.req.app; - var done = callback; - var opts = options || {}; - var req = this.req; - var self2 = this; - if (typeof options === "function") { - done = options; - opts = {}; - } - opts._locals = self2.locals; - done = done || function(err, str) { - if (err) return req.next(err); - self2.send(str); - }; - app.render(view, opts, done); - }; - function sendfile(res2, file2, options, callback) { - var done = false; - var streaming; - function onaborted() { - if (done) return; - done = true; - var err = new Error("Request aborted"); - err.code = "ECONNABORTED"; - callback(err); - } - function ondirectory() { - if (done) return; - done = true; - var err = new Error("EISDIR, read"); - err.code = "EISDIR"; - callback(err); - } - function onerror(err) { - if (done) return; - done = true; - callback(err); - } - function onend() { - if (done) return; - done = true; - callback(); - } - function onfile() { - streaming = false; - } - function onfinish(err) { - if (err && err.code === "ECONNRESET") return onaborted(); - if (err) return onerror(err); - if (done) return; - setImmediate(function() { - if (streaming !== false && !done) { - onaborted(); - return; - } - if (done) return; - done = true; - callback(); - }); - } - function onstream() { - streaming = true; - } - file2.on("directory", ondirectory); - file2.on("end", onend); - file2.on("error", onerror); - file2.on("file", onfile); - file2.on("stream", onstream); - onFinished(res2, onfinish); - if (options.headers) { - file2.on("headers", function headers(res3) { - var obj = options.headers; - var keys = Object.keys(obj); - for (var i5 = 0; i5 < keys.length; i5++) { - var k5 = keys[i5]; - res3.setHeader(k5, obj[k5]); - } - }); - } - file2.pipe(res2); - } - function stringify2(value, replacer, spaces, escape3) { - var json3 = replacer || spaces ? JSON.stringify(value, replacer, spaces) : JSON.stringify(value); - if (escape3 && typeof json3 === "string") { - json3 = json3.replace(/[<>&]/g, function(c5) { - switch (c5.charCodeAt(0)) { - case 60: - return "\\u003c"; - case 62: - return "\\u003e"; - case 38: - return "\\u0026"; - /* istanbul ignore next: unreachable default */ - default: - return c5; - } - }); - } - return json3; - } - } -}); - -// node_modules/.pnpm/serve-static@2.2.1/node_modules/serve-static/index.js -var require_serve_static = __commonJS({ - "node_modules/.pnpm/serve-static@2.2.1/node_modules/serve-static/index.js"(exports, module) { - "use strict"; - var encodeUrl = require_encodeurl(); - var escapeHtml = require_escape_html(); - var parseUrl7 = require_parseurl(); - var resolve4 = __require("path").resolve; - var send = require_send(); - var url2 = __require("url"); - module.exports = serveStatic; - function serveStatic(root, options) { - if (!root) { - throw new TypeError("root path required"); - } - if (typeof root !== "string") { - throw new TypeError("root path must be a string"); - } - var opts = Object.create(options || null); - var fallthrough = opts.fallthrough !== false; - var redirect = opts.redirect !== false; - var setHeaders = opts.setHeaders; - if (setHeaders && typeof setHeaders !== "function") { - throw new TypeError("option setHeaders must be function"); - } - opts.maxage = opts.maxage || opts.maxAge || 0; - opts.root = resolve4(root); - var onDirectory = redirect ? createRedirectDirectoryListener() : createNotFoundDirectoryListener(); - return function serveStatic2(req, res, next) { - if (req.method !== "GET" && req.method !== "HEAD") { - if (fallthrough) { - return next(); - } - res.statusCode = 405; - res.setHeader("Allow", "GET, HEAD"); - res.setHeader("Content-Length", "0"); - res.end(); - return; - } - var forwardError = !fallthrough; - var originalUrl = parseUrl7.original(req); - var path53 = parseUrl7(req).pathname; - if (path53 === "/" && originalUrl.pathname.substr(-1) !== "/") { - path53 = ""; - } - var stream = send(req, path53, opts); - stream.on("directory", onDirectory); - if (setHeaders) { - stream.on("headers", setHeaders); - } - if (fallthrough) { - stream.on("file", function onFile() { - forwardError = true; - }); - } - stream.on("error", function error50(err) { - if (forwardError || !(err.statusCode < 500)) { - next(err); - return; - } - next(); - }); - stream.pipe(res); - }; - } - function collapseLeadingSlashes(str) { - for (var i5 = 0; i5 < str.length; i5++) { - if (str.charCodeAt(i5) !== 47) { - break; - } - } - return i5 > 1 ? "/" + str.substr(i5) : str; - } - function createHtmlDocument(title, body) { - return '\n\n\n\n' + title + "\n\n\n
" + body + "
\n\n\n"; - } - function createNotFoundDirectoryListener() { - return function notFound2() { - this.error(404); - }; - } - function createRedirectDirectoryListener() { - return function redirect(res) { - if (this.hasTrailingSlash()) { - this.error(404); - return; - } - var originalUrl = parseUrl7.original(this.req); - originalUrl.path = null; - originalUrl.pathname = collapseLeadingSlashes(originalUrl.pathname + "/"); - var loc = encodeUrl(url2.format(originalUrl)); - var doc = createHtmlDocument("Redirecting", "Redirecting to " + escapeHtml(loc)); - res.statusCode = 301; - res.setHeader("Content-Type", "text/html; charset=UTF-8"); - res.setHeader("Content-Length", Buffer.byteLength(doc)); - res.setHeader("Content-Security-Policy", "default-src 'none'"); - res.setHeader("X-Content-Type-Options", "nosniff"); - res.setHeader("Location", loc); - res.end(doc); - }; - } - } -}); - -// node_modules/.pnpm/express@5.2.1/node_modules/express/lib/express.js -var require_express = __commonJS({ - "node_modules/.pnpm/express@5.2.1/node_modules/express/lib/express.js"(exports, module) { - "use strict"; - var bodyParser = require_body_parser(); - var EventEmitter5 = __require("node:events").EventEmitter; - var mixin = require_merge_descriptors(); - var proto = require_application(); - var Router26 = require_router(); - var req = require_request(); - var res = require_response(); - exports = module.exports = createApplication; - function createApplication() { - var app = function(req2, res2, next) { - app.handle(req2, res2, next); - }; - mixin(app, EventEmitter5.prototype, false); - mixin(app, proto, false); - app.request = Object.create(req, { - app: { configurable: true, enumerable: true, writable: true, value: app } - }); - app.response = Object.create(res, { - app: { configurable: true, enumerable: true, writable: true, value: app } - }); - app.init(); - return app; - } - exports.application = proto; - exports.request = req; - exports.response = res; - exports.Route = Router26.Route; - exports.Router = Router26; - exports.json = bodyParser.json; - exports.raw = bodyParser.raw; - exports.static = require_serve_static(); - exports.text = bodyParser.text; - exports.urlencoded = bodyParser.urlencoded; - } -}); - -// node_modules/.pnpm/express@5.2.1/node_modules/express/index.js -var require_express2 = __commonJS({ - "node_modules/.pnpm/express@5.2.1/node_modules/express/index.js"(exports, module) { - "use strict"; - module.exports = require_express(); - } -}); - -// node_modules/.pnpm/pino-std-serializers@7.1.0/node_modules/pino-std-serializers/lib/err-helpers.js -var require_err_helpers = __commonJS({ - "node_modules/.pnpm/pino-std-serializers@7.1.0/node_modules/pino-std-serializers/lib/err-helpers.js"(exports, module) { - "use strict"; - var isErrorLike = (err) => { - return err && typeof err.message === "string"; - }; - var getErrorCause = (err) => { - if (!err) return; - const cause = err.cause; - if (typeof cause === "function") { - const causeResult = err.cause(); - return isErrorLike(causeResult) ? causeResult : void 0; - } else { - return isErrorLike(cause) ? cause : void 0; - } - }; - var _stackWithCauses = (err, seen) => { - if (!isErrorLike(err)) return ""; - const stack = err.stack || ""; - if (seen.has(err)) { - return stack + "\ncauses have become circular..."; - } - const cause = getErrorCause(err); - if (cause) { - seen.add(err); - return stack + "\ncaused by: " + _stackWithCauses(cause, seen); - } else { - return stack; - } - }; - var stackWithCauses = (err) => _stackWithCauses(err, /* @__PURE__ */ new Set()); - var _messageWithCauses = (err, seen, skip) => { - if (!isErrorLike(err)) return ""; - const message2 = skip ? "" : err.message || ""; - if (seen.has(err)) { - return message2 + ": ..."; - } - const cause = getErrorCause(err); - if (cause) { - seen.add(err); - const skipIfVErrorStyleCause = typeof err.cause === "function"; - return message2 + (skipIfVErrorStyleCause ? "" : ": ") + _messageWithCauses(cause, seen, skipIfVErrorStyleCause); - } else { - return message2; - } - }; - var messageWithCauses = (err) => _messageWithCauses(err, /* @__PURE__ */ new Set()); - module.exports = { - isErrorLike, - getErrorCause, - stackWithCauses, - messageWithCauses - }; - } -}); - -// node_modules/.pnpm/pino-std-serializers@7.1.0/node_modules/pino-std-serializers/lib/err-proto.js -var require_err_proto = __commonJS({ - "node_modules/.pnpm/pino-std-serializers@7.1.0/node_modules/pino-std-serializers/lib/err-proto.js"(exports, module) { - "use strict"; - var seen = /* @__PURE__ */ Symbol("circular-ref-tag"); - var rawSymbol = /* @__PURE__ */ Symbol("pino-raw-err-ref"); - var pinoErrProto = Object.create({}, { - type: { - enumerable: true, - writable: true, - value: void 0 - }, - message: { - enumerable: true, - writable: true, - value: void 0 - }, - stack: { - enumerable: true, - writable: true, - value: void 0 - }, - aggregateErrors: { - enumerable: true, - writable: true, - value: void 0 - }, - raw: { - enumerable: false, - get: function() { - return this[rawSymbol]; - }, - set: function(val) { - this[rawSymbol] = val; - } - } - }); - Object.defineProperty(pinoErrProto, rawSymbol, { - writable: true, - value: {} - }); - module.exports = { - pinoErrProto, - pinoErrorSymbols: { - seen, - rawSymbol - } - }; - } -}); - -// node_modules/.pnpm/pino-std-serializers@7.1.0/node_modules/pino-std-serializers/lib/err.js -var require_err = __commonJS({ - "node_modules/.pnpm/pino-std-serializers@7.1.0/node_modules/pino-std-serializers/lib/err.js"(exports, module) { - "use strict"; - module.exports = errSerializer; - var { messageWithCauses, stackWithCauses, isErrorLike } = require_err_helpers(); - var { pinoErrProto, pinoErrorSymbols } = require_err_proto(); - var { seen } = pinoErrorSymbols; - var { toString } = Object.prototype; - function errSerializer(err) { - if (!isErrorLike(err)) { - return err; - } - err[seen] = void 0; - const _err = Object.create(pinoErrProto); - _err.type = toString.call(err.constructor) === "[object Function]" ? err.constructor.name : err.name; - _err.message = messageWithCauses(err); - _err.stack = stackWithCauses(err); - if (Array.isArray(err.errors)) { - _err.aggregateErrors = err.errors.map((err2) => errSerializer(err2)); - } - for (const key in err) { - if (_err[key] === void 0) { - const val = err[key]; - if (isErrorLike(val)) { - if (key !== "cause" && !Object.prototype.hasOwnProperty.call(val, seen)) { - _err[key] = errSerializer(val); - } - } else { - _err[key] = val; - } - } - } - delete err[seen]; - _err.raw = err; - return _err; - } - } -}); - -// node_modules/.pnpm/pino-std-serializers@7.1.0/node_modules/pino-std-serializers/lib/err-with-cause.js -var require_err_with_cause = __commonJS({ - "node_modules/.pnpm/pino-std-serializers@7.1.0/node_modules/pino-std-serializers/lib/err-with-cause.js"(exports, module) { - "use strict"; - module.exports = errWithCauseSerializer; - var { isErrorLike } = require_err_helpers(); - var { pinoErrProto, pinoErrorSymbols } = require_err_proto(); - var { seen } = pinoErrorSymbols; - var { toString } = Object.prototype; - function errWithCauseSerializer(err) { - if (!isErrorLike(err)) { - return err; - } - err[seen] = void 0; - const _err = Object.create(pinoErrProto); - _err.type = toString.call(err.constructor) === "[object Function]" ? err.constructor.name : err.name; - _err.message = err.message; - _err.stack = err.stack; - if (Array.isArray(err.errors)) { - _err.aggregateErrors = err.errors.map((err2) => errWithCauseSerializer(err2)); - } - if (isErrorLike(err.cause) && !Object.prototype.hasOwnProperty.call(err.cause, seen)) { - _err.cause = errWithCauseSerializer(err.cause); - } - for (const key in err) { - if (_err[key] === void 0) { - const val = err[key]; - if (isErrorLike(val)) { - if (!Object.prototype.hasOwnProperty.call(val, seen)) { - _err[key] = errWithCauseSerializer(val); - } - } else { - _err[key] = val; - } - } - } - delete err[seen]; - _err.raw = err; - return _err; - } - } -}); - -// node_modules/.pnpm/pino-std-serializers@7.1.0/node_modules/pino-std-serializers/lib/req.js -var require_req = __commonJS({ - "node_modules/.pnpm/pino-std-serializers@7.1.0/node_modules/pino-std-serializers/lib/req.js"(exports, module) { - "use strict"; - module.exports = { - mapHttpRequest, - reqSerializer - }; - var rawSymbol = /* @__PURE__ */ Symbol("pino-raw-req-ref"); - var pinoReqProto = Object.create({}, { - id: { - enumerable: true, - writable: true, - value: "" - }, - method: { - enumerable: true, - writable: true, - value: "" - }, - url: { - enumerable: true, - writable: true, - value: "" - }, - query: { - enumerable: true, - writable: true, - value: "" - }, - params: { - enumerable: true, - writable: true, - value: "" - }, - headers: { - enumerable: true, - writable: true, - value: {} - }, - remoteAddress: { - enumerable: true, - writable: true, - value: "" - }, - remotePort: { - enumerable: true, - writable: true, - value: "" - }, - raw: { - enumerable: false, - get: function() { - return this[rawSymbol]; - }, - set: function(val) { - this[rawSymbol] = val; - } - } - }); - Object.defineProperty(pinoReqProto, rawSymbol, { - writable: true, - value: {} - }); - function reqSerializer(req) { - const connection2 = req.info || req.socket; - const _req = Object.create(pinoReqProto); - _req.id = typeof req.id === "function" ? req.id() : req.id || (req.info ? req.info.id : void 0); - _req.method = req.method; - if (req.originalUrl) { - _req.url = req.originalUrl; - } else { - const path53 = req.path; - _req.url = typeof path53 === "string" ? path53 : req.url ? req.url.path || req.url : void 0; - } - if (req.query) { - _req.query = req.query; - } - if (req.params) { - _req.params = req.params; - } - _req.headers = req.headers; - _req.remoteAddress = connection2 && connection2.remoteAddress; - _req.remotePort = connection2 && connection2.remotePort; - _req.raw = req.raw || req; - return _req; - } - function mapHttpRequest(req) { - return { - req: reqSerializer(req) - }; - } - } -}); - -// node_modules/.pnpm/pino-std-serializers@7.1.0/node_modules/pino-std-serializers/lib/res.js -var require_res = __commonJS({ - "node_modules/.pnpm/pino-std-serializers@7.1.0/node_modules/pino-std-serializers/lib/res.js"(exports, module) { - "use strict"; - module.exports = { - mapHttpResponse, - resSerializer - }; - var rawSymbol = /* @__PURE__ */ Symbol("pino-raw-res-ref"); - var pinoResProto = Object.create({}, { - statusCode: { - enumerable: true, - writable: true, - value: 0 - }, - headers: { - enumerable: true, - writable: true, - value: "" - }, - raw: { - enumerable: false, - get: function() { - return this[rawSymbol]; - }, - set: function(val) { - this[rawSymbol] = val; - } - } - }); - Object.defineProperty(pinoResProto, rawSymbol, { - writable: true, - value: {} - }); - function resSerializer(res) { - const _res = Object.create(pinoResProto); - _res.statusCode = res.headersSent ? res.statusCode : null; - _res.headers = res.getHeaders ? res.getHeaders() : res._headers; - _res.raw = res; - return _res; - } - function mapHttpResponse(res) { - return { - res: resSerializer(res) - }; - } - } -}); - -// node_modules/.pnpm/pino-std-serializers@7.1.0/node_modules/pino-std-serializers/index.js -var require_pino_std_serializers = __commonJS({ - "node_modules/.pnpm/pino-std-serializers@7.1.0/node_modules/pino-std-serializers/index.js"(exports, module) { - "use strict"; - var errSerializer = require_err(); - var errWithCauseSerializer = require_err_with_cause(); - var reqSerializers = require_req(); - var resSerializers = require_res(); - module.exports = { - err: errSerializer, - errWithCause: errWithCauseSerializer, - mapHttpRequest: reqSerializers.mapHttpRequest, - mapHttpResponse: resSerializers.mapHttpResponse, - req: reqSerializers.reqSerializer, - res: resSerializers.resSerializer, - wrapErrorSerializer: function wrapErrorSerializer(customSerializer) { - if (customSerializer === errSerializer) return customSerializer; - return function wrapErrSerializer(err) { - return customSerializer(errSerializer(err)); - }; - }, - wrapRequestSerializer: function wrapRequestSerializer(customSerializer) { - if (customSerializer === reqSerializers.reqSerializer) return customSerializer; - return function wrappedReqSerializer(req) { - return customSerializer(reqSerializers.reqSerializer(req)); - }; - }, - wrapResponseSerializer: function wrapResponseSerializer(customSerializer) { - if (customSerializer === resSerializers.resSerializer) return customSerializer; - return function wrappedResSerializer(res) { - return customSerializer(resSerializers.resSerializer(res)); - }; - } - }; - } -}); - -// node_modules/.pnpm/pino@9.14.0/node_modules/pino/lib/caller.js -var require_caller = __commonJS({ - "node_modules/.pnpm/pino@9.14.0/node_modules/pino/lib/caller.js"(exports, module) { - "use strict"; - function noOpPrepareStackTrace(_, stack) { - return stack; - } - module.exports = function getCallers() { - const originalPrepare = Error.prepareStackTrace; - Error.prepareStackTrace = noOpPrepareStackTrace; - const stack = new Error().stack; - Error.prepareStackTrace = originalPrepare; - if (!Array.isArray(stack)) { - return void 0; - } - const entries2 = stack.slice(2); - const fileNames = []; - for (const entry of entries2) { - if (!entry) { - continue; - } - fileNames.push(entry.getFileName()); - } - return fileNames; - }; - } -}); - -// node_modules/.pnpm/@pinojs+redact@0.4.0/node_modules/@pinojs/redact/index.js -var require_redact = __commonJS({ - "node_modules/.pnpm/@pinojs+redact@0.4.0/node_modules/@pinojs/redact/index.js"(exports, module) { - "use strict"; - function deepClone(obj) { - if (obj === null || typeof obj !== "object") { - return obj; - } - if (obj instanceof Date) { - return new Date(obj.getTime()); - } - if (obj instanceof Array) { - const cloned = []; - for (let i5 = 0; i5 < obj.length; i5++) { - cloned[i5] = deepClone(obj[i5]); - } - return cloned; - } - if (typeof obj === "object") { - const cloned = Object.create(Object.getPrototypeOf(obj)); - for (const key in obj) { - if (Object.prototype.hasOwnProperty.call(obj, key)) { - cloned[key] = deepClone(obj[key]); - } - } - return cloned; - } - return obj; - } - function parsePath(path53) { - const parts = []; - let current = ""; - let inBrackets = false; - let inQuotes = false; - let quoteChar = ""; - for (let i5 = 0; i5 < path53.length; i5++) { - const char2 = path53[i5]; - if (!inBrackets && char2 === ".") { - if (current) { - parts.push(current); - current = ""; - } - } else if (char2 === "[") { - if (current) { - parts.push(current); - current = ""; - } - inBrackets = true; - } else if (char2 === "]" && inBrackets) { - parts.push(current); - current = ""; - inBrackets = false; - inQuotes = false; - } else if ((char2 === '"' || char2 === "'") && inBrackets) { - if (!inQuotes) { - inQuotes = true; - quoteChar = char2; - } else if (char2 === quoteChar) { - inQuotes = false; - quoteChar = ""; - } else { - current += char2; - } - } else { - current += char2; - } - } - if (current) { - parts.push(current); - } - return parts; - } - function setValue(obj, parts, value) { - let current = obj; - for (let i5 = 0; i5 < parts.length - 1; i5++) { - const key = parts[i5]; - if (typeof current !== "object" || current === null || !(key in current)) { - return false; - } - if (typeof current[key] !== "object" || current[key] === null) { - return false; - } - current = current[key]; - } - const lastKey = parts[parts.length - 1]; - if (lastKey === "*") { - if (Array.isArray(current)) { - for (let i5 = 0; i5 < current.length; i5++) { - current[i5] = value; - } - } else if (typeof current === "object" && current !== null) { - for (const key in current) { - if (Object.prototype.hasOwnProperty.call(current, key)) { - current[key] = value; - } - } - } - } else { - if (typeof current === "object" && current !== null && lastKey in current && Object.prototype.hasOwnProperty.call(current, lastKey)) { - current[lastKey] = value; - } - } - return true; - } - function removeKey(obj, parts) { - let current = obj; - for (let i5 = 0; i5 < parts.length - 1; i5++) { - const key = parts[i5]; - if (typeof current !== "object" || current === null || !(key in current)) { - return false; - } - if (typeof current[key] !== "object" || current[key] === null) { - return false; - } - current = current[key]; - } - const lastKey = parts[parts.length - 1]; - if (lastKey === "*") { - if (Array.isArray(current)) { - for (let i5 = 0; i5 < current.length; i5++) { - current[i5] = void 0; - } - } else if (typeof current === "object" && current !== null) { - for (const key in current) { - if (Object.prototype.hasOwnProperty.call(current, key)) { - delete current[key]; - } - } - } - } else { - if (typeof current === "object" && current !== null && lastKey in current && Object.prototype.hasOwnProperty.call(current, lastKey)) { - delete current[lastKey]; - } - } - return true; - } - var PATH_NOT_FOUND = /* @__PURE__ */ Symbol("PATH_NOT_FOUND"); - function getValueIfExists(obj, parts) { - let current = obj; - for (const part of parts) { - if (current === null || current === void 0) { - return PATH_NOT_FOUND; - } - if (typeof current !== "object" || current === null) { - return PATH_NOT_FOUND; - } - if (!(part in current)) { - return PATH_NOT_FOUND; - } - current = current[part]; - } - return current; - } - function getValue(obj, parts) { - let current = obj; - for (const part of parts) { - if (current === null || current === void 0) { - return void 0; - } - if (typeof current !== "object" || current === null) { - return void 0; - } - current = current[part]; - } - return current; - } - function redactPaths(obj, paths2, censor, remove = false) { - for (const path53 of paths2) { - const parts = parsePath(path53); - if (parts.includes("*")) { - redactWildcardPath(obj, parts, censor, path53, remove); - } else { - if (remove) { - removeKey(obj, parts); - } else { - const value = getValueIfExists(obj, parts); - if (value === PATH_NOT_FOUND) { - continue; - } - const actualCensor = typeof censor === "function" ? censor(value, parts) : censor; - setValue(obj, parts, actualCensor); - } - } - } - } - function redactWildcardPath(obj, parts, censor, originalPath, remove = false) { - const wildcardIndex = parts.indexOf("*"); - if (wildcardIndex === parts.length - 1) { - const parentParts = parts.slice(0, -1); - let current = obj; - for (const part of parentParts) { - if (current === null || current === void 0) return; - if (typeof current !== "object" || current === null) return; - current = current[part]; - } - if (Array.isArray(current)) { - if (remove) { - for (let i5 = 0; i5 < current.length; i5++) { - current[i5] = void 0; - } - } else { - for (let i5 = 0; i5 < current.length; i5++) { - const indexPath = [...parentParts, i5.toString()]; - const actualCensor = typeof censor === "function" ? censor(current[i5], indexPath) : censor; - current[i5] = actualCensor; - } - } - } else if (typeof current === "object" && current !== null) { - if (remove) { - const keysToDelete = []; - for (const key in current) { - if (Object.prototype.hasOwnProperty.call(current, key)) { - keysToDelete.push(key); - } - } - for (const key of keysToDelete) { - delete current[key]; - } - } else { - for (const key in current) { - const keyPath = [...parentParts, key]; - const actualCensor = typeof censor === "function" ? censor(current[key], keyPath) : censor; - current[key] = actualCensor; - } - } - } - } else { - redactIntermediateWildcard(obj, parts, censor, wildcardIndex, originalPath, remove); - } - } - function redactIntermediateWildcard(obj, parts, censor, wildcardIndex, originalPath, remove = false) { - const beforeWildcard = parts.slice(0, wildcardIndex); - const afterWildcard = parts.slice(wildcardIndex + 1); - const pathArray = []; - function traverse(current, pathLength) { - if (pathLength === beforeWildcard.length) { - if (Array.isArray(current)) { - for (let i5 = 0; i5 < current.length; i5++) { - pathArray[pathLength] = i5.toString(); - traverse(current[i5], pathLength + 1); - } - } else if (typeof current === "object" && current !== null) { - for (const key in current) { - pathArray[pathLength] = key; - traverse(current[key], pathLength + 1); - } - } - } else if (pathLength < beforeWildcard.length) { - const nextKey = beforeWildcard[pathLength]; - if (current && typeof current === "object" && current !== null && nextKey in current) { - pathArray[pathLength] = nextKey; - traverse(current[nextKey], pathLength + 1); - } - } else { - if (afterWildcard.includes("*")) { - const wrappedCensor = typeof censor === "function" ? (value, path53) => { - const fullPath = [...pathArray.slice(0, pathLength), ...path53]; - return censor(value, fullPath); - } : censor; - redactWildcardPath(current, afterWildcard, wrappedCensor, originalPath, remove); - } else { - if (remove) { - removeKey(current, afterWildcard); - } else { - const actualCensor = typeof censor === "function" ? censor(getValue(current, afterWildcard), [...pathArray.slice(0, pathLength), ...afterWildcard]) : censor; - setValue(current, afterWildcard, actualCensor); - } - } - } - } - if (beforeWildcard.length === 0) { - traverse(obj, 0); - } else { - let current = obj; - for (let i5 = 0; i5 < beforeWildcard.length; i5++) { - const part = beforeWildcard[i5]; - if (current === null || current === void 0) return; - if (typeof current !== "object" || current === null) return; - current = current[part]; - pathArray[i5] = part; - } - if (current !== null && current !== void 0) { - traverse(current, beforeWildcard.length); - } - } - } - function buildPathStructure(pathsToClone) { - if (pathsToClone.length === 0) { - return null; - } - const pathStructure = /* @__PURE__ */ new Map(); - for (const path53 of pathsToClone) { - const parts = parsePath(path53); - let current = pathStructure; - for (let i5 = 0; i5 < parts.length; i5++) { - const part = parts[i5]; - if (!current.has(part)) { - current.set(part, /* @__PURE__ */ new Map()); - } - current = current.get(part); - } - } - return pathStructure; - } - function selectiveClone(obj, pathStructure) { - if (!pathStructure) { - return obj; - } - function cloneSelectively(source, pathMap, depth = 0) { - if (!pathMap || pathMap.size === 0) { - return source; - } - if (source === null || typeof source !== "object") { - return source; - } - if (source instanceof Date) { - return new Date(source.getTime()); - } - if (Array.isArray(source)) { - const cloned2 = []; - for (let i5 = 0; i5 < source.length; i5++) { - const indexStr = i5.toString(); - if (pathMap.has(indexStr) || pathMap.has("*")) { - cloned2[i5] = cloneSelectively(source[i5], pathMap.get(indexStr) || pathMap.get("*")); - } else { - cloned2[i5] = source[i5]; - } - } - return cloned2; - } - const cloned = Object.create(Object.getPrototypeOf(source)); - for (const key in source) { - if (Object.prototype.hasOwnProperty.call(source, key)) { - if (pathMap.has(key) || pathMap.has("*")) { - cloned[key] = cloneSelectively(source[key], pathMap.get(key) || pathMap.get("*")); - } else { - cloned[key] = source[key]; - } - } - } - return cloned; - } - return cloneSelectively(obj, pathStructure); - } - function validatePath(path53) { - if (typeof path53 !== "string") { - throw new Error("Paths must be (non-empty) strings"); - } - if (path53 === "") { - throw new Error("Invalid redaction path ()"); - } - if (path53.includes("..")) { - throw new Error(`Invalid redaction path (${path53})`); - } - if (path53.includes(",")) { - throw new Error(`Invalid redaction path (${path53})`); - } - let bracketCount = 0; - let inQuotes = false; - let quoteChar = ""; - for (let i5 = 0; i5 < path53.length; i5++) { - const char2 = path53[i5]; - if ((char2 === '"' || char2 === "'") && bracketCount > 0) { - if (!inQuotes) { - inQuotes = true; - quoteChar = char2; - } else if (char2 === quoteChar) { - inQuotes = false; - quoteChar = ""; - } - } else if (char2 === "[" && !inQuotes) { - bracketCount++; - } else if (char2 === "]" && !inQuotes) { - bracketCount--; - if (bracketCount < 0) { - throw new Error(`Invalid redaction path (${path53})`); - } - } - } - if (bracketCount !== 0) { - throw new Error(`Invalid redaction path (${path53})`); - } - } - function validatePaths(paths2) { - if (!Array.isArray(paths2)) { - throw new TypeError("paths must be an array"); - } - for (const path53 of paths2) { - validatePath(path53); - } - } - function slowRedact(options = {}) { - const { - paths: paths2 = [], - censor = "[REDACTED]", - serialize = JSON.stringify, - strict = true, - remove = false - } = options; - validatePaths(paths2); - const pathStructure = buildPathStructure(paths2); - return function redact(obj) { - if (strict && (obj === null || typeof obj !== "object")) { - if (obj === null || obj === void 0) { - return serialize ? serialize(obj) : obj; - } - if (typeof obj !== "object") { - return serialize ? serialize(obj) : obj; - } - } - const cloned = selectiveClone(obj, pathStructure); - const original = obj; - let actualCensor = censor; - if (typeof censor === "function") { - actualCensor = censor; - } - redactPaths(cloned, paths2, actualCensor, remove); - if (serialize === false) { - cloned.restore = function() { - return deepClone(original); - }; - return cloned; - } - if (typeof serialize === "function") { - return serialize(cloned); - } - return JSON.stringify(cloned); - }; - } - module.exports = slowRedact; - } -}); - -// node_modules/.pnpm/pino@9.14.0/node_modules/pino/lib/symbols.js -var require_symbols = __commonJS({ - "node_modules/.pnpm/pino@9.14.0/node_modules/pino/lib/symbols.js"(exports, module) { - "use strict"; - var setLevelSym = /* @__PURE__ */ Symbol("pino.setLevel"); - var getLevelSym = /* @__PURE__ */ Symbol("pino.getLevel"); - var levelValSym = /* @__PURE__ */ Symbol("pino.levelVal"); - var levelCompSym = /* @__PURE__ */ Symbol("pino.levelComp"); - var useLevelLabelsSym = /* @__PURE__ */ Symbol("pino.useLevelLabels"); - var useOnlyCustomLevelsSym = /* @__PURE__ */ Symbol("pino.useOnlyCustomLevels"); - var mixinSym = /* @__PURE__ */ Symbol("pino.mixin"); - var lsCacheSym = /* @__PURE__ */ Symbol("pino.lsCache"); - var chindingsSym = /* @__PURE__ */ Symbol("pino.chindings"); - var asJsonSym = /* @__PURE__ */ Symbol("pino.asJson"); - var writeSym = /* @__PURE__ */ Symbol("pino.write"); - var redactFmtSym = /* @__PURE__ */ Symbol("pino.redactFmt"); - var timeSym = /* @__PURE__ */ Symbol("pino.time"); - var timeSliceIndexSym = /* @__PURE__ */ Symbol("pino.timeSliceIndex"); - var streamSym = /* @__PURE__ */ Symbol("pino.stream"); - var stringifySym = /* @__PURE__ */ Symbol("pino.stringify"); - var stringifySafeSym = /* @__PURE__ */ Symbol("pino.stringifySafe"); - var stringifiersSym = /* @__PURE__ */ Symbol("pino.stringifiers"); - var endSym = /* @__PURE__ */ Symbol("pino.end"); - var formatOptsSym = /* @__PURE__ */ Symbol("pino.formatOpts"); - var messageKeySym = /* @__PURE__ */ Symbol("pino.messageKey"); - var errorKeySym = /* @__PURE__ */ Symbol("pino.errorKey"); - var nestedKeySym = /* @__PURE__ */ Symbol("pino.nestedKey"); - var nestedKeyStrSym = /* @__PURE__ */ Symbol("pino.nestedKeyStr"); - var mixinMergeStrategySym = /* @__PURE__ */ Symbol("pino.mixinMergeStrategy"); - var msgPrefixSym = /* @__PURE__ */ Symbol("pino.msgPrefix"); - var wildcardFirstSym = /* @__PURE__ */ Symbol("pino.wildcardFirst"); - var serializersSym = /* @__PURE__ */ Symbol.for("pino.serializers"); - var formattersSym = /* @__PURE__ */ Symbol.for("pino.formatters"); - var hooksSym = /* @__PURE__ */ Symbol.for("pino.hooks"); - var needsMetadataGsym = /* @__PURE__ */ Symbol.for("pino.metadata"); - module.exports = { - setLevelSym, - getLevelSym, - levelValSym, - levelCompSym, - useLevelLabelsSym, - mixinSym, - lsCacheSym, - chindingsSym, - asJsonSym, - writeSym, - serializersSym, - redactFmtSym, - timeSym, - timeSliceIndexSym, - streamSym, - stringifySym, - stringifySafeSym, - stringifiersSym, - endSym, - formatOptsSym, - messageKeySym, - errorKeySym, - nestedKeySym, - wildcardFirstSym, - needsMetadataGsym, - useOnlyCustomLevelsSym, - formattersSym, - hooksSym, - nestedKeyStrSym, - mixinMergeStrategySym, - msgPrefixSym - }; - } -}); - -// node_modules/.pnpm/pino@9.14.0/node_modules/pino/lib/redaction.js -var require_redaction = __commonJS({ - "node_modules/.pnpm/pino@9.14.0/node_modules/pino/lib/redaction.js"(exports, module) { - "use strict"; - var Redact = require_redact(); - var { redactFmtSym, wildcardFirstSym } = require_symbols(); - var rx = /[^.[\]]+|\[([^[\]]*?)\]/g; - var CENSOR = "[Redacted]"; - var strict = false; - function redaction(opts, serialize) { - const { paths: paths2, censor, remove } = handle(opts); - const shape = paths2.reduce((o5, str) => { - rx.lastIndex = 0; - const first = rx.exec(str); - const next = rx.exec(str); - let ns = first[1] !== void 0 ? first[1].replace(/^(?:"|'|`)(.*)(?:"|'|`)$/, "$1") : first[0]; - if (ns === "*") { - ns = wildcardFirstSym; - } - if (next === null) { - o5[ns] = null; - return o5; - } - if (o5[ns] === null) { - return o5; - } - const { index: index2 } = next; - const nextPath = `${str.substr(index2, str.length - 1)}`; - o5[ns] = o5[ns] || []; - if (ns !== wildcardFirstSym && o5[ns].length === 0) { - o5[ns].push(...o5[wildcardFirstSym] || []); - } - if (ns === wildcardFirstSym) { - Object.keys(o5).forEach(function(k5) { - if (o5[k5]) { - o5[k5].push(nextPath); - } - }); - } - o5[ns].push(nextPath); - return o5; - }, {}); - const result = { - [redactFmtSym]: Redact({ paths: paths2, censor, serialize, strict, remove }) - }; - const topCensor = (...args) => { - return typeof censor === "function" ? serialize(censor(...args)) : serialize(censor); - }; - return [...Object.keys(shape), ...Object.getOwnPropertySymbols(shape)].reduce((o5, k5) => { - if (shape[k5] === null) { - o5[k5] = (value) => topCensor(value, [k5]); - } else { - const wrappedCensor = typeof censor === "function" ? (value, path53) => { - return censor(value, [k5, ...path53]); - } : censor; - o5[k5] = Redact({ - paths: shape[k5], - censor: wrappedCensor, - serialize, - strict, - remove - }); - } - return o5; - }, result); - } - function handle(opts) { - if (Array.isArray(opts)) { - opts = { paths: opts, censor: CENSOR }; - return opts; - } - let { paths: paths2, censor = CENSOR, remove } = opts; - if (Array.isArray(paths2) === false) { - throw Error("pino \u2013 redact must contain an array of strings"); - } - if (remove === true) censor = void 0; - return { paths: paths2, censor, remove }; - } - module.exports = redaction; - } -}); - -// node_modules/.pnpm/pino@9.14.0/node_modules/pino/lib/time.js -var require_time = __commonJS({ - "node_modules/.pnpm/pino@9.14.0/node_modules/pino/lib/time.js"(exports, module) { - "use strict"; - var nullTime = () => ""; - var epochTime = () => `,"time":${Date.now()}`; - var unixTime = () => `,"time":${Math.round(Date.now() / 1e3)}`; - var isoTime = () => `,"time":"${new Date(Date.now()).toISOString()}"`; - var NS_PER_MS = 1000000n; - var NS_PER_SEC = 1000000000n; - var startWallTimeNs = BigInt(Date.now()) * NS_PER_MS; - var startHrTime = process.hrtime.bigint(); - var isoTimeNano = () => { - const elapsedNs = process.hrtime.bigint() - startHrTime; - const currentTimeNs = startWallTimeNs + elapsedNs; - const secondsSinceEpoch = currentTimeNs / NS_PER_SEC; - const nanosWithinSecond = currentTimeNs % NS_PER_SEC; - const msSinceEpoch = Number(secondsSinceEpoch * 1000n + nanosWithinSecond / 1000000n); - const date7 = new Date(msSinceEpoch); - const year3 = date7.getUTCFullYear(); - const month = (date7.getUTCMonth() + 1).toString().padStart(2, "0"); - const day2 = date7.getUTCDate().toString().padStart(2, "0"); - const hours = date7.getUTCHours().toString().padStart(2, "0"); - const minutes = date7.getUTCMinutes().toString().padStart(2, "0"); - const seconds = date7.getUTCSeconds().toString().padStart(2, "0"); - return `,"time":"${year3}-${month}-${day2}T${hours}:${minutes}:${seconds}.${nanosWithinSecond.toString().padStart(9, "0")}Z"`; - }; - module.exports = { nullTime, epochTime, unixTime, isoTime, isoTimeNano }; - } -}); - -// node_modules/.pnpm/quick-format-unescaped@4.0.4/node_modules/quick-format-unescaped/index.js -var require_quick_format_unescaped = __commonJS({ - "node_modules/.pnpm/quick-format-unescaped@4.0.4/node_modules/quick-format-unescaped/index.js"(exports, module) { - "use strict"; - function tryStringify(o5) { - try { - return JSON.stringify(o5); - } catch (e5) { - return '"[Circular]"'; - } - } - module.exports = format2; - function format2(f5, args, opts) { - var ss = opts && opts.stringify || tryStringify; - var offset = 1; - if (typeof f5 === "object" && f5 !== null) { - var len = args.length + offset; - if (len === 1) return f5; - var objects = new Array(len); - objects[0] = ss(f5); - for (var index2 = 1; index2 < len; index2++) { - objects[index2] = ss(args[index2]); - } - return objects.join(" "); - } - if (typeof f5 !== "string") { - return f5; - } - var argLen = args.length; - if (argLen === 0) return f5; - var str = ""; - var a5 = 1 - offset; - var lastPos = -1; - var flen = f5 && f5.length || 0; - for (var i5 = 0; i5 < flen; ) { - if (f5.charCodeAt(i5) === 37 && i5 + 1 < flen) { - lastPos = lastPos > -1 ? lastPos : 0; - switch (f5.charCodeAt(i5 + 1)) { - case 100: - // 'd' - case 102: - if (a5 >= argLen) - break; - if (args[a5] == null) break; - if (lastPos < i5) - str += f5.slice(lastPos, i5); - str += Number(args[a5]); - lastPos = i5 + 2; - i5++; - break; - case 105: - if (a5 >= argLen) - break; - if (args[a5] == null) break; - if (lastPos < i5) - str += f5.slice(lastPos, i5); - str += Math.floor(Number(args[a5])); - lastPos = i5 + 2; - i5++; - break; - case 79: - // 'O' - case 111: - // 'o' - case 106: - if (a5 >= argLen) - break; - if (args[a5] === void 0) break; - if (lastPos < i5) - str += f5.slice(lastPos, i5); - var type = typeof args[a5]; - if (type === "string") { - str += "'" + args[a5] + "'"; - lastPos = i5 + 2; - i5++; - break; - } - if (type === "function") { - str += args[a5].name || ""; - lastPos = i5 + 2; - i5++; - break; - } - str += ss(args[a5]); - lastPos = i5 + 2; - i5++; - break; - case 115: - if (a5 >= argLen) - break; - if (lastPos < i5) - str += f5.slice(lastPos, i5); - str += String(args[a5]); - lastPos = i5 + 2; - i5++; - break; - case 37: - if (lastPos < i5) - str += f5.slice(lastPos, i5); - str += "%"; - lastPos = i5 + 2; - i5++; - a5--; - break; - } - ++a5; - } - ++i5; - } - if (lastPos === -1) - return f5; - else if (lastPos < flen) { - str += f5.slice(lastPos); - } - return str; - } - } -}); - -// node_modules/.pnpm/atomic-sleep@1.0.0/node_modules/atomic-sleep/index.js -var require_atomic_sleep = __commonJS({ - "node_modules/.pnpm/atomic-sleep@1.0.0/node_modules/atomic-sleep/index.js"(exports, module) { - "use strict"; - if (typeof SharedArrayBuffer !== "undefined" && typeof Atomics !== "undefined") { - let sleep = function(ms) { - const valid = ms > 0 && ms < Infinity; - if (valid === false) { - if (typeof ms !== "number" && typeof ms !== "bigint") { - throw TypeError("sleep: ms must be a number"); - } - throw RangeError("sleep: ms must be a number that is greater than 0 but less than Infinity"); - } - Atomics.wait(nil, 0, 0, Number(ms)); - }; - const nil = new Int32Array(new SharedArrayBuffer(4)); - module.exports = sleep; - } else { - let sleep = function(ms) { - const valid = ms > 0 && ms < Infinity; - if (valid === false) { - if (typeof ms !== "number" && typeof ms !== "bigint") { - throw TypeError("sleep: ms must be a number"); - } - throw RangeError("sleep: ms must be a number that is greater than 0 but less than Infinity"); - } - const target = Date.now() + Number(ms); - while (target > Date.now()) { - } - }; - module.exports = sleep; - } - } -}); - -// node_modules/.pnpm/sonic-boom@4.2.1/node_modules/sonic-boom/index.js -var require_sonic_boom = __commonJS({ - "node_modules/.pnpm/sonic-boom@4.2.1/node_modules/sonic-boom/index.js"(exports, module) { - "use strict"; - var fs41 = __require("fs"); - var EventEmitter5 = __require("events"); - var inherits = __require("util").inherits; - var path53 = __require("path"); - var sleep = require_atomic_sleep(); - var assert2 = __require("assert"); - var BUSY_WRITE_TIMEOUT = 100; - var kEmptyBuffer = Buffer.allocUnsafe(0); - var MAX_WRITE = 16 * 1024; - var kContentModeBuffer = "buffer"; - var kContentModeUtf8 = "utf8"; - var [major, minor] = (process.versions.node || "0.0").split(".").map(Number); - var kCopyBuffer = major >= 22 && minor >= 7; - function openFile(file2, sonic) { - sonic._opening = true; - sonic._writing = true; - sonic._asyncDrainScheduled = false; - function fileOpened(err, fd) { - if (err) { - sonic._reopening = false; - sonic._writing = false; - sonic._opening = false; - if (sonic.sync) { - process.nextTick(() => { - if (sonic.listenerCount("error") > 0) { - sonic.emit("error", err); - } - }); - } else { - sonic.emit("error", err); - } - return; - } - const reopening = sonic._reopening; - sonic.fd = fd; - sonic.file = file2; - sonic._reopening = false; - sonic._opening = false; - sonic._writing = false; - if (sonic.sync) { - process.nextTick(() => sonic.emit("ready")); - } else { - sonic.emit("ready"); - } - if (sonic.destroyed) { - return; - } - if (!sonic._writing && sonic._len > sonic.minLength || sonic._flushPending) { - sonic._actualWrite(); - } else if (reopening) { - process.nextTick(() => sonic.emit("drain")); - } - } - const flags = sonic.append ? "a" : "w"; - const mode = sonic.mode; - if (sonic.sync) { - try { - if (sonic.mkdir) fs41.mkdirSync(path53.dirname(file2), { recursive: true }); - const fd = fs41.openSync(file2, flags, mode); - fileOpened(null, fd); - } catch (err) { - fileOpened(err); - throw err; - } - } else if (sonic.mkdir) { - fs41.mkdir(path53.dirname(file2), { recursive: true }, (err) => { - if (err) return fileOpened(err); - fs41.open(file2, flags, mode, fileOpened); - }); - } else { - fs41.open(file2, flags, mode, fileOpened); - } - } - function SonicBoom(opts) { - if (!(this instanceof SonicBoom)) { - return new SonicBoom(opts); - } - let { fd, dest, minLength, maxLength, maxWrite, periodicFlush, sync, append = true, mkdir, retryEAGAIN, fsync, contentMode, mode } = opts || {}; - fd = fd || dest; - this._len = 0; - this.fd = -1; - this._bufs = []; - this._lens = []; - this._writing = false; - this._ending = false; - this._reopening = false; - this._asyncDrainScheduled = false; - this._flushPending = false; - this._hwm = Math.max(minLength || 0, 16387); - this.file = null; - this.destroyed = false; - this.minLength = minLength || 0; - this.maxLength = maxLength || 0; - this.maxWrite = maxWrite || MAX_WRITE; - this._periodicFlush = periodicFlush || 0; - this._periodicFlushTimer = void 0; - this.sync = sync || false; - this.writable = true; - this._fsync = fsync || false; - this.append = append || false; - this.mode = mode; - this.retryEAGAIN = retryEAGAIN || (() => true); - this.mkdir = mkdir || false; - let fsWriteSync; - let fsWrite; - if (contentMode === kContentModeBuffer) { - this._writingBuf = kEmptyBuffer; - this.write = writeBuffer; - this.flush = flushBuffer; - this.flushSync = flushBufferSync; - this._actualWrite = actualWriteBuffer; - fsWriteSync = () => fs41.writeSync(this.fd, this._writingBuf); - fsWrite = () => fs41.write(this.fd, this._writingBuf, this.release); - } else if (contentMode === void 0 || contentMode === kContentModeUtf8) { - this._writingBuf = ""; - this.write = write; - this.flush = flush; - this.flushSync = flushSync; - this._actualWrite = actualWrite; - fsWriteSync = () => { - if (Buffer.isBuffer(this._writingBuf)) { - return fs41.writeSync(this.fd, this._writingBuf); - } - return fs41.writeSync(this.fd, this._writingBuf, "utf8"); - }; - fsWrite = () => { - if (Buffer.isBuffer(this._writingBuf)) { - return fs41.write(this.fd, this._writingBuf, this.release); - } - return fs41.write(this.fd, this._writingBuf, "utf8", this.release); - }; - } else { - throw new Error(`SonicBoom supports "${kContentModeUtf8}" and "${kContentModeBuffer}", but passed ${contentMode}`); - } - if (typeof fd === "number") { - this.fd = fd; - process.nextTick(() => this.emit("ready")); - } else if (typeof fd === "string") { - openFile(fd, this); - } else { - throw new Error("SonicBoom supports only file descriptors and files"); - } - if (this.minLength >= this.maxWrite) { - throw new Error(`minLength should be smaller than maxWrite (${this.maxWrite})`); - } - this.release = (err, n5) => { - if (err) { - if ((err.code === "EAGAIN" || err.code === "EBUSY") && this.retryEAGAIN(err, this._writingBuf.length, this._len - this._writingBuf.length)) { - if (this.sync) { - try { - sleep(BUSY_WRITE_TIMEOUT); - this.release(void 0, 0); - } catch (err2) { - this.release(err2); - } - } else { - setTimeout(fsWrite, BUSY_WRITE_TIMEOUT); - } - } else { - this._writing = false; - this.emit("error", err); - } - return; - } - this.emit("write", n5); - const releasedBufObj = releaseWritingBuf(this._writingBuf, this._len, n5); - this._len = releasedBufObj.len; - this._writingBuf = releasedBufObj.writingBuf; - if (this._writingBuf.length) { - if (!this.sync) { - fsWrite(); - return; - } - try { - do { - const n6 = fsWriteSync(); - const releasedBufObj2 = releaseWritingBuf(this._writingBuf, this._len, n6); - this._len = releasedBufObj2.len; - this._writingBuf = releasedBufObj2.writingBuf; - } while (this._writingBuf.length); - } catch (err2) { - this.release(err2); - return; - } - } - if (this._fsync) { - fs41.fsyncSync(this.fd); - } - const len = this._len; - if (this._reopening) { - this._writing = false; - this._reopening = false; - this.reopen(); - } else if (len > this.minLength) { - this._actualWrite(); - } else if (this._ending) { - if (len > 0) { - this._actualWrite(); - } else { - this._writing = false; - actualClose(this); - } - } else { - this._writing = false; - if (this.sync) { - if (!this._asyncDrainScheduled) { - this._asyncDrainScheduled = true; - process.nextTick(emitDrain, this); - } - } else { - this.emit("drain"); - } - } - }; - this.on("newListener", function(name) { - if (name === "drain") { - this._asyncDrainScheduled = false; - } - }); - if (this._periodicFlush !== 0) { - this._periodicFlushTimer = setInterval(() => this.flush(null), this._periodicFlush); - this._periodicFlushTimer.unref(); - } - } - function releaseWritingBuf(writingBuf, len, n5) { - if (typeof writingBuf === "string") { - writingBuf = Buffer.from(writingBuf); - } - len = Math.max(len - n5, 0); - writingBuf = writingBuf.subarray(n5); - return { writingBuf, len }; - } - function emitDrain(sonic) { - const hasListeners = sonic.listenerCount("drain") > 0; - if (!hasListeners) return; - sonic._asyncDrainScheduled = false; - sonic.emit("drain"); - } - inherits(SonicBoom, EventEmitter5); - function mergeBuf(bufs, len) { - if (bufs.length === 0) { - return kEmptyBuffer; - } - if (bufs.length === 1) { - return bufs[0]; - } - return Buffer.concat(bufs, len); - } - function write(data2) { - if (this.destroyed) { - throw new Error("SonicBoom destroyed"); - } - data2 = "" + data2; - const dataLen = Buffer.byteLength(data2); - const len = this._len + dataLen; - const bufs = this._bufs; - if (this.maxLength && len > this.maxLength) { - this.emit("drop", data2); - return this._len < this._hwm; - } - if (bufs.length === 0 || Buffer.byteLength(bufs[bufs.length - 1]) + dataLen > this.maxWrite) { - bufs.push(data2); - } else { - bufs[bufs.length - 1] += data2; - } - this._len = len; - if (!this._writing && this._len >= this.minLength) { - this._actualWrite(); - } - return this._len < this._hwm; - } - function writeBuffer(data2) { - if (this.destroyed) { - throw new Error("SonicBoom destroyed"); - } - const len = this._len + data2.length; - const bufs = this._bufs; - const lens = this._lens; - if (this.maxLength && len > this.maxLength) { - this.emit("drop", data2); - return this._len < this._hwm; - } - if (bufs.length === 0 || lens[lens.length - 1] + data2.length > this.maxWrite) { - bufs.push([data2]); - lens.push(data2.length); - } else { - bufs[bufs.length - 1].push(data2); - lens[lens.length - 1] += data2.length; - } - this._len = len; - if (!this._writing && this._len >= this.minLength) { - this._actualWrite(); - } - return this._len < this._hwm; - } - function callFlushCallbackOnDrain(cb) { - this._flushPending = true; - const onDrain = () => { - if (!this._fsync) { - try { - fs41.fsync(this.fd, (err) => { - this._flushPending = false; - cb(err); - }); - } catch (err) { - cb(err); - } - } else { - this._flushPending = false; - cb(); - } - this.off("error", onError); - }; - const onError = (err) => { - this._flushPending = false; - cb(err); - this.off("drain", onDrain); - }; - this.once("drain", onDrain); - this.once("error", onError); - } - function flush(cb) { - if (cb != null && typeof cb !== "function") { - throw new Error("flush cb must be a function"); - } - if (this.destroyed) { - const error50 = new Error("SonicBoom destroyed"); - if (cb) { - cb(error50); - return; - } - throw error50; - } - if (this.minLength <= 0) { - cb?.(); - return; - } - if (cb) { - callFlushCallbackOnDrain.call(this, cb); - } - if (this._writing) { - return; - } - if (this._bufs.length === 0) { - this._bufs.push(""); - } - this._actualWrite(); - } - function flushBuffer(cb) { - if (cb != null && typeof cb !== "function") { - throw new Error("flush cb must be a function"); - } - if (this.destroyed) { - const error50 = new Error("SonicBoom destroyed"); - if (cb) { - cb(error50); - return; - } - throw error50; - } - if (this.minLength <= 0) { - cb?.(); - return; - } - if (cb) { - callFlushCallbackOnDrain.call(this, cb); - } - if (this._writing) { - return; - } - if (this._bufs.length === 0) { - this._bufs.push([]); - this._lens.push(0); - } - this._actualWrite(); - } - SonicBoom.prototype.reopen = function(file2) { - if (this.destroyed) { - throw new Error("SonicBoom destroyed"); - } - if (this._opening) { - this.once("ready", () => { - this.reopen(file2); - }); - return; - } - if (this._ending) { - return; - } - if (!this.file) { - throw new Error("Unable to reopen a file descriptor, you must pass a file to SonicBoom"); - } - if (file2) { - this.file = file2; - } - this._reopening = true; - if (this._writing) { - return; - } - const fd = this.fd; - this.once("ready", () => { - if (fd !== this.fd) { - fs41.close(fd, (err) => { - if (err) { - return this.emit("error", err); - } - }); - } - }); - openFile(this.file, this); - }; - SonicBoom.prototype.end = function() { - if (this.destroyed) { - throw new Error("SonicBoom destroyed"); - } - if (this._opening) { - this.once("ready", () => { - this.end(); - }); - return; - } - if (this._ending) { - return; - } - this._ending = true; - if (this._writing) { - return; - } - if (this._len > 0 && this.fd >= 0) { - this._actualWrite(); - } else { - actualClose(this); - } - }; - function flushSync() { - if (this.destroyed) { - throw new Error("SonicBoom destroyed"); - } - if (this.fd < 0) { - throw new Error("sonic boom is not ready yet"); - } - if (!this._writing && this._writingBuf.length > 0) { - this._bufs.unshift(this._writingBuf); - this._writingBuf = ""; - } - let buf = ""; - while (this._bufs.length || buf.length) { - if (buf.length <= 0) { - buf = this._bufs[0]; - } - try { - const n5 = Buffer.isBuffer(buf) ? fs41.writeSync(this.fd, buf) : fs41.writeSync(this.fd, buf, "utf8"); - const releasedBufObj = releaseWritingBuf(buf, this._len, n5); - buf = releasedBufObj.writingBuf; - this._len = releasedBufObj.len; - if (buf.length <= 0) { - this._bufs.shift(); - } - } catch (err) { - const shouldRetry = err.code === "EAGAIN" || err.code === "EBUSY"; - if (shouldRetry && !this.retryEAGAIN(err, buf.length, this._len - buf.length)) { - throw err; - } - sleep(BUSY_WRITE_TIMEOUT); - } - } - try { - fs41.fsyncSync(this.fd); - } catch { - } - } - function flushBufferSync() { - if (this.destroyed) { - throw new Error("SonicBoom destroyed"); - } - if (this.fd < 0) { - throw new Error("sonic boom is not ready yet"); - } - if (!this._writing && this._writingBuf.length > 0) { - this._bufs.unshift([this._writingBuf]); - this._writingBuf = kEmptyBuffer; - } - let buf = kEmptyBuffer; - while (this._bufs.length || buf.length) { - if (buf.length <= 0) { - buf = mergeBuf(this._bufs[0], this._lens[0]); - } - try { - const n5 = fs41.writeSync(this.fd, buf); - buf = buf.subarray(n5); - this._len = Math.max(this._len - n5, 0); - if (buf.length <= 0) { - this._bufs.shift(); - this._lens.shift(); - } - } catch (err) { - const shouldRetry = err.code === "EAGAIN" || err.code === "EBUSY"; - if (shouldRetry && !this.retryEAGAIN(err, buf.length, this._len - buf.length)) { - throw err; - } - sleep(BUSY_WRITE_TIMEOUT); - } - } - } - SonicBoom.prototype.destroy = function() { - if (this.destroyed) { - return; - } - actualClose(this); - }; - function actualWrite() { - const release = this.release; - this._writing = true; - this._writingBuf = this._writingBuf.length ? this._writingBuf : this._bufs.shift() || ""; - if (this.sync) { - try { - const written = Buffer.isBuffer(this._writingBuf) ? fs41.writeSync(this.fd, this._writingBuf) : fs41.writeSync(this.fd, this._writingBuf, "utf8"); - release(null, written); - } catch (err) { - release(err); - } - } else { - fs41.write(this.fd, this._writingBuf, release); - } - } - function actualWriteBuffer() { - const release = this.release; - this._writing = true; - this._writingBuf = this._writingBuf.length ? this._writingBuf : mergeBuf(this._bufs.shift(), this._lens.shift()); - if (this.sync) { - try { - const written = fs41.writeSync(this.fd, this._writingBuf); - release(null, written); - } catch (err) { - release(err); - } - } else { - if (kCopyBuffer) { - this._writingBuf = Buffer.from(this._writingBuf); - } - fs41.write(this.fd, this._writingBuf, release); - } - } - function actualClose(sonic) { - if (sonic.fd === -1) { - sonic.once("ready", actualClose.bind(null, sonic)); - return; - } - if (sonic._periodicFlushTimer !== void 0) { - clearInterval(sonic._periodicFlushTimer); - } - sonic.destroyed = true; - sonic._bufs = []; - sonic._lens = []; - assert2(typeof sonic.fd === "number", `sonic.fd must be a number, got ${typeof sonic.fd}`); - try { - fs41.fsync(sonic.fd, closeWrapped); - } catch { - } - function closeWrapped() { - if (sonic.fd !== 1 && sonic.fd !== 2) { - fs41.close(sonic.fd, done); - } else { - done(); - } - } - function done(err) { - if (err) { - sonic.emit("error", err); - return; - } - if (sonic._ending && !sonic._writing) { - sonic.emit("finish"); - } - sonic.emit("close"); - } - } - SonicBoom.SonicBoom = SonicBoom; - SonicBoom.default = SonicBoom; - module.exports = SonicBoom; - } -}); - -// node_modules/.pnpm/on-exit-leak-free@2.1.2/node_modules/on-exit-leak-free/index.js -var require_on_exit_leak_free = __commonJS({ - "node_modules/.pnpm/on-exit-leak-free@2.1.2/node_modules/on-exit-leak-free/index.js"(exports, module) { - "use strict"; - var refs = { - exit: [], - beforeExit: [] - }; - var functions = { - exit: onExit, - beforeExit: onBeforeExit - }; - var registry2; - function ensureRegistry() { - if (registry2 === void 0) { - registry2 = new FinalizationRegistry(clear); - } - } - function install(event) { - if (refs[event].length > 0) { - return; - } - process.on(event, functions[event]); - } - function uninstall(event) { - if (refs[event].length > 0) { - return; - } - process.removeListener(event, functions[event]); - if (refs.exit.length === 0 && refs.beforeExit.length === 0) { - registry2 = void 0; - } - } - function onExit() { - callRefs("exit"); - } - function onBeforeExit() { - callRefs("beforeExit"); - } - function callRefs(event) { - for (const ref of refs[event]) { - const obj = ref.deref(); - const fn = ref.fn; - if (obj !== void 0) { - fn(obj, event); - } - } - refs[event] = []; - } - function clear(ref) { - for (const event of ["exit", "beforeExit"]) { - const index2 = refs[event].indexOf(ref); - refs[event].splice(index2, index2 + 1); - uninstall(event); - } - } - function _register(event, obj, fn) { - if (obj === void 0) { - throw new Error("the object can't be undefined"); - } - install(event); - const ref = new WeakRef(obj); - ref.fn = fn; - ensureRegistry(); - registry2.register(obj, ref); - refs[event].push(ref); - } - function register(obj, fn) { - _register("exit", obj, fn); - } - function registerBeforeExit(obj, fn) { - _register("beforeExit", obj, fn); - } - function unregister(obj) { - if (registry2 === void 0) { - return; - } - registry2.unregister(obj); - for (const event of ["exit", "beforeExit"]) { - refs[event] = refs[event].filter((ref) => { - const _obj = ref.deref(); - return _obj && _obj !== obj; - }); - uninstall(event); - } - } - module.exports = { - register, - registerBeforeExit, - unregister - }; - } -}); - -// node_modules/.pnpm/thread-stream@3.1.0/node_modules/thread-stream/package.json -var require_package = __commonJS({ - "node_modules/.pnpm/thread-stream@3.1.0/node_modules/thread-stream/package.json"(exports, module) { - module.exports = { - name: "thread-stream", - version: "3.1.0", - description: "A streaming way to send data to a Node.js Worker Thread", - main: "index.js", - types: "index.d.ts", - dependencies: { - "real-require": "^0.2.0" - }, - devDependencies: { - "@types/node": "^20.1.0", - "@types/tap": "^15.0.0", - "@yao-pkg/pkg": "^5.11.5", - desm: "^1.3.0", - fastbench: "^1.0.1", - husky: "^9.0.6", - "pino-elasticsearch": "^8.0.0", - "sonic-boom": "^4.0.1", - standard: "^17.0.0", - tap: "^16.2.0", - "ts-node": "^10.8.0", - typescript: "^5.3.2", - "why-is-node-running": "^2.2.2" - }, - scripts: { - build: "tsc --noEmit", - test: 'standard && npm run build && npm run transpile && tap "test/**/*.test.*js" && tap --ts test/*.test.*ts', - "test:ci": "standard && npm run transpile && npm run test:ci:js && npm run test:ci:ts", - "test:ci:js": 'tap --no-check-coverage --timeout=120 --coverage-report=lcovonly "test/**/*.test.*js"', - "test:ci:ts": 'tap --ts --no-check-coverage --coverage-report=lcovonly "test/**/*.test.*ts"', - "test:yarn": 'npm run transpile && tap "test/**/*.test.js" --no-check-coverage', - transpile: "sh ./test/ts/transpile.sh", - prepare: "husky install" - }, - standard: { - ignore: [ - "test/ts/**/*", - "test/syntax-error.mjs" - ] - }, - repository: { - type: "git", - url: "git+https://github.com/mcollina/thread-stream.git" - }, - keywords: [ - "worker", - "thread", - "threads", - "stream" - ], - author: "Matteo Collina ", - license: "MIT", - bugs: { - url: "https://github.com/mcollina/thread-stream/issues" - }, - homepage: "https://github.com/mcollina/thread-stream#readme" - }; - } -}); - -// node_modules/.pnpm/thread-stream@3.1.0/node_modules/thread-stream/lib/wait.js -var require_wait = __commonJS({ - "node_modules/.pnpm/thread-stream@3.1.0/node_modules/thread-stream/lib/wait.js"(exports, module) { - "use strict"; - var MAX_TIMEOUT = 1e3; - function wait(state2, index2, expected, timeout, done) { - const max = Date.now() + timeout; - let current = Atomics.load(state2, index2); - if (current === expected) { - done(null, "ok"); - return; - } - let prior = current; - const check3 = (backoff2) => { - if (Date.now() > max) { - done(null, "timed-out"); - } else { - setTimeout(() => { - prior = current; - current = Atomics.load(state2, index2); - if (current === prior) { - check3(backoff2 >= MAX_TIMEOUT ? MAX_TIMEOUT : backoff2 * 2); - } else { - if (current === expected) done(null, "ok"); - else done(null, "not-equal"); - } - }, backoff2); - } - }; - check3(1); - } - function waitDiff(state2, index2, expected, timeout, done) { - const max = Date.now() + timeout; - let current = Atomics.load(state2, index2); - if (current !== expected) { - done(null, "ok"); - return; - } - const check3 = (backoff2) => { - if (Date.now() > max) { - done(null, "timed-out"); - } else { - setTimeout(() => { - current = Atomics.load(state2, index2); - if (current !== expected) { - done(null, "ok"); - } else { - check3(backoff2 >= MAX_TIMEOUT ? MAX_TIMEOUT : backoff2 * 2); - } - }, backoff2); - } - }; - check3(1); - } - module.exports = { wait, waitDiff }; - } -}); - -// node_modules/.pnpm/thread-stream@3.1.0/node_modules/thread-stream/lib/indexes.js -var require_indexes = __commonJS({ - "node_modules/.pnpm/thread-stream@3.1.0/node_modules/thread-stream/lib/indexes.js"(exports, module) { - "use strict"; - var WRITE_INDEX = 4; - var READ_INDEX = 8; - module.exports = { - WRITE_INDEX, - READ_INDEX - }; - } -}); - -// node_modules/.pnpm/thread-stream@3.1.0/node_modules/thread-stream/index.js -var require_thread_stream = __commonJS({ - "node_modules/.pnpm/thread-stream@3.1.0/node_modules/thread-stream/index.js"(exports, module) { - "use strict"; - var { version: version3 } = require_package(); - var { EventEmitter: EventEmitter5 } = __require("events"); - var { Worker } = __require("worker_threads"); - var { join: join4 } = __require("path"); - var { pathToFileURL } = __require("url"); - var { wait } = require_wait(); - var { - WRITE_INDEX, - READ_INDEX - } = require_indexes(); - var buffer2 = __require("buffer"); - var assert2 = __require("assert"); - var kImpl = /* @__PURE__ */ Symbol("kImpl"); - var MAX_STRING = buffer2.constants.MAX_STRING_LENGTH; - var FakeWeakRef = class { - constructor(value) { - this._value = value; - } - deref() { - return this._value; - } - }; - var FakeFinalizationRegistry = class { - register() { - } - unregister() { - } - }; - var FinalizationRegistry2 = process.env.NODE_V8_COVERAGE ? FakeFinalizationRegistry : global.FinalizationRegistry || FakeFinalizationRegistry; - var WeakRef2 = process.env.NODE_V8_COVERAGE ? FakeWeakRef : global.WeakRef || FakeWeakRef; - var registry2 = new FinalizationRegistry2((worker) => { - if (worker.exited) { - return; - } - worker.terminate(); - }); - function createWorker(stream, opts) { - const { filename, workerData } = opts; - const bundlerOverrides = "__bundlerPathsOverrides" in globalThis ? globalThis.__bundlerPathsOverrides : {}; - const toExecute = bundlerOverrides["thread-stream-worker"] || join4(__dirname, "lib", "worker.js"); - const worker = new Worker(toExecute, { - ...opts.workerOpts, - trackUnmanagedFds: false, - workerData: { - filename: filename.indexOf("file://") === 0 ? filename : pathToFileURL(filename).href, - dataBuf: stream[kImpl].dataBuf, - stateBuf: stream[kImpl].stateBuf, - workerData: { - $context: { - threadStreamVersion: version3 - }, - ...workerData - } - } - }); - worker.stream = new FakeWeakRef(stream); - worker.on("message", onWorkerMessage); - worker.on("exit", onWorkerExit); - registry2.register(stream, worker); - return worker; - } - function drain(stream) { - assert2(!stream[kImpl].sync); - if (stream[kImpl].needDrain) { - stream[kImpl].needDrain = false; - stream.emit("drain"); - } - } - function nextFlush(stream) { - const writeIndex = Atomics.load(stream[kImpl].state, WRITE_INDEX); - let leftover = stream[kImpl].data.length - writeIndex; - if (leftover > 0) { - if (stream[kImpl].buf.length === 0) { - stream[kImpl].flushing = false; - if (stream[kImpl].ending) { - end(stream); - } else if (stream[kImpl].needDrain) { - process.nextTick(drain, stream); - } - return; - } - let toWrite = stream[kImpl].buf.slice(0, leftover); - let toWriteBytes = Buffer.byteLength(toWrite); - if (toWriteBytes <= leftover) { - stream[kImpl].buf = stream[kImpl].buf.slice(leftover); - write(stream, toWrite, nextFlush.bind(null, stream)); - } else { - stream.flush(() => { - if (stream.destroyed) { - return; - } - Atomics.store(stream[kImpl].state, READ_INDEX, 0); - Atomics.store(stream[kImpl].state, WRITE_INDEX, 0); - while (toWriteBytes > stream[kImpl].data.length) { - leftover = leftover / 2; - toWrite = stream[kImpl].buf.slice(0, leftover); - toWriteBytes = Buffer.byteLength(toWrite); - } - stream[kImpl].buf = stream[kImpl].buf.slice(leftover); - write(stream, toWrite, nextFlush.bind(null, stream)); - }); - } - } else if (leftover === 0) { - if (writeIndex === 0 && stream[kImpl].buf.length === 0) { - return; - } - stream.flush(() => { - Atomics.store(stream[kImpl].state, READ_INDEX, 0); - Atomics.store(stream[kImpl].state, WRITE_INDEX, 0); - nextFlush(stream); - }); - } else { - destroy(stream, new Error("overwritten")); - } - } - function onWorkerMessage(msg) { - const stream = this.stream.deref(); - if (stream === void 0) { - this.exited = true; - this.terminate(); - return; - } - switch (msg.code) { - case "READY": - this.stream = new WeakRef2(stream); - stream.flush(() => { - stream[kImpl].ready = true; - stream.emit("ready"); - }); - break; - case "ERROR": - destroy(stream, msg.err); - break; - case "EVENT": - if (Array.isArray(msg.args)) { - stream.emit(msg.name, ...msg.args); - } else { - stream.emit(msg.name, msg.args); - } - break; - case "WARNING": - process.emitWarning(msg.err); - break; - default: - destroy(stream, new Error("this should not happen: " + msg.code)); - } - } - function onWorkerExit(code) { - const stream = this.stream.deref(); - if (stream === void 0) { - return; - } - registry2.unregister(stream); - stream.worker.exited = true; - stream.worker.off("exit", onWorkerExit); - destroy(stream, code !== 0 ? new Error("the worker thread exited") : null); - } - var ThreadStream = class extends EventEmitter5 { - constructor(opts = {}) { - super(); - if (opts.bufferSize < 4) { - throw new Error("bufferSize must at least fit a 4-byte utf-8 char"); - } - this[kImpl] = {}; - this[kImpl].stateBuf = new SharedArrayBuffer(128); - this[kImpl].state = new Int32Array(this[kImpl].stateBuf); - this[kImpl].dataBuf = new SharedArrayBuffer(opts.bufferSize || 4 * 1024 * 1024); - this[kImpl].data = Buffer.from(this[kImpl].dataBuf); - this[kImpl].sync = opts.sync || false; - this[kImpl].ending = false; - this[kImpl].ended = false; - this[kImpl].needDrain = false; - this[kImpl].destroyed = false; - this[kImpl].flushing = false; - this[kImpl].ready = false; - this[kImpl].finished = false; - this[kImpl].errored = null; - this[kImpl].closed = false; - this[kImpl].buf = ""; - this.worker = createWorker(this, opts); - this.on("message", (message2, transferList) => { - this.worker.postMessage(message2, transferList); - }); - } - write(data2) { - if (this[kImpl].destroyed) { - error50(this, new Error("the worker has exited")); - return false; - } - if (this[kImpl].ending) { - error50(this, new Error("the worker is ending")); - return false; - } - if (this[kImpl].flushing && this[kImpl].buf.length + data2.length >= MAX_STRING) { - try { - writeSync(this); - this[kImpl].flushing = true; - } catch (err) { - destroy(this, err); - return false; - } - } - this[kImpl].buf += data2; - if (this[kImpl].sync) { - try { - writeSync(this); - return true; - } catch (err) { - destroy(this, err); - return false; - } - } - if (!this[kImpl].flushing) { - this[kImpl].flushing = true; - setImmediate(nextFlush, this); - } - this[kImpl].needDrain = this[kImpl].data.length - this[kImpl].buf.length - Atomics.load(this[kImpl].state, WRITE_INDEX) <= 0; - return !this[kImpl].needDrain; - } - end() { - if (this[kImpl].destroyed) { - return; - } - this[kImpl].ending = true; - end(this); - } - flush(cb) { - if (this[kImpl].destroyed) { - if (typeof cb === "function") { - process.nextTick(cb, new Error("the worker has exited")); - } - return; - } - const writeIndex = Atomics.load(this[kImpl].state, WRITE_INDEX); - wait(this[kImpl].state, READ_INDEX, writeIndex, Infinity, (err, res) => { - if (err) { - destroy(this, err); - process.nextTick(cb, err); - return; - } - if (res === "not-equal") { - this.flush(cb); - return; - } - process.nextTick(cb); - }); - } - flushSync() { - if (this[kImpl].destroyed) { - return; - } - writeSync(this); - flushSync(this); - } - unref() { - this.worker.unref(); - } - ref() { - this.worker.ref(); - } - get ready() { - return this[kImpl].ready; - } - get destroyed() { - return this[kImpl].destroyed; - } - get closed() { - return this[kImpl].closed; - } - get writable() { - return !this[kImpl].destroyed && !this[kImpl].ending; - } - get writableEnded() { - return this[kImpl].ending; - } - get writableFinished() { - return this[kImpl].finished; - } - get writableNeedDrain() { - return this[kImpl].needDrain; - } - get writableObjectMode() { - return false; - } - get writableErrored() { - return this[kImpl].errored; - } - }; - function error50(stream, err) { - setImmediate(() => { - stream.emit("error", err); - }); - } - function destroy(stream, err) { - if (stream[kImpl].destroyed) { - return; - } - stream[kImpl].destroyed = true; - if (err) { - stream[kImpl].errored = err; - error50(stream, err); - } - if (!stream.worker.exited) { - stream.worker.terminate().catch(() => { - }).then(() => { - stream[kImpl].closed = true; - stream.emit("close"); - }); - } else { - setImmediate(() => { - stream[kImpl].closed = true; - stream.emit("close"); - }); - } - } - function write(stream, data2, cb) { - const current = Atomics.load(stream[kImpl].state, WRITE_INDEX); - const length = Buffer.byteLength(data2); - stream[kImpl].data.write(data2, current); - Atomics.store(stream[kImpl].state, WRITE_INDEX, current + length); - Atomics.notify(stream[kImpl].state, WRITE_INDEX); - cb(); - return true; - } - function end(stream) { - if (stream[kImpl].ended || !stream[kImpl].ending || stream[kImpl].flushing) { - return; - } - stream[kImpl].ended = true; - try { - stream.flushSync(); - let readIndex = Atomics.load(stream[kImpl].state, READ_INDEX); - Atomics.store(stream[kImpl].state, WRITE_INDEX, -1); - Atomics.notify(stream[kImpl].state, WRITE_INDEX); - let spins = 0; - while (readIndex !== -1) { - Atomics.wait(stream[kImpl].state, READ_INDEX, readIndex, 1e3); - readIndex = Atomics.load(stream[kImpl].state, READ_INDEX); - if (readIndex === -2) { - destroy(stream, new Error("end() failed")); - return; - } - if (++spins === 10) { - destroy(stream, new Error("end() took too long (10s)")); - return; - } - } - process.nextTick(() => { - stream[kImpl].finished = true; - stream.emit("finish"); - }); - } catch (err) { - destroy(stream, err); - } - } - function writeSync(stream) { - const cb = () => { - if (stream[kImpl].ending) { - end(stream); - } else if (stream[kImpl].needDrain) { - process.nextTick(drain, stream); - } - }; - stream[kImpl].flushing = false; - while (stream[kImpl].buf.length !== 0) { - const writeIndex = Atomics.load(stream[kImpl].state, WRITE_INDEX); - let leftover = stream[kImpl].data.length - writeIndex; - if (leftover === 0) { - flushSync(stream); - Atomics.store(stream[kImpl].state, READ_INDEX, 0); - Atomics.store(stream[kImpl].state, WRITE_INDEX, 0); - continue; - } else if (leftover < 0) { - throw new Error("overwritten"); - } - let toWrite = stream[kImpl].buf.slice(0, leftover); - let toWriteBytes = Buffer.byteLength(toWrite); - if (toWriteBytes <= leftover) { - stream[kImpl].buf = stream[kImpl].buf.slice(leftover); - write(stream, toWrite, cb); - } else { - flushSync(stream); - Atomics.store(stream[kImpl].state, READ_INDEX, 0); - Atomics.store(stream[kImpl].state, WRITE_INDEX, 0); - while (toWriteBytes > stream[kImpl].buf.length) { - leftover = leftover / 2; - toWrite = stream[kImpl].buf.slice(0, leftover); - toWriteBytes = Buffer.byteLength(toWrite); - } - stream[kImpl].buf = stream[kImpl].buf.slice(leftover); - write(stream, toWrite, cb); - } - } - } - function flushSync(stream) { - if (stream[kImpl].flushing) { - throw new Error("unable to flush while flushing"); - } - const writeIndex = Atomics.load(stream[kImpl].state, WRITE_INDEX); - let spins = 0; - while (true) { - const readIndex = Atomics.load(stream[kImpl].state, READ_INDEX); - if (readIndex === -2) { - throw Error("_flushSync failed"); - } - if (readIndex !== writeIndex) { - Atomics.wait(stream[kImpl].state, READ_INDEX, readIndex, 1e3); - } else { - break; - } - if (++spins === 10) { - throw new Error("_flushSync took too long (10s)"); - } - } - } - module.exports = ThreadStream; - } -}); - -// node_modules/.pnpm/pino@9.14.0/node_modules/pino/lib/transport.js -var require_transport = __commonJS({ - "node_modules/.pnpm/pino@9.14.0/node_modules/pino/lib/transport.js"(exports, module) { - "use strict"; - var { createRequire: createRequire2 } = __require("module"); - var getCallers = require_caller(); - var { join: join4, isAbsolute: isAbsolute2, sep } = __require("node:path"); - var sleep = require_atomic_sleep(); - var onExit = require_on_exit_leak_free(); - var ThreadStream = require_thread_stream(); - function setupOnExit(stream) { - onExit.register(stream, autoEnd); - onExit.registerBeforeExit(stream, flush); - stream.on("close", function() { - onExit.unregister(stream); - }); - } - function buildStream(filename, workerData, workerOpts, sync) { - const stream = new ThreadStream({ - filename, - workerData, - workerOpts, - sync - }); - stream.on("ready", onReady); - stream.on("close", function() { - process.removeListener("exit", onExit2); - }); - process.on("exit", onExit2); - function onReady() { - process.removeListener("exit", onExit2); - stream.unref(); - if (workerOpts.autoEnd !== false) { - setupOnExit(stream); - } - } - function onExit2() { - if (stream.closed) { - return; - } - stream.flushSync(); - sleep(100); - stream.end(); - } - return stream; - } - function autoEnd(stream) { - stream.ref(); - stream.flushSync(); - stream.end(); - stream.once("close", function() { - stream.unref(); - }); - } - function flush(stream) { - stream.flushSync(); - } - function transport(fullOptions) { - const { pipeline, targets, levels: levels2, dedupe, worker = {}, caller = getCallers(), sync = false } = fullOptions; - const options = { - ...fullOptions.options - }; - const callers = typeof caller === "string" ? [caller] : caller; - const bundlerOverrides = "__bundlerPathsOverrides" in globalThis ? globalThis.__bundlerPathsOverrides : {}; - let target = fullOptions.target; - if (target && targets) { - throw new Error("only one of target or targets can be specified"); - } - if (targets) { - target = bundlerOverrides["pino-worker"] || join4(__dirname, "worker.js"); - options.targets = targets.filter((dest) => dest.target).map((dest) => { - return { - ...dest, - target: fixTarget(dest.target) - }; - }); - options.pipelines = targets.filter((dest) => dest.pipeline).map((dest) => { - return dest.pipeline.map((t5) => { - return { - ...t5, - level: dest.level, - // duplicate the pipeline `level` property defined in the upper level - target: fixTarget(t5.target) - }; - }); - }); - } else if (pipeline) { - target = bundlerOverrides["pino-worker"] || join4(__dirname, "worker.js"); - options.pipelines = [pipeline.map((dest) => { - return { - ...dest, - target: fixTarget(dest.target) - }; - })]; - } - if (levels2) { - options.levels = levels2; - } - if (dedupe) { - options.dedupe = dedupe; - } - options.pinoWillSendConfig = true; - return buildStream(fixTarget(target), options, worker, sync); - function fixTarget(origin) { - origin = bundlerOverrides[origin] || origin; - if (isAbsolute2(origin) || origin.indexOf("file://") === 0) { - return origin; - } - if (origin === "pino/file") { - return join4(__dirname, "..", "file.js"); - } - let fixTarget2; - for (const filePath of callers) { - try { - const context = filePath === "node:repl" ? process.cwd() + sep : filePath; - fixTarget2 = createRequire2(context).resolve(origin); - break; - } catch (err) { - continue; - } - } - if (!fixTarget2) { - throw new Error(`unable to determine transport target for "${origin}"`); - } - return fixTarget2; - } - } - module.exports = transport; - } -}); - -// node_modules/.pnpm/pino@9.14.0/node_modules/pino/lib/tools.js -var require_tools = __commonJS({ - "node_modules/.pnpm/pino@9.14.0/node_modules/pino/lib/tools.js"(exports, module) { - "use strict"; - var diagChan = __require("node:diagnostics_channel"); - var format2 = require_quick_format_unescaped(); - var { mapHttpRequest, mapHttpResponse } = require_pino_std_serializers(); - var SonicBoom = require_sonic_boom(); - var onExit = require_on_exit_leak_free(); - var { - lsCacheSym, - chindingsSym, - writeSym, - serializersSym, - formatOptsSym, - endSym, - stringifiersSym, - stringifySym, - stringifySafeSym, - wildcardFirstSym, - nestedKeySym, - formattersSym, - messageKeySym, - errorKeySym, - nestedKeyStrSym, - msgPrefixSym - } = require_symbols(); - var { isMainThread } = __require("worker_threads"); - var transport = require_transport(); - var asJsonChan; - if (typeof diagChan.tracingChannel === "function") { - asJsonChan = diagChan.tracingChannel("pino_asJson"); - } else { - asJsonChan = { - hasSubscribers: false, - traceSync(fn, store, thisArg, ...args) { - return fn.call(thisArg, ...args); - } - }; - } - function noop5() { - } - function genLog(level, hook) { - if (!hook) return LOG; - return function hookWrappedLog(...args) { - hook.call(this, args, LOG, level); - }; - function LOG(o5, ...n5) { - if (typeof o5 === "object") { - let msg = o5; - if (o5 !== null) { - if (o5.method && o5.headers && o5.socket) { - o5 = mapHttpRequest(o5); - } else if (typeof o5.setHeader === "function") { - o5 = mapHttpResponse(o5); - } - } - let formatParams; - if (msg === null && n5.length === 0) { - formatParams = [null]; - } else { - msg = n5.shift(); - formatParams = n5; - } - if (typeof this[msgPrefixSym] === "string" && msg !== void 0 && msg !== null) { - msg = this[msgPrefixSym] + msg; - } - this[writeSym](o5, format2(msg, formatParams, this[formatOptsSym]), level); - } else { - let msg = o5 === void 0 ? n5.shift() : o5; - if (typeof this[msgPrefixSym] === "string" && msg !== void 0 && msg !== null) { - msg = this[msgPrefixSym] + msg; - } - this[writeSym](null, format2(msg, n5, this[formatOptsSym]), level); - } - } - } - function asString15(str) { - let result = ""; - let last = 0; - let found = false; - let point2 = 255; - const l5 = str.length; - if (l5 > 100) { - return JSON.stringify(str); - } - for (var i5 = 0; i5 < l5 && point2 >= 32; i5++) { - point2 = str.charCodeAt(i5); - if (point2 === 34 || point2 === 92) { - result += str.slice(last, i5) + "\\"; - last = i5; - found = true; - } - } - if (!found) { - result = str; - } else { - result += str.slice(last); - } - return point2 < 32 ? JSON.stringify(str) : '"' + result + '"'; - } - function asJson(obj, msg, num, time5) { - if (asJsonChan.hasSubscribers === false) { - return _asJson.call(this, obj, msg, num, time5); - } - const store = { instance: this, arguments }; - return asJsonChan.traceSync(_asJson, store, this, obj, msg, num, time5); - } - function _asJson(obj, msg, num, time5) { - const stringify3 = this[stringifySym]; - const stringifySafe = this[stringifySafeSym]; - const stringifiers = this[stringifiersSym]; - const end = this[endSym]; - const chindings = this[chindingsSym]; - const serializers2 = this[serializersSym]; - const formatters = this[formattersSym]; - const messageKey = this[messageKeySym]; - const errorKey = this[errorKeySym]; - let data2 = this[lsCacheSym][num] + time5; - data2 = data2 + chindings; - let value; - if (formatters.log) { - obj = formatters.log(obj); - } - const wildcardStringifier = stringifiers[wildcardFirstSym]; - let propStr = ""; - for (const key in obj) { - value = obj[key]; - if (Object.prototype.hasOwnProperty.call(obj, key) && value !== void 0) { - if (serializers2[key]) { - value = serializers2[key](value); - } else if (key === errorKey && serializers2.err) { - value = serializers2.err(value); - } - const stringifier = stringifiers[key] || wildcardStringifier; - switch (typeof value) { - case "undefined": - case "function": - continue; - case "number": - if (Number.isFinite(value) === false) { - value = null; - } - // this case explicitly falls through to the next one - case "boolean": - if (stringifier) value = stringifier(value); - break; - case "string": - value = (stringifier || asString15)(value); - break; - default: - value = (stringifier || stringify3)(value, stringifySafe); - } - if (value === void 0) continue; - const strKey = asString15(key); - propStr += "," + strKey + ":" + value; - } - } - let msgStr = ""; - if (msg !== void 0) { - value = serializers2[messageKey] ? serializers2[messageKey](msg) : msg; - const stringifier = stringifiers[messageKey] || wildcardStringifier; - switch (typeof value) { - case "function": - break; - case "number": - if (Number.isFinite(value) === false) { - value = null; - } - // this case explicitly falls through to the next one - case "boolean": - if (stringifier) value = stringifier(value); - msgStr = ',"' + messageKey + '":' + value; - break; - case "string": - value = (stringifier || asString15)(value); - msgStr = ',"' + messageKey + '":' + value; - break; - default: - value = (stringifier || stringify3)(value, stringifySafe); - msgStr = ',"' + messageKey + '":' + value; - } - } - if (this[nestedKeySym] && propStr) { - return data2 + this[nestedKeyStrSym] + propStr.slice(1) + "}" + msgStr + end; - } else { - return data2 + propStr + msgStr + end; - } - } - function asChindings(instance, bindings) { - let value; - let data2 = instance[chindingsSym]; - const stringify3 = instance[stringifySym]; - const stringifySafe = instance[stringifySafeSym]; - const stringifiers = instance[stringifiersSym]; - const wildcardStringifier = stringifiers[wildcardFirstSym]; - const serializers2 = instance[serializersSym]; - const formatter = instance[formattersSym].bindings; - bindings = formatter(bindings); - for (const key in bindings) { - value = bindings[key]; - const valid = (key.length < 5 || key !== "level" && key !== "serializers" && key !== "formatters" && key !== "customLevels") && bindings.hasOwnProperty(key) && value !== void 0; - if (valid === true) { - value = serializers2[key] ? serializers2[key](value) : value; - value = (stringifiers[key] || wildcardStringifier || stringify3)(value, stringifySafe); - if (value === void 0) continue; - data2 += ',"' + key + '":' + value; - } - } - return data2; - } - function hasBeenTampered(stream) { - return stream.write !== stream.constructor.prototype.write; - } - function buildSafeSonicBoom(opts) { - const stream = new SonicBoom(opts); - stream.on("error", filterBrokenPipe); - if (!opts.sync && isMainThread) { - onExit.register(stream, autoEnd); - stream.on("close", function() { - onExit.unregister(stream); - }); - } - return stream; - function filterBrokenPipe(err) { - if (err.code === "EPIPE") { - stream.write = noop5; - stream.end = noop5; - stream.flushSync = noop5; - stream.destroy = noop5; - return; - } - stream.removeListener("error", filterBrokenPipe); - stream.emit("error", err); - } - } - function autoEnd(stream, eventName) { - if (stream.destroyed) { - return; - } - if (eventName === "beforeExit") { - stream.flush(); - stream.on("drain", function() { - stream.end(); - }); - } else { - stream.flushSync(); - } - } - function createArgsNormalizer(defaultOptions2) { - return function normalizeArgs(instance, caller, opts = {}, stream) { - if (typeof opts === "string") { - stream = buildSafeSonicBoom({ dest: opts }); - opts = {}; - } else if (typeof stream === "string") { - if (opts && opts.transport) { - throw Error("only one of option.transport or stream can be specified"); - } - stream = buildSafeSonicBoom({ dest: stream }); - } else if (opts instanceof SonicBoom || opts.writable || opts._writableState) { - stream = opts; - opts = {}; - } else if (opts.transport) { - if (opts.transport instanceof SonicBoom || opts.transport.writable || opts.transport._writableState) { - throw Error("option.transport do not allow stream, please pass to option directly. e.g. pino(transport)"); - } - if (opts.transport.targets && opts.transport.targets.length && opts.formatters && typeof opts.formatters.level === "function") { - throw Error("option.transport.targets do not allow custom level formatters"); - } - let customLevels; - if (opts.customLevels) { - customLevels = opts.useOnlyCustomLevels ? opts.customLevels : Object.assign({}, opts.levels, opts.customLevels); - } - stream = transport({ caller, ...opts.transport, levels: customLevels }); - } - opts = Object.assign({}, defaultOptions2, opts); - opts.serializers = Object.assign({}, defaultOptions2.serializers, opts.serializers); - opts.formatters = Object.assign({}, defaultOptions2.formatters, opts.formatters); - if (opts.prettyPrint) { - throw new Error("prettyPrint option is no longer supported, see the pino-pretty package (https://github.com/pinojs/pino-pretty)"); - } - const { enabled, onChild } = opts; - if (enabled === false) opts.level = "silent"; - if (!onChild) opts.onChild = noop5; - if (!stream) { - if (!hasBeenTampered(process.stdout)) { - stream = buildSafeSonicBoom({ fd: process.stdout.fd || 1 }); - } else { - stream = process.stdout; - } - } - return { opts, stream }; - }; - } - function stringify2(obj, stringifySafeFn) { - try { - return JSON.stringify(obj); - } catch (_) { - try { - const stringify3 = stringifySafeFn || this[stringifySafeSym]; - return stringify3(obj); - } catch (_2) { - return '"[unable to serialize, circular reference is too complex to analyze]"'; - } - } - } - function buildFormatters(level, bindings, log2) { - return { - level, - bindings, - log: log2 - }; - } - function normalizeDestFileDescriptor(destination) { - const fd = Number(destination); - if (typeof destination === "string" && Number.isFinite(fd)) { - return fd; - } - if (destination === void 0) { - return 1; - } - return destination; - } - module.exports = { - noop: noop5, - buildSafeSonicBoom, - asChindings, - asJson, - genLog, - createArgsNormalizer, - stringify: stringify2, - buildFormatters, - normalizeDestFileDescriptor - }; - } -}); - -// node_modules/.pnpm/pino@9.14.0/node_modules/pino/lib/constants.js -var require_constants = __commonJS({ - "node_modules/.pnpm/pino@9.14.0/node_modules/pino/lib/constants.js"(exports, module) { - var DEFAULT_LEVELS = { - trace: 10, - debug: 20, - info: 30, - warn: 40, - error: 50, - fatal: 60 - }; - var SORTING_ORDER = { - ASC: "ASC", - DESC: "DESC" - }; - module.exports = { - DEFAULT_LEVELS, - SORTING_ORDER - }; - } -}); - -// node_modules/.pnpm/pino@9.14.0/node_modules/pino/lib/levels.js -var require_levels = __commonJS({ - "node_modules/.pnpm/pino@9.14.0/node_modules/pino/lib/levels.js"(exports, module) { - "use strict"; - var { - lsCacheSym, - levelValSym, - useOnlyCustomLevelsSym, - streamSym, - formattersSym, - hooksSym, - levelCompSym - } = require_symbols(); - var { noop: noop5, genLog } = require_tools(); - var { DEFAULT_LEVELS, SORTING_ORDER } = require_constants(); - var levelMethods = { - fatal: (hook) => { - const logFatal = genLog(DEFAULT_LEVELS.fatal, hook); - return function(...args) { - const stream = this[streamSym]; - logFatal.call(this, ...args); - if (typeof stream.flushSync === "function") { - try { - stream.flushSync(); - } catch (e5) { - } - } - }; - }, - error: (hook) => genLog(DEFAULT_LEVELS.error, hook), - warn: (hook) => genLog(DEFAULT_LEVELS.warn, hook), - info: (hook) => genLog(DEFAULT_LEVELS.info, hook), - debug: (hook) => genLog(DEFAULT_LEVELS.debug, hook), - trace: (hook) => genLog(DEFAULT_LEVELS.trace, hook) - }; - var nums = Object.keys(DEFAULT_LEVELS).reduce((o5, k5) => { - o5[DEFAULT_LEVELS[k5]] = k5; - return o5; - }, {}); - var initialLsCache = Object.keys(nums).reduce((o5, k5) => { - o5[k5] = '{"level":' + Number(k5); - return o5; - }, {}); - function genLsCache(instance) { - const formatter = instance[formattersSym].level; - const { labels: labels2 } = instance.levels; - const cache7 = {}; - for (const label in labels2) { - const level = formatter(labels2[label], Number(label)); - cache7[label] = JSON.stringify(level).slice(0, -1); - } - instance[lsCacheSym] = cache7; - return instance; - } - function isStandardLevel(level, useOnlyCustomLevels) { - if (useOnlyCustomLevels) { - return false; - } - switch (level) { - case "fatal": - case "error": - case "warn": - case "info": - case "debug": - case "trace": - return true; - default: - return false; - } - } - function setLevel(level) { - const { labels: labels2, values: values2 } = this.levels; - if (typeof level === "number") { - if (labels2[level] === void 0) throw Error("unknown level value" + level); - level = labels2[level]; - } - if (values2[level] === void 0) throw Error("unknown level " + level); - const preLevelVal = this[levelValSym]; - const levelVal = this[levelValSym] = values2[level]; - const useOnlyCustomLevelsVal = this[useOnlyCustomLevelsSym]; - const levelComparison = this[levelCompSym]; - const hook = this[hooksSym].logMethod; - for (const key in values2) { - if (levelComparison(values2[key], levelVal) === false) { - this[key] = noop5; - continue; - } - this[key] = isStandardLevel(key, useOnlyCustomLevelsVal) ? levelMethods[key](hook) : genLog(values2[key], hook); - } - this.emit( - "level-change", - level, - levelVal, - labels2[preLevelVal], - preLevelVal, - this - ); - } - function getLevel(level) { - const { levels: levels2, levelVal } = this; - return levels2 && levels2.labels ? levels2.labels[levelVal] : ""; - } - function isLevelEnabled(logLevel) { - const { values: values2 } = this.levels; - const logLevelVal = values2[logLevel]; - return logLevelVal !== void 0 && this[levelCompSym](logLevelVal, this[levelValSym]); - } - function compareLevel(direction, current, expected) { - if (direction === SORTING_ORDER.DESC) { - return current <= expected; - } - return current >= expected; - } - function genLevelComparison(levelComparison) { - if (typeof levelComparison === "string") { - return compareLevel.bind(null, levelComparison); - } - return levelComparison; - } - function mappings(customLevels = null, useOnlyCustomLevels = false) { - const customNums = customLevels ? Object.keys(customLevels).reduce((o5, k5) => { - o5[customLevels[k5]] = k5; - return o5; - }, {}) : null; - const labels2 = Object.assign( - Object.create(Object.prototype, { Infinity: { value: "silent" } }), - useOnlyCustomLevels ? null : nums, - customNums - ); - const values2 = Object.assign( - Object.create(Object.prototype, { silent: { value: Infinity } }), - useOnlyCustomLevels ? null : DEFAULT_LEVELS, - customLevels - ); - return { labels: labels2, values: values2 }; - } - function assertDefaultLevelFound(defaultLevel, customLevels, useOnlyCustomLevels) { - if (typeof defaultLevel === "number") { - const values2 = [].concat( - Object.keys(customLevels || {}).map((key) => customLevels[key]), - useOnlyCustomLevels ? [] : Object.keys(nums).map((level) => +level), - Infinity - ); - if (!values2.includes(defaultLevel)) { - throw Error(`default level:${defaultLevel} must be included in custom levels`); - } - return; - } - const labels2 = Object.assign( - Object.create(Object.prototype, { silent: { value: Infinity } }), - useOnlyCustomLevels ? null : DEFAULT_LEVELS, - customLevels - ); - if (!(defaultLevel in labels2)) { - throw Error(`default level:${defaultLevel} must be included in custom levels`); - } - } - function assertNoLevelCollisions(levels2, customLevels) { - const { labels: labels2, values: values2 } = levels2; - for (const k5 in customLevels) { - if (k5 in values2) { - throw Error("levels cannot be overridden"); - } - if (customLevels[k5] in labels2) { - throw Error("pre-existing level values cannot be used for new levels"); - } - } - } - function assertLevelComparison(levelComparison) { - if (typeof levelComparison === "function") { - return; - } - if (typeof levelComparison === "string" && Object.values(SORTING_ORDER).includes(levelComparison)) { - return; - } - throw new Error('Levels comparison should be one of "ASC", "DESC" or "function" type'); - } - module.exports = { - initialLsCache, - genLsCache, - levelMethods, - getLevel, - setLevel, - isLevelEnabled, - mappings, - assertNoLevelCollisions, - assertDefaultLevelFound, - genLevelComparison, - assertLevelComparison - }; - } -}); - -// node_modules/.pnpm/pino@9.14.0/node_modules/pino/lib/meta.js -var require_meta = __commonJS({ - "node_modules/.pnpm/pino@9.14.0/node_modules/pino/lib/meta.js"(exports, module) { - "use strict"; - module.exports = { version: "9.14.0" }; - } -}); - -// node_modules/.pnpm/pino@9.14.0/node_modules/pino/lib/proto.js -var require_proto = __commonJS({ - "node_modules/.pnpm/pino@9.14.0/node_modules/pino/lib/proto.js"(exports, module) { - "use strict"; - var { EventEmitter: EventEmitter5 } = __require("node:events"); - var { - lsCacheSym, - levelValSym, - setLevelSym, - getLevelSym, - chindingsSym, - parsedChindingsSym, - mixinSym, - asJsonSym, - writeSym, - mixinMergeStrategySym, - timeSym, - timeSliceIndexSym, - streamSym, - serializersSym, - formattersSym, - errorKeySym, - messageKeySym, - useOnlyCustomLevelsSym, - needsMetadataGsym, - redactFmtSym, - stringifySym, - formatOptsSym, - stringifiersSym, - msgPrefixSym, - hooksSym - } = require_symbols(); - var { - getLevel, - setLevel, - isLevelEnabled, - mappings, - initialLsCache, - genLsCache, - assertNoLevelCollisions - } = require_levels(); - var { - asChindings, - asJson, - buildFormatters, - stringify: stringify2, - noop: noop5 - } = require_tools(); - var { - version: version3 - } = require_meta(); - var redaction = require_redaction(); - var constructor = class Pino { - }; - var prototype = { - constructor, - child, - bindings, - setBindings, - flush, - isLevelEnabled, - version: version3, - get level() { - return this[getLevelSym](); - }, - set level(lvl) { - this[setLevelSym](lvl); - }, - get levelVal() { - return this[levelValSym]; - }, - set levelVal(n5) { - throw Error("levelVal is read-only"); - }, - get msgPrefix() { - return this[msgPrefixSym]; - }, - get [Symbol.toStringTag]() { - return "Pino"; - }, - [lsCacheSym]: initialLsCache, - [writeSym]: write, - [asJsonSym]: asJson, - [getLevelSym]: getLevel, - [setLevelSym]: setLevel - }; - Object.setPrototypeOf(prototype, EventEmitter5.prototype); - module.exports = function() { - return Object.create(prototype); - }; - var resetChildingsFormatter = (bindings2) => bindings2; - function child(bindings2, options) { - if (!bindings2) { - throw Error("missing bindings for child Pino"); - } - const serializers2 = this[serializersSym]; - const formatters = this[formattersSym]; - const instance = Object.create(this); - if (options == null) { - if (instance[formattersSym].bindings !== resetChildingsFormatter) { - instance[formattersSym] = buildFormatters( - formatters.level, - resetChildingsFormatter, - formatters.log - ); - } - instance[chindingsSym] = asChindings(instance, bindings2); - instance[setLevelSym](this.level); - if (this.onChild !== noop5) { - this.onChild(instance); - } - return instance; - } - if (options.hasOwnProperty("serializers") === true) { - instance[serializersSym] = /* @__PURE__ */ Object.create(null); - for (const k5 in serializers2) { - instance[serializersSym][k5] = serializers2[k5]; - } - const parentSymbols = Object.getOwnPropertySymbols(serializers2); - for (var i5 = 0; i5 < parentSymbols.length; i5++) { - const ks = parentSymbols[i5]; - instance[serializersSym][ks] = serializers2[ks]; - } - for (const bk in options.serializers) { - instance[serializersSym][bk] = options.serializers[bk]; - } - const bindingsSymbols = Object.getOwnPropertySymbols(options.serializers); - for (var bi = 0; bi < bindingsSymbols.length; bi++) { - const bks = bindingsSymbols[bi]; - instance[serializersSym][bks] = options.serializers[bks]; - } - } else instance[serializersSym] = serializers2; - if (options.hasOwnProperty("formatters")) { - const { level, bindings: chindings, log: log2 } = options.formatters; - instance[formattersSym] = buildFormatters( - level || formatters.level, - chindings || resetChildingsFormatter, - log2 || formatters.log - ); - } else { - instance[formattersSym] = buildFormatters( - formatters.level, - resetChildingsFormatter, - formatters.log - ); - } - if (options.hasOwnProperty("customLevels") === true) { - assertNoLevelCollisions(this.levels, options.customLevels); - instance.levels = mappings(options.customLevels, instance[useOnlyCustomLevelsSym]); - genLsCache(instance); - } - if (typeof options.redact === "object" && options.redact !== null || Array.isArray(options.redact)) { - instance.redact = options.redact; - const stringifiers = redaction(instance.redact, stringify2); - const formatOpts = { stringify: stringifiers[redactFmtSym] }; - instance[stringifySym] = stringify2; - instance[stringifiersSym] = stringifiers; - instance[formatOptsSym] = formatOpts; - } - if (typeof options.msgPrefix === "string") { - instance[msgPrefixSym] = (this[msgPrefixSym] || "") + options.msgPrefix; - } - instance[chindingsSym] = asChindings(instance, bindings2); - const childLevel = options.level || this.level; - instance[setLevelSym](childLevel); - this.onChild(instance); - return instance; - } - function bindings() { - const chindings = this[chindingsSym]; - const chindingsJson = `{${chindings.substr(1)}}`; - const bindingsFromJson = JSON.parse(chindingsJson); - delete bindingsFromJson.pid; - delete bindingsFromJson.hostname; - return bindingsFromJson; - } - function setBindings(newBindings) { - const chindings = asChindings(this, newBindings); - this[chindingsSym] = chindings; - delete this[parsedChindingsSym]; - } - function defaultMixinMergeStrategy(mergeObject, mixinObject) { - return Object.assign(mixinObject, mergeObject); - } - function write(_obj, msg, num) { - const t5 = this[timeSym](); - const mixin = this[mixinSym]; - const errorKey = this[errorKeySym]; - const messageKey = this[messageKeySym]; - const mixinMergeStrategy = this[mixinMergeStrategySym] || defaultMixinMergeStrategy; - let obj; - const streamWriteHook = this[hooksSym].streamWrite; - if (_obj === void 0 || _obj === null) { - obj = {}; - } else if (_obj instanceof Error) { - obj = { [errorKey]: _obj }; - if (msg === void 0) { - msg = _obj.message; - } - } else { - obj = _obj; - if (msg === void 0 && _obj[messageKey] === void 0 && _obj[errorKey]) { - msg = _obj[errorKey].message; - } - } - if (mixin) { - obj = mixinMergeStrategy(obj, mixin(obj, num, this)); - } - const s5 = this[asJsonSym](obj, msg, num, t5); - const stream = this[streamSym]; - if (stream[needsMetadataGsym] === true) { - stream.lastLevel = num; - stream.lastObj = obj; - stream.lastMsg = msg; - stream.lastTime = t5.slice(this[timeSliceIndexSym]); - stream.lastLogger = this; - } - stream.write(streamWriteHook ? streamWriteHook(s5) : s5); - } - function flush(cb) { - if (cb != null && typeof cb !== "function") { - throw Error("callback must be a function"); - } - const stream = this[streamSym]; - if (typeof stream.flush === "function") { - stream.flush(cb || noop5); - } else if (cb) cb(); - } - } -}); - -// node_modules/.pnpm/safe-stable-stringify@2.5.0/node_modules/safe-stable-stringify/index.js -var require_safe_stable_stringify = __commonJS({ - "node_modules/.pnpm/safe-stable-stringify@2.5.0/node_modules/safe-stable-stringify/index.js"(exports, module) { - "use strict"; - var { hasOwnProperty } = Object.prototype; - var stringify2 = configure(); - stringify2.configure = configure; - stringify2.stringify = stringify2; - stringify2.default = stringify2; - exports.stringify = stringify2; - exports.configure = configure; - module.exports = stringify2; - var strEscapeSequencesRegExp = /[\u0000-\u001f\u0022\u005c\ud800-\udfff]/; - function strEscape(str) { - if (str.length < 5e3 && !strEscapeSequencesRegExp.test(str)) { - return `"${str}"`; - } - return JSON.stringify(str); - } - function sort(array2, comparator) { - if (array2.length > 200 || comparator) { - return array2.sort(comparator); - } - for (let i5 = 1; i5 < array2.length; i5++) { - const currentValue = array2[i5]; - let position = i5; - while (position !== 0 && array2[position - 1] > currentValue) { - array2[position] = array2[position - 1]; - position--; - } - array2[position] = currentValue; - } - return array2; - } - var typedArrayPrototypeGetSymbolToStringTag = Object.getOwnPropertyDescriptor( - Object.getPrototypeOf( - Object.getPrototypeOf( - new Int8Array() - ) - ), - Symbol.toStringTag - ).get; - function isTypedArrayWithEntries(value) { - return typedArrayPrototypeGetSymbolToStringTag.call(value) !== void 0 && value.length !== 0; - } - function stringifyTypedArray(array2, separator, maximumBreadth) { - if (array2.length < maximumBreadth) { - maximumBreadth = array2.length; - } - const whitespace = separator === "," ? "" : " "; - let res = `"0":${whitespace}${array2[0]}`; - for (let i5 = 1; i5 < maximumBreadth; i5++) { - res += `${separator}"${i5}":${whitespace}${array2[i5]}`; - } - return res; - } - function getCircularValueOption(options) { - if (hasOwnProperty.call(options, "circularValue")) { - const circularValue = options.circularValue; - if (typeof circularValue === "string") { - return `"${circularValue}"`; - } - if (circularValue == null) { - return circularValue; - } - if (circularValue === Error || circularValue === TypeError) { - return { - toString() { - throw new TypeError("Converting circular structure to JSON"); - } - }; - } - throw new TypeError('The "circularValue" argument must be of type string or the value null or undefined'); - } - return '"[Circular]"'; - } - function getDeterministicOption(options) { - let value; - if (hasOwnProperty.call(options, "deterministic")) { - value = options.deterministic; - if (typeof value !== "boolean" && typeof value !== "function") { - throw new TypeError('The "deterministic" argument must be of type boolean or comparator function'); - } - } - return value === void 0 ? true : value; - } - function getBooleanOption(options, key) { - let value; - if (hasOwnProperty.call(options, key)) { - value = options[key]; - if (typeof value !== "boolean") { - throw new TypeError(`The "${key}" argument must be of type boolean`); - } - } - return value === void 0 ? true : value; - } - function getPositiveIntegerOption(options, key) { - let value; - if (hasOwnProperty.call(options, key)) { - value = options[key]; - if (typeof value !== "number") { - throw new TypeError(`The "${key}" argument must be of type number`); - } - if (!Number.isInteger(value)) { - throw new TypeError(`The "${key}" argument must be an integer`); - } - if (value < 1) { - throw new RangeError(`The "${key}" argument must be >= 1`); - } - } - return value === void 0 ? Infinity : value; - } - function getItemCount(number4) { - if (number4 === 1) { - return "1 item"; - } - return `${number4} items`; - } - function getUniqueReplacerSet(replacerArray) { - const replacerSet = /* @__PURE__ */ new Set(); - for (const value of replacerArray) { - if (typeof value === "string" || typeof value === "number") { - replacerSet.add(String(value)); - } - } - return replacerSet; - } - function getStrictOption(options) { - if (hasOwnProperty.call(options, "strict")) { - const value = options.strict; - if (typeof value !== "boolean") { - throw new TypeError('The "strict" argument must be of type boolean'); - } - if (value) { - return (value2) => { - let message2 = `Object can not safely be stringified. Received type ${typeof value2}`; - if (typeof value2 !== "function") message2 += ` (${value2.toString()})`; - throw new Error(message2); - }; - } - } - } - function configure(options) { - options = { ...options }; - const fail = getStrictOption(options); - if (fail) { - if (options.bigint === void 0) { - options.bigint = false; - } - if (!("circularValue" in options)) { - options.circularValue = Error; - } - } - const circularValue = getCircularValueOption(options); - const bigint5 = getBooleanOption(options, "bigint"); - const deterministic = getDeterministicOption(options); - const comparator = typeof deterministic === "function" ? deterministic : void 0; - const maximumDepth = getPositiveIntegerOption(options, "maximumDepth"); - const maximumBreadth = getPositiveIntegerOption(options, "maximumBreadth"); - function stringifyFnReplacer(key, parent, stack, replacer, spacer, indentation) { - let value = parent[key]; - if (typeof value === "object" && value !== null && typeof value.toJSON === "function") { - value = value.toJSON(key); - } - value = replacer.call(parent, key, value); - switch (typeof value) { - case "string": - return strEscape(value); - case "object": { - if (value === null) { - return "null"; - } - if (stack.indexOf(value) !== -1) { - return circularValue; - } - let res = ""; - let join4 = ","; - const originalIndentation = indentation; - if (Array.isArray(value)) { - if (value.length === 0) { - return "[]"; - } - if (maximumDepth < stack.length + 1) { - return '"[Array]"'; - } - stack.push(value); - if (spacer !== "") { - indentation += spacer; - res += ` -${indentation}`; - join4 = `, -${indentation}`; - } - const maximumValuesToStringify = Math.min(value.length, maximumBreadth); - let i5 = 0; - for (; i5 < maximumValuesToStringify - 1; i5++) { - const tmp2 = stringifyFnReplacer(String(i5), value, stack, replacer, spacer, indentation); - res += tmp2 !== void 0 ? tmp2 : "null"; - res += join4; - } - const tmp = stringifyFnReplacer(String(i5), value, stack, replacer, spacer, indentation); - res += tmp !== void 0 ? tmp : "null"; - if (value.length - 1 > maximumBreadth) { - const removedKeys = value.length - maximumBreadth - 1; - res += `${join4}"... ${getItemCount(removedKeys)} not stringified"`; - } - if (spacer !== "") { - res += ` -${originalIndentation}`; - } - stack.pop(); - return `[${res}]`; - } - let keys = Object.keys(value); - const keyLength = keys.length; - if (keyLength === 0) { - return "{}"; - } - if (maximumDepth < stack.length + 1) { - return '"[Object]"'; - } - let whitespace = ""; - let separator = ""; - if (spacer !== "") { - indentation += spacer; - join4 = `, -${indentation}`; - whitespace = " "; - } - const maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth); - if (deterministic && !isTypedArrayWithEntries(value)) { - keys = sort(keys, comparator); - } - stack.push(value); - for (let i5 = 0; i5 < maximumPropertiesToStringify; i5++) { - const key2 = keys[i5]; - const tmp = stringifyFnReplacer(key2, value, stack, replacer, spacer, indentation); - if (tmp !== void 0) { - res += `${separator}${strEscape(key2)}:${whitespace}${tmp}`; - separator = join4; - } - } - if (keyLength > maximumBreadth) { - const removedKeys = keyLength - maximumBreadth; - res += `${separator}"...":${whitespace}"${getItemCount(removedKeys)} not stringified"`; - separator = join4; - } - if (spacer !== "" && separator.length > 1) { - res = ` -${indentation}${res} -${originalIndentation}`; - } - stack.pop(); - return `{${res}}`; - } - case "number": - return isFinite(value) ? String(value) : fail ? fail(value) : "null"; - case "boolean": - return value === true ? "true" : "false"; - case "undefined": - return void 0; - case "bigint": - if (bigint5) { - return String(value); - } - // fallthrough - default: - return fail ? fail(value) : void 0; - } - } - function stringifyArrayReplacer(key, value, stack, replacer, spacer, indentation) { - if (typeof value === "object" && value !== null && typeof value.toJSON === "function") { - value = value.toJSON(key); - } - switch (typeof value) { - case "string": - return strEscape(value); - case "object": { - if (value === null) { - return "null"; - } - if (stack.indexOf(value) !== -1) { - return circularValue; - } - const originalIndentation = indentation; - let res = ""; - let join4 = ","; - if (Array.isArray(value)) { - if (value.length === 0) { - return "[]"; - } - if (maximumDepth < stack.length + 1) { - return '"[Array]"'; - } - stack.push(value); - if (spacer !== "") { - indentation += spacer; - res += ` -${indentation}`; - join4 = `, -${indentation}`; - } - const maximumValuesToStringify = Math.min(value.length, maximumBreadth); - let i5 = 0; - for (; i5 < maximumValuesToStringify - 1; i5++) { - const tmp2 = stringifyArrayReplacer(String(i5), value[i5], stack, replacer, spacer, indentation); - res += tmp2 !== void 0 ? tmp2 : "null"; - res += join4; - } - const tmp = stringifyArrayReplacer(String(i5), value[i5], stack, replacer, spacer, indentation); - res += tmp !== void 0 ? tmp : "null"; - if (value.length - 1 > maximumBreadth) { - const removedKeys = value.length - maximumBreadth - 1; - res += `${join4}"... ${getItemCount(removedKeys)} not stringified"`; - } - if (spacer !== "") { - res += ` -${originalIndentation}`; - } - stack.pop(); - return `[${res}]`; - } - stack.push(value); - let whitespace = ""; - if (spacer !== "") { - indentation += spacer; - join4 = `, -${indentation}`; - whitespace = " "; - } - let separator = ""; - for (const key2 of replacer) { - const tmp = stringifyArrayReplacer(key2, value[key2], stack, replacer, spacer, indentation); - if (tmp !== void 0) { - res += `${separator}${strEscape(key2)}:${whitespace}${tmp}`; - separator = join4; - } - } - if (spacer !== "" && separator.length > 1) { - res = ` -${indentation}${res} -${originalIndentation}`; - } - stack.pop(); - return `{${res}}`; - } - case "number": - return isFinite(value) ? String(value) : fail ? fail(value) : "null"; - case "boolean": - return value === true ? "true" : "false"; - case "undefined": - return void 0; - case "bigint": - if (bigint5) { - return String(value); - } - // fallthrough - default: - return fail ? fail(value) : void 0; - } - } - function stringifyIndent(key, value, stack, spacer, indentation) { - switch (typeof value) { - case "string": - return strEscape(value); - case "object": { - if (value === null) { - return "null"; - } - if (typeof value.toJSON === "function") { - value = value.toJSON(key); - if (typeof value !== "object") { - return stringifyIndent(key, value, stack, spacer, indentation); - } - if (value === null) { - return "null"; - } - } - if (stack.indexOf(value) !== -1) { - return circularValue; - } - const originalIndentation = indentation; - if (Array.isArray(value)) { - if (value.length === 0) { - return "[]"; - } - if (maximumDepth < stack.length + 1) { - return '"[Array]"'; - } - stack.push(value); - indentation += spacer; - let res2 = ` -${indentation}`; - const join5 = `, -${indentation}`; - const maximumValuesToStringify = Math.min(value.length, maximumBreadth); - let i5 = 0; - for (; i5 < maximumValuesToStringify - 1; i5++) { - const tmp2 = stringifyIndent(String(i5), value[i5], stack, spacer, indentation); - res2 += tmp2 !== void 0 ? tmp2 : "null"; - res2 += join5; - } - const tmp = stringifyIndent(String(i5), value[i5], stack, spacer, indentation); - res2 += tmp !== void 0 ? tmp : "null"; - if (value.length - 1 > maximumBreadth) { - const removedKeys = value.length - maximumBreadth - 1; - res2 += `${join5}"... ${getItemCount(removedKeys)} not stringified"`; - } - res2 += ` -${originalIndentation}`; - stack.pop(); - return `[${res2}]`; - } - let keys = Object.keys(value); - const keyLength = keys.length; - if (keyLength === 0) { - return "{}"; - } - if (maximumDepth < stack.length + 1) { - return '"[Object]"'; - } - indentation += spacer; - const join4 = `, -${indentation}`; - let res = ""; - let separator = ""; - let maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth); - if (isTypedArrayWithEntries(value)) { - res += stringifyTypedArray(value, join4, maximumBreadth); - keys = keys.slice(value.length); - maximumPropertiesToStringify -= value.length; - separator = join4; - } - if (deterministic) { - keys = sort(keys, comparator); - } - stack.push(value); - for (let i5 = 0; i5 < maximumPropertiesToStringify; i5++) { - const key2 = keys[i5]; - const tmp = stringifyIndent(key2, value[key2], stack, spacer, indentation); - if (tmp !== void 0) { - res += `${separator}${strEscape(key2)}: ${tmp}`; - separator = join4; - } - } - if (keyLength > maximumBreadth) { - const removedKeys = keyLength - maximumBreadth; - res += `${separator}"...": "${getItemCount(removedKeys)} not stringified"`; - separator = join4; - } - if (separator !== "") { - res = ` -${indentation}${res} -${originalIndentation}`; - } - stack.pop(); - return `{${res}}`; - } - case "number": - return isFinite(value) ? String(value) : fail ? fail(value) : "null"; - case "boolean": - return value === true ? "true" : "false"; - case "undefined": - return void 0; - case "bigint": - if (bigint5) { - return String(value); - } - // fallthrough - default: - return fail ? fail(value) : void 0; - } - } - function stringifySimple(key, value, stack) { - switch (typeof value) { - case "string": - return strEscape(value); - case "object": { - if (value === null) { - return "null"; - } - if (typeof value.toJSON === "function") { - value = value.toJSON(key); - if (typeof value !== "object") { - return stringifySimple(key, value, stack); - } - if (value === null) { - return "null"; - } - } - if (stack.indexOf(value) !== -1) { - return circularValue; - } - let res = ""; - const hasLength = value.length !== void 0; - if (hasLength && Array.isArray(value)) { - if (value.length === 0) { - return "[]"; - } - if (maximumDepth < stack.length + 1) { - return '"[Array]"'; - } - stack.push(value); - const maximumValuesToStringify = Math.min(value.length, maximumBreadth); - let i5 = 0; - for (; i5 < maximumValuesToStringify - 1; i5++) { - const tmp2 = stringifySimple(String(i5), value[i5], stack); - res += tmp2 !== void 0 ? tmp2 : "null"; - res += ","; - } - const tmp = stringifySimple(String(i5), value[i5], stack); - res += tmp !== void 0 ? tmp : "null"; - if (value.length - 1 > maximumBreadth) { - const removedKeys = value.length - maximumBreadth - 1; - res += `,"... ${getItemCount(removedKeys)} not stringified"`; - } - stack.pop(); - return `[${res}]`; - } - let keys = Object.keys(value); - const keyLength = keys.length; - if (keyLength === 0) { - return "{}"; - } - if (maximumDepth < stack.length + 1) { - return '"[Object]"'; - } - let separator = ""; - let maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth); - if (hasLength && isTypedArrayWithEntries(value)) { - res += stringifyTypedArray(value, ",", maximumBreadth); - keys = keys.slice(value.length); - maximumPropertiesToStringify -= value.length; - separator = ","; - } - if (deterministic) { - keys = sort(keys, comparator); - } - stack.push(value); - for (let i5 = 0; i5 < maximumPropertiesToStringify; i5++) { - const key2 = keys[i5]; - const tmp = stringifySimple(key2, value[key2], stack); - if (tmp !== void 0) { - res += `${separator}${strEscape(key2)}:${tmp}`; - separator = ","; - } - } - if (keyLength > maximumBreadth) { - const removedKeys = keyLength - maximumBreadth; - res += `${separator}"...":"${getItemCount(removedKeys)} not stringified"`; - } - stack.pop(); - return `{${res}}`; - } - case "number": - return isFinite(value) ? String(value) : fail ? fail(value) : "null"; - case "boolean": - return value === true ? "true" : "false"; - case "undefined": - return void 0; - case "bigint": - if (bigint5) { - return String(value); - } - // fallthrough - default: - return fail ? fail(value) : void 0; - } - } - function stringify3(value, replacer, space) { - if (arguments.length > 1) { - let spacer = ""; - if (typeof space === "number") { - spacer = " ".repeat(Math.min(space, 10)); - } else if (typeof space === "string") { - spacer = space.slice(0, 10); - } - if (replacer != null) { - if (typeof replacer === "function") { - return stringifyFnReplacer("", { "": value }, [], replacer, spacer, ""); - } - if (Array.isArray(replacer)) { - return stringifyArrayReplacer("", value, [], getUniqueReplacerSet(replacer), spacer, ""); - } - } - if (spacer.length !== 0) { - return stringifyIndent("", value, [], spacer, ""); - } - } - return stringifySimple("", value, []); - } - return stringify3; - } - } -}); - -// node_modules/.pnpm/pino@9.14.0/node_modules/pino/lib/multistream.js -var require_multistream = __commonJS({ - "node_modules/.pnpm/pino@9.14.0/node_modules/pino/lib/multistream.js"(exports, module) { - "use strict"; - var metadata = /* @__PURE__ */ Symbol.for("pino.metadata"); - var { DEFAULT_LEVELS } = require_constants(); - var DEFAULT_INFO_LEVEL = DEFAULT_LEVELS.info; - function multistream(streamsArray, opts) { - streamsArray = streamsArray || []; - opts = opts || { dedupe: false }; - const streamLevels = Object.create(DEFAULT_LEVELS); - streamLevels.silent = Infinity; - if (opts.levels && typeof opts.levels === "object") { - Object.keys(opts.levels).forEach((i5) => { - streamLevels[i5] = opts.levels[i5]; - }); - } - const res = { - write, - add, - remove, - emit, - flushSync, - end, - minLevel: 0, - lastId: 0, - streams: [], - clone: clone3, - [metadata]: true, - streamLevels - }; - if (Array.isArray(streamsArray)) { - streamsArray.forEach(add, res); - } else { - add.call(res, streamsArray); - } - streamsArray = null; - return res; - function write(data2) { - let dest; - const level = this.lastLevel; - const { streams } = this; - let recordedLevel = 0; - let stream; - for (let i5 = initLoopVar(streams.length, opts.dedupe); checkLoopVar(i5, streams.length, opts.dedupe); i5 = adjustLoopVar(i5, opts.dedupe)) { - dest = streams[i5]; - if (dest.level <= level) { - if (recordedLevel !== 0 && recordedLevel !== dest.level) { - break; - } - stream = dest.stream; - if (stream[metadata]) { - const { lastTime, lastMsg, lastObj, lastLogger } = this; - stream.lastLevel = level; - stream.lastTime = lastTime; - stream.lastMsg = lastMsg; - stream.lastObj = lastObj; - stream.lastLogger = lastLogger; - } - stream.write(data2); - if (opts.dedupe) { - recordedLevel = dest.level; - } - } else if (!opts.dedupe) { - break; - } - } - } - function emit(...args) { - for (const { stream } of this.streams) { - if (typeof stream.emit === "function") { - stream.emit(...args); - } - } - } - function flushSync() { - for (const { stream } of this.streams) { - if (typeof stream.flushSync === "function") { - stream.flushSync(); - } - } - } - function add(dest) { - if (!dest) { - return res; - } - const isStream = typeof dest.write === "function" || dest.stream; - const stream_ = dest.write ? dest : dest.stream; - if (!isStream) { - throw Error("stream object needs to implement either StreamEntry or DestinationStream interface"); - } - const { streams, streamLevels: streamLevels2 } = this; - let level; - if (typeof dest.levelVal === "number") { - level = dest.levelVal; - } else if (typeof dest.level === "string") { - level = streamLevels2[dest.level]; - } else if (typeof dest.level === "number") { - level = dest.level; - } else { - level = DEFAULT_INFO_LEVEL; - } - const dest_ = { - stream: stream_, - level, - levelVal: void 0, - id: ++res.lastId - }; - streams.unshift(dest_); - streams.sort(compareByLevel); - this.minLevel = streams[0].level; - return res; - } - function remove(id) { - const { streams } = this; - const index2 = streams.findIndex((s5) => s5.id === id); - if (index2 >= 0) { - streams.splice(index2, 1); - streams.sort(compareByLevel); - this.minLevel = streams.length > 0 ? streams[0].level : -1; - } - return res; - } - function end() { - for (const { stream } of this.streams) { - if (typeof stream.flushSync === "function") { - stream.flushSync(); - } - stream.end(); - } - } - function clone3(level) { - const streams = new Array(this.streams.length); - for (let i5 = 0; i5 < streams.length; i5++) { - streams[i5] = { - level, - stream: this.streams[i5].stream - }; - } - return { - write, - add, - remove, - minLevel: level, - streams, - clone: clone3, - emit, - flushSync, - [metadata]: true - }; - } - } - function compareByLevel(a5, b6) { - return a5.level - b6.level; - } - function initLoopVar(length, dedupe) { - return dedupe ? length - 1 : 0; - } - function adjustLoopVar(i5, dedupe) { - return dedupe ? i5 - 1 : i5 + 1; - } - function checkLoopVar(i5, length, dedupe) { - return dedupe ? i5 >= 0 : i5 < length; - } - module.exports = multistream; - } -}); - -// node_modules/.pnpm/pino@9.14.0/node_modules/pino/pino.js -var require_pino = __commonJS({ - "node_modules/.pnpm/pino@9.14.0/node_modules/pino/pino.js"(exports, module) { - "use strict"; - var os24 = __require("node:os"); - var stdSerializers = require_pino_std_serializers(); - var caller = require_caller(); - var redaction = require_redaction(); - var time5 = require_time(); - var proto = require_proto(); - var symbols = require_symbols(); - var { configure } = require_safe_stable_stringify(); - var { assertDefaultLevelFound, mappings, genLsCache, genLevelComparison, assertLevelComparison } = require_levels(); - var { DEFAULT_LEVELS, SORTING_ORDER } = require_constants(); - var { - createArgsNormalizer, - asChindings, - buildSafeSonicBoom, - buildFormatters, - stringify: stringify2, - normalizeDestFileDescriptor, - noop: noop5 - } = require_tools(); - var { version: version3 } = require_meta(); - var { - chindingsSym, - redactFmtSym, - serializersSym, - timeSym, - timeSliceIndexSym, - streamSym, - stringifySym, - stringifySafeSym, - stringifiersSym, - setLevelSym, - endSym, - formatOptsSym, - messageKeySym, - errorKeySym, - nestedKeySym, - mixinSym, - levelCompSym, - useOnlyCustomLevelsSym, - formattersSym, - hooksSym, - nestedKeyStrSym, - mixinMergeStrategySym, - msgPrefixSym - } = symbols; - var { epochTime, nullTime } = time5; - var { pid } = process; - var hostname3 = os24.hostname(); - var defaultErrorSerializer = stdSerializers.err; - var defaultOptions2 = { - level: "info", - levelComparison: SORTING_ORDER.ASC, - levels: DEFAULT_LEVELS, - messageKey: "msg", - errorKey: "err", - nestedKey: null, - enabled: true, - base: { pid, hostname: hostname3 }, - serializers: Object.assign(/* @__PURE__ */ Object.create(null), { - err: defaultErrorSerializer - }), - formatters: Object.assign(/* @__PURE__ */ Object.create(null), { - bindings(bindings) { - return bindings; - }, - level(label, number4) { - return { level: number4 }; - } - }), - hooks: { - logMethod: void 0, - streamWrite: void 0 - }, - timestamp: epochTime, - name: void 0, - redact: null, - customLevels: null, - useOnlyCustomLevels: false, - depthLimit: 5, - edgeLimit: 100 - }; - var normalize2 = createArgsNormalizer(defaultOptions2); - var serializers2 = Object.assign(/* @__PURE__ */ Object.create(null), stdSerializers); - function pino2(...args) { - const instance = {}; - const { opts, stream } = normalize2(instance, caller(), ...args); - if (opts.level && typeof opts.level === "string" && DEFAULT_LEVELS[opts.level.toLowerCase()] !== void 0) opts.level = opts.level.toLowerCase(); - const { - redact, - crlf, - serializers: serializers3, - timestamp: timestamp2, - messageKey, - errorKey, - nestedKey, - base, - name, - level, - customLevels, - levelComparison, - mixin, - mixinMergeStrategy, - useOnlyCustomLevels, - formatters, - hooks, - depthLimit, - edgeLimit, - onChild, - msgPrefix - } = opts; - const stringifySafe = configure({ - maximumDepth: depthLimit, - maximumBreadth: edgeLimit - }); - const allFormatters = buildFormatters( - formatters.level, - formatters.bindings, - formatters.log - ); - const stringifyFn = stringify2.bind({ - [stringifySafeSym]: stringifySafe - }); - const stringifiers = redact ? redaction(redact, stringifyFn) : {}; - const formatOpts = redact ? { stringify: stringifiers[redactFmtSym] } : { stringify: stringifyFn }; - const end = "}" + (crlf ? "\r\n" : "\n"); - const coreChindings = asChindings.bind(null, { - [chindingsSym]: "", - [serializersSym]: serializers3, - [stringifiersSym]: stringifiers, - [stringifySym]: stringify2, - [stringifySafeSym]: stringifySafe, - [formattersSym]: allFormatters - }); - let chindings = ""; - if (base !== null) { - if (name === void 0) { - chindings = coreChindings(base); - } else { - chindings = coreChindings(Object.assign({}, base, { name })); - } - } - const time6 = timestamp2 instanceof Function ? timestamp2 : timestamp2 ? epochTime : nullTime; - const timeSliceIndex = time6().indexOf(":") + 1; - if (useOnlyCustomLevels && !customLevels) throw Error("customLevels is required if useOnlyCustomLevels is set true"); - if (mixin && typeof mixin !== "function") throw Error(`Unknown mixin type "${typeof mixin}" - expected "function"`); - if (msgPrefix && typeof msgPrefix !== "string") throw Error(`Unknown msgPrefix type "${typeof msgPrefix}" - expected "string"`); - assertDefaultLevelFound(level, customLevels, useOnlyCustomLevels); - const levels2 = mappings(customLevels, useOnlyCustomLevels); - if (typeof stream.emit === "function") { - stream.emit("message", { code: "PINO_CONFIG", config: { levels: levels2, messageKey, errorKey } }); - } - assertLevelComparison(levelComparison); - const levelCompFunc = genLevelComparison(levelComparison); - Object.assign(instance, { - levels: levels2, - [levelCompSym]: levelCompFunc, - [useOnlyCustomLevelsSym]: useOnlyCustomLevels, - [streamSym]: stream, - [timeSym]: time6, - [timeSliceIndexSym]: timeSliceIndex, - [stringifySym]: stringify2, - [stringifySafeSym]: stringifySafe, - [stringifiersSym]: stringifiers, - [endSym]: end, - [formatOptsSym]: formatOpts, - [messageKeySym]: messageKey, - [errorKeySym]: errorKey, - [nestedKeySym]: nestedKey, - // protect against injection - [nestedKeyStrSym]: nestedKey ? `,${JSON.stringify(nestedKey)}:{` : "", - [serializersSym]: serializers3, - [mixinSym]: mixin, - [mixinMergeStrategySym]: mixinMergeStrategy, - [chindingsSym]: chindings, - [formattersSym]: allFormatters, - [hooksSym]: hooks, - silent: noop5, - onChild, - [msgPrefixSym]: msgPrefix - }); - Object.setPrototypeOf(instance, proto()); - genLsCache(instance); - instance[setLevelSym](level); - return instance; - } - module.exports = pino2; - module.exports.destination = (dest = process.stdout.fd) => { - if (typeof dest === "object") { - dest.dest = normalizeDestFileDescriptor(dest.dest || process.stdout.fd); - return buildSafeSonicBoom(dest); - } else { - return buildSafeSonicBoom({ dest: normalizeDestFileDescriptor(dest), minLength: 0 }); - } - }; - module.exports.transport = require_transport(); - module.exports.multistream = require_multistream(); - module.exports.levels = mappings(); - module.exports.stdSerializers = serializers2; - module.exports.stdTimeFunctions = Object.assign({}, time5); - module.exports.symbols = symbols; - module.exports.version = version3; - module.exports.default = pino2; - module.exports.pino = pino2; - } -}); - -// node_modules/.pnpm/get-caller-file@2.0.5/node_modules/get-caller-file/index.js -var require_get_caller_file = __commonJS({ - "node_modules/.pnpm/get-caller-file@2.0.5/node_modules/get-caller-file/index.js"(exports, module) { - "use strict"; - module.exports = function getCallerFile(position) { - if (position === void 0) { - position = 2; - } - if (position >= Error.stackTraceLimit) { - throw new TypeError("getCallerFile(position) requires position be less then Error.stackTraceLimit but position was: `" + position + "` and Error.stackTraceLimit was: `" + Error.stackTraceLimit + "`"); - } - var oldPrepareStackTrace = Error.prepareStackTrace; - Error.prepareStackTrace = function(_, stack2) { - return stack2; - }; - var stack = new Error().stack; - Error.prepareStackTrace = oldPrepareStackTrace; - if (stack !== null && typeof stack === "object") { - return stack[position] ? stack[position].getFileName() : void 0; - } - }; - } -}); - -// node_modules/.pnpm/pino-http@10.5.0/node_modules/pino-http/logger.js -var require_logger = __commonJS({ - "node_modules/.pnpm/pino-http@10.5.0/node_modules/pino-http/logger.js"(exports, module) { - "use strict"; - var { pino: pino2, symbols: { stringifySym, chindingsSym } } = require_pino(); - var serializers2 = require_pino_std_serializers(); - var getCallerFile = require_get_caller_file(); - var startTime = /* @__PURE__ */ Symbol("startTime"); - var reqObject = /* @__PURE__ */ Symbol("reqObject"); - function pinoLogger(opts, stream) { - if (opts && opts._writableState) { - stream = opts; - opts = null; - } - opts = Object.assign({}, opts); - opts.customAttributeKeys = opts.customAttributeKeys || {}; - const reqKey = opts.customAttributeKeys.req || "req"; - const resKey = opts.customAttributeKeys.res || "res"; - const errKey = opts.customAttributeKeys.err || "err"; - const requestIdKey = opts.customAttributeKeys.reqId || "reqId"; - const responseTimeKey = opts.customAttributeKeys.responseTime || "responseTime"; - delete opts.customAttributeKeys; - const customProps = opts.customProps || void 0; - opts.wrapSerializers = "wrapSerializers" in opts ? opts.wrapSerializers : true; - if (opts.wrapSerializers) { - opts.serializers = Object.assign({}, opts.serializers); - const requestSerializer = opts.serializers[reqKey] || opts.serializers.req || serializers2.req; - const responseSerializer = opts.serializers[resKey] || opts.serializers.res || serializers2.res; - const errorSerializer = opts.serializers[errKey] || opts.serializers.err || serializers2.err; - opts.serializers[reqKey] = serializers2.wrapRequestSerializer(requestSerializer); - opts.serializers[resKey] = serializers2.wrapResponseSerializer(responseSerializer); - opts.serializers[errKey] = serializers2.wrapErrorSerializer(errorSerializer); - } - delete opts.wrapSerializers; - if (opts.useLevel && opts.customLogLevel) { - throw new Error("You can't pass 'useLevel' and 'customLogLevel' together"); - } - function getValidLogLevel(level, defaultValue = "info") { - if (level && typeof level === "string") { - const logLevel = level.trim(); - if (validLogLevels.includes(logLevel) === true) { - return logLevel; - } - } - return defaultValue; - } - function getLogLevelFromCustomLogLevel(customLogLevel2, useLevel2, res, err, req) { - return customLogLevel2 ? getValidLogLevel(customLogLevel2(req, res, err), useLevel2) : useLevel2; - } - const customLogLevel = opts.customLogLevel; - delete opts.customLogLevel; - const theStream = opts.stream || stream; - delete opts.stream; - const autoLogging = opts.autoLogging !== false; - const autoLoggingIgnore = opts.autoLogging && opts.autoLogging.ignore ? opts.autoLogging.ignore : null; - delete opts.autoLogging; - const onRequestReceivedObject = getFunctionOrDefault(opts.customReceivedObject, void 0); - const receivedMessage = getFunctionOrDefault(opts.customReceivedMessage, void 0); - const onRequestSuccessObject = getFunctionOrDefault(opts.customSuccessObject, defaultSuccessfulRequestObjectProvider); - const successMessage = getFunctionOrDefault(opts.customSuccessMessage, defaultSuccessfulRequestMessageProvider); - const onRequestErrorObject = getFunctionOrDefault(opts.customErrorObject, defaultFailedRequestObjectProvider); - const errorMessage = getFunctionOrDefault(opts.customErrorMessage, defaultFailedRequestMessageProvider); - delete opts.customSuccessfulMessage; - delete opts.customErroredMessage; - const quietReqLogger = !!opts.quietReqLogger; - const quietResLogger = !!opts.quietResLogger; - const logger4 = wrapChild(opts, theStream); - const validLogLevels = Object.keys(logger4.levels.values).concat("silent"); - const useLevel = getValidLogLevel(opts.useLevel); - delete opts.useLevel; - const genReqId = reqIdGenFactory(opts.genReqId); - const result = (req, res, next) => { - return loggingMiddleware(logger4, req, res, next); - }; - result.logger = logger4; - return result; - function onResFinished(res, logger5, err) { - let log2 = logger5; - const responseTime = Date.now() - res[startTime]; - const req = res[reqObject]; - const level = getLogLevelFromCustomLogLevel(customLogLevel, useLevel, res, err, req); - if (level === "silent") { - return; - } - const customPropBindings = typeof customProps === "function" ? customProps(req, res) : customProps; - if (customPropBindings) { - const customPropBindingStr = logger5[stringifySym](customPropBindings).replace(/[{}]/g, ""); - const customPropBindingsStr = logger5[chindingsSym]; - if (!customPropBindingsStr.includes(customPropBindingStr)) { - log2 = logger5.child(customPropBindings); - } - } - if (err || res.err || res.statusCode >= 500) { - const error50 = err || res.err || new Error("failed with status code " + res.statusCode); - log2[level]( - onRequestErrorObject(req, res, error50, { - [resKey]: res, - [errKey]: error50, - [responseTimeKey]: responseTime - }), - errorMessage(req, res, error50, responseTime) - ); - return; - } - log2[level]( - onRequestSuccessObject(req, res, { - [resKey]: res, - [responseTimeKey]: responseTime - }), - successMessage(req, res, responseTime) - ); - } - function loggingMiddleware(logger5, req, res, next) { - let shouldLogSuccess = true; - req.id = req.id || genReqId(req, res); - const log2 = quietReqLogger ? logger5.child({ [requestIdKey]: req.id }) : logger5; - let fullReqLogger = log2.child({ [reqKey]: req }); - const customPropBindings = typeof customProps === "function" ? customProps(req, res) : customProps; - if (customPropBindings) { - fullReqLogger = fullReqLogger.child(customPropBindings); - } - const responseLogger = quietResLogger ? log2 : fullReqLogger; - const requestLogger = quietReqLogger ? log2 : fullReqLogger; - if (!res.log) { - res.log = responseLogger; - } - if (Array.isArray(res.allLogs) === false) { - res.allLogs = []; - } - res.allLogs.push(responseLogger); - if (!req.log) { - req.log = requestLogger; - } - if (!req.allLogs) { - req.allLogs = []; - } - req.allLogs.push(requestLogger); - res[startTime] = res[startTime] || Date.now(); - res[reqObject] = req; - const onResponseComplete = (err) => { - res.removeListener("close", onResponseComplete); - res.removeListener("finish", onResponseComplete); - res.removeListener("error", onResponseComplete); - return onResFinished(res, responseLogger, err); - }; - if (autoLogging) { - if (autoLoggingIgnore !== null && shouldLogSuccess === true) { - const isIgnored = autoLoggingIgnore(req); - shouldLogSuccess = !isIgnored; - } - if (shouldLogSuccess) { - const shouldLogReceived = receivedMessage !== void 0 || onRequestReceivedObject !== void 0; - if (shouldLogReceived) { - const level = getLogLevelFromCustomLogLevel(customLogLevel, useLevel, res, void 0, req); - const receivedObjectResult = onRequestReceivedObject !== void 0 ? onRequestReceivedObject(req, res, void 0) : {}; - const receivedStringResult = receivedMessage !== void 0 ? receivedMessage(req, res) : void 0; - requestLogger[level](receivedObjectResult, receivedStringResult); - } - res.on("close", onResponseComplete); - res.on("finish", onResponseComplete); - } - res.on("error", onResponseComplete); - } - if (next) { - next(); - } - } - } - function wrapChild(opts, stream) { - const prevLogger = opts.logger; - const prevGenReqId = opts.genReqId; - let logger4 = null; - if (prevLogger) { - opts.logger = void 0; - opts.genReqId = void 0; - logger4 = prevLogger.child({}, opts); - opts.logger = prevLogger; - opts.genReqId = prevGenReqId; - } else { - if (opts.transport && !opts.transport.caller) { - opts.transport.caller = getCallerFile(); - } - logger4 = pino2(opts, stream); - } - return logger4; - } - function reqIdGenFactory(func) { - if (typeof func === "function") return func; - const maxInt = 2147483647; - let nextReqId = 0; - return function genReqId(req, res) { - return req.id || (nextReqId = nextReqId + 1 & maxInt); - }; - } - function getFunctionOrDefault(value, defaultValue) { - if (value && typeof value === "function") { - return value; - } - return defaultValue; - } - function defaultSuccessfulRequestObjectProvider(req, res, successObject) { - return successObject; - } - function defaultFailedRequestObjectProvider(req, res, error50, errorObject) { - return errorObject; - } - function defaultFailedRequestMessageProvider() { - return "request errored"; - } - function defaultSuccessfulRequestMessageProvider(req, res) { - return !req.readableAborted && res.writableEnded ? "request completed" : "request aborted"; - } - module.exports = pinoLogger; - module.exports.stdSerializers = { - err: serializers2.err, - req: serializers2.req, - res: serializers2.res - }; - module.exports.startTime = startTime; - module.exports.default = pinoLogger; - module.exports.pinoHttp = pinoLogger; - } -}); - -// node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/constants.js -var require_constants2 = __commonJS({ - "node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/constants.js"(exports, module) { - "use strict"; - var BINARY_TYPES = ["nodebuffer", "arraybuffer", "fragments"]; - var hasBlob = typeof Blob !== "undefined"; - if (hasBlob) BINARY_TYPES.push("blob"); - module.exports = { - BINARY_TYPES, - CLOSE_TIMEOUT: 3e4, - EMPTY_BUFFER: Buffer.alloc(0), - GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11", - hasBlob, - kForOnEventAttribute: /* @__PURE__ */ Symbol("kIsForOnEventAttribute"), - kListener: /* @__PURE__ */ Symbol("kListener"), - kStatusCode: /* @__PURE__ */ Symbol("status-code"), - kWebSocket: /* @__PURE__ */ Symbol("websocket"), - NOOP: () => { - } - }; - } -}); - -// node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/buffer-util.js -var require_buffer_util = __commonJS({ - "node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/buffer-util.js"(exports, module) { - "use strict"; - var { EMPTY_BUFFER: EMPTY_BUFFER2 } = require_constants2(); - var FastBuffer = Buffer[Symbol.species]; - function concat2(list2, totalLength) { - if (list2.length === 0) return EMPTY_BUFFER2; - if (list2.length === 1) return list2[0]; - const target = Buffer.allocUnsafe(totalLength); - let offset = 0; - for (let i5 = 0; i5 < list2.length; i5++) { - const buf = list2[i5]; - target.set(buf, offset); - offset += buf.length; - } - if (offset < totalLength) { - return new FastBuffer(target.buffer, target.byteOffset, offset); - } - return target; - } - function _mask(source, mask, output, offset, length) { - for (let i5 = 0; i5 < length; i5++) { - output[offset + i5] = source[i5] ^ mask[i5 & 3]; - } - } - function _unmask(buffer2, mask) { - for (let i5 = 0; i5 < buffer2.length; i5++) { - buffer2[i5] ^= mask[i5 & 3]; - } - } - function toArrayBuffer(buf) { - if (buf.length === buf.buffer.byteLength) { - return buf.buffer; - } - return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length); - } - function toBuffer(data2) { - toBuffer.readOnly = true; - if (Buffer.isBuffer(data2)) return data2; - let buf; - if (data2 instanceof ArrayBuffer) { - buf = new FastBuffer(data2); - } else if (ArrayBuffer.isView(data2)) { - buf = new FastBuffer(data2.buffer, data2.byteOffset, data2.byteLength); - } else { - buf = Buffer.from(data2); - toBuffer.readOnly = false; - } - return buf; - } - module.exports = { - concat: concat2, - mask: _mask, - toArrayBuffer, - toBuffer, - unmask: _unmask - }; - if (!process.env.WS_NO_BUFFER_UTIL) { - try { - const bufferUtil = __require("bufferutil"); - module.exports.mask = function(source, mask, output, offset, length) { - if (length < 48) _mask(source, mask, output, offset, length); - else bufferUtil.mask(source, mask, output, offset, length); - }; - module.exports.unmask = function(buffer2, mask) { - if (buffer2.length < 32) _unmask(buffer2, mask); - else bufferUtil.unmask(buffer2, mask); - }; - } catch (e5) { - } - } - } -}); - -// node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/limiter.js -var require_limiter = __commonJS({ - "node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/limiter.js"(exports, module) { - "use strict"; - var kDone = /* @__PURE__ */ Symbol("kDone"); - var kRun = /* @__PURE__ */ Symbol("kRun"); - var Limiter = class { - /** - * Creates a new `Limiter`. - * - * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed - * to run concurrently - */ - constructor(concurrency) { - this[kDone] = () => { - this.pending--; - this[kRun](); - }; - this.concurrency = concurrency || Infinity; - this.jobs = []; - this.pending = 0; - } - /** - * Adds a job to the queue. - * - * @param {Function} job The job to run - * @public - */ - add(job) { - this.jobs.push(job); - this[kRun](); - } - /** - * Removes a job from the queue and runs it if possible. - * - * @private - */ - [kRun]() { - if (this.pending === this.concurrency) return; - if (this.jobs.length) { - const job = this.jobs.shift(); - this.pending++; - job(this[kDone]); - } - } - }; - module.exports = Limiter; - } -}); - -// node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/permessage-deflate.js -var require_permessage_deflate = __commonJS({ - "node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/permessage-deflate.js"(exports, module) { - "use strict"; - var zlib = __require("zlib"); - var bufferUtil = require_buffer_util(); - var Limiter = require_limiter(); - var { kStatusCode } = require_constants2(); - var FastBuffer = Buffer[Symbol.species]; - var TRAILER = Buffer.from([0, 0, 255, 255]); - var kPerMessageDeflate = /* @__PURE__ */ Symbol("permessage-deflate"); - var kTotalLength = /* @__PURE__ */ Symbol("total-length"); - var kCallback = /* @__PURE__ */ Symbol("callback"); - var kBuffers = /* @__PURE__ */ Symbol("buffers"); - var kError = /* @__PURE__ */ Symbol("error"); - var zlibLimiter; - var PerMessageDeflate2 = class { - /** - * Creates a PerMessageDeflate instance. - * - * @param {Object} [options] Configuration options - * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support - * for, or request, a custom client window size - * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/ - * acknowledge disabling of client context takeover - * @param {Number} [options.concurrencyLimit=10] The number of concurrent - * calls to zlib - * @param {Boolean} [options.isServer=false] Create the instance in either - * server or client mode - * @param {Number} [options.maxPayload=0] The maximum allowed message length - * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the - * use of a custom server window size - * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept - * disabling of server context takeover - * @param {Number} [options.threshold=1024] Size (in bytes) below which - * messages should not be compressed if context takeover is disabled - * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on - * deflate - * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on - * inflate - */ - constructor(options) { - this._options = options || {}; - this._threshold = this._options.threshold !== void 0 ? this._options.threshold : 1024; - this._maxPayload = this._options.maxPayload | 0; - this._isServer = !!this._options.isServer; - this._deflate = null; - this._inflate = null; - this.params = null; - if (!zlibLimiter) { - const concurrency = this._options.concurrencyLimit !== void 0 ? this._options.concurrencyLimit : 10; - zlibLimiter = new Limiter(concurrency); - } - } - /** - * @type {String} - */ - static get extensionName() { - return "permessage-deflate"; - } - /** - * Create an extension negotiation offer. - * - * @return {Object} Extension parameters - * @public - */ - offer() { - const params = {}; - if (this._options.serverNoContextTakeover) { - params.server_no_context_takeover = true; - } - if (this._options.clientNoContextTakeover) { - params.client_no_context_takeover = true; - } - if (this._options.serverMaxWindowBits) { - params.server_max_window_bits = this._options.serverMaxWindowBits; - } - if (this._options.clientMaxWindowBits) { - params.client_max_window_bits = this._options.clientMaxWindowBits; - } else if (this._options.clientMaxWindowBits == null) { - params.client_max_window_bits = true; - } - return params; - } - /** - * Accept an extension negotiation offer/response. - * - * @param {Array} configurations The extension negotiation offers/reponse - * @return {Object} Accepted configuration - * @public - */ - accept(configurations) { - configurations = this.normalizeParams(configurations); - this.params = this._isServer ? this.acceptAsServer(configurations) : this.acceptAsClient(configurations); - return this.params; - } - /** - * Releases all resources used by the extension. - * - * @public - */ - cleanup() { - if (this._inflate) { - this._inflate.close(); - this._inflate = null; - } - if (this._deflate) { - const callback = this._deflate[kCallback]; - this._deflate.close(); - this._deflate = null; - if (callback) { - callback( - new Error( - "The deflate stream was closed while data was being processed" - ) - ); - } - } - } - /** - * Accept an extension negotiation offer. - * - * @param {Array} offers The extension negotiation offers - * @return {Object} Accepted configuration - * @private - */ - acceptAsServer(offers) { - const opts = this._options; - const accepted = offers.find((params) => { - if (opts.serverNoContextTakeover === false && params.server_no_context_takeover || params.server_max_window_bits && (opts.serverMaxWindowBits === false || typeof opts.serverMaxWindowBits === "number" && opts.serverMaxWindowBits > params.server_max_window_bits) || typeof opts.clientMaxWindowBits === "number" && !params.client_max_window_bits) { - return false; - } - return true; - }); - if (!accepted) { - throw new Error("None of the extension offers can be accepted"); - } - if (opts.serverNoContextTakeover) { - accepted.server_no_context_takeover = true; - } - if (opts.clientNoContextTakeover) { - accepted.client_no_context_takeover = true; - } - if (typeof opts.serverMaxWindowBits === "number") { - accepted.server_max_window_bits = opts.serverMaxWindowBits; - } - if (typeof opts.clientMaxWindowBits === "number") { - accepted.client_max_window_bits = opts.clientMaxWindowBits; - } else if (accepted.client_max_window_bits === true || opts.clientMaxWindowBits === false) { - delete accepted.client_max_window_bits; - } - return accepted; - } - /** - * Accept the extension negotiation response. - * - * @param {Array} response The extension negotiation response - * @return {Object} Accepted configuration - * @private - */ - acceptAsClient(response) { - const params = response[0]; - if (this._options.clientNoContextTakeover === false && params.client_no_context_takeover) { - throw new Error('Unexpected parameter "client_no_context_takeover"'); - } - if (!params.client_max_window_bits) { - if (typeof this._options.clientMaxWindowBits === "number") { - params.client_max_window_bits = this._options.clientMaxWindowBits; - } - } else if (this._options.clientMaxWindowBits === false || typeof this._options.clientMaxWindowBits === "number" && params.client_max_window_bits > this._options.clientMaxWindowBits) { - throw new Error( - 'Unexpected or invalid parameter "client_max_window_bits"' - ); - } - return params; - } - /** - * Normalize parameters. - * - * @param {Array} configurations The extension negotiation offers/reponse - * @return {Array} The offers/response with normalized parameters - * @private - */ - normalizeParams(configurations) { - configurations.forEach((params) => { - Object.keys(params).forEach((key) => { - let value = params[key]; - if (value.length > 1) { - throw new Error(`Parameter "${key}" must have only a single value`); - } - value = value[0]; - if (key === "client_max_window_bits") { - if (value !== true) { - const num = +value; - if (!Number.isInteger(num) || num < 8 || num > 15) { - throw new TypeError( - `Invalid value for parameter "${key}": ${value}` - ); - } - value = num; - } else if (!this._isServer) { - throw new TypeError( - `Invalid value for parameter "${key}": ${value}` - ); - } - } else if (key === "server_max_window_bits") { - const num = +value; - if (!Number.isInteger(num) || num < 8 || num > 15) { - throw new TypeError( - `Invalid value for parameter "${key}": ${value}` - ); - } - value = num; - } else if (key === "client_no_context_takeover" || key === "server_no_context_takeover") { - if (value !== true) { - throw new TypeError( - `Invalid value for parameter "${key}": ${value}` - ); - } - } else { - throw new Error(`Unknown parameter "${key}"`); - } - params[key] = value; - }); - }); - return configurations; - } - /** - * Decompress data. Concurrency limited. - * - * @param {Buffer} data Compressed data - * @param {Boolean} fin Specifies whether or not this is the last fragment - * @param {Function} callback Callback - * @public - */ - decompress(data2, fin, callback) { - zlibLimiter.add((done) => { - this._decompress(data2, fin, (err, result) => { - done(); - callback(err, result); - }); - }); - } - /** - * Compress data. Concurrency limited. - * - * @param {(Buffer|String)} data Data to compress - * @param {Boolean} fin Specifies whether or not this is the last fragment - * @param {Function} callback Callback - * @public - */ - compress(data2, fin, callback) { - zlibLimiter.add((done) => { - this._compress(data2, fin, (err, result) => { - done(); - callback(err, result); - }); - }); - } - /** - * Decompress data. - * - * @param {Buffer} data Compressed data - * @param {Boolean} fin Specifies whether or not this is the last fragment - * @param {Function} callback Callback - * @private - */ - _decompress(data2, fin, callback) { - const endpoint = this._isServer ? "client" : "server"; - if (!this._inflate) { - const key = `${endpoint}_max_window_bits`; - const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key]; - this._inflate = zlib.createInflateRaw({ - ...this._options.zlibInflateOptions, - windowBits - }); - this._inflate[kPerMessageDeflate] = this; - this._inflate[kTotalLength] = 0; - this._inflate[kBuffers] = []; - this._inflate.on("error", inflateOnError); - this._inflate.on("data", inflateOnData); - } - this._inflate[kCallback] = callback; - this._inflate.write(data2); - if (fin) this._inflate.write(TRAILER); - this._inflate.flush(() => { - const err = this._inflate[kError]; - if (err) { - this._inflate.close(); - this._inflate = null; - callback(err); - return; - } - const data3 = bufferUtil.concat( - this._inflate[kBuffers], - this._inflate[kTotalLength] - ); - if (this._inflate._readableState.endEmitted) { - this._inflate.close(); - this._inflate = null; - } else { - this._inflate[kTotalLength] = 0; - this._inflate[kBuffers] = []; - if (fin && this.params[`${endpoint}_no_context_takeover`]) { - this._inflate.reset(); - } - } - callback(null, data3); - }); - } - /** - * Compress data. - * - * @param {(Buffer|String)} data Data to compress - * @param {Boolean} fin Specifies whether or not this is the last fragment - * @param {Function} callback Callback - * @private - */ - _compress(data2, fin, callback) { - const endpoint = this._isServer ? "server" : "client"; - if (!this._deflate) { - const key = `${endpoint}_max_window_bits`; - const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key]; - this._deflate = zlib.createDeflateRaw({ - ...this._options.zlibDeflateOptions, - windowBits - }); - this._deflate[kTotalLength] = 0; - this._deflate[kBuffers] = []; - this._deflate.on("data", deflateOnData); - } - this._deflate[kCallback] = callback; - this._deflate.write(data2); - this._deflate.flush(zlib.Z_SYNC_FLUSH, () => { - if (!this._deflate) { - return; - } - let data3 = bufferUtil.concat( - this._deflate[kBuffers], - this._deflate[kTotalLength] - ); - if (fin) { - data3 = new FastBuffer(data3.buffer, data3.byteOffset, data3.length - 4); - } - this._deflate[kCallback] = null; - this._deflate[kTotalLength] = 0; - this._deflate[kBuffers] = []; - if (fin && this.params[`${endpoint}_no_context_takeover`]) { - this._deflate.reset(); - } - callback(null, data3); - }); - } - }; - module.exports = PerMessageDeflate2; - function deflateOnData(chunk) { - this[kBuffers].push(chunk); - this[kTotalLength] += chunk.length; - } - function inflateOnData(chunk) { - this[kTotalLength] += chunk.length; - if (this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload) { - this[kBuffers].push(chunk); - return; - } - this[kError] = new RangeError("Max payload size exceeded"); - this[kError].code = "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"; - this[kError][kStatusCode] = 1009; - this.removeListener("data", inflateOnData); - this.reset(); - } - function inflateOnError(err) { - this[kPerMessageDeflate]._inflate = null; - if (this[kError]) { - this[kCallback](this[kError]); - return; - } - err[kStatusCode] = 1007; - this[kCallback](err); - } - } -}); - -// node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/validation.js -var require_validation = __commonJS({ - "node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/validation.js"(exports, module) { - "use strict"; - var { isUtf8 } = __require("buffer"); - var { hasBlob } = require_constants2(); - var tokenChars = [ - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - // 0 - 15 - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - // 16 - 31 - 0, - 1, - 0, - 1, - 1, - 1, - 1, - 1, - 0, - 0, - 1, - 1, - 0, - 1, - 1, - 0, - // 32 - 47 - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 0, - 0, - 0, - 0, - 0, - 0, - // 48 - 63 - 0, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - // 64 - 79 - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 0, - 0, - 0, - 1, - 1, - // 80 - 95 - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - // 96 - 111 - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 0, - 1, - 0, - 1, - 0 - // 112 - 127 - ]; - function isValidStatusCode(code) { - return code >= 1e3 && code <= 1014 && code !== 1004 && code !== 1005 && code !== 1006 || code >= 3e3 && code <= 4999; - } - function _isValidUTF8(buf) { - const len = buf.length; - let i5 = 0; - while (i5 < len) { - if ((buf[i5] & 128) === 0) { - i5++; - } else if ((buf[i5] & 224) === 192) { - if (i5 + 1 === len || (buf[i5 + 1] & 192) !== 128 || (buf[i5] & 254) === 192) { - return false; - } - i5 += 2; - } else if ((buf[i5] & 240) === 224) { - if (i5 + 2 >= len || (buf[i5 + 1] & 192) !== 128 || (buf[i5 + 2] & 192) !== 128 || buf[i5] === 224 && (buf[i5 + 1] & 224) === 128 || // Overlong - buf[i5] === 237 && (buf[i5 + 1] & 224) === 160) { - return false; - } - i5 += 3; - } else if ((buf[i5] & 248) === 240) { - if (i5 + 3 >= len || (buf[i5 + 1] & 192) !== 128 || (buf[i5 + 2] & 192) !== 128 || (buf[i5 + 3] & 192) !== 128 || buf[i5] === 240 && (buf[i5 + 1] & 240) === 128 || // Overlong - buf[i5] === 244 && buf[i5 + 1] > 143 || buf[i5] > 244) { - return false; - } - i5 += 4; - } else { - return false; - } - } - return true; - } - function isBlob(value) { - return hasBlob && typeof value === "object" && typeof value.arrayBuffer === "function" && typeof value.type === "string" && typeof value.stream === "function" && (value[Symbol.toStringTag] === "Blob" || value[Symbol.toStringTag] === "File"); - } - module.exports = { - isBlob, - isValidStatusCode, - isValidUTF8: _isValidUTF8, - tokenChars - }; - if (isUtf8) { - module.exports.isValidUTF8 = function(buf) { - return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf); - }; - } else if (!process.env.WS_NO_UTF_8_VALIDATE) { - try { - const isValidUTF8 = __require("utf-8-validate"); - module.exports.isValidUTF8 = function(buf) { - return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf); - }; - } catch (e5) { - } - } - } -}); - -// node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/receiver.js -var require_receiver = __commonJS({ - "node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/receiver.js"(exports, module) { - "use strict"; - var { Writable } = __require("stream"); - var PerMessageDeflate2 = require_permessage_deflate(); - var { - BINARY_TYPES, - EMPTY_BUFFER: EMPTY_BUFFER2, - kStatusCode, - kWebSocket - } = require_constants2(); - var { concat: concat2, toArrayBuffer, unmask } = require_buffer_util(); - var { isValidStatusCode, isValidUTF8 } = require_validation(); - var FastBuffer = Buffer[Symbol.species]; - var GET_INFO = 0; - var GET_PAYLOAD_LENGTH_16 = 1; - var GET_PAYLOAD_LENGTH_64 = 2; - var GET_MASK = 3; - var GET_DATA = 4; - var INFLATING = 5; - var DEFER_EVENT = 6; - var Receiver2 = class extends Writable { - /** - * Creates a Receiver instance. - * - * @param {Object} [options] Options object - * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether - * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted - * multiple times in the same tick - * @param {String} [options.binaryType=nodebuffer] The type for binary data - * @param {Object} [options.extensions] An object containing the negotiated - * extensions - * @param {Boolean} [options.isServer=false] Specifies whether to operate in - * client or server mode - * @param {Number} [options.maxPayload=0] The maximum allowed message length - * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or - * not to skip UTF-8 validation for text and close messages - */ - constructor(options = {}) { - super(); - this._allowSynchronousEvents = options.allowSynchronousEvents !== void 0 ? options.allowSynchronousEvents : true; - this._binaryType = options.binaryType || BINARY_TYPES[0]; - this._extensions = options.extensions || {}; - this._isServer = !!options.isServer; - this._maxPayload = options.maxPayload | 0; - this._skipUTF8Validation = !!options.skipUTF8Validation; - this[kWebSocket] = void 0; - this._bufferedBytes = 0; - this._buffers = []; - this._compressed = false; - this._payloadLength = 0; - this._mask = void 0; - this._fragmented = 0; - this._masked = false; - this._fin = false; - this._opcode = 0; - this._totalPayloadLength = 0; - this._messageLength = 0; - this._fragments = []; - this._errored = false; - this._loop = false; - this._state = GET_INFO; - } - /** - * Implements `Writable.prototype._write()`. - * - * @param {Buffer} chunk The chunk of data to write - * @param {String} encoding The character encoding of `chunk` - * @param {Function} cb Callback - * @private - */ - _write(chunk, encoding, cb) { - if (this._opcode === 8 && this._state == GET_INFO) return cb(); - this._bufferedBytes += chunk.length; - this._buffers.push(chunk); - this.startLoop(cb); - } - /** - * Consumes `n` bytes from the buffered data. - * - * @param {Number} n The number of bytes to consume - * @return {Buffer} The consumed bytes - * @private - */ - consume(n5) { - this._bufferedBytes -= n5; - if (n5 === this._buffers[0].length) return this._buffers.shift(); - if (n5 < this._buffers[0].length) { - const buf = this._buffers[0]; - this._buffers[0] = new FastBuffer( - buf.buffer, - buf.byteOffset + n5, - buf.length - n5 - ); - return new FastBuffer(buf.buffer, buf.byteOffset, n5); - } - const dst = Buffer.allocUnsafe(n5); - do { - const buf = this._buffers[0]; - const offset = dst.length - n5; - if (n5 >= buf.length) { - dst.set(this._buffers.shift(), offset); - } else { - dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n5), offset); - this._buffers[0] = new FastBuffer( - buf.buffer, - buf.byteOffset + n5, - buf.length - n5 - ); - } - n5 -= buf.length; - } while (n5 > 0); - return dst; - } - /** - * Starts the parsing loop. - * - * @param {Function} cb Callback - * @private - */ - startLoop(cb) { - this._loop = true; - do { - switch (this._state) { - case GET_INFO: - this.getInfo(cb); - break; - case GET_PAYLOAD_LENGTH_16: - this.getPayloadLength16(cb); - break; - case GET_PAYLOAD_LENGTH_64: - this.getPayloadLength64(cb); - break; - case GET_MASK: - this.getMask(); - break; - case GET_DATA: - this.getData(cb); - break; - case INFLATING: - case DEFER_EVENT: - this._loop = false; - return; - } - } while (this._loop); - if (!this._errored) cb(); - } - /** - * Reads the first two bytes of a frame. - * - * @param {Function} cb Callback - * @private - */ - getInfo(cb) { - if (this._bufferedBytes < 2) { - this._loop = false; - return; - } - const buf = this.consume(2); - if ((buf[0] & 48) !== 0) { - const error50 = this.createError( - RangeError, - "RSV2 and RSV3 must be clear", - true, - 1002, - "WS_ERR_UNEXPECTED_RSV_2_3" - ); - cb(error50); - return; - } - const compressed = (buf[0] & 64) === 64; - if (compressed && !this._extensions[PerMessageDeflate2.extensionName]) { - const error50 = this.createError( - RangeError, - "RSV1 must be clear", - true, - 1002, - "WS_ERR_UNEXPECTED_RSV_1" - ); - cb(error50); - return; - } - this._fin = (buf[0] & 128) === 128; - this._opcode = buf[0] & 15; - this._payloadLength = buf[1] & 127; - if (this._opcode === 0) { - if (compressed) { - const error50 = this.createError( - RangeError, - "RSV1 must be clear", - true, - 1002, - "WS_ERR_UNEXPECTED_RSV_1" - ); - cb(error50); - return; - } - if (!this._fragmented) { - const error50 = this.createError( - RangeError, - "invalid opcode 0", - true, - 1002, - "WS_ERR_INVALID_OPCODE" - ); - cb(error50); - return; - } - this._opcode = this._fragmented; - } else if (this._opcode === 1 || this._opcode === 2) { - if (this._fragmented) { - const error50 = this.createError( - RangeError, - `invalid opcode ${this._opcode}`, - true, - 1002, - "WS_ERR_INVALID_OPCODE" - ); - cb(error50); - return; - } - this._compressed = compressed; - } else if (this._opcode > 7 && this._opcode < 11) { - if (!this._fin) { - const error50 = this.createError( - RangeError, - "FIN must be set", - true, - 1002, - "WS_ERR_EXPECTED_FIN" - ); - cb(error50); - return; - } - if (compressed) { - const error50 = this.createError( - RangeError, - "RSV1 must be clear", - true, - 1002, - "WS_ERR_UNEXPECTED_RSV_1" - ); - cb(error50); - return; - } - if (this._payloadLength > 125 || this._opcode === 8 && this._payloadLength === 1) { - const error50 = this.createError( - RangeError, - `invalid payload length ${this._payloadLength}`, - true, - 1002, - "WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH" - ); - cb(error50); - return; - } - } else { - const error50 = this.createError( - RangeError, - `invalid opcode ${this._opcode}`, - true, - 1002, - "WS_ERR_INVALID_OPCODE" - ); - cb(error50); - return; - } - if (!this._fin && !this._fragmented) this._fragmented = this._opcode; - this._masked = (buf[1] & 128) === 128; - if (this._isServer) { - if (!this._masked) { - const error50 = this.createError( - RangeError, - "MASK must be set", - true, - 1002, - "WS_ERR_EXPECTED_MASK" - ); - cb(error50); - return; - } - } else if (this._masked) { - const error50 = this.createError( - RangeError, - "MASK must be clear", - true, - 1002, - "WS_ERR_UNEXPECTED_MASK" - ); - cb(error50); - return; - } - if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16; - else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64; - else this.haveLength(cb); - } - /** - * Gets extended payload length (7+16). - * - * @param {Function} cb Callback - * @private - */ - getPayloadLength16(cb) { - if (this._bufferedBytes < 2) { - this._loop = false; - return; - } - this._payloadLength = this.consume(2).readUInt16BE(0); - this.haveLength(cb); - } - /** - * Gets extended payload length (7+64). - * - * @param {Function} cb Callback - * @private - */ - getPayloadLength64(cb) { - if (this._bufferedBytes < 8) { - this._loop = false; - return; - } - const buf = this.consume(8); - const num = buf.readUInt32BE(0); - if (num > Math.pow(2, 53 - 32) - 1) { - const error50 = this.createError( - RangeError, - "Unsupported WebSocket frame: payload length > 2^53 - 1", - false, - 1009, - "WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH" - ); - cb(error50); - return; - } - this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4); - this.haveLength(cb); - } - /** - * Payload length has been read. - * - * @param {Function} cb Callback - * @private - */ - haveLength(cb) { - if (this._payloadLength && this._opcode < 8) { - this._totalPayloadLength += this._payloadLength; - if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) { - const error50 = this.createError( - RangeError, - "Max payload size exceeded", - false, - 1009, - "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH" - ); - cb(error50); - return; - } - } - if (this._masked) this._state = GET_MASK; - else this._state = GET_DATA; - } - /** - * Reads mask bytes. - * - * @private - */ - getMask() { - if (this._bufferedBytes < 4) { - this._loop = false; - return; - } - this._mask = this.consume(4); - this._state = GET_DATA; - } - /** - * Reads data bytes. - * - * @param {Function} cb Callback - * @private - */ - getData(cb) { - let data2 = EMPTY_BUFFER2; - if (this._payloadLength) { - if (this._bufferedBytes < this._payloadLength) { - this._loop = false; - return; - } - data2 = this.consume(this._payloadLength); - if (this._masked && (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0) { - unmask(data2, this._mask); - } - } - if (this._opcode > 7) { - this.controlMessage(data2, cb); - return; - } - if (this._compressed) { - this._state = INFLATING; - this.decompress(data2, cb); - return; - } - if (data2.length) { - this._messageLength = this._totalPayloadLength; - this._fragments.push(data2); - } - this.dataMessage(cb); - } - /** - * Decompresses data. - * - * @param {Buffer} data Compressed data - * @param {Function} cb Callback - * @private - */ - decompress(data2, cb) { - const perMessageDeflate = this._extensions[PerMessageDeflate2.extensionName]; - perMessageDeflate.decompress(data2, this._fin, (err, buf) => { - if (err) return cb(err); - if (buf.length) { - this._messageLength += buf.length; - if (this._messageLength > this._maxPayload && this._maxPayload > 0) { - const error50 = this.createError( - RangeError, - "Max payload size exceeded", - false, - 1009, - "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH" - ); - cb(error50); - return; - } - this._fragments.push(buf); - } - this.dataMessage(cb); - if (this._state === GET_INFO) this.startLoop(cb); - }); - } - /** - * Handles a data message. - * - * @param {Function} cb Callback - * @private - */ - dataMessage(cb) { - if (!this._fin) { - this._state = GET_INFO; - return; - } - const messageLength = this._messageLength; - const fragments = this._fragments; - this._totalPayloadLength = 0; - this._messageLength = 0; - this._fragmented = 0; - this._fragments = []; - if (this._opcode === 2) { - let data2; - if (this._binaryType === "nodebuffer") { - data2 = concat2(fragments, messageLength); - } else if (this._binaryType === "arraybuffer") { - data2 = toArrayBuffer(concat2(fragments, messageLength)); - } else if (this._binaryType === "blob") { - data2 = new Blob(fragments); - } else { - data2 = fragments; - } - if (this._allowSynchronousEvents) { - this.emit("message", data2, true); - this._state = GET_INFO; - } else { - this._state = DEFER_EVENT; - setImmediate(() => { - this.emit("message", data2, true); - this._state = GET_INFO; - this.startLoop(cb); - }); - } - } else { - const buf = concat2(fragments, messageLength); - if (!this._skipUTF8Validation && !isValidUTF8(buf)) { - const error50 = this.createError( - Error, - "invalid UTF-8 sequence", - true, - 1007, - "WS_ERR_INVALID_UTF8" - ); - cb(error50); - return; - } - if (this._state === INFLATING || this._allowSynchronousEvents) { - this.emit("message", buf, false); - this._state = GET_INFO; - } else { - this._state = DEFER_EVENT; - setImmediate(() => { - this.emit("message", buf, false); - this._state = GET_INFO; - this.startLoop(cb); - }); - } - } - } - /** - * Handles a control message. - * - * @param {Buffer} data Data to handle - * @return {(Error|RangeError|undefined)} A possible error - * @private - */ - controlMessage(data2, cb) { - if (this._opcode === 8) { - if (data2.length === 0) { - this._loop = false; - this.emit("conclude", 1005, EMPTY_BUFFER2); - this.end(); - } else { - const code = data2.readUInt16BE(0); - if (!isValidStatusCode(code)) { - const error50 = this.createError( - RangeError, - `invalid status code ${code}`, - true, - 1002, - "WS_ERR_INVALID_CLOSE_CODE" - ); - cb(error50); - return; - } - const buf = new FastBuffer( - data2.buffer, - data2.byteOffset + 2, - data2.length - 2 - ); - if (!this._skipUTF8Validation && !isValidUTF8(buf)) { - const error50 = this.createError( - Error, - "invalid UTF-8 sequence", - true, - 1007, - "WS_ERR_INVALID_UTF8" - ); - cb(error50); - return; - } - this._loop = false; - this.emit("conclude", code, buf); - this.end(); - } - this._state = GET_INFO; - return; - } - if (this._allowSynchronousEvents) { - this.emit(this._opcode === 9 ? "ping" : "pong", data2); - this._state = GET_INFO; - } else { - this._state = DEFER_EVENT; - setImmediate(() => { - this.emit(this._opcode === 9 ? "ping" : "pong", data2); - this._state = GET_INFO; - this.startLoop(cb); - }); - } - } - /** - * Builds an error object. - * - * @param {function(new:Error|RangeError)} ErrorCtor The error constructor - * @param {String} message The error message - * @param {Boolean} prefix Specifies whether or not to add a default prefix to - * `message` - * @param {Number} statusCode The status code - * @param {String} errorCode The exposed error code - * @return {(Error|RangeError)} The error - * @private - */ - createError(ErrorCtor, message2, prefix, statusCode, errorCode) { - this._loop = false; - this._errored = true; - const err = new ErrorCtor( - prefix ? `Invalid WebSocket frame: ${message2}` : message2 - ); - Error.captureStackTrace(err, this.createError); - err.code = errorCode; - err[kStatusCode] = statusCode; - return err; - } - }; - module.exports = Receiver2; - } -}); - -// node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/sender.js -var require_sender = __commonJS({ - "node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/sender.js"(exports, module) { - "use strict"; - var { Duplex } = __require("stream"); - var { randomFillSync } = __require("crypto"); - var PerMessageDeflate2 = require_permessage_deflate(); - var { EMPTY_BUFFER: EMPTY_BUFFER2, kWebSocket, NOOP } = require_constants2(); - var { isBlob, isValidStatusCode } = require_validation(); - var { mask: applyMask, toBuffer } = require_buffer_util(); - var kByteLength = /* @__PURE__ */ Symbol("kByteLength"); - var maskBuffer = Buffer.alloc(4); - var RANDOM_POOL_SIZE = 8 * 1024; - var randomPool; - var randomPoolPointer = RANDOM_POOL_SIZE; - var DEFAULT = 0; - var DEFLATING = 1; - var GET_BLOB_DATA = 2; - var Sender2 = class _Sender { - /** - * Creates a Sender instance. - * - * @param {Duplex} socket The connection socket - * @param {Object} [extensions] An object containing the negotiated extensions - * @param {Function} [generateMask] The function used to generate the masking - * key - */ - constructor(socket, extensions, generateMask) { - this._extensions = extensions || {}; - if (generateMask) { - this._generateMask = generateMask; - this._maskBuffer = Buffer.alloc(4); - } - this._socket = socket; - this._firstFragment = true; - this._compress = false; - this._bufferedBytes = 0; - this._queue = []; - this._state = DEFAULT; - this.onerror = NOOP; - this[kWebSocket] = void 0; - } - /** - * Frames a piece of data according to the HyBi WebSocket protocol. - * - * @param {(Buffer|String)} data The data to frame - * @param {Object} options Options object - * @param {Boolean} [options.fin=false] Specifies whether or not to set the - * FIN bit - * @param {Function} [options.generateMask] The function used to generate the - * masking key - * @param {Boolean} [options.mask=false] Specifies whether or not to mask - * `data` - * @param {Buffer} [options.maskBuffer] The buffer used to store the masking - * key - * @param {Number} options.opcode The opcode - * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be - * modified - * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the - * RSV1 bit - * @return {(Buffer|String)[]} The framed data - * @public - */ - static frame(data2, options) { - let mask; - let merge2 = false; - let offset = 2; - let skipMasking = false; - if (options.mask) { - mask = options.maskBuffer || maskBuffer; - if (options.generateMask) { - options.generateMask(mask); - } else { - if (randomPoolPointer === RANDOM_POOL_SIZE) { - if (randomPool === void 0) { - randomPool = Buffer.alloc(RANDOM_POOL_SIZE); - } - randomFillSync(randomPool, 0, RANDOM_POOL_SIZE); - randomPoolPointer = 0; - } - mask[0] = randomPool[randomPoolPointer++]; - mask[1] = randomPool[randomPoolPointer++]; - mask[2] = randomPool[randomPoolPointer++]; - mask[3] = randomPool[randomPoolPointer++]; - } - skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0; - offset = 6; - } - let dataLength; - if (typeof data2 === "string") { - if ((!options.mask || skipMasking) && options[kByteLength] !== void 0) { - dataLength = options[kByteLength]; - } else { - data2 = Buffer.from(data2); - dataLength = data2.length; - } - } else { - dataLength = data2.length; - merge2 = options.mask && options.readOnly && !skipMasking; - } - let payloadLength = dataLength; - if (dataLength >= 65536) { - offset += 8; - payloadLength = 127; - } else if (dataLength > 125) { - offset += 2; - payloadLength = 126; - } - const target = Buffer.allocUnsafe(merge2 ? dataLength + offset : offset); - target[0] = options.fin ? options.opcode | 128 : options.opcode; - if (options.rsv1) target[0] |= 64; - target[1] = payloadLength; - if (payloadLength === 126) { - target.writeUInt16BE(dataLength, 2); - } else if (payloadLength === 127) { - target[2] = target[3] = 0; - target.writeUIntBE(dataLength, 4, 6); - } - if (!options.mask) return [target, data2]; - target[1] |= 128; - target[offset - 4] = mask[0]; - target[offset - 3] = mask[1]; - target[offset - 2] = mask[2]; - target[offset - 1] = mask[3]; - if (skipMasking) return [target, data2]; - if (merge2) { - applyMask(data2, mask, target, offset, dataLength); - return [target]; - } - applyMask(data2, mask, data2, 0, dataLength); - return [target, data2]; - } - /** - * Sends a close message to the other peer. - * - * @param {Number} [code] The status code component of the body - * @param {(String|Buffer)} [data] The message component of the body - * @param {Boolean} [mask=false] Specifies whether or not to mask the message - * @param {Function} [cb] Callback - * @public - */ - close(code, data2, mask, cb) { - let buf; - if (code === void 0) { - buf = EMPTY_BUFFER2; - } else if (typeof code !== "number" || !isValidStatusCode(code)) { - throw new TypeError("First argument must be a valid error code number"); - } else if (data2 === void 0 || !data2.length) { - buf = Buffer.allocUnsafe(2); - buf.writeUInt16BE(code, 0); - } else { - const length = Buffer.byteLength(data2); - if (length > 123) { - throw new RangeError("The message must not be greater than 123 bytes"); - } - buf = Buffer.allocUnsafe(2 + length); - buf.writeUInt16BE(code, 0); - if (typeof data2 === "string") { - buf.write(data2, 2); - } else { - buf.set(data2, 2); - } - } - const options = { - [kByteLength]: buf.length, - fin: true, - generateMask: this._generateMask, - mask, - maskBuffer: this._maskBuffer, - opcode: 8, - readOnly: false, - rsv1: false - }; - if (this._state !== DEFAULT) { - this.enqueue([this.dispatch, buf, false, options, cb]); - } else { - this.sendFrame(_Sender.frame(buf, options), cb); - } - } - /** - * Sends a ping message to the other peer. - * - * @param {*} data The message to send - * @param {Boolean} [mask=false] Specifies whether or not to mask `data` - * @param {Function} [cb] Callback - * @public - */ - ping(data2, mask, cb) { - let byteLength; - let readOnly; - if (typeof data2 === "string") { - byteLength = Buffer.byteLength(data2); - readOnly = false; - } else if (isBlob(data2)) { - byteLength = data2.size; - readOnly = false; - } else { - data2 = toBuffer(data2); - byteLength = data2.length; - readOnly = toBuffer.readOnly; - } - if (byteLength > 125) { - throw new RangeError("The data size must not be greater than 125 bytes"); - } - const options = { - [kByteLength]: byteLength, - fin: true, - generateMask: this._generateMask, - mask, - maskBuffer: this._maskBuffer, - opcode: 9, - readOnly, - rsv1: false - }; - if (isBlob(data2)) { - if (this._state !== DEFAULT) { - this.enqueue([this.getBlobData, data2, false, options, cb]); - } else { - this.getBlobData(data2, false, options, cb); - } - } else if (this._state !== DEFAULT) { - this.enqueue([this.dispatch, data2, false, options, cb]); - } else { - this.sendFrame(_Sender.frame(data2, options), cb); - } - } - /** - * Sends a pong message to the other peer. - * - * @param {*} data The message to send - * @param {Boolean} [mask=false] Specifies whether or not to mask `data` - * @param {Function} [cb] Callback - * @public - */ - pong(data2, mask, cb) { - let byteLength; - let readOnly; - if (typeof data2 === "string") { - byteLength = Buffer.byteLength(data2); - readOnly = false; - } else if (isBlob(data2)) { - byteLength = data2.size; - readOnly = false; - } else { - data2 = toBuffer(data2); - byteLength = data2.length; - readOnly = toBuffer.readOnly; - } - if (byteLength > 125) { - throw new RangeError("The data size must not be greater than 125 bytes"); - } - const options = { - [kByteLength]: byteLength, - fin: true, - generateMask: this._generateMask, - mask, - maskBuffer: this._maskBuffer, - opcode: 10, - readOnly, - rsv1: false - }; - if (isBlob(data2)) { - if (this._state !== DEFAULT) { - this.enqueue([this.getBlobData, data2, false, options, cb]); - } else { - this.getBlobData(data2, false, options, cb); - } - } else if (this._state !== DEFAULT) { - this.enqueue([this.dispatch, data2, false, options, cb]); - } else { - this.sendFrame(_Sender.frame(data2, options), cb); - } - } - /** - * Sends a data message to the other peer. - * - * @param {*} data The message to send - * @param {Object} options Options object - * @param {Boolean} [options.binary=false] Specifies whether `data` is binary - * or text - * @param {Boolean} [options.compress=false] Specifies whether or not to - * compress `data` - * @param {Boolean} [options.fin=false] Specifies whether the fragment is the - * last one - * @param {Boolean} [options.mask=false] Specifies whether or not to mask - * `data` - * @param {Function} [cb] Callback - * @public - */ - send(data2, options, cb) { - const perMessageDeflate = this._extensions[PerMessageDeflate2.extensionName]; - let opcode = options.binary ? 2 : 1; - let rsv1 = options.compress; - let byteLength; - let readOnly; - if (typeof data2 === "string") { - byteLength = Buffer.byteLength(data2); - readOnly = false; - } else if (isBlob(data2)) { - byteLength = data2.size; - readOnly = false; - } else { - data2 = toBuffer(data2); - byteLength = data2.length; - readOnly = toBuffer.readOnly; - } - if (this._firstFragment) { - this._firstFragment = false; - if (rsv1 && perMessageDeflate && perMessageDeflate.params[perMessageDeflate._isServer ? "server_no_context_takeover" : "client_no_context_takeover"]) { - rsv1 = byteLength >= perMessageDeflate._threshold; - } - this._compress = rsv1; - } else { - rsv1 = false; - opcode = 0; - } - if (options.fin) this._firstFragment = true; - const opts = { - [kByteLength]: byteLength, - fin: options.fin, - generateMask: this._generateMask, - mask: options.mask, - maskBuffer: this._maskBuffer, - opcode, - readOnly, - rsv1 - }; - if (isBlob(data2)) { - if (this._state !== DEFAULT) { - this.enqueue([this.getBlobData, data2, this._compress, opts, cb]); - } else { - this.getBlobData(data2, this._compress, opts, cb); - } - } else if (this._state !== DEFAULT) { - this.enqueue([this.dispatch, data2, this._compress, opts, cb]); - } else { - this.dispatch(data2, this._compress, opts, cb); - } - } - /** - * Gets the contents of a blob as binary data. - * - * @param {Blob} blob The blob - * @param {Boolean} [compress=false] Specifies whether or not to compress - * the data - * @param {Object} options Options object - * @param {Boolean} [options.fin=false] Specifies whether or not to set the - * FIN bit - * @param {Function} [options.generateMask] The function used to generate the - * masking key - * @param {Boolean} [options.mask=false] Specifies whether or not to mask - * `data` - * @param {Buffer} [options.maskBuffer] The buffer used to store the masking - * key - * @param {Number} options.opcode The opcode - * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be - * modified - * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the - * RSV1 bit - * @param {Function} [cb] Callback - * @private - */ - getBlobData(blob, compress2, options, cb) { - this._bufferedBytes += options[kByteLength]; - this._state = GET_BLOB_DATA; - blob.arrayBuffer().then((arrayBuffer) => { - if (this._socket.destroyed) { - const err = new Error( - "The socket was closed while the blob was being read" - ); - process.nextTick(callCallbacks, this, err, cb); - return; - } - this._bufferedBytes -= options[kByteLength]; - const data2 = toBuffer(arrayBuffer); - if (!compress2) { - this._state = DEFAULT; - this.sendFrame(_Sender.frame(data2, options), cb); - this.dequeue(); - } else { - this.dispatch(data2, compress2, options, cb); - } - }).catch((err) => { - process.nextTick(onError, this, err, cb); - }); - } - /** - * Dispatches a message. - * - * @param {(Buffer|String)} data The message to send - * @param {Boolean} [compress=false] Specifies whether or not to compress - * `data` - * @param {Object} options Options object - * @param {Boolean} [options.fin=false] Specifies whether or not to set the - * FIN bit - * @param {Function} [options.generateMask] The function used to generate the - * masking key - * @param {Boolean} [options.mask=false] Specifies whether or not to mask - * `data` - * @param {Buffer} [options.maskBuffer] The buffer used to store the masking - * key - * @param {Number} options.opcode The opcode - * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be - * modified - * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the - * RSV1 bit - * @param {Function} [cb] Callback - * @private - */ - dispatch(data2, compress2, options, cb) { - if (!compress2) { - this.sendFrame(_Sender.frame(data2, options), cb); - return; - } - const perMessageDeflate = this._extensions[PerMessageDeflate2.extensionName]; - this._bufferedBytes += options[kByteLength]; - this._state = DEFLATING; - perMessageDeflate.compress(data2, options.fin, (_, buf) => { - if (this._socket.destroyed) { - const err = new Error( - "The socket was closed while data was being compressed" - ); - callCallbacks(this, err, cb); - return; - } - this._bufferedBytes -= options[kByteLength]; - this._state = DEFAULT; - options.readOnly = false; - this.sendFrame(_Sender.frame(buf, options), cb); - this.dequeue(); - }); - } - /** - * Executes queued send operations. - * - * @private - */ - dequeue() { - while (this._state === DEFAULT && this._queue.length) { - const params = this._queue.shift(); - this._bufferedBytes -= params[3][kByteLength]; - Reflect.apply(params[0], this, params.slice(1)); - } - } - /** - * Enqueues a send operation. - * - * @param {Array} params Send operation parameters. - * @private - */ - enqueue(params) { - this._bufferedBytes += params[3][kByteLength]; - this._queue.push(params); - } - /** - * Sends a frame. - * - * @param {(Buffer | String)[]} list The frame to send - * @param {Function} [cb] Callback - * @private - */ - sendFrame(list2, cb) { - if (list2.length === 2) { - this._socket.cork(); - this._socket.write(list2[0]); - this._socket.write(list2[1], cb); - this._socket.uncork(); - } else { - this._socket.write(list2[0], cb); - } - } - }; - module.exports = Sender2; - function callCallbacks(sender, err, cb) { - if (typeof cb === "function") cb(err); - for (let i5 = 0; i5 < sender._queue.length; i5++) { - const params = sender._queue[i5]; - const callback = params[params.length - 1]; - if (typeof callback === "function") callback(err); - } - } - function onError(sender, err, cb) { - callCallbacks(sender, err, cb); - sender.onerror(err); - } - } -}); - -// node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/event-target.js -var require_event_target = __commonJS({ - "node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/event-target.js"(exports, module) { - "use strict"; - var { kForOnEventAttribute, kListener } = require_constants2(); - var kCode = /* @__PURE__ */ Symbol("kCode"); - var kData = /* @__PURE__ */ Symbol("kData"); - var kError = /* @__PURE__ */ Symbol("kError"); - var kMessage = /* @__PURE__ */ Symbol("kMessage"); - var kReason = /* @__PURE__ */ Symbol("kReason"); - var kTarget = /* @__PURE__ */ Symbol("kTarget"); - var kType = /* @__PURE__ */ Symbol("kType"); - var kWasClean = /* @__PURE__ */ Symbol("kWasClean"); - var Event = class { - /** - * Create a new `Event`. - * - * @param {String} type The name of the event - * @throws {TypeError} If the `type` argument is not specified - */ - constructor(type) { - this[kTarget] = null; - this[kType] = type; - } - /** - * @type {*} - */ - get target() { - return this[kTarget]; - } - /** - * @type {String} - */ - get type() { - return this[kType]; - } - }; - Object.defineProperty(Event.prototype, "target", { enumerable: true }); - Object.defineProperty(Event.prototype, "type", { enumerable: true }); - var CloseEvent = class extends Event { - /** - * Create a new `CloseEvent`. - * - * @param {String} type The name of the event - * @param {Object} [options] A dictionary object that allows for setting - * attributes via object members of the same name - * @param {Number} [options.code=0] The status code explaining why the - * connection was closed - * @param {String} [options.reason=''] A human-readable string explaining why - * the connection was closed - * @param {Boolean} [options.wasClean=false] Indicates whether or not the - * connection was cleanly closed - */ - constructor(type, options = {}) { - super(type); - this[kCode] = options.code === void 0 ? 0 : options.code; - this[kReason] = options.reason === void 0 ? "" : options.reason; - this[kWasClean] = options.wasClean === void 0 ? false : options.wasClean; - } - /** - * @type {Number} - */ - get code() { - return this[kCode]; - } - /** - * @type {String} - */ - get reason() { - return this[kReason]; - } - /** - * @type {Boolean} - */ - get wasClean() { - return this[kWasClean]; - } - }; - Object.defineProperty(CloseEvent.prototype, "code", { enumerable: true }); - Object.defineProperty(CloseEvent.prototype, "reason", { enumerable: true }); - Object.defineProperty(CloseEvent.prototype, "wasClean", { enumerable: true }); - var ErrorEvent = class extends Event { - /** - * Create a new `ErrorEvent`. - * - * @param {String} type The name of the event - * @param {Object} [options] A dictionary object that allows for setting - * attributes via object members of the same name - * @param {*} [options.error=null] The error that generated this event - * @param {String} [options.message=''] The error message - */ - constructor(type, options = {}) { - super(type); - this[kError] = options.error === void 0 ? null : options.error; - this[kMessage] = options.message === void 0 ? "" : options.message; - } - /** - * @type {*} - */ - get error() { - return this[kError]; - } - /** - * @type {String} - */ - get message() { - return this[kMessage]; - } - }; - Object.defineProperty(ErrorEvent.prototype, "error", { enumerable: true }); - Object.defineProperty(ErrorEvent.prototype, "message", { enumerable: true }); - var MessageEvent = class extends Event { - /** - * Create a new `MessageEvent`. - * - * @param {String} type The name of the event - * @param {Object} [options] A dictionary object that allows for setting - * attributes via object members of the same name - * @param {*} [options.data=null] The message content - */ - constructor(type, options = {}) { - super(type); - this[kData] = options.data === void 0 ? null : options.data; - } - /** - * @type {*} - */ - get data() { - return this[kData]; - } - }; - Object.defineProperty(MessageEvent.prototype, "data", { enumerable: true }); - var EventTarget = { - /** - * Register an event listener. - * - * @param {String} type A string representing the event type to listen for - * @param {(Function|Object)} handler The listener to add - * @param {Object} [options] An options object specifies characteristics about - * the event listener - * @param {Boolean} [options.once=false] A `Boolean` indicating that the - * listener should be invoked at most once after being added. If `true`, - * the listener would be automatically removed when invoked. - * @public - */ - addEventListener(type, handler, options = {}) { - for (const listener of this.listeners(type)) { - if (!options[kForOnEventAttribute] && listener[kListener] === handler && !listener[kForOnEventAttribute]) { - return; - } - } - let wrapper; - if (type === "message") { - wrapper = function onMessage(data2, isBinary) { - const event = new MessageEvent("message", { - data: isBinary ? data2 : data2.toString() - }); - event[kTarget] = this; - callListener(handler, this, event); - }; - } else if (type === "close") { - wrapper = function onClose(code, message2) { - const event = new CloseEvent("close", { - code, - reason: message2.toString(), - wasClean: this._closeFrameReceived && this._closeFrameSent - }); - event[kTarget] = this; - callListener(handler, this, event); - }; - } else if (type === "error") { - wrapper = function onError(error50) { - const event = new ErrorEvent("error", { - error: error50, - message: error50.message - }); - event[kTarget] = this; - callListener(handler, this, event); - }; - } else if (type === "open") { - wrapper = function onOpen() { - const event = new Event("open"); - event[kTarget] = this; - callListener(handler, this, event); - }; - } else { - return; - } - wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute]; - wrapper[kListener] = handler; - if (options.once) { - this.once(type, wrapper); - } else { - this.on(type, wrapper); - } - }, - /** - * Remove an event listener. - * - * @param {String} type A string representing the event type to remove - * @param {(Function|Object)} handler The listener to remove - * @public - */ - removeEventListener(type, handler) { - for (const listener of this.listeners(type)) { - if (listener[kListener] === handler && !listener[kForOnEventAttribute]) { - this.removeListener(type, listener); - break; - } - } - } - }; - module.exports = { - CloseEvent, - ErrorEvent, - Event, - EventTarget, - MessageEvent - }; - function callListener(listener, thisArg, event) { - if (typeof listener === "object" && listener.handleEvent) { - listener.handleEvent.call(listener, event); - } else { - listener.call(thisArg, event); - } - } - } -}); - -// node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/extension.js -var require_extension = __commonJS({ - "node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/extension.js"(exports, module) { - "use strict"; - var { tokenChars } = require_validation(); - function push(dest, name, elem) { - if (dest[name] === void 0) dest[name] = [elem]; - else dest[name].push(elem); - } - function parse5(header) { - const offers = /* @__PURE__ */ Object.create(null); - let params = /* @__PURE__ */ Object.create(null); - let mustUnescape = false; - let isEscaping = false; - let inQuotes = false; - let extensionName; - let paramName; - let start = -1; - let code = -1; - let end = -1; - let i5 = 0; - for (; i5 < header.length; i5++) { - code = header.charCodeAt(i5); - if (extensionName === void 0) { - if (end === -1 && tokenChars[code] === 1) { - if (start === -1) start = i5; - } else if (i5 !== 0 && (code === 32 || code === 9)) { - if (end === -1 && start !== -1) end = i5; - } else if (code === 59 || code === 44) { - if (start === -1) { - throw new SyntaxError(`Unexpected character at index ${i5}`); - } - if (end === -1) end = i5; - const name = header.slice(start, end); - if (code === 44) { - push(offers, name, params); - params = /* @__PURE__ */ Object.create(null); - } else { - extensionName = name; - } - start = end = -1; - } else { - throw new SyntaxError(`Unexpected character at index ${i5}`); - } - } else if (paramName === void 0) { - if (end === -1 && tokenChars[code] === 1) { - if (start === -1) start = i5; - } else if (code === 32 || code === 9) { - if (end === -1 && start !== -1) end = i5; - } else if (code === 59 || code === 44) { - if (start === -1) { - throw new SyntaxError(`Unexpected character at index ${i5}`); - } - if (end === -1) end = i5; - push(params, header.slice(start, end), true); - if (code === 44) { - push(offers, extensionName, params); - params = /* @__PURE__ */ Object.create(null); - extensionName = void 0; - } - start = end = -1; - } else if (code === 61 && start !== -1 && end === -1) { - paramName = header.slice(start, i5); - start = end = -1; - } else { - throw new SyntaxError(`Unexpected character at index ${i5}`); - } - } else { - if (isEscaping) { - if (tokenChars[code] !== 1) { - throw new SyntaxError(`Unexpected character at index ${i5}`); - } - if (start === -1) start = i5; - else if (!mustUnescape) mustUnescape = true; - isEscaping = false; - } else if (inQuotes) { - if (tokenChars[code] === 1) { - if (start === -1) start = i5; - } else if (code === 34 && start !== -1) { - inQuotes = false; - end = i5; - } else if (code === 92) { - isEscaping = true; - } else { - throw new SyntaxError(`Unexpected character at index ${i5}`); - } - } else if (code === 34 && header.charCodeAt(i5 - 1) === 61) { - inQuotes = true; - } else if (end === -1 && tokenChars[code] === 1) { - if (start === -1) start = i5; - } else if (start !== -1 && (code === 32 || code === 9)) { - if (end === -1) end = i5; - } else if (code === 59 || code === 44) { - if (start === -1) { - throw new SyntaxError(`Unexpected character at index ${i5}`); - } - if (end === -1) end = i5; - let value = header.slice(start, end); - if (mustUnescape) { - value = value.replace(/\\/g, ""); - mustUnescape = false; - } - push(params, paramName, value); - if (code === 44) { - push(offers, extensionName, params); - params = /* @__PURE__ */ Object.create(null); - extensionName = void 0; - } - paramName = void 0; - start = end = -1; - } else { - throw new SyntaxError(`Unexpected character at index ${i5}`); - } - } - } - if (start === -1 || inQuotes || code === 32 || code === 9) { - throw new SyntaxError("Unexpected end of input"); - } - if (end === -1) end = i5; - const token = header.slice(start, end); - if (extensionName === void 0) { - push(offers, token, params); - } else { - if (paramName === void 0) { - push(params, token, true); - } else if (mustUnescape) { - push(params, paramName, token.replace(/\\/g, "")); - } else { - push(params, paramName, token); - } - push(offers, extensionName, params); - } - return offers; - } - function format2(extensions) { - return Object.keys(extensions).map((extension2) => { - let configurations = extensions[extension2]; - if (!Array.isArray(configurations)) configurations = [configurations]; - return configurations.map((params) => { - return [extension2].concat( - Object.keys(params).map((k5) => { - let values2 = params[k5]; - if (!Array.isArray(values2)) values2 = [values2]; - return values2.map((v5) => v5 === true ? k5 : `${k5}=${v5}`).join("; "); - }) - ).join("; "); - }).join(", "); - }).join(", "); - } - module.exports = { format: format2, parse: parse5 }; - } -}); - -// node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/websocket.js -var require_websocket = __commonJS({ - "node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/websocket.js"(exports, module) { - "use strict"; - var EventEmitter5 = __require("events"); - var https = __require("https"); - var http = __require("http"); - var net3 = __require("net"); - var tls2 = __require("tls"); - var { randomBytes: randomBytes7, createHash: createHash18 } = __require("crypto"); - var { Duplex, Readable: Readable3 } = __require("stream"); - var { URL: URL2 } = __require("url"); - var PerMessageDeflate2 = require_permessage_deflate(); - var Receiver2 = require_receiver(); - var Sender2 = require_sender(); - var { isBlob } = require_validation(); - var { - BINARY_TYPES, - CLOSE_TIMEOUT, - EMPTY_BUFFER: EMPTY_BUFFER2, - GUID, - kForOnEventAttribute, - kListener, - kStatusCode, - kWebSocket, - NOOP - } = require_constants2(); - var { - EventTarget: { addEventListener, removeEventListener } - } = require_event_target(); - var { format: format2, parse: parse5 } = require_extension(); - var { toBuffer } = require_buffer_util(); - var kAborted = /* @__PURE__ */ Symbol("kAborted"); - var protocolVersions = [8, 13]; - var readyStates = ["CONNECTING", "OPEN", "CLOSING", "CLOSED"]; - var subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/; - var WebSocket2 = class _WebSocket extends EventEmitter5 { - /** - * Create a new `WebSocket`. - * - * @param {(String|URL)} address The URL to which to connect - * @param {(String|String[])} [protocols] The subprotocols - * @param {Object} [options] Connection options - */ - constructor(address, protocols, options) { - super(); - this._binaryType = BINARY_TYPES[0]; - this._closeCode = 1006; - this._closeFrameReceived = false; - this._closeFrameSent = false; - this._closeMessage = EMPTY_BUFFER2; - this._closeTimer = null; - this._errorEmitted = false; - this._extensions = {}; - this._paused = false; - this._protocol = ""; - this._readyState = _WebSocket.CONNECTING; - this._receiver = null; - this._sender = null; - this._socket = null; - if (address !== null) { - this._bufferedAmount = 0; - this._isServer = false; - this._redirects = 0; - if (protocols === void 0) { - protocols = []; - } else if (!Array.isArray(protocols)) { - if (typeof protocols === "object" && protocols !== null) { - options = protocols; - protocols = []; - } else { - protocols = [protocols]; - } - } - initAsClient(this, address, protocols, options); - } else { - this._autoPong = options.autoPong; - this._closeTimeout = options.closeTimeout; - this._isServer = true; - } - } - /** - * For historical reasons, the custom "nodebuffer" type is used by the default - * instead of "blob". - * - * @type {String} - */ - get binaryType() { - return this._binaryType; - } - set binaryType(type) { - if (!BINARY_TYPES.includes(type)) return; - this._binaryType = type; - if (this._receiver) this._receiver._binaryType = type; - } - /** - * @type {Number} - */ - get bufferedAmount() { - if (!this._socket) return this._bufferedAmount; - return this._socket._writableState.length + this._sender._bufferedBytes; - } - /** - * @type {String} - */ - get extensions() { - return Object.keys(this._extensions).join(); - } - /** - * @type {Boolean} - */ - get isPaused() { - return this._paused; - } - /** - * @type {Function} - */ - /* istanbul ignore next */ - get onclose() { - return null; - } - /** - * @type {Function} - */ - /* istanbul ignore next */ - get onerror() { - return null; - } - /** - * @type {Function} - */ - /* istanbul ignore next */ - get onopen() { - return null; - } - /** - * @type {Function} - */ - /* istanbul ignore next */ - get onmessage() { - return null; - } - /** - * @type {String} - */ - get protocol() { - return this._protocol; - } - /** - * @type {Number} - */ - get readyState() { - return this._readyState; - } - /** - * @type {String} - */ - get url() { - return this._url; - } - /** - * Set up the socket and the internal resources. - * - * @param {Duplex} socket The network socket between the server and client - * @param {Buffer} head The first packet of the upgraded stream - * @param {Object} options Options object - * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether - * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted - * multiple times in the same tick - * @param {Function} [options.generateMask] The function used to generate the - * masking key - * @param {Number} [options.maxPayload=0] The maximum allowed message size - * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or - * not to skip UTF-8 validation for text and close messages - * @private - */ - setSocket(socket, head, options) { - const receiver = new Receiver2({ - allowSynchronousEvents: options.allowSynchronousEvents, - binaryType: this.binaryType, - extensions: this._extensions, - isServer: this._isServer, - maxPayload: options.maxPayload, - skipUTF8Validation: options.skipUTF8Validation - }); - const sender = new Sender2(socket, this._extensions, options.generateMask); - this._receiver = receiver; - this._sender = sender; - this._socket = socket; - receiver[kWebSocket] = this; - sender[kWebSocket] = this; - socket[kWebSocket] = this; - receiver.on("conclude", receiverOnConclude); - receiver.on("drain", receiverOnDrain); - receiver.on("error", receiverOnError); - receiver.on("message", receiverOnMessage); - receiver.on("ping", receiverOnPing); - receiver.on("pong", receiverOnPong); - sender.onerror = senderOnError; - if (socket.setTimeout) socket.setTimeout(0); - if (socket.setNoDelay) socket.setNoDelay(); - if (head.length > 0) socket.unshift(head); - socket.on("close", socketOnClose); - socket.on("data", socketOnData); - socket.on("end", socketOnEnd); - socket.on("error", socketOnError); - this._readyState = _WebSocket.OPEN; - this.emit("open"); - } - /** - * Emit the `'close'` event. - * - * @private - */ - emitClose() { - if (!this._socket) { - this._readyState = _WebSocket.CLOSED; - this.emit("close", this._closeCode, this._closeMessage); - return; - } - if (this._extensions[PerMessageDeflate2.extensionName]) { - this._extensions[PerMessageDeflate2.extensionName].cleanup(); - } - this._receiver.removeAllListeners(); - this._readyState = _WebSocket.CLOSED; - this.emit("close", this._closeCode, this._closeMessage); - } - /** - * Start a closing handshake. - * - * +----------+ +-----------+ +----------+ - * - - -|ws.close()|-->|close frame|-->|ws.close()|- - - - * | +----------+ +-----------+ +----------+ | - * +----------+ +-----------+ | - * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING - * +----------+ +-----------+ | - * | | | +---+ | - * +------------------------+-->|fin| - - - - - * | +---+ | +---+ - * - - - - -|fin|<---------------------+ - * +---+ - * - * @param {Number} [code] Status code explaining why the connection is closing - * @param {(String|Buffer)} [data] The reason why the connection is - * closing - * @public - */ - close(code, data2) { - if (this.readyState === _WebSocket.CLOSED) return; - if (this.readyState === _WebSocket.CONNECTING) { - const msg = "WebSocket was closed before the connection was established"; - abortHandshake(this, this._req, msg); - return; - } - if (this.readyState === _WebSocket.CLOSING) { - if (this._closeFrameSent && (this._closeFrameReceived || this._receiver._writableState.errorEmitted)) { - this._socket.end(); - } - return; - } - this._readyState = _WebSocket.CLOSING; - this._sender.close(code, data2, !this._isServer, (err) => { - if (err) return; - this._closeFrameSent = true; - if (this._closeFrameReceived || this._receiver._writableState.errorEmitted) { - this._socket.end(); - } - }); - setCloseTimer(this); - } - /** - * Pause the socket. - * - * @public - */ - pause() { - if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) { - return; - } - this._paused = true; - this._socket.pause(); - } - /** - * Send a ping. - * - * @param {*} [data] The data to send - * @param {Boolean} [mask] Indicates whether or not to mask `data` - * @param {Function} [cb] Callback which is executed when the ping is sent - * @public - */ - ping(data2, mask, cb) { - if (this.readyState === _WebSocket.CONNECTING) { - throw new Error("WebSocket is not open: readyState 0 (CONNECTING)"); - } - if (typeof data2 === "function") { - cb = data2; - data2 = mask = void 0; - } else if (typeof mask === "function") { - cb = mask; - mask = void 0; - } - if (typeof data2 === "number") data2 = data2.toString(); - if (this.readyState !== _WebSocket.OPEN) { - sendAfterClose(this, data2, cb); - return; - } - if (mask === void 0) mask = !this._isServer; - this._sender.ping(data2 || EMPTY_BUFFER2, mask, cb); - } - /** - * Send a pong. - * - * @param {*} [data] The data to send - * @param {Boolean} [mask] Indicates whether or not to mask `data` - * @param {Function} [cb] Callback which is executed when the pong is sent - * @public - */ - pong(data2, mask, cb) { - if (this.readyState === _WebSocket.CONNECTING) { - throw new Error("WebSocket is not open: readyState 0 (CONNECTING)"); - } - if (typeof data2 === "function") { - cb = data2; - data2 = mask = void 0; - } else if (typeof mask === "function") { - cb = mask; - mask = void 0; - } - if (typeof data2 === "number") data2 = data2.toString(); - if (this.readyState !== _WebSocket.OPEN) { - sendAfterClose(this, data2, cb); - return; - } - if (mask === void 0) mask = !this._isServer; - this._sender.pong(data2 || EMPTY_BUFFER2, mask, cb); - } - /** - * Resume the socket. - * - * @public - */ - resume() { - if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) { - return; - } - this._paused = false; - if (!this._receiver._writableState.needDrain) this._socket.resume(); - } - /** - * Send a data message. - * - * @param {*} data The message to send - * @param {Object} [options] Options object - * @param {Boolean} [options.binary] Specifies whether `data` is binary or - * text - * @param {Boolean} [options.compress] Specifies whether or not to compress - * `data` - * @param {Boolean} [options.fin=true] Specifies whether the fragment is the - * last one - * @param {Boolean} [options.mask] Specifies whether or not to mask `data` - * @param {Function} [cb] Callback which is executed when data is written out - * @public - */ - send(data2, options, cb) { - if (this.readyState === _WebSocket.CONNECTING) { - throw new Error("WebSocket is not open: readyState 0 (CONNECTING)"); - } - if (typeof options === "function") { - cb = options; - options = {}; - } - if (typeof data2 === "number") data2 = data2.toString(); - if (this.readyState !== _WebSocket.OPEN) { - sendAfterClose(this, data2, cb); - return; - } - const opts = { - binary: typeof data2 !== "string", - mask: !this._isServer, - compress: true, - fin: true, - ...options - }; - if (!this._extensions[PerMessageDeflate2.extensionName]) { - opts.compress = false; - } - this._sender.send(data2 || EMPTY_BUFFER2, opts, cb); - } - /** - * Forcibly close the connection. - * - * @public - */ - terminate() { - if (this.readyState === _WebSocket.CLOSED) return; - if (this.readyState === _WebSocket.CONNECTING) { - const msg = "WebSocket was closed before the connection was established"; - abortHandshake(this, this._req, msg); - return; - } - if (this._socket) { - this._readyState = _WebSocket.CLOSING; - this._socket.destroy(); - } - } - }; - Object.defineProperty(WebSocket2, "CONNECTING", { - enumerable: true, - value: readyStates.indexOf("CONNECTING") - }); - Object.defineProperty(WebSocket2.prototype, "CONNECTING", { - enumerable: true, - value: readyStates.indexOf("CONNECTING") - }); - Object.defineProperty(WebSocket2, "OPEN", { - enumerable: true, - value: readyStates.indexOf("OPEN") - }); - Object.defineProperty(WebSocket2.prototype, "OPEN", { - enumerable: true, - value: readyStates.indexOf("OPEN") - }); - Object.defineProperty(WebSocket2, "CLOSING", { - enumerable: true, - value: readyStates.indexOf("CLOSING") - }); - Object.defineProperty(WebSocket2.prototype, "CLOSING", { - enumerable: true, - value: readyStates.indexOf("CLOSING") - }); - Object.defineProperty(WebSocket2, "CLOSED", { - enumerable: true, - value: readyStates.indexOf("CLOSED") - }); - Object.defineProperty(WebSocket2.prototype, "CLOSED", { - enumerable: true, - value: readyStates.indexOf("CLOSED") - }); - [ - "binaryType", - "bufferedAmount", - "extensions", - "isPaused", - "protocol", - "readyState", - "url" - ].forEach((property) => { - Object.defineProperty(WebSocket2.prototype, property, { enumerable: true }); - }); - ["open", "error", "close", "message"].forEach((method) => { - Object.defineProperty(WebSocket2.prototype, `on${method}`, { - enumerable: true, - get() { - for (const listener of this.listeners(method)) { - if (listener[kForOnEventAttribute]) return listener[kListener]; - } - return null; - }, - set(handler) { - for (const listener of this.listeners(method)) { - if (listener[kForOnEventAttribute]) { - this.removeListener(method, listener); - break; - } - } - if (typeof handler !== "function") return; - this.addEventListener(method, handler, { - [kForOnEventAttribute]: true - }); - } - }); - }); - WebSocket2.prototype.addEventListener = addEventListener; - WebSocket2.prototype.removeEventListener = removeEventListener; - module.exports = WebSocket2; - function initAsClient(websocket, address, protocols, options) { - const opts = { - allowSynchronousEvents: true, - autoPong: true, - closeTimeout: CLOSE_TIMEOUT, - protocolVersion: protocolVersions[1], - maxPayload: 100 * 1024 * 1024, - skipUTF8Validation: false, - perMessageDeflate: true, - followRedirects: false, - maxRedirects: 10, - ...options, - socketPath: void 0, - hostname: void 0, - protocol: void 0, - timeout: void 0, - method: "GET", - host: void 0, - path: void 0, - port: void 0 - }; - websocket._autoPong = opts.autoPong; - websocket._closeTimeout = opts.closeTimeout; - if (!protocolVersions.includes(opts.protocolVersion)) { - throw new RangeError( - `Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})` - ); - } - let parsedUrl; - if (address instanceof URL2) { - parsedUrl = address; - } else { - try { - parsedUrl = new URL2(address); - } catch { - throw new SyntaxError(`Invalid URL: ${address}`); - } - } - if (parsedUrl.protocol === "http:") { - parsedUrl.protocol = "ws:"; - } else if (parsedUrl.protocol === "https:") { - parsedUrl.protocol = "wss:"; - } - websocket._url = parsedUrl.href; - const isSecure = parsedUrl.protocol === "wss:"; - const isIpcUrl = parsedUrl.protocol === "ws+unix:"; - let invalidUrlMessage; - if (parsedUrl.protocol !== "ws:" && !isSecure && !isIpcUrl) { - invalidUrlMessage = `The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`; - } else if (isIpcUrl && !parsedUrl.pathname) { - invalidUrlMessage = "The URL's pathname is empty"; - } else if (parsedUrl.hash) { - invalidUrlMessage = "The URL contains a fragment identifier"; - } - if (invalidUrlMessage) { - const err = new SyntaxError(invalidUrlMessage); - if (websocket._redirects === 0) { - throw err; - } else { - emitErrorAndClose(websocket, err); - return; - } - } - const defaultPort = isSecure ? 443 : 80; - const key = randomBytes7(16).toString("base64"); - const request = isSecure ? https.request : http.request; - const protocolSet = /* @__PURE__ */ new Set(); - let perMessageDeflate; - opts.createConnection = opts.createConnection || (isSecure ? tlsConnect : netConnect); - opts.defaultPort = opts.defaultPort || defaultPort; - opts.port = parsedUrl.port || defaultPort; - opts.host = parsedUrl.hostname.startsWith("[") ? parsedUrl.hostname.slice(1, -1) : parsedUrl.hostname; - opts.headers = { - ...opts.headers, - "Sec-WebSocket-Version": opts.protocolVersion, - "Sec-WebSocket-Key": key, - Connection: "Upgrade", - Upgrade: "websocket" - }; - opts.path = parsedUrl.pathname + parsedUrl.search; - opts.timeout = opts.handshakeTimeout; - if (opts.perMessageDeflate) { - perMessageDeflate = new PerMessageDeflate2({ - ...opts.perMessageDeflate, - isServer: false, - maxPayload: opts.maxPayload - }); - opts.headers["Sec-WebSocket-Extensions"] = format2({ - [PerMessageDeflate2.extensionName]: perMessageDeflate.offer() - }); - } - if (protocols.length) { - for (const protocol of protocols) { - if (typeof protocol !== "string" || !subprotocolRegex.test(protocol) || protocolSet.has(protocol)) { - throw new SyntaxError( - "An invalid or duplicated subprotocol was specified" - ); - } - protocolSet.add(protocol); - } - opts.headers["Sec-WebSocket-Protocol"] = protocols.join(","); - } - if (opts.origin) { - if (opts.protocolVersion < 13) { - opts.headers["Sec-WebSocket-Origin"] = opts.origin; - } else { - opts.headers.Origin = opts.origin; - } - } - if (parsedUrl.username || parsedUrl.password) { - opts.auth = `${parsedUrl.username}:${parsedUrl.password}`; - } - if (isIpcUrl) { - const parts = opts.path.split(":"); - opts.socketPath = parts[0]; - opts.path = parts[1]; - } - let req; - if (opts.followRedirects) { - if (websocket._redirects === 0) { - websocket._originalIpc = isIpcUrl; - websocket._originalSecure = isSecure; - websocket._originalHostOrSocketPath = isIpcUrl ? opts.socketPath : parsedUrl.host; - const headers = options && options.headers; - options = { ...options, headers: {} }; - if (headers) { - for (const [key2, value] of Object.entries(headers)) { - options.headers[key2.toLowerCase()] = value; - } - } - } else if (websocket.listenerCount("redirect") === 0) { - const isSameHost = isIpcUrl ? websocket._originalIpc ? opts.socketPath === websocket._originalHostOrSocketPath : false : websocket._originalIpc ? false : parsedUrl.host === websocket._originalHostOrSocketPath; - if (!isSameHost || websocket._originalSecure && !isSecure) { - delete opts.headers.authorization; - delete opts.headers.cookie; - if (!isSameHost) delete opts.headers.host; - opts.auth = void 0; - } - } - if (opts.auth && !options.headers.authorization) { - options.headers.authorization = "Basic " + Buffer.from(opts.auth).toString("base64"); - } - req = websocket._req = request(opts); - if (websocket._redirects) { - websocket.emit("redirect", websocket.url, req); - } - } else { - req = websocket._req = request(opts); - } - if (opts.timeout) { - req.on("timeout", () => { - abortHandshake(websocket, req, "Opening handshake has timed out"); - }); - } - req.on("error", (err) => { - if (req === null || req[kAborted]) return; - req = websocket._req = null; - emitErrorAndClose(websocket, err); - }); - req.on("response", (res) => { - const location = res.headers.location; - const statusCode = res.statusCode; - if (location && opts.followRedirects && statusCode >= 300 && statusCode < 400) { - if (++websocket._redirects > opts.maxRedirects) { - abortHandshake(websocket, req, "Maximum redirects exceeded"); - return; - } - req.abort(); - let addr; - try { - addr = new URL2(location, address); - } catch (e5) { - const err = new SyntaxError(`Invalid URL: ${location}`); - emitErrorAndClose(websocket, err); - return; - } - initAsClient(websocket, addr, protocols, options); - } else if (!websocket.emit("unexpected-response", req, res)) { - abortHandshake( - websocket, - req, - `Unexpected server response: ${res.statusCode}` - ); - } - }); - req.on("upgrade", (res, socket, head) => { - websocket.emit("upgrade", res); - if (websocket.readyState !== WebSocket2.CONNECTING) return; - req = websocket._req = null; - const upgrade = res.headers.upgrade; - if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") { - abortHandshake(websocket, socket, "Invalid Upgrade header"); - return; - } - const digest2 = createHash18("sha1").update(key + GUID).digest("base64"); - if (res.headers["sec-websocket-accept"] !== digest2) { - abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header"); - return; - } - const serverProt = res.headers["sec-websocket-protocol"]; - let protError; - if (serverProt !== void 0) { - if (!protocolSet.size) { - protError = "Server sent a subprotocol but none was requested"; - } else if (!protocolSet.has(serverProt)) { - protError = "Server sent an invalid subprotocol"; - } - } else if (protocolSet.size) { - protError = "Server sent no subprotocol"; - } - if (protError) { - abortHandshake(websocket, socket, protError); - return; - } - if (serverProt) websocket._protocol = serverProt; - const secWebSocketExtensions = res.headers["sec-websocket-extensions"]; - if (secWebSocketExtensions !== void 0) { - if (!perMessageDeflate) { - const message2 = "Server sent a Sec-WebSocket-Extensions header but no extension was requested"; - abortHandshake(websocket, socket, message2); - return; - } - let extensions; - try { - extensions = parse5(secWebSocketExtensions); - } catch (err) { - const message2 = "Invalid Sec-WebSocket-Extensions header"; - abortHandshake(websocket, socket, message2); - return; - } - const extensionNames = Object.keys(extensions); - if (extensionNames.length !== 1 || extensionNames[0] !== PerMessageDeflate2.extensionName) { - const message2 = "Server indicated an extension that was not requested"; - abortHandshake(websocket, socket, message2); - return; - } - try { - perMessageDeflate.accept(extensions[PerMessageDeflate2.extensionName]); - } catch (err) { - const message2 = "Invalid Sec-WebSocket-Extensions header"; - abortHandshake(websocket, socket, message2); - return; - } - websocket._extensions[PerMessageDeflate2.extensionName] = perMessageDeflate; - } - websocket.setSocket(socket, head, { - allowSynchronousEvents: opts.allowSynchronousEvents, - generateMask: opts.generateMask, - maxPayload: opts.maxPayload, - skipUTF8Validation: opts.skipUTF8Validation - }); - }); - if (opts.finishRequest) { - opts.finishRequest(req, websocket); - } else { - req.end(); - } - } - function emitErrorAndClose(websocket, err) { - websocket._readyState = WebSocket2.CLOSING; - websocket._errorEmitted = true; - websocket.emit("error", err); - websocket.emitClose(); - } - function netConnect(options) { - options.path = options.socketPath; - return net3.connect(options); - } - function tlsConnect(options) { - options.path = void 0; - if (!options.servername && options.servername !== "") { - options.servername = net3.isIP(options.host) ? "" : options.host; - } - return tls2.connect(options); - } - function abortHandshake(websocket, stream, message2) { - websocket._readyState = WebSocket2.CLOSING; - const err = new Error(message2); - Error.captureStackTrace(err, abortHandshake); - if (stream.setHeader) { - stream[kAborted] = true; - stream.abort(); - if (stream.socket && !stream.socket.destroyed) { - stream.socket.destroy(); - } - process.nextTick(emitErrorAndClose, websocket, err); - } else { - stream.destroy(err); - stream.once("error", websocket.emit.bind(websocket, "error")); - stream.once("close", websocket.emitClose.bind(websocket)); - } - } - function sendAfterClose(websocket, data2, cb) { - if (data2) { - const length = isBlob(data2) ? data2.size : toBuffer(data2).length; - if (websocket._socket) websocket._sender._bufferedBytes += length; - else websocket._bufferedAmount += length; - } - if (cb) { - const err = new Error( - `WebSocket is not open: readyState ${websocket.readyState} (${readyStates[websocket.readyState]})` - ); - process.nextTick(cb, err); - } - } - function receiverOnConclude(code, reason) { - const websocket = this[kWebSocket]; - websocket._closeFrameReceived = true; - websocket._closeMessage = reason; - websocket._closeCode = code; - if (websocket._socket[kWebSocket] === void 0) return; - websocket._socket.removeListener("data", socketOnData); - process.nextTick(resume, websocket._socket); - if (code === 1005) websocket.close(); - else websocket.close(code, reason); - } - function receiverOnDrain() { - const websocket = this[kWebSocket]; - if (!websocket.isPaused) websocket._socket.resume(); - } - function receiverOnError(err) { - const websocket = this[kWebSocket]; - if (websocket._socket[kWebSocket] !== void 0) { - websocket._socket.removeListener("data", socketOnData); - process.nextTick(resume, websocket._socket); - websocket.close(err[kStatusCode]); - } - if (!websocket._errorEmitted) { - websocket._errorEmitted = true; - websocket.emit("error", err); - } - } - function receiverOnFinish() { - this[kWebSocket].emitClose(); - } - function receiverOnMessage(data2, isBinary) { - this[kWebSocket].emit("message", data2, isBinary); - } - function receiverOnPing(data2) { - const websocket = this[kWebSocket]; - if (websocket._autoPong) websocket.pong(data2, !this._isServer, NOOP); - websocket.emit("ping", data2); - } - function receiverOnPong(data2) { - this[kWebSocket].emit("pong", data2); - } - function resume(stream) { - stream.resume(); - } - function senderOnError(err) { - const websocket = this[kWebSocket]; - if (websocket.readyState === WebSocket2.CLOSED) return; - if (websocket.readyState === WebSocket2.OPEN) { - websocket._readyState = WebSocket2.CLOSING; - setCloseTimer(websocket); - } - this._socket.end(); - if (!websocket._errorEmitted) { - websocket._errorEmitted = true; - websocket.emit("error", err); - } - } - function setCloseTimer(websocket) { - websocket._closeTimer = setTimeout( - websocket._socket.destroy.bind(websocket._socket), - websocket._closeTimeout - ); - } - function socketOnClose() { - const websocket = this[kWebSocket]; - this.removeListener("close", socketOnClose); - this.removeListener("data", socketOnData); - this.removeListener("end", socketOnEnd); - websocket._readyState = WebSocket2.CLOSING; - if (!this._readableState.endEmitted && !websocket._closeFrameReceived && !websocket._receiver._writableState.errorEmitted && this._readableState.length !== 0) { - const chunk = this.read(this._readableState.length); - websocket._receiver.write(chunk); - } - websocket._receiver.end(); - this[kWebSocket] = void 0; - clearTimeout(websocket._closeTimer); - if (websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted) { - websocket.emitClose(); - } else { - websocket._receiver.on("error", receiverOnFinish); - websocket._receiver.on("finish", receiverOnFinish); - } - } - function socketOnData(chunk) { - if (!this[kWebSocket]._receiver.write(chunk)) { - this.pause(); - } - } - function socketOnEnd() { - const websocket = this[kWebSocket]; - websocket._readyState = WebSocket2.CLOSING; - websocket._receiver.end(); - this.end(); - } - function socketOnError() { - const websocket = this[kWebSocket]; - this.removeListener("error", socketOnError); - this.on("error", NOOP); - if (websocket) { - websocket._readyState = WebSocket2.CLOSING; - this.destroy(); - } - } - } -}); - -// node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/stream.js -var require_stream = __commonJS({ - "node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/stream.js"(exports, module) { - "use strict"; - var WebSocket2 = require_websocket(); - var { Duplex } = __require("stream"); - function emitClose(stream) { - stream.emit("close"); - } - function duplexOnEnd() { - if (!this.destroyed && this._writableState.finished) { - this.destroy(); - } - } - function duplexOnError(err) { - this.removeListener("error", duplexOnError); - this.destroy(); - if (this.listenerCount("error") === 0) { - this.emit("error", err); - } - } - function createWebSocketStream2(ws, options) { - let terminateOnDestroy = true; - const duplex = new Duplex({ - ...options, - autoDestroy: false, - emitClose: false, - objectMode: false, - writableObjectMode: false - }); - ws.on("message", function message2(msg, isBinary) { - const data2 = !isBinary && duplex._readableState.objectMode ? msg.toString() : msg; - if (!duplex.push(data2)) ws.pause(); - }); - ws.once("error", function error50(err) { - if (duplex.destroyed) return; - terminateOnDestroy = false; - duplex.destroy(err); - }); - ws.once("close", function close() { - if (duplex.destroyed) return; - duplex.push(null); - }); - duplex._destroy = function(err, callback) { - if (ws.readyState === ws.CLOSED) { - callback(err); - process.nextTick(emitClose, duplex); - return; - } - let called = false; - ws.once("error", function error50(err2) { - called = true; - callback(err2); - }); - ws.once("close", function close() { - if (!called) callback(err); - process.nextTick(emitClose, duplex); - }); - if (terminateOnDestroy) ws.terminate(); - }; - duplex._final = function(callback) { - if (ws.readyState === ws.CONNECTING) { - ws.once("open", function open2() { - duplex._final(callback); - }); - return; - } - if (ws._socket === null) return; - if (ws._socket._writableState.finished) { - callback(); - if (duplex._readableState.endEmitted) duplex.destroy(); - } else { - ws._socket.once("finish", function finish() { - callback(); - }); - ws.close(); - } - }; - duplex._read = function() { - if (ws.isPaused) ws.resume(); - }; - duplex._write = function(chunk, encoding, callback) { - if (ws.readyState === ws.CONNECTING) { - ws.once("open", function open2() { - duplex._write(chunk, encoding, callback); - }); - return; - } - ws.send(chunk, callback); - }; - duplex.on("end", duplexOnEnd); - duplex.on("error", duplexOnError); - return duplex; - } - module.exports = createWebSocketStream2; - } -}); - -// node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/subprotocol.js -var require_subprotocol = __commonJS({ - "node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/subprotocol.js"(exports, module) { - "use strict"; - var { tokenChars } = require_validation(); - function parse5(header) { - const protocols = /* @__PURE__ */ new Set(); - let start = -1; - let end = -1; - let i5 = 0; - for (i5; i5 < header.length; i5++) { - const code = header.charCodeAt(i5); - if (end === -1 && tokenChars[code] === 1) { - if (start === -1) start = i5; - } else if (i5 !== 0 && (code === 32 || code === 9)) { - if (end === -1 && start !== -1) end = i5; - } else if (code === 44) { - if (start === -1) { - throw new SyntaxError(`Unexpected character at index ${i5}`); - } - if (end === -1) end = i5; - const protocol2 = header.slice(start, end); - if (protocols.has(protocol2)) { - throw new SyntaxError(`The "${protocol2}" subprotocol is duplicated`); - } - protocols.add(protocol2); - start = end = -1; - } else { - throw new SyntaxError(`Unexpected character at index ${i5}`); - } - } - if (start === -1 || end !== -1) { - throw new SyntaxError("Unexpected end of input"); - } - const protocol = header.slice(start, i5); - if (protocols.has(protocol)) { - throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`); - } - protocols.add(protocol); - return protocols; - } - module.exports = { parse: parse5 }; - } -}); - -// node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/websocket-server.js -var require_websocket_server = __commonJS({ - "node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/websocket-server.js"(exports, module) { - "use strict"; - var EventEmitter5 = __require("events"); - var http = __require("http"); - var { Duplex } = __require("stream"); - var { createHash: createHash18 } = __require("crypto"); - var extension2 = require_extension(); - var PerMessageDeflate2 = require_permessage_deflate(); - var subprotocol2 = require_subprotocol(); - var WebSocket2 = require_websocket(); - var { CLOSE_TIMEOUT, GUID, kWebSocket } = require_constants2(); - var keyRegex = /^[+/0-9A-Za-z]{22}==$/; - var RUNNING = 0; - var CLOSING = 1; - var CLOSED = 2; - var WebSocketServer2 = class extends EventEmitter5 { - /** - * Create a `WebSocketServer` instance. - * - * @param {Object} options Configuration options - * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether - * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted - * multiple times in the same tick - * @param {Boolean} [options.autoPong=true] Specifies whether or not to - * automatically send a pong in response to a ping - * @param {Number} [options.backlog=511] The maximum length of the queue of - * pending connections - * @param {Boolean} [options.clientTracking=true] Specifies whether or not to - * track clients - * @param {Number} [options.closeTimeout=30000] Duration in milliseconds to - * wait for the closing handshake to finish after `websocket.close()` is - * called - * @param {Function} [options.handleProtocols] A hook to handle protocols - * @param {String} [options.host] The hostname where to bind the server - * @param {Number} [options.maxPayload=104857600] The maximum allowed message - * size - * @param {Boolean} [options.noServer=false] Enable no server mode - * @param {String} [options.path] Accept only connections matching this path - * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable - * permessage-deflate - * @param {Number} [options.port] The port where to bind the server - * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S - * server to use - * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or - * not to skip UTF-8 validation for text and close messages - * @param {Function} [options.verifyClient] A hook to reject connections - * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket` - * class to use. It must be the `WebSocket` class or class that extends it - * @param {Function} [callback] A listener for the `listening` event - */ - constructor(options, callback) { - super(); - options = { - allowSynchronousEvents: true, - autoPong: true, - maxPayload: 100 * 1024 * 1024, - skipUTF8Validation: false, - perMessageDeflate: false, - handleProtocols: null, - clientTracking: true, - closeTimeout: CLOSE_TIMEOUT, - verifyClient: null, - noServer: false, - backlog: null, - // use default (511 as implemented in net.js) - server: null, - host: null, - path: null, - port: null, - WebSocket: WebSocket2, - ...options - }; - if (options.port == null && !options.server && !options.noServer || options.port != null && (options.server || options.noServer) || options.server && options.noServer) { - throw new TypeError( - 'One and only one of the "port", "server", or "noServer" options must be specified' - ); - } - if (options.port != null) { - this._server = http.createServer((req, res) => { - const body = http.STATUS_CODES[426]; - res.writeHead(426, { - "Content-Length": body.length, - "Content-Type": "text/plain" - }); - res.end(body); - }); - this._server.listen( - options.port, - options.host, - options.backlog, - callback - ); - } else if (options.server) { - this._server = options.server; - } - if (this._server) { - const emitConnection = this.emit.bind(this, "connection"); - this._removeListeners = addListeners(this._server, { - listening: this.emit.bind(this, "listening"), - error: this.emit.bind(this, "error"), - upgrade: (req, socket, head) => { - this.handleUpgrade(req, socket, head, emitConnection); - } - }); - } - if (options.perMessageDeflate === true) options.perMessageDeflate = {}; - if (options.clientTracking) { - this.clients = /* @__PURE__ */ new Set(); - this._shouldEmitClose = false; - } - this.options = options; - this._state = RUNNING; - } - /** - * Returns the bound address, the address family name, and port of the server - * as reported by the operating system if listening on an IP socket. - * If the server is listening on a pipe or UNIX domain socket, the name is - * returned as a string. - * - * @return {(Object|String|null)} The address of the server - * @public - */ - address() { - if (this.options.noServer) { - throw new Error('The server is operating in "noServer" mode'); - } - if (!this._server) return null; - return this._server.address(); - } - /** - * Stop the server from accepting new connections and emit the `'close'` event - * when all existing connections are closed. - * - * @param {Function} [cb] A one-time listener for the `'close'` event - * @public - */ - close(cb) { - if (this._state === CLOSED) { - if (cb) { - this.once("close", () => { - cb(new Error("The server is not running")); - }); - } - process.nextTick(emitClose, this); - return; - } - if (cb) this.once("close", cb); - if (this._state === CLOSING) return; - this._state = CLOSING; - if (this.options.noServer || this.options.server) { - if (this._server) { - this._removeListeners(); - this._removeListeners = this._server = null; - } - if (this.clients) { - if (!this.clients.size) { - process.nextTick(emitClose, this); - } else { - this._shouldEmitClose = true; - } - } else { - process.nextTick(emitClose, this); - } - } else { - const server = this._server; - this._removeListeners(); - this._removeListeners = this._server = null; - server.close(() => { - emitClose(this); - }); - } - } - /** - * See if a given request should be handled by this server instance. - * - * @param {http.IncomingMessage} req Request object to inspect - * @return {Boolean} `true` if the request is valid, else `false` - * @public - */ - shouldHandle(req) { - if (this.options.path) { - const index2 = req.url.indexOf("?"); - const pathname = index2 !== -1 ? req.url.slice(0, index2) : req.url; - if (pathname !== this.options.path) return false; - } - return true; - } - /** - * Handle a HTTP Upgrade request. - * - * @param {http.IncomingMessage} req The request object - * @param {Duplex} socket The network socket between the server and client - * @param {Buffer} head The first packet of the upgraded stream - * @param {Function} cb Callback - * @public - */ - handleUpgrade(req, socket, head, cb) { - socket.on("error", socketOnError); - const key = req.headers["sec-websocket-key"]; - const upgrade = req.headers.upgrade; - const version3 = +req.headers["sec-websocket-version"]; - if (req.method !== "GET") { - const message2 = "Invalid HTTP method"; - abortHandshakeOrEmitwsClientError(this, req, socket, 405, message2); - return; - } - if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") { - const message2 = "Invalid Upgrade header"; - abortHandshakeOrEmitwsClientError(this, req, socket, 400, message2); - return; - } - if (key === void 0 || !keyRegex.test(key)) { - const message2 = "Missing or invalid Sec-WebSocket-Key header"; - abortHandshakeOrEmitwsClientError(this, req, socket, 400, message2); - return; - } - if (version3 !== 13 && version3 !== 8) { - const message2 = "Missing or invalid Sec-WebSocket-Version header"; - abortHandshakeOrEmitwsClientError(this, req, socket, 400, message2, { - "Sec-WebSocket-Version": "13, 8" - }); - return; - } - if (!this.shouldHandle(req)) { - abortHandshake(socket, 400); - return; - } - const secWebSocketProtocol = req.headers["sec-websocket-protocol"]; - let protocols = /* @__PURE__ */ new Set(); - if (secWebSocketProtocol !== void 0) { - try { - protocols = subprotocol2.parse(secWebSocketProtocol); - } catch (err) { - const message2 = "Invalid Sec-WebSocket-Protocol header"; - abortHandshakeOrEmitwsClientError(this, req, socket, 400, message2); - return; - } - } - const secWebSocketExtensions = req.headers["sec-websocket-extensions"]; - const extensions = {}; - if (this.options.perMessageDeflate && secWebSocketExtensions !== void 0) { - const perMessageDeflate = new PerMessageDeflate2({ - ...this.options.perMessageDeflate, - isServer: true, - maxPayload: this.options.maxPayload - }); - try { - const offers = extension2.parse(secWebSocketExtensions); - if (offers[PerMessageDeflate2.extensionName]) { - perMessageDeflate.accept(offers[PerMessageDeflate2.extensionName]); - extensions[PerMessageDeflate2.extensionName] = perMessageDeflate; - } - } catch (err) { - const message2 = "Invalid or unacceptable Sec-WebSocket-Extensions header"; - abortHandshakeOrEmitwsClientError(this, req, socket, 400, message2); - return; - } - } - if (this.options.verifyClient) { - const info2 = { - origin: req.headers[`${version3 === 8 ? "sec-websocket-origin" : "origin"}`], - secure: !!(req.socket.authorized || req.socket.encrypted), - req - }; - if (this.options.verifyClient.length === 2) { - this.options.verifyClient(info2, (verified, code, message2, headers) => { - if (!verified) { - return abortHandshake(socket, code || 401, message2, headers); - } - this.completeUpgrade( - extensions, - key, - protocols, - req, - socket, - head, - cb - ); - }); - return; - } - if (!this.options.verifyClient(info2)) return abortHandshake(socket, 401); - } - this.completeUpgrade(extensions, key, protocols, req, socket, head, cb); - } - /** - * Upgrade the connection to WebSocket. - * - * @param {Object} extensions The accepted extensions - * @param {String} key The value of the `Sec-WebSocket-Key` header - * @param {Set} protocols The subprotocols - * @param {http.IncomingMessage} req The request object - * @param {Duplex} socket The network socket between the server and client - * @param {Buffer} head The first packet of the upgraded stream - * @param {Function} cb Callback - * @throws {Error} If called more than once with the same socket - * @private - */ - completeUpgrade(extensions, key, protocols, req, socket, head, cb) { - if (!socket.readable || !socket.writable) return socket.destroy(); - if (socket[kWebSocket]) { - throw new Error( - "server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration" - ); - } - if (this._state > RUNNING) return abortHandshake(socket, 503); - const digest2 = createHash18("sha1").update(key + GUID).digest("base64"); - const headers = [ - "HTTP/1.1 101 Switching Protocols", - "Upgrade: websocket", - "Connection: Upgrade", - `Sec-WebSocket-Accept: ${digest2}` - ]; - const ws = new this.options.WebSocket(null, void 0, this.options); - if (protocols.size) { - const protocol = this.options.handleProtocols ? this.options.handleProtocols(protocols, req) : protocols.values().next().value; - if (protocol) { - headers.push(`Sec-WebSocket-Protocol: ${protocol}`); - ws._protocol = protocol; - } - } - if (extensions[PerMessageDeflate2.extensionName]) { - const params = extensions[PerMessageDeflate2.extensionName].params; - const value = extension2.format({ - [PerMessageDeflate2.extensionName]: [params] - }); - headers.push(`Sec-WebSocket-Extensions: ${value}`); - ws._extensions = extensions; - } - this.emit("headers", headers, req); - socket.write(headers.concat("\r\n").join("\r\n")); - socket.removeListener("error", socketOnError); - ws.setSocket(socket, head, { - allowSynchronousEvents: this.options.allowSynchronousEvents, - maxPayload: this.options.maxPayload, - skipUTF8Validation: this.options.skipUTF8Validation - }); - if (this.clients) { - this.clients.add(ws); - ws.on("close", () => { - this.clients.delete(ws); - if (this._shouldEmitClose && !this.clients.size) { - process.nextTick(emitClose, this); - } - }); - } - cb(ws, req); - } - }; - module.exports = WebSocketServer2; - function addListeners(server, map4) { - for (const event of Object.keys(map4)) server.on(event, map4[event]); - return function removeListeners() { - for (const event of Object.keys(map4)) { - server.removeListener(event, map4[event]); - } - }; - } - function emitClose(server) { - server._state = CLOSED; - server.emit("close"); - } - function socketOnError() { - this.destroy(); - } - function abortHandshake(socket, code, message2, headers) { - message2 = message2 || http.STATUS_CODES[code]; - headers = { - Connection: "close", - "Content-Type": "text/html", - "Content-Length": Buffer.byteLength(message2), - ...headers - }; - socket.once("finish", socket.destroy); - socket.end( - `HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r -` + Object.keys(headers).map((h5) => `${h5}: ${headers[h5]}`).join("\r\n") + "\r\n\r\n" + message2 - ); - } - function abortHandshakeOrEmitwsClientError(server, req, socket, code, message2, headers) { - if (server.listenerCount("wsClientError")) { - const err = new Error(message2); - Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError); - server.emit("wsClientError", err, socket, req); - } else { - abortHandshake(socket, code, message2, headers); - } - } - } -}); - -// node_modules/.pnpm/dotenv@17.4.2/node_modules/dotenv/lib/main.js -var require_main = __commonJS({ - "node_modules/.pnpm/dotenv@17.4.2/node_modules/dotenv/lib/main.js"(exports, module) { - var fs41 = __require("fs"); - var path53 = __require("path"); - var os24 = __require("os"); - var crypto6 = __require("crypto"); - var TIPS = [ - "\u25C8 encrypted .env [www.dotenvx.com]", - "\u25C8 secrets for agents [www.dotenvx.com]", - "\u2301 auth for agents [www.vestauth.com]", - "\u2318 custom filepath { path: '/custom/path/.env' }", - "\u2318 enable debugging { debug: true }", - "\u2318 override existing { override: true }", - "\u2318 suppress logs { quiet: true }", - "\u2318 multiple files { path: ['.env.local', '.env'] }" - ]; - function _getRandomTip() { - return TIPS[Math.floor(Math.random() * TIPS.length)]; - } - function parseBoolean3(value) { - if (typeof value === "string") { - return !["false", "0", "no", "off", ""].includes(value.toLowerCase()); - } - return Boolean(value); - } - function supportsAnsi() { - return process.stdout.isTTY; - } - function dim(text3) { - return supportsAnsi() ? `\x1B[2m${text3}\x1B[0m` : text3; - } - var LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg; - function parse5(src) { - const obj = {}; - let lines = src.toString(); - lines = lines.replace(/\r\n?/mg, "\n"); - let match; - while ((match = LINE.exec(lines)) != null) { - const key = match[1]; - let value = match[2] || ""; - value = value.trim(); - const maybeQuote = value[0]; - value = value.replace(/^(['"`])([\s\S]*)\1$/mg, "$2"); - if (maybeQuote === '"') { - value = value.replace(/\\n/g, "\n"); - value = value.replace(/\\r/g, "\r"); - } - obj[key] = value; - } - return obj; - } - function _parseVault(options) { - options = options || {}; - const vaultPath = _vaultPath(options); - options.path = vaultPath; - const result = DotenvModule.configDotenv(options); - if (!result.parsed) { - const err = new Error(`MISSING_DATA: Cannot parse ${vaultPath} for an unknown reason`); - err.code = "MISSING_DATA"; - throw err; - } - const keys = _dotenvKey(options).split(","); - const length = keys.length; - let decrypted; - for (let i5 = 0; i5 < length; i5++) { - try { - const key = keys[i5].trim(); - const attrs = _instructions(result, key); - decrypted = DotenvModule.decrypt(attrs.ciphertext, attrs.key); - break; - } catch (error50) { - if (i5 + 1 >= length) { - throw error50; - } - } - } - return DotenvModule.parse(decrypted); - } - function _warn(message2) { - console.error(`\u26A0 ${message2}`); - } - function _debug(message2) { - console.log(`\u2506 ${message2}`); - } - function _log(message2) { - console.log(`\u25C7 ${message2}`); - } - function _dotenvKey(options) { - if (options && options.DOTENV_KEY && options.DOTENV_KEY.length > 0) { - return options.DOTENV_KEY; - } - if (process.env.DOTENV_KEY && process.env.DOTENV_KEY.length > 0) { - return process.env.DOTENV_KEY; - } - return ""; - } - function _instructions(result, dotenvKey) { - let uri; - try { - uri = new URL(dotenvKey); - } catch (error50) { - if (error50.code === "ERR_INVALID_URL") { - const err = new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development"); - err.code = "INVALID_DOTENV_KEY"; - throw err; - } - throw error50; - } - const key = uri.password; - if (!key) { - const err = new Error("INVALID_DOTENV_KEY: Missing key part"); - err.code = "INVALID_DOTENV_KEY"; - throw err; - } - const environment = uri.searchParams.get("environment"); - if (!environment) { - const err = new Error("INVALID_DOTENV_KEY: Missing environment part"); - err.code = "INVALID_DOTENV_KEY"; - throw err; - } - const environmentKey = `DOTENV_VAULT_${environment.toUpperCase()}`; - const ciphertext = result.parsed[environmentKey]; - if (!ciphertext) { - const err = new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${environmentKey} in your .env.vault file.`); - err.code = "NOT_FOUND_DOTENV_ENVIRONMENT"; - throw err; - } - return { ciphertext, key }; - } - function _vaultPath(options) { - let possibleVaultPath = null; - if (options && options.path && options.path.length > 0) { - if (Array.isArray(options.path)) { - for (const filepath of options.path) { - if (fs41.existsSync(filepath)) { - possibleVaultPath = filepath.endsWith(".vault") ? filepath : `${filepath}.vault`; - } - } - } else { - possibleVaultPath = options.path.endsWith(".vault") ? options.path : `${options.path}.vault`; - } - } else { - possibleVaultPath = path53.resolve(process.cwd(), ".env.vault"); - } - if (fs41.existsSync(possibleVaultPath)) { - return possibleVaultPath; - } - return null; - } - function _resolveHome(envPath) { - return envPath[0] === "~" ? path53.join(os24.homedir(), envPath.slice(1)) : envPath; - } - function _configVault(options) { - const debug = parseBoolean3(process.env.DOTENV_CONFIG_DEBUG || options && options.debug); - const quiet = parseBoolean3(process.env.DOTENV_CONFIG_QUIET || options && options.quiet); - if (debug || !quiet) { - _log("loading env from encrypted .env.vault"); - } - const parsed = DotenvModule._parseVault(options); - let processEnv = process.env; - if (options && options.processEnv != null) { - processEnv = options.processEnv; - } - DotenvModule.populate(processEnv, parsed, options); - return { parsed }; - } - function configDotenv(options) { - const dotenvPath = path53.resolve(process.cwd(), ".env"); - let encoding = "utf8"; - let processEnv = process.env; - if (options && options.processEnv != null) { - processEnv = options.processEnv; - } - let debug = parseBoolean3(processEnv.DOTENV_CONFIG_DEBUG || options && options.debug); - let quiet = parseBoolean3(processEnv.DOTENV_CONFIG_QUIET || options && options.quiet); - if (options && options.encoding) { - encoding = options.encoding; - } else { - if (debug) { - _debug("no encoding is specified (UTF-8 is used by default)"); - } - } - let optionPaths = [dotenvPath]; - if (options && options.path) { - if (!Array.isArray(options.path)) { - optionPaths = [_resolveHome(options.path)]; - } else { - optionPaths = []; - for (const filepath of options.path) { - optionPaths.push(_resolveHome(filepath)); - } - } - } - let lastError; - const parsedAll = {}; - for (const path54 of optionPaths) { - try { - const parsed = DotenvModule.parse(fs41.readFileSync(path54, { encoding })); - DotenvModule.populate(parsedAll, parsed, options); - } catch (e5) { - if (debug) { - _debug(`failed to load ${path54} ${e5.message}`); - } - lastError = e5; - } - } - const populated = DotenvModule.populate(processEnv, parsedAll, options); - debug = parseBoolean3(processEnv.DOTENV_CONFIG_DEBUG || debug); - quiet = parseBoolean3(processEnv.DOTENV_CONFIG_QUIET || quiet); - if (debug || !quiet) { - const keysCount = Object.keys(populated).length; - const shortPaths = []; - for (const filePath of optionPaths) { - try { - const relative3 = path53.relative(process.cwd(), filePath); - shortPaths.push(relative3); - } catch (e5) { - if (debug) { - _debug(`failed to load ${filePath} ${e5.message}`); - } - lastError = e5; - } - } - _log(`injected env (${keysCount}) from ${shortPaths.join(",")} ${dim(`// tip: ${_getRandomTip()}`)}`); - } - if (lastError) { - return { parsed: parsedAll, error: lastError }; - } else { - return { parsed: parsedAll }; - } - } - function config3(options) { - if (_dotenvKey(options).length === 0) { - return DotenvModule.configDotenv(options); - } - const vaultPath = _vaultPath(options); - if (!vaultPath) { - _warn(`you set DOTENV_KEY but you are missing a .env.vault file at ${vaultPath}`); - return DotenvModule.configDotenv(options); - } - return DotenvModule._configVault(options); - } - function decrypt3(encrypted, keyStr) { - const key = Buffer.from(keyStr.slice(-64), "hex"); - let ciphertext = Buffer.from(encrypted, "base64"); - const nonce = ciphertext.subarray(0, 12); - const authTag = ciphertext.subarray(-16); - ciphertext = ciphertext.subarray(12, -16); - try { - const aesgcm = crypto6.createDecipheriv("aes-256-gcm", key, nonce); - aesgcm.setAuthTag(authTag); - return `${aesgcm.update(ciphertext)}${aesgcm.final()}`; - } catch (error50) { - const isRange = error50 instanceof RangeError; - const invalidKeyLength = error50.message === "Invalid key length"; - const decryptionFailed = error50.message === "Unsupported state or unable to authenticate data"; - if (isRange || invalidKeyLength) { - const err = new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)"); - err.code = "INVALID_DOTENV_KEY"; - throw err; - } else if (decryptionFailed) { - const err = new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY"); - err.code = "DECRYPTION_FAILED"; - throw err; - } else { - throw error50; - } - } - } - function populate(processEnv, parsed, options = {}) { - const debug = Boolean(options && options.debug); - const override = Boolean(options && options.override); - const populated = {}; - if (typeof parsed !== "object") { - const err = new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate"); - err.code = "OBJECT_REQUIRED"; - throw err; - } - for (const key of Object.keys(parsed)) { - if (Object.prototype.hasOwnProperty.call(processEnv, key)) { - if (override === true) { - processEnv[key] = parsed[key]; - populated[key] = parsed[key]; - } - if (debug) { - if (override === true) { - _debug(`"${key}" is already defined and WAS overwritten`); - } else { - _debug(`"${key}" is already defined and was NOT overwritten`); - } - } - } else { - processEnv[key] = parsed[key]; - populated[key] = parsed[key]; - } - } - return populated; - } - var DotenvModule = { - configDotenv, - _configVault, - _parseVault, - config: config3, - decrypt: decrypt3, - parse: parse5, - populate - }; - module.exports.configDotenv = DotenvModule.configDotenv; - module.exports._configVault = DotenvModule._configVault; - module.exports._parseVault = DotenvModule._parseVault; - module.exports.config = DotenvModule.config; - module.exports.decrypt = DotenvModule.decrypt; - module.exports.parse = DotenvModule.parse; - module.exports.populate = DotenvModule.populate; - module.exports = DotenvModule; - } -}); - -// node_modules/.pnpm/@smithy+types@4.14.0/node_modules/@smithy/types/dist-cjs/index.js -var require_dist_cjs = __commonJS({ - "node_modules/.pnpm/@smithy+types@4.14.0/node_modules/@smithy/types/dist-cjs/index.js"(exports) { - "use strict"; - exports.HttpAuthLocation = void 0; - (function(HttpAuthLocation) { - HttpAuthLocation["HEADER"] = "header"; - HttpAuthLocation["QUERY"] = "query"; - })(exports.HttpAuthLocation || (exports.HttpAuthLocation = {})); - exports.HttpApiKeyAuthLocation = void 0; - (function(HttpApiKeyAuthLocation2) { - HttpApiKeyAuthLocation2["HEADER"] = "header"; - HttpApiKeyAuthLocation2["QUERY"] = "query"; - })(exports.HttpApiKeyAuthLocation || (exports.HttpApiKeyAuthLocation = {})); - exports.EndpointURLScheme = void 0; - (function(EndpointURLScheme) { - EndpointURLScheme["HTTP"] = "http"; - EndpointURLScheme["HTTPS"] = "https"; - })(exports.EndpointURLScheme || (exports.EndpointURLScheme = {})); - exports.AlgorithmId = void 0; - (function(AlgorithmId) { - AlgorithmId["MD5"] = "md5"; - AlgorithmId["CRC32"] = "crc32"; - AlgorithmId["CRC32C"] = "crc32c"; - AlgorithmId["SHA1"] = "sha1"; - AlgorithmId["SHA256"] = "sha256"; - })(exports.AlgorithmId || (exports.AlgorithmId = {})); - var getChecksumConfiguration = (runtimeConfig) => { - const checksumAlgorithms = []; - if (runtimeConfig.sha256 !== void 0) { - checksumAlgorithms.push({ - algorithmId: () => exports.AlgorithmId.SHA256, - checksumConstructor: () => runtimeConfig.sha256 - }); - } - if (runtimeConfig.md5 != void 0) { - checksumAlgorithms.push({ - algorithmId: () => exports.AlgorithmId.MD5, - checksumConstructor: () => runtimeConfig.md5 - }); - } - return { - addChecksumAlgorithm(algo) { - checksumAlgorithms.push(algo); - }, - checksumAlgorithms() { - return checksumAlgorithms; - } - }; - }; - var resolveChecksumRuntimeConfig = (clientConfig) => { - const runtimeConfig = {}; - clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { - runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); - }); - return runtimeConfig; - }; - var getDefaultClientConfiguration = (runtimeConfig) => { - return getChecksumConfiguration(runtimeConfig); - }; - var resolveDefaultRuntimeConfig5 = (config3) => { - return resolveChecksumRuntimeConfig(config3); - }; - exports.FieldPosition = void 0; - (function(FieldPosition) { - FieldPosition[FieldPosition["HEADER"] = 0] = "HEADER"; - FieldPosition[FieldPosition["TRAILER"] = 1] = "TRAILER"; - })(exports.FieldPosition || (exports.FieldPosition = {})); - var SMITHY_CONTEXT_KEY2 = "__smithy_context"; - exports.IniSectionType = void 0; - (function(IniSectionType) { - IniSectionType["PROFILE"] = "profile"; - IniSectionType["SSO_SESSION"] = "sso-session"; - IniSectionType["SERVICES"] = "services"; - })(exports.IniSectionType || (exports.IniSectionType = {})); - exports.RequestHandlerProtocol = void 0; - (function(RequestHandlerProtocol) { - RequestHandlerProtocol["HTTP_0_9"] = "http/0.9"; - RequestHandlerProtocol["HTTP_1_0"] = "http/1.0"; - RequestHandlerProtocol["TDS_8_0"] = "tds/8.0"; - })(exports.RequestHandlerProtocol || (exports.RequestHandlerProtocol = {})); - exports.SMITHY_CONTEXT_KEY = SMITHY_CONTEXT_KEY2; - exports.getDefaultClientConfiguration = getDefaultClientConfiguration; - exports.resolveDefaultRuntimeConfig = resolveDefaultRuntimeConfig5; - } -}); - -// node_modules/.pnpm/@smithy+protocol-http@5.3.13/node_modules/@smithy/protocol-http/dist-cjs/index.js -var require_dist_cjs2 = __commonJS({ - "node_modules/.pnpm/@smithy+protocol-http@5.3.13/node_modules/@smithy/protocol-http/dist-cjs/index.js"(exports) { - "use strict"; - var types2 = require_dist_cjs(); - var getHttpHandlerExtensionConfiguration5 = (runtimeConfig) => { - return { - setHttpHandler(handler) { - runtimeConfig.httpHandler = handler; - }, - httpHandler() { - return runtimeConfig.httpHandler; - }, - updateHttpClientConfig(key, value) { - runtimeConfig.httpHandler?.updateHttpClientConfig(key, value); - }, - httpHandlerConfigs() { - return runtimeConfig.httpHandler.httpHandlerConfigs(); - } - }; - }; - var resolveHttpHandlerRuntimeConfig5 = (httpHandlerExtensionConfiguration) => { - return { - httpHandler: httpHandlerExtensionConfiguration.httpHandler() - }; - }; - var Field = class { - name; - kind; - values; - constructor({ name, kind = types2.FieldPosition.HEADER, values: values2 = [] }) { - this.name = name; - this.kind = kind; - this.values = values2; - } - add(value) { - this.values.push(value); - } - set(values2) { - this.values = values2; - } - remove(value) { - this.values = this.values.filter((v5) => v5 !== value); - } - toString() { - return this.values.map((v5) => v5.includes(",") || v5.includes(" ") ? `"${v5}"` : v5).join(", "); - } - get() { - return this.values; - } - }; - var Fields = class { - entries = {}; - encoding; - constructor({ fields = [], encoding = "utf-8" }) { - fields.forEach(this.setField.bind(this)); - this.encoding = encoding; - } - setField(field) { - this.entries[field.name.toLowerCase()] = field; - } - getField(name) { - return this.entries[name.toLowerCase()]; - } - removeField(name) { - delete this.entries[name.toLowerCase()]; - } - getByType(kind) { - return Object.values(this.entries).filter((field) => field.kind === kind); - } - }; - var HttpRequest10 = class _HttpRequest { - method; - protocol; - hostname; - port; - path; - query; - headers; - username; - password; - fragment; - body; - constructor(options) { - this.method = options.method || "GET"; - this.hostname = options.hostname || "localhost"; - this.port = options.port; - this.query = options.query || {}; - this.headers = options.headers || {}; - this.body = options.body; - this.protocol = options.protocol ? options.protocol.slice(-1) !== ":" ? `${options.protocol}:` : options.protocol : "https:"; - this.path = options.path ? options.path.charAt(0) !== "/" ? `/${options.path}` : options.path : "/"; - this.username = options.username; - this.password = options.password; - this.fragment = options.fragment; - } - static clone(request) { - const cloned = new _HttpRequest({ - ...request, - headers: { ...request.headers } - }); - if (cloned.query) { - cloned.query = cloneQuery(cloned.query); - } - return cloned; - } - static isInstance(request) { - if (!request) { - return false; - } - const req = request; - return "method" in req && "protocol" in req && "hostname" in req && "path" in req && typeof req["query"] === "object" && typeof req["headers"] === "object"; - } - clone() { - return _HttpRequest.clone(this); - } - }; - function cloneQuery(query) { - return Object.keys(query).reduce((carry, paramName) => { - const param = query[paramName]; - return { - ...carry, - [paramName]: Array.isArray(param) ? [...param] : param - }; - }, {}); - } - var HttpResponse4 = class { - statusCode; - reason; - headers; - body; - constructor(options) { - this.statusCode = options.statusCode; - this.reason = options.reason; - this.headers = options.headers || {}; - this.body = options.body; - } - static isInstance(response) { - if (!response) - return false; - const resp = response; - return typeof resp.statusCode === "number" && typeof resp.headers === "object"; - } - }; - function isValidHostname(hostname3) { - const hostPattern = /^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/; - return hostPattern.test(hostname3); - } - exports.Field = Field; - exports.Fields = Fields; - exports.HttpRequest = HttpRequest10; - exports.HttpResponse = HttpResponse4; - exports.getHttpHandlerExtensionConfiguration = getHttpHandlerExtensionConfiguration5; - exports.isValidHostname = isValidHostname; - exports.resolveHttpHandlerRuntimeConfig = resolveHttpHandlerRuntimeConfig5; - } -}); - -// node_modules/.pnpm/@aws-sdk+middleware-expect-continue@3.972.9/node_modules/@aws-sdk/middleware-expect-continue/dist-cjs/index.js -var require_dist_cjs3 = __commonJS({ - "node_modules/.pnpm/@aws-sdk+middleware-expect-continue@3.972.9/node_modules/@aws-sdk/middleware-expect-continue/dist-cjs/index.js"(exports) { - "use strict"; - var protocolHttp = require_dist_cjs2(); - function addExpectContinueMiddleware(options) { - return (next) => async (args) => { - const { request } = args; - if (options.expectContinueHeader !== false && protocolHttp.HttpRequest.isInstance(request) && request.body && options.runtime === "node" && options.requestHandler?.constructor?.name !== "FetchHttpHandler") { - let sendHeader = true; - if (typeof options.expectContinueHeader === "number") { - try { - const bodyLength = Number(request.headers?.["content-length"]) ?? options.bodyLengthChecker?.(request.body) ?? Infinity; - sendHeader = bodyLength >= options.expectContinueHeader; - } catch (e5) { - } - } else { - sendHeader = !!options.expectContinueHeader; - } - if (sendHeader) { - request.headers.Expect = "100-continue"; - } - } - return next({ - ...args, - request - }); - }; - } - var addExpectContinueMiddlewareOptions = { - step: "build", - tags: ["SET_EXPECT_HEADER", "EXPECT_HEADER"], - name: "addExpectContinueMiddleware", - override: true - }; - var getAddExpectContinuePlugin = (options) => ({ - applyToStack: (clientStack) => { - clientStack.add(addExpectContinueMiddleware(options), addExpectContinueMiddlewareOptions); - } - }); - exports.addExpectContinueMiddleware = addExpectContinueMiddleware; - exports.addExpectContinueMiddlewareOptions = addExpectContinueMiddlewareOptions; - exports.getAddExpectContinuePlugin = getAddExpectContinuePlugin; - } -}); - -// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/client/emitWarningIfUnsupportedVersion.js -var state, emitWarningIfUnsupportedVersion; -var init_emitWarningIfUnsupportedVersion = __esm({ - "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/client/emitWarningIfUnsupportedVersion.js"() { - state = { - warningEmitted: false - }; - emitWarningIfUnsupportedVersion = (version3) => { - if (version3 && !state.warningEmitted && parseInt(version3.substring(1, version3.indexOf("."))) < 20) { - state.warningEmitted = true; - process.emitWarning(`NodeDeprecationWarning: The AWS SDK for JavaScript (v3) will -no longer support Node.js ${version3} in January 2026. - -To continue receiving updates to AWS services, bug fixes, and security -updates please upgrade to a supported Node.js LTS version. - -More information can be found at: https://a.co/c895JFp`); - } - }; - } -}); - -// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/client/longPollMiddleware.js -var longPollMiddleware, longPollMiddlewareOptions, getLongPollPlugin; -var init_longPollMiddleware = __esm({ - "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/client/longPollMiddleware.js"() { - longPollMiddleware = () => (next, context) => async (args) => { - context.__retryLongPoll = true; - return next(args); - }; - longPollMiddlewareOptions = { - name: "longPollMiddleware", - tags: ["RETRY"], - step: "initialize", - override: true - }; - getLongPollPlugin = (options) => ({ - applyToStack: (clientStack) => { - clientStack.add(longPollMiddleware(), longPollMiddlewareOptions); - } - }); - } -}); - -// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/client/setCredentialFeature.js -function setCredentialFeature(credentials, feature, value) { - if (!credentials.$source) { - credentials.$source = {}; - } - credentials.$source[feature] = value; - return credentials; -} -var init_setCredentialFeature = __esm({ - "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/client/setCredentialFeature.js"() { - } -}); - -// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/client/setFeature.js -function setFeature(context, feature, value) { - if (!context.__aws_sdk_context) { - context.__aws_sdk_context = { - features: {} - }; - } else if (!context.__aws_sdk_context.features) { - context.__aws_sdk_context.features = {}; - } - context.__aws_sdk_context.features[feature] = value; -} -var init_setFeature = __esm({ - "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/client/setFeature.js"() { - } -}); - -// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/client/setTokenFeature.js -function setTokenFeature(token, feature, value) { - if (!token.$source) { - token.$source = {}; - } - token.$source[feature] = value; - return token; -} -var init_setTokenFeature = __esm({ - "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/client/setTokenFeature.js"() { - } -}); - -// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/client/index.js -var client_exports = {}; -__export(client_exports, { - emitWarningIfUnsupportedVersion: () => emitWarningIfUnsupportedVersion, - getLongPollPlugin: () => getLongPollPlugin, - setCredentialFeature: () => setCredentialFeature, - setFeature: () => setFeature, - setTokenFeature: () => setTokenFeature, - state: () => state -}); -var init_client2 = __esm({ - "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/client/index.js"() { - init_emitWarningIfUnsupportedVersion(); - init_longPollMiddleware(); - init_setCredentialFeature(); - init_setFeature(); - init_setTokenFeature(); - } -}); - -// node_modules/.pnpm/@smithy+is-array-buffer@4.2.2/node_modules/@smithy/is-array-buffer/dist-cjs/index.js -var require_dist_cjs4 = __commonJS({ - "node_modules/.pnpm/@smithy+is-array-buffer@4.2.2/node_modules/@smithy/is-array-buffer/dist-cjs/index.js"(exports) { - "use strict"; - var isArrayBuffer = (arg) => typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer || Object.prototype.toString.call(arg) === "[object ArrayBuffer]"; - exports.isArrayBuffer = isArrayBuffer; - } -}); - -// node_modules/.pnpm/@smithy+util-buffer-from@4.2.2/node_modules/@smithy/util-buffer-from/dist-cjs/index.js -var require_dist_cjs5 = __commonJS({ - "node_modules/.pnpm/@smithy+util-buffer-from@4.2.2/node_modules/@smithy/util-buffer-from/dist-cjs/index.js"(exports) { - "use strict"; - var isArrayBuffer = require_dist_cjs4(); - var buffer2 = __require("buffer"); - var fromArrayBuffer = (input, offset = 0, length = input.byteLength - offset) => { - if (!isArrayBuffer.isArrayBuffer(input)) { - throw new TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof input} (${input})`); - } - return buffer2.Buffer.from(input, offset, length); - }; - var fromString = (input, encoding) => { - if (typeof input !== "string") { - throw new TypeError(`The "input" argument must be of type string. Received type ${typeof input} (${input})`); - } - return encoding ? buffer2.Buffer.from(input, encoding) : buffer2.Buffer.from(input); - }; - exports.fromArrayBuffer = fromArrayBuffer; - exports.fromString = fromString; - } -}); - -// node_modules/.pnpm/@smithy+util-base64@4.3.2/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js -var require_fromBase64 = __commonJS({ - "node_modules/.pnpm/@smithy+util-base64@4.3.2/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.fromBase64 = void 0; - var util_buffer_from_1 = require_dist_cjs5(); - var BASE64_REGEX = /^[A-Za-z0-9+/]*={0,2}$/; - var fromBase649 = (input) => { - if (input.length * 3 % 4 !== 0) { - throw new TypeError(`Incorrect padding on base64 string.`); - } - if (!BASE64_REGEX.exec(input)) { - throw new TypeError(`Invalid base64 string.`); - } - const buffer2 = (0, util_buffer_from_1.fromString)(input, "base64"); - return new Uint8Array(buffer2.buffer, buffer2.byteOffset, buffer2.byteLength); - }; - exports.fromBase64 = fromBase649; - } -}); - -// node_modules/.pnpm/@smithy+util-utf8@4.2.2/node_modules/@smithy/util-utf8/dist-cjs/index.js -var require_dist_cjs6 = __commonJS({ - "node_modules/.pnpm/@smithy+util-utf8@4.2.2/node_modules/@smithy/util-utf8/dist-cjs/index.js"(exports) { - "use strict"; - var utilBufferFrom = require_dist_cjs5(); - var fromUtf88 = (input) => { - const buf = utilBufferFrom.fromString(input, "utf8"); - return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength / Uint8Array.BYTES_PER_ELEMENT); - }; - var toUint8Array2 = (data2) => { - if (typeof data2 === "string") { - return fromUtf88(data2); - } - if (ArrayBuffer.isView(data2)) { - return new Uint8Array(data2.buffer, data2.byteOffset, data2.byteLength / Uint8Array.BYTES_PER_ELEMENT); - } - return new Uint8Array(data2); - }; - var toUtf811 = (input) => { - if (typeof input === "string") { - return input; - } - if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") { - throw new Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array."); - } - return utilBufferFrom.fromArrayBuffer(input.buffer, input.byteOffset, input.byteLength).toString("utf8"); - }; - exports.fromUtf8 = fromUtf88; - exports.toUint8Array = toUint8Array2; - exports.toUtf8 = toUtf811; - } -}); - -// node_modules/.pnpm/@smithy+util-base64@4.3.2/node_modules/@smithy/util-base64/dist-cjs/toBase64.js -var require_toBase64 = __commonJS({ - "node_modules/.pnpm/@smithy+util-base64@4.3.2/node_modules/@smithy/util-base64/dist-cjs/toBase64.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.toBase64 = void 0; - var util_buffer_from_1 = require_dist_cjs5(); - var util_utf8_1 = require_dist_cjs6(); - var toBase649 = (_input) => { - let input; - if (typeof _input === "string") { - input = (0, util_utf8_1.fromUtf8)(_input); - } else { - input = _input; - } - if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") { - throw new Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array."); - } - return (0, util_buffer_from_1.fromArrayBuffer)(input.buffer, input.byteOffset, input.byteLength).toString("base64"); - }; - exports.toBase64 = toBase649; - } -}); - -// node_modules/.pnpm/@smithy+util-base64@4.3.2/node_modules/@smithy/util-base64/dist-cjs/index.js -var require_dist_cjs7 = __commonJS({ - "node_modules/.pnpm/@smithy+util-base64@4.3.2/node_modules/@smithy/util-base64/dist-cjs/index.js"(exports) { - "use strict"; - var fromBase649 = require_fromBase64(); - var toBase649 = require_toBase64(); - Object.prototype.hasOwnProperty.call(fromBase649, "__proto__") && !Object.prototype.hasOwnProperty.call(exports, "__proto__") && Object.defineProperty(exports, "__proto__", { - enumerable: true, - value: fromBase649["__proto__"] - }); - Object.keys(fromBase649).forEach(function(k5) { - if (k5 !== "default" && !Object.prototype.hasOwnProperty.call(exports, k5)) exports[k5] = fromBase649[k5]; - }); - Object.prototype.hasOwnProperty.call(toBase649, "__proto__") && !Object.prototype.hasOwnProperty.call(exports, "__proto__") && Object.defineProperty(exports, "__proto__", { - enumerable: true, - value: toBase649["__proto__"] - }); - Object.keys(toBase649).forEach(function(k5) { - if (k5 !== "default" && !Object.prototype.hasOwnProperty.call(exports, k5)) exports[k5] = toBase649[k5]; - }); - } -}); - -// node_modules/.pnpm/@smithy+util-stream@4.5.22/node_modules/@smithy/util-stream/dist-cjs/checksum/ChecksumStream.js -var require_ChecksumStream = __commonJS({ - "node_modules/.pnpm/@smithy+util-stream@4.5.22/node_modules/@smithy/util-stream/dist-cjs/checksum/ChecksumStream.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.ChecksumStream = void 0; - var util_base64_1 = require_dist_cjs7(); - var stream_1 = __require("stream"); - var ChecksumStream = class extends stream_1.Duplex { - expectedChecksum; - checksumSourceLocation; - checksum; - source; - base64Encoder; - pendingCallback = null; - constructor({ expectedChecksum, checksum, source, checksumSourceLocation, base64Encoder }) { - super(); - if (typeof source.pipe === "function") { - this.source = source; - } else { - throw new Error(`@smithy/util-stream: unsupported source type ${source?.constructor?.name ?? source} in ChecksumStream.`); - } - this.base64Encoder = base64Encoder ?? util_base64_1.toBase64; - this.expectedChecksum = expectedChecksum; - this.checksum = checksum; - this.checksumSourceLocation = checksumSourceLocation; - this.source.pipe(this); - } - _read(size2) { - if (this.pendingCallback) { - const callback = this.pendingCallback; - this.pendingCallback = null; - callback(); - } - } - _write(chunk, encoding, callback) { - try { - this.checksum.update(chunk); - const canPushMore = this.push(chunk); - if (!canPushMore) { - this.pendingCallback = callback; - return; - } - } catch (e5) { - return callback(e5); - } - return callback(); - } - async _final(callback) { - try { - const digest2 = await this.checksum.digest(); - const received = this.base64Encoder(digest2); - if (this.expectedChecksum !== received) { - return callback(new Error(`Checksum mismatch: expected "${this.expectedChecksum}" but received "${received}" in response header "${this.checksumSourceLocation}".`)); - } - } catch (e5) { - return callback(e5); - } - this.push(null); - return callback(); - } - }; - exports.ChecksumStream = ChecksumStream; - } -}); - -// node_modules/.pnpm/@smithy+util-stream@4.5.22/node_modules/@smithy/util-stream/dist-cjs/stream-type-check.js -var require_stream_type_check = __commonJS({ - "node_modules/.pnpm/@smithy+util-stream@4.5.22/node_modules/@smithy/util-stream/dist-cjs/stream-type-check.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.isBlob = exports.isReadableStream = void 0; - var isReadableStream = (stream) => typeof ReadableStream === "function" && (stream?.constructor?.name === ReadableStream.name || stream instanceof ReadableStream); - exports.isReadableStream = isReadableStream; - var isBlob = (blob) => { - return typeof Blob === "function" && (blob?.constructor?.name === Blob.name || blob instanceof Blob); - }; - exports.isBlob = isBlob; - } -}); - -// node_modules/.pnpm/@smithy+util-stream@4.5.22/node_modules/@smithy/util-stream/dist-cjs/checksum/ChecksumStream.browser.js -var require_ChecksumStream_browser = __commonJS({ - "node_modules/.pnpm/@smithy+util-stream@4.5.22/node_modules/@smithy/util-stream/dist-cjs/checksum/ChecksumStream.browser.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.ChecksumStream = void 0; - var ReadableStreamRef = typeof ReadableStream === "function" ? ReadableStream : function() { - }; - var ChecksumStream = class extends ReadableStreamRef { - }; - exports.ChecksumStream = ChecksumStream; - } -}); - -// node_modules/.pnpm/@smithy+util-stream@4.5.22/node_modules/@smithy/util-stream/dist-cjs/checksum/createChecksumStream.browser.js -var require_createChecksumStream_browser = __commonJS({ - "node_modules/.pnpm/@smithy+util-stream@4.5.22/node_modules/@smithy/util-stream/dist-cjs/checksum/createChecksumStream.browser.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.createChecksumStream = void 0; - var util_base64_1 = require_dist_cjs7(); - var stream_type_check_1 = require_stream_type_check(); - var ChecksumStream_browser_1 = require_ChecksumStream_browser(); - var createChecksumStream = ({ expectedChecksum, checksum, source, checksumSourceLocation, base64Encoder }) => { - if (!(0, stream_type_check_1.isReadableStream)(source)) { - throw new Error(`@smithy/util-stream: unsupported source type ${source?.constructor?.name ?? source} in ChecksumStream.`); - } - const encoder3 = base64Encoder ?? util_base64_1.toBase64; - if (typeof TransformStream !== "function") { - throw new Error("@smithy/util-stream: unable to instantiate ChecksumStream because API unavailable: ReadableStream/TransformStream."); - } - const transform3 = new TransformStream({ - start() { - }, - async transform(chunk, controller) { - checksum.update(chunk); - controller.enqueue(chunk); - }, - async flush(controller) { - const digest2 = await checksum.digest(); - const received = encoder3(digest2); - if (expectedChecksum !== received) { - const error50 = new Error(`Checksum mismatch: expected "${expectedChecksum}" but received "${received}" in response header "${checksumSourceLocation}".`); - controller.error(error50); - } else { - controller.terminate(); - } - } - }); - source.pipeThrough(transform3); - const readable = transform3.readable; - Object.setPrototypeOf(readable, ChecksumStream_browser_1.ChecksumStream.prototype); - return readable; - }; - exports.createChecksumStream = createChecksumStream; - } -}); - -// node_modules/.pnpm/@smithy+util-stream@4.5.22/node_modules/@smithy/util-stream/dist-cjs/checksum/createChecksumStream.js -var require_createChecksumStream = __commonJS({ - "node_modules/.pnpm/@smithy+util-stream@4.5.22/node_modules/@smithy/util-stream/dist-cjs/checksum/createChecksumStream.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.createChecksumStream = createChecksumStream; - var stream_type_check_1 = require_stream_type_check(); - var ChecksumStream_1 = require_ChecksumStream(); - var createChecksumStream_browser_1 = require_createChecksumStream_browser(); - function createChecksumStream(init2) { - if (typeof ReadableStream === "function" && (0, stream_type_check_1.isReadableStream)(init2.source)) { - return (0, createChecksumStream_browser_1.createChecksumStream)(init2); - } - return new ChecksumStream_1.ChecksumStream(init2); - } - } -}); - -// node_modules/.pnpm/@smithy+util-stream@4.5.22/node_modules/@smithy/util-stream/dist-cjs/ByteArrayCollector.js -var require_ByteArrayCollector = __commonJS({ - "node_modules/.pnpm/@smithy+util-stream@4.5.22/node_modules/@smithy/util-stream/dist-cjs/ByteArrayCollector.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.ByteArrayCollector = void 0; - var ByteArrayCollector = class { - allocByteArray; - byteLength = 0; - byteArrays = []; - constructor(allocByteArray) { - this.allocByteArray = allocByteArray; - } - push(byteArray) { - this.byteArrays.push(byteArray); - this.byteLength += byteArray.byteLength; - } - flush() { - if (this.byteArrays.length === 1) { - const bytes = this.byteArrays[0]; - this.reset(); - return bytes; - } - const aggregation = this.allocByteArray(this.byteLength); - let cursor2 = 0; - for (let i5 = 0; i5 < this.byteArrays.length; ++i5) { - const bytes = this.byteArrays[i5]; - aggregation.set(bytes, cursor2); - cursor2 += bytes.byteLength; - } - this.reset(); - return aggregation; - } - reset() { - this.byteArrays = []; - this.byteLength = 0; - } - }; - exports.ByteArrayCollector = ByteArrayCollector; - } -}); - -// node_modules/.pnpm/@smithy+util-stream@4.5.22/node_modules/@smithy/util-stream/dist-cjs/createBufferedReadableStream.js -var require_createBufferedReadableStream = __commonJS({ - "node_modules/.pnpm/@smithy+util-stream@4.5.22/node_modules/@smithy/util-stream/dist-cjs/createBufferedReadableStream.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.createBufferedReadable = void 0; - exports.createBufferedReadableStream = createBufferedReadableStream; - exports.merge = merge2; - exports.flush = flush; - exports.sizeOf = sizeOf; - exports.modeOf = modeOf; - var ByteArrayCollector_1 = require_ByteArrayCollector(); - function createBufferedReadableStream(upstream, size2, logger4) { - const reader = upstream.getReader(); - let streamBufferingLoggedWarning = false; - let bytesSeen = 0; - const buffers = ["", new ByteArrayCollector_1.ByteArrayCollector((size3) => new Uint8Array(size3))]; - let mode = -1; - const pull = async (controller) => { - const { value, done } = await reader.read(); - const chunk = value; - if (done) { - if (mode !== -1) { - const remainder = flush(buffers, mode); - if (sizeOf(remainder) > 0) { - controller.enqueue(remainder); - } - } - controller.close(); - } else { - const chunkMode = modeOf(chunk, false); - if (mode !== chunkMode) { - if (mode >= 0) { - controller.enqueue(flush(buffers, mode)); - } - mode = chunkMode; - } - if (mode === -1) { - controller.enqueue(chunk); - return; - } - const chunkSize = sizeOf(chunk); - bytesSeen += chunkSize; - const bufferSize = sizeOf(buffers[mode]); - if (chunkSize >= size2 && bufferSize === 0) { - controller.enqueue(chunk); - } else { - const newSize = merge2(buffers, mode, chunk); - if (!streamBufferingLoggedWarning && bytesSeen > size2 * 2) { - streamBufferingLoggedWarning = true; - logger4?.warn(`@smithy/util-stream - stream chunk size ${chunkSize} is below threshold of ${size2}, automatically buffering.`); - } - if (newSize >= size2) { - controller.enqueue(flush(buffers, mode)); - } else { - await pull(controller); - } - } - } - }; - return new ReadableStream({ - pull - }); - } - exports.createBufferedReadable = createBufferedReadableStream; - function merge2(buffers, mode, chunk) { - switch (mode) { - case 0: - buffers[0] += chunk; - return sizeOf(buffers[0]); - case 1: - case 2: - buffers[mode].push(chunk); - return sizeOf(buffers[mode]); - } - } - function flush(buffers, mode) { - switch (mode) { - case 0: - const s5 = buffers[0]; - buffers[0] = ""; - return s5; - case 1: - case 2: - return buffers[mode].flush(); - } - throw new Error(`@smithy/util-stream - invalid index ${mode} given to flush()`); - } - function sizeOf(chunk) { - return chunk?.byteLength ?? chunk?.length ?? 0; - } - function modeOf(chunk, allowBuffer = true) { - if (allowBuffer && typeof Buffer !== "undefined" && chunk instanceof Buffer) { - return 2; - } - if (chunk instanceof Uint8Array) { - return 1; - } - if (typeof chunk === "string") { - return 0; - } - return -1; - } - } -}); - -// node_modules/.pnpm/@smithy+util-stream@4.5.22/node_modules/@smithy/util-stream/dist-cjs/createBufferedReadable.js -var require_createBufferedReadable = __commonJS({ - "node_modules/.pnpm/@smithy+util-stream@4.5.22/node_modules/@smithy/util-stream/dist-cjs/createBufferedReadable.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.createBufferedReadable = createBufferedReadable; - var node_stream_1 = __require("node:stream"); - var ByteArrayCollector_1 = require_ByteArrayCollector(); - var createBufferedReadableStream_1 = require_createBufferedReadableStream(); - var stream_type_check_1 = require_stream_type_check(); - function createBufferedReadable(upstream, size2, logger4) { - if ((0, stream_type_check_1.isReadableStream)(upstream)) { - return (0, createBufferedReadableStream_1.createBufferedReadableStream)(upstream, size2, logger4); - } - const downstream = new node_stream_1.Readable({ read() { - } }); - let streamBufferingLoggedWarning = false; - let bytesSeen = 0; - const buffers = [ - "", - new ByteArrayCollector_1.ByteArrayCollector((size3) => new Uint8Array(size3)), - new ByteArrayCollector_1.ByteArrayCollector((size3) => Buffer.from(new Uint8Array(size3))) - ]; - let mode = -1; - upstream.on("data", (chunk) => { - const chunkMode = (0, createBufferedReadableStream_1.modeOf)(chunk, true); - if (mode !== chunkMode) { - if (mode >= 0) { - downstream.push((0, createBufferedReadableStream_1.flush)(buffers, mode)); - } - mode = chunkMode; - } - if (mode === -1) { - downstream.push(chunk); - return; - } - const chunkSize = (0, createBufferedReadableStream_1.sizeOf)(chunk); - bytesSeen += chunkSize; - const bufferSize = (0, createBufferedReadableStream_1.sizeOf)(buffers[mode]); - if (chunkSize >= size2 && bufferSize === 0) { - downstream.push(chunk); - } else { - const newSize = (0, createBufferedReadableStream_1.merge)(buffers, mode, chunk); - if (!streamBufferingLoggedWarning && bytesSeen > size2 * 2) { - streamBufferingLoggedWarning = true; - logger4?.warn(`@smithy/util-stream - stream chunk size ${chunkSize} is below threshold of ${size2}, automatically buffering.`); - } - if (newSize >= size2) { - downstream.push((0, createBufferedReadableStream_1.flush)(buffers, mode)); - } - } - }); - upstream.on("end", () => { - if (mode !== -1) { - const remainder = (0, createBufferedReadableStream_1.flush)(buffers, mode); - if ((0, createBufferedReadableStream_1.sizeOf)(remainder) > 0) { - downstream.push(remainder); - } - } - downstream.push(null); - }); - return downstream; - } - } -}); - -// node_modules/.pnpm/@smithy+util-stream@4.5.22/node_modules/@smithy/util-stream/dist-cjs/getAwsChunkedEncodingStream.browser.js -var require_getAwsChunkedEncodingStream_browser = __commonJS({ - "node_modules/.pnpm/@smithy+util-stream@4.5.22/node_modules/@smithy/util-stream/dist-cjs/getAwsChunkedEncodingStream.browser.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.getAwsChunkedEncodingStream = void 0; - var getAwsChunkedEncodingStream = (readableStream, options) => { - const { base64Encoder, bodyLengthChecker, checksumAlgorithmFn, checksumLocationName, streamHasher } = options; - const checksumRequired = base64Encoder !== void 0 && bodyLengthChecker !== void 0 && checksumAlgorithmFn !== void 0 && checksumLocationName !== void 0 && streamHasher !== void 0; - const digest2 = checksumRequired ? streamHasher(checksumAlgorithmFn, readableStream) : void 0; - const reader = readableStream.getReader(); - return new ReadableStream({ - async pull(controller) { - const { value, done } = await reader.read(); - if (done) { - controller.enqueue(`0\r -`); - if (checksumRequired) { - const checksum = base64Encoder(await digest2); - controller.enqueue(`${checksumLocationName}:${checksum}\r -`); - controller.enqueue(`\r -`); - } - controller.close(); - } else { - controller.enqueue(`${(bodyLengthChecker(value) || 0).toString(16)}\r -${value}\r -`); - } - } - }); - }; - exports.getAwsChunkedEncodingStream = getAwsChunkedEncodingStream; - } -}); - -// node_modules/.pnpm/@smithy+util-stream@4.5.22/node_modules/@smithy/util-stream/dist-cjs/getAwsChunkedEncodingStream.js -var require_getAwsChunkedEncodingStream = __commonJS({ - "node_modules/.pnpm/@smithy+util-stream@4.5.22/node_modules/@smithy/util-stream/dist-cjs/getAwsChunkedEncodingStream.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.getAwsChunkedEncodingStream = getAwsChunkedEncodingStream; - var node_stream_1 = __require("node:stream"); - var getAwsChunkedEncodingStream_browser_1 = require_getAwsChunkedEncodingStream_browser(); - var stream_type_check_1 = require_stream_type_check(); - function getAwsChunkedEncodingStream(stream, options) { - const readable = stream; - const readableStream = stream; - if ((0, stream_type_check_1.isReadableStream)(readableStream)) { - return (0, getAwsChunkedEncodingStream_browser_1.getAwsChunkedEncodingStream)(readableStream, options); - } - const { base64Encoder, bodyLengthChecker, checksumAlgorithmFn, checksumLocationName, streamHasher } = options; - const checksumRequired = base64Encoder !== void 0 && checksumAlgorithmFn !== void 0 && checksumLocationName !== void 0 && streamHasher !== void 0; - const digest2 = checksumRequired ? streamHasher(checksumAlgorithmFn, readable) : void 0; - const awsChunkedEncodingStream = new node_stream_1.Readable({ - read: () => { - } - }); - readable.on("data", (data2) => { - const length = bodyLengthChecker(data2) || 0; - if (length === 0) { - return; - } - awsChunkedEncodingStream.push(`${length.toString(16)}\r -`); - awsChunkedEncodingStream.push(data2); - awsChunkedEncodingStream.push("\r\n"); - }); - readable.on("end", async () => { - awsChunkedEncodingStream.push(`0\r -`); - if (checksumRequired) { - const checksum = base64Encoder(await digest2); - awsChunkedEncodingStream.push(`${checksumLocationName}:${checksum}\r -`); - awsChunkedEncodingStream.push(`\r -`); - } - awsChunkedEncodingStream.push(null); - }); - return awsChunkedEncodingStream; - } - } -}); - -// node_modules/.pnpm/@smithy+util-stream@4.5.22/node_modules/@smithy/util-stream/dist-cjs/headStream.browser.js -var require_headStream_browser = __commonJS({ - "node_modules/.pnpm/@smithy+util-stream@4.5.22/node_modules/@smithy/util-stream/dist-cjs/headStream.browser.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.headStream = headStream; - async function headStream(stream, bytes) { - let byteLengthCounter = 0; - const chunks = []; - const reader = stream.getReader(); - let isDone = false; - while (!isDone) { - const { done, value } = await reader.read(); - if (value) { - chunks.push(value); - byteLengthCounter += value?.byteLength ?? 0; - } - if (byteLengthCounter >= bytes) { - break; - } - isDone = done; - } - reader.releaseLock(); - const collected = new Uint8Array(Math.min(bytes, byteLengthCounter)); - let offset = 0; - for (const chunk of chunks) { - if (chunk.byteLength > collected.byteLength - offset) { - collected.set(chunk.subarray(0, collected.byteLength - offset), offset); - break; - } else { - collected.set(chunk, offset); - } - offset += chunk.length; - } - return collected; - } - } -}); - -// node_modules/.pnpm/@smithy+util-stream@4.5.22/node_modules/@smithy/util-stream/dist-cjs/headStream.js -var require_headStream = __commonJS({ - "node_modules/.pnpm/@smithy+util-stream@4.5.22/node_modules/@smithy/util-stream/dist-cjs/headStream.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.headStream = void 0; - var stream_1 = __require("stream"); - var headStream_browser_1 = require_headStream_browser(); - var stream_type_check_1 = require_stream_type_check(); - var headStream = (stream, bytes) => { - if ((0, stream_type_check_1.isReadableStream)(stream)) { - return (0, headStream_browser_1.headStream)(stream, bytes); - } - return new Promise((resolve4, reject) => { - const collector = new Collector(); - collector.limit = bytes; - stream.pipe(collector); - stream.on("error", (err) => { - collector.end(); - reject(err); - }); - collector.on("error", reject); - collector.on("finish", function() { - const bytes2 = new Uint8Array(Buffer.concat(this.buffers)); - resolve4(bytes2); - }); - }); - }; - exports.headStream = headStream; - var Collector = class extends stream_1.Writable { - buffers = []; - limit = Infinity; - bytesBuffered = 0; - _write(chunk, encoding, callback) { - this.buffers.push(chunk); - this.bytesBuffered += chunk.byteLength ?? 0; - if (this.bytesBuffered >= this.limit) { - const excess = this.bytesBuffered - this.limit; - const tailBuffer = this.buffers[this.buffers.length - 1]; - this.buffers[this.buffers.length - 1] = tailBuffer.subarray(0, tailBuffer.byteLength - excess); - this.emit("finish"); - } - callback(); - } - }; - } -}); - -// node_modules/.pnpm/@smithy+util-uri-escape@4.2.2/node_modules/@smithy/util-uri-escape/dist-cjs/index.js -var require_dist_cjs8 = __commonJS({ - "node_modules/.pnpm/@smithy+util-uri-escape@4.2.2/node_modules/@smithy/util-uri-escape/dist-cjs/index.js"(exports) { - "use strict"; - var escapeUri = (uri) => encodeURIComponent(uri).replace(/[!'()*]/g, hexEncode); - var hexEncode = (c5) => `%${c5.charCodeAt(0).toString(16).toUpperCase()}`; - var escapeUriPath = (uri) => uri.split("/").map(escapeUri).join("/"); - exports.escapeUri = escapeUri; - exports.escapeUriPath = escapeUriPath; - } -}); - -// node_modules/.pnpm/@smithy+querystring-builder@4.2.13/node_modules/@smithy/querystring-builder/dist-cjs/index.js -var require_dist_cjs9 = __commonJS({ - "node_modules/.pnpm/@smithy+querystring-builder@4.2.13/node_modules/@smithy/querystring-builder/dist-cjs/index.js"(exports) { - "use strict"; - var utilUriEscape = require_dist_cjs8(); - function buildQueryString(query) { - const parts = []; - for (let key of Object.keys(query).sort()) { - const value = query[key]; - key = utilUriEscape.escapeUri(key); - if (Array.isArray(value)) { - for (let i5 = 0, iLen = value.length; i5 < iLen; i5++) { - parts.push(`${key}=${utilUriEscape.escapeUri(value[i5])}`); - } - } else { - let qsEntry = key; - if (value || typeof value === "string") { - qsEntry += `=${utilUriEscape.escapeUri(value)}`; - } - parts.push(qsEntry); - } - } - return parts.join("&"); - } - exports.buildQueryString = buildQueryString; - } -}); - -// node_modules/.pnpm/@smithy+node-http-handler@4.5.2/node_modules/@smithy/node-http-handler/dist-cjs/index.js -var require_dist_cjs10 = __commonJS({ - "node_modules/.pnpm/@smithy+node-http-handler@4.5.2/node_modules/@smithy/node-http-handler/dist-cjs/index.js"(exports) { - "use strict"; - var protocolHttp = require_dist_cjs2(); - var querystringBuilder = require_dist_cjs9(); - var node_https = __require("node:https"); - var node_stream = __require("node:stream"); - var http2 = __require("node:http2"); - function buildAbortError(abortSignal) { - const reason = abortSignal && typeof abortSignal === "object" && "reason" in abortSignal ? abortSignal.reason : void 0; - if (reason) { - if (reason instanceof Error) { - const abortError3 = new Error("Request aborted"); - abortError3.name = "AbortError"; - abortError3.cause = reason; - return abortError3; - } - const abortError2 = new Error(String(reason)); - abortError2.name = "AbortError"; - return abortError2; - } - const abortError = new Error("Request aborted"); - abortError.name = "AbortError"; - return abortError; - } - var NODEJS_TIMEOUT_ERROR_CODES = ["ECONNRESET", "EPIPE", "ETIMEDOUT"]; - var getTransformedHeaders = (headers) => { - const transformedHeaders = {}; - for (const name of Object.keys(headers)) { - const headerValues = headers[name]; - transformedHeaders[name] = Array.isArray(headerValues) ? headerValues.join(",") : headerValues; - } - return transformedHeaders; - }; - var timing = { - setTimeout: (cb, ms) => setTimeout(cb, ms), - clearTimeout: (timeoutId) => clearTimeout(timeoutId) - }; - var DEFER_EVENT_LISTENER_TIME$2 = 1e3; - var setConnectionTimeout = (request, reject, timeoutInMs = 0) => { - if (!timeoutInMs) { - return -1; - } - const registerTimeout = (offset) => { - const timeoutId = timing.setTimeout(() => { - request.destroy(); - reject(Object.assign(new Error(`@smithy/node-http-handler - the request socket did not establish a connection with the server within the configured timeout of ${timeoutInMs} ms.`), { - name: "TimeoutError" - })); - }, timeoutInMs - offset); - const doWithSocket = (socket) => { - if (socket?.connecting) { - socket.on("connect", () => { - timing.clearTimeout(timeoutId); - }); - } else { - timing.clearTimeout(timeoutId); - } - }; - if (request.socket) { - doWithSocket(request.socket); - } else { - request.on("socket", doWithSocket); - } - }; - if (timeoutInMs < 2e3) { - registerTimeout(0); - return 0; - } - return timing.setTimeout(registerTimeout.bind(null, DEFER_EVENT_LISTENER_TIME$2), DEFER_EVENT_LISTENER_TIME$2); - }; - var setRequestTimeout = (req, reject, timeoutInMs = 0, throwOnRequestTimeout, logger4) => { - if (timeoutInMs) { - return timing.setTimeout(() => { - let msg = `@smithy/node-http-handler - [${throwOnRequestTimeout ? "ERROR" : "WARN"}] a request has exceeded the configured ${timeoutInMs} ms requestTimeout.`; - if (throwOnRequestTimeout) { - const error50 = Object.assign(new Error(msg), { - name: "TimeoutError", - code: "ETIMEDOUT" - }); - req.destroy(error50); - reject(error50); - } else { - msg += ` Init client requestHandler with throwOnRequestTimeout=true to turn this into an error.`; - logger4?.warn?.(msg); - } - }, timeoutInMs); - } - return -1; - }; - var DEFER_EVENT_LISTENER_TIME$1 = 3e3; - var setSocketKeepAlive = (request, { keepAlive, keepAliveMsecs }, deferTimeMs = DEFER_EVENT_LISTENER_TIME$1) => { - if (keepAlive !== true) { - return -1; - } - const registerListener = () => { - if (request.socket) { - request.socket.setKeepAlive(keepAlive, keepAliveMsecs || 0); - } else { - request.on("socket", (socket) => { - socket.setKeepAlive(keepAlive, keepAliveMsecs || 0); - }); - } - }; - if (deferTimeMs === 0) { - registerListener(); - return 0; - } - return timing.setTimeout(registerListener, deferTimeMs); - }; - var DEFER_EVENT_LISTENER_TIME = 3e3; - var setSocketTimeout = (request, reject, timeoutInMs = 0) => { - const registerTimeout = (offset) => { - const timeout = timeoutInMs - offset; - const onTimeout = () => { - request.destroy(); - reject(Object.assign(new Error(`@smithy/node-http-handler - the request socket timed out after ${timeoutInMs} ms of inactivity (configured by client requestHandler).`), { name: "TimeoutError" })); - }; - if (request.socket) { - request.socket.setTimeout(timeout, onTimeout); - request.on("close", () => request.socket?.removeListener("timeout", onTimeout)); - } else { - request.setTimeout(timeout, onTimeout); - } - }; - if (0 < timeoutInMs && timeoutInMs < 6e3) { - registerTimeout(0); - return 0; - } - return timing.setTimeout(registerTimeout.bind(null, timeoutInMs === 0 ? 0 : DEFER_EVENT_LISTENER_TIME), DEFER_EVENT_LISTENER_TIME); - }; - var MIN_WAIT_TIME = 6e3; - async function writeRequestBody(httpRequest2, request, maxContinueTimeoutMs = MIN_WAIT_TIME, externalAgent = false) { - const headers = request.headers ?? {}; - const expect = headers.Expect || headers.expect; - let timeoutId = -1; - let sendBody = true; - if (!externalAgent && expect === "100-continue") { - sendBody = await Promise.race([ - new Promise((resolve4) => { - timeoutId = Number(timing.setTimeout(() => resolve4(true), Math.max(MIN_WAIT_TIME, maxContinueTimeoutMs))); - }), - new Promise((resolve4) => { - httpRequest2.on("continue", () => { - timing.clearTimeout(timeoutId); - resolve4(true); - }); - httpRequest2.on("response", () => { - timing.clearTimeout(timeoutId); - resolve4(false); - }); - httpRequest2.on("error", () => { - timing.clearTimeout(timeoutId); - resolve4(false); - }); - }) - ]); - } - if (sendBody) { - writeBody(httpRequest2, request.body); - } - } - function writeBody(httpRequest2, body) { - if (body instanceof node_stream.Readable) { - body.pipe(httpRequest2); - return; - } - if (body) { - const isBuffer2 = Buffer.isBuffer(body); - const isString2 = typeof body === "string"; - if (isBuffer2 || isString2) { - if (isBuffer2 && body.byteLength === 0) { - httpRequest2.end(); - } else { - httpRequest2.end(body); - } - return; - } - const uint8 = body; - if (typeof uint8 === "object" && uint8.buffer && typeof uint8.byteOffset === "number" && typeof uint8.byteLength === "number") { - httpRequest2.end(Buffer.from(uint8.buffer, uint8.byteOffset, uint8.byteLength)); - return; - } - httpRequest2.end(Buffer.from(body)); - return; - } - httpRequest2.end(); - } - var DEFAULT_REQUEST_TIMEOUT = 0; - var hAgent = void 0; - var hRequest = void 0; - var NodeHttpHandler = class _NodeHttpHandler { - config; - configProvider; - socketWarningTimestamp = 0; - externalAgent = false; - metadata = { handlerProtocol: "http/1.1" }; - static create(instanceOrOptions) { - if (typeof instanceOrOptions?.handle === "function") { - return instanceOrOptions; - } - return new _NodeHttpHandler(instanceOrOptions); - } - static checkSocketUsage(agent, socketWarningTimestamp, logger4 = console) { - const { sockets, requests, maxSockets } = agent; - if (typeof maxSockets !== "number" || maxSockets === Infinity) { - return socketWarningTimestamp; - } - const interval2 = 15e3; - if (Date.now() - interval2 < socketWarningTimestamp) { - return socketWarningTimestamp; - } - if (sockets && requests) { - for (const origin in sockets) { - const socketsInUse = sockets[origin]?.length ?? 0; - const requestsEnqueued = requests[origin]?.length ?? 0; - if (socketsInUse >= maxSockets && requestsEnqueued >= 2 * maxSockets) { - logger4?.warn?.(`@smithy/node-http-handler:WARN - socket usage at capacity=${socketsInUse} and ${requestsEnqueued} additional requests are enqueued. -See https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/node-configuring-maxsockets.html -or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler config.`); - return Date.now(); - } - } - } - return socketWarningTimestamp; - } - constructor(options) { - this.configProvider = new Promise((resolve4, reject) => { - if (typeof options === "function") { - options().then((_options) => { - resolve4(this.resolveDefaultConfig(_options)); - }).catch(reject); - } else { - resolve4(this.resolveDefaultConfig(options)); - } - }); - } - destroy() { - this.config?.httpAgent?.destroy(); - this.config?.httpsAgent?.destroy(); - } - async handle(request, { abortSignal, requestTimeout } = {}) { - if (!this.config) { - this.config = await this.configProvider; - } - const config3 = this.config; - const isSSL = request.protocol === "https:"; - if (!isSSL && !this.config.httpAgent) { - this.config.httpAgent = await this.config.httpAgentProvider(); - } - return new Promise((_resolve, _reject) => { - let writeRequestBodyPromise = void 0; - const timeouts = []; - const resolve4 = async (arg) => { - await writeRequestBodyPromise; - timeouts.forEach(timing.clearTimeout); - _resolve(arg); - }; - const reject = async (arg) => { - await writeRequestBodyPromise; - timeouts.forEach(timing.clearTimeout); - _reject(arg); - }; - if (abortSignal?.aborted) { - const abortError = buildAbortError(abortSignal); - reject(abortError); - return; - } - const headers = request.headers ?? {}; - const expectContinue = (headers.Expect ?? headers.expect) === "100-continue"; - let agent = isSSL ? config3.httpsAgent : config3.httpAgent; - if (expectContinue && !this.externalAgent) { - agent = new (isSSL ? node_https.Agent : hAgent)({ - keepAlive: false, - maxSockets: Infinity - }); - } - timeouts.push(timing.setTimeout(() => { - this.socketWarningTimestamp = _NodeHttpHandler.checkSocketUsage(agent, this.socketWarningTimestamp, config3.logger); - }, config3.socketAcquisitionWarningTimeout ?? (config3.requestTimeout ?? 2e3) + (config3.connectionTimeout ?? 1e3))); - const queryString = querystringBuilder.buildQueryString(request.query || {}); - let auth = void 0; - if (request.username != null || request.password != null) { - const username = request.username ?? ""; - const password = request.password ?? ""; - auth = `${username}:${password}`; - } - let path53 = request.path; - if (queryString) { - path53 += `?${queryString}`; - } - if (request.fragment) { - path53 += `#${request.fragment}`; - } - let hostname3 = request.hostname ?? ""; - if (hostname3[0] === "[" && hostname3.endsWith("]")) { - hostname3 = request.hostname.slice(1, -1); - } else { - hostname3 = request.hostname; - } - const nodeHttpsOptions = { - headers: request.headers, - host: hostname3, - method: request.method, - path: path53, - port: request.port, - agent, - auth - }; - const requestFunc = isSSL ? node_https.request : hRequest; - const req = requestFunc(nodeHttpsOptions, (res) => { - const httpResponse = new protocolHttp.HttpResponse({ - statusCode: res.statusCode || -1, - reason: res.statusMessage, - headers: getTransformedHeaders(res.headers), - body: res - }); - resolve4({ response: httpResponse }); - }); - req.on("error", (err) => { - if (NODEJS_TIMEOUT_ERROR_CODES.includes(err.code)) { - reject(Object.assign(err, { name: "TimeoutError" })); - } else { - reject(err); - } - }); - if (abortSignal) { - const onAbort = () => { - req.destroy(); - const abortError = buildAbortError(abortSignal); - reject(abortError); - }; - if (typeof abortSignal.addEventListener === "function") { - const signal = abortSignal; - signal.addEventListener("abort", onAbort, { once: true }); - req.once("close", () => signal.removeEventListener("abort", onAbort)); - } else { - abortSignal.onabort = onAbort; - } - } - const effectiveRequestTimeout = requestTimeout ?? config3.requestTimeout; - timeouts.push(setConnectionTimeout(req, reject, config3.connectionTimeout)); - timeouts.push(setRequestTimeout(req, reject, effectiveRequestTimeout, config3.throwOnRequestTimeout, config3.logger ?? console)); - timeouts.push(setSocketTimeout(req, reject, config3.socketTimeout)); - const httpAgent = nodeHttpsOptions.agent; - if (typeof httpAgent === "object" && "keepAlive" in httpAgent) { - timeouts.push(setSocketKeepAlive(req, { - keepAlive: httpAgent.keepAlive, - keepAliveMsecs: httpAgent.keepAliveMsecs - })); - } - writeRequestBodyPromise = writeRequestBody(req, request, effectiveRequestTimeout, this.externalAgent).catch((e5) => { - timeouts.forEach(timing.clearTimeout); - return _reject(e5); - }); - }); - } - updateHttpClientConfig(key, value) { - this.config = void 0; - this.configProvider = this.configProvider.then((config3) => { - return { - ...config3, - [key]: value - }; - }); - } - httpHandlerConfigs() { - return this.config ?? {}; - } - resolveDefaultConfig(options) { - const { requestTimeout, connectionTimeout, socketTimeout, socketAcquisitionWarningTimeout, httpAgent, httpsAgent, throwOnRequestTimeout, logger: logger4 } = options || {}; - const keepAlive = true; - const maxSockets = 50; - return { - connectionTimeout, - requestTimeout, - socketTimeout, - socketAcquisitionWarningTimeout, - throwOnRequestTimeout, - httpAgentProvider: async () => { - const { Agent, request } = await import("node:http"); - hRequest = request; - hAgent = Agent; - if (httpAgent instanceof hAgent || typeof httpAgent?.destroy === "function") { - this.externalAgent = true; - return httpAgent; - } - return new hAgent({ keepAlive, maxSockets, ...httpAgent }); - }, - httpsAgent: (() => { - if (httpsAgent instanceof node_https.Agent || typeof httpsAgent?.destroy === "function") { - this.externalAgent = true; - return httpsAgent; - } - return new node_https.Agent({ keepAlive, maxSockets, ...httpsAgent }); - })(), - logger: logger4 - }; - } - }; - var NodeHttp2ConnectionPool = class { - sessions = []; - constructor(sessions) { - this.sessions = sessions ?? []; - } - poll() { - if (this.sessions.length > 0) { - return this.sessions.shift(); - } - } - offerLast(session) { - this.sessions.push(session); - } - contains(session) { - return this.sessions.includes(session); - } - remove(session) { - this.sessions = this.sessions.filter((s5) => s5 !== session); - } - [Symbol.iterator]() { - return this.sessions[Symbol.iterator](); - } - destroy(connection2) { - for (const session of this.sessions) { - if (session === connection2) { - if (!session.destroyed) { - session.destroy(); - } - } - } - } - }; - var NodeHttp2ConnectionManager = class { - constructor(config3) { - this.config = config3; - if (this.config.maxConcurrency && this.config.maxConcurrency <= 0) { - throw new RangeError("maxConcurrency must be greater than zero."); - } - } - config; - sessionCache = /* @__PURE__ */ new Map(); - lease(requestContext, connectionConfiguration) { - const url2 = this.getUrlString(requestContext); - const existingPool = this.sessionCache.get(url2); - if (existingPool) { - const existingSession = existingPool.poll(); - if (existingSession && !this.config.disableConcurrency) { - return existingSession; - } - } - const session = http2.connect(url2); - if (this.config.maxConcurrency) { - session.settings({ maxConcurrentStreams: this.config.maxConcurrency }, (err) => { - if (err) { - throw new Error("Fail to set maxConcurrentStreams to " + this.config.maxConcurrency + "when creating new session for " + requestContext.destination.toString()); - } - }); - } - session.unref(); - const destroySessionCb = () => { - session.destroy(); - this.deleteSession(url2, session); - }; - session.on("goaway", destroySessionCb); - session.on("error", destroySessionCb); - session.on("frameError", destroySessionCb); - session.on("close", () => this.deleteSession(url2, session)); - if (connectionConfiguration.requestTimeout) { - session.setTimeout(connectionConfiguration.requestTimeout, destroySessionCb); - } - const connectionPool = this.sessionCache.get(url2) || new NodeHttp2ConnectionPool(); - connectionPool.offerLast(session); - this.sessionCache.set(url2, connectionPool); - return session; - } - deleteSession(authority, session) { - const existingConnectionPool = this.sessionCache.get(authority); - if (!existingConnectionPool) { - return; - } - if (!existingConnectionPool.contains(session)) { - return; - } - existingConnectionPool.remove(session); - this.sessionCache.set(authority, existingConnectionPool); - } - release(requestContext, session) { - const cacheKey = this.getUrlString(requestContext); - this.sessionCache.get(cacheKey)?.offerLast(session); - } - destroy() { - for (const [key, connectionPool] of this.sessionCache) { - for (const session of connectionPool) { - if (!session.destroyed) { - session.destroy(); - } - connectionPool.remove(session); - } - this.sessionCache.delete(key); - } - } - setMaxConcurrentStreams(maxConcurrentStreams) { - if (maxConcurrentStreams && maxConcurrentStreams <= 0) { - throw new RangeError("maxConcurrentStreams must be greater than zero."); - } - this.config.maxConcurrency = maxConcurrentStreams; - } - setDisableConcurrentStreams(disableConcurrentStreams) { - this.config.disableConcurrency = disableConcurrentStreams; - } - getUrlString(request) { - return request.destination.toString(); - } - }; - var NodeHttp2Handler = class _NodeHttp2Handler { - config; - configProvider; - metadata = { handlerProtocol: "h2" }; - connectionManager = new NodeHttp2ConnectionManager({}); - static create(instanceOrOptions) { - if (typeof instanceOrOptions?.handle === "function") { - return instanceOrOptions; - } - return new _NodeHttp2Handler(instanceOrOptions); - } - constructor(options) { - this.configProvider = new Promise((resolve4, reject) => { - if (typeof options === "function") { - options().then((opts) => { - resolve4(opts || {}); - }).catch(reject); - } else { - resolve4(options || {}); - } - }); - } - destroy() { - this.connectionManager.destroy(); - } - async handle(request, { abortSignal, requestTimeout } = {}) { - if (!this.config) { - this.config = await this.configProvider; - this.connectionManager.setDisableConcurrentStreams(this.config.disableConcurrentStreams || false); - if (this.config.maxConcurrentStreams) { - this.connectionManager.setMaxConcurrentStreams(this.config.maxConcurrentStreams); - } - } - const { requestTimeout: configRequestTimeout, disableConcurrentStreams } = this.config; - const effectiveRequestTimeout = requestTimeout ?? configRequestTimeout; - return new Promise((_resolve, _reject) => { - let fulfilled = false; - let writeRequestBodyPromise = void 0; - const resolve4 = async (arg) => { - await writeRequestBodyPromise; - _resolve(arg); - }; - const reject = async (arg) => { - await writeRequestBodyPromise; - _reject(arg); - }; - if (abortSignal?.aborted) { - fulfilled = true; - const abortError = buildAbortError(abortSignal); - reject(abortError); - return; - } - const { hostname: hostname3, method, port, protocol, query } = request; - let auth = ""; - if (request.username != null || request.password != null) { - const username = request.username ?? ""; - const password = request.password ?? ""; - auth = `${username}:${password}@`; - } - const authority = `${protocol}//${auth}${hostname3}${port ? `:${port}` : ""}`; - const requestContext = { destination: new URL(authority) }; - const session = this.connectionManager.lease(requestContext, { - requestTimeout: this.config?.sessionTimeout, - disableConcurrentStreams: disableConcurrentStreams || false - }); - const rejectWithDestroy = (err) => { - if (disableConcurrentStreams) { - this.destroySession(session); - } - fulfilled = true; - reject(err); - }; - const queryString = querystringBuilder.buildQueryString(query || {}); - let path53 = request.path; - if (queryString) { - path53 += `?${queryString}`; - } - if (request.fragment) { - path53 += `#${request.fragment}`; - } - const req = session.request({ - ...request.headers, - [http2.constants.HTTP2_HEADER_PATH]: path53, - [http2.constants.HTTP2_HEADER_METHOD]: method - }); - session.ref(); - req.on("response", (headers) => { - const httpResponse = new protocolHttp.HttpResponse({ - statusCode: headers[":status"] || -1, - headers: getTransformedHeaders(headers), - body: req - }); - fulfilled = true; - resolve4({ response: httpResponse }); - if (disableConcurrentStreams) { - session.close(); - this.connectionManager.deleteSession(authority, session); - } - }); - if (effectiveRequestTimeout) { - req.setTimeout(effectiveRequestTimeout, () => { - req.close(); - const timeoutError = new Error(`Stream timed out because of no activity for ${effectiveRequestTimeout} ms`); - timeoutError.name = "TimeoutError"; - rejectWithDestroy(timeoutError); - }); - } - if (abortSignal) { - const onAbort = () => { - req.close(); - const abortError = buildAbortError(abortSignal); - rejectWithDestroy(abortError); - }; - if (typeof abortSignal.addEventListener === "function") { - const signal = abortSignal; - signal.addEventListener("abort", onAbort, { once: true }); - req.once("close", () => signal.removeEventListener("abort", onAbort)); - } else { - abortSignal.onabort = onAbort; - } - } - req.on("frameError", (type, code, id) => { - rejectWithDestroy(new Error(`Frame type id ${type} in stream id ${id} has failed with code ${code}.`)); - }); - req.on("error", rejectWithDestroy); - req.on("aborted", () => { - rejectWithDestroy(new Error(`HTTP/2 stream is abnormally aborted in mid-communication with result code ${req.rstCode}.`)); - }); - req.on("close", () => { - session.unref(); - if (disableConcurrentStreams) { - session.destroy(); - } - if (!fulfilled) { - rejectWithDestroy(new Error("Unexpected error: http2 request did not get a response")); - } - }); - writeRequestBodyPromise = writeRequestBody(req, request, effectiveRequestTimeout); - }); - } - updateHttpClientConfig(key, value) { - this.config = void 0; - this.configProvider = this.configProvider.then((config3) => { - return { - ...config3, - [key]: value - }; - }); - } - httpHandlerConfigs() { - return this.config ?? {}; - } - destroySession(session) { - if (!session.destroyed) { - session.destroy(); - } - } - }; - var Collector = class extends node_stream.Writable { - bufferedBytes = []; - _write(chunk, encoding, callback) { - this.bufferedBytes.push(chunk); - callback(); - } - }; - var streamCollector5 = (stream) => { - if (isReadableStreamInstance(stream)) { - return collectReadableStream(stream); - } - return new Promise((resolve4, reject) => { - const collector = new Collector(); - stream.pipe(collector); - stream.on("error", (err) => { - collector.end(); - reject(err); - }); - collector.on("error", reject); - collector.on("finish", function() { - const bytes = new Uint8Array(Buffer.concat(this.bufferedBytes)); - resolve4(bytes); - }); - }); - }; - var isReadableStreamInstance = (stream) => typeof ReadableStream === "function" && stream instanceof ReadableStream; - async function collectReadableStream(stream) { - const chunks = []; - const reader = stream.getReader(); - let isDone = false; - let length = 0; - while (!isDone) { - const { done, value } = await reader.read(); - if (value) { - chunks.push(value); - length += value.length; - } - isDone = done; - } - const collected = new Uint8Array(length); - let offset = 0; - for (const chunk of chunks) { - collected.set(chunk, offset); - offset += chunk.length; - } - return collected; - } - exports.DEFAULT_REQUEST_TIMEOUT = DEFAULT_REQUEST_TIMEOUT; - exports.NodeHttp2Handler = NodeHttp2Handler; - exports.NodeHttpHandler = NodeHttpHandler; - exports.streamCollector = streamCollector5; - } -}); - -// node_modules/.pnpm/@smithy+fetch-http-handler@5.3.16/node_modules/@smithy/fetch-http-handler/dist-cjs/index.js -var require_dist_cjs11 = __commonJS({ - "node_modules/.pnpm/@smithy+fetch-http-handler@5.3.16/node_modules/@smithy/fetch-http-handler/dist-cjs/index.js"(exports) { - "use strict"; - var protocolHttp = require_dist_cjs2(); - var querystringBuilder = require_dist_cjs9(); - var utilBase64 = require_dist_cjs7(); - function createRequest2(url2, requestOptions) { - return new Request(url2, requestOptions); - } - function requestTimeout(timeoutInMs = 0) { - return new Promise((resolve4, reject) => { - if (timeoutInMs) { - setTimeout(() => { - const timeoutError = new Error(`Request did not complete within ${timeoutInMs} ms`); - timeoutError.name = "TimeoutError"; - reject(timeoutError); - }, timeoutInMs); - } - }); - } - var keepAliveSupport = { - supported: void 0 - }; - var FetchHttpHandler = class _FetchHttpHandler { - config; - configProvider; - static create(instanceOrOptions) { - if (typeof instanceOrOptions?.handle === "function") { - return instanceOrOptions; - } - return new _FetchHttpHandler(instanceOrOptions); - } - constructor(options) { - if (typeof options === "function") { - this.configProvider = options().then((opts) => opts || {}); - } else { - this.config = options ?? {}; - this.configProvider = Promise.resolve(this.config); - } - if (keepAliveSupport.supported === void 0) { - keepAliveSupport.supported = Boolean(typeof Request !== "undefined" && "keepalive" in createRequest2("https://[::1]")); - } - } - destroy() { - } - async handle(request, { abortSignal, requestTimeout: requestTimeout$1 } = {}) { - if (!this.config) { - this.config = await this.configProvider; - } - const requestTimeoutInMs = requestTimeout$1 ?? this.config.requestTimeout; - const keepAlive = this.config.keepAlive === true; - const credentials = this.config.credentials; - if (abortSignal?.aborted) { - const abortError = buildAbortError(abortSignal); - return Promise.reject(abortError); - } - let path53 = request.path; - const queryString = querystringBuilder.buildQueryString(request.query || {}); - if (queryString) { - path53 += `?${queryString}`; - } - if (request.fragment) { - path53 += `#${request.fragment}`; - } - let auth = ""; - if (request.username != null || request.password != null) { - const username = request.username ?? ""; - const password = request.password ?? ""; - auth = `${username}:${password}@`; - } - const { port, method } = request; - const url2 = `${request.protocol}//${auth}${request.hostname}${port ? `:${port}` : ""}${path53}`; - const body = method === "GET" || method === "HEAD" ? void 0 : request.body; - const requestOptions = { - body, - headers: new Headers(request.headers), - method, - credentials - }; - if (this.config?.cache) { - requestOptions.cache = this.config.cache; - } - if (body) { - requestOptions.duplex = "half"; - } - if (typeof AbortController !== "undefined") { - requestOptions.signal = abortSignal; - } - if (keepAliveSupport.supported) { - requestOptions.keepalive = keepAlive; - } - if (typeof this.config.requestInit === "function") { - Object.assign(requestOptions, this.config.requestInit(request)); - } - let removeSignalEventListener = () => { - }; - const fetchRequest = createRequest2(url2, requestOptions); - const raceOfPromises = [ - fetch(fetchRequest).then((response) => { - const fetchHeaders = response.headers; - const transformedHeaders = {}; - for (const pair of fetchHeaders.entries()) { - transformedHeaders[pair[0]] = pair[1]; - } - const hasReadableStream = response.body != void 0; - if (!hasReadableStream) { - return response.blob().then((body2) => ({ - response: new protocolHttp.HttpResponse({ - headers: transformedHeaders, - reason: response.statusText, - statusCode: response.status, - body: body2 - }) - })); - } - return { - response: new protocolHttp.HttpResponse({ - headers: transformedHeaders, - reason: response.statusText, - statusCode: response.status, - body: response.body - }) - }; - }), - requestTimeout(requestTimeoutInMs) - ]; - if (abortSignal) { - raceOfPromises.push(new Promise((resolve4, reject) => { - const onAbort = () => { - const abortError = buildAbortError(abortSignal); - reject(abortError); - }; - if (typeof abortSignal.addEventListener === "function") { - const signal = abortSignal; - signal.addEventListener("abort", onAbort, { once: true }); - removeSignalEventListener = () => signal.removeEventListener("abort", onAbort); - } else { - abortSignal.onabort = onAbort; - } - })); - } - return Promise.race(raceOfPromises).finally(removeSignalEventListener); - } - updateHttpClientConfig(key, value) { - this.config = void 0; - this.configProvider = this.configProvider.then((config3) => { - config3[key] = value; - return config3; - }); - } - httpHandlerConfigs() { - return this.config ?? {}; - } - }; - function buildAbortError(abortSignal) { - const reason = abortSignal && typeof abortSignal === "object" && "reason" in abortSignal ? abortSignal.reason : void 0; - if (reason) { - if (reason instanceof Error) { - const abortError3 = new Error("Request aborted"); - abortError3.name = "AbortError"; - abortError3.cause = reason; - return abortError3; - } - const abortError2 = new Error(String(reason)); - abortError2.name = "AbortError"; - return abortError2; - } - const abortError = new Error("Request aborted"); - abortError.name = "AbortError"; - return abortError; - } - var streamCollector5 = async (stream) => { - if (typeof Blob === "function" && stream instanceof Blob || stream.constructor?.name === "Blob") { - if (Blob.prototype.arrayBuffer !== void 0) { - return new Uint8Array(await stream.arrayBuffer()); - } - return collectBlob(stream); - } - return collectStream(stream); - }; - async function collectBlob(blob) { - const base644 = await readToBase64(blob); - const arrayBuffer = utilBase64.fromBase64(base644); - return new Uint8Array(arrayBuffer); - } - async function collectStream(stream) { - const chunks = []; - const reader = stream.getReader(); - let isDone = false; - let length = 0; - while (!isDone) { - const { done, value } = await reader.read(); - if (value) { - chunks.push(value); - length += value.length; - } - isDone = done; - } - const collected = new Uint8Array(length); - let offset = 0; - for (const chunk of chunks) { - collected.set(chunk, offset); - offset += chunk.length; - } - return collected; - } - function readToBase64(blob) { - return new Promise((resolve4, reject) => { - const reader = new FileReader(); - reader.onloadend = () => { - if (reader.readyState !== 2) { - return reject(new Error("Reader aborted too early")); - } - const result = reader.result ?? ""; - const commaIndex = result.indexOf(","); - const dataOffset = commaIndex > -1 ? commaIndex + 1 : result.length; - resolve4(result.substring(dataOffset)); - }; - reader.onabort = () => reject(new Error("Read aborted")); - reader.onerror = () => reject(reader.error); - reader.readAsDataURL(blob); - }); - } - exports.FetchHttpHandler = FetchHttpHandler; - exports.keepAliveSupport = keepAliveSupport; - exports.streamCollector = streamCollector5; - } -}); - -// node_modules/.pnpm/@smithy+util-hex-encoding@4.2.2/node_modules/@smithy/util-hex-encoding/dist-cjs/index.js -var require_dist_cjs12 = __commonJS({ - "node_modules/.pnpm/@smithy+util-hex-encoding@4.2.2/node_modules/@smithy/util-hex-encoding/dist-cjs/index.js"(exports) { - "use strict"; - var SHORT_TO_HEX = {}; - var HEX_TO_SHORT = {}; - for (let i5 = 0; i5 < 256; i5++) { - let encodedByte = i5.toString(16).toLowerCase(); - if (encodedByte.length === 1) { - encodedByte = `0${encodedByte}`; - } - SHORT_TO_HEX[i5] = encodedByte; - HEX_TO_SHORT[encodedByte] = i5; - } - function fromHex(encoded) { - if (encoded.length % 2 !== 0) { - throw new Error("Hex encoded strings must have an even number length"); - } - const out = new Uint8Array(encoded.length / 2); - for (let i5 = 0; i5 < encoded.length; i5 += 2) { - const encodedByte = encoded.slice(i5, i5 + 2).toLowerCase(); - if (encodedByte in HEX_TO_SHORT) { - out[i5 / 2] = HEX_TO_SHORT[encodedByte]; - } else { - throw new Error(`Cannot decode unrecognized sequence ${encodedByte} as hexadecimal`); - } - } - return out; - } - function toHex(bytes) { - let out = ""; - for (let i5 = 0; i5 < bytes.byteLength; i5++) { - out += SHORT_TO_HEX[bytes[i5]]; - } - return out; - } - exports.fromHex = fromHex; - exports.toHex = toHex; - } -}); - -// node_modules/.pnpm/@smithy+util-stream@4.5.22/node_modules/@smithy/util-stream/dist-cjs/sdk-stream-mixin.browser.js -var require_sdk_stream_mixin_browser = __commonJS({ - "node_modules/.pnpm/@smithy+util-stream@4.5.22/node_modules/@smithy/util-stream/dist-cjs/sdk-stream-mixin.browser.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.sdkStreamMixin = void 0; - var fetch_http_handler_1 = require_dist_cjs11(); - var util_base64_1 = require_dist_cjs7(); - var util_hex_encoding_1 = require_dist_cjs12(); - var util_utf8_1 = require_dist_cjs6(); - var stream_type_check_1 = require_stream_type_check(); - var ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED = "The stream has already been transformed."; - var sdkStreamMixin2 = (stream) => { - if (!isBlobInstance(stream) && !(0, stream_type_check_1.isReadableStream)(stream)) { - const name = stream?.__proto__?.constructor?.name || stream; - throw new Error(`Unexpected stream implementation, expect Blob or ReadableStream, got ${name}`); - } - let transformed = false; - const transformToByteArray = async () => { - if (transformed) { - throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); - } - transformed = true; - return await (0, fetch_http_handler_1.streamCollector)(stream); - }; - const blobToWebStream = (blob) => { - if (typeof blob.stream !== "function") { - throw new Error("Cannot transform payload Blob to web stream. Please make sure the Blob.stream() is polyfilled.\nIf you are using React Native, this API is not yet supported, see: https://react-native.canny.io/feature-requests/p/fetch-streaming-body"); - } - return blob.stream(); - }; - return Object.assign(stream, { - transformToByteArray, - transformToString: async (encoding) => { - const buf = await transformToByteArray(); - if (encoding === "base64") { - return (0, util_base64_1.toBase64)(buf); - } else if (encoding === "hex") { - return (0, util_hex_encoding_1.toHex)(buf); - } else if (encoding === void 0 || encoding === "utf8" || encoding === "utf-8") { - return (0, util_utf8_1.toUtf8)(buf); - } else if (typeof TextDecoder === "function") { - return new TextDecoder(encoding).decode(buf); - } else { - throw new Error("TextDecoder is not available, please make sure polyfill is provided."); - } - }, - transformToWebStream: () => { - if (transformed) { - throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); - } - transformed = true; - if (isBlobInstance(stream)) { - return blobToWebStream(stream); - } else if ((0, stream_type_check_1.isReadableStream)(stream)) { - return stream; - } else { - throw new Error(`Cannot transform payload to web stream, got ${stream}`); - } - } - }); - }; - exports.sdkStreamMixin = sdkStreamMixin2; - var isBlobInstance = (stream) => typeof Blob === "function" && stream instanceof Blob; - } -}); - -// node_modules/.pnpm/@smithy+util-stream@4.5.22/node_modules/@smithy/util-stream/dist-cjs/sdk-stream-mixin.js -var require_sdk_stream_mixin = __commonJS({ - "node_modules/.pnpm/@smithy+util-stream@4.5.22/node_modules/@smithy/util-stream/dist-cjs/sdk-stream-mixin.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.sdkStreamMixin = void 0; - var node_http_handler_1 = require_dist_cjs10(); - var util_buffer_from_1 = require_dist_cjs5(); - var stream_1 = __require("stream"); - var sdk_stream_mixin_browser_1 = require_sdk_stream_mixin_browser(); - var ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED = "The stream has already been transformed."; - var sdkStreamMixin2 = (stream) => { - if (!(stream instanceof stream_1.Readable)) { - try { - return (0, sdk_stream_mixin_browser_1.sdkStreamMixin)(stream); - } catch (e5) { - const name = stream?.__proto__?.constructor?.name || stream; - throw new Error(`Unexpected stream implementation, expect Stream.Readable instance, got ${name}`); - } - } - let transformed = false; - const transformToByteArray = async () => { - if (transformed) { - throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); - } - transformed = true; - return await (0, node_http_handler_1.streamCollector)(stream); - }; - return Object.assign(stream, { - transformToByteArray, - transformToString: async (encoding) => { - const buf = await transformToByteArray(); - if (encoding === void 0 || Buffer.isEncoding(encoding)) { - return (0, util_buffer_from_1.fromArrayBuffer)(buf.buffer, buf.byteOffset, buf.byteLength).toString(encoding); - } else { - const decoder2 = new TextDecoder(encoding); - return decoder2.decode(buf); - } - }, - transformToWebStream: () => { - if (transformed) { - throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); - } - if (stream.readableFlowing !== null) { - throw new Error("The stream has been consumed by other callbacks."); - } - if (typeof stream_1.Readable.toWeb !== "function") { - throw new Error("Readable.toWeb() is not supported. Please ensure a polyfill is available."); - } - transformed = true; - return stream_1.Readable.toWeb(stream); - } - }); - }; - exports.sdkStreamMixin = sdkStreamMixin2; - } -}); - -// node_modules/.pnpm/@smithy+util-stream@4.5.22/node_modules/@smithy/util-stream/dist-cjs/splitStream.browser.js -var require_splitStream_browser = __commonJS({ - "node_modules/.pnpm/@smithy+util-stream@4.5.22/node_modules/@smithy/util-stream/dist-cjs/splitStream.browser.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.splitStream = splitStream; - async function splitStream(stream) { - if (typeof stream.stream === "function") { - stream = stream.stream(); - } - const readableStream = stream; - return readableStream.tee(); - } - } -}); - -// node_modules/.pnpm/@smithy+util-stream@4.5.22/node_modules/@smithy/util-stream/dist-cjs/splitStream.js -var require_splitStream = __commonJS({ - "node_modules/.pnpm/@smithy+util-stream@4.5.22/node_modules/@smithy/util-stream/dist-cjs/splitStream.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.splitStream = splitStream; - var stream_1 = __require("stream"); - var splitStream_browser_1 = require_splitStream_browser(); - var stream_type_check_1 = require_stream_type_check(); - async function splitStream(stream) { - if ((0, stream_type_check_1.isReadableStream)(stream) || (0, stream_type_check_1.isBlob)(stream)) { - return (0, splitStream_browser_1.splitStream)(stream); - } - const stream1 = new stream_1.PassThrough(); - const stream2 = new stream_1.PassThrough(); - stream.pipe(stream1); - stream.pipe(stream2); - return [stream1, stream2]; - } - } -}); - -// node_modules/.pnpm/@smithy+util-stream@4.5.22/node_modules/@smithy/util-stream/dist-cjs/index.js -var require_dist_cjs13 = __commonJS({ - "node_modules/.pnpm/@smithy+util-stream@4.5.22/node_modules/@smithy/util-stream/dist-cjs/index.js"(exports) { - "use strict"; - var utilBase64 = require_dist_cjs7(); - var utilUtf8 = require_dist_cjs6(); - var ChecksumStream = require_ChecksumStream(); - var createChecksumStream = require_createChecksumStream(); - var createBufferedReadable = require_createBufferedReadable(); - var getAwsChunkedEncodingStream = require_getAwsChunkedEncodingStream(); - var headStream = require_headStream(); - var sdkStreamMixin2 = require_sdk_stream_mixin(); - var splitStream = require_splitStream(); - var streamTypeCheck = require_stream_type_check(); - var Uint8ArrayBlobAdapter2 = class _Uint8ArrayBlobAdapter extends Uint8Array { - static fromString(source, encoding = "utf-8") { - if (typeof source === "string") { - if (encoding === "base64") { - return _Uint8ArrayBlobAdapter.mutate(utilBase64.fromBase64(source)); - } - return _Uint8ArrayBlobAdapter.mutate(utilUtf8.fromUtf8(source)); - } - throw new Error(`Unsupported conversion from ${typeof source} to Uint8ArrayBlobAdapter.`); - } - static mutate(source) { - Object.setPrototypeOf(source, _Uint8ArrayBlobAdapter.prototype); - return source; - } - transformToString(encoding = "utf-8") { - if (encoding === "base64") { - return utilBase64.toBase64(this); - } - return utilUtf8.toUtf8(this); - } - }; - exports.isBlob = streamTypeCheck.isBlob; - exports.isReadableStream = streamTypeCheck.isReadableStream; - exports.Uint8ArrayBlobAdapter = Uint8ArrayBlobAdapter2; - Object.prototype.hasOwnProperty.call(ChecksumStream, "__proto__") && !Object.prototype.hasOwnProperty.call(exports, "__proto__") && Object.defineProperty(exports, "__proto__", { - enumerable: true, - value: ChecksumStream["__proto__"] - }); - Object.keys(ChecksumStream).forEach(function(k5) { - if (k5 !== "default" && !Object.prototype.hasOwnProperty.call(exports, k5)) exports[k5] = ChecksumStream[k5]; - }); - Object.prototype.hasOwnProperty.call(createChecksumStream, "__proto__") && !Object.prototype.hasOwnProperty.call(exports, "__proto__") && Object.defineProperty(exports, "__proto__", { - enumerable: true, - value: createChecksumStream["__proto__"] - }); - Object.keys(createChecksumStream).forEach(function(k5) { - if (k5 !== "default" && !Object.prototype.hasOwnProperty.call(exports, k5)) exports[k5] = createChecksumStream[k5]; - }); - Object.prototype.hasOwnProperty.call(createBufferedReadable, "__proto__") && !Object.prototype.hasOwnProperty.call(exports, "__proto__") && Object.defineProperty(exports, "__proto__", { - enumerable: true, - value: createBufferedReadable["__proto__"] - }); - Object.keys(createBufferedReadable).forEach(function(k5) { - if (k5 !== "default" && !Object.prototype.hasOwnProperty.call(exports, k5)) exports[k5] = createBufferedReadable[k5]; - }); - Object.prototype.hasOwnProperty.call(getAwsChunkedEncodingStream, "__proto__") && !Object.prototype.hasOwnProperty.call(exports, "__proto__") && Object.defineProperty(exports, "__proto__", { - enumerable: true, - value: getAwsChunkedEncodingStream["__proto__"] - }); - Object.keys(getAwsChunkedEncodingStream).forEach(function(k5) { - if (k5 !== "default" && !Object.prototype.hasOwnProperty.call(exports, k5)) exports[k5] = getAwsChunkedEncodingStream[k5]; - }); - Object.prototype.hasOwnProperty.call(headStream, "__proto__") && !Object.prototype.hasOwnProperty.call(exports, "__proto__") && Object.defineProperty(exports, "__proto__", { - enumerable: true, - value: headStream["__proto__"] - }); - Object.keys(headStream).forEach(function(k5) { - if (k5 !== "default" && !Object.prototype.hasOwnProperty.call(exports, k5)) exports[k5] = headStream[k5]; - }); - Object.prototype.hasOwnProperty.call(sdkStreamMixin2, "__proto__") && !Object.prototype.hasOwnProperty.call(exports, "__proto__") && Object.defineProperty(exports, "__proto__", { - enumerable: true, - value: sdkStreamMixin2["__proto__"] - }); - Object.keys(sdkStreamMixin2).forEach(function(k5) { - if (k5 !== "default" && !Object.prototype.hasOwnProperty.call(exports, k5)) exports[k5] = sdkStreamMixin2[k5]; - }); - Object.prototype.hasOwnProperty.call(splitStream, "__proto__") && !Object.prototype.hasOwnProperty.call(exports, "__proto__") && Object.defineProperty(exports, "__proto__", { - enumerable: true, - value: splitStream["__proto__"] - }); - Object.keys(splitStream).forEach(function(k5) { - if (k5 !== "default" && !Object.prototype.hasOwnProperty.call(exports, k5)) exports[k5] = splitStream[k5]; - }); - } -}); - -// node_modules/.pnpm/tslib@2.8.1/node_modules/tslib/tslib.es6.mjs -var tslib_es6_exports = {}; -__export(tslib_es6_exports, { - __addDisposableResource: () => __addDisposableResource, - __assign: () => __assign, - __asyncDelegator: () => __asyncDelegator, - __asyncGenerator: () => __asyncGenerator, - __asyncValues: () => __asyncValues, - __await: () => __await, - __awaiter: () => __awaiter, - __classPrivateFieldGet: () => __classPrivateFieldGet, - __classPrivateFieldIn: () => __classPrivateFieldIn, - __classPrivateFieldSet: () => __classPrivateFieldSet, - __createBinding: () => __createBinding, - __decorate: () => __decorate, - __disposeResources: () => __disposeResources, - __esDecorate: () => __esDecorate, - __exportStar: () => __exportStar, - __extends: () => __extends, - __generator: () => __generator, - __importDefault: () => __importDefault, - __importStar: () => __importStar, - __makeTemplateObject: () => __makeTemplateObject, - __metadata: () => __metadata, - __param: () => __param, - __propKey: () => __propKey, - __read: () => __read, - __rest: () => __rest, - __rewriteRelativeImportExtension: () => __rewriteRelativeImportExtension, - __runInitializers: () => __runInitializers, - __setFunctionName: () => __setFunctionName, - __spread: () => __spread, - __spreadArray: () => __spreadArray, - __spreadArrays: () => __spreadArrays, - __values: () => __values, - default: () => tslib_es6_default -}); -function __extends(d5, b6) { - if (typeof b6 !== "function" && b6 !== null) - throw new TypeError("Class extends value " + String(b6) + " is not a constructor or null"); - extendStatics(d5, b6); - function __() { - this.constructor = d5; - } - d5.prototype = b6 === null ? Object.create(b6) : (__.prototype = b6.prototype, new __()); -} -function __rest(s5, e5) { - var t5 = {}; - for (var p5 in s5) if (Object.prototype.hasOwnProperty.call(s5, p5) && e5.indexOf(p5) < 0) - t5[p5] = s5[p5]; - if (s5 != null && typeof Object.getOwnPropertySymbols === "function") - for (var i5 = 0, p5 = Object.getOwnPropertySymbols(s5); i5 < p5.length; i5++) { - if (e5.indexOf(p5[i5]) < 0 && Object.prototype.propertyIsEnumerable.call(s5, p5[i5])) - t5[p5[i5]] = s5[p5[i5]]; - } - return t5; -} -function __decorate(decorators, target, key, desc3) { - var c5 = arguments.length, r5 = c5 < 3 ? target : desc3 === null ? desc3 = Object.getOwnPropertyDescriptor(target, key) : desc3, d5; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r5 = Reflect.decorate(decorators, target, key, desc3); - else for (var i5 = decorators.length - 1; i5 >= 0; i5--) if (d5 = decorators[i5]) r5 = (c5 < 3 ? d5(r5) : c5 > 3 ? d5(target, key, r5) : d5(target, key)) || r5; - return c5 > 3 && r5 && Object.defineProperty(target, key, r5), r5; -} -function __param(paramIndex, decorator) { - return function(target, key) { - decorator(target, key, paramIndex); - }; -} -function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { - function accept(f5) { - if (f5 !== void 0 && typeof f5 !== "function") throw new TypeError("Function expected"); - return f5; - } - var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; - var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; - var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); - var _, done = false; - for (var i5 = decorators.length - 1; i5 >= 0; i5--) { - var context = {}; - for (var p5 in contextIn) context[p5] = p5 === "access" ? {} : contextIn[p5]; - for (var p5 in contextIn.access) context.access[p5] = contextIn.access[p5]; - context.addInitializer = function(f5) { - if (done) throw new TypeError("Cannot add initializers after decoration has completed"); - extraInitializers.push(accept(f5 || null)); - }; - var result = (0, decorators[i5])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context); - if (kind === "accessor") { - if (result === void 0) continue; - if (result === null || typeof result !== "object") throw new TypeError("Object expected"); - if (_ = accept(result.get)) descriptor.get = _; - if (_ = accept(result.set)) descriptor.set = _; - if (_ = accept(result.init)) initializers.unshift(_); - } else if (_ = accept(result)) { - if (kind === "field") initializers.unshift(_); - else descriptor[key] = _; - } - } - if (target) Object.defineProperty(target, contextIn.name, descriptor); - done = true; -} -function __runInitializers(thisArg, initializers, value) { - var useValue = arguments.length > 2; - for (var i5 = 0; i5 < initializers.length; i5++) { - value = useValue ? initializers[i5].call(thisArg, value) : initializers[i5].call(thisArg); - } - return useValue ? value : void 0; -} -function __propKey(x5) { - return typeof x5 === "symbol" ? x5 : "".concat(x5); -} -function __setFunctionName(f5, name, prefix) { - if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : ""; - return Object.defineProperty(f5, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name }); -} -function __metadata(metadataKey, metadataValue) { - if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); -} -function __awaiter(thisArg, _arguments, P, generator2) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve4) { - resolve4(value); - }); - } - return new (P || (P = Promise))(function(resolve4, reject) { - function fulfilled(value) { - try { - step(generator2.next(value)); - } catch (e5) { - reject(e5); - } - } - function rejected(value) { - try { - step(generator2["throw"](value)); - } catch (e5) { - reject(e5); - } - } - function step(result) { - result.done ? resolve4(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator2 = generator2.apply(thisArg, _arguments || [])).next()); - }); -} -function __generator(thisArg, body) { - var _ = { label: 0, sent: function() { - if (t5[0] & 1) throw t5[1]; - return t5[1]; - }, trys: [], ops: [] }, f5, y2, t5, g5 = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype); - return g5.next = verb(0), g5["throw"] = verb(1), g5["return"] = verb(2), typeof Symbol === "function" && (g5[Symbol.iterator] = function() { - return this; - }), g5; - function verb(n5) { - return function(v5) { - return step([n5, v5]); - }; - } - function step(op2) { - if (f5) throw new TypeError("Generator is already executing."); - while (g5 && (g5 = 0, op2[0] && (_ = 0)), _) try { - if (f5 = 1, y2 && (t5 = op2[0] & 2 ? y2["return"] : op2[0] ? y2["throw"] || ((t5 = y2["return"]) && t5.call(y2), 0) : y2.next) && !(t5 = t5.call(y2, op2[1])).done) return t5; - if (y2 = 0, t5) op2 = [op2[0] & 2, t5.value]; - switch (op2[0]) { - case 0: - case 1: - t5 = op2; - break; - case 4: - _.label++; - return { value: op2[1], done: false }; - case 5: - _.label++; - y2 = op2[1]; - op2 = [0]; - continue; - case 7: - op2 = _.ops.pop(); - _.trys.pop(); - continue; - default: - if (!(t5 = _.trys, t5 = t5.length > 0 && t5[t5.length - 1]) && (op2[0] === 6 || op2[0] === 2)) { - _ = 0; - continue; - } - if (op2[0] === 3 && (!t5 || op2[1] > t5[0] && op2[1] < t5[3])) { - _.label = op2[1]; - break; - } - if (op2[0] === 6 && _.label < t5[1]) { - _.label = t5[1]; - t5 = op2; - break; - } - if (t5 && _.label < t5[2]) { - _.label = t5[2]; - _.ops.push(op2); - break; - } - if (t5[2]) _.ops.pop(); - _.trys.pop(); - continue; - } - op2 = body.call(thisArg, _); - } catch (e5) { - op2 = [6, e5]; - y2 = 0; - } finally { - f5 = t5 = 0; - } - if (op2[0] & 5) throw op2[1]; - return { value: op2[0] ? op2[1] : void 0, done: true }; - } -} -function __exportStar(m5, o5) { - for (var p5 in m5) if (p5 !== "default" && !Object.prototype.hasOwnProperty.call(o5, p5)) __createBinding(o5, m5, p5); -} -function __values(o5) { - var s5 = typeof Symbol === "function" && Symbol.iterator, m5 = s5 && o5[s5], i5 = 0; - if (m5) return m5.call(o5); - if (o5 && typeof o5.length === "number") return { - next: function() { - if (o5 && i5 >= o5.length) o5 = void 0; - return { value: o5 && o5[i5++], done: !o5 }; - } - }; - throw new TypeError(s5 ? "Object is not iterable." : "Symbol.iterator is not defined."); -} -function __read(o5, n5) { - var m5 = typeof Symbol === "function" && o5[Symbol.iterator]; - if (!m5) return o5; - var i5 = m5.call(o5), r5, ar = [], e5; - try { - while ((n5 === void 0 || n5-- > 0) && !(r5 = i5.next()).done) ar.push(r5.value); - } catch (error50) { - e5 = { error: error50 }; - } finally { - try { - if (r5 && !r5.done && (m5 = i5["return"])) m5.call(i5); - } finally { - if (e5) throw e5.error; - } - } - return ar; -} -function __spread() { - for (var ar = [], i5 = 0; i5 < arguments.length; i5++) - ar = ar.concat(__read(arguments[i5])); - return ar; -} -function __spreadArrays() { - for (var s5 = 0, i5 = 0, il = arguments.length; i5 < il; i5++) s5 += arguments[i5].length; - for (var r5 = Array(s5), k5 = 0, i5 = 0; i5 < il; i5++) - for (var a5 = arguments[i5], j5 = 0, jl = a5.length; j5 < jl; j5++, k5++) - r5[k5] = a5[j5]; - return r5; -} -function __spreadArray(to, from, pack) { - if (pack || arguments.length === 2) for (var i5 = 0, l5 = from.length, ar; i5 < l5; i5++) { - if (ar || !(i5 in from)) { - if (!ar) ar = Array.prototype.slice.call(from, 0, i5); - ar[i5] = from[i5]; - } - } - return to.concat(ar || Array.prototype.slice.call(from)); -} -function __await(v5) { - return this instanceof __await ? (this.v = v5, this) : new __await(v5); -} -function __asyncGenerator(thisArg, _arguments, generator2) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g5 = generator2.apply(thisArg, _arguments || []), i5, q5 = []; - return i5 = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i5[Symbol.asyncIterator] = function() { - return this; - }, i5; - function awaitReturn(f5) { - return function(v5) { - return Promise.resolve(v5).then(f5, reject); - }; - } - function verb(n5, f5) { - if (g5[n5]) { - i5[n5] = function(v5) { - return new Promise(function(a5, b6) { - q5.push([n5, v5, a5, b6]) > 1 || resume(n5, v5); - }); - }; - if (f5) i5[n5] = f5(i5[n5]); - } - } - function resume(n5, v5) { - try { - step(g5[n5](v5)); - } catch (e5) { - settle(q5[0][3], e5); - } - } - function step(r5) { - r5.value instanceof __await ? Promise.resolve(r5.value.v).then(fulfill, reject) : settle(q5[0][2], r5); - } - function fulfill(value) { - resume("next", value); - } - function reject(value) { - resume("throw", value); - } - function settle(f5, v5) { - if (f5(v5), q5.shift(), q5.length) resume(q5[0][0], q5[0][1]); - } -} -function __asyncDelegator(o5) { - var i5, p5; - return i5 = {}, verb("next"), verb("throw", function(e5) { - throw e5; - }), verb("return"), i5[Symbol.iterator] = function() { - return this; - }, i5; - function verb(n5, f5) { - i5[n5] = o5[n5] ? function(v5) { - return (p5 = !p5) ? { value: __await(o5[n5](v5)), done: false } : f5 ? f5(v5) : v5; - } : f5; - } -} -function __asyncValues(o5) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var m5 = o5[Symbol.asyncIterator], i5; - return m5 ? m5.call(o5) : (o5 = typeof __values === "function" ? __values(o5) : o5[Symbol.iterator](), i5 = {}, verb("next"), verb("throw"), verb("return"), i5[Symbol.asyncIterator] = function() { - return this; - }, i5); - function verb(n5) { - i5[n5] = o5[n5] && function(v5) { - return new Promise(function(resolve4, reject) { - v5 = o5[n5](v5), settle(resolve4, reject, v5.done, v5.value); - }); - }; - } - function settle(resolve4, reject, d5, v5) { - Promise.resolve(v5).then(function(v6) { - resolve4({ value: v6, done: d5 }); - }, reject); - } -} -function __makeTemplateObject(cooked, raw) { - if (Object.defineProperty) { - Object.defineProperty(cooked, "raw", { value: raw }); - } else { - cooked.raw = raw; - } - return cooked; -} -function __importStar(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k5 = ownKeys(mod), i5 = 0; i5 < k5.length; i5++) if (k5[i5] !== "default") __createBinding(result, mod, k5[i5]); - } - __setModuleDefault(result, mod); - return result; -} -function __importDefault(mod) { - return mod && mod.__esModule ? mod : { default: mod }; -} -function __classPrivateFieldGet(receiver, state2, kind, f5) { - if (kind === "a" && !f5) throw new TypeError("Private accessor was defined without a getter"); - if (typeof state2 === "function" ? receiver !== state2 || !f5 : !state2.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); - return kind === "m" ? f5 : kind === "a" ? f5.call(receiver) : f5 ? f5.value : state2.get(receiver); -} -function __classPrivateFieldSet(receiver, state2, value, kind, f5) { - if (kind === "m") throw new TypeError("Private method is not writable"); - if (kind === "a" && !f5) throw new TypeError("Private accessor was defined without a setter"); - if (typeof state2 === "function" ? receiver !== state2 || !f5 : !state2.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); - return kind === "a" ? f5.call(receiver, value) : f5 ? f5.value = value : state2.set(receiver, value), value; -} -function __classPrivateFieldIn(state2, receiver) { - if (receiver === null || typeof receiver !== "object" && typeof receiver !== "function") throw new TypeError("Cannot use 'in' operator on non-object"); - return typeof state2 === "function" ? receiver === state2 : state2.has(receiver); -} -function __addDisposableResource(env2, value, async) { - if (value !== null && value !== void 0) { - if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected."); - var dispose, inner; - if (async) { - if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); - dispose = value[Symbol.asyncDispose]; - } - if (dispose === void 0) { - if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); - dispose = value[Symbol.dispose]; - if (async) inner = dispose; - } - if (typeof dispose !== "function") throw new TypeError("Object not disposable."); - if (inner) dispose = function() { - try { - inner.call(this); - } catch (e5) { - return Promise.reject(e5); - } - }; - env2.stack.push({ value, dispose, async }); - } else if (async) { - env2.stack.push({ async: true }); - } - return value; -} -function __disposeResources(env2) { - function fail(e5) { - env2.error = env2.hasError ? new _SuppressedError(e5, env2.error, "An error was suppressed during disposal.") : e5; - env2.hasError = true; - } - var r5, s5 = 0; - function next() { - while (r5 = env2.stack.pop()) { - try { - if (!r5.async && s5 === 1) return s5 = 0, env2.stack.push(r5), Promise.resolve().then(next); - if (r5.dispose) { - var result = r5.dispose.call(r5.value); - if (r5.async) return s5 |= 2, Promise.resolve(result).then(next, function(e5) { - fail(e5); - return next(); - }); - } else s5 |= 1; - } catch (e5) { - fail(e5); - } - } - if (s5 === 1) return env2.hasError ? Promise.reject(env2.error) : Promise.resolve(); - if (env2.hasError) throw env2.error; - } - return next(); -} -function __rewriteRelativeImportExtension(path53, preserveJsx) { - if (typeof path53 === "string" && /^\.\.?\//.test(path53)) { - return path53.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function(m5, tsx, d5, ext, cm) { - return tsx ? preserveJsx ? ".jsx" : ".js" : d5 && (!ext || !cm) ? m5 : d5 + ext + "." + cm.toLowerCase() + "js"; - }); - } - return path53; -} -var extendStatics, __assign, __createBinding, __setModuleDefault, ownKeys, _SuppressedError, tslib_es6_default; -var init_tslib_es6 = __esm({ - "node_modules/.pnpm/tslib@2.8.1/node_modules/tslib/tslib.es6.mjs"() { - extendStatics = function(d5, b6) { - extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d6, b7) { - d6.__proto__ = b7; - } || function(d6, b7) { - for (var p5 in b7) if (Object.prototype.hasOwnProperty.call(b7, p5)) d6[p5] = b7[p5]; - }; - return extendStatics(d5, b6); - }; - __assign = function() { - __assign = Object.assign || function __assign2(t5) { - for (var s5, i5 = 1, n5 = arguments.length; i5 < n5; i5++) { - s5 = arguments[i5]; - for (var p5 in s5) if (Object.prototype.hasOwnProperty.call(s5, p5)) t5[p5] = s5[p5]; - } - return t5; - }; - return __assign.apply(this, arguments); - }; - __createBinding = Object.create ? (function(o5, m5, k5, k22) { - if (k22 === void 0) k22 = k5; - var desc3 = Object.getOwnPropertyDescriptor(m5, k5); - if (!desc3 || ("get" in desc3 ? !m5.__esModule : desc3.writable || desc3.configurable)) { - desc3 = { enumerable: true, get: function() { - return m5[k5]; - } }; - } - Object.defineProperty(o5, k22, desc3); - }) : (function(o5, m5, k5, k22) { - if (k22 === void 0) k22 = k5; - o5[k22] = m5[k5]; - }); - __setModuleDefault = Object.create ? (function(o5, v5) { - Object.defineProperty(o5, "default", { enumerable: true, value: v5 }); - }) : function(o5, v5) { - o5["default"] = v5; - }; - ownKeys = function(o5) { - ownKeys = Object.getOwnPropertyNames || function(o6) { - var ar = []; - for (var k5 in o6) if (Object.prototype.hasOwnProperty.call(o6, k5)) ar[ar.length] = k5; - return ar; - }; - return ownKeys(o5); - }; - _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function(error50, suppressed, message2) { - var e5 = new Error(message2); - return e5.name = "SuppressedError", e5.error = error50, e5.suppressed = suppressed, e5; - }; - tslib_es6_default = { - __extends, - __assign, - __rest, - __decorate, - __param, - __esDecorate, - __runInitializers, - __propKey, - __setFunctionName, - __metadata, - __awaiter, - __generator, - __createBinding, - __exportStar, - __values, - __read, - __spread, - __spreadArrays, - __spreadArray, - __await, - __asyncGenerator, - __asyncDelegator, - __asyncValues, - __makeTemplateObject, - __importStar, - __importDefault, - __classPrivateFieldGet, - __classPrivateFieldSet, - __classPrivateFieldIn, - __addDisposableResource, - __disposeResources, - __rewriteRelativeImportExtension - }; - } -}); - -// node_modules/.pnpm/@smithy+is-array-buffer@2.2.0/node_modules/@smithy/is-array-buffer/dist-cjs/index.js -var require_dist_cjs14 = __commonJS({ - "node_modules/.pnpm/@smithy+is-array-buffer@2.2.0/node_modules/@smithy/is-array-buffer/dist-cjs/index.js"(exports, module) { - var __defProp4 = Object.defineProperty; - var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp4 = Object.prototype.hasOwnProperty; - var __name = (target, value) => __defProp4(target, "name", { value, configurable: true }); - var __export3 = (target, all) => { - for (var name in all) - __defProp4(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps3 = (to, from, except2, desc3) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp4.call(to, key) && key !== except2) - __defProp4(to, key, { get: () => from[key], enumerable: !(desc3 = __getOwnPropDesc3(from, key)) || desc3.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps3(__defProp4({}, "__esModule", { value: true }), mod); - var src_exports = {}; - __export3(src_exports, { - isArrayBuffer: () => isArrayBuffer - }); - module.exports = __toCommonJS2(src_exports); - var isArrayBuffer = /* @__PURE__ */ __name((arg) => typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer || Object.prototype.toString.call(arg) === "[object ArrayBuffer]", "isArrayBuffer"); - } -}); - -// node_modules/.pnpm/@smithy+util-buffer-from@2.2.0/node_modules/@smithy/util-buffer-from/dist-cjs/index.js -var require_dist_cjs15 = __commonJS({ - "node_modules/.pnpm/@smithy+util-buffer-from@2.2.0/node_modules/@smithy/util-buffer-from/dist-cjs/index.js"(exports, module) { - var __defProp4 = Object.defineProperty; - var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp4 = Object.prototype.hasOwnProperty; - var __name = (target, value) => __defProp4(target, "name", { value, configurable: true }); - var __export3 = (target, all) => { - for (var name in all) - __defProp4(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps3 = (to, from, except2, desc3) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp4.call(to, key) && key !== except2) - __defProp4(to, key, { get: () => from[key], enumerable: !(desc3 = __getOwnPropDesc3(from, key)) || desc3.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps3(__defProp4({}, "__esModule", { value: true }), mod); - var src_exports = {}; - __export3(src_exports, { - fromArrayBuffer: () => fromArrayBuffer, - fromString: () => fromString - }); - module.exports = __toCommonJS2(src_exports); - var import_is_array_buffer = require_dist_cjs14(); - var import_buffer3 = __require("buffer"); - var fromArrayBuffer = /* @__PURE__ */ __name((input, offset = 0, length = input.byteLength - offset) => { - if (!(0, import_is_array_buffer.isArrayBuffer)(input)) { - throw new TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof input} (${input})`); - } - return import_buffer3.Buffer.from(input, offset, length); - }, "fromArrayBuffer"); - var fromString = /* @__PURE__ */ __name((input, encoding) => { - if (typeof input !== "string") { - throw new TypeError(`The "input" argument must be of type string. Received type ${typeof input} (${input})`); - } - return encoding ? import_buffer3.Buffer.from(input, encoding) : import_buffer3.Buffer.from(input); - }, "fromString"); - } -}); - -// node_modules/.pnpm/@smithy+util-utf8@2.3.0/node_modules/@smithy/util-utf8/dist-cjs/index.js -var require_dist_cjs16 = __commonJS({ - "node_modules/.pnpm/@smithy+util-utf8@2.3.0/node_modules/@smithy/util-utf8/dist-cjs/index.js"(exports, module) { - var __defProp4 = Object.defineProperty; - var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames3 = Object.getOwnPropertyNames; - var __hasOwnProp4 = Object.prototype.hasOwnProperty; - var __name = (target, value) => __defProp4(target, "name", { value, configurable: true }); - var __export3 = (target, all) => { - for (var name in all) - __defProp4(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps3 = (to, from, except2, desc3) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames3(from)) - if (!__hasOwnProp4.call(to, key) && key !== except2) - __defProp4(to, key, { get: () => from[key], enumerable: !(desc3 = __getOwnPropDesc3(from, key)) || desc3.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps3(__defProp4({}, "__esModule", { value: true }), mod); - var src_exports = {}; - __export3(src_exports, { - fromUtf8: () => fromUtf88, - toUint8Array: () => toUint8Array2, - toUtf8: () => toUtf811 - }); - module.exports = __toCommonJS2(src_exports); - var import_util_buffer_from = require_dist_cjs15(); - var fromUtf88 = /* @__PURE__ */ __name((input) => { - const buf = (0, import_util_buffer_from.fromString)(input, "utf8"); - return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength / Uint8Array.BYTES_PER_ELEMENT); - }, "fromUtf8"); - var toUint8Array2 = /* @__PURE__ */ __name((data2) => { - if (typeof data2 === "string") { - return fromUtf88(data2); - } - if (ArrayBuffer.isView(data2)) { - return new Uint8Array(data2.buffer, data2.byteOffset, data2.byteLength / Uint8Array.BYTES_PER_ELEMENT); - } - return new Uint8Array(data2); - }, "toUint8Array"); - var toUtf811 = /* @__PURE__ */ __name((input) => { - if (typeof input === "string") { - return input; - } - if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") { - throw new Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array."); - } - return (0, import_util_buffer_from.fromArrayBuffer)(input.buffer, input.byteOffset, input.byteLength).toString("utf8"); - }, "toUtf8"); - } -}); - -// node_modules/.pnpm/@aws-crypto+util@5.2.0/node_modules/@aws-crypto/util/build/main/convertToBuffer.js -var require_convertToBuffer = __commonJS({ - "node_modules/.pnpm/@aws-crypto+util@5.2.0/node_modules/@aws-crypto/util/build/main/convertToBuffer.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.convertToBuffer = void 0; - var util_utf8_1 = require_dist_cjs16(); - var fromUtf88 = typeof Buffer !== "undefined" && Buffer.from ? function(input) { - return Buffer.from(input, "utf8"); - } : util_utf8_1.fromUtf8; - function convertToBuffer(data2) { - if (data2 instanceof Uint8Array) - return data2; - if (typeof data2 === "string") { - return fromUtf88(data2); - } - if (ArrayBuffer.isView(data2)) { - return new Uint8Array(data2.buffer, data2.byteOffset, data2.byteLength / Uint8Array.BYTES_PER_ELEMENT); - } - return new Uint8Array(data2); - } - exports.convertToBuffer = convertToBuffer; - } -}); - -// node_modules/.pnpm/@aws-crypto+util@5.2.0/node_modules/@aws-crypto/util/build/main/isEmptyData.js -var require_isEmptyData = __commonJS({ - "node_modules/.pnpm/@aws-crypto+util@5.2.0/node_modules/@aws-crypto/util/build/main/isEmptyData.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.isEmptyData = void 0; - function isEmptyData(data2) { - if (typeof data2 === "string") { - return data2.length === 0; - } - return data2.byteLength === 0; - } - exports.isEmptyData = isEmptyData; - } -}); - -// node_modules/.pnpm/@aws-crypto+util@5.2.0/node_modules/@aws-crypto/util/build/main/numToUint8.js -var require_numToUint8 = __commonJS({ - "node_modules/.pnpm/@aws-crypto+util@5.2.0/node_modules/@aws-crypto/util/build/main/numToUint8.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.numToUint8 = void 0; - function numToUint8(num) { - return new Uint8Array([ - (num & 4278190080) >> 24, - (num & 16711680) >> 16, - (num & 65280) >> 8, - num & 255 - ]); - } - exports.numToUint8 = numToUint8; - } -}); - -// node_modules/.pnpm/@aws-crypto+util@5.2.0/node_modules/@aws-crypto/util/build/main/uint32ArrayFrom.js -var require_uint32ArrayFrom = __commonJS({ - "node_modules/.pnpm/@aws-crypto+util@5.2.0/node_modules/@aws-crypto/util/build/main/uint32ArrayFrom.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.uint32ArrayFrom = void 0; - function uint32ArrayFrom(a_lookUpTable) { - if (!Uint32Array.from) { - var return_array = new Uint32Array(a_lookUpTable.length); - var a_index = 0; - while (a_index < a_lookUpTable.length) { - return_array[a_index] = a_lookUpTable[a_index]; - a_index += 1; - } - return return_array; - } - return Uint32Array.from(a_lookUpTable); - } - exports.uint32ArrayFrom = uint32ArrayFrom; - } -}); - -// node_modules/.pnpm/@aws-crypto+util@5.2.0/node_modules/@aws-crypto/util/build/main/index.js -var require_main2 = __commonJS({ - "node_modules/.pnpm/@aws-crypto+util@5.2.0/node_modules/@aws-crypto/util/build/main/index.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.uint32ArrayFrom = exports.numToUint8 = exports.isEmptyData = exports.convertToBuffer = void 0; - var convertToBuffer_1 = require_convertToBuffer(); - Object.defineProperty(exports, "convertToBuffer", { enumerable: true, get: function() { - return convertToBuffer_1.convertToBuffer; - } }); - var isEmptyData_1 = require_isEmptyData(); - Object.defineProperty(exports, "isEmptyData", { enumerable: true, get: function() { - return isEmptyData_1.isEmptyData; - } }); - var numToUint8_1 = require_numToUint8(); - Object.defineProperty(exports, "numToUint8", { enumerable: true, get: function() { - return numToUint8_1.numToUint8; - } }); - var uint32ArrayFrom_1 = require_uint32ArrayFrom(); - Object.defineProperty(exports, "uint32ArrayFrom", { enumerable: true, get: function() { - return uint32ArrayFrom_1.uint32ArrayFrom; - } }); - } -}); - -// node_modules/.pnpm/@aws-crypto+crc32c@5.2.0/node_modules/@aws-crypto/crc32c/build/main/aws_crc32c.js -var require_aws_crc32c = __commonJS({ - "node_modules/.pnpm/@aws-crypto+crc32c@5.2.0/node_modules/@aws-crypto/crc32c/build/main/aws_crc32c.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.AwsCrc32c = void 0; - var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); - var util_1 = require_main2(); - var index_1 = require_main3(); - var AwsCrc32c = ( - /** @class */ - (function() { - function AwsCrc32c2() { - this.crc32c = new index_1.Crc32c(); - } - AwsCrc32c2.prototype.update = function(toHash) { - if ((0, util_1.isEmptyData)(toHash)) - return; - this.crc32c.update((0, util_1.convertToBuffer)(toHash)); - }; - AwsCrc32c2.prototype.digest = function() { - return tslib_1.__awaiter(this, void 0, void 0, function() { - return tslib_1.__generator(this, function(_a6) { - return [2, (0, util_1.numToUint8)(this.crc32c.digest())]; - }); - }); - }; - AwsCrc32c2.prototype.reset = function() { - this.crc32c = new index_1.Crc32c(); - }; - return AwsCrc32c2; - })() - ); - exports.AwsCrc32c = AwsCrc32c; - } -}); - -// node_modules/.pnpm/@aws-crypto+crc32c@5.2.0/node_modules/@aws-crypto/crc32c/build/main/index.js -var require_main3 = __commonJS({ - "node_modules/.pnpm/@aws-crypto+crc32c@5.2.0/node_modules/@aws-crypto/crc32c/build/main/index.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.AwsCrc32c = exports.Crc32c = exports.crc32c = void 0; - var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); - var util_1 = require_main2(); - function crc32c(data2) { - return new Crc32c().update(data2).digest(); - } - exports.crc32c = crc32c; - var Crc32c = ( - /** @class */ - (function() { - function Crc32c2() { - this.checksum = 4294967295; - } - Crc32c2.prototype.update = function(data2) { - var e_1, _a6; - try { - for (var data_1 = tslib_1.__values(data2), data_1_1 = data_1.next(); !data_1_1.done; data_1_1 = data_1.next()) { - var byte = data_1_1.value; - this.checksum = this.checksum >>> 8 ^ lookupTable[(this.checksum ^ byte) & 255]; - } - } catch (e_1_1) { - e_1 = { error: e_1_1 }; - } finally { - try { - if (data_1_1 && !data_1_1.done && (_a6 = data_1.return)) _a6.call(data_1); - } finally { - if (e_1) throw e_1.error; - } - } - return this; - }; - Crc32c2.prototype.digest = function() { - return (this.checksum ^ 4294967295) >>> 0; - }; - return Crc32c2; - })() - ); - exports.Crc32c = Crc32c; - var a_lookupTable = [ - 0, - 4067132163, - 3778769143, - 324072436, - 3348797215, - 904991772, - 648144872, - 3570033899, - 2329499855, - 2024987596, - 1809983544, - 2575936315, - 1296289744, - 3207089363, - 2893594407, - 1578318884, - 274646895, - 3795141740, - 4049975192, - 51262619, - 3619967088, - 632279923, - 922689671, - 3298075524, - 2592579488, - 1760304291, - 2075979607, - 2312596564, - 1562183871, - 2943781820, - 3156637768, - 1313733451, - 549293790, - 3537243613, - 3246849577, - 871202090, - 3878099393, - 357341890, - 102525238, - 4101499445, - 2858735121, - 1477399826, - 1264559846, - 3107202533, - 1845379342, - 2677391885, - 2361733625, - 2125378298, - 820201905, - 3263744690, - 3520608582, - 598981189, - 4151959214, - 85089709, - 373468761, - 3827903834, - 3124367742, - 1213305469, - 1526817161, - 2842354314, - 2107672161, - 2412447074, - 2627466902, - 1861252501, - 1098587580, - 3004210879, - 2688576843, - 1378610760, - 2262928035, - 1955203488, - 1742404180, - 2511436119, - 3416409459, - 969524848, - 714683780, - 3639785095, - 205050476, - 4266873199, - 3976438427, - 526918040, - 1361435347, - 2739821008, - 2954799652, - 1114974503, - 2529119692, - 1691668175, - 2005155131, - 2247081528, - 3690758684, - 697762079, - 986182379, - 3366744552, - 476452099, - 3993867776, - 4250756596, - 255256311, - 1640403810, - 2477592673, - 2164122517, - 1922457750, - 2791048317, - 1412925310, - 1197962378, - 3037525897, - 3944729517, - 427051182, - 170179418, - 4165941337, - 746937522, - 3740196785, - 3451792453, - 1070968646, - 1905808397, - 2213795598, - 2426610938, - 1657317369, - 3053634322, - 1147748369, - 1463399397, - 2773627110, - 4215344322, - 153784257, - 444234805, - 3893493558, - 1021025245, - 3467647198, - 3722505002, - 797665321, - 2197175160, - 1889384571, - 1674398607, - 2443626636, - 1164749927, - 3070701412, - 2757221520, - 1446797203, - 137323447, - 4198817972, - 3910406976, - 461344835, - 3484808360, - 1037989803, - 781091935, - 3705997148, - 2460548119, - 1623424788, - 1939049696, - 2180517859, - 1429367560, - 2807687179, - 3020495871, - 1180866812, - 410100952, - 3927582683, - 4182430767, - 186734380, - 3756733383, - 763408580, - 1053836080, - 3434856499, - 2722870694, - 1344288421, - 1131464017, - 2971354706, - 1708204729, - 2545590714, - 2229949006, - 1988219213, - 680717673, - 3673779818, - 3383336350, - 1002577565, - 4010310262, - 493091189, - 238226049, - 4233660802, - 2987750089, - 1082061258, - 1395524158, - 2705686845, - 1972364758, - 2279892693, - 2494862625, - 1725896226, - 952904198, - 3399985413, - 3656866545, - 731699698, - 4283874585, - 222117402, - 510512622, - 3959836397, - 3280807620, - 837199303, - 582374963, - 3504198960, - 68661723, - 4135334616, - 3844915500, - 390545967, - 1230274059, - 3141532936, - 2825850620, - 1510247935, - 2395924756, - 2091215383, - 1878366691, - 2644384480, - 3553878443, - 565732008, - 854102364, - 3229815391, - 340358836, - 3861050807, - 4117890627, - 119113024, - 1493875044, - 2875275879, - 3090270611, - 1247431312, - 2660249211, - 1828433272, - 2141937292, - 2378227087, - 3811616794, - 291187481, - 34330861, - 4032846830, - 615137029, - 3603020806, - 3314634738, - 939183345, - 1776939221, - 2609017814, - 2295496738, - 2058945313, - 2926798794, - 1545135305, - 1330124605, - 3173225534, - 4084100981, - 17165430, - 307568514, - 3762199681, - 888469610, - 3332340585, - 3587147933, - 665062302, - 2042050490, - 2346497209, - 2559330125, - 1793573966, - 3190661285, - 1279665062, - 1595330642, - 2910671697 - ]; - var lookupTable = (0, util_1.uint32ArrayFrom)(a_lookupTable); - var aws_crc32c_1 = require_aws_crc32c(); - Object.defineProperty(exports, "AwsCrc32c", { enumerable: true, get: function() { - return aws_crc32c_1.AwsCrc32c; - } }); - } -}); - -// node_modules/.pnpm/@aws-sdk+crc64-nvme@3.972.6/node_modules/@aws-sdk/crc64-nvme/dist-cjs/index.js -var require_dist_cjs17 = __commonJS({ - "node_modules/.pnpm/@aws-sdk+crc64-nvme@3.972.6/node_modules/@aws-sdk/crc64-nvme/dist-cjs/index.js"(exports) { - "use strict"; - var generateCRC64NVMETable = () => { - const sliceLength = 8; - const tables = new Array(sliceLength); - for (let slice = 0; slice < sliceLength; slice++) { - const table = new Array(512); - for (let i5 = 0; i5 < 256; i5++) { - let crc = BigInt(i5); - for (let j5 = 0; j5 < 8 * (slice + 1); j5++) { - if (crc & 1n) { - crc = crc >> 1n ^ 0x9a6c9329ac4bc9b5n; - } else { - crc = crc >> 1n; - } - } - table[i5 * 2] = Number(crc >> 32n & 0xffffffffn); - table[i5 * 2 + 1] = Number(crc & 0xffffffffn); - } - tables[slice] = new Uint32Array(table); - } - return tables; - }; - var CRC64_NVME_REVERSED_TABLE; - var t0; - var t1; - var t22; - var t32; - var t42; - var t5; - var t6; - var t7; - var ensureTablesInitialized = () => { - if (!CRC64_NVME_REVERSED_TABLE) { - CRC64_NVME_REVERSED_TABLE = generateCRC64NVMETable(); - [t0, t1, t22, t32, t42, t5, t6, t7] = CRC64_NVME_REVERSED_TABLE; - } - }; - var Crc64Nvme = class { - c1 = 0; - c2 = 0; - constructor() { - ensureTablesInitialized(); - this.reset(); - } - update(data2) { - const len = data2.length; - let i5 = 0; - let crc1 = this.c1; - let crc2 = this.c2; - while (i5 + 8 <= len) { - const idx0 = ((crc2 ^ data2[i5++]) & 255) << 1; - const idx1 = ((crc2 >>> 8 ^ data2[i5++]) & 255) << 1; - const idx2 = ((crc2 >>> 16 ^ data2[i5++]) & 255) << 1; - const idx3 = ((crc2 >>> 24 ^ data2[i5++]) & 255) << 1; - const idx4 = ((crc1 ^ data2[i5++]) & 255) << 1; - const idx5 = ((crc1 >>> 8 ^ data2[i5++]) & 255) << 1; - const idx6 = ((crc1 >>> 16 ^ data2[i5++]) & 255) << 1; - const idx7 = ((crc1 >>> 24 ^ data2[i5++]) & 255) << 1; - crc1 = t7[idx0] ^ t6[idx1] ^ t5[idx2] ^ t42[idx3] ^ t32[idx4] ^ t22[idx5] ^ t1[idx6] ^ t0[idx7]; - crc2 = t7[idx0 + 1] ^ t6[idx1 + 1] ^ t5[idx2 + 1] ^ t42[idx3 + 1] ^ t32[idx4 + 1] ^ t22[idx5 + 1] ^ t1[idx6 + 1] ^ t0[idx7 + 1]; - } - while (i5 < len) { - const idx = ((crc2 ^ data2[i5]) & 255) << 1; - crc2 = (crc2 >>> 8 | (crc1 & 255) << 24) >>> 0; - crc1 = crc1 >>> 8 ^ t0[idx]; - crc2 ^= t0[idx + 1]; - i5++; - } - this.c1 = crc1; - this.c2 = crc2; - } - async digest() { - const c1 = this.c1 ^ 4294967295; - const c22 = this.c2 ^ 4294967295; - return new Uint8Array([ - c1 >>> 24, - c1 >>> 16 & 255, - c1 >>> 8 & 255, - c1 & 255, - c22 >>> 24, - c22 >>> 16 & 255, - c22 >>> 8 & 255, - c22 & 255 - ]); - } - reset() { - this.c1 = 4294967295; - this.c2 = 4294967295; - } - }; - var crc64NvmeCrtContainer = { - CrtCrc64Nvme: null - }; - exports.Crc64Nvme = Crc64Nvme; - exports.crc64NvmeCrtContainer = crc64NvmeCrtContainer; - } -}); - -// node_modules/.pnpm/@aws-crypto+crc32@5.2.0/node_modules/@aws-crypto/crc32/build/main/aws_crc32.js -var require_aws_crc32 = __commonJS({ - "node_modules/.pnpm/@aws-crypto+crc32@5.2.0/node_modules/@aws-crypto/crc32/build/main/aws_crc32.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.AwsCrc32 = void 0; - var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); - var util_1 = require_main2(); - var index_1 = require_main4(); - var AwsCrc32 = ( - /** @class */ - (function() { - function AwsCrc322() { - this.crc32 = new index_1.Crc32(); - } - AwsCrc322.prototype.update = function(toHash) { - if ((0, util_1.isEmptyData)(toHash)) - return; - this.crc32.update((0, util_1.convertToBuffer)(toHash)); - }; - AwsCrc322.prototype.digest = function() { - return tslib_1.__awaiter(this, void 0, void 0, function() { - return tslib_1.__generator(this, function(_a6) { - return [2, (0, util_1.numToUint8)(this.crc32.digest())]; - }); - }); - }; - AwsCrc322.prototype.reset = function() { - this.crc32 = new index_1.Crc32(); - }; - return AwsCrc322; - })() - ); - exports.AwsCrc32 = AwsCrc32; - } -}); - -// node_modules/.pnpm/@aws-crypto+crc32@5.2.0/node_modules/@aws-crypto/crc32/build/main/index.js -var require_main4 = __commonJS({ - "node_modules/.pnpm/@aws-crypto+crc32@5.2.0/node_modules/@aws-crypto/crc32/build/main/index.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.AwsCrc32 = exports.Crc32 = exports.crc32 = void 0; - var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); - var util_1 = require_main2(); - function crc32(data2) { - return new Crc32().update(data2).digest(); - } - exports.crc32 = crc32; - var Crc32 = ( - /** @class */ - (function() { - function Crc322() { - this.checksum = 4294967295; - } - Crc322.prototype.update = function(data2) { - var e_1, _a6; - try { - for (var data_1 = tslib_1.__values(data2), data_1_1 = data_1.next(); !data_1_1.done; data_1_1 = data_1.next()) { - var byte = data_1_1.value; - this.checksum = this.checksum >>> 8 ^ lookupTable[(this.checksum ^ byte) & 255]; - } - } catch (e_1_1) { - e_1 = { error: e_1_1 }; - } finally { - try { - if (data_1_1 && !data_1_1.done && (_a6 = data_1.return)) _a6.call(data_1); - } finally { - if (e_1) throw e_1.error; - } - } - return this; - }; - Crc322.prototype.digest = function() { - return (this.checksum ^ 4294967295) >>> 0; - }; - return Crc322; - })() - ); - exports.Crc32 = Crc32; - var a_lookUpTable = [ - 0, - 1996959894, - 3993919788, - 2567524794, - 124634137, - 1886057615, - 3915621685, - 2657392035, - 249268274, - 2044508324, - 3772115230, - 2547177864, - 162941995, - 2125561021, - 3887607047, - 2428444049, - 498536548, - 1789927666, - 4089016648, - 2227061214, - 450548861, - 1843258603, - 4107580753, - 2211677639, - 325883990, - 1684777152, - 4251122042, - 2321926636, - 335633487, - 1661365465, - 4195302755, - 2366115317, - 997073096, - 1281953886, - 3579855332, - 2724688242, - 1006888145, - 1258607687, - 3524101629, - 2768942443, - 901097722, - 1119000684, - 3686517206, - 2898065728, - 853044451, - 1172266101, - 3705015759, - 2882616665, - 651767980, - 1373503546, - 3369554304, - 3218104598, - 565507253, - 1454621731, - 3485111705, - 3099436303, - 671266974, - 1594198024, - 3322730930, - 2970347812, - 795835527, - 1483230225, - 3244367275, - 3060149565, - 1994146192, - 31158534, - 2563907772, - 4023717930, - 1907459465, - 112637215, - 2680153253, - 3904427059, - 2013776290, - 251722036, - 2517215374, - 3775830040, - 2137656763, - 141376813, - 2439277719, - 3865271297, - 1802195444, - 476864866, - 2238001368, - 4066508878, - 1812370925, - 453092731, - 2181625025, - 4111451223, - 1706088902, - 314042704, - 2344532202, - 4240017532, - 1658658271, - 366619977, - 2362670323, - 4224994405, - 1303535960, - 984961486, - 2747007092, - 3569037538, - 1256170817, - 1037604311, - 2765210733, - 3554079995, - 1131014506, - 879679996, - 2909243462, - 3663771856, - 1141124467, - 855842277, - 2852801631, - 3708648649, - 1342533948, - 654459306, - 3188396048, - 3373015174, - 1466479909, - 544179635, - 3110523913, - 3462522015, - 1591671054, - 702138776, - 2966460450, - 3352799412, - 1504918807, - 783551873, - 3082640443, - 3233442989, - 3988292384, - 2596254646, - 62317068, - 1957810842, - 3939845945, - 2647816111, - 81470997, - 1943803523, - 3814918930, - 2489596804, - 225274430, - 2053790376, - 3826175755, - 2466906013, - 167816743, - 2097651377, - 4027552580, - 2265490386, - 503444072, - 1762050814, - 4150417245, - 2154129355, - 426522225, - 1852507879, - 4275313526, - 2312317920, - 282753626, - 1742555852, - 4189708143, - 2394877945, - 397917763, - 1622183637, - 3604390888, - 2714866558, - 953729732, - 1340076626, - 3518719985, - 2797360999, - 1068828381, - 1219638859, - 3624741850, - 2936675148, - 906185462, - 1090812512, - 3747672003, - 2825379669, - 829329135, - 1181335161, - 3412177804, - 3160834842, - 628085408, - 1382605366, - 3423369109, - 3138078467, - 570562233, - 1426400815, - 3317316542, - 2998733608, - 733239954, - 1555261956, - 3268935591, - 3050360625, - 752459403, - 1541320221, - 2607071920, - 3965973030, - 1969922972, - 40735498, - 2617837225, - 3943577151, - 1913087877, - 83908371, - 2512341634, - 3803740692, - 2075208622, - 213261112, - 2463272603, - 3855990285, - 2094854071, - 198958881, - 2262029012, - 4057260610, - 1759359992, - 534414190, - 2176718541, - 4139329115, - 1873836001, - 414664567, - 2282248934, - 4279200368, - 1711684554, - 285281116, - 2405801727, - 4167216745, - 1634467795, - 376229701, - 2685067896, - 3608007406, - 1308918612, - 956543938, - 2808555105, - 3495958263, - 1231636301, - 1047427035, - 2932959818, - 3654703836, - 1088359270, - 936918e3, - 2847714899, - 3736837829, - 1202900863, - 817233897, - 3183342108, - 3401237130, - 1404277552, - 615818150, - 3134207493, - 3453421203, - 1423857449, - 601450431, - 3009837614, - 3294710456, - 1567103746, - 711928724, - 3020668471, - 3272380065, - 1510334235, - 755167117 - ]; - var lookupTable = (0, util_1.uint32ArrayFrom)(a_lookUpTable); - var aws_crc32_1 = require_aws_crc32(); - Object.defineProperty(exports, "AwsCrc32", { enumerable: true, get: function() { - return aws_crc32_1.AwsCrc32; - } }); - } -}); - -// node_modules/.pnpm/@aws-sdk+middleware-flexible-checksums@3.974.7/node_modules/@aws-sdk/middleware-flexible-checksums/dist-cjs/getCrc32ChecksumAlgorithmFunction.js -var require_getCrc32ChecksumAlgorithmFunction = __commonJS({ - "node_modules/.pnpm/@aws-sdk+middleware-flexible-checksums@3.974.7/node_modules/@aws-sdk/middleware-flexible-checksums/dist-cjs/getCrc32ChecksumAlgorithmFunction.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.getCrc32ChecksumAlgorithmFunction = void 0; - var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); - var crc32_1 = require_main4(); - var util_1 = require_main2(); - var zlib = tslib_1.__importStar(__require("node:zlib")); - var NodeCrc32 = class { - checksum = 0; - update(data2) { - this.checksum = zlib.crc32(data2, this.checksum); - } - async digest() { - return (0, util_1.numToUint8)(this.checksum); - } - reset() { - this.checksum = 0; - } - }; - var getCrc32ChecksumAlgorithmFunction = () => { - if (typeof zlib.crc32 === "undefined") { - return crc32_1.AwsCrc32; - } - return NodeCrc32; - }; - exports.getCrc32ChecksumAlgorithmFunction = getCrc32ChecksumAlgorithmFunction; - } -}); - -// node_modules/.pnpm/@smithy+util-middleware@4.2.13/node_modules/@smithy/util-middleware/dist-cjs/index.js -var require_dist_cjs18 = __commonJS({ - "node_modules/.pnpm/@smithy+util-middleware@4.2.13/node_modules/@smithy/util-middleware/dist-cjs/index.js"(exports) { - "use strict"; - var types2 = require_dist_cjs(); - var getSmithyContext11 = (context) => context[types2.SMITHY_CONTEXT_KEY] || (context[types2.SMITHY_CONTEXT_KEY] = {}); - var normalizeProvider6 = (input) => { - if (typeof input === "function") - return input; - const promisified = Promise.resolve(input); - return () => promisified; - }; - exports.getSmithyContext = getSmithyContext11; - exports.normalizeProvider = normalizeProvider6; - } -}); - -// node_modules/.pnpm/@aws-sdk+middleware-flexible-checksums@3.974.7/node_modules/@aws-sdk/middleware-flexible-checksums/dist-cjs/index.js -var require_dist_cjs19 = __commonJS({ - "node_modules/.pnpm/@aws-sdk+middleware-flexible-checksums@3.974.7/node_modules/@aws-sdk/middleware-flexible-checksums/dist-cjs/index.js"(exports) { - "use strict"; - var client2 = (init_client2(), __toCommonJS(client_exports)); - var protocolHttp = require_dist_cjs2(); - var utilStream = require_dist_cjs13(); - var isArrayBuffer = require_dist_cjs4(); - var crc32c = require_main3(); - var crc64Nvme = require_dist_cjs17(); - var getCrc32ChecksumAlgorithmFunction = require_getCrc32ChecksumAlgorithmFunction(); - var utilUtf8 = require_dist_cjs6(); - var utilMiddleware = require_dist_cjs18(); - var RequestChecksumCalculation = { - WHEN_SUPPORTED: "WHEN_SUPPORTED", - WHEN_REQUIRED: "WHEN_REQUIRED" - }; - var DEFAULT_REQUEST_CHECKSUM_CALCULATION = RequestChecksumCalculation.WHEN_SUPPORTED; - var ResponseChecksumValidation = { - WHEN_SUPPORTED: "WHEN_SUPPORTED", - WHEN_REQUIRED: "WHEN_REQUIRED" - }; - var DEFAULT_RESPONSE_CHECKSUM_VALIDATION = RequestChecksumCalculation.WHEN_SUPPORTED; - exports.ChecksumAlgorithm = void 0; - (function(ChecksumAlgorithm) { - ChecksumAlgorithm["MD5"] = "MD5"; - ChecksumAlgorithm["CRC32"] = "CRC32"; - ChecksumAlgorithm["CRC32C"] = "CRC32C"; - ChecksumAlgorithm["CRC64NVME"] = "CRC64NVME"; - ChecksumAlgorithm["SHA1"] = "SHA1"; - ChecksumAlgorithm["SHA256"] = "SHA256"; - })(exports.ChecksumAlgorithm || (exports.ChecksumAlgorithm = {})); - exports.ChecksumLocation = void 0; - (function(ChecksumLocation) { - ChecksumLocation["HEADER"] = "header"; - ChecksumLocation["TRAILER"] = "trailer"; - })(exports.ChecksumLocation || (exports.ChecksumLocation = {})); - var DEFAULT_CHECKSUM_ALGORITHM = exports.ChecksumAlgorithm.CRC32; - var SelectorType; - (function(SelectorType2) { - SelectorType2["ENV"] = "env"; - SelectorType2["CONFIG"] = "shared config entry"; - })(SelectorType || (SelectorType = {})); - var stringUnionSelector = (obj, key, union3, type) => { - if (!(key in obj)) - return void 0; - const value = obj[key].toUpperCase(); - if (!Object.values(union3).includes(value)) { - throw new TypeError(`Cannot load ${type} '${key}'. Expected one of ${Object.values(union3)}, got '${obj[key]}'.`); - } - return value; - }; - var ENV_REQUEST_CHECKSUM_CALCULATION = "AWS_REQUEST_CHECKSUM_CALCULATION"; - var CONFIG_REQUEST_CHECKSUM_CALCULATION = "request_checksum_calculation"; - var NODE_REQUEST_CHECKSUM_CALCULATION_CONFIG_OPTIONS = { - environmentVariableSelector: (env2) => stringUnionSelector(env2, ENV_REQUEST_CHECKSUM_CALCULATION, RequestChecksumCalculation, SelectorType.ENV), - configFileSelector: (profile) => stringUnionSelector(profile, CONFIG_REQUEST_CHECKSUM_CALCULATION, RequestChecksumCalculation, SelectorType.CONFIG), - default: DEFAULT_REQUEST_CHECKSUM_CALCULATION - }; - var ENV_RESPONSE_CHECKSUM_VALIDATION = "AWS_RESPONSE_CHECKSUM_VALIDATION"; - var CONFIG_RESPONSE_CHECKSUM_VALIDATION = "response_checksum_validation"; - var NODE_RESPONSE_CHECKSUM_VALIDATION_CONFIG_OPTIONS = { - environmentVariableSelector: (env2) => stringUnionSelector(env2, ENV_RESPONSE_CHECKSUM_VALIDATION, ResponseChecksumValidation, SelectorType.ENV), - configFileSelector: (profile) => stringUnionSelector(profile, CONFIG_RESPONSE_CHECKSUM_VALIDATION, ResponseChecksumValidation, SelectorType.CONFIG), - default: DEFAULT_RESPONSE_CHECKSUM_VALIDATION - }; - var getChecksumAlgorithmForRequest = (input, { requestChecksumRequired, requestAlgorithmMember, requestChecksumCalculation }) => { - if (!requestAlgorithmMember) { - return requestChecksumCalculation === RequestChecksumCalculation.WHEN_SUPPORTED || requestChecksumRequired ? DEFAULT_CHECKSUM_ALGORITHM : void 0; - } - if (!input[requestAlgorithmMember]) { - return void 0; - } - const checksumAlgorithm = input[requestAlgorithmMember]; - return checksumAlgorithm; - }; - var getChecksumLocationName = (algorithm2) => algorithm2 === exports.ChecksumAlgorithm.MD5 ? "content-md5" : `x-amz-checksum-${algorithm2.toLowerCase()}`; - var hasHeader = (header, headers) => { - const soughtHeader = header.toLowerCase(); - for (const headerName of Object.keys(headers)) { - if (soughtHeader === headerName.toLowerCase()) { - return true; - } - } - return false; - }; - var hasHeaderWithPrefix = (headerPrefix, headers) => { - const soughtHeaderPrefix = headerPrefix.toLowerCase(); - for (const headerName of Object.keys(headers)) { - if (headerName.toLowerCase().startsWith(soughtHeaderPrefix)) { - return true; - } - } - return false; - }; - var isStreaming = (body) => body !== void 0 && typeof body !== "string" && !ArrayBuffer.isView(body) && !isArrayBuffer.isArrayBuffer(body); - var CLIENT_SUPPORTED_ALGORITHMS = [ - exports.ChecksumAlgorithm.CRC32, - exports.ChecksumAlgorithm.CRC32C, - exports.ChecksumAlgorithm.CRC64NVME, - exports.ChecksumAlgorithm.SHA1, - exports.ChecksumAlgorithm.SHA256 - ]; - var PRIORITY_ORDER_ALGORITHMS = [ - exports.ChecksumAlgorithm.SHA256, - exports.ChecksumAlgorithm.SHA1, - exports.ChecksumAlgorithm.CRC32, - exports.ChecksumAlgorithm.CRC32C, - exports.ChecksumAlgorithm.CRC64NVME - ]; - var selectChecksumAlgorithmFunction = (checksumAlgorithm, config3) => { - const { checksumAlgorithms = {} } = config3; - switch (checksumAlgorithm) { - case exports.ChecksumAlgorithm.MD5: - return checksumAlgorithms?.MD5 ?? config3.md5; - case exports.ChecksumAlgorithm.CRC32: - return checksumAlgorithms?.CRC32 ?? getCrc32ChecksumAlgorithmFunction.getCrc32ChecksumAlgorithmFunction(); - case exports.ChecksumAlgorithm.CRC32C: - return checksumAlgorithms?.CRC32C ?? crc32c.AwsCrc32c; - case exports.ChecksumAlgorithm.CRC64NVME: - if (typeof crc64Nvme.crc64NvmeCrtContainer.CrtCrc64Nvme !== "function") { - return checksumAlgorithms?.CRC64NVME ?? crc64Nvme.Crc64Nvme; - } - return checksumAlgorithms?.CRC64NVME ?? crc64Nvme.crc64NvmeCrtContainer.CrtCrc64Nvme; - case exports.ChecksumAlgorithm.SHA1: - return checksumAlgorithms?.SHA1 ?? config3.sha1; - case exports.ChecksumAlgorithm.SHA256: - return checksumAlgorithms?.SHA256 ?? config3.sha256; - default: - if (checksumAlgorithms?.[checksumAlgorithm]) { - return checksumAlgorithms[checksumAlgorithm]; - } - throw new Error(`The checksum algorithm "${checksumAlgorithm}" is not supported by the client. Select one of ${CLIENT_SUPPORTED_ALGORITHMS}, or provide an implementation to the client constructor checksums field.`); - } - }; - var stringHasher = (checksumAlgorithmFn, body) => { - const hash2 = new checksumAlgorithmFn(); - hash2.update(utilUtf8.toUint8Array(body || "")); - return hash2.digest(); - }; - var flexibleChecksumsMiddlewareOptions = { - name: "flexibleChecksumsMiddleware", - step: "build", - tags: ["BODY_CHECKSUM"], - override: true - }; - var flexibleChecksumsMiddleware = (config3, middlewareConfig) => (next, context) => async (args) => { - if (!protocolHttp.HttpRequest.isInstance(args.request)) { - return next(args); - } - if (hasHeaderWithPrefix("x-amz-checksum-", args.request.headers)) { - return next(args); - } - const { request, input } = args; - const { body: requestBody, headers } = request; - const { base64Encoder, streamHasher } = config3; - const { requestChecksumRequired, requestAlgorithmMember } = middlewareConfig; - const requestChecksumCalculation = await config3.requestChecksumCalculation(); - const requestAlgorithmMemberName = requestAlgorithmMember?.name; - const requestAlgorithmMemberHttpHeader = requestAlgorithmMember?.httpHeader; - if (requestAlgorithmMemberName && !input[requestAlgorithmMemberName]) { - if (requestChecksumCalculation === RequestChecksumCalculation.WHEN_SUPPORTED || requestChecksumRequired) { - input[requestAlgorithmMemberName] = DEFAULT_CHECKSUM_ALGORITHM; - if (requestAlgorithmMemberHttpHeader) { - headers[requestAlgorithmMemberHttpHeader] = DEFAULT_CHECKSUM_ALGORITHM; - } - } - } - const checksumAlgorithm = getChecksumAlgorithmForRequest(input, { - requestChecksumRequired, - requestAlgorithmMember: requestAlgorithmMember?.name, - requestChecksumCalculation - }); - let updatedBody = requestBody; - let updatedHeaders = headers; - if (checksumAlgorithm) { - switch (checksumAlgorithm) { - case exports.ChecksumAlgorithm.CRC32: - client2.setFeature(context, "FLEXIBLE_CHECKSUMS_REQ_CRC32", "U"); - break; - case exports.ChecksumAlgorithm.CRC32C: - client2.setFeature(context, "FLEXIBLE_CHECKSUMS_REQ_CRC32C", "V"); - break; - case exports.ChecksumAlgorithm.CRC64NVME: - client2.setFeature(context, "FLEXIBLE_CHECKSUMS_REQ_CRC64", "W"); - break; - case exports.ChecksumAlgorithm.SHA1: - client2.setFeature(context, "FLEXIBLE_CHECKSUMS_REQ_SHA1", "X"); - break; - case exports.ChecksumAlgorithm.SHA256: - client2.setFeature(context, "FLEXIBLE_CHECKSUMS_REQ_SHA256", "Y"); - break; - } - const checksumLocationName = getChecksumLocationName(checksumAlgorithm); - const checksumAlgorithmFn = selectChecksumAlgorithmFunction(checksumAlgorithm, config3); - if (isStreaming(requestBody)) { - const { getAwsChunkedEncodingStream, bodyLengthChecker } = config3; - updatedBody = getAwsChunkedEncodingStream(typeof config3.requestStreamBufferSize === "number" && config3.requestStreamBufferSize >= 8 * 1024 ? utilStream.createBufferedReadable(requestBody, config3.requestStreamBufferSize, context.logger) : requestBody, { - base64Encoder, - bodyLengthChecker, - checksumLocationName, - checksumAlgorithmFn, - streamHasher - }); - updatedHeaders = { - ...headers, - "content-encoding": headers["content-encoding"] ? `${headers["content-encoding"]},aws-chunked` : "aws-chunked", - "transfer-encoding": "chunked", - "x-amz-decoded-content-length": headers["content-length"], - "x-amz-content-sha256": "STREAMING-UNSIGNED-PAYLOAD-TRAILER", - "x-amz-trailer": checksumLocationName - }; - delete updatedHeaders["content-length"]; - } else if (!hasHeader(checksumLocationName, headers)) { - const rawChecksum = await stringHasher(checksumAlgorithmFn, requestBody); - updatedHeaders = { - ...headers, - [checksumLocationName]: base64Encoder(rawChecksum) - }; - } - } - try { - const result = await next({ - ...args, - request: { - ...request, - headers: updatedHeaders, - body: updatedBody - } - }); - return result; - } catch (e5) { - if (e5 instanceof Error && e5.name === "InvalidChunkSizeError") { - try { - if (!e5.message.endsWith(".")) { - e5.message += "."; - } - e5.message += " Set [requestStreamBufferSize=number e.g. 65_536] in client constructor to instruct AWS SDK to buffer your input stream."; - } catch (ignored) { - } - } - throw e5; - } - }; - var flexibleChecksumsInputMiddlewareOptions = { - name: "flexibleChecksumsInputMiddleware", - toMiddleware: "serializerMiddleware", - relation: "before", - tags: ["BODY_CHECKSUM"], - override: true - }; - var flexibleChecksumsInputMiddleware = (config3, middlewareConfig) => (next, context) => async (args) => { - const input = args.input; - const { requestValidationModeMember } = middlewareConfig; - const requestChecksumCalculation = await config3.requestChecksumCalculation(); - const responseChecksumValidation = await config3.responseChecksumValidation(); - switch (requestChecksumCalculation) { - case RequestChecksumCalculation.WHEN_REQUIRED: - client2.setFeature(context, "FLEXIBLE_CHECKSUMS_REQ_WHEN_REQUIRED", "a"); - break; - case RequestChecksumCalculation.WHEN_SUPPORTED: - client2.setFeature(context, "FLEXIBLE_CHECKSUMS_REQ_WHEN_SUPPORTED", "Z"); - break; - } - switch (responseChecksumValidation) { - case ResponseChecksumValidation.WHEN_REQUIRED: - client2.setFeature(context, "FLEXIBLE_CHECKSUMS_RES_WHEN_REQUIRED", "c"); - break; - case ResponseChecksumValidation.WHEN_SUPPORTED: - client2.setFeature(context, "FLEXIBLE_CHECKSUMS_RES_WHEN_SUPPORTED", "b"); - break; - } - if (requestValidationModeMember && !input[requestValidationModeMember]) { - if (responseChecksumValidation === ResponseChecksumValidation.WHEN_SUPPORTED) { - input[requestValidationModeMember] = "ENABLED"; - } - } - return next(args); - }; - var getChecksumAlgorithmListForResponse = (responseAlgorithms = []) => { - const validChecksumAlgorithms = []; - let i5 = PRIORITY_ORDER_ALGORITHMS.length; - for (const algorithm2 of responseAlgorithms) { - const priority = PRIORITY_ORDER_ALGORITHMS.indexOf(algorithm2); - if (priority !== -1) { - validChecksumAlgorithms[priority] = algorithm2; - } else { - validChecksumAlgorithms[i5++] = algorithm2; - } - } - return validChecksumAlgorithms.filter(Boolean); - }; - var isChecksumWithPartNumber = (checksum) => { - const lastHyphenIndex = checksum.lastIndexOf("-"); - if (lastHyphenIndex !== -1) { - const numberPart = checksum.slice(lastHyphenIndex + 1); - if (!numberPart.startsWith("0")) { - const number4 = parseInt(numberPart, 10); - if (!isNaN(number4) && number4 >= 1 && number4 <= 1e4) { - return true; - } - } - } - return false; - }; - var getChecksum = async (body, { checksumAlgorithmFn, base64Encoder }) => base64Encoder(await stringHasher(checksumAlgorithmFn, body)); - var validateChecksumFromResponse = async (response, { config: config3, responseAlgorithms, logger: logger4 }) => { - const checksumAlgorithms = getChecksumAlgorithmListForResponse(responseAlgorithms); - const { body: responseBody, headers: responseHeaders } = response; - for (const algorithm2 of checksumAlgorithms) { - const responseHeader = getChecksumLocationName(algorithm2); - const checksumFromResponse = responseHeaders[responseHeader]; - if (checksumFromResponse) { - let checksumAlgorithmFn; - try { - checksumAlgorithmFn = selectChecksumAlgorithmFunction(algorithm2, config3); - } catch (error50) { - if (algorithm2 === exports.ChecksumAlgorithm.CRC64NVME) { - logger4?.warn(`Skipping ${exports.ChecksumAlgorithm.CRC64NVME} checksum validation: ${error50.message}`); - continue; - } - throw error50; - } - const { base64Encoder } = config3; - if (isStreaming(responseBody)) { - response.body = utilStream.createChecksumStream({ - expectedChecksum: checksumFromResponse, - checksumSourceLocation: responseHeader, - checksum: new checksumAlgorithmFn(), - source: responseBody, - base64Encoder - }); - return; - } - const checksum = await getChecksum(responseBody, { checksumAlgorithmFn, base64Encoder }); - if (checksum === checksumFromResponse) { - break; - } - throw new Error(`Checksum mismatch: expected "${checksum}" but received "${checksumFromResponse}" in response header "${responseHeader}".`); - } - } - }; - var flexibleChecksumsResponseMiddlewareOptions = { - name: "flexibleChecksumsResponseMiddleware", - toMiddleware: "deserializerMiddleware", - relation: "after", - tags: ["BODY_CHECKSUM"], - override: true - }; - var flexibleChecksumsResponseMiddleware = (config3, middlewareConfig) => (next, context) => async (args) => { - if (!protocolHttp.HttpRequest.isInstance(args.request)) { - return next(args); - } - const input = args.input; - const result = await next(args); - const response = result.response; - const { requestValidationModeMember, responseAlgorithms } = middlewareConfig; - if (requestValidationModeMember && input[requestValidationModeMember] === "ENABLED") { - const { clientName, commandName } = context; - const customChecksumAlgorithms = Object.keys(config3.checksumAlgorithms ?? {}).filter((algorithm2) => { - const responseHeader = getChecksumLocationName(algorithm2); - return response.headers[responseHeader] !== void 0; - }); - const algoList = getChecksumAlgorithmListForResponse([ - ...responseAlgorithms ?? [], - ...customChecksumAlgorithms - ]); - const isS3WholeObjectMultipartGetResponseChecksum = clientName === "S3Client" && commandName === "GetObjectCommand" && algoList.every((algorithm2) => { - const responseHeader = getChecksumLocationName(algorithm2); - const checksumFromResponse = response.headers[responseHeader]; - return !checksumFromResponse || isChecksumWithPartNumber(checksumFromResponse); - }); - if (isS3WholeObjectMultipartGetResponseChecksum) { - return result; - } - await validateChecksumFromResponse(response, { - config: config3, - responseAlgorithms: algoList, - logger: context.logger - }); - } - return result; - }; - var getFlexibleChecksumsPlugin = (config3, middlewareConfig) => ({ - applyToStack: (clientStack) => { - clientStack.add(flexibleChecksumsMiddleware(config3, middlewareConfig), flexibleChecksumsMiddlewareOptions); - clientStack.addRelativeTo(flexibleChecksumsInputMiddleware(config3, middlewareConfig), flexibleChecksumsInputMiddlewareOptions); - clientStack.addRelativeTo(flexibleChecksumsResponseMiddleware(config3, middlewareConfig), flexibleChecksumsResponseMiddlewareOptions); - } - }); - var resolveFlexibleChecksumsConfig = (input) => { - const { requestChecksumCalculation, responseChecksumValidation, requestStreamBufferSize } = input; - return Object.assign(input, { - requestChecksumCalculation: utilMiddleware.normalizeProvider(requestChecksumCalculation ?? DEFAULT_REQUEST_CHECKSUM_CALCULATION), - responseChecksumValidation: utilMiddleware.normalizeProvider(responseChecksumValidation ?? DEFAULT_RESPONSE_CHECKSUM_VALIDATION), - requestStreamBufferSize: Number(requestStreamBufferSize ?? 0), - checksumAlgorithms: input.checksumAlgorithms ?? {} - }); - }; - exports.CONFIG_REQUEST_CHECKSUM_CALCULATION = CONFIG_REQUEST_CHECKSUM_CALCULATION; - exports.CONFIG_RESPONSE_CHECKSUM_VALIDATION = CONFIG_RESPONSE_CHECKSUM_VALIDATION; - exports.DEFAULT_CHECKSUM_ALGORITHM = DEFAULT_CHECKSUM_ALGORITHM; - exports.DEFAULT_REQUEST_CHECKSUM_CALCULATION = DEFAULT_REQUEST_CHECKSUM_CALCULATION; - exports.DEFAULT_RESPONSE_CHECKSUM_VALIDATION = DEFAULT_RESPONSE_CHECKSUM_VALIDATION; - exports.ENV_REQUEST_CHECKSUM_CALCULATION = ENV_REQUEST_CHECKSUM_CALCULATION; - exports.ENV_RESPONSE_CHECKSUM_VALIDATION = ENV_RESPONSE_CHECKSUM_VALIDATION; - exports.NODE_REQUEST_CHECKSUM_CALCULATION_CONFIG_OPTIONS = NODE_REQUEST_CHECKSUM_CALCULATION_CONFIG_OPTIONS; - exports.NODE_RESPONSE_CHECKSUM_VALIDATION_CONFIG_OPTIONS = NODE_RESPONSE_CHECKSUM_VALIDATION_CONFIG_OPTIONS; - exports.RequestChecksumCalculation = RequestChecksumCalculation; - exports.ResponseChecksumValidation = ResponseChecksumValidation; - exports.flexibleChecksumsMiddleware = flexibleChecksumsMiddleware; - exports.flexibleChecksumsMiddlewareOptions = flexibleChecksumsMiddlewareOptions; - exports.getFlexibleChecksumsPlugin = getFlexibleChecksumsPlugin; - exports.resolveFlexibleChecksumsConfig = resolveFlexibleChecksumsConfig; - } -}); - -// node_modules/.pnpm/@aws-sdk+middleware-host-header@3.972.9/node_modules/@aws-sdk/middleware-host-header/dist-cjs/index.js -var require_dist_cjs20 = __commonJS({ - "node_modules/.pnpm/@aws-sdk+middleware-host-header@3.972.9/node_modules/@aws-sdk/middleware-host-header/dist-cjs/index.js"(exports) { - "use strict"; - var protocolHttp = require_dist_cjs2(); - function resolveHostHeaderConfig5(input) { - return input; - } - var hostHeaderMiddleware = (options) => (next) => async (args) => { - if (!protocolHttp.HttpRequest.isInstance(args.request)) - return next(args); - const { request } = args; - const { handlerProtocol = "" } = options.requestHandler.metadata || {}; - if (handlerProtocol.indexOf("h2") >= 0 && !request.headers[":authority"]) { - delete request.headers["host"]; - request.headers[":authority"] = request.hostname + (request.port ? ":" + request.port : ""); - } else if (!request.headers["host"]) { - let host = request.hostname; - if (request.port != null) - host += `:${request.port}`; - request.headers["host"] = host; - } - return next(args); - }; - var hostHeaderMiddlewareOptions = { - name: "hostHeaderMiddleware", - step: "build", - priority: "low", - tags: ["HOST"], - override: true - }; - var getHostHeaderPlugin5 = (options) => ({ - applyToStack: (clientStack) => { - clientStack.add(hostHeaderMiddleware(options), hostHeaderMiddlewareOptions); - } - }); - exports.getHostHeaderPlugin = getHostHeaderPlugin5; - exports.hostHeaderMiddleware = hostHeaderMiddleware; - exports.hostHeaderMiddlewareOptions = hostHeaderMiddlewareOptions; - exports.resolveHostHeaderConfig = resolveHostHeaderConfig5; - } -}); - -// node_modules/.pnpm/@aws-sdk+middleware-logger@3.972.9/node_modules/@aws-sdk/middleware-logger/dist-cjs/index.js -var require_dist_cjs21 = __commonJS({ - "node_modules/.pnpm/@aws-sdk+middleware-logger@3.972.9/node_modules/@aws-sdk/middleware-logger/dist-cjs/index.js"(exports) { - "use strict"; - var loggerMiddleware = () => (next, context) => async (args) => { - try { - const response = await next(args); - const { clientName, commandName, logger: logger4, dynamoDbDocumentClientOptions = {} } = context; - const { overrideInputFilterSensitiveLog, overrideOutputFilterSensitiveLog } = dynamoDbDocumentClientOptions; - const inputFilterSensitiveLog = overrideInputFilterSensitiveLog ?? context.inputFilterSensitiveLog; - const outputFilterSensitiveLog = overrideOutputFilterSensitiveLog ?? context.outputFilterSensitiveLog; - const { $metadata, ...outputWithoutMetadata } = response.output; - logger4?.info?.({ - clientName, - commandName, - input: inputFilterSensitiveLog(args.input), - output: outputFilterSensitiveLog(outputWithoutMetadata), - metadata: $metadata - }); - return response; - } catch (error50) { - const { clientName, commandName, logger: logger4, dynamoDbDocumentClientOptions = {} } = context; - const { overrideInputFilterSensitiveLog } = dynamoDbDocumentClientOptions; - const inputFilterSensitiveLog = overrideInputFilterSensitiveLog ?? context.inputFilterSensitiveLog; - logger4?.error?.({ - clientName, - commandName, - input: inputFilterSensitiveLog(args.input), - error: error50, - metadata: error50.$metadata - }); - throw error50; - } - }; - var loggerMiddlewareOptions = { - name: "loggerMiddleware", - tags: ["LOGGER"], - step: "initialize", - override: true - }; - var getLoggerPlugin5 = (options) => ({ - applyToStack: (clientStack) => { - clientStack.add(loggerMiddleware(), loggerMiddlewareOptions); - } - }); - exports.getLoggerPlugin = getLoggerPlugin5; - exports.loggerMiddleware = loggerMiddleware; - exports.loggerMiddlewareOptions = loggerMiddlewareOptions; - } -}); - -// node_modules/.pnpm/@aws+lambda-invoke-store@0.2.4/node_modules/@aws/lambda-invoke-store/dist-es/invoke-store.js -var invoke_store_exports = {}; -__export(invoke_store_exports, { - InvokeStore: () => InvokeStore, - InvokeStoreBase: () => InvokeStoreBase -}); -var PROTECTED_KEYS, NO_GLOBAL_AWS_LAMBDA, InvokeStoreBase, InvokeStoreSingle, InvokeStoreMulti, InvokeStore; -var init_invoke_store = __esm({ - "node_modules/.pnpm/@aws+lambda-invoke-store@0.2.4/node_modules/@aws/lambda-invoke-store/dist-es/invoke-store.js"() { - PROTECTED_KEYS = { - REQUEST_ID: /* @__PURE__ */ Symbol.for("_AWS_LAMBDA_REQUEST_ID"), - X_RAY_TRACE_ID: /* @__PURE__ */ Symbol.for("_AWS_LAMBDA_X_RAY_TRACE_ID"), - TENANT_ID: /* @__PURE__ */ Symbol.for("_AWS_LAMBDA_TENANT_ID") - }; - NO_GLOBAL_AWS_LAMBDA = ["true", "1"].includes(process.env?.AWS_LAMBDA_NODEJS_NO_GLOBAL_AWSLAMBDA ?? ""); - if (!NO_GLOBAL_AWS_LAMBDA) { - globalThis.awslambda = globalThis.awslambda || {}; - } - InvokeStoreBase = class { - static PROTECTED_KEYS = PROTECTED_KEYS; - isProtectedKey(key) { - return Object.values(PROTECTED_KEYS).includes(key); - } - getRequestId() { - return this.get(PROTECTED_KEYS.REQUEST_ID) ?? "-"; - } - getXRayTraceId() { - return this.get(PROTECTED_KEYS.X_RAY_TRACE_ID); - } - getTenantId() { - return this.get(PROTECTED_KEYS.TENANT_ID); - } - }; - InvokeStoreSingle = class extends InvokeStoreBase { - currentContext; - getContext() { - return this.currentContext; - } - hasContext() { - return this.currentContext !== void 0; - } - get(key) { - return this.currentContext?.[key]; - } - set(key, value) { - if (this.isProtectedKey(key)) { - throw new Error(`Cannot modify protected Lambda context field: ${String(key)}`); - } - this.currentContext = this.currentContext || {}; - this.currentContext[key] = value; - } - run(context, fn) { - this.currentContext = context; - return fn(); - } - }; - InvokeStoreMulti = class _InvokeStoreMulti extends InvokeStoreBase { - als; - static async create() { - const instance = new _InvokeStoreMulti(); - const asyncHooks = await import("node:async_hooks"); - instance.als = new asyncHooks.AsyncLocalStorage(); - return instance; - } - getContext() { - return this.als.getStore(); - } - hasContext() { - return this.als.getStore() !== void 0; - } - get(key) { - return this.als.getStore()?.[key]; - } - set(key, value) { - if (this.isProtectedKey(key)) { - throw new Error(`Cannot modify protected Lambda context field: ${String(key)}`); - } - const store = this.als.getStore(); - if (!store) { - throw new Error("No context available"); - } - store[key] = value; - } - run(context, fn) { - return this.als.run(context, fn); - } - }; - (function(InvokeStore2) { - let instance = null; - async function getInstanceAsync(forceInvokeStoreMulti) { - if (!instance) { - instance = (async () => { - const isMulti = forceInvokeStoreMulti === true || "AWS_LAMBDA_MAX_CONCURRENCY" in process.env; - const newInstance = isMulti ? await InvokeStoreMulti.create() : new InvokeStoreSingle(); - if (!NO_GLOBAL_AWS_LAMBDA && globalThis.awslambda?.InvokeStore) { - return globalThis.awslambda.InvokeStore; - } else if (!NO_GLOBAL_AWS_LAMBDA && globalThis.awslambda) { - globalThis.awslambda.InvokeStore = newInstance; - return newInstance; - } else { - return newInstance; - } - })(); - } - return instance; - } - InvokeStore2.getInstanceAsync = getInstanceAsync; - InvokeStore2._testing = process.env.AWS_LAMBDA_BENCHMARK_MODE === "1" ? { - reset: () => { - instance = null; - if (globalThis.awslambda?.InvokeStore) { - delete globalThis.awslambda.InvokeStore; - } - globalThis.awslambda = { InvokeStore: void 0 }; - } - } : void 0; - })(InvokeStore || (InvokeStore = {})); - } -}); - -// node_modules/.pnpm/@aws-sdk+middleware-recursion-detection@3.972.10/node_modules/@aws-sdk/middleware-recursion-detection/dist-cjs/recursionDetectionMiddleware.js -var require_recursionDetectionMiddleware = __commonJS({ - "node_modules/.pnpm/@aws-sdk+middleware-recursion-detection@3.972.10/node_modules/@aws-sdk/middleware-recursion-detection/dist-cjs/recursionDetectionMiddleware.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.recursionDetectionMiddleware = void 0; - var lambda_invoke_store_1 = (init_invoke_store(), __toCommonJS(invoke_store_exports)); - var protocol_http_1 = require_dist_cjs2(); - var TRACE_ID_HEADER_NAME = "X-Amzn-Trace-Id"; - var ENV_LAMBDA_FUNCTION_NAME = "AWS_LAMBDA_FUNCTION_NAME"; - var ENV_TRACE_ID = "_X_AMZN_TRACE_ID"; - var recursionDetectionMiddleware = () => (next) => async (args) => { - const { request } = args; - if (!protocol_http_1.HttpRequest.isInstance(request)) { - return next(args); - } - const traceIdHeader = Object.keys(request.headers ?? {}).find((h5) => h5.toLowerCase() === TRACE_ID_HEADER_NAME.toLowerCase()) ?? TRACE_ID_HEADER_NAME; - if (request.headers.hasOwnProperty(traceIdHeader)) { - return next(args); - } - const functionName = process.env[ENV_LAMBDA_FUNCTION_NAME]; - const traceIdFromEnv = process.env[ENV_TRACE_ID]; - const invokeStore = await lambda_invoke_store_1.InvokeStore.getInstanceAsync(); - const traceIdFromInvokeStore = invokeStore?.getXRayTraceId(); - const traceId = traceIdFromInvokeStore ?? traceIdFromEnv; - const nonEmptyString = (str) => typeof str === "string" && str.length > 0; - if (nonEmptyString(functionName) && nonEmptyString(traceId)) { - request.headers[TRACE_ID_HEADER_NAME] = traceId; - } - return next({ - ...args, - request - }); - }; - exports.recursionDetectionMiddleware = recursionDetectionMiddleware; - } -}); - -// node_modules/.pnpm/@aws-sdk+middleware-recursion-detection@3.972.10/node_modules/@aws-sdk/middleware-recursion-detection/dist-cjs/index.js -var require_dist_cjs22 = __commonJS({ - "node_modules/.pnpm/@aws-sdk+middleware-recursion-detection@3.972.10/node_modules/@aws-sdk/middleware-recursion-detection/dist-cjs/index.js"(exports) { - "use strict"; - var recursionDetectionMiddleware = require_recursionDetectionMiddleware(); - var recursionDetectionMiddlewareOptions = { - step: "build", - tags: ["RECURSION_DETECTION"], - name: "recursionDetectionMiddleware", - override: true, - priority: "low" - }; - var getRecursionDetectionPlugin5 = (options) => ({ - applyToStack: (clientStack) => { - clientStack.add(recursionDetectionMiddleware.recursionDetectionMiddleware(), recursionDetectionMiddlewareOptions); - } - }); - exports.getRecursionDetectionPlugin = getRecursionDetectionPlugin5; - Object.prototype.hasOwnProperty.call(recursionDetectionMiddleware, "__proto__") && !Object.prototype.hasOwnProperty.call(exports, "__proto__") && Object.defineProperty(exports, "__proto__", { - enumerable: true, - value: recursionDetectionMiddleware["__proto__"] - }); - Object.keys(recursionDetectionMiddleware).forEach(function(k5) { - if (k5 !== "default" && !Object.prototype.hasOwnProperty.call(exports, k5)) exports[k5] = recursionDetectionMiddleware[k5]; - }); - } -}); - -// node_modules/.pnpm/@smithy+middleware-stack@4.2.13/node_modules/@smithy/middleware-stack/dist-cjs/index.js -var require_dist_cjs23 = __commonJS({ - "node_modules/.pnpm/@smithy+middleware-stack@4.2.13/node_modules/@smithy/middleware-stack/dist-cjs/index.js"(exports) { - "use strict"; - var getAllAliases = (name, aliases) => { - const _aliases = []; - if (name) { - _aliases.push(name); - } - if (aliases) { - for (const alias of aliases) { - _aliases.push(alias); - } - } - return _aliases; - }; - var getMiddlewareNameWithAliases = (name, aliases) => { - return `${name || "anonymous"}${aliases && aliases.length > 0 ? ` (a.k.a. ${aliases.join(",")})` : ""}`; - }; - var constructStack = () => { - let absoluteEntries = []; - let relativeEntries = []; - let identifyOnResolve = false; - const entriesNameSet = /* @__PURE__ */ new Set(); - const sort = (entries2) => entries2.sort((a5, b6) => stepWeights[b6.step] - stepWeights[a5.step] || priorityWeights[b6.priority || "normal"] - priorityWeights[a5.priority || "normal"]); - const removeByName = (toRemove) => { - let isRemoved = false; - const filterCb = (entry) => { - const aliases = getAllAliases(entry.name, entry.aliases); - if (aliases.includes(toRemove)) { - isRemoved = true; - for (const alias of aliases) { - entriesNameSet.delete(alias); - } - return false; - } - return true; - }; - absoluteEntries = absoluteEntries.filter(filterCb); - relativeEntries = relativeEntries.filter(filterCb); - return isRemoved; - }; - const removeByReference = (toRemove) => { - let isRemoved = false; - const filterCb = (entry) => { - if (entry.middleware === toRemove) { - isRemoved = true; - for (const alias of getAllAliases(entry.name, entry.aliases)) { - entriesNameSet.delete(alias); - } - return false; - } - return true; - }; - absoluteEntries = absoluteEntries.filter(filterCb); - relativeEntries = relativeEntries.filter(filterCb); - return isRemoved; - }; - const cloneTo = (toStack) => { - absoluteEntries.forEach((entry) => { - toStack.add(entry.middleware, { ...entry }); - }); - relativeEntries.forEach((entry) => { - toStack.addRelativeTo(entry.middleware, { ...entry }); - }); - toStack.identifyOnResolve?.(stack.identifyOnResolve()); - return toStack; - }; - const expandRelativeMiddlewareList = (from) => { - const expandedMiddlewareList = []; - from.before.forEach((entry) => { - if (entry.before.length === 0 && entry.after.length === 0) { - expandedMiddlewareList.push(entry); - } else { - expandedMiddlewareList.push(...expandRelativeMiddlewareList(entry)); - } - }); - expandedMiddlewareList.push(from); - from.after.reverse().forEach((entry) => { - if (entry.before.length === 0 && entry.after.length === 0) { - expandedMiddlewareList.push(entry); - } else { - expandedMiddlewareList.push(...expandRelativeMiddlewareList(entry)); - } - }); - return expandedMiddlewareList; - }; - const getMiddlewareList = (debug = false) => { - const normalizedAbsoluteEntries = []; - const normalizedRelativeEntries = []; - const normalizedEntriesNameMap = {}; - absoluteEntries.forEach((entry) => { - const normalizedEntry = { - ...entry, - before: [], - after: [] - }; - for (const alias of getAllAliases(normalizedEntry.name, normalizedEntry.aliases)) { - normalizedEntriesNameMap[alias] = normalizedEntry; - } - normalizedAbsoluteEntries.push(normalizedEntry); - }); - relativeEntries.forEach((entry) => { - const normalizedEntry = { - ...entry, - before: [], - after: [] - }; - for (const alias of getAllAliases(normalizedEntry.name, normalizedEntry.aliases)) { - normalizedEntriesNameMap[alias] = normalizedEntry; - } - normalizedRelativeEntries.push(normalizedEntry); - }); - normalizedRelativeEntries.forEach((entry) => { - if (entry.toMiddleware) { - const toMiddleware = normalizedEntriesNameMap[entry.toMiddleware]; - if (toMiddleware === void 0) { - if (debug) { - return; - } - throw new Error(`${entry.toMiddleware} is not found when adding ${getMiddlewareNameWithAliases(entry.name, entry.aliases)} middleware ${entry.relation} ${entry.toMiddleware}`); - } - if (entry.relation === "after") { - toMiddleware.after.push(entry); - } - if (entry.relation === "before") { - toMiddleware.before.push(entry); - } - } - }); - const mainChain = sort(normalizedAbsoluteEntries).map(expandRelativeMiddlewareList).reduce((wholeList, expandedMiddlewareList) => { - wholeList.push(...expandedMiddlewareList); - return wholeList; - }, []); - return mainChain; - }; - const stack = { - add: (middleware, options = {}) => { - const { name, override, aliases: _aliases } = options; - const entry = { - step: "initialize", - priority: "normal", - middleware, - ...options - }; - const aliases = getAllAliases(name, _aliases); - if (aliases.length > 0) { - if (aliases.some((alias) => entriesNameSet.has(alias))) { - if (!override) - throw new Error(`Duplicate middleware name '${getMiddlewareNameWithAliases(name, _aliases)}'`); - for (const alias of aliases) { - const toOverrideIndex = absoluteEntries.findIndex((entry2) => entry2.name === alias || entry2.aliases?.some((a5) => a5 === alias)); - if (toOverrideIndex === -1) { - continue; - } - const toOverride = absoluteEntries[toOverrideIndex]; - if (toOverride.step !== entry.step || entry.priority !== toOverride.priority) { - throw new Error(`"${getMiddlewareNameWithAliases(toOverride.name, toOverride.aliases)}" middleware with ${toOverride.priority} priority in ${toOverride.step} step cannot be overridden by "${getMiddlewareNameWithAliases(name, _aliases)}" middleware with ${entry.priority} priority in ${entry.step} step.`); - } - absoluteEntries.splice(toOverrideIndex, 1); - } - } - for (const alias of aliases) { - entriesNameSet.add(alias); - } - } - absoluteEntries.push(entry); - }, - addRelativeTo: (middleware, options) => { - const { name, override, aliases: _aliases } = options; - const entry = { - middleware, - ...options - }; - const aliases = getAllAliases(name, _aliases); - if (aliases.length > 0) { - if (aliases.some((alias) => entriesNameSet.has(alias))) { - if (!override) - throw new Error(`Duplicate middleware name '${getMiddlewareNameWithAliases(name, _aliases)}'`); - for (const alias of aliases) { - const toOverrideIndex = relativeEntries.findIndex((entry2) => entry2.name === alias || entry2.aliases?.some((a5) => a5 === alias)); - if (toOverrideIndex === -1) { - continue; - } - const toOverride = relativeEntries[toOverrideIndex]; - if (toOverride.toMiddleware !== entry.toMiddleware || toOverride.relation !== entry.relation) { - throw new Error(`"${getMiddlewareNameWithAliases(toOverride.name, toOverride.aliases)}" middleware ${toOverride.relation} "${toOverride.toMiddleware}" middleware cannot be overridden by "${getMiddlewareNameWithAliases(name, _aliases)}" middleware ${entry.relation} "${entry.toMiddleware}" middleware.`); - } - relativeEntries.splice(toOverrideIndex, 1); - } - } - for (const alias of aliases) { - entriesNameSet.add(alias); - } - } - relativeEntries.push(entry); - }, - clone: () => cloneTo(constructStack()), - use: (plugin) => { - plugin.applyToStack(stack); - }, - remove: (toRemove) => { - if (typeof toRemove === "string") - return removeByName(toRemove); - else - return removeByReference(toRemove); - }, - removeByTag: (toRemove) => { - let isRemoved = false; - const filterCb = (entry) => { - const { tags, name, aliases: _aliases } = entry; - if (tags && tags.includes(toRemove)) { - const aliases = getAllAliases(name, _aliases); - for (const alias of aliases) { - entriesNameSet.delete(alias); - } - isRemoved = true; - return false; - } - return true; - }; - absoluteEntries = absoluteEntries.filter(filterCb); - relativeEntries = relativeEntries.filter(filterCb); - return isRemoved; - }, - concat: (from) => { - const cloned = cloneTo(constructStack()); - cloned.use(from); - cloned.identifyOnResolve(identifyOnResolve || cloned.identifyOnResolve() || (from.identifyOnResolve?.() ?? false)); - return cloned; - }, - applyToStack: cloneTo, - identify: () => { - return getMiddlewareList(true).map((mw) => { - const step = mw.step ?? mw.relation + " " + mw.toMiddleware; - return getMiddlewareNameWithAliases(mw.name, mw.aliases) + " - " + step; - }); - }, - identifyOnResolve(toggle) { - if (typeof toggle === "boolean") - identifyOnResolve = toggle; - return identifyOnResolve; - }, - resolve: (handler, context) => { - for (const middleware of getMiddlewareList().map((entry) => entry.middleware).reverse()) { - handler = middleware(handler, context); - } - if (identifyOnResolve) { - console.log(stack.identify()); - } - return handler; - } - }; - return stack; - }; - var stepWeights = { - initialize: 5, - serialize: 4, - build: 3, - finalizeRequest: 2, - deserialize: 1 - }; - var priorityWeights = { - high: 3, - normal: 2, - low: 1 - }; - exports.constructStack = constructStack; - } -}); - -// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/schema/deref.js -var deref; -var init_deref = __esm({ - "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/schema/deref.js"() { - deref = (schemaRef) => { - if (typeof schemaRef === "function") { - return schemaRef(); - } - return schemaRef; - }; - } -}); - -// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/schema/schemas/operation.js -var operation; -var init_operation = __esm({ - "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/schema/schemas/operation.js"() { - operation = (namespace, name, traits, input, output) => ({ - name, - namespace, - traits, - input, - output - }); - } -}); - -// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/schema/middleware/schemaDeserializationMiddleware.js -var import_protocol_http, import_util_middleware, schemaDeserializationMiddleware, findHeader; -var init_schemaDeserializationMiddleware = __esm({ - "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/schema/middleware/schemaDeserializationMiddleware.js"() { - import_protocol_http = __toESM(require_dist_cjs2()); - import_util_middleware = __toESM(require_dist_cjs18()); - init_operation(); - schemaDeserializationMiddleware = (config3) => (next, context) => async (args) => { - const { response } = await next(args); - const { operationSchema } = (0, import_util_middleware.getSmithyContext)(context); - const [, ns, n5, t5, i5, o5] = operationSchema ?? []; - try { - const parsed = await config3.protocol.deserializeResponse(operation(ns, n5, t5, i5, o5), { - ...config3, - ...context - }, response); - return { - response, - output: parsed - }; - } catch (error50) { - Object.defineProperty(error50, "$response", { - value: response, - enumerable: false, - writable: false, - configurable: false - }); - if (!("$metadata" in error50)) { - const hint = `Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`; - try { - error50.message += "\n " + hint; - } catch (e5) { - if (!context.logger || context.logger?.constructor?.name === "NoOpLogger") { - console.warn(hint); - } else { - context.logger?.warn?.(hint); - } - } - if (typeof error50.$responseBodyText !== "undefined") { - if (error50.$response) { - error50.$response.body = error50.$responseBodyText; - } - } - try { - if (import_protocol_http.HttpResponse.isInstance(response)) { - const { headers = {} } = response; - const headerEntries = Object.entries(headers); - error50.$metadata = { - httpStatusCode: response.statusCode, - requestId: findHeader(/^x-[\w-]+-request-?id$/, headerEntries), - extendedRequestId: findHeader(/^x-[\w-]+-id-2$/, headerEntries), - cfId: findHeader(/^x-[\w-]+-cf-id$/, headerEntries) - }; - } - } catch (e5) { - } - } - throw error50; - } - }; - findHeader = (pattern, headers) => { - return (headers.find(([k5]) => { - return k5.match(pattern); - }) || [void 0, void 0])[1]; - }; - } -}); - -// node_modules/.pnpm/@smithy+querystring-parser@4.2.13/node_modules/@smithy/querystring-parser/dist-cjs/index.js -var require_dist_cjs24 = __commonJS({ - "node_modules/.pnpm/@smithy+querystring-parser@4.2.13/node_modules/@smithy/querystring-parser/dist-cjs/index.js"(exports) { - "use strict"; - function parseQueryString(querystring) { - const query = {}; - querystring = querystring.replace(/^\?/, ""); - if (querystring) { - for (const pair of querystring.split("&")) { - let [key, value = null] = pair.split("="); - key = decodeURIComponent(key); - if (value) { - value = decodeURIComponent(value); - } - if (!(key in query)) { - query[key] = value; - } else if (Array.isArray(query[key])) { - query[key].push(value); - } else { - query[key] = [query[key], value]; - } - } - } - return query; - } - exports.parseQueryString = parseQueryString; - } -}); - -// node_modules/.pnpm/@smithy+url-parser@4.2.13/node_modules/@smithy/url-parser/dist-cjs/index.js -var require_dist_cjs25 = __commonJS({ - "node_modules/.pnpm/@smithy+url-parser@4.2.13/node_modules/@smithy/url-parser/dist-cjs/index.js"(exports) { - "use strict"; - var querystringParser = require_dist_cjs24(); - var parseUrl7 = (url2) => { - if (typeof url2 === "string") { - return parseUrl7(new URL(url2)); - } - const { hostname: hostname3, pathname, port, protocol, search } = url2; - let query; - if (search) { - query = querystringParser.parseQueryString(search); - } - return { - hostname: hostname3, - port: port ? parseInt(port) : void 0, - protocol, - path: pathname, - query - }; - }; - exports.parseUrl = parseUrl7; - } -}); - -// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/endpoints/toEndpointV1.js -var import_url_parser, toEndpointV1; -var init_toEndpointV1 = __esm({ - "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/endpoints/toEndpointV1.js"() { - import_url_parser = __toESM(require_dist_cjs25()); - toEndpointV1 = (endpoint) => { - if (typeof endpoint === "object") { - if ("url" in endpoint) { - const v1Endpoint = (0, import_url_parser.parseUrl)(endpoint.url); - if (endpoint.headers) { - v1Endpoint.headers = {}; - for (const [name, values2] of Object.entries(endpoint.headers)) { - v1Endpoint.headers[name.toLowerCase()] = values2.join(", "); - } - } - return v1Endpoint; - } - return endpoint; - } - return (0, import_url_parser.parseUrl)(endpoint); - }; - } -}); - -// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/endpoints/index.js -var endpoints_exports = {}; -__export(endpoints_exports, { - toEndpointV1: () => toEndpointV1 -}); -var init_endpoints = __esm({ - "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/endpoints/index.js"() { - init_toEndpointV1(); - } -}); - -// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/schema/middleware/schemaSerializationMiddleware.js -var import_util_middleware2, schemaSerializationMiddleware; -var init_schemaSerializationMiddleware = __esm({ - "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/schema/middleware/schemaSerializationMiddleware.js"() { - init_endpoints(); - import_util_middleware2 = __toESM(require_dist_cjs18()); - init_operation(); - schemaSerializationMiddleware = (config3) => (next, context) => async (args) => { - const { operationSchema } = (0, import_util_middleware2.getSmithyContext)(context); - const [, ns, n5, t5, i5, o5] = operationSchema ?? []; - const endpoint = context.endpointV2 ? async () => toEndpointV1(context.endpointV2) : config3.endpoint; - const request = await config3.protocol.serializeRequest(operation(ns, n5, t5, i5, o5), args.input, { - ...config3, - ...context, - endpoint - }); - return next({ - ...args, - request - }); - }; - } -}); - -// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/schema/middleware/getSchemaSerdePlugin.js -function getSchemaSerdePlugin(config3) { - return { - applyToStack: (commandStack) => { - commandStack.add(schemaSerializationMiddleware(config3), serializerMiddlewareOption); - commandStack.add(schemaDeserializationMiddleware(config3), deserializerMiddlewareOption); - config3.protocol.setSerdeContext(config3); - } - }; -} -var deserializerMiddlewareOption, serializerMiddlewareOption; -var init_getSchemaSerdePlugin = __esm({ - "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/schema/middleware/getSchemaSerdePlugin.js"() { - init_schemaDeserializationMiddleware(); - init_schemaSerializationMiddleware(); - deserializerMiddlewareOption = { - name: "deserializerMiddleware", - step: "deserialize", - tags: ["DESERIALIZER"], - override: true - }; - serializerMiddlewareOption = { - name: "serializerMiddleware", - step: "serialize", - tags: ["SERIALIZER"], - override: true - }; - } -}); - -// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/schema/schemas/Schema.js -var Schema2; -var init_Schema = __esm({ - "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/schema/schemas/Schema.js"() { - Schema2 = class { - name; - namespace; - traits; - static assign(instance, values2) { - const schema2 = Object.assign(instance, values2); - return schema2; - } - static [Symbol.hasInstance](lhs) { - const isPrototype = this.prototype.isPrototypeOf(lhs); - if (!isPrototype && typeof lhs === "object" && lhs !== null) { - const list2 = lhs; - return list2.symbol === this.symbol; - } - return isPrototype; - } - getName() { - return this.namespace + "#" + this.name; - } - }; - } -}); - -// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/schema/schemas/ListSchema.js -var ListSchema, list; -var init_ListSchema = __esm({ - "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/schema/schemas/ListSchema.js"() { - init_Schema(); - ListSchema = class _ListSchema extends Schema2 { - static symbol = /* @__PURE__ */ Symbol.for("@smithy/lis"); - name; - traits; - valueSchema; - symbol = _ListSchema.symbol; - }; - list = (namespace, name, traits, valueSchema) => Schema2.assign(new ListSchema(), { - name, - namespace, - traits, - valueSchema - }); - } -}); - -// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/schema/schemas/MapSchema.js -var MapSchema, map; -var init_MapSchema = __esm({ - "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/schema/schemas/MapSchema.js"() { - init_Schema(); - MapSchema = class _MapSchema extends Schema2 { - static symbol = /* @__PURE__ */ Symbol.for("@smithy/map"); - name; - traits; - keySchema; - valueSchema; - symbol = _MapSchema.symbol; - }; - map = (namespace, name, traits, keySchema, valueSchema) => Schema2.assign(new MapSchema(), { - name, - namespace, - traits, - keySchema, - valueSchema - }); - } -}); - -// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/schema/schemas/OperationSchema.js -var OperationSchema, op; -var init_OperationSchema = __esm({ - "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/schema/schemas/OperationSchema.js"() { - init_Schema(); - OperationSchema = class _OperationSchema extends Schema2 { - static symbol = /* @__PURE__ */ Symbol.for("@smithy/ope"); - name; - traits; - input; - output; - symbol = _OperationSchema.symbol; - }; - op = (namespace, name, traits, input, output) => Schema2.assign(new OperationSchema(), { - name, - namespace, - traits, - input, - output - }); - } -}); - -// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/schema/schemas/StructureSchema.js -var StructureSchema, struct; -var init_StructureSchema = __esm({ - "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/schema/schemas/StructureSchema.js"() { - init_Schema(); - StructureSchema = class _StructureSchema extends Schema2 { - static symbol = /* @__PURE__ */ Symbol.for("@smithy/str"); - name; - traits; - memberNames; - memberList; - symbol = _StructureSchema.symbol; - }; - struct = (namespace, name, traits, memberNames, memberList) => Schema2.assign(new StructureSchema(), { - name, - namespace, - traits, - memberNames, - memberList - }); - } -}); - -// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/schema/schemas/ErrorSchema.js -var ErrorSchema, error; -var init_ErrorSchema = __esm({ - "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/schema/schemas/ErrorSchema.js"() { - init_Schema(); - init_StructureSchema(); - ErrorSchema = class _ErrorSchema extends StructureSchema { - static symbol = /* @__PURE__ */ Symbol.for("@smithy/err"); - ctor; - symbol = _ErrorSchema.symbol; - }; - error = (namespace, name, traits, memberNames, memberList, ctor) => Schema2.assign(new ErrorSchema(), { - name, - namespace, - traits, - memberNames, - memberList, - ctor: null - }); - } -}); - -// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/schema/schemas/translateTraits.js -function translateTraits(indicator) { - if (typeof indicator === "object") { - return indicator; - } - indicator = indicator | 0; - if (traitsCache[indicator]) { - return traitsCache[indicator]; - } - const traits = {}; - let i5 = 0; - for (const trait of [ - "httpLabel", - "idempotent", - "idempotencyToken", - "sensitive", - "httpPayload", - "httpResponseCode", - "httpQueryParams" - ]) { - if ((indicator >> i5++ & 1) === 1) { - traits[trait] = 1; - } - } - return traitsCache[indicator] = traits; -} -var traitsCache; -var init_translateTraits = __esm({ - "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/schema/schemas/translateTraits.js"() { - traitsCache = []; - } -}); - -// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/schema/schemas/NormalizedSchema.js -function member(memberSchema, memberName) { - if (memberSchema instanceof NormalizedSchema) { - return Object.assign(memberSchema, { - memberName, - _isMemberSchema: true - }); - } - const internalCtorAccess = NormalizedSchema; - return new internalCtorAccess(memberSchema, memberName); -} -var anno, simpleSchemaCacheN, simpleSchemaCacheS, NormalizedSchema, isMemberSchema, isStaticSchema; -var init_NormalizedSchema = __esm({ - "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/schema/schemas/NormalizedSchema.js"() { - init_deref(); - init_translateTraits(); - anno = { - it: /* @__PURE__ */ Symbol.for("@smithy/nor-struct-it"), - ns: /* @__PURE__ */ Symbol.for("@smithy/ns") - }; - simpleSchemaCacheN = []; - simpleSchemaCacheS = {}; - NormalizedSchema = class _NormalizedSchema { - ref; - memberName; - static symbol = /* @__PURE__ */ Symbol.for("@smithy/nor"); - symbol = _NormalizedSchema.symbol; - name; - schema; - _isMemberSchema; - traits; - memberTraits; - normalizedTraits; - constructor(ref, memberName) { - this.ref = ref; - this.memberName = memberName; - const traitStack = []; - let _ref = ref; - let schema2 = ref; - this._isMemberSchema = false; - while (isMemberSchema(_ref)) { - traitStack.push(_ref[1]); - _ref = _ref[0]; - schema2 = deref(_ref); - this._isMemberSchema = true; - } - if (traitStack.length > 0) { - this.memberTraits = {}; - for (let i5 = traitStack.length - 1; i5 >= 0; --i5) { - const traitSet = traitStack[i5]; - Object.assign(this.memberTraits, translateTraits(traitSet)); - } - } else { - this.memberTraits = 0; - } - if (schema2 instanceof _NormalizedSchema) { - const computedMemberTraits = this.memberTraits; - Object.assign(this, schema2); - this.memberTraits = Object.assign({}, computedMemberTraits, schema2.getMemberTraits(), this.getMemberTraits()); - this.normalizedTraits = void 0; - this.memberName = memberName ?? schema2.memberName; - return; - } - this.schema = deref(schema2); - if (isStaticSchema(this.schema)) { - this.name = `${this.schema[1]}#${this.schema[2]}`; - this.traits = this.schema[3]; - } else { - this.name = this.memberName ?? String(schema2); - this.traits = 0; - } - if (this._isMemberSchema && !memberName) { - throw new Error(`@smithy/core/schema - NormalizedSchema member init ${this.getName(true)} missing member name.`); - } - } - static [Symbol.hasInstance](lhs) { - const isPrototype = this.prototype.isPrototypeOf(lhs); - if (!isPrototype && typeof lhs === "object" && lhs !== null) { - const ns = lhs; - return ns.symbol === this.symbol; - } - return isPrototype; - } - static of(ref) { - const keyAble = typeof ref === "function" || typeof ref === "object" && ref !== null; - if (typeof ref === "number") { - if (simpleSchemaCacheN[ref]) { - return simpleSchemaCacheN[ref]; - } - } else if (typeof ref === "string") { - if (simpleSchemaCacheS[ref]) { - return simpleSchemaCacheS[ref]; - } - } else if (keyAble) { - if (ref[anno.ns]) { - return ref[anno.ns]; - } - } - const sc = deref(ref); - if (sc instanceof _NormalizedSchema) { - return sc; - } - if (isMemberSchema(sc)) { - const [ns2, traits] = sc; - if (ns2 instanceof _NormalizedSchema) { - Object.assign(ns2.getMergedTraits(), translateTraits(traits)); - return ns2; - } - throw new Error(`@smithy/core/schema - may not init unwrapped member schema=${JSON.stringify(ref, null, 2)}.`); - } - const ns = new _NormalizedSchema(sc); - if (keyAble) { - return ref[anno.ns] = ns; - } - if (typeof sc === "string") { - return simpleSchemaCacheS[sc] = ns; - } - if (typeof sc === "number") { - return simpleSchemaCacheN[sc] = ns; - } - return ns; - } - getSchema() { - const sc = this.schema; - if (Array.isArray(sc) && sc[0] === 0) { - return sc[4]; - } - return sc; - } - getName(withNamespace = false) { - const { name } = this; - const short = !withNamespace && name && name.includes("#"); - return short ? name.split("#")[1] : name || void 0; - } - getMemberName() { - return this.memberName; - } - isMemberSchema() { - return this._isMemberSchema; - } - isListSchema() { - const sc = this.getSchema(); - return typeof sc === "number" ? sc >= 64 && sc < 128 : sc[0] === 1; - } - isMapSchema() { - const sc = this.getSchema(); - return typeof sc === "number" ? sc >= 128 && sc <= 255 : sc[0] === 2; - } - isStructSchema() { - const sc = this.getSchema(); - if (typeof sc !== "object") { - return false; - } - const id = sc[0]; - return id === 3 || id === -3 || id === 4; - } - isUnionSchema() { - const sc = this.getSchema(); - if (typeof sc !== "object") { - return false; - } - return sc[0] === 4; - } - isBlobSchema() { - const sc = this.getSchema(); - return sc === 21 || sc === 42; - } - isTimestampSchema() { - const sc = this.getSchema(); - return typeof sc === "number" && sc >= 4 && sc <= 7; - } - isUnitSchema() { - return this.getSchema() === "unit"; - } - isDocumentSchema() { - return this.getSchema() === 15; - } - isStringSchema() { - return this.getSchema() === 0; - } - isBooleanSchema() { - return this.getSchema() === 2; - } - isNumericSchema() { - return this.getSchema() === 1; - } - isBigIntegerSchema() { - return this.getSchema() === 17; - } - isBigDecimalSchema() { - return this.getSchema() === 19; - } - isStreaming() { - const { streaming } = this.getMergedTraits(); - return !!streaming || this.getSchema() === 42; - } - isIdempotencyToken() { - return !!this.getMergedTraits().idempotencyToken; - } - getMergedTraits() { - return this.normalizedTraits ?? (this.normalizedTraits = { - ...this.getOwnTraits(), - ...this.getMemberTraits() - }); - } - getMemberTraits() { - return translateTraits(this.memberTraits); - } - getOwnTraits() { - return translateTraits(this.traits); - } - getKeySchema() { - const [isDoc, isMap] = [this.isDocumentSchema(), this.isMapSchema()]; - if (!isDoc && !isMap) { - throw new Error(`@smithy/core/schema - cannot get key for non-map: ${this.getName(true)}`); - } - const schema2 = this.getSchema(); - const memberSchema = isDoc ? 15 : schema2[4] ?? 0; - return member([memberSchema, 0], "key"); - } - getValueSchema() { - const sc = this.getSchema(); - const [isDoc, isMap, isList] = [this.isDocumentSchema(), this.isMapSchema(), this.isListSchema()]; - const memberSchema = typeof sc === "number" ? 63 & sc : sc && typeof sc === "object" && (isMap || isList) ? sc[3 + sc[0]] : isDoc ? 15 : void 0; - if (memberSchema != null) { - return member([memberSchema, 0], isMap ? "value" : "member"); - } - throw new Error(`@smithy/core/schema - ${this.getName(true)} has no value member.`); - } - getMemberSchema(memberName) { - const struct2 = this.getSchema(); - if (this.isStructSchema() && struct2[4].includes(memberName)) { - const i5 = struct2[4].indexOf(memberName); - const memberSchema = struct2[5][i5]; - return member(isMemberSchema(memberSchema) ? memberSchema : [memberSchema, 0], memberName); - } - if (this.isDocumentSchema()) { - return member([15, 0], memberName); - } - throw new Error(`@smithy/core/schema - ${this.getName(true)} has no member=${memberName}.`); - } - getMemberSchemas() { - const buffer2 = {}; - try { - for (const [k5, v5] of this.structIterator()) { - buffer2[k5] = v5; - } - } catch (ignored) { - } - return buffer2; - } - getEventStreamMember() { - if (this.isStructSchema()) { - for (const [memberName, memberSchema] of this.structIterator()) { - if (memberSchema.isStreaming() && memberSchema.isStructSchema()) { - return memberName; - } - } - } - return ""; - } - *structIterator() { - if (this.isUnitSchema()) { - return; - } - if (!this.isStructSchema()) { - throw new Error("@smithy/core/schema - cannot iterate non-struct schema."); - } - const struct2 = this.getSchema(); - const z3 = struct2[4].length; - let it = struct2[anno.it]; - if (it && z3 === it.length) { - yield* it; - return; - } - it = Array(z3); - for (let i5 = 0; i5 < z3; ++i5) { - const k5 = struct2[4][i5]; - const v5 = member([struct2[5][i5], 0], k5); - yield it[i5] = [k5, v5]; - } - struct2[anno.it] = it; - } - }; - isMemberSchema = (sc) => Array.isArray(sc) && sc.length === 2; - isStaticSchema = (sc) => Array.isArray(sc) && sc.length >= 5; - } -}); - -// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/schema/schemas/SimpleSchema.js -var SimpleSchema, sim, simAdapter; -var init_SimpleSchema = __esm({ - "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/schema/schemas/SimpleSchema.js"() { - init_Schema(); - SimpleSchema = class _SimpleSchema extends Schema2 { - static symbol = /* @__PURE__ */ Symbol.for("@smithy/sim"); - name; - schemaRef; - traits; - symbol = _SimpleSchema.symbol; - }; - sim = (namespace, name, schemaRef, traits) => Schema2.assign(new SimpleSchema(), { - name, - namespace, - traits, - schemaRef - }); - simAdapter = (namespace, name, traits, schemaRef) => Schema2.assign(new SimpleSchema(), { - name, - namespace, - traits, - schemaRef - }); - } -}); - -// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/schema/schemas/sentinels.js -var SCHEMA; -var init_sentinels = __esm({ - "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/schema/schemas/sentinels.js"() { - SCHEMA = { - BLOB: 21, - STREAMING_BLOB: 42, - BOOLEAN: 2, - STRING: 0, - NUMERIC: 1, - BIG_INTEGER: 17, - BIG_DECIMAL: 19, - DOCUMENT: 15, - TIMESTAMP_DEFAULT: 4, - TIMESTAMP_DATE_TIME: 5, - TIMESTAMP_HTTP_DATE: 6, - TIMESTAMP_EPOCH_SECONDS: 7, - LIST_MODIFIER: 64, - MAP_MODIFIER: 128 - }; - } -}); - -// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/schema/TypeRegistry.js -var TypeRegistry; -var init_TypeRegistry = __esm({ - "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/schema/TypeRegistry.js"() { - TypeRegistry = class _TypeRegistry { - namespace; - schemas; - exceptions; - static registries = /* @__PURE__ */ new Map(); - constructor(namespace, schemas = /* @__PURE__ */ new Map(), exceptions = /* @__PURE__ */ new Map()) { - this.namespace = namespace; - this.schemas = schemas; - this.exceptions = exceptions; - } - static for(namespace) { - if (!_TypeRegistry.registries.has(namespace)) { - _TypeRegistry.registries.set(namespace, new _TypeRegistry(namespace)); - } - return _TypeRegistry.registries.get(namespace); - } - copyFrom(other) { - const { schemas, exceptions } = this; - for (const [k5, v5] of other.schemas) { - if (!schemas.has(k5)) { - schemas.set(k5, v5); - } - } - for (const [k5, v5] of other.exceptions) { - if (!exceptions.has(k5)) { - exceptions.set(k5, v5); - } - } - } - register(shapeId, schema2) { - const qualifiedName = this.normalizeShapeId(shapeId); - for (const r5 of [this, _TypeRegistry.for(qualifiedName.split("#")[0])]) { - r5.schemas.set(qualifiedName, schema2); - } - } - getSchema(shapeId) { - const id = this.normalizeShapeId(shapeId); - if (!this.schemas.has(id)) { - throw new Error(`@smithy/core/schema - schema not found for ${id}`); - } - return this.schemas.get(id); - } - registerError(es, ctor) { - const $error = es; - const ns = $error[1]; - for (const r5 of [this, _TypeRegistry.for(ns)]) { - r5.schemas.set(ns + "#" + $error[2], $error); - r5.exceptions.set($error, ctor); - } - } - getErrorCtor(es) { - const $error = es; - if (this.exceptions.has($error)) { - return this.exceptions.get($error); - } - const registry2 = _TypeRegistry.for($error[1]); - return registry2.exceptions.get($error); - } - getBaseException() { - for (const exceptionKey of this.exceptions.keys()) { - if (Array.isArray(exceptionKey)) { - const [, ns, name] = exceptionKey; - const id = ns + "#" + name; - if (id.startsWith("smithy.ts.sdk.synthetic.") && id.endsWith("ServiceException")) { - return exceptionKey; - } - } - } - return void 0; - } - find(predicate) { - return [...this.schemas.values()].find(predicate); - } - clear() { - this.schemas.clear(); - this.exceptions.clear(); - } - normalizeShapeId(shapeId) { - if (shapeId.includes("#")) { - return shapeId; - } - return this.namespace + "#" + shapeId; - } - }; - } -}); - -// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/schema/index.js -var schema_exports2 = {}; -__export(schema_exports2, { - ErrorSchema: () => ErrorSchema, - ListSchema: () => ListSchema, - MapSchema: () => MapSchema, - NormalizedSchema: () => NormalizedSchema, - OperationSchema: () => OperationSchema, - SCHEMA: () => SCHEMA, - Schema: () => Schema2, - SimpleSchema: () => SimpleSchema, - StructureSchema: () => StructureSchema, - TypeRegistry: () => TypeRegistry, - deref: () => deref, - deserializerMiddlewareOption: () => deserializerMiddlewareOption, - error: () => error, - getSchemaSerdePlugin: () => getSchemaSerdePlugin, - isStaticSchema: () => isStaticSchema, - list: () => list, - map: () => map, - op: () => op, - operation: () => operation, - serializerMiddlewareOption: () => serializerMiddlewareOption, - sim: () => sim, - simAdapter: () => simAdapter, - simpleSchemaCacheN: () => simpleSchemaCacheN, - simpleSchemaCacheS: () => simpleSchemaCacheS, - struct: () => struct, - traitsCache: () => traitsCache, - translateTraits: () => translateTraits -}); -var init_schema3 = __esm({ - "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/schema/index.js"() { - init_deref(); - init_getSchemaSerdePlugin(); - init_ListSchema(); - init_MapSchema(); - init_OperationSchema(); - init_operation(); - init_ErrorSchema(); - init_NormalizedSchema(); - init_Schema(); - init_SimpleSchema(); - init_StructureSchema(); - init_sentinels(); - init_translateTraits(); - init_TypeRegistry(); - } -}); - -// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/serde/copyDocumentWithTransform.js -var copyDocumentWithTransform; -var init_copyDocumentWithTransform = __esm({ - "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/serde/copyDocumentWithTransform.js"() { - copyDocumentWithTransform = (source, schemaRef, transform3 = (_) => _) => source; - } -}); - -// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/serde/parse-utils.js -var parseBoolean2, expectBoolean, expectNumber, MAX_FLOAT, expectFloat32, expectLong, expectInt, expectInt32, expectShort, expectByte, expectSizedInt, castInt, expectNonNull, expectObject, expectString, expectUnion, strictParseDouble, strictParseFloat, strictParseFloat32, NUMBER_REGEX, parseNumber2, limitedParseDouble, handleFloat, limitedParseFloat, limitedParseFloat32, parseFloatString, strictParseLong, strictParseInt, strictParseInt32, strictParseShort, strictParseByte, stackTraceWarning, logger2; -var init_parse_utils = __esm({ - "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/serde/parse-utils.js"() { - parseBoolean2 = (value) => { - switch (value) { - case "true": - return true; - case "false": - return false; - default: - throw new Error(`Unable to parse boolean value "${value}"`); - } - }; - expectBoolean = (value) => { - if (value === null || value === void 0) { - return void 0; - } - if (typeof value === "number") { - if (value === 0 || value === 1) { - logger2.warn(stackTraceWarning(`Expected boolean, got ${typeof value}: ${value}`)); - } - if (value === 0) { - return false; - } - if (value === 1) { - return true; - } - } - if (typeof value === "string") { - const lower = value.toLowerCase(); - if (lower === "false" || lower === "true") { - logger2.warn(stackTraceWarning(`Expected boolean, got ${typeof value}: ${value}`)); - } - if (lower === "false") { - return false; - } - if (lower === "true") { - return true; - } - } - if (typeof value === "boolean") { - return value; - } - throw new TypeError(`Expected boolean, got ${typeof value}: ${value}`); - }; - expectNumber = (value) => { - if (value === null || value === void 0) { - return void 0; - } - if (typeof value === "string") { - const parsed = parseFloat(value); - if (!Number.isNaN(parsed)) { - if (String(parsed) !== String(value)) { - logger2.warn(stackTraceWarning(`Expected number but observed string: ${value}`)); - } - return parsed; - } - } - if (typeof value === "number") { - return value; - } - throw new TypeError(`Expected number, got ${typeof value}: ${value}`); - }; - MAX_FLOAT = Math.ceil(2 ** 127 * (2 - 2 ** -23)); - expectFloat32 = (value) => { - const expected = expectNumber(value); - if (expected !== void 0 && !Number.isNaN(expected) && expected !== Infinity && expected !== -Infinity) { - if (Math.abs(expected) > MAX_FLOAT) { - throw new TypeError(`Expected 32-bit float, got ${value}`); - } - } - return expected; - }; - expectLong = (value) => { - if (value === null || value === void 0) { - return void 0; - } - if (Number.isInteger(value) && !Number.isNaN(value)) { - return value; - } - throw new TypeError(`Expected integer, got ${typeof value}: ${value}`); - }; - expectInt = expectLong; - expectInt32 = (value) => expectSizedInt(value, 32); - expectShort = (value) => expectSizedInt(value, 16); - expectByte = (value) => expectSizedInt(value, 8); - expectSizedInt = (value, size2) => { - const expected = expectLong(value); - if (expected !== void 0 && castInt(expected, size2) !== expected) { - throw new TypeError(`Expected ${size2}-bit integer, got ${value}`); - } - return expected; - }; - castInt = (value, size2) => { - switch (size2) { - case 32: - return Int32Array.of(value)[0]; - case 16: - return Int16Array.of(value)[0]; - case 8: - return Int8Array.of(value)[0]; - } - }; - expectNonNull = (value, location) => { - if (value === null || value === void 0) { - if (location) { - throw new TypeError(`Expected a non-null value for ${location}`); - } - throw new TypeError("Expected a non-null value"); - } - return value; - }; - expectObject = (value) => { - if (value === null || value === void 0) { - return void 0; - } - if (typeof value === "object" && !Array.isArray(value)) { - return value; - } - const receivedType = Array.isArray(value) ? "array" : typeof value; - throw new TypeError(`Expected object, got ${receivedType}: ${value}`); - }; - expectString = (value) => { - if (value === null || value === void 0) { - return void 0; - } - if (typeof value === "string") { - return value; - } - if (["boolean", "number", "bigint"].includes(typeof value)) { - logger2.warn(stackTraceWarning(`Expected string, got ${typeof value}: ${value}`)); - return String(value); - } - throw new TypeError(`Expected string, got ${typeof value}: ${value}`); - }; - expectUnion = (value) => { - if (value === null || value === void 0) { - return void 0; - } - const asObject = expectObject(value); - const setKeys = Object.entries(asObject).filter(([, v5]) => v5 != null).map(([k5]) => k5); - if (setKeys.length === 0) { - throw new TypeError(`Unions must have exactly one non-null member. None were found.`); - } - if (setKeys.length > 1) { - throw new TypeError(`Unions must have exactly one non-null member. Keys ${setKeys} were not null.`); - } - return asObject; - }; - strictParseDouble = (value) => { - if (typeof value == "string") { - return expectNumber(parseNumber2(value)); - } - return expectNumber(value); - }; - strictParseFloat = strictParseDouble; - strictParseFloat32 = (value) => { - if (typeof value == "string") { - return expectFloat32(parseNumber2(value)); - } - return expectFloat32(value); - }; - NUMBER_REGEX = /(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)|(-?Infinity)|(NaN)/g; - parseNumber2 = (value) => { - const matches = value.match(NUMBER_REGEX); - if (matches === null || matches[0].length !== value.length) { - throw new TypeError(`Expected real number, got implicit NaN`); - } - return parseFloat(value); - }; - limitedParseDouble = (value) => { - if (typeof value == "string") { - return parseFloatString(value); - } - return expectNumber(value); - }; - handleFloat = limitedParseDouble; - limitedParseFloat = limitedParseDouble; - limitedParseFloat32 = (value) => { - if (typeof value == "string") { - return parseFloatString(value); - } - return expectFloat32(value); - }; - parseFloatString = (value) => { - switch (value) { - case "NaN": - return NaN; - case "Infinity": - return Infinity; - case "-Infinity": - return -Infinity; - default: - throw new Error(`Unable to parse float value: ${value}`); - } - }; - strictParseLong = (value) => { - if (typeof value === "string") { - return expectLong(parseNumber2(value)); - } - return expectLong(value); - }; - strictParseInt = strictParseLong; - strictParseInt32 = (value) => { - if (typeof value === "string") { - return expectInt32(parseNumber2(value)); - } - return expectInt32(value); - }; - strictParseShort = (value) => { - if (typeof value === "string") { - return expectShort(parseNumber2(value)); - } - return expectShort(value); - }; - strictParseByte = (value) => { - if (typeof value === "string") { - return expectByte(parseNumber2(value)); - } - return expectByte(value); - }; - stackTraceWarning = (message2) => { - return String(new TypeError(message2).stack || message2).split("\n").slice(0, 5).filter((s5) => !s5.includes("stackTraceWarning")).join("\n"); - }; - logger2 = { - warn: console.warn - }; - } -}); - -// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/serde/date-utils.js -function dateToUtcString(date7) { - const year3 = date7.getUTCFullYear(); - const month = date7.getUTCMonth(); - const dayOfWeek = date7.getUTCDay(); - const dayOfMonthInt = date7.getUTCDate(); - const hoursInt = date7.getUTCHours(); - const minutesInt = date7.getUTCMinutes(); - const secondsInt = date7.getUTCSeconds(); - const dayOfMonthString = dayOfMonthInt < 10 ? `0${dayOfMonthInt}` : `${dayOfMonthInt}`; - const hoursString = hoursInt < 10 ? `0${hoursInt}` : `${hoursInt}`; - const minutesString = minutesInt < 10 ? `0${minutesInt}` : `${minutesInt}`; - const secondsString = secondsInt < 10 ? `0${secondsInt}` : `${secondsInt}`; - return `${DAYS[dayOfWeek]}, ${dayOfMonthString} ${MONTHS[month]} ${year3} ${hoursString}:${minutesString}:${secondsString} GMT`; -} -var DAYS, MONTHS, RFC3339, parseRfc3339DateTime, RFC3339_WITH_OFFSET, parseRfc3339DateTimeWithOffset, IMF_FIXDATE, RFC_850_DATE, ASC_TIME, parseRfc7231DateTime, parseEpochTimestamp, buildDate, parseTwoDigitYear, FIFTY_YEARS_IN_MILLIS, adjustRfc850Year, parseMonthByShortName, DAYS_IN_MONTH, validateDayOfMonth, isLeapYear, parseDateValue, parseMilliseconds, parseOffsetToMilliseconds, stripLeadingZeroes; -var init_date_utils = __esm({ - "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/serde/date-utils.js"() { - init_parse_utils(); - DAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; - MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; - RFC3339 = new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?[zZ]$/); - parseRfc3339DateTime = (value) => { - if (value === null || value === void 0) { - return void 0; - } - if (typeof value !== "string") { - throw new TypeError("RFC-3339 date-times must be expressed as strings"); - } - const match = RFC3339.exec(value); - if (!match) { - throw new TypeError("Invalid RFC-3339 date-time value"); - } - const [_, yearStr, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds] = match; - const year3 = strictParseShort(stripLeadingZeroes(yearStr)); - const month = parseDateValue(monthStr, "month", 1, 12); - const day2 = parseDateValue(dayStr, "day", 1, 31); - return buildDate(year3, month, day2, { hours, minutes, seconds, fractionalMilliseconds }); - }; - RFC3339_WITH_OFFSET = new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}\:\d{2})|[zZ])$/); - parseRfc3339DateTimeWithOffset = (value) => { - if (value === null || value === void 0) { - return void 0; - } - if (typeof value !== "string") { - throw new TypeError("RFC-3339 date-times must be expressed as strings"); - } - const match = RFC3339_WITH_OFFSET.exec(value); - if (!match) { - throw new TypeError("Invalid RFC-3339 date-time value"); - } - const [_, yearStr, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds, offsetStr] = match; - const year3 = strictParseShort(stripLeadingZeroes(yearStr)); - const month = parseDateValue(monthStr, "month", 1, 12); - const day2 = parseDateValue(dayStr, "day", 1, 31); - const date7 = buildDate(year3, month, day2, { hours, minutes, seconds, fractionalMilliseconds }); - if (offsetStr.toUpperCase() != "Z") { - date7.setTime(date7.getTime() - parseOffsetToMilliseconds(offsetStr)); - } - return date7; - }; - IMF_FIXDATE = new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/); - RFC_850_DATE = new RegExp(/^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/); - ASC_TIME = new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( [1-9]|\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? (\d{4})$/); - parseRfc7231DateTime = (value) => { - if (value === null || value === void 0) { - return void 0; - } - if (typeof value !== "string") { - throw new TypeError("RFC-7231 date-times must be expressed as strings"); - } - let match = IMF_FIXDATE.exec(value); - if (match) { - const [_, dayStr, monthStr, yearStr, hours, minutes, seconds, fractionalMilliseconds] = match; - return buildDate(strictParseShort(stripLeadingZeroes(yearStr)), parseMonthByShortName(monthStr), parseDateValue(dayStr, "day", 1, 31), { hours, minutes, seconds, fractionalMilliseconds }); - } - match = RFC_850_DATE.exec(value); - if (match) { - const [_, dayStr, monthStr, yearStr, hours, minutes, seconds, fractionalMilliseconds] = match; - return adjustRfc850Year(buildDate(parseTwoDigitYear(yearStr), parseMonthByShortName(monthStr), parseDateValue(dayStr, "day", 1, 31), { - hours, - minutes, - seconds, - fractionalMilliseconds - })); - } - match = ASC_TIME.exec(value); - if (match) { - const [_, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds, yearStr] = match; - return buildDate(strictParseShort(stripLeadingZeroes(yearStr)), parseMonthByShortName(monthStr), parseDateValue(dayStr.trimLeft(), "day", 1, 31), { hours, minutes, seconds, fractionalMilliseconds }); - } - throw new TypeError("Invalid RFC-7231 date-time value"); - }; - parseEpochTimestamp = (value) => { - if (value === null || value === void 0) { - return void 0; - } - let valueAsDouble; - if (typeof value === "number") { - valueAsDouble = value; - } else if (typeof value === "string") { - valueAsDouble = strictParseDouble(value); - } else if (typeof value === "object" && value.tag === 1) { - valueAsDouble = value.value; - } else { - throw new TypeError("Epoch timestamps must be expressed as floating point numbers or their string representation"); - } - if (Number.isNaN(valueAsDouble) || valueAsDouble === Infinity || valueAsDouble === -Infinity) { - throw new TypeError("Epoch timestamps must be valid, non-Infinite, non-NaN numerics"); - } - return new Date(Math.round(valueAsDouble * 1e3)); - }; - buildDate = (year3, month, day2, time5) => { - const adjustedMonth = month - 1; - validateDayOfMonth(year3, adjustedMonth, day2); - return new Date(Date.UTC(year3, adjustedMonth, day2, parseDateValue(time5.hours, "hour", 0, 23), parseDateValue(time5.minutes, "minute", 0, 59), parseDateValue(time5.seconds, "seconds", 0, 60), parseMilliseconds(time5.fractionalMilliseconds))); - }; - parseTwoDigitYear = (value) => { - const thisYear = (/* @__PURE__ */ new Date()).getUTCFullYear(); - const valueInThisCentury = Math.floor(thisYear / 100) * 100 + strictParseShort(stripLeadingZeroes(value)); - if (valueInThisCentury < thisYear) { - return valueInThisCentury + 100; - } - return valueInThisCentury; - }; - FIFTY_YEARS_IN_MILLIS = 50 * 365 * 24 * 60 * 60 * 1e3; - adjustRfc850Year = (input) => { - if (input.getTime() - (/* @__PURE__ */ new Date()).getTime() > FIFTY_YEARS_IN_MILLIS) { - return new Date(Date.UTC(input.getUTCFullYear() - 100, input.getUTCMonth(), input.getUTCDate(), input.getUTCHours(), input.getUTCMinutes(), input.getUTCSeconds(), input.getUTCMilliseconds())); - } - return input; - }; - parseMonthByShortName = (value) => { - const monthIdx = MONTHS.indexOf(value); - if (monthIdx < 0) { - throw new TypeError(`Invalid month: ${value}`); - } - return monthIdx + 1; - }; - DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; - validateDayOfMonth = (year3, month, day2) => { - let maxDays = DAYS_IN_MONTH[month]; - if (month === 1 && isLeapYear(year3)) { - maxDays = 29; - } - if (day2 > maxDays) { - throw new TypeError(`Invalid day for ${MONTHS[month]} in ${year3}: ${day2}`); - } - }; - isLeapYear = (year3) => { - return year3 % 4 === 0 && (year3 % 100 !== 0 || year3 % 400 === 0); - }; - parseDateValue = (value, type, lower, upper) => { - const dateVal = strictParseByte(stripLeadingZeroes(value)); - if (dateVal < lower || dateVal > upper) { - throw new TypeError(`${type} must be between ${lower} and ${upper}, inclusive`); - } - return dateVal; - }; - parseMilliseconds = (value) => { - if (value === null || value === void 0) { - return 0; - } - return strictParseFloat32("0." + value) * 1e3; - }; - parseOffsetToMilliseconds = (value) => { - const directionStr = value[0]; - let direction = 1; - if (directionStr == "+") { - direction = 1; - } else if (directionStr == "-") { - direction = -1; - } else { - throw new TypeError(`Offset direction, ${directionStr}, must be "+" or "-"`); - } - const hour2 = Number(value.substring(1, 3)); - const minute2 = Number(value.substring(4, 6)); - return direction * (hour2 * 60 + minute2) * 60 * 1e3; - }; - stripLeadingZeroes = (value) => { - let idx = 0; - while (idx < value.length - 1 && value.charAt(idx) === "0") { - idx++; - } - if (idx === 0) { - return value; - } - return value.slice(idx); - }; - } -}); - -// node_modules/.pnpm/@smithy+uuid@1.1.2/node_modules/@smithy/uuid/dist-cjs/randomUUID.js -var require_randomUUID = __commonJS({ - "node_modules/.pnpm/@smithy+uuid@1.1.2/node_modules/@smithy/uuid/dist-cjs/randomUUID.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.randomUUID = void 0; - var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); - var crypto_1 = tslib_1.__importDefault(__require("crypto")); - exports.randomUUID = crypto_1.default.randomUUID.bind(crypto_1.default); - } -}); - -// node_modules/.pnpm/@smithy+uuid@1.1.2/node_modules/@smithy/uuid/dist-cjs/index.js -var require_dist_cjs26 = __commonJS({ - "node_modules/.pnpm/@smithy+uuid@1.1.2/node_modules/@smithy/uuid/dist-cjs/index.js"(exports) { - "use strict"; - var randomUUID12 = require_randomUUID(); - var decimalToHex = Array.from({ length: 256 }, (_, i5) => i5.toString(16).padStart(2, "0")); - var v42 = () => { - if (randomUUID12.randomUUID) { - return randomUUID12.randomUUID(); - } - const rnds = new Uint8Array(16); - crypto.getRandomValues(rnds); - rnds[6] = rnds[6] & 15 | 64; - rnds[8] = rnds[8] & 63 | 128; - return decimalToHex[rnds[0]] + decimalToHex[rnds[1]] + decimalToHex[rnds[2]] + decimalToHex[rnds[3]] + "-" + decimalToHex[rnds[4]] + decimalToHex[rnds[5]] + "-" + decimalToHex[rnds[6]] + decimalToHex[rnds[7]] + "-" + decimalToHex[rnds[8]] + decimalToHex[rnds[9]] + "-" + decimalToHex[rnds[10]] + decimalToHex[rnds[11]] + decimalToHex[rnds[12]] + decimalToHex[rnds[13]] + decimalToHex[rnds[14]] + decimalToHex[rnds[15]]; - }; - exports.v4 = v42; - } -}); - -// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/serde/generateIdempotencyToken.js -var import_uuid2; -var init_generateIdempotencyToken = __esm({ - "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/serde/generateIdempotencyToken.js"() { - import_uuid2 = __toESM(require_dist_cjs26()); - } -}); - -// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/serde/lazy-json.js -var LazyJsonString; -var init_lazy_json = __esm({ - "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/serde/lazy-json.js"() { - LazyJsonString = function LazyJsonString2(val) { - const str = Object.assign(new String(val), { - deserializeJSON() { - return JSON.parse(String(val)); - }, - toString() { - return String(val); - }, - toJSON() { - return String(val); - } - }); - return str; - }; - LazyJsonString.from = (object2) => { - if (object2 && typeof object2 === "object" && (object2 instanceof LazyJsonString || "deserializeJSON" in object2)) { - return object2; - } else if (typeof object2 === "string" || Object.getPrototypeOf(object2) === String.prototype) { - return LazyJsonString(String(object2)); - } - return LazyJsonString(JSON.stringify(object2)); - }; - LazyJsonString.fromObject = LazyJsonString.from; - } -}); - -// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/serde/quote-header.js -function quoteHeader(part) { - if (part.includes(",") || part.includes('"')) { - part = `"${part.replace(/"/g, '\\"')}"`; - } - return part; -} -var init_quote_header = __esm({ - "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/serde/quote-header.js"() { - } -}); - -// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/serde/schema-serde-lib/schema-date-utils.js -function range(v5, min, max) { - const _v = Number(v5); - if (_v < min || _v > max) { - throw new Error(`Value ${_v} out of range [${min}, ${max}]`); - } -} -var ddd, mmm, time2, date2, year, RFC3339_WITH_OFFSET2, IMF_FIXDATE2, RFC_850_DATE2, ASC_TIME2, months, _parseEpochTimestamp, _parseRfc3339DateTimeWithOffset, _parseRfc7231DateTime; -var init_schema_date_utils = __esm({ - "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/serde/schema-serde-lib/schema-date-utils.js"() { - ddd = `(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)(?:[ne|u?r]?s?day)?`; - mmm = `(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)`; - time2 = `(\\d?\\d):(\\d{2}):(\\d{2})(?:\\.(\\d+))?`; - date2 = `(\\d?\\d)`; - year = `(\\d{4})`; - RFC3339_WITH_OFFSET2 = new RegExp(/^(\d{4})-(\d\d)-(\d\d)[tT](\d\d):(\d\d):(\d\d)(\.(\d+))?(([-+]\d\d:\d\d)|[zZ])$/); - IMF_FIXDATE2 = new RegExp(`^${ddd}, ${date2} ${mmm} ${year} ${time2} GMT$`); - RFC_850_DATE2 = new RegExp(`^${ddd}, ${date2}-${mmm}-(\\d\\d) ${time2} GMT$`); - ASC_TIME2 = new RegExp(`^${ddd} ${mmm} ( [1-9]|\\d\\d) ${time2} ${year}$`); - months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; - _parseEpochTimestamp = (value) => { - if (value == null) { - return void 0; - } - let num = NaN; - if (typeof value === "number") { - num = value; - } else if (typeof value === "string") { - if (!/^-?\d*\.?\d+$/.test(value)) { - throw new TypeError(`parseEpochTimestamp - numeric string invalid.`); - } - num = Number.parseFloat(value); - } else if (typeof value === "object" && value.tag === 1) { - num = value.value; - } - if (isNaN(num) || Math.abs(num) === Infinity) { - throw new TypeError("Epoch timestamps must be valid finite numbers."); - } - return new Date(Math.round(num * 1e3)); - }; - _parseRfc3339DateTimeWithOffset = (value) => { - if (value == null) { - return void 0; - } - if (typeof value !== "string") { - throw new TypeError("RFC3339 timestamps must be strings"); - } - const matches = RFC3339_WITH_OFFSET2.exec(value); - if (!matches) { - throw new TypeError(`Invalid RFC3339 timestamp format ${value}`); - } - const [, yearStr, monthStr, dayStr, hours, minutes, seconds, , ms, offsetStr] = matches; - range(monthStr, 1, 12); - range(dayStr, 1, 31); - range(hours, 0, 23); - range(minutes, 0, 59); - range(seconds, 0, 60); - const date7 = new Date(Date.UTC(Number(yearStr), Number(monthStr) - 1, Number(dayStr), Number(hours), Number(minutes), Number(seconds), Number(ms) ? Math.round(parseFloat(`0.${ms}`) * 1e3) : 0)); - date7.setUTCFullYear(Number(yearStr)); - if (offsetStr.toUpperCase() != "Z") { - const [, sign2, offsetH, offsetM] = /([+-])(\d\d):(\d\d)/.exec(offsetStr) || [void 0, "+", 0, 0]; - const scalar = sign2 === "-" ? 1 : -1; - date7.setTime(date7.getTime() + scalar * (Number(offsetH) * 60 * 60 * 1e3 + Number(offsetM) * 60 * 1e3)); - } - return date7; - }; - _parseRfc7231DateTime = (value) => { - if (value == null) { - return void 0; - } - if (typeof value !== "string") { - throw new TypeError("RFC7231 timestamps must be strings."); - } - let day2; - let month; - let year3; - let hour2; - let minute2; - let second; - let fraction; - let matches; - if (matches = IMF_FIXDATE2.exec(value)) { - [, day2, month, year3, hour2, minute2, second, fraction] = matches; - } else if (matches = RFC_850_DATE2.exec(value)) { - [, day2, month, year3, hour2, minute2, second, fraction] = matches; - year3 = (Number(year3) + 1900).toString(); - } else if (matches = ASC_TIME2.exec(value)) { - [, month, day2, hour2, minute2, second, fraction, year3] = matches; - } - if (year3 && second) { - const timestamp2 = Date.UTC(Number(year3), months.indexOf(month), Number(day2), Number(hour2), Number(minute2), Number(second), fraction ? Math.round(parseFloat(`0.${fraction}`) * 1e3) : 0); - range(day2, 1, 31); - range(hour2, 0, 23); - range(minute2, 0, 59); - range(second, 0, 60); - const date7 = new Date(timestamp2); - date7.setUTCFullYear(Number(year3)); - return date7; - } - throw new TypeError(`Invalid RFC7231 date-time value ${value}.`); - }; - } -}); - -// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/serde/split-every.js -function splitEvery(value, delimiter, numDelimiters) { - if (numDelimiters <= 0 || !Number.isInteger(numDelimiters)) { - throw new Error("Invalid number of delimiters (" + numDelimiters + ") for splitEvery."); - } - const segments = value.split(delimiter); - if (numDelimiters === 1) { - return segments; - } - const compoundSegments = []; - let currentSegment = ""; - for (let i5 = 0; i5 < segments.length; i5++) { - if (currentSegment === "") { - currentSegment = segments[i5]; - } else { - currentSegment += delimiter + segments[i5]; - } - if ((i5 + 1) % numDelimiters === 0) { - compoundSegments.push(currentSegment); - currentSegment = ""; - } - } - if (currentSegment !== "") { - compoundSegments.push(currentSegment); - } - return compoundSegments; -} -var init_split_every = __esm({ - "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/serde/split-every.js"() { - } -}); - -// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/serde/split-header.js -var splitHeader; -var init_split_header = __esm({ - "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/serde/split-header.js"() { - splitHeader = (value) => { - const z3 = value.length; - const values2 = []; - let withinQuotes = false; - let prevChar = void 0; - let anchor = 0; - for (let i5 = 0; i5 < z3; ++i5) { - const char2 = value[i5]; - switch (char2) { - case `"`: - if (prevChar !== "\\") { - withinQuotes = !withinQuotes; - } - break; - case ",": - if (!withinQuotes) { - values2.push(value.slice(anchor, i5)); - anchor = i5 + 1; - } - break; - default: - } - prevChar = char2; - } - values2.push(value.slice(anchor)); - return values2.map((v5) => { - v5 = v5.trim(); - const z4 = v5.length; - if (z4 < 2) { - return v5; - } - if (v5[0] === `"` && v5[z4 - 1] === `"`) { - v5 = v5.slice(1, z4 - 1); - } - return v5.replace(/\\"/g, '"'); - }); - }; - } -}); - -// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/serde/value/NumericValue.js -function nv(input) { - return new NumericValue(String(input), "bigDecimal"); -} -var format, NumericValue; -var init_NumericValue = __esm({ - "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/serde/value/NumericValue.js"() { - format = /^-?\d*(\.\d+)?$/; - NumericValue = class _NumericValue { - string; - type; - constructor(string4, type) { - this.string = string4; - this.type = type; - if (!format.test(string4)) { - throw new Error(`@smithy/core/serde - NumericValue must only contain [0-9], at most one decimal point ".", and an optional negation prefix "-".`); - } - } - toString() { - return this.string; - } - static [Symbol.hasInstance](object2) { - if (!object2 || typeof object2 !== "object") { - return false; - } - const _nv = object2; - return _NumericValue.prototype.isPrototypeOf(object2) || _nv.type === "bigDecimal" && format.test(_nv.string); - } - }; - } -}); - -// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/serde/index.js -var serde_exports = {}; -__export(serde_exports, { - LazyJsonString: () => LazyJsonString, - NumericValue: () => NumericValue, - _parseEpochTimestamp: () => _parseEpochTimestamp, - _parseRfc3339DateTimeWithOffset: () => _parseRfc3339DateTimeWithOffset, - _parseRfc7231DateTime: () => _parseRfc7231DateTime, - copyDocumentWithTransform: () => copyDocumentWithTransform, - dateToUtcString: () => dateToUtcString, - expectBoolean: () => expectBoolean, - expectByte: () => expectByte, - expectFloat32: () => expectFloat32, - expectInt: () => expectInt, - expectInt32: () => expectInt32, - expectLong: () => expectLong, - expectNonNull: () => expectNonNull, - expectNumber: () => expectNumber, - expectObject: () => expectObject, - expectShort: () => expectShort, - expectString: () => expectString, - expectUnion: () => expectUnion, - generateIdempotencyToken: () => import_uuid2.v4, - handleFloat: () => handleFloat, - limitedParseDouble: () => limitedParseDouble, - limitedParseFloat: () => limitedParseFloat, - limitedParseFloat32: () => limitedParseFloat32, - logger: () => logger2, - nv: () => nv, - parseBoolean: () => parseBoolean2, - parseEpochTimestamp: () => parseEpochTimestamp, - parseRfc3339DateTime: () => parseRfc3339DateTime, - parseRfc3339DateTimeWithOffset: () => parseRfc3339DateTimeWithOffset, - parseRfc7231DateTime: () => parseRfc7231DateTime, - quoteHeader: () => quoteHeader, - splitEvery: () => splitEvery, - splitHeader: () => splitHeader, - strictParseByte: () => strictParseByte, - strictParseDouble: () => strictParseDouble, - strictParseFloat: () => strictParseFloat, - strictParseFloat32: () => strictParseFloat32, - strictParseInt: () => strictParseInt, - strictParseInt32: () => strictParseInt32, - strictParseLong: () => strictParseLong, - strictParseShort: () => strictParseShort -}); -var init_serde = __esm({ - "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/serde/index.js"() { - init_copyDocumentWithTransform(); - init_date_utils(); - init_generateIdempotencyToken(); - init_lazy_json(); - init_parse_utils(); - init_quote_header(); - init_schema_date_utils(); - init_split_every(); - init_split_header(); - init_NumericValue(); - } -}); - -// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/protocols/collect-stream-body.js -var import_util_stream, collectBody; -var init_collect_stream_body = __esm({ - "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/protocols/collect-stream-body.js"() { - import_util_stream = __toESM(require_dist_cjs13()); - collectBody = async (streamBody = new Uint8Array(), context) => { - if (streamBody instanceof Uint8Array) { - return import_util_stream.Uint8ArrayBlobAdapter.mutate(streamBody); - } - if (!streamBody) { - return import_util_stream.Uint8ArrayBlobAdapter.mutate(new Uint8Array()); - } - const fromContext = context.streamCollector(streamBody); - return import_util_stream.Uint8ArrayBlobAdapter.mutate(await fromContext); - }; - } -}); - -// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/protocols/extended-encode-uri-component.js -function extendedEncodeURIComponent(str) { - return encodeURIComponent(str).replace(/[!'()*]/g, function(c5) { - return "%" + c5.charCodeAt(0).toString(16).toUpperCase(); - }); -} -var init_extended_encode_uri_component = __esm({ - "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/protocols/extended-encode-uri-component.js"() { - } -}); - -// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/protocols/SerdeContext.js -var SerdeContext; -var init_SerdeContext = __esm({ - "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/protocols/SerdeContext.js"() { - SerdeContext = class { - serdeContext; - setSerdeContext(serdeContext) { - this.serdeContext = serdeContext; - } - }; - } -}); - -// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/event-streams/EventStreamSerde.js -var import_util_utf8, EventStreamSerde; -var init_EventStreamSerde = __esm({ - "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/event-streams/EventStreamSerde.js"() { - import_util_utf8 = __toESM(require_dist_cjs6()); - EventStreamSerde = class { - marshaller; - serializer; - deserializer; - serdeContext; - defaultContentType; - constructor({ marshaller, serializer, deserializer, serdeContext, defaultContentType }) { - this.marshaller = marshaller; - this.serializer = serializer; - this.deserializer = deserializer; - this.serdeContext = serdeContext; - this.defaultContentType = defaultContentType; - } - async serializeEventStream({ eventStream, requestSchema, initialRequest }) { - const marshaller = this.marshaller; - const eventStreamMember = requestSchema.getEventStreamMember(); - const unionSchema = requestSchema.getMemberSchema(eventStreamMember); - const serializer = this.serializer; - const defaultContentType = this.defaultContentType; - const initialRequestMarker = /* @__PURE__ */ Symbol("initialRequestMarker"); - const eventStreamIterable = { - async *[Symbol.asyncIterator]() { - if (initialRequest) { - const headers = { - ":event-type": { type: "string", value: "initial-request" }, - ":message-type": { type: "string", value: "event" }, - ":content-type": { type: "string", value: defaultContentType } - }; - serializer.write(requestSchema, initialRequest); - const body = serializer.flush(); - yield { - [initialRequestMarker]: true, - headers, - body - }; - } - for await (const page of eventStream) { - yield page; - } - } - }; - return marshaller.serialize(eventStreamIterable, (event) => { - if (event[initialRequestMarker]) { - return { - headers: event.headers, - body: event.body - }; - } - const unionMember = Object.keys(event).find((key) => { - return key !== "__type"; - }) ?? ""; - const { additionalHeaders, body, eventType, explicitPayloadContentType } = this.writeEventBody(unionMember, unionSchema, event); - const headers = { - ":event-type": { type: "string", value: eventType }, - ":message-type": { type: "string", value: "event" }, - ":content-type": { type: "string", value: explicitPayloadContentType ?? defaultContentType }, - ...additionalHeaders - }; - return { - headers, - body - }; - }); - } - async deserializeEventStream({ response, responseSchema, initialResponseContainer }) { - const marshaller = this.marshaller; - const eventStreamMember = responseSchema.getEventStreamMember(); - const unionSchema = responseSchema.getMemberSchema(eventStreamMember); - const memberSchemas = unionSchema.getMemberSchemas(); - const initialResponseMarker = /* @__PURE__ */ Symbol("initialResponseMarker"); - const asyncIterable = marshaller.deserialize(response.body, async (event) => { - const unionMember = Object.keys(event).find((key) => { - return key !== "__type"; - }) ?? ""; - const body = event[unionMember].body; - if (unionMember === "initial-response") { - const dataObject = await this.deserializer.read(responseSchema, body); - delete dataObject[eventStreamMember]; - return { - [initialResponseMarker]: true, - ...dataObject - }; - } else if (unionMember in memberSchemas) { - const eventStreamSchema = memberSchemas[unionMember]; - if (eventStreamSchema.isStructSchema()) { - const out = {}; - let hasBindings = false; - for (const [name, member2] of eventStreamSchema.structIterator()) { - const { eventHeader, eventPayload } = member2.getMergedTraits(); - hasBindings = hasBindings || Boolean(eventHeader || eventPayload); - if (eventPayload) { - if (member2.isBlobSchema()) { - out[name] = body; - } else if (member2.isStringSchema()) { - out[name] = (this.serdeContext?.utf8Encoder ?? import_util_utf8.toUtf8)(body); - } else if (member2.isStructSchema()) { - out[name] = await this.deserializer.read(member2, body); - } - } else if (eventHeader) { - const value = event[unionMember].headers[name]?.value; - if (value != null) { - if (member2.isNumericSchema()) { - if (value && typeof value === "object" && "bytes" in value) { - out[name] = BigInt(value.toString()); - } else { - out[name] = Number(value); - } - } else { - out[name] = value; - } - } - } - } - if (hasBindings) { - return { - [unionMember]: out - }; - } - if (body.byteLength === 0) { - return { - [unionMember]: {} - }; - } - } - return { - [unionMember]: await this.deserializer.read(eventStreamSchema, body) - }; - } else { - return { - $unknown: event - }; - } - }); - const asyncIterator = asyncIterable[Symbol.asyncIterator](); - const firstEvent = await asyncIterator.next(); - if (firstEvent.done) { - return asyncIterable; - } - if (firstEvent.value?.[initialResponseMarker]) { - if (!responseSchema) { - throw new Error("@smithy::core/protocols - initial-response event encountered in event stream but no response schema given."); - } - for (const [key, value] of Object.entries(firstEvent.value)) { - initialResponseContainer[key] = value; - } - } - return { - async *[Symbol.asyncIterator]() { - if (!firstEvent?.value?.[initialResponseMarker]) { - yield firstEvent.value; - } - while (true) { - const { done, value } = await asyncIterator.next(); - if (done) { - break; - } - yield value; - } - } - }; - } - writeEventBody(unionMember, unionSchema, event) { - const serializer = this.serializer; - let eventType = unionMember; - let explicitPayloadMember = null; - let explicitPayloadContentType; - const isKnownSchema = (() => { - const struct2 = unionSchema.getSchema(); - return struct2[4].includes(unionMember); - })(); - const additionalHeaders = {}; - if (!isKnownSchema) { - const [type, value] = event[unionMember]; - eventType = type; - serializer.write(15, value); - } else { - const eventSchema = unionSchema.getMemberSchema(unionMember); - if (eventSchema.isStructSchema()) { - for (const [memberName, memberSchema] of eventSchema.structIterator()) { - const { eventHeader, eventPayload } = memberSchema.getMergedTraits(); - if (eventPayload) { - explicitPayloadMember = memberName; - } else if (eventHeader) { - const value = event[unionMember][memberName]; - let type = "binary"; - if (memberSchema.isNumericSchema()) { - if ((-2) ** 31 <= value && value <= 2 ** 31 - 1) { - type = "integer"; - } else { - type = "long"; - } - } else if (memberSchema.isTimestampSchema()) { - type = "timestamp"; - } else if (memberSchema.isStringSchema()) { - type = "string"; - } else if (memberSchema.isBooleanSchema()) { - type = "boolean"; - } - if (value != null) { - additionalHeaders[memberName] = { - type, - value - }; - delete event[unionMember][memberName]; - } - } - } - if (explicitPayloadMember !== null) { - const payloadSchema = eventSchema.getMemberSchema(explicitPayloadMember); - if (payloadSchema.isBlobSchema()) { - explicitPayloadContentType = "application/octet-stream"; - } else if (payloadSchema.isStringSchema()) { - explicitPayloadContentType = "text/plain"; - } - serializer.write(payloadSchema, event[unionMember][explicitPayloadMember]); - } else { - serializer.write(eventSchema, event[unionMember]); - } - } else if (eventSchema.isUnitSchema()) { - serializer.write(eventSchema, {}); - } else { - throw new Error("@smithy/core/event-streams - non-struct member not supported in event stream union."); - } - } - const messageSerialization = serializer.flush() ?? new Uint8Array(); - const body = typeof messageSerialization === "string" ? (this.serdeContext?.utf8Decoder ?? import_util_utf8.fromUtf8)(messageSerialization) : messageSerialization; - return { - body, - eventType, - explicitPayloadContentType, - additionalHeaders - }; - } - }; - } -}); - -// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/event-streams/index.js -var event_streams_exports = {}; -__export(event_streams_exports, { - EventStreamSerde: () => EventStreamSerde -}); -var init_event_streams = __esm({ - "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/event-streams/index.js"() { - init_EventStreamSerde(); - } -}); - -// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/protocols/HttpProtocol.js -var import_protocol_http2, HttpProtocol; -var init_HttpProtocol = __esm({ - "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/protocols/HttpProtocol.js"() { - init_schema3(); - import_protocol_http2 = __toESM(require_dist_cjs2()); - init_SerdeContext(); - HttpProtocol = class extends SerdeContext { - options; - compositeErrorRegistry; - constructor(options) { - super(); - this.options = options; - this.compositeErrorRegistry = TypeRegistry.for(options.defaultNamespace); - for (const etr of options.errorTypeRegistries ?? []) { - this.compositeErrorRegistry.copyFrom(etr); - } - } - getRequestType() { - return import_protocol_http2.HttpRequest; - } - getResponseType() { - return import_protocol_http2.HttpResponse; - } - setSerdeContext(serdeContext) { - this.serdeContext = serdeContext; - this.serializer.setSerdeContext(serdeContext); - this.deserializer.setSerdeContext(serdeContext); - if (this.getPayloadCodec()) { - this.getPayloadCodec().setSerdeContext(serdeContext); - } - } - updateServiceEndpoint(request, endpoint) { - if ("url" in endpoint) { - request.protocol = endpoint.url.protocol; - request.hostname = endpoint.url.hostname; - request.port = endpoint.url.port ? Number(endpoint.url.port) : void 0; - request.path = endpoint.url.pathname; - request.fragment = endpoint.url.hash || void 0; - request.username = endpoint.url.username || void 0; - request.password = endpoint.url.password || void 0; - if (!request.query) { - request.query = {}; - } - for (const [k5, v5] of endpoint.url.searchParams.entries()) { - request.query[k5] = v5; - } - if (endpoint.headers) { - for (const [name, values2] of Object.entries(endpoint.headers)) { - request.headers[name] = values2.join(", "); - } - } - return request; - } else { - request.protocol = endpoint.protocol; - request.hostname = endpoint.hostname; - request.port = endpoint.port ? Number(endpoint.port) : void 0; - request.path = endpoint.path; - request.query = { - ...endpoint.query - }; - if (endpoint.headers) { - for (const [name, value] of Object.entries(endpoint.headers)) { - request.headers[name] = value; - } - } - return request; - } - } - setHostPrefix(request, operationSchema, input) { - if (this.serdeContext?.disableHostPrefix) { - return; - } - const inputNs = NormalizedSchema.of(operationSchema.input); - const opTraits = translateTraits(operationSchema.traits ?? {}); - if (opTraits.endpoint) { - let hostPrefix = opTraits.endpoint?.[0]; - if (typeof hostPrefix === "string") { - const hostLabelInputs = [...inputNs.structIterator()].filter(([, member2]) => member2.getMergedTraits().hostLabel); - for (const [name] of hostLabelInputs) { - const replacement = input[name]; - if (typeof replacement !== "string") { - throw new Error(`@smithy/core/schema - ${name} in input must be a string as hostLabel.`); - } - hostPrefix = hostPrefix.replace(`{${name}}`, replacement); - } - request.hostname = hostPrefix + request.hostname; - } - } - } - deserializeMetadata(output) { - return { - httpStatusCode: output.statusCode, - requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"], - extendedRequestId: output.headers["x-amz-id-2"], - cfId: output.headers["x-amz-cf-id"] - }; - } - async serializeEventStream({ eventStream, requestSchema, initialRequest }) { - const eventStreamSerde = await this.loadEventStreamCapability(); - return eventStreamSerde.serializeEventStream({ - eventStream, - requestSchema, - initialRequest - }); - } - async deserializeEventStream({ response, responseSchema, initialResponseContainer }) { - const eventStreamSerde = await this.loadEventStreamCapability(); - return eventStreamSerde.deserializeEventStream({ - response, - responseSchema, - initialResponseContainer - }); - } - async loadEventStreamCapability() { - const { EventStreamSerde: EventStreamSerde2 } = await Promise.resolve().then(() => (init_event_streams(), event_streams_exports)); - return new EventStreamSerde2({ - marshaller: this.getEventStreamMarshaller(), - serializer: this.serializer, - deserializer: this.deserializer, - serdeContext: this.serdeContext, - defaultContentType: this.getDefaultContentType() - }); - } - getDefaultContentType() { - throw new Error(`@smithy/core/protocols - ${this.constructor.name} getDefaultContentType() implementation missing.`); - } - async deserializeHttpMessage(schema2, context, response, arg4, arg5) { - void schema2; - void context; - void response; - void arg4; - void arg5; - return []; - } - getEventStreamMarshaller() { - const context = this.serdeContext; - if (!context.eventStreamMarshaller) { - throw new Error("@smithy/core - HttpProtocol: eventStreamMarshaller missing in serdeContext."); - } - return context.eventStreamMarshaller; - } - }; - } -}); - -// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/protocols/HttpBindingProtocol.js -var import_protocol_http3, import_util_stream2, HttpBindingProtocol; -var init_HttpBindingProtocol = __esm({ - "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/protocols/HttpBindingProtocol.js"() { - init_schema3(); - init_serde(); - import_protocol_http3 = __toESM(require_dist_cjs2()); - import_util_stream2 = __toESM(require_dist_cjs13()); - init_collect_stream_body(); - init_extended_encode_uri_component(); - init_HttpProtocol(); - HttpBindingProtocol = class extends HttpProtocol { - async serializeRequest(operationSchema, _input, context) { - const input = _input && typeof _input === "object" ? _input : {}; - const serializer = this.serializer; - const query = {}; - const headers = {}; - const endpoint = await context.endpoint(); - const ns = NormalizedSchema.of(operationSchema?.input); - const payloadMemberNames = []; - const payloadMemberSchemas = []; - let hasNonHttpBindingMember = false; - let payload2; - const request = new import_protocol_http3.HttpRequest({ - protocol: "", - hostname: "", - port: void 0, - path: "", - fragment: void 0, - query, - headers, - body: void 0 - }); - if (endpoint) { - this.updateServiceEndpoint(request, endpoint); - this.setHostPrefix(request, operationSchema, input); - const opTraits = translateTraits(operationSchema.traits); - if (opTraits.http) { - request.method = opTraits.http[0]; - const [path53, search] = opTraits.http[1].split("?"); - if (request.path == "/") { - request.path = path53; - } else { - request.path += path53; - } - const traitSearchParams = new URLSearchParams(search ?? ""); - Object.assign(query, Object.fromEntries(traitSearchParams)); - } - } - for (const [memberName, memberNs] of ns.structIterator()) { - const memberTraits = memberNs.getMergedTraits() ?? {}; - const inputMemberValue = input[memberName]; - if (inputMemberValue == null && !memberNs.isIdempotencyToken()) { - if (memberTraits.httpLabel) { - if (request.path.includes(`{${memberName}+}`) || request.path.includes(`{${memberName}}`)) { - throw new Error(`No value provided for input HTTP label: ${memberName}.`); - } - } - continue; - } - if (memberTraits.httpPayload) { - const isStreaming = memberNs.isStreaming(); - if (isStreaming) { - const isEventStream = memberNs.isStructSchema(); - if (isEventStream) { - if (input[memberName]) { - payload2 = await this.serializeEventStream({ - eventStream: input[memberName], - requestSchema: ns - }); - } - } else { - payload2 = inputMemberValue; - } - } else { - serializer.write(memberNs, inputMemberValue); - payload2 = serializer.flush(); - } - } else if (memberTraits.httpLabel) { - serializer.write(memberNs, inputMemberValue); - const replacement = serializer.flush(); - if (request.path.includes(`{${memberName}+}`)) { - request.path = request.path.replace(`{${memberName}+}`, replacement.split("/").map(extendedEncodeURIComponent).join("/")); - } else if (request.path.includes(`{${memberName}}`)) { - request.path = request.path.replace(`{${memberName}}`, extendedEncodeURIComponent(replacement)); - } - } else if (memberTraits.httpHeader) { - serializer.write(memberNs, inputMemberValue); - headers[memberTraits.httpHeader.toLowerCase()] = String(serializer.flush()); - } else if (typeof memberTraits.httpPrefixHeaders === "string") { - for (const [key, val] of Object.entries(inputMemberValue)) { - const amalgam = memberTraits.httpPrefixHeaders + key; - serializer.write([memberNs.getValueSchema(), { httpHeader: amalgam }], val); - headers[amalgam.toLowerCase()] = serializer.flush(); - } - } else if (memberTraits.httpQuery || memberTraits.httpQueryParams) { - this.serializeQuery(memberNs, inputMemberValue, query); - } else { - hasNonHttpBindingMember = true; - payloadMemberNames.push(memberName); - payloadMemberSchemas.push(memberNs); - } - } - if (hasNonHttpBindingMember && input) { - const [namespace, name] = (ns.getName(true) ?? "#Unknown").split("#"); - const requiredMembers = ns.getSchema()[6]; - const payloadSchema = [ - 3, - namespace, - name, - ns.getMergedTraits(), - payloadMemberNames, - payloadMemberSchemas, - void 0 - ]; - if (requiredMembers) { - payloadSchema[6] = requiredMembers; - } else { - payloadSchema.pop(); - } - serializer.write(payloadSchema, input); - payload2 = serializer.flush(); - } - request.headers = headers; - request.query = query; - request.body = payload2; - return request; - } - serializeQuery(ns, data2, query) { - const serializer = this.serializer; - const traits = ns.getMergedTraits(); - if (traits.httpQueryParams) { - for (const [key, val] of Object.entries(data2)) { - if (!(key in query)) { - const valueSchema = ns.getValueSchema(); - Object.assign(valueSchema.getMergedTraits(), { - ...traits, - httpQuery: key, - httpQueryParams: void 0 - }); - this.serializeQuery(valueSchema, val, query); - } - } - return; - } - if (ns.isListSchema()) { - const sparse = !!ns.getMergedTraits().sparse; - const buffer2 = []; - for (const item of data2) { - serializer.write([ns.getValueSchema(), traits], item); - const serializable = serializer.flush(); - if (sparse || serializable !== void 0) { - buffer2.push(serializable); - } - } - query[traits.httpQuery] = buffer2; - } else { - serializer.write([ns, traits], data2); - query[traits.httpQuery] = serializer.flush(); - } - } - async deserializeResponse(operationSchema, context, response) { - const deserializer = this.deserializer; - const ns = NormalizedSchema.of(operationSchema.output); - const dataObject = {}; - if (response.statusCode >= 300) { - const bytes = await collectBody(response.body, context); - if (bytes.byteLength > 0) { - Object.assign(dataObject, await deserializer.read(15, bytes)); - } - await this.handleError(operationSchema, context, response, dataObject, this.deserializeMetadata(response)); - throw new Error("@smithy/core/protocols - HTTP Protocol error handler failed to throw."); - } - for (const header in response.headers) { - const value = response.headers[header]; - delete response.headers[header]; - response.headers[header.toLowerCase()] = value; - } - const nonHttpBindingMembers = await this.deserializeHttpMessage(ns, context, response, dataObject); - if (nonHttpBindingMembers.length) { - const bytes = await collectBody(response.body, context); - if (bytes.byteLength > 0) { - const dataFromBody = await deserializer.read(ns, bytes); - for (const member2 of nonHttpBindingMembers) { - if (dataFromBody[member2] != null) { - dataObject[member2] = dataFromBody[member2]; - } - } - } - } else if (nonHttpBindingMembers.discardResponseBody) { - await collectBody(response.body, context); - } - dataObject.$metadata = this.deserializeMetadata(response); - return dataObject; - } - async deserializeHttpMessage(schema2, context, response, arg4, arg5) { - let dataObject; - if (arg4 instanceof Set) { - dataObject = arg5; - } else { - dataObject = arg4; - } - let discardResponseBody = true; - const deserializer = this.deserializer; - const ns = NormalizedSchema.of(schema2); - const nonHttpBindingMembers = []; - for (const [memberName, memberSchema] of ns.structIterator()) { - const memberTraits = memberSchema.getMemberTraits(); - if (memberTraits.httpPayload) { - discardResponseBody = false; - const isStreaming = memberSchema.isStreaming(); - if (isStreaming) { - const isEventStream = memberSchema.isStructSchema(); - if (isEventStream) { - dataObject[memberName] = await this.deserializeEventStream({ - response, - responseSchema: ns - }); - } else { - dataObject[memberName] = (0, import_util_stream2.sdkStreamMixin)(response.body); - } - } else if (response.body) { - const bytes = await collectBody(response.body, context); - if (bytes.byteLength > 0) { - dataObject[memberName] = await deserializer.read(memberSchema, bytes); - } - } - } else if (memberTraits.httpHeader) { - const key = String(memberTraits.httpHeader).toLowerCase(); - const value = response.headers[key]; - if (null != value) { - if (memberSchema.isListSchema()) { - const headerListValueSchema = memberSchema.getValueSchema(); - headerListValueSchema.getMergedTraits().httpHeader = key; - let sections; - if (headerListValueSchema.isTimestampSchema() && headerListValueSchema.getSchema() === 4) { - sections = splitEvery(value, ",", 2); - } else { - sections = splitHeader(value); - } - const list2 = []; - for (const section of sections) { - list2.push(await deserializer.read(headerListValueSchema, section.trim())); - } - dataObject[memberName] = list2; - } else { - dataObject[memberName] = await deserializer.read(memberSchema, value); - } - } - } else if (memberTraits.httpPrefixHeaders !== void 0) { - dataObject[memberName] = {}; - for (const [header, value] of Object.entries(response.headers)) { - if (header.startsWith(memberTraits.httpPrefixHeaders)) { - const valueSchema = memberSchema.getValueSchema(); - valueSchema.getMergedTraits().httpHeader = header; - dataObject[memberName][header.slice(memberTraits.httpPrefixHeaders.length)] = await deserializer.read(valueSchema, value); - } - } - } else if (memberTraits.httpResponseCode) { - dataObject[memberName] = response.statusCode; - } else { - nonHttpBindingMembers.push(memberName); - } - } - nonHttpBindingMembers.discardResponseBody = discardResponseBody; - return nonHttpBindingMembers; - } - }; - } -}); - -// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/protocols/RpcProtocol.js -var import_protocol_http4, RpcProtocol; -var init_RpcProtocol = __esm({ - "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/protocols/RpcProtocol.js"() { - init_schema3(); - import_protocol_http4 = __toESM(require_dist_cjs2()); - init_collect_stream_body(); - init_HttpProtocol(); - RpcProtocol = class extends HttpProtocol { - async serializeRequest(operationSchema, _input, context) { - const serializer = this.serializer; - const query = {}; - const headers = {}; - const endpoint = await context.endpoint(); - const ns = NormalizedSchema.of(operationSchema?.input); - const schema2 = ns.getSchema(); - let payload2; - const input = _input && typeof _input === "object" ? _input : {}; - const request = new import_protocol_http4.HttpRequest({ - protocol: "", - hostname: "", - port: void 0, - path: "/", - fragment: void 0, - query, - headers, - body: void 0 - }); - if (endpoint) { - this.updateServiceEndpoint(request, endpoint); - this.setHostPrefix(request, operationSchema, input); - } - if (input) { - const eventStreamMember = ns.getEventStreamMember(); - if (eventStreamMember) { - if (input[eventStreamMember]) { - const initialRequest = {}; - for (const [memberName, memberSchema] of ns.structIterator()) { - if (memberName !== eventStreamMember && input[memberName]) { - serializer.write(memberSchema, input[memberName]); - initialRequest[memberName] = serializer.flush(); - } - } - payload2 = await this.serializeEventStream({ - eventStream: input[eventStreamMember], - requestSchema: ns, - initialRequest - }); - } - } else { - serializer.write(schema2, input); - payload2 = serializer.flush(); - } - } - request.headers = Object.assign(request.headers, headers); - request.query = query; - request.body = payload2; - request.method = "POST"; - return request; - } - async deserializeResponse(operationSchema, context, response) { - const deserializer = this.deserializer; - const ns = NormalizedSchema.of(operationSchema.output); - const dataObject = {}; - if (response.statusCode >= 300) { - const bytes = await collectBody(response.body, context); - if (bytes.byteLength > 0) { - Object.assign(dataObject, await deserializer.read(15, bytes)); - } - await this.handleError(operationSchema, context, response, dataObject, this.deserializeMetadata(response)); - throw new Error("@smithy/core/protocols - RPC Protocol error handler failed to throw."); - } - for (const header in response.headers) { - const value = response.headers[header]; - delete response.headers[header]; - response.headers[header.toLowerCase()] = value; - } - const eventStreamMember = ns.getEventStreamMember(); - if (eventStreamMember) { - dataObject[eventStreamMember] = await this.deserializeEventStream({ - response, - responseSchema: ns, - initialResponseContainer: dataObject - }); - } else { - const bytes = await collectBody(response.body, context); - if (bytes.byteLength > 0) { - Object.assign(dataObject, await deserializer.read(ns, bytes)); - } - } - dataObject.$metadata = this.deserializeMetadata(response); - return dataObject; - } - }; - } -}); - -// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/protocols/resolve-path.js -var resolvedPath; -var init_resolve_path = __esm({ - "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/protocols/resolve-path.js"() { - init_extended_encode_uri_component(); - resolvedPath = (resolvedPath2, input, memberName, labelValueProvider, uriLabel, isGreedyLabel) => { - if (input != null && input[memberName] !== void 0) { - const labelValue = labelValueProvider(); - if (labelValue == null || labelValue.length <= 0) { - throw new Error("Empty value provided for input HTTP label: " + memberName + "."); - } - resolvedPath2 = resolvedPath2.replace(uriLabel, isGreedyLabel ? labelValue.split("/").map((segment) => extendedEncodeURIComponent(segment)).join("/") : extendedEncodeURIComponent(labelValue)); - } else { - throw new Error("No value provided for input HTTP label: " + memberName + "."); - } - return resolvedPath2; - }; - } -}); - -// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/protocols/requestBuilder.js -function requestBuilder(input, context) { - return new RequestBuilder(input, context); -} -var import_protocol_http5, RequestBuilder; -var init_requestBuilder = __esm({ - "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/protocols/requestBuilder.js"() { - import_protocol_http5 = __toESM(require_dist_cjs2()); - init_resolve_path(); - RequestBuilder = class { - input; - context; - query = {}; - method = ""; - headers = {}; - path = ""; - body = null; - hostname = ""; - resolvePathStack = []; - constructor(input, context) { - this.input = input; - this.context = context; - } - async build() { - const { hostname: hostname3, protocol = "https", port, path: basePath } = await this.context.endpoint(); - this.path = basePath; - for (const resolvePath of this.resolvePathStack) { - resolvePath(this.path); - } - return new import_protocol_http5.HttpRequest({ - protocol, - hostname: this.hostname || hostname3, - port, - method: this.method, - path: this.path, - query: this.query, - body: this.body, - headers: this.headers - }); - } - hn(hostname3) { - this.hostname = hostname3; - return this; - } - bp(uriLabel) { - this.resolvePathStack.push((basePath) => { - this.path = `${basePath?.endsWith("/") ? basePath.slice(0, -1) : basePath || ""}` + uriLabel; - }); - return this; - } - p(memberName, labelValueProvider, uriLabel, isGreedyLabel) { - this.resolvePathStack.push((path53) => { - this.path = resolvedPath(path53, this.input, memberName, labelValueProvider, uriLabel, isGreedyLabel); - }); - return this; - } - h(headers) { - this.headers = headers; - return this; - } - q(query) { - this.query = query; - return this; - } - b(body) { - this.body = body; - return this; - } - m(method) { - this.method = method; - return this; - } - }; - } -}); - -// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/protocols/serde/determineTimestampFormat.js -function determineTimestampFormat(ns, settings) { - if (settings.timestampFormat.useTrait) { - if (ns.isTimestampSchema() && (ns.getSchema() === 5 || ns.getSchema() === 6 || ns.getSchema() === 7)) { - return ns.getSchema(); - } - } - const { httpLabel, httpPrefixHeaders, httpHeader, httpQuery } = ns.getMergedTraits(); - const bindingFormat = settings.httpBindings ? typeof httpPrefixHeaders === "string" || Boolean(httpHeader) ? 6 : Boolean(httpQuery) || Boolean(httpLabel) ? 5 : void 0 : void 0; - return bindingFormat ?? settings.timestampFormat.default; -} -var init_determineTimestampFormat = __esm({ - "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/protocols/serde/determineTimestampFormat.js"() { - } -}); - -// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/protocols/serde/FromStringShapeDeserializer.js -var import_util_base64, import_util_utf82, FromStringShapeDeserializer; -var init_FromStringShapeDeserializer = __esm({ - "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/protocols/serde/FromStringShapeDeserializer.js"() { - init_schema3(); - init_serde(); - import_util_base64 = __toESM(require_dist_cjs7()); - import_util_utf82 = __toESM(require_dist_cjs6()); - init_SerdeContext(); - init_determineTimestampFormat(); - FromStringShapeDeserializer = class extends SerdeContext { - settings; - constructor(settings) { - super(); - this.settings = settings; - } - read(_schema, data2) { - const ns = NormalizedSchema.of(_schema); - if (ns.isListSchema()) { - return splitHeader(data2).map((item) => this.read(ns.getValueSchema(), item)); - } - if (ns.isBlobSchema()) { - return (this.serdeContext?.base64Decoder ?? import_util_base64.fromBase64)(data2); - } - if (ns.isTimestampSchema()) { - const format2 = determineTimestampFormat(ns, this.settings); - switch (format2) { - case 5: - return _parseRfc3339DateTimeWithOffset(data2); - case 6: - return _parseRfc7231DateTime(data2); - case 7: - return _parseEpochTimestamp(data2); - default: - console.warn("Missing timestamp format, parsing value with Date constructor:", data2); - return new Date(data2); - } - } - if (ns.isStringSchema()) { - const mediaType = ns.getMergedTraits().mediaType; - let intermediateValue = data2; - if (mediaType) { - if (ns.getMergedTraits().httpHeader) { - intermediateValue = this.base64ToUtf8(intermediateValue); - } - const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); - if (isJson) { - intermediateValue = LazyJsonString.from(intermediateValue); - } - return intermediateValue; - } - } - if (ns.isNumericSchema()) { - return Number(data2); - } - if (ns.isBigIntegerSchema()) { - return BigInt(data2); - } - if (ns.isBigDecimalSchema()) { - return new NumericValue(data2, "bigDecimal"); - } - if (ns.isBooleanSchema()) { - return String(data2).toLowerCase() === "true"; - } - return data2; - } - base64ToUtf8(base64String) { - return (this.serdeContext?.utf8Encoder ?? import_util_utf82.toUtf8)((this.serdeContext?.base64Decoder ?? import_util_base64.fromBase64)(base64String)); - } - }; - } -}); - -// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/protocols/serde/HttpInterceptingShapeDeserializer.js -var import_util_utf83, HttpInterceptingShapeDeserializer; -var init_HttpInterceptingShapeDeserializer = __esm({ - "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/protocols/serde/HttpInterceptingShapeDeserializer.js"() { - init_schema3(); - import_util_utf83 = __toESM(require_dist_cjs6()); - init_SerdeContext(); - init_FromStringShapeDeserializer(); - HttpInterceptingShapeDeserializer = class extends SerdeContext { - codecDeserializer; - stringDeserializer; - constructor(codecDeserializer, codecSettings) { - super(); - this.codecDeserializer = codecDeserializer; - this.stringDeserializer = new FromStringShapeDeserializer(codecSettings); - } - setSerdeContext(serdeContext) { - this.stringDeserializer.setSerdeContext(serdeContext); - this.codecDeserializer.setSerdeContext(serdeContext); - this.serdeContext = serdeContext; - } - read(schema2, data2) { - const ns = NormalizedSchema.of(schema2); - const traits = ns.getMergedTraits(); - const toString = this.serdeContext?.utf8Encoder ?? import_util_utf83.toUtf8; - if (traits.httpHeader || traits.httpResponseCode) { - return this.stringDeserializer.read(ns, toString(data2)); - } - if (traits.httpPayload) { - if (ns.isBlobSchema()) { - const toBytes = this.serdeContext?.utf8Decoder ?? import_util_utf83.fromUtf8; - if (typeof data2 === "string") { - return toBytes(data2); - } - return data2; - } else if (ns.isStringSchema()) { - if ("byteLength" in data2) { - return toString(data2); - } - return data2; - } - } - return this.codecDeserializer.read(ns, data2); - } - }; - } -}); - -// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/protocols/serde/ToStringShapeSerializer.js -var import_util_base642, ToStringShapeSerializer; -var init_ToStringShapeSerializer = __esm({ - "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/protocols/serde/ToStringShapeSerializer.js"() { - init_schema3(); - init_serde(); - import_util_base642 = __toESM(require_dist_cjs7()); - init_SerdeContext(); - init_determineTimestampFormat(); - ToStringShapeSerializer = class extends SerdeContext { - settings; - stringBuffer = ""; - constructor(settings) { - super(); - this.settings = settings; - } - write(schema2, value) { - const ns = NormalizedSchema.of(schema2); - switch (typeof value) { - case "object": - if (value === null) { - this.stringBuffer = "null"; - return; - } - if (ns.isTimestampSchema()) { - if (!(value instanceof Date)) { - throw new Error(`@smithy/core/protocols - received non-Date value ${value} when schema expected Date in ${ns.getName(true)}`); - } - const format2 = determineTimestampFormat(ns, this.settings); - switch (format2) { - case 5: - this.stringBuffer = value.toISOString().replace(".000Z", "Z"); - break; - case 6: - this.stringBuffer = dateToUtcString(value); - break; - case 7: - this.stringBuffer = String(value.getTime() / 1e3); - break; - default: - console.warn("Missing timestamp format, using epoch seconds", value); - this.stringBuffer = String(value.getTime() / 1e3); - } - return; - } - if (ns.isBlobSchema() && "byteLength" in value) { - this.stringBuffer = (this.serdeContext?.base64Encoder ?? import_util_base642.toBase64)(value); - return; - } - if (ns.isListSchema() && Array.isArray(value)) { - let buffer2 = ""; - for (const item of value) { - this.write([ns.getValueSchema(), ns.getMergedTraits()], item); - const headerItem = this.flush(); - const serialized = ns.getValueSchema().isTimestampSchema() ? headerItem : quoteHeader(headerItem); - if (buffer2 !== "") { - buffer2 += ", "; - } - buffer2 += serialized; - } - this.stringBuffer = buffer2; - return; - } - this.stringBuffer = JSON.stringify(value, null, 2); - break; - case "string": - const mediaType = ns.getMergedTraits().mediaType; - let intermediateValue = value; - if (mediaType) { - const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); - if (isJson) { - intermediateValue = LazyJsonString.from(intermediateValue); - } - if (ns.getMergedTraits().httpHeader) { - this.stringBuffer = (this.serdeContext?.base64Encoder ?? import_util_base642.toBase64)(intermediateValue.toString()); - return; - } - } - this.stringBuffer = value; - break; - default: - if (ns.isIdempotencyToken()) { - this.stringBuffer = (0, import_uuid2.v4)(); - } else { - this.stringBuffer = String(value); - } - } - } - flush() { - const buffer2 = this.stringBuffer; - this.stringBuffer = ""; - return buffer2; - } - }; - } -}); - -// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/protocols/serde/HttpInterceptingShapeSerializer.js -var HttpInterceptingShapeSerializer; -var init_HttpInterceptingShapeSerializer = __esm({ - "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/protocols/serde/HttpInterceptingShapeSerializer.js"() { - init_schema3(); - init_ToStringShapeSerializer(); - HttpInterceptingShapeSerializer = class { - codecSerializer; - stringSerializer; - buffer; - constructor(codecSerializer, codecSettings, stringSerializer = new ToStringShapeSerializer(codecSettings)) { - this.codecSerializer = codecSerializer; - this.stringSerializer = stringSerializer; - } - setSerdeContext(serdeContext) { - this.codecSerializer.setSerdeContext(serdeContext); - this.stringSerializer.setSerdeContext(serdeContext); - } - write(schema2, value) { - const ns = NormalizedSchema.of(schema2); - const traits = ns.getMergedTraits(); - if (traits.httpHeader || traits.httpLabel || traits.httpQuery) { - this.stringSerializer.write(ns, value); - this.buffer = this.stringSerializer.flush(); - return; - } - return this.codecSerializer.write(ns, value); - } - flush() { - if (this.buffer !== void 0) { - const buffer2 = this.buffer; - this.buffer = void 0; - return buffer2; - } - return this.codecSerializer.flush(); - } - }; - } -}); - -// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/protocols/index.js -var protocols_exports = {}; -__export(protocols_exports, { - FromStringShapeDeserializer: () => FromStringShapeDeserializer, - HttpBindingProtocol: () => HttpBindingProtocol, - HttpInterceptingShapeDeserializer: () => HttpInterceptingShapeDeserializer, - HttpInterceptingShapeSerializer: () => HttpInterceptingShapeSerializer, - HttpProtocol: () => HttpProtocol, - RequestBuilder: () => RequestBuilder, - RpcProtocol: () => RpcProtocol, - SerdeContext: () => SerdeContext, - ToStringShapeSerializer: () => ToStringShapeSerializer, - collectBody: () => collectBody, - determineTimestampFormat: () => determineTimestampFormat, - extendedEncodeURIComponent: () => extendedEncodeURIComponent, - requestBuilder: () => requestBuilder, - resolvedPath: () => resolvedPath -}); -var init_protocols = __esm({ - "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/protocols/index.js"() { - init_collect_stream_body(); - init_extended_encode_uri_component(); - init_HttpBindingProtocol(); - init_HttpProtocol(); - init_RpcProtocol(); - init_requestBuilder(); - init_resolve_path(); - init_FromStringShapeDeserializer(); - init_HttpInterceptingShapeDeserializer(); - init_HttpInterceptingShapeSerializer(); - init_ToStringShapeSerializer(); - init_determineTimestampFormat(); - init_SerdeContext(); - } -}); - -// node_modules/.pnpm/@smithy+smithy-client@4.12.9/node_modules/@smithy/smithy-client/dist-cjs/index.js -var require_dist_cjs27 = __commonJS({ - "node_modules/.pnpm/@smithy+smithy-client@4.12.9/node_modules/@smithy/smithy-client/dist-cjs/index.js"(exports) { - "use strict"; - var middlewareStack = require_dist_cjs23(); - var types2 = require_dist_cjs(); - var schema2 = (init_schema3(), __toCommonJS(schema_exports2)); - var serde = (init_serde(), __toCommonJS(serde_exports)); - var protocols = (init_protocols(), __toCommonJS(protocols_exports)); - var Client = class { - config; - middlewareStack = middlewareStack.constructStack(); - initConfig; - handlers; - constructor(config3) { - this.config = config3; - const { protocol, protocolSettings } = config3; - if (protocolSettings) { - if (typeof protocol === "function") { - config3.protocol = new protocol(protocolSettings); - } - } - } - send(command, optionsOrCb, cb) { - const options = typeof optionsOrCb !== "function" ? optionsOrCb : void 0; - const callback = typeof optionsOrCb === "function" ? optionsOrCb : cb; - const useHandlerCache = options === void 0 && this.config.cacheMiddleware === true; - let handler; - if (useHandlerCache) { - if (!this.handlers) { - this.handlers = /* @__PURE__ */ new WeakMap(); - } - const handlers = this.handlers; - if (handlers.has(command.constructor)) { - handler = handlers.get(command.constructor); - } else { - handler = command.resolveMiddleware(this.middlewareStack, this.config, options); - handlers.set(command.constructor, handler); - } - } else { - delete this.handlers; - handler = command.resolveMiddleware(this.middlewareStack, this.config, options); - } - if (callback) { - handler(command).then((result) => callback(null, result.output), (err) => callback(err)).catch(() => { - }); - } else { - return handler(command).then((result) => result.output); - } - } - destroy() { - this.config?.requestHandler?.destroy?.(); - delete this.handlers; - } - }; - var SENSITIVE_STRING$1 = "***SensitiveInformation***"; - function schemaLogFilter(schema$1, data2) { - if (data2 == null) { - return data2; - } - const ns = schema2.NormalizedSchema.of(schema$1); - if (ns.getMergedTraits().sensitive) { - return SENSITIVE_STRING$1; - } - if (ns.isListSchema()) { - const isSensitive = !!ns.getValueSchema().getMergedTraits().sensitive; - if (isSensitive) { - return SENSITIVE_STRING$1; - } - } else if (ns.isMapSchema()) { - const isSensitive = !!ns.getKeySchema().getMergedTraits().sensitive || !!ns.getValueSchema().getMergedTraits().sensitive; - if (isSensitive) { - return SENSITIVE_STRING$1; - } - } else if (ns.isStructSchema() && typeof data2 === "object") { - const object2 = data2; - const newObject = {}; - for (const [member2, memberNs] of ns.structIterator()) { - if (object2[member2] != null) { - newObject[member2] = schemaLogFilter(memberNs, object2[member2]); - } - } - return newObject; - } - return data2; - } - var Command2 = class { - middlewareStack = middlewareStack.constructStack(); - schema; - static classBuilder() { - return new ClassBuilder(); - } - resolveMiddlewareWithContext(clientStack, configuration, options, { middlewareFn, clientName, commandName, inputFilterSensitiveLog, outputFilterSensitiveLog, smithyContext, additionalContext, CommandCtor }) { - for (const mw of middlewareFn.bind(this)(CommandCtor, clientStack, configuration, options)) { - this.middlewareStack.use(mw); - } - const stack = clientStack.concat(this.middlewareStack); - const { logger: logger4 } = configuration; - const handlerExecutionContext = { - logger: logger4, - clientName, - commandName, - inputFilterSensitiveLog, - outputFilterSensitiveLog, - [types2.SMITHY_CONTEXT_KEY]: { - commandInstance: this, - ...smithyContext - }, - ...additionalContext - }; - const { requestHandler } = configuration; - return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); - } - }; - var ClassBuilder = class { - _init = () => { - }; - _ep = {}; - _middlewareFn = () => []; - _commandName = ""; - _clientName = ""; - _additionalContext = {}; - _smithyContext = {}; - _inputFilterSensitiveLog = void 0; - _outputFilterSensitiveLog = void 0; - _serializer = null; - _deserializer = null; - _operationSchema; - init(cb) { - this._init = cb; - } - ep(endpointParameterInstructions) { - this._ep = endpointParameterInstructions; - return this; - } - m(middlewareSupplier) { - this._middlewareFn = middlewareSupplier; - return this; - } - s(service, operation2, smithyContext = {}) { - this._smithyContext = { - service, - operation: operation2, - ...smithyContext - }; - return this; - } - c(additionalContext = {}) { - this._additionalContext = additionalContext; - return this; - } - n(clientName, commandName) { - this._clientName = clientName; - this._commandName = commandName; - return this; - } - f(inputFilter = (_) => _, outputFilter = (_) => _) { - this._inputFilterSensitiveLog = inputFilter; - this._outputFilterSensitiveLog = outputFilter; - return this; - } - ser(serializer) { - this._serializer = serializer; - return this; - } - de(deserializer) { - this._deserializer = deserializer; - return this; - } - sc(operation2) { - this._operationSchema = operation2; - this._smithyContext.operationSchema = operation2; - return this; - } - build() { - const closure = this; - let CommandRef; - return CommandRef = class extends Command2 { - input; - static getEndpointParameterInstructions() { - return closure._ep; - } - constructor(...[input]) { - super(); - this.input = input ?? {}; - closure._init(this); - this.schema = closure._operationSchema; - } - resolveMiddleware(stack, configuration, options) { - const op2 = closure._operationSchema; - const input = op2?.[4] ?? op2?.input; - const output = op2?.[5] ?? op2?.output; - return this.resolveMiddlewareWithContext(stack, configuration, options, { - CommandCtor: CommandRef, - middlewareFn: closure._middlewareFn, - clientName: closure._clientName, - commandName: closure._commandName, - inputFilterSensitiveLog: closure._inputFilterSensitiveLog ?? (op2 ? schemaLogFilter.bind(null, input) : (_) => _), - outputFilterSensitiveLog: closure._outputFilterSensitiveLog ?? (op2 ? schemaLogFilter.bind(null, output) : (_) => _), - smithyContext: closure._smithyContext, - additionalContext: closure._additionalContext - }); - } - serialize = closure._serializer; - deserialize = closure._deserializer; - }; - } - }; - var SENSITIVE_STRING = "***SensitiveInformation***"; - var createAggregatedClient5 = (commands5, Client2, options) => { - for (const [command, CommandCtor] of Object.entries(commands5)) { - const methodImpl = async function(args, optionsOrCb, cb) { - const command2 = new CommandCtor(args); - if (typeof optionsOrCb === "function") { - this.send(command2, optionsOrCb); - } else if (typeof cb === "function") { - if (typeof optionsOrCb !== "object") - throw new Error(`Expected http options but got ${typeof optionsOrCb}`); - this.send(command2, optionsOrCb || {}, cb); - } else { - return this.send(command2, optionsOrCb); - } - }; - const methodName = (command[0].toLowerCase() + command.slice(1)).replace(/Command$/, ""); - Client2.prototype[methodName] = methodImpl; - } - const { paginators = {}, waiters = {} } = options ?? {}; - for (const [paginatorName, paginatorFn] of Object.entries(paginators)) { - if (Client2.prototype[paginatorName] === void 0) { - Client2.prototype[paginatorName] = function(commandInput = {}, paginationConfiguration, ...rest) { - return paginatorFn({ - ...paginationConfiguration, - client: this - }, commandInput, ...rest); - }; - } - } - for (const [waiterName, waiterFn] of Object.entries(waiters)) { - if (Client2.prototype[waiterName] === void 0) { - Client2.prototype[waiterName] = async function(commandInput = {}, waiterConfiguration, ...rest) { - let config3 = waiterConfiguration; - if (typeof waiterConfiguration === "number") { - config3 = { - maxWaitTime: waiterConfiguration - }; - } - return waiterFn({ - ...config3, - client: this - }, commandInput, ...rest); - }; - } - } - }; - var ServiceException = class _ServiceException extends Error { - $fault; - $response; - $retryable; - $metadata; - constructor(options) { - super(options.message); - Object.setPrototypeOf(this, Object.getPrototypeOf(this).constructor.prototype); - this.name = options.name; - this.$fault = options.$fault; - this.$metadata = options.$metadata; - } - static isInstance(value) { - if (!value) - return false; - const candidate = value; - return _ServiceException.prototype.isPrototypeOf(candidate) || Boolean(candidate.$fault) && Boolean(candidate.$metadata) && (candidate.$fault === "client" || candidate.$fault === "server"); - } - static [Symbol.hasInstance](instance) { - if (!instance) - return false; - const candidate = instance; - if (this === _ServiceException) { - return _ServiceException.isInstance(instance); - } - if (_ServiceException.isInstance(instance)) { - if (candidate.name && this.name) { - return this.prototype.isPrototypeOf(instance) || candidate.name === this.name; - } - return this.prototype.isPrototypeOf(instance); - } - return false; - } - }; - var decorateServiceException2 = (exception, additions = {}) => { - Object.entries(additions).filter(([, v5]) => v5 !== void 0).forEach(([k5, v5]) => { - if (exception[k5] == void 0 || exception[k5] === "") { - exception[k5] = v5; - } - }); - const message2 = exception.message || exception.Message || "UnknownError"; - exception.message = message2; - delete exception.Message; - return exception; - }; - var throwDefaultError = ({ output, parsedBody, exceptionCtor, errorCode }) => { - const $metadata = deserializeMetadata(output); - const statusCode = $metadata.httpStatusCode ? $metadata.httpStatusCode + "" : void 0; - const response = new exceptionCtor({ - name: parsedBody?.code || parsedBody?.Code || errorCode || statusCode || "UnknownError", - $fault: "client", - $metadata - }); - throw decorateServiceException2(response, parsedBody); - }; - var withBaseException = (ExceptionCtor) => { - return ({ output, parsedBody, errorCode }) => { - throwDefaultError({ output, parsedBody, exceptionCtor: ExceptionCtor, errorCode }); - }; - }; - var deserializeMetadata = (output) => ({ - httpStatusCode: output.statusCode, - requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"], - extendedRequestId: output.headers["x-amz-id-2"], - cfId: output.headers["x-amz-cf-id"] - }); - var loadConfigsForDefaultMode5 = (mode) => { - switch (mode) { - case "standard": - return { - retryMode: "standard", - connectionTimeout: 3100 - }; - case "in-region": - return { - retryMode: "standard", - connectionTimeout: 1100 - }; - case "cross-region": - return { - retryMode: "standard", - connectionTimeout: 3100 - }; - case "mobile": - return { - retryMode: "standard", - connectionTimeout: 3e4 - }; - default: - return {}; - } - }; - var warningEmitted = false; - var emitWarningIfUnsupportedVersion6 = (version3) => { - if (version3 && !warningEmitted && parseInt(version3.substring(1, version3.indexOf("."))) < 16) { - warningEmitted = true; - } - }; - var knownAlgorithms = Object.values(types2.AlgorithmId); - var getChecksumConfiguration = (runtimeConfig) => { - const checksumAlgorithms = []; - for (const id in types2.AlgorithmId) { - const algorithmId = types2.AlgorithmId[id]; - if (runtimeConfig[algorithmId] === void 0) { - continue; - } - checksumAlgorithms.push({ - algorithmId: () => algorithmId, - checksumConstructor: () => runtimeConfig[algorithmId] - }); - } - for (const [id, ChecksumCtor] of Object.entries(runtimeConfig.checksumAlgorithms ?? {})) { - checksumAlgorithms.push({ - algorithmId: () => id, - checksumConstructor: () => ChecksumCtor - }); - } - return { - addChecksumAlgorithm(algo) { - runtimeConfig.checksumAlgorithms = runtimeConfig.checksumAlgorithms ?? {}; - const id = algo.algorithmId(); - const ctor = algo.checksumConstructor(); - if (knownAlgorithms.includes(id)) { - runtimeConfig.checksumAlgorithms[id.toUpperCase()] = ctor; - } else { - runtimeConfig.checksumAlgorithms[id] = ctor; - } - checksumAlgorithms.push(algo); - }, - checksumAlgorithms() { - return checksumAlgorithms; - } - }; - }; - var resolveChecksumRuntimeConfig = (clientConfig) => { - const runtimeConfig = {}; - clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { - const id = checksumAlgorithm.algorithmId(); - if (knownAlgorithms.includes(id)) { - runtimeConfig[id] = checksumAlgorithm.checksumConstructor(); - } - }); - return runtimeConfig; - }; - var getRetryConfiguration = (runtimeConfig) => { - return { - setRetryStrategy(retryStrategy) { - runtimeConfig.retryStrategy = retryStrategy; - }, - retryStrategy() { - return runtimeConfig.retryStrategy; - } - }; - }; - var resolveRetryRuntimeConfig = (retryStrategyConfiguration) => { - const runtimeConfig = {}; - runtimeConfig.retryStrategy = retryStrategyConfiguration.retryStrategy(); - return runtimeConfig; - }; - var getDefaultExtensionConfiguration5 = (runtimeConfig) => { - return Object.assign(getChecksumConfiguration(runtimeConfig), getRetryConfiguration(runtimeConfig)); - }; - var getDefaultClientConfiguration = getDefaultExtensionConfiguration5; - var resolveDefaultRuntimeConfig5 = (config3) => { - return Object.assign(resolveChecksumRuntimeConfig(config3), resolveRetryRuntimeConfig(config3)); - }; - var getArrayIfSingleItem = (mayBeArray) => Array.isArray(mayBeArray) ? mayBeArray : [mayBeArray]; - var getValueFromTextNode3 = (obj) => { - const textNodeName = "#text"; - for (const key in obj) { - if (obj.hasOwnProperty(key) && obj[key][textNodeName] !== void 0) { - obj[key] = obj[key][textNodeName]; - } else if (typeof obj[key] === "object" && obj[key] !== null) { - obj[key] = getValueFromTextNode3(obj[key]); - } - } - return obj; - }; - var isSerializableHeaderValue = (value) => { - return value != null; - }; - var NoOpLogger5 = class { - trace() { - } - debug() { - } - info() { - } - warn() { - } - error() { - } - }; - function map4(arg0, arg1, arg2) { - let target; - let filter; - let instructions; - if (typeof arg1 === "undefined" && typeof arg2 === "undefined") { - target = {}; - instructions = arg0; - } else { - target = arg0; - if (typeof arg1 === "function") { - filter = arg1; - instructions = arg2; - return mapWithFilter(target, filter, instructions); - } else { - instructions = arg1; - } - } - for (const key of Object.keys(instructions)) { - if (!Array.isArray(instructions[key])) { - target[key] = instructions[key]; - continue; - } - applyInstruction(target, null, instructions, key); - } - return target; - } - var convertMap = (target) => { - const output = {}; - for (const [k5, v5] of Object.entries(target || {})) { - output[k5] = [, v5]; - } - return output; - }; - var take = (source, instructions) => { - const out = {}; - for (const key in instructions) { - applyInstruction(out, source, instructions, key); - } - return out; - }; - var mapWithFilter = (target, filter, instructions) => { - return map4(target, Object.entries(instructions).reduce((_instructions, [key, value]) => { - if (Array.isArray(value)) { - _instructions[key] = value; - } else { - if (typeof value === "function") { - _instructions[key] = [filter, value()]; - } else { - _instructions[key] = [filter, value]; - } - } - return _instructions; - }, {})); - }; - var applyInstruction = (target, source, instructions, targetKey) => { - if (source !== null) { - let instruction = instructions[targetKey]; - if (typeof instruction === "function") { - instruction = [, instruction]; - } - const [filter2 = nonNullish, valueFn = pass, sourceKey = targetKey] = instruction; - if (typeof filter2 === "function" && filter2(source[sourceKey]) || typeof filter2 !== "function" && !!filter2) { - target[targetKey] = valueFn(source[sourceKey]); - } - return; - } - let [filter, value] = instructions[targetKey]; - if (typeof value === "function") { - let _value; - const defaultFilterPassed = filter === void 0 && (_value = value()) != null; - const customFilterPassed = typeof filter === "function" && !!filter(void 0) || typeof filter !== "function" && !!filter; - if (defaultFilterPassed) { - target[targetKey] = _value; - } else if (customFilterPassed) { - target[targetKey] = value(); - } - } else { - const defaultFilterPassed = filter === void 0 && value != null; - const customFilterPassed = typeof filter === "function" && !!filter(value) || typeof filter !== "function" && !!filter; - if (defaultFilterPassed || customFilterPassed) { - target[targetKey] = value; - } - } - }; - var nonNullish = (_) => _ != null; - var pass = (_) => _; - var serializeFloat = (value) => { - if (value !== value) { - return "NaN"; - } - switch (value) { - case Infinity: - return "Infinity"; - case -Infinity: - return "-Infinity"; - default: - return value; - } - }; - var serializeDateTime = (date7) => date7.toISOString().replace(".000Z", "Z"); - var _json = (obj) => { - if (obj == null) { - return {}; - } - if (Array.isArray(obj)) { - return obj.filter((_) => _ != null).map(_json); - } - if (typeof obj === "object") { - const target = {}; - for (const key of Object.keys(obj)) { - if (obj[key] == null) { - continue; - } - target[key] = _json(obj[key]); - } - return target; - } - return obj; - }; - exports.collectBody = protocols.collectBody; - exports.extendedEncodeURIComponent = protocols.extendedEncodeURIComponent; - exports.resolvedPath = protocols.resolvedPath; - exports.Client = Client; - exports.Command = Command2; - exports.NoOpLogger = NoOpLogger5; - exports.SENSITIVE_STRING = SENSITIVE_STRING; - exports.ServiceException = ServiceException; - exports._json = _json; - exports.convertMap = convertMap; - exports.createAggregatedClient = createAggregatedClient5; - exports.decorateServiceException = decorateServiceException2; - exports.emitWarningIfUnsupportedVersion = emitWarningIfUnsupportedVersion6; - exports.getArrayIfSingleItem = getArrayIfSingleItem; - exports.getDefaultClientConfiguration = getDefaultClientConfiguration; - exports.getDefaultExtensionConfiguration = getDefaultExtensionConfiguration5; - exports.getValueFromTextNode = getValueFromTextNode3; - exports.isSerializableHeaderValue = isSerializableHeaderValue; - exports.loadConfigsForDefaultMode = loadConfigsForDefaultMode5; - exports.map = map4; - exports.resolveDefaultRuntimeConfig = resolveDefaultRuntimeConfig5; - exports.serializeDateTime = serializeDateTime; - exports.serializeFloat = serializeFloat; - exports.take = take; - exports.throwDefaultError = throwDefaultError; - exports.withBaseException = withBaseException; - Object.prototype.hasOwnProperty.call(serde, "__proto__") && !Object.prototype.hasOwnProperty.call(exports, "__proto__") && Object.defineProperty(exports, "__proto__", { - enumerable: true, - value: serde["__proto__"] - }); - Object.keys(serde).forEach(function(k5) { - if (k5 !== "default" && !Object.prototype.hasOwnProperty.call(exports, k5)) exports[k5] = serde[k5]; - }); - } -}); - -// node_modules/.pnpm/@aws-sdk+util-arn-parser@3.972.3/node_modules/@aws-sdk/util-arn-parser/dist-cjs/index.js -var require_dist_cjs28 = __commonJS({ - "node_modules/.pnpm/@aws-sdk+util-arn-parser@3.972.3/node_modules/@aws-sdk/util-arn-parser/dist-cjs/index.js"(exports) { - "use strict"; - var validate2 = (str) => typeof str === "string" && str.indexOf("arn:") === 0 && str.split(":").length >= 6; - var parse5 = (arn) => { - const segments = arn.split(":"); - if (segments.length < 6 || segments[0] !== "arn") - throw new Error("Malformed ARN"); - const [, partition, service, region, accountId, ...resource] = segments; - return { - partition, - service, - region, - accountId, - resource: resource.join(":") - }; - }; - var build = (arnObject) => { - const { partition = "aws", service, region, accountId, resource } = arnObject; - if ([service, region, accountId, resource].some((segment) => typeof segment !== "string")) { - throw new Error("Input ARN object is invalid"); - } - return `arn:${partition}:${service}:${region}:${accountId}:${resource}`; - }; - exports.build = build; - exports.parse = parse5; - exports.validate = validate2; - } -}); - -// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/cbor/cbor-types.js -function alloc(size2) { - return typeof Buffer !== "undefined" ? Buffer.alloc(size2) : new Uint8Array(size2); -} -function tag(data2) { - data2[tagSymbol] = true; - return data2; -} -var majorUint64, majorNegativeInt64, majorUnstructuredByteString, majorUtf8String, majorList, majorMap, majorTag, majorSpecial, specialFalse, specialTrue, specialNull, specialUndefined, extendedOneByte, extendedFloat16, extendedFloat32, extendedFloat64, minorIndefinite, tagSymbol; -var init_cbor_types = __esm({ - "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/cbor/cbor-types.js"() { - majorUint64 = 0; - majorNegativeInt64 = 1; - majorUnstructuredByteString = 2; - majorUtf8String = 3; - majorList = 4; - majorMap = 5; - majorTag = 6; - majorSpecial = 7; - specialFalse = 20; - specialTrue = 21; - specialNull = 22; - specialUndefined = 23; - extendedOneByte = 24; - extendedFloat16 = 25; - extendedFloat32 = 26; - extendedFloat64 = 27; - minorIndefinite = 31; - tagSymbol = /* @__PURE__ */ Symbol("@smithy/core/cbor::tagSymbol"); - } -}); - -// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/cbor/cbor-decode.js -function setPayload(bytes) { - payload = bytes; - dataView = new DataView(payload.buffer, payload.byteOffset, payload.byteLength); -} -function decode(at, to) { - if (at >= to) { - throw new Error("unexpected end of (decode) payload."); - } - const major = (payload[at] & 224) >> 5; - const minor = payload[at] & 31; - switch (major) { - case majorUint64: - case majorNegativeInt64: - case majorTag: - let unsignedInt; - let offset; - if (minor < 24) { - unsignedInt = minor; - offset = 1; - } else { - switch (minor) { - case extendedOneByte: - case extendedFloat16: - case extendedFloat32: - case extendedFloat64: - const countLength = minorValueToArgumentLength[minor]; - const countOffset = countLength + 1; - offset = countOffset; - if (to - at < countOffset) { - throw new Error(`countLength ${countLength} greater than remaining buf len.`); - } - const countIndex = at + 1; - if (countLength === 1) { - unsignedInt = payload[countIndex]; - } else if (countLength === 2) { - unsignedInt = dataView.getUint16(countIndex); - } else if (countLength === 4) { - unsignedInt = dataView.getUint32(countIndex); - } else { - unsignedInt = dataView.getBigUint64(countIndex); - } - break; - default: - throw new Error(`unexpected minor value ${minor}.`); - } - } - if (major === majorUint64) { - _offset = offset; - return castBigInt(unsignedInt); - } else if (major === majorNegativeInt64) { - let negativeInt; - if (typeof unsignedInt === "bigint") { - negativeInt = BigInt(-1) - unsignedInt; - } else { - negativeInt = -1 - unsignedInt; - } - _offset = offset; - return castBigInt(negativeInt); - } else { - if (minor === 2 || minor === 3) { - const length = decodeCount(at + offset, to); - let b6 = BigInt(0); - const start = at + offset + _offset; - for (let i5 = start; i5 < start + length; ++i5) { - b6 = b6 << BigInt(8) | BigInt(payload[i5]); - } - _offset = offset + _offset + length; - return minor === 3 ? -b6 - BigInt(1) : b6; - } else if (minor === 4) { - const decimalFraction = decode(at + offset, to); - const [exponent, mantissa] = decimalFraction; - const normalizer = mantissa < 0 ? -1 : 1; - const mantissaStr = "0".repeat(Math.abs(exponent) + 1) + String(BigInt(normalizer) * BigInt(mantissa)); - let numericString; - const sign2 = mantissa < 0 ? "-" : ""; - numericString = exponent === 0 ? mantissaStr : mantissaStr.slice(0, mantissaStr.length + exponent) + "." + mantissaStr.slice(exponent); - numericString = numericString.replace(/^0+/g, ""); - if (numericString === "") { - numericString = "0"; - } - if (numericString[0] === ".") { - numericString = "0" + numericString; - } - numericString = sign2 + numericString; - _offset = offset + _offset; - return nv(numericString); - } else { - const value = decode(at + offset, to); - const valueOffset = _offset; - _offset = offset + valueOffset; - return tag({ tag: castBigInt(unsignedInt), value }); - } - } - case majorUtf8String: - case majorMap: - case majorList: - case majorUnstructuredByteString: - if (minor === minorIndefinite) { - switch (major) { - case majorUtf8String: - return decodeUtf8StringIndefinite(at, to); - case majorMap: - return decodeMapIndefinite(at, to); - case majorList: - return decodeListIndefinite(at, to); - case majorUnstructuredByteString: - return decodeUnstructuredByteStringIndefinite(at, to); - } - } else { - switch (major) { - case majorUtf8String: - return decodeUtf8String(at, to); - case majorMap: - return decodeMap(at, to); - case majorList: - return decodeList(at, to); - case majorUnstructuredByteString: - return decodeUnstructuredByteString(at, to); - } - } - default: - return decodeSpecial(at, to); - } -} -function bytesToUtf8(bytes, at, to) { - if (USE_BUFFER && bytes.constructor?.name === "Buffer") { - return bytes.toString("utf-8", at, to); - } - if (textDecoder) { - return textDecoder.decode(bytes.subarray(at, to)); - } - return (0, import_util_utf84.toUtf8)(bytes.subarray(at, to)); -} -function demote(bigInteger) { - const num = Number(bigInteger); - if (num < Number.MIN_SAFE_INTEGER || Number.MAX_SAFE_INTEGER < num) { - console.warn(new Error(`@smithy/core/cbor - truncating BigInt(${bigInteger}) to ${num} with loss of precision.`)); - } - return num; -} -function bytesToFloat16(a5, b6) { - const sign2 = a5 >> 7; - const exponent = (a5 & 124) >> 2; - const fraction = (a5 & 3) << 8 | b6; - const scalar = sign2 === 0 ? 1 : -1; - let exponentComponent; - let summation; - if (exponent === 0) { - if (fraction === 0) { - return 0; - } else { - exponentComponent = Math.pow(2, 1 - 15); - summation = 0; - } - } else if (exponent === 31) { - if (fraction === 0) { - return scalar * Infinity; - } else { - return NaN; - } - } else { - exponentComponent = Math.pow(2, exponent - 15); - summation = 1; - } - summation += fraction / 1024; - return scalar * (exponentComponent * summation); -} -function decodeCount(at, to) { - const minor = payload[at] & 31; - if (minor < 24) { - _offset = 1; - return minor; - } - if (minor === extendedOneByte || minor === extendedFloat16 || minor === extendedFloat32 || minor === extendedFloat64) { - const countLength = minorValueToArgumentLength[minor]; - _offset = countLength + 1; - if (to - at < _offset) { - throw new Error(`countLength ${countLength} greater than remaining buf len.`); - } - const countIndex = at + 1; - if (countLength === 1) { - return payload[countIndex]; - } else if (countLength === 2) { - return dataView.getUint16(countIndex); - } else if (countLength === 4) { - return dataView.getUint32(countIndex); - } - return demote(dataView.getBigUint64(countIndex)); - } - throw new Error(`unexpected minor value ${minor}.`); -} -function decodeUtf8String(at, to) { - const length = decodeCount(at, to); - const offset = _offset; - at += offset; - if (to - at < length) { - throw new Error(`string len ${length} greater than remaining buf len.`); - } - const value = bytesToUtf8(payload, at, at + length); - _offset = offset + length; - return value; -} -function decodeUtf8StringIndefinite(at, to) { - at += 1; - const vector2 = []; - for (const base = at; at < to; ) { - if (payload[at] === 255) { - const data2 = alloc(vector2.length); - data2.set(vector2, 0); - _offset = at - base + 2; - return bytesToUtf8(data2, 0, data2.length); - } - const major = (payload[at] & 224) >> 5; - const minor = payload[at] & 31; - if (major !== majorUtf8String) { - throw new Error(`unexpected major type ${major} in indefinite string.`); - } - if (minor === minorIndefinite) { - throw new Error("nested indefinite string."); - } - const bytes = decodeUnstructuredByteString(at, to); - const length = _offset; - at += length; - for (let i5 = 0; i5 < bytes.length; ++i5) { - vector2.push(bytes[i5]); - } - } - throw new Error("expected break marker."); -} -function decodeUnstructuredByteString(at, to) { - const length = decodeCount(at, to); - const offset = _offset; - at += offset; - if (to - at < length) { - throw new Error(`unstructured byte string len ${length} greater than remaining buf len.`); - } - const value = payload.subarray(at, at + length); - _offset = offset + length; - return value; -} -function decodeUnstructuredByteStringIndefinite(at, to) { - at += 1; - const vector2 = []; - for (const base = at; at < to; ) { - if (payload[at] === 255) { - const data2 = alloc(vector2.length); - data2.set(vector2, 0); - _offset = at - base + 2; - return data2; - } - const major = (payload[at] & 224) >> 5; - const minor = payload[at] & 31; - if (major !== majorUnstructuredByteString) { - throw new Error(`unexpected major type ${major} in indefinite string.`); - } - if (minor === minorIndefinite) { - throw new Error("nested indefinite string."); - } - const bytes = decodeUnstructuredByteString(at, to); - const length = _offset; - at += length; - for (let i5 = 0; i5 < bytes.length; ++i5) { - vector2.push(bytes[i5]); - } - } - throw new Error("expected break marker."); -} -function decodeList(at, to) { - const listDataLength = decodeCount(at, to); - const offset = _offset; - at += offset; - const base = at; - const list2 = Array(listDataLength); - for (let i5 = 0; i5 < listDataLength; ++i5) { - const item = decode(at, to); - const itemOffset = _offset; - list2[i5] = item; - at += itemOffset; - } - _offset = offset + (at - base); - return list2; -} -function decodeListIndefinite(at, to) { - at += 1; - const list2 = []; - for (const base = at; at < to; ) { - if (payload[at] === 255) { - _offset = at - base + 2; - return list2; - } - const item = decode(at, to); - const n5 = _offset; - at += n5; - list2.push(item); - } - throw new Error("expected break marker."); -} -function decodeMap(at, to) { - const mapDataLength = decodeCount(at, to); - const offset = _offset; - at += offset; - const base = at; - const map4 = {}; - for (let i5 = 0; i5 < mapDataLength; ++i5) { - if (at >= to) { - throw new Error("unexpected end of map payload."); - } - const major = (payload[at] & 224) >> 5; - if (major !== majorUtf8String) { - throw new Error(`unexpected major type ${major} for map key at index ${at}.`); - } - const key = decode(at, to); - at += _offset; - const value = decode(at, to); - at += _offset; - map4[key] = value; - } - _offset = offset + (at - base); - return map4; -} -function decodeMapIndefinite(at, to) { - at += 1; - const base = at; - const map4 = {}; - for (; at < to; ) { - if (at >= to) { - throw new Error("unexpected end of map payload."); - } - if (payload[at] === 255) { - _offset = at - base + 2; - return map4; - } - const major = (payload[at] & 224) >> 5; - if (major !== majorUtf8String) { - throw new Error(`unexpected major type ${major} for map key.`); - } - const key = decode(at, to); - at += _offset; - const value = decode(at, to); - at += _offset; - map4[key] = value; - } - throw new Error("expected break marker."); -} -function decodeSpecial(at, to) { - const minor = payload[at] & 31; - switch (minor) { - case specialTrue: - case specialFalse: - _offset = 1; - return minor === specialTrue; - case specialNull: - _offset = 1; - return null; - case specialUndefined: - _offset = 1; - return null; - case extendedFloat16: - if (to - at < 3) { - throw new Error("incomplete float16 at end of buf."); - } - _offset = 3; - return bytesToFloat16(payload[at + 1], payload[at + 2]); - case extendedFloat32: - if (to - at < 5) { - throw new Error("incomplete float32 at end of buf."); - } - _offset = 5; - return dataView.getFloat32(at + 1); - case extendedFloat64: - if (to - at < 9) { - throw new Error("incomplete float64 at end of buf."); - } - _offset = 9; - return dataView.getFloat64(at + 1); - default: - throw new Error(`unexpected minor value ${minor}.`); - } -} -function castBigInt(bigInt) { - if (typeof bigInt === "number") { - return bigInt; - } - const num = Number(bigInt); - if (Number.MIN_SAFE_INTEGER <= num && num <= Number.MAX_SAFE_INTEGER) { - return num; - } - return bigInt; -} -var import_util_utf84, USE_TEXT_DECODER, USE_BUFFER, payload, dataView, textDecoder, _offset, minorValueToArgumentLength; -var init_cbor_decode = __esm({ - "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/cbor/cbor-decode.js"() { - init_serde(); - import_util_utf84 = __toESM(require_dist_cjs6()); - init_cbor_types(); - USE_TEXT_DECODER = typeof TextDecoder !== "undefined"; - USE_BUFFER = typeof Buffer !== "undefined"; - payload = alloc(0); - dataView = new DataView(payload.buffer, payload.byteOffset, payload.byteLength); - textDecoder = USE_TEXT_DECODER ? new TextDecoder() : null; - _offset = 0; - minorValueToArgumentLength = { - [extendedOneByte]: 1, - [extendedFloat16]: 2, - [extendedFloat32]: 4, - [extendedFloat64]: 8 - }; - } -}); - -// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/cbor/cbor-encode.js -function ensureSpace(bytes) { - const remaining = data.byteLength - cursor; - if (remaining < bytes) { - if (cursor < 16e6) { - resize(Math.max(data.byteLength * 4, data.byteLength + bytes)); - } else { - resize(data.byteLength + bytes + 16e6); - } - } -} -function toUint8Array() { - const out = alloc(cursor); - out.set(data.subarray(0, cursor), 0); - cursor = 0; - return out; -} -function resize(size2) { - const old = data; - data = alloc(size2); - if (old) { - if (old.copy) { - old.copy(data, 0, 0, old.byteLength); - } else { - data.set(old, 0); - } - } - dataView2 = new DataView(data.buffer, data.byteOffset, data.byteLength); -} -function encodeHeader(major, value) { - if (value < 24) { - data[cursor++] = major << 5 | value; - } else if (value < 1 << 8) { - data[cursor++] = major << 5 | 24; - data[cursor++] = value; - } else if (value < 1 << 16) { - data[cursor++] = major << 5 | extendedFloat16; - dataView2.setUint16(cursor, value); - cursor += 2; - } else if (value < 2 ** 32) { - data[cursor++] = major << 5 | extendedFloat32; - dataView2.setUint32(cursor, value); - cursor += 4; - } else { - data[cursor++] = major << 5 | extendedFloat64; - dataView2.setBigUint64(cursor, typeof value === "bigint" ? value : BigInt(value)); - cursor += 8; - } -} -function encode(_input) { - const encodeStack = [_input]; - while (encodeStack.length) { - const input = encodeStack.pop(); - ensureSpace(typeof input === "string" ? input.length * 4 : 64); - if (typeof input === "string") { - if (USE_BUFFER2) { - encodeHeader(majorUtf8String, Buffer.byteLength(input)); - cursor += data.write(input, cursor); - } else { - const bytes = (0, import_util_utf85.fromUtf8)(input); - encodeHeader(majorUtf8String, bytes.byteLength); - data.set(bytes, cursor); - cursor += bytes.byteLength; - } - continue; - } else if (typeof input === "number") { - if (Number.isInteger(input)) { - const nonNegative = input >= 0; - const major = nonNegative ? majorUint64 : majorNegativeInt64; - const value = nonNegative ? input : -input - 1; - if (value < 24) { - data[cursor++] = major << 5 | value; - } else if (value < 256) { - data[cursor++] = major << 5 | 24; - data[cursor++] = value; - } else if (value < 65536) { - data[cursor++] = major << 5 | extendedFloat16; - data[cursor++] = value >> 8; - data[cursor++] = value; - } else if (value < 4294967296) { - data[cursor++] = major << 5 | extendedFloat32; - dataView2.setUint32(cursor, value); - cursor += 4; - } else { - data[cursor++] = major << 5 | extendedFloat64; - dataView2.setBigUint64(cursor, BigInt(value)); - cursor += 8; - } - continue; - } - data[cursor++] = majorSpecial << 5 | extendedFloat64; - dataView2.setFloat64(cursor, input); - cursor += 8; - continue; - } else if (typeof input === "bigint") { - const nonNegative = input >= 0; - const major = nonNegative ? majorUint64 : majorNegativeInt64; - const value = nonNegative ? input : -input - BigInt(1); - const n5 = Number(value); - if (n5 < 24) { - data[cursor++] = major << 5 | n5; - } else if (n5 < 256) { - data[cursor++] = major << 5 | 24; - data[cursor++] = n5; - } else if (n5 < 65536) { - data[cursor++] = major << 5 | extendedFloat16; - data[cursor++] = n5 >> 8; - data[cursor++] = n5 & 255; - } else if (n5 < 4294967296) { - data[cursor++] = major << 5 | extendedFloat32; - dataView2.setUint32(cursor, n5); - cursor += 4; - } else if (value < BigInt("18446744073709551616")) { - data[cursor++] = major << 5 | extendedFloat64; - dataView2.setBigUint64(cursor, value); - cursor += 8; - } else { - const binaryBigInt = value.toString(2); - const bigIntBytes = new Uint8Array(Math.ceil(binaryBigInt.length / 8)); - let b6 = value; - let i5 = 0; - while (bigIntBytes.byteLength - ++i5 >= 0) { - bigIntBytes[bigIntBytes.byteLength - i5] = Number(b6 & BigInt(255)); - b6 >>= BigInt(8); - } - ensureSpace(bigIntBytes.byteLength * 2); - data[cursor++] = nonNegative ? 194 : 195; - if (USE_BUFFER2) { - encodeHeader(majorUnstructuredByteString, Buffer.byteLength(bigIntBytes)); - } else { - encodeHeader(majorUnstructuredByteString, bigIntBytes.byteLength); - } - data.set(bigIntBytes, cursor); - cursor += bigIntBytes.byteLength; - } - continue; - } else if (input === null) { - data[cursor++] = majorSpecial << 5 | specialNull; - continue; - } else if (typeof input === "boolean") { - data[cursor++] = majorSpecial << 5 | (input ? specialTrue : specialFalse); - continue; - } else if (typeof input === "undefined") { - throw new Error("@smithy/core/cbor: client may not serialize undefined value."); - } else if (Array.isArray(input)) { - for (let i5 = input.length - 1; i5 >= 0; --i5) { - encodeStack.push(input[i5]); - } - encodeHeader(majorList, input.length); - continue; - } else if (typeof input.byteLength === "number") { - ensureSpace(input.length * 2); - encodeHeader(majorUnstructuredByteString, input.length); - data.set(input, cursor); - cursor += input.byteLength; - continue; - } else if (typeof input === "object") { - if (input instanceof NumericValue) { - const decimalIndex = input.string.indexOf("."); - const exponent = decimalIndex === -1 ? 0 : decimalIndex - input.string.length + 1; - const mantissa = BigInt(input.string.replace(".", "")); - data[cursor++] = 196; - encodeStack.push(mantissa); - encodeStack.push(exponent); - encodeHeader(majorList, 2); - continue; - } - if (input[tagSymbol]) { - if ("tag" in input && "value" in input) { - encodeStack.push(input.value); - encodeHeader(majorTag, input.tag); - continue; - } else { - throw new Error("tag encountered with missing fields, need 'tag' and 'value', found: " + JSON.stringify(input)); - } - } - const keys = Object.keys(input); - for (let i5 = keys.length - 1; i5 >= 0; --i5) { - const key = keys[i5]; - encodeStack.push(input[key]); - encodeStack.push(key); - } - encodeHeader(majorMap, keys.length); - continue; - } - throw new Error(`data type ${input?.constructor?.name ?? typeof input} not compatible for encoding.`); - } -} -var import_util_utf85, USE_BUFFER2, initialSize, data, dataView2, cursor; -var init_cbor_encode = __esm({ - "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/cbor/cbor-encode.js"() { - init_serde(); - import_util_utf85 = __toESM(require_dist_cjs6()); - init_cbor_types(); - USE_BUFFER2 = typeof Buffer !== "undefined"; - initialSize = 2048; - data = alloc(initialSize); - dataView2 = new DataView(data.buffer, data.byteOffset, data.byteLength); - cursor = 0; - } -}); - -// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/cbor/cbor.js -var cbor; -var init_cbor = __esm({ - "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/cbor/cbor.js"() { - init_cbor_decode(); - init_cbor_encode(); - cbor = { - deserialize(payload2) { - setPayload(payload2); - return decode(0, payload2.length); - }, - serialize(input) { - try { - encode(input); - return toUint8Array(); - } catch (e5) { - toUint8Array(); - throw e5; - } - }, - resizeEncodingBuffer(size2) { - resize(size2); - } - }; - } -}); - -// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/cbor/parseCborBody.js -var dateToTag, loadSmithyRpcV2CborErrorCode; -var init_parseCborBody = __esm({ - "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/cbor/parseCborBody.js"() { - init_cbor_types(); - dateToTag = (date7) => { - return tag({ - tag: 1, - value: date7.getTime() / 1e3 - }); - }; - loadSmithyRpcV2CborErrorCode = (output, data2) => { - const sanitizeErrorCode = (rawValue) => { - let cleanValue = rawValue; - if (typeof cleanValue === "number") { - cleanValue = cleanValue.toString(); - } - if (cleanValue.indexOf(",") >= 0) { - cleanValue = cleanValue.split(",")[0]; - } - if (cleanValue.indexOf(":") >= 0) { - cleanValue = cleanValue.split(":")[0]; - } - if (cleanValue.indexOf("#") >= 0) { - cleanValue = cleanValue.split("#")[1]; - } - return cleanValue; - }; - if (data2["__type"] !== void 0) { - return sanitizeErrorCode(data2["__type"]); - } - const codeKey = Object.keys(data2).find((key) => key.toLowerCase() === "code"); - if (codeKey && data2[codeKey] !== void 0) { - return sanitizeErrorCode(data2[codeKey]); - } - }; - } -}); - -// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/cbor/CborCodec.js -var import_util_base643, CborCodec, CborShapeSerializer, CborShapeDeserializer; -var init_CborCodec = __esm({ - "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/cbor/CborCodec.js"() { - init_protocols(); - init_schema3(); - init_serde(); - init_serde(); - import_util_base643 = __toESM(require_dist_cjs7()); - init_cbor(); - init_parseCborBody(); - CborCodec = class extends SerdeContext { - createSerializer() { - const serializer = new CborShapeSerializer(); - serializer.setSerdeContext(this.serdeContext); - return serializer; - } - createDeserializer() { - const deserializer = new CborShapeDeserializer(); - deserializer.setSerdeContext(this.serdeContext); - return deserializer; - } - }; - CborShapeSerializer = class extends SerdeContext { - value; - write(schema2, value) { - this.value = this.serialize(schema2, value); - } - serialize(schema2, source) { - const ns = NormalizedSchema.of(schema2); - if (source == null) { - if (ns.isIdempotencyToken()) { - return (0, import_uuid2.v4)(); - } - return source; - } - if (ns.isBlobSchema()) { - if (typeof source === "string") { - return (this.serdeContext?.base64Decoder ?? import_util_base643.fromBase64)(source); - } - return source; - } - if (ns.isTimestampSchema()) { - if (typeof source === "number" || typeof source === "bigint") { - return dateToTag(new Date(Number(source) / 1e3 | 0)); - } - return dateToTag(source); - } - if (typeof source === "function" || typeof source === "object") { - const sourceObject = source; - if (ns.isListSchema() && Array.isArray(sourceObject)) { - const sparse = !!ns.getMergedTraits().sparse; - const newArray = []; - let i5 = 0; - for (const item of sourceObject) { - const value = this.serialize(ns.getValueSchema(), item); - if (value != null || sparse) { - newArray[i5++] = value; - } - } - return newArray; - } - if (sourceObject instanceof Date) { - return dateToTag(sourceObject); - } - const newObject = {}; - if (ns.isMapSchema()) { - const sparse = !!ns.getMergedTraits().sparse; - for (const key of Object.keys(sourceObject)) { - const value = this.serialize(ns.getValueSchema(), sourceObject[key]); - if (value != null || sparse) { - newObject[key] = value; - } - } - } else if (ns.isStructSchema()) { - for (const [key, memberSchema] of ns.structIterator()) { - const value = this.serialize(memberSchema, sourceObject[key]); - if (value != null) { - newObject[key] = value; - } - } - const isUnion = ns.isUnionSchema(); - if (isUnion && Array.isArray(sourceObject.$unknown)) { - const [k5, v5] = sourceObject.$unknown; - newObject[k5] = v5; - } else if (typeof sourceObject.__type === "string") { - for (const [k5, v5] of Object.entries(sourceObject)) { - if (!(k5 in newObject)) { - newObject[k5] = this.serialize(15, v5); - } - } - } - } else if (ns.isDocumentSchema()) { - for (const key of Object.keys(sourceObject)) { - newObject[key] = this.serialize(ns.getValueSchema(), sourceObject[key]); - } - } else if (ns.isBigDecimalSchema()) { - return sourceObject; - } - return newObject; - } - return source; - } - flush() { - const buffer2 = cbor.serialize(this.value); - this.value = void 0; - return buffer2; - } - }; - CborShapeDeserializer = class extends SerdeContext { - read(schema2, bytes) { - const data2 = cbor.deserialize(bytes); - return this.readValue(schema2, data2); - } - readValue(_schema, value) { - const ns = NormalizedSchema.of(_schema); - if (ns.isTimestampSchema()) { - if (typeof value === "number") { - return _parseEpochTimestamp(value); - } - if (typeof value === "object") { - if (value.tag === 1 && "value" in value) { - return _parseEpochTimestamp(value.value); - } - } - } - if (ns.isBlobSchema()) { - if (typeof value === "string") { - return (this.serdeContext?.base64Decoder ?? import_util_base643.fromBase64)(value); - } - return value; - } - if (typeof value === "undefined" || typeof value === "boolean" || typeof value === "number" || typeof value === "string" || typeof value === "bigint" || typeof value === "symbol") { - return value; - } else if (typeof value === "object") { - if (value === null) { - return null; - } - if ("byteLength" in value) { - return value; - } - if (value instanceof Date) { - return value; - } - if (ns.isDocumentSchema()) { - return value; - } - if (ns.isListSchema()) { - const newArray = []; - const memberSchema = ns.getValueSchema(); - for (const item of value) { - const itemValue = this.readValue(memberSchema, item); - newArray.push(itemValue); - } - return newArray; - } - const newObject = {}; - if (ns.isMapSchema()) { - const targetSchema = ns.getValueSchema(); - for (const key of Object.keys(value)) { - const itemValue = this.readValue(targetSchema, value[key]); - newObject[key] = itemValue; - } - } else if (ns.isStructSchema()) { - const isUnion = ns.isUnionSchema(); - let keys; - if (isUnion) { - keys = new Set(Object.keys(value).filter((k5) => k5 !== "__type")); - } - for (const [key, memberSchema] of ns.structIterator()) { - if (isUnion) { - keys.delete(key); - } - if (value[key] != null) { - newObject[key] = this.readValue(memberSchema, value[key]); - } - } - if (isUnion && keys?.size === 1 && Object.keys(newObject).length === 0) { - const k5 = keys.values().next().value; - newObject.$unknown = [k5, value[k5]]; - } else if (typeof value.__type === "string") { - for (const [k5, v5] of Object.entries(value)) { - if (!(k5 in newObject)) { - newObject[k5] = v5; - } - } - } - } else if (value instanceof NumericValue) { - return value; - } - return newObject; - } else { - return value; - } - } - }; - } -}); - -// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/cbor/SmithyRpcV2CborProtocol.js -var import_util_middleware3, SmithyRpcV2CborProtocol; -var init_SmithyRpcV2CborProtocol = __esm({ - "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/cbor/SmithyRpcV2CborProtocol.js"() { - init_protocols(); - init_schema3(); - init_schema3(); - import_util_middleware3 = __toESM(require_dist_cjs18()); - init_CborCodec(); - init_parseCborBody(); - SmithyRpcV2CborProtocol = class extends RpcProtocol { - codec = new CborCodec(); - serializer = this.codec.createSerializer(); - deserializer = this.codec.createDeserializer(); - constructor({ defaultNamespace, errorTypeRegistries: errorTypeRegistries5 }) { - super({ defaultNamespace, errorTypeRegistries: errorTypeRegistries5 }); - } - getShapeId() { - return "smithy.protocols#rpcv2Cbor"; - } - getPayloadCodec() { - return this.codec; - } - async serializeRequest(operationSchema, input, context) { - const request = await super.serializeRequest(operationSchema, input, context); - Object.assign(request.headers, { - "content-type": this.getDefaultContentType(), - "smithy-protocol": "rpc-v2-cbor", - accept: this.getDefaultContentType() - }); - if (deref(operationSchema.input) === "unit") { - delete request.body; - delete request.headers["content-type"]; - } else { - if (!request.body) { - this.serializer.write(15, {}); - request.body = this.serializer.flush(); - } - try { - request.headers["content-length"] = String(request.body.byteLength); - } catch (e5) { - } - } - const { service, operation: operation2 } = (0, import_util_middleware3.getSmithyContext)(context); - const path53 = `/service/${service}/operation/${operation2}`; - if (request.path.endsWith("/")) { - request.path += path53.slice(1); - } else { - request.path += path53; - } - return request; - } - async deserializeResponse(operationSchema, context, response) { - return super.deserializeResponse(operationSchema, context, response); - } - async handleError(operationSchema, context, response, dataObject, metadata) { - const errorName = loadSmithyRpcV2CborErrorCode(response, dataObject) ?? "Unknown"; - const errorMetadata = { - $metadata: metadata, - $fault: response.statusCode <= 500 ? "client" : "server" - }; - let namespace = this.options.defaultNamespace; - if (errorName.includes("#")) { - [namespace] = errorName.split("#"); - } - const registry2 = this.compositeErrorRegistry; - const nsRegistry = TypeRegistry.for(namespace); - registry2.copyFrom(nsRegistry); - let errorSchema; - try { - errorSchema = registry2.getSchema(errorName); - } catch (e5) { - if (dataObject.Message) { - dataObject.message = dataObject.Message; - } - const syntheticRegistry = TypeRegistry.for("smithy.ts.sdk.synthetic." + namespace); - registry2.copyFrom(syntheticRegistry); - const baseExceptionSchema = registry2.getBaseException(); - if (baseExceptionSchema) { - const ErrorCtor2 = registry2.getErrorCtor(baseExceptionSchema); - throw Object.assign(new ErrorCtor2({ name: errorName }), errorMetadata, dataObject); - } - throw Object.assign(new Error(errorName), errorMetadata, dataObject); - } - const ns = NormalizedSchema.of(errorSchema); - const ErrorCtor = registry2.getErrorCtor(errorSchema); - const message2 = dataObject.message ?? dataObject.Message ?? "Unknown"; - const exception = new ErrorCtor(message2); - const output = {}; - for (const [name, member2] of ns.structIterator()) { - output[name] = this.deserializer.readValue(member2, dataObject[name]); - } - throw Object.assign(exception, errorMetadata, { - $fault: ns.getMergedTraits().error, - message: message2 - }, output); - } - getDefaultContentType() { - return "application/cbor"; - } - }; - } -}); - -// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/cbor/index.js -var init_cbor2 = __esm({ - "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/submodules/cbor/index.js"() { - init_parseCborBody(); - init_SmithyRpcV2CborProtocol(); - init_CborCodec(); - } -}); - -// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/ProtocolLib.js -var import_smithy_client, ProtocolLib; -var init_ProtocolLib = __esm({ - "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/ProtocolLib.js"() { - init_schema3(); - import_smithy_client = __toESM(require_dist_cjs27()); - ProtocolLib = class { - queryCompat; - errorRegistry; - constructor(queryCompat = false) { - this.queryCompat = queryCompat; - } - resolveRestContentType(defaultContentType, inputSchema) { - const members = inputSchema.getMemberSchemas(); - const httpPayloadMember = Object.values(members).find((m5) => { - return !!m5.getMergedTraits().httpPayload; - }); - if (httpPayloadMember) { - const mediaType = httpPayloadMember.getMergedTraits().mediaType; - if (mediaType) { - return mediaType; - } else if (httpPayloadMember.isStringSchema()) { - return "text/plain"; - } else if (httpPayloadMember.isBlobSchema()) { - return "application/octet-stream"; - } else { - return defaultContentType; - } - } else if (!inputSchema.isUnitSchema()) { - const hasBody = Object.values(members).find((m5) => { - const { httpQuery, httpQueryParams, httpHeader, httpLabel, httpPrefixHeaders } = m5.getMergedTraits(); - const noPrefixHeaders = httpPrefixHeaders === void 0; - return !httpQuery && !httpQueryParams && !httpHeader && !httpLabel && noPrefixHeaders; - }); - if (hasBody) { - return defaultContentType; - } - } - } - async getErrorSchemaOrThrowBaseException(errorIdentifier, defaultNamespace, response, dataObject, metadata, getErrorSchema) { - let errorName = errorIdentifier; - if (errorIdentifier.includes("#")) { - [, errorName] = errorIdentifier.split("#"); - } - const errorMetadata = { - $metadata: metadata, - $fault: response.statusCode < 500 ? "client" : "server" - }; - if (!this.errorRegistry) { - throw new Error("@aws-sdk/core/protocols - error handler not initialized."); - } - try { - const errorSchema = getErrorSchema?.(this.errorRegistry, errorName) ?? this.errorRegistry.getSchema(errorIdentifier); - return { errorSchema, errorMetadata }; - } catch (e5) { - dataObject.message = dataObject.message ?? dataObject.Message ?? "UnknownError"; - const synthetic = this.errorRegistry; - const baseExceptionSchema = synthetic.getBaseException(); - if (baseExceptionSchema) { - const ErrorCtor = synthetic.getErrorCtor(baseExceptionSchema) ?? Error; - throw this.decorateServiceException(Object.assign(new ErrorCtor({ name: errorName }), errorMetadata), dataObject); - } - const d5 = dataObject; - const message2 = d5?.message ?? d5?.Message ?? d5?.Error?.Message ?? d5?.Error?.message; - throw this.decorateServiceException(Object.assign(new Error(message2), { - name: errorName - }, errorMetadata), dataObject); - } - } - compose(composite, errorIdentifier, defaultNamespace) { - let namespace = defaultNamespace; - if (errorIdentifier.includes("#")) { - [namespace] = errorIdentifier.split("#"); - } - const staticRegistry = TypeRegistry.for(namespace); - const defaultSyntheticRegistry = TypeRegistry.for("smithy.ts.sdk.synthetic." + defaultNamespace); - composite.copyFrom(staticRegistry); - composite.copyFrom(defaultSyntheticRegistry); - this.errorRegistry = composite; - } - decorateServiceException(exception, additions = {}) { - if (this.queryCompat) { - const msg = exception.Message ?? additions.Message; - const error50 = (0, import_smithy_client.decorateServiceException)(exception, additions); - if (msg) { - error50.message = msg; - } - error50.Error = { - ...error50.Error, - Type: error50.Error?.Type, - Code: error50.Error?.Code, - Message: error50.Error?.message ?? error50.Error?.Message ?? msg - }; - const reqId = error50.$metadata.requestId; - if (reqId) { - error50.RequestId = reqId; - } - return error50; - } - return (0, import_smithy_client.decorateServiceException)(exception, additions); - } - setQueryCompatError(output, response) { - const queryErrorHeader = response.headers?.["x-amzn-query-error"]; - if (output !== void 0 && queryErrorHeader != null) { - const [Code, Type] = queryErrorHeader.split(";"); - const entries2 = Object.entries(output); - const Error2 = { - Code, - Type - }; - Object.assign(output, Error2); - for (const [k5, v5] of entries2) { - Error2[k5 === "message" ? "Message" : k5] = v5; - } - delete Error2.__type; - output.Error = Error2; - } - } - queryCompatOutput(queryCompatErrorData, errorData) { - if (queryCompatErrorData.Error) { - errorData.Error = queryCompatErrorData.Error; - } - if (queryCompatErrorData.Type) { - errorData.Type = queryCompatErrorData.Type; - } - if (queryCompatErrorData.Code) { - errorData.Code = queryCompatErrorData.Code; - } - } - findQueryCompatibleError(registry2, errorName) { - try { - return registry2.getSchema(errorName); - } catch (e5) { - return registry2.find((schema2) => NormalizedSchema.of(schema2).getMergedTraits().awsQueryError?.[0] === errorName); - } - } - }; - } -}); - -// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/cbor/AwsSmithyRpcV2CborProtocol.js -var AwsSmithyRpcV2CborProtocol; -var init_AwsSmithyRpcV2CborProtocol = __esm({ - "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/cbor/AwsSmithyRpcV2CborProtocol.js"() { - init_cbor2(); - init_schema3(); - init_ProtocolLib(); - AwsSmithyRpcV2CborProtocol = class extends SmithyRpcV2CborProtocol { - awsQueryCompatible; - mixin; - constructor({ defaultNamespace, errorTypeRegistries: errorTypeRegistries5, awsQueryCompatible }) { - super({ defaultNamespace, errorTypeRegistries: errorTypeRegistries5 }); - this.awsQueryCompatible = !!awsQueryCompatible; - this.mixin = new ProtocolLib(this.awsQueryCompatible); - } - async serializeRequest(operationSchema, input, context) { - const request = await super.serializeRequest(operationSchema, input, context); - if (this.awsQueryCompatible) { - request.headers["x-amzn-query-mode"] = "true"; - } - return request; - } - async handleError(operationSchema, context, response, dataObject, metadata) { - if (this.awsQueryCompatible) { - this.mixin.setQueryCompatError(dataObject, response); - } - const errorName = (() => { - const compatHeader = response.headers["x-amzn-query-error"]; - if (compatHeader && this.awsQueryCompatible) { - return compatHeader.split(";")[0]; - } - return loadSmithyRpcV2CborErrorCode(response, dataObject) ?? "Unknown"; - })(); - this.mixin.compose(this.compositeErrorRegistry, errorName, this.options.defaultNamespace); - const { errorSchema, errorMetadata } = await this.mixin.getErrorSchemaOrThrowBaseException(errorName, this.options.defaultNamespace, response, dataObject, metadata, this.awsQueryCompatible ? this.mixin.findQueryCompatibleError : void 0); - const ns = NormalizedSchema.of(errorSchema); - const message2 = dataObject.message ?? dataObject.Message ?? "UnknownError"; - const ErrorCtor = this.compositeErrorRegistry.getErrorCtor(errorSchema) ?? Error; - const exception = new ErrorCtor(message2); - const output = {}; - for (const [name, member2] of ns.structIterator()) { - if (dataObject[name] != null) { - output[name] = this.deserializer.readValue(member2, dataObject[name]); - } - } - if (this.awsQueryCompatible) { - this.mixin.queryCompatOutput(dataObject, output); - } - throw this.mixin.decorateServiceException(Object.assign(exception, errorMetadata, { - $fault: ns.getMergedTraits().error, - message: message2 - }, output), dataObject); - } - }; - } -}); - -// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/coercing-serializers.js -var _toStr, _toBool, _toNum; -var init_coercing_serializers = __esm({ - "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/coercing-serializers.js"() { - _toStr = (val) => { - if (val == null) { - return val; - } - if (typeof val === "number" || typeof val === "bigint") { - const warning = new Error(`Received number ${val} where a string was expected.`); - warning.name = "Warning"; - console.warn(warning); - return String(val); - } - if (typeof val === "boolean") { - const warning = new Error(`Received boolean ${val} where a string was expected.`); - warning.name = "Warning"; - console.warn(warning); - return String(val); - } - return val; - }; - _toBool = (val) => { - if (val == null) { - return val; - } - if (typeof val === "number") { - } - if (typeof val === "string") { - const lowercase2 = val.toLowerCase(); - if (val !== "" && lowercase2 !== "false" && lowercase2 !== "true") { - const warning = new Error(`Received string "${val}" where a boolean was expected.`); - warning.name = "Warning"; - console.warn(warning); - } - return val !== "" && lowercase2 !== "false"; - } - return val; - }; - _toNum = (val) => { - if (val == null) { - return val; - } - if (typeof val === "boolean") { - } - if (typeof val === "string") { - const num = Number(val); - if (num.toString() !== val) { - const warning = new Error(`Received string "${val}" where a number was expected.`); - warning.name = "Warning"; - console.warn(warning); - return val; - } - return num; - } - return val; - }; - } -}); - -// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/ConfigurableSerdeContext.js -var SerdeContextConfig; -var init_ConfigurableSerdeContext = __esm({ - "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/ConfigurableSerdeContext.js"() { - SerdeContextConfig = class { - serdeContext; - setSerdeContext(serdeContext) { - this.serdeContext = serdeContext; - } - }; - } -}); - -// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/UnionSerde.js -var UnionSerde; -var init_UnionSerde = __esm({ - "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/UnionSerde.js"() { - UnionSerde = class { - from; - to; - keys; - constructor(from, to) { - this.from = from; - this.to = to; - this.keys = new Set(Object.keys(this.from).filter((k5) => k5 !== "__type")); - } - mark(key) { - this.keys.delete(key); - } - hasUnknown() { - return this.keys.size === 1 && Object.keys(this.to).length === 0; - } - writeUnknown() { - if (this.hasUnknown()) { - const k5 = this.keys.values().next().value; - const v5 = this.from[k5]; - this.to.$unknown = [k5, v5]; - } - } - }; - } -}); - -// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/jsonReviver.js -function jsonReviver(key, value, context) { - if (context?.source) { - const numericString = context.source; - if (typeof value === "number") { - if (value > Number.MAX_SAFE_INTEGER || value < Number.MIN_SAFE_INTEGER || numericString !== String(value)) { - const isFractional = numericString.includes("."); - if (isFractional) { - return new NumericValue(numericString, "bigDecimal"); - } else { - return BigInt(numericString); - } - } - } - } - return value; -} -var init_jsonReviver = __esm({ - "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/jsonReviver.js"() { - init_serde(); - } -}); - -// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/common.js -var import_smithy_client2, import_util_utf86, collectBodyString; -var init_common2 = __esm({ - "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/common.js"() { - import_smithy_client2 = __toESM(require_dist_cjs27()); - import_util_utf86 = __toESM(require_dist_cjs6()); - collectBodyString = (streamBody, context) => (0, import_smithy_client2.collectBody)(streamBody, context).then((body) => (context?.utf8Encoder ?? import_util_utf86.toUtf8)(body)); - } -}); - -// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/parseJsonBody.js -var parseJsonBody, parseJsonErrorBody, loadRestJsonErrorCode; -var init_parseJsonBody = __esm({ - "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/parseJsonBody.js"() { - init_common2(); - parseJsonBody = (streamBody, context) => collectBodyString(streamBody, context).then((encoded) => { - if (encoded.length) { - try { - return JSON.parse(encoded); - } catch (e5) { - if (e5?.name === "SyntaxError") { - Object.defineProperty(e5, "$responseBodyText", { - value: encoded - }); - } - throw e5; - } - } - return {}; - }); - parseJsonErrorBody = async (errorBody, context) => { - const value = await parseJsonBody(errorBody, context); - value.message = value.message ?? value.Message; - return value; - }; - loadRestJsonErrorCode = (output, data2) => { - const findKey = (object2, key) => Object.keys(object2).find((k5) => k5.toLowerCase() === key.toLowerCase()); - const sanitizeErrorCode = (rawValue) => { - let cleanValue = rawValue; - if (typeof cleanValue === "number") { - cleanValue = cleanValue.toString(); - } - if (cleanValue.indexOf(",") >= 0) { - cleanValue = cleanValue.split(",")[0]; - } - if (cleanValue.indexOf(":") >= 0) { - cleanValue = cleanValue.split(":")[0]; - } - if (cleanValue.indexOf("#") >= 0) { - cleanValue = cleanValue.split("#")[1]; - } - return cleanValue; - }; - const headerKey = findKey(output.headers, "x-amzn-errortype"); - if (headerKey !== void 0) { - return sanitizeErrorCode(output.headers[headerKey]); - } - if (data2 && typeof data2 === "object") { - const codeKey = findKey(data2, "code"); - if (codeKey && data2[codeKey] !== void 0) { - return sanitizeErrorCode(data2[codeKey]); - } - if (data2["__type"] !== void 0) { - return sanitizeErrorCode(data2["__type"]); - } - } - }; - } -}); - -// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/JsonShapeDeserializer.js -var import_util_base644, JsonShapeDeserializer; -var init_JsonShapeDeserializer = __esm({ - "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/JsonShapeDeserializer.js"() { - init_protocols(); - init_schema3(); - init_serde(); - import_util_base644 = __toESM(require_dist_cjs7()); - init_ConfigurableSerdeContext(); - init_UnionSerde(); - init_jsonReviver(); - init_parseJsonBody(); - JsonShapeDeserializer = class extends SerdeContextConfig { - settings; - constructor(settings) { - super(); - this.settings = settings; - } - async read(schema2, data2) { - return this._read(schema2, typeof data2 === "string" ? JSON.parse(data2, jsonReviver) : await parseJsonBody(data2, this.serdeContext)); - } - readObject(schema2, data2) { - return this._read(schema2, data2); - } - _read(schema2, value) { - const isObject4 = value !== null && typeof value === "object"; - const ns = NormalizedSchema.of(schema2); - if (isObject4) { - if (ns.isStructSchema()) { - const record2 = value; - const union3 = ns.isUnionSchema(); - const out = {}; - let nameMap = void 0; - const { jsonName } = this.settings; - if (jsonName) { - nameMap = {}; - } - let unionSerde; - if (union3) { - unionSerde = new UnionSerde(record2, out); - } - for (const [memberName, memberSchema] of ns.structIterator()) { - let fromKey = memberName; - if (jsonName) { - fromKey = memberSchema.getMergedTraits().jsonName ?? fromKey; - nameMap[fromKey] = memberName; - } - if (union3) { - unionSerde.mark(fromKey); - } - if (record2[fromKey] != null) { - out[memberName] = this._read(memberSchema, record2[fromKey]); - } - } - if (union3) { - unionSerde.writeUnknown(); - } else if (typeof record2.__type === "string") { - for (const [k5, v5] of Object.entries(record2)) { - const t5 = jsonName ? nameMap[k5] ?? k5 : k5; - if (!(t5 in out)) { - out[t5] = v5; - } - } - } - return out; - } - if (Array.isArray(value) && ns.isListSchema()) { - const listMember = ns.getValueSchema(); - const out = []; - for (const item of value) { - out.push(this._read(listMember, item)); - } - return out; - } - if (ns.isMapSchema()) { - const mapMember = ns.getValueSchema(); - const out = {}; - for (const [_k, _v] of Object.entries(value)) { - out[_k] = this._read(mapMember, _v); - } - return out; - } - } - if (ns.isBlobSchema() && typeof value === "string") { - return (0, import_util_base644.fromBase64)(value); - } - const mediaType = ns.getMergedTraits().mediaType; - if (ns.isStringSchema() && typeof value === "string" && mediaType) { - const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); - if (isJson) { - return LazyJsonString.from(value); - } - return value; - } - if (ns.isTimestampSchema() && value != null) { - const format2 = determineTimestampFormat(ns, this.settings); - switch (format2) { - case 5: - return parseRfc3339DateTimeWithOffset(value); - case 6: - return parseRfc7231DateTime(value); - case 7: - return parseEpochTimestamp(value); - default: - console.warn("Missing timestamp format, parsing value with Date constructor:", value); - return new Date(value); - } - } - if (ns.isBigIntegerSchema() && (typeof value === "number" || typeof value === "string")) { - return BigInt(value); - } - if (ns.isBigDecimalSchema() && value != void 0) { - if (value instanceof NumericValue) { - return value; - } - const untyped = value; - if (untyped.type === "bigDecimal" && "string" in untyped) { - return new NumericValue(untyped.string, untyped.type); - } - return new NumericValue(String(value), "bigDecimal"); - } - if (ns.isNumericSchema() && typeof value === "string") { - switch (value) { - case "Infinity": - return Infinity; - case "-Infinity": - return -Infinity; - case "NaN": - return NaN; - } - return value; - } - if (ns.isDocumentSchema()) { - if (isObject4) { - const out = Array.isArray(value) ? [] : {}; - for (const [k5, v5] of Object.entries(value)) { - if (v5 instanceof NumericValue) { - out[k5] = v5; - } else { - out[k5] = this._read(ns, v5); - } - } - return out; - } else { - return structuredClone(value); - } - } - return value; - } - }; - } -}); - -// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/jsonReplacer.js -var NUMERIC_CONTROL_CHAR, JsonReplacer; -var init_jsonReplacer = __esm({ - "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/jsonReplacer.js"() { - init_serde(); - NUMERIC_CONTROL_CHAR = String.fromCharCode(925); - JsonReplacer = class { - values = /* @__PURE__ */ new Map(); - counter = 0; - stage = 0; - createReplacer() { - if (this.stage === 1) { - throw new Error("@aws-sdk/core/protocols - JsonReplacer already created."); - } - if (this.stage === 2) { - throw new Error("@aws-sdk/core/protocols - JsonReplacer exhausted."); - } - this.stage = 1; - return (key, value) => { - if (value instanceof NumericValue) { - const v5 = `${NUMERIC_CONTROL_CHAR + "nv" + this.counter++}_` + value.string; - this.values.set(`"${v5}"`, value.string); - return v5; - } - if (typeof value === "bigint") { - const s5 = value.toString(); - const v5 = `${NUMERIC_CONTROL_CHAR + "b" + this.counter++}_` + s5; - this.values.set(`"${v5}"`, s5); - return v5; - } - return value; - }; - } - replaceInJson(json3) { - if (this.stage === 0) { - throw new Error("@aws-sdk/core/protocols - JsonReplacer not created yet."); - } - if (this.stage === 2) { - throw new Error("@aws-sdk/core/protocols - JsonReplacer exhausted."); - } - this.stage = 2; - if (this.counter === 0) { - return json3; - } - for (const [key, value] of this.values) { - json3 = json3.replace(key, value); - } - return json3; - } - }; - } -}); - -// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/JsonShapeSerializer.js -var import_util_base645, JsonShapeSerializer; -var init_JsonShapeSerializer = __esm({ - "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/JsonShapeSerializer.js"() { - init_protocols(); - init_schema3(); - init_serde(); - import_util_base645 = __toESM(require_dist_cjs7()); - init_ConfigurableSerdeContext(); - init_jsonReplacer(); - JsonShapeSerializer = class extends SerdeContextConfig { - settings; - buffer; - useReplacer = false; - rootSchema; - constructor(settings) { - super(); - this.settings = settings; - } - write(schema2, value) { - this.rootSchema = NormalizedSchema.of(schema2); - this.buffer = this._write(this.rootSchema, value); - } - writeDiscriminatedDocument(schema2, value) { - this.write(schema2, value); - if (typeof this.buffer === "object") { - this.buffer.__type = NormalizedSchema.of(schema2).getName(true); - } - } - flush() { - const { rootSchema, useReplacer } = this; - this.rootSchema = void 0; - this.useReplacer = false; - if (rootSchema?.isStructSchema() || rootSchema?.isDocumentSchema()) { - if (!useReplacer) { - return JSON.stringify(this.buffer); - } - const replacer = new JsonReplacer(); - return replacer.replaceInJson(JSON.stringify(this.buffer, replacer.createReplacer(), 0)); - } - return this.buffer; - } - _write(schema2, value, container) { - const isObject4 = value !== null && typeof value === "object"; - const ns = NormalizedSchema.of(schema2); - if (isObject4) { - if (ns.isStructSchema()) { - const record2 = value; - const out = {}; - const { jsonName } = this.settings; - let nameMap = void 0; - if (jsonName) { - nameMap = {}; - } - for (const [memberName, memberSchema] of ns.structIterator()) { - const serializableValue = this._write(memberSchema, record2[memberName], ns); - if (serializableValue !== void 0) { - let targetKey = memberName; - if (jsonName) { - targetKey = memberSchema.getMergedTraits().jsonName ?? memberName; - nameMap[memberName] = targetKey; - } - out[targetKey] = serializableValue; - } - } - if (ns.isUnionSchema() && Object.keys(out).length === 0) { - const { $unknown } = record2; - if (Array.isArray($unknown)) { - const [k5, v5] = $unknown; - out[k5] = this._write(15, v5); - } - } else if (typeof record2.__type === "string") { - for (const [k5, v5] of Object.entries(record2)) { - const targetKey = jsonName ? nameMap[k5] ?? k5 : k5; - if (!(targetKey in out)) { - out[targetKey] = this._write(15, v5); - } - } - } - return out; - } - if (Array.isArray(value) && ns.isListSchema()) { - const listMember = ns.getValueSchema(); - const out = []; - const sparse = !!ns.getMergedTraits().sparse; - for (const item of value) { - if (sparse || item != null) { - out.push(this._write(listMember, item)); - } - } - return out; - } - if (ns.isMapSchema()) { - const mapMember = ns.getValueSchema(); - const out = {}; - const sparse = !!ns.getMergedTraits().sparse; - for (const [_k, _v] of Object.entries(value)) { - if (sparse || _v != null) { - out[_k] = this._write(mapMember, _v); - } - } - return out; - } - if (value instanceof Uint8Array && (ns.isBlobSchema() || ns.isDocumentSchema())) { - if (ns === this.rootSchema) { - return value; - } - return (this.serdeContext?.base64Encoder ?? import_util_base645.toBase64)(value); - } - if (value instanceof Date && (ns.isTimestampSchema() || ns.isDocumentSchema())) { - const format2 = determineTimestampFormat(ns, this.settings); - switch (format2) { - case 5: - return value.toISOString().replace(".000Z", "Z"); - case 6: - return dateToUtcString(value); - case 7: - return value.getTime() / 1e3; - default: - console.warn("Missing timestamp format, using epoch seconds", value); - return value.getTime() / 1e3; - } - } - if (value instanceof NumericValue) { - this.useReplacer = true; - } - } - if (value === null && container?.isStructSchema()) { - return void 0; - } - if (ns.isStringSchema()) { - if (typeof value === "undefined" && ns.isIdempotencyToken()) { - return (0, import_uuid2.v4)(); - } - const mediaType = ns.getMergedTraits().mediaType; - if (value != null && mediaType) { - const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); - if (isJson) { - return LazyJsonString.from(value); - } - } - return value; - } - if (typeof value === "number" && ns.isNumericSchema()) { - if (Math.abs(value) === Infinity || isNaN(value)) { - return String(value); - } - return value; - } - if (typeof value === "string" && ns.isBlobSchema()) { - if (ns === this.rootSchema) { - return value; - } - return (this.serdeContext?.base64Encoder ?? import_util_base645.toBase64)(value); - } - if (typeof value === "bigint") { - this.useReplacer = true; - } - if (ns.isDocumentSchema()) { - if (isObject4) { - const out = Array.isArray(value) ? [] : {}; - for (const [k5, v5] of Object.entries(value)) { - if (v5 instanceof NumericValue) { - this.useReplacer = true; - out[k5] = v5; - } else { - out[k5] = this._write(ns, v5); - } - } - return out; - } else { - return structuredClone(value); - } - } - return value; - } - }; - } -}); - -// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/JsonCodec.js -var JsonCodec; -var init_JsonCodec = __esm({ - "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/JsonCodec.js"() { - init_ConfigurableSerdeContext(); - init_JsonShapeDeserializer(); - init_JsonShapeSerializer(); - JsonCodec = class extends SerdeContextConfig { - settings; - constructor(settings) { - super(); - this.settings = settings; - } - createSerializer() { - const serializer = new JsonShapeSerializer(this.settings); - serializer.setSerdeContext(this.serdeContext); - return serializer; - } - createDeserializer() { - const deserializer = new JsonShapeDeserializer(this.settings); - deserializer.setSerdeContext(this.serdeContext); - return deserializer; - } - }; - } -}); - -// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/AwsJsonRpcProtocol.js -var AwsJsonRpcProtocol; -var init_AwsJsonRpcProtocol = __esm({ - "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/AwsJsonRpcProtocol.js"() { - init_protocols(); - init_schema3(); - init_ProtocolLib(); - init_JsonCodec(); - init_parseJsonBody(); - AwsJsonRpcProtocol = class extends RpcProtocol { - serializer; - deserializer; - serviceTarget; - codec; - mixin; - awsQueryCompatible; - constructor({ defaultNamespace, errorTypeRegistries: errorTypeRegistries5, serviceTarget, awsQueryCompatible, jsonCodec }) { - super({ - defaultNamespace, - errorTypeRegistries: errorTypeRegistries5 - }); - this.serviceTarget = serviceTarget; - this.codec = jsonCodec ?? new JsonCodec({ - timestampFormat: { - useTrait: true, - default: 7 - }, - jsonName: false - }); - this.serializer = this.codec.createSerializer(); - this.deserializer = this.codec.createDeserializer(); - this.awsQueryCompatible = !!awsQueryCompatible; - this.mixin = new ProtocolLib(this.awsQueryCompatible); - } - async serializeRequest(operationSchema, input, context) { - const request = await super.serializeRequest(operationSchema, input, context); - if (!request.path.endsWith("/")) { - request.path += "/"; - } - Object.assign(request.headers, { - "content-type": `application/x-amz-json-${this.getJsonRpcVersion()}`, - "x-amz-target": `${this.serviceTarget}.${operationSchema.name}` - }); - if (this.awsQueryCompatible) { - request.headers["x-amzn-query-mode"] = "true"; - } - if (deref(operationSchema.input) === "unit" || !request.body) { - request.body = "{}"; - } - return request; - } - getPayloadCodec() { - return this.codec; - } - async handleError(operationSchema, context, response, dataObject, metadata) { - if (this.awsQueryCompatible) { - this.mixin.setQueryCompatError(dataObject, response); - } - const errorIdentifier = loadRestJsonErrorCode(response, dataObject) ?? "Unknown"; - this.mixin.compose(this.compositeErrorRegistry, errorIdentifier, this.options.defaultNamespace); - const { errorSchema, errorMetadata } = await this.mixin.getErrorSchemaOrThrowBaseException(errorIdentifier, this.options.defaultNamespace, response, dataObject, metadata, this.awsQueryCompatible ? this.mixin.findQueryCompatibleError : void 0); - const ns = NormalizedSchema.of(errorSchema); - const message2 = dataObject.message ?? dataObject.Message ?? "UnknownError"; - const ErrorCtor = this.compositeErrorRegistry.getErrorCtor(errorSchema) ?? Error; - const exception = new ErrorCtor(message2); - const output = {}; - for (const [name, member2] of ns.structIterator()) { - if (dataObject[name] != null) { - output[name] = this.codec.createDeserializer().readObject(member2, dataObject[name]); - } - } - if (this.awsQueryCompatible) { - this.mixin.queryCompatOutput(dataObject, output); - } - throw this.mixin.decorateServiceException(Object.assign(exception, errorMetadata, { - $fault: ns.getMergedTraits().error, - message: message2 - }, output), dataObject); - } - }; - } -}); - -// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/AwsJson1_0Protocol.js -var AwsJson1_0Protocol; -var init_AwsJson1_0Protocol = __esm({ - "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/AwsJson1_0Protocol.js"() { - init_AwsJsonRpcProtocol(); - AwsJson1_0Protocol = class extends AwsJsonRpcProtocol { - constructor({ defaultNamespace, errorTypeRegistries: errorTypeRegistries5, serviceTarget, awsQueryCompatible, jsonCodec }) { - super({ - defaultNamespace, - errorTypeRegistries: errorTypeRegistries5, - serviceTarget, - awsQueryCompatible, - jsonCodec - }); - } - getShapeId() { - return "aws.protocols#awsJson1_0"; - } - getJsonRpcVersion() { - return "1.0"; - } - getDefaultContentType() { - return "application/x-amz-json-1.0"; - } - }; - } -}); - -// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/AwsJson1_1Protocol.js -var AwsJson1_1Protocol; -var init_AwsJson1_1Protocol = __esm({ - "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/AwsJson1_1Protocol.js"() { - init_AwsJsonRpcProtocol(); - AwsJson1_1Protocol = class extends AwsJsonRpcProtocol { - constructor({ defaultNamespace, errorTypeRegistries: errorTypeRegistries5, serviceTarget, awsQueryCompatible, jsonCodec }) { - super({ - defaultNamespace, - errorTypeRegistries: errorTypeRegistries5, - serviceTarget, - awsQueryCompatible, - jsonCodec - }); - } - getShapeId() { - return "aws.protocols#awsJson1_1"; - } - getJsonRpcVersion() { - return "1.1"; - } - getDefaultContentType() { - return "application/x-amz-json-1.1"; - } - }; - } -}); - -// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/AwsRestJsonProtocol.js -var AwsRestJsonProtocol; -var init_AwsRestJsonProtocol = __esm({ - "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/AwsRestJsonProtocol.js"() { - init_protocols(); - init_schema3(); - init_ProtocolLib(); - init_JsonCodec(); - init_parseJsonBody(); - AwsRestJsonProtocol = class extends HttpBindingProtocol { - serializer; - deserializer; - codec; - mixin = new ProtocolLib(); - constructor({ defaultNamespace, errorTypeRegistries: errorTypeRegistries5 }) { - super({ - defaultNamespace, - errorTypeRegistries: errorTypeRegistries5 - }); - const settings = { - timestampFormat: { - useTrait: true, - default: 7 - }, - httpBindings: true, - jsonName: true - }; - this.codec = new JsonCodec(settings); - this.serializer = new HttpInterceptingShapeSerializer(this.codec.createSerializer(), settings); - this.deserializer = new HttpInterceptingShapeDeserializer(this.codec.createDeserializer(), settings); - } - getShapeId() { - return "aws.protocols#restJson1"; - } - getPayloadCodec() { - return this.codec; - } - setSerdeContext(serdeContext) { - this.codec.setSerdeContext(serdeContext); - super.setSerdeContext(serdeContext); - } - async serializeRequest(operationSchema, input, context) { - const request = await super.serializeRequest(operationSchema, input, context); - const inputSchema = NormalizedSchema.of(operationSchema.input); - if (!request.headers["content-type"]) { - const contentType = this.mixin.resolveRestContentType(this.getDefaultContentType(), inputSchema); - if (contentType) { - request.headers["content-type"] = contentType; - } - } - if (request.body == null && request.headers["content-type"] === this.getDefaultContentType()) { - request.body = "{}"; - } - return request; - } - async deserializeResponse(operationSchema, context, response) { - const output = await super.deserializeResponse(operationSchema, context, response); - const outputSchema = NormalizedSchema.of(operationSchema.output); - for (const [name, member2] of outputSchema.structIterator()) { - if (member2.getMemberTraits().httpPayload && !(name in output)) { - output[name] = null; - } - } - return output; - } - async handleError(operationSchema, context, response, dataObject, metadata) { - const errorIdentifier = loadRestJsonErrorCode(response, dataObject) ?? "Unknown"; - this.mixin.compose(this.compositeErrorRegistry, errorIdentifier, this.options.defaultNamespace); - const { errorSchema, errorMetadata } = await this.mixin.getErrorSchemaOrThrowBaseException(errorIdentifier, this.options.defaultNamespace, response, dataObject, metadata); - const ns = NormalizedSchema.of(errorSchema); - const message2 = dataObject.message ?? dataObject.Message ?? "UnknownError"; - const ErrorCtor = this.compositeErrorRegistry.getErrorCtor(errorSchema) ?? Error; - const exception = new ErrorCtor(message2); - await this.deserializeHttpMessage(errorSchema, context, response, dataObject); - const output = {}; - for (const [name, member2] of ns.structIterator()) { - const target = member2.getMergedTraits().jsonName ?? name; - output[name] = this.codec.createDeserializer().readObject(member2, dataObject[target]); - } - throw this.mixin.decorateServiceException(Object.assign(exception, errorMetadata, { - $fault: ns.getMergedTraits().error, - message: message2 - }, output), dataObject); - } - getDefaultContentType() { - return "application/json"; - } - }; - } -}); - -// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/awsExpectUnion.js -var import_smithy_client3, awsExpectUnion; -var init_awsExpectUnion = __esm({ - "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/awsExpectUnion.js"() { - import_smithy_client3 = __toESM(require_dist_cjs27()); - awsExpectUnion = (value) => { - if (value == null) { - return void 0; - } - if (typeof value === "object" && "__type" in value) { - delete value.__type; - } - return (0, import_smithy_client3.expectUnion)(value); - }; - } -}); - -// node_modules/.pnpm/fast-xml-parser@5.5.8/node_modules/fast-xml-parser/lib/fxp.cjs -var require_fxp = __commonJS({ - "node_modules/.pnpm/fast-xml-parser@5.5.8/node_modules/fast-xml-parser/lib/fxp.cjs"(exports, module) { - (() => { - "use strict"; - var t5 = { d: (e6, i6) => { - for (var n6 in i6) t5.o(i6, n6) && !t5.o(e6, n6) && Object.defineProperty(e6, n6, { enumerable: true, get: i6[n6] }); - }, o: (t6, e6) => Object.prototype.hasOwnProperty.call(t6, e6), r: (t6) => { - "undefined" != typeof Symbol && Symbol.toStringTag && Object.defineProperty(t6, Symbol.toStringTag, { value: "Module" }), Object.defineProperty(t6, "__esModule", { value: true }); - } }, e5 = {}; - t5.r(e5), t5.d(e5, { XMLBuilder: () => $t, XMLParser: () => gt2, XMLValidator: () => It }); - const i5 = ":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD", n5 = new RegExp("^[" + i5 + "][" + i5 + "\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*$"); - function s5(t6, e6) { - const i6 = []; - let n6 = e6.exec(t6); - for (; n6; ) { - const s6 = []; - s6.startIndex = e6.lastIndex - n6[0].length; - const r6 = n6.length; - for (let t7 = 0; t7 < r6; t7++) s6.push(n6[t7]); - i6.push(s6), n6 = e6.exec(t6); - } - return i6; - } - const r5 = function(t6) { - return !(null == n5.exec(t6)); - }, o5 = ["hasOwnProperty", "toString", "valueOf", "__defineGetter__", "__defineSetter__", "__lookupGetter__", "__lookupSetter__"], a5 = ["__proto__", "constructor", "prototype"], h5 = { allowBooleanAttributes: false, unpairedTags: [] }; - function l5(t6, e6) { - e6 = Object.assign({}, h5, e6); - const i6 = []; - let n6 = false, s6 = false; - "\uFEFF" === t6[0] && (t6 = t6.substr(1)); - for (let r6 = 0; r6 < t6.length; r6++) if ("<" === t6[r6] && "?" === t6[r6 + 1]) { - if (r6 += 2, r6 = u5(t6, r6), r6.err) return r6; - } else { - if ("<" !== t6[r6]) { - if (p5(t6[r6])) continue; - return b6("InvalidChar", "char '" + t6[r6] + "' is not expected.", w5(t6, r6)); - } - { - let o6 = r6; - if (r6++, "!" === t6[r6]) { - r6 = c5(t6, r6); - continue; - } - { - let a6 = false; - "/" === t6[r6] && (a6 = true, r6++); - let h6 = ""; - for (; r6 < t6.length && ">" !== t6[r6] && " " !== t6[r6] && " " !== t6[r6] && "\n" !== t6[r6] && "\r" !== t6[r6]; r6++) h6 += t6[r6]; - if (h6 = h6.trim(), "/" === h6[h6.length - 1] && (h6 = h6.substring(0, h6.length - 1), r6--), !y2(h6)) { - let e7; - return e7 = 0 === h6.trim().length ? "Invalid space after '<'." : "Tag '" + h6 + "' is an invalid name.", b6("InvalidTag", e7, w5(t6, r6)); - } - const l6 = g5(t6, r6); - if (false === l6) return b6("InvalidAttr", "Attributes for '" + h6 + "' have open quote.", w5(t6, r6)); - let d6 = l6.value; - if (r6 = l6.index, "/" === d6[d6.length - 1]) { - const i7 = r6 - d6.length; - d6 = d6.substring(0, d6.length - 1); - const s7 = x5(d6, e6); - if (true !== s7) return b6(s7.err.code, s7.err.msg, w5(t6, i7 + s7.err.line)); - n6 = true; - } else if (a6) { - if (!l6.tagClosed) return b6("InvalidTag", "Closing tag '" + h6 + "' doesn't have proper closing.", w5(t6, r6)); - if (d6.trim().length > 0) return b6("InvalidTag", "Closing tag '" + h6 + "' can't have attributes or invalid starting.", w5(t6, o6)); - if (0 === i6.length) return b6("InvalidTag", "Closing tag '" + h6 + "' has not been opened.", w5(t6, o6)); - { - const e7 = i6.pop(); - if (h6 !== e7.tagName) { - let i7 = w5(t6, e7.tagStartPos); - return b6("InvalidTag", "Expected closing tag '" + e7.tagName + "' (opened in line " + i7.line + ", col " + i7.col + ") instead of closing tag '" + h6 + "'.", w5(t6, o6)); - } - 0 == i6.length && (s6 = true); - } - } else { - const a7 = x5(d6, e6); - if (true !== a7) return b6(a7.err.code, a7.err.msg, w5(t6, r6 - d6.length + a7.err.line)); - if (true === s6) return b6("InvalidXml", "Multiple possible root nodes found.", w5(t6, r6)); - -1 !== e6.unpairedTags.indexOf(h6) || i6.push({ tagName: h6, tagStartPos: o6 }), n6 = true; - } - for (r6++; r6 < t6.length; r6++) if ("<" === t6[r6]) { - if ("!" === t6[r6 + 1]) { - r6++, r6 = c5(t6, r6); - continue; - } - if ("?" !== t6[r6 + 1]) break; - if (r6 = u5(t6, ++r6), r6.err) return r6; - } else if ("&" === t6[r6]) { - const e7 = N(t6, r6); - if (-1 == e7) return b6("InvalidChar", "char '&' is not expected.", w5(t6, r6)); - r6 = e7; - } else if (true === s6 && !p5(t6[r6])) return b6("InvalidXml", "Extra text at the end", w5(t6, r6)); - "<" === t6[r6] && r6--; - } - } - } - return n6 ? 1 == i6.length ? b6("InvalidTag", "Unclosed tag '" + i6[0].tagName + "'.", w5(t6, i6[0].tagStartPos)) : !(i6.length > 0) || b6("InvalidXml", "Invalid '" + JSON.stringify(i6.map((t7) => t7.tagName), null, 4).replace(/\r?\n/g, "") + "' found.", { line: 1, col: 1 }) : b6("InvalidXml", "Start tag expected.", 1); - } - function p5(t6) { - return " " === t6 || " " === t6 || "\n" === t6 || "\r" === t6; - } - function u5(t6, e6) { - const i6 = e6; - for (; e6 < t6.length; e6++) if ("?" == t6[e6] || " " == t6[e6]) { - const n6 = t6.substr(i6, e6 - i6); - if (e6 > 5 && "xml" === n6) return b6("InvalidXml", "XML declaration allowed only at the start of the document.", w5(t6, e6)); - if ("?" == t6[e6] && ">" == t6[e6 + 1]) { - e6++; - break; - } - continue; - } - return e6; - } - function c5(t6, e6) { - if (t6.length > e6 + 5 && "-" === t6[e6 + 1] && "-" === t6[e6 + 2]) { - for (e6 += 3; e6 < t6.length; e6++) if ("-" === t6[e6] && "-" === t6[e6 + 1] && ">" === t6[e6 + 2]) { - e6 += 2; - break; - } - } else if (t6.length > e6 + 8 && "D" === t6[e6 + 1] && "O" === t6[e6 + 2] && "C" === t6[e6 + 3] && "T" === t6[e6 + 4] && "Y" === t6[e6 + 5] && "P" === t6[e6 + 6] && "E" === t6[e6 + 7]) { - let i6 = 1; - for (e6 += 8; e6 < t6.length; e6++) if ("<" === t6[e6]) i6++; - else if (">" === t6[e6] && (i6--, 0 === i6)) break; - } else if (t6.length > e6 + 9 && "[" === t6[e6 + 1] && "C" === t6[e6 + 2] && "D" === t6[e6 + 3] && "A" === t6[e6 + 4] && "T" === t6[e6 + 5] && "A" === t6[e6 + 6] && "[" === t6[e6 + 7]) { - for (e6 += 8; e6 < t6.length; e6++) if ("]" === t6[e6] && "]" === t6[e6 + 1] && ">" === t6[e6 + 2]) { - e6 += 2; - break; - } - } - return e6; - } - const d5 = '"', f5 = "'"; - function g5(t6, e6) { - let i6 = "", n6 = "", s6 = false; - for (; e6 < t6.length; e6++) { - if (t6[e6] === d5 || t6[e6] === f5) "" === n6 ? n6 = t6[e6] : n6 !== t6[e6] || (n6 = ""); - else if (">" === t6[e6] && "" === n6) { - s6 = true; - break; - } - i6 += t6[e6]; - } - return "" === n6 && { value: i6, index: e6, tagClosed: s6 }; - } - const m5 = new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`, "g"); - function x5(t6, e6) { - const i6 = s5(t6, m5), n6 = {}; - for (let t7 = 0; t7 < i6.length; t7++) { - if (0 === i6[t7][1].length) return b6("InvalidAttr", "Attribute '" + i6[t7][2] + "' has no space in starting.", v5(i6[t7])); - if (void 0 !== i6[t7][3] && void 0 === i6[t7][4]) return b6("InvalidAttr", "Attribute '" + i6[t7][2] + "' is without value.", v5(i6[t7])); - if (void 0 === i6[t7][3] && !e6.allowBooleanAttributes) return b6("InvalidAttr", "boolean attribute '" + i6[t7][2] + "' is not allowed.", v5(i6[t7])); - const s6 = i6[t7][2]; - if (!E2(s6)) return b6("InvalidAttr", "Attribute '" + s6 + "' is an invalid name.", v5(i6[t7])); - if (Object.prototype.hasOwnProperty.call(n6, s6)) return b6("InvalidAttr", "Attribute '" + s6 + "' is repeated.", v5(i6[t7])); - n6[s6] = 1; - } - return true; - } - function N(t6, e6) { - if (";" === t6[++e6]) return -1; - if ("#" === t6[e6]) return (function(t7, e7) { - let i7 = /\d/; - for ("x" === t7[e7] && (e7++, i7 = /[\da-fA-F]/); e7 < t7.length; e7++) { - if (";" === t7[e7]) return e7; - if (!t7[e7].match(i7)) break; - } - return -1; - })(t6, ++e6); - let i6 = 0; - for (; e6 < t6.length; e6++, i6++) if (!(t6[e6].match(/\w/) && i6 < 20)) { - if (";" === t6[e6]) break; - return -1; - } - return e6; - } - function b6(t6, e6, i6) { - return { err: { code: t6, msg: e6, line: i6.line || i6, col: i6.col } }; - } - function E2(t6) { - return r5(t6); - } - function y2(t6) { - return r5(t6); - } - function w5(t6, e6) { - const i6 = t6.substring(0, e6).split(/\r?\n/); - return { line: i6.length, col: i6[i6.length - 1].length + 1 }; - } - function v5(t6) { - return t6.startIndex + t6[1].length; - } - const T = (t6) => o5.includes(t6) ? "__" + t6 : t6, P = { preserveOrder: false, attributeNamePrefix: "@_", attributesGroupName: false, textNodeName: "#text", ignoreAttributes: true, removeNSPrefix: false, allowBooleanAttributes: false, parseTagValue: true, parseAttributeValue: false, trimValues: true, cdataPropName: false, numberParseOptions: { hex: true, leadingZeros: true, eNotation: true }, tagValueProcessor: function(t6, e6) { - return e6; - }, attributeValueProcessor: function(t6, e6) { - return e6; - }, stopNodes: [], alwaysCreateTextNode: false, isArray: () => false, commentPropName: false, unpairedTags: [], processEntities: true, htmlEntities: false, ignoreDeclaration: false, ignorePiTags: false, transformTagName: false, transformAttributeName: false, updateTag: function(t6, e6, i6) { - return t6; - }, captureMetaData: false, maxNestedTags: 100, strictReservedNames: true, jPath: true, onDangerousProperty: T }; - function S(t6, e6) { - if ("string" != typeof t6) return; - const i6 = t6.toLowerCase(); - if (o5.some((t7) => i6 === t7.toLowerCase())) throw new Error(`[SECURITY] Invalid ${e6}: "${t6}" is a reserved JavaScript keyword that could cause prototype pollution`); - if (a5.some((t7) => i6 === t7.toLowerCase())) throw new Error(`[SECURITY] Invalid ${e6}: "${t6}" is a reserved JavaScript keyword that could cause prototype pollution`); - } - function A2(t6) { - return "boolean" == typeof t6 ? { enabled: t6, maxEntitySize: 1e4, maxExpansionDepth: 10, maxTotalExpansions: 1e3, maxExpandedLength: 1e5, maxEntityCount: 100, allowedTags: null, tagFilter: null } : "object" == typeof t6 && null !== t6 ? { enabled: false !== t6.enabled, maxEntitySize: Math.max(1, t6.maxEntitySize ?? 1e4), maxExpansionDepth: Math.max(1, t6.maxExpansionDepth ?? 10), maxTotalExpansions: Math.max(1, t6.maxTotalExpansions ?? 1e3), maxExpandedLength: Math.max(1, t6.maxExpandedLength ?? 1e5), maxEntityCount: Math.max(1, t6.maxEntityCount ?? 100), allowedTags: t6.allowedTags ?? null, tagFilter: t6.tagFilter ?? null } : A2(true); - } - const O = function(t6) { - const e6 = Object.assign({}, P, t6), i6 = [{ value: e6.attributeNamePrefix, name: "attributeNamePrefix" }, { value: e6.attributesGroupName, name: "attributesGroupName" }, { value: e6.textNodeName, name: "textNodeName" }, { value: e6.cdataPropName, name: "cdataPropName" }, { value: e6.commentPropName, name: "commentPropName" }]; - for (const { value: t7, name: e7 } of i6) t7 && S(t7, e7); - return null === e6.onDangerousProperty && (e6.onDangerousProperty = T), e6.processEntities = A2(e6.processEntities), e6.stopNodes && Array.isArray(e6.stopNodes) && (e6.stopNodes = e6.stopNodes.map((t7) => "string" == typeof t7 && t7.startsWith("*.") ? ".." + t7.substring(2) : t7)), e6; - }; - let C2; - C2 = "function" != typeof Symbol ? "@@xmlMetadata" : /* @__PURE__ */ Symbol("XML Node Metadata"); - class $ { - constructor(t6) { - this.tagname = t6, this.child = [], this[":@"] = /* @__PURE__ */ Object.create(null); - } - add(t6, e6) { - "__proto__" === t6 && (t6 = "#__proto__"), this.child.push({ [t6]: e6 }); - } - addChild(t6, e6) { - "__proto__" === t6.tagname && (t6.tagname = "#__proto__"), t6[":@"] && Object.keys(t6[":@"]).length > 0 ? this.child.push({ [t6.tagname]: t6.child, ":@": t6[":@"] }) : this.child.push({ [t6.tagname]: t6.child }), void 0 !== e6 && (this.child[this.child.length - 1][C2] = { startIndex: e6 }); - } - static getMetaDataSymbol() { - return C2; - } - } - class I2 { - constructor(t6) { - this.suppressValidationErr = !t6, this.options = t6; - } - readDocType(t6, e6) { - const i6 = /* @__PURE__ */ Object.create(null); - let n6 = 0; - if ("O" !== t6[e6 + 3] || "C" !== t6[e6 + 4] || "T" !== t6[e6 + 5] || "Y" !== t6[e6 + 6] || "P" !== t6[e6 + 7] || "E" !== t6[e6 + 8]) throw new Error("Invalid Tag instead of DOCTYPE"); - { - e6 += 9; - let s6 = 1, r6 = false, o6 = false, a6 = ""; - for (; e6 < t6.length; e6++) if ("<" !== t6[e6] || o6) if (">" === t6[e6]) { - if (o6 ? "-" === t6[e6 - 1] && "-" === t6[e6 - 2] && (o6 = false, s6--) : s6--, 0 === s6) break; - } else "[" === t6[e6] ? r6 = true : a6 += t6[e6]; - else { - if (r6 && M(t6, "!ENTITY", e6)) { - let s7, r7; - if (e6 += 7, [s7, r7, e6] = this.readEntityExp(t6, e6 + 1, this.suppressValidationErr), -1 === r7.indexOf("&")) { - if (false !== this.options.enabled && null != this.options.maxEntityCount && n6 >= this.options.maxEntityCount) throw new Error(`Entity count (${n6 + 1}) exceeds maximum allowed (${this.options.maxEntityCount})`); - const t7 = s7.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); - i6[s7] = { regx: RegExp(`&${t7};`, "g"), val: r7 }, n6++; - } - } else if (r6 && M(t6, "!ELEMENT", e6)) { - e6 += 8; - const { index: i7 } = this.readElementExp(t6, e6 + 1); - e6 = i7; - } else if (r6 && M(t6, "!ATTLIST", e6)) e6 += 8; - else if (r6 && M(t6, "!NOTATION", e6)) { - e6 += 9; - const { index: i7 } = this.readNotationExp(t6, e6 + 1, this.suppressValidationErr); - e6 = i7; - } else { - if (!M(t6, "!--", e6)) throw new Error("Invalid DOCTYPE"); - o6 = true; - } - s6++, a6 = ""; - } - if (0 !== s6) throw new Error("Unclosed DOCTYPE"); - } - return { entities: i6, i: e6 }; - } - readEntityExp(t6, e6) { - const i6 = e6 = j5(t6, e6); - for (; e6 < t6.length && !/\s/.test(t6[e6]) && '"' !== t6[e6] && "'" !== t6[e6]; ) e6++; - let n6 = t6.substring(i6, e6); - if (_(n6), e6 = j5(t6, e6), !this.suppressValidationErr) { - if ("SYSTEM" === t6.substring(e6, e6 + 6).toUpperCase()) throw new Error("External entities are not supported"); - if ("%" === t6[e6]) throw new Error("Parameter entities are not supported"); - } - let s6 = ""; - if ([e6, s6] = this.readIdentifierVal(t6, e6, "entity"), false !== this.options.enabled && null != this.options.maxEntitySize && s6.length > this.options.maxEntitySize) throw new Error(`Entity "${n6}" size (${s6.length}) exceeds maximum allowed size (${this.options.maxEntitySize})`); - return [n6, s6, --e6]; - } - readNotationExp(t6, e6) { - const i6 = e6 = j5(t6, e6); - for (; e6 < t6.length && !/\s/.test(t6[e6]); ) e6++; - let n6 = t6.substring(i6, e6); - !this.suppressValidationErr && _(n6), e6 = j5(t6, e6); - const s6 = t6.substring(e6, e6 + 6).toUpperCase(); - if (!this.suppressValidationErr && "SYSTEM" !== s6 && "PUBLIC" !== s6) throw new Error(`Expected SYSTEM or PUBLIC, found "${s6}"`); - e6 += s6.length, e6 = j5(t6, e6); - let r6 = null, o6 = null; - if ("PUBLIC" === s6) [e6, r6] = this.readIdentifierVal(t6, e6, "publicIdentifier"), '"' !== t6[e6 = j5(t6, e6)] && "'" !== t6[e6] || ([e6, o6] = this.readIdentifierVal(t6, e6, "systemIdentifier")); - else if ("SYSTEM" === s6 && ([e6, o6] = this.readIdentifierVal(t6, e6, "systemIdentifier"), !this.suppressValidationErr && !o6)) throw new Error("Missing mandatory system identifier for SYSTEM notation"); - return { notationName: n6, publicIdentifier: r6, systemIdentifier: o6, index: --e6 }; - } - readIdentifierVal(t6, e6, i6) { - let n6 = ""; - const s6 = t6[e6]; - if ('"' !== s6 && "'" !== s6) throw new Error(`Expected quoted string, found "${s6}"`); - const r6 = ++e6; - for (; e6 < t6.length && t6[e6] !== s6; ) e6++; - if (n6 = t6.substring(r6, e6), t6[e6] !== s6) throw new Error(`Unterminated ${i6} value`); - return [++e6, n6]; - } - readElementExp(t6, e6) { - const i6 = e6 = j5(t6, e6); - for (; e6 < t6.length && !/\s/.test(t6[e6]); ) e6++; - let n6 = t6.substring(i6, e6); - if (!this.suppressValidationErr && !r5(n6)) throw new Error(`Invalid element name: "${n6}"`); - let s6 = ""; - if ("E" === t6[e6 = j5(t6, e6)] && M(t6, "MPTY", e6)) e6 += 4; - else if ("A" === t6[e6] && M(t6, "NY", e6)) e6 += 2; - else if ("(" === t6[e6]) { - const i7 = ++e6; - for (; e6 < t6.length && ")" !== t6[e6]; ) e6++; - if (s6 = t6.substring(i7, e6), ")" !== t6[e6]) throw new Error("Unterminated content model"); - } else if (!this.suppressValidationErr) throw new Error(`Invalid Element Expression, found "${t6[e6]}"`); - return { elementName: n6, contentModel: s6.trim(), index: e6 }; - } - readAttlistExp(t6, e6) { - let i6 = e6 = j5(t6, e6); - for (; e6 < t6.length && !/\s/.test(t6[e6]); ) e6++; - let n6 = t6.substring(i6, e6); - for (_(n6), i6 = e6 = j5(t6, e6); e6 < t6.length && !/\s/.test(t6[e6]); ) e6++; - let s6 = t6.substring(i6, e6); - if (!_(s6)) throw new Error(`Invalid attribute name: "${s6}"`); - e6 = j5(t6, e6); - let r6 = ""; - if ("NOTATION" === t6.substring(e6, e6 + 8).toUpperCase()) { - if (r6 = "NOTATION", "(" !== t6[e6 = j5(t6, e6 += 8)]) throw new Error(`Expected '(', found "${t6[e6]}"`); - e6++; - let i7 = []; - for (; e6 < t6.length && ")" !== t6[e6]; ) { - const n7 = e6; - for (; e6 < t6.length && "|" !== t6[e6] && ")" !== t6[e6]; ) e6++; - let s7 = t6.substring(n7, e6); - if (s7 = s7.trim(), !_(s7)) throw new Error(`Invalid notation name: "${s7}"`); - i7.push(s7), "|" === t6[e6] && (e6++, e6 = j5(t6, e6)); - } - if (")" !== t6[e6]) throw new Error("Unterminated list of notations"); - e6++, r6 += " (" + i7.join("|") + ")"; - } else { - const i7 = e6; - for (; e6 < t6.length && !/\s/.test(t6[e6]); ) e6++; - r6 += t6.substring(i7, e6); - const n7 = ["CDATA", "ID", "IDREF", "IDREFS", "ENTITY", "ENTITIES", "NMTOKEN", "NMTOKENS"]; - if (!this.suppressValidationErr && !n7.includes(r6.toUpperCase())) throw new Error(`Invalid attribute type: "${r6}"`); - } - e6 = j5(t6, e6); - let o6 = ""; - return "#REQUIRED" === t6.substring(e6, e6 + 8).toUpperCase() ? (o6 = "#REQUIRED", e6 += 8) : "#IMPLIED" === t6.substring(e6, e6 + 7).toUpperCase() ? (o6 = "#IMPLIED", e6 += 7) : [e6, o6] = this.readIdentifierVal(t6, e6, "ATTLIST"), { elementName: n6, attributeName: s6, attributeType: r6, defaultValue: o6, index: e6 }; - } - } - const j5 = (t6, e6) => { - for (; e6 < t6.length && /\s/.test(t6[e6]); ) e6++; - return e6; - }; - function M(t6, e6, i6) { - for (let n6 = 0; n6 < e6.length; n6++) if (e6[n6] !== t6[i6 + n6 + 1]) return false; - return true; - } - function _(t6) { - if (r5(t6)) return t6; - throw new Error(`Invalid entity name ${t6}`); - } - const D2 = /^[-+]?0x[a-fA-F0-9]+$/, V = /^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/, k5 = { hex: true, leadingZeros: true, decimalPoint: ".", eNotation: true, infinity: "original" }; - const F2 = /^([-+])?(0*)(\d*(\.\d*)?[eE][-\+]?\d+)$/, L = /* @__PURE__ */ new Set(["push", "pop", "reset", "updateCurrent", "restore"]); - class G2 { - constructor(t6 = {}) { - this.separator = t6.separator || ".", this.path = [], this.siblingStacks = []; - } - push(t6, e6 = null, i6 = null) { - this.path.length > 0 && (this.path[this.path.length - 1].values = void 0); - const n6 = this.path.length; - this.siblingStacks[n6] || (this.siblingStacks[n6] = /* @__PURE__ */ new Map()); - const s6 = this.siblingStacks[n6], r6 = i6 ? `${i6}:${t6}` : t6, o6 = s6.get(r6) || 0; - let a6 = 0; - for (const t7 of s6.values()) a6 += t7; - s6.set(r6, o6 + 1); - const h6 = { tag: t6, position: a6, counter: o6 }; - null != i6 && (h6.namespace = i6), null != e6 && (h6.values = e6), this.path.push(h6); - } - pop() { - if (0 === this.path.length) return; - const t6 = this.path.pop(); - return this.siblingStacks.length > this.path.length + 1 && (this.siblingStacks.length = this.path.length + 1), t6; - } - updateCurrent(t6) { - if (this.path.length > 0) { - const e6 = this.path[this.path.length - 1]; - null != t6 && (e6.values = t6); - } - } - getCurrentTag() { - return this.path.length > 0 ? this.path[this.path.length - 1].tag : void 0; - } - getCurrentNamespace() { - return this.path.length > 0 ? this.path[this.path.length - 1].namespace : void 0; - } - getAttrValue(t6) { - if (0 === this.path.length) return; - const e6 = this.path[this.path.length - 1]; - return e6.values?.[t6]; - } - hasAttr(t6) { - if (0 === this.path.length) return false; - const e6 = this.path[this.path.length - 1]; - return void 0 !== e6.values && t6 in e6.values; - } - getPosition() { - return 0 === this.path.length ? -1 : this.path[this.path.length - 1].position ?? 0; - } - getCounter() { - return 0 === this.path.length ? -1 : this.path[this.path.length - 1].counter ?? 0; - } - getIndex() { - return this.getPosition(); - } - getDepth() { - return this.path.length; - } - toString(t6, e6 = true) { - const i6 = t6 || this.separator; - return this.path.map((t7) => e6 && t7.namespace ? `${t7.namespace}:${t7.tag}` : t7.tag).join(i6); - } - toArray() { - return this.path.map((t6) => t6.tag); - } - reset() { - this.path = [], this.siblingStacks = []; - } - matches(t6) { - const e6 = t6.segments; - return 0 !== e6.length && (t6.hasDeepWildcard() ? this._matchWithDeepWildcard(e6) : this._matchSimple(e6)); - } - _matchSimple(t6) { - if (this.path.length !== t6.length) return false; - for (let e6 = 0; e6 < t6.length; e6++) { - const i6 = t6[e6], n6 = this.path[e6], s6 = e6 === this.path.length - 1; - if (!this._matchSegment(i6, n6, s6)) return false; - } - return true; - } - _matchWithDeepWildcard(t6) { - let e6 = this.path.length - 1, i6 = t6.length - 1; - for (; i6 >= 0 && e6 >= 0; ) { - const n6 = t6[i6]; - if ("deep-wildcard" === n6.type) { - if (i6--, i6 < 0) return true; - const n7 = t6[i6]; - let s6 = false; - for (let t7 = e6; t7 >= 0; t7--) { - const r6 = t7 === this.path.length - 1; - if (this._matchSegment(n7, this.path[t7], r6)) { - e6 = t7 - 1, i6--, s6 = true; - break; - } - } - if (!s6) return false; - } else { - const t7 = e6 === this.path.length - 1; - if (!this._matchSegment(n6, this.path[e6], t7)) return false; - e6--, i6--; - } - } - return i6 < 0; - } - _matchSegment(t6, e6, i6) { - if ("*" !== t6.tag && t6.tag !== e6.tag) return false; - if (void 0 !== t6.namespace && "*" !== t6.namespace && t6.namespace !== e6.namespace) return false; - if (void 0 !== t6.attrName) { - if (!i6) return false; - if (!e6.values || !(t6.attrName in e6.values)) return false; - if (void 0 !== t6.attrValue) { - const i7 = e6.values[t6.attrName]; - if (String(i7) !== String(t6.attrValue)) return false; - } - } - if (void 0 !== t6.position) { - if (!i6) return false; - const n6 = e6.counter ?? 0; - if ("first" === t6.position && 0 !== n6) return false; - if ("odd" === t6.position && n6 % 2 != 1) return false; - if ("even" === t6.position && n6 % 2 != 0) return false; - if ("nth" === t6.position && n6 !== t6.positionValue) return false; - } - return true; - } - snapshot() { - return { path: this.path.map((t6) => ({ ...t6 })), siblingStacks: this.siblingStacks.map((t6) => new Map(t6)) }; - } - restore(t6) { - this.path = t6.path.map((t7) => ({ ...t7 })), this.siblingStacks = t6.siblingStacks.map((t7) => new Map(t7)); - } - readOnly() { - return new Proxy(this, { get(t6, e6, i6) { - if (L.has(e6)) return () => { - throw new TypeError(`Cannot call '${e6}' on a read-only Matcher. Obtain a writable instance to mutate state.`); - }; - const n6 = Reflect.get(t6, e6, i6); - return "path" === e6 || "siblingStacks" === e6 ? Object.freeze(Array.isArray(n6) ? n6.map((t7) => t7 instanceof Map ? Object.freeze(new Map(t7)) : Object.freeze({ ...t7 })) : n6) : "function" == typeof n6 ? n6.bind(t6) : n6; - }, set(t6, e6) { - throw new TypeError(`Cannot set property '${String(e6)}' on a read-only Matcher.`); - }, deleteProperty(t6, e6) { - throw new TypeError(`Cannot delete property '${String(e6)}' from a read-only Matcher.`); - } }); - } - } - class R { - constructor(t6, e6 = {}) { - this.pattern = t6, this.separator = e6.separator || ".", this.segments = this._parse(t6), this._hasDeepWildcard = this.segments.some((t7) => "deep-wildcard" === t7.type), this._hasAttributeCondition = this.segments.some((t7) => void 0 !== t7.attrName), this._hasPositionSelector = this.segments.some((t7) => void 0 !== t7.position); - } - _parse(t6) { - const e6 = []; - let i6 = 0, n6 = ""; - for (; i6 < t6.length; ) t6[i6] === this.separator ? i6 + 1 < t6.length && t6[i6 + 1] === this.separator ? (n6.trim() && (e6.push(this._parseSegment(n6.trim())), n6 = ""), e6.push({ type: "deep-wildcard" }), i6 += 2) : (n6.trim() && e6.push(this._parseSegment(n6.trim())), n6 = "", i6++) : (n6 += t6[i6], i6++); - return n6.trim() && e6.push(this._parseSegment(n6.trim())), e6; - } - _parseSegment(t6) { - const e6 = { type: "tag" }; - let i6 = null, n6 = t6; - const s6 = t6.match(/^([^\[]+)(\[[^\]]*\])(.*)$/); - if (s6 && (n6 = s6[1] + s6[3], s6[2])) { - const t7 = s6[2].slice(1, -1); - t7 && (i6 = t7); - } - let r6, o6, a6 = n6; - if (n6.includes("::")) { - const e7 = n6.indexOf("::"); - if (r6 = n6.substring(0, e7).trim(), a6 = n6.substring(e7 + 2).trim(), !r6) throw new Error(`Invalid namespace in pattern: ${t6}`); - } - let h6 = null; - if (a6.includes(":")) { - const t7 = a6.lastIndexOf(":"), e7 = a6.substring(0, t7).trim(), i7 = a6.substring(t7 + 1).trim(); - ["first", "last", "odd", "even"].includes(i7) || /^nth\(\d+\)$/.test(i7) ? (o6 = e7, h6 = i7) : o6 = a6; - } else o6 = a6; - if (!o6) throw new Error(`Invalid segment pattern: ${t6}`); - if (e6.tag = o6, r6 && (e6.namespace = r6), i6) if (i6.includes("=")) { - const t7 = i6.indexOf("="); - e6.attrName = i6.substring(0, t7).trim(), e6.attrValue = i6.substring(t7 + 1).trim(); - } else e6.attrName = i6.trim(); - if (h6) { - const t7 = h6.match(/^nth\((\d+)\)$/); - t7 ? (e6.position = "nth", e6.positionValue = parseInt(t7[1], 10)) : e6.position = h6; - } - return e6; - } - get length() { - return this.segments.length; - } - hasDeepWildcard() { - return this._hasDeepWildcard; - } - hasAttributeCondition() { - return this._hasAttributeCondition; - } - hasPositionSelector() { - return this._hasPositionSelector; - } - toString() { - return this.pattern; - } - } - function U(t6, e6) { - if (!t6) return {}; - const i6 = e6.attributesGroupName ? t6[e6.attributesGroupName] : t6; - if (!i6) return {}; - const n6 = {}; - for (const t7 in i6) t7.startsWith(e6.attributeNamePrefix) ? n6[t7.substring(e6.attributeNamePrefix.length)] = i6[t7] : n6[t7] = i6[t7]; - return n6; - } - function B2(t6) { - if (!t6 || "string" != typeof t6) return; - const e6 = t6.indexOf(":"); - if (-1 !== e6 && e6 > 0) { - const i6 = t6.substring(0, e6); - if ("xmlns" !== i6) return i6; - } - } - class W { - constructor(t6) { - var e6; - if (this.options = t6, this.currentNode = null, this.tagsNodeStack = [], this.docTypeEntities = {}, this.lastEntities = { apos: { regex: /&(apos|#39|#x27);/g, val: "'" }, gt: { regex: /&(gt|#62|#x3E);/g, val: ">" }, lt: { regex: /&(lt|#60|#x3C);/g, val: "<" }, quot: { regex: /&(quot|#34|#x22);/g, val: '"' } }, this.ampEntity = { regex: /&(amp|#38|#x26);/g, val: "&" }, this.htmlEntities = { space: { regex: /&(nbsp|#160);/g, val: " " }, cent: { regex: /&(cent|#162);/g, val: "\xA2" }, pound: { regex: /&(pound|#163);/g, val: "\xA3" }, yen: { regex: /&(yen|#165);/g, val: "\xA5" }, euro: { regex: /&(euro|#8364);/g, val: "\u20AC" }, copyright: { regex: /&(copy|#169);/g, val: "\xA9" }, reg: { regex: /&(reg|#174);/g, val: "\xAE" }, inr: { regex: /&(inr|#8377);/g, val: "\u20B9" }, num_dec: { regex: /&#([0-9]{1,7});/g, val: (t7, e7) => rt(e7, 10, "&#") }, num_hex: { regex: /&#x([0-9a-fA-F]{1,6});/g, val: (t7, e7) => rt(e7, 16, "&#x") } }, this.addExternalEntities = Y, this.parseXml = J2, this.parseTextData = z3, this.resolveNameSpace = X, this.buildAttributesMap = Z, this.isItStopNode = tt, this.replaceEntitiesValue = Q, this.readStopNodeData = nt, this.saveTextToParentTag = H2, this.addChild = K, this.ignoreAttributesFn = "function" == typeof (e6 = this.options.ignoreAttributes) ? e6 : Array.isArray(e6) ? (t7) => { - for (const i6 of e6) { - if ("string" == typeof i6 && t7 === i6) return true; - if (i6 instanceof RegExp && i6.test(t7)) return true; - } - } : () => false, this.entityExpansionCount = 0, this.currentExpandedLength = 0, this.matcher = new G2(), this.readonlyMatcher = this.matcher.readOnly(), this.isCurrentNodeStopNode = false, this.options.stopNodes && this.options.stopNodes.length > 0) { - this.stopNodeExpressions = []; - for (let t7 = 0; t7 < this.options.stopNodes.length; t7++) { - const e7 = this.options.stopNodes[t7]; - "string" == typeof e7 ? this.stopNodeExpressions.push(new R(e7)) : e7 instanceof R && this.stopNodeExpressions.push(e7); - } - } - } - } - function Y(t6) { - const e6 = Object.keys(t6); - for (let i6 = 0; i6 < e6.length; i6++) { - const n6 = e6[i6], s6 = n6.replace(/[.\-+*:]/g, "\\."); - this.lastEntities[n6] = { regex: new RegExp("&" + s6 + ";", "g"), val: t6[n6] }; - } - } - function z3(t6, e6, i6, n6, s6, r6, o6) { - if (void 0 !== t6 && (this.options.trimValues && !n6 && (t6 = t6.trim()), t6.length > 0)) { - o6 || (t6 = this.replaceEntitiesValue(t6, e6, i6)); - const n7 = this.options.jPath ? i6.toString() : i6, a6 = this.options.tagValueProcessor(e6, t6, n7, s6, r6); - return null == a6 ? t6 : typeof a6 != typeof t6 || a6 !== t6 ? a6 : this.options.trimValues || t6.trim() === t6 ? st(t6, this.options.parseTagValue, this.options.numberParseOptions) : t6; - } - } - function X(t6) { - if (this.options.removeNSPrefix) { - const e6 = t6.split(":"), i6 = "/" === t6.charAt(0) ? "/" : ""; - if ("xmlns" === e6[0]) return ""; - 2 === e6.length && (t6 = i6 + e6[1]); - } - return t6; - } - const q5 = new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`, "gm"); - function Z(t6, e6, i6) { - if (true !== this.options.ignoreAttributes && "string" == typeof t6) { - const n6 = s5(t6, q5), r6 = n6.length, o6 = {}, a6 = {}; - for (let t7 = 0; t7 < r6; t7++) { - const e7 = this.resolveNameSpace(n6[t7][1]), s6 = n6[t7][4]; - if (e7.length && void 0 !== s6) { - let t8 = s6; - this.options.trimValues && (t8 = t8.trim()), t8 = this.replaceEntitiesValue(t8, i6, this.readonlyMatcher), a6[e7] = t8; - } - } - Object.keys(a6).length > 0 && "object" == typeof e6 && e6.updateCurrent && e6.updateCurrent(a6); - for (let t7 = 0; t7 < r6; t7++) { - const s6 = this.resolveNameSpace(n6[t7][1]), r7 = this.options.jPath ? e6.toString() : this.readonlyMatcher; - if (this.ignoreAttributesFn(s6, r7)) continue; - let a7 = n6[t7][4], h6 = this.options.attributeNamePrefix + s6; - if (s6.length) if (this.options.transformAttributeName && (h6 = this.options.transformAttributeName(h6)), h6 = at(h6, this.options), void 0 !== a7) { - this.options.trimValues && (a7 = a7.trim()), a7 = this.replaceEntitiesValue(a7, i6, this.readonlyMatcher); - const t8 = this.options.jPath ? e6.toString() : this.readonlyMatcher, n7 = this.options.attributeValueProcessor(s6, a7, t8); - o6[h6] = null == n7 ? a7 : typeof n7 != typeof a7 || n7 !== a7 ? n7 : st(a7, this.options.parseAttributeValue, this.options.numberParseOptions); - } else this.options.allowBooleanAttributes && (o6[h6] = true); - } - if (!Object.keys(o6).length) return; - if (this.options.attributesGroupName) { - const t7 = {}; - return t7[this.options.attributesGroupName] = o6, t7; - } - return o6; - } - } - const J2 = function(t6) { - t6 = t6.replace(/\r\n?/g, "\n"); - const e6 = new $("!xml"); - let i6 = e6, n6 = ""; - this.matcher.reset(), this.entityExpansionCount = 0, this.currentExpandedLength = 0; - const s6 = new I2(this.options.processEntities); - for (let r6 = 0; r6 < t6.length; r6++) if ("<" === t6[r6]) if ("/" === t6[r6 + 1]) { - const e7 = et(t6, ">", r6, "Closing Tag is not closed."); - let s7 = t6.substring(r6 + 2, e7).trim(); - if (this.options.removeNSPrefix) { - const t7 = s7.indexOf(":"); - -1 !== t7 && (s7 = s7.substr(t7 + 1)); - } - s7 = ot(this.options.transformTagName, s7, "", this.options).tagName, i6 && (n6 = this.saveTextToParentTag(n6, i6, this.readonlyMatcher)); - const o6 = this.matcher.getCurrentTag(); - if (s7 && -1 !== this.options.unpairedTags.indexOf(s7)) throw new Error(`Unpaired tag can not be used as closing tag: `); - o6 && -1 !== this.options.unpairedTags.indexOf(o6) && (this.matcher.pop(), this.tagsNodeStack.pop()), this.matcher.pop(), this.isCurrentNodeStopNode = false, i6 = this.tagsNodeStack.pop(), n6 = "", r6 = e7; - } else if ("?" === t6[r6 + 1]) { - let e7 = it(t6, r6, false, "?>"); - if (!e7) throw new Error("Pi Tag is not closed."); - if (n6 = this.saveTextToParentTag(n6, i6, this.readonlyMatcher), this.options.ignoreDeclaration && "?xml" === e7.tagName || this.options.ignorePiTags) ; - else { - const t7 = new $(e7.tagName); - t7.add(this.options.textNodeName, ""), e7.tagName !== e7.tagExp && e7.attrExpPresent && (t7[":@"] = this.buildAttributesMap(e7.tagExp, this.matcher, e7.tagName)), this.addChild(i6, t7, this.readonlyMatcher, r6); - } - r6 = e7.closeIndex + 1; - } else if ("!--" === t6.substr(r6 + 1, 3)) { - const e7 = et(t6, "-->", r6 + 4, "Comment is not closed."); - if (this.options.commentPropName) { - const s7 = t6.substring(r6 + 4, e7 - 2); - n6 = this.saveTextToParentTag(n6, i6, this.readonlyMatcher), i6.add(this.options.commentPropName, [{ [this.options.textNodeName]: s7 }]); - } - r6 = e7; - } else if ("!D" === t6.substr(r6 + 1, 2)) { - const e7 = s6.readDocType(t6, r6); - this.docTypeEntities = e7.entities, r6 = e7.i; - } else if ("![" === t6.substr(r6 + 1, 2)) { - const e7 = et(t6, "]]>", r6, "CDATA is not closed.") - 2, s7 = t6.substring(r6 + 9, e7); - n6 = this.saveTextToParentTag(n6, i6, this.readonlyMatcher); - let o6 = this.parseTextData(s7, i6.tagname, this.readonlyMatcher, true, false, true, true); - null == o6 && (o6 = ""), this.options.cdataPropName ? i6.add(this.options.cdataPropName, [{ [this.options.textNodeName]: s7 }]) : i6.add(this.options.textNodeName, o6), r6 = e7 + 2; - } else { - let s7 = it(t6, r6, this.options.removeNSPrefix); - if (!s7) { - const e7 = t6.substring(Math.max(0, r6 - 50), Math.min(t6.length, r6 + 50)); - throw new Error(`readTagExp returned undefined at position ${r6}. Context: "${e7}"`); - } - let o6 = s7.tagName; - const a6 = s7.rawTagName; - let h6 = s7.tagExp, l6 = s7.attrExpPresent, p6 = s7.closeIndex; - if ({ tagName: o6, tagExp: h6 } = ot(this.options.transformTagName, o6, h6, this.options), this.options.strictReservedNames && (o6 === this.options.commentPropName || o6 === this.options.cdataPropName || o6 === this.options.textNodeName || o6 === this.options.attributesGroupName)) throw new Error(`Invalid tag name: ${o6}`); - i6 && n6 && "!xml" !== i6.tagname && (n6 = this.saveTextToParentTag(n6, i6, this.readonlyMatcher, false)); - const u6 = i6; - u6 && -1 !== this.options.unpairedTags.indexOf(u6.tagname) && (i6 = this.tagsNodeStack.pop(), this.matcher.pop()); - let c6 = false; - h6.length > 0 && h6.lastIndexOf("/") === h6.length - 1 && (c6 = true, "/" === o6[o6.length - 1] ? (o6 = o6.substr(0, o6.length - 1), h6 = o6) : h6 = h6.substr(0, h6.length - 1), l6 = o6 !== h6); - let d6, f6 = null, g6 = {}; - d6 = B2(a6), o6 !== e6.tagname && this.matcher.push(o6, {}, d6), o6 !== h6 && l6 && (f6 = this.buildAttributesMap(h6, this.matcher, o6), f6 && (g6 = U(f6, this.options))), o6 !== e6.tagname && (this.isCurrentNodeStopNode = this.isItStopNode(this.stopNodeExpressions, this.matcher)); - const m6 = r6; - if (this.isCurrentNodeStopNode) { - let e7 = ""; - if (c6) r6 = s7.closeIndex; - else if (-1 !== this.options.unpairedTags.indexOf(o6)) r6 = s7.closeIndex; - else { - const i7 = this.readStopNodeData(t6, a6, p6 + 1); - if (!i7) throw new Error(`Unexpected end of ${a6}`); - r6 = i7.i, e7 = i7.tagContent; - } - const n7 = new $(o6); - f6 && (n7[":@"] = f6), n7.add(this.options.textNodeName, e7), this.matcher.pop(), this.isCurrentNodeStopNode = false, this.addChild(i6, n7, this.readonlyMatcher, m6); - } else { - if (c6) { - ({ tagName: o6, tagExp: h6 } = ot(this.options.transformTagName, o6, h6, this.options)); - const t7 = new $(o6); - f6 && (t7[":@"] = f6), this.addChild(i6, t7, this.readonlyMatcher, m6), this.matcher.pop(), this.isCurrentNodeStopNode = false; - } else { - if (-1 !== this.options.unpairedTags.indexOf(o6)) { - const t7 = new $(o6); - f6 && (t7[":@"] = f6), this.addChild(i6, t7, this.readonlyMatcher, m6), this.matcher.pop(), this.isCurrentNodeStopNode = false, r6 = s7.closeIndex; - continue; - } - { - const t7 = new $(o6); - if (this.tagsNodeStack.length > this.options.maxNestedTags) throw new Error("Maximum nested tags exceeded"); - this.tagsNodeStack.push(i6), f6 && (t7[":@"] = f6), this.addChild(i6, t7, this.readonlyMatcher, m6), i6 = t7; - } - } - n6 = "", r6 = p6; - } - } - else n6 += t6[r6]; - return e6.child; - }; - function K(t6, e6, i6, n6) { - this.options.captureMetaData || (n6 = void 0); - const s6 = this.options.jPath ? i6.toString() : i6, r6 = this.options.updateTag(e6.tagname, s6, e6[":@"]); - false === r6 || ("string" == typeof r6 ? (e6.tagname = r6, t6.addChild(e6, n6)) : t6.addChild(e6, n6)); - } - function Q(t6, e6, i6) { - const n6 = this.options.processEntities; - if (!n6 || !n6.enabled) return t6; - if (n6.allowedTags) { - const s6 = this.options.jPath ? i6.toString() : i6; - if (!(Array.isArray(n6.allowedTags) ? n6.allowedTags.includes(e6) : n6.allowedTags(e6, s6))) return t6; - } - if (n6.tagFilter) { - const s6 = this.options.jPath ? i6.toString() : i6; - if (!n6.tagFilter(e6, s6)) return t6; - } - for (const e7 of Object.keys(this.docTypeEntities)) { - const i7 = this.docTypeEntities[e7], s6 = t6.match(i7.regx); - if (s6) { - if (this.entityExpansionCount += s6.length, n6.maxTotalExpansions && this.entityExpansionCount > n6.maxTotalExpansions) throw new Error(`Entity expansion limit exceeded: ${this.entityExpansionCount} > ${n6.maxTotalExpansions}`); - const e8 = t6.length; - if (t6 = t6.replace(i7.regx, i7.val), n6.maxExpandedLength && (this.currentExpandedLength += t6.length - e8, this.currentExpandedLength > n6.maxExpandedLength)) throw new Error(`Total expanded content size exceeded: ${this.currentExpandedLength} > ${n6.maxExpandedLength}`); - } - } - for (const e7 of Object.keys(this.lastEntities)) { - const i7 = this.lastEntities[e7], s6 = t6.match(i7.regex); - if (s6 && (this.entityExpansionCount += s6.length, n6.maxTotalExpansions && this.entityExpansionCount > n6.maxTotalExpansions)) throw new Error(`Entity expansion limit exceeded: ${this.entityExpansionCount} > ${n6.maxTotalExpansions}`); - t6 = t6.replace(i7.regex, i7.val); - } - if (-1 === t6.indexOf("&")) return t6; - if (this.options.htmlEntities) for (const e7 of Object.keys(this.htmlEntities)) { - const i7 = this.htmlEntities[e7], s6 = t6.match(i7.regex); - if (s6 && (this.entityExpansionCount += s6.length, n6.maxTotalExpansions && this.entityExpansionCount > n6.maxTotalExpansions)) throw new Error(`Entity expansion limit exceeded: ${this.entityExpansionCount} > ${n6.maxTotalExpansions}`); - t6 = t6.replace(i7.regex, i7.val); - } - return t6.replace(this.ampEntity.regex, this.ampEntity.val); - } - function H2(t6, e6, i6, n6) { - return t6 && (void 0 === n6 && (n6 = 0 === e6.child.length), void 0 !== (t6 = this.parseTextData(t6, e6.tagname, i6, false, !!e6[":@"] && 0 !== Object.keys(e6[":@"]).length, n6)) && "" !== t6 && e6.add(this.options.textNodeName, t6), t6 = ""), t6; - } - function tt(t6, e6) { - if (!t6 || 0 === t6.length) return false; - for (let i6 = 0; i6 < t6.length; i6++) if (e6.matches(t6[i6])) return true; - return false; - } - function et(t6, e6, i6, n6) { - const s6 = t6.indexOf(e6, i6); - if (-1 === s6) throw new Error(n6); - return s6 + e6.length - 1; - } - function it(t6, e6, i6, n6 = ">") { - const s6 = (function(t7, e7, i7 = ">") { - let n7, s7 = ""; - for (let r7 = e7; r7 < t7.length; r7++) { - let e8 = t7[r7]; - if (n7) e8 === n7 && (n7 = ""); - else if ('"' === e8 || "'" === e8) n7 = e8; - else if (e8 === i7[0]) { - if (!i7[1]) return { data: s7, index: r7 }; - if (t7[r7 + 1] === i7[1]) return { data: s7, index: r7 }; - } else " " === e8 && (e8 = " "); - s7 += e8; - } - })(t6, e6 + 1, n6); - if (!s6) return; - let r6 = s6.data; - const o6 = s6.index, a6 = r6.search(/\s/); - let h6 = r6, l6 = true; - -1 !== a6 && (h6 = r6.substring(0, a6), r6 = r6.substring(a6 + 1).trimStart()); - const p6 = h6; - if (i6) { - const t7 = h6.indexOf(":"); - -1 !== t7 && (h6 = h6.substr(t7 + 1), l6 = h6 !== s6.data.substr(t7 + 1)); - } - return { tagName: h6, tagExp: r6, closeIndex: o6, attrExpPresent: l6, rawTagName: p6 }; - } - function nt(t6, e6, i6) { - const n6 = i6; - let s6 = 1; - for (; i6 < t6.length; i6++) if ("<" === t6[i6]) if ("/" === t6[i6 + 1]) { - const r6 = et(t6, ">", i6, `${e6} is not closed`); - if (t6.substring(i6 + 2, r6).trim() === e6 && (s6--, 0 === s6)) return { tagContent: t6.substring(n6, i6), i: r6 }; - i6 = r6; - } else if ("?" === t6[i6 + 1]) i6 = et(t6, "?>", i6 + 1, "StopNode is not closed."); - else if ("!--" === t6.substr(i6 + 1, 3)) i6 = et(t6, "-->", i6 + 3, "StopNode is not closed."); - else if ("![" === t6.substr(i6 + 1, 2)) i6 = et(t6, "]]>", i6, "StopNode is not closed.") - 2; - else { - const n7 = it(t6, i6, ">"); - n7 && ((n7 && n7.tagName) === e6 && "/" !== n7.tagExp[n7.tagExp.length - 1] && s6++, i6 = n7.closeIndex); - } - } - function st(t6, e6, i6) { - if (e6 && "string" == typeof t6) { - const e7 = t6.trim(); - return "true" === e7 || "false" !== e7 && (function(t7, e8 = {}) { - if (e8 = Object.assign({}, k5, e8), !t7 || "string" != typeof t7) return t7; - let i7 = t7.trim(); - if (void 0 !== e8.skipLike && e8.skipLike.test(i7)) return t7; - if ("0" === t7) return 0; - if (e8.hex && D2.test(i7)) return (function(t8) { - if (parseInt) return parseInt(t8, 16); - if (Number.parseInt) return Number.parseInt(t8, 16); - if (window && window.parseInt) return window.parseInt(t8, 16); - throw new Error("parseInt, Number.parseInt, window.parseInt are not supported"); - })(i7); - if (isFinite(i7)) { - if (i7.includes("e") || i7.includes("E")) return (function(t8, e9, i8) { - if (!i8.eNotation) return t8; - const n7 = e9.match(F2); - if (n7) { - let s6 = n7[1] || ""; - const r6 = -1 === n7[3].indexOf("e") ? "E" : "e", o6 = n7[2], a6 = s6 ? t8[o6.length + 1] === r6 : t8[o6.length] === r6; - return o6.length > 1 && a6 ? t8 : (1 !== o6.length || !n7[3].startsWith(`.${r6}`) && n7[3][0] !== r6) && o6.length > 0 ? i8.leadingZeros && !a6 ? (e9 = (n7[1] || "") + n7[3], Number(e9)) : t8 : Number(e9); - } - return t8; - })(t7, i7, e8); - { - const s6 = V.exec(i7); - if (s6) { - const r6 = s6[1] || "", o6 = s6[2]; - let a6 = (n6 = s6[3]) && -1 !== n6.indexOf(".") ? ("." === (n6 = n6.replace(/0+$/, "")) ? n6 = "0" : "." === n6[0] ? n6 = "0" + n6 : "." === n6[n6.length - 1] && (n6 = n6.substring(0, n6.length - 1)), n6) : n6; - const h6 = r6 ? "." === t7[o6.length + 1] : "." === t7[o6.length]; - if (!e8.leadingZeros && (o6.length > 1 || 1 === o6.length && !h6)) return t7; - { - const n7 = Number(i7), s7 = String(n7); - if (0 === n7) return n7; - if (-1 !== s7.search(/[eE]/)) return e8.eNotation ? n7 : t7; - if (-1 !== i7.indexOf(".")) return "0" === s7 || s7 === a6 || s7 === `${r6}${a6}` ? n7 : t7; - let h7 = o6 ? a6 : i7; - return o6 ? h7 === s7 || r6 + h7 === s7 ? n7 : t7 : h7 === s7 || h7 === r6 + s7 ? n7 : t7; - } - } - return t7; - } - } - var n6; - return (function(t8, e9, i8) { - const n7 = e9 === 1 / 0; - switch (i8.infinity.toLowerCase()) { - case "null": - return null; - case "infinity": - return e9; - case "string": - return n7 ? "Infinity" : "-Infinity"; - default: - return t8; - } - })(t7, Number(i7), e8); - })(t6, i6); - } - return void 0 !== t6 ? t6 : ""; - } - function rt(t6, e6, i6) { - const n6 = Number.parseInt(t6, e6); - return n6 >= 0 && n6 <= 1114111 ? String.fromCodePoint(n6) : i6 + t6 + ";"; - } - function ot(t6, e6, i6, n6) { - if (t6) { - const n7 = t6(e6); - i6 === e6 && (i6 = n7), e6 = n7; - } - return { tagName: e6 = at(e6, n6), tagExp: i6 }; - } - function at(t6, e6) { - if (a5.includes(t6)) throw new Error(`[SECURITY] Invalid name: "${t6}" is a reserved JavaScript keyword that could cause prototype pollution`); - return o5.includes(t6) ? e6.onDangerousProperty(t6) : t6; - } - const ht = $.getMetaDataSymbol(); - function lt2(t6, e6) { - if (!t6 || "object" != typeof t6) return {}; - if (!e6) return t6; - const i6 = {}; - for (const n6 in t6) n6.startsWith(e6) ? i6[n6.substring(e6.length)] = t6[n6] : i6[n6] = t6[n6]; - return i6; - } - function pt(t6, e6, i6, n6) { - return ut(t6, e6, i6, n6); - } - function ut(t6, e6, i6, n6) { - let s6; - const r6 = {}; - for (let o6 = 0; o6 < t6.length; o6++) { - const a6 = t6[o6], h6 = ct(a6); - if (void 0 !== h6 && h6 !== e6.textNodeName) { - const t7 = lt2(a6[":@"] || {}, e6.attributeNamePrefix); - i6.push(h6, t7); - } - if (h6 === e6.textNodeName) void 0 === s6 ? s6 = a6[h6] : s6 += "" + a6[h6]; - else { - if (void 0 === h6) continue; - if (a6[h6]) { - let t7 = ut(a6[h6], e6, i6, n6); - const s7 = ft(t7, e6); - if (a6[":@"] ? dt(t7, a6[":@"], n6, e6) : 1 !== Object.keys(t7).length || void 0 === t7[e6.textNodeName] || e6.alwaysCreateTextNode ? 0 === Object.keys(t7).length && (e6.alwaysCreateTextNode ? t7[e6.textNodeName] = "" : t7 = "") : t7 = t7[e6.textNodeName], void 0 !== a6[ht] && "object" == typeof t7 && null !== t7 && (t7[ht] = a6[ht]), void 0 !== r6[h6] && Object.prototype.hasOwnProperty.call(r6, h6)) Array.isArray(r6[h6]) || (r6[h6] = [r6[h6]]), r6[h6].push(t7); - else { - const i7 = e6.jPath ? n6.toString() : n6; - e6.isArray(h6, i7, s7) ? r6[h6] = [t7] : r6[h6] = t7; - } - void 0 !== h6 && h6 !== e6.textNodeName && i6.pop(); - } - } - } - return "string" == typeof s6 ? s6.length > 0 && (r6[e6.textNodeName] = s6) : void 0 !== s6 && (r6[e6.textNodeName] = s6), r6; - } - function ct(t6) { - const e6 = Object.keys(t6); - for (let t7 = 0; t7 < e6.length; t7++) { - const i6 = e6[t7]; - if (":@" !== i6) return i6; - } - } - function dt(t6, e6, i6, n6) { - if (e6) { - const s6 = Object.keys(e6), r6 = s6.length; - for (let o6 = 0; o6 < r6; o6++) { - const r7 = s6[o6], a6 = r7.startsWith(n6.attributeNamePrefix) ? r7.substring(n6.attributeNamePrefix.length) : r7, h6 = n6.jPath ? i6.toString() + "." + a6 : i6; - n6.isArray(r7, h6, true, true) ? t6[r7] = [e6[r7]] : t6[r7] = e6[r7]; - } - } - } - function ft(t6, e6) { - const { textNodeName: i6 } = e6, n6 = Object.keys(t6).length; - return 0 === n6 || !(1 !== n6 || !t6[i6] && "boolean" != typeof t6[i6] && 0 !== t6[i6]); - } - class gt2 { - constructor(t6) { - this.externalEntities = {}, this.options = O(t6); - } - parse(t6, e6) { - if ("string" != typeof t6 && t6.toString) t6 = t6.toString(); - else if ("string" != typeof t6) throw new Error("XML data is accepted in String or Bytes[] form."); - if (e6) { - true === e6 && (e6 = {}); - const i7 = l5(t6, e6); - if (true !== i7) throw Error(`${i7.err.msg}:${i7.err.line}:${i7.err.col}`); - } - const i6 = new W(this.options); - i6.addExternalEntities(this.externalEntities); - const n6 = i6.parseXml(t6); - return this.options.preserveOrder || void 0 === n6 ? n6 : pt(n6, this.options, i6.matcher, i6.readonlyMatcher); - } - addEntity(t6, e6) { - if (-1 !== e6.indexOf("&")) throw new Error("Entity value can't have '&'"); - if (-1 !== t6.indexOf("&") || -1 !== t6.indexOf(";")) throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for ' '"); - if ("&" === e6) throw new Error("An entity with value '&' is not permitted"); - this.externalEntities[t6] = e6; - } - static getMetaDataSymbol() { - return $.getMetaDataSymbol(); - } - } - function mt(t6, e6) { - let i6 = ""; - e6.format && e6.indentBy.length > 0 && (i6 = "\n"); - const n6 = []; - if (e6.stopNodes && Array.isArray(e6.stopNodes)) for (let t7 = 0; t7 < e6.stopNodes.length; t7++) { - const i7 = e6.stopNodes[t7]; - "string" == typeof i7 ? n6.push(new R(i7)) : i7 instanceof R && n6.push(i7); - } - return xt(t6, e6, i6, new G2(), n6); - } - function xt(t6, e6, i6, n6, s6) { - let r6 = "", o6 = false; - if (e6.maxNestedTags && n6.getDepth() > e6.maxNestedTags) throw new Error("Maximum nested tags exceeded"); - if (!Array.isArray(t6)) { - if (null != t6) { - let i7 = t6.toString(); - return i7 = Tt(i7, e6), i7; - } - return ""; - } - for (let a6 = 0; a6 < t6.length; a6++) { - const h6 = t6[a6], l6 = yt(h6); - if (void 0 === l6) continue; - const p6 = Nt(h6[":@"], e6); - n6.push(l6, p6); - const u6 = vt(n6, s6); - if (l6 === e6.textNodeName) { - let t7 = h6[l6]; - u6 || (t7 = e6.tagValueProcessor(l6, t7), t7 = Tt(t7, e6)), o6 && (r6 += i6), r6 += t7, o6 = false, n6.pop(); - continue; - } - if (l6 === e6.cdataPropName) { - o6 && (r6 += i6), r6 += ``, o6 = false, n6.pop(); - continue; - } - if (l6 === e6.commentPropName) { - r6 += i6 + ``, o6 = true, n6.pop(); - continue; - } - if ("?" === l6[0]) { - const t7 = wt(h6[":@"], e6, u6), s7 = "?xml" === l6 ? "" : i6; - let a7 = h6[l6][0][e6.textNodeName]; - a7 = 0 !== a7.length ? " " + a7 : "", r6 += s7 + `<${l6}${a7}${t7}?>`, o6 = true, n6.pop(); - continue; - } - let c6 = i6; - "" !== c6 && (c6 += e6.indentBy); - const d6 = i6 + `<${l6}${wt(h6[":@"], e6, u6)}`; - let f6; - f6 = u6 ? bt(h6[l6], e6) : xt(h6[l6], e6, c6, n6, s6), -1 !== e6.unpairedTags.indexOf(l6) ? e6.suppressUnpairedNode ? r6 += d6 + ">" : r6 += d6 + "/>" : f6 && 0 !== f6.length || !e6.suppressEmptyNode ? f6 && f6.endsWith(">") ? r6 += d6 + `>${f6}${i6}` : (r6 += d6 + ">", f6 && "" !== i6 && (f6.includes("/>") || f6.includes("`) : r6 += d6 + "/>", o6 = true, n6.pop(); - } - return r6; - } - function Nt(t6, e6) { - if (!t6 || e6.ignoreAttributes) return null; - const i6 = {}; - let n6 = false; - for (let s6 in t6) Object.prototype.hasOwnProperty.call(t6, s6) && (i6[s6.startsWith(e6.attributeNamePrefix) ? s6.substr(e6.attributeNamePrefix.length) : s6] = t6[s6], n6 = true); - return n6 ? i6 : null; - } - function bt(t6, e6) { - if (!Array.isArray(t6)) return null != t6 ? t6.toString() : ""; - let i6 = ""; - for (let n6 = 0; n6 < t6.length; n6++) { - const s6 = t6[n6], r6 = yt(s6); - if (r6 === e6.textNodeName) i6 += s6[r6]; - else if (r6 === e6.cdataPropName) i6 += s6[r6][0][e6.textNodeName]; - else if (r6 === e6.commentPropName) i6 += s6[r6][0][e6.textNodeName]; - else { - if (r6 && "?" === r6[0]) continue; - if (r6) { - const t7 = Et(s6[":@"], e6), n7 = bt(s6[r6], e6); - n7 && 0 !== n7.length ? i6 += `<${r6}${t7}>${n7}` : i6 += `<${r6}${t7}/>`; - } - } - } - return i6; - } - function Et(t6, e6) { - let i6 = ""; - if (t6 && !e6.ignoreAttributes) for (let n6 in t6) { - if (!Object.prototype.hasOwnProperty.call(t6, n6)) continue; - let s6 = t6[n6]; - true === s6 && e6.suppressBooleanAttributes ? i6 += ` ${n6.substr(e6.attributeNamePrefix.length)}` : i6 += ` ${n6.substr(e6.attributeNamePrefix.length)}="${s6}"`; - } - return i6; - } - function yt(t6) { - const e6 = Object.keys(t6); - for (let i6 = 0; i6 < e6.length; i6++) { - const n6 = e6[i6]; - if (Object.prototype.hasOwnProperty.call(t6, n6) && ":@" !== n6) return n6; - } - } - function wt(t6, e6, i6) { - let n6 = ""; - if (t6 && !e6.ignoreAttributes) for (let s6 in t6) { - if (!Object.prototype.hasOwnProperty.call(t6, s6)) continue; - let r6; - i6 ? r6 = t6[s6] : (r6 = e6.attributeValueProcessor(s6, t6[s6]), r6 = Tt(r6, e6)), true === r6 && e6.suppressBooleanAttributes ? n6 += ` ${s6.substr(e6.attributeNamePrefix.length)}` : n6 += ` ${s6.substr(e6.attributeNamePrefix.length)}="${r6}"`; - } - return n6; - } - function vt(t6, e6) { - if (!e6 || 0 === e6.length) return false; - for (let i6 = 0; i6 < e6.length; i6++) if (t6.matches(e6[i6])) return true; - return false; - } - function Tt(t6, e6) { - if (t6 && t6.length > 0 && e6.processEntities) for (let i6 = 0; i6 < e6.entities.length; i6++) { - const n6 = e6.entities[i6]; - t6 = t6.replace(n6.regex, n6.val); - } - return t6; - } - const Pt = { attributeNamePrefix: "@_", attributesGroupName: false, textNodeName: "#text", ignoreAttributes: true, cdataPropName: false, format: false, indentBy: " ", suppressEmptyNode: false, suppressUnpairedNode: true, suppressBooleanAttributes: true, tagValueProcessor: function(t6, e6) { - return e6; - }, attributeValueProcessor: function(t6, e6) { - return e6; - }, preserveOrder: false, commentPropName: false, unpairedTags: [], entities: [{ regex: new RegExp("&", "g"), val: "&" }, { regex: new RegExp(">", "g"), val: ">" }, { regex: new RegExp("<", "g"), val: "<" }, { regex: new RegExp("'", "g"), val: "'" }, { regex: new RegExp('"', "g"), val: """ }], processEntities: true, stopNodes: [], oneListGroup: false, maxNestedTags: 100, jPath: true }; - function St(t6) { - if (this.options = Object.assign({}, Pt, t6), this.options.stopNodes && Array.isArray(this.options.stopNodes) && (this.options.stopNodes = this.options.stopNodes.map((t7) => "string" == typeof t7 && t7.startsWith("*.") ? ".." + t7.substring(2) : t7)), this.stopNodeExpressions = [], this.options.stopNodes && Array.isArray(this.options.stopNodes)) for (let t7 = 0; t7 < this.options.stopNodes.length; t7++) { - const e7 = this.options.stopNodes[t7]; - "string" == typeof e7 ? this.stopNodeExpressions.push(new R(e7)) : e7 instanceof R && this.stopNodeExpressions.push(e7); - } - var e6; - true === this.options.ignoreAttributes || this.options.attributesGroupName ? this.isAttribute = function() { - return false; - } : (this.ignoreAttributesFn = "function" == typeof (e6 = this.options.ignoreAttributes) ? e6 : Array.isArray(e6) ? (t7) => { - for (const i6 of e6) { - if ("string" == typeof i6 && t7 === i6) return true; - if (i6 instanceof RegExp && i6.test(t7)) return true; - } - } : () => false, this.attrPrefixLen = this.options.attributeNamePrefix.length, this.isAttribute = Ct), this.processTextOrObjNode = At, this.options.format ? (this.indentate = Ot, this.tagEndChar = ">\n", this.newLine = "\n") : (this.indentate = function() { - return ""; - }, this.tagEndChar = ">", this.newLine = ""); - } - function At(t6, e6, i6, n6) { - const s6 = this.extractAttributes(t6); - if (n6.push(e6, s6), this.checkStopNode(n6)) { - const s7 = this.buildRawContent(t6), r7 = this.buildAttributesForStopNode(t6); - return n6.pop(), this.buildObjectNode(s7, e6, r7, i6); - } - const r6 = this.j2x(t6, i6 + 1, n6); - return n6.pop(), void 0 !== t6[this.options.textNodeName] && 1 === Object.keys(t6).length ? this.buildTextValNode(t6[this.options.textNodeName], e6, r6.attrStr, i6, n6) : this.buildObjectNode(r6.val, e6, r6.attrStr, i6); - } - function Ot(t6) { - return this.options.indentBy.repeat(t6); - } - function Ct(t6) { - return !(!t6.startsWith(this.options.attributeNamePrefix) || t6 === this.options.textNodeName) && t6.substr(this.attrPrefixLen); - } - St.prototype.build = function(t6) { - if (this.options.preserveOrder) return mt(t6, this.options); - { - Array.isArray(t6) && this.options.arrayNodeName && this.options.arrayNodeName.length > 1 && (t6 = { [this.options.arrayNodeName]: t6 }); - const e6 = new G2(); - return this.j2x(t6, 0, e6).val; - } - }, St.prototype.j2x = function(t6, e6, i6) { - let n6 = "", s6 = ""; - if (this.options.maxNestedTags && i6.getDepth() >= this.options.maxNestedTags) throw new Error("Maximum nested tags exceeded"); - const r6 = this.options.jPath ? i6.toString() : i6, o6 = this.checkStopNode(i6); - for (let a6 in t6) if (Object.prototype.hasOwnProperty.call(t6, a6)) if (void 0 === t6[a6]) this.isAttribute(a6) && (s6 += ""); - else if (null === t6[a6]) this.isAttribute(a6) || a6 === this.options.cdataPropName ? s6 += "" : "?" === a6[0] ? s6 += this.indentate(e6) + "<" + a6 + "?" + this.tagEndChar : s6 += this.indentate(e6) + "<" + a6 + "/" + this.tagEndChar; - else if (t6[a6] instanceof Date) s6 += this.buildTextValNode(t6[a6], a6, "", e6, i6); - else if ("object" != typeof t6[a6]) { - const h6 = this.isAttribute(a6); - if (h6 && !this.ignoreAttributesFn(h6, r6)) n6 += this.buildAttrPairStr(h6, "" + t6[a6], o6); - else if (!h6) if (a6 === this.options.textNodeName) { - let e7 = this.options.tagValueProcessor(a6, "" + t6[a6]); - s6 += this.replaceEntitiesValue(e7); - } else { - i6.push(a6); - const n7 = this.checkStopNode(i6); - if (i6.pop(), n7) { - const i7 = "" + t6[a6]; - s6 += "" === i7 ? this.indentate(e6) + "<" + a6 + this.closeTag(a6) + this.tagEndChar : this.indentate(e6) + "<" + a6 + ">" + i7 + "" + t8 + "${t7}`; - else if ("object" == typeof t7 && null !== t7) { - const n7 = this.buildRawContent(t7), s6 = this.buildAttributesForStopNode(t7); - e6 += "" === n7 ? `<${i6}${s6}/>` : `<${i6}${s6}>${n7}`; - } - } else if ("object" == typeof n6 && null !== n6) { - const t7 = this.buildRawContent(n6), s6 = this.buildAttributesForStopNode(n6); - e6 += "" === t7 ? `<${i6}${s6}/>` : `<${i6}${s6}>${t7}`; - } else e6 += `<${i6}>${n6}`; - } - return e6; - }, St.prototype.buildAttributesForStopNode = function(t6) { - if (!t6 || "object" != typeof t6) return ""; - let e6 = ""; - if (this.options.attributesGroupName && t6[this.options.attributesGroupName]) { - const i6 = t6[this.options.attributesGroupName]; - for (let t7 in i6) { - if (!Object.prototype.hasOwnProperty.call(i6, t7)) continue; - const n6 = t7.startsWith(this.options.attributeNamePrefix) ? t7.substring(this.options.attributeNamePrefix.length) : t7, s6 = i6[t7]; - true === s6 && this.options.suppressBooleanAttributes ? e6 += " " + n6 : e6 += " " + n6 + '="' + s6 + '"'; - } - } else for (let i6 in t6) { - if (!Object.prototype.hasOwnProperty.call(t6, i6)) continue; - const n6 = this.isAttribute(i6); - if (n6) { - const s6 = t6[i6]; - true === s6 && this.options.suppressBooleanAttributes ? e6 += " " + n6 : e6 += " " + n6 + '="' + s6 + '"'; - } - } - return e6; - }, St.prototype.buildObjectNode = function(t6, e6, i6, n6) { - if ("" === t6) return "?" === e6[0] ? this.indentate(n6) + "<" + e6 + i6 + "?" + this.tagEndChar : this.indentate(n6) + "<" + e6 + i6 + this.closeTag(e6) + this.tagEndChar; - { - let s6 = "` + this.newLine : this.indentate(n6) + "<" + e6 + i6 + r6 + this.tagEndChar + t6 + this.indentate(n6) + s6 : this.indentate(n6) + "<" + e6 + i6 + r6 + ">" + t6 + s6; - } - }, St.prototype.closeTag = function(t6) { - let e6 = ""; - return -1 !== this.options.unpairedTags.indexOf(t6) ? this.options.suppressUnpairedNode || (e6 = "/") : e6 = this.options.suppressEmptyNode ? "/" : `>` + this.newLine; - if (false !== this.options.commentPropName && e6 === this.options.commentPropName) return this.indentate(n6) + `` + this.newLine; - if ("?" === e6[0]) return this.indentate(n6) + "<" + e6 + i6 + "?" + this.tagEndChar; - { - let s7 = this.options.tagValueProcessor(e6, t6); - return s7 = this.replaceEntitiesValue(s7), "" === s7 ? this.indentate(n6) + "<" + e6 + i6 + this.closeTag(e6) + this.tagEndChar : this.indentate(n6) + "<" + e6 + i6 + ">" + s7 + " 0 && this.options.processEntities) for (let e6 = 0; e6 < this.options.entities.length; e6++) { - const i6 = this.options.entities[e6]; - t6 = t6.replace(i6.regex, i6.val); - } - return t6; - }; - const $t = St, It = { validate: l5 }; - module.exports = e5; - })(); - } -}); - -// node_modules/.pnpm/@aws-sdk+xml-builder@3.972.17/node_modules/@aws-sdk/xml-builder/dist-cjs/xml-parser.js -var require_xml_parser = __commonJS({ - "node_modules/.pnpm/@aws-sdk+xml-builder@3.972.17/node_modules/@aws-sdk/xml-builder/dist-cjs/xml-parser.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.parseXML = parseXML3; - var fast_xml_parser_1 = require_fxp(); - var parser = new fast_xml_parser_1.XMLParser({ - attributeNamePrefix: "", - processEntities: { - enabled: true, - maxTotalExpansions: Infinity - }, - htmlEntities: true, - ignoreAttributes: false, - ignoreDeclaration: true, - parseTagValue: false, - trimValues: false, - tagValueProcessor: (_, val) => val.trim() === "" && val.includes("\n") ? "" : void 0, - maxNestedTags: Infinity - }); - parser.addEntity("#xD", "\r"); - parser.addEntity("#10", "\n"); - function parseXML3(xmlString) { - return parser.parse(xmlString, true); - } - } -}); - -// node_modules/.pnpm/@aws-sdk+xml-builder@3.972.17/node_modules/@aws-sdk/xml-builder/dist-cjs/index.js -var require_dist_cjs29 = __commonJS({ - "node_modules/.pnpm/@aws-sdk+xml-builder@3.972.17/node_modules/@aws-sdk/xml-builder/dist-cjs/index.js"(exports) { - "use strict"; - var xmlParser = require_xml_parser(); - var ATTR_ESCAPE_RE = /[&<>"]/g; - var ATTR_ESCAPE_MAP = { - "&": "&", - "<": "<", - ">": ">", - '"': """ - }; - function escapeAttribute(value) { - return value.replace(ATTR_ESCAPE_RE, (ch) => ATTR_ESCAPE_MAP[ch]); - } - var ELEMENT_ESCAPE_RE = /[&"'<>\r\n\u0085\u2028]/g; - var ELEMENT_ESCAPE_MAP = { - "&": "&", - '"': """, - "'": "'", - "<": "<", - ">": ">", - "\r": " ", - "\n": " ", - "\x85": "…", - "\u2028": "
" - }; - function escapeElement(value) { - return value.replace(ELEMENT_ESCAPE_RE, (ch) => ELEMENT_ESCAPE_MAP[ch]); - } - var XmlText2 = class { - value; - constructor(value) { - this.value = value; - } - toString() { - return escapeElement("" + this.value); - } - }; - var XmlNode2 = class _XmlNode { - name; - children; - attributes = {}; - static of(name, childText, withName) { - const node = new _XmlNode(name); - if (childText !== void 0) { - node.addChildNode(new XmlText2(childText)); - } - if (withName !== void 0) { - node.withName(withName); - } - return node; - } - constructor(name, children = []) { - this.name = name; - this.children = children; - } - withName(name) { - this.name = name; - return this; - } - addAttribute(name, value) { - this.attributes[name] = value; - return this; - } - addChildNode(child) { - this.children.push(child); - return this; - } - removeAttribute(name) { - delete this.attributes[name]; - return this; - } - n(name) { - this.name = name; - return this; - } - c(child) { - this.children.push(child); - return this; - } - a(name, value) { - if (value != null) { - this.attributes[name] = value; - } - return this; - } - cc(input, field, withName = field) { - if (input[field] != null) { - const node = _XmlNode.of(field, input[field]).withName(withName); - this.c(node); - } - } - l(input, listName, memberName, valueProvider) { - if (input[listName] != null) { - const nodes = valueProvider(); - nodes.map((node) => { - node.withName(memberName); - this.c(node); - }); - } - } - lc(input, listName, memberName, valueProvider) { - if (input[listName] != null) { - const nodes = valueProvider(); - const containerNode = new _XmlNode(memberName); - nodes.map((node) => { - containerNode.c(node); - }); - this.c(containerNode); - } - } - toString() { - const hasChildren = Boolean(this.children.length); - let xmlText = `<${this.name}`; - const attributes = this.attributes; - for (const attributeName of Object.keys(attributes)) { - const attribute = attributes[attributeName]; - if (attribute != null) { - xmlText += ` ${attributeName}="${escapeAttribute("" + attribute)}"`; - } - } - return xmlText += !hasChildren ? "/>" : `>${this.children.map((c5) => c5.toString()).join("")}`; - } - }; - exports.parseXML = xmlParser.parseXML; - exports.XmlNode = XmlNode2; - exports.XmlText = XmlText2; - } -}); - -// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/xml/XmlShapeDeserializer.js -var import_xml_builder, import_smithy_client4, import_util_utf87, XmlShapeDeserializer; -var init_XmlShapeDeserializer = __esm({ - "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/xml/XmlShapeDeserializer.js"() { - import_xml_builder = __toESM(require_dist_cjs29()); - init_protocols(); - init_schema3(); - import_smithy_client4 = __toESM(require_dist_cjs27()); - import_util_utf87 = __toESM(require_dist_cjs6()); - init_ConfigurableSerdeContext(); - init_UnionSerde(); - XmlShapeDeserializer = class extends SerdeContextConfig { - settings; - stringDeserializer; - constructor(settings) { - super(); - this.settings = settings; - this.stringDeserializer = new FromStringShapeDeserializer(settings); - } - setSerdeContext(serdeContext) { - this.serdeContext = serdeContext; - this.stringDeserializer.setSerdeContext(serdeContext); - } - read(schema2, bytes, key) { - const ns = NormalizedSchema.of(schema2); - const memberSchemas = ns.getMemberSchemas(); - const isEventPayload = ns.isStructSchema() && ns.isMemberSchema() && !!Object.values(memberSchemas).find((memberNs) => { - return !!memberNs.getMemberTraits().eventPayload; - }); - if (isEventPayload) { - const output = {}; - const memberName = Object.keys(memberSchemas)[0]; - const eventMemberSchema = memberSchemas[memberName]; - if (eventMemberSchema.isBlobSchema()) { - output[memberName] = bytes; - } else { - output[memberName] = this.read(memberSchemas[memberName], bytes); - } - return output; - } - const xmlString = (this.serdeContext?.utf8Encoder ?? import_util_utf87.toUtf8)(bytes); - const parsedObject = this.parseXml(xmlString); - return this.readSchema(schema2, key ? parsedObject[key] : parsedObject); - } - readSchema(_schema, value) { - const ns = NormalizedSchema.of(_schema); - if (ns.isUnitSchema()) { - return; - } - const traits = ns.getMergedTraits(); - if (ns.isListSchema() && !Array.isArray(value)) { - return this.readSchema(ns, [value]); - } - if (value == null) { - return value; - } - if (typeof value === "object") { - const flat = !!traits.xmlFlattened; - if (ns.isListSchema()) { - const listValue = ns.getValueSchema(); - const buffer3 = []; - const sourceKey = listValue.getMergedTraits().xmlName ?? "member"; - const source = flat ? value : (value[0] ?? value)[sourceKey]; - if (source == null) { - return buffer3; - } - const sourceArray = Array.isArray(source) ? source : [source]; - for (const v5 of sourceArray) { - buffer3.push(this.readSchema(listValue, v5)); - } - return buffer3; - } - const buffer2 = {}; - if (ns.isMapSchema()) { - const keyNs = ns.getKeySchema(); - const memberNs = ns.getValueSchema(); - let entries2; - if (flat) { - entries2 = Array.isArray(value) ? value : [value]; - } else { - entries2 = Array.isArray(value.entry) ? value.entry : [value.entry]; - } - const keyProperty = keyNs.getMergedTraits().xmlName ?? "key"; - const valueProperty = memberNs.getMergedTraits().xmlName ?? "value"; - for (const entry of entries2) { - const key = entry[keyProperty]; - const value2 = entry[valueProperty]; - buffer2[key] = this.readSchema(memberNs, value2); - } - return buffer2; - } - if (ns.isStructSchema()) { - const union3 = ns.isUnionSchema(); - let unionSerde; - if (union3) { - unionSerde = new UnionSerde(value, buffer2); - } - for (const [memberName, memberSchema] of ns.structIterator()) { - const memberTraits = memberSchema.getMergedTraits(); - const xmlObjectKey = !memberTraits.httpPayload ? memberSchema.getMemberTraits().xmlName ?? memberName : memberTraits.xmlName ?? memberSchema.getName(); - if (union3) { - unionSerde.mark(xmlObjectKey); - } - if (value[xmlObjectKey] != null) { - buffer2[memberName] = this.readSchema(memberSchema, value[xmlObjectKey]); - } - } - if (union3) { - unionSerde.writeUnknown(); - } - return buffer2; - } - if (ns.isDocumentSchema()) { - return value; - } - throw new Error(`@aws-sdk/core/protocols - xml deserializer unhandled schema type for ${ns.getName(true)}`); - } - if (ns.isListSchema()) { - return []; - } - if (ns.isMapSchema() || ns.isStructSchema()) { - return {}; - } - return this.stringDeserializer.read(ns, value); - } - parseXml(xml2) { - if (xml2.length) { - let parsedObj; - try { - parsedObj = (0, import_xml_builder.parseXML)(xml2); - } catch (e5) { - if (e5 && typeof e5 === "object") { - Object.defineProperty(e5, "$responseBodyText", { - value: xml2 - }); - } - throw e5; - } - const textNodeName = "#text"; - const key = Object.keys(parsedObj)[0]; - const parsedObjToReturn = parsedObj[key]; - if (parsedObjToReturn[textNodeName]) { - parsedObjToReturn[key] = parsedObjToReturn[textNodeName]; - delete parsedObjToReturn[textNodeName]; - } - return (0, import_smithy_client4.getValueFromTextNode)(parsedObjToReturn); - } - return {}; - } - }; - } -}); - -// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/query/QueryShapeSerializer.js -var import_smithy_client5, import_util_base646, QueryShapeSerializer; -var init_QueryShapeSerializer = __esm({ - "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/query/QueryShapeSerializer.js"() { - init_protocols(); - init_schema3(); - init_serde(); - import_smithy_client5 = __toESM(require_dist_cjs27()); - import_util_base646 = __toESM(require_dist_cjs7()); - init_ConfigurableSerdeContext(); - QueryShapeSerializer = class extends SerdeContextConfig { - settings; - buffer; - constructor(settings) { - super(); - this.settings = settings; - } - write(schema2, value, prefix = "") { - if (this.buffer === void 0) { - this.buffer = ""; - } - const ns = NormalizedSchema.of(schema2); - if (prefix && !prefix.endsWith(".")) { - prefix += "."; - } - if (ns.isBlobSchema()) { - if (typeof value === "string" || value instanceof Uint8Array) { - this.writeKey(prefix); - this.writeValue((this.serdeContext?.base64Encoder ?? import_util_base646.toBase64)(value)); - } - } else if (ns.isBooleanSchema() || ns.isNumericSchema() || ns.isStringSchema()) { - if (value != null) { - this.writeKey(prefix); - this.writeValue(String(value)); - } else if (ns.isIdempotencyToken()) { - this.writeKey(prefix); - this.writeValue((0, import_uuid2.v4)()); - } - } else if (ns.isBigIntegerSchema()) { - if (value != null) { - this.writeKey(prefix); - this.writeValue(String(value)); - } - } else if (ns.isBigDecimalSchema()) { - if (value != null) { - this.writeKey(prefix); - this.writeValue(value instanceof NumericValue ? value.string : String(value)); - } - } else if (ns.isTimestampSchema()) { - if (value instanceof Date) { - this.writeKey(prefix); - const format2 = determineTimestampFormat(ns, this.settings); - switch (format2) { - case 5: - this.writeValue(value.toISOString().replace(".000Z", "Z")); - break; - case 6: - this.writeValue((0, import_smithy_client5.dateToUtcString)(value)); - break; - case 7: - this.writeValue(String(value.getTime() / 1e3)); - break; - } - } - } else if (ns.isDocumentSchema()) { - if (Array.isArray(value)) { - this.write(64 | 15, value, prefix); - } else if (value instanceof Date) { - this.write(4, value, prefix); - } else if (value instanceof Uint8Array) { - this.write(21, value, prefix); - } else if (value && typeof value === "object") { - this.write(128 | 15, value, prefix); - } else { - this.writeKey(prefix); - this.writeValue(String(value)); - } - } else if (ns.isListSchema()) { - if (Array.isArray(value)) { - if (value.length === 0) { - if (this.settings.serializeEmptyLists) { - this.writeKey(prefix); - this.writeValue(""); - } - } else { - const member2 = ns.getValueSchema(); - const flat = this.settings.flattenLists || ns.getMergedTraits().xmlFlattened; - let i5 = 1; - for (const item of value) { - if (item == null) { - continue; - } - const traits = member2.getMergedTraits(); - const suffix = this.getKey("member", traits.xmlName, traits.ec2QueryName); - const key = flat ? `${prefix}${i5}` : `${prefix}${suffix}.${i5}`; - this.write(member2, item, key); - ++i5; - } - } - } - } else if (ns.isMapSchema()) { - if (value && typeof value === "object") { - const keySchema = ns.getKeySchema(); - const memberSchema = ns.getValueSchema(); - const flat = ns.getMergedTraits().xmlFlattened; - let i5 = 1; - for (const [k5, v5] of Object.entries(value)) { - if (v5 == null) { - continue; - } - const keyTraits = keySchema.getMergedTraits(); - const keySuffix = this.getKey("key", keyTraits.xmlName, keyTraits.ec2QueryName); - const key = flat ? `${prefix}${i5}.${keySuffix}` : `${prefix}entry.${i5}.${keySuffix}`; - const valTraits = memberSchema.getMergedTraits(); - const valueSuffix = this.getKey("value", valTraits.xmlName, valTraits.ec2QueryName); - const valueKey = flat ? `${prefix}${i5}.${valueSuffix}` : `${prefix}entry.${i5}.${valueSuffix}`; - this.write(keySchema, k5, key); - this.write(memberSchema, v5, valueKey); - ++i5; - } - } - } else if (ns.isStructSchema()) { - if (value && typeof value === "object") { - let didWriteMember = false; - for (const [memberName, member2] of ns.structIterator()) { - if (value[memberName] == null && !member2.isIdempotencyToken()) { - continue; - } - const traits = member2.getMergedTraits(); - const suffix = this.getKey(memberName, traits.xmlName, traits.ec2QueryName, "struct"); - const key = `${prefix}${suffix}`; - this.write(member2, value[memberName], key); - didWriteMember = true; - } - if (!didWriteMember && ns.isUnionSchema()) { - const { $unknown } = value; - if (Array.isArray($unknown)) { - const [k5, v5] = $unknown; - const key = `${prefix}${k5}`; - this.write(15, v5, key); - } - } - } - } else if (ns.isUnitSchema()) { - } else { - throw new Error(`@aws-sdk/core/protocols - QuerySerializer unrecognized schema type ${ns.getName(true)}`); - } - } - flush() { - if (this.buffer === void 0) { - throw new Error("@aws-sdk/core/protocols - QuerySerializer cannot flush with nothing written to buffer."); - } - const str = this.buffer; - delete this.buffer; - return str; - } - getKey(memberName, xmlName, ec2QueryName, keySource) { - const { ec2, capitalizeKeys } = this.settings; - if (ec2 && ec2QueryName) { - return ec2QueryName; - } - const key = xmlName ?? memberName; - if (capitalizeKeys && keySource === "struct") { - return key[0].toUpperCase() + key.slice(1); - } - return key; - } - writeKey(key) { - if (key.endsWith(".")) { - key = key.slice(0, key.length - 1); - } - this.buffer += `&${extendedEncodeURIComponent(key)}=`; - } - writeValue(value) { - this.buffer += extendedEncodeURIComponent(value); - } - }; - } -}); - -// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/query/AwsQueryProtocol.js -var AwsQueryProtocol; -var init_AwsQueryProtocol = __esm({ - "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/query/AwsQueryProtocol.js"() { - init_protocols(); - init_schema3(); - init_ProtocolLib(); - init_XmlShapeDeserializer(); - init_QueryShapeSerializer(); - AwsQueryProtocol = class extends RpcProtocol { - options; - serializer; - deserializer; - mixin = new ProtocolLib(); - constructor(options) { - super({ - defaultNamespace: options.defaultNamespace, - errorTypeRegistries: options.errorTypeRegistries - }); - this.options = options; - const settings = { - timestampFormat: { - useTrait: true, - default: 5 - }, - httpBindings: false, - xmlNamespace: options.xmlNamespace, - serviceNamespace: options.defaultNamespace, - serializeEmptyLists: true - }; - this.serializer = new QueryShapeSerializer(settings); - this.deserializer = new XmlShapeDeserializer(settings); - } - getShapeId() { - return "aws.protocols#awsQuery"; - } - setSerdeContext(serdeContext) { - this.serializer.setSerdeContext(serdeContext); - this.deserializer.setSerdeContext(serdeContext); - } - getPayloadCodec() { - throw new Error("AWSQuery protocol has no payload codec."); - } - async serializeRequest(operationSchema, input, context) { - const request = await super.serializeRequest(operationSchema, input, context); - if (!request.path.endsWith("/")) { - request.path += "/"; - } - Object.assign(request.headers, { - "content-type": `application/x-www-form-urlencoded` - }); - if (deref(operationSchema.input) === "unit" || !request.body) { - request.body = ""; - } - const action = operationSchema.name.split("#")[1] ?? operationSchema.name; - request.body = `Action=${action}&Version=${this.options.version}` + request.body; - if (request.body.endsWith("&")) { - request.body = request.body.slice(-1); - } - return request; - } - async deserializeResponse(operationSchema, context, response) { - const deserializer = this.deserializer; - const ns = NormalizedSchema.of(operationSchema.output); - const dataObject = {}; - if (response.statusCode >= 300) { - const bytes2 = await collectBody(response.body, context); - if (bytes2.byteLength > 0) { - Object.assign(dataObject, await deserializer.read(15, bytes2)); - } - await this.handleError(operationSchema, context, response, dataObject, this.deserializeMetadata(response)); - } - for (const header in response.headers) { - const value = response.headers[header]; - delete response.headers[header]; - response.headers[header.toLowerCase()] = value; - } - const shortName = operationSchema.name.split("#")[1] ?? operationSchema.name; - const awsQueryResultKey = ns.isStructSchema() && this.useNestedResult() ? shortName + "Result" : void 0; - const bytes = await collectBody(response.body, context); - if (bytes.byteLength > 0) { - Object.assign(dataObject, await deserializer.read(ns, bytes, awsQueryResultKey)); - } - const output = { - $metadata: this.deserializeMetadata(response), - ...dataObject - }; - return output; - } - useNestedResult() { - return true; - } - async handleError(operationSchema, context, response, dataObject, metadata) { - const errorIdentifier = this.loadQueryErrorCode(response, dataObject) ?? "Unknown"; - this.mixin.compose(this.compositeErrorRegistry, errorIdentifier, this.options.defaultNamespace); - const errorData = this.loadQueryError(dataObject) ?? {}; - const message2 = this.loadQueryErrorMessage(dataObject); - errorData.message = message2; - errorData.Error = { - Type: errorData.Type, - Code: errorData.Code, - Message: message2 - }; - const { errorSchema, errorMetadata } = await this.mixin.getErrorSchemaOrThrowBaseException(errorIdentifier, this.options.defaultNamespace, response, errorData, metadata, this.mixin.findQueryCompatibleError); - const ns = NormalizedSchema.of(errorSchema); - const ErrorCtor = this.compositeErrorRegistry.getErrorCtor(errorSchema) ?? Error; - const exception = new ErrorCtor(message2); - const output = { - Type: errorData.Error.Type, - Code: errorData.Error.Code, - Error: errorData.Error - }; - for (const [name, member2] of ns.structIterator()) { - const target = member2.getMergedTraits().xmlName ?? name; - const value = errorData[target] ?? dataObject[target]; - output[name] = this.deserializer.readSchema(member2, value); - } - throw this.mixin.decorateServiceException(Object.assign(exception, errorMetadata, { - $fault: ns.getMergedTraits().error, - message: message2 - }, output), dataObject); - } - loadQueryErrorCode(output, data2) { - const code = (data2.Errors?.[0]?.Error ?? data2.Errors?.Error ?? data2.Error)?.Code; - if (code !== void 0) { - return code; - } - if (output.statusCode == 404) { - return "NotFound"; - } - } - loadQueryError(data2) { - return data2.Errors?.[0]?.Error ?? data2.Errors?.Error ?? data2.Error; - } - loadQueryErrorMessage(data2) { - const errorData = this.loadQueryError(data2); - return errorData?.message ?? errorData?.Message ?? data2.message ?? data2.Message ?? "Unknown"; - } - getDefaultContentType() { - return "application/x-www-form-urlencoded"; - } - }; - } -}); - -// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/query/AwsEc2QueryProtocol.js -var AwsEc2QueryProtocol; -var init_AwsEc2QueryProtocol = __esm({ - "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/query/AwsEc2QueryProtocol.js"() { - init_AwsQueryProtocol(); - AwsEc2QueryProtocol = class extends AwsQueryProtocol { - options; - constructor(options) { - super(options); - this.options = options; - const ec2Settings = { - capitalizeKeys: true, - flattenLists: true, - serializeEmptyLists: false, - ec2: true - }; - Object.assign(this.serializer.settings, ec2Settings); - } - getShapeId() { - return "aws.protocols#ec2Query"; - } - useNestedResult() { - return false; - } - }; - } -}); - -// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/query/QuerySerializerSettings.js -var init_QuerySerializerSettings = __esm({ - "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/query/QuerySerializerSettings.js"() { - } -}); - -// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/xml/parseXmlBody.js -var import_xml_builder2, import_smithy_client6, parseXmlBody, parseXmlErrorBody, loadRestXmlErrorCode; -var init_parseXmlBody = __esm({ - "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/xml/parseXmlBody.js"() { - import_xml_builder2 = __toESM(require_dist_cjs29()); - import_smithy_client6 = __toESM(require_dist_cjs27()); - init_common2(); - parseXmlBody = (streamBody, context) => collectBodyString(streamBody, context).then((encoded) => { - if (encoded.length) { - let parsedObj; - try { - parsedObj = (0, import_xml_builder2.parseXML)(encoded); - } catch (e5) { - if (e5 && typeof e5 === "object") { - Object.defineProperty(e5, "$responseBodyText", { - value: encoded - }); - } - throw e5; - } - const textNodeName = "#text"; - const key = Object.keys(parsedObj)[0]; - const parsedObjToReturn = parsedObj[key]; - if (parsedObjToReturn[textNodeName]) { - parsedObjToReturn[key] = parsedObjToReturn[textNodeName]; - delete parsedObjToReturn[textNodeName]; - } - return (0, import_smithy_client6.getValueFromTextNode)(parsedObjToReturn); - } - return {}; - }); - parseXmlErrorBody = async (errorBody, context) => { - const value = await parseXmlBody(errorBody, context); - if (value.Error) { - value.Error.message = value.Error.message ?? value.Error.Message; - } - return value; - }; - loadRestXmlErrorCode = (output, data2) => { - if (data2?.Error?.Code !== void 0) { - return data2.Error.Code; - } - if (data2?.Code !== void 0) { - return data2.Code; - } - if (output.statusCode == 404) { - return "NotFound"; - } - }; - } -}); - -// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/xml/XmlShapeSerializer.js -var import_xml_builder3, import_smithy_client7, import_util_base647, XmlShapeSerializer; -var init_XmlShapeSerializer = __esm({ - "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/xml/XmlShapeSerializer.js"() { - import_xml_builder3 = __toESM(require_dist_cjs29()); - init_protocols(); - init_schema3(); - init_serde(); - import_smithy_client7 = __toESM(require_dist_cjs27()); - import_util_base647 = __toESM(require_dist_cjs7()); - init_ConfigurableSerdeContext(); - XmlShapeSerializer = class extends SerdeContextConfig { - settings; - stringBuffer; - byteBuffer; - buffer; - constructor(settings) { - super(); - this.settings = settings; - } - write(schema2, value) { - const ns = NormalizedSchema.of(schema2); - if (ns.isStringSchema() && typeof value === "string") { - this.stringBuffer = value; - } else if (ns.isBlobSchema()) { - this.byteBuffer = "byteLength" in value ? value : (this.serdeContext?.base64Decoder ?? import_util_base647.fromBase64)(value); - } else { - this.buffer = this.writeStruct(ns, value, void 0); - const traits = ns.getMergedTraits(); - if (traits.httpPayload && !traits.xmlName) { - this.buffer.withName(ns.getName()); - } - } - } - flush() { - if (this.byteBuffer !== void 0) { - const bytes = this.byteBuffer; - delete this.byteBuffer; - return bytes; - } - if (this.stringBuffer !== void 0) { - const str = this.stringBuffer; - delete this.stringBuffer; - return str; - } - const buffer2 = this.buffer; - if (this.settings.xmlNamespace) { - if (!buffer2?.attributes?.["xmlns"]) { - buffer2.addAttribute("xmlns", this.settings.xmlNamespace); - } - } - delete this.buffer; - return buffer2.toString(); - } - writeStruct(ns, value, parentXmlns) { - const traits = ns.getMergedTraits(); - const name = ns.isMemberSchema() && !traits.httpPayload ? ns.getMemberTraits().xmlName ?? ns.getMemberName() : traits.xmlName ?? ns.getName(); - if (!name || !ns.isStructSchema()) { - throw new Error(`@aws-sdk/core/protocols - xml serializer, cannot write struct with empty name or non-struct, schema=${ns.getName(true)}.`); - } - const structXmlNode = import_xml_builder3.XmlNode.of(name); - const [xmlnsAttr, xmlns] = this.getXmlnsAttribute(ns, parentXmlns); - for (const [memberName, memberSchema] of ns.structIterator()) { - const val = value[memberName]; - if (val != null || memberSchema.isIdempotencyToken()) { - if (memberSchema.getMergedTraits().xmlAttribute) { - structXmlNode.addAttribute(memberSchema.getMergedTraits().xmlName ?? memberName, this.writeSimple(memberSchema, val)); - continue; - } - if (memberSchema.isListSchema()) { - this.writeList(memberSchema, val, structXmlNode, xmlns); - } else if (memberSchema.isMapSchema()) { - this.writeMap(memberSchema, val, structXmlNode, xmlns); - } else if (memberSchema.isStructSchema()) { - structXmlNode.addChildNode(this.writeStruct(memberSchema, val, xmlns)); - } else { - const memberNode = import_xml_builder3.XmlNode.of(memberSchema.getMergedTraits().xmlName ?? memberSchema.getMemberName()); - this.writeSimpleInto(memberSchema, val, memberNode, xmlns); - structXmlNode.addChildNode(memberNode); - } - } - } - const { $unknown } = value; - if ($unknown && ns.isUnionSchema() && Array.isArray($unknown) && Object.keys(value).length === 1) { - const [k5, v5] = $unknown; - const node = import_xml_builder3.XmlNode.of(k5); - if (typeof v5 !== "string") { - if (value instanceof import_xml_builder3.XmlNode || value instanceof import_xml_builder3.XmlText) { - structXmlNode.addChildNode(value); - } else { - throw new Error(`@aws-sdk - $unknown union member in XML requires value of type string, @aws-sdk/xml-builder::XmlNode or XmlText.`); - } - } - this.writeSimpleInto(0, v5, node, xmlns); - structXmlNode.addChildNode(node); - } - if (xmlns) { - structXmlNode.addAttribute(xmlnsAttr, xmlns); - } - return structXmlNode; - } - writeList(listMember, array2, container, parentXmlns) { - if (!listMember.isMemberSchema()) { - throw new Error(`@aws-sdk/core/protocols - xml serializer, cannot write non-member list: ${listMember.getName(true)}`); - } - const listTraits = listMember.getMergedTraits(); - const listValueSchema = listMember.getValueSchema(); - const listValueTraits = listValueSchema.getMergedTraits(); - const sparse = !!listValueTraits.sparse; - const flat = !!listTraits.xmlFlattened; - const [xmlnsAttr, xmlns] = this.getXmlnsAttribute(listMember, parentXmlns); - const writeItem = (container2, value) => { - if (listValueSchema.isListSchema()) { - this.writeList(listValueSchema, Array.isArray(value) ? value : [value], container2, xmlns); - } else if (listValueSchema.isMapSchema()) { - this.writeMap(listValueSchema, value, container2, xmlns); - } else if (listValueSchema.isStructSchema()) { - const struct2 = this.writeStruct(listValueSchema, value, xmlns); - container2.addChildNode(struct2.withName(flat ? listTraits.xmlName ?? listMember.getMemberName() : listValueTraits.xmlName ?? "member")); - } else { - const listItemNode = import_xml_builder3.XmlNode.of(flat ? listTraits.xmlName ?? listMember.getMemberName() : listValueTraits.xmlName ?? "member"); - this.writeSimpleInto(listValueSchema, value, listItemNode, xmlns); - container2.addChildNode(listItemNode); - } - }; - if (flat) { - for (const value of array2) { - if (sparse || value != null) { - writeItem(container, value); - } - } - } else { - const listNode = import_xml_builder3.XmlNode.of(listTraits.xmlName ?? listMember.getMemberName()); - if (xmlns) { - listNode.addAttribute(xmlnsAttr, xmlns); - } - for (const value of array2) { - if (sparse || value != null) { - writeItem(listNode, value); - } - } - container.addChildNode(listNode); - } - } - writeMap(mapMember, map4, container, parentXmlns, containerIsMap = false) { - if (!mapMember.isMemberSchema()) { - throw new Error(`@aws-sdk/core/protocols - xml serializer, cannot write non-member map: ${mapMember.getName(true)}`); - } - const mapTraits = mapMember.getMergedTraits(); - const mapKeySchema = mapMember.getKeySchema(); - const mapKeyTraits = mapKeySchema.getMergedTraits(); - const keyTag = mapKeyTraits.xmlName ?? "key"; - const mapValueSchema = mapMember.getValueSchema(); - const mapValueTraits = mapValueSchema.getMergedTraits(); - const valueTag = mapValueTraits.xmlName ?? "value"; - const sparse = !!mapValueTraits.sparse; - const flat = !!mapTraits.xmlFlattened; - const [xmlnsAttr, xmlns] = this.getXmlnsAttribute(mapMember, parentXmlns); - const addKeyValue = (entry, key, val) => { - const keyNode = import_xml_builder3.XmlNode.of(keyTag, key); - const [keyXmlnsAttr, keyXmlns] = this.getXmlnsAttribute(mapKeySchema, xmlns); - if (keyXmlns) { - keyNode.addAttribute(keyXmlnsAttr, keyXmlns); - } - entry.addChildNode(keyNode); - let valueNode = import_xml_builder3.XmlNode.of(valueTag); - if (mapValueSchema.isListSchema()) { - this.writeList(mapValueSchema, val, valueNode, xmlns); - } else if (mapValueSchema.isMapSchema()) { - this.writeMap(mapValueSchema, val, valueNode, xmlns, true); - } else if (mapValueSchema.isStructSchema()) { - valueNode = this.writeStruct(mapValueSchema, val, xmlns); - } else { - this.writeSimpleInto(mapValueSchema, val, valueNode, xmlns); - } - entry.addChildNode(valueNode); - }; - if (flat) { - for (const [key, val] of Object.entries(map4)) { - if (sparse || val != null) { - const entry = import_xml_builder3.XmlNode.of(mapTraits.xmlName ?? mapMember.getMemberName()); - addKeyValue(entry, key, val); - container.addChildNode(entry); - } - } - } else { - let mapNode; - if (!containerIsMap) { - mapNode = import_xml_builder3.XmlNode.of(mapTraits.xmlName ?? mapMember.getMemberName()); - if (xmlns) { - mapNode.addAttribute(xmlnsAttr, xmlns); - } - container.addChildNode(mapNode); - } - for (const [key, val] of Object.entries(map4)) { - if (sparse || val != null) { - const entry = import_xml_builder3.XmlNode.of("entry"); - addKeyValue(entry, key, val); - (containerIsMap ? container : mapNode).addChildNode(entry); - } - } - } - } - writeSimple(_schema, value) { - if (null === value) { - throw new Error("@aws-sdk/core/protocols - (XML serializer) cannot write null value."); - } - const ns = NormalizedSchema.of(_schema); - let nodeContents = null; - if (value && typeof value === "object") { - if (ns.isBlobSchema()) { - nodeContents = (this.serdeContext?.base64Encoder ?? import_util_base647.toBase64)(value); - } else if (ns.isTimestampSchema() && value instanceof Date) { - const format2 = determineTimestampFormat(ns, this.settings); - switch (format2) { - case 5: - nodeContents = value.toISOString().replace(".000Z", "Z"); - break; - case 6: - nodeContents = (0, import_smithy_client7.dateToUtcString)(value); - break; - case 7: - nodeContents = String(value.getTime() / 1e3); - break; - default: - console.warn("Missing timestamp format, using http date", value); - nodeContents = (0, import_smithy_client7.dateToUtcString)(value); - break; - } - } else if (ns.isBigDecimalSchema() && value) { - if (value instanceof NumericValue) { - return value.string; - } - return String(value); - } else if (ns.isMapSchema() || ns.isListSchema()) { - throw new Error("@aws-sdk/core/protocols - xml serializer, cannot call _write() on List/Map schema, call writeList or writeMap() instead."); - } else { - throw new Error(`@aws-sdk/core/protocols - xml serializer, unhandled schema type for object value and schema: ${ns.getName(true)}`); - } - } - if (ns.isBooleanSchema() || ns.isNumericSchema() || ns.isBigIntegerSchema() || ns.isBigDecimalSchema()) { - nodeContents = String(value); - } - if (ns.isStringSchema()) { - if (value === void 0 && ns.isIdempotencyToken()) { - nodeContents = (0, import_uuid2.v4)(); - } else { - nodeContents = String(value); - } - } - if (nodeContents === null) { - throw new Error(`Unhandled schema-value pair ${ns.getName(true)}=${value}`); - } - return nodeContents; - } - writeSimpleInto(_schema, value, into, parentXmlns) { - const nodeContents = this.writeSimple(_schema, value); - const ns = NormalizedSchema.of(_schema); - const content = new import_xml_builder3.XmlText(nodeContents); - const [xmlnsAttr, xmlns] = this.getXmlnsAttribute(ns, parentXmlns); - if (xmlns) { - into.addAttribute(xmlnsAttr, xmlns); - } - into.addChildNode(content); - } - getXmlnsAttribute(ns, parentXmlns) { - const traits = ns.getMergedTraits(); - const [prefix, xmlns] = traits.xmlNamespace ?? []; - if (xmlns && xmlns !== parentXmlns) { - return [prefix ? `xmlns:${prefix}` : "xmlns", xmlns]; - } - return [void 0, void 0]; - } - }; - } -}); - -// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/xml/XmlCodec.js -var XmlCodec; -var init_XmlCodec = __esm({ - "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/xml/XmlCodec.js"() { - init_ConfigurableSerdeContext(); - init_XmlShapeDeserializer(); - init_XmlShapeSerializer(); - XmlCodec = class extends SerdeContextConfig { - settings; - constructor(settings) { - super(); - this.settings = settings; - } - createSerializer() { - const serializer = new XmlShapeSerializer(this.settings); - serializer.setSerdeContext(this.serdeContext); - return serializer; - } - createDeserializer() { - const deserializer = new XmlShapeDeserializer(this.settings); - deserializer.setSerdeContext(this.serdeContext); - return deserializer; - } - }; - } -}); - -// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/xml/AwsRestXmlProtocol.js -var AwsRestXmlProtocol; -var init_AwsRestXmlProtocol = __esm({ - "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/xml/AwsRestXmlProtocol.js"() { - init_protocols(); - init_schema3(); - init_ProtocolLib(); - init_parseXmlBody(); - init_XmlCodec(); - AwsRestXmlProtocol = class extends HttpBindingProtocol { - codec; - serializer; - deserializer; - mixin = new ProtocolLib(); - constructor(options) { - super(options); - const settings = { - timestampFormat: { - useTrait: true, - default: 5 - }, - httpBindings: true, - xmlNamespace: options.xmlNamespace, - serviceNamespace: options.defaultNamespace - }; - this.codec = new XmlCodec(settings); - this.serializer = new HttpInterceptingShapeSerializer(this.codec.createSerializer(), settings); - this.deserializer = new HttpInterceptingShapeDeserializer(this.codec.createDeserializer(), settings); - this.compositeErrorRegistry; - } - getPayloadCodec() { - return this.codec; - } - getShapeId() { - return "aws.protocols#restXml"; - } - async serializeRequest(operationSchema, input, context) { - const request = await super.serializeRequest(operationSchema, input, context); - const inputSchema = NormalizedSchema.of(operationSchema.input); - if (!request.headers["content-type"]) { - const contentType = this.mixin.resolveRestContentType(this.getDefaultContentType(), inputSchema); - if (contentType) { - request.headers["content-type"] = contentType; - } - } - if (typeof request.body === "string" && request.headers["content-type"] === this.getDefaultContentType() && !request.body.startsWith("' + request.body; - } - return request; - } - async deserializeResponse(operationSchema, context, response) { - return super.deserializeResponse(operationSchema, context, response); - } - async handleError(operationSchema, context, response, dataObject, metadata) { - const errorIdentifier = loadRestXmlErrorCode(response, dataObject) ?? "Unknown"; - this.mixin.compose(this.compositeErrorRegistry, errorIdentifier, this.options.defaultNamespace); - if (dataObject.Error && typeof dataObject.Error === "object") { - for (const key of Object.keys(dataObject.Error)) { - dataObject[key] = dataObject.Error[key]; - if (key.toLowerCase() === "message") { - dataObject.message = dataObject.Error[key]; - } - } - } - if (dataObject.RequestId && !metadata.requestId) { - metadata.requestId = dataObject.RequestId; - } - const { errorSchema, errorMetadata } = await this.mixin.getErrorSchemaOrThrowBaseException(errorIdentifier, this.options.defaultNamespace, response, dataObject, metadata); - const ns = NormalizedSchema.of(errorSchema); - const message2 = dataObject.Error?.message ?? dataObject.Error?.Message ?? dataObject.message ?? dataObject.Message ?? "UnknownError"; - const ErrorCtor = this.compositeErrorRegistry.getErrorCtor(errorSchema) ?? Error; - const exception = new ErrorCtor(message2); - await this.deserializeHttpMessage(errorSchema, context, response, dataObject); - const output = {}; - for (const [name, member2] of ns.structIterator()) { - const target = member2.getMergedTraits().xmlName ?? name; - const value = dataObject.Error?.[target] ?? dataObject[target]; - output[name] = this.codec.createDeserializer().readSchema(member2, value); - } - throw this.mixin.decorateServiceException(Object.assign(exception, errorMetadata, { - $fault: ns.getMergedTraits().error, - message: message2 - }, output), dataObject); - } - getDefaultContentType() { - return "application/xml"; - } - hasUnstructuredPayloadBinding(ns) { - for (const [, member2] of ns.structIterator()) { - if (member2.getMergedTraits().httpPayload) { - return !(member2.isStructSchema() || member2.isMapSchema() || member2.isListSchema()); - } - } - return false; - } - }; - } -}); - -// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/index.js -var protocols_exports2 = {}; -__export(protocols_exports2, { - AwsEc2QueryProtocol: () => AwsEc2QueryProtocol, - AwsJson1_0Protocol: () => AwsJson1_0Protocol, - AwsJson1_1Protocol: () => AwsJson1_1Protocol, - AwsJsonRpcProtocol: () => AwsJsonRpcProtocol, - AwsQueryProtocol: () => AwsQueryProtocol, - AwsRestJsonProtocol: () => AwsRestJsonProtocol, - AwsRestXmlProtocol: () => AwsRestXmlProtocol, - AwsSmithyRpcV2CborProtocol: () => AwsSmithyRpcV2CborProtocol, - JsonCodec: () => JsonCodec, - JsonShapeDeserializer: () => JsonShapeDeserializer, - JsonShapeSerializer: () => JsonShapeSerializer, - QueryShapeSerializer: () => QueryShapeSerializer, - XmlCodec: () => XmlCodec, - XmlShapeDeserializer: () => XmlShapeDeserializer, - XmlShapeSerializer: () => XmlShapeSerializer, - _toBool: () => _toBool, - _toNum: () => _toNum, - _toStr: () => _toStr, - awsExpectUnion: () => awsExpectUnion, - loadRestJsonErrorCode: () => loadRestJsonErrorCode, - loadRestXmlErrorCode: () => loadRestXmlErrorCode, - parseJsonBody: () => parseJsonBody, - parseJsonErrorBody: () => parseJsonErrorBody, - parseXmlBody: () => parseXmlBody, - parseXmlErrorBody: () => parseXmlErrorBody -}); -var init_protocols2 = __esm({ - "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/protocols/index.js"() { - init_AwsSmithyRpcV2CborProtocol(); - init_coercing_serializers(); - init_AwsJson1_0Protocol(); - init_AwsJson1_1Protocol(); - init_AwsJsonRpcProtocol(); - init_AwsRestJsonProtocol(); - init_JsonCodec(); - init_JsonShapeDeserializer(); - init_JsonShapeSerializer(); - init_awsExpectUnion(); - init_parseJsonBody(); - init_AwsEc2QueryProtocol(); - init_AwsQueryProtocol(); - init_QuerySerializerSettings(); - init_QueryShapeSerializer(); - init_AwsRestXmlProtocol(); - init_XmlCodec(); - init_XmlShapeDeserializer(); - init_XmlShapeSerializer(); - init_parseXmlBody(); - } -}); - -// node_modules/.pnpm/@smithy+signature-v4@5.3.13/node_modules/@smithy/signature-v4/dist-cjs/index.js -var require_dist_cjs30 = __commonJS({ - "node_modules/.pnpm/@smithy+signature-v4@5.3.13/node_modules/@smithy/signature-v4/dist-cjs/index.js"(exports) { - "use strict"; - var utilHexEncoding = require_dist_cjs12(); - var utilUtf8 = require_dist_cjs6(); - var isArrayBuffer = require_dist_cjs4(); - var protocolHttp = require_dist_cjs2(); - var utilMiddleware = require_dist_cjs18(); - var utilUriEscape = require_dist_cjs8(); - var ALGORITHM_QUERY_PARAM = "X-Amz-Algorithm"; - var CREDENTIAL_QUERY_PARAM = "X-Amz-Credential"; - var AMZ_DATE_QUERY_PARAM = "X-Amz-Date"; - var SIGNED_HEADERS_QUERY_PARAM = "X-Amz-SignedHeaders"; - var EXPIRES_QUERY_PARAM = "X-Amz-Expires"; - var SIGNATURE_QUERY_PARAM = "X-Amz-Signature"; - var TOKEN_QUERY_PARAM = "X-Amz-Security-Token"; - var REGION_SET_PARAM = "X-Amz-Region-Set"; - var AUTH_HEADER = "authorization"; - var AMZ_DATE_HEADER = AMZ_DATE_QUERY_PARAM.toLowerCase(); - var DATE_HEADER = "date"; - var GENERATED_HEADERS = [AUTH_HEADER, AMZ_DATE_HEADER, DATE_HEADER]; - var SIGNATURE_HEADER = SIGNATURE_QUERY_PARAM.toLowerCase(); - var SHA256_HEADER = "x-amz-content-sha256"; - var TOKEN_HEADER = TOKEN_QUERY_PARAM.toLowerCase(); - var HOST_HEADER = "host"; - var ALWAYS_UNSIGNABLE_HEADERS = { - authorization: true, - "cache-control": true, - connection: true, - expect: true, - from: true, - "keep-alive": true, - "max-forwards": true, - pragma: true, - referer: true, - te: true, - trailer: true, - "transfer-encoding": true, - upgrade: true, - "user-agent": true, - "x-amzn-trace-id": true - }; - var PROXY_HEADER_PATTERN = /^proxy-/; - var SEC_HEADER_PATTERN = /^sec-/; - var UNSIGNABLE_PATTERNS = [/^proxy-/i, /^sec-/i]; - var ALGORITHM_IDENTIFIER = "AWS4-HMAC-SHA256"; - var ALGORITHM_IDENTIFIER_V4A = "AWS4-ECDSA-P256-SHA256"; - var EVENT_ALGORITHM_IDENTIFIER = "AWS4-HMAC-SHA256-PAYLOAD"; - var UNSIGNED_PAYLOAD = "UNSIGNED-PAYLOAD"; - var MAX_CACHE_SIZE = 50; - var KEY_TYPE_IDENTIFIER = "aws4_request"; - var MAX_PRESIGNED_TTL = 60 * 60 * 24 * 7; - var signingKeyCache = {}; - var cacheQueue = []; - var createScope = (shortDate, region, service) => `${shortDate}/${region}/${service}/${KEY_TYPE_IDENTIFIER}`; - var getSigningKey = async (sha256Constructor, credentials, shortDate, region, service) => { - const credsHash = await hmac3(sha256Constructor, credentials.secretAccessKey, credentials.accessKeyId); - const cacheKey = `${shortDate}:${region}:${service}:${utilHexEncoding.toHex(credsHash)}:${credentials.sessionToken}`; - if (cacheKey in signingKeyCache) { - return signingKeyCache[cacheKey]; - } - cacheQueue.push(cacheKey); - while (cacheQueue.length > MAX_CACHE_SIZE) { - delete signingKeyCache[cacheQueue.shift()]; - } - let key = `AWS4${credentials.secretAccessKey}`; - for (const signable of [shortDate, region, service, KEY_TYPE_IDENTIFIER]) { - key = await hmac3(sha256Constructor, key, signable); - } - return signingKeyCache[cacheKey] = key; - }; - var clearCredentialCache = () => { - cacheQueue.length = 0; - Object.keys(signingKeyCache).forEach((cacheKey) => { - delete signingKeyCache[cacheKey]; - }); - }; - var hmac3 = (ctor, secret, data2) => { - const hash2 = new ctor(secret); - hash2.update(utilUtf8.toUint8Array(data2)); - return hash2.digest(); - }; - var getCanonicalHeaders = ({ headers }, unsignableHeaders, signableHeaders) => { - const canonical = {}; - for (const headerName of Object.keys(headers).sort()) { - if (headers[headerName] == void 0) { - continue; - } - const canonicalHeaderName = headerName.toLowerCase(); - if (canonicalHeaderName in ALWAYS_UNSIGNABLE_HEADERS || unsignableHeaders?.has(canonicalHeaderName) || PROXY_HEADER_PATTERN.test(canonicalHeaderName) || SEC_HEADER_PATTERN.test(canonicalHeaderName)) { - if (!signableHeaders || signableHeaders && !signableHeaders.has(canonicalHeaderName)) { - continue; - } - } - canonical[canonicalHeaderName] = headers[headerName].trim().replace(/\s+/g, " "); - } - return canonical; - }; - var getPayloadHash = async ({ headers, body }, hashConstructor) => { - for (const headerName of Object.keys(headers)) { - if (headerName.toLowerCase() === SHA256_HEADER) { - return headers[headerName]; - } - } - if (body == void 0) { - return "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"; - } else if (typeof body === "string" || ArrayBuffer.isView(body) || isArrayBuffer.isArrayBuffer(body)) { - const hashCtor = new hashConstructor(); - hashCtor.update(utilUtf8.toUint8Array(body)); - return utilHexEncoding.toHex(await hashCtor.digest()); - } - return UNSIGNED_PAYLOAD; - }; - var HeaderFormatter = class { - format(headers) { - const chunks = []; - for (const headerName of Object.keys(headers)) { - const bytes = utilUtf8.fromUtf8(headerName); - chunks.push(Uint8Array.from([bytes.byteLength]), bytes, this.formatHeaderValue(headers[headerName])); - } - const out = new Uint8Array(chunks.reduce((carry, bytes) => carry + bytes.byteLength, 0)); - let position = 0; - for (const chunk of chunks) { - out.set(chunk, position); - position += chunk.byteLength; - } - return out; - } - formatHeaderValue(header) { - switch (header.type) { - case "boolean": - return Uint8Array.from([header.value ? 0 : 1]); - case "byte": - return Uint8Array.from([2, header.value]); - case "short": - const shortView = new DataView(new ArrayBuffer(3)); - shortView.setUint8(0, 3); - shortView.setInt16(1, header.value, false); - return new Uint8Array(shortView.buffer); - case "integer": - const intView = new DataView(new ArrayBuffer(5)); - intView.setUint8(0, 4); - intView.setInt32(1, header.value, false); - return new Uint8Array(intView.buffer); - case "long": - const longBytes = new Uint8Array(9); - longBytes[0] = 5; - longBytes.set(header.value.bytes, 1); - return longBytes; - case "binary": - const binView = new DataView(new ArrayBuffer(3 + header.value.byteLength)); - binView.setUint8(0, 6); - binView.setUint16(1, header.value.byteLength, false); - const binBytes = new Uint8Array(binView.buffer); - binBytes.set(header.value, 3); - return binBytes; - case "string": - const utf8Bytes = utilUtf8.fromUtf8(header.value); - const strView = new DataView(new ArrayBuffer(3 + utf8Bytes.byteLength)); - strView.setUint8(0, 7); - strView.setUint16(1, utf8Bytes.byteLength, false); - const strBytes = new Uint8Array(strView.buffer); - strBytes.set(utf8Bytes, 3); - return strBytes; - case "timestamp": - const tsBytes = new Uint8Array(9); - tsBytes[0] = 8; - tsBytes.set(Int64.fromNumber(header.value.valueOf()).bytes, 1); - return tsBytes; - case "uuid": - if (!UUID_PATTERN2.test(header.value)) { - throw new Error(`Invalid UUID received: ${header.value}`); - } - const uuidBytes = new Uint8Array(17); - uuidBytes[0] = 9; - uuidBytes.set(utilHexEncoding.fromHex(header.value.replace(/\-/g, "")), 1); - return uuidBytes; - } - } - }; - var HEADER_VALUE_TYPE; - (function(HEADER_VALUE_TYPE2) { - HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["boolTrue"] = 0] = "boolTrue"; - HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["boolFalse"] = 1] = "boolFalse"; - HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["byte"] = 2] = "byte"; - HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["short"] = 3] = "short"; - HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["integer"] = 4] = "integer"; - HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["long"] = 5] = "long"; - HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["byteArray"] = 6] = "byteArray"; - HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["string"] = 7] = "string"; - HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["timestamp"] = 8] = "timestamp"; - HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["uuid"] = 9] = "uuid"; - })(HEADER_VALUE_TYPE || (HEADER_VALUE_TYPE = {})); - var UUID_PATTERN2 = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/; - var Int64 = class _Int64 { - bytes; - constructor(bytes) { - this.bytes = bytes; - if (bytes.byteLength !== 8) { - throw new Error("Int64 buffers must be exactly 8 bytes"); - } - } - static fromNumber(number4) { - if (number4 > 9223372036854776e3 || number4 < -9223372036854776e3) { - throw new Error(`${number4} is too large (or, if negative, too small) to represent as an Int64`); - } - const bytes = new Uint8Array(8); - for (let i5 = 7, remaining = Math.abs(Math.round(number4)); i5 > -1 && remaining > 0; i5--, remaining /= 256) { - bytes[i5] = remaining; - } - if (number4 < 0) { - negate(bytes); - } - return new _Int64(bytes); - } - valueOf() { - const bytes = this.bytes.slice(0); - const negative = bytes[0] & 128; - if (negative) { - negate(bytes); - } - return parseInt(utilHexEncoding.toHex(bytes), 16) * (negative ? -1 : 1); - } - toString() { - return String(this.valueOf()); - } - }; - function negate(bytes) { - for (let i5 = 0; i5 < 8; i5++) { - bytes[i5] ^= 255; - } - for (let i5 = 7; i5 > -1; i5--) { - bytes[i5]++; - if (bytes[i5] !== 0) - break; - } - } - var hasHeader = (soughtHeader, headers) => { - soughtHeader = soughtHeader.toLowerCase(); - for (const headerName of Object.keys(headers)) { - if (soughtHeader === headerName.toLowerCase()) { - return true; - } - } - return false; - }; - var moveHeadersToQuery = (request, options = {}) => { - const { headers, query = {} } = protocolHttp.HttpRequest.clone(request); - for (const name of Object.keys(headers)) { - const lname = name.toLowerCase(); - if (lname.slice(0, 6) === "x-amz-" && !options.unhoistableHeaders?.has(lname) || options.hoistableHeaders?.has(lname)) { - query[name] = headers[name]; - delete headers[name]; - } - } - return { - ...request, - headers, - query - }; - }; - var prepareRequest = (request) => { - request = protocolHttp.HttpRequest.clone(request); - for (const headerName of Object.keys(request.headers)) { - if (GENERATED_HEADERS.indexOf(headerName.toLowerCase()) > -1) { - delete request.headers[headerName]; - } - } - return request; - }; - var getCanonicalQuery = ({ query = {} }) => { - const keys = []; - const serialized = {}; - for (const key of Object.keys(query)) { - if (key.toLowerCase() === SIGNATURE_HEADER) { - continue; - } - const encodedKey = utilUriEscape.escapeUri(key); - keys.push(encodedKey); - const value = query[key]; - if (typeof value === "string") { - serialized[encodedKey] = `${encodedKey}=${utilUriEscape.escapeUri(value)}`; - } else if (Array.isArray(value)) { - serialized[encodedKey] = value.slice(0).reduce((encoded, value2) => encoded.concat([`${encodedKey}=${utilUriEscape.escapeUri(value2)}`]), []).sort().join("&"); - } - } - return keys.sort().map((key) => serialized[key]).filter((serialized2) => serialized2).join("&"); - }; - var iso8601 = (time5) => toDate2(time5).toISOString().replace(/\.\d{3}Z$/, "Z"); - var toDate2 = (time5) => { - if (typeof time5 === "number") { - return new Date(time5 * 1e3); - } - if (typeof time5 === "string") { - if (Number(time5)) { - return new Date(Number(time5) * 1e3); - } - return new Date(time5); - } - return time5; - }; - var SignatureV4Base = class { - service; - regionProvider; - credentialProvider; - sha256; - uriEscapePath; - applyChecksum; - constructor({ applyChecksum, credentials, region, service, sha256: sha2563, uriEscapePath = true }) { - this.service = service; - this.sha256 = sha2563; - this.uriEscapePath = uriEscapePath; - this.applyChecksum = typeof applyChecksum === "boolean" ? applyChecksum : true; - this.regionProvider = utilMiddleware.normalizeProvider(region); - this.credentialProvider = utilMiddleware.normalizeProvider(credentials); - } - createCanonicalRequest(request, canonicalHeaders, payloadHash) { - const sortedHeaders = Object.keys(canonicalHeaders).sort(); - return `${request.method} -${this.getCanonicalPath(request)} -${getCanonicalQuery(request)} -${sortedHeaders.map((name) => `${name}:${canonicalHeaders[name]}`).join("\n")} - -${sortedHeaders.join(";")} -${payloadHash}`; - } - async createStringToSign(longDate, credentialScope, canonicalRequest, algorithmIdentifier) { - const hash2 = new this.sha256(); - hash2.update(utilUtf8.toUint8Array(canonicalRequest)); - const hashedRequest = await hash2.digest(); - return `${algorithmIdentifier} -${longDate} -${credentialScope} -${utilHexEncoding.toHex(hashedRequest)}`; - } - getCanonicalPath({ path: path53 }) { - if (this.uriEscapePath) { - const normalizedPathSegments = []; - for (const pathSegment of path53.split("/")) { - if (pathSegment?.length === 0) - continue; - if (pathSegment === ".") - continue; - if (pathSegment === "..") { - normalizedPathSegments.pop(); - } else { - normalizedPathSegments.push(pathSegment); - } - } - const normalizedPath = `${path53?.startsWith("/") ? "/" : ""}${normalizedPathSegments.join("/")}${normalizedPathSegments.length > 0 && path53?.endsWith("/") ? "/" : ""}`; - const doubleEncoded = utilUriEscape.escapeUri(normalizedPath); - return doubleEncoded.replace(/%2F/g, "/"); - } - return path53; - } - validateResolvedCredentials(credentials) { - if (typeof credentials !== "object" || typeof credentials.accessKeyId !== "string" || typeof credentials.secretAccessKey !== "string") { - throw new Error("Resolved credential object is not valid"); - } - } - formatDate(now2) { - const longDate = iso8601(now2).replace(/[\-:]/g, ""); - return { - longDate, - shortDate: longDate.slice(0, 8) - }; - } - getCanonicalHeaderList(headers) { - return Object.keys(headers).sort().join(";"); - } - }; - var SignatureV42 = class extends SignatureV4Base { - headerFormatter = new HeaderFormatter(); - constructor({ applyChecksum, credentials, region, service, sha256: sha2563, uriEscapePath = true }) { - super({ - applyChecksum, - credentials, - region, - service, - sha256: sha2563, - uriEscapePath - }); - } - async presign(originalRequest, options = {}) { - const { signingDate = /* @__PURE__ */ new Date(), expiresIn = 3600, unsignableHeaders, unhoistableHeaders, signableHeaders, hoistableHeaders, signingRegion, signingService } = options; - const credentials = await this.credentialProvider(); - this.validateResolvedCredentials(credentials); - const region = signingRegion ?? await this.regionProvider(); - const { longDate, shortDate } = this.formatDate(signingDate); - if (expiresIn > MAX_PRESIGNED_TTL) { - return Promise.reject("Signature version 4 presigned URLs must have an expiration date less than one week in the future"); - } - const scope = createScope(shortDate, region, signingService ?? this.service); - const request = moveHeadersToQuery(prepareRequest(originalRequest), { unhoistableHeaders, hoistableHeaders }); - if (credentials.sessionToken) { - request.query[TOKEN_QUERY_PARAM] = credentials.sessionToken; - } - request.query[ALGORITHM_QUERY_PARAM] = ALGORITHM_IDENTIFIER; - request.query[CREDENTIAL_QUERY_PARAM] = `${credentials.accessKeyId}/${scope}`; - request.query[AMZ_DATE_QUERY_PARAM] = longDate; - request.query[EXPIRES_QUERY_PARAM] = expiresIn.toString(10); - const canonicalHeaders = getCanonicalHeaders(request, unsignableHeaders, signableHeaders); - request.query[SIGNED_HEADERS_QUERY_PARAM] = this.getCanonicalHeaderList(canonicalHeaders); - request.query[SIGNATURE_QUERY_PARAM] = await this.getSignature(longDate, scope, this.getSigningKey(credentials, region, shortDate, signingService), this.createCanonicalRequest(request, canonicalHeaders, await getPayloadHash(originalRequest, this.sha256))); - return request; - } - async sign(toSign, options) { - if (typeof toSign === "string") { - return this.signString(toSign, options); - } else if (toSign.headers && toSign.payload) { - return this.signEvent(toSign, options); - } else if (toSign.message) { - return this.signMessage(toSign, options); - } else { - return this.signRequest(toSign, options); - } - } - async signEvent({ headers, payload: payload2 }, { signingDate = /* @__PURE__ */ new Date(), priorSignature, signingRegion, signingService }) { - const region = signingRegion ?? await this.regionProvider(); - const { shortDate, longDate } = this.formatDate(signingDate); - const scope = createScope(shortDate, region, signingService ?? this.service); - const hashedPayload = await getPayloadHash({ headers: {}, body: payload2 }, this.sha256); - const hash2 = new this.sha256(); - hash2.update(headers); - const hashedHeaders = utilHexEncoding.toHex(await hash2.digest()); - const stringToSign = [ - EVENT_ALGORITHM_IDENTIFIER, - longDate, - scope, - priorSignature, - hashedHeaders, - hashedPayload - ].join("\n"); - return this.signString(stringToSign, { signingDate, signingRegion: region, signingService }); - } - async signMessage(signableMessage, { signingDate = /* @__PURE__ */ new Date(), signingRegion, signingService }) { - const promise2 = this.signEvent({ - headers: this.headerFormatter.format(signableMessage.message.headers), - payload: signableMessage.message.body - }, { - signingDate, - signingRegion, - signingService, - priorSignature: signableMessage.priorSignature - }); - return promise2.then((signature) => { - return { message: signableMessage.message, signature }; - }); - } - async signString(stringToSign, { signingDate = /* @__PURE__ */ new Date(), signingRegion, signingService } = {}) { - const credentials = await this.credentialProvider(); - this.validateResolvedCredentials(credentials); - const region = signingRegion ?? await this.regionProvider(); - const { shortDate } = this.formatDate(signingDate); - const hash2 = new this.sha256(await this.getSigningKey(credentials, region, shortDate, signingService)); - hash2.update(utilUtf8.toUint8Array(stringToSign)); - return utilHexEncoding.toHex(await hash2.digest()); - } - async signRequest(requestToSign, { signingDate = /* @__PURE__ */ new Date(), signableHeaders, unsignableHeaders, signingRegion, signingService } = {}) { - const credentials = await this.credentialProvider(); - this.validateResolvedCredentials(credentials); - const region = signingRegion ?? await this.regionProvider(); - const request = prepareRequest(requestToSign); - const { longDate, shortDate } = this.formatDate(signingDate); - const scope = createScope(shortDate, region, signingService ?? this.service); - request.headers[AMZ_DATE_HEADER] = longDate; - if (credentials.sessionToken) { - request.headers[TOKEN_HEADER] = credentials.sessionToken; - } - const payloadHash = await getPayloadHash(request, this.sha256); - if (!hasHeader(SHA256_HEADER, request.headers) && this.applyChecksum) { - request.headers[SHA256_HEADER] = payloadHash; - } - const canonicalHeaders = getCanonicalHeaders(request, unsignableHeaders, signableHeaders); - const signature = await this.getSignature(longDate, scope, this.getSigningKey(credentials, region, shortDate, signingService), this.createCanonicalRequest(request, canonicalHeaders, payloadHash)); - request.headers[AUTH_HEADER] = `${ALGORITHM_IDENTIFIER} Credential=${credentials.accessKeyId}/${scope}, SignedHeaders=${this.getCanonicalHeaderList(canonicalHeaders)}, Signature=${signature}`; - return request; - } - async getSignature(longDate, credentialScope, keyPromise, canonicalRequest) { - const stringToSign = await this.createStringToSign(longDate, credentialScope, canonicalRequest, ALGORITHM_IDENTIFIER); - const hash2 = new this.sha256(await keyPromise); - hash2.update(utilUtf8.toUint8Array(stringToSign)); - return utilHexEncoding.toHex(await hash2.digest()); - } - getSigningKey(credentials, region, shortDate, service) { - return getSigningKey(this.sha256, credentials, shortDate, region, service || this.service); - } - }; - var signatureV4aContainer = { - SignatureV4a: null - }; - exports.ALGORITHM_IDENTIFIER = ALGORITHM_IDENTIFIER; - exports.ALGORITHM_IDENTIFIER_V4A = ALGORITHM_IDENTIFIER_V4A; - exports.ALGORITHM_QUERY_PARAM = ALGORITHM_QUERY_PARAM; - exports.ALWAYS_UNSIGNABLE_HEADERS = ALWAYS_UNSIGNABLE_HEADERS; - exports.AMZ_DATE_HEADER = AMZ_DATE_HEADER; - exports.AMZ_DATE_QUERY_PARAM = AMZ_DATE_QUERY_PARAM; - exports.AUTH_HEADER = AUTH_HEADER; - exports.CREDENTIAL_QUERY_PARAM = CREDENTIAL_QUERY_PARAM; - exports.DATE_HEADER = DATE_HEADER; - exports.EVENT_ALGORITHM_IDENTIFIER = EVENT_ALGORITHM_IDENTIFIER; - exports.EXPIRES_QUERY_PARAM = EXPIRES_QUERY_PARAM; - exports.GENERATED_HEADERS = GENERATED_HEADERS; - exports.HOST_HEADER = HOST_HEADER; - exports.KEY_TYPE_IDENTIFIER = KEY_TYPE_IDENTIFIER; - exports.MAX_CACHE_SIZE = MAX_CACHE_SIZE; - exports.MAX_PRESIGNED_TTL = MAX_PRESIGNED_TTL; - exports.PROXY_HEADER_PATTERN = PROXY_HEADER_PATTERN; - exports.REGION_SET_PARAM = REGION_SET_PARAM; - exports.SEC_HEADER_PATTERN = SEC_HEADER_PATTERN; - exports.SHA256_HEADER = SHA256_HEADER; - exports.SIGNATURE_HEADER = SIGNATURE_HEADER; - exports.SIGNATURE_QUERY_PARAM = SIGNATURE_QUERY_PARAM; - exports.SIGNED_HEADERS_QUERY_PARAM = SIGNED_HEADERS_QUERY_PARAM; - exports.SignatureV4 = SignatureV42; - exports.SignatureV4Base = SignatureV4Base; - exports.TOKEN_HEADER = TOKEN_HEADER; - exports.TOKEN_QUERY_PARAM = TOKEN_QUERY_PARAM; - exports.UNSIGNABLE_PATTERNS = UNSIGNABLE_PATTERNS; - exports.UNSIGNED_PAYLOAD = UNSIGNED_PAYLOAD; - exports.clearCredentialCache = clearCredentialCache; - exports.createScope = createScope; - exports.getCanonicalHeaders = getCanonicalHeaders; - exports.getCanonicalQuery = getCanonicalQuery; - exports.getPayloadHash = getPayloadHash; - exports.getSigningKey = getSigningKey; - exports.hasHeader = hasHeader; - exports.moveHeadersToQuery = moveHeadersToQuery; - exports.prepareRequest = prepareRequest; - exports.signatureV4aContainer = signatureV4aContainer; - } -}); - -// node_modules/.pnpm/@smithy+util-config-provider@4.2.2/node_modules/@smithy/util-config-provider/dist-cjs/index.js -var require_dist_cjs31 = __commonJS({ - "node_modules/.pnpm/@smithy+util-config-provider@4.2.2/node_modules/@smithy/util-config-provider/dist-cjs/index.js"(exports) { - "use strict"; - var booleanSelector = (obj, key, type) => { - if (!(key in obj)) - return void 0; - if (obj[key] === "true") - return true; - if (obj[key] === "false") - return false; - throw new Error(`Cannot load ${type} "${key}". Expected "true" or "false", got ${obj[key]}.`); - }; - var numberSelector = (obj, key, type) => { - if (!(key in obj)) - return void 0; - const numberValue = parseInt(obj[key], 10); - if (Number.isNaN(numberValue)) { - throw new TypeError(`Cannot load ${type} '${key}'. Expected number, got '${obj[key]}'.`); - } - return numberValue; - }; - exports.SelectorType = void 0; - (function(SelectorType) { - SelectorType["ENV"] = "env"; - SelectorType["CONFIG"] = "shared config entry"; - })(exports.SelectorType || (exports.SelectorType = {})); - exports.booleanSelector = booleanSelector; - exports.numberSelector = numberSelector; - } -}); - -// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/getSmithyContext.js -var import_types3, getSmithyContext4; -var init_getSmithyContext = __esm({ - "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/getSmithyContext.js"() { - import_types3 = __toESM(require_dist_cjs()); - getSmithyContext4 = (context) => context[import_types3.SMITHY_CONTEXT_KEY] || (context[import_types3.SMITHY_CONTEXT_KEY] = {}); - } -}); - -// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/resolveAuthOptions.js -var resolveAuthOptions; -var init_resolveAuthOptions = __esm({ - "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/resolveAuthOptions.js"() { - resolveAuthOptions = (candidateAuthOptions, authSchemePreference) => { - if (!authSchemePreference || authSchemePreference.length === 0) { - return candidateAuthOptions; - } - const preferredAuthOptions = []; - for (const preferredSchemeName of authSchemePreference) { - for (const candidateAuthOption of candidateAuthOptions) { - const candidateAuthSchemeName = candidateAuthOption.schemeId.split("#")[1]; - if (candidateAuthSchemeName === preferredSchemeName) { - preferredAuthOptions.push(candidateAuthOption); - } - } - } - for (const candidateAuthOption of candidateAuthOptions) { - if (!preferredAuthOptions.find(({ schemeId }) => schemeId === candidateAuthOption.schemeId)) { - preferredAuthOptions.push(candidateAuthOption); - } - } - return preferredAuthOptions; - }; - } -}); - -// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/httpAuthSchemeMiddleware.js -function convertHttpAuthSchemesToMap(httpAuthSchemes) { - const map4 = /* @__PURE__ */ new Map(); - for (const scheme of httpAuthSchemes) { - map4.set(scheme.schemeId, scheme); - } - return map4; -} -var import_util_middleware4, httpAuthSchemeMiddleware; -var init_httpAuthSchemeMiddleware = __esm({ - "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/httpAuthSchemeMiddleware.js"() { - import_util_middleware4 = __toESM(require_dist_cjs18()); - init_resolveAuthOptions(); - httpAuthSchemeMiddleware = (config3, mwOptions) => (next, context) => async (args) => { - const options = config3.httpAuthSchemeProvider(await mwOptions.httpAuthSchemeParametersProvider(config3, context, args.input)); - const authSchemePreference = config3.authSchemePreference ? await config3.authSchemePreference() : []; - const resolvedOptions = resolveAuthOptions(options, authSchemePreference); - const authSchemes = convertHttpAuthSchemesToMap(config3.httpAuthSchemes); - const smithyContext = (0, import_util_middleware4.getSmithyContext)(context); - const failureReasons = []; - for (const option of resolvedOptions) { - const scheme = authSchemes.get(option.schemeId); - if (!scheme) { - failureReasons.push(`HttpAuthScheme \`${option.schemeId}\` was not enabled for this service.`); - continue; - } - const identityProvider = scheme.identityProvider(await mwOptions.identityProviderConfigProvider(config3)); - if (!identityProvider) { - failureReasons.push(`HttpAuthScheme \`${option.schemeId}\` did not have an IdentityProvider configured.`); - continue; - } - const { identityProperties = {}, signingProperties = {} } = option.propertiesExtractor?.(config3, context) || {}; - option.identityProperties = Object.assign(option.identityProperties || {}, identityProperties); - option.signingProperties = Object.assign(option.signingProperties || {}, signingProperties); - smithyContext.selectedHttpAuthScheme = { - httpAuthOption: option, - identity: await identityProvider(option.identityProperties), - signer: scheme.signer - }; - break; - } - if (!smithyContext.selectedHttpAuthScheme) { - throw new Error(failureReasons.join("\n")); - } - return next(args); - }; - } -}); - -// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/getHttpAuthSchemeEndpointRuleSetPlugin.js -var httpAuthSchemeEndpointRuleSetMiddlewareOptions, getHttpAuthSchemeEndpointRuleSetPlugin; -var init_getHttpAuthSchemeEndpointRuleSetPlugin = __esm({ - "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/getHttpAuthSchemeEndpointRuleSetPlugin.js"() { - init_httpAuthSchemeMiddleware(); - httpAuthSchemeEndpointRuleSetMiddlewareOptions = { - step: "serialize", - tags: ["HTTP_AUTH_SCHEME"], - name: "httpAuthSchemeMiddleware", - override: true, - relation: "before", - toMiddleware: "endpointV2Middleware" - }; - getHttpAuthSchemeEndpointRuleSetPlugin = (config3, { httpAuthSchemeParametersProvider, identityProviderConfigProvider }) => ({ - applyToStack: (clientStack) => { - clientStack.addRelativeTo(httpAuthSchemeMiddleware(config3, { - httpAuthSchemeParametersProvider, - identityProviderConfigProvider - }), httpAuthSchemeEndpointRuleSetMiddlewareOptions); - } - }); - } -}); - -// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/getHttpAuthSchemePlugin.js -var httpAuthSchemeMiddlewareOptions, getHttpAuthSchemePlugin; -var init_getHttpAuthSchemePlugin = __esm({ - "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/getHttpAuthSchemePlugin.js"() { - init_httpAuthSchemeMiddleware(); - httpAuthSchemeMiddlewareOptions = { - step: "serialize", - tags: ["HTTP_AUTH_SCHEME"], - name: "httpAuthSchemeMiddleware", - override: true, - relation: "before", - toMiddleware: "serializerMiddleware" - }; - getHttpAuthSchemePlugin = (config3, { httpAuthSchemeParametersProvider, identityProviderConfigProvider }) => ({ - applyToStack: (clientStack) => { - clientStack.addRelativeTo(httpAuthSchemeMiddleware(config3, { - httpAuthSchemeParametersProvider, - identityProviderConfigProvider - }), httpAuthSchemeMiddlewareOptions); - } - }); - } -}); - -// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/index.js -var init_middleware_http_auth_scheme = __esm({ - "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/index.js"() { - init_httpAuthSchemeMiddleware(); - init_getHttpAuthSchemeEndpointRuleSetPlugin(); - init_getHttpAuthSchemePlugin(); - } -}); - -// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/middleware-http-signing/httpSigningMiddleware.js -var import_protocol_http6, import_util_middleware5, defaultErrorHandler, defaultSuccessHandler, httpSigningMiddleware; -var init_httpSigningMiddleware = __esm({ - "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/middleware-http-signing/httpSigningMiddleware.js"() { - import_protocol_http6 = __toESM(require_dist_cjs2()); - import_util_middleware5 = __toESM(require_dist_cjs18()); - defaultErrorHandler = (signingProperties) => (error50) => { - throw error50; - }; - defaultSuccessHandler = (httpResponse, signingProperties) => { - }; - httpSigningMiddleware = (config3) => (next, context) => async (args) => { - if (!import_protocol_http6.HttpRequest.isInstance(args.request)) { - return next(args); - } - const smithyContext = (0, import_util_middleware5.getSmithyContext)(context); - const scheme = smithyContext.selectedHttpAuthScheme; - if (!scheme) { - throw new Error(`No HttpAuthScheme was selected: unable to sign request`); - } - const { httpAuthOption: { signingProperties = {} }, identity, signer } = scheme; - const output = await next({ - ...args, - request: await signer.sign(args.request, identity, signingProperties) - }).catch((signer.errorHandler || defaultErrorHandler)(signingProperties)); - (signer.successHandler || defaultSuccessHandler)(output.response, signingProperties); - return output; - }; - } -}); - -// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/middleware-http-signing/getHttpSigningMiddleware.js -var httpSigningMiddlewareOptions, getHttpSigningPlugin; -var init_getHttpSigningMiddleware = __esm({ - "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/middleware-http-signing/getHttpSigningMiddleware.js"() { - init_httpSigningMiddleware(); - httpSigningMiddlewareOptions = { - step: "finalizeRequest", - tags: ["HTTP_SIGNING"], - name: "httpSigningMiddleware", - aliases: ["apiKeyMiddleware", "tokenMiddleware", "awsAuthMiddleware"], - override: true, - relation: "after", - toMiddleware: "retryMiddleware" - }; - getHttpSigningPlugin = (config3) => ({ - applyToStack: (clientStack) => { - clientStack.addRelativeTo(httpSigningMiddleware(config3), httpSigningMiddlewareOptions); - } - }); - } -}); - -// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/middleware-http-signing/index.js -var init_middleware_http_signing = __esm({ - "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/middleware-http-signing/index.js"() { - init_httpSigningMiddleware(); - init_getHttpSigningMiddleware(); - } -}); - -// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/normalizeProvider.js -var normalizeProvider; -var init_normalizeProvider = __esm({ - "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/normalizeProvider.js"() { - normalizeProvider = (input) => { - if (typeof input === "function") - return input; - const promisified = Promise.resolve(input); - return () => promisified; - }; - } -}); - -// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/pagination/createPaginator.js -function createPaginator(ClientCtor, CommandCtor, inputTokenName, outputTokenName, pageSizeTokenName) { - return async function* paginateOperation(config3, input, ...additionalArguments) { - const _input = input; - let token = config3.startingToken ?? _input[inputTokenName]; - let hasNext = true; - let page; - while (hasNext) { - _input[inputTokenName] = token; - if (pageSizeTokenName) { - _input[pageSizeTokenName] = _input[pageSizeTokenName] ?? config3.pageSize; - } - if (config3.client instanceof ClientCtor) { - page = await makePagedClientRequest(CommandCtor, config3.client, input, config3.withCommand, ...additionalArguments); - } else { - throw new Error(`Invalid client, expected instance of ${ClientCtor.name}`); - } - yield page; - const prevToken = token; - token = get(page, outputTokenName); - hasNext = !!(token && (!config3.stopOnSameToken || token !== prevToken)); - } - return void 0; - }; -} -var makePagedClientRequest, get; -var init_createPaginator = __esm({ - "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/pagination/createPaginator.js"() { - makePagedClientRequest = async (CommandCtor, client2, input, withCommand = (_) => _, ...args) => { - let command = new CommandCtor(input); - command = withCommand(command) ?? command; - return await client2.send(command, ...args); - }; - get = (fromObject, path53) => { - let cursor2 = fromObject; - const pathComponents = path53.split("."); - for (const step of pathComponents) { - if (!cursor2 || typeof cursor2 !== "object") { - return void 0; - } - cursor2 = cursor2[step]; - } - return cursor2; - }; - } -}); - -// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/request-builder/requestBuilder.js -var init_requestBuilder2 = __esm({ - "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/request-builder/requestBuilder.js"() { - init_protocols(); - } -}); - -// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/setFeature.js -function setFeature2(context, feature, value) { - if (!context.__smithy_context) { - context.__smithy_context = { - features: {} - }; - } else if (!context.__smithy_context.features) { - context.__smithy_context.features = {}; - } - context.__smithy_context.features[feature] = value; -} -var init_setFeature2 = __esm({ - "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/setFeature.js"() { - } -}); - -// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/util-identity-and-auth/DefaultIdentityProviderConfig.js -var DefaultIdentityProviderConfig; -var init_DefaultIdentityProviderConfig = __esm({ - "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/util-identity-and-auth/DefaultIdentityProviderConfig.js"() { - DefaultIdentityProviderConfig = class { - authSchemes = /* @__PURE__ */ new Map(); - constructor(config3) { - for (const [key, value] of Object.entries(config3)) { - if (value !== void 0) { - this.authSchemes.set(key, value); - } - } - } - getIdentityProvider(schemeId) { - return this.authSchemes.get(schemeId); - } - }; - } -}); - -// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/httpApiKeyAuth.js -var import_protocol_http7, import_types4, HttpApiKeyAuthSigner; -var init_httpApiKeyAuth = __esm({ - "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/httpApiKeyAuth.js"() { - import_protocol_http7 = __toESM(require_dist_cjs2()); - import_types4 = __toESM(require_dist_cjs()); - HttpApiKeyAuthSigner = class { - async sign(httpRequest2, identity, signingProperties) { - if (!signingProperties) { - throw new Error("request could not be signed with `apiKey` since the `name` and `in` signer properties are missing"); - } - if (!signingProperties.name) { - throw new Error("request could not be signed with `apiKey` since the `name` signer property is missing"); - } - if (!signingProperties.in) { - throw new Error("request could not be signed with `apiKey` since the `in` signer property is missing"); - } - if (!identity.apiKey) { - throw new Error("request could not be signed with `apiKey` since the `apiKey` is not defined"); - } - const clonedRequest = import_protocol_http7.HttpRequest.clone(httpRequest2); - if (signingProperties.in === import_types4.HttpApiKeyAuthLocation.QUERY) { - clonedRequest.query[signingProperties.name] = identity.apiKey; - } else if (signingProperties.in === import_types4.HttpApiKeyAuthLocation.HEADER) { - clonedRequest.headers[signingProperties.name] = signingProperties.scheme ? `${signingProperties.scheme} ${identity.apiKey}` : identity.apiKey; - } else { - throw new Error("request can only be signed with `apiKey` locations `query` or `header`, but found: `" + signingProperties.in + "`"); - } - return clonedRequest; - } - }; - } -}); - -// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/httpBearerAuth.js -var import_protocol_http8, HttpBearerAuthSigner; -var init_httpBearerAuth = __esm({ - "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/httpBearerAuth.js"() { - import_protocol_http8 = __toESM(require_dist_cjs2()); - HttpBearerAuthSigner = class { - async sign(httpRequest2, identity, signingProperties) { - const clonedRequest = import_protocol_http8.HttpRequest.clone(httpRequest2); - if (!identity.token) { - throw new Error("request could not be signed with `token` since the `token` is not defined"); - } - clonedRequest.headers["Authorization"] = `Bearer ${identity.token}`; - return clonedRequest; - } - }; - } -}); - -// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/noAuth.js -var NoAuthSigner; -var init_noAuth = __esm({ - "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/noAuth.js"() { - NoAuthSigner = class { - async sign(httpRequest2, identity, signingProperties) { - return httpRequest2; - } - }; - } -}); - -// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/index.js -var init_httpAuthSchemes = __esm({ - "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/index.js"() { - init_httpApiKeyAuth(); - init_httpBearerAuth(); - init_noAuth(); - } -}); - -// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/util-identity-and-auth/memoizeIdentityProvider.js -var createIsIdentityExpiredFunction, EXPIRATION_MS, isIdentityExpired, doesIdentityRequireRefresh, memoizeIdentityProvider; -var init_memoizeIdentityProvider = __esm({ - "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/util-identity-and-auth/memoizeIdentityProvider.js"() { - createIsIdentityExpiredFunction = (expirationMs) => function isIdentityExpired2(identity) { - return doesIdentityRequireRefresh(identity) && identity.expiration.getTime() - Date.now() < expirationMs; - }; - EXPIRATION_MS = 3e5; - isIdentityExpired = createIsIdentityExpiredFunction(EXPIRATION_MS); - doesIdentityRequireRefresh = (identity) => identity.expiration !== void 0; - memoizeIdentityProvider = (provider, isExpired, requiresRefresh) => { - if (provider === void 0) { - return void 0; - } - const normalizedProvider = typeof provider !== "function" ? async () => Promise.resolve(provider) : provider; - let resolved; - let pending; - let hasResult; - let isConstant = false; - const coalesceProvider = async (options) => { - if (!pending) { - pending = normalizedProvider(options); - } - try { - resolved = await pending; - hasResult = true; - isConstant = false; - } finally { - pending = void 0; - } - return resolved; - }; - if (isExpired === void 0) { - return async (options) => { - if (!hasResult || options?.forceRefresh) { - resolved = await coalesceProvider(options); - } - return resolved; - }; - } - return async (options) => { - if (!hasResult || options?.forceRefresh) { - resolved = await coalesceProvider(options); - } - if (isConstant) { - return resolved; - } - if (!requiresRefresh(resolved)) { - isConstant = true; - return resolved; - } - if (isExpired(resolved)) { - await coalesceProvider(options); - return resolved; - } - return resolved; - }; - }; - } -}); - -// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/util-identity-and-auth/index.js -var init_util_identity_and_auth = __esm({ - "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/util-identity-and-auth/index.js"() { - init_DefaultIdentityProviderConfig(); - init_httpAuthSchemes(); - init_memoizeIdentityProvider(); - } -}); - -// node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/index.js -var dist_es_exports = {}; -__export(dist_es_exports, { - DefaultIdentityProviderConfig: () => DefaultIdentityProviderConfig, - EXPIRATION_MS: () => EXPIRATION_MS, - HttpApiKeyAuthSigner: () => HttpApiKeyAuthSigner, - HttpBearerAuthSigner: () => HttpBearerAuthSigner, - NoAuthSigner: () => NoAuthSigner, - createIsIdentityExpiredFunction: () => createIsIdentityExpiredFunction, - createPaginator: () => createPaginator, - doesIdentityRequireRefresh: () => doesIdentityRequireRefresh, - getHttpAuthSchemeEndpointRuleSetPlugin: () => getHttpAuthSchemeEndpointRuleSetPlugin, - getHttpAuthSchemePlugin: () => getHttpAuthSchemePlugin, - getHttpSigningPlugin: () => getHttpSigningPlugin, - getSmithyContext: () => getSmithyContext4, - httpAuthSchemeEndpointRuleSetMiddlewareOptions: () => httpAuthSchemeEndpointRuleSetMiddlewareOptions, - httpAuthSchemeMiddleware: () => httpAuthSchemeMiddleware, - httpAuthSchemeMiddlewareOptions: () => httpAuthSchemeMiddlewareOptions, - httpSigningMiddleware: () => httpSigningMiddleware, - httpSigningMiddlewareOptions: () => httpSigningMiddlewareOptions, - isIdentityExpired: () => isIdentityExpired, - memoizeIdentityProvider: () => memoizeIdentityProvider, - normalizeProvider: () => normalizeProvider, - requestBuilder: () => requestBuilder, - setFeature: () => setFeature2 -}); -var init_dist_es = __esm({ - "node_modules/.pnpm/@smithy+core@3.23.14/node_modules/@smithy/core/dist-es/index.js"() { - init_getSmithyContext(); - init_middleware_http_auth_scheme(); - init_middleware_http_signing(); - init_normalizeProvider(); - init_createPaginator(); - init_requestBuilder2(); - init_setFeature2(); - init_util_identity_and_auth(); - } -}); - -// node_modules/.pnpm/@aws-sdk+middleware-sdk-s3@3.972.28/node_modules/@aws-sdk/middleware-sdk-s3/dist-cjs/index.js -var require_dist_cjs32 = __commonJS({ - "node_modules/.pnpm/@aws-sdk+middleware-sdk-s3@3.972.28/node_modules/@aws-sdk/middleware-sdk-s3/dist-cjs/index.js"(exports) { - "use strict"; - var protocolHttp = require_dist_cjs2(); - var smithyClient = require_dist_cjs27(); - var utilStream = require_dist_cjs13(); - var utilArnParser = require_dist_cjs28(); - var protocols = (init_protocols2(), __toCommonJS(protocols_exports2)); - var schema2 = (init_schema3(), __toCommonJS(schema_exports2)); - var signatureV4 = require_dist_cjs30(); - var utilConfigProvider = require_dist_cjs31(); - var client2 = (init_client2(), __toCommonJS(client_exports)); - var core = (init_dist_es(), __toCommonJS(dist_es_exports)); - var utilMiddleware = require_dist_cjs18(); - var CONTENT_LENGTH_HEADER = "content-length"; - var DECODED_CONTENT_LENGTH_HEADER = "x-amz-decoded-content-length"; - function checkContentLengthHeader() { - return (next, context) => async (args) => { - const { request } = args; - if (protocolHttp.HttpRequest.isInstance(request)) { - if (!(CONTENT_LENGTH_HEADER in request.headers) && !(DECODED_CONTENT_LENGTH_HEADER in request.headers)) { - const message2 = `Are you using a Stream of unknown length as the Body of a PutObject request? Consider using Upload instead from @aws-sdk/lib-storage.`; - if (typeof context?.logger?.warn === "function" && !(context.logger instanceof smithyClient.NoOpLogger)) { - context.logger.warn(message2); - } else { - console.warn(message2); - } - } - } - return next({ ...args }); - }; - } - var checkContentLengthHeaderMiddlewareOptions = { - step: "finalizeRequest", - tags: ["CHECK_CONTENT_LENGTH_HEADER"], - name: "getCheckContentLengthHeaderPlugin", - override: true - }; - var getCheckContentLengthHeaderPlugin = (unused) => ({ - applyToStack: (clientStack) => { - clientStack.add(checkContentLengthHeader(), checkContentLengthHeaderMiddlewareOptions); - } - }); - var regionRedirectEndpointMiddleware = (config3) => { - return (next, context) => async (args) => { - const originalRegion = await config3.region(); - const regionProviderRef = config3.region; - let unlock = () => { - }; - if (context.__s3RegionRedirect) { - Object.defineProperty(config3, "region", { - writable: false, - value: async () => { - return context.__s3RegionRedirect; - } - }); - unlock = () => Object.defineProperty(config3, "region", { - writable: true, - value: regionProviderRef - }); - } - try { - const result = await next(args); - if (context.__s3RegionRedirect) { - unlock(); - const region = await config3.region(); - if (originalRegion !== region) { - throw new Error("Region was not restored following S3 region redirect."); - } - } - return result; - } catch (e5) { - unlock(); - throw e5; - } - }; - }; - var regionRedirectEndpointMiddlewareOptions = { - tags: ["REGION_REDIRECT", "S3"], - name: "regionRedirectEndpointMiddleware", - override: true, - relation: "before", - toMiddleware: "endpointV2Middleware" - }; - function regionRedirectMiddleware(clientConfig) { - return (next, context) => async (args) => { - try { - return await next(args); - } catch (err) { - if (clientConfig.followRegionRedirects) { - const statusCode = err?.$metadata?.httpStatusCode; - const isHeadBucket = context.commandName === "HeadBucketCommand"; - const bucketRegionHeader = err?.$response?.headers?.["x-amz-bucket-region"]; - if (bucketRegionHeader) { - if (statusCode === 301 || statusCode === 400 && (err?.name === "IllegalLocationConstraintException" || isHeadBucket)) { - try { - const actualRegion = bucketRegionHeader; - context.logger?.debug(`Redirecting from ${await clientConfig.region()} to ${actualRegion}`); - context.__s3RegionRedirect = actualRegion; - } catch (e5) { - throw new Error("Region redirect failed: " + e5); - } - return next(args); - } - } - } - throw err; - } - }; - } - var regionRedirectMiddlewareOptions = { - step: "initialize", - tags: ["REGION_REDIRECT", "S3"], - name: "regionRedirectMiddleware", - override: true - }; - var getRegionRedirectMiddlewarePlugin = (clientConfig) => ({ - applyToStack: (clientStack) => { - clientStack.add(regionRedirectMiddleware(clientConfig), regionRedirectMiddlewareOptions); - clientStack.addRelativeTo(regionRedirectEndpointMiddleware(clientConfig), regionRedirectEndpointMiddlewareOptions); - } - }); - var s3ExpiresMiddleware = (config3) => { - return (next, context) => async (args) => { - const result = await next(args); - const { response } = result; - if (protocolHttp.HttpResponse.isInstance(response)) { - if (response.headers.expires) { - response.headers.expiresstring = response.headers.expires; - try { - smithyClient.parseRfc7231DateTime(response.headers.expires); - } catch (e5) { - context.logger?.warn(`AWS SDK Warning for ${context.clientName}::${context.commandName} response parsing (${response.headers.expires}): ${e5}`); - delete response.headers.expires; - } - } - } - return result; - }; - }; - var s3ExpiresMiddlewareOptions = { - tags: ["S3"], - name: "s3ExpiresMiddleware", - override: true, - relation: "after", - toMiddleware: "deserializerMiddleware" - }; - var getS3ExpiresMiddlewarePlugin = (clientConfig) => ({ - applyToStack: (clientStack) => { - clientStack.addRelativeTo(s3ExpiresMiddleware(), s3ExpiresMiddlewareOptions); - } - }); - var S3ExpressIdentityCache = class _S3ExpressIdentityCache { - data; - lastPurgeTime = Date.now(); - static EXPIRED_CREDENTIAL_PURGE_INTERVAL_MS = 3e4; - constructor(data2 = {}) { - this.data = data2; - } - get(key) { - const entry = this.data[key]; - if (!entry) { - return; - } - return entry; - } - set(key, entry) { - this.data[key] = entry; - return entry; - } - delete(key) { - delete this.data[key]; - } - async purgeExpired() { - const now2 = Date.now(); - if (this.lastPurgeTime + _S3ExpressIdentityCache.EXPIRED_CREDENTIAL_PURGE_INTERVAL_MS > now2) { - return; - } - for (const key in this.data) { - const entry = this.data[key]; - if (!entry.isRefreshing) { - const credential = await entry.identity; - if (credential.expiration) { - if (credential.expiration.getTime() < now2) { - delete this.data[key]; - } - } - } - } - } - }; - var S3ExpressIdentityCacheEntry = class { - _identity; - isRefreshing; - accessed; - constructor(_identity, isRefreshing = false, accessed = Date.now()) { - this._identity = _identity; - this.isRefreshing = isRefreshing; - this.accessed = accessed; - } - get identity() { - this.accessed = Date.now(); - return this._identity; - } - }; - var S3ExpressIdentityProviderImpl = class _S3ExpressIdentityProviderImpl { - createSessionFn; - cache; - static REFRESH_WINDOW_MS = 6e4; - constructor(createSessionFn, cache7 = new S3ExpressIdentityCache()) { - this.createSessionFn = createSessionFn; - this.cache = cache7; - } - async getS3ExpressIdentity(awsIdentity, identityProperties) { - const key = identityProperties.Bucket; - const { cache: cache7 } = this; - const entry = cache7.get(key); - if (entry) { - return entry.identity.then((identity) => { - const isExpired = (identity.expiration?.getTime() ?? 0) < Date.now(); - if (isExpired) { - return cache7.set(key, new S3ExpressIdentityCacheEntry(this.getIdentity(key))).identity; - } - const isExpiringSoon = (identity.expiration?.getTime() ?? 0) < Date.now() + _S3ExpressIdentityProviderImpl.REFRESH_WINDOW_MS; - if (isExpiringSoon && !entry.isRefreshing) { - entry.isRefreshing = true; - this.getIdentity(key).then((id) => { - cache7.set(key, new S3ExpressIdentityCacheEntry(Promise.resolve(id))); - }); - } - return identity; - }); - } - return cache7.set(key, new S3ExpressIdentityCacheEntry(this.getIdentity(key))).identity; - } - async getIdentity(key) { - await this.cache.purgeExpired().catch((error50) => { - console.warn("Error while clearing expired entries in S3ExpressIdentityCache: \n" + error50); - }); - const session = await this.createSessionFn(key); - if (!session.Credentials?.AccessKeyId || !session.Credentials?.SecretAccessKey) { - throw new Error("s3#createSession response credential missing AccessKeyId or SecretAccessKey."); - } - const identity = { - accessKeyId: session.Credentials.AccessKeyId, - secretAccessKey: session.Credentials.SecretAccessKey, - sessionToken: session.Credentials.SessionToken, - expiration: session.Credentials.Expiration ? new Date(session.Credentials.Expiration) : void 0 - }; - return identity; - } - }; - var S3_EXPRESS_BUCKET_TYPE = "Directory"; - var S3_EXPRESS_BACKEND = "S3Express"; - var S3_EXPRESS_AUTH_SCHEME = "sigv4-s3express"; - var SESSION_TOKEN_QUERY_PARAM = "X-Amz-S3session-Token"; - var SESSION_TOKEN_HEADER = SESSION_TOKEN_QUERY_PARAM.toLowerCase(); - var NODE_DISABLE_S3_EXPRESS_SESSION_AUTH_ENV_NAME = "AWS_S3_DISABLE_EXPRESS_SESSION_AUTH"; - var NODE_DISABLE_S3_EXPRESS_SESSION_AUTH_INI_NAME = "s3_disable_express_session_auth"; - var NODE_DISABLE_S3_EXPRESS_SESSION_AUTH_OPTIONS = { - environmentVariableSelector: (env2) => utilConfigProvider.booleanSelector(env2, NODE_DISABLE_S3_EXPRESS_SESSION_AUTH_ENV_NAME, utilConfigProvider.SelectorType.ENV), - configFileSelector: (profile) => utilConfigProvider.booleanSelector(profile, NODE_DISABLE_S3_EXPRESS_SESSION_AUTH_INI_NAME, utilConfigProvider.SelectorType.CONFIG), - default: false - }; - var SignatureV4S3Express = class extends signatureV4.SignatureV4 { - async signWithCredentials(requestToSign, credentials, options) { - const credentialsWithoutSessionToken = getCredentialsWithoutSessionToken(credentials); - requestToSign.headers[SESSION_TOKEN_HEADER] = credentials.sessionToken; - const privateAccess = this; - setSingleOverride(privateAccess, credentialsWithoutSessionToken); - return privateAccess.signRequest(requestToSign, options ?? {}); - } - async presignWithCredentials(requestToSign, credentials, options) { - const credentialsWithoutSessionToken = getCredentialsWithoutSessionToken(credentials); - delete requestToSign.headers[SESSION_TOKEN_HEADER]; - requestToSign.headers[SESSION_TOKEN_QUERY_PARAM] = credentials.sessionToken; - requestToSign.query = requestToSign.query ?? {}; - requestToSign.query[SESSION_TOKEN_QUERY_PARAM] = credentials.sessionToken; - const privateAccess = this; - setSingleOverride(privateAccess, credentialsWithoutSessionToken); - return this.presign(requestToSign, options); - } - }; - function getCredentialsWithoutSessionToken(credentials) { - const credentialsWithoutSessionToken = { - accessKeyId: credentials.accessKeyId, - secretAccessKey: credentials.secretAccessKey, - expiration: credentials.expiration - }; - return credentialsWithoutSessionToken; - } - function setSingleOverride(privateAccess, credentialsWithoutSessionToken) { - const id = setTimeout(() => { - throw new Error("SignatureV4S3Express credential override was created but not called."); - }, 10); - const currentCredentialProvider = privateAccess.credentialProvider; - const overrideCredentialsProviderOnce = () => { - clearTimeout(id); - privateAccess.credentialProvider = currentCredentialProvider; - return Promise.resolve(credentialsWithoutSessionToken); - }; - privateAccess.credentialProvider = overrideCredentialsProviderOnce; - } - var s3ExpressMiddleware = (options) => { - return (next, context) => async (args) => { - if (context.endpointV2) { - const endpoint = context.endpointV2; - const isS3ExpressAuth = endpoint.properties?.authSchemes?.[0]?.name === S3_EXPRESS_AUTH_SCHEME; - const isS3ExpressBucket = endpoint.properties?.backend === S3_EXPRESS_BACKEND || endpoint.properties?.bucketType === S3_EXPRESS_BUCKET_TYPE; - if (isS3ExpressBucket) { - client2.setFeature(context, "S3_EXPRESS_BUCKET", "J"); - context.isS3ExpressBucket = true; - } - if (isS3ExpressAuth) { - const requestBucket = args.input.Bucket; - if (requestBucket) { - const s3ExpressIdentity = await options.s3ExpressIdentityProvider.getS3ExpressIdentity(await options.credentials(), { - Bucket: requestBucket - }); - context.s3ExpressIdentity = s3ExpressIdentity; - if (protocolHttp.HttpRequest.isInstance(args.request) && s3ExpressIdentity.sessionToken) { - args.request.headers[SESSION_TOKEN_HEADER] = s3ExpressIdentity.sessionToken; - } - } - } - } - return next(args); - }; - }; - var s3ExpressMiddlewareOptions = { - name: "s3ExpressMiddleware", - step: "build", - tags: ["S3", "S3_EXPRESS"], - override: true - }; - var getS3ExpressPlugin = (options) => ({ - applyToStack: (clientStack) => { - clientStack.add(s3ExpressMiddleware(options), s3ExpressMiddlewareOptions); - } - }); - var signS3Express = async (s3ExpressIdentity, signingOptions, request, sigV4MultiRegionSigner) => { - const signedRequest = await sigV4MultiRegionSigner.signWithCredentials(request, s3ExpressIdentity, {}); - if (signedRequest.headers["X-Amz-Security-Token"] || signedRequest.headers["x-amz-security-token"]) { - throw new Error("X-Amz-Security-Token must not be set for s3-express requests."); - } - return signedRequest; - }; - var defaultErrorHandler2 = (signingProperties) => (error50) => { - throw error50; - }; - var defaultSuccessHandler2 = (httpResponse, signingProperties) => { - }; - var s3ExpressHttpSigningMiddlewareOptions = core.httpSigningMiddlewareOptions; - var s3ExpressHttpSigningMiddleware = (config3) => (next, context) => async (args) => { - if (!protocolHttp.HttpRequest.isInstance(args.request)) { - return next(args); - } - const smithyContext = utilMiddleware.getSmithyContext(context); - const scheme = smithyContext.selectedHttpAuthScheme; - if (!scheme) { - throw new Error(`No HttpAuthScheme was selected: unable to sign request`); - } - const { httpAuthOption: { signingProperties = {} }, identity, signer } = scheme; - let request; - if (context.s3ExpressIdentity) { - request = await signS3Express(context.s3ExpressIdentity, signingProperties, args.request, await config3.signer()); - } else { - request = await signer.sign(args.request, identity, signingProperties); - } - const output = await next({ - ...args, - request - }).catch((signer.errorHandler || defaultErrorHandler2)(signingProperties)); - (signer.successHandler || defaultSuccessHandler2)(output.response, signingProperties); - return output; - }; - var getS3ExpressHttpSigningPlugin = (config3) => ({ - applyToStack: (clientStack) => { - clientStack.addRelativeTo(s3ExpressHttpSigningMiddleware(config3), core.httpSigningMiddlewareOptions); - } - }); - var resolveS3Config = (input, { session }) => { - const [s3ClientProvider, CreateSessionCommandCtor] = session; - const { forcePathStyle, useAccelerateEndpoint, disableMultiregionAccessPoints, followRegionRedirects, s3ExpressIdentityProvider, bucketEndpoint, expectContinueHeader } = input; - return Object.assign(input, { - forcePathStyle: forcePathStyle ?? false, - useAccelerateEndpoint: useAccelerateEndpoint ?? false, - disableMultiregionAccessPoints: disableMultiregionAccessPoints ?? false, - followRegionRedirects: followRegionRedirects ?? false, - s3ExpressIdentityProvider: s3ExpressIdentityProvider ?? new S3ExpressIdentityProviderImpl(async (key) => s3ClientProvider().send(new CreateSessionCommandCtor({ - Bucket: key - }))), - bucketEndpoint: bucketEndpoint ?? false, - expectContinueHeader: expectContinueHeader ?? 2097152 - }); - }; - var THROW_IF_EMPTY_BODY = { - CopyObjectCommand: true, - UploadPartCopyCommand: true, - CompleteMultipartUploadCommand: true - }; - var MAX_BYTES_TO_INSPECT = 3e3; - var throw200ExceptionsMiddleware = (config3) => (next, context) => async (args) => { - const result = await next(args); - const { response } = result; - if (!protocolHttp.HttpResponse.isInstance(response)) { - return result; - } - const { statusCode, body: sourceBody } = response; - if (statusCode < 200 || statusCode >= 300) { - return result; - } - const isSplittableStream = typeof sourceBody?.stream === "function" || typeof sourceBody?.pipe === "function" || typeof sourceBody?.tee === "function"; - if (!isSplittableStream) { - return result; - } - let bodyCopy = sourceBody; - let body = sourceBody; - if (sourceBody && typeof sourceBody === "object" && !(sourceBody instanceof Uint8Array)) { - [bodyCopy, body] = await utilStream.splitStream(sourceBody); - } - response.body = body; - const bodyBytes = await collectBody3(bodyCopy, { - streamCollector: async (stream) => { - return utilStream.headStream(stream, MAX_BYTES_TO_INSPECT); - } - }); - if (typeof bodyCopy?.destroy === "function") { - bodyCopy.destroy(); - } - const bodyStringTail = config3.utf8Encoder(bodyBytes.subarray(bodyBytes.length - 16)); - if (bodyBytes.length === 0 && THROW_IF_EMPTY_BODY[context.commandName]) { - const err = new Error("S3 aborted request"); - err.name = "InternalError"; - throw err; - } - if (bodyStringTail && bodyStringTail.endsWith("")) { - response.statusCode = 400; - } - return result; - }; - var collectBody3 = (streamBody = new Uint8Array(), context) => { - if (streamBody instanceof Uint8Array) { - return Promise.resolve(streamBody); - } - return context.streamCollector(streamBody) || Promise.resolve(new Uint8Array()); - }; - var throw200ExceptionsMiddlewareOptions = { - relation: "after", - toMiddleware: "deserializerMiddleware", - tags: ["THROW_200_EXCEPTIONS", "S3"], - name: "throw200ExceptionsMiddleware", - override: true - }; - var getThrow200ExceptionsPlugin = (config3) => ({ - applyToStack: (clientStack) => { - clientStack.addRelativeTo(throw200ExceptionsMiddleware(config3), throw200ExceptionsMiddlewareOptions); - } - }); - function bucketEndpointMiddleware(options) { - return (next, context) => async (args) => { - if (options.bucketEndpoint) { - const endpoint = context.endpointV2; - if (endpoint) { - const bucket = args.input.Bucket; - if (typeof bucket === "string") { - try { - const bucketEndpointUrl = new URL(bucket); - context.endpointV2 = { - ...endpoint, - url: bucketEndpointUrl - }; - } catch (e5) { - const warning = `@aws-sdk/middleware-sdk-s3: bucketEndpoint=true was set but Bucket=${bucket} could not be parsed as URL.`; - if (context.logger?.constructor?.name === "NoOpLogger") { - console.warn(warning); - } else { - context.logger?.warn?.(warning); - } - throw e5; - } - } - } - } - return next(args); - }; - } - var bucketEndpointMiddlewareOptions = { - name: "bucketEndpointMiddleware", - override: true, - relation: "after", - toMiddleware: "endpointV2Middleware" - }; - function validateBucketNameMiddleware({ bucketEndpoint }) { - return (next) => async (args) => { - const { input: { Bucket } } = args; - if (!bucketEndpoint && typeof Bucket === "string" && !utilArnParser.validate(Bucket) && Bucket.indexOf("/") >= 0) { - const err = new Error(`Bucket name shouldn't contain '/', received '${Bucket}'`); - err.name = "InvalidBucketName"; - throw err; - } - return next({ ...args }); - }; - } - var validateBucketNameMiddlewareOptions = { - step: "initialize", - tags: ["VALIDATE_BUCKET_NAME"], - name: "validateBucketNameMiddleware", - override: true - }; - var getValidateBucketNamePlugin = (options) => ({ - applyToStack: (clientStack) => { - clientStack.add(validateBucketNameMiddleware(options), validateBucketNameMiddlewareOptions); - clientStack.addRelativeTo(bucketEndpointMiddleware(options), bucketEndpointMiddlewareOptions); - } - }); - var S3RestXmlProtocol = class extends protocols.AwsRestXmlProtocol { - async serializeRequest(operationSchema, input, context) { - const request = await super.serializeRequest(operationSchema, input, context); - const ns = schema2.NormalizedSchema.of(operationSchema.input); - const staticStructureSchema = ns.getSchema(); - let bucketMemberIndex = 0; - const requiredMemberCount = staticStructureSchema[6] ?? 0; - if (input && typeof input === "object") { - for (const [memberName, memberNs] of ns.structIterator()) { - if (++bucketMemberIndex > requiredMemberCount) { - break; - } - if (memberName === "Bucket") { - if (!input.Bucket && memberNs.getMergedTraits().httpLabel) { - throw new Error(`No value provided for input HTTP label: Bucket.`); - } - break; - } - } - } - return request; - } - }; - exports.NODE_DISABLE_S3_EXPRESS_SESSION_AUTH_OPTIONS = NODE_DISABLE_S3_EXPRESS_SESSION_AUTH_OPTIONS; - exports.S3ExpressIdentityCache = S3ExpressIdentityCache; - exports.S3ExpressIdentityCacheEntry = S3ExpressIdentityCacheEntry; - exports.S3ExpressIdentityProviderImpl = S3ExpressIdentityProviderImpl; - exports.S3RestXmlProtocol = S3RestXmlProtocol; - exports.SignatureV4S3Express = SignatureV4S3Express; - exports.checkContentLengthHeader = checkContentLengthHeader; - exports.checkContentLengthHeaderMiddlewareOptions = checkContentLengthHeaderMiddlewareOptions; - exports.getCheckContentLengthHeaderPlugin = getCheckContentLengthHeaderPlugin; - exports.getRegionRedirectMiddlewarePlugin = getRegionRedirectMiddlewarePlugin; - exports.getS3ExpiresMiddlewarePlugin = getS3ExpiresMiddlewarePlugin; - exports.getS3ExpressHttpSigningPlugin = getS3ExpressHttpSigningPlugin; - exports.getS3ExpressPlugin = getS3ExpressPlugin; - exports.getThrow200ExceptionsPlugin = getThrow200ExceptionsPlugin; - exports.getValidateBucketNamePlugin = getValidateBucketNamePlugin; - exports.regionRedirectEndpointMiddleware = regionRedirectEndpointMiddleware; - exports.regionRedirectEndpointMiddlewareOptions = regionRedirectEndpointMiddlewareOptions; - exports.regionRedirectMiddleware = regionRedirectMiddleware; - exports.regionRedirectMiddlewareOptions = regionRedirectMiddlewareOptions; - exports.resolveS3Config = resolveS3Config; - exports.s3ExpiresMiddleware = s3ExpiresMiddleware; - exports.s3ExpiresMiddlewareOptions = s3ExpiresMiddlewareOptions; - exports.s3ExpressHttpSigningMiddleware = s3ExpressHttpSigningMiddleware; - exports.s3ExpressHttpSigningMiddlewareOptions = s3ExpressHttpSigningMiddlewareOptions; - exports.s3ExpressMiddleware = s3ExpressMiddleware; - exports.s3ExpressMiddlewareOptions = s3ExpressMiddlewareOptions; - exports.throw200ExceptionsMiddleware = throw200ExceptionsMiddleware; - exports.throw200ExceptionsMiddlewareOptions = throw200ExceptionsMiddlewareOptions; - exports.validateBucketNameMiddleware = validateBucketNameMiddleware; - exports.validateBucketNameMiddlewareOptions = validateBucketNameMiddlewareOptions; - } -}); - -// node_modules/.pnpm/@smithy+util-endpoints@3.4.0/node_modules/@smithy/util-endpoints/dist-cjs/index.js -var require_dist_cjs33 = __commonJS({ - "node_modules/.pnpm/@smithy+util-endpoints@3.4.0/node_modules/@smithy/util-endpoints/dist-cjs/index.js"(exports) { - "use strict"; - var types2 = require_dist_cjs(); - var BinaryDecisionDiagram = class _BinaryDecisionDiagram { - nodes; - root; - conditions; - results; - constructor(bdd, root, conditions, results) { - this.nodes = bdd; - this.root = root; - this.conditions = conditions; - this.results = results; - } - static from(bdd, root, conditions, results) { - return new _BinaryDecisionDiagram(bdd, root, conditions, results); - } - }; - var EndpointCache5 = class { - capacity; - data = /* @__PURE__ */ new Map(); - parameters = []; - constructor({ size: size2, params }) { - this.capacity = size2 ?? 50; - if (params) { - this.parameters = params; - } - } - get(endpointParams, resolver) { - const key = this.hash(endpointParams); - if (key === false) { - return resolver(); - } - if (!this.data.has(key)) { - if (this.data.size > this.capacity + 10) { - const keys = this.data.keys(); - let i5 = 0; - while (true) { - const { value, done } = keys.next(); - this.data.delete(value); - if (done || ++i5 > 10) { - break; - } - } - } - this.data.set(key, resolver()); - } - return this.data.get(key); - } - size() { - return this.data.size; - } - hash(endpointParams) { - let buffer2 = ""; - const { parameters } = this; - if (parameters.length === 0) { - return false; - } - for (const param of parameters) { - const val = String(endpointParams[param] ?? ""); - if (val.includes("|;")) { - return false; - } - buffer2 += val + "|;"; - } - return buffer2; - } - }; - var EndpointError = class extends Error { - constructor(message2) { - super(message2); - this.name = "EndpointError"; - } - }; - var debugId = "endpoints"; - function toDebugString(input) { - if (typeof input !== "object" || input == null) { - return input; - } - if ("ref" in input) { - return `$${toDebugString(input.ref)}`; - } - if ("fn" in input) { - return `${input.fn}(${(input.argv || []).map(toDebugString).join(", ")})`; - } - return JSON.stringify(input, null, 2); - } - var customEndpointFunctions5 = {}; - var booleanEquals = (value1, value2) => value1 === value2; - function coalesce(...args) { - for (const arg of args) { - if (arg != null) { - return arg; - } - } - return void 0; - } - var getAttrPathList = (path53) => { - const parts = path53.split("."); - const pathList = []; - for (const part of parts) { - const squareBracketIndex = part.indexOf("["); - if (squareBracketIndex !== -1) { - if (part.indexOf("]") !== part.length - 1) { - throw new EndpointError(`Path: '${path53}' does not end with ']'`); - } - const arrayIndex = part.slice(squareBracketIndex + 1, -1); - if (Number.isNaN(parseInt(arrayIndex))) { - throw new EndpointError(`Invalid array index: '${arrayIndex}' in path: '${path53}'`); - } - if (squareBracketIndex !== 0) { - pathList.push(part.slice(0, squareBracketIndex)); - } - pathList.push(arrayIndex); - } else { - pathList.push(part); - } - } - return pathList; - }; - var getAttr = (value, path53) => getAttrPathList(path53).reduce((acc, index2) => { - if (typeof acc !== "object") { - throw new EndpointError(`Index '${index2}' in '${path53}' not found in '${JSON.stringify(value)}'`); - } else if (Array.isArray(acc)) { - return acc[parseInt(index2)]; - } - return acc[index2]; - }, value); - var isSet = (value) => value != null; - var VALID_HOST_LABEL_REGEX = new RegExp(`^(?!.*-$)(?!-)[a-zA-Z0-9-]{1,63}$`); - var isValidHostLabel = (value, allowSubDomains = false) => { - if (!allowSubDomains) { - return VALID_HOST_LABEL_REGEX.test(value); - } - const labels2 = value.split("."); - for (const label of labels2) { - if (!isValidHostLabel(label)) { - return false; - } - } - return true; - }; - function ite(condition, trueValue, falseValue) { - return condition ? trueValue : falseValue; - } - var not2 = (value) => !value; - var IP_V4_REGEX = new RegExp(`^(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}$`); - var isIpAddress = (value) => IP_V4_REGEX.test(value) || value.startsWith("[") && value.endsWith("]"); - var DEFAULT_PORTS = { - [types2.EndpointURLScheme.HTTP]: 80, - [types2.EndpointURLScheme.HTTPS]: 443 - }; - var parseURL = (value) => { - const whatwgURL = (() => { - try { - if (value instanceof URL) { - return value; - } - if (typeof value === "object" && "hostname" in value) { - const { hostname: hostname4, port, protocol: protocol2 = "", path: path53 = "", query = {} } = value; - const url2 = new URL(`${protocol2}//${hostname4}${port ? `:${port}` : ""}${path53}`); - url2.search = Object.entries(query).map(([k5, v5]) => `${k5}=${v5}`).join("&"); - return url2; - } - return new URL(value); - } catch (error50) { - return null; - } - })(); - if (!whatwgURL) { - console.error(`Unable to parse ${JSON.stringify(value)} as a whatwg URL.`); - return null; - } - const urlString = whatwgURL.href; - const { host, hostname: hostname3, pathname, protocol, search } = whatwgURL; - if (search) { - return null; - } - const scheme = protocol.slice(0, -1); - if (!Object.values(types2.EndpointURLScheme).includes(scheme)) { - return null; - } - const isIp = isIpAddress(hostname3); - const inputContainsDefaultPort = urlString.includes(`${host}:${DEFAULT_PORTS[scheme]}`) || typeof value === "string" && value.includes(`${host}:${DEFAULT_PORTS[scheme]}`); - const authority = `${host}${inputContainsDefaultPort ? `:${DEFAULT_PORTS[scheme]}` : ``}`; - return { - scheme, - authority, - path: pathname, - normalizedPath: pathname.endsWith("/") ? pathname : `${pathname}/`, - isIp - }; - }; - function split(value, delimiter, limit) { - if (limit === 1) { - return [value]; - } - if (value === "") { - return [""]; - } - const parts = value.split(delimiter); - if (limit === 0) { - return parts; - } - return parts.slice(0, limit - 1).concat(parts.slice(1).join(delimiter)); - } - var stringEquals = (value1, value2) => value1 === value2; - var substring = (input, start, stop, reverse) => { - if (input == null || start >= stop || input.length < stop || /[^\u0000-\u007f]/.test(input)) { - return null; - } - if (!reverse) { - return input.substring(start, stop); - } - return input.substring(input.length - stop, input.length - start); - }; - var uriEncode = (value) => encodeURIComponent(value).replace(/[!*'()]/g, (c5) => `%${c5.charCodeAt(0).toString(16).toUpperCase()}`); - var endpointFunctions = { - booleanEquals, - coalesce, - getAttr, - isSet, - isValidHostLabel, - ite, - not: not2, - parseURL, - split, - stringEquals, - substring, - uriEncode - }; - var evaluateTemplate = (template, options) => { - const evaluatedTemplateArr = []; - const { referenceRecord, endpointParams } = options; - let currentIndex = 0; - while (currentIndex < template.length) { - const openingBraceIndex = template.indexOf("{", currentIndex); - if (openingBraceIndex === -1) { - evaluatedTemplateArr.push(template.slice(currentIndex)); - break; - } - evaluatedTemplateArr.push(template.slice(currentIndex, openingBraceIndex)); - const closingBraceIndex = template.indexOf("}", openingBraceIndex); - if (closingBraceIndex === -1) { - evaluatedTemplateArr.push(template.slice(openingBraceIndex)); - break; - } - if (template[openingBraceIndex + 1] === "{" && template[closingBraceIndex + 1] === "}") { - evaluatedTemplateArr.push(template.slice(openingBraceIndex + 1, closingBraceIndex)); - currentIndex = closingBraceIndex + 2; - } - const parameterName = template.substring(openingBraceIndex + 1, closingBraceIndex); - if (parameterName.includes("#")) { - const [refName, attrName] = parameterName.split("#"); - evaluatedTemplateArr.push(getAttr(referenceRecord[refName] ?? endpointParams[refName], attrName)); - } else { - evaluatedTemplateArr.push(referenceRecord[parameterName] ?? endpointParams[parameterName]); - } - currentIndex = closingBraceIndex + 1; - } - return evaluatedTemplateArr.join(""); - }; - var getReferenceValue = ({ ref }, options) => { - return options.referenceRecord[ref] ?? options.endpointParams[ref]; - }; - var evaluateExpression = (obj, keyName, options) => { - if (typeof obj === "string") { - return evaluateTemplate(obj, options); - } else if (obj["fn"]) { - return group$2.callFunction(obj, options); - } else if (obj["ref"]) { - return getReferenceValue(obj, options); - } - throw new EndpointError(`'${keyName}': ${String(obj)} is not a string, function or reference.`); - }; - var callFunction = ({ fn, argv }, options) => { - const evaluatedArgs = Array(argv.length); - for (let i5 = 0; i5 < evaluatedArgs.length; ++i5) { - const arg = argv[i5]; - if (typeof arg === "boolean" || typeof arg === "number") { - evaluatedArgs[i5] = arg; - } else { - evaluatedArgs[i5] = group$2.evaluateExpression(arg, "arg", options); - } - } - if (fn.includes(".")) { - const fnSegments = fn.split("."); - if (fnSegments[0] in customEndpointFunctions5 && fnSegments[1] != null) { - return customEndpointFunctions5[fnSegments[0]][fnSegments[1]](...evaluatedArgs); - } - } - if (typeof endpointFunctions[fn] !== "function") { - throw new Error(`function ${fn} not loaded in endpointFunctions.`); - } - const callable = endpointFunctions[fn]; - return callable(...evaluatedArgs); - }; - var group$2 = { - evaluateExpression, - callFunction - }; - var evaluateCondition = ({ assign, ...fnArgs }, options) => { - if (assign && assign in options.referenceRecord) { - throw new EndpointError(`'${assign}' is already defined in Reference Record.`); - } - const value = callFunction(fnArgs, options); - options.logger?.debug?.(`${debugId} evaluateCondition: ${toDebugString(fnArgs)} = ${toDebugString(value)}`); - return { - result: value === "" ? true : !!value, - ...assign != null && { toAssign: { name: assign, value } } - }; - }; - var getEndpointHeaders = (headers, options) => Object.entries(headers).reduce((acc, [headerKey, headerVal]) => ({ - ...acc, - [headerKey]: headerVal.map((headerValEntry) => { - const processedExpr = evaluateExpression(headerValEntry, "Header value entry", options); - if (typeof processedExpr !== "string") { - throw new EndpointError(`Header '${headerKey}' value '${processedExpr}' is not a string`); - } - return processedExpr; - }) - }), {}); - var getEndpointProperties = (properties, options) => Object.entries(properties).reduce((acc, [propertyKey, propertyVal]) => ({ - ...acc, - [propertyKey]: group$1.getEndpointProperty(propertyVal, options) - }), {}); - var getEndpointProperty = (property, options) => { - if (Array.isArray(property)) { - return property.map((propertyEntry) => getEndpointProperty(propertyEntry, options)); - } - switch (typeof property) { - case "string": - return evaluateTemplate(property, options); - case "object": - if (property === null) { - throw new EndpointError(`Unexpected endpoint property: ${property}`); - } - return group$1.getEndpointProperties(property, options); - case "boolean": - return property; - default: - throw new EndpointError(`Unexpected endpoint property type: ${typeof property}`); - } - }; - var group$1 = { - getEndpointProperty, - getEndpointProperties - }; - var getEndpointUrl = (endpointUrl, options) => { - const expression = evaluateExpression(endpointUrl, "Endpoint URL", options); - if (typeof expression === "string") { - try { - return new URL(expression); - } catch (error50) { - console.error(`Failed to construct URL with ${expression}`, error50); - throw error50; - } - } - throw new EndpointError(`Endpoint URL must be a string, got ${typeof expression}`); - }; - var RESULT = 1e8; - var decideEndpoint = (bdd, options) => { - const { nodes, root, results, conditions } = bdd; - let ref = root; - const referenceRecord = {}; - const closure = { - referenceRecord, - endpointParams: options.endpointParams, - logger: options.logger - }; - while (ref !== 1 && ref !== -1 && ref < RESULT) { - const node_i = 3 * (Math.abs(ref) - 1); - const [condition_i, highRef, lowRef] = [nodes[node_i], nodes[node_i + 1], nodes[node_i + 2]]; - const [fn, argv, assign] = conditions[condition_i]; - const evaluation = evaluateCondition({ fn, assign, argv }, closure); - if (evaluation.toAssign) { - const { name, value } = evaluation.toAssign; - referenceRecord[name] = value; - } - ref = ref >= 0 === evaluation.result ? highRef : lowRef; - } - if (ref >= RESULT) { - const result = results[ref - RESULT]; - if (result[0] === -1) { - const [, errorMessage] = result; - throw new EndpointError(errorMessage); - } - const [url2, properties, headers] = result; - return { - url: getEndpointUrl(url2, closure), - properties: getEndpointProperties(properties, closure), - headers: getEndpointHeaders(headers, closure) - }; - } - throw new EndpointError(`No matching endpoint.`); - }; - var evaluateConditions = (conditions = [], options) => { - const conditionsReferenceRecord = {}; - for (const condition of conditions) { - const { result, toAssign } = evaluateCondition(condition, { - ...options, - referenceRecord: { - ...options.referenceRecord, - ...conditionsReferenceRecord - } - }); - if (!result) { - return { result }; - } - if (toAssign) { - conditionsReferenceRecord[toAssign.name] = toAssign.value; - options.logger?.debug?.(`${debugId} assign: ${toAssign.name} := ${toDebugString(toAssign.value)}`); - } - } - return { result: true, referenceRecord: conditionsReferenceRecord }; - }; - var evaluateEndpointRule = (endpointRule, options) => { - const { conditions, endpoint } = endpointRule; - const { result, referenceRecord } = evaluateConditions(conditions, options); - if (!result) { - return; - } - const endpointRuleOptions = { - ...options, - referenceRecord: { ...options.referenceRecord, ...referenceRecord } - }; - const { url: url2, properties, headers } = endpoint; - options.logger?.debug?.(`${debugId} Resolving endpoint from template: ${toDebugString(endpoint)}`); - return { - ...headers != void 0 && { - headers: getEndpointHeaders(headers, endpointRuleOptions) - }, - ...properties != void 0 && { - properties: getEndpointProperties(properties, endpointRuleOptions) - }, - url: getEndpointUrl(url2, endpointRuleOptions) - }; - }; - var evaluateErrorRule = (errorRule, options) => { - const { conditions, error: error50 } = errorRule; - const { result, referenceRecord } = evaluateConditions(conditions, options); - if (!result) { - return; - } - throw new EndpointError(evaluateExpression(error50, "Error", { - ...options, - referenceRecord: { ...options.referenceRecord, ...referenceRecord } - })); - }; - var evaluateRules = (rules, options) => { - for (const rule of rules) { - if (rule.type === "endpoint") { - const endpointOrUndefined = evaluateEndpointRule(rule, options); - if (endpointOrUndefined) { - return endpointOrUndefined; - } - } else if (rule.type === "error") { - evaluateErrorRule(rule, options); - } else if (rule.type === "tree") { - const endpointOrUndefined = group.evaluateTreeRule(rule, options); - if (endpointOrUndefined) { - return endpointOrUndefined; - } - } else { - throw new EndpointError(`Unknown endpoint rule: ${rule}`); - } - } - throw new EndpointError(`Rules evaluation failed`); - }; - var evaluateTreeRule = (treeRule, options) => { - const { conditions, rules } = treeRule; - const { result, referenceRecord } = evaluateConditions(conditions, options); - if (!result) { - return; - } - return group.evaluateRules(rules, { - ...options, - referenceRecord: { ...options.referenceRecord, ...referenceRecord } - }); - }; - var group = { - evaluateRules, - evaluateTreeRule - }; - var resolveEndpoint5 = (ruleSetObject, options) => { - const { endpointParams, logger: logger4 } = options; - const { parameters, rules } = ruleSetObject; - options.logger?.debug?.(`${debugId} Initial EndpointParams: ${toDebugString(endpointParams)}`); - const paramsWithDefault = Object.entries(parameters).filter(([, v5]) => v5.default != null).map(([k5, v5]) => [k5, v5.default]); - if (paramsWithDefault.length > 0) { - for (const [paramKey, paramDefaultValue] of paramsWithDefault) { - endpointParams[paramKey] = endpointParams[paramKey] ?? paramDefaultValue; - } - } - const requiredParams = Object.entries(parameters).filter(([, v5]) => v5.required).map(([k5]) => k5); - for (const requiredParam of requiredParams) { - if (endpointParams[requiredParam] == null) { - throw new EndpointError(`Missing required parameter: '${requiredParam}'`); - } - } - const endpoint = evaluateRules(rules, { endpointParams, logger: logger4, referenceRecord: {} }); - options.logger?.debug?.(`${debugId} Resolved endpoint: ${toDebugString(endpoint)}`); - return endpoint; - }; - exports.BinaryDecisionDiagram = BinaryDecisionDiagram; - exports.EndpointCache = EndpointCache5; - exports.EndpointError = EndpointError; - exports.customEndpointFunctions = customEndpointFunctions5; - exports.decideEndpoint = decideEndpoint; - exports.isIpAddress = isIpAddress; - exports.isValidHostLabel = isValidHostLabel; - exports.resolveEndpoint = resolveEndpoint5; - } -}); - -// node_modules/.pnpm/@aws-sdk+util-endpoints@3.996.6/node_modules/@aws-sdk/util-endpoints/dist-cjs/index.js -var require_dist_cjs34 = __commonJS({ - "node_modules/.pnpm/@aws-sdk+util-endpoints@3.996.6/node_modules/@aws-sdk/util-endpoints/dist-cjs/index.js"(exports) { - "use strict"; - var utilEndpoints = require_dist_cjs33(); - var urlParser = require_dist_cjs25(); - var isVirtualHostableS3Bucket = (value, allowSubDomains = false) => { - if (allowSubDomains) { - for (const label of value.split(".")) { - if (!isVirtualHostableS3Bucket(label)) { - return false; - } - } - return true; - } - if (!utilEndpoints.isValidHostLabel(value)) { - return false; - } - if (value.length < 3 || value.length > 63) { - return false; - } - if (value !== value.toLowerCase()) { - return false; - } - if (utilEndpoints.isIpAddress(value)) { - return false; - } - return true; - }; - var ARN_DELIMITER = ":"; - var RESOURCE_DELIMITER = "/"; - var parseArn = (value) => { - const segments = value.split(ARN_DELIMITER); - if (segments.length < 6) - return null; - const [arn, partition2, service, region, accountId, ...resourcePath] = segments; - if (arn !== "arn" || partition2 === "" || service === "" || resourcePath.join(ARN_DELIMITER) === "") - return null; - const resourceId = resourcePath.map((resource) => resource.split(RESOURCE_DELIMITER)).flat(); - return { - partition: partition2, - service, - region, - accountId, - resourceId - }; - }; - var partitions = [ - { - id: "aws", - outputs: { - dnsSuffix: "amazonaws.com", - dualStackDnsSuffix: "api.aws", - implicitGlobalRegion: "us-east-1", - name: "aws", - supportsDualStack: true, - supportsFIPS: true - }, - regionRegex: "^(us|eu|ap|sa|ca|me|af|il|mx)\\-\\w+\\-\\d+$", - regions: { - "af-south-1": { - description: "Africa (Cape Town)" - }, - "ap-east-1": { - description: "Asia Pacific (Hong Kong)" - }, - "ap-east-2": { - description: "Asia Pacific (Taipei)" - }, - "ap-northeast-1": { - description: "Asia Pacific (Tokyo)" - }, - "ap-northeast-2": { - description: "Asia Pacific (Seoul)" - }, - "ap-northeast-3": { - description: "Asia Pacific (Osaka)" - }, - "ap-south-1": { - description: "Asia Pacific (Mumbai)" - }, - "ap-south-2": { - description: "Asia Pacific (Hyderabad)" - }, - "ap-southeast-1": { - description: "Asia Pacific (Singapore)" - }, - "ap-southeast-2": { - description: "Asia Pacific (Sydney)" - }, - "ap-southeast-3": { - description: "Asia Pacific (Jakarta)" - }, - "ap-southeast-4": { - description: "Asia Pacific (Melbourne)" - }, - "ap-southeast-5": { - description: "Asia Pacific (Malaysia)" - }, - "ap-southeast-6": { - description: "Asia Pacific (New Zealand)" - }, - "ap-southeast-7": { - description: "Asia Pacific (Thailand)" - }, - "aws-global": { - description: "aws global region" - }, - "ca-central-1": { - description: "Canada (Central)" - }, - "ca-west-1": { - description: "Canada West (Calgary)" - }, - "eu-central-1": { - description: "Europe (Frankfurt)" - }, - "eu-central-2": { - description: "Europe (Zurich)" - }, - "eu-north-1": { - description: "Europe (Stockholm)" - }, - "eu-south-1": { - description: "Europe (Milan)" - }, - "eu-south-2": { - description: "Europe (Spain)" - }, - "eu-west-1": { - description: "Europe (Ireland)" - }, - "eu-west-2": { - description: "Europe (London)" - }, - "eu-west-3": { - description: "Europe (Paris)" - }, - "il-central-1": { - description: "Israel (Tel Aviv)" - }, - "me-central-1": { - description: "Middle East (UAE)" - }, - "me-south-1": { - description: "Middle East (Bahrain)" - }, - "mx-central-1": { - description: "Mexico (Central)" - }, - "sa-east-1": { - description: "South America (Sao Paulo)" - }, - "us-east-1": { - description: "US East (N. Virginia)" - }, - "us-east-2": { - description: "US East (Ohio)" - }, - "us-west-1": { - description: "US West (N. California)" - }, - "us-west-2": { - description: "US West (Oregon)" - } - } - }, - { - id: "aws-cn", - outputs: { - dnsSuffix: "amazonaws.com.cn", - dualStackDnsSuffix: "api.amazonwebservices.com.cn", - implicitGlobalRegion: "cn-northwest-1", - name: "aws-cn", - supportsDualStack: true, - supportsFIPS: true - }, - regionRegex: "^cn\\-\\w+\\-\\d+$", - regions: { - "aws-cn-global": { - description: "aws-cn global region" - }, - "cn-north-1": { - description: "China (Beijing)" - }, - "cn-northwest-1": { - description: "China (Ningxia)" - } - } - }, - { - id: "aws-eusc", - outputs: { - dnsSuffix: "amazonaws.eu", - dualStackDnsSuffix: "api.amazonwebservices.eu", - implicitGlobalRegion: "eusc-de-east-1", - name: "aws-eusc", - supportsDualStack: true, - supportsFIPS: true - }, - regionRegex: "^eusc\\-(de)\\-\\w+\\-\\d+$", - regions: { - "eusc-de-east-1": { - description: "AWS European Sovereign Cloud (Germany)" - } - } - }, - { - id: "aws-iso", - outputs: { - dnsSuffix: "c2s.ic.gov", - dualStackDnsSuffix: "api.aws.ic.gov", - implicitGlobalRegion: "us-iso-east-1", - name: "aws-iso", - supportsDualStack: true, - supportsFIPS: true - }, - regionRegex: "^us\\-iso\\-\\w+\\-\\d+$", - regions: { - "aws-iso-global": { - description: "aws-iso global region" - }, - "us-iso-east-1": { - description: "US ISO East" - }, - "us-iso-west-1": { - description: "US ISO WEST" - } - } - }, - { - id: "aws-iso-b", - outputs: { - dnsSuffix: "sc2s.sgov.gov", - dualStackDnsSuffix: "api.aws.scloud", - implicitGlobalRegion: "us-isob-east-1", - name: "aws-iso-b", - supportsDualStack: true, - supportsFIPS: true - }, - regionRegex: "^us\\-isob\\-\\w+\\-\\d+$", - regions: { - "aws-iso-b-global": { - description: "aws-iso-b global region" - }, - "us-isob-east-1": { - description: "US ISOB East (Ohio)" - }, - "us-isob-west-1": { - description: "US ISOB West" - } - } - }, - { - id: "aws-iso-e", - outputs: { - dnsSuffix: "cloud.adc-e.uk", - dualStackDnsSuffix: "api.cloud-aws.adc-e.uk", - implicitGlobalRegion: "eu-isoe-west-1", - name: "aws-iso-e", - supportsDualStack: true, - supportsFIPS: true - }, - regionRegex: "^eu\\-isoe\\-\\w+\\-\\d+$", - regions: { - "aws-iso-e-global": { - description: "aws-iso-e global region" - }, - "eu-isoe-west-1": { - description: "EU ISOE West" - } - } - }, - { - id: "aws-iso-f", - outputs: { - dnsSuffix: "csp.hci.ic.gov", - dualStackDnsSuffix: "api.aws.hci.ic.gov", - implicitGlobalRegion: "us-isof-south-1", - name: "aws-iso-f", - supportsDualStack: true, - supportsFIPS: true - }, - regionRegex: "^us\\-isof\\-\\w+\\-\\d+$", - regions: { - "aws-iso-f-global": { - description: "aws-iso-f global region" - }, - "us-isof-east-1": { - description: "US ISOF EAST" - }, - "us-isof-south-1": { - description: "US ISOF SOUTH" - } - } - }, - { - id: "aws-us-gov", - outputs: { - dnsSuffix: "amazonaws.com", - dualStackDnsSuffix: "api.aws", - implicitGlobalRegion: "us-gov-west-1", - name: "aws-us-gov", - supportsDualStack: true, - supportsFIPS: true - }, - regionRegex: "^us\\-gov\\-\\w+\\-\\d+$", - regions: { - "aws-us-gov-global": { - description: "aws-us-gov global region" - }, - "us-gov-east-1": { - description: "AWS GovCloud (US-East)" - }, - "us-gov-west-1": { - description: "AWS GovCloud (US-West)" - } - } - } - ]; - var version3 = "1.1"; - var partitionsInfo = { - partitions, - version: version3 - }; - var selectedPartitionsInfo = partitionsInfo; - var selectedUserAgentPrefix = ""; - var partition = (value) => { - const { partitions: partitions2 } = selectedPartitionsInfo; - for (const partition2 of partitions2) { - const { regions, outputs } = partition2; - for (const [region, regionData] of Object.entries(regions)) { - if (region === value) { - return { - ...outputs, - ...regionData - }; - } - } - } - for (const partition2 of partitions2) { - const { regionRegex, outputs } = partition2; - if (new RegExp(regionRegex).test(value)) { - return { - ...outputs - }; - } - } - const DEFAULT_PARTITION = partitions2.find((partition2) => partition2.id === "aws"); - if (!DEFAULT_PARTITION) { - throw new Error("Provided region was not found in the partition array or regex, and default partition with id 'aws' doesn't exist."); - } - return { - ...DEFAULT_PARTITION.outputs - }; - }; - var setPartitionInfo = (partitionsInfo2, userAgentPrefix = "") => { - selectedPartitionsInfo = partitionsInfo2; - selectedUserAgentPrefix = userAgentPrefix; - }; - var useDefaultPartitionInfo = () => { - setPartitionInfo(partitionsInfo, ""); - }; - var getUserAgentPrefix = () => selectedUserAgentPrefix; - var awsEndpointFunctions5 = { - isVirtualHostableS3Bucket, - parseArn, - partition - }; - utilEndpoints.customEndpointFunctions.aws = awsEndpointFunctions5; - var resolveDefaultAwsRegionalEndpointsConfig = (input) => { - if (typeof input.endpointProvider !== "function") { - throw new Error("@aws-sdk/util-endpoint - endpointProvider and endpoint missing in config for this client."); - } - const { endpoint } = input; - if (endpoint === void 0) { - input.endpoint = async () => { - return toEndpointV12(input.endpointProvider({ - Region: typeof input.region === "function" ? await input.region() : input.region, - UseDualStack: typeof input.useDualstackEndpoint === "function" ? await input.useDualstackEndpoint() : input.useDualstackEndpoint, - UseFIPS: typeof input.useFipsEndpoint === "function" ? await input.useFipsEndpoint() : input.useFipsEndpoint, - Endpoint: void 0 - }, { logger: input.logger })); - }; - } - return input; - }; - var toEndpointV12 = (endpoint) => urlParser.parseUrl(endpoint.url); - exports.EndpointError = utilEndpoints.EndpointError; - exports.isIpAddress = utilEndpoints.isIpAddress; - exports.resolveEndpoint = utilEndpoints.resolveEndpoint; - exports.awsEndpointFunctions = awsEndpointFunctions5; - exports.getUserAgentPrefix = getUserAgentPrefix; - exports.partition = partition; - exports.resolveDefaultAwsRegionalEndpointsConfig = resolveDefaultAwsRegionalEndpointsConfig; - exports.setPartitionInfo = setPartitionInfo; - exports.toEndpointV1 = toEndpointV12; - exports.useDefaultPartitionInfo = useDefaultPartitionInfo; - } -}); - -// node_modules/.pnpm/@smithy+service-error-classification@4.2.13/node_modules/@smithy/service-error-classification/dist-cjs/index.js -var require_dist_cjs35 = __commonJS({ - "node_modules/.pnpm/@smithy+service-error-classification@4.2.13/node_modules/@smithy/service-error-classification/dist-cjs/index.js"(exports) { - "use strict"; - var CLOCK_SKEW_ERROR_CODES = [ - "AuthFailure", - "InvalidSignatureException", - "RequestExpired", - "RequestInTheFuture", - "RequestTimeTooSkewed", - "SignatureDoesNotMatch" - ]; - var THROTTLING_ERROR_CODES = [ - "BandwidthLimitExceeded", - "EC2ThrottledException", - "LimitExceededException", - "PriorRequestNotComplete", - "ProvisionedThroughputExceededException", - "RequestLimitExceeded", - "RequestThrottled", - "RequestThrottledException", - "SlowDown", - "ThrottledException", - "Throttling", - "ThrottlingException", - "TooManyRequestsException", - "TransactionInProgressException" - ]; - var TRANSIENT_ERROR_CODES = ["TimeoutError", "RequestTimeout", "RequestTimeoutException"]; - var TRANSIENT_ERROR_STATUS_CODES = [500, 502, 503, 504]; - var NODEJS_TIMEOUT_ERROR_CODES = ["ECONNRESET", "ECONNREFUSED", "EPIPE", "ETIMEDOUT"]; - var NODEJS_NETWORK_ERROR_CODES = ["EHOSTUNREACH", "ENETUNREACH", "ENOTFOUND"]; - var isRetryableByTrait = (error50) => error50?.$retryable !== void 0; - var isClockSkewError = (error50) => CLOCK_SKEW_ERROR_CODES.includes(error50.name); - var isClockSkewCorrectedError = (error50) => error50.$metadata?.clockSkewCorrected; - var isBrowserNetworkError = (error50) => { - const errorMessages = /* @__PURE__ */ new Set([ - "Failed to fetch", - "NetworkError when attempting to fetch resource", - "The Internet connection appears to be offline", - "Load failed", - "Network request failed" - ]); - const isValid2 = error50 && error50 instanceof TypeError; - if (!isValid2) { - return false; - } - return errorMessages.has(error50.message); - }; - var isThrottlingError = (error50) => error50.$metadata?.httpStatusCode === 429 || THROTTLING_ERROR_CODES.includes(error50.name) || error50.$retryable?.throttling == true; - var isTransientError = (error50, depth = 0) => isRetryableByTrait(error50) || isClockSkewCorrectedError(error50) || TRANSIENT_ERROR_CODES.includes(error50.name) || NODEJS_TIMEOUT_ERROR_CODES.includes(error50?.code || "") || NODEJS_NETWORK_ERROR_CODES.includes(error50?.code || "") || TRANSIENT_ERROR_STATUS_CODES.includes(error50.$metadata?.httpStatusCode || 0) || isBrowserNetworkError(error50) || error50.cause !== void 0 && depth <= 10 && isTransientError(error50.cause, depth + 1); - var isServerError = (error50) => { - if (error50.$metadata?.httpStatusCode !== void 0) { - const statusCode = error50.$metadata.httpStatusCode; - if (500 <= statusCode && statusCode <= 599 && !isTransientError(error50)) { - return true; - } - return false; - } - return false; - }; - exports.isBrowserNetworkError = isBrowserNetworkError; - exports.isClockSkewCorrectedError = isClockSkewCorrectedError; - exports.isClockSkewError = isClockSkewError; - exports.isRetryableByTrait = isRetryableByTrait; - exports.isServerError = isServerError; - exports.isThrottlingError = isThrottlingError; - exports.isTransientError = isTransientError; - } -}); - -// node_modules/.pnpm/@smithy+util-retry@4.3.1/node_modules/@smithy/util-retry/dist-cjs/index.js -var require_dist_cjs36 = __commonJS({ - "node_modules/.pnpm/@smithy+util-retry@4.3.1/node_modules/@smithy/util-retry/dist-cjs/index.js"(exports) { - "use strict"; - var serviceErrorClassification = require_dist_cjs35(); - exports.RETRY_MODES = void 0; - (function(RETRY_MODES) { - RETRY_MODES["STANDARD"] = "standard"; - RETRY_MODES["ADAPTIVE"] = "adaptive"; - })(exports.RETRY_MODES || (exports.RETRY_MODES = {})); - var DEFAULT_MAX_ATTEMPTS = 3; - var DEFAULT_RETRY_MODE5 = exports.RETRY_MODES.STANDARD; - var DefaultRateLimiter = class _DefaultRateLimiter { - static setTimeoutFn = setTimeout; - beta; - minCapacity; - minFillRate; - scaleConstant; - smooth; - enabled = false; - availableTokens = 0; - lastMaxRate = 0; - measuredTxRate = 0; - requestCount = 0; - fillRate; - lastThrottleTime; - lastTimestamp = 0; - lastTxRateBucket; - maxCapacity; - timeWindow = 0; - constructor(options) { - this.beta = options?.beta ?? 0.7; - this.minCapacity = options?.minCapacity ?? 1; - this.minFillRate = options?.minFillRate ?? 0.5; - this.scaleConstant = options?.scaleConstant ?? 0.4; - this.smooth = options?.smooth ?? 0.8; - this.lastThrottleTime = this.getCurrentTimeInSeconds(); - this.lastTxRateBucket = Math.floor(this.getCurrentTimeInSeconds()); - this.fillRate = this.minFillRate; - this.maxCapacity = this.minCapacity; - } - async getSendToken() { - return this.acquireTokenBucket(1); - } - updateClientSendingRate(response) { - let calculatedRate; - this.updateMeasuredRate(); - const retryErrorInfo = response; - const isThrottling = retryErrorInfo?.errorType === "THROTTLING" || serviceErrorClassification.isThrottlingError(retryErrorInfo?.error ?? response); - if (isThrottling) { - const rateToUse = !this.enabled ? this.measuredTxRate : Math.min(this.measuredTxRate, this.fillRate); - this.lastMaxRate = rateToUse; - this.calculateTimeWindow(); - this.lastThrottleTime = this.getCurrentTimeInSeconds(); - calculatedRate = this.cubicThrottle(rateToUse); - this.enableTokenBucket(); - } else { - this.calculateTimeWindow(); - calculatedRate = this.cubicSuccess(this.getCurrentTimeInSeconds()); - } - const newRate = Math.min(calculatedRate, 2 * this.measuredTxRate); - this.updateTokenBucketRate(newRate); - } - getCurrentTimeInSeconds() { - return Date.now() / 1e3; - } - async acquireTokenBucket(amount) { - if (!this.enabled) { - return; - } - this.refillTokenBucket(); - if (amount > this.availableTokens) { - const delay3 = (amount - this.availableTokens) / this.fillRate * 1e3; - await new Promise((resolve4) => _DefaultRateLimiter.setTimeoutFn(resolve4, delay3)); - } - this.availableTokens = this.availableTokens - amount; - } - refillTokenBucket() { - const timestamp2 = this.getCurrentTimeInSeconds(); - if (!this.lastTimestamp) { - this.lastTimestamp = timestamp2; - return; - } - const fillAmount = (timestamp2 - this.lastTimestamp) * this.fillRate; - this.availableTokens = Math.min(this.maxCapacity, this.availableTokens + fillAmount); - this.lastTimestamp = timestamp2; - } - calculateTimeWindow() { - this.timeWindow = this.getPrecise(Math.pow(this.lastMaxRate * (1 - this.beta) / this.scaleConstant, 1 / 3)); - } - cubicThrottle(rateToUse) { - return this.getPrecise(rateToUse * this.beta); - } - cubicSuccess(timestamp2) { - return this.getPrecise(this.scaleConstant * Math.pow(timestamp2 - this.lastThrottleTime - this.timeWindow, 3) + this.lastMaxRate); - } - enableTokenBucket() { - this.enabled = true; - } - updateTokenBucketRate(newRate) { - this.refillTokenBucket(); - this.fillRate = Math.max(newRate, this.minFillRate); - this.maxCapacity = Math.max(newRate, this.minCapacity); - this.availableTokens = Math.min(this.availableTokens, this.maxCapacity); - } - updateMeasuredRate() { - const t5 = this.getCurrentTimeInSeconds(); - const timeBucket = Math.floor(t5 * 2) / 2; - this.requestCount++; - if (timeBucket > this.lastTxRateBucket) { - const currentRate = this.requestCount / (timeBucket - this.lastTxRateBucket); - this.measuredTxRate = this.getPrecise(currentRate * this.smooth + this.measuredTxRate * (1 - this.smooth)); - this.requestCount = 0; - this.lastTxRateBucket = timeBucket; - } - } - getPrecise(num) { - return parseFloat(num.toFixed(8)); - } - }; - var DEFAULT_RETRY_DELAY_BASE = 100; - var MAXIMUM_RETRY_DELAY = 20 * 1e3; - var THROTTLING_RETRY_DELAY_BASE = 500; - var INITIAL_RETRY_TOKENS = 500; - var RETRY_COST = 5; - var TIMEOUT_RETRY_COST = 10; - var NO_RETRY_INCREMENT = 1; - var INVOCATION_ID_HEADER = "amz-sdk-invocation-id"; - var REQUEST_HEADER = "amz-sdk-request"; - var Retry = class _Retry { - static v2026 = typeof process !== "undefined" && process.env?.SMITHY_NEW_RETRIES_2026 === "true"; - static delay() { - return _Retry.v2026 ? 50 : 100; - } - static throttlingDelay() { - return _Retry.v2026 ? 1e3 : 500; - } - static cost() { - return _Retry.v2026 ? 14 : 5; - } - static throttlingCost() { - return _Retry.v2026 ? 5 : 10; - } - static modifiedCostType() { - return _Retry.v2026 ? "THROTTLING" : "TRANSIENT"; - } - }; - var DefaultRetryBackoffStrategy = class { - x = Retry.delay(); - computeNextBackoffDelay(i5) { - const b6 = Math.random(); - const r5 = 2; - const t_i = b6 * Math.min(this.x * r5 ** i5, MAXIMUM_RETRY_DELAY); - return Math.floor(t_i); - } - setDelayBase(delay3) { - this.x = delay3; - } - }; - var DefaultRetryToken = class { - delay; - count; - cost; - longPoll; - constructor(delay3, count2, cost, longPoll) { - this.delay = delay3; - this.count = count2; - this.cost = cost; - this.longPoll = longPoll; - } - getRetryCount() { - return this.count; - } - getRetryDelay() { - return Math.min(MAXIMUM_RETRY_DELAY, this.delay); - } - getRetryCost() { - return this.cost; - } - isLongPoll() { - return this.longPoll; - } - }; - var StandardRetryStrategy = class { - mode = exports.RETRY_MODES.STANDARD; - capacity = INITIAL_RETRY_TOKENS; - retryBackoffStrategy; - maxAttemptsProvider; - baseDelay; - constructor(arg1) { - if (typeof arg1 === "number") { - this.maxAttemptsProvider = async () => arg1; - } else if (typeof arg1 === "function") { - this.maxAttemptsProvider = arg1; - } else if (arg1 && typeof arg1 === "object") { - this.maxAttemptsProvider = async () => arg1.maxAttempts; - this.baseDelay = arg1.baseDelay; - this.retryBackoffStrategy = arg1.backoff; - } - this.maxAttemptsProvider ??= async () => DEFAULT_MAX_ATTEMPTS; - this.baseDelay ??= Retry.delay(); - this.retryBackoffStrategy ??= new DefaultRetryBackoffStrategy(); - } - async acquireInitialRetryToken(retryTokenScope) { - return new DefaultRetryToken(Retry.delay(), 0, void 0, Retry.v2026 && retryTokenScope.includes(":longpoll")); - } - async refreshRetryTokenForRetry(token, errorInfo) { - const maxAttempts = await this.getMaxAttempts(); - const shouldRetry = this.shouldRetry(token, errorInfo, maxAttempts); - if (shouldRetry || token.isLongPoll?.()) { - const errorType = errorInfo.errorType; - this.retryBackoffStrategy.setDelayBase(errorType === "THROTTLING" ? Retry.throttlingDelay() : this.baseDelay); - const delayFromErrorType = this.retryBackoffStrategy.computeNextBackoffDelay(token.getRetryCount()); - let retryDelay = delayFromErrorType; - if (errorInfo.retryAfterHint instanceof Date) { - retryDelay = Math.max(delayFromErrorType, Math.min(errorInfo.retryAfterHint.getTime() - Date.now(), delayFromErrorType + 5e3)); - } - if (!shouldRetry) { - throw Object.assign(new Error("No retry token available"), { $backoff: Retry.v2026 ? retryDelay : 0 }); - } else { - const capacityCost = this.getCapacityCost(errorType); - this.capacity -= capacityCost; - return new DefaultRetryToken(retryDelay, token.getRetryCount() + 1, capacityCost, token.isLongPoll?.() ?? false); - } - } - throw new Error("No retry token available"); - } - recordSuccess(token) { - this.capacity = Math.min(INITIAL_RETRY_TOKENS, this.capacity + (token.getRetryCost() ?? NO_RETRY_INCREMENT)); - } - getCapacity() { - return this.capacity; - } - async getMaxAttempts() { - try { - return await this.maxAttemptsProvider(); - } catch (error50) { - console.warn(`Max attempts provider could not resolve. Using default of ${DEFAULT_MAX_ATTEMPTS}`); - return DEFAULT_MAX_ATTEMPTS; - } - } - shouldRetry(tokenToRenew, errorInfo, maxAttempts) { - const attempts = tokenToRenew.getRetryCount() + 1; - return attempts < maxAttempts && this.capacity >= this.getCapacityCost(errorInfo.errorType) && this.isRetryableError(errorInfo.errorType); - } - getCapacityCost(errorType) { - return errorType === Retry.modifiedCostType() ? Retry.throttlingCost() : Retry.cost(); - } - isRetryableError(errorType) { - return errorType === "THROTTLING" || errorType === "TRANSIENT"; - } - async maxAttempts() { - return this.maxAttemptsProvider(); - } - }; - var AdaptiveRetryStrategy = class { - mode = exports.RETRY_MODES.ADAPTIVE; - rateLimiter; - standardRetryStrategy; - constructor(maxAttemptsProvider, options) { - const { rateLimiter } = options ?? {}; - this.rateLimiter = rateLimiter ?? new DefaultRateLimiter(); - this.standardRetryStrategy = options ? new StandardRetryStrategy({ - maxAttempts: typeof maxAttemptsProvider === "number" ? maxAttemptsProvider : 3, - ...options - }) : new StandardRetryStrategy(maxAttemptsProvider); - } - async acquireInitialRetryToken(retryTokenScope) { - await this.rateLimiter.getSendToken(); - return this.standardRetryStrategy.acquireInitialRetryToken(retryTokenScope); - } - async refreshRetryTokenForRetry(tokenToRenew, errorInfo) { - this.rateLimiter.updateClientSendingRate(errorInfo); - return this.standardRetryStrategy.refreshRetryTokenForRetry(tokenToRenew, errorInfo); - } - recordSuccess(token) { - this.rateLimiter.updateClientSendingRate({}); - this.standardRetryStrategy.recordSuccess(token); - } - async maxAttemptsProvider() { - return this.standardRetryStrategy.maxAttempts(); - } - }; - var ConfiguredRetryStrategy = class extends StandardRetryStrategy { - computeNextBackoffDelay; - constructor(maxAttempts, computeNextBackoffDelay = Retry.delay()) { - super(typeof maxAttempts === "function" ? maxAttempts : async () => maxAttempts); - if (typeof computeNextBackoffDelay === "number") { - this.computeNextBackoffDelay = () => computeNextBackoffDelay; - } else { - this.computeNextBackoffDelay = computeNextBackoffDelay; - } - } - async refreshRetryTokenForRetry(tokenToRenew, errorInfo) { - const token = await super.refreshRetryTokenForRetry(tokenToRenew, errorInfo); - token.getRetryDelay = () => this.computeNextBackoffDelay(token.getRetryCount()); - return token; - } - }; - exports.AdaptiveRetryStrategy = AdaptiveRetryStrategy; - exports.ConfiguredRetryStrategy = ConfiguredRetryStrategy; - exports.DEFAULT_MAX_ATTEMPTS = DEFAULT_MAX_ATTEMPTS; - exports.DEFAULT_RETRY_DELAY_BASE = DEFAULT_RETRY_DELAY_BASE; - exports.DEFAULT_RETRY_MODE = DEFAULT_RETRY_MODE5; - exports.DefaultRateLimiter = DefaultRateLimiter; - exports.INITIAL_RETRY_TOKENS = INITIAL_RETRY_TOKENS; - exports.INVOCATION_ID_HEADER = INVOCATION_ID_HEADER; - exports.MAXIMUM_RETRY_DELAY = MAXIMUM_RETRY_DELAY; - exports.NO_RETRY_INCREMENT = NO_RETRY_INCREMENT; - exports.REQUEST_HEADER = REQUEST_HEADER; - exports.RETRY_COST = RETRY_COST; - exports.Retry = Retry; - exports.StandardRetryStrategy = StandardRetryStrategy; - exports.THROTTLING_RETRY_DELAY_BASE = THROTTLING_RETRY_DELAY_BASE; - exports.TIMEOUT_RETRY_COST = TIMEOUT_RETRY_COST; - } -}); - -// node_modules/.pnpm/@aws-sdk+middleware-user-agent@3.972.29/node_modules/@aws-sdk/middleware-user-agent/dist-cjs/index.js -var require_dist_cjs37 = __commonJS({ - "node_modules/.pnpm/@aws-sdk+middleware-user-agent@3.972.29/node_modules/@aws-sdk/middleware-user-agent/dist-cjs/index.js"(exports) { - "use strict"; - var core = (init_dist_es(), __toCommonJS(dist_es_exports)); - var utilEndpoints = require_dist_cjs34(); - var protocolHttp = require_dist_cjs2(); - var client2 = (init_client2(), __toCommonJS(client_exports)); - var utilRetry = require_dist_cjs36(); - var DEFAULT_UA_APP_ID = void 0; - function isValidUserAgentAppId(appId) { - if (appId === void 0) { - return true; - } - return typeof appId === "string" && appId.length <= 50; - } - function resolveUserAgentConfig5(input) { - const normalizedAppIdProvider = core.normalizeProvider(input.userAgentAppId ?? DEFAULT_UA_APP_ID); - const { customUserAgent } = input; - return Object.assign(input, { - customUserAgent: typeof customUserAgent === "string" ? [[customUserAgent]] : customUserAgent, - userAgentAppId: async () => { - const appId = await normalizedAppIdProvider(); - if (!isValidUserAgentAppId(appId)) { - const logger4 = input.logger?.constructor?.name === "NoOpLogger" || !input.logger ? console : input.logger; - if (typeof appId !== "string") { - logger4?.warn("userAgentAppId must be a string or undefined."); - } else if (appId.length > 50) { - logger4?.warn("The provided userAgentAppId exceeds the maximum length of 50 characters."); - } - } - return appId; - } - }); - } - var ACCOUNT_ID_ENDPOINT_REGEX = /\d{12}\.ddb/; - async function checkFeatures(context, config3, args) { - const request = args.request; - if (request?.headers?.["smithy-protocol"] === "rpc-v2-cbor") { - client2.setFeature(context, "PROTOCOL_RPC_V2_CBOR", "M"); - } - if (typeof config3.retryStrategy === "function") { - const retryStrategy = await config3.retryStrategy(); - if (typeof retryStrategy.mode === "string") { - switch (retryStrategy.mode) { - case utilRetry.RETRY_MODES.ADAPTIVE: - client2.setFeature(context, "RETRY_MODE_ADAPTIVE", "F"); - break; - case utilRetry.RETRY_MODES.STANDARD: - client2.setFeature(context, "RETRY_MODE_STANDARD", "E"); - break; - } - } - } - if (typeof config3.accountIdEndpointMode === "function") { - const endpointV2 = context.endpointV2; - if (String(endpointV2?.url?.hostname).match(ACCOUNT_ID_ENDPOINT_REGEX)) { - client2.setFeature(context, "ACCOUNT_ID_ENDPOINT", "O"); - } - switch (await config3.accountIdEndpointMode?.()) { - case "disabled": - client2.setFeature(context, "ACCOUNT_ID_MODE_DISABLED", "Q"); - break; - case "preferred": - client2.setFeature(context, "ACCOUNT_ID_MODE_PREFERRED", "P"); - break; - case "required": - client2.setFeature(context, "ACCOUNT_ID_MODE_REQUIRED", "R"); - break; - } - } - const identity = context.__smithy_context?.selectedHttpAuthScheme?.identity; - if (identity?.$source) { - const credentials = identity; - if (credentials.accountId) { - client2.setFeature(context, "RESOLVED_ACCOUNT_ID", "T"); - } - for (const [key, value] of Object.entries(credentials.$source ?? {})) { - client2.setFeature(context, key, value); - } - } - } - var USER_AGENT2 = "user-agent"; - var X_AMZ_USER_AGENT = "x-amz-user-agent"; - var SPACE = " "; - var UA_NAME_SEPARATOR = "/"; - var UA_NAME_ESCAPE_REGEX = /[^!$%&'*+\-.^_`|~\w]/g; - var UA_VALUE_ESCAPE_REGEX = /[^!$%&'*+\-.^_`|~\w#]/g; - var UA_ESCAPE_CHAR = "-"; - var BYTE_LIMIT = 1024; - function encodeFeatures(features) { - let buffer2 = ""; - for (const key in features) { - const val = features[key]; - if (buffer2.length + val.length + 1 <= BYTE_LIMIT) { - if (buffer2.length) { - buffer2 += "," + val; - } else { - buffer2 += val; - } - continue; - } - break; - } - return buffer2; - } - var userAgentMiddleware = (options) => (next, context) => async (args) => { - const { request } = args; - if (!protocolHttp.HttpRequest.isInstance(request)) { - return next(args); - } - const { headers } = request; - const userAgent = context?.userAgent?.map(escapeUserAgent) || []; - const defaultUserAgent = (await options.defaultUserAgentProvider()).map(escapeUserAgent); - await checkFeatures(context, options, args); - const awsContext = context; - defaultUserAgent.push(`m/${encodeFeatures(Object.assign({}, context.__smithy_context?.features, awsContext.__aws_sdk_context?.features))}`); - const customUserAgent = options?.customUserAgent?.map(escapeUserAgent) || []; - const appId = await options.userAgentAppId(); - if (appId) { - defaultUserAgent.push(escapeUserAgent([`app`, `${appId}`])); - } - const prefix = utilEndpoints.getUserAgentPrefix(); - const sdkUserAgentValue = (prefix ? [prefix] : []).concat([...defaultUserAgent, ...userAgent, ...customUserAgent]).join(SPACE); - const normalUAValue = [ - ...defaultUserAgent.filter((section) => section.startsWith("aws-sdk-")), - ...customUserAgent - ].join(SPACE); - if (options.runtime !== "browser") { - if (normalUAValue) { - headers[X_AMZ_USER_AGENT] = headers[X_AMZ_USER_AGENT] ? `${headers[USER_AGENT2]} ${normalUAValue}` : normalUAValue; - } - headers[USER_AGENT2] = sdkUserAgentValue; - } else { - headers[X_AMZ_USER_AGENT] = sdkUserAgentValue; - } - return next({ - ...args, - request - }); - }; - var escapeUserAgent = (userAgentPair) => { - const name = userAgentPair[0].split(UA_NAME_SEPARATOR).map((part) => part.replace(UA_NAME_ESCAPE_REGEX, UA_ESCAPE_CHAR)).join(UA_NAME_SEPARATOR); - const version3 = userAgentPair[1]?.replace(UA_VALUE_ESCAPE_REGEX, UA_ESCAPE_CHAR); - const prefixSeparatorIndex = name.indexOf(UA_NAME_SEPARATOR); - const prefix = name.substring(0, prefixSeparatorIndex); - let uaName = name.substring(prefixSeparatorIndex + 1); - if (prefix === "api") { - uaName = uaName.toLowerCase(); - } - return [prefix, uaName, version3].filter((item) => item && item.length > 0).reduce((acc, item, index2) => { - switch (index2) { - case 0: - return item; - case 1: - return `${acc}/${item}`; - default: - return `${acc}#${item}`; - } - }, ""); - }; - var getUserAgentMiddlewareOptions = { - name: "getUserAgentMiddleware", - step: "build", - priority: "low", - tags: ["SET_USER_AGENT", "USER_AGENT"], - override: true - }; - var getUserAgentPlugin5 = (config3) => ({ - applyToStack: (clientStack) => { - clientStack.add(userAgentMiddleware(config3), getUserAgentMiddlewareOptions); - } - }); - exports.DEFAULT_UA_APP_ID = DEFAULT_UA_APP_ID; - exports.getUserAgentMiddlewareOptions = getUserAgentMiddlewareOptions; - exports.getUserAgentPlugin = getUserAgentPlugin5; - exports.resolveUserAgentConfig = resolveUserAgentConfig5; - exports.userAgentMiddleware = userAgentMiddleware; - } -}); - -// node_modules/.pnpm/@smithy+config-resolver@4.4.15/node_modules/@smithy/config-resolver/dist-cjs/index.js -var require_dist_cjs38 = __commonJS({ - "node_modules/.pnpm/@smithy+config-resolver@4.4.15/node_modules/@smithy/config-resolver/dist-cjs/index.js"(exports) { - "use strict"; - var utilConfigProvider = require_dist_cjs31(); - var utilMiddleware = require_dist_cjs18(); - var utilEndpoints = require_dist_cjs33(); - var ENV_USE_DUALSTACK_ENDPOINT = "AWS_USE_DUALSTACK_ENDPOINT"; - var CONFIG_USE_DUALSTACK_ENDPOINT = "use_dualstack_endpoint"; - var DEFAULT_USE_DUALSTACK_ENDPOINT = false; - var NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS5 = { - environmentVariableSelector: (env2) => utilConfigProvider.booleanSelector(env2, ENV_USE_DUALSTACK_ENDPOINT, utilConfigProvider.SelectorType.ENV), - configFileSelector: (profile) => utilConfigProvider.booleanSelector(profile, CONFIG_USE_DUALSTACK_ENDPOINT, utilConfigProvider.SelectorType.CONFIG), - default: false - }; - var nodeDualstackConfigSelectors = { - environmentVariableSelector: (env2) => utilConfigProvider.booleanSelector(env2, ENV_USE_DUALSTACK_ENDPOINT, utilConfigProvider.SelectorType.ENV), - configFileSelector: (profile) => utilConfigProvider.booleanSelector(profile, CONFIG_USE_DUALSTACK_ENDPOINT, utilConfigProvider.SelectorType.CONFIG), - default: void 0 - }; - var ENV_USE_FIPS_ENDPOINT = "AWS_USE_FIPS_ENDPOINT"; - var CONFIG_USE_FIPS_ENDPOINT = "use_fips_endpoint"; - var DEFAULT_USE_FIPS_ENDPOINT = false; - var NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS5 = { - environmentVariableSelector: (env2) => utilConfigProvider.booleanSelector(env2, ENV_USE_FIPS_ENDPOINT, utilConfigProvider.SelectorType.ENV), - configFileSelector: (profile) => utilConfigProvider.booleanSelector(profile, CONFIG_USE_FIPS_ENDPOINT, utilConfigProvider.SelectorType.CONFIG), - default: false - }; - var nodeFipsConfigSelectors = { - environmentVariableSelector: (env2) => utilConfigProvider.booleanSelector(env2, ENV_USE_FIPS_ENDPOINT, utilConfigProvider.SelectorType.ENV), - configFileSelector: (profile) => utilConfigProvider.booleanSelector(profile, CONFIG_USE_FIPS_ENDPOINT, utilConfigProvider.SelectorType.CONFIG), - default: void 0 - }; - var resolveCustomEndpointsConfig = (input) => { - const { tls: tls2, endpoint, urlParser, useDualstackEndpoint } = input; - return Object.assign(input, { - tls: tls2 ?? true, - endpoint: utilMiddleware.normalizeProvider(typeof endpoint === "string" ? urlParser(endpoint) : endpoint), - isCustomEndpoint: true, - useDualstackEndpoint: utilMiddleware.normalizeProvider(useDualstackEndpoint ?? false) - }); - }; - var getEndpointFromRegion = async (input) => { - const { tls: tls2 = true } = input; - const region = await input.region(); - const dnsHostRegex = new RegExp(/^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9])$/); - if (!dnsHostRegex.test(region)) { - throw new Error("Invalid region in client config"); - } - const useDualstackEndpoint = await input.useDualstackEndpoint(); - const useFipsEndpoint = await input.useFipsEndpoint(); - const { hostname: hostname3 } = await input.regionInfoProvider(region, { useDualstackEndpoint, useFipsEndpoint }) ?? {}; - if (!hostname3) { - throw new Error("Cannot resolve hostname from client config"); - } - return input.urlParser(`${tls2 ? "https:" : "http:"}//${hostname3}`); - }; - var resolveEndpointsConfig = (input) => { - const useDualstackEndpoint = utilMiddleware.normalizeProvider(input.useDualstackEndpoint ?? false); - const { endpoint, useFipsEndpoint, urlParser, tls: tls2 } = input; - return Object.assign(input, { - tls: tls2 ?? true, - endpoint: endpoint ? utilMiddleware.normalizeProvider(typeof endpoint === "string" ? urlParser(endpoint) : endpoint) : () => getEndpointFromRegion({ ...input, useDualstackEndpoint, useFipsEndpoint }), - isCustomEndpoint: !!endpoint, - useDualstackEndpoint - }); - }; - var REGION_ENV_NAME = "AWS_REGION"; - var REGION_INI_NAME = "region"; - var NODE_REGION_CONFIG_OPTIONS5 = { - environmentVariableSelector: (env2) => env2[REGION_ENV_NAME], - configFileSelector: (profile) => profile[REGION_INI_NAME], - default: () => { - throw new Error("Region is missing"); - } - }; - var NODE_REGION_CONFIG_FILE_OPTIONS5 = { - preferredFile: "credentials" - }; - var validRegions = /* @__PURE__ */ new Set(); - var checkRegion = (region, check3 = utilEndpoints.isValidHostLabel) => { - if (!validRegions.has(region) && !check3(region)) { - if (region === "*") { - console.warn(`@smithy/config-resolver WARN - Please use the caller region instead of "*". See "sigv4a" in https://github.com/aws/aws-sdk-js-v3/blob/main/supplemental-docs/CLIENTS.md.`); - } else { - throw new Error(`Region not accepted: region="${region}" is not a valid hostname component.`); - } - } else { - validRegions.add(region); - } - }; - var isFipsRegion = (region) => typeof region === "string" && (region.startsWith("fips-") || region.endsWith("-fips")); - var getRealRegion = (region) => isFipsRegion(region) ? ["fips-aws-global", "aws-fips"].includes(region) ? "us-east-1" : region.replace(/fips-(dkr-|prod-)?|-fips/, "") : region; - var resolveRegionConfig5 = (input) => { - const { region, useFipsEndpoint } = input; - if (!region) { - throw new Error("Region is missing"); - } - return Object.assign(input, { - region: async () => { - const providedRegion = typeof region === "function" ? await region() : region; - const realRegion = getRealRegion(providedRegion); - checkRegion(realRegion); - return realRegion; - }, - useFipsEndpoint: async () => { - const providedRegion = typeof region === "string" ? region : await region(); - if (isFipsRegion(providedRegion)) { - return true; - } - return typeof useFipsEndpoint !== "function" ? Promise.resolve(!!useFipsEndpoint) : useFipsEndpoint(); - } - }); - }; - var getHostnameFromVariants = (variants = [], { useFipsEndpoint, useDualstackEndpoint }) => variants.find(({ tags }) => useFipsEndpoint === tags.includes("fips") && useDualstackEndpoint === tags.includes("dualstack"))?.hostname; - var getResolvedHostname = (resolvedRegion, { regionHostname, partitionHostname }) => regionHostname ? regionHostname : partitionHostname ? partitionHostname.replace("{region}", resolvedRegion) : void 0; - var getResolvedPartition = (region, { partitionHash }) => Object.keys(partitionHash || {}).find((key) => partitionHash[key].regions.includes(region)) ?? "aws"; - var getResolvedSigningRegion = (hostname3, { signingRegion, regionRegex, useFipsEndpoint }) => { - if (signingRegion) { - return signingRegion; - } else if (useFipsEndpoint) { - const regionRegexJs = regionRegex.replace("\\\\", "\\").replace(/^\^/g, "\\.").replace(/\$$/g, "\\."); - const regionRegexmatchArray = hostname3.match(regionRegexJs); - if (regionRegexmatchArray) { - return regionRegexmatchArray[0].slice(1, -1); - } - } - }; - var getRegionInfo = (region, { useFipsEndpoint = false, useDualstackEndpoint = false, signingService, regionHash, partitionHash }) => { - const partition = getResolvedPartition(region, { partitionHash }); - const resolvedRegion = region in regionHash ? region : partitionHash[partition]?.endpoint ?? region; - const hostnameOptions = { useFipsEndpoint, useDualstackEndpoint }; - const regionHostname = getHostnameFromVariants(regionHash[resolvedRegion]?.variants, hostnameOptions); - const partitionHostname = getHostnameFromVariants(partitionHash[partition]?.variants, hostnameOptions); - const hostname3 = getResolvedHostname(resolvedRegion, { regionHostname, partitionHostname }); - if (hostname3 === void 0) { - throw new Error(`Endpoint resolution failed for: ${{ resolvedRegion, useFipsEndpoint, useDualstackEndpoint }}`); - } - const signingRegion = getResolvedSigningRegion(hostname3, { - signingRegion: regionHash[resolvedRegion]?.signingRegion, - regionRegex: partitionHash[partition].regionRegex, - useFipsEndpoint - }); - return { - partition, - signingService, - hostname: hostname3, - ...signingRegion && { signingRegion }, - ...regionHash[resolvedRegion]?.signingService && { - signingService: regionHash[resolvedRegion].signingService - } - }; - }; - exports.CONFIG_USE_DUALSTACK_ENDPOINT = CONFIG_USE_DUALSTACK_ENDPOINT; - exports.CONFIG_USE_FIPS_ENDPOINT = CONFIG_USE_FIPS_ENDPOINT; - exports.DEFAULT_USE_DUALSTACK_ENDPOINT = DEFAULT_USE_DUALSTACK_ENDPOINT; - exports.DEFAULT_USE_FIPS_ENDPOINT = DEFAULT_USE_FIPS_ENDPOINT; - exports.ENV_USE_DUALSTACK_ENDPOINT = ENV_USE_DUALSTACK_ENDPOINT; - exports.ENV_USE_FIPS_ENDPOINT = ENV_USE_FIPS_ENDPOINT; - exports.NODE_REGION_CONFIG_FILE_OPTIONS = NODE_REGION_CONFIG_FILE_OPTIONS5; - exports.NODE_REGION_CONFIG_OPTIONS = NODE_REGION_CONFIG_OPTIONS5; - exports.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS = NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS5; - exports.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS = NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS5; - exports.REGION_ENV_NAME = REGION_ENV_NAME; - exports.REGION_INI_NAME = REGION_INI_NAME; - exports.getRegionInfo = getRegionInfo; - exports.nodeDualstackConfigSelectors = nodeDualstackConfigSelectors; - exports.nodeFipsConfigSelectors = nodeFipsConfigSelectors; - exports.resolveCustomEndpointsConfig = resolveCustomEndpointsConfig; - exports.resolveEndpointsConfig = resolveEndpointsConfig; - exports.resolveRegionConfig = resolveRegionConfig5; - } -}); - -// node_modules/.pnpm/@smithy+eventstream-serde-config-resolver@4.3.13/node_modules/@smithy/eventstream-serde-config-resolver/dist-cjs/index.js -var require_dist_cjs39 = __commonJS({ - "node_modules/.pnpm/@smithy+eventstream-serde-config-resolver@4.3.13/node_modules/@smithy/eventstream-serde-config-resolver/dist-cjs/index.js"(exports) { - "use strict"; - var resolveEventStreamSerdeConfig = (input) => Object.assign(input, { - eventStreamMarshaller: input.eventStreamSerdeProvider(input) - }); - exports.resolveEventStreamSerdeConfig = resolveEventStreamSerdeConfig; - } -}); - -// node_modules/.pnpm/@smithy+middleware-content-length@4.2.13/node_modules/@smithy/middleware-content-length/dist-cjs/index.js -var require_dist_cjs40 = __commonJS({ - "node_modules/.pnpm/@smithy+middleware-content-length@4.2.13/node_modules/@smithy/middleware-content-length/dist-cjs/index.js"(exports) { - "use strict"; - var protocolHttp = require_dist_cjs2(); - var CONTENT_LENGTH_HEADER = "content-length"; - function contentLengthMiddleware(bodyLengthChecker) { - return (next) => async (args) => { - const request = args.request; - if (protocolHttp.HttpRequest.isInstance(request)) { - const { body, headers } = request; - if (body && Object.keys(headers).map((str) => str.toLowerCase()).indexOf(CONTENT_LENGTH_HEADER) === -1) { - try { - const length = bodyLengthChecker(body); - request.headers = { - ...request.headers, - [CONTENT_LENGTH_HEADER]: String(length) - }; - } catch (error50) { - } - } - } - return next({ - ...args, - request - }); - }; - } - var contentLengthMiddlewareOptions = { - step: "build", - tags: ["SET_CONTENT_LENGTH", "CONTENT_LENGTH"], - name: "contentLengthMiddleware", - override: true - }; - var getContentLengthPlugin5 = (options) => ({ - applyToStack: (clientStack) => { - clientStack.add(contentLengthMiddleware(options.bodyLengthChecker), contentLengthMiddlewareOptions); - } - }); - exports.contentLengthMiddleware = contentLengthMiddleware; - exports.contentLengthMiddlewareOptions = contentLengthMiddlewareOptions; - exports.getContentLengthPlugin = getContentLengthPlugin5; - } -}); - -// node_modules/.pnpm/@smithy+property-provider@4.2.13/node_modules/@smithy/property-provider/dist-cjs/index.js -var require_dist_cjs41 = __commonJS({ - "node_modules/.pnpm/@smithy+property-provider@4.2.13/node_modules/@smithy/property-provider/dist-cjs/index.js"(exports) { - "use strict"; - var ProviderError2 = class _ProviderError extends Error { - name = "ProviderError"; - tryNextLink; - constructor(message2, options = true) { - let logger4; - let tryNextLink = true; - if (typeof options === "boolean") { - logger4 = void 0; - tryNextLink = options; - } else if (options != null && typeof options === "object") { - logger4 = options.logger; - tryNextLink = options.tryNextLink ?? true; - } - super(message2); - this.tryNextLink = tryNextLink; - Object.setPrototypeOf(this, _ProviderError.prototype); - logger4?.debug?.(`@smithy/property-provider ${tryNextLink ? "->" : "(!)"} ${message2}`); - } - static from(error50, options = true) { - return Object.assign(new this(error50.message, options), error50); - } - }; - var CredentialsProviderError = class _CredentialsProviderError extends ProviderError2 { - name = "CredentialsProviderError"; - constructor(message2, options = true) { - super(message2, options); - Object.setPrototypeOf(this, _CredentialsProviderError.prototype); - } - }; - var TokenProviderError = class _TokenProviderError extends ProviderError2 { - name = "TokenProviderError"; - constructor(message2, options = true) { - super(message2, options); - Object.setPrototypeOf(this, _TokenProviderError.prototype); - } - }; - var chain = (...providers2) => async () => { - if (providers2.length === 0) { - throw new ProviderError2("No providers in chain"); - } - let lastProviderError; - for (const provider of providers2) { - try { - const credentials = await provider(); - return credentials; - } catch (err) { - lastProviderError = err; - if (err?.tryNextLink) { - continue; - } - throw err; - } - } - throw lastProviderError; - }; - var fromStatic = (staticValue) => () => Promise.resolve(staticValue); - var memoize = (provider, isExpired, requiresRefresh) => { - let resolved; - let pending; - let hasResult; - let isConstant = false; - const coalesceProvider = async () => { - if (!pending) { - pending = provider(); - } - try { - resolved = await pending; - hasResult = true; - isConstant = false; - } finally { - pending = void 0; - } - return resolved; - }; - if (isExpired === void 0) { - return async (options) => { - if (!hasResult || options?.forceRefresh) { - resolved = await coalesceProvider(); - } - return resolved; - }; - } - return async (options) => { - if (!hasResult || options?.forceRefresh) { - resolved = await coalesceProvider(); - } - if (isConstant) { - return resolved; - } - if (requiresRefresh && !requiresRefresh(resolved)) { - isConstant = true; - return resolved; - } - if (isExpired(resolved)) { - await coalesceProvider(); - return resolved; - } - return resolved; - }; - }; - exports.CredentialsProviderError = CredentialsProviderError; - exports.ProviderError = ProviderError2; - exports.TokenProviderError = TokenProviderError; - exports.chain = chain; - exports.fromStatic = fromStatic; - exports.memoize = memoize; - } -}); - -// node_modules/.pnpm/@smithy+shared-ini-file-loader@4.4.8/node_modules/@smithy/shared-ini-file-loader/dist-cjs/getHomeDir.js -var require_getHomeDir = __commonJS({ - "node_modules/.pnpm/@smithy+shared-ini-file-loader@4.4.8/node_modules/@smithy/shared-ini-file-loader/dist-cjs/getHomeDir.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.getHomeDir = void 0; - var os_1 = __require("os"); - var path_1 = __require("path"); - var homeDirCache = {}; - var getHomeDirCacheKey = () => { - if (process && process.geteuid) { - return `${process.geteuid()}`; - } - return "DEFAULT"; - }; - var getHomeDir = () => { - const { HOME, USERPROFILE, HOMEPATH, HOMEDRIVE = `C:${path_1.sep}` } = process.env; - if (HOME) - return HOME; - if (USERPROFILE) - return USERPROFILE; - if (HOMEPATH) - return `${HOMEDRIVE}${HOMEPATH}`; - const homeDirCacheKey = getHomeDirCacheKey(); - if (!homeDirCache[homeDirCacheKey]) - homeDirCache[homeDirCacheKey] = (0, os_1.homedir)(); - return homeDirCache[homeDirCacheKey]; - }; - exports.getHomeDir = getHomeDir; - } -}); - -// node_modules/.pnpm/@smithy+shared-ini-file-loader@4.4.8/node_modules/@smithy/shared-ini-file-loader/dist-cjs/getSSOTokenFilepath.js -var require_getSSOTokenFilepath = __commonJS({ - "node_modules/.pnpm/@smithy+shared-ini-file-loader@4.4.8/node_modules/@smithy/shared-ini-file-loader/dist-cjs/getSSOTokenFilepath.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.getSSOTokenFilepath = void 0; - var crypto_1 = __require("crypto"); - var path_1 = __require("path"); - var getHomeDir_1 = require_getHomeDir(); - var getSSOTokenFilepath = (id) => { - const hasher = (0, crypto_1.createHash)("sha1"); - const cacheName = hasher.update(id).digest("hex"); - return (0, path_1.join)((0, getHomeDir_1.getHomeDir)(), ".aws", "sso", "cache", `${cacheName}.json`); - }; - exports.getSSOTokenFilepath = getSSOTokenFilepath; - } -}); - -// node_modules/.pnpm/@smithy+shared-ini-file-loader@4.4.8/node_modules/@smithy/shared-ini-file-loader/dist-cjs/getSSOTokenFromFile.js -var require_getSSOTokenFromFile = __commonJS({ - "node_modules/.pnpm/@smithy+shared-ini-file-loader@4.4.8/node_modules/@smithy/shared-ini-file-loader/dist-cjs/getSSOTokenFromFile.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.getSSOTokenFromFile = exports.tokenIntercept = void 0; - var promises_1 = __require("fs/promises"); - var getSSOTokenFilepath_1 = require_getSSOTokenFilepath(); - exports.tokenIntercept = {}; - var getSSOTokenFromFile = async (id) => { - if (exports.tokenIntercept[id]) { - return exports.tokenIntercept[id]; - } - const ssoTokenFilepath = (0, getSSOTokenFilepath_1.getSSOTokenFilepath)(id); - const ssoTokenText = await (0, promises_1.readFile)(ssoTokenFilepath, "utf8"); - return JSON.parse(ssoTokenText); - }; - exports.getSSOTokenFromFile = getSSOTokenFromFile; - } -}); - -// node_modules/.pnpm/@smithy+shared-ini-file-loader@4.4.8/node_modules/@smithy/shared-ini-file-loader/dist-cjs/readFile.js -var require_readFile = __commonJS({ - "node_modules/.pnpm/@smithy+shared-ini-file-loader@4.4.8/node_modules/@smithy/shared-ini-file-loader/dist-cjs/readFile.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.readFile = exports.fileIntercept = exports.filePromises = void 0; - var promises_1 = __require("node:fs/promises"); - exports.filePromises = {}; - exports.fileIntercept = {}; - var readFile5 = (path53, options) => { - if (exports.fileIntercept[path53] !== void 0) { - return exports.fileIntercept[path53]; - } - if (!exports.filePromises[path53] || options?.ignoreCache) { - exports.filePromises[path53] = (0, promises_1.readFile)(path53, "utf8"); - } - return exports.filePromises[path53]; - }; - exports.readFile = readFile5; - } -}); - -// node_modules/.pnpm/@smithy+shared-ini-file-loader@4.4.8/node_modules/@smithy/shared-ini-file-loader/dist-cjs/index.js -var require_dist_cjs42 = __commonJS({ - "node_modules/.pnpm/@smithy+shared-ini-file-loader@4.4.8/node_modules/@smithy/shared-ini-file-loader/dist-cjs/index.js"(exports) { - "use strict"; - var getHomeDir = require_getHomeDir(); - var getSSOTokenFilepath = require_getSSOTokenFilepath(); - var getSSOTokenFromFile = require_getSSOTokenFromFile(); - var path53 = __require("path"); - var types2 = require_dist_cjs(); - var readFile5 = require_readFile(); - var ENV_PROFILE = "AWS_PROFILE"; - var DEFAULT_PROFILE = "default"; - var getProfileName = (init2) => init2.profile || process.env[ENV_PROFILE] || DEFAULT_PROFILE; - var CONFIG_PREFIX_SEPARATOR = "."; - var getConfigData = (data2) => Object.entries(data2).filter(([key]) => { - const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR); - if (indexOfSeparator === -1) { - return false; - } - return Object.values(types2.IniSectionType).includes(key.substring(0, indexOfSeparator)); - }).reduce((acc, [key, value]) => { - const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR); - const updatedKey = key.substring(0, indexOfSeparator) === types2.IniSectionType.PROFILE ? key.substring(indexOfSeparator + 1) : key; - acc[updatedKey] = value; - return acc; - }, { - ...data2.default && { default: data2.default } - }); - var ENV_CONFIG_PATH = "AWS_CONFIG_FILE"; - var getConfigFilepath = () => process.env[ENV_CONFIG_PATH] || path53.join(getHomeDir.getHomeDir(), ".aws", "config"); - var ENV_CREDENTIALS_PATH = "AWS_SHARED_CREDENTIALS_FILE"; - var getCredentialsFilepath = () => process.env[ENV_CREDENTIALS_PATH] || path53.join(getHomeDir.getHomeDir(), ".aws", "credentials"); - var prefixKeyRegex = /^([\w-]+)\s(["'])?([\w-@\+\.%:/]+)\2$/; - var profileNameBlockList = ["__proto__", "profile __proto__"]; - var parseIni = (iniData) => { - const map4 = {}; - let currentSection; - let currentSubSection; - for (const iniLine of iniData.split(/\r?\n/)) { - const trimmedLine = iniLine.split(/(^|\s)[;#]/)[0].trim(); - const isSection = trimmedLine[0] === "[" && trimmedLine[trimmedLine.length - 1] === "]"; - if (isSection) { - currentSection = void 0; - currentSubSection = void 0; - const sectionName = trimmedLine.substring(1, trimmedLine.length - 1); - const matches = prefixKeyRegex.exec(sectionName); - if (matches) { - const [, prefix, , name] = matches; - if (Object.values(types2.IniSectionType).includes(prefix)) { - currentSection = [prefix, name].join(CONFIG_PREFIX_SEPARATOR); - } - } else { - currentSection = sectionName; - } - if (profileNameBlockList.includes(sectionName)) { - throw new Error(`Found invalid profile name "${sectionName}"`); - } - } else if (currentSection) { - const indexOfEqualsSign = trimmedLine.indexOf("="); - if (![0, -1].includes(indexOfEqualsSign)) { - const [name, value] = [ - trimmedLine.substring(0, indexOfEqualsSign).trim(), - trimmedLine.substring(indexOfEqualsSign + 1).trim() - ]; - if (value === "") { - currentSubSection = name; - } else { - if (currentSubSection && iniLine.trimStart() === iniLine) { - currentSubSection = void 0; - } - map4[currentSection] = map4[currentSection] || {}; - const key = currentSubSection ? [currentSubSection, name].join(CONFIG_PREFIX_SEPARATOR) : name; - map4[currentSection][key] = value; - } - } - } - } - return map4; - }; - var swallowError$1 = () => ({}); - var loadSharedConfigFiles = async (init2 = {}) => { - const { filepath = getCredentialsFilepath(), configFilepath = getConfigFilepath() } = init2; - const homeDir = getHomeDir.getHomeDir(); - const relativeHomeDirPrefix = "~/"; - let resolvedFilepath = filepath; - if (filepath.startsWith(relativeHomeDirPrefix)) { - resolvedFilepath = path53.join(homeDir, filepath.slice(2)); - } - let resolvedConfigFilepath = configFilepath; - if (configFilepath.startsWith(relativeHomeDirPrefix)) { - resolvedConfigFilepath = path53.join(homeDir, configFilepath.slice(2)); - } - const parsedFiles = await Promise.all([ - readFile5.readFile(resolvedConfigFilepath, { - ignoreCache: init2.ignoreCache - }).then(parseIni).then(getConfigData).catch(swallowError$1), - readFile5.readFile(resolvedFilepath, { - ignoreCache: init2.ignoreCache - }).then(parseIni).catch(swallowError$1) - ]); - return { - configFile: parsedFiles[0], - credentialsFile: parsedFiles[1] - }; - }; - var getSsoSessionData = (data2) => Object.entries(data2).filter(([key]) => key.startsWith(types2.IniSectionType.SSO_SESSION + CONFIG_PREFIX_SEPARATOR)).reduce((acc, [key, value]) => ({ ...acc, [key.substring(key.indexOf(CONFIG_PREFIX_SEPARATOR) + 1)]: value }), {}); - var swallowError = () => ({}); - var loadSsoSessionData = async (init2 = {}) => readFile5.readFile(init2.configFilepath ?? getConfigFilepath()).then(parseIni).then(getSsoSessionData).catch(swallowError); - var mergeConfigFiles = (...files) => { - const merged = {}; - for (const file2 of files) { - for (const [key, values2] of Object.entries(file2)) { - if (merged[key] !== void 0) { - Object.assign(merged[key], values2); - } else { - merged[key] = values2; - } - } - } - return merged; - }; - var parseKnownFiles = async (init2) => { - const parsedFiles = await loadSharedConfigFiles(init2); - return mergeConfigFiles(parsedFiles.configFile, parsedFiles.credentialsFile); - }; - var externalDataInterceptor = { - getFileRecord() { - return readFile5.fileIntercept; - }, - interceptFile(path54, contents) { - readFile5.fileIntercept[path54] = Promise.resolve(contents); - }, - getTokenRecord() { - return getSSOTokenFromFile.tokenIntercept; - }, - interceptToken(id, contents) { - getSSOTokenFromFile.tokenIntercept[id] = contents; - } - }; - exports.getSSOTokenFromFile = getSSOTokenFromFile.getSSOTokenFromFile; - exports.readFile = readFile5.readFile; - exports.CONFIG_PREFIX_SEPARATOR = CONFIG_PREFIX_SEPARATOR; - exports.DEFAULT_PROFILE = DEFAULT_PROFILE; - exports.ENV_PROFILE = ENV_PROFILE; - exports.externalDataInterceptor = externalDataInterceptor; - exports.getProfileName = getProfileName; - exports.loadSharedConfigFiles = loadSharedConfigFiles; - exports.loadSsoSessionData = loadSsoSessionData; - exports.parseKnownFiles = parseKnownFiles; - Object.prototype.hasOwnProperty.call(getHomeDir, "__proto__") && !Object.prototype.hasOwnProperty.call(exports, "__proto__") && Object.defineProperty(exports, "__proto__", { - enumerable: true, - value: getHomeDir["__proto__"] - }); - Object.keys(getHomeDir).forEach(function(k5) { - if (k5 !== "default" && !Object.prototype.hasOwnProperty.call(exports, k5)) exports[k5] = getHomeDir[k5]; - }); - Object.prototype.hasOwnProperty.call(getSSOTokenFilepath, "__proto__") && !Object.prototype.hasOwnProperty.call(exports, "__proto__") && Object.defineProperty(exports, "__proto__", { - enumerable: true, - value: getSSOTokenFilepath["__proto__"] - }); - Object.keys(getSSOTokenFilepath).forEach(function(k5) { - if (k5 !== "default" && !Object.prototype.hasOwnProperty.call(exports, k5)) exports[k5] = getSSOTokenFilepath[k5]; - }); - } -}); - -// node_modules/.pnpm/@smithy+node-config-provider@4.3.13/node_modules/@smithy/node-config-provider/dist-cjs/index.js -var require_dist_cjs43 = __commonJS({ - "node_modules/.pnpm/@smithy+node-config-provider@4.3.13/node_modules/@smithy/node-config-provider/dist-cjs/index.js"(exports) { - "use strict"; - var propertyProvider = require_dist_cjs41(); - var sharedIniFileLoader = require_dist_cjs42(); - function getSelectorName(functionString) { - try { - const constants = new Set(Array.from(functionString.match(/([A-Z_]){3,}/g) ?? [])); - constants.delete("CONFIG"); - constants.delete("CONFIG_PREFIX_SEPARATOR"); - constants.delete("ENV"); - return [...constants].join(", "); - } catch (e5) { - return functionString; - } - } - var fromEnv = (envVarSelector, options) => async () => { - try { - const config3 = envVarSelector(process.env, options); - if (config3 === void 0) { - throw new Error(); - } - return config3; - } catch (e5) { - throw new propertyProvider.CredentialsProviderError(e5.message || `Not found in ENV: ${getSelectorName(envVarSelector.toString())}`, { logger: options?.logger }); - } - }; - var fromSharedConfigFiles = (configSelector, { preferredFile = "config", ...init2 } = {}) => async () => { - const profile = sharedIniFileLoader.getProfileName(init2); - const { configFile, credentialsFile } = await sharedIniFileLoader.loadSharedConfigFiles(init2); - const profileFromCredentials = credentialsFile[profile] || {}; - const profileFromConfig = configFile[profile] || {}; - const mergedProfile = preferredFile === "config" ? { ...profileFromCredentials, ...profileFromConfig } : { ...profileFromConfig, ...profileFromCredentials }; - try { - const cfgFile = preferredFile === "config" ? configFile : credentialsFile; - const configValue = configSelector(mergedProfile, cfgFile); - if (configValue === void 0) { - throw new Error(); - } - return configValue; - } catch (e5) { - throw new propertyProvider.CredentialsProviderError(e5.message || `Not found in config files w/ profile [${profile}]: ${getSelectorName(configSelector.toString())}`, { logger: init2.logger }); - } - }; - var isFunction3 = (func) => typeof func === "function"; - var fromStatic = (defaultValue) => isFunction3(defaultValue) ? async () => await defaultValue() : propertyProvider.fromStatic(defaultValue); - var loadConfig2 = ({ environmentVariableSelector, configFileSelector, default: defaultValue }, configuration = {}) => { - const { signingName, logger: logger4 } = configuration; - const envOptions = { signingName, logger: logger4 }; - return propertyProvider.memoize(propertyProvider.chain(fromEnv(environmentVariableSelector, envOptions), fromSharedConfigFiles(configFileSelector, configuration), fromStatic(defaultValue))); - }; - exports.loadConfig = loadConfig2; - } -}); - -// node_modules/.pnpm/@smithy+middleware-endpoint@4.4.29/node_modules/@smithy/middleware-endpoint/dist-cjs/adaptors/getEndpointUrlConfig.js -var require_getEndpointUrlConfig = __commonJS({ - "node_modules/.pnpm/@smithy+middleware-endpoint@4.4.29/node_modules/@smithy/middleware-endpoint/dist-cjs/adaptors/getEndpointUrlConfig.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.getEndpointUrlConfig = void 0; - var shared_ini_file_loader_1 = require_dist_cjs42(); - var ENV_ENDPOINT_URL = "AWS_ENDPOINT_URL"; - var CONFIG_ENDPOINT_URL = "endpoint_url"; - var getEndpointUrlConfig = (serviceId) => ({ - environmentVariableSelector: (env2) => { - const serviceSuffixParts = serviceId.split(" ").map((w5) => w5.toUpperCase()); - const serviceEndpointUrl = env2[[ENV_ENDPOINT_URL, ...serviceSuffixParts].join("_")]; - if (serviceEndpointUrl) - return serviceEndpointUrl; - const endpointUrl = env2[ENV_ENDPOINT_URL]; - if (endpointUrl) - return endpointUrl; - return void 0; - }, - configFileSelector: (profile, config3) => { - if (config3 && profile.services) { - const servicesSection = config3[["services", profile.services].join(shared_ini_file_loader_1.CONFIG_PREFIX_SEPARATOR)]; - if (servicesSection) { - const servicePrefixParts = serviceId.split(" ").map((w5) => w5.toLowerCase()); - const endpointUrl2 = servicesSection[[servicePrefixParts.join("_"), CONFIG_ENDPOINT_URL].join(shared_ini_file_loader_1.CONFIG_PREFIX_SEPARATOR)]; - if (endpointUrl2) - return endpointUrl2; - } - } - const endpointUrl = profile[CONFIG_ENDPOINT_URL]; - if (endpointUrl) - return endpointUrl; - return void 0; - }, - default: void 0 - }); - exports.getEndpointUrlConfig = getEndpointUrlConfig; - } -}); - -// node_modules/.pnpm/@smithy+middleware-endpoint@4.4.29/node_modules/@smithy/middleware-endpoint/dist-cjs/adaptors/getEndpointFromConfig.js -var require_getEndpointFromConfig = __commonJS({ - "node_modules/.pnpm/@smithy+middleware-endpoint@4.4.29/node_modules/@smithy/middleware-endpoint/dist-cjs/adaptors/getEndpointFromConfig.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.getEndpointFromConfig = void 0; - var node_config_provider_1 = require_dist_cjs43(); - var getEndpointUrlConfig_1 = require_getEndpointUrlConfig(); - var getEndpointFromConfig = async (serviceId) => (0, node_config_provider_1.loadConfig)((0, getEndpointUrlConfig_1.getEndpointUrlConfig)(serviceId ?? ""))(); - exports.getEndpointFromConfig = getEndpointFromConfig; - } -}); - -// node_modules/.pnpm/@smithy+middleware-serde@4.2.17/node_modules/@smithy/middleware-serde/dist-cjs/index.js -var require_dist_cjs44 = __commonJS({ - "node_modules/.pnpm/@smithy+middleware-serde@4.2.17/node_modules/@smithy/middleware-serde/dist-cjs/index.js"(exports) { - "use strict"; - var protocolHttp = require_dist_cjs2(); - var endpoints = (init_endpoints(), __toCommonJS(endpoints_exports)); - var deserializerMiddleware = (options, deserializer) => (next, context) => async (args) => { - const { response } = await next(args); - try { - const parsed = await deserializer(response, options); - return { - response, - output: parsed - }; - } catch (error50) { - Object.defineProperty(error50, "$response", { - value: response, - enumerable: false, - writable: false, - configurable: false - }); - if (!("$metadata" in error50)) { - const hint = `Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`; - try { - error50.message += "\n " + hint; - } catch (e5) { - if (!context.logger || context.logger?.constructor?.name === "NoOpLogger") { - console.warn(hint); - } else { - context.logger?.warn?.(hint); - } - } - if (typeof error50.$responseBodyText !== "undefined") { - if (error50.$response) { - error50.$response.body = error50.$responseBodyText; - } - } - try { - if (protocolHttp.HttpResponse.isInstance(response)) { - const { headers = {} } = response; - const headerEntries = Object.entries(headers); - error50.$metadata = { - httpStatusCode: response.statusCode, - requestId: findHeader2(/^x-[\w-]+-request-?id$/, headerEntries), - extendedRequestId: findHeader2(/^x-[\w-]+-id-2$/, headerEntries), - cfId: findHeader2(/^x-[\w-]+-cf-id$/, headerEntries) - }; - } - } catch (e5) { - } - } - throw error50; - } - }; - var findHeader2 = (pattern, headers) => { - return (headers.find(([k5]) => { - return k5.match(pattern); - }) || [void 0, void 0])[1]; - }; - var serializerMiddleware = (options, serializer) => (next, context) => async (args) => { - const endpointConfig = options; - const endpoint = context.endpointV2 ? async () => endpoints.toEndpointV1(context.endpointV2) : endpointConfig.endpoint; - if (!endpoint) { - throw new Error("No valid endpoint provider available."); - } - const request = await serializer(args.input, { ...options, endpoint }); - return next({ - ...args, - request - }); - }; - var deserializerMiddlewareOption2 = { - name: "deserializerMiddleware", - step: "deserialize", - tags: ["DESERIALIZER"], - override: true - }; - var serializerMiddlewareOption2 = { - name: "serializerMiddleware", - step: "serialize", - tags: ["SERIALIZER"], - override: true - }; - function getSerdePlugin(config3, serializer, deserializer) { - return { - applyToStack: (commandStack) => { - commandStack.add(deserializerMiddleware(config3, deserializer), deserializerMiddlewareOption2); - commandStack.add(serializerMiddleware(config3, serializer), serializerMiddlewareOption2); - } - }; - } - exports.deserializerMiddleware = deserializerMiddleware; - exports.deserializerMiddlewareOption = deserializerMiddlewareOption2; - exports.getSerdePlugin = getSerdePlugin; - exports.serializerMiddleware = serializerMiddleware; - exports.serializerMiddlewareOption = serializerMiddlewareOption2; - } -}); - -// node_modules/.pnpm/@smithy+middleware-endpoint@4.4.29/node_modules/@smithy/middleware-endpoint/dist-cjs/index.js -var require_dist_cjs45 = __commonJS({ - "node_modules/.pnpm/@smithy+middleware-endpoint@4.4.29/node_modules/@smithy/middleware-endpoint/dist-cjs/index.js"(exports) { - "use strict"; - var core = (init_dist_es(), __toCommonJS(dist_es_exports)); - var utilMiddleware = require_dist_cjs18(); - var getEndpointFromConfig = require_getEndpointFromConfig(); - var urlParser = require_dist_cjs25(); - var middlewareSerde = require_dist_cjs44(); - var resolveParamsForS3 = async (endpointParams) => { - const bucket = endpointParams?.Bucket || ""; - if (typeof endpointParams.Bucket === "string") { - endpointParams.Bucket = bucket.replace(/#/g, encodeURIComponent("#")).replace(/\?/g, encodeURIComponent("?")); - } - if (isArnBucketName(bucket)) { - if (endpointParams.ForcePathStyle === true) { - throw new Error("Path-style addressing cannot be used with ARN buckets"); - } - } else if (!isDnsCompatibleBucketName(bucket) || bucket.indexOf(".") !== -1 && !String(endpointParams.Endpoint).startsWith("http:") || bucket.toLowerCase() !== bucket || bucket.length < 3) { - endpointParams.ForcePathStyle = true; - } - if (endpointParams.DisableMultiRegionAccessPoints) { - endpointParams.disableMultiRegionAccessPoints = true; - endpointParams.DisableMRAP = true; - } - return endpointParams; - }; - var DOMAIN_PATTERN = /^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$/; - var IP_ADDRESS_PATTERN = /(\d+\.){3}\d+/; - var DOTS_PATTERN = /\.\./; - var isDnsCompatibleBucketName = (bucketName) => DOMAIN_PATTERN.test(bucketName) && !IP_ADDRESS_PATTERN.test(bucketName) && !DOTS_PATTERN.test(bucketName); - var isArnBucketName = (bucketName) => { - const [arn, partition, service, , , bucket] = bucketName.split(":"); - const isArn = arn === "arn" && bucketName.split(":").length >= 6; - const isValidArn = Boolean(isArn && partition && service && bucket); - if (isArn && !isValidArn) { - throw new Error(`Invalid ARN: ${bucketName} was an invalid ARN.`); - } - return isValidArn; - }; - var createConfigValueProvider = (configKey, canonicalEndpointParamKey, config3, isClientContextParam = false) => { - const configProvider = async () => { - let configValue; - if (isClientContextParam) { - const clientContextParams = config3.clientContextParams; - const nestedValue = clientContextParams?.[configKey]; - configValue = nestedValue ?? config3[configKey] ?? config3[canonicalEndpointParamKey]; - } else { - configValue = config3[configKey] ?? config3[canonicalEndpointParamKey]; - } - if (typeof configValue === "function") { - return configValue(); - } - return configValue; - }; - if (configKey === "credentialScope" || canonicalEndpointParamKey === "CredentialScope") { - return async () => { - const credentials = typeof config3.credentials === "function" ? await config3.credentials() : config3.credentials; - const configValue = credentials?.credentialScope ?? credentials?.CredentialScope; - return configValue; - }; - } - if (configKey === "accountId" || canonicalEndpointParamKey === "AccountId") { - return async () => { - const credentials = typeof config3.credentials === "function" ? await config3.credentials() : config3.credentials; - const configValue = credentials?.accountId ?? credentials?.AccountId; - return configValue; - }; - } - if (configKey === "endpoint" || canonicalEndpointParamKey === "endpoint") { - return async () => { - if (config3.isCustomEndpoint === false) { - return void 0; - } - const endpoint = await configProvider(); - if (endpoint && typeof endpoint === "object") { - if ("url" in endpoint) { - return endpoint.url.href; - } - if ("hostname" in endpoint) { - const { protocol, hostname: hostname3, port, path: path53 } = endpoint; - return `${protocol}//${hostname3}${port ? ":" + port : ""}${path53}`; - } - } - return endpoint; - }; - } - return configProvider; - }; - var toEndpointV12 = (endpoint) => { - if (typeof endpoint === "object") { - if ("url" in endpoint) { - const v1Endpoint = urlParser.parseUrl(endpoint.url); - if (endpoint.headers) { - v1Endpoint.headers = {}; - for (const [name, values2] of Object.entries(endpoint.headers)) { - v1Endpoint.headers[name.toLowerCase()] = values2.join(", "); - } - } - return v1Endpoint; - } - return endpoint; - } - return urlParser.parseUrl(endpoint); - }; - var getEndpointFromInstructions = async (commandInput, instructionsSupplier, clientConfig, context) => { - if (!clientConfig.isCustomEndpoint) { - let endpointFromConfig; - if (clientConfig.serviceConfiguredEndpoint) { - endpointFromConfig = await clientConfig.serviceConfiguredEndpoint(); - } else { - endpointFromConfig = await getEndpointFromConfig.getEndpointFromConfig(clientConfig.serviceId); - } - if (endpointFromConfig) { - clientConfig.endpoint = () => Promise.resolve(toEndpointV12(endpointFromConfig)); - clientConfig.isCustomEndpoint = true; - } - } - const endpointParams = await resolveParams(commandInput, instructionsSupplier, clientConfig); - if (typeof clientConfig.endpointProvider !== "function") { - throw new Error("config.endpointProvider is not set."); - } - const endpoint = clientConfig.endpointProvider(endpointParams, context); - if (clientConfig.isCustomEndpoint && clientConfig.endpoint) { - const customEndpoint = await clientConfig.endpoint(); - if (customEndpoint?.headers) { - endpoint.headers ??= {}; - for (const [name, value] of Object.entries(customEndpoint.headers)) { - endpoint.headers[name] = Array.isArray(value) ? value : [value]; - } - } - } - return endpoint; - }; - var resolveParams = async (commandInput, instructionsSupplier, clientConfig) => { - const endpointParams = {}; - const instructions = instructionsSupplier?.getEndpointParameterInstructions?.() || {}; - for (const [name, instruction] of Object.entries(instructions)) { - switch (instruction.type) { - case "staticContextParams": - endpointParams[name] = instruction.value; - break; - case "contextParams": - endpointParams[name] = commandInput[instruction.name]; - break; - case "clientContextParams": - case "builtInParams": - endpointParams[name] = await createConfigValueProvider(instruction.name, name, clientConfig, instruction.type !== "builtInParams")(); - break; - case "operationContextParams": - endpointParams[name] = instruction.get(commandInput); - break; - default: - throw new Error("Unrecognized endpoint parameter instruction: " + JSON.stringify(instruction)); - } - } - if (Object.keys(instructions).length === 0) { - Object.assign(endpointParams, clientConfig); - } - if (String(clientConfig.serviceId).toLowerCase() === "s3") { - await resolveParamsForS3(endpointParams); - } - return endpointParams; - }; - var endpointMiddleware = ({ config: config3, instructions }) => { - return (next, context) => async (args) => { - if (config3.isCustomEndpoint) { - core.setFeature(context, "ENDPOINT_OVERRIDE", "N"); - } - const endpoint = await getEndpointFromInstructions(args.input, { - getEndpointParameterInstructions() { - return instructions; - } - }, { ...config3 }, context); - context.endpointV2 = endpoint; - context.authSchemes = endpoint.properties?.authSchemes; - const authScheme = context.authSchemes?.[0]; - if (authScheme) { - context["signing_region"] = authScheme.signingRegion; - context["signing_service"] = authScheme.signingName; - const smithyContext = utilMiddleware.getSmithyContext(context); - const httpAuthOption = smithyContext?.selectedHttpAuthScheme?.httpAuthOption; - if (httpAuthOption) { - httpAuthOption.signingProperties = Object.assign(httpAuthOption.signingProperties || {}, { - signing_region: authScheme.signingRegion, - signingRegion: authScheme.signingRegion, - signing_service: authScheme.signingName, - signingName: authScheme.signingName, - signingRegionSet: authScheme.signingRegionSet - }, authScheme.properties); - } - } - return next({ - ...args - }); - }; - }; - var endpointMiddlewareOptions = { - step: "serialize", - tags: ["ENDPOINT_PARAMETERS", "ENDPOINT_V2", "ENDPOINT"], - name: "endpointV2Middleware", - override: true, - relation: "before", - toMiddleware: middlewareSerde.serializerMiddlewareOption.name - }; - var getEndpointPlugin6 = (config3, instructions) => ({ - applyToStack: (clientStack) => { - clientStack.addRelativeTo(endpointMiddleware({ - config: config3, - instructions - }), endpointMiddlewareOptions); - } - }); - var resolveEndpointConfig5 = (input) => { - const tls2 = input.tls ?? true; - const { endpoint, useDualstackEndpoint, useFipsEndpoint } = input; - const customEndpointProvider = endpoint != null ? async () => toEndpointV12(await utilMiddleware.normalizeProvider(endpoint)()) : void 0; - const isCustomEndpoint = !!endpoint; - const resolvedConfig = Object.assign(input, { - endpoint: customEndpointProvider, - tls: tls2, - isCustomEndpoint, - useDualstackEndpoint: utilMiddleware.normalizeProvider(useDualstackEndpoint ?? false), - useFipsEndpoint: utilMiddleware.normalizeProvider(useFipsEndpoint ?? false) - }); - let configuredEndpointPromise = void 0; - resolvedConfig.serviceConfiguredEndpoint = async () => { - if (input.serviceId && !configuredEndpointPromise) { - configuredEndpointPromise = getEndpointFromConfig.getEndpointFromConfig(input.serviceId); - } - return configuredEndpointPromise; - }; - return resolvedConfig; - }; - var resolveEndpointRequiredConfig = (input) => { - const { endpoint } = input; - if (endpoint === void 0) { - input.endpoint = async () => { - throw new Error("@smithy/middleware-endpoint: (default endpointRuleSet) endpoint is not set - you must configure an endpoint."); - }; - } - return input; - }; - exports.endpointMiddleware = endpointMiddleware; - exports.endpointMiddlewareOptions = endpointMiddlewareOptions; - exports.getEndpointFromInstructions = getEndpointFromInstructions; - exports.getEndpointPlugin = getEndpointPlugin6; - exports.resolveEndpointConfig = resolveEndpointConfig5; - exports.resolveEndpointRequiredConfig = resolveEndpointRequiredConfig; - exports.resolveParams = resolveParams; - exports.toEndpointV1 = toEndpointV12; - } -}); - -// node_modules/.pnpm/@smithy+middleware-retry@4.5.1/node_modules/@smithy/middleware-retry/dist-cjs/isStreamingPayload/isStreamingPayload.js -var require_isStreamingPayload = __commonJS({ - "node_modules/.pnpm/@smithy+middleware-retry@4.5.1/node_modules/@smithy/middleware-retry/dist-cjs/isStreamingPayload/isStreamingPayload.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.isStreamingPayload = void 0; - var stream_1 = __require("stream"); - var isStreamingPayload = (request) => request?.body instanceof stream_1.Readable || typeof ReadableStream !== "undefined" && request?.body instanceof ReadableStream; - exports.isStreamingPayload = isStreamingPayload; - } -}); - -// node_modules/.pnpm/@smithy+middleware-retry@4.5.1/node_modules/@smithy/middleware-retry/dist-cjs/index.js -var require_dist_cjs46 = __commonJS({ - "node_modules/.pnpm/@smithy+middleware-retry@4.5.1/node_modules/@smithy/middleware-retry/dist-cjs/index.js"(exports) { - "use strict"; - var utilRetry = require_dist_cjs36(); - var protocolHttp = require_dist_cjs2(); - var serviceErrorClassification = require_dist_cjs35(); - var uuid5 = require_dist_cjs26(); - var utilMiddleware = require_dist_cjs18(); - var smithyClient = require_dist_cjs27(); - var isStreamingPayload = require_isStreamingPayload(); - var serde = (init_serde(), __toCommonJS(serde_exports)); - var asSdkError = (error50) => { - if (error50 instanceof Error) - return error50; - if (error50 instanceof Object) - return Object.assign(new Error(), error50); - if (typeof error50 === "string") - return new Error(error50); - return new Error(`AWS SDK error wrapper for ${error50}`); - }; - var getDefaultRetryQuota = (initialRetryTokens, options) => { - const MAX_CAPACITY = initialRetryTokens; - const noRetryIncrement = utilRetry.NO_RETRY_INCREMENT; - const retryCost = utilRetry.RETRY_COST; - const timeoutRetryCost = utilRetry.TIMEOUT_RETRY_COST; - let availableCapacity = initialRetryTokens; - const getCapacityAmount = (error50) => error50.name === "TimeoutError" ? timeoutRetryCost : retryCost; - const hasRetryTokens = (error50) => getCapacityAmount(error50) <= availableCapacity; - const retrieveRetryTokens = (error50) => { - if (!hasRetryTokens(error50)) { - throw new Error("No retry token available"); - } - const capacityAmount = getCapacityAmount(error50); - availableCapacity -= capacityAmount; - return capacityAmount; - }; - const releaseRetryTokens = (capacityReleaseAmount) => { - availableCapacity += capacityReleaseAmount ?? noRetryIncrement; - availableCapacity = Math.min(availableCapacity, MAX_CAPACITY); - }; - return Object.freeze({ - hasRetryTokens, - retrieveRetryTokens, - releaseRetryTokens - }); - }; - var defaultDelayDecider = (delayBase, attempts) => Math.floor(Math.min(utilRetry.MAXIMUM_RETRY_DELAY, Math.random() * 2 ** attempts * delayBase)); - var defaultRetryDecider = (error50) => { - if (!error50) { - return false; - } - return serviceErrorClassification.isRetryableByTrait(error50) || serviceErrorClassification.isClockSkewError(error50) || serviceErrorClassification.isThrottlingError(error50) || serviceErrorClassification.isTransientError(error50); - }; - var StandardRetryStrategy = class { - maxAttemptsProvider; - retryDecider; - delayDecider; - retryQuota; - mode = utilRetry.RETRY_MODES.STANDARD; - constructor(maxAttemptsProvider, options) { - this.maxAttemptsProvider = maxAttemptsProvider; - this.retryDecider = options?.retryDecider ?? defaultRetryDecider; - this.delayDecider = options?.delayDecider ?? defaultDelayDecider; - this.retryQuota = options?.retryQuota ?? getDefaultRetryQuota(utilRetry.INITIAL_RETRY_TOKENS); - } - shouldRetry(error50, attempts, maxAttempts) { - return attempts < maxAttempts && this.retryDecider(error50) && this.retryQuota.hasRetryTokens(error50); - } - async getMaxAttempts() { - let maxAttempts; - try { - maxAttempts = await this.maxAttemptsProvider(); - } catch (error50) { - maxAttempts = utilRetry.DEFAULT_MAX_ATTEMPTS; - } - return maxAttempts; - } - async retry(next, args, options) { - let retryTokenAmount; - let attempts = 0; - let totalDelay = 0; - const maxAttempts = await this.getMaxAttempts(); - const { request } = args; - if (protocolHttp.HttpRequest.isInstance(request)) { - request.headers[utilRetry.INVOCATION_ID_HEADER] = uuid5.v4(); - } - while (true) { - try { - if (protocolHttp.HttpRequest.isInstance(request)) { - request.headers[utilRetry.REQUEST_HEADER] = `attempt=${attempts + 1}; max=${maxAttempts}`; - } - if (options?.beforeRequest) { - await options.beforeRequest(); - } - const { response, output } = await next(args); - if (options?.afterRequest) { - options.afterRequest(response); - } - this.retryQuota.releaseRetryTokens(retryTokenAmount); - output.$metadata.attempts = attempts + 1; - output.$metadata.totalRetryDelay = totalDelay; - return { response, output }; - } catch (e5) { - const err = asSdkError(e5); - attempts++; - if (this.shouldRetry(err, attempts, maxAttempts)) { - retryTokenAmount = this.retryQuota.retrieveRetryTokens(err); - const delayFromDecider = this.delayDecider(serviceErrorClassification.isThrottlingError(err) ? utilRetry.THROTTLING_RETRY_DELAY_BASE : utilRetry.DEFAULT_RETRY_DELAY_BASE, attempts); - const delayFromResponse = getDelayFromRetryAfterHeader(err.$response); - const delay3 = Math.max(delayFromResponse || 0, delayFromDecider); - totalDelay += delay3; - await new Promise((resolve4) => setTimeout(resolve4, delay3)); - continue; - } - if (!err.$metadata) { - err.$metadata = {}; - } - err.$metadata.attempts = attempts; - err.$metadata.totalRetryDelay = totalDelay; - throw err; - } - } - } - }; - var getDelayFromRetryAfterHeader = (response) => { - if (!protocolHttp.HttpResponse.isInstance(response)) - return; - const retryAfterHeaderName = Object.keys(response.headers).find((key) => key.toLowerCase() === "retry-after"); - if (!retryAfterHeaderName) - return; - const retryAfter = response.headers[retryAfterHeaderName]; - const retryAfterSeconds = Number(retryAfter); - if (!Number.isNaN(retryAfterSeconds)) - return retryAfterSeconds * 1e3; - const retryAfterDate = new Date(retryAfter); - return retryAfterDate.getTime() - Date.now(); - }; - var AdaptiveRetryStrategy = class extends StandardRetryStrategy { - rateLimiter; - constructor(maxAttemptsProvider, options) { - const { rateLimiter, ...superOptions } = options ?? {}; - super(maxAttemptsProvider, superOptions); - this.rateLimiter = rateLimiter ?? new utilRetry.DefaultRateLimiter(); - this.mode = utilRetry.RETRY_MODES.ADAPTIVE; - } - async retry(next, args) { - return super.retry(next, args, { - beforeRequest: async () => { - return this.rateLimiter.getSendToken(); - }, - afterRequest: (response) => { - this.rateLimiter.updateClientSendingRate(response); - } - }); - } - }; - var ENV_MAX_ATTEMPTS = "AWS_MAX_ATTEMPTS"; - var CONFIG_MAX_ATTEMPTS = "max_attempts"; - var NODE_MAX_ATTEMPT_CONFIG_OPTIONS5 = { - environmentVariableSelector: (env2) => { - const value = env2[ENV_MAX_ATTEMPTS]; - if (!value) - return void 0; - const maxAttempt = parseInt(value); - if (Number.isNaN(maxAttempt)) { - throw new Error(`Environment variable ${ENV_MAX_ATTEMPTS} mast be a number, got "${value}"`); - } - return maxAttempt; - }, - configFileSelector: (profile) => { - const value = profile[CONFIG_MAX_ATTEMPTS]; - if (!value) - return void 0; - const maxAttempt = parseInt(value); - if (Number.isNaN(maxAttempt)) { - throw new Error(`Shared config file entry ${CONFIG_MAX_ATTEMPTS} mast be a number, got "${value}"`); - } - return maxAttempt; - }, - default: utilRetry.DEFAULT_MAX_ATTEMPTS - }; - var resolveRetryConfig5 = (input) => { - const { retryStrategy, retryMode } = input; - const maxAttempts = utilMiddleware.normalizeProvider(input.maxAttempts ?? utilRetry.DEFAULT_MAX_ATTEMPTS); - let controller = retryStrategy ? Promise.resolve(retryStrategy) : void 0; - const getDefault = async () => await utilMiddleware.normalizeProvider(retryMode)() === utilRetry.RETRY_MODES.ADAPTIVE ? new utilRetry.AdaptiveRetryStrategy(maxAttempts) : new utilRetry.StandardRetryStrategy(maxAttempts); - return Object.assign(input, { - maxAttempts, - retryStrategy: () => controller ??= getDefault() - }); - }; - var ENV_RETRY_MODE = "AWS_RETRY_MODE"; - var CONFIG_RETRY_MODE = "retry_mode"; - var NODE_RETRY_MODE_CONFIG_OPTIONS5 = { - environmentVariableSelector: (env2) => env2[ENV_RETRY_MODE], - configFileSelector: (profile) => profile[CONFIG_RETRY_MODE], - default: utilRetry.DEFAULT_RETRY_MODE - }; - var omitRetryHeadersMiddleware = () => (next) => async (args) => { - const { request } = args; - if (protocolHttp.HttpRequest.isInstance(request)) { - delete request.headers[utilRetry.INVOCATION_ID_HEADER]; - delete request.headers[utilRetry.REQUEST_HEADER]; - } - return next(args); - }; - var omitRetryHeadersMiddlewareOptions = { - name: "omitRetryHeadersMiddleware", - tags: ["RETRY", "HEADERS", "OMIT_RETRY_HEADERS"], - relation: "before", - toMiddleware: "awsAuthMiddleware", - override: true - }; - var getOmitRetryHeadersPlugin = (options) => ({ - applyToStack: (clientStack) => { - clientStack.addRelativeTo(omitRetryHeadersMiddleware(), omitRetryHeadersMiddlewareOptions); - } - }); - function parseRetryAfterHeader(response, logger4) { - if (!protocolHttp.HttpResponse.isInstance(response)) { - return; - } - for (const header of Object.keys(response.headers)) { - const h5 = header.toLowerCase(); - if (h5 === "retry-after") { - const retryAfter = response.headers[header]; - let retryAfterSeconds = NaN; - if (retryAfter.endsWith("GMT")) { - try { - const date7 = serde.parseRfc7231DateTime(retryAfter); - retryAfterSeconds = (date7.getTime() - Date.now()) / 1e3; - } catch (e5) { - logger4?.trace?.("Failed to parse retry-after header"); - logger4?.trace?.(e5); - } - } else if (retryAfter.match(/ GMT, ((\d+)|(\d+\.\d+))$/)) { - retryAfterSeconds = Number(retryAfter.match(/ GMT, ([\d.]+)$/)?.[1]); - } else if (retryAfter.match(/^((\d+)|(\d+\.\d+))$/)) { - retryAfterSeconds = Number(retryAfter); - } else if (Date.parse(retryAfter) >= Date.now()) { - retryAfterSeconds = (Date.parse(retryAfter) - Date.now()) / 1e3; - } - if (isNaN(retryAfterSeconds)) { - return; - } - return new Date(Date.now() + retryAfterSeconds * 1e3); - } else if (h5 === "x-amz-retry-after") { - const v5 = response.headers[header]; - const backoffMilliseconds = Number(v5); - if (isNaN(backoffMilliseconds)) { - logger4?.trace?.(`Failed to parse x-amz-retry-after=${v5}`); - return; - } - return new Date(Date.now() + backoffMilliseconds); - } - } - } - function getRetryAfterHint(response, logger4) { - return parseRetryAfterHeader(response, logger4); - } - var retryMiddleware = (options) => (next, context) => async (args) => { - let retryStrategy = await options.retryStrategy(); - const maxAttempts = await options.maxAttempts(); - if (isRetryStrategyV2(retryStrategy)) { - retryStrategy = retryStrategy; - let retryToken = await retryStrategy.acquireInitialRetryToken((context["partition_id"] ?? "") + (context.__retryLongPoll ? ":longpoll" : "")); - let lastError = new Error(); - let attempts = 0; - let totalRetryDelay = 0; - const { request } = args; - const isRequest2 = protocolHttp.HttpRequest.isInstance(request); - if (isRequest2) { - request.headers[utilRetry.INVOCATION_ID_HEADER] = uuid5.v4(); - } - while (true) { - try { - if (isRequest2) { - request.headers[utilRetry.REQUEST_HEADER] = `attempt=${attempts + 1}; max=${maxAttempts}`; - } - const { response, output } = await next(args); - retryStrategy.recordSuccess(retryToken); - output.$metadata.attempts = attempts + 1; - output.$metadata.totalRetryDelay = totalRetryDelay; - return { response, output }; - } catch (e5) { - const retryErrorInfo = getRetryErrorInfo(e5, options.logger); - lastError = asSdkError(e5); - if (isRequest2 && isStreamingPayload.isStreamingPayload(request)) { - (context.logger instanceof smithyClient.NoOpLogger ? console : context.logger)?.warn("An error was encountered in a non-retryable streaming request."); - throw lastError; - } - try { - retryToken = await retryStrategy.refreshRetryTokenForRetry(retryToken, retryErrorInfo); - } catch (refreshError) { - if (typeof refreshError.$backoff === "number") { - await cooldown(refreshError.$backoff); - } - if (!lastError.$metadata) { - lastError.$metadata = {}; - } - lastError.$metadata.attempts = attempts + 1; - lastError.$metadata.totalRetryDelay = totalRetryDelay; - throw lastError; - } - attempts = retryToken.getRetryCount(); - const delay3 = retryToken.getRetryDelay(); - totalRetryDelay += delay3; - await cooldown(delay3); - } - } - } else { - retryStrategy = retryStrategy; - if (retryStrategy?.mode) { - context.userAgent = [...context.userAgent || [], ["cfg/retry-mode", retryStrategy.mode]]; - } - return retryStrategy.retry(next, args); - } - }; - var cooldown = (ms) => new Promise((resolve4) => setTimeout(resolve4, ms)); - var isRetryStrategyV2 = (retryStrategy) => typeof retryStrategy.acquireInitialRetryToken !== "undefined" && typeof retryStrategy.refreshRetryTokenForRetry !== "undefined" && typeof retryStrategy.recordSuccess !== "undefined"; - var getRetryErrorInfo = (error50, logger4) => { - const errorInfo = { - error: error50, - errorType: getRetryErrorType(error50) - }; - const retryAfterHint = parseRetryAfterHeader(error50.$response, logger4); - if (retryAfterHint) { - errorInfo.retryAfterHint = retryAfterHint; - } - return errorInfo; - }; - var getRetryErrorType = (error50) => { - if (serviceErrorClassification.isThrottlingError(error50)) - return "THROTTLING"; - if (serviceErrorClassification.isTransientError(error50)) - return "TRANSIENT"; - if (serviceErrorClassification.isServerError(error50)) - return "SERVER_ERROR"; - return "CLIENT_ERROR"; - }; - var retryMiddlewareOptions = { - name: "retryMiddleware", - tags: ["RETRY"], - step: "finalizeRequest", - priority: "high", - override: true - }; - var getRetryPlugin5 = (options) => ({ - applyToStack: (clientStack) => { - clientStack.add(retryMiddleware(options), retryMiddlewareOptions); - } - }); - exports.AdaptiveRetryStrategy = AdaptiveRetryStrategy; - exports.CONFIG_MAX_ATTEMPTS = CONFIG_MAX_ATTEMPTS; - exports.CONFIG_RETRY_MODE = CONFIG_RETRY_MODE; - exports.ENV_MAX_ATTEMPTS = ENV_MAX_ATTEMPTS; - exports.ENV_RETRY_MODE = ENV_RETRY_MODE; - exports.NODE_MAX_ATTEMPT_CONFIG_OPTIONS = NODE_MAX_ATTEMPT_CONFIG_OPTIONS5; - exports.NODE_RETRY_MODE_CONFIG_OPTIONS = NODE_RETRY_MODE_CONFIG_OPTIONS5; - exports.StandardRetryStrategy = StandardRetryStrategy; - exports.defaultDelayDecider = defaultDelayDecider; - exports.defaultRetryDecider = defaultRetryDecider; - exports.getOmitRetryHeadersPlugin = getOmitRetryHeadersPlugin; - exports.getRetryAfterHint = getRetryAfterHint; - exports.getRetryPlugin = getRetryPlugin5; - exports.omitRetryHeadersMiddleware = omitRetryHeadersMiddleware; - exports.omitRetryHeadersMiddlewareOptions = omitRetryHeadersMiddlewareOptions; - exports.resolveRetryConfig = resolveRetryConfig5; - exports.retryMiddleware = retryMiddleware; - exports.retryMiddlewareOptions = retryMiddlewareOptions; - } -}); - -// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getDateHeader.js -var import_protocol_http9, getDateHeader; -var init_getDateHeader = __esm({ - "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getDateHeader.js"() { - import_protocol_http9 = __toESM(require_dist_cjs2()); - getDateHeader = (response) => import_protocol_http9.HttpResponse.isInstance(response) ? response.headers?.date ?? response.headers?.Date : void 0; - } -}); - -// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getSkewCorrectedDate.js -var getSkewCorrectedDate; -var init_getSkewCorrectedDate = __esm({ - "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getSkewCorrectedDate.js"() { - getSkewCorrectedDate = (systemClockOffset) => new Date(Date.now() + systemClockOffset); - } -}); - -// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/isClockSkewed.js -var isClockSkewed; -var init_isClockSkewed = __esm({ - "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/isClockSkewed.js"() { - init_getSkewCorrectedDate(); - isClockSkewed = (clockTime, systemClockOffset) => Math.abs(getSkewCorrectedDate(systemClockOffset).getTime() - clockTime) >= 3e5; - } -}); - -// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getUpdatedSystemClockOffset.js -var getUpdatedSystemClockOffset; -var init_getUpdatedSystemClockOffset = __esm({ - "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getUpdatedSystemClockOffset.js"() { - init_isClockSkewed(); - getUpdatedSystemClockOffset = (clockTime, currentSystemClockOffset) => { - const clockTimeInMs = Date.parse(clockTime); - if (isClockSkewed(clockTimeInMs, currentSystemClockOffset)) { - return clockTimeInMs - Date.now(); - } - return currentSystemClockOffset; - }; - } -}); - -// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/index.js -var init_utils5 = __esm({ - "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/index.js"() { - init_getDateHeader(); - init_getSkewCorrectedDate(); - init_getUpdatedSystemClockOffset(); - } -}); - -// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/AwsSdkSigV4Signer.js -var import_protocol_http10, throwSigningPropertyError, validateSigningProperties, AwsSdkSigV4Signer, AWSSDKSigV4Signer; -var init_AwsSdkSigV4Signer = __esm({ - "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/AwsSdkSigV4Signer.js"() { - import_protocol_http10 = __toESM(require_dist_cjs2()); - init_utils5(); - throwSigningPropertyError = (name, property) => { - if (!property) { - throw new Error(`Property \`${name}\` is not resolved for AWS SDK SigV4Auth`); - } - return property; - }; - validateSigningProperties = async (signingProperties) => { - const context = throwSigningPropertyError("context", signingProperties.context); - const config3 = throwSigningPropertyError("config", signingProperties.config); - const authScheme = context.endpointV2?.properties?.authSchemes?.[0]; - const signerFunction = throwSigningPropertyError("signer", config3.signer); - const signer = await signerFunction(authScheme); - const signingRegion = signingProperties?.signingRegion; - const signingRegionSet = signingProperties?.signingRegionSet; - const signingName = signingProperties?.signingName; - return { - config: config3, - signer, - signingRegion, - signingRegionSet, - signingName - }; - }; - AwsSdkSigV4Signer = class { - async sign(httpRequest2, identity, signingProperties) { - if (!import_protocol_http10.HttpRequest.isInstance(httpRequest2)) { - throw new Error("The request is not an instance of `HttpRequest` and cannot be signed"); - } - const validatedProps = await validateSigningProperties(signingProperties); - const { config: config3, signer } = validatedProps; - let { signingRegion, signingName } = validatedProps; - const handlerExecutionContext = signingProperties.context; - if (handlerExecutionContext?.authSchemes?.length ?? 0 > 1) { - const [first, second] = handlerExecutionContext.authSchemes; - if (first?.name === "sigv4a" && second?.name === "sigv4") { - signingRegion = second?.signingRegion ?? signingRegion; - signingName = second?.signingName ?? signingName; - } - } - const signedRequest = await signer.sign(httpRequest2, { - signingDate: getSkewCorrectedDate(config3.systemClockOffset), - signingRegion, - signingService: signingName - }); - return signedRequest; - } - errorHandler(signingProperties) { - return (error50) => { - const serverTime = error50.ServerTime ?? getDateHeader(error50.$response); - if (serverTime) { - const config3 = throwSigningPropertyError("config", signingProperties.config); - const initialSystemClockOffset = config3.systemClockOffset; - config3.systemClockOffset = getUpdatedSystemClockOffset(serverTime, config3.systemClockOffset); - const clockSkewCorrected = config3.systemClockOffset !== initialSystemClockOffset; - if (clockSkewCorrected && error50.$metadata) { - error50.$metadata.clockSkewCorrected = true; - } - } - throw error50; - }; - } - successHandler(httpResponse, signingProperties) { - const dateHeader = getDateHeader(httpResponse); - if (dateHeader) { - const config3 = throwSigningPropertyError("config", signingProperties.config); - config3.systemClockOffset = getUpdatedSystemClockOffset(dateHeader, config3.systemClockOffset); - } - } - }; - AWSSDKSigV4Signer = AwsSdkSigV4Signer; - } -}); - -// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/AwsSdkSigV4ASigner.js -var import_protocol_http11, AwsSdkSigV4ASigner; -var init_AwsSdkSigV4ASigner = __esm({ - "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/AwsSdkSigV4ASigner.js"() { - import_protocol_http11 = __toESM(require_dist_cjs2()); - init_utils5(); - init_AwsSdkSigV4Signer(); - AwsSdkSigV4ASigner = class extends AwsSdkSigV4Signer { - async sign(httpRequest2, identity, signingProperties) { - if (!import_protocol_http11.HttpRequest.isInstance(httpRequest2)) { - throw new Error("The request is not an instance of `HttpRequest` and cannot be signed"); - } - const { config: config3, signer, signingRegion, signingRegionSet, signingName } = await validateSigningProperties(signingProperties); - const configResolvedSigningRegionSet = await config3.sigv4aSigningRegionSet?.(); - const multiRegionOverride = (configResolvedSigningRegionSet ?? signingRegionSet ?? [signingRegion]).join(","); - const signedRequest = await signer.sign(httpRequest2, { - signingDate: getSkewCorrectedDate(config3.systemClockOffset), - signingRegion: multiRegionOverride, - signingService: signingName - }); - return signedRequest; - } - }; - } -}); - -// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getArrayForCommaSeparatedString.js -var getArrayForCommaSeparatedString; -var init_getArrayForCommaSeparatedString = __esm({ - "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getArrayForCommaSeparatedString.js"() { - getArrayForCommaSeparatedString = (str) => typeof str === "string" && str.length > 0 ? str.split(",").map((item) => item.trim()) : []; - } -}); - -// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getBearerTokenEnvKey.js -var getBearerTokenEnvKey; -var init_getBearerTokenEnvKey = __esm({ - "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getBearerTokenEnvKey.js"() { - getBearerTokenEnvKey = (signingName) => `AWS_BEARER_TOKEN_${signingName.replace(/[\s-]/g, "_").toUpperCase()}`; - } -}); - -// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/NODE_AUTH_SCHEME_PREFERENCE_OPTIONS.js -var NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY, NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY, NODE_AUTH_SCHEME_PREFERENCE_OPTIONS; -var init_NODE_AUTH_SCHEME_PREFERENCE_OPTIONS = __esm({ - "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/NODE_AUTH_SCHEME_PREFERENCE_OPTIONS.js"() { - init_getArrayForCommaSeparatedString(); - init_getBearerTokenEnvKey(); - NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY = "AWS_AUTH_SCHEME_PREFERENCE"; - NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY = "auth_scheme_preference"; - NODE_AUTH_SCHEME_PREFERENCE_OPTIONS = { - environmentVariableSelector: (env2, options) => { - if (options?.signingName) { - const bearerTokenKey = getBearerTokenEnvKey(options.signingName); - if (bearerTokenKey in env2) - return ["httpBearerAuth"]; - } - if (!(NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY in env2)) - return void 0; - return getArrayForCommaSeparatedString(env2[NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY]); - }, - configFileSelector: (profile) => { - if (!(NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY in profile)) - return void 0; - return getArrayForCommaSeparatedString(profile[NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY]); - }, - default: [] - }; - } -}); - -// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/resolveAwsSdkSigV4AConfig.js -var import_property_provider, resolveAwsSdkSigV4AConfig, NODE_SIGV4A_CONFIG_OPTIONS; -var init_resolveAwsSdkSigV4AConfig = __esm({ - "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/resolveAwsSdkSigV4AConfig.js"() { - init_dist_es(); - import_property_provider = __toESM(require_dist_cjs41()); - resolveAwsSdkSigV4AConfig = (config3) => { - config3.sigv4aSigningRegionSet = normalizeProvider(config3.sigv4aSigningRegionSet); - return config3; - }; - NODE_SIGV4A_CONFIG_OPTIONS = { - environmentVariableSelector(env2) { - if (env2.AWS_SIGV4A_SIGNING_REGION_SET) { - return env2.AWS_SIGV4A_SIGNING_REGION_SET.split(",").map((_) => _.trim()); - } - throw new import_property_provider.ProviderError("AWS_SIGV4A_SIGNING_REGION_SET not set in env.", { - tryNextLink: true - }); - }, - configFileSelector(profile) { - if (profile.sigv4a_signing_region_set) { - return (profile.sigv4a_signing_region_set ?? "").split(",").map((_) => _.trim()); - } - throw new import_property_provider.ProviderError("sigv4a_signing_region_set not set in profile.", { - tryNextLink: true - }); - }, - default: void 0 - }; - } -}); - -// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/resolveAwsSdkSigV4Config.js -function normalizeCredentialProvider(config3, { credentials, credentialDefaultProvider }) { - let credentialsProvider; - if (credentials) { - if (!credentials?.memoized) { - credentialsProvider = memoizeIdentityProvider(credentials, isIdentityExpired, doesIdentityRequireRefresh); - } else { - credentialsProvider = credentials; - } - } else { - if (credentialDefaultProvider) { - credentialsProvider = normalizeProvider(credentialDefaultProvider(Object.assign({}, config3, { - parentClientConfig: config3 - }))); - } else { - credentialsProvider = async () => { - throw new Error("@aws-sdk/core::resolveAwsSdkSigV4Config - `credentials` not provided and no credentialDefaultProvider was configured."); - }; - } - } - credentialsProvider.memoized = true; - return credentialsProvider; -} -function bindCallerConfig(config3, credentialsProvider) { - if (credentialsProvider.configBound) { - return credentialsProvider; - } - const fn = async (options) => credentialsProvider({ ...options, callerClientConfig: config3 }); - fn.memoized = credentialsProvider.memoized; - fn.configBound = true; - return fn; -} -var import_signature_v4, resolveAwsSdkSigV4Config, resolveAWSSDKSigV4Config; -var init_resolveAwsSdkSigV4Config = __esm({ - "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/resolveAwsSdkSigV4Config.js"() { - init_client2(); - init_dist_es(); - import_signature_v4 = __toESM(require_dist_cjs30()); - resolveAwsSdkSigV4Config = (config3) => { - let inputCredentials = config3.credentials; - let isUserSupplied = !!config3.credentials; - let resolvedCredentials = void 0; - Object.defineProperty(config3, "credentials", { - set(credentials) { - if (credentials && credentials !== inputCredentials && credentials !== resolvedCredentials) { - isUserSupplied = true; - } - inputCredentials = credentials; - const memoizedProvider = normalizeCredentialProvider(config3, { - credentials: inputCredentials, - credentialDefaultProvider: config3.credentialDefaultProvider - }); - const boundProvider = bindCallerConfig(config3, memoizedProvider); - if (isUserSupplied && !boundProvider.attributed) { - const isCredentialObject = typeof inputCredentials === "object" && inputCredentials !== null; - resolvedCredentials = async (options) => { - const creds = await boundProvider(options); - const attributedCreds = creds; - if (isCredentialObject && (!attributedCreds.$source || Object.keys(attributedCreds.$source).length === 0)) { - return setCredentialFeature(attributedCreds, "CREDENTIALS_CODE", "e"); - } - return attributedCreds; - }; - resolvedCredentials.memoized = boundProvider.memoized; - resolvedCredentials.configBound = boundProvider.configBound; - resolvedCredentials.attributed = true; - } else { - resolvedCredentials = boundProvider; - } - }, - get() { - return resolvedCredentials; - }, - enumerable: true, - configurable: true - }); - config3.credentials = inputCredentials; - const { signingEscapePath = true, systemClockOffset = config3.systemClockOffset || 0, sha256: sha2563 } = config3; - let signer; - if (config3.signer) { - signer = normalizeProvider(config3.signer); - } else if (config3.regionInfoProvider) { - signer = () => normalizeProvider(config3.region)().then(async (region) => [ - await config3.regionInfoProvider(region, { - useFipsEndpoint: await config3.useFipsEndpoint(), - useDualstackEndpoint: await config3.useDualstackEndpoint() - }) || {}, - region - ]).then(([regionInfo, region]) => { - const { signingRegion, signingService } = regionInfo; - config3.signingRegion = config3.signingRegion || signingRegion || region; - config3.signingName = config3.signingName || signingService || config3.serviceId; - const params = { - ...config3, - credentials: config3.credentials, - region: config3.signingRegion, - service: config3.signingName, - sha256: sha2563, - uriEscapePath: signingEscapePath - }; - const SignerCtor = config3.signerConstructor || import_signature_v4.SignatureV4; - return new SignerCtor(params); - }); - } else { - signer = async (authScheme) => { - authScheme = Object.assign({}, { - name: "sigv4", - signingName: config3.signingName || config3.defaultSigningName, - signingRegion: await normalizeProvider(config3.region)(), - properties: {} - }, authScheme); - const signingRegion = authScheme.signingRegion; - const signingService = authScheme.signingName; - config3.signingRegion = config3.signingRegion || signingRegion; - config3.signingName = config3.signingName || signingService || config3.serviceId; - const params = { - ...config3, - credentials: config3.credentials, - region: config3.signingRegion, - service: config3.signingName, - sha256: sha2563, - uriEscapePath: signingEscapePath - }; - const SignerCtor = config3.signerConstructor || import_signature_v4.SignatureV4; - return new SignerCtor(params); - }; - } - const resolvedConfig = Object.assign(config3, { - systemClockOffset, - signingEscapePath, - signer - }); - return resolvedConfig; - }; - resolveAWSSDKSigV4Config = resolveAwsSdkSigV4Config; - } -}); - -// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/index.js -var init_aws_sdk = __esm({ - "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/index.js"() { - init_AwsSdkSigV4Signer(); - init_AwsSdkSigV4ASigner(); - init_NODE_AUTH_SCHEME_PREFERENCE_OPTIONS(); - init_resolveAwsSdkSigV4AConfig(); - init_resolveAwsSdkSigV4Config(); - } -}); - -// node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/index.js -var httpAuthSchemes_exports = {}; -__export(httpAuthSchemes_exports, { - AWSSDKSigV4Signer: () => AWSSDKSigV4Signer, - AwsSdkSigV4ASigner: () => AwsSdkSigV4ASigner, - AwsSdkSigV4Signer: () => AwsSdkSigV4Signer, - NODE_AUTH_SCHEME_PREFERENCE_OPTIONS: () => NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, - NODE_SIGV4A_CONFIG_OPTIONS: () => NODE_SIGV4A_CONFIG_OPTIONS, - getBearerTokenEnvKey: () => getBearerTokenEnvKey, - resolveAWSSDKSigV4Config: () => resolveAWSSDKSigV4Config, - resolveAwsSdkSigV4AConfig: () => resolveAwsSdkSigV4AConfig, - resolveAwsSdkSigV4Config: () => resolveAwsSdkSigV4Config, - validateSigningProperties: () => validateSigningProperties -}); -var init_httpAuthSchemes2 = __esm({ - "node_modules/.pnpm/@aws-sdk+core@3.973.27/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/index.js"() { - init_aws_sdk(); - init_getBearerTokenEnvKey(); - } -}); - -// node_modules/.pnpm/@aws-sdk+signature-v4-multi-region@3.996.16/node_modules/@aws-sdk/signature-v4-multi-region/dist-cjs/index.js -var require_dist_cjs47 = __commonJS({ - "node_modules/.pnpm/@aws-sdk+signature-v4-multi-region@3.996.16/node_modules/@aws-sdk/signature-v4-multi-region/dist-cjs/index.js"(exports) { - "use strict"; - var middlewareSdkS3 = require_dist_cjs32(); - var signatureV4 = require_dist_cjs30(); - var signatureV4CrtContainer = { - CrtSignerV4: null - }; - var SignatureV4MultiRegion = class { - sigv4aSigner; - sigv4Signer; - signerOptions; - static sigv4aDependency() { - if (typeof signatureV4CrtContainer.CrtSignerV4 === "function") { - return "crt"; - } else if (typeof signatureV4.signatureV4aContainer.SignatureV4a === "function") { - return "js"; - } - return "none"; - } - constructor(options) { - this.sigv4Signer = new middlewareSdkS3.SignatureV4S3Express(options); - this.signerOptions = options; - } - async sign(requestToSign, options = {}) { - if (options.signingRegion === "*") { - return this.getSigv4aSigner().sign(requestToSign, options); - } - return this.sigv4Signer.sign(requestToSign, options); - } - async signWithCredentials(requestToSign, credentials, options = {}) { - if (options.signingRegion === "*") { - const signer = this.getSigv4aSigner(); - const CrtSignerV4 = signatureV4CrtContainer.CrtSignerV4; - if (CrtSignerV4 && signer instanceof CrtSignerV4) { - return signer.signWithCredentials(requestToSign, credentials, options); - } else { - throw new Error(`signWithCredentials with signingRegion '*' is only supported when using the CRT dependency @aws-sdk/signature-v4-crt. Please check whether you have installed the "@aws-sdk/signature-v4-crt" package explicitly. You must also register the package by calling [require("@aws-sdk/signature-v4-crt");] or an ESM equivalent such as [import "@aws-sdk/signature-v4-crt";]. For more information please go to https://github.com/aws/aws-sdk-js-v3#functionality-requiring-aws-common-runtime-crt`); - } - } - return this.sigv4Signer.signWithCredentials(requestToSign, credentials, options); - } - async presign(originalRequest, options = {}) { - if (options.signingRegion === "*") { - const signer = this.getSigv4aSigner(); - const CrtSignerV4 = signatureV4CrtContainer.CrtSignerV4; - if (CrtSignerV4 && signer instanceof CrtSignerV4) { - return signer.presign(originalRequest, options); - } else { - throw new Error(`presign with signingRegion '*' is only supported when using the CRT dependency @aws-sdk/signature-v4-crt. Please check whether you have installed the "@aws-sdk/signature-v4-crt" package explicitly. You must also register the package by calling [require("@aws-sdk/signature-v4-crt");] or an ESM equivalent such as [import "@aws-sdk/signature-v4-crt";]. For more information please go to https://github.com/aws/aws-sdk-js-v3#functionality-requiring-aws-common-runtime-crt`); - } - } - return this.sigv4Signer.presign(originalRequest, options); - } - async presignWithCredentials(originalRequest, credentials, options = {}) { - if (options.signingRegion === "*") { - throw new Error("Method presignWithCredentials is not supported for [signingRegion=*]."); - } - return this.sigv4Signer.presignWithCredentials(originalRequest, credentials, options); - } - getSigv4aSigner() { - if (!this.sigv4aSigner) { - const CrtSignerV4 = signatureV4CrtContainer.CrtSignerV4; - const JsSigV4aSigner = signatureV4.signatureV4aContainer.SignatureV4a; - if (this.signerOptions.runtime === "node") { - if (!CrtSignerV4 && !JsSigV4aSigner) { - throw new Error("Neither CRT nor JS SigV4a implementation is available. Please load either @aws-sdk/signature-v4-crt or @aws-sdk/signature-v4a. For more information please go to https://github.com/aws/aws-sdk-js-v3#functionality-requiring-aws-common-runtime-crt"); - } - if (CrtSignerV4 && typeof CrtSignerV4 === "function") { - this.sigv4aSigner = new CrtSignerV4({ - ...this.signerOptions, - signingAlgorithm: 1 - }); - } else if (JsSigV4aSigner && typeof JsSigV4aSigner === "function") { - this.sigv4aSigner = new JsSigV4aSigner({ - ...this.signerOptions - }); - } else { - throw new Error("Available SigV4a implementation is not a valid constructor. Please ensure you've properly imported @aws-sdk/signature-v4-crt or @aws-sdk/signature-v4a.For more information please go to https://github.com/aws/aws-sdk-js-v3#functionality-requiring-aws-common-runtime-crt"); - } - } else { - if (!JsSigV4aSigner || typeof JsSigV4aSigner !== "function") { - throw new Error("JS SigV4a implementation is not available or not a valid constructor. Please check whether you have installed the @aws-sdk/signature-v4a package explicitly. The CRT implementation is not available for browsers. You must also register the package by calling [require('@aws-sdk/signature-v4a');] or an ESM equivalent such as [import '@aws-sdk/signature-v4a';]. For more information please go to https://github.com/aws/aws-sdk-js-v3#using-javascript-non-crt-implementation-of-sigv4a"); - } - this.sigv4aSigner = new JsSigV4aSigner({ - ...this.signerOptions - }); - } - } - return this.sigv4aSigner; - } - }; - exports.SignatureV4MultiRegion = SignatureV4MultiRegion; - exports.signatureV4CrtContainer = signatureV4CrtContainer; - } -}); - -// node_modules/.pnpm/@aws-sdk+client-s3@3.1030.0/node_modules/@aws-sdk/client-s3/dist-cjs/endpoint/ruleset.js -var require_ruleset = __commonJS({ - "node_modules/.pnpm/@aws-sdk+client-s3@3.1030.0/node_modules/@aws-sdk/client-s3/dist-cjs/endpoint/ruleset.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.ruleSet = void 0; - var cs = "required"; - var ct = "type"; - var cu = "rules"; - var cv = "conditions"; - var cw = "fn"; - var cx = "argv"; - var cy = "ref"; - var cz = "assign"; - var cA = "url"; - var cB = "properties"; - var cC = "backend"; - var cD = "authSchemes"; - var cE = "disableDoubleEncoding"; - var cF = "signingName"; - var cG = "signingRegion"; - var cH = "headers"; - var cI = "signingRegionSet"; - var a5 = 6; - var b6 = false; - var c5 = true; - var d5 = "isSet"; - var e5 = "booleanEquals"; - var f5 = "error"; - var g5 = "aws.partition"; - var h5 = "stringEquals"; - var i5 = "getAttr"; - var j5 = "name"; - var k5 = "substring"; - var l5 = "bucketSuffix"; - var m5 = "parseURL"; - var n5 = "endpoint"; - var o5 = "tree"; - var p5 = "aws.isVirtualHostableS3Bucket"; - var q5 = "{url#scheme}://{Bucket}.{url#authority}{url#path}"; - var r5 = "not"; - var s5 = "accessPointSuffix"; - var t5 = "{url#scheme}://{url#authority}{url#path}"; - var u5 = "hardwareType"; - var v5 = "regionPrefix"; - var w5 = "bucketAliasSuffix"; - var x5 = "outpostId"; - var y2 = "isValidHostLabel"; - var z3 = "sigv4a"; - var A2 = "s3-outposts"; - var B2 = "s3"; - var C2 = "{url#scheme}://{url#authority}{url#normalizedPath}{Bucket}"; - var D2 = "https://{Bucket}.s3-accelerate.{partitionResult#dnsSuffix}"; - var E2 = "https://{Bucket}.s3.{partitionResult#dnsSuffix}"; - var F2 = "aws.parseArn"; - var G2 = "bucketArn"; - var H2 = "arnType"; - var I2 = ""; - var J2 = "s3-object-lambda"; - var K = "accesspoint"; - var L = "accessPointName"; - var M = "{url#scheme}://{accessPointName}-{bucketArn#accountId}.{url#authority}{url#path}"; - var N = "mrapPartition"; - var O = "outpostType"; - var P = "arnPrefix"; - var Q = "{url#scheme}://{url#authority}{url#normalizedPath}{uri_encoded_bucket}"; - var R = "https://s3.{partitionResult#dnsSuffix}/{uri_encoded_bucket}"; - var S = "https://s3.{partitionResult#dnsSuffix}"; - var T = { [cs]: false, [ct]: "string" }; - var U = { [cs]: true, "default": false, [ct]: "boolean" }; - var V = { [cs]: false, [ct]: "boolean" }; - var W = { [cw]: e5, [cx]: [{ [cy]: "Accelerate" }, true] }; - var X = { [cw]: e5, [cx]: [{ [cy]: "UseFIPS" }, true] }; - var Y = { [cw]: e5, [cx]: [{ [cy]: "UseDualStack" }, true] }; - var Z = { [cw]: d5, [cx]: [{ [cy]: "Endpoint" }] }; - var aa = { [cw]: g5, [cx]: [{ [cy]: "Region" }], [cz]: "partitionResult" }; - var ab = { [cw]: h5, [cx]: [{ [cw]: i5, [cx]: [{ [cy]: "partitionResult" }, j5] }, "aws-cn"] }; - var ac = { [cw]: d5, [cx]: [{ [cy]: "Bucket" }] }; - var ad = { [cy]: "Bucket" }; - var ae = { [cv]: [W], [f5]: "S3Express does not support S3 Accelerate.", [ct]: f5 }; - var af = { [cv]: [Z, { [cw]: m5, [cx]: [{ [cy]: "Endpoint" }], [cz]: "url" }], [cu]: [{ [cv]: [{ [cw]: d5, [cx]: [{ [cy]: "DisableS3ExpressSessionAuth" }] }, { [cw]: e5, [cx]: [{ [cy]: "DisableS3ExpressSessionAuth" }, true] }], [cu]: [{ [cv]: [{ [cw]: e5, [cx]: [{ [cw]: i5, [cx]: [{ [cy]: "url" }, "isIp"] }, true] }], [cu]: [{ [cv]: [{ [cw]: "uriEncode", [cx]: [ad], [cz]: "uri_encoded_bucket" }], [cu]: [{ [n5]: { [cA]: "{url#scheme}://{url#authority}/{uri_encoded_bucket}{url#path}", [cB]: { [cC]: "S3Express", [cD]: [{ [cE]: true, [j5]: "sigv4", [cF]: "s3express", [cG]: "{Region}" }] }, [cH]: {} }, [ct]: n5 }], [ct]: o5 }], [ct]: o5 }, { [cv]: [{ [cw]: p5, [cx]: [ad, false] }], [cu]: [{ [n5]: { [cA]: q5, [cB]: { [cC]: "S3Express", [cD]: [{ [cE]: true, [j5]: "sigv4", [cF]: "s3express", [cG]: "{Region}" }] }, [cH]: {} }, [ct]: n5 }], [ct]: o5 }, { [f5]: "S3Express bucket name is not a valid virtual hostable name.", [ct]: f5 }], [ct]: o5 }, { [cv]: [{ [cw]: e5, [cx]: [{ [cw]: i5, [cx]: [{ [cy]: "url" }, "isIp"] }, true] }], [cu]: [{ [cv]: [{ [cw]: "uriEncode", [cx]: [ad], [cz]: "uri_encoded_bucket" }], [cu]: [{ [n5]: { [cA]: "{url#scheme}://{url#authority}/{uri_encoded_bucket}{url#path}", [cB]: { [cC]: "S3Express", [cD]: [{ [cE]: true, [j5]: "sigv4-s3express", [cF]: "s3express", [cG]: "{Region}" }] }, [cH]: {} }, [ct]: n5 }], [ct]: o5 }], [ct]: o5 }, { [cv]: [{ [cw]: p5, [cx]: [ad, false] }], [cu]: [{ [n5]: { [cA]: q5, [cB]: { [cC]: "S3Express", [cD]: [{ [cE]: true, [j5]: "sigv4-s3express", [cF]: "s3express", [cG]: "{Region}" }] }, [cH]: {} }, [ct]: n5 }], [ct]: o5 }, { [f5]: "S3Express bucket name is not a valid virtual hostable name.", [ct]: f5 }], [ct]: o5 }; - var ag = { [cw]: m5, [cx]: [{ [cy]: "Endpoint" }], [cz]: "url" }; - var ah = { [cw]: e5, [cx]: [{ [cw]: i5, [cx]: [{ [cy]: "url" }, "isIp"] }, true] }; - var ai = { [cy]: "url" }; - var aj = { [cw]: "uriEncode", [cx]: [ad], [cz]: "uri_encoded_bucket" }; - var ak = { [cC]: "S3Express", [cD]: [{ [cE]: true, [j5]: "sigv4", [cF]: "s3express", [cG]: "{Region}" }] }; - var al = {}; - var am = { [cw]: p5, [cx]: [ad, false] }; - var an = { [f5]: "S3Express bucket name is not a valid virtual hostable name.", [ct]: f5 }; - var ao = { [cw]: d5, [cx]: [{ [cy]: "UseS3ExpressControlEndpoint" }] }; - var ap = { [cw]: e5, [cx]: [{ [cy]: "UseS3ExpressControlEndpoint" }, true] }; - var aq = { [cw]: r5, [cx]: [Z] }; - var ar = { [cw]: e5, [cx]: [{ [cy]: "UseDualStack" }, false] }; - var as = { [cw]: e5, [cx]: [{ [cy]: "UseFIPS" }, false] }; - var at = { [f5]: "Unrecognized S3Express bucket name format.", [ct]: f5 }; - var au = { [cw]: r5, [cx]: [ac] }; - var av = { [cy]: u5 }; - var aw = { [cv]: [aq], [f5]: "Expected a endpoint to be specified but no endpoint was found", [ct]: f5 }; - var ax = { [cD]: [{ [cE]: true, [j5]: z3, [cF]: A2, [cI]: ["*"] }, { [cE]: true, [j5]: "sigv4", [cF]: A2, [cG]: "{Region}" }] }; - var ay = { [cw]: e5, [cx]: [{ [cy]: "ForcePathStyle" }, false] }; - var az = { [cy]: "ForcePathStyle" }; - var aA = { [cw]: e5, [cx]: [{ [cy]: "Accelerate" }, false] }; - var aB = { [cw]: h5, [cx]: [{ [cy]: "Region" }, "aws-global"] }; - var aC = { [cD]: [{ [cE]: true, [j5]: "sigv4", [cF]: B2, [cG]: "us-east-1" }] }; - var aD = { [cw]: r5, [cx]: [aB] }; - var aE = { [cw]: e5, [cx]: [{ [cy]: "UseGlobalEndpoint" }, true] }; - var aF = { [cA]: "https://{Bucket}.s3-fips.dualstack.{Region}.{partitionResult#dnsSuffix}", [cB]: { [cD]: [{ [cE]: true, [j5]: "sigv4", [cF]: B2, [cG]: "{Region}" }] }, [cH]: {} }; - var aG = { [cD]: [{ [cE]: true, [j5]: "sigv4", [cF]: B2, [cG]: "{Region}" }] }; - var aH = { [cw]: e5, [cx]: [{ [cy]: "UseGlobalEndpoint" }, false] }; - var aI = { [cA]: "https://{Bucket}.s3-fips.{Region}.{partitionResult#dnsSuffix}", [cB]: aG, [cH]: {} }; - var aJ = { [cA]: "https://{Bucket}.s3-accelerate.dualstack.{partitionResult#dnsSuffix}", [cB]: aG, [cH]: {} }; - var aK = { [cA]: "https://{Bucket}.s3.dualstack.{Region}.{partitionResult#dnsSuffix}", [cB]: aG, [cH]: {} }; - var aL = { [cw]: e5, [cx]: [{ [cw]: i5, [cx]: [ai, "isIp"] }, false] }; - var aM = { [cA]: C2, [cB]: aG, [cH]: {} }; - var aN = { [cA]: q5, [cB]: aG, [cH]: {} }; - var aO = { [n5]: aN, [ct]: n5 }; - var aP = { [cA]: D2, [cB]: aG, [cH]: {} }; - var aQ = { [cA]: "https://{Bucket}.s3.{Region}.{partitionResult#dnsSuffix}", [cB]: aG, [cH]: {} }; - var aR = { [f5]: "Invalid region: region was not a valid DNS name.", [ct]: f5 }; - var aS = { [cy]: G2 }; - var aT = { [cy]: H2 }; - var aU = { [cw]: i5, [cx]: [aS, "service"] }; - var aV = { [cy]: L }; - var aW = { [cv]: [Y], [f5]: "S3 Object Lambda does not support Dual-stack", [ct]: f5 }; - var aX = { [cv]: [W], [f5]: "S3 Object Lambda does not support S3 Accelerate", [ct]: f5 }; - var aY = { [cv]: [{ [cw]: d5, [cx]: [{ [cy]: "DisableAccessPoints" }] }, { [cw]: e5, [cx]: [{ [cy]: "DisableAccessPoints" }, true] }], [f5]: "Access points are not supported for this operation", [ct]: f5 }; - var aZ = { [cv]: [{ [cw]: d5, [cx]: [{ [cy]: "UseArnRegion" }] }, { [cw]: e5, [cx]: [{ [cy]: "UseArnRegion" }, false] }, { [cw]: r5, [cx]: [{ [cw]: h5, [cx]: [{ [cw]: i5, [cx]: [aS, "region"] }, "{Region}"] }] }], [f5]: "Invalid configuration: region from ARN `{bucketArn#region}` does not match client region `{Region}` and UseArnRegion is `false`", [ct]: f5 }; - var ba = { [cw]: i5, [cx]: [{ [cy]: "bucketPartition" }, j5] }; - var bb = { [cw]: i5, [cx]: [aS, "accountId"] }; - var bc = { [cD]: [{ [cE]: true, [j5]: "sigv4", [cF]: J2, [cG]: "{bucketArn#region}" }] }; - var bd = { [f5]: "Invalid ARN: The access point name may only contain a-z, A-Z, 0-9 and `-`. Found: `{accessPointName}`", [ct]: f5 }; - var be = { [f5]: "Invalid ARN: The account id may only contain a-z, A-Z, 0-9 and `-`. Found: `{bucketArn#accountId}`", [ct]: f5 }; - var bf = { [f5]: "Invalid region in ARN: `{bucketArn#region}` (invalid DNS name)", [ct]: f5 }; - var bg = { [f5]: "Client was configured for partition `{partitionResult#name}` but ARN (`{Bucket}`) has `{bucketPartition#name}`", [ct]: f5 }; - var bh = { [f5]: "Invalid ARN: The ARN may only contain a single resource component after `accesspoint`.", [ct]: f5 }; - var bi = { [f5]: "Invalid ARN: Expected a resource of the format `accesspoint:` but no name was provided", [ct]: f5 }; - var bj = { [cD]: [{ [cE]: true, [j5]: "sigv4", [cF]: B2, [cG]: "{bucketArn#region}" }] }; - var bk = { [cD]: [{ [cE]: true, [j5]: z3, [cF]: A2, [cI]: ["*"] }, { [cE]: true, [j5]: "sigv4", [cF]: A2, [cG]: "{bucketArn#region}" }] }; - var bl = { [cw]: F2, [cx]: [ad] }; - var bm = { [cA]: "https://s3-fips.dualstack.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}", [cB]: aG, [cH]: {} }; - var bn = { [cA]: "https://s3-fips.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}", [cB]: aG, [cH]: {} }; - var bo = { [cA]: "https://s3.dualstack.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}", [cB]: aG, [cH]: {} }; - var bp = { [cA]: Q, [cB]: aG, [cH]: {} }; - var bq = { [cA]: "https://s3.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}", [cB]: aG, [cH]: {} }; - var br = { [cy]: "UseObjectLambdaEndpoint" }; - var bs = { [cD]: [{ [cE]: true, [j5]: "sigv4", [cF]: J2, [cG]: "{Region}" }] }; - var bt = { [cA]: "https://s3-fips.dualstack.{Region}.{partitionResult#dnsSuffix}", [cB]: aG, [cH]: {} }; - var bu = { [cA]: "https://s3-fips.{Region}.{partitionResult#dnsSuffix}", [cB]: aG, [cH]: {} }; - var bv = { [cA]: "https://s3.dualstack.{Region}.{partitionResult#dnsSuffix}", [cB]: aG, [cH]: {} }; - var bw = { [cA]: t5, [cB]: aG, [cH]: {} }; - var bx = { [cA]: "https://s3.{Region}.{partitionResult#dnsSuffix}", [cB]: aG, [cH]: {} }; - var by = [{ [cy]: "Region" }]; - var bz = [{ [cy]: "Endpoint" }]; - var bA = [ad]; - var bB = [W]; - var bC = [Z, ag]; - var bD = [{ [cw]: d5, [cx]: [{ [cy]: "DisableS3ExpressSessionAuth" }] }, { [cw]: e5, [cx]: [{ [cy]: "DisableS3ExpressSessionAuth" }, true] }]; - var bE = [aj]; - var bF = [am]; - var bG = [aa]; - var bH = [X, Y]; - var bI = [X, ar]; - var bJ = [as, Y]; - var bK = [as, ar]; - var bL = [{ [cw]: k5, [cx]: [ad, 6, 14, true], [cz]: "s3expressAvailabilityZoneId" }, { [cw]: k5, [cx]: [ad, 14, 16, true], [cz]: "s3expressAvailabilityZoneDelim" }, { [cw]: h5, [cx]: [{ [cy]: "s3expressAvailabilityZoneDelim" }, "--"] }]; - var bM = [{ [cv]: [X, Y], [n5]: { [cA]: "https://{Bucket}.s3express-fips-{s3expressAvailabilityZoneId}.dualstack.{Region}.{partitionResult#dnsSuffix}", [cB]: ak, [cH]: {} }, [ct]: n5 }, { [cv]: bI, [n5]: { [cA]: "https://{Bucket}.s3express-fips-{s3expressAvailabilityZoneId}.{Region}.{partitionResult#dnsSuffix}", [cB]: ak, [cH]: {} }, [ct]: n5 }, { [cv]: bJ, [n5]: { [cA]: "https://{Bucket}.s3express-{s3expressAvailabilityZoneId}.dualstack.{Region}.{partitionResult#dnsSuffix}", [cB]: ak, [cH]: {} }, [ct]: n5 }, { [cv]: bK, [n5]: { [cA]: "https://{Bucket}.s3express-{s3expressAvailabilityZoneId}.{Region}.{partitionResult#dnsSuffix}", [cB]: ak, [cH]: {} }, [ct]: n5 }]; - var bN = [{ [cw]: k5, [cx]: [ad, 6, 15, true], [cz]: "s3expressAvailabilityZoneId" }, { [cw]: k5, [cx]: [ad, 15, 17, true], [cz]: "s3expressAvailabilityZoneDelim" }, { [cw]: h5, [cx]: [{ [cy]: "s3expressAvailabilityZoneDelim" }, "--"] }]; - var bO = [{ [cw]: k5, [cx]: [ad, 6, 19, true], [cz]: "s3expressAvailabilityZoneId" }, { [cw]: k5, [cx]: [ad, 19, 21, true], [cz]: "s3expressAvailabilityZoneDelim" }, { [cw]: h5, [cx]: [{ [cy]: "s3expressAvailabilityZoneDelim" }, "--"] }]; - var bP = [{ [cw]: k5, [cx]: [ad, 6, 20, true], [cz]: "s3expressAvailabilityZoneId" }, { [cw]: k5, [cx]: [ad, 20, 22, true], [cz]: "s3expressAvailabilityZoneDelim" }, { [cw]: h5, [cx]: [{ [cy]: "s3expressAvailabilityZoneDelim" }, "--"] }]; - var bQ = [{ [cw]: k5, [cx]: [ad, 6, 26, true], [cz]: "s3expressAvailabilityZoneId" }, { [cw]: k5, [cx]: [ad, 26, 28, true], [cz]: "s3expressAvailabilityZoneDelim" }, { [cw]: h5, [cx]: [{ [cy]: "s3expressAvailabilityZoneDelim" }, "--"] }]; - var bR = [{ [cv]: [X, Y], [n5]: { [cA]: "https://{Bucket}.s3express-fips-{s3expressAvailabilityZoneId}.dualstack.{Region}.{partitionResult#dnsSuffix}", [cB]: { [cC]: "S3Express", [cD]: [{ [cE]: true, [j5]: "sigv4-s3express", [cF]: "s3express", [cG]: "{Region}" }] }, [cH]: {} }, [ct]: n5 }, { [cv]: bI, [n5]: { [cA]: "https://{Bucket}.s3express-fips-{s3expressAvailabilityZoneId}.{Region}.{partitionResult#dnsSuffix}", [cB]: { [cC]: "S3Express", [cD]: [{ [cE]: true, [j5]: "sigv4-s3express", [cF]: "s3express", [cG]: "{Region}" }] }, [cH]: {} }, [ct]: n5 }, { [cv]: bJ, [n5]: { [cA]: "https://{Bucket}.s3express-{s3expressAvailabilityZoneId}.dualstack.{Region}.{partitionResult#dnsSuffix}", [cB]: { [cC]: "S3Express", [cD]: [{ [cE]: true, [j5]: "sigv4-s3express", [cF]: "s3express", [cG]: "{Region}" }] }, [cH]: {} }, [ct]: n5 }, { [cv]: bK, [n5]: { [cA]: "https://{Bucket}.s3express-{s3expressAvailabilityZoneId}.{Region}.{partitionResult#dnsSuffix}", [cB]: { [cC]: "S3Express", [cD]: [{ [cE]: true, [j5]: "sigv4-s3express", [cF]: "s3express", [cG]: "{Region}" }] }, [cH]: {} }, [ct]: n5 }]; - var bS = [ad, 0, 7, true]; - var bT = [{ [cw]: k5, [cx]: [ad, 7, 15, true], [cz]: "s3expressAvailabilityZoneId" }, { [cw]: k5, [cx]: [ad, 15, 17, true], [cz]: "s3expressAvailabilityZoneDelim" }, { [cw]: h5, [cx]: [{ [cy]: "s3expressAvailabilityZoneDelim" }, "--"] }]; - var bU = [{ [cw]: k5, [cx]: [ad, 7, 16, true], [cz]: "s3expressAvailabilityZoneId" }, { [cw]: k5, [cx]: [ad, 16, 18, true], [cz]: "s3expressAvailabilityZoneDelim" }, { [cw]: h5, [cx]: [{ [cy]: "s3expressAvailabilityZoneDelim" }, "--"] }]; - var bV = [{ [cw]: k5, [cx]: [ad, 7, 20, true], [cz]: "s3expressAvailabilityZoneId" }, { [cw]: k5, [cx]: [ad, 20, 22, true], [cz]: "s3expressAvailabilityZoneDelim" }, { [cw]: h5, [cx]: [{ [cy]: "s3expressAvailabilityZoneDelim" }, "--"] }]; - var bW = [{ [cw]: k5, [cx]: [ad, 7, 21, true], [cz]: "s3expressAvailabilityZoneId" }, { [cw]: k5, [cx]: [ad, 21, 23, true], [cz]: "s3expressAvailabilityZoneDelim" }, { [cw]: h5, [cx]: [{ [cy]: "s3expressAvailabilityZoneDelim" }, "--"] }]; - var bX = [{ [cw]: k5, [cx]: [ad, 7, 27, true], [cz]: "s3expressAvailabilityZoneId" }, { [cw]: k5, [cx]: [ad, 27, 29, true], [cz]: "s3expressAvailabilityZoneDelim" }, { [cw]: h5, [cx]: [{ [cy]: "s3expressAvailabilityZoneDelim" }, "--"] }]; - var bY = [ac]; - var bZ = [{ [cw]: y2, [cx]: [{ [cy]: x5 }, false] }]; - var ca = [{ [cw]: h5, [cx]: [{ [cy]: v5 }, "beta"] }]; - var cb = ["*"]; - var cc = [{ [cw]: y2, [cx]: [{ [cy]: "Region" }, false] }]; - var cd = [{ [cw]: h5, [cx]: [{ [cy]: "Region" }, "us-east-1"] }]; - var ce = [{ [cw]: h5, [cx]: [aT, K] }]; - var cf = [{ [cw]: i5, [cx]: [aS, "resourceId[1]"], [cz]: L }, { [cw]: r5, [cx]: [{ [cw]: h5, [cx]: [aV, I2] }] }]; - var cg = [aS, "resourceId[1]"]; - var ch = [Y]; - var ci = [{ [cw]: r5, [cx]: [{ [cw]: h5, [cx]: [{ [cw]: i5, [cx]: [aS, "region"] }, I2] }] }]; - var cj = [{ [cw]: r5, [cx]: [{ [cw]: d5, [cx]: [{ [cw]: i5, [cx]: [aS, "resourceId[2]"] }] }] }]; - var ck = [aS, "resourceId[2]"]; - var cl = [{ [cw]: g5, [cx]: [{ [cw]: i5, [cx]: [aS, "region"] }], [cz]: "bucketPartition" }]; - var cm = [{ [cw]: h5, [cx]: [ba, { [cw]: i5, [cx]: [{ [cy]: "partitionResult" }, j5] }] }]; - var cn = [{ [cw]: y2, [cx]: [{ [cw]: i5, [cx]: [aS, "region"] }, true] }]; - var co = [{ [cw]: y2, [cx]: [bb, false] }]; - var cp = [{ [cw]: y2, [cx]: [aV, false] }]; - var cq = [X]; - var cr = [{ [cw]: y2, [cx]: [{ [cy]: "Region" }, true] }]; - var _data5 = { version: "1.0", parameters: { Bucket: T, Region: T, UseFIPS: U, UseDualStack: U, Endpoint: T, ForcePathStyle: U, Accelerate: U, UseGlobalEndpoint: U, UseObjectLambdaEndpoint: V, Key: T, Prefix: T, CopySource: T, DisableAccessPoints: V, DisableMultiRegionAccessPoints: U, UseArnRegion: V, UseS3ExpressControlEndpoint: V, DisableS3ExpressSessionAuth: V }, [cu]: [{ [cv]: [{ [cw]: d5, [cx]: by }], [cu]: [{ [cv]: [W, X], error: "Accelerate cannot be used with FIPS", [ct]: f5 }, { [cv]: [Y, Z], error: "Cannot set dual-stack in combination with a custom endpoint.", [ct]: f5 }, { [cv]: [Z, X], error: "A custom endpoint cannot be combined with FIPS", [ct]: f5 }, { [cv]: [Z, W], error: "A custom endpoint cannot be combined with S3 Accelerate", [ct]: f5 }, { [cv]: [X, aa, ab], error: "Partition does not support FIPS", [ct]: f5 }, { [cv]: [ac, { [cw]: k5, [cx]: [ad, 0, a5, c5], [cz]: l5 }, { [cw]: h5, [cx]: [{ [cy]: l5 }, "--x-s3"] }], [cu]: [ae, af, { [cv]: [ao, ap], [cu]: [{ [cv]: bG, [cu]: [{ [cv]: [aj, aq], [cu]: [{ [cv]: bH, endpoint: { [cA]: "https://s3express-control-fips.dualstack.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}", [cB]: ak, [cH]: al }, [ct]: n5 }, { [cv]: bI, endpoint: { [cA]: "https://s3express-control-fips.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}", [cB]: ak, [cH]: al }, [ct]: n5 }, { [cv]: bJ, endpoint: { [cA]: "https://s3express-control.dualstack.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}", [cB]: ak, [cH]: al }, [ct]: n5 }, { [cv]: bK, endpoint: { [cA]: "https://s3express-control.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}", [cB]: ak, [cH]: al }, [ct]: n5 }], [ct]: o5 }], [ct]: o5 }], [ct]: o5 }, { [cv]: bF, [cu]: [{ [cv]: bG, [cu]: [{ [cv]: bD, [cu]: [{ [cv]: bL, [cu]: bM, [ct]: o5 }, { [cv]: bN, [cu]: bM, [ct]: o5 }, { [cv]: bO, [cu]: bM, [ct]: o5 }, { [cv]: bP, [cu]: bM, [ct]: o5 }, { [cv]: bQ, [cu]: bM, [ct]: o5 }, at], [ct]: o5 }, { [cv]: bL, [cu]: bR, [ct]: o5 }, { [cv]: bN, [cu]: bR, [ct]: o5 }, { [cv]: bO, [cu]: bR, [ct]: o5 }, { [cv]: bP, [cu]: bR, [ct]: o5 }, { [cv]: bQ, [cu]: bR, [ct]: o5 }, at], [ct]: o5 }], [ct]: o5 }, an], [ct]: o5 }, { [cv]: [ac, { [cw]: k5, [cx]: bS, [cz]: s5 }, { [cw]: h5, [cx]: [{ [cy]: s5 }, "--xa-s3"] }], [cu]: [ae, af, { [cv]: bF, [cu]: [{ [cv]: bG, [cu]: [{ [cv]: bD, [cu]: [{ [cv]: bT, [cu]: bM, [ct]: o5 }, { [cv]: bU, [cu]: bM, [ct]: o5 }, { [cv]: bV, [cu]: bM, [ct]: o5 }, { [cv]: bW, [cu]: bM, [ct]: o5 }, { [cv]: bX, [cu]: bM, [ct]: o5 }, at], [ct]: o5 }, { [cv]: bT, [cu]: bR, [ct]: o5 }, { [cv]: bU, [cu]: bR, [ct]: o5 }, { [cv]: bV, [cu]: bR, [ct]: o5 }, { [cv]: bW, [cu]: bR, [ct]: o5 }, { [cv]: bX, [cu]: bR, [ct]: o5 }, at], [ct]: o5 }], [ct]: o5 }, an], [ct]: o5 }, { [cv]: [au, ao, ap], [cu]: [{ [cv]: bG, [cu]: [{ [cv]: bC, endpoint: { [cA]: t5, [cB]: ak, [cH]: al }, [ct]: n5 }, { [cv]: bH, endpoint: { [cA]: "https://s3express-control-fips.dualstack.{Region}.{partitionResult#dnsSuffix}", [cB]: ak, [cH]: al }, [ct]: n5 }, { [cv]: bI, endpoint: { [cA]: "https://s3express-control-fips.{Region}.{partitionResult#dnsSuffix}", [cB]: ak, [cH]: al }, [ct]: n5 }, { [cv]: bJ, endpoint: { [cA]: "https://s3express-control.dualstack.{Region}.{partitionResult#dnsSuffix}", [cB]: ak, [cH]: al }, [ct]: n5 }, { [cv]: bK, endpoint: { [cA]: "https://s3express-control.{Region}.{partitionResult#dnsSuffix}", [cB]: ak, [cH]: al }, [ct]: n5 }], [ct]: o5 }], [ct]: o5 }, { [cv]: [ac, { [cw]: k5, [cx]: [ad, 49, 50, c5], [cz]: u5 }, { [cw]: k5, [cx]: [ad, 8, 12, c5], [cz]: v5 }, { [cw]: k5, [cx]: bS, [cz]: w5 }, { [cw]: k5, [cx]: [ad, 32, 49, c5], [cz]: x5 }, { [cw]: g5, [cx]: by, [cz]: "regionPartition" }, { [cw]: h5, [cx]: [{ [cy]: w5 }, "--op-s3"] }], [cu]: [{ [cv]: bZ, [cu]: [{ [cv]: bF, [cu]: [{ [cv]: [{ [cw]: h5, [cx]: [av, "e"] }], [cu]: [{ [cv]: ca, [cu]: [aw, { [cv]: bC, endpoint: { [cA]: "https://{Bucket}.ec2.{url#authority}", [cB]: ax, [cH]: al }, [ct]: n5 }], [ct]: o5 }, { endpoint: { [cA]: "https://{Bucket}.ec2.s3-outposts.{Region}.{regionPartition#dnsSuffix}", [cB]: ax, [cH]: al }, [ct]: n5 }], [ct]: o5 }, { [cv]: [{ [cw]: h5, [cx]: [av, "o"] }], [cu]: [{ [cv]: ca, [cu]: [aw, { [cv]: bC, endpoint: { [cA]: "https://{Bucket}.op-{outpostId}.{url#authority}", [cB]: ax, [cH]: al }, [ct]: n5 }], [ct]: o5 }, { endpoint: { [cA]: "https://{Bucket}.op-{outpostId}.s3-outposts.{Region}.{regionPartition#dnsSuffix}", [cB]: ax, [cH]: al }, [ct]: n5 }], [ct]: o5 }, { error: 'Unrecognized hardware type: "Expected hardware type o or e but got {hardwareType}"', [ct]: f5 }], [ct]: o5 }, { error: "Invalid Outposts Bucket alias - it must be a valid bucket name.", [ct]: f5 }], [ct]: o5 }, { error: "Invalid ARN: The outpost Id must only contain a-z, A-Z, 0-9 and `-`.", [ct]: f5 }], [ct]: o5 }, { [cv]: bY, [cu]: [{ [cv]: [Z, { [cw]: r5, [cx]: [{ [cw]: d5, [cx]: [{ [cw]: m5, [cx]: bz }] }] }], error: "Custom endpoint `{Endpoint}` was not a valid URI", [ct]: f5 }, { [cv]: [ay, am], [cu]: [{ [cv]: bG, [cu]: [{ [cv]: cc, [cu]: [{ [cv]: [W, ab], error: "S3 Accelerate cannot be used in this region", [ct]: f5 }, { [cv]: [Y, X, aA, aq, aB], endpoint: { [cA]: "https://{Bucket}.s3-fips.dualstack.us-east-1.{partitionResult#dnsSuffix}", [cB]: aC, [cH]: al }, [ct]: n5 }, { [cv]: [Y, X, aA, aq, aD, aE], [cu]: [{ endpoint: aF, [ct]: n5 }], [ct]: o5 }, { [cv]: [Y, X, aA, aq, aD, aH], endpoint: aF, [ct]: n5 }, { [cv]: [ar, X, aA, aq, aB], endpoint: { [cA]: "https://{Bucket}.s3-fips.us-east-1.{partitionResult#dnsSuffix}", [cB]: aC, [cH]: al }, [ct]: n5 }, { [cv]: [ar, X, aA, aq, aD, aE], [cu]: [{ endpoint: aI, [ct]: n5 }], [ct]: o5 }, { [cv]: [ar, X, aA, aq, aD, aH], endpoint: aI, [ct]: n5 }, { [cv]: [Y, as, W, aq, aB], endpoint: { [cA]: "https://{Bucket}.s3-accelerate.dualstack.us-east-1.{partitionResult#dnsSuffix}", [cB]: aC, [cH]: al }, [ct]: n5 }, { [cv]: [Y, as, W, aq, aD, aE], [cu]: [{ endpoint: aJ, [ct]: n5 }], [ct]: o5 }, { [cv]: [Y, as, W, aq, aD, aH], endpoint: aJ, [ct]: n5 }, { [cv]: [Y, as, aA, aq, aB], endpoint: { [cA]: "https://{Bucket}.s3.dualstack.us-east-1.{partitionResult#dnsSuffix}", [cB]: aC, [cH]: al }, [ct]: n5 }, { [cv]: [Y, as, aA, aq, aD, aE], [cu]: [{ endpoint: aK, [ct]: n5 }], [ct]: o5 }, { [cv]: [Y, as, aA, aq, aD, aH], endpoint: aK, [ct]: n5 }, { [cv]: [ar, as, aA, Z, ag, ah, aB], endpoint: { [cA]: C2, [cB]: aC, [cH]: al }, [ct]: n5 }, { [cv]: [ar, as, aA, Z, ag, aL, aB], endpoint: { [cA]: q5, [cB]: aC, [cH]: al }, [ct]: n5 }, { [cv]: [ar, as, aA, Z, ag, ah, aD, aE], [cu]: [{ [cv]: cd, endpoint: aM, [ct]: n5 }, { endpoint: aM, [ct]: n5 }], [ct]: o5 }, { [cv]: [ar, as, aA, Z, ag, aL, aD, aE], [cu]: [{ [cv]: cd, endpoint: aN, [ct]: n5 }, aO], [ct]: o5 }, { [cv]: [ar, as, aA, Z, ag, ah, aD, aH], endpoint: aM, [ct]: n5 }, { [cv]: [ar, as, aA, Z, ag, aL, aD, aH], endpoint: aN, [ct]: n5 }, { [cv]: [ar, as, W, aq, aB], endpoint: { [cA]: D2, [cB]: aC, [cH]: al }, [ct]: n5 }, { [cv]: [ar, as, W, aq, aD, aE], [cu]: [{ [cv]: cd, endpoint: aP, [ct]: n5 }, { endpoint: aP, [ct]: n5 }], [ct]: o5 }, { [cv]: [ar, as, W, aq, aD, aH], endpoint: aP, [ct]: n5 }, { [cv]: [ar, as, aA, aq, aB], endpoint: { [cA]: E2, [cB]: aC, [cH]: al }, [ct]: n5 }, { [cv]: [ar, as, aA, aq, aD, aE], [cu]: [{ [cv]: cd, endpoint: { [cA]: E2, [cB]: aG, [cH]: al }, [ct]: n5 }, { endpoint: aQ, [ct]: n5 }], [ct]: o5 }, { [cv]: [ar, as, aA, aq, aD, aH], endpoint: aQ, [ct]: n5 }], [ct]: o5 }, aR], [ct]: o5 }], [ct]: o5 }, { [cv]: [Z, ag, { [cw]: h5, [cx]: [{ [cw]: i5, [cx]: [ai, "scheme"] }, "http"] }, { [cw]: p5, [cx]: [ad, c5] }, ay, as, ar, aA], [cu]: [{ [cv]: bG, [cu]: [{ [cv]: cc, [cu]: [aO], [ct]: o5 }, aR], [ct]: o5 }], [ct]: o5 }, { [cv]: [ay, { [cw]: F2, [cx]: bA, [cz]: G2 }], [cu]: [{ [cv]: [{ [cw]: i5, [cx]: [aS, "resourceId[0]"], [cz]: H2 }, { [cw]: r5, [cx]: [{ [cw]: h5, [cx]: [aT, I2] }] }], [cu]: [{ [cv]: [{ [cw]: h5, [cx]: [aU, J2] }], [cu]: [{ [cv]: ce, [cu]: [{ [cv]: cf, [cu]: [aW, aX, { [cv]: ci, [cu]: [aY, { [cv]: cj, [cu]: [aZ, { [cv]: cl, [cu]: [{ [cv]: bG, [cu]: [{ [cv]: cm, [cu]: [{ [cv]: cn, [cu]: [{ [cv]: [{ [cw]: h5, [cx]: [bb, I2] }], error: "Invalid ARN: Missing account id", [ct]: f5 }, { [cv]: co, [cu]: [{ [cv]: cp, [cu]: [{ [cv]: bC, endpoint: { [cA]: M, [cB]: bc, [cH]: al }, [ct]: n5 }, { [cv]: cq, endpoint: { [cA]: "https://{accessPointName}-{bucketArn#accountId}.s3-object-lambda-fips.{bucketArn#region}.{bucketPartition#dnsSuffix}", [cB]: bc, [cH]: al }, [ct]: n5 }, { endpoint: { [cA]: "https://{accessPointName}-{bucketArn#accountId}.s3-object-lambda.{bucketArn#region}.{bucketPartition#dnsSuffix}", [cB]: bc, [cH]: al }, [ct]: n5 }], [ct]: o5 }, bd], [ct]: o5 }, be], [ct]: o5 }, bf], [ct]: o5 }, bg], [ct]: o5 }], [ct]: o5 }], [ct]: o5 }, bh], [ct]: o5 }, { error: "Invalid ARN: bucket ARN is missing a region", [ct]: f5 }], [ct]: o5 }, bi], [ct]: o5 }, { error: "Invalid ARN: Object Lambda ARNs only support `accesspoint` arn types, but found: `{arnType}`", [ct]: f5 }], [ct]: o5 }, { [cv]: ce, [cu]: [{ [cv]: cf, [cu]: [{ [cv]: ci, [cu]: [{ [cv]: ce, [cu]: [{ [cv]: ci, [cu]: [aY, { [cv]: cj, [cu]: [aZ, { [cv]: cl, [cu]: [{ [cv]: bG, [cu]: [{ [cv]: [{ [cw]: h5, [cx]: [ba, "{partitionResult#name}"] }], [cu]: [{ [cv]: cn, [cu]: [{ [cv]: [{ [cw]: h5, [cx]: [aU, B2] }], [cu]: [{ [cv]: co, [cu]: [{ [cv]: cp, [cu]: [{ [cv]: bB, error: "Access Points do not support S3 Accelerate", [ct]: f5 }, { [cv]: bH, endpoint: { [cA]: "https://{accessPointName}-{bucketArn#accountId}.s3-accesspoint-fips.dualstack.{bucketArn#region}.{bucketPartition#dnsSuffix}", [cB]: bj, [cH]: al }, [ct]: n5 }, { [cv]: bI, endpoint: { [cA]: "https://{accessPointName}-{bucketArn#accountId}.s3-accesspoint-fips.{bucketArn#region}.{bucketPartition#dnsSuffix}", [cB]: bj, [cH]: al }, [ct]: n5 }, { [cv]: bJ, endpoint: { [cA]: "https://{accessPointName}-{bucketArn#accountId}.s3-accesspoint.dualstack.{bucketArn#region}.{bucketPartition#dnsSuffix}", [cB]: bj, [cH]: al }, [ct]: n5 }, { [cv]: [as, ar, Z, ag], endpoint: { [cA]: M, [cB]: bj, [cH]: al }, [ct]: n5 }, { [cv]: bK, endpoint: { [cA]: "https://{accessPointName}-{bucketArn#accountId}.s3-accesspoint.{bucketArn#region}.{bucketPartition#dnsSuffix}", [cB]: bj, [cH]: al }, [ct]: n5 }], [ct]: o5 }, bd], [ct]: o5 }, be], [ct]: o5 }, { error: "Invalid ARN: The ARN was not for the S3 service, found: {bucketArn#service}", [ct]: f5 }], [ct]: o5 }, bf], [ct]: o5 }, bg], [ct]: o5 }], [ct]: o5 }], [ct]: o5 }, bh], [ct]: o5 }], [ct]: o5 }], [ct]: o5 }, { [cv]: [{ [cw]: y2, [cx]: [aV, c5] }], [cu]: [{ [cv]: ch, error: "S3 MRAP does not support dual-stack", [ct]: f5 }, { [cv]: cq, error: "S3 MRAP does not support FIPS", [ct]: f5 }, { [cv]: bB, error: "S3 MRAP does not support S3 Accelerate", [ct]: f5 }, { [cv]: [{ [cw]: e5, [cx]: [{ [cy]: "DisableMultiRegionAccessPoints" }, c5] }], error: "Invalid configuration: Multi-Region Access Point ARNs are disabled.", [ct]: f5 }, { [cv]: [{ [cw]: g5, [cx]: by, [cz]: N }], [cu]: [{ [cv]: [{ [cw]: h5, [cx]: [{ [cw]: i5, [cx]: [{ [cy]: N }, j5] }, { [cw]: i5, [cx]: [aS, "partition"] }] }], [cu]: [{ endpoint: { [cA]: "https://{accessPointName}.accesspoint.s3-global.{mrapPartition#dnsSuffix}", [cB]: { [cD]: [{ [cE]: c5, name: z3, [cF]: B2, [cI]: cb }] }, [cH]: al }, [ct]: n5 }], [ct]: o5 }, { error: "Client was configured for partition `{mrapPartition#name}` but bucket referred to partition `{bucketArn#partition}`", [ct]: f5 }], [ct]: o5 }], [ct]: o5 }, { error: "Invalid Access Point Name", [ct]: f5 }], [ct]: o5 }, bi], [ct]: o5 }, { [cv]: [{ [cw]: h5, [cx]: [aU, A2] }], [cu]: [{ [cv]: ch, error: "S3 Outposts does not support Dual-stack", [ct]: f5 }, { [cv]: cq, error: "S3 Outposts does not support FIPS", [ct]: f5 }, { [cv]: bB, error: "S3 Outposts does not support S3 Accelerate", [ct]: f5 }, { [cv]: [{ [cw]: d5, [cx]: [{ [cw]: i5, [cx]: [aS, "resourceId[4]"] }] }], error: "Invalid Arn: Outpost Access Point ARN contains sub resources", [ct]: f5 }, { [cv]: [{ [cw]: i5, [cx]: cg, [cz]: x5 }], [cu]: [{ [cv]: bZ, [cu]: [aZ, { [cv]: cl, [cu]: [{ [cv]: bG, [cu]: [{ [cv]: cm, [cu]: [{ [cv]: cn, [cu]: [{ [cv]: co, [cu]: [{ [cv]: [{ [cw]: i5, [cx]: ck, [cz]: O }], [cu]: [{ [cv]: [{ [cw]: i5, [cx]: [aS, "resourceId[3]"], [cz]: L }], [cu]: [{ [cv]: [{ [cw]: h5, [cx]: [{ [cy]: O }, K] }], [cu]: [{ [cv]: bC, endpoint: { [cA]: "https://{accessPointName}-{bucketArn#accountId}.{outpostId}.{url#authority}", [cB]: bk, [cH]: al }, [ct]: n5 }, { endpoint: { [cA]: "https://{accessPointName}-{bucketArn#accountId}.{outpostId}.s3-outposts.{bucketArn#region}.{bucketPartition#dnsSuffix}", [cB]: bk, [cH]: al }, [ct]: n5 }], [ct]: o5 }, { error: "Expected an outpost type `accesspoint`, found {outpostType}", [ct]: f5 }], [ct]: o5 }, { error: "Invalid ARN: expected an access point name", [ct]: f5 }], [ct]: o5 }, { error: "Invalid ARN: Expected a 4-component resource", [ct]: f5 }], [ct]: o5 }, be], [ct]: o5 }, bf], [ct]: o5 }, bg], [ct]: o5 }], [ct]: o5 }], [ct]: o5 }, { error: "Invalid ARN: The outpost Id may only contain a-z, A-Z, 0-9 and `-`. Found: `{outpostId}`", [ct]: f5 }], [ct]: o5 }, { error: "Invalid ARN: The Outpost Id was not set", [ct]: f5 }], [ct]: o5 }, { error: "Invalid ARN: Unrecognized format: {Bucket} (type: {arnType})", [ct]: f5 }], [ct]: o5 }, { error: "Invalid ARN: No ARN type specified", [ct]: f5 }], [ct]: o5 }, { [cv]: [{ [cw]: k5, [cx]: [ad, 0, 4, b6], [cz]: P }, { [cw]: h5, [cx]: [{ [cy]: P }, "arn:"] }, { [cw]: r5, [cx]: [{ [cw]: d5, [cx]: [bl] }] }], error: "Invalid ARN: `{Bucket}` was not a valid ARN", [ct]: f5 }, { [cv]: [{ [cw]: e5, [cx]: [az, c5] }, bl], error: "Path-style addressing cannot be used with ARN buckets", [ct]: f5 }, { [cv]: bE, [cu]: [{ [cv]: bG, [cu]: [{ [cv]: [aA], [cu]: [{ [cv]: [Y, aq, X, aB], endpoint: { [cA]: "https://s3-fips.dualstack.us-east-1.{partitionResult#dnsSuffix}/{uri_encoded_bucket}", [cB]: aC, [cH]: al }, [ct]: n5 }, { [cv]: [Y, aq, X, aD, aE], [cu]: [{ endpoint: bm, [ct]: n5 }], [ct]: o5 }, { [cv]: [Y, aq, X, aD, aH], endpoint: bm, [ct]: n5 }, { [cv]: [ar, aq, X, aB], endpoint: { [cA]: "https://s3-fips.us-east-1.{partitionResult#dnsSuffix}/{uri_encoded_bucket}", [cB]: aC, [cH]: al }, [ct]: n5 }, { [cv]: [ar, aq, X, aD, aE], [cu]: [{ endpoint: bn, [ct]: n5 }], [ct]: o5 }, { [cv]: [ar, aq, X, aD, aH], endpoint: bn, [ct]: n5 }, { [cv]: [Y, aq, as, aB], endpoint: { [cA]: "https://s3.dualstack.us-east-1.{partitionResult#dnsSuffix}/{uri_encoded_bucket}", [cB]: aC, [cH]: al }, [ct]: n5 }, { [cv]: [Y, aq, as, aD, aE], [cu]: [{ endpoint: bo, [ct]: n5 }], [ct]: o5 }, { [cv]: [Y, aq, as, aD, aH], endpoint: bo, [ct]: n5 }, { [cv]: [ar, Z, ag, as, aB], endpoint: { [cA]: Q, [cB]: aC, [cH]: al }, [ct]: n5 }, { [cv]: [ar, Z, ag, as, aD, aE], [cu]: [{ [cv]: cd, endpoint: bp, [ct]: n5 }, { endpoint: bp, [ct]: n5 }], [ct]: o5 }, { [cv]: [ar, Z, ag, as, aD, aH], endpoint: bp, [ct]: n5 }, { [cv]: [ar, aq, as, aB], endpoint: { [cA]: R, [cB]: aC, [cH]: al }, [ct]: n5 }, { [cv]: [ar, aq, as, aD, aE], [cu]: [{ [cv]: cd, endpoint: { [cA]: R, [cB]: aG, [cH]: al }, [ct]: n5 }, { endpoint: bq, [ct]: n5 }], [ct]: o5 }, { [cv]: [ar, aq, as, aD, aH], endpoint: bq, [ct]: n5 }], [ct]: o5 }, { error: "Path-style addressing cannot be used with S3 Accelerate", [ct]: f5 }], [ct]: o5 }], [ct]: o5 }], [ct]: o5 }, { [cv]: [{ [cw]: d5, [cx]: [br] }, { [cw]: e5, [cx]: [br, c5] }], [cu]: [{ [cv]: bG, [cu]: [{ [cv]: cr, [cu]: [aW, aX, { [cv]: bC, endpoint: { [cA]: t5, [cB]: bs, [cH]: al }, [ct]: n5 }, { [cv]: cq, endpoint: { [cA]: "https://s3-object-lambda-fips.{Region}.{partitionResult#dnsSuffix}", [cB]: bs, [cH]: al }, [ct]: n5 }, { endpoint: { [cA]: "https://s3-object-lambda.{Region}.{partitionResult#dnsSuffix}", [cB]: bs, [cH]: al }, [ct]: n5 }], [ct]: o5 }, aR], [ct]: o5 }], [ct]: o5 }, { [cv]: [au], [cu]: [{ [cv]: bG, [cu]: [{ [cv]: cr, [cu]: [{ [cv]: [X, Y, aq, aB], endpoint: { [cA]: "https://s3-fips.dualstack.us-east-1.{partitionResult#dnsSuffix}", [cB]: aC, [cH]: al }, [ct]: n5 }, { [cv]: [X, Y, aq, aD, aE], [cu]: [{ endpoint: bt, [ct]: n5 }], [ct]: o5 }, { [cv]: [X, Y, aq, aD, aH], endpoint: bt, [ct]: n5 }, { [cv]: [X, ar, aq, aB], endpoint: { [cA]: "https://s3-fips.us-east-1.{partitionResult#dnsSuffix}", [cB]: aC, [cH]: al }, [ct]: n5 }, { [cv]: [X, ar, aq, aD, aE], [cu]: [{ endpoint: bu, [ct]: n5 }], [ct]: o5 }, { [cv]: [X, ar, aq, aD, aH], endpoint: bu, [ct]: n5 }, { [cv]: [as, Y, aq, aB], endpoint: { [cA]: "https://s3.dualstack.us-east-1.{partitionResult#dnsSuffix}", [cB]: aC, [cH]: al }, [ct]: n5 }, { [cv]: [as, Y, aq, aD, aE], [cu]: [{ endpoint: bv, [ct]: n5 }], [ct]: o5 }, { [cv]: [as, Y, aq, aD, aH], endpoint: bv, [ct]: n5 }, { [cv]: [as, ar, Z, ag, aB], endpoint: { [cA]: t5, [cB]: aC, [cH]: al }, [ct]: n5 }, { [cv]: [as, ar, Z, ag, aD, aE], [cu]: [{ [cv]: cd, endpoint: bw, [ct]: n5 }, { endpoint: bw, [ct]: n5 }], [ct]: o5 }, { [cv]: [as, ar, Z, ag, aD, aH], endpoint: bw, [ct]: n5 }, { [cv]: [as, ar, aq, aB], endpoint: { [cA]: S, [cB]: aC, [cH]: al }, [ct]: n5 }, { [cv]: [as, ar, aq, aD, aE], [cu]: [{ [cv]: cd, endpoint: { [cA]: S, [cB]: aG, [cH]: al }, [ct]: n5 }, { endpoint: bx, [ct]: n5 }], [ct]: o5 }, { [cv]: [as, ar, aq, aD, aH], endpoint: bx, [ct]: n5 }], [ct]: o5 }, aR], [ct]: o5 }], [ct]: o5 }], [ct]: o5 }, { error: "A region must be set when sending requests to S3.", [ct]: f5 }] }; - exports.ruleSet = _data5; - } -}); - -// node_modules/.pnpm/@aws-sdk+client-s3@3.1030.0/node_modules/@aws-sdk/client-s3/dist-cjs/endpoint/endpointResolver.js -var require_endpointResolver = __commonJS({ - "node_modules/.pnpm/@aws-sdk+client-s3@3.1030.0/node_modules/@aws-sdk/client-s3/dist-cjs/endpoint/endpointResolver.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.defaultEndpointResolver = void 0; - var util_endpoints_1 = require_dist_cjs34(); - var util_endpoints_2 = require_dist_cjs33(); - var ruleset_1 = require_ruleset(); - var cache7 = new util_endpoints_2.EndpointCache({ - size: 50, - params: [ - "Accelerate", - "Bucket", - "DisableAccessPoints", - "DisableMultiRegionAccessPoints", - "DisableS3ExpressSessionAuth", - "Endpoint", - "ForcePathStyle", - "Region", - "UseArnRegion", - "UseDualStack", - "UseFIPS", - "UseGlobalEndpoint", - "UseObjectLambdaEndpoint", - "UseS3ExpressControlEndpoint" - ] - }); - var defaultEndpointResolver5 = (endpointParams, context = {}) => { - return cache7.get(endpointParams, () => (0, util_endpoints_2.resolveEndpoint)(ruleset_1.ruleSet, { - endpointParams, - logger: context.logger - })); - }; - exports.defaultEndpointResolver = defaultEndpointResolver5; - util_endpoints_2.customEndpointFunctions.aws = util_endpoints_1.awsEndpointFunctions; - } -}); - -// node_modules/.pnpm/@aws-sdk+client-s3@3.1030.0/node_modules/@aws-sdk/client-s3/dist-cjs/auth/httpAuthSchemeProvider.js -var require_httpAuthSchemeProvider = __commonJS({ - "node_modules/.pnpm/@aws-sdk+client-s3@3.1030.0/node_modules/@aws-sdk/client-s3/dist-cjs/auth/httpAuthSchemeProvider.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.resolveHttpAuthSchemeConfig = exports.defaultS3HttpAuthSchemeProvider = exports.defaultS3HttpAuthSchemeParametersProvider = void 0; - var httpAuthSchemes_1 = (init_httpAuthSchemes2(), __toCommonJS(httpAuthSchemes_exports)); - var signature_v4_multi_region_1 = require_dist_cjs47(); - var middleware_endpoint_1 = require_dist_cjs45(); - var util_middleware_1 = require_dist_cjs18(); - var endpointResolver_1 = require_endpointResolver(); - var createEndpointRuleSetHttpAuthSchemeParametersProvider = (defaultHttpAuthSchemeParametersProvider) => async (config3, context, input) => { - if (!input) { - throw new Error("Could not find `input` for `defaultEndpointRuleSetHttpAuthSchemeParametersProvider`"); - } - const defaultParameters = await defaultHttpAuthSchemeParametersProvider(config3, context, input); - const instructionsFn = (0, util_middleware_1.getSmithyContext)(context)?.commandInstance?.constructor?.getEndpointParameterInstructions; - if (!instructionsFn) { - throw new Error(`getEndpointParameterInstructions() is not defined on '${context.commandName}'`); - } - const endpointParameters = await (0, middleware_endpoint_1.resolveParams)(input, { getEndpointParameterInstructions: instructionsFn }, config3); - return Object.assign(defaultParameters, endpointParameters); - }; - var _defaultS3HttpAuthSchemeParametersProvider = async (config3, context, input) => { - return { - operation: (0, util_middleware_1.getSmithyContext)(context).operation, - region: await (0, util_middleware_1.normalizeProvider)(config3.region)() || (() => { - throw new Error("expected `region` to be configured for `aws.auth#sigv4`"); - })() - }; - }; - exports.defaultS3HttpAuthSchemeParametersProvider = createEndpointRuleSetHttpAuthSchemeParametersProvider(_defaultS3HttpAuthSchemeParametersProvider); - function createAwsAuthSigv4HttpAuthOption5(authParameters) { - return { - schemeId: "aws.auth#sigv4", - signingProperties: { - name: "s3", - region: authParameters.region - }, - propertiesExtractor: (config3, context) => ({ - signingProperties: { - config: config3, - context - } - }) - }; - } - function createAwsAuthSigv4aHttpAuthOption(authParameters) { - return { - schemeId: "aws.auth#sigv4a", - signingProperties: { - name: "s3", - region: authParameters.region - }, - propertiesExtractor: (config3, context) => ({ - signingProperties: { - config: config3, - context - } - }) - }; - } - var createEndpointRuleSetHttpAuthSchemeProvider = (defaultEndpointResolver5, defaultHttpAuthSchemeResolver, createHttpAuthOptionFunctions) => { - const endpointRuleSetHttpAuthSchemeProvider = (authParameters) => { - const endpoint = defaultEndpointResolver5(authParameters); - const authSchemes = endpoint.properties?.authSchemes; - if (!authSchemes) { - return defaultHttpAuthSchemeResolver(authParameters); - } - const options = []; - for (const scheme of authSchemes) { - const { name: resolvedName, properties = {}, ...rest } = scheme; - const name = resolvedName.toLowerCase(); - if (resolvedName !== name) { - console.warn(`HttpAuthScheme has been normalized with lowercasing: '${resolvedName}' to '${name}'`); - } - let schemeId; - if (name === "sigv4a") { - schemeId = "aws.auth#sigv4a"; - const sigv4Present = authSchemes.find((s5) => { - const name2 = s5.name.toLowerCase(); - return name2 !== "sigv4a" && name2.startsWith("sigv4"); - }); - if (signature_v4_multi_region_1.SignatureV4MultiRegion.sigv4aDependency() === "none" && sigv4Present) { - continue; - } - } else if (name.startsWith("sigv4")) { - schemeId = "aws.auth#sigv4"; - } else { - throw new Error(`Unknown HttpAuthScheme found in '@smithy.rules#endpointRuleSet': '${name}'`); - } - const createOption = createHttpAuthOptionFunctions[schemeId]; - if (!createOption) { - throw new Error(`Could not find HttpAuthOption create function for '${schemeId}'`); - } - const option = createOption(authParameters); - option.schemeId = schemeId; - option.signingProperties = { ...option.signingProperties || {}, ...rest, ...properties }; - options.push(option); - } - return options; - }; - return endpointRuleSetHttpAuthSchemeProvider; - }; - var _defaultS3HttpAuthSchemeProvider = (authParameters) => { - const options = []; - switch (authParameters.operation) { - default: { - options.push(createAwsAuthSigv4HttpAuthOption5(authParameters)); - options.push(createAwsAuthSigv4aHttpAuthOption(authParameters)); - } - } - return options; - }; - exports.defaultS3HttpAuthSchemeProvider = createEndpointRuleSetHttpAuthSchemeProvider(endpointResolver_1.defaultEndpointResolver, _defaultS3HttpAuthSchemeProvider, { - "aws.auth#sigv4": createAwsAuthSigv4HttpAuthOption5, - "aws.auth#sigv4a": createAwsAuthSigv4aHttpAuthOption - }); - var resolveHttpAuthSchemeConfig5 = (config3) => { - const config_0 = (0, httpAuthSchemes_1.resolveAwsSdkSigV4Config)(config3); - const config_1 = (0, httpAuthSchemes_1.resolveAwsSdkSigV4AConfig)(config_0); - return Object.assign(config_1, { - authSchemePreference: (0, util_middleware_1.normalizeProvider)(config3.authSchemePreference ?? []) - }); - }; - exports.resolveHttpAuthSchemeConfig = resolveHttpAuthSchemeConfig5; - } -}); - -// node_modules/.pnpm/@aws-sdk+client-s3@3.1030.0/node_modules/@aws-sdk/client-s3/dist-cjs/models/S3ServiceException.js -var require_S3ServiceException = __commonJS({ - "node_modules/.pnpm/@aws-sdk+client-s3@3.1030.0/node_modules/@aws-sdk/client-s3/dist-cjs/models/S3ServiceException.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.S3ServiceException = exports.__ServiceException = void 0; - var smithy_client_1 = require_dist_cjs27(); - Object.defineProperty(exports, "__ServiceException", { enumerable: true, get: function() { - return smithy_client_1.ServiceException; - } }); - var S3ServiceException = class _S3ServiceException extends smithy_client_1.ServiceException { - constructor(options) { - super(options); - Object.setPrototypeOf(this, _S3ServiceException.prototype); - } - }; - exports.S3ServiceException = S3ServiceException; - } -}); - -// node_modules/.pnpm/@aws-sdk+client-s3@3.1030.0/node_modules/@aws-sdk/client-s3/dist-cjs/models/errors.js -var require_errors = __commonJS({ - "node_modules/.pnpm/@aws-sdk+client-s3@3.1030.0/node_modules/@aws-sdk/client-s3/dist-cjs/models/errors.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.ObjectAlreadyInActiveTierError = exports.IdempotencyParameterMismatch = exports.TooManyParts = exports.InvalidWriteOffset = exports.InvalidRequest = exports.EncryptionTypeMismatch = exports.NotFound = exports.NoSuchKey = exports.InvalidObjectState = exports.NoSuchBucket = exports.BucketAlreadyOwnedByYou = exports.BucketAlreadyExists = exports.ObjectNotInActiveTierError = exports.AccessDenied = exports.NoSuchUpload = void 0; - var S3ServiceException_1 = require_S3ServiceException(); - var NoSuchUpload = class _NoSuchUpload extends S3ServiceException_1.S3ServiceException { - name = "NoSuchUpload"; - $fault = "client"; - constructor(opts) { - super({ - name: "NoSuchUpload", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _NoSuchUpload.prototype); - } - }; - exports.NoSuchUpload = NoSuchUpload; - var AccessDenied = class _AccessDenied extends S3ServiceException_1.S3ServiceException { - name = "AccessDenied"; - $fault = "client"; - constructor(opts) { - super({ - name: "AccessDenied", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _AccessDenied.prototype); - } - }; - exports.AccessDenied = AccessDenied; - var ObjectNotInActiveTierError = class _ObjectNotInActiveTierError extends S3ServiceException_1.S3ServiceException { - name = "ObjectNotInActiveTierError"; - $fault = "client"; - constructor(opts) { - super({ - name: "ObjectNotInActiveTierError", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _ObjectNotInActiveTierError.prototype); - } - }; - exports.ObjectNotInActiveTierError = ObjectNotInActiveTierError; - var BucketAlreadyExists = class _BucketAlreadyExists extends S3ServiceException_1.S3ServiceException { - name = "BucketAlreadyExists"; - $fault = "client"; - constructor(opts) { - super({ - name: "BucketAlreadyExists", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _BucketAlreadyExists.prototype); - } - }; - exports.BucketAlreadyExists = BucketAlreadyExists; - var BucketAlreadyOwnedByYou = class _BucketAlreadyOwnedByYou extends S3ServiceException_1.S3ServiceException { - name = "BucketAlreadyOwnedByYou"; - $fault = "client"; - constructor(opts) { - super({ - name: "BucketAlreadyOwnedByYou", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _BucketAlreadyOwnedByYou.prototype); - } - }; - exports.BucketAlreadyOwnedByYou = BucketAlreadyOwnedByYou; - var NoSuchBucket = class _NoSuchBucket extends S3ServiceException_1.S3ServiceException { - name = "NoSuchBucket"; - $fault = "client"; - constructor(opts) { - super({ - name: "NoSuchBucket", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _NoSuchBucket.prototype); - } - }; - exports.NoSuchBucket = NoSuchBucket; - var InvalidObjectState = class _InvalidObjectState extends S3ServiceException_1.S3ServiceException { - name = "InvalidObjectState"; - $fault = "client"; - StorageClass; - AccessTier; - constructor(opts) { - super({ - name: "InvalidObjectState", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _InvalidObjectState.prototype); - this.StorageClass = opts.StorageClass; - this.AccessTier = opts.AccessTier; - } - }; - exports.InvalidObjectState = InvalidObjectState; - var NoSuchKey = class _NoSuchKey extends S3ServiceException_1.S3ServiceException { - name = "NoSuchKey"; - $fault = "client"; - constructor(opts) { - super({ - name: "NoSuchKey", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _NoSuchKey.prototype); - } - }; - exports.NoSuchKey = NoSuchKey; - var NotFound = class _NotFound extends S3ServiceException_1.S3ServiceException { - name = "NotFound"; - $fault = "client"; - constructor(opts) { - super({ - name: "NotFound", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _NotFound.prototype); - } - }; - exports.NotFound = NotFound; - var EncryptionTypeMismatch = class _EncryptionTypeMismatch extends S3ServiceException_1.S3ServiceException { - name = "EncryptionTypeMismatch"; - $fault = "client"; - constructor(opts) { - super({ - name: "EncryptionTypeMismatch", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _EncryptionTypeMismatch.prototype); - } - }; - exports.EncryptionTypeMismatch = EncryptionTypeMismatch; - var InvalidRequest = class _InvalidRequest extends S3ServiceException_1.S3ServiceException { - name = "InvalidRequest"; - $fault = "client"; - constructor(opts) { - super({ - name: "InvalidRequest", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _InvalidRequest.prototype); - } - }; - exports.InvalidRequest = InvalidRequest; - var InvalidWriteOffset = class _InvalidWriteOffset extends S3ServiceException_1.S3ServiceException { - name = "InvalidWriteOffset"; - $fault = "client"; - constructor(opts) { - super({ - name: "InvalidWriteOffset", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _InvalidWriteOffset.prototype); - } - }; - exports.InvalidWriteOffset = InvalidWriteOffset; - var TooManyParts = class _TooManyParts extends S3ServiceException_1.S3ServiceException { - name = "TooManyParts"; - $fault = "client"; - constructor(opts) { - super({ - name: "TooManyParts", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _TooManyParts.prototype); - } - }; - exports.TooManyParts = TooManyParts; - var IdempotencyParameterMismatch = class _IdempotencyParameterMismatch extends S3ServiceException_1.S3ServiceException { - name = "IdempotencyParameterMismatch"; - $fault = "client"; - constructor(opts) { - super({ - name: "IdempotencyParameterMismatch", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _IdempotencyParameterMismatch.prototype); - } - }; - exports.IdempotencyParameterMismatch = IdempotencyParameterMismatch; - var ObjectAlreadyInActiveTierError = class _ObjectAlreadyInActiveTierError extends S3ServiceException_1.S3ServiceException { - name = "ObjectAlreadyInActiveTierError"; - $fault = "client"; - constructor(opts) { - super({ - name: "ObjectAlreadyInActiveTierError", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _ObjectAlreadyInActiveTierError.prototype); - } - }; - exports.ObjectAlreadyInActiveTierError = ObjectAlreadyInActiveTierError; - } -}); - -// node_modules/.pnpm/@aws-sdk+client-s3@3.1030.0/node_modules/@aws-sdk/client-s3/dist-cjs/schemas/schemas_0.js -var require_schemas_0 = __commonJS({ - "node_modules/.pnpm/@aws-sdk+client-s3@3.1030.0/node_modules/@aws-sdk/client-s3/dist-cjs/schemas/schemas_0.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.CreateBucketMetadataTableConfigurationRequest$ = exports.CreateBucketMetadataConfigurationRequest$ = exports.CreateBucketConfiguration$ = exports.CORSRule$ = exports.CORSConfiguration$ = exports.CopyPartResult$ = exports.CopyObjectResult$ = exports.CopyObjectRequest$ = exports.CopyObjectOutput$ = exports.ContinuationEvent$ = exports.Condition$ = exports.CompleteMultipartUploadRequest$ = exports.CompleteMultipartUploadOutput$ = exports.CompletedPart$ = exports.CompletedMultipartUpload$ = exports.CommonPrefix$ = exports.Checksum$ = exports.BucketLoggingStatus$ = exports.BucketLifecycleConfiguration$ = exports.BucketInfo$ = exports.Bucket$ = exports.BlockedEncryptionTypes$ = exports.AnalyticsS3BucketDestination$ = exports.AnalyticsExportDestination$ = exports.AnalyticsConfiguration$ = exports.AnalyticsAndOperator$ = exports.AccessControlTranslation$ = exports.AccessControlPolicy$ = exports.AccelerateConfiguration$ = exports.AbortMultipartUploadRequest$ = exports.AbortMultipartUploadOutput$ = exports.AbortIncompleteMultipartUpload$ = exports.AbacStatus$ = exports.errorTypeRegistries = exports.TooManyParts$ = exports.ObjectNotInActiveTierError$ = exports.ObjectAlreadyInActiveTierError$ = exports.NotFound$ = exports.NoSuchUpload$ = exports.NoSuchKey$ = exports.NoSuchBucket$ = exports.InvalidWriteOffset$ = exports.InvalidRequest$ = exports.InvalidObjectState$ = exports.IdempotencyParameterMismatch$ = exports.EncryptionTypeMismatch$ = exports.BucketAlreadyOwnedByYou$ = exports.BucketAlreadyExists$ = exports.AccessDenied$ = exports.S3ServiceException$ = void 0; - exports.GetBucketAccelerateConfigurationRequest$ = exports.GetBucketAccelerateConfigurationOutput$ = exports.GetBucketAbacRequest$ = exports.GetBucketAbacOutput$ = exports.FilterRule$ = exports.ExistingObjectReplication$ = exports.EventBridgeConfiguration$ = exports.ErrorDocument$ = exports.ErrorDetails$ = exports._Error$ = exports.EndEvent$ = exports.EncryptionConfiguration$ = exports.Encryption$ = exports.DestinationResult$ = exports.Destination$ = exports.DeletePublicAccessBlockRequest$ = exports.DeleteObjectTaggingRequest$ = exports.DeleteObjectTaggingOutput$ = exports.DeleteObjectsRequest$ = exports.DeleteObjectsOutput$ = exports.DeleteObjectRequest$ = exports.DeleteObjectOutput$ = exports.DeleteMarkerReplication$ = exports.DeleteMarkerEntry$ = exports.DeletedObject$ = exports.DeleteBucketWebsiteRequest$ = exports.DeleteBucketTaggingRequest$ = exports.DeleteBucketRequest$ = exports.DeleteBucketReplicationRequest$ = exports.DeleteBucketPolicyRequest$ = exports.DeleteBucketOwnershipControlsRequest$ = exports.DeleteBucketMetricsConfigurationRequest$ = exports.DeleteBucketMetadataTableConfigurationRequest$ = exports.DeleteBucketMetadataConfigurationRequest$ = exports.DeleteBucketLifecycleRequest$ = exports.DeleteBucketInventoryConfigurationRequest$ = exports.DeleteBucketIntelligentTieringConfigurationRequest$ = exports.DeleteBucketEncryptionRequest$ = exports.DeleteBucketCorsRequest$ = exports.DeleteBucketAnalyticsConfigurationRequest$ = exports.Delete$ = exports.DefaultRetention$ = exports.CSVOutput$ = exports.CSVInput$ = exports.CreateSessionRequest$ = exports.CreateSessionOutput$ = exports.CreateMultipartUploadRequest$ = exports.CreateMultipartUploadOutput$ = exports.CreateBucketRequest$ = exports.CreateBucketOutput$ = void 0; - exports.GetObjectLegalHoldRequest$ = exports.GetObjectLegalHoldOutput$ = exports.GetObjectAttributesRequest$ = exports.GetObjectAttributesParts$ = exports.GetObjectAttributesOutput$ = exports.GetObjectAclRequest$ = exports.GetObjectAclOutput$ = exports.GetBucketWebsiteRequest$ = exports.GetBucketWebsiteOutput$ = exports.GetBucketVersioningRequest$ = exports.GetBucketVersioningOutput$ = exports.GetBucketTaggingRequest$ = exports.GetBucketTaggingOutput$ = exports.GetBucketRequestPaymentRequest$ = exports.GetBucketRequestPaymentOutput$ = exports.GetBucketReplicationRequest$ = exports.GetBucketReplicationOutput$ = exports.GetBucketPolicyStatusRequest$ = exports.GetBucketPolicyStatusOutput$ = exports.GetBucketPolicyRequest$ = exports.GetBucketPolicyOutput$ = exports.GetBucketOwnershipControlsRequest$ = exports.GetBucketOwnershipControlsOutput$ = exports.GetBucketNotificationConfigurationRequest$ = exports.GetBucketMetricsConfigurationRequest$ = exports.GetBucketMetricsConfigurationOutput$ = exports.GetBucketMetadataTableConfigurationResult$ = exports.GetBucketMetadataTableConfigurationRequest$ = exports.GetBucketMetadataTableConfigurationOutput$ = exports.GetBucketMetadataConfigurationResult$ = exports.GetBucketMetadataConfigurationRequest$ = exports.GetBucketMetadataConfigurationOutput$ = exports.GetBucketLoggingRequest$ = exports.GetBucketLoggingOutput$ = exports.GetBucketLocationRequest$ = exports.GetBucketLocationOutput$ = exports.GetBucketLifecycleConfigurationRequest$ = exports.GetBucketLifecycleConfigurationOutput$ = exports.GetBucketInventoryConfigurationRequest$ = exports.GetBucketInventoryConfigurationOutput$ = exports.GetBucketIntelligentTieringConfigurationRequest$ = exports.GetBucketIntelligentTieringConfigurationOutput$ = exports.GetBucketEncryptionRequest$ = exports.GetBucketEncryptionOutput$ = exports.GetBucketCorsRequest$ = exports.GetBucketCorsOutput$ = exports.GetBucketAnalyticsConfigurationRequest$ = exports.GetBucketAnalyticsConfigurationOutput$ = exports.GetBucketAclRequest$ = exports.GetBucketAclOutput$ = void 0; - exports.ListBucketInventoryConfigurationsRequest$ = exports.ListBucketInventoryConfigurationsOutput$ = exports.ListBucketIntelligentTieringConfigurationsRequest$ = exports.ListBucketIntelligentTieringConfigurationsOutput$ = exports.ListBucketAnalyticsConfigurationsRequest$ = exports.ListBucketAnalyticsConfigurationsOutput$ = exports.LifecycleRuleFilter$ = exports.LifecycleRuleAndOperator$ = exports.LifecycleRule$ = exports.LifecycleExpiration$ = exports.LambdaFunctionConfiguration$ = exports.JSONOutput$ = exports.JSONInput$ = exports.JournalTableConfigurationUpdates$ = exports.JournalTableConfigurationResult$ = exports.JournalTableConfiguration$ = exports.InventoryTableConfigurationUpdates$ = exports.InventoryTableConfigurationResult$ = exports.InventoryTableConfiguration$ = exports.InventorySchedule$ = exports.InventoryS3BucketDestination$ = exports.InventoryFilter$ = exports.InventoryEncryption$ = exports.InventoryDestination$ = exports.InventoryConfiguration$ = exports.IntelligentTieringFilter$ = exports.IntelligentTieringConfiguration$ = exports.IntelligentTieringAndOperator$ = exports.InputSerialization$ = exports.Initiator$ = exports.IndexDocument$ = exports.HeadObjectRequest$ = exports.HeadObjectOutput$ = exports.HeadBucketRequest$ = exports.HeadBucketOutput$ = exports.Grantee$ = exports.Grant$ = exports.GlacierJobParameters$ = exports.GetPublicAccessBlockRequest$ = exports.GetPublicAccessBlockOutput$ = exports.GetObjectTorrentRequest$ = exports.GetObjectTorrentOutput$ = exports.GetObjectTaggingRequest$ = exports.GetObjectTaggingOutput$ = exports.GetObjectRetentionRequest$ = exports.GetObjectRetentionOutput$ = exports.GetObjectRequest$ = exports.GetObjectOutput$ = exports.GetObjectLockConfigurationRequest$ = exports.GetObjectLockConfigurationOutput$ = void 0; - exports.Progress$ = exports.PolicyStatus$ = exports.PartitionedPrefix$ = exports.Part$ = exports.ParquetInput$ = exports.OwnershipControlsRule$ = exports.OwnershipControls$ = exports.Owner$ = exports.OutputSerialization$ = exports.OutputLocation$ = exports.ObjectVersion$ = exports.ObjectPart$ = exports.ObjectLockRule$ = exports.ObjectLockRetention$ = exports.ObjectLockLegalHold$ = exports.ObjectLockConfiguration$ = exports.ObjectIdentifier$ = exports._Object$ = exports.NotificationConfigurationFilter$ = exports.NotificationConfiguration$ = exports.NoncurrentVersionTransition$ = exports.NoncurrentVersionExpiration$ = exports.MultipartUpload$ = exports.MetricsConfiguration$ = exports.MetricsAndOperator$ = exports.Metrics$ = exports.MetadataTableEncryptionConfiguration$ = exports.MetadataTableConfigurationResult$ = exports.MetadataTableConfiguration$ = exports.MetadataEntry$ = exports.MetadataConfigurationResult$ = exports.MetadataConfiguration$ = exports.LoggingEnabled$ = exports.LocationInfo$ = exports.ListPartsRequest$ = exports.ListPartsOutput$ = exports.ListObjectVersionsRequest$ = exports.ListObjectVersionsOutput$ = exports.ListObjectsV2Request$ = exports.ListObjectsV2Output$ = exports.ListObjectsRequest$ = exports.ListObjectsOutput$ = exports.ListMultipartUploadsRequest$ = exports.ListMultipartUploadsOutput$ = exports.ListDirectoryBucketsRequest$ = exports.ListDirectoryBucketsOutput$ = exports.ListBucketsRequest$ = exports.ListBucketsOutput$ = exports.ListBucketMetricsConfigurationsRequest$ = exports.ListBucketMetricsConfigurationsOutput$ = void 0; - exports.RequestPaymentConfiguration$ = exports.ReplicationTimeValue$ = exports.ReplicationTime$ = exports.ReplicationRuleFilter$ = exports.ReplicationRuleAndOperator$ = exports.ReplicationRule$ = exports.ReplicationConfiguration$ = exports.ReplicaModifications$ = exports.RenameObjectRequest$ = exports.RenameObjectOutput$ = exports.RedirectAllRequestsTo$ = exports.Redirect$ = exports.RecordsEvent$ = exports.RecordExpiration$ = exports.QueueConfiguration$ = exports.PutPublicAccessBlockRequest$ = exports.PutObjectTaggingRequest$ = exports.PutObjectTaggingOutput$ = exports.PutObjectRetentionRequest$ = exports.PutObjectRetentionOutput$ = exports.PutObjectRequest$ = exports.PutObjectOutput$ = exports.PutObjectLockConfigurationRequest$ = exports.PutObjectLockConfigurationOutput$ = exports.PutObjectLegalHoldRequest$ = exports.PutObjectLegalHoldOutput$ = exports.PutObjectAclRequest$ = exports.PutObjectAclOutput$ = exports.PutBucketWebsiteRequest$ = exports.PutBucketVersioningRequest$ = exports.PutBucketTaggingRequest$ = exports.PutBucketRequestPaymentRequest$ = exports.PutBucketReplicationRequest$ = exports.PutBucketPolicyRequest$ = exports.PutBucketOwnershipControlsRequest$ = exports.PutBucketNotificationConfigurationRequest$ = exports.PutBucketMetricsConfigurationRequest$ = exports.PutBucketLoggingRequest$ = exports.PutBucketLifecycleConfigurationRequest$ = exports.PutBucketLifecycleConfigurationOutput$ = exports.PutBucketInventoryConfigurationRequest$ = exports.PutBucketIntelligentTieringConfigurationRequest$ = exports.PutBucketEncryptionRequest$ = exports.PutBucketCorsRequest$ = exports.PutBucketAnalyticsConfigurationRequest$ = exports.PutBucketAclRequest$ = exports.PutBucketAccelerateConfigurationRequest$ = exports.PutBucketAbacRequest$ = exports.PublicAccessBlockConfiguration$ = exports.ProgressEvent$ = void 0; - exports.SelectObjectContentEventStream$ = exports.ObjectEncryption$ = exports.MetricsFilter$ = exports.AnalyticsFilter$ = exports.WriteGetObjectResponseRequest$ = exports.WebsiteConfiguration$ = exports.VersioningConfiguration$ = exports.UploadPartRequest$ = exports.UploadPartOutput$ = exports.UploadPartCopyRequest$ = exports.UploadPartCopyOutput$ = exports.UpdateObjectEncryptionResponse$ = exports.UpdateObjectEncryptionRequest$ = exports.UpdateBucketMetadataJournalTableConfigurationRequest$ = exports.UpdateBucketMetadataInventoryTableConfigurationRequest$ = exports.Transition$ = exports.TopicConfiguration$ = exports.Tiering$ = exports.TargetObjectKeyFormat$ = exports.TargetGrant$ = exports.Tagging$ = exports.Tag$ = exports.StorageClassAnalysisDataExport$ = exports.StorageClassAnalysis$ = exports.StatsEvent$ = exports.Stats$ = exports.SSES3$ = exports.SSEKMSEncryption$ = exports.SseKmsEncryptedObjects$ = exports.SSEKMS$ = exports.SourceSelectionCriteria$ = exports.SimplePrefix$ = exports.SessionCredentials$ = exports.ServerSideEncryptionRule$ = exports.ServerSideEncryptionConfiguration$ = exports.ServerSideEncryptionByDefault$ = exports.SelectParameters$ = exports.SelectObjectContentRequest$ = exports.SelectObjectContentOutput$ = exports.ScanRange$ = exports.S3TablesDestinationResult$ = exports.S3TablesDestination$ = exports.S3Location$ = exports.S3KeyFilter$ = exports.RoutingRule$ = exports.RestoreStatus$ = exports.RestoreRequest$ = exports.RestoreObjectRequest$ = exports.RestoreObjectOutput$ = exports.RequestProgress$ = void 0; - exports.GetBucketWebsite$ = exports.GetBucketVersioning$ = exports.GetBucketTagging$ = exports.GetBucketRequestPayment$ = exports.GetBucketReplication$ = exports.GetBucketPolicyStatus$ = exports.GetBucketPolicy$ = exports.GetBucketOwnershipControls$ = exports.GetBucketNotificationConfiguration$ = exports.GetBucketMetricsConfiguration$ = exports.GetBucketMetadataTableConfiguration$ = exports.GetBucketMetadataConfiguration$ = exports.GetBucketLogging$ = exports.GetBucketLocation$ = exports.GetBucketLifecycleConfiguration$ = exports.GetBucketInventoryConfiguration$ = exports.GetBucketIntelligentTieringConfiguration$ = exports.GetBucketEncryption$ = exports.GetBucketCors$ = exports.GetBucketAnalyticsConfiguration$ = exports.GetBucketAcl$ = exports.GetBucketAccelerateConfiguration$ = exports.GetBucketAbac$ = exports.DeletePublicAccessBlock$ = exports.DeleteObjectTagging$ = exports.DeleteObjects$ = exports.DeleteObject$ = exports.DeleteBucketWebsite$ = exports.DeleteBucketTagging$ = exports.DeleteBucketReplication$ = exports.DeleteBucketPolicy$ = exports.DeleteBucketOwnershipControls$ = exports.DeleteBucketMetricsConfiguration$ = exports.DeleteBucketMetadataTableConfiguration$ = exports.DeleteBucketMetadataConfiguration$ = exports.DeleteBucketLifecycle$ = exports.DeleteBucketInventoryConfiguration$ = exports.DeleteBucketIntelligentTieringConfiguration$ = exports.DeleteBucketEncryption$ = exports.DeleteBucketCors$ = exports.DeleteBucketAnalyticsConfiguration$ = exports.DeleteBucket$ = exports.CreateSession$ = exports.CreateMultipartUpload$ = exports.CreateBucketMetadataTableConfiguration$ = exports.CreateBucketMetadataConfiguration$ = exports.CreateBucket$ = exports.CopyObject$ = exports.CompleteMultipartUpload$ = exports.AbortMultipartUpload$ = void 0; - exports.RestoreObject$ = exports.RenameObject$ = exports.PutPublicAccessBlock$ = exports.PutObjectTagging$ = exports.PutObjectRetention$ = exports.PutObjectLockConfiguration$ = exports.PutObjectLegalHold$ = exports.PutObjectAcl$ = exports.PutObject$ = exports.PutBucketWebsite$ = exports.PutBucketVersioning$ = exports.PutBucketTagging$ = exports.PutBucketRequestPayment$ = exports.PutBucketReplication$ = exports.PutBucketPolicy$ = exports.PutBucketOwnershipControls$ = exports.PutBucketNotificationConfiguration$ = exports.PutBucketMetricsConfiguration$ = exports.PutBucketLogging$ = exports.PutBucketLifecycleConfiguration$ = exports.PutBucketInventoryConfiguration$ = exports.PutBucketIntelligentTieringConfiguration$ = exports.PutBucketEncryption$ = exports.PutBucketCors$ = exports.PutBucketAnalyticsConfiguration$ = exports.PutBucketAcl$ = exports.PutBucketAccelerateConfiguration$ = exports.PutBucketAbac$ = exports.ListParts$ = exports.ListObjectVersions$ = exports.ListObjectsV2$ = exports.ListObjects$ = exports.ListMultipartUploads$ = exports.ListDirectoryBuckets$ = exports.ListBuckets$ = exports.ListBucketMetricsConfigurations$ = exports.ListBucketInventoryConfigurations$ = exports.ListBucketIntelligentTieringConfigurations$ = exports.ListBucketAnalyticsConfigurations$ = exports.HeadObject$ = exports.HeadBucket$ = exports.GetPublicAccessBlock$ = exports.GetObjectTorrent$ = exports.GetObjectTagging$ = exports.GetObjectRetention$ = exports.GetObjectLockConfiguration$ = exports.GetObjectLegalHold$ = exports.GetObjectAttributes$ = exports.GetObjectAcl$ = exports.GetObject$ = void 0; - exports.WriteGetObjectResponse$ = exports.UploadPartCopy$ = exports.UploadPart$ = exports.UpdateObjectEncryption$ = exports.UpdateBucketMetadataJournalTableConfiguration$ = exports.UpdateBucketMetadataInventoryTableConfiguration$ = exports.SelectObjectContent$ = void 0; - var _A2 = "Account"; - var _AAO = "AnalyticsAndOperator"; - var _AC = "AccelerateConfiguration"; - var _ACL = "AccessControlList"; - var _ACL_ = "ACL"; - var _ACLn = "AnalyticsConfigurationList"; - var _ACP = "AccessControlPolicy"; - var _ACT = "AccessControlTranslation"; - var _ACn = "AnalyticsConfiguration"; - var _AD = "AccessDenied"; - var _ADb = "AbortDate"; - var _AED = "AnalyticsExportDestination"; - var _AF = "AnalyticsFilter"; - var _AH = "AllowedHeaders"; - var _AHl = "AllowedHeader"; - var _AI = "AccountId"; - var _AIMU = "AbortIncompleteMultipartUpload"; - var _AKI2 = "AccessKeyId"; - var _AM = "AllowedMethods"; - var _AMU = "AbortMultipartUpload"; - var _AMUO = "AbortMultipartUploadOutput"; - var _AMUR = "AbortMultipartUploadRequest"; - var _AMl = "AllowedMethod"; - var _AO = "AllowedOrigins"; - var _AOl = "AllowedOrigin"; - var _APA = "AccessPointAlias"; - var _APAc = "AccessPointArn"; - var _AQRD = "AllowQuotedRecordDelimiter"; - var _AR2 = "AcceptRanges"; - var _ARI2 = "AbortRuleId"; - var _AS = "AbacStatus"; - var _ASBD = "AnalyticsS3BucketDestination"; - var _ASSEBD = "ApplyServerSideEncryptionByDefault"; - var _ASr = "ArchiveStatus"; - var _AT3 = "AccessTier"; - var _An = "And"; - var _B = "Bucket"; - var _BA = "BucketArn"; - var _BAE = "BucketAlreadyExists"; - var _BAI = "BucketAccountId"; - var _BAOBY = "BucketAlreadyOwnedByYou"; - var _BET = "BlockedEncryptionTypes"; - var _BGR = "BypassGovernanceRetention"; - var _BI = "BucketInfo"; - var _BKE = "BucketKeyEnabled"; - var _BLC = "BucketLifecycleConfiguration"; - var _BLN = "BucketLocationName"; - var _BLS = "BucketLoggingStatus"; - var _BLT = "BucketLocationType"; - var _BN = "BucketNamespace"; - var _BNu = "BucketName"; - var _BP = "BytesProcessed"; - var _BPA = "BlockPublicAcls"; - var _BPP = "BlockPublicPolicy"; - var _BR = "BucketRegion"; - var _BRy = "BytesReturned"; - var _BS = "BytesScanned"; - var _Bo = "Body"; - var _Bu = "Buckets"; - var _C2 = "Checksum"; - var _CA2 = "ChecksumAlgorithm"; - var _CACL = "CannedACL"; - var _CB = "CreateBucket"; - var _CBC = "CreateBucketConfiguration"; - var _CBMC = "CreateBucketMetadataConfiguration"; - var _CBMCR = "CreateBucketMetadataConfigurationRequest"; - var _CBMTC = "CreateBucketMetadataTableConfiguration"; - var _CBMTCR = "CreateBucketMetadataTableConfigurationRequest"; - var _CBO = "CreateBucketOutput"; - var _CBR = "CreateBucketRequest"; - var _CC = "CacheControl"; - var _CCRC = "ChecksumCRC32"; - var _CCRCC = "ChecksumCRC32C"; - var _CCRCNVME = "ChecksumCRC64NVME"; - var _CC_ = "Cache-Control"; - var _CD = "CreationDate"; - var _CD_ = "Content-Disposition"; - var _CDo = "ContentDisposition"; - var _CE = "ContinuationEvent"; - var _CE_ = "Content-Encoding"; - var _CEo = "ContentEncoding"; - var _CF = "CloudFunction"; - var _CFC = "CloudFunctionConfiguration"; - var _CL = "ContentLanguage"; - var _CL_ = "Content-Language"; - var _CL__ = "Content-Length"; - var _CLo = "ContentLength"; - var _CM = "Content-MD5"; - var _CMD = "ContentMD5"; - var _CMU = "CompletedMultipartUpload"; - var _CMUO = "CompleteMultipartUploadOutput"; - var _CMUOr = "CreateMultipartUploadOutput"; - var _CMUR = "CompleteMultipartUploadResult"; - var _CMURo = "CompleteMultipartUploadRequest"; - var _CMURr = "CreateMultipartUploadRequest"; - var _CMUo = "CompleteMultipartUpload"; - var _CMUr = "CreateMultipartUpload"; - var _CMh = "ChecksumMode"; - var _CO = "CopyObject"; - var _COO = "CopyObjectOutput"; - var _COR = "CopyObjectResult"; - var _CORSC = "CORSConfiguration"; - var _CORSR = "CORSRules"; - var _CORSRu = "CORSRule"; - var _CORo = "CopyObjectRequest"; - var _CP = "CommonPrefix"; - var _CPL = "CommonPrefixList"; - var _CPLo = "CompletedPartList"; - var _CPR = "CopyPartResult"; - var _CPo = "CompletedPart"; - var _CPom = "CommonPrefixes"; - var _CR = "ContentRange"; - var _CRSBA = "ConfirmRemoveSelfBucketAccess"; - var _CR_ = "Content-Range"; - var _CS2 = "CopySource"; - var _CSHA = "ChecksumSHA1"; - var _CSHAh = "ChecksumSHA256"; - var _CSIM = "CopySourceIfMatch"; - var _CSIMS = "CopySourceIfModifiedSince"; - var _CSINM = "CopySourceIfNoneMatch"; - var _CSIUS = "CopySourceIfUnmodifiedSince"; - var _CSO = "CreateSessionOutput"; - var _CSR = "CreateSessionResult"; - var _CSRo = "CopySourceRange"; - var _CSRr = "CreateSessionRequest"; - var _CSSSECA = "CopySourceSSECustomerAlgorithm"; - var _CSSSECK = "CopySourceSSECustomerKey"; - var _CSSSECKMD = "CopySourceSSECustomerKeyMD5"; - var _CSV = "CSV"; - var _CSVI = "CopySourceVersionId"; - var _CSVIn = "CSVInput"; - var _CSVO = "CSVOutput"; - var _CSo = "ConfigurationState"; - var _CSr = "CreateSession"; - var _CT2 = "ChecksumType"; - var _CT_ = "Content-Type"; - var _CTl = "ClientToken"; - var _CTo = "ContentType"; - var _CTom = "CompressionType"; - var _CTon = "ContinuationToken"; - var _Co = "Condition"; - var _Cod = "Code"; - var _Com = "Comments"; - var _Con = "Contents"; - var _Cont = "Cont"; - var _Cr = "Credentials"; - var _D = "Days"; - var _DAI = "DaysAfterInitiation"; - var _DB = "DeleteBucket"; - var _DBAC = "DeleteBucketAnalyticsConfiguration"; - var _DBACR = "DeleteBucketAnalyticsConfigurationRequest"; - var _DBC = "DeleteBucketCors"; - var _DBCR = "DeleteBucketCorsRequest"; - var _DBE = "DeleteBucketEncryption"; - var _DBER = "DeleteBucketEncryptionRequest"; - var _DBIC = "DeleteBucketInventoryConfiguration"; - var _DBICR = "DeleteBucketInventoryConfigurationRequest"; - var _DBITC = "DeleteBucketIntelligentTieringConfiguration"; - var _DBITCR = "DeleteBucketIntelligentTieringConfigurationRequest"; - var _DBL = "DeleteBucketLifecycle"; - var _DBLR = "DeleteBucketLifecycleRequest"; - var _DBMC = "DeleteBucketMetadataConfiguration"; - var _DBMCR = "DeleteBucketMetadataConfigurationRequest"; - var _DBMCRe = "DeleteBucketMetricsConfigurationRequest"; - var _DBMCe = "DeleteBucketMetricsConfiguration"; - var _DBMTC = "DeleteBucketMetadataTableConfiguration"; - var _DBMTCR = "DeleteBucketMetadataTableConfigurationRequest"; - var _DBOC = "DeleteBucketOwnershipControls"; - var _DBOCR = "DeleteBucketOwnershipControlsRequest"; - var _DBP = "DeleteBucketPolicy"; - var _DBPR = "DeleteBucketPolicyRequest"; - var _DBR = "DeleteBucketRequest"; - var _DBRR = "DeleteBucketReplicationRequest"; - var _DBRe = "DeleteBucketReplication"; - var _DBT = "DeleteBucketTagging"; - var _DBTR = "DeleteBucketTaggingRequest"; - var _DBW = "DeleteBucketWebsite"; - var _DBWR = "DeleteBucketWebsiteRequest"; - var _DE = "DataExport"; - var _DIM = "DestinationIfMatch"; - var _DIMS = "DestinationIfModifiedSince"; - var _DINM = "DestinationIfNoneMatch"; - var _DIUS = "DestinationIfUnmodifiedSince"; - var _DM = "DeleteMarker"; - var _DME = "DeleteMarkerEntry"; - var _DMR = "DeleteMarkerReplication"; - var _DMVI = "DeleteMarkerVersionId"; - var _DMe = "DeleteMarkers"; - var _DN = "DisplayName"; - var _DO = "DeletedObject"; - var _DOO = "DeleteObjectOutput"; - var _DOOe = "DeleteObjectsOutput"; - var _DOR = "DeleteObjectRequest"; - var _DORe = "DeleteObjectsRequest"; - var _DOT = "DeleteObjectTagging"; - var _DOTO = "DeleteObjectTaggingOutput"; - var _DOTR = "DeleteObjectTaggingRequest"; - var _DOe = "DeletedObjects"; - var _DOel = "DeleteObject"; - var _DOele = "DeleteObjects"; - var _DPAB = "DeletePublicAccessBlock"; - var _DPABR = "DeletePublicAccessBlockRequest"; - var _DR = "DataRedundancy"; - var _DRe = "DefaultRetention"; - var _DRel = "DeleteResult"; - var _DRes = "DestinationResult"; - var _Da = "Date"; - var _De = "Delete"; - var _Del = "Deleted"; - var _Deli = "Delimiter"; - var _Des = "Destination"; - var _Desc = "Description"; - var _Det = "Details"; - var _E2 = "Expiration"; - var _EA = "EmailAddress"; - var _EBC = "EventBridgeConfiguration"; - var _EBO = "ExpectedBucketOwner"; - var _EC = "EncryptionConfiguration"; - var _ECr = "ErrorCode"; - var _ED = "ErrorDetails"; - var _EDr = "ErrorDocument"; - var _EE = "EndEvent"; - var _EH = "ExposeHeaders"; - var _EHx = "ExposeHeader"; - var _EM = "ErrorMessage"; - var _EODM = "ExpiredObjectDeleteMarker"; - var _EOR = "ExistingObjectReplication"; - var _ES = "ExpiresString"; - var _ESBO = "ExpectedSourceBucketOwner"; - var _ET = "EncryptionType"; - var _ETL = "EncryptionTypeList"; - var _ETM = "EncryptionTypeMismatch"; - var _ETa = "ETag"; - var _ETn = "EncodingType"; - var _ETv = "EventThreshold"; - var _ETx = "ExpressionType"; - var _En = "Encryption"; - var _Ena = "Enabled"; - var _End = "End"; - var _Er = "Errors"; - var _Err = "Error"; - var _Ev = "Events"; - var _Eve = "Event"; - var _Ex = "Expires"; - var _Exp = "Expression"; - var _F = "Filter"; - var _FD = "FieldDelimiter"; - var _FHI = "FileHeaderInfo"; - var _FO = "FetchOwner"; - var _FR = "FilterRule"; - var _FRL = "FilterRuleList"; - var _FRi = "FilterRules"; - var _Fi = "Field"; - var _Fo = "Format"; - var _Fr = "Frequency"; - var _G = "Grants"; - var _GBA = "GetBucketAbac"; - var _GBAC = "GetBucketAccelerateConfiguration"; - var _GBACO = "GetBucketAccelerateConfigurationOutput"; - var _GBACOe = "GetBucketAnalyticsConfigurationOutput"; - var _GBACR = "GetBucketAccelerateConfigurationRequest"; - var _GBACRe = "GetBucketAnalyticsConfigurationRequest"; - var _GBACe = "GetBucketAnalyticsConfiguration"; - var _GBAO = "GetBucketAbacOutput"; - var _GBAOe = "GetBucketAclOutput"; - var _GBAR = "GetBucketAbacRequest"; - var _GBARe = "GetBucketAclRequest"; - var _GBAe = "GetBucketAcl"; - var _GBC = "GetBucketCors"; - var _GBCO = "GetBucketCorsOutput"; - var _GBCR = "GetBucketCorsRequest"; - var _GBE = "GetBucketEncryption"; - var _GBEO = "GetBucketEncryptionOutput"; - var _GBER = "GetBucketEncryptionRequest"; - var _GBIC = "GetBucketInventoryConfiguration"; - var _GBICO = "GetBucketInventoryConfigurationOutput"; - var _GBICR = "GetBucketInventoryConfigurationRequest"; - var _GBITC = "GetBucketIntelligentTieringConfiguration"; - var _GBITCO = "GetBucketIntelligentTieringConfigurationOutput"; - var _GBITCR = "GetBucketIntelligentTieringConfigurationRequest"; - var _GBL = "GetBucketLocation"; - var _GBLC = "GetBucketLifecycleConfiguration"; - var _GBLCO = "GetBucketLifecycleConfigurationOutput"; - var _GBLCR = "GetBucketLifecycleConfigurationRequest"; - var _GBLO = "GetBucketLocationOutput"; - var _GBLOe = "GetBucketLoggingOutput"; - var _GBLR = "GetBucketLocationRequest"; - var _GBLRe = "GetBucketLoggingRequest"; - var _GBLe = "GetBucketLogging"; - var _GBMC = "GetBucketMetadataConfiguration"; - var _GBMCO = "GetBucketMetadataConfigurationOutput"; - var _GBMCOe = "GetBucketMetricsConfigurationOutput"; - var _GBMCR = "GetBucketMetadataConfigurationResult"; - var _GBMCRe = "GetBucketMetadataConfigurationRequest"; - var _GBMCRet = "GetBucketMetricsConfigurationRequest"; - var _GBMCe = "GetBucketMetricsConfiguration"; - var _GBMTC = "GetBucketMetadataTableConfiguration"; - var _GBMTCO = "GetBucketMetadataTableConfigurationOutput"; - var _GBMTCR = "GetBucketMetadataTableConfigurationResult"; - var _GBMTCRe = "GetBucketMetadataTableConfigurationRequest"; - var _GBNC = "GetBucketNotificationConfiguration"; - var _GBNCR = "GetBucketNotificationConfigurationRequest"; - var _GBOC = "GetBucketOwnershipControls"; - var _GBOCO = "GetBucketOwnershipControlsOutput"; - var _GBOCR = "GetBucketOwnershipControlsRequest"; - var _GBP = "GetBucketPolicy"; - var _GBPO = "GetBucketPolicyOutput"; - var _GBPR = "GetBucketPolicyRequest"; - var _GBPS = "GetBucketPolicyStatus"; - var _GBPSO = "GetBucketPolicyStatusOutput"; - var _GBPSR = "GetBucketPolicyStatusRequest"; - var _GBR = "GetBucketReplication"; - var _GBRO = "GetBucketReplicationOutput"; - var _GBRP = "GetBucketRequestPayment"; - var _GBRPO = "GetBucketRequestPaymentOutput"; - var _GBRPR = "GetBucketRequestPaymentRequest"; - var _GBRR = "GetBucketReplicationRequest"; - var _GBT = "GetBucketTagging"; - var _GBTO = "GetBucketTaggingOutput"; - var _GBTR = "GetBucketTaggingRequest"; - var _GBV = "GetBucketVersioning"; - var _GBVO = "GetBucketVersioningOutput"; - var _GBVR = "GetBucketVersioningRequest"; - var _GBW = "GetBucketWebsite"; - var _GBWO = "GetBucketWebsiteOutput"; - var _GBWR = "GetBucketWebsiteRequest"; - var _GFC = "GrantFullControl"; - var _GJP = "GlacierJobParameters"; - var _GO = "GetObject"; - var _GOA = "GetObjectAcl"; - var _GOAO = "GetObjectAclOutput"; - var _GOAOe = "GetObjectAttributesOutput"; - var _GOAP = "GetObjectAttributesParts"; - var _GOAR = "GetObjectAclRequest"; - var _GOARe = "GetObjectAttributesResponse"; - var _GOARet = "GetObjectAttributesRequest"; - var _GOAe = "GetObjectAttributes"; - var _GOLC = "GetObjectLockConfiguration"; - var _GOLCO = "GetObjectLockConfigurationOutput"; - var _GOLCR = "GetObjectLockConfigurationRequest"; - var _GOLH = "GetObjectLegalHold"; - var _GOLHO = "GetObjectLegalHoldOutput"; - var _GOLHR = "GetObjectLegalHoldRequest"; - var _GOO = "GetObjectOutput"; - var _GOR = "GetObjectRequest"; - var _GORO = "GetObjectRetentionOutput"; - var _GORR = "GetObjectRetentionRequest"; - var _GORe = "GetObjectRetention"; - var _GOT = "GetObjectTagging"; - var _GOTO = "GetObjectTaggingOutput"; - var _GOTOe = "GetObjectTorrentOutput"; - var _GOTR = "GetObjectTaggingRequest"; - var _GOTRe = "GetObjectTorrentRequest"; - var _GOTe = "GetObjectTorrent"; - var _GPAB = "GetPublicAccessBlock"; - var _GPABO = "GetPublicAccessBlockOutput"; - var _GPABR = "GetPublicAccessBlockRequest"; - var _GR = "GrantRead"; - var _GRACP = "GrantReadACP"; - var _GW = "GrantWrite"; - var _GWACP = "GrantWriteACP"; - var _Gr = "Grant"; - var _Gra = "Grantee"; - var _HB = "HeadBucket"; - var _HBO = "HeadBucketOutput"; - var _HBR = "HeadBucketRequest"; - var _HECRE = "HttpErrorCodeReturnedEquals"; - var _HN = "HostName"; - var _HO = "HeadObject"; - var _HOO = "HeadObjectOutput"; - var _HOR = "HeadObjectRequest"; - var _HRC = "HttpRedirectCode"; - var _I = "Id"; - var _IC = "InventoryConfiguration"; - var _ICL = "InventoryConfigurationList"; - var _ID = "ID"; - var _IDn = "IndexDocument"; - var _IDnv = "InventoryDestination"; - var _IE = "IsEnabled"; - var _IEn = "InventoryEncryption"; - var _IF = "InventoryFilter"; - var _IL = "IsLatest"; - var _IM = "IfMatch"; - var _IMIT = "IfMatchInitiatedTime"; - var _IMLMT = "IfMatchLastModifiedTime"; - var _IMS = "IfMatchSize"; - var _IMS_ = "If-Modified-Since"; - var _IMSf = "IfModifiedSince"; - var _IMUR = "InitiateMultipartUploadResult"; - var _IM_ = "If-Match"; - var _INM = "IfNoneMatch"; - var _INM_ = "If-None-Match"; - var _IOF = "InventoryOptionalFields"; - var _IOS = "InvalidObjectState"; - var _IOV = "IncludedObjectVersions"; - var _IP = "IsPublic"; - var _IPA = "IgnorePublicAcls"; - var _IPM = "IdempotencyParameterMismatch"; - var _IR = "InvalidRequest"; - var _IRIP = "IsRestoreInProgress"; - var _IS = "InputSerialization"; - var _ISBD = "InventoryS3BucketDestination"; - var _ISn = "InventorySchedule"; - var _IT2 = "IsTruncated"; - var _ITAO = "IntelligentTieringAndOperator"; - var _ITC = "IntelligentTieringConfiguration"; - var _ITCL = "IntelligentTieringConfigurationList"; - var _ITCR = "InventoryTableConfigurationResult"; - var _ITCU = "InventoryTableConfigurationUpdates"; - var _ITCn = "InventoryTableConfiguration"; - var _ITF = "IntelligentTieringFilter"; - var _IUS = "IfUnmodifiedSince"; - var _IUS_ = "If-Unmodified-Since"; - var _IWO = "InvalidWriteOffset"; - var _In = "Initiator"; - var _Ini = "Initiated"; - var _JSON = "JSON"; - var _JSONI = "JSONInput"; - var _JSONO = "JSONOutput"; - var _JTC = "JournalTableConfiguration"; - var _JTCR = "JournalTableConfigurationResult"; - var _JTCU = "JournalTableConfigurationUpdates"; - var _K2 = "Key"; - var _KC = "KeyCount"; - var _KI = "KeyId"; - var _KKA = "KmsKeyArn"; - var _KM = "KeyMarker"; - var _KMSC = "KMSContext"; - var _KMSKA = "KMSKeyArn"; - var _KMSKI = "KMSKeyId"; - var _KMSMKID = "KMSMasterKeyID"; - var _KPE = "KeyPrefixEquals"; - var _L = "Location"; - var _LAMBR = "ListAllMyBucketsResult"; - var _LAMDBR = "ListAllMyDirectoryBucketsResult"; - var _LB = "ListBuckets"; - var _LBAC = "ListBucketAnalyticsConfigurations"; - var _LBACO = "ListBucketAnalyticsConfigurationsOutput"; - var _LBACR = "ListBucketAnalyticsConfigurationResult"; - var _LBACRi = "ListBucketAnalyticsConfigurationsRequest"; - var _LBIC = "ListBucketInventoryConfigurations"; - var _LBICO = "ListBucketInventoryConfigurationsOutput"; - var _LBICR = "ListBucketInventoryConfigurationsRequest"; - var _LBITC = "ListBucketIntelligentTieringConfigurations"; - var _LBITCO = "ListBucketIntelligentTieringConfigurationsOutput"; - var _LBITCR = "ListBucketIntelligentTieringConfigurationsRequest"; - var _LBMC = "ListBucketMetricsConfigurations"; - var _LBMCO = "ListBucketMetricsConfigurationsOutput"; - var _LBMCR = "ListBucketMetricsConfigurationsRequest"; - var _LBO = "ListBucketsOutput"; - var _LBR = "ListBucketsRequest"; - var _LBRi = "ListBucketResult"; - var _LC = "LocationConstraint"; - var _LCi = "LifecycleConfiguration"; - var _LDB = "ListDirectoryBuckets"; - var _LDBO = "ListDirectoryBucketsOutput"; - var _LDBR = "ListDirectoryBucketsRequest"; - var _LE = "LoggingEnabled"; - var _LEi = "LifecycleExpiration"; - var _LFA = "LambdaFunctionArn"; - var _LFC = "LambdaFunctionConfiguration"; - var _LFCL = "LambdaFunctionConfigurationList"; - var _LFCa = "LambdaFunctionConfigurations"; - var _LH = "LegalHold"; - var _LI = "LocationInfo"; - var _LICR = "ListInventoryConfigurationsResult"; - var _LM = "LastModified"; - var _LMCR = "ListMetricsConfigurationsResult"; - var _LMT = "LastModifiedTime"; - var _LMU = "ListMultipartUploads"; - var _LMUO = "ListMultipartUploadsOutput"; - var _LMUR = "ListMultipartUploadsResult"; - var _LMURi = "ListMultipartUploadsRequest"; - var _LM_ = "Last-Modified"; - var _LO = "ListObjects"; - var _LOO = "ListObjectsOutput"; - var _LOR = "ListObjectsRequest"; - var _LOV = "ListObjectsV2"; - var _LOVO = "ListObjectsV2Output"; - var _LOVOi = "ListObjectVersionsOutput"; - var _LOVR = "ListObjectsV2Request"; - var _LOVRi = "ListObjectVersionsRequest"; - var _LOVi = "ListObjectVersions"; - var _LP = "ListParts"; - var _LPO = "ListPartsOutput"; - var _LPR = "ListPartsResult"; - var _LPRi = "ListPartsRequest"; - var _LR = "LifecycleRule"; - var _LRAO = "LifecycleRuleAndOperator"; - var _LRF = "LifecycleRuleFilter"; - var _LRi = "LifecycleRules"; - var _LVR = "ListVersionsResult"; - var _M = "Metadata"; - var _MAO = "MetricsAndOperator"; - var _MAS = "MaxAgeSeconds"; - var _MB = "MaxBuckets"; - var _MC = "MetadataConfiguration"; - var _MCL = "MetricsConfigurationList"; - var _MCR = "MetadataConfigurationResult"; - var _MCe = "MetricsConfiguration"; - var _MD = "MetadataDirective"; - var _MDB = "MaxDirectoryBuckets"; - var _MDf = "MfaDelete"; - var _ME = "MetadataEntry"; - var _MF = "MetricsFilter"; - var _MFA = "MFA"; - var _MFAD = "MFADelete"; - var _MK = "MaxKeys"; - var _MM = "MissingMeta"; - var _MOS = "MpuObjectSize"; - var _MP = "MaxParts"; - var _MTC = "MetadataTableConfiguration"; - var _MTCR = "MetadataTableConfigurationResult"; - var _MTEC = "MetadataTableEncryptionConfiguration"; - var _MU = "MultipartUpload"; - var _MUL = "MultipartUploadList"; - var _MUa = "MaxUploads"; - var _Ma = "Marker"; - var _Me = "Metrics"; - var _Mes = "Message"; - var _Mi = "Minutes"; - var _Mo = "Mode"; - var _N = "Name"; - var _NC = "NotificationConfiguration"; - var _NCF = "NotificationConfigurationFilter"; - var _NCT = "NextContinuationToken"; - var _ND = "NoncurrentDays"; - var _NEKKAS = "NonEmptyKmsKeyArnString"; - var _NF = "NotFound"; - var _NKM = "NextKeyMarker"; - var _NM = "NextMarker"; - var _NNV = "NewerNoncurrentVersions"; - var _NPNM = "NextPartNumberMarker"; - var _NSB = "NoSuchBucket"; - var _NSK = "NoSuchKey"; - var _NSU = "NoSuchUpload"; - var _NUIM = "NextUploadIdMarker"; - var _NVE = "NoncurrentVersionExpiration"; - var _NVIM = "NextVersionIdMarker"; - var _NVT = "NoncurrentVersionTransitions"; - var _NVTL = "NoncurrentVersionTransitionList"; - var _NVTo = "NoncurrentVersionTransition"; - var _O = "Owner"; - var _OA = "ObjectAttributes"; - var _OAIATE = "ObjectAlreadyInActiveTierError"; - var _OC = "OwnershipControls"; - var _OCR = "OwnershipControlsRule"; - var _OCRw = "OwnershipControlsRules"; - var _OE = "ObjectEncryption"; - var _OF = "OptionalFields"; - var _OI = "ObjectIdentifier"; - var _OIL = "ObjectIdentifierList"; - var _OL = "OutputLocation"; - var _OLC = "ObjectLockConfiguration"; - var _OLE = "ObjectLockEnabled"; - var _OLEFB = "ObjectLockEnabledForBucket"; - var _OLLH = "ObjectLockLegalHold"; - var _OLLHS = "ObjectLockLegalHoldStatus"; - var _OLM = "ObjectLockMode"; - var _OLR = "ObjectLockRetention"; - var _OLRUD = "ObjectLockRetainUntilDate"; - var _OLRb = "ObjectLockRule"; - var _OLb = "ObjectList"; - var _ONIATE = "ObjectNotInActiveTierError"; - var _OO = "ObjectOwnership"; - var _OOA = "OptionalObjectAttributes"; - var _OP = "ObjectParts"; - var _OPb = "ObjectPart"; - var _OS = "ObjectSize"; - var _OSGT = "ObjectSizeGreaterThan"; - var _OSLT = "ObjectSizeLessThan"; - var _OSV = "OutputSchemaVersion"; - var _OSu = "OutputSerialization"; - var _OV = "ObjectVersion"; - var _OVL = "ObjectVersionList"; - var _Ob = "Objects"; - var _Obj = "Object"; - var _P2 = "Prefix"; - var _PABC = "PublicAccessBlockConfiguration"; - var _PBA = "PutBucketAbac"; - var _PBAC = "PutBucketAccelerateConfiguration"; - var _PBACR = "PutBucketAccelerateConfigurationRequest"; - var _PBACRu = "PutBucketAnalyticsConfigurationRequest"; - var _PBACu = "PutBucketAnalyticsConfiguration"; - var _PBAR = "PutBucketAbacRequest"; - var _PBARu = "PutBucketAclRequest"; - var _PBAu = "PutBucketAcl"; - var _PBC = "PutBucketCors"; - var _PBCR = "PutBucketCorsRequest"; - var _PBE = "PutBucketEncryption"; - var _PBER = "PutBucketEncryptionRequest"; - var _PBIC = "PutBucketInventoryConfiguration"; - var _PBICR = "PutBucketInventoryConfigurationRequest"; - var _PBITC = "PutBucketIntelligentTieringConfiguration"; - var _PBITCR = "PutBucketIntelligentTieringConfigurationRequest"; - var _PBL = "PutBucketLogging"; - var _PBLC = "PutBucketLifecycleConfiguration"; - var _PBLCO = "PutBucketLifecycleConfigurationOutput"; - var _PBLCR = "PutBucketLifecycleConfigurationRequest"; - var _PBLR = "PutBucketLoggingRequest"; - var _PBMC = "PutBucketMetricsConfiguration"; - var _PBMCR = "PutBucketMetricsConfigurationRequest"; - var _PBNC = "PutBucketNotificationConfiguration"; - var _PBNCR = "PutBucketNotificationConfigurationRequest"; - var _PBOC = "PutBucketOwnershipControls"; - var _PBOCR = "PutBucketOwnershipControlsRequest"; - var _PBP = "PutBucketPolicy"; - var _PBPR = "PutBucketPolicyRequest"; - var _PBR = "PutBucketReplication"; - var _PBRP = "PutBucketRequestPayment"; - var _PBRPR = "PutBucketRequestPaymentRequest"; - var _PBRR = "PutBucketReplicationRequest"; - var _PBT = "PutBucketTagging"; - var _PBTR = "PutBucketTaggingRequest"; - var _PBV = "PutBucketVersioning"; - var _PBVR = "PutBucketVersioningRequest"; - var _PBW = "PutBucketWebsite"; - var _PBWR = "PutBucketWebsiteRequest"; - var _PC2 = "PartsCount"; - var _PDS = "PartitionDateSource"; - var _PE = "ProgressEvent"; - var _PI2 = "ParquetInput"; - var _PL = "PartsList"; - var _PN = "PartNumber"; - var _PNM = "PartNumberMarker"; - var _PO = "PutObject"; - var _POA = "PutObjectAcl"; - var _POAO = "PutObjectAclOutput"; - var _POAR = "PutObjectAclRequest"; - var _POLC = "PutObjectLockConfiguration"; - var _POLCO = "PutObjectLockConfigurationOutput"; - var _POLCR = "PutObjectLockConfigurationRequest"; - var _POLH = "PutObjectLegalHold"; - var _POLHO = "PutObjectLegalHoldOutput"; - var _POLHR = "PutObjectLegalHoldRequest"; - var _POO = "PutObjectOutput"; - var _POR = "PutObjectRequest"; - var _PORO = "PutObjectRetentionOutput"; - var _PORR = "PutObjectRetentionRequest"; - var _PORu = "PutObjectRetention"; - var _POT = "PutObjectTagging"; - var _POTO = "PutObjectTaggingOutput"; - var _POTR = "PutObjectTaggingRequest"; - var _PP = "PartitionedPrefix"; - var _PPAB = "PutPublicAccessBlock"; - var _PPABR = "PutPublicAccessBlockRequest"; - var _PS = "PolicyStatus"; - var _Pa = "Parts"; - var _Par = "Part"; - var _Parq = "Parquet"; - var _Pay = "Payer"; - var _Payl = "Payload"; - var _Pe = "Permission"; - var _Po = "Policy"; - var _Pr2 = "Progress"; - var _Pri = "Priority"; - var _Pro = "Protocol"; - var _Q = "Quiet"; - var _QA = "QueueArn"; - var _QC = "QuoteCharacter"; - var _QCL = "QueueConfigurationList"; - var _QCu = "QueueConfigurations"; - var _QCue = "QueueConfiguration"; - var _QEC = "QuoteEscapeCharacter"; - var _QF = "QuoteFields"; - var _Qu = "Queue"; - var _R = "Rules"; - var _RART = "RedirectAllRequestsTo"; - var _RC2 = "RequestCharged"; - var _RCC = "ResponseCacheControl"; - var _RCD = "ResponseContentDisposition"; - var _RCE = "ResponseContentEncoding"; - var _RCL = "ResponseContentLanguage"; - var _RCT = "ResponseContentType"; - var _RCe = "ReplicationConfiguration"; - var _RD = "RecordDelimiter"; - var _RE = "ResponseExpires"; - var _RED = "RestoreExpiryDate"; - var _REe = "RecordExpiration"; - var _REec = "RecordsEvent"; - var _RKKID = "ReplicaKmsKeyID"; - var _RKPW = "ReplaceKeyPrefixWith"; - var _RKW = "ReplaceKeyWith"; - var _RM = "ReplicaModifications"; - var _RO = "RenameObject"; - var _ROO = "RenameObjectOutput"; - var _ROOe = "RestoreObjectOutput"; - var _ROP = "RestoreOutputPath"; - var _ROR = "RenameObjectRequest"; - var _RORe = "RestoreObjectRequest"; - var _ROe = "RestoreObject"; - var _RP = "RequestPayer"; - var _RPB = "RestrictPublicBuckets"; - var _RPC = "RequestPaymentConfiguration"; - var _RPe = "RequestProgress"; - var _RR = "RoutingRules"; - var _RRAO = "ReplicationRuleAndOperator"; - var _RRF = "ReplicationRuleFilter"; - var _RRe = "ReplicationRule"; - var _RRep = "ReplicationRules"; - var _RReq = "RequestRoute"; - var _RRes = "RestoreRequest"; - var _RRo = "RoutingRule"; - var _RS = "ReplicationStatus"; - var _RSe = "RestoreStatus"; - var _RSen = "RenameSource"; - var _RT3 = "ReplicationTime"; - var _RTV = "ReplicationTimeValue"; - var _RTe = "RequestToken"; - var _RUD = "RetainUntilDate"; - var _Ra = "Range"; - var _Re = "Restore"; - var _Rec = "Records"; - var _Red = "Redirect"; - var _Ret = "Retention"; - var _Ro = "Role"; - var _Ru = "Rule"; - var _S = "Status"; - var _SA = "StartAfter"; - var _SAK2 = "SecretAccessKey"; - var _SAs = "SseAlgorithm"; - var _SB = "StreamingBlob"; - var _SBD = "S3BucketDestination"; - var _SC = "StorageClass"; - var _SCA = "StorageClassAnalysis"; - var _SCADE = "StorageClassAnalysisDataExport"; - var _SCV = "SessionCredentialValue"; - var _SCe = "SessionCredentials"; - var _SCt = "StatusCode"; - var _SDV = "SkipDestinationValidation"; - var _SE = "StatsEvent"; - var _SIM = "SourceIfMatch"; - var _SIMS = "SourceIfModifiedSince"; - var _SINM = "SourceIfNoneMatch"; - var _SIUS = "SourceIfUnmodifiedSince"; - var _SK = "SSE-KMS"; - var _SKEO = "SseKmsEncryptedObjects"; - var _SKF = "S3KeyFilter"; - var _SKe = "S3Key"; - var _SL = "S3Location"; - var _SM = "SessionMode"; - var _SOC = "SelectObjectContent"; - var _SOCES = "SelectObjectContentEventStream"; - var _SOCO = "SelectObjectContentOutput"; - var _SOCR = "SelectObjectContentRequest"; - var _SP = "SelectParameters"; - var _SPi = "SimplePrefix"; - var _SR = "ScanRange"; - var _SS = "SSE-S3"; - var _SSC = "SourceSelectionCriteria"; - var _SSE = "ServerSideEncryption"; - var _SSEA = "SSEAlgorithm"; - var _SSEBD = "ServerSideEncryptionByDefault"; - var _SSEC = "ServerSideEncryptionConfiguration"; - var _SSECA = "SSECustomerAlgorithm"; - var _SSECK = "SSECustomerKey"; - var _SSECKMD = "SSECustomerKeyMD5"; - var _SSEKMS = "SSEKMS"; - var _SSEKMSE = "SSEKMSEncryption"; - var _SSEKMSEC = "SSEKMSEncryptionContext"; - var _SSEKMSKI = "SSEKMSKeyId"; - var _SSER = "ServerSideEncryptionRule"; - var _SSERe = "ServerSideEncryptionRules"; - var _SSES = "SSES3"; - var _ST2 = "SessionToken"; - var _STD = "S3TablesDestination"; - var _STDR = "S3TablesDestinationResult"; - var _S_ = "S3"; - var _Sc = "Schedule"; - var _Si = "Size"; - var _St = "Start"; - var _Sta = "Stats"; - var _Su = "Suffix"; - var _T2 = "Tags"; - var _TA = "TableArn"; - var _TAo = "TopicArn"; - var _TB = "TargetBucket"; - var _TBA = "TableBucketArn"; - var _TBT = "TableBucketType"; - var _TC2 = "TagCount"; - var _TCL = "TopicConfigurationList"; - var _TCo = "TopicConfigurations"; - var _TCop = "TopicConfiguration"; - var _TD = "TaggingDirective"; - var _TDMOS = "TransitionDefaultMinimumObjectSize"; - var _TG = "TargetGrants"; - var _TGa = "TargetGrant"; - var _TL = "TieringList"; - var _TLr = "TransitionList"; - var _TMP = "TooManyParts"; - var _TN = "TableNamespace"; - var _TNa = "TableName"; - var _TOKF = "TargetObjectKeyFormat"; - var _TP = "TargetPrefix"; - var _TPC = "TotalPartsCount"; - var _TS = "TagSet"; - var _TSa = "TableStatus"; - var _Ta2 = "Tag"; - var _Tag = "Tagging"; - var _Ti = "Tier"; - var _Tie = "Tierings"; - var _Tier = "Tiering"; - var _Tim = "Time"; - var _To = "Token"; - var _Top = "Topic"; - var _Tr = "Transitions"; - var _Tra = "Transition"; - var _Ty = "Type"; - var _U = "Uploads"; - var _UBMITC = "UpdateBucketMetadataInventoryTableConfiguration"; - var _UBMITCR = "UpdateBucketMetadataInventoryTableConfigurationRequest"; - var _UBMJTC = "UpdateBucketMetadataJournalTableConfiguration"; - var _UBMJTCR = "UpdateBucketMetadataJournalTableConfigurationRequest"; - var _UI = "UploadId"; - var _UIM = "UploadIdMarker"; - var _UM = "UserMetadata"; - var _UOE = "UpdateObjectEncryption"; - var _UOER = "UpdateObjectEncryptionRequest"; - var _UOERp = "UpdateObjectEncryptionResponse"; - var _UP = "UploadPart"; - var _UPC = "UploadPartCopy"; - var _UPCO = "UploadPartCopyOutput"; - var _UPCR = "UploadPartCopyRequest"; - var _UPO = "UploadPartOutput"; - var _UPR = "UploadPartRequest"; - var _URI = "URI"; - var _Up = "Upload"; - var _V2 = "Value"; - var _VC = "VersioningConfiguration"; - var _VI = "VersionId"; - var _VIM = "VersionIdMarker"; - var _Ve = "Versions"; - var _Ver = "Version"; - var _WC = "WebsiteConfiguration"; - var _WGOR = "WriteGetObjectResponse"; - var _WGORR = "WriteGetObjectResponseRequest"; - var _WOB = "WriteOffsetBytes"; - var _WRL = "WebsiteRedirectLocation"; - var _Y = "Years"; - var _ar = "accept-ranges"; - var _br = "bucket-region"; - var _c5 = "client"; - var _ct = "continuation-token"; - var _d = "delimiter"; - var _e5 = "error"; - var _eP = "eventPayload"; - var _en = "endpoint"; - var _et = "encoding-type"; - var _fo = "fetch-owner"; - var _h4 = "http"; - var _hC = "httpChecksum"; - var _hE5 = "httpError"; - var _hH2 = "httpHeader"; - var _hL = "hostLabel"; - var _hP = "httpPayload"; - var _hPH = "httpPrefixHeaders"; - var _hQ2 = "httpQuery"; - var _hi = "http://www.w3.org/2001/XMLSchema-instance"; - var _i = "id"; - var _iT3 = "idempotencyToken"; - var _km = "key-marker"; - var _m4 = "marker"; - var _mb = "max-buckets"; - var _mdb = "max-directory-buckets"; - var _mk = "max-keys"; - var _mp = "max-parts"; - var _mu = "max-uploads"; - var _p = "prefix"; - var _pN = "partNumber"; - var _pnm = "part-number-marker"; - var _rcc = "response-cache-control"; - var _rcd = "response-content-disposition"; - var _rce = "response-content-encoding"; - var _rcl = "response-content-language"; - var _rct = "response-content-type"; - var _re = "response-expires"; - var _s5 = "smithy.ts.sdk.synthetic.com.amazonaws.s3"; - var _sa = "start-after"; - var _st = "streaming"; - var _uI = "uploadId"; - var _uim = "upload-id-marker"; - var _vI = "versionId"; - var _vim = "version-id-marker"; - var _x = "xsi"; - var _xA = "xmlAttribute"; - var _xF = "xmlFlattened"; - var _xN = "xmlName"; - var _xNm = "xmlNamespace"; - var _xaa = "x-amz-acl"; - var _xaad = "x-amz-abort-date"; - var _xaapa = "x-amz-access-point-alias"; - var _xaari = "x-amz-abort-rule-id"; - var _xaas = "x-amz-archive-status"; - var _xaba = "x-amz-bucket-arn"; - var _xabgr = "x-amz-bypass-governance-retention"; - var _xabln = "x-amz-bucket-location-name"; - var _xablt = "x-amz-bucket-location-type"; - var _xabn = "x-amz-bucket-namespace"; - var _xabole = "x-amz-bucket-object-lock-enabled"; - var _xabolt = "x-amz-bucket-object-lock-token"; - var _xabr = "x-amz-bucket-region"; - var _xaca = "x-amz-checksum-algorithm"; - var _xacc = "x-amz-checksum-crc32"; - var _xacc_ = "x-amz-checksum-crc32c"; - var _xacc__ = "x-amz-checksum-crc64nvme"; - var _xacm = "x-amz-checksum-mode"; - var _xacrsba = "x-amz-confirm-remove-self-bucket-access"; - var _xacs = "x-amz-checksum-sha1"; - var _xacs_ = "x-amz-checksum-sha256"; - var _xacs__ = "x-amz-copy-source"; - var _xacsim = "x-amz-copy-source-if-match"; - var _xacsims = "x-amz-copy-source-if-modified-since"; - var _xacsinm = "x-amz-copy-source-if-none-match"; - var _xacsius = "x-amz-copy-source-if-unmodified-since"; - var _xacsm = "x-amz-create-session-mode"; - var _xacsr = "x-amz-copy-source-range"; - var _xacssseca = "x-amz-copy-source-server-side-encryption-customer-algorithm"; - var _xacssseck = "x-amz-copy-source-server-side-encryption-customer-key"; - var _xacssseckM = "x-amz-copy-source-server-side-encryption-customer-key-MD5"; - var _xacsvi = "x-amz-copy-source-version-id"; - var _xact = "x-amz-checksum-type"; - var _xact_ = "x-amz-client-token"; - var _xadm = "x-amz-delete-marker"; - var _xae = "x-amz-expiration"; - var _xaebo = "x-amz-expected-bucket-owner"; - var _xafec = "x-amz-fwd-error-code"; - var _xafem = "x-amz-fwd-error-message"; - var _xafhCC = "x-amz-fwd-header-Cache-Control"; - var _xafhCD = "x-amz-fwd-header-Content-Disposition"; - var _xafhCE = "x-amz-fwd-header-Content-Encoding"; - var _xafhCL = "x-amz-fwd-header-Content-Language"; - var _xafhCR = "x-amz-fwd-header-Content-Range"; - var _xafhCT = "x-amz-fwd-header-Content-Type"; - var _xafhE = "x-amz-fwd-header-ETag"; - var _xafhE_ = "x-amz-fwd-header-Expires"; - var _xafhLM = "x-amz-fwd-header-Last-Modified"; - var _xafhar = "x-amz-fwd-header-accept-ranges"; - var _xafhxacc = "x-amz-fwd-header-x-amz-checksum-crc32"; - var _xafhxacc_ = "x-amz-fwd-header-x-amz-checksum-crc32c"; - var _xafhxacc__ = "x-amz-fwd-header-x-amz-checksum-crc64nvme"; - var _xafhxacs = "x-amz-fwd-header-x-amz-checksum-sha1"; - var _xafhxacs_ = "x-amz-fwd-header-x-amz-checksum-sha256"; - var _xafhxadm = "x-amz-fwd-header-x-amz-delete-marker"; - var _xafhxae = "x-amz-fwd-header-x-amz-expiration"; - var _xafhxamm = "x-amz-fwd-header-x-amz-missing-meta"; - var _xafhxampc = "x-amz-fwd-header-x-amz-mp-parts-count"; - var _xafhxaollh = "x-amz-fwd-header-x-amz-object-lock-legal-hold"; - var _xafhxaolm = "x-amz-fwd-header-x-amz-object-lock-mode"; - var _xafhxaolrud = "x-amz-fwd-header-x-amz-object-lock-retain-until-date"; - var _xafhxar = "x-amz-fwd-header-x-amz-restore"; - var _xafhxarc = "x-amz-fwd-header-x-amz-request-charged"; - var _xafhxars = "x-amz-fwd-header-x-amz-replication-status"; - var _xafhxasc = "x-amz-fwd-header-x-amz-storage-class"; - var _xafhxasse = "x-amz-fwd-header-x-amz-server-side-encryption"; - var _xafhxasseakki = "x-amz-fwd-header-x-amz-server-side-encryption-aws-kms-key-id"; - var _xafhxassebke = "x-amz-fwd-header-x-amz-server-side-encryption-bucket-key-enabled"; - var _xafhxasseca = "x-amz-fwd-header-x-amz-server-side-encryption-customer-algorithm"; - var _xafhxasseckM = "x-amz-fwd-header-x-amz-server-side-encryption-customer-key-MD5"; - var _xafhxatc = "x-amz-fwd-header-x-amz-tagging-count"; - var _xafhxavi = "x-amz-fwd-header-x-amz-version-id"; - var _xafs = "x-amz-fwd-status"; - var _xagfc = "x-amz-grant-full-control"; - var _xagr = "x-amz-grant-read"; - var _xagra = "x-amz-grant-read-acp"; - var _xagw = "x-amz-grant-write"; - var _xagwa = "x-amz-grant-write-acp"; - var _xaimit = "x-amz-if-match-initiated-time"; - var _xaimlmt = "x-amz-if-match-last-modified-time"; - var _xaims = "x-amz-if-match-size"; - var _xam = "x-amz-meta-"; - var _xam_ = "x-amz-mfa"; - var _xamd = "x-amz-metadata-directive"; - var _xamm = "x-amz-missing-meta"; - var _xamos = "x-amz-mp-object-size"; - var _xamp = "x-amz-max-parts"; - var _xampc = "x-amz-mp-parts-count"; - var _xaoa = "x-amz-object-attributes"; - var _xaollh = "x-amz-object-lock-legal-hold"; - var _xaolm = "x-amz-object-lock-mode"; - var _xaolrud = "x-amz-object-lock-retain-until-date"; - var _xaoo = "x-amz-object-ownership"; - var _xaooa = "x-amz-optional-object-attributes"; - var _xaos = "x-amz-object-size"; - var _xapnm = "x-amz-part-number-marker"; - var _xar = "x-amz-restore"; - var _xarc = "x-amz-request-charged"; - var _xarop = "x-amz-restore-output-path"; - var _xarp = "x-amz-request-payer"; - var _xarr = "x-amz-request-route"; - var _xars = "x-amz-replication-status"; - var _xars_ = "x-amz-rename-source"; - var _xarsim = "x-amz-rename-source-if-match"; - var _xarsims = "x-amz-rename-source-if-modified-since"; - var _xarsinm = "x-amz-rename-source-if-none-match"; - var _xarsius = "x-amz-rename-source-if-unmodified-since"; - var _xart = "x-amz-request-token"; - var _xasc = "x-amz-storage-class"; - var _xasca = "x-amz-sdk-checksum-algorithm"; - var _xasdv = "x-amz-skip-destination-validation"; - var _xasebo = "x-amz-source-expected-bucket-owner"; - var _xasse = "x-amz-server-side-encryption"; - var _xasseakki = "x-amz-server-side-encryption-aws-kms-key-id"; - var _xassebke = "x-amz-server-side-encryption-bucket-key-enabled"; - var _xassec = "x-amz-server-side-encryption-context"; - var _xasseca = "x-amz-server-side-encryption-customer-algorithm"; - var _xasseck = "x-amz-server-side-encryption-customer-key"; - var _xasseckM = "x-amz-server-side-encryption-customer-key-MD5"; - var _xat = "x-amz-tagging"; - var _xatc = "x-amz-tagging-count"; - var _xatd = "x-amz-tagging-directive"; - var _xatdmos = "x-amz-transition-default-minimum-object-size"; - var _xavi = "x-amz-version-id"; - var _xawob = "x-amz-write-offset-bytes"; - var _xawrl = "x-amz-website-redirect-location"; - var _xs = "xsi:type"; - var n05 = "com.amazonaws.s3"; - var schema_1 = (init_schema3(), __toCommonJS(schema_exports2)); - var errors_1 = require_errors(); - var S3ServiceException_1 = require_S3ServiceException(); - var _s_registry5 = schema_1.TypeRegistry.for(_s5); - exports.S3ServiceException$ = [-3, _s5, "S3ServiceException", 0, [], []]; - _s_registry5.registerError(exports.S3ServiceException$, S3ServiceException_1.S3ServiceException); - var n0_registry5 = schema_1.TypeRegistry.for(n05); - exports.AccessDenied$ = [ - -3, - n05, - _AD, - { [_e5]: _c5, [_hE5]: 403 }, - [], - [] - ]; - n0_registry5.registerError(exports.AccessDenied$, errors_1.AccessDenied); - exports.BucketAlreadyExists$ = [ - -3, - n05, - _BAE, - { [_e5]: _c5, [_hE5]: 409 }, - [], - [] - ]; - n0_registry5.registerError(exports.BucketAlreadyExists$, errors_1.BucketAlreadyExists); - exports.BucketAlreadyOwnedByYou$ = [ - -3, - n05, - _BAOBY, - { [_e5]: _c5, [_hE5]: 409 }, - [], - [] - ]; - n0_registry5.registerError(exports.BucketAlreadyOwnedByYou$, errors_1.BucketAlreadyOwnedByYou); - exports.EncryptionTypeMismatch$ = [ - -3, - n05, - _ETM, - { [_e5]: _c5, [_hE5]: 400 }, - [], - [] - ]; - n0_registry5.registerError(exports.EncryptionTypeMismatch$, errors_1.EncryptionTypeMismatch); - exports.IdempotencyParameterMismatch$ = [ - -3, - n05, - _IPM, - { [_e5]: _c5, [_hE5]: 400 }, - [], - [] - ]; - n0_registry5.registerError(exports.IdempotencyParameterMismatch$, errors_1.IdempotencyParameterMismatch); - exports.InvalidObjectState$ = [ - -3, - n05, - _IOS, - { [_e5]: _c5, [_hE5]: 403 }, - [_SC, _AT3], - [0, 0] - ]; - n0_registry5.registerError(exports.InvalidObjectState$, errors_1.InvalidObjectState); - exports.InvalidRequest$ = [ - -3, - n05, - _IR, - { [_e5]: _c5, [_hE5]: 400 }, - [], - [] - ]; - n0_registry5.registerError(exports.InvalidRequest$, errors_1.InvalidRequest); - exports.InvalidWriteOffset$ = [ - -3, - n05, - _IWO, - { [_e5]: _c5, [_hE5]: 400 }, - [], - [] - ]; - n0_registry5.registerError(exports.InvalidWriteOffset$, errors_1.InvalidWriteOffset); - exports.NoSuchBucket$ = [ - -3, - n05, - _NSB, - { [_e5]: _c5, [_hE5]: 404 }, - [], - [] - ]; - n0_registry5.registerError(exports.NoSuchBucket$, errors_1.NoSuchBucket); - exports.NoSuchKey$ = [ - -3, - n05, - _NSK, - { [_e5]: _c5, [_hE5]: 404 }, - [], - [] - ]; - n0_registry5.registerError(exports.NoSuchKey$, errors_1.NoSuchKey); - exports.NoSuchUpload$ = [ - -3, - n05, - _NSU, - { [_e5]: _c5, [_hE5]: 404 }, - [], - [] - ]; - n0_registry5.registerError(exports.NoSuchUpload$, errors_1.NoSuchUpload); - exports.NotFound$ = [ - -3, - n05, - _NF, - { [_e5]: _c5 }, - [], - [] - ]; - n0_registry5.registerError(exports.NotFound$, errors_1.NotFound); - exports.ObjectAlreadyInActiveTierError$ = [ - -3, - n05, - _OAIATE, - { [_e5]: _c5, [_hE5]: 403 }, - [], - [] - ]; - n0_registry5.registerError(exports.ObjectAlreadyInActiveTierError$, errors_1.ObjectAlreadyInActiveTierError); - exports.ObjectNotInActiveTierError$ = [ - -3, - n05, - _ONIATE, - { [_e5]: _c5, [_hE5]: 403 }, - [], - [] - ]; - n0_registry5.registerError(exports.ObjectNotInActiveTierError$, errors_1.ObjectNotInActiveTierError); - exports.TooManyParts$ = [ - -3, - n05, - _TMP, - { [_e5]: _c5, [_hE5]: 400 }, - [], - [] - ]; - n0_registry5.registerError(exports.TooManyParts$, errors_1.TooManyParts); - exports.errorTypeRegistries = [ - _s_registry5, - n0_registry5 - ]; - var CopySourceSSECustomerKey = [0, n05, _CSSSECK, 8, 0]; - var NonEmptyKmsKeyArnString = [0, n05, _NEKKAS, 8, 0]; - var SessionCredentialValue = [0, n05, _SCV, 8, 0]; - var SSECustomerKey = [0, n05, _SSECK, 8, 0]; - var SSEKMSEncryptionContext = [0, n05, _SSEKMSEC, 8, 0]; - var SSEKMSKeyId = [0, n05, _SSEKMSKI, 8, 0]; - var StreamingBlob = [0, n05, _SB, { [_st]: 1 }, 42]; - exports.AbacStatus$ = [ - 3, - n05, - _AS, - 0, - [_S], - [0] - ]; - exports.AbortIncompleteMultipartUpload$ = [ - 3, - n05, - _AIMU, - 0, - [_DAI], - [1] - ]; - exports.AbortMultipartUploadOutput$ = [ - 3, - n05, - _AMUO, - 0, - [_RC2], - [[0, { [_hH2]: _xarc }]] - ]; - exports.AbortMultipartUploadRequest$ = [ - 3, - n05, - _AMUR, - 0, - [_B, _K2, _UI, _RP, _EBO, _IMIT], - [[0, 1], [0, 1], [0, { [_hQ2]: _uI }], [0, { [_hH2]: _xarp }], [0, { [_hH2]: _xaebo }], [6, { [_hH2]: _xaimit }]], - 3 - ]; - exports.AccelerateConfiguration$ = [ - 3, - n05, - _AC, - 0, - [_S], - [0] - ]; - exports.AccessControlPolicy$ = [ - 3, - n05, - _ACP, - 0, - [_G, _O], - [[() => Grants, { [_xN]: _ACL }], () => exports.Owner$] - ]; - exports.AccessControlTranslation$ = [ - 3, - n05, - _ACT, - 0, - [_O], - [0], - 1 - ]; - exports.AnalyticsAndOperator$ = [ - 3, - n05, - _AAO, - 0, - [_P2, _T2], - [0, [() => TagSet, { [_xF]: 1, [_xN]: _Ta2 }]] - ]; - exports.AnalyticsConfiguration$ = [ - 3, - n05, - _ACn, - 0, - [_I, _SCA, _F], - [0, () => exports.StorageClassAnalysis$, [() => exports.AnalyticsFilter$, 0]], - 2 - ]; - exports.AnalyticsExportDestination$ = [ - 3, - n05, - _AED, - 0, - [_SBD], - [() => exports.AnalyticsS3BucketDestination$], - 1 - ]; - exports.AnalyticsS3BucketDestination$ = [ - 3, - n05, - _ASBD, - 0, - [_Fo, _B, _BAI, _P2], - [0, 0, 0, 0], - 2 - ]; - exports.BlockedEncryptionTypes$ = [ - 3, - n05, - _BET, - 0, - [_ET], - [[() => EncryptionTypeList, { [_xF]: 1 }]] - ]; - exports.Bucket$ = [ - 3, - n05, - _B, - 0, - [_N, _CD, _BR, _BA], - [0, 4, 0, 0] - ]; - exports.BucketInfo$ = [ - 3, - n05, - _BI, - 0, - [_DR, _Ty], - [0, 0] - ]; - exports.BucketLifecycleConfiguration$ = [ - 3, - n05, - _BLC, - 0, - [_R], - [[() => LifecycleRules, { [_xF]: 1, [_xN]: _Ru }]], - 1 - ]; - exports.BucketLoggingStatus$ = [ - 3, - n05, - _BLS, - 0, - [_LE], - [[() => exports.LoggingEnabled$, 0]] - ]; - exports.Checksum$ = [ - 3, - n05, - _C2, - 0, - [_CCRC, _CCRCC, _CCRCNVME, _CSHA, _CSHAh, _CT2], - [0, 0, 0, 0, 0, 0] - ]; - exports.CommonPrefix$ = [ - 3, - n05, - _CP, - 0, - [_P2], - [0] - ]; - exports.CompletedMultipartUpload$ = [ - 3, - n05, - _CMU, - 0, - [_Pa], - [[() => CompletedPartList, { [_xF]: 1, [_xN]: _Par }]] - ]; - exports.CompletedPart$ = [ - 3, - n05, - _CPo, - 0, - [_ETa, _CCRC, _CCRCC, _CCRCNVME, _CSHA, _CSHAh, _PN], - [0, 0, 0, 0, 0, 0, 1] - ]; - exports.CompleteMultipartUploadOutput$ = [ - 3, - n05, - _CMUO, - { [_xN]: _CMUR }, - [_L, _B, _K2, _E2, _ETa, _CCRC, _CCRCC, _CCRCNVME, _CSHA, _CSHAh, _CT2, _SSE, _VI, _SSEKMSKI, _BKE, _RC2], - [0, 0, 0, [0, { [_hH2]: _xae }], 0, 0, 0, 0, 0, 0, 0, [0, { [_hH2]: _xasse }], [0, { [_hH2]: _xavi }], [() => SSEKMSKeyId, { [_hH2]: _xasseakki }], [2, { [_hH2]: _xassebke }], [0, { [_hH2]: _xarc }]] - ]; - exports.CompleteMultipartUploadRequest$ = [ - 3, - n05, - _CMURo, - 0, - [_B, _K2, _UI, _MU, _CCRC, _CCRCC, _CCRCNVME, _CSHA, _CSHAh, _CT2, _MOS, _RP, _EBO, _IM, _INM, _SSECA, _SSECK, _SSECKMD], - [[0, 1], [0, 1], [0, { [_hQ2]: _uI }], [() => exports.CompletedMultipartUpload$, { [_hP]: 1, [_xN]: _CMUo }], [0, { [_hH2]: _xacc }], [0, { [_hH2]: _xacc_ }], [0, { [_hH2]: _xacc__ }], [0, { [_hH2]: _xacs }], [0, { [_hH2]: _xacs_ }], [0, { [_hH2]: _xact }], [1, { [_hH2]: _xamos }], [0, { [_hH2]: _xarp }], [0, { [_hH2]: _xaebo }], [0, { [_hH2]: _IM_ }], [0, { [_hH2]: _INM_ }], [0, { [_hH2]: _xasseca }], [() => SSECustomerKey, { [_hH2]: _xasseck }], [0, { [_hH2]: _xasseckM }]], - 3 - ]; - exports.Condition$ = [ - 3, - n05, - _Co, - 0, - [_HECRE, _KPE], - [0, 0] - ]; - exports.ContinuationEvent$ = [ - 3, - n05, - _CE, - 0, - [], - [] - ]; - exports.CopyObjectOutput$ = [ - 3, - n05, - _COO, - 0, - [_COR, _E2, _CSVI, _VI, _SSE, _SSECA, _SSECKMD, _SSEKMSKI, _SSEKMSEC, _BKE, _RC2], - [[() => exports.CopyObjectResult$, 16], [0, { [_hH2]: _xae }], [0, { [_hH2]: _xacsvi }], [0, { [_hH2]: _xavi }], [0, { [_hH2]: _xasse }], [0, { [_hH2]: _xasseca }], [0, { [_hH2]: _xasseckM }], [() => SSEKMSKeyId, { [_hH2]: _xasseakki }], [() => SSEKMSEncryptionContext, { [_hH2]: _xassec }], [2, { [_hH2]: _xassebke }], [0, { [_hH2]: _xarc }]] - ]; - exports.CopyObjectRequest$ = [ - 3, - n05, - _CORo, - 0, - [_B, _CS2, _K2, _ACL_, _CC, _CA2, _CDo, _CEo, _CL, _CTo, _CSIM, _CSIMS, _CSINM, _CSIUS, _Ex, _GFC, _GR, _GRACP, _GWACP, _IM, _INM, _M, _MD, _TD, _SSE, _SC, _WRL, _SSECA, _SSECK, _SSECKMD, _SSEKMSKI, _SSEKMSEC, _BKE, _CSSSECA, _CSSSECK, _CSSSECKMD, _RP, _Tag, _OLM, _OLRUD, _OLLHS, _EBO, _ESBO], - [[0, 1], [0, { [_hH2]: _xacs__ }], [0, 1], [0, { [_hH2]: _xaa }], [0, { [_hH2]: _CC_ }], [0, { [_hH2]: _xaca }], [0, { [_hH2]: _CD_ }], [0, { [_hH2]: _CE_ }], [0, { [_hH2]: _CL_ }], [0, { [_hH2]: _CT_ }], [0, { [_hH2]: _xacsim }], [4, { [_hH2]: _xacsims }], [0, { [_hH2]: _xacsinm }], [4, { [_hH2]: _xacsius }], [4, { [_hH2]: _Ex }], [0, { [_hH2]: _xagfc }], [0, { [_hH2]: _xagr }], [0, { [_hH2]: _xagra }], [0, { [_hH2]: _xagwa }], [0, { [_hH2]: _IM_ }], [0, { [_hH2]: _INM_ }], [128 | 0, { [_hPH]: _xam }], [0, { [_hH2]: _xamd }], [0, { [_hH2]: _xatd }], [0, { [_hH2]: _xasse }], [0, { [_hH2]: _xasc }], [0, { [_hH2]: _xawrl }], [0, { [_hH2]: _xasseca }], [() => SSECustomerKey, { [_hH2]: _xasseck }], [0, { [_hH2]: _xasseckM }], [() => SSEKMSKeyId, { [_hH2]: _xasseakki }], [() => SSEKMSEncryptionContext, { [_hH2]: _xassec }], [2, { [_hH2]: _xassebke }], [0, { [_hH2]: _xacssseca }], [() => CopySourceSSECustomerKey, { [_hH2]: _xacssseck }], [0, { [_hH2]: _xacssseckM }], [0, { [_hH2]: _xarp }], [0, { [_hH2]: _xat }], [0, { [_hH2]: _xaolm }], [5, { [_hH2]: _xaolrud }], [0, { [_hH2]: _xaollh }], [0, { [_hH2]: _xaebo }], [0, { [_hH2]: _xasebo }]], - 3 - ]; - exports.CopyObjectResult$ = [ - 3, - n05, - _COR, - 0, - [_ETa, _LM, _CT2, _CCRC, _CCRCC, _CCRCNVME, _CSHA, _CSHAh], - [0, 4, 0, 0, 0, 0, 0, 0] - ]; - exports.CopyPartResult$ = [ - 3, - n05, - _CPR, - 0, - [_ETa, _LM, _CCRC, _CCRCC, _CCRCNVME, _CSHA, _CSHAh], - [0, 4, 0, 0, 0, 0, 0] - ]; - exports.CORSConfiguration$ = [ - 3, - n05, - _CORSC, - 0, - [_CORSR], - [[() => CORSRules, { [_xF]: 1, [_xN]: _CORSRu }]], - 1 - ]; - exports.CORSRule$ = [ - 3, - n05, - _CORSRu, - 0, - [_AM, _AO, _ID, _AH, _EH, _MAS], - [[64 | 0, { [_xF]: 1, [_xN]: _AMl }], [64 | 0, { [_xF]: 1, [_xN]: _AOl }], 0, [64 | 0, { [_xF]: 1, [_xN]: _AHl }], [64 | 0, { [_xF]: 1, [_xN]: _EHx }], 1], - 2 - ]; - exports.CreateBucketConfiguration$ = [ - 3, - n05, - _CBC, - 0, - [_LC, _L, _B, _T2], - [0, () => exports.LocationInfo$, () => exports.BucketInfo$, [() => TagSet, 0]] - ]; - exports.CreateBucketMetadataConfigurationRequest$ = [ - 3, - n05, - _CBMCR, - 0, - [_B, _MC, _CMD, _CA2, _EBO], - [[0, 1], [() => exports.MetadataConfiguration$, { [_hP]: 1, [_xN]: _MC }], [0, { [_hH2]: _CM }], [0, { [_hH2]: _xasca }], [0, { [_hH2]: _xaebo }]], - 2 - ]; - exports.CreateBucketMetadataTableConfigurationRequest$ = [ - 3, - n05, - _CBMTCR, - 0, - [_B, _MTC, _CMD, _CA2, _EBO], - [[0, 1], [() => exports.MetadataTableConfiguration$, { [_hP]: 1, [_xN]: _MTC }], [0, { [_hH2]: _CM }], [0, { [_hH2]: _xasca }], [0, { [_hH2]: _xaebo }]], - 2 - ]; - exports.CreateBucketOutput$ = [ - 3, - n05, - _CBO, - 0, - [_L, _BA], - [[0, { [_hH2]: _L }], [0, { [_hH2]: _xaba }]] - ]; - exports.CreateBucketRequest$ = [ - 3, - n05, - _CBR, - 0, - [_B, _ACL_, _CBC, _GFC, _GR, _GRACP, _GW, _GWACP, _OLEFB, _OO, _BN], - [[0, 1], [0, { [_hH2]: _xaa }], [() => exports.CreateBucketConfiguration$, { [_hP]: 1, [_xN]: _CBC }], [0, { [_hH2]: _xagfc }], [0, { [_hH2]: _xagr }], [0, { [_hH2]: _xagra }], [0, { [_hH2]: _xagw }], [0, { [_hH2]: _xagwa }], [2, { [_hH2]: _xabole }], [0, { [_hH2]: _xaoo }], [0, { [_hH2]: _xabn }]], - 1 - ]; - exports.CreateMultipartUploadOutput$ = [ - 3, - n05, - _CMUOr, - { [_xN]: _IMUR }, - [_ADb, _ARI2, _B, _K2, _UI, _SSE, _SSECA, _SSECKMD, _SSEKMSKI, _SSEKMSEC, _BKE, _RC2, _CA2, _CT2], - [[4, { [_hH2]: _xaad }], [0, { [_hH2]: _xaari }], [0, { [_xN]: _B }], 0, 0, [0, { [_hH2]: _xasse }], [0, { [_hH2]: _xasseca }], [0, { [_hH2]: _xasseckM }], [() => SSEKMSKeyId, { [_hH2]: _xasseakki }], [() => SSEKMSEncryptionContext, { [_hH2]: _xassec }], [2, { [_hH2]: _xassebke }], [0, { [_hH2]: _xarc }], [0, { [_hH2]: _xaca }], [0, { [_hH2]: _xact }]] - ]; - exports.CreateMultipartUploadRequest$ = [ - 3, - n05, - _CMURr, - 0, - [_B, _K2, _ACL_, _CC, _CDo, _CEo, _CL, _CTo, _Ex, _GFC, _GR, _GRACP, _GWACP, _M, _SSE, _SC, _WRL, _SSECA, _SSECK, _SSECKMD, _SSEKMSKI, _SSEKMSEC, _BKE, _RP, _Tag, _OLM, _OLRUD, _OLLHS, _EBO, _CA2, _CT2], - [[0, 1], [0, 1], [0, { [_hH2]: _xaa }], [0, { [_hH2]: _CC_ }], [0, { [_hH2]: _CD_ }], [0, { [_hH2]: _CE_ }], [0, { [_hH2]: _CL_ }], [0, { [_hH2]: _CT_ }], [4, { [_hH2]: _Ex }], [0, { [_hH2]: _xagfc }], [0, { [_hH2]: _xagr }], [0, { [_hH2]: _xagra }], [0, { [_hH2]: _xagwa }], [128 | 0, { [_hPH]: _xam }], [0, { [_hH2]: _xasse }], [0, { [_hH2]: _xasc }], [0, { [_hH2]: _xawrl }], [0, { [_hH2]: _xasseca }], [() => SSECustomerKey, { [_hH2]: _xasseck }], [0, { [_hH2]: _xasseckM }], [() => SSEKMSKeyId, { [_hH2]: _xasseakki }], [() => SSEKMSEncryptionContext, { [_hH2]: _xassec }], [2, { [_hH2]: _xassebke }], [0, { [_hH2]: _xarp }], [0, { [_hH2]: _xat }], [0, { [_hH2]: _xaolm }], [5, { [_hH2]: _xaolrud }], [0, { [_hH2]: _xaollh }], [0, { [_hH2]: _xaebo }], [0, { [_hH2]: _xaca }], [0, { [_hH2]: _xact }]], - 2 - ]; - exports.CreateSessionOutput$ = [ - 3, - n05, - _CSO, - { [_xN]: _CSR }, - [_Cr, _SSE, _SSEKMSKI, _SSEKMSEC, _BKE], - [[() => exports.SessionCredentials$, { [_xN]: _Cr }], [0, { [_hH2]: _xasse }], [() => SSEKMSKeyId, { [_hH2]: _xasseakki }], [() => SSEKMSEncryptionContext, { [_hH2]: _xassec }], [2, { [_hH2]: _xassebke }]], - 1 - ]; - exports.CreateSessionRequest$ = [ - 3, - n05, - _CSRr, - 0, - [_B, _SM, _SSE, _SSEKMSKI, _SSEKMSEC, _BKE], - [[0, 1], [0, { [_hH2]: _xacsm }], [0, { [_hH2]: _xasse }], [() => SSEKMSKeyId, { [_hH2]: _xasseakki }], [() => SSEKMSEncryptionContext, { [_hH2]: _xassec }], [2, { [_hH2]: _xassebke }]], - 1 - ]; - exports.CSVInput$ = [ - 3, - n05, - _CSVIn, - 0, - [_FHI, _Com, _QEC, _RD, _FD, _QC, _AQRD], - [0, 0, 0, 0, 0, 0, 2] - ]; - exports.CSVOutput$ = [ - 3, - n05, - _CSVO, - 0, - [_QF, _QEC, _RD, _FD, _QC], - [0, 0, 0, 0, 0] - ]; - exports.DefaultRetention$ = [ - 3, - n05, - _DRe, - 0, - [_Mo, _D, _Y], - [0, 1, 1] - ]; - exports.Delete$ = [ - 3, - n05, - _De, - 0, - [_Ob, _Q], - [[() => ObjectIdentifierList, { [_xF]: 1, [_xN]: _Obj }], 2], - 1 - ]; - exports.DeleteBucketAnalyticsConfigurationRequest$ = [ - 3, - n05, - _DBACR, - 0, - [_B, _I, _EBO], - [[0, 1], [0, { [_hQ2]: _i }], [0, { [_hH2]: _xaebo }]], - 2 - ]; - exports.DeleteBucketCorsRequest$ = [ - 3, - n05, - _DBCR, - 0, - [_B, _EBO], - [[0, 1], [0, { [_hH2]: _xaebo }]], - 1 - ]; - exports.DeleteBucketEncryptionRequest$ = [ - 3, - n05, - _DBER, - 0, - [_B, _EBO], - [[0, 1], [0, { [_hH2]: _xaebo }]], - 1 - ]; - exports.DeleteBucketIntelligentTieringConfigurationRequest$ = [ - 3, - n05, - _DBITCR, - 0, - [_B, _I, _EBO], - [[0, 1], [0, { [_hQ2]: _i }], [0, { [_hH2]: _xaebo }]], - 2 - ]; - exports.DeleteBucketInventoryConfigurationRequest$ = [ - 3, - n05, - _DBICR, - 0, - [_B, _I, _EBO], - [[0, 1], [0, { [_hQ2]: _i }], [0, { [_hH2]: _xaebo }]], - 2 - ]; - exports.DeleteBucketLifecycleRequest$ = [ - 3, - n05, - _DBLR, - 0, - [_B, _EBO], - [[0, 1], [0, { [_hH2]: _xaebo }]], - 1 - ]; - exports.DeleteBucketMetadataConfigurationRequest$ = [ - 3, - n05, - _DBMCR, - 0, - [_B, _EBO], - [[0, 1], [0, { [_hH2]: _xaebo }]], - 1 - ]; - exports.DeleteBucketMetadataTableConfigurationRequest$ = [ - 3, - n05, - _DBMTCR, - 0, - [_B, _EBO], - [[0, 1], [0, { [_hH2]: _xaebo }]], - 1 - ]; - exports.DeleteBucketMetricsConfigurationRequest$ = [ - 3, - n05, - _DBMCRe, - 0, - [_B, _I, _EBO], - [[0, 1], [0, { [_hQ2]: _i }], [0, { [_hH2]: _xaebo }]], - 2 - ]; - exports.DeleteBucketOwnershipControlsRequest$ = [ - 3, - n05, - _DBOCR, - 0, - [_B, _EBO], - [[0, 1], [0, { [_hH2]: _xaebo }]], - 1 - ]; - exports.DeleteBucketPolicyRequest$ = [ - 3, - n05, - _DBPR, - 0, - [_B, _EBO], - [[0, 1], [0, { [_hH2]: _xaebo }]], - 1 - ]; - exports.DeleteBucketReplicationRequest$ = [ - 3, - n05, - _DBRR, - 0, - [_B, _EBO], - [[0, 1], [0, { [_hH2]: _xaebo }]], - 1 - ]; - exports.DeleteBucketRequest$ = [ - 3, - n05, - _DBR, - 0, - [_B, _EBO], - [[0, 1], [0, { [_hH2]: _xaebo }]], - 1 - ]; - exports.DeleteBucketTaggingRequest$ = [ - 3, - n05, - _DBTR, - 0, - [_B, _EBO], - [[0, 1], [0, { [_hH2]: _xaebo }]], - 1 - ]; - exports.DeleteBucketWebsiteRequest$ = [ - 3, - n05, - _DBWR, - 0, - [_B, _EBO], - [[0, 1], [0, { [_hH2]: _xaebo }]], - 1 - ]; - exports.DeletedObject$ = [ - 3, - n05, - _DO, - 0, - [_K2, _VI, _DM, _DMVI], - [0, 0, 2, 0] - ]; - exports.DeleteMarkerEntry$ = [ - 3, - n05, - _DME, - 0, - [_O, _K2, _VI, _IL, _LM], - [() => exports.Owner$, 0, 0, 2, 4] - ]; - exports.DeleteMarkerReplication$ = [ - 3, - n05, - _DMR, - 0, - [_S], - [0] - ]; - exports.DeleteObjectOutput$ = [ - 3, - n05, - _DOO, - 0, - [_DM, _VI, _RC2], - [[2, { [_hH2]: _xadm }], [0, { [_hH2]: _xavi }], [0, { [_hH2]: _xarc }]] - ]; - exports.DeleteObjectRequest$ = [ - 3, - n05, - _DOR, - 0, - [_B, _K2, _MFA, _VI, _RP, _BGR, _EBO, _IM, _IMLMT, _IMS], - [[0, 1], [0, 1], [0, { [_hH2]: _xam_ }], [0, { [_hQ2]: _vI }], [0, { [_hH2]: _xarp }], [2, { [_hH2]: _xabgr }], [0, { [_hH2]: _xaebo }], [0, { [_hH2]: _IM_ }], [6, { [_hH2]: _xaimlmt }], [1, { [_hH2]: _xaims }]], - 2 - ]; - exports.DeleteObjectsOutput$ = [ - 3, - n05, - _DOOe, - { [_xN]: _DRel }, - [_Del, _RC2, _Er], - [[() => DeletedObjects, { [_xF]: 1 }], [0, { [_hH2]: _xarc }], [() => Errors2, { [_xF]: 1, [_xN]: _Err }]] - ]; - exports.DeleteObjectsRequest$ = [ - 3, - n05, - _DORe, - 0, - [_B, _De, _MFA, _RP, _BGR, _EBO, _CA2], - [[0, 1], [() => exports.Delete$, { [_hP]: 1, [_xN]: _De }], [0, { [_hH2]: _xam_ }], [0, { [_hH2]: _xarp }], [2, { [_hH2]: _xabgr }], [0, { [_hH2]: _xaebo }], [0, { [_hH2]: _xasca }]], - 2 - ]; - exports.DeleteObjectTaggingOutput$ = [ - 3, - n05, - _DOTO, - 0, - [_VI], - [[0, { [_hH2]: _xavi }]] - ]; - exports.DeleteObjectTaggingRequest$ = [ - 3, - n05, - _DOTR, - 0, - [_B, _K2, _VI, _EBO], - [[0, 1], [0, 1], [0, { [_hQ2]: _vI }], [0, { [_hH2]: _xaebo }]], - 2 - ]; - exports.DeletePublicAccessBlockRequest$ = [ - 3, - n05, - _DPABR, - 0, - [_B, _EBO], - [[0, 1], [0, { [_hH2]: _xaebo }]], - 1 - ]; - exports.Destination$ = [ - 3, - n05, - _Des, - 0, - [_B, _A2, _SC, _ACT, _EC, _RT3, _Me], - [0, 0, 0, () => exports.AccessControlTranslation$, () => exports.EncryptionConfiguration$, () => exports.ReplicationTime$, () => exports.Metrics$], - 1 - ]; - exports.DestinationResult$ = [ - 3, - n05, - _DRes, - 0, - [_TBT, _TBA, _TN], - [0, 0, 0] - ]; - exports.Encryption$ = [ - 3, - n05, - _En, - 0, - [_ET, _KMSKI, _KMSC], - [0, [() => SSEKMSKeyId, 0], 0], - 1 - ]; - exports.EncryptionConfiguration$ = [ - 3, - n05, - _EC, - 0, - [_RKKID], - [0] - ]; - exports.EndEvent$ = [ - 3, - n05, - _EE, - 0, - [], - [] - ]; - exports._Error$ = [ - 3, - n05, - _Err, - 0, - [_K2, _VI, _Cod, _Mes], - [0, 0, 0, 0] - ]; - exports.ErrorDetails$ = [ - 3, - n05, - _ED, - 0, - [_ECr, _EM], - [0, 0] - ]; - exports.ErrorDocument$ = [ - 3, - n05, - _EDr, - 0, - [_K2], - [0], - 1 - ]; - exports.EventBridgeConfiguration$ = [ - 3, - n05, - _EBC, - 0, - [], - [] - ]; - exports.ExistingObjectReplication$ = [ - 3, - n05, - _EOR, - 0, - [_S], - [0], - 1 - ]; - exports.FilterRule$ = [ - 3, - n05, - _FR, - 0, - [_N, _V2], - [0, 0] - ]; - exports.GetBucketAbacOutput$ = [ - 3, - n05, - _GBAO, - 0, - [_AS], - [[() => exports.AbacStatus$, 16]] - ]; - exports.GetBucketAbacRequest$ = [ - 3, - n05, - _GBAR, - 0, - [_B, _EBO], - [[0, 1], [0, { [_hH2]: _xaebo }]], - 1 - ]; - exports.GetBucketAccelerateConfigurationOutput$ = [ - 3, - n05, - _GBACO, - { [_xN]: _AC }, - [_S, _RC2], - [0, [0, { [_hH2]: _xarc }]] - ]; - exports.GetBucketAccelerateConfigurationRequest$ = [ - 3, - n05, - _GBACR, - 0, - [_B, _EBO, _RP], - [[0, 1], [0, { [_hH2]: _xaebo }], [0, { [_hH2]: _xarp }]], - 1 - ]; - exports.GetBucketAclOutput$ = [ - 3, - n05, - _GBAOe, - { [_xN]: _ACP }, - [_O, _G], - [() => exports.Owner$, [() => Grants, { [_xN]: _ACL }]] - ]; - exports.GetBucketAclRequest$ = [ - 3, - n05, - _GBARe, - 0, - [_B, _EBO], - [[0, 1], [0, { [_hH2]: _xaebo }]], - 1 - ]; - exports.GetBucketAnalyticsConfigurationOutput$ = [ - 3, - n05, - _GBACOe, - 0, - [_ACn], - [[() => exports.AnalyticsConfiguration$, 16]] - ]; - exports.GetBucketAnalyticsConfigurationRequest$ = [ - 3, - n05, - _GBACRe, - 0, - [_B, _I, _EBO], - [[0, 1], [0, { [_hQ2]: _i }], [0, { [_hH2]: _xaebo }]], - 2 - ]; - exports.GetBucketCorsOutput$ = [ - 3, - n05, - _GBCO, - { [_xN]: _CORSC }, - [_CORSR], - [[() => CORSRules, { [_xF]: 1, [_xN]: _CORSRu }]] - ]; - exports.GetBucketCorsRequest$ = [ - 3, - n05, - _GBCR, - 0, - [_B, _EBO], - [[0, 1], [0, { [_hH2]: _xaebo }]], - 1 - ]; - exports.GetBucketEncryptionOutput$ = [ - 3, - n05, - _GBEO, - 0, - [_SSEC], - [[() => exports.ServerSideEncryptionConfiguration$, 16]] - ]; - exports.GetBucketEncryptionRequest$ = [ - 3, - n05, - _GBER, - 0, - [_B, _EBO], - [[0, 1], [0, { [_hH2]: _xaebo }]], - 1 - ]; - exports.GetBucketIntelligentTieringConfigurationOutput$ = [ - 3, - n05, - _GBITCO, - 0, - [_ITC], - [[() => exports.IntelligentTieringConfiguration$, 16]] - ]; - exports.GetBucketIntelligentTieringConfigurationRequest$ = [ - 3, - n05, - _GBITCR, - 0, - [_B, _I, _EBO], - [[0, 1], [0, { [_hQ2]: _i }], [0, { [_hH2]: _xaebo }]], - 2 - ]; - exports.GetBucketInventoryConfigurationOutput$ = [ - 3, - n05, - _GBICO, - 0, - [_IC], - [[() => exports.InventoryConfiguration$, 16]] - ]; - exports.GetBucketInventoryConfigurationRequest$ = [ - 3, - n05, - _GBICR, - 0, - [_B, _I, _EBO], - [[0, 1], [0, { [_hQ2]: _i }], [0, { [_hH2]: _xaebo }]], - 2 - ]; - exports.GetBucketLifecycleConfigurationOutput$ = [ - 3, - n05, - _GBLCO, - { [_xN]: _LCi }, - [_R, _TDMOS], - [[() => LifecycleRules, { [_xF]: 1, [_xN]: _Ru }], [0, { [_hH2]: _xatdmos }]] - ]; - exports.GetBucketLifecycleConfigurationRequest$ = [ - 3, - n05, - _GBLCR, - 0, - [_B, _EBO], - [[0, 1], [0, { [_hH2]: _xaebo }]], - 1 - ]; - exports.GetBucketLocationOutput$ = [ - 3, - n05, - _GBLO, - { [_xN]: _LC }, - [_LC], - [0] - ]; - exports.GetBucketLocationRequest$ = [ - 3, - n05, - _GBLR, - 0, - [_B, _EBO], - [[0, 1], [0, { [_hH2]: _xaebo }]], - 1 - ]; - exports.GetBucketLoggingOutput$ = [ - 3, - n05, - _GBLOe, - { [_xN]: _BLS }, - [_LE], - [[() => exports.LoggingEnabled$, 0]] - ]; - exports.GetBucketLoggingRequest$ = [ - 3, - n05, - _GBLRe, - 0, - [_B, _EBO], - [[0, 1], [0, { [_hH2]: _xaebo }]], - 1 - ]; - exports.GetBucketMetadataConfigurationOutput$ = [ - 3, - n05, - _GBMCO, - 0, - [_GBMCR], - [[() => exports.GetBucketMetadataConfigurationResult$, 16]] - ]; - exports.GetBucketMetadataConfigurationRequest$ = [ - 3, - n05, - _GBMCRe, - 0, - [_B, _EBO], - [[0, 1], [0, { [_hH2]: _xaebo }]], - 1 - ]; - exports.GetBucketMetadataConfigurationResult$ = [ - 3, - n05, - _GBMCR, - 0, - [_MCR], - [() => exports.MetadataConfigurationResult$], - 1 - ]; - exports.GetBucketMetadataTableConfigurationOutput$ = [ - 3, - n05, - _GBMTCO, - 0, - [_GBMTCR], - [[() => exports.GetBucketMetadataTableConfigurationResult$, 16]] - ]; - exports.GetBucketMetadataTableConfigurationRequest$ = [ - 3, - n05, - _GBMTCRe, - 0, - [_B, _EBO], - [[0, 1], [0, { [_hH2]: _xaebo }]], - 1 - ]; - exports.GetBucketMetadataTableConfigurationResult$ = [ - 3, - n05, - _GBMTCR, - 0, - [_MTCR, _S, _Err], - [() => exports.MetadataTableConfigurationResult$, 0, () => exports.ErrorDetails$], - 2 - ]; - exports.GetBucketMetricsConfigurationOutput$ = [ - 3, - n05, - _GBMCOe, - 0, - [_MCe], - [[() => exports.MetricsConfiguration$, 16]] - ]; - exports.GetBucketMetricsConfigurationRequest$ = [ - 3, - n05, - _GBMCRet, - 0, - [_B, _I, _EBO], - [[0, 1], [0, { [_hQ2]: _i }], [0, { [_hH2]: _xaebo }]], - 2 - ]; - exports.GetBucketNotificationConfigurationRequest$ = [ - 3, - n05, - _GBNCR, - 0, - [_B, _EBO], - [[0, 1], [0, { [_hH2]: _xaebo }]], - 1 - ]; - exports.GetBucketOwnershipControlsOutput$ = [ - 3, - n05, - _GBOCO, - 0, - [_OC], - [[() => exports.OwnershipControls$, 16]] - ]; - exports.GetBucketOwnershipControlsRequest$ = [ - 3, - n05, - _GBOCR, - 0, - [_B, _EBO], - [[0, 1], [0, { [_hH2]: _xaebo }]], - 1 - ]; - exports.GetBucketPolicyOutput$ = [ - 3, - n05, - _GBPO, - 0, - [_Po], - [[0, 16]] - ]; - exports.GetBucketPolicyRequest$ = [ - 3, - n05, - _GBPR, - 0, - [_B, _EBO], - [[0, 1], [0, { [_hH2]: _xaebo }]], - 1 - ]; - exports.GetBucketPolicyStatusOutput$ = [ - 3, - n05, - _GBPSO, - 0, - [_PS], - [[() => exports.PolicyStatus$, 16]] - ]; - exports.GetBucketPolicyStatusRequest$ = [ - 3, - n05, - _GBPSR, - 0, - [_B, _EBO], - [[0, 1], [0, { [_hH2]: _xaebo }]], - 1 - ]; - exports.GetBucketReplicationOutput$ = [ - 3, - n05, - _GBRO, - 0, - [_RCe], - [[() => exports.ReplicationConfiguration$, 16]] - ]; - exports.GetBucketReplicationRequest$ = [ - 3, - n05, - _GBRR, - 0, - [_B, _EBO], - [[0, 1], [0, { [_hH2]: _xaebo }]], - 1 - ]; - exports.GetBucketRequestPaymentOutput$ = [ - 3, - n05, - _GBRPO, - { [_xN]: _RPC }, - [_Pay], - [0] - ]; - exports.GetBucketRequestPaymentRequest$ = [ - 3, - n05, - _GBRPR, - 0, - [_B, _EBO], - [[0, 1], [0, { [_hH2]: _xaebo }]], - 1 - ]; - exports.GetBucketTaggingOutput$ = [ - 3, - n05, - _GBTO, - { [_xN]: _Tag }, - [_TS], - [[() => TagSet, 0]], - 1 - ]; - exports.GetBucketTaggingRequest$ = [ - 3, - n05, - _GBTR, - 0, - [_B, _EBO], - [[0, 1], [0, { [_hH2]: _xaebo }]], - 1 - ]; - exports.GetBucketVersioningOutput$ = [ - 3, - n05, - _GBVO, - { [_xN]: _VC }, - [_S, _MFAD], - [0, [0, { [_xN]: _MDf }]] - ]; - exports.GetBucketVersioningRequest$ = [ - 3, - n05, - _GBVR, - 0, - [_B, _EBO], - [[0, 1], [0, { [_hH2]: _xaebo }]], - 1 - ]; - exports.GetBucketWebsiteOutput$ = [ - 3, - n05, - _GBWO, - { [_xN]: _WC }, - [_RART, _IDn, _EDr, _RR], - [() => exports.RedirectAllRequestsTo$, () => exports.IndexDocument$, () => exports.ErrorDocument$, [() => RoutingRules, 0]] - ]; - exports.GetBucketWebsiteRequest$ = [ - 3, - n05, - _GBWR, - 0, - [_B, _EBO], - [[0, 1], [0, { [_hH2]: _xaebo }]], - 1 - ]; - exports.GetObjectAclOutput$ = [ - 3, - n05, - _GOAO, - { [_xN]: _ACP }, - [_O, _G, _RC2], - [() => exports.Owner$, [() => Grants, { [_xN]: _ACL }], [0, { [_hH2]: _xarc }]] - ]; - exports.GetObjectAclRequest$ = [ - 3, - n05, - _GOAR, - 0, - [_B, _K2, _VI, _RP, _EBO], - [[0, 1], [0, 1], [0, { [_hQ2]: _vI }], [0, { [_hH2]: _xarp }], [0, { [_hH2]: _xaebo }]], - 2 - ]; - exports.GetObjectAttributesOutput$ = [ - 3, - n05, - _GOAOe, - { [_xN]: _GOARe }, - [_DM, _LM, _VI, _RC2, _ETa, _C2, _OP, _SC, _OS], - [[2, { [_hH2]: _xadm }], [4, { [_hH2]: _LM_ }], [0, { [_hH2]: _xavi }], [0, { [_hH2]: _xarc }], 0, () => exports.Checksum$, [() => exports.GetObjectAttributesParts$, 0], 0, 1] - ]; - exports.GetObjectAttributesParts$ = [ - 3, - n05, - _GOAP, - 0, - [_TPC, _PNM, _NPNM, _MP, _IT2, _Pa], - [[1, { [_xN]: _PC2 }], 0, 0, 1, 2, [() => PartsList, { [_xF]: 1, [_xN]: _Par }]] - ]; - exports.GetObjectAttributesRequest$ = [ - 3, - n05, - _GOARet, - 0, - [_B, _K2, _OA, _VI, _MP, _PNM, _SSECA, _SSECK, _SSECKMD, _RP, _EBO], - [[0, 1], [0, 1], [64 | 0, { [_hH2]: _xaoa }], [0, { [_hQ2]: _vI }], [1, { [_hH2]: _xamp }], [0, { [_hH2]: _xapnm }], [0, { [_hH2]: _xasseca }], [() => SSECustomerKey, { [_hH2]: _xasseck }], [0, { [_hH2]: _xasseckM }], [0, { [_hH2]: _xarp }], [0, { [_hH2]: _xaebo }]], - 3 - ]; - exports.GetObjectLegalHoldOutput$ = [ - 3, - n05, - _GOLHO, - 0, - [_LH], - [[() => exports.ObjectLockLegalHold$, { [_hP]: 1, [_xN]: _LH }]] - ]; - exports.GetObjectLegalHoldRequest$ = [ - 3, - n05, - _GOLHR, - 0, - [_B, _K2, _VI, _RP, _EBO], - [[0, 1], [0, 1], [0, { [_hQ2]: _vI }], [0, { [_hH2]: _xarp }], [0, { [_hH2]: _xaebo }]], - 2 - ]; - exports.GetObjectLockConfigurationOutput$ = [ - 3, - n05, - _GOLCO, - 0, - [_OLC], - [[() => exports.ObjectLockConfiguration$, 16]] - ]; - exports.GetObjectLockConfigurationRequest$ = [ - 3, - n05, - _GOLCR, - 0, - [_B, _EBO], - [[0, 1], [0, { [_hH2]: _xaebo }]], - 1 - ]; - exports.GetObjectOutput$ = [ - 3, - n05, - _GOO, - 0, - [_Bo, _DM, _AR2, _E2, _Re, _LM, _CLo, _ETa, _CCRC, _CCRCC, _CCRCNVME, _CSHA, _CSHAh, _CT2, _MM, _VI, _CC, _CDo, _CEo, _CL, _CR, _CTo, _Ex, _ES, _WRL, _SSE, _M, _SSECA, _SSECKMD, _SSEKMSKI, _BKE, _SC, _RC2, _RS, _PC2, _TC2, _OLM, _OLRUD, _OLLHS], - [[() => StreamingBlob, 16], [2, { [_hH2]: _xadm }], [0, { [_hH2]: _ar }], [0, { [_hH2]: _xae }], [0, { [_hH2]: _xar }], [4, { [_hH2]: _LM_ }], [1, { [_hH2]: _CL__ }], [0, { [_hH2]: _ETa }], [0, { [_hH2]: _xacc }], [0, { [_hH2]: _xacc_ }], [0, { [_hH2]: _xacc__ }], [0, { [_hH2]: _xacs }], [0, { [_hH2]: _xacs_ }], [0, { [_hH2]: _xact }], [1, { [_hH2]: _xamm }], [0, { [_hH2]: _xavi }], [0, { [_hH2]: _CC_ }], [0, { [_hH2]: _CD_ }], [0, { [_hH2]: _CE_ }], [0, { [_hH2]: _CL_ }], [0, { [_hH2]: _CR_ }], [0, { [_hH2]: _CT_ }], [4, { [_hH2]: _Ex }], [0, { [_hH2]: _ES }], [0, { [_hH2]: _xawrl }], [0, { [_hH2]: _xasse }], [128 | 0, { [_hPH]: _xam }], [0, { [_hH2]: _xasseca }], [0, { [_hH2]: _xasseckM }], [() => SSEKMSKeyId, { [_hH2]: _xasseakki }], [2, { [_hH2]: _xassebke }], [0, { [_hH2]: _xasc }], [0, { [_hH2]: _xarc }], [0, { [_hH2]: _xars }], [1, { [_hH2]: _xampc }], [1, { [_hH2]: _xatc }], [0, { [_hH2]: _xaolm }], [5, { [_hH2]: _xaolrud }], [0, { [_hH2]: _xaollh }]] - ]; - exports.GetObjectRequest$ = [ - 3, - n05, - _GOR, - 0, - [_B, _K2, _IM, _IMSf, _INM, _IUS, _Ra, _RCC, _RCD, _RCE, _RCL, _RCT, _RE, _VI, _SSECA, _SSECK, _SSECKMD, _RP, _PN, _EBO, _CMh], - [[0, 1], [0, 1], [0, { [_hH2]: _IM_ }], [4, { [_hH2]: _IMS_ }], [0, { [_hH2]: _INM_ }], [4, { [_hH2]: _IUS_ }], [0, { [_hH2]: _Ra }], [0, { [_hQ2]: _rcc }], [0, { [_hQ2]: _rcd }], [0, { [_hQ2]: _rce }], [0, { [_hQ2]: _rcl }], [0, { [_hQ2]: _rct }], [6, { [_hQ2]: _re }], [0, { [_hQ2]: _vI }], [0, { [_hH2]: _xasseca }], [() => SSECustomerKey, { [_hH2]: _xasseck }], [0, { [_hH2]: _xasseckM }], [0, { [_hH2]: _xarp }], [1, { [_hQ2]: _pN }], [0, { [_hH2]: _xaebo }], [0, { [_hH2]: _xacm }]], - 2 - ]; - exports.GetObjectRetentionOutput$ = [ - 3, - n05, - _GORO, - 0, - [_Ret], - [[() => exports.ObjectLockRetention$, { [_hP]: 1, [_xN]: _Ret }]] - ]; - exports.GetObjectRetentionRequest$ = [ - 3, - n05, - _GORR, - 0, - [_B, _K2, _VI, _RP, _EBO], - [[0, 1], [0, 1], [0, { [_hQ2]: _vI }], [0, { [_hH2]: _xarp }], [0, { [_hH2]: _xaebo }]], - 2 - ]; - exports.GetObjectTaggingOutput$ = [ - 3, - n05, - _GOTO, - { [_xN]: _Tag }, - [_TS, _VI], - [[() => TagSet, 0], [0, { [_hH2]: _xavi }]], - 1 - ]; - exports.GetObjectTaggingRequest$ = [ - 3, - n05, - _GOTR, - 0, - [_B, _K2, _VI, _EBO, _RP], - [[0, 1], [0, 1], [0, { [_hQ2]: _vI }], [0, { [_hH2]: _xaebo }], [0, { [_hH2]: _xarp }]], - 2 - ]; - exports.GetObjectTorrentOutput$ = [ - 3, - n05, - _GOTOe, - 0, - [_Bo, _RC2], - [[() => StreamingBlob, 16], [0, { [_hH2]: _xarc }]] - ]; - exports.GetObjectTorrentRequest$ = [ - 3, - n05, - _GOTRe, - 0, - [_B, _K2, _RP, _EBO], - [[0, 1], [0, 1], [0, { [_hH2]: _xarp }], [0, { [_hH2]: _xaebo }]], - 2 - ]; - exports.GetPublicAccessBlockOutput$ = [ - 3, - n05, - _GPABO, - 0, - [_PABC], - [[() => exports.PublicAccessBlockConfiguration$, 16]] - ]; - exports.GetPublicAccessBlockRequest$ = [ - 3, - n05, - _GPABR, - 0, - [_B, _EBO], - [[0, 1], [0, { [_hH2]: _xaebo }]], - 1 - ]; - exports.GlacierJobParameters$ = [ - 3, - n05, - _GJP, - 0, - [_Ti], - [0], - 1 - ]; - exports.Grant$ = [ - 3, - n05, - _Gr, - 0, - [_Gra, _Pe], - [[() => exports.Grantee$, { [_xNm]: [_x, _hi] }], 0] - ]; - exports.Grantee$ = [ - 3, - n05, - _Gra, - 0, - [_Ty, _DN, _EA, _ID, _URI], - [[0, { [_xA]: 1, [_xN]: _xs }], 0, 0, 0, 0], - 1 - ]; - exports.HeadBucketOutput$ = [ - 3, - n05, - _HBO, - 0, - [_BA, _BLT, _BLN, _BR, _APA], - [[0, { [_hH2]: _xaba }], [0, { [_hH2]: _xablt }], [0, { [_hH2]: _xabln }], [0, { [_hH2]: _xabr }], [2, { [_hH2]: _xaapa }]] - ]; - exports.HeadBucketRequest$ = [ - 3, - n05, - _HBR, - 0, - [_B, _EBO], - [[0, 1], [0, { [_hH2]: _xaebo }]], - 1 - ]; - exports.HeadObjectOutput$ = [ - 3, - n05, - _HOO, - 0, - [_DM, _AR2, _E2, _Re, _ASr, _LM, _CLo, _CCRC, _CCRCC, _CCRCNVME, _CSHA, _CSHAh, _CT2, _ETa, _MM, _VI, _CC, _CDo, _CEo, _CL, _CTo, _CR, _Ex, _ES, _WRL, _SSE, _M, _SSECA, _SSECKMD, _SSEKMSKI, _BKE, _SC, _RC2, _RS, _PC2, _TC2, _OLM, _OLRUD, _OLLHS], - [[2, { [_hH2]: _xadm }], [0, { [_hH2]: _ar }], [0, { [_hH2]: _xae }], [0, { [_hH2]: _xar }], [0, { [_hH2]: _xaas }], [4, { [_hH2]: _LM_ }], [1, { [_hH2]: _CL__ }], [0, { [_hH2]: _xacc }], [0, { [_hH2]: _xacc_ }], [0, { [_hH2]: _xacc__ }], [0, { [_hH2]: _xacs }], [0, { [_hH2]: _xacs_ }], [0, { [_hH2]: _xact }], [0, { [_hH2]: _ETa }], [1, { [_hH2]: _xamm }], [0, { [_hH2]: _xavi }], [0, { [_hH2]: _CC_ }], [0, { [_hH2]: _CD_ }], [0, { [_hH2]: _CE_ }], [0, { [_hH2]: _CL_ }], [0, { [_hH2]: _CT_ }], [0, { [_hH2]: _CR_ }], [4, { [_hH2]: _Ex }], [0, { [_hH2]: _ES }], [0, { [_hH2]: _xawrl }], [0, { [_hH2]: _xasse }], [128 | 0, { [_hPH]: _xam }], [0, { [_hH2]: _xasseca }], [0, { [_hH2]: _xasseckM }], [() => SSEKMSKeyId, { [_hH2]: _xasseakki }], [2, { [_hH2]: _xassebke }], [0, { [_hH2]: _xasc }], [0, { [_hH2]: _xarc }], [0, { [_hH2]: _xars }], [1, { [_hH2]: _xampc }], [1, { [_hH2]: _xatc }], [0, { [_hH2]: _xaolm }], [5, { [_hH2]: _xaolrud }], [0, { [_hH2]: _xaollh }]] - ]; - exports.HeadObjectRequest$ = [ - 3, - n05, - _HOR, - 0, - [_B, _K2, _IM, _IMSf, _INM, _IUS, _Ra, _RCC, _RCD, _RCE, _RCL, _RCT, _RE, _VI, _SSECA, _SSECK, _SSECKMD, _RP, _PN, _EBO, _CMh], - [[0, 1], [0, 1], [0, { [_hH2]: _IM_ }], [4, { [_hH2]: _IMS_ }], [0, { [_hH2]: _INM_ }], [4, { [_hH2]: _IUS_ }], [0, { [_hH2]: _Ra }], [0, { [_hQ2]: _rcc }], [0, { [_hQ2]: _rcd }], [0, { [_hQ2]: _rce }], [0, { [_hQ2]: _rcl }], [0, { [_hQ2]: _rct }], [6, { [_hQ2]: _re }], [0, { [_hQ2]: _vI }], [0, { [_hH2]: _xasseca }], [() => SSECustomerKey, { [_hH2]: _xasseck }], [0, { [_hH2]: _xasseckM }], [0, { [_hH2]: _xarp }], [1, { [_hQ2]: _pN }], [0, { [_hH2]: _xaebo }], [0, { [_hH2]: _xacm }]], - 2 - ]; - exports.IndexDocument$ = [ - 3, - n05, - _IDn, - 0, - [_Su], - [0], - 1 - ]; - exports.Initiator$ = [ - 3, - n05, - _In, - 0, - [_ID, _DN], - [0, 0] - ]; - exports.InputSerialization$ = [ - 3, - n05, - _IS, - 0, - [_CSV, _CTom, _JSON, _Parq], - [() => exports.CSVInput$, 0, () => exports.JSONInput$, () => exports.ParquetInput$] - ]; - exports.IntelligentTieringAndOperator$ = [ - 3, - n05, - _ITAO, - 0, - [_P2, _T2], - [0, [() => TagSet, { [_xF]: 1, [_xN]: _Ta2 }]] - ]; - exports.IntelligentTieringConfiguration$ = [ - 3, - n05, - _ITC, - 0, - [_I, _S, _Tie, _F], - [0, 0, [() => TieringList, { [_xF]: 1, [_xN]: _Tier }], [() => exports.IntelligentTieringFilter$, 0]], - 3 - ]; - exports.IntelligentTieringFilter$ = [ - 3, - n05, - _ITF, - 0, - [_P2, _Ta2, _An], - [0, () => exports.Tag$, [() => exports.IntelligentTieringAndOperator$, 0]] - ]; - exports.InventoryConfiguration$ = [ - 3, - n05, - _IC, - 0, - [_Des, _IE, _I, _IOV, _Sc, _F, _OF], - [[() => exports.InventoryDestination$, 0], 2, 0, 0, () => exports.InventorySchedule$, () => exports.InventoryFilter$, [() => InventoryOptionalFields, 0]], - 5 - ]; - exports.InventoryDestination$ = [ - 3, - n05, - _IDnv, - 0, - [_SBD], - [[() => exports.InventoryS3BucketDestination$, 0]], - 1 - ]; - exports.InventoryEncryption$ = [ - 3, - n05, - _IEn, - 0, - [_SSES, _SSEKMS], - [[() => exports.SSES3$, { [_xN]: _SS }], [() => exports.SSEKMS$, { [_xN]: _SK }]] - ]; - exports.InventoryFilter$ = [ - 3, - n05, - _IF, - 0, - [_P2], - [0], - 1 - ]; - exports.InventoryS3BucketDestination$ = [ - 3, - n05, - _ISBD, - 0, - [_B, _Fo, _AI, _P2, _En], - [0, 0, 0, 0, [() => exports.InventoryEncryption$, 0]], - 2 - ]; - exports.InventorySchedule$ = [ - 3, - n05, - _ISn, - 0, - [_Fr], - [0], - 1 - ]; - exports.InventoryTableConfiguration$ = [ - 3, - n05, - _ITCn, - 0, - [_CSo, _EC], - [0, () => exports.MetadataTableEncryptionConfiguration$], - 1 - ]; - exports.InventoryTableConfigurationResult$ = [ - 3, - n05, - _ITCR, - 0, - [_CSo, _TSa, _Err, _TNa, _TA], - [0, 0, () => exports.ErrorDetails$, 0, 0], - 1 - ]; - exports.InventoryTableConfigurationUpdates$ = [ - 3, - n05, - _ITCU, - 0, - [_CSo, _EC], - [0, () => exports.MetadataTableEncryptionConfiguration$], - 1 - ]; - exports.JournalTableConfiguration$ = [ - 3, - n05, - _JTC, - 0, - [_REe, _EC], - [() => exports.RecordExpiration$, () => exports.MetadataTableEncryptionConfiguration$], - 1 - ]; - exports.JournalTableConfigurationResult$ = [ - 3, - n05, - _JTCR, - 0, - [_TSa, _TNa, _REe, _Err, _TA], - [0, 0, () => exports.RecordExpiration$, () => exports.ErrorDetails$, 0], - 3 - ]; - exports.JournalTableConfigurationUpdates$ = [ - 3, - n05, - _JTCU, - 0, - [_REe], - [() => exports.RecordExpiration$], - 1 - ]; - exports.JSONInput$ = [ - 3, - n05, - _JSONI, - 0, - [_Ty], - [0] - ]; - exports.JSONOutput$ = [ - 3, - n05, - _JSONO, - 0, - [_RD], - [0] - ]; - exports.LambdaFunctionConfiguration$ = [ - 3, - n05, - _LFC, - 0, - [_LFA, _Ev, _I, _F], - [[0, { [_xN]: _CF }], [64 | 0, { [_xF]: 1, [_xN]: _Eve }], 0, [() => exports.NotificationConfigurationFilter$, 0]], - 2 - ]; - exports.LifecycleExpiration$ = [ - 3, - n05, - _LEi, - 0, - [_Da, _D, _EODM], - [5, 1, 2] - ]; - exports.LifecycleRule$ = [ - 3, - n05, - _LR, - 0, - [_S, _E2, _ID, _P2, _F, _Tr, _NVT, _NVE, _AIMU], - [0, () => exports.LifecycleExpiration$, 0, 0, [() => exports.LifecycleRuleFilter$, 0], [() => TransitionList, { [_xF]: 1, [_xN]: _Tra }], [() => NoncurrentVersionTransitionList, { [_xF]: 1, [_xN]: _NVTo }], () => exports.NoncurrentVersionExpiration$, () => exports.AbortIncompleteMultipartUpload$], - 1 - ]; - exports.LifecycleRuleAndOperator$ = [ - 3, - n05, - _LRAO, - 0, - [_P2, _T2, _OSGT, _OSLT], - [0, [() => TagSet, { [_xF]: 1, [_xN]: _Ta2 }], 1, 1] - ]; - exports.LifecycleRuleFilter$ = [ - 3, - n05, - _LRF, - 0, - [_P2, _Ta2, _OSGT, _OSLT, _An], - [0, () => exports.Tag$, 1, 1, [() => exports.LifecycleRuleAndOperator$, 0]] - ]; - exports.ListBucketAnalyticsConfigurationsOutput$ = [ - 3, - n05, - _LBACO, - { [_xN]: _LBACR }, - [_IT2, _CTon, _NCT, _ACLn], - [2, 0, 0, [() => AnalyticsConfigurationList, { [_xF]: 1, [_xN]: _ACn }]] - ]; - exports.ListBucketAnalyticsConfigurationsRequest$ = [ - 3, - n05, - _LBACRi, - 0, - [_B, _CTon, _EBO], - [[0, 1], [0, { [_hQ2]: _ct }], [0, { [_hH2]: _xaebo }]], - 1 - ]; - exports.ListBucketIntelligentTieringConfigurationsOutput$ = [ - 3, - n05, - _LBITCO, - 0, - [_IT2, _CTon, _NCT, _ITCL], - [2, 0, 0, [() => IntelligentTieringConfigurationList, { [_xF]: 1, [_xN]: _ITC }]] - ]; - exports.ListBucketIntelligentTieringConfigurationsRequest$ = [ - 3, - n05, - _LBITCR, - 0, - [_B, _CTon, _EBO], - [[0, 1], [0, { [_hQ2]: _ct }], [0, { [_hH2]: _xaebo }]], - 1 - ]; - exports.ListBucketInventoryConfigurationsOutput$ = [ - 3, - n05, - _LBICO, - { [_xN]: _LICR }, - [_CTon, _ICL, _IT2, _NCT], - [0, [() => InventoryConfigurationList, { [_xF]: 1, [_xN]: _IC }], 2, 0] - ]; - exports.ListBucketInventoryConfigurationsRequest$ = [ - 3, - n05, - _LBICR, - 0, - [_B, _CTon, _EBO], - [[0, 1], [0, { [_hQ2]: _ct }], [0, { [_hH2]: _xaebo }]], - 1 - ]; - exports.ListBucketMetricsConfigurationsOutput$ = [ - 3, - n05, - _LBMCO, - { [_xN]: _LMCR }, - [_IT2, _CTon, _NCT, _MCL], - [2, 0, 0, [() => MetricsConfigurationList, { [_xF]: 1, [_xN]: _MCe }]] - ]; - exports.ListBucketMetricsConfigurationsRequest$ = [ - 3, - n05, - _LBMCR, - 0, - [_B, _CTon, _EBO], - [[0, 1], [0, { [_hQ2]: _ct }], [0, { [_hH2]: _xaebo }]], - 1 - ]; - exports.ListBucketsOutput$ = [ - 3, - n05, - _LBO, - { [_xN]: _LAMBR }, - [_Bu, _O, _CTon, _P2], - [[() => Buckets, 0], () => exports.Owner$, 0, 0] - ]; - exports.ListBucketsRequest$ = [ - 3, - n05, - _LBR, - 0, - [_MB, _CTon, _P2, _BR], - [[1, { [_hQ2]: _mb }], [0, { [_hQ2]: _ct }], [0, { [_hQ2]: _p }], [0, { [_hQ2]: _br }]] - ]; - exports.ListDirectoryBucketsOutput$ = [ - 3, - n05, - _LDBO, - { [_xN]: _LAMDBR }, - [_Bu, _CTon], - [[() => Buckets, 0], 0] - ]; - exports.ListDirectoryBucketsRequest$ = [ - 3, - n05, - _LDBR, - 0, - [_CTon, _MDB], - [[0, { [_hQ2]: _ct }], [1, { [_hQ2]: _mdb }]] - ]; - exports.ListMultipartUploadsOutput$ = [ - 3, - n05, - _LMUO, - { [_xN]: _LMUR }, - [_B, _KM, _UIM, _NKM, _P2, _Deli, _NUIM, _MUa, _IT2, _U, _CPom, _ETn, _RC2], - [0, 0, 0, 0, 0, 0, 0, 1, 2, [() => MultipartUploadList, { [_xF]: 1, [_xN]: _Up }], [() => CommonPrefixList, { [_xF]: 1 }], 0, [0, { [_hH2]: _xarc }]] - ]; - exports.ListMultipartUploadsRequest$ = [ - 3, - n05, - _LMURi, - 0, - [_B, _Deli, _ETn, _KM, _MUa, _P2, _UIM, _EBO, _RP], - [[0, 1], [0, { [_hQ2]: _d }], [0, { [_hQ2]: _et }], [0, { [_hQ2]: _km }], [1, { [_hQ2]: _mu }], [0, { [_hQ2]: _p }], [0, { [_hQ2]: _uim }], [0, { [_hH2]: _xaebo }], [0, { [_hH2]: _xarp }]], - 1 - ]; - exports.ListObjectsOutput$ = [ - 3, - n05, - _LOO, - { [_xN]: _LBRi }, - [_IT2, _Ma, _NM, _Con, _N, _P2, _Deli, _MK, _CPom, _ETn, _RC2], - [2, 0, 0, [() => ObjectList, { [_xF]: 1 }], 0, 0, 0, 1, [() => CommonPrefixList, { [_xF]: 1 }], 0, [0, { [_hH2]: _xarc }]] - ]; - exports.ListObjectsRequest$ = [ - 3, - n05, - _LOR, - 0, - [_B, _Deli, _ETn, _Ma, _MK, _P2, _RP, _EBO, _OOA], - [[0, 1], [0, { [_hQ2]: _d }], [0, { [_hQ2]: _et }], [0, { [_hQ2]: _m4 }], [1, { [_hQ2]: _mk }], [0, { [_hQ2]: _p }], [0, { [_hH2]: _xarp }], [0, { [_hH2]: _xaebo }], [64 | 0, { [_hH2]: _xaooa }]], - 1 - ]; - exports.ListObjectsV2Output$ = [ - 3, - n05, - _LOVO, - { [_xN]: _LBRi }, - [_IT2, _Con, _N, _P2, _Deli, _MK, _CPom, _ETn, _KC, _CTon, _NCT, _SA, _RC2], - [2, [() => ObjectList, { [_xF]: 1 }], 0, 0, 0, 1, [() => CommonPrefixList, { [_xF]: 1 }], 0, 1, 0, 0, 0, [0, { [_hH2]: _xarc }]] - ]; - exports.ListObjectsV2Request$ = [ - 3, - n05, - _LOVR, - 0, - [_B, _Deli, _ETn, _MK, _P2, _CTon, _FO, _SA, _RP, _EBO, _OOA], - [[0, 1], [0, { [_hQ2]: _d }], [0, { [_hQ2]: _et }], [1, { [_hQ2]: _mk }], [0, { [_hQ2]: _p }], [0, { [_hQ2]: _ct }], [2, { [_hQ2]: _fo }], [0, { [_hQ2]: _sa }], [0, { [_hH2]: _xarp }], [0, { [_hH2]: _xaebo }], [64 | 0, { [_hH2]: _xaooa }]], - 1 - ]; - exports.ListObjectVersionsOutput$ = [ - 3, - n05, - _LOVOi, - { [_xN]: _LVR }, - [_IT2, _KM, _VIM, _NKM, _NVIM, _Ve, _DMe, _N, _P2, _Deli, _MK, _CPom, _ETn, _RC2], - [2, 0, 0, 0, 0, [() => ObjectVersionList, { [_xF]: 1, [_xN]: _Ver }], [() => DeleteMarkers, { [_xF]: 1, [_xN]: _DM }], 0, 0, 0, 1, [() => CommonPrefixList, { [_xF]: 1 }], 0, [0, { [_hH2]: _xarc }]] - ]; - exports.ListObjectVersionsRequest$ = [ - 3, - n05, - _LOVRi, - 0, - [_B, _Deli, _ETn, _KM, _MK, _P2, _VIM, _EBO, _RP, _OOA], - [[0, 1], [0, { [_hQ2]: _d }], [0, { [_hQ2]: _et }], [0, { [_hQ2]: _km }], [1, { [_hQ2]: _mk }], [0, { [_hQ2]: _p }], [0, { [_hQ2]: _vim }], [0, { [_hH2]: _xaebo }], [0, { [_hH2]: _xarp }], [64 | 0, { [_hH2]: _xaooa }]], - 1 - ]; - exports.ListPartsOutput$ = [ - 3, - n05, - _LPO, - { [_xN]: _LPR }, - [_ADb, _ARI2, _B, _K2, _UI, _PNM, _NPNM, _MP, _IT2, _Pa, _In, _O, _SC, _RC2, _CA2, _CT2], - [[4, { [_hH2]: _xaad }], [0, { [_hH2]: _xaari }], 0, 0, 0, 0, 0, 1, 2, [() => Parts, { [_xF]: 1, [_xN]: _Par }], () => exports.Initiator$, () => exports.Owner$, 0, [0, { [_hH2]: _xarc }], 0, 0] - ]; - exports.ListPartsRequest$ = [ - 3, - n05, - _LPRi, - 0, - [_B, _K2, _UI, _MP, _PNM, _RP, _EBO, _SSECA, _SSECK, _SSECKMD], - [[0, 1], [0, 1], [0, { [_hQ2]: _uI }], [1, { [_hQ2]: _mp }], [0, { [_hQ2]: _pnm }], [0, { [_hH2]: _xarp }], [0, { [_hH2]: _xaebo }], [0, { [_hH2]: _xasseca }], [() => SSECustomerKey, { [_hH2]: _xasseck }], [0, { [_hH2]: _xasseckM }]], - 3 - ]; - exports.LocationInfo$ = [ - 3, - n05, - _LI, - 0, - [_Ty, _N], - [0, 0] - ]; - exports.LoggingEnabled$ = [ - 3, - n05, - _LE, - 0, - [_TB, _TP, _TG, _TOKF], - [0, 0, [() => TargetGrants, 0], [() => exports.TargetObjectKeyFormat$, 0]], - 2 - ]; - exports.MetadataConfiguration$ = [ - 3, - n05, - _MC, - 0, - [_JTC, _ITCn], - [() => exports.JournalTableConfiguration$, () => exports.InventoryTableConfiguration$], - 1 - ]; - exports.MetadataConfigurationResult$ = [ - 3, - n05, - _MCR, - 0, - [_DRes, _JTCR, _ITCR], - [() => exports.DestinationResult$, () => exports.JournalTableConfigurationResult$, () => exports.InventoryTableConfigurationResult$], - 1 - ]; - exports.MetadataEntry$ = [ - 3, - n05, - _ME, - 0, - [_N, _V2], - [0, 0] - ]; - exports.MetadataTableConfiguration$ = [ - 3, - n05, - _MTC, - 0, - [_STD], - [() => exports.S3TablesDestination$], - 1 - ]; - exports.MetadataTableConfigurationResult$ = [ - 3, - n05, - _MTCR, - 0, - [_STDR], - [() => exports.S3TablesDestinationResult$], - 1 - ]; - exports.MetadataTableEncryptionConfiguration$ = [ - 3, - n05, - _MTEC, - 0, - [_SAs, _KKA], - [0, 0], - 1 - ]; - exports.Metrics$ = [ - 3, - n05, - _Me, - 0, - [_S, _ETv], - [0, () => exports.ReplicationTimeValue$], - 1 - ]; - exports.MetricsAndOperator$ = [ - 3, - n05, - _MAO, - 0, - [_P2, _T2, _APAc], - [0, [() => TagSet, { [_xF]: 1, [_xN]: _Ta2 }], 0] - ]; - exports.MetricsConfiguration$ = [ - 3, - n05, - _MCe, - 0, - [_I, _F], - [0, [() => exports.MetricsFilter$, 0]], - 1 - ]; - exports.MultipartUpload$ = [ - 3, - n05, - _MU, - 0, - [_UI, _K2, _Ini, _SC, _O, _In, _CA2, _CT2], - [0, 0, 4, 0, () => exports.Owner$, () => exports.Initiator$, 0, 0] - ]; - exports.NoncurrentVersionExpiration$ = [ - 3, - n05, - _NVE, - 0, - [_ND, _NNV], - [1, 1] - ]; - exports.NoncurrentVersionTransition$ = [ - 3, - n05, - _NVTo, - 0, - [_ND, _SC, _NNV], - [1, 0, 1] - ]; - exports.NotificationConfiguration$ = [ - 3, - n05, - _NC, - 0, - [_TCo, _QCu, _LFCa, _EBC], - [[() => TopicConfigurationList, { [_xF]: 1, [_xN]: _TCop }], [() => QueueConfigurationList, { [_xF]: 1, [_xN]: _QCue }], [() => LambdaFunctionConfigurationList, { [_xF]: 1, [_xN]: _CFC }], () => exports.EventBridgeConfiguration$] - ]; - exports.NotificationConfigurationFilter$ = [ - 3, - n05, - _NCF, - 0, - [_K2], - [[() => exports.S3KeyFilter$, { [_xN]: _SKe }]] - ]; - exports._Object$ = [ - 3, - n05, - _Obj, - 0, - [_K2, _LM, _ETa, _CA2, _CT2, _Si, _SC, _O, _RSe], - [0, 4, 0, [64 | 0, { [_xF]: 1 }], 0, 1, 0, () => exports.Owner$, () => exports.RestoreStatus$] - ]; - exports.ObjectIdentifier$ = [ - 3, - n05, - _OI, - 0, - [_K2, _VI, _ETa, _LMT, _Si], - [0, 0, 0, 6, 1], - 1 - ]; - exports.ObjectLockConfiguration$ = [ - 3, - n05, - _OLC, - 0, - [_OLE, _Ru], - [0, () => exports.ObjectLockRule$] - ]; - exports.ObjectLockLegalHold$ = [ - 3, - n05, - _OLLH, - 0, - [_S], - [0] - ]; - exports.ObjectLockRetention$ = [ - 3, - n05, - _OLR, - 0, - [_Mo, _RUD], - [0, 5] - ]; - exports.ObjectLockRule$ = [ - 3, - n05, - _OLRb, - 0, - [_DRe], - [() => exports.DefaultRetention$] - ]; - exports.ObjectPart$ = [ - 3, - n05, - _OPb, - 0, - [_PN, _Si, _CCRC, _CCRCC, _CCRCNVME, _CSHA, _CSHAh], - [1, 1, 0, 0, 0, 0, 0] - ]; - exports.ObjectVersion$ = [ - 3, - n05, - _OV, - 0, - [_ETa, _CA2, _CT2, _Si, _SC, _K2, _VI, _IL, _LM, _O, _RSe], - [0, [64 | 0, { [_xF]: 1 }], 0, 1, 0, 0, 0, 2, 4, () => exports.Owner$, () => exports.RestoreStatus$] - ]; - exports.OutputLocation$ = [ - 3, - n05, - _OL, - 0, - [_S_], - [[() => exports.S3Location$, 0]] - ]; - exports.OutputSerialization$ = [ - 3, - n05, - _OSu, - 0, - [_CSV, _JSON], - [() => exports.CSVOutput$, () => exports.JSONOutput$] - ]; - exports.Owner$ = [ - 3, - n05, - _O, - 0, - [_DN, _ID], - [0, 0] - ]; - exports.OwnershipControls$ = [ - 3, - n05, - _OC, - 0, - [_R], - [[() => OwnershipControlsRules, { [_xF]: 1, [_xN]: _Ru }]], - 1 - ]; - exports.OwnershipControlsRule$ = [ - 3, - n05, - _OCR, - 0, - [_OO], - [0], - 1 - ]; - exports.ParquetInput$ = [ - 3, - n05, - _PI2, - 0, - [], - [] - ]; - exports.Part$ = [ - 3, - n05, - _Par, - 0, - [_PN, _LM, _ETa, _Si, _CCRC, _CCRCC, _CCRCNVME, _CSHA, _CSHAh], - [1, 4, 0, 1, 0, 0, 0, 0, 0] - ]; - exports.PartitionedPrefix$ = [ - 3, - n05, - _PP, - { [_xN]: _PP }, - [_PDS], - [0] - ]; - exports.PolicyStatus$ = [ - 3, - n05, - _PS, - 0, - [_IP], - [[2, { [_xN]: _IP }]] - ]; - exports.Progress$ = [ - 3, - n05, - _Pr2, - 0, - [_BS, _BP, _BRy], - [1, 1, 1] - ]; - exports.ProgressEvent$ = [ - 3, - n05, - _PE, - 0, - [_Det], - [[() => exports.Progress$, { [_eP]: 1 }]] - ]; - exports.PublicAccessBlockConfiguration$ = [ - 3, - n05, - _PABC, - 0, - [_BPA, _IPA, _BPP, _RPB], - [[2, { [_xN]: _BPA }], [2, { [_xN]: _IPA }], [2, { [_xN]: _BPP }], [2, { [_xN]: _RPB }]] - ]; - exports.PutBucketAbacRequest$ = [ - 3, - n05, - _PBAR, - 0, - [_B, _AS, _CMD, _CA2, _EBO], - [[0, 1], [() => exports.AbacStatus$, { [_hP]: 1, [_xN]: _AS }], [0, { [_hH2]: _CM }], [0, { [_hH2]: _xasca }], [0, { [_hH2]: _xaebo }]], - 2 - ]; - exports.PutBucketAccelerateConfigurationRequest$ = [ - 3, - n05, - _PBACR, - 0, - [_B, _AC, _EBO, _CA2], - [[0, 1], [() => exports.AccelerateConfiguration$, { [_hP]: 1, [_xN]: _AC }], [0, { [_hH2]: _xaebo }], [0, { [_hH2]: _xasca }]], - 2 - ]; - exports.PutBucketAclRequest$ = [ - 3, - n05, - _PBARu, - 0, - [_B, _ACL_, _ACP, _CMD, _CA2, _GFC, _GR, _GRACP, _GW, _GWACP, _EBO], - [[0, 1], [0, { [_hH2]: _xaa }], [() => exports.AccessControlPolicy$, { [_hP]: 1, [_xN]: _ACP }], [0, { [_hH2]: _CM }], [0, { [_hH2]: _xasca }], [0, { [_hH2]: _xagfc }], [0, { [_hH2]: _xagr }], [0, { [_hH2]: _xagra }], [0, { [_hH2]: _xagw }], [0, { [_hH2]: _xagwa }], [0, { [_hH2]: _xaebo }]], - 1 - ]; - exports.PutBucketAnalyticsConfigurationRequest$ = [ - 3, - n05, - _PBACRu, - 0, - [_B, _I, _ACn, _EBO], - [[0, 1], [0, { [_hQ2]: _i }], [() => exports.AnalyticsConfiguration$, { [_hP]: 1, [_xN]: _ACn }], [0, { [_hH2]: _xaebo }]], - 3 - ]; - exports.PutBucketCorsRequest$ = [ - 3, - n05, - _PBCR, - 0, - [_B, _CORSC, _CMD, _CA2, _EBO], - [[0, 1], [() => exports.CORSConfiguration$, { [_hP]: 1, [_xN]: _CORSC }], [0, { [_hH2]: _CM }], [0, { [_hH2]: _xasca }], [0, { [_hH2]: _xaebo }]], - 2 - ]; - exports.PutBucketEncryptionRequest$ = [ - 3, - n05, - _PBER, - 0, - [_B, _SSEC, _CMD, _CA2, _EBO], - [[0, 1], [() => exports.ServerSideEncryptionConfiguration$, { [_hP]: 1, [_xN]: _SSEC }], [0, { [_hH2]: _CM }], [0, { [_hH2]: _xasca }], [0, { [_hH2]: _xaebo }]], - 2 - ]; - exports.PutBucketIntelligentTieringConfigurationRequest$ = [ - 3, - n05, - _PBITCR, - 0, - [_B, _I, _ITC, _EBO], - [[0, 1], [0, { [_hQ2]: _i }], [() => exports.IntelligentTieringConfiguration$, { [_hP]: 1, [_xN]: _ITC }], [0, { [_hH2]: _xaebo }]], - 3 - ]; - exports.PutBucketInventoryConfigurationRequest$ = [ - 3, - n05, - _PBICR, - 0, - [_B, _I, _IC, _EBO], - [[0, 1], [0, { [_hQ2]: _i }], [() => exports.InventoryConfiguration$, { [_hP]: 1, [_xN]: _IC }], [0, { [_hH2]: _xaebo }]], - 3 - ]; - exports.PutBucketLifecycleConfigurationOutput$ = [ - 3, - n05, - _PBLCO, - 0, - [_TDMOS], - [[0, { [_hH2]: _xatdmos }]] - ]; - exports.PutBucketLifecycleConfigurationRequest$ = [ - 3, - n05, - _PBLCR, - 0, - [_B, _CA2, _LCi, _EBO, _TDMOS], - [[0, 1], [0, { [_hH2]: _xasca }], [() => exports.BucketLifecycleConfiguration$, { [_hP]: 1, [_xN]: _LCi }], [0, { [_hH2]: _xaebo }], [0, { [_hH2]: _xatdmos }]], - 1 - ]; - exports.PutBucketLoggingRequest$ = [ - 3, - n05, - _PBLR, - 0, - [_B, _BLS, _CMD, _CA2, _EBO], - [[0, 1], [() => exports.BucketLoggingStatus$, { [_hP]: 1, [_xN]: _BLS }], [0, { [_hH2]: _CM }], [0, { [_hH2]: _xasca }], [0, { [_hH2]: _xaebo }]], - 2 - ]; - exports.PutBucketMetricsConfigurationRequest$ = [ - 3, - n05, - _PBMCR, - 0, - [_B, _I, _MCe, _EBO], - [[0, 1], [0, { [_hQ2]: _i }], [() => exports.MetricsConfiguration$, { [_hP]: 1, [_xN]: _MCe }], [0, { [_hH2]: _xaebo }]], - 3 - ]; - exports.PutBucketNotificationConfigurationRequest$ = [ - 3, - n05, - _PBNCR, - 0, - [_B, _NC, _EBO, _SDV], - [[0, 1], [() => exports.NotificationConfiguration$, { [_hP]: 1, [_xN]: _NC }], [0, { [_hH2]: _xaebo }], [2, { [_hH2]: _xasdv }]], - 2 - ]; - exports.PutBucketOwnershipControlsRequest$ = [ - 3, - n05, - _PBOCR, - 0, - [_B, _OC, _CMD, _EBO, _CA2], - [[0, 1], [() => exports.OwnershipControls$, { [_hP]: 1, [_xN]: _OC }], [0, { [_hH2]: _CM }], [0, { [_hH2]: _xaebo }], [0, { [_hH2]: _xasca }]], - 2 - ]; - exports.PutBucketPolicyRequest$ = [ - 3, - n05, - _PBPR, - 0, - [_B, _Po, _CMD, _CA2, _CRSBA, _EBO], - [[0, 1], [0, 16], [0, { [_hH2]: _CM }], [0, { [_hH2]: _xasca }], [2, { [_hH2]: _xacrsba }], [0, { [_hH2]: _xaebo }]], - 2 - ]; - exports.PutBucketReplicationRequest$ = [ - 3, - n05, - _PBRR, - 0, - [_B, _RCe, _CMD, _CA2, _To, _EBO], - [[0, 1], [() => exports.ReplicationConfiguration$, { [_hP]: 1, [_xN]: _RCe }], [0, { [_hH2]: _CM }], [0, { [_hH2]: _xasca }], [0, { [_hH2]: _xabolt }], [0, { [_hH2]: _xaebo }]], - 2 - ]; - exports.PutBucketRequestPaymentRequest$ = [ - 3, - n05, - _PBRPR, - 0, - [_B, _RPC, _CMD, _CA2, _EBO], - [[0, 1], [() => exports.RequestPaymentConfiguration$, { [_hP]: 1, [_xN]: _RPC }], [0, { [_hH2]: _CM }], [0, { [_hH2]: _xasca }], [0, { [_hH2]: _xaebo }]], - 2 - ]; - exports.PutBucketTaggingRequest$ = [ - 3, - n05, - _PBTR, - 0, - [_B, _Tag, _CMD, _CA2, _EBO], - [[0, 1], [() => exports.Tagging$, { [_hP]: 1, [_xN]: _Tag }], [0, { [_hH2]: _CM }], [0, { [_hH2]: _xasca }], [0, { [_hH2]: _xaebo }]], - 2 - ]; - exports.PutBucketVersioningRequest$ = [ - 3, - n05, - _PBVR, - 0, - [_B, _VC, _CMD, _CA2, _MFA, _EBO], - [[0, 1], [() => exports.VersioningConfiguration$, { [_hP]: 1, [_xN]: _VC }], [0, { [_hH2]: _CM }], [0, { [_hH2]: _xasca }], [0, { [_hH2]: _xam_ }], [0, { [_hH2]: _xaebo }]], - 2 - ]; - exports.PutBucketWebsiteRequest$ = [ - 3, - n05, - _PBWR, - 0, - [_B, _WC, _CMD, _CA2, _EBO], - [[0, 1], [() => exports.WebsiteConfiguration$, { [_hP]: 1, [_xN]: _WC }], [0, { [_hH2]: _CM }], [0, { [_hH2]: _xasca }], [0, { [_hH2]: _xaebo }]], - 2 - ]; - exports.PutObjectAclOutput$ = [ - 3, - n05, - _POAO, - 0, - [_RC2], - [[0, { [_hH2]: _xarc }]] - ]; - exports.PutObjectAclRequest$ = [ - 3, - n05, - _POAR, - 0, - [_B, _K2, _ACL_, _ACP, _CMD, _CA2, _GFC, _GR, _GRACP, _GW, _GWACP, _RP, _VI, _EBO], - [[0, 1], [0, 1], [0, { [_hH2]: _xaa }], [() => exports.AccessControlPolicy$, { [_hP]: 1, [_xN]: _ACP }], [0, { [_hH2]: _CM }], [0, { [_hH2]: _xasca }], [0, { [_hH2]: _xagfc }], [0, { [_hH2]: _xagr }], [0, { [_hH2]: _xagra }], [0, { [_hH2]: _xagw }], [0, { [_hH2]: _xagwa }], [0, { [_hH2]: _xarp }], [0, { [_hQ2]: _vI }], [0, { [_hH2]: _xaebo }]], - 2 - ]; - exports.PutObjectLegalHoldOutput$ = [ - 3, - n05, - _POLHO, - 0, - [_RC2], - [[0, { [_hH2]: _xarc }]] - ]; - exports.PutObjectLegalHoldRequest$ = [ - 3, - n05, - _POLHR, - 0, - [_B, _K2, _LH, _RP, _VI, _CMD, _CA2, _EBO], - [[0, 1], [0, 1], [() => exports.ObjectLockLegalHold$, { [_hP]: 1, [_xN]: _LH }], [0, { [_hH2]: _xarp }], [0, { [_hQ2]: _vI }], [0, { [_hH2]: _CM }], [0, { [_hH2]: _xasca }], [0, { [_hH2]: _xaebo }]], - 2 - ]; - exports.PutObjectLockConfigurationOutput$ = [ - 3, - n05, - _POLCO, - 0, - [_RC2], - [[0, { [_hH2]: _xarc }]] - ]; - exports.PutObjectLockConfigurationRequest$ = [ - 3, - n05, - _POLCR, - 0, - [_B, _OLC, _RP, _To, _CMD, _CA2, _EBO], - [[0, 1], [() => exports.ObjectLockConfiguration$, { [_hP]: 1, [_xN]: _OLC }], [0, { [_hH2]: _xarp }], [0, { [_hH2]: _xabolt }], [0, { [_hH2]: _CM }], [0, { [_hH2]: _xasca }], [0, { [_hH2]: _xaebo }]], - 1 - ]; - exports.PutObjectOutput$ = [ - 3, - n05, - _POO, - 0, - [_E2, _ETa, _CCRC, _CCRCC, _CCRCNVME, _CSHA, _CSHAh, _CT2, _SSE, _VI, _SSECA, _SSECKMD, _SSEKMSKI, _SSEKMSEC, _BKE, _Si, _RC2], - [[0, { [_hH2]: _xae }], [0, { [_hH2]: _ETa }], [0, { [_hH2]: _xacc }], [0, { [_hH2]: _xacc_ }], [0, { [_hH2]: _xacc__ }], [0, { [_hH2]: _xacs }], [0, { [_hH2]: _xacs_ }], [0, { [_hH2]: _xact }], [0, { [_hH2]: _xasse }], [0, { [_hH2]: _xavi }], [0, { [_hH2]: _xasseca }], [0, { [_hH2]: _xasseckM }], [() => SSEKMSKeyId, { [_hH2]: _xasseakki }], [() => SSEKMSEncryptionContext, { [_hH2]: _xassec }], [2, { [_hH2]: _xassebke }], [1, { [_hH2]: _xaos }], [0, { [_hH2]: _xarc }]] - ]; - exports.PutObjectRequest$ = [ - 3, - n05, - _POR, - 0, - [_B, _K2, _ACL_, _Bo, _CC, _CDo, _CEo, _CL, _CLo, _CMD, _CTo, _CA2, _CCRC, _CCRCC, _CCRCNVME, _CSHA, _CSHAh, _Ex, _IM, _INM, _GFC, _GR, _GRACP, _GWACP, _WOB, _M, _SSE, _SC, _WRL, _SSECA, _SSECK, _SSECKMD, _SSEKMSKI, _SSEKMSEC, _BKE, _RP, _Tag, _OLM, _OLRUD, _OLLHS, _EBO], - [[0, 1], [0, 1], [0, { [_hH2]: _xaa }], [() => StreamingBlob, 16], [0, { [_hH2]: _CC_ }], [0, { [_hH2]: _CD_ }], [0, { [_hH2]: _CE_ }], [0, { [_hH2]: _CL_ }], [1, { [_hH2]: _CL__ }], [0, { [_hH2]: _CM }], [0, { [_hH2]: _CT_ }], [0, { [_hH2]: _xasca }], [0, { [_hH2]: _xacc }], [0, { [_hH2]: _xacc_ }], [0, { [_hH2]: _xacc__ }], [0, { [_hH2]: _xacs }], [0, { [_hH2]: _xacs_ }], [4, { [_hH2]: _Ex }], [0, { [_hH2]: _IM_ }], [0, { [_hH2]: _INM_ }], [0, { [_hH2]: _xagfc }], [0, { [_hH2]: _xagr }], [0, { [_hH2]: _xagra }], [0, { [_hH2]: _xagwa }], [1, { [_hH2]: _xawob }], [128 | 0, { [_hPH]: _xam }], [0, { [_hH2]: _xasse }], [0, { [_hH2]: _xasc }], [0, { [_hH2]: _xawrl }], [0, { [_hH2]: _xasseca }], [() => SSECustomerKey, { [_hH2]: _xasseck }], [0, { [_hH2]: _xasseckM }], [() => SSEKMSKeyId, { [_hH2]: _xasseakki }], [() => SSEKMSEncryptionContext, { [_hH2]: _xassec }], [2, { [_hH2]: _xassebke }], [0, { [_hH2]: _xarp }], [0, { [_hH2]: _xat }], [0, { [_hH2]: _xaolm }], [5, { [_hH2]: _xaolrud }], [0, { [_hH2]: _xaollh }], [0, { [_hH2]: _xaebo }]], - 2 - ]; - exports.PutObjectRetentionOutput$ = [ - 3, - n05, - _PORO, - 0, - [_RC2], - [[0, { [_hH2]: _xarc }]] - ]; - exports.PutObjectRetentionRequest$ = [ - 3, - n05, - _PORR, - 0, - [_B, _K2, _Ret, _RP, _VI, _BGR, _CMD, _CA2, _EBO], - [[0, 1], [0, 1], [() => exports.ObjectLockRetention$, { [_hP]: 1, [_xN]: _Ret }], [0, { [_hH2]: _xarp }], [0, { [_hQ2]: _vI }], [2, { [_hH2]: _xabgr }], [0, { [_hH2]: _CM }], [0, { [_hH2]: _xasca }], [0, { [_hH2]: _xaebo }]], - 2 - ]; - exports.PutObjectTaggingOutput$ = [ - 3, - n05, - _POTO, - 0, - [_VI], - [[0, { [_hH2]: _xavi }]] - ]; - exports.PutObjectTaggingRequest$ = [ - 3, - n05, - _POTR, - 0, - [_B, _K2, _Tag, _VI, _CMD, _CA2, _EBO, _RP], - [[0, 1], [0, 1], [() => exports.Tagging$, { [_hP]: 1, [_xN]: _Tag }], [0, { [_hQ2]: _vI }], [0, { [_hH2]: _CM }], [0, { [_hH2]: _xasca }], [0, { [_hH2]: _xaebo }], [0, { [_hH2]: _xarp }]], - 3 - ]; - exports.PutPublicAccessBlockRequest$ = [ - 3, - n05, - _PPABR, - 0, - [_B, _PABC, _CMD, _CA2, _EBO], - [[0, 1], [() => exports.PublicAccessBlockConfiguration$, { [_hP]: 1, [_xN]: _PABC }], [0, { [_hH2]: _CM }], [0, { [_hH2]: _xasca }], [0, { [_hH2]: _xaebo }]], - 2 - ]; - exports.QueueConfiguration$ = [ - 3, - n05, - _QCue, - 0, - [_QA, _Ev, _I, _F], - [[0, { [_xN]: _Qu }], [64 | 0, { [_xF]: 1, [_xN]: _Eve }], 0, [() => exports.NotificationConfigurationFilter$, 0]], - 2 - ]; - exports.RecordExpiration$ = [ - 3, - n05, - _REe, - 0, - [_E2, _D], - [0, 1], - 1 - ]; - exports.RecordsEvent$ = [ - 3, - n05, - _REec, - 0, - [_Payl], - [[21, { [_eP]: 1 }]] - ]; - exports.Redirect$ = [ - 3, - n05, - _Red, - 0, - [_HN, _HRC, _Pro, _RKPW, _RKW], - [0, 0, 0, 0, 0] - ]; - exports.RedirectAllRequestsTo$ = [ - 3, - n05, - _RART, - 0, - [_HN, _Pro], - [0, 0], - 1 - ]; - exports.RenameObjectOutput$ = [ - 3, - n05, - _ROO, - 0, - [], - [] - ]; - exports.RenameObjectRequest$ = [ - 3, - n05, - _ROR, - 0, - [_B, _K2, _RSen, _DIM, _DINM, _DIMS, _DIUS, _SIM, _SINM, _SIMS, _SIUS, _CTl], - [[0, 1], [0, 1], [0, { [_hH2]: _xars_ }], [0, { [_hH2]: _IM_ }], [0, { [_hH2]: _INM_ }], [4, { [_hH2]: _IMS_ }], [4, { [_hH2]: _IUS_ }], [0, { [_hH2]: _xarsim }], [0, { [_hH2]: _xarsinm }], [6, { [_hH2]: _xarsims }], [6, { [_hH2]: _xarsius }], [0, { [_hH2]: _xact_, [_iT3]: 1 }]], - 3 - ]; - exports.ReplicaModifications$ = [ - 3, - n05, - _RM, - 0, - [_S], - [0], - 1 - ]; - exports.ReplicationConfiguration$ = [ - 3, - n05, - _RCe, - 0, - [_Ro, _R], - [0, [() => ReplicationRules, { [_xF]: 1, [_xN]: _Ru }]], - 2 - ]; - exports.ReplicationRule$ = [ - 3, - n05, - _RRe, - 0, - [_S, _Des, _ID, _Pri, _P2, _F, _SSC, _EOR, _DMR], - [0, () => exports.Destination$, 0, 1, 0, [() => exports.ReplicationRuleFilter$, 0], () => exports.SourceSelectionCriteria$, () => exports.ExistingObjectReplication$, () => exports.DeleteMarkerReplication$], - 2 - ]; - exports.ReplicationRuleAndOperator$ = [ - 3, - n05, - _RRAO, - 0, - [_P2, _T2], - [0, [() => TagSet, { [_xF]: 1, [_xN]: _Ta2 }]] - ]; - exports.ReplicationRuleFilter$ = [ - 3, - n05, - _RRF, - 0, - [_P2, _Ta2, _An], - [0, () => exports.Tag$, [() => exports.ReplicationRuleAndOperator$, 0]] - ]; - exports.ReplicationTime$ = [ - 3, - n05, - _RT3, - 0, - [_S, _Tim], - [0, () => exports.ReplicationTimeValue$], - 2 - ]; - exports.ReplicationTimeValue$ = [ - 3, - n05, - _RTV, - 0, - [_Mi], - [1] - ]; - exports.RequestPaymentConfiguration$ = [ - 3, - n05, - _RPC, - 0, - [_Pay], - [0], - 1 - ]; - exports.RequestProgress$ = [ - 3, - n05, - _RPe, - 0, - [_Ena], - [2] - ]; - exports.RestoreObjectOutput$ = [ - 3, - n05, - _ROOe, - 0, - [_RC2, _ROP], - [[0, { [_hH2]: _xarc }], [0, { [_hH2]: _xarop }]] - ]; - exports.RestoreObjectRequest$ = [ - 3, - n05, - _RORe, - 0, - [_B, _K2, _VI, _RRes, _RP, _CA2, _EBO], - [[0, 1], [0, 1], [0, { [_hQ2]: _vI }], [() => exports.RestoreRequest$, { [_hP]: 1, [_xN]: _RRes }], [0, { [_hH2]: _xarp }], [0, { [_hH2]: _xasca }], [0, { [_hH2]: _xaebo }]], - 2 - ]; - exports.RestoreRequest$ = [ - 3, - n05, - _RRes, - 0, - [_D, _GJP, _Ty, _Ti, _Desc, _SP, _OL], - [1, () => exports.GlacierJobParameters$, 0, 0, 0, () => exports.SelectParameters$, [() => exports.OutputLocation$, 0]] - ]; - exports.RestoreStatus$ = [ - 3, - n05, - _RSe, - 0, - [_IRIP, _RED], - [2, 4] - ]; - exports.RoutingRule$ = [ - 3, - n05, - _RRo, - 0, - [_Red, _Co], - [() => exports.Redirect$, () => exports.Condition$], - 1 - ]; - exports.S3KeyFilter$ = [ - 3, - n05, - _SKF, - 0, - [_FRi], - [[() => FilterRuleList, { [_xF]: 1, [_xN]: _FR }]] - ]; - exports.S3Location$ = [ - 3, - n05, - _SL, - 0, - [_BNu, _P2, _En, _CACL, _ACL, _Tag, _UM, _SC], - [0, 0, [() => exports.Encryption$, 0], 0, [() => Grants, 0], [() => exports.Tagging$, 0], [() => UserMetadata, 0], 0], - 2 - ]; - exports.S3TablesDestination$ = [ - 3, - n05, - _STD, - 0, - [_TBA, _TNa], - [0, 0], - 2 - ]; - exports.S3TablesDestinationResult$ = [ - 3, - n05, - _STDR, - 0, - [_TBA, _TNa, _TA, _TN], - [0, 0, 0, 0], - 4 - ]; - exports.ScanRange$ = [ - 3, - n05, - _SR, - 0, - [_St, _End], - [1, 1] - ]; - exports.SelectObjectContentOutput$ = [ - 3, - n05, - _SOCO, - 0, - [_Payl], - [[() => exports.SelectObjectContentEventStream$, 16]] - ]; - exports.SelectObjectContentRequest$ = [ - 3, - n05, - _SOCR, - 0, - [_B, _K2, _Exp, _ETx, _IS, _OSu, _SSECA, _SSECK, _SSECKMD, _RPe, _SR, _EBO], - [[0, 1], [0, 1], 0, 0, () => exports.InputSerialization$, () => exports.OutputSerialization$, [0, { [_hH2]: _xasseca }], [() => SSECustomerKey, { [_hH2]: _xasseck }], [0, { [_hH2]: _xasseckM }], () => exports.RequestProgress$, () => exports.ScanRange$, [0, { [_hH2]: _xaebo }]], - 6 - ]; - exports.SelectParameters$ = [ - 3, - n05, - _SP, - 0, - [_IS, _ETx, _Exp, _OSu], - [() => exports.InputSerialization$, 0, 0, () => exports.OutputSerialization$], - 4 - ]; - exports.ServerSideEncryptionByDefault$ = [ - 3, - n05, - _SSEBD, - 0, - [_SSEA, _KMSMKID], - [0, [() => SSEKMSKeyId, 0]], - 1 - ]; - exports.ServerSideEncryptionConfiguration$ = [ - 3, - n05, - _SSEC, - 0, - [_R], - [[() => ServerSideEncryptionRules, { [_xF]: 1, [_xN]: _Ru }]], - 1 - ]; - exports.ServerSideEncryptionRule$ = [ - 3, - n05, - _SSER, - 0, - [_ASSEBD, _BKE, _BET], - [[() => exports.ServerSideEncryptionByDefault$, 0], 2, [() => exports.BlockedEncryptionTypes$, 0]] - ]; - exports.SessionCredentials$ = [ - 3, - n05, - _SCe, - 0, - [_AKI2, _SAK2, _ST2, _E2], - [[0, { [_xN]: _AKI2 }], [() => SessionCredentialValue, { [_xN]: _SAK2 }], [() => SessionCredentialValue, { [_xN]: _ST2 }], [4, { [_xN]: _E2 }]], - 4 - ]; - exports.SimplePrefix$ = [ - 3, - n05, - _SPi, - { [_xN]: _SPi }, - [], - [] - ]; - exports.SourceSelectionCriteria$ = [ - 3, - n05, - _SSC, - 0, - [_SKEO, _RM], - [() => exports.SseKmsEncryptedObjects$, () => exports.ReplicaModifications$] - ]; - exports.SSEKMS$ = [ - 3, - n05, - _SSEKMS, - { [_xN]: _SK }, - [_KI], - [[() => SSEKMSKeyId, 0]], - 1 - ]; - exports.SseKmsEncryptedObjects$ = [ - 3, - n05, - _SKEO, - 0, - [_S], - [0], - 1 - ]; - exports.SSEKMSEncryption$ = [ - 3, - n05, - _SSEKMSE, - { [_xN]: _SK }, - [_KMSKA, _BKE], - [[() => NonEmptyKmsKeyArnString, 0], 2], - 1 - ]; - exports.SSES3$ = [ - 3, - n05, - _SSES, - { [_xN]: _SS }, - [], - [] - ]; - exports.Stats$ = [ - 3, - n05, - _Sta, - 0, - [_BS, _BP, _BRy], - [1, 1, 1] - ]; - exports.StatsEvent$ = [ - 3, - n05, - _SE, - 0, - [_Det], - [[() => exports.Stats$, { [_eP]: 1 }]] - ]; - exports.StorageClassAnalysis$ = [ - 3, - n05, - _SCA, - 0, - [_DE], - [() => exports.StorageClassAnalysisDataExport$] - ]; - exports.StorageClassAnalysisDataExport$ = [ - 3, - n05, - _SCADE, - 0, - [_OSV, _Des], - [0, () => exports.AnalyticsExportDestination$], - 2 - ]; - exports.Tag$ = [ - 3, - n05, - _Ta2, - 0, - [_K2, _V2], - [0, 0], - 2 - ]; - exports.Tagging$ = [ - 3, - n05, - _Tag, - 0, - [_TS], - [[() => TagSet, 0]], - 1 - ]; - exports.TargetGrant$ = [ - 3, - n05, - _TGa, - 0, - [_Gra, _Pe], - [[() => exports.Grantee$, { [_xNm]: [_x, _hi] }], 0] - ]; - exports.TargetObjectKeyFormat$ = [ - 3, - n05, - _TOKF, - 0, - [_SPi, _PP], - [[() => exports.SimplePrefix$, { [_xN]: _SPi }], [() => exports.PartitionedPrefix$, { [_xN]: _PP }]] - ]; - exports.Tiering$ = [ - 3, - n05, - _Tier, - 0, - [_D, _AT3], - [1, 0], - 2 - ]; - exports.TopicConfiguration$ = [ - 3, - n05, - _TCop, - 0, - [_TAo, _Ev, _I, _F], - [[0, { [_xN]: _Top }], [64 | 0, { [_xF]: 1, [_xN]: _Eve }], 0, [() => exports.NotificationConfigurationFilter$, 0]], - 2 - ]; - exports.Transition$ = [ - 3, - n05, - _Tra, - 0, - [_Da, _D, _SC], - [5, 1, 0] - ]; - exports.UpdateBucketMetadataInventoryTableConfigurationRequest$ = [ - 3, - n05, - _UBMITCR, - 0, - [_B, _ITCn, _CMD, _CA2, _EBO], - [[0, 1], [() => exports.InventoryTableConfigurationUpdates$, { [_hP]: 1, [_xN]: _ITCn }], [0, { [_hH2]: _CM }], [0, { [_hH2]: _xasca }], [0, { [_hH2]: _xaebo }]], - 2 - ]; - exports.UpdateBucketMetadataJournalTableConfigurationRequest$ = [ - 3, - n05, - _UBMJTCR, - 0, - [_B, _JTC, _CMD, _CA2, _EBO], - [[0, 1], [() => exports.JournalTableConfigurationUpdates$, { [_hP]: 1, [_xN]: _JTC }], [0, { [_hH2]: _CM }], [0, { [_hH2]: _xasca }], [0, { [_hH2]: _xaebo }]], - 2 - ]; - exports.UpdateObjectEncryptionRequest$ = [ - 3, - n05, - _UOER, - 0, - [_B, _K2, _OE, _VI, _RP, _EBO, _CMD, _CA2], - [[0, 1], [0, 1], [() => exports.ObjectEncryption$, 16], [0, { [_hQ2]: _vI }], [0, { [_hH2]: _xarp }], [0, { [_hH2]: _xaebo }], [0, { [_hH2]: _CM }], [0, { [_hH2]: _xasca }]], - 3 - ]; - exports.UpdateObjectEncryptionResponse$ = [ - 3, - n05, - _UOERp, - 0, - [_RC2], - [[0, { [_hH2]: _xarc }]] - ]; - exports.UploadPartCopyOutput$ = [ - 3, - n05, - _UPCO, - 0, - [_CSVI, _CPR, _SSE, _SSECA, _SSECKMD, _SSEKMSKI, _BKE, _RC2], - [[0, { [_hH2]: _xacsvi }], [() => exports.CopyPartResult$, 16], [0, { [_hH2]: _xasse }], [0, { [_hH2]: _xasseca }], [0, { [_hH2]: _xasseckM }], [() => SSEKMSKeyId, { [_hH2]: _xasseakki }], [2, { [_hH2]: _xassebke }], [0, { [_hH2]: _xarc }]] - ]; - exports.UploadPartCopyRequest$ = [ - 3, - n05, - _UPCR, - 0, - [_B, _CS2, _K2, _PN, _UI, _CSIM, _CSIMS, _CSINM, _CSIUS, _CSRo, _SSECA, _SSECK, _SSECKMD, _CSSSECA, _CSSSECK, _CSSSECKMD, _RP, _EBO, _ESBO], - [[0, 1], [0, { [_hH2]: _xacs__ }], [0, 1], [1, { [_hQ2]: _pN }], [0, { [_hQ2]: _uI }], [0, { [_hH2]: _xacsim }], [4, { [_hH2]: _xacsims }], [0, { [_hH2]: _xacsinm }], [4, { [_hH2]: _xacsius }], [0, { [_hH2]: _xacsr }], [0, { [_hH2]: _xasseca }], [() => SSECustomerKey, { [_hH2]: _xasseck }], [0, { [_hH2]: _xasseckM }], [0, { [_hH2]: _xacssseca }], [() => CopySourceSSECustomerKey, { [_hH2]: _xacssseck }], [0, { [_hH2]: _xacssseckM }], [0, { [_hH2]: _xarp }], [0, { [_hH2]: _xaebo }], [0, { [_hH2]: _xasebo }]], - 5 - ]; - exports.UploadPartOutput$ = [ - 3, - n05, - _UPO, - 0, - [_SSE, _ETa, _CCRC, _CCRCC, _CCRCNVME, _CSHA, _CSHAh, _SSECA, _SSECKMD, _SSEKMSKI, _BKE, _RC2], - [[0, { [_hH2]: _xasse }], [0, { [_hH2]: _ETa }], [0, { [_hH2]: _xacc }], [0, { [_hH2]: _xacc_ }], [0, { [_hH2]: _xacc__ }], [0, { [_hH2]: _xacs }], [0, { [_hH2]: _xacs_ }], [0, { [_hH2]: _xasseca }], [0, { [_hH2]: _xasseckM }], [() => SSEKMSKeyId, { [_hH2]: _xasseakki }], [2, { [_hH2]: _xassebke }], [0, { [_hH2]: _xarc }]] - ]; - exports.UploadPartRequest$ = [ - 3, - n05, - _UPR, - 0, - [_B, _K2, _PN, _UI, _Bo, _CLo, _CMD, _CA2, _CCRC, _CCRCC, _CCRCNVME, _CSHA, _CSHAh, _SSECA, _SSECK, _SSECKMD, _RP, _EBO], - [[0, 1], [0, 1], [1, { [_hQ2]: _pN }], [0, { [_hQ2]: _uI }], [() => StreamingBlob, 16], [1, { [_hH2]: _CL__ }], [0, { [_hH2]: _CM }], [0, { [_hH2]: _xasca }], [0, { [_hH2]: _xacc }], [0, { [_hH2]: _xacc_ }], [0, { [_hH2]: _xacc__ }], [0, { [_hH2]: _xacs }], [0, { [_hH2]: _xacs_ }], [0, { [_hH2]: _xasseca }], [() => SSECustomerKey, { [_hH2]: _xasseck }], [0, { [_hH2]: _xasseckM }], [0, { [_hH2]: _xarp }], [0, { [_hH2]: _xaebo }]], - 4 - ]; - exports.VersioningConfiguration$ = [ - 3, - n05, - _VC, - 0, - [_MFAD, _S], - [[0, { [_xN]: _MDf }], 0] - ]; - exports.WebsiteConfiguration$ = [ - 3, - n05, - _WC, - 0, - [_EDr, _IDn, _RART, _RR], - [() => exports.ErrorDocument$, () => exports.IndexDocument$, () => exports.RedirectAllRequestsTo$, [() => RoutingRules, 0]] - ]; - exports.WriteGetObjectResponseRequest$ = [ - 3, - n05, - _WGORR, - 0, - [_RReq, _RTe, _Bo, _SCt, _ECr, _EM, _AR2, _CC, _CDo, _CEo, _CL, _CLo, _CR, _CTo, _CCRC, _CCRCC, _CCRCNVME, _CSHA, _CSHAh, _DM, _ETa, _Ex, _E2, _LM, _MM, _M, _OLM, _OLLHS, _OLRUD, _PC2, _RS, _RC2, _Re, _SSE, _SSECA, _SSEKMSKI, _SSECKMD, _SC, _TC2, _VI, _BKE], - [[0, { [_hL]: 1, [_hH2]: _xarr }], [0, { [_hH2]: _xart }], [() => StreamingBlob, 16], [1, { [_hH2]: _xafs }], [0, { [_hH2]: _xafec }], [0, { [_hH2]: _xafem }], [0, { [_hH2]: _xafhar }], [0, { [_hH2]: _xafhCC }], [0, { [_hH2]: _xafhCD }], [0, { [_hH2]: _xafhCE }], [0, { [_hH2]: _xafhCL }], [1, { [_hH2]: _CL__ }], [0, { [_hH2]: _xafhCR }], [0, { [_hH2]: _xafhCT }], [0, { [_hH2]: _xafhxacc }], [0, { [_hH2]: _xafhxacc_ }], [0, { [_hH2]: _xafhxacc__ }], [0, { [_hH2]: _xafhxacs }], [0, { [_hH2]: _xafhxacs_ }], [2, { [_hH2]: _xafhxadm }], [0, { [_hH2]: _xafhE }], [4, { [_hH2]: _xafhE_ }], [0, { [_hH2]: _xafhxae }], [4, { [_hH2]: _xafhLM }], [1, { [_hH2]: _xafhxamm }], [128 | 0, { [_hPH]: _xam }], [0, { [_hH2]: _xafhxaolm }], [0, { [_hH2]: _xafhxaollh }], [5, { [_hH2]: _xafhxaolrud }], [1, { [_hH2]: _xafhxampc }], [0, { [_hH2]: _xafhxars }], [0, { [_hH2]: _xafhxarc }], [0, { [_hH2]: _xafhxar }], [0, { [_hH2]: _xafhxasse }], [0, { [_hH2]: _xafhxasseca }], [() => SSEKMSKeyId, { [_hH2]: _xafhxasseakki }], [0, { [_hH2]: _xafhxasseckM }], [0, { [_hH2]: _xafhxasc }], [1, { [_hH2]: _xafhxatc }], [0, { [_hH2]: _xafhxavi }], [2, { [_hH2]: _xafhxassebke }]], - 2 - ]; - var __Unit = "unit"; - var AllowedHeaders = 64 | 0; - var AllowedMethods = 64 | 0; - var AllowedOrigins = 64 | 0; - var AnalyticsConfigurationList = [ - 1, - n05, - _ACLn, - 0, - [ - () => exports.AnalyticsConfiguration$, - 0 - ] - ]; - var Buckets = [ - 1, - n05, - _Bu, - 0, - [ - () => exports.Bucket$, - { [_xN]: _B } - ] - ]; - var ChecksumAlgorithmList = 64 | 0; - var CommonPrefixList = [ - 1, - n05, - _CPL, - 0, - () => exports.CommonPrefix$ - ]; - var CompletedPartList = [ - 1, - n05, - _CPLo, - 0, - () => exports.CompletedPart$ - ]; - var CORSRules = [ - 1, - n05, - _CORSR, - 0, - [ - () => exports.CORSRule$, - 0 - ] - ]; - var DeletedObjects = [ - 1, - n05, - _DOe, - 0, - () => exports.DeletedObject$ - ]; - var DeleteMarkers = [ - 1, - n05, - _DMe, - 0, - () => exports.DeleteMarkerEntry$ - ]; - var EncryptionTypeList = [ - 1, - n05, - _ETL, - 0, - [ - 0, - { [_xN]: _ET } - ] - ]; - var Errors2 = [ - 1, - n05, - _Er, - 0, - () => exports._Error$ - ]; - var EventList = 64 | 0; - var ExposeHeaders = 64 | 0; - var FilterRuleList = [ - 1, - n05, - _FRL, - 0, - () => exports.FilterRule$ - ]; - var Grants = [ - 1, - n05, - _G, - 0, - [ - () => exports.Grant$, - { [_xN]: _Gr } - ] - ]; - var IntelligentTieringConfigurationList = [ - 1, - n05, - _ITCL, - 0, - [ - () => exports.IntelligentTieringConfiguration$, - 0 - ] - ]; - var InventoryConfigurationList = [ - 1, - n05, - _ICL, - 0, - [ - () => exports.InventoryConfiguration$, - 0 - ] - ]; - var InventoryOptionalFields = [ - 1, - n05, - _IOF, - 0, - [ - 0, - { [_xN]: _Fi } - ] - ]; - var LambdaFunctionConfigurationList = [ - 1, - n05, - _LFCL, - 0, - [ - () => exports.LambdaFunctionConfiguration$, - 0 - ] - ]; - var LifecycleRules = [ - 1, - n05, - _LRi, - 0, - [ - () => exports.LifecycleRule$, - 0 - ] - ]; - var MetricsConfigurationList = [ - 1, - n05, - _MCL, - 0, - [ - () => exports.MetricsConfiguration$, - 0 - ] - ]; - var MultipartUploadList = [ - 1, - n05, - _MUL, - 0, - () => exports.MultipartUpload$ - ]; - var NoncurrentVersionTransitionList = [ - 1, - n05, - _NVTL, - 0, - () => exports.NoncurrentVersionTransition$ - ]; - var ObjectAttributesList = 64 | 0; - var ObjectIdentifierList = [ - 1, - n05, - _OIL, - 0, - () => exports.ObjectIdentifier$ - ]; - var ObjectList = [ - 1, - n05, - _OLb, - 0, - [ - () => exports._Object$, - 0 - ] - ]; - var ObjectVersionList = [ - 1, - n05, - _OVL, - 0, - [ - () => exports.ObjectVersion$, - 0 - ] - ]; - var OptionalObjectAttributesList = 64 | 0; - var OwnershipControlsRules = [ - 1, - n05, - _OCRw, - 0, - () => exports.OwnershipControlsRule$ - ]; - var Parts = [ - 1, - n05, - _Pa, - 0, - () => exports.Part$ - ]; - var PartsList = [ - 1, - n05, - _PL, - 0, - () => exports.ObjectPart$ - ]; - var QueueConfigurationList = [ - 1, - n05, - _QCL, - 0, - [ - () => exports.QueueConfiguration$, - 0 - ] - ]; - var ReplicationRules = [ - 1, - n05, - _RRep, - 0, - [ - () => exports.ReplicationRule$, - 0 - ] - ]; - var RoutingRules = [ - 1, - n05, - _RR, - 0, - [ - () => exports.RoutingRule$, - { [_xN]: _RRo } - ] - ]; - var ServerSideEncryptionRules = [ - 1, - n05, - _SSERe, - 0, - [ - () => exports.ServerSideEncryptionRule$, - 0 - ] - ]; - var TagSet = [ - 1, - n05, - _TS, - 0, - [ - () => exports.Tag$, - { [_xN]: _Ta2 } - ] - ]; - var TargetGrants = [ - 1, - n05, - _TG, - 0, - [ - () => exports.TargetGrant$, - { [_xN]: _Gr } - ] - ]; - var TieringList = [ - 1, - n05, - _TL, - 0, - () => exports.Tiering$ - ]; - var TopicConfigurationList = [ - 1, - n05, - _TCL, - 0, - [ - () => exports.TopicConfiguration$, - 0 - ] - ]; - var TransitionList = [ - 1, - n05, - _TLr, - 0, - () => exports.Transition$ - ]; - var UserMetadata = [ - 1, - n05, - _UM, - 0, - [ - () => exports.MetadataEntry$, - { [_xN]: _ME } - ] - ]; - var Metadata = 128 | 0; - exports.AnalyticsFilter$ = [ - 4, - n05, - _AF, - 0, - [_P2, _Ta2, _An], - [0, () => exports.Tag$, [() => exports.AnalyticsAndOperator$, 0]] - ]; - exports.MetricsFilter$ = [ - 4, - n05, - _MF, - 0, - [_P2, _Ta2, _APAc, _An], - [0, () => exports.Tag$, 0, [() => exports.MetricsAndOperator$, 0]] - ]; - exports.ObjectEncryption$ = [ - 4, - n05, - _OE, - 0, - [_SSEKMS], - [[() => exports.SSEKMSEncryption$, { [_xN]: _SK }]] - ]; - exports.SelectObjectContentEventStream$ = [ - 4, - n05, - _SOCES, - { [_st]: 1 }, - [_Rec, _Sta, _Pr2, _Cont, _End], - [[() => exports.RecordsEvent$, 0], [() => exports.StatsEvent$, 0], [() => exports.ProgressEvent$, 0], () => exports.ContinuationEvent$, () => exports.EndEvent$] - ]; - exports.AbortMultipartUpload$ = [ - 9, - n05, - _AMU, - { [_h4]: ["DELETE", "/{Key+}?x-id=AbortMultipartUpload", 204] }, - () => exports.AbortMultipartUploadRequest$, - () => exports.AbortMultipartUploadOutput$ - ]; - exports.CompleteMultipartUpload$ = [ - 9, - n05, - _CMUo, - { [_h4]: ["POST", "/{Key+}", 200] }, - () => exports.CompleteMultipartUploadRequest$, - () => exports.CompleteMultipartUploadOutput$ - ]; - exports.CopyObject$ = [ - 9, - n05, - _CO, - { [_h4]: ["PUT", "/{Key+}?x-id=CopyObject", 200] }, - () => exports.CopyObjectRequest$, - () => exports.CopyObjectOutput$ - ]; - exports.CreateBucket$ = [ - 9, - n05, - _CB, - { [_h4]: ["PUT", "/", 200] }, - () => exports.CreateBucketRequest$, - () => exports.CreateBucketOutput$ - ]; - exports.CreateBucketMetadataConfiguration$ = [ - 9, - n05, - _CBMC, - { [_hC]: "-", [_h4]: ["POST", "/?metadataConfiguration", 200] }, - () => exports.CreateBucketMetadataConfigurationRequest$, - () => __Unit - ]; - exports.CreateBucketMetadataTableConfiguration$ = [ - 9, - n05, - _CBMTC, - { [_hC]: "-", [_h4]: ["POST", "/?metadataTable", 200] }, - () => exports.CreateBucketMetadataTableConfigurationRequest$, - () => __Unit - ]; - exports.CreateMultipartUpload$ = [ - 9, - n05, - _CMUr, - { [_h4]: ["POST", "/{Key+}?uploads", 200] }, - () => exports.CreateMultipartUploadRequest$, - () => exports.CreateMultipartUploadOutput$ - ]; - exports.CreateSession$ = [ - 9, - n05, - _CSr, - { [_h4]: ["GET", "/?session", 200] }, - () => exports.CreateSessionRequest$, - () => exports.CreateSessionOutput$ - ]; - exports.DeleteBucket$ = [ - 9, - n05, - _DB, - { [_h4]: ["DELETE", "/", 204] }, - () => exports.DeleteBucketRequest$, - () => __Unit - ]; - exports.DeleteBucketAnalyticsConfiguration$ = [ - 9, - n05, - _DBAC, - { [_h4]: ["DELETE", "/?analytics", 204] }, - () => exports.DeleteBucketAnalyticsConfigurationRequest$, - () => __Unit - ]; - exports.DeleteBucketCors$ = [ - 9, - n05, - _DBC, - { [_h4]: ["DELETE", "/?cors", 204] }, - () => exports.DeleteBucketCorsRequest$, - () => __Unit - ]; - exports.DeleteBucketEncryption$ = [ - 9, - n05, - _DBE, - { [_h4]: ["DELETE", "/?encryption", 204] }, - () => exports.DeleteBucketEncryptionRequest$, - () => __Unit - ]; - exports.DeleteBucketIntelligentTieringConfiguration$ = [ - 9, - n05, - _DBITC, - { [_h4]: ["DELETE", "/?intelligent-tiering", 204] }, - () => exports.DeleteBucketIntelligentTieringConfigurationRequest$, - () => __Unit - ]; - exports.DeleteBucketInventoryConfiguration$ = [ - 9, - n05, - _DBIC, - { [_h4]: ["DELETE", "/?inventory", 204] }, - () => exports.DeleteBucketInventoryConfigurationRequest$, - () => __Unit - ]; - exports.DeleteBucketLifecycle$ = [ - 9, - n05, - _DBL, - { [_h4]: ["DELETE", "/?lifecycle", 204] }, - () => exports.DeleteBucketLifecycleRequest$, - () => __Unit - ]; - exports.DeleteBucketMetadataConfiguration$ = [ - 9, - n05, - _DBMC, - { [_h4]: ["DELETE", "/?metadataConfiguration", 204] }, - () => exports.DeleteBucketMetadataConfigurationRequest$, - () => __Unit - ]; - exports.DeleteBucketMetadataTableConfiguration$ = [ - 9, - n05, - _DBMTC, - { [_h4]: ["DELETE", "/?metadataTable", 204] }, - () => exports.DeleteBucketMetadataTableConfigurationRequest$, - () => __Unit - ]; - exports.DeleteBucketMetricsConfiguration$ = [ - 9, - n05, - _DBMCe, - { [_h4]: ["DELETE", "/?metrics", 204] }, - () => exports.DeleteBucketMetricsConfigurationRequest$, - () => __Unit - ]; - exports.DeleteBucketOwnershipControls$ = [ - 9, - n05, - _DBOC, - { [_h4]: ["DELETE", "/?ownershipControls", 204] }, - () => exports.DeleteBucketOwnershipControlsRequest$, - () => __Unit - ]; - exports.DeleteBucketPolicy$ = [ - 9, - n05, - _DBP, - { [_h4]: ["DELETE", "/?policy", 204] }, - () => exports.DeleteBucketPolicyRequest$, - () => __Unit - ]; - exports.DeleteBucketReplication$ = [ - 9, - n05, - _DBRe, - { [_h4]: ["DELETE", "/?replication", 204] }, - () => exports.DeleteBucketReplicationRequest$, - () => __Unit - ]; - exports.DeleteBucketTagging$ = [ - 9, - n05, - _DBT, - { [_h4]: ["DELETE", "/?tagging", 204] }, - () => exports.DeleteBucketTaggingRequest$, - () => __Unit - ]; - exports.DeleteBucketWebsite$ = [ - 9, - n05, - _DBW, - { [_h4]: ["DELETE", "/?website", 204] }, - () => exports.DeleteBucketWebsiteRequest$, - () => __Unit - ]; - exports.DeleteObject$ = [ - 9, - n05, - _DOel, - { [_h4]: ["DELETE", "/{Key+}?x-id=DeleteObject", 204] }, - () => exports.DeleteObjectRequest$, - () => exports.DeleteObjectOutput$ - ]; - exports.DeleteObjects$ = [ - 9, - n05, - _DOele, - { [_hC]: "-", [_h4]: ["POST", "/?delete", 200] }, - () => exports.DeleteObjectsRequest$, - () => exports.DeleteObjectsOutput$ - ]; - exports.DeleteObjectTagging$ = [ - 9, - n05, - _DOT, - { [_h4]: ["DELETE", "/{Key+}?tagging", 204] }, - () => exports.DeleteObjectTaggingRequest$, - () => exports.DeleteObjectTaggingOutput$ - ]; - exports.DeletePublicAccessBlock$ = [ - 9, - n05, - _DPAB, - { [_h4]: ["DELETE", "/?publicAccessBlock", 204] }, - () => exports.DeletePublicAccessBlockRequest$, - () => __Unit - ]; - exports.GetBucketAbac$ = [ - 9, - n05, - _GBA, - { [_h4]: ["GET", "/?abac", 200] }, - () => exports.GetBucketAbacRequest$, - () => exports.GetBucketAbacOutput$ - ]; - exports.GetBucketAccelerateConfiguration$ = [ - 9, - n05, - _GBAC, - { [_h4]: ["GET", "/?accelerate", 200] }, - () => exports.GetBucketAccelerateConfigurationRequest$, - () => exports.GetBucketAccelerateConfigurationOutput$ - ]; - exports.GetBucketAcl$ = [ - 9, - n05, - _GBAe, - { [_h4]: ["GET", "/?acl", 200] }, - () => exports.GetBucketAclRequest$, - () => exports.GetBucketAclOutput$ - ]; - exports.GetBucketAnalyticsConfiguration$ = [ - 9, - n05, - _GBACe, - { [_h4]: ["GET", "/?analytics&x-id=GetBucketAnalyticsConfiguration", 200] }, - () => exports.GetBucketAnalyticsConfigurationRequest$, - () => exports.GetBucketAnalyticsConfigurationOutput$ - ]; - exports.GetBucketCors$ = [ - 9, - n05, - _GBC, - { [_h4]: ["GET", "/?cors", 200] }, - () => exports.GetBucketCorsRequest$, - () => exports.GetBucketCorsOutput$ - ]; - exports.GetBucketEncryption$ = [ - 9, - n05, - _GBE, - { [_h4]: ["GET", "/?encryption", 200] }, - () => exports.GetBucketEncryptionRequest$, - () => exports.GetBucketEncryptionOutput$ - ]; - exports.GetBucketIntelligentTieringConfiguration$ = [ - 9, - n05, - _GBITC, - { [_h4]: ["GET", "/?intelligent-tiering&x-id=GetBucketIntelligentTieringConfiguration", 200] }, - () => exports.GetBucketIntelligentTieringConfigurationRequest$, - () => exports.GetBucketIntelligentTieringConfigurationOutput$ - ]; - exports.GetBucketInventoryConfiguration$ = [ - 9, - n05, - _GBIC, - { [_h4]: ["GET", "/?inventory&x-id=GetBucketInventoryConfiguration", 200] }, - () => exports.GetBucketInventoryConfigurationRequest$, - () => exports.GetBucketInventoryConfigurationOutput$ - ]; - exports.GetBucketLifecycleConfiguration$ = [ - 9, - n05, - _GBLC, - { [_h4]: ["GET", "/?lifecycle", 200] }, - () => exports.GetBucketLifecycleConfigurationRequest$, - () => exports.GetBucketLifecycleConfigurationOutput$ - ]; - exports.GetBucketLocation$ = [ - 9, - n05, - _GBL, - { [_h4]: ["GET", "/?location", 200] }, - () => exports.GetBucketLocationRequest$, - () => exports.GetBucketLocationOutput$ - ]; - exports.GetBucketLogging$ = [ - 9, - n05, - _GBLe, - { [_h4]: ["GET", "/?logging", 200] }, - () => exports.GetBucketLoggingRequest$, - () => exports.GetBucketLoggingOutput$ - ]; - exports.GetBucketMetadataConfiguration$ = [ - 9, - n05, - _GBMC, - { [_h4]: ["GET", "/?metadataConfiguration", 200] }, - () => exports.GetBucketMetadataConfigurationRequest$, - () => exports.GetBucketMetadataConfigurationOutput$ - ]; - exports.GetBucketMetadataTableConfiguration$ = [ - 9, - n05, - _GBMTC, - { [_h4]: ["GET", "/?metadataTable", 200] }, - () => exports.GetBucketMetadataTableConfigurationRequest$, - () => exports.GetBucketMetadataTableConfigurationOutput$ - ]; - exports.GetBucketMetricsConfiguration$ = [ - 9, - n05, - _GBMCe, - { [_h4]: ["GET", "/?metrics&x-id=GetBucketMetricsConfiguration", 200] }, - () => exports.GetBucketMetricsConfigurationRequest$, - () => exports.GetBucketMetricsConfigurationOutput$ - ]; - exports.GetBucketNotificationConfiguration$ = [ - 9, - n05, - _GBNC, - { [_h4]: ["GET", "/?notification", 200] }, - () => exports.GetBucketNotificationConfigurationRequest$, - () => exports.NotificationConfiguration$ - ]; - exports.GetBucketOwnershipControls$ = [ - 9, - n05, - _GBOC, - { [_h4]: ["GET", "/?ownershipControls", 200] }, - () => exports.GetBucketOwnershipControlsRequest$, - () => exports.GetBucketOwnershipControlsOutput$ - ]; - exports.GetBucketPolicy$ = [ - 9, - n05, - _GBP, - { [_h4]: ["GET", "/?policy", 200] }, - () => exports.GetBucketPolicyRequest$, - () => exports.GetBucketPolicyOutput$ - ]; - exports.GetBucketPolicyStatus$ = [ - 9, - n05, - _GBPS, - { [_h4]: ["GET", "/?policyStatus", 200] }, - () => exports.GetBucketPolicyStatusRequest$, - () => exports.GetBucketPolicyStatusOutput$ - ]; - exports.GetBucketReplication$ = [ - 9, - n05, - _GBR, - { [_h4]: ["GET", "/?replication", 200] }, - () => exports.GetBucketReplicationRequest$, - () => exports.GetBucketReplicationOutput$ - ]; - exports.GetBucketRequestPayment$ = [ - 9, - n05, - _GBRP, - { [_h4]: ["GET", "/?requestPayment", 200] }, - () => exports.GetBucketRequestPaymentRequest$, - () => exports.GetBucketRequestPaymentOutput$ - ]; - exports.GetBucketTagging$ = [ - 9, - n05, - _GBT, - { [_h4]: ["GET", "/?tagging", 200] }, - () => exports.GetBucketTaggingRequest$, - () => exports.GetBucketTaggingOutput$ - ]; - exports.GetBucketVersioning$ = [ - 9, - n05, - _GBV, - { [_h4]: ["GET", "/?versioning", 200] }, - () => exports.GetBucketVersioningRequest$, - () => exports.GetBucketVersioningOutput$ - ]; - exports.GetBucketWebsite$ = [ - 9, - n05, - _GBW, - { [_h4]: ["GET", "/?website", 200] }, - () => exports.GetBucketWebsiteRequest$, - () => exports.GetBucketWebsiteOutput$ - ]; - exports.GetObject$ = [ - 9, - n05, - _GO, - { [_hC]: "-", [_h4]: ["GET", "/{Key+}?x-id=GetObject", 200] }, - () => exports.GetObjectRequest$, - () => exports.GetObjectOutput$ - ]; - exports.GetObjectAcl$ = [ - 9, - n05, - _GOA, - { [_h4]: ["GET", "/{Key+}?acl", 200] }, - () => exports.GetObjectAclRequest$, - () => exports.GetObjectAclOutput$ - ]; - exports.GetObjectAttributes$ = [ - 9, - n05, - _GOAe, - { [_h4]: ["GET", "/{Key+}?attributes", 200] }, - () => exports.GetObjectAttributesRequest$, - () => exports.GetObjectAttributesOutput$ - ]; - exports.GetObjectLegalHold$ = [ - 9, - n05, - _GOLH, - { [_h4]: ["GET", "/{Key+}?legal-hold", 200] }, - () => exports.GetObjectLegalHoldRequest$, - () => exports.GetObjectLegalHoldOutput$ - ]; - exports.GetObjectLockConfiguration$ = [ - 9, - n05, - _GOLC, - { [_h4]: ["GET", "/?object-lock", 200] }, - () => exports.GetObjectLockConfigurationRequest$, - () => exports.GetObjectLockConfigurationOutput$ - ]; - exports.GetObjectRetention$ = [ - 9, - n05, - _GORe, - { [_h4]: ["GET", "/{Key+}?retention", 200] }, - () => exports.GetObjectRetentionRequest$, - () => exports.GetObjectRetentionOutput$ - ]; - exports.GetObjectTagging$ = [ - 9, - n05, - _GOT, - { [_h4]: ["GET", "/{Key+}?tagging", 200] }, - () => exports.GetObjectTaggingRequest$, - () => exports.GetObjectTaggingOutput$ - ]; - exports.GetObjectTorrent$ = [ - 9, - n05, - _GOTe, - { [_h4]: ["GET", "/{Key+}?torrent", 200] }, - () => exports.GetObjectTorrentRequest$, - () => exports.GetObjectTorrentOutput$ - ]; - exports.GetPublicAccessBlock$ = [ - 9, - n05, - _GPAB, - { [_h4]: ["GET", "/?publicAccessBlock", 200] }, - () => exports.GetPublicAccessBlockRequest$, - () => exports.GetPublicAccessBlockOutput$ - ]; - exports.HeadBucket$ = [ - 9, - n05, - _HB, - { [_h4]: ["HEAD", "/", 200] }, - () => exports.HeadBucketRequest$, - () => exports.HeadBucketOutput$ - ]; - exports.HeadObject$ = [ - 9, - n05, - _HO, - { [_h4]: ["HEAD", "/{Key+}", 200] }, - () => exports.HeadObjectRequest$, - () => exports.HeadObjectOutput$ - ]; - exports.ListBucketAnalyticsConfigurations$ = [ - 9, - n05, - _LBAC, - { [_h4]: ["GET", "/?analytics&x-id=ListBucketAnalyticsConfigurations", 200] }, - () => exports.ListBucketAnalyticsConfigurationsRequest$, - () => exports.ListBucketAnalyticsConfigurationsOutput$ - ]; - exports.ListBucketIntelligentTieringConfigurations$ = [ - 9, - n05, - _LBITC, - { [_h4]: ["GET", "/?intelligent-tiering&x-id=ListBucketIntelligentTieringConfigurations", 200] }, - () => exports.ListBucketIntelligentTieringConfigurationsRequest$, - () => exports.ListBucketIntelligentTieringConfigurationsOutput$ - ]; - exports.ListBucketInventoryConfigurations$ = [ - 9, - n05, - _LBIC, - { [_h4]: ["GET", "/?inventory&x-id=ListBucketInventoryConfigurations", 200] }, - () => exports.ListBucketInventoryConfigurationsRequest$, - () => exports.ListBucketInventoryConfigurationsOutput$ - ]; - exports.ListBucketMetricsConfigurations$ = [ - 9, - n05, - _LBMC, - { [_h4]: ["GET", "/?metrics&x-id=ListBucketMetricsConfigurations", 200] }, - () => exports.ListBucketMetricsConfigurationsRequest$, - () => exports.ListBucketMetricsConfigurationsOutput$ - ]; - exports.ListBuckets$ = [ - 9, - n05, - _LB, - { [_h4]: ["GET", "/?x-id=ListBuckets", 200] }, - () => exports.ListBucketsRequest$, - () => exports.ListBucketsOutput$ - ]; - exports.ListDirectoryBuckets$ = [ - 9, - n05, - _LDB, - { [_h4]: ["GET", "/?x-id=ListDirectoryBuckets", 200] }, - () => exports.ListDirectoryBucketsRequest$, - () => exports.ListDirectoryBucketsOutput$ - ]; - exports.ListMultipartUploads$ = [ - 9, - n05, - _LMU, - { [_h4]: ["GET", "/?uploads", 200] }, - () => exports.ListMultipartUploadsRequest$, - () => exports.ListMultipartUploadsOutput$ - ]; - exports.ListObjects$ = [ - 9, - n05, - _LO, - { [_h4]: ["GET", "/", 200] }, - () => exports.ListObjectsRequest$, - () => exports.ListObjectsOutput$ - ]; - exports.ListObjectsV2$ = [ - 9, - n05, - _LOV, - { [_h4]: ["GET", "/?list-type=2", 200] }, - () => exports.ListObjectsV2Request$, - () => exports.ListObjectsV2Output$ - ]; - exports.ListObjectVersions$ = [ - 9, - n05, - _LOVi, - { [_h4]: ["GET", "/?versions", 200] }, - () => exports.ListObjectVersionsRequest$, - () => exports.ListObjectVersionsOutput$ - ]; - exports.ListParts$ = [ - 9, - n05, - _LP, - { [_h4]: ["GET", "/{Key+}?x-id=ListParts", 200] }, - () => exports.ListPartsRequest$, - () => exports.ListPartsOutput$ - ]; - exports.PutBucketAbac$ = [ - 9, - n05, - _PBA, - { [_hC]: "-", [_h4]: ["PUT", "/?abac", 200] }, - () => exports.PutBucketAbacRequest$, - () => __Unit - ]; - exports.PutBucketAccelerateConfiguration$ = [ - 9, - n05, - _PBAC, - { [_hC]: "-", [_h4]: ["PUT", "/?accelerate", 200] }, - () => exports.PutBucketAccelerateConfigurationRequest$, - () => __Unit - ]; - exports.PutBucketAcl$ = [ - 9, - n05, - _PBAu, - { [_hC]: "-", [_h4]: ["PUT", "/?acl", 200] }, - () => exports.PutBucketAclRequest$, - () => __Unit - ]; - exports.PutBucketAnalyticsConfiguration$ = [ - 9, - n05, - _PBACu, - { [_h4]: ["PUT", "/?analytics", 200] }, - () => exports.PutBucketAnalyticsConfigurationRequest$, - () => __Unit - ]; - exports.PutBucketCors$ = [ - 9, - n05, - _PBC, - { [_hC]: "-", [_h4]: ["PUT", "/?cors", 200] }, - () => exports.PutBucketCorsRequest$, - () => __Unit - ]; - exports.PutBucketEncryption$ = [ - 9, - n05, - _PBE, - { [_hC]: "-", [_h4]: ["PUT", "/?encryption", 200] }, - () => exports.PutBucketEncryptionRequest$, - () => __Unit - ]; - exports.PutBucketIntelligentTieringConfiguration$ = [ - 9, - n05, - _PBITC, - { [_h4]: ["PUT", "/?intelligent-tiering", 200] }, - () => exports.PutBucketIntelligentTieringConfigurationRequest$, - () => __Unit - ]; - exports.PutBucketInventoryConfiguration$ = [ - 9, - n05, - _PBIC, - { [_h4]: ["PUT", "/?inventory", 200] }, - () => exports.PutBucketInventoryConfigurationRequest$, - () => __Unit - ]; - exports.PutBucketLifecycleConfiguration$ = [ - 9, - n05, - _PBLC, - { [_hC]: "-", [_h4]: ["PUT", "/?lifecycle", 200] }, - () => exports.PutBucketLifecycleConfigurationRequest$, - () => exports.PutBucketLifecycleConfigurationOutput$ - ]; - exports.PutBucketLogging$ = [ - 9, - n05, - _PBL, - { [_hC]: "-", [_h4]: ["PUT", "/?logging", 200] }, - () => exports.PutBucketLoggingRequest$, - () => __Unit - ]; - exports.PutBucketMetricsConfiguration$ = [ - 9, - n05, - _PBMC, - { [_h4]: ["PUT", "/?metrics", 200] }, - () => exports.PutBucketMetricsConfigurationRequest$, - () => __Unit - ]; - exports.PutBucketNotificationConfiguration$ = [ - 9, - n05, - _PBNC, - { [_h4]: ["PUT", "/?notification", 200] }, - () => exports.PutBucketNotificationConfigurationRequest$, - () => __Unit - ]; - exports.PutBucketOwnershipControls$ = [ - 9, - n05, - _PBOC, - { [_hC]: "-", [_h4]: ["PUT", "/?ownershipControls", 200] }, - () => exports.PutBucketOwnershipControlsRequest$, - () => __Unit - ]; - exports.PutBucketPolicy$ = [ - 9, - n05, - _PBP, - { [_hC]: "-", [_h4]: ["PUT", "/?policy", 200] }, - () => exports.PutBucketPolicyRequest$, - () => __Unit - ]; - exports.PutBucketReplication$ = [ - 9, - n05, - _PBR, - { [_hC]: "-", [_h4]: ["PUT", "/?replication", 200] }, - () => exports.PutBucketReplicationRequest$, - () => __Unit - ]; - exports.PutBucketRequestPayment$ = [ - 9, - n05, - _PBRP, - { [_hC]: "-", [_h4]: ["PUT", "/?requestPayment", 200] }, - () => exports.PutBucketRequestPaymentRequest$, - () => __Unit - ]; - exports.PutBucketTagging$ = [ - 9, - n05, - _PBT, - { [_hC]: "-", [_h4]: ["PUT", "/?tagging", 200] }, - () => exports.PutBucketTaggingRequest$, - () => __Unit - ]; - exports.PutBucketVersioning$ = [ - 9, - n05, - _PBV, - { [_hC]: "-", [_h4]: ["PUT", "/?versioning", 200] }, - () => exports.PutBucketVersioningRequest$, - () => __Unit - ]; - exports.PutBucketWebsite$ = [ - 9, - n05, - _PBW, - { [_hC]: "-", [_h4]: ["PUT", "/?website", 200] }, - () => exports.PutBucketWebsiteRequest$, - () => __Unit - ]; - exports.PutObject$ = [ - 9, - n05, - _PO, - { [_hC]: "-", [_h4]: ["PUT", "/{Key+}?x-id=PutObject", 200] }, - () => exports.PutObjectRequest$, - () => exports.PutObjectOutput$ - ]; - exports.PutObjectAcl$ = [ - 9, - n05, - _POA, - { [_hC]: "-", [_h4]: ["PUT", "/{Key+}?acl", 200] }, - () => exports.PutObjectAclRequest$, - () => exports.PutObjectAclOutput$ - ]; - exports.PutObjectLegalHold$ = [ - 9, - n05, - _POLH, - { [_hC]: "-", [_h4]: ["PUT", "/{Key+}?legal-hold", 200] }, - () => exports.PutObjectLegalHoldRequest$, - () => exports.PutObjectLegalHoldOutput$ - ]; - exports.PutObjectLockConfiguration$ = [ - 9, - n05, - _POLC, - { [_hC]: "-", [_h4]: ["PUT", "/?object-lock", 200] }, - () => exports.PutObjectLockConfigurationRequest$, - () => exports.PutObjectLockConfigurationOutput$ - ]; - exports.PutObjectRetention$ = [ - 9, - n05, - _PORu, - { [_hC]: "-", [_h4]: ["PUT", "/{Key+}?retention", 200] }, - () => exports.PutObjectRetentionRequest$, - () => exports.PutObjectRetentionOutput$ - ]; - exports.PutObjectTagging$ = [ - 9, - n05, - _POT, - { [_hC]: "-", [_h4]: ["PUT", "/{Key+}?tagging", 200] }, - () => exports.PutObjectTaggingRequest$, - () => exports.PutObjectTaggingOutput$ - ]; - exports.PutPublicAccessBlock$ = [ - 9, - n05, - _PPAB, - { [_hC]: "-", [_h4]: ["PUT", "/?publicAccessBlock", 200] }, - () => exports.PutPublicAccessBlockRequest$, - () => __Unit - ]; - exports.RenameObject$ = [ - 9, - n05, - _RO, - { [_h4]: ["PUT", "/{Key+}?renameObject", 200] }, - () => exports.RenameObjectRequest$, - () => exports.RenameObjectOutput$ - ]; - exports.RestoreObject$ = [ - 9, - n05, - _ROe, - { [_hC]: "-", [_h4]: ["POST", "/{Key+}?restore", 200] }, - () => exports.RestoreObjectRequest$, - () => exports.RestoreObjectOutput$ - ]; - exports.SelectObjectContent$ = [ - 9, - n05, - _SOC, - { [_h4]: ["POST", "/{Key+}?select&select-type=2", 200] }, - () => exports.SelectObjectContentRequest$, - () => exports.SelectObjectContentOutput$ - ]; - exports.UpdateBucketMetadataInventoryTableConfiguration$ = [ - 9, - n05, - _UBMITC, - { [_hC]: "-", [_h4]: ["PUT", "/?metadataInventoryTable", 200] }, - () => exports.UpdateBucketMetadataInventoryTableConfigurationRequest$, - () => __Unit - ]; - exports.UpdateBucketMetadataJournalTableConfiguration$ = [ - 9, - n05, - _UBMJTC, - { [_hC]: "-", [_h4]: ["PUT", "/?metadataJournalTable", 200] }, - () => exports.UpdateBucketMetadataJournalTableConfigurationRequest$, - () => __Unit - ]; - exports.UpdateObjectEncryption$ = [ - 9, - n05, - _UOE, - { [_hC]: "-", [_h4]: ["PUT", "/{Key+}?encryption", 200] }, - () => exports.UpdateObjectEncryptionRequest$, - () => exports.UpdateObjectEncryptionResponse$ - ]; - exports.UploadPart$ = [ - 9, - n05, - _UP, - { [_hC]: "-", [_h4]: ["PUT", "/{Key+}?x-id=UploadPart", 200] }, - () => exports.UploadPartRequest$, - () => exports.UploadPartOutput$ - ]; - exports.UploadPartCopy$ = [ - 9, - n05, - _UPC, - { [_h4]: ["PUT", "/{Key+}?x-id=UploadPartCopy", 200] }, - () => exports.UploadPartCopyRequest$, - () => exports.UploadPartCopyOutput$ - ]; - exports.WriteGetObjectResponse$ = [ - 9, - n05, - _WGOR, - { [_en]: ["{RequestRoute}."], [_h4]: ["POST", "/WriteGetObjectResponse", 200] }, - () => exports.WriteGetObjectResponseRequest$, - () => __Unit - ]; - } -}); - -// node_modules/.pnpm/@aws-sdk+client-s3@3.1030.0/node_modules/@aws-sdk/client-s3/package.json -var require_package2 = __commonJS({ - "node_modules/.pnpm/@aws-sdk+client-s3@3.1030.0/node_modules/@aws-sdk/client-s3/package.json"(exports, module) { - module.exports = { - name: "@aws-sdk/client-s3", - description: "AWS SDK for JavaScript S3 Client for Node.js, Browser and React Native", - version: "3.1030.0", - scripts: { - build: "concurrently 'yarn:build:types' 'yarn:build:es' && yarn build:cjs", - "build:cjs": "node ../../scripts/compilation/inline client-s3", - "build:es": "tsc -p tsconfig.es.json", - "build:include:deps": 'yarn g:turbo run build -F="$npm_package_name"', - "build:types": "tsc -p tsconfig.types.json", - "build:types:downlevel": "downlevel-dts dist-types dist-types/ts3.4", - clean: "premove dist-cjs dist-es dist-types tsconfig.cjs.tsbuildinfo tsconfig.es.tsbuildinfo tsconfig.types.tsbuildinfo", - "extract:docs": "api-extractor run --local", - "generate:client": "node ../../scripts/generate-clients/single-service --solo s3", - test: "yarn g:vitest run", - "test:browser": "node ./test/browser-build/esbuild && yarn g:vitest run -c vitest.config.browser.mts", - "test:browser:watch": "node ./test/browser-build/esbuild && yarn g:vitest watch -c vitest.config.browser.mts", - "test:e2e": "yarn g:vitest run -c vitest.config.e2e.mts && yarn test:browser", - "test:e2e:watch": "yarn g:vitest watch -c vitest.config.e2e.mts", - "test:index": "tsc --noEmit ./test/index-types.ts && node ./test/index-objects.spec.mjs", - "test:integration": "yarn g:vitest run -c vitest.config.integ.mts", - "test:integration:watch": "yarn g:vitest watch -c vitest.config.integ.mts", - "test:watch": "yarn g:vitest watch" - }, - main: "./dist-cjs/index.js", - types: "./dist-types/index.d.ts", - module: "./dist-es/index.js", - sideEffects: false, - dependencies: { - "@aws-crypto/sha1-browser": "5.2.0", - "@aws-crypto/sha256-browser": "5.2.0", - "@aws-crypto/sha256-js": "5.2.0", - "@aws-sdk/core": "^3.973.27", - "@aws-sdk/credential-provider-node": "^3.972.30", - "@aws-sdk/middleware-bucket-endpoint": "^3.972.9", - "@aws-sdk/middleware-expect-continue": "^3.972.9", - "@aws-sdk/middleware-flexible-checksums": "^3.974.7", - "@aws-sdk/middleware-host-header": "^3.972.9", - "@aws-sdk/middleware-location-constraint": "^3.972.9", - "@aws-sdk/middleware-logger": "^3.972.9", - "@aws-sdk/middleware-recursion-detection": "^3.972.10", - "@aws-sdk/middleware-sdk-s3": "^3.972.28", - "@aws-sdk/middleware-ssec": "^3.972.9", - "@aws-sdk/middleware-user-agent": "^3.972.29", - "@aws-sdk/region-config-resolver": "^3.972.11", - "@aws-sdk/signature-v4-multi-region": "^3.996.16", - "@aws-sdk/types": "^3.973.7", - "@aws-sdk/util-endpoints": "^3.996.6", - "@aws-sdk/util-user-agent-browser": "^3.972.9", - "@aws-sdk/util-user-agent-node": "^3.973.15", - "@smithy/config-resolver": "^4.4.14", - "@smithy/core": "^3.23.14", - "@smithy/eventstream-serde-browser": "^4.2.13", - "@smithy/eventstream-serde-config-resolver": "^4.3.13", - "@smithy/eventstream-serde-node": "^4.2.13", - "@smithy/fetch-http-handler": "^5.3.16", - "@smithy/hash-blob-browser": "^4.2.14", - "@smithy/hash-node": "^4.2.13", - "@smithy/hash-stream-node": "^4.2.13", - "@smithy/invalid-dependency": "^4.2.13", - "@smithy/md5-js": "^4.2.13", - "@smithy/middleware-content-length": "^4.2.13", - "@smithy/middleware-endpoint": "^4.4.29", - "@smithy/middleware-retry": "^4.5.0", - "@smithy/middleware-serde": "^4.2.17", - "@smithy/middleware-stack": "^4.2.13", - "@smithy/node-config-provider": "^4.3.13", - "@smithy/node-http-handler": "^4.5.2", - "@smithy/protocol-http": "^5.3.13", - "@smithy/smithy-client": "^4.12.9", - "@smithy/types": "^4.14.0", - "@smithy/url-parser": "^4.2.13", - "@smithy/util-base64": "^4.3.2", - "@smithy/util-body-length-browser": "^4.2.2", - "@smithy/util-body-length-node": "^4.2.3", - "@smithy/util-defaults-mode-browser": "^4.3.45", - "@smithy/util-defaults-mode-node": "^4.2.49", - "@smithy/util-endpoints": "^3.3.4", - "@smithy/util-middleware": "^4.2.13", - "@smithy/util-retry": "^4.3.0", - "@smithy/util-stream": "^4.5.22", - "@smithy/util-utf8": "^4.2.2", - "@smithy/util-waiter": "^4.2.15", - tslib: "^2.6.2" - }, - devDependencies: { - "@aws-sdk/signature-v4-crt": "3.1030.0", - "@smithy/snapshot-testing": "^2.0.5", - "@tsconfig/node20": "20.1.8", - "@types/node": "^20.14.8", - concurrently: "7.0.0", - "downlevel-dts": "0.10.1", - premove: "4.0.0", - typescript: "~5.8.3", - vitest: "^4.0.17" - }, - engines: { - node: ">=20.0.0" - }, - typesVersions: { - "<4.5": { - "dist-types/*": [ - "dist-types/ts3.4/*" - ] - } - }, - files: [ - "dist-*/**" - ], - author: { - name: "AWS SDK for JavaScript Team", - url: "https://aws.amazon.com/javascript/" - }, - license: "Apache-2.0", - browser: { - "./dist-es/runtimeConfig": "./dist-es/runtimeConfig.browser" - }, - "react-native": { - "./dist-es/runtimeConfig": "./dist-es/runtimeConfig.native" - }, - homepage: "https://github.com/aws/aws-sdk-js-v3/tree/main/clients/client-s3", - repository: { - type: "git", - url: "https://github.com/aws/aws-sdk-js-v3.git", - directory: "clients/client-s3" - } - }; - } -}); - -// node_modules/.pnpm/@aws-sdk+credential-provider-env@3.972.25/node_modules/@aws-sdk/credential-provider-env/dist-cjs/index.js -var require_dist_cjs48 = __commonJS({ - "node_modules/.pnpm/@aws-sdk+credential-provider-env@3.972.25/node_modules/@aws-sdk/credential-provider-env/dist-cjs/index.js"(exports) { - "use strict"; - var client2 = (init_client2(), __toCommonJS(client_exports)); - var propertyProvider = require_dist_cjs41(); - var ENV_KEY = "AWS_ACCESS_KEY_ID"; - var ENV_SECRET = "AWS_SECRET_ACCESS_KEY"; - var ENV_SESSION = "AWS_SESSION_TOKEN"; - var ENV_EXPIRATION = "AWS_CREDENTIAL_EXPIRATION"; - var ENV_CREDENTIAL_SCOPE = "AWS_CREDENTIAL_SCOPE"; - var ENV_ACCOUNT_ID = "AWS_ACCOUNT_ID"; - var fromEnv = (init2) => async () => { - init2?.logger?.debug("@aws-sdk/credential-provider-env - fromEnv"); - const accessKeyId = process.env[ENV_KEY]; - const secretAccessKey = process.env[ENV_SECRET]; - const sessionToken = process.env[ENV_SESSION]; - const expiry = process.env[ENV_EXPIRATION]; - const credentialScope = process.env[ENV_CREDENTIAL_SCOPE]; - const accountId = process.env[ENV_ACCOUNT_ID]; - if (accessKeyId && secretAccessKey) { - const credentials = { - accessKeyId, - secretAccessKey, - ...sessionToken && { sessionToken }, - ...expiry && { expiration: new Date(expiry) }, - ...credentialScope && { credentialScope }, - ...accountId && { accountId } - }; - client2.setCredentialFeature(credentials, "CREDENTIALS_ENV_VARS", "g"); - return credentials; - } - throw new propertyProvider.CredentialsProviderError("Unable to find environment variable credentials.", { logger: init2?.logger }); - }; - exports.ENV_ACCOUNT_ID = ENV_ACCOUNT_ID; - exports.ENV_CREDENTIAL_SCOPE = ENV_CREDENTIAL_SCOPE; - exports.ENV_EXPIRATION = ENV_EXPIRATION; - exports.ENV_KEY = ENV_KEY; - exports.ENV_SECRET = ENV_SECRET; - exports.ENV_SESSION = ENV_SESSION; - exports.fromEnv = fromEnv; - } -}); - -// node_modules/.pnpm/@smithy+credential-provider-imds@4.2.13/node_modules/@smithy/credential-provider-imds/dist-cjs/index.js -var require_dist_cjs49 = __commonJS({ - "node_modules/.pnpm/@smithy+credential-provider-imds@4.2.13/node_modules/@smithy/credential-provider-imds/dist-cjs/index.js"(exports) { - "use strict"; - var propertyProvider = require_dist_cjs41(); - var url2 = __require("url"); - var buffer2 = __require("buffer"); - var http = __require("http"); - var nodeConfigProvider = require_dist_cjs43(); - var urlParser = require_dist_cjs25(); - function httpRequest2(options) { - return new Promise((resolve4, reject) => { - const req = http.request({ - method: "GET", - ...options, - hostname: options.hostname?.replace(/^\[(.+)\]$/, "$1") - }); - req.on("error", (err) => { - reject(Object.assign(new propertyProvider.ProviderError("Unable to connect to instance metadata service"), err)); - req.destroy(); - }); - req.on("timeout", () => { - reject(new propertyProvider.ProviderError("TimeoutError from instance metadata service")); - req.destroy(); - }); - req.on("response", (res) => { - const { statusCode = 400 } = res; - if (statusCode < 200 || 300 <= statusCode) { - reject(Object.assign(new propertyProvider.ProviderError("Error response received from instance metadata service"), { statusCode })); - req.destroy(); - } - const chunks = []; - res.on("data", (chunk) => { - chunks.push(chunk); - }); - res.on("end", () => { - resolve4(buffer2.Buffer.concat(chunks)); - req.destroy(); - }); - }); - req.end(); - }); - } - var isImdsCredentials = (arg) => Boolean(arg) && typeof arg === "object" && typeof arg.AccessKeyId === "string" && typeof arg.SecretAccessKey === "string" && typeof arg.Token === "string" && typeof arg.Expiration === "string"; - var fromImdsCredentials = (creds) => ({ - accessKeyId: creds.AccessKeyId, - secretAccessKey: creds.SecretAccessKey, - sessionToken: creds.Token, - expiration: new Date(creds.Expiration), - ...creds.AccountId && { accountId: creds.AccountId } - }); - var DEFAULT_TIMEOUT = 1e3; - var DEFAULT_MAX_RETRIES = 0; - var providerConfigFromInit = ({ maxRetries = DEFAULT_MAX_RETRIES, timeout = DEFAULT_TIMEOUT }) => ({ maxRetries, timeout }); - var retry = (toRetry, maxRetries) => { - let promise2 = toRetry(); - for (let i5 = 0; i5 < maxRetries; i5++) { - promise2 = promise2.catch(toRetry); - } - return promise2; - }; - var ENV_CMDS_FULL_URI = "AWS_CONTAINER_CREDENTIALS_FULL_URI"; - var ENV_CMDS_RELATIVE_URI = "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI"; - var ENV_CMDS_AUTH_TOKEN = "AWS_CONTAINER_AUTHORIZATION_TOKEN"; - var fromContainerMetadata = (init2 = {}) => { - const { timeout, maxRetries } = providerConfigFromInit(init2); - return () => retry(async () => { - const requestOptions = await getCmdsUri({ logger: init2.logger }); - const credsResponse = JSON.parse(await requestFromEcsImds(timeout, requestOptions)); - if (!isImdsCredentials(credsResponse)) { - throw new propertyProvider.CredentialsProviderError("Invalid response received from instance metadata service.", { - logger: init2.logger - }); - } - return fromImdsCredentials(credsResponse); - }, maxRetries); - }; - var requestFromEcsImds = async (timeout, options) => { - if (process.env[ENV_CMDS_AUTH_TOKEN]) { - options.headers = { - ...options.headers, - Authorization: process.env[ENV_CMDS_AUTH_TOKEN] - }; - } - const buffer3 = await httpRequest2({ - ...options, - timeout - }); - return buffer3.toString(); - }; - var CMDS_IP = "169.254.170.2"; - var GREENGRASS_HOSTS = { - localhost: true, - "127.0.0.1": true - }; - var GREENGRASS_PROTOCOLS = { - "http:": true, - "https:": true - }; - var getCmdsUri = async ({ logger: logger4 }) => { - if (process.env[ENV_CMDS_RELATIVE_URI]) { - return { - hostname: CMDS_IP, - path: process.env[ENV_CMDS_RELATIVE_URI] - }; - } - if (process.env[ENV_CMDS_FULL_URI]) { - const parsed = url2.parse(process.env[ENV_CMDS_FULL_URI]); - if (!parsed.hostname || !(parsed.hostname in GREENGRASS_HOSTS)) { - throw new propertyProvider.CredentialsProviderError(`${parsed.hostname} is not a valid container metadata service hostname`, { - tryNextLink: false, - logger: logger4 - }); - } - if (!parsed.protocol || !(parsed.protocol in GREENGRASS_PROTOCOLS)) { - throw new propertyProvider.CredentialsProviderError(`${parsed.protocol} is not a valid container metadata service protocol`, { - tryNextLink: false, - logger: logger4 - }); - } - return { - ...parsed, - port: parsed.port ? parseInt(parsed.port, 10) : void 0 - }; - } - throw new propertyProvider.CredentialsProviderError(`The container metadata credential provider cannot be used unless the ${ENV_CMDS_RELATIVE_URI} or ${ENV_CMDS_FULL_URI} environment variable is set`, { - tryNextLink: false, - logger: logger4 - }); - }; - var InstanceMetadataV1FallbackError = class _InstanceMetadataV1FallbackError extends propertyProvider.CredentialsProviderError { - tryNextLink; - name = "InstanceMetadataV1FallbackError"; - constructor(message2, tryNextLink = true) { - super(message2, tryNextLink); - this.tryNextLink = tryNextLink; - Object.setPrototypeOf(this, _InstanceMetadataV1FallbackError.prototype); - } - }; - exports.Endpoint = void 0; - (function(Endpoint) { - Endpoint["IPv4"] = "http://169.254.169.254"; - Endpoint["IPv6"] = "http://[fd00:ec2::254]"; - })(exports.Endpoint || (exports.Endpoint = {})); - var ENV_ENDPOINT_NAME = "AWS_EC2_METADATA_SERVICE_ENDPOINT"; - var CONFIG_ENDPOINT_NAME = "ec2_metadata_service_endpoint"; - var ENDPOINT_CONFIG_OPTIONS = { - environmentVariableSelector: (env2) => env2[ENV_ENDPOINT_NAME], - configFileSelector: (profile) => profile[CONFIG_ENDPOINT_NAME], - default: void 0 - }; - var EndpointMode; - (function(EndpointMode2) { - EndpointMode2["IPv4"] = "IPv4"; - EndpointMode2["IPv6"] = "IPv6"; - })(EndpointMode || (EndpointMode = {})); - var ENV_ENDPOINT_MODE_NAME = "AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE"; - var CONFIG_ENDPOINT_MODE_NAME = "ec2_metadata_service_endpoint_mode"; - var ENDPOINT_MODE_CONFIG_OPTIONS = { - environmentVariableSelector: (env2) => env2[ENV_ENDPOINT_MODE_NAME], - configFileSelector: (profile) => profile[CONFIG_ENDPOINT_MODE_NAME], - default: EndpointMode.IPv4 - }; - var getInstanceMetadataEndpoint = async () => urlParser.parseUrl(await getFromEndpointConfig() || await getFromEndpointModeConfig()); - var getFromEndpointConfig = async () => nodeConfigProvider.loadConfig(ENDPOINT_CONFIG_OPTIONS)(); - var getFromEndpointModeConfig = async () => { - const endpointMode = await nodeConfigProvider.loadConfig(ENDPOINT_MODE_CONFIG_OPTIONS)(); - switch (endpointMode) { - case EndpointMode.IPv4: - return exports.Endpoint.IPv4; - case EndpointMode.IPv6: - return exports.Endpoint.IPv6; - default: - throw new Error(`Unsupported endpoint mode: ${endpointMode}. Select from ${Object.values(EndpointMode)}`); - } - }; - var STATIC_STABILITY_REFRESH_INTERVAL_SECONDS = 5 * 60; - var STATIC_STABILITY_REFRESH_INTERVAL_JITTER_WINDOW_SECONDS = 5 * 60; - var STATIC_STABILITY_DOC_URL = "https://docs.aws.amazon.com/sdkref/latest/guide/feature-static-credentials.html"; - var getExtendedInstanceMetadataCredentials = (credentials, logger4) => { - const refreshInterval = STATIC_STABILITY_REFRESH_INTERVAL_SECONDS + Math.floor(Math.random() * STATIC_STABILITY_REFRESH_INTERVAL_JITTER_WINDOW_SECONDS); - const newExpiration = new Date(Date.now() + refreshInterval * 1e3); - logger4.warn(`Attempting credential expiration extension due to a credential service availability issue. A refresh of these credentials will be attempted after ${new Date(newExpiration)}. -For more information, please visit: ` + STATIC_STABILITY_DOC_URL); - const originalExpiration = credentials.originalExpiration ?? credentials.expiration; - return { - ...credentials, - ...originalExpiration ? { originalExpiration } : {}, - expiration: newExpiration - }; - }; - var staticStabilityProvider = (provider, options = {}) => { - const logger4 = options?.logger || console; - let pastCredentials; - return async () => { - let credentials; - try { - credentials = await provider(); - if (credentials.expiration && credentials.expiration.getTime() < Date.now()) { - credentials = getExtendedInstanceMetadataCredentials(credentials, logger4); - } - } catch (e5) { - if (pastCredentials) { - logger4.warn("Credential renew failed: ", e5); - credentials = getExtendedInstanceMetadataCredentials(pastCredentials, logger4); - } else { - throw e5; - } - } - pastCredentials = credentials; - return credentials; - }; - }; - var IMDS_PATH = "/latest/meta-data/iam/security-credentials/"; - var IMDS_TOKEN_PATH = "/latest/api/token"; - var AWS_EC2_METADATA_V1_DISABLED = "AWS_EC2_METADATA_V1_DISABLED"; - var PROFILE_AWS_EC2_METADATA_V1_DISABLED = "ec2_metadata_v1_disabled"; - var X_AWS_EC2_METADATA_TOKEN = "x-aws-ec2-metadata-token"; - var fromInstanceMetadata = (init2 = {}) => staticStabilityProvider(getInstanceMetadataProvider(init2), { logger: init2.logger }); - var getInstanceMetadataProvider = (init2 = {}) => { - let disableFetchToken = false; - const { logger: logger4, profile } = init2; - const { timeout, maxRetries } = providerConfigFromInit(init2); - const getCredentials = async (maxRetries2, options) => { - const isImdsV1Fallback = disableFetchToken || options.headers?.[X_AWS_EC2_METADATA_TOKEN] == null; - if (isImdsV1Fallback) { - let fallbackBlockedFromProfile = false; - let fallbackBlockedFromProcessEnv = false; - const configValue = await nodeConfigProvider.loadConfig({ - environmentVariableSelector: (env2) => { - const envValue = env2[AWS_EC2_METADATA_V1_DISABLED]; - fallbackBlockedFromProcessEnv = !!envValue && envValue !== "false"; - if (envValue === void 0) { - throw new propertyProvider.CredentialsProviderError(`${AWS_EC2_METADATA_V1_DISABLED} not set in env, checking config file next.`, { logger: init2.logger }); - } - return fallbackBlockedFromProcessEnv; - }, - configFileSelector: (profile2) => { - const profileValue = profile2[PROFILE_AWS_EC2_METADATA_V1_DISABLED]; - fallbackBlockedFromProfile = !!profileValue && profileValue !== "false"; - return fallbackBlockedFromProfile; - }, - default: false - }, { - profile - })(); - if (init2.ec2MetadataV1Disabled || configValue) { - const causes = []; - if (init2.ec2MetadataV1Disabled) - causes.push("credential provider initialization (runtime option ec2MetadataV1Disabled)"); - if (fallbackBlockedFromProfile) - causes.push(`config file profile (${PROFILE_AWS_EC2_METADATA_V1_DISABLED})`); - if (fallbackBlockedFromProcessEnv) - causes.push(`process environment variable (${AWS_EC2_METADATA_V1_DISABLED})`); - throw new InstanceMetadataV1FallbackError(`AWS EC2 Metadata v1 fallback has been blocked by AWS SDK configuration in the following: [${causes.join(", ")}].`); - } - } - const imdsProfile = (await retry(async () => { - let profile2; - try { - profile2 = await getProfile(options); - } catch (err) { - if (err.statusCode === 401) { - disableFetchToken = false; - } - throw err; - } - return profile2; - }, maxRetries2)).trim(); - return retry(async () => { - let creds; - try { - creds = await getCredentialsFromProfile(imdsProfile, options, init2); - } catch (err) { - if (err.statusCode === 401) { - disableFetchToken = false; - } - throw err; - } - return creds; - }, maxRetries2); - }; - return async () => { - const endpoint = await getInstanceMetadataEndpoint(); - if (disableFetchToken) { - logger4?.debug("AWS SDK Instance Metadata", "using v1 fallback (no token fetch)"); - return getCredentials(maxRetries, { ...endpoint, timeout }); - } else { - let token; - try { - token = (await getMetadataToken({ ...endpoint, timeout })).toString(); - } catch (error50) { - if (error50?.statusCode === 400) { - throw Object.assign(error50, { - message: "EC2 Metadata token request returned error" - }); - } else if (error50.message === "TimeoutError" || [403, 404, 405].includes(error50.statusCode)) { - disableFetchToken = true; - } - logger4?.debug("AWS SDK Instance Metadata", "using v1 fallback (initial)"); - return getCredentials(maxRetries, { ...endpoint, timeout }); - } - return getCredentials(maxRetries, { - ...endpoint, - headers: { - [X_AWS_EC2_METADATA_TOKEN]: token - }, - timeout - }); - } - }; - }; - var getMetadataToken = async (options) => httpRequest2({ - ...options, - path: IMDS_TOKEN_PATH, - method: "PUT", - headers: { - "x-aws-ec2-metadata-token-ttl-seconds": "21600" - } - }); - var getProfile = async (options) => (await httpRequest2({ ...options, path: IMDS_PATH })).toString(); - var getCredentialsFromProfile = async (profile, options, init2) => { - const credentialsResponse = JSON.parse((await httpRequest2({ - ...options, - path: IMDS_PATH + profile - })).toString()); - if (!isImdsCredentials(credentialsResponse)) { - throw new propertyProvider.CredentialsProviderError("Invalid response received from instance metadata service.", { - logger: init2.logger - }); - } - return fromImdsCredentials(credentialsResponse); - }; - exports.DEFAULT_MAX_RETRIES = DEFAULT_MAX_RETRIES; - exports.DEFAULT_TIMEOUT = DEFAULT_TIMEOUT; - exports.ENV_CMDS_AUTH_TOKEN = ENV_CMDS_AUTH_TOKEN; - exports.ENV_CMDS_FULL_URI = ENV_CMDS_FULL_URI; - exports.ENV_CMDS_RELATIVE_URI = ENV_CMDS_RELATIVE_URI; - exports.fromContainerMetadata = fromContainerMetadata; - exports.fromInstanceMetadata = fromInstanceMetadata; - exports.getInstanceMetadataEndpoint = getInstanceMetadataEndpoint; - exports.httpRequest = httpRequest2; - exports.providerConfigFromInit = providerConfigFromInit; - } -}); - -// node_modules/.pnpm/@aws-sdk+credential-provider-http@3.972.27/node_modules/@aws-sdk/credential-provider-http/dist-cjs/fromHttp/checkUrl.js -var require_checkUrl = __commonJS({ - "node_modules/.pnpm/@aws-sdk+credential-provider-http@3.972.27/node_modules/@aws-sdk/credential-provider-http/dist-cjs/fromHttp/checkUrl.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.checkUrl = void 0; - var property_provider_1 = require_dist_cjs41(); - var ECS_CONTAINER_HOST = "169.254.170.2"; - var EKS_CONTAINER_HOST_IPv4 = "169.254.170.23"; - var EKS_CONTAINER_HOST_IPv6 = "[fd00:ec2::23]"; - var checkUrl = (url2, logger4) => { - if (url2.protocol === "https:") { - return; - } - if (url2.hostname === ECS_CONTAINER_HOST || url2.hostname === EKS_CONTAINER_HOST_IPv4 || url2.hostname === EKS_CONTAINER_HOST_IPv6) { - return; - } - if (url2.hostname.includes("[")) { - if (url2.hostname === "[::1]" || url2.hostname === "[0000:0000:0000:0000:0000:0000:0000:0001]") { - return; - } - } else { - if (url2.hostname === "localhost") { - return; - } - const ipComponents = url2.hostname.split("."); - const inRange = (component) => { - const num = parseInt(component, 10); - return 0 <= num && num <= 255; - }; - if (ipComponents[0] === "127" && inRange(ipComponents[1]) && inRange(ipComponents[2]) && inRange(ipComponents[3]) && ipComponents.length === 4) { - return; - } - } - throw new property_provider_1.CredentialsProviderError(`URL not accepted. It must either be HTTPS or match one of the following: - - loopback CIDR 127.0.0.0/8 or [::1/128] - - ECS container host 169.254.170.2 - - EKS container host 169.254.170.23 or [fd00:ec2::23]`, { logger: logger4 }); - }; - exports.checkUrl = checkUrl; - } -}); - -// node_modules/.pnpm/@aws-sdk+credential-provider-http@3.972.27/node_modules/@aws-sdk/credential-provider-http/dist-cjs/fromHttp/requestHelpers.js -var require_requestHelpers = __commonJS({ - "node_modules/.pnpm/@aws-sdk+credential-provider-http@3.972.27/node_modules/@aws-sdk/credential-provider-http/dist-cjs/fromHttp/requestHelpers.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.createGetRequest = createGetRequest; - exports.getCredentials = getCredentials; - var property_provider_1 = require_dist_cjs41(); - var protocol_http_1 = require_dist_cjs2(); - var smithy_client_1 = require_dist_cjs27(); - var util_stream_1 = require_dist_cjs13(); - function createGetRequest(url2) { - return new protocol_http_1.HttpRequest({ - protocol: url2.protocol, - hostname: url2.hostname, - port: Number(url2.port), - path: url2.pathname, - query: Array.from(url2.searchParams.entries()).reduce((acc, [k5, v5]) => { - acc[k5] = v5; - return acc; - }, {}), - fragment: url2.hash - }); - } - async function getCredentials(response, logger4) { - const stream = (0, util_stream_1.sdkStreamMixin)(response.body); - const str = await stream.transformToString(); - if (response.statusCode === 200) { - const parsed = JSON.parse(str); - if (typeof parsed.AccessKeyId !== "string" || typeof parsed.SecretAccessKey !== "string" || typeof parsed.Token !== "string" || typeof parsed.Expiration !== "string") { - throw new property_provider_1.CredentialsProviderError("HTTP credential provider response not of the required format, an object matching: { AccessKeyId: string, SecretAccessKey: string, Token: string, Expiration: string(rfc3339) }", { logger: logger4 }); - } - return { - accessKeyId: parsed.AccessKeyId, - secretAccessKey: parsed.SecretAccessKey, - sessionToken: parsed.Token, - expiration: (0, smithy_client_1.parseRfc3339DateTime)(parsed.Expiration) - }; - } - if (response.statusCode >= 400 && response.statusCode < 500) { - let parsedBody = {}; - try { - parsedBody = JSON.parse(str); - } catch (e5) { - } - throw Object.assign(new property_provider_1.CredentialsProviderError(`Server responded with status: ${response.statusCode}`, { logger: logger4 }), { - Code: parsedBody.Code, - Message: parsedBody.Message - }); - } - throw new property_provider_1.CredentialsProviderError(`Server responded with status: ${response.statusCode}`, { logger: logger4 }); - } - } -}); - -// node_modules/.pnpm/@aws-sdk+credential-provider-http@3.972.27/node_modules/@aws-sdk/credential-provider-http/dist-cjs/fromHttp/retry-wrapper.js -var require_retry_wrapper = __commonJS({ - "node_modules/.pnpm/@aws-sdk+credential-provider-http@3.972.27/node_modules/@aws-sdk/credential-provider-http/dist-cjs/fromHttp/retry-wrapper.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.retryWrapper = void 0; - var retryWrapper = (toRetry, maxRetries, delayMs) => { - return async () => { - for (let i5 = 0; i5 < maxRetries; ++i5) { - try { - return await toRetry(); - } catch (e5) { - await new Promise((resolve4) => setTimeout(resolve4, delayMs)); - } - } - return await toRetry(); - }; - }; - exports.retryWrapper = retryWrapper; - } -}); - -// node_modules/.pnpm/@aws-sdk+credential-provider-http@3.972.27/node_modules/@aws-sdk/credential-provider-http/dist-cjs/fromHttp/fromHttp.js -var require_fromHttp = __commonJS({ - "node_modules/.pnpm/@aws-sdk+credential-provider-http@3.972.27/node_modules/@aws-sdk/credential-provider-http/dist-cjs/fromHttp/fromHttp.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.fromHttp = void 0; - var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); - var client_1 = (init_client2(), __toCommonJS(client_exports)); - var node_http_handler_1 = require_dist_cjs10(); - var property_provider_1 = require_dist_cjs41(); - var promises_1 = tslib_1.__importDefault(__require("node:fs/promises")); - var checkUrl_1 = require_checkUrl(); - var requestHelpers_1 = require_requestHelpers(); - var retry_wrapper_1 = require_retry_wrapper(); - var AWS_CONTAINER_CREDENTIALS_RELATIVE_URI = "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI"; - var DEFAULT_LINK_LOCAL_HOST = "http://169.254.170.2"; - var AWS_CONTAINER_CREDENTIALS_FULL_URI = "AWS_CONTAINER_CREDENTIALS_FULL_URI"; - var AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE = "AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE"; - var AWS_CONTAINER_AUTHORIZATION_TOKEN = "AWS_CONTAINER_AUTHORIZATION_TOKEN"; - var fromHttp = (options = {}) => { - options.logger?.debug("@aws-sdk/credential-provider-http - fromHttp"); - let host; - const relative3 = options.awsContainerCredentialsRelativeUri ?? process.env[AWS_CONTAINER_CREDENTIALS_RELATIVE_URI]; - const full = options.awsContainerCredentialsFullUri ?? process.env[AWS_CONTAINER_CREDENTIALS_FULL_URI]; - const token = options.awsContainerAuthorizationToken ?? process.env[AWS_CONTAINER_AUTHORIZATION_TOKEN]; - const tokenFile = options.awsContainerAuthorizationTokenFile ?? process.env[AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE]; - const warn = options.logger?.constructor?.name === "NoOpLogger" || !options.logger?.warn ? console.warn : options.logger.warn.bind(options.logger); - if (relative3 && full) { - warn("@aws-sdk/credential-provider-http: you have set both awsContainerCredentialsRelativeUri and awsContainerCredentialsFullUri."); - warn("awsContainerCredentialsFullUri will take precedence."); - } - if (token && tokenFile) { - warn("@aws-sdk/credential-provider-http: you have set both awsContainerAuthorizationToken and awsContainerAuthorizationTokenFile."); - warn("awsContainerAuthorizationToken will take precedence."); - } - if (full) { - host = full; - } else if (relative3) { - host = `${DEFAULT_LINK_LOCAL_HOST}${relative3}`; - } else { - throw new property_provider_1.CredentialsProviderError(`No HTTP credential provider host provided. -Set AWS_CONTAINER_CREDENTIALS_FULL_URI or AWS_CONTAINER_CREDENTIALS_RELATIVE_URI.`, { logger: options.logger }); - } - const url2 = new URL(host); - (0, checkUrl_1.checkUrl)(url2, options.logger); - const requestHandler = node_http_handler_1.NodeHttpHandler.create({ - requestTimeout: options.timeout ?? 1e3, - connectionTimeout: options.timeout ?? 1e3 - }); - return (0, retry_wrapper_1.retryWrapper)(async () => { - const request = (0, requestHelpers_1.createGetRequest)(url2); - if (token) { - request.headers.Authorization = token; - } else if (tokenFile) { - request.headers.Authorization = (await promises_1.default.readFile(tokenFile)).toString(); - } - try { - const result = await requestHandler.handle(request); - return (0, requestHelpers_1.getCredentials)(result.response).then((creds) => (0, client_1.setCredentialFeature)(creds, "CREDENTIALS_HTTP", "z")); - } catch (e5) { - throw new property_provider_1.CredentialsProviderError(String(e5), { logger: options.logger }); - } - }, options.maxRetries ?? 3, options.timeout ?? 1e3); - }; - exports.fromHttp = fromHttp; - } -}); - -// node_modules/.pnpm/@aws-sdk+credential-provider-http@3.972.27/node_modules/@aws-sdk/credential-provider-http/dist-cjs/index.js -var require_dist_cjs50 = __commonJS({ - "node_modules/.pnpm/@aws-sdk+credential-provider-http@3.972.27/node_modules/@aws-sdk/credential-provider-http/dist-cjs/index.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.fromHttp = void 0; - var fromHttp_1 = require_fromHttp(); - Object.defineProperty(exports, "fromHttp", { enumerable: true, get: function() { - return fromHttp_1.fromHttp; - } }); - } -}); - -// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/auth/httpAuthSchemeProvider.js -function createAwsAuthSigv4HttpAuthOption(authParameters) { - return { - schemeId: "aws.auth#sigv4", - signingProperties: { - name: "sso-oauth", - region: authParameters.region - }, - propertiesExtractor: (config3, context) => ({ - signingProperties: { - config: config3, - context - } - }) - }; -} -function createSmithyApiNoAuthHttpAuthOption(authParameters) { - return { - schemeId: "smithy.api#noAuth" - }; -} -var import_util_middleware6, defaultSSOOIDCHttpAuthSchemeParametersProvider, defaultSSOOIDCHttpAuthSchemeProvider, resolveHttpAuthSchemeConfig; -var init_httpAuthSchemeProvider = __esm({ - "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/auth/httpAuthSchemeProvider.js"() { - init_httpAuthSchemes2(); - import_util_middleware6 = __toESM(require_dist_cjs18()); - defaultSSOOIDCHttpAuthSchemeParametersProvider = async (config3, context, input) => { - return { - operation: (0, import_util_middleware6.getSmithyContext)(context).operation, - region: await (0, import_util_middleware6.normalizeProvider)(config3.region)() || (() => { - throw new Error("expected `region` to be configured for `aws.auth#sigv4`"); - })() - }; - }; - defaultSSOOIDCHttpAuthSchemeProvider = (authParameters) => { - const options = []; - switch (authParameters.operation) { - case "CreateToken": { - options.push(createSmithyApiNoAuthHttpAuthOption(authParameters)); - break; - } - default: { - options.push(createAwsAuthSigv4HttpAuthOption(authParameters)); - } - } - return options; - }; - resolveHttpAuthSchemeConfig = (config3) => { - const config_0 = resolveAwsSdkSigV4Config(config3); - return Object.assign(config_0, { - authSchemePreference: (0, import_util_middleware6.normalizeProvider)(config3.authSchemePreference ?? []) - }); - }; - } -}); - -// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/endpoint/EndpointParameters.js -var resolveClientEndpointParameters, commonParams; -var init_EndpointParameters = __esm({ - "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/endpoint/EndpointParameters.js"() { - resolveClientEndpointParameters = (options) => { - return Object.assign(options, { - useDualstackEndpoint: options.useDualstackEndpoint ?? false, - useFipsEndpoint: options.useFipsEndpoint ?? false, - defaultSigningName: "sso-oauth" - }); - }; - commonParams = { - UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, - Endpoint: { type: "builtInParams", name: "endpoint" }, - Region: { type: "builtInParams", name: "region" }, - UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" } - }; - } -}); - -// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/package.json -var package_default; -var init_package = __esm({ - "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/package.json"() { - package_default = { - name: "@aws-sdk/nested-clients", - version: "3.996.19", - description: "Nested clients for AWS SDK packages.", - main: "./dist-cjs/index.js", - module: "./dist-es/index.js", - types: "./dist-types/index.d.ts", - scripts: { - build: "yarn lint && concurrently 'yarn:build:types' 'yarn:build:es' && yarn build:cjs", - "build:cjs": "node ../../scripts/compilation/inline nested-clients", - "build:es": "tsc -p tsconfig.es.json", - "build:include:deps": 'yarn g:turbo run build -F="$npm_package_name"', - "build:types": "tsc -p tsconfig.types.json", - "build:types:downlevel": "downlevel-dts dist-types dist-types/ts3.4", - clean: "premove dist-cjs dist-es dist-types tsconfig.cjs.tsbuildinfo tsconfig.es.tsbuildinfo tsconfig.types.tsbuildinfo", - lint: "node ../../scripts/validation/submodules-linter.js --pkg nested-clients", - test: "yarn g:vitest run", - "test:watch": "yarn g:vitest watch" - }, - engines: { - node: ">=20.0.0" - }, - sideEffects: false, - author: { - name: "AWS SDK for JavaScript Team", - url: "https://aws.amazon.com/javascript/" - }, - license: "Apache-2.0", - dependencies: { - "@aws-crypto/sha256-browser": "5.2.0", - "@aws-crypto/sha256-js": "5.2.0", - "@aws-sdk/core": "^3.973.27", - "@aws-sdk/middleware-host-header": "^3.972.9", - "@aws-sdk/middleware-logger": "^3.972.9", - "@aws-sdk/middleware-recursion-detection": "^3.972.10", - "@aws-sdk/middleware-user-agent": "^3.972.29", - "@aws-sdk/region-config-resolver": "^3.972.11", - "@aws-sdk/types": "^3.973.7", - "@aws-sdk/util-endpoints": "^3.996.6", - "@aws-sdk/util-user-agent-browser": "^3.972.9", - "@aws-sdk/util-user-agent-node": "^3.973.15", - "@smithy/config-resolver": "^4.4.14", - "@smithy/core": "^3.23.14", - "@smithy/fetch-http-handler": "^5.3.16", - "@smithy/hash-node": "^4.2.13", - "@smithy/invalid-dependency": "^4.2.13", - "@smithy/middleware-content-length": "^4.2.13", - "@smithy/middleware-endpoint": "^4.4.29", - "@smithy/middleware-retry": "^4.5.0", - "@smithy/middleware-serde": "^4.2.17", - "@smithy/middleware-stack": "^4.2.13", - "@smithy/node-config-provider": "^4.3.13", - "@smithy/node-http-handler": "^4.5.2", - "@smithy/protocol-http": "^5.3.13", - "@smithy/smithy-client": "^4.12.9", - "@smithy/types": "^4.14.0", - "@smithy/url-parser": "^4.2.13", - "@smithy/util-base64": "^4.3.2", - "@smithy/util-body-length-browser": "^4.2.2", - "@smithy/util-body-length-node": "^4.2.3", - "@smithy/util-defaults-mode-browser": "^4.3.45", - "@smithy/util-defaults-mode-node": "^4.2.49", - "@smithy/util-endpoints": "^3.3.4", - "@smithy/util-middleware": "^4.2.13", - "@smithy/util-retry": "^4.3.0", - "@smithy/util-utf8": "^4.2.2", - tslib: "^2.6.2" - }, - devDependencies: { - concurrently: "7.0.0", - "downlevel-dts": "0.10.1", - premove: "4.0.0", - typescript: "~5.8.3" - }, - typesVersions: { - "<4.5": { - "dist-types/*": [ - "dist-types/ts3.4/*" - ] - } - }, - files: [ - "./cognito-identity.d.ts", - "./cognito-identity.js", - "./signin.d.ts", - "./signin.js", - "./sso-oidc.d.ts", - "./sso-oidc.js", - "./sso.d.ts", - "./sso.js", - "./sts.d.ts", - "./sts.js", - "dist-*/**" - ], - browser: { - "./dist-es/submodules/cognito-identity/runtimeConfig": "./dist-es/submodules/cognito-identity/runtimeConfig.browser", - "./dist-es/submodules/signin/runtimeConfig": "./dist-es/submodules/signin/runtimeConfig.browser", - "./dist-es/submodules/sso-oidc/runtimeConfig": "./dist-es/submodules/sso-oidc/runtimeConfig.browser", - "./dist-es/submodules/sso/runtimeConfig": "./dist-es/submodules/sso/runtimeConfig.browser", - "./dist-es/submodules/sts/runtimeConfig": "./dist-es/submodules/sts/runtimeConfig.browser" - }, - "react-native": {}, - homepage: "https://github.com/aws/aws-sdk-js-v3/tree/main/packages/nested-clients", - repository: { - type: "git", - url: "https://github.com/aws/aws-sdk-js-v3.git", - directory: "packages/nested-clients" - }, - exports: { - "./package.json": "./package.json", - "./sso-oidc": { - types: "./dist-types/submodules/sso-oidc/index.d.ts", - module: "./dist-es/submodules/sso-oidc/index.js", - node: "./dist-cjs/submodules/sso-oidc/index.js", - import: "./dist-es/submodules/sso-oidc/index.js", - require: "./dist-cjs/submodules/sso-oidc/index.js" - }, - "./sts": { - types: "./dist-types/submodules/sts/index.d.ts", - module: "./dist-es/submodules/sts/index.js", - node: "./dist-cjs/submodules/sts/index.js", - import: "./dist-es/submodules/sts/index.js", - require: "./dist-cjs/submodules/sts/index.js" - }, - "./signin": { - types: "./dist-types/submodules/signin/index.d.ts", - module: "./dist-es/submodules/signin/index.js", - node: "./dist-cjs/submodules/signin/index.js", - import: "./dist-es/submodules/signin/index.js", - require: "./dist-cjs/submodules/signin/index.js" - }, - "./cognito-identity": { - types: "./dist-types/submodules/cognito-identity/index.d.ts", - module: "./dist-es/submodules/cognito-identity/index.js", - node: "./dist-cjs/submodules/cognito-identity/index.js", - import: "./dist-es/submodules/cognito-identity/index.js", - require: "./dist-cjs/submodules/cognito-identity/index.js" - }, - "./sso": { - types: "./dist-types/submodules/sso/index.d.ts", - module: "./dist-es/submodules/sso/index.js", - node: "./dist-cjs/submodules/sso/index.js", - import: "./dist-es/submodules/sso/index.js", - require: "./dist-cjs/submodules/sso/index.js" - } - } - }; - } -}); - -// node_modules/.pnpm/@aws-sdk+util-user-agent-node@3.973.15/node_modules/@aws-sdk/util-user-agent-node/dist-cjs/index.js -var require_dist_cjs51 = __commonJS({ - "node_modules/.pnpm/@aws-sdk+util-user-agent-node@3.973.15/node_modules/@aws-sdk/util-user-agent-node/dist-cjs/index.js"(exports) { - "use strict"; - var node_os = __require("node:os"); - var node_process = __require("node:process"); - var utilConfigProvider = require_dist_cjs31(); - var promises = __require("node:fs/promises"); - var node_path = __require("node:path"); - var middlewareUserAgent = require_dist_cjs37(); - var getRuntimeUserAgentPair = () => { - const runtimesToCheck = ["deno", "bun", "llrt"]; - for (const runtime of runtimesToCheck) { - if (node_process.versions[runtime]) { - return [`md/${runtime}`, node_process.versions[runtime]]; - } - } - return ["md/nodejs", node_process.versions.node]; - }; - var getNodeModulesParentDirs = (dirname3) => { - const cwd = process.cwd(); - if (!dirname3) { - return [cwd]; - } - const normalizedPath = node_path.normalize(dirname3); - const parts = normalizedPath.split(node_path.sep); - const nodeModulesIndex = parts.indexOf("node_modules"); - const parentDir = nodeModulesIndex !== -1 ? parts.slice(0, nodeModulesIndex).join(node_path.sep) : normalizedPath; - if (cwd === parentDir) { - return [cwd]; - } - return [parentDir, cwd]; - }; - var SEMVER_REGEX = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*)?$/; - var getSanitizedTypeScriptVersion = (version3 = "") => { - const match = version3.match(SEMVER_REGEX); - if (!match) { - return void 0; - } - const [major, minor, patch, prerelease] = [match[1], match[2], match[3], match[4]]; - return prerelease ? `${major}.${minor}.${patch}-${prerelease}` : `${major}.${minor}.${patch}`; - }; - var ALLOWED_PREFIXES = ["^", "~", ">=", "<=", ">", "<"]; - var ALLOWED_DIST_TAGS = ["latest", "beta", "dev", "rc", "insiders", "next"]; - var getSanitizedDevTypeScriptVersion = (version3 = "") => { - if (ALLOWED_DIST_TAGS.includes(version3)) { - return version3; - } - const prefix = ALLOWED_PREFIXES.find((p5) => version3.startsWith(p5)) ?? ""; - const sanitizedTypeScriptVersion = getSanitizedTypeScriptVersion(version3.slice(prefix.length)); - if (!sanitizedTypeScriptVersion) { - return void 0; - } - return `${prefix}${sanitizedTypeScriptVersion}`; - }; - var tscVersion; - var TS_PACKAGE_JSON = node_path.join("node_modules", "typescript", "package.json"); - var getTypeScriptUserAgentPair = async () => { - if (tscVersion === null) { - return void 0; - } else if (typeof tscVersion === "string") { - return ["md/tsc", tscVersion]; - } - let isTypeScriptDetectionDisabled = false; - try { - isTypeScriptDetectionDisabled = utilConfigProvider.booleanSelector(process.env, "AWS_SDK_JS_TYPESCRIPT_DETECTION_DISABLED", utilConfigProvider.SelectorType.ENV) || false; - } catch { - } - if (isTypeScriptDetectionDisabled) { - tscVersion = null; - return void 0; - } - const dirname3 = typeof __dirname !== "undefined" ? __dirname : void 0; - const nodeModulesParentDirs = getNodeModulesParentDirs(dirname3); - let versionFromApp; - for (const nodeModulesParentDir of nodeModulesParentDirs) { - try { - const appPackageJsonPath = node_path.join(nodeModulesParentDir, "package.json"); - const packageJson = await promises.readFile(appPackageJsonPath, "utf-8"); - const { dependencies, devDependencies } = JSON.parse(packageJson); - const version3 = devDependencies?.typescript ?? dependencies?.typescript; - if (typeof version3 !== "string") { - continue; - } - versionFromApp = version3; - break; - } catch { - } - } - if (!versionFromApp) { - tscVersion = null; - return void 0; - } - let versionFromNodeModules; - for (const nodeModulesParentDir of nodeModulesParentDirs) { - try { - const tsPackageJsonPath = node_path.join(nodeModulesParentDir, TS_PACKAGE_JSON); - const packageJson = await promises.readFile(tsPackageJsonPath, "utf-8"); - const { version: version3 } = JSON.parse(packageJson); - const sanitizedVersion2 = getSanitizedTypeScriptVersion(version3); - if (typeof sanitizedVersion2 !== "string") { - continue; - } - versionFromNodeModules = sanitizedVersion2; - break; - } catch { - } - } - if (versionFromNodeModules) { - tscVersion = versionFromNodeModules; - return ["md/tsc", tscVersion]; - } - const sanitizedVersion = getSanitizedDevTypeScriptVersion(versionFromApp); - if (typeof sanitizedVersion !== "string") { - tscVersion = null; - return void 0; - } - tscVersion = `dev_${sanitizedVersion}`; - return ["md/tsc", tscVersion]; - }; - var crtAvailability = { - isCrtAvailable: false - }; - var isCrtAvailable = () => { - if (crtAvailability.isCrtAvailable) { - return ["md/crt-avail"]; - } - return null; - }; - var createDefaultUserAgentProvider5 = ({ serviceId, clientVersion }) => { - const runtimeUserAgentPair = getRuntimeUserAgentPair(); - return async (config3) => { - const sections = [ - ["aws-sdk-js", clientVersion], - ["ua", "2.1"], - [`os/${node_os.platform()}`, node_os.release()], - ["lang/js"], - runtimeUserAgentPair - ]; - const typescriptUserAgentPair = await getTypeScriptUserAgentPair(); - if (typescriptUserAgentPair) { - sections.push(typescriptUserAgentPair); - } - const crtAvailable = isCrtAvailable(); - if (crtAvailable) { - sections.push(crtAvailable); - } - if (serviceId) { - sections.push([`api/${serviceId}`, clientVersion]); - } - if (node_process.env.AWS_EXECUTION_ENV) { - sections.push([`exec-env/${node_process.env.AWS_EXECUTION_ENV}`]); - } - const appId = await config3?.userAgentAppId?.(); - const resolvedUserAgent = appId ? [...sections, [`app/${appId}`]] : [...sections]; - return resolvedUserAgent; - }; - }; - var defaultUserAgent = createDefaultUserAgentProvider5; - var UA_APP_ID_ENV_NAME = "AWS_SDK_UA_APP_ID"; - var UA_APP_ID_INI_NAME = "sdk_ua_app_id"; - var UA_APP_ID_INI_NAME_DEPRECATED = "sdk-ua-app-id"; - var NODE_APP_ID_CONFIG_OPTIONS5 = { - environmentVariableSelector: (env2) => env2[UA_APP_ID_ENV_NAME], - configFileSelector: (profile) => profile[UA_APP_ID_INI_NAME] ?? profile[UA_APP_ID_INI_NAME_DEPRECATED], - default: middlewareUserAgent.DEFAULT_UA_APP_ID - }; - exports.NODE_APP_ID_CONFIG_OPTIONS = NODE_APP_ID_CONFIG_OPTIONS5; - exports.UA_APP_ID_ENV_NAME = UA_APP_ID_ENV_NAME; - exports.UA_APP_ID_INI_NAME = UA_APP_ID_INI_NAME; - exports.createDefaultUserAgentProvider = createDefaultUserAgentProvider5; - exports.crtAvailability = crtAvailability; - exports.defaultUserAgent = defaultUserAgent; - } -}); - -// node_modules/.pnpm/@smithy+hash-node@4.2.13/node_modules/@smithy/hash-node/dist-cjs/index.js -var require_dist_cjs52 = __commonJS({ - "node_modules/.pnpm/@smithy+hash-node@4.2.13/node_modules/@smithy/hash-node/dist-cjs/index.js"(exports) { - "use strict"; - var utilBufferFrom = require_dist_cjs5(); - var utilUtf8 = require_dist_cjs6(); - var buffer2 = __require("buffer"); - var crypto6 = __require("crypto"); - var Hash5 = class { - algorithmIdentifier; - secret; - hash; - constructor(algorithmIdentifier, secret) { - this.algorithmIdentifier = algorithmIdentifier; - this.secret = secret; - this.reset(); - } - update(toHash, encoding) { - this.hash.update(utilUtf8.toUint8Array(castSourceData(toHash, encoding))); - } - digest() { - return Promise.resolve(this.hash.digest()); - } - reset() { - this.hash = this.secret ? crypto6.createHmac(this.algorithmIdentifier, castSourceData(this.secret)) : crypto6.createHash(this.algorithmIdentifier); - } - }; - function castSourceData(toCast, encoding) { - if (buffer2.Buffer.isBuffer(toCast)) { - return toCast; - } - if (typeof toCast === "string") { - return utilBufferFrom.fromString(toCast, encoding); - } - if (ArrayBuffer.isView(toCast)) { - return utilBufferFrom.fromArrayBuffer(toCast.buffer, toCast.byteOffset, toCast.byteLength); - } - return utilBufferFrom.fromArrayBuffer(toCast); - } - exports.Hash = Hash5; - } -}); - -// node_modules/.pnpm/@smithy+util-body-length-node@4.2.3/node_modules/@smithy/util-body-length-node/dist-cjs/index.js -var require_dist_cjs53 = __commonJS({ - "node_modules/.pnpm/@smithy+util-body-length-node@4.2.3/node_modules/@smithy/util-body-length-node/dist-cjs/index.js"(exports) { - "use strict"; - var node_fs = __require("node:fs"); - var calculateBodyLength5 = (body) => { - if (!body) { - return 0; - } - if (typeof body === "string") { - return Buffer.byteLength(body); - } else if (typeof body.byteLength === "number") { - return body.byteLength; - } else if (typeof body.size === "number") { - return body.size; - } else if (typeof body.start === "number" && typeof body.end === "number") { - return body.end + 1 - body.start; - } else if (body instanceof node_fs.ReadStream) { - if (body.path != null) { - return node_fs.lstatSync(body.path).size; - } else if (typeof body.fd === "number") { - return node_fs.fstatSync(body.fd).size; - } - } - throw new Error(`Body Length computation failed for ${body}`); - }; - exports.calculateBodyLength = calculateBodyLength5; - } -}); - -// node_modules/.pnpm/@smithy+util-defaults-mode-node@4.2.50/node_modules/@smithy/util-defaults-mode-node/dist-cjs/index.js -var require_dist_cjs54 = __commonJS({ - "node_modules/.pnpm/@smithy+util-defaults-mode-node@4.2.50/node_modules/@smithy/util-defaults-mode-node/dist-cjs/index.js"(exports) { - "use strict"; - var configResolver = require_dist_cjs38(); - var nodeConfigProvider = require_dist_cjs43(); - var propertyProvider = require_dist_cjs41(); - var AWS_EXECUTION_ENV = "AWS_EXECUTION_ENV"; - var AWS_REGION_ENV = "AWS_REGION"; - var AWS_DEFAULT_REGION_ENV = "AWS_DEFAULT_REGION"; - var ENV_IMDS_DISABLED = "AWS_EC2_METADATA_DISABLED"; - var DEFAULTS_MODE_OPTIONS = ["in-region", "cross-region", "mobile", "standard", "legacy"]; - var IMDS_REGION_PATH = "/latest/meta-data/placement/region"; - var AWS_DEFAULTS_MODE_ENV = "AWS_DEFAULTS_MODE"; - var AWS_DEFAULTS_MODE_CONFIG = "defaults_mode"; - var NODE_DEFAULTS_MODE_CONFIG_OPTIONS = { - environmentVariableSelector: (env2) => { - return env2[AWS_DEFAULTS_MODE_ENV]; - }, - configFileSelector: (profile) => { - return profile[AWS_DEFAULTS_MODE_CONFIG]; - }, - default: "legacy" - }; - var resolveDefaultsModeConfig5 = ({ region = nodeConfigProvider.loadConfig(configResolver.NODE_REGION_CONFIG_OPTIONS), defaultsMode = nodeConfigProvider.loadConfig(NODE_DEFAULTS_MODE_CONFIG_OPTIONS) } = {}) => propertyProvider.memoize(async () => { - const mode = typeof defaultsMode === "function" ? await defaultsMode() : defaultsMode; - switch (mode?.toLowerCase()) { - case "auto": - return resolveNodeDefaultsModeAuto(region); - case "in-region": - case "cross-region": - case "mobile": - case "standard": - case "legacy": - return Promise.resolve(mode?.toLocaleLowerCase()); - case void 0: - return Promise.resolve("legacy"); - default: - throw new Error(`Invalid parameter for "defaultsMode", expect ${DEFAULTS_MODE_OPTIONS.join(", ")}, got ${mode}`); - } - }); - var resolveNodeDefaultsModeAuto = async (clientRegion) => { - if (clientRegion) { - const resolvedRegion = typeof clientRegion === "function" ? await clientRegion() : clientRegion; - const inferredRegion = await inferPhysicalRegion(); - if (!inferredRegion) { - return "standard"; - } - if (resolvedRegion === inferredRegion) { - return "in-region"; - } else { - return "cross-region"; - } - } - return "standard"; - }; - var inferPhysicalRegion = async () => { - if (process.env[AWS_EXECUTION_ENV] && (process.env[AWS_REGION_ENV] || process.env[AWS_DEFAULT_REGION_ENV])) { - return process.env[AWS_REGION_ENV] ?? process.env[AWS_DEFAULT_REGION_ENV]; - } - if (!process.env[ENV_IMDS_DISABLED]) { - try { - const { getInstanceMetadataEndpoint, httpRequest: httpRequest2 } = await Promise.resolve().then(() => __toESM(require_dist_cjs49())); - const endpoint = await getInstanceMetadataEndpoint(); - return (await httpRequest2({ ...endpoint, path: IMDS_REGION_PATH })).toString(); - } catch (e5) { - } - } - }; - exports.resolveDefaultsModeConfig = resolveDefaultsModeConfig5; - } -}); - -// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/endpoint/ruleset.js -var u, v, w, x, a, b2, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, _data, ruleSet; -var init_ruleset = __esm({ - "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/endpoint/ruleset.js"() { - u = "required"; - v = "fn"; - w = "argv"; - x = "ref"; - a = true; - b2 = "isSet"; - c = "booleanEquals"; - d = "error"; - e = "endpoint"; - f = "tree"; - g = "PartitionResult"; - h = "getAttr"; - i = { [u]: false, type: "string" }; - j = { [u]: true, default: false, type: "boolean" }; - k = { [x]: "Endpoint" }; - l = { [v]: c, [w]: [{ [x]: "UseFIPS" }, true] }; - m = { [v]: c, [w]: [{ [x]: "UseDualStack" }, true] }; - n = {}; - o = { [v]: h, [w]: [{ [x]: g }, "supportsFIPS"] }; - p = { [x]: g }; - q = { [v]: c, [w]: [true, { [v]: h, [w]: [p, "supportsDualStack"] }] }; - r = [l]; - s = [m]; - t = [{ [x]: "Region" }]; - _data = { - version: "1.0", - parameters: { Region: i, UseDualStack: j, UseFIPS: j, Endpoint: i }, - rules: [ - { - conditions: [{ [v]: b2, [w]: [k] }], - rules: [ - { conditions: r, error: "Invalid Configuration: FIPS and custom endpoint are not supported", type: d }, - { conditions: s, error: "Invalid Configuration: Dualstack and custom endpoint are not supported", type: d }, - { endpoint: { url: k, properties: n, headers: n }, type: e } - ], - type: f - }, - { - conditions: [{ [v]: b2, [w]: t }], - rules: [ - { - conditions: [{ [v]: "aws.partition", [w]: t, assign: g }], - rules: [ - { - conditions: [l, m], - rules: [ - { - conditions: [{ [v]: c, [w]: [a, o] }, q], - rules: [ - { - endpoint: { - url: "https://oidc-fips.{Region}.{PartitionResult#dualStackDnsSuffix}", - properties: n, - headers: n - }, - type: e - } - ], - type: f - }, - { error: "FIPS and DualStack are enabled, but this partition does not support one or both", type: d } - ], - type: f - }, - { - conditions: r, - rules: [ - { - conditions: [{ [v]: c, [w]: [o, a] }], - rules: [ - { - conditions: [{ [v]: "stringEquals", [w]: [{ [v]: h, [w]: [p, "name"] }, "aws-us-gov"] }], - endpoint: { url: "https://oidc.{Region}.amazonaws.com", properties: n, headers: n }, - type: e - }, - { - endpoint: { - url: "https://oidc-fips.{Region}.{PartitionResult#dnsSuffix}", - properties: n, - headers: n - }, - type: e - } - ], - type: f - }, - { error: "FIPS is enabled but this partition does not support FIPS", type: d } - ], - type: f - }, - { - conditions: s, - rules: [ - { - conditions: [q], - rules: [ - { - endpoint: { - url: "https://oidc.{Region}.{PartitionResult#dualStackDnsSuffix}", - properties: n, - headers: n - }, - type: e - } - ], - type: f - }, - { error: "DualStack is enabled but this partition does not support DualStack", type: d } - ], - type: f - }, - { - endpoint: { url: "https://oidc.{Region}.{PartitionResult#dnsSuffix}", properties: n, headers: n }, - type: e - } - ], - type: f - } - ], - type: f - }, - { error: "Invalid Configuration: Missing Region", type: d } - ] - }; - ruleSet = _data; - } -}); - -// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/endpoint/endpointResolver.js -var import_util_endpoints, import_util_endpoints2, cache, defaultEndpointResolver; -var init_endpointResolver = __esm({ - "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/endpoint/endpointResolver.js"() { - import_util_endpoints = __toESM(require_dist_cjs34()); - import_util_endpoints2 = __toESM(require_dist_cjs33()); - init_ruleset(); - cache = new import_util_endpoints2.EndpointCache({ - size: 50, - params: ["Endpoint", "Region", "UseDualStack", "UseFIPS"] - }); - defaultEndpointResolver = (endpointParams, context = {}) => { - return cache.get(endpointParams, () => (0, import_util_endpoints2.resolveEndpoint)(ruleSet, { - endpointParams, - logger: context.logger - })); - }; - import_util_endpoints2.customEndpointFunctions.aws = import_util_endpoints.awsEndpointFunctions; - } -}); - -// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/models/SSOOIDCServiceException.js -var import_smithy_client8, SSOOIDCServiceException; -var init_SSOOIDCServiceException = __esm({ - "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/models/SSOOIDCServiceException.js"() { - import_smithy_client8 = __toESM(require_dist_cjs27()); - SSOOIDCServiceException = class _SSOOIDCServiceException extends import_smithy_client8.ServiceException { - constructor(options) { - super(options); - Object.setPrototypeOf(this, _SSOOIDCServiceException.prototype); - } - }; - } -}); - -// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/models/errors.js -var AccessDeniedException, AuthorizationPendingException, ExpiredTokenException, InternalServerException, InvalidClientException, InvalidGrantException, InvalidRequestException, InvalidScopeException, SlowDownException, UnauthorizedClientException, UnsupportedGrantTypeException; -var init_errors3 = __esm({ - "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/models/errors.js"() { - init_SSOOIDCServiceException(); - AccessDeniedException = class _AccessDeniedException extends SSOOIDCServiceException { - name = "AccessDeniedException"; - $fault = "client"; - error; - reason; - error_description; - constructor(opts) { - super({ - name: "AccessDeniedException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _AccessDeniedException.prototype); - this.error = opts.error; - this.reason = opts.reason; - this.error_description = opts.error_description; - } - }; - AuthorizationPendingException = class _AuthorizationPendingException extends SSOOIDCServiceException { - name = "AuthorizationPendingException"; - $fault = "client"; - error; - error_description; - constructor(opts) { - super({ - name: "AuthorizationPendingException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _AuthorizationPendingException.prototype); - this.error = opts.error; - this.error_description = opts.error_description; - } - }; - ExpiredTokenException = class _ExpiredTokenException extends SSOOIDCServiceException { - name = "ExpiredTokenException"; - $fault = "client"; - error; - error_description; - constructor(opts) { - super({ - name: "ExpiredTokenException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _ExpiredTokenException.prototype); - this.error = opts.error; - this.error_description = opts.error_description; - } - }; - InternalServerException = class _InternalServerException extends SSOOIDCServiceException { - name = "InternalServerException"; - $fault = "server"; - error; - error_description; - constructor(opts) { - super({ - name: "InternalServerException", - $fault: "server", - ...opts - }); - Object.setPrototypeOf(this, _InternalServerException.prototype); - this.error = opts.error; - this.error_description = opts.error_description; - } - }; - InvalidClientException = class _InvalidClientException extends SSOOIDCServiceException { - name = "InvalidClientException"; - $fault = "client"; - error; - error_description; - constructor(opts) { - super({ - name: "InvalidClientException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _InvalidClientException.prototype); - this.error = opts.error; - this.error_description = opts.error_description; - } - }; - InvalidGrantException = class _InvalidGrantException extends SSOOIDCServiceException { - name = "InvalidGrantException"; - $fault = "client"; - error; - error_description; - constructor(opts) { - super({ - name: "InvalidGrantException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _InvalidGrantException.prototype); - this.error = opts.error; - this.error_description = opts.error_description; - } - }; - InvalidRequestException = class _InvalidRequestException extends SSOOIDCServiceException { - name = "InvalidRequestException"; - $fault = "client"; - error; - reason; - error_description; - constructor(opts) { - super({ - name: "InvalidRequestException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _InvalidRequestException.prototype); - this.error = opts.error; - this.reason = opts.reason; - this.error_description = opts.error_description; - } - }; - InvalidScopeException = class _InvalidScopeException extends SSOOIDCServiceException { - name = "InvalidScopeException"; - $fault = "client"; - error; - error_description; - constructor(opts) { - super({ - name: "InvalidScopeException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _InvalidScopeException.prototype); - this.error = opts.error; - this.error_description = opts.error_description; - } - }; - SlowDownException = class _SlowDownException extends SSOOIDCServiceException { - name = "SlowDownException"; - $fault = "client"; - error; - error_description; - constructor(opts) { - super({ - name: "SlowDownException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _SlowDownException.prototype); - this.error = opts.error; - this.error_description = opts.error_description; - } - }; - UnauthorizedClientException = class _UnauthorizedClientException extends SSOOIDCServiceException { - name = "UnauthorizedClientException"; - $fault = "client"; - error; - error_description; - constructor(opts) { - super({ - name: "UnauthorizedClientException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _UnauthorizedClientException.prototype); - this.error = opts.error; - this.error_description = opts.error_description; - } - }; - UnsupportedGrantTypeException = class _UnsupportedGrantTypeException extends SSOOIDCServiceException { - name = "UnsupportedGrantTypeException"; - $fault = "client"; - error; - error_description; - constructor(opts) { - super({ - name: "UnsupportedGrantTypeException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _UnsupportedGrantTypeException.prototype); - this.error = opts.error; - this.error_description = opts.error_description; - } - }; - } -}); - -// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/schemas/schemas_0.js -var _ADE, _APE, _AT, _CS, _CT, _CTR, _CTRr, _CV, _ETE, _ICE, _IGE, _IRE, _ISE, _ISEn, _IT, _RT, _SDE, _UCE, _UGTE, _aT, _c, _cI, _cS, _cV, _co, _dC, _e, _eI, _ed, _gT, _h, _hE, _iT, _r, _rT, _rU, _s, _sc, _se, _tT, n0, _s_registry, SSOOIDCServiceException$, n0_registry, AccessDeniedException$, AuthorizationPendingException$, ExpiredTokenException$, InternalServerException$, InvalidClientException$, InvalidGrantException$, InvalidRequestException$, InvalidScopeException$, SlowDownException$, UnauthorizedClientException$, UnsupportedGrantTypeException$, errorTypeRegistries, AccessToken, ClientSecret, CodeVerifier, IdToken, RefreshToken, CreateTokenRequest$, CreateTokenResponse$, Scopes, CreateToken$; -var init_schemas_0 = __esm({ - "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/schemas/schemas_0.js"() { - init_schema3(); - init_errors3(); - init_SSOOIDCServiceException(); - _ADE = "AccessDeniedException"; - _APE = "AuthorizationPendingException"; - _AT = "AccessToken"; - _CS = "ClientSecret"; - _CT = "CreateToken"; - _CTR = "CreateTokenRequest"; - _CTRr = "CreateTokenResponse"; - _CV = "CodeVerifier"; - _ETE = "ExpiredTokenException"; - _ICE = "InvalidClientException"; - _IGE = "InvalidGrantException"; - _IRE = "InvalidRequestException"; - _ISE = "InternalServerException"; - _ISEn = "InvalidScopeException"; - _IT = "IdToken"; - _RT = "RefreshToken"; - _SDE = "SlowDownException"; - _UCE = "UnauthorizedClientException"; - _UGTE = "UnsupportedGrantTypeException"; - _aT = "accessToken"; - _c = "client"; - _cI = "clientId"; - _cS = "clientSecret"; - _cV = "codeVerifier"; - _co = "code"; - _dC = "deviceCode"; - _e = "error"; - _eI = "expiresIn"; - _ed = "error_description"; - _gT = "grantType"; - _h = "http"; - _hE = "httpError"; - _iT = "idToken"; - _r = "reason"; - _rT = "refreshToken"; - _rU = "redirectUri"; - _s = "smithy.ts.sdk.synthetic.com.amazonaws.ssooidc"; - _sc = "scope"; - _se = "server"; - _tT = "tokenType"; - n0 = "com.amazonaws.ssooidc"; - _s_registry = TypeRegistry.for(_s); - SSOOIDCServiceException$ = [-3, _s, "SSOOIDCServiceException", 0, [], []]; - _s_registry.registerError(SSOOIDCServiceException$, SSOOIDCServiceException); - n0_registry = TypeRegistry.for(n0); - AccessDeniedException$ = [ - -3, - n0, - _ADE, - { [_e]: _c, [_hE]: 400 }, - [_e, _r, _ed], - [0, 0, 0] - ]; - n0_registry.registerError(AccessDeniedException$, AccessDeniedException); - AuthorizationPendingException$ = [ - -3, - n0, - _APE, - { [_e]: _c, [_hE]: 400 }, - [_e, _ed], - [0, 0] - ]; - n0_registry.registerError(AuthorizationPendingException$, AuthorizationPendingException); - ExpiredTokenException$ = [-3, n0, _ETE, { [_e]: _c, [_hE]: 400 }, [_e, _ed], [0, 0]]; - n0_registry.registerError(ExpiredTokenException$, ExpiredTokenException); - InternalServerException$ = [-3, n0, _ISE, { [_e]: _se, [_hE]: 500 }, [_e, _ed], [0, 0]]; - n0_registry.registerError(InternalServerException$, InternalServerException); - InvalidClientException$ = [-3, n0, _ICE, { [_e]: _c, [_hE]: 401 }, [_e, _ed], [0, 0]]; - n0_registry.registerError(InvalidClientException$, InvalidClientException); - InvalidGrantException$ = [-3, n0, _IGE, { [_e]: _c, [_hE]: 400 }, [_e, _ed], [0, 0]]; - n0_registry.registerError(InvalidGrantException$, InvalidGrantException); - InvalidRequestException$ = [ - -3, - n0, - _IRE, - { [_e]: _c, [_hE]: 400 }, - [_e, _r, _ed], - [0, 0, 0] - ]; - n0_registry.registerError(InvalidRequestException$, InvalidRequestException); - InvalidScopeException$ = [-3, n0, _ISEn, { [_e]: _c, [_hE]: 400 }, [_e, _ed], [0, 0]]; - n0_registry.registerError(InvalidScopeException$, InvalidScopeException); - SlowDownException$ = [-3, n0, _SDE, { [_e]: _c, [_hE]: 400 }, [_e, _ed], [0, 0]]; - n0_registry.registerError(SlowDownException$, SlowDownException); - UnauthorizedClientException$ = [ - -3, - n0, - _UCE, - { [_e]: _c, [_hE]: 400 }, - [_e, _ed], - [0, 0] - ]; - n0_registry.registerError(UnauthorizedClientException$, UnauthorizedClientException); - UnsupportedGrantTypeException$ = [ - -3, - n0, - _UGTE, - { [_e]: _c, [_hE]: 400 }, - [_e, _ed], - [0, 0] - ]; - n0_registry.registerError(UnsupportedGrantTypeException$, UnsupportedGrantTypeException); - errorTypeRegistries = [_s_registry, n0_registry]; - AccessToken = [0, n0, _AT, 8, 0]; - ClientSecret = [0, n0, _CS, 8, 0]; - CodeVerifier = [0, n0, _CV, 8, 0]; - IdToken = [0, n0, _IT, 8, 0]; - RefreshToken = [0, n0, _RT, 8, 0]; - CreateTokenRequest$ = [ - 3, - n0, - _CTR, - 0, - [_cI, _cS, _gT, _dC, _co, _rT, _sc, _rU, _cV], - [0, [() => ClientSecret, 0], 0, 0, 0, [() => RefreshToken, 0], 64 | 0, 0, [() => CodeVerifier, 0]], - 3 - ]; - CreateTokenResponse$ = [ - 3, - n0, - _CTRr, - 0, - [_aT, _tT, _eI, _rT, _iT], - [[() => AccessToken, 0], 0, 1, [() => RefreshToken, 0], [() => IdToken, 0]] - ]; - Scopes = 64 | 0; - CreateToken$ = [ - 9, - n0, - _CT, - { [_h]: ["POST", "/token", 200] }, - () => CreateTokenRequest$, - () => CreateTokenResponse$ - ]; - } -}); - -// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/runtimeConfig.shared.js -var import_smithy_client9, import_url_parser2, import_util_base648, import_util_utf88, getRuntimeConfig; -var init_runtimeConfig_shared = __esm({ - "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/runtimeConfig.shared.js"() { - init_httpAuthSchemes2(); - init_protocols2(); - init_dist_es(); - import_smithy_client9 = __toESM(require_dist_cjs27()); - import_url_parser2 = __toESM(require_dist_cjs25()); - import_util_base648 = __toESM(require_dist_cjs7()); - import_util_utf88 = __toESM(require_dist_cjs6()); - init_httpAuthSchemeProvider(); - init_endpointResolver(); - init_schemas_0(); - getRuntimeConfig = (config3) => { - return { - apiVersion: "2019-06-10", - base64Decoder: config3?.base64Decoder ?? import_util_base648.fromBase64, - base64Encoder: config3?.base64Encoder ?? import_util_base648.toBase64, - disableHostPrefix: config3?.disableHostPrefix ?? false, - endpointProvider: config3?.endpointProvider ?? defaultEndpointResolver, - extensions: config3?.extensions ?? [], - httpAuthSchemeProvider: config3?.httpAuthSchemeProvider ?? defaultSSOOIDCHttpAuthSchemeProvider, - httpAuthSchemes: config3?.httpAuthSchemes ?? [ - { - schemeId: "aws.auth#sigv4", - identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"), - signer: new AwsSdkSigV4Signer() - }, - { - schemeId: "smithy.api#noAuth", - identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})), - signer: new NoAuthSigner() - } - ], - logger: config3?.logger ?? new import_smithy_client9.NoOpLogger(), - protocol: config3?.protocol ?? AwsRestJsonProtocol, - protocolSettings: config3?.protocolSettings ?? { - defaultNamespace: "com.amazonaws.ssooidc", - errorTypeRegistries, - version: "2019-06-10", - serviceTarget: "AWSSSOOIDCService" - }, - serviceId: config3?.serviceId ?? "SSO OIDC", - urlParser: config3?.urlParser ?? import_url_parser2.parseUrl, - utf8Decoder: config3?.utf8Decoder ?? import_util_utf88.fromUtf8, - utf8Encoder: config3?.utf8Encoder ?? import_util_utf88.toUtf8 - }; - }; - } -}); - -// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/runtimeConfig.js -var import_util_user_agent_node, import_config_resolver, import_hash_node, import_middleware_retry, import_node_config_provider, import_node_http_handler, import_smithy_client10, import_util_body_length_node, import_util_defaults_mode_node, import_util_retry, getRuntimeConfig2; -var init_runtimeConfig = __esm({ - "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/runtimeConfig.js"() { - init_package(); - init_client2(); - init_httpAuthSchemes2(); - import_util_user_agent_node = __toESM(require_dist_cjs51()); - import_config_resolver = __toESM(require_dist_cjs38()); - import_hash_node = __toESM(require_dist_cjs52()); - import_middleware_retry = __toESM(require_dist_cjs46()); - import_node_config_provider = __toESM(require_dist_cjs43()); - import_node_http_handler = __toESM(require_dist_cjs10()); - import_smithy_client10 = __toESM(require_dist_cjs27()); - import_util_body_length_node = __toESM(require_dist_cjs53()); - import_util_defaults_mode_node = __toESM(require_dist_cjs54()); - import_util_retry = __toESM(require_dist_cjs36()); - init_runtimeConfig_shared(); - getRuntimeConfig2 = (config3) => { - (0, import_smithy_client10.emitWarningIfUnsupportedVersion)(process.version); - const defaultsMode = (0, import_util_defaults_mode_node.resolveDefaultsModeConfig)(config3); - const defaultConfigProvider = () => defaultsMode().then(import_smithy_client10.loadConfigsForDefaultMode); - const clientSharedValues = getRuntimeConfig(config3); - emitWarningIfUnsupportedVersion(process.version); - const loaderConfig = { - profile: config3?.profile, - logger: clientSharedValues.logger - }; - return { - ...clientSharedValues, - ...config3, - runtime: "node", - defaultsMode, - authSchemePreference: config3?.authSchemePreference ?? (0, import_node_config_provider.loadConfig)(NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig), - bodyLengthChecker: config3?.bodyLengthChecker ?? import_util_body_length_node.calculateBodyLength, - defaultUserAgentProvider: config3?.defaultUserAgentProvider ?? (0, import_util_user_agent_node.createDefaultUserAgentProvider)({ serviceId: clientSharedValues.serviceId, clientVersion: package_default.version }), - maxAttempts: config3?.maxAttempts ?? (0, import_node_config_provider.loadConfig)(import_middleware_retry.NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config3), - region: config3?.region ?? (0, import_node_config_provider.loadConfig)(import_config_resolver.NODE_REGION_CONFIG_OPTIONS, { ...import_config_resolver.NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }), - requestHandler: import_node_http_handler.NodeHttpHandler.create(config3?.requestHandler ?? defaultConfigProvider), - retryMode: config3?.retryMode ?? (0, import_node_config_provider.loadConfig)({ - ...import_middleware_retry.NODE_RETRY_MODE_CONFIG_OPTIONS, - default: async () => (await defaultConfigProvider()).retryMode || import_util_retry.DEFAULT_RETRY_MODE - }, config3), - sha256: config3?.sha256 ?? import_hash_node.Hash.bind(null, "sha256"), - streamCollector: config3?.streamCollector ?? import_node_http_handler.streamCollector, - useDualstackEndpoint: config3?.useDualstackEndpoint ?? (0, import_node_config_provider.loadConfig)(import_config_resolver.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig), - useFipsEndpoint: config3?.useFipsEndpoint ?? (0, import_node_config_provider.loadConfig)(import_config_resolver.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig), - userAgentAppId: config3?.userAgentAppId ?? (0, import_node_config_provider.loadConfig)(import_util_user_agent_node.NODE_APP_ID_CONFIG_OPTIONS, loaderConfig) - }; - }; - } -}); - -// node_modules/.pnpm/@aws-sdk+region-config-resolver@3.972.11/node_modules/@aws-sdk/region-config-resolver/dist-cjs/regionConfig/stsRegionDefaultResolver.js -var require_stsRegionDefaultResolver = __commonJS({ - "node_modules/.pnpm/@aws-sdk+region-config-resolver@3.972.11/node_modules/@aws-sdk/region-config-resolver/dist-cjs/regionConfig/stsRegionDefaultResolver.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.warning = void 0; - exports.stsRegionDefaultResolver = stsRegionDefaultResolver2; - var config_resolver_1 = require_dist_cjs38(); - var node_config_provider_1 = require_dist_cjs43(); - function stsRegionDefaultResolver2(loaderConfig = {}) { - return (0, node_config_provider_1.loadConfig)({ - ...config_resolver_1.NODE_REGION_CONFIG_OPTIONS, - async default() { - if (!exports.warning.silence) { - console.warn("@aws-sdk - WARN - default STS region of us-east-1 used. See @aws-sdk/credential-providers README and set a region explicitly."); - } - return "us-east-1"; - } - }, { ...config_resolver_1.NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }); - } - exports.warning = { - silence: false - }; - } -}); - -// node_modules/.pnpm/@aws-sdk+region-config-resolver@3.972.11/node_modules/@aws-sdk/region-config-resolver/dist-cjs/index.js -var require_dist_cjs55 = __commonJS({ - "node_modules/.pnpm/@aws-sdk+region-config-resolver@3.972.11/node_modules/@aws-sdk/region-config-resolver/dist-cjs/index.js"(exports) { - "use strict"; - var stsRegionDefaultResolver2 = require_stsRegionDefaultResolver(); - var configResolver = require_dist_cjs38(); - var getAwsRegionExtensionConfiguration5 = (runtimeConfig) => { - return { - setRegion(region) { - runtimeConfig.region = region; - }, - region() { - return runtimeConfig.region; - } - }; - }; - var resolveAwsRegionExtensionConfiguration5 = (awsRegionExtensionConfiguration) => { - return { - region: awsRegionExtensionConfiguration.region() - }; - }; - exports.NODE_REGION_CONFIG_FILE_OPTIONS = configResolver.NODE_REGION_CONFIG_FILE_OPTIONS; - exports.NODE_REGION_CONFIG_OPTIONS = configResolver.NODE_REGION_CONFIG_OPTIONS; - exports.REGION_ENV_NAME = configResolver.REGION_ENV_NAME; - exports.REGION_INI_NAME = configResolver.REGION_INI_NAME; - exports.resolveRegionConfig = configResolver.resolveRegionConfig; - exports.getAwsRegionExtensionConfiguration = getAwsRegionExtensionConfiguration5; - exports.resolveAwsRegionExtensionConfiguration = resolveAwsRegionExtensionConfiguration5; - Object.prototype.hasOwnProperty.call(stsRegionDefaultResolver2, "__proto__") && !Object.prototype.hasOwnProperty.call(exports, "__proto__") && Object.defineProperty(exports, "__proto__", { - enumerable: true, - value: stsRegionDefaultResolver2["__proto__"] - }); - Object.keys(stsRegionDefaultResolver2).forEach(function(k5) { - if (k5 !== "default" && !Object.prototype.hasOwnProperty.call(exports, k5)) exports[k5] = stsRegionDefaultResolver2[k5]; - }); - } -}); - -// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/auth/httpAuthExtensionConfiguration.js -var getHttpAuthExtensionConfiguration, resolveHttpAuthRuntimeConfig; -var init_httpAuthExtensionConfiguration = __esm({ - "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/auth/httpAuthExtensionConfiguration.js"() { - getHttpAuthExtensionConfiguration = (runtimeConfig) => { - const _httpAuthSchemes = runtimeConfig.httpAuthSchemes; - let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider; - let _credentials = runtimeConfig.credentials; - return { - setHttpAuthScheme(httpAuthScheme) { - const index2 = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId); - if (index2 === -1) { - _httpAuthSchemes.push(httpAuthScheme); - } else { - _httpAuthSchemes.splice(index2, 1, httpAuthScheme); - } - }, - httpAuthSchemes() { - return _httpAuthSchemes; - }, - setHttpAuthSchemeProvider(httpAuthSchemeProvider) { - _httpAuthSchemeProvider = httpAuthSchemeProvider; - }, - httpAuthSchemeProvider() { - return _httpAuthSchemeProvider; - }, - setCredentials(credentials) { - _credentials = credentials; - }, - credentials() { - return _credentials; - } - }; - }; - resolveHttpAuthRuntimeConfig = (config3) => { - return { - httpAuthSchemes: config3.httpAuthSchemes(), - httpAuthSchemeProvider: config3.httpAuthSchemeProvider(), - credentials: config3.credentials() - }; - }; - } -}); - -// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/runtimeExtensions.js -var import_region_config_resolver, import_protocol_http12, import_smithy_client11, resolveRuntimeExtensions; -var init_runtimeExtensions = __esm({ - "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/runtimeExtensions.js"() { - import_region_config_resolver = __toESM(require_dist_cjs55()); - import_protocol_http12 = __toESM(require_dist_cjs2()); - import_smithy_client11 = __toESM(require_dist_cjs27()); - init_httpAuthExtensionConfiguration(); - resolveRuntimeExtensions = (runtimeConfig, extensions) => { - const extensionConfiguration = Object.assign((0, import_region_config_resolver.getAwsRegionExtensionConfiguration)(runtimeConfig), (0, import_smithy_client11.getDefaultExtensionConfiguration)(runtimeConfig), (0, import_protocol_http12.getHttpHandlerExtensionConfiguration)(runtimeConfig), getHttpAuthExtensionConfiguration(runtimeConfig)); - extensions.forEach((extension2) => extension2.configure(extensionConfiguration)); - return Object.assign(runtimeConfig, (0, import_region_config_resolver.resolveAwsRegionExtensionConfiguration)(extensionConfiguration), (0, import_smithy_client11.resolveDefaultRuntimeConfig)(extensionConfiguration), (0, import_protocol_http12.resolveHttpHandlerRuntimeConfig)(extensionConfiguration), resolveHttpAuthRuntimeConfig(extensionConfiguration)); - }; - } -}); - -// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/SSOOIDCClient.js -var import_middleware_host_header, import_middleware_logger, import_middleware_recursion_detection, import_middleware_user_agent, import_config_resolver2, import_middleware_content_length, import_middleware_endpoint, import_middleware_retry2, import_smithy_client12, SSOOIDCClient; -var init_SSOOIDCClient = __esm({ - "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/SSOOIDCClient.js"() { - import_middleware_host_header = __toESM(require_dist_cjs20()); - import_middleware_logger = __toESM(require_dist_cjs21()); - import_middleware_recursion_detection = __toESM(require_dist_cjs22()); - import_middleware_user_agent = __toESM(require_dist_cjs37()); - import_config_resolver2 = __toESM(require_dist_cjs38()); - init_dist_es(); - init_schema3(); - import_middleware_content_length = __toESM(require_dist_cjs40()); - import_middleware_endpoint = __toESM(require_dist_cjs45()); - import_middleware_retry2 = __toESM(require_dist_cjs46()); - import_smithy_client12 = __toESM(require_dist_cjs27()); - init_httpAuthSchemeProvider(); - init_EndpointParameters(); - init_runtimeConfig(); - init_runtimeExtensions(); - SSOOIDCClient = class extends import_smithy_client12.Client { - config; - constructor(...[configuration]) { - const _config_0 = getRuntimeConfig2(configuration || {}); - super(_config_0); - this.initConfig = _config_0; - const _config_1 = resolveClientEndpointParameters(_config_0); - const _config_2 = (0, import_middleware_user_agent.resolveUserAgentConfig)(_config_1); - const _config_3 = (0, import_middleware_retry2.resolveRetryConfig)(_config_2); - const _config_4 = (0, import_config_resolver2.resolveRegionConfig)(_config_3); - const _config_5 = (0, import_middleware_host_header.resolveHostHeaderConfig)(_config_4); - const _config_6 = (0, import_middleware_endpoint.resolveEndpointConfig)(_config_5); - const _config_7 = resolveHttpAuthSchemeConfig(_config_6); - const _config_8 = resolveRuntimeExtensions(_config_7, configuration?.extensions || []); - this.config = _config_8; - this.middlewareStack.use(getSchemaSerdePlugin(this.config)); - this.middlewareStack.use((0, import_middleware_user_agent.getUserAgentPlugin)(this.config)); - this.middlewareStack.use((0, import_middleware_retry2.getRetryPlugin)(this.config)); - this.middlewareStack.use((0, import_middleware_content_length.getContentLengthPlugin)(this.config)); - this.middlewareStack.use((0, import_middleware_host_header.getHostHeaderPlugin)(this.config)); - this.middlewareStack.use((0, import_middleware_logger.getLoggerPlugin)(this.config)); - this.middlewareStack.use((0, import_middleware_recursion_detection.getRecursionDetectionPlugin)(this.config)); - this.middlewareStack.use(getHttpAuthSchemeEndpointRuleSetPlugin(this.config, { - httpAuthSchemeParametersProvider: defaultSSOOIDCHttpAuthSchemeParametersProvider, - identityProviderConfigProvider: async (config3) => new DefaultIdentityProviderConfig({ - "aws.auth#sigv4": config3.credentials - }) - })); - this.middlewareStack.use(getHttpSigningPlugin(this.config)); - } - destroy() { - super.destroy(); - } - }; - } -}); - -// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/commands/CreateTokenCommand.js -var import_middleware_endpoint2, import_smithy_client13, CreateTokenCommand; -var init_CreateTokenCommand = __esm({ - "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/commands/CreateTokenCommand.js"() { - import_middleware_endpoint2 = __toESM(require_dist_cjs45()); - import_smithy_client13 = __toESM(require_dist_cjs27()); - init_EndpointParameters(); - init_schemas_0(); - CreateTokenCommand = class extends import_smithy_client13.Command.classBuilder().ep(commonParams).m(function(Command2, cs, config3, o5) { - return [(0, import_middleware_endpoint2.getEndpointPlugin)(config3, Command2.getEndpointParameterInstructions())]; - }).s("AWSSSOOIDCService", "CreateToken", {}).n("SSOOIDCClient", "CreateTokenCommand").sc(CreateToken$).build() { - }; - } -}); - -// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/SSOOIDC.js -var import_smithy_client14, commands, SSOOIDC; -var init_SSOOIDC = __esm({ - "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/SSOOIDC.js"() { - import_smithy_client14 = __toESM(require_dist_cjs27()); - init_CreateTokenCommand(); - init_SSOOIDCClient(); - commands = { - CreateTokenCommand - }; - SSOOIDC = class extends SSOOIDCClient { - }; - (0, import_smithy_client14.createAggregatedClient)(commands, SSOOIDC); - } -}); - -// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/commands/index.js -var init_commands = __esm({ - "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/commands/index.js"() { - init_CreateTokenCommand(); - } -}); - -// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/models/enums.js -var AccessDeniedExceptionReason, InvalidRequestExceptionReason; -var init_enums = __esm({ - "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/models/enums.js"() { - AccessDeniedExceptionReason = { - KMS_ACCESS_DENIED: "KMS_AccessDeniedException" - }; - InvalidRequestExceptionReason = { - KMS_DISABLED_KEY: "KMS_DisabledException", - KMS_INVALID_KEY_USAGE: "KMS_InvalidKeyUsageException", - KMS_INVALID_STATE: "KMS_InvalidStateException", - KMS_KEY_NOT_FOUND: "KMS_NotFoundException" - }; - } -}); - -// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/models/models_0.js -var init_models_0 = __esm({ - "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/models/models_0.js"() { - } -}); - -// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/index.js -var sso_oidc_exports = {}; -__export(sso_oidc_exports, { - $Command: () => import_smithy_client13.Command, - AccessDeniedException: () => AccessDeniedException, - AccessDeniedException$: () => AccessDeniedException$, - AccessDeniedExceptionReason: () => AccessDeniedExceptionReason, - AuthorizationPendingException: () => AuthorizationPendingException, - AuthorizationPendingException$: () => AuthorizationPendingException$, - CreateToken$: () => CreateToken$, - CreateTokenCommand: () => CreateTokenCommand, - CreateTokenRequest$: () => CreateTokenRequest$, - CreateTokenResponse$: () => CreateTokenResponse$, - ExpiredTokenException: () => ExpiredTokenException, - ExpiredTokenException$: () => ExpiredTokenException$, - InternalServerException: () => InternalServerException, - InternalServerException$: () => InternalServerException$, - InvalidClientException: () => InvalidClientException, - InvalidClientException$: () => InvalidClientException$, - InvalidGrantException: () => InvalidGrantException, - InvalidGrantException$: () => InvalidGrantException$, - InvalidRequestException: () => InvalidRequestException, - InvalidRequestException$: () => InvalidRequestException$, - InvalidRequestExceptionReason: () => InvalidRequestExceptionReason, - InvalidScopeException: () => InvalidScopeException, - InvalidScopeException$: () => InvalidScopeException$, - SSOOIDC: () => SSOOIDC, - SSOOIDCClient: () => SSOOIDCClient, - SSOOIDCServiceException: () => SSOOIDCServiceException, - SSOOIDCServiceException$: () => SSOOIDCServiceException$, - SlowDownException: () => SlowDownException, - SlowDownException$: () => SlowDownException$, - UnauthorizedClientException: () => UnauthorizedClientException, - UnauthorizedClientException$: () => UnauthorizedClientException$, - UnsupportedGrantTypeException: () => UnsupportedGrantTypeException, - UnsupportedGrantTypeException$: () => UnsupportedGrantTypeException$, - __Client: () => import_smithy_client12.Client, - errorTypeRegistries: () => errorTypeRegistries -}); -var init_sso_oidc = __esm({ - "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/index.js"() { - init_SSOOIDCClient(); - init_SSOOIDC(); - init_commands(); - init_schemas_0(); - init_enums(); - init_errors3(); - init_models_0(); - init_SSOOIDCServiceException(); - } -}); - -// node_modules/.pnpm/@aws-sdk+token-providers@3.1026.0/node_modules/@aws-sdk/token-providers/dist-cjs/index.js -var require_dist_cjs56 = __commonJS({ - "node_modules/.pnpm/@aws-sdk+token-providers@3.1026.0/node_modules/@aws-sdk/token-providers/dist-cjs/index.js"(exports) { - "use strict"; - var client2 = (init_client2(), __toCommonJS(client_exports)); - var httpAuthSchemes = (init_httpAuthSchemes2(), __toCommonJS(httpAuthSchemes_exports)); - var propertyProvider = require_dist_cjs41(); - var sharedIniFileLoader = require_dist_cjs42(); - var node_fs = __require("node:fs"); - var fromEnvSigningName = ({ logger: logger4, signingName } = {}) => async () => { - logger4?.debug?.("@aws-sdk/token-providers - fromEnvSigningName"); - if (!signingName) { - throw new propertyProvider.TokenProviderError("Please pass 'signingName' to compute environment variable key", { logger: logger4 }); - } - const bearerTokenKey = httpAuthSchemes.getBearerTokenEnvKey(signingName); - if (!(bearerTokenKey in process.env)) { - throw new propertyProvider.TokenProviderError(`Token not present in '${bearerTokenKey}' environment variable`, { logger: logger4 }); - } - const token = { token: process.env[bearerTokenKey] }; - client2.setTokenFeature(token, "BEARER_SERVICE_ENV_VARS", "3"); - return token; - }; - var EXPIRE_WINDOW_MS = 5 * 60 * 1e3; - var REFRESH_MESSAGE = `To refresh this SSO session run 'aws sso login' with the corresponding profile.`; - var getSsoOidcClient = async (ssoRegion, init2 = {}, callerClientConfig) => { - const { SSOOIDCClient: SSOOIDCClient2 } = await Promise.resolve().then(() => (init_sso_oidc(), sso_oidc_exports)); - const coalesce = (prop) => init2.clientConfig?.[prop] ?? init2.parentClientConfig?.[prop] ?? callerClientConfig?.[prop]; - const ssoOidcClient = new SSOOIDCClient2(Object.assign({}, init2.clientConfig ?? {}, { - region: ssoRegion ?? init2.clientConfig?.region, - logger: coalesce("logger"), - userAgentAppId: coalesce("userAgentAppId") - })); - return ssoOidcClient; - }; - var getNewSsoOidcToken = async (ssoToken, ssoRegion, init2 = {}, callerClientConfig) => { - const { CreateTokenCommand: CreateTokenCommand2 } = await Promise.resolve().then(() => (init_sso_oidc(), sso_oidc_exports)); - const ssoOidcClient = await getSsoOidcClient(ssoRegion, init2, callerClientConfig); - return ssoOidcClient.send(new CreateTokenCommand2({ - clientId: ssoToken.clientId, - clientSecret: ssoToken.clientSecret, - refreshToken: ssoToken.refreshToken, - grantType: "refresh_token" - })); - }; - var validateTokenExpiry = (token) => { - if (token.expiration && token.expiration.getTime() < Date.now()) { - throw new propertyProvider.TokenProviderError(`Token is expired. ${REFRESH_MESSAGE}`, false); - } - }; - var validateTokenKey = (key, value, forRefresh = false) => { - if (typeof value === "undefined") { - throw new propertyProvider.TokenProviderError(`Value not present for '${key}' in SSO Token${forRefresh ? ". Cannot refresh" : ""}. ${REFRESH_MESSAGE}`, false); - } - }; - var { writeFile } = node_fs.promises; - var writeSSOTokenToFile = (id, ssoToken) => { - const tokenFilepath = sharedIniFileLoader.getSSOTokenFilepath(id); - const tokenString = JSON.stringify(ssoToken, null, 2); - return writeFile(tokenFilepath, tokenString); - }; - var lastRefreshAttemptTime = /* @__PURE__ */ new Date(0); - var fromSso = (init2 = {}) => async ({ callerClientConfig } = {}) => { - init2.logger?.debug("@aws-sdk/token-providers - fromSso"); - const profiles = await sharedIniFileLoader.parseKnownFiles(init2); - const profileName = sharedIniFileLoader.getProfileName({ - profile: init2.profile ?? callerClientConfig?.profile - }); - const profile = profiles[profileName]; - if (!profile) { - throw new propertyProvider.TokenProviderError(`Profile '${profileName}' could not be found in shared credentials file.`, false); - } else if (!profile["sso_session"]) { - throw new propertyProvider.TokenProviderError(`Profile '${profileName}' is missing required property 'sso_session'.`); - } - const ssoSessionName = profile["sso_session"]; - const ssoSessions = await sharedIniFileLoader.loadSsoSessionData(init2); - const ssoSession = ssoSessions[ssoSessionName]; - if (!ssoSession) { - throw new propertyProvider.TokenProviderError(`Sso session '${ssoSessionName}' could not be found in shared credentials file.`, false); - } - for (const ssoSessionRequiredKey of ["sso_start_url", "sso_region"]) { - if (!ssoSession[ssoSessionRequiredKey]) { - throw new propertyProvider.TokenProviderError(`Sso session '${ssoSessionName}' is missing required property '${ssoSessionRequiredKey}'.`, false); - } - } - ssoSession["sso_start_url"]; - const ssoRegion = ssoSession["sso_region"]; - let ssoToken; - try { - ssoToken = await sharedIniFileLoader.getSSOTokenFromFile(ssoSessionName); - } catch (e5) { - throw new propertyProvider.TokenProviderError(`The SSO session token associated with profile=${profileName} was not found or is invalid. ${REFRESH_MESSAGE}`, false); - } - validateTokenKey("accessToken", ssoToken.accessToken); - validateTokenKey("expiresAt", ssoToken.expiresAt); - const { accessToken, expiresAt } = ssoToken; - const existingToken = { token: accessToken, expiration: new Date(expiresAt) }; - if (existingToken.expiration.getTime() - Date.now() > EXPIRE_WINDOW_MS) { - return existingToken; - } - if (Date.now() - lastRefreshAttemptTime.getTime() < 30 * 1e3) { - validateTokenExpiry(existingToken); - return existingToken; - } - validateTokenKey("clientId", ssoToken.clientId, true); - validateTokenKey("clientSecret", ssoToken.clientSecret, true); - validateTokenKey("refreshToken", ssoToken.refreshToken, true); - try { - lastRefreshAttemptTime.setTime(Date.now()); - const newSsoOidcToken = await getNewSsoOidcToken(ssoToken, ssoRegion, init2, callerClientConfig); - validateTokenKey("accessToken", newSsoOidcToken.accessToken); - validateTokenKey("expiresIn", newSsoOidcToken.expiresIn); - const newTokenExpiration = new Date(Date.now() + newSsoOidcToken.expiresIn * 1e3); - try { - await writeSSOTokenToFile(ssoSessionName, { - ...ssoToken, - accessToken: newSsoOidcToken.accessToken, - expiresAt: newTokenExpiration.toISOString(), - refreshToken: newSsoOidcToken.refreshToken - }); - } catch (error50) { - } - return { - token: newSsoOidcToken.accessToken, - expiration: newTokenExpiration - }; - } catch (error50) { - validateTokenExpiry(existingToken); - return existingToken; - } - }; - var fromStatic = ({ token, logger: logger4 }) => async () => { - logger4?.debug("@aws-sdk/token-providers - fromStatic"); - if (!token || !token.token) { - throw new propertyProvider.TokenProviderError(`Please pass a valid token to fromStatic`, false); - } - return token; - }; - var nodeProvider = (init2 = {}) => propertyProvider.memoize(propertyProvider.chain(fromSso(init2), async () => { - throw new propertyProvider.TokenProviderError("Could not load token from any providers", false); - }), (token) => token.expiration !== void 0 && token.expiration.getTime() - Date.now() < 3e5, (token) => token.expiration !== void 0); - exports.fromEnvSigningName = fromEnvSigningName; - exports.fromSso = fromSso; - exports.fromStatic = fromStatic; - exports.nodeProvider = nodeProvider; - } -}); - -// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/auth/httpAuthSchemeProvider.js -function createAwsAuthSigv4HttpAuthOption2(authParameters) { - return { - schemeId: "aws.auth#sigv4", - signingProperties: { - name: "awsssoportal", - region: authParameters.region - }, - propertiesExtractor: (config3, context) => ({ - signingProperties: { - config: config3, - context - } - }) - }; -} -function createSmithyApiNoAuthHttpAuthOption2(authParameters) { - return { - schemeId: "smithy.api#noAuth" - }; -} -var import_util_middleware7, defaultSSOHttpAuthSchemeParametersProvider, defaultSSOHttpAuthSchemeProvider, resolveHttpAuthSchemeConfig2; -var init_httpAuthSchemeProvider2 = __esm({ - "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/auth/httpAuthSchemeProvider.js"() { - init_httpAuthSchemes2(); - import_util_middleware7 = __toESM(require_dist_cjs18()); - defaultSSOHttpAuthSchemeParametersProvider = async (config3, context, input) => { - return { - operation: (0, import_util_middleware7.getSmithyContext)(context).operation, - region: await (0, import_util_middleware7.normalizeProvider)(config3.region)() || (() => { - throw new Error("expected `region` to be configured for `aws.auth#sigv4`"); - })() - }; - }; - defaultSSOHttpAuthSchemeProvider = (authParameters) => { - const options = []; - switch (authParameters.operation) { - case "GetRoleCredentials": { - options.push(createSmithyApiNoAuthHttpAuthOption2(authParameters)); - break; - } - default: { - options.push(createAwsAuthSigv4HttpAuthOption2(authParameters)); - } - } - return options; - }; - resolveHttpAuthSchemeConfig2 = (config3) => { - const config_0 = resolveAwsSdkSigV4Config(config3); - return Object.assign(config_0, { - authSchemePreference: (0, import_util_middleware7.normalizeProvider)(config3.authSchemePreference ?? []) - }); - }; - } -}); - -// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/endpoint/EndpointParameters.js -var resolveClientEndpointParameters2, commonParams2; -var init_EndpointParameters2 = __esm({ - "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/endpoint/EndpointParameters.js"() { - resolveClientEndpointParameters2 = (options) => { - return Object.assign(options, { - useDualstackEndpoint: options.useDualstackEndpoint ?? false, - useFipsEndpoint: options.useFipsEndpoint ?? false, - defaultSigningName: "awsssoportal" - }); - }; - commonParams2 = { - UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, - Endpoint: { type: "builtInParams", name: "endpoint" }, - Region: { type: "builtInParams", name: "region" }, - UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" } - }; - } -}); - -// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/endpoint/ruleset.js -var u2, v2, w2, x2, a2, b3, c2, d2, e2, f2, g2, h2, i2, j2, k2, l2, m2, n2, o2, p2, q2, r2, s2, t2, _data2, ruleSet2; -var init_ruleset2 = __esm({ - "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/endpoint/ruleset.js"() { - u2 = "required"; - v2 = "fn"; - w2 = "argv"; - x2 = "ref"; - a2 = true; - b3 = "isSet"; - c2 = "booleanEquals"; - d2 = "error"; - e2 = "endpoint"; - f2 = "tree"; - g2 = "PartitionResult"; - h2 = "getAttr"; - i2 = { [u2]: false, type: "string" }; - j2 = { [u2]: true, default: false, type: "boolean" }; - k2 = { [x2]: "Endpoint" }; - l2 = { [v2]: c2, [w2]: [{ [x2]: "UseFIPS" }, true] }; - m2 = { [v2]: c2, [w2]: [{ [x2]: "UseDualStack" }, true] }; - n2 = {}; - o2 = { [v2]: h2, [w2]: [{ [x2]: g2 }, "supportsFIPS"] }; - p2 = { [x2]: g2 }; - q2 = { [v2]: c2, [w2]: [true, { [v2]: h2, [w2]: [p2, "supportsDualStack"] }] }; - r2 = [l2]; - s2 = [m2]; - t2 = [{ [x2]: "Region" }]; - _data2 = { - version: "1.0", - parameters: { Region: i2, UseDualStack: j2, UseFIPS: j2, Endpoint: i2 }, - rules: [ - { - conditions: [{ [v2]: b3, [w2]: [k2] }], - rules: [ - { conditions: r2, error: "Invalid Configuration: FIPS and custom endpoint are not supported", type: d2 }, - { conditions: s2, error: "Invalid Configuration: Dualstack and custom endpoint are not supported", type: d2 }, - { endpoint: { url: k2, properties: n2, headers: n2 }, type: e2 } - ], - type: f2 - }, - { - conditions: [{ [v2]: b3, [w2]: t2 }], - rules: [ - { - conditions: [{ [v2]: "aws.partition", [w2]: t2, assign: g2 }], - rules: [ - { - conditions: [l2, m2], - rules: [ - { - conditions: [{ [v2]: c2, [w2]: [a2, o2] }, q2], - rules: [ - { - endpoint: { - url: "https://portal.sso-fips.{Region}.{PartitionResult#dualStackDnsSuffix}", - properties: n2, - headers: n2 - }, - type: e2 - } - ], - type: f2 - }, - { error: "FIPS and DualStack are enabled, but this partition does not support one or both", type: d2 } - ], - type: f2 - }, - { - conditions: r2, - rules: [ - { - conditions: [{ [v2]: c2, [w2]: [o2, a2] }], - rules: [ - { - conditions: [{ [v2]: "stringEquals", [w2]: [{ [v2]: h2, [w2]: [p2, "name"] }, "aws-us-gov"] }], - endpoint: { url: "https://portal.sso.{Region}.amazonaws.com", properties: n2, headers: n2 }, - type: e2 - }, - { - endpoint: { - url: "https://portal.sso-fips.{Region}.{PartitionResult#dnsSuffix}", - properties: n2, - headers: n2 - }, - type: e2 - } - ], - type: f2 - }, - { error: "FIPS is enabled but this partition does not support FIPS", type: d2 } - ], - type: f2 - }, - { - conditions: s2, - rules: [ - { - conditions: [q2], - rules: [ - { - endpoint: { - url: "https://portal.sso.{Region}.{PartitionResult#dualStackDnsSuffix}", - properties: n2, - headers: n2 - }, - type: e2 - } - ], - type: f2 - }, - { error: "DualStack is enabled but this partition does not support DualStack", type: d2 } - ], - type: f2 - }, - { - endpoint: { url: "https://portal.sso.{Region}.{PartitionResult#dnsSuffix}", properties: n2, headers: n2 }, - type: e2 - } - ], - type: f2 - } - ], - type: f2 - }, - { error: "Invalid Configuration: Missing Region", type: d2 } - ] - }; - ruleSet2 = _data2; - } -}); - -// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/endpoint/endpointResolver.js -var import_util_endpoints3, import_util_endpoints4, cache2, defaultEndpointResolver2; -var init_endpointResolver2 = __esm({ - "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/endpoint/endpointResolver.js"() { - import_util_endpoints3 = __toESM(require_dist_cjs34()); - import_util_endpoints4 = __toESM(require_dist_cjs33()); - init_ruleset2(); - cache2 = new import_util_endpoints4.EndpointCache({ - size: 50, - params: ["Endpoint", "Region", "UseDualStack", "UseFIPS"] - }); - defaultEndpointResolver2 = (endpointParams, context = {}) => { - return cache2.get(endpointParams, () => (0, import_util_endpoints4.resolveEndpoint)(ruleSet2, { - endpointParams, - logger: context.logger - })); - }; - import_util_endpoints4.customEndpointFunctions.aws = import_util_endpoints3.awsEndpointFunctions; - } -}); - -// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/models/SSOServiceException.js -var import_smithy_client15, SSOServiceException; -var init_SSOServiceException = __esm({ - "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/models/SSOServiceException.js"() { - import_smithy_client15 = __toESM(require_dist_cjs27()); - SSOServiceException = class _SSOServiceException extends import_smithy_client15.ServiceException { - constructor(options) { - super(options); - Object.setPrototypeOf(this, _SSOServiceException.prototype); - } - }; - } -}); - -// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/models/errors.js -var InvalidRequestException2, ResourceNotFoundException, TooManyRequestsException, UnauthorizedException; -var init_errors4 = __esm({ - "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/models/errors.js"() { - init_SSOServiceException(); - InvalidRequestException2 = class _InvalidRequestException extends SSOServiceException { - name = "InvalidRequestException"; - $fault = "client"; - constructor(opts) { - super({ - name: "InvalidRequestException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _InvalidRequestException.prototype); - } - }; - ResourceNotFoundException = class _ResourceNotFoundException extends SSOServiceException { - name = "ResourceNotFoundException"; - $fault = "client"; - constructor(opts) { - super({ - name: "ResourceNotFoundException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _ResourceNotFoundException.prototype); - } - }; - TooManyRequestsException = class _TooManyRequestsException extends SSOServiceException { - name = "TooManyRequestsException"; - $fault = "client"; - constructor(opts) { - super({ - name: "TooManyRequestsException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _TooManyRequestsException.prototype); - } - }; - UnauthorizedException = class _UnauthorizedException extends SSOServiceException { - name = "UnauthorizedException"; - $fault = "client"; - constructor(opts) { - super({ - name: "UnauthorizedException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _UnauthorizedException.prototype); - } - }; - } -}); - -// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/schemas/schemas_0.js -var _ATT, _GRC, _GRCR, _GRCRe, _IRE2, _RC, _RNFE, _SAKT, _STT, _TMRE, _UE, _aI, _aKI, _aT2, _ai, _c2, _e2, _ex, _h2, _hE2, _hH, _hQ, _m, _rC, _rN, _rn, _s2, _sAK, _sT, _xasbt, n02, _s_registry2, SSOServiceException$, n0_registry2, InvalidRequestException$2, ResourceNotFoundException$, TooManyRequestsException$, UnauthorizedException$, errorTypeRegistries2, AccessTokenType, SecretAccessKeyType, SessionTokenType, GetRoleCredentialsRequest$, GetRoleCredentialsResponse$, RoleCredentials$, GetRoleCredentials$; -var init_schemas_02 = __esm({ - "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/schemas/schemas_0.js"() { - init_schema3(); - init_errors4(); - init_SSOServiceException(); - _ATT = "AccessTokenType"; - _GRC = "GetRoleCredentials"; - _GRCR = "GetRoleCredentialsRequest"; - _GRCRe = "GetRoleCredentialsResponse"; - _IRE2 = "InvalidRequestException"; - _RC = "RoleCredentials"; - _RNFE = "ResourceNotFoundException"; - _SAKT = "SecretAccessKeyType"; - _STT = "SessionTokenType"; - _TMRE = "TooManyRequestsException"; - _UE = "UnauthorizedException"; - _aI = "accountId"; - _aKI = "accessKeyId"; - _aT2 = "accessToken"; - _ai = "account_id"; - _c2 = "client"; - _e2 = "error"; - _ex = "expiration"; - _h2 = "http"; - _hE2 = "httpError"; - _hH = "httpHeader"; - _hQ = "httpQuery"; - _m = "message"; - _rC = "roleCredentials"; - _rN = "roleName"; - _rn = "role_name"; - _s2 = "smithy.ts.sdk.synthetic.com.amazonaws.sso"; - _sAK = "secretAccessKey"; - _sT = "sessionToken"; - _xasbt = "x-amz-sso_bearer_token"; - n02 = "com.amazonaws.sso"; - _s_registry2 = TypeRegistry.for(_s2); - SSOServiceException$ = [-3, _s2, "SSOServiceException", 0, [], []]; - _s_registry2.registerError(SSOServiceException$, SSOServiceException); - n0_registry2 = TypeRegistry.for(n02); - InvalidRequestException$2 = [-3, n02, _IRE2, { [_e2]: _c2, [_hE2]: 400 }, [_m], [0]]; - n0_registry2.registerError(InvalidRequestException$2, InvalidRequestException2); - ResourceNotFoundException$ = [-3, n02, _RNFE, { [_e2]: _c2, [_hE2]: 404 }, [_m], [0]]; - n0_registry2.registerError(ResourceNotFoundException$, ResourceNotFoundException); - TooManyRequestsException$ = [-3, n02, _TMRE, { [_e2]: _c2, [_hE2]: 429 }, [_m], [0]]; - n0_registry2.registerError(TooManyRequestsException$, TooManyRequestsException); - UnauthorizedException$ = [-3, n02, _UE, { [_e2]: _c2, [_hE2]: 401 }, [_m], [0]]; - n0_registry2.registerError(UnauthorizedException$, UnauthorizedException); - errorTypeRegistries2 = [_s_registry2, n0_registry2]; - AccessTokenType = [0, n02, _ATT, 8, 0]; - SecretAccessKeyType = [0, n02, _SAKT, 8, 0]; - SessionTokenType = [0, n02, _STT, 8, 0]; - GetRoleCredentialsRequest$ = [ - 3, - n02, - _GRCR, - 0, - [_rN, _aI, _aT2], - [ - [0, { [_hQ]: _rn }], - [0, { [_hQ]: _ai }], - [() => AccessTokenType, { [_hH]: _xasbt }] - ], - 3 - ]; - GetRoleCredentialsResponse$ = [ - 3, - n02, - _GRCRe, - 0, - [_rC], - [[() => RoleCredentials$, 0]] - ]; - RoleCredentials$ = [ - 3, - n02, - _RC, - 0, - [_aKI, _sAK, _sT, _ex], - [0, [() => SecretAccessKeyType, 0], [() => SessionTokenType, 0], 1] - ]; - GetRoleCredentials$ = [ - 9, - n02, - _GRC, - { [_h2]: ["GET", "/federation/credentials", 200] }, - () => GetRoleCredentialsRequest$, - () => GetRoleCredentialsResponse$ - ]; - } -}); - -// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/runtimeConfig.shared.js -var import_smithy_client16, import_url_parser3, import_util_base649, import_util_utf89, getRuntimeConfig3; -var init_runtimeConfig_shared2 = __esm({ - "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/runtimeConfig.shared.js"() { - init_httpAuthSchemes2(); - init_protocols2(); - init_dist_es(); - import_smithy_client16 = __toESM(require_dist_cjs27()); - import_url_parser3 = __toESM(require_dist_cjs25()); - import_util_base649 = __toESM(require_dist_cjs7()); - import_util_utf89 = __toESM(require_dist_cjs6()); - init_httpAuthSchemeProvider2(); - init_endpointResolver2(); - init_schemas_02(); - getRuntimeConfig3 = (config3) => { - return { - apiVersion: "2019-06-10", - base64Decoder: config3?.base64Decoder ?? import_util_base649.fromBase64, - base64Encoder: config3?.base64Encoder ?? import_util_base649.toBase64, - disableHostPrefix: config3?.disableHostPrefix ?? false, - endpointProvider: config3?.endpointProvider ?? defaultEndpointResolver2, - extensions: config3?.extensions ?? [], - httpAuthSchemeProvider: config3?.httpAuthSchemeProvider ?? defaultSSOHttpAuthSchemeProvider, - httpAuthSchemes: config3?.httpAuthSchemes ?? [ - { - schemeId: "aws.auth#sigv4", - identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"), - signer: new AwsSdkSigV4Signer() - }, - { - schemeId: "smithy.api#noAuth", - identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})), - signer: new NoAuthSigner() - } - ], - logger: config3?.logger ?? new import_smithy_client16.NoOpLogger(), - protocol: config3?.protocol ?? AwsRestJsonProtocol, - protocolSettings: config3?.protocolSettings ?? { - defaultNamespace: "com.amazonaws.sso", - errorTypeRegistries: errorTypeRegistries2, - version: "2019-06-10", - serviceTarget: "SWBPortalService" - }, - serviceId: config3?.serviceId ?? "SSO", - urlParser: config3?.urlParser ?? import_url_parser3.parseUrl, - utf8Decoder: config3?.utf8Decoder ?? import_util_utf89.fromUtf8, - utf8Encoder: config3?.utf8Encoder ?? import_util_utf89.toUtf8 - }; - }; - } -}); - -// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/runtimeConfig.js -var import_util_user_agent_node2, import_config_resolver3, import_hash_node2, import_middleware_retry3, import_node_config_provider2, import_node_http_handler2, import_smithy_client17, import_util_body_length_node2, import_util_defaults_mode_node2, import_util_retry2, getRuntimeConfig4; -var init_runtimeConfig2 = __esm({ - "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/runtimeConfig.js"() { - init_package(); - init_client2(); - init_httpAuthSchemes2(); - import_util_user_agent_node2 = __toESM(require_dist_cjs51()); - import_config_resolver3 = __toESM(require_dist_cjs38()); - import_hash_node2 = __toESM(require_dist_cjs52()); - import_middleware_retry3 = __toESM(require_dist_cjs46()); - import_node_config_provider2 = __toESM(require_dist_cjs43()); - import_node_http_handler2 = __toESM(require_dist_cjs10()); - import_smithy_client17 = __toESM(require_dist_cjs27()); - import_util_body_length_node2 = __toESM(require_dist_cjs53()); - import_util_defaults_mode_node2 = __toESM(require_dist_cjs54()); - import_util_retry2 = __toESM(require_dist_cjs36()); - init_runtimeConfig_shared2(); - getRuntimeConfig4 = (config3) => { - (0, import_smithy_client17.emitWarningIfUnsupportedVersion)(process.version); - const defaultsMode = (0, import_util_defaults_mode_node2.resolveDefaultsModeConfig)(config3); - const defaultConfigProvider = () => defaultsMode().then(import_smithy_client17.loadConfigsForDefaultMode); - const clientSharedValues = getRuntimeConfig3(config3); - emitWarningIfUnsupportedVersion(process.version); - const loaderConfig = { - profile: config3?.profile, - logger: clientSharedValues.logger - }; - return { - ...clientSharedValues, - ...config3, - runtime: "node", - defaultsMode, - authSchemePreference: config3?.authSchemePreference ?? (0, import_node_config_provider2.loadConfig)(NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig), - bodyLengthChecker: config3?.bodyLengthChecker ?? import_util_body_length_node2.calculateBodyLength, - defaultUserAgentProvider: config3?.defaultUserAgentProvider ?? (0, import_util_user_agent_node2.createDefaultUserAgentProvider)({ serviceId: clientSharedValues.serviceId, clientVersion: package_default.version }), - maxAttempts: config3?.maxAttempts ?? (0, import_node_config_provider2.loadConfig)(import_middleware_retry3.NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config3), - region: config3?.region ?? (0, import_node_config_provider2.loadConfig)(import_config_resolver3.NODE_REGION_CONFIG_OPTIONS, { ...import_config_resolver3.NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }), - requestHandler: import_node_http_handler2.NodeHttpHandler.create(config3?.requestHandler ?? defaultConfigProvider), - retryMode: config3?.retryMode ?? (0, import_node_config_provider2.loadConfig)({ - ...import_middleware_retry3.NODE_RETRY_MODE_CONFIG_OPTIONS, - default: async () => (await defaultConfigProvider()).retryMode || import_util_retry2.DEFAULT_RETRY_MODE - }, config3), - sha256: config3?.sha256 ?? import_hash_node2.Hash.bind(null, "sha256"), - streamCollector: config3?.streamCollector ?? import_node_http_handler2.streamCollector, - useDualstackEndpoint: config3?.useDualstackEndpoint ?? (0, import_node_config_provider2.loadConfig)(import_config_resolver3.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig), - useFipsEndpoint: config3?.useFipsEndpoint ?? (0, import_node_config_provider2.loadConfig)(import_config_resolver3.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig), - userAgentAppId: config3?.userAgentAppId ?? (0, import_node_config_provider2.loadConfig)(import_util_user_agent_node2.NODE_APP_ID_CONFIG_OPTIONS, loaderConfig) - }; - }; - } -}); - -// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/auth/httpAuthExtensionConfiguration.js -var getHttpAuthExtensionConfiguration2, resolveHttpAuthRuntimeConfig2; -var init_httpAuthExtensionConfiguration2 = __esm({ - "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/auth/httpAuthExtensionConfiguration.js"() { - getHttpAuthExtensionConfiguration2 = (runtimeConfig) => { - const _httpAuthSchemes = runtimeConfig.httpAuthSchemes; - let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider; - let _credentials = runtimeConfig.credentials; - return { - setHttpAuthScheme(httpAuthScheme) { - const index2 = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId); - if (index2 === -1) { - _httpAuthSchemes.push(httpAuthScheme); - } else { - _httpAuthSchemes.splice(index2, 1, httpAuthScheme); - } - }, - httpAuthSchemes() { - return _httpAuthSchemes; - }, - setHttpAuthSchemeProvider(httpAuthSchemeProvider) { - _httpAuthSchemeProvider = httpAuthSchemeProvider; - }, - httpAuthSchemeProvider() { - return _httpAuthSchemeProvider; - }, - setCredentials(credentials) { - _credentials = credentials; - }, - credentials() { - return _credentials; - } - }; - }; - resolveHttpAuthRuntimeConfig2 = (config3) => { - return { - httpAuthSchemes: config3.httpAuthSchemes(), - httpAuthSchemeProvider: config3.httpAuthSchemeProvider(), - credentials: config3.credentials() - }; - }; - } -}); - -// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/runtimeExtensions.js -var import_region_config_resolver2, import_protocol_http13, import_smithy_client18, resolveRuntimeExtensions2; -var init_runtimeExtensions2 = __esm({ - "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/runtimeExtensions.js"() { - import_region_config_resolver2 = __toESM(require_dist_cjs55()); - import_protocol_http13 = __toESM(require_dist_cjs2()); - import_smithy_client18 = __toESM(require_dist_cjs27()); - init_httpAuthExtensionConfiguration2(); - resolveRuntimeExtensions2 = (runtimeConfig, extensions) => { - const extensionConfiguration = Object.assign((0, import_region_config_resolver2.getAwsRegionExtensionConfiguration)(runtimeConfig), (0, import_smithy_client18.getDefaultExtensionConfiguration)(runtimeConfig), (0, import_protocol_http13.getHttpHandlerExtensionConfiguration)(runtimeConfig), getHttpAuthExtensionConfiguration2(runtimeConfig)); - extensions.forEach((extension2) => extension2.configure(extensionConfiguration)); - return Object.assign(runtimeConfig, (0, import_region_config_resolver2.resolveAwsRegionExtensionConfiguration)(extensionConfiguration), (0, import_smithy_client18.resolveDefaultRuntimeConfig)(extensionConfiguration), (0, import_protocol_http13.resolveHttpHandlerRuntimeConfig)(extensionConfiguration), resolveHttpAuthRuntimeConfig2(extensionConfiguration)); - }; - } -}); - -// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/SSOClient.js -var import_middleware_host_header2, import_middleware_logger2, import_middleware_recursion_detection2, import_middleware_user_agent2, import_config_resolver4, import_middleware_content_length2, import_middleware_endpoint3, import_middleware_retry4, import_smithy_client19, SSOClient; -var init_SSOClient = __esm({ - "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/SSOClient.js"() { - import_middleware_host_header2 = __toESM(require_dist_cjs20()); - import_middleware_logger2 = __toESM(require_dist_cjs21()); - import_middleware_recursion_detection2 = __toESM(require_dist_cjs22()); - import_middleware_user_agent2 = __toESM(require_dist_cjs37()); - import_config_resolver4 = __toESM(require_dist_cjs38()); - init_dist_es(); - init_schema3(); - import_middleware_content_length2 = __toESM(require_dist_cjs40()); - import_middleware_endpoint3 = __toESM(require_dist_cjs45()); - import_middleware_retry4 = __toESM(require_dist_cjs46()); - import_smithy_client19 = __toESM(require_dist_cjs27()); - init_httpAuthSchemeProvider2(); - init_EndpointParameters2(); - init_runtimeConfig2(); - init_runtimeExtensions2(); - SSOClient = class extends import_smithy_client19.Client { - config; - constructor(...[configuration]) { - const _config_0 = getRuntimeConfig4(configuration || {}); - super(_config_0); - this.initConfig = _config_0; - const _config_1 = resolveClientEndpointParameters2(_config_0); - const _config_2 = (0, import_middleware_user_agent2.resolveUserAgentConfig)(_config_1); - const _config_3 = (0, import_middleware_retry4.resolveRetryConfig)(_config_2); - const _config_4 = (0, import_config_resolver4.resolveRegionConfig)(_config_3); - const _config_5 = (0, import_middleware_host_header2.resolveHostHeaderConfig)(_config_4); - const _config_6 = (0, import_middleware_endpoint3.resolveEndpointConfig)(_config_5); - const _config_7 = resolveHttpAuthSchemeConfig2(_config_6); - const _config_8 = resolveRuntimeExtensions2(_config_7, configuration?.extensions || []); - this.config = _config_8; - this.middlewareStack.use(getSchemaSerdePlugin(this.config)); - this.middlewareStack.use((0, import_middleware_user_agent2.getUserAgentPlugin)(this.config)); - this.middlewareStack.use((0, import_middleware_retry4.getRetryPlugin)(this.config)); - this.middlewareStack.use((0, import_middleware_content_length2.getContentLengthPlugin)(this.config)); - this.middlewareStack.use((0, import_middleware_host_header2.getHostHeaderPlugin)(this.config)); - this.middlewareStack.use((0, import_middleware_logger2.getLoggerPlugin)(this.config)); - this.middlewareStack.use((0, import_middleware_recursion_detection2.getRecursionDetectionPlugin)(this.config)); - this.middlewareStack.use(getHttpAuthSchemeEndpointRuleSetPlugin(this.config, { - httpAuthSchemeParametersProvider: defaultSSOHttpAuthSchemeParametersProvider, - identityProviderConfigProvider: async (config3) => new DefaultIdentityProviderConfig({ - "aws.auth#sigv4": config3.credentials - }) - })); - this.middlewareStack.use(getHttpSigningPlugin(this.config)); - } - destroy() { - super.destroy(); - } - }; - } -}); - -// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/commands/GetRoleCredentialsCommand.js -var import_middleware_endpoint4, import_smithy_client20, GetRoleCredentialsCommand; -var init_GetRoleCredentialsCommand = __esm({ - "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/commands/GetRoleCredentialsCommand.js"() { - import_middleware_endpoint4 = __toESM(require_dist_cjs45()); - import_smithy_client20 = __toESM(require_dist_cjs27()); - init_EndpointParameters2(); - init_schemas_02(); - GetRoleCredentialsCommand = class extends import_smithy_client20.Command.classBuilder().ep(commonParams2).m(function(Command2, cs, config3, o5) { - return [(0, import_middleware_endpoint4.getEndpointPlugin)(config3, Command2.getEndpointParameterInstructions())]; - }).s("SWBPortalService", "GetRoleCredentials", {}).n("SSOClient", "GetRoleCredentialsCommand").sc(GetRoleCredentials$).build() { - }; - } -}); - -// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/SSO.js -var import_smithy_client21, commands2, SSO; -var init_SSO = __esm({ - "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/SSO.js"() { - import_smithy_client21 = __toESM(require_dist_cjs27()); - init_GetRoleCredentialsCommand(); - init_SSOClient(); - commands2 = { - GetRoleCredentialsCommand - }; - SSO = class extends SSOClient { - }; - (0, import_smithy_client21.createAggregatedClient)(commands2, SSO); - } -}); - -// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/commands/index.js -var init_commands2 = __esm({ - "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/commands/index.js"() { - init_GetRoleCredentialsCommand(); - } -}); - -// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/models/models_0.js -var init_models_02 = __esm({ - "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/models/models_0.js"() { - } -}); - -// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/index.js -var sso_exports = {}; -__export(sso_exports, { - $Command: () => import_smithy_client20.Command, - GetRoleCredentials$: () => GetRoleCredentials$, - GetRoleCredentialsCommand: () => GetRoleCredentialsCommand, - GetRoleCredentialsRequest$: () => GetRoleCredentialsRequest$, - GetRoleCredentialsResponse$: () => GetRoleCredentialsResponse$, - InvalidRequestException: () => InvalidRequestException2, - InvalidRequestException$: () => InvalidRequestException$2, - ResourceNotFoundException: () => ResourceNotFoundException, - ResourceNotFoundException$: () => ResourceNotFoundException$, - RoleCredentials$: () => RoleCredentials$, - SSO: () => SSO, - SSOClient: () => SSOClient, - SSOServiceException: () => SSOServiceException, - SSOServiceException$: () => SSOServiceException$, - TooManyRequestsException: () => TooManyRequestsException, - TooManyRequestsException$: () => TooManyRequestsException$, - UnauthorizedException: () => UnauthorizedException, - UnauthorizedException$: () => UnauthorizedException$, - __Client: () => import_smithy_client19.Client, - errorTypeRegistries: () => errorTypeRegistries2 -}); -var init_sso = __esm({ - "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/index.js"() { - init_SSOClient(); - init_SSO(); - init_commands2(); - init_schemas_02(); - init_errors4(); - init_models_02(); - init_SSOServiceException(); - } -}); - -// node_modules/.pnpm/@aws-sdk+credential-provider-sso@3.972.29/node_modules/@aws-sdk/credential-provider-sso/dist-cjs/loadSso-BKDNrsal.js -var require_loadSso_BKDNrsal = __commonJS({ - "node_modules/.pnpm/@aws-sdk+credential-provider-sso@3.972.29/node_modules/@aws-sdk/credential-provider-sso/dist-cjs/loadSso-BKDNrsal.js"(exports) { - "use strict"; - var sso = (init_sso(), __toCommonJS(sso_exports)); - exports.GetRoleCredentialsCommand = sso.GetRoleCredentialsCommand; - exports.SSOClient = sso.SSOClient; - } -}); - -// node_modules/.pnpm/@aws-sdk+credential-provider-sso@3.972.29/node_modules/@aws-sdk/credential-provider-sso/dist-cjs/index.js -var require_dist_cjs57 = __commonJS({ - "node_modules/.pnpm/@aws-sdk+credential-provider-sso@3.972.29/node_modules/@aws-sdk/credential-provider-sso/dist-cjs/index.js"(exports) { - "use strict"; - var propertyProvider = require_dist_cjs41(); - var sharedIniFileLoader = require_dist_cjs42(); - var client2 = (init_client2(), __toCommonJS(client_exports)); - var tokenProviders = require_dist_cjs56(); - var isSsoProfile = (arg) => arg && (typeof arg.sso_start_url === "string" || typeof arg.sso_account_id === "string" || typeof arg.sso_session === "string" || typeof arg.sso_region === "string" || typeof arg.sso_role_name === "string"); - var SHOULD_FAIL_CREDENTIAL_CHAIN = false; - var resolveSSOCredentials = async ({ ssoStartUrl, ssoSession, ssoAccountId, ssoRegion, ssoRoleName, ssoClient, clientConfig, parentClientConfig, callerClientConfig, profile, filepath, configFilepath, ignoreCache, logger: logger4 }) => { - let token; - const refreshMessage = `To refresh this SSO session run aws sso login with the corresponding profile.`; - if (ssoSession) { - try { - const _token = await tokenProviders.fromSso({ - profile, - filepath, - configFilepath, - ignoreCache - })(); - token = { - accessToken: _token.token, - expiresAt: new Date(_token.expiration).toISOString() - }; - } catch (e5) { - throw new propertyProvider.CredentialsProviderError(e5.message, { - tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN, - logger: logger4 - }); - } - } else { - try { - token = await sharedIniFileLoader.getSSOTokenFromFile(ssoStartUrl); - } catch (e5) { - throw new propertyProvider.CredentialsProviderError(`The SSO session associated with this profile is invalid. ${refreshMessage}`, { - tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN, - logger: logger4 - }); - } - } - if (new Date(token.expiresAt).getTime() - Date.now() <= 0) { - throw new propertyProvider.CredentialsProviderError(`The SSO session associated with this profile has expired. ${refreshMessage}`, { - tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN, - logger: logger4 - }); - } - const { accessToken } = token; - const { SSOClient: SSOClient2, GetRoleCredentialsCommand: GetRoleCredentialsCommand2 } = await Promise.resolve().then(function() { - return require_loadSso_BKDNrsal(); - }); - const sso = ssoClient || new SSOClient2(Object.assign({}, clientConfig ?? {}, { - logger: clientConfig?.logger ?? callerClientConfig?.logger ?? parentClientConfig?.logger, - region: clientConfig?.region ?? ssoRegion, - userAgentAppId: clientConfig?.userAgentAppId ?? callerClientConfig?.userAgentAppId ?? parentClientConfig?.userAgentAppId - })); - let ssoResp; - try { - ssoResp = await sso.send(new GetRoleCredentialsCommand2({ - accountId: ssoAccountId, - roleName: ssoRoleName, - accessToken - })); - } catch (e5) { - throw new propertyProvider.CredentialsProviderError(e5, { - tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN, - logger: logger4 - }); - } - const { roleCredentials: { accessKeyId, secretAccessKey, sessionToken, expiration, credentialScope, accountId } = {} } = ssoResp; - if (!accessKeyId || !secretAccessKey || !sessionToken || !expiration) { - throw new propertyProvider.CredentialsProviderError("SSO returns an invalid temporary credential.", { - tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN, - logger: logger4 - }); - } - const credentials = { - accessKeyId, - secretAccessKey, - sessionToken, - expiration: new Date(expiration), - ...credentialScope && { credentialScope }, - ...accountId && { accountId } - }; - if (ssoSession) { - client2.setCredentialFeature(credentials, "CREDENTIALS_SSO", "s"); - } else { - client2.setCredentialFeature(credentials, "CREDENTIALS_SSO_LEGACY", "u"); - } - return credentials; - }; - var validateSsoProfile = (profile, logger4) => { - const { sso_start_url, sso_account_id, sso_region, sso_role_name } = profile; - if (!sso_start_url || !sso_account_id || !sso_region || !sso_role_name) { - throw new propertyProvider.CredentialsProviderError(`Profile is configured with invalid SSO credentials. Required parameters "sso_account_id", "sso_region", "sso_role_name", "sso_start_url". Got ${Object.keys(profile).join(", ")} -Reference: https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sso.html`, { tryNextLink: false, logger: logger4 }); - } - return profile; - }; - var fromSSO = (init2 = {}) => async ({ callerClientConfig } = {}) => { - init2.logger?.debug("@aws-sdk/credential-provider-sso - fromSSO"); - const { ssoStartUrl, ssoAccountId, ssoRegion, ssoRoleName, ssoSession } = init2; - const { ssoClient } = init2; - const profileName = sharedIniFileLoader.getProfileName({ - profile: init2.profile ?? callerClientConfig?.profile - }); - if (!ssoStartUrl && !ssoAccountId && !ssoRegion && !ssoRoleName && !ssoSession) { - const profiles = await sharedIniFileLoader.parseKnownFiles(init2); - const profile = profiles[profileName]; - if (!profile) { - throw new propertyProvider.CredentialsProviderError(`Profile ${profileName} was not found.`, { logger: init2.logger }); - } - if (!isSsoProfile(profile)) { - throw new propertyProvider.CredentialsProviderError(`Profile ${profileName} is not configured with SSO credentials.`, { - logger: init2.logger - }); - } - if (profile?.sso_session) { - const ssoSessions = await sharedIniFileLoader.loadSsoSessionData(init2); - const session = ssoSessions[profile.sso_session]; - const conflictMsg = ` configurations in profile ${profileName} and sso-session ${profile.sso_session}`; - if (ssoRegion && ssoRegion !== session.sso_region) { - throw new propertyProvider.CredentialsProviderError(`Conflicting SSO region` + conflictMsg, { - tryNextLink: false, - logger: init2.logger - }); - } - if (ssoStartUrl && ssoStartUrl !== session.sso_start_url) { - throw new propertyProvider.CredentialsProviderError(`Conflicting SSO start_url` + conflictMsg, { - tryNextLink: false, - logger: init2.logger - }); - } - profile.sso_region = session.sso_region; - profile.sso_start_url = session.sso_start_url; - } - const { sso_start_url, sso_account_id, sso_region, sso_role_name, sso_session } = validateSsoProfile(profile, init2.logger); - return resolveSSOCredentials({ - ssoStartUrl: sso_start_url, - ssoSession: sso_session, - ssoAccountId: sso_account_id, - ssoRegion: sso_region, - ssoRoleName: sso_role_name, - ssoClient, - clientConfig: init2.clientConfig, - parentClientConfig: init2.parentClientConfig, - callerClientConfig: init2.callerClientConfig, - profile: profileName, - filepath: init2.filepath, - configFilepath: init2.configFilepath, - ignoreCache: init2.ignoreCache, - logger: init2.logger - }); - } else if (!ssoStartUrl || !ssoAccountId || !ssoRegion || !ssoRoleName) { - throw new propertyProvider.CredentialsProviderError('Incomplete configuration. The fromSSO() argument hash must include "ssoStartUrl", "ssoAccountId", "ssoRegion", "ssoRoleName"', { tryNextLink: false, logger: init2.logger }); - } else { - return resolveSSOCredentials({ - ssoStartUrl, - ssoSession, - ssoAccountId, - ssoRegion, - ssoRoleName, - ssoClient, - clientConfig: init2.clientConfig, - parentClientConfig: init2.parentClientConfig, - callerClientConfig: init2.callerClientConfig, - profile: profileName, - filepath: init2.filepath, - configFilepath: init2.configFilepath, - ignoreCache: init2.ignoreCache, - logger: init2.logger - }); - } - }; - exports.fromSSO = fromSSO; - exports.isSsoProfile = isSsoProfile; - exports.validateSsoProfile = validateSsoProfile; - } -}); - -// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/auth/httpAuthSchemeProvider.js -function createAwsAuthSigv4HttpAuthOption3(authParameters) { - return { - schemeId: "aws.auth#sigv4", - signingProperties: { - name: "signin", - region: authParameters.region - }, - propertiesExtractor: (config3, context) => ({ - signingProperties: { - config: config3, - context - } - }) - }; -} -function createSmithyApiNoAuthHttpAuthOption3(authParameters) { - return { - schemeId: "smithy.api#noAuth" - }; -} -var import_util_middleware8, defaultSigninHttpAuthSchemeParametersProvider, defaultSigninHttpAuthSchemeProvider, resolveHttpAuthSchemeConfig3; -var init_httpAuthSchemeProvider3 = __esm({ - "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/auth/httpAuthSchemeProvider.js"() { - init_httpAuthSchemes2(); - import_util_middleware8 = __toESM(require_dist_cjs18()); - defaultSigninHttpAuthSchemeParametersProvider = async (config3, context, input) => { - return { - operation: (0, import_util_middleware8.getSmithyContext)(context).operation, - region: await (0, import_util_middleware8.normalizeProvider)(config3.region)() || (() => { - throw new Error("expected `region` to be configured for `aws.auth#sigv4`"); - })() - }; - }; - defaultSigninHttpAuthSchemeProvider = (authParameters) => { - const options = []; - switch (authParameters.operation) { - case "CreateOAuth2Token": { - options.push(createSmithyApiNoAuthHttpAuthOption3(authParameters)); - break; - } - default: { - options.push(createAwsAuthSigv4HttpAuthOption3(authParameters)); - } - } - return options; - }; - resolveHttpAuthSchemeConfig3 = (config3) => { - const config_0 = resolveAwsSdkSigV4Config(config3); - return Object.assign(config_0, { - authSchemePreference: (0, import_util_middleware8.normalizeProvider)(config3.authSchemePreference ?? []) - }); - }; - } -}); - -// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/endpoint/EndpointParameters.js -var resolveClientEndpointParameters3, commonParams3; -var init_EndpointParameters3 = __esm({ - "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/endpoint/EndpointParameters.js"() { - resolveClientEndpointParameters3 = (options) => { - return Object.assign(options, { - useDualstackEndpoint: options.useDualstackEndpoint ?? false, - useFipsEndpoint: options.useFipsEndpoint ?? false, - defaultSigningName: "signin" - }); - }; - commonParams3 = { - UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, - Endpoint: { type: "builtInParams", name: "endpoint" }, - Region: { type: "builtInParams", name: "region" }, - UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" } - }; - } -}); - -// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/endpoint/ruleset.js -var u3, v3, w3, x3, a3, b4, c3, d3, e3, f3, g3, h3, i3, j3, k3, l3, m3, n3, o3, p3, q3, r3, s3, t3, _data3, ruleSet3; -var init_ruleset3 = __esm({ - "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/endpoint/ruleset.js"() { - u3 = "required"; - v3 = "fn"; - w3 = "argv"; - x3 = "ref"; - a3 = true; - b4 = "isSet"; - c3 = "booleanEquals"; - d3 = "error"; - e3 = "endpoint"; - f3 = "tree"; - g3 = "PartitionResult"; - h3 = "stringEquals"; - i3 = { [u3]: true, default: false, type: "boolean" }; - j3 = { [u3]: false, type: "string" }; - k3 = { [x3]: "Endpoint" }; - l3 = { [v3]: c3, [w3]: [{ [x3]: "UseFIPS" }, true] }; - m3 = { [v3]: c3, [w3]: [{ [x3]: "UseDualStack" }, true] }; - n3 = {}; - o3 = { [v3]: "getAttr", [w3]: [{ [x3]: g3 }, "name"] }; - p3 = { [v3]: c3, [w3]: [{ [x3]: "UseFIPS" }, false] }; - q3 = { [v3]: c3, [w3]: [{ [x3]: "UseDualStack" }, false] }; - r3 = { [v3]: "getAttr", [w3]: [{ [x3]: g3 }, "supportsFIPS"] }; - s3 = { [v3]: c3, [w3]: [true, { [v3]: "getAttr", [w3]: [{ [x3]: g3 }, "supportsDualStack"] }] }; - t3 = [{ [x3]: "Region" }]; - _data3 = { - version: "1.0", - parameters: { UseDualStack: i3, UseFIPS: i3, Endpoint: j3, Region: j3 }, - rules: [ - { - conditions: [{ [v3]: b4, [w3]: [k3] }], - rules: [ - { conditions: [l3], error: "Invalid Configuration: FIPS and custom endpoint are not supported", type: d3 }, - { - rules: [ - { - conditions: [m3], - error: "Invalid Configuration: Dualstack and custom endpoint are not supported", - type: d3 - }, - { endpoint: { url: k3, properties: n3, headers: n3 }, type: e3 } - ], - type: f3 - } - ], - type: f3 - }, - { - rules: [ - { - conditions: [{ [v3]: b4, [w3]: t3 }], - rules: [ - { - conditions: [{ [v3]: "aws.partition", [w3]: t3, assign: g3 }], - rules: [ - { - conditions: [{ [v3]: h3, [w3]: [o3, "aws"] }, p3, q3], - endpoint: { url: "https://{Region}.signin.aws.amazon.com", properties: n3, headers: n3 }, - type: e3 - }, - { - conditions: [{ [v3]: h3, [w3]: [o3, "aws-cn"] }, p3, q3], - endpoint: { url: "https://{Region}.signin.amazonaws.cn", properties: n3, headers: n3 }, - type: e3 - }, - { - conditions: [{ [v3]: h3, [w3]: [o3, "aws-us-gov"] }, p3, q3], - endpoint: { url: "https://{Region}.signin.amazonaws-us-gov.com", properties: n3, headers: n3 }, - type: e3 - }, - { - conditions: [l3, m3], - rules: [ - { - conditions: [{ [v3]: c3, [w3]: [a3, r3] }, s3], - rules: [ - { - endpoint: { - url: "https://signin-fips.{Region}.{PartitionResult#dualStackDnsSuffix}", - properties: n3, - headers: n3 - }, - type: e3 - } - ], - type: f3 - }, - { - error: "FIPS and DualStack are enabled, but this partition does not support one or both", - type: d3 - } - ], - type: f3 - }, - { - conditions: [l3, q3], - rules: [ - { - conditions: [{ [v3]: c3, [w3]: [r3, a3] }], - rules: [ - { - endpoint: { - url: "https://signin-fips.{Region}.{PartitionResult#dnsSuffix}", - properties: n3, - headers: n3 - }, - type: e3 - } - ], - type: f3 - }, - { error: "FIPS is enabled but this partition does not support FIPS", type: d3 } - ], - type: f3 - }, - { - conditions: [p3, m3], - rules: [ - { - conditions: [s3], - rules: [ - { - endpoint: { - url: "https://signin.{Region}.{PartitionResult#dualStackDnsSuffix}", - properties: n3, - headers: n3 - }, - type: e3 - } - ], - type: f3 - }, - { error: "DualStack is enabled but this partition does not support DualStack", type: d3 } - ], - type: f3 - }, - { - endpoint: { url: "https://signin.{Region}.{PartitionResult#dnsSuffix}", properties: n3, headers: n3 }, - type: e3 - } - ], - type: f3 - } - ], - type: f3 - }, - { error: "Invalid Configuration: Missing Region", type: d3 } - ], - type: f3 - } - ] - }; - ruleSet3 = _data3; - } -}); - -// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/endpoint/endpointResolver.js -var import_util_endpoints5, import_util_endpoints6, cache3, defaultEndpointResolver3; -var init_endpointResolver3 = __esm({ - "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/endpoint/endpointResolver.js"() { - import_util_endpoints5 = __toESM(require_dist_cjs34()); - import_util_endpoints6 = __toESM(require_dist_cjs33()); - init_ruleset3(); - cache3 = new import_util_endpoints6.EndpointCache({ - size: 50, - params: ["Endpoint", "Region", "UseDualStack", "UseFIPS"] - }); - defaultEndpointResolver3 = (endpointParams, context = {}) => { - return cache3.get(endpointParams, () => (0, import_util_endpoints6.resolveEndpoint)(ruleSet3, { - endpointParams, - logger: context.logger - })); - }; - import_util_endpoints6.customEndpointFunctions.aws = import_util_endpoints5.awsEndpointFunctions; - } -}); - -// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/models/SigninServiceException.js -var import_smithy_client22, SigninServiceException; -var init_SigninServiceException = __esm({ - "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/models/SigninServiceException.js"() { - import_smithy_client22 = __toESM(require_dist_cjs27()); - SigninServiceException = class _SigninServiceException extends import_smithy_client22.ServiceException { - constructor(options) { - super(options); - Object.setPrototypeOf(this, _SigninServiceException.prototype); - } - }; - } -}); - -// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/models/errors.js -var AccessDeniedException2, InternalServerException2, TooManyRequestsError, ValidationException; -var init_errors5 = __esm({ - "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/models/errors.js"() { - init_SigninServiceException(); - AccessDeniedException2 = class _AccessDeniedException extends SigninServiceException { - name = "AccessDeniedException"; - $fault = "client"; - error; - constructor(opts) { - super({ - name: "AccessDeniedException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _AccessDeniedException.prototype); - this.error = opts.error; - } - }; - InternalServerException2 = class _InternalServerException extends SigninServiceException { - name = "InternalServerException"; - $fault = "server"; - error; - constructor(opts) { - super({ - name: "InternalServerException", - $fault: "server", - ...opts - }); - Object.setPrototypeOf(this, _InternalServerException.prototype); - this.error = opts.error; - } - }; - TooManyRequestsError = class _TooManyRequestsError extends SigninServiceException { - name = "TooManyRequestsError"; - $fault = "client"; - error; - constructor(opts) { - super({ - name: "TooManyRequestsError", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _TooManyRequestsError.prototype); - this.error = opts.error; - } - }; - ValidationException = class _ValidationException extends SigninServiceException { - name = "ValidationException"; - $fault = "client"; - error; - constructor(opts) { - super({ - name: "ValidationException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _ValidationException.prototype); - this.error = opts.error; - } - }; - } -}); - -// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/schemas/schemas_0.js -var _ADE2, _AT2, _COAT, _COATR, _COATRB, _COATRBr, _COATRr, _ISE2, _RT2, _TMRE2, _VE, _aKI2, _aT3, _c3, _cI2, _cV2, _co2, _e3, _eI2, _gT2, _h3, _hE3, _iT2, _jN, _m2, _rT2, _rU2, _s3, _sAK2, _sT2, _se2, _tI, _tO, _tT2, n03, _s_registry3, SigninServiceException$, n0_registry3, AccessDeniedException$2, InternalServerException$2, TooManyRequestsError$, ValidationException$, errorTypeRegistries3, RefreshToken2, AccessToken$, CreateOAuth2TokenRequest$, CreateOAuth2TokenRequestBody$, CreateOAuth2TokenResponse$, CreateOAuth2TokenResponseBody$, CreateOAuth2Token$; -var init_schemas_03 = __esm({ - "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/schemas/schemas_0.js"() { - init_schema3(); - init_errors5(); - init_SigninServiceException(); - _ADE2 = "AccessDeniedException"; - _AT2 = "AccessToken"; - _COAT = "CreateOAuth2Token"; - _COATR = "CreateOAuth2TokenRequest"; - _COATRB = "CreateOAuth2TokenRequestBody"; - _COATRBr = "CreateOAuth2TokenResponseBody"; - _COATRr = "CreateOAuth2TokenResponse"; - _ISE2 = "InternalServerException"; - _RT2 = "RefreshToken"; - _TMRE2 = "TooManyRequestsError"; - _VE = "ValidationException"; - _aKI2 = "accessKeyId"; - _aT3 = "accessToken"; - _c3 = "client"; - _cI2 = "clientId"; - _cV2 = "codeVerifier"; - _co2 = "code"; - _e3 = "error"; - _eI2 = "expiresIn"; - _gT2 = "grantType"; - _h3 = "http"; - _hE3 = "httpError"; - _iT2 = "idToken"; - _jN = "jsonName"; - _m2 = "message"; - _rT2 = "refreshToken"; - _rU2 = "redirectUri"; - _s3 = "smithy.ts.sdk.synthetic.com.amazonaws.signin"; - _sAK2 = "secretAccessKey"; - _sT2 = "sessionToken"; - _se2 = "server"; - _tI = "tokenInput"; - _tO = "tokenOutput"; - _tT2 = "tokenType"; - n03 = "com.amazonaws.signin"; - _s_registry3 = TypeRegistry.for(_s3); - SigninServiceException$ = [-3, _s3, "SigninServiceException", 0, [], []]; - _s_registry3.registerError(SigninServiceException$, SigninServiceException); - n0_registry3 = TypeRegistry.for(n03); - AccessDeniedException$2 = [-3, n03, _ADE2, { [_e3]: _c3 }, [_e3, _m2], [0, 0], 2]; - n0_registry3.registerError(AccessDeniedException$2, AccessDeniedException2); - InternalServerException$2 = [-3, n03, _ISE2, { [_e3]: _se2, [_hE3]: 500 }, [_e3, _m2], [0, 0], 2]; - n0_registry3.registerError(InternalServerException$2, InternalServerException2); - TooManyRequestsError$ = [-3, n03, _TMRE2, { [_e3]: _c3, [_hE3]: 429 }, [_e3, _m2], [0, 0], 2]; - n0_registry3.registerError(TooManyRequestsError$, TooManyRequestsError); - ValidationException$ = [-3, n03, _VE, { [_e3]: _c3, [_hE3]: 400 }, [_e3, _m2], [0, 0], 2]; - n0_registry3.registerError(ValidationException$, ValidationException); - errorTypeRegistries3 = [_s_registry3, n0_registry3]; - RefreshToken2 = [0, n03, _RT2, 8, 0]; - AccessToken$ = [ - 3, - n03, - _AT2, - 8, - [_aKI2, _sAK2, _sT2], - [ - [0, { [_jN]: _aKI2 }], - [0, { [_jN]: _sAK2 }], - [0, { [_jN]: _sT2 }] - ], - 3 - ]; - CreateOAuth2TokenRequest$ = [ - 3, - n03, - _COATR, - 0, - [_tI], - [[() => CreateOAuth2TokenRequestBody$, 16]], - 1 - ]; - CreateOAuth2TokenRequestBody$ = [ - 3, - n03, - _COATRB, - 0, - [_cI2, _gT2, _co2, _rU2, _cV2, _rT2], - [ - [0, { [_jN]: _cI2 }], - [0, { [_jN]: _gT2 }], - 0, - [0, { [_jN]: _rU2 }], - [0, { [_jN]: _cV2 }], - [() => RefreshToken2, { [_jN]: _rT2 }] - ], - 2 - ]; - CreateOAuth2TokenResponse$ = [ - 3, - n03, - _COATRr, - 0, - [_tO], - [[() => CreateOAuth2TokenResponseBody$, 16]], - 1 - ]; - CreateOAuth2TokenResponseBody$ = [ - 3, - n03, - _COATRBr, - 0, - [_aT3, _tT2, _eI2, _rT2, _iT2], - [ - [() => AccessToken$, { [_jN]: _aT3 }], - [0, { [_jN]: _tT2 }], - [1, { [_jN]: _eI2 }], - [() => RefreshToken2, { [_jN]: _rT2 }], - [0, { [_jN]: _iT2 }] - ], - 4 - ]; - CreateOAuth2Token$ = [ - 9, - n03, - _COAT, - { [_h3]: ["POST", "/v1/token", 200] }, - () => CreateOAuth2TokenRequest$, - () => CreateOAuth2TokenResponse$ - ]; - } -}); - -// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/runtimeConfig.shared.js -var import_smithy_client23, import_url_parser4, import_util_base6410, import_util_utf810, getRuntimeConfig5; -var init_runtimeConfig_shared3 = __esm({ - "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/runtimeConfig.shared.js"() { - init_httpAuthSchemes2(); - init_protocols2(); - init_dist_es(); - import_smithy_client23 = __toESM(require_dist_cjs27()); - import_url_parser4 = __toESM(require_dist_cjs25()); - import_util_base6410 = __toESM(require_dist_cjs7()); - import_util_utf810 = __toESM(require_dist_cjs6()); - init_httpAuthSchemeProvider3(); - init_endpointResolver3(); - init_schemas_03(); - getRuntimeConfig5 = (config3) => { - return { - apiVersion: "2023-01-01", - base64Decoder: config3?.base64Decoder ?? import_util_base6410.fromBase64, - base64Encoder: config3?.base64Encoder ?? import_util_base6410.toBase64, - disableHostPrefix: config3?.disableHostPrefix ?? false, - endpointProvider: config3?.endpointProvider ?? defaultEndpointResolver3, - extensions: config3?.extensions ?? [], - httpAuthSchemeProvider: config3?.httpAuthSchemeProvider ?? defaultSigninHttpAuthSchemeProvider, - httpAuthSchemes: config3?.httpAuthSchemes ?? [ - { - schemeId: "aws.auth#sigv4", - identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"), - signer: new AwsSdkSigV4Signer() - }, - { - schemeId: "smithy.api#noAuth", - identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})), - signer: new NoAuthSigner() - } - ], - logger: config3?.logger ?? new import_smithy_client23.NoOpLogger(), - protocol: config3?.protocol ?? AwsRestJsonProtocol, - protocolSettings: config3?.protocolSettings ?? { - defaultNamespace: "com.amazonaws.signin", - errorTypeRegistries: errorTypeRegistries3, - version: "2023-01-01", - serviceTarget: "Signin" - }, - serviceId: config3?.serviceId ?? "Signin", - urlParser: config3?.urlParser ?? import_url_parser4.parseUrl, - utf8Decoder: config3?.utf8Decoder ?? import_util_utf810.fromUtf8, - utf8Encoder: config3?.utf8Encoder ?? import_util_utf810.toUtf8 - }; - }; - } -}); - -// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/runtimeConfig.js -var import_util_user_agent_node3, import_config_resolver5, import_hash_node3, import_middleware_retry5, import_node_config_provider3, import_node_http_handler3, import_smithy_client24, import_util_body_length_node3, import_util_defaults_mode_node3, import_util_retry3, getRuntimeConfig6; -var init_runtimeConfig3 = __esm({ - "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/runtimeConfig.js"() { - init_package(); - init_client2(); - init_httpAuthSchemes2(); - import_util_user_agent_node3 = __toESM(require_dist_cjs51()); - import_config_resolver5 = __toESM(require_dist_cjs38()); - import_hash_node3 = __toESM(require_dist_cjs52()); - import_middleware_retry5 = __toESM(require_dist_cjs46()); - import_node_config_provider3 = __toESM(require_dist_cjs43()); - import_node_http_handler3 = __toESM(require_dist_cjs10()); - import_smithy_client24 = __toESM(require_dist_cjs27()); - import_util_body_length_node3 = __toESM(require_dist_cjs53()); - import_util_defaults_mode_node3 = __toESM(require_dist_cjs54()); - import_util_retry3 = __toESM(require_dist_cjs36()); - init_runtimeConfig_shared3(); - getRuntimeConfig6 = (config3) => { - (0, import_smithy_client24.emitWarningIfUnsupportedVersion)(process.version); - const defaultsMode = (0, import_util_defaults_mode_node3.resolveDefaultsModeConfig)(config3); - const defaultConfigProvider = () => defaultsMode().then(import_smithy_client24.loadConfigsForDefaultMode); - const clientSharedValues = getRuntimeConfig5(config3); - emitWarningIfUnsupportedVersion(process.version); - const loaderConfig = { - profile: config3?.profile, - logger: clientSharedValues.logger - }; - return { - ...clientSharedValues, - ...config3, - runtime: "node", - defaultsMode, - authSchemePreference: config3?.authSchemePreference ?? (0, import_node_config_provider3.loadConfig)(NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig), - bodyLengthChecker: config3?.bodyLengthChecker ?? import_util_body_length_node3.calculateBodyLength, - defaultUserAgentProvider: config3?.defaultUserAgentProvider ?? (0, import_util_user_agent_node3.createDefaultUserAgentProvider)({ serviceId: clientSharedValues.serviceId, clientVersion: package_default.version }), - maxAttempts: config3?.maxAttempts ?? (0, import_node_config_provider3.loadConfig)(import_middleware_retry5.NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config3), - region: config3?.region ?? (0, import_node_config_provider3.loadConfig)(import_config_resolver5.NODE_REGION_CONFIG_OPTIONS, { ...import_config_resolver5.NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }), - requestHandler: import_node_http_handler3.NodeHttpHandler.create(config3?.requestHandler ?? defaultConfigProvider), - retryMode: config3?.retryMode ?? (0, import_node_config_provider3.loadConfig)({ - ...import_middleware_retry5.NODE_RETRY_MODE_CONFIG_OPTIONS, - default: async () => (await defaultConfigProvider()).retryMode || import_util_retry3.DEFAULT_RETRY_MODE - }, config3), - sha256: config3?.sha256 ?? import_hash_node3.Hash.bind(null, "sha256"), - streamCollector: config3?.streamCollector ?? import_node_http_handler3.streamCollector, - useDualstackEndpoint: config3?.useDualstackEndpoint ?? (0, import_node_config_provider3.loadConfig)(import_config_resolver5.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig), - useFipsEndpoint: config3?.useFipsEndpoint ?? (0, import_node_config_provider3.loadConfig)(import_config_resolver5.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig), - userAgentAppId: config3?.userAgentAppId ?? (0, import_node_config_provider3.loadConfig)(import_util_user_agent_node3.NODE_APP_ID_CONFIG_OPTIONS, loaderConfig) - }; - }; - } -}); - -// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/auth/httpAuthExtensionConfiguration.js -var getHttpAuthExtensionConfiguration3, resolveHttpAuthRuntimeConfig3; -var init_httpAuthExtensionConfiguration3 = __esm({ - "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/auth/httpAuthExtensionConfiguration.js"() { - getHttpAuthExtensionConfiguration3 = (runtimeConfig) => { - const _httpAuthSchemes = runtimeConfig.httpAuthSchemes; - let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider; - let _credentials = runtimeConfig.credentials; - return { - setHttpAuthScheme(httpAuthScheme) { - const index2 = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId); - if (index2 === -1) { - _httpAuthSchemes.push(httpAuthScheme); - } else { - _httpAuthSchemes.splice(index2, 1, httpAuthScheme); - } - }, - httpAuthSchemes() { - return _httpAuthSchemes; - }, - setHttpAuthSchemeProvider(httpAuthSchemeProvider) { - _httpAuthSchemeProvider = httpAuthSchemeProvider; - }, - httpAuthSchemeProvider() { - return _httpAuthSchemeProvider; - }, - setCredentials(credentials) { - _credentials = credentials; - }, - credentials() { - return _credentials; - } - }; - }; - resolveHttpAuthRuntimeConfig3 = (config3) => { - return { - httpAuthSchemes: config3.httpAuthSchemes(), - httpAuthSchemeProvider: config3.httpAuthSchemeProvider(), - credentials: config3.credentials() - }; - }; - } -}); - -// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/runtimeExtensions.js -var import_region_config_resolver3, import_protocol_http14, import_smithy_client25, resolveRuntimeExtensions3; -var init_runtimeExtensions3 = __esm({ - "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/runtimeExtensions.js"() { - import_region_config_resolver3 = __toESM(require_dist_cjs55()); - import_protocol_http14 = __toESM(require_dist_cjs2()); - import_smithy_client25 = __toESM(require_dist_cjs27()); - init_httpAuthExtensionConfiguration3(); - resolveRuntimeExtensions3 = (runtimeConfig, extensions) => { - const extensionConfiguration = Object.assign((0, import_region_config_resolver3.getAwsRegionExtensionConfiguration)(runtimeConfig), (0, import_smithy_client25.getDefaultExtensionConfiguration)(runtimeConfig), (0, import_protocol_http14.getHttpHandlerExtensionConfiguration)(runtimeConfig), getHttpAuthExtensionConfiguration3(runtimeConfig)); - extensions.forEach((extension2) => extension2.configure(extensionConfiguration)); - return Object.assign(runtimeConfig, (0, import_region_config_resolver3.resolveAwsRegionExtensionConfiguration)(extensionConfiguration), (0, import_smithy_client25.resolveDefaultRuntimeConfig)(extensionConfiguration), (0, import_protocol_http14.resolveHttpHandlerRuntimeConfig)(extensionConfiguration), resolveHttpAuthRuntimeConfig3(extensionConfiguration)); - }; - } -}); - -// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/SigninClient.js -var import_middleware_host_header3, import_middleware_logger3, import_middleware_recursion_detection3, import_middleware_user_agent3, import_config_resolver6, import_middleware_content_length3, import_middleware_endpoint5, import_middleware_retry6, import_smithy_client26, SigninClient; -var init_SigninClient = __esm({ - "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/SigninClient.js"() { - import_middleware_host_header3 = __toESM(require_dist_cjs20()); - import_middleware_logger3 = __toESM(require_dist_cjs21()); - import_middleware_recursion_detection3 = __toESM(require_dist_cjs22()); - import_middleware_user_agent3 = __toESM(require_dist_cjs37()); - import_config_resolver6 = __toESM(require_dist_cjs38()); - init_dist_es(); - init_schema3(); - import_middleware_content_length3 = __toESM(require_dist_cjs40()); - import_middleware_endpoint5 = __toESM(require_dist_cjs45()); - import_middleware_retry6 = __toESM(require_dist_cjs46()); - import_smithy_client26 = __toESM(require_dist_cjs27()); - init_httpAuthSchemeProvider3(); - init_EndpointParameters3(); - init_runtimeConfig3(); - init_runtimeExtensions3(); - SigninClient = class extends import_smithy_client26.Client { - config; - constructor(...[configuration]) { - const _config_0 = getRuntimeConfig6(configuration || {}); - super(_config_0); - this.initConfig = _config_0; - const _config_1 = resolveClientEndpointParameters3(_config_0); - const _config_2 = (0, import_middleware_user_agent3.resolveUserAgentConfig)(_config_1); - const _config_3 = (0, import_middleware_retry6.resolveRetryConfig)(_config_2); - const _config_4 = (0, import_config_resolver6.resolveRegionConfig)(_config_3); - const _config_5 = (0, import_middleware_host_header3.resolveHostHeaderConfig)(_config_4); - const _config_6 = (0, import_middleware_endpoint5.resolveEndpointConfig)(_config_5); - const _config_7 = resolveHttpAuthSchemeConfig3(_config_6); - const _config_8 = resolveRuntimeExtensions3(_config_7, configuration?.extensions || []); - this.config = _config_8; - this.middlewareStack.use(getSchemaSerdePlugin(this.config)); - this.middlewareStack.use((0, import_middleware_user_agent3.getUserAgentPlugin)(this.config)); - this.middlewareStack.use((0, import_middleware_retry6.getRetryPlugin)(this.config)); - this.middlewareStack.use((0, import_middleware_content_length3.getContentLengthPlugin)(this.config)); - this.middlewareStack.use((0, import_middleware_host_header3.getHostHeaderPlugin)(this.config)); - this.middlewareStack.use((0, import_middleware_logger3.getLoggerPlugin)(this.config)); - this.middlewareStack.use((0, import_middleware_recursion_detection3.getRecursionDetectionPlugin)(this.config)); - this.middlewareStack.use(getHttpAuthSchemeEndpointRuleSetPlugin(this.config, { - httpAuthSchemeParametersProvider: defaultSigninHttpAuthSchemeParametersProvider, - identityProviderConfigProvider: async (config3) => new DefaultIdentityProviderConfig({ - "aws.auth#sigv4": config3.credentials - }) - })); - this.middlewareStack.use(getHttpSigningPlugin(this.config)); - } - destroy() { - super.destroy(); - } - }; - } -}); - -// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/commands/CreateOAuth2TokenCommand.js -var import_middleware_endpoint6, import_smithy_client27, CreateOAuth2TokenCommand; -var init_CreateOAuth2TokenCommand = __esm({ - "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/commands/CreateOAuth2TokenCommand.js"() { - import_middleware_endpoint6 = __toESM(require_dist_cjs45()); - import_smithy_client27 = __toESM(require_dist_cjs27()); - init_EndpointParameters3(); - init_schemas_03(); - CreateOAuth2TokenCommand = class extends import_smithy_client27.Command.classBuilder().ep(commonParams3).m(function(Command2, cs, config3, o5) { - return [(0, import_middleware_endpoint6.getEndpointPlugin)(config3, Command2.getEndpointParameterInstructions())]; - }).s("Signin", "CreateOAuth2Token", {}).n("SigninClient", "CreateOAuth2TokenCommand").sc(CreateOAuth2Token$).build() { - }; - } -}); - -// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/Signin.js -var import_smithy_client28, commands3, Signin; -var init_Signin = __esm({ - "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/Signin.js"() { - import_smithy_client28 = __toESM(require_dist_cjs27()); - init_CreateOAuth2TokenCommand(); - init_SigninClient(); - commands3 = { - CreateOAuth2TokenCommand - }; - Signin = class extends SigninClient { - }; - (0, import_smithy_client28.createAggregatedClient)(commands3, Signin); - } -}); - -// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/commands/index.js -var init_commands3 = __esm({ - "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/commands/index.js"() { - init_CreateOAuth2TokenCommand(); - } -}); - -// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/models/enums.js -var OAuth2ErrorCode; -var init_enums2 = __esm({ - "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/models/enums.js"() { - OAuth2ErrorCode = { - AUTHCODE_EXPIRED: "AUTHCODE_EXPIRED", - INSUFFICIENT_PERMISSIONS: "INSUFFICIENT_PERMISSIONS", - INVALID_REQUEST: "INVALID_REQUEST", - SERVER_ERROR: "server_error", - TOKEN_EXPIRED: "TOKEN_EXPIRED", - USER_CREDENTIALS_CHANGED: "USER_CREDENTIALS_CHANGED" - }; - } -}); - -// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/models/models_0.js -var init_models_03 = __esm({ - "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/models/models_0.js"() { - } -}); - -// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/index.js -var signin_exports = {}; -__export(signin_exports, { - $Command: () => import_smithy_client27.Command, - AccessDeniedException: () => AccessDeniedException2, - AccessDeniedException$: () => AccessDeniedException$2, - AccessToken$: () => AccessToken$, - CreateOAuth2Token$: () => CreateOAuth2Token$, - CreateOAuth2TokenCommand: () => CreateOAuth2TokenCommand, - CreateOAuth2TokenRequest$: () => CreateOAuth2TokenRequest$, - CreateOAuth2TokenRequestBody$: () => CreateOAuth2TokenRequestBody$, - CreateOAuth2TokenResponse$: () => CreateOAuth2TokenResponse$, - CreateOAuth2TokenResponseBody$: () => CreateOAuth2TokenResponseBody$, - InternalServerException: () => InternalServerException2, - InternalServerException$: () => InternalServerException$2, - OAuth2ErrorCode: () => OAuth2ErrorCode, - Signin: () => Signin, - SigninClient: () => SigninClient, - SigninServiceException: () => SigninServiceException, - SigninServiceException$: () => SigninServiceException$, - TooManyRequestsError: () => TooManyRequestsError, - TooManyRequestsError$: () => TooManyRequestsError$, - ValidationException: () => ValidationException, - ValidationException$: () => ValidationException$, - __Client: () => import_smithy_client26.Client, - errorTypeRegistries: () => errorTypeRegistries3 -}); -var init_signin = __esm({ - "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/index.js"() { - init_SigninClient(); - init_Signin(); - init_commands3(); - init_schemas_03(); - init_enums2(); - init_errors5(); - init_models_03(); - init_SigninServiceException(); - } -}); - -// node_modules/.pnpm/@aws-sdk+credential-provider-login@3.972.29/node_modules/@aws-sdk/credential-provider-login/dist-cjs/index.js -var require_dist_cjs58 = __commonJS({ - "node_modules/.pnpm/@aws-sdk+credential-provider-login@3.972.29/node_modules/@aws-sdk/credential-provider-login/dist-cjs/index.js"(exports) { - "use strict"; - var client2 = (init_client2(), __toCommonJS(client_exports)); - var propertyProvider = require_dist_cjs41(); - var sharedIniFileLoader = require_dist_cjs42(); - var protocolHttp = require_dist_cjs2(); - var node_crypto = __require("node:crypto"); - var node_fs = __require("node:fs"); - var node_os = __require("node:os"); - var node_path = __require("node:path"); - var LoginCredentialsFetcher = class _LoginCredentialsFetcher { - profileData; - init; - callerClientConfig; - static REFRESH_THRESHOLD = 5 * 60 * 1e3; - constructor(profileData, init2, callerClientConfig) { - this.profileData = profileData; - this.init = init2; - this.callerClientConfig = callerClientConfig; - } - async loadCredentials() { - const token = await this.loadToken(); - if (!token) { - throw new propertyProvider.CredentialsProviderError(`Failed to load a token for session ${this.loginSession}, please re-authenticate using aws login`, { tryNextLink: false, logger: this.logger }); - } - const accessToken = token.accessToken; - const now2 = Date.now(); - const expiryTime = new Date(accessToken.expiresAt).getTime(); - const timeUntilExpiry = expiryTime - now2; - if (timeUntilExpiry <= _LoginCredentialsFetcher.REFRESH_THRESHOLD) { - return this.refresh(token); - } - return { - accessKeyId: accessToken.accessKeyId, - secretAccessKey: accessToken.secretAccessKey, - sessionToken: accessToken.sessionToken, - accountId: accessToken.accountId, - expiration: new Date(accessToken.expiresAt) - }; - } - get logger() { - return this.init?.logger; - } - get loginSession() { - return this.profileData.login_session; - } - async refresh(token) { - const { SigninClient: SigninClient2, CreateOAuth2TokenCommand: CreateOAuth2TokenCommand2 } = await Promise.resolve().then(() => (init_signin(), signin_exports)); - const { logger: logger4, userAgentAppId } = this.callerClientConfig ?? {}; - const isH22 = (requestHandler2) => { - return requestHandler2?.metadata?.handlerProtocol === "h2"; - }; - const requestHandler = isH22(this.callerClientConfig?.requestHandler) ? void 0 : this.callerClientConfig?.requestHandler; - const region = this.profileData.region ?? await this.callerClientConfig?.region?.() ?? process.env.AWS_REGION; - const client3 = new SigninClient2({ - credentials: { - accessKeyId: "", - secretAccessKey: "" - }, - region, - requestHandler, - logger: logger4, - userAgentAppId, - ...this.init?.clientConfig - }); - this.createDPoPInterceptor(client3.middlewareStack); - const commandInput = { - tokenInput: { - clientId: token.clientId, - refreshToken: token.refreshToken, - grantType: "refresh_token" - } - }; - try { - const response = await client3.send(new CreateOAuth2TokenCommand2(commandInput)); - const { accessKeyId, secretAccessKey, sessionToken } = response.tokenOutput?.accessToken ?? {}; - const { refreshToken: refreshToken2, expiresIn } = response.tokenOutput ?? {}; - if (!accessKeyId || !secretAccessKey || !sessionToken || !refreshToken2) { - throw new propertyProvider.CredentialsProviderError("Token refresh response missing required fields", { - logger: this.logger, - tryNextLink: false - }); - } - const expiresInMs = (expiresIn ?? 900) * 1e3; - const expiration = new Date(Date.now() + expiresInMs); - const updatedToken = { - ...token, - accessToken: { - ...token.accessToken, - accessKeyId, - secretAccessKey, - sessionToken, - expiresAt: expiration.toISOString() - }, - refreshToken: refreshToken2 - }; - await this.saveToken(updatedToken); - const newAccessToken = updatedToken.accessToken; - return { - accessKeyId: newAccessToken.accessKeyId, - secretAccessKey: newAccessToken.secretAccessKey, - sessionToken: newAccessToken.sessionToken, - accountId: newAccessToken.accountId, - expiration - }; - } catch (error50) { - if (error50.name === "AccessDeniedException") { - const errorType = error50.error; - let message2; - switch (errorType) { - case "TOKEN_EXPIRED": - message2 = "Your session has expired. Please reauthenticate."; - break; - case "USER_CREDENTIALS_CHANGED": - message2 = "Unable to refresh credentials because of a change in your password. Please reauthenticate with your new password."; - break; - case "INSUFFICIENT_PERMISSIONS": - message2 = "Unable to refresh credentials due to insufficient permissions. You may be missing permission for the 'CreateOAuth2Token' action."; - break; - default: - message2 = `Failed to refresh token: ${String(error50)}. Please re-authenticate using \`aws login\``; - } - throw new propertyProvider.CredentialsProviderError(message2, { logger: this.logger, tryNextLink: false }); - } - throw new propertyProvider.CredentialsProviderError(`Failed to refresh token: ${String(error50)}. Please re-authenticate using aws login`, { logger: this.logger }); - } - } - async loadToken() { - const tokenFilePath = this.getTokenFilePath(); - try { - let tokenData; - try { - tokenData = await sharedIniFileLoader.readFile(tokenFilePath, { ignoreCache: this.init?.ignoreCache }); - } catch { - tokenData = await node_fs.promises.readFile(tokenFilePath, "utf8"); - } - const token = JSON.parse(tokenData); - const missingFields = ["accessToken", "clientId", "refreshToken", "dpopKey"].filter((k5) => !token[k5]); - if (!token.accessToken?.accountId) { - missingFields.push("accountId"); - } - if (missingFields.length > 0) { - throw new propertyProvider.CredentialsProviderError(`Token validation failed, missing fields: ${missingFields.join(", ")}`, { - logger: this.logger, - tryNextLink: false - }); - } - return token; - } catch (error50) { - throw new propertyProvider.CredentialsProviderError(`Failed to load token from ${tokenFilePath}: ${String(error50)}`, { - logger: this.logger, - tryNextLink: false - }); - } - } - async saveToken(token) { - const tokenFilePath = this.getTokenFilePath(); - const directory = node_path.dirname(tokenFilePath); - try { - await node_fs.promises.mkdir(directory, { recursive: true }); - } catch (error50) { - } - await node_fs.promises.writeFile(tokenFilePath, JSON.stringify(token, null, 2), "utf8"); - } - getTokenFilePath() { - const directory = process.env.AWS_LOGIN_CACHE_DIRECTORY ?? node_path.join(node_os.homedir(), ".aws", "login", "cache"); - const loginSessionBytes = Buffer.from(this.loginSession, "utf8"); - const loginSessionSha256 = node_crypto.createHash("sha256").update(loginSessionBytes).digest("hex"); - return node_path.join(directory, `${loginSessionSha256}.json`); - } - derToRawSignature(derSignature) { - let offset = 2; - if (derSignature[offset] !== 2) { - throw new Error("Invalid DER signature"); - } - offset++; - const rLength = derSignature[offset++]; - let r5 = derSignature.subarray(offset, offset + rLength); - offset += rLength; - if (derSignature[offset] !== 2) { - throw new Error("Invalid DER signature"); - } - offset++; - const sLength = derSignature[offset++]; - let s5 = derSignature.subarray(offset, offset + sLength); - r5 = r5[0] === 0 ? r5.subarray(1) : r5; - s5 = s5[0] === 0 ? s5.subarray(1) : s5; - const rPadded = Buffer.concat([Buffer.alloc(32 - r5.length), r5]); - const sPadded = Buffer.concat([Buffer.alloc(32 - s5.length), s5]); - return Buffer.concat([rPadded, sPadded]); - } - createDPoPInterceptor(middlewareStack) { - middlewareStack.add((next) => async (args) => { - if (protocolHttp.HttpRequest.isInstance(args.request)) { - const request = args.request; - const actualEndpoint = `${request.protocol}//${request.hostname}${request.port ? `:${request.port}` : ""}${request.path}`; - const dpop = await this.generateDpop(request.method, actualEndpoint); - request.headers = { - ...request.headers, - DPoP: dpop - }; - } - return next(args); - }, { - step: "finalizeRequest", - name: "dpopInterceptor", - override: true - }); - } - async generateDpop(method = "POST", endpoint) { - const token = await this.loadToken(); - try { - const privateKey = node_crypto.createPrivateKey({ - key: token.dpopKey, - format: "pem", - type: "sec1" - }); - const publicKey = node_crypto.createPublicKey(privateKey); - const publicDer = publicKey.export({ format: "der", type: "spki" }); - let pointStart = -1; - for (let i5 = 0; i5 < publicDer.length; i5++) { - if (publicDer[i5] === 4) { - pointStart = i5; - break; - } - } - const x5 = publicDer.slice(pointStart + 1, pointStart + 33); - const y2 = publicDer.slice(pointStart + 33, pointStart + 65); - const header = { - alg: "ES256", - typ: "dpop+jwt", - jwk: { - kty: "EC", - crv: "P-256", - x: x5.toString("base64url"), - y: y2.toString("base64url") - } - }; - const payload2 = { - jti: crypto.randomUUID(), - htm: method, - htu: endpoint, - iat: Math.floor(Date.now() / 1e3) - }; - const headerB64 = Buffer.from(JSON.stringify(header)).toString("base64url"); - const payloadB64 = Buffer.from(JSON.stringify(payload2)).toString("base64url"); - const message2 = `${headerB64}.${payloadB64}`; - const asn1Signature = node_crypto.sign("sha256", Buffer.from(message2), privateKey); - const rawSignature = this.derToRawSignature(asn1Signature); - const signatureB64 = rawSignature.toString("base64url"); - return `${message2}.${signatureB64}`; - } catch (error50) { - throw new propertyProvider.CredentialsProviderError(`Failed to generate Dpop proof: ${error50 instanceof Error ? error50.message : String(error50)}`, { logger: this.logger, tryNextLink: false }); - } - } - }; - var fromLoginCredentials = (init2) => async ({ callerClientConfig } = {}) => { - init2?.logger?.debug?.("@aws-sdk/credential-providers - fromLoginCredentials"); - const profiles = await sharedIniFileLoader.parseKnownFiles(init2 || {}); - const profileName = sharedIniFileLoader.getProfileName({ - profile: init2?.profile ?? callerClientConfig?.profile - }); - const profile = profiles[profileName]; - if (!profile?.login_session) { - throw new propertyProvider.CredentialsProviderError(`Profile ${profileName} does not contain login_session.`, { - tryNextLink: true, - logger: init2?.logger - }); - } - const fetcher = new LoginCredentialsFetcher(profile, init2, callerClientConfig); - const credentials = await fetcher.loadCredentials(); - return client2.setCredentialFeature(credentials, "CREDENTIALS_LOGIN", "AD"); - }; - exports.fromLoginCredentials = fromLoginCredentials; - } -}); - -// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/auth/httpAuthSchemeProvider.js -function createAwsAuthSigv4HttpAuthOption4(authParameters) { - return { - schemeId: "aws.auth#sigv4", - signingProperties: { - name: "sts", - region: authParameters.region - }, - propertiesExtractor: (config3, context) => ({ - signingProperties: { - config: config3, - context - } - }) - }; -} -function createSmithyApiNoAuthHttpAuthOption4(authParameters) { - return { - schemeId: "smithy.api#noAuth" - }; -} -var import_util_middleware9, defaultSTSHttpAuthSchemeParametersProvider, defaultSTSHttpAuthSchemeProvider, resolveStsAuthConfig, resolveHttpAuthSchemeConfig4; -var init_httpAuthSchemeProvider4 = __esm({ - "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/auth/httpAuthSchemeProvider.js"() { - init_httpAuthSchemes2(); - import_util_middleware9 = __toESM(require_dist_cjs18()); - init_STSClient(); - defaultSTSHttpAuthSchemeParametersProvider = async (config3, context, input) => { - return { - operation: (0, import_util_middleware9.getSmithyContext)(context).operation, - region: await (0, import_util_middleware9.normalizeProvider)(config3.region)() || (() => { - throw new Error("expected `region` to be configured for `aws.auth#sigv4`"); - })() - }; - }; - defaultSTSHttpAuthSchemeProvider = (authParameters) => { - const options = []; - switch (authParameters.operation) { - case "AssumeRoleWithWebIdentity": { - options.push(createSmithyApiNoAuthHttpAuthOption4(authParameters)); - break; - } - default: { - options.push(createAwsAuthSigv4HttpAuthOption4(authParameters)); - } - } - return options; - }; - resolveStsAuthConfig = (input) => Object.assign(input, { - stsClientCtor: STSClient - }); - resolveHttpAuthSchemeConfig4 = (config3) => { - const config_0 = resolveStsAuthConfig(config3); - const config_1 = resolveAwsSdkSigV4Config(config_0); - return Object.assign(config_1, { - authSchemePreference: (0, import_util_middleware9.normalizeProvider)(config3.authSchemePreference ?? []) - }); - }; - } -}); - -// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/endpoint/EndpointParameters.js -var resolveClientEndpointParameters4, commonParams4; -var init_EndpointParameters4 = __esm({ - "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/endpoint/EndpointParameters.js"() { - resolveClientEndpointParameters4 = (options) => { - return Object.assign(options, { - useDualstackEndpoint: options.useDualstackEndpoint ?? false, - useFipsEndpoint: options.useFipsEndpoint ?? false, - useGlobalEndpoint: options.useGlobalEndpoint ?? false, - defaultSigningName: "sts" - }); - }; - commonParams4 = { - UseGlobalEndpoint: { type: "builtInParams", name: "useGlobalEndpoint" }, - UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, - Endpoint: { type: "builtInParams", name: "endpoint" }, - Region: { type: "builtInParams", name: "region" }, - UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" } - }; - } -}); - -// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/endpoint/ruleset.js -var F, G, H, I, J, a4, b5, c4, d4, e4, f4, g4, h4, i4, j4, k4, l4, m4, n4, o4, p4, q4, r4, s4, t4, u4, v4, w4, x4, y, z, A, B, C, D, E, _data4, ruleSet4; -var init_ruleset4 = __esm({ - "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/endpoint/ruleset.js"() { - F = "required"; - G = "type"; - H = "fn"; - I = "argv"; - J = "ref"; - a4 = false; - b5 = true; - c4 = "booleanEquals"; - d4 = "stringEquals"; - e4 = "sigv4"; - f4 = "sts"; - g4 = "us-east-1"; - h4 = "endpoint"; - i4 = "https://sts.{Region}.{PartitionResult#dnsSuffix}"; - j4 = "tree"; - k4 = "error"; - l4 = "getAttr"; - m4 = { [F]: false, [G]: "string" }; - n4 = { [F]: true, default: false, [G]: "boolean" }; - o4 = { [J]: "Endpoint" }; - p4 = { [H]: "isSet", [I]: [{ [J]: "Region" }] }; - q4 = { [J]: "Region" }; - r4 = { [H]: "aws.partition", [I]: [q4], assign: "PartitionResult" }; - s4 = { [J]: "UseFIPS" }; - t4 = { [J]: "UseDualStack" }; - u4 = { - url: "https://sts.amazonaws.com", - properties: { authSchemes: [{ name: e4, signingName: f4, signingRegion: g4 }] }, - headers: {} - }; - v4 = {}; - w4 = { conditions: [{ [H]: d4, [I]: [q4, "aws-global"] }], [h4]: u4, [G]: h4 }; - x4 = { [H]: c4, [I]: [s4, true] }; - y = { [H]: c4, [I]: [t4, true] }; - z = { [H]: l4, [I]: [{ [J]: "PartitionResult" }, "supportsFIPS"] }; - A = { [J]: "PartitionResult" }; - B = { [H]: c4, [I]: [true, { [H]: l4, [I]: [A, "supportsDualStack"] }] }; - C = [{ [H]: "isSet", [I]: [o4] }]; - D = [x4]; - E = [y]; - _data4 = { - version: "1.0", - parameters: { Region: m4, UseDualStack: n4, UseFIPS: n4, Endpoint: m4, UseGlobalEndpoint: n4 }, - rules: [ - { - conditions: [ - { [H]: c4, [I]: [{ [J]: "UseGlobalEndpoint" }, b5] }, - { [H]: "not", [I]: C }, - p4, - r4, - { [H]: c4, [I]: [s4, a4] }, - { [H]: c4, [I]: [t4, a4] } - ], - rules: [ - { conditions: [{ [H]: d4, [I]: [q4, "ap-northeast-1"] }], endpoint: u4, [G]: h4 }, - { conditions: [{ [H]: d4, [I]: [q4, "ap-south-1"] }], endpoint: u4, [G]: h4 }, - { conditions: [{ [H]: d4, [I]: [q4, "ap-southeast-1"] }], endpoint: u4, [G]: h4 }, - { conditions: [{ [H]: d4, [I]: [q4, "ap-southeast-2"] }], endpoint: u4, [G]: h4 }, - w4, - { conditions: [{ [H]: d4, [I]: [q4, "ca-central-1"] }], endpoint: u4, [G]: h4 }, - { conditions: [{ [H]: d4, [I]: [q4, "eu-central-1"] }], endpoint: u4, [G]: h4 }, - { conditions: [{ [H]: d4, [I]: [q4, "eu-north-1"] }], endpoint: u4, [G]: h4 }, - { conditions: [{ [H]: d4, [I]: [q4, "eu-west-1"] }], endpoint: u4, [G]: h4 }, - { conditions: [{ [H]: d4, [I]: [q4, "eu-west-2"] }], endpoint: u4, [G]: h4 }, - { conditions: [{ [H]: d4, [I]: [q4, "eu-west-3"] }], endpoint: u4, [G]: h4 }, - { conditions: [{ [H]: d4, [I]: [q4, "sa-east-1"] }], endpoint: u4, [G]: h4 }, - { conditions: [{ [H]: d4, [I]: [q4, g4] }], endpoint: u4, [G]: h4 }, - { conditions: [{ [H]: d4, [I]: [q4, "us-east-2"] }], endpoint: u4, [G]: h4 }, - { conditions: [{ [H]: d4, [I]: [q4, "us-west-1"] }], endpoint: u4, [G]: h4 }, - { conditions: [{ [H]: d4, [I]: [q4, "us-west-2"] }], endpoint: u4, [G]: h4 }, - { - endpoint: { - url: i4, - properties: { authSchemes: [{ name: e4, signingName: f4, signingRegion: "{Region}" }] }, - headers: v4 - }, - [G]: h4 - } - ], - [G]: j4 - }, - { - conditions: C, - rules: [ - { conditions: D, error: "Invalid Configuration: FIPS and custom endpoint are not supported", [G]: k4 }, - { conditions: E, error: "Invalid Configuration: Dualstack and custom endpoint are not supported", [G]: k4 }, - { endpoint: { url: o4, properties: v4, headers: v4 }, [G]: h4 } - ], - [G]: j4 - }, - { - conditions: [p4], - rules: [ - { - conditions: [r4], - rules: [ - { - conditions: [x4, y], - rules: [ - { - conditions: [{ [H]: c4, [I]: [b5, z] }, B], - rules: [ - { - endpoint: { - url: "https://sts-fips.{Region}.{PartitionResult#dualStackDnsSuffix}", - properties: v4, - headers: v4 - }, - [G]: h4 - } - ], - [G]: j4 - }, - { error: "FIPS and DualStack are enabled, but this partition does not support one or both", [G]: k4 } - ], - [G]: j4 - }, - { - conditions: D, - rules: [ - { - conditions: [{ [H]: c4, [I]: [z, b5] }], - rules: [ - { - conditions: [{ [H]: d4, [I]: [{ [H]: l4, [I]: [A, "name"] }, "aws-us-gov"] }], - endpoint: { url: "https://sts.{Region}.amazonaws.com", properties: v4, headers: v4 }, - [G]: h4 - }, - { - endpoint: { - url: "https://sts-fips.{Region}.{PartitionResult#dnsSuffix}", - properties: v4, - headers: v4 - }, - [G]: h4 - } - ], - [G]: j4 - }, - { error: "FIPS is enabled but this partition does not support FIPS", [G]: k4 } - ], - [G]: j4 - }, - { - conditions: E, - rules: [ - { - conditions: [B], - rules: [ - { - endpoint: { - url: "https://sts.{Region}.{PartitionResult#dualStackDnsSuffix}", - properties: v4, - headers: v4 - }, - [G]: h4 - } - ], - [G]: j4 - }, - { error: "DualStack is enabled but this partition does not support DualStack", [G]: k4 } - ], - [G]: j4 - }, - w4, - { endpoint: { url: i4, properties: v4, headers: v4 }, [G]: h4 } - ], - [G]: j4 - } - ], - [G]: j4 - }, - { error: "Invalid Configuration: Missing Region", [G]: k4 } - ] - }; - ruleSet4 = _data4; - } -}); - -// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/endpoint/endpointResolver.js -var import_util_endpoints7, import_util_endpoints8, cache4, defaultEndpointResolver4; -var init_endpointResolver4 = __esm({ - "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/endpoint/endpointResolver.js"() { - import_util_endpoints7 = __toESM(require_dist_cjs34()); - import_util_endpoints8 = __toESM(require_dist_cjs33()); - init_ruleset4(); - cache4 = new import_util_endpoints8.EndpointCache({ - size: 50, - params: ["Endpoint", "Region", "UseDualStack", "UseFIPS", "UseGlobalEndpoint"] - }); - defaultEndpointResolver4 = (endpointParams, context = {}) => { - return cache4.get(endpointParams, () => (0, import_util_endpoints8.resolveEndpoint)(ruleSet4, { - endpointParams, - logger: context.logger - })); - }; - import_util_endpoints8.customEndpointFunctions.aws = import_util_endpoints7.awsEndpointFunctions; - } -}); - -// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/models/STSServiceException.js -var import_smithy_client29, STSServiceException; -var init_STSServiceException = __esm({ - "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/models/STSServiceException.js"() { - import_smithy_client29 = __toESM(require_dist_cjs27()); - STSServiceException = class _STSServiceException extends import_smithy_client29.ServiceException { - constructor(options) { - super(options); - Object.setPrototypeOf(this, _STSServiceException.prototype); - } - }; - } -}); - -// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/models/errors.js -var ExpiredTokenException2, MalformedPolicyDocumentException, PackedPolicyTooLargeException, RegionDisabledException, IDPRejectedClaimException, InvalidIdentityTokenException, IDPCommunicationErrorException; -var init_errors6 = __esm({ - "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/models/errors.js"() { - init_STSServiceException(); - ExpiredTokenException2 = class _ExpiredTokenException extends STSServiceException { - name = "ExpiredTokenException"; - $fault = "client"; - constructor(opts) { - super({ - name: "ExpiredTokenException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _ExpiredTokenException.prototype); - } - }; - MalformedPolicyDocumentException = class _MalformedPolicyDocumentException extends STSServiceException { - name = "MalformedPolicyDocumentException"; - $fault = "client"; - constructor(opts) { - super({ - name: "MalformedPolicyDocumentException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _MalformedPolicyDocumentException.prototype); - } - }; - PackedPolicyTooLargeException = class _PackedPolicyTooLargeException extends STSServiceException { - name = "PackedPolicyTooLargeException"; - $fault = "client"; - constructor(opts) { - super({ - name: "PackedPolicyTooLargeException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _PackedPolicyTooLargeException.prototype); - } - }; - RegionDisabledException = class _RegionDisabledException extends STSServiceException { - name = "RegionDisabledException"; - $fault = "client"; - constructor(opts) { - super({ - name: "RegionDisabledException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _RegionDisabledException.prototype); - } - }; - IDPRejectedClaimException = class _IDPRejectedClaimException extends STSServiceException { - name = "IDPRejectedClaimException"; - $fault = "client"; - constructor(opts) { - super({ - name: "IDPRejectedClaimException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _IDPRejectedClaimException.prototype); - } - }; - InvalidIdentityTokenException = class _InvalidIdentityTokenException extends STSServiceException { - name = "InvalidIdentityTokenException"; - $fault = "client"; - constructor(opts) { - super({ - name: "InvalidIdentityTokenException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _InvalidIdentityTokenException.prototype); - } - }; - IDPCommunicationErrorException = class _IDPCommunicationErrorException extends STSServiceException { - name = "IDPCommunicationErrorException"; - $fault = "client"; - constructor(opts) { - super({ - name: "IDPCommunicationErrorException", - $fault: "client", - ...opts - }); - Object.setPrototypeOf(this, _IDPCommunicationErrorException.prototype); - } - }; - } -}); - -// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/schemas/schemas_0.js -var _A, _AKI, _AR, _ARI, _ARR, _ARRs, _ARU, _ARWWI, _ARWWIR, _ARWWIRs, _Au, _C, _CA, _DS, _E, _EI, _ETE2, _IDPCEE, _IDPRCE, _IITE, _K, _MPDE, _P, _PA, _PAr, _PC, _PCLT, _PCr, _PDT, _PI, _PPS, _PPTLE, _Pr, _RA, _RDE, _RSN, _SAK, _SFWIT, _SI, _SN, _ST, _T, _TC, _TTK, _Ta, _V, _WIT, _a, _aKST, _aQE, _c4, _cTT, _e4, _hE4, _m3, _pDLT, _s4, _tLT, n04, _s_registry4, STSServiceException$, n0_registry4, ExpiredTokenException$2, IDPCommunicationErrorException$, IDPRejectedClaimException$, InvalidIdentityTokenException$, MalformedPolicyDocumentException$, PackedPolicyTooLargeException$, RegionDisabledException$, errorTypeRegistries4, accessKeySecretType, clientTokenType, AssumedRoleUser$, AssumeRoleRequest$, AssumeRoleResponse$, AssumeRoleWithWebIdentityRequest$, AssumeRoleWithWebIdentityResponse$, Credentials$, PolicyDescriptorType$, ProvidedContext$, Tag$, policyDescriptorListType, ProvidedContextsListType, tagKeyListType, tagListType, AssumeRole$, AssumeRoleWithWebIdentity$; -var init_schemas_04 = __esm({ - "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/schemas/schemas_0.js"() { - init_schema3(); - init_errors6(); - init_STSServiceException(); - _A = "Arn"; - _AKI = "AccessKeyId"; - _AR = "AssumeRole"; - _ARI = "AssumedRoleId"; - _ARR = "AssumeRoleRequest"; - _ARRs = "AssumeRoleResponse"; - _ARU = "AssumedRoleUser"; - _ARWWI = "AssumeRoleWithWebIdentity"; - _ARWWIR = "AssumeRoleWithWebIdentityRequest"; - _ARWWIRs = "AssumeRoleWithWebIdentityResponse"; - _Au = "Audience"; - _C = "Credentials"; - _CA = "ContextAssertion"; - _DS = "DurationSeconds"; - _E = "Expiration"; - _EI = "ExternalId"; - _ETE2 = "ExpiredTokenException"; - _IDPCEE = "IDPCommunicationErrorException"; - _IDPRCE = "IDPRejectedClaimException"; - _IITE = "InvalidIdentityTokenException"; - _K = "Key"; - _MPDE = "MalformedPolicyDocumentException"; - _P = "Policy"; - _PA = "PolicyArns"; - _PAr = "ProviderArn"; - _PC = "ProvidedContexts"; - _PCLT = "ProvidedContextsListType"; - _PCr = "ProvidedContext"; - _PDT = "PolicyDescriptorType"; - _PI = "ProviderId"; - _PPS = "PackedPolicySize"; - _PPTLE = "PackedPolicyTooLargeException"; - _Pr = "Provider"; - _RA = "RoleArn"; - _RDE = "RegionDisabledException"; - _RSN = "RoleSessionName"; - _SAK = "SecretAccessKey"; - _SFWIT = "SubjectFromWebIdentityToken"; - _SI = "SourceIdentity"; - _SN = "SerialNumber"; - _ST = "SessionToken"; - _T = "Tags"; - _TC = "TokenCode"; - _TTK = "TransitiveTagKeys"; - _Ta = "Tag"; - _V = "Value"; - _WIT = "WebIdentityToken"; - _a = "arn"; - _aKST = "accessKeySecretType"; - _aQE = "awsQueryError"; - _c4 = "client"; - _cTT = "clientTokenType"; - _e4 = "error"; - _hE4 = "httpError"; - _m3 = "message"; - _pDLT = "policyDescriptorListType"; - _s4 = "smithy.ts.sdk.synthetic.com.amazonaws.sts"; - _tLT = "tagListType"; - n04 = "com.amazonaws.sts"; - _s_registry4 = TypeRegistry.for(_s4); - STSServiceException$ = [-3, _s4, "STSServiceException", 0, [], []]; - _s_registry4.registerError(STSServiceException$, STSServiceException); - n0_registry4 = TypeRegistry.for(n04); - ExpiredTokenException$2 = [ - -3, - n04, - _ETE2, - { [_aQE]: [`ExpiredTokenException`, 400], [_e4]: _c4, [_hE4]: 400 }, - [_m3], - [0] - ]; - n0_registry4.registerError(ExpiredTokenException$2, ExpiredTokenException2); - IDPCommunicationErrorException$ = [ - -3, - n04, - _IDPCEE, - { [_aQE]: [`IDPCommunicationError`, 400], [_e4]: _c4, [_hE4]: 400 }, - [_m3], - [0] - ]; - n0_registry4.registerError(IDPCommunicationErrorException$, IDPCommunicationErrorException); - IDPRejectedClaimException$ = [ - -3, - n04, - _IDPRCE, - { [_aQE]: [`IDPRejectedClaim`, 403], [_e4]: _c4, [_hE4]: 403 }, - [_m3], - [0] - ]; - n0_registry4.registerError(IDPRejectedClaimException$, IDPRejectedClaimException); - InvalidIdentityTokenException$ = [ - -3, - n04, - _IITE, - { [_aQE]: [`InvalidIdentityToken`, 400], [_e4]: _c4, [_hE4]: 400 }, - [_m3], - [0] - ]; - n0_registry4.registerError(InvalidIdentityTokenException$, InvalidIdentityTokenException); - MalformedPolicyDocumentException$ = [ - -3, - n04, - _MPDE, - { [_aQE]: [`MalformedPolicyDocument`, 400], [_e4]: _c4, [_hE4]: 400 }, - [_m3], - [0] - ]; - n0_registry4.registerError(MalformedPolicyDocumentException$, MalformedPolicyDocumentException); - PackedPolicyTooLargeException$ = [ - -3, - n04, - _PPTLE, - { [_aQE]: [`PackedPolicyTooLarge`, 400], [_e4]: _c4, [_hE4]: 400 }, - [_m3], - [0] - ]; - n0_registry4.registerError(PackedPolicyTooLargeException$, PackedPolicyTooLargeException); - RegionDisabledException$ = [ - -3, - n04, - _RDE, - { [_aQE]: [`RegionDisabledException`, 403], [_e4]: _c4, [_hE4]: 403 }, - [_m3], - [0] - ]; - n0_registry4.registerError(RegionDisabledException$, RegionDisabledException); - errorTypeRegistries4 = [_s_registry4, n0_registry4]; - accessKeySecretType = [0, n04, _aKST, 8, 0]; - clientTokenType = [0, n04, _cTT, 8, 0]; - AssumedRoleUser$ = [3, n04, _ARU, 0, [_ARI, _A], [0, 0], 2]; - AssumeRoleRequest$ = [ - 3, - n04, - _ARR, - 0, - [_RA, _RSN, _PA, _P, _DS, _T, _TTK, _EI, _SN, _TC, _SI, _PC], - [0, 0, () => policyDescriptorListType, 0, 1, () => tagListType, 64 | 0, 0, 0, 0, 0, () => ProvidedContextsListType], - 2 - ]; - AssumeRoleResponse$ = [ - 3, - n04, - _ARRs, - 0, - [_C, _ARU, _PPS, _SI], - [[() => Credentials$, 0], () => AssumedRoleUser$, 1, 0] - ]; - AssumeRoleWithWebIdentityRequest$ = [ - 3, - n04, - _ARWWIR, - 0, - [_RA, _RSN, _WIT, _PI, _PA, _P, _DS], - [0, 0, [() => clientTokenType, 0], 0, () => policyDescriptorListType, 0, 1], - 3 - ]; - AssumeRoleWithWebIdentityResponse$ = [ - 3, - n04, - _ARWWIRs, - 0, - [_C, _SFWIT, _ARU, _PPS, _Pr, _Au, _SI], - [[() => Credentials$, 0], 0, () => AssumedRoleUser$, 1, 0, 0, 0] - ]; - Credentials$ = [ - 3, - n04, - _C, - 0, - [_AKI, _SAK, _ST, _E], - [0, [() => accessKeySecretType, 0], 0, 4], - 4 - ]; - PolicyDescriptorType$ = [3, n04, _PDT, 0, [_a], [0]]; - ProvidedContext$ = [3, n04, _PCr, 0, [_PAr, _CA], [0, 0]]; - Tag$ = [3, n04, _Ta, 0, [_K, _V], [0, 0], 2]; - policyDescriptorListType = [1, n04, _pDLT, 0, () => PolicyDescriptorType$]; - ProvidedContextsListType = [1, n04, _PCLT, 0, () => ProvidedContext$]; - tagKeyListType = 64 | 0; - tagListType = [1, n04, _tLT, 0, () => Tag$]; - AssumeRole$ = [9, n04, _AR, 0, () => AssumeRoleRequest$, () => AssumeRoleResponse$]; - AssumeRoleWithWebIdentity$ = [ - 9, - n04, - _ARWWI, - 0, - () => AssumeRoleWithWebIdentityRequest$, - () => AssumeRoleWithWebIdentityResponse$ - ]; - } -}); - -// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/runtimeConfig.shared.js -var import_smithy_client30, import_url_parser5, import_util_base6411, import_util_utf811, getRuntimeConfig7; -var init_runtimeConfig_shared4 = __esm({ - "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/runtimeConfig.shared.js"() { - init_httpAuthSchemes2(); - init_protocols2(); - init_dist_es(); - import_smithy_client30 = __toESM(require_dist_cjs27()); - import_url_parser5 = __toESM(require_dist_cjs25()); - import_util_base6411 = __toESM(require_dist_cjs7()); - import_util_utf811 = __toESM(require_dist_cjs6()); - init_httpAuthSchemeProvider4(); - init_endpointResolver4(); - init_schemas_04(); - getRuntimeConfig7 = (config3) => { - return { - apiVersion: "2011-06-15", - base64Decoder: config3?.base64Decoder ?? import_util_base6411.fromBase64, - base64Encoder: config3?.base64Encoder ?? import_util_base6411.toBase64, - disableHostPrefix: config3?.disableHostPrefix ?? false, - endpointProvider: config3?.endpointProvider ?? defaultEndpointResolver4, - extensions: config3?.extensions ?? [], - httpAuthSchemeProvider: config3?.httpAuthSchemeProvider ?? defaultSTSHttpAuthSchemeProvider, - httpAuthSchemes: config3?.httpAuthSchemes ?? [ - { - schemeId: "aws.auth#sigv4", - identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"), - signer: new AwsSdkSigV4Signer() - }, - { - schemeId: "smithy.api#noAuth", - identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})), - signer: new NoAuthSigner() - } - ], - logger: config3?.logger ?? new import_smithy_client30.NoOpLogger(), - protocol: config3?.protocol ?? AwsQueryProtocol, - protocolSettings: config3?.protocolSettings ?? { - defaultNamespace: "com.amazonaws.sts", - errorTypeRegistries: errorTypeRegistries4, - xmlNamespace: "https://sts.amazonaws.com/doc/2011-06-15/", - version: "2011-06-15", - serviceTarget: "AWSSecurityTokenServiceV20110615" - }, - serviceId: config3?.serviceId ?? "STS", - urlParser: config3?.urlParser ?? import_url_parser5.parseUrl, - utf8Decoder: config3?.utf8Decoder ?? import_util_utf811.fromUtf8, - utf8Encoder: config3?.utf8Encoder ?? import_util_utf811.toUtf8 - }; - }; - } -}); - -// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/runtimeConfig.js -var import_util_user_agent_node4, import_config_resolver7, import_hash_node4, import_middleware_retry7, import_node_config_provider4, import_node_http_handler4, import_smithy_client31, import_util_body_length_node4, import_util_defaults_mode_node4, import_util_retry4, getRuntimeConfig8; -var init_runtimeConfig4 = __esm({ - "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/runtimeConfig.js"() { - init_package(); - init_client2(); - init_httpAuthSchemes2(); - import_util_user_agent_node4 = __toESM(require_dist_cjs51()); - import_config_resolver7 = __toESM(require_dist_cjs38()); - init_dist_es(); - import_hash_node4 = __toESM(require_dist_cjs52()); - import_middleware_retry7 = __toESM(require_dist_cjs46()); - import_node_config_provider4 = __toESM(require_dist_cjs43()); - import_node_http_handler4 = __toESM(require_dist_cjs10()); - import_smithy_client31 = __toESM(require_dist_cjs27()); - import_util_body_length_node4 = __toESM(require_dist_cjs53()); - import_util_defaults_mode_node4 = __toESM(require_dist_cjs54()); - import_util_retry4 = __toESM(require_dist_cjs36()); - init_runtimeConfig_shared4(); - getRuntimeConfig8 = (config3) => { - (0, import_smithy_client31.emitWarningIfUnsupportedVersion)(process.version); - const defaultsMode = (0, import_util_defaults_mode_node4.resolveDefaultsModeConfig)(config3); - const defaultConfigProvider = () => defaultsMode().then(import_smithy_client31.loadConfigsForDefaultMode); - const clientSharedValues = getRuntimeConfig7(config3); - emitWarningIfUnsupportedVersion(process.version); - const loaderConfig = { - profile: config3?.profile, - logger: clientSharedValues.logger - }; - return { - ...clientSharedValues, - ...config3, - runtime: "node", - defaultsMode, - authSchemePreference: config3?.authSchemePreference ?? (0, import_node_config_provider4.loadConfig)(NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig), - bodyLengthChecker: config3?.bodyLengthChecker ?? import_util_body_length_node4.calculateBodyLength, - defaultUserAgentProvider: config3?.defaultUserAgentProvider ?? (0, import_util_user_agent_node4.createDefaultUserAgentProvider)({ serviceId: clientSharedValues.serviceId, clientVersion: package_default.version }), - httpAuthSchemes: config3?.httpAuthSchemes ?? [ - { - schemeId: "aws.auth#sigv4", - identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4") || (async (idProps) => await config3.credentialDefaultProvider(idProps?.__config || {})()), - signer: new AwsSdkSigV4Signer() - }, - { - schemeId: "smithy.api#noAuth", - identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})), - signer: new NoAuthSigner() - } - ], - maxAttempts: config3?.maxAttempts ?? (0, import_node_config_provider4.loadConfig)(import_middleware_retry7.NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config3), - region: config3?.region ?? (0, import_node_config_provider4.loadConfig)(import_config_resolver7.NODE_REGION_CONFIG_OPTIONS, { ...import_config_resolver7.NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }), - requestHandler: import_node_http_handler4.NodeHttpHandler.create(config3?.requestHandler ?? defaultConfigProvider), - retryMode: config3?.retryMode ?? (0, import_node_config_provider4.loadConfig)({ - ...import_middleware_retry7.NODE_RETRY_MODE_CONFIG_OPTIONS, - default: async () => (await defaultConfigProvider()).retryMode || import_util_retry4.DEFAULT_RETRY_MODE - }, config3), - sha256: config3?.sha256 ?? import_hash_node4.Hash.bind(null, "sha256"), - streamCollector: config3?.streamCollector ?? import_node_http_handler4.streamCollector, - useDualstackEndpoint: config3?.useDualstackEndpoint ?? (0, import_node_config_provider4.loadConfig)(import_config_resolver7.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig), - useFipsEndpoint: config3?.useFipsEndpoint ?? (0, import_node_config_provider4.loadConfig)(import_config_resolver7.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig), - userAgentAppId: config3?.userAgentAppId ?? (0, import_node_config_provider4.loadConfig)(import_util_user_agent_node4.NODE_APP_ID_CONFIG_OPTIONS, loaderConfig) - }; - }; - } -}); - -// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/auth/httpAuthExtensionConfiguration.js -var getHttpAuthExtensionConfiguration4, resolveHttpAuthRuntimeConfig4; -var init_httpAuthExtensionConfiguration4 = __esm({ - "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/auth/httpAuthExtensionConfiguration.js"() { - getHttpAuthExtensionConfiguration4 = (runtimeConfig) => { - const _httpAuthSchemes = runtimeConfig.httpAuthSchemes; - let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider; - let _credentials = runtimeConfig.credentials; - return { - setHttpAuthScheme(httpAuthScheme) { - const index2 = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId); - if (index2 === -1) { - _httpAuthSchemes.push(httpAuthScheme); - } else { - _httpAuthSchemes.splice(index2, 1, httpAuthScheme); - } - }, - httpAuthSchemes() { - return _httpAuthSchemes; - }, - setHttpAuthSchemeProvider(httpAuthSchemeProvider) { - _httpAuthSchemeProvider = httpAuthSchemeProvider; - }, - httpAuthSchemeProvider() { - return _httpAuthSchemeProvider; - }, - setCredentials(credentials) { - _credentials = credentials; - }, - credentials() { - return _credentials; - } - }; - }; - resolveHttpAuthRuntimeConfig4 = (config3) => { - return { - httpAuthSchemes: config3.httpAuthSchemes(), - httpAuthSchemeProvider: config3.httpAuthSchemeProvider(), - credentials: config3.credentials() - }; - }; - } -}); - -// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/runtimeExtensions.js -var import_region_config_resolver4, import_protocol_http15, import_smithy_client32, resolveRuntimeExtensions4; -var init_runtimeExtensions4 = __esm({ - "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/runtimeExtensions.js"() { - import_region_config_resolver4 = __toESM(require_dist_cjs55()); - import_protocol_http15 = __toESM(require_dist_cjs2()); - import_smithy_client32 = __toESM(require_dist_cjs27()); - init_httpAuthExtensionConfiguration4(); - resolveRuntimeExtensions4 = (runtimeConfig, extensions) => { - const extensionConfiguration = Object.assign((0, import_region_config_resolver4.getAwsRegionExtensionConfiguration)(runtimeConfig), (0, import_smithy_client32.getDefaultExtensionConfiguration)(runtimeConfig), (0, import_protocol_http15.getHttpHandlerExtensionConfiguration)(runtimeConfig), getHttpAuthExtensionConfiguration4(runtimeConfig)); - extensions.forEach((extension2) => extension2.configure(extensionConfiguration)); - return Object.assign(runtimeConfig, (0, import_region_config_resolver4.resolveAwsRegionExtensionConfiguration)(extensionConfiguration), (0, import_smithy_client32.resolveDefaultRuntimeConfig)(extensionConfiguration), (0, import_protocol_http15.resolveHttpHandlerRuntimeConfig)(extensionConfiguration), resolveHttpAuthRuntimeConfig4(extensionConfiguration)); - }; - } -}); - -// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/STSClient.js -var import_middleware_host_header4, import_middleware_logger4, import_middleware_recursion_detection4, import_middleware_user_agent4, import_config_resolver8, import_middleware_content_length4, import_middleware_endpoint7, import_middleware_retry8, import_smithy_client33, STSClient; -var init_STSClient = __esm({ - "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/STSClient.js"() { - import_middleware_host_header4 = __toESM(require_dist_cjs20()); - import_middleware_logger4 = __toESM(require_dist_cjs21()); - import_middleware_recursion_detection4 = __toESM(require_dist_cjs22()); - import_middleware_user_agent4 = __toESM(require_dist_cjs37()); - import_config_resolver8 = __toESM(require_dist_cjs38()); - init_dist_es(); - init_schema3(); - import_middleware_content_length4 = __toESM(require_dist_cjs40()); - import_middleware_endpoint7 = __toESM(require_dist_cjs45()); - import_middleware_retry8 = __toESM(require_dist_cjs46()); - import_smithy_client33 = __toESM(require_dist_cjs27()); - init_httpAuthSchemeProvider4(); - init_EndpointParameters4(); - init_runtimeConfig4(); - init_runtimeExtensions4(); - STSClient = class extends import_smithy_client33.Client { - config; - constructor(...[configuration]) { - const _config_0 = getRuntimeConfig8(configuration || {}); - super(_config_0); - this.initConfig = _config_0; - const _config_1 = resolveClientEndpointParameters4(_config_0); - const _config_2 = (0, import_middleware_user_agent4.resolveUserAgentConfig)(_config_1); - const _config_3 = (0, import_middleware_retry8.resolveRetryConfig)(_config_2); - const _config_4 = (0, import_config_resolver8.resolveRegionConfig)(_config_3); - const _config_5 = (0, import_middleware_host_header4.resolveHostHeaderConfig)(_config_4); - const _config_6 = (0, import_middleware_endpoint7.resolveEndpointConfig)(_config_5); - const _config_7 = resolveHttpAuthSchemeConfig4(_config_6); - const _config_8 = resolveRuntimeExtensions4(_config_7, configuration?.extensions || []); - this.config = _config_8; - this.middlewareStack.use(getSchemaSerdePlugin(this.config)); - this.middlewareStack.use((0, import_middleware_user_agent4.getUserAgentPlugin)(this.config)); - this.middlewareStack.use((0, import_middleware_retry8.getRetryPlugin)(this.config)); - this.middlewareStack.use((0, import_middleware_content_length4.getContentLengthPlugin)(this.config)); - this.middlewareStack.use((0, import_middleware_host_header4.getHostHeaderPlugin)(this.config)); - this.middlewareStack.use((0, import_middleware_logger4.getLoggerPlugin)(this.config)); - this.middlewareStack.use((0, import_middleware_recursion_detection4.getRecursionDetectionPlugin)(this.config)); - this.middlewareStack.use(getHttpAuthSchemeEndpointRuleSetPlugin(this.config, { - httpAuthSchemeParametersProvider: defaultSTSHttpAuthSchemeParametersProvider, - identityProviderConfigProvider: async (config3) => new DefaultIdentityProviderConfig({ - "aws.auth#sigv4": config3.credentials - }) - })); - this.middlewareStack.use(getHttpSigningPlugin(this.config)); - } - destroy() { - super.destroy(); - } - }; - } -}); - -// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/commands/AssumeRoleCommand.js -var import_middleware_endpoint8, import_smithy_client34, AssumeRoleCommand; -var init_AssumeRoleCommand = __esm({ - "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/commands/AssumeRoleCommand.js"() { - import_middleware_endpoint8 = __toESM(require_dist_cjs45()); - import_smithy_client34 = __toESM(require_dist_cjs27()); - init_EndpointParameters4(); - init_schemas_04(); - AssumeRoleCommand = class extends import_smithy_client34.Command.classBuilder().ep(commonParams4).m(function(Command2, cs, config3, o5) { - return [(0, import_middleware_endpoint8.getEndpointPlugin)(config3, Command2.getEndpointParameterInstructions())]; - }).s("AWSSecurityTokenServiceV20110615", "AssumeRole", {}).n("STSClient", "AssumeRoleCommand").sc(AssumeRole$).build() { - }; - } -}); - -// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/commands/AssumeRoleWithWebIdentityCommand.js -var import_middleware_endpoint9, import_smithy_client35, AssumeRoleWithWebIdentityCommand; -var init_AssumeRoleWithWebIdentityCommand = __esm({ - "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/commands/AssumeRoleWithWebIdentityCommand.js"() { - import_middleware_endpoint9 = __toESM(require_dist_cjs45()); - import_smithy_client35 = __toESM(require_dist_cjs27()); - init_EndpointParameters4(); - init_schemas_04(); - AssumeRoleWithWebIdentityCommand = class extends import_smithy_client35.Command.classBuilder().ep(commonParams4).m(function(Command2, cs, config3, o5) { - return [(0, import_middleware_endpoint9.getEndpointPlugin)(config3, Command2.getEndpointParameterInstructions())]; - }).s("AWSSecurityTokenServiceV20110615", "AssumeRoleWithWebIdentity", {}).n("STSClient", "AssumeRoleWithWebIdentityCommand").sc(AssumeRoleWithWebIdentity$).build() { - }; - } -}); - -// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/STS.js -var import_smithy_client36, commands4, STS; -var init_STS = __esm({ - "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/STS.js"() { - import_smithy_client36 = __toESM(require_dist_cjs27()); - init_AssumeRoleCommand(); - init_AssumeRoleWithWebIdentityCommand(); - init_STSClient(); - commands4 = { - AssumeRoleCommand, - AssumeRoleWithWebIdentityCommand - }; - STS = class extends STSClient { - }; - (0, import_smithy_client36.createAggregatedClient)(commands4, STS); - } -}); - -// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/commands/index.js -var init_commands4 = __esm({ - "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/commands/index.js"() { - init_AssumeRoleCommand(); - init_AssumeRoleWithWebIdentityCommand(); - } -}); - -// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/models/models_0.js -var init_models_04 = __esm({ - "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/models/models_0.js"() { - } -}); - -// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/defaultStsRoleAssumers.js -var import_region_config_resolver5, getAccountIdFromAssumedRoleUser, resolveRegion, getDefaultRoleAssumer, getDefaultRoleAssumerWithWebIdentity, isH2; -var init_defaultStsRoleAssumers = __esm({ - "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/defaultStsRoleAssumers.js"() { - init_client2(); - import_region_config_resolver5 = __toESM(require_dist_cjs55()); - init_AssumeRoleCommand(); - init_AssumeRoleWithWebIdentityCommand(); - getAccountIdFromAssumedRoleUser = (assumedRoleUser) => { - if (typeof assumedRoleUser?.Arn === "string") { - const arnComponents = assumedRoleUser.Arn.split(":"); - if (arnComponents.length > 4 && arnComponents[4] !== "") { - return arnComponents[4]; - } - } - return void 0; - }; - resolveRegion = async (_region, _parentRegion, credentialProviderLogger, loaderConfig = {}) => { - const region = typeof _region === "function" ? await _region() : _region; - const parentRegion = typeof _parentRegion === "function" ? await _parentRegion() : _parentRegion; - let stsDefaultRegion = ""; - const resolvedRegion = region ?? parentRegion ?? (stsDefaultRegion = await (0, import_region_config_resolver5.stsRegionDefaultResolver)(loaderConfig)()); - credentialProviderLogger?.debug?.("@aws-sdk/client-sts::resolveRegion", "accepting first of:", `${region} (credential provider clientConfig)`, `${parentRegion} (contextual client)`, `${stsDefaultRegion} (STS default: AWS_REGION, profile region, or us-east-1)`); - return resolvedRegion; - }; - getDefaultRoleAssumer = (stsOptions, STSClient2) => { - let stsClient; - let closureSourceCreds; - return async (sourceCreds, params) => { - closureSourceCreds = sourceCreds; - if (!stsClient) { - const { logger: logger4 = stsOptions?.parentClientConfig?.logger, profile = stsOptions?.parentClientConfig?.profile, region, requestHandler = stsOptions?.parentClientConfig?.requestHandler, credentialProviderLogger, userAgentAppId = stsOptions?.parentClientConfig?.userAgentAppId } = stsOptions; - const resolvedRegion = await resolveRegion(region, stsOptions?.parentClientConfig?.region, credentialProviderLogger, { - logger: logger4, - profile - }); - const isCompatibleRequestHandler = !isH2(requestHandler); - stsClient = new STSClient2({ - ...stsOptions, - userAgentAppId, - profile, - credentialDefaultProvider: () => async () => closureSourceCreds, - region: resolvedRegion, - requestHandler: isCompatibleRequestHandler ? requestHandler : void 0, - logger: logger4 - }); - } - const { Credentials, AssumedRoleUser } = await stsClient.send(new AssumeRoleCommand(params)); - if (!Credentials || !Credentials.AccessKeyId || !Credentials.SecretAccessKey) { - throw new Error(`Invalid response from STS.assumeRole call with role ${params.RoleArn}`); - } - const accountId = getAccountIdFromAssumedRoleUser(AssumedRoleUser); - const credentials = { - accessKeyId: Credentials.AccessKeyId, - secretAccessKey: Credentials.SecretAccessKey, - sessionToken: Credentials.SessionToken, - expiration: Credentials.Expiration, - ...Credentials.CredentialScope && { credentialScope: Credentials.CredentialScope }, - ...accountId && { accountId } - }; - setCredentialFeature(credentials, "CREDENTIALS_STS_ASSUME_ROLE", "i"); - return credentials; - }; - }; - getDefaultRoleAssumerWithWebIdentity = (stsOptions, STSClient2) => { - let stsClient; - return async (params) => { - if (!stsClient) { - const { logger: logger4 = stsOptions?.parentClientConfig?.logger, profile = stsOptions?.parentClientConfig?.profile, region, requestHandler = stsOptions?.parentClientConfig?.requestHandler, credentialProviderLogger, userAgentAppId = stsOptions?.parentClientConfig?.userAgentAppId } = stsOptions; - const resolvedRegion = await resolveRegion(region, stsOptions?.parentClientConfig?.region, credentialProviderLogger, { - logger: logger4, - profile - }); - const isCompatibleRequestHandler = !isH2(requestHandler); - stsClient = new STSClient2({ - ...stsOptions, - userAgentAppId, - profile, - region: resolvedRegion, - requestHandler: isCompatibleRequestHandler ? requestHandler : void 0, - logger: logger4 - }); - } - const { Credentials, AssumedRoleUser } = await stsClient.send(new AssumeRoleWithWebIdentityCommand(params)); - if (!Credentials || !Credentials.AccessKeyId || !Credentials.SecretAccessKey) { - throw new Error(`Invalid response from STS.assumeRoleWithWebIdentity call with role ${params.RoleArn}`); - } - const accountId = getAccountIdFromAssumedRoleUser(AssumedRoleUser); - const credentials = { - accessKeyId: Credentials.AccessKeyId, - secretAccessKey: Credentials.SecretAccessKey, - sessionToken: Credentials.SessionToken, - expiration: Credentials.Expiration, - ...Credentials.CredentialScope && { credentialScope: Credentials.CredentialScope }, - ...accountId && { accountId } - }; - if (accountId) { - setCredentialFeature(credentials, "RESOLVED_ACCOUNT_ID", "T"); - } - setCredentialFeature(credentials, "CREDENTIALS_STS_ASSUME_ROLE_WEB_ID", "k"); - return credentials; - }; - }; - isH2 = (requestHandler) => { - return requestHandler?.metadata?.handlerProtocol === "h2"; - }; - } -}); - -// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/defaultRoleAssumers.js -var getCustomizableStsClientCtor, getDefaultRoleAssumer2, getDefaultRoleAssumerWithWebIdentity2, decorateDefaultCredentialProvider; -var init_defaultRoleAssumers = __esm({ - "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/defaultRoleAssumers.js"() { - init_defaultStsRoleAssumers(); - init_STSClient(); - getCustomizableStsClientCtor = (baseCtor, customizations) => { - if (!customizations) - return baseCtor; - else - return class CustomizableSTSClient extends baseCtor { - constructor(config3) { - super(config3); - for (const customization of customizations) { - this.middlewareStack.use(customization); - } - } - }; - }; - getDefaultRoleAssumer2 = (stsOptions = {}, stsPlugins) => getDefaultRoleAssumer(stsOptions, getCustomizableStsClientCtor(STSClient, stsPlugins)); - getDefaultRoleAssumerWithWebIdentity2 = (stsOptions = {}, stsPlugins) => getDefaultRoleAssumerWithWebIdentity(stsOptions, getCustomizableStsClientCtor(STSClient, stsPlugins)); - decorateDefaultCredentialProvider = (provider) => (input) => provider({ - roleAssumer: getDefaultRoleAssumer2(input), - roleAssumerWithWebIdentity: getDefaultRoleAssumerWithWebIdentity2(input), - ...input - }); - } -}); - -// node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/index.js -var sts_exports = {}; -__export(sts_exports, { - AssumeRole$: () => AssumeRole$, - AssumeRoleCommand: () => AssumeRoleCommand, - AssumeRoleRequest$: () => AssumeRoleRequest$, - AssumeRoleResponse$: () => AssumeRoleResponse$, - AssumeRoleWithWebIdentity$: () => AssumeRoleWithWebIdentity$, - AssumeRoleWithWebIdentityCommand: () => AssumeRoleWithWebIdentityCommand, - AssumeRoleWithWebIdentityRequest$: () => AssumeRoleWithWebIdentityRequest$, - AssumeRoleWithWebIdentityResponse$: () => AssumeRoleWithWebIdentityResponse$, - AssumedRoleUser$: () => AssumedRoleUser$, - Credentials$: () => Credentials$, - ExpiredTokenException: () => ExpiredTokenException2, - ExpiredTokenException$: () => ExpiredTokenException$2, - IDPCommunicationErrorException: () => IDPCommunicationErrorException, - IDPCommunicationErrorException$: () => IDPCommunicationErrorException$, - IDPRejectedClaimException: () => IDPRejectedClaimException, - IDPRejectedClaimException$: () => IDPRejectedClaimException$, - InvalidIdentityTokenException: () => InvalidIdentityTokenException, - InvalidIdentityTokenException$: () => InvalidIdentityTokenException$, - MalformedPolicyDocumentException: () => MalformedPolicyDocumentException, - MalformedPolicyDocumentException$: () => MalformedPolicyDocumentException$, - PackedPolicyTooLargeException: () => PackedPolicyTooLargeException, - PackedPolicyTooLargeException$: () => PackedPolicyTooLargeException$, - PolicyDescriptorType$: () => PolicyDescriptorType$, - ProvidedContext$: () => ProvidedContext$, - RegionDisabledException: () => RegionDisabledException, - RegionDisabledException$: () => RegionDisabledException$, - STS: () => STS, - STSClient: () => STSClient, - STSServiceException: () => STSServiceException, - STSServiceException$: () => STSServiceException$, - Tag$: () => Tag$, - __Client: () => import_smithy_client33.Client, - decorateDefaultCredentialProvider: () => decorateDefaultCredentialProvider, - errorTypeRegistries: () => errorTypeRegistries4, - getDefaultRoleAssumer: () => getDefaultRoleAssumer2, - getDefaultRoleAssumerWithWebIdentity: () => getDefaultRoleAssumerWithWebIdentity2 -}); -var init_sts = __esm({ - "node_modules/.pnpm/@aws-sdk+nested-clients@3.996.19/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/index.js"() { - init_STSClient(); - init_STS(); - init_commands4(); - init_schemas_04(); - init_errors6(); - init_models_04(); - init_defaultRoleAssumers(); - init_STSServiceException(); - } -}); - -// node_modules/.pnpm/@aws-sdk+credential-provider-process@3.972.25/node_modules/@aws-sdk/credential-provider-process/dist-cjs/index.js -var require_dist_cjs59 = __commonJS({ - "node_modules/.pnpm/@aws-sdk+credential-provider-process@3.972.25/node_modules/@aws-sdk/credential-provider-process/dist-cjs/index.js"(exports) { - "use strict"; - var sharedIniFileLoader = require_dist_cjs42(); - var propertyProvider = require_dist_cjs41(); - var node_child_process = __require("node:child_process"); - var node_util = __require("node:util"); - var client2 = (init_client2(), __toCommonJS(client_exports)); - var getValidatedProcessCredentials = (profileName, data2, profiles) => { - if (data2.Version !== 1) { - throw Error(`Profile ${profileName} credential_process did not return Version 1.`); - } - if (data2.AccessKeyId === void 0 || data2.SecretAccessKey === void 0) { - throw Error(`Profile ${profileName} credential_process returned invalid credentials.`); - } - if (data2.Expiration) { - const currentTime = /* @__PURE__ */ new Date(); - const expireTime = new Date(data2.Expiration); - if (expireTime < currentTime) { - throw Error(`Profile ${profileName} credential_process returned expired credentials.`); - } - } - let accountId = data2.AccountId; - if (!accountId && profiles?.[profileName]?.aws_account_id) { - accountId = profiles[profileName].aws_account_id; - } - const credentials = { - accessKeyId: data2.AccessKeyId, - secretAccessKey: data2.SecretAccessKey, - ...data2.SessionToken && { sessionToken: data2.SessionToken }, - ...data2.Expiration && { expiration: new Date(data2.Expiration) }, - ...data2.CredentialScope && { credentialScope: data2.CredentialScope }, - ...accountId && { accountId } - }; - client2.setCredentialFeature(credentials, "CREDENTIALS_PROCESS", "w"); - return credentials; - }; - var resolveProcessCredentials = async (profileName, profiles, logger4) => { - const profile = profiles[profileName]; - if (profiles[profileName]) { - const credentialProcess = profile["credential_process"]; - if (credentialProcess !== void 0) { - const execPromise = node_util.promisify(sharedIniFileLoader.externalDataInterceptor?.getTokenRecord?.().exec ?? node_child_process.exec); - try { - const { stdout } = await execPromise(credentialProcess); - let data2; - try { - data2 = JSON.parse(stdout.trim()); - } catch { - throw Error(`Profile ${profileName} credential_process returned invalid JSON.`); - } - return getValidatedProcessCredentials(profileName, data2, profiles); - } catch (error50) { - throw new propertyProvider.CredentialsProviderError(error50.message, { logger: logger4 }); - } - } else { - throw new propertyProvider.CredentialsProviderError(`Profile ${profileName} did not contain credential_process.`, { logger: logger4 }); - } - } else { - throw new propertyProvider.CredentialsProviderError(`Profile ${profileName} could not be found in shared credentials file.`, { - logger: logger4 - }); - } - }; - var fromProcess = (init2 = {}) => async ({ callerClientConfig } = {}) => { - init2.logger?.debug("@aws-sdk/credential-provider-process - fromProcess"); - const profiles = await sharedIniFileLoader.parseKnownFiles(init2); - return resolveProcessCredentials(sharedIniFileLoader.getProfileName({ - profile: init2.profile ?? callerClientConfig?.profile - }), profiles, init2.logger); - }; - exports.fromProcess = fromProcess; - } -}); - -// node_modules/.pnpm/@aws-sdk+credential-provider-web-identity@3.972.29/node_modules/@aws-sdk/credential-provider-web-identity/dist-cjs/fromWebToken.js -var require_fromWebToken = __commonJS({ - "node_modules/.pnpm/@aws-sdk+credential-provider-web-identity@3.972.29/node_modules/@aws-sdk/credential-provider-web-identity/dist-cjs/fromWebToken.js"(exports) { - "use strict"; - var __createBinding2 = exports && exports.__createBinding || (Object.create ? (function(o5, m5, k5, k22) { - if (k22 === void 0) k22 = k5; - var desc3 = Object.getOwnPropertyDescriptor(m5, k5); - if (!desc3 || ("get" in desc3 ? !m5.__esModule : desc3.writable || desc3.configurable)) { - desc3 = { enumerable: true, get: function() { - return m5[k5]; - } }; - } - Object.defineProperty(o5, k22, desc3); - }) : (function(o5, m5, k5, k22) { - if (k22 === void 0) k22 = k5; - o5[k22] = m5[k5]; - })); - var __setModuleDefault2 = exports && exports.__setModuleDefault || (Object.create ? (function(o5, v5) { - Object.defineProperty(o5, "default", { enumerable: true, value: v5 }); - }) : function(o5, v5) { - o5["default"] = v5; - }); - var __importStar2 = exports && exports.__importStar || /* @__PURE__ */ (function() { - var ownKeys2 = function(o5) { - ownKeys2 = Object.getOwnPropertyNames || function(o6) { - var ar = []; - for (var k5 in o6) if (Object.prototype.hasOwnProperty.call(o6, k5)) ar[ar.length] = k5; - return ar; - }; - return ownKeys2(o5); - }; - return function(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for (var k5 = ownKeys2(mod), i5 = 0; i5 < k5.length; i5++) if (k5[i5] !== "default") __createBinding2(result, mod, k5[i5]); - } - __setModuleDefault2(result, mod); - return result; - }; - })(); - Object.defineProperty(exports, "__esModule", { value: true }); - exports.fromWebToken = void 0; - var fromWebToken = (init2) => async (awsIdentityProperties) => { - init2.logger?.debug("@aws-sdk/credential-provider-web-identity - fromWebToken"); - const { roleArn, roleSessionName, webIdentityToken, providerId, policyArns, policy, durationSeconds } = init2; - let { roleAssumerWithWebIdentity } = init2; - if (!roleAssumerWithWebIdentity) { - const { getDefaultRoleAssumerWithWebIdentity: getDefaultRoleAssumerWithWebIdentity3 } = await Promise.resolve().then(() => __importStar2((init_sts(), __toCommonJS(sts_exports)))); - roleAssumerWithWebIdentity = getDefaultRoleAssumerWithWebIdentity3({ - ...init2.clientConfig, - credentialProviderLogger: init2.logger, - parentClientConfig: { - ...awsIdentityProperties?.callerClientConfig, - ...init2.parentClientConfig - } - }, init2.clientPlugins); - } - return roleAssumerWithWebIdentity({ - RoleArn: roleArn, - RoleSessionName: roleSessionName ?? `aws-sdk-js-session-${Date.now()}`, - WebIdentityToken: webIdentityToken, - ProviderId: providerId, - PolicyArns: policyArns, - Policy: policy, - DurationSeconds: durationSeconds - }); - }; - exports.fromWebToken = fromWebToken; - } -}); - -// node_modules/.pnpm/@aws-sdk+credential-provider-web-identity@3.972.29/node_modules/@aws-sdk/credential-provider-web-identity/dist-cjs/fromTokenFile.js -var require_fromTokenFile = __commonJS({ - "node_modules/.pnpm/@aws-sdk+credential-provider-web-identity@3.972.29/node_modules/@aws-sdk/credential-provider-web-identity/dist-cjs/fromTokenFile.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.fromTokenFile = void 0; - var client_1 = (init_client2(), __toCommonJS(client_exports)); - var property_provider_1 = require_dist_cjs41(); - var shared_ini_file_loader_1 = require_dist_cjs42(); - var node_fs_1 = __require("node:fs"); - var fromWebToken_1 = require_fromWebToken(); - var ENV_TOKEN_FILE = "AWS_WEB_IDENTITY_TOKEN_FILE"; - var ENV_ROLE_ARN = "AWS_ROLE_ARN"; - var ENV_ROLE_SESSION_NAME = "AWS_ROLE_SESSION_NAME"; - var fromTokenFile = (init2 = {}) => async (awsIdentityProperties) => { - init2.logger?.debug("@aws-sdk/credential-provider-web-identity - fromTokenFile"); - const webIdentityTokenFile = init2?.webIdentityTokenFile ?? process.env[ENV_TOKEN_FILE]; - const roleArn = init2?.roleArn ?? process.env[ENV_ROLE_ARN]; - const roleSessionName = init2?.roleSessionName ?? process.env[ENV_ROLE_SESSION_NAME]; - if (!webIdentityTokenFile || !roleArn) { - throw new property_provider_1.CredentialsProviderError("Web identity configuration not specified", { - logger: init2.logger - }); - } - const credentials = await (0, fromWebToken_1.fromWebToken)({ - ...init2, - webIdentityToken: shared_ini_file_loader_1.externalDataInterceptor?.getTokenRecord?.()[webIdentityTokenFile] ?? (0, node_fs_1.readFileSync)(webIdentityTokenFile, { encoding: "ascii" }), - roleArn, - roleSessionName - })(awsIdentityProperties); - if (webIdentityTokenFile === process.env[ENV_TOKEN_FILE]) { - (0, client_1.setCredentialFeature)(credentials, "CREDENTIALS_ENV_VARS_STS_WEB_ID_TOKEN", "h"); - } - return credentials; - }; - exports.fromTokenFile = fromTokenFile; - } -}); - -// node_modules/.pnpm/@aws-sdk+credential-provider-web-identity@3.972.29/node_modules/@aws-sdk/credential-provider-web-identity/dist-cjs/index.js -var require_dist_cjs60 = __commonJS({ - "node_modules/.pnpm/@aws-sdk+credential-provider-web-identity@3.972.29/node_modules/@aws-sdk/credential-provider-web-identity/dist-cjs/index.js"(exports) { - "use strict"; - var fromTokenFile = require_fromTokenFile(); - var fromWebToken = require_fromWebToken(); - Object.prototype.hasOwnProperty.call(fromTokenFile, "__proto__") && !Object.prototype.hasOwnProperty.call(exports, "__proto__") && Object.defineProperty(exports, "__proto__", { - enumerable: true, - value: fromTokenFile["__proto__"] - }); - Object.keys(fromTokenFile).forEach(function(k5) { - if (k5 !== "default" && !Object.prototype.hasOwnProperty.call(exports, k5)) exports[k5] = fromTokenFile[k5]; - }); - Object.prototype.hasOwnProperty.call(fromWebToken, "__proto__") && !Object.prototype.hasOwnProperty.call(exports, "__proto__") && Object.defineProperty(exports, "__proto__", { - enumerable: true, - value: fromWebToken["__proto__"] - }); - Object.keys(fromWebToken).forEach(function(k5) { - if (k5 !== "default" && !Object.prototype.hasOwnProperty.call(exports, k5)) exports[k5] = fromWebToken[k5]; - }); - } -}); - -// node_modules/.pnpm/@aws-sdk+credential-provider-ini@3.972.29/node_modules/@aws-sdk/credential-provider-ini/dist-cjs/index.js -var require_dist_cjs61 = __commonJS({ - "node_modules/.pnpm/@aws-sdk+credential-provider-ini@3.972.29/node_modules/@aws-sdk/credential-provider-ini/dist-cjs/index.js"(exports) { - "use strict"; - var sharedIniFileLoader = require_dist_cjs42(); - var propertyProvider = require_dist_cjs41(); - var client2 = (init_client2(), __toCommonJS(client_exports)); - var credentialProviderLogin = require_dist_cjs58(); - var resolveCredentialSource = (credentialSource, profileName, logger4) => { - const sourceProvidersMap = { - EcsContainer: async (options) => { - const { fromHttp } = await Promise.resolve().then(() => __toESM(require_dist_cjs50())); - const { fromContainerMetadata } = await Promise.resolve().then(() => __toESM(require_dist_cjs49())); - logger4?.debug("@aws-sdk/credential-provider-ini - credential_source is EcsContainer"); - return async () => propertyProvider.chain(fromHttp(options ?? {}), fromContainerMetadata(options))().then(setNamedProvider); - }, - Ec2InstanceMetadata: async (options) => { - logger4?.debug("@aws-sdk/credential-provider-ini - credential_source is Ec2InstanceMetadata"); - const { fromInstanceMetadata } = await Promise.resolve().then(() => __toESM(require_dist_cjs49())); - return async () => fromInstanceMetadata(options)().then(setNamedProvider); - }, - Environment: async (options) => { - logger4?.debug("@aws-sdk/credential-provider-ini - credential_source is Environment"); - const { fromEnv } = await Promise.resolve().then(() => __toESM(require_dist_cjs48())); - return async () => fromEnv(options)().then(setNamedProvider); - } - }; - if (credentialSource in sourceProvidersMap) { - return sourceProvidersMap[credentialSource]; - } else { - throw new propertyProvider.CredentialsProviderError(`Unsupported credential source in profile ${profileName}. Got ${credentialSource}, expected EcsContainer or Ec2InstanceMetadata or Environment.`, { logger: logger4 }); - } - }; - var setNamedProvider = (creds) => client2.setCredentialFeature(creds, "CREDENTIALS_PROFILE_NAMED_PROVIDER", "p"); - var isAssumeRoleProfile = (arg, { profile = "default", logger: logger4 } = {}) => { - return Boolean(arg) && typeof arg === "object" && typeof arg.role_arn === "string" && ["undefined", "string"].indexOf(typeof arg.role_session_name) > -1 && ["undefined", "string"].indexOf(typeof arg.external_id) > -1 && ["undefined", "string"].indexOf(typeof arg.mfa_serial) > -1 && (isAssumeRoleWithSourceProfile(arg, { profile, logger: logger4 }) || isCredentialSourceProfile(arg, { profile, logger: logger4 })); - }; - var isAssumeRoleWithSourceProfile = (arg, { profile, logger: logger4 }) => { - const withSourceProfile = typeof arg.source_profile === "string" && typeof arg.credential_source === "undefined"; - if (withSourceProfile) { - logger4?.debug?.(` ${profile} isAssumeRoleWithSourceProfile source_profile=${arg.source_profile}`); - } - return withSourceProfile; - }; - var isCredentialSourceProfile = (arg, { profile, logger: logger4 }) => { - const withProviderProfile = typeof arg.credential_source === "string" && typeof arg.source_profile === "undefined"; - if (withProviderProfile) { - logger4?.debug?.(` ${profile} isCredentialSourceProfile credential_source=${arg.credential_source}`); - } - return withProviderProfile; - }; - var resolveAssumeRoleCredentials = async (profileName, profiles, options, callerClientConfig, visitedProfiles = {}, resolveProfileData2) => { - options.logger?.debug("@aws-sdk/credential-provider-ini - resolveAssumeRoleCredentials (STS)"); - const profileData = profiles[profileName]; - const { source_profile, region } = profileData; - if (!options.roleAssumer) { - const { getDefaultRoleAssumer: getDefaultRoleAssumer3 } = await Promise.resolve().then(() => (init_sts(), sts_exports)); - options.roleAssumer = getDefaultRoleAssumer3({ - ...options.clientConfig, - credentialProviderLogger: options.logger, - parentClientConfig: { - ...callerClientConfig, - ...options?.parentClientConfig, - region: region ?? options?.parentClientConfig?.region ?? callerClientConfig?.region - } - }, options.clientPlugins); - } - if (source_profile && source_profile in visitedProfiles) { - throw new propertyProvider.CredentialsProviderError(`Detected a cycle attempting to resolve credentials for profile ${sharedIniFileLoader.getProfileName(options)}. Profiles visited: ` + Object.keys(visitedProfiles).join(", "), { logger: options.logger }); - } - options.logger?.debug(`@aws-sdk/credential-provider-ini - finding credential resolver using ${source_profile ? `source_profile=[${source_profile}]` : `profile=[${profileName}]`}`); - const sourceCredsProvider = source_profile ? resolveProfileData2(source_profile, profiles, options, callerClientConfig, { - ...visitedProfiles, - [source_profile]: true - }, isCredentialSourceWithoutRoleArn(profiles[source_profile] ?? {})) : (await resolveCredentialSource(profileData.credential_source, profileName, options.logger)(options))(); - if (isCredentialSourceWithoutRoleArn(profileData)) { - return sourceCredsProvider.then((creds) => client2.setCredentialFeature(creds, "CREDENTIALS_PROFILE_SOURCE_PROFILE", "o")); - } else { - const params = { - RoleArn: profileData.role_arn, - RoleSessionName: profileData.role_session_name || `aws-sdk-js-${Date.now()}`, - ExternalId: profileData.external_id, - DurationSeconds: parseInt(profileData.duration_seconds || "3600", 10) - }; - const { mfa_serial } = profileData; - if (mfa_serial) { - if (!options.mfaCodeProvider) { - throw new propertyProvider.CredentialsProviderError(`Profile ${profileName} requires multi-factor authentication, but no MFA code callback was provided.`, { logger: options.logger, tryNextLink: false }); - } - params.SerialNumber = mfa_serial; - params.TokenCode = await options.mfaCodeProvider(mfa_serial); - } - const sourceCreds = await sourceCredsProvider; - return options.roleAssumer(sourceCreds, params).then((creds) => client2.setCredentialFeature(creds, "CREDENTIALS_PROFILE_SOURCE_PROFILE", "o")); - } - }; - var isCredentialSourceWithoutRoleArn = (section) => { - return !section.role_arn && !!section.credential_source; - }; - var isLoginProfile = (data2) => { - return Boolean(data2 && data2.login_session); - }; - var resolveLoginCredentials = async (profileName, options, callerClientConfig) => { - const credentials = await credentialProviderLogin.fromLoginCredentials({ - ...options, - profile: profileName - })({ callerClientConfig }); - return client2.setCredentialFeature(credentials, "CREDENTIALS_PROFILE_LOGIN", "AC"); - }; - var isProcessProfile = (arg) => Boolean(arg) && typeof arg === "object" && typeof arg.credential_process === "string"; - var resolveProcessCredentials = async (options, profile) => Promise.resolve().then(() => __toESM(require_dist_cjs59())).then(({ fromProcess }) => fromProcess({ - ...options, - profile - })().then((creds) => client2.setCredentialFeature(creds, "CREDENTIALS_PROFILE_PROCESS", "v"))); - var resolveSsoCredentials = async (profile, profileData, options = {}, callerClientConfig) => { - const { fromSSO } = await Promise.resolve().then(() => __toESM(require_dist_cjs57())); - return fromSSO({ - profile, - logger: options.logger, - parentClientConfig: options.parentClientConfig, - clientConfig: options.clientConfig - })({ - callerClientConfig - }).then((creds) => { - if (profileData.sso_session) { - return client2.setCredentialFeature(creds, "CREDENTIALS_PROFILE_SSO", "r"); - } else { - return client2.setCredentialFeature(creds, "CREDENTIALS_PROFILE_SSO_LEGACY", "t"); - } - }); - }; - var isSsoProfile = (arg) => arg && (typeof arg.sso_start_url === "string" || typeof arg.sso_account_id === "string" || typeof arg.sso_session === "string" || typeof arg.sso_region === "string" || typeof arg.sso_role_name === "string"); - var isStaticCredsProfile = (arg) => Boolean(arg) && typeof arg === "object" && typeof arg.aws_access_key_id === "string" && typeof arg.aws_secret_access_key === "string" && ["undefined", "string"].indexOf(typeof arg.aws_session_token) > -1 && ["undefined", "string"].indexOf(typeof arg.aws_account_id) > -1; - var resolveStaticCredentials = async (profile, options) => { - options?.logger?.debug("@aws-sdk/credential-provider-ini - resolveStaticCredentials"); - const credentials = { - accessKeyId: profile.aws_access_key_id, - secretAccessKey: profile.aws_secret_access_key, - sessionToken: profile.aws_session_token, - ...profile.aws_credential_scope && { credentialScope: profile.aws_credential_scope }, - ...profile.aws_account_id && { accountId: profile.aws_account_id } - }; - return client2.setCredentialFeature(credentials, "CREDENTIALS_PROFILE", "n"); - }; - var isWebIdentityProfile = (arg) => Boolean(arg) && typeof arg === "object" && typeof arg.web_identity_token_file === "string" && typeof arg.role_arn === "string" && ["undefined", "string"].indexOf(typeof arg.role_session_name) > -1; - var resolveWebIdentityCredentials = async (profile, options, callerClientConfig) => Promise.resolve().then(() => __toESM(require_dist_cjs60())).then(({ fromTokenFile }) => fromTokenFile({ - webIdentityTokenFile: profile.web_identity_token_file, - roleArn: profile.role_arn, - roleSessionName: profile.role_session_name, - roleAssumerWithWebIdentity: options.roleAssumerWithWebIdentity, - logger: options.logger, - parentClientConfig: options.parentClientConfig - })({ - callerClientConfig - }).then((creds) => client2.setCredentialFeature(creds, "CREDENTIALS_PROFILE_STS_WEB_ID_TOKEN", "q"))); - var resolveProfileData = async (profileName, profiles, options, callerClientConfig, visitedProfiles = {}, isAssumeRoleRecursiveCall = false) => { - const data2 = profiles[profileName]; - if (Object.keys(visitedProfiles).length > 0 && isStaticCredsProfile(data2)) { - return resolveStaticCredentials(data2, options); - } - if (isAssumeRoleRecursiveCall || isAssumeRoleProfile(data2, { profile: profileName, logger: options.logger })) { - return resolveAssumeRoleCredentials(profileName, profiles, options, callerClientConfig, visitedProfiles, resolveProfileData); - } - if (isStaticCredsProfile(data2)) { - return resolveStaticCredentials(data2, options); - } - if (isWebIdentityProfile(data2)) { - return resolveWebIdentityCredentials(data2, options, callerClientConfig); - } - if (isProcessProfile(data2)) { - return resolveProcessCredentials(options, profileName); - } - if (isSsoProfile(data2)) { - return await resolveSsoCredentials(profileName, data2, options, callerClientConfig); - } - if (isLoginProfile(data2)) { - return resolveLoginCredentials(profileName, options, callerClientConfig); - } - throw new propertyProvider.CredentialsProviderError(`Could not resolve credentials using profile: [${profileName}] in configuration/credentials file(s).`, { logger: options.logger }); - }; - var fromIni = (init2 = {}) => async ({ callerClientConfig } = {}) => { - init2.logger?.debug("@aws-sdk/credential-provider-ini - fromIni"); - const profiles = await sharedIniFileLoader.parseKnownFiles(init2); - return resolveProfileData(sharedIniFileLoader.getProfileName({ - profile: init2.profile ?? callerClientConfig?.profile - }), profiles, init2, callerClientConfig); - }; - exports.fromIni = fromIni; - } -}); - -// node_modules/.pnpm/@aws-sdk+credential-provider-node@3.972.30/node_modules/@aws-sdk/credential-provider-node/dist-cjs/index.js -var require_dist_cjs62 = __commonJS({ - "node_modules/.pnpm/@aws-sdk+credential-provider-node@3.972.30/node_modules/@aws-sdk/credential-provider-node/dist-cjs/index.js"(exports) { - "use strict"; - var credentialProviderEnv = require_dist_cjs48(); - var propertyProvider = require_dist_cjs41(); - var sharedIniFileLoader = require_dist_cjs42(); - var ENV_IMDS_DISABLED = "AWS_EC2_METADATA_DISABLED"; - var remoteProvider = async (init2) => { - const { ENV_CMDS_FULL_URI, ENV_CMDS_RELATIVE_URI, fromContainerMetadata, fromInstanceMetadata } = await Promise.resolve().then(() => __toESM(require_dist_cjs49())); - if (process.env[ENV_CMDS_RELATIVE_URI] || process.env[ENV_CMDS_FULL_URI]) { - init2.logger?.debug("@aws-sdk/credential-provider-node - remoteProvider::fromHttp/fromContainerMetadata"); - const { fromHttp } = await Promise.resolve().then(() => __toESM(require_dist_cjs50())); - return propertyProvider.chain(fromHttp(init2), fromContainerMetadata(init2)); - } - if (process.env[ENV_IMDS_DISABLED] && process.env[ENV_IMDS_DISABLED] !== "false") { - return async () => { - throw new propertyProvider.CredentialsProviderError("EC2 Instance Metadata Service access disabled", { logger: init2.logger }); - }; - } - init2.logger?.debug("@aws-sdk/credential-provider-node - remoteProvider::fromInstanceMetadata"); - return fromInstanceMetadata(init2); - }; - function memoizeChain(providers2, treatAsExpired) { - const chain = internalCreateChain(providers2); - let activeLock; - let passiveLock; - let credentials; - const provider = async (options) => { - if (options?.forceRefresh) { - return await chain(options); - } - if (credentials?.expiration) { - if (credentials?.expiration?.getTime() < Date.now()) { - credentials = void 0; - } - } - if (activeLock) { - await activeLock; - } else if (!credentials || treatAsExpired?.(credentials)) { - if (credentials) { - if (!passiveLock) { - passiveLock = chain(options).then((c5) => { - credentials = c5; - }).finally(() => { - passiveLock = void 0; - }); - } - } else { - activeLock = chain(options).then((c5) => { - credentials = c5; - }).finally(() => { - activeLock = void 0; - }); - return provider(options); - } - } - return credentials; - }; - return provider; - } - var internalCreateChain = (providers2) => async (awsIdentityProperties) => { - let lastProviderError; - for (const provider of providers2) { - try { - return await provider(awsIdentityProperties); - } catch (err) { - lastProviderError = err; - if (err?.tryNextLink) { - continue; - } - throw err; - } - } - throw lastProviderError; - }; - var multipleCredentialSourceWarningEmitted = false; - var defaultProvider = (init2 = {}) => memoizeChain([ - async () => { - const profile = init2.profile ?? process.env[sharedIniFileLoader.ENV_PROFILE]; - if (profile) { - const envStaticCredentialsAreSet = process.env[credentialProviderEnv.ENV_KEY] && process.env[credentialProviderEnv.ENV_SECRET]; - if (envStaticCredentialsAreSet) { - if (!multipleCredentialSourceWarningEmitted) { - const warnFn = init2.logger?.warn && init2.logger?.constructor?.name !== "NoOpLogger" ? init2.logger.warn.bind(init2.logger) : console.warn; - warnFn(`@aws-sdk/credential-provider-node - defaultProvider::fromEnv WARNING: - Multiple credential sources detected: - Both AWS_PROFILE and the pair AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY static credentials are set. - This SDK will proceed with the AWS_PROFILE value. - - However, a future version may change this behavior to prefer the ENV static credentials. - Please ensure that your environment only sets either the AWS_PROFILE or the - AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY pair. -`); - multipleCredentialSourceWarningEmitted = true; - } - } - throw new propertyProvider.CredentialsProviderError("AWS_PROFILE is set, skipping fromEnv provider.", { - logger: init2.logger, - tryNextLink: true - }); - } - init2.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromEnv"); - return credentialProviderEnv.fromEnv(init2)(); - }, - async (awsIdentityProperties) => { - init2.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromSSO"); - const { ssoStartUrl, ssoAccountId, ssoRegion, ssoRoleName, ssoSession } = init2; - if (!ssoStartUrl && !ssoAccountId && !ssoRegion && !ssoRoleName && !ssoSession) { - throw new propertyProvider.CredentialsProviderError("Skipping SSO provider in default chain (inputs do not include SSO fields).", { logger: init2.logger }); - } - const { fromSSO } = await Promise.resolve().then(() => __toESM(require_dist_cjs57())); - return fromSSO(init2)(awsIdentityProperties); - }, - async (awsIdentityProperties) => { - init2.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromIni"); - const { fromIni } = await Promise.resolve().then(() => __toESM(require_dist_cjs61())); - return fromIni(init2)(awsIdentityProperties); - }, - async (awsIdentityProperties) => { - init2.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromProcess"); - const { fromProcess } = await Promise.resolve().then(() => __toESM(require_dist_cjs59())); - return fromProcess(init2)(awsIdentityProperties); - }, - async (awsIdentityProperties) => { - init2.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromTokenFile"); - const { fromTokenFile } = await Promise.resolve().then(() => __toESM(require_dist_cjs60())); - return fromTokenFile(init2)(awsIdentityProperties); - }, - async () => { - init2.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::remoteProvider"); - return (await remoteProvider(init2))(); - }, - async () => { - throw new propertyProvider.CredentialsProviderError("Could not load credentials from any providers", { - tryNextLink: false, - logger: init2.logger - }); - } - ], credentialsTreatedAsExpired); - var credentialsWillNeedRefresh = (credentials) => credentials?.expiration !== void 0; - var credentialsTreatedAsExpired = (credentials) => credentials?.expiration !== void 0 && credentials.expiration.getTime() - Date.now() < 3e5; - exports.credentialsTreatedAsExpired = credentialsTreatedAsExpired; - exports.credentialsWillNeedRefresh = credentialsWillNeedRefresh; - exports.defaultProvider = defaultProvider; - } -}); - -// node_modules/.pnpm/@aws-sdk+middleware-bucket-endpoint@3.972.9/node_modules/@aws-sdk/middleware-bucket-endpoint/dist-cjs/index.js -var require_dist_cjs63 = __commonJS({ - "node_modules/.pnpm/@aws-sdk+middleware-bucket-endpoint@3.972.9/node_modules/@aws-sdk/middleware-bucket-endpoint/dist-cjs/index.js"(exports) { - "use strict"; - var utilConfigProvider = require_dist_cjs31(); - var utilArnParser = require_dist_cjs28(); - var protocolHttp = require_dist_cjs2(); - var NODE_DISABLE_MULTIREGION_ACCESS_POINT_ENV_NAME = "AWS_S3_DISABLE_MULTIREGION_ACCESS_POINTS"; - var NODE_DISABLE_MULTIREGION_ACCESS_POINT_INI_NAME = "s3_disable_multiregion_access_points"; - var NODE_DISABLE_MULTIREGION_ACCESS_POINT_CONFIG_OPTIONS = { - environmentVariableSelector: (env2) => utilConfigProvider.booleanSelector(env2, NODE_DISABLE_MULTIREGION_ACCESS_POINT_ENV_NAME, utilConfigProvider.SelectorType.ENV), - configFileSelector: (profile) => utilConfigProvider.booleanSelector(profile, NODE_DISABLE_MULTIREGION_ACCESS_POINT_INI_NAME, utilConfigProvider.SelectorType.CONFIG), - default: false - }; - var NODE_USE_ARN_REGION_ENV_NAME = "AWS_S3_USE_ARN_REGION"; - var NODE_USE_ARN_REGION_INI_NAME = "s3_use_arn_region"; - var NODE_USE_ARN_REGION_CONFIG_OPTIONS = { - environmentVariableSelector: (env2) => utilConfigProvider.booleanSelector(env2, NODE_USE_ARN_REGION_ENV_NAME, utilConfigProvider.SelectorType.ENV), - configFileSelector: (profile) => utilConfigProvider.booleanSelector(profile, NODE_USE_ARN_REGION_INI_NAME, utilConfigProvider.SelectorType.CONFIG), - default: void 0 - }; - var DOMAIN_PATTERN = /^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$/; - var IP_ADDRESS_PATTERN = /(\d+\.){3}\d+/; - var DOTS_PATTERN = /\.\./; - var DOT_PATTERN = /\./; - var S3_HOSTNAME_PATTERN = /^(.+\.)?s3(-fips)?(\.dualstack)?[.-]([a-z0-9-]+)\./; - var S3_US_EAST_1_ALTNAME_PATTERN = /^s3(-external-1)?\.amazonaws\.com$/; - var AWS_PARTITION_SUFFIX = "amazonaws.com"; - var isBucketNameOptions = (options) => typeof options.bucketName === "string"; - var isDnsCompatibleBucketName = (bucketName) => DOMAIN_PATTERN.test(bucketName) && !IP_ADDRESS_PATTERN.test(bucketName) && !DOTS_PATTERN.test(bucketName); - var getRegionalSuffix = (hostname3) => { - const parts = hostname3.match(S3_HOSTNAME_PATTERN); - return [parts[4], hostname3.replace(new RegExp(`^${parts[0]}`), "")]; - }; - var getSuffix = (hostname3) => S3_US_EAST_1_ALTNAME_PATTERN.test(hostname3) ? ["us-east-1", AWS_PARTITION_SUFFIX] : getRegionalSuffix(hostname3); - var getSuffixForArnEndpoint = (hostname3) => S3_US_EAST_1_ALTNAME_PATTERN.test(hostname3) ? [hostname3.replace(`.${AWS_PARTITION_SUFFIX}`, ""), AWS_PARTITION_SUFFIX] : getRegionalSuffix(hostname3); - var validateArnEndpointOptions = (options) => { - if (options.pathStyleEndpoint) { - throw new Error("Path-style S3 endpoint is not supported when bucket is an ARN"); - } - if (options.accelerateEndpoint) { - throw new Error("Accelerate endpoint is not supported when bucket is an ARN"); - } - if (!options.tlsCompatible) { - throw new Error("HTTPS is required when bucket is an ARN"); - } - }; - var validateService = (service) => { - if (service !== "s3" && service !== "s3-outposts" && service !== "s3-object-lambda") { - throw new Error("Expect 's3' or 's3-outposts' or 's3-object-lambda' in ARN service component"); - } - }; - var validateS3Service = (service) => { - if (service !== "s3") { - throw new Error("Expect 's3' in Accesspoint ARN service component"); - } - }; - var validateOutpostService = (service) => { - if (service !== "s3-outposts") { - throw new Error("Expect 's3-posts' in Outpost ARN service component"); - } - }; - var validatePartition = (partition, options) => { - if (partition !== options.clientPartition) { - throw new Error(`Partition in ARN is incompatible, got "${partition}" but expected "${options.clientPartition}"`); - } - }; - var validateRegion = (region, options) => { - }; - var validateRegionalClient = (region) => { - if (["s3-external-1", "aws-global"].includes(region)) { - throw new Error(`Client region ${region} is not regional`); - } - }; - var validateAccountId = (accountId) => { - if (!/[0-9]{12}/.exec(accountId)) { - throw new Error("Access point ARN accountID does not match regex '[0-9]{12}'"); - } - }; - var validateDNSHostLabel = (label, options = { tlsCompatible: true }) => { - if (label.length >= 64 || !/^[a-z0-9][a-z0-9.-]*[a-z0-9]$/.test(label) || /(\d+\.){3}\d+/.test(label) || /[.-]{2}/.test(label) || options?.tlsCompatible && DOT_PATTERN.test(label)) { - throw new Error(`Invalid DNS label ${label}`); - } - }; - var validateCustomEndpoint = (options) => { - if (options.isCustomEndpoint) { - if (options.dualstackEndpoint) - throw new Error("Dualstack endpoint is not supported with custom endpoint"); - if (options.accelerateEndpoint) - throw new Error("Accelerate endpoint is not supported with custom endpoint"); - } - }; - var getArnResources = (resource) => { - const delimiter = resource.includes(":") ? ":" : "/"; - const [resourceType, ...rest] = resource.split(delimiter); - if (resourceType === "accesspoint") { - if (rest.length !== 1 || rest[0] === "") { - throw new Error(`Access Point ARN should have one resource accesspoint${delimiter}{accesspointname}`); - } - return { accesspointName: rest[0] }; - } else if (resourceType === "outpost") { - if (!rest[0] || rest[1] !== "accesspoint" || !rest[2] || rest.length !== 3) { - throw new Error(`Outpost ARN should have resource outpost${delimiter}{outpostId}${delimiter}accesspoint${delimiter}{accesspointName}`); - } - const [outpostId, _, accesspointName] = rest; - return { outpostId, accesspointName }; - } else { - throw new Error(`ARN resource should begin with 'accesspoint${delimiter}' or 'outpost${delimiter}'`); - } - }; - var validateNoDualstack = (dualstackEndpoint) => { - }; - var validateNoFIPS = (useFipsEndpoint) => { - if (useFipsEndpoint) - throw new Error(`FIPS region is not supported with Outpost.`); - }; - var validateMrapAlias = (name) => { - try { - name.split(".").forEach((label) => { - validateDNSHostLabel(label); - }); - } catch (e5) { - throw new Error(`"${name}" is not a DNS compatible name.`); - } - }; - var bucketHostname = (options) => { - validateCustomEndpoint(options); - return isBucketNameOptions(options) ? getEndpointFromBucketName(options) : getEndpointFromArn(options); - }; - var getEndpointFromBucketName = ({ accelerateEndpoint = false, clientRegion: region, baseHostname, bucketName, dualstackEndpoint = false, fipsEndpoint = false, pathStyleEndpoint = false, tlsCompatible = true, isCustomEndpoint = false }) => { - const [clientRegion, hostnameSuffix] = isCustomEndpoint ? [region, baseHostname] : getSuffix(baseHostname); - if (pathStyleEndpoint || !isDnsCompatibleBucketName(bucketName) || tlsCompatible && DOT_PATTERN.test(bucketName)) { - return { - bucketEndpoint: false, - hostname: dualstackEndpoint ? `s3.dualstack.${clientRegion}.${hostnameSuffix}` : baseHostname - }; - } - if (accelerateEndpoint) { - baseHostname = `s3-accelerate${dualstackEndpoint ? ".dualstack" : ""}.${hostnameSuffix}`; - } else if (dualstackEndpoint) { - baseHostname = `s3.dualstack.${clientRegion}.${hostnameSuffix}`; - } - return { - bucketEndpoint: true, - hostname: `${bucketName}.${baseHostname}` - }; - }; - var getEndpointFromArn = (options) => { - const { isCustomEndpoint, baseHostname, clientRegion } = options; - const hostnameSuffix = isCustomEndpoint ? baseHostname : getSuffixForArnEndpoint(baseHostname)[1]; - const { pathStyleEndpoint, accelerateEndpoint = false, fipsEndpoint = false, tlsCompatible = true, bucketName, clientPartition = "aws" } = options; - validateArnEndpointOptions({ pathStyleEndpoint, accelerateEndpoint, tlsCompatible }); - const { service, partition, accountId, region, resource } = bucketName; - validateService(service); - validatePartition(partition, { clientPartition }); - validateAccountId(accountId); - const { accesspointName, outpostId } = getArnResources(resource); - if (service === "s3-object-lambda") { - return getEndpointFromObjectLambdaArn({ ...options, tlsCompatible, bucketName, accesspointName, hostnameSuffix }); - } - if (region === "") { - return getEndpointFromMRAPArn({ ...options, mrapAlias: accesspointName, hostnameSuffix }); - } - if (outpostId) { - return getEndpointFromOutpostArn({ ...options, clientRegion, outpostId, accesspointName, hostnameSuffix }); - } - return getEndpointFromAccessPointArn({ ...options, clientRegion, accesspointName, hostnameSuffix }); - }; - var getEndpointFromObjectLambdaArn = ({ dualstackEndpoint = false, fipsEndpoint = false, tlsCompatible = true, useArnRegion, clientRegion, clientSigningRegion = clientRegion, accesspointName, bucketName, hostnameSuffix }) => { - const { accountId, region, service } = bucketName; - validateRegionalClient(clientRegion); - const DNSHostLabel = `${accesspointName}-${accountId}`; - validateDNSHostLabel(DNSHostLabel, { tlsCompatible }); - const endpointRegion = useArnRegion ? region : clientRegion; - const signingRegion = useArnRegion ? region : clientSigningRegion; - return { - bucketEndpoint: true, - hostname: `${DNSHostLabel}.${service}${fipsEndpoint ? "-fips" : ""}.${endpointRegion}.${hostnameSuffix}`, - signingRegion, - signingService: service - }; - }; - var getEndpointFromMRAPArn = ({ disableMultiregionAccessPoints, dualstackEndpoint = false, isCustomEndpoint, mrapAlias, hostnameSuffix }) => { - if (disableMultiregionAccessPoints === true) { - throw new Error("SDK is attempting to use a MRAP ARN. Please enable to feature."); - } - validateMrapAlias(mrapAlias); - return { - bucketEndpoint: true, - hostname: `${mrapAlias}${isCustomEndpoint ? "" : `.accesspoint.s3-global`}.${hostnameSuffix}`, - signingRegion: "*" - }; - }; - var getEndpointFromOutpostArn = ({ useArnRegion, clientRegion, clientSigningRegion = clientRegion, bucketName, outpostId, dualstackEndpoint = false, fipsEndpoint = false, tlsCompatible = true, accesspointName, isCustomEndpoint, hostnameSuffix }) => { - validateRegionalClient(clientRegion); - const DNSHostLabel = `${accesspointName}-${bucketName.accountId}`; - validateDNSHostLabel(DNSHostLabel, { tlsCompatible }); - const endpointRegion = useArnRegion ? bucketName.region : clientRegion; - const signingRegion = useArnRegion ? bucketName.region : clientSigningRegion; - validateOutpostService(bucketName.service); - validateDNSHostLabel(outpostId, { tlsCompatible }); - validateNoFIPS(fipsEndpoint); - const hostnamePrefix = `${DNSHostLabel}.${outpostId}`; - return { - bucketEndpoint: true, - hostname: `${hostnamePrefix}${isCustomEndpoint ? "" : `.s3-outposts.${endpointRegion}`}.${hostnameSuffix}`, - signingRegion, - signingService: "s3-outposts" - }; - }; - var getEndpointFromAccessPointArn = ({ useArnRegion, clientRegion, clientSigningRegion = clientRegion, bucketName, dualstackEndpoint = false, fipsEndpoint = false, tlsCompatible = true, accesspointName, isCustomEndpoint, hostnameSuffix }) => { - validateRegionalClient(clientRegion); - const hostnamePrefix = `${accesspointName}-${bucketName.accountId}`; - validateDNSHostLabel(hostnamePrefix, { tlsCompatible }); - const endpointRegion = useArnRegion ? bucketName.region : clientRegion; - const signingRegion = useArnRegion ? bucketName.region : clientSigningRegion; - validateS3Service(bucketName.service); - return { - bucketEndpoint: true, - hostname: `${hostnamePrefix}${isCustomEndpoint ? "" : `.s3-accesspoint${fipsEndpoint ? "-fips" : ""}${dualstackEndpoint ? ".dualstack" : ""}.${endpointRegion}`}.${hostnameSuffix}`, - signingRegion - }; - }; - var bucketEndpointMiddleware = (options) => (next, context) => async (args) => { - const { Bucket: bucketName } = args.input; - let replaceBucketInPath = options.bucketEndpoint; - const request = args.request; - if (protocolHttp.HttpRequest.isInstance(request)) { - if (options.bucketEndpoint) { - request.hostname = bucketName; - } else if (utilArnParser.validate(bucketName)) { - const bucketArn = utilArnParser.parse(bucketName); - const clientRegion = await options.region(); - const useDualstackEndpoint = await options.useDualstackEndpoint(); - const useFipsEndpoint = await options.useFipsEndpoint(); - const { partition, signingRegion = clientRegion } = await options.regionInfoProvider(clientRegion, { useDualstackEndpoint, useFipsEndpoint }) || {}; - const useArnRegion = await options.useArnRegion(); - const { hostname: hostname3, bucketEndpoint, signingRegion: modifiedSigningRegion, signingService } = bucketHostname({ - bucketName: bucketArn, - baseHostname: request.hostname, - accelerateEndpoint: options.useAccelerateEndpoint, - dualstackEndpoint: useDualstackEndpoint, - fipsEndpoint: useFipsEndpoint, - pathStyleEndpoint: options.forcePathStyle, - tlsCompatible: request.protocol === "https:", - useArnRegion, - clientPartition: partition, - clientSigningRegion: signingRegion, - clientRegion, - isCustomEndpoint: options.isCustomEndpoint, - disableMultiregionAccessPoints: await options.disableMultiregionAccessPoints() - }); - if (modifiedSigningRegion && modifiedSigningRegion !== signingRegion) { - context["signing_region"] = modifiedSigningRegion; - } - if (signingService && signingService !== "s3") { - context["signing_service"] = signingService; - } - request.hostname = hostname3; - replaceBucketInPath = bucketEndpoint; - } else { - const clientRegion = await options.region(); - const dualstackEndpoint = await options.useDualstackEndpoint(); - const fipsEndpoint = await options.useFipsEndpoint(); - const { hostname: hostname3, bucketEndpoint } = bucketHostname({ - bucketName, - clientRegion, - baseHostname: request.hostname, - accelerateEndpoint: options.useAccelerateEndpoint, - dualstackEndpoint, - fipsEndpoint, - pathStyleEndpoint: options.forcePathStyle, - tlsCompatible: request.protocol === "https:", - isCustomEndpoint: options.isCustomEndpoint - }); - request.hostname = hostname3; - replaceBucketInPath = bucketEndpoint; - } - if (replaceBucketInPath) { - request.path = request.path.replace(/^(\/)?[^\/]+/, ""); - if (request.path === "") { - request.path = "/"; - } - } - } - return next({ ...args, request }); - }; - var bucketEndpointMiddlewareOptions = { - tags: ["BUCKET_ENDPOINT"], - name: "bucketEndpointMiddleware", - relation: "before", - toMiddleware: "hostHeaderMiddleware", - override: true - }; - var getBucketEndpointPlugin = (options) => ({ - applyToStack: (clientStack) => { - clientStack.addRelativeTo(bucketEndpointMiddleware(options), bucketEndpointMiddlewareOptions); - } - }); - function resolveBucketEndpointConfig(input) { - const { bucketEndpoint = false, forcePathStyle = false, useAccelerateEndpoint = false, useArnRegion, disableMultiregionAccessPoints = false } = input; - return Object.assign(input, { - bucketEndpoint, - forcePathStyle, - useAccelerateEndpoint, - useArnRegion: typeof useArnRegion === "function" ? useArnRegion : () => Promise.resolve(useArnRegion), - disableMultiregionAccessPoints: typeof disableMultiregionAccessPoints === "function" ? disableMultiregionAccessPoints : () => Promise.resolve(disableMultiregionAccessPoints) - }); - } - exports.NODE_DISABLE_MULTIREGION_ACCESS_POINT_CONFIG_OPTIONS = NODE_DISABLE_MULTIREGION_ACCESS_POINT_CONFIG_OPTIONS; - exports.NODE_DISABLE_MULTIREGION_ACCESS_POINT_ENV_NAME = NODE_DISABLE_MULTIREGION_ACCESS_POINT_ENV_NAME; - exports.NODE_DISABLE_MULTIREGION_ACCESS_POINT_INI_NAME = NODE_DISABLE_MULTIREGION_ACCESS_POINT_INI_NAME; - exports.NODE_USE_ARN_REGION_CONFIG_OPTIONS = NODE_USE_ARN_REGION_CONFIG_OPTIONS; - exports.NODE_USE_ARN_REGION_ENV_NAME = NODE_USE_ARN_REGION_ENV_NAME; - exports.NODE_USE_ARN_REGION_INI_NAME = NODE_USE_ARN_REGION_INI_NAME; - exports.bucketEndpointMiddleware = bucketEndpointMiddleware; - exports.bucketEndpointMiddlewareOptions = bucketEndpointMiddlewareOptions; - exports.bucketHostname = bucketHostname; - exports.getArnResources = getArnResources; - exports.getBucketEndpointPlugin = getBucketEndpointPlugin; - exports.getSuffixForArnEndpoint = getSuffixForArnEndpoint; - exports.resolveBucketEndpointConfig = resolveBucketEndpointConfig; - exports.validateAccountId = validateAccountId; - exports.validateDNSHostLabel = validateDNSHostLabel; - exports.validateNoDualstack = validateNoDualstack; - exports.validateNoFIPS = validateNoFIPS; - exports.validateOutpostService = validateOutpostService; - exports.validatePartition = validatePartition; - exports.validateRegion = validateRegion; - } -}); - -// node_modules/.pnpm/@smithy+eventstream-codec@4.2.13/node_modules/@smithy/eventstream-codec/dist-cjs/index.js -var require_dist_cjs64 = __commonJS({ - "node_modules/.pnpm/@smithy+eventstream-codec@4.2.13/node_modules/@smithy/eventstream-codec/dist-cjs/index.js"(exports) { - "use strict"; - var crc32 = require_main4(); - var utilHexEncoding = require_dist_cjs12(); - var Int64 = class _Int64 { - bytes; - constructor(bytes) { - this.bytes = bytes; - if (bytes.byteLength !== 8) { - throw new Error("Int64 buffers must be exactly 8 bytes"); - } - } - static fromNumber(number4) { - if (number4 > 9223372036854776e3 || number4 < -9223372036854776e3) { - throw new Error(`${number4} is too large (or, if negative, too small) to represent as an Int64`); - } - const bytes = new Uint8Array(8); - for (let i5 = 7, remaining = Math.abs(Math.round(number4)); i5 > -1 && remaining > 0; i5--, remaining /= 256) { - bytes[i5] = remaining; - } - if (number4 < 0) { - negate(bytes); - } - return new _Int64(bytes); - } - valueOf() { - const bytes = this.bytes.slice(0); - const negative = bytes[0] & 128; - if (negative) { - negate(bytes); - } - return parseInt(utilHexEncoding.toHex(bytes), 16) * (negative ? -1 : 1); - } - toString() { - return String(this.valueOf()); - } - }; - function negate(bytes) { - for (let i5 = 0; i5 < 8; i5++) { - bytes[i5] ^= 255; - } - for (let i5 = 7; i5 > -1; i5--) { - bytes[i5]++; - if (bytes[i5] !== 0) - break; - } - } - var HeaderMarshaller = class { - toUtf8; - fromUtf8; - constructor(toUtf811, fromUtf88) { - this.toUtf8 = toUtf811; - this.fromUtf8 = fromUtf88; - } - format(headers) { - const chunks = []; - for (const headerName of Object.keys(headers)) { - const bytes = this.fromUtf8(headerName); - chunks.push(Uint8Array.from([bytes.byteLength]), bytes, this.formatHeaderValue(headers[headerName])); - } - const out = new Uint8Array(chunks.reduce((carry, bytes) => carry + bytes.byteLength, 0)); - let position = 0; - for (const chunk of chunks) { - out.set(chunk, position); - position += chunk.byteLength; - } - return out; - } - formatHeaderValue(header) { - switch (header.type) { - case "boolean": - return Uint8Array.from([header.value ? 0 : 1]); - case "byte": - return Uint8Array.from([2, header.value]); - case "short": - const shortView = new DataView(new ArrayBuffer(3)); - shortView.setUint8(0, 3); - shortView.setInt16(1, header.value, false); - return new Uint8Array(shortView.buffer); - case "integer": - const intView = new DataView(new ArrayBuffer(5)); - intView.setUint8(0, 4); - intView.setInt32(1, header.value, false); - return new Uint8Array(intView.buffer); - case "long": - const longBytes = new Uint8Array(9); - longBytes[0] = 5; - longBytes.set(header.value.bytes, 1); - return longBytes; - case "binary": - const binView = new DataView(new ArrayBuffer(3 + header.value.byteLength)); - binView.setUint8(0, 6); - binView.setUint16(1, header.value.byteLength, false); - const binBytes = new Uint8Array(binView.buffer); - binBytes.set(header.value, 3); - return binBytes; - case "string": - const utf8Bytes = this.fromUtf8(header.value); - const strView = new DataView(new ArrayBuffer(3 + utf8Bytes.byteLength)); - strView.setUint8(0, 7); - strView.setUint16(1, utf8Bytes.byteLength, false); - const strBytes = new Uint8Array(strView.buffer); - strBytes.set(utf8Bytes, 3); - return strBytes; - case "timestamp": - const tsBytes = new Uint8Array(9); - tsBytes[0] = 8; - tsBytes.set(Int64.fromNumber(header.value.valueOf()).bytes, 1); - return tsBytes; - case "uuid": - if (!UUID_PATTERN2.test(header.value)) { - throw new Error(`Invalid UUID received: ${header.value}`); - } - const uuidBytes = new Uint8Array(17); - uuidBytes[0] = 9; - uuidBytes.set(utilHexEncoding.fromHex(header.value.replace(/\-/g, "")), 1); - return uuidBytes; - } - } - parse(headers) { - const out = {}; - let position = 0; - while (position < headers.byteLength) { - const nameLength = headers.getUint8(position++); - const name = this.toUtf8(new Uint8Array(headers.buffer, headers.byteOffset + position, nameLength)); - position += nameLength; - switch (headers.getUint8(position++)) { - case 0: - out[name] = { - type: BOOLEAN_TAG, - value: true - }; - break; - case 1: - out[name] = { - type: BOOLEAN_TAG, - value: false - }; - break; - case 2: - out[name] = { - type: BYTE_TAG, - value: headers.getInt8(position++) - }; - break; - case 3: - out[name] = { - type: SHORT_TAG, - value: headers.getInt16(position, false) - }; - position += 2; - break; - case 4: - out[name] = { - type: INT_TAG, - value: headers.getInt32(position, false) - }; - position += 4; - break; - case 5: - out[name] = { - type: LONG_TAG, - value: new Int64(new Uint8Array(headers.buffer, headers.byteOffset + position, 8)) - }; - position += 8; - break; - case 6: - const binaryLength = headers.getUint16(position, false); - position += 2; - out[name] = { - type: BINARY_TAG, - value: new Uint8Array(headers.buffer, headers.byteOffset + position, binaryLength) - }; - position += binaryLength; - break; - case 7: - const stringLength = headers.getUint16(position, false); - position += 2; - out[name] = { - type: STRING_TAG, - value: this.toUtf8(new Uint8Array(headers.buffer, headers.byteOffset + position, stringLength)) - }; - position += stringLength; - break; - case 8: - out[name] = { - type: TIMESTAMP_TAG, - value: new Date(new Int64(new Uint8Array(headers.buffer, headers.byteOffset + position, 8)).valueOf()) - }; - position += 8; - break; - case 9: - const uuidBytes = new Uint8Array(headers.buffer, headers.byteOffset + position, 16); - position += 16; - out[name] = { - type: UUID_TAG, - value: `${utilHexEncoding.toHex(uuidBytes.subarray(0, 4))}-${utilHexEncoding.toHex(uuidBytes.subarray(4, 6))}-${utilHexEncoding.toHex(uuidBytes.subarray(6, 8))}-${utilHexEncoding.toHex(uuidBytes.subarray(8, 10))}-${utilHexEncoding.toHex(uuidBytes.subarray(10))}` - }; - break; - default: - throw new Error(`Unrecognized header type tag`); - } - } - return out; - } - }; - var HEADER_VALUE_TYPE; - (function(HEADER_VALUE_TYPE2) { - HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["boolTrue"] = 0] = "boolTrue"; - HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["boolFalse"] = 1] = "boolFalse"; - HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["byte"] = 2] = "byte"; - HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["short"] = 3] = "short"; - HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["integer"] = 4] = "integer"; - HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["long"] = 5] = "long"; - HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["byteArray"] = 6] = "byteArray"; - HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["string"] = 7] = "string"; - HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["timestamp"] = 8] = "timestamp"; - HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["uuid"] = 9] = "uuid"; - })(HEADER_VALUE_TYPE || (HEADER_VALUE_TYPE = {})); - var BOOLEAN_TAG = "boolean"; - var BYTE_TAG = "byte"; - var SHORT_TAG = "short"; - var INT_TAG = "integer"; - var LONG_TAG = "long"; - var BINARY_TAG = "binary"; - var STRING_TAG = "string"; - var TIMESTAMP_TAG = "timestamp"; - var UUID_TAG = "uuid"; - var UUID_PATTERN2 = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/; - var PRELUDE_MEMBER_LENGTH = 4; - var PRELUDE_LENGTH = PRELUDE_MEMBER_LENGTH * 2; - var CHECKSUM_LENGTH = 4; - var MINIMUM_MESSAGE_LENGTH = PRELUDE_LENGTH + CHECKSUM_LENGTH * 2; - function splitMessage({ byteLength, byteOffset, buffer: buffer2 }) { - if (byteLength < MINIMUM_MESSAGE_LENGTH) { - throw new Error("Provided message too short to accommodate event stream message overhead"); - } - const view = new DataView(buffer2, byteOffset, byteLength); - const messageLength = view.getUint32(0, false); - if (byteLength !== messageLength) { - throw new Error("Reported message length does not match received message length"); - } - const headerLength = view.getUint32(PRELUDE_MEMBER_LENGTH, false); - const expectedPreludeChecksum = view.getUint32(PRELUDE_LENGTH, false); - const expectedMessageChecksum = view.getUint32(byteLength - CHECKSUM_LENGTH, false); - const checksummer = new crc32.Crc32().update(new Uint8Array(buffer2, byteOffset, PRELUDE_LENGTH)); - if (expectedPreludeChecksum !== checksummer.digest()) { - throw new Error(`The prelude checksum specified in the message (${expectedPreludeChecksum}) does not match the calculated CRC32 checksum (${checksummer.digest()})`); - } - checksummer.update(new Uint8Array(buffer2, byteOffset + PRELUDE_LENGTH, byteLength - (PRELUDE_LENGTH + CHECKSUM_LENGTH))); - if (expectedMessageChecksum !== checksummer.digest()) { - throw new Error(`The message checksum (${checksummer.digest()}) did not match the expected value of ${expectedMessageChecksum}`); - } - return { - headers: new DataView(buffer2, byteOffset + PRELUDE_LENGTH + CHECKSUM_LENGTH, headerLength), - body: new Uint8Array(buffer2, byteOffset + PRELUDE_LENGTH + CHECKSUM_LENGTH + headerLength, messageLength - headerLength - (PRELUDE_LENGTH + CHECKSUM_LENGTH + CHECKSUM_LENGTH)) - }; - } - var EventStreamCodec = class { - headerMarshaller; - messageBuffer; - isEndOfStream; - constructor(toUtf811, fromUtf88) { - this.headerMarshaller = new HeaderMarshaller(toUtf811, fromUtf88); - this.messageBuffer = []; - this.isEndOfStream = false; - } - feed(message2) { - this.messageBuffer.push(this.decode(message2)); - } - endOfStream() { - this.isEndOfStream = true; - } - getMessage() { - const message2 = this.messageBuffer.pop(); - const isEndOfStream = this.isEndOfStream; - return { - getMessage() { - return message2; - }, - isEndOfStream() { - return isEndOfStream; - } - }; - } - getAvailableMessages() { - const messages2 = this.messageBuffer; - this.messageBuffer = []; - const isEndOfStream = this.isEndOfStream; - return { - getMessages() { - return messages2; - }, - isEndOfStream() { - return isEndOfStream; - } - }; - } - encode({ headers: rawHeaders, body }) { - const headers = this.headerMarshaller.format(rawHeaders); - const length = headers.byteLength + body.byteLength + 16; - const out = new Uint8Array(length); - const view = new DataView(out.buffer, out.byteOffset, out.byteLength); - const checksum = new crc32.Crc32(); - view.setUint32(0, length, false); - view.setUint32(4, headers.byteLength, false); - view.setUint32(8, checksum.update(out.subarray(0, 8)).digest(), false); - out.set(headers, 12); - out.set(body, headers.byteLength + 12); - view.setUint32(length - 4, checksum.update(out.subarray(8, length - 4)).digest(), false); - return out; - } - decode(message2) { - const { headers, body } = splitMessage(message2); - return { headers: this.headerMarshaller.parse(headers), body }; - } - formatHeaders(rawHeaders) { - return this.headerMarshaller.format(rawHeaders); - } - }; - var MessageDecoderStream = class { - options; - constructor(options) { - this.options = options; - } - [Symbol.asyncIterator]() { - return this.asyncIterator(); - } - async *asyncIterator() { - for await (const bytes of this.options.inputStream) { - const decoded = this.options.decoder.decode(bytes); - yield decoded; - } - } - }; - var MessageEncoderStream = class { - options; - constructor(options) { - this.options = options; - } - [Symbol.asyncIterator]() { - return this.asyncIterator(); - } - async *asyncIterator() { - for await (const msg of this.options.messageStream) { - const encoded = this.options.encoder.encode(msg); - yield encoded; - } - if (this.options.includeEndFrame) { - yield new Uint8Array(0); - } - } - }; - var SmithyMessageDecoderStream = class { - options; - constructor(options) { - this.options = options; - } - [Symbol.asyncIterator]() { - return this.asyncIterator(); - } - async *asyncIterator() { - for await (const message2 of this.options.messageStream) { - const deserialized = await this.options.deserializer(message2); - if (deserialized === void 0) - continue; - yield deserialized; - } - } - }; - var SmithyMessageEncoderStream = class { - options; - constructor(options) { - this.options = options; - } - [Symbol.asyncIterator]() { - return this.asyncIterator(); - } - async *asyncIterator() { - for await (const chunk of this.options.inputStream) { - const payloadBuf = this.options.serializer(chunk); - yield payloadBuf; - } - } - }; - exports.EventStreamCodec = EventStreamCodec; - exports.HeaderMarshaller = HeaderMarshaller; - exports.Int64 = Int64; - exports.MessageDecoderStream = MessageDecoderStream; - exports.MessageEncoderStream = MessageEncoderStream; - exports.SmithyMessageDecoderStream = SmithyMessageDecoderStream; - exports.SmithyMessageEncoderStream = SmithyMessageEncoderStream; - } -}); - -// node_modules/.pnpm/@smithy+eventstream-serde-universal@4.2.13/node_modules/@smithy/eventstream-serde-universal/dist-cjs/index.js -var require_dist_cjs65 = __commonJS({ - "node_modules/.pnpm/@smithy+eventstream-serde-universal@4.2.13/node_modules/@smithy/eventstream-serde-universal/dist-cjs/index.js"(exports) { - "use strict"; - var eventstreamCodec = require_dist_cjs64(); - function getChunkedStream(source) { - let currentMessageTotalLength = 0; - let currentMessagePendingLength = 0; - let currentMessage = null; - let messageLengthBuffer = null; - const allocateMessage = (size2) => { - if (typeof size2 !== "number") { - throw new Error("Attempted to allocate an event message where size was not a number: " + size2); - } - currentMessageTotalLength = size2; - currentMessagePendingLength = 4; - currentMessage = new Uint8Array(size2); - const currentMessageView = new DataView(currentMessage.buffer); - currentMessageView.setUint32(0, size2, false); - }; - const iterator = async function* () { - const sourceIterator = source[Symbol.asyncIterator](); - while (true) { - const { value, done } = await sourceIterator.next(); - if (done) { - if (!currentMessageTotalLength) { - return; - } else if (currentMessageTotalLength === currentMessagePendingLength) { - yield currentMessage; - } else { - throw new Error("Truncated event message received."); - } - return; - } - const chunkLength = value.length; - let currentOffset = 0; - while (currentOffset < chunkLength) { - if (!currentMessage) { - const bytesRemaining = chunkLength - currentOffset; - if (!messageLengthBuffer) { - messageLengthBuffer = new Uint8Array(4); - } - const numBytesForTotal = Math.min(4 - currentMessagePendingLength, bytesRemaining); - messageLengthBuffer.set(value.slice(currentOffset, currentOffset + numBytesForTotal), currentMessagePendingLength); - currentMessagePendingLength += numBytesForTotal; - currentOffset += numBytesForTotal; - if (currentMessagePendingLength < 4) { - break; - } - allocateMessage(new DataView(messageLengthBuffer.buffer).getUint32(0, false)); - messageLengthBuffer = null; - } - const numBytesToWrite = Math.min(currentMessageTotalLength - currentMessagePendingLength, chunkLength - currentOffset); - currentMessage.set(value.slice(currentOffset, currentOffset + numBytesToWrite), currentMessagePendingLength); - currentMessagePendingLength += numBytesToWrite; - currentOffset += numBytesToWrite; - if (currentMessageTotalLength && currentMessageTotalLength === currentMessagePendingLength) { - yield currentMessage; - currentMessage = null; - currentMessageTotalLength = 0; - currentMessagePendingLength = 0; - } - } - } - }; - return { - [Symbol.asyncIterator]: iterator - }; - } - function getMessageUnmarshaller(deserializer, toUtf811) { - return async function(message2) { - const { value: messageType } = message2.headers[":message-type"]; - if (messageType === "error") { - const unmodeledError = new Error(message2.headers[":error-message"].value || "UnknownError"); - unmodeledError.name = message2.headers[":error-code"].value; - throw unmodeledError; - } else if (messageType === "exception") { - const code = message2.headers[":exception-type"].value; - const exception = { [code]: message2 }; - const deserializedException = await deserializer(exception); - if (deserializedException.$unknown) { - const error50 = new Error(toUtf811(message2.body)); - error50.name = code; - throw error50; - } - throw deserializedException[code]; - } else if (messageType === "event") { - const event = { - [message2.headers[":event-type"].value]: message2 - }; - const deserialized = await deserializer(event); - if (deserialized.$unknown) - return; - return deserialized; - } else { - throw Error(`Unrecognizable event type: ${message2.headers[":event-type"].value}`); - } - }; - } - var EventStreamMarshaller = class { - eventStreamCodec; - utfEncoder; - constructor({ utf8Encoder, utf8Decoder }) { - this.eventStreamCodec = new eventstreamCodec.EventStreamCodec(utf8Encoder, utf8Decoder); - this.utfEncoder = utf8Encoder; - } - deserialize(body, deserializer) { - const inputStream = getChunkedStream(body); - return new eventstreamCodec.SmithyMessageDecoderStream({ - messageStream: new eventstreamCodec.MessageDecoderStream({ inputStream, decoder: this.eventStreamCodec }), - deserializer: getMessageUnmarshaller(deserializer, this.utfEncoder) - }); - } - serialize(inputStream, serializer) { - return new eventstreamCodec.MessageEncoderStream({ - messageStream: new eventstreamCodec.SmithyMessageEncoderStream({ inputStream, serializer }), - encoder: this.eventStreamCodec, - includeEndFrame: true - }); - } - }; - var eventStreamSerdeProvider = (options) => new EventStreamMarshaller(options); - exports.EventStreamMarshaller = EventStreamMarshaller; - exports.eventStreamSerdeProvider = eventStreamSerdeProvider; - } -}); - -// node_modules/.pnpm/@smithy+eventstream-serde-node@4.2.13/node_modules/@smithy/eventstream-serde-node/dist-cjs/index.js -var require_dist_cjs66 = __commonJS({ - "node_modules/.pnpm/@smithy+eventstream-serde-node@4.2.13/node_modules/@smithy/eventstream-serde-node/dist-cjs/index.js"(exports) { - "use strict"; - var eventstreamSerdeUniversal = require_dist_cjs65(); - var stream = __require("stream"); - async function* readabletoIterable(readStream) { - let streamEnded = false; - let generationEnded = false; - const records = new Array(); - readStream.on("error", (err) => { - if (!streamEnded) { - streamEnded = true; - } - if (err) { - throw err; - } - }); - readStream.on("data", (data2) => { - records.push(data2); - }); - readStream.on("end", () => { - streamEnded = true; - }); - while (!generationEnded) { - const value = await new Promise((resolve4) => setTimeout(() => resolve4(records.shift()), 0)); - if (value) { - yield value; - } - generationEnded = streamEnded && records.length === 0; - } - } - var EventStreamMarshaller = class { - universalMarshaller; - constructor({ utf8Encoder, utf8Decoder }) { - this.universalMarshaller = new eventstreamSerdeUniversal.EventStreamMarshaller({ - utf8Decoder, - utf8Encoder - }); - } - deserialize(body, deserializer) { - const bodyIterable = typeof body[Symbol.asyncIterator] === "function" ? body : readabletoIterable(body); - return this.universalMarshaller.deserialize(bodyIterable, deserializer); - } - serialize(input, serializer) { - return stream.Readable.from(this.universalMarshaller.serialize(input, serializer)); - } - }; - var eventStreamSerdeProvider = (options) => new EventStreamMarshaller(options); - exports.EventStreamMarshaller = EventStreamMarshaller; - exports.eventStreamSerdeProvider = eventStreamSerdeProvider; - } -}); - -// node_modules/.pnpm/@smithy+hash-stream-node@4.2.13/node_modules/@smithy/hash-stream-node/dist-cjs/index.js -var require_dist_cjs67 = __commonJS({ - "node_modules/.pnpm/@smithy+hash-stream-node@4.2.13/node_modules/@smithy/hash-stream-node/dist-cjs/index.js"(exports) { - "use strict"; - var fs41 = __require("fs"); - var utilUtf8 = require_dist_cjs6(); - var stream = __require("stream"); - var HashCalculator = class extends stream.Writable { - hash; - constructor(hash2, options) { - super(options); - this.hash = hash2; - } - _write(chunk, encoding, callback) { - try { - this.hash.update(utilUtf8.toUint8Array(chunk)); - } catch (err) { - return callback(err); - } - callback(); - } - }; - var fileStreamHasher = (hashCtor, fileStream) => new Promise((resolve4, reject) => { - if (!isReadStream(fileStream)) { - reject(new Error("Unable to calculate hash for non-file streams.")); - return; - } - const fileStreamTee = fs41.createReadStream(fileStream.path, { - start: fileStream.start, - end: fileStream.end - }); - const hash2 = new hashCtor(); - const hashCalculator = new HashCalculator(hash2); - fileStreamTee.pipe(hashCalculator); - fileStreamTee.on("error", (err) => { - hashCalculator.end(); - reject(err); - }); - hashCalculator.on("error", reject); - hashCalculator.on("finish", function() { - hash2.digest().then(resolve4).catch(reject); - }); - }); - var isReadStream = (stream2) => typeof stream2.path === "string"; - var readableStreamHasher = (hashCtor, readableStream) => { - if (readableStream.readableFlowing !== null) { - throw new Error("Unable to calculate hash for flowing readable stream"); - } - const hash2 = new hashCtor(); - const hashCalculator = new HashCalculator(hash2); - readableStream.pipe(hashCalculator); - return new Promise((resolve4, reject) => { - readableStream.on("error", (err) => { - hashCalculator.end(); - reject(err); - }); - hashCalculator.on("error", reject); - hashCalculator.on("finish", () => { - hash2.digest().then(resolve4).catch(reject); - }); - }); - }; - exports.fileStreamHasher = fileStreamHasher; - exports.readableStreamHasher = readableStreamHasher; - } -}); - -// node_modules/.pnpm/@aws-sdk+client-s3@3.1030.0/node_modules/@aws-sdk/client-s3/dist-cjs/runtimeConfig.shared.js -var require_runtimeConfig_shared = __commonJS({ - "node_modules/.pnpm/@aws-sdk+client-s3@3.1030.0/node_modules/@aws-sdk/client-s3/dist-cjs/runtimeConfig.shared.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.getRuntimeConfig = void 0; - var httpAuthSchemes_1 = (init_httpAuthSchemes2(), __toCommonJS(httpAuthSchemes_exports)); - var middleware_sdk_s3_1 = require_dist_cjs32(); - var signature_v4_multi_region_1 = require_dist_cjs47(); - var smithy_client_1 = require_dist_cjs27(); - var url_parser_1 = require_dist_cjs25(); - var util_base64_1 = require_dist_cjs7(); - var util_stream_1 = require_dist_cjs13(); - var util_utf8_1 = require_dist_cjs6(); - var httpAuthSchemeProvider_1 = require_httpAuthSchemeProvider(); - var endpointResolver_1 = require_endpointResolver(); - var schemas_0_1 = require_schemas_0(); - var getRuntimeConfig9 = (config3) => { - return { - apiVersion: "2006-03-01", - base64Decoder: config3?.base64Decoder ?? util_base64_1.fromBase64, - base64Encoder: config3?.base64Encoder ?? util_base64_1.toBase64, - disableHostPrefix: config3?.disableHostPrefix ?? false, - endpointProvider: config3?.endpointProvider ?? endpointResolver_1.defaultEndpointResolver, - extensions: config3?.extensions ?? [], - getAwsChunkedEncodingStream: config3?.getAwsChunkedEncodingStream ?? util_stream_1.getAwsChunkedEncodingStream, - httpAuthSchemeProvider: config3?.httpAuthSchemeProvider ?? httpAuthSchemeProvider_1.defaultS3HttpAuthSchemeProvider, - httpAuthSchemes: config3?.httpAuthSchemes ?? [ - { - schemeId: "aws.auth#sigv4", - identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"), - signer: new httpAuthSchemes_1.AwsSdkSigV4Signer() - }, - { - schemeId: "aws.auth#sigv4a", - identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4a"), - signer: new httpAuthSchemes_1.AwsSdkSigV4ASigner() - } - ], - logger: config3?.logger ?? new smithy_client_1.NoOpLogger(), - protocol: config3?.protocol ?? middleware_sdk_s3_1.S3RestXmlProtocol, - protocolSettings: config3?.protocolSettings ?? { - defaultNamespace: "com.amazonaws.s3", - errorTypeRegistries: schemas_0_1.errorTypeRegistries, - xmlNamespace: "http://s3.amazonaws.com/doc/2006-03-01/", - version: "2006-03-01", - serviceTarget: "AmazonS3" - }, - sdkStreamMixin: config3?.sdkStreamMixin ?? util_stream_1.sdkStreamMixin, - serviceId: config3?.serviceId ?? "S3", - signerConstructor: config3?.signerConstructor ?? signature_v4_multi_region_1.SignatureV4MultiRegion, - signingEscapePath: config3?.signingEscapePath ?? false, - urlParser: config3?.urlParser ?? url_parser_1.parseUrl, - useArnRegion: config3?.useArnRegion ?? void 0, - utf8Decoder: config3?.utf8Decoder ?? util_utf8_1.fromUtf8, - utf8Encoder: config3?.utf8Encoder ?? util_utf8_1.toUtf8 - }; - }; - exports.getRuntimeConfig = getRuntimeConfig9; - } -}); - -// node_modules/.pnpm/@aws-sdk+client-s3@3.1030.0/node_modules/@aws-sdk/client-s3/dist-cjs/runtimeConfig.js -var require_runtimeConfig = __commonJS({ - "node_modules/.pnpm/@aws-sdk+client-s3@3.1030.0/node_modules/@aws-sdk/client-s3/dist-cjs/runtimeConfig.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.getRuntimeConfig = void 0; - var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); - var package_json_1 = tslib_1.__importDefault(require_package2()); - var client_1 = (init_client2(), __toCommonJS(client_exports)); - var httpAuthSchemes_1 = (init_httpAuthSchemes2(), __toCommonJS(httpAuthSchemes_exports)); - var credential_provider_node_1 = require_dist_cjs62(); - var middleware_bucket_endpoint_1 = require_dist_cjs63(); - var middleware_flexible_checksums_1 = require_dist_cjs19(); - var middleware_sdk_s3_1 = require_dist_cjs32(); - var util_user_agent_node_1 = require_dist_cjs51(); - var config_resolver_1 = require_dist_cjs38(); - var eventstream_serde_node_1 = require_dist_cjs66(); - var hash_node_1 = require_dist_cjs52(); - var hash_stream_node_1 = require_dist_cjs67(); - var middleware_retry_1 = require_dist_cjs46(); - var node_config_provider_1 = require_dist_cjs43(); - var node_http_handler_1 = require_dist_cjs10(); - var smithy_client_1 = require_dist_cjs27(); - var util_body_length_node_1 = require_dist_cjs53(); - var util_defaults_mode_node_1 = require_dist_cjs54(); - var util_retry_1 = require_dist_cjs36(); - var runtimeConfig_shared_1 = require_runtimeConfig_shared(); - var getRuntimeConfig9 = (config3) => { - (0, smithy_client_1.emitWarningIfUnsupportedVersion)(process.version); - const defaultsMode = (0, util_defaults_mode_node_1.resolveDefaultsModeConfig)(config3); - const defaultConfigProvider = () => defaultsMode().then(smithy_client_1.loadConfigsForDefaultMode); - const clientSharedValues = (0, runtimeConfig_shared_1.getRuntimeConfig)(config3); - (0, client_1.emitWarningIfUnsupportedVersion)(process.version); - const loaderConfig = { - profile: config3?.profile, - logger: clientSharedValues.logger - }; - return { - ...clientSharedValues, - ...config3, - runtime: "node", - defaultsMode, - authSchemePreference: config3?.authSchemePreference ?? (0, node_config_provider_1.loadConfig)(httpAuthSchemes_1.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig), - bodyLengthChecker: config3?.bodyLengthChecker ?? util_body_length_node_1.calculateBodyLength, - credentialDefaultProvider: config3?.credentialDefaultProvider ?? credential_provider_node_1.defaultProvider, - defaultUserAgentProvider: config3?.defaultUserAgentProvider ?? (0, util_user_agent_node_1.createDefaultUserAgentProvider)({ serviceId: clientSharedValues.serviceId, clientVersion: package_json_1.default.version }), - disableS3ExpressSessionAuth: config3?.disableS3ExpressSessionAuth ?? (0, node_config_provider_1.loadConfig)(middleware_sdk_s3_1.NODE_DISABLE_S3_EXPRESS_SESSION_AUTH_OPTIONS, loaderConfig), - eventStreamSerdeProvider: config3?.eventStreamSerdeProvider ?? eventstream_serde_node_1.eventStreamSerdeProvider, - maxAttempts: config3?.maxAttempts ?? (0, node_config_provider_1.loadConfig)(middleware_retry_1.NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config3), - md5: config3?.md5 ?? hash_node_1.Hash.bind(null, "md5"), - region: config3?.region ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_REGION_CONFIG_OPTIONS, { ...config_resolver_1.NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }), - requestChecksumCalculation: config3?.requestChecksumCalculation ?? (0, node_config_provider_1.loadConfig)(middleware_flexible_checksums_1.NODE_REQUEST_CHECKSUM_CALCULATION_CONFIG_OPTIONS, loaderConfig), - requestHandler: node_http_handler_1.NodeHttpHandler.create(config3?.requestHandler ?? defaultConfigProvider), - responseChecksumValidation: config3?.responseChecksumValidation ?? (0, node_config_provider_1.loadConfig)(middleware_flexible_checksums_1.NODE_RESPONSE_CHECKSUM_VALIDATION_CONFIG_OPTIONS, loaderConfig), - retryMode: config3?.retryMode ?? (0, node_config_provider_1.loadConfig)({ - ...middleware_retry_1.NODE_RETRY_MODE_CONFIG_OPTIONS, - default: async () => (await defaultConfigProvider()).retryMode || util_retry_1.DEFAULT_RETRY_MODE - }, config3), - sha1: config3?.sha1 ?? hash_node_1.Hash.bind(null, "sha1"), - sha256: config3?.sha256 ?? hash_node_1.Hash.bind(null, "sha256"), - sigv4aSigningRegionSet: config3?.sigv4aSigningRegionSet ?? (0, node_config_provider_1.loadConfig)(httpAuthSchemes_1.NODE_SIGV4A_CONFIG_OPTIONS, loaderConfig), - streamCollector: config3?.streamCollector ?? node_http_handler_1.streamCollector, - streamHasher: config3?.streamHasher ?? hash_stream_node_1.readableStreamHasher, - useArnRegion: config3?.useArnRegion ?? (0, node_config_provider_1.loadConfig)(middleware_bucket_endpoint_1.NODE_USE_ARN_REGION_CONFIG_OPTIONS, loaderConfig), - useDualstackEndpoint: config3?.useDualstackEndpoint ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig), - useFipsEndpoint: config3?.useFipsEndpoint ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig), - userAgentAppId: config3?.userAgentAppId ?? (0, node_config_provider_1.loadConfig)(util_user_agent_node_1.NODE_APP_ID_CONFIG_OPTIONS, loaderConfig) - }; - }; - exports.getRuntimeConfig = getRuntimeConfig9; - } -}); - -// node_modules/.pnpm/@aws-sdk+middleware-ssec@3.972.9/node_modules/@aws-sdk/middleware-ssec/dist-cjs/index.js -var require_dist_cjs68 = __commonJS({ - "node_modules/.pnpm/@aws-sdk+middleware-ssec@3.972.9/node_modules/@aws-sdk/middleware-ssec/dist-cjs/index.js"(exports) { - "use strict"; - function ssecMiddleware(options) { - return (next) => async (args) => { - const input = { ...args.input }; - const properties = [ - { - target: "SSECustomerKey", - hash: "SSECustomerKeyMD5" - }, - { - target: "CopySourceSSECustomerKey", - hash: "CopySourceSSECustomerKeyMD5" - } - ]; - for (const prop of properties) { - const value = input[prop.target]; - if (value) { - let valueForHash; - if (typeof value === "string") { - if (isValidBase64EncodedSSECustomerKey(value, options)) { - valueForHash = options.base64Decoder(value); - } else { - valueForHash = options.utf8Decoder(value); - input[prop.target] = options.base64Encoder(valueForHash); - } - } else { - valueForHash = ArrayBuffer.isView(value) ? new Uint8Array(value.buffer, value.byteOffset, value.byteLength) : new Uint8Array(value); - input[prop.target] = options.base64Encoder(valueForHash); - } - const hash2 = new options.md5(); - hash2.update(valueForHash); - input[prop.hash] = options.base64Encoder(await hash2.digest()); - } - } - return next({ - ...args, - input - }); - }; - } - var ssecMiddlewareOptions = { - name: "ssecMiddleware", - step: "initialize", - tags: ["SSE"], - override: true - }; - var getSsecPlugin = (config3) => ({ - applyToStack: (clientStack) => { - clientStack.add(ssecMiddleware(config3), ssecMiddlewareOptions); - } - }); - function isValidBase64EncodedSSECustomerKey(str, options) { - const base64Regex2 = /^(?:[A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/; - if (!base64Regex2.test(str)) - return false; - try { - const decodedBytes = options.base64Decoder(str); - return decodedBytes.length === 32; - } catch { - return false; - } - } - exports.getSsecPlugin = getSsecPlugin; - exports.isValidBase64EncodedSSECustomerKey = isValidBase64EncodedSSECustomerKey; - exports.ssecMiddleware = ssecMiddleware; - exports.ssecMiddlewareOptions = ssecMiddlewareOptions; - } -}); - -// node_modules/.pnpm/@aws-sdk+middleware-location-constraint@3.972.9/node_modules/@aws-sdk/middleware-location-constraint/dist-cjs/index.js -var require_dist_cjs69 = __commonJS({ - "node_modules/.pnpm/@aws-sdk+middleware-location-constraint@3.972.9/node_modules/@aws-sdk/middleware-location-constraint/dist-cjs/index.js"(exports) { - "use strict"; - function locationConstraintMiddleware(options) { - return (next) => async (args) => { - const { CreateBucketConfiguration } = args.input; - const region = await options.region(); - if (!CreateBucketConfiguration?.LocationConstraint && !CreateBucketConfiguration?.Location) { - if (region !== "us-east-1") { - args.input.CreateBucketConfiguration = args.input.CreateBucketConfiguration ?? {}; - args.input.CreateBucketConfiguration.LocationConstraint = region; - } - } - return next(args); - }; - } - var locationConstraintMiddlewareOptions = { - step: "initialize", - tags: ["LOCATION_CONSTRAINT", "CREATE_BUCKET_CONFIGURATION"], - name: "locationConstraintMiddleware", - override: true - }; - var getLocationConstraintPlugin = (config3) => ({ - applyToStack: (clientStack) => { - clientStack.add(locationConstraintMiddleware(config3), locationConstraintMiddlewareOptions); - } - }); - exports.getLocationConstraintPlugin = getLocationConstraintPlugin; - exports.locationConstraintMiddleware = locationConstraintMiddleware; - exports.locationConstraintMiddlewareOptions = locationConstraintMiddlewareOptions; - } -}); - -// node_modules/.pnpm/@smithy+util-waiter@4.2.15/node_modules/@smithy/util-waiter/dist-cjs/index.js -var require_dist_cjs70 = __commonJS({ - "node_modules/.pnpm/@smithy+util-waiter@4.2.15/node_modules/@smithy/util-waiter/dist-cjs/index.js"(exports) { - "use strict"; - var getCircularReplacer = () => { - const seen = /* @__PURE__ */ new WeakSet(); - return (key, value) => { - if (typeof value === "object" && value !== null) { - if (seen.has(value)) { - return "[Circular]"; - } - seen.add(value); - } - return value; - }; - }; - var sleep = (seconds) => { - return new Promise((resolve4) => setTimeout(resolve4, seconds * 1e3)); - }; - var waiterServiceDefaults = { - minDelay: 2, - maxDelay: 120 - }; - exports.WaiterState = void 0; - (function(WaiterState) { - WaiterState["ABORTED"] = "ABORTED"; - WaiterState["FAILURE"] = "FAILURE"; - WaiterState["SUCCESS"] = "SUCCESS"; - WaiterState["RETRY"] = "RETRY"; - WaiterState["TIMEOUT"] = "TIMEOUT"; - })(exports.WaiterState || (exports.WaiterState = {})); - var checkExceptions = (result) => { - if (result.state === exports.WaiterState.ABORTED) { - const abortError = new Error(`${JSON.stringify({ - ...result, - reason: "Request was aborted" - }, getCircularReplacer())}`); - abortError.name = "AbortError"; - throw abortError; - } else if (result.state === exports.WaiterState.TIMEOUT) { - const timeoutError = new Error(`${JSON.stringify({ - ...result, - reason: "Waiter has timed out" - }, getCircularReplacer())}`); - timeoutError.name = "TimeoutError"; - throw timeoutError; - } else if (result.state !== exports.WaiterState.SUCCESS) { - throw new Error(`${JSON.stringify(result, getCircularReplacer())}`); - } - return result; - }; - var exponentialBackoffWithJitter = (minDelay, maxDelay, attemptCeiling, attempt) => { - if (attempt > attemptCeiling) - return maxDelay; - const delay3 = minDelay * 2 ** (attempt - 1); - return randomInRange(minDelay, delay3); - }; - var randomInRange = (min, max) => min + Math.random() * (max - min); - var runPolling = async ({ minDelay, maxDelay, maxWaitTime, abortController, client: client2, abortSignal }, input, acceptorChecks) => { - const observedResponses = {}; - const { state: state2, reason } = await acceptorChecks(client2, input); - if (reason) { - const message2 = createMessageFromResponse(reason); - observedResponses[message2] |= 0; - observedResponses[message2] += 1; - } - if (state2 !== exports.WaiterState.RETRY) { - return { state: state2, reason, observedResponses }; - } - let currentAttempt = 1; - const waitUntil = Date.now() + maxWaitTime * 1e3; - const attemptCeiling = Math.log(maxDelay / minDelay) / Math.log(2) + 1; - while (true) { - if (abortController?.signal?.aborted || abortSignal?.aborted) { - const message2 = "AbortController signal aborted."; - observedResponses[message2] |= 0; - observedResponses[message2] += 1; - return { state: exports.WaiterState.ABORTED, observedResponses }; - } - const delay3 = exponentialBackoffWithJitter(minDelay, maxDelay, attemptCeiling, currentAttempt); - if (Date.now() + delay3 * 1e3 > waitUntil) { - return { state: exports.WaiterState.TIMEOUT, observedResponses }; - } - await sleep(delay3); - const { state: state3, reason: reason2 } = await acceptorChecks(client2, input); - if (reason2) { - const message2 = createMessageFromResponse(reason2); - observedResponses[message2] |= 0; - observedResponses[message2] += 1; - } - if (state3 !== exports.WaiterState.RETRY) { - return { state: state3, reason: reason2, observedResponses }; - } - currentAttempt += 1; - } - }; - var createMessageFromResponse = (reason) => { - if (reason?.$responseBodyText) { - return `Deserialization error for body: ${reason.$responseBodyText}`; - } - if (reason?.$metadata?.httpStatusCode) { - if (reason.$response || reason.message) { - return `${reason.$response?.statusCode ?? reason.$metadata.httpStatusCode ?? "Unknown"}: ${reason.message}`; - } - return `${reason.$metadata.httpStatusCode}: OK`; - } - return String(reason?.message ?? JSON.stringify(reason, getCircularReplacer()) ?? "Unknown"); - }; - var validateWaiterOptions = (options) => { - if (options.maxWaitTime <= 0) { - throw new Error(`WaiterConfiguration.maxWaitTime must be greater than 0`); - } else if (options.minDelay <= 0) { - throw new Error(`WaiterConfiguration.minDelay must be greater than 0`); - } else if (options.maxDelay <= 0) { - throw new Error(`WaiterConfiguration.maxDelay must be greater than 0`); - } else if (options.maxWaitTime <= options.minDelay) { - throw new Error(`WaiterConfiguration.maxWaitTime [${options.maxWaitTime}] must be greater than WaiterConfiguration.minDelay [${options.minDelay}] for this waiter`); - } else if (options.maxDelay < options.minDelay) { - throw new Error(`WaiterConfiguration.maxDelay [${options.maxDelay}] must be greater than WaiterConfiguration.minDelay [${options.minDelay}] for this waiter`); - } - }; - var abortTimeout = (abortSignal) => { - let onAbort; - const promise2 = new Promise((resolve4) => { - onAbort = () => resolve4({ state: exports.WaiterState.ABORTED }); - if (typeof abortSignal.addEventListener === "function") { - abortSignal.addEventListener("abort", onAbort); - } else { - abortSignal.onabort = onAbort; - } - }); - return { - clearListener() { - if (typeof abortSignal.removeEventListener === "function") { - abortSignal.removeEventListener("abort", onAbort); - } - }, - aborted: promise2 - }; - }; - var createWaiter = async (options, input, acceptorChecks) => { - const params = { - ...waiterServiceDefaults, - ...options - }; - validateWaiterOptions(params); - const exitConditions = [runPolling(params, input, acceptorChecks)]; - const finalize2 = []; - if (options.abortSignal) { - const { aborted: aborted2, clearListener } = abortTimeout(options.abortSignal); - finalize2.push(clearListener); - exitConditions.push(aborted2); - } - if (options.abortController?.signal) { - const { aborted: aborted2, clearListener } = abortTimeout(options.abortController.signal); - finalize2.push(clearListener); - exitConditions.push(aborted2); - } - return Promise.race(exitConditions).then((result) => { - for (const fn of finalize2) { - fn(); - } - return result; - }); - }; - exports.checkExceptions = checkExceptions; - exports.createWaiter = createWaiter; - exports.waiterServiceDefaults = waiterServiceDefaults; - } -}); - -// node_modules/.pnpm/@aws-sdk+client-s3@3.1030.0/node_modules/@aws-sdk/client-s3/dist-cjs/index.js -var require_dist_cjs71 = __commonJS({ - "node_modules/.pnpm/@aws-sdk+client-s3@3.1030.0/node_modules/@aws-sdk/client-s3/dist-cjs/index.js"(exports) { - "use strict"; - var middlewareExpectContinue = require_dist_cjs3(); - var middlewareFlexibleChecksums = require_dist_cjs19(); - var middlewareHostHeader = require_dist_cjs20(); - var middlewareLogger = require_dist_cjs21(); - var middlewareRecursionDetection = require_dist_cjs22(); - var middlewareSdkS3 = require_dist_cjs32(); - var middlewareUserAgent = require_dist_cjs37(); - var configResolver = require_dist_cjs38(); - var core = (init_dist_es(), __toCommonJS(dist_es_exports)); - var schema2 = (init_schema3(), __toCommonJS(schema_exports2)); - var eventstreamSerdeConfigResolver = require_dist_cjs39(); - var middlewareContentLength = require_dist_cjs40(); - var middlewareEndpoint = require_dist_cjs45(); - var middlewareRetry = require_dist_cjs46(); - var smithyClient = require_dist_cjs27(); - var httpAuthSchemeProvider = require_httpAuthSchemeProvider(); - var schemas_0 = require_schemas_0(); - var runtimeConfig = require_runtimeConfig(); - var regionConfigResolver = require_dist_cjs55(); - var protocolHttp = require_dist_cjs2(); - var middlewareSsec = require_dist_cjs68(); - var middlewareLocationConstraint = require_dist_cjs69(); - var utilWaiter = require_dist_cjs70(); - var errors = require_errors(); - var S3ServiceException = require_S3ServiceException(); - var resolveClientEndpointParameters5 = (options) => { - return Object.assign(options, { - useFipsEndpoint: options.useFipsEndpoint ?? false, - useDualstackEndpoint: options.useDualstackEndpoint ?? false, - forcePathStyle: options.forcePathStyle ?? false, - useAccelerateEndpoint: options.useAccelerateEndpoint ?? false, - useGlobalEndpoint: options.useGlobalEndpoint ?? false, - disableMultiregionAccessPoints: options.disableMultiregionAccessPoints ?? false, - defaultSigningName: "s3", - clientContextParams: options.clientContextParams ?? {} - }); - }; - var commonParams5 = { - ForcePathStyle: { type: "clientContextParams", name: "forcePathStyle" }, - UseArnRegion: { type: "clientContextParams", name: "useArnRegion" }, - DisableMultiRegionAccessPoints: { type: "clientContextParams", name: "disableMultiregionAccessPoints" }, - Accelerate: { type: "clientContextParams", name: "useAccelerateEndpoint" }, - DisableS3ExpressSessionAuth: { type: "clientContextParams", name: "disableS3ExpressSessionAuth" }, - UseGlobalEndpoint: { type: "builtInParams", name: "useGlobalEndpoint" }, - UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, - Endpoint: { type: "builtInParams", name: "endpoint" }, - Region: { type: "builtInParams", name: "region" }, - UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" } - }; - var CreateSessionCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - DisableS3ExpressSessionAuth: { type: "staticContextParams", value: true }, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareSdkS3.getThrow200ExceptionsPlugin(config3) - ]; - }).s("AmazonS3", "CreateSession", {}).n("S3Client", "CreateSessionCommand").sc(schemas_0.CreateSession$).build() { - }; - var getHttpAuthExtensionConfiguration5 = (runtimeConfig2) => { - const _httpAuthSchemes = runtimeConfig2.httpAuthSchemes; - let _httpAuthSchemeProvider = runtimeConfig2.httpAuthSchemeProvider; - let _credentials = runtimeConfig2.credentials; - return { - setHttpAuthScheme(httpAuthScheme) { - const index2 = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId); - if (index2 === -1) { - _httpAuthSchemes.push(httpAuthScheme); - } else { - _httpAuthSchemes.splice(index2, 1, httpAuthScheme); - } - }, - httpAuthSchemes() { - return _httpAuthSchemes; - }, - setHttpAuthSchemeProvider(httpAuthSchemeProvider2) { - _httpAuthSchemeProvider = httpAuthSchemeProvider2; - }, - httpAuthSchemeProvider() { - return _httpAuthSchemeProvider; - }, - setCredentials(credentials) { - _credentials = credentials; - }, - credentials() { - return _credentials; - } - }; - }; - var resolveHttpAuthRuntimeConfig5 = (config3) => { - return { - httpAuthSchemes: config3.httpAuthSchemes(), - httpAuthSchemeProvider: config3.httpAuthSchemeProvider(), - credentials: config3.credentials() - }; - }; - var resolveRuntimeExtensions5 = (runtimeConfig2, extensions) => { - const extensionConfiguration = Object.assign(regionConfigResolver.getAwsRegionExtensionConfiguration(runtimeConfig2), smithyClient.getDefaultExtensionConfiguration(runtimeConfig2), protocolHttp.getHttpHandlerExtensionConfiguration(runtimeConfig2), getHttpAuthExtensionConfiguration5(runtimeConfig2)); - extensions.forEach((extension2) => extension2.configure(extensionConfiguration)); - return Object.assign(runtimeConfig2, regionConfigResolver.resolveAwsRegionExtensionConfiguration(extensionConfiguration), smithyClient.resolveDefaultRuntimeConfig(extensionConfiguration), protocolHttp.resolveHttpHandlerRuntimeConfig(extensionConfiguration), resolveHttpAuthRuntimeConfig5(extensionConfiguration)); - }; - var S3Client2 = class extends smithyClient.Client { - config; - constructor(...[configuration]) { - const _config_0 = runtimeConfig.getRuntimeConfig(configuration || {}); - super(_config_0); - this.initConfig = _config_0; - const _config_1 = resolveClientEndpointParameters5(_config_0); - const _config_2 = middlewareUserAgent.resolveUserAgentConfig(_config_1); - const _config_3 = middlewareFlexibleChecksums.resolveFlexibleChecksumsConfig(_config_2); - const _config_4 = middlewareRetry.resolveRetryConfig(_config_3); - const _config_5 = configResolver.resolveRegionConfig(_config_4); - const _config_6 = middlewareHostHeader.resolveHostHeaderConfig(_config_5); - const _config_7 = middlewareEndpoint.resolveEndpointConfig(_config_6); - const _config_8 = eventstreamSerdeConfigResolver.resolveEventStreamSerdeConfig(_config_7); - const _config_9 = httpAuthSchemeProvider.resolveHttpAuthSchemeConfig(_config_8); - const _config_10 = middlewareSdkS3.resolveS3Config(_config_9, { session: [() => this, CreateSessionCommand] }); - const _config_11 = resolveRuntimeExtensions5(_config_10, configuration?.extensions || []); - this.config = _config_11; - this.middlewareStack.use(schema2.getSchemaSerdePlugin(this.config)); - this.middlewareStack.use(middlewareUserAgent.getUserAgentPlugin(this.config)); - this.middlewareStack.use(middlewareRetry.getRetryPlugin(this.config)); - this.middlewareStack.use(middlewareContentLength.getContentLengthPlugin(this.config)); - this.middlewareStack.use(middlewareHostHeader.getHostHeaderPlugin(this.config)); - this.middlewareStack.use(middlewareLogger.getLoggerPlugin(this.config)); - this.middlewareStack.use(middlewareRecursionDetection.getRecursionDetectionPlugin(this.config)); - this.middlewareStack.use(core.getHttpAuthSchemeEndpointRuleSetPlugin(this.config, { - httpAuthSchemeParametersProvider: httpAuthSchemeProvider.defaultS3HttpAuthSchemeParametersProvider, - identityProviderConfigProvider: async (config3) => new core.DefaultIdentityProviderConfig({ - "aws.auth#sigv4": config3.credentials, - "aws.auth#sigv4a": config3.credentials - }) - })); - this.middlewareStack.use(core.getHttpSigningPlugin(this.config)); - this.middlewareStack.use(middlewareSdkS3.getValidateBucketNamePlugin(this.config)); - this.middlewareStack.use(middlewareExpectContinue.getAddExpectContinuePlugin(this.config)); - this.middlewareStack.use(middlewareSdkS3.getRegionRedirectMiddlewarePlugin(this.config)); - this.middlewareStack.use(middlewareSdkS3.getS3ExpressPlugin(this.config)); - this.middlewareStack.use(middlewareSdkS3.getS3ExpressHttpSigningPlugin(this.config)); - } - destroy() { - super.destroy(); - } - }; - var AbortMultipartUploadCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - Bucket: { type: "contextParams", name: "Bucket" }, - Key: { type: "contextParams", name: "Key" } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareSdkS3.getThrow200ExceptionsPlugin(config3) - ]; - }).s("AmazonS3", "AbortMultipartUpload", {}).n("S3Client", "AbortMultipartUploadCommand").sc(schemas_0.AbortMultipartUpload$).build() { - }; - var CompleteMultipartUploadCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - Bucket: { type: "contextParams", name: "Bucket" }, - Key: { type: "contextParams", name: "Key" } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareSdkS3.getThrow200ExceptionsPlugin(config3), - middlewareSsec.getSsecPlugin(config3) - ]; - }).s("AmazonS3", "CompleteMultipartUpload", {}).n("S3Client", "CompleteMultipartUploadCommand").sc(schemas_0.CompleteMultipartUpload$).build() { - }; - var CopyObjectCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - DisableS3ExpressSessionAuth: { type: "staticContextParams", value: true }, - Bucket: { type: "contextParams", name: "Bucket" }, - Key: { type: "contextParams", name: "Key" }, - CopySource: { type: "contextParams", name: "CopySource" } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareSdkS3.getThrow200ExceptionsPlugin(config3), - middlewareSsec.getSsecPlugin(config3) - ]; - }).s("AmazonS3", "CopyObject", {}).n("S3Client", "CopyObjectCommand").sc(schemas_0.CopyObject$).build() { - }; - var CreateBucketCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, - DisableAccessPoints: { type: "staticContextParams", value: true }, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareSdkS3.getThrow200ExceptionsPlugin(config3), - middlewareLocationConstraint.getLocationConstraintPlugin(config3) - ]; - }).s("AmazonS3", "CreateBucket", {}).n("S3Client", "CreateBucketCommand").sc(schemas_0.CreateBucket$).build() { - }; - var CreateBucketMetadataConfigurationCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareFlexibleChecksums.getFlexibleChecksumsPlugin(config3, { - requestAlgorithmMember: { "httpHeader": "x-amz-sdk-checksum-algorithm", "name": "ChecksumAlgorithm" }, - requestChecksumRequired: true - }) - ]; - }).s("AmazonS3", "CreateBucketMetadataConfiguration", {}).n("S3Client", "CreateBucketMetadataConfigurationCommand").sc(schemas_0.CreateBucketMetadataConfiguration$).build() { - }; - var CreateBucketMetadataTableConfigurationCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareFlexibleChecksums.getFlexibleChecksumsPlugin(config3, { - requestAlgorithmMember: { "httpHeader": "x-amz-sdk-checksum-algorithm", "name": "ChecksumAlgorithm" }, - requestChecksumRequired: true - }) - ]; - }).s("AmazonS3", "CreateBucketMetadataTableConfiguration", {}).n("S3Client", "CreateBucketMetadataTableConfigurationCommand").sc(schemas_0.CreateBucketMetadataTableConfiguration$).build() { - }; - var CreateMultipartUploadCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - Bucket: { type: "contextParams", name: "Bucket" }, - Key: { type: "contextParams", name: "Key" } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareSdkS3.getThrow200ExceptionsPlugin(config3), - middlewareSsec.getSsecPlugin(config3) - ]; - }).s("AmazonS3", "CreateMultipartUpload", {}).n("S3Client", "CreateMultipartUploadCommand").sc(schemas_0.CreateMultipartUpload$).build() { - }; - var DeleteBucketAnalyticsConfigurationCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions())]; - }).s("AmazonS3", "DeleteBucketAnalyticsConfiguration", {}).n("S3Client", "DeleteBucketAnalyticsConfigurationCommand").sc(schemas_0.DeleteBucketAnalyticsConfiguration$).build() { - }; - var DeleteBucketCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions())]; - }).s("AmazonS3", "DeleteBucket", {}).n("S3Client", "DeleteBucketCommand").sc(schemas_0.DeleteBucket$).build() { - }; - var DeleteBucketCorsCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions())]; - }).s("AmazonS3", "DeleteBucketCors", {}).n("S3Client", "DeleteBucketCorsCommand").sc(schemas_0.DeleteBucketCors$).build() { - }; - var DeleteBucketEncryptionCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions())]; - }).s("AmazonS3", "DeleteBucketEncryption", {}).n("S3Client", "DeleteBucketEncryptionCommand").sc(schemas_0.DeleteBucketEncryption$).build() { - }; - var DeleteBucketIntelligentTieringConfigurationCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions())]; - }).s("AmazonS3", "DeleteBucketIntelligentTieringConfiguration", {}).n("S3Client", "DeleteBucketIntelligentTieringConfigurationCommand").sc(schemas_0.DeleteBucketIntelligentTieringConfiguration$).build() { - }; - var DeleteBucketInventoryConfigurationCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions())]; - }).s("AmazonS3", "DeleteBucketInventoryConfiguration", {}).n("S3Client", "DeleteBucketInventoryConfigurationCommand").sc(schemas_0.DeleteBucketInventoryConfiguration$).build() { - }; - var DeleteBucketLifecycleCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions())]; - }).s("AmazonS3", "DeleteBucketLifecycle", {}).n("S3Client", "DeleteBucketLifecycleCommand").sc(schemas_0.DeleteBucketLifecycle$).build() { - }; - var DeleteBucketMetadataConfigurationCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions())]; - }).s("AmazonS3", "DeleteBucketMetadataConfiguration", {}).n("S3Client", "DeleteBucketMetadataConfigurationCommand").sc(schemas_0.DeleteBucketMetadataConfiguration$).build() { - }; - var DeleteBucketMetadataTableConfigurationCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions())]; - }).s("AmazonS3", "DeleteBucketMetadataTableConfiguration", {}).n("S3Client", "DeleteBucketMetadataTableConfigurationCommand").sc(schemas_0.DeleteBucketMetadataTableConfiguration$).build() { - }; - var DeleteBucketMetricsConfigurationCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions())]; - }).s("AmazonS3", "DeleteBucketMetricsConfiguration", {}).n("S3Client", "DeleteBucketMetricsConfigurationCommand").sc(schemas_0.DeleteBucketMetricsConfiguration$).build() { - }; - var DeleteBucketOwnershipControlsCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions())]; - }).s("AmazonS3", "DeleteBucketOwnershipControls", {}).n("S3Client", "DeleteBucketOwnershipControlsCommand").sc(schemas_0.DeleteBucketOwnershipControls$).build() { - }; - var DeleteBucketPolicyCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions())]; - }).s("AmazonS3", "DeleteBucketPolicy", {}).n("S3Client", "DeleteBucketPolicyCommand").sc(schemas_0.DeleteBucketPolicy$).build() { - }; - var DeleteBucketReplicationCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions())]; - }).s("AmazonS3", "DeleteBucketReplication", {}).n("S3Client", "DeleteBucketReplicationCommand").sc(schemas_0.DeleteBucketReplication$).build() { - }; - var DeleteBucketTaggingCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions())]; - }).s("AmazonS3", "DeleteBucketTagging", {}).n("S3Client", "DeleteBucketTaggingCommand").sc(schemas_0.DeleteBucketTagging$).build() { - }; - var DeleteBucketWebsiteCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions())]; - }).s("AmazonS3", "DeleteBucketWebsite", {}).n("S3Client", "DeleteBucketWebsiteCommand").sc(schemas_0.DeleteBucketWebsite$).build() { - }; - var DeleteObjectCommand2 = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - Bucket: { type: "contextParams", name: "Bucket" }, - Key: { type: "contextParams", name: "Key" } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareSdkS3.getThrow200ExceptionsPlugin(config3) - ]; - }).s("AmazonS3", "DeleteObject", {}).n("S3Client", "DeleteObjectCommand").sc(schemas_0.DeleteObject$).build() { - }; - var DeleteObjectsCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareFlexibleChecksums.getFlexibleChecksumsPlugin(config3, { - requestAlgorithmMember: { "httpHeader": "x-amz-sdk-checksum-algorithm", "name": "ChecksumAlgorithm" }, - requestChecksumRequired: true - }), - middlewareSdkS3.getThrow200ExceptionsPlugin(config3) - ]; - }).s("AmazonS3", "DeleteObjects", {}).n("S3Client", "DeleteObjectsCommand").sc(schemas_0.DeleteObjects$).build() { - }; - var DeleteObjectTaggingCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareSdkS3.getThrow200ExceptionsPlugin(config3) - ]; - }).s("AmazonS3", "DeleteObjectTagging", {}).n("S3Client", "DeleteObjectTaggingCommand").sc(schemas_0.DeleteObjectTagging$).build() { - }; - var DeletePublicAccessBlockCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions())]; - }).s("AmazonS3", "DeletePublicAccessBlock", {}).n("S3Client", "DeletePublicAccessBlockCommand").sc(schemas_0.DeletePublicAccessBlock$).build() { - }; - var GetBucketAbacCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareSdkS3.getThrow200ExceptionsPlugin(config3) - ]; - }).s("AmazonS3", "GetBucketAbac", {}).n("S3Client", "GetBucketAbacCommand").sc(schemas_0.GetBucketAbac$).build() { - }; - var GetBucketAccelerateConfigurationCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareSdkS3.getThrow200ExceptionsPlugin(config3) - ]; - }).s("AmazonS3", "GetBucketAccelerateConfiguration", {}).n("S3Client", "GetBucketAccelerateConfigurationCommand").sc(schemas_0.GetBucketAccelerateConfiguration$).build() { - }; - var GetBucketAclCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareSdkS3.getThrow200ExceptionsPlugin(config3) - ]; - }).s("AmazonS3", "GetBucketAcl", {}).n("S3Client", "GetBucketAclCommand").sc(schemas_0.GetBucketAcl$).build() { - }; - var GetBucketAnalyticsConfigurationCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareSdkS3.getThrow200ExceptionsPlugin(config3) - ]; - }).s("AmazonS3", "GetBucketAnalyticsConfiguration", {}).n("S3Client", "GetBucketAnalyticsConfigurationCommand").sc(schemas_0.GetBucketAnalyticsConfiguration$).build() { - }; - var GetBucketCorsCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareSdkS3.getThrow200ExceptionsPlugin(config3) - ]; - }).s("AmazonS3", "GetBucketCors", {}).n("S3Client", "GetBucketCorsCommand").sc(schemas_0.GetBucketCors$).build() { - }; - var GetBucketEncryptionCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareSdkS3.getThrow200ExceptionsPlugin(config3) - ]; - }).s("AmazonS3", "GetBucketEncryption", {}).n("S3Client", "GetBucketEncryptionCommand").sc(schemas_0.GetBucketEncryption$).build() { - }; - var GetBucketIntelligentTieringConfigurationCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareSdkS3.getThrow200ExceptionsPlugin(config3) - ]; - }).s("AmazonS3", "GetBucketIntelligentTieringConfiguration", {}).n("S3Client", "GetBucketIntelligentTieringConfigurationCommand").sc(schemas_0.GetBucketIntelligentTieringConfiguration$).build() { - }; - var GetBucketInventoryConfigurationCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareSdkS3.getThrow200ExceptionsPlugin(config3) - ]; - }).s("AmazonS3", "GetBucketInventoryConfiguration", {}).n("S3Client", "GetBucketInventoryConfigurationCommand").sc(schemas_0.GetBucketInventoryConfiguration$).build() { - }; - var GetBucketLifecycleConfigurationCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareSdkS3.getThrow200ExceptionsPlugin(config3) - ]; - }).s("AmazonS3", "GetBucketLifecycleConfiguration", {}).n("S3Client", "GetBucketLifecycleConfigurationCommand").sc(schemas_0.GetBucketLifecycleConfiguration$).build() { - }; - var GetBucketLocationCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareSdkS3.getThrow200ExceptionsPlugin(config3) - ]; - }).s("AmazonS3", "GetBucketLocation", {}).n("S3Client", "GetBucketLocationCommand").sc(schemas_0.GetBucketLocation$).build() { - }; - var GetBucketLoggingCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareSdkS3.getThrow200ExceptionsPlugin(config3) - ]; - }).s("AmazonS3", "GetBucketLogging", {}).n("S3Client", "GetBucketLoggingCommand").sc(schemas_0.GetBucketLogging$).build() { - }; - var GetBucketMetadataConfigurationCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareSdkS3.getThrow200ExceptionsPlugin(config3) - ]; - }).s("AmazonS3", "GetBucketMetadataConfiguration", {}).n("S3Client", "GetBucketMetadataConfigurationCommand").sc(schemas_0.GetBucketMetadataConfiguration$).build() { - }; - var GetBucketMetadataTableConfigurationCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareSdkS3.getThrow200ExceptionsPlugin(config3) - ]; - }).s("AmazonS3", "GetBucketMetadataTableConfiguration", {}).n("S3Client", "GetBucketMetadataTableConfigurationCommand").sc(schemas_0.GetBucketMetadataTableConfiguration$).build() { - }; - var GetBucketMetricsConfigurationCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareSdkS3.getThrow200ExceptionsPlugin(config3) - ]; - }).s("AmazonS3", "GetBucketMetricsConfiguration", {}).n("S3Client", "GetBucketMetricsConfigurationCommand").sc(schemas_0.GetBucketMetricsConfiguration$).build() { - }; - var GetBucketNotificationConfigurationCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareSdkS3.getThrow200ExceptionsPlugin(config3) - ]; - }).s("AmazonS3", "GetBucketNotificationConfiguration", {}).n("S3Client", "GetBucketNotificationConfigurationCommand").sc(schemas_0.GetBucketNotificationConfiguration$).build() { - }; - var GetBucketOwnershipControlsCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareSdkS3.getThrow200ExceptionsPlugin(config3) - ]; - }).s("AmazonS3", "GetBucketOwnershipControls", {}).n("S3Client", "GetBucketOwnershipControlsCommand").sc(schemas_0.GetBucketOwnershipControls$).build() { - }; - var GetBucketPolicyCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareSdkS3.getThrow200ExceptionsPlugin(config3) - ]; - }).s("AmazonS3", "GetBucketPolicy", {}).n("S3Client", "GetBucketPolicyCommand").sc(schemas_0.GetBucketPolicy$).build() { - }; - var GetBucketPolicyStatusCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareSdkS3.getThrow200ExceptionsPlugin(config3) - ]; - }).s("AmazonS3", "GetBucketPolicyStatus", {}).n("S3Client", "GetBucketPolicyStatusCommand").sc(schemas_0.GetBucketPolicyStatus$).build() { - }; - var GetBucketReplicationCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareSdkS3.getThrow200ExceptionsPlugin(config3) - ]; - }).s("AmazonS3", "GetBucketReplication", {}).n("S3Client", "GetBucketReplicationCommand").sc(schemas_0.GetBucketReplication$).build() { - }; - var GetBucketRequestPaymentCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareSdkS3.getThrow200ExceptionsPlugin(config3) - ]; - }).s("AmazonS3", "GetBucketRequestPayment", {}).n("S3Client", "GetBucketRequestPaymentCommand").sc(schemas_0.GetBucketRequestPayment$).build() { - }; - var GetBucketTaggingCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareSdkS3.getThrow200ExceptionsPlugin(config3) - ]; - }).s("AmazonS3", "GetBucketTagging", {}).n("S3Client", "GetBucketTaggingCommand").sc(schemas_0.GetBucketTagging$).build() { - }; - var GetBucketVersioningCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareSdkS3.getThrow200ExceptionsPlugin(config3) - ]; - }).s("AmazonS3", "GetBucketVersioning", {}).n("S3Client", "GetBucketVersioningCommand").sc(schemas_0.GetBucketVersioning$).build() { - }; - var GetBucketWebsiteCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareSdkS3.getThrow200ExceptionsPlugin(config3) - ]; - }).s("AmazonS3", "GetBucketWebsite", {}).n("S3Client", "GetBucketWebsiteCommand").sc(schemas_0.GetBucketWebsite$).build() { - }; - var GetObjectAclCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - Bucket: { type: "contextParams", name: "Bucket" }, - Key: { type: "contextParams", name: "Key" } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareSdkS3.getThrow200ExceptionsPlugin(config3) - ]; - }).s("AmazonS3", "GetObjectAcl", {}).n("S3Client", "GetObjectAclCommand").sc(schemas_0.GetObjectAcl$).build() { - }; - var GetObjectAttributesCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareSdkS3.getThrow200ExceptionsPlugin(config3), - middlewareSsec.getSsecPlugin(config3) - ]; - }).s("AmazonS3", "GetObjectAttributes", {}).n("S3Client", "GetObjectAttributesCommand").sc(schemas_0.GetObjectAttributes$).build() { - }; - var GetObjectCommand2 = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - Bucket: { type: "contextParams", name: "Bucket" }, - Key: { type: "contextParams", name: "Key" } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareFlexibleChecksums.getFlexibleChecksumsPlugin(config3, { - requestChecksumRequired: false, - requestValidationModeMember: "ChecksumMode", - "responseAlgorithms": ["CRC64NVME", "CRC32", "CRC32C", "SHA256", "SHA1"] - }), - middlewareSsec.getSsecPlugin(config3), - middlewareSdkS3.getS3ExpiresMiddlewarePlugin(config3) - ]; - }).s("AmazonS3", "GetObject", {}).n("S3Client", "GetObjectCommand").sc(schemas_0.GetObject$).build() { - }; - var GetObjectLegalHoldCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareSdkS3.getThrow200ExceptionsPlugin(config3) - ]; - }).s("AmazonS3", "GetObjectLegalHold", {}).n("S3Client", "GetObjectLegalHoldCommand").sc(schemas_0.GetObjectLegalHold$).build() { - }; - var GetObjectLockConfigurationCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareSdkS3.getThrow200ExceptionsPlugin(config3) - ]; - }).s("AmazonS3", "GetObjectLockConfiguration", {}).n("S3Client", "GetObjectLockConfigurationCommand").sc(schemas_0.GetObjectLockConfiguration$).build() { - }; - var GetObjectRetentionCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareSdkS3.getThrow200ExceptionsPlugin(config3) - ]; - }).s("AmazonS3", "GetObjectRetention", {}).n("S3Client", "GetObjectRetentionCommand").sc(schemas_0.GetObjectRetention$).build() { - }; - var GetObjectTaggingCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareSdkS3.getThrow200ExceptionsPlugin(config3) - ]; - }).s("AmazonS3", "GetObjectTagging", {}).n("S3Client", "GetObjectTaggingCommand").sc(schemas_0.GetObjectTagging$).build() { - }; - var GetObjectTorrentCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions())]; - }).s("AmazonS3", "GetObjectTorrent", {}).n("S3Client", "GetObjectTorrentCommand").sc(schemas_0.GetObjectTorrent$).build() { - }; - var GetPublicAccessBlockCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareSdkS3.getThrow200ExceptionsPlugin(config3) - ]; - }).s("AmazonS3", "GetPublicAccessBlock", {}).n("S3Client", "GetPublicAccessBlockCommand").sc(schemas_0.GetPublicAccessBlock$).build() { - }; - var HeadBucketCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareSdkS3.getThrow200ExceptionsPlugin(config3) - ]; - }).s("AmazonS3", "HeadBucket", {}).n("S3Client", "HeadBucketCommand").sc(schemas_0.HeadBucket$).build() { - }; - var HeadObjectCommand2 = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - Bucket: { type: "contextParams", name: "Bucket" }, - Key: { type: "contextParams", name: "Key" } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareSdkS3.getThrow200ExceptionsPlugin(config3), - middlewareSsec.getSsecPlugin(config3), - middlewareSdkS3.getS3ExpiresMiddlewarePlugin(config3) - ]; - }).s("AmazonS3", "HeadObject", {}).n("S3Client", "HeadObjectCommand").sc(schemas_0.HeadObject$).build() { - }; - var ListBucketAnalyticsConfigurationsCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareSdkS3.getThrow200ExceptionsPlugin(config3) - ]; - }).s("AmazonS3", "ListBucketAnalyticsConfigurations", {}).n("S3Client", "ListBucketAnalyticsConfigurationsCommand").sc(schemas_0.ListBucketAnalyticsConfigurations$).build() { - }; - var ListBucketIntelligentTieringConfigurationsCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareSdkS3.getThrow200ExceptionsPlugin(config3) - ]; - }).s("AmazonS3", "ListBucketIntelligentTieringConfigurations", {}).n("S3Client", "ListBucketIntelligentTieringConfigurationsCommand").sc(schemas_0.ListBucketIntelligentTieringConfigurations$).build() { - }; - var ListBucketInventoryConfigurationsCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareSdkS3.getThrow200ExceptionsPlugin(config3) - ]; - }).s("AmazonS3", "ListBucketInventoryConfigurations", {}).n("S3Client", "ListBucketInventoryConfigurationsCommand").sc(schemas_0.ListBucketInventoryConfigurations$).build() { - }; - var ListBucketMetricsConfigurationsCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareSdkS3.getThrow200ExceptionsPlugin(config3) - ]; - }).s("AmazonS3", "ListBucketMetricsConfigurations", {}).n("S3Client", "ListBucketMetricsConfigurationsCommand").sc(schemas_0.ListBucketMetricsConfigurations$).build() { - }; - var ListBucketsCommand = class extends smithyClient.Command.classBuilder().ep(commonParams5).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareSdkS3.getThrow200ExceptionsPlugin(config3) - ]; - }).s("AmazonS3", "ListBuckets", {}).n("S3Client", "ListBucketsCommand").sc(schemas_0.ListBuckets$).build() { - }; - var ListDirectoryBucketsCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareSdkS3.getThrow200ExceptionsPlugin(config3) - ]; - }).s("AmazonS3", "ListDirectoryBuckets", {}).n("S3Client", "ListDirectoryBucketsCommand").sc(schemas_0.ListDirectoryBuckets$).build() { - }; - var ListMultipartUploadsCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - Bucket: { type: "contextParams", name: "Bucket" }, - Prefix: { type: "contextParams", name: "Prefix" } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareSdkS3.getThrow200ExceptionsPlugin(config3) - ]; - }).s("AmazonS3", "ListMultipartUploads", {}).n("S3Client", "ListMultipartUploadsCommand").sc(schemas_0.ListMultipartUploads$).build() { - }; - var ListObjectsCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - Bucket: { type: "contextParams", name: "Bucket" }, - Prefix: { type: "contextParams", name: "Prefix" } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareSdkS3.getThrow200ExceptionsPlugin(config3) - ]; - }).s("AmazonS3", "ListObjects", {}).n("S3Client", "ListObjectsCommand").sc(schemas_0.ListObjects$).build() { - }; - var ListObjectsV2Command = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - Bucket: { type: "contextParams", name: "Bucket" }, - Prefix: { type: "contextParams", name: "Prefix" } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareSdkS3.getThrow200ExceptionsPlugin(config3) - ]; - }).s("AmazonS3", "ListObjectsV2", {}).n("S3Client", "ListObjectsV2Command").sc(schemas_0.ListObjectsV2$).build() { - }; - var ListObjectVersionsCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - Bucket: { type: "contextParams", name: "Bucket" }, - Prefix: { type: "contextParams", name: "Prefix" } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareSdkS3.getThrow200ExceptionsPlugin(config3) - ]; - }).s("AmazonS3", "ListObjectVersions", {}).n("S3Client", "ListObjectVersionsCommand").sc(schemas_0.ListObjectVersions$).build() { - }; - var ListPartsCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - Bucket: { type: "contextParams", name: "Bucket" }, - Key: { type: "contextParams", name: "Key" } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareSdkS3.getThrow200ExceptionsPlugin(config3), - middlewareSsec.getSsecPlugin(config3) - ]; - }).s("AmazonS3", "ListParts", {}).n("S3Client", "ListPartsCommand").sc(schemas_0.ListParts$).build() { - }; - var PutBucketAbacCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareFlexibleChecksums.getFlexibleChecksumsPlugin(config3, { - requestAlgorithmMember: { "httpHeader": "x-amz-sdk-checksum-algorithm", "name": "ChecksumAlgorithm" }, - requestChecksumRequired: false - }) - ]; - }).s("AmazonS3", "PutBucketAbac", {}).n("S3Client", "PutBucketAbacCommand").sc(schemas_0.PutBucketAbac$).build() { - }; - var PutBucketAccelerateConfigurationCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareFlexibleChecksums.getFlexibleChecksumsPlugin(config3, { - requestAlgorithmMember: { "httpHeader": "x-amz-sdk-checksum-algorithm", "name": "ChecksumAlgorithm" }, - requestChecksumRequired: false - }) - ]; - }).s("AmazonS3", "PutBucketAccelerateConfiguration", {}).n("S3Client", "PutBucketAccelerateConfigurationCommand").sc(schemas_0.PutBucketAccelerateConfiguration$).build() { - }; - var PutBucketAclCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareFlexibleChecksums.getFlexibleChecksumsPlugin(config3, { - requestAlgorithmMember: { "httpHeader": "x-amz-sdk-checksum-algorithm", "name": "ChecksumAlgorithm" }, - requestChecksumRequired: true - }) - ]; - }).s("AmazonS3", "PutBucketAcl", {}).n("S3Client", "PutBucketAclCommand").sc(schemas_0.PutBucketAcl$).build() { - }; - var PutBucketAnalyticsConfigurationCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions())]; - }).s("AmazonS3", "PutBucketAnalyticsConfiguration", {}).n("S3Client", "PutBucketAnalyticsConfigurationCommand").sc(schemas_0.PutBucketAnalyticsConfiguration$).build() { - }; - var PutBucketCorsCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareFlexibleChecksums.getFlexibleChecksumsPlugin(config3, { - requestAlgorithmMember: { "httpHeader": "x-amz-sdk-checksum-algorithm", "name": "ChecksumAlgorithm" }, - requestChecksumRequired: true - }) - ]; - }).s("AmazonS3", "PutBucketCors", {}).n("S3Client", "PutBucketCorsCommand").sc(schemas_0.PutBucketCors$).build() { - }; - var PutBucketEncryptionCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareFlexibleChecksums.getFlexibleChecksumsPlugin(config3, { - requestAlgorithmMember: { "httpHeader": "x-amz-sdk-checksum-algorithm", "name": "ChecksumAlgorithm" }, - requestChecksumRequired: true - }) - ]; - }).s("AmazonS3", "PutBucketEncryption", {}).n("S3Client", "PutBucketEncryptionCommand").sc(schemas_0.PutBucketEncryption$).build() { - }; - var PutBucketIntelligentTieringConfigurationCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions())]; - }).s("AmazonS3", "PutBucketIntelligentTieringConfiguration", {}).n("S3Client", "PutBucketIntelligentTieringConfigurationCommand").sc(schemas_0.PutBucketIntelligentTieringConfiguration$).build() { - }; - var PutBucketInventoryConfigurationCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions())]; - }).s("AmazonS3", "PutBucketInventoryConfiguration", {}).n("S3Client", "PutBucketInventoryConfigurationCommand").sc(schemas_0.PutBucketInventoryConfiguration$).build() { - }; - var PutBucketLifecycleConfigurationCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareFlexibleChecksums.getFlexibleChecksumsPlugin(config3, { - requestAlgorithmMember: { "httpHeader": "x-amz-sdk-checksum-algorithm", "name": "ChecksumAlgorithm" }, - requestChecksumRequired: true - }), - middlewareSdkS3.getThrow200ExceptionsPlugin(config3) - ]; - }).s("AmazonS3", "PutBucketLifecycleConfiguration", {}).n("S3Client", "PutBucketLifecycleConfigurationCommand").sc(schemas_0.PutBucketLifecycleConfiguration$).build() { - }; - var PutBucketLoggingCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareFlexibleChecksums.getFlexibleChecksumsPlugin(config3, { - requestAlgorithmMember: { "httpHeader": "x-amz-sdk-checksum-algorithm", "name": "ChecksumAlgorithm" }, - requestChecksumRequired: true - }) - ]; - }).s("AmazonS3", "PutBucketLogging", {}).n("S3Client", "PutBucketLoggingCommand").sc(schemas_0.PutBucketLogging$).build() { - }; - var PutBucketMetricsConfigurationCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions())]; - }).s("AmazonS3", "PutBucketMetricsConfiguration", {}).n("S3Client", "PutBucketMetricsConfigurationCommand").sc(schemas_0.PutBucketMetricsConfiguration$).build() { - }; - var PutBucketNotificationConfigurationCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions())]; - }).s("AmazonS3", "PutBucketNotificationConfiguration", {}).n("S3Client", "PutBucketNotificationConfigurationCommand").sc(schemas_0.PutBucketNotificationConfiguration$).build() { - }; - var PutBucketOwnershipControlsCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareFlexibleChecksums.getFlexibleChecksumsPlugin(config3, { - requestAlgorithmMember: { "httpHeader": "x-amz-sdk-checksum-algorithm", "name": "ChecksumAlgorithm" }, - requestChecksumRequired: true - }) - ]; - }).s("AmazonS3", "PutBucketOwnershipControls", {}).n("S3Client", "PutBucketOwnershipControlsCommand").sc(schemas_0.PutBucketOwnershipControls$).build() { - }; - var PutBucketPolicyCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareFlexibleChecksums.getFlexibleChecksumsPlugin(config3, { - requestAlgorithmMember: { "httpHeader": "x-amz-sdk-checksum-algorithm", "name": "ChecksumAlgorithm" }, - requestChecksumRequired: true - }) - ]; - }).s("AmazonS3", "PutBucketPolicy", {}).n("S3Client", "PutBucketPolicyCommand").sc(schemas_0.PutBucketPolicy$).build() { - }; - var PutBucketReplicationCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareFlexibleChecksums.getFlexibleChecksumsPlugin(config3, { - requestAlgorithmMember: { "httpHeader": "x-amz-sdk-checksum-algorithm", "name": "ChecksumAlgorithm" }, - requestChecksumRequired: true - }) - ]; - }).s("AmazonS3", "PutBucketReplication", {}).n("S3Client", "PutBucketReplicationCommand").sc(schemas_0.PutBucketReplication$).build() { - }; - var PutBucketRequestPaymentCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareFlexibleChecksums.getFlexibleChecksumsPlugin(config3, { - requestAlgorithmMember: { "httpHeader": "x-amz-sdk-checksum-algorithm", "name": "ChecksumAlgorithm" }, - requestChecksumRequired: true - }) - ]; - }).s("AmazonS3", "PutBucketRequestPayment", {}).n("S3Client", "PutBucketRequestPaymentCommand").sc(schemas_0.PutBucketRequestPayment$).build() { - }; - var PutBucketTaggingCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareFlexibleChecksums.getFlexibleChecksumsPlugin(config3, { - requestAlgorithmMember: { "httpHeader": "x-amz-sdk-checksum-algorithm", "name": "ChecksumAlgorithm" }, - requestChecksumRequired: true - }) - ]; - }).s("AmazonS3", "PutBucketTagging", {}).n("S3Client", "PutBucketTaggingCommand").sc(schemas_0.PutBucketTagging$).build() { - }; - var PutBucketVersioningCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareFlexibleChecksums.getFlexibleChecksumsPlugin(config3, { - requestAlgorithmMember: { "httpHeader": "x-amz-sdk-checksum-algorithm", "name": "ChecksumAlgorithm" }, - requestChecksumRequired: true - }) - ]; - }).s("AmazonS3", "PutBucketVersioning", {}).n("S3Client", "PutBucketVersioningCommand").sc(schemas_0.PutBucketVersioning$).build() { - }; - var PutBucketWebsiteCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareFlexibleChecksums.getFlexibleChecksumsPlugin(config3, { - requestAlgorithmMember: { "httpHeader": "x-amz-sdk-checksum-algorithm", "name": "ChecksumAlgorithm" }, - requestChecksumRequired: true - }) - ]; - }).s("AmazonS3", "PutBucketWebsite", {}).n("S3Client", "PutBucketWebsiteCommand").sc(schemas_0.PutBucketWebsite$).build() { - }; - var PutObjectAclCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - Bucket: { type: "contextParams", name: "Bucket" }, - Key: { type: "contextParams", name: "Key" } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareFlexibleChecksums.getFlexibleChecksumsPlugin(config3, { - requestAlgorithmMember: { "httpHeader": "x-amz-sdk-checksum-algorithm", "name": "ChecksumAlgorithm" }, - requestChecksumRequired: true - }), - middlewareSdkS3.getThrow200ExceptionsPlugin(config3) - ]; - }).s("AmazonS3", "PutObjectAcl", {}).n("S3Client", "PutObjectAclCommand").sc(schemas_0.PutObjectAcl$).build() { - }; - var PutObjectCommand2 = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - Bucket: { type: "contextParams", name: "Bucket" }, - Key: { type: "contextParams", name: "Key" } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareFlexibleChecksums.getFlexibleChecksumsPlugin(config3, { - requestAlgorithmMember: { "httpHeader": "x-amz-sdk-checksum-algorithm", "name": "ChecksumAlgorithm" }, - requestChecksumRequired: false - }), - middlewareSdkS3.getCheckContentLengthHeaderPlugin(config3), - middlewareSdkS3.getThrow200ExceptionsPlugin(config3), - middlewareSsec.getSsecPlugin(config3) - ]; - }).s("AmazonS3", "PutObject", {}).n("S3Client", "PutObjectCommand").sc(schemas_0.PutObject$).build() { - }; - var PutObjectLegalHoldCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareFlexibleChecksums.getFlexibleChecksumsPlugin(config3, { - requestAlgorithmMember: { "httpHeader": "x-amz-sdk-checksum-algorithm", "name": "ChecksumAlgorithm" }, - requestChecksumRequired: true - }), - middlewareSdkS3.getThrow200ExceptionsPlugin(config3) - ]; - }).s("AmazonS3", "PutObjectLegalHold", {}).n("S3Client", "PutObjectLegalHoldCommand").sc(schemas_0.PutObjectLegalHold$).build() { - }; - var PutObjectLockConfigurationCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareFlexibleChecksums.getFlexibleChecksumsPlugin(config3, { - requestAlgorithmMember: { "httpHeader": "x-amz-sdk-checksum-algorithm", "name": "ChecksumAlgorithm" }, - requestChecksumRequired: true - }), - middlewareSdkS3.getThrow200ExceptionsPlugin(config3) - ]; - }).s("AmazonS3", "PutObjectLockConfiguration", {}).n("S3Client", "PutObjectLockConfigurationCommand").sc(schemas_0.PutObjectLockConfiguration$).build() { - }; - var PutObjectRetentionCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareFlexibleChecksums.getFlexibleChecksumsPlugin(config3, { - requestAlgorithmMember: { "httpHeader": "x-amz-sdk-checksum-algorithm", "name": "ChecksumAlgorithm" }, - requestChecksumRequired: true - }), - middlewareSdkS3.getThrow200ExceptionsPlugin(config3) - ]; - }).s("AmazonS3", "PutObjectRetention", {}).n("S3Client", "PutObjectRetentionCommand").sc(schemas_0.PutObjectRetention$).build() { - }; - var PutObjectTaggingCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareFlexibleChecksums.getFlexibleChecksumsPlugin(config3, { - requestAlgorithmMember: { "httpHeader": "x-amz-sdk-checksum-algorithm", "name": "ChecksumAlgorithm" }, - requestChecksumRequired: true - }), - middlewareSdkS3.getThrow200ExceptionsPlugin(config3) - ]; - }).s("AmazonS3", "PutObjectTagging", {}).n("S3Client", "PutObjectTaggingCommand").sc(schemas_0.PutObjectTagging$).build() { - }; - var PutPublicAccessBlockCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareFlexibleChecksums.getFlexibleChecksumsPlugin(config3, { - requestAlgorithmMember: { "httpHeader": "x-amz-sdk-checksum-algorithm", "name": "ChecksumAlgorithm" }, - requestChecksumRequired: true - }) - ]; - }).s("AmazonS3", "PutPublicAccessBlock", {}).n("S3Client", "PutPublicAccessBlockCommand").sc(schemas_0.PutPublicAccessBlock$).build() { - }; - var RenameObjectCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - Bucket: { type: "contextParams", name: "Bucket" }, - Key: { type: "contextParams", name: "Key" } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareSdkS3.getThrow200ExceptionsPlugin(config3) - ]; - }).s("AmazonS3", "RenameObject", {}).n("S3Client", "RenameObjectCommand").sc(schemas_0.RenameObject$).build() { - }; - var RestoreObjectCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareFlexibleChecksums.getFlexibleChecksumsPlugin(config3, { - requestAlgorithmMember: { "httpHeader": "x-amz-sdk-checksum-algorithm", "name": "ChecksumAlgorithm" }, - requestChecksumRequired: false - }), - middlewareSdkS3.getThrow200ExceptionsPlugin(config3) - ]; - }).s("AmazonS3", "RestoreObject", {}).n("S3Client", "RestoreObjectCommand").sc(schemas_0.RestoreObject$).build() { - }; - var SelectObjectContentCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareSdkS3.getThrow200ExceptionsPlugin(config3), - middlewareSsec.getSsecPlugin(config3) - ]; - }).s("AmazonS3", "SelectObjectContent", { - eventStream: { - output: true - } - }).n("S3Client", "SelectObjectContentCommand").sc(schemas_0.SelectObjectContent$).build() { - }; - var UpdateBucketMetadataInventoryTableConfigurationCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareFlexibleChecksums.getFlexibleChecksumsPlugin(config3, { - requestAlgorithmMember: { "httpHeader": "x-amz-sdk-checksum-algorithm", "name": "ChecksumAlgorithm" }, - requestChecksumRequired: true - }) - ]; - }).s("AmazonS3", "UpdateBucketMetadataInventoryTableConfiguration", {}).n("S3Client", "UpdateBucketMetadataInventoryTableConfigurationCommand").sc(schemas_0.UpdateBucketMetadataInventoryTableConfiguration$).build() { - }; - var UpdateBucketMetadataJournalTableConfigurationCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - UseS3ExpressControlEndpoint: { type: "staticContextParams", value: true }, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareFlexibleChecksums.getFlexibleChecksumsPlugin(config3, { - requestAlgorithmMember: { "httpHeader": "x-amz-sdk-checksum-algorithm", "name": "ChecksumAlgorithm" }, - requestChecksumRequired: true - }) - ]; - }).s("AmazonS3", "UpdateBucketMetadataJournalTableConfiguration", {}).n("S3Client", "UpdateBucketMetadataJournalTableConfigurationCommand").sc(schemas_0.UpdateBucketMetadataJournalTableConfiguration$).build() { - }; - var UpdateObjectEncryptionCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareFlexibleChecksums.getFlexibleChecksumsPlugin(config3, { - requestAlgorithmMember: { "httpHeader": "x-amz-sdk-checksum-algorithm", "name": "ChecksumAlgorithm" }, - requestChecksumRequired: true - }), - middlewareSdkS3.getThrow200ExceptionsPlugin(config3) - ]; - }).s("AmazonS3", "UpdateObjectEncryption", {}).n("S3Client", "UpdateObjectEncryptionCommand").sc(schemas_0.UpdateObjectEncryption$).build() { - }; - var UploadPartCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - Bucket: { type: "contextParams", name: "Bucket" }, - Key: { type: "contextParams", name: "Key" } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareFlexibleChecksums.getFlexibleChecksumsPlugin(config3, { - requestAlgorithmMember: { "httpHeader": "x-amz-sdk-checksum-algorithm", "name": "ChecksumAlgorithm" }, - requestChecksumRequired: false - }), - middlewareSdkS3.getThrow200ExceptionsPlugin(config3), - middlewareSsec.getSsecPlugin(config3) - ]; - }).s("AmazonS3", "UploadPart", {}).n("S3Client", "UploadPartCommand").sc(schemas_0.UploadPart$).build() { - }; - var UploadPartCopyCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - DisableS3ExpressSessionAuth: { type: "staticContextParams", value: true }, - Bucket: { type: "contextParams", name: "Bucket" } - }).m(function(Command2, cs, config3, o5) { - return [ - middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions()), - middlewareSdkS3.getThrow200ExceptionsPlugin(config3), - middlewareSsec.getSsecPlugin(config3) - ]; - }).s("AmazonS3", "UploadPartCopy", {}).n("S3Client", "UploadPartCopyCommand").sc(schemas_0.UploadPartCopy$).build() { - }; - var WriteGetObjectResponseCommand = class extends smithyClient.Command.classBuilder().ep({ - ...commonParams5, - UseObjectLambdaEndpoint: { type: "staticContextParams", value: true } - }).m(function(Command2, cs, config3, o5) { - return [middlewareEndpoint.getEndpointPlugin(config3, Command2.getEndpointParameterInstructions())]; - }).s("AmazonS3", "WriteGetObjectResponse", {}).n("S3Client", "WriteGetObjectResponseCommand").sc(schemas_0.WriteGetObjectResponse$).build() { - }; - var paginateListBuckets = core.createPaginator(S3Client2, ListBucketsCommand, "ContinuationToken", "ContinuationToken", "MaxBuckets"); - var paginateListDirectoryBuckets = core.createPaginator(S3Client2, ListDirectoryBucketsCommand, "ContinuationToken", "ContinuationToken", "MaxDirectoryBuckets"); - var paginateListObjectsV2 = core.createPaginator(S3Client2, ListObjectsV2Command, "ContinuationToken", "NextContinuationToken", "MaxKeys"); - var paginateListParts = core.createPaginator(S3Client2, ListPartsCommand, "PartNumberMarker", "NextPartNumberMarker", "MaxParts"); - var checkState$3 = async (client2, input) => { - let reason; - try { - let result = await client2.send(new HeadBucketCommand(input)); - reason = result; - return { state: utilWaiter.WaiterState.SUCCESS, reason }; - } catch (exception) { - reason = exception; - if (exception.name && exception.name == "NotFound") { - return { state: utilWaiter.WaiterState.RETRY, reason }; - } - } - return { state: utilWaiter.WaiterState.RETRY, reason }; - }; - var waitForBucketExists = async (params, input) => { - const serviceDefaults = { minDelay: 5, maxDelay: 120 }; - return utilWaiter.createWaiter({ ...serviceDefaults, ...params }, input, checkState$3); - }; - var waitUntilBucketExists = async (params, input) => { - const serviceDefaults = { minDelay: 5, maxDelay: 120 }; - const result = await utilWaiter.createWaiter({ ...serviceDefaults, ...params }, input, checkState$3); - return utilWaiter.checkExceptions(result); - }; - var checkState$2 = async (client2, input) => { - let reason; - try { - let result = await client2.send(new HeadBucketCommand(input)); - reason = result; - } catch (exception) { - reason = exception; - if (exception.name && exception.name == "NotFound") { - return { state: utilWaiter.WaiterState.SUCCESS, reason }; - } - } - return { state: utilWaiter.WaiterState.RETRY, reason }; - }; - var waitForBucketNotExists = async (params, input) => { - const serviceDefaults = { minDelay: 5, maxDelay: 120 }; - return utilWaiter.createWaiter({ ...serviceDefaults, ...params }, input, checkState$2); - }; - var waitUntilBucketNotExists = async (params, input) => { - const serviceDefaults = { minDelay: 5, maxDelay: 120 }; - const result = await utilWaiter.createWaiter({ ...serviceDefaults, ...params }, input, checkState$2); - return utilWaiter.checkExceptions(result); - }; - var checkState$1 = async (client2, input) => { - let reason; - try { - let result = await client2.send(new HeadObjectCommand2(input)); - reason = result; - return { state: utilWaiter.WaiterState.SUCCESS, reason }; - } catch (exception) { - reason = exception; - if (exception.name && exception.name == "NotFound") { - return { state: utilWaiter.WaiterState.RETRY, reason }; - } - } - return { state: utilWaiter.WaiterState.RETRY, reason }; - }; - var waitForObjectExists = async (params, input) => { - const serviceDefaults = { minDelay: 5, maxDelay: 120 }; - return utilWaiter.createWaiter({ ...serviceDefaults, ...params }, input, checkState$1); - }; - var waitUntilObjectExists = async (params, input) => { - const serviceDefaults = { minDelay: 5, maxDelay: 120 }; - const result = await utilWaiter.createWaiter({ ...serviceDefaults, ...params }, input, checkState$1); - return utilWaiter.checkExceptions(result); - }; - var checkState = async (client2, input) => { - let reason; - try { - let result = await client2.send(new HeadObjectCommand2(input)); - reason = result; - } catch (exception) { - reason = exception; - if (exception.name && exception.name == "NotFound") { - return { state: utilWaiter.WaiterState.SUCCESS, reason }; - } - } - return { state: utilWaiter.WaiterState.RETRY, reason }; - }; - var waitForObjectNotExists = async (params, input) => { - const serviceDefaults = { minDelay: 5, maxDelay: 120 }; - return utilWaiter.createWaiter({ ...serviceDefaults, ...params }, input, checkState); - }; - var waitUntilObjectNotExists = async (params, input) => { - const serviceDefaults = { minDelay: 5, maxDelay: 120 }; - const result = await utilWaiter.createWaiter({ ...serviceDefaults, ...params }, input, checkState); - return utilWaiter.checkExceptions(result); - }; - var commands5 = { - AbortMultipartUploadCommand, - CompleteMultipartUploadCommand, - CopyObjectCommand, - CreateBucketCommand, - CreateBucketMetadataConfigurationCommand, - CreateBucketMetadataTableConfigurationCommand, - CreateMultipartUploadCommand, - CreateSessionCommand, - DeleteBucketCommand, - DeleteBucketAnalyticsConfigurationCommand, - DeleteBucketCorsCommand, - DeleteBucketEncryptionCommand, - DeleteBucketIntelligentTieringConfigurationCommand, - DeleteBucketInventoryConfigurationCommand, - DeleteBucketLifecycleCommand, - DeleteBucketMetadataConfigurationCommand, - DeleteBucketMetadataTableConfigurationCommand, - DeleteBucketMetricsConfigurationCommand, - DeleteBucketOwnershipControlsCommand, - DeleteBucketPolicyCommand, - DeleteBucketReplicationCommand, - DeleteBucketTaggingCommand, - DeleteBucketWebsiteCommand, - DeleteObjectCommand: DeleteObjectCommand2, - DeleteObjectsCommand, - DeleteObjectTaggingCommand, - DeletePublicAccessBlockCommand, - GetBucketAbacCommand, - GetBucketAccelerateConfigurationCommand, - GetBucketAclCommand, - GetBucketAnalyticsConfigurationCommand, - GetBucketCorsCommand, - GetBucketEncryptionCommand, - GetBucketIntelligentTieringConfigurationCommand, - GetBucketInventoryConfigurationCommand, - GetBucketLifecycleConfigurationCommand, - GetBucketLocationCommand, - GetBucketLoggingCommand, - GetBucketMetadataConfigurationCommand, - GetBucketMetadataTableConfigurationCommand, - GetBucketMetricsConfigurationCommand, - GetBucketNotificationConfigurationCommand, - GetBucketOwnershipControlsCommand, - GetBucketPolicyCommand, - GetBucketPolicyStatusCommand, - GetBucketReplicationCommand, - GetBucketRequestPaymentCommand, - GetBucketTaggingCommand, - GetBucketVersioningCommand, - GetBucketWebsiteCommand, - GetObjectCommand: GetObjectCommand2, - GetObjectAclCommand, - GetObjectAttributesCommand, - GetObjectLegalHoldCommand, - GetObjectLockConfigurationCommand, - GetObjectRetentionCommand, - GetObjectTaggingCommand, - GetObjectTorrentCommand, - GetPublicAccessBlockCommand, - HeadBucketCommand, - HeadObjectCommand: HeadObjectCommand2, - ListBucketAnalyticsConfigurationsCommand, - ListBucketIntelligentTieringConfigurationsCommand, - ListBucketInventoryConfigurationsCommand, - ListBucketMetricsConfigurationsCommand, - ListBucketsCommand, - ListDirectoryBucketsCommand, - ListMultipartUploadsCommand, - ListObjectsCommand, - ListObjectsV2Command, - ListObjectVersionsCommand, - ListPartsCommand, - PutBucketAbacCommand, - PutBucketAccelerateConfigurationCommand, - PutBucketAclCommand, - PutBucketAnalyticsConfigurationCommand, - PutBucketCorsCommand, - PutBucketEncryptionCommand, - PutBucketIntelligentTieringConfigurationCommand, - PutBucketInventoryConfigurationCommand, - PutBucketLifecycleConfigurationCommand, - PutBucketLoggingCommand, - PutBucketMetricsConfigurationCommand, - PutBucketNotificationConfigurationCommand, - PutBucketOwnershipControlsCommand, - PutBucketPolicyCommand, - PutBucketReplicationCommand, - PutBucketRequestPaymentCommand, - PutBucketTaggingCommand, - PutBucketVersioningCommand, - PutBucketWebsiteCommand, - PutObjectCommand: PutObjectCommand2, - PutObjectAclCommand, - PutObjectLegalHoldCommand, - PutObjectLockConfigurationCommand, - PutObjectRetentionCommand, - PutObjectTaggingCommand, - PutPublicAccessBlockCommand, - RenameObjectCommand, - RestoreObjectCommand, - SelectObjectContentCommand, - UpdateBucketMetadataInventoryTableConfigurationCommand, - UpdateBucketMetadataJournalTableConfigurationCommand, - UpdateObjectEncryptionCommand, - UploadPartCommand, - UploadPartCopyCommand, - WriteGetObjectResponseCommand - }; - var paginators = { - paginateListBuckets, - paginateListDirectoryBuckets, - paginateListObjectsV2, - paginateListParts - }; - var waiters = { - waitUntilBucketExists, - waitUntilBucketNotExists, - waitUntilObjectExists, - waitUntilObjectNotExists - }; - var S3 = class extends S3Client2 { - }; - smithyClient.createAggregatedClient(commands5, S3, { paginators, waiters }); - var BucketAbacStatus = { - Disabled: "Disabled", - Enabled: "Enabled" - }; - var RequestCharged = { - requester: "requester" - }; - var RequestPayer = { - requester: "requester" - }; - var BucketAccelerateStatus = { - Enabled: "Enabled", - Suspended: "Suspended" - }; - var Type = { - AmazonCustomerByEmail: "AmazonCustomerByEmail", - CanonicalUser: "CanonicalUser", - Group: "Group" - }; - var Permission = { - FULL_CONTROL: "FULL_CONTROL", - READ: "READ", - READ_ACP: "READ_ACP", - WRITE: "WRITE", - WRITE_ACP: "WRITE_ACP" - }; - var OwnerOverride = { - Destination: "Destination" - }; - var ChecksumType = { - COMPOSITE: "COMPOSITE", - FULL_OBJECT: "FULL_OBJECT" - }; - var ServerSideEncryption = { - AES256: "AES256", - aws_fsx: "aws:fsx", - aws_kms: "aws:kms", - aws_kms_dsse: "aws:kms:dsse" - }; - var ObjectCannedACL = { - authenticated_read: "authenticated-read", - aws_exec_read: "aws-exec-read", - bucket_owner_full_control: "bucket-owner-full-control", - bucket_owner_read: "bucket-owner-read", - private: "private", - public_read: "public-read", - public_read_write: "public-read-write" - }; - var ChecksumAlgorithm = { - CRC32: "CRC32", - CRC32C: "CRC32C", - CRC64NVME: "CRC64NVME", - SHA1: "SHA1", - SHA256: "SHA256" - }; - var MetadataDirective = { - COPY: "COPY", - REPLACE: "REPLACE" - }; - var ObjectLockLegalHoldStatus = { - OFF: "OFF", - ON: "ON" - }; - var ObjectLockMode = { - COMPLIANCE: "COMPLIANCE", - GOVERNANCE: "GOVERNANCE" - }; - var StorageClass = { - DEEP_ARCHIVE: "DEEP_ARCHIVE", - EXPRESS_ONEZONE: "EXPRESS_ONEZONE", - FSX_ONTAP: "FSX_ONTAP", - FSX_OPENZFS: "FSX_OPENZFS", - GLACIER: "GLACIER", - GLACIER_IR: "GLACIER_IR", - INTELLIGENT_TIERING: "INTELLIGENT_TIERING", - ONEZONE_IA: "ONEZONE_IA", - OUTPOSTS: "OUTPOSTS", - REDUCED_REDUNDANCY: "REDUCED_REDUNDANCY", - SNOW: "SNOW", - STANDARD: "STANDARD", - STANDARD_IA: "STANDARD_IA" - }; - var TaggingDirective = { - COPY: "COPY", - REPLACE: "REPLACE" - }; - var BucketCannedACL = { - authenticated_read: "authenticated-read", - private: "private", - public_read: "public-read", - public_read_write: "public-read-write" - }; - var BucketNamespace = { - ACCOUNT_REGIONAL: "account-regional", - GLOBAL: "global" - }; - var DataRedundancy = { - SingleAvailabilityZone: "SingleAvailabilityZone", - SingleLocalZone: "SingleLocalZone" - }; - var BucketType = { - Directory: "Directory" - }; - var LocationType = { - AvailabilityZone: "AvailabilityZone", - LocalZone: "LocalZone" - }; - var BucketLocationConstraint = { - EU: "EU", - af_south_1: "af-south-1", - ap_east_1: "ap-east-1", - ap_east_2: "ap-east-2", - ap_northeast_1: "ap-northeast-1", - ap_northeast_2: "ap-northeast-2", - ap_northeast_3: "ap-northeast-3", - ap_south_1: "ap-south-1", - ap_south_2: "ap-south-2", - ap_southeast_1: "ap-southeast-1", - ap_southeast_2: "ap-southeast-2", - ap_southeast_3: "ap-southeast-3", - ap_southeast_4: "ap-southeast-4", - ap_southeast_5: "ap-southeast-5", - ap_southeast_6: "ap-southeast-6", - ap_southeast_7: "ap-southeast-7", - ca_central_1: "ca-central-1", - ca_west_1: "ca-west-1", - cn_north_1: "cn-north-1", - cn_northwest_1: "cn-northwest-1", - eu_central_1: "eu-central-1", - eu_central_2: "eu-central-2", - eu_north_1: "eu-north-1", - eu_south_1: "eu-south-1", - eu_south_2: "eu-south-2", - eu_west_1: "eu-west-1", - eu_west_2: "eu-west-2", - eu_west_3: "eu-west-3", - il_central_1: "il-central-1", - me_central_1: "me-central-1", - me_south_1: "me-south-1", - mx_central_1: "mx-central-1", - sa_east_1: "sa-east-1", - us_east_2: "us-east-2", - us_gov_east_1: "us-gov-east-1", - us_gov_west_1: "us-gov-west-1", - us_west_1: "us-west-1", - us_west_2: "us-west-2" - }; - var ObjectOwnership = { - BucketOwnerEnforced: "BucketOwnerEnforced", - BucketOwnerPreferred: "BucketOwnerPreferred", - ObjectWriter: "ObjectWriter" - }; - var InventoryConfigurationState = { - DISABLED: "DISABLED", - ENABLED: "ENABLED" - }; - var TableSseAlgorithm = { - AES256: "AES256", - aws_kms: "aws:kms" - }; - var ExpirationState = { - DISABLED: "DISABLED", - ENABLED: "ENABLED" - }; - var SessionMode = { - ReadOnly: "ReadOnly", - ReadWrite: "ReadWrite" - }; - var AnalyticsS3ExportFileFormat = { - CSV: "CSV" - }; - var StorageClassAnalysisSchemaVersion = { - V_1: "V_1" - }; - var EncryptionType = { - NONE: "NONE", - SSE_C: "SSE-C" - }; - var IntelligentTieringStatus = { - Disabled: "Disabled", - Enabled: "Enabled" - }; - var IntelligentTieringAccessTier = { - ARCHIVE_ACCESS: "ARCHIVE_ACCESS", - DEEP_ARCHIVE_ACCESS: "DEEP_ARCHIVE_ACCESS" - }; - var InventoryFormat = { - CSV: "CSV", - ORC: "ORC", - Parquet: "Parquet" - }; - var InventoryIncludedObjectVersions = { - All: "All", - Current: "Current" - }; - var InventoryOptionalField = { - BucketKeyStatus: "BucketKeyStatus", - ChecksumAlgorithm: "ChecksumAlgorithm", - ETag: "ETag", - EncryptionStatus: "EncryptionStatus", - IntelligentTieringAccessTier: "IntelligentTieringAccessTier", - IsMultipartUploaded: "IsMultipartUploaded", - LastModifiedDate: "LastModifiedDate", - LifecycleExpirationDate: "LifecycleExpirationDate", - ObjectAccessControlList: "ObjectAccessControlList", - ObjectLockLegalHoldStatus: "ObjectLockLegalHoldStatus", - ObjectLockMode: "ObjectLockMode", - ObjectLockRetainUntilDate: "ObjectLockRetainUntilDate", - ObjectOwner: "ObjectOwner", - ReplicationStatus: "ReplicationStatus", - Size: "Size", - StorageClass: "StorageClass" - }; - var InventoryFrequency = { - Daily: "Daily", - Weekly: "Weekly" - }; - var TransitionStorageClass = { - DEEP_ARCHIVE: "DEEP_ARCHIVE", - GLACIER: "GLACIER", - GLACIER_IR: "GLACIER_IR", - INTELLIGENT_TIERING: "INTELLIGENT_TIERING", - ONEZONE_IA: "ONEZONE_IA", - STANDARD_IA: "STANDARD_IA" - }; - var ExpirationStatus = { - Disabled: "Disabled", - Enabled: "Enabled" - }; - var TransitionDefaultMinimumObjectSize = { - all_storage_classes_128K: "all_storage_classes_128K", - varies_by_storage_class: "varies_by_storage_class" - }; - var BucketLogsPermission = { - FULL_CONTROL: "FULL_CONTROL", - READ: "READ", - WRITE: "WRITE" - }; - var PartitionDateSource = { - DeliveryTime: "DeliveryTime", - EventTime: "EventTime" - }; - var S3TablesBucketType = { - aws: "aws", - customer: "customer" - }; - var Event = { - s3_IntelligentTiering: "s3:IntelligentTiering", - s3_LifecycleExpiration_: "s3:LifecycleExpiration:*", - s3_LifecycleExpiration_Delete: "s3:LifecycleExpiration:Delete", - s3_LifecycleExpiration_DeleteMarkerCreated: "s3:LifecycleExpiration:DeleteMarkerCreated", - s3_LifecycleTransition: "s3:LifecycleTransition", - s3_ObjectAcl_Put: "s3:ObjectAcl:Put", - s3_ObjectCreated_: "s3:ObjectCreated:*", - s3_ObjectCreated_CompleteMultipartUpload: "s3:ObjectCreated:CompleteMultipartUpload", - s3_ObjectCreated_Copy: "s3:ObjectCreated:Copy", - s3_ObjectCreated_Post: "s3:ObjectCreated:Post", - s3_ObjectCreated_Put: "s3:ObjectCreated:Put", - s3_ObjectRemoved_: "s3:ObjectRemoved:*", - s3_ObjectRemoved_Delete: "s3:ObjectRemoved:Delete", - s3_ObjectRemoved_DeleteMarkerCreated: "s3:ObjectRemoved:DeleteMarkerCreated", - s3_ObjectRestore_: "s3:ObjectRestore:*", - s3_ObjectRestore_Completed: "s3:ObjectRestore:Completed", - s3_ObjectRestore_Delete: "s3:ObjectRestore:Delete", - s3_ObjectRestore_Post: "s3:ObjectRestore:Post", - s3_ObjectTagging_: "s3:ObjectTagging:*", - s3_ObjectTagging_Delete: "s3:ObjectTagging:Delete", - s3_ObjectTagging_Put: "s3:ObjectTagging:Put", - s3_ReducedRedundancyLostObject: "s3:ReducedRedundancyLostObject", - s3_Replication_: "s3:Replication:*", - s3_Replication_OperationFailedReplication: "s3:Replication:OperationFailedReplication", - s3_Replication_OperationMissedThreshold: "s3:Replication:OperationMissedThreshold", - s3_Replication_OperationNotTracked: "s3:Replication:OperationNotTracked", - s3_Replication_OperationReplicatedAfterThreshold: "s3:Replication:OperationReplicatedAfterThreshold" - }; - var FilterRuleName = { - prefix: "prefix", - suffix: "suffix" - }; - var DeleteMarkerReplicationStatus = { - Disabled: "Disabled", - Enabled: "Enabled" - }; - var MetricsStatus = { - Disabled: "Disabled", - Enabled: "Enabled" - }; - var ReplicationTimeStatus = { - Disabled: "Disabled", - Enabled: "Enabled" - }; - var ExistingObjectReplicationStatus = { - Disabled: "Disabled", - Enabled: "Enabled" - }; - var ReplicaModificationsStatus = { - Disabled: "Disabled", - Enabled: "Enabled" - }; - var SseKmsEncryptedObjectsStatus = { - Disabled: "Disabled", - Enabled: "Enabled" - }; - var ReplicationRuleStatus = { - Disabled: "Disabled", - Enabled: "Enabled" - }; - var Payer = { - BucketOwner: "BucketOwner", - Requester: "Requester" - }; - var MFADeleteStatus = { - Disabled: "Disabled", - Enabled: "Enabled" - }; - var BucketVersioningStatus = { - Enabled: "Enabled", - Suspended: "Suspended" - }; - var Protocol = { - http: "http", - https: "https" - }; - var ReplicationStatus = { - COMPLETE: "COMPLETE", - COMPLETED: "COMPLETED", - FAILED: "FAILED", - PENDING: "PENDING", - REPLICA: "REPLICA" - }; - var ChecksumMode = { - ENABLED: "ENABLED" - }; - var ObjectAttributes = { - CHECKSUM: "Checksum", - ETAG: "ETag", - OBJECT_PARTS: "ObjectParts", - OBJECT_SIZE: "ObjectSize", - STORAGE_CLASS: "StorageClass" - }; - var ObjectLockEnabled = { - Enabled: "Enabled" - }; - var ObjectLockRetentionMode = { - COMPLIANCE: "COMPLIANCE", - GOVERNANCE: "GOVERNANCE" - }; - var ArchiveStatus = { - ARCHIVE_ACCESS: "ARCHIVE_ACCESS", - DEEP_ARCHIVE_ACCESS: "DEEP_ARCHIVE_ACCESS" - }; - var EncodingType = { - url: "url" - }; - var ObjectStorageClass = { - DEEP_ARCHIVE: "DEEP_ARCHIVE", - EXPRESS_ONEZONE: "EXPRESS_ONEZONE", - FSX_ONTAP: "FSX_ONTAP", - FSX_OPENZFS: "FSX_OPENZFS", - GLACIER: "GLACIER", - GLACIER_IR: "GLACIER_IR", - INTELLIGENT_TIERING: "INTELLIGENT_TIERING", - ONEZONE_IA: "ONEZONE_IA", - OUTPOSTS: "OUTPOSTS", - REDUCED_REDUNDANCY: "REDUCED_REDUNDANCY", - SNOW: "SNOW", - STANDARD: "STANDARD", - STANDARD_IA: "STANDARD_IA" - }; - var OptionalObjectAttributes = { - RESTORE_STATUS: "RestoreStatus" - }; - var ObjectVersionStorageClass = { - STANDARD: "STANDARD" - }; - var MFADelete = { - Disabled: "Disabled", - Enabled: "Enabled" - }; - var Tier = { - Bulk: "Bulk", - Expedited: "Expedited", - Standard: "Standard" - }; - var ExpressionType = { - SQL: "SQL" - }; - var CompressionType = { - BZIP2: "BZIP2", - GZIP: "GZIP", - NONE: "NONE" - }; - var FileHeaderInfo = { - IGNORE: "IGNORE", - NONE: "NONE", - USE: "USE" - }; - var JSONType = { - DOCUMENT: "DOCUMENT", - LINES: "LINES" - }; - var QuoteFields = { - ALWAYS: "ALWAYS", - ASNEEDED: "ASNEEDED" - }; - var RestoreRequestType = { - SELECT: "SELECT" - }; - exports.$Command = smithyClient.Command; - exports.__Client = smithyClient.Client; - exports.S3ServiceException = S3ServiceException.S3ServiceException; - exports.AbortMultipartUploadCommand = AbortMultipartUploadCommand; - exports.AnalyticsS3ExportFileFormat = AnalyticsS3ExportFileFormat; - exports.ArchiveStatus = ArchiveStatus; - exports.BucketAbacStatus = BucketAbacStatus; - exports.BucketAccelerateStatus = BucketAccelerateStatus; - exports.BucketCannedACL = BucketCannedACL; - exports.BucketLocationConstraint = BucketLocationConstraint; - exports.BucketLogsPermission = BucketLogsPermission; - exports.BucketNamespace = BucketNamespace; - exports.BucketType = BucketType; - exports.BucketVersioningStatus = BucketVersioningStatus; - exports.ChecksumAlgorithm = ChecksumAlgorithm; - exports.ChecksumMode = ChecksumMode; - exports.ChecksumType = ChecksumType; - exports.CompleteMultipartUploadCommand = CompleteMultipartUploadCommand; - exports.CompressionType = CompressionType; - exports.CopyObjectCommand = CopyObjectCommand; - exports.CreateBucketCommand = CreateBucketCommand; - exports.CreateBucketMetadataConfigurationCommand = CreateBucketMetadataConfigurationCommand; - exports.CreateBucketMetadataTableConfigurationCommand = CreateBucketMetadataTableConfigurationCommand; - exports.CreateMultipartUploadCommand = CreateMultipartUploadCommand; - exports.CreateSessionCommand = CreateSessionCommand; - exports.DataRedundancy = DataRedundancy; - exports.DeleteBucketAnalyticsConfigurationCommand = DeleteBucketAnalyticsConfigurationCommand; - exports.DeleteBucketCommand = DeleteBucketCommand; - exports.DeleteBucketCorsCommand = DeleteBucketCorsCommand; - exports.DeleteBucketEncryptionCommand = DeleteBucketEncryptionCommand; - exports.DeleteBucketIntelligentTieringConfigurationCommand = DeleteBucketIntelligentTieringConfigurationCommand; - exports.DeleteBucketInventoryConfigurationCommand = DeleteBucketInventoryConfigurationCommand; - exports.DeleteBucketLifecycleCommand = DeleteBucketLifecycleCommand; - exports.DeleteBucketMetadataConfigurationCommand = DeleteBucketMetadataConfigurationCommand; - exports.DeleteBucketMetadataTableConfigurationCommand = DeleteBucketMetadataTableConfigurationCommand; - exports.DeleteBucketMetricsConfigurationCommand = DeleteBucketMetricsConfigurationCommand; - exports.DeleteBucketOwnershipControlsCommand = DeleteBucketOwnershipControlsCommand; - exports.DeleteBucketPolicyCommand = DeleteBucketPolicyCommand; - exports.DeleteBucketReplicationCommand = DeleteBucketReplicationCommand; - exports.DeleteBucketTaggingCommand = DeleteBucketTaggingCommand; - exports.DeleteBucketWebsiteCommand = DeleteBucketWebsiteCommand; - exports.DeleteMarkerReplicationStatus = DeleteMarkerReplicationStatus; - exports.DeleteObjectCommand = DeleteObjectCommand2; - exports.DeleteObjectTaggingCommand = DeleteObjectTaggingCommand; - exports.DeleteObjectsCommand = DeleteObjectsCommand; - exports.DeletePublicAccessBlockCommand = DeletePublicAccessBlockCommand; - exports.EncodingType = EncodingType; - exports.EncryptionType = EncryptionType; - exports.Event = Event; - exports.ExistingObjectReplicationStatus = ExistingObjectReplicationStatus; - exports.ExpirationState = ExpirationState; - exports.ExpirationStatus = ExpirationStatus; - exports.ExpressionType = ExpressionType; - exports.FileHeaderInfo = FileHeaderInfo; - exports.FilterRuleName = FilterRuleName; - exports.GetBucketAbacCommand = GetBucketAbacCommand; - exports.GetBucketAccelerateConfigurationCommand = GetBucketAccelerateConfigurationCommand; - exports.GetBucketAclCommand = GetBucketAclCommand; - exports.GetBucketAnalyticsConfigurationCommand = GetBucketAnalyticsConfigurationCommand; - exports.GetBucketCorsCommand = GetBucketCorsCommand; - exports.GetBucketEncryptionCommand = GetBucketEncryptionCommand; - exports.GetBucketIntelligentTieringConfigurationCommand = GetBucketIntelligentTieringConfigurationCommand; - exports.GetBucketInventoryConfigurationCommand = GetBucketInventoryConfigurationCommand; - exports.GetBucketLifecycleConfigurationCommand = GetBucketLifecycleConfigurationCommand; - exports.GetBucketLocationCommand = GetBucketLocationCommand; - exports.GetBucketLoggingCommand = GetBucketLoggingCommand; - exports.GetBucketMetadataConfigurationCommand = GetBucketMetadataConfigurationCommand; - exports.GetBucketMetadataTableConfigurationCommand = GetBucketMetadataTableConfigurationCommand; - exports.GetBucketMetricsConfigurationCommand = GetBucketMetricsConfigurationCommand; - exports.GetBucketNotificationConfigurationCommand = GetBucketNotificationConfigurationCommand; - exports.GetBucketOwnershipControlsCommand = GetBucketOwnershipControlsCommand; - exports.GetBucketPolicyCommand = GetBucketPolicyCommand; - exports.GetBucketPolicyStatusCommand = GetBucketPolicyStatusCommand; - exports.GetBucketReplicationCommand = GetBucketReplicationCommand; - exports.GetBucketRequestPaymentCommand = GetBucketRequestPaymentCommand; - exports.GetBucketTaggingCommand = GetBucketTaggingCommand; - exports.GetBucketVersioningCommand = GetBucketVersioningCommand; - exports.GetBucketWebsiteCommand = GetBucketWebsiteCommand; - exports.GetObjectAclCommand = GetObjectAclCommand; - exports.GetObjectAttributesCommand = GetObjectAttributesCommand; - exports.GetObjectCommand = GetObjectCommand2; - exports.GetObjectLegalHoldCommand = GetObjectLegalHoldCommand; - exports.GetObjectLockConfigurationCommand = GetObjectLockConfigurationCommand; - exports.GetObjectRetentionCommand = GetObjectRetentionCommand; - exports.GetObjectTaggingCommand = GetObjectTaggingCommand; - exports.GetObjectTorrentCommand = GetObjectTorrentCommand; - exports.GetPublicAccessBlockCommand = GetPublicAccessBlockCommand; - exports.HeadBucketCommand = HeadBucketCommand; - exports.HeadObjectCommand = HeadObjectCommand2; - exports.IntelligentTieringAccessTier = IntelligentTieringAccessTier; - exports.IntelligentTieringStatus = IntelligentTieringStatus; - exports.InventoryConfigurationState = InventoryConfigurationState; - exports.InventoryFormat = InventoryFormat; - exports.InventoryFrequency = InventoryFrequency; - exports.InventoryIncludedObjectVersions = InventoryIncludedObjectVersions; - exports.InventoryOptionalField = InventoryOptionalField; - exports.JSONType = JSONType; - exports.ListBucketAnalyticsConfigurationsCommand = ListBucketAnalyticsConfigurationsCommand; - exports.ListBucketIntelligentTieringConfigurationsCommand = ListBucketIntelligentTieringConfigurationsCommand; - exports.ListBucketInventoryConfigurationsCommand = ListBucketInventoryConfigurationsCommand; - exports.ListBucketMetricsConfigurationsCommand = ListBucketMetricsConfigurationsCommand; - exports.ListBucketsCommand = ListBucketsCommand; - exports.ListDirectoryBucketsCommand = ListDirectoryBucketsCommand; - exports.ListMultipartUploadsCommand = ListMultipartUploadsCommand; - exports.ListObjectVersionsCommand = ListObjectVersionsCommand; - exports.ListObjectsCommand = ListObjectsCommand; - exports.ListObjectsV2Command = ListObjectsV2Command; - exports.ListPartsCommand = ListPartsCommand; - exports.LocationType = LocationType; - exports.MFADelete = MFADelete; - exports.MFADeleteStatus = MFADeleteStatus; - exports.MetadataDirective = MetadataDirective; - exports.MetricsStatus = MetricsStatus; - exports.ObjectAttributes = ObjectAttributes; - exports.ObjectCannedACL = ObjectCannedACL; - exports.ObjectLockEnabled = ObjectLockEnabled; - exports.ObjectLockLegalHoldStatus = ObjectLockLegalHoldStatus; - exports.ObjectLockMode = ObjectLockMode; - exports.ObjectLockRetentionMode = ObjectLockRetentionMode; - exports.ObjectOwnership = ObjectOwnership; - exports.ObjectStorageClass = ObjectStorageClass; - exports.ObjectVersionStorageClass = ObjectVersionStorageClass; - exports.OptionalObjectAttributes = OptionalObjectAttributes; - exports.OwnerOverride = OwnerOverride; - exports.PartitionDateSource = PartitionDateSource; - exports.Payer = Payer; - exports.Permission = Permission; - exports.Protocol = Protocol; - exports.PutBucketAbacCommand = PutBucketAbacCommand; - exports.PutBucketAccelerateConfigurationCommand = PutBucketAccelerateConfigurationCommand; - exports.PutBucketAclCommand = PutBucketAclCommand; - exports.PutBucketAnalyticsConfigurationCommand = PutBucketAnalyticsConfigurationCommand; - exports.PutBucketCorsCommand = PutBucketCorsCommand; - exports.PutBucketEncryptionCommand = PutBucketEncryptionCommand; - exports.PutBucketIntelligentTieringConfigurationCommand = PutBucketIntelligentTieringConfigurationCommand; - exports.PutBucketInventoryConfigurationCommand = PutBucketInventoryConfigurationCommand; - exports.PutBucketLifecycleConfigurationCommand = PutBucketLifecycleConfigurationCommand; - exports.PutBucketLoggingCommand = PutBucketLoggingCommand; - exports.PutBucketMetricsConfigurationCommand = PutBucketMetricsConfigurationCommand; - exports.PutBucketNotificationConfigurationCommand = PutBucketNotificationConfigurationCommand; - exports.PutBucketOwnershipControlsCommand = PutBucketOwnershipControlsCommand; - exports.PutBucketPolicyCommand = PutBucketPolicyCommand; - exports.PutBucketReplicationCommand = PutBucketReplicationCommand; - exports.PutBucketRequestPaymentCommand = PutBucketRequestPaymentCommand; - exports.PutBucketTaggingCommand = PutBucketTaggingCommand; - exports.PutBucketVersioningCommand = PutBucketVersioningCommand; - exports.PutBucketWebsiteCommand = PutBucketWebsiteCommand; - exports.PutObjectAclCommand = PutObjectAclCommand; - exports.PutObjectCommand = PutObjectCommand2; - exports.PutObjectLegalHoldCommand = PutObjectLegalHoldCommand; - exports.PutObjectLockConfigurationCommand = PutObjectLockConfigurationCommand; - exports.PutObjectRetentionCommand = PutObjectRetentionCommand; - exports.PutObjectTaggingCommand = PutObjectTaggingCommand; - exports.PutPublicAccessBlockCommand = PutPublicAccessBlockCommand; - exports.QuoteFields = QuoteFields; - exports.RenameObjectCommand = RenameObjectCommand; - exports.ReplicaModificationsStatus = ReplicaModificationsStatus; - exports.ReplicationRuleStatus = ReplicationRuleStatus; - exports.ReplicationStatus = ReplicationStatus; - exports.ReplicationTimeStatus = ReplicationTimeStatus; - exports.RequestCharged = RequestCharged; - exports.RequestPayer = RequestPayer; - exports.RestoreObjectCommand = RestoreObjectCommand; - exports.RestoreRequestType = RestoreRequestType; - exports.S3 = S3; - exports.S3Client = S3Client2; - exports.S3TablesBucketType = S3TablesBucketType; - exports.SelectObjectContentCommand = SelectObjectContentCommand; - exports.ServerSideEncryption = ServerSideEncryption; - exports.SessionMode = SessionMode; - exports.SseKmsEncryptedObjectsStatus = SseKmsEncryptedObjectsStatus; - exports.StorageClass = StorageClass; - exports.StorageClassAnalysisSchemaVersion = StorageClassAnalysisSchemaVersion; - exports.TableSseAlgorithm = TableSseAlgorithm; - exports.TaggingDirective = TaggingDirective; - exports.Tier = Tier; - exports.TransitionDefaultMinimumObjectSize = TransitionDefaultMinimumObjectSize; - exports.TransitionStorageClass = TransitionStorageClass; - exports.Type = Type; - exports.UpdateBucketMetadataInventoryTableConfigurationCommand = UpdateBucketMetadataInventoryTableConfigurationCommand; - exports.UpdateBucketMetadataJournalTableConfigurationCommand = UpdateBucketMetadataJournalTableConfigurationCommand; - exports.UpdateObjectEncryptionCommand = UpdateObjectEncryptionCommand; - exports.UploadPartCommand = UploadPartCommand; - exports.UploadPartCopyCommand = UploadPartCopyCommand; - exports.WriteGetObjectResponseCommand = WriteGetObjectResponseCommand; - exports.paginateListBuckets = paginateListBuckets; - exports.paginateListDirectoryBuckets = paginateListDirectoryBuckets; - exports.paginateListObjectsV2 = paginateListObjectsV2; - exports.paginateListParts = paginateListParts; - exports.waitForBucketExists = waitForBucketExists; - exports.waitForBucketNotExists = waitForBucketNotExists; - exports.waitForObjectExists = waitForObjectExists; - exports.waitForObjectNotExists = waitForObjectNotExists; - exports.waitUntilBucketExists = waitUntilBucketExists; - exports.waitUntilBucketNotExists = waitUntilBucketNotExists; - exports.waitUntilObjectExists = waitUntilObjectExists; - exports.waitUntilObjectNotExists = waitUntilObjectNotExists; - Object.prototype.hasOwnProperty.call(schemas_0, "__proto__") && !Object.prototype.hasOwnProperty.call(exports, "__proto__") && Object.defineProperty(exports, "__proto__", { - enumerable: true, - value: schemas_0["__proto__"] - }); - Object.keys(schemas_0).forEach(function(k5) { - if (k5 !== "default" && !Object.prototype.hasOwnProperty.call(exports, k5)) exports[k5] = schemas_0[k5]; - }); - Object.prototype.hasOwnProperty.call(errors, "__proto__") && !Object.prototype.hasOwnProperty.call(exports, "__proto__") && Object.defineProperty(exports, "__proto__", { - enumerable: true, - value: errors["__proto__"] - }); - Object.keys(errors).forEach(function(k5) { - if (k5 !== "default" && !Object.prototype.hasOwnProperty.call(exports, k5)) exports[k5] = errors[k5]; - }); - } -}); - -// node_modules/.pnpm/media-typer@0.3.0/node_modules/media-typer/index.js -var require_media_typer2 = __commonJS({ - "node_modules/.pnpm/media-typer@0.3.0/node_modules/media-typer/index.js"(exports) { - var paramRegExp = /; *([!#$%&'\*\+\-\.0-9A-Z\^_`a-z\|~]+) *= *("(?:[ !\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u0020-\u007e])*"|[!#$%&'\*\+\-\.0-9A-Z\^_`a-z\|~]+) */g; - var textRegExp = /^[\u0020-\u007e\u0080-\u00ff]+$/; - var tokenRegExp = /^[!#$%&'\*\+\-\.0-9A-Z\^_`a-z\|~]+$/; - var qescRegExp = /\\([\u0000-\u007f])/g; - var quoteRegExp = /([\\"])/g; - var subtypeNameRegExp = /^[A-Za-z0-9][A-Za-z0-9!#$&^_.-]{0,126}$/; - var typeNameRegExp = /^[A-Za-z0-9][A-Za-z0-9!#$&^_-]{0,126}$/; - var typeRegExp = /^ *([A-Za-z0-9][A-Za-z0-9!#$&^_-]{0,126})\/([A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}) *$/; - exports.format = format2; - exports.parse = parse5; - function format2(obj) { - if (!obj || typeof obj !== "object") { - throw new TypeError("argument obj is required"); - } - var parameters = obj.parameters; - var subtype = obj.subtype; - var suffix = obj.suffix; - var type = obj.type; - if (!type || !typeNameRegExp.test(type)) { - throw new TypeError("invalid type"); - } - if (!subtype || !subtypeNameRegExp.test(subtype)) { - throw new TypeError("invalid subtype"); - } - var string4 = type + "/" + subtype; - if (suffix) { - if (!typeNameRegExp.test(suffix)) { - throw new TypeError("invalid suffix"); - } - string4 += "+" + suffix; - } - if (parameters && typeof parameters === "object") { - var param; - var params = Object.keys(parameters).sort(); - for (var i5 = 0; i5 < params.length; i5++) { - param = params[i5]; - if (!tokenRegExp.test(param)) { - throw new TypeError("invalid parameter name"); - } - string4 += "; " + param + "=" + qstring(parameters[param]); - } - } - return string4; - } - function parse5(string4) { - if (!string4) { - throw new TypeError("argument string is required"); - } - if (typeof string4 === "object") { - string4 = getcontenttype(string4); - } - if (typeof string4 !== "string") { - throw new TypeError("argument string is required to be a string"); - } - var index2 = string4.indexOf(";"); - var type = index2 !== -1 ? string4.substr(0, index2) : string4; - var key; - var match; - var obj = splitType(type); - var params = {}; - var value; - paramRegExp.lastIndex = index2; - while (match = paramRegExp.exec(string4)) { - if (match.index !== index2) { - throw new TypeError("invalid parameter format"); - } - index2 += match[0].length; - key = match[1].toLowerCase(); - value = match[2]; - if (value[0] === '"') { - value = value.substr(1, value.length - 2).replace(qescRegExp, "$1"); - } - params[key] = value; - } - if (index2 !== -1 && index2 !== string4.length) { - throw new TypeError("invalid parameter format"); - } - obj.parameters = params; - return obj; - } - function getcontenttype(obj) { - if (typeof obj.getHeader === "function") { - return obj.getHeader("content-type"); - } - if (typeof obj.headers === "object") { - return obj.headers && obj.headers["content-type"]; - } - } - function qstring(val) { - var str = String(val); - if (tokenRegExp.test(str)) { - return str; - } - if (str.length > 0 && !textRegExp.test(str)) { - throw new TypeError("invalid parameter value"); - } - return '"' + str.replace(quoteRegExp, "\\$1") + '"'; - } - function splitType(string4) { - var match = typeRegExp.exec(string4.toLowerCase()); - if (!match) { - throw new TypeError("invalid media type"); - } - var type = match[1]; - var subtype = match[2]; - var suffix; - var index2 = subtype.lastIndexOf("+"); - if (index2 !== -1) { - suffix = subtype.substr(index2 + 1); - subtype = subtype.substr(0, index2); - } - var obj = { - type, - subtype, - suffix - }; - return obj; - } - } -}); - -// node_modules/.pnpm/mime-db@1.52.0/node_modules/mime-db/db.json -var require_db2 = __commonJS({ - "node_modules/.pnpm/mime-db@1.52.0/node_modules/mime-db/db.json"(exports, module) { - module.exports = { - "application/1d-interleaved-parityfec": { - source: "iana" - }, - "application/3gpdash-qoe-report+xml": { - source: "iana", - charset: "UTF-8", - compressible: true - }, - "application/3gpp-ims+xml": { - source: "iana", - compressible: true - }, - "application/3gpphal+json": { - source: "iana", - compressible: true - }, - "application/3gpphalforms+json": { - source: "iana", - compressible: true - }, - "application/a2l": { - source: "iana" - }, - "application/ace+cbor": { - source: "iana" - }, - "application/activemessage": { - source: "iana" - }, - "application/activity+json": { - source: "iana", - compressible: true - }, - "application/alto-costmap+json": { - source: "iana", - compressible: true - }, - "application/alto-costmapfilter+json": { - source: "iana", - compressible: true - }, - "application/alto-directory+json": { - source: "iana", - compressible: true - }, - "application/alto-endpointcost+json": { - source: "iana", - compressible: true - }, - "application/alto-endpointcostparams+json": { - source: "iana", - compressible: true - }, - "application/alto-endpointprop+json": { - source: "iana", - compressible: true - }, - "application/alto-endpointpropparams+json": { - source: "iana", - compressible: true - }, - "application/alto-error+json": { - source: "iana", - compressible: true - }, - "application/alto-networkmap+json": { - source: "iana", - compressible: true - }, - "application/alto-networkmapfilter+json": { - source: "iana", - compressible: true - }, - "application/alto-updatestreamcontrol+json": { - source: "iana", - compressible: true - }, - "application/alto-updatestreamparams+json": { - source: "iana", - compressible: true - }, - "application/aml": { - source: "iana" - }, - "application/andrew-inset": { - source: "iana", - extensions: ["ez"] - }, - "application/applefile": { - source: "iana" - }, - "application/applixware": { - source: "apache", - extensions: ["aw"] - }, - "application/at+jwt": { - source: "iana" - }, - "application/atf": { - source: "iana" - }, - "application/atfx": { - source: "iana" - }, - "application/atom+xml": { - source: "iana", - compressible: true, - extensions: ["atom"] - }, - "application/atomcat+xml": { - source: "iana", - compressible: true, - extensions: ["atomcat"] - }, - "application/atomdeleted+xml": { - source: "iana", - compressible: true, - extensions: ["atomdeleted"] - }, - "application/atomicmail": { - source: "iana" - }, - "application/atomsvc+xml": { - source: "iana", - compressible: true, - extensions: ["atomsvc"] - }, - "application/atsc-dwd+xml": { - source: "iana", - compressible: true, - extensions: ["dwd"] - }, - "application/atsc-dynamic-event-message": { - source: "iana" - }, - "application/atsc-held+xml": { - source: "iana", - compressible: true, - extensions: ["held"] - }, - "application/atsc-rdt+json": { - source: "iana", - compressible: true - }, - "application/atsc-rsat+xml": { - source: "iana", - compressible: true, - extensions: ["rsat"] - }, - "application/atxml": { - source: "iana" - }, - "application/auth-policy+xml": { - source: "iana", - compressible: true - }, - "application/bacnet-xdd+zip": { - source: "iana", - compressible: false - }, - "application/batch-smtp": { - source: "iana" - }, - "application/bdoc": { - compressible: false, - extensions: ["bdoc"] - }, - "application/beep+xml": { - source: "iana", - charset: "UTF-8", - compressible: true - }, - "application/calendar+json": { - source: "iana", - compressible: true - }, - "application/calendar+xml": { - source: "iana", - compressible: true, - extensions: ["xcs"] - }, - "application/call-completion": { - source: "iana" - }, - "application/cals-1840": { - source: "iana" - }, - "application/captive+json": { - source: "iana", - compressible: true - }, - "application/cbor": { - source: "iana" - }, - "application/cbor-seq": { - source: "iana" - }, - "application/cccex": { - source: "iana" - }, - "application/ccmp+xml": { - source: "iana", - compressible: true - }, - "application/ccxml+xml": { - source: "iana", - compressible: true, - extensions: ["ccxml"] - }, - "application/cdfx+xml": { - source: "iana", - compressible: true, - extensions: ["cdfx"] - }, - "application/cdmi-capability": { - source: "iana", - extensions: ["cdmia"] - }, - "application/cdmi-container": { - source: "iana", - extensions: ["cdmic"] - }, - "application/cdmi-domain": { - source: "iana", - extensions: ["cdmid"] - }, - "application/cdmi-object": { - source: "iana", - extensions: ["cdmio"] - }, - "application/cdmi-queue": { - source: "iana", - extensions: ["cdmiq"] - }, - "application/cdni": { - source: "iana" - }, - "application/cea": { - source: "iana" - }, - "application/cea-2018+xml": { - source: "iana", - compressible: true - }, - "application/cellml+xml": { - source: "iana", - compressible: true - }, - "application/cfw": { - source: "iana" - }, - "application/city+json": { - source: "iana", - compressible: true - }, - "application/clr": { - source: "iana" - }, - "application/clue+xml": { - source: "iana", - compressible: true - }, - "application/clue_info+xml": { - source: "iana", - compressible: true - }, - "application/cms": { - source: "iana" - }, - "application/cnrp+xml": { - source: "iana", - compressible: true - }, - "application/coap-group+json": { - source: "iana", - compressible: true - }, - "application/coap-payload": { - source: "iana" - }, - "application/commonground": { - source: "iana" - }, - "application/conference-info+xml": { - source: "iana", - compressible: true - }, - "application/cose": { - source: "iana" - }, - "application/cose-key": { - source: "iana" - }, - "application/cose-key-set": { - source: "iana" - }, - "application/cpl+xml": { - source: "iana", - compressible: true, - extensions: ["cpl"] - }, - "application/csrattrs": { - source: "iana" - }, - "application/csta+xml": { - source: "iana", - compressible: true - }, - "application/cstadata+xml": { - source: "iana", - compressible: true - }, - "application/csvm+json": { - source: "iana", - compressible: true - }, - "application/cu-seeme": { - source: "apache", - extensions: ["cu"] - }, - "application/cwt": { - source: "iana" - }, - "application/cybercash": { - source: "iana" - }, - "application/dart": { - compressible: true - }, - "application/dash+xml": { - source: "iana", - compressible: true, - extensions: ["mpd"] - }, - "application/dash-patch+xml": { - source: "iana", - compressible: true, - extensions: ["mpp"] - }, - "application/dashdelta": { - source: "iana" - }, - "application/davmount+xml": { - source: "iana", - compressible: true, - extensions: ["davmount"] - }, - "application/dca-rft": { - source: "iana" - }, - "application/dcd": { - source: "iana" - }, - "application/dec-dx": { - source: "iana" - }, - "application/dialog-info+xml": { - source: "iana", - compressible: true - }, - "application/dicom": { - source: "iana" - }, - "application/dicom+json": { - source: "iana", - compressible: true - }, - "application/dicom+xml": { - source: "iana", - compressible: true - }, - "application/dii": { - source: "iana" - }, - "application/dit": { - source: "iana" - }, - "application/dns": { - source: "iana" - }, - "application/dns+json": { - source: "iana", - compressible: true - }, - "application/dns-message": { - source: "iana" - }, - "application/docbook+xml": { - source: "apache", - compressible: true, - extensions: ["dbk"] - }, - "application/dots+cbor": { - source: "iana" - }, - "application/dskpp+xml": { - source: "iana", - compressible: true - }, - "application/dssc+der": { - source: "iana", - extensions: ["dssc"] - }, - "application/dssc+xml": { - source: "iana", - compressible: true, - extensions: ["xdssc"] - }, - "application/dvcs": { - source: "iana" - }, - "application/ecmascript": { - source: "iana", - compressible: true, - extensions: ["es", "ecma"] - }, - "application/edi-consent": { - source: "iana" - }, - "application/edi-x12": { - source: "iana", - compressible: false - }, - "application/edifact": { - source: "iana", - compressible: false - }, - "application/efi": { - source: "iana" - }, - "application/elm+json": { - source: "iana", - charset: "UTF-8", - compressible: true - }, - "application/elm+xml": { - source: "iana", - compressible: true - }, - "application/emergencycalldata.cap+xml": { - source: "iana", - charset: "UTF-8", - compressible: true - }, - "application/emergencycalldata.comment+xml": { - source: "iana", - compressible: true - }, - "application/emergencycalldata.control+xml": { - source: "iana", - compressible: true - }, - "application/emergencycalldata.deviceinfo+xml": { - source: "iana", - compressible: true - }, - "application/emergencycalldata.ecall.msd": { - source: "iana" - }, - "application/emergencycalldata.providerinfo+xml": { - source: "iana", - compressible: true - }, - "application/emergencycalldata.serviceinfo+xml": { - source: "iana", - compressible: true - }, - "application/emergencycalldata.subscriberinfo+xml": { - source: "iana", - compressible: true - }, - "application/emergencycalldata.veds+xml": { - source: "iana", - compressible: true - }, - "application/emma+xml": { - source: "iana", - compressible: true, - extensions: ["emma"] - }, - "application/emotionml+xml": { - source: "iana", - compressible: true, - extensions: ["emotionml"] - }, - "application/encaprtp": { - source: "iana" - }, - "application/epp+xml": { - source: "iana", - compressible: true - }, - "application/epub+zip": { - source: "iana", - compressible: false, - extensions: ["epub"] - }, - "application/eshop": { - source: "iana" - }, - "application/exi": { - source: "iana", - extensions: ["exi"] - }, - "application/expect-ct-report+json": { - source: "iana", - compressible: true - }, - "application/express": { - source: "iana", - extensions: ["exp"] - }, - "application/fastinfoset": { - source: "iana" - }, - "application/fastsoap": { - source: "iana" - }, - "application/fdt+xml": { - source: "iana", - compressible: true, - extensions: ["fdt"] - }, - "application/fhir+json": { - source: "iana", - charset: "UTF-8", - compressible: true - }, - "application/fhir+xml": { - source: "iana", - charset: "UTF-8", - compressible: true - }, - "application/fido.trusted-apps+json": { - compressible: true - }, - "application/fits": { - source: "iana" - }, - "application/flexfec": { - source: "iana" - }, - "application/font-sfnt": { - source: "iana" - }, - "application/font-tdpfr": { - source: "iana", - extensions: ["pfr"] - }, - "application/font-woff": { - source: "iana", - compressible: false - }, - "application/framework-attributes+xml": { - source: "iana", - compressible: true - }, - "application/geo+json": { - source: "iana", - compressible: true, - extensions: ["geojson"] - }, - "application/geo+json-seq": { - source: "iana" - }, - "application/geopackage+sqlite3": { - source: "iana" - }, - "application/geoxacml+xml": { - source: "iana", - compressible: true - }, - "application/gltf-buffer": { - source: "iana" - }, - "application/gml+xml": { - source: "iana", - compressible: true, - extensions: ["gml"] - }, - "application/gpx+xml": { - source: "apache", - compressible: true, - extensions: ["gpx"] - }, - "application/gxf": { - source: "apache", - extensions: ["gxf"] - }, - "application/gzip": { - source: "iana", - compressible: false, - extensions: ["gz"] - }, - "application/h224": { - source: "iana" - }, - "application/held+xml": { - source: "iana", - compressible: true - }, - "application/hjson": { - extensions: ["hjson"] - }, - "application/http": { - source: "iana" - }, - "application/hyperstudio": { - source: "iana", - extensions: ["stk"] - }, - "application/ibe-key-request+xml": { - source: "iana", - compressible: true - }, - "application/ibe-pkg-reply+xml": { - source: "iana", - compressible: true - }, - "application/ibe-pp-data": { - source: "iana" - }, - "application/iges": { - source: "iana" - }, - "application/im-iscomposing+xml": { - source: "iana", - charset: "UTF-8", - compressible: true - }, - "application/index": { - source: "iana" - }, - "application/index.cmd": { - source: "iana" - }, - "application/index.obj": { - source: "iana" - }, - "application/index.response": { - source: "iana" - }, - "application/index.vnd": { - source: "iana" - }, - "application/inkml+xml": { - source: "iana", - compressible: true, - extensions: ["ink", "inkml"] - }, - "application/iotp": { - source: "iana" - }, - "application/ipfix": { - source: "iana", - extensions: ["ipfix"] - }, - "application/ipp": { - source: "iana" - }, - "application/isup": { - source: "iana" - }, - "application/its+xml": { - source: "iana", - compressible: true, - extensions: ["its"] - }, - "application/java-archive": { - source: "apache", - compressible: false, - extensions: ["jar", "war", "ear"] - }, - "application/java-serialized-object": { - source: "apache", - compressible: false, - extensions: ["ser"] - }, - "application/java-vm": { - source: "apache", - compressible: false, - extensions: ["class"] - }, - "application/javascript": { - source: "iana", - charset: "UTF-8", - compressible: true, - extensions: ["js", "mjs"] - }, - "application/jf2feed+json": { - source: "iana", - compressible: true - }, - "application/jose": { - source: "iana" - }, - "application/jose+json": { - source: "iana", - compressible: true - }, - "application/jrd+json": { - source: "iana", - compressible: true - }, - "application/jscalendar+json": { - source: "iana", - compressible: true - }, - "application/json": { - source: "iana", - charset: "UTF-8", - compressible: true, - extensions: ["json", "map"] - }, - "application/json-patch+json": { - source: "iana", - compressible: true - }, - "application/json-seq": { - source: "iana" - }, - "application/json5": { - extensions: ["json5"] - }, - "application/jsonml+json": { - source: "apache", - compressible: true, - extensions: ["jsonml"] - }, - "application/jwk+json": { - source: "iana", - compressible: true - }, - "application/jwk-set+json": { - source: "iana", - compressible: true - }, - "application/jwt": { - source: "iana" - }, - "application/kpml-request+xml": { - source: "iana", - compressible: true - }, - "application/kpml-response+xml": { - source: "iana", - compressible: true - }, - "application/ld+json": { - source: "iana", - compressible: true, - extensions: ["jsonld"] - }, - "application/lgr+xml": { - source: "iana", - compressible: true, - extensions: ["lgr"] - }, - "application/link-format": { - source: "iana" - }, - "application/load-control+xml": { - source: "iana", - compressible: true - }, - "application/lost+xml": { - source: "iana", - compressible: true, - extensions: ["lostxml"] - }, - "application/lostsync+xml": { - source: "iana", - compressible: true - }, - "application/lpf+zip": { - source: "iana", - compressible: false - }, - "application/lxf": { - source: "iana" - }, - "application/mac-binhex40": { - source: "iana", - extensions: ["hqx"] - }, - "application/mac-compactpro": { - source: "apache", - extensions: ["cpt"] - }, - "application/macwriteii": { - source: "iana" - }, - "application/mads+xml": { - source: "iana", - compressible: true, - extensions: ["mads"] - }, - "application/manifest+json": { - source: "iana", - charset: "UTF-8", - compressible: true, - extensions: ["webmanifest"] - }, - "application/marc": { - source: "iana", - extensions: ["mrc"] - }, - "application/marcxml+xml": { - source: "iana", - compressible: true, - extensions: ["mrcx"] - }, - "application/mathematica": { - source: "iana", - extensions: ["ma", "nb", "mb"] - }, - "application/mathml+xml": { - source: "iana", - compressible: true, - extensions: ["mathml"] - }, - "application/mathml-content+xml": { - source: "iana", - compressible: true - }, - "application/mathml-presentation+xml": { - source: "iana", - compressible: true - }, - "application/mbms-associated-procedure-description+xml": { - source: "iana", - compressible: true - }, - "application/mbms-deregister+xml": { - source: "iana", - compressible: true - }, - "application/mbms-envelope+xml": { - source: "iana", - compressible: true - }, - "application/mbms-msk+xml": { - source: "iana", - compressible: true - }, - "application/mbms-msk-response+xml": { - source: "iana", - compressible: true - }, - "application/mbms-protection-description+xml": { - source: "iana", - compressible: true - }, - "application/mbms-reception-report+xml": { - source: "iana", - compressible: true - }, - "application/mbms-register+xml": { - source: "iana", - compressible: true - }, - "application/mbms-register-response+xml": { - source: "iana", - compressible: true - }, - "application/mbms-schedule+xml": { - source: "iana", - compressible: true - }, - "application/mbms-user-service-description+xml": { - source: "iana", - compressible: true - }, - "application/mbox": { - source: "iana", - extensions: ["mbox"] - }, - "application/media-policy-dataset+xml": { - source: "iana", - compressible: true, - extensions: ["mpf"] - }, - "application/media_control+xml": { - source: "iana", - compressible: true - }, - "application/mediaservercontrol+xml": { - source: "iana", - compressible: true, - extensions: ["mscml"] - }, - "application/merge-patch+json": { - source: "iana", - compressible: true - }, - "application/metalink+xml": { - source: "apache", - compressible: true, - extensions: ["metalink"] - }, - "application/metalink4+xml": { - source: "iana", - compressible: true, - extensions: ["meta4"] - }, - "application/mets+xml": { - source: "iana", - compressible: true, - extensions: ["mets"] - }, - "application/mf4": { - source: "iana" - }, - "application/mikey": { - source: "iana" - }, - "application/mipc": { - source: "iana" - }, - "application/missing-blocks+cbor-seq": { - source: "iana" - }, - "application/mmt-aei+xml": { - source: "iana", - compressible: true, - extensions: ["maei"] - }, - "application/mmt-usd+xml": { - source: "iana", - compressible: true, - extensions: ["musd"] - }, - "application/mods+xml": { - source: "iana", - compressible: true, - extensions: ["mods"] - }, - "application/moss-keys": { - source: "iana" - }, - "application/moss-signature": { - source: "iana" - }, - "application/mosskey-data": { - source: "iana" - }, - "application/mosskey-request": { - source: "iana" - }, - "application/mp21": { - source: "iana", - extensions: ["m21", "mp21"] - }, - "application/mp4": { - source: "iana", - extensions: ["mp4s", "m4p"] - }, - "application/mpeg4-generic": { - source: "iana" - }, - "application/mpeg4-iod": { - source: "iana" - }, - "application/mpeg4-iod-xmt": { - source: "iana" - }, - "application/mrb-consumer+xml": { - source: "iana", - compressible: true - }, - "application/mrb-publish+xml": { - source: "iana", - compressible: true - }, - "application/msc-ivr+xml": { - source: "iana", - charset: "UTF-8", - compressible: true - }, - "application/msc-mixer+xml": { - source: "iana", - charset: "UTF-8", - compressible: true - }, - "application/msword": { - source: "iana", - compressible: false, - extensions: ["doc", "dot"] - }, - "application/mud+json": { - source: "iana", - compressible: true - }, - "application/multipart-core": { - source: "iana" - }, - "application/mxf": { - source: "iana", - extensions: ["mxf"] - }, - "application/n-quads": { - source: "iana", - extensions: ["nq"] - }, - "application/n-triples": { - source: "iana", - extensions: ["nt"] - }, - "application/nasdata": { - source: "iana" - }, - "application/news-checkgroups": { - source: "iana", - charset: "US-ASCII" - }, - "application/news-groupinfo": { - source: "iana", - charset: "US-ASCII" - }, - "application/news-transmission": { - source: "iana" - }, - "application/nlsml+xml": { - source: "iana", - compressible: true - }, - "application/node": { - source: "iana", - extensions: ["cjs"] - }, - "application/nss": { - source: "iana" - }, - "application/oauth-authz-req+jwt": { - source: "iana" - }, - "application/oblivious-dns-message": { - source: "iana" - }, - "application/ocsp-request": { - source: "iana" - }, - "application/ocsp-response": { - source: "iana" - }, - "application/octet-stream": { - source: "iana", - compressible: false, - extensions: ["bin", "dms", "lrf", "mar", "so", "dist", "distz", "pkg", "bpk", "dump", "elc", "deploy", "exe", "dll", "deb", "dmg", "iso", "img", "msi", "msp", "msm", "buffer"] - }, - "application/oda": { - source: "iana", - extensions: ["oda"] - }, - "application/odm+xml": { - source: "iana", - compressible: true - }, - "application/odx": { - source: "iana" - }, - "application/oebps-package+xml": { - source: "iana", - compressible: true, - extensions: ["opf"] - }, - "application/ogg": { - source: "iana", - compressible: false, - extensions: ["ogx"] - }, - "application/omdoc+xml": { - source: "apache", - compressible: true, - extensions: ["omdoc"] - }, - "application/onenote": { - source: "apache", - extensions: ["onetoc", "onetoc2", "onetmp", "onepkg"] - }, - "application/opc-nodeset+xml": { - source: "iana", - compressible: true - }, - "application/oscore": { - source: "iana" - }, - "application/oxps": { - source: "iana", - extensions: ["oxps"] - }, - "application/p21": { - source: "iana" - }, - "application/p21+zip": { - source: "iana", - compressible: false - }, - "application/p2p-overlay+xml": { - source: "iana", - compressible: true, - extensions: ["relo"] - }, - "application/parityfec": { - source: "iana" - }, - "application/passport": { - source: "iana" - }, - "application/patch-ops-error+xml": { - source: "iana", - compressible: true, - extensions: ["xer"] - }, - "application/pdf": { - source: "iana", - compressible: false, - extensions: ["pdf"] - }, - "application/pdx": { - source: "iana" - }, - "application/pem-certificate-chain": { - source: "iana" - }, - "application/pgp-encrypted": { - source: "iana", - compressible: false, - extensions: ["pgp"] - }, - "application/pgp-keys": { - source: "iana", - extensions: ["asc"] - }, - "application/pgp-signature": { - source: "iana", - extensions: ["asc", "sig"] - }, - "application/pics-rules": { - source: "apache", - extensions: ["prf"] - }, - "application/pidf+xml": { - source: "iana", - charset: "UTF-8", - compressible: true - }, - "application/pidf-diff+xml": { - source: "iana", - charset: "UTF-8", - compressible: true - }, - "application/pkcs10": { - source: "iana", - extensions: ["p10"] - }, - "application/pkcs12": { - source: "iana" - }, - "application/pkcs7-mime": { - source: "iana", - extensions: ["p7m", "p7c"] - }, - "application/pkcs7-signature": { - source: "iana", - extensions: ["p7s"] - }, - "application/pkcs8": { - source: "iana", - extensions: ["p8"] - }, - "application/pkcs8-encrypted": { - source: "iana" - }, - "application/pkix-attr-cert": { - source: "iana", - extensions: ["ac"] - }, - "application/pkix-cert": { - source: "iana", - extensions: ["cer"] - }, - "application/pkix-crl": { - source: "iana", - extensions: ["crl"] - }, - "application/pkix-pkipath": { - source: "iana", - extensions: ["pkipath"] - }, - "application/pkixcmp": { - source: "iana", - extensions: ["pki"] - }, - "application/pls+xml": { - source: "iana", - compressible: true, - extensions: ["pls"] - }, - "application/poc-settings+xml": { - source: "iana", - charset: "UTF-8", - compressible: true - }, - "application/postscript": { - source: "iana", - compressible: true, - extensions: ["ai", "eps", "ps"] - }, - "application/ppsp-tracker+json": { - source: "iana", - compressible: true - }, - "application/problem+json": { - source: "iana", - compressible: true - }, - "application/problem+xml": { - source: "iana", - compressible: true - }, - "application/provenance+xml": { - source: "iana", - compressible: true, - extensions: ["provx"] - }, - "application/prs.alvestrand.titrax-sheet": { - source: "iana" - }, - "application/prs.cww": { - source: "iana", - extensions: ["cww"] - }, - "application/prs.cyn": { - source: "iana", - charset: "7-BIT" - }, - "application/prs.hpub+zip": { - source: "iana", - compressible: false - }, - "application/prs.nprend": { - source: "iana" - }, - "application/prs.plucker": { - source: "iana" - }, - "application/prs.rdf-xml-crypt": { - source: "iana" - }, - "application/prs.xsf+xml": { - source: "iana", - compressible: true - }, - "application/pskc+xml": { - source: "iana", - compressible: true, - extensions: ["pskcxml"] - }, - "application/pvd+json": { - source: "iana", - compressible: true - }, - "application/qsig": { - source: "iana" - }, - "application/raml+yaml": { - compressible: true, - extensions: ["raml"] - }, - "application/raptorfec": { - source: "iana" - }, - "application/rdap+json": { - source: "iana", - compressible: true - }, - "application/rdf+xml": { - source: "iana", - compressible: true, - extensions: ["rdf", "owl"] - }, - "application/reginfo+xml": { - source: "iana", - compressible: true, - extensions: ["rif"] - }, - "application/relax-ng-compact-syntax": { - source: "iana", - extensions: ["rnc"] - }, - "application/remote-printing": { - source: "iana" - }, - "application/reputon+json": { - source: "iana", - compressible: true - }, - "application/resource-lists+xml": { - source: "iana", - compressible: true, - extensions: ["rl"] - }, - "application/resource-lists-diff+xml": { - source: "iana", - compressible: true, - extensions: ["rld"] - }, - "application/rfc+xml": { - source: "iana", - compressible: true - }, - "application/riscos": { - source: "iana" - }, - "application/rlmi+xml": { - source: "iana", - compressible: true - }, - "application/rls-services+xml": { - source: "iana", - compressible: true, - extensions: ["rs"] - }, - "application/route-apd+xml": { - source: "iana", - compressible: true, - extensions: ["rapd"] - }, - "application/route-s-tsid+xml": { - source: "iana", - compressible: true, - extensions: ["sls"] - }, - "application/route-usd+xml": { - source: "iana", - compressible: true, - extensions: ["rusd"] - }, - "application/rpki-ghostbusters": { - source: "iana", - extensions: ["gbr"] - }, - "application/rpki-manifest": { - source: "iana", - extensions: ["mft"] - }, - "application/rpki-publication": { - source: "iana" - }, - "application/rpki-roa": { - source: "iana", - extensions: ["roa"] - }, - "application/rpki-updown": { - source: "iana" - }, - "application/rsd+xml": { - source: "apache", - compressible: true, - extensions: ["rsd"] - }, - "application/rss+xml": { - source: "apache", - compressible: true, - extensions: ["rss"] - }, - "application/rtf": { - source: "iana", - compressible: true, - extensions: ["rtf"] - }, - "application/rtploopback": { - source: "iana" - }, - "application/rtx": { - source: "iana" - }, - "application/samlassertion+xml": { - source: "iana", - compressible: true - }, - "application/samlmetadata+xml": { - source: "iana", - compressible: true - }, - "application/sarif+json": { - source: "iana", - compressible: true - }, - "application/sarif-external-properties+json": { - source: "iana", - compressible: true - }, - "application/sbe": { - source: "iana" - }, - "application/sbml+xml": { - source: "iana", - compressible: true, - extensions: ["sbml"] - }, - "application/scaip+xml": { - source: "iana", - compressible: true - }, - "application/scim+json": { - source: "iana", - compressible: true - }, - "application/scvp-cv-request": { - source: "iana", - extensions: ["scq"] - }, - "application/scvp-cv-response": { - source: "iana", - extensions: ["scs"] - }, - "application/scvp-vp-request": { - source: "iana", - extensions: ["spq"] - }, - "application/scvp-vp-response": { - source: "iana", - extensions: ["spp"] - }, - "application/sdp": { - source: "iana", - extensions: ["sdp"] - }, - "application/secevent+jwt": { - source: "iana" - }, - "application/senml+cbor": { - source: "iana" - }, - "application/senml+json": { - source: "iana", - compressible: true - }, - "application/senml+xml": { - source: "iana", - compressible: true, - extensions: ["senmlx"] - }, - "application/senml-etch+cbor": { - source: "iana" - }, - "application/senml-etch+json": { - source: "iana", - compressible: true - }, - "application/senml-exi": { - source: "iana" - }, - "application/sensml+cbor": { - source: "iana" - }, - "application/sensml+json": { - source: "iana", - compressible: true - }, - "application/sensml+xml": { - source: "iana", - compressible: true, - extensions: ["sensmlx"] - }, - "application/sensml-exi": { - source: "iana" - }, - "application/sep+xml": { - source: "iana", - compressible: true - }, - "application/sep-exi": { - source: "iana" - }, - "application/session-info": { - source: "iana" - }, - "application/set-payment": { - source: "iana" - }, - "application/set-payment-initiation": { - source: "iana", - extensions: ["setpay"] - }, - "application/set-registration": { - source: "iana" - }, - "application/set-registration-initiation": { - source: "iana", - extensions: ["setreg"] - }, - "application/sgml": { - source: "iana" - }, - "application/sgml-open-catalog": { - source: "iana" - }, - "application/shf+xml": { - source: "iana", - compressible: true, - extensions: ["shf"] - }, - "application/sieve": { - source: "iana", - extensions: ["siv", "sieve"] - }, - "application/simple-filter+xml": { - source: "iana", - compressible: true - }, - "application/simple-message-summary": { - source: "iana" - }, - "application/simplesymbolcontainer": { - source: "iana" - }, - "application/sipc": { - source: "iana" - }, - "application/slate": { - source: "iana" - }, - "application/smil": { - source: "iana" - }, - "application/smil+xml": { - source: "iana", - compressible: true, - extensions: ["smi", "smil"] - }, - "application/smpte336m": { - source: "iana" - }, - "application/soap+fastinfoset": { - source: "iana" - }, - "application/soap+xml": { - source: "iana", - compressible: true - }, - "application/sparql-query": { - source: "iana", - extensions: ["rq"] - }, - "application/sparql-results+xml": { - source: "iana", - compressible: true, - extensions: ["srx"] - }, - "application/spdx+json": { - source: "iana", - compressible: true - }, - "application/spirits-event+xml": { - source: "iana", - compressible: true - }, - "application/sql": { - source: "iana" - }, - "application/srgs": { - source: "iana", - extensions: ["gram"] - }, - "application/srgs+xml": { - source: "iana", - compressible: true, - extensions: ["grxml"] - }, - "application/sru+xml": { - source: "iana", - compressible: true, - extensions: ["sru"] - }, - "application/ssdl+xml": { - source: "apache", - compressible: true, - extensions: ["ssdl"] - }, - "application/ssml+xml": { - source: "iana", - compressible: true, - extensions: ["ssml"] - }, - "application/stix+json": { - source: "iana", - compressible: true - }, - "application/swid+xml": { - source: "iana", - compressible: true, - extensions: ["swidtag"] - }, - "application/tamp-apex-update": { - source: "iana" - }, - "application/tamp-apex-update-confirm": { - source: "iana" - }, - "application/tamp-community-update": { - source: "iana" - }, - "application/tamp-community-update-confirm": { - source: "iana" - }, - "application/tamp-error": { - source: "iana" - }, - "application/tamp-sequence-adjust": { - source: "iana" - }, - "application/tamp-sequence-adjust-confirm": { - source: "iana" - }, - "application/tamp-status-query": { - source: "iana" - }, - "application/tamp-status-response": { - source: "iana" - }, - "application/tamp-update": { - source: "iana" - }, - "application/tamp-update-confirm": { - source: "iana" - }, - "application/tar": { - compressible: true - }, - "application/taxii+json": { - source: "iana", - compressible: true - }, - "application/td+json": { - source: "iana", - compressible: true - }, - "application/tei+xml": { - source: "iana", - compressible: true, - extensions: ["tei", "teicorpus"] - }, - "application/tetra_isi": { - source: "iana" - }, - "application/thraud+xml": { - source: "iana", - compressible: true, - extensions: ["tfi"] - }, - "application/timestamp-query": { - source: "iana" - }, - "application/timestamp-reply": { - source: "iana" - }, - "application/timestamped-data": { - source: "iana", - extensions: ["tsd"] - }, - "application/tlsrpt+gzip": { - source: "iana" - }, - "application/tlsrpt+json": { - source: "iana", - compressible: true - }, - "application/tnauthlist": { - source: "iana" - }, - "application/token-introspection+jwt": { - source: "iana" - }, - "application/toml": { - compressible: true, - extensions: ["toml"] - }, - "application/trickle-ice-sdpfrag": { - source: "iana" - }, - "application/trig": { - source: "iana", - extensions: ["trig"] - }, - "application/ttml+xml": { - source: "iana", - compressible: true, - extensions: ["ttml"] - }, - "application/tve-trigger": { - source: "iana" - }, - "application/tzif": { - source: "iana" - }, - "application/tzif-leap": { - source: "iana" - }, - "application/ubjson": { - compressible: false, - extensions: ["ubj"] - }, - "application/ulpfec": { - source: "iana" - }, - "application/urc-grpsheet+xml": { - source: "iana", - compressible: true - }, - "application/urc-ressheet+xml": { - source: "iana", - compressible: true, - extensions: ["rsheet"] - }, - "application/urc-targetdesc+xml": { - source: "iana", - compressible: true, - extensions: ["td"] - }, - "application/urc-uisocketdesc+xml": { - source: "iana", - compressible: true - }, - "application/vcard+json": { - source: "iana", - compressible: true - }, - "application/vcard+xml": { - source: "iana", - compressible: true - }, - "application/vemmi": { - source: "iana" - }, - "application/vividence.scriptfile": { - source: "apache" - }, - "application/vnd.1000minds.decision-model+xml": { - source: "iana", - compressible: true, - extensions: ["1km"] - }, - "application/vnd.3gpp-prose+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp-prose-pc3ch+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp-v2x-local-service-information": { - source: "iana" - }, - "application/vnd.3gpp.5gnas": { - source: "iana" - }, - "application/vnd.3gpp.access-transfer-events+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.bsf+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.gmop+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.gtpc": { - source: "iana" - }, - "application/vnd.3gpp.interworking-data": { - source: "iana" - }, - "application/vnd.3gpp.lpp": { - source: "iana" - }, - "application/vnd.3gpp.mc-signalling-ear": { - source: "iana" - }, - "application/vnd.3gpp.mcdata-affiliation-command+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.mcdata-info+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.mcdata-payload": { - source: "iana" - }, - "application/vnd.3gpp.mcdata-service-config+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.mcdata-signalling": { - source: "iana" - }, - "application/vnd.3gpp.mcdata-ue-config+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.mcdata-user-profile+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.mcptt-affiliation-command+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.mcptt-floor-request+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.mcptt-info+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.mcptt-location-info+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.mcptt-mbms-usage-info+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.mcptt-service-config+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.mcptt-signed+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.mcptt-ue-config+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.mcptt-ue-init-config+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.mcptt-user-profile+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.mcvideo-affiliation-command+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.mcvideo-affiliation-info+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.mcvideo-info+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.mcvideo-location-info+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.mcvideo-mbms-usage-info+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.mcvideo-service-config+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.mcvideo-transmission-request+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.mcvideo-ue-config+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.mcvideo-user-profile+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.mid-call+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.ngap": { - source: "iana" - }, - "application/vnd.3gpp.pfcp": { - source: "iana" - }, - "application/vnd.3gpp.pic-bw-large": { - source: "iana", - extensions: ["plb"] - }, - "application/vnd.3gpp.pic-bw-small": { - source: "iana", - extensions: ["psb"] - }, - "application/vnd.3gpp.pic-bw-var": { - source: "iana", - extensions: ["pvb"] - }, - "application/vnd.3gpp.s1ap": { - source: "iana" - }, - "application/vnd.3gpp.sms": { - source: "iana" - }, - "application/vnd.3gpp.sms+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.srvcc-ext+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.srvcc-info+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.state-and-event-info+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp.ussd+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp2.bcmcsinfo+xml": { - source: "iana", - compressible: true - }, - "application/vnd.3gpp2.sms": { - source: "iana" - }, - "application/vnd.3gpp2.tcap": { - source: "iana", - extensions: ["tcap"] - }, - "application/vnd.3lightssoftware.imagescal": { - source: "iana" - }, - "application/vnd.3m.post-it-notes": { - source: "iana", - extensions: ["pwn"] - }, - "application/vnd.accpac.simply.aso": { - source: "iana", - extensions: ["aso"] - }, - "application/vnd.accpac.simply.imp": { - source: "iana", - extensions: ["imp"] - }, - "application/vnd.acucobol": { - source: "iana", - extensions: ["acu"] - }, - "application/vnd.acucorp": { - source: "iana", - extensions: ["atc", "acutc"] - }, - "application/vnd.adobe.air-application-installer-package+zip": { - source: "apache", - compressible: false, - extensions: ["air"] - }, - "application/vnd.adobe.flash.movie": { - source: "iana" - }, - "application/vnd.adobe.formscentral.fcdt": { - source: "iana", - extensions: ["fcdt"] - }, - "application/vnd.adobe.fxp": { - source: "iana", - extensions: ["fxp", "fxpl"] - }, - "application/vnd.adobe.partial-upload": { - source: "iana" - }, - "application/vnd.adobe.xdp+xml": { - source: "iana", - compressible: true, - extensions: ["xdp"] - }, - "application/vnd.adobe.xfdf": { - source: "iana", - extensions: ["xfdf"] - }, - "application/vnd.aether.imp": { - source: "iana" - }, - "application/vnd.afpc.afplinedata": { - source: "iana" - }, - "application/vnd.afpc.afplinedata-pagedef": { - source: "iana" - }, - "application/vnd.afpc.cmoca-cmresource": { - source: "iana" - }, - "application/vnd.afpc.foca-charset": { - source: "iana" - }, - "application/vnd.afpc.foca-codedfont": { - source: "iana" - }, - "application/vnd.afpc.foca-codepage": { - source: "iana" - }, - "application/vnd.afpc.modca": { - source: "iana" - }, - "application/vnd.afpc.modca-cmtable": { - source: "iana" - }, - "application/vnd.afpc.modca-formdef": { - source: "iana" - }, - "application/vnd.afpc.modca-mediummap": { - source: "iana" - }, - "application/vnd.afpc.modca-objectcontainer": { - source: "iana" - }, - "application/vnd.afpc.modca-overlay": { - source: "iana" - }, - "application/vnd.afpc.modca-pagesegment": { - source: "iana" - }, - "application/vnd.age": { - source: "iana", - extensions: ["age"] - }, - "application/vnd.ah-barcode": { - source: "iana" - }, - "application/vnd.ahead.space": { - source: "iana", - extensions: ["ahead"] - }, - "application/vnd.airzip.filesecure.azf": { - source: "iana", - extensions: ["azf"] - }, - "application/vnd.airzip.filesecure.azs": { - source: "iana", - extensions: ["azs"] - }, - "application/vnd.amadeus+json": { - source: "iana", - compressible: true - }, - "application/vnd.amazon.ebook": { - source: "apache", - extensions: ["azw"] - }, - "application/vnd.amazon.mobi8-ebook": { - source: "iana" - }, - "application/vnd.americandynamics.acc": { - source: "iana", - extensions: ["acc"] - }, - "application/vnd.amiga.ami": { - source: "iana", - extensions: ["ami"] - }, - "application/vnd.amundsen.maze+xml": { - source: "iana", - compressible: true - }, - "application/vnd.android.ota": { - source: "iana" - }, - "application/vnd.android.package-archive": { - source: "apache", - compressible: false, - extensions: ["apk"] - }, - "application/vnd.anki": { - source: "iana" - }, - "application/vnd.anser-web-certificate-issue-initiation": { - source: "iana", - extensions: ["cii"] - }, - "application/vnd.anser-web-funds-transfer-initiation": { - source: "apache", - extensions: ["fti"] - }, - "application/vnd.antix.game-component": { - source: "iana", - extensions: ["atx"] - }, - "application/vnd.apache.arrow.file": { - source: "iana" - }, - "application/vnd.apache.arrow.stream": { - source: "iana" - }, - "application/vnd.apache.thrift.binary": { - source: "iana" - }, - "application/vnd.apache.thrift.compact": { - source: "iana" - }, - "application/vnd.apache.thrift.json": { - source: "iana" - }, - "application/vnd.api+json": { - source: "iana", - compressible: true - }, - "application/vnd.aplextor.warrp+json": { - source: "iana", - compressible: true - }, - "application/vnd.apothekende.reservation+json": { - source: "iana", - compressible: true - }, - "application/vnd.apple.installer+xml": { - source: "iana", - compressible: true, - extensions: ["mpkg"] - }, - "application/vnd.apple.keynote": { - source: "iana", - extensions: ["key"] - }, - "application/vnd.apple.mpegurl": { - source: "iana", - extensions: ["m3u8"] - }, - "application/vnd.apple.numbers": { - source: "iana", - extensions: ["numbers"] - }, - "application/vnd.apple.pages": { - source: "iana", - extensions: ["pages"] - }, - "application/vnd.apple.pkpass": { - compressible: false, - extensions: ["pkpass"] - }, - "application/vnd.arastra.swi": { - source: "iana" - }, - "application/vnd.aristanetworks.swi": { - source: "iana", - extensions: ["swi"] - }, - "application/vnd.artisan+json": { - source: "iana", - compressible: true - }, - "application/vnd.artsquare": { - source: "iana" - }, - "application/vnd.astraea-software.iota": { - source: "iana", - extensions: ["iota"] - }, - "application/vnd.audiograph": { - source: "iana", - extensions: ["aep"] - }, - "application/vnd.autopackage": { - source: "iana" - }, - "application/vnd.avalon+json": { - source: "iana", - compressible: true - }, - "application/vnd.avistar+xml": { - source: "iana", - compressible: true - }, - "application/vnd.balsamiq.bmml+xml": { - source: "iana", - compressible: true, - extensions: ["bmml"] - }, - "application/vnd.balsamiq.bmpr": { - source: "iana" - }, - "application/vnd.banana-accounting": { - source: "iana" - }, - "application/vnd.bbf.usp.error": { - source: "iana" - }, - "application/vnd.bbf.usp.msg": { - source: "iana" - }, - "application/vnd.bbf.usp.msg+json": { - source: "iana", - compressible: true - }, - "application/vnd.bekitzur-stech+json": { - source: "iana", - compressible: true - }, - "application/vnd.bint.med-content": { - source: "iana" - }, - "application/vnd.biopax.rdf+xml": { - source: "iana", - compressible: true - }, - "application/vnd.blink-idb-value-wrapper": { - source: "iana" - }, - "application/vnd.blueice.multipass": { - source: "iana", - extensions: ["mpm"] - }, - "application/vnd.bluetooth.ep.oob": { - source: "iana" - }, - "application/vnd.bluetooth.le.oob": { - source: "iana" - }, - "application/vnd.bmi": { - source: "iana", - extensions: ["bmi"] - }, - "application/vnd.bpf": { - source: "iana" - }, - "application/vnd.bpf3": { - source: "iana" - }, - "application/vnd.businessobjects": { - source: "iana", - extensions: ["rep"] - }, - "application/vnd.byu.uapi+json": { - source: "iana", - compressible: true - }, - "application/vnd.cab-jscript": { - source: "iana" - }, - "application/vnd.canon-cpdl": { - source: "iana" - }, - "application/vnd.canon-lips": { - source: "iana" - }, - "application/vnd.capasystems-pg+json": { - source: "iana", - compressible: true - }, - "application/vnd.cendio.thinlinc.clientconf": { - source: "iana" - }, - "application/vnd.century-systems.tcp_stream": { - source: "iana" - }, - "application/vnd.chemdraw+xml": { - source: "iana", - compressible: true, - extensions: ["cdxml"] - }, - "application/vnd.chess-pgn": { - source: "iana" - }, - "application/vnd.chipnuts.karaoke-mmd": { - source: "iana", - extensions: ["mmd"] - }, - "application/vnd.ciedi": { - source: "iana" - }, - "application/vnd.cinderella": { - source: "iana", - extensions: ["cdy"] - }, - "application/vnd.cirpack.isdn-ext": { - source: "iana" - }, - "application/vnd.citationstyles.style+xml": { - source: "iana", - compressible: true, - extensions: ["csl"] - }, - "application/vnd.claymore": { - source: "iana", - extensions: ["cla"] - }, - "application/vnd.cloanto.rp9": { - source: "iana", - extensions: ["rp9"] - }, - "application/vnd.clonk.c4group": { - source: "iana", - extensions: ["c4g", "c4d", "c4f", "c4p", "c4u"] - }, - "application/vnd.cluetrust.cartomobile-config": { - source: "iana", - extensions: ["c11amc"] - }, - "application/vnd.cluetrust.cartomobile-config-pkg": { - source: "iana", - extensions: ["c11amz"] - }, - "application/vnd.coffeescript": { - source: "iana" - }, - "application/vnd.collabio.xodocuments.document": { - source: "iana" - }, - "application/vnd.collabio.xodocuments.document-template": { - source: "iana" - }, - "application/vnd.collabio.xodocuments.presentation": { - source: "iana" - }, - "application/vnd.collabio.xodocuments.presentation-template": { - source: "iana" - }, - "application/vnd.collabio.xodocuments.spreadsheet": { - source: "iana" - }, - "application/vnd.collabio.xodocuments.spreadsheet-template": { - source: "iana" - }, - "application/vnd.collection+json": { - source: "iana", - compressible: true - }, - "application/vnd.collection.doc+json": { - source: "iana", - compressible: true - }, - "application/vnd.collection.next+json": { - source: "iana", - compressible: true - }, - "application/vnd.comicbook+zip": { - source: "iana", - compressible: false - }, - "application/vnd.comicbook-rar": { - source: "iana" - }, - "application/vnd.commerce-battelle": { - source: "iana" - }, - "application/vnd.commonspace": { - source: "iana", - extensions: ["csp"] - }, - "application/vnd.contact.cmsg": { - source: "iana", - extensions: ["cdbcmsg"] - }, - "application/vnd.coreos.ignition+json": { - source: "iana", - compressible: true - }, - "application/vnd.cosmocaller": { - source: "iana", - extensions: ["cmc"] - }, - "application/vnd.crick.clicker": { - source: "iana", - extensions: ["clkx"] - }, - "application/vnd.crick.clicker.keyboard": { - source: "iana", - extensions: ["clkk"] - }, - "application/vnd.crick.clicker.palette": { - source: "iana", - extensions: ["clkp"] - }, - "application/vnd.crick.clicker.template": { - source: "iana", - extensions: ["clkt"] - }, - "application/vnd.crick.clicker.wordbank": { - source: "iana", - extensions: ["clkw"] - }, - "application/vnd.criticaltools.wbs+xml": { - source: "iana", - compressible: true, - extensions: ["wbs"] - }, - "application/vnd.cryptii.pipe+json": { - source: "iana", - compressible: true - }, - "application/vnd.crypto-shade-file": { - source: "iana" - }, - "application/vnd.cryptomator.encrypted": { - source: "iana" - }, - "application/vnd.cryptomator.vault": { - source: "iana" - }, - "application/vnd.ctc-posml": { - source: "iana", - extensions: ["pml"] - }, - "application/vnd.ctct.ws+xml": { - source: "iana", - compressible: true - }, - "application/vnd.cups-pdf": { - source: "iana" - }, - "application/vnd.cups-postscript": { - source: "iana" - }, - "application/vnd.cups-ppd": { - source: "iana", - extensions: ["ppd"] - }, - "application/vnd.cups-raster": { - source: "iana" - }, - "application/vnd.cups-raw": { - source: "iana" - }, - "application/vnd.curl": { - source: "iana" - }, - "application/vnd.curl.car": { - source: "apache", - extensions: ["car"] - }, - "application/vnd.curl.pcurl": { - source: "apache", - extensions: ["pcurl"] - }, - "application/vnd.cyan.dean.root+xml": { - source: "iana", - compressible: true - }, - "application/vnd.cybank": { - source: "iana" - }, - "application/vnd.cyclonedx+json": { - source: "iana", - compressible: true - }, - "application/vnd.cyclonedx+xml": { - source: "iana", - compressible: true - }, - "application/vnd.d2l.coursepackage1p0+zip": { - source: "iana", - compressible: false - }, - "application/vnd.d3m-dataset": { - source: "iana" - }, - "application/vnd.d3m-problem": { - source: "iana" - }, - "application/vnd.dart": { - source: "iana", - compressible: true, - extensions: ["dart"] - }, - "application/vnd.data-vision.rdz": { - source: "iana", - extensions: ["rdz"] - }, - "application/vnd.datapackage+json": { - source: "iana", - compressible: true - }, - "application/vnd.dataresource+json": { - source: "iana", - compressible: true - }, - "application/vnd.dbf": { - source: "iana", - extensions: ["dbf"] - }, - "application/vnd.debian.binary-package": { - source: "iana" - }, - "application/vnd.dece.data": { - source: "iana", - extensions: ["uvf", "uvvf", "uvd", "uvvd"] - }, - "application/vnd.dece.ttml+xml": { - source: "iana", - compressible: true, - extensions: ["uvt", "uvvt"] - }, - "application/vnd.dece.unspecified": { - source: "iana", - extensions: ["uvx", "uvvx"] - }, - "application/vnd.dece.zip": { - source: "iana", - extensions: ["uvz", "uvvz"] - }, - "application/vnd.denovo.fcselayout-link": { - source: "iana", - extensions: ["fe_launch"] - }, - "application/vnd.desmume.movie": { - source: "iana" - }, - "application/vnd.dir-bi.plate-dl-nosuffix": { - source: "iana" - }, - "application/vnd.dm.delegation+xml": { - source: "iana", - compressible: true - }, - "application/vnd.dna": { - source: "iana", - extensions: ["dna"] - }, - "application/vnd.document+json": { - source: "iana", - compressible: true - }, - "application/vnd.dolby.mlp": { - source: "apache", - extensions: ["mlp"] - }, - "application/vnd.dolby.mobile.1": { - source: "iana" - }, - "application/vnd.dolby.mobile.2": { - source: "iana" - }, - "application/vnd.doremir.scorecloud-binary-document": { - source: "iana" - }, - "application/vnd.dpgraph": { - source: "iana", - extensions: ["dpg"] - }, - "application/vnd.dreamfactory": { - source: "iana", - extensions: ["dfac"] - }, - "application/vnd.drive+json": { - source: "iana", - compressible: true - }, - "application/vnd.ds-keypoint": { - source: "apache", - extensions: ["kpxx"] - }, - "application/vnd.dtg.local": { - source: "iana" - }, - "application/vnd.dtg.local.flash": { - source: "iana" - }, - "application/vnd.dtg.local.html": { - source: "iana" - }, - "application/vnd.dvb.ait": { - source: "iana", - extensions: ["ait"] - }, - "application/vnd.dvb.dvbisl+xml": { - source: "iana", - compressible: true - }, - "application/vnd.dvb.dvbj": { - source: "iana" - }, - "application/vnd.dvb.esgcontainer": { - source: "iana" - }, - "application/vnd.dvb.ipdcdftnotifaccess": { - source: "iana" - }, - "application/vnd.dvb.ipdcesgaccess": { - source: "iana" - }, - "application/vnd.dvb.ipdcesgaccess2": { - source: "iana" - }, - "application/vnd.dvb.ipdcesgpdd": { - source: "iana" - }, - "application/vnd.dvb.ipdcroaming": { - source: "iana" - }, - "application/vnd.dvb.iptv.alfec-base": { - source: "iana" - }, - "application/vnd.dvb.iptv.alfec-enhancement": { - source: "iana" - }, - "application/vnd.dvb.notif-aggregate-root+xml": { - source: "iana", - compressible: true - }, - "application/vnd.dvb.notif-container+xml": { - source: "iana", - compressible: true - }, - "application/vnd.dvb.notif-generic+xml": { - source: "iana", - compressible: true - }, - "application/vnd.dvb.notif-ia-msglist+xml": { - source: "iana", - compressible: true - }, - "application/vnd.dvb.notif-ia-registration-request+xml": { - source: "iana", - compressible: true - }, - "application/vnd.dvb.notif-ia-registration-response+xml": { - source: "iana", - compressible: true - }, - "application/vnd.dvb.notif-init+xml": { - source: "iana", - compressible: true - }, - "application/vnd.dvb.pfr": { - source: "iana" - }, - "application/vnd.dvb.service": { - source: "iana", - extensions: ["svc"] - }, - "application/vnd.dxr": { - source: "iana" - }, - "application/vnd.dynageo": { - source: "iana", - extensions: ["geo"] - }, - "application/vnd.dzr": { - source: "iana" - }, - "application/vnd.easykaraoke.cdgdownload": { - source: "iana" - }, - "application/vnd.ecdis-update": { - source: "iana" - }, - "application/vnd.ecip.rlp": { - source: "iana" - }, - "application/vnd.eclipse.ditto+json": { - source: "iana", - compressible: true - }, - "application/vnd.ecowin.chart": { - source: "iana", - extensions: ["mag"] - }, - "application/vnd.ecowin.filerequest": { - source: "iana" - }, - "application/vnd.ecowin.fileupdate": { - source: "iana" - }, - "application/vnd.ecowin.series": { - source: "iana" - }, - "application/vnd.ecowin.seriesrequest": { - source: "iana" - }, - "application/vnd.ecowin.seriesupdate": { - source: "iana" - }, - "application/vnd.efi.img": { - source: "iana" - }, - "application/vnd.efi.iso": { - source: "iana" - }, - "application/vnd.emclient.accessrequest+xml": { - source: "iana", - compressible: true - }, - "application/vnd.enliven": { - source: "iana", - extensions: ["nml"] - }, - "application/vnd.enphase.envoy": { - source: "iana" - }, - "application/vnd.eprints.data+xml": { - source: "iana", - compressible: true - }, - "application/vnd.epson.esf": { - source: "iana", - extensions: ["esf"] - }, - "application/vnd.epson.msf": { - source: "iana", - extensions: ["msf"] - }, - "application/vnd.epson.quickanime": { - source: "iana", - extensions: ["qam"] - }, - "application/vnd.epson.salt": { - source: "iana", - extensions: ["slt"] - }, - "application/vnd.epson.ssf": { - source: "iana", - extensions: ["ssf"] - }, - "application/vnd.ericsson.quickcall": { - source: "iana" - }, - "application/vnd.espass-espass+zip": { - source: "iana", - compressible: false - }, - "application/vnd.eszigno3+xml": { - source: "iana", - compressible: true, - extensions: ["es3", "et3"] - }, - "application/vnd.etsi.aoc+xml": { - source: "iana", - compressible: true - }, - "application/vnd.etsi.asic-e+zip": { - source: "iana", - compressible: false - }, - "application/vnd.etsi.asic-s+zip": { - source: "iana", - compressible: false - }, - "application/vnd.etsi.cug+xml": { - source: "iana", - compressible: true - }, - "application/vnd.etsi.iptvcommand+xml": { - source: "iana", - compressible: true - }, - "application/vnd.etsi.iptvdiscovery+xml": { - source: "iana", - compressible: true - }, - "application/vnd.etsi.iptvprofile+xml": { - source: "iana", - compressible: true - }, - "application/vnd.etsi.iptvsad-bc+xml": { - source: "iana", - compressible: true - }, - "application/vnd.etsi.iptvsad-cod+xml": { - source: "iana", - compressible: true - }, - "application/vnd.etsi.iptvsad-npvr+xml": { - source: "iana", - compressible: true - }, - "application/vnd.etsi.iptvservice+xml": { - source: "iana", - compressible: true - }, - "application/vnd.etsi.iptvsync+xml": { - source: "iana", - compressible: true - }, - "application/vnd.etsi.iptvueprofile+xml": { - source: "iana", - compressible: true - }, - "application/vnd.etsi.mcid+xml": { - source: "iana", - compressible: true - }, - "application/vnd.etsi.mheg5": { - source: "iana" - }, - "application/vnd.etsi.overload-control-policy-dataset+xml": { - source: "iana", - compressible: true - }, - "application/vnd.etsi.pstn+xml": { - source: "iana", - compressible: true - }, - "application/vnd.etsi.sci+xml": { - source: "iana", - compressible: true - }, - "application/vnd.etsi.simservs+xml": { - source: "iana", - compressible: true - }, - "application/vnd.etsi.timestamp-token": { - source: "iana" - }, - "application/vnd.etsi.tsl+xml": { - source: "iana", - compressible: true - }, - "application/vnd.etsi.tsl.der": { - source: "iana" - }, - "application/vnd.eu.kasparian.car+json": { - source: "iana", - compressible: true - }, - "application/vnd.eudora.data": { - source: "iana" - }, - "application/vnd.evolv.ecig.profile": { - source: "iana" - }, - "application/vnd.evolv.ecig.settings": { - source: "iana" - }, - "application/vnd.evolv.ecig.theme": { - source: "iana" - }, - "application/vnd.exstream-empower+zip": { - source: "iana", - compressible: false - }, - "application/vnd.exstream-package": { - source: "iana" - }, - "application/vnd.ezpix-album": { - source: "iana", - extensions: ["ez2"] - }, - "application/vnd.ezpix-package": { - source: "iana", - extensions: ["ez3"] - }, - "application/vnd.f-secure.mobile": { - source: "iana" - }, - "application/vnd.familysearch.gedcom+zip": { - source: "iana", - compressible: false - }, - "application/vnd.fastcopy-disk-image": { - source: "iana" - }, - "application/vnd.fdf": { - source: "iana", - extensions: ["fdf"] - }, - "application/vnd.fdsn.mseed": { - source: "iana", - extensions: ["mseed"] - }, - "application/vnd.fdsn.seed": { - source: "iana", - extensions: ["seed", "dataless"] - }, - "application/vnd.ffsns": { - source: "iana" - }, - "application/vnd.ficlab.flb+zip": { - source: "iana", - compressible: false - }, - "application/vnd.filmit.zfc": { - source: "iana" - }, - "application/vnd.fints": { - source: "iana" - }, - "application/vnd.firemonkeys.cloudcell": { - source: "iana" - }, - "application/vnd.flographit": { - source: "iana", - extensions: ["gph"] - }, - "application/vnd.fluxtime.clip": { - source: "iana", - extensions: ["ftc"] - }, - "application/vnd.font-fontforge-sfd": { - source: "iana" - }, - "application/vnd.framemaker": { - source: "iana", - extensions: ["fm", "frame", "maker", "book"] - }, - "application/vnd.frogans.fnc": { - source: "iana", - extensions: ["fnc"] - }, - "application/vnd.frogans.ltf": { - source: "iana", - extensions: ["ltf"] - }, - "application/vnd.fsc.weblaunch": { - source: "iana", - extensions: ["fsc"] - }, - "application/vnd.fujifilm.fb.docuworks": { - source: "iana" - }, - "application/vnd.fujifilm.fb.docuworks.binder": { - source: "iana" - }, - "application/vnd.fujifilm.fb.docuworks.container": { - source: "iana" - }, - "application/vnd.fujifilm.fb.jfi+xml": { - source: "iana", - compressible: true - }, - "application/vnd.fujitsu.oasys": { - source: "iana", - extensions: ["oas"] - }, - "application/vnd.fujitsu.oasys2": { - source: "iana", - extensions: ["oa2"] - }, - "application/vnd.fujitsu.oasys3": { - source: "iana", - extensions: ["oa3"] - }, - "application/vnd.fujitsu.oasysgp": { - source: "iana", - extensions: ["fg5"] - }, - "application/vnd.fujitsu.oasysprs": { - source: "iana", - extensions: ["bh2"] - }, - "application/vnd.fujixerox.art-ex": { - source: "iana" - }, - "application/vnd.fujixerox.art4": { - source: "iana" - }, - "application/vnd.fujixerox.ddd": { - source: "iana", - extensions: ["ddd"] - }, - "application/vnd.fujixerox.docuworks": { - source: "iana", - extensions: ["xdw"] - }, - "application/vnd.fujixerox.docuworks.binder": { - source: "iana", - extensions: ["xbd"] - }, - "application/vnd.fujixerox.docuworks.container": { - source: "iana" - }, - "application/vnd.fujixerox.hbpl": { - source: "iana" - }, - "application/vnd.fut-misnet": { - source: "iana" - }, - "application/vnd.futoin+cbor": { - source: "iana" - }, - "application/vnd.futoin+json": { - source: "iana", - compressible: true - }, - "application/vnd.fuzzysheet": { - source: "iana", - extensions: ["fzs"] - }, - "application/vnd.genomatix.tuxedo": { - source: "iana", - extensions: ["txd"] - }, - "application/vnd.gentics.grd+json": { - source: "iana", - compressible: true - }, - "application/vnd.geo+json": { - source: "iana", - compressible: true - }, - "application/vnd.geocube+xml": { - source: "iana", - compressible: true - }, - "application/vnd.geogebra.file": { - source: "iana", - extensions: ["ggb"] - }, - "application/vnd.geogebra.slides": { - source: "iana" - }, - "application/vnd.geogebra.tool": { - source: "iana", - extensions: ["ggt"] - }, - "application/vnd.geometry-explorer": { - source: "iana", - extensions: ["gex", "gre"] - }, - "application/vnd.geonext": { - source: "iana", - extensions: ["gxt"] - }, - "application/vnd.geoplan": { - source: "iana", - extensions: ["g2w"] - }, - "application/vnd.geospace": { - source: "iana", - extensions: ["g3w"] - }, - "application/vnd.gerber": { - source: "iana" - }, - "application/vnd.globalplatform.card-content-mgt": { - source: "iana" - }, - "application/vnd.globalplatform.card-content-mgt-response": { - source: "iana" - }, - "application/vnd.gmx": { - source: "iana", - extensions: ["gmx"] - }, - "application/vnd.google-apps.document": { - compressible: false, - extensions: ["gdoc"] - }, - "application/vnd.google-apps.presentation": { - compressible: false, - extensions: ["gslides"] - }, - "application/vnd.google-apps.spreadsheet": { - compressible: false, - extensions: ["gsheet"] - }, - "application/vnd.google-earth.kml+xml": { - source: "iana", - compressible: true, - extensions: ["kml"] - }, - "application/vnd.google-earth.kmz": { - source: "iana", - compressible: false, - extensions: ["kmz"] - }, - "application/vnd.gov.sk.e-form+xml": { - source: "iana", - compressible: true - }, - "application/vnd.gov.sk.e-form+zip": { - source: "iana", - compressible: false - }, - "application/vnd.gov.sk.xmldatacontainer+xml": { - source: "iana", - compressible: true - }, - "application/vnd.grafeq": { - source: "iana", - extensions: ["gqf", "gqs"] - }, - "application/vnd.gridmp": { - source: "iana" - }, - "application/vnd.groove-account": { - source: "iana", - extensions: ["gac"] - }, - "application/vnd.groove-help": { - source: "iana", - extensions: ["ghf"] - }, - "application/vnd.groove-identity-message": { - source: "iana", - extensions: ["gim"] - }, - "application/vnd.groove-injector": { - source: "iana", - extensions: ["grv"] - }, - "application/vnd.groove-tool-message": { - source: "iana", - extensions: ["gtm"] - }, - "application/vnd.groove-tool-template": { - source: "iana", - extensions: ["tpl"] - }, - "application/vnd.groove-vcard": { - source: "iana", - extensions: ["vcg"] - }, - "application/vnd.hal+json": { - source: "iana", - compressible: true - }, - "application/vnd.hal+xml": { - source: "iana", - compressible: true, - extensions: ["hal"] - }, - "application/vnd.handheld-entertainment+xml": { - source: "iana", - compressible: true, - extensions: ["zmm"] - }, - "application/vnd.hbci": { - source: "iana", - extensions: ["hbci"] - }, - "application/vnd.hc+json": { - source: "iana", - compressible: true - }, - "application/vnd.hcl-bireports": { - source: "iana" - }, - "application/vnd.hdt": { - source: "iana" - }, - "application/vnd.heroku+json": { - source: "iana", - compressible: true - }, - "application/vnd.hhe.lesson-player": { - source: "iana", - extensions: ["les"] - }, - "application/vnd.hl7cda+xml": { - source: "iana", - charset: "UTF-8", - compressible: true - }, - "application/vnd.hl7v2+xml": { - source: "iana", - charset: "UTF-8", - compressible: true - }, - "application/vnd.hp-hpgl": { - source: "iana", - extensions: ["hpgl"] - }, - "application/vnd.hp-hpid": { - source: "iana", - extensions: ["hpid"] - }, - "application/vnd.hp-hps": { - source: "iana", - extensions: ["hps"] - }, - "application/vnd.hp-jlyt": { - source: "iana", - extensions: ["jlt"] - }, - "application/vnd.hp-pcl": { - source: "iana", - extensions: ["pcl"] - }, - "application/vnd.hp-pclxl": { - source: "iana", - extensions: ["pclxl"] - }, - "application/vnd.httphone": { - source: "iana" - }, - "application/vnd.hydrostatix.sof-data": { - source: "iana", - extensions: ["sfd-hdstx"] - }, - "application/vnd.hyper+json": { - source: "iana", - compressible: true - }, - "application/vnd.hyper-item+json": { - source: "iana", - compressible: true - }, - "application/vnd.hyperdrive+json": { - source: "iana", - compressible: true - }, - "application/vnd.hzn-3d-crossword": { - source: "iana" - }, - "application/vnd.ibm.afplinedata": { - source: "iana" - }, - "application/vnd.ibm.electronic-media": { - source: "iana" - }, - "application/vnd.ibm.minipay": { - source: "iana", - extensions: ["mpy"] - }, - "application/vnd.ibm.modcap": { - source: "iana", - extensions: ["afp", "listafp", "list3820"] - }, - "application/vnd.ibm.rights-management": { - source: "iana", - extensions: ["irm"] - }, - "application/vnd.ibm.secure-container": { - source: "iana", - extensions: ["sc"] - }, - "application/vnd.iccprofile": { - source: "iana", - extensions: ["icc", "icm"] - }, - "application/vnd.ieee.1905": { - source: "iana" - }, - "application/vnd.igloader": { - source: "iana", - extensions: ["igl"] - }, - "application/vnd.imagemeter.folder+zip": { - source: "iana", - compressible: false - }, - "application/vnd.imagemeter.image+zip": { - source: "iana", - compressible: false - }, - "application/vnd.immervision-ivp": { - source: "iana", - extensions: ["ivp"] - }, - "application/vnd.immervision-ivu": { - source: "iana", - extensions: ["ivu"] - }, - "application/vnd.ims.imsccv1p1": { - source: "iana" - }, - "application/vnd.ims.imsccv1p2": { - source: "iana" - }, - "application/vnd.ims.imsccv1p3": { - source: "iana" - }, - "application/vnd.ims.lis.v2.result+json": { - source: "iana", - compressible: true - }, - "application/vnd.ims.lti.v2.toolconsumerprofile+json": { - source: "iana", - compressible: true - }, - "application/vnd.ims.lti.v2.toolproxy+json": { - source: "iana", - compressible: true - }, - "application/vnd.ims.lti.v2.toolproxy.id+json": { - source: "iana", - compressible: true - }, - "application/vnd.ims.lti.v2.toolsettings+json": { - source: "iana", - compressible: true - }, - "application/vnd.ims.lti.v2.toolsettings.simple+json": { - source: "iana", - compressible: true - }, - "application/vnd.informedcontrol.rms+xml": { - source: "iana", - compressible: true - }, - "application/vnd.informix-visionary": { - source: "iana" - }, - "application/vnd.infotech.project": { - source: "iana" - }, - "application/vnd.infotech.project+xml": { - source: "iana", - compressible: true - }, - "application/vnd.innopath.wamp.notification": { - source: "iana" - }, - "application/vnd.insors.igm": { - source: "iana", - extensions: ["igm"] - }, - "application/vnd.intercon.formnet": { - source: "iana", - extensions: ["xpw", "xpx"] - }, - "application/vnd.intergeo": { - source: "iana", - extensions: ["i2g"] - }, - "application/vnd.intertrust.digibox": { - source: "iana" - }, - "application/vnd.intertrust.nncp": { - source: "iana" - }, - "application/vnd.intu.qbo": { - source: "iana", - extensions: ["qbo"] - }, - "application/vnd.intu.qfx": { - source: "iana", - extensions: ["qfx"] - }, - "application/vnd.iptc.g2.catalogitem+xml": { - source: "iana", - compressible: true - }, - "application/vnd.iptc.g2.conceptitem+xml": { - source: "iana", - compressible: true - }, - "application/vnd.iptc.g2.knowledgeitem+xml": { - source: "iana", - compressible: true - }, - "application/vnd.iptc.g2.newsitem+xml": { - source: "iana", - compressible: true - }, - "application/vnd.iptc.g2.newsmessage+xml": { - source: "iana", - compressible: true - }, - "application/vnd.iptc.g2.packageitem+xml": { - source: "iana", - compressible: true - }, - "application/vnd.iptc.g2.planningitem+xml": { - source: "iana", - compressible: true - }, - "application/vnd.ipunplugged.rcprofile": { - source: "iana", - extensions: ["rcprofile"] - }, - "application/vnd.irepository.package+xml": { - source: "iana", - compressible: true, - extensions: ["irp"] - }, - "application/vnd.is-xpr": { - source: "iana", - extensions: ["xpr"] - }, - "application/vnd.isac.fcs": { - source: "iana", - extensions: ["fcs"] - }, - "application/vnd.iso11783-10+zip": { - source: "iana", - compressible: false - }, - "application/vnd.jam": { - source: "iana", - extensions: ["jam"] - }, - "application/vnd.japannet-directory-service": { - source: "iana" - }, - "application/vnd.japannet-jpnstore-wakeup": { - source: "iana" - }, - "application/vnd.japannet-payment-wakeup": { - source: "iana" - }, - "application/vnd.japannet-registration": { - source: "iana" - }, - "application/vnd.japannet-registration-wakeup": { - source: "iana" - }, - "application/vnd.japannet-setstore-wakeup": { - source: "iana" - }, - "application/vnd.japannet-verification": { - source: "iana" - }, - "application/vnd.japannet-verification-wakeup": { - source: "iana" - }, - "application/vnd.jcp.javame.midlet-rms": { - source: "iana", - extensions: ["rms"] - }, - "application/vnd.jisp": { - source: "iana", - extensions: ["jisp"] - }, - "application/vnd.joost.joda-archive": { - source: "iana", - extensions: ["joda"] - }, - "application/vnd.jsk.isdn-ngn": { - source: "iana" - }, - "application/vnd.kahootz": { - source: "iana", - extensions: ["ktz", "ktr"] - }, - "application/vnd.kde.karbon": { - source: "iana", - extensions: ["karbon"] - }, - "application/vnd.kde.kchart": { - source: "iana", - extensions: ["chrt"] - }, - "application/vnd.kde.kformula": { - source: "iana", - extensions: ["kfo"] - }, - "application/vnd.kde.kivio": { - source: "iana", - extensions: ["flw"] - }, - "application/vnd.kde.kontour": { - source: "iana", - extensions: ["kon"] - }, - "application/vnd.kde.kpresenter": { - source: "iana", - extensions: ["kpr", "kpt"] - }, - "application/vnd.kde.kspread": { - source: "iana", - extensions: ["ksp"] - }, - "application/vnd.kde.kword": { - source: "iana", - extensions: ["kwd", "kwt"] - }, - "application/vnd.kenameaapp": { - source: "iana", - extensions: ["htke"] - }, - "application/vnd.kidspiration": { - source: "iana", - extensions: ["kia"] - }, - "application/vnd.kinar": { - source: "iana", - extensions: ["kne", "knp"] - }, - "application/vnd.koan": { - source: "iana", - extensions: ["skp", "skd", "skt", "skm"] - }, - "application/vnd.kodak-descriptor": { - source: "iana", - extensions: ["sse"] - }, - "application/vnd.las": { - source: "iana" - }, - "application/vnd.las.las+json": { - source: "iana", - compressible: true - }, - "application/vnd.las.las+xml": { - source: "iana", - compressible: true, - extensions: ["lasxml"] - }, - "application/vnd.laszip": { - source: "iana" - }, - "application/vnd.leap+json": { - source: "iana", - compressible: true - }, - "application/vnd.liberty-request+xml": { - source: "iana", - compressible: true - }, - "application/vnd.llamagraphics.life-balance.desktop": { - source: "iana", - extensions: ["lbd"] - }, - "application/vnd.llamagraphics.life-balance.exchange+xml": { - source: "iana", - compressible: true, - extensions: ["lbe"] - }, - "application/vnd.logipipe.circuit+zip": { - source: "iana", - compressible: false - }, - "application/vnd.loom": { - source: "iana" - }, - "application/vnd.lotus-1-2-3": { - source: "iana", - extensions: ["123"] - }, - "application/vnd.lotus-approach": { - source: "iana", - extensions: ["apr"] - }, - "application/vnd.lotus-freelance": { - source: "iana", - extensions: ["pre"] - }, - "application/vnd.lotus-notes": { - source: "iana", - extensions: ["nsf"] - }, - "application/vnd.lotus-organizer": { - source: "iana", - extensions: ["org"] - }, - "application/vnd.lotus-screencam": { - source: "iana", - extensions: ["scm"] - }, - "application/vnd.lotus-wordpro": { - source: "iana", - extensions: ["lwp"] - }, - "application/vnd.macports.portpkg": { - source: "iana", - extensions: ["portpkg"] - }, - "application/vnd.mapbox-vector-tile": { - source: "iana", - extensions: ["mvt"] - }, - "application/vnd.marlin.drm.actiontoken+xml": { - source: "iana", - compressible: true - }, - "application/vnd.marlin.drm.conftoken+xml": { - source: "iana", - compressible: true - }, - "application/vnd.marlin.drm.license+xml": { - source: "iana", - compressible: true - }, - "application/vnd.marlin.drm.mdcf": { - source: "iana" - }, - "application/vnd.mason+json": { - source: "iana", - compressible: true - }, - "application/vnd.maxar.archive.3tz+zip": { - source: "iana", - compressible: false - }, - "application/vnd.maxmind.maxmind-db": { - source: "iana" - }, - "application/vnd.mcd": { - source: "iana", - extensions: ["mcd"] - }, - "application/vnd.medcalcdata": { - source: "iana", - extensions: ["mc1"] - }, - "application/vnd.mediastation.cdkey": { - source: "iana", - extensions: ["cdkey"] - }, - "application/vnd.meridian-slingshot": { - source: "iana" - }, - "application/vnd.mfer": { - source: "iana", - extensions: ["mwf"] - }, - "application/vnd.mfmp": { - source: "iana", - extensions: ["mfm"] - }, - "application/vnd.micro+json": { - source: "iana", - compressible: true - }, - "application/vnd.micrografx.flo": { - source: "iana", - extensions: ["flo"] - }, - "application/vnd.micrografx.igx": { - source: "iana", - extensions: ["igx"] - }, - "application/vnd.microsoft.portable-executable": { - source: "iana" - }, - "application/vnd.microsoft.windows.thumbnail-cache": { - source: "iana" - }, - "application/vnd.miele+json": { - source: "iana", - compressible: true - }, - "application/vnd.mif": { - source: "iana", - extensions: ["mif"] - }, - "application/vnd.minisoft-hp3000-save": { - source: "iana" - }, - "application/vnd.mitsubishi.misty-guard.trustweb": { - source: "iana" - }, - "application/vnd.mobius.daf": { - source: "iana", - extensions: ["daf"] - }, - "application/vnd.mobius.dis": { - source: "iana", - extensions: ["dis"] - }, - "application/vnd.mobius.mbk": { - source: "iana", - extensions: ["mbk"] - }, - "application/vnd.mobius.mqy": { - source: "iana", - extensions: ["mqy"] - }, - "application/vnd.mobius.msl": { - source: "iana", - extensions: ["msl"] - }, - "application/vnd.mobius.plc": { - source: "iana", - extensions: ["plc"] - }, - "application/vnd.mobius.txf": { - source: "iana", - extensions: ["txf"] - }, - "application/vnd.mophun.application": { - source: "iana", - extensions: ["mpn"] - }, - "application/vnd.mophun.certificate": { - source: "iana", - extensions: ["mpc"] - }, - "application/vnd.motorola.flexsuite": { - source: "iana" - }, - "application/vnd.motorola.flexsuite.adsi": { - source: "iana" - }, - "application/vnd.motorola.flexsuite.fis": { - source: "iana" - }, - "application/vnd.motorola.flexsuite.gotap": { - source: "iana" - }, - "application/vnd.motorola.flexsuite.kmr": { - source: "iana" - }, - "application/vnd.motorola.flexsuite.ttc": { - source: "iana" - }, - "application/vnd.motorola.flexsuite.wem": { - source: "iana" - }, - "application/vnd.motorola.iprm": { - source: "iana" - }, - "application/vnd.mozilla.xul+xml": { - source: "iana", - compressible: true, - extensions: ["xul"] - }, - "application/vnd.ms-3mfdocument": { - source: "iana" - }, - "application/vnd.ms-artgalry": { - source: "iana", - extensions: ["cil"] - }, - "application/vnd.ms-asf": { - source: "iana" - }, - "application/vnd.ms-cab-compressed": { - source: "iana", - extensions: ["cab"] - }, - "application/vnd.ms-color.iccprofile": { - source: "apache" - }, - "application/vnd.ms-excel": { - source: "iana", - compressible: false, - extensions: ["xls", "xlm", "xla", "xlc", "xlt", "xlw"] - }, - "application/vnd.ms-excel.addin.macroenabled.12": { - source: "iana", - extensions: ["xlam"] - }, - "application/vnd.ms-excel.sheet.binary.macroenabled.12": { - source: "iana", - extensions: ["xlsb"] - }, - "application/vnd.ms-excel.sheet.macroenabled.12": { - source: "iana", - extensions: ["xlsm"] - }, - "application/vnd.ms-excel.template.macroenabled.12": { - source: "iana", - extensions: ["xltm"] - }, - "application/vnd.ms-fontobject": { - source: "iana", - compressible: true, - extensions: ["eot"] - }, - "application/vnd.ms-htmlhelp": { - source: "iana", - extensions: ["chm"] - }, - "application/vnd.ms-ims": { - source: "iana", - extensions: ["ims"] - }, - "application/vnd.ms-lrm": { - source: "iana", - extensions: ["lrm"] - }, - "application/vnd.ms-office.activex+xml": { - source: "iana", - compressible: true - }, - "application/vnd.ms-officetheme": { - source: "iana", - extensions: ["thmx"] - }, - "application/vnd.ms-opentype": { - source: "apache", - compressible: true - }, - "application/vnd.ms-outlook": { - compressible: false, - extensions: ["msg"] - }, - "application/vnd.ms-package.obfuscated-opentype": { - source: "apache" - }, - "application/vnd.ms-pki.seccat": { - source: "apache", - extensions: ["cat"] - }, - "application/vnd.ms-pki.stl": { - source: "apache", - extensions: ["stl"] - }, - "application/vnd.ms-playready.initiator+xml": { - source: "iana", - compressible: true - }, - "application/vnd.ms-powerpoint": { - source: "iana", - compressible: false, - extensions: ["ppt", "pps", "pot"] - }, - "application/vnd.ms-powerpoint.addin.macroenabled.12": { - source: "iana", - extensions: ["ppam"] - }, - "application/vnd.ms-powerpoint.presentation.macroenabled.12": { - source: "iana", - extensions: ["pptm"] - }, - "application/vnd.ms-powerpoint.slide.macroenabled.12": { - source: "iana", - extensions: ["sldm"] - }, - "application/vnd.ms-powerpoint.slideshow.macroenabled.12": { - source: "iana", - extensions: ["ppsm"] - }, - "application/vnd.ms-powerpoint.template.macroenabled.12": { - source: "iana", - extensions: ["potm"] - }, - "application/vnd.ms-printdevicecapabilities+xml": { - source: "iana", - compressible: true - }, - "application/vnd.ms-printing.printticket+xml": { - source: "apache", - compressible: true - }, - "application/vnd.ms-printschematicket+xml": { - source: "iana", - compressible: true - }, - "application/vnd.ms-project": { - source: "iana", - extensions: ["mpp", "mpt"] - }, - "application/vnd.ms-tnef": { - source: "iana" - }, - "application/vnd.ms-windows.devicepairing": { - source: "iana" - }, - "application/vnd.ms-windows.nwprinting.oob": { - source: "iana" - }, - "application/vnd.ms-windows.printerpairing": { - source: "iana" - }, - "application/vnd.ms-windows.wsd.oob": { - source: "iana" - }, - "application/vnd.ms-wmdrm.lic-chlg-req": { - source: "iana" - }, - "application/vnd.ms-wmdrm.lic-resp": { - source: "iana" - }, - "application/vnd.ms-wmdrm.meter-chlg-req": { - source: "iana" - }, - "application/vnd.ms-wmdrm.meter-resp": { - source: "iana" - }, - "application/vnd.ms-word.document.macroenabled.12": { - source: "iana", - extensions: ["docm"] - }, - "application/vnd.ms-word.template.macroenabled.12": { - source: "iana", - extensions: ["dotm"] - }, - "application/vnd.ms-works": { - source: "iana", - extensions: ["wps", "wks", "wcm", "wdb"] - }, - "application/vnd.ms-wpl": { - source: "iana", - extensions: ["wpl"] - }, - "application/vnd.ms-xpsdocument": { - source: "iana", - compressible: false, - extensions: ["xps"] - }, - "application/vnd.msa-disk-image": { - source: "iana" - }, - "application/vnd.mseq": { - source: "iana", - extensions: ["mseq"] - }, - "application/vnd.msign": { - source: "iana" - }, - "application/vnd.multiad.creator": { - source: "iana" - }, - "application/vnd.multiad.creator.cif": { - source: "iana" - }, - "application/vnd.music-niff": { - source: "iana" - }, - "application/vnd.musician": { - source: "iana", - extensions: ["mus"] - }, - "application/vnd.muvee.style": { - source: "iana", - extensions: ["msty"] - }, - "application/vnd.mynfc": { - source: "iana", - extensions: ["taglet"] - }, - "application/vnd.nacamar.ybrid+json": { - source: "iana", - compressible: true - }, - "application/vnd.ncd.control": { - source: "iana" - }, - "application/vnd.ncd.reference": { - source: "iana" - }, - "application/vnd.nearst.inv+json": { - source: "iana", - compressible: true - }, - "application/vnd.nebumind.line": { - source: "iana" - }, - "application/vnd.nervana": { - source: "iana" - }, - "application/vnd.netfpx": { - source: "iana" - }, - "application/vnd.neurolanguage.nlu": { - source: "iana", - extensions: ["nlu"] - }, - "application/vnd.nimn": { - source: "iana" - }, - "application/vnd.nintendo.nitro.rom": { - source: "iana" - }, - "application/vnd.nintendo.snes.rom": { - source: "iana" - }, - "application/vnd.nitf": { - source: "iana", - extensions: ["ntf", "nitf"] - }, - "application/vnd.noblenet-directory": { - source: "iana", - extensions: ["nnd"] - }, - "application/vnd.noblenet-sealer": { - source: "iana", - extensions: ["nns"] - }, - "application/vnd.noblenet-web": { - source: "iana", - extensions: ["nnw"] - }, - "application/vnd.nokia.catalogs": { - source: "iana" - }, - "application/vnd.nokia.conml+wbxml": { - source: "iana" - }, - "application/vnd.nokia.conml+xml": { - source: "iana", - compressible: true - }, - "application/vnd.nokia.iptv.config+xml": { - source: "iana", - compressible: true - }, - "application/vnd.nokia.isds-radio-presets": { - source: "iana" - }, - "application/vnd.nokia.landmark+wbxml": { - source: "iana" - }, - "application/vnd.nokia.landmark+xml": { - source: "iana", - compressible: true - }, - "application/vnd.nokia.landmarkcollection+xml": { - source: "iana", - compressible: true - }, - "application/vnd.nokia.n-gage.ac+xml": { - source: "iana", - compressible: true, - extensions: ["ac"] - }, - "application/vnd.nokia.n-gage.data": { - source: "iana", - extensions: ["ngdat"] - }, - "application/vnd.nokia.n-gage.symbian.install": { - source: "iana", - extensions: ["n-gage"] - }, - "application/vnd.nokia.ncd": { - source: "iana" - }, - "application/vnd.nokia.pcd+wbxml": { - source: "iana" - }, - "application/vnd.nokia.pcd+xml": { - source: "iana", - compressible: true - }, - "application/vnd.nokia.radio-preset": { - source: "iana", - extensions: ["rpst"] - }, - "application/vnd.nokia.radio-presets": { - source: "iana", - extensions: ["rpss"] - }, - "application/vnd.novadigm.edm": { - source: "iana", - extensions: ["edm"] - }, - "application/vnd.novadigm.edx": { - source: "iana", - extensions: ["edx"] - }, - "application/vnd.novadigm.ext": { - source: "iana", - extensions: ["ext"] - }, - "application/vnd.ntt-local.content-share": { - source: "iana" - }, - "application/vnd.ntt-local.file-transfer": { - source: "iana" - }, - "application/vnd.ntt-local.ogw_remote-access": { - source: "iana" - }, - "application/vnd.ntt-local.sip-ta_remote": { - source: "iana" - }, - "application/vnd.ntt-local.sip-ta_tcp_stream": { - source: "iana" - }, - "application/vnd.oasis.opendocument.chart": { - source: "iana", - extensions: ["odc"] - }, - "application/vnd.oasis.opendocument.chart-template": { - source: "iana", - extensions: ["otc"] - }, - "application/vnd.oasis.opendocument.database": { - source: "iana", - extensions: ["odb"] - }, - "application/vnd.oasis.opendocument.formula": { - source: "iana", - extensions: ["odf"] - }, - "application/vnd.oasis.opendocument.formula-template": { - source: "iana", - extensions: ["odft"] - }, - "application/vnd.oasis.opendocument.graphics": { - source: "iana", - compressible: false, - extensions: ["odg"] - }, - "application/vnd.oasis.opendocument.graphics-template": { - source: "iana", - extensions: ["otg"] - }, - "application/vnd.oasis.opendocument.image": { - source: "iana", - extensions: ["odi"] - }, - "application/vnd.oasis.opendocument.image-template": { - source: "iana", - extensions: ["oti"] - }, - "application/vnd.oasis.opendocument.presentation": { - source: "iana", - compressible: false, - extensions: ["odp"] - }, - "application/vnd.oasis.opendocument.presentation-template": { - source: "iana", - extensions: ["otp"] - }, - "application/vnd.oasis.opendocument.spreadsheet": { - source: "iana", - compressible: false, - extensions: ["ods"] - }, - "application/vnd.oasis.opendocument.spreadsheet-template": { - source: "iana", - extensions: ["ots"] - }, - "application/vnd.oasis.opendocument.text": { - source: "iana", - compressible: false, - extensions: ["odt"] - }, - "application/vnd.oasis.opendocument.text-master": { - source: "iana", - extensions: ["odm"] - }, - "application/vnd.oasis.opendocument.text-template": { - source: "iana", - extensions: ["ott"] - }, - "application/vnd.oasis.opendocument.text-web": { - source: "iana", - extensions: ["oth"] - }, - "application/vnd.obn": { - source: "iana" - }, - "application/vnd.ocf+cbor": { - source: "iana" - }, - "application/vnd.oci.image.manifest.v1+json": { - source: "iana", - compressible: true - }, - "application/vnd.oftn.l10n+json": { - source: "iana", - compressible: true - }, - "application/vnd.oipf.contentaccessdownload+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oipf.contentaccessstreaming+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oipf.cspg-hexbinary": { - source: "iana" - }, - "application/vnd.oipf.dae.svg+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oipf.dae.xhtml+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oipf.mippvcontrolmessage+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oipf.pae.gem": { - source: "iana" - }, - "application/vnd.oipf.spdiscovery+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oipf.spdlist+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oipf.ueprofile+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oipf.userprofile+xml": { - source: "iana", - compressible: true - }, - "application/vnd.olpc-sugar": { - source: "iana", - extensions: ["xo"] - }, - "application/vnd.oma-scws-config": { - source: "iana" - }, - "application/vnd.oma-scws-http-request": { - source: "iana" - }, - "application/vnd.oma-scws-http-response": { - source: "iana" - }, - "application/vnd.oma.bcast.associated-procedure-parameter+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oma.bcast.drm-trigger+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oma.bcast.imd+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oma.bcast.ltkm": { - source: "iana" - }, - "application/vnd.oma.bcast.notification+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oma.bcast.provisioningtrigger": { - source: "iana" - }, - "application/vnd.oma.bcast.sgboot": { - source: "iana" - }, - "application/vnd.oma.bcast.sgdd+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oma.bcast.sgdu": { - source: "iana" - }, - "application/vnd.oma.bcast.simple-symbol-container": { - source: "iana" - }, - "application/vnd.oma.bcast.smartcard-trigger+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oma.bcast.sprov+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oma.bcast.stkm": { - source: "iana" - }, - "application/vnd.oma.cab-address-book+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oma.cab-feature-handler+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oma.cab-pcc+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oma.cab-subs-invite+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oma.cab-user-prefs+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oma.dcd": { - source: "iana" - }, - "application/vnd.oma.dcdc": { - source: "iana" - }, - "application/vnd.oma.dd2+xml": { - source: "iana", - compressible: true, - extensions: ["dd2"] - }, - "application/vnd.oma.drm.risd+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oma.group-usage-list+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oma.lwm2m+cbor": { - source: "iana" - }, - "application/vnd.oma.lwm2m+json": { - source: "iana", - compressible: true - }, - "application/vnd.oma.lwm2m+tlv": { - source: "iana" - }, - "application/vnd.oma.pal+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oma.poc.detailed-progress-report+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oma.poc.final-report+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oma.poc.groups+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oma.poc.invocation-descriptor+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oma.poc.optimized-progress-report+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oma.push": { - source: "iana" - }, - "application/vnd.oma.scidm.messages+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oma.xcap-directory+xml": { - source: "iana", - compressible: true - }, - "application/vnd.omads-email+xml": { - source: "iana", - charset: "UTF-8", - compressible: true - }, - "application/vnd.omads-file+xml": { - source: "iana", - charset: "UTF-8", - compressible: true - }, - "application/vnd.omads-folder+xml": { - source: "iana", - charset: "UTF-8", - compressible: true - }, - "application/vnd.omaloc-supl-init": { - source: "iana" - }, - "application/vnd.onepager": { - source: "iana" - }, - "application/vnd.onepagertamp": { - source: "iana" - }, - "application/vnd.onepagertamx": { - source: "iana" - }, - "application/vnd.onepagertat": { - source: "iana" - }, - "application/vnd.onepagertatp": { - source: "iana" - }, - "application/vnd.onepagertatx": { - source: "iana" - }, - "application/vnd.openblox.game+xml": { - source: "iana", - compressible: true, - extensions: ["obgx"] - }, - "application/vnd.openblox.game-binary": { - source: "iana" - }, - "application/vnd.openeye.oeb": { - source: "iana" - }, - "application/vnd.openofficeorg.extension": { - source: "apache", - extensions: ["oxt"] - }, - "application/vnd.openstreetmap.data+xml": { - source: "iana", - compressible: true, - extensions: ["osm"] - }, - "application/vnd.opentimestamps.ots": { - source: "iana" - }, - "application/vnd.openxmlformats-officedocument.custom-properties+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.customxmlproperties+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.drawing+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.drawingml.chart+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.drawingml.diagramcolors+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.drawingml.diagramdata+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.drawingml.diagramlayout+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.drawingml.diagramstyle+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.extended-properties+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.presentationml.commentauthors+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.presentationml.comments+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.presentationml.handoutmaster+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.presentationml.notesmaster+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.presentationml.notesslide+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.presentationml.presentation": { - source: "iana", - compressible: false, - extensions: ["pptx"] - }, - "application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.presentationml.presprops+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.presentationml.slide": { - source: "iana", - extensions: ["sldx"] - }, - "application/vnd.openxmlformats-officedocument.presentationml.slide+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.presentationml.slidelayout+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.presentationml.slidemaster+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.presentationml.slideshow": { - source: "iana", - extensions: ["ppsx"] - }, - "application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.presentationml.slideupdateinfo+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.presentationml.tablestyles+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.presentationml.tags+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.presentationml.template": { - source: "iana", - extensions: ["potx"] - }, - "application/vnd.openxmlformats-officedocument.presentationml.template.main+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.presentationml.viewprops+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.calcchain+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.externallink+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcachedefinition+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcacherecords+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.pivottable+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.querytable+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionheaders+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionlog+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedstrings+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": { - source: "iana", - compressible: false, - extensions: ["xlsx"] - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.sheetmetadata+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.tablesinglecells+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.template": { - source: "iana", - extensions: ["xltx"] - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.usernames+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.volatiledependencies+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.theme+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.themeoverride+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.vmldrawing": { - source: "iana" - }, - "application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.wordprocessingml.document": { - source: "iana", - compressible: false, - extensions: ["docx"] - }, - "application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.wordprocessingml.fonttable+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.wordprocessingml.template": { - source: "iana", - extensions: ["dotx"] - }, - "application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-officedocument.wordprocessingml.websettings+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-package.core-properties+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml": { - source: "iana", - compressible: true - }, - "application/vnd.openxmlformats-package.relationships+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oracle.resource+json": { - source: "iana", - compressible: true - }, - "application/vnd.orange.indata": { - source: "iana" - }, - "application/vnd.osa.netdeploy": { - source: "iana" - }, - "application/vnd.osgeo.mapguide.package": { - source: "iana", - extensions: ["mgp"] - }, - "application/vnd.osgi.bundle": { - source: "iana" - }, - "application/vnd.osgi.dp": { - source: "iana", - extensions: ["dp"] - }, - "application/vnd.osgi.subsystem": { - source: "iana", - extensions: ["esa"] - }, - "application/vnd.otps.ct-kip+xml": { - source: "iana", - compressible: true - }, - "application/vnd.oxli.countgraph": { - source: "iana" - }, - "application/vnd.pagerduty+json": { - source: "iana", - compressible: true - }, - "application/vnd.palm": { - source: "iana", - extensions: ["pdb", "pqa", "oprc"] - }, - "application/vnd.panoply": { - source: "iana" - }, - "application/vnd.paos.xml": { - source: "iana" - }, - "application/vnd.patentdive": { - source: "iana" - }, - "application/vnd.patientecommsdoc": { - source: "iana" - }, - "application/vnd.pawaafile": { - source: "iana", - extensions: ["paw"] - }, - "application/vnd.pcos": { - source: "iana" - }, - "application/vnd.pg.format": { - source: "iana", - extensions: ["str"] - }, - "application/vnd.pg.osasli": { - source: "iana", - extensions: ["ei6"] - }, - "application/vnd.piaccess.application-licence": { - source: "iana" - }, - "application/vnd.picsel": { - source: "iana", - extensions: ["efif"] - }, - "application/vnd.pmi.widget": { - source: "iana", - extensions: ["wg"] - }, - "application/vnd.poc.group-advertisement+xml": { - source: "iana", - compressible: true - }, - "application/vnd.pocketlearn": { - source: "iana", - extensions: ["plf"] - }, - "application/vnd.powerbuilder6": { - source: "iana", - extensions: ["pbd"] - }, - "application/vnd.powerbuilder6-s": { - source: "iana" - }, - "application/vnd.powerbuilder7": { - source: "iana" - }, - "application/vnd.powerbuilder7-s": { - source: "iana" - }, - "application/vnd.powerbuilder75": { - source: "iana" - }, - "application/vnd.powerbuilder75-s": { - source: "iana" - }, - "application/vnd.preminet": { - source: "iana" - }, - "application/vnd.previewsystems.box": { - source: "iana", - extensions: ["box"] - }, - "application/vnd.proteus.magazine": { - source: "iana", - extensions: ["mgz"] - }, - "application/vnd.psfs": { - source: "iana" - }, - "application/vnd.publishare-delta-tree": { - source: "iana", - extensions: ["qps"] - }, - "application/vnd.pvi.ptid1": { - source: "iana", - extensions: ["ptid"] - }, - "application/vnd.pwg-multiplexed": { - source: "iana" - }, - "application/vnd.pwg-xhtml-print+xml": { - source: "iana", - compressible: true - }, - "application/vnd.qualcomm.brew-app-res": { - source: "iana" - }, - "application/vnd.quarantainenet": { - source: "iana" - }, - "application/vnd.quark.quarkxpress": { - source: "iana", - extensions: ["qxd", "qxt", "qwd", "qwt", "qxl", "qxb"] - }, - "application/vnd.quobject-quoxdocument": { - source: "iana" - }, - "application/vnd.radisys.moml+xml": { - source: "iana", - compressible: true - }, - "application/vnd.radisys.msml+xml": { - source: "iana", - compressible: true - }, - "application/vnd.radisys.msml-audit+xml": { - source: "iana", - compressible: true - }, - "application/vnd.radisys.msml-audit-conf+xml": { - source: "iana", - compressible: true - }, - "application/vnd.radisys.msml-audit-conn+xml": { - source: "iana", - compressible: true - }, - "application/vnd.radisys.msml-audit-dialog+xml": { - source: "iana", - compressible: true - }, - "application/vnd.radisys.msml-audit-stream+xml": { - source: "iana", - compressible: true - }, - "application/vnd.radisys.msml-conf+xml": { - source: "iana", - compressible: true - }, - "application/vnd.radisys.msml-dialog+xml": { - source: "iana", - compressible: true - }, - "application/vnd.radisys.msml-dialog-base+xml": { - source: "iana", - compressible: true - }, - "application/vnd.radisys.msml-dialog-fax-detect+xml": { - source: "iana", - compressible: true - }, - "application/vnd.radisys.msml-dialog-fax-sendrecv+xml": { - source: "iana", - compressible: true - }, - "application/vnd.radisys.msml-dialog-group+xml": { - source: "iana", - compressible: true - }, - "application/vnd.radisys.msml-dialog-speech+xml": { - source: "iana", - compressible: true - }, - "application/vnd.radisys.msml-dialog-transform+xml": { - source: "iana", - compressible: true - }, - "application/vnd.rainstor.data": { - source: "iana" - }, - "application/vnd.rapid": { - source: "iana" - }, - "application/vnd.rar": { - source: "iana", - extensions: ["rar"] - }, - "application/vnd.realvnc.bed": { - source: "iana", - extensions: ["bed"] - }, - "application/vnd.recordare.musicxml": { - source: "iana", - extensions: ["mxl"] - }, - "application/vnd.recordare.musicxml+xml": { - source: "iana", - compressible: true, - extensions: ["musicxml"] - }, - "application/vnd.renlearn.rlprint": { - source: "iana" - }, - "application/vnd.resilient.logic": { - source: "iana" - }, - "application/vnd.restful+json": { - source: "iana", - compressible: true - }, - "application/vnd.rig.cryptonote": { - source: "iana", - extensions: ["cryptonote"] - }, - "application/vnd.rim.cod": { - source: "apache", - extensions: ["cod"] - }, - "application/vnd.rn-realmedia": { - source: "apache", - extensions: ["rm"] - }, - "application/vnd.rn-realmedia-vbr": { - source: "apache", - extensions: ["rmvb"] - }, - "application/vnd.route66.link66+xml": { - source: "iana", - compressible: true, - extensions: ["link66"] - }, - "application/vnd.rs-274x": { - source: "iana" - }, - "application/vnd.ruckus.download": { - source: "iana" - }, - "application/vnd.s3sms": { - source: "iana" - }, - "application/vnd.sailingtracker.track": { - source: "iana", - extensions: ["st"] - }, - "application/vnd.sar": { - source: "iana" - }, - "application/vnd.sbm.cid": { - source: "iana" - }, - "application/vnd.sbm.mid2": { - source: "iana" - }, - "application/vnd.scribus": { - source: "iana" - }, - "application/vnd.sealed.3df": { - source: "iana" - }, - "application/vnd.sealed.csf": { - source: "iana" - }, - "application/vnd.sealed.doc": { - source: "iana" - }, - "application/vnd.sealed.eml": { - source: "iana" - }, - "application/vnd.sealed.mht": { - source: "iana" - }, - "application/vnd.sealed.net": { - source: "iana" - }, - "application/vnd.sealed.ppt": { - source: "iana" - }, - "application/vnd.sealed.tiff": { - source: "iana" - }, - "application/vnd.sealed.xls": { - source: "iana" - }, - "application/vnd.sealedmedia.softseal.html": { - source: "iana" - }, - "application/vnd.sealedmedia.softseal.pdf": { - source: "iana" - }, - "application/vnd.seemail": { - source: "iana", - extensions: ["see"] - }, - "application/vnd.seis+json": { - source: "iana", - compressible: true - }, - "application/vnd.sema": { - source: "iana", - extensions: ["sema"] - }, - "application/vnd.semd": { - source: "iana", - extensions: ["semd"] - }, - "application/vnd.semf": { - source: "iana", - extensions: ["semf"] - }, - "application/vnd.shade-save-file": { - source: "iana" - }, - "application/vnd.shana.informed.formdata": { - source: "iana", - extensions: ["ifm"] - }, - "application/vnd.shana.informed.formtemplate": { - source: "iana", - extensions: ["itp"] - }, - "application/vnd.shana.informed.interchange": { - source: "iana", - extensions: ["iif"] - }, - "application/vnd.shana.informed.package": { - source: "iana", - extensions: ["ipk"] - }, - "application/vnd.shootproof+json": { - source: "iana", - compressible: true - }, - "application/vnd.shopkick+json": { - source: "iana", - compressible: true - }, - "application/vnd.shp": { - source: "iana" - }, - "application/vnd.shx": { - source: "iana" - }, - "application/vnd.sigrok.session": { - source: "iana" - }, - "application/vnd.simtech-mindmapper": { - source: "iana", - extensions: ["twd", "twds"] - }, - "application/vnd.siren+json": { - source: "iana", - compressible: true - }, - "application/vnd.smaf": { - source: "iana", - extensions: ["mmf"] - }, - "application/vnd.smart.notebook": { - source: "iana" - }, - "application/vnd.smart.teacher": { - source: "iana", - extensions: ["teacher"] - }, - "application/vnd.snesdev-page-table": { - source: "iana" - }, - "application/vnd.software602.filler.form+xml": { - source: "iana", - compressible: true, - extensions: ["fo"] - }, - "application/vnd.software602.filler.form-xml-zip": { - source: "iana" - }, - "application/vnd.solent.sdkm+xml": { - source: "iana", - compressible: true, - extensions: ["sdkm", "sdkd"] - }, - "application/vnd.spotfire.dxp": { - source: "iana", - extensions: ["dxp"] - }, - "application/vnd.spotfire.sfs": { - source: "iana", - extensions: ["sfs"] - }, - "application/vnd.sqlite3": { - source: "iana" - }, - "application/vnd.sss-cod": { - source: "iana" - }, - "application/vnd.sss-dtf": { - source: "iana" - }, - "application/vnd.sss-ntf": { - source: "iana" - }, - "application/vnd.stardivision.calc": { - source: "apache", - extensions: ["sdc"] - }, - "application/vnd.stardivision.draw": { - source: "apache", - extensions: ["sda"] - }, - "application/vnd.stardivision.impress": { - source: "apache", - extensions: ["sdd"] - }, - "application/vnd.stardivision.math": { - source: "apache", - extensions: ["smf"] - }, - "application/vnd.stardivision.writer": { - source: "apache", - extensions: ["sdw", "vor"] - }, - "application/vnd.stardivision.writer-global": { - source: "apache", - extensions: ["sgl"] - }, - "application/vnd.stepmania.package": { - source: "iana", - extensions: ["smzip"] - }, - "application/vnd.stepmania.stepchart": { - source: "iana", - extensions: ["sm"] - }, - "application/vnd.street-stream": { - source: "iana" - }, - "application/vnd.sun.wadl+xml": { - source: "iana", - compressible: true, - extensions: ["wadl"] - }, - "application/vnd.sun.xml.calc": { - source: "apache", - extensions: ["sxc"] - }, - "application/vnd.sun.xml.calc.template": { - source: "apache", - extensions: ["stc"] - }, - "application/vnd.sun.xml.draw": { - source: "apache", - extensions: ["sxd"] - }, - "application/vnd.sun.xml.draw.template": { - source: "apache", - extensions: ["std"] - }, - "application/vnd.sun.xml.impress": { - source: "apache", - extensions: ["sxi"] - }, - "application/vnd.sun.xml.impress.template": { - source: "apache", - extensions: ["sti"] - }, - "application/vnd.sun.xml.math": { - source: "apache", - extensions: ["sxm"] - }, - "application/vnd.sun.xml.writer": { - source: "apache", - extensions: ["sxw"] - }, - "application/vnd.sun.xml.writer.global": { - source: "apache", - extensions: ["sxg"] - }, - "application/vnd.sun.xml.writer.template": { - source: "apache", - extensions: ["stw"] - }, - "application/vnd.sus-calendar": { - source: "iana", - extensions: ["sus", "susp"] - }, - "application/vnd.svd": { - source: "iana", - extensions: ["svd"] - }, - "application/vnd.swiftview-ics": { - source: "iana" - }, - "application/vnd.sycle+xml": { - source: "iana", - compressible: true - }, - "application/vnd.syft+json": { - source: "iana", - compressible: true - }, - "application/vnd.symbian.install": { - source: "apache", - extensions: ["sis", "sisx"] - }, - "application/vnd.syncml+xml": { - source: "iana", - charset: "UTF-8", - compressible: true, - extensions: ["xsm"] - }, - "application/vnd.syncml.dm+wbxml": { - source: "iana", - charset: "UTF-8", - extensions: ["bdm"] - }, - "application/vnd.syncml.dm+xml": { - source: "iana", - charset: "UTF-8", - compressible: true, - extensions: ["xdm"] - }, - "application/vnd.syncml.dm.notification": { - source: "iana" - }, - "application/vnd.syncml.dmddf+wbxml": { - source: "iana" - }, - "application/vnd.syncml.dmddf+xml": { - source: "iana", - charset: "UTF-8", - compressible: true, - extensions: ["ddf"] - }, - "application/vnd.syncml.dmtnds+wbxml": { - source: "iana" - }, - "application/vnd.syncml.dmtnds+xml": { - source: "iana", - charset: "UTF-8", - compressible: true - }, - "application/vnd.syncml.ds.notification": { - source: "iana" - }, - "application/vnd.tableschema+json": { - source: "iana", - compressible: true - }, - "application/vnd.tao.intent-module-archive": { - source: "iana", - extensions: ["tao"] - }, - "application/vnd.tcpdump.pcap": { - source: "iana", - extensions: ["pcap", "cap", "dmp"] - }, - "application/vnd.think-cell.ppttc+json": { - source: "iana", - compressible: true - }, - "application/vnd.tmd.mediaflex.api+xml": { - source: "iana", - compressible: true - }, - "application/vnd.tml": { - source: "iana" - }, - "application/vnd.tmobile-livetv": { - source: "iana", - extensions: ["tmo"] - }, - "application/vnd.tri.onesource": { - source: "iana" - }, - "application/vnd.trid.tpt": { - source: "iana", - extensions: ["tpt"] - }, - "application/vnd.triscape.mxs": { - source: "iana", - extensions: ["mxs"] - }, - "application/vnd.trueapp": { - source: "iana", - extensions: ["tra"] - }, - "application/vnd.truedoc": { - source: "iana" - }, - "application/vnd.ubisoft.webplayer": { - source: "iana" - }, - "application/vnd.ufdl": { - source: "iana", - extensions: ["ufd", "ufdl"] - }, - "application/vnd.uiq.theme": { - source: "iana", - extensions: ["utz"] - }, - "application/vnd.umajin": { - source: "iana", - extensions: ["umj"] - }, - "application/vnd.unity": { - source: "iana", - extensions: ["unityweb"] - }, - "application/vnd.uoml+xml": { - source: "iana", - compressible: true, - extensions: ["uoml"] - }, - "application/vnd.uplanet.alert": { - source: "iana" - }, - "application/vnd.uplanet.alert-wbxml": { - source: "iana" - }, - "application/vnd.uplanet.bearer-choice": { - source: "iana" - }, - "application/vnd.uplanet.bearer-choice-wbxml": { - source: "iana" - }, - "application/vnd.uplanet.cacheop": { - source: "iana" - }, - "application/vnd.uplanet.cacheop-wbxml": { - source: "iana" - }, - "application/vnd.uplanet.channel": { - source: "iana" - }, - "application/vnd.uplanet.channel-wbxml": { - source: "iana" - }, - "application/vnd.uplanet.list": { - source: "iana" - }, - "application/vnd.uplanet.list-wbxml": { - source: "iana" - }, - "application/vnd.uplanet.listcmd": { - source: "iana" - }, - "application/vnd.uplanet.listcmd-wbxml": { - source: "iana" - }, - "application/vnd.uplanet.signal": { - source: "iana" - }, - "application/vnd.uri-map": { - source: "iana" - }, - "application/vnd.valve.source.material": { - source: "iana" - }, - "application/vnd.vcx": { - source: "iana", - extensions: ["vcx"] - }, - "application/vnd.vd-study": { - source: "iana" - }, - "application/vnd.vectorworks": { - source: "iana" - }, - "application/vnd.vel+json": { - source: "iana", - compressible: true - }, - "application/vnd.verimatrix.vcas": { - source: "iana" - }, - "application/vnd.veritone.aion+json": { - source: "iana", - compressible: true - }, - "application/vnd.veryant.thin": { - source: "iana" - }, - "application/vnd.ves.encrypted": { - source: "iana" - }, - "application/vnd.vidsoft.vidconference": { - source: "iana" - }, - "application/vnd.visio": { - source: "iana", - extensions: ["vsd", "vst", "vss", "vsw"] - }, - "application/vnd.visionary": { - source: "iana", - extensions: ["vis"] - }, - "application/vnd.vividence.scriptfile": { - source: "iana" - }, - "application/vnd.vsf": { - source: "iana", - extensions: ["vsf"] - }, - "application/vnd.wap.sic": { - source: "iana" - }, - "application/vnd.wap.slc": { - source: "iana" - }, - "application/vnd.wap.wbxml": { - source: "iana", - charset: "UTF-8", - extensions: ["wbxml"] - }, - "application/vnd.wap.wmlc": { - source: "iana", - extensions: ["wmlc"] - }, - "application/vnd.wap.wmlscriptc": { - source: "iana", - extensions: ["wmlsc"] - }, - "application/vnd.webturbo": { - source: "iana", - extensions: ["wtb"] - }, - "application/vnd.wfa.dpp": { - source: "iana" - }, - "application/vnd.wfa.p2p": { - source: "iana" - }, - "application/vnd.wfa.wsc": { - source: "iana" - }, - "application/vnd.windows.devicepairing": { - source: "iana" - }, - "application/vnd.wmc": { - source: "iana" - }, - "application/vnd.wmf.bootstrap": { - source: "iana" - }, - "application/vnd.wolfram.mathematica": { - source: "iana" - }, - "application/vnd.wolfram.mathematica.package": { - source: "iana" - }, - "application/vnd.wolfram.player": { - source: "iana", - extensions: ["nbp"] - }, - "application/vnd.wordperfect": { - source: "iana", - extensions: ["wpd"] - }, - "application/vnd.wqd": { - source: "iana", - extensions: ["wqd"] - }, - "application/vnd.wrq-hp3000-labelled": { - source: "iana" - }, - "application/vnd.wt.stf": { - source: "iana", - extensions: ["stf"] - }, - "application/vnd.wv.csp+wbxml": { - source: "iana" - }, - "application/vnd.wv.csp+xml": { - source: "iana", - compressible: true - }, - "application/vnd.wv.ssp+xml": { - source: "iana", - compressible: true - }, - "application/vnd.xacml+json": { - source: "iana", - compressible: true - }, - "application/vnd.xara": { - source: "iana", - extensions: ["xar"] - }, - "application/vnd.xfdl": { - source: "iana", - extensions: ["xfdl"] - }, - "application/vnd.xfdl.webform": { - source: "iana" - }, - "application/vnd.xmi+xml": { - source: "iana", - compressible: true - }, - "application/vnd.xmpie.cpkg": { - source: "iana" - }, - "application/vnd.xmpie.dpkg": { - source: "iana" - }, - "application/vnd.xmpie.plan": { - source: "iana" - }, - "application/vnd.xmpie.ppkg": { - source: "iana" - }, - "application/vnd.xmpie.xlim": { - source: "iana" - }, - "application/vnd.yamaha.hv-dic": { - source: "iana", - extensions: ["hvd"] - }, - "application/vnd.yamaha.hv-script": { - source: "iana", - extensions: ["hvs"] - }, - "application/vnd.yamaha.hv-voice": { - source: "iana", - extensions: ["hvp"] - }, - "application/vnd.yamaha.openscoreformat": { - source: "iana", - extensions: ["osf"] - }, - "application/vnd.yamaha.openscoreformat.osfpvg+xml": { - source: "iana", - compressible: true, - extensions: ["osfpvg"] - }, - "application/vnd.yamaha.remote-setup": { - source: "iana" - }, - "application/vnd.yamaha.smaf-audio": { - source: "iana", - extensions: ["saf"] - }, - "application/vnd.yamaha.smaf-phrase": { - source: "iana", - extensions: ["spf"] - }, - "application/vnd.yamaha.through-ngn": { - source: "iana" - }, - "application/vnd.yamaha.tunnel-udpencap": { - source: "iana" - }, - "application/vnd.yaoweme": { - source: "iana" - }, - "application/vnd.yellowriver-custom-menu": { - source: "iana", - extensions: ["cmp"] - }, - "application/vnd.youtube.yt": { - source: "iana" - }, - "application/vnd.zul": { - source: "iana", - extensions: ["zir", "zirz"] - }, - "application/vnd.zzazz.deck+xml": { - source: "iana", - compressible: true, - extensions: ["zaz"] - }, - "application/voicexml+xml": { - source: "iana", - compressible: true, - extensions: ["vxml"] - }, - "application/voucher-cms+json": { - source: "iana", - compressible: true - }, - "application/vq-rtcpxr": { - source: "iana" - }, - "application/wasm": { - source: "iana", - compressible: true, - extensions: ["wasm"] - }, - "application/watcherinfo+xml": { - source: "iana", - compressible: true, - extensions: ["wif"] - }, - "application/webpush-options+json": { - source: "iana", - compressible: true - }, - "application/whoispp-query": { - source: "iana" - }, - "application/whoispp-response": { - source: "iana" - }, - "application/widget": { - source: "iana", - extensions: ["wgt"] - }, - "application/winhlp": { - source: "apache", - extensions: ["hlp"] - }, - "application/wita": { - source: "iana" - }, - "application/wordperfect5.1": { - source: "iana" - }, - "application/wsdl+xml": { - source: "iana", - compressible: true, - extensions: ["wsdl"] - }, - "application/wspolicy+xml": { - source: "iana", - compressible: true, - extensions: ["wspolicy"] - }, - "application/x-7z-compressed": { - source: "apache", - compressible: false, - extensions: ["7z"] - }, - "application/x-abiword": { - source: "apache", - extensions: ["abw"] - }, - "application/x-ace-compressed": { - source: "apache", - extensions: ["ace"] - }, - "application/x-amf": { - source: "apache" - }, - "application/x-apple-diskimage": { - source: "apache", - extensions: ["dmg"] - }, - "application/x-arj": { - compressible: false, - extensions: ["arj"] - }, - "application/x-authorware-bin": { - source: "apache", - extensions: ["aab", "x32", "u32", "vox"] - }, - "application/x-authorware-map": { - source: "apache", - extensions: ["aam"] - }, - "application/x-authorware-seg": { - source: "apache", - extensions: ["aas"] - }, - "application/x-bcpio": { - source: "apache", - extensions: ["bcpio"] - }, - "application/x-bdoc": { - compressible: false, - extensions: ["bdoc"] - }, - "application/x-bittorrent": { - source: "apache", - extensions: ["torrent"] - }, - "application/x-blorb": { - source: "apache", - extensions: ["blb", "blorb"] - }, - "application/x-bzip": { - source: "apache", - compressible: false, - extensions: ["bz"] - }, - "application/x-bzip2": { - source: "apache", - compressible: false, - extensions: ["bz2", "boz"] - }, - "application/x-cbr": { - source: "apache", - extensions: ["cbr", "cba", "cbt", "cbz", "cb7"] - }, - "application/x-cdlink": { - source: "apache", - extensions: ["vcd"] - }, - "application/x-cfs-compressed": { - source: "apache", - extensions: ["cfs"] - }, - "application/x-chat": { - source: "apache", - extensions: ["chat"] - }, - "application/x-chess-pgn": { - source: "apache", - extensions: ["pgn"] - }, - "application/x-chrome-extension": { - extensions: ["crx"] - }, - "application/x-cocoa": { - source: "nginx", - extensions: ["cco"] - }, - "application/x-compress": { - source: "apache" - }, - "application/x-conference": { - source: "apache", - extensions: ["nsc"] - }, - "application/x-cpio": { - source: "apache", - extensions: ["cpio"] - }, - "application/x-csh": { - source: "apache", - extensions: ["csh"] - }, - "application/x-deb": { - compressible: false - }, - "application/x-debian-package": { - source: "apache", - extensions: ["deb", "udeb"] - }, - "application/x-dgc-compressed": { - source: "apache", - extensions: ["dgc"] - }, - "application/x-director": { - source: "apache", - extensions: ["dir", "dcr", "dxr", "cst", "cct", "cxt", "w3d", "fgd", "swa"] - }, - "application/x-doom": { - source: "apache", - extensions: ["wad"] - }, - "application/x-dtbncx+xml": { - source: "apache", - compressible: true, - extensions: ["ncx"] - }, - "application/x-dtbook+xml": { - source: "apache", - compressible: true, - extensions: ["dtb"] - }, - "application/x-dtbresource+xml": { - source: "apache", - compressible: true, - extensions: ["res"] - }, - "application/x-dvi": { - source: "apache", - compressible: false, - extensions: ["dvi"] - }, - "application/x-envoy": { - source: "apache", - extensions: ["evy"] - }, - "application/x-eva": { - source: "apache", - extensions: ["eva"] - }, - "application/x-font-bdf": { - source: "apache", - extensions: ["bdf"] - }, - "application/x-font-dos": { - source: "apache" - }, - "application/x-font-framemaker": { - source: "apache" - }, - "application/x-font-ghostscript": { - source: "apache", - extensions: ["gsf"] - }, - "application/x-font-libgrx": { - source: "apache" - }, - "application/x-font-linux-psf": { - source: "apache", - extensions: ["psf"] - }, - "application/x-font-pcf": { - source: "apache", - extensions: ["pcf"] - }, - "application/x-font-snf": { - source: "apache", - extensions: ["snf"] - }, - "application/x-font-speedo": { - source: "apache" - }, - "application/x-font-sunos-news": { - source: "apache" - }, - "application/x-font-type1": { - source: "apache", - extensions: ["pfa", "pfb", "pfm", "afm"] - }, - "application/x-font-vfont": { - source: "apache" - }, - "application/x-freearc": { - source: "apache", - extensions: ["arc"] - }, - "application/x-futuresplash": { - source: "apache", - extensions: ["spl"] - }, - "application/x-gca-compressed": { - source: "apache", - extensions: ["gca"] - }, - "application/x-glulx": { - source: "apache", - extensions: ["ulx"] - }, - "application/x-gnumeric": { - source: "apache", - extensions: ["gnumeric"] - }, - "application/x-gramps-xml": { - source: "apache", - extensions: ["gramps"] - }, - "application/x-gtar": { - source: "apache", - extensions: ["gtar"] - }, - "application/x-gzip": { - source: "apache" - }, - "application/x-hdf": { - source: "apache", - extensions: ["hdf"] - }, - "application/x-httpd-php": { - compressible: true, - extensions: ["php"] - }, - "application/x-install-instructions": { - source: "apache", - extensions: ["install"] - }, - "application/x-iso9660-image": { - source: "apache", - extensions: ["iso"] - }, - "application/x-iwork-keynote-sffkey": { - extensions: ["key"] - }, - "application/x-iwork-numbers-sffnumbers": { - extensions: ["numbers"] - }, - "application/x-iwork-pages-sffpages": { - extensions: ["pages"] - }, - "application/x-java-archive-diff": { - source: "nginx", - extensions: ["jardiff"] - }, - "application/x-java-jnlp-file": { - source: "apache", - compressible: false, - extensions: ["jnlp"] - }, - "application/x-javascript": { - compressible: true - }, - "application/x-keepass2": { - extensions: ["kdbx"] - }, - "application/x-latex": { - source: "apache", - compressible: false, - extensions: ["latex"] - }, - "application/x-lua-bytecode": { - extensions: ["luac"] - }, - "application/x-lzh-compressed": { - source: "apache", - extensions: ["lzh", "lha"] - }, - "application/x-makeself": { - source: "nginx", - extensions: ["run"] - }, - "application/x-mie": { - source: "apache", - extensions: ["mie"] - }, - "application/x-mobipocket-ebook": { - source: "apache", - extensions: ["prc", "mobi"] - }, - "application/x-mpegurl": { - compressible: false - }, - "application/x-ms-application": { - source: "apache", - extensions: ["application"] - }, - "application/x-ms-shortcut": { - source: "apache", - extensions: ["lnk"] - }, - "application/x-ms-wmd": { - source: "apache", - extensions: ["wmd"] - }, - "application/x-ms-wmz": { - source: "apache", - extensions: ["wmz"] - }, - "application/x-ms-xbap": { - source: "apache", - extensions: ["xbap"] - }, - "application/x-msaccess": { - source: "apache", - extensions: ["mdb"] - }, - "application/x-msbinder": { - source: "apache", - extensions: ["obd"] - }, - "application/x-mscardfile": { - source: "apache", - extensions: ["crd"] - }, - "application/x-msclip": { - source: "apache", - extensions: ["clp"] - }, - "application/x-msdos-program": { - extensions: ["exe"] - }, - "application/x-msdownload": { - source: "apache", - extensions: ["exe", "dll", "com", "bat", "msi"] - }, - "application/x-msmediaview": { - source: "apache", - extensions: ["mvb", "m13", "m14"] - }, - "application/x-msmetafile": { - source: "apache", - extensions: ["wmf", "wmz", "emf", "emz"] - }, - "application/x-msmoney": { - source: "apache", - extensions: ["mny"] - }, - "application/x-mspublisher": { - source: "apache", - extensions: ["pub"] - }, - "application/x-msschedule": { - source: "apache", - extensions: ["scd"] - }, - "application/x-msterminal": { - source: "apache", - extensions: ["trm"] - }, - "application/x-mswrite": { - source: "apache", - extensions: ["wri"] - }, - "application/x-netcdf": { - source: "apache", - extensions: ["nc", "cdf"] - }, - "application/x-ns-proxy-autoconfig": { - compressible: true, - extensions: ["pac"] - }, - "application/x-nzb": { - source: "apache", - extensions: ["nzb"] - }, - "application/x-perl": { - source: "nginx", - extensions: ["pl", "pm"] - }, - "application/x-pilot": { - source: "nginx", - extensions: ["prc", "pdb"] - }, - "application/x-pkcs12": { - source: "apache", - compressible: false, - extensions: ["p12", "pfx"] - }, - "application/x-pkcs7-certificates": { - source: "apache", - extensions: ["p7b", "spc"] - }, - "application/x-pkcs7-certreqresp": { - source: "apache", - extensions: ["p7r"] - }, - "application/x-pki-message": { - source: "iana" - }, - "application/x-rar-compressed": { - source: "apache", - compressible: false, - extensions: ["rar"] - }, - "application/x-redhat-package-manager": { - source: "nginx", - extensions: ["rpm"] - }, - "application/x-research-info-systems": { - source: "apache", - extensions: ["ris"] - }, - "application/x-sea": { - source: "nginx", - extensions: ["sea"] - }, - "application/x-sh": { - source: "apache", - compressible: true, - extensions: ["sh"] - }, - "application/x-shar": { - source: "apache", - extensions: ["shar"] - }, - "application/x-shockwave-flash": { - source: "apache", - compressible: false, - extensions: ["swf"] - }, - "application/x-silverlight-app": { - source: "apache", - extensions: ["xap"] - }, - "application/x-sql": { - source: "apache", - extensions: ["sql"] - }, - "application/x-stuffit": { - source: "apache", - compressible: false, - extensions: ["sit"] - }, - "application/x-stuffitx": { - source: "apache", - extensions: ["sitx"] - }, - "application/x-subrip": { - source: "apache", - extensions: ["srt"] - }, - "application/x-sv4cpio": { - source: "apache", - extensions: ["sv4cpio"] - }, - "application/x-sv4crc": { - source: "apache", - extensions: ["sv4crc"] - }, - "application/x-t3vm-image": { - source: "apache", - extensions: ["t3"] - }, - "application/x-tads": { - source: "apache", - extensions: ["gam"] - }, - "application/x-tar": { - source: "apache", - compressible: true, - extensions: ["tar"] - }, - "application/x-tcl": { - source: "apache", - extensions: ["tcl", "tk"] - }, - "application/x-tex": { - source: "apache", - extensions: ["tex"] - }, - "application/x-tex-tfm": { - source: "apache", - extensions: ["tfm"] - }, - "application/x-texinfo": { - source: "apache", - extensions: ["texinfo", "texi"] - }, - "application/x-tgif": { - source: "apache", - extensions: ["obj"] - }, - "application/x-ustar": { - source: "apache", - extensions: ["ustar"] - }, - "application/x-virtualbox-hdd": { - compressible: true, - extensions: ["hdd"] - }, - "application/x-virtualbox-ova": { - compressible: true, - extensions: ["ova"] - }, - "application/x-virtualbox-ovf": { - compressible: true, - extensions: ["ovf"] - }, - "application/x-virtualbox-vbox": { - compressible: true, - extensions: ["vbox"] - }, - "application/x-virtualbox-vbox-extpack": { - compressible: false, - extensions: ["vbox-extpack"] - }, - "application/x-virtualbox-vdi": { - compressible: true, - extensions: ["vdi"] - }, - "application/x-virtualbox-vhd": { - compressible: true, - extensions: ["vhd"] - }, - "application/x-virtualbox-vmdk": { - compressible: true, - extensions: ["vmdk"] - }, - "application/x-wais-source": { - source: "apache", - extensions: ["src"] - }, - "application/x-web-app-manifest+json": { - compressible: true, - extensions: ["webapp"] - }, - "application/x-www-form-urlencoded": { - source: "iana", - compressible: true - }, - "application/x-x509-ca-cert": { - source: "iana", - extensions: ["der", "crt", "pem"] - }, - "application/x-x509-ca-ra-cert": { - source: "iana" - }, - "application/x-x509-next-ca-cert": { - source: "iana" - }, - "application/x-xfig": { - source: "apache", - extensions: ["fig"] - }, - "application/x-xliff+xml": { - source: "apache", - compressible: true, - extensions: ["xlf"] - }, - "application/x-xpinstall": { - source: "apache", - compressible: false, - extensions: ["xpi"] - }, - "application/x-xz": { - source: "apache", - extensions: ["xz"] - }, - "application/x-zmachine": { - source: "apache", - extensions: ["z1", "z2", "z3", "z4", "z5", "z6", "z7", "z8"] - }, - "application/x400-bp": { - source: "iana" - }, - "application/xacml+xml": { - source: "iana", - compressible: true - }, - "application/xaml+xml": { - source: "apache", - compressible: true, - extensions: ["xaml"] - }, - "application/xcap-att+xml": { - source: "iana", - compressible: true, - extensions: ["xav"] - }, - "application/xcap-caps+xml": { - source: "iana", - compressible: true, - extensions: ["xca"] - }, - "application/xcap-diff+xml": { - source: "iana", - compressible: true, - extensions: ["xdf"] - }, - "application/xcap-el+xml": { - source: "iana", - compressible: true, - extensions: ["xel"] - }, - "application/xcap-error+xml": { - source: "iana", - compressible: true - }, - "application/xcap-ns+xml": { - source: "iana", - compressible: true, - extensions: ["xns"] - }, - "application/xcon-conference-info+xml": { - source: "iana", - compressible: true - }, - "application/xcon-conference-info-diff+xml": { - source: "iana", - compressible: true - }, - "application/xenc+xml": { - source: "iana", - compressible: true, - extensions: ["xenc"] - }, - "application/xhtml+xml": { - source: "iana", - compressible: true, - extensions: ["xhtml", "xht"] - }, - "application/xhtml-voice+xml": { - source: "apache", - compressible: true - }, - "application/xliff+xml": { - source: "iana", - compressible: true, - extensions: ["xlf"] - }, - "application/xml": { - source: "iana", - compressible: true, - extensions: ["xml", "xsl", "xsd", "rng"] - }, - "application/xml-dtd": { - source: "iana", - compressible: true, - extensions: ["dtd"] - }, - "application/xml-external-parsed-entity": { - source: "iana" - }, - "application/xml-patch+xml": { - source: "iana", - compressible: true - }, - "application/xmpp+xml": { - source: "iana", - compressible: true - }, - "application/xop+xml": { - source: "iana", - compressible: true, - extensions: ["xop"] - }, - "application/xproc+xml": { - source: "apache", - compressible: true, - extensions: ["xpl"] - }, - "application/xslt+xml": { - source: "iana", - compressible: true, - extensions: ["xsl", "xslt"] - }, - "application/xspf+xml": { - source: "apache", - compressible: true, - extensions: ["xspf"] - }, - "application/xv+xml": { - source: "iana", - compressible: true, - extensions: ["mxml", "xhvml", "xvml", "xvm"] - }, - "application/yang": { - source: "iana", - extensions: ["yang"] - }, - "application/yang-data+json": { - source: "iana", - compressible: true - }, - "application/yang-data+xml": { - source: "iana", - compressible: true - }, - "application/yang-patch+json": { - source: "iana", - compressible: true - }, - "application/yang-patch+xml": { - source: "iana", - compressible: true - }, - "application/yin+xml": { - source: "iana", - compressible: true, - extensions: ["yin"] - }, - "application/zip": { - source: "iana", - compressible: false, - extensions: ["zip"] - }, - "application/zlib": { - source: "iana" - }, - "application/zstd": { - source: "iana" - }, - "audio/1d-interleaved-parityfec": { - source: "iana" - }, - "audio/32kadpcm": { - source: "iana" - }, - "audio/3gpp": { - source: "iana", - compressible: false, - extensions: ["3gpp"] - }, - "audio/3gpp2": { - source: "iana" - }, - "audio/aac": { - source: "iana" - }, - "audio/ac3": { - source: "iana" - }, - "audio/adpcm": { - source: "apache", - extensions: ["adp"] - }, - "audio/amr": { - source: "iana", - extensions: ["amr"] - }, - "audio/amr-wb": { - source: "iana" - }, - "audio/amr-wb+": { - source: "iana" - }, - "audio/aptx": { - source: "iana" - }, - "audio/asc": { - source: "iana" - }, - "audio/atrac-advanced-lossless": { - source: "iana" - }, - "audio/atrac-x": { - source: "iana" - }, - "audio/atrac3": { - source: "iana" - }, - "audio/basic": { - source: "iana", - compressible: false, - extensions: ["au", "snd"] - }, - "audio/bv16": { - source: "iana" - }, - "audio/bv32": { - source: "iana" - }, - "audio/clearmode": { - source: "iana" - }, - "audio/cn": { - source: "iana" - }, - "audio/dat12": { - source: "iana" - }, - "audio/dls": { - source: "iana" - }, - "audio/dsr-es201108": { - source: "iana" - }, - "audio/dsr-es202050": { - source: "iana" - }, - "audio/dsr-es202211": { - source: "iana" - }, - "audio/dsr-es202212": { - source: "iana" - }, - "audio/dv": { - source: "iana" - }, - "audio/dvi4": { - source: "iana" - }, - "audio/eac3": { - source: "iana" - }, - "audio/encaprtp": { - source: "iana" - }, - "audio/evrc": { - source: "iana" - }, - "audio/evrc-qcp": { - source: "iana" - }, - "audio/evrc0": { - source: "iana" - }, - "audio/evrc1": { - source: "iana" - }, - "audio/evrcb": { - source: "iana" - }, - "audio/evrcb0": { - source: "iana" - }, - "audio/evrcb1": { - source: "iana" - }, - "audio/evrcnw": { - source: "iana" - }, - "audio/evrcnw0": { - source: "iana" - }, - "audio/evrcnw1": { - source: "iana" - }, - "audio/evrcwb": { - source: "iana" - }, - "audio/evrcwb0": { - source: "iana" - }, - "audio/evrcwb1": { - source: "iana" - }, - "audio/evs": { - source: "iana" - }, - "audio/flexfec": { - source: "iana" - }, - "audio/fwdred": { - source: "iana" - }, - "audio/g711-0": { - source: "iana" - }, - "audio/g719": { - source: "iana" - }, - "audio/g722": { - source: "iana" - }, - "audio/g7221": { - source: "iana" - }, - "audio/g723": { - source: "iana" - }, - "audio/g726-16": { - source: "iana" - }, - "audio/g726-24": { - source: "iana" - }, - "audio/g726-32": { - source: "iana" - }, - "audio/g726-40": { - source: "iana" - }, - "audio/g728": { - source: "iana" - }, - "audio/g729": { - source: "iana" - }, - "audio/g7291": { - source: "iana" - }, - "audio/g729d": { - source: "iana" - }, - "audio/g729e": { - source: "iana" - }, - "audio/gsm": { - source: "iana" - }, - "audio/gsm-efr": { - source: "iana" - }, - "audio/gsm-hr-08": { - source: "iana" - }, - "audio/ilbc": { - source: "iana" - }, - "audio/ip-mr_v2.5": { - source: "iana" - }, - "audio/isac": { - source: "apache" - }, - "audio/l16": { - source: "iana" - }, - "audio/l20": { - source: "iana" - }, - "audio/l24": { - source: "iana", - compressible: false - }, - "audio/l8": { - source: "iana" - }, - "audio/lpc": { - source: "iana" - }, - "audio/melp": { - source: "iana" - }, - "audio/melp1200": { - source: "iana" - }, - "audio/melp2400": { - source: "iana" - }, - "audio/melp600": { - source: "iana" - }, - "audio/mhas": { - source: "iana" - }, - "audio/midi": { - source: "apache", - extensions: ["mid", "midi", "kar", "rmi"] - }, - "audio/mobile-xmf": { - source: "iana", - extensions: ["mxmf"] - }, - "audio/mp3": { - compressible: false, - extensions: ["mp3"] - }, - "audio/mp4": { - source: "iana", - compressible: false, - extensions: ["m4a", "mp4a"] - }, - "audio/mp4a-latm": { - source: "iana" - }, - "audio/mpa": { - source: "iana" - }, - "audio/mpa-robust": { - source: "iana" - }, - "audio/mpeg": { - source: "iana", - compressible: false, - extensions: ["mpga", "mp2", "mp2a", "mp3", "m2a", "m3a"] - }, - "audio/mpeg4-generic": { - source: "iana" - }, - "audio/musepack": { - source: "apache" - }, - "audio/ogg": { - source: "iana", - compressible: false, - extensions: ["oga", "ogg", "spx", "opus"] - }, - "audio/opus": { - source: "iana" - }, - "audio/parityfec": { - source: "iana" - }, - "audio/pcma": { - source: "iana" - }, - "audio/pcma-wb": { - source: "iana" - }, - "audio/pcmu": { - source: "iana" - }, - "audio/pcmu-wb": { - source: "iana" - }, - "audio/prs.sid": { - source: "iana" - }, - "audio/qcelp": { - source: "iana" - }, - "audio/raptorfec": { - source: "iana" - }, - "audio/red": { - source: "iana" - }, - "audio/rtp-enc-aescm128": { - source: "iana" - }, - "audio/rtp-midi": { - source: "iana" - }, - "audio/rtploopback": { - source: "iana" - }, - "audio/rtx": { - source: "iana" - }, - "audio/s3m": { - source: "apache", - extensions: ["s3m"] - }, - "audio/scip": { - source: "iana" - }, - "audio/silk": { - source: "apache", - extensions: ["sil"] - }, - "audio/smv": { - source: "iana" - }, - "audio/smv-qcp": { - source: "iana" - }, - "audio/smv0": { - source: "iana" - }, - "audio/sofa": { - source: "iana" - }, - "audio/sp-midi": { - source: "iana" - }, - "audio/speex": { - source: "iana" - }, - "audio/t140c": { - source: "iana" - }, - "audio/t38": { - source: "iana" - }, - "audio/telephone-event": { - source: "iana" - }, - "audio/tetra_acelp": { - source: "iana" - }, - "audio/tetra_acelp_bb": { - source: "iana" - }, - "audio/tone": { - source: "iana" - }, - "audio/tsvcis": { - source: "iana" - }, - "audio/uemclip": { - source: "iana" - }, - "audio/ulpfec": { - source: "iana" - }, - "audio/usac": { - source: "iana" - }, - "audio/vdvi": { - source: "iana" - }, - "audio/vmr-wb": { - source: "iana" - }, - "audio/vnd.3gpp.iufp": { - source: "iana" - }, - "audio/vnd.4sb": { - source: "iana" - }, - "audio/vnd.audiokoz": { - source: "iana" - }, - "audio/vnd.celp": { - source: "iana" - }, - "audio/vnd.cisco.nse": { - source: "iana" - }, - "audio/vnd.cmles.radio-events": { - source: "iana" - }, - "audio/vnd.cns.anp1": { - source: "iana" - }, - "audio/vnd.cns.inf1": { - source: "iana" - }, - "audio/vnd.dece.audio": { - source: "iana", - extensions: ["uva", "uvva"] - }, - "audio/vnd.digital-winds": { - source: "iana", - extensions: ["eol"] - }, - "audio/vnd.dlna.adts": { - source: "iana" - }, - "audio/vnd.dolby.heaac.1": { - source: "iana" - }, - "audio/vnd.dolby.heaac.2": { - source: "iana" - }, - "audio/vnd.dolby.mlp": { - source: "iana" - }, - "audio/vnd.dolby.mps": { - source: "iana" - }, - "audio/vnd.dolby.pl2": { - source: "iana" - }, - "audio/vnd.dolby.pl2x": { - source: "iana" - }, - "audio/vnd.dolby.pl2z": { - source: "iana" - }, - "audio/vnd.dolby.pulse.1": { - source: "iana" - }, - "audio/vnd.dra": { - source: "iana", - extensions: ["dra"] - }, - "audio/vnd.dts": { - source: "iana", - extensions: ["dts"] - }, - "audio/vnd.dts.hd": { - source: "iana", - extensions: ["dtshd"] - }, - "audio/vnd.dts.uhd": { - source: "iana" - }, - "audio/vnd.dvb.file": { - source: "iana" - }, - "audio/vnd.everad.plj": { - source: "iana" - }, - "audio/vnd.hns.audio": { - source: "iana" - }, - "audio/vnd.lucent.voice": { - source: "iana", - extensions: ["lvp"] - }, - "audio/vnd.ms-playready.media.pya": { - source: "iana", - extensions: ["pya"] - }, - "audio/vnd.nokia.mobile-xmf": { - source: "iana" - }, - "audio/vnd.nortel.vbk": { - source: "iana" - }, - "audio/vnd.nuera.ecelp4800": { - source: "iana", - extensions: ["ecelp4800"] - }, - "audio/vnd.nuera.ecelp7470": { - source: "iana", - extensions: ["ecelp7470"] - }, - "audio/vnd.nuera.ecelp9600": { - source: "iana", - extensions: ["ecelp9600"] - }, - "audio/vnd.octel.sbc": { - source: "iana" - }, - "audio/vnd.presonus.multitrack": { - source: "iana" - }, - "audio/vnd.qcelp": { - source: "iana" - }, - "audio/vnd.rhetorex.32kadpcm": { - source: "iana" - }, - "audio/vnd.rip": { - source: "iana", - extensions: ["rip"] - }, - "audio/vnd.rn-realaudio": { - compressible: false - }, - "audio/vnd.sealedmedia.softseal.mpeg": { - source: "iana" - }, - "audio/vnd.vmx.cvsd": { - source: "iana" - }, - "audio/vnd.wave": { - compressible: false - }, - "audio/vorbis": { - source: "iana", - compressible: false - }, - "audio/vorbis-config": { - source: "iana" - }, - "audio/wav": { - compressible: false, - extensions: ["wav"] - }, - "audio/wave": { - compressible: false, - extensions: ["wav"] - }, - "audio/webm": { - source: "apache", - compressible: false, - extensions: ["weba"] - }, - "audio/x-aac": { - source: "apache", - compressible: false, - extensions: ["aac"] - }, - "audio/x-aiff": { - source: "apache", - extensions: ["aif", "aiff", "aifc"] - }, - "audio/x-caf": { - source: "apache", - compressible: false, - extensions: ["caf"] - }, - "audio/x-flac": { - source: "apache", - extensions: ["flac"] - }, - "audio/x-m4a": { - source: "nginx", - extensions: ["m4a"] - }, - "audio/x-matroska": { - source: "apache", - extensions: ["mka"] - }, - "audio/x-mpegurl": { - source: "apache", - extensions: ["m3u"] - }, - "audio/x-ms-wax": { - source: "apache", - extensions: ["wax"] - }, - "audio/x-ms-wma": { - source: "apache", - extensions: ["wma"] - }, - "audio/x-pn-realaudio": { - source: "apache", - extensions: ["ram", "ra"] - }, - "audio/x-pn-realaudio-plugin": { - source: "apache", - extensions: ["rmp"] - }, - "audio/x-realaudio": { - source: "nginx", - extensions: ["ra"] - }, - "audio/x-tta": { - source: "apache" - }, - "audio/x-wav": { - source: "apache", - extensions: ["wav"] - }, - "audio/xm": { - source: "apache", - extensions: ["xm"] - }, - "chemical/x-cdx": { - source: "apache", - extensions: ["cdx"] - }, - "chemical/x-cif": { - source: "apache", - extensions: ["cif"] - }, - "chemical/x-cmdf": { - source: "apache", - extensions: ["cmdf"] - }, - "chemical/x-cml": { - source: "apache", - extensions: ["cml"] - }, - "chemical/x-csml": { - source: "apache", - extensions: ["csml"] - }, - "chemical/x-pdb": { - source: "apache" - }, - "chemical/x-xyz": { - source: "apache", - extensions: ["xyz"] - }, - "font/collection": { - source: "iana", - extensions: ["ttc"] - }, - "font/otf": { - source: "iana", - compressible: true, - extensions: ["otf"] - }, - "font/sfnt": { - source: "iana" - }, - "font/ttf": { - source: "iana", - compressible: true, - extensions: ["ttf"] - }, - "font/woff": { - source: "iana", - extensions: ["woff"] - }, - "font/woff2": { - source: "iana", - extensions: ["woff2"] - }, - "image/aces": { - source: "iana", - extensions: ["exr"] - }, - "image/apng": { - compressible: false, - extensions: ["apng"] - }, - "image/avci": { - source: "iana", - extensions: ["avci"] - }, - "image/avcs": { - source: "iana", - extensions: ["avcs"] - }, - "image/avif": { - source: "iana", - compressible: false, - extensions: ["avif"] - }, - "image/bmp": { - source: "iana", - compressible: true, - extensions: ["bmp"] - }, - "image/cgm": { - source: "iana", - extensions: ["cgm"] - }, - "image/dicom-rle": { - source: "iana", - extensions: ["drle"] - }, - "image/emf": { - source: "iana", - extensions: ["emf"] - }, - "image/fits": { - source: "iana", - extensions: ["fits"] - }, - "image/g3fax": { - source: "iana", - extensions: ["g3"] - }, - "image/gif": { - source: "iana", - compressible: false, - extensions: ["gif"] - }, - "image/heic": { - source: "iana", - extensions: ["heic"] - }, - "image/heic-sequence": { - source: "iana", - extensions: ["heics"] - }, - "image/heif": { - source: "iana", - extensions: ["heif"] - }, - "image/heif-sequence": { - source: "iana", - extensions: ["heifs"] - }, - "image/hej2k": { - source: "iana", - extensions: ["hej2"] - }, - "image/hsj2": { - source: "iana", - extensions: ["hsj2"] - }, - "image/ief": { - source: "iana", - extensions: ["ief"] - }, - "image/jls": { - source: "iana", - extensions: ["jls"] - }, - "image/jp2": { - source: "iana", - compressible: false, - extensions: ["jp2", "jpg2"] - }, - "image/jpeg": { - source: "iana", - compressible: false, - extensions: ["jpeg", "jpg", "jpe"] - }, - "image/jph": { - source: "iana", - extensions: ["jph"] - }, - "image/jphc": { - source: "iana", - extensions: ["jhc"] - }, - "image/jpm": { - source: "iana", - compressible: false, - extensions: ["jpm"] - }, - "image/jpx": { - source: "iana", - compressible: false, - extensions: ["jpx", "jpf"] - }, - "image/jxr": { - source: "iana", - extensions: ["jxr"] - }, - "image/jxra": { - source: "iana", - extensions: ["jxra"] - }, - "image/jxrs": { - source: "iana", - extensions: ["jxrs"] - }, - "image/jxs": { - source: "iana", - extensions: ["jxs"] - }, - "image/jxsc": { - source: "iana", - extensions: ["jxsc"] - }, - "image/jxsi": { - source: "iana", - extensions: ["jxsi"] - }, - "image/jxss": { - source: "iana", - extensions: ["jxss"] - }, - "image/ktx": { - source: "iana", - extensions: ["ktx"] - }, - "image/ktx2": { - source: "iana", - extensions: ["ktx2"] - }, - "image/naplps": { - source: "iana" - }, - "image/pjpeg": { - compressible: false - }, - "image/png": { - source: "iana", - compressible: false, - extensions: ["png"] - }, - "image/prs.btif": { - source: "iana", - extensions: ["btif"] - }, - "image/prs.pti": { - source: "iana", - extensions: ["pti"] - }, - "image/pwg-raster": { - source: "iana" - }, - "image/sgi": { - source: "apache", - extensions: ["sgi"] - }, - "image/svg+xml": { - source: "iana", - compressible: true, - extensions: ["svg", "svgz"] - }, - "image/t38": { - source: "iana", - extensions: ["t38"] - }, - "image/tiff": { - source: "iana", - compressible: false, - extensions: ["tif", "tiff"] - }, - "image/tiff-fx": { - source: "iana", - extensions: ["tfx"] - }, - "image/vnd.adobe.photoshop": { - source: "iana", - compressible: true, - extensions: ["psd"] - }, - "image/vnd.airzip.accelerator.azv": { - source: "iana", - extensions: ["azv"] - }, - "image/vnd.cns.inf2": { - source: "iana" - }, - "image/vnd.dece.graphic": { - source: "iana", - extensions: ["uvi", "uvvi", "uvg", "uvvg"] - }, - "image/vnd.djvu": { - source: "iana", - extensions: ["djvu", "djv"] - }, - "image/vnd.dvb.subtitle": { - source: "iana", - extensions: ["sub"] - }, - "image/vnd.dwg": { - source: "iana", - extensions: ["dwg"] - }, - "image/vnd.dxf": { - source: "iana", - extensions: ["dxf"] - }, - "image/vnd.fastbidsheet": { - source: "iana", - extensions: ["fbs"] - }, - "image/vnd.fpx": { - source: "iana", - extensions: ["fpx"] - }, - "image/vnd.fst": { - source: "iana", - extensions: ["fst"] - }, - "image/vnd.fujixerox.edmics-mmr": { - source: "iana", - extensions: ["mmr"] - }, - "image/vnd.fujixerox.edmics-rlc": { - source: "iana", - extensions: ["rlc"] - }, - "image/vnd.globalgraphics.pgb": { - source: "iana" - }, - "image/vnd.microsoft.icon": { - source: "iana", - compressible: true, - extensions: ["ico"] - }, - "image/vnd.mix": { - source: "iana" - }, - "image/vnd.mozilla.apng": { - source: "iana" - }, - "image/vnd.ms-dds": { - compressible: true, - extensions: ["dds"] - }, - "image/vnd.ms-modi": { - source: "iana", - extensions: ["mdi"] - }, - "image/vnd.ms-photo": { - source: "apache", - extensions: ["wdp"] - }, - "image/vnd.net-fpx": { - source: "iana", - extensions: ["npx"] - }, - "image/vnd.pco.b16": { - source: "iana", - extensions: ["b16"] - }, - "image/vnd.radiance": { - source: "iana" - }, - "image/vnd.sealed.png": { - source: "iana" - }, - "image/vnd.sealedmedia.softseal.gif": { - source: "iana" - }, - "image/vnd.sealedmedia.softseal.jpg": { - source: "iana" - }, - "image/vnd.svf": { - source: "iana" - }, - "image/vnd.tencent.tap": { - source: "iana", - extensions: ["tap"] - }, - "image/vnd.valve.source.texture": { - source: "iana", - extensions: ["vtf"] - }, - "image/vnd.wap.wbmp": { - source: "iana", - extensions: ["wbmp"] - }, - "image/vnd.xiff": { - source: "iana", - extensions: ["xif"] - }, - "image/vnd.zbrush.pcx": { - source: "iana", - extensions: ["pcx"] - }, - "image/webp": { - source: "apache", - extensions: ["webp"] - }, - "image/wmf": { - source: "iana", - extensions: ["wmf"] - }, - "image/x-3ds": { - source: "apache", - extensions: ["3ds"] - }, - "image/x-cmu-raster": { - source: "apache", - extensions: ["ras"] - }, - "image/x-cmx": { - source: "apache", - extensions: ["cmx"] - }, - "image/x-freehand": { - source: "apache", - extensions: ["fh", "fhc", "fh4", "fh5", "fh7"] - }, - "image/x-icon": { - source: "apache", - compressible: true, - extensions: ["ico"] - }, - "image/x-jng": { - source: "nginx", - extensions: ["jng"] - }, - "image/x-mrsid-image": { - source: "apache", - extensions: ["sid"] - }, - "image/x-ms-bmp": { - source: "nginx", - compressible: true, - extensions: ["bmp"] - }, - "image/x-pcx": { - source: "apache", - extensions: ["pcx"] - }, - "image/x-pict": { - source: "apache", - extensions: ["pic", "pct"] - }, - "image/x-portable-anymap": { - source: "apache", - extensions: ["pnm"] - }, - "image/x-portable-bitmap": { - source: "apache", - extensions: ["pbm"] - }, - "image/x-portable-graymap": { - source: "apache", - extensions: ["pgm"] - }, - "image/x-portable-pixmap": { - source: "apache", - extensions: ["ppm"] - }, - "image/x-rgb": { - source: "apache", - extensions: ["rgb"] - }, - "image/x-tga": { - source: "apache", - extensions: ["tga"] - }, - "image/x-xbitmap": { - source: "apache", - extensions: ["xbm"] - }, - "image/x-xcf": { - compressible: false - }, - "image/x-xpixmap": { - source: "apache", - extensions: ["xpm"] - }, - "image/x-xwindowdump": { - source: "apache", - extensions: ["xwd"] - }, - "message/cpim": { - source: "iana" - }, - "message/delivery-status": { - source: "iana" - }, - "message/disposition-notification": { - source: "iana", - extensions: [ - "disposition-notification" - ] - }, - "message/external-body": { - source: "iana" - }, - "message/feedback-report": { - source: "iana" - }, - "message/global": { - source: "iana", - extensions: ["u8msg"] - }, - "message/global-delivery-status": { - source: "iana", - extensions: ["u8dsn"] - }, - "message/global-disposition-notification": { - source: "iana", - extensions: ["u8mdn"] - }, - "message/global-headers": { - source: "iana", - extensions: ["u8hdr"] - }, - "message/http": { - source: "iana", - compressible: false - }, - "message/imdn+xml": { - source: "iana", - compressible: true - }, - "message/news": { - source: "iana" - }, - "message/partial": { - source: "iana", - compressible: false - }, - "message/rfc822": { - source: "iana", - compressible: true, - extensions: ["eml", "mime"] - }, - "message/s-http": { - source: "iana" - }, - "message/sip": { - source: "iana" - }, - "message/sipfrag": { - source: "iana" - }, - "message/tracking-status": { - source: "iana" - }, - "message/vnd.si.simp": { - source: "iana" - }, - "message/vnd.wfa.wsc": { - source: "iana", - extensions: ["wsc"] - }, - "model/3mf": { - source: "iana", - extensions: ["3mf"] - }, - "model/e57": { - source: "iana" - }, - "model/gltf+json": { - source: "iana", - compressible: true, - extensions: ["gltf"] - }, - "model/gltf-binary": { - source: "iana", - compressible: true, - extensions: ["glb"] - }, - "model/iges": { - source: "iana", - compressible: false, - extensions: ["igs", "iges"] - }, - "model/mesh": { - source: "iana", - compressible: false, - extensions: ["msh", "mesh", "silo"] - }, - "model/mtl": { - source: "iana", - extensions: ["mtl"] - }, - "model/obj": { - source: "iana", - extensions: ["obj"] - }, - "model/step": { - source: "iana" - }, - "model/step+xml": { - source: "iana", - compressible: true, - extensions: ["stpx"] - }, - "model/step+zip": { - source: "iana", - compressible: false, - extensions: ["stpz"] - }, - "model/step-xml+zip": { - source: "iana", - compressible: false, - extensions: ["stpxz"] - }, - "model/stl": { - source: "iana", - extensions: ["stl"] - }, - "model/vnd.collada+xml": { - source: "iana", - compressible: true, - extensions: ["dae"] - }, - "model/vnd.dwf": { - source: "iana", - extensions: ["dwf"] - }, - "model/vnd.flatland.3dml": { - source: "iana" - }, - "model/vnd.gdl": { - source: "iana", - extensions: ["gdl"] - }, - "model/vnd.gs-gdl": { - source: "apache" - }, - "model/vnd.gs.gdl": { - source: "iana" - }, - "model/vnd.gtw": { - source: "iana", - extensions: ["gtw"] - }, - "model/vnd.moml+xml": { - source: "iana", - compressible: true - }, - "model/vnd.mts": { - source: "iana", - extensions: ["mts"] - }, - "model/vnd.opengex": { - source: "iana", - extensions: ["ogex"] - }, - "model/vnd.parasolid.transmit.binary": { - source: "iana", - extensions: ["x_b"] - }, - "model/vnd.parasolid.transmit.text": { - source: "iana", - extensions: ["x_t"] - }, - "model/vnd.pytha.pyox": { - source: "iana" - }, - "model/vnd.rosette.annotated-data-model": { - source: "iana" - }, - "model/vnd.sap.vds": { - source: "iana", - extensions: ["vds"] - }, - "model/vnd.usdz+zip": { - source: "iana", - compressible: false, - extensions: ["usdz"] - }, - "model/vnd.valve.source.compiled-map": { - source: "iana", - extensions: ["bsp"] - }, - "model/vnd.vtu": { - source: "iana", - extensions: ["vtu"] - }, - "model/vrml": { - source: "iana", - compressible: false, - extensions: ["wrl", "vrml"] - }, - "model/x3d+binary": { - source: "apache", - compressible: false, - extensions: ["x3db", "x3dbz"] - }, - "model/x3d+fastinfoset": { - source: "iana", - extensions: ["x3db"] - }, - "model/x3d+vrml": { - source: "apache", - compressible: false, - extensions: ["x3dv", "x3dvz"] - }, - "model/x3d+xml": { - source: "iana", - compressible: true, - extensions: ["x3d", "x3dz"] - }, - "model/x3d-vrml": { - source: "iana", - extensions: ["x3dv"] - }, - "multipart/alternative": { - source: "iana", - compressible: false - }, - "multipart/appledouble": { - source: "iana" - }, - "multipart/byteranges": { - source: "iana" - }, - "multipart/digest": { - source: "iana" - }, - "multipart/encrypted": { - source: "iana", - compressible: false - }, - "multipart/form-data": { - source: "iana", - compressible: false - }, - "multipart/header-set": { - source: "iana" - }, - "multipart/mixed": { - source: "iana" - }, - "multipart/multilingual": { - source: "iana" - }, - "multipart/parallel": { - source: "iana" - }, - "multipart/related": { - source: "iana", - compressible: false - }, - "multipart/report": { - source: "iana" - }, - "multipart/signed": { - source: "iana", - compressible: false - }, - "multipart/vnd.bint.med-plus": { - source: "iana" - }, - "multipart/voice-message": { - source: "iana" - }, - "multipart/x-mixed-replace": { - source: "iana" - }, - "text/1d-interleaved-parityfec": { - source: "iana" - }, - "text/cache-manifest": { - source: "iana", - compressible: true, - extensions: ["appcache", "manifest"] - }, - "text/calendar": { - source: "iana", - extensions: ["ics", "ifb"] - }, - "text/calender": { - compressible: true - }, - "text/cmd": { - compressible: true - }, - "text/coffeescript": { - extensions: ["coffee", "litcoffee"] - }, - "text/cql": { - source: "iana" - }, - "text/cql-expression": { - source: "iana" - }, - "text/cql-identifier": { - source: "iana" - }, - "text/css": { - source: "iana", - charset: "UTF-8", - compressible: true, - extensions: ["css"] - }, - "text/csv": { - source: "iana", - compressible: true, - extensions: ["csv"] - }, - "text/csv-schema": { - source: "iana" - }, - "text/directory": { - source: "iana" - }, - "text/dns": { - source: "iana" - }, - "text/ecmascript": { - source: "iana" - }, - "text/encaprtp": { - source: "iana" - }, - "text/enriched": { - source: "iana" - }, - "text/fhirpath": { - source: "iana" - }, - "text/flexfec": { - source: "iana" - }, - "text/fwdred": { - source: "iana" - }, - "text/gff3": { - source: "iana" - }, - "text/grammar-ref-list": { - source: "iana" - }, - "text/html": { - source: "iana", - compressible: true, - extensions: ["html", "htm", "shtml"] - }, - "text/jade": { - extensions: ["jade"] - }, - "text/javascript": { - source: "iana", - compressible: true - }, - "text/jcr-cnd": { - source: "iana" - }, - "text/jsx": { - compressible: true, - extensions: ["jsx"] - }, - "text/less": { - compressible: true, - extensions: ["less"] - }, - "text/markdown": { - source: "iana", - compressible: true, - extensions: ["markdown", "md"] - }, - "text/mathml": { - source: "nginx", - extensions: ["mml"] - }, - "text/mdx": { - compressible: true, - extensions: ["mdx"] - }, - "text/mizar": { - source: "iana" - }, - "text/n3": { - source: "iana", - charset: "UTF-8", - compressible: true, - extensions: ["n3"] - }, - "text/parameters": { - source: "iana", - charset: "UTF-8" - }, - "text/parityfec": { - source: "iana" - }, - "text/plain": { - source: "iana", - compressible: true, - extensions: ["txt", "text", "conf", "def", "list", "log", "in", "ini"] - }, - "text/provenance-notation": { - source: "iana", - charset: "UTF-8" - }, - "text/prs.fallenstein.rst": { - source: "iana" - }, - "text/prs.lines.tag": { - source: "iana", - extensions: ["dsc"] - }, - "text/prs.prop.logic": { - source: "iana" - }, - "text/raptorfec": { - source: "iana" - }, - "text/red": { - source: "iana" - }, - "text/rfc822-headers": { - source: "iana" - }, - "text/richtext": { - source: "iana", - compressible: true, - extensions: ["rtx"] - }, - "text/rtf": { - source: "iana", - compressible: true, - extensions: ["rtf"] - }, - "text/rtp-enc-aescm128": { - source: "iana" - }, - "text/rtploopback": { - source: "iana" - }, - "text/rtx": { - source: "iana" - }, - "text/sgml": { - source: "iana", - extensions: ["sgml", "sgm"] - }, - "text/shaclc": { - source: "iana" - }, - "text/shex": { - source: "iana", - extensions: ["shex"] - }, - "text/slim": { - extensions: ["slim", "slm"] - }, - "text/spdx": { - source: "iana", - extensions: ["spdx"] - }, - "text/strings": { - source: "iana" - }, - "text/stylus": { - extensions: ["stylus", "styl"] - }, - "text/t140": { - source: "iana" - }, - "text/tab-separated-values": { - source: "iana", - compressible: true, - extensions: ["tsv"] - }, - "text/troff": { - source: "iana", - extensions: ["t", "tr", "roff", "man", "me", "ms"] - }, - "text/turtle": { - source: "iana", - charset: "UTF-8", - extensions: ["ttl"] - }, - "text/ulpfec": { - source: "iana" - }, - "text/uri-list": { - source: "iana", - compressible: true, - extensions: ["uri", "uris", "urls"] - }, - "text/vcard": { - source: "iana", - compressible: true, - extensions: ["vcard"] - }, - "text/vnd.a": { - source: "iana" - }, - "text/vnd.abc": { - source: "iana" - }, - "text/vnd.ascii-art": { - source: "iana" - }, - "text/vnd.curl": { - source: "iana", - extensions: ["curl"] - }, - "text/vnd.curl.dcurl": { - source: "apache", - extensions: ["dcurl"] - }, - "text/vnd.curl.mcurl": { - source: "apache", - extensions: ["mcurl"] - }, - "text/vnd.curl.scurl": { - source: "apache", - extensions: ["scurl"] - }, - "text/vnd.debian.copyright": { - source: "iana", - charset: "UTF-8" - }, - "text/vnd.dmclientscript": { - source: "iana" - }, - "text/vnd.dvb.subtitle": { - source: "iana", - extensions: ["sub"] - }, - "text/vnd.esmertec.theme-descriptor": { - source: "iana", - charset: "UTF-8" - }, - "text/vnd.familysearch.gedcom": { - source: "iana", - extensions: ["ged"] - }, - "text/vnd.ficlab.flt": { - source: "iana" - }, - "text/vnd.fly": { - source: "iana", - extensions: ["fly"] - }, - "text/vnd.fmi.flexstor": { - source: "iana", - extensions: ["flx"] - }, - "text/vnd.gml": { - source: "iana" - }, - "text/vnd.graphviz": { - source: "iana", - extensions: ["gv"] - }, - "text/vnd.hans": { - source: "iana" - }, - "text/vnd.hgl": { - source: "iana" - }, - "text/vnd.in3d.3dml": { - source: "iana", - extensions: ["3dml"] - }, - "text/vnd.in3d.spot": { - source: "iana", - extensions: ["spot"] - }, - "text/vnd.iptc.newsml": { - source: "iana" - }, - "text/vnd.iptc.nitf": { - source: "iana" - }, - "text/vnd.latex-z": { - source: "iana" - }, - "text/vnd.motorola.reflex": { - source: "iana" - }, - "text/vnd.ms-mediapackage": { - source: "iana" - }, - "text/vnd.net2phone.commcenter.command": { - source: "iana" - }, - "text/vnd.radisys.msml-basic-layout": { - source: "iana" - }, - "text/vnd.senx.warpscript": { - source: "iana" - }, - "text/vnd.si.uricatalogue": { - source: "iana" - }, - "text/vnd.sosi": { - source: "iana" - }, - "text/vnd.sun.j2me.app-descriptor": { - source: "iana", - charset: "UTF-8", - extensions: ["jad"] - }, - "text/vnd.trolltech.linguist": { - source: "iana", - charset: "UTF-8" - }, - "text/vnd.wap.si": { - source: "iana" - }, - "text/vnd.wap.sl": { - source: "iana" - }, - "text/vnd.wap.wml": { - source: "iana", - extensions: ["wml"] - }, - "text/vnd.wap.wmlscript": { - source: "iana", - extensions: ["wmls"] - }, - "text/vtt": { - source: "iana", - charset: "UTF-8", - compressible: true, - extensions: ["vtt"] - }, - "text/x-asm": { - source: "apache", - extensions: ["s", "asm"] - }, - "text/x-c": { - source: "apache", - extensions: ["c", "cc", "cxx", "cpp", "h", "hh", "dic"] - }, - "text/x-component": { - source: "nginx", - extensions: ["htc"] - }, - "text/x-fortran": { - source: "apache", - extensions: ["f", "for", "f77", "f90"] - }, - "text/x-gwt-rpc": { - compressible: true - }, - "text/x-handlebars-template": { - extensions: ["hbs"] - }, - "text/x-java-source": { - source: "apache", - extensions: ["java"] - }, - "text/x-jquery-tmpl": { - compressible: true - }, - "text/x-lua": { - extensions: ["lua"] - }, - "text/x-markdown": { - compressible: true, - extensions: ["mkd"] - }, - "text/x-nfo": { - source: "apache", - extensions: ["nfo"] - }, - "text/x-opml": { - source: "apache", - extensions: ["opml"] - }, - "text/x-org": { - compressible: true, - extensions: ["org"] - }, - "text/x-pascal": { - source: "apache", - extensions: ["p", "pas"] - }, - "text/x-processing": { - compressible: true, - extensions: ["pde"] - }, - "text/x-sass": { - extensions: ["sass"] - }, - "text/x-scss": { - extensions: ["scss"] - }, - "text/x-setext": { - source: "apache", - extensions: ["etx"] - }, - "text/x-sfv": { - source: "apache", - extensions: ["sfv"] - }, - "text/x-suse-ymp": { - compressible: true, - extensions: ["ymp"] - }, - "text/x-uuencode": { - source: "apache", - extensions: ["uu"] - }, - "text/x-vcalendar": { - source: "apache", - extensions: ["vcs"] - }, - "text/x-vcard": { - source: "apache", - extensions: ["vcf"] - }, - "text/xml": { - source: "iana", - compressible: true, - extensions: ["xml"] - }, - "text/xml-external-parsed-entity": { - source: "iana" - }, - "text/yaml": { - compressible: true, - extensions: ["yaml", "yml"] - }, - "video/1d-interleaved-parityfec": { - source: "iana" - }, - "video/3gpp": { - source: "iana", - extensions: ["3gp", "3gpp"] - }, - "video/3gpp-tt": { - source: "iana" - }, - "video/3gpp2": { - source: "iana", - extensions: ["3g2"] - }, - "video/av1": { - source: "iana" - }, - "video/bmpeg": { - source: "iana" - }, - "video/bt656": { - source: "iana" - }, - "video/celb": { - source: "iana" - }, - "video/dv": { - source: "iana" - }, - "video/encaprtp": { - source: "iana" - }, - "video/ffv1": { - source: "iana" - }, - "video/flexfec": { - source: "iana" - }, - "video/h261": { - source: "iana", - extensions: ["h261"] - }, - "video/h263": { - source: "iana", - extensions: ["h263"] - }, - "video/h263-1998": { - source: "iana" - }, - "video/h263-2000": { - source: "iana" - }, - "video/h264": { - source: "iana", - extensions: ["h264"] - }, - "video/h264-rcdo": { - source: "iana" - }, - "video/h264-svc": { - source: "iana" - }, - "video/h265": { - source: "iana" - }, - "video/iso.segment": { - source: "iana", - extensions: ["m4s"] - }, - "video/jpeg": { - source: "iana", - extensions: ["jpgv"] - }, - "video/jpeg2000": { - source: "iana" - }, - "video/jpm": { - source: "apache", - extensions: ["jpm", "jpgm"] - }, - "video/jxsv": { - source: "iana" - }, - "video/mj2": { - source: "iana", - extensions: ["mj2", "mjp2"] - }, - "video/mp1s": { - source: "iana" - }, - "video/mp2p": { - source: "iana" - }, - "video/mp2t": { - source: "iana", - extensions: ["ts"] - }, - "video/mp4": { - source: "iana", - compressible: false, - extensions: ["mp4", "mp4v", "mpg4"] - }, - "video/mp4v-es": { - source: "iana" - }, - "video/mpeg": { - source: "iana", - compressible: false, - extensions: ["mpeg", "mpg", "mpe", "m1v", "m2v"] - }, - "video/mpeg4-generic": { - source: "iana" - }, - "video/mpv": { - source: "iana" - }, - "video/nv": { - source: "iana" - }, - "video/ogg": { - source: "iana", - compressible: false, - extensions: ["ogv"] - }, - "video/parityfec": { - source: "iana" - }, - "video/pointer": { - source: "iana" - }, - "video/quicktime": { - source: "iana", - compressible: false, - extensions: ["qt", "mov"] - }, - "video/raptorfec": { - source: "iana" - }, - "video/raw": { - source: "iana" - }, - "video/rtp-enc-aescm128": { - source: "iana" - }, - "video/rtploopback": { - source: "iana" - }, - "video/rtx": { - source: "iana" - }, - "video/scip": { - source: "iana" - }, - "video/smpte291": { - source: "iana" - }, - "video/smpte292m": { - source: "iana" - }, - "video/ulpfec": { - source: "iana" - }, - "video/vc1": { - source: "iana" - }, - "video/vc2": { - source: "iana" - }, - "video/vnd.cctv": { - source: "iana" - }, - "video/vnd.dece.hd": { - source: "iana", - extensions: ["uvh", "uvvh"] - }, - "video/vnd.dece.mobile": { - source: "iana", - extensions: ["uvm", "uvvm"] - }, - "video/vnd.dece.mp4": { - source: "iana" - }, - "video/vnd.dece.pd": { - source: "iana", - extensions: ["uvp", "uvvp"] - }, - "video/vnd.dece.sd": { - source: "iana", - extensions: ["uvs", "uvvs"] - }, - "video/vnd.dece.video": { - source: "iana", - extensions: ["uvv", "uvvv"] - }, - "video/vnd.directv.mpeg": { - source: "iana" - }, - "video/vnd.directv.mpeg-tts": { - source: "iana" - }, - "video/vnd.dlna.mpeg-tts": { - source: "iana" - }, - "video/vnd.dvb.file": { - source: "iana", - extensions: ["dvb"] - }, - "video/vnd.fvt": { - source: "iana", - extensions: ["fvt"] - }, - "video/vnd.hns.video": { - source: "iana" - }, - "video/vnd.iptvforum.1dparityfec-1010": { - source: "iana" - }, - "video/vnd.iptvforum.1dparityfec-2005": { - source: "iana" - }, - "video/vnd.iptvforum.2dparityfec-1010": { - source: "iana" - }, - "video/vnd.iptvforum.2dparityfec-2005": { - source: "iana" - }, - "video/vnd.iptvforum.ttsavc": { - source: "iana" - }, - "video/vnd.iptvforum.ttsmpeg2": { - source: "iana" - }, - "video/vnd.motorola.video": { - source: "iana" - }, - "video/vnd.motorola.videop": { - source: "iana" - }, - "video/vnd.mpegurl": { - source: "iana", - extensions: ["mxu", "m4u"] - }, - "video/vnd.ms-playready.media.pyv": { - source: "iana", - extensions: ["pyv"] - }, - "video/vnd.nokia.interleaved-multimedia": { - source: "iana" - }, - "video/vnd.nokia.mp4vr": { - source: "iana" - }, - "video/vnd.nokia.videovoip": { - source: "iana" - }, - "video/vnd.objectvideo": { - source: "iana" - }, - "video/vnd.radgamettools.bink": { - source: "iana" - }, - "video/vnd.radgamettools.smacker": { - source: "iana" - }, - "video/vnd.sealed.mpeg1": { - source: "iana" - }, - "video/vnd.sealed.mpeg4": { - source: "iana" - }, - "video/vnd.sealed.swf": { - source: "iana" - }, - "video/vnd.sealedmedia.softseal.mov": { - source: "iana" - }, - "video/vnd.uvvu.mp4": { - source: "iana", - extensions: ["uvu", "uvvu"] - }, - "video/vnd.vivo": { - source: "iana", - extensions: ["viv"] - }, - "video/vnd.youtube.yt": { - source: "iana" - }, - "video/vp8": { - source: "iana" - }, - "video/vp9": { - source: "iana" - }, - "video/webm": { - source: "apache", - compressible: false, - extensions: ["webm"] - }, - "video/x-f4v": { - source: "apache", - extensions: ["f4v"] - }, - "video/x-fli": { - source: "apache", - extensions: ["fli"] - }, - "video/x-flv": { - source: "apache", - compressible: false, - extensions: ["flv"] - }, - "video/x-m4v": { - source: "apache", - extensions: ["m4v"] - }, - "video/x-matroska": { - source: "apache", - compressible: false, - extensions: ["mkv", "mk3d", "mks"] - }, - "video/x-mng": { - source: "apache", - extensions: ["mng"] - }, - "video/x-ms-asf": { - source: "apache", - extensions: ["asf", "asx"] - }, - "video/x-ms-vob": { - source: "apache", - extensions: ["vob"] - }, - "video/x-ms-wm": { - source: "apache", - extensions: ["wm"] - }, - "video/x-ms-wmv": { - source: "apache", - compressible: false, - extensions: ["wmv"] - }, - "video/x-ms-wmx": { - source: "apache", - extensions: ["wmx"] - }, - "video/x-ms-wvx": { - source: "apache", - extensions: ["wvx"] - }, - "video/x-msvideo": { - source: "apache", - extensions: ["avi"] - }, - "video/x-sgi-movie": { - source: "apache", - extensions: ["movie"] - }, - "video/x-smv": { - source: "apache", - extensions: ["smv"] - }, - "x-conference/x-cooltalk": { - source: "apache", - extensions: ["ice"] - }, - "x-shader/x-fragment": { - compressible: true - }, - "x-shader/x-vertex": { - compressible: true - } - }; - } -}); - -// node_modules/.pnpm/mime-db@1.52.0/node_modules/mime-db/index.js -var require_mime_db2 = __commonJS({ - "node_modules/.pnpm/mime-db@1.52.0/node_modules/mime-db/index.js"(exports, module) { - module.exports = require_db2(); - } -}); - -// node_modules/.pnpm/mime-types@2.1.35/node_modules/mime-types/index.js -var require_mime_types2 = __commonJS({ - "node_modules/.pnpm/mime-types@2.1.35/node_modules/mime-types/index.js"(exports) { - "use strict"; - var db = require_mime_db2(); - var extname2 = __require("path").extname; - var EXTRACT_TYPE_REGEXP = /^\s*([^;\s]*)(?:;|\s|$)/; - var TEXT_TYPE_REGEXP = /^text\//i; - exports.charset = charset; - exports.charsets = { lookup: charset }; - exports.contentType = contentType; - exports.extension = extension2; - exports.extensions = /* @__PURE__ */ Object.create(null); - exports.lookup = lookup; - exports.types = /* @__PURE__ */ Object.create(null); - populateMaps(exports.extensions, exports.types); - function charset(type) { - if (!type || typeof type !== "string") { - return false; - } - var match = EXTRACT_TYPE_REGEXP.exec(type); - var mime = match && db[match[1].toLowerCase()]; - if (mime && mime.charset) { - return mime.charset; - } - if (match && TEXT_TYPE_REGEXP.test(match[1])) { - return "UTF-8"; - } - return false; - } - function contentType(str) { - if (!str || typeof str !== "string") { - return false; - } - var mime = str.indexOf("/") === -1 ? exports.lookup(str) : str; - if (!mime) { - return false; - } - if (mime.indexOf("charset") === -1) { - var charset2 = exports.charset(mime); - if (charset2) mime += "; charset=" + charset2.toLowerCase(); - } - return mime; - } - function extension2(type) { - if (!type || typeof type !== "string") { - return false; - } - var match = EXTRACT_TYPE_REGEXP.exec(type); - var exts = match && exports.extensions[match[1].toLowerCase()]; - if (!exts || !exts.length) { - return false; - } - return exts[0]; - } - function lookup(path53) { - if (!path53 || typeof path53 !== "string") { - return false; - } - var extension3 = extname2("x." + path53).toLowerCase().substr(1); - if (!extension3) { - return false; - } - return exports.types[extension3] || false; - } - function populateMaps(extensions, types2) { - var preference = ["nginx", "apache", void 0, "iana"]; - Object.keys(db).forEach(function forEachMimeType(type) { - var mime = db[type]; - var exts = mime.extensions; - if (!exts || !exts.length) { - return; - } - extensions[type] = exts; - for (var i5 = 0; i5 < exts.length; i5++) { - var extension3 = exts[i5]; - if (types2[extension3]) { - var from = preference.indexOf(db[types2[extension3]].source); - var to = preference.indexOf(mime.source); - if (types2[extension3] !== "application/octet-stream" && (from > to || from === to && types2[extension3].substr(0, 12) === "application/")) { - continue; - } - } - types2[extension3] = type; - } - }); - } - } -}); - -// node_modules/.pnpm/type-is@1.6.18/node_modules/type-is/index.js -var require_type_is2 = __commonJS({ - "node_modules/.pnpm/type-is@1.6.18/node_modules/type-is/index.js"(exports, module) { - "use strict"; - var typer = require_media_typer2(); - var mime = require_mime_types2(); - module.exports = typeofrequest; - module.exports.is = typeis; - module.exports.hasBody = hasbody; - module.exports.normalize = normalize2; - module.exports.match = mimeMatch; - function typeis(value, types_) { - var i5; - var types2 = types_; - var val = tryNormalizeType(value); - if (!val) { - return false; - } - if (types2 && !Array.isArray(types2)) { - types2 = new Array(arguments.length - 1); - for (i5 = 0; i5 < types2.length; i5++) { - types2[i5] = arguments[i5 + 1]; - } - } - if (!types2 || !types2.length) { - return val; - } - var type; - for (i5 = 0; i5 < types2.length; i5++) { - if (mimeMatch(normalize2(type = types2[i5]), val)) { - return type[0] === "+" || type.indexOf("*") !== -1 ? val : type; - } - } - return false; - } - function hasbody(req) { - return req.headers["transfer-encoding"] !== void 0 || !isNaN(req.headers["content-length"]); - } - function typeofrequest(req, types_) { - var types2 = types_; - if (!hasbody(req)) { - return null; - } - if (arguments.length > 2) { - types2 = new Array(arguments.length - 1); - for (var i5 = 0; i5 < types2.length; i5++) { - types2[i5] = arguments[i5 + 1]; - } - } - var value = req.headers["content-type"]; - return typeis(value, types2); - } - function normalize2(type) { - if (typeof type !== "string") { - return false; - } - switch (type) { - case "urlencoded": - return "application/x-www-form-urlencoded"; - case "multipart": - return "multipart/*"; - } - if (type[0] === "+") { - return "*/*" + type; - } - return type.indexOf("/") === -1 ? mime.lookup(type) : type; - } - function mimeMatch(expected, actual) { - if (expected === false) { - return false; - } - var actualParts = actual.split("/"); - var expectedParts = expected.split("/"); - if (actualParts.length !== 2 || expectedParts.length !== 2) { - return false; - } - if (expectedParts[0] !== "*" && expectedParts[0] !== actualParts[0]) { - return false; - } - if (expectedParts[1].substr(0, 2) === "*+") { - return expectedParts[1].length <= actualParts[1].length + 1 && expectedParts[1].substr(1) === actualParts[1].substr(1 - expectedParts[1].length); - } - if (expectedParts[1] !== "*" && expectedParts[1] !== actualParts[1]) { - return false; - } - return true; - } - function normalizeType(value) { - var type = typer.parse(value); - type.parameters = void 0; - return typer.format(type); - } - function tryNormalizeType(value) { - if (!value) { - return null; - } - try { - return normalizeType(value); - } catch (err) { - return null; - } - } - } -}); - -// node_modules/.pnpm/busboy@1.6.0/node_modules/busboy/lib/utils.js -var require_utils4 = __commonJS({ - "node_modules/.pnpm/busboy@1.6.0/node_modules/busboy/lib/utils.js"(exports, module) { - "use strict"; - function parseContentType(str) { - if (str.length === 0) - return; - const params = /* @__PURE__ */ Object.create(null); - let i5 = 0; - for (; i5 < str.length; ++i5) { - const code = str.charCodeAt(i5); - if (TOKEN[code] !== 1) { - if (code !== 47 || i5 === 0) - return; - break; - } - } - if (i5 === str.length) - return; - const type = str.slice(0, i5).toLowerCase(); - const subtypeStart = ++i5; - for (; i5 < str.length; ++i5) { - const code = str.charCodeAt(i5); - if (TOKEN[code] !== 1) { - if (i5 === subtypeStart) - return; - if (parseContentTypeParams(str, i5, params) === void 0) - return; - break; - } - } - if (i5 === subtypeStart) - return; - const subtype = str.slice(subtypeStart, i5).toLowerCase(); - return { type, subtype, params }; - } - function parseContentTypeParams(str, i5, params) { - while (i5 < str.length) { - for (; i5 < str.length; ++i5) { - const code = str.charCodeAt(i5); - if (code !== 32 && code !== 9) - break; - } - if (i5 === str.length) - break; - if (str.charCodeAt(i5++) !== 59) - return; - for (; i5 < str.length; ++i5) { - const code = str.charCodeAt(i5); - if (code !== 32 && code !== 9) - break; - } - if (i5 === str.length) - return; - let name; - const nameStart = i5; - for (; i5 < str.length; ++i5) { - const code = str.charCodeAt(i5); - if (TOKEN[code] !== 1) { - if (code !== 61) - return; - break; - } - } - if (i5 === str.length) - return; - name = str.slice(nameStart, i5); - ++i5; - if (i5 === str.length) - return; - let value = ""; - let valueStart; - if (str.charCodeAt(i5) === 34) { - valueStart = ++i5; - let escaping = false; - for (; i5 < str.length; ++i5) { - const code = str.charCodeAt(i5); - if (code === 92) { - if (escaping) { - valueStart = i5; - escaping = false; - } else { - value += str.slice(valueStart, i5); - escaping = true; - } - continue; - } - if (code === 34) { - if (escaping) { - valueStart = i5; - escaping = false; - continue; - } - value += str.slice(valueStart, i5); - break; - } - if (escaping) { - valueStart = i5 - 1; - escaping = false; - } - if (QDTEXT[code] !== 1) - return; - } - if (i5 === str.length) - return; - ++i5; - } else { - valueStart = i5; - for (; i5 < str.length; ++i5) { - const code = str.charCodeAt(i5); - if (TOKEN[code] !== 1) { - if (i5 === valueStart) - return; - break; - } - } - value = str.slice(valueStart, i5); - } - name = name.toLowerCase(); - if (params[name] === void 0) - params[name] = value; - } - return params; - } - function parseDisposition(str, defDecoder) { - if (str.length === 0) - return; - const params = /* @__PURE__ */ Object.create(null); - let i5 = 0; - for (; i5 < str.length; ++i5) { - const code = str.charCodeAt(i5); - if (TOKEN[code] !== 1) { - if (parseDispositionParams(str, i5, params, defDecoder) === void 0) - return; - break; - } - } - const type = str.slice(0, i5).toLowerCase(); - return { type, params }; - } - function parseDispositionParams(str, i5, params, defDecoder) { - while (i5 < str.length) { - for (; i5 < str.length; ++i5) { - const code = str.charCodeAt(i5); - if (code !== 32 && code !== 9) - break; - } - if (i5 === str.length) - break; - if (str.charCodeAt(i5++) !== 59) - return; - for (; i5 < str.length; ++i5) { - const code = str.charCodeAt(i5); - if (code !== 32 && code !== 9) - break; - } - if (i5 === str.length) - return; - let name; - const nameStart = i5; - for (; i5 < str.length; ++i5) { - const code = str.charCodeAt(i5); - if (TOKEN[code] !== 1) { - if (code === 61) - break; - return; - } - } - if (i5 === str.length) - return; - let value = ""; - let valueStart; - let charset; - name = str.slice(nameStart, i5); - if (name.charCodeAt(name.length - 1) === 42) { - const charsetStart = ++i5; - for (; i5 < str.length; ++i5) { - const code = str.charCodeAt(i5); - if (CHARSET[code] !== 1) { - if (code !== 39) - return; - break; - } - } - if (i5 === str.length) - return; - charset = str.slice(charsetStart, i5); - ++i5; - for (; i5 < str.length; ++i5) { - const code = str.charCodeAt(i5); - if (code === 39) - break; - } - if (i5 === str.length) - return; - ++i5; - if (i5 === str.length) - return; - valueStart = i5; - let encode6 = 0; - for (; i5 < str.length; ++i5) { - const code = str.charCodeAt(i5); - if (EXTENDED_VALUE[code] !== 1) { - if (code === 37) { - let hexUpper; - let hexLower; - if (i5 + 2 < str.length && (hexUpper = HEX_VALUES[str.charCodeAt(i5 + 1)]) !== -1 && (hexLower = HEX_VALUES[str.charCodeAt(i5 + 2)]) !== -1) { - const byteVal = (hexUpper << 4) + hexLower; - value += str.slice(valueStart, i5); - value += String.fromCharCode(byteVal); - i5 += 2; - valueStart = i5 + 1; - if (byteVal >= 128) - encode6 = 2; - else if (encode6 === 0) - encode6 = 1; - continue; - } - return; - } - break; - } - } - value += str.slice(valueStart, i5); - value = convertToUTF8(value, charset, encode6); - if (value === void 0) - return; - } else { - ++i5; - if (i5 === str.length) - return; - if (str.charCodeAt(i5) === 34) { - valueStart = ++i5; - let escaping = false; - for (; i5 < str.length; ++i5) { - const code = str.charCodeAt(i5); - if (code === 92) { - if (escaping) { - valueStart = i5; - escaping = false; - } else { - value += str.slice(valueStart, i5); - escaping = true; - } - continue; - } - if (code === 34) { - if (escaping) { - valueStart = i5; - escaping = false; - continue; - } - value += str.slice(valueStart, i5); - break; - } - if (escaping) { - valueStart = i5 - 1; - escaping = false; - } - if (QDTEXT[code] !== 1) - return; - } - if (i5 === str.length) - return; - ++i5; - } else { - valueStart = i5; - for (; i5 < str.length; ++i5) { - const code = str.charCodeAt(i5); - if (TOKEN[code] !== 1) { - if (i5 === valueStart) - return; - break; - } - } - value = str.slice(valueStart, i5); - } - value = defDecoder(value, 2); - if (value === void 0) - return; - } - name = name.toLowerCase(); - if (params[name] === void 0) - params[name] = value; - } - return params; - } - function getDecoder(charset) { - let lc; - while (true) { - switch (charset) { - case "utf-8": - case "utf8": - return decoders2.utf8; - case "latin1": - case "ascii": - // TODO: Make these a separate, strict decoder? - case "us-ascii": - case "iso-8859-1": - case "iso8859-1": - case "iso88591": - case "iso_8859-1": - case "windows-1252": - case "iso_8859-1:1987": - case "cp1252": - case "x-cp1252": - return decoders2.latin1; - case "utf16le": - case "utf-16le": - case "ucs2": - case "ucs-2": - return decoders2.utf16le; - case "base64": - return decoders2.base64; - default: - if (lc === void 0) { - lc = true; - charset = charset.toLowerCase(); - continue; - } - return decoders2.other.bind(charset); - } - } - } - var decoders2 = { - utf8: (data2, hint) => { - if (data2.length === 0) - return ""; - if (typeof data2 === "string") { - if (hint < 2) - return data2; - data2 = Buffer.from(data2, "latin1"); - } - return data2.utf8Slice(0, data2.length); - }, - latin1: (data2, hint) => { - if (data2.length === 0) - return ""; - if (typeof data2 === "string") - return data2; - return data2.latin1Slice(0, data2.length); - }, - utf16le: (data2, hint) => { - if (data2.length === 0) - return ""; - if (typeof data2 === "string") - data2 = Buffer.from(data2, "latin1"); - return data2.ucs2Slice(0, data2.length); - }, - base64: (data2, hint) => { - if (data2.length === 0) - return ""; - if (typeof data2 === "string") - data2 = Buffer.from(data2, "latin1"); - return data2.base64Slice(0, data2.length); - }, - other: (data2, hint) => { - if (data2.length === 0) - return ""; - if (typeof data2 === "string") - data2 = Buffer.from(data2, "latin1"); - try { - const decoder2 = new TextDecoder(exports); - return decoder2.decode(data2); - } catch { - } - } - }; - function convertToUTF8(data2, charset, hint) { - const decode5 = getDecoder(charset); - if (decode5) - return decode5(data2, hint); - } - function basename3(path53) { - if (typeof path53 !== "string") - return ""; - for (let i5 = path53.length - 1; i5 >= 0; --i5) { - switch (path53.charCodeAt(i5)) { - case 47: - // '/' - case 92: - path53 = path53.slice(i5 + 1); - return path53 === ".." || path53 === "." ? "" : path53; - } - } - return path53 === ".." || path53 === "." ? "" : path53; - } - var TOKEN = [ - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 1, - 0, - 1, - 1, - 1, - 1, - 1, - 0, - 0, - 1, - 1, - 0, - 1, - 1, - 0, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 0, - 0, - 0, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 0, - 1, - 0, - 1, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0 - ]; - var QDTEXT = [ - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 1, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 1, - 1, - 0, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 0, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 0, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1 - ]; - var CHARSET = [ - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 1, - 0, - 1, - 1, - 1, - 1, - 0, - 0, - 0, - 0, - 1, - 0, - 1, - 0, - 0, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 0, - 0, - 0, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 0, - 1, - 1, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0 - ]; - var EXTENDED_VALUE = [ - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 1, - 0, - 1, - 1, - 0, - 1, - 0, - 0, - 0, - 0, - 1, - 0, - 1, - 1, - 0, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 0, - 0, - 0, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 0, - 1, - 0, - 1, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0 - ]; - var HEX_VALUES = [ - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - 0, - 1, - 2, - 3, - 4, - 5, - 6, - 7, - 8, - 9, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - 10, - 11, - 12, - 13, - 14, - 15, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - 10, - 11, - 12, - 13, - 14, - 15, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1 - ]; - module.exports = { - basename: basename3, - convertToUTF8, - getDecoder, - parseContentType, - parseDisposition - }; - } -}); - -// node_modules/.pnpm/streamsearch@1.1.0/node_modules/streamsearch/lib/sbmh.js -var require_sbmh = __commonJS({ - "node_modules/.pnpm/streamsearch@1.1.0/node_modules/streamsearch/lib/sbmh.js"(exports, module) { - "use strict"; - function memcmp(buf1, pos1, buf2, pos2, num) { - for (let i5 = 0; i5 < num; ++i5) { - if (buf1[pos1 + i5] !== buf2[pos2 + i5]) - return false; - } - return true; - } - var SBMH = class { - constructor(needle, cb) { - if (typeof cb !== "function") - throw new Error("Missing match callback"); - if (typeof needle === "string") - needle = Buffer.from(needle); - else if (!Buffer.isBuffer(needle)) - throw new Error(`Expected Buffer for needle, got ${typeof needle}`); - const needleLen = needle.length; - this.maxMatches = Infinity; - this.matches = 0; - this._cb = cb; - this._lookbehindSize = 0; - this._needle = needle; - this._bufPos = 0; - this._lookbehind = Buffer.allocUnsafe(needleLen); - this._occ = [ - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen, - needleLen - ]; - if (needleLen > 1) { - for (let i5 = 0; i5 < needleLen - 1; ++i5) - this._occ[needle[i5]] = needleLen - 1 - i5; - } - } - reset() { - this.matches = 0; - this._lookbehindSize = 0; - this._bufPos = 0; - } - push(chunk, pos) { - let result; - if (!Buffer.isBuffer(chunk)) - chunk = Buffer.from(chunk, "latin1"); - const chunkLen = chunk.length; - this._bufPos = pos || 0; - while (result !== chunkLen && this.matches < this.maxMatches) - result = feed(this, chunk); - return result; - } - destroy() { - const lbSize = this._lookbehindSize; - if (lbSize) - this._cb(false, this._lookbehind, 0, lbSize, false); - this.reset(); - } - }; - function feed(self2, data2) { - const len = data2.length; - const needle = self2._needle; - const needleLen = needle.length; - let pos = -self2._lookbehindSize; - const lastNeedleCharPos = needleLen - 1; - const lastNeedleChar = needle[lastNeedleCharPos]; - const end = len - needleLen; - const occ = self2._occ; - const lookbehind = self2._lookbehind; - if (pos < 0) { - while (pos < 0 && pos <= end) { - const nextPos = pos + lastNeedleCharPos; - const ch = nextPos < 0 ? lookbehind[self2._lookbehindSize + nextPos] : data2[nextPos]; - if (ch === lastNeedleChar && matchNeedle(self2, data2, pos, lastNeedleCharPos)) { - self2._lookbehindSize = 0; - ++self2.matches; - if (pos > -self2._lookbehindSize) - self2._cb(true, lookbehind, 0, self2._lookbehindSize + pos, false); - else - self2._cb(true, void 0, 0, 0, true); - return self2._bufPos = pos + needleLen; - } - pos += occ[ch]; - } - while (pos < 0 && !matchNeedle(self2, data2, pos, len - pos)) - ++pos; - if (pos < 0) { - const bytesToCutOff = self2._lookbehindSize + pos; - if (bytesToCutOff > 0) { - self2._cb(false, lookbehind, 0, bytesToCutOff, false); - } - self2._lookbehindSize -= bytesToCutOff; - lookbehind.copy(lookbehind, 0, bytesToCutOff, self2._lookbehindSize); - lookbehind.set(data2, self2._lookbehindSize); - self2._lookbehindSize += len; - self2._bufPos = len; - return len; - } - self2._cb(false, lookbehind, 0, self2._lookbehindSize, false); - self2._lookbehindSize = 0; - } - pos += self2._bufPos; - const firstNeedleChar = needle[0]; - while (pos <= end) { - const ch = data2[pos + lastNeedleCharPos]; - if (ch === lastNeedleChar && data2[pos] === firstNeedleChar && memcmp(needle, 0, data2, pos, lastNeedleCharPos)) { - ++self2.matches; - if (pos > 0) - self2._cb(true, data2, self2._bufPos, pos, true); - else - self2._cb(true, void 0, 0, 0, true); - return self2._bufPos = pos + needleLen; - } - pos += occ[ch]; - } - while (pos < len) { - if (data2[pos] !== firstNeedleChar || !memcmp(data2, pos, needle, 0, len - pos)) { - ++pos; - continue; - } - data2.copy(lookbehind, 0, pos, len); - self2._lookbehindSize = len - pos; - break; - } - if (pos > 0) - self2._cb(false, data2, self2._bufPos, pos < len ? pos : len, true); - self2._bufPos = len; - return len; - } - function matchNeedle(self2, data2, pos, len) { - const lb = self2._lookbehind; - const lbSize = self2._lookbehindSize; - const needle = self2._needle; - for (let i5 = 0; i5 < len; ++i5, ++pos) { - const ch = pos < 0 ? lb[lbSize + pos] : data2[pos]; - if (ch !== needle[i5]) - return false; - } - return true; - } - module.exports = SBMH; - } -}); - -// node_modules/.pnpm/busboy@1.6.0/node_modules/busboy/lib/types/multipart.js -var require_multipart = __commonJS({ - "node_modules/.pnpm/busboy@1.6.0/node_modules/busboy/lib/types/multipart.js"(exports, module) { - "use strict"; - var { Readable: Readable3, Writable } = __require("stream"); - var StreamSearch = require_sbmh(); - var { - basename: basename3, - convertToUTF8, - getDecoder, - parseContentType, - parseDisposition - } = require_utils4(); - var BUF_CRLF = Buffer.from("\r\n"); - var BUF_CR = Buffer.from("\r"); - var BUF_DASH = Buffer.from("-"); - function noop5() { - } - var MAX_HEADER_PAIRS = 2e3; - var MAX_HEADER_SIZE = 16 * 1024; - var HPARSER_NAME = 0; - var HPARSER_PRE_OWS = 1; - var HPARSER_VALUE = 2; - var HeaderParser = class { - constructor(cb) { - this.header = /* @__PURE__ */ Object.create(null); - this.pairCount = 0; - this.byteCount = 0; - this.state = HPARSER_NAME; - this.name = ""; - this.value = ""; - this.crlf = 0; - this.cb = cb; - } - reset() { - this.header = /* @__PURE__ */ Object.create(null); - this.pairCount = 0; - this.byteCount = 0; - this.state = HPARSER_NAME; - this.name = ""; - this.value = ""; - this.crlf = 0; - } - push(chunk, pos, end) { - let start = pos; - while (pos < end) { - switch (this.state) { - case HPARSER_NAME: { - let done = false; - for (; pos < end; ++pos) { - if (this.byteCount === MAX_HEADER_SIZE) - return -1; - ++this.byteCount; - const code = chunk[pos]; - if (TOKEN[code] !== 1) { - if (code !== 58) - return -1; - this.name += chunk.latin1Slice(start, pos); - if (this.name.length === 0) - return -1; - ++pos; - done = true; - this.state = HPARSER_PRE_OWS; - break; - } - } - if (!done) { - this.name += chunk.latin1Slice(start, pos); - break; - } - } - case HPARSER_PRE_OWS: { - let done = false; - for (; pos < end; ++pos) { - if (this.byteCount === MAX_HEADER_SIZE) - return -1; - ++this.byteCount; - const code = chunk[pos]; - if (code !== 32 && code !== 9) { - start = pos; - done = true; - this.state = HPARSER_VALUE; - break; - } - } - if (!done) - break; - } - case HPARSER_VALUE: - switch (this.crlf) { - case 0: - for (; pos < end; ++pos) { - if (this.byteCount === MAX_HEADER_SIZE) - return -1; - ++this.byteCount; - const code = chunk[pos]; - if (FIELD_VCHAR[code] !== 1) { - if (code !== 13) - return -1; - ++this.crlf; - break; - } - } - this.value += chunk.latin1Slice(start, pos++); - break; - case 1: - if (this.byteCount === MAX_HEADER_SIZE) - return -1; - ++this.byteCount; - if (chunk[pos++] !== 10) - return -1; - ++this.crlf; - break; - case 2: { - if (this.byteCount === MAX_HEADER_SIZE) - return -1; - ++this.byteCount; - const code = chunk[pos]; - if (code === 32 || code === 9) { - start = pos; - this.crlf = 0; - } else { - if (++this.pairCount < MAX_HEADER_PAIRS) { - this.name = this.name.toLowerCase(); - if (this.header[this.name] === void 0) - this.header[this.name] = [this.value]; - else - this.header[this.name].push(this.value); - } - if (code === 13) { - ++this.crlf; - ++pos; - } else { - start = pos; - this.crlf = 0; - this.state = HPARSER_NAME; - this.name = ""; - this.value = ""; - } - } - break; - } - case 3: { - if (this.byteCount === MAX_HEADER_SIZE) - return -1; - ++this.byteCount; - if (chunk[pos++] !== 10) - return -1; - const header = this.header; - this.reset(); - this.cb(header); - return pos; - } - } - break; - } - } - return pos; - } - }; - var FileStream = class extends Readable3 { - constructor(opts, owner) { - super(opts); - this.truncated = false; - this._readcb = null; - this.once("end", () => { - this._read(); - if (--owner._fileEndsLeft === 0 && owner._finalcb) { - const cb = owner._finalcb; - owner._finalcb = null; - process.nextTick(cb); - } - }); - } - _read(n5) { - const cb = this._readcb; - if (cb) { - this._readcb = null; - cb(); - } - } - }; - var ignoreData = { - push: (chunk, pos) => { - }, - destroy: () => { - } - }; - function callAndUnsetCb(self2, err) { - const cb = self2._writecb; - self2._writecb = null; - if (err) - self2.destroy(err); - else if (cb) - cb(); - } - function nullDecoder(val, hint) { - return val; - } - var Multipart = class extends Writable { - constructor(cfg) { - const streamOpts = { - autoDestroy: true, - emitClose: true, - highWaterMark: typeof cfg.highWaterMark === "number" ? cfg.highWaterMark : void 0 - }; - super(streamOpts); - if (!cfg.conType.params || typeof cfg.conType.params.boundary !== "string") - throw new Error("Multipart: Boundary not found"); - const boundary = cfg.conType.params.boundary; - const paramDecoder = typeof cfg.defParamCharset === "string" && cfg.defParamCharset ? getDecoder(cfg.defParamCharset) : nullDecoder; - const defCharset = cfg.defCharset || "utf8"; - const preservePath = cfg.preservePath; - const fileOpts = { - autoDestroy: true, - emitClose: true, - highWaterMark: typeof cfg.fileHwm === "number" ? cfg.fileHwm : void 0 - }; - const limits = cfg.limits; - const fieldSizeLimit = limits && typeof limits.fieldSize === "number" ? limits.fieldSize : 1 * 1024 * 1024; - const fileSizeLimit = limits && typeof limits.fileSize === "number" ? limits.fileSize : Infinity; - const filesLimit = limits && typeof limits.files === "number" ? limits.files : Infinity; - const fieldsLimit = limits && typeof limits.fields === "number" ? limits.fields : Infinity; - const partsLimit = limits && typeof limits.parts === "number" ? limits.parts : Infinity; - let parts = -1; - let fields = 0; - let files = 0; - let skipPart = false; - this._fileEndsLeft = 0; - this._fileStream = void 0; - this._complete = false; - let fileSize = 0; - let field; - let fieldSize = 0; - let partCharset; - let partEncoding; - let partType; - let partName; - let partTruncated = false; - let hitFilesLimit = false; - let hitFieldsLimit = false; - this._hparser = null; - const hparser = new HeaderParser((header) => { - this._hparser = null; - skipPart = false; - partType = "text/plain"; - partCharset = defCharset; - partEncoding = "7bit"; - partName = void 0; - partTruncated = false; - let filename; - if (!header["content-disposition"]) { - skipPart = true; - return; - } - const disp = parseDisposition( - header["content-disposition"][0], - paramDecoder - ); - if (!disp || disp.type !== "form-data") { - skipPart = true; - return; - } - if (disp.params) { - if (disp.params.name) - partName = disp.params.name; - if (disp.params["filename*"]) - filename = disp.params["filename*"]; - else if (disp.params.filename) - filename = disp.params.filename; - if (filename !== void 0 && !preservePath) - filename = basename3(filename); - } - if (header["content-type"]) { - const conType = parseContentType(header["content-type"][0]); - if (conType) { - partType = `${conType.type}/${conType.subtype}`; - if (conType.params && typeof conType.params.charset === "string") - partCharset = conType.params.charset.toLowerCase(); - } - } - if (header["content-transfer-encoding"]) - partEncoding = header["content-transfer-encoding"][0].toLowerCase(); - if (partType === "application/octet-stream" || filename !== void 0) { - if (files === filesLimit) { - if (!hitFilesLimit) { - hitFilesLimit = true; - this.emit("filesLimit"); - } - skipPart = true; - return; - } - ++files; - if (this.listenerCount("file") === 0) { - skipPart = true; - return; - } - fileSize = 0; - this._fileStream = new FileStream(fileOpts, this); - ++this._fileEndsLeft; - this.emit( - "file", - partName, - this._fileStream, - { - filename, - encoding: partEncoding, - mimeType: partType - } - ); - } else { - if (fields === fieldsLimit) { - if (!hitFieldsLimit) { - hitFieldsLimit = true; - this.emit("fieldsLimit"); - } - skipPart = true; - return; - } - ++fields; - if (this.listenerCount("field") === 0) { - skipPart = true; - return; - } - field = []; - fieldSize = 0; - } - }); - let matchPostBoundary = 0; - const ssCb = (isMatch2, data2, start, end, isDataSafe) => { - retrydata: - while (data2) { - if (this._hparser !== null) { - const ret = this._hparser.push(data2, start, end); - if (ret === -1) { - this._hparser = null; - hparser.reset(); - this.emit("error", new Error("Malformed part header")); - break; - } - start = ret; - } - if (start === end) - break; - if (matchPostBoundary !== 0) { - if (matchPostBoundary === 1) { - switch (data2[start]) { - case 45: - matchPostBoundary = 2; - ++start; - break; - case 13: - matchPostBoundary = 3; - ++start; - break; - default: - matchPostBoundary = 0; - } - if (start === end) - return; - } - if (matchPostBoundary === 2) { - matchPostBoundary = 0; - if (data2[start] === 45) { - this._complete = true; - this._bparser = ignoreData; - return; - } - const writecb = this._writecb; - this._writecb = noop5; - ssCb(false, BUF_DASH, 0, 1, false); - this._writecb = writecb; - } else if (matchPostBoundary === 3) { - matchPostBoundary = 0; - if (data2[start] === 10) { - ++start; - if (parts >= partsLimit) - break; - this._hparser = hparser; - if (start === end) - break; - continue retrydata; - } else { - const writecb = this._writecb; - this._writecb = noop5; - ssCb(false, BUF_CR, 0, 1, false); - this._writecb = writecb; - } - } - } - if (!skipPart) { - if (this._fileStream) { - let chunk; - const actualLen = Math.min(end - start, fileSizeLimit - fileSize); - if (!isDataSafe) { - chunk = Buffer.allocUnsafe(actualLen); - data2.copy(chunk, 0, start, start + actualLen); - } else { - chunk = data2.slice(start, start + actualLen); - } - fileSize += chunk.length; - if (fileSize === fileSizeLimit) { - if (chunk.length > 0) - this._fileStream.push(chunk); - this._fileStream.emit("limit"); - this._fileStream.truncated = true; - skipPart = true; - } else if (!this._fileStream.push(chunk)) { - if (this._writecb) - this._fileStream._readcb = this._writecb; - this._writecb = null; - } - } else if (field !== void 0) { - let chunk; - const actualLen = Math.min( - end - start, - fieldSizeLimit - fieldSize - ); - if (!isDataSafe) { - chunk = Buffer.allocUnsafe(actualLen); - data2.copy(chunk, 0, start, start + actualLen); - } else { - chunk = data2.slice(start, start + actualLen); - } - fieldSize += actualLen; - field.push(chunk); - if (fieldSize === fieldSizeLimit) { - skipPart = true; - partTruncated = true; - } - } - } - break; - } - if (isMatch2) { - matchPostBoundary = 1; - if (this._fileStream) { - this._fileStream.push(null); - this._fileStream = null; - } else if (field !== void 0) { - let data3; - switch (field.length) { - case 0: - data3 = ""; - break; - case 1: - data3 = convertToUTF8(field[0], partCharset, 0); - break; - default: - data3 = convertToUTF8( - Buffer.concat(field, fieldSize), - partCharset, - 0 - ); - } - field = void 0; - fieldSize = 0; - this.emit( - "field", - partName, - data3, - { - nameTruncated: false, - valueTruncated: partTruncated, - encoding: partEncoding, - mimeType: partType - } - ); - } - if (++parts === partsLimit) - this.emit("partsLimit"); - } - }; - this._bparser = new StreamSearch(`\r ---${boundary}`, ssCb); - this._writecb = null; - this._finalcb = null; - this.write(BUF_CRLF); - } - static detect(conType) { - return conType.type === "multipart" && conType.subtype === "form-data"; - } - _write(chunk, enc2, cb) { - this._writecb = cb; - this._bparser.push(chunk, 0); - if (this._writecb) - callAndUnsetCb(this); - } - _destroy(err, cb) { - this._hparser = null; - this._bparser = ignoreData; - if (!err) - err = checkEndState(this); - const fileStream = this._fileStream; - if (fileStream) { - this._fileStream = null; - fileStream.destroy(err); - } - cb(err); - } - _final(cb) { - this._bparser.destroy(); - if (!this._complete) - return cb(new Error("Unexpected end of form")); - if (this._fileEndsLeft) - this._finalcb = finalcb.bind(null, this, cb); - else - finalcb(this, cb); - } - }; - function finalcb(self2, cb, err) { - if (err) - return cb(err); - err = checkEndState(self2); - cb(err); - } - function checkEndState(self2) { - if (self2._hparser) - return new Error("Malformed part header"); - const fileStream = self2._fileStream; - if (fileStream) { - self2._fileStream = null; - fileStream.destroy(new Error("Unexpected end of file")); - } - if (!self2._complete) - return new Error("Unexpected end of form"); - } - var TOKEN = [ - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 1, - 0, - 1, - 1, - 1, - 1, - 1, - 0, - 0, - 1, - 1, - 0, - 1, - 1, - 0, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 0, - 0, - 0, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 0, - 1, - 0, - 1, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0 - ]; - var FIELD_VCHAR = [ - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 1, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 0, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1 - ]; - module.exports = Multipart; - } -}); - -// node_modules/.pnpm/busboy@1.6.0/node_modules/busboy/lib/types/urlencoded.js -var require_urlencoded2 = __commonJS({ - "node_modules/.pnpm/busboy@1.6.0/node_modules/busboy/lib/types/urlencoded.js"(exports, module) { - "use strict"; - var { Writable } = __require("stream"); - var { getDecoder } = require_utils4(); - var URLEncoded = class extends Writable { - constructor(cfg) { - const streamOpts = { - autoDestroy: true, - emitClose: true, - highWaterMark: typeof cfg.highWaterMark === "number" ? cfg.highWaterMark : void 0 - }; - super(streamOpts); - let charset = cfg.defCharset || "utf8"; - if (cfg.conType.params && typeof cfg.conType.params.charset === "string") - charset = cfg.conType.params.charset; - this.charset = charset; - const limits = cfg.limits; - this.fieldSizeLimit = limits && typeof limits.fieldSize === "number" ? limits.fieldSize : 1 * 1024 * 1024; - this.fieldsLimit = limits && typeof limits.fields === "number" ? limits.fields : Infinity; - this.fieldNameSizeLimit = limits && typeof limits.fieldNameSize === "number" ? limits.fieldNameSize : 100; - this._inKey = true; - this._keyTrunc = false; - this._valTrunc = false; - this._bytesKey = 0; - this._bytesVal = 0; - this._fields = 0; - this._key = ""; - this._val = ""; - this._byte = -2; - this._lastPos = 0; - this._encode = 0; - this._decoder = getDecoder(charset); - } - static detect(conType) { - return conType.type === "application" && conType.subtype === "x-www-form-urlencoded"; - } - _write(chunk, enc2, cb) { - if (this._fields >= this.fieldsLimit) - return cb(); - let i5 = 0; - const len = chunk.length; - this._lastPos = 0; - if (this._byte !== -2) { - i5 = readPctEnc(this, chunk, i5, len); - if (i5 === -1) - return cb(new Error("Malformed urlencoded form")); - if (i5 >= len) - return cb(); - if (this._inKey) - ++this._bytesKey; - else - ++this._bytesVal; - } - main: - while (i5 < len) { - if (this._inKey) { - i5 = skipKeyBytes(this, chunk, i5, len); - while (i5 < len) { - switch (chunk[i5]) { - case 61: - if (this._lastPos < i5) - this._key += chunk.latin1Slice(this._lastPos, i5); - this._lastPos = ++i5; - this._key = this._decoder(this._key, this._encode); - this._encode = 0; - this._inKey = false; - continue main; - case 38: - if (this._lastPos < i5) - this._key += chunk.latin1Slice(this._lastPos, i5); - this._lastPos = ++i5; - this._key = this._decoder(this._key, this._encode); - this._encode = 0; - if (this._bytesKey > 0) { - this.emit( - "field", - this._key, - "", - { - nameTruncated: this._keyTrunc, - valueTruncated: false, - encoding: this.charset, - mimeType: "text/plain" - } - ); - } - this._key = ""; - this._val = ""; - this._keyTrunc = false; - this._valTrunc = false; - this._bytesKey = 0; - this._bytesVal = 0; - if (++this._fields >= this.fieldsLimit) { - this.emit("fieldsLimit"); - return cb(); - } - continue; - case 43: - if (this._lastPos < i5) - this._key += chunk.latin1Slice(this._lastPos, i5); - this._key += " "; - this._lastPos = i5 + 1; - break; - case 37: - if (this._encode === 0) - this._encode = 1; - if (this._lastPos < i5) - this._key += chunk.latin1Slice(this._lastPos, i5); - this._lastPos = i5 + 1; - this._byte = -1; - i5 = readPctEnc(this, chunk, i5 + 1, len); - if (i5 === -1) - return cb(new Error("Malformed urlencoded form")); - if (i5 >= len) - return cb(); - ++this._bytesKey; - i5 = skipKeyBytes(this, chunk, i5, len); - continue; - } - ++i5; - ++this._bytesKey; - i5 = skipKeyBytes(this, chunk, i5, len); - } - if (this._lastPos < i5) - this._key += chunk.latin1Slice(this._lastPos, i5); - } else { - i5 = skipValBytes(this, chunk, i5, len); - while (i5 < len) { - switch (chunk[i5]) { - case 38: - if (this._lastPos < i5) - this._val += chunk.latin1Slice(this._lastPos, i5); - this._lastPos = ++i5; - this._inKey = true; - this._val = this._decoder(this._val, this._encode); - this._encode = 0; - if (this._bytesKey > 0 || this._bytesVal > 0) { - this.emit( - "field", - this._key, - this._val, - { - nameTruncated: this._keyTrunc, - valueTruncated: this._valTrunc, - encoding: this.charset, - mimeType: "text/plain" - } - ); - } - this._key = ""; - this._val = ""; - this._keyTrunc = false; - this._valTrunc = false; - this._bytesKey = 0; - this._bytesVal = 0; - if (++this._fields >= this.fieldsLimit) { - this.emit("fieldsLimit"); - return cb(); - } - continue main; - case 43: - if (this._lastPos < i5) - this._val += chunk.latin1Slice(this._lastPos, i5); - this._val += " "; - this._lastPos = i5 + 1; - break; - case 37: - if (this._encode === 0) - this._encode = 1; - if (this._lastPos < i5) - this._val += chunk.latin1Slice(this._lastPos, i5); - this._lastPos = i5 + 1; - this._byte = -1; - i5 = readPctEnc(this, chunk, i5 + 1, len); - if (i5 === -1) - return cb(new Error("Malformed urlencoded form")); - if (i5 >= len) - return cb(); - ++this._bytesVal; - i5 = skipValBytes(this, chunk, i5, len); - continue; - } - ++i5; - ++this._bytesVal; - i5 = skipValBytes(this, chunk, i5, len); - } - if (this._lastPos < i5) - this._val += chunk.latin1Slice(this._lastPos, i5); - } - } - cb(); - } - _final(cb) { - if (this._byte !== -2) - return cb(new Error("Malformed urlencoded form")); - if (!this._inKey || this._bytesKey > 0 || this._bytesVal > 0) { - if (this._inKey) - this._key = this._decoder(this._key, this._encode); - else - this._val = this._decoder(this._val, this._encode); - this.emit( - "field", - this._key, - this._val, - { - nameTruncated: this._keyTrunc, - valueTruncated: this._valTrunc, - encoding: this.charset, - mimeType: "text/plain" - } - ); - } - cb(); - } - }; - function readPctEnc(self2, chunk, pos, len) { - if (pos >= len) - return len; - if (self2._byte === -1) { - const hexUpper = HEX_VALUES[chunk[pos++]]; - if (hexUpper === -1) - return -1; - if (hexUpper >= 8) - self2._encode = 2; - if (pos < len) { - const hexLower = HEX_VALUES[chunk[pos++]]; - if (hexLower === -1) - return -1; - if (self2._inKey) - self2._key += String.fromCharCode((hexUpper << 4) + hexLower); - else - self2._val += String.fromCharCode((hexUpper << 4) + hexLower); - self2._byte = -2; - self2._lastPos = pos; - } else { - self2._byte = hexUpper; - } - } else { - const hexLower = HEX_VALUES[chunk[pos++]]; - if (hexLower === -1) - return -1; - if (self2._inKey) - self2._key += String.fromCharCode((self2._byte << 4) + hexLower); - else - self2._val += String.fromCharCode((self2._byte << 4) + hexLower); - self2._byte = -2; - self2._lastPos = pos; - } - return pos; - } - function skipKeyBytes(self2, chunk, pos, len) { - if (self2._bytesKey > self2.fieldNameSizeLimit) { - if (!self2._keyTrunc) { - if (self2._lastPos < pos) - self2._key += chunk.latin1Slice(self2._lastPos, pos - 1); - } - self2._keyTrunc = true; - for (; pos < len; ++pos) { - const code = chunk[pos]; - if (code === 61 || code === 38) - break; - ++self2._bytesKey; - } - self2._lastPos = pos; - } - return pos; - } - function skipValBytes(self2, chunk, pos, len) { - if (self2._bytesVal > self2.fieldSizeLimit) { - if (!self2._valTrunc) { - if (self2._lastPos < pos) - self2._val += chunk.latin1Slice(self2._lastPos, pos - 1); - } - self2._valTrunc = true; - for (; pos < len; ++pos) { - if (chunk[pos] === 38) - break; - ++self2._bytesVal; - } - self2._lastPos = pos; - } - return pos; - } - var HEX_VALUES = [ - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - 0, - 1, - 2, - 3, - 4, - 5, - 6, - 7, - 8, - 9, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - 10, - 11, - 12, - 13, - 14, - 15, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - 10, - 11, - 12, - 13, - 14, - 15, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1, - -1 - ]; - module.exports = URLEncoded; - } -}); - -// node_modules/.pnpm/busboy@1.6.0/node_modules/busboy/lib/index.js -var require_lib3 = __commonJS({ - "node_modules/.pnpm/busboy@1.6.0/node_modules/busboy/lib/index.js"(exports, module) { - "use strict"; - var { parseContentType } = require_utils4(); - function getInstance(cfg) { - const headers = cfg.headers; - const conType = parseContentType(headers["content-type"]); - if (!conType) - throw new Error("Malformed content type"); - for (const type of TYPES) { - const matched = type.detect(conType); - if (!matched) - continue; - const instanceCfg = { - limits: cfg.limits, - headers, - conType, - highWaterMark: void 0, - fileHwm: void 0, - defCharset: void 0, - defParamCharset: void 0, - preservePath: false - }; - if (cfg.highWaterMark) - instanceCfg.highWaterMark = cfg.highWaterMark; - if (cfg.fileHwm) - instanceCfg.fileHwm = cfg.fileHwm; - instanceCfg.defCharset = cfg.defCharset; - instanceCfg.defParamCharset = cfg.defParamCharset; - instanceCfg.preservePath = cfg.preservePath; - return new type(instanceCfg); - } - throw new Error(`Unsupported content type: ${headers["content-type"]}`); - } - var TYPES = [ - require_multipart(), - require_urlencoded2() - ].filter(function(typemod) { - return typeof typemod.detect === "function"; - }); - module.exports = (cfg) => { - if (typeof cfg !== "object" || cfg === null) - cfg = {}; - if (typeof cfg.headers !== "object" || cfg.headers === null || typeof cfg.headers["content-type"] !== "string") { - throw new Error("Missing Content-Type"); - } - return getInstance(cfg); - }; - } -}); - -// node_modules/.pnpm/append-field@1.0.0/node_modules/append-field/lib/parse-path.js -var require_parse_path = __commonJS({ - "node_modules/.pnpm/append-field@1.0.0/node_modules/append-field/lib/parse-path.js"(exports, module) { - var reFirstKey = /^[^\[]*/; - var reDigitPath = /^\[(\d+)\]/; - var reNormalPath = /^\[([^\]]+)\]/; - function parsePath(key) { - function failure() { - return [{ type: "object", key, last: true }]; - } - var firstKey = reFirstKey.exec(key)[0]; - if (!firstKey) return failure(); - var len = key.length; - var pos = firstKey.length; - var tail = { type: "object", key: firstKey }; - var steps = [tail]; - while (pos < len) { - var m5; - if (key[pos] === "[" && key[pos + 1] === "]") { - pos += 2; - tail.append = true; - if (pos !== len) return failure(); - continue; - } - m5 = reDigitPath.exec(key.substring(pos)); - if (m5 !== null) { - pos += m5[0].length; - tail.nextType = "array"; - tail = { type: "array", key: parseInt(m5[1], 10) }; - steps.push(tail); - continue; - } - m5 = reNormalPath.exec(key.substring(pos)); - if (m5 !== null) { - pos += m5[0].length; - tail.nextType = "object"; - tail = { type: "object", key: m5[1] }; - steps.push(tail); - continue; - } - return failure(); - } - tail.last = true; - return steps; - } - module.exports = parsePath; - } -}); - -// node_modules/.pnpm/append-field@1.0.0/node_modules/append-field/lib/set-value.js -var require_set_value = __commonJS({ - "node_modules/.pnpm/append-field@1.0.0/node_modules/append-field/lib/set-value.js"(exports, module) { - function valueType(value) { - if (value === void 0) return "undefined"; - if (Array.isArray(value)) return "array"; - if (typeof value === "object") return "object"; - return "scalar"; - } - function setLastValue(context, step, currentValue, entryValue) { - switch (valueType(currentValue)) { - case "undefined": - if (step.append) { - context[step.key] = [entryValue]; - } else { - context[step.key] = entryValue; - } - break; - case "array": - context[step.key].push(entryValue); - break; - case "object": - return setLastValue(currentValue, { type: "object", key: "", last: true }, currentValue[""], entryValue); - case "scalar": - context[step.key] = [context[step.key], entryValue]; - break; - } - return context; - } - function setValue(context, step, currentValue, entryValue) { - if (step.last) return setLastValue(context, step, currentValue, entryValue); - var obj; - switch (valueType(currentValue)) { - case "undefined": - if (step.nextType === "array") { - context[step.key] = []; - } else { - context[step.key] = /* @__PURE__ */ Object.create(null); - } - return context[step.key]; - case "object": - return context[step.key]; - case "array": - if (step.nextType === "array") { - return currentValue; - } - obj = /* @__PURE__ */ Object.create(null); - context[step.key] = obj; - currentValue.forEach(function(item, i5) { - if (item !== void 0) obj["" + i5] = item; - }); - return obj; - case "scalar": - obj = /* @__PURE__ */ Object.create(null); - obj[""] = currentValue; - context[step.key] = obj; - return obj; - } - } - module.exports = setValue; - } -}); - -// node_modules/.pnpm/append-field@1.0.0/node_modules/append-field/index.js -var require_append_field = __commonJS({ - "node_modules/.pnpm/append-field@1.0.0/node_modules/append-field/index.js"(exports, module) { - var parsePath = require_parse_path(); - var setValue = require_set_value(); - function appendField(store, key, value) { - var steps = parsePath(key); - steps.reduce(function(context, step) { - return setValue(context, step, context[step.key], value); - }, store); - } - module.exports = appendField; - } -}); - -// node_modules/.pnpm/multer@2.1.1/node_modules/multer/lib/counter.js -var require_counter = __commonJS({ - "node_modules/.pnpm/multer@2.1.1/node_modules/multer/lib/counter.js"(exports, module) { - var EventEmitter5 = __require("events").EventEmitter; - function Counter() { - EventEmitter5.call(this); - this.value = 0; - } - Counter.prototype = Object.create(EventEmitter5.prototype); - Counter.prototype.increment = function increment2() { - this.value++; - }; - Counter.prototype.decrement = function decrement() { - if (--this.value === 0) this.emit("zero"); - }; - Counter.prototype.isZero = function isZero() { - return this.value === 0; - }; - Counter.prototype.onceZero = function onceZero(fn) { - if (this.isZero()) return fn(); - this.once("zero", fn); - }; - module.exports = Counter; - } -}); - -// node_modules/.pnpm/multer@2.1.1/node_modules/multer/lib/multer-error.js -var require_multer_error = __commonJS({ - "node_modules/.pnpm/multer@2.1.1/node_modules/multer/lib/multer-error.js"(exports, module) { - var util2 = __require("util"); - var errorMessages = { - LIMIT_PART_COUNT: "Too many parts", - LIMIT_FILE_SIZE: "File too large", - LIMIT_FILE_COUNT: "Too many files", - LIMIT_FIELD_KEY: "Field name too long", - LIMIT_FIELD_VALUE: "Field value too long", - LIMIT_FIELD_COUNT: "Too many fields", - LIMIT_UNEXPECTED_FILE: "Unexpected field", - MISSING_FIELD_NAME: "Field name missing" - }; - function MulterError(code, field) { - Error.captureStackTrace(this, this.constructor); - this.name = this.constructor.name; - this.message = errorMessages[code]; - this.code = code; - if (field) this.field = field; - } - util2.inherits(MulterError, Error); - module.exports = MulterError; - } -}); - -// node_modules/.pnpm/multer@2.1.1/node_modules/multer/lib/file-appender.js -var require_file_appender = __commonJS({ - "node_modules/.pnpm/multer@2.1.1/node_modules/multer/lib/file-appender.js"(exports, module) { - function arrayRemove(arr, item) { - var idx = arr.indexOf(item); - if (~idx) arr.splice(idx, 1); - } - function FileAppender(strategy, req) { - this.strategy = strategy; - this.req = req; - switch (strategy) { - case "NONE": - break; - case "VALUE": - break; - case "ARRAY": - req.files = []; - break; - case "OBJECT": - req.files = /* @__PURE__ */ Object.create(null); - break; - default: - throw new Error("Unknown file strategy: " + strategy); - } - } - FileAppender.prototype.insertPlaceholder = function(file2) { - var placeholder = { - fieldname: file2.fieldname - }; - switch (this.strategy) { - case "NONE": - break; - case "VALUE": - break; - case "ARRAY": - this.req.files.push(placeholder); - break; - case "OBJECT": - if (this.req.files[file2.fieldname]) { - this.req.files[file2.fieldname].push(placeholder); - } else { - this.req.files[file2.fieldname] = [placeholder]; - } - break; - } - return placeholder; - }; - FileAppender.prototype.removePlaceholder = function(placeholder) { - switch (this.strategy) { - case "NONE": - break; - case "VALUE": - break; - case "ARRAY": - arrayRemove(this.req.files, placeholder); - break; - case "OBJECT": - if (this.req.files[placeholder.fieldname].length === 1) { - delete this.req.files[placeholder.fieldname]; - } else { - arrayRemove(this.req.files[placeholder.fieldname], placeholder); - } - break; - } - }; - FileAppender.prototype.replacePlaceholder = function(placeholder, file2) { - if (this.strategy === "VALUE") { - this.req.file = file2; - return; - } - delete placeholder.fieldname; - Object.assign(placeholder, file2); - }; - module.exports = FileAppender; - } -}); - -// node_modules/.pnpm/multer@2.1.1/node_modules/multer/lib/remove-uploaded-files.js -var require_remove_uploaded_files = __commonJS({ - "node_modules/.pnpm/multer@2.1.1/node_modules/multer/lib/remove-uploaded-files.js"(exports, module) { - function removeUploadedFiles(uploadedFiles, remove, cb) { - var length = uploadedFiles.length; - var errors = []; - if (length === 0) return cb(null, errors); - function handleFile(idx) { - var file2 = uploadedFiles[idx]; - remove(file2, function(err) { - if (err) { - err.file = file2; - err.field = file2.fieldname; - errors.push(err); - } - if (idx < length - 1) { - setImmediate(function() { - handleFile(idx + 1); - }); - } else { - cb(null, errors); - } - }); - } - handleFile(0); - } - module.exports = removeUploadedFiles; - } -}); - -// node_modules/.pnpm/multer@2.1.1/node_modules/multer/lib/make-middleware.js -var require_make_middleware = __commonJS({ - "node_modules/.pnpm/multer@2.1.1/node_modules/multer/lib/make-middleware.js"(exports, module) { - var is2 = require_type_is2(); - var Busboy = require_lib3(); - var appendField = require_append_field(); - var Counter = require_counter(); - var MulterError = require_multer_error(); - var FileAppender = require_file_appender(); - var removeUploadedFiles = require_remove_uploaded_files(); - function drainStream(stream) { - stream.on("readable", () => { - while (stream.read() !== null) { - } - }); - } - function makeMiddleware(setup) { - return function multerMiddleware(req, res, next) { - if (!is2(req, ["multipart"])) return next(); - var options = setup(); - var limits = options.limits; - var storage = options.storage; - var fileFilter = options.fileFilter; - var fileStrategy = options.fileStrategy; - var preservePath = options.preservePath; - var defParamCharset = options.defParamCharset; - req.body = /* @__PURE__ */ Object.create(null); - var busboy; - var appender = null; - var isDone = false; - var readFinished = false; - var errorOccured = false; - var pendingWrites = new Counter(); - var uploadedFiles = []; - function done(err) { - var called = false; - function onFinished() { - if (called) return; - called = true; - next(err); - } - if (isDone) return; - isDone = true; - if (busboy) { - req.unpipe(busboy); - setImmediate(() => { - busboy.removeAllListeners(); - }); - } - drainStream(req); - req.resume(); - if (err && req.readable && !req.destroyed) { - req.once("end", onFinished); - req.once("error", onFinished); - req.once("close", onFinished); - return; - } - next(err); - } - function indicateDone() { - if (readFinished && pendingWrites.isZero() && !errorOccured) done(); - } - function abortWithError(uploadError, skipPendingWait) { - if (errorOccured) return; - errorOccured = true; - function finishAbort() { - function remove(file2, cb) { - storage._removeFile(req, file2, cb); - } - removeUploadedFiles(uploadedFiles, remove, function(err, storageErrors) { - if (err) return done(err); - uploadError.storageErrors = storageErrors; - done(uploadError); - }); - } - if (skipPendingWait) { - finishAbort(); - } else { - pendingWrites.onceZero(finishAbort); - } - } - function abortWithCode(code, optionalField) { - abortWithError(new MulterError(code, optionalField)); - } - function handleRequestFailure(err) { - if (isDone) return; - if (busboy) { - req.unpipe(busboy); - busboy.destroy(err); - } - abortWithError(err, true); - } - req.on("error", function(err) { - handleRequestFailure(err || new Error("Request error")); - }); - req.on("aborted", function() { - handleRequestFailure(new Error("Request aborted")); - }); - req.on("close", function() { - if (req.readableEnded) return; - handleRequestFailure(new Error("Request closed")); - }); - try { - busboy = Busboy({ - headers: req.headers, - limits, - preservePath, - defParamCharset - }); - } catch (err) { - return next(err); - } - appender = new FileAppender(fileStrategy, req); - busboy.on("field", function(fieldname, value, { nameTruncated, valueTruncated }) { - if (fieldname == null) return abortWithCode("MISSING_FIELD_NAME"); - if (nameTruncated) return abortWithCode("LIMIT_FIELD_KEY"); - if (valueTruncated) return abortWithCode("LIMIT_FIELD_VALUE", fieldname); - if (limits && Object.prototype.hasOwnProperty.call(limits, "fieldNameSize")) { - if (fieldname.length > limits.fieldNameSize) return abortWithCode("LIMIT_FIELD_KEY"); - } - appendField(req.body, fieldname, value); - }); - busboy.on("file", function(fieldname, fileStream, { filename, encoding, mimeType }) { - var pendingWritesIncremented = false; - fileStream.on("error", function(err) { - if (pendingWritesIncremented) { - pendingWrites.decrement(); - } - abortWithError(err); - }); - if (fieldname == null) return abortWithCode("MISSING_FIELD_NAME"); - if (!filename) return fileStream.resume(); - if (limits && Object.prototype.hasOwnProperty.call(limits, "fieldNameSize")) { - if (fieldname.length > limits.fieldNameSize) return abortWithCode("LIMIT_FIELD_KEY"); - } - var file2 = { - fieldname, - originalname: filename, - encoding, - mimetype: mimeType - }; - var placeholder = appender.insertPlaceholder(file2); - fileFilter(req, file2, function(err, includeFile) { - if (errorOccured) { - appender.removePlaceholder(placeholder); - return fileStream.resume(); - } - if (err) { - appender.removePlaceholder(placeholder); - return abortWithError(err); - } - if (!includeFile) { - appender.removePlaceholder(placeholder); - return fileStream.resume(); - } - var aborting = false; - pendingWritesIncremented = true; - pendingWrites.increment(); - Object.defineProperty(file2, "stream", { - configurable: true, - enumerable: false, - value: fileStream - }); - fileStream.on("limit", function() { - aborting = true; - abortWithCode("LIMIT_FILE_SIZE", fieldname); - }); - storage._handleFile(req, file2, function(err2, info2) { - if (aborting) { - appender.removePlaceholder(placeholder); - uploadedFiles.push({ ...file2, ...info2 }); - return pendingWrites.decrement(); - } - if (err2) { - appender.removePlaceholder(placeholder); - pendingWrites.decrement(); - return abortWithError(err2); - } - var fileInfo = { ...file2, ...info2 }; - appender.replacePlaceholder(placeholder, fileInfo); - uploadedFiles.push(fileInfo); - pendingWrites.decrement(); - indicateDone(); - }); - }); - }); - busboy.on("error", function(err) { - abortWithError(err); - }); - busboy.on("partsLimit", function() { - abortWithCode("LIMIT_PART_COUNT"); - }); - busboy.on("filesLimit", function() { - abortWithCode("LIMIT_FILE_COUNT"); - }); - busboy.on("fieldsLimit", function() { - abortWithCode("LIMIT_FIELD_COUNT"); - }); - busboy.on("close", function() { - readFinished = true; - indicateDone(); - }); - req.pipe(busboy); - }; - } - module.exports = makeMiddleware; - } -}); - -// node_modules/.pnpm/multer@2.1.1/node_modules/multer/storage/disk.js -var require_disk = __commonJS({ - "node_modules/.pnpm/multer@2.1.1/node_modules/multer/storage/disk.js"(exports, module) { - var fs41 = __require("fs"); - var os24 = __require("os"); - var path53 = __require("path"); - var crypto6 = __require("crypto"); - function getFilename(req, file2, cb) { - crypto6.randomBytes(16, function(err, raw) { - cb(err, err ? void 0 : raw.toString("hex")); - }); - } - function getDestination(req, file2, cb) { - cb(null, os24.tmpdir()); - } - function DiskStorage(opts) { - this.getFilename = opts.filename || getFilename; - if (typeof opts.destination === "string") { - fs41.mkdirSync(opts.destination, { recursive: true }); - this.getDestination = function($0, $1, cb) { - cb(null, opts.destination); - }; - } else { - this.getDestination = opts.destination || getDestination; - } - } - DiskStorage.prototype._handleFile = function _handleFile(req, file2, cb) { - var that = this; - that.getDestination(req, file2, function(err, destination) { - if (err) return cb(err); - that.getFilename(req, file2, function(err2, filename) { - if (err2) return cb(err2); - var finalPath = path53.join(destination, filename); - var outStream = fs41.createWriteStream(finalPath); - file2.stream.pipe(outStream); - outStream.on("error", cb); - outStream.on("finish", function() { - cb(null, { - destination, - filename, - path: finalPath, - size: outStream.bytesWritten - }); - }); - }); - }); - }; - DiskStorage.prototype._removeFile = function _removeFile(req, file2, cb) { - var path54 = file2.path; - delete file2.destination; - delete file2.filename; - delete file2.path; - fs41.unlink(path54, cb); - }; - module.exports = function(opts) { - return new DiskStorage(opts); - }; - } -}); - -// node_modules/.pnpm/readable-stream@3.6.2/node_modules/readable-stream/lib/internal/streams/stream.js -var require_stream2 = __commonJS({ - "node_modules/.pnpm/readable-stream@3.6.2/node_modules/readable-stream/lib/internal/streams/stream.js"(exports, module) { - module.exports = __require("stream"); - } -}); - -// node_modules/.pnpm/readable-stream@3.6.2/node_modules/readable-stream/lib/internal/streams/buffer_list.js -var require_buffer_list = __commonJS({ - "node_modules/.pnpm/readable-stream@3.6.2/node_modules/readable-stream/lib/internal/streams/buffer_list.js"(exports, module) { - "use strict"; - function ownKeys2(object2, enumerableOnly) { - var keys = Object.keys(object2); - if (Object.getOwnPropertySymbols) { - var symbols = Object.getOwnPropertySymbols(object2); - enumerableOnly && (symbols = symbols.filter(function(sym) { - return Object.getOwnPropertyDescriptor(object2, sym).enumerable; - })), keys.push.apply(keys, symbols); - } - return keys; - } - function _objectSpread(target) { - for (var i5 = 1; i5 < arguments.length; i5++) { - var source = null != arguments[i5] ? arguments[i5] : {}; - i5 % 2 ? ownKeys2(Object(source), true).forEach(function(key) { - _defineProperty(target, key, source[key]); - }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys2(Object(source)).forEach(function(key) { - Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); - }); - } - return target; - } - function _defineProperty(obj, key, value) { - key = _toPropertyKey(key); - if (key in obj) { - Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true }); - } else { - obj[key] = value; - } - return obj; - } - function _classCallCheck(instance, Constructor) { - if (!(instance instanceof Constructor)) { - throw new TypeError("Cannot call a class as a function"); - } - } - function _defineProperties(target, props) { - for (var i5 = 0; i5 < props.length; i5++) { - var descriptor = props[i5]; - descriptor.enumerable = descriptor.enumerable || false; - descriptor.configurable = true; - if ("value" in descriptor) descriptor.writable = true; - Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); - } - } - function _createClass(Constructor, protoProps, staticProps) { - if (protoProps) _defineProperties(Constructor.prototype, protoProps); - if (staticProps) _defineProperties(Constructor, staticProps); - Object.defineProperty(Constructor, "prototype", { writable: false }); - return Constructor; - } - function _toPropertyKey(arg) { - var key = _toPrimitive(arg, "string"); - return typeof key === "symbol" ? key : String(key); - } - function _toPrimitive(input, hint) { - if (typeof input !== "object" || input === null) return input; - var prim = input[Symbol.toPrimitive]; - if (prim !== void 0) { - var res = prim.call(input, hint || "default"); - if (typeof res !== "object") return res; - throw new TypeError("@@toPrimitive must return a primitive value."); - } - return (hint === "string" ? String : Number)(input); - } - var _require = __require("buffer"); - var Buffer2 = _require.Buffer; - var _require2 = __require("util"); - var inspect = _require2.inspect; - var custom3 = inspect && inspect.custom || "inspect"; - function copyBuffer(src, target, offset) { - Buffer2.prototype.copy.call(src, target, offset); - } - module.exports = /* @__PURE__ */ (function() { - function BufferList() { - _classCallCheck(this, BufferList); - this.head = null; - this.tail = null; - this.length = 0; - } - _createClass(BufferList, [{ - key: "push", - value: function push(v5) { - var entry = { - data: v5, - next: null - }; - if (this.length > 0) this.tail.next = entry; - else this.head = entry; - this.tail = entry; - ++this.length; - } - }, { - key: "unshift", - value: function unshift(v5) { - var entry = { - data: v5, - next: this.head - }; - if (this.length === 0) this.tail = entry; - this.head = entry; - ++this.length; - } - }, { - key: "shift", - value: function shift() { - if (this.length === 0) return; - var ret = this.head.data; - if (this.length === 1) this.head = this.tail = null; - else this.head = this.head.next; - --this.length; - return ret; - } - }, { - key: "clear", - value: function clear() { - this.head = this.tail = null; - this.length = 0; - } - }, { - key: "join", - value: function join4(s5) { - if (this.length === 0) return ""; - var p5 = this.head; - var ret = "" + p5.data; - while (p5 = p5.next) ret += s5 + p5.data; - return ret; - } - }, { - key: "concat", - value: function concat2(n5) { - if (this.length === 0) return Buffer2.alloc(0); - var ret = Buffer2.allocUnsafe(n5 >>> 0); - var p5 = this.head; - var i5 = 0; - while (p5) { - copyBuffer(p5.data, ret, i5); - i5 += p5.data.length; - p5 = p5.next; - } - return ret; - } - // Consumes a specified amount of bytes or characters from the buffered data. - }, { - key: "consume", - value: function consume(n5, hasStrings) { - var ret; - if (n5 < this.head.data.length) { - ret = this.head.data.slice(0, n5); - this.head.data = this.head.data.slice(n5); - } else if (n5 === this.head.data.length) { - ret = this.shift(); - } else { - ret = hasStrings ? this._getString(n5) : this._getBuffer(n5); - } - return ret; - } - }, { - key: "first", - value: function first() { - return this.head.data; - } - // Consumes a specified amount of characters from the buffered data. - }, { - key: "_getString", - value: function _getString(n5) { - var p5 = this.head; - var c5 = 1; - var ret = p5.data; - n5 -= ret.length; - while (p5 = p5.next) { - var str = p5.data; - var nb = n5 > str.length ? str.length : n5; - if (nb === str.length) ret += str; - else ret += str.slice(0, n5); - n5 -= nb; - if (n5 === 0) { - if (nb === str.length) { - ++c5; - if (p5.next) this.head = p5.next; - else this.head = this.tail = null; - } else { - this.head = p5; - p5.data = str.slice(nb); - } - break; - } - ++c5; - } - this.length -= c5; - return ret; - } - // Consumes a specified amount of bytes from the buffered data. - }, { - key: "_getBuffer", - value: function _getBuffer(n5) { - var ret = Buffer2.allocUnsafe(n5); - var p5 = this.head; - var c5 = 1; - p5.data.copy(ret); - n5 -= p5.data.length; - while (p5 = p5.next) { - var buf = p5.data; - var nb = n5 > buf.length ? buf.length : n5; - buf.copy(ret, ret.length - n5, 0, nb); - n5 -= nb; - if (n5 === 0) { - if (nb === buf.length) { - ++c5; - if (p5.next) this.head = p5.next; - else this.head = this.tail = null; - } else { - this.head = p5; - p5.data = buf.slice(nb); - } - break; - } - ++c5; - } - this.length -= c5; - return ret; - } - // Make sure the linked list only shows the minimal necessary information. - }, { - key: custom3, - value: function value(_, options) { - return inspect(this, _objectSpread(_objectSpread({}, options), {}, { - // Only inspect one level. - depth: 0, - // It should not recurse. - customInspect: false - })); - } - }]); - return BufferList; - })(); - } -}); - -// node_modules/.pnpm/readable-stream@3.6.2/node_modules/readable-stream/lib/internal/streams/destroy.js -var require_destroy = __commonJS({ - "node_modules/.pnpm/readable-stream@3.6.2/node_modules/readable-stream/lib/internal/streams/destroy.js"(exports, module) { - "use strict"; - function destroy(err, cb) { - var _this = this; - var readableDestroyed = this._readableState && this._readableState.destroyed; - var writableDestroyed = this._writableState && this._writableState.destroyed; - if (readableDestroyed || writableDestroyed) { - if (cb) { - cb(err); - } else if (err) { - if (!this._writableState) { - process.nextTick(emitErrorNT, this, err); - } else if (!this._writableState.errorEmitted) { - this._writableState.errorEmitted = true; - process.nextTick(emitErrorNT, this, err); - } - } - return this; - } - if (this._readableState) { - this._readableState.destroyed = true; - } - if (this._writableState) { - this._writableState.destroyed = true; - } - this._destroy(err || null, function(err2) { - if (!cb && err2) { - if (!_this._writableState) { - process.nextTick(emitErrorAndCloseNT, _this, err2); - } else if (!_this._writableState.errorEmitted) { - _this._writableState.errorEmitted = true; - process.nextTick(emitErrorAndCloseNT, _this, err2); - } else { - process.nextTick(emitCloseNT, _this); - } - } else if (cb) { - process.nextTick(emitCloseNT, _this); - cb(err2); - } else { - process.nextTick(emitCloseNT, _this); - } - }); - return this; - } - function emitErrorAndCloseNT(self2, err) { - emitErrorNT(self2, err); - emitCloseNT(self2); - } - function emitCloseNT(self2) { - if (self2._writableState && !self2._writableState.emitClose) return; - if (self2._readableState && !self2._readableState.emitClose) return; - self2.emit("close"); - } - function undestroy() { - if (this._readableState) { - this._readableState.destroyed = false; - this._readableState.reading = false; - this._readableState.ended = false; - this._readableState.endEmitted = false; - } - if (this._writableState) { - this._writableState.destroyed = false; - this._writableState.ended = false; - this._writableState.ending = false; - this._writableState.finalCalled = false; - this._writableState.prefinished = false; - this._writableState.finished = false; - this._writableState.errorEmitted = false; - } - } - function emitErrorNT(self2, err) { - self2.emit("error", err); - } - function errorOrDestroy(stream, err) { - var rState = stream._readableState; - var wState = stream._writableState; - if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err); - else stream.emit("error", err); - } - module.exports = { - destroy, - undestroy, - errorOrDestroy - }; - } -}); - -// node_modules/.pnpm/readable-stream@3.6.2/node_modules/readable-stream/errors.js -var require_errors2 = __commonJS({ - "node_modules/.pnpm/readable-stream@3.6.2/node_modules/readable-stream/errors.js"(exports, module) { - "use strict"; - var codes = {}; - function createErrorType(code, message2, Base) { - if (!Base) { - Base = Error; - } - function getMessage(arg1, arg2, arg3) { - if (typeof message2 === "string") { - return message2; - } else { - return message2(arg1, arg2, arg3); - } - } - class NodeError extends Base { - constructor(arg1, arg2, arg3) { - super(getMessage(arg1, arg2, arg3)); - } - } - NodeError.prototype.name = Base.name; - NodeError.prototype.code = code; - codes[code] = NodeError; - } - function oneOf(expected, thing) { - if (Array.isArray(expected)) { - const len = expected.length; - expected = expected.map((i5) => String(i5)); - if (len > 2) { - return `one of ${thing} ${expected.slice(0, len - 1).join(", ")}, or ` + expected[len - 1]; - } else if (len === 2) { - return `one of ${thing} ${expected[0]} or ${expected[1]}`; - } else { - return `of ${thing} ${expected[0]}`; - } - } else { - return `of ${thing} ${String(expected)}`; - } - } - function startsWith(str, search, pos) { - return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; - } - function endsWith(str, search, this_len) { - if (this_len === void 0 || this_len > str.length) { - this_len = str.length; - } - return str.substring(this_len - search.length, this_len) === search; - } - function includes(str, search, start) { - if (typeof start !== "number") { - start = 0; - } - if (start + search.length > str.length) { - return false; - } else { - return str.indexOf(search, start) !== -1; - } - } - createErrorType("ERR_INVALID_OPT_VALUE", function(name, value) { - return 'The value "' + value + '" is invalid for option "' + name + '"'; - }, TypeError); - createErrorType("ERR_INVALID_ARG_TYPE", function(name, expected, actual) { - let determiner; - if (typeof expected === "string" && startsWith(expected, "not ")) { - determiner = "must not be"; - expected = expected.replace(/^not /, ""); - } else { - determiner = "must be"; - } - let msg; - if (endsWith(name, " argument")) { - msg = `The ${name} ${determiner} ${oneOf(expected, "type")}`; - } else { - const type = includes(name, ".") ? "property" : "argument"; - msg = `The "${name}" ${type} ${determiner} ${oneOf(expected, "type")}`; - } - msg += `. Received type ${typeof actual}`; - return msg; - }, TypeError); - createErrorType("ERR_STREAM_PUSH_AFTER_EOF", "stream.push() after EOF"); - createErrorType("ERR_METHOD_NOT_IMPLEMENTED", function(name) { - return "The " + name + " method is not implemented"; - }); - createErrorType("ERR_STREAM_PREMATURE_CLOSE", "Premature close"); - createErrorType("ERR_STREAM_DESTROYED", function(name) { - return "Cannot call " + name + " after a stream was destroyed"; - }); - createErrorType("ERR_MULTIPLE_CALLBACK", "Callback called multiple times"); - createErrorType("ERR_STREAM_CANNOT_PIPE", "Cannot pipe, not readable"); - createErrorType("ERR_STREAM_WRITE_AFTER_END", "write after end"); - createErrorType("ERR_STREAM_NULL_VALUES", "May not write null values to stream", TypeError); - createErrorType("ERR_UNKNOWN_ENCODING", function(arg) { - return "Unknown encoding: " + arg; - }, TypeError); - createErrorType("ERR_STREAM_UNSHIFT_AFTER_END_EVENT", "stream.unshift() after end event"); - module.exports.codes = codes; - } -}); - -// node_modules/.pnpm/readable-stream@3.6.2/node_modules/readable-stream/lib/internal/streams/state.js -var require_state = __commonJS({ - "node_modules/.pnpm/readable-stream@3.6.2/node_modules/readable-stream/lib/internal/streams/state.js"(exports, module) { - "use strict"; - var ERR_INVALID_OPT_VALUE = require_errors2().codes.ERR_INVALID_OPT_VALUE; - function highWaterMarkFrom(options, isDuplex, duplexKey) { - return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null; - } - function getHighWaterMark(state2, options, duplexKey, isDuplex) { - var hwm = highWaterMarkFrom(options, isDuplex, duplexKey); - if (hwm != null) { - if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) { - var name = isDuplex ? duplexKey : "highWaterMark"; - throw new ERR_INVALID_OPT_VALUE(name, hwm); - } - return Math.floor(hwm); - } - return state2.objectMode ? 16 : 16 * 1024; - } - module.exports = { - getHighWaterMark - }; - } -}); - -// node_modules/.pnpm/util-deprecate@1.0.2/node_modules/util-deprecate/node.js -var require_node2 = __commonJS({ - "node_modules/.pnpm/util-deprecate@1.0.2/node_modules/util-deprecate/node.js"(exports, module) { - module.exports = __require("util").deprecate; - } -}); - -// node_modules/.pnpm/readable-stream@3.6.2/node_modules/readable-stream/lib/_stream_writable.js -var require_stream_writable = __commonJS({ - "node_modules/.pnpm/readable-stream@3.6.2/node_modules/readable-stream/lib/_stream_writable.js"(exports, module) { - "use strict"; - module.exports = Writable; - function CorkedRequest(state2) { - var _this = this; - this.next = null; - this.entry = null; - this.finish = function() { - onCorkedFinish(_this, state2); - }; - } - var Duplex; - Writable.WritableState = WritableState; - var internalUtil = { - deprecate: require_node2() - }; - var Stream3 = require_stream2(); - var Buffer2 = __require("buffer").Buffer; - var OurUint8Array = (typeof global !== "undefined" ? global : typeof window !== "undefined" ? window : typeof self !== "undefined" ? self : {}).Uint8Array || function() { - }; - function _uint8ArrayToBuffer(chunk) { - return Buffer2.from(chunk); - } - function _isUint8Array(obj) { - return Buffer2.isBuffer(obj) || obj instanceof OurUint8Array; - } - var destroyImpl = require_destroy(); - var _require = require_state(); - var getHighWaterMark = _require.getHighWaterMark; - var _require$codes = require_errors2().codes; - var ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE; - var ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED; - var ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK; - var ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE; - var ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; - var ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES; - var ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END; - var ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING; - var errorOrDestroy = destroyImpl.errorOrDestroy; - require_inherits()(Writable, Stream3); - function nop() { - } - function WritableState(options, stream, isDuplex) { - Duplex = Duplex || require_stream_duplex(); - options = options || {}; - if (typeof isDuplex !== "boolean") isDuplex = stream instanceof Duplex; - this.objectMode = !!options.objectMode; - if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; - this.highWaterMark = getHighWaterMark(this, options, "writableHighWaterMark", isDuplex); - this.finalCalled = false; - this.needDrain = false; - this.ending = false; - this.ended = false; - this.finished = false; - this.destroyed = false; - var noDecode = options.decodeStrings === false; - this.decodeStrings = !noDecode; - this.defaultEncoding = options.defaultEncoding || "utf8"; - this.length = 0; - this.writing = false; - this.corked = 0; - this.sync = true; - this.bufferProcessing = false; - this.onwrite = function(er) { - onwrite(stream, er); - }; - this.writecb = null; - this.writelen = 0; - this.bufferedRequest = null; - this.lastBufferedRequest = null; - this.pendingcb = 0; - this.prefinished = false; - this.errorEmitted = false; - this.emitClose = options.emitClose !== false; - this.autoDestroy = !!options.autoDestroy; - this.bufferedRequestCount = 0; - this.corkedRequestsFree = new CorkedRequest(this); - } - WritableState.prototype.getBuffer = function getBuffer() { - var current = this.bufferedRequest; - var out = []; - while (current) { - out.push(current); - current = current.next; - } - return out; - }; - (function() { - try { - Object.defineProperty(WritableState.prototype, "buffer", { - get: internalUtil.deprecate(function writableStateBufferGetter() { - return this.getBuffer(); - }, "_writableState.buffer is deprecated. Use _writableState.getBuffer instead.", "DEP0003") - }); - } catch (_) { - } - })(); - var realHasInstance; - if (typeof Symbol === "function" && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === "function") { - realHasInstance = Function.prototype[Symbol.hasInstance]; - Object.defineProperty(Writable, Symbol.hasInstance, { - value: function value(object2) { - if (realHasInstance.call(this, object2)) return true; - if (this !== Writable) return false; - return object2 && object2._writableState instanceof WritableState; - } - }); - } else { - realHasInstance = function realHasInstance2(object2) { - return object2 instanceof this; - }; - } - function Writable(options) { - Duplex = Duplex || require_stream_duplex(); - var isDuplex = this instanceof Duplex; - if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options); - this._writableState = new WritableState(options, this, isDuplex); - this.writable = true; - if (options) { - if (typeof options.write === "function") this._write = options.write; - if (typeof options.writev === "function") this._writev = options.writev; - if (typeof options.destroy === "function") this._destroy = options.destroy; - if (typeof options.final === "function") this._final = options.final; - } - Stream3.call(this); - } - Writable.prototype.pipe = function() { - errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE()); - }; - function writeAfterEnd(stream, cb) { - var er = new ERR_STREAM_WRITE_AFTER_END(); - errorOrDestroy(stream, er); - process.nextTick(cb, er); - } - function validChunk(stream, state2, chunk, cb) { - var er; - if (chunk === null) { - er = new ERR_STREAM_NULL_VALUES(); - } else if (typeof chunk !== "string" && !state2.objectMode) { - er = new ERR_INVALID_ARG_TYPE("chunk", ["string", "Buffer"], chunk); - } - if (er) { - errorOrDestroy(stream, er); - process.nextTick(cb, er); - return false; - } - return true; - } - Writable.prototype.write = function(chunk, encoding, cb) { - var state2 = this._writableState; - var ret = false; - var isBuf = !state2.objectMode && _isUint8Array(chunk); - if (isBuf && !Buffer2.isBuffer(chunk)) { - chunk = _uint8ArrayToBuffer(chunk); - } - if (typeof encoding === "function") { - cb = encoding; - encoding = null; - } - if (isBuf) encoding = "buffer"; - else if (!encoding) encoding = state2.defaultEncoding; - if (typeof cb !== "function") cb = nop; - if (state2.ending) writeAfterEnd(this, cb); - else if (isBuf || validChunk(this, state2, chunk, cb)) { - state2.pendingcb++; - ret = writeOrBuffer(this, state2, isBuf, chunk, encoding, cb); - } - return ret; - }; - Writable.prototype.cork = function() { - this._writableState.corked++; - }; - Writable.prototype.uncork = function() { - var state2 = this._writableState; - if (state2.corked) { - state2.corked--; - if (!state2.writing && !state2.corked && !state2.bufferProcessing && state2.bufferedRequest) clearBuffer(this, state2); - } - }; - Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { - if (typeof encoding === "string") encoding = encoding.toLowerCase(); - if (!(["hex", "utf8", "utf-8", "ascii", "binary", "base64", "ucs2", "ucs-2", "utf16le", "utf-16le", "raw"].indexOf((encoding + "").toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding); - this._writableState.defaultEncoding = encoding; - return this; - }; - Object.defineProperty(Writable.prototype, "writableBuffer", { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get2() { - return this._writableState && this._writableState.getBuffer(); - } - }); - function decodeChunk(state2, chunk, encoding) { - if (!state2.objectMode && state2.decodeStrings !== false && typeof chunk === "string") { - chunk = Buffer2.from(chunk, encoding); - } - return chunk; - } - Object.defineProperty(Writable.prototype, "writableHighWaterMark", { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get2() { - return this._writableState.highWaterMark; - } - }); - function writeOrBuffer(stream, state2, isBuf, chunk, encoding, cb) { - if (!isBuf) { - var newChunk = decodeChunk(state2, chunk, encoding); - if (chunk !== newChunk) { - isBuf = true; - encoding = "buffer"; - chunk = newChunk; - } - } - var len = state2.objectMode ? 1 : chunk.length; - state2.length += len; - var ret = state2.length < state2.highWaterMark; - if (!ret) state2.needDrain = true; - if (state2.writing || state2.corked) { - var last = state2.lastBufferedRequest; - state2.lastBufferedRequest = { - chunk, - encoding, - isBuf, - callback: cb, - next: null - }; - if (last) { - last.next = state2.lastBufferedRequest; - } else { - state2.bufferedRequest = state2.lastBufferedRequest; - } - state2.bufferedRequestCount += 1; - } else { - doWrite(stream, state2, false, len, chunk, encoding, cb); - } - return ret; - } - function doWrite(stream, state2, writev, len, chunk, encoding, cb) { - state2.writelen = len; - state2.writecb = cb; - state2.writing = true; - state2.sync = true; - if (state2.destroyed) state2.onwrite(new ERR_STREAM_DESTROYED("write")); - else if (writev) stream._writev(chunk, state2.onwrite); - else stream._write(chunk, encoding, state2.onwrite); - state2.sync = false; - } - function onwriteError(stream, state2, sync, er, cb) { - --state2.pendingcb; - if (sync) { - process.nextTick(cb, er); - process.nextTick(finishMaybe, stream, state2); - stream._writableState.errorEmitted = true; - errorOrDestroy(stream, er); - } else { - cb(er); - stream._writableState.errorEmitted = true; - errorOrDestroy(stream, er); - finishMaybe(stream, state2); - } - } - function onwriteStateUpdate(state2) { - state2.writing = false; - state2.writecb = null; - state2.length -= state2.writelen; - state2.writelen = 0; - } - function onwrite(stream, er) { - var state2 = stream._writableState; - var sync = state2.sync; - var cb = state2.writecb; - if (typeof cb !== "function") throw new ERR_MULTIPLE_CALLBACK(); - onwriteStateUpdate(state2); - if (er) onwriteError(stream, state2, sync, er, cb); - else { - var finished = needFinish(state2) || stream.destroyed; - if (!finished && !state2.corked && !state2.bufferProcessing && state2.bufferedRequest) { - clearBuffer(stream, state2); - } - if (sync) { - process.nextTick(afterWrite, stream, state2, finished, cb); - } else { - afterWrite(stream, state2, finished, cb); - } - } - } - function afterWrite(stream, state2, finished, cb) { - if (!finished) onwriteDrain(stream, state2); - state2.pendingcb--; - cb(); - finishMaybe(stream, state2); - } - function onwriteDrain(stream, state2) { - if (state2.length === 0 && state2.needDrain) { - state2.needDrain = false; - stream.emit("drain"); - } - } - function clearBuffer(stream, state2) { - state2.bufferProcessing = true; - var entry = state2.bufferedRequest; - if (stream._writev && entry && entry.next) { - var l5 = state2.bufferedRequestCount; - var buffer2 = new Array(l5); - var holder = state2.corkedRequestsFree; - holder.entry = entry; - var count2 = 0; - var allBuffers = true; - while (entry) { - buffer2[count2] = entry; - if (!entry.isBuf) allBuffers = false; - entry = entry.next; - count2 += 1; - } - buffer2.allBuffers = allBuffers; - doWrite(stream, state2, true, state2.length, buffer2, "", holder.finish); - state2.pendingcb++; - state2.lastBufferedRequest = null; - if (holder.next) { - state2.corkedRequestsFree = holder.next; - holder.next = null; - } else { - state2.corkedRequestsFree = new CorkedRequest(state2); - } - state2.bufferedRequestCount = 0; - } else { - while (entry) { - var chunk = entry.chunk; - var encoding = entry.encoding; - var cb = entry.callback; - var len = state2.objectMode ? 1 : chunk.length; - doWrite(stream, state2, false, len, chunk, encoding, cb); - entry = entry.next; - state2.bufferedRequestCount--; - if (state2.writing) { - break; - } - } - if (entry === null) state2.lastBufferedRequest = null; - } - state2.bufferedRequest = entry; - state2.bufferProcessing = false; - } - Writable.prototype._write = function(chunk, encoding, cb) { - cb(new ERR_METHOD_NOT_IMPLEMENTED("_write()")); - }; - Writable.prototype._writev = null; - Writable.prototype.end = function(chunk, encoding, cb) { - var state2 = this._writableState; - if (typeof chunk === "function") { - cb = chunk; - chunk = null; - encoding = null; - } else if (typeof encoding === "function") { - cb = encoding; - encoding = null; - } - if (chunk !== null && chunk !== void 0) this.write(chunk, encoding); - if (state2.corked) { - state2.corked = 1; - this.uncork(); - } - if (!state2.ending) endWritable(this, state2, cb); - return this; - }; - Object.defineProperty(Writable.prototype, "writableLength", { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get2() { - return this._writableState.length; - } - }); - function needFinish(state2) { - return state2.ending && state2.length === 0 && state2.bufferedRequest === null && !state2.finished && !state2.writing; - } - function callFinal(stream, state2) { - stream._final(function(err) { - state2.pendingcb--; - if (err) { - errorOrDestroy(stream, err); - } - state2.prefinished = true; - stream.emit("prefinish"); - finishMaybe(stream, state2); - }); - } - function prefinish(stream, state2) { - if (!state2.prefinished && !state2.finalCalled) { - if (typeof stream._final === "function" && !state2.destroyed) { - state2.pendingcb++; - state2.finalCalled = true; - process.nextTick(callFinal, stream, state2); - } else { - state2.prefinished = true; - stream.emit("prefinish"); - } - } - } - function finishMaybe(stream, state2) { - var need = needFinish(state2); - if (need) { - prefinish(stream, state2); - if (state2.pendingcb === 0) { - state2.finished = true; - stream.emit("finish"); - if (state2.autoDestroy) { - var rState = stream._readableState; - if (!rState || rState.autoDestroy && rState.endEmitted) { - stream.destroy(); - } - } - } - } - return need; - } - function endWritable(stream, state2, cb) { - state2.ending = true; - finishMaybe(stream, state2); - if (cb) { - if (state2.finished) process.nextTick(cb); - else stream.once("finish", cb); - } - state2.ended = true; - stream.writable = false; - } - function onCorkedFinish(corkReq, state2, err) { - var entry = corkReq.entry; - corkReq.entry = null; - while (entry) { - var cb = entry.callback; - state2.pendingcb--; - cb(err); - entry = entry.next; - } - state2.corkedRequestsFree.next = corkReq; - } - Object.defineProperty(Writable.prototype, "destroyed", { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get2() { - if (this._writableState === void 0) { - return false; - } - return this._writableState.destroyed; - }, - set: function set2(value) { - if (!this._writableState) { - return; - } - this._writableState.destroyed = value; - } - }); - Writable.prototype.destroy = destroyImpl.destroy; - Writable.prototype._undestroy = destroyImpl.undestroy; - Writable.prototype._destroy = function(err, cb) { - cb(err); - }; - } -}); - -// node_modules/.pnpm/readable-stream@3.6.2/node_modules/readable-stream/lib/_stream_duplex.js -var require_stream_duplex = __commonJS({ - "node_modules/.pnpm/readable-stream@3.6.2/node_modules/readable-stream/lib/_stream_duplex.js"(exports, module) { - "use strict"; - var objectKeys = Object.keys || function(obj) { - var keys2 = []; - for (var key in obj) keys2.push(key); - return keys2; - }; - module.exports = Duplex; - var Readable3 = require_stream_readable(); - var Writable = require_stream_writable(); - require_inherits()(Duplex, Readable3); - { - keys = objectKeys(Writable.prototype); - for (v5 = 0; v5 < keys.length; v5++) { - method = keys[v5]; - if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; - } - } - var keys; - var method; - var v5; - function Duplex(options) { - if (!(this instanceof Duplex)) return new Duplex(options); - Readable3.call(this, options); - Writable.call(this, options); - this.allowHalfOpen = true; - if (options) { - if (options.readable === false) this.readable = false; - if (options.writable === false) this.writable = false; - if (options.allowHalfOpen === false) { - this.allowHalfOpen = false; - this.once("end", onend); - } - } - } - Object.defineProperty(Duplex.prototype, "writableHighWaterMark", { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get2() { - return this._writableState.highWaterMark; - } - }); - Object.defineProperty(Duplex.prototype, "writableBuffer", { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get2() { - return this._writableState && this._writableState.getBuffer(); - } - }); - Object.defineProperty(Duplex.prototype, "writableLength", { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get2() { - return this._writableState.length; - } - }); - function onend() { - if (this._writableState.ended) return; - process.nextTick(onEndNT, this); - } - function onEndNT(self2) { - self2.end(); - } - Object.defineProperty(Duplex.prototype, "destroyed", { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get2() { - if (this._readableState === void 0 || this._writableState === void 0) { - return false; - } - return this._readableState.destroyed && this._writableState.destroyed; - }, - set: function set2(value) { - if (this._readableState === void 0 || this._writableState === void 0) { - return; - } - this._readableState.destroyed = value; - this._writableState.destroyed = value; - } - }); - } -}); - -// node_modules/.pnpm/safe-buffer@5.2.1/node_modules/safe-buffer/index.js -var require_safe_buffer = __commonJS({ - "node_modules/.pnpm/safe-buffer@5.2.1/node_modules/safe-buffer/index.js"(exports, module) { - var buffer2 = __require("buffer"); - var Buffer2 = buffer2.Buffer; - function copyProps(src, dst) { - for (var key in src) { - dst[key] = src[key]; - } - } - if (Buffer2.from && Buffer2.alloc && Buffer2.allocUnsafe && Buffer2.allocUnsafeSlow) { - module.exports = buffer2; - } else { - copyProps(buffer2, exports); - exports.Buffer = SafeBuffer; - } - function SafeBuffer(arg, encodingOrOffset, length) { - return Buffer2(arg, encodingOrOffset, length); - } - SafeBuffer.prototype = Object.create(Buffer2.prototype); - copyProps(Buffer2, SafeBuffer); - SafeBuffer.from = function(arg, encodingOrOffset, length) { - if (typeof arg === "number") { - throw new TypeError("Argument must not be a number"); - } - return Buffer2(arg, encodingOrOffset, length); - }; - SafeBuffer.alloc = function(size2, fill, encoding) { - if (typeof size2 !== "number") { - throw new TypeError("Argument must be a number"); - } - var buf = Buffer2(size2); - if (fill !== void 0) { - if (typeof encoding === "string") { - buf.fill(fill, encoding); - } else { - buf.fill(fill); - } - } else { - buf.fill(0); - } - return buf; - }; - SafeBuffer.allocUnsafe = function(size2) { - if (typeof size2 !== "number") { - throw new TypeError("Argument must be a number"); - } - return Buffer2(size2); - }; - SafeBuffer.allocUnsafeSlow = function(size2) { - if (typeof size2 !== "number") { - throw new TypeError("Argument must be a number"); - } - return buffer2.SlowBuffer(size2); - }; - } -}); - -// node_modules/.pnpm/string_decoder@1.3.0/node_modules/string_decoder/lib/string_decoder.js -var require_string_decoder = __commonJS({ - "node_modules/.pnpm/string_decoder@1.3.0/node_modules/string_decoder/lib/string_decoder.js"(exports) { - "use strict"; - var Buffer2 = require_safe_buffer().Buffer; - var isEncoding = Buffer2.isEncoding || function(encoding) { - encoding = "" + encoding; - switch (encoding && encoding.toLowerCase()) { - case "hex": - case "utf8": - case "utf-8": - case "ascii": - case "binary": - case "base64": - case "ucs2": - case "ucs-2": - case "utf16le": - case "utf-16le": - case "raw": - return true; - default: - return false; - } - }; - function _normalizeEncoding(enc2) { - if (!enc2) return "utf8"; - var retried; - while (true) { - switch (enc2) { - case "utf8": - case "utf-8": - return "utf8"; - case "ucs2": - case "ucs-2": - case "utf16le": - case "utf-16le": - return "utf16le"; - case "latin1": - case "binary": - return "latin1"; - case "base64": - case "ascii": - case "hex": - return enc2; - default: - if (retried) return; - enc2 = ("" + enc2).toLowerCase(); - retried = true; - } - } - } - function normalizeEncoding(enc2) { - var nenc = _normalizeEncoding(enc2); - if (typeof nenc !== "string" && (Buffer2.isEncoding === isEncoding || !isEncoding(enc2))) throw new Error("Unknown encoding: " + enc2); - return nenc || enc2; - } - exports.StringDecoder = StringDecoder; - function StringDecoder(encoding) { - this.encoding = normalizeEncoding(encoding); - var nb; - switch (this.encoding) { - case "utf16le": - this.text = utf16Text; - this.end = utf16End; - nb = 4; - break; - case "utf8": - this.fillLast = utf8FillLast; - nb = 4; - break; - case "base64": - this.text = base64Text; - this.end = base64End; - nb = 3; - break; - default: - this.write = simpleWrite; - this.end = simpleEnd; - return; - } - this.lastNeed = 0; - this.lastTotal = 0; - this.lastChar = Buffer2.allocUnsafe(nb); - } - StringDecoder.prototype.write = function(buf) { - if (buf.length === 0) return ""; - var r5; - var i5; - if (this.lastNeed) { - r5 = this.fillLast(buf); - if (r5 === void 0) return ""; - i5 = this.lastNeed; - this.lastNeed = 0; - } else { - i5 = 0; - } - if (i5 < buf.length) return r5 ? r5 + this.text(buf, i5) : this.text(buf, i5); - return r5 || ""; - }; - StringDecoder.prototype.end = utf8End; - StringDecoder.prototype.text = utf8Text; - StringDecoder.prototype.fillLast = function(buf) { - if (this.lastNeed <= buf.length) { - buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); - return this.lastChar.toString(this.encoding, 0, this.lastTotal); - } - buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); - this.lastNeed -= buf.length; - }; - function utf8CheckByte(byte) { - if (byte <= 127) return 0; - else if (byte >> 5 === 6) return 2; - else if (byte >> 4 === 14) return 3; - else if (byte >> 3 === 30) return 4; - return byte >> 6 === 2 ? -1 : -2; - } - function utf8CheckIncomplete(self2, buf, i5) { - var j5 = buf.length - 1; - if (j5 < i5) return 0; - var nb = utf8CheckByte(buf[j5]); - if (nb >= 0) { - if (nb > 0) self2.lastNeed = nb - 1; - return nb; - } - if (--j5 < i5 || nb === -2) return 0; - nb = utf8CheckByte(buf[j5]); - if (nb >= 0) { - if (nb > 0) self2.lastNeed = nb - 2; - return nb; - } - if (--j5 < i5 || nb === -2) return 0; - nb = utf8CheckByte(buf[j5]); - if (nb >= 0) { - if (nb > 0) { - if (nb === 2) nb = 0; - else self2.lastNeed = nb - 3; - } - return nb; - } - return 0; - } - function utf8CheckExtraBytes(self2, buf, p5) { - if ((buf[0] & 192) !== 128) { - self2.lastNeed = 0; - return "\uFFFD"; - } - if (self2.lastNeed > 1 && buf.length > 1) { - if ((buf[1] & 192) !== 128) { - self2.lastNeed = 1; - return "\uFFFD"; - } - if (self2.lastNeed > 2 && buf.length > 2) { - if ((buf[2] & 192) !== 128) { - self2.lastNeed = 2; - return "\uFFFD"; - } - } - } - } - function utf8FillLast(buf) { - var p5 = this.lastTotal - this.lastNeed; - var r5 = utf8CheckExtraBytes(this, buf, p5); - if (r5 !== void 0) return r5; - if (this.lastNeed <= buf.length) { - buf.copy(this.lastChar, p5, 0, this.lastNeed); - return this.lastChar.toString(this.encoding, 0, this.lastTotal); - } - buf.copy(this.lastChar, p5, 0, buf.length); - this.lastNeed -= buf.length; - } - function utf8Text(buf, i5) { - var total = utf8CheckIncomplete(this, buf, i5); - if (!this.lastNeed) return buf.toString("utf8", i5); - this.lastTotal = total; - var end = buf.length - (total - this.lastNeed); - buf.copy(this.lastChar, 0, end); - return buf.toString("utf8", i5, end); - } - function utf8End(buf) { - var r5 = buf && buf.length ? this.write(buf) : ""; - if (this.lastNeed) return r5 + "\uFFFD"; - return r5; - } - function utf16Text(buf, i5) { - if ((buf.length - i5) % 2 === 0) { - var r5 = buf.toString("utf16le", i5); - if (r5) { - var c5 = r5.charCodeAt(r5.length - 1); - if (c5 >= 55296 && c5 <= 56319) { - this.lastNeed = 2; - this.lastTotal = 4; - this.lastChar[0] = buf[buf.length - 2]; - this.lastChar[1] = buf[buf.length - 1]; - return r5.slice(0, -1); - } - } - return r5; - } - this.lastNeed = 1; - this.lastTotal = 2; - this.lastChar[0] = buf[buf.length - 1]; - return buf.toString("utf16le", i5, buf.length - 1); - } - function utf16End(buf) { - var r5 = buf && buf.length ? this.write(buf) : ""; - if (this.lastNeed) { - var end = this.lastTotal - this.lastNeed; - return r5 + this.lastChar.toString("utf16le", 0, end); - } - return r5; - } - function base64Text(buf, i5) { - var n5 = (buf.length - i5) % 3; - if (n5 === 0) return buf.toString("base64", i5); - this.lastNeed = 3 - n5; - this.lastTotal = 3; - if (n5 === 1) { - this.lastChar[0] = buf[buf.length - 1]; - } else { - this.lastChar[0] = buf[buf.length - 2]; - this.lastChar[1] = buf[buf.length - 1]; - } - return buf.toString("base64", i5, buf.length - n5); - } - function base64End(buf) { - var r5 = buf && buf.length ? this.write(buf) : ""; - if (this.lastNeed) return r5 + this.lastChar.toString("base64", 0, 3 - this.lastNeed); - return r5; - } - function simpleWrite(buf) { - return buf.toString(this.encoding); - } - function simpleEnd(buf) { - return buf && buf.length ? this.write(buf) : ""; - } - } -}); - -// node_modules/.pnpm/readable-stream@3.6.2/node_modules/readable-stream/lib/internal/streams/end-of-stream.js -var require_end_of_stream = __commonJS({ - "node_modules/.pnpm/readable-stream@3.6.2/node_modules/readable-stream/lib/internal/streams/end-of-stream.js"(exports, module) { - "use strict"; - var ERR_STREAM_PREMATURE_CLOSE = require_errors2().codes.ERR_STREAM_PREMATURE_CLOSE; - function once(callback) { - var called = false; - return function() { - if (called) return; - called = true; - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } - callback.apply(this, args); - }; - } - function noop5() { - } - function isRequest2(stream) { - return stream.setHeader && typeof stream.abort === "function"; - } - function eos(stream, opts, callback) { - if (typeof opts === "function") return eos(stream, null, opts); - if (!opts) opts = {}; - callback = once(callback || noop5); - var readable = opts.readable || opts.readable !== false && stream.readable; - var writable = opts.writable || opts.writable !== false && stream.writable; - var onlegacyfinish = function onlegacyfinish2() { - if (!stream.writable) onfinish(); - }; - var writableEnded = stream._writableState && stream._writableState.finished; - var onfinish = function onfinish2() { - writable = false; - writableEnded = true; - if (!readable) callback.call(stream); - }; - var readableEnded = stream._readableState && stream._readableState.endEmitted; - var onend = function onend2() { - readable = false; - readableEnded = true; - if (!writable) callback.call(stream); - }; - var onerror = function onerror2(err) { - callback.call(stream, err); - }; - var onclose = function onclose2() { - var err; - if (readable && !readableEnded) { - if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); - return callback.call(stream, err); - } - if (writable && !writableEnded) { - if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); - return callback.call(stream, err); - } - }; - var onrequest = function onrequest2() { - stream.req.on("finish", onfinish); - }; - if (isRequest2(stream)) { - stream.on("complete", onfinish); - stream.on("abort", onclose); - if (stream.req) onrequest(); - else stream.on("request", onrequest); - } else if (writable && !stream._writableState) { - stream.on("end", onlegacyfinish); - stream.on("close", onlegacyfinish); - } - stream.on("end", onend); - stream.on("finish", onfinish); - if (opts.error !== false) stream.on("error", onerror); - stream.on("close", onclose); - return function() { - stream.removeListener("complete", onfinish); - stream.removeListener("abort", onclose); - stream.removeListener("request", onrequest); - if (stream.req) stream.req.removeListener("finish", onfinish); - stream.removeListener("end", onlegacyfinish); - stream.removeListener("close", onlegacyfinish); - stream.removeListener("finish", onfinish); - stream.removeListener("end", onend); - stream.removeListener("error", onerror); - stream.removeListener("close", onclose); - }; - } - module.exports = eos; - } -}); - -// node_modules/.pnpm/readable-stream@3.6.2/node_modules/readable-stream/lib/internal/streams/async_iterator.js -var require_async_iterator = __commonJS({ - "node_modules/.pnpm/readable-stream@3.6.2/node_modules/readable-stream/lib/internal/streams/async_iterator.js"(exports, module) { - "use strict"; - var _Object$setPrototypeO; - function _defineProperty(obj, key, value) { - key = _toPropertyKey(key); - if (key in obj) { - Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true }); - } else { - obj[key] = value; - } - return obj; - } - function _toPropertyKey(arg) { - var key = _toPrimitive(arg, "string"); - return typeof key === "symbol" ? key : String(key); - } - function _toPrimitive(input, hint) { - if (typeof input !== "object" || input === null) return input; - var prim = input[Symbol.toPrimitive]; - if (prim !== void 0) { - var res = prim.call(input, hint || "default"); - if (typeof res !== "object") return res; - throw new TypeError("@@toPrimitive must return a primitive value."); - } - return (hint === "string" ? String : Number)(input); - } - var finished = require_end_of_stream(); - var kLastResolve = /* @__PURE__ */ Symbol("lastResolve"); - var kLastReject = /* @__PURE__ */ Symbol("lastReject"); - var kError = /* @__PURE__ */ Symbol("error"); - var kEnded = /* @__PURE__ */ Symbol("ended"); - var kLastPromise = /* @__PURE__ */ Symbol("lastPromise"); - var kHandlePromise = /* @__PURE__ */ Symbol("handlePromise"); - var kStream = /* @__PURE__ */ Symbol("stream"); - function createIterResult(value, done) { - return { - value, - done - }; - } - function readAndResolve(iter) { - var resolve4 = iter[kLastResolve]; - if (resolve4 !== null) { - var data2 = iter[kStream].read(); - if (data2 !== null) { - iter[kLastPromise] = null; - iter[kLastResolve] = null; - iter[kLastReject] = null; - resolve4(createIterResult(data2, false)); - } - } - } - function onReadable(iter) { - process.nextTick(readAndResolve, iter); - } - function wrapForNext(lastPromise, iter) { - return function(resolve4, reject) { - lastPromise.then(function() { - if (iter[kEnded]) { - resolve4(createIterResult(void 0, true)); - return; - } - iter[kHandlePromise](resolve4, reject); - }, reject); - }; - } - var AsyncIteratorPrototype = Object.getPrototypeOf(function() { - }); - var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = { - get stream() { - return this[kStream]; - }, - next: function next() { - var _this = this; - var error50 = this[kError]; - if (error50 !== null) { - return Promise.reject(error50); - } - if (this[kEnded]) { - return Promise.resolve(createIterResult(void 0, true)); - } - if (this[kStream].destroyed) { - return new Promise(function(resolve4, reject) { - process.nextTick(function() { - if (_this[kError]) { - reject(_this[kError]); - } else { - resolve4(createIterResult(void 0, true)); - } - }); - }); - } - var lastPromise = this[kLastPromise]; - var promise2; - if (lastPromise) { - promise2 = new Promise(wrapForNext(lastPromise, this)); - } else { - var data2 = this[kStream].read(); - if (data2 !== null) { - return Promise.resolve(createIterResult(data2, false)); - } - promise2 = new Promise(this[kHandlePromise]); - } - this[kLastPromise] = promise2; - return promise2; - } - }, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function() { - return this; - }), _defineProperty(_Object$setPrototypeO, "return", function _return() { - var _this2 = this; - return new Promise(function(resolve4, reject) { - _this2[kStream].destroy(null, function(err) { - if (err) { - reject(err); - return; - } - resolve4(createIterResult(void 0, true)); - }); - }); - }), _Object$setPrototypeO), AsyncIteratorPrototype); - var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator2(stream) { - var _Object$create; - var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, { - value: stream, - writable: true - }), _defineProperty(_Object$create, kLastResolve, { - value: null, - writable: true - }), _defineProperty(_Object$create, kLastReject, { - value: null, - writable: true - }), _defineProperty(_Object$create, kError, { - value: null, - writable: true - }), _defineProperty(_Object$create, kEnded, { - value: stream._readableState.endEmitted, - writable: true - }), _defineProperty(_Object$create, kHandlePromise, { - value: function value(resolve4, reject) { - var data2 = iterator[kStream].read(); - if (data2) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - resolve4(createIterResult(data2, false)); - } else { - iterator[kLastResolve] = resolve4; - iterator[kLastReject] = reject; - } - }, - writable: true - }), _Object$create)); - iterator[kLastPromise] = null; - finished(stream, function(err) { - if (err && err.code !== "ERR_STREAM_PREMATURE_CLOSE") { - var reject = iterator[kLastReject]; - if (reject !== null) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - reject(err); - } - iterator[kError] = err; - return; - } - var resolve4 = iterator[kLastResolve]; - if (resolve4 !== null) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - resolve4(createIterResult(void 0, true)); - } - iterator[kEnded] = true; - }); - stream.on("readable", onReadable.bind(null, iterator)); - return iterator; - }; - module.exports = createReadableStreamAsyncIterator; - } -}); - -// node_modules/.pnpm/readable-stream@3.6.2/node_modules/readable-stream/lib/internal/streams/from.js -var require_from = __commonJS({ - "node_modules/.pnpm/readable-stream@3.6.2/node_modules/readable-stream/lib/internal/streams/from.js"(exports, module) { - "use strict"; - function asyncGeneratorStep(gen, resolve4, reject, _next, _throw, key, arg) { - try { - var info2 = gen[key](arg); - var value = info2.value; - } catch (error50) { - reject(error50); - return; - } - if (info2.done) { - resolve4(value); - } else { - Promise.resolve(value).then(_next, _throw); - } - } - function _asyncToGenerator(fn) { - return function() { - var self2 = this, args = arguments; - return new Promise(function(resolve4, reject) { - var gen = fn.apply(self2, args); - function _next(value) { - asyncGeneratorStep(gen, resolve4, reject, _next, _throw, "next", value); - } - function _throw(err) { - asyncGeneratorStep(gen, resolve4, reject, _next, _throw, "throw", err); - } - _next(void 0); - }); - }; - } - function ownKeys2(object2, enumerableOnly) { - var keys = Object.keys(object2); - if (Object.getOwnPropertySymbols) { - var symbols = Object.getOwnPropertySymbols(object2); - enumerableOnly && (symbols = symbols.filter(function(sym) { - return Object.getOwnPropertyDescriptor(object2, sym).enumerable; - })), keys.push.apply(keys, symbols); - } - return keys; - } - function _objectSpread(target) { - for (var i5 = 1; i5 < arguments.length; i5++) { - var source = null != arguments[i5] ? arguments[i5] : {}; - i5 % 2 ? ownKeys2(Object(source), true).forEach(function(key) { - _defineProperty(target, key, source[key]); - }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys2(Object(source)).forEach(function(key) { - Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); - }); - } - return target; - } - function _defineProperty(obj, key, value) { - key = _toPropertyKey(key); - if (key in obj) { - Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true }); - } else { - obj[key] = value; - } - return obj; - } - function _toPropertyKey(arg) { - var key = _toPrimitive(arg, "string"); - return typeof key === "symbol" ? key : String(key); - } - function _toPrimitive(input, hint) { - if (typeof input !== "object" || input === null) return input; - var prim = input[Symbol.toPrimitive]; - if (prim !== void 0) { - var res = prim.call(input, hint || "default"); - if (typeof res !== "object") return res; - throw new TypeError("@@toPrimitive must return a primitive value."); - } - return (hint === "string" ? String : Number)(input); - } - var ERR_INVALID_ARG_TYPE = require_errors2().codes.ERR_INVALID_ARG_TYPE; - function from(Readable3, iterable, opts) { - var iterator; - if (iterable && typeof iterable.next === "function") { - iterator = iterable; - } else if (iterable && iterable[Symbol.asyncIterator]) iterator = iterable[Symbol.asyncIterator](); - else if (iterable && iterable[Symbol.iterator]) iterator = iterable[Symbol.iterator](); - else throw new ERR_INVALID_ARG_TYPE("iterable", ["Iterable"], iterable); - var readable = new Readable3(_objectSpread({ - objectMode: true - }, opts)); - var reading = false; - readable._read = function() { - if (!reading) { - reading = true; - next(); - } - }; - function next() { - return _next2.apply(this, arguments); - } - function _next2() { - _next2 = _asyncToGenerator(function* () { - try { - var _yield$iterator$next = yield iterator.next(), value = _yield$iterator$next.value, done = _yield$iterator$next.done; - if (done) { - readable.push(null); - } else if (readable.push(yield value)) { - next(); - } else { - reading = false; - } - } catch (err) { - readable.destroy(err); - } - }); - return _next2.apply(this, arguments); - } - return readable; - } - module.exports = from; - } -}); - -// node_modules/.pnpm/readable-stream@3.6.2/node_modules/readable-stream/lib/_stream_readable.js -var require_stream_readable = __commonJS({ - "node_modules/.pnpm/readable-stream@3.6.2/node_modules/readable-stream/lib/_stream_readable.js"(exports, module) { - "use strict"; - module.exports = Readable3; - var Duplex; - Readable3.ReadableState = ReadableState; - var EE = __require("events").EventEmitter; - var EElistenerCount = function EElistenerCount2(emitter2, type) { - return emitter2.listeners(type).length; - }; - var Stream3 = require_stream2(); - var Buffer2 = __require("buffer").Buffer; - var OurUint8Array = (typeof global !== "undefined" ? global : typeof window !== "undefined" ? window : typeof self !== "undefined" ? self : {}).Uint8Array || function() { - }; - function _uint8ArrayToBuffer(chunk) { - return Buffer2.from(chunk); - } - function _isUint8Array(obj) { - return Buffer2.isBuffer(obj) || obj instanceof OurUint8Array; - } - var debugUtil = __require("util"); - var debug; - if (debugUtil && debugUtil.debuglog) { - debug = debugUtil.debuglog("stream"); - } else { - debug = function debug2() { - }; - } - var BufferList = require_buffer_list(); - var destroyImpl = require_destroy(); - var _require = require_state(); - var getHighWaterMark = _require.getHighWaterMark; - var _require$codes = require_errors2().codes; - var ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE; - var ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF; - var ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED; - var ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; - var StringDecoder; - var createReadableStreamAsyncIterator; - var from; - require_inherits()(Readable3, Stream3); - var errorOrDestroy = destroyImpl.errorOrDestroy; - var kProxyEvents = ["error", "close", "destroy", "pause", "resume"]; - function prependListener(emitter2, event, fn) { - if (typeof emitter2.prependListener === "function") return emitter2.prependListener(event, fn); - if (!emitter2._events || !emitter2._events[event]) emitter2.on(event, fn); - else if (Array.isArray(emitter2._events[event])) emitter2._events[event].unshift(fn); - else emitter2._events[event] = [fn, emitter2._events[event]]; - } - function ReadableState(options, stream, isDuplex) { - Duplex = Duplex || require_stream_duplex(); - options = options || {}; - if (typeof isDuplex !== "boolean") isDuplex = stream instanceof Duplex; - this.objectMode = !!options.objectMode; - if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; - this.highWaterMark = getHighWaterMark(this, options, "readableHighWaterMark", isDuplex); - this.buffer = new BufferList(); - this.length = 0; - this.pipes = null; - this.pipesCount = 0; - this.flowing = null; - this.ended = false; - this.endEmitted = false; - this.reading = false; - this.sync = true; - this.needReadable = false; - this.emittedReadable = false; - this.readableListening = false; - this.resumeScheduled = false; - this.paused = true; - this.emitClose = options.emitClose !== false; - this.autoDestroy = !!options.autoDestroy; - this.destroyed = false; - this.defaultEncoding = options.defaultEncoding || "utf8"; - this.awaitDrain = 0; - this.readingMore = false; - this.decoder = null; - this.encoding = null; - if (options.encoding) { - if (!StringDecoder) StringDecoder = require_string_decoder().StringDecoder; - this.decoder = new StringDecoder(options.encoding); - this.encoding = options.encoding; - } - } - function Readable3(options) { - Duplex = Duplex || require_stream_duplex(); - if (!(this instanceof Readable3)) return new Readable3(options); - var isDuplex = this instanceof Duplex; - this._readableState = new ReadableState(options, this, isDuplex); - this.readable = true; - if (options) { - if (typeof options.read === "function") this._read = options.read; - if (typeof options.destroy === "function") this._destroy = options.destroy; - } - Stream3.call(this); - } - Object.defineProperty(Readable3.prototype, "destroyed", { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get2() { - if (this._readableState === void 0) { - return false; - } - return this._readableState.destroyed; - }, - set: function set2(value) { - if (!this._readableState) { - return; - } - this._readableState.destroyed = value; - } - }); - Readable3.prototype.destroy = destroyImpl.destroy; - Readable3.prototype._undestroy = destroyImpl.undestroy; - Readable3.prototype._destroy = function(err, cb) { - cb(err); - }; - Readable3.prototype.push = function(chunk, encoding) { - var state2 = this._readableState; - var skipChunkCheck; - if (!state2.objectMode) { - if (typeof chunk === "string") { - encoding = encoding || state2.defaultEncoding; - if (encoding !== state2.encoding) { - chunk = Buffer2.from(chunk, encoding); - encoding = ""; - } - skipChunkCheck = true; - } - } else { - skipChunkCheck = true; - } - return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); - }; - Readable3.prototype.unshift = function(chunk) { - return readableAddChunk(this, chunk, null, true, false); - }; - function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { - debug("readableAddChunk", chunk); - var state2 = stream._readableState; - if (chunk === null) { - state2.reading = false; - onEofChunk(stream, state2); - } else { - var er; - if (!skipChunkCheck) er = chunkInvalid(state2, chunk); - if (er) { - errorOrDestroy(stream, er); - } else if (state2.objectMode || chunk && chunk.length > 0) { - if (typeof chunk !== "string" && !state2.objectMode && Object.getPrototypeOf(chunk) !== Buffer2.prototype) { - chunk = _uint8ArrayToBuffer(chunk); - } - if (addToFront) { - if (state2.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT()); - else addChunk(stream, state2, chunk, true); - } else if (state2.ended) { - errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF()); - } else if (state2.destroyed) { - return false; - } else { - state2.reading = false; - if (state2.decoder && !encoding) { - chunk = state2.decoder.write(chunk); - if (state2.objectMode || chunk.length !== 0) addChunk(stream, state2, chunk, false); - else maybeReadMore(stream, state2); - } else { - addChunk(stream, state2, chunk, false); - } - } - } else if (!addToFront) { - state2.reading = false; - maybeReadMore(stream, state2); - } - } - return !state2.ended && (state2.length < state2.highWaterMark || state2.length === 0); - } - function addChunk(stream, state2, chunk, addToFront) { - if (state2.flowing && state2.length === 0 && !state2.sync) { - state2.awaitDrain = 0; - stream.emit("data", chunk); - } else { - state2.length += state2.objectMode ? 1 : chunk.length; - if (addToFront) state2.buffer.unshift(chunk); - else state2.buffer.push(chunk); - if (state2.needReadable) emitReadable(stream); - } - maybeReadMore(stream, state2); - } - function chunkInvalid(state2, chunk) { - var er; - if (!_isUint8Array(chunk) && typeof chunk !== "string" && chunk !== void 0 && !state2.objectMode) { - er = new ERR_INVALID_ARG_TYPE("chunk", ["string", "Buffer", "Uint8Array"], chunk); - } - return er; - } - Readable3.prototype.isPaused = function() { - return this._readableState.flowing === false; - }; - Readable3.prototype.setEncoding = function(enc2) { - if (!StringDecoder) StringDecoder = require_string_decoder().StringDecoder; - var decoder2 = new StringDecoder(enc2); - this._readableState.decoder = decoder2; - this._readableState.encoding = this._readableState.decoder.encoding; - var p5 = this._readableState.buffer.head; - var content = ""; - while (p5 !== null) { - content += decoder2.write(p5.data); - p5 = p5.next; - } - this._readableState.buffer.clear(); - if (content !== "") this._readableState.buffer.push(content); - this._readableState.length = content.length; - return this; - }; - var MAX_HWM = 1073741824; - function computeNewHighWaterMark(n5) { - if (n5 >= MAX_HWM) { - n5 = MAX_HWM; - } else { - n5--; - n5 |= n5 >>> 1; - n5 |= n5 >>> 2; - n5 |= n5 >>> 4; - n5 |= n5 >>> 8; - n5 |= n5 >>> 16; - n5++; - } - return n5; - } - function howMuchToRead(n5, state2) { - if (n5 <= 0 || state2.length === 0 && state2.ended) return 0; - if (state2.objectMode) return 1; - if (n5 !== n5) { - if (state2.flowing && state2.length) return state2.buffer.head.data.length; - else return state2.length; - } - if (n5 > state2.highWaterMark) state2.highWaterMark = computeNewHighWaterMark(n5); - if (n5 <= state2.length) return n5; - if (!state2.ended) { - state2.needReadable = true; - return 0; - } - return state2.length; - } - Readable3.prototype.read = function(n5) { - debug("read", n5); - n5 = parseInt(n5, 10); - var state2 = this._readableState; - var nOrig = n5; - if (n5 !== 0) state2.emittedReadable = false; - if (n5 === 0 && state2.needReadable && ((state2.highWaterMark !== 0 ? state2.length >= state2.highWaterMark : state2.length > 0) || state2.ended)) { - debug("read: emitReadable", state2.length, state2.ended); - if (state2.length === 0 && state2.ended) endReadable(this); - else emitReadable(this); - return null; - } - n5 = howMuchToRead(n5, state2); - if (n5 === 0 && state2.ended) { - if (state2.length === 0) endReadable(this); - return null; - } - var doRead = state2.needReadable; - debug("need readable", doRead); - if (state2.length === 0 || state2.length - n5 < state2.highWaterMark) { - doRead = true; - debug("length less than watermark", doRead); - } - if (state2.ended || state2.reading) { - doRead = false; - debug("reading or ended", doRead); - } else if (doRead) { - debug("do read"); - state2.reading = true; - state2.sync = true; - if (state2.length === 0) state2.needReadable = true; - this._read(state2.highWaterMark); - state2.sync = false; - if (!state2.reading) n5 = howMuchToRead(nOrig, state2); - } - var ret; - if (n5 > 0) ret = fromList(n5, state2); - else ret = null; - if (ret === null) { - state2.needReadable = state2.length <= state2.highWaterMark; - n5 = 0; - } else { - state2.length -= n5; - state2.awaitDrain = 0; - } - if (state2.length === 0) { - if (!state2.ended) state2.needReadable = true; - if (nOrig !== n5 && state2.ended) endReadable(this); - } - if (ret !== null) this.emit("data", ret); - return ret; - }; - function onEofChunk(stream, state2) { - debug("onEofChunk"); - if (state2.ended) return; - if (state2.decoder) { - var chunk = state2.decoder.end(); - if (chunk && chunk.length) { - state2.buffer.push(chunk); - state2.length += state2.objectMode ? 1 : chunk.length; - } - } - state2.ended = true; - if (state2.sync) { - emitReadable(stream); - } else { - state2.needReadable = false; - if (!state2.emittedReadable) { - state2.emittedReadable = true; - emitReadable_(stream); - } - } - } - function emitReadable(stream) { - var state2 = stream._readableState; - debug("emitReadable", state2.needReadable, state2.emittedReadable); - state2.needReadable = false; - if (!state2.emittedReadable) { - debug("emitReadable", state2.flowing); - state2.emittedReadable = true; - process.nextTick(emitReadable_, stream); - } - } - function emitReadable_(stream) { - var state2 = stream._readableState; - debug("emitReadable_", state2.destroyed, state2.length, state2.ended); - if (!state2.destroyed && (state2.length || state2.ended)) { - stream.emit("readable"); - state2.emittedReadable = false; - } - state2.needReadable = !state2.flowing && !state2.ended && state2.length <= state2.highWaterMark; - flow(stream); - } - function maybeReadMore(stream, state2) { - if (!state2.readingMore) { - state2.readingMore = true; - process.nextTick(maybeReadMore_, stream, state2); - } - } - function maybeReadMore_(stream, state2) { - while (!state2.reading && !state2.ended && (state2.length < state2.highWaterMark || state2.flowing && state2.length === 0)) { - var len = state2.length; - debug("maybeReadMore read 0"); - stream.read(0); - if (len === state2.length) - break; - } - state2.readingMore = false; - } - Readable3.prototype._read = function(n5) { - errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED("_read()")); - }; - Readable3.prototype.pipe = function(dest, pipeOpts) { - var src = this; - var state2 = this._readableState; - switch (state2.pipesCount) { - case 0: - state2.pipes = dest; - break; - case 1: - state2.pipes = [state2.pipes, dest]; - break; - default: - state2.pipes.push(dest); - break; - } - state2.pipesCount += 1; - debug("pipe count=%d opts=%j", state2.pipesCount, pipeOpts); - var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; - var endFn = doEnd ? onend : unpipe; - if (state2.endEmitted) process.nextTick(endFn); - else src.once("end", endFn); - dest.on("unpipe", onunpipe); - function onunpipe(readable, unpipeInfo) { - debug("onunpipe"); - if (readable === src) { - if (unpipeInfo && unpipeInfo.hasUnpiped === false) { - unpipeInfo.hasUnpiped = true; - cleanup(); - } - } - } - function onend() { - debug("onend"); - dest.end(); - } - var ondrain = pipeOnDrain(src); - dest.on("drain", ondrain); - var cleanedUp = false; - function cleanup() { - debug("cleanup"); - dest.removeListener("close", onclose); - dest.removeListener("finish", onfinish); - dest.removeListener("drain", ondrain); - dest.removeListener("error", onerror); - dest.removeListener("unpipe", onunpipe); - src.removeListener("end", onend); - src.removeListener("end", unpipe); - src.removeListener("data", ondata); - cleanedUp = true; - if (state2.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); - } - src.on("data", ondata); - function ondata(chunk) { - debug("ondata"); - var ret = dest.write(chunk); - debug("dest.write", ret); - if (ret === false) { - if ((state2.pipesCount === 1 && state2.pipes === dest || state2.pipesCount > 1 && indexOf(state2.pipes, dest) !== -1) && !cleanedUp) { - debug("false write response, pause", state2.awaitDrain); - state2.awaitDrain++; - } - src.pause(); - } - } - function onerror(er) { - debug("onerror", er); - unpipe(); - dest.removeListener("error", onerror); - if (EElistenerCount(dest, "error") === 0) errorOrDestroy(dest, er); - } - prependListener(dest, "error", onerror); - function onclose() { - dest.removeListener("finish", onfinish); - unpipe(); - } - dest.once("close", onclose); - function onfinish() { - debug("onfinish"); - dest.removeListener("close", onclose); - unpipe(); - } - dest.once("finish", onfinish); - function unpipe() { - debug("unpipe"); - src.unpipe(dest); - } - dest.emit("pipe", src); - if (!state2.flowing) { - debug("pipe resume"); - src.resume(); - } - return dest; - }; - function pipeOnDrain(src) { - return function pipeOnDrainFunctionResult() { - var state2 = src._readableState; - debug("pipeOnDrain", state2.awaitDrain); - if (state2.awaitDrain) state2.awaitDrain--; - if (state2.awaitDrain === 0 && EElistenerCount(src, "data")) { - state2.flowing = true; - flow(src); - } - }; - } - Readable3.prototype.unpipe = function(dest) { - var state2 = this._readableState; - var unpipeInfo = { - hasUnpiped: false - }; - if (state2.pipesCount === 0) return this; - if (state2.pipesCount === 1) { - if (dest && dest !== state2.pipes) return this; - if (!dest) dest = state2.pipes; - state2.pipes = null; - state2.pipesCount = 0; - state2.flowing = false; - if (dest) dest.emit("unpipe", this, unpipeInfo); - return this; - } - if (!dest) { - var dests = state2.pipes; - var len = state2.pipesCount; - state2.pipes = null; - state2.pipesCount = 0; - state2.flowing = false; - for (var i5 = 0; i5 < len; i5++) dests[i5].emit("unpipe", this, { - hasUnpiped: false - }); - return this; - } - var index2 = indexOf(state2.pipes, dest); - if (index2 === -1) return this; - state2.pipes.splice(index2, 1); - state2.pipesCount -= 1; - if (state2.pipesCount === 1) state2.pipes = state2.pipes[0]; - dest.emit("unpipe", this, unpipeInfo); - return this; - }; - Readable3.prototype.on = function(ev, fn) { - var res = Stream3.prototype.on.call(this, ev, fn); - var state2 = this._readableState; - if (ev === "data") { - state2.readableListening = this.listenerCount("readable") > 0; - if (state2.flowing !== false) this.resume(); - } else if (ev === "readable") { - if (!state2.endEmitted && !state2.readableListening) { - state2.readableListening = state2.needReadable = true; - state2.flowing = false; - state2.emittedReadable = false; - debug("on readable", state2.length, state2.reading); - if (state2.length) { - emitReadable(this); - } else if (!state2.reading) { - process.nextTick(nReadingNextTick, this); - } - } - } - return res; - }; - Readable3.prototype.addListener = Readable3.prototype.on; - Readable3.prototype.removeListener = function(ev, fn) { - var res = Stream3.prototype.removeListener.call(this, ev, fn); - if (ev === "readable") { - process.nextTick(updateReadableListening, this); - } - return res; - }; - Readable3.prototype.removeAllListeners = function(ev) { - var res = Stream3.prototype.removeAllListeners.apply(this, arguments); - if (ev === "readable" || ev === void 0) { - process.nextTick(updateReadableListening, this); - } - return res; - }; - function updateReadableListening(self2) { - var state2 = self2._readableState; - state2.readableListening = self2.listenerCount("readable") > 0; - if (state2.resumeScheduled && !state2.paused) { - state2.flowing = true; - } else if (self2.listenerCount("data") > 0) { - self2.resume(); - } - } - function nReadingNextTick(self2) { - debug("readable nexttick read 0"); - self2.read(0); - } - Readable3.prototype.resume = function() { - var state2 = this._readableState; - if (!state2.flowing) { - debug("resume"); - state2.flowing = !state2.readableListening; - resume(this, state2); - } - state2.paused = false; - return this; - }; - function resume(stream, state2) { - if (!state2.resumeScheduled) { - state2.resumeScheduled = true; - process.nextTick(resume_, stream, state2); - } - } - function resume_(stream, state2) { - debug("resume", state2.reading); - if (!state2.reading) { - stream.read(0); - } - state2.resumeScheduled = false; - stream.emit("resume"); - flow(stream); - if (state2.flowing && !state2.reading) stream.read(0); - } - Readable3.prototype.pause = function() { - debug("call pause flowing=%j", this._readableState.flowing); - if (this._readableState.flowing !== false) { - debug("pause"); - this._readableState.flowing = false; - this.emit("pause"); - } - this._readableState.paused = true; - return this; - }; - function flow(stream) { - var state2 = stream._readableState; - debug("flow", state2.flowing); - while (state2.flowing && stream.read() !== null) ; - } - Readable3.prototype.wrap = function(stream) { - var _this = this; - var state2 = this._readableState; - var paused = false; - stream.on("end", function() { - debug("wrapped end"); - if (state2.decoder && !state2.ended) { - var chunk = state2.decoder.end(); - if (chunk && chunk.length) _this.push(chunk); - } - _this.push(null); - }); - stream.on("data", function(chunk) { - debug("wrapped data"); - if (state2.decoder) chunk = state2.decoder.write(chunk); - if (state2.objectMode && (chunk === null || chunk === void 0)) return; - else if (!state2.objectMode && (!chunk || !chunk.length)) return; - var ret = _this.push(chunk); - if (!ret) { - paused = true; - stream.pause(); - } - }); - for (var i5 in stream) { - if (this[i5] === void 0 && typeof stream[i5] === "function") { - this[i5] = /* @__PURE__ */ (function methodWrap(method) { - return function methodWrapReturnFunction() { - return stream[method].apply(stream, arguments); - }; - })(i5); - } - } - for (var n5 = 0; n5 < kProxyEvents.length; n5++) { - stream.on(kProxyEvents[n5], this.emit.bind(this, kProxyEvents[n5])); - } - this._read = function(n6) { - debug("wrapped _read", n6); - if (paused) { - paused = false; - stream.resume(); - } - }; - return this; - }; - if (typeof Symbol === "function") { - Readable3.prototype[Symbol.asyncIterator] = function() { - if (createReadableStreamAsyncIterator === void 0) { - createReadableStreamAsyncIterator = require_async_iterator(); - } - return createReadableStreamAsyncIterator(this); - }; - } - Object.defineProperty(Readable3.prototype, "readableHighWaterMark", { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get2() { - return this._readableState.highWaterMark; - } - }); - Object.defineProperty(Readable3.prototype, "readableBuffer", { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get2() { - return this._readableState && this._readableState.buffer; - } - }); - Object.defineProperty(Readable3.prototype, "readableFlowing", { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get2() { - return this._readableState.flowing; - }, - set: function set2(state2) { - if (this._readableState) { - this._readableState.flowing = state2; - } - } - }); - Readable3._fromList = fromList; - Object.defineProperty(Readable3.prototype, "readableLength", { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get2() { - return this._readableState.length; - } - }); - function fromList(n5, state2) { - if (state2.length === 0) return null; - var ret; - if (state2.objectMode) ret = state2.buffer.shift(); - else if (!n5 || n5 >= state2.length) { - if (state2.decoder) ret = state2.buffer.join(""); - else if (state2.buffer.length === 1) ret = state2.buffer.first(); - else ret = state2.buffer.concat(state2.length); - state2.buffer.clear(); - } else { - ret = state2.buffer.consume(n5, state2.decoder); - } - return ret; - } - function endReadable(stream) { - var state2 = stream._readableState; - debug("endReadable", state2.endEmitted); - if (!state2.endEmitted) { - state2.ended = true; - process.nextTick(endReadableNT, state2, stream); - } - } - function endReadableNT(state2, stream) { - debug("endReadableNT", state2.endEmitted, state2.length); - if (!state2.endEmitted && state2.length === 0) { - state2.endEmitted = true; - stream.readable = false; - stream.emit("end"); - if (state2.autoDestroy) { - var wState = stream._writableState; - if (!wState || wState.autoDestroy && wState.finished) { - stream.destroy(); - } - } - } - } - if (typeof Symbol === "function") { - Readable3.from = function(iterable, opts) { - if (from === void 0) { - from = require_from(); - } - return from(Readable3, iterable, opts); - }; - } - function indexOf(xs, x5) { - for (var i5 = 0, l5 = xs.length; i5 < l5; i5++) { - if (xs[i5] === x5) return i5; - } - return -1; - } - } -}); - -// node_modules/.pnpm/readable-stream@3.6.2/node_modules/readable-stream/lib/_stream_transform.js -var require_stream_transform = __commonJS({ - "node_modules/.pnpm/readable-stream@3.6.2/node_modules/readable-stream/lib/_stream_transform.js"(exports, module) { - "use strict"; - module.exports = Transform; - var _require$codes = require_errors2().codes; - var ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED; - var ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK; - var ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING; - var ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0; - var Duplex = require_stream_duplex(); - require_inherits()(Transform, Duplex); - function afterTransform(er, data2) { - var ts = this._transformState; - ts.transforming = false; - var cb = ts.writecb; - if (cb === null) { - return this.emit("error", new ERR_MULTIPLE_CALLBACK()); - } - ts.writechunk = null; - ts.writecb = null; - if (data2 != null) - this.push(data2); - cb(er); - var rs = this._readableState; - rs.reading = false; - if (rs.needReadable || rs.length < rs.highWaterMark) { - this._read(rs.highWaterMark); - } - } - function Transform(options) { - if (!(this instanceof Transform)) return new Transform(options); - Duplex.call(this, options); - this._transformState = { - afterTransform: afterTransform.bind(this), - needTransform: false, - transforming: false, - writecb: null, - writechunk: null, - writeencoding: null - }; - this._readableState.needReadable = true; - this._readableState.sync = false; - if (options) { - if (typeof options.transform === "function") this._transform = options.transform; - if (typeof options.flush === "function") this._flush = options.flush; - } - this.on("prefinish", prefinish); - } - function prefinish() { - var _this = this; - if (typeof this._flush === "function" && !this._readableState.destroyed) { - this._flush(function(er, data2) { - done(_this, er, data2); - }); - } else { - done(this, null, null); - } - } - Transform.prototype.push = function(chunk, encoding) { - this._transformState.needTransform = false; - return Duplex.prototype.push.call(this, chunk, encoding); - }; - Transform.prototype._transform = function(chunk, encoding, cb) { - cb(new ERR_METHOD_NOT_IMPLEMENTED("_transform()")); - }; - Transform.prototype._write = function(chunk, encoding, cb) { - var ts = this._transformState; - ts.writecb = cb; - ts.writechunk = chunk; - ts.writeencoding = encoding; - if (!ts.transforming) { - var rs = this._readableState; - if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); - } - }; - Transform.prototype._read = function(n5) { - var ts = this._transformState; - if (ts.writechunk !== null && !ts.transforming) { - ts.transforming = true; - this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); - } else { - ts.needTransform = true; - } - }; - Transform.prototype._destroy = function(err, cb) { - Duplex.prototype._destroy.call(this, err, function(err2) { - cb(err2); - }); - }; - function done(stream, er, data2) { - if (er) return stream.emit("error", er); - if (data2 != null) - stream.push(data2); - if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0(); - if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING(); - return stream.push(null); - } - } -}); - -// node_modules/.pnpm/readable-stream@3.6.2/node_modules/readable-stream/lib/_stream_passthrough.js -var require_stream_passthrough = __commonJS({ - "node_modules/.pnpm/readable-stream@3.6.2/node_modules/readable-stream/lib/_stream_passthrough.js"(exports, module) { - "use strict"; - module.exports = PassThrough; - var Transform = require_stream_transform(); - require_inherits()(PassThrough, Transform); - function PassThrough(options) { - if (!(this instanceof PassThrough)) return new PassThrough(options); - Transform.call(this, options); - } - PassThrough.prototype._transform = function(chunk, encoding, cb) { - cb(null, chunk); - }; - } -}); - -// node_modules/.pnpm/readable-stream@3.6.2/node_modules/readable-stream/lib/internal/streams/pipeline.js -var require_pipeline = __commonJS({ - "node_modules/.pnpm/readable-stream@3.6.2/node_modules/readable-stream/lib/internal/streams/pipeline.js"(exports, module) { - "use strict"; - var eos; - function once(callback) { - var called = false; - return function() { - if (called) return; - called = true; - callback.apply(void 0, arguments); - }; - } - var _require$codes = require_errors2().codes; - var ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS; - var ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; - function noop5(err) { - if (err) throw err; - } - function isRequest2(stream) { - return stream.setHeader && typeof stream.abort === "function"; - } - function destroyer(stream, reading, writing, callback) { - callback = once(callback); - var closed = false; - stream.on("close", function() { - closed = true; - }); - if (eos === void 0) eos = require_end_of_stream(); - eos(stream, { - readable: reading, - writable: writing - }, function(err) { - if (err) return callback(err); - closed = true; - callback(); - }); - var destroyed = false; - return function(err) { - if (closed) return; - if (destroyed) return; - destroyed = true; - if (isRequest2(stream)) return stream.abort(); - if (typeof stream.destroy === "function") return stream.destroy(); - callback(err || new ERR_STREAM_DESTROYED("pipe")); - }; - } - function call(fn) { - fn(); - } - function pipe2(from, to) { - return from.pipe(to); - } - function popCallback(streams) { - if (!streams.length) return noop5; - if (typeof streams[streams.length - 1] !== "function") return noop5; - return streams.pop(); - } - function pipeline() { - for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) { - streams[_key] = arguments[_key]; - } - var callback = popCallback(streams); - if (Array.isArray(streams[0])) streams = streams[0]; - if (streams.length < 2) { - throw new ERR_MISSING_ARGS("streams"); - } - var error50; - var destroys = streams.map(function(stream, i5) { - var reading = i5 < streams.length - 1; - var writing = i5 > 0; - return destroyer(stream, reading, writing, function(err) { - if (!error50) error50 = err; - if (err) destroys.forEach(call); - if (reading) return; - destroys.forEach(call); - callback(error50); - }); - }); - return streams.reduce(pipe2); - } - module.exports = pipeline; - } -}); - -// node_modules/.pnpm/readable-stream@3.6.2/node_modules/readable-stream/readable.js -var require_readable = __commonJS({ - "node_modules/.pnpm/readable-stream@3.6.2/node_modules/readable-stream/readable.js"(exports, module) { - var Stream3 = __require("stream"); - if (process.env.READABLE_STREAM === "disable" && Stream3) { - module.exports = Stream3.Readable; - Object.assign(module.exports, Stream3); - module.exports.Stream = Stream3; - } else { - exports = module.exports = require_stream_readable(); - exports.Stream = Stream3 || exports; - exports.Readable = exports; - exports.Writable = require_stream_writable(); - exports.Duplex = require_stream_duplex(); - exports.Transform = require_stream_transform(); - exports.PassThrough = require_stream_passthrough(); - exports.finished = require_end_of_stream(); - exports.pipeline = require_pipeline(); - } - } -}); - -// node_modules/.pnpm/buffer-from@1.1.2/node_modules/buffer-from/index.js -var require_buffer_from = __commonJS({ - "node_modules/.pnpm/buffer-from@1.1.2/node_modules/buffer-from/index.js"(exports, module) { - var toString = Object.prototype.toString; - var isModern = typeof Buffer !== "undefined" && typeof Buffer.alloc === "function" && typeof Buffer.allocUnsafe === "function" && typeof Buffer.from === "function"; - function isArrayBuffer(input) { - return toString.call(input).slice(8, -1) === "ArrayBuffer"; - } - function fromArrayBuffer(obj, byteOffset, length) { - byteOffset >>>= 0; - var maxLength = obj.byteLength - byteOffset; - if (maxLength < 0) { - throw new RangeError("'offset' is out of bounds"); - } - if (length === void 0) { - length = maxLength; - } else { - length >>>= 0; - if (length > maxLength) { - throw new RangeError("'length' is out of bounds"); - } - } - return isModern ? Buffer.from(obj.slice(byteOffset, byteOffset + length)) : new Buffer(new Uint8Array(obj.slice(byteOffset, byteOffset + length))); - } - function fromString(string4, encoding) { - if (typeof encoding !== "string" || encoding === "") { - encoding = "utf8"; - } - if (!Buffer.isEncoding(encoding)) { - throw new TypeError('"encoding" must be a valid string encoding'); - } - return isModern ? Buffer.from(string4, encoding) : new Buffer(string4, encoding); - } - function bufferFrom(value, encodingOrOffset, length) { - if (typeof value === "number") { - throw new TypeError('"value" argument must not be a number'); - } - if (isArrayBuffer(value)) { - return fromArrayBuffer(value, encodingOrOffset, length); - } - if (typeof value === "string") { - return fromString(value, encodingOrOffset); - } - return isModern ? Buffer.from(value) : new Buffer(value); - } - module.exports = bufferFrom; - } -}); - -// node_modules/.pnpm/typedarray@0.0.6/node_modules/typedarray/index.js -var require_typedarray = __commonJS({ - "node_modules/.pnpm/typedarray@0.0.6/node_modules/typedarray/index.js"(exports) { - var undefined2 = void 0; - var MAX_ARRAY_LENGTH = 1e5; - var ECMAScript = /* @__PURE__ */ (function() { - var opts = Object.prototype.toString, ophop = Object.prototype.hasOwnProperty; - return { - // Class returns internal [[Class]] property, used to avoid cross-frame instanceof issues: - Class: function(v5) { - return opts.call(v5).replace(/^\[object *|\]$/g, ""); - }, - HasProperty: function(o5, p5) { - return p5 in o5; - }, - HasOwnProperty: function(o5, p5) { - return ophop.call(o5, p5); - }, - IsCallable: function(o5) { - return typeof o5 === "function"; - }, - ToInt32: function(v5) { - return v5 >> 0; - }, - ToUint32: function(v5) { - return v5 >>> 0; - } - }; - })(); - var LN2 = Math.LN2; - var abs = Math.abs; - var floor = Math.floor; - var log2 = Math.log; - var min = Math.min; - var pow = Math.pow; - var round = Math.round; - function configureProperties(obj) { - if (getOwnPropNames && defineProp) { - var props = getOwnPropNames(obj), i5; - for (i5 = 0; i5 < props.length; i5 += 1) { - defineProp(obj, props[i5], { - value: obj[props[i5]], - writable: false, - enumerable: false, - configurable: false - }); - } - } - } - var defineProp; - if (Object.defineProperty && (function() { - try { - Object.defineProperty({}, "x", {}); - return true; - } catch (e5) { - return false; - } - })()) { - defineProp = Object.defineProperty; - } else { - defineProp = function(o5, p5, desc3) { - if (!o5 === Object(o5)) throw new TypeError("Object.defineProperty called on non-object"); - if (ECMAScript.HasProperty(desc3, "get") && Object.prototype.__defineGetter__) { - Object.prototype.__defineGetter__.call(o5, p5, desc3.get); - } - if (ECMAScript.HasProperty(desc3, "set") && Object.prototype.__defineSetter__) { - Object.prototype.__defineSetter__.call(o5, p5, desc3.set); - } - if (ECMAScript.HasProperty(desc3, "value")) { - o5[p5] = desc3.value; - } - return o5; - }; - } - var getOwnPropNames = Object.getOwnPropertyNames || function(o5) { - if (o5 !== Object(o5)) throw new TypeError("Object.getOwnPropertyNames called on non-object"); - var props = [], p5; - for (p5 in o5) { - if (ECMAScript.HasOwnProperty(o5, p5)) { - props.push(p5); - } - } - return props; - }; - function makeArrayAccessors(obj) { - if (!defineProp) { - return; - } - if (obj.length > MAX_ARRAY_LENGTH) throw new RangeError("Array too large for polyfill"); - function makeArrayAccessor(index2) { - defineProp(obj, index2, { - "get": function() { - return obj._getter(index2); - }, - "set": function(v5) { - obj._setter(index2, v5); - }, - enumerable: true, - configurable: false - }); - } - var i5; - for (i5 = 0; i5 < obj.length; i5 += 1) { - makeArrayAccessor(i5); - } - } - function as_signed(value, bits) { - var s5 = 32 - bits; - return value << s5 >> s5; - } - function as_unsigned(value, bits) { - var s5 = 32 - bits; - return value << s5 >>> s5; - } - function packI8(n5) { - return [n5 & 255]; - } - function unpackI8(bytes) { - return as_signed(bytes[0], 8); - } - function packU8(n5) { - return [n5 & 255]; - } - function unpackU8(bytes) { - return as_unsigned(bytes[0], 8); - } - function packU8Clamped(n5) { - n5 = round(Number(n5)); - return [n5 < 0 ? 0 : n5 > 255 ? 255 : n5 & 255]; - } - function packI16(n5) { - return [n5 >> 8 & 255, n5 & 255]; - } - function unpackI16(bytes) { - return as_signed(bytes[0] << 8 | bytes[1], 16); - } - function packU16(n5) { - return [n5 >> 8 & 255, n5 & 255]; - } - function unpackU16(bytes) { - return as_unsigned(bytes[0] << 8 | bytes[1], 16); - } - function packI32(n5) { - return [n5 >> 24 & 255, n5 >> 16 & 255, n5 >> 8 & 255, n5 & 255]; - } - function unpackI32(bytes) { - return as_signed(bytes[0] << 24 | bytes[1] << 16 | bytes[2] << 8 | bytes[3], 32); - } - function packU32(n5) { - return [n5 >> 24 & 255, n5 >> 16 & 255, n5 >> 8 & 255, n5 & 255]; - } - function unpackU32(bytes) { - return as_unsigned(bytes[0] << 24 | bytes[1] << 16 | bytes[2] << 8 | bytes[3], 32); - } - function packIEEE754(v5, ebits, fbits) { - var bias = (1 << ebits - 1) - 1, s5, e5, f5, ln, i5, bits, str, bytes; - function roundToEven(n5) { - var w5 = floor(n5), f6 = n5 - w5; - if (f6 < 0.5) - return w5; - if (f6 > 0.5) - return w5 + 1; - return w5 % 2 ? w5 + 1 : w5; - } - if (v5 !== v5) { - e5 = (1 << ebits) - 1; - f5 = pow(2, fbits - 1); - s5 = 0; - } else if (v5 === Infinity || v5 === -Infinity) { - e5 = (1 << ebits) - 1; - f5 = 0; - s5 = v5 < 0 ? 1 : 0; - } else if (v5 === 0) { - e5 = 0; - f5 = 0; - s5 = 1 / v5 === -Infinity ? 1 : 0; - } else { - s5 = v5 < 0; - v5 = abs(v5); - if (v5 >= pow(2, 1 - bias)) { - e5 = min(floor(log2(v5) / LN2), 1023); - f5 = roundToEven(v5 / pow(2, e5) * pow(2, fbits)); - if (f5 / pow(2, fbits) >= 2) { - e5 = e5 + 1; - f5 = 1; - } - if (e5 > bias) { - e5 = (1 << ebits) - 1; - f5 = 0; - } else { - e5 = e5 + bias; - f5 = f5 - pow(2, fbits); - } - } else { - e5 = 0; - f5 = roundToEven(v5 / pow(2, 1 - bias - fbits)); - } - } - bits = []; - for (i5 = fbits; i5; i5 -= 1) { - bits.push(f5 % 2 ? 1 : 0); - f5 = floor(f5 / 2); - } - for (i5 = ebits; i5; i5 -= 1) { - bits.push(e5 % 2 ? 1 : 0); - e5 = floor(e5 / 2); - } - bits.push(s5 ? 1 : 0); - bits.reverse(); - str = bits.join(""); - bytes = []; - while (str.length) { - bytes.push(parseInt(str.substring(0, 8), 2)); - str = str.substring(8); - } - return bytes; - } - function unpackIEEE754(bytes, ebits, fbits) { - var bits = [], i5, j5, b6, str, bias, s5, e5, f5; - for (i5 = bytes.length; i5; i5 -= 1) { - b6 = bytes[i5 - 1]; - for (j5 = 8; j5; j5 -= 1) { - bits.push(b6 % 2 ? 1 : 0); - b6 = b6 >> 1; - } - } - bits.reverse(); - str = bits.join(""); - bias = (1 << ebits - 1) - 1; - s5 = parseInt(str.substring(0, 1), 2) ? -1 : 1; - e5 = parseInt(str.substring(1, 1 + ebits), 2); - f5 = parseInt(str.substring(1 + ebits), 2); - if (e5 === (1 << ebits) - 1) { - return f5 !== 0 ? NaN : s5 * Infinity; - } else if (e5 > 0) { - return s5 * pow(2, e5 - bias) * (1 + f5 / pow(2, fbits)); - } else if (f5 !== 0) { - return s5 * pow(2, -(bias - 1)) * (f5 / pow(2, fbits)); - } else { - return s5 < 0 ? -0 : 0; - } - } - function unpackF64(b6) { - return unpackIEEE754(b6, 11, 52); - } - function packF64(v5) { - return packIEEE754(v5, 11, 52); - } - function unpackF32(b6) { - return unpackIEEE754(b6, 8, 23); - } - function packF32(v5) { - return packIEEE754(v5, 8, 23); - } - (function() { - var ArrayBuffer2 = function ArrayBuffer3(length) { - length = ECMAScript.ToInt32(length); - if (length < 0) throw new RangeError("ArrayBuffer size is not a small enough positive integer"); - this.byteLength = length; - this._bytes = []; - this._bytes.length = length; - var i5; - for (i5 = 0; i5 < this.byteLength; i5 += 1) { - this._bytes[i5] = 0; - } - configureProperties(this); - }; - exports.ArrayBuffer = exports.ArrayBuffer || ArrayBuffer2; - var ArrayBufferView = function ArrayBufferView2() { - }; - function makeConstructor(bytesPerElement, pack, unpack) { - var ctor; - ctor = function(buffer2, byteOffset, length) { - var array2, sequence, i5, s5; - if (!arguments.length || typeof arguments[0] === "number") { - this.length = ECMAScript.ToInt32(arguments[0]); - if (length < 0) throw new RangeError("ArrayBufferView size is not a small enough positive integer"); - this.byteLength = this.length * this.BYTES_PER_ELEMENT; - this.buffer = new ArrayBuffer2(this.byteLength); - this.byteOffset = 0; - } else if (typeof arguments[0] === "object" && arguments[0].constructor === ctor) { - array2 = arguments[0]; - this.length = array2.length; - this.byteLength = this.length * this.BYTES_PER_ELEMENT; - this.buffer = new ArrayBuffer2(this.byteLength); - this.byteOffset = 0; - for (i5 = 0; i5 < this.length; i5 += 1) { - this._setter(i5, array2._getter(i5)); - } - } else if (typeof arguments[0] === "object" && !(arguments[0] instanceof ArrayBuffer2 || ECMAScript.Class(arguments[0]) === "ArrayBuffer")) { - sequence = arguments[0]; - this.length = ECMAScript.ToUint32(sequence.length); - this.byteLength = this.length * this.BYTES_PER_ELEMENT; - this.buffer = new ArrayBuffer2(this.byteLength); - this.byteOffset = 0; - for (i5 = 0; i5 < this.length; i5 += 1) { - s5 = sequence[i5]; - this._setter(i5, Number(s5)); - } - } else if (typeof arguments[0] === "object" && (arguments[0] instanceof ArrayBuffer2 || ECMAScript.Class(arguments[0]) === "ArrayBuffer")) { - this.buffer = buffer2; - this.byteOffset = ECMAScript.ToUint32(byteOffset); - if (this.byteOffset > this.buffer.byteLength) { - throw new RangeError("byteOffset out of range"); - } - if (this.byteOffset % this.BYTES_PER_ELEMENT) { - throw new RangeError("ArrayBuffer length minus the byteOffset is not a multiple of the element size."); - } - if (arguments.length < 3) { - this.byteLength = this.buffer.byteLength - this.byteOffset; - if (this.byteLength % this.BYTES_PER_ELEMENT) { - throw new RangeError("length of buffer minus byteOffset not a multiple of the element size"); - } - this.length = this.byteLength / this.BYTES_PER_ELEMENT; - } else { - this.length = ECMAScript.ToUint32(length); - this.byteLength = this.length * this.BYTES_PER_ELEMENT; - } - if (this.byteOffset + this.byteLength > this.buffer.byteLength) { - throw new RangeError("byteOffset and length reference an area beyond the end of the buffer"); - } - } else { - throw new TypeError("Unexpected argument type(s)"); - } - this.constructor = ctor; - configureProperties(this); - makeArrayAccessors(this); - }; - ctor.prototype = new ArrayBufferView(); - ctor.prototype.BYTES_PER_ELEMENT = bytesPerElement; - ctor.prototype._pack = pack; - ctor.prototype._unpack = unpack; - ctor.BYTES_PER_ELEMENT = bytesPerElement; - ctor.prototype._getter = function(index2) { - if (arguments.length < 1) throw new SyntaxError("Not enough arguments"); - index2 = ECMAScript.ToUint32(index2); - if (index2 >= this.length) { - return undefined2; - } - var bytes = [], i5, o5; - for (i5 = 0, o5 = this.byteOffset + index2 * this.BYTES_PER_ELEMENT; i5 < this.BYTES_PER_ELEMENT; i5 += 1, o5 += 1) { - bytes.push(this.buffer._bytes[o5]); - } - return this._unpack(bytes); - }; - ctor.prototype.get = ctor.prototype._getter; - ctor.prototype._setter = function(index2, value) { - if (arguments.length < 2) throw new SyntaxError("Not enough arguments"); - index2 = ECMAScript.ToUint32(index2); - if (index2 >= this.length) { - return undefined2; - } - var bytes = this._pack(value), i5, o5; - for (i5 = 0, o5 = this.byteOffset + index2 * this.BYTES_PER_ELEMENT; i5 < this.BYTES_PER_ELEMENT; i5 += 1, o5 += 1) { - this.buffer._bytes[o5] = bytes[i5]; - } - }; - ctor.prototype.set = function(index2, value) { - if (arguments.length < 1) throw new SyntaxError("Not enough arguments"); - var array2, sequence, offset, len, i5, s5, d5, byteOffset, byteLength, tmp; - if (typeof arguments[0] === "object" && arguments[0].constructor === this.constructor) { - array2 = arguments[0]; - offset = ECMAScript.ToUint32(arguments[1]); - if (offset + array2.length > this.length) { - throw new RangeError("Offset plus length of array is out of range"); - } - byteOffset = this.byteOffset + offset * this.BYTES_PER_ELEMENT; - byteLength = array2.length * this.BYTES_PER_ELEMENT; - if (array2.buffer === this.buffer) { - tmp = []; - for (i5 = 0, s5 = array2.byteOffset; i5 < byteLength; i5 += 1, s5 += 1) { - tmp[i5] = array2.buffer._bytes[s5]; - } - for (i5 = 0, d5 = byteOffset; i5 < byteLength; i5 += 1, d5 += 1) { - this.buffer._bytes[d5] = tmp[i5]; - } - } else { - for (i5 = 0, s5 = array2.byteOffset, d5 = byteOffset; i5 < byteLength; i5 += 1, s5 += 1, d5 += 1) { - this.buffer._bytes[d5] = array2.buffer._bytes[s5]; - } - } - } else if (typeof arguments[0] === "object" && typeof arguments[0].length !== "undefined") { - sequence = arguments[0]; - len = ECMAScript.ToUint32(sequence.length); - offset = ECMAScript.ToUint32(arguments[1]); - if (offset + len > this.length) { - throw new RangeError("Offset plus length of array is out of range"); - } - for (i5 = 0; i5 < len; i5 += 1) { - s5 = sequence[i5]; - this._setter(offset + i5, Number(s5)); - } - } else { - throw new TypeError("Unexpected argument type(s)"); - } - }; - ctor.prototype.subarray = function(start, end) { - function clamp(v5, min2, max) { - return v5 < min2 ? min2 : v5 > max ? max : v5; - } - start = ECMAScript.ToInt32(start); - end = ECMAScript.ToInt32(end); - if (arguments.length < 1) { - start = 0; - } - if (arguments.length < 2) { - end = this.length; - } - if (start < 0) { - start = this.length + start; - } - if (end < 0) { - end = this.length + end; - } - start = clamp(start, 0, this.length); - end = clamp(end, 0, this.length); - var len = end - start; - if (len < 0) { - len = 0; - } - return new this.constructor( - this.buffer, - this.byteOffset + start * this.BYTES_PER_ELEMENT, - len - ); - }; - return ctor; - } - var Int8Array2 = makeConstructor(1, packI8, unpackI8); - var Uint8Array2 = makeConstructor(1, packU8, unpackU8); - var Uint8ClampedArray2 = makeConstructor(1, packU8Clamped, unpackU8); - var Int16Array2 = makeConstructor(2, packI16, unpackI16); - var Uint16Array2 = makeConstructor(2, packU16, unpackU16); - var Int32Array2 = makeConstructor(4, packI32, unpackI32); - var Uint32Array2 = makeConstructor(4, packU32, unpackU32); - var Float32Array2 = makeConstructor(4, packF32, unpackF32); - var Float64Array2 = makeConstructor(8, packF64, unpackF64); - exports.Int8Array = exports.Int8Array || Int8Array2; - exports.Uint8Array = exports.Uint8Array || Uint8Array2; - exports.Uint8ClampedArray = exports.Uint8ClampedArray || Uint8ClampedArray2; - exports.Int16Array = exports.Int16Array || Int16Array2; - exports.Uint16Array = exports.Uint16Array || Uint16Array2; - exports.Int32Array = exports.Int32Array || Int32Array2; - exports.Uint32Array = exports.Uint32Array || Uint32Array2; - exports.Float32Array = exports.Float32Array || Float32Array2; - exports.Float64Array = exports.Float64Array || Float64Array2; - })(); - (function() { - function r5(array2, index2) { - return ECMAScript.IsCallable(array2.get) ? array2.get(index2) : array2[index2]; - } - var IS_BIG_ENDIAN = (function() { - var u16array = new exports.Uint16Array([4660]), u8array = new exports.Uint8Array(u16array.buffer); - return r5(u8array, 0) === 18; - })(); - var DataView2 = function DataView3(buffer2, byteOffset, byteLength) { - if (arguments.length === 0) { - buffer2 = new exports.ArrayBuffer(0); - } else if (!(buffer2 instanceof exports.ArrayBuffer || ECMAScript.Class(buffer2) === "ArrayBuffer")) { - throw new TypeError("TypeError"); - } - this.buffer = buffer2 || new exports.ArrayBuffer(0); - this.byteOffset = ECMAScript.ToUint32(byteOffset); - if (this.byteOffset > this.buffer.byteLength) { - throw new RangeError("byteOffset out of range"); - } - if (arguments.length < 3) { - this.byteLength = this.buffer.byteLength - this.byteOffset; - } else { - this.byteLength = ECMAScript.ToUint32(byteLength); - } - if (this.byteOffset + this.byteLength > this.buffer.byteLength) { - throw new RangeError("byteOffset and length reference an area beyond the end of the buffer"); - } - configureProperties(this); - }; - function makeGetter(arrayType2) { - return function(byteOffset, littleEndian) { - byteOffset = ECMAScript.ToUint32(byteOffset); - if (byteOffset + arrayType2.BYTES_PER_ELEMENT > this.byteLength) { - throw new RangeError("Array index out of range"); - } - byteOffset += this.byteOffset; - var uint8Array = new exports.Uint8Array(this.buffer, byteOffset, arrayType2.BYTES_PER_ELEMENT), bytes = [], i5; - for (i5 = 0; i5 < arrayType2.BYTES_PER_ELEMENT; i5 += 1) { - bytes.push(r5(uint8Array, i5)); - } - if (Boolean(littleEndian) === Boolean(IS_BIG_ENDIAN)) { - bytes.reverse(); - } - return r5(new arrayType2(new exports.Uint8Array(bytes).buffer), 0); - }; - } - DataView2.prototype.getUint8 = makeGetter(exports.Uint8Array); - DataView2.prototype.getInt8 = makeGetter(exports.Int8Array); - DataView2.prototype.getUint16 = makeGetter(exports.Uint16Array); - DataView2.prototype.getInt16 = makeGetter(exports.Int16Array); - DataView2.prototype.getUint32 = makeGetter(exports.Uint32Array); - DataView2.prototype.getInt32 = makeGetter(exports.Int32Array); - DataView2.prototype.getFloat32 = makeGetter(exports.Float32Array); - DataView2.prototype.getFloat64 = makeGetter(exports.Float64Array); - function makeSetter(arrayType2) { - return function(byteOffset, value, littleEndian) { - byteOffset = ECMAScript.ToUint32(byteOffset); - if (byteOffset + arrayType2.BYTES_PER_ELEMENT > this.byteLength) { - throw new RangeError("Array index out of range"); - } - var typeArray = new arrayType2([value]), byteArray = new exports.Uint8Array(typeArray.buffer), bytes = [], i5, byteView; - for (i5 = 0; i5 < arrayType2.BYTES_PER_ELEMENT; i5 += 1) { - bytes.push(r5(byteArray, i5)); - } - if (Boolean(littleEndian) === Boolean(IS_BIG_ENDIAN)) { - bytes.reverse(); - } - byteView = new exports.Uint8Array(this.buffer, byteOffset, arrayType2.BYTES_PER_ELEMENT); - byteView.set(bytes); - }; - } - DataView2.prototype.setUint8 = makeSetter(exports.Uint8Array); - DataView2.prototype.setInt8 = makeSetter(exports.Int8Array); - DataView2.prototype.setUint16 = makeSetter(exports.Uint16Array); - DataView2.prototype.setInt16 = makeSetter(exports.Int16Array); - DataView2.prototype.setUint32 = makeSetter(exports.Uint32Array); - DataView2.prototype.setInt32 = makeSetter(exports.Int32Array); - DataView2.prototype.setFloat32 = makeSetter(exports.Float32Array); - DataView2.prototype.setFloat64 = makeSetter(exports.Float64Array); - exports.DataView = exports.DataView || DataView2; - })(); - } -}); - -// node_modules/.pnpm/concat-stream@2.0.0/node_modules/concat-stream/index.js -var require_concat_stream = __commonJS({ - "node_modules/.pnpm/concat-stream@2.0.0/node_modules/concat-stream/index.js"(exports, module) { - var Writable = require_readable().Writable; - var inherits = require_inherits(); - var bufferFrom = require_buffer_from(); - if (typeof Uint8Array === "undefined") { - U8 = require_typedarray().Uint8Array; - } else { - U8 = Uint8Array; - } - var U8; - function ConcatStream(opts, cb) { - if (!(this instanceof ConcatStream)) return new ConcatStream(opts, cb); - if (typeof opts === "function") { - cb = opts; - opts = {}; - } - if (!opts) opts = {}; - var encoding = opts.encoding; - var shouldInferEncoding = false; - if (!encoding) { - shouldInferEncoding = true; - } else { - encoding = String(encoding).toLowerCase(); - if (encoding === "u8" || encoding === "uint8") { - encoding = "uint8array"; - } - } - Writable.call(this, { objectMode: true }); - this.encoding = encoding; - this.shouldInferEncoding = shouldInferEncoding; - if (cb) this.on("finish", function() { - cb(this.getBody()); - }); - this.body = []; - } - module.exports = ConcatStream; - inherits(ConcatStream, Writable); - ConcatStream.prototype._write = function(chunk, enc2, next) { - this.body.push(chunk); - next(); - }; - ConcatStream.prototype.inferEncoding = function(buff) { - var firstBuffer = buff === void 0 ? this.body[0] : buff; - if (Buffer.isBuffer(firstBuffer)) return "buffer"; - if (typeof Uint8Array !== "undefined" && firstBuffer instanceof Uint8Array) return "uint8array"; - if (Array.isArray(firstBuffer)) return "array"; - if (typeof firstBuffer === "string") return "string"; - if (Object.prototype.toString.call(firstBuffer) === "[object Object]") return "object"; - return "buffer"; - }; - ConcatStream.prototype.getBody = function() { - if (!this.encoding && this.body.length === 0) return []; - if (this.shouldInferEncoding) this.encoding = this.inferEncoding(); - if (this.encoding === "array") return arrayConcat(this.body); - if (this.encoding === "string") return stringConcat(this.body); - if (this.encoding === "buffer") return bufferConcat(this.body); - if (this.encoding === "uint8array") return u8Concat(this.body); - return this.body; - }; - function isArrayish(arr) { - return /Array\]$/.test(Object.prototype.toString.call(arr)); - } - function isBufferish(p5) { - return typeof p5 === "string" || isArrayish(p5) || p5 && typeof p5.subarray === "function"; - } - function stringConcat(parts) { - var strings = []; - var needsToString = false; - for (var i5 = 0; i5 < parts.length; i5++) { - var p5 = parts[i5]; - if (typeof p5 === "string") { - strings.push(p5); - } else if (Buffer.isBuffer(p5)) { - strings.push(p5); - } else if (isBufferish(p5)) { - strings.push(bufferFrom(p5)); - } else { - strings.push(bufferFrom(String(p5))); - } - } - if (Buffer.isBuffer(parts[0])) { - strings = Buffer.concat(strings); - strings = strings.toString("utf8"); - } else { - strings = strings.join(""); - } - return strings; - } - function bufferConcat(parts) { - var bufs = []; - for (var i5 = 0; i5 < parts.length; i5++) { - var p5 = parts[i5]; - if (Buffer.isBuffer(p5)) { - bufs.push(p5); - } else if (isBufferish(p5)) { - bufs.push(bufferFrom(p5)); - } else { - bufs.push(bufferFrom(String(p5))); - } - } - return Buffer.concat(bufs); - } - function arrayConcat(parts) { - var res = []; - for (var i5 = 0; i5 < parts.length; i5++) { - res.push.apply(res, parts[i5]); - } - return res; - } - function u8Concat(parts) { - var len = 0; - for (var i5 = 0; i5 < parts.length; i5++) { - if (typeof parts[i5] === "string") { - parts[i5] = bufferFrom(parts[i5]); - } - len += parts[i5].length; - } - var u8 = new U8(len); - for (var i5 = 0, offset = 0; i5 < parts.length; i5++) { - var part = parts[i5]; - for (var j5 = 0; j5 < part.length; j5++) { - u8[offset++] = part[j5]; - } - } - return u8; - } - } -}); - -// node_modules/.pnpm/multer@2.1.1/node_modules/multer/storage/memory.js -var require_memory = __commonJS({ - "node_modules/.pnpm/multer@2.1.1/node_modules/multer/storage/memory.js"(exports, module) { - var concat2 = require_concat_stream(); - function MemoryStorage(opts) { - } - MemoryStorage.prototype._handleFile = function _handleFile(req, file2, cb) { - file2.stream.pipe(concat2({ encoding: "buffer" }, function(data2) { - cb(null, { - buffer: data2, - size: data2.length - }); - })); - }; - MemoryStorage.prototype._removeFile = function _removeFile(req, file2, cb) { - delete file2.buffer; - cb(null); - }; - module.exports = function(opts) { - return new MemoryStorage(opts); - }; - } -}); - -// node_modules/.pnpm/multer@2.1.1/node_modules/multer/index.js -var require_multer = __commonJS({ - "node_modules/.pnpm/multer@2.1.1/node_modules/multer/index.js"(exports, module) { - var makeMiddleware = require_make_middleware(); - var diskStorage = require_disk(); - var memoryStorage = require_memory(); - var MulterError = require_multer_error(); - function allowAll(req, file2, cb) { - cb(null, true); - } - function Multer(options) { - if (options.storage) { - this.storage = options.storage; - } else if (options.dest) { - this.storage = diskStorage({ destination: options.dest }); - } else { - this.storage = memoryStorage(); - } - this.limits = options.limits; - this.preservePath = options.preservePath; - this.defParamCharset = options.defParamCharset || "latin1"; - this.fileFilter = options.fileFilter || allowAll; - } - Multer.prototype._makeMiddleware = function(fields, fileStrategy) { - function setup() { - var fileFilter = this.fileFilter; - var filesLeft = /* @__PURE__ */ Object.create(null); - fields.forEach(function(field) { - if (typeof field.maxCount === "number") { - filesLeft[field.name] = field.maxCount; - } else { - filesLeft[field.name] = Infinity; - } - }); - function wrappedFileFilter(req, file2, cb) { - if ((filesLeft[file2.fieldname] || 0) <= 0) { - return cb(new MulterError("LIMIT_UNEXPECTED_FILE", file2.fieldname)); - } - filesLeft[file2.fieldname] -= 1; - fileFilter(req, file2, cb); - } - return { - limits: this.limits, - preservePath: this.preservePath, - defParamCharset: this.defParamCharset, - storage: this.storage, - fileFilter: wrappedFileFilter, - fileStrategy - }; - } - return makeMiddleware(setup.bind(this)); - }; - Multer.prototype.single = function(name) { - return this._makeMiddleware([{ name, maxCount: 1 }], "VALUE"); - }; - Multer.prototype.array = function(name, maxCount) { - return this._makeMiddleware([{ name, maxCount }], "ARRAY"); - }; - Multer.prototype.fields = function(fields) { - return this._makeMiddleware(fields, "OBJECT"); - }; - Multer.prototype.none = function() { - return this._makeMiddleware([], "NONE"); - }; - Multer.prototype.any = function() { - function setup() { - return { - limits: this.limits, - preservePath: this.preservePath, - defParamCharset: this.defParamCharset, - storage: this.storage, - fileFilter: this.fileFilter, - fileStrategy: "ARRAY" - }; - } - return makeMiddleware(setup.bind(this)); - }; - function multer3(options) { - if (options === void 0) { - return new Multer({}); - } - if (typeof options === "object" && options !== null) { - return new Multer(options); - } - throw new TypeError("Expected object for argument options"); - } - module.exports = multer3; - module.exports.diskStorage = diskStorage; - module.exports.memoryStorage = memoryStorage; - module.exports.MulterError = MulterError; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/codegen/code.js -var require_code = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/codegen/code.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.regexpCode = exports.getEsmExportName = exports.getProperty = exports.safeStringify = exports.stringify = exports.strConcat = exports.addCodeArg = exports.str = exports._ = exports.nil = exports._Code = exports.Name = exports.IDENTIFIER = exports._CodeOrName = void 0; - var _CodeOrName = class { - }; - exports._CodeOrName = _CodeOrName; - exports.IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i; - var Name2 = class extends _CodeOrName { - constructor(s5) { - super(); - if (!exports.IDENTIFIER.test(s5)) - throw new Error("CodeGen: name must be a valid identifier"); - this.str = s5; - } - toString() { - return this.str; - } - emptyStr() { - return false; - } - get names() { - return { [this.str]: 1 }; - } - }; - exports.Name = Name2; - var _Code = class extends _CodeOrName { - constructor(code) { - super(); - this._items = typeof code === "string" ? [code] : code; - } - toString() { - return this.str; - } - emptyStr() { - if (this._items.length > 1) - return false; - const item = this._items[0]; - return item === "" || item === '""'; - } - get str() { - var _a6; - return (_a6 = this._str) !== null && _a6 !== void 0 ? _a6 : this._str = this._items.reduce((s5, c5) => `${s5}${c5}`, ""); - } - get names() { - var _a6; - return (_a6 = this._names) !== null && _a6 !== void 0 ? _a6 : this._names = this._items.reduce((names, c5) => { - if (c5 instanceof Name2) - names[c5.str] = (names[c5.str] || 0) + 1; - return names; - }, {}); - } - }; - exports._Code = _Code; - exports.nil = new _Code(""); - function _(strs, ...args) { - const code = [strs[0]]; - let i5 = 0; - while (i5 < args.length) { - addCodeArg(code, args[i5]); - code.push(strs[++i5]); - } - return new _Code(code); - } - exports._ = _; - var plus = new _Code("+"); - function str(strs, ...args) { - const expr = [safeStringify2(strs[0])]; - let i5 = 0; - while (i5 < args.length) { - expr.push(plus); - addCodeArg(expr, args[i5]); - expr.push(plus, safeStringify2(strs[++i5])); - } - optimize(expr); - return new _Code(expr); - } - exports.str = str; - function addCodeArg(code, arg) { - if (arg instanceof _Code) - code.push(...arg._items); - else if (arg instanceof Name2) - code.push(arg); - else - code.push(interpolate(arg)); - } - exports.addCodeArg = addCodeArg; - function optimize(expr) { - let i5 = 1; - while (i5 < expr.length - 1) { - if (expr[i5] === plus) { - const res = mergeExprItems(expr[i5 - 1], expr[i5 + 1]); - if (res !== void 0) { - expr.splice(i5 - 1, 3, res); - continue; - } - expr[i5++] = "+"; - } - i5++; - } - } - function mergeExprItems(a5, b6) { - if (b6 === '""') - return a5; - if (a5 === '""') - return b6; - if (typeof a5 == "string") { - if (b6 instanceof Name2 || a5[a5.length - 1] !== '"') - return; - if (typeof b6 != "string") - return `${a5.slice(0, -1)}${b6}"`; - if (b6[0] === '"') - return a5.slice(0, -1) + b6.slice(1); - return; - } - if (typeof b6 == "string" && b6[0] === '"' && !(a5 instanceof Name2)) - return `"${a5}${b6.slice(1)}`; - return; - } - function strConcat(c1, c22) { - return c22.emptyStr() ? c1 : c1.emptyStr() ? c22 : str`${c1}${c22}`; - } - exports.strConcat = strConcat; - function interpolate(x5) { - return typeof x5 == "number" || typeof x5 == "boolean" || x5 === null ? x5 : safeStringify2(Array.isArray(x5) ? x5.join(",") : x5); - } - function stringify2(x5) { - return new _Code(safeStringify2(x5)); - } - exports.stringify = stringify2; - function safeStringify2(x5) { - return JSON.stringify(x5).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029"); - } - exports.safeStringify = safeStringify2; - function getProperty(key) { - return typeof key == "string" && exports.IDENTIFIER.test(key) ? new _Code(`.${key}`) : _`[${key}]`; - } - exports.getProperty = getProperty; - function getEsmExportName(key) { - if (typeof key == "string" && exports.IDENTIFIER.test(key)) { - return new _Code(`${key}`); - } - throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`); - } - exports.getEsmExportName = getEsmExportName; - function regexpCode(rx) { - return new _Code(rx.toString()); - } - exports.regexpCode = regexpCode; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/codegen/scope.js -var require_scope = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/codegen/scope.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.ValueScope = exports.ValueScopeName = exports.Scope = exports.varKinds = exports.UsedValueState = void 0; - var code_1 = require_code(); - var ValueError = class extends Error { - constructor(name) { - super(`CodeGen: "code" for ${name} not defined`); - this.value = name.value; - } - }; - var UsedValueState; - (function(UsedValueState2) { - UsedValueState2[UsedValueState2["Started"] = 0] = "Started"; - UsedValueState2[UsedValueState2["Completed"] = 1] = "Completed"; - })(UsedValueState || (exports.UsedValueState = UsedValueState = {})); - exports.varKinds = { - const: new code_1.Name("const"), - let: new code_1.Name("let"), - var: new code_1.Name("var") - }; - var Scope = class { - constructor({ prefixes, parent } = {}) { - this._names = {}; - this._prefixes = prefixes; - this._parent = parent; - } - toName(nameOrPrefix) { - return nameOrPrefix instanceof code_1.Name ? nameOrPrefix : this.name(nameOrPrefix); - } - name(prefix) { - return new code_1.Name(this._newName(prefix)); - } - _newName(prefix) { - const ng = this._names[prefix] || this._nameGroup(prefix); - return `${prefix}${ng.index++}`; - } - _nameGroup(prefix) { - var _a6, _b; - if (((_b = (_a6 = this._parent) === null || _a6 === void 0 ? void 0 : _a6._prefixes) === null || _b === void 0 ? void 0 : _b.has(prefix)) || this._prefixes && !this._prefixes.has(prefix)) { - throw new Error(`CodeGen: prefix "${prefix}" is not allowed in this scope`); - } - return this._names[prefix] = { prefix, index: 0 }; - } - }; - exports.Scope = Scope; - var ValueScopeName = class extends code_1.Name { - constructor(prefix, nameStr) { - super(nameStr); - this.prefix = prefix; - } - setValue(value, { property, itemIndex }) { - this.value = value; - this.scopePath = (0, code_1._)`.${new code_1.Name(property)}[${itemIndex}]`; - } - }; - exports.ValueScopeName = ValueScopeName; - var line3 = (0, code_1._)`\n`; - var ValueScope = class extends Scope { - constructor(opts) { - super(opts); - this._values = {}; - this._scope = opts.scope; - this.opts = { ...opts, _n: opts.lines ? line3 : code_1.nil }; - } - get() { - return this._scope; - } - name(prefix) { - return new ValueScopeName(prefix, this._newName(prefix)); - } - value(nameOrPrefix, value) { - var _a6; - if (value.ref === void 0) - throw new Error("CodeGen: ref must be passed in value"); - const name = this.toName(nameOrPrefix); - const { prefix } = name; - const valueKey = (_a6 = value.key) !== null && _a6 !== void 0 ? _a6 : value.ref; - let vs = this._values[prefix]; - if (vs) { - const _name = vs.get(valueKey); - if (_name) - return _name; - } else { - vs = this._values[prefix] = /* @__PURE__ */ new Map(); - } - vs.set(valueKey, name); - const s5 = this._scope[prefix] || (this._scope[prefix] = []); - const itemIndex = s5.length; - s5[itemIndex] = value.ref; - name.setValue(value, { property: prefix, itemIndex }); - return name; - } - getValue(prefix, keyOrRef) { - const vs = this._values[prefix]; - if (!vs) - return; - return vs.get(keyOrRef); - } - scopeRefs(scopeName, values2 = this._values) { - return this._reduceValues(values2, (name) => { - if (name.scopePath === void 0) - throw new Error(`CodeGen: name "${name}" has no value`); - return (0, code_1._)`${scopeName}${name.scopePath}`; - }); - } - scopeCode(values2 = this._values, usedValues, getCode) { - return this._reduceValues(values2, (name) => { - if (name.value === void 0) - throw new Error(`CodeGen: name "${name}" has no value`); - return name.value.code; - }, usedValues, getCode); - } - _reduceValues(values2, valueCode, usedValues = {}, getCode) { - let code = code_1.nil; - for (const prefix in values2) { - const vs = values2[prefix]; - if (!vs) - continue; - const nameSet = usedValues[prefix] = usedValues[prefix] || /* @__PURE__ */ new Map(); - vs.forEach((name) => { - if (nameSet.has(name)) - return; - nameSet.set(name, UsedValueState.Started); - let c5 = valueCode(name); - if (c5) { - const def = this.opts.es5 ? exports.varKinds.var : exports.varKinds.const; - code = (0, code_1._)`${code}${def} ${name} = ${c5};${this.opts._n}`; - } else if (c5 = getCode === null || getCode === void 0 ? void 0 : getCode(name)) { - code = (0, code_1._)`${code}${c5}${this.opts._n}`; - } else { - throw new ValueError(name); - } - nameSet.set(name, UsedValueState.Completed); - }); - } - return code; - } - }; - exports.ValueScope = ValueScope; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/codegen/index.js -var require_codegen = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/codegen/index.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.or = exports.and = exports.not = exports.CodeGen = exports.operators = exports.varKinds = exports.ValueScopeName = exports.ValueScope = exports.Scope = exports.Name = exports.regexpCode = exports.stringify = exports.getProperty = exports.nil = exports.strConcat = exports.str = exports._ = void 0; - var code_1 = require_code(); - var scope_1 = require_scope(); - var code_2 = require_code(); - Object.defineProperty(exports, "_", { enumerable: true, get: function() { - return code_2._; - } }); - Object.defineProperty(exports, "str", { enumerable: true, get: function() { - return code_2.str; - } }); - Object.defineProperty(exports, "strConcat", { enumerable: true, get: function() { - return code_2.strConcat; - } }); - Object.defineProperty(exports, "nil", { enumerable: true, get: function() { - return code_2.nil; - } }); - Object.defineProperty(exports, "getProperty", { enumerable: true, get: function() { - return code_2.getProperty; - } }); - Object.defineProperty(exports, "stringify", { enumerable: true, get: function() { - return code_2.stringify; - } }); - Object.defineProperty(exports, "regexpCode", { enumerable: true, get: function() { - return code_2.regexpCode; - } }); - Object.defineProperty(exports, "Name", { enumerable: true, get: function() { - return code_2.Name; - } }); - var scope_2 = require_scope(); - Object.defineProperty(exports, "Scope", { enumerable: true, get: function() { - return scope_2.Scope; - } }); - Object.defineProperty(exports, "ValueScope", { enumerable: true, get: function() { - return scope_2.ValueScope; - } }); - Object.defineProperty(exports, "ValueScopeName", { enumerable: true, get: function() { - return scope_2.ValueScopeName; - } }); - Object.defineProperty(exports, "varKinds", { enumerable: true, get: function() { - return scope_2.varKinds; - } }); - exports.operators = { - GT: new code_1._Code(">"), - GTE: new code_1._Code(">="), - LT: new code_1._Code("<"), - LTE: new code_1._Code("<="), - EQ: new code_1._Code("==="), - NEQ: new code_1._Code("!=="), - NOT: new code_1._Code("!"), - OR: new code_1._Code("||"), - AND: new code_1._Code("&&"), - ADD: new code_1._Code("+") - }; - var Node = class { - optimizeNodes() { - return this; - } - optimizeNames(_names, _constants) { - return this; - } - }; - var Def = class extends Node { - constructor(varKind, name, rhs) { - super(); - this.varKind = varKind; - this.name = name; - this.rhs = rhs; - } - render({ es5, _n }) { - const varKind = es5 ? scope_1.varKinds.var : this.varKind; - const rhs = this.rhs === void 0 ? "" : ` = ${this.rhs}`; - return `${varKind} ${this.name}${rhs};` + _n; - } - optimizeNames(names, constants) { - if (!names[this.name.str]) - return; - if (this.rhs) - this.rhs = optimizeExpr(this.rhs, names, constants); - return this; - } - get names() { - return this.rhs instanceof code_1._CodeOrName ? this.rhs.names : {}; - } - }; - var Assign = class extends Node { - constructor(lhs, rhs, sideEffects) { - super(); - this.lhs = lhs; - this.rhs = rhs; - this.sideEffects = sideEffects; - } - render({ _n }) { - return `${this.lhs} = ${this.rhs};` + _n; - } - optimizeNames(names, constants) { - if (this.lhs instanceof code_1.Name && !names[this.lhs.str] && !this.sideEffects) - return; - this.rhs = optimizeExpr(this.rhs, names, constants); - return this; - } - get names() { - const names = this.lhs instanceof code_1.Name ? {} : { ...this.lhs.names }; - return addExprNames(names, this.rhs); - } - }; - var AssignOp = class extends Assign { - constructor(lhs, op2, rhs, sideEffects) { - super(lhs, rhs, sideEffects); - this.op = op2; - } - render({ _n }) { - return `${this.lhs} ${this.op}= ${this.rhs};` + _n; - } - }; - var Label = class extends Node { - constructor(label) { - super(); - this.label = label; - this.names = {}; - } - render({ _n }) { - return `${this.label}:` + _n; - } - }; - var Break = class extends Node { - constructor(label) { - super(); - this.label = label; - this.names = {}; - } - render({ _n }) { - const label = this.label ? ` ${this.label}` : ""; - return `break${label};` + _n; - } - }; - var Throw = class extends Node { - constructor(error50) { - super(); - this.error = error50; - } - render({ _n }) { - return `throw ${this.error};` + _n; - } - get names() { - return this.error.names; - } - }; - var AnyCode = class extends Node { - constructor(code) { - super(); - this.code = code; - } - render({ _n }) { - return `${this.code};` + _n; - } - optimizeNodes() { - return `${this.code}` ? this : void 0; - } - optimizeNames(names, constants) { - this.code = optimizeExpr(this.code, names, constants); - return this; - } - get names() { - return this.code instanceof code_1._CodeOrName ? this.code.names : {}; - } - }; - var ParentNode = class extends Node { - constructor(nodes = []) { - super(); - this.nodes = nodes; - } - render(opts) { - return this.nodes.reduce((code, n5) => code + n5.render(opts), ""); - } - optimizeNodes() { - const { nodes } = this; - let i5 = nodes.length; - while (i5--) { - const n5 = nodes[i5].optimizeNodes(); - if (Array.isArray(n5)) - nodes.splice(i5, 1, ...n5); - else if (n5) - nodes[i5] = n5; - else - nodes.splice(i5, 1); - } - return nodes.length > 0 ? this : void 0; - } - optimizeNames(names, constants) { - const { nodes } = this; - let i5 = nodes.length; - while (i5--) { - const n5 = nodes[i5]; - if (n5.optimizeNames(names, constants)) - continue; - subtractNames(names, n5.names); - nodes.splice(i5, 1); - } - return nodes.length > 0 ? this : void 0; - } - get names() { - return this.nodes.reduce((names, n5) => addNames(names, n5.names), {}); - } - }; - var BlockNode = class extends ParentNode { - render(opts) { - return "{" + opts._n + super.render(opts) + "}" + opts._n; - } - }; - var Root = class extends ParentNode { - }; - var Else = class extends BlockNode { - }; - Else.kind = "else"; - var If = class _If extends BlockNode { - constructor(condition, nodes) { - super(nodes); - this.condition = condition; - } - render(opts) { - let code = `if(${this.condition})` + super.render(opts); - if (this.else) - code += "else " + this.else.render(opts); - return code; - } - optimizeNodes() { - super.optimizeNodes(); - const cond = this.condition; - if (cond === true) - return this.nodes; - let e5 = this.else; - if (e5) { - const ns = e5.optimizeNodes(); - e5 = this.else = Array.isArray(ns) ? new Else(ns) : ns; - } - if (e5) { - if (cond === false) - return e5 instanceof _If ? e5 : e5.nodes; - if (this.nodes.length) - return this; - return new _If(not2(cond), e5 instanceof _If ? [e5] : e5.nodes); - } - if (cond === false || !this.nodes.length) - return void 0; - return this; - } - optimizeNames(names, constants) { - var _a6; - this.else = (_a6 = this.else) === null || _a6 === void 0 ? void 0 : _a6.optimizeNames(names, constants); - if (!(super.optimizeNames(names, constants) || this.else)) - return; - this.condition = optimizeExpr(this.condition, names, constants); - return this; - } - get names() { - const names = super.names; - addExprNames(names, this.condition); - if (this.else) - addNames(names, this.else.names); - return names; - } - }; - If.kind = "if"; - var For = class extends BlockNode { - }; - For.kind = "for"; - var ForLoop = class extends For { - constructor(iteration) { - super(); - this.iteration = iteration; - } - render(opts) { - return `for(${this.iteration})` + super.render(opts); - } - optimizeNames(names, constants) { - if (!super.optimizeNames(names, constants)) - return; - this.iteration = optimizeExpr(this.iteration, names, constants); - return this; - } - get names() { - return addNames(super.names, this.iteration.names); - } - }; - var ForRange = class extends For { - constructor(varKind, name, from, to) { - super(); - this.varKind = varKind; - this.name = name; - this.from = from; - this.to = to; - } - render(opts) { - const varKind = opts.es5 ? scope_1.varKinds.var : this.varKind; - const { name, from, to } = this; - return `for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)` + super.render(opts); - } - get names() { - const names = addExprNames(super.names, this.from); - return addExprNames(names, this.to); - } - }; - var ForIter = class extends For { - constructor(loop, varKind, name, iterable) { - super(); - this.loop = loop; - this.varKind = varKind; - this.name = name; - this.iterable = iterable; - } - render(opts) { - return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts); - } - optimizeNames(names, constants) { - if (!super.optimizeNames(names, constants)) - return; - this.iterable = optimizeExpr(this.iterable, names, constants); - return this; - } - get names() { - return addNames(super.names, this.iterable.names); - } - }; - var Func = class extends BlockNode { - constructor(name, args, async) { - super(); - this.name = name; - this.args = args; - this.async = async; - } - render(opts) { - const _async = this.async ? "async " : ""; - return `${_async}function ${this.name}(${this.args})` + super.render(opts); - } - }; - Func.kind = "func"; - var Return = class extends ParentNode { - render(opts) { - return "return " + super.render(opts); - } - }; - Return.kind = "return"; - var Try = class extends BlockNode { - render(opts) { - let code = "try" + super.render(opts); - if (this.catch) - code += this.catch.render(opts); - if (this.finally) - code += this.finally.render(opts); - return code; - } - optimizeNodes() { - var _a6, _b; - super.optimizeNodes(); - (_a6 = this.catch) === null || _a6 === void 0 ? void 0 : _a6.optimizeNodes(); - (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNodes(); - return this; - } - optimizeNames(names, constants) { - var _a6, _b; - super.optimizeNames(names, constants); - (_a6 = this.catch) === null || _a6 === void 0 ? void 0 : _a6.optimizeNames(names, constants); - (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNames(names, constants); - return this; - } - get names() { - const names = super.names; - if (this.catch) - addNames(names, this.catch.names); - if (this.finally) - addNames(names, this.finally.names); - return names; - } - }; - var Catch = class extends BlockNode { - constructor(error50) { - super(); - this.error = error50; - } - render(opts) { - return `catch(${this.error})` + super.render(opts); - } - }; - Catch.kind = "catch"; - var Finally = class extends BlockNode { - render(opts) { - return "finally" + super.render(opts); - } - }; - Finally.kind = "finally"; - var CodeGen = class { - constructor(extScope, opts = {}) { - this._values = {}; - this._blockStarts = []; - this._constants = {}; - this.opts = { ...opts, _n: opts.lines ? "\n" : "" }; - this._extScope = extScope; - this._scope = new scope_1.Scope({ parent: extScope }); - this._nodes = [new Root()]; - } - toString() { - return this._root.render(this.opts); - } - // returns unique name in the internal scope - name(prefix) { - return this._scope.name(prefix); - } - // reserves unique name in the external scope - scopeName(prefix) { - return this._extScope.name(prefix); - } - // reserves unique name in the external scope and assigns value to it - scopeValue(prefixOrName, value) { - const name = this._extScope.value(prefixOrName, value); - const vs = this._values[name.prefix] || (this._values[name.prefix] = /* @__PURE__ */ new Set()); - vs.add(name); - return name; - } - getScopeValue(prefix, keyOrRef) { - return this._extScope.getValue(prefix, keyOrRef); - } - // return code that assigns values in the external scope to the names that are used internally - // (same names that were returned by gen.scopeName or gen.scopeValue) - scopeRefs(scopeName) { - return this._extScope.scopeRefs(scopeName, this._values); - } - scopeCode() { - return this._extScope.scopeCode(this._values); - } - _def(varKind, nameOrPrefix, rhs, constant) { - const name = this._scope.toName(nameOrPrefix); - if (rhs !== void 0 && constant) - this._constants[name.str] = rhs; - this._leafNode(new Def(varKind, name, rhs)); - return name; - } - // `const` declaration (`var` in es5 mode) - const(nameOrPrefix, rhs, _constant) { - return this._def(scope_1.varKinds.const, nameOrPrefix, rhs, _constant); - } - // `let` declaration with optional assignment (`var` in es5 mode) - let(nameOrPrefix, rhs, _constant) { - return this._def(scope_1.varKinds.let, nameOrPrefix, rhs, _constant); - } - // `var` declaration with optional assignment - var(nameOrPrefix, rhs, _constant) { - return this._def(scope_1.varKinds.var, nameOrPrefix, rhs, _constant); - } - // assignment code - assign(lhs, rhs, sideEffects) { - return this._leafNode(new Assign(lhs, rhs, sideEffects)); - } - // `+=` code - add(lhs, rhs) { - return this._leafNode(new AssignOp(lhs, exports.operators.ADD, rhs)); - } - // appends passed SafeExpr to code or executes Block - code(c5) { - if (typeof c5 == "function") - c5(); - else if (c5 !== code_1.nil) - this._leafNode(new AnyCode(c5)); - return this; - } - // returns code for object literal for the passed argument list of key-value pairs - object(...keyValues) { - const code = ["{"]; - for (const [key, value] of keyValues) { - if (code.length > 1) - code.push(","); - code.push(key); - if (key !== value || this.opts.es5) { - code.push(":"); - (0, code_1.addCodeArg)(code, value); - } - } - code.push("}"); - return new code_1._Code(code); - } - // `if` clause (or statement if `thenBody` and, optionally, `elseBody` are passed) - if(condition, thenBody, elseBody) { - this._blockNode(new If(condition)); - if (thenBody && elseBody) { - this.code(thenBody).else().code(elseBody).endIf(); - } else if (thenBody) { - this.code(thenBody).endIf(); - } else if (elseBody) { - throw new Error('CodeGen: "else" body without "then" body'); - } - return this; - } - // `else if` clause - invalid without `if` or after `else` clauses - elseIf(condition) { - return this._elseNode(new If(condition)); - } - // `else` clause - only valid after `if` or `else if` clauses - else() { - return this._elseNode(new Else()); - } - // end `if` statement (needed if gen.if was used only with condition) - endIf() { - return this._endBlockNode(If, Else); - } - _for(node, forBody) { - this._blockNode(node); - if (forBody) - this.code(forBody).endFor(); - return this; - } - // a generic `for` clause (or statement if `forBody` is passed) - for(iteration, forBody) { - return this._for(new ForLoop(iteration), forBody); - } - // `for` statement for a range of values - forRange(nameOrPrefix, from, to, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.let) { - const name = this._scope.toName(nameOrPrefix); - return this._for(new ForRange(varKind, name, from, to), () => forBody(name)); - } - // `for-of` statement (in es5 mode replace with a normal for loop) - forOf(nameOrPrefix, iterable, forBody, varKind = scope_1.varKinds.const) { - const name = this._scope.toName(nameOrPrefix); - if (this.opts.es5) { - const arr = iterable instanceof code_1.Name ? iterable : this.var("_arr", iterable); - return this.forRange("_i", 0, (0, code_1._)`${arr}.length`, (i5) => { - this.var(name, (0, code_1._)`${arr}[${i5}]`); - forBody(name); - }); - } - return this._for(new ForIter("of", varKind, name, iterable), () => forBody(name)); - } - // `for-in` statement. - // With option `ownProperties` replaced with a `for-of` loop for object keys - forIn(nameOrPrefix, obj, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.const) { - if (this.opts.ownProperties) { - return this.forOf(nameOrPrefix, (0, code_1._)`Object.keys(${obj})`, forBody); - } - const name = this._scope.toName(nameOrPrefix); - return this._for(new ForIter("in", varKind, name, obj), () => forBody(name)); - } - // end `for` loop - endFor() { - return this._endBlockNode(For); - } - // `label` statement - label(label) { - return this._leafNode(new Label(label)); - } - // `break` statement - break(label) { - return this._leafNode(new Break(label)); - } - // `return` statement - return(value) { - const node = new Return(); - this._blockNode(node); - this.code(value); - if (node.nodes.length !== 1) - throw new Error('CodeGen: "return" should have one node'); - return this._endBlockNode(Return); - } - // `try` statement - try(tryBody, catchCode, finallyCode) { - if (!catchCode && !finallyCode) - throw new Error('CodeGen: "try" without "catch" and "finally"'); - const node = new Try(); - this._blockNode(node); - this.code(tryBody); - if (catchCode) { - const error50 = this.name("e"); - this._currNode = node.catch = new Catch(error50); - catchCode(error50); - } - if (finallyCode) { - this._currNode = node.finally = new Finally(); - this.code(finallyCode); - } - return this._endBlockNode(Catch, Finally); - } - // `throw` statement - throw(error50) { - return this._leafNode(new Throw(error50)); - } - // start self-balancing block - block(body, nodeCount) { - this._blockStarts.push(this._nodes.length); - if (body) - this.code(body).endBlock(nodeCount); - return this; - } - // end the current self-balancing block - endBlock(nodeCount) { - const len = this._blockStarts.pop(); - if (len === void 0) - throw new Error("CodeGen: not in self-balancing block"); - const toClose = this._nodes.length - len; - if (toClose < 0 || nodeCount !== void 0 && toClose !== nodeCount) { - throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`); - } - this._nodes.length = len; - return this; - } - // `function` heading (or definition if funcBody is passed) - func(name, args = code_1.nil, async, funcBody) { - this._blockNode(new Func(name, args, async)); - if (funcBody) - this.code(funcBody).endFunc(); - return this; - } - // end function definition - endFunc() { - return this._endBlockNode(Func); - } - optimize(n5 = 1) { - while (n5-- > 0) { - this._root.optimizeNodes(); - this._root.optimizeNames(this._root.names, this._constants); - } - } - _leafNode(node) { - this._currNode.nodes.push(node); - return this; - } - _blockNode(node) { - this._currNode.nodes.push(node); - this._nodes.push(node); - } - _endBlockNode(N1, N2) { - const n5 = this._currNode; - if (n5 instanceof N1 || N2 && n5 instanceof N2) { - this._nodes.pop(); - return this; - } - throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`); - } - _elseNode(node) { - const n5 = this._currNode; - if (!(n5 instanceof If)) { - throw new Error('CodeGen: "else" without "if"'); - } - this._currNode = n5.else = node; - return this; - } - get _root() { - return this._nodes[0]; - } - get _currNode() { - const ns = this._nodes; - return ns[ns.length - 1]; - } - set _currNode(node) { - const ns = this._nodes; - ns[ns.length - 1] = node; - } - }; - exports.CodeGen = CodeGen; - function addNames(names, from) { - for (const n5 in from) - names[n5] = (names[n5] || 0) + (from[n5] || 0); - return names; - } - function addExprNames(names, from) { - return from instanceof code_1._CodeOrName ? addNames(names, from.names) : names; - } - function optimizeExpr(expr, names, constants) { - if (expr instanceof code_1.Name) - return replaceName(expr); - if (!canOptimize(expr)) - return expr; - return new code_1._Code(expr._items.reduce((items, c5) => { - if (c5 instanceof code_1.Name) - c5 = replaceName(c5); - if (c5 instanceof code_1._Code) - items.push(...c5._items); - else - items.push(c5); - return items; - }, [])); - function replaceName(n5) { - const c5 = constants[n5.str]; - if (c5 === void 0 || names[n5.str] !== 1) - return n5; - delete names[n5.str]; - return c5; - } - function canOptimize(e5) { - return e5 instanceof code_1._Code && e5._items.some((c5) => c5 instanceof code_1.Name && names[c5.str] === 1 && constants[c5.str] !== void 0); - } - } - function subtractNames(names, from) { - for (const n5 in from) - names[n5] = (names[n5] || 0) - (from[n5] || 0); - } - function not2(x5) { - return typeof x5 == "boolean" || typeof x5 == "number" || x5 === null ? !x5 : (0, code_1._)`!${par(x5)}`; - } - exports.not = not2; - var andCode = mappend(exports.operators.AND); - function and2(...args) { - return args.reduce(andCode); - } - exports.and = and2; - var orCode = mappend(exports.operators.OR); - function or3(...args) { - return args.reduce(orCode); - } - exports.or = or3; - function mappend(op2) { - return (x5, y2) => x5 === code_1.nil ? y2 : y2 === code_1.nil ? x5 : (0, code_1._)`${par(x5)} ${op2} ${par(y2)}`; - } - function par(x5) { - return x5 instanceof code_1.Name ? x5 : (0, code_1._)`(${x5})`; - } - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/util.js -var require_util = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/util.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.checkStrictMode = exports.getErrorPath = exports.Type = exports.useFunc = exports.setEvaluated = exports.evaluatedPropsToName = exports.mergeEvaluated = exports.eachItem = exports.unescapeJsonPointer = exports.escapeJsonPointer = exports.escapeFragment = exports.unescapeFragment = exports.schemaRefOrVal = exports.schemaHasRulesButRef = exports.schemaHasRules = exports.checkUnknownRules = exports.alwaysValidSchema = exports.toHash = void 0; - var codegen_1 = require_codegen(); - var code_1 = require_code(); - function toHash(arr) { - const hash2 = {}; - for (const item of arr) - hash2[item] = true; - return hash2; - } - exports.toHash = toHash; - function alwaysValidSchema(it, schema2) { - if (typeof schema2 == "boolean") - return schema2; - if (Object.keys(schema2).length === 0) - return true; - checkUnknownRules(it, schema2); - return !schemaHasRules(schema2, it.self.RULES.all); - } - exports.alwaysValidSchema = alwaysValidSchema; - function checkUnknownRules(it, schema2 = it.schema) { - const { opts, self: self2 } = it; - if (!opts.strictSchema) - return; - if (typeof schema2 === "boolean") - return; - const rules = self2.RULES.keywords; - for (const key in schema2) { - if (!rules[key]) - checkStrictMode(it, `unknown keyword: "${key}"`); - } - } - exports.checkUnknownRules = checkUnknownRules; - function schemaHasRules(schema2, rules) { - if (typeof schema2 == "boolean") - return !schema2; - for (const key in schema2) - if (rules[key]) - return true; - return false; - } - exports.schemaHasRules = schemaHasRules; - function schemaHasRulesButRef(schema2, RULES) { - if (typeof schema2 == "boolean") - return !schema2; - for (const key in schema2) - if (key !== "$ref" && RULES.all[key]) - return true; - return false; - } - exports.schemaHasRulesButRef = schemaHasRulesButRef; - function schemaRefOrVal({ topSchemaRef, schemaPath }, schema2, keyword, $data) { - if (!$data) { - if (typeof schema2 == "number" || typeof schema2 == "boolean") - return schema2; - if (typeof schema2 == "string") - return (0, codegen_1._)`${schema2}`; - } - return (0, codegen_1._)`${topSchemaRef}${schemaPath}${(0, codegen_1.getProperty)(keyword)}`; - } - exports.schemaRefOrVal = schemaRefOrVal; - function unescapeFragment(str) { - return unescapeJsonPointer(decodeURIComponent(str)); - } - exports.unescapeFragment = unescapeFragment; - function escapeFragment(str) { - return encodeURIComponent(escapeJsonPointer(str)); - } - exports.escapeFragment = escapeFragment; - function escapeJsonPointer(str) { - if (typeof str == "number") - return `${str}`; - return str.replace(/~/g, "~0").replace(/\//g, "~1"); - } - exports.escapeJsonPointer = escapeJsonPointer; - function unescapeJsonPointer(str) { - return str.replace(/~1/g, "/").replace(/~0/g, "~"); - } - exports.unescapeJsonPointer = unescapeJsonPointer; - function eachItem(xs, f5) { - if (Array.isArray(xs)) { - for (const x5 of xs) - f5(x5); - } else { - f5(xs); - } - } - exports.eachItem = eachItem; - function makeMergeEvaluated({ mergeNames, mergeToName, mergeValues: mergeValues3, resultToName }) { - return (gen, from, to, toName) => { - const res = to === void 0 ? from : to instanceof codegen_1.Name ? (from instanceof codegen_1.Name ? mergeNames(gen, from, to) : mergeToName(gen, from, to), to) : from instanceof codegen_1.Name ? (mergeToName(gen, to, from), from) : mergeValues3(from, to); - return toName === codegen_1.Name && !(res instanceof codegen_1.Name) ? resultToName(gen, res) : res; - }; - } - exports.mergeEvaluated = { - props: makeMergeEvaluated({ - mergeNames: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true && ${from} !== undefined`, () => { - gen.if((0, codegen_1._)`${from} === true`, () => gen.assign(to, true), () => gen.assign(to, (0, codegen_1._)`${to} || {}`).code((0, codegen_1._)`Object.assign(${to}, ${from})`)); - }), - mergeToName: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true`, () => { - if (from === true) { - gen.assign(to, true); - } else { - gen.assign(to, (0, codegen_1._)`${to} || {}`); - setEvaluated(gen, to, from); - } - }), - mergeValues: (from, to) => from === true ? true : { ...from, ...to }, - resultToName: evaluatedPropsToName - }), - items: makeMergeEvaluated({ - mergeNames: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true && ${from} !== undefined`, () => gen.assign(to, (0, codegen_1._)`${from} === true ? true : ${to} > ${from} ? ${to} : ${from}`)), - mergeToName: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true`, () => gen.assign(to, from === true ? true : (0, codegen_1._)`${to} > ${from} ? ${to} : ${from}`)), - mergeValues: (from, to) => from === true ? true : Math.max(from, to), - resultToName: (gen, items) => gen.var("items", items) - }) - }; - function evaluatedPropsToName(gen, ps) { - if (ps === true) - return gen.var("props", true); - const props = gen.var("props", (0, codegen_1._)`{}`); - if (ps !== void 0) - setEvaluated(gen, props, ps); - return props; - } - exports.evaluatedPropsToName = evaluatedPropsToName; - function setEvaluated(gen, props, ps) { - Object.keys(ps).forEach((p5) => gen.assign((0, codegen_1._)`${props}${(0, codegen_1.getProperty)(p5)}`, true)); - } - exports.setEvaluated = setEvaluated; - var snippets = {}; - function useFunc(gen, f5) { - return gen.scopeValue("func", { - ref: f5, - code: snippets[f5.code] || (snippets[f5.code] = new code_1._Code(f5.code)) - }); - } - exports.useFunc = useFunc; - var Type; - (function(Type2) { - Type2[Type2["Num"] = 0] = "Num"; - Type2[Type2["Str"] = 1] = "Str"; - })(Type || (exports.Type = Type = {})); - function getErrorPath(dataProp, dataPropType, jsPropertySyntax) { - if (dataProp instanceof codegen_1.Name) { - const isNumber2 = dataPropType === Type.Num; - return jsPropertySyntax ? isNumber2 ? (0, codegen_1._)`"[" + ${dataProp} + "]"` : (0, codegen_1._)`"['" + ${dataProp} + "']"` : isNumber2 ? (0, codegen_1._)`"/" + ${dataProp}` : (0, codegen_1._)`"/" + ${dataProp}.replace(/~/g, "~0").replace(/\\//g, "~1")`; - } - return jsPropertySyntax ? (0, codegen_1.getProperty)(dataProp).toString() : "/" + escapeJsonPointer(dataProp); - } - exports.getErrorPath = getErrorPath; - function checkStrictMode(it, msg, mode = it.opts.strictSchema) { - if (!mode) - return; - msg = `strict mode: ${msg}`; - if (mode === true) - throw new Error(msg); - it.self.logger.warn(msg); - } - exports.checkStrictMode = checkStrictMode; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/names.js -var require_names = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/names.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - var codegen_1 = require_codegen(); - var names = { - // validation function arguments - data: new codegen_1.Name("data"), - // data passed to validation function - // args passed from referencing schema - valCxt: new codegen_1.Name("valCxt"), - // validation/data context - should not be used directly, it is destructured to the names below - instancePath: new codegen_1.Name("instancePath"), - parentData: new codegen_1.Name("parentData"), - parentDataProperty: new codegen_1.Name("parentDataProperty"), - rootData: new codegen_1.Name("rootData"), - // root data - same as the data passed to the first/top validation function - dynamicAnchors: new codegen_1.Name("dynamicAnchors"), - // used to support recursiveRef and dynamicRef - // function scoped variables - vErrors: new codegen_1.Name("vErrors"), - // null or array of validation errors - errors: new codegen_1.Name("errors"), - // counter of validation errors - this: new codegen_1.Name("this"), - // "globals" - self: new codegen_1.Name("self"), - scope: new codegen_1.Name("scope"), - // JTD serialize/parse name for JSON string and position - json: new codegen_1.Name("json"), - jsonPos: new codegen_1.Name("jsonPos"), - jsonLen: new codegen_1.Name("jsonLen"), - jsonPart: new codegen_1.Name("jsonPart") - }; - exports.default = names; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/errors.js -var require_errors3 = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/errors.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.extendErrors = exports.resetErrorsCount = exports.reportExtraError = exports.reportError = exports.keyword$DataError = exports.keywordError = void 0; - var codegen_1 = require_codegen(); - var util_1 = require_util(); - var names_1 = require_names(); - exports.keywordError = { - message: ({ keyword }) => (0, codegen_1.str)`must pass "${keyword}" keyword validation` - }; - exports.keyword$DataError = { - message: ({ keyword, schemaType }) => schemaType ? (0, codegen_1.str)`"${keyword}" keyword must be ${schemaType} ($data)` : (0, codegen_1.str)`"${keyword}" keyword is invalid ($data)` - }; - function reportError(cxt, error50 = exports.keywordError, errorPaths, overrideAllErrors) { - const { it } = cxt; - const { gen, compositeRule, allErrors } = it; - const errObj = errorObjectCode(cxt, error50, errorPaths); - if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : compositeRule || allErrors) { - addError(gen, errObj); - } else { - returnErrors(it, (0, codegen_1._)`[${errObj}]`); - } - } - exports.reportError = reportError; - function reportExtraError(cxt, error50 = exports.keywordError, errorPaths) { - const { it } = cxt; - const { gen, compositeRule, allErrors } = it; - const errObj = errorObjectCode(cxt, error50, errorPaths); - addError(gen, errObj); - if (!(compositeRule || allErrors)) { - returnErrors(it, names_1.default.vErrors); - } - } - exports.reportExtraError = reportExtraError; - function resetErrorsCount(gen, errsCount) { - gen.assign(names_1.default.errors, errsCount); - gen.if((0, codegen_1._)`${names_1.default.vErrors} !== null`, () => gen.if(errsCount, () => gen.assign((0, codegen_1._)`${names_1.default.vErrors}.length`, errsCount), () => gen.assign(names_1.default.vErrors, null))); - } - exports.resetErrorsCount = resetErrorsCount; - function extendErrors({ gen, keyword, schemaValue, data: data2, errsCount, it }) { - if (errsCount === void 0) - throw new Error("ajv implementation error"); - const err = gen.name("err"); - gen.forRange("i", errsCount, names_1.default.errors, (i5) => { - gen.const(err, (0, codegen_1._)`${names_1.default.vErrors}[${i5}]`); - gen.if((0, codegen_1._)`${err}.instancePath === undefined`, () => gen.assign((0, codegen_1._)`${err}.instancePath`, (0, codegen_1.strConcat)(names_1.default.instancePath, it.errorPath))); - gen.assign((0, codegen_1._)`${err}.schemaPath`, (0, codegen_1.str)`${it.errSchemaPath}/${keyword}`); - if (it.opts.verbose) { - gen.assign((0, codegen_1._)`${err}.schema`, schemaValue); - gen.assign((0, codegen_1._)`${err}.data`, data2); - } - }); - } - exports.extendErrors = extendErrors; - function addError(gen, errObj) { - const err = gen.const("err", errObj); - gen.if((0, codegen_1._)`${names_1.default.vErrors} === null`, () => gen.assign(names_1.default.vErrors, (0, codegen_1._)`[${err}]`), (0, codegen_1._)`${names_1.default.vErrors}.push(${err})`); - gen.code((0, codegen_1._)`${names_1.default.errors}++`); - } - function returnErrors(it, errs) { - const { gen, validateName, schemaEnv } = it; - if (schemaEnv.$async) { - gen.throw((0, codegen_1._)`new ${it.ValidationError}(${errs})`); - } else { - gen.assign((0, codegen_1._)`${validateName}.errors`, errs); - gen.return(false); - } - } - var E2 = { - keyword: new codegen_1.Name("keyword"), - schemaPath: new codegen_1.Name("schemaPath"), - // also used in JTD errors - params: new codegen_1.Name("params"), - propertyName: new codegen_1.Name("propertyName"), - message: new codegen_1.Name("message"), - schema: new codegen_1.Name("schema"), - parentSchema: new codegen_1.Name("parentSchema") - }; - function errorObjectCode(cxt, error50, errorPaths) { - const { createErrors } = cxt.it; - if (createErrors === false) - return (0, codegen_1._)`{}`; - return errorObject(cxt, error50, errorPaths); - } - function errorObject(cxt, error50, errorPaths = {}) { - const { gen, it } = cxt; - const keyValues = [ - errorInstancePath(it, errorPaths), - errorSchemaPath(cxt, errorPaths) - ]; - extraErrorProps(cxt, error50, keyValues); - return gen.object(...keyValues); - } - function errorInstancePath({ errorPath }, { instancePath }) { - const instPath = instancePath ? (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(instancePath, util_1.Type.Str)}` : errorPath; - return [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, instPath)]; - } - function errorSchemaPath({ keyword, it: { errSchemaPath } }, { schemaPath, parentSchema }) { - let schPath = parentSchema ? errSchemaPath : (0, codegen_1.str)`${errSchemaPath}/${keyword}`; - if (schemaPath) { - schPath = (0, codegen_1.str)`${schPath}${(0, util_1.getErrorPath)(schemaPath, util_1.Type.Str)}`; - } - return [E2.schemaPath, schPath]; - } - function extraErrorProps(cxt, { params, message: message2 }, keyValues) { - const { keyword, data: data2, schemaValue, it } = cxt; - const { opts, propertyName, topSchemaRef, schemaPath } = it; - keyValues.push([E2.keyword, keyword], [E2.params, typeof params == "function" ? params(cxt) : params || (0, codegen_1._)`{}`]); - if (opts.messages) { - keyValues.push([E2.message, typeof message2 == "function" ? message2(cxt) : message2]); - } - if (opts.verbose) { - keyValues.push([E2.schema, schemaValue], [E2.parentSchema, (0, codegen_1._)`${topSchemaRef}${schemaPath}`], [names_1.default.data, data2]); - } - if (propertyName) - keyValues.push([E2.propertyName, propertyName]); - } - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/boolSchema.js -var require_boolSchema = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/boolSchema.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.boolOrEmptySchema = exports.topBoolOrEmptySchema = void 0; - var errors_1 = require_errors3(); - var codegen_1 = require_codegen(); - var names_1 = require_names(); - var boolError = { - message: "boolean schema is false" - }; - function topBoolOrEmptySchema(it) { - const { gen, schema: schema2, validateName } = it; - if (schema2 === false) { - falseSchemaError(it, false); - } else if (typeof schema2 == "object" && schema2.$async === true) { - gen.return(names_1.default.data); - } else { - gen.assign((0, codegen_1._)`${validateName}.errors`, null); - gen.return(true); - } - } - exports.topBoolOrEmptySchema = topBoolOrEmptySchema; - function boolOrEmptySchema(it, valid) { - const { gen, schema: schema2 } = it; - if (schema2 === false) { - gen.var(valid, false); - falseSchemaError(it); - } else { - gen.var(valid, true); - } - } - exports.boolOrEmptySchema = boolOrEmptySchema; - function falseSchemaError(it, overrideAllErrors) { - const { gen, data: data2 } = it; - const cxt = { - gen, - keyword: "false schema", - data: data2, - schema: false, - schemaCode: false, - schemaValue: false, - params: {}, - it - }; - (0, errors_1.reportError)(cxt, boolError, void 0, overrideAllErrors); - } - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/rules.js -var require_rules = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/rules.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.getRules = exports.isJSONType = void 0; - var _jsonTypes = ["string", "number", "integer", "boolean", "null", "object", "array"]; - var jsonTypes = new Set(_jsonTypes); - function isJSONType(x5) { - return typeof x5 == "string" && jsonTypes.has(x5); - } - exports.isJSONType = isJSONType; - function getRules() { - const groups = { - number: { type: "number", rules: [] }, - string: { type: "string", rules: [] }, - array: { type: "array", rules: [] }, - object: { type: "object", rules: [] } - }; - return { - types: { ...groups, integer: true, boolean: true, null: true }, - rules: [{ rules: [] }, groups.number, groups.string, groups.array, groups.object], - post: { rules: [] }, - all: {}, - keywords: {} - }; - } - exports.getRules = getRules; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/applicability.js -var require_applicability = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/applicability.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.shouldUseRule = exports.shouldUseGroup = exports.schemaHasRulesForType = void 0; - function schemaHasRulesForType({ schema: schema2, self: self2 }, type) { - const group = self2.RULES.types[type]; - return group && group !== true && shouldUseGroup(schema2, group); - } - exports.schemaHasRulesForType = schemaHasRulesForType; - function shouldUseGroup(schema2, group) { - return group.rules.some((rule) => shouldUseRule(schema2, rule)); - } - exports.shouldUseGroup = shouldUseGroup; - function shouldUseRule(schema2, rule) { - var _a6; - return schema2[rule.keyword] !== void 0 || ((_a6 = rule.definition.implements) === null || _a6 === void 0 ? void 0 : _a6.some((kwd) => schema2[kwd] !== void 0)); - } - exports.shouldUseRule = shouldUseRule; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/dataType.js -var require_dataType = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/dataType.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.reportTypeError = exports.checkDataTypes = exports.checkDataType = exports.coerceAndCheckDataType = exports.getJSONTypes = exports.getSchemaTypes = exports.DataType = void 0; - var rules_1 = require_rules(); - var applicability_1 = require_applicability(); - var errors_1 = require_errors3(); - var codegen_1 = require_codegen(); - var util_1 = require_util(); - var DataType; - (function(DataType2) { - DataType2[DataType2["Correct"] = 0] = "Correct"; - DataType2[DataType2["Wrong"] = 1] = "Wrong"; - })(DataType || (exports.DataType = DataType = {})); - function getSchemaTypes(schema2) { - const types2 = getJSONTypes(schema2.type); - const hasNull = types2.includes("null"); - if (hasNull) { - if (schema2.nullable === false) - throw new Error("type: null contradicts nullable: false"); - } else { - if (!types2.length && schema2.nullable !== void 0) { - throw new Error('"nullable" cannot be used without "type"'); - } - if (schema2.nullable === true) - types2.push("null"); - } - return types2; - } - exports.getSchemaTypes = getSchemaTypes; - function getJSONTypes(ts) { - const types2 = Array.isArray(ts) ? ts : ts ? [ts] : []; - if (types2.every(rules_1.isJSONType)) - return types2; - throw new Error("type must be JSONType or JSONType[]: " + types2.join(",")); - } - exports.getJSONTypes = getJSONTypes; - function coerceAndCheckDataType(it, types2) { - const { gen, data: data2, opts } = it; - const coerceTo = coerceToTypes(types2, opts.coerceTypes); - const checkTypes = types2.length > 0 && !(coerceTo.length === 0 && types2.length === 1 && (0, applicability_1.schemaHasRulesForType)(it, types2[0])); - if (checkTypes) { - const wrongType = checkDataTypes(types2, data2, opts.strictNumbers, DataType.Wrong); - gen.if(wrongType, () => { - if (coerceTo.length) - coerceData(it, types2, coerceTo); - else - reportTypeError(it); - }); - } - return checkTypes; - } - exports.coerceAndCheckDataType = coerceAndCheckDataType; - var COERCIBLE = /* @__PURE__ */ new Set(["string", "number", "integer", "boolean", "null"]); - function coerceToTypes(types2, coerceTypes) { - return coerceTypes ? types2.filter((t5) => COERCIBLE.has(t5) || coerceTypes === "array" && t5 === "array") : []; - } - function coerceData(it, types2, coerceTo) { - const { gen, data: data2, opts } = it; - const dataType = gen.let("dataType", (0, codegen_1._)`typeof ${data2}`); - const coerced = gen.let("coerced", (0, codegen_1._)`undefined`); - if (opts.coerceTypes === "array") { - gen.if((0, codegen_1._)`${dataType} == 'object' && Array.isArray(${data2}) && ${data2}.length == 1`, () => gen.assign(data2, (0, codegen_1._)`${data2}[0]`).assign(dataType, (0, codegen_1._)`typeof ${data2}`).if(checkDataTypes(types2, data2, opts.strictNumbers), () => gen.assign(coerced, data2))); - } - gen.if((0, codegen_1._)`${coerced} !== undefined`); - for (const t5 of coerceTo) { - if (COERCIBLE.has(t5) || t5 === "array" && opts.coerceTypes === "array") { - coerceSpecificType(t5); - } - } - gen.else(); - reportTypeError(it); - gen.endIf(); - gen.if((0, codegen_1._)`${coerced} !== undefined`, () => { - gen.assign(data2, coerced); - assignParentData(it, coerced); - }); - function coerceSpecificType(t5) { - switch (t5) { - case "string": - gen.elseIf((0, codegen_1._)`${dataType} == "number" || ${dataType} == "boolean"`).assign(coerced, (0, codegen_1._)`"" + ${data2}`).elseIf((0, codegen_1._)`${data2} === null`).assign(coerced, (0, codegen_1._)`""`); - return; - case "number": - gen.elseIf((0, codegen_1._)`${dataType} == "boolean" || ${data2} === null - || (${dataType} == "string" && ${data2} && ${data2} == +${data2})`).assign(coerced, (0, codegen_1._)`+${data2}`); - return; - case "integer": - gen.elseIf((0, codegen_1._)`${dataType} === "boolean" || ${data2} === null - || (${dataType} === "string" && ${data2} && ${data2} == +${data2} && !(${data2} % 1))`).assign(coerced, (0, codegen_1._)`+${data2}`); - return; - case "boolean": - gen.elseIf((0, codegen_1._)`${data2} === "false" || ${data2} === 0 || ${data2} === null`).assign(coerced, false).elseIf((0, codegen_1._)`${data2} === "true" || ${data2} === 1`).assign(coerced, true); - return; - case "null": - gen.elseIf((0, codegen_1._)`${data2} === "" || ${data2} === 0 || ${data2} === false`); - gen.assign(coerced, null); - return; - case "array": - gen.elseIf((0, codegen_1._)`${dataType} === "string" || ${dataType} === "number" - || ${dataType} === "boolean" || ${data2} === null`).assign(coerced, (0, codegen_1._)`[${data2}]`); - } - } - } - function assignParentData({ gen, parentData, parentDataProperty }, expr) { - gen.if((0, codegen_1._)`${parentData} !== undefined`, () => gen.assign((0, codegen_1._)`${parentData}[${parentDataProperty}]`, expr)); - } - function checkDataType(dataType, data2, strictNums, correct = DataType.Correct) { - const EQ = correct === DataType.Correct ? codegen_1.operators.EQ : codegen_1.operators.NEQ; - let cond; - switch (dataType) { - case "null": - return (0, codegen_1._)`${data2} ${EQ} null`; - case "array": - cond = (0, codegen_1._)`Array.isArray(${data2})`; - break; - case "object": - cond = (0, codegen_1._)`${data2} && typeof ${data2} == "object" && !Array.isArray(${data2})`; - break; - case "integer": - cond = numCond((0, codegen_1._)`!(${data2} % 1) && !isNaN(${data2})`); - break; - case "number": - cond = numCond(); - break; - default: - return (0, codegen_1._)`typeof ${data2} ${EQ} ${dataType}`; - } - return correct === DataType.Correct ? cond : (0, codegen_1.not)(cond); - function numCond(_cond = codegen_1.nil) { - return (0, codegen_1.and)((0, codegen_1._)`typeof ${data2} == "number"`, _cond, strictNums ? (0, codegen_1._)`isFinite(${data2})` : codegen_1.nil); - } - } - exports.checkDataType = checkDataType; - function checkDataTypes(dataTypes, data2, strictNums, correct) { - if (dataTypes.length === 1) { - return checkDataType(dataTypes[0], data2, strictNums, correct); - } - let cond; - const types2 = (0, util_1.toHash)(dataTypes); - if (types2.array && types2.object) { - const notObj = (0, codegen_1._)`typeof ${data2} != "object"`; - cond = types2.null ? notObj : (0, codegen_1._)`!${data2} || ${notObj}`; - delete types2.null; - delete types2.array; - delete types2.object; - } else { - cond = codegen_1.nil; - } - if (types2.number) - delete types2.integer; - for (const t5 in types2) - cond = (0, codegen_1.and)(cond, checkDataType(t5, data2, strictNums, correct)); - return cond; - } - exports.checkDataTypes = checkDataTypes; - var typeError = { - message: ({ schema: schema2 }) => `must be ${schema2}`, - params: ({ schema: schema2, schemaValue }) => typeof schema2 == "string" ? (0, codegen_1._)`{type: ${schema2}}` : (0, codegen_1._)`{type: ${schemaValue}}` - }; - function reportTypeError(it) { - const cxt = getTypeErrorContext(it); - (0, errors_1.reportError)(cxt, typeError); - } - exports.reportTypeError = reportTypeError; - function getTypeErrorContext(it) { - const { gen, data: data2, schema: schema2 } = it; - const schemaCode = (0, util_1.schemaRefOrVal)(it, schema2, "type"); - return { - gen, - keyword: "type", - data: data2, - schema: schema2.type, - schemaCode, - schemaValue: schemaCode, - parentSchema: schema2, - params: {}, - it - }; - } - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/defaults.js -var require_defaults = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/defaults.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.assignDefaults = void 0; - var codegen_1 = require_codegen(); - var util_1 = require_util(); - function assignDefaults(it, ty) { - const { properties, items } = it.schema; - if (ty === "object" && properties) { - for (const key in properties) { - assignDefault(it, key, properties[key].default); - } - } else if (ty === "array" && Array.isArray(items)) { - items.forEach((sch, i5) => assignDefault(it, i5, sch.default)); - } - } - exports.assignDefaults = assignDefaults; - function assignDefault(it, prop, defaultValue) { - const { gen, compositeRule, data: data2, opts } = it; - if (defaultValue === void 0) - return; - const childData = (0, codegen_1._)`${data2}${(0, codegen_1.getProperty)(prop)}`; - if (compositeRule) { - (0, util_1.checkStrictMode)(it, `default is ignored for: ${childData}`); - return; - } - let condition = (0, codegen_1._)`${childData} === undefined`; - if (opts.useDefaults === "empty") { - condition = (0, codegen_1._)`${condition} || ${childData} === null || ${childData} === ""`; - } - gen.if(condition, (0, codegen_1._)`${childData} = ${(0, codegen_1.stringify)(defaultValue)}`); - } - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/code.js -var require_code2 = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/code.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.validateUnion = exports.validateArray = exports.usePattern = exports.callValidateCode = exports.schemaProperties = exports.allSchemaProperties = exports.noPropertyInData = exports.propertyInData = exports.isOwnProperty = exports.hasPropFunc = exports.reportMissingProp = exports.checkMissingProp = exports.checkReportMissingProp = void 0; - var codegen_1 = require_codegen(); - var util_1 = require_util(); - var names_1 = require_names(); - var util_2 = require_util(); - function checkReportMissingProp(cxt, prop) { - const { gen, data: data2, it } = cxt; - gen.if(noPropertyInData(gen, data2, prop, it.opts.ownProperties), () => { - cxt.setParams({ missingProperty: (0, codegen_1._)`${prop}` }, true); - cxt.error(); - }); - } - exports.checkReportMissingProp = checkReportMissingProp; - function checkMissingProp({ gen, data: data2, it: { opts } }, properties, missing) { - return (0, codegen_1.or)(...properties.map((prop) => (0, codegen_1.and)(noPropertyInData(gen, data2, prop, opts.ownProperties), (0, codegen_1._)`${missing} = ${prop}`))); - } - exports.checkMissingProp = checkMissingProp; - function reportMissingProp(cxt, missing) { - cxt.setParams({ missingProperty: missing }, true); - cxt.error(); - } - exports.reportMissingProp = reportMissingProp; - function hasPropFunc(gen) { - return gen.scopeValue("func", { - // eslint-disable-next-line @typescript-eslint/unbound-method - ref: Object.prototype.hasOwnProperty, - code: (0, codegen_1._)`Object.prototype.hasOwnProperty` - }); - } - exports.hasPropFunc = hasPropFunc; - function isOwnProperty(gen, data2, property) { - return (0, codegen_1._)`${hasPropFunc(gen)}.call(${data2}, ${property})`; - } - exports.isOwnProperty = isOwnProperty; - function propertyInData(gen, data2, property, ownProperties) { - const cond = (0, codegen_1._)`${data2}${(0, codegen_1.getProperty)(property)} !== undefined`; - return ownProperties ? (0, codegen_1._)`${cond} && ${isOwnProperty(gen, data2, property)}` : cond; - } - exports.propertyInData = propertyInData; - function noPropertyInData(gen, data2, property, ownProperties) { - const cond = (0, codegen_1._)`${data2}${(0, codegen_1.getProperty)(property)} === undefined`; - return ownProperties ? (0, codegen_1.or)(cond, (0, codegen_1.not)(isOwnProperty(gen, data2, property))) : cond; - } - exports.noPropertyInData = noPropertyInData; - function allSchemaProperties(schemaMap) { - return schemaMap ? Object.keys(schemaMap).filter((p5) => p5 !== "__proto__") : []; - } - exports.allSchemaProperties = allSchemaProperties; - function schemaProperties(it, schemaMap) { - return allSchemaProperties(schemaMap).filter((p5) => !(0, util_1.alwaysValidSchema)(it, schemaMap[p5])); - } - exports.schemaProperties = schemaProperties; - function callValidateCode({ schemaCode, data: data2, it: { gen, topSchemaRef, schemaPath, errorPath }, it }, func, context, passSchema) { - const dataAndSchema = passSchema ? (0, codegen_1._)`${schemaCode}, ${data2}, ${topSchemaRef}${schemaPath}` : data2; - const valCxt = [ - [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, errorPath)], - [names_1.default.parentData, it.parentData], - [names_1.default.parentDataProperty, it.parentDataProperty], - [names_1.default.rootData, names_1.default.rootData] - ]; - if (it.opts.dynamicRef) - valCxt.push([names_1.default.dynamicAnchors, names_1.default.dynamicAnchors]); - const args = (0, codegen_1._)`${dataAndSchema}, ${gen.object(...valCxt)}`; - return context !== codegen_1.nil ? (0, codegen_1._)`${func}.call(${context}, ${args})` : (0, codegen_1._)`${func}(${args})`; - } - exports.callValidateCode = callValidateCode; - var newRegExp = (0, codegen_1._)`new RegExp`; - function usePattern({ gen, it: { opts } }, pattern) { - const u5 = opts.unicodeRegExp ? "u" : ""; - const { regExp } = opts.code; - const rx = regExp(pattern, u5); - return gen.scopeValue("pattern", { - key: rx.toString(), - ref: rx, - code: (0, codegen_1._)`${regExp.code === "new RegExp" ? newRegExp : (0, util_2.useFunc)(gen, regExp)}(${pattern}, ${u5})` - }); - } - exports.usePattern = usePattern; - function validateArray(cxt) { - const { gen, data: data2, keyword, it } = cxt; - const valid = gen.name("valid"); - if (it.allErrors) { - const validArr = gen.let("valid", true); - validateItems(() => gen.assign(validArr, false)); - return validArr; - } - gen.var(valid, true); - validateItems(() => gen.break()); - return valid; - function validateItems(notValid) { - const len = gen.const("len", (0, codegen_1._)`${data2}.length`); - gen.forRange("i", 0, len, (i5) => { - cxt.subschema({ - keyword, - dataProp: i5, - dataPropType: util_1.Type.Num - }, valid); - gen.if((0, codegen_1.not)(valid), notValid); - }); - } - } - exports.validateArray = validateArray; - function validateUnion(cxt) { - const { gen, schema: schema2, keyword, it } = cxt; - if (!Array.isArray(schema2)) - throw new Error("ajv implementation error"); - const alwaysValid = schema2.some((sch) => (0, util_1.alwaysValidSchema)(it, sch)); - if (alwaysValid && !it.opts.unevaluated) - return; - const valid = gen.let("valid", false); - const schValid = gen.name("_valid"); - gen.block(() => schema2.forEach((_sch, i5) => { - const schCxt = cxt.subschema({ - keyword, - schemaProp: i5, - compositeRule: true - }, schValid); - gen.assign(valid, (0, codegen_1._)`${valid} || ${schValid}`); - const merged = cxt.mergeValidEvaluated(schCxt, schValid); - if (!merged) - gen.if((0, codegen_1.not)(valid)); - })); - cxt.result(valid, () => cxt.reset(), () => cxt.error(true)); - } - exports.validateUnion = validateUnion; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/keyword.js -var require_keyword = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/keyword.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.validateKeywordUsage = exports.validSchemaType = exports.funcKeywordCode = exports.macroKeywordCode = void 0; - var codegen_1 = require_codegen(); - var names_1 = require_names(); - var code_1 = require_code2(); - var errors_1 = require_errors3(); - function macroKeywordCode(cxt, def) { - const { gen, keyword, schema: schema2, parentSchema, it } = cxt; - const macroSchema = def.macro.call(it.self, schema2, parentSchema, it); - const schemaRef = useKeyword(gen, keyword, macroSchema); - if (it.opts.validateSchema !== false) - it.self.validateSchema(macroSchema, true); - const valid = gen.name("valid"); - cxt.subschema({ - schema: macroSchema, - schemaPath: codegen_1.nil, - errSchemaPath: `${it.errSchemaPath}/${keyword}`, - topSchemaRef: schemaRef, - compositeRule: true - }, valid); - cxt.pass(valid, () => cxt.error(true)); - } - exports.macroKeywordCode = macroKeywordCode; - function funcKeywordCode(cxt, def) { - var _a6; - const { gen, keyword, schema: schema2, parentSchema, $data, it } = cxt; - checkAsyncKeyword(it, def); - const validate2 = !$data && def.compile ? def.compile.call(it.self, schema2, parentSchema, it) : def.validate; - const validateRef = useKeyword(gen, keyword, validate2); - const valid = gen.let("valid"); - cxt.block$data(valid, validateKeyword); - cxt.ok((_a6 = def.valid) !== null && _a6 !== void 0 ? _a6 : valid); - function validateKeyword() { - if (def.errors === false) { - assignValid(); - if (def.modifying) - modifyData(cxt); - reportErrs(() => cxt.error()); - } else { - const ruleErrs = def.async ? validateAsync() : validateSync(); - if (def.modifying) - modifyData(cxt); - reportErrs(() => addErrs(cxt, ruleErrs)); - } - } - function validateAsync() { - const ruleErrs = gen.let("ruleErrs", null); - gen.try(() => assignValid((0, codegen_1._)`await `), (e5) => gen.assign(valid, false).if((0, codegen_1._)`${e5} instanceof ${it.ValidationError}`, () => gen.assign(ruleErrs, (0, codegen_1._)`${e5}.errors`), () => gen.throw(e5))); - return ruleErrs; - } - function validateSync() { - const validateErrs = (0, codegen_1._)`${validateRef}.errors`; - gen.assign(validateErrs, null); - assignValid(codegen_1.nil); - return validateErrs; - } - function assignValid(_await = def.async ? (0, codegen_1._)`await ` : codegen_1.nil) { - const passCxt = it.opts.passContext ? names_1.default.this : names_1.default.self; - const passSchema = !("compile" in def && !$data || def.schema === false); - gen.assign(valid, (0, codegen_1._)`${_await}${(0, code_1.callValidateCode)(cxt, validateRef, passCxt, passSchema)}`, def.modifying); - } - function reportErrs(errors) { - var _a7; - gen.if((0, codegen_1.not)((_a7 = def.valid) !== null && _a7 !== void 0 ? _a7 : valid), errors); - } - } - exports.funcKeywordCode = funcKeywordCode; - function modifyData(cxt) { - const { gen, data: data2, it } = cxt; - gen.if(it.parentData, () => gen.assign(data2, (0, codegen_1._)`${it.parentData}[${it.parentDataProperty}]`)); - } - function addErrs(cxt, errs) { - const { gen } = cxt; - gen.if((0, codegen_1._)`Array.isArray(${errs})`, () => { - gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`).assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`); - (0, errors_1.extendErrors)(cxt); - }, () => cxt.error()); - } - function checkAsyncKeyword({ schemaEnv }, def) { - if (def.async && !schemaEnv.$async) - throw new Error("async keyword in sync schema"); - } - function useKeyword(gen, keyword, result) { - if (result === void 0) - throw new Error(`keyword "${keyword}" failed to compile`); - return gen.scopeValue("keyword", typeof result == "function" ? { ref: result } : { ref: result, code: (0, codegen_1.stringify)(result) }); - } - function validSchemaType(schema2, schemaType, allowUndefined = false) { - return !schemaType.length || schemaType.some((st) => st === "array" ? Array.isArray(schema2) : st === "object" ? schema2 && typeof schema2 == "object" && !Array.isArray(schema2) : typeof schema2 == st || allowUndefined && typeof schema2 == "undefined"); - } - exports.validSchemaType = validSchemaType; - function validateKeywordUsage({ schema: schema2, opts, self: self2, errSchemaPath }, def, keyword) { - if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) { - throw new Error("ajv implementation error"); - } - const deps = def.dependencies; - if (deps === null || deps === void 0 ? void 0 : deps.some((kwd) => !Object.prototype.hasOwnProperty.call(schema2, kwd))) { - throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(",")}`); - } - if (def.validateSchema) { - const valid = def.validateSchema(schema2[keyword]); - if (!valid) { - const msg = `keyword "${keyword}" value is invalid at path "${errSchemaPath}": ` + self2.errorsText(def.validateSchema.errors); - if (opts.validateSchema === "log") - self2.logger.error(msg); - else - throw new Error(msg); - } - } - } - exports.validateKeywordUsage = validateKeywordUsage; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/subschema.js -var require_subschema = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/subschema.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.extendSubschemaMode = exports.extendSubschemaData = exports.getSubschema = void 0; - var codegen_1 = require_codegen(); - var util_1 = require_util(); - function getSubschema(it, { keyword, schemaProp, schema: schema2, schemaPath, errSchemaPath, topSchemaRef }) { - if (keyword !== void 0 && schema2 !== void 0) { - throw new Error('both "keyword" and "schema" passed, only one allowed'); - } - if (keyword !== void 0) { - const sch = it.schema[keyword]; - return schemaProp === void 0 ? { - schema: sch, - schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}`, - errSchemaPath: `${it.errSchemaPath}/${keyword}` - } : { - schema: sch[schemaProp], - schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}${(0, codegen_1.getProperty)(schemaProp)}`, - errSchemaPath: `${it.errSchemaPath}/${keyword}/${(0, util_1.escapeFragment)(schemaProp)}` - }; - } - if (schema2 !== void 0) { - if (schemaPath === void 0 || errSchemaPath === void 0 || topSchemaRef === void 0) { - throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"'); - } - return { - schema: schema2, - schemaPath, - topSchemaRef, - errSchemaPath - }; - } - throw new Error('either "keyword" or "schema" must be passed'); - } - exports.getSubschema = getSubschema; - function extendSubschemaData(subschema, it, { dataProp, dataPropType: dpType, data: data2, dataTypes, propertyName }) { - if (data2 !== void 0 && dataProp !== void 0) { - throw new Error('both "data" and "dataProp" passed, only one allowed'); - } - const { gen } = it; - if (dataProp !== void 0) { - const { errorPath, dataPathArr, opts } = it; - const nextData = gen.let("data", (0, codegen_1._)`${it.data}${(0, codegen_1.getProperty)(dataProp)}`, true); - dataContextProps(nextData); - subschema.errorPath = (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(dataProp, dpType, opts.jsPropertySyntax)}`; - subschema.parentDataProperty = (0, codegen_1._)`${dataProp}`; - subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty]; - } - if (data2 !== void 0) { - const nextData = data2 instanceof codegen_1.Name ? data2 : gen.let("data", data2, true); - dataContextProps(nextData); - if (propertyName !== void 0) - subschema.propertyName = propertyName; - } - if (dataTypes) - subschema.dataTypes = dataTypes; - function dataContextProps(_nextData) { - subschema.data = _nextData; - subschema.dataLevel = it.dataLevel + 1; - subschema.dataTypes = []; - it.definedProperties = /* @__PURE__ */ new Set(); - subschema.parentData = it.data; - subschema.dataNames = [...it.dataNames, _nextData]; - } - } - exports.extendSubschemaData = extendSubschemaData; - function extendSubschemaMode(subschema, { jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors }) { - if (compositeRule !== void 0) - subschema.compositeRule = compositeRule; - if (createErrors !== void 0) - subschema.createErrors = createErrors; - if (allErrors !== void 0) - subschema.allErrors = allErrors; - subschema.jtdDiscriminator = jtdDiscriminator; - subschema.jtdMetadata = jtdMetadata; - } - exports.extendSubschemaMode = extendSubschemaMode; - } -}); - -// node_modules/.pnpm/fast-deep-equal@3.1.3/node_modules/fast-deep-equal/index.js -var require_fast_deep_equal = __commonJS({ - "node_modules/.pnpm/fast-deep-equal@3.1.3/node_modules/fast-deep-equal/index.js"(exports, module) { - "use strict"; - module.exports = function equal(a5, b6) { - if (a5 === b6) return true; - if (a5 && b6 && typeof a5 == "object" && typeof b6 == "object") { - if (a5.constructor !== b6.constructor) return false; - var length, i5, keys; - if (Array.isArray(a5)) { - length = a5.length; - if (length != b6.length) return false; - for (i5 = length; i5-- !== 0; ) - if (!equal(a5[i5], b6[i5])) return false; - return true; - } - if (a5.constructor === RegExp) return a5.source === b6.source && a5.flags === b6.flags; - if (a5.valueOf !== Object.prototype.valueOf) return a5.valueOf() === b6.valueOf(); - if (a5.toString !== Object.prototype.toString) return a5.toString() === b6.toString(); - keys = Object.keys(a5); - length = keys.length; - if (length !== Object.keys(b6).length) return false; - for (i5 = length; i5-- !== 0; ) - if (!Object.prototype.hasOwnProperty.call(b6, keys[i5])) return false; - for (i5 = length; i5-- !== 0; ) { - var key = keys[i5]; - if (!equal(a5[key], b6[key])) return false; - } - return true; - } - return a5 !== a5 && b6 !== b6; - }; - } -}); - -// node_modules/.pnpm/json-schema-traverse@1.0.0/node_modules/json-schema-traverse/index.js -var require_json_schema_traverse = __commonJS({ - "node_modules/.pnpm/json-schema-traverse@1.0.0/node_modules/json-schema-traverse/index.js"(exports, module) { - "use strict"; - var traverse = module.exports = function(schema2, opts, cb) { - if (typeof opts == "function") { - cb = opts; - opts = {}; - } - cb = opts.cb || cb; - var pre = typeof cb == "function" ? cb : cb.pre || function() { - }; - var post = cb.post || function() { - }; - _traverse(opts, pre, post, schema2, "", schema2); - }; - traverse.keywords = { - additionalItems: true, - items: true, - contains: true, - additionalProperties: true, - propertyNames: true, - not: true, - if: true, - then: true, - else: true - }; - traverse.arrayKeywords = { - items: true, - allOf: true, - anyOf: true, - oneOf: true - }; - traverse.propsKeywords = { - $defs: true, - definitions: true, - properties: true, - patternProperties: true, - dependencies: true - }; - traverse.skipKeywords = { - default: true, - enum: true, - const: true, - required: true, - maximum: true, - minimum: true, - exclusiveMaximum: true, - exclusiveMinimum: true, - multipleOf: true, - maxLength: true, - minLength: true, - pattern: true, - format: true, - maxItems: true, - minItems: true, - uniqueItems: true, - maxProperties: true, - minProperties: true - }; - function _traverse(opts, pre, post, schema2, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) { - if (schema2 && typeof schema2 == "object" && !Array.isArray(schema2)) { - pre(schema2, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); - for (var key in schema2) { - var sch = schema2[key]; - if (Array.isArray(sch)) { - if (key in traverse.arrayKeywords) { - for (var i5 = 0; i5 < sch.length; i5++) - _traverse(opts, pre, post, sch[i5], jsonPtr + "/" + key + "/" + i5, rootSchema, jsonPtr, key, schema2, i5); - } - } else if (key in traverse.propsKeywords) { - if (sch && typeof sch == "object") { - for (var prop in sch) - _traverse(opts, pre, post, sch[prop], jsonPtr + "/" + key + "/" + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema2, prop); - } - } else if (key in traverse.keywords || opts.allKeys && !(key in traverse.skipKeywords)) { - _traverse(opts, pre, post, sch, jsonPtr + "/" + key, rootSchema, jsonPtr, key, schema2); - } - } - post(schema2, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); - } - } - function escapeJsonPtr(str) { - return str.replace(/~/g, "~0").replace(/\//g, "~1"); - } - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/resolve.js -var require_resolve = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/resolve.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.getSchemaRefs = exports.resolveUrl = exports.normalizeId = exports._getFullPath = exports.getFullPath = exports.inlineRef = void 0; - var util_1 = require_util(); - var equal = require_fast_deep_equal(); - var traverse = require_json_schema_traverse(); - var SIMPLE_INLINED = /* @__PURE__ */ new Set([ - "type", - "format", - "pattern", - "maxLength", - "minLength", - "maxProperties", - "minProperties", - "maxItems", - "minItems", - "maximum", - "minimum", - "uniqueItems", - "multipleOf", - "required", - "enum", - "const" - ]); - function inlineRef(schema2, limit = true) { - if (typeof schema2 == "boolean") - return true; - if (limit === true) - return !hasRef(schema2); - if (!limit) - return false; - return countKeys(schema2) <= limit; - } - exports.inlineRef = inlineRef; - var REF_KEYWORDS = /* @__PURE__ */ new Set([ - "$ref", - "$recursiveRef", - "$recursiveAnchor", - "$dynamicRef", - "$dynamicAnchor" - ]); - function hasRef(schema2) { - for (const key in schema2) { - if (REF_KEYWORDS.has(key)) - return true; - const sch = schema2[key]; - if (Array.isArray(sch) && sch.some(hasRef)) - return true; - if (typeof sch == "object" && hasRef(sch)) - return true; - } - return false; - } - function countKeys(schema2) { - let count2 = 0; - for (const key in schema2) { - if (key === "$ref") - return Infinity; - count2++; - if (SIMPLE_INLINED.has(key)) - continue; - if (typeof schema2[key] == "object") { - (0, util_1.eachItem)(schema2[key], (sch) => count2 += countKeys(sch)); - } - if (count2 === Infinity) - return Infinity; - } - return count2; - } - function getFullPath(resolver, id = "", normalize2) { - if (normalize2 !== false) - id = normalizeId(id); - const p5 = resolver.parse(id); - return _getFullPath(resolver, p5); - } - exports.getFullPath = getFullPath; - function _getFullPath(resolver, p5) { - const serialized = resolver.serialize(p5); - return serialized.split("#")[0] + "#"; - } - exports._getFullPath = _getFullPath; - var TRAILING_SLASH_HASH = /#\/?$/; - function normalizeId(id) { - return id ? id.replace(TRAILING_SLASH_HASH, "") : ""; - } - exports.normalizeId = normalizeId; - function resolveUrl(resolver, baseId, id) { - id = normalizeId(id); - return resolver.resolve(baseId, id); - } - exports.resolveUrl = resolveUrl; - var ANCHOR = /^[a-z_][-a-z0-9._]*$/i; - function getSchemaRefs(schema2, baseId) { - if (typeof schema2 == "boolean") - return {}; - const { schemaId, uriResolver } = this.opts; - const schId = normalizeId(schema2[schemaId] || baseId); - const baseIds = { "": schId }; - const pathPrefix = getFullPath(uriResolver, schId, false); - const localRefs = {}; - const schemaRefs = /* @__PURE__ */ new Set(); - traverse(schema2, { allKeys: true }, (sch, jsonPtr, _, parentJsonPtr) => { - if (parentJsonPtr === void 0) - return; - const fullPath = pathPrefix + jsonPtr; - let innerBaseId = baseIds[parentJsonPtr]; - if (typeof sch[schemaId] == "string") - innerBaseId = addRef.call(this, sch[schemaId]); - addAnchor.call(this, sch.$anchor); - addAnchor.call(this, sch.$dynamicAnchor); - baseIds[jsonPtr] = innerBaseId; - function addRef(ref) { - const _resolve = this.opts.uriResolver.resolve; - ref = normalizeId(innerBaseId ? _resolve(innerBaseId, ref) : ref); - if (schemaRefs.has(ref)) - throw ambiguos(ref); - schemaRefs.add(ref); - let schOrRef = this.refs[ref]; - if (typeof schOrRef == "string") - schOrRef = this.refs[schOrRef]; - if (typeof schOrRef == "object") { - checkAmbiguosRef(sch, schOrRef.schema, ref); - } else if (ref !== normalizeId(fullPath)) { - if (ref[0] === "#") { - checkAmbiguosRef(sch, localRefs[ref], ref); - localRefs[ref] = sch; - } else { - this.refs[ref] = fullPath; - } - } - return ref; - } - function addAnchor(anchor) { - if (typeof anchor == "string") { - if (!ANCHOR.test(anchor)) - throw new Error(`invalid anchor "${anchor}"`); - addRef.call(this, `#${anchor}`); - } - } - }); - return localRefs; - function checkAmbiguosRef(sch1, sch2, ref) { - if (sch2 !== void 0 && !equal(sch1, sch2)) - throw ambiguos(ref); - } - function ambiguos(ref) { - return new Error(`reference "${ref}" resolves to more than one schema`); - } - } - exports.getSchemaRefs = getSchemaRefs; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/index.js -var require_validate = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/index.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.getData = exports.KeywordCxt = exports.validateFunctionCode = void 0; - var boolSchema_1 = require_boolSchema(); - var dataType_1 = require_dataType(); - var applicability_1 = require_applicability(); - var dataType_2 = require_dataType(); - var defaults_1 = require_defaults(); - var keyword_1 = require_keyword(); - var subschema_1 = require_subschema(); - var codegen_1 = require_codegen(); - var names_1 = require_names(); - var resolve_1 = require_resolve(); - var util_1 = require_util(); - var errors_1 = require_errors3(); - function validateFunctionCode(it) { - if (isSchemaObj(it)) { - checkKeywords(it); - if (schemaCxtHasRules(it)) { - topSchemaObjCode(it); - return; - } - } - validateFunction(it, () => (0, boolSchema_1.topBoolOrEmptySchema)(it)); - } - exports.validateFunctionCode = validateFunctionCode; - function validateFunction({ gen, validateName, schema: schema2, schemaEnv, opts }, body) { - if (opts.code.es5) { - gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${names_1.default.valCxt}`, schemaEnv.$async, () => { - gen.code((0, codegen_1._)`"use strict"; ${funcSourceUrl(schema2, opts)}`); - destructureValCxtES5(gen, opts); - gen.code(body); - }); - } else { - gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () => gen.code(funcSourceUrl(schema2, opts)).code(body)); - } - } - function destructureValCxt(opts) { - return (0, codegen_1._)`{${names_1.default.instancePath}="", ${names_1.default.parentData}, ${names_1.default.parentDataProperty}, ${names_1.default.rootData}=${names_1.default.data}${opts.dynamicRef ? (0, codegen_1._)`, ${names_1.default.dynamicAnchors}={}` : codegen_1.nil}}={}`; - } - function destructureValCxtES5(gen, opts) { - gen.if(names_1.default.valCxt, () => { - gen.var(names_1.default.instancePath, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.instancePath}`); - gen.var(names_1.default.parentData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentData}`); - gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentDataProperty}`); - gen.var(names_1.default.rootData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.rootData}`); - if (opts.dynamicRef) - gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.dynamicAnchors}`); - }, () => { - gen.var(names_1.default.instancePath, (0, codegen_1._)`""`); - gen.var(names_1.default.parentData, (0, codegen_1._)`undefined`); - gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`undefined`); - gen.var(names_1.default.rootData, names_1.default.data); - if (opts.dynamicRef) - gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`{}`); - }); - } - function topSchemaObjCode(it) { - const { schema: schema2, opts, gen } = it; - validateFunction(it, () => { - if (opts.$comment && schema2.$comment) - commentKeyword(it); - checkNoDefault(it); - gen.let(names_1.default.vErrors, null); - gen.let(names_1.default.errors, 0); - if (opts.unevaluated) - resetEvaluated(it); - typeAndKeywords(it); - returnResults(it); - }); - return; - } - function resetEvaluated(it) { - const { gen, validateName } = it; - it.evaluated = gen.const("evaluated", (0, codegen_1._)`${validateName}.evaluated`); - gen.if((0, codegen_1._)`${it.evaluated}.dynamicProps`, () => gen.assign((0, codegen_1._)`${it.evaluated}.props`, (0, codegen_1._)`undefined`)); - gen.if((0, codegen_1._)`${it.evaluated}.dynamicItems`, () => gen.assign((0, codegen_1._)`${it.evaluated}.items`, (0, codegen_1._)`undefined`)); - } - function funcSourceUrl(schema2, opts) { - const schId = typeof schema2 == "object" && schema2[opts.schemaId]; - return schId && (opts.code.source || opts.code.process) ? (0, codegen_1._)`/*# sourceURL=${schId} */` : codegen_1.nil; - } - function subschemaCode(it, valid) { - if (isSchemaObj(it)) { - checkKeywords(it); - if (schemaCxtHasRules(it)) { - subSchemaObjCode(it, valid); - return; - } - } - (0, boolSchema_1.boolOrEmptySchema)(it, valid); - } - function schemaCxtHasRules({ schema: schema2, self: self2 }) { - if (typeof schema2 == "boolean") - return !schema2; - for (const key in schema2) - if (self2.RULES.all[key]) - return true; - return false; - } - function isSchemaObj(it) { - return typeof it.schema != "boolean"; - } - function subSchemaObjCode(it, valid) { - const { schema: schema2, gen, opts } = it; - if (opts.$comment && schema2.$comment) - commentKeyword(it); - updateContext(it); - checkAsyncSchema(it); - const errsCount = gen.const("_errs", names_1.default.errors); - typeAndKeywords(it, errsCount); - gen.var(valid, (0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); - } - function checkKeywords(it) { - (0, util_1.checkUnknownRules)(it); - checkRefsAndKeywords(it); - } - function typeAndKeywords(it, errsCount) { - if (it.opts.jtd) - return schemaKeywords(it, [], false, errsCount); - const types2 = (0, dataType_1.getSchemaTypes)(it.schema); - const checkedTypes = (0, dataType_1.coerceAndCheckDataType)(it, types2); - schemaKeywords(it, types2, !checkedTypes, errsCount); - } - function checkRefsAndKeywords(it) { - const { schema: schema2, errSchemaPath, opts, self: self2 } = it; - if (schema2.$ref && opts.ignoreKeywordsWithRef && (0, util_1.schemaHasRulesButRef)(schema2, self2.RULES)) { - self2.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`); - } - } - function checkNoDefault(it) { - const { schema: schema2, opts } = it; - if (schema2.default !== void 0 && opts.useDefaults && opts.strictSchema) { - (0, util_1.checkStrictMode)(it, "default is ignored in the schema root"); - } - } - function updateContext(it) { - const schId = it.schema[it.opts.schemaId]; - if (schId) - it.baseId = (0, resolve_1.resolveUrl)(it.opts.uriResolver, it.baseId, schId); - } - function checkAsyncSchema(it) { - if (it.schema.$async && !it.schemaEnv.$async) - throw new Error("async schema in sync schema"); - } - function commentKeyword({ gen, schemaEnv, schema: schema2, errSchemaPath, opts }) { - const msg = schema2.$comment; - if (opts.$comment === true) { - gen.code((0, codegen_1._)`${names_1.default.self}.logger.log(${msg})`); - } else if (typeof opts.$comment == "function") { - const schemaPath = (0, codegen_1.str)`${errSchemaPath}/$comment`; - const rootName = gen.scopeValue("root", { ref: schemaEnv.root }); - gen.code((0, codegen_1._)`${names_1.default.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`); - } - } - function returnResults(it) { - const { gen, schemaEnv, validateName, ValidationError: ValidationError3, opts } = it; - if (schemaEnv.$async) { - gen.if((0, codegen_1._)`${names_1.default.errors} === 0`, () => gen.return(names_1.default.data), () => gen.throw((0, codegen_1._)`new ${ValidationError3}(${names_1.default.vErrors})`)); - } else { - gen.assign((0, codegen_1._)`${validateName}.errors`, names_1.default.vErrors); - if (opts.unevaluated) - assignEvaluated(it); - gen.return((0, codegen_1._)`${names_1.default.errors} === 0`); - } - } - function assignEvaluated({ gen, evaluated, props, items }) { - if (props instanceof codegen_1.Name) - gen.assign((0, codegen_1._)`${evaluated}.props`, props); - if (items instanceof codegen_1.Name) - gen.assign((0, codegen_1._)`${evaluated}.items`, items); - } - function schemaKeywords(it, types2, typeErrors, errsCount) { - const { gen, schema: schema2, data: data2, allErrors, opts, self: self2 } = it; - const { RULES } = self2; - if (schema2.$ref && (opts.ignoreKeywordsWithRef || !(0, util_1.schemaHasRulesButRef)(schema2, RULES))) { - gen.block(() => keywordCode(it, "$ref", RULES.all.$ref.definition)); - return; - } - if (!opts.jtd) - checkStrictTypes(it, types2); - gen.block(() => { - for (const group of RULES.rules) - groupKeywords(group); - groupKeywords(RULES.post); - }); - function groupKeywords(group) { - if (!(0, applicability_1.shouldUseGroup)(schema2, group)) - return; - if (group.type) { - gen.if((0, dataType_2.checkDataType)(group.type, data2, opts.strictNumbers)); - iterateKeywords(it, group); - if (types2.length === 1 && types2[0] === group.type && typeErrors) { - gen.else(); - (0, dataType_2.reportTypeError)(it); - } - gen.endIf(); - } else { - iterateKeywords(it, group); - } - if (!allErrors) - gen.if((0, codegen_1._)`${names_1.default.errors} === ${errsCount || 0}`); - } - } - function iterateKeywords(it, group) { - const { gen, schema: schema2, opts: { useDefaults } } = it; - if (useDefaults) - (0, defaults_1.assignDefaults)(it, group.type); - gen.block(() => { - for (const rule of group.rules) { - if ((0, applicability_1.shouldUseRule)(schema2, rule)) { - keywordCode(it, rule.keyword, rule.definition, group.type); - } - } - }); - } - function checkStrictTypes(it, types2) { - if (it.schemaEnv.meta || !it.opts.strictTypes) - return; - checkContextTypes(it, types2); - if (!it.opts.allowUnionTypes) - checkMultipleTypes(it, types2); - checkKeywordTypes(it, it.dataTypes); - } - function checkContextTypes(it, types2) { - if (!types2.length) - return; - if (!it.dataTypes.length) { - it.dataTypes = types2; - return; - } - types2.forEach((t5) => { - if (!includesType(it.dataTypes, t5)) { - strictTypesError(it, `type "${t5}" not allowed by context "${it.dataTypes.join(",")}"`); - } - }); - narrowSchemaTypes(it, types2); - } - function checkMultipleTypes(it, ts) { - if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) { - strictTypesError(it, "use allowUnionTypes to allow union type keyword"); - } - } - function checkKeywordTypes(it, ts) { - const rules = it.self.RULES.all; - for (const keyword in rules) { - const rule = rules[keyword]; - if (typeof rule == "object" && (0, applicability_1.shouldUseRule)(it.schema, rule)) { - const { type } = rule.definition; - if (type.length && !type.some((t5) => hasApplicableType(ts, t5))) { - strictTypesError(it, `missing type "${type.join(",")}" for keyword "${keyword}"`); - } - } - } - } - function hasApplicableType(schTs, kwdT) { - return schTs.includes(kwdT) || kwdT === "number" && schTs.includes("integer"); - } - function includesType(ts, t5) { - return ts.includes(t5) || t5 === "integer" && ts.includes("number"); - } - function narrowSchemaTypes(it, withTypes) { - const ts = []; - for (const t5 of it.dataTypes) { - if (includesType(withTypes, t5)) - ts.push(t5); - else if (withTypes.includes("integer") && t5 === "number") - ts.push("integer"); - } - it.dataTypes = ts; - } - function strictTypesError(it, msg) { - const schemaPath = it.schemaEnv.baseId + it.errSchemaPath; - msg += ` at "${schemaPath}" (strictTypes)`; - (0, util_1.checkStrictMode)(it, msg, it.opts.strictTypes); - } - var KeywordCxt = class { - constructor(it, def, keyword) { - (0, keyword_1.validateKeywordUsage)(it, def, keyword); - this.gen = it.gen; - this.allErrors = it.allErrors; - this.keyword = keyword; - this.data = it.data; - this.schema = it.schema[keyword]; - this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data; - this.schemaValue = (0, util_1.schemaRefOrVal)(it, this.schema, keyword, this.$data); - this.schemaType = def.schemaType; - this.parentSchema = it.schema; - this.params = {}; - this.it = it; - this.def = def; - if (this.$data) { - this.schemaCode = it.gen.const("vSchema", getData(this.$data, it)); - } else { - this.schemaCode = this.schemaValue; - if (!(0, keyword_1.validSchemaType)(this.schema, def.schemaType, def.allowUndefined)) { - throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`); - } - } - if ("code" in def ? def.trackErrors : def.errors !== false) { - this.errsCount = it.gen.const("_errs", names_1.default.errors); - } - } - result(condition, successAction, failAction) { - this.failResult((0, codegen_1.not)(condition), successAction, failAction); - } - failResult(condition, successAction, failAction) { - this.gen.if(condition); - if (failAction) - failAction(); - else - this.error(); - if (successAction) { - this.gen.else(); - successAction(); - if (this.allErrors) - this.gen.endIf(); - } else { - if (this.allErrors) - this.gen.endIf(); - else - this.gen.else(); - } - } - pass(condition, failAction) { - this.failResult((0, codegen_1.not)(condition), void 0, failAction); - } - fail(condition) { - if (condition === void 0) { - this.error(); - if (!this.allErrors) - this.gen.if(false); - return; - } - this.gen.if(condition); - this.error(); - if (this.allErrors) - this.gen.endIf(); - else - this.gen.else(); - } - fail$data(condition) { - if (!this.$data) - return this.fail(condition); - const { schemaCode } = this; - this.fail((0, codegen_1._)`${schemaCode} !== undefined && (${(0, codegen_1.or)(this.invalid$data(), condition)})`); - } - error(append, errorParams, errorPaths) { - if (errorParams) { - this.setParams(errorParams); - this._error(append, errorPaths); - this.setParams({}); - return; - } - this._error(append, errorPaths); - } - _error(append, errorPaths) { - ; - (append ? errors_1.reportExtraError : errors_1.reportError)(this, this.def.error, errorPaths); - } - $dataError() { - (0, errors_1.reportError)(this, this.def.$dataError || errors_1.keyword$DataError); - } - reset() { - if (this.errsCount === void 0) - throw new Error('add "trackErrors" to keyword definition'); - (0, errors_1.resetErrorsCount)(this.gen, this.errsCount); - } - ok(cond) { - if (!this.allErrors) - this.gen.if(cond); - } - setParams(obj, assign) { - if (assign) - Object.assign(this.params, obj); - else - this.params = obj; - } - block$data(valid, codeBlock, $dataValid = codegen_1.nil) { - this.gen.block(() => { - this.check$data(valid, $dataValid); - codeBlock(); - }); - } - check$data(valid = codegen_1.nil, $dataValid = codegen_1.nil) { - if (!this.$data) - return; - const { gen, schemaCode, schemaType, def } = this; - gen.if((0, codegen_1.or)((0, codegen_1._)`${schemaCode} === undefined`, $dataValid)); - if (valid !== codegen_1.nil) - gen.assign(valid, true); - if (schemaType.length || def.validateSchema) { - gen.elseIf(this.invalid$data()); - this.$dataError(); - if (valid !== codegen_1.nil) - gen.assign(valid, false); - } - gen.else(); - } - invalid$data() { - const { gen, schemaCode, schemaType, def, it } = this; - return (0, codegen_1.or)(wrong$DataType(), invalid$DataSchema()); - function wrong$DataType() { - if (schemaType.length) { - if (!(schemaCode instanceof codegen_1.Name)) - throw new Error("ajv implementation error"); - const st = Array.isArray(schemaType) ? schemaType : [schemaType]; - return (0, codegen_1._)`${(0, dataType_2.checkDataTypes)(st, schemaCode, it.opts.strictNumbers, dataType_2.DataType.Wrong)}`; - } - return codegen_1.nil; - } - function invalid$DataSchema() { - if (def.validateSchema) { - const validateSchemaRef = gen.scopeValue("validate$data", { ref: def.validateSchema }); - return (0, codegen_1._)`!${validateSchemaRef}(${schemaCode})`; - } - return codegen_1.nil; - } - } - subschema(appl, valid) { - const subschema = (0, subschema_1.getSubschema)(this.it, appl); - (0, subschema_1.extendSubschemaData)(subschema, this.it, appl); - (0, subschema_1.extendSubschemaMode)(subschema, appl); - const nextContext = { ...this.it, ...subschema, items: void 0, props: void 0 }; - subschemaCode(nextContext, valid); - return nextContext; - } - mergeEvaluated(schemaCxt, toName) { - const { it, gen } = this; - if (!it.opts.unevaluated) - return; - if (it.props !== true && schemaCxt.props !== void 0) { - it.props = util_1.mergeEvaluated.props(gen, schemaCxt.props, it.props, toName); - } - if (it.items !== true && schemaCxt.items !== void 0) { - it.items = util_1.mergeEvaluated.items(gen, schemaCxt.items, it.items, toName); - } - } - mergeValidEvaluated(schemaCxt, valid) { - const { it, gen } = this; - if (it.opts.unevaluated && (it.props !== true || it.items !== true)) { - gen.if(valid, () => this.mergeEvaluated(schemaCxt, codegen_1.Name)); - return true; - } - } - }; - exports.KeywordCxt = KeywordCxt; - function keywordCode(it, keyword, def, ruleType) { - const cxt = new KeywordCxt(it, def, keyword); - if ("code" in def) { - def.code(cxt, ruleType); - } else if (cxt.$data && def.validate) { - (0, keyword_1.funcKeywordCode)(cxt, def); - } else if ("macro" in def) { - (0, keyword_1.macroKeywordCode)(cxt, def); - } else if (def.compile || def.validate) { - (0, keyword_1.funcKeywordCode)(cxt, def); - } - } - var JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/; - var RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/; - function getData($data, { dataLevel, dataNames, dataPathArr }) { - let jsonPointer; - let data2; - if ($data === "") - return names_1.default.rootData; - if ($data[0] === "/") { - if (!JSON_POINTER.test($data)) - throw new Error(`Invalid JSON-pointer: ${$data}`); - jsonPointer = $data; - data2 = names_1.default.rootData; - } else { - const matches = RELATIVE_JSON_POINTER.exec($data); - if (!matches) - throw new Error(`Invalid JSON-pointer: ${$data}`); - const up = +matches[1]; - jsonPointer = matches[2]; - if (jsonPointer === "#") { - if (up >= dataLevel) - throw new Error(errorMsg("property/index", up)); - return dataPathArr[dataLevel - up]; - } - if (up > dataLevel) - throw new Error(errorMsg("data", up)); - data2 = dataNames[dataLevel - up]; - if (!jsonPointer) - return data2; - } - let expr = data2; - const segments = jsonPointer.split("/"); - for (const segment of segments) { - if (segment) { - data2 = (0, codegen_1._)`${data2}${(0, codegen_1.getProperty)((0, util_1.unescapeJsonPointer)(segment))}`; - expr = (0, codegen_1._)`${expr} && ${data2}`; - } - } - return expr; - function errorMsg(pointerType, up) { - return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`; - } - } - exports.getData = getData; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/validation_error.js -var require_validation_error = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/validation_error.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - var ValidationError3 = class extends Error { - constructor(errors) { - super("validation failed"); - this.errors = errors; - this.ajv = this.validation = true; - } - }; - exports.default = ValidationError3; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/ref_error.js -var require_ref_error = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/ref_error.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - var resolve_1 = require_resolve(); - var MissingRefError = class extends Error { - constructor(resolver, baseId, ref, msg) { - super(msg || `can't resolve reference ${ref} from id ${baseId}`); - this.missingRef = (0, resolve_1.resolveUrl)(resolver, baseId, ref); - this.missingSchema = (0, resolve_1.normalizeId)((0, resolve_1.getFullPath)(resolver, this.missingRef)); - } - }; - exports.default = MissingRefError; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/index.js -var require_compile = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/index.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.resolveSchema = exports.getCompilingSchema = exports.resolveRef = exports.compileSchema = exports.SchemaEnv = void 0; - var codegen_1 = require_codegen(); - var validation_error_1 = require_validation_error(); - var names_1 = require_names(); - var resolve_1 = require_resolve(); - var util_1 = require_util(); - var validate_1 = require_validate(); - var SchemaEnv = class { - constructor(env2) { - var _a6; - this.refs = {}; - this.dynamicAnchors = {}; - let schema2; - if (typeof env2.schema == "object") - schema2 = env2.schema; - this.schema = env2.schema; - this.schemaId = env2.schemaId; - this.root = env2.root || this; - this.baseId = (_a6 = env2.baseId) !== null && _a6 !== void 0 ? _a6 : (0, resolve_1.normalizeId)(schema2 === null || schema2 === void 0 ? void 0 : schema2[env2.schemaId || "$id"]); - this.schemaPath = env2.schemaPath; - this.localRefs = env2.localRefs; - this.meta = env2.meta; - this.$async = schema2 === null || schema2 === void 0 ? void 0 : schema2.$async; - this.refs = {}; - } - }; - exports.SchemaEnv = SchemaEnv; - function compileSchema(sch) { - const _sch = getCompilingSchema.call(this, sch); - if (_sch) - return _sch; - const rootId = (0, resolve_1.getFullPath)(this.opts.uriResolver, sch.root.baseId); - const { es5, lines } = this.opts.code; - const { ownProperties } = this.opts; - const gen = new codegen_1.CodeGen(this.scope, { es5, lines, ownProperties }); - let _ValidationError2; - if (sch.$async) { - _ValidationError2 = gen.scopeValue("Error", { - ref: validation_error_1.default, - code: (0, codegen_1._)`require("ajv/dist/runtime/validation_error").default` - }); - } - const validateName = gen.scopeName("validate"); - sch.validateName = validateName; - const schemaCxt = { - gen, - allErrors: this.opts.allErrors, - data: names_1.default.data, - parentData: names_1.default.parentData, - parentDataProperty: names_1.default.parentDataProperty, - dataNames: [names_1.default.data], - dataPathArr: [codegen_1.nil], - // TODO can its length be used as dataLevel if nil is removed? - dataLevel: 0, - dataTypes: [], - definedProperties: /* @__PURE__ */ new Set(), - topSchemaRef: gen.scopeValue("schema", this.opts.code.source === true ? { ref: sch.schema, code: (0, codegen_1.stringify)(sch.schema) } : { ref: sch.schema }), - validateName, - ValidationError: _ValidationError2, - schema: sch.schema, - schemaEnv: sch, - rootId, - baseId: sch.baseId || rootId, - schemaPath: codegen_1.nil, - errSchemaPath: sch.schemaPath || (this.opts.jtd ? "" : "#"), - errorPath: (0, codegen_1._)`""`, - opts: this.opts, - self: this - }; - let sourceCode; - try { - this._compilations.add(sch); - (0, validate_1.validateFunctionCode)(schemaCxt); - gen.optimize(this.opts.code.optimize); - const validateCode = gen.toString(); - sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${validateCode}`; - if (this.opts.code.process) - sourceCode = this.opts.code.process(sourceCode, sch); - const makeValidate = new Function(`${names_1.default.self}`, `${names_1.default.scope}`, sourceCode); - const validate2 = makeValidate(this, this.scope.get()); - this.scope.value(validateName, { ref: validate2 }); - validate2.errors = null; - validate2.schema = sch.schema; - validate2.schemaEnv = sch; - if (sch.$async) - validate2.$async = true; - if (this.opts.code.source === true) { - validate2.source = { validateName, validateCode, scopeValues: gen._values }; - } - if (this.opts.unevaluated) { - const { props, items } = schemaCxt; - validate2.evaluated = { - props: props instanceof codegen_1.Name ? void 0 : props, - items: items instanceof codegen_1.Name ? void 0 : items, - dynamicProps: props instanceof codegen_1.Name, - dynamicItems: items instanceof codegen_1.Name - }; - if (validate2.source) - validate2.source.evaluated = (0, codegen_1.stringify)(validate2.evaluated); - } - sch.validate = validate2; - return sch; - } catch (e5) { - delete sch.validate; - delete sch.validateName; - if (sourceCode) - this.logger.error("Error compiling schema, function code:", sourceCode); - throw e5; - } finally { - this._compilations.delete(sch); - } - } - exports.compileSchema = compileSchema; - function resolveRef2(root, baseId, ref) { - var _a6; - ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, ref); - const schOrFunc = root.refs[ref]; - if (schOrFunc) - return schOrFunc; - let _sch = resolve4.call(this, root, ref); - if (_sch === void 0) { - const schema2 = (_a6 = root.localRefs) === null || _a6 === void 0 ? void 0 : _a6[ref]; - const { schemaId } = this.opts; - if (schema2) - _sch = new SchemaEnv({ schema: schema2, schemaId, root, baseId }); - } - if (_sch === void 0) - return; - return root.refs[ref] = inlineOrCompile.call(this, _sch); - } - exports.resolveRef = resolveRef2; - function inlineOrCompile(sch) { - if ((0, resolve_1.inlineRef)(sch.schema, this.opts.inlineRefs)) - return sch.schema; - return sch.validate ? sch : compileSchema.call(this, sch); - } - function getCompilingSchema(schEnv) { - for (const sch of this._compilations) { - if (sameSchemaEnv(sch, schEnv)) - return sch; - } - } - exports.getCompilingSchema = getCompilingSchema; - function sameSchemaEnv(s1, s22) { - return s1.schema === s22.schema && s1.root === s22.root && s1.baseId === s22.baseId; - } - function resolve4(root, ref) { - let sch; - while (typeof (sch = this.refs[ref]) == "string") - ref = sch; - return sch || this.schemas[ref] || resolveSchema.call(this, root, ref); - } - function resolveSchema(root, ref) { - const p5 = this.opts.uriResolver.parse(ref); - const refPath = (0, resolve_1._getFullPath)(this.opts.uriResolver, p5); - let baseId = (0, resolve_1.getFullPath)(this.opts.uriResolver, root.baseId, void 0); - if (Object.keys(root.schema).length > 0 && refPath === baseId) { - return getJsonPointer.call(this, p5, root); - } - const id = (0, resolve_1.normalizeId)(refPath); - const schOrRef = this.refs[id] || this.schemas[id]; - if (typeof schOrRef == "string") { - const sch = resolveSchema.call(this, root, schOrRef); - if (typeof (sch === null || sch === void 0 ? void 0 : sch.schema) !== "object") - return; - return getJsonPointer.call(this, p5, sch); - } - if (typeof (schOrRef === null || schOrRef === void 0 ? void 0 : schOrRef.schema) !== "object") - return; - if (!schOrRef.validate) - compileSchema.call(this, schOrRef); - if (id === (0, resolve_1.normalizeId)(ref)) { - const { schema: schema2 } = schOrRef; - const { schemaId } = this.opts; - const schId = schema2[schemaId]; - if (schId) - baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); - return new SchemaEnv({ schema: schema2, schemaId, root, baseId }); - } - return getJsonPointer.call(this, p5, schOrRef); - } - exports.resolveSchema = resolveSchema; - var PREVENT_SCOPE_CHANGE = /* @__PURE__ */ new Set([ - "properties", - "patternProperties", - "enum", - "dependencies", - "definitions" - ]); - function getJsonPointer(parsedRef, { baseId, schema: schema2, root }) { - var _a6; - if (((_a6 = parsedRef.fragment) === null || _a6 === void 0 ? void 0 : _a6[0]) !== "/") - return; - for (const part of parsedRef.fragment.slice(1).split("/")) { - if (typeof schema2 === "boolean") - return; - const partSchema = schema2[(0, util_1.unescapeFragment)(part)]; - if (partSchema === void 0) - return; - schema2 = partSchema; - const schId = typeof schema2 === "object" && schema2[this.opts.schemaId]; - if (!PREVENT_SCOPE_CHANGE.has(part) && schId) { - baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); - } - } - let env2; - if (typeof schema2 != "boolean" && schema2.$ref && !(0, util_1.schemaHasRulesButRef)(schema2, this.RULES)) { - const $ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schema2.$ref); - env2 = resolveSchema.call(this, root, $ref); - } - const { schemaId } = this.opts; - env2 = env2 || new SchemaEnv({ schema: schema2, schemaId, root, baseId }); - if (env2.schema !== env2.root.schema) - return env2; - return void 0; - } - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/data.json -var require_data = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/data.json"(exports, module) { - module.exports = { - $id: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#", - description: "Meta-schema for $data reference (JSON AnySchema extension proposal)", - type: "object", - required: ["$data"], - properties: { - $data: { - type: "string", - anyOf: [{ format: "relative-json-pointer" }, { format: "json-pointer" }] - } - }, - additionalProperties: false - }; - } -}); - -// node_modules/.pnpm/fast-uri@3.1.0/node_modules/fast-uri/lib/utils.js -var require_utils5 = __commonJS({ - "node_modules/.pnpm/fast-uri@3.1.0/node_modules/fast-uri/lib/utils.js"(exports, module) { - "use strict"; - var isUUID = RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu); - var isIPv4 = RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u); - function stringArrayToHexStripped(input) { - let acc = ""; - let code = 0; - let i5 = 0; - for (i5 = 0; i5 < input.length; i5++) { - code = input[i5].charCodeAt(0); - if (code === 48) { - continue; - } - if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) { - return ""; - } - acc += input[i5]; - break; - } - for (i5 += 1; i5 < input.length; i5++) { - code = input[i5].charCodeAt(0); - if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) { - return ""; - } - acc += input[i5]; - } - return acc; - } - var nonSimpleDomain = RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u); - function consumeIsZone(buffer2) { - buffer2.length = 0; - return true; - } - function consumeHextets(buffer2, address, output) { - if (buffer2.length) { - const hex4 = stringArrayToHexStripped(buffer2); - if (hex4 !== "") { - address.push(hex4); - } else { - output.error = true; - return false; - } - buffer2.length = 0; - } - return true; - } - function getIPV6(input) { - let tokenCount = 0; - const output = { error: false, address: "", zone: "" }; - const address = []; - const buffer2 = []; - let endipv6Encountered = false; - let endIpv6 = false; - let consume = consumeHextets; - for (let i5 = 0; i5 < input.length; i5++) { - const cursor2 = input[i5]; - if (cursor2 === "[" || cursor2 === "]") { - continue; - } - if (cursor2 === ":") { - if (endipv6Encountered === true) { - endIpv6 = true; - } - if (!consume(buffer2, address, output)) { - break; - } - if (++tokenCount > 7) { - output.error = true; - break; - } - if (i5 > 0 && input[i5 - 1] === ":") { - endipv6Encountered = true; - } - address.push(":"); - continue; - } else if (cursor2 === "%") { - if (!consume(buffer2, address, output)) { - break; - } - consume = consumeIsZone; - } else { - buffer2.push(cursor2); - continue; - } - } - if (buffer2.length) { - if (consume === consumeIsZone) { - output.zone = buffer2.join(""); - } else if (endIpv6) { - address.push(buffer2.join("")); - } else { - address.push(stringArrayToHexStripped(buffer2)); - } - } - output.address = address.join(""); - return output; - } - function normalizeIPv62(host) { - if (findToken(host, ":") < 2) { - return { host, isIPV6: false }; - } - const ipv63 = getIPV6(host); - if (!ipv63.error) { - let newHost = ipv63.address; - let escapedHost = ipv63.address; - if (ipv63.zone) { - newHost += "%" + ipv63.zone; - escapedHost += "%25" + ipv63.zone; - } - return { host: newHost, isIPV6: true, escapedHost }; - } else { - return { host, isIPV6: false }; - } - } - function findToken(str, token) { - let ind = 0; - for (let i5 = 0; i5 < str.length; i5++) { - if (str[i5] === token) ind++; - } - return ind; - } - function removeDotSegments(path53) { - let input = path53; - const output = []; - let nextSlash = -1; - let len = 0; - while (len = input.length) { - if (len === 1) { - if (input === ".") { - break; - } else if (input === "/") { - output.push("/"); - break; - } else { - output.push(input); - break; - } - } else if (len === 2) { - if (input[0] === ".") { - if (input[1] === ".") { - break; - } else if (input[1] === "/") { - input = input.slice(2); - continue; - } - } else if (input[0] === "/") { - if (input[1] === "." || input[1] === "/") { - output.push("/"); - break; - } - } - } else if (len === 3) { - if (input === "/..") { - if (output.length !== 0) { - output.pop(); - } - output.push("/"); - break; - } - } - if (input[0] === ".") { - if (input[1] === ".") { - if (input[2] === "/") { - input = input.slice(3); - continue; - } - } else if (input[1] === "/") { - input = input.slice(2); - continue; - } - } else if (input[0] === "/") { - if (input[1] === ".") { - if (input[2] === "/") { - input = input.slice(2); - continue; - } else if (input[2] === ".") { - if (input[3] === "/") { - input = input.slice(3); - if (output.length !== 0) { - output.pop(); - } - continue; - } - } - } - } - if ((nextSlash = input.indexOf("/", 1)) === -1) { - output.push(input); - break; - } else { - output.push(input.slice(0, nextSlash)); - input = input.slice(nextSlash); - } - } - return output.join(""); - } - function normalizeComponentEncoding(component, esc2) { - const func = esc2 !== true ? escape : unescape; - if (component.scheme !== void 0) { - component.scheme = func(component.scheme); - } - if (component.userinfo !== void 0) { - component.userinfo = func(component.userinfo); - } - if (component.host !== void 0) { - component.host = func(component.host); - } - if (component.path !== void 0) { - component.path = func(component.path); - } - if (component.query !== void 0) { - component.query = func(component.query); - } - if (component.fragment !== void 0) { - component.fragment = func(component.fragment); - } - return component; - } - function recomposeAuthority(component) { - const uriTokens = []; - if (component.userinfo !== void 0) { - uriTokens.push(component.userinfo); - uriTokens.push("@"); - } - if (component.host !== void 0) { - let host = unescape(component.host); - if (!isIPv4(host)) { - const ipV6res = normalizeIPv62(host); - if (ipV6res.isIPV6 === true) { - host = `[${ipV6res.escapedHost}]`; - } else { - host = component.host; - } - } - uriTokens.push(host); - } - if (typeof component.port === "number" || typeof component.port === "string") { - uriTokens.push(":"); - uriTokens.push(String(component.port)); - } - return uriTokens.length ? uriTokens.join("") : void 0; - } - module.exports = { - nonSimpleDomain, - recomposeAuthority, - normalizeComponentEncoding, - removeDotSegments, - isIPv4, - isUUID, - normalizeIPv6: normalizeIPv62, - stringArrayToHexStripped - }; - } -}); - -// node_modules/.pnpm/fast-uri@3.1.0/node_modules/fast-uri/lib/schemes.js -var require_schemes = __commonJS({ - "node_modules/.pnpm/fast-uri@3.1.0/node_modules/fast-uri/lib/schemes.js"(exports, module) { - "use strict"; - var { isUUID } = require_utils5(); - var URN_REG = /([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu; - var supportedSchemeNames = ( - /** @type {const} */ - [ - "http", - "https", - "ws", - "wss", - "urn", - "urn:uuid" - ] - ); - function isValidSchemeName(name) { - return supportedSchemeNames.indexOf( - /** @type {*} */ - name - ) !== -1; - } - function wsIsSecure(wsComponent) { - if (wsComponent.secure === true) { - return true; - } else if (wsComponent.secure === false) { - return false; - } else if (wsComponent.scheme) { - return wsComponent.scheme.length === 3 && (wsComponent.scheme[0] === "w" || wsComponent.scheme[0] === "W") && (wsComponent.scheme[1] === "s" || wsComponent.scheme[1] === "S") && (wsComponent.scheme[2] === "s" || wsComponent.scheme[2] === "S"); - } else { - return false; - } - } - function httpParse(component) { - if (!component.host) { - component.error = component.error || "HTTP URIs must have a host."; - } - return component; - } - function httpSerialize(component) { - const secure = String(component.scheme).toLowerCase() === "https"; - if (component.port === (secure ? 443 : 80) || component.port === "") { - component.port = void 0; - } - if (!component.path) { - component.path = "/"; - } - return component; - } - function wsParse(wsComponent) { - wsComponent.secure = wsIsSecure(wsComponent); - wsComponent.resourceName = (wsComponent.path || "/") + (wsComponent.query ? "?" + wsComponent.query : ""); - wsComponent.path = void 0; - wsComponent.query = void 0; - return wsComponent; - } - function wsSerialize(wsComponent) { - if (wsComponent.port === (wsIsSecure(wsComponent) ? 443 : 80) || wsComponent.port === "") { - wsComponent.port = void 0; - } - if (typeof wsComponent.secure === "boolean") { - wsComponent.scheme = wsComponent.secure ? "wss" : "ws"; - wsComponent.secure = void 0; - } - if (wsComponent.resourceName) { - const [path53, query] = wsComponent.resourceName.split("?"); - wsComponent.path = path53 && path53 !== "/" ? path53 : void 0; - wsComponent.query = query; - wsComponent.resourceName = void 0; - } - wsComponent.fragment = void 0; - return wsComponent; - } - function urnParse(urnComponent, options) { - if (!urnComponent.path) { - urnComponent.error = "URN can not be parsed"; - return urnComponent; - } - const matches = urnComponent.path.match(URN_REG); - if (matches) { - const scheme = options.scheme || urnComponent.scheme || "urn"; - urnComponent.nid = matches[1].toLowerCase(); - urnComponent.nss = matches[2]; - const urnScheme = `${scheme}:${options.nid || urnComponent.nid}`; - const schemeHandler = getSchemeHandler(urnScheme); - urnComponent.path = void 0; - if (schemeHandler) { - urnComponent = schemeHandler.parse(urnComponent, options); - } - } else { - urnComponent.error = urnComponent.error || "URN can not be parsed."; - } - return urnComponent; - } - function urnSerialize(urnComponent, options) { - if (urnComponent.nid === void 0) { - throw new Error("URN without nid cannot be serialized"); - } - const scheme = options.scheme || urnComponent.scheme || "urn"; - const nid = urnComponent.nid.toLowerCase(); - const urnScheme = `${scheme}:${options.nid || nid}`; - const schemeHandler = getSchemeHandler(urnScheme); - if (schemeHandler) { - urnComponent = schemeHandler.serialize(urnComponent, options); - } - const uriComponent = urnComponent; - const nss = urnComponent.nss; - uriComponent.path = `${nid || options.nid}:${nss}`; - options.skipEscape = true; - return uriComponent; - } - function urnuuidParse(urnComponent, options) { - const uuidComponent = urnComponent; - uuidComponent.uuid = uuidComponent.nss; - uuidComponent.nss = void 0; - if (!options.tolerant && (!uuidComponent.uuid || !isUUID(uuidComponent.uuid))) { - uuidComponent.error = uuidComponent.error || "UUID is not valid."; - } - return uuidComponent; - } - function urnuuidSerialize(uuidComponent) { - const urnComponent = uuidComponent; - urnComponent.nss = (uuidComponent.uuid || "").toLowerCase(); - return urnComponent; - } - var http = ( - /** @type {SchemeHandler} */ - { - scheme: "http", - domainHost: true, - parse: httpParse, - serialize: httpSerialize - } - ); - var https = ( - /** @type {SchemeHandler} */ - { - scheme: "https", - domainHost: http.domainHost, - parse: httpParse, - serialize: httpSerialize - } - ); - var ws = ( - /** @type {SchemeHandler} */ - { - scheme: "ws", - domainHost: true, - parse: wsParse, - serialize: wsSerialize - } - ); - var wss = ( - /** @type {SchemeHandler} */ - { - scheme: "wss", - domainHost: ws.domainHost, - parse: ws.parse, - serialize: ws.serialize - } - ); - var urn = ( - /** @type {SchemeHandler} */ - { - scheme: "urn", - parse: urnParse, - serialize: urnSerialize, - skipNormalize: true - } - ); - var urnuuid = ( - /** @type {SchemeHandler} */ - { - scheme: "urn:uuid", - parse: urnuuidParse, - serialize: urnuuidSerialize, - skipNormalize: true - } - ); - var SCHEMES = ( - /** @type {Record} */ - { - http, - https, - ws, - wss, - urn, - "urn:uuid": urnuuid - } - ); - Object.setPrototypeOf(SCHEMES, null); - function getSchemeHandler(scheme) { - return scheme && (SCHEMES[ - /** @type {SchemeName} */ - scheme - ] || SCHEMES[ - /** @type {SchemeName} */ - scheme.toLowerCase() - ]) || void 0; - } - module.exports = { - wsIsSecure, - SCHEMES, - isValidSchemeName, - getSchemeHandler - }; - } -}); - -// node_modules/.pnpm/fast-uri@3.1.0/node_modules/fast-uri/index.js -var require_fast_uri = __commonJS({ - "node_modules/.pnpm/fast-uri@3.1.0/node_modules/fast-uri/index.js"(exports, module) { - "use strict"; - var { normalizeIPv6: normalizeIPv62, removeDotSegments, recomposeAuthority, normalizeComponentEncoding, isIPv4, nonSimpleDomain } = require_utils5(); - var { SCHEMES, getSchemeHandler } = require_schemes(); - function normalize2(uri, options) { - if (typeof uri === "string") { - uri = /** @type {T} */ - serialize(parse5(uri, options), options); - } else if (typeof uri === "object") { - uri = /** @type {T} */ - parse5(serialize(uri, options), options); - } - return uri; - } - function resolve4(baseURI, relativeURI, options) { - const schemelessOptions = options ? Object.assign({ scheme: "null" }, options) : { scheme: "null" }; - const resolved = resolveComponent(parse5(baseURI, schemelessOptions), parse5(relativeURI, schemelessOptions), schemelessOptions, true); - schemelessOptions.skipEscape = true; - return serialize(resolved, schemelessOptions); - } - function resolveComponent(base, relative3, options, skipNormalization) { - const target = {}; - if (!skipNormalization) { - base = parse5(serialize(base, options), options); - relative3 = parse5(serialize(relative3, options), options); - } - options = options || {}; - if (!options.tolerant && relative3.scheme) { - target.scheme = relative3.scheme; - target.userinfo = relative3.userinfo; - target.host = relative3.host; - target.port = relative3.port; - target.path = removeDotSegments(relative3.path || ""); - target.query = relative3.query; - } else { - if (relative3.userinfo !== void 0 || relative3.host !== void 0 || relative3.port !== void 0) { - target.userinfo = relative3.userinfo; - target.host = relative3.host; - target.port = relative3.port; - target.path = removeDotSegments(relative3.path || ""); - target.query = relative3.query; - } else { - if (!relative3.path) { - target.path = base.path; - if (relative3.query !== void 0) { - target.query = relative3.query; - } else { - target.query = base.query; - } - } else { - if (relative3.path[0] === "/") { - target.path = removeDotSegments(relative3.path); - } else { - if ((base.userinfo !== void 0 || base.host !== void 0 || base.port !== void 0) && !base.path) { - target.path = "/" + relative3.path; - } else if (!base.path) { - target.path = relative3.path; - } else { - target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative3.path; - } - target.path = removeDotSegments(target.path); - } - target.query = relative3.query; - } - target.userinfo = base.userinfo; - target.host = base.host; - target.port = base.port; - } - target.scheme = base.scheme; - } - target.fragment = relative3.fragment; - return target; - } - function equal(uriA, uriB, options) { - if (typeof uriA === "string") { - uriA = unescape(uriA); - uriA = serialize(normalizeComponentEncoding(parse5(uriA, options), true), { ...options, skipEscape: true }); - } else if (typeof uriA === "object") { - uriA = serialize(normalizeComponentEncoding(uriA, true), { ...options, skipEscape: true }); - } - if (typeof uriB === "string") { - uriB = unescape(uriB); - uriB = serialize(normalizeComponentEncoding(parse5(uriB, options), true), { ...options, skipEscape: true }); - } else if (typeof uriB === "object") { - uriB = serialize(normalizeComponentEncoding(uriB, true), { ...options, skipEscape: true }); - } - return uriA.toLowerCase() === uriB.toLowerCase(); - } - function serialize(cmpts, opts) { - const component = { - host: cmpts.host, - scheme: cmpts.scheme, - userinfo: cmpts.userinfo, - port: cmpts.port, - path: cmpts.path, - query: cmpts.query, - nid: cmpts.nid, - nss: cmpts.nss, - uuid: cmpts.uuid, - fragment: cmpts.fragment, - reference: cmpts.reference, - resourceName: cmpts.resourceName, - secure: cmpts.secure, - error: "" - }; - const options = Object.assign({}, opts); - const uriTokens = []; - const schemeHandler = getSchemeHandler(options.scheme || component.scheme); - if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(component, options); - if (component.path !== void 0) { - if (!options.skipEscape) { - component.path = escape(component.path); - if (component.scheme !== void 0) { - component.path = component.path.split("%3A").join(":"); - } - } else { - component.path = unescape(component.path); - } - } - if (options.reference !== "suffix" && component.scheme) { - uriTokens.push(component.scheme, ":"); - } - const authority = recomposeAuthority(component); - if (authority !== void 0) { - if (options.reference !== "suffix") { - uriTokens.push("//"); - } - uriTokens.push(authority); - if (component.path && component.path[0] !== "/") { - uriTokens.push("/"); - } - } - if (component.path !== void 0) { - let s5 = component.path; - if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) { - s5 = removeDotSegments(s5); - } - if (authority === void 0 && s5[0] === "/" && s5[1] === "/") { - s5 = "/%2F" + s5.slice(2); - } - uriTokens.push(s5); - } - if (component.query !== void 0) { - uriTokens.push("?", component.query); - } - if (component.fragment !== void 0) { - uriTokens.push("#", component.fragment); - } - return uriTokens.join(""); - } - var URI_PARSE = /^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u; - function parse5(uri, opts) { - const options = Object.assign({}, opts); - const parsed = { - scheme: void 0, - userinfo: void 0, - host: "", - port: void 0, - path: "", - query: void 0, - fragment: void 0 - }; - let isIP2 = false; - if (options.reference === "suffix") { - if (options.scheme) { - uri = options.scheme + ":" + uri; - } else { - uri = "//" + uri; - } - } - const matches = uri.match(URI_PARSE); - if (matches) { - parsed.scheme = matches[1]; - parsed.userinfo = matches[3]; - parsed.host = matches[4]; - parsed.port = parseInt(matches[5], 10); - parsed.path = matches[6] || ""; - parsed.query = matches[7]; - parsed.fragment = matches[8]; - if (isNaN(parsed.port)) { - parsed.port = matches[5]; - } - if (parsed.host) { - const ipv4result = isIPv4(parsed.host); - if (ipv4result === false) { - const ipv6result = normalizeIPv62(parsed.host); - parsed.host = ipv6result.host.toLowerCase(); - isIP2 = ipv6result.isIPV6; - } else { - isIP2 = true; - } - } - if (parsed.scheme === void 0 && parsed.userinfo === void 0 && parsed.host === void 0 && parsed.port === void 0 && parsed.query === void 0 && !parsed.path) { - parsed.reference = "same-document"; - } else if (parsed.scheme === void 0) { - parsed.reference = "relative"; - } else if (parsed.fragment === void 0) { - parsed.reference = "absolute"; - } else { - parsed.reference = "uri"; - } - if (options.reference && options.reference !== "suffix" && options.reference !== parsed.reference) { - parsed.error = parsed.error || "URI is not a " + options.reference + " reference."; - } - const schemeHandler = getSchemeHandler(options.scheme || parsed.scheme); - if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) { - if (parsed.host && (options.domainHost || schemeHandler && schemeHandler.domainHost) && isIP2 === false && nonSimpleDomain(parsed.host)) { - try { - parsed.host = URL.domainToASCII(parsed.host.toLowerCase()); - } catch (e5) { - parsed.error = parsed.error || "Host's domain name can not be converted to ASCII: " + e5; - } - } - } - if (!schemeHandler || schemeHandler && !schemeHandler.skipNormalize) { - if (uri.indexOf("%") !== -1) { - if (parsed.scheme !== void 0) { - parsed.scheme = unescape(parsed.scheme); - } - if (parsed.host !== void 0) { - parsed.host = unescape(parsed.host); - } - } - if (parsed.path) { - parsed.path = escape(unescape(parsed.path)); - } - if (parsed.fragment) { - parsed.fragment = encodeURI(decodeURIComponent(parsed.fragment)); - } - } - if (schemeHandler && schemeHandler.parse) { - schemeHandler.parse(parsed, options); - } - } else { - parsed.error = parsed.error || "URI can not be parsed."; - } - return parsed; - } - var fastUri = { - SCHEMES, - normalize: normalize2, - resolve: resolve4, - resolveComponent, - equal, - serialize, - parse: parse5 - }; - module.exports = fastUri; - module.exports.default = fastUri; - module.exports.fastUri = fastUri; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/uri.js -var require_uri2 = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/uri.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - var uri = require_fast_uri(); - uri.code = 'require("ajv/dist/runtime/uri").default'; - exports.default = uri; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/core.js -var require_core = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/core.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = void 0; - var validate_1 = require_validate(); - Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function() { - return validate_1.KeywordCxt; - } }); - var codegen_1 = require_codegen(); - Object.defineProperty(exports, "_", { enumerable: true, get: function() { - return codegen_1._; - } }); - Object.defineProperty(exports, "str", { enumerable: true, get: function() { - return codegen_1.str; - } }); - Object.defineProperty(exports, "stringify", { enumerable: true, get: function() { - return codegen_1.stringify; - } }); - Object.defineProperty(exports, "nil", { enumerable: true, get: function() { - return codegen_1.nil; - } }); - Object.defineProperty(exports, "Name", { enumerable: true, get: function() { - return codegen_1.Name; - } }); - Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function() { - return codegen_1.CodeGen; - } }); - var validation_error_1 = require_validation_error(); - var ref_error_1 = require_ref_error(); - var rules_1 = require_rules(); - var compile_1 = require_compile(); - var codegen_2 = require_codegen(); - var resolve_1 = require_resolve(); - var dataType_1 = require_dataType(); - var util_1 = require_util(); - var $dataRefSchema = require_data(); - var uri_1 = require_uri2(); - var defaultRegExp = (str, flags) => new RegExp(str, flags); - defaultRegExp.code = "new RegExp"; - var META_IGNORE_OPTIONS = ["removeAdditional", "useDefaults", "coerceTypes"]; - var EXT_SCOPE_NAMES = /* @__PURE__ */ new Set([ - "validate", - "serialize", - "parse", - "wrapper", - "root", - "schema", - "keyword", - "pattern", - "formats", - "validate$data", - "func", - "obj", - "Error" - ]); - var removedOptions = { - errorDataPath: "", - format: "`validateFormats: false` can be used instead.", - nullable: '"nullable" keyword is supported by default.', - jsonPointers: "Deprecated jsPropertySyntax can be used instead.", - extendRefs: "Deprecated ignoreKeywordsWithRef can be used instead.", - missingRefs: "Pass empty schema with $id that should be ignored to ajv.addSchema.", - processCode: "Use option `code: {process: (code, schemaEnv: object) => string}`", - sourceCode: "Use option `code: {source: true}`", - strictDefaults: "It is default now, see option `strict`.", - strictKeywords: "It is default now, see option `strict`.", - uniqueItems: '"uniqueItems" keyword is always validated.', - unknownFormats: "Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).", - cache: "Map is used as cache, schema object as key.", - serialize: "Map is used as cache, schema object as key.", - ajvErrors: "It is default now." - }; - var deprecatedOptions = { - ignoreKeywordsWithRef: "", - jsPropertySyntax: "", - unicode: '"minLength"/"maxLength" account for unicode characters by default.' - }; - var MAX_EXPRESSION = 200; - function requiredOptions(o5) { - var _a6, _b, _c5, _d, _e5, _f, _g, _h4, _j, _k, _l, _m4, _o, _p, _q, _r2, _s5, _t, _u, _v, _w, _x, _y, _z, _0; - const s5 = o5.strict; - const _optz = (_a6 = o5.code) === null || _a6 === void 0 ? void 0 : _a6.optimize; - const optimize = _optz === true || _optz === void 0 ? 1 : _optz || 0; - const regExp = (_c5 = (_b = o5.code) === null || _b === void 0 ? void 0 : _b.regExp) !== null && _c5 !== void 0 ? _c5 : defaultRegExp; - const uriResolver = (_d = o5.uriResolver) !== null && _d !== void 0 ? _d : uri_1.default; - return { - strictSchema: (_f = (_e5 = o5.strictSchema) !== null && _e5 !== void 0 ? _e5 : s5) !== null && _f !== void 0 ? _f : true, - strictNumbers: (_h4 = (_g = o5.strictNumbers) !== null && _g !== void 0 ? _g : s5) !== null && _h4 !== void 0 ? _h4 : true, - strictTypes: (_k = (_j = o5.strictTypes) !== null && _j !== void 0 ? _j : s5) !== null && _k !== void 0 ? _k : "log", - strictTuples: (_m4 = (_l = o5.strictTuples) !== null && _l !== void 0 ? _l : s5) !== null && _m4 !== void 0 ? _m4 : "log", - strictRequired: (_p = (_o = o5.strictRequired) !== null && _o !== void 0 ? _o : s5) !== null && _p !== void 0 ? _p : false, - code: o5.code ? { ...o5.code, optimize, regExp } : { optimize, regExp }, - loopRequired: (_q = o5.loopRequired) !== null && _q !== void 0 ? _q : MAX_EXPRESSION, - loopEnum: (_r2 = o5.loopEnum) !== null && _r2 !== void 0 ? _r2 : MAX_EXPRESSION, - meta: (_s5 = o5.meta) !== null && _s5 !== void 0 ? _s5 : true, - messages: (_t = o5.messages) !== null && _t !== void 0 ? _t : true, - inlineRefs: (_u = o5.inlineRefs) !== null && _u !== void 0 ? _u : true, - schemaId: (_v = o5.schemaId) !== null && _v !== void 0 ? _v : "$id", - addUsedSchema: (_w = o5.addUsedSchema) !== null && _w !== void 0 ? _w : true, - validateSchema: (_x = o5.validateSchema) !== null && _x !== void 0 ? _x : true, - validateFormats: (_y = o5.validateFormats) !== null && _y !== void 0 ? _y : true, - unicodeRegExp: (_z = o5.unicodeRegExp) !== null && _z !== void 0 ? _z : true, - int32range: (_0 = o5.int32range) !== null && _0 !== void 0 ? _0 : true, - uriResolver - }; - } - var Ajv2 = class { - constructor(opts = {}) { - this.schemas = {}; - this.refs = {}; - this.formats = {}; - this._compilations = /* @__PURE__ */ new Set(); - this._loading = {}; - this._cache = /* @__PURE__ */ new Map(); - opts = this.opts = { ...opts, ...requiredOptions(opts) }; - const { es5, lines } = this.opts.code; - this.scope = new codegen_2.ValueScope({ scope: {}, prefixes: EXT_SCOPE_NAMES, es5, lines }); - this.logger = getLogger(opts.logger); - const formatOpt = opts.validateFormats; - opts.validateFormats = false; - this.RULES = (0, rules_1.getRules)(); - checkOptions.call(this, removedOptions, opts, "NOT SUPPORTED"); - checkOptions.call(this, deprecatedOptions, opts, "DEPRECATED", "warn"); - this._metaOpts = getMetaSchemaOptions.call(this); - if (opts.formats) - addInitialFormats.call(this); - this._addVocabularies(); - this._addDefaultMetaSchema(); - if (opts.keywords) - addInitialKeywords.call(this, opts.keywords); - if (typeof opts.meta == "object") - this.addMetaSchema(opts.meta); - addInitialSchemas.call(this); - opts.validateFormats = formatOpt; - } - _addVocabularies() { - this.addKeyword("$async"); - } - _addDefaultMetaSchema() { - const { $data, meta: meta3, schemaId } = this.opts; - let _dataRefSchema = $dataRefSchema; - if (schemaId === "id") { - _dataRefSchema = { ...$dataRefSchema }; - _dataRefSchema.id = _dataRefSchema.$id; - delete _dataRefSchema.$id; - } - if (meta3 && $data) - this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false); - } - defaultMeta() { - const { meta: meta3, schemaId } = this.opts; - return this.opts.defaultMeta = typeof meta3 == "object" ? meta3[schemaId] || meta3 : void 0; - } - validate(schemaKeyRef, data2) { - let v5; - if (typeof schemaKeyRef == "string") { - v5 = this.getSchema(schemaKeyRef); - if (!v5) - throw new Error(`no schema with key or ref "${schemaKeyRef}"`); - } else { - v5 = this.compile(schemaKeyRef); - } - const valid = v5(data2); - if (!("$async" in v5)) - this.errors = v5.errors; - return valid; - } - compile(schema2, _meta) { - const sch = this._addSchema(schema2, _meta); - return sch.validate || this._compileSchemaEnv(sch); - } - compileAsync(schema2, meta3) { - if (typeof this.opts.loadSchema != "function") { - throw new Error("options.loadSchema should be a function"); - } - const { loadSchema } = this.opts; - return runCompileAsync.call(this, schema2, meta3); - async function runCompileAsync(_schema, _meta) { - await loadMetaSchema.call(this, _schema.$schema); - const sch = this._addSchema(_schema, _meta); - return sch.validate || _compileAsync.call(this, sch); - } - async function loadMetaSchema($ref) { - if ($ref && !this.getSchema($ref)) { - await runCompileAsync.call(this, { $ref }, true); - } - } - async function _compileAsync(sch) { - try { - return this._compileSchemaEnv(sch); - } catch (e5) { - if (!(e5 instanceof ref_error_1.default)) - throw e5; - checkLoaded.call(this, e5); - await loadMissingSchema.call(this, e5.missingSchema); - return _compileAsync.call(this, sch); - } - } - function checkLoaded({ missingSchema: ref, missingRef }) { - if (this.refs[ref]) { - throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`); - } - } - async function loadMissingSchema(ref) { - const _schema = await _loadSchema.call(this, ref); - if (!this.refs[ref]) - await loadMetaSchema.call(this, _schema.$schema); - if (!this.refs[ref]) - this.addSchema(_schema, ref, meta3); - } - async function _loadSchema(ref) { - const p5 = this._loading[ref]; - if (p5) - return p5; - try { - return await (this._loading[ref] = loadSchema(ref)); - } finally { - delete this._loading[ref]; - } - } - } - // Adds schema to the instance - addSchema(schema2, key, _meta, _validateSchema = this.opts.validateSchema) { - if (Array.isArray(schema2)) { - for (const sch of schema2) - this.addSchema(sch, void 0, _meta, _validateSchema); - return this; - } - let id; - if (typeof schema2 === "object") { - const { schemaId } = this.opts; - id = schema2[schemaId]; - if (id !== void 0 && typeof id != "string") { - throw new Error(`schema ${schemaId} must be string`); - } - } - key = (0, resolve_1.normalizeId)(key || id); - this._checkUnique(key); - this.schemas[key] = this._addSchema(schema2, _meta, key, _validateSchema, true); - return this; - } - // Add schema that will be used to validate other schemas - // options in META_IGNORE_OPTIONS are alway set to false - addMetaSchema(schema2, key, _validateSchema = this.opts.validateSchema) { - this.addSchema(schema2, key, true, _validateSchema); - return this; - } - // Validate schema against its meta-schema - validateSchema(schema2, throwOrLogError) { - if (typeof schema2 == "boolean") - return true; - let $schema; - $schema = schema2.$schema; - if ($schema !== void 0 && typeof $schema != "string") { - throw new Error("$schema must be a string"); - } - $schema = $schema || this.opts.defaultMeta || this.defaultMeta(); - if (!$schema) { - this.logger.warn("meta-schema not available"); - this.errors = null; - return true; - } - const valid = this.validate($schema, schema2); - if (!valid && throwOrLogError) { - const message2 = "schema is invalid: " + this.errorsText(); - if (this.opts.validateSchema === "log") - this.logger.error(message2); - else - throw new Error(message2); - } - return valid; - } - // Get compiled schema by `key` or `ref`. - // (`key` that was passed to `addSchema` or full schema reference - `schema.$id` or resolved id) - getSchema(keyRef) { - let sch; - while (typeof (sch = getSchEnv.call(this, keyRef)) == "string") - keyRef = sch; - if (sch === void 0) { - const { schemaId } = this.opts; - const root = new compile_1.SchemaEnv({ schema: {}, schemaId }); - sch = compile_1.resolveSchema.call(this, root, keyRef); - if (!sch) - return; - this.refs[keyRef] = sch; - } - return sch.validate || this._compileSchemaEnv(sch); - } - // Remove cached schema(s). - // If no parameter is passed all schemas but meta-schemas are removed. - // If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed. - // Even if schema is referenced by other schemas it still can be removed as other schemas have local references. - removeSchema(schemaKeyRef) { - if (schemaKeyRef instanceof RegExp) { - this._removeAllSchemas(this.schemas, schemaKeyRef); - this._removeAllSchemas(this.refs, schemaKeyRef); - return this; - } - switch (typeof schemaKeyRef) { - case "undefined": - this._removeAllSchemas(this.schemas); - this._removeAllSchemas(this.refs); - this._cache.clear(); - return this; - case "string": { - const sch = getSchEnv.call(this, schemaKeyRef); - if (typeof sch == "object") - this._cache.delete(sch.schema); - delete this.schemas[schemaKeyRef]; - delete this.refs[schemaKeyRef]; - return this; - } - case "object": { - const cacheKey = schemaKeyRef; - this._cache.delete(cacheKey); - let id = schemaKeyRef[this.opts.schemaId]; - if (id) { - id = (0, resolve_1.normalizeId)(id); - delete this.schemas[id]; - delete this.refs[id]; - } - return this; - } - default: - throw new Error("ajv.removeSchema: invalid parameter"); - } - } - // add "vocabulary" - a collection of keywords - addVocabulary(definitions) { - for (const def of definitions) - this.addKeyword(def); - return this; - } - addKeyword(kwdOrDef, def) { - let keyword; - if (typeof kwdOrDef == "string") { - keyword = kwdOrDef; - if (typeof def == "object") { - this.logger.warn("these parameters are deprecated, see docs for addKeyword"); - def.keyword = keyword; - } - } else if (typeof kwdOrDef == "object" && def === void 0) { - def = kwdOrDef; - keyword = def.keyword; - if (Array.isArray(keyword) && !keyword.length) { - throw new Error("addKeywords: keyword must be string or non-empty array"); - } - } else { - throw new Error("invalid addKeywords parameters"); - } - checkKeyword.call(this, keyword, def); - if (!def) { - (0, util_1.eachItem)(keyword, (kwd) => addRule.call(this, kwd)); - return this; - } - keywordMetaschema.call(this, def); - const definition = { - ...def, - type: (0, dataType_1.getJSONTypes)(def.type), - schemaType: (0, dataType_1.getJSONTypes)(def.schemaType) - }; - (0, util_1.eachItem)(keyword, definition.type.length === 0 ? (k5) => addRule.call(this, k5, definition) : (k5) => definition.type.forEach((t5) => addRule.call(this, k5, definition, t5))); - return this; - } - getKeyword(keyword) { - const rule = this.RULES.all[keyword]; - return typeof rule == "object" ? rule.definition : !!rule; - } - // Remove keyword - removeKeyword(keyword) { - const { RULES } = this; - delete RULES.keywords[keyword]; - delete RULES.all[keyword]; - for (const group of RULES.rules) { - const i5 = group.rules.findIndex((rule) => rule.keyword === keyword); - if (i5 >= 0) - group.rules.splice(i5, 1); - } - return this; - } - // Add format - addFormat(name, format2) { - if (typeof format2 == "string") - format2 = new RegExp(format2); - this.formats[name] = format2; - return this; - } - errorsText(errors = this.errors, { separator = ", ", dataVar = "data" } = {}) { - if (!errors || errors.length === 0) - return "No errors"; - return errors.map((e5) => `${dataVar}${e5.instancePath} ${e5.message}`).reduce((text3, msg) => text3 + separator + msg); - } - $dataMetaSchema(metaSchema, keywordsJsonPointers) { - const rules = this.RULES.all; - metaSchema = JSON.parse(JSON.stringify(metaSchema)); - for (const jsonPointer of keywordsJsonPointers) { - const segments = jsonPointer.split("/").slice(1); - let keywords = metaSchema; - for (const seg of segments) - keywords = keywords[seg]; - for (const key in rules) { - const rule = rules[key]; - if (typeof rule != "object") - continue; - const { $data } = rule.definition; - const schema2 = keywords[key]; - if ($data && schema2) - keywords[key] = schemaOrData(schema2); - } - } - return metaSchema; - } - _removeAllSchemas(schemas, regex) { - for (const keyRef in schemas) { - const sch = schemas[keyRef]; - if (!regex || regex.test(keyRef)) { - if (typeof sch == "string") { - delete schemas[keyRef]; - } else if (sch && !sch.meta) { - this._cache.delete(sch.schema); - delete schemas[keyRef]; - } - } - } - } - _addSchema(schema2, meta3, baseId, validateSchema = this.opts.validateSchema, addSchema = this.opts.addUsedSchema) { - let id; - const { schemaId } = this.opts; - if (typeof schema2 == "object") { - id = schema2[schemaId]; - } else { - if (this.opts.jtd) - throw new Error("schema must be object"); - else if (typeof schema2 != "boolean") - throw new Error("schema must be object or boolean"); - } - let sch = this._cache.get(schema2); - if (sch !== void 0) - return sch; - baseId = (0, resolve_1.normalizeId)(id || baseId); - const localRefs = resolve_1.getSchemaRefs.call(this, schema2, baseId); - sch = new compile_1.SchemaEnv({ schema: schema2, schemaId, meta: meta3, baseId, localRefs }); - this._cache.set(sch.schema, sch); - if (addSchema && !baseId.startsWith("#")) { - if (baseId) - this._checkUnique(baseId); - this.refs[baseId] = sch; - } - if (validateSchema) - this.validateSchema(schema2, true); - return sch; - } - _checkUnique(id) { - if (this.schemas[id] || this.refs[id]) { - throw new Error(`schema with key or id "${id}" already exists`); - } - } - _compileSchemaEnv(sch) { - if (sch.meta) - this._compileMetaSchema(sch); - else - compile_1.compileSchema.call(this, sch); - if (!sch.validate) - throw new Error("ajv implementation error"); - return sch.validate; - } - _compileMetaSchema(sch) { - const currentOpts = this.opts; - this.opts = this._metaOpts; - try { - compile_1.compileSchema.call(this, sch); - } finally { - this.opts = currentOpts; - } - } - }; - Ajv2.ValidationError = validation_error_1.default; - Ajv2.MissingRefError = ref_error_1.default; - exports.default = Ajv2; - function checkOptions(checkOpts3, options, msg, log2 = "error") { - for (const key in checkOpts3) { - const opt = key; - if (opt in options) - this.logger[log2](`${msg}: option ${key}. ${checkOpts3[opt]}`); - } - } - function getSchEnv(keyRef) { - keyRef = (0, resolve_1.normalizeId)(keyRef); - return this.schemas[keyRef] || this.refs[keyRef]; - } - function addInitialSchemas() { - const optsSchemas = this.opts.schemas; - if (!optsSchemas) - return; - if (Array.isArray(optsSchemas)) - this.addSchema(optsSchemas); - else - for (const key in optsSchemas) - this.addSchema(optsSchemas[key], key); - } - function addInitialFormats() { - for (const name in this.opts.formats) { - const format2 = this.opts.formats[name]; - if (format2) - this.addFormat(name, format2); - } - } - function addInitialKeywords(defs) { - if (Array.isArray(defs)) { - this.addVocabulary(defs); - return; - } - this.logger.warn("keywords option as map is deprecated, pass array"); - for (const keyword in defs) { - const def = defs[keyword]; - if (!def.keyword) - def.keyword = keyword; - this.addKeyword(def); - } - } - function getMetaSchemaOptions() { - const metaOpts = { ...this.opts }; - for (const opt of META_IGNORE_OPTIONS) - delete metaOpts[opt]; - return metaOpts; - } - var noLogs = { log() { - }, warn() { - }, error() { - } }; - function getLogger(logger4) { - if (logger4 === false) - return noLogs; - if (logger4 === void 0) - return console; - if (logger4.log && logger4.warn && logger4.error) - return logger4; - throw new Error("logger must implement log, warn and error methods"); - } - var KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i; - function checkKeyword(keyword, def) { - const { RULES } = this; - (0, util_1.eachItem)(keyword, (kwd) => { - if (RULES.keywords[kwd]) - throw new Error(`Keyword ${kwd} is already defined`); - if (!KEYWORD_NAME.test(kwd)) - throw new Error(`Keyword ${kwd} has invalid name`); - }); - if (!def) - return; - if (def.$data && !("code" in def || "validate" in def)) { - throw new Error('$data keyword must have "code" or "validate" function'); - } - } - function addRule(keyword, definition, dataType) { - var _a6; - const post = definition === null || definition === void 0 ? void 0 : definition.post; - if (dataType && post) - throw new Error('keyword with "post" flag cannot have "type"'); - const { RULES } = this; - let ruleGroup = post ? RULES.post : RULES.rules.find(({ type: t5 }) => t5 === dataType); - if (!ruleGroup) { - ruleGroup = { type: dataType, rules: [] }; - RULES.rules.push(ruleGroup); - } - RULES.keywords[keyword] = true; - if (!definition) - return; - const rule = { - keyword, - definition: { - ...definition, - type: (0, dataType_1.getJSONTypes)(definition.type), - schemaType: (0, dataType_1.getJSONTypes)(definition.schemaType) - } - }; - if (definition.before) - addBeforeRule.call(this, ruleGroup, rule, definition.before); - else - ruleGroup.rules.push(rule); - RULES.all[keyword] = rule; - (_a6 = definition.implements) === null || _a6 === void 0 ? void 0 : _a6.forEach((kwd) => this.addKeyword(kwd)); - } - function addBeforeRule(ruleGroup, rule, before) { - const i5 = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before); - if (i5 >= 0) { - ruleGroup.rules.splice(i5, 0, rule); - } else { - ruleGroup.rules.push(rule); - this.logger.warn(`rule ${before} is not defined`); - } - } - function keywordMetaschema(def) { - let { metaSchema } = def; - if (metaSchema === void 0) - return; - if (def.$data && this.opts.$data) - metaSchema = schemaOrData(metaSchema); - def.validateSchema = this.compile(metaSchema, true); - } - var $dataRef = { - $ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#" - }; - function schemaOrData(schema2) { - return { anyOf: [schema2, $dataRef] }; - } - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/core/id.js -var require_id = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/core/id.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - var def = { - keyword: "id", - code() { - throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID'); - } - }; - exports.default = def; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/core/ref.js -var require_ref2 = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/core/ref.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.callRef = exports.getValidate = void 0; - var ref_error_1 = require_ref_error(); - var code_1 = require_code2(); - var codegen_1 = require_codegen(); - var names_1 = require_names(); - var compile_1 = require_compile(); - var util_1 = require_util(); - var def = { - keyword: "$ref", - schemaType: "string", - code(cxt) { - const { gen, schema: $ref, it } = cxt; - const { baseId, schemaEnv: env2, validateName, opts, self: self2 } = it; - const { root } = env2; - if (($ref === "#" || $ref === "#/") && baseId === root.baseId) - return callRootRef(); - const schOrEnv = compile_1.resolveRef.call(self2, root, baseId, $ref); - if (schOrEnv === void 0) - throw new ref_error_1.default(it.opts.uriResolver, baseId, $ref); - if (schOrEnv instanceof compile_1.SchemaEnv) - return callValidate(schOrEnv); - return inlineRefSchema(schOrEnv); - function callRootRef() { - if (env2 === root) - return callRef(cxt, validateName, env2, env2.$async); - const rootName = gen.scopeValue("root", { ref: root }); - return callRef(cxt, (0, codegen_1._)`${rootName}.validate`, root, root.$async); - } - function callValidate(sch) { - const v5 = getValidate(cxt, sch); - callRef(cxt, v5, sch, sch.$async); - } - function inlineRefSchema(sch) { - const schName = gen.scopeValue("schema", opts.code.source === true ? { ref: sch, code: (0, codegen_1.stringify)(sch) } : { ref: sch }); - const valid = gen.name("valid"); - const schCxt = cxt.subschema({ - schema: sch, - dataTypes: [], - schemaPath: codegen_1.nil, - topSchemaRef: schName, - errSchemaPath: $ref - }, valid); - cxt.mergeEvaluated(schCxt); - cxt.ok(valid); - } - } - }; - function getValidate(cxt, sch) { - const { gen } = cxt; - return sch.validate ? gen.scopeValue("validate", { ref: sch.validate }) : (0, codegen_1._)`${gen.scopeValue("wrapper", { ref: sch })}.validate`; - } - exports.getValidate = getValidate; - function callRef(cxt, v5, sch, $async) { - const { gen, it } = cxt; - const { allErrors, schemaEnv: env2, opts } = it; - const passCxt = opts.passContext ? names_1.default.this : codegen_1.nil; - if ($async) - callAsyncRef(); - else - callSyncRef(); - function callAsyncRef() { - if (!env2.$async) - throw new Error("async schema referenced by sync schema"); - const valid = gen.let("valid"); - gen.try(() => { - gen.code((0, codegen_1._)`await ${(0, code_1.callValidateCode)(cxt, v5, passCxt)}`); - addEvaluatedFrom(v5); - if (!allErrors) - gen.assign(valid, true); - }, (e5) => { - gen.if((0, codegen_1._)`!(${e5} instanceof ${it.ValidationError})`, () => gen.throw(e5)); - addErrorsFrom(e5); - if (!allErrors) - gen.assign(valid, false); - }); - cxt.ok(valid); - } - function callSyncRef() { - cxt.result((0, code_1.callValidateCode)(cxt, v5, passCxt), () => addEvaluatedFrom(v5), () => addErrorsFrom(v5)); - } - function addErrorsFrom(source) { - const errs = (0, codegen_1._)`${source}.errors`; - gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`); - gen.assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`); - } - function addEvaluatedFrom(source) { - var _a6; - if (!it.opts.unevaluated) - return; - const schEvaluated = (_a6 = sch === null || sch === void 0 ? void 0 : sch.validate) === null || _a6 === void 0 ? void 0 : _a6.evaluated; - if (it.props !== true) { - if (schEvaluated && !schEvaluated.dynamicProps) { - if (schEvaluated.props !== void 0) { - it.props = util_1.mergeEvaluated.props(gen, schEvaluated.props, it.props); - } - } else { - const props = gen.var("props", (0, codegen_1._)`${source}.evaluated.props`); - it.props = util_1.mergeEvaluated.props(gen, props, it.props, codegen_1.Name); - } - } - if (it.items !== true) { - if (schEvaluated && !schEvaluated.dynamicItems) { - if (schEvaluated.items !== void 0) { - it.items = util_1.mergeEvaluated.items(gen, schEvaluated.items, it.items); - } - } else { - const items = gen.var("items", (0, codegen_1._)`${source}.evaluated.items`); - it.items = util_1.mergeEvaluated.items(gen, items, it.items, codegen_1.Name); - } - } - } - } - exports.callRef = callRef; - exports.default = def; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/core/index.js -var require_core2 = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/core/index.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - var id_1 = require_id(); - var ref_1 = require_ref2(); - var core = [ - "$schema", - "$id", - "$defs", - "$vocabulary", - { keyword: "$comment" }, - "definitions", - id_1.default, - ref_1.default - ]; - exports.default = core; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitNumber.js -var require_limitNumber = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitNumber.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - var codegen_1 = require_codegen(); - var ops = codegen_1.operators; - var KWDs = { - maximum: { okStr: "<=", ok: ops.LTE, fail: ops.GT }, - minimum: { okStr: ">=", ok: ops.GTE, fail: ops.LT }, - exclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE }, - exclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE } - }; - var error50 = { - message: ({ keyword, schemaCode }) => (0, codegen_1.str)`must be ${KWDs[keyword].okStr} ${schemaCode}`, - params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}` - }; - var def = { - keyword: Object.keys(KWDs), - type: "number", - schemaType: "number", - $data: true, - error: error50, - code(cxt) { - const { keyword, data: data2, schemaCode } = cxt; - cxt.fail$data((0, codegen_1._)`${data2} ${KWDs[keyword].fail} ${schemaCode} || isNaN(${data2})`); - } - }; - exports.default = def; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/multipleOf.js -var require_multipleOf = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/multipleOf.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - var codegen_1 = require_codegen(); - var error50 = { - message: ({ schemaCode }) => (0, codegen_1.str)`must be multiple of ${schemaCode}`, - params: ({ schemaCode }) => (0, codegen_1._)`{multipleOf: ${schemaCode}}` - }; - var def = { - keyword: "multipleOf", - type: "number", - schemaType: "number", - $data: true, - error: error50, - code(cxt) { - const { gen, data: data2, schemaCode, it } = cxt; - const prec = it.opts.multipleOfPrecision; - const res = gen.let("res"); - const invalid = prec ? (0, codegen_1._)`Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}` : (0, codegen_1._)`${res} !== parseInt(${res})`; - cxt.fail$data((0, codegen_1._)`(${schemaCode} === 0 || (${res} = ${data2}/${schemaCode}, ${invalid}))`); - } - }; - exports.default = def; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/ucs2length.js -var require_ucs2length = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/ucs2length.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - function ucs2length(str) { - const len = str.length; - let length = 0; - let pos = 0; - let value; - while (pos < len) { - length++; - value = str.charCodeAt(pos++); - if (value >= 55296 && value <= 56319 && pos < len) { - value = str.charCodeAt(pos); - if ((value & 64512) === 56320) - pos++; - } - } - return length; - } - exports.default = ucs2length; - ucs2length.code = 'require("ajv/dist/runtime/ucs2length").default'; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitLength.js -var require_limitLength = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitLength.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - var codegen_1 = require_codegen(); - var util_1 = require_util(); - var ucs2length_1 = require_ucs2length(); - var error50 = { - message({ keyword, schemaCode }) { - const comp = keyword === "maxLength" ? "more" : "fewer"; - return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} characters`; - }, - params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` - }; - var def = { - keyword: ["maxLength", "minLength"], - type: "string", - schemaType: "number", - $data: true, - error: error50, - code(cxt) { - const { keyword, data: data2, schemaCode, it } = cxt; - const op2 = keyword === "maxLength" ? codegen_1.operators.GT : codegen_1.operators.LT; - const len = it.opts.unicode === false ? (0, codegen_1._)`${data2}.length` : (0, codegen_1._)`${(0, util_1.useFunc)(cxt.gen, ucs2length_1.default)}(${data2})`; - cxt.fail$data((0, codegen_1._)`${len} ${op2} ${schemaCode}`); - } - }; - exports.default = def; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/pattern.js -var require_pattern = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/pattern.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - var code_1 = require_code2(); - var util_1 = require_util(); - var codegen_1 = require_codegen(); - var error50 = { - message: ({ schemaCode }) => (0, codegen_1.str)`must match pattern "${schemaCode}"`, - params: ({ schemaCode }) => (0, codegen_1._)`{pattern: ${schemaCode}}` - }; - var def = { - keyword: "pattern", - type: "string", - schemaType: "string", - $data: true, - error: error50, - code(cxt) { - const { gen, data: data2, $data, schema: schema2, schemaCode, it } = cxt; - const u5 = it.opts.unicodeRegExp ? "u" : ""; - if ($data) { - const { regExp } = it.opts.code; - const regExpCode = regExp.code === "new RegExp" ? (0, codegen_1._)`new RegExp` : (0, util_1.useFunc)(gen, regExp); - const valid = gen.let("valid"); - gen.try(() => gen.assign(valid, (0, codegen_1._)`${regExpCode}(${schemaCode}, ${u5}).test(${data2})`), () => gen.assign(valid, false)); - cxt.fail$data((0, codegen_1._)`!${valid}`); - } else { - const regExp = (0, code_1.usePattern)(cxt, schema2); - cxt.fail$data((0, codegen_1._)`!${regExp}.test(${data2})`); - } - } - }; - exports.default = def; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitProperties.js -var require_limitProperties = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitProperties.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - var codegen_1 = require_codegen(); - var error50 = { - message({ keyword, schemaCode }) { - const comp = keyword === "maxProperties" ? "more" : "fewer"; - return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} properties`; - }, - params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` - }; - var def = { - keyword: ["maxProperties", "minProperties"], - type: "object", - schemaType: "number", - $data: true, - error: error50, - code(cxt) { - const { keyword, data: data2, schemaCode } = cxt; - const op2 = keyword === "maxProperties" ? codegen_1.operators.GT : codegen_1.operators.LT; - cxt.fail$data((0, codegen_1._)`Object.keys(${data2}).length ${op2} ${schemaCode}`); - } - }; - exports.default = def; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/required.js -var require_required = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/required.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - var code_1 = require_code2(); - var codegen_1 = require_codegen(); - var util_1 = require_util(); - var error50 = { - message: ({ params: { missingProperty } }) => (0, codegen_1.str)`must have required property '${missingProperty}'`, - params: ({ params: { missingProperty } }) => (0, codegen_1._)`{missingProperty: ${missingProperty}}` - }; - var def = { - keyword: "required", - type: "object", - schemaType: "array", - $data: true, - error: error50, - code(cxt) { - const { gen, schema: schema2, schemaCode, data: data2, $data, it } = cxt; - const { opts } = it; - if (!$data && schema2.length === 0) - return; - const useLoop = schema2.length >= opts.loopRequired; - if (it.allErrors) - allErrorsMode(); - else - exitOnErrorMode(); - if (opts.strictRequired) { - const props = cxt.parentSchema.properties; - const { definedProperties } = cxt.it; - for (const requiredKey of schema2) { - if ((props === null || props === void 0 ? void 0 : props[requiredKey]) === void 0 && !definedProperties.has(requiredKey)) { - const schemaPath = it.schemaEnv.baseId + it.errSchemaPath; - const msg = `required property "${requiredKey}" is not defined at "${schemaPath}" (strictRequired)`; - (0, util_1.checkStrictMode)(it, msg, it.opts.strictRequired); - } - } - } - function allErrorsMode() { - if (useLoop || $data) { - cxt.block$data(codegen_1.nil, loopAllRequired); - } else { - for (const prop of schema2) { - (0, code_1.checkReportMissingProp)(cxt, prop); - } - } - } - function exitOnErrorMode() { - const missing = gen.let("missing"); - if (useLoop || $data) { - const valid = gen.let("valid", true); - cxt.block$data(valid, () => loopUntilMissing(missing, valid)); - cxt.ok(valid); - } else { - gen.if((0, code_1.checkMissingProp)(cxt, schema2, missing)); - (0, code_1.reportMissingProp)(cxt, missing); - gen.else(); - } - } - function loopAllRequired() { - gen.forOf("prop", schemaCode, (prop) => { - cxt.setParams({ missingProperty: prop }); - gen.if((0, code_1.noPropertyInData)(gen, data2, prop, opts.ownProperties), () => cxt.error()); - }); - } - function loopUntilMissing(missing, valid) { - cxt.setParams({ missingProperty: missing }); - gen.forOf(missing, schemaCode, () => { - gen.assign(valid, (0, code_1.propertyInData)(gen, data2, missing, opts.ownProperties)); - gen.if((0, codegen_1.not)(valid), () => { - cxt.error(); - gen.break(); - }); - }, codegen_1.nil); - } - } - }; - exports.default = def; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitItems.js -var require_limitItems = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitItems.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - var codegen_1 = require_codegen(); - var error50 = { - message({ keyword, schemaCode }) { - const comp = keyword === "maxItems" ? "more" : "fewer"; - return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} items`; - }, - params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` - }; - var def = { - keyword: ["maxItems", "minItems"], - type: "array", - schemaType: "number", - $data: true, - error: error50, - code(cxt) { - const { keyword, data: data2, schemaCode } = cxt; - const op2 = keyword === "maxItems" ? codegen_1.operators.GT : codegen_1.operators.LT; - cxt.fail$data((0, codegen_1._)`${data2}.length ${op2} ${schemaCode}`); - } - }; - exports.default = def; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/equal.js -var require_equal = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/equal.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - var equal = require_fast_deep_equal(); - equal.code = 'require("ajv/dist/runtime/equal").default'; - exports.default = equal; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/uniqueItems.js -var require_uniqueItems = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/uniqueItems.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - var dataType_1 = require_dataType(); - var codegen_1 = require_codegen(); - var util_1 = require_util(); - var equal_1 = require_equal(); - var error50 = { - message: ({ params: { i: i5, j: j5 } }) => (0, codegen_1.str)`must NOT have duplicate items (items ## ${j5} and ${i5} are identical)`, - params: ({ params: { i: i5, j: j5 } }) => (0, codegen_1._)`{i: ${i5}, j: ${j5}}` - }; - var def = { - keyword: "uniqueItems", - type: "array", - schemaType: "boolean", - $data: true, - error: error50, - code(cxt) { - const { gen, data: data2, $data, schema: schema2, parentSchema, schemaCode, it } = cxt; - if (!$data && !schema2) - return; - const valid = gen.let("valid"); - const itemTypes = parentSchema.items ? (0, dataType_1.getSchemaTypes)(parentSchema.items) : []; - cxt.block$data(valid, validateUniqueItems, (0, codegen_1._)`${schemaCode} === false`); - cxt.ok(valid); - function validateUniqueItems() { - const i5 = gen.let("i", (0, codegen_1._)`${data2}.length`); - const j5 = gen.let("j"); - cxt.setParams({ i: i5, j: j5 }); - gen.assign(valid, true); - gen.if((0, codegen_1._)`${i5} > 1`, () => (canOptimize() ? loopN : loopN2)(i5, j5)); - } - function canOptimize() { - return itemTypes.length > 0 && !itemTypes.some((t5) => t5 === "object" || t5 === "array"); - } - function loopN(i5, j5) { - const item = gen.name("item"); - const wrongType = (0, dataType_1.checkDataTypes)(itemTypes, item, it.opts.strictNumbers, dataType_1.DataType.Wrong); - const indices = gen.const("indices", (0, codegen_1._)`{}`); - gen.for((0, codegen_1._)`;${i5}--;`, () => { - gen.let(item, (0, codegen_1._)`${data2}[${i5}]`); - gen.if(wrongType, (0, codegen_1._)`continue`); - if (itemTypes.length > 1) - gen.if((0, codegen_1._)`typeof ${item} == "string"`, (0, codegen_1._)`${item} += "_"`); - gen.if((0, codegen_1._)`typeof ${indices}[${item}] == "number"`, () => { - gen.assign(j5, (0, codegen_1._)`${indices}[${item}]`); - cxt.error(); - gen.assign(valid, false).break(); - }).code((0, codegen_1._)`${indices}[${item}] = ${i5}`); - }); - } - function loopN2(i5, j5) { - const eql = (0, util_1.useFunc)(gen, equal_1.default); - const outer = gen.name("outer"); - gen.label(outer).for((0, codegen_1._)`;${i5}--;`, () => gen.for((0, codegen_1._)`${j5} = ${i5}; ${j5}--;`, () => gen.if((0, codegen_1._)`${eql}(${data2}[${i5}], ${data2}[${j5}])`, () => { - cxt.error(); - gen.assign(valid, false).break(outer); - }))); - } - } - }; - exports.default = def; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/const.js -var require_const = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/const.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - var codegen_1 = require_codegen(); - var util_1 = require_util(); - var equal_1 = require_equal(); - var error50 = { - message: "must be equal to constant", - params: ({ schemaCode }) => (0, codegen_1._)`{allowedValue: ${schemaCode}}` - }; - var def = { - keyword: "const", - $data: true, - error: error50, - code(cxt) { - const { gen, data: data2, $data, schemaCode, schema: schema2 } = cxt; - if ($data || schema2 && typeof schema2 == "object") { - cxt.fail$data((0, codegen_1._)`!${(0, util_1.useFunc)(gen, equal_1.default)}(${data2}, ${schemaCode})`); - } else { - cxt.fail((0, codegen_1._)`${schema2} !== ${data2}`); - } - } - }; - exports.default = def; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/enum.js -var require_enum = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/enum.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - var codegen_1 = require_codegen(); - var util_1 = require_util(); - var equal_1 = require_equal(); - var error50 = { - message: "must be equal to one of the allowed values", - params: ({ schemaCode }) => (0, codegen_1._)`{allowedValues: ${schemaCode}}` - }; - var def = { - keyword: "enum", - schemaType: "array", - $data: true, - error: error50, - code(cxt) { - const { gen, data: data2, $data, schema: schema2, schemaCode, it } = cxt; - if (!$data && schema2.length === 0) - throw new Error("enum must have non-empty array"); - const useLoop = schema2.length >= it.opts.loopEnum; - let eql; - const getEql = () => eql !== null && eql !== void 0 ? eql : eql = (0, util_1.useFunc)(gen, equal_1.default); - let valid; - if (useLoop || $data) { - valid = gen.let("valid"); - cxt.block$data(valid, loopEnum); - } else { - if (!Array.isArray(schema2)) - throw new Error("ajv implementation error"); - const vSchema = gen.const("vSchema", schemaCode); - valid = (0, codegen_1.or)(...schema2.map((_x, i5) => equalCode(vSchema, i5))); - } - cxt.pass(valid); - function loopEnum() { - gen.assign(valid, false); - gen.forOf("v", schemaCode, (v5) => gen.if((0, codegen_1._)`${getEql()}(${data2}, ${v5})`, () => gen.assign(valid, true).break())); - } - function equalCode(vSchema, i5) { - const sch = schema2[i5]; - return typeof sch === "object" && sch !== null ? (0, codegen_1._)`${getEql()}(${data2}, ${vSchema}[${i5}])` : (0, codegen_1._)`${data2} === ${sch}`; - } - } - }; - exports.default = def; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/index.js -var require_validation2 = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/index.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - var limitNumber_1 = require_limitNumber(); - var multipleOf_1 = require_multipleOf(); - var limitLength_1 = require_limitLength(); - var pattern_1 = require_pattern(); - var limitProperties_1 = require_limitProperties(); - var required_1 = require_required(); - var limitItems_1 = require_limitItems(); - var uniqueItems_1 = require_uniqueItems(); - var const_1 = require_const(); - var enum_1 = require_enum(); - var validation = [ - // number - limitNumber_1.default, - multipleOf_1.default, - // string - limitLength_1.default, - pattern_1.default, - // object - limitProperties_1.default, - required_1.default, - // array - limitItems_1.default, - uniqueItems_1.default, - // any - { keyword: "type", schemaType: ["string", "array"] }, - { keyword: "nullable", schemaType: "boolean" }, - const_1.default, - enum_1.default - ]; - exports.default = validation; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/additionalItems.js -var require_additionalItems = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/additionalItems.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.validateAdditionalItems = void 0; - var codegen_1 = require_codegen(); - var util_1 = require_util(); - var error50 = { - message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, - params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` - }; - var def = { - keyword: "additionalItems", - type: "array", - schemaType: ["boolean", "object"], - before: "uniqueItems", - error: error50, - code(cxt) { - const { parentSchema, it } = cxt; - const { items } = parentSchema; - if (!Array.isArray(items)) { - (0, util_1.checkStrictMode)(it, '"additionalItems" is ignored when "items" is not an array of schemas'); - return; - } - validateAdditionalItems(cxt, items); - } - }; - function validateAdditionalItems(cxt, items) { - const { gen, schema: schema2, data: data2, keyword, it } = cxt; - it.items = true; - const len = gen.const("len", (0, codegen_1._)`${data2}.length`); - if (schema2 === false) { - cxt.setParams({ len: items.length }); - cxt.pass((0, codegen_1._)`${len} <= ${items.length}`); - } else if (typeof schema2 == "object" && !(0, util_1.alwaysValidSchema)(it, schema2)) { - const valid = gen.var("valid", (0, codegen_1._)`${len} <= ${items.length}`); - gen.if((0, codegen_1.not)(valid), () => validateItems(valid)); - cxt.ok(valid); - } - function validateItems(valid) { - gen.forRange("i", items.length, len, (i5) => { - cxt.subschema({ keyword, dataProp: i5, dataPropType: util_1.Type.Num }, valid); - if (!it.allErrors) - gen.if((0, codegen_1.not)(valid), () => gen.break()); - }); - } - } - exports.validateAdditionalItems = validateAdditionalItems; - exports.default = def; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/items.js -var require_items = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/items.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.validateTuple = void 0; - var codegen_1 = require_codegen(); - var util_1 = require_util(); - var code_1 = require_code2(); - var def = { - keyword: "items", - type: "array", - schemaType: ["object", "array", "boolean"], - before: "uniqueItems", - code(cxt) { - const { schema: schema2, it } = cxt; - if (Array.isArray(schema2)) - return validateTuple(cxt, "additionalItems", schema2); - it.items = true; - if ((0, util_1.alwaysValidSchema)(it, schema2)) - return; - cxt.ok((0, code_1.validateArray)(cxt)); - } - }; - function validateTuple(cxt, extraItems, schArr = cxt.schema) { - const { gen, parentSchema, data: data2, keyword, it } = cxt; - checkStrictTuple(parentSchema); - if (it.opts.unevaluated && schArr.length && it.items !== true) { - it.items = util_1.mergeEvaluated.items(gen, schArr.length, it.items); - } - const valid = gen.name("valid"); - const len = gen.const("len", (0, codegen_1._)`${data2}.length`); - schArr.forEach((sch, i5) => { - if ((0, util_1.alwaysValidSchema)(it, sch)) - return; - gen.if((0, codegen_1._)`${len} > ${i5}`, () => cxt.subschema({ - keyword, - schemaProp: i5, - dataProp: i5 - }, valid)); - cxt.ok(valid); - }); - function checkStrictTuple(sch) { - const { opts, errSchemaPath } = it; - const l5 = schArr.length; - const fullTuple = l5 === sch.minItems && (l5 === sch.maxItems || sch[extraItems] === false); - if (opts.strictTuples && !fullTuple) { - const msg = `"${keyword}" is ${l5}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path "${errSchemaPath}"`; - (0, util_1.checkStrictMode)(it, msg, opts.strictTuples); - } - } - } - exports.validateTuple = validateTuple; - exports.default = def; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/prefixItems.js -var require_prefixItems = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/prefixItems.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - var items_1 = require_items(); - var def = { - keyword: "prefixItems", - type: "array", - schemaType: ["array"], - before: "uniqueItems", - code: (cxt) => (0, items_1.validateTuple)(cxt, "items") - }; - exports.default = def; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/items2020.js -var require_items2020 = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/items2020.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - var codegen_1 = require_codegen(); - var util_1 = require_util(); - var code_1 = require_code2(); - var additionalItems_1 = require_additionalItems(); - var error50 = { - message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, - params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` - }; - var def = { - keyword: "items", - type: "array", - schemaType: ["object", "boolean"], - before: "uniqueItems", - error: error50, - code(cxt) { - const { schema: schema2, parentSchema, it } = cxt; - const { prefixItems } = parentSchema; - it.items = true; - if ((0, util_1.alwaysValidSchema)(it, schema2)) - return; - if (prefixItems) - (0, additionalItems_1.validateAdditionalItems)(cxt, prefixItems); - else - cxt.ok((0, code_1.validateArray)(cxt)); - } - }; - exports.default = def; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/contains.js -var require_contains = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/contains.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - var codegen_1 = require_codegen(); - var util_1 = require_util(); - var error50 = { - message: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1.str)`must contain at least ${min} valid item(s)` : (0, codegen_1.str)`must contain at least ${min} and no more than ${max} valid item(s)`, - params: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1._)`{minContains: ${min}}` : (0, codegen_1._)`{minContains: ${min}, maxContains: ${max}}` - }; - var def = { - keyword: "contains", - type: "array", - schemaType: ["object", "boolean"], - before: "uniqueItems", - trackErrors: true, - error: error50, - code(cxt) { - const { gen, schema: schema2, parentSchema, data: data2, it } = cxt; - let min; - let max; - const { minContains, maxContains } = parentSchema; - if (it.opts.next) { - min = minContains === void 0 ? 1 : minContains; - max = maxContains; - } else { - min = 1; - } - const len = gen.const("len", (0, codegen_1._)`${data2}.length`); - cxt.setParams({ min, max }); - if (max === void 0 && min === 0) { - (0, util_1.checkStrictMode)(it, `"minContains" == 0 without "maxContains": "contains" keyword ignored`); - return; - } - if (max !== void 0 && min > max) { - (0, util_1.checkStrictMode)(it, `"minContains" > "maxContains" is always invalid`); - cxt.fail(); - return; - } - if ((0, util_1.alwaysValidSchema)(it, schema2)) { - let cond = (0, codegen_1._)`${len} >= ${min}`; - if (max !== void 0) - cond = (0, codegen_1._)`${cond} && ${len} <= ${max}`; - cxt.pass(cond); - return; - } - it.items = true; - const valid = gen.name("valid"); - if (max === void 0 && min === 1) { - validateItems(valid, () => gen.if(valid, () => gen.break())); - } else if (min === 0) { - gen.let(valid, true); - if (max !== void 0) - gen.if((0, codegen_1._)`${data2}.length > 0`, validateItemsWithCount); - } else { - gen.let(valid, false); - validateItemsWithCount(); - } - cxt.result(valid, () => cxt.reset()); - function validateItemsWithCount() { - const schValid = gen.name("_valid"); - const count2 = gen.let("count", 0); - validateItems(schValid, () => gen.if(schValid, () => checkLimits(count2))); - } - function validateItems(_valid, block) { - gen.forRange("i", 0, len, (i5) => { - cxt.subschema({ - keyword: "contains", - dataProp: i5, - dataPropType: util_1.Type.Num, - compositeRule: true - }, _valid); - block(); - }); - } - function checkLimits(count2) { - gen.code((0, codegen_1._)`${count2}++`); - if (max === void 0) { - gen.if((0, codegen_1._)`${count2} >= ${min}`, () => gen.assign(valid, true).break()); - } else { - gen.if((0, codegen_1._)`${count2} > ${max}`, () => gen.assign(valid, false).break()); - if (min === 1) - gen.assign(valid, true); - else - gen.if((0, codegen_1._)`${count2} >= ${min}`, () => gen.assign(valid, true)); - } - } - } - }; - exports.default = def; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/dependencies.js -var require_dependencies = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/dependencies.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.validateSchemaDeps = exports.validatePropertyDeps = exports.error = void 0; - var codegen_1 = require_codegen(); - var util_1 = require_util(); - var code_1 = require_code2(); - exports.error = { - message: ({ params: { property, depsCount, deps } }) => { - const property_ies = depsCount === 1 ? "property" : "properties"; - return (0, codegen_1.str)`must have ${property_ies} ${deps} when property ${property} is present`; - }, - params: ({ params: { property, depsCount, deps, missingProperty } }) => (0, codegen_1._)`{property: ${property}, - missingProperty: ${missingProperty}, - depsCount: ${depsCount}, - deps: ${deps}}` - // TODO change to reference - }; - var def = { - keyword: "dependencies", - type: "object", - schemaType: "object", - error: exports.error, - code(cxt) { - const [propDeps, schDeps] = splitDependencies(cxt); - validatePropertyDeps(cxt, propDeps); - validateSchemaDeps(cxt, schDeps); - } - }; - function splitDependencies({ schema: schema2 }) { - const propertyDeps = {}; - const schemaDeps = {}; - for (const key in schema2) { - if (key === "__proto__") - continue; - const deps = Array.isArray(schema2[key]) ? propertyDeps : schemaDeps; - deps[key] = schema2[key]; - } - return [propertyDeps, schemaDeps]; - } - function validatePropertyDeps(cxt, propertyDeps = cxt.schema) { - const { gen, data: data2, it } = cxt; - if (Object.keys(propertyDeps).length === 0) - return; - const missing = gen.let("missing"); - for (const prop in propertyDeps) { - const deps = propertyDeps[prop]; - if (deps.length === 0) - continue; - const hasProperty = (0, code_1.propertyInData)(gen, data2, prop, it.opts.ownProperties); - cxt.setParams({ - property: prop, - depsCount: deps.length, - deps: deps.join(", ") - }); - if (it.allErrors) { - gen.if(hasProperty, () => { - for (const depProp of deps) { - (0, code_1.checkReportMissingProp)(cxt, depProp); - } - }); - } else { - gen.if((0, codegen_1._)`${hasProperty} && (${(0, code_1.checkMissingProp)(cxt, deps, missing)})`); - (0, code_1.reportMissingProp)(cxt, missing); - gen.else(); - } - } - } - exports.validatePropertyDeps = validatePropertyDeps; - function validateSchemaDeps(cxt, schemaDeps = cxt.schema) { - const { gen, data: data2, keyword, it } = cxt; - const valid = gen.name("valid"); - for (const prop in schemaDeps) { - if ((0, util_1.alwaysValidSchema)(it, schemaDeps[prop])) - continue; - gen.if( - (0, code_1.propertyInData)(gen, data2, prop, it.opts.ownProperties), - () => { - const schCxt = cxt.subschema({ keyword, schemaProp: prop }, valid); - cxt.mergeValidEvaluated(schCxt, valid); - }, - () => gen.var(valid, true) - // TODO var - ); - cxt.ok(valid); - } - } - exports.validateSchemaDeps = validateSchemaDeps; - exports.default = def; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/propertyNames.js -var require_propertyNames = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/propertyNames.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - var codegen_1 = require_codegen(); - var util_1 = require_util(); - var error50 = { - message: "property name must be valid", - params: ({ params }) => (0, codegen_1._)`{propertyName: ${params.propertyName}}` - }; - var def = { - keyword: "propertyNames", - type: "object", - schemaType: ["object", "boolean"], - error: error50, - code(cxt) { - const { gen, schema: schema2, data: data2, it } = cxt; - if ((0, util_1.alwaysValidSchema)(it, schema2)) - return; - const valid = gen.name("valid"); - gen.forIn("key", data2, (key) => { - cxt.setParams({ propertyName: key }); - cxt.subschema({ - keyword: "propertyNames", - data: key, - dataTypes: ["string"], - propertyName: key, - compositeRule: true - }, valid); - gen.if((0, codegen_1.not)(valid), () => { - cxt.error(true); - if (!it.allErrors) - gen.break(); - }); - }); - cxt.ok(valid); - } - }; - exports.default = def; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js -var require_additionalProperties = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - var code_1 = require_code2(); - var codegen_1 = require_codegen(); - var names_1 = require_names(); - var util_1 = require_util(); - var error50 = { - message: "must NOT have additional properties", - params: ({ params }) => (0, codegen_1._)`{additionalProperty: ${params.additionalProperty}}` - }; - var def = { - keyword: "additionalProperties", - type: ["object"], - schemaType: ["boolean", "object"], - allowUndefined: true, - trackErrors: true, - error: error50, - code(cxt) { - const { gen, schema: schema2, parentSchema, data: data2, errsCount, it } = cxt; - if (!errsCount) - throw new Error("ajv implementation error"); - const { allErrors, opts } = it; - it.props = true; - if (opts.removeAdditional !== "all" && (0, util_1.alwaysValidSchema)(it, schema2)) - return; - const props = (0, code_1.allSchemaProperties)(parentSchema.properties); - const patProps = (0, code_1.allSchemaProperties)(parentSchema.patternProperties); - checkAdditionalProperties(); - cxt.ok((0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); - function checkAdditionalProperties() { - gen.forIn("key", data2, (key) => { - if (!props.length && !patProps.length) - additionalPropertyCode(key); - else - gen.if(isAdditional(key), () => additionalPropertyCode(key)); - }); - } - function isAdditional(key) { - let definedProp; - if (props.length > 8) { - const propsSchema = (0, util_1.schemaRefOrVal)(it, parentSchema.properties, "properties"); - definedProp = (0, code_1.isOwnProperty)(gen, propsSchema, key); - } else if (props.length) { - definedProp = (0, codegen_1.or)(...props.map((p5) => (0, codegen_1._)`${key} === ${p5}`)); - } else { - definedProp = codegen_1.nil; - } - if (patProps.length) { - definedProp = (0, codegen_1.or)(definedProp, ...patProps.map((p5) => (0, codegen_1._)`${(0, code_1.usePattern)(cxt, p5)}.test(${key})`)); - } - return (0, codegen_1.not)(definedProp); - } - function deleteAdditional(key) { - gen.code((0, codegen_1._)`delete ${data2}[${key}]`); - } - function additionalPropertyCode(key) { - if (opts.removeAdditional === "all" || opts.removeAdditional && schema2 === false) { - deleteAdditional(key); - return; - } - if (schema2 === false) { - cxt.setParams({ additionalProperty: key }); - cxt.error(); - if (!allErrors) - gen.break(); - return; - } - if (typeof schema2 == "object" && !(0, util_1.alwaysValidSchema)(it, schema2)) { - const valid = gen.name("valid"); - if (opts.removeAdditional === "failing") { - applyAdditionalSchema(key, valid, false); - gen.if((0, codegen_1.not)(valid), () => { - cxt.reset(); - deleteAdditional(key); - }); - } else { - applyAdditionalSchema(key, valid); - if (!allErrors) - gen.if((0, codegen_1.not)(valid), () => gen.break()); - } - } - } - function applyAdditionalSchema(key, valid, errors) { - const subschema = { - keyword: "additionalProperties", - dataProp: key, - dataPropType: util_1.Type.Str - }; - if (errors === false) { - Object.assign(subschema, { - compositeRule: true, - createErrors: false, - allErrors: false - }); - } - cxt.subschema(subschema, valid); - } - } - }; - exports.default = def; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/properties.js -var require_properties = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/properties.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - var validate_1 = require_validate(); - var code_1 = require_code2(); - var util_1 = require_util(); - var additionalProperties_1 = require_additionalProperties(); - var def = { - keyword: "properties", - type: "object", - schemaType: "object", - code(cxt) { - const { gen, schema: schema2, parentSchema, data: data2, it } = cxt; - if (it.opts.removeAdditional === "all" && parentSchema.additionalProperties === void 0) { - additionalProperties_1.default.code(new validate_1.KeywordCxt(it, additionalProperties_1.default, "additionalProperties")); - } - const allProps = (0, code_1.allSchemaProperties)(schema2); - for (const prop of allProps) { - it.definedProperties.add(prop); - } - if (it.opts.unevaluated && allProps.length && it.props !== true) { - it.props = util_1.mergeEvaluated.props(gen, (0, util_1.toHash)(allProps), it.props); - } - const properties = allProps.filter((p5) => !(0, util_1.alwaysValidSchema)(it, schema2[p5])); - if (properties.length === 0) - return; - const valid = gen.name("valid"); - for (const prop of properties) { - if (hasDefault(prop)) { - applyPropertySchema(prop); - } else { - gen.if((0, code_1.propertyInData)(gen, data2, prop, it.opts.ownProperties)); - applyPropertySchema(prop); - if (!it.allErrors) - gen.else().var(valid, true); - gen.endIf(); - } - cxt.it.definedProperties.add(prop); - cxt.ok(valid); - } - function hasDefault(prop) { - return it.opts.useDefaults && !it.compositeRule && schema2[prop].default !== void 0; - } - function applyPropertySchema(prop) { - cxt.subschema({ - keyword: "properties", - schemaProp: prop, - dataProp: prop - }, valid); - } - } - }; - exports.default = def; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/patternProperties.js -var require_patternProperties = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/patternProperties.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - var code_1 = require_code2(); - var codegen_1 = require_codegen(); - var util_1 = require_util(); - var util_2 = require_util(); - var def = { - keyword: "patternProperties", - type: "object", - schemaType: "object", - code(cxt) { - const { gen, schema: schema2, data: data2, parentSchema, it } = cxt; - const { opts } = it; - const patterns = (0, code_1.allSchemaProperties)(schema2); - const alwaysValidPatterns = patterns.filter((p5) => (0, util_1.alwaysValidSchema)(it, schema2[p5])); - if (patterns.length === 0 || alwaysValidPatterns.length === patterns.length && (!it.opts.unevaluated || it.props === true)) { - return; - } - const checkProperties = opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties; - const valid = gen.name("valid"); - if (it.props !== true && !(it.props instanceof codegen_1.Name)) { - it.props = (0, util_2.evaluatedPropsToName)(gen, it.props); - } - const { props } = it; - validatePatternProperties(); - function validatePatternProperties() { - for (const pat of patterns) { - if (checkProperties) - checkMatchingProperties(pat); - if (it.allErrors) { - validateProperties(pat); - } else { - gen.var(valid, true); - validateProperties(pat); - gen.if(valid); - } - } - } - function checkMatchingProperties(pat) { - for (const prop in checkProperties) { - if (new RegExp(pat).test(prop)) { - (0, util_1.checkStrictMode)(it, `property ${prop} matches pattern ${pat} (use allowMatchingProperties)`); - } - } - } - function validateProperties(pat) { - gen.forIn("key", data2, (key) => { - gen.if((0, codegen_1._)`${(0, code_1.usePattern)(cxt, pat)}.test(${key})`, () => { - const alwaysValid = alwaysValidPatterns.includes(pat); - if (!alwaysValid) { - cxt.subschema({ - keyword: "patternProperties", - schemaProp: pat, - dataProp: key, - dataPropType: util_2.Type.Str - }, valid); - } - if (it.opts.unevaluated && props !== true) { - gen.assign((0, codegen_1._)`${props}[${key}]`, true); - } else if (!alwaysValid && !it.allErrors) { - gen.if((0, codegen_1.not)(valid), () => gen.break()); - } - }); - }); - } - } - }; - exports.default = def; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/not.js -var require_not = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/not.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - var util_1 = require_util(); - var def = { - keyword: "not", - schemaType: ["object", "boolean"], - trackErrors: true, - code(cxt) { - const { gen, schema: schema2, it } = cxt; - if ((0, util_1.alwaysValidSchema)(it, schema2)) { - cxt.fail(); - return; - } - const valid = gen.name("valid"); - cxt.subschema({ - keyword: "not", - compositeRule: true, - createErrors: false, - allErrors: false - }, valid); - cxt.failResult(valid, () => cxt.reset(), () => cxt.error()); - }, - error: { message: "must NOT be valid" } - }; - exports.default = def; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/anyOf.js -var require_anyOf = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/anyOf.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - var code_1 = require_code2(); - var def = { - keyword: "anyOf", - schemaType: "array", - trackErrors: true, - code: code_1.validateUnion, - error: { message: "must match a schema in anyOf" } - }; - exports.default = def; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/oneOf.js -var require_oneOf = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/oneOf.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - var codegen_1 = require_codegen(); - var util_1 = require_util(); - var error50 = { - message: "must match exactly one schema in oneOf", - params: ({ params }) => (0, codegen_1._)`{passingSchemas: ${params.passing}}` - }; - var def = { - keyword: "oneOf", - schemaType: "array", - trackErrors: true, - error: error50, - code(cxt) { - const { gen, schema: schema2, parentSchema, it } = cxt; - if (!Array.isArray(schema2)) - throw new Error("ajv implementation error"); - if (it.opts.discriminator && parentSchema.discriminator) - return; - const schArr = schema2; - const valid = gen.let("valid", false); - const passing = gen.let("passing", null); - const schValid = gen.name("_valid"); - cxt.setParams({ passing }); - gen.block(validateOneOf); - cxt.result(valid, () => cxt.reset(), () => cxt.error(true)); - function validateOneOf() { - schArr.forEach((sch, i5) => { - let schCxt; - if ((0, util_1.alwaysValidSchema)(it, sch)) { - gen.var(schValid, true); - } else { - schCxt = cxt.subschema({ - keyword: "oneOf", - schemaProp: i5, - compositeRule: true - }, schValid); - } - if (i5 > 0) { - gen.if((0, codegen_1._)`${schValid} && ${valid}`).assign(valid, false).assign(passing, (0, codegen_1._)`[${passing}, ${i5}]`).else(); - } - gen.if(schValid, () => { - gen.assign(valid, true); - gen.assign(passing, i5); - if (schCxt) - cxt.mergeEvaluated(schCxt, codegen_1.Name); - }); - }); - } - } - }; - exports.default = def; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/allOf.js -var require_allOf = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/allOf.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - var util_1 = require_util(); - var def = { - keyword: "allOf", - schemaType: "array", - code(cxt) { - const { gen, schema: schema2, it } = cxt; - if (!Array.isArray(schema2)) - throw new Error("ajv implementation error"); - const valid = gen.name("valid"); - schema2.forEach((sch, i5) => { - if ((0, util_1.alwaysValidSchema)(it, sch)) - return; - const schCxt = cxt.subschema({ keyword: "allOf", schemaProp: i5 }, valid); - cxt.ok(valid); - cxt.mergeEvaluated(schCxt); - }); - } - }; - exports.default = def; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/if.js -var require_if = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/if.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - var codegen_1 = require_codegen(); - var util_1 = require_util(); - var error50 = { - message: ({ params }) => (0, codegen_1.str)`must match "${params.ifClause}" schema`, - params: ({ params }) => (0, codegen_1._)`{failingKeyword: ${params.ifClause}}` - }; - var def = { - keyword: "if", - schemaType: ["object", "boolean"], - trackErrors: true, - error: error50, - code(cxt) { - const { gen, parentSchema, it } = cxt; - if (parentSchema.then === void 0 && parentSchema.else === void 0) { - (0, util_1.checkStrictMode)(it, '"if" without "then" and "else" is ignored'); - } - const hasThen = hasSchema(it, "then"); - const hasElse = hasSchema(it, "else"); - if (!hasThen && !hasElse) - return; - const valid = gen.let("valid", true); - const schValid = gen.name("_valid"); - validateIf(); - cxt.reset(); - if (hasThen && hasElse) { - const ifClause = gen.let("ifClause"); - cxt.setParams({ ifClause }); - gen.if(schValid, validateClause("then", ifClause), validateClause("else", ifClause)); - } else if (hasThen) { - gen.if(schValid, validateClause("then")); - } else { - gen.if((0, codegen_1.not)(schValid), validateClause("else")); - } - cxt.pass(valid, () => cxt.error(true)); - function validateIf() { - const schCxt = cxt.subschema({ - keyword: "if", - compositeRule: true, - createErrors: false, - allErrors: false - }, schValid); - cxt.mergeEvaluated(schCxt); - } - function validateClause(keyword, ifClause) { - return () => { - const schCxt = cxt.subschema({ keyword }, schValid); - gen.assign(valid, schValid); - cxt.mergeValidEvaluated(schCxt, valid); - if (ifClause) - gen.assign(ifClause, (0, codegen_1._)`${keyword}`); - else - cxt.setParams({ ifClause: keyword }); - }; - } - } - }; - function hasSchema(it, keyword) { - const schema2 = it.schema[keyword]; - return schema2 !== void 0 && !(0, util_1.alwaysValidSchema)(it, schema2); - } - exports.default = def; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/thenElse.js -var require_thenElse = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/thenElse.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - var util_1 = require_util(); - var def = { - keyword: ["then", "else"], - schemaType: ["object", "boolean"], - code({ keyword, parentSchema, it }) { - if (parentSchema.if === void 0) - (0, util_1.checkStrictMode)(it, `"${keyword}" without "if" is ignored`); - } - }; - exports.default = def; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/index.js -var require_applicator = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/index.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - var additionalItems_1 = require_additionalItems(); - var prefixItems_1 = require_prefixItems(); - var items_1 = require_items(); - var items2020_1 = require_items2020(); - var contains_1 = require_contains(); - var dependencies_1 = require_dependencies(); - var propertyNames_1 = require_propertyNames(); - var additionalProperties_1 = require_additionalProperties(); - var properties_1 = require_properties(); - var patternProperties_1 = require_patternProperties(); - var not_1 = require_not(); - var anyOf_1 = require_anyOf(); - var oneOf_1 = require_oneOf(); - var allOf_1 = require_allOf(); - var if_1 = require_if(); - var thenElse_1 = require_thenElse(); - function getApplicator(draft2020 = false) { - const applicator = [ - // any - not_1.default, - anyOf_1.default, - oneOf_1.default, - allOf_1.default, - if_1.default, - thenElse_1.default, - // object - propertyNames_1.default, - additionalProperties_1.default, - dependencies_1.default, - properties_1.default, - patternProperties_1.default - ]; - if (draft2020) - applicator.push(prefixItems_1.default, items2020_1.default); - else - applicator.push(additionalItems_1.default, items_1.default); - applicator.push(contains_1.default); - return applicator; - } - exports.default = getApplicator; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/format/format.js -var require_format = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/format/format.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - var codegen_1 = require_codegen(); - var error50 = { - message: ({ schemaCode }) => (0, codegen_1.str)`must match format "${schemaCode}"`, - params: ({ schemaCode }) => (0, codegen_1._)`{format: ${schemaCode}}` - }; - var def = { - keyword: "format", - type: ["number", "string"], - schemaType: "string", - $data: true, - error: error50, - code(cxt, ruleType) { - const { gen, data: data2, $data, schema: schema2, schemaCode, it } = cxt; - const { opts, errSchemaPath, schemaEnv, self: self2 } = it; - if (!opts.validateFormats) - return; - if ($data) - validate$DataFormat(); - else - validateFormat(); - function validate$DataFormat() { - const fmts = gen.scopeValue("formats", { - ref: self2.formats, - code: opts.code.formats - }); - const fDef = gen.const("fDef", (0, codegen_1._)`${fmts}[${schemaCode}]`); - const fType = gen.let("fType"); - const format2 = gen.let("format"); - gen.if((0, codegen_1._)`typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`, () => gen.assign(fType, (0, codegen_1._)`${fDef}.type || "string"`).assign(format2, (0, codegen_1._)`${fDef}.validate`), () => gen.assign(fType, (0, codegen_1._)`"string"`).assign(format2, fDef)); - cxt.fail$data((0, codegen_1.or)(unknownFmt(), invalidFmt())); - function unknownFmt() { - if (opts.strictSchema === false) - return codegen_1.nil; - return (0, codegen_1._)`${schemaCode} && !${format2}`; - } - function invalidFmt() { - const callFormat = schemaEnv.$async ? (0, codegen_1._)`(${fDef}.async ? await ${format2}(${data2}) : ${format2}(${data2}))` : (0, codegen_1._)`${format2}(${data2})`; - const validData = (0, codegen_1._)`(typeof ${format2} == "function" ? ${callFormat} : ${format2}.test(${data2}))`; - return (0, codegen_1._)`${format2} && ${format2} !== true && ${fType} === ${ruleType} && !${validData}`; - } - } - function validateFormat() { - const formatDef = self2.formats[schema2]; - if (!formatDef) { - unknownFormat(); - return; - } - if (formatDef === true) - return; - const [fmtType, format2, fmtRef] = getFormat(formatDef); - if (fmtType === ruleType) - cxt.pass(validCondition()); - function unknownFormat() { - if (opts.strictSchema === false) { - self2.logger.warn(unknownMsg()); - return; - } - throw new Error(unknownMsg()); - function unknownMsg() { - return `unknown format "${schema2}" ignored in schema at path "${errSchemaPath}"`; - } - } - function getFormat(fmtDef) { - const code = fmtDef instanceof RegExp ? (0, codegen_1.regexpCode)(fmtDef) : opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(schema2)}` : void 0; - const fmt = gen.scopeValue("formats", { key: schema2, ref: fmtDef, code }); - if (typeof fmtDef == "object" && !(fmtDef instanceof RegExp)) { - return [fmtDef.type || "string", fmtDef.validate, (0, codegen_1._)`${fmt}.validate`]; - } - return ["string", fmtDef, fmt]; - } - function validCondition() { - if (typeof formatDef == "object" && !(formatDef instanceof RegExp) && formatDef.async) { - if (!schemaEnv.$async) - throw new Error("async format in sync schema"); - return (0, codegen_1._)`await ${fmtRef}(${data2})`; - } - return typeof format2 == "function" ? (0, codegen_1._)`${fmtRef}(${data2})` : (0, codegen_1._)`${fmtRef}.test(${data2})`; - } - } - } - }; - exports.default = def; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/format/index.js -var require_format2 = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/format/index.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - var format_1 = require_format(); - var format2 = [format_1.default]; - exports.default = format2; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/metadata.js -var require_metadata = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/metadata.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.contentVocabulary = exports.metadataVocabulary = void 0; - exports.metadataVocabulary = [ - "title", - "description", - "default", - "deprecated", - "readOnly", - "writeOnly", - "examples" - ]; - exports.contentVocabulary = [ - "contentMediaType", - "contentEncoding", - "contentSchema" - ]; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/draft7.js -var require_draft7 = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/draft7.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - var core_1 = require_core2(); - var validation_1 = require_validation2(); - var applicator_1 = require_applicator(); - var format_1 = require_format2(); - var metadata_1 = require_metadata(); - var draft7Vocabularies = [ - core_1.default, - validation_1.default, - (0, applicator_1.default)(), - format_1.default, - metadata_1.metadataVocabulary, - metadata_1.contentVocabulary - ]; - exports.default = draft7Vocabularies; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/discriminator/types.js -var require_types = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/discriminator/types.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.DiscrError = void 0; - var DiscrError; - (function(DiscrError2) { - DiscrError2["Tag"] = "tag"; - DiscrError2["Mapping"] = "mapping"; - })(DiscrError || (exports.DiscrError = DiscrError = {})); - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/discriminator/index.js -var require_discriminator = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/discriminator/index.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - var codegen_1 = require_codegen(); - var types_1 = require_types(); - var compile_1 = require_compile(); - var ref_error_1 = require_ref_error(); - var util_1 = require_util(); - var error50 = { - message: ({ params: { discrError, tagName } }) => discrError === types_1.DiscrError.Tag ? `tag "${tagName}" must be string` : `value of tag "${tagName}" must be in oneOf`, - params: ({ params: { discrError, tag: tag3, tagName } }) => (0, codegen_1._)`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag3}}` - }; - var def = { - keyword: "discriminator", - type: "object", - schemaType: "object", - error: error50, - code(cxt) { - const { gen, data: data2, schema: schema2, parentSchema, it } = cxt; - const { oneOf } = parentSchema; - if (!it.opts.discriminator) { - throw new Error("discriminator: requires discriminator option"); - } - const tagName = schema2.propertyName; - if (typeof tagName != "string") - throw new Error("discriminator: requires propertyName"); - if (schema2.mapping) - throw new Error("discriminator: mapping is not supported"); - if (!oneOf) - throw new Error("discriminator: requires oneOf keyword"); - const valid = gen.let("valid", false); - const tag3 = gen.const("tag", (0, codegen_1._)`${data2}${(0, codegen_1.getProperty)(tagName)}`); - gen.if((0, codegen_1._)`typeof ${tag3} == "string"`, () => validateMapping(), () => cxt.error(false, { discrError: types_1.DiscrError.Tag, tag: tag3, tagName })); - cxt.ok(valid); - function validateMapping() { - const mapping = getMapping(); - gen.if(false); - for (const tagValue in mapping) { - gen.elseIf((0, codegen_1._)`${tag3} === ${tagValue}`); - gen.assign(valid, applyTagSchema(mapping[tagValue])); - } - gen.else(); - cxt.error(false, { discrError: types_1.DiscrError.Mapping, tag: tag3, tagName }); - gen.endIf(); - } - function applyTagSchema(schemaProp) { - const _valid = gen.name("valid"); - const schCxt = cxt.subschema({ keyword: "oneOf", schemaProp }, _valid); - cxt.mergeEvaluated(schCxt, codegen_1.Name); - return _valid; - } - function getMapping() { - var _a6; - const oneOfMapping = {}; - const topRequired = hasRequired(parentSchema); - let tagRequired = true; - for (let i5 = 0; i5 < oneOf.length; i5++) { - let sch = oneOf[i5]; - if ((sch === null || sch === void 0 ? void 0 : sch.$ref) && !(0, util_1.schemaHasRulesButRef)(sch, it.self.RULES)) { - const ref = sch.$ref; - sch = compile_1.resolveRef.call(it.self, it.schemaEnv.root, it.baseId, ref); - if (sch instanceof compile_1.SchemaEnv) - sch = sch.schema; - if (sch === void 0) - throw new ref_error_1.default(it.opts.uriResolver, it.baseId, ref); - } - const propSch = (_a6 = sch === null || sch === void 0 ? void 0 : sch.properties) === null || _a6 === void 0 ? void 0 : _a6[tagName]; - if (typeof propSch != "object") { - throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${tagName}"`); - } - tagRequired = tagRequired && (topRequired || hasRequired(sch)); - addMappings(propSch, i5); - } - if (!tagRequired) - throw new Error(`discriminator: "${tagName}" must be required`); - return oneOfMapping; - function hasRequired({ required: required2 }) { - return Array.isArray(required2) && required2.includes(tagName); - } - function addMappings(sch, i5) { - if (sch.const) { - addMapping(sch.const, i5); - } else if (sch.enum) { - for (const tagValue of sch.enum) { - addMapping(tagValue, i5); - } - } else { - throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`); - } - } - function addMapping(tagValue, i5) { - if (typeof tagValue != "string" || tagValue in oneOfMapping) { - throw new Error(`discriminator: "${tagName}" values must be unique strings`); - } - oneOfMapping[tagValue] = i5; - } - } - } - }; - exports.default = def; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-draft-07.json -var require_json_schema_draft_07 = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-draft-07.json"(exports, module) { - module.exports = { - $schema: "http://json-schema.org/draft-07/schema#", - $id: "http://json-schema.org/draft-07/schema#", - title: "Core schema meta-schema", - definitions: { - schemaArray: { - type: "array", - minItems: 1, - items: { $ref: "#" } - }, - nonNegativeInteger: { - type: "integer", - minimum: 0 - }, - nonNegativeIntegerDefault0: { - allOf: [{ $ref: "#/definitions/nonNegativeInteger" }, { default: 0 }] - }, - simpleTypes: { - enum: ["array", "boolean", "integer", "null", "number", "object", "string"] - }, - stringArray: { - type: "array", - items: { type: "string" }, - uniqueItems: true, - default: [] - } - }, - type: ["object", "boolean"], - properties: { - $id: { - type: "string", - format: "uri-reference" - }, - $schema: { - type: "string", - format: "uri" - }, - $ref: { - type: "string", - format: "uri-reference" - }, - $comment: { - type: "string" - }, - title: { - type: "string" - }, - description: { - type: "string" - }, - default: true, - readOnly: { - type: "boolean", - default: false - }, - examples: { - type: "array", - items: true - }, - multipleOf: { - type: "number", - exclusiveMinimum: 0 - }, - maximum: { - type: "number" - }, - exclusiveMaximum: { - type: "number" - }, - minimum: { - type: "number" - }, - exclusiveMinimum: { - type: "number" - }, - maxLength: { $ref: "#/definitions/nonNegativeInteger" }, - minLength: { $ref: "#/definitions/nonNegativeIntegerDefault0" }, - pattern: { - type: "string", - format: "regex" - }, - additionalItems: { $ref: "#" }, - items: { - anyOf: [{ $ref: "#" }, { $ref: "#/definitions/schemaArray" }], - default: true - }, - maxItems: { $ref: "#/definitions/nonNegativeInteger" }, - minItems: { $ref: "#/definitions/nonNegativeIntegerDefault0" }, - uniqueItems: { - type: "boolean", - default: false - }, - contains: { $ref: "#" }, - maxProperties: { $ref: "#/definitions/nonNegativeInteger" }, - minProperties: { $ref: "#/definitions/nonNegativeIntegerDefault0" }, - required: { $ref: "#/definitions/stringArray" }, - additionalProperties: { $ref: "#" }, - definitions: { - type: "object", - additionalProperties: { $ref: "#" }, - default: {} - }, - properties: { - type: "object", - additionalProperties: { $ref: "#" }, - default: {} - }, - patternProperties: { - type: "object", - additionalProperties: { $ref: "#" }, - propertyNames: { format: "regex" }, - default: {} - }, - dependencies: { - type: "object", - additionalProperties: { - anyOf: [{ $ref: "#" }, { $ref: "#/definitions/stringArray" }] - } - }, - propertyNames: { $ref: "#" }, - const: true, - enum: { - type: "array", - items: true, - minItems: 1, - uniqueItems: true - }, - type: { - anyOf: [ - { $ref: "#/definitions/simpleTypes" }, - { - type: "array", - items: { $ref: "#/definitions/simpleTypes" }, - minItems: 1, - uniqueItems: true - } - ] - }, - format: { type: "string" }, - contentMediaType: { type: "string" }, - contentEncoding: { type: "string" }, - if: { $ref: "#" }, - then: { $ref: "#" }, - else: { $ref: "#" }, - allOf: { $ref: "#/definitions/schemaArray" }, - anyOf: { $ref: "#/definitions/schemaArray" }, - oneOf: { $ref: "#/definitions/schemaArray" }, - not: { $ref: "#" } - }, - default: true - }; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/ajv.js -var require_ajv = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/ajv.js"(exports, module) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv = void 0; - var core_1 = require_core(); - var draft7_1 = require_draft7(); - var discriminator_1 = require_discriminator(); - var draft7MetaSchema = require_json_schema_draft_07(); - var META_SUPPORT_DATA = ["/properties"]; - var META_SCHEMA_ID = "http://json-schema.org/draft-07/schema"; - var Ajv2 = class extends core_1.default { - _addVocabularies() { - super._addVocabularies(); - draft7_1.default.forEach((v5) => this.addVocabulary(v5)); - if (this.opts.discriminator) - this.addKeyword(discriminator_1.default); - } - _addDefaultMetaSchema() { - super._addDefaultMetaSchema(); - if (!this.opts.meta) - return; - const metaSchema = this.opts.$data ? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA) : draft7MetaSchema; - this.addMetaSchema(metaSchema, META_SCHEMA_ID, false); - this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID; - } - defaultMeta() { - return this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : void 0); - } - }; - exports.Ajv = Ajv2; - module.exports = exports = Ajv2; - module.exports.Ajv = Ajv2; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.default = Ajv2; - var validate_1 = require_validate(); - Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function() { - return validate_1.KeywordCxt; - } }); - var codegen_1 = require_codegen(); - Object.defineProperty(exports, "_", { enumerable: true, get: function() { - return codegen_1._; - } }); - Object.defineProperty(exports, "str", { enumerable: true, get: function() { - return codegen_1.str; - } }); - Object.defineProperty(exports, "stringify", { enumerable: true, get: function() { - return codegen_1.stringify; - } }); - Object.defineProperty(exports, "nil", { enumerable: true, get: function() { - return codegen_1.nil; - } }); - Object.defineProperty(exports, "Name", { enumerable: true, get: function() { - return codegen_1.Name; - } }); - Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function() { - return codegen_1.CodeGen; - } }); - var validation_error_1 = require_validation_error(); - Object.defineProperty(exports, "ValidationError", { enumerable: true, get: function() { - return validation_error_1.default; - } }); - var ref_error_1 = require_ref_error(); - Object.defineProperty(exports, "MissingRefError", { enumerable: true, get: function() { - return ref_error_1.default; - } }); - } -}); - -// node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.18.0/node_modules/ajv-formats/dist/formats.js -var require_formats2 = __commonJS({ - "node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.18.0/node_modules/ajv-formats/dist/formats.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.formatNames = exports.fastFormats = exports.fullFormats = void 0; - function fmtDef(validate2, compare) { - return { validate: validate2, compare }; - } - exports.fullFormats = { - // date: http://tools.ietf.org/html/rfc3339#section-5.6 - date: fmtDef(date7, compareDate), - // date-time: http://tools.ietf.org/html/rfc3339#section-5.6 - time: fmtDef(getTime(true), compareTime), - "date-time": fmtDef(getDateTime(true), compareDateTime), - "iso-time": fmtDef(getTime(), compareIsoTime), - "iso-date-time": fmtDef(getDateTime(), compareIsoDateTime), - // duration: https://tools.ietf.org/html/rfc3339#appendix-A - duration: /^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/, - uri, - "uri-reference": /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i, - // uri-template: https://tools.ietf.org/html/rfc6570 - "uri-template": /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i, - // For the source: https://gist.github.com/dperini/729294 - // For test cases: https://mathiasbynens.be/demo/url-regex - url: /^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu, - email: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i, - hostname: /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i, - // optimized https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html - ipv4: /^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/, - ipv6: /^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i, - regex, - // uuid: http://tools.ietf.org/html/rfc4122 - uuid: /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i, - // JSON-pointer: https://tools.ietf.org/html/rfc6901 - // uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A - "json-pointer": /^(?:\/(?:[^~/]|~0|~1)*)*$/, - "json-pointer-uri-fragment": /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i, - // relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00 - "relative-json-pointer": /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/, - // the following formats are used by the openapi specification: https://spec.openapis.org/oas/v3.0.0#data-types - // byte: https://github.com/miguelmota/is-base64 - byte, - // signed 32 bit integer - int32: { type: "number", validate: validateInt32 }, - // signed 64 bit integer - int64: { type: "number", validate: validateInt64 }, - // C-type float - float: { type: "number", validate: validateNumber }, - // C-type double - double: { type: "number", validate: validateNumber }, - // hint to the UI to hide input strings - password: true, - // unchecked string payload - binary: true - }; - exports.fastFormats = { - ...exports.fullFormats, - date: fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d$/, compareDate), - time: fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareTime), - "date-time": fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareDateTime), - "iso-time": fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, compareIsoTime), - "iso-date-time": fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, compareIsoDateTime), - // uri: https://github.com/mafintosh/is-my-json-valid/blob/master/formats.js - uri: /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i, - "uri-reference": /^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i, - // email (sources from jsen validator): - // http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address#answer-8829363 - // http://www.w3.org/TR/html5/forms.html#valid-e-mail-address (search for 'wilful violation') - email: /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i - }; - exports.formatNames = Object.keys(exports.fullFormats); - function isLeapYear2(year3) { - return year3 % 4 === 0 && (year3 % 100 !== 0 || year3 % 400 === 0); - } - var DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/; - var DAYS2 = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; - function date7(str) { - const matches = DATE.exec(str); - if (!matches) - return false; - const year3 = +matches[1]; - const month = +matches[2]; - const day2 = +matches[3]; - return month >= 1 && month <= 12 && day2 >= 1 && day2 <= (month === 2 && isLeapYear2(year3) ? 29 : DAYS2[month]); - } - function compareDate(d1, d22) { - if (!(d1 && d22)) - return void 0; - if (d1 > d22) - return 1; - if (d1 < d22) - return -1; - return 0; - } - var TIME = /^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i; - function getTime(strictTimeZone) { - return function time5(str) { - const matches = TIME.exec(str); - if (!matches) - return false; - const hr = +matches[1]; - const min = +matches[2]; - const sec2 = +matches[3]; - const tz = matches[4]; - const tzSign = matches[5] === "-" ? -1 : 1; - const tzH = +(matches[6] || 0); - const tzM = +(matches[7] || 0); - if (tzH > 23 || tzM > 59 || strictTimeZone && !tz) - return false; - if (hr <= 23 && min <= 59 && sec2 < 60) - return true; - const utcMin = min - tzM * tzSign; - const utcHr = hr - tzH * tzSign - (utcMin < 0 ? 1 : 0); - return (utcHr === 23 || utcHr === -1) && (utcMin === 59 || utcMin === -1) && sec2 < 61; - }; - } - function compareTime(s1, s22) { - if (!(s1 && s22)) - return void 0; - const t1 = (/* @__PURE__ */ new Date("2020-01-01T" + s1)).valueOf(); - const t22 = (/* @__PURE__ */ new Date("2020-01-01T" + s22)).valueOf(); - if (!(t1 && t22)) - return void 0; - return t1 - t22; - } - function compareIsoTime(t1, t22) { - if (!(t1 && t22)) - return void 0; - const a1 = TIME.exec(t1); - const a22 = TIME.exec(t22); - if (!(a1 && a22)) - return void 0; - t1 = a1[1] + a1[2] + a1[3]; - t22 = a22[1] + a22[2] + a22[3]; - if (t1 > t22) - return 1; - if (t1 < t22) - return -1; - return 0; - } - var DATE_TIME_SEPARATOR = /t|\s/i; - function getDateTime(strictTimeZone) { - const time5 = getTime(strictTimeZone); - return function date_time(str) { - const dateTime = str.split(DATE_TIME_SEPARATOR); - return dateTime.length === 2 && date7(dateTime[0]) && time5(dateTime[1]); - }; - } - function compareDateTime(dt1, dt2) { - if (!(dt1 && dt2)) - return void 0; - const d1 = new Date(dt1).valueOf(); - const d22 = new Date(dt2).valueOf(); - if (!(d1 && d22)) - return void 0; - return d1 - d22; - } - function compareIsoDateTime(dt1, dt2) { - if (!(dt1 && dt2)) - return void 0; - const [d1, t1] = dt1.split(DATE_TIME_SEPARATOR); - const [d22, t22] = dt2.split(DATE_TIME_SEPARATOR); - const res = compareDate(d1, d22); - if (res === void 0) - return void 0; - return res || compareTime(t1, t22); - } - var NOT_URI_FRAGMENT = /\/|:/; - var URI = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; - function uri(str) { - return NOT_URI_FRAGMENT.test(str) && URI.test(str); - } - var BYTE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm; - function byte(str) { - BYTE.lastIndex = 0; - return BYTE.test(str); - } - var MIN_INT32 = -(2 ** 31); - var MAX_INT322 = 2 ** 31 - 1; - function validateInt32(value) { - return Number.isInteger(value) && value <= MAX_INT322 && value >= MIN_INT32; - } - function validateInt64(value) { - return Number.isInteger(value); - } - function validateNumber() { - return true; - } - var Z_ANCHOR = /[^\\]\\Z/; - function regex(str) { - if (Z_ANCHOR.test(str)) - return false; - try { - new RegExp(str); - return true; - } catch (e5) { - return false; - } - } - } -}); - -// node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.18.0/node_modules/ajv-formats/dist/limit.js -var require_limit = __commonJS({ - "node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.18.0/node_modules/ajv-formats/dist/limit.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.formatLimitDefinition = void 0; - var ajv_1 = require_ajv(); - var codegen_1 = require_codegen(); - var ops = codegen_1.operators; - var KWDs = { - formatMaximum: { okStr: "<=", ok: ops.LTE, fail: ops.GT }, - formatMinimum: { okStr: ">=", ok: ops.GTE, fail: ops.LT }, - formatExclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE }, - formatExclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE } - }; - var error50 = { - message: ({ keyword, schemaCode }) => (0, codegen_1.str)`should be ${KWDs[keyword].okStr} ${schemaCode}`, - params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}` - }; - exports.formatLimitDefinition = { - keyword: Object.keys(KWDs), - type: "string", - schemaType: "string", - $data: true, - error: error50, - code(cxt) { - const { gen, data: data2, schemaCode, keyword, it } = cxt; - const { opts, self: self2 } = it; - if (!opts.validateFormats) - return; - const fCxt = new ajv_1.KeywordCxt(it, self2.RULES.all.format.definition, "format"); - if (fCxt.$data) - validate$DataFormat(); - else - validateFormat(); - function validate$DataFormat() { - const fmts = gen.scopeValue("formats", { - ref: self2.formats, - code: opts.code.formats - }); - const fmt = gen.const("fmt", (0, codegen_1._)`${fmts}[${fCxt.schemaCode}]`); - cxt.fail$data((0, codegen_1.or)((0, codegen_1._)`typeof ${fmt} != "object"`, (0, codegen_1._)`${fmt} instanceof RegExp`, (0, codegen_1._)`typeof ${fmt}.compare != "function"`, compareCode(fmt))); - } - function validateFormat() { - const format2 = fCxt.schema; - const fmtDef = self2.formats[format2]; - if (!fmtDef || fmtDef === true) - return; - if (typeof fmtDef != "object" || fmtDef instanceof RegExp || typeof fmtDef.compare != "function") { - throw new Error(`"${keyword}": format "${format2}" does not define "compare" function`); - } - const fmt = gen.scopeValue("formats", { - key: format2, - ref: fmtDef, - code: opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(format2)}` : void 0 - }); - cxt.fail$data(compareCode(fmt)); - } - function compareCode(fmt) { - return (0, codegen_1._)`${fmt}.compare(${data2}, ${schemaCode}) ${KWDs[keyword].fail} 0`; - } - }, - dependencies: ["format"] - }; - var formatLimitPlugin = (ajv) => { - ajv.addKeyword(exports.formatLimitDefinition); - return ajv; - }; - exports.default = formatLimitPlugin; - } -}); - -// node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.18.0/node_modules/ajv-formats/dist/index.js -var require_dist2 = __commonJS({ - "node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.18.0/node_modules/ajv-formats/dist/index.js"(exports, module) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - var formats_1 = require_formats2(); - var limit_1 = require_limit(); - var codegen_1 = require_codegen(); - var fullName = new codegen_1.Name("fullFormats"); - var fastName = new codegen_1.Name("fastFormats"); - var formatsPlugin = (ajv, opts = { keywords: true }) => { - if (Array.isArray(opts)) { - addFormats2(ajv, opts, formats_1.fullFormats, fullName); - return ajv; - } - const [formats, exportName] = opts.mode === "fast" ? [formats_1.fastFormats, fastName] : [formats_1.fullFormats, fullName]; - const list2 = opts.formats || formats_1.formatNames; - addFormats2(ajv, list2, formats, exportName); - if (opts.keywords) - (0, limit_1.default)(ajv); - return ajv; - }; - formatsPlugin.get = (name, mode = "full") => { - const formats = mode === "fast" ? formats_1.fastFormats : formats_1.fullFormats; - const f5 = formats[name]; - if (!f5) - throw new Error(`Unknown format "${name}"`); - return f5; - }; - function addFormats2(ajv, list2, fs41, exportName) { - var _a6; - var _b; - (_a6 = (_b = ajv.opts.code).formats) !== null && _a6 !== void 0 ? _a6 : _b.formats = (0, codegen_1._)`require("ajv-formats/dist/formats").${exportName}`; - for (const f5 of list2) - ajv.addFormat(f5, fs41[f5]); - } - module.exports = exports = formatsPlugin; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.default = formatsPlugin; - } -}); - -// node_modules/.pnpm/@better-auth+utils@0.3.0/node_modules/@better-auth/utils/dist/random.mjs -function expandAlphabet(alphabet) { - switch (alphabet) { - case "a-z": - return "abcdefghijklmnopqrstuvwxyz"; - case "A-Z": - return "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; - case "0-9": - return "0123456789"; - case "-_": - return "-_"; - default: - throw new Error(`Unsupported alphabet: ${alphabet}`); - } -} -function createRandomStringGenerator(...baseAlphabets) { - const baseCharSet = baseAlphabets.map(expandAlphabet).join(""); - if (baseCharSet.length === 0) { - throw new Error( - "No valid characters provided for random string generation." - ); - } - const baseCharSetLength = baseCharSet.length; - return (length, ...alphabets) => { - if (length <= 0) { - throw new Error("Length must be a positive integer."); - } - let charSet = baseCharSet; - let charSetLength = baseCharSetLength; - if (alphabets.length > 0) { - charSet = alphabets.map(expandAlphabet).join(""); - charSetLength = charSet.length; - } - const maxValid = Math.floor(256 / charSetLength) * charSetLength; - const buf = new Uint8Array(length * 2); - const bufLength = buf.length; - let result = ""; - let bufIndex = bufLength; - let rand; - while (result.length < length) { - if (bufIndex >= bufLength) { - crypto.getRandomValues(buf); - bufIndex = 0; - } - rand = buf[bufIndex++]; - if (rand < maxValid) { - result += charSet[rand % charSetLength]; - } - } - return result; - }; -} -var init_random = __esm({ - "node_modules/.pnpm/@better-auth+utils@0.3.0/node_modules/@better-auth/utils/dist/random.mjs"() { - } -}); - -// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/crypto/random.mjs -var generateRandomString; -var init_random2 = __esm({ - "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/crypto/random.mjs"() { - init_random(); - generateRandomString = createRandomStringGenerator("a-z", "0-9", "A-Z", "-_"); - } -}); - -// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/crypto/buffer.mjs -function constantTimeEqual(a5, b6) { - if (typeof a5 === "string") a5 = new TextEncoder().encode(a5); - if (typeof b6 === "string") b6 = new TextEncoder().encode(b6); - const aBuffer = new Uint8Array(a5); - const bBuffer = new Uint8Array(b6); - let c5 = aBuffer.length ^ bBuffer.length; - const length = Math.max(aBuffer.length, bBuffer.length); - for (let i5 = 0; i5 < length; i5++) c5 |= (i5 < aBuffer.length ? aBuffer[i5] : 0) ^ (i5 < bBuffer.length ? bBuffer[i5] : 0); - return c5 === 0; -} -var init_buffer = __esm({ - "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/crypto/buffer.mjs"() { - } -}); - -// node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/utils.js -function isBytes(a5) { - return a5 instanceof Uint8Array || ArrayBuffer.isView(a5) && a5.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a5 && a5.BYTES_PER_ELEMENT === 1; -} -function anumber(n5, title = "") { - if (typeof n5 !== "number") { - const prefix = title && `"${title}" `; - throw new TypeError(`${prefix}expected number, got ${typeof n5}`); - } - if (!Number.isSafeInteger(n5) || n5 < 0) { - const prefix = title && `"${title}" `; - throw new RangeError(`${prefix}expected integer >= 0, got ${n5}`); - } -} -function abytes(value, length, title = "") { - const bytes = isBytes(value); - const len = value?.length; - const needsLen = length !== void 0; - if (!bytes || needsLen && len !== length) { - const prefix = title && `"${title}" `; - const ofLen = needsLen ? ` of length ${length}` : ""; - const got = bytes ? `length=${len}` : `type=${typeof value}`; - const message2 = prefix + "expected Uint8Array" + ofLen + ", got " + got; - if (!bytes) - throw new TypeError(message2); - throw new RangeError(message2); - } - return value; -} -function ahash(h5) { - if (typeof h5 !== "function" || typeof h5.create !== "function") - throw new TypeError("Hash must wrapped by utils.createHasher"); - anumber(h5.outputLen); - anumber(h5.blockLen); - if (h5.outputLen < 1) - throw new Error('"outputLen" must be >= 1'); - if (h5.blockLen < 1) - throw new Error('"blockLen" must be >= 1'); -} -function aexists(instance, checkFinished = true) { - if (instance.destroyed) - throw new Error("Hash instance has been destroyed"); - if (checkFinished && instance.finished) - throw new Error("Hash#digest() has already been called"); -} -function aoutput(out, instance) { - abytes(out, void 0, "digestInto() output"); - const min = instance.outputLen; - if (out.length < min) { - throw new RangeError('"digestInto() output" expected to be of length >=' + min); - } -} -function u32(arr) { - return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); -} -function clean(...arrays) { - for (let i5 = 0; i5 < arrays.length; i5++) { - arrays[i5].fill(0); - } -} -function createView(arr) { - return new DataView(arr.buffer, arr.byteOffset, arr.byteLength); -} -function rotr(word, shift) { - return word << 32 - shift | word >>> shift; -} -function rotl(word, shift) { - return word << shift | word >>> 32 - shift >>> 0; -} -function byteSwap(word) { - return word << 24 & 4278190080 | word << 8 & 16711680 | word >>> 8 & 65280 | word >>> 24 & 255; -} -function byteSwap32(arr) { - for (let i5 = 0; i5 < arr.length; i5++) { - arr[i5] = byteSwap(arr[i5]); - } - return arr; -} -function asciiToBase16(ch) { - if (ch >= asciis._0 && ch <= asciis._9) - return ch - asciis._0; - if (ch >= asciis.A && ch <= asciis.F) - return ch - (asciis.A - 10); - if (ch >= asciis.a && ch <= asciis.f) - return ch - (asciis.a - 10); - return; -} -function hexToBytes2(hex4) { - if (typeof hex4 !== "string") - throw new TypeError("hex string expected, got " + typeof hex4); - if (hasHexBuiltin) { - try { - return Uint8Array.fromHex(hex4); - } catch (error50) { - if (error50 instanceof SyntaxError) - throw new RangeError(error50.message); - throw error50; - } - } - const hl = hex4.length; - const al = hl / 2; - if (hl % 2) - throw new RangeError("hex string expected, got unpadded hex of length " + hl); - const array2 = new Uint8Array(al); - for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) { - const n1 = asciiToBase16(hex4.charCodeAt(hi)); - const n22 = asciiToBase16(hex4.charCodeAt(hi + 1)); - if (n1 === void 0 || n22 === void 0) { - const char2 = hex4[hi] + hex4[hi + 1]; - throw new RangeError('hex string expected, got non-hex character "' + char2 + '" at index ' + hi); - } - array2[ai] = n1 * 16 + n22; - } - return array2; -} -async function asyncLoop(iters, tick, cb) { - let ts = Date.now(); - for (let i5 = 0; i5 < iters; i5++) { - cb(i5); - const diff = Date.now() - ts; - if (diff >= 0 && diff < tick) - continue; - await nextTick(); - ts += diff; - } -} -function utf8ToBytes(str) { - if (typeof str !== "string") - throw new TypeError("string expected"); - return new Uint8Array(new TextEncoder().encode(str)); -} -function kdfInputToBytes(data2, errorTitle = "") { - if (typeof data2 === "string") - return utf8ToBytes(data2); - return abytes(data2, void 0, errorTitle); -} -function checkOpts(defaults, opts) { - if (opts !== void 0 && {}.toString.call(opts) !== "[object Object]") - throw new TypeError("options must be object or undefined"); - const merged = Object.assign(defaults, opts); - return merged; -} -function createHasher(hashCons, info2 = {}) { - const hashC = (msg, opts) => hashCons(opts).update(msg).digest(); - const tmp = hashCons(void 0); - hashC.outputLen = tmp.outputLen; - hashC.blockLen = tmp.blockLen; - hashC.canXOF = tmp.canXOF; - hashC.create = (opts) => hashCons(opts); - Object.assign(hashC, info2); - return Object.freeze(hashC); -} -var isLE, swap32IfBE, hasHexBuiltin, asciis, nextTick, oidNist; -var init_utils6 = __esm({ - "node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/utils.js"() { - isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)(); - swap32IfBE = isLE ? (u5) => u5 : byteSwap32; - hasHexBuiltin = /* @__PURE__ */ (() => ( - // @ts-ignore - typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function" - ))(); - asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 }; - nextTick = async () => { - }; - oidNist = (suffix) => ({ - // Current NIST hashAlgs suffixes used here fit in one DER subidentifier octet. - // Larger suffix values would need base-128 OID encoding and a different length byte. - oid: Uint8Array.from([6, 9, 96, 134, 72, 1, 101, 3, 4, 2, suffix]) - }); - } -}); - -// node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/hmac.js -var _HMAC, hmac2; -var init_hmac = __esm({ - "node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/hmac.js"() { - init_utils6(); - _HMAC = class { - oHash; - iHash; - blockLen; - outputLen; - canXOF = false; - finished = false; - destroyed = false; - constructor(hash2, key) { - ahash(hash2); - abytes(key, void 0, "key"); - this.iHash = hash2.create(); - if (typeof this.iHash.update !== "function") - throw new Error("Expected instance of class which extends utils.Hash"); - this.blockLen = this.iHash.blockLen; - this.outputLen = this.iHash.outputLen; - const blockLen = this.blockLen; - const pad = new Uint8Array(blockLen); - pad.set(key.length > blockLen ? hash2.create().update(key).digest() : key); - for (let i5 = 0; i5 < pad.length; i5++) - pad[i5] ^= 54; - this.iHash.update(pad); - this.oHash = hash2.create(); - for (let i5 = 0; i5 < pad.length; i5++) - pad[i5] ^= 54 ^ 92; - this.oHash.update(pad); - clean(pad); - } - update(buf) { - aexists(this); - this.iHash.update(buf); - return this; - } - digestInto(out) { - aexists(this); - aoutput(out, this); - this.finished = true; - const buf = out.subarray(0, this.outputLen); - this.iHash.digestInto(buf); - this.oHash.update(buf); - this.oHash.digestInto(buf); - this.destroy(); - } - digest() { - const out = new Uint8Array(this.oHash.outputLen); - this.digestInto(out); - return out; - } - _cloneInto(to) { - to ||= Object.create(Object.getPrototypeOf(this), {}); - const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this; - to = to; - to.finished = finished; - to.destroyed = destroyed; - to.blockLen = blockLen; - to.outputLen = outputLen; - to.oHash = oHash._cloneInto(to.oHash); - to.iHash = iHash._cloneInto(to.iHash); - return to; - } - clone() { - return this._cloneInto(); - } - destroy() { - this.destroyed = true; - this.oHash.destroy(); - this.iHash.destroy(); - } - }; - hmac2 = /* @__PURE__ */ (() => { - const hmac_ = ((hash2, key, message2) => new _HMAC(hash2, key).update(message2).digest()); - hmac_.create = (hash2, key) => new _HMAC(hash2, key); - return hmac_; - })(); - } -}); - -// node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/hkdf.js -function extract(hash2, ikm, salt) { - ahash(hash2); - if (salt === void 0) - salt = new Uint8Array(hash2.outputLen); - return hmac2(hash2, salt, ikm); -} -function expand(hash2, prk, info2, length = 32) { - ahash(hash2); - anumber(length, "length"); - abytes(prk, void 0, "prk"); - const olen = hash2.outputLen; - if (prk.length < olen) - throw new Error('"prk" must be at least HashLen octets'); - if (length > 255 * olen) - throw new Error("Length must be <= 255*HashLen"); - const blocks = Math.ceil(length / olen); - if (info2 === void 0) - info2 = EMPTY_BUFFER; - else - abytes(info2, void 0, "info"); - const okm = new Uint8Array(blocks * olen); - const HMAC = hmac2.create(hash2, prk); - const HMACTmp = HMAC._cloneInto(); - const T = new Uint8Array(HMAC.outputLen); - for (let counter = 0; counter < blocks; counter++) { - HKDF_COUNTER[0] = counter + 1; - HMACTmp.update(counter === 0 ? EMPTY_BUFFER : T).update(info2).update(HKDF_COUNTER).digestInto(T); - okm.set(T, olen * counter); - HMAC._cloneInto(HMACTmp); - } - HMAC.destroy(); - HMACTmp.destroy(); - clean(T, HKDF_COUNTER); - return okm.slice(0, length); -} -var HKDF_COUNTER, EMPTY_BUFFER, hkdf; -var init_hkdf = __esm({ - "node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/hkdf.js"() { - init_hmac(); - init_utils6(); - HKDF_COUNTER = /* @__PURE__ */ Uint8Array.of(0); - EMPTY_BUFFER = /* @__PURE__ */ Uint8Array.of(); - hkdf = (hash2, ikm, salt, info2, length) => expand(hash2, extract(hash2, ikm, salt), info2, length); - } -}); - -// node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/_md.js -function Chi(a5, b6, c5) { - return a5 & b6 ^ ~a5 & c5; -} -function Maj(a5, b6, c5) { - return a5 & b6 ^ a5 & c5 ^ b6 & c5; -} -var HashMD, SHA256_IV; -var init_md = __esm({ - "node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/_md.js"() { - init_utils6(); - HashMD = class { - blockLen; - outputLen; - canXOF = false; - padOffset; - isLE; - // For partial updates less than block size - buffer; - view; - finished = false; - length = 0; - pos = 0; - destroyed = false; - constructor(blockLen, outputLen, padOffset, isLE3) { - this.blockLen = blockLen; - this.outputLen = outputLen; - this.padOffset = padOffset; - this.isLE = isLE3; - this.buffer = new Uint8Array(blockLen); - this.view = createView(this.buffer); - } - update(data2) { - aexists(this); - abytes(data2); - const { view, buffer: buffer2, blockLen } = this; - const len = data2.length; - for (let pos = 0; pos < len; ) { - const take = Math.min(blockLen - this.pos, len - pos); - if (take === blockLen) { - const dataView3 = createView(data2); - for (; blockLen <= len - pos; pos += blockLen) - this.process(dataView3, pos); - continue; - } - buffer2.set(data2.subarray(pos, pos + take), this.pos); - this.pos += take; - pos += take; - if (this.pos === blockLen) { - this.process(view, 0); - this.pos = 0; - } - } - this.length += data2.length; - this.roundClean(); - return this; - } - digestInto(out) { - aexists(this); - aoutput(out, this); - this.finished = true; - const { buffer: buffer2, view, blockLen, isLE: isLE3 } = this; - let { pos } = this; - buffer2[pos++] = 128; - clean(this.buffer.subarray(pos)); - if (this.padOffset > blockLen - pos) { - this.process(view, 0); - pos = 0; - } - for (let i5 = pos; i5 < blockLen; i5++) - buffer2[i5] = 0; - view.setBigUint64(blockLen - 8, BigInt(this.length * 8), isLE3); - this.process(view, 0); - const oview = createView(out); - const len = this.outputLen; - if (len % 4) - throw new Error("_sha2: outputLen must be aligned to 32bit"); - const outLen = len / 4; - const state2 = this.get(); - if (outLen > state2.length) - throw new Error("_sha2: outputLen bigger than state"); - for (let i5 = 0; i5 < outLen; i5++) - oview.setUint32(4 * i5, state2[i5], isLE3); - } - digest() { - const { buffer: buffer2, outputLen } = this; - this.digestInto(buffer2); - const res = buffer2.slice(0, outputLen); - this.destroy(); - return res; - } - _cloneInto(to) { - to ||= new this.constructor(); - to.set(...this.get()); - const { blockLen, buffer: buffer2, length, finished, destroyed, pos } = this; - to.destroyed = destroyed; - to.finished = finished; - to.length = length; - to.pos = pos; - if (length % blockLen) - to.buffer.set(buffer2); - return to; - } - clone() { - return this._cloneInto(); - } - }; - SHA256_IV = /* @__PURE__ */ Uint32Array.from([ - 1779033703, - 3144134277, - 1013904242, - 2773480762, - 1359893119, - 2600822924, - 528734635, - 1541459225 - ]); - } -}); - -// node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/sha2.js -var SHA256_K, SHA256_W, SHA2_32B, _SHA256, sha2562; -var init_sha2 = __esm({ - "node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/sha2.js"() { - init_md(); - init_utils6(); - SHA256_K = /* @__PURE__ */ Uint32Array.from([ - 1116352408, - 1899447441, - 3049323471, - 3921009573, - 961987163, - 1508970993, - 2453635748, - 2870763221, - 3624381080, - 310598401, - 607225278, - 1426881987, - 1925078388, - 2162078206, - 2614888103, - 3248222580, - 3835390401, - 4022224774, - 264347078, - 604807628, - 770255983, - 1249150122, - 1555081692, - 1996064986, - 2554220882, - 2821834349, - 2952996808, - 3210313671, - 3336571891, - 3584528711, - 113926993, - 338241895, - 666307205, - 773529912, - 1294757372, - 1396182291, - 1695183700, - 1986661051, - 2177026350, - 2456956037, - 2730485921, - 2820302411, - 3259730800, - 3345764771, - 3516065817, - 3600352804, - 4094571909, - 275423344, - 430227734, - 506948616, - 659060556, - 883997877, - 958139571, - 1322822218, - 1537002063, - 1747873779, - 1955562222, - 2024104815, - 2227730452, - 2361852424, - 2428436474, - 2756734187, - 3204031479, - 3329325298 - ]); - SHA256_W = /* @__PURE__ */ new Uint32Array(64); - SHA2_32B = class extends HashMD { - constructor(outputLen) { - super(64, outputLen, 8, false); - } - get() { - const { A: A2, B: B2, C: C2, D: D2, E: E2, F: F2, G: G2, H: H2 } = this; - return [A2, B2, C2, D2, E2, F2, G2, H2]; - } - // prettier-ignore - set(A2, B2, C2, D2, E2, F2, G2, H2) { - this.A = A2 | 0; - this.B = B2 | 0; - this.C = C2 | 0; - this.D = D2 | 0; - this.E = E2 | 0; - this.F = F2 | 0; - this.G = G2 | 0; - this.H = H2 | 0; - } - process(view, offset) { - for (let i5 = 0; i5 < 16; i5++, offset += 4) - SHA256_W[i5] = view.getUint32(offset, false); - for (let i5 = 16; i5 < 64; i5++) { - const W15 = SHA256_W[i5 - 15]; - const W2 = SHA256_W[i5 - 2]; - const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3; - const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10; - SHA256_W[i5] = s1 + SHA256_W[i5 - 7] + s0 + SHA256_W[i5 - 16] | 0; - } - let { A: A2, B: B2, C: C2, D: D2, E: E2, F: F2, G: G2, H: H2 } = this; - for (let i5 = 0; i5 < 64; i5++) { - const sigma1 = rotr(E2, 6) ^ rotr(E2, 11) ^ rotr(E2, 25); - const T1 = H2 + sigma1 + Chi(E2, F2, G2) + SHA256_K[i5] + SHA256_W[i5] | 0; - const sigma0 = rotr(A2, 2) ^ rotr(A2, 13) ^ rotr(A2, 22); - const T2 = sigma0 + Maj(A2, B2, C2) | 0; - H2 = G2; - G2 = F2; - F2 = E2; - E2 = D2 + T1 | 0; - D2 = C2; - C2 = B2; - B2 = A2; - A2 = T1 + T2 | 0; - } - A2 = A2 + this.A | 0; - B2 = B2 + this.B | 0; - C2 = C2 + this.C | 0; - D2 = D2 + this.D | 0; - E2 = E2 + this.E | 0; - F2 = F2 + this.F | 0; - G2 = G2 + this.G | 0; - H2 = H2 + this.H | 0; - this.set(A2, B2, C2, D2, E2, F2, G2, H2); - } - roundClean() { - clean(SHA256_W); - } - destroy() { - this.destroyed = true; - this.set(0, 0, 0, 0, 0, 0, 0, 0); - clean(this.buffer); - } - }; - _SHA256 = class extends SHA2_32B { - // We cannot use array here since array allows indexing by variable - // which means optimizer/compiler cannot use registers. - A = SHA256_IV[0] | 0; - B = SHA256_IV[1] | 0; - C = SHA256_IV[2] | 0; - D = SHA256_IV[3] | 0; - E = SHA256_IV[4] | 0; - F = SHA256_IV[5] | 0; - G = SHA256_IV[6] | 0; - H = SHA256_IV[7] | 0; - constructor() { - super(32); - } - }; - sha2562 = /* @__PURE__ */ createHasher( - () => new _SHA256(), - /* @__PURE__ */ oidNist(1) - ); - } -}); - -// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/buffer_utils.js -function concat(...buffers) { - const size2 = buffers.reduce((acc, { length }) => acc + length, 0); - const buf = new Uint8Array(size2); - let i5 = 0; - for (const buffer2 of buffers) { - buf.set(buffer2, i5); - i5 += buffer2.length; - } - return buf; -} -function writeUInt32BE(buf, value, offset) { - if (value < 0 || value >= MAX_INT32) { - throw new RangeError(`value must be >= 0 and <= ${MAX_INT32 - 1}. Received ${value}`); - } - buf.set([value >>> 24, value >>> 16, value >>> 8, value & 255], offset); -} -function uint64be(value) { - const high = Math.floor(value / MAX_INT32); - const low = value % MAX_INT32; - const buf = new Uint8Array(8); - writeUInt32BE(buf, high, 0); - writeUInt32BE(buf, low, 4); - return buf; -} -function uint32be(value) { - const buf = new Uint8Array(4); - writeUInt32BE(buf, value); - return buf; -} -function encode2(string4) { - const bytes = new Uint8Array(string4.length); - for (let i5 = 0; i5 < string4.length; i5++) { - const code = string4.charCodeAt(i5); - if (code > 127) { - throw new TypeError("non-ASCII string encountered in encode()"); - } - bytes[i5] = code; - } - return bytes; -} -var encoder, decoder, MAX_INT32; -var init_buffer_utils = __esm({ - "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/buffer_utils.js"() { - encoder = new TextEncoder(); - decoder = new TextDecoder(); - MAX_INT32 = 2 ** 32; - } -}); - -// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/base64.js -function encodeBase64(input) { - if (Uint8Array.prototype.toBase64) { - return input.toBase64(); - } - const CHUNK_SIZE2 = 32768; - const arr = []; - for (let i5 = 0; i5 < input.length; i5 += CHUNK_SIZE2) { - arr.push(String.fromCharCode.apply(null, input.subarray(i5, i5 + CHUNK_SIZE2))); - } - return btoa(arr.join("")); -} -function decodeBase64(encoded) { - if (Uint8Array.fromBase64) { - return Uint8Array.fromBase64(encoded); - } - const binary2 = atob(encoded); - const bytes = new Uint8Array(binary2.length); - for (let i5 = 0; i5 < binary2.length; i5++) { - bytes[i5] = binary2.charCodeAt(i5); - } - return bytes; -} -var init_base64 = __esm({ - "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/base64.js"() { - } -}); - -// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/util/base64url.js -var base64url_exports = {}; -__export(base64url_exports, { - decode: () => decode2, - encode: () => encode3 -}); -function decode2(input) { - if (Uint8Array.fromBase64) { - return Uint8Array.fromBase64(typeof input === "string" ? input : decoder.decode(input), { - alphabet: "base64url" - }); - } - let encoded = input; - if (encoded instanceof Uint8Array) { - encoded = decoder.decode(encoded); - } - encoded = encoded.replace(/-/g, "+").replace(/_/g, "/"); - try { - return decodeBase64(encoded); - } catch { - throw new TypeError("The input to be decoded is not correctly encoded."); - } -} -function encode3(input) { - let unencoded = input; - if (typeof unencoded === "string") { - unencoded = encoder.encode(unencoded); - } - if (Uint8Array.prototype.toBase64) { - return unencoded.toBase64({ alphabet: "base64url", omitPadding: true }); - } - return encodeBase64(unencoded).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_"); -} -var init_base64url = __esm({ - "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/util/base64url.js"() { - init_buffer_utils(); - init_base64(); - } -}); - -// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/crypto_key.js -function getHashLength(hash2) { - return parseInt(hash2.name.slice(4), 10); -} -function checkHashLength(algorithm2, expected) { - const actual = getHashLength(algorithm2.hash); - if (actual !== expected) - throw unusable(`SHA-${expected}`, "algorithm.hash"); -} -function getNamedCurve(alg2) { - switch (alg2) { - case "ES256": - return "P-256"; - case "ES384": - return "P-384"; - case "ES512": - return "P-521"; - default: - throw new Error("unreachable"); - } -} -function checkUsage(key, usage) { - if (usage && !key.usages.includes(usage)) { - throw new TypeError(`CryptoKey does not support this operation, its usages must include ${usage}.`); - } -} -function checkSigCryptoKey(key, alg2, usage) { - switch (alg2) { - case "HS256": - case "HS384": - case "HS512": { - if (!isAlgorithm(key.algorithm, "HMAC")) - throw unusable("HMAC"); - checkHashLength(key.algorithm, parseInt(alg2.slice(2), 10)); - break; - } - case "RS256": - case "RS384": - case "RS512": { - if (!isAlgorithm(key.algorithm, "RSASSA-PKCS1-v1_5")) - throw unusable("RSASSA-PKCS1-v1_5"); - checkHashLength(key.algorithm, parseInt(alg2.slice(2), 10)); - break; - } - case "PS256": - case "PS384": - case "PS512": { - if (!isAlgorithm(key.algorithm, "RSA-PSS")) - throw unusable("RSA-PSS"); - checkHashLength(key.algorithm, parseInt(alg2.slice(2), 10)); - break; - } - case "Ed25519": - case "EdDSA": { - if (!isAlgorithm(key.algorithm, "Ed25519")) - throw unusable("Ed25519"); - break; - } - case "ML-DSA-44": - case "ML-DSA-65": - case "ML-DSA-87": { - if (!isAlgorithm(key.algorithm, alg2)) - throw unusable(alg2); - break; - } - case "ES256": - case "ES384": - case "ES512": { - if (!isAlgorithm(key.algorithm, "ECDSA")) - throw unusable("ECDSA"); - const expected = getNamedCurve(alg2); - const actual = key.algorithm.namedCurve; - if (actual !== expected) - throw unusable(expected, "algorithm.namedCurve"); - break; - } - default: - throw new TypeError("CryptoKey does not support this operation"); - } - checkUsage(key, usage); -} -function checkEncCryptoKey(key, alg2, usage) { - switch (alg2) { - case "A128GCM": - case "A192GCM": - case "A256GCM": { - if (!isAlgorithm(key.algorithm, "AES-GCM")) - throw unusable("AES-GCM"); - const expected = parseInt(alg2.slice(1, 4), 10); - const actual = key.algorithm.length; - if (actual !== expected) - throw unusable(expected, "algorithm.length"); - break; - } - case "A128KW": - case "A192KW": - case "A256KW": { - if (!isAlgorithm(key.algorithm, "AES-KW")) - throw unusable("AES-KW"); - const expected = parseInt(alg2.slice(1, 4), 10); - const actual = key.algorithm.length; - if (actual !== expected) - throw unusable(expected, "algorithm.length"); - break; - } - case "ECDH": { - switch (key.algorithm.name) { - case "ECDH": - case "X25519": - break; - default: - throw unusable("ECDH or X25519"); - } - break; - } - case "PBES2-HS256+A128KW": - case "PBES2-HS384+A192KW": - case "PBES2-HS512+A256KW": - if (!isAlgorithm(key.algorithm, "PBKDF2")) - throw unusable("PBKDF2"); - break; - case "RSA-OAEP": - case "RSA-OAEP-256": - case "RSA-OAEP-384": - case "RSA-OAEP-512": { - if (!isAlgorithm(key.algorithm, "RSA-OAEP")) - throw unusable("RSA-OAEP"); - checkHashLength(key.algorithm, parseInt(alg2.slice(9), 10) || 1); - break; - } - default: - throw new TypeError("CryptoKey does not support this operation"); - } - checkUsage(key, usage); -} -var unusable, isAlgorithm; -var init_crypto_key = __esm({ - "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/crypto_key.js"() { - unusable = (name, prop = "algorithm.name") => new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`); - isAlgorithm = (algorithm2, name) => algorithm2.name === name; - } -}); - -// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/invalid_key_input.js -function message(msg, actual, ...types2) { - types2 = types2.filter(Boolean); - if (types2.length > 2) { - const last = types2.pop(); - msg += `one of type ${types2.join(", ")}, or ${last}.`; - } else if (types2.length === 2) { - msg += `one of type ${types2[0]} or ${types2[1]}.`; - } else { - msg += `of type ${types2[0]}.`; - } - if (actual == null) { - msg += ` Received ${actual}`; - } else if (typeof actual === "function" && actual.name) { - msg += ` Received function ${actual.name}`; - } else if (typeof actual === "object" && actual != null) { - if (actual.constructor?.name) { - msg += ` Received an instance of ${actual.constructor.name}`; - } - } - return msg; -} -var invalidKeyInput, withAlg; -var init_invalid_key_input = __esm({ - "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/invalid_key_input.js"() { - invalidKeyInput = (actual, ...types2) => message("Key must be ", actual, ...types2); - withAlg = (alg2, actual, ...types2) => message(`Key for the ${alg2} algorithm must be `, actual, ...types2); - } -}); - -// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/util/errors.js -var JOSEError, JWTClaimValidationFailed, JWTExpired, JOSEAlgNotAllowed, JOSENotSupported, JWEDecryptionFailed, JWEInvalid, JWSInvalid, JWTInvalid, JWKInvalid, JWKSInvalid, JWKSNoMatchingKey, JWKSMultipleMatchingKeys, JWKSTimeout, JWSSignatureVerificationFailed; -var init_errors7 = __esm({ - "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/util/errors.js"() { - JOSEError = class extends Error { - static code = "ERR_JOSE_GENERIC"; - code = "ERR_JOSE_GENERIC"; - constructor(message2, options) { - super(message2, options); - this.name = this.constructor.name; - Error.captureStackTrace?.(this, this.constructor); - } - }; - JWTClaimValidationFailed = class extends JOSEError { - static code = "ERR_JWT_CLAIM_VALIDATION_FAILED"; - code = "ERR_JWT_CLAIM_VALIDATION_FAILED"; - claim; - reason; - payload; - constructor(message2, payload2, claim = "unspecified", reason = "unspecified") { - super(message2, { cause: { claim, reason, payload: payload2 } }); - this.claim = claim; - this.reason = reason; - this.payload = payload2; - } - }; - JWTExpired = class extends JOSEError { - static code = "ERR_JWT_EXPIRED"; - code = "ERR_JWT_EXPIRED"; - claim; - reason; - payload; - constructor(message2, payload2, claim = "unspecified", reason = "unspecified") { - super(message2, { cause: { claim, reason, payload: payload2 } }); - this.claim = claim; - this.reason = reason; - this.payload = payload2; - } - }; - JOSEAlgNotAllowed = class extends JOSEError { - static code = "ERR_JOSE_ALG_NOT_ALLOWED"; - code = "ERR_JOSE_ALG_NOT_ALLOWED"; - }; - JOSENotSupported = class extends JOSEError { - static code = "ERR_JOSE_NOT_SUPPORTED"; - code = "ERR_JOSE_NOT_SUPPORTED"; - }; - JWEDecryptionFailed = class extends JOSEError { - static code = "ERR_JWE_DECRYPTION_FAILED"; - code = "ERR_JWE_DECRYPTION_FAILED"; - constructor(message2 = "decryption operation failed", options) { - super(message2, options); - } - }; - JWEInvalid = class extends JOSEError { - static code = "ERR_JWE_INVALID"; - code = "ERR_JWE_INVALID"; - }; - JWSInvalid = class extends JOSEError { - static code = "ERR_JWS_INVALID"; - code = "ERR_JWS_INVALID"; - }; - JWTInvalid = class extends JOSEError { - static code = "ERR_JWT_INVALID"; - code = "ERR_JWT_INVALID"; - }; - JWKInvalid = class extends JOSEError { - static code = "ERR_JWK_INVALID"; - code = "ERR_JWK_INVALID"; - }; - JWKSInvalid = class extends JOSEError { - static code = "ERR_JWKS_INVALID"; - code = "ERR_JWKS_INVALID"; - }; - JWKSNoMatchingKey = class extends JOSEError { - static code = "ERR_JWKS_NO_MATCHING_KEY"; - code = "ERR_JWKS_NO_MATCHING_KEY"; - constructor(message2 = "no applicable key found in the JSON Web Key Set", options) { - super(message2, options); - } - }; - JWKSMultipleMatchingKeys = class extends JOSEError { - [Symbol.asyncIterator]; - static code = "ERR_JWKS_MULTIPLE_MATCHING_KEYS"; - code = "ERR_JWKS_MULTIPLE_MATCHING_KEYS"; - constructor(message2 = "multiple matching keys found in the JSON Web Key Set", options) { - super(message2, options); - } - }; - JWKSTimeout = class extends JOSEError { - static code = "ERR_JWKS_TIMEOUT"; - code = "ERR_JWKS_TIMEOUT"; - constructor(message2 = "request timed out", options) { - super(message2, options); - } - }; - JWSSignatureVerificationFailed = class extends JOSEError { - static code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED"; - code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED"; - constructor(message2 = "signature verification failed", options) { - super(message2, options); - } - }; - } -}); - -// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/is_key_like.js -function assertCryptoKey(key) { - if (!isCryptoKey(key)) { - throw new Error("CryptoKey instance expected"); - } -} -var isCryptoKey, isKeyObject, isKeyLike; -var init_is_key_like = __esm({ - "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/is_key_like.js"() { - isCryptoKey = (key) => { - if (key?.[Symbol.toStringTag] === "CryptoKey") - return true; - try { - return key instanceof CryptoKey; - } catch { - return false; - } - }; - isKeyObject = (key) => key?.[Symbol.toStringTag] === "KeyObject"; - isKeyLike = (key) => isCryptoKey(key) || isKeyObject(key); - } -}); - -// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/content_encryption.js -function cekLength(alg2) { - switch (alg2) { - case "A128GCM": - return 128; - case "A192GCM": - return 192; - case "A256GCM": - case "A128CBC-HS256": - return 256; - case "A192CBC-HS384": - return 384; - case "A256CBC-HS512": - return 512; - default: - throw new JOSENotSupported(`Unsupported JWE Algorithm: ${alg2}`); - } -} -function checkCekLength(cek, expected) { - const actual = cek.byteLength << 3; - if (actual !== expected) { - throw new JWEInvalid(`Invalid Content Encryption Key length. Expected ${expected} bits, got ${actual} bits`); - } -} -function ivBitLength(alg2) { - switch (alg2) { - case "A128GCM": - case "A128GCMKW": - case "A192GCM": - case "A192GCMKW": - case "A256GCM": - case "A256GCMKW": - return 96; - case "A128CBC-HS256": - case "A192CBC-HS384": - case "A256CBC-HS512": - return 128; - default: - throw new JOSENotSupported(`Unsupported JWE Algorithm: ${alg2}`); - } -} -function checkIvLength(enc2, iv) { - if (iv.length << 3 !== ivBitLength(enc2)) { - throw new JWEInvalid("Invalid Initialization Vector length"); - } -} -async function cbcKeySetup(enc2, cek, usage) { - if (!(cek instanceof Uint8Array)) { - throw new TypeError(invalidKeyInput(cek, "Uint8Array")); - } - const keySize = parseInt(enc2.slice(1, 4), 10); - const encKey = await crypto.subtle.importKey("raw", cek.subarray(keySize >> 3), "AES-CBC", false, [usage]); - const macKey = await crypto.subtle.importKey("raw", cek.subarray(0, keySize >> 3), { - hash: `SHA-${keySize << 1}`, - name: "HMAC" - }, false, ["sign"]); - return { encKey, macKey, keySize }; -} -async function cbcHmacTag(macKey, macData, keySize) { - return new Uint8Array((await crypto.subtle.sign("HMAC", macKey, macData)).slice(0, keySize >> 3)); -} -async function cbcEncrypt(enc2, plaintext, cek, iv, aad) { - const { encKey, macKey, keySize } = await cbcKeySetup(enc2, cek, "encrypt"); - const ciphertext = new Uint8Array(await crypto.subtle.encrypt({ - iv, - name: "AES-CBC" - }, encKey, plaintext)); - const macData = concat(aad, iv, ciphertext, uint64be(aad.length << 3)); - const tag3 = await cbcHmacTag(macKey, macData, keySize); - return { ciphertext, tag: tag3, iv }; -} -async function timingSafeEqual4(a5, b6) { - if (!(a5 instanceof Uint8Array)) { - throw new TypeError("First argument must be a buffer"); - } - if (!(b6 instanceof Uint8Array)) { - throw new TypeError("Second argument must be a buffer"); - } - const algorithm2 = { name: "HMAC", hash: "SHA-256" }; - const key = await crypto.subtle.generateKey(algorithm2, false, ["sign"]); - const aHmac = new Uint8Array(await crypto.subtle.sign(algorithm2, key, a5)); - const bHmac = new Uint8Array(await crypto.subtle.sign(algorithm2, key, b6)); - let out = 0; - let i5 = -1; - while (++i5 < 32) { - out |= aHmac[i5] ^ bHmac[i5]; - } - return out === 0; -} -async function cbcDecrypt(enc2, cek, ciphertext, iv, tag3, aad) { - const { encKey, macKey, keySize } = await cbcKeySetup(enc2, cek, "decrypt"); - const macData = concat(aad, iv, ciphertext, uint64be(aad.length << 3)); - const expectedTag = await cbcHmacTag(macKey, macData, keySize); - let macCheckPassed; - try { - macCheckPassed = await timingSafeEqual4(tag3, expectedTag); - } catch { - } - if (!macCheckPassed) { - throw new JWEDecryptionFailed(); - } - let plaintext; - try { - plaintext = new Uint8Array(await crypto.subtle.decrypt({ iv, name: "AES-CBC" }, encKey, ciphertext)); - } catch { - } - if (!plaintext) { - throw new JWEDecryptionFailed(); - } - return plaintext; -} -async function gcmEncrypt(enc2, plaintext, cek, iv, aad) { - let encKey; - if (cek instanceof Uint8Array) { - encKey = await crypto.subtle.importKey("raw", cek, "AES-GCM", false, ["encrypt"]); - } else { - checkEncCryptoKey(cek, enc2, "encrypt"); - encKey = cek; - } - const encrypted = new Uint8Array(await crypto.subtle.encrypt({ - additionalData: aad, - iv, - name: "AES-GCM", - tagLength: 128 - }, encKey, plaintext)); - const tag3 = encrypted.slice(-16); - const ciphertext = encrypted.slice(0, -16); - return { ciphertext, tag: tag3, iv }; -} -async function gcmDecrypt(enc2, cek, ciphertext, iv, tag3, aad) { - let encKey; - if (cek instanceof Uint8Array) { - encKey = await crypto.subtle.importKey("raw", cek, "AES-GCM", false, ["decrypt"]); - } else { - checkEncCryptoKey(cek, enc2, "decrypt"); - encKey = cek; - } - try { - return new Uint8Array(await crypto.subtle.decrypt({ - additionalData: aad, - iv, - name: "AES-GCM", - tagLength: 128 - }, encKey, concat(ciphertext, tag3))); - } catch { - throw new JWEDecryptionFailed(); - } -} -async function encrypt(enc2, plaintext, cek, iv, aad) { - if (!isCryptoKey(cek) && !(cek instanceof Uint8Array)) { - throw new TypeError(invalidKeyInput(cek, "CryptoKey", "KeyObject", "Uint8Array", "JSON Web Key")); - } - if (iv) { - checkIvLength(enc2, iv); - } else { - iv = generateIv(enc2); - } - switch (enc2) { - case "A128CBC-HS256": - case "A192CBC-HS384": - case "A256CBC-HS512": - if (cek instanceof Uint8Array) { - checkCekLength(cek, parseInt(enc2.slice(-3), 10)); - } - return cbcEncrypt(enc2, plaintext, cek, iv, aad); - case "A128GCM": - case "A192GCM": - case "A256GCM": - if (cek instanceof Uint8Array) { - checkCekLength(cek, parseInt(enc2.slice(1, 4), 10)); - } - return gcmEncrypt(enc2, plaintext, cek, iv, aad); - default: - throw new JOSENotSupported(unsupportedEnc); - } -} -async function decrypt(enc2, cek, ciphertext, iv, tag3, aad) { - if (!isCryptoKey(cek) && !(cek instanceof Uint8Array)) { - throw new TypeError(invalidKeyInput(cek, "CryptoKey", "KeyObject", "Uint8Array", "JSON Web Key")); - } - if (!iv) { - throw new JWEInvalid("JWE Initialization Vector missing"); - } - if (!tag3) { - throw new JWEInvalid("JWE Authentication Tag missing"); - } - checkIvLength(enc2, iv); - switch (enc2) { - case "A128CBC-HS256": - case "A192CBC-HS384": - case "A256CBC-HS512": - if (cek instanceof Uint8Array) - checkCekLength(cek, parseInt(enc2.slice(-3), 10)); - return cbcDecrypt(enc2, cek, ciphertext, iv, tag3, aad); - case "A128GCM": - case "A192GCM": - case "A256GCM": - if (cek instanceof Uint8Array) - checkCekLength(cek, parseInt(enc2.slice(1, 4), 10)); - return gcmDecrypt(enc2, cek, ciphertext, iv, tag3, aad); - default: - throw new JOSENotSupported(unsupportedEnc); - } -} -var generateCek, generateIv, unsupportedEnc; -var init_content_encryption = __esm({ - "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/content_encryption.js"() { - init_buffer_utils(); - init_crypto_key(); - init_invalid_key_input(); - init_errors7(); - init_is_key_like(); - generateCek = (alg2) => crypto.getRandomValues(new Uint8Array(cekLength(alg2) >> 3)); - generateIv = (alg2) => crypto.getRandomValues(new Uint8Array(ivBitLength(alg2) >> 3)); - unsupportedEnc = "Unsupported JWE Content Encryption Algorithm"; - } -}); - -// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/helpers.js -function assertNotSet(value, name) { - if (value) { - throw new TypeError(`${name} can only be called once`); - } -} -function decodeBase64url(value, label, ErrorClass) { - try { - return decode2(value); - } catch { - throw new ErrorClass(`Failed to base64url decode the ${label}`); - } -} -async function digest(algorithm2, data2) { - const subtleDigest = `SHA-${algorithm2.slice(-3)}`; - return new Uint8Array(await crypto.subtle.digest(subtleDigest, data2)); -} -var unprotected; -var init_helpers = __esm({ - "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/helpers.js"() { - init_base64url(); - unprotected = /* @__PURE__ */ Symbol(); - } -}); - -// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/type_checks.js -function isObject(input) { - if (!isObjectLike(input) || Object.prototype.toString.call(input) !== "[object Object]") { - return false; - } - if (Object.getPrototypeOf(input) === null) { - return true; - } - let proto = input; - while (Object.getPrototypeOf(proto) !== null) { - proto = Object.getPrototypeOf(proto); - } - return Object.getPrototypeOf(input) === proto; -} -function isDisjoint(...headers) { - const sources = headers.filter(Boolean); - if (sources.length === 0 || sources.length === 1) { - return true; - } - let acc; - for (const header of sources) { - const parameters = Object.keys(header); - if (!acc || acc.size === 0) { - acc = new Set(parameters); - continue; - } - for (const parameter of parameters) { - if (acc.has(parameter)) { - return false; - } - acc.add(parameter); - } - } - return true; -} -var isObjectLike, isJWK, isPrivateJWK, isPublicJWK, isSecretJWK; -var init_type_checks = __esm({ - "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/type_checks.js"() { - isObjectLike = (value) => typeof value === "object" && value !== null; - isJWK = (key) => isObject(key) && typeof key.kty === "string"; - isPrivateJWK = (key) => key.kty !== "oct" && (key.kty === "AKP" && typeof key.priv === "string" || typeof key.d === "string"); - isPublicJWK = (key) => key.kty !== "oct" && key.d === void 0 && key.priv === void 0; - isSecretJWK = (key) => key.kty === "oct" && typeof key.k === "string"; - } -}); - -// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/aeskw.js -function checkKeySize(key, alg2) { - if (key.algorithm.length !== parseInt(alg2.slice(1, 4), 10)) { - throw new TypeError(`Invalid key size for alg: ${alg2}`); - } -} -function getCryptoKey(key, alg2, usage) { - if (key instanceof Uint8Array) { - return crypto.subtle.importKey("raw", key, "AES-KW", true, [usage]); - } - checkEncCryptoKey(key, alg2, usage); - return key; -} -async function wrap(alg2, key, cek) { - const cryptoKey = await getCryptoKey(key, alg2, "wrapKey"); - checkKeySize(cryptoKey, alg2); - const cryptoKeyCek = await crypto.subtle.importKey("raw", cek, { hash: "SHA-256", name: "HMAC" }, true, ["sign"]); - return new Uint8Array(await crypto.subtle.wrapKey("raw", cryptoKeyCek, cryptoKey, "AES-KW")); -} -async function unwrap(alg2, key, encryptedKey) { - const cryptoKey = await getCryptoKey(key, alg2, "unwrapKey"); - checkKeySize(cryptoKey, alg2); - const cryptoKeyCek = await crypto.subtle.unwrapKey("raw", encryptedKey, cryptoKey, "AES-KW", { hash: "SHA-256", name: "HMAC" }, true, ["sign"]); - return new Uint8Array(await crypto.subtle.exportKey("raw", cryptoKeyCek)); -} -var init_aeskw = __esm({ - "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/aeskw.js"() { - init_crypto_key(); - } -}); - -// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/ecdhes.js -function lengthAndInput(input) { - return concat(uint32be(input.length), input); -} -async function concatKdf(Z, L, OtherInfo) { - const dkLen = L >> 3; - const hashLen = 32; - const reps = Math.ceil(dkLen / hashLen); - const dk = new Uint8Array(reps * hashLen); - for (let i5 = 1; i5 <= reps; i5++) { - const hashInput = new Uint8Array(4 + Z.length + OtherInfo.length); - hashInput.set(uint32be(i5), 0); - hashInput.set(Z, 4); - hashInput.set(OtherInfo, 4 + Z.length); - const hashResult = await digest("sha256", hashInput); - dk.set(hashResult, (i5 - 1) * hashLen); - } - return dk.slice(0, dkLen); -} -async function deriveKey(publicKey, privateKey, algorithm2, keyLength, apu = new Uint8Array(), apv = new Uint8Array()) { - checkEncCryptoKey(publicKey, "ECDH"); - checkEncCryptoKey(privateKey, "ECDH", "deriveBits"); - const algorithmID = lengthAndInput(encode2(algorithm2)); - const partyUInfo = lengthAndInput(apu); - const partyVInfo = lengthAndInput(apv); - const suppPubInfo = uint32be(keyLength); - const suppPrivInfo = new Uint8Array(); - const otherInfo = concat(algorithmID, partyUInfo, partyVInfo, suppPubInfo, suppPrivInfo); - const Z = new Uint8Array(await crypto.subtle.deriveBits({ - name: publicKey.algorithm.name, - public: publicKey - }, privateKey, getEcdhBitLength(publicKey))); - return concatKdf(Z, keyLength, otherInfo); -} -function getEcdhBitLength(publicKey) { - if (publicKey.algorithm.name === "X25519") { - return 256; - } - return Math.ceil(parseInt(publicKey.algorithm.namedCurve.slice(-3), 10) / 8) << 3; -} -function allowed(key) { - switch (key.algorithm.namedCurve) { - case "P-256": - case "P-384": - case "P-521": - return true; - default: - return key.algorithm.name === "X25519"; - } -} -var init_ecdhes = __esm({ - "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/ecdhes.js"() { - init_buffer_utils(); - init_crypto_key(); - init_helpers(); - } -}); - -// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/pbes2kw.js -function getCryptoKey2(key, alg2) { - if (key instanceof Uint8Array) { - return crypto.subtle.importKey("raw", key, "PBKDF2", false, [ - "deriveBits" - ]); - } - checkEncCryptoKey(key, alg2, "deriveBits"); - return key; -} -async function deriveKey2(p2s, alg2, p2c, key) { - if (!(p2s instanceof Uint8Array) || p2s.length < 8) { - throw new JWEInvalid("PBES2 Salt Input must be 8 or more octets"); - } - const salt = concatSalt(alg2, p2s); - const keylen = parseInt(alg2.slice(13, 16), 10); - const subtleAlg = { - hash: `SHA-${alg2.slice(8, 11)}`, - iterations: p2c, - name: "PBKDF2", - salt - }; - const cryptoKey = await getCryptoKey2(key, alg2); - return new Uint8Array(await crypto.subtle.deriveBits(subtleAlg, cryptoKey, keylen)); -} -async function wrap2(alg2, key, cek, p2c = 2048, p2s = crypto.getRandomValues(new Uint8Array(16))) { - const derived = await deriveKey2(p2s, alg2, p2c, key); - const encryptedKey = await wrap(alg2.slice(-6), derived, cek); - return { encryptedKey, p2c, p2s: encode3(p2s) }; -} -async function unwrap2(alg2, key, encryptedKey, p2c, p2s) { - const derived = await deriveKey2(p2s, alg2, p2c, key); - return unwrap(alg2.slice(-6), derived, encryptedKey); -} -var concatSalt; -var init_pbes2kw = __esm({ - "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/pbes2kw.js"() { - init_base64url(); - init_aeskw(); - init_crypto_key(); - init_buffer_utils(); - init_errors7(); - concatSalt = (alg2, p2sInput) => concat(encode2(alg2), Uint8Array.of(0), p2sInput); - } -}); - -// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/signing.js -function checkKeyLength(alg2, key) { - if (alg2.startsWith("RS") || alg2.startsWith("PS")) { - const { modulusLength } = key.algorithm; - if (typeof modulusLength !== "number" || modulusLength < 2048) { - throw new TypeError(`${alg2} requires key modulusLength to be 2048 bits or larger`); - } - } -} -function subtleAlgorithm(alg2, algorithm2) { - const hash2 = `SHA-${alg2.slice(-3)}`; - switch (alg2) { - case "HS256": - case "HS384": - case "HS512": - return { hash: hash2, name: "HMAC" }; - case "PS256": - case "PS384": - case "PS512": - return { hash: hash2, name: "RSA-PSS", saltLength: parseInt(alg2.slice(-3), 10) >> 3 }; - case "RS256": - case "RS384": - case "RS512": - return { hash: hash2, name: "RSASSA-PKCS1-v1_5" }; - case "ES256": - case "ES384": - case "ES512": - return { hash: hash2, name: "ECDSA", namedCurve: algorithm2.namedCurve }; - case "Ed25519": - case "EdDSA": - return { name: "Ed25519" }; - case "ML-DSA-44": - case "ML-DSA-65": - case "ML-DSA-87": - return { name: alg2 }; - default: - throw new JOSENotSupported(`alg ${alg2} is not supported either by JOSE or your javascript runtime`); - } -} -async function getSigKey(alg2, key, usage) { - if (key instanceof Uint8Array) { - if (!alg2.startsWith("HS")) { - throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject", "JSON Web Key")); - } - return crypto.subtle.importKey("raw", key, { hash: `SHA-${alg2.slice(-3)}`, name: "HMAC" }, false, [usage]); - } - checkSigCryptoKey(key, alg2, usage); - return key; -} -async function sign(alg2, key, data2) { - const cryptoKey = await getSigKey(alg2, key, "sign"); - checkKeyLength(alg2, cryptoKey); - const signature = await crypto.subtle.sign(subtleAlgorithm(alg2, cryptoKey.algorithm), cryptoKey, data2); - return new Uint8Array(signature); -} -async function verify(alg2, key, signature, data2) { - const cryptoKey = await getSigKey(alg2, key, "verify"); - checkKeyLength(alg2, cryptoKey); - const algorithm2 = subtleAlgorithm(alg2, cryptoKey.algorithm); - try { - return await crypto.subtle.verify(algorithm2, cryptoKey, signature, data2); - } catch { - return false; - } -} -var init_signing = __esm({ - "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/signing.js"() { - init_errors7(); - init_crypto_key(); - init_invalid_key_input(); - } -}); - -// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/rsaes.js -async function encrypt2(alg2, key, cek) { - checkEncCryptoKey(key, alg2, "encrypt"); - checkKeyLength(alg2, key); - return new Uint8Array(await crypto.subtle.encrypt(subtleAlgorithm2(alg2), key, cek)); -} -async function decrypt2(alg2, key, encryptedKey) { - checkEncCryptoKey(key, alg2, "decrypt"); - checkKeyLength(alg2, key); - return new Uint8Array(await crypto.subtle.decrypt(subtleAlgorithm2(alg2), key, encryptedKey)); -} -var subtleAlgorithm2; -var init_rsaes = __esm({ - "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/rsaes.js"() { - init_crypto_key(); - init_signing(); - init_errors7(); - subtleAlgorithm2 = (alg2) => { - switch (alg2) { - case "RSA-OAEP": - case "RSA-OAEP-256": - case "RSA-OAEP-384": - case "RSA-OAEP-512": - return "RSA-OAEP"; - default: - throw new JOSENotSupported(`alg ${alg2} is not supported either by JOSE or your javascript runtime`); - } - }; - } -}); - -// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/jwk_to_key.js -function subtleMapping(jwk) { - let algorithm2; - let keyUsages; - switch (jwk.kty) { - case "AKP": { - switch (jwk.alg) { - case "ML-DSA-44": - case "ML-DSA-65": - case "ML-DSA-87": - algorithm2 = { name: jwk.alg }; - keyUsages = jwk.priv ? ["sign"] : ["verify"]; - break; - default: - throw new JOSENotSupported(unsupportedAlg); - } - break; - } - case "RSA": { - switch (jwk.alg) { - case "PS256": - case "PS384": - case "PS512": - algorithm2 = { name: "RSA-PSS", hash: `SHA-${jwk.alg.slice(-3)}` }; - keyUsages = jwk.d ? ["sign"] : ["verify"]; - break; - case "RS256": - case "RS384": - case "RS512": - algorithm2 = { name: "RSASSA-PKCS1-v1_5", hash: `SHA-${jwk.alg.slice(-3)}` }; - keyUsages = jwk.d ? ["sign"] : ["verify"]; - break; - case "RSA-OAEP": - case "RSA-OAEP-256": - case "RSA-OAEP-384": - case "RSA-OAEP-512": - algorithm2 = { - name: "RSA-OAEP", - hash: `SHA-${parseInt(jwk.alg.slice(-3), 10) || 1}` - }; - keyUsages = jwk.d ? ["decrypt", "unwrapKey"] : ["encrypt", "wrapKey"]; - break; - default: - throw new JOSENotSupported(unsupportedAlg); - } - break; - } - case "EC": { - switch (jwk.alg) { - case "ES256": - case "ES384": - case "ES512": - algorithm2 = { - name: "ECDSA", - namedCurve: { ES256: "P-256", ES384: "P-384", ES512: "P-521" }[jwk.alg] - }; - keyUsages = jwk.d ? ["sign"] : ["verify"]; - break; - case "ECDH-ES": - case "ECDH-ES+A128KW": - case "ECDH-ES+A192KW": - case "ECDH-ES+A256KW": - algorithm2 = { name: "ECDH", namedCurve: jwk.crv }; - keyUsages = jwk.d ? ["deriveBits"] : []; - break; - default: - throw new JOSENotSupported(unsupportedAlg); - } - break; - } - case "OKP": { - switch (jwk.alg) { - case "Ed25519": - case "EdDSA": - algorithm2 = { name: "Ed25519" }; - keyUsages = jwk.d ? ["sign"] : ["verify"]; - break; - case "ECDH-ES": - case "ECDH-ES+A128KW": - case "ECDH-ES+A192KW": - case "ECDH-ES+A256KW": - algorithm2 = { name: jwk.crv }; - keyUsages = jwk.d ? ["deriveBits"] : []; - break; - default: - throw new JOSENotSupported(unsupportedAlg); - } - break; - } - default: - throw new JOSENotSupported('Invalid or unsupported JWK "kty" (Key Type) Parameter value'); - } - return { algorithm: algorithm2, keyUsages }; -} -async function jwkToKey(jwk) { - if (!jwk.alg) { - throw new TypeError('"alg" argument is required when "jwk.alg" is not present'); - } - const { algorithm: algorithm2, keyUsages } = subtleMapping(jwk); - const keyData = { ...jwk }; - if (keyData.kty !== "AKP") { - delete keyData.alg; - } - delete keyData.use; - return crypto.subtle.importKey("jwk", keyData, algorithm2, jwk.ext ?? (jwk.d || jwk.priv ? false : true), jwk.key_ops ?? keyUsages); -} -var unsupportedAlg; -var init_jwk_to_key = __esm({ - "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/jwk_to_key.js"() { - init_errors7(); - unsupportedAlg = 'Invalid or unsupported JWK "alg" (Algorithm) Parameter value'; - } -}); - -// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/normalize_key.js -async function normalizeKey(key, alg2) { - if (key instanceof Uint8Array) { - return key; - } - if (isCryptoKey(key)) { - return key; - } - if (isKeyObject(key)) { - if (key.type === "secret") { - return key.export(); - } - if ("toCryptoKey" in key && typeof key.toCryptoKey === "function") { - try { - return handleKeyObject(key, alg2); - } catch (err) { - if (err instanceof TypeError) { - throw err; - } - } - } - let jwk = key.export({ format: "jwk" }); - return handleJWK(key, jwk, alg2); - } - if (isJWK(key)) { - if (key.k) { - return decode2(key.k); - } - return handleJWK(key, key, alg2, true); - } - throw new Error("unreachable"); -} -var unusableForAlg, cache5, handleJWK, handleKeyObject; -var init_normalize_key = __esm({ - "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/normalize_key.js"() { - init_type_checks(); - init_base64url(); - init_jwk_to_key(); - init_is_key_like(); - unusableForAlg = "given KeyObject instance cannot be used for this algorithm"; - handleJWK = async (key, jwk, alg2, freeze3 = false) => { - cache5 ||= /* @__PURE__ */ new WeakMap(); - let cached4 = cache5.get(key); - if (cached4?.[alg2]) { - return cached4[alg2]; - } - const cryptoKey = await jwkToKey({ ...jwk, alg: alg2 }); - if (freeze3) - Object.freeze(key); - if (!cached4) { - cache5.set(key, { [alg2]: cryptoKey }); - } else { - cached4[alg2] = cryptoKey; - } - return cryptoKey; - }; - handleKeyObject = (keyObject, alg2) => { - cache5 ||= /* @__PURE__ */ new WeakMap(); - let cached4 = cache5.get(keyObject); - if (cached4?.[alg2]) { - return cached4[alg2]; - } - const isPublic = keyObject.type === "public"; - const extractable = isPublic ? true : false; - let cryptoKey; - if (keyObject.asymmetricKeyType === "x25519") { - switch (alg2) { - case "ECDH-ES": - case "ECDH-ES+A128KW": - case "ECDH-ES+A192KW": - case "ECDH-ES+A256KW": - break; - default: - throw new TypeError(unusableForAlg); - } - cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, isPublic ? [] : ["deriveBits"]); - } - if (keyObject.asymmetricKeyType === "ed25519") { - if (alg2 !== "EdDSA" && alg2 !== "Ed25519") { - throw new TypeError(unusableForAlg); - } - cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, [ - isPublic ? "verify" : "sign" - ]); - } - switch (keyObject.asymmetricKeyType) { - case "ml-dsa-44": - case "ml-dsa-65": - case "ml-dsa-87": { - if (alg2 !== keyObject.asymmetricKeyType.toUpperCase()) { - throw new TypeError(unusableForAlg); - } - cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, [ - isPublic ? "verify" : "sign" - ]); - } - } - if (keyObject.asymmetricKeyType === "rsa") { - let hash2; - switch (alg2) { - case "RSA-OAEP": - hash2 = "SHA-1"; - break; - case "RS256": - case "PS256": - case "RSA-OAEP-256": - hash2 = "SHA-256"; - break; - case "RS384": - case "PS384": - case "RSA-OAEP-384": - hash2 = "SHA-384"; - break; - case "RS512": - case "PS512": - case "RSA-OAEP-512": - hash2 = "SHA-512"; - break; - default: - throw new TypeError(unusableForAlg); - } - if (alg2.startsWith("RSA-OAEP")) { - return keyObject.toCryptoKey({ - name: "RSA-OAEP", - hash: hash2 - }, extractable, isPublic ? ["encrypt"] : ["decrypt"]); - } - cryptoKey = keyObject.toCryptoKey({ - name: alg2.startsWith("PS") ? "RSA-PSS" : "RSASSA-PKCS1-v1_5", - hash: hash2 - }, extractable, [isPublic ? "verify" : "sign"]); - } - if (keyObject.asymmetricKeyType === "ec") { - const nist = /* @__PURE__ */ new Map([ - ["prime256v1", "P-256"], - ["secp384r1", "P-384"], - ["secp521r1", "P-521"] - ]); - const namedCurve = nist.get(keyObject.asymmetricKeyDetails?.namedCurve); - if (!namedCurve) { - throw new TypeError(unusableForAlg); - } - const expectedCurve = { ES256: "P-256", ES384: "P-384", ES512: "P-521" }; - if (expectedCurve[alg2] && namedCurve === expectedCurve[alg2]) { - cryptoKey = keyObject.toCryptoKey({ - name: "ECDSA", - namedCurve - }, extractable, [isPublic ? "verify" : "sign"]); - } - if (alg2.startsWith("ECDH-ES")) { - cryptoKey = keyObject.toCryptoKey({ - name: "ECDH", - namedCurve - }, extractable, isPublic ? [] : ["deriveBits"]); - } - } - if (!cryptoKey) { - throw new TypeError(unusableForAlg); - } - if (!cached4) { - cache5.set(keyObject, { [alg2]: cryptoKey }); - } else { - cached4[alg2] = cryptoKey; - } - return cryptoKey; - }; - } -}); - -// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/key/import.js -async function importJWK(jwk, alg2, options) { - if (!isObject(jwk)) { - throw new TypeError("JWK must be an object"); - } - let ext; - alg2 ??= jwk.alg; - ext ??= options?.extractable ?? jwk.ext; - switch (jwk.kty) { - case "oct": - if (typeof jwk.k !== "string" || !jwk.k) { - throw new TypeError('missing "k" (Key Value) Parameter value'); - } - return decode2(jwk.k); - case "RSA": - if ("oth" in jwk && jwk.oth !== void 0) { - throw new JOSENotSupported('RSA JWK "oth" (Other Primes Info) Parameter value is not supported'); - } - return jwkToKey({ ...jwk, alg: alg2, ext }); - case "AKP": { - if (typeof jwk.alg !== "string" || !jwk.alg) { - throw new TypeError('missing "alg" (Algorithm) Parameter value'); - } - if (alg2 !== void 0 && alg2 !== jwk.alg) { - throw new TypeError("JWK alg and alg option value mismatch"); - } - return jwkToKey({ ...jwk, ext }); - } - case "EC": - case "OKP": - return jwkToKey({ ...jwk, alg: alg2, ext }); - default: - throw new JOSENotSupported('Unsupported "kty" (Key Type) Parameter value'); - } -} -var init_import = __esm({ - "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/key/import.js"() { - init_base64url(); - init_jwk_to_key(); - init_errors7(); - init_type_checks(); - } -}); - -// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/key_to_jwk.js -async function keyToJWK(key) { - if (isKeyObject(key)) { - if (key.type === "secret") { - key = key.export(); - } else { - return key.export({ format: "jwk" }); - } - } - if (key instanceof Uint8Array) { - return { - kty: "oct", - k: encode3(key) - }; - } - if (!isCryptoKey(key)) { - throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject", "Uint8Array")); - } - if (!key.extractable) { - throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK"); - } - const { ext, key_ops, alg: alg2, use: use2, ...jwk } = await crypto.subtle.exportKey("jwk", key); - if (jwk.kty === "AKP") { - ; - jwk.alg = alg2; - } - return jwk; -} -var init_key_to_jwk = __esm({ - "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/key_to_jwk.js"() { - init_invalid_key_input(); - init_base64url(); - init_is_key_like(); - } -}); - -// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/key/export.js -async function exportJWK(key) { - return keyToJWK(key); -} -var init_export = __esm({ - "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/key/export.js"() { - init_key_to_jwk(); - } -}); - -// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/aesgcmkw.js -async function wrap3(alg2, key, cek, iv) { - const jweAlgorithm = alg2.slice(0, 7); - const wrapped = await encrypt(jweAlgorithm, cek, key, iv, new Uint8Array()); - return { - encryptedKey: wrapped.ciphertext, - iv: encode3(wrapped.iv), - tag: encode3(wrapped.tag) - }; -} -async function unwrap3(alg2, key, encryptedKey, iv, tag3) { - const jweAlgorithm = alg2.slice(0, 7); - return decrypt(jweAlgorithm, key, encryptedKey, iv, tag3, new Uint8Array()); -} -var init_aesgcmkw = __esm({ - "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/aesgcmkw.js"() { - init_content_encryption(); - init_base64url(); - } -}); - -// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/key_management.js -function assertEncryptedKey(encryptedKey) { - if (encryptedKey === void 0) - throw new JWEInvalid("JWE Encrypted Key missing"); -} -async function decryptKeyManagement(alg2, key, encryptedKey, joseHeader, options) { - switch (alg2) { - case "dir": { - if (encryptedKey !== void 0) - throw new JWEInvalid("Encountered unexpected JWE Encrypted Key"); - return key; - } - case "ECDH-ES": - if (encryptedKey !== void 0) - throw new JWEInvalid("Encountered unexpected JWE Encrypted Key"); - case "ECDH-ES+A128KW": - case "ECDH-ES+A192KW": - case "ECDH-ES+A256KW": { - if (!isObject(joseHeader.epk)) - throw new JWEInvalid(`JOSE Header "epk" (Ephemeral Public Key) missing or invalid`); - assertCryptoKey(key); - if (!allowed(key)) - throw new JOSENotSupported("ECDH with the provided key is not allowed or not supported by your javascript runtime"); - const epk = await importJWK(joseHeader.epk, alg2); - assertCryptoKey(epk); - let partyUInfo; - let partyVInfo; - if (joseHeader.apu !== void 0) { - if (typeof joseHeader.apu !== "string") - throw new JWEInvalid(`JOSE Header "apu" (Agreement PartyUInfo) invalid`); - partyUInfo = decodeBase64url(joseHeader.apu, "apu", JWEInvalid); - } - if (joseHeader.apv !== void 0) { - if (typeof joseHeader.apv !== "string") - throw new JWEInvalid(`JOSE Header "apv" (Agreement PartyVInfo) invalid`); - partyVInfo = decodeBase64url(joseHeader.apv, "apv", JWEInvalid); - } - const sharedSecret = await deriveKey(epk, key, alg2 === "ECDH-ES" ? joseHeader.enc : alg2, alg2 === "ECDH-ES" ? cekLength(joseHeader.enc) : parseInt(alg2.slice(-5, -2), 10), partyUInfo, partyVInfo); - if (alg2 === "ECDH-ES") - return sharedSecret; - assertEncryptedKey(encryptedKey); - return unwrap(alg2.slice(-6), sharedSecret, encryptedKey); - } - case "RSA-OAEP": - case "RSA-OAEP-256": - case "RSA-OAEP-384": - case "RSA-OAEP-512": { - assertEncryptedKey(encryptedKey); - assertCryptoKey(key); - return decrypt2(alg2, key, encryptedKey); - } - case "PBES2-HS256+A128KW": - case "PBES2-HS384+A192KW": - case "PBES2-HS512+A256KW": { - assertEncryptedKey(encryptedKey); - if (typeof joseHeader.p2c !== "number") - throw new JWEInvalid(`JOSE Header "p2c" (PBES2 Count) missing or invalid`); - const p2cLimit = options?.maxPBES2Count || 1e4; - if (joseHeader.p2c > p2cLimit) - throw new JWEInvalid(`JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds`); - if (typeof joseHeader.p2s !== "string") - throw new JWEInvalid(`JOSE Header "p2s" (PBES2 Salt) missing or invalid`); - let p2s; - p2s = decodeBase64url(joseHeader.p2s, "p2s", JWEInvalid); - return unwrap2(alg2, key, encryptedKey, joseHeader.p2c, p2s); - } - case "A128KW": - case "A192KW": - case "A256KW": { - assertEncryptedKey(encryptedKey); - return unwrap(alg2, key, encryptedKey); - } - case "A128GCMKW": - case "A192GCMKW": - case "A256GCMKW": { - assertEncryptedKey(encryptedKey); - if (typeof joseHeader.iv !== "string") - throw new JWEInvalid(`JOSE Header "iv" (Initialization Vector) missing or invalid`); - if (typeof joseHeader.tag !== "string") - throw new JWEInvalid(`JOSE Header "tag" (Authentication Tag) missing or invalid`); - let iv; - iv = decodeBase64url(joseHeader.iv, "iv", JWEInvalid); - let tag3; - tag3 = decodeBase64url(joseHeader.tag, "tag", JWEInvalid); - return unwrap3(alg2, key, encryptedKey, iv, tag3); - } - default: { - throw new JOSENotSupported(unsupportedAlgHeader); - } - } -} -async function encryptKeyManagement(alg2, enc2, key, providedCek, providedParameters = {}) { - let encryptedKey; - let parameters; - let cek; - switch (alg2) { - case "dir": { - cek = key; - break; - } - case "ECDH-ES": - case "ECDH-ES+A128KW": - case "ECDH-ES+A192KW": - case "ECDH-ES+A256KW": { - assertCryptoKey(key); - if (!allowed(key)) { - throw new JOSENotSupported("ECDH with the provided key is not allowed or not supported by your javascript runtime"); - } - const { apu, apv } = providedParameters; - let ephemeralKey; - if (providedParameters.epk) { - ephemeralKey = await normalizeKey(providedParameters.epk, alg2); - } else { - ephemeralKey = (await crypto.subtle.generateKey(key.algorithm, true, ["deriveBits"])).privateKey; - } - const { x: x5, y: y2, crv, kty } = await exportJWK(ephemeralKey); - const sharedSecret = await deriveKey(key, ephemeralKey, alg2 === "ECDH-ES" ? enc2 : alg2, alg2 === "ECDH-ES" ? cekLength(enc2) : parseInt(alg2.slice(-5, -2), 10), apu, apv); - parameters = { epk: { x: x5, crv, kty } }; - if (kty === "EC") - parameters.epk.y = y2; - if (apu) - parameters.apu = encode3(apu); - if (apv) - parameters.apv = encode3(apv); - if (alg2 === "ECDH-ES") { - cek = sharedSecret; - break; - } - cek = providedCek || generateCek(enc2); - const kwAlg = alg2.slice(-6); - encryptedKey = await wrap(kwAlg, sharedSecret, cek); - break; - } - case "RSA-OAEP": - case "RSA-OAEP-256": - case "RSA-OAEP-384": - case "RSA-OAEP-512": { - cek = providedCek || generateCek(enc2); - assertCryptoKey(key); - encryptedKey = await encrypt2(alg2, key, cek); - break; - } - case "PBES2-HS256+A128KW": - case "PBES2-HS384+A192KW": - case "PBES2-HS512+A256KW": { - cek = providedCek || generateCek(enc2); - const { p2c, p2s } = providedParameters; - ({ encryptedKey, ...parameters } = await wrap2(alg2, key, cek, p2c, p2s)); - break; - } - case "A128KW": - case "A192KW": - case "A256KW": { - cek = providedCek || generateCek(enc2); - encryptedKey = await wrap(alg2, key, cek); - break; - } - case "A128GCMKW": - case "A192GCMKW": - case "A256GCMKW": { - cek = providedCek || generateCek(enc2); - const { iv } = providedParameters; - ({ encryptedKey, ...parameters } = await wrap3(alg2, key, cek, iv)); - break; - } - default: { - throw new JOSENotSupported(unsupportedAlgHeader); - } - } - return { cek, encryptedKey, parameters }; -} -var unsupportedAlgHeader; -var init_key_management = __esm({ - "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/key_management.js"() { - init_aeskw(); - init_ecdhes(); - init_pbes2kw(); - init_rsaes(); - init_base64url(); - init_normalize_key(); - init_errors7(); - init_helpers(); - init_content_encryption(); - init_import(); - init_export(); - init_type_checks(); - init_aesgcmkw(); - init_is_key_like(); - unsupportedAlgHeader = 'Invalid or unsupported "alg" (JWE Algorithm) header value'; - } -}); - -// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/validate_crit.js -function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) { - if (joseHeader.crit !== void 0 && protectedHeader?.crit === void 0) { - throw new Err('"crit" (Critical) Header Parameter MUST be integrity protected'); - } - if (!protectedHeader || protectedHeader.crit === void 0) { - return /* @__PURE__ */ new Set(); - } - if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input) => typeof input !== "string" || input.length === 0)) { - throw new Err('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present'); - } - let recognized; - if (recognizedOption !== void 0) { - recognized = new Map([...Object.entries(recognizedOption), ...recognizedDefault.entries()]); - } else { - recognized = recognizedDefault; - } - for (const parameter of protectedHeader.crit) { - if (!recognized.has(parameter)) { - throw new JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`); - } - if (joseHeader[parameter] === void 0) { - throw new Err(`Extension Header Parameter "${parameter}" is missing`); - } - if (recognized.get(parameter) && protectedHeader[parameter] === void 0) { - throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`); - } - } - return new Set(protectedHeader.crit); -} -var init_validate_crit = __esm({ - "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/validate_crit.js"() { - init_errors7(); - } -}); - -// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/validate_algorithms.js -function validateAlgorithms(option, algorithms) { - if (algorithms !== void 0 && (!Array.isArray(algorithms) || algorithms.some((s5) => typeof s5 !== "string"))) { - throw new TypeError(`"${option}" option must be an array of strings`); - } - if (!algorithms) { - return void 0; - } - return new Set(algorithms); -} -var init_validate_algorithms = __esm({ - "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/validate_algorithms.js"() { - } -}); - -// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/check_key_type.js -function checkKeyType(alg2, key, usage) { - switch (alg2.substring(0, 2)) { - case "A1": - case "A2": - case "di": - case "HS": - case "PB": - symmetricTypeCheck(alg2, key, usage); - break; - default: - asymmetricTypeCheck(alg2, key, usage); - } -} -var tag2, jwkMatchesOp, symmetricTypeCheck, asymmetricTypeCheck; -var init_check_key_type = __esm({ - "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/check_key_type.js"() { - init_invalid_key_input(); - init_is_key_like(); - init_type_checks(); - tag2 = (key) => key?.[Symbol.toStringTag]; - jwkMatchesOp = (alg2, key, usage) => { - if (key.use !== void 0) { - let expected; - switch (usage) { - case "sign": - case "verify": - expected = "sig"; - break; - case "encrypt": - case "decrypt": - expected = "enc"; - break; - } - if (key.use !== expected) { - throw new TypeError(`Invalid key for this operation, its "use" must be "${expected}" when present`); - } - } - if (key.alg !== void 0 && key.alg !== alg2) { - throw new TypeError(`Invalid key for this operation, its "alg" must be "${alg2}" when present`); - } - if (Array.isArray(key.key_ops)) { - let expectedKeyOp; - switch (true) { - case (usage === "sign" || usage === "verify"): - case alg2 === "dir": - case alg2.includes("CBC-HS"): - expectedKeyOp = usage; - break; - case alg2.startsWith("PBES2"): - expectedKeyOp = "deriveBits"; - break; - case /^A\d{3}(?:GCM)?(?:KW)?$/.test(alg2): - if (!alg2.includes("GCM") && alg2.endsWith("KW")) { - expectedKeyOp = usage === "encrypt" ? "wrapKey" : "unwrapKey"; - } else { - expectedKeyOp = usage; - } - break; - case (usage === "encrypt" && alg2.startsWith("RSA")): - expectedKeyOp = "wrapKey"; - break; - case usage === "decrypt": - expectedKeyOp = alg2.startsWith("RSA") ? "unwrapKey" : "deriveBits"; - break; - } - if (expectedKeyOp && key.key_ops?.includes?.(expectedKeyOp) === false) { - throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${expectedKeyOp}" when present`); - } - } - return true; - }; - symmetricTypeCheck = (alg2, key, usage) => { - if (key instanceof Uint8Array) - return; - if (isJWK(key)) { - if (isSecretJWK(key) && jwkMatchesOp(alg2, key, usage)) - return; - throw new TypeError(`JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present`); - } - if (!isKeyLike(key)) { - throw new TypeError(withAlg(alg2, key, "CryptoKey", "KeyObject", "JSON Web Key", "Uint8Array")); - } - if (key.type !== "secret") { - throw new TypeError(`${tag2(key)} instances for symmetric algorithms must be of type "secret"`); - } - }; - asymmetricTypeCheck = (alg2, key, usage) => { - if (isJWK(key)) { - switch (usage) { - case "decrypt": - case "sign": - if (isPrivateJWK(key) && jwkMatchesOp(alg2, key, usage)) - return; - throw new TypeError(`JSON Web Key for this operation must be a private JWK`); - case "encrypt": - case "verify": - if (isPublicJWK(key) && jwkMatchesOp(alg2, key, usage)) - return; - throw new TypeError(`JSON Web Key for this operation must be a public JWK`); - } - } - if (!isKeyLike(key)) { - throw new TypeError(withAlg(alg2, key, "CryptoKey", "KeyObject", "JSON Web Key")); - } - if (key.type === "secret") { - throw new TypeError(`${tag2(key)} instances for asymmetric algorithms must not be of type "secret"`); - } - if (key.type === "public") { - switch (usage) { - case "sign": - throw new TypeError(`${tag2(key)} instances for asymmetric algorithm signing must be of type "private"`); - case "decrypt": - throw new TypeError(`${tag2(key)} instances for asymmetric algorithm decryption must be of type "private"`); - } - } - if (key.type === "private") { - switch (usage) { - case "verify": - throw new TypeError(`${tag2(key)} instances for asymmetric algorithm verifying must be of type "public"`); - case "encrypt": - throw new TypeError(`${tag2(key)} instances for asymmetric algorithm encryption must be of type "public"`); - } - } - }; - } -}); - -// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/deflate.js -function supported(name) { - if (typeof globalThis[name] === "undefined") { - throw new JOSENotSupported(`JWE "zip" (Compression Algorithm) Header Parameter requires the ${name} API.`); - } -} -async function compress(input) { - supported("CompressionStream"); - const cs = new CompressionStream("deflate-raw"); - const writer = cs.writable.getWriter(); - writer.write(input).catch(() => { - }); - writer.close().catch(() => { - }); - const chunks = []; - const reader = cs.readable.getReader(); - for (; ; ) { - const { value, done } = await reader.read(); - if (done) - break; - chunks.push(value); - } - return concat(...chunks); -} -async function decompress(input, maxLength) { - supported("DecompressionStream"); - const ds = new DecompressionStream("deflate-raw"); - const writer = ds.writable.getWriter(); - writer.write(input).catch(() => { - }); - writer.close().catch(() => { - }); - const chunks = []; - let length = 0; - const reader = ds.readable.getReader(); - for (; ; ) { - const { value, done } = await reader.read(); - if (done) - break; - chunks.push(value); - length += value.byteLength; - if (maxLength !== Infinity && length > maxLength) { - throw new JWEInvalid("Decompressed plaintext exceeded the configured limit"); - } - } - return concat(...chunks); -} -var init_deflate = __esm({ - "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/deflate.js"() { - init_errors7(); - init_buffer_utils(); - } -}); - -// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwe/flattened/decrypt.js -async function flattenedDecrypt(jwe, key, options) { - if (!isObject(jwe)) { - throw new JWEInvalid("Flattened JWE must be an object"); - } - if (jwe.protected === void 0 && jwe.header === void 0 && jwe.unprotected === void 0) { - throw new JWEInvalid("JOSE Header missing"); - } - if (jwe.iv !== void 0 && typeof jwe.iv !== "string") { - throw new JWEInvalid("JWE Initialization Vector incorrect type"); - } - if (typeof jwe.ciphertext !== "string") { - throw new JWEInvalid("JWE Ciphertext missing or incorrect type"); - } - if (jwe.tag !== void 0 && typeof jwe.tag !== "string") { - throw new JWEInvalid("JWE Authentication Tag incorrect type"); - } - if (jwe.protected !== void 0 && typeof jwe.protected !== "string") { - throw new JWEInvalid("JWE Protected Header incorrect type"); - } - if (jwe.encrypted_key !== void 0 && typeof jwe.encrypted_key !== "string") { - throw new JWEInvalid("JWE Encrypted Key incorrect type"); - } - if (jwe.aad !== void 0 && typeof jwe.aad !== "string") { - throw new JWEInvalid("JWE AAD incorrect type"); - } - if (jwe.header !== void 0 && !isObject(jwe.header)) { - throw new JWEInvalid("JWE Shared Unprotected Header incorrect type"); - } - if (jwe.unprotected !== void 0 && !isObject(jwe.unprotected)) { - throw new JWEInvalid("JWE Per-Recipient Unprotected Header incorrect type"); - } - let parsedProt; - if (jwe.protected) { - try { - const protectedHeader2 = decode2(jwe.protected); - parsedProt = JSON.parse(decoder.decode(protectedHeader2)); - } catch { - throw new JWEInvalid("JWE Protected Header is invalid"); - } - } - if (!isDisjoint(parsedProt, jwe.header, jwe.unprotected)) { - throw new JWEInvalid("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint"); - } - const joseHeader = { - ...parsedProt, - ...jwe.header, - ...jwe.unprotected - }; - validateCrit(JWEInvalid, /* @__PURE__ */ new Map(), options?.crit, parsedProt, joseHeader); - if (joseHeader.zip !== void 0 && joseHeader.zip !== "DEF") { - throw new JOSENotSupported('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.'); - } - if (joseHeader.zip !== void 0 && !parsedProt?.zip) { - throw new JWEInvalid('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.'); - } - const { alg: alg2, enc: enc2 } = joseHeader; - if (typeof alg2 !== "string" || !alg2) { - throw new JWEInvalid("missing JWE Algorithm (alg) in JWE Header"); - } - if (typeof enc2 !== "string" || !enc2) { - throw new JWEInvalid("missing JWE Encryption Algorithm (enc) in JWE Header"); - } - const keyManagementAlgorithms = options && validateAlgorithms("keyManagementAlgorithms", options.keyManagementAlgorithms); - const contentEncryptionAlgorithms = options && validateAlgorithms("contentEncryptionAlgorithms", options.contentEncryptionAlgorithms); - if (keyManagementAlgorithms && !keyManagementAlgorithms.has(alg2) || !keyManagementAlgorithms && alg2.startsWith("PBES2")) { - throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed'); - } - if (contentEncryptionAlgorithms && !contentEncryptionAlgorithms.has(enc2)) { - throw new JOSEAlgNotAllowed('"enc" (Encryption Algorithm) Header Parameter value not allowed'); - } - let encryptedKey; - if (jwe.encrypted_key !== void 0) { - encryptedKey = decodeBase64url(jwe.encrypted_key, "encrypted_key", JWEInvalid); - } - let resolvedKey = false; - if (typeof key === "function") { - key = await key(parsedProt, jwe); - resolvedKey = true; - } - checkKeyType(alg2 === "dir" ? enc2 : alg2, key, "decrypt"); - const k5 = await normalizeKey(key, alg2); - let cek; - try { - cek = await decryptKeyManagement(alg2, k5, encryptedKey, joseHeader, options); - } catch (err) { - if (err instanceof TypeError || err instanceof JWEInvalid || err instanceof JOSENotSupported) { - throw err; - } - cek = generateCek(enc2); - } - let iv; - let tag3; - if (jwe.iv !== void 0) { - iv = decodeBase64url(jwe.iv, "iv", JWEInvalid); - } - if (jwe.tag !== void 0) { - tag3 = decodeBase64url(jwe.tag, "tag", JWEInvalid); - } - const protectedHeader = jwe.protected !== void 0 ? encode2(jwe.protected) : new Uint8Array(); - let additionalData; - if (jwe.aad !== void 0) { - additionalData = concat(protectedHeader, encode2("."), encode2(jwe.aad)); - } else { - additionalData = protectedHeader; - } - const ciphertext = decodeBase64url(jwe.ciphertext, "ciphertext", JWEInvalid); - const plaintext = await decrypt(enc2, cek, ciphertext, iv, tag3, additionalData); - const result = { plaintext }; - if (joseHeader.zip === "DEF") { - const maxDecompressedLength = options?.maxDecompressedLength ?? 25e4; - if (maxDecompressedLength === 0) { - throw new JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported.'); - } - if (maxDecompressedLength !== Infinity && (!Number.isSafeInteger(maxDecompressedLength) || maxDecompressedLength < 1)) { - throw new TypeError("maxDecompressedLength must be 0, a positive safe integer, or Infinity"); - } - result.plaintext = await decompress(plaintext, maxDecompressedLength).catch((cause) => { - if (cause instanceof JWEInvalid) - throw cause; - throw new JWEInvalid("Failed to decompress plaintext", { cause }); - }); - } - if (jwe.protected !== void 0) { - result.protectedHeader = parsedProt; - } - if (jwe.aad !== void 0) { - result.additionalAuthenticatedData = decodeBase64url(jwe.aad, "aad", JWEInvalid); - } - if (jwe.unprotected !== void 0) { - result.sharedUnprotectedHeader = jwe.unprotected; - } - if (jwe.header !== void 0) { - result.unprotectedHeader = jwe.header; - } - if (resolvedKey) { - return { ...result, key: k5 }; - } - return result; -} -var init_decrypt = __esm({ - "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwe/flattened/decrypt.js"() { - init_base64url(); - init_content_encryption(); - init_helpers(); - init_errors7(); - init_type_checks(); - init_type_checks(); - init_key_management(); - init_buffer_utils(); - init_content_encryption(); - init_validate_crit(); - init_validate_algorithms(); - init_normalize_key(); - init_check_key_type(); - init_deflate(); - } -}); - -// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwe/compact/decrypt.js -async function compactDecrypt(jwe, key, options) { - if (jwe instanceof Uint8Array) { - jwe = decoder.decode(jwe); - } - if (typeof jwe !== "string") { - throw new JWEInvalid("Compact JWE must be a string or Uint8Array"); - } - const { 0: protectedHeader, 1: encryptedKey, 2: iv, 3: ciphertext, 4: tag3, length } = jwe.split("."); - if (length !== 5) { - throw new JWEInvalid("Invalid Compact JWE"); - } - const decrypted = await flattenedDecrypt({ - ciphertext, - iv: iv || void 0, - protected: protectedHeader, - tag: tag3 || void 0, - encrypted_key: encryptedKey || void 0 - }, key, options); - const result = { plaintext: decrypted.plaintext, protectedHeader: decrypted.protectedHeader }; - if (typeof key === "function") { - return { ...result, key: decrypted.key }; - } - return result; -} -var init_decrypt2 = __esm({ - "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwe/compact/decrypt.js"() { - init_decrypt(); - init_errors7(); - init_buffer_utils(); - } -}); - -// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwe/flattened/encrypt.js -var FlattenedEncrypt; -var init_encrypt = __esm({ - "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwe/flattened/encrypt.js"() { - init_base64url(); - init_helpers(); - init_content_encryption(); - init_key_management(); - init_errors7(); - init_type_checks(); - init_buffer_utils(); - init_validate_crit(); - init_normalize_key(); - init_check_key_type(); - init_deflate(); - FlattenedEncrypt = class { - #plaintext; - #protectedHeader; - #sharedUnprotectedHeader; - #unprotectedHeader; - #aad; - #cek; - #iv; - #keyManagementParameters; - constructor(plaintext) { - if (!(plaintext instanceof Uint8Array)) { - throw new TypeError("plaintext must be an instance of Uint8Array"); - } - this.#plaintext = plaintext; - } - setKeyManagementParameters(parameters) { - assertNotSet(this.#keyManagementParameters, "setKeyManagementParameters"); - this.#keyManagementParameters = parameters; - return this; - } - setProtectedHeader(protectedHeader) { - assertNotSet(this.#protectedHeader, "setProtectedHeader"); - this.#protectedHeader = protectedHeader; - return this; - } - setSharedUnprotectedHeader(sharedUnprotectedHeader) { - assertNotSet(this.#sharedUnprotectedHeader, "setSharedUnprotectedHeader"); - this.#sharedUnprotectedHeader = sharedUnprotectedHeader; - return this; - } - setUnprotectedHeader(unprotectedHeader) { - assertNotSet(this.#unprotectedHeader, "setUnprotectedHeader"); - this.#unprotectedHeader = unprotectedHeader; - return this; - } - setAdditionalAuthenticatedData(aad) { - this.#aad = aad; - return this; - } - setContentEncryptionKey(cek) { - assertNotSet(this.#cek, "setContentEncryptionKey"); - this.#cek = cek; - return this; - } - setInitializationVector(iv) { - assertNotSet(this.#iv, "setInitializationVector"); - this.#iv = iv; - return this; - } - async encrypt(key, options) { - if (!this.#protectedHeader && !this.#unprotectedHeader && !this.#sharedUnprotectedHeader) { - throw new JWEInvalid("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()"); - } - if (!isDisjoint(this.#protectedHeader, this.#unprotectedHeader, this.#sharedUnprotectedHeader)) { - throw new JWEInvalid("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint"); - } - const joseHeader = { - ...this.#protectedHeader, - ...this.#unprotectedHeader, - ...this.#sharedUnprotectedHeader - }; - validateCrit(JWEInvalid, /* @__PURE__ */ new Map(), options?.crit, this.#protectedHeader, joseHeader); - if (joseHeader.zip !== void 0 && joseHeader.zip !== "DEF") { - throw new JOSENotSupported('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.'); - } - if (joseHeader.zip !== void 0 && !this.#protectedHeader?.zip) { - throw new JWEInvalid('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.'); - } - const { alg: alg2, enc: enc2 } = joseHeader; - if (typeof alg2 !== "string" || !alg2) { - throw new JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid'); - } - if (typeof enc2 !== "string" || !enc2) { - throw new JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid'); - } - let encryptedKey; - if (this.#cek && (alg2 === "dir" || alg2 === "ECDH-ES")) { - throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${alg2}`); - } - checkKeyType(alg2 === "dir" ? enc2 : alg2, key, "encrypt"); - let cek; - { - let parameters; - const k5 = await normalizeKey(key, alg2); - ({ cek, encryptedKey, parameters } = await encryptKeyManagement(alg2, enc2, k5, this.#cek, this.#keyManagementParameters)); - if (parameters) { - if (options && unprotected in options) { - if (!this.#unprotectedHeader) { - this.setUnprotectedHeader(parameters); - } else { - this.#unprotectedHeader = { ...this.#unprotectedHeader, ...parameters }; - } - } else if (!this.#protectedHeader) { - this.setProtectedHeader(parameters); - } else { - this.#protectedHeader = { ...this.#protectedHeader, ...parameters }; - } - } - } - let additionalData; - let protectedHeaderS; - let protectedHeaderB; - let aadMember; - if (this.#protectedHeader) { - protectedHeaderS = encode3(JSON.stringify(this.#protectedHeader)); - protectedHeaderB = encode2(protectedHeaderS); - } else { - protectedHeaderS = ""; - protectedHeaderB = new Uint8Array(); - } - if (this.#aad) { - aadMember = encode3(this.#aad); - const aadMemberBytes = encode2(aadMember); - additionalData = concat(protectedHeaderB, encode2("."), aadMemberBytes); - } else { - additionalData = protectedHeaderB; - } - let plaintext = this.#plaintext; - if (joseHeader.zip === "DEF") { - plaintext = await compress(plaintext).catch((cause) => { - throw new JWEInvalid("Failed to compress plaintext", { cause }); - }); - } - const { ciphertext, tag: tag3, iv } = await encrypt(enc2, plaintext, cek, this.#iv, additionalData); - const jwe = { - ciphertext: encode3(ciphertext) - }; - if (iv) { - jwe.iv = encode3(iv); - } - if (tag3) { - jwe.tag = encode3(tag3); - } - if (encryptedKey) { - jwe.encrypted_key = encode3(encryptedKey); - } - if (aadMember) { - jwe.aad = aadMember; - } - if (this.#protectedHeader) { - jwe.protected = protectedHeaderS; - } - if (this.#sharedUnprotectedHeader) { - jwe.unprotected = this.#sharedUnprotectedHeader; - } - if (this.#unprotectedHeader) { - jwe.header = this.#unprotectedHeader; - } - return jwe; - } - }; - } -}); - -// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/flattened/verify.js -async function flattenedVerify(jws, key, options) { - if (!isObject(jws)) { - throw new JWSInvalid("Flattened JWS must be an object"); - } - if (jws.protected === void 0 && jws.header === void 0) { - throw new JWSInvalid('Flattened JWS must have either of the "protected" or "header" members'); - } - if (jws.protected !== void 0 && typeof jws.protected !== "string") { - throw new JWSInvalid("JWS Protected Header incorrect type"); - } - if (jws.payload === void 0) { - throw new JWSInvalid("JWS Payload missing"); - } - if (typeof jws.signature !== "string") { - throw new JWSInvalid("JWS Signature missing or incorrect type"); - } - if (jws.header !== void 0 && !isObject(jws.header)) { - throw new JWSInvalid("JWS Unprotected Header incorrect type"); - } - let parsedProt = {}; - if (jws.protected) { - try { - const protectedHeader = decode2(jws.protected); - parsedProt = JSON.parse(decoder.decode(protectedHeader)); - } catch { - throw new JWSInvalid("JWS Protected Header is invalid"); - } - } - if (!isDisjoint(parsedProt, jws.header)) { - throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint"); - } - const joseHeader = { - ...parsedProt, - ...jws.header - }; - const extensions = validateCrit(JWSInvalid, /* @__PURE__ */ new Map([["b64", true]]), options?.crit, parsedProt, joseHeader); - let b64 = true; - if (extensions.has("b64")) { - b64 = parsedProt.b64; - if (typeof b64 !== "boolean") { - throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean'); - } - } - const { alg: alg2 } = joseHeader; - if (typeof alg2 !== "string" || !alg2) { - throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid'); - } - const algorithms = options && validateAlgorithms("algorithms", options.algorithms); - if (algorithms && !algorithms.has(alg2)) { - throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed'); - } - if (b64) { - if (typeof jws.payload !== "string") { - throw new JWSInvalid("JWS Payload must be a string"); - } - } else if (typeof jws.payload !== "string" && !(jws.payload instanceof Uint8Array)) { - throw new JWSInvalid("JWS Payload must be a string or an Uint8Array instance"); - } - let resolvedKey = false; - if (typeof key === "function") { - key = await key(parsedProt, jws); - resolvedKey = true; - } - checkKeyType(alg2, key, "verify"); - const data2 = concat(jws.protected !== void 0 ? encode2(jws.protected) : new Uint8Array(), encode2("."), typeof jws.payload === "string" ? b64 ? encode2(jws.payload) : encoder.encode(jws.payload) : jws.payload); - const signature = decodeBase64url(jws.signature, "signature", JWSInvalid); - const k5 = await normalizeKey(key, alg2); - const verified = await verify(alg2, k5, signature, data2); - if (!verified) { - throw new JWSSignatureVerificationFailed(); - } - let payload2; - if (b64) { - payload2 = decodeBase64url(jws.payload, "payload", JWSInvalid); - } else if (typeof jws.payload === "string") { - payload2 = encoder.encode(jws.payload); - } else { - payload2 = jws.payload; - } - const result = { payload: payload2 }; - if (jws.protected !== void 0) { - result.protectedHeader = parsedProt; - } - if (jws.header !== void 0) { - result.unprotectedHeader = jws.header; - } - if (resolvedKey) { - return { ...result, key: k5 }; - } - return result; -} -var init_verify = __esm({ - "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/flattened/verify.js"() { - init_base64url(); - init_signing(); - init_errors7(); - init_buffer_utils(); - init_helpers(); - init_type_checks(); - init_type_checks(); - init_check_key_type(); - init_validate_crit(); - init_validate_algorithms(); - init_normalize_key(); - } -}); - -// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/compact/verify.js -async function compactVerify(jws, key, options) { - if (jws instanceof Uint8Array) { - jws = decoder.decode(jws); - } - if (typeof jws !== "string") { - throw new JWSInvalid("Compact JWS must be a string or Uint8Array"); - } - const { 0: protectedHeader, 1: payload2, 2: signature, length } = jws.split("."); - if (length !== 3) { - throw new JWSInvalid("Invalid Compact JWS"); - } - const verified = await flattenedVerify({ payload: payload2, protected: protectedHeader, signature }, key, options); - const result = { payload: verified.payload, protectedHeader: verified.protectedHeader }; - if (typeof key === "function") { - return { ...result, key: verified.key }; - } - return result; -} -var init_verify2 = __esm({ - "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/compact/verify.js"() { - init_verify(); - init_errors7(); - init_buffer_utils(); - } -}); - -// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/jwt_claims_set.js -function secs(str) { - const matched = REGEX.exec(str); - if (!matched || matched[4] && matched[1]) { - throw new TypeError("Invalid time period format"); - } - const value = parseFloat(matched[2]); - const unit = matched[3].toLowerCase(); - let numericDate; - switch (unit) { - case "sec": - case "secs": - case "second": - case "seconds": - case "s": - numericDate = Math.round(value); - break; - case "minute": - case "minutes": - case "min": - case "mins": - case "m": - numericDate = Math.round(value * minute); - break; - case "hour": - case "hours": - case "hr": - case "hrs": - case "h": - numericDate = Math.round(value * hour); - break; - case "day": - case "days": - case "d": - numericDate = Math.round(value * day); - break; - case "week": - case "weeks": - case "w": - numericDate = Math.round(value * week); - break; - default: - numericDate = Math.round(value * year2); - break; - } - if (matched[1] === "-" || matched[4] === "ago") { - return -numericDate; - } - return numericDate; -} -function validateInput(label, input) { - if (!Number.isFinite(input)) { - throw new TypeError(`Invalid ${label} input`); - } - return input; -} -function validateClaimsSet(protectedHeader, encodedPayload, options = {}) { - let payload2; - try { - payload2 = JSON.parse(decoder.decode(encodedPayload)); - } catch { - } - if (!isObject(payload2)) { - throw new JWTInvalid("JWT Claims Set must be a top-level JSON object"); - } - const { typ } = options; - if (typ && (typeof protectedHeader.typ !== "string" || normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ))) { - throw new JWTClaimValidationFailed('unexpected "typ" JWT header value', payload2, "typ", "check_failed"); - } - const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options; - const presenceCheck = [...requiredClaims]; - if (maxTokenAge !== void 0) - presenceCheck.push("iat"); - if (audience !== void 0) - presenceCheck.push("aud"); - if (subject !== void 0) - presenceCheck.push("sub"); - if (issuer !== void 0) - presenceCheck.push("iss"); - for (const claim of new Set(presenceCheck.reverse())) { - if (!(claim in payload2)) { - throw new JWTClaimValidationFailed(`missing required "${claim}" claim`, payload2, claim, "missing"); - } - } - if (issuer && !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload2.iss)) { - throw new JWTClaimValidationFailed('unexpected "iss" claim value', payload2, "iss", "check_failed"); - } - if (subject && payload2.sub !== subject) { - throw new JWTClaimValidationFailed('unexpected "sub" claim value', payload2, "sub", "check_failed"); - } - if (audience && !checkAudiencePresence(payload2.aud, typeof audience === "string" ? [audience] : audience)) { - throw new JWTClaimValidationFailed('unexpected "aud" claim value', payload2, "aud", "check_failed"); - } - let tolerance; - switch (typeof options.clockTolerance) { - case "string": - tolerance = secs(options.clockTolerance); - break; - case "number": - tolerance = options.clockTolerance; - break; - case "undefined": - tolerance = 0; - break; - default: - throw new TypeError("Invalid clockTolerance option type"); - } - const { currentDate } = options; - const now2 = epoch(currentDate || /* @__PURE__ */ new Date()); - if ((payload2.iat !== void 0 || maxTokenAge) && typeof payload2.iat !== "number") { - throw new JWTClaimValidationFailed('"iat" claim must be a number', payload2, "iat", "invalid"); - } - if (payload2.nbf !== void 0) { - if (typeof payload2.nbf !== "number") { - throw new JWTClaimValidationFailed('"nbf" claim must be a number', payload2, "nbf", "invalid"); - } - if (payload2.nbf > now2 + tolerance) { - throw new JWTClaimValidationFailed('"nbf" claim timestamp check failed', payload2, "nbf", "check_failed"); - } - } - if (payload2.exp !== void 0) { - if (typeof payload2.exp !== "number") { - throw new JWTClaimValidationFailed('"exp" claim must be a number', payload2, "exp", "invalid"); - } - if (payload2.exp <= now2 - tolerance) { - throw new JWTExpired('"exp" claim timestamp check failed', payload2, "exp", "check_failed"); - } - } - if (maxTokenAge) { - const age = now2 - payload2.iat; - const max = typeof maxTokenAge === "number" ? maxTokenAge : secs(maxTokenAge); - if (age - tolerance > max) { - throw new JWTExpired('"iat" claim timestamp check failed (too far in the past)', payload2, "iat", "check_failed"); - } - if (age < 0 - tolerance) { - throw new JWTClaimValidationFailed('"iat" claim timestamp check failed (it should be in the past)', payload2, "iat", "check_failed"); - } - } - return payload2; -} -var epoch, minute, hour, day, week, year2, REGEX, normalizeTyp, checkAudiencePresence, JWTClaimsBuilder; -var init_jwt_claims_set = __esm({ - "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/jwt_claims_set.js"() { - init_errors7(); - init_buffer_utils(); - init_type_checks(); - epoch = (date7) => Math.floor(date7.getTime() / 1e3); - minute = 60; - hour = minute * 60; - day = hour * 24; - week = day * 7; - year2 = day * 365.25; - REGEX = /^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i; - normalizeTyp = (value) => { - if (value.includes("/")) { - return value.toLowerCase(); - } - return `application/${value.toLowerCase()}`; - }; - checkAudiencePresence = (audPayload, audOption) => { - if (typeof audPayload === "string") { - return audOption.includes(audPayload); - } - if (Array.isArray(audPayload)) { - return audOption.some(Set.prototype.has.bind(new Set(audPayload))); - } - return false; - }; - JWTClaimsBuilder = class { - #payload; - constructor(payload2) { - if (!isObject(payload2)) { - throw new TypeError("JWT Claims Set MUST be an object"); - } - this.#payload = structuredClone(payload2); - } - data() { - return encoder.encode(JSON.stringify(this.#payload)); - } - get iss() { - return this.#payload.iss; - } - set iss(value) { - this.#payload.iss = value; - } - get sub() { - return this.#payload.sub; - } - set sub(value) { - this.#payload.sub = value; - } - get aud() { - return this.#payload.aud; - } - set aud(value) { - this.#payload.aud = value; - } - set jti(value) { - this.#payload.jti = value; - } - set nbf(value) { - if (typeof value === "number") { - this.#payload.nbf = validateInput("setNotBefore", value); - } else if (value instanceof Date) { - this.#payload.nbf = validateInput("setNotBefore", epoch(value)); - } else { - this.#payload.nbf = epoch(/* @__PURE__ */ new Date()) + secs(value); - } - } - set exp(value) { - if (typeof value === "number") { - this.#payload.exp = validateInput("setExpirationTime", value); - } else if (value instanceof Date) { - this.#payload.exp = validateInput("setExpirationTime", epoch(value)); - } else { - this.#payload.exp = epoch(/* @__PURE__ */ new Date()) + secs(value); - } - } - set iat(value) { - if (value === void 0) { - this.#payload.iat = epoch(/* @__PURE__ */ new Date()); - } else if (value instanceof Date) { - this.#payload.iat = validateInput("setIssuedAt", epoch(value)); - } else if (typeof value === "string") { - this.#payload.iat = validateInput("setIssuedAt", epoch(/* @__PURE__ */ new Date()) + secs(value)); - } else { - this.#payload.iat = validateInput("setIssuedAt", value); - } - } - }; - } -}); - -// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwt/verify.js -async function jwtVerify(jwt2, key, options) { - const verified = await compactVerify(jwt2, key, options); - if (verified.protectedHeader.crit?.includes("b64") && verified.protectedHeader.b64 === false) { - throw new JWTInvalid("JWTs MUST NOT use unencoded payload"); - } - const payload2 = validateClaimsSet(verified.protectedHeader, verified.payload, options); - const result = { payload: payload2, protectedHeader: verified.protectedHeader }; - if (typeof key === "function") { - return { ...result, key: verified.key }; - } - return result; -} -var init_verify3 = __esm({ - "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwt/verify.js"() { - init_verify2(); - init_jwt_claims_set(); - init_errors7(); - } -}); - -// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwt/decrypt.js -async function jwtDecrypt(jwt2, key, options) { - const decrypted = await compactDecrypt(jwt2, key, options); - const payload2 = validateClaimsSet(decrypted.protectedHeader, decrypted.plaintext, options); - const { protectedHeader } = decrypted; - if (protectedHeader.iss !== void 0 && protectedHeader.iss !== payload2.iss) { - throw new JWTClaimValidationFailed('replicated "iss" claim header parameter mismatch', payload2, "iss", "mismatch"); - } - if (protectedHeader.sub !== void 0 && protectedHeader.sub !== payload2.sub) { - throw new JWTClaimValidationFailed('replicated "sub" claim header parameter mismatch', payload2, "sub", "mismatch"); - } - if (protectedHeader.aud !== void 0 && JSON.stringify(protectedHeader.aud) !== JSON.stringify(payload2.aud)) { - throw new JWTClaimValidationFailed('replicated "aud" claim header parameter mismatch', payload2, "aud", "mismatch"); - } - const result = { payload: payload2, protectedHeader }; - if (typeof key === "function") { - return { ...result, key: decrypted.key }; - } - return result; -} -var init_decrypt3 = __esm({ - "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwt/decrypt.js"() { - init_decrypt2(); - init_jwt_claims_set(); - init_errors7(); - } -}); - -// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwe/compact/encrypt.js -var CompactEncrypt; -var init_encrypt2 = __esm({ - "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwe/compact/encrypt.js"() { - init_encrypt(); - CompactEncrypt = class { - #flattened; - constructor(plaintext) { - this.#flattened = new FlattenedEncrypt(plaintext); - } - setContentEncryptionKey(cek) { - this.#flattened.setContentEncryptionKey(cek); - return this; - } - setInitializationVector(iv) { - this.#flattened.setInitializationVector(iv); - return this; - } - setProtectedHeader(protectedHeader) { - this.#flattened.setProtectedHeader(protectedHeader); - return this; - } - setKeyManagementParameters(parameters) { - this.#flattened.setKeyManagementParameters(parameters); - return this; - } - async encrypt(key, options) { - const jwe = await this.#flattened.encrypt(key, options); - return [jwe.protected, jwe.encrypted_key, jwe.iv, jwe.ciphertext, jwe.tag].join("."); - } - }; - } -}); - -// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/flattened/sign.js -var FlattenedSign; -var init_sign = __esm({ - "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/flattened/sign.js"() { - init_base64url(); - init_signing(); - init_type_checks(); - init_errors7(); - init_buffer_utils(); - init_check_key_type(); - init_validate_crit(); - init_normalize_key(); - init_helpers(); - FlattenedSign = class { - #payload; - #protectedHeader; - #unprotectedHeader; - constructor(payload2) { - if (!(payload2 instanceof Uint8Array)) { - throw new TypeError("payload must be an instance of Uint8Array"); - } - this.#payload = payload2; - } - setProtectedHeader(protectedHeader) { - assertNotSet(this.#protectedHeader, "setProtectedHeader"); - this.#protectedHeader = protectedHeader; - return this; - } - setUnprotectedHeader(unprotectedHeader) { - assertNotSet(this.#unprotectedHeader, "setUnprotectedHeader"); - this.#unprotectedHeader = unprotectedHeader; - return this; - } - async sign(key, options) { - if (!this.#protectedHeader && !this.#unprotectedHeader) { - throw new JWSInvalid("either setProtectedHeader or setUnprotectedHeader must be called before #sign()"); - } - if (!isDisjoint(this.#protectedHeader, this.#unprotectedHeader)) { - throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint"); - } - const joseHeader = { - ...this.#protectedHeader, - ...this.#unprotectedHeader - }; - const extensions = validateCrit(JWSInvalid, /* @__PURE__ */ new Map([["b64", true]]), options?.crit, this.#protectedHeader, joseHeader); - let b64 = true; - if (extensions.has("b64")) { - b64 = this.#protectedHeader.b64; - if (typeof b64 !== "boolean") { - throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean'); - } - } - const { alg: alg2 } = joseHeader; - if (typeof alg2 !== "string" || !alg2) { - throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid'); - } - checkKeyType(alg2, key, "sign"); - let payloadS; - let payloadB; - if (b64) { - payloadS = encode3(this.#payload); - payloadB = encode2(payloadS); - } else { - payloadB = this.#payload; - payloadS = ""; - } - let protectedHeaderString; - let protectedHeaderBytes; - if (this.#protectedHeader) { - protectedHeaderString = encode3(JSON.stringify(this.#protectedHeader)); - protectedHeaderBytes = encode2(protectedHeaderString); - } else { - protectedHeaderString = ""; - protectedHeaderBytes = new Uint8Array(); - } - const data2 = concat(protectedHeaderBytes, encode2("."), payloadB); - const k5 = await normalizeKey(key, alg2); - const signature = await sign(alg2, k5, data2); - const jws = { - signature: encode3(signature), - payload: payloadS - }; - if (this.#unprotectedHeader) { - jws.header = this.#unprotectedHeader; - } - if (this.#protectedHeader) { - jws.protected = protectedHeaderString; - } - return jws; - } - }; - } -}); - -// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/compact/sign.js -var CompactSign; -var init_sign2 = __esm({ - "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/compact/sign.js"() { - init_sign(); - CompactSign = class { - #flattened; - constructor(payload2) { - this.#flattened = new FlattenedSign(payload2); - } - setProtectedHeader(protectedHeader) { - this.#flattened.setProtectedHeader(protectedHeader); - return this; - } - async sign(key, options) { - const jws = await this.#flattened.sign(key, options); - if (jws.payload === void 0) { - throw new TypeError("use the flattened module for creating JWS with b64: false"); - } - return `${jws.protected}.${jws.payload}.${jws.signature}`; - } - }; - } -}); - -// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwt/sign.js -var SignJWT; -var init_sign3 = __esm({ - "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwt/sign.js"() { - init_sign2(); - init_errors7(); - init_jwt_claims_set(); - SignJWT = class { - #protectedHeader; - #jwt; - constructor(payload2 = {}) { - this.#jwt = new JWTClaimsBuilder(payload2); - } - setIssuer(issuer) { - this.#jwt.iss = issuer; - return this; - } - setSubject(subject) { - this.#jwt.sub = subject; - return this; - } - setAudience(audience) { - this.#jwt.aud = audience; - return this; - } - setJti(jwtId) { - this.#jwt.jti = jwtId; - return this; - } - setNotBefore(input) { - this.#jwt.nbf = input; - return this; - } - setExpirationTime(input) { - this.#jwt.exp = input; - return this; - } - setIssuedAt(input) { - this.#jwt.iat = input; - return this; - } - setProtectedHeader(protectedHeader) { - this.#protectedHeader = protectedHeader; - return this; - } - async sign(key, options) { - const sig = new CompactSign(this.#jwt.data()); - sig.setProtectedHeader(this.#protectedHeader); - if (Array.isArray(this.#protectedHeader?.crit) && this.#protectedHeader.crit.includes("b64") && this.#protectedHeader.b64 === false) { - throw new JWTInvalid("JWTs MUST NOT use unencoded payload"); - } - return sig.sign(key, options); - } - }; - } -}); - -// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwt/encrypt.js -var EncryptJWT; -var init_encrypt3 = __esm({ - "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwt/encrypt.js"() { - init_encrypt2(); - init_jwt_claims_set(); - init_helpers(); - EncryptJWT = class { - #cek; - #iv; - #keyManagementParameters; - #protectedHeader; - #replicateIssuerAsHeader; - #replicateSubjectAsHeader; - #replicateAudienceAsHeader; - #jwt; - constructor(payload2 = {}) { - this.#jwt = new JWTClaimsBuilder(payload2); - } - setIssuer(issuer) { - this.#jwt.iss = issuer; - return this; - } - setSubject(subject) { - this.#jwt.sub = subject; - return this; - } - setAudience(audience) { - this.#jwt.aud = audience; - return this; - } - setJti(jwtId) { - this.#jwt.jti = jwtId; - return this; - } - setNotBefore(input) { - this.#jwt.nbf = input; - return this; - } - setExpirationTime(input) { - this.#jwt.exp = input; - return this; - } - setIssuedAt(input) { - this.#jwt.iat = input; - return this; - } - setProtectedHeader(protectedHeader) { - assertNotSet(this.#protectedHeader, "setProtectedHeader"); - this.#protectedHeader = protectedHeader; - return this; - } - setKeyManagementParameters(parameters) { - assertNotSet(this.#keyManagementParameters, "setKeyManagementParameters"); - this.#keyManagementParameters = parameters; - return this; - } - setContentEncryptionKey(cek) { - assertNotSet(this.#cek, "setContentEncryptionKey"); - this.#cek = cek; - return this; - } - setInitializationVector(iv) { - assertNotSet(this.#iv, "setInitializationVector"); - this.#iv = iv; - return this; - } - replicateIssuerAsHeader() { - this.#replicateIssuerAsHeader = true; - return this; - } - replicateSubjectAsHeader() { - this.#replicateSubjectAsHeader = true; - return this; - } - replicateAudienceAsHeader() { - this.#replicateAudienceAsHeader = true; - return this; - } - async encrypt(key, options) { - const enc2 = new CompactEncrypt(this.#jwt.data()); - if (this.#protectedHeader && (this.#replicateIssuerAsHeader || this.#replicateSubjectAsHeader || this.#replicateAudienceAsHeader)) { - this.#protectedHeader = { - ...this.#protectedHeader, - iss: this.#replicateIssuerAsHeader ? this.#jwt.iss : void 0, - sub: this.#replicateSubjectAsHeader ? this.#jwt.sub : void 0, - aud: this.#replicateAudienceAsHeader ? this.#jwt.aud : void 0 - }; - } - enc2.setProtectedHeader(this.#protectedHeader); - if (this.#iv) { - enc2.setInitializationVector(this.#iv); - } - if (this.#cek) { - enc2.setContentEncryptionKey(this.#cek); - } - if (this.#keyManagementParameters) { - enc2.setKeyManagementParameters(this.#keyManagementParameters); - } - return enc2.encrypt(key, options); - } - }; - } -}); - -// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwk/thumbprint.js -async function calculateJwkThumbprint(key, digestAlgorithm) { - let jwk; - if (isJWK(key)) { - jwk = key; - } else if (isKeyLike(key)) { - jwk = await exportJWK(key); - } else { - throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject", "JSON Web Key")); - } - digestAlgorithm ??= "sha256"; - if (digestAlgorithm !== "sha256" && digestAlgorithm !== "sha384" && digestAlgorithm !== "sha512") { - throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"'); - } - let components; - switch (jwk.kty) { - case "AKP": - check(jwk.alg, '"alg" (Algorithm) Parameter'); - check(jwk.pub, '"pub" (Public key) Parameter'); - components = { alg: jwk.alg, kty: jwk.kty, pub: jwk.pub }; - break; - case "EC": - check(jwk.crv, '"crv" (Curve) Parameter'); - check(jwk.x, '"x" (X Coordinate) Parameter'); - check(jwk.y, '"y" (Y Coordinate) Parameter'); - components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y }; - break; - case "OKP": - check(jwk.crv, '"crv" (Subtype of Key Pair) Parameter'); - check(jwk.x, '"x" (Public Key) Parameter'); - components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x }; - break; - case "RSA": - check(jwk.e, '"e" (Exponent) Parameter'); - check(jwk.n, '"n" (Modulus) Parameter'); - components = { e: jwk.e, kty: jwk.kty, n: jwk.n }; - break; - case "oct": - check(jwk.k, '"k" (Key Value) Parameter'); - components = { k: jwk.k, kty: jwk.kty }; - break; - default: - throw new JOSENotSupported('"kty" (Key Type) Parameter missing or unsupported'); - } - const data2 = encode2(JSON.stringify(components)); - return encode3(await digest(digestAlgorithm, data2)); -} -var check; -var init_thumbprint = __esm({ - "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwk/thumbprint.js"() { - init_helpers(); - init_base64url(); - init_errors7(); - init_buffer_utils(); - init_is_key_like(); - init_type_checks(); - init_export(); - init_invalid_key_input(); - check = (value, description) => { - if (typeof value !== "string" || !value) { - throw new JWKInvalid(`${description} missing or invalid`); - } - }; - } -}); - -// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwks/local.js -function getKtyFromAlg(alg2) { - switch (typeof alg2 === "string" && alg2.slice(0, 2)) { - case "RS": - case "PS": - return "RSA"; - case "ES": - return "EC"; - case "Ed": - return "OKP"; - case "ML": - return "AKP"; - default: - throw new JOSENotSupported('Unsupported "alg" value for a JSON Web Key Set'); - } -} -function isJWKSLike(jwks) { - return jwks && typeof jwks === "object" && Array.isArray(jwks.keys) && jwks.keys.every(isJWKLike); -} -function isJWKLike(key) { - return isObject(key); -} -async function importWithAlgCache(cache7, jwk, alg2) { - const cached4 = cache7.get(jwk) || cache7.set(jwk, {}).get(jwk); - if (cached4[alg2] === void 0) { - const key = await importJWK({ ...jwk, ext: true }, alg2); - if (key instanceof Uint8Array || key.type !== "public") { - throw new JWKSInvalid("JSON Web Key Set members must be public keys"); - } - cached4[alg2] = key; - } - return cached4[alg2]; -} -function createLocalJWKSet(jwks) { - const set2 = new LocalJWKSet(jwks); - const localJWKSet = async (protectedHeader, token) => set2.getKey(protectedHeader, token); - Object.defineProperties(localJWKSet, { - jwks: { - value: () => structuredClone(set2.jwks()), - enumerable: false, - configurable: false, - writable: false - } - }); - return localJWKSet; -} -var LocalJWKSet; -var init_local = __esm({ - "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwks/local.js"() { - init_import(); - init_errors7(); - init_type_checks(); - LocalJWKSet = class { - #jwks; - #cached = /* @__PURE__ */ new WeakMap(); - constructor(jwks) { - if (!isJWKSLike(jwks)) { - throw new JWKSInvalid("JSON Web Key Set malformed"); - } - this.#jwks = structuredClone(jwks); - } - jwks() { - return this.#jwks; - } - async getKey(protectedHeader, token) { - const { alg: alg2, kid } = { ...protectedHeader, ...token?.header }; - const kty = getKtyFromAlg(alg2); - const candidates = this.#jwks.keys.filter((jwk2) => { - let candidate = kty === jwk2.kty; - if (candidate && typeof kid === "string") { - candidate = kid === jwk2.kid; - } - if (candidate && (typeof jwk2.alg === "string" || kty === "AKP")) { - candidate = alg2 === jwk2.alg; - } - if (candidate && typeof jwk2.use === "string") { - candidate = jwk2.use === "sig"; - } - if (candidate && Array.isArray(jwk2.key_ops)) { - candidate = jwk2.key_ops.includes("verify"); - } - if (candidate) { - switch (alg2) { - case "ES256": - candidate = jwk2.crv === "P-256"; - break; - case "ES384": - candidate = jwk2.crv === "P-384"; - break; - case "ES512": - candidate = jwk2.crv === "P-521"; - break; - case "Ed25519": - case "EdDSA": - candidate = jwk2.crv === "Ed25519"; - break; - } - } - return candidate; - }); - const { 0: jwk, length } = candidates; - if (length === 0) { - throw new JWKSNoMatchingKey(); - } - if (length !== 1) { - const error50 = new JWKSMultipleMatchingKeys(); - const _cached = this.#cached; - error50[Symbol.asyncIterator] = async function* () { - for (const jwk2 of candidates) { - try { - yield await importWithAlgCache(_cached, jwk2, alg2); - } catch { - } - } - }; - throw error50; - } - return importWithAlgCache(this.#cached, jwk, alg2); - } - }; - } -}); - -// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwks/remote.js -function isCloudflareWorkers() { - return typeof WebSocketPair !== "undefined" || typeof navigator !== "undefined" && navigator.userAgent === "Cloudflare-Workers" || typeof EdgeRuntime !== "undefined" && EdgeRuntime === "vercel"; -} -async function fetchJwks(url2, headers, signal, fetchImpl = fetch) { - const response = await fetchImpl(url2, { - method: "GET", - signal, - redirect: "manual", - headers - }).catch((err) => { - if (err.name === "TimeoutError") { - throw new JWKSTimeout(); - } - throw err; - }); - if (response.status !== 200) { - throw new JOSEError("Expected 200 OK from the JSON Web Key Set HTTP response"); - } - try { - return await response.json(); - } catch { - throw new JOSEError("Failed to parse the JSON Web Key Set HTTP response as JSON"); - } -} -function isFreshJwksCache(input, cacheMaxAge) { - if (typeof input !== "object" || input === null) { - return false; - } - if (!("uat" in input) || typeof input.uat !== "number" || Date.now() - input.uat >= cacheMaxAge) { - return false; - } - if (!("jwks" in input) || !isObject(input.jwks) || !Array.isArray(input.jwks.keys) || !Array.prototype.every.call(input.jwks.keys, isObject)) { - return false; - } - return true; -} -function createRemoteJWKSet(url2, options) { - const set2 = new RemoteJWKSet(url2, options); - const remoteJWKSet = async (protectedHeader, token) => set2.getKey(protectedHeader, token); - Object.defineProperties(remoteJWKSet, { - coolingDown: { - get: () => set2.coolingDown(), - enumerable: true, - configurable: false - }, - fresh: { - get: () => set2.fresh(), - enumerable: true, - configurable: false - }, - reload: { - value: () => set2.reload(), - enumerable: true, - configurable: false, - writable: false - }, - reloading: { - get: () => set2.pendingFetch(), - enumerable: true, - configurable: false - }, - jwks: { - value: () => set2.jwks(), - enumerable: true, - configurable: false, - writable: false - } - }); - return remoteJWKSet; -} -var USER_AGENT, customFetch, jwksCache, RemoteJWKSet; -var init_remote = __esm({ - "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwks/remote.js"() { - init_errors7(); - init_local(); - init_type_checks(); - if (typeof navigator === "undefined" || !navigator.userAgent?.startsWith?.("Mozilla/5.0 ")) { - const NAME = "jose"; - const VERSION = "v6.2.2"; - USER_AGENT = `${NAME}/${VERSION}`; - } - customFetch = /* @__PURE__ */ Symbol(); - jwksCache = /* @__PURE__ */ Symbol(); - RemoteJWKSet = class { - #url; - #timeoutDuration; - #cooldownDuration; - #cacheMaxAge; - #jwksTimestamp; - #pendingFetch; - #headers; - #customFetch; - #local; - #cache; - constructor(url2, options) { - if (!(url2 instanceof URL)) { - throw new TypeError("url must be an instance of URL"); - } - this.#url = new URL(url2.href); - this.#timeoutDuration = typeof options?.timeoutDuration === "number" ? options?.timeoutDuration : 5e3; - this.#cooldownDuration = typeof options?.cooldownDuration === "number" ? options?.cooldownDuration : 3e4; - this.#cacheMaxAge = typeof options?.cacheMaxAge === "number" ? options?.cacheMaxAge : 6e5; - this.#headers = new Headers(options?.headers); - if (USER_AGENT && !this.#headers.has("User-Agent")) { - this.#headers.set("User-Agent", USER_AGENT); - } - if (!this.#headers.has("accept")) { - this.#headers.set("accept", "application/json"); - this.#headers.append("accept", "application/jwk-set+json"); - } - this.#customFetch = options?.[customFetch]; - if (options?.[jwksCache] !== void 0) { - this.#cache = options?.[jwksCache]; - if (isFreshJwksCache(options?.[jwksCache], this.#cacheMaxAge)) { - this.#jwksTimestamp = this.#cache.uat; - this.#local = createLocalJWKSet(this.#cache.jwks); - } - } - } - pendingFetch() { - return !!this.#pendingFetch; - } - coolingDown() { - return typeof this.#jwksTimestamp === "number" ? Date.now() < this.#jwksTimestamp + this.#cooldownDuration : false; - } - fresh() { - return typeof this.#jwksTimestamp === "number" ? Date.now() < this.#jwksTimestamp + this.#cacheMaxAge : false; - } - jwks() { - return this.#local?.jwks(); - } - async getKey(protectedHeader, token) { - if (!this.#local || !this.fresh()) { - await this.reload(); - } - try { - return await this.#local(protectedHeader, token); - } catch (err) { - if (err instanceof JWKSNoMatchingKey) { - if (this.coolingDown() === false) { - await this.reload(); - return this.#local(protectedHeader, token); - } - } - throw err; - } - } - async reload() { - if (this.#pendingFetch && isCloudflareWorkers()) { - this.#pendingFetch = void 0; - } - this.#pendingFetch ||= fetchJwks(this.#url.href, this.#headers, AbortSignal.timeout(this.#timeoutDuration), this.#customFetch).then((json3) => { - this.#local = createLocalJWKSet(json3); - if (this.#cache) { - this.#cache.uat = Date.now(); - this.#cache.jwks = json3; - } - this.#jwksTimestamp = Date.now(); - this.#pendingFetch = void 0; - }).catch((err) => { - this.#pendingFetch = void 0; - throw err; - }); - await this.#pendingFetch; - } - }; - } -}); - -// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/util/decode_protected_header.js -function decodeProtectedHeader(token) { - let protectedB64u; - if (typeof token === "string") { - const parts = token.split("."); - if (parts.length === 3 || parts.length === 5) { - ; - [protectedB64u] = parts; - } - } else if (typeof token === "object" && token) { - if ("protected" in token) { - protectedB64u = token.protected; - } else { - throw new TypeError("Token does not contain a Protected Header"); - } - } - try { - if (typeof protectedB64u !== "string" || !protectedB64u) { - throw new Error(); - } - const result = JSON.parse(decoder.decode(decode2(protectedB64u))); - if (!isObject(result)) { - throw new Error(); - } - return result; - } catch { - throw new TypeError("Invalid Token or Protected Header formatting"); - } -} -var init_decode_protected_header = __esm({ - "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/util/decode_protected_header.js"() { - init_base64url(); - init_buffer_utils(); - init_type_checks(); - } -}); - -// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/util/decode_jwt.js -function decodeJwt(jwt2) { - if (typeof jwt2 !== "string") - throw new JWTInvalid("JWTs must use Compact JWS serialization, JWT must be a string"); - const { 1: payload2, length } = jwt2.split("."); - if (length === 5) - throw new JWTInvalid("Only JWTs using Compact JWS serialization can be decoded"); - if (length !== 3) - throw new JWTInvalid("Invalid JWT"); - if (!payload2) - throw new JWTInvalid("JWTs must contain a payload"); - let decoded; - try { - decoded = decode2(payload2); - } catch { - throw new JWTInvalid("Failed to base64url decode the payload"); - } - let result; - try { - result = JSON.parse(decoder.decode(decoded)); - } catch { - throw new JWTInvalid("Failed to parse the decoded payload as JSON"); - } - if (!isObject(result)) - throw new JWTInvalid("Invalid JWT Claims Set"); - return result; -} -var init_decode_jwt = __esm({ - "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/util/decode_jwt.js"() { - init_base64url(); - init_buffer_utils(); - init_type_checks(); - init_errors7(); - } -}); - -// node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/index.js -var init_webapi = __esm({ - "node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/index.js"() { - init_verify3(); - init_decrypt3(); - init_sign3(); - init_encrypt3(); - init_thumbprint(); - init_remote(); - init_import(); - init_decode_protected_header(); - init_decode_jwt(); - init_base64url(); - } -}); - -// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/crypto/jwt.mjs -async function signJWT(payload2, secret, expiresIn = 3600) { - return await new SignJWT(payload2).setProtectedHeader({ alg: "HS256" }).setIssuedAt().setExpirationTime(Math.floor(Date.now() / 1e3) + expiresIn).sign(new TextEncoder().encode(secret)); -} -async function verifyJWT(token, secret) { - try { - return (await jwtVerify(token, new TextEncoder().encode(secret))).payload; - } catch { - return null; - } -} -async function symmetricEncodeJWT(payload2, secret, salt, expiresIn = 3600) { - const encryptionSecret = hkdf(sha2562, new TextEncoder().encode(secret), new TextEncoder().encode(salt), info, 64); - const thumbprint = await calculateJwkThumbprint({ - kty: "oct", - k: base64url_exports.encode(encryptionSecret) - }, "sha256"); - return await new EncryptJWT(payload2).setProtectedHeader({ - alg, - enc, - kid: thumbprint - }).setIssuedAt().setExpirationTime(now() + expiresIn).setJti(crypto.randomUUID()).encrypt(encryptionSecret); -} -async function symmetricDecodeJWT(token, secret, salt) { - if (!token) return null; - try { - const { payload: payload2 } = await jwtDecrypt(token, async ({ kid }) => { - const encryptionSecret = hkdf(sha2562, new TextEncoder().encode(secret), new TextEncoder().encode(salt), info, 64); - if (kid === void 0) return encryptionSecret; - if (kid === await calculateJwkThumbprint({ - kty: "oct", - k: base64url_exports.encode(encryptionSecret) - }, "sha256")) return encryptionSecret; - throw new Error("no matching decryption secret"); - }, { - clockTolerance: 15, - keyManagementAlgorithms: [alg], - contentEncryptionAlgorithms: [enc, "A256GCM"] - }); - return payload2; - } catch { - return null; - } -} -var info, now, alg, enc; -var init_jwt = __esm({ - "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/crypto/jwt.mjs"() { - init_hkdf(); - init_sha2(); - init_webapi(); - info = new Uint8Array([ - 66, - 101, - 116, - 116, - 101, - 114, - 65, - 117, - 116, - 104, - 46, - 106, - 115, - 32, - 71, - 101, - 110, - 101, - 114, - 97, - 116, - 101, - 100, - 32, - 69, - 110, - 99, - 114, - 121, - 112, - 116, - 105, - 111, - 110, - 32, - 75, - 101, - 121 - ]); - now = () => Date.now() / 1e3 | 0; - alg = "dir"; - enc = "A256CBC-HS512"; - } -}); - -// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/utils/error-codes.mjs -function defineErrorCodes(codes) { - return codes; -} -var init_error_codes = __esm({ - "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/utils/error-codes.mjs"() { - } -}); - -// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/utils/db.mjs -function filterOutputFields(data2, additionalFields) { - if (!data2 || !additionalFields) return data2; - const returnFiltered = Object.entries(additionalFields).filter(([, { returned }]) => returned === false).map(([key]) => key); - return Object.entries(structuredClone(data2)).filter(([key]) => !returnFiltered.includes(key)).reduce((acc, [key, value]) => ({ - ...acc, - [key]: value - }), {}); -} -var init_db2 = __esm({ - "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/utils/db.mjs"() { - } -}); - -// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/utils/deprecate.mjs -function deprecate(fn, message2, logger4) { - let warned = false; - return function(...args) { - if (!warned) { - (logger4?.warn ?? console.warn)(`[Deprecation] ${message2}`); - warned = true; - } - return fn.apply(this, args); - }; -} -var init_deprecate = __esm({ - "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/utils/deprecate.mjs"() { - } -}); - -// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/utils/id.mjs -var generateId; -var init_id = __esm({ - "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/utils/id.mjs"() { - init_random(); - generateId = (size2) => { - return createRandomStringGenerator("a-z", "A-Z", "0-9")(size2 || 32); - }; - } -}); - -// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/core.js -// @__NO_SIDE_EFFECTS__ -function $constructor(name, initializer3, params) { - function init2(inst, def) { - if (!inst._zod) { - Object.defineProperty(inst, "_zod", { - value: { - def, - constr: _, - traits: /* @__PURE__ */ new Set() - }, - enumerable: false - }); - } - if (inst._zod.traits.has(name)) { - return; - } - inst._zod.traits.add(name); - initializer3(inst, def); - const proto = _.prototype; - const keys = Object.keys(proto); - for (let i5 = 0; i5 < keys.length; i5++) { - const k5 = keys[i5]; - if (!(k5 in inst)) { - inst[k5] = proto[k5].bind(inst); - } - } - } - const Parent = params?.Parent ?? Object; - class Definition extends Parent { - } - Object.defineProperty(Definition, "name", { value: name }); - function _(def) { - var _a6; - const inst = params?.Parent ? new Definition() : this; - init2(inst, def); - (_a6 = inst._zod).deferred ?? (_a6.deferred = []); - for (const fn of inst._zod.deferred) { - fn(); - } - return inst; - } - Object.defineProperty(_, "init", { value: init2 }); - Object.defineProperty(_, Symbol.hasInstance, { - value: (inst) => { - if (params?.Parent && inst instanceof params.Parent) - return true; - return inst?._zod?.traits?.has(name); - } - }); - Object.defineProperty(_, "name", { value: name }); - return _; -} -function config(newConfig) { - if (newConfig) - Object.assign(globalConfig, newConfig); - return globalConfig; -} -var NEVER2, $brand, $ZodAsyncError, $ZodEncodeError, globalConfig; -var init_core = __esm({ - "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/core.js"() { - NEVER2 = Object.freeze({ - status: "aborted" - }); - $brand = /* @__PURE__ */ Symbol("zod_brand"); - $ZodAsyncError = class extends Error { - constructor() { - super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`); - } - }; - $ZodEncodeError = class extends Error { - constructor(name) { - super(`Encountered unidirectional transform during encode: ${name}`); - this.name = "ZodEncodeError"; - } - }; - globalConfig = {}; - } -}); - -// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/util.js -var util_exports = {}; -__export(util_exports, { - BIGINT_FORMAT_RANGES: () => BIGINT_FORMAT_RANGES, - Class: () => Class, - NUMBER_FORMAT_RANGES: () => NUMBER_FORMAT_RANGES, - aborted: () => aborted, - allowsEval: () => allowsEval, - assert: () => assert, - assertEqual: () => assertEqual, - assertIs: () => assertIs, - assertNever: () => assertNever, - assertNotEqual: () => assertNotEqual, - assignProp: () => assignProp, - base64ToUint8Array: () => base64ToUint8Array, - base64urlToUint8Array: () => base64urlToUint8Array, - cached: () => cached3, - captureStackTrace: () => captureStackTrace, - cleanEnum: () => cleanEnum, - cleanRegex: () => cleanRegex, - clone: () => clone2, - cloneDef: () => cloneDef, - createTransparentProxy: () => createTransparentProxy, - defineLazy: () => defineLazy, - esc: () => esc, - escapeRegex: () => escapeRegex, - extend: () => extend, - finalizeIssue: () => finalizeIssue, - floatSafeRemainder: () => floatSafeRemainder2, - getElementAtPath: () => getElementAtPath, - getEnumValues: () => getEnumValues, - getLengthableOrigin: () => getLengthableOrigin, - getParsedType: () => getParsedType2, - getSizableOrigin: () => getSizableOrigin, - hexToUint8Array: () => hexToUint8Array, - isObject: () => isObject2, - isPlainObject: () => isPlainObject5, - issue: () => issue, - joinValues: () => joinValues, - jsonStringifyReplacer: () => jsonStringifyReplacer, - merge: () => merge, - mergeDefs: () => mergeDefs, - normalizeParams: () => normalizeParams, - nullish: () => nullish, - numKeys: () => numKeys, - objectClone: () => objectClone, - omit: () => omit, - optionalKeys: () => optionalKeys, - parsedType: () => parsedType, - partial: () => partial, - pick: () => pick, - prefixIssues: () => prefixIssues, - primitiveTypes: () => primitiveTypes, - promiseAllObject: () => promiseAllObject, - propertyKeyTypes: () => propertyKeyTypes, - randomString: () => randomString, - required: () => required, - safeExtend: () => safeExtend, - shallowClone: () => shallowClone, - slugify: () => slugify2, - stringifyPrimitive: () => stringifyPrimitive, - uint8ArrayToBase64: () => uint8ArrayToBase64, - uint8ArrayToBase64url: () => uint8ArrayToBase64url, - uint8ArrayToHex: () => uint8ArrayToHex, - unwrapMessage: () => unwrapMessage -}); -function assertEqual(val) { - return val; -} -function assertNotEqual(val) { - return val; -} -function assertIs(_arg) { -} -function assertNever(_x) { - throw new Error("Unexpected value in exhaustive check"); -} -function assert(_) { -} -function getEnumValues(entries2) { - const numericValues = Object.values(entries2).filter((v5) => typeof v5 === "number"); - const values2 = Object.entries(entries2).filter(([k5, _]) => numericValues.indexOf(+k5) === -1).map(([_, v5]) => v5); - return values2; -} -function joinValues(array2, separator = "|") { - return array2.map((val) => stringifyPrimitive(val)).join(separator); -} -function jsonStringifyReplacer(_, value) { - if (typeof value === "bigint") - return value.toString(); - return value; -} -function cached3(getter) { - const set2 = false; - return { - get value() { - if (!set2) { - const value = getter(); - Object.defineProperty(this, "value", { value }); - return value; - } - throw new Error("cached value already set"); - } - }; -} -function nullish(input) { - return input === null || input === void 0; -} -function cleanRegex(source) { - const start = source.startsWith("^") ? 1 : 0; - const end = source.endsWith("$") ? source.length - 1 : source.length; - return source.slice(start, end); -} -function floatSafeRemainder2(val, step) { - const valDecCount = (val.toString().split(".")[1] || "").length; - const stepString = step.toString(); - let stepDecCount = (stepString.split(".")[1] || "").length; - if (stepDecCount === 0 && /\d?e-\d?/.test(stepString)) { - const match = stepString.match(/\d?e-(\d?)/); - if (match?.[1]) { - stepDecCount = Number.parseInt(match[1]); - } - } - const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; - const valInt = Number.parseInt(val.toFixed(decCount).replace(".", "")); - const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", "")); - return valInt % stepInt / 10 ** decCount; -} -function defineLazy(object2, key, getter) { - let value = void 0; - Object.defineProperty(object2, key, { - get() { - if (value === EVALUATING) { - return void 0; - } - if (value === void 0) { - value = EVALUATING; - value = getter(); - } - return value; - }, - set(v5) { - Object.defineProperty(object2, key, { - value: v5 - // configurable: true, - }); - }, - configurable: true - }); -} -function objectClone(obj) { - return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj)); -} -function assignProp(target, prop, value) { - Object.defineProperty(target, prop, { - value, - writable: true, - enumerable: true, - configurable: true - }); -} -function mergeDefs(...defs) { - const mergedDescriptors = {}; - for (const def of defs) { - const descriptors = Object.getOwnPropertyDescriptors(def); - Object.assign(mergedDescriptors, descriptors); - } - return Object.defineProperties({}, mergedDescriptors); -} -function cloneDef(schema2) { - return mergeDefs(schema2._zod.def); -} -function getElementAtPath(obj, path53) { - if (!path53) - return obj; - return path53.reduce((acc, key) => acc?.[key], obj); -} -function promiseAllObject(promisesObj) { - const keys = Object.keys(promisesObj); - const promises = keys.map((key) => promisesObj[key]); - return Promise.all(promises).then((results) => { - const resolvedObj = {}; - for (let i5 = 0; i5 < keys.length; i5++) { - resolvedObj[keys[i5]] = results[i5]; - } - return resolvedObj; - }); -} -function randomString(length = 10) { - const chars = "abcdefghijklmnopqrstuvwxyz"; - let str = ""; - for (let i5 = 0; i5 < length; i5++) { - str += chars[Math.floor(Math.random() * chars.length)]; - } - return str; -} -function esc(str) { - return JSON.stringify(str); -} -function slugify2(input) { - return input.toLowerCase().trim().replace(/[^\w\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, ""); -} -function isObject2(data2) { - return typeof data2 === "object" && data2 !== null && !Array.isArray(data2); -} -function isPlainObject5(o5) { - if (isObject2(o5) === false) - return false; - const ctor = o5.constructor; - if (ctor === void 0) - return true; - if (typeof ctor !== "function") - return true; - const prot = ctor.prototype; - if (isObject2(prot) === false) - return false; - if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) { - return false; - } - return true; -} -function shallowClone(o5) { - if (isPlainObject5(o5)) - return { ...o5 }; - if (Array.isArray(o5)) - return [...o5]; - return o5; -} -function numKeys(data2) { - let keyCount = 0; - for (const key in data2) { - if (Object.prototype.hasOwnProperty.call(data2, key)) { - keyCount++; - } - } - return keyCount; -} -function escapeRegex(str) { - return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); -} -function clone2(inst, def, params) { - const cl = new inst._zod.constr(def ?? inst._zod.def); - if (!def || params?.parent) - cl._zod.parent = inst; - return cl; -} -function normalizeParams(_params) { - const params = _params; - if (!params) - return {}; - if (typeof params === "string") - return { error: () => params }; - if (params?.message !== void 0) { - if (params?.error !== void 0) - throw new Error("Cannot specify both `message` and `error` params"); - params.error = params.message; - } - delete params.message; - if (typeof params.error === "string") - return { ...params, error: () => params.error }; - return params; -} -function createTransparentProxy(getter) { - let target; - return new Proxy({}, { - get(_, prop, receiver) { - target ?? (target = getter()); - return Reflect.get(target, prop, receiver); - }, - set(_, prop, value, receiver) { - target ?? (target = getter()); - return Reflect.set(target, prop, value, receiver); - }, - has(_, prop) { - target ?? (target = getter()); - return Reflect.has(target, prop); - }, - deleteProperty(_, prop) { - target ?? (target = getter()); - return Reflect.deleteProperty(target, prop); - }, - ownKeys(_) { - target ?? (target = getter()); - return Reflect.ownKeys(target); - }, - getOwnPropertyDescriptor(_, prop) { - target ?? (target = getter()); - return Reflect.getOwnPropertyDescriptor(target, prop); - }, - defineProperty(_, prop, descriptor) { - target ?? (target = getter()); - return Reflect.defineProperty(target, prop, descriptor); - } - }); -} -function stringifyPrimitive(value) { - if (typeof value === "bigint") - return value.toString() + "n"; - if (typeof value === "string") - return `"${value}"`; - return `${value}`; -} -function optionalKeys(shape) { - return Object.keys(shape).filter((k5) => { - return shape[k5]._zod.optin === "optional" && shape[k5]._zod.optout === "optional"; - }); -} -function pick(schema2, mask) { - const currDef = schema2._zod.def; - const checks = currDef.checks; - const hasChecks = checks && checks.length > 0; - if (hasChecks) { - throw new Error(".pick() cannot be used on object schemas containing refinements"); - } - const def = mergeDefs(schema2._zod.def, { - get shape() { - const newShape = {}; - for (const key in mask) { - if (!(key in currDef.shape)) { - throw new Error(`Unrecognized key: "${key}"`); - } - if (!mask[key]) - continue; - newShape[key] = currDef.shape[key]; - } - assignProp(this, "shape", newShape); - return newShape; - }, - checks: [] - }); - return clone2(schema2, def); -} -function omit(schema2, mask) { - const currDef = schema2._zod.def; - const checks = currDef.checks; - const hasChecks = checks && checks.length > 0; - if (hasChecks) { - throw new Error(".omit() cannot be used on object schemas containing refinements"); - } - const def = mergeDefs(schema2._zod.def, { - get shape() { - const newShape = { ...schema2._zod.def.shape }; - for (const key in mask) { - if (!(key in currDef.shape)) { - throw new Error(`Unrecognized key: "${key}"`); - } - if (!mask[key]) - continue; - delete newShape[key]; - } - assignProp(this, "shape", newShape); - return newShape; - }, - checks: [] - }); - return clone2(schema2, def); -} -function extend(schema2, shape) { - if (!isPlainObject5(shape)) { - throw new Error("Invalid input to extend: expected a plain object"); - } - const checks = schema2._zod.def.checks; - const hasChecks = checks && checks.length > 0; - if (hasChecks) { - const existingShape = schema2._zod.def.shape; - for (const key in shape) { - if (Object.getOwnPropertyDescriptor(existingShape, key) !== void 0) { - throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead."); - } - } - } - const def = mergeDefs(schema2._zod.def, { - get shape() { - const _shape = { ...schema2._zod.def.shape, ...shape }; - assignProp(this, "shape", _shape); - return _shape; - } - }); - return clone2(schema2, def); -} -function safeExtend(schema2, shape) { - if (!isPlainObject5(shape)) { - throw new Error("Invalid input to safeExtend: expected a plain object"); - } - const def = mergeDefs(schema2._zod.def, { - get shape() { - const _shape = { ...schema2._zod.def.shape, ...shape }; - assignProp(this, "shape", _shape); - return _shape; - } - }); - return clone2(schema2, def); -} -function merge(a5, b6) { - const def = mergeDefs(a5._zod.def, { - get shape() { - const _shape = { ...a5._zod.def.shape, ...b6._zod.def.shape }; - assignProp(this, "shape", _shape); - return _shape; - }, - get catchall() { - return b6._zod.def.catchall; - }, - checks: [] - // delete existing checks - }); - return clone2(a5, def); -} -function partial(Class2, schema2, mask) { - const currDef = schema2._zod.def; - const checks = currDef.checks; - const hasChecks = checks && checks.length > 0; - if (hasChecks) { - throw new Error(".partial() cannot be used on object schemas containing refinements"); - } - const def = mergeDefs(schema2._zod.def, { - get shape() { - const oldShape = schema2._zod.def.shape; - const shape = { ...oldShape }; - if (mask) { - for (const key in mask) { - if (!(key in oldShape)) { - throw new Error(`Unrecognized key: "${key}"`); - } - if (!mask[key]) - continue; - shape[key] = Class2 ? new Class2({ - type: "optional", - innerType: oldShape[key] - }) : oldShape[key]; - } - } else { - for (const key in oldShape) { - shape[key] = Class2 ? new Class2({ - type: "optional", - innerType: oldShape[key] - }) : oldShape[key]; - } - } - assignProp(this, "shape", shape); - return shape; - }, - checks: [] - }); - return clone2(schema2, def); -} -function required(Class2, schema2, mask) { - const def = mergeDefs(schema2._zod.def, { - get shape() { - const oldShape = schema2._zod.def.shape; - const shape = { ...oldShape }; - if (mask) { - for (const key in mask) { - if (!(key in shape)) { - throw new Error(`Unrecognized key: "${key}"`); - } - if (!mask[key]) - continue; - shape[key] = new Class2({ - type: "nonoptional", - innerType: oldShape[key] - }); - } - } else { - for (const key in oldShape) { - shape[key] = new Class2({ - type: "nonoptional", - innerType: oldShape[key] - }); - } - } - assignProp(this, "shape", shape); - return shape; - } - }); - return clone2(schema2, def); -} -function aborted(x5, startIndex = 0) { - if (x5.aborted === true) - return true; - for (let i5 = startIndex; i5 < x5.issues.length; i5++) { - if (x5.issues[i5]?.continue !== true) { - return true; - } - } - return false; -} -function prefixIssues(path53, issues2) { - return issues2.map((iss) => { - var _a6; - (_a6 = iss).path ?? (_a6.path = []); - iss.path.unshift(path53); - return iss; - }); -} -function unwrapMessage(message2) { - return typeof message2 === "string" ? message2 : message2?.message; -} -function finalizeIssue(iss, ctx, config3) { - const full = { ...iss, path: iss.path ?? [] }; - if (!iss.message) { - const message2 = unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config3.customError?.(iss)) ?? unwrapMessage(config3.localeError?.(iss)) ?? "Invalid input"; - full.message = message2; - } - delete full.inst; - delete full.continue; - if (!ctx?.reportInput) { - delete full.input; - } - return full; -} -function getSizableOrigin(input) { - if (input instanceof Set) - return "set"; - if (input instanceof Map) - return "map"; - if (input instanceof File) - return "file"; - return "unknown"; -} -function getLengthableOrigin(input) { - if (Array.isArray(input)) - return "array"; - if (typeof input === "string") - return "string"; - return "unknown"; -} -function parsedType(data2) { - const t5 = typeof data2; - switch (t5) { - case "number": { - return Number.isNaN(data2) ? "nan" : "number"; - } - case "object": { - if (data2 === null) { - return "null"; - } - if (Array.isArray(data2)) { - return "array"; - } - const obj = data2; - if (obj && Object.getPrototypeOf(obj) !== Object.prototype && "constructor" in obj && obj.constructor) { - return obj.constructor.name; - } - } - } - return t5; -} -function issue(...args) { - const [iss, input, inst] = args; - if (typeof iss === "string") { - return { - message: iss, - code: "custom", - input, - inst - }; - } - return { ...iss }; -} -function cleanEnum(obj) { - return Object.entries(obj).filter(([k5, _]) => { - return Number.isNaN(Number.parseInt(k5, 10)); - }).map((el) => el[1]); -} -function base64ToUint8Array(base644) { - const binaryString = atob(base644); - const bytes = new Uint8Array(binaryString.length); - for (let i5 = 0; i5 < binaryString.length; i5++) { - bytes[i5] = binaryString.charCodeAt(i5); - } - return bytes; -} -function uint8ArrayToBase64(bytes) { - let binaryString = ""; - for (let i5 = 0; i5 < bytes.length; i5++) { - binaryString += String.fromCharCode(bytes[i5]); - } - return btoa(binaryString); -} -function base64urlToUint8Array(base64url3) { - const base644 = base64url3.replace(/-/g, "+").replace(/_/g, "/"); - const padding = "=".repeat((4 - base644.length % 4) % 4); - return base64ToUint8Array(base644 + padding); -} -function uint8ArrayToBase64url(bytes) { - return uint8ArrayToBase64(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, ""); -} -function hexToUint8Array(hex4) { - const cleanHex = hex4.replace(/^0x/, ""); - if (cleanHex.length % 2 !== 0) { - throw new Error("Invalid hex string length"); - } - const bytes = new Uint8Array(cleanHex.length / 2); - for (let i5 = 0; i5 < cleanHex.length; i5 += 2) { - bytes[i5 / 2] = Number.parseInt(cleanHex.slice(i5, i5 + 2), 16); - } - return bytes; -} -function uint8ArrayToHex(bytes) { - return Array.from(bytes).map((b6) => b6.toString(16).padStart(2, "0")).join(""); -} -var EVALUATING, captureStackTrace, allowsEval, getParsedType2, propertyKeyTypes, primitiveTypes, NUMBER_FORMAT_RANGES, BIGINT_FORMAT_RANGES, Class; -var init_util = __esm({ - "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/util.js"() { - EVALUATING = /* @__PURE__ */ Symbol("evaluating"); - captureStackTrace = "captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => { - }; - allowsEval = cached3(() => { - if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) { - return false; - } - try { - const F2 = Function; - new F2(""); - return true; - } catch (_) { - return false; - } - }); - getParsedType2 = (data2) => { - const t5 = typeof data2; - switch (t5) { - case "undefined": - return "undefined"; - case "string": - return "string"; - case "number": - return Number.isNaN(data2) ? "nan" : "number"; - case "boolean": - return "boolean"; - case "function": - return "function"; - case "bigint": - return "bigint"; - case "symbol": - return "symbol"; - case "object": - if (Array.isArray(data2)) { - return "array"; - } - if (data2 === null) { - return "null"; - } - if (data2.then && typeof data2.then === "function" && data2.catch && typeof data2.catch === "function") { - return "promise"; - } - if (typeof Map !== "undefined" && data2 instanceof Map) { - return "map"; - } - if (typeof Set !== "undefined" && data2 instanceof Set) { - return "set"; - } - if (typeof Date !== "undefined" && data2 instanceof Date) { - return "date"; - } - if (typeof File !== "undefined" && data2 instanceof File) { - return "file"; - } - return "object"; - default: - throw new Error(`Unknown data type: ${t5}`); - } - }; - propertyKeyTypes = /* @__PURE__ */ new Set(["string", "number", "symbol"]); - primitiveTypes = /* @__PURE__ */ new Set(["string", "number", "bigint", "boolean", "symbol", "undefined"]); - NUMBER_FORMAT_RANGES = { - safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER], - int32: [-2147483648, 2147483647], - uint32: [0, 4294967295], - float32: [-34028234663852886e22, 34028234663852886e22], - float64: [-Number.MAX_VALUE, Number.MAX_VALUE] - }; - BIGINT_FORMAT_RANGES = { - int64: [/* @__PURE__ */ BigInt("-9223372036854775808"), /* @__PURE__ */ BigInt("9223372036854775807")], - uint64: [/* @__PURE__ */ BigInt(0), /* @__PURE__ */ BigInt("18446744073709551615")] - }; - Class = class { - constructor(..._args) { - } - }; - } -}); - -// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/errors.js -function flattenError(error50, mapper = (issue2) => issue2.message) { - const fieldErrors = {}; - const formErrors = []; - for (const sub of error50.issues) { - if (sub.path.length > 0) { - fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || []; - fieldErrors[sub.path[0]].push(mapper(sub)); - } else { - formErrors.push(mapper(sub)); - } - } - return { formErrors, fieldErrors }; -} -function formatError(error50, mapper = (issue2) => issue2.message) { - const fieldErrors = { _errors: [] }; - const processError = (error51) => { - for (const issue2 of error51.issues) { - if (issue2.code === "invalid_union" && issue2.errors.length) { - issue2.errors.map((issues2) => processError({ issues: issues2 })); - } else if (issue2.code === "invalid_key") { - processError({ issues: issue2.issues }); - } else if (issue2.code === "invalid_element") { - processError({ issues: issue2.issues }); - } else if (issue2.path.length === 0) { - fieldErrors._errors.push(mapper(issue2)); - } else { - let curr = fieldErrors; - let i5 = 0; - while (i5 < issue2.path.length) { - const el = issue2.path[i5]; - const terminal = i5 === issue2.path.length - 1; - if (!terminal) { - curr[el] = curr[el] || { _errors: [] }; - } else { - curr[el] = curr[el] || { _errors: [] }; - curr[el]._errors.push(mapper(issue2)); - } - curr = curr[el]; - i5++; - } - } - } - }; - processError(error50); - return fieldErrors; -} -function treeifyError(error50, mapper = (issue2) => issue2.message) { - const result = { errors: [] }; - const processError = (error51, path53 = []) => { - var _a6, _b; - for (const issue2 of error51.issues) { - if (issue2.code === "invalid_union" && issue2.errors.length) { - issue2.errors.map((issues2) => processError({ issues: issues2 }, issue2.path)); - } else if (issue2.code === "invalid_key") { - processError({ issues: issue2.issues }, issue2.path); - } else if (issue2.code === "invalid_element") { - processError({ issues: issue2.issues }, issue2.path); - } else { - const fullpath = [...path53, ...issue2.path]; - if (fullpath.length === 0) { - result.errors.push(mapper(issue2)); - continue; - } - let curr = result; - let i5 = 0; - while (i5 < fullpath.length) { - const el = fullpath[i5]; - const terminal = i5 === fullpath.length - 1; - if (typeof el === "string") { - curr.properties ?? (curr.properties = {}); - (_a6 = curr.properties)[el] ?? (_a6[el] = { errors: [] }); - curr = curr.properties[el]; - } else { - curr.items ?? (curr.items = []); - (_b = curr.items)[el] ?? (_b[el] = { errors: [] }); - curr = curr.items[el]; - } - if (terminal) { - curr.errors.push(mapper(issue2)); - } - i5++; - } - } - } - }; - processError(error50); - return result; -} -function toDotPath(_path) { - const segs = []; - const path53 = _path.map((seg) => typeof seg === "object" ? seg.key : seg); - for (const seg of path53) { - if (typeof seg === "number") - segs.push(`[${seg}]`); - else if (typeof seg === "symbol") - segs.push(`[${JSON.stringify(String(seg))}]`); - else if (/[^\w$]/.test(seg)) - segs.push(`[${JSON.stringify(seg)}]`); - else { - if (segs.length) - segs.push("."); - segs.push(seg); - } - } - return segs.join(""); -} -function prettifyError(error50) { - const lines = []; - const issues2 = [...error50.issues].sort((a5, b6) => (a5.path ?? []).length - (b6.path ?? []).length); - for (const issue2 of issues2) { - lines.push(`\u2716 ${issue2.message}`); - if (issue2.path?.length) - lines.push(` \u2192 at ${toDotPath(issue2.path)}`); - } - return lines.join("\n"); -} -var initializer, $ZodError, $ZodRealError; -var init_errors8 = __esm({ - "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/errors.js"() { - init_core(); - init_util(); - initializer = (inst, def) => { - inst.name = "$ZodError"; - Object.defineProperty(inst, "_zod", { - value: inst._zod, - enumerable: false - }); - Object.defineProperty(inst, "issues", { - value: def, - enumerable: false - }); - inst.message = JSON.stringify(def, jsonStringifyReplacer, 2); - Object.defineProperty(inst, "toString", { - value: () => inst.message, - enumerable: false - }); - }; - $ZodError = $constructor("$ZodError", initializer); - $ZodRealError = $constructor("$ZodError", initializer, { Parent: Error }); - } -}); - -// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/parse.js -var _parse, parse2, _parseAsync, parseAsync, _safeParse, safeParse, _safeParseAsync, safeParseAsync, _encode, encode4, _decode, decode3, _encodeAsync, encodeAsync, _decodeAsync, decodeAsync, _safeEncode, safeEncode, _safeDecode, safeDecode, _safeEncodeAsync, safeEncodeAsync, _safeDecodeAsync, safeDecodeAsync; -var init_parse = __esm({ - "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/parse.js"() { - init_core(); - init_errors8(); - init_util(); - _parse = (_Err) => (schema2, value, _ctx, _params) => { - const ctx = _ctx ? Object.assign(_ctx, { async: false }) : { async: false }; - const result = schema2._zod.run({ value, issues: [] }, ctx); - if (result instanceof Promise) { - throw new $ZodAsyncError(); - } - if (result.issues.length) { - const e5 = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); - captureStackTrace(e5, _params?.callee); - throw e5; - } - return result.value; - }; - parse2 = /* @__PURE__ */ _parse($ZodRealError); - _parseAsync = (_Err) => async (schema2, value, _ctx, params) => { - const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true }; - let result = schema2._zod.run({ value, issues: [] }, ctx); - if (result instanceof Promise) - result = await result; - if (result.issues.length) { - const e5 = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); - captureStackTrace(e5, params?.callee); - throw e5; - } - return result.value; - }; - parseAsync = /* @__PURE__ */ _parseAsync($ZodRealError); - _safeParse = (_Err) => (schema2, value, _ctx) => { - const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; - const result = schema2._zod.run({ value, issues: [] }, ctx); - if (result instanceof Promise) { - throw new $ZodAsyncError(); - } - return result.issues.length ? { - success: false, - error: new (_Err ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) - } : { success: true, data: result.value }; - }; - safeParse = /* @__PURE__ */ _safeParse($ZodRealError); - _safeParseAsync = (_Err) => async (schema2, value, _ctx) => { - const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true }; - let result = schema2._zod.run({ value, issues: [] }, ctx); - if (result instanceof Promise) - result = await result; - return result.issues.length ? { - success: false, - error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) - } : { success: true, data: result.value }; - }; - safeParseAsync = /* @__PURE__ */ _safeParseAsync($ZodRealError); - _encode = (_Err) => (schema2, value, _ctx) => { - const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" }; - return _parse(_Err)(schema2, value, ctx); - }; - encode4 = /* @__PURE__ */ _encode($ZodRealError); - _decode = (_Err) => (schema2, value, _ctx) => { - return _parse(_Err)(schema2, value, _ctx); - }; - decode3 = /* @__PURE__ */ _decode($ZodRealError); - _encodeAsync = (_Err) => async (schema2, value, _ctx) => { - const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" }; - return _parseAsync(_Err)(schema2, value, ctx); - }; - encodeAsync = /* @__PURE__ */ _encodeAsync($ZodRealError); - _decodeAsync = (_Err) => async (schema2, value, _ctx) => { - return _parseAsync(_Err)(schema2, value, _ctx); - }; - decodeAsync = /* @__PURE__ */ _decodeAsync($ZodRealError); - _safeEncode = (_Err) => (schema2, value, _ctx) => { - const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" }; - return _safeParse(_Err)(schema2, value, ctx); - }; - safeEncode = /* @__PURE__ */ _safeEncode($ZodRealError); - _safeDecode = (_Err) => (schema2, value, _ctx) => { - return _safeParse(_Err)(schema2, value, _ctx); - }; - safeDecode = /* @__PURE__ */ _safeDecode($ZodRealError); - _safeEncodeAsync = (_Err) => async (schema2, value, _ctx) => { - const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" }; - return _safeParseAsync(_Err)(schema2, value, ctx); - }; - safeEncodeAsync = /* @__PURE__ */ _safeEncodeAsync($ZodRealError); - _safeDecodeAsync = (_Err) => async (schema2, value, _ctx) => { - return _safeParseAsync(_Err)(schema2, value, _ctx); - }; - safeDecodeAsync = /* @__PURE__ */ _safeDecodeAsync($ZodRealError); - } -}); - -// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/regexes.js -var regexes_exports = {}; -__export(regexes_exports, { - base64: () => base64, - base64url: () => base64url, - bigint: () => bigint2, - boolean: () => boolean2, - browserEmail: () => browserEmail, - cidrv4: () => cidrv4, - cidrv6: () => cidrv6, - cuid: () => cuid, - cuid2: () => cuid2, - date: () => date3, - datetime: () => datetime, - domain: () => domain, - duration: () => duration, - e164: () => e164, - email: () => email, - emoji: () => emoji, - extendedDuration: () => extendedDuration, - guid: () => guid, - hex: () => hex, - hostname: () => hostname, - html5Email: () => html5Email, - idnEmail: () => idnEmail, - integer: () => integer2, - ipv4: () => ipv4, - ipv6: () => ipv6, - ksuid: () => ksuid, - lowercase: () => lowercase, - mac: () => mac, - md5_base64: () => md5_base64, - md5_base64url: () => md5_base64url, - md5_hex: () => md5_hex, - nanoid: () => nanoid, - null: () => _null, - number: () => number, - rfc5322Email: () => rfc5322Email, - sha1_base64: () => sha1_base64, - sha1_base64url: () => sha1_base64url, - sha1_hex: () => sha1_hex, - sha256_base64: () => sha256_base64, - sha256_base64url: () => sha256_base64url, - sha256_hex: () => sha256_hex, - sha384_base64: () => sha384_base64, - sha384_base64url: () => sha384_base64url, - sha384_hex: () => sha384_hex, - sha512_base64: () => sha512_base64, - sha512_base64url: () => sha512_base64url, - sha512_hex: () => sha512_hex, - string: () => string, - time: () => time3, - ulid: () => ulid, - undefined: () => _undefined, - unicodeEmail: () => unicodeEmail, - uppercase: () => uppercase, - uuid: () => uuid2, - uuid4: () => uuid4, - uuid6: () => uuid6, - uuid7: () => uuid7, - xid: () => xid -}); -function emoji() { - return new RegExp(_emoji, "u"); -} -function timeSource(args) { - const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`; - const regex = typeof args.precision === "number" ? args.precision === -1 ? `${hhmm}` : args.precision === 0 ? `${hhmm}:[0-5]\\d` : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`; - return regex; -} -function time3(args) { - return new RegExp(`^${timeSource(args)}$`); -} -function datetime(args) { - const time5 = timeSource({ precision: args.precision }); - const opts = ["Z"]; - if (args.local) - opts.push(""); - if (args.offset) - opts.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`); - const timeRegex2 = `${time5}(?:${opts.join("|")})`; - return new RegExp(`^${dateSource}T(?:${timeRegex2})$`); -} -function fixedBase64(bodyLength, padding) { - return new RegExp(`^[A-Za-z0-9+/]{${bodyLength}}${padding}$`); -} -function fixedBase64url(length) { - return new RegExp(`^[A-Za-z0-9_-]{${length}}$`); -} -var cuid, cuid2, ulid, xid, ksuid, nanoid, duration, extendedDuration, guid, uuid2, uuid4, uuid6, uuid7, email, html5Email, rfc5322Email, unicodeEmail, idnEmail, browserEmail, _emoji, ipv4, ipv6, mac, cidrv4, cidrv6, base64, base64url, hostname, domain, e164, dateSource, date3, string, bigint2, integer2, number, boolean2, _null, _undefined, lowercase, uppercase, hex, md5_hex, md5_base64, md5_base64url, sha1_hex, sha1_base64, sha1_base64url, sha256_hex, sha256_base64, sha256_base64url, sha384_hex, sha384_base64, sha384_base64url, sha512_hex, sha512_base64, sha512_base64url; -var init_regexes = __esm({ - "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/regexes.js"() { - init_util(); - cuid = /^[cC][^\s-]{8,}$/; - cuid2 = /^[0-9a-z]+$/; - ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/; - xid = /^[0-9a-vA-V]{20}$/; - ksuid = /^[A-Za-z0-9]{27}$/; - nanoid = /^[a-zA-Z0-9_-]{21}$/; - duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/; - extendedDuration = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; - guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/; - uuid2 = (version3) => { - if (!version3) - return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/; - return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version3}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`); - }; - uuid4 = /* @__PURE__ */ uuid2(4); - uuid6 = /* @__PURE__ */ uuid2(6); - uuid7 = /* @__PURE__ */ uuid2(7); - email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/; - html5Email = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; - rfc5322Email = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; - unicodeEmail = /^[^\s@"]{1,64}@[^\s@]{1,255}$/u; - idnEmail = unicodeEmail; - browserEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; - _emoji = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; - ipv4 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/; - ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/; - mac = (delimiter) => { - const escapedDelim = escapeRegex(delimiter ?? ":"); - return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`); - }; - cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/; - cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; - base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/; - base64url = /^[A-Za-z0-9_-]*$/; - hostname = /^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/; - domain = /^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/; - e164 = /^\+[1-9]\d{6,14}$/; - dateSource = `(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`; - date3 = /* @__PURE__ */ new RegExp(`^${dateSource}$`); - string = (params) => { - const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`; - return new RegExp(`^${regex}$`); - }; - bigint2 = /^-?\d+n?$/; - integer2 = /^-?\d+$/; - number = /^-?\d+(?:\.\d+)?$/; - boolean2 = /^(?:true|false)$/i; - _null = /^null$/i; - _undefined = /^undefined$/i; - lowercase = /^[^A-Z]*$/; - uppercase = /^[^a-z]*$/; - hex = /^[0-9a-fA-F]*$/; - md5_hex = /^[0-9a-fA-F]{32}$/; - md5_base64 = /* @__PURE__ */ fixedBase64(22, "=="); - md5_base64url = /* @__PURE__ */ fixedBase64url(22); - sha1_hex = /^[0-9a-fA-F]{40}$/; - sha1_base64 = /* @__PURE__ */ fixedBase64(27, "="); - sha1_base64url = /* @__PURE__ */ fixedBase64url(27); - sha256_hex = /^[0-9a-fA-F]{64}$/; - sha256_base64 = /* @__PURE__ */ fixedBase64(43, "="); - sha256_base64url = /* @__PURE__ */ fixedBase64url(43); - sha384_hex = /^[0-9a-fA-F]{96}$/; - sha384_base64 = /* @__PURE__ */ fixedBase64(64, ""); - sha384_base64url = /* @__PURE__ */ fixedBase64url(64); - sha512_hex = /^[0-9a-fA-F]{128}$/; - sha512_base64 = /* @__PURE__ */ fixedBase64(86, "=="); - sha512_base64url = /* @__PURE__ */ fixedBase64url(86); - } -}); - -// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/checks.js -function handleCheckPropertyResult(result, payload2, property) { - if (result.issues.length) { - payload2.issues.push(...prefixIssues(property, result.issues)); - } -} -var $ZodCheck, numericOriginMap, $ZodCheckLessThan, $ZodCheckGreaterThan, $ZodCheckMultipleOf, $ZodCheckNumberFormat, $ZodCheckBigIntFormat, $ZodCheckMaxSize, $ZodCheckMinSize, $ZodCheckSizeEquals, $ZodCheckMaxLength, $ZodCheckMinLength, $ZodCheckLengthEquals, $ZodCheckStringFormat, $ZodCheckRegex, $ZodCheckLowerCase, $ZodCheckUpperCase, $ZodCheckIncludes, $ZodCheckStartsWith, $ZodCheckEndsWith, $ZodCheckProperty, $ZodCheckMimeType, $ZodCheckOverwrite; -var init_checks2 = __esm({ - "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/checks.js"() { - init_core(); - init_regexes(); - init_util(); - $ZodCheck = /* @__PURE__ */ $constructor("$ZodCheck", (inst, def) => { - var _a6; - inst._zod ?? (inst._zod = {}); - inst._zod.def = def; - (_a6 = inst._zod).onattach ?? (_a6.onattach = []); - }); - numericOriginMap = { - number: "number", - bigint: "bigint", - object: "date" - }; - $ZodCheckLessThan = /* @__PURE__ */ $constructor("$ZodCheckLessThan", (inst, def) => { - $ZodCheck.init(inst, def); - const origin = numericOriginMap[typeof def.value]; - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY; - if (def.value < curr) { - if (def.inclusive) - bag.maximum = def.value; - else - bag.exclusiveMaximum = def.value; - } - }); - inst._zod.check = (payload2) => { - if (def.inclusive ? payload2.value <= def.value : payload2.value < def.value) { - return; - } - payload2.issues.push({ - origin, - code: "too_big", - maximum: typeof def.value === "object" ? def.value.getTime() : def.value, - input: payload2.value, - inclusive: def.inclusive, - inst, - continue: !def.abort - }); - }; - }); - $ZodCheckGreaterThan = /* @__PURE__ */ $constructor("$ZodCheckGreaterThan", (inst, def) => { - $ZodCheck.init(inst, def); - const origin = numericOriginMap[typeof def.value]; - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY; - if (def.value > curr) { - if (def.inclusive) - bag.minimum = def.value; - else - bag.exclusiveMinimum = def.value; - } - }); - inst._zod.check = (payload2) => { - if (def.inclusive ? payload2.value >= def.value : payload2.value > def.value) { - return; - } - payload2.issues.push({ - origin, - code: "too_small", - minimum: typeof def.value === "object" ? def.value.getTime() : def.value, - input: payload2.value, - inclusive: def.inclusive, - inst, - continue: !def.abort - }); - }; - }); - $ZodCheckMultipleOf = /* @__PURE__ */ $constructor("$ZodCheckMultipleOf", (inst, def) => { - $ZodCheck.init(inst, def); - inst._zod.onattach.push((inst2) => { - var _a6; - (_a6 = inst2._zod.bag).multipleOf ?? (_a6.multipleOf = def.value); - }); - inst._zod.check = (payload2) => { - if (typeof payload2.value !== typeof def.value) - throw new Error("Cannot mix number and bigint in multiple_of check."); - const isMultiple = typeof payload2.value === "bigint" ? payload2.value % def.value === BigInt(0) : floatSafeRemainder2(payload2.value, def.value) === 0; - if (isMultiple) - return; - payload2.issues.push({ - origin: typeof payload2.value, - code: "not_multiple_of", - divisor: def.value, - input: payload2.value, - inst, - continue: !def.abort - }); - }; - }); - $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat", (inst, def) => { - $ZodCheck.init(inst, def); - def.format = def.format || "float64"; - const isInt = def.format?.includes("int"); - const origin = isInt ? "int" : "number"; - const [minimum, maximum] = NUMBER_FORMAT_RANGES[def.format]; - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.format = def.format; - bag.minimum = minimum; - bag.maximum = maximum; - if (isInt) - bag.pattern = integer2; - }); - inst._zod.check = (payload2) => { - const input = payload2.value; - if (isInt) { - if (!Number.isInteger(input)) { - payload2.issues.push({ - expected: origin, - format: def.format, - code: "invalid_type", - continue: false, - input, - inst - }); - return; - } - if (!Number.isSafeInteger(input)) { - if (input > 0) { - payload2.issues.push({ - input, - code: "too_big", - maximum: Number.MAX_SAFE_INTEGER, - note: "Integers must be within the safe integer range.", - inst, - origin, - inclusive: true, - continue: !def.abort - }); - } else { - payload2.issues.push({ - input, - code: "too_small", - minimum: Number.MIN_SAFE_INTEGER, - note: "Integers must be within the safe integer range.", - inst, - origin, - inclusive: true, - continue: !def.abort - }); - } - return; - } - } - if (input < minimum) { - payload2.issues.push({ - origin: "number", - input, - code: "too_small", - minimum, - inclusive: true, - inst, - continue: !def.abort - }); - } - if (input > maximum) { - payload2.issues.push({ - origin: "number", - input, - code: "too_big", - maximum, - inclusive: true, - inst, - continue: !def.abort - }); - } - }; - }); - $ZodCheckBigIntFormat = /* @__PURE__ */ $constructor("$ZodCheckBigIntFormat", (inst, def) => { - $ZodCheck.init(inst, def); - const [minimum, maximum] = BIGINT_FORMAT_RANGES[def.format]; - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.format = def.format; - bag.minimum = minimum; - bag.maximum = maximum; - }); - inst._zod.check = (payload2) => { - const input = payload2.value; - if (input < minimum) { - payload2.issues.push({ - origin: "bigint", - input, - code: "too_small", - minimum, - inclusive: true, - inst, - continue: !def.abort - }); - } - if (input > maximum) { - payload2.issues.push({ - origin: "bigint", - input, - code: "too_big", - maximum, - inclusive: true, - inst, - continue: !def.abort - }); - } - }; - }); - $ZodCheckMaxSize = /* @__PURE__ */ $constructor("$ZodCheckMaxSize", (inst, def) => { - var _a6; - $ZodCheck.init(inst, def); - (_a6 = inst._zod.def).when ?? (_a6.when = (payload2) => { - const val = payload2.value; - return !nullish(val) && val.size !== void 0; - }); - inst._zod.onattach.push((inst2) => { - const curr = inst2._zod.bag.maximum ?? Number.POSITIVE_INFINITY; - if (def.maximum < curr) - inst2._zod.bag.maximum = def.maximum; - }); - inst._zod.check = (payload2) => { - const input = payload2.value; - const size2 = input.size; - if (size2 <= def.maximum) - return; - payload2.issues.push({ - origin: getSizableOrigin(input), - code: "too_big", - maximum: def.maximum, - inclusive: true, - input, - inst, - continue: !def.abort - }); - }; - }); - $ZodCheckMinSize = /* @__PURE__ */ $constructor("$ZodCheckMinSize", (inst, def) => { - var _a6; - $ZodCheck.init(inst, def); - (_a6 = inst._zod.def).when ?? (_a6.when = (payload2) => { - const val = payload2.value; - return !nullish(val) && val.size !== void 0; - }); - inst._zod.onattach.push((inst2) => { - const curr = inst2._zod.bag.minimum ?? Number.NEGATIVE_INFINITY; - if (def.minimum > curr) - inst2._zod.bag.minimum = def.minimum; - }); - inst._zod.check = (payload2) => { - const input = payload2.value; - const size2 = input.size; - if (size2 >= def.minimum) - return; - payload2.issues.push({ - origin: getSizableOrigin(input), - code: "too_small", - minimum: def.minimum, - inclusive: true, - input, - inst, - continue: !def.abort - }); - }; - }); - $ZodCheckSizeEquals = /* @__PURE__ */ $constructor("$ZodCheckSizeEquals", (inst, def) => { - var _a6; - $ZodCheck.init(inst, def); - (_a6 = inst._zod.def).when ?? (_a6.when = (payload2) => { - const val = payload2.value; - return !nullish(val) && val.size !== void 0; - }); - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.minimum = def.size; - bag.maximum = def.size; - bag.size = def.size; - }); - inst._zod.check = (payload2) => { - const input = payload2.value; - const size2 = input.size; - if (size2 === def.size) - return; - const tooBig = size2 > def.size; - payload2.issues.push({ - origin: getSizableOrigin(input), - ...tooBig ? { code: "too_big", maximum: def.size } : { code: "too_small", minimum: def.size }, - inclusive: true, - exact: true, - input: payload2.value, - inst, - continue: !def.abort - }); - }; - }); - $ZodCheckMaxLength = /* @__PURE__ */ $constructor("$ZodCheckMaxLength", (inst, def) => { - var _a6; - $ZodCheck.init(inst, def); - (_a6 = inst._zod.def).when ?? (_a6.when = (payload2) => { - const val = payload2.value; - return !nullish(val) && val.length !== void 0; - }); - inst._zod.onattach.push((inst2) => { - const curr = inst2._zod.bag.maximum ?? Number.POSITIVE_INFINITY; - if (def.maximum < curr) - inst2._zod.bag.maximum = def.maximum; - }); - inst._zod.check = (payload2) => { - const input = payload2.value; - const length = input.length; - if (length <= def.maximum) - return; - const origin = getLengthableOrigin(input); - payload2.issues.push({ - origin, - code: "too_big", - maximum: def.maximum, - inclusive: true, - input, - inst, - continue: !def.abort - }); - }; - }); - $ZodCheckMinLength = /* @__PURE__ */ $constructor("$ZodCheckMinLength", (inst, def) => { - var _a6; - $ZodCheck.init(inst, def); - (_a6 = inst._zod.def).when ?? (_a6.when = (payload2) => { - const val = payload2.value; - return !nullish(val) && val.length !== void 0; - }); - inst._zod.onattach.push((inst2) => { - const curr = inst2._zod.bag.minimum ?? Number.NEGATIVE_INFINITY; - if (def.minimum > curr) - inst2._zod.bag.minimum = def.minimum; - }); - inst._zod.check = (payload2) => { - const input = payload2.value; - const length = input.length; - if (length >= def.minimum) - return; - const origin = getLengthableOrigin(input); - payload2.issues.push({ - origin, - code: "too_small", - minimum: def.minimum, - inclusive: true, - input, - inst, - continue: !def.abort - }); - }; - }); - $ZodCheckLengthEquals = /* @__PURE__ */ $constructor("$ZodCheckLengthEquals", (inst, def) => { - var _a6; - $ZodCheck.init(inst, def); - (_a6 = inst._zod.def).when ?? (_a6.when = (payload2) => { - const val = payload2.value; - return !nullish(val) && val.length !== void 0; - }); - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.minimum = def.length; - bag.maximum = def.length; - bag.length = def.length; - }); - inst._zod.check = (payload2) => { - const input = payload2.value; - const length = input.length; - if (length === def.length) - return; - const origin = getLengthableOrigin(input); - const tooBig = length > def.length; - payload2.issues.push({ - origin, - ...tooBig ? { code: "too_big", maximum: def.length } : { code: "too_small", minimum: def.length }, - inclusive: true, - exact: true, - input: payload2.value, - inst, - continue: !def.abort - }); - }; - }); - $ZodCheckStringFormat = /* @__PURE__ */ $constructor("$ZodCheckStringFormat", (inst, def) => { - var _a6, _b; - $ZodCheck.init(inst, def); - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.format = def.format; - if (def.pattern) { - bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); - bag.patterns.add(def.pattern); - } - }); - if (def.pattern) - (_a6 = inst._zod).check ?? (_a6.check = (payload2) => { - def.pattern.lastIndex = 0; - if (def.pattern.test(payload2.value)) - return; - payload2.issues.push({ - origin: "string", - code: "invalid_format", - format: def.format, - input: payload2.value, - ...def.pattern ? { pattern: def.pattern.toString() } : {}, - inst, - continue: !def.abort - }); - }); - else - (_b = inst._zod).check ?? (_b.check = () => { - }); - }); - $ZodCheckRegex = /* @__PURE__ */ $constructor("$ZodCheckRegex", (inst, def) => { - $ZodCheckStringFormat.init(inst, def); - inst._zod.check = (payload2) => { - def.pattern.lastIndex = 0; - if (def.pattern.test(payload2.value)) - return; - payload2.issues.push({ - origin: "string", - code: "invalid_format", - format: "regex", - input: payload2.value, - pattern: def.pattern.toString(), - inst, - continue: !def.abort - }); - }; - }); - $ZodCheckLowerCase = /* @__PURE__ */ $constructor("$ZodCheckLowerCase", (inst, def) => { - def.pattern ?? (def.pattern = lowercase); - $ZodCheckStringFormat.init(inst, def); - }); - $ZodCheckUpperCase = /* @__PURE__ */ $constructor("$ZodCheckUpperCase", (inst, def) => { - def.pattern ?? (def.pattern = uppercase); - $ZodCheckStringFormat.init(inst, def); - }); - $ZodCheckIncludes = /* @__PURE__ */ $constructor("$ZodCheckIncludes", (inst, def) => { - $ZodCheck.init(inst, def); - const escapedRegex = escapeRegex(def.includes); - const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position}}${escapedRegex}` : escapedRegex); - def.pattern = pattern; - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); - bag.patterns.add(pattern); - }); - inst._zod.check = (payload2) => { - if (payload2.value.includes(def.includes, def.position)) - return; - payload2.issues.push({ - origin: "string", - code: "invalid_format", - format: "includes", - includes: def.includes, - input: payload2.value, - inst, - continue: !def.abort - }); - }; - }); - $ZodCheckStartsWith = /* @__PURE__ */ $constructor("$ZodCheckStartsWith", (inst, def) => { - $ZodCheck.init(inst, def); - const pattern = new RegExp(`^${escapeRegex(def.prefix)}.*`); - def.pattern ?? (def.pattern = pattern); - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); - bag.patterns.add(pattern); - }); - inst._zod.check = (payload2) => { - if (payload2.value.startsWith(def.prefix)) - return; - payload2.issues.push({ - origin: "string", - code: "invalid_format", - format: "starts_with", - prefix: def.prefix, - input: payload2.value, - inst, - continue: !def.abort - }); - }; - }); - $ZodCheckEndsWith = /* @__PURE__ */ $constructor("$ZodCheckEndsWith", (inst, def) => { - $ZodCheck.init(inst, def); - const pattern = new RegExp(`.*${escapeRegex(def.suffix)}$`); - def.pattern ?? (def.pattern = pattern); - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); - bag.patterns.add(pattern); - }); - inst._zod.check = (payload2) => { - if (payload2.value.endsWith(def.suffix)) - return; - payload2.issues.push({ - origin: "string", - code: "invalid_format", - format: "ends_with", - suffix: def.suffix, - input: payload2.value, - inst, - continue: !def.abort - }); - }; - }); - $ZodCheckProperty = /* @__PURE__ */ $constructor("$ZodCheckProperty", (inst, def) => { - $ZodCheck.init(inst, def); - inst._zod.check = (payload2) => { - const result = def.schema._zod.run({ - value: payload2.value[def.property], - issues: [] - }, {}); - if (result instanceof Promise) { - return result.then((result2) => handleCheckPropertyResult(result2, payload2, def.property)); - } - handleCheckPropertyResult(result, payload2, def.property); - return; - }; - }); - $ZodCheckMimeType = /* @__PURE__ */ $constructor("$ZodCheckMimeType", (inst, def) => { - $ZodCheck.init(inst, def); - const mimeSet = new Set(def.mime); - inst._zod.onattach.push((inst2) => { - inst2._zod.bag.mime = def.mime; - }); - inst._zod.check = (payload2) => { - if (mimeSet.has(payload2.value.type)) - return; - payload2.issues.push({ - code: "invalid_value", - values: def.mime, - input: payload2.value.type, - inst, - continue: !def.abort - }); - }; - }); - $ZodCheckOverwrite = /* @__PURE__ */ $constructor("$ZodCheckOverwrite", (inst, def) => { - $ZodCheck.init(inst, def); - inst._zod.check = (payload2) => { - payload2.value = def.tx(payload2.value); - }; - }); - } -}); - -// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/doc.js -var Doc; -var init_doc = __esm({ - "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/doc.js"() { - Doc = class { - constructor(args = []) { - this.content = []; - this.indent = 0; - if (this) - this.args = args; - } - indented(fn) { - this.indent += 1; - fn(this); - this.indent -= 1; - } - write(arg) { - if (typeof arg === "function") { - arg(this, { execution: "sync" }); - arg(this, { execution: "async" }); - return; - } - const content = arg; - const lines = content.split("\n").filter((x5) => x5); - const minIndent = Math.min(...lines.map((x5) => x5.length - x5.trimStart().length)); - const dedented = lines.map((x5) => x5.slice(minIndent)).map((x5) => " ".repeat(this.indent * 2) + x5); - for (const line3 of dedented) { - this.content.push(line3); - } - } - compile() { - const F2 = Function; - const args = this?.args; - const content = this?.content ?? [``]; - const lines = [...content.map((x5) => ` ${x5}`)]; - return new F2(...args, lines.join("\n")); - } - }; - } -}); - -// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/versions.js -var version2; -var init_versions = __esm({ - "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/versions.js"() { - version2 = { - major: 4, - minor: 3, - patch: 6 - }; - } -}); - -// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/schemas.js -function isValidBase64(data2) { - if (data2 === "") - return true; - if (data2.length % 4 !== 0) - return false; - try { - atob(data2); - return true; - } catch { - return false; - } -} -function isValidBase64URL(data2) { - if (!base64url.test(data2)) - return false; - const base644 = data2.replace(/[-_]/g, (c5) => c5 === "-" ? "+" : "/"); - const padded = base644.padEnd(Math.ceil(base644.length / 4) * 4, "="); - return isValidBase64(padded); -} -function isValidJWT2(token, algorithm2 = null) { - try { - const tokensParts = token.split("."); - if (tokensParts.length !== 3) - return false; - const [header] = tokensParts; - if (!header) - return false; - const parsedHeader = JSON.parse(atob(header)); - if ("typ" in parsedHeader && parsedHeader?.typ !== "JWT") - return false; - if (!parsedHeader.alg) - return false; - if (algorithm2 && (!("alg" in parsedHeader) || parsedHeader.alg !== algorithm2)) - return false; - return true; - } catch { - return false; - } -} -function handleArrayResult(result, final, index2) { - if (result.issues.length) { - final.issues.push(...prefixIssues(index2, result.issues)); - } - final.value[index2] = result.value; -} -function handlePropertyResult(result, final, key, input, isOptionalOut) { - if (result.issues.length) { - if (isOptionalOut && !(key in input)) { - return; - } - final.issues.push(...prefixIssues(key, result.issues)); - } - if (result.value === void 0) { - if (key in input) { - final.value[key] = void 0; - } - } else { - final.value[key] = result.value; - } -} -function normalizeDef(def) { - const keys = Object.keys(def.shape); - for (const k5 of keys) { - if (!def.shape?.[k5]?._zod?.traits?.has("$ZodType")) { - throw new Error(`Invalid element at key "${k5}": expected a Zod schema`); - } - } - const okeys = optionalKeys(def.shape); - return { - ...def, - keys, - keySet: new Set(keys), - numKeys: keys.length, - optionalKeys: new Set(okeys) - }; -} -function handleCatchall(proms, input, payload2, ctx, def, inst) { - const unrecognized = []; - const keySet = def.keySet; - const _catchall = def.catchall._zod; - const t5 = _catchall.def.type; - const isOptionalOut = _catchall.optout === "optional"; - for (const key in input) { - if (keySet.has(key)) - continue; - if (t5 === "never") { - unrecognized.push(key); - continue; - } - const r5 = _catchall.run({ value: input[key], issues: [] }, ctx); - if (r5 instanceof Promise) { - proms.push(r5.then((r6) => handlePropertyResult(r6, payload2, key, input, isOptionalOut))); - } else { - handlePropertyResult(r5, payload2, key, input, isOptionalOut); - } - } - if (unrecognized.length) { - payload2.issues.push({ - code: "unrecognized_keys", - keys: unrecognized, - input, - inst - }); - } - if (!proms.length) - return payload2; - return Promise.all(proms).then(() => { - return payload2; - }); -} -function handleUnionResults(results, final, inst, ctx) { - for (const result of results) { - if (result.issues.length === 0) { - final.value = result.value; - return final; - } - } - const nonaborted = results.filter((r5) => !aborted(r5)); - if (nonaborted.length === 1) { - final.value = nonaborted[0].value; - return nonaborted[0]; - } - final.issues.push({ - code: "invalid_union", - input: final.value, - inst, - errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) - }); - return final; -} -function handleExclusiveUnionResults(results, final, inst, ctx) { - const successes = results.filter((r5) => r5.issues.length === 0); - if (successes.length === 1) { - final.value = successes[0].value; - return final; - } - if (successes.length === 0) { - final.issues.push({ - code: "invalid_union", - input: final.value, - inst, - errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) - }); - } else { - final.issues.push({ - code: "invalid_union", - input: final.value, - inst, - errors: [], - inclusive: false - }); - } - return final; -} -function mergeValues2(a5, b6) { - if (a5 === b6) { - return { valid: true, data: a5 }; - } - if (a5 instanceof Date && b6 instanceof Date && +a5 === +b6) { - return { valid: true, data: a5 }; - } - if (isPlainObject5(a5) && isPlainObject5(b6)) { - const bKeys = Object.keys(b6); - const sharedKeys = Object.keys(a5).filter((key) => bKeys.indexOf(key) !== -1); - const newObj = { ...a5, ...b6 }; - for (const key of sharedKeys) { - const sharedValue = mergeValues2(a5[key], b6[key]); - if (!sharedValue.valid) { - return { - valid: false, - mergeErrorPath: [key, ...sharedValue.mergeErrorPath] - }; - } - newObj[key] = sharedValue.data; - } - return { valid: true, data: newObj }; - } - if (Array.isArray(a5) && Array.isArray(b6)) { - if (a5.length !== b6.length) { - return { valid: false, mergeErrorPath: [] }; - } - const newArray = []; - for (let index2 = 0; index2 < a5.length; index2++) { - const itemA = a5[index2]; - const itemB = b6[index2]; - const sharedValue = mergeValues2(itemA, itemB); - if (!sharedValue.valid) { - return { - valid: false, - mergeErrorPath: [index2, ...sharedValue.mergeErrorPath] - }; - } - newArray.push(sharedValue.data); - } - return { valid: true, data: newArray }; - } - return { valid: false, mergeErrorPath: [] }; -} -function handleIntersectionResults(result, left, right) { - const unrecKeys = /* @__PURE__ */ new Map(); - let unrecIssue; - for (const iss of left.issues) { - if (iss.code === "unrecognized_keys") { - unrecIssue ?? (unrecIssue = iss); - for (const k5 of iss.keys) { - if (!unrecKeys.has(k5)) - unrecKeys.set(k5, {}); - unrecKeys.get(k5).l = true; - } - } else { - result.issues.push(iss); - } - } - for (const iss of right.issues) { - if (iss.code === "unrecognized_keys") { - for (const k5 of iss.keys) { - if (!unrecKeys.has(k5)) - unrecKeys.set(k5, {}); - unrecKeys.get(k5).r = true; - } - } else { - result.issues.push(iss); - } - } - const bothKeys = [...unrecKeys].filter(([, f5]) => f5.l && f5.r).map(([k5]) => k5); - if (bothKeys.length && unrecIssue) { - result.issues.push({ ...unrecIssue, keys: bothKeys }); - } - if (aborted(result)) - return result; - const merged = mergeValues2(left.value, right.value); - if (!merged.valid) { - throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(merged.mergeErrorPath)}`); - } - result.value = merged.data; - return result; -} -function handleTupleResult(result, final, index2) { - if (result.issues.length) { - final.issues.push(...prefixIssues(index2, result.issues)); - } - final.value[index2] = result.value; -} -function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) { - if (keyResult.issues.length) { - if (propertyKeyTypes.has(typeof key)) { - final.issues.push(...prefixIssues(key, keyResult.issues)); - } else { - final.issues.push({ - code: "invalid_key", - origin: "map", - input, - inst, - issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())) - }); - } - } - if (valueResult.issues.length) { - if (propertyKeyTypes.has(typeof key)) { - final.issues.push(...prefixIssues(key, valueResult.issues)); - } else { - final.issues.push({ - origin: "map", - code: "invalid_element", - input, - inst, - key, - issues: valueResult.issues.map((iss) => finalizeIssue(iss, ctx, config())) - }); - } - } - final.value.set(keyResult.value, valueResult.value); -} -function handleSetResult(result, final) { - if (result.issues.length) { - final.issues.push(...result.issues); - } - final.value.add(result.value); -} -function handleOptionalResult(result, input) { - if (result.issues.length && input === void 0) { - return { issues: [], value: void 0 }; - } - return result; -} -function handleDefaultResult(payload2, def) { - if (payload2.value === void 0) { - payload2.value = def.defaultValue; - } - return payload2; -} -function handleNonOptionalResult(payload2, inst) { - if (!payload2.issues.length && payload2.value === void 0) { - payload2.issues.push({ - code: "invalid_type", - expected: "nonoptional", - input: payload2.value, - inst - }); - } - return payload2; -} -function handlePipeResult(left, next, ctx) { - if (left.issues.length) { - left.aborted = true; - return left; - } - return next._zod.run({ value: left.value, issues: left.issues }, ctx); -} -function handleCodecAResult(result, def, ctx) { - if (result.issues.length) { - result.aborted = true; - return result; - } - const direction = ctx.direction || "forward"; - if (direction === "forward") { - const transformed = def.transform(result.value, result); - if (transformed instanceof Promise) { - return transformed.then((value) => handleCodecTxResult(result, value, def.out, ctx)); - } - return handleCodecTxResult(result, transformed, def.out, ctx); - } else { - const transformed = def.reverseTransform(result.value, result); - if (transformed instanceof Promise) { - return transformed.then((value) => handleCodecTxResult(result, value, def.in, ctx)); - } - return handleCodecTxResult(result, transformed, def.in, ctx); - } -} -function handleCodecTxResult(left, value, nextSchema, ctx) { - if (left.issues.length) { - left.aborted = true; - return left; - } - return nextSchema._zod.run({ value, issues: left.issues }, ctx); -} -function handleReadonlyResult(payload2) { - payload2.value = Object.freeze(payload2.value); - return payload2; -} -function handleRefineResult(result, payload2, input, inst) { - if (!result) { - const _iss = { - code: "custom", - input, - inst, - // incorporates params.error into issue reporting - path: [...inst._zod.def.path ?? []], - // incorporates params.error into issue reporting - continue: !inst._zod.def.abort - // params: inst._zod.def.params, - }; - if (inst._zod.def.params) - _iss.params = inst._zod.def.params; - payload2.issues.push(issue(_iss)); - } -} -var $ZodType, $ZodString, $ZodStringFormat, $ZodGUID, $ZodUUID, $ZodEmail, $ZodURL, $ZodEmoji, $ZodNanoID, $ZodCUID, $ZodCUID2, $ZodULID, $ZodXID, $ZodKSUID, $ZodISODateTime, $ZodISODate, $ZodISOTime, $ZodISODuration, $ZodIPv4, $ZodIPv6, $ZodMAC, $ZodCIDRv4, $ZodCIDRv6, $ZodBase64, $ZodBase64URL, $ZodE164, $ZodJWT, $ZodCustomStringFormat, $ZodNumber, $ZodNumberFormat, $ZodBoolean, $ZodBigInt, $ZodBigIntFormat, $ZodSymbol, $ZodUndefined, $ZodNull, $ZodAny, $ZodUnknown, $ZodNever, $ZodVoid, $ZodDate, $ZodArray, $ZodObject, $ZodObjectJIT, $ZodUnion, $ZodXor, $ZodDiscriminatedUnion, $ZodIntersection, $ZodTuple, $ZodRecord, $ZodMap, $ZodSet, $ZodEnum, $ZodLiteral, $ZodFile, $ZodTransform, $ZodOptional, $ZodExactOptional, $ZodNullable, $ZodDefault, $ZodPrefault, $ZodNonOptional, $ZodSuccess, $ZodCatch, $ZodNaN, $ZodPipe, $ZodCodec, $ZodReadonly, $ZodTemplateLiteral, $ZodFunction, $ZodPromise, $ZodLazy, $ZodCustom; -var init_schemas = __esm({ - "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/schemas.js"() { - init_checks2(); - init_core(); - init_doc(); - init_parse(); - init_regexes(); - init_util(); - init_versions(); - init_util(); - $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => { - var _a6; - inst ?? (inst = {}); - inst._zod.def = def; - inst._zod.bag = inst._zod.bag || {}; - inst._zod.version = version2; - const checks = [...inst._zod.def.checks ?? []]; - if (inst._zod.traits.has("$ZodCheck")) { - checks.unshift(inst); - } - for (const ch of checks) { - for (const fn of ch._zod.onattach) { - fn(inst); - } - } - if (checks.length === 0) { - (_a6 = inst._zod).deferred ?? (_a6.deferred = []); - inst._zod.deferred?.push(() => { - inst._zod.run = inst._zod.parse; - }); - } else { - const runChecks = (payload2, checks2, ctx) => { - let isAborted2 = aborted(payload2); - let asyncResult; - for (const ch of checks2) { - if (ch._zod.def.when) { - const shouldRun = ch._zod.def.when(payload2); - if (!shouldRun) - continue; - } else if (isAborted2) { - continue; - } - const currLen = payload2.issues.length; - const _ = ch._zod.check(payload2); - if (_ instanceof Promise && ctx?.async === false) { - throw new $ZodAsyncError(); - } - if (asyncResult || _ instanceof Promise) { - asyncResult = (asyncResult ?? Promise.resolve()).then(async () => { - await _; - const nextLen = payload2.issues.length; - if (nextLen === currLen) - return; - if (!isAborted2) - isAborted2 = aborted(payload2, currLen); - }); - } else { - const nextLen = payload2.issues.length; - if (nextLen === currLen) - continue; - if (!isAborted2) - isAborted2 = aborted(payload2, currLen); - } - } - if (asyncResult) { - return asyncResult.then(() => { - return payload2; - }); - } - return payload2; - }; - const handleCanaryResult = (canary, payload2, ctx) => { - if (aborted(canary)) { - canary.aborted = true; - return canary; - } - const checkResult = runChecks(payload2, checks, ctx); - if (checkResult instanceof Promise) { - if (ctx.async === false) - throw new $ZodAsyncError(); - return checkResult.then((checkResult2) => inst._zod.parse(checkResult2, ctx)); - } - return inst._zod.parse(checkResult, ctx); - }; - inst._zod.run = (payload2, ctx) => { - if (ctx.skipChecks) { - return inst._zod.parse(payload2, ctx); - } - if (ctx.direction === "backward") { - const canary = inst._zod.parse({ value: payload2.value, issues: [] }, { ...ctx, skipChecks: true }); - if (canary instanceof Promise) { - return canary.then((canary2) => { - return handleCanaryResult(canary2, payload2, ctx); - }); - } - return handleCanaryResult(canary, payload2, ctx); - } - const result = inst._zod.parse(payload2, ctx); - if (result instanceof Promise) { - if (ctx.async === false) - throw new $ZodAsyncError(); - return result.then((result2) => runChecks(result2, checks, ctx)); - } - return runChecks(result, checks, ctx); - }; - } - defineLazy(inst, "~standard", () => ({ - validate: (value) => { - try { - const r5 = safeParse(inst, value); - return r5.success ? { value: r5.data } : { issues: r5.error?.issues }; - } catch (_) { - return safeParseAsync(inst, value).then((r5) => r5.success ? { value: r5.data } : { issues: r5.error?.issues }); - } - }, - vendor: "zod", - version: 1 - })); - }); - $ZodString = /* @__PURE__ */ $constructor("$ZodString", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.pattern = [...inst?._zod.bag?.patterns ?? []].pop() ?? string(inst._zod.bag); - inst._zod.parse = (payload2, _) => { - if (def.coerce) - try { - payload2.value = String(payload2.value); - } catch (_2) { - } - if (typeof payload2.value === "string") - return payload2; - payload2.issues.push({ - expected: "string", - code: "invalid_type", - input: payload2.value, - inst - }); - return payload2; - }; - }); - $ZodStringFormat = /* @__PURE__ */ $constructor("$ZodStringFormat", (inst, def) => { - $ZodCheckStringFormat.init(inst, def); - $ZodString.init(inst, def); - }); - $ZodGUID = /* @__PURE__ */ $constructor("$ZodGUID", (inst, def) => { - def.pattern ?? (def.pattern = guid); - $ZodStringFormat.init(inst, def); - }); - $ZodUUID = /* @__PURE__ */ $constructor("$ZodUUID", (inst, def) => { - if (def.version) { - const versionMap = { - v1: 1, - v2: 2, - v3: 3, - v4: 4, - v5: 5, - v6: 6, - v7: 7, - v8: 8 - }; - const v5 = versionMap[def.version]; - if (v5 === void 0) - throw new Error(`Invalid UUID version: "${def.version}"`); - def.pattern ?? (def.pattern = uuid2(v5)); - } else - def.pattern ?? (def.pattern = uuid2()); - $ZodStringFormat.init(inst, def); - }); - $ZodEmail = /* @__PURE__ */ $constructor("$ZodEmail", (inst, def) => { - def.pattern ?? (def.pattern = email); - $ZodStringFormat.init(inst, def); - }); - $ZodURL = /* @__PURE__ */ $constructor("$ZodURL", (inst, def) => { - $ZodStringFormat.init(inst, def); - inst._zod.check = (payload2) => { - try { - const trimmed = payload2.value.trim(); - const url2 = new URL(trimmed); - if (def.hostname) { - def.hostname.lastIndex = 0; - if (!def.hostname.test(url2.hostname)) { - payload2.issues.push({ - code: "invalid_format", - format: "url", - note: "Invalid hostname", - pattern: def.hostname.source, - input: payload2.value, - inst, - continue: !def.abort - }); - } - } - if (def.protocol) { - def.protocol.lastIndex = 0; - if (!def.protocol.test(url2.protocol.endsWith(":") ? url2.protocol.slice(0, -1) : url2.protocol)) { - payload2.issues.push({ - code: "invalid_format", - format: "url", - note: "Invalid protocol", - pattern: def.protocol.source, - input: payload2.value, - inst, - continue: !def.abort - }); - } - } - if (def.normalize) { - payload2.value = url2.href; - } else { - payload2.value = trimmed; - } - return; - } catch (_) { - payload2.issues.push({ - code: "invalid_format", - format: "url", - input: payload2.value, - inst, - continue: !def.abort - }); - } - }; - }); - $ZodEmoji = /* @__PURE__ */ $constructor("$ZodEmoji", (inst, def) => { - def.pattern ?? (def.pattern = emoji()); - $ZodStringFormat.init(inst, def); - }); - $ZodNanoID = /* @__PURE__ */ $constructor("$ZodNanoID", (inst, def) => { - def.pattern ?? (def.pattern = nanoid); - $ZodStringFormat.init(inst, def); - }); - $ZodCUID = /* @__PURE__ */ $constructor("$ZodCUID", (inst, def) => { - def.pattern ?? (def.pattern = cuid); - $ZodStringFormat.init(inst, def); - }); - $ZodCUID2 = /* @__PURE__ */ $constructor("$ZodCUID2", (inst, def) => { - def.pattern ?? (def.pattern = cuid2); - $ZodStringFormat.init(inst, def); - }); - $ZodULID = /* @__PURE__ */ $constructor("$ZodULID", (inst, def) => { - def.pattern ?? (def.pattern = ulid); - $ZodStringFormat.init(inst, def); - }); - $ZodXID = /* @__PURE__ */ $constructor("$ZodXID", (inst, def) => { - def.pattern ?? (def.pattern = xid); - $ZodStringFormat.init(inst, def); - }); - $ZodKSUID = /* @__PURE__ */ $constructor("$ZodKSUID", (inst, def) => { - def.pattern ?? (def.pattern = ksuid); - $ZodStringFormat.init(inst, def); - }); - $ZodISODateTime = /* @__PURE__ */ $constructor("$ZodISODateTime", (inst, def) => { - def.pattern ?? (def.pattern = datetime(def)); - $ZodStringFormat.init(inst, def); - }); - $ZodISODate = /* @__PURE__ */ $constructor("$ZodISODate", (inst, def) => { - def.pattern ?? (def.pattern = date3); - $ZodStringFormat.init(inst, def); - }); - $ZodISOTime = /* @__PURE__ */ $constructor("$ZodISOTime", (inst, def) => { - def.pattern ?? (def.pattern = time3(def)); - $ZodStringFormat.init(inst, def); - }); - $ZodISODuration = /* @__PURE__ */ $constructor("$ZodISODuration", (inst, def) => { - def.pattern ?? (def.pattern = duration); - $ZodStringFormat.init(inst, def); - }); - $ZodIPv4 = /* @__PURE__ */ $constructor("$ZodIPv4", (inst, def) => { - def.pattern ?? (def.pattern = ipv4); - $ZodStringFormat.init(inst, def); - inst._zod.bag.format = `ipv4`; - }); - $ZodIPv6 = /* @__PURE__ */ $constructor("$ZodIPv6", (inst, def) => { - def.pattern ?? (def.pattern = ipv6); - $ZodStringFormat.init(inst, def); - inst._zod.bag.format = `ipv6`; - inst._zod.check = (payload2) => { - try { - new URL(`http://[${payload2.value}]`); - } catch { - payload2.issues.push({ - code: "invalid_format", - format: "ipv6", - input: payload2.value, - inst, - continue: !def.abort - }); - } - }; - }); - $ZodMAC = /* @__PURE__ */ $constructor("$ZodMAC", (inst, def) => { - def.pattern ?? (def.pattern = mac(def.delimiter)); - $ZodStringFormat.init(inst, def); - inst._zod.bag.format = `mac`; - }); - $ZodCIDRv4 = /* @__PURE__ */ $constructor("$ZodCIDRv4", (inst, def) => { - def.pattern ?? (def.pattern = cidrv4); - $ZodStringFormat.init(inst, def); - }); - $ZodCIDRv6 = /* @__PURE__ */ $constructor("$ZodCIDRv6", (inst, def) => { - def.pattern ?? (def.pattern = cidrv6); - $ZodStringFormat.init(inst, def); - inst._zod.check = (payload2) => { - const parts = payload2.value.split("/"); - try { - if (parts.length !== 2) - throw new Error(); - const [address, prefix] = parts; - if (!prefix) - throw new Error(); - const prefixNum = Number(prefix); - if (`${prefixNum}` !== prefix) - throw new Error(); - if (prefixNum < 0 || prefixNum > 128) - throw new Error(); - new URL(`http://[${address}]`); - } catch { - payload2.issues.push({ - code: "invalid_format", - format: "cidrv6", - input: payload2.value, - inst, - continue: !def.abort - }); - } - }; - }); - $ZodBase64 = /* @__PURE__ */ $constructor("$ZodBase64", (inst, def) => { - def.pattern ?? (def.pattern = base64); - $ZodStringFormat.init(inst, def); - inst._zod.bag.contentEncoding = "base64"; - inst._zod.check = (payload2) => { - if (isValidBase64(payload2.value)) - return; - payload2.issues.push({ - code: "invalid_format", - format: "base64", - input: payload2.value, - inst, - continue: !def.abort - }); - }; - }); - $ZodBase64URL = /* @__PURE__ */ $constructor("$ZodBase64URL", (inst, def) => { - def.pattern ?? (def.pattern = base64url); - $ZodStringFormat.init(inst, def); - inst._zod.bag.contentEncoding = "base64url"; - inst._zod.check = (payload2) => { - if (isValidBase64URL(payload2.value)) - return; - payload2.issues.push({ - code: "invalid_format", - format: "base64url", - input: payload2.value, - inst, - continue: !def.abort - }); - }; - }); - $ZodE164 = /* @__PURE__ */ $constructor("$ZodE164", (inst, def) => { - def.pattern ?? (def.pattern = e164); - $ZodStringFormat.init(inst, def); - }); - $ZodJWT = /* @__PURE__ */ $constructor("$ZodJWT", (inst, def) => { - $ZodStringFormat.init(inst, def); - inst._zod.check = (payload2) => { - if (isValidJWT2(payload2.value, def.alg)) - return; - payload2.issues.push({ - code: "invalid_format", - format: "jwt", - input: payload2.value, - inst, - continue: !def.abort - }); - }; - }); - $ZodCustomStringFormat = /* @__PURE__ */ $constructor("$ZodCustomStringFormat", (inst, def) => { - $ZodStringFormat.init(inst, def); - inst._zod.check = (payload2) => { - if (def.fn(payload2.value)) - return; - payload2.issues.push({ - code: "invalid_format", - format: def.format, - input: payload2.value, - inst, - continue: !def.abort - }); - }; - }); - $ZodNumber = /* @__PURE__ */ $constructor("$ZodNumber", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.pattern = inst._zod.bag.pattern ?? number; - inst._zod.parse = (payload2, _ctx) => { - if (def.coerce) - try { - payload2.value = Number(payload2.value); - } catch (_) { - } - const input = payload2.value; - if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) { - return payload2; - } - const received = typeof input === "number" ? Number.isNaN(input) ? "NaN" : !Number.isFinite(input) ? "Infinity" : void 0 : void 0; - payload2.issues.push({ - expected: "number", - code: "invalid_type", - input, - inst, - ...received ? { received } : {} - }); - return payload2; - }; - }); - $ZodNumberFormat = /* @__PURE__ */ $constructor("$ZodNumberFormat", (inst, def) => { - $ZodCheckNumberFormat.init(inst, def); - $ZodNumber.init(inst, def); - }); - $ZodBoolean = /* @__PURE__ */ $constructor("$ZodBoolean", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.pattern = boolean2; - inst._zod.parse = (payload2, _ctx) => { - if (def.coerce) - try { - payload2.value = Boolean(payload2.value); - } catch (_) { - } - const input = payload2.value; - if (typeof input === "boolean") - return payload2; - payload2.issues.push({ - expected: "boolean", - code: "invalid_type", - input, - inst - }); - return payload2; - }; - }); - $ZodBigInt = /* @__PURE__ */ $constructor("$ZodBigInt", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.pattern = bigint2; - inst._zod.parse = (payload2, _ctx) => { - if (def.coerce) - try { - payload2.value = BigInt(payload2.value); - } catch (_) { - } - if (typeof payload2.value === "bigint") - return payload2; - payload2.issues.push({ - expected: "bigint", - code: "invalid_type", - input: payload2.value, - inst - }); - return payload2; - }; - }); - $ZodBigIntFormat = /* @__PURE__ */ $constructor("$ZodBigIntFormat", (inst, def) => { - $ZodCheckBigIntFormat.init(inst, def); - $ZodBigInt.init(inst, def); - }); - $ZodSymbol = /* @__PURE__ */ $constructor("$ZodSymbol", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload2, _ctx) => { - const input = payload2.value; - if (typeof input === "symbol") - return payload2; - payload2.issues.push({ - expected: "symbol", - code: "invalid_type", - input, - inst - }); - return payload2; - }; - }); - $ZodUndefined = /* @__PURE__ */ $constructor("$ZodUndefined", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.pattern = _undefined; - inst._zod.values = /* @__PURE__ */ new Set([void 0]); - inst._zod.optin = "optional"; - inst._zod.optout = "optional"; - inst._zod.parse = (payload2, _ctx) => { - const input = payload2.value; - if (typeof input === "undefined") - return payload2; - payload2.issues.push({ - expected: "undefined", - code: "invalid_type", - input, - inst - }); - return payload2; - }; - }); - $ZodNull = /* @__PURE__ */ $constructor("$ZodNull", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.pattern = _null; - inst._zod.values = /* @__PURE__ */ new Set([null]); - inst._zod.parse = (payload2, _ctx) => { - const input = payload2.value; - if (input === null) - return payload2; - payload2.issues.push({ - expected: "null", - code: "invalid_type", - input, - inst - }); - return payload2; - }; - }); - $ZodAny = /* @__PURE__ */ $constructor("$ZodAny", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload2) => payload2; - }); - $ZodUnknown = /* @__PURE__ */ $constructor("$ZodUnknown", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload2) => payload2; - }); - $ZodNever = /* @__PURE__ */ $constructor("$ZodNever", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload2, _ctx) => { - payload2.issues.push({ - expected: "never", - code: "invalid_type", - input: payload2.value, - inst - }); - return payload2; - }; - }); - $ZodVoid = /* @__PURE__ */ $constructor("$ZodVoid", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload2, _ctx) => { - const input = payload2.value; - if (typeof input === "undefined") - return payload2; - payload2.issues.push({ - expected: "void", - code: "invalid_type", - input, - inst - }); - return payload2; - }; - }); - $ZodDate = /* @__PURE__ */ $constructor("$ZodDate", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload2, _ctx) => { - if (def.coerce) { - try { - payload2.value = new Date(payload2.value); - } catch (_err) { - } - } - const input = payload2.value; - const isDate2 = input instanceof Date; - const isValidDate = isDate2 && !Number.isNaN(input.getTime()); - if (isValidDate) - return payload2; - payload2.issues.push({ - expected: "date", - code: "invalid_type", - input, - ...isDate2 ? { received: "Invalid Date" } : {}, - inst - }); - return payload2; - }; - }); - $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload2, ctx) => { - const input = payload2.value; - if (!Array.isArray(input)) { - payload2.issues.push({ - expected: "array", - code: "invalid_type", - input, - inst - }); - return payload2; - } - payload2.value = Array(input.length); - const proms = []; - for (let i5 = 0; i5 < input.length; i5++) { - const item = input[i5]; - const result = def.element._zod.run({ - value: item, - issues: [] - }, ctx); - if (result instanceof Promise) { - proms.push(result.then((result2) => handleArrayResult(result2, payload2, i5))); - } else { - handleArrayResult(result, payload2, i5); - } - } - if (proms.length) { - return Promise.all(proms).then(() => payload2); - } - return payload2; - }; - }); - $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => { - $ZodType.init(inst, def); - const desc3 = Object.getOwnPropertyDescriptor(def, "shape"); - if (!desc3?.get) { - const sh = def.shape; - Object.defineProperty(def, "shape", { - get: () => { - const newSh = { ...sh }; - Object.defineProperty(def, "shape", { - value: newSh - }); - return newSh; - } - }); - } - const _normalized = cached3(() => normalizeDef(def)); - defineLazy(inst._zod, "propValues", () => { - const shape = def.shape; - const propValues = {}; - for (const key in shape) { - const field = shape[key]._zod; - if (field.values) { - propValues[key] ?? (propValues[key] = /* @__PURE__ */ new Set()); - for (const v5 of field.values) - propValues[key].add(v5); - } - } - return propValues; - }); - const isObject4 = isObject2; - const catchall = def.catchall; - let value; - inst._zod.parse = (payload2, ctx) => { - value ?? (value = _normalized.value); - const input = payload2.value; - if (!isObject4(input)) { - payload2.issues.push({ - expected: "object", - code: "invalid_type", - input, - inst - }); - return payload2; - } - payload2.value = {}; - const proms = []; - const shape = value.shape; - for (const key of value.keys) { - const el = shape[key]; - const isOptionalOut = el._zod.optout === "optional"; - const r5 = el._zod.run({ value: input[key], issues: [] }, ctx); - if (r5 instanceof Promise) { - proms.push(r5.then((r6) => handlePropertyResult(r6, payload2, key, input, isOptionalOut))); - } else { - handlePropertyResult(r5, payload2, key, input, isOptionalOut); - } - } - if (!catchall) { - return proms.length ? Promise.all(proms).then(() => payload2) : payload2; - } - return handleCatchall(proms, input, payload2, ctx, _normalized.value, inst); - }; - }); - $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) => { - $ZodObject.init(inst, def); - const superParse = inst._zod.parse; - const _normalized = cached3(() => normalizeDef(def)); - const generateFastpass = (shape) => { - const doc = new Doc(["shape", "payload", "ctx"]); - const normalized = _normalized.value; - const parseStr = (key) => { - const k5 = esc(key); - return `shape[${k5}]._zod.run({ value: input[${k5}], issues: [] }, ctx)`; - }; - doc.write(`const input = payload.value;`); - const ids = /* @__PURE__ */ Object.create(null); - let counter = 0; - for (const key of normalized.keys) { - ids[key] = `key_${counter++}`; - } - doc.write(`const newResult = {};`); - for (const key of normalized.keys) { - const id = ids[key]; - const k5 = esc(key); - const schema2 = shape[key]; - const isOptionalOut = schema2?._zod?.optout === "optional"; - doc.write(`const ${id} = ${parseStr(key)};`); - if (isOptionalOut) { - doc.write(` - if (${id}.issues.length) { - if (${k5} in input) { - payload.issues = payload.issues.concat(${id}.issues.map(iss => ({ - ...iss, - path: iss.path ? [${k5}, ...iss.path] : [${k5}] - }))); - } - } - - if (${id}.value === undefined) { - if (${k5} in input) { - newResult[${k5}] = undefined; - } - } else { - newResult[${k5}] = ${id}.value; - } - - `); - } else { - doc.write(` - if (${id}.issues.length) { - payload.issues = payload.issues.concat(${id}.issues.map(iss => ({ - ...iss, - path: iss.path ? [${k5}, ...iss.path] : [${k5}] - }))); - } - - if (${id}.value === undefined) { - if (${k5} in input) { - newResult[${k5}] = undefined; - } - } else { - newResult[${k5}] = ${id}.value; - } - - `); - } - } - doc.write(`payload.value = newResult;`); - doc.write(`return payload;`); - const fn = doc.compile(); - return (payload2, ctx) => fn(shape, payload2, ctx); - }; - let fastpass; - const isObject4 = isObject2; - const jit = !globalConfig.jitless; - const allowsEval2 = allowsEval; - const fastEnabled = jit && allowsEval2.value; - const catchall = def.catchall; - let value; - inst._zod.parse = (payload2, ctx) => { - value ?? (value = _normalized.value); - const input = payload2.value; - if (!isObject4(input)) { - payload2.issues.push({ - expected: "object", - code: "invalid_type", - input, - inst - }); - return payload2; - } - if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) { - if (!fastpass) - fastpass = generateFastpass(def.shape); - payload2 = fastpass(payload2, ctx); - if (!catchall) - return payload2; - return handleCatchall([], input, payload2, ctx, value, inst); - } - return superParse(payload2, ctx); - }; - }); - $ZodUnion = /* @__PURE__ */ $constructor("$ZodUnion", (inst, def) => { - $ZodType.init(inst, def); - defineLazy(inst._zod, "optin", () => def.options.some((o5) => o5._zod.optin === "optional") ? "optional" : void 0); - defineLazy(inst._zod, "optout", () => def.options.some((o5) => o5._zod.optout === "optional") ? "optional" : void 0); - defineLazy(inst._zod, "values", () => { - if (def.options.every((o5) => o5._zod.values)) { - return new Set(def.options.flatMap((option) => Array.from(option._zod.values))); - } - return void 0; - }); - defineLazy(inst._zod, "pattern", () => { - if (def.options.every((o5) => o5._zod.pattern)) { - const patterns = def.options.map((o5) => o5._zod.pattern); - return new RegExp(`^(${patterns.map((p5) => cleanRegex(p5.source)).join("|")})$`); - } - return void 0; - }); - const single = def.options.length === 1; - const first = def.options[0]._zod.run; - inst._zod.parse = (payload2, ctx) => { - if (single) { - return first(payload2, ctx); - } - let async = false; - const results = []; - for (const option of def.options) { - const result = option._zod.run({ - value: payload2.value, - issues: [] - }, ctx); - if (result instanceof Promise) { - results.push(result); - async = true; - } else { - if (result.issues.length === 0) - return result; - results.push(result); - } - } - if (!async) - return handleUnionResults(results, payload2, inst, ctx); - return Promise.all(results).then((results2) => { - return handleUnionResults(results2, payload2, inst, ctx); - }); - }; - }); - $ZodXor = /* @__PURE__ */ $constructor("$ZodXor", (inst, def) => { - $ZodUnion.init(inst, def); - def.inclusive = false; - const single = def.options.length === 1; - const first = def.options[0]._zod.run; - inst._zod.parse = (payload2, ctx) => { - if (single) { - return first(payload2, ctx); - } - let async = false; - const results = []; - for (const option of def.options) { - const result = option._zod.run({ - value: payload2.value, - issues: [] - }, ctx); - if (result instanceof Promise) { - results.push(result); - async = true; - } else { - results.push(result); - } - } - if (!async) - return handleExclusiveUnionResults(results, payload2, inst, ctx); - return Promise.all(results).then((results2) => { - return handleExclusiveUnionResults(results2, payload2, inst, ctx); - }); - }; - }); - $ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("$ZodDiscriminatedUnion", (inst, def) => { - def.inclusive = false; - $ZodUnion.init(inst, def); - const _super = inst._zod.parse; - defineLazy(inst._zod, "propValues", () => { - const propValues = {}; - for (const option of def.options) { - const pv = option._zod.propValues; - if (!pv || Object.keys(pv).length === 0) - throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`); - for (const [k5, v5] of Object.entries(pv)) { - if (!propValues[k5]) - propValues[k5] = /* @__PURE__ */ new Set(); - for (const val of v5) { - propValues[k5].add(val); - } - } - } - return propValues; - }); - const disc = cached3(() => { - const opts = def.options; - const map4 = /* @__PURE__ */ new Map(); - for (const o5 of opts) { - const values2 = o5._zod.propValues?.[def.discriminator]; - if (!values2 || values2.size === 0) - throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(o5)}"`); - for (const v5 of values2) { - if (map4.has(v5)) { - throw new Error(`Duplicate discriminator value "${String(v5)}"`); - } - map4.set(v5, o5); - } - } - return map4; - }); - inst._zod.parse = (payload2, ctx) => { - const input = payload2.value; - if (!isObject2(input)) { - payload2.issues.push({ - code: "invalid_type", - expected: "object", - input, - inst - }); - return payload2; - } - const opt = disc.value.get(input?.[def.discriminator]); - if (opt) { - return opt._zod.run(payload2, ctx); - } - if (def.unionFallback) { - return _super(payload2, ctx); - } - payload2.issues.push({ - code: "invalid_union", - errors: [], - note: "No matching discriminator", - discriminator: def.discriminator, - input, - path: [def.discriminator], - inst - }); - return payload2; - }; - }); - $ZodIntersection = /* @__PURE__ */ $constructor("$ZodIntersection", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload2, ctx) => { - const input = payload2.value; - const left = def.left._zod.run({ value: input, issues: [] }, ctx); - const right = def.right._zod.run({ value: input, issues: [] }, ctx); - const async = left instanceof Promise || right instanceof Promise; - if (async) { - return Promise.all([left, right]).then(([left2, right2]) => { - return handleIntersectionResults(payload2, left2, right2); - }); - } - return handleIntersectionResults(payload2, left, right); - }; - }); - $ZodTuple = /* @__PURE__ */ $constructor("$ZodTuple", (inst, def) => { - $ZodType.init(inst, def); - const items = def.items; - inst._zod.parse = (payload2, ctx) => { - const input = payload2.value; - if (!Array.isArray(input)) { - payload2.issues.push({ - input, - inst, - expected: "tuple", - code: "invalid_type" - }); - return payload2; - } - payload2.value = []; - const proms = []; - const reversedIndex = [...items].reverse().findIndex((item) => item._zod.optin !== "optional"); - const optStart = reversedIndex === -1 ? 0 : items.length - reversedIndex; - if (!def.rest) { - const tooBig = input.length > items.length; - const tooSmall = input.length < optStart - 1; - if (tooBig || tooSmall) { - payload2.issues.push({ - ...tooBig ? { code: "too_big", maximum: items.length, inclusive: true } : { code: "too_small", minimum: items.length }, - input, - inst, - origin: "array" - }); - return payload2; - } - } - let i5 = -1; - for (const item of items) { - i5++; - if (i5 >= input.length) { - if (i5 >= optStart) - continue; - } - const result = item._zod.run({ - value: input[i5], - issues: [] - }, ctx); - if (result instanceof Promise) { - proms.push(result.then((result2) => handleTupleResult(result2, payload2, i5))); - } else { - handleTupleResult(result, payload2, i5); - } - } - if (def.rest) { - const rest = input.slice(items.length); - for (const el of rest) { - i5++; - const result = def.rest._zod.run({ - value: el, - issues: [] - }, ctx); - if (result instanceof Promise) { - proms.push(result.then((result2) => handleTupleResult(result2, payload2, i5))); - } else { - handleTupleResult(result, payload2, i5); - } - } - } - if (proms.length) - return Promise.all(proms).then(() => payload2); - return payload2; - }; - }); - $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload2, ctx) => { - const input = payload2.value; - if (!isPlainObject5(input)) { - payload2.issues.push({ - expected: "record", - code: "invalid_type", - input, - inst - }); - return payload2; - } - const proms = []; - const values2 = def.keyType._zod.values; - if (values2) { - payload2.value = {}; - const recordKeys = /* @__PURE__ */ new Set(); - for (const key of values2) { - if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") { - recordKeys.add(typeof key === "number" ? key.toString() : key); - const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); - if (result instanceof Promise) { - proms.push(result.then((result2) => { - if (result2.issues.length) { - payload2.issues.push(...prefixIssues(key, result2.issues)); - } - payload2.value[key] = result2.value; - })); - } else { - if (result.issues.length) { - payload2.issues.push(...prefixIssues(key, result.issues)); - } - payload2.value[key] = result.value; - } - } - } - let unrecognized; - for (const key in input) { - if (!recordKeys.has(key)) { - unrecognized = unrecognized ?? []; - unrecognized.push(key); - } - } - if (unrecognized && unrecognized.length > 0) { - payload2.issues.push({ - code: "unrecognized_keys", - input, - inst, - keys: unrecognized - }); - } - } else { - payload2.value = {}; - for (const key of Reflect.ownKeys(input)) { - if (key === "__proto__") - continue; - let keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); - if (keyResult instanceof Promise) { - throw new Error("Async schemas not supported in object keys currently"); - } - const checkNumericKey = typeof key === "string" && number.test(key) && keyResult.issues.length; - if (checkNumericKey) { - const retryResult = def.keyType._zod.run({ value: Number(key), issues: [] }, ctx); - if (retryResult instanceof Promise) { - throw new Error("Async schemas not supported in object keys currently"); - } - if (retryResult.issues.length === 0) { - keyResult = retryResult; - } - } - if (keyResult.issues.length) { - if (def.mode === "loose") { - payload2.value[key] = input[key]; - } else { - payload2.issues.push({ - code: "invalid_key", - origin: "record", - issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())), - input: key, - path: [key], - inst - }); - } - continue; - } - const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); - if (result instanceof Promise) { - proms.push(result.then((result2) => { - if (result2.issues.length) { - payload2.issues.push(...prefixIssues(key, result2.issues)); - } - payload2.value[keyResult.value] = result2.value; - })); - } else { - if (result.issues.length) { - payload2.issues.push(...prefixIssues(key, result.issues)); - } - payload2.value[keyResult.value] = result.value; - } - } - } - if (proms.length) { - return Promise.all(proms).then(() => payload2); - } - return payload2; - }; - }); - $ZodMap = /* @__PURE__ */ $constructor("$ZodMap", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload2, ctx) => { - const input = payload2.value; - if (!(input instanceof Map)) { - payload2.issues.push({ - expected: "map", - code: "invalid_type", - input, - inst - }); - return payload2; - } - const proms = []; - payload2.value = /* @__PURE__ */ new Map(); - for (const [key, value] of input) { - const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); - const valueResult = def.valueType._zod.run({ value, issues: [] }, ctx); - if (keyResult instanceof Promise || valueResult instanceof Promise) { - proms.push(Promise.all([keyResult, valueResult]).then(([keyResult2, valueResult2]) => { - handleMapResult(keyResult2, valueResult2, payload2, key, input, inst, ctx); - })); - } else { - handleMapResult(keyResult, valueResult, payload2, key, input, inst, ctx); - } - } - if (proms.length) - return Promise.all(proms).then(() => payload2); - return payload2; - }; - }); - $ZodSet = /* @__PURE__ */ $constructor("$ZodSet", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload2, ctx) => { - const input = payload2.value; - if (!(input instanceof Set)) { - payload2.issues.push({ - input, - inst, - expected: "set", - code: "invalid_type" - }); - return payload2; - } - const proms = []; - payload2.value = /* @__PURE__ */ new Set(); - for (const item of input) { - const result = def.valueType._zod.run({ value: item, issues: [] }, ctx); - if (result instanceof Promise) { - proms.push(result.then((result2) => handleSetResult(result2, payload2))); - } else - handleSetResult(result, payload2); - } - if (proms.length) - return Promise.all(proms).then(() => payload2); - return payload2; - }; - }); - $ZodEnum = /* @__PURE__ */ $constructor("$ZodEnum", (inst, def) => { - $ZodType.init(inst, def); - const values2 = getEnumValues(def.entries); - const valuesSet = new Set(values2); - inst._zod.values = valuesSet; - inst._zod.pattern = new RegExp(`^(${values2.filter((k5) => propertyKeyTypes.has(typeof k5)).map((o5) => typeof o5 === "string" ? escapeRegex(o5) : o5.toString()).join("|")})$`); - inst._zod.parse = (payload2, _ctx) => { - const input = payload2.value; - if (valuesSet.has(input)) { - return payload2; - } - payload2.issues.push({ - code: "invalid_value", - values: values2, - input, - inst - }); - return payload2; - }; - }); - $ZodLiteral = /* @__PURE__ */ $constructor("$ZodLiteral", (inst, def) => { - $ZodType.init(inst, def); - if (def.values.length === 0) { - throw new Error("Cannot create literal schema with no valid values"); - } - const values2 = new Set(def.values); - inst._zod.values = values2; - inst._zod.pattern = new RegExp(`^(${def.values.map((o5) => typeof o5 === "string" ? escapeRegex(o5) : o5 ? escapeRegex(o5.toString()) : String(o5)).join("|")})$`); - inst._zod.parse = (payload2, _ctx) => { - const input = payload2.value; - if (values2.has(input)) { - return payload2; - } - payload2.issues.push({ - code: "invalid_value", - values: def.values, - input, - inst - }); - return payload2; - }; - }); - $ZodFile = /* @__PURE__ */ $constructor("$ZodFile", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload2, _ctx) => { - const input = payload2.value; - if (input instanceof File) - return payload2; - payload2.issues.push({ - expected: "file", - code: "invalid_type", - input, - inst - }); - return payload2; - }; - }); - $ZodTransform = /* @__PURE__ */ $constructor("$ZodTransform", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload2, ctx) => { - if (ctx.direction === "backward") { - throw new $ZodEncodeError(inst.constructor.name); - } - const _out = def.transform(payload2.value, payload2); - if (ctx.async) { - const output = _out instanceof Promise ? _out : Promise.resolve(_out); - return output.then((output2) => { - payload2.value = output2; - return payload2; - }); - } - if (_out instanceof Promise) { - throw new $ZodAsyncError(); - } - payload2.value = _out; - return payload2; - }; - }); - $ZodOptional = /* @__PURE__ */ $constructor("$ZodOptional", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.optin = "optional"; - inst._zod.optout = "optional"; - defineLazy(inst._zod, "values", () => { - return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, void 0]) : void 0; - }); - defineLazy(inst._zod, "pattern", () => { - const pattern = def.innerType._zod.pattern; - return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : void 0; - }); - inst._zod.parse = (payload2, ctx) => { - if (def.innerType._zod.optin === "optional") { - const result = def.innerType._zod.run(payload2, ctx); - if (result instanceof Promise) - return result.then((r5) => handleOptionalResult(r5, payload2.value)); - return handleOptionalResult(result, payload2.value); - } - if (payload2.value === void 0) { - return payload2; - } - return def.innerType._zod.run(payload2, ctx); - }; - }); - $ZodExactOptional = /* @__PURE__ */ $constructor("$ZodExactOptional", (inst, def) => { - $ZodOptional.init(inst, def); - defineLazy(inst._zod, "values", () => def.innerType._zod.values); - defineLazy(inst._zod, "pattern", () => def.innerType._zod.pattern); - inst._zod.parse = (payload2, ctx) => { - return def.innerType._zod.run(payload2, ctx); - }; - }); - $ZodNullable = /* @__PURE__ */ $constructor("$ZodNullable", (inst, def) => { - $ZodType.init(inst, def); - defineLazy(inst._zod, "optin", () => def.innerType._zod.optin); - defineLazy(inst._zod, "optout", () => def.innerType._zod.optout); - defineLazy(inst._zod, "pattern", () => { - const pattern = def.innerType._zod.pattern; - return pattern ? new RegExp(`^(${cleanRegex(pattern.source)}|null)$`) : void 0; - }); - defineLazy(inst._zod, "values", () => { - return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, null]) : void 0; - }); - inst._zod.parse = (payload2, ctx) => { - if (payload2.value === null) - return payload2; - return def.innerType._zod.run(payload2, ctx); - }; - }); - $ZodDefault = /* @__PURE__ */ $constructor("$ZodDefault", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.optin = "optional"; - defineLazy(inst._zod, "values", () => def.innerType._zod.values); - inst._zod.parse = (payload2, ctx) => { - if (ctx.direction === "backward") { - return def.innerType._zod.run(payload2, ctx); - } - if (payload2.value === void 0) { - payload2.value = def.defaultValue; - return payload2; - } - const result = def.innerType._zod.run(payload2, ctx); - if (result instanceof Promise) { - return result.then((result2) => handleDefaultResult(result2, def)); - } - return handleDefaultResult(result, def); - }; - }); - $ZodPrefault = /* @__PURE__ */ $constructor("$ZodPrefault", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.optin = "optional"; - defineLazy(inst._zod, "values", () => def.innerType._zod.values); - inst._zod.parse = (payload2, ctx) => { - if (ctx.direction === "backward") { - return def.innerType._zod.run(payload2, ctx); - } - if (payload2.value === void 0) { - payload2.value = def.defaultValue; - } - return def.innerType._zod.run(payload2, ctx); - }; - }); - $ZodNonOptional = /* @__PURE__ */ $constructor("$ZodNonOptional", (inst, def) => { - $ZodType.init(inst, def); - defineLazy(inst._zod, "values", () => { - const v5 = def.innerType._zod.values; - return v5 ? new Set([...v5].filter((x5) => x5 !== void 0)) : void 0; - }); - inst._zod.parse = (payload2, ctx) => { - const result = def.innerType._zod.run(payload2, ctx); - if (result instanceof Promise) { - return result.then((result2) => handleNonOptionalResult(result2, inst)); - } - return handleNonOptionalResult(result, inst); - }; - }); - $ZodSuccess = /* @__PURE__ */ $constructor("$ZodSuccess", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload2, ctx) => { - if (ctx.direction === "backward") { - throw new $ZodEncodeError("ZodSuccess"); - } - const result = def.innerType._zod.run(payload2, ctx); - if (result instanceof Promise) { - return result.then((result2) => { - payload2.value = result2.issues.length === 0; - return payload2; - }); - } - payload2.value = result.issues.length === 0; - return payload2; - }; - }); - $ZodCatch = /* @__PURE__ */ $constructor("$ZodCatch", (inst, def) => { - $ZodType.init(inst, def); - defineLazy(inst._zod, "optin", () => def.innerType._zod.optin); - defineLazy(inst._zod, "optout", () => def.innerType._zod.optout); - defineLazy(inst._zod, "values", () => def.innerType._zod.values); - inst._zod.parse = (payload2, ctx) => { - if (ctx.direction === "backward") { - return def.innerType._zod.run(payload2, ctx); - } - const result = def.innerType._zod.run(payload2, ctx); - if (result instanceof Promise) { - return result.then((result2) => { - payload2.value = result2.value; - if (result2.issues.length) { - payload2.value = def.catchValue({ - ...payload2, - error: { - issues: result2.issues.map((iss) => finalizeIssue(iss, ctx, config())) - }, - input: payload2.value - }); - payload2.issues = []; - } - return payload2; - }); - } - payload2.value = result.value; - if (result.issues.length) { - payload2.value = def.catchValue({ - ...payload2, - error: { - issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config())) - }, - input: payload2.value - }); - payload2.issues = []; - } - return payload2; - }; - }); - $ZodNaN = /* @__PURE__ */ $constructor("$ZodNaN", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload2, _ctx) => { - if (typeof payload2.value !== "number" || !Number.isNaN(payload2.value)) { - payload2.issues.push({ - input: payload2.value, - inst, - expected: "nan", - code: "invalid_type" - }); - return payload2; - } - return payload2; - }; - }); - $ZodPipe = /* @__PURE__ */ $constructor("$ZodPipe", (inst, def) => { - $ZodType.init(inst, def); - defineLazy(inst._zod, "values", () => def.in._zod.values); - defineLazy(inst._zod, "optin", () => def.in._zod.optin); - defineLazy(inst._zod, "optout", () => def.out._zod.optout); - defineLazy(inst._zod, "propValues", () => def.in._zod.propValues); - inst._zod.parse = (payload2, ctx) => { - if (ctx.direction === "backward") { - const right = def.out._zod.run(payload2, ctx); - if (right instanceof Promise) { - return right.then((right2) => handlePipeResult(right2, def.in, ctx)); - } - return handlePipeResult(right, def.in, ctx); - } - const left = def.in._zod.run(payload2, ctx); - if (left instanceof Promise) { - return left.then((left2) => handlePipeResult(left2, def.out, ctx)); - } - return handlePipeResult(left, def.out, ctx); - }; - }); - $ZodCodec = /* @__PURE__ */ $constructor("$ZodCodec", (inst, def) => { - $ZodType.init(inst, def); - defineLazy(inst._zod, "values", () => def.in._zod.values); - defineLazy(inst._zod, "optin", () => def.in._zod.optin); - defineLazy(inst._zod, "optout", () => def.out._zod.optout); - defineLazy(inst._zod, "propValues", () => def.in._zod.propValues); - inst._zod.parse = (payload2, ctx) => { - const direction = ctx.direction || "forward"; - if (direction === "forward") { - const left = def.in._zod.run(payload2, ctx); - if (left instanceof Promise) { - return left.then((left2) => handleCodecAResult(left2, def, ctx)); - } - return handleCodecAResult(left, def, ctx); - } else { - const right = def.out._zod.run(payload2, ctx); - if (right instanceof Promise) { - return right.then((right2) => handleCodecAResult(right2, def, ctx)); - } - return handleCodecAResult(right, def, ctx); - } - }; - }); - $ZodReadonly = /* @__PURE__ */ $constructor("$ZodReadonly", (inst, def) => { - $ZodType.init(inst, def); - defineLazy(inst._zod, "propValues", () => def.innerType._zod.propValues); - defineLazy(inst._zod, "values", () => def.innerType._zod.values); - defineLazy(inst._zod, "optin", () => def.innerType?._zod?.optin); - defineLazy(inst._zod, "optout", () => def.innerType?._zod?.optout); - inst._zod.parse = (payload2, ctx) => { - if (ctx.direction === "backward") { - return def.innerType._zod.run(payload2, ctx); - } - const result = def.innerType._zod.run(payload2, ctx); - if (result instanceof Promise) { - return result.then(handleReadonlyResult); - } - return handleReadonlyResult(result); - }; - }); - $ZodTemplateLiteral = /* @__PURE__ */ $constructor("$ZodTemplateLiteral", (inst, def) => { - $ZodType.init(inst, def); - const regexParts = []; - for (const part of def.parts) { - if (typeof part === "object" && part !== null) { - if (!part._zod.pattern) { - throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`); - } - const source = part._zod.pattern instanceof RegExp ? part._zod.pattern.source : part._zod.pattern; - if (!source) - throw new Error(`Invalid template literal part: ${part._zod.traits}`); - const start = source.startsWith("^") ? 1 : 0; - const end = source.endsWith("$") ? source.length - 1 : source.length; - regexParts.push(source.slice(start, end)); - } else if (part === null || primitiveTypes.has(typeof part)) { - regexParts.push(escapeRegex(`${part}`)); - } else { - throw new Error(`Invalid template literal part: ${part}`); - } - } - inst._zod.pattern = new RegExp(`^${regexParts.join("")}$`); - inst._zod.parse = (payload2, _ctx) => { - if (typeof payload2.value !== "string") { - payload2.issues.push({ - input: payload2.value, - inst, - expected: "string", - code: "invalid_type" - }); - return payload2; - } - inst._zod.pattern.lastIndex = 0; - if (!inst._zod.pattern.test(payload2.value)) { - payload2.issues.push({ - input: payload2.value, - inst, - code: "invalid_format", - format: def.format ?? "template_literal", - pattern: inst._zod.pattern.source - }); - return payload2; - } - return payload2; - }; - }); - $ZodFunction = /* @__PURE__ */ $constructor("$ZodFunction", (inst, def) => { - $ZodType.init(inst, def); - inst._def = def; - inst._zod.def = def; - inst.implement = (func) => { - if (typeof func !== "function") { - throw new Error("implement() must be called with a function"); - } - return function(...args) { - const parsedArgs = inst._def.input ? parse2(inst._def.input, args) : args; - const result = Reflect.apply(func, this, parsedArgs); - if (inst._def.output) { - return parse2(inst._def.output, result); - } - return result; - }; - }; - inst.implementAsync = (func) => { - if (typeof func !== "function") { - throw new Error("implementAsync() must be called with a function"); - } - return async function(...args) { - const parsedArgs = inst._def.input ? await parseAsync(inst._def.input, args) : args; - const result = await Reflect.apply(func, this, parsedArgs); - if (inst._def.output) { - return await parseAsync(inst._def.output, result); - } - return result; - }; - }; - inst._zod.parse = (payload2, _ctx) => { - if (typeof payload2.value !== "function") { - payload2.issues.push({ - code: "invalid_type", - expected: "function", - input: payload2.value, - inst - }); - return payload2; - } - const hasPromiseOutput = inst._def.output && inst._def.output._zod.def.type === "promise"; - if (hasPromiseOutput) { - payload2.value = inst.implementAsync(payload2.value); - } else { - payload2.value = inst.implement(payload2.value); - } - return payload2; - }; - inst.input = (...args) => { - const F2 = inst.constructor; - if (Array.isArray(args[0])) { - return new F2({ - type: "function", - input: new $ZodTuple({ - type: "tuple", - items: args[0], - rest: args[1] - }), - output: inst._def.output - }); - } - return new F2({ - type: "function", - input: args[0], - output: inst._def.output - }); - }; - inst.output = (output) => { - const F2 = inst.constructor; - return new F2({ - type: "function", - input: inst._def.input, - output - }); - }; - return inst; - }); - $ZodPromise = /* @__PURE__ */ $constructor("$ZodPromise", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload2, ctx) => { - return Promise.resolve(payload2.value).then((inner) => def.innerType._zod.run({ value: inner, issues: [] }, ctx)); - }; - }); - $ZodLazy = /* @__PURE__ */ $constructor("$ZodLazy", (inst, def) => { - $ZodType.init(inst, def); - defineLazy(inst._zod, "innerType", () => def.getter()); - defineLazy(inst._zod, "pattern", () => inst._zod.innerType?._zod?.pattern); - defineLazy(inst._zod, "propValues", () => inst._zod.innerType?._zod?.propValues); - defineLazy(inst._zod, "optin", () => inst._zod.innerType?._zod?.optin ?? void 0); - defineLazy(inst._zod, "optout", () => inst._zod.innerType?._zod?.optout ?? void 0); - inst._zod.parse = (payload2, ctx) => { - const inner = inst._zod.innerType; - return inner._zod.run(payload2, ctx); - }; - }); - $ZodCustom = /* @__PURE__ */ $constructor("$ZodCustom", (inst, def) => { - $ZodCheck.init(inst, def); - $ZodType.init(inst, def); - inst._zod.parse = (payload2, _) => { - return payload2; - }; - inst._zod.check = (payload2) => { - const input = payload2.value; - const r5 = def.fn(input); - if (r5 instanceof Promise) { - return r5.then((r6) => handleRefineResult(r6, payload2, input, inst)); - } - handleRefineResult(r5, payload2, input, inst); - return; - }; - }); - } -}); - -// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ar.js -function ar_default() { - return { - localeError: error2() - }; -} -var error2; -var init_ar = __esm({ - "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ar.js"() { - init_util(); - error2 = () => { - const Sizable = { - string: { unit: "\u062D\u0631\u0641", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, - file: { unit: "\u0628\u0627\u064A\u062A", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, - array: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, - set: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "\u0645\u062F\u062E\u0644", - email: "\u0628\u0631\u064A\u062F \u0625\u0644\u0643\u062A\u0631\u0648\u0646\u064A", - url: "\u0631\u0627\u0628\u0637", - emoji: "\u0625\u064A\u0645\u0648\u062C\u064A", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "\u062A\u0627\u0631\u064A\u062E \u0648\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO", - date: "\u062A\u0627\u0631\u064A\u062E \u0628\u0645\u0639\u064A\u0627\u0631 ISO", - time: "\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO", - duration: "\u0645\u062F\u0629 \u0628\u0645\u0639\u064A\u0627\u0631 ISO", - ipv4: "\u0639\u0646\u0648\u0627\u0646 IPv4", - ipv6: "\u0639\u0646\u0648\u0627\u0646 IPv6", - cidrv4: "\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv4", - cidrv6: "\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv6", - base64: "\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64-encoded", - base64url: "\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64url-encoded", - json_string: "\u0646\u064E\u0635 \u0639\u0644\u0649 \u0647\u064A\u0626\u0629 JSON", - e164: "\u0631\u0642\u0645 \u0647\u0627\u062A\u0641 \u0628\u0645\u0639\u064A\u0627\u0631 E.164", - jwt: "JWT", - template_literal: "\u0645\u062F\u062E\u0644" - }; - const TypeDictionary = { - nan: "NaN" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 instanceof ${issue2.expected}\u060C \u0648\u0644\u0643\u0646 \u062A\u0645 \u0625\u062F\u062E\u0627\u0644 ${received}`; - } - return `\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${expected}\u060C \u0648\u0644\u0643\u0646 \u062A\u0645 \u0625\u062F\u062E\u0627\u0644 ${received}`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${stringifyPrimitive(issue2.values[0])}`; - return `\u0627\u062E\u062A\u064A\u0627\u0631 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062A\u0648\u0642\u0639 \u0627\u0646\u062A\u0642\u0627\u0621 \u0623\u062D\u062F \u0647\u0630\u0647 \u0627\u0644\u062E\u064A\u0627\u0631\u0627\u062A: ${joinValues(issue2.values, "|")}`; - case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; - const sizing = getSizing(issue2.origin); - if (sizing) - return ` \u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${issue2.origin ?? "\u0627\u0644\u0642\u064A\u0645\u0629"} ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "\u0639\u0646\u0635\u0631"}`; - return `\u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${issue2.origin ?? "\u0627\u0644\u0642\u064A\u0645\u0629"} ${adj} ${issue2.maximum.toString()}`; - } - case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${issue2.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${adj} ${issue2.minimum.toString()} ${sizing.unit}`; - } - return `\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${issue2.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${adj} ${issue2.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") - return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0628\u062F\u0623 \u0628\u0640 "${issue2.prefix}"`; - if (_issue.format === "ends_with") - return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0646\u062A\u0647\u064A \u0628\u0640 "${_issue.suffix}"`; - if (_issue.format === "includes") - return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u062A\u0636\u0645\u0651\u064E\u0646 "${_issue.includes}"`; - if (_issue.format === "regex") - return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0637\u0627\u0628\u0642 \u0627\u0644\u0646\u0645\u0637 ${_issue.pattern}`; - return `${FormatDictionary[_issue.format] ?? issue2.format} \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644`; - } - case "not_multiple_of": - return `\u0631\u0642\u0645 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0643\u0648\u0646 \u0645\u0646 \u0645\u0636\u0627\u0639\u0641\u0627\u062A ${issue2.divisor}`; - case "unrecognized_keys": - return `\u0645\u0639\u0631\u0641${issue2.keys.length > 1 ? "\u0627\u062A" : ""} \u063A\u0631\u064A\u0628${issue2.keys.length > 1 ? "\u0629" : ""}: ${joinValues(issue2.keys, "\u060C ")}`; - case "invalid_key": - return `\u0645\u0639\u0631\u0641 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${issue2.origin}`; - case "invalid_union": - return "\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644"; - case "invalid_element": - return `\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${issue2.origin}`; - default: - return "\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644"; - } - }; - }; - } -}); - -// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/az.js -function az_default() { - return { - localeError: error3() - }; -} -var error3; -var init_az = __esm({ - "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/az.js"() { - init_util(); - error3 = () => { - const Sizable = { - string: { unit: "simvol", verb: "olmal\u0131d\u0131r" }, - file: { unit: "bayt", verb: "olmal\u0131d\u0131r" }, - array: { unit: "element", verb: "olmal\u0131d\u0131r" }, - set: { unit: "element", verb: "olmal\u0131d\u0131r" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "input", - email: "email address", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO datetime", - date: "ISO date", - time: "ISO time", - duration: "ISO duration", - ipv4: "IPv4 address", - ipv6: "IPv6 address", - cidrv4: "IPv4 range", - cidrv6: "IPv6 range", - base64: "base64-encoded string", - base64url: "base64url-encoded string", - json_string: "JSON string", - e164: "E.164 number", - jwt: "JWT", - template_literal: "input" - }; - const TypeDictionary = { - nan: "NaN" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n instanceof ${issue2.expected}, daxil olan ${received}`; - } - return `Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${expected}, daxil olan ${received}`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${stringifyPrimitive(issue2.values[0])}`; - return `Yanl\u0131\u015F se\xE7im: a\u015Fa\u011F\u0131dak\u0131lardan biri olmal\u0131d\u0131r: ${joinValues(issue2.values, "|")}`; - case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; - const sizing = getSizing(issue2.origin); - if (sizing) - return `\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${issue2.origin ?? "d\u0259y\u0259r"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "element"}`; - return `\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${issue2.origin ?? "d\u0259y\u0259r"} ${adj}${issue2.maximum.toString()}`; - } - case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; - const sizing = getSizing(issue2.origin); - if (sizing) - return `\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; - return `\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${issue2.origin} ${adj}${issue2.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") - return `Yanl\u0131\u015F m\u0259tn: "${_issue.prefix}" il\u0259 ba\u015Flamal\u0131d\u0131r`; - if (_issue.format === "ends_with") - return `Yanl\u0131\u015F m\u0259tn: "${_issue.suffix}" il\u0259 bitm\u0259lidir`; - if (_issue.format === "includes") - return `Yanl\u0131\u015F m\u0259tn: "${_issue.includes}" daxil olmal\u0131d\u0131r`; - if (_issue.format === "regex") - return `Yanl\u0131\u015F m\u0259tn: ${_issue.pattern} \u015Fablonuna uy\u011Fun olmal\u0131d\u0131r`; - return `Yanl\u0131\u015F ${FormatDictionary[_issue.format] ?? issue2.format}`; - } - case "not_multiple_of": - return `Yanl\u0131\u015F \u0259d\u0259d: ${issue2.divisor} il\u0259 b\xF6l\xFCn\u0259 bil\u0259n olmal\u0131d\u0131r`; - case "unrecognized_keys": - return `Tan\u0131nmayan a\xE7ar${issue2.keys.length > 1 ? "lar" : ""}: ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return `${issue2.origin} daxilind\u0259 yanl\u0131\u015F a\xE7ar`; - case "invalid_union": - return "Yanl\u0131\u015F d\u0259y\u0259r"; - case "invalid_element": - return `${issue2.origin} daxilind\u0259 yanl\u0131\u015F d\u0259y\u0259r`; - default: - return `Yanl\u0131\u015F d\u0259y\u0259r`; - } - }; - }; - } -}); - -// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/be.js -function getBelarusianPlural(count2, one, few, many) { - const absCount = Math.abs(count2); - const lastDigit = absCount % 10; - const lastTwoDigits = absCount % 100; - if (lastTwoDigits >= 11 && lastTwoDigits <= 19) { - return many; - } - if (lastDigit === 1) { - return one; - } - if (lastDigit >= 2 && lastDigit <= 4) { - return few; - } - return many; -} -function be_default() { - return { - localeError: error4() - }; -} -var error4; -var init_be = __esm({ - "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/be.js"() { - init_util(); - error4 = () => { - const Sizable = { - string: { - unit: { - one: "\u0441\u0456\u043C\u0432\u0430\u043B", - few: "\u0441\u0456\u043C\u0432\u0430\u043B\u044B", - many: "\u0441\u0456\u043C\u0432\u0430\u043B\u0430\u045E" - }, - verb: "\u043C\u0435\u0446\u044C" - }, - array: { - unit: { - one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442", - few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B", - many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E" - }, - verb: "\u043C\u0435\u0446\u044C" - }, - set: { - unit: { - one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442", - few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B", - many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E" - }, - verb: "\u043C\u0435\u0446\u044C" - }, - file: { - unit: { - one: "\u0431\u0430\u0439\u0442", - few: "\u0431\u0430\u0439\u0442\u044B", - many: "\u0431\u0430\u0439\u0442\u0430\u045E" - }, - verb: "\u043C\u0435\u0446\u044C" - } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "\u0443\u0432\u043E\u0434", - email: "email \u0430\u0434\u0440\u0430\u0441", - url: "URL", - emoji: "\u044D\u043C\u043E\u0434\u0437\u0456", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO \u0434\u0430\u0442\u0430 \u0456 \u0447\u0430\u0441", - date: "ISO \u0434\u0430\u0442\u0430", - time: "ISO \u0447\u0430\u0441", - duration: "ISO \u043F\u0440\u0430\u0446\u044F\u0433\u043B\u0430\u0441\u0446\u044C", - ipv4: "IPv4 \u0430\u0434\u0440\u0430\u0441", - ipv6: "IPv6 \u0430\u0434\u0440\u0430\u0441", - cidrv4: "IPv4 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D", - cidrv6: "IPv6 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D", - base64: "\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64", - base64url: "\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64url", - json_string: "JSON \u0440\u0430\u0434\u043E\u043A", - e164: "\u043D\u0443\u043C\u0430\u0440 E.164", - jwt: "JWT", - template_literal: "\u0443\u0432\u043E\u0434" - }; - const TypeDictionary = { - nan: "NaN", - number: "\u043B\u0456\u043A", - array: "\u043C\u0430\u0441\u0456\u045E" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u045E\u0441\u044F instanceof ${issue2.expected}, \u0430\u0442\u0440\u044B\u043C\u0430\u043D\u0430 ${received}`; - } - return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u045E\u0441\u044F ${expected}, \u0430\u0442\u0440\u044B\u043C\u0430\u043D\u0430 ${received}`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F ${stringifyPrimitive(issue2.values[0])}`; - return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0432\u0430\u0440\u044B\u044F\u043D\u0442: \u0447\u0430\u043A\u0430\u045E\u0441\u044F \u0430\u0434\u0437\u0456\u043D \u0437 ${joinValues(issue2.values, "|")}`; - case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; - const sizing = getSizing(issue2.origin); - if (sizing) { - const maxValue = Number(issue2.maximum); - const unit = getBelarusianPlural(maxValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); - return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${sizing.verb} ${adj}${issue2.maximum.toString()} ${unit}`; - } - return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${adj}${issue2.maximum.toString()}`; - } - case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; - const sizing = getSizing(issue2.origin); - if (sizing) { - const minValue = Number(issue2.minimum); - const unit = getBelarusianPlural(minValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); - return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue2.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${sizing.verb} ${adj}${issue2.minimum.toString()} ${unit}`; - } - return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue2.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${adj}${issue2.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") - return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u043F\u0430\u0447\u044B\u043D\u0430\u0446\u0446\u0430 \u0437 "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u0430\u043A\u0430\u043D\u0447\u0432\u0430\u0446\u0446\u0430 \u043D\u0430 "${_issue.suffix}"`; - if (_issue.format === "includes") - return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u043C\u044F\u0448\u0447\u0430\u0446\u044C "${_issue.includes}"`; - if (_issue.format === "regex") - return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0430\u0434\u043F\u0430\u0432\u044F\u0434\u0430\u0446\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${_issue.pattern}`; - return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B ${FormatDictionary[_issue.format] ?? issue2.format}`; - } - case "not_multiple_of": - return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043B\u0456\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0431\u044B\u0446\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${issue2.divisor}`; - case "unrecognized_keys": - return `\u041D\u0435\u0440\u0430\u0441\u043F\u0430\u0437\u043D\u0430\u043D\u044B ${issue2.keys.length > 1 ? "\u043A\u043B\u044E\u0447\u044B" : "\u043A\u043B\u044E\u0447"}: ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043A\u043B\u044E\u0447 \u0443 ${issue2.origin}`; - case "invalid_union": - return "\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434"; - case "invalid_element": - return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u0430\u0435 \u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435 \u045E ${issue2.origin}`; - default: - return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434`; - } - }; - }; - } -}); - -// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/bg.js -function bg_default() { - return { - localeError: error5() - }; -} -var error5; -var init_bg = __esm({ - "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/bg.js"() { - init_util(); - error5 = () => { - const Sizable = { - string: { unit: "\u0441\u0438\u043C\u0432\u043E\u043B\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" }, - file: { unit: "\u0431\u0430\u0439\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" }, - array: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" }, - set: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "\u0432\u0445\u043E\u0434", - email: "\u0438\u043C\u0435\u0439\u043B \u0430\u0434\u0440\u0435\u0441", - url: "URL", - emoji: "\u0435\u043C\u043E\u0434\u0436\u0438", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO \u0432\u0440\u0435\u043C\u0435", - date: "ISO \u0434\u0430\u0442\u0430", - time: "ISO \u0432\u0440\u0435\u043C\u0435", - duration: "ISO \u043F\u0440\u043E\u0434\u044A\u043B\u0436\u0438\u0442\u0435\u043B\u043D\u043E\u0441\u0442", - ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441", - ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441", - cidrv4: "IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", - cidrv6: "IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", - base64: "base64-\u043A\u043E\u0434\u0438\u0440\u0430\u043D \u043D\u0438\u0437", - base64url: "base64url-\u043A\u043E\u0434\u0438\u0440\u0430\u043D \u043D\u0438\u0437", - json_string: "JSON \u043D\u0438\u0437", - e164: "E.164 \u043D\u043E\u043C\u0435\u0440", - jwt: "JWT", - template_literal: "\u0432\u0445\u043E\u0434" - }; - const TypeDictionary = { - nan: "NaN", - number: "\u0447\u0438\u0441\u043B\u043E", - array: "\u043C\u0430\u0441\u0438\u0432" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D instanceof ${issue2.expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D ${received}`; - } - return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D ${expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D ${received}`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D ${stringifyPrimitive(issue2.values[0])}`; - return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430 \u043E\u043F\u0446\u0438\u044F: \u043E\u0447\u0430\u043A\u0432\u0430\u043D\u043E \u0435\u0434\u043D\u043E \u043E\u0442 ${joinValues(issue2.values, "|")}`; - case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; - const sizing = getSizing(issue2.origin); - if (sizing) - return `\u0422\u0432\u044A\u0440\u0434\u0435 \u0433\u043E\u043B\u044F\u043C\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${issue2.origin ?? "\u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442"} \u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430"}`; - return `\u0422\u0432\u044A\u0440\u0434\u0435 \u0433\u043E\u043B\u044F\u043C\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${issue2.origin ?? "\u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442"} \u0434\u0430 \u0431\u044A\u0434\u0435 ${adj}${issue2.maximum.toString()}`; - } - case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `\u0422\u0432\u044A\u0440\u0434\u0435 \u043C\u0430\u043B\u043A\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${issue2.origin} \u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430 ${adj}${issue2.minimum.toString()} ${sizing.unit}`; - } - return `\u0422\u0432\u044A\u0440\u0434\u0435 \u043C\u0430\u043B\u043A\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${issue2.origin} \u0434\u0430 \u0431\u044A\u0434\u0435 ${adj}${issue2.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") { - return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0437\u0430\u043F\u043E\u0447\u0432\u0430 \u0441 "${_issue.prefix}"`; - } - if (_issue.format === "ends_with") - return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0437\u0430\u0432\u044A\u0440\u0448\u0432\u0430 \u0441 "${_issue.suffix}"`; - if (_issue.format === "includes") - return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0432\u043A\u043B\u044E\u0447\u0432\u0430 "${_issue.includes}"`; - if (_issue.format === "regex") - return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0441\u044A\u0432\u043F\u0430\u0434\u0430 \u0441 ${_issue.pattern}`; - let invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D"; - if (_issue.format === "emoji") - invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E"; - if (_issue.format === "datetime") - invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E"; - if (_issue.format === "date") - invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430"; - if (_issue.format === "time") - invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E"; - if (_issue.format === "duration") - invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430"; - return `${invalid_adj} ${FormatDictionary[_issue.format] ?? issue2.format}`; - } - case "not_multiple_of": - return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E \u0447\u0438\u0441\u043B\u043E: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0431\u044A\u0434\u0435 \u043A\u0440\u0430\u0442\u043D\u043E \u043D\u0430 ${issue2.divisor}`; - case "unrecognized_keys": - return `\u041D\u0435\u0440\u0430\u0437\u043F\u043E\u0437\u043D\u0430\u0442${issue2.keys.length > 1 ? "\u0438" : ""} \u043A\u043B\u044E\u0447${issue2.keys.length > 1 ? "\u043E\u0432\u0435" : ""}: ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043A\u043B\u044E\u0447 \u0432 ${issue2.origin}`; - case "invalid_union": - return "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434"; - case "invalid_element": - return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430 \u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442 \u0432 ${issue2.origin}`; - default: - return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434`; - } - }; - }; - } -}); - -// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ca.js -function ca_default() { - return { - localeError: error6() - }; -} -var error6; -var init_ca = __esm({ - "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ca.js"() { - init_util(); - error6 = () => { - const Sizable = { - string: { unit: "car\xE0cters", verb: "contenir" }, - file: { unit: "bytes", verb: "contenir" }, - array: { unit: "elements", verb: "contenir" }, - set: { unit: "elements", verb: "contenir" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "entrada", - email: "adre\xE7a electr\xF2nica", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "data i hora ISO", - date: "data ISO", - time: "hora ISO", - duration: "durada ISO", - ipv4: "adre\xE7a IPv4", - ipv6: "adre\xE7a IPv6", - cidrv4: "rang IPv4", - cidrv6: "rang IPv6", - base64: "cadena codificada en base64", - base64url: "cadena codificada en base64url", - json_string: "cadena JSON", - e164: "n\xFAmero E.164", - jwt: "JWT", - template_literal: "entrada" - }; - const TypeDictionary = { - nan: "NaN" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `Tipus inv\xE0lid: s'esperava instanceof ${issue2.expected}, s'ha rebut ${received}`; - } - return `Tipus inv\xE0lid: s'esperava ${expected}, s'ha rebut ${received}`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `Valor inv\xE0lid: s'esperava ${stringifyPrimitive(issue2.values[0])}`; - return `Opci\xF3 inv\xE0lida: s'esperava una de ${joinValues(issue2.values, " o ")}`; - case "too_big": { - const adj = issue2.inclusive ? "com a m\xE0xim" : "menys de"; - const sizing = getSizing(issue2.origin); - if (sizing) - return `Massa gran: s'esperava que ${issue2.origin ?? "el valor"} contingu\xE9s ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "elements"}`; - return `Massa gran: s'esperava que ${issue2.origin ?? "el valor"} fos ${adj} ${issue2.maximum.toString()}`; - } - case "too_small": { - const adj = issue2.inclusive ? "com a m\xEDnim" : "m\xE9s de"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `Massa petit: s'esperava que ${issue2.origin} contingu\xE9s ${adj} ${issue2.minimum.toString()} ${sizing.unit}`; - } - return `Massa petit: s'esperava que ${issue2.origin} fos ${adj} ${issue2.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") { - return `Format inv\xE0lid: ha de comen\xE7ar amb "${_issue.prefix}"`; - } - if (_issue.format === "ends_with") - return `Format inv\xE0lid: ha d'acabar amb "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Format inv\xE0lid: ha d'incloure "${_issue.includes}"`; - if (_issue.format === "regex") - return `Format inv\xE0lid: ha de coincidir amb el patr\xF3 ${_issue.pattern}`; - return `Format inv\xE0lid per a ${FormatDictionary[_issue.format] ?? issue2.format}`; - } - case "not_multiple_of": - return `N\xFAmero inv\xE0lid: ha de ser m\xFAltiple de ${issue2.divisor}`; - case "unrecognized_keys": - return `Clau${issue2.keys.length > 1 ? "s" : ""} no reconeguda${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return `Clau inv\xE0lida a ${issue2.origin}`; - case "invalid_union": - return "Entrada inv\xE0lida"; - // Could also be "Tipus d'unió invàlid" but "Entrada invàlida" is more general - case "invalid_element": - return `Element inv\xE0lid a ${issue2.origin}`; - default: - return `Entrada inv\xE0lida`; - } - }; - }; - } -}); - -// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/cs.js -function cs_default() { - return { - localeError: error7() - }; -} -var error7; -var init_cs = __esm({ - "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/cs.js"() { - init_util(); - error7 = () => { - const Sizable = { - string: { unit: "znak\u016F", verb: "m\xEDt" }, - file: { unit: "bajt\u016F", verb: "m\xEDt" }, - array: { unit: "prvk\u016F", verb: "m\xEDt" }, - set: { unit: "prvk\u016F", verb: "m\xEDt" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "regul\xE1rn\xED v\xFDraz", - email: "e-mailov\xE1 adresa", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "datum a \u010Das ve form\xE1tu ISO", - date: "datum ve form\xE1tu ISO", - time: "\u010Das ve form\xE1tu ISO", - duration: "doba trv\xE1n\xED ISO", - ipv4: "IPv4 adresa", - ipv6: "IPv6 adresa", - cidrv4: "rozsah IPv4", - cidrv6: "rozsah IPv6", - base64: "\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64", - base64url: "\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64url", - json_string: "\u0159et\u011Bzec ve form\xE1tu JSON", - e164: "\u010D\xEDslo E.164", - jwt: "JWT", - template_literal: "vstup" - }; - const TypeDictionary = { - nan: "NaN", - number: "\u010D\xEDslo", - string: "\u0159et\u011Bzec", - function: "funkce", - array: "pole" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no instanceof ${issue2.expected}, obdr\u017Eeno ${received}`; - } - return `Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${expected}, obdr\u017Eeno ${received}`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${stringifyPrimitive(issue2.values[0])}`; - return `Neplatn\xE1 mo\u017Enost: o\u010Dek\xE1v\xE1na jedna z hodnot ${joinValues(issue2.values, "|")}`; - case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${issue2.origin ?? "hodnota"} mus\xED m\xEDt ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "prvk\u016F"}`; - } - return `Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${issue2.origin ?? "hodnota"} mus\xED b\xFDt ${adj}${issue2.maximum.toString()}`; - } - case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${issue2.origin ?? "hodnota"} mus\xED m\xEDt ${adj}${issue2.minimum.toString()} ${sizing.unit ?? "prvk\u016F"}`; - } - return `Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${issue2.origin ?? "hodnota"} mus\xED b\xFDt ${adj}${issue2.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") - return `Neplatn\xFD \u0159et\u011Bzec: mus\xED za\u010D\xEDnat na "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `Neplatn\xFD \u0159et\u011Bzec: mus\xED kon\u010Dit na "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Neplatn\xFD \u0159et\u011Bzec: mus\xED obsahovat "${_issue.includes}"`; - if (_issue.format === "regex") - return `Neplatn\xFD \u0159et\u011Bzec: mus\xED odpov\xEDdat vzoru ${_issue.pattern}`; - return `Neplatn\xFD form\xE1t ${FormatDictionary[_issue.format] ?? issue2.format}`; - } - case "not_multiple_of": - return `Neplatn\xE9 \u010D\xEDslo: mus\xED b\xFDt n\xE1sobkem ${issue2.divisor}`; - case "unrecognized_keys": - return `Nezn\xE1m\xE9 kl\xED\u010De: ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return `Neplatn\xFD kl\xED\u010D v ${issue2.origin}`; - case "invalid_union": - return "Neplatn\xFD vstup"; - case "invalid_element": - return `Neplatn\xE1 hodnota v ${issue2.origin}`; - default: - return `Neplatn\xFD vstup`; - } - }; - }; - } -}); - -// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/da.js -function da_default() { - return { - localeError: error8() - }; -} -var error8; -var init_da = __esm({ - "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/da.js"() { - init_util(); - error8 = () => { - const Sizable = { - string: { unit: "tegn", verb: "havde" }, - file: { unit: "bytes", verb: "havde" }, - array: { unit: "elementer", verb: "indeholdt" }, - set: { unit: "elementer", verb: "indeholdt" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "input", - email: "e-mailadresse", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO dato- og klokkesl\xE6t", - date: "ISO-dato", - time: "ISO-klokkesl\xE6t", - duration: "ISO-varighed", - ipv4: "IPv4-omr\xE5de", - ipv6: "IPv6-omr\xE5de", - cidrv4: "IPv4-spektrum", - cidrv6: "IPv6-spektrum", - base64: "base64-kodet streng", - base64url: "base64url-kodet streng", - json_string: "JSON-streng", - e164: "E.164-nummer", - jwt: "JWT", - template_literal: "input" - }; - const TypeDictionary = { - nan: "NaN", - string: "streng", - number: "tal", - boolean: "boolean", - array: "liste", - object: "objekt", - set: "s\xE6t", - file: "fil" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `Ugyldigt input: forventede instanceof ${issue2.expected}, fik ${received}`; - } - return `Ugyldigt input: forventede ${expected}, fik ${received}`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `Ugyldig v\xE6rdi: forventede ${stringifyPrimitive(issue2.values[0])}`; - return `Ugyldigt valg: forventede en af f\xF8lgende ${joinValues(issue2.values, "|")}`; - case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; - const sizing = getSizing(issue2.origin); - const origin = TypeDictionary[issue2.origin] ?? issue2.origin; - if (sizing) - return `For stor: forventede ${origin ?? "value"} ${sizing.verb} ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "elementer"}`; - return `For stor: forventede ${origin ?? "value"} havde ${adj} ${issue2.maximum.toString()}`; - } - case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; - const sizing = getSizing(issue2.origin); - const origin = TypeDictionary[issue2.origin] ?? issue2.origin; - if (sizing) { - return `For lille: forventede ${origin} ${sizing.verb} ${adj} ${issue2.minimum.toString()} ${sizing.unit}`; - } - return `For lille: forventede ${origin} havde ${adj} ${issue2.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") - return `Ugyldig streng: skal starte med "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `Ugyldig streng: skal ende med "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Ugyldig streng: skal indeholde "${_issue.includes}"`; - if (_issue.format === "regex") - return `Ugyldig streng: skal matche m\xF8nsteret ${_issue.pattern}`; - return `Ugyldig ${FormatDictionary[_issue.format] ?? issue2.format}`; - } - case "not_multiple_of": - return `Ugyldigt tal: skal v\xE6re deleligt med ${issue2.divisor}`; - case "unrecognized_keys": - return `${issue2.keys.length > 1 ? "Ukendte n\xF8gler" : "Ukendt n\xF8gle"}: ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return `Ugyldig n\xF8gle i ${issue2.origin}`; - case "invalid_union": - return "Ugyldigt input: matcher ingen af de tilladte typer"; - case "invalid_element": - return `Ugyldig v\xE6rdi i ${issue2.origin}`; - default: - return `Ugyldigt input`; - } - }; - }; - } -}); - -// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/de.js -function de_default() { - return { - localeError: error9() - }; -} -var error9; -var init_de = __esm({ - "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/de.js"() { - init_util(); - error9 = () => { - const Sizable = { - string: { unit: "Zeichen", verb: "zu haben" }, - file: { unit: "Bytes", verb: "zu haben" }, - array: { unit: "Elemente", verb: "zu haben" }, - set: { unit: "Elemente", verb: "zu haben" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "Eingabe", - email: "E-Mail-Adresse", - url: "URL", - emoji: "Emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO-Datum und -Uhrzeit", - date: "ISO-Datum", - time: "ISO-Uhrzeit", - duration: "ISO-Dauer", - ipv4: "IPv4-Adresse", - ipv6: "IPv6-Adresse", - cidrv4: "IPv4-Bereich", - cidrv6: "IPv6-Bereich", - base64: "Base64-codierter String", - base64url: "Base64-URL-codierter String", - json_string: "JSON-String", - e164: "E.164-Nummer", - jwt: "JWT", - template_literal: "Eingabe" - }; - const TypeDictionary = { - nan: "NaN", - number: "Zahl", - array: "Array" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `Ung\xFCltige Eingabe: erwartet instanceof ${issue2.expected}, erhalten ${received}`; - } - return `Ung\xFCltige Eingabe: erwartet ${expected}, erhalten ${received}`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `Ung\xFCltige Eingabe: erwartet ${stringifyPrimitive(issue2.values[0])}`; - return `Ung\xFCltige Option: erwartet eine von ${joinValues(issue2.values, "|")}`; - case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; - const sizing = getSizing(issue2.origin); - if (sizing) - return `Zu gro\xDF: erwartet, dass ${issue2.origin ?? "Wert"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "Elemente"} hat`; - return `Zu gro\xDF: erwartet, dass ${issue2.origin ?? "Wert"} ${adj}${issue2.maximum.toString()} ist`; - } - case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `Zu klein: erwartet, dass ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} hat`; - } - return `Zu klein: erwartet, dass ${issue2.origin} ${adj}${issue2.minimum.toString()} ist`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") - return `Ung\xFCltiger String: muss mit "${_issue.prefix}" beginnen`; - if (_issue.format === "ends_with") - return `Ung\xFCltiger String: muss mit "${_issue.suffix}" enden`; - if (_issue.format === "includes") - return `Ung\xFCltiger String: muss "${_issue.includes}" enthalten`; - if (_issue.format === "regex") - return `Ung\xFCltiger String: muss dem Muster ${_issue.pattern} entsprechen`; - return `Ung\xFCltig: ${FormatDictionary[_issue.format] ?? issue2.format}`; - } - case "not_multiple_of": - return `Ung\xFCltige Zahl: muss ein Vielfaches von ${issue2.divisor} sein`; - case "unrecognized_keys": - return `${issue2.keys.length > 1 ? "Unbekannte Schl\xFCssel" : "Unbekannter Schl\xFCssel"}: ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return `Ung\xFCltiger Schl\xFCssel in ${issue2.origin}`; - case "invalid_union": - return "Ung\xFCltige Eingabe"; - case "invalid_element": - return `Ung\xFCltiger Wert in ${issue2.origin}`; - default: - return `Ung\xFCltige Eingabe`; - } - }; - }; - } -}); - -// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/en.js -function en_default2() { - return { - localeError: error10() - }; -} -var error10; -var init_en = __esm({ - "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/en.js"() { - init_util(); - error10 = () => { - const Sizable = { - string: { unit: "characters", verb: "to have" }, - file: { unit: "bytes", verb: "to have" }, - array: { unit: "items", verb: "to have" }, - set: { unit: "items", verb: "to have" }, - map: { unit: "entries", verb: "to have" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "input", - email: "email address", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO datetime", - date: "ISO date", - time: "ISO time", - duration: "ISO duration", - ipv4: "IPv4 address", - ipv6: "IPv6 address", - mac: "MAC address", - cidrv4: "IPv4 range", - cidrv6: "IPv6 range", - base64: "base64-encoded string", - base64url: "base64url-encoded string", - json_string: "JSON string", - e164: "E.164 number", - jwt: "JWT", - template_literal: "input" - }; - const TypeDictionary = { - // Compatibility: "nan" -> "NaN" for display - nan: "NaN" - // All other type names omitted - they fall back to raw values via ?? operator - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - return `Invalid input: expected ${expected}, received ${received}`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `Invalid input: expected ${stringifyPrimitive(issue2.values[0])}`; - return `Invalid option: expected one of ${joinValues(issue2.values, "|")}`; - case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; - const sizing = getSizing(issue2.origin); - if (sizing) - return `Too big: expected ${issue2.origin ?? "value"} to have ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elements"}`; - return `Too big: expected ${issue2.origin ?? "value"} to be ${adj}${issue2.maximum.toString()}`; - } - case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `Too small: expected ${issue2.origin} to have ${adj}${issue2.minimum.toString()} ${sizing.unit}`; - } - return `Too small: expected ${issue2.origin} to be ${adj}${issue2.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") { - return `Invalid string: must start with "${_issue.prefix}"`; - } - if (_issue.format === "ends_with") - return `Invalid string: must end with "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Invalid string: must include "${_issue.includes}"`; - if (_issue.format === "regex") - return `Invalid string: must match pattern ${_issue.pattern}`; - return `Invalid ${FormatDictionary[_issue.format] ?? issue2.format}`; - } - case "not_multiple_of": - return `Invalid number: must be a multiple of ${issue2.divisor}`; - case "unrecognized_keys": - return `Unrecognized key${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return `Invalid key in ${issue2.origin}`; - case "invalid_union": - return "Invalid input"; - case "invalid_element": - return `Invalid value in ${issue2.origin}`; - default: - return `Invalid input`; - } - }; - }; - } -}); - -// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/eo.js -function eo_default() { - return { - localeError: error11() - }; -} -var error11; -var init_eo = __esm({ - "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/eo.js"() { - init_util(); - error11 = () => { - const Sizable = { - string: { unit: "karaktrojn", verb: "havi" }, - file: { unit: "bajtojn", verb: "havi" }, - array: { unit: "elementojn", verb: "havi" }, - set: { unit: "elementojn", verb: "havi" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "enigo", - email: "retadreso", - url: "URL", - emoji: "emo\u011Dio", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO-datotempo", - date: "ISO-dato", - time: "ISO-tempo", - duration: "ISO-da\u016Dro", - ipv4: "IPv4-adreso", - ipv6: "IPv6-adreso", - cidrv4: "IPv4-rango", - cidrv6: "IPv6-rango", - base64: "64-ume kodita karaktraro", - base64url: "URL-64-ume kodita karaktraro", - json_string: "JSON-karaktraro", - e164: "E.164-nombro", - jwt: "JWT", - template_literal: "enigo" - }; - const TypeDictionary = { - nan: "NaN", - number: "nombro", - array: "tabelo", - null: "senvalora" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `Nevalida enigo: atendi\u011Dis instanceof ${issue2.expected}, ricevi\u011Dis ${received}`; - } - return `Nevalida enigo: atendi\u011Dis ${expected}, ricevi\u011Dis ${received}`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `Nevalida enigo: atendi\u011Dis ${stringifyPrimitive(issue2.values[0])}`; - return `Nevalida opcio: atendi\u011Dis unu el ${joinValues(issue2.values, "|")}`; - case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; - const sizing = getSizing(issue2.origin); - if (sizing) - return `Tro granda: atendi\u011Dis ke ${issue2.origin ?? "valoro"} havu ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementojn"}`; - return `Tro granda: atendi\u011Dis ke ${issue2.origin ?? "valoro"} havu ${adj}${issue2.maximum.toString()}`; - } - case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `Tro malgranda: atendi\u011Dis ke ${issue2.origin} havu ${adj}${issue2.minimum.toString()} ${sizing.unit}`; - } - return `Tro malgranda: atendi\u011Dis ke ${issue2.origin} estu ${adj}${issue2.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") - return `Nevalida karaktraro: devas komenci\u011Di per "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `Nevalida karaktraro: devas fini\u011Di per "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Nevalida karaktraro: devas inkluzivi "${_issue.includes}"`; - if (_issue.format === "regex") - return `Nevalida karaktraro: devas kongrui kun la modelo ${_issue.pattern}`; - return `Nevalida ${FormatDictionary[_issue.format] ?? issue2.format}`; - } - case "not_multiple_of": - return `Nevalida nombro: devas esti oblo de ${issue2.divisor}`; - case "unrecognized_keys": - return `Nekonata${issue2.keys.length > 1 ? "j" : ""} \u015Dlosilo${issue2.keys.length > 1 ? "j" : ""}: ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return `Nevalida \u015Dlosilo en ${issue2.origin}`; - case "invalid_union": - return "Nevalida enigo"; - case "invalid_element": - return `Nevalida valoro en ${issue2.origin}`; - default: - return `Nevalida enigo`; - } - }; - }; - } -}); - -// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/es.js -function es_default() { - return { - localeError: error12() - }; -} -var error12; -var init_es = __esm({ - "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/es.js"() { - init_util(); - error12 = () => { - const Sizable = { - string: { unit: "caracteres", verb: "tener" }, - file: { unit: "bytes", verb: "tener" }, - array: { unit: "elementos", verb: "tener" }, - set: { unit: "elementos", verb: "tener" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "entrada", - email: "direcci\xF3n de correo electr\xF3nico", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "fecha y hora ISO", - date: "fecha ISO", - time: "hora ISO", - duration: "duraci\xF3n ISO", - ipv4: "direcci\xF3n IPv4", - ipv6: "direcci\xF3n IPv6", - cidrv4: "rango IPv4", - cidrv6: "rango IPv6", - base64: "cadena codificada en base64", - base64url: "URL codificada en base64", - json_string: "cadena JSON", - e164: "n\xFAmero E.164", - jwt: "JWT", - template_literal: "entrada" - }; - const TypeDictionary = { - nan: "NaN", - string: "texto", - number: "n\xFAmero", - boolean: "booleano", - array: "arreglo", - object: "objeto", - set: "conjunto", - file: "archivo", - date: "fecha", - bigint: "n\xFAmero grande", - symbol: "s\xEDmbolo", - undefined: "indefinido", - null: "nulo", - function: "funci\xF3n", - map: "mapa", - record: "registro", - tuple: "tupla", - enum: "enumeraci\xF3n", - union: "uni\xF3n", - literal: "literal", - promise: "promesa", - void: "vac\xEDo", - never: "nunca", - unknown: "desconocido", - any: "cualquiera" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `Entrada inv\xE1lida: se esperaba instanceof ${issue2.expected}, recibido ${received}`; - } - return `Entrada inv\xE1lida: se esperaba ${expected}, recibido ${received}`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `Entrada inv\xE1lida: se esperaba ${stringifyPrimitive(issue2.values[0])}`; - return `Opci\xF3n inv\xE1lida: se esperaba una de ${joinValues(issue2.values, "|")}`; - case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; - const sizing = getSizing(issue2.origin); - const origin = TypeDictionary[issue2.origin] ?? issue2.origin; - if (sizing) - return `Demasiado grande: se esperaba que ${origin ?? "valor"} tuviera ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementos"}`; - return `Demasiado grande: se esperaba que ${origin ?? "valor"} fuera ${adj}${issue2.maximum.toString()}`; - } - case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; - const sizing = getSizing(issue2.origin); - const origin = TypeDictionary[issue2.origin] ?? issue2.origin; - if (sizing) { - return `Demasiado peque\xF1o: se esperaba que ${origin} tuviera ${adj}${issue2.minimum.toString()} ${sizing.unit}`; - } - return `Demasiado peque\xF1o: se esperaba que ${origin} fuera ${adj}${issue2.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") - return `Cadena inv\xE1lida: debe comenzar con "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `Cadena inv\xE1lida: debe terminar en "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Cadena inv\xE1lida: debe incluir "${_issue.includes}"`; - if (_issue.format === "regex") - return `Cadena inv\xE1lida: debe coincidir con el patr\xF3n ${_issue.pattern}`; - return `Inv\xE1lido ${FormatDictionary[_issue.format] ?? issue2.format}`; - } - case "not_multiple_of": - return `N\xFAmero inv\xE1lido: debe ser m\xFAltiplo de ${issue2.divisor}`; - case "unrecognized_keys": - return `Llave${issue2.keys.length > 1 ? "s" : ""} desconocida${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return `Llave inv\xE1lida en ${TypeDictionary[issue2.origin] ?? issue2.origin}`; - case "invalid_union": - return "Entrada inv\xE1lida"; - case "invalid_element": - return `Valor inv\xE1lido en ${TypeDictionary[issue2.origin] ?? issue2.origin}`; - default: - return `Entrada inv\xE1lida`; - } - }; - }; - } -}); - -// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/fa.js -function fa_default() { - return { - localeError: error13() - }; -} -var error13; -var init_fa = __esm({ - "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/fa.js"() { - init_util(); - error13 = () => { - const Sizable = { - string: { unit: "\u06A9\u0627\u0631\u0627\u06A9\u062A\u0631", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, - file: { unit: "\u0628\u0627\u06CC\u062A", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, - array: { unit: "\u0622\u06CC\u062A\u0645", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, - set: { unit: "\u0622\u06CC\u062A\u0645", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "\u0648\u0631\u0648\u062F\u06CC", - email: "\u0622\u062F\u0631\u0633 \u0627\u06CC\u0645\u06CC\u0644", - url: "URL", - emoji: "\u0627\u06CC\u0645\u0648\u062C\u06CC", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "\u062A\u0627\u0631\u06CC\u062E \u0648 \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648", - date: "\u062A\u0627\u0631\u06CC\u062E \u0627\u06CC\u0632\u0648", - time: "\u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648", - duration: "\u0645\u062F\u062A \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648", - ipv4: "IPv4 \u0622\u062F\u0631\u0633", - ipv6: "IPv6 \u0622\u062F\u0631\u0633", - cidrv4: "IPv4 \u062F\u0627\u0645\u0646\u0647", - cidrv6: "IPv6 \u062F\u0627\u0645\u0646\u0647", - base64: "base64-encoded \u0631\u0634\u062A\u0647", - base64url: "base64url-encoded \u0631\u0634\u062A\u0647", - json_string: "JSON \u0631\u0634\u062A\u0647", - e164: "E.164 \u0639\u062F\u062F", - jwt: "JWT", - template_literal: "\u0648\u0631\u0648\u062F\u06CC" - }; - const TypeDictionary = { - nan: "NaN", - number: "\u0639\u062F\u062F", - array: "\u0622\u0631\u0627\u06CC\u0647" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A instanceof ${issue2.expected} \u0645\u06CC\u200C\u0628\u0648\u062F\u060C ${received} \u062F\u0631\u06CC\u0627\u0641\u062A \u0634\u062F`; - } - return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${expected} \u0645\u06CC\u200C\u0628\u0648\u062F\u060C ${received} \u062F\u0631\u06CC\u0627\u0641\u062A \u0634\u062F`; - } - case "invalid_value": - if (issue2.values.length === 1) { - return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${stringifyPrimitive(issue2.values[0])} \u0645\u06CC\u200C\u0628\u0648\u062F`; - } - return `\u06AF\u0632\u06CC\u0646\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A \u06CC\u06A9\u06CC \u0627\u0632 ${joinValues(issue2.values, "|")} \u0645\u06CC\u200C\u0628\u0648\u062F`; - case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${issue2.origin ?? "\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0639\u0646\u0635\u0631"} \u0628\u0627\u0634\u062F`; - } - return `\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${issue2.origin ?? "\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${adj}${issue2.maximum.toString()} \u0628\u0627\u0634\u062F`; - } - case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${issue2.origin} \u0628\u0627\u06CC\u062F ${adj}${issue2.minimum.toString()} ${sizing.unit} \u0628\u0627\u0634\u062F`; - } - return `\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${issue2.origin} \u0628\u0627\u06CC\u062F ${adj}${issue2.minimum.toString()} \u0628\u0627\u0634\u062F`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") { - return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${_issue.prefix}" \u0634\u0631\u0648\u0639 \u0634\u0648\u062F`; - } - if (_issue.format === "ends_with") { - return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${_issue.suffix}" \u062A\u0645\u0627\u0645 \u0634\u0648\u062F`; - } - if (_issue.format === "includes") { - return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0634\u0627\u0645\u0644 "${_issue.includes}" \u0628\u0627\u0634\u062F`; - } - if (_issue.format === "regex") { - return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 \u0627\u0644\u06AF\u0648\u06CC ${_issue.pattern} \u0645\u0637\u0627\u0628\u0642\u062A \u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F`; - } - return `${FormatDictionary[_issue.format] ?? issue2.format} \u0646\u0627\u0645\u0639\u062A\u0628\u0631`; - } - case "not_multiple_of": - return `\u0639\u062F\u062F \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0645\u0636\u0631\u0628 ${issue2.divisor} \u0628\u0627\u0634\u062F`; - case "unrecognized_keys": - return `\u06A9\u0644\u06CC\u062F${issue2.keys.length > 1 ? "\u0647\u0627\u06CC" : ""} \u0646\u0627\u0634\u0646\u0627\u0633: ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return `\u06A9\u0644\u06CC\u062F \u0646\u0627\u0634\u0646\u0627\u0633 \u062F\u0631 ${issue2.origin}`; - case "invalid_union": - return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631`; - case "invalid_element": - return `\u0645\u0642\u062F\u0627\u0631 \u0646\u0627\u0645\u0639\u062A\u0628\u0631 \u062F\u0631 ${issue2.origin}`; - default: - return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631`; - } - }; - }; - } -}); - -// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/fi.js -function fi_default() { - return { - localeError: error14() - }; -} -var error14; -var init_fi = __esm({ - "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/fi.js"() { - init_util(); - error14 = () => { - const Sizable = { - string: { unit: "merkki\xE4", subject: "merkkijonon" }, - file: { unit: "tavua", subject: "tiedoston" }, - array: { unit: "alkiota", subject: "listan" }, - set: { unit: "alkiota", subject: "joukon" }, - number: { unit: "", subject: "luvun" }, - bigint: { unit: "", subject: "suuren kokonaisluvun" }, - int: { unit: "", subject: "kokonaisluvun" }, - date: { unit: "", subject: "p\xE4iv\xE4m\xE4\xE4r\xE4n" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "s\xE4\xE4nn\xF6llinen lauseke", - email: "s\xE4hk\xF6postiosoite", - url: "URL-osoite", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO-aikaleima", - date: "ISO-p\xE4iv\xE4m\xE4\xE4r\xE4", - time: "ISO-aika", - duration: "ISO-kesto", - ipv4: "IPv4-osoite", - ipv6: "IPv6-osoite", - cidrv4: "IPv4-alue", - cidrv6: "IPv6-alue", - base64: "base64-koodattu merkkijono", - base64url: "base64url-koodattu merkkijono", - json_string: "JSON-merkkijono", - e164: "E.164-luku", - jwt: "JWT", - template_literal: "templaattimerkkijono" - }; - const TypeDictionary = { - nan: "NaN" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `Virheellinen tyyppi: odotettiin instanceof ${issue2.expected}, oli ${received}`; - } - return `Virheellinen tyyppi: odotettiin ${expected}, oli ${received}`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `Virheellinen sy\xF6te: t\xE4ytyy olla ${stringifyPrimitive(issue2.values[0])}`; - return `Virheellinen valinta: t\xE4ytyy olla yksi seuraavista: ${joinValues(issue2.values, "|")}`; - case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `Liian suuri: ${sizing.subject} t\xE4ytyy olla ${adj}${issue2.maximum.toString()} ${sizing.unit}`.trim(); - } - return `Liian suuri: arvon t\xE4ytyy olla ${adj}${issue2.maximum.toString()}`; - } - case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `Liian pieni: ${sizing.subject} t\xE4ytyy olla ${adj}${issue2.minimum.toString()} ${sizing.unit}`.trim(); - } - return `Liian pieni: arvon t\xE4ytyy olla ${adj}${issue2.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") - return `Virheellinen sy\xF6te: t\xE4ytyy alkaa "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `Virheellinen sy\xF6te: t\xE4ytyy loppua "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Virheellinen sy\xF6te: t\xE4ytyy sis\xE4lt\xE4\xE4 "${_issue.includes}"`; - if (_issue.format === "regex") { - return `Virheellinen sy\xF6te: t\xE4ytyy vastata s\xE4\xE4nn\xF6llist\xE4 lauseketta ${_issue.pattern}`; - } - return `Virheellinen ${FormatDictionary[_issue.format] ?? issue2.format}`; - } - case "not_multiple_of": - return `Virheellinen luku: t\xE4ytyy olla luvun ${issue2.divisor} monikerta`; - case "unrecognized_keys": - return `${issue2.keys.length > 1 ? "Tuntemattomat avaimet" : "Tuntematon avain"}: ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return "Virheellinen avain tietueessa"; - case "invalid_union": - return "Virheellinen unioni"; - case "invalid_element": - return "Virheellinen arvo joukossa"; - default: - return `Virheellinen sy\xF6te`; - } - }; - }; - } -}); - -// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/fr.js -function fr_default() { - return { - localeError: error15() - }; -} -var error15; -var init_fr = __esm({ - "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/fr.js"() { - init_util(); - error15 = () => { - const Sizable = { - string: { unit: "caract\xE8res", verb: "avoir" }, - file: { unit: "octets", verb: "avoir" }, - array: { unit: "\xE9l\xE9ments", verb: "avoir" }, - set: { unit: "\xE9l\xE9ments", verb: "avoir" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "entr\xE9e", - email: "adresse e-mail", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "date et heure ISO", - date: "date ISO", - time: "heure ISO", - duration: "dur\xE9e ISO", - ipv4: "adresse IPv4", - ipv6: "adresse IPv6", - cidrv4: "plage IPv4", - cidrv6: "plage IPv6", - base64: "cha\xEEne encod\xE9e en base64", - base64url: "cha\xEEne encod\xE9e en base64url", - json_string: "cha\xEEne JSON", - e164: "num\xE9ro E.164", - jwt: "JWT", - template_literal: "entr\xE9e" - }; - const TypeDictionary = { - nan: "NaN", - number: "nombre", - array: "tableau" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `Entr\xE9e invalide : instanceof ${issue2.expected} attendu, ${received} re\xE7u`; - } - return `Entr\xE9e invalide : ${expected} attendu, ${received} re\xE7u`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `Entr\xE9e invalide : ${stringifyPrimitive(issue2.values[0])} attendu`; - return `Option invalide : une valeur parmi ${joinValues(issue2.values, "|")} attendue`; - case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; - const sizing = getSizing(issue2.origin); - if (sizing) - return `Trop grand : ${issue2.origin ?? "valeur"} doit ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\xE9l\xE9ment(s)"}`; - return `Trop grand : ${issue2.origin ?? "valeur"} doit \xEAtre ${adj}${issue2.maximum.toString()}`; - } - case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `Trop petit : ${issue2.origin} doit ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; - } - return `Trop petit : ${issue2.origin} doit \xEAtre ${adj}${issue2.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") - return `Cha\xEEne invalide : doit commencer par "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `Cha\xEEne invalide : doit se terminer par "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Cha\xEEne invalide : doit inclure "${_issue.includes}"`; - if (_issue.format === "regex") - return `Cha\xEEne invalide : doit correspondre au mod\xE8le ${_issue.pattern}`; - return `${FormatDictionary[_issue.format] ?? issue2.format} invalide`; - } - case "not_multiple_of": - return `Nombre invalide : doit \xEAtre un multiple de ${issue2.divisor}`; - case "unrecognized_keys": - return `Cl\xE9${issue2.keys.length > 1 ? "s" : ""} non reconnue${issue2.keys.length > 1 ? "s" : ""} : ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return `Cl\xE9 invalide dans ${issue2.origin}`; - case "invalid_union": - return "Entr\xE9e invalide"; - case "invalid_element": - return `Valeur invalide dans ${issue2.origin}`; - default: - return `Entr\xE9e invalide`; - } - }; - }; - } -}); - -// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/fr-CA.js -function fr_CA_default() { - return { - localeError: error16() - }; -} -var error16; -var init_fr_CA = __esm({ - "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/fr-CA.js"() { - init_util(); - error16 = () => { - const Sizable = { - string: { unit: "caract\xE8res", verb: "avoir" }, - file: { unit: "octets", verb: "avoir" }, - array: { unit: "\xE9l\xE9ments", verb: "avoir" }, - set: { unit: "\xE9l\xE9ments", verb: "avoir" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "entr\xE9e", - email: "adresse courriel", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "date-heure ISO", - date: "date ISO", - time: "heure ISO", - duration: "dur\xE9e ISO", - ipv4: "adresse IPv4", - ipv6: "adresse IPv6", - cidrv4: "plage IPv4", - cidrv6: "plage IPv6", - base64: "cha\xEEne encod\xE9e en base64", - base64url: "cha\xEEne encod\xE9e en base64url", - json_string: "cha\xEEne JSON", - e164: "num\xE9ro E.164", - jwt: "JWT", - template_literal: "entr\xE9e" - }; - const TypeDictionary = { - nan: "NaN" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `Entr\xE9e invalide : attendu instanceof ${issue2.expected}, re\xE7u ${received}`; - } - return `Entr\xE9e invalide : attendu ${expected}, re\xE7u ${received}`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `Entr\xE9e invalide : attendu ${stringifyPrimitive(issue2.values[0])}`; - return `Option invalide : attendu l'une des valeurs suivantes ${joinValues(issue2.values, "|")}`; - case "too_big": { - const adj = issue2.inclusive ? "\u2264" : "<"; - const sizing = getSizing(issue2.origin); - if (sizing) - return `Trop grand : attendu que ${issue2.origin ?? "la valeur"} ait ${adj}${issue2.maximum.toString()} ${sizing.unit}`; - return `Trop grand : attendu que ${issue2.origin ?? "la valeur"} soit ${adj}${issue2.maximum.toString()}`; - } - case "too_small": { - const adj = issue2.inclusive ? "\u2265" : ">"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `Trop petit : attendu que ${issue2.origin} ait ${adj}${issue2.minimum.toString()} ${sizing.unit}`; - } - return `Trop petit : attendu que ${issue2.origin} soit ${adj}${issue2.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") { - return `Cha\xEEne invalide : doit commencer par "${_issue.prefix}"`; - } - if (_issue.format === "ends_with") - return `Cha\xEEne invalide : doit se terminer par "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Cha\xEEne invalide : doit inclure "${_issue.includes}"`; - if (_issue.format === "regex") - return `Cha\xEEne invalide : doit correspondre au motif ${_issue.pattern}`; - return `${FormatDictionary[_issue.format] ?? issue2.format} invalide`; - } - case "not_multiple_of": - return `Nombre invalide : doit \xEAtre un multiple de ${issue2.divisor}`; - case "unrecognized_keys": - return `Cl\xE9${issue2.keys.length > 1 ? "s" : ""} non reconnue${issue2.keys.length > 1 ? "s" : ""} : ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return `Cl\xE9 invalide dans ${issue2.origin}`; - case "invalid_union": - return "Entr\xE9e invalide"; - case "invalid_element": - return `Valeur invalide dans ${issue2.origin}`; - default: - return `Entr\xE9e invalide`; - } - }; - }; - } -}); - -// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/he.js -function he_default() { - return { - localeError: error17() - }; -} -var error17; -var init_he = __esm({ - "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/he.js"() { - init_util(); - error17 = () => { - const TypeNames = { - string: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA", gender: "f" }, - number: { label: "\u05DE\u05E1\u05E4\u05E8", gender: "m" }, - boolean: { label: "\u05E2\u05E8\u05DA \u05D1\u05D5\u05DC\u05D9\u05D0\u05E0\u05D9", gender: "m" }, - bigint: { label: "BigInt", gender: "m" }, - date: { label: "\u05EA\u05D0\u05E8\u05D9\u05DA", gender: "m" }, - array: { label: "\u05DE\u05E2\u05E8\u05DA", gender: "m" }, - object: { label: "\u05D0\u05D5\u05D1\u05D9\u05D9\u05E7\u05D8", gender: "m" }, - null: { label: "\u05E2\u05E8\u05DA \u05E8\u05D9\u05E7 (null)", gender: "m" }, - undefined: { label: "\u05E2\u05E8\u05DA \u05DC\u05D0 \u05DE\u05D5\u05D2\u05D3\u05E8 (undefined)", gender: "m" }, - symbol: { label: "\u05E1\u05D9\u05DE\u05D1\u05D5\u05DC (Symbol)", gender: "m" }, - function: { label: "\u05E4\u05D5\u05E0\u05E7\u05E6\u05D9\u05D4", gender: "f" }, - map: { label: "\u05DE\u05E4\u05D4 (Map)", gender: "f" }, - set: { label: "\u05E7\u05D1\u05D5\u05E6\u05D4 (Set)", gender: "f" }, - file: { label: "\u05E7\u05D5\u05D1\u05E5", gender: "m" }, - promise: { label: "Promise", gender: "m" }, - NaN: { label: "NaN", gender: "m" }, - unknown: { label: "\u05E2\u05E8\u05DA \u05DC\u05D0 \u05D9\u05D3\u05D5\u05E2", gender: "m" }, - value: { label: "\u05E2\u05E8\u05DA", gender: "m" } - }; - const Sizable = { - string: { unit: "\u05EA\u05D5\u05D5\u05D9\u05DD", shortLabel: "\u05E7\u05E6\u05E8", longLabel: "\u05D0\u05E8\u05D5\u05DA" }, - file: { unit: "\u05D1\u05D9\u05D9\u05D8\u05D9\u05DD", shortLabel: "\u05E7\u05D8\u05DF", longLabel: "\u05D2\u05D3\u05D5\u05DC" }, - array: { unit: "\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD", shortLabel: "\u05E7\u05D8\u05DF", longLabel: "\u05D2\u05D3\u05D5\u05DC" }, - set: { unit: "\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD", shortLabel: "\u05E7\u05D8\u05DF", longLabel: "\u05D2\u05D3\u05D5\u05DC" }, - number: { unit: "", shortLabel: "\u05E7\u05D8\u05DF", longLabel: "\u05D2\u05D3\u05D5\u05DC" } - // no unit - }; - const typeEntry = (t5) => t5 ? TypeNames[t5] : void 0; - const typeLabel = (t5) => { - const e5 = typeEntry(t5); - if (e5) - return e5.label; - return t5 ?? TypeNames.unknown.label; - }; - const withDefinite = (t5) => `\u05D4${typeLabel(t5)}`; - const verbFor = (t5) => { - const e5 = typeEntry(t5); - const gender = e5?.gender ?? "m"; - return gender === "f" ? "\u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05D9\u05D5\u05EA" : "\u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA"; - }; - const getSizing = (origin) => { - if (!origin) - return null; - return Sizable[origin] ?? null; - }; - const FormatDictionary = { - regex: { label: "\u05E7\u05DC\u05D8", gender: "m" }, - email: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA \u05D0\u05D9\u05DE\u05D9\u05D9\u05DC", gender: "f" }, - url: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA \u05E8\u05E9\u05EA", gender: "f" }, - emoji: { label: "\u05D0\u05D9\u05DE\u05D5\u05D2'\u05D9", gender: "m" }, - uuid: { label: "UUID", gender: "m" }, - nanoid: { label: "nanoid", gender: "m" }, - guid: { label: "GUID", gender: "m" }, - cuid: { label: "cuid", gender: "m" }, - cuid2: { label: "cuid2", gender: "m" }, - ulid: { label: "ULID", gender: "m" }, - xid: { label: "XID", gender: "m" }, - ksuid: { label: "KSUID", gender: "m" }, - datetime: { label: "\u05EA\u05D0\u05E8\u05D9\u05DA \u05D5\u05D6\u05DE\u05DF ISO", gender: "m" }, - date: { label: "\u05EA\u05D0\u05E8\u05D9\u05DA ISO", gender: "m" }, - time: { label: "\u05D6\u05DE\u05DF ISO", gender: "m" }, - duration: { label: "\u05DE\u05E9\u05DA \u05D6\u05DE\u05DF ISO", gender: "m" }, - ipv4: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA IPv4", gender: "f" }, - ipv6: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA IPv6", gender: "f" }, - cidrv4: { label: "\u05D8\u05D5\u05D5\u05D7 IPv4", gender: "m" }, - cidrv6: { label: "\u05D8\u05D5\u05D5\u05D7 IPv6", gender: "m" }, - base64: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64", gender: "f" }, - base64url: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64 \u05DC\u05DB\u05EA\u05D5\u05D1\u05D5\u05EA \u05E8\u05E9\u05EA", gender: "f" }, - json_string: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA JSON", gender: "f" }, - e164: { label: "\u05DE\u05E1\u05E4\u05E8 E.164", gender: "m" }, - jwt: { label: "JWT", gender: "m" }, - ends_with: { label: "\u05E7\u05DC\u05D8", gender: "m" }, - includes: { label: "\u05E7\u05DC\u05D8", gender: "m" }, - lowercase: { label: "\u05E7\u05DC\u05D8", gender: "m" }, - starts_with: { label: "\u05E7\u05DC\u05D8", gender: "m" }, - uppercase: { label: "\u05E7\u05DC\u05D8", gender: "m" } - }; - const TypeDictionary = { - nan: "NaN" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expectedKey = issue2.expected; - const expected = TypeDictionary[expectedKey ?? ""] ?? typeLabel(expectedKey); - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? TypeNames[receivedType]?.label ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA instanceof ${issue2.expected}, \u05D4\u05EA\u05E7\u05D1\u05DC ${received}`; - } - return `\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${expected}, \u05D4\u05EA\u05E7\u05D1\u05DC ${received}`; - } - case "invalid_value": { - if (issue2.values.length === 1) { - return `\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05E2\u05E8\u05DA \u05D7\u05D9\u05D9\u05D1 \u05DC\u05D4\u05D9\u05D5\u05EA ${stringifyPrimitive(issue2.values[0])}`; - } - const stringified = issue2.values.map((v5) => stringifyPrimitive(v5)); - if (issue2.values.length === 2) { - return `\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05D0\u05E4\u05E9\u05E8\u05D5\u05D9\u05D5\u05EA \u05D4\u05DE\u05EA\u05D0\u05D9\u05DE\u05D5\u05EA \u05D4\u05DF ${stringified[0]} \u05D0\u05D5 ${stringified[1]}`; - } - const lastValue = stringified[stringified.length - 1]; - const restValues = stringified.slice(0, -1).join(", "); - return `\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05D0\u05E4\u05E9\u05E8\u05D5\u05D9\u05D5\u05EA \u05D4\u05DE\u05EA\u05D0\u05D9\u05DE\u05D5\u05EA \u05D4\u05DF ${restValues} \u05D0\u05D5 ${lastValue}`; - } - case "too_big": { - const sizing = getSizing(issue2.origin); - const subject = withDefinite(issue2.origin ?? "value"); - if (issue2.origin === "string") { - return `${sizing?.longLabel ?? "\u05D0\u05E8\u05D5\u05DA"} \u05DE\u05D3\u05D9: ${subject} \u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05DB\u05D9\u05DC ${issue2.maximum.toString()} ${sizing?.unit ?? ""} ${issue2.inclusive ? "\u05D0\u05D5 \u05E4\u05D7\u05D5\u05EA" : "\u05DC\u05DB\u05DC \u05D4\u05D9\u05D5\u05EA\u05E8"}`.trim(); - } - if (issue2.origin === "number") { - const comparison = issue2.inclusive ? `\u05E7\u05D8\u05DF \u05D0\u05D5 \u05E9\u05D5\u05D5\u05D4 \u05DC-${issue2.maximum}` : `\u05E7\u05D8\u05DF \u05DE-${issue2.maximum}`; - return `\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${subject} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${comparison}`; - } - if (issue2.origin === "array" || issue2.origin === "set") { - const verb = issue2.origin === "set" ? "\u05E6\u05E8\u05D9\u05DB\u05D4" : "\u05E6\u05E8\u05D9\u05DA"; - const comparison = issue2.inclusive ? `${issue2.maximum} ${sizing?.unit ?? ""} \u05D0\u05D5 \u05E4\u05D7\u05D5\u05EA` : `\u05E4\u05D7\u05D5\u05EA \u05DE-${issue2.maximum} ${sizing?.unit ?? ""}`; - return `\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${subject} ${verb} \u05DC\u05D4\u05DB\u05D9\u05DC ${comparison}`.trim(); - } - const adj = issue2.inclusive ? "<=" : "<"; - const be = verbFor(issue2.origin ?? "value"); - if (sizing?.unit) { - return `${sizing.longLabel} \u05DE\u05D3\u05D9: ${subject} ${be} ${adj}${issue2.maximum.toString()} ${sizing.unit}`; - } - return `${sizing?.longLabel ?? "\u05D2\u05D3\u05D5\u05DC"} \u05DE\u05D3\u05D9: ${subject} ${be} ${adj}${issue2.maximum.toString()}`; - } - case "too_small": { - const sizing = getSizing(issue2.origin); - const subject = withDefinite(issue2.origin ?? "value"); - if (issue2.origin === "string") { - return `${sizing?.shortLabel ?? "\u05E7\u05E6\u05E8"} \u05DE\u05D3\u05D9: ${subject} \u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05DB\u05D9\u05DC ${issue2.minimum.toString()} ${sizing?.unit ?? ""} ${issue2.inclusive ? "\u05D0\u05D5 \u05D9\u05D5\u05EA\u05E8" : "\u05DC\u05E4\u05D7\u05D5\u05EA"}`.trim(); - } - if (issue2.origin === "number") { - const comparison = issue2.inclusive ? `\u05D2\u05D3\u05D5\u05DC \u05D0\u05D5 \u05E9\u05D5\u05D5\u05D4 \u05DC-${issue2.minimum}` : `\u05D2\u05D3\u05D5\u05DC \u05DE-${issue2.minimum}`; - return `\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${subject} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${comparison}`; - } - if (issue2.origin === "array" || issue2.origin === "set") { - const verb = issue2.origin === "set" ? "\u05E6\u05E8\u05D9\u05DB\u05D4" : "\u05E6\u05E8\u05D9\u05DA"; - if (issue2.minimum === 1 && issue2.inclusive) { - const singularPhrase = issue2.origin === "set" ? "\u05DC\u05E4\u05D7\u05D5\u05EA \u05E4\u05E8\u05D9\u05D8 \u05D0\u05D7\u05D3" : "\u05DC\u05E4\u05D7\u05D5\u05EA \u05E4\u05E8\u05D9\u05D8 \u05D0\u05D7\u05D3"; - return `\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${subject} ${verb} \u05DC\u05D4\u05DB\u05D9\u05DC ${singularPhrase}`; - } - const comparison = issue2.inclusive ? `${issue2.minimum} ${sizing?.unit ?? ""} \u05D0\u05D5 \u05D9\u05D5\u05EA\u05E8` : `\u05D9\u05D5\u05EA\u05E8 \u05DE-${issue2.minimum} ${sizing?.unit ?? ""}`; - return `\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${subject} ${verb} \u05DC\u05D4\u05DB\u05D9\u05DC ${comparison}`.trim(); - } - const adj = issue2.inclusive ? ">=" : ">"; - const be = verbFor(issue2.origin ?? "value"); - if (sizing?.unit) { - return `${sizing.shortLabel} \u05DE\u05D3\u05D9: ${subject} ${be} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; - } - return `${sizing?.shortLabel ?? "\u05E7\u05D8\u05DF"} \u05DE\u05D3\u05D9: ${subject} ${be} ${adj}${issue2.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") - return `\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D7\u05D9\u05DC \u05D1 "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05E1\u05EA\u05D9\u05D9\u05DD \u05D1 "${_issue.suffix}"`; - if (_issue.format === "includes") - return `\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05DB\u05DC\u05D5\u05DC "${_issue.includes}"`; - if (_issue.format === "regex") - return `\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D0\u05D9\u05DD \u05DC\u05EA\u05D1\u05E0\u05D9\u05EA ${_issue.pattern}`; - const nounEntry = FormatDictionary[_issue.format]; - const noun = nounEntry?.label ?? _issue.format; - const gender = nounEntry?.gender ?? "m"; - const adjective = gender === "f" ? "\u05EA\u05E7\u05D9\u05E0\u05D4" : "\u05EA\u05E7\u05D9\u05DF"; - return `${noun} \u05DC\u05D0 ${adjective}`; - } - case "not_multiple_of": - return `\u05DE\u05E1\u05E4\u05E8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D7\u05D9\u05D9\u05D1 \u05DC\u05D4\u05D9\u05D5\u05EA \u05DE\u05DB\u05E4\u05DC\u05D4 \u05E9\u05DC ${issue2.divisor}`; - case "unrecognized_keys": - return `\u05DE\u05E4\u05EA\u05D7${issue2.keys.length > 1 ? "\u05D5\u05EA" : ""} \u05DC\u05D0 \u05DE\u05D6\u05D5\u05D4${issue2.keys.length > 1 ? "\u05D9\u05DD" : "\u05D4"}: ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": { - return `\u05E9\u05D3\u05D4 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1\u05D0\u05D5\u05D1\u05D9\u05D9\u05E7\u05D8`; - } - case "invalid_union": - return "\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF"; - case "invalid_element": { - const place = withDefinite(issue2.origin ?? "array"); - return `\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1${place}`; - } - default: - return `\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF`; - } - }; - }; - } -}); - -// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/hu.js -function hu_default() { - return { - localeError: error18() - }; -} -var error18; -var init_hu = __esm({ - "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/hu.js"() { - init_util(); - error18 = () => { - const Sizable = { - string: { unit: "karakter", verb: "legyen" }, - file: { unit: "byte", verb: "legyen" }, - array: { unit: "elem", verb: "legyen" }, - set: { unit: "elem", verb: "legyen" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "bemenet", - email: "email c\xEDm", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO id\u0151b\xE9lyeg", - date: "ISO d\xE1tum", - time: "ISO id\u0151", - duration: "ISO id\u0151intervallum", - ipv4: "IPv4 c\xEDm", - ipv6: "IPv6 c\xEDm", - cidrv4: "IPv4 tartom\xE1ny", - cidrv6: "IPv6 tartom\xE1ny", - base64: "base64-k\xF3dolt string", - base64url: "base64url-k\xF3dolt string", - json_string: "JSON string", - e164: "E.164 sz\xE1m", - jwt: "JWT", - template_literal: "bemenet" - }; - const TypeDictionary = { - nan: "NaN", - number: "sz\xE1m", - array: "t\xF6mb" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k instanceof ${issue2.expected}, a kapott \xE9rt\xE9k ${received}`; - } - return `\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${expected}, a kapott \xE9rt\xE9k ${received}`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${stringifyPrimitive(issue2.values[0])}`; - return `\xC9rv\xE9nytelen opci\xF3: valamelyik \xE9rt\xE9k v\xE1rt ${joinValues(issue2.values, "|")}`; - case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; - const sizing = getSizing(issue2.origin); - if (sizing) - return `T\xFAl nagy: ${issue2.origin ?? "\xE9rt\xE9k"} m\xE9rete t\xFAl nagy ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elem"}`; - return `T\xFAl nagy: a bemeneti \xE9rt\xE9k ${issue2.origin ?? "\xE9rt\xE9k"} t\xFAl nagy: ${adj}${issue2.maximum.toString()}`; - } - case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${issue2.origin} m\xE9rete t\xFAl kicsi ${adj}${issue2.minimum.toString()} ${sizing.unit}`; - } - return `T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${issue2.origin} t\xFAl kicsi ${adj}${issue2.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") - return `\xC9rv\xE9nytelen string: "${_issue.prefix}" \xE9rt\xE9kkel kell kezd\u0151dnie`; - if (_issue.format === "ends_with") - return `\xC9rv\xE9nytelen string: "${_issue.suffix}" \xE9rt\xE9kkel kell v\xE9gz\u0151dnie`; - if (_issue.format === "includes") - return `\xC9rv\xE9nytelen string: "${_issue.includes}" \xE9rt\xE9ket kell tartalmaznia`; - if (_issue.format === "regex") - return `\xC9rv\xE9nytelen string: ${_issue.pattern} mint\xE1nak kell megfelelnie`; - return `\xC9rv\xE9nytelen ${FormatDictionary[_issue.format] ?? issue2.format}`; - } - case "not_multiple_of": - return `\xC9rv\xE9nytelen sz\xE1m: ${issue2.divisor} t\xF6bbsz\xF6r\xF6s\xE9nek kell lennie`; - case "unrecognized_keys": - return `Ismeretlen kulcs${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return `\xC9rv\xE9nytelen kulcs ${issue2.origin}`; - case "invalid_union": - return "\xC9rv\xE9nytelen bemenet"; - case "invalid_element": - return `\xC9rv\xE9nytelen \xE9rt\xE9k: ${issue2.origin}`; - default: - return `\xC9rv\xE9nytelen bemenet`; - } - }; - }; - } -}); - -// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/hy.js -function getArmenianPlural(count2, one, many) { - return Math.abs(count2) === 1 ? one : many; -} -function withDefiniteArticle(word) { - if (!word) - return ""; - const vowels = ["\u0561", "\u0565", "\u0568", "\u056B", "\u0578", "\u0578\u0582", "\u0585"]; - const lastChar = word[word.length - 1]; - return word + (vowels.includes(lastChar) ? "\u0576" : "\u0568"); -} -function hy_default() { - return { - localeError: error19() - }; -} -var error19; -var init_hy = __esm({ - "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/hy.js"() { - init_util(); - error19 = () => { - const Sizable = { - string: { - unit: { - one: "\u0576\u0577\u0561\u0576", - many: "\u0576\u0577\u0561\u0576\u0576\u0565\u0580" - }, - verb: "\u0578\u0582\u0576\u0565\u0576\u0561\u056C" - }, - file: { - unit: { - one: "\u0562\u0561\u0575\u0569", - many: "\u0562\u0561\u0575\u0569\u0565\u0580" - }, - verb: "\u0578\u0582\u0576\u0565\u0576\u0561\u056C" - }, - array: { - unit: { - one: "\u057F\u0561\u0580\u0580", - many: "\u057F\u0561\u0580\u0580\u0565\u0580" - }, - verb: "\u0578\u0582\u0576\u0565\u0576\u0561\u056C" - }, - set: { - unit: { - one: "\u057F\u0561\u0580\u0580", - many: "\u057F\u0561\u0580\u0580\u0565\u0580" - }, - verb: "\u0578\u0582\u0576\u0565\u0576\u0561\u056C" - } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "\u0574\u0578\u0582\u057F\u0584", - email: "\u0567\u056C. \u0570\u0561\u057D\u0581\u0565", - url: "URL", - emoji: "\u0567\u0574\u0578\u057B\u056B", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO \u0561\u0574\u057D\u0561\u0569\u056B\u057E \u0587 \u056A\u0561\u0574", - date: "ISO \u0561\u0574\u057D\u0561\u0569\u056B\u057E", - time: "ISO \u056A\u0561\u0574", - duration: "ISO \u057F\u0587\u0578\u0572\u0578\u0582\u0569\u0575\u0578\u0582\u0576", - ipv4: "IPv4 \u0570\u0561\u057D\u0581\u0565", - ipv6: "IPv6 \u0570\u0561\u057D\u0581\u0565", - cidrv4: "IPv4 \u0574\u056B\u057B\u0561\u056F\u0561\u0575\u0584", - cidrv6: "IPv6 \u0574\u056B\u057B\u0561\u056F\u0561\u0575\u0584", - base64: "base64 \u0571\u0587\u0561\u0579\u0561\u0583\u0578\u057E \u057F\u0578\u0572", - base64url: "base64url \u0571\u0587\u0561\u0579\u0561\u0583\u0578\u057E \u057F\u0578\u0572", - json_string: "JSON \u057F\u0578\u0572", - e164: "E.164 \u0570\u0561\u0574\u0561\u0580", - jwt: "JWT", - template_literal: "\u0574\u0578\u0582\u057F\u0584" - }; - const TypeDictionary = { - nan: "NaN", - number: "\u0569\u056B\u057E", - array: "\u0566\u0561\u0576\u0563\u057E\u0561\u056E" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 instanceof ${issue2.expected}, \u057D\u057F\u0561\u0581\u057E\u0565\u056C \u0567 ${received}`; - } - return `\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 ${expected}, \u057D\u057F\u0561\u0581\u057E\u0565\u056C \u0567 ${received}`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 ${stringifyPrimitive(issue2.values[1])}`; - return `\u054D\u056D\u0561\u056C \u057F\u0561\u0580\u0562\u0565\u0580\u0561\u056F\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 \u0570\u0565\u057F\u0587\u0575\u0561\u056C\u0576\u0565\u0580\u056B\u0581 \u0574\u0565\u056F\u0568\u055D ${joinValues(issue2.values, "|")}`; - case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; - const sizing = getSizing(issue2.origin); - if (sizing) { - const maxValue = Number(issue2.maximum); - const unit = getArmenianPlural(maxValue, sizing.unit.one, sizing.unit.many); - return `\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0574\u0565\u056E \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${withDefiniteArticle(issue2.origin ?? "\u0561\u0580\u056A\u0565\u0584")} \u056F\u0578\u0582\u0576\u0565\u0576\u0561 ${adj}${issue2.maximum.toString()} ${unit}`; - } - return `\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0574\u0565\u056E \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${withDefiniteArticle(issue2.origin ?? "\u0561\u0580\u056A\u0565\u0584")} \u056C\u056B\u0576\u056B ${adj}${issue2.maximum.toString()}`; - } - case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; - const sizing = getSizing(issue2.origin); - if (sizing) { - const minValue = Number(issue2.minimum); - const unit = getArmenianPlural(minValue, sizing.unit.one, sizing.unit.many); - return `\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0583\u0578\u0584\u0580 \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${withDefiniteArticle(issue2.origin)} \u056F\u0578\u0582\u0576\u0565\u0576\u0561 ${adj}${issue2.minimum.toString()} ${unit}`; - } - return `\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0583\u0578\u0584\u0580 \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${withDefiniteArticle(issue2.origin)} \u056C\u056B\u0576\u056B ${adj}${issue2.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") - return `\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u057D\u056F\u057D\u057E\u056B "${_issue.prefix}"-\u0578\u057E`; - if (_issue.format === "ends_with") - return `\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0561\u057E\u0561\u0580\u057F\u057E\u056B "${_issue.suffix}"-\u0578\u057E`; - if (_issue.format === "includes") - return `\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u057A\u0561\u0580\u0578\u0582\u0576\u0561\u056F\u056B "${_issue.includes}"`; - if (_issue.format === "regex") - return `\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0570\u0561\u0574\u0561\u057A\u0561\u057F\u0561\u057D\u056D\u0561\u0576\u056B ${_issue.pattern} \u0571\u0587\u0561\u0579\u0561\u0583\u056B\u0576`; - return `\u054D\u056D\u0561\u056C ${FormatDictionary[_issue.format] ?? issue2.format}`; - } - case "not_multiple_of": - return `\u054D\u056D\u0561\u056C \u0569\u056B\u057E\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0562\u0561\u0566\u0574\u0561\u057A\u0561\u057F\u056B\u056F \u056C\u056B\u0576\u056B ${issue2.divisor}-\u056B`; - case "unrecognized_keys": - return `\u0549\u0573\u0561\u0576\u0561\u0579\u057E\u0561\u056E \u0562\u0561\u0576\u0561\u056C\u056B${issue2.keys.length > 1 ? "\u0576\u0565\u0580" : ""}. ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return `\u054D\u056D\u0561\u056C \u0562\u0561\u0576\u0561\u056C\u056B ${withDefiniteArticle(issue2.origin)}-\u0578\u0582\u0574`; - case "invalid_union": - return "\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574"; - case "invalid_element": - return `\u054D\u056D\u0561\u056C \u0561\u0580\u056A\u0565\u0584 ${withDefiniteArticle(issue2.origin)}-\u0578\u0582\u0574`; - default: - return `\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574`; - } - }; - }; - } -}); - -// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/id.js -function id_default() { - return { - localeError: error20() - }; -} -var error20; -var init_id2 = __esm({ - "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/id.js"() { - init_util(); - error20 = () => { - const Sizable = { - string: { unit: "karakter", verb: "memiliki" }, - file: { unit: "byte", verb: "memiliki" }, - array: { unit: "item", verb: "memiliki" }, - set: { unit: "item", verb: "memiliki" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "input", - email: "alamat email", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "tanggal dan waktu format ISO", - date: "tanggal format ISO", - time: "jam format ISO", - duration: "durasi format ISO", - ipv4: "alamat IPv4", - ipv6: "alamat IPv6", - cidrv4: "rentang alamat IPv4", - cidrv6: "rentang alamat IPv6", - base64: "string dengan enkode base64", - base64url: "string dengan enkode base64url", - json_string: "string JSON", - e164: "angka E.164", - jwt: "JWT", - template_literal: "input" - }; - const TypeDictionary = { - nan: "NaN" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `Input tidak valid: diharapkan instanceof ${issue2.expected}, diterima ${received}`; - } - return `Input tidak valid: diharapkan ${expected}, diterima ${received}`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `Input tidak valid: diharapkan ${stringifyPrimitive(issue2.values[0])}`; - return `Pilihan tidak valid: diharapkan salah satu dari ${joinValues(issue2.values, "|")}`; - case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; - const sizing = getSizing(issue2.origin); - if (sizing) - return `Terlalu besar: diharapkan ${issue2.origin ?? "value"} memiliki ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elemen"}`; - return `Terlalu besar: diharapkan ${issue2.origin ?? "value"} menjadi ${adj}${issue2.maximum.toString()}`; - } - case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `Terlalu kecil: diharapkan ${issue2.origin} memiliki ${adj}${issue2.minimum.toString()} ${sizing.unit}`; - } - return `Terlalu kecil: diharapkan ${issue2.origin} menjadi ${adj}${issue2.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") - return `String tidak valid: harus dimulai dengan "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `String tidak valid: harus berakhir dengan "${_issue.suffix}"`; - if (_issue.format === "includes") - return `String tidak valid: harus menyertakan "${_issue.includes}"`; - if (_issue.format === "regex") - return `String tidak valid: harus sesuai pola ${_issue.pattern}`; - return `${FormatDictionary[_issue.format] ?? issue2.format} tidak valid`; - } - case "not_multiple_of": - return `Angka tidak valid: harus kelipatan dari ${issue2.divisor}`; - case "unrecognized_keys": - return `Kunci tidak dikenali ${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return `Kunci tidak valid di ${issue2.origin}`; - case "invalid_union": - return "Input tidak valid"; - case "invalid_element": - return `Nilai tidak valid di ${issue2.origin}`; - default: - return `Input tidak valid`; - } - }; - }; - } -}); - -// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/is.js -function is_default() { - return { - localeError: error21() - }; -} -var error21; -var init_is = __esm({ - "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/is.js"() { - init_util(); - error21 = () => { - const Sizable = { - string: { unit: "stafi", verb: "a\xF0 hafa" }, - file: { unit: "b\xE6ti", verb: "a\xF0 hafa" }, - array: { unit: "hluti", verb: "a\xF0 hafa" }, - set: { unit: "hluti", verb: "a\xF0 hafa" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "gildi", - email: "netfang", - url: "vefsl\xF3\xF0", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO dagsetning og t\xEDmi", - date: "ISO dagsetning", - time: "ISO t\xEDmi", - duration: "ISO t\xEDmalengd", - ipv4: "IPv4 address", - ipv6: "IPv6 address", - cidrv4: "IPv4 range", - cidrv6: "IPv6 range", - base64: "base64-encoded strengur", - base64url: "base64url-encoded strengur", - json_string: "JSON strengur", - e164: "E.164 t\xF6lugildi", - jwt: "JWT", - template_literal: "gildi" - }; - const TypeDictionary = { - nan: "NaN", - number: "n\xFAmer", - array: "fylki" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `Rangt gildi: \xDE\xFA sl\xF3st inn ${received} \xFEar sem \xE1 a\xF0 vera instanceof ${issue2.expected}`; - } - return `Rangt gildi: \xDE\xFA sl\xF3st inn ${received} \xFEar sem \xE1 a\xF0 vera ${expected}`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `Rangt gildi: gert r\xE1\xF0 fyrir ${stringifyPrimitive(issue2.values[0])}`; - return `\xD3gilt val: m\xE1 vera eitt af eftirfarandi ${joinValues(issue2.values, "|")}`; - case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; - const sizing = getSizing(issue2.origin); - if (sizing) - return `Of st\xF3rt: gert er r\xE1\xF0 fyrir a\xF0 ${issue2.origin ?? "gildi"} hafi ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "hluti"}`; - return `Of st\xF3rt: gert er r\xE1\xF0 fyrir a\xF0 ${issue2.origin ?? "gildi"} s\xE9 ${adj}${issue2.maximum.toString()}`; - } - case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `Of l\xEDti\xF0: gert er r\xE1\xF0 fyrir a\xF0 ${issue2.origin} hafi ${adj}${issue2.minimum.toString()} ${sizing.unit}`; - } - return `Of l\xEDti\xF0: gert er r\xE1\xF0 fyrir a\xF0 ${issue2.origin} s\xE9 ${adj}${issue2.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") { - return `\xD3gildur strengur: ver\xF0ur a\xF0 byrja \xE1 "${_issue.prefix}"`; - } - if (_issue.format === "ends_with") - return `\xD3gildur strengur: ver\xF0ur a\xF0 enda \xE1 "${_issue.suffix}"`; - if (_issue.format === "includes") - return `\xD3gildur strengur: ver\xF0ur a\xF0 innihalda "${_issue.includes}"`; - if (_issue.format === "regex") - return `\xD3gildur strengur: ver\xF0ur a\xF0 fylgja mynstri ${_issue.pattern}`; - return `Rangt ${FormatDictionary[_issue.format] ?? issue2.format}`; - } - case "not_multiple_of": - return `R\xF6ng tala: ver\xF0ur a\xF0 vera margfeldi af ${issue2.divisor}`; - case "unrecognized_keys": - return `\xD3\xFEekkt ${issue2.keys.length > 1 ? "ir lyklar" : "ur lykill"}: ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return `Rangur lykill \xED ${issue2.origin}`; - case "invalid_union": - return "Rangt gildi"; - case "invalid_element": - return `Rangt gildi \xED ${issue2.origin}`; - default: - return `Rangt gildi`; - } - }; - }; - } -}); - -// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/it.js -function it_default() { - return { - localeError: error22() - }; -} -var error22; -var init_it = __esm({ - "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/it.js"() { - init_util(); - error22 = () => { - const Sizable = { - string: { unit: "caratteri", verb: "avere" }, - file: { unit: "byte", verb: "avere" }, - array: { unit: "elementi", verb: "avere" }, - set: { unit: "elementi", verb: "avere" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "input", - email: "indirizzo email", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "data e ora ISO", - date: "data ISO", - time: "ora ISO", - duration: "durata ISO", - ipv4: "indirizzo IPv4", - ipv6: "indirizzo IPv6", - cidrv4: "intervallo IPv4", - cidrv6: "intervallo IPv6", - base64: "stringa codificata in base64", - base64url: "URL codificata in base64", - json_string: "stringa JSON", - e164: "numero E.164", - jwt: "JWT", - template_literal: "input" - }; - const TypeDictionary = { - nan: "NaN", - number: "numero", - array: "vettore" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `Input non valido: atteso instanceof ${issue2.expected}, ricevuto ${received}`; - } - return `Input non valido: atteso ${expected}, ricevuto ${received}`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `Input non valido: atteso ${stringifyPrimitive(issue2.values[0])}`; - return `Opzione non valida: atteso uno tra ${joinValues(issue2.values, "|")}`; - case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; - const sizing = getSizing(issue2.origin); - if (sizing) - return `Troppo grande: ${issue2.origin ?? "valore"} deve avere ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementi"}`; - return `Troppo grande: ${issue2.origin ?? "valore"} deve essere ${adj}${issue2.maximum.toString()}`; - } - case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `Troppo piccolo: ${issue2.origin} deve avere ${adj}${issue2.minimum.toString()} ${sizing.unit}`; - } - return `Troppo piccolo: ${issue2.origin} deve essere ${adj}${issue2.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") - return `Stringa non valida: deve iniziare con "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `Stringa non valida: deve terminare con "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Stringa non valida: deve includere "${_issue.includes}"`; - if (_issue.format === "regex") - return `Stringa non valida: deve corrispondere al pattern ${_issue.pattern}`; - return `Invalid ${FormatDictionary[_issue.format] ?? issue2.format}`; - } - case "not_multiple_of": - return `Numero non valido: deve essere un multiplo di ${issue2.divisor}`; - case "unrecognized_keys": - return `Chiav${issue2.keys.length > 1 ? "i" : "e"} non riconosciut${issue2.keys.length > 1 ? "e" : "a"}: ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return `Chiave non valida in ${issue2.origin}`; - case "invalid_union": - return "Input non valido"; - case "invalid_element": - return `Valore non valido in ${issue2.origin}`; - default: - return `Input non valido`; - } - }; - }; - } -}); - -// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ja.js -function ja_default() { - return { - localeError: error23() - }; -} -var error23; -var init_ja = __esm({ - "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ja.js"() { - init_util(); - error23 = () => { - const Sizable = { - string: { unit: "\u6587\u5B57", verb: "\u3067\u3042\u308B" }, - file: { unit: "\u30D0\u30A4\u30C8", verb: "\u3067\u3042\u308B" }, - array: { unit: "\u8981\u7D20", verb: "\u3067\u3042\u308B" }, - set: { unit: "\u8981\u7D20", verb: "\u3067\u3042\u308B" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "\u5165\u529B\u5024", - email: "\u30E1\u30FC\u30EB\u30A2\u30C9\u30EC\u30B9", - url: "URL", - emoji: "\u7D75\u6587\u5B57", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO\u65E5\u6642", - date: "ISO\u65E5\u4ED8", - time: "ISO\u6642\u523B", - duration: "ISO\u671F\u9593", - ipv4: "IPv4\u30A2\u30C9\u30EC\u30B9", - ipv6: "IPv6\u30A2\u30C9\u30EC\u30B9", - cidrv4: "IPv4\u7BC4\u56F2", - cidrv6: "IPv6\u7BC4\u56F2", - base64: "base64\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217", - base64url: "base64url\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217", - json_string: "JSON\u6587\u5B57\u5217", - e164: "E.164\u756A\u53F7", - jwt: "JWT", - template_literal: "\u5165\u529B\u5024" - }; - const TypeDictionary = { - nan: "NaN", - number: "\u6570\u5024", - array: "\u914D\u5217" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `\u7121\u52B9\u306A\u5165\u529B: instanceof ${issue2.expected}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F\u304C\u3001${received}\u304C\u5165\u529B\u3055\u308C\u307E\u3057\u305F`; - } - return `\u7121\u52B9\u306A\u5165\u529B: ${expected}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F\u304C\u3001${received}\u304C\u5165\u529B\u3055\u308C\u307E\u3057\u305F`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `\u7121\u52B9\u306A\u5165\u529B: ${stringifyPrimitive(issue2.values[0])}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F`; - return `\u7121\u52B9\u306A\u9078\u629E: ${joinValues(issue2.values, "\u3001")}\u306E\u3044\u305A\u308C\u304B\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; - case "too_big": { - const adj = issue2.inclusive ? "\u4EE5\u4E0B\u3067\u3042\u308B" : "\u3088\u308A\u5C0F\u3055\u3044"; - const sizing = getSizing(issue2.origin); - if (sizing) - return `\u5927\u304D\u3059\u304E\u308B\u5024: ${issue2.origin ?? "\u5024"}\u306F${issue2.maximum.toString()}${sizing.unit ?? "\u8981\u7D20"}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; - return `\u5927\u304D\u3059\u304E\u308B\u5024: ${issue2.origin ?? "\u5024"}\u306F${issue2.maximum.toString()}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; - } - case "too_small": { - const adj = issue2.inclusive ? "\u4EE5\u4E0A\u3067\u3042\u308B" : "\u3088\u308A\u5927\u304D\u3044"; - const sizing = getSizing(issue2.origin); - if (sizing) - return `\u5C0F\u3055\u3059\u304E\u308B\u5024: ${issue2.origin}\u306F${issue2.minimum.toString()}${sizing.unit}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; - return `\u5C0F\u3055\u3059\u304E\u308B\u5024: ${issue2.origin}\u306F${issue2.minimum.toString()}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") - return `\u7121\u52B9\u306A\u6587\u5B57\u5217: "${_issue.prefix}"\u3067\u59CB\u307E\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; - if (_issue.format === "ends_with") - return `\u7121\u52B9\u306A\u6587\u5B57\u5217: "${_issue.suffix}"\u3067\u7D42\u308F\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; - if (_issue.format === "includes") - return `\u7121\u52B9\u306A\u6587\u5B57\u5217: "${_issue.includes}"\u3092\u542B\u3080\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; - if (_issue.format === "regex") - return `\u7121\u52B9\u306A\u6587\u5B57\u5217: \u30D1\u30BF\u30FC\u30F3${_issue.pattern}\u306B\u4E00\u81F4\u3059\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; - return `\u7121\u52B9\u306A${FormatDictionary[_issue.format] ?? issue2.format}`; - } - case "not_multiple_of": - return `\u7121\u52B9\u306A\u6570\u5024: ${issue2.divisor}\u306E\u500D\u6570\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; - case "unrecognized_keys": - return `\u8A8D\u8B58\u3055\u308C\u3066\u3044\u306A\u3044\u30AD\u30FC${issue2.keys.length > 1 ? "\u7FA4" : ""}: ${joinValues(issue2.keys, "\u3001")}`; - case "invalid_key": - return `${issue2.origin}\u5185\u306E\u7121\u52B9\u306A\u30AD\u30FC`; - case "invalid_union": - return "\u7121\u52B9\u306A\u5165\u529B"; - case "invalid_element": - return `${issue2.origin}\u5185\u306E\u7121\u52B9\u306A\u5024`; - default: - return `\u7121\u52B9\u306A\u5165\u529B`; - } - }; - }; - } -}); - -// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ka.js -function ka_default() { - return { - localeError: error24() - }; -} -var error24; -var init_ka = __esm({ - "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ka.js"() { - init_util(); - error24 = () => { - const Sizable = { - string: { unit: "\u10E1\u10D8\u10DB\u10D1\u10DD\u10DA\u10DD", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" }, - file: { unit: "\u10D1\u10D0\u10D8\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" }, - array: { unit: "\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" }, - set: { unit: "\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "\u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0", - email: "\u10D4\u10DA-\u10E4\u10DD\u10E1\u10E2\u10D8\u10E1 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8", - url: "URL", - emoji: "\u10D4\u10DB\u10DD\u10EF\u10D8", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "\u10D7\u10D0\u10E0\u10D8\u10E6\u10D8-\u10D3\u10E0\u10DD", - date: "\u10D7\u10D0\u10E0\u10D8\u10E6\u10D8", - time: "\u10D3\u10E0\u10DD", - duration: "\u10EE\u10D0\u10DC\u10D2\u10E0\u10EB\u10DA\u10D8\u10D5\u10DD\u10D1\u10D0", - ipv4: "IPv4 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8", - ipv6: "IPv6 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8", - cidrv4: "IPv4 \u10D3\u10D8\u10D0\u10DE\u10D0\u10D6\u10DD\u10DC\u10D8", - cidrv6: "IPv6 \u10D3\u10D8\u10D0\u10DE\u10D0\u10D6\u10DD\u10DC\u10D8", - base64: "base64-\u10D9\u10DD\u10D3\u10D8\u10E0\u10D4\u10D1\u10E3\u10DA\u10D8 \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8", - base64url: "base64url-\u10D9\u10DD\u10D3\u10D8\u10E0\u10D4\u10D1\u10E3\u10DA\u10D8 \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8", - json_string: "JSON \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8", - e164: "E.164 \u10DC\u10DD\u10DB\u10D4\u10E0\u10D8", - jwt: "JWT", - template_literal: "\u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0" - }; - const TypeDictionary = { - nan: "NaN", - number: "\u10E0\u10D8\u10EA\u10EE\u10D5\u10D8", - string: "\u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8", - boolean: "\u10D1\u10E3\u10DA\u10D4\u10D0\u10DC\u10D8", - function: "\u10E4\u10E3\u10DC\u10E5\u10EA\u10D8\u10D0", - array: "\u10DB\u10D0\u10E1\u10D8\u10D5\u10D8" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 instanceof ${issue2.expected}, \u10DB\u10D8\u10E6\u10D4\u10D1\u10E3\u10DA\u10D8 ${received}`; - } - return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${expected}, \u10DB\u10D8\u10E6\u10D4\u10D1\u10E3\u10DA\u10D8 ${received}`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${stringifyPrimitive(issue2.values[0])}`; - return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D0\u10E0\u10D8\u10D0\u10DC\u10E2\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8\u10D0 \u10D4\u10E0\u10D7-\u10D4\u10E0\u10D7\u10D8 ${joinValues(issue2.values, "|")}-\u10D3\u10D0\u10DC`; - case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; - const sizing = getSizing(issue2.origin); - if (sizing) - return `\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10D3\u10D8\u10D3\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${issue2.origin ?? "\u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit}`; - return `\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10D3\u10D8\u10D3\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${issue2.origin ?? "\u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0"} \u10D8\u10E7\u10DD\u10E1 ${adj}${issue2.maximum.toString()}`; - } - case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10DE\u10D0\u10E2\u10D0\u10E0\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; - } - return `\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10DE\u10D0\u10E2\u10D0\u10E0\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${issue2.origin} \u10D8\u10E7\u10DD\u10E1 ${adj}${issue2.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") { - return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10D8\u10EC\u10E7\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 "${_issue.prefix}"-\u10D8\u10D7`; - } - if (_issue.format === "ends_with") - return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10DB\u10D7\u10D0\u10D5\u10E0\u10D3\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 "${_issue.suffix}"-\u10D8\u10D7`; - if (_issue.format === "includes") - return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1 "${_issue.includes}"-\u10E1`; - if (_issue.format === "regex") - return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D4\u10E1\u10D0\u10D1\u10D0\u10DB\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 \u10E8\u10D0\u10D1\u10DA\u10DD\u10DC\u10E1 ${_issue.pattern}`; - return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 ${FormatDictionary[_issue.format] ?? issue2.format}`; - } - case "not_multiple_of": - return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E0\u10D8\u10EA\u10EE\u10D5\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10D8\u10E7\u10DD\u10E1 ${issue2.divisor}-\u10D8\u10E1 \u10EF\u10D4\u10E0\u10D0\u10D3\u10D8`; - case "unrecognized_keys": - return `\u10E3\u10EA\u10DC\u10DD\u10D1\u10D8 \u10D2\u10D0\u10E1\u10D0\u10E6\u10D4\u10D1${issue2.keys.length > 1 ? "\u10D4\u10D1\u10D8" : "\u10D8"}: ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D2\u10D0\u10E1\u10D0\u10E6\u10D4\u10D1\u10D8 ${issue2.origin}-\u10E8\u10D8`; - case "invalid_union": - return "\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0"; - case "invalid_element": - return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0 ${issue2.origin}-\u10E8\u10D8`; - default: - return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0`; - } - }; - }; - } -}); - -// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/km.js -function km_default() { - return { - localeError: error25() - }; -} -var error25; -var init_km = __esm({ - "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/km.js"() { - init_util(); - error25 = () => { - const Sizable = { - string: { unit: "\u178F\u17BD\u17A2\u1780\u17D2\u179F\u179A", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, - file: { unit: "\u1794\u17C3", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, - array: { unit: "\u1792\u17B6\u178F\u17BB", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, - set: { unit: "\u1792\u17B6\u178F\u17BB", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B", - email: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793\u17A2\u17CA\u17B8\u1798\u17C2\u179B", - url: "URL", - emoji: "\u179F\u1789\u17D2\u1789\u17B6\u17A2\u17B6\u179A\u1798\u17D2\u1798\u178E\u17CD", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 \u1793\u17B7\u1784\u1798\u17C9\u17C4\u1784 ISO", - date: "\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 ISO", - time: "\u1798\u17C9\u17C4\u1784 ISO", - duration: "\u179A\u1799\u17C8\u1796\u17C1\u179B ISO", - ipv4: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4", - ipv6: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6", - cidrv4: "\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4", - cidrv6: "\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6", - base64: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64", - base64url: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64url", - json_string: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A JSON", - e164: "\u179B\u17C1\u1781 E.164", - jwt: "JWT", - template_literal: "\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B" - }; - const TypeDictionary = { - nan: "NaN", - number: "\u179B\u17C1\u1781", - array: "\u17A2\u17B6\u179A\u17C1 (Array)", - null: "\u1782\u17D2\u1798\u17B6\u1793\u178F\u1798\u17D2\u179B\u17C3 (null)" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A instanceof ${issue2.expected} \u1794\u17C9\u17BB\u1793\u17D2\u178F\u17C2\u1791\u1791\u17BD\u179B\u1794\u17B6\u1793 ${received}`; - } - return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${expected} \u1794\u17C9\u17BB\u1793\u17D2\u178F\u17C2\u1791\u1791\u17BD\u179B\u1794\u17B6\u1793 ${received}`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${stringifyPrimitive(issue2.values[0])}`; - return `\u1787\u1798\u17D2\u179A\u17BE\u179F\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1787\u17B6\u1798\u17BD\u1799\u1780\u17D2\u1793\u17BB\u1784\u1785\u17C6\u178E\u17C4\u1798 ${joinValues(issue2.values, "|")}`; - case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; - const sizing = getSizing(issue2.origin); - if (sizing) - return `\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue2.origin ?? "\u178F\u1798\u17D2\u179B\u17C3"} ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "\u1792\u17B6\u178F\u17BB"}`; - return `\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue2.origin ?? "\u178F\u1798\u17D2\u179B\u17C3"} ${adj} ${issue2.maximum.toString()}`; - } - case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue2.origin} ${adj} ${issue2.minimum.toString()} ${sizing.unit}`; - } - return `\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue2.origin} ${adj} ${issue2.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") { - return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1785\u17B6\u1794\u17CB\u1795\u17D2\u178F\u17BE\u1798\u178A\u17C4\u1799 "${_issue.prefix}"`; - } - if (_issue.format === "ends_with") - return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1794\u1789\u17D2\u1785\u1794\u17CB\u178A\u17C4\u1799 "${_issue.suffix}"`; - if (_issue.format === "includes") - return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1798\u17B6\u1793 "${_issue.includes}"`; - if (_issue.format === "regex") - return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1795\u17D2\u1782\u17BC\u1795\u17D2\u1782\u1784\u1793\u17B9\u1784\u1791\u1798\u17D2\u179A\u1784\u17CB\u178A\u17C2\u179B\u1794\u17B6\u1793\u1780\u17C6\u178E\u178F\u17CB ${_issue.pattern}`; - return `\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 ${FormatDictionary[_issue.format] ?? issue2.format}`; - } - case "not_multiple_of": - return `\u179B\u17C1\u1781\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1787\u17B6\u1796\u17A0\u17BB\u1782\u17BB\u178E\u1793\u17C3 ${issue2.divisor}`; - case "unrecognized_keys": - return `\u179A\u1780\u1783\u17BE\u1789\u179F\u17C4\u1798\u17B7\u1793\u179F\u17D2\u1782\u17B6\u179B\u17CB\u17D6 ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return `\u179F\u17C4\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${issue2.origin}`; - case "invalid_union": - return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C`; - case "invalid_element": - return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${issue2.origin}`; - default: - return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C`; - } - }; - }; - } -}); - -// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/kh.js -function kh_default() { - return km_default(); -} -var init_kh = __esm({ - "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/kh.js"() { - init_km(); - } -}); - -// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ko.js -function ko_default() { - return { - localeError: error26() - }; -} -var error26; -var init_ko = __esm({ - "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ko.js"() { - init_util(); - error26 = () => { - const Sizable = { - string: { unit: "\uBB38\uC790", verb: "to have" }, - file: { unit: "\uBC14\uC774\uD2B8", verb: "to have" }, - array: { unit: "\uAC1C", verb: "to have" }, - set: { unit: "\uAC1C", verb: "to have" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "\uC785\uB825", - email: "\uC774\uBA54\uC77C \uC8FC\uC18C", - url: "URL", - emoji: "\uC774\uBAA8\uC9C0", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO \uB0A0\uC9DC\uC2DC\uAC04", - date: "ISO \uB0A0\uC9DC", - time: "ISO \uC2DC\uAC04", - duration: "ISO \uAE30\uAC04", - ipv4: "IPv4 \uC8FC\uC18C", - ipv6: "IPv6 \uC8FC\uC18C", - cidrv4: "IPv4 \uBC94\uC704", - cidrv6: "IPv6 \uBC94\uC704", - base64: "base64 \uC778\uCF54\uB529 \uBB38\uC790\uC5F4", - base64url: "base64url \uC778\uCF54\uB529 \uBB38\uC790\uC5F4", - json_string: "JSON \uBB38\uC790\uC5F4", - e164: "E.164 \uBC88\uD638", - jwt: "JWT", - template_literal: "\uC785\uB825" - }; - const TypeDictionary = { - nan: "NaN" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `\uC798\uBABB\uB41C \uC785\uB825: \uC608\uC0C1 \uD0C0\uC785\uC740 instanceof ${issue2.expected}, \uBC1B\uC740 \uD0C0\uC785\uC740 ${received}\uC785\uB2C8\uB2E4`; - } - return `\uC798\uBABB\uB41C \uC785\uB825: \uC608\uC0C1 \uD0C0\uC785\uC740 ${expected}, \uBC1B\uC740 \uD0C0\uC785\uC740 ${received}\uC785\uB2C8\uB2E4`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `\uC798\uBABB\uB41C \uC785\uB825: \uAC12\uC740 ${stringifyPrimitive(issue2.values[0])} \uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4`; - return `\uC798\uBABB\uB41C \uC635\uC158: ${joinValues(issue2.values, "\uB610\uB294 ")} \uC911 \uD558\uB098\uC5EC\uC57C \uD569\uB2C8\uB2E4`; - case "too_big": { - const adj = issue2.inclusive ? "\uC774\uD558" : "\uBBF8\uB9CC"; - const suffix = adj === "\uBBF8\uB9CC" ? "\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4" : "\uC5EC\uC57C \uD569\uB2C8\uB2E4"; - const sizing = getSizing(issue2.origin); - const unit = sizing?.unit ?? "\uC694\uC18C"; - if (sizing) - return `${issue2.origin ?? "\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${issue2.maximum.toString()}${unit} ${adj}${suffix}`; - return `${issue2.origin ?? "\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${issue2.maximum.toString()} ${adj}${suffix}`; - } - case "too_small": { - const adj = issue2.inclusive ? "\uC774\uC0C1" : "\uCD08\uACFC"; - const suffix = adj === "\uC774\uC0C1" ? "\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4" : "\uC5EC\uC57C \uD569\uB2C8\uB2E4"; - const sizing = getSizing(issue2.origin); - const unit = sizing?.unit ?? "\uC694\uC18C"; - if (sizing) { - return `${issue2.origin ?? "\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${issue2.minimum.toString()}${unit} ${adj}${suffix}`; - } - return `${issue2.origin ?? "\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${issue2.minimum.toString()} ${adj}${suffix}`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") { - return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${_issue.prefix}"(\uC73C)\uB85C \uC2DC\uC791\uD574\uC57C \uD569\uB2C8\uB2E4`; - } - if (_issue.format === "ends_with") - return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${_issue.suffix}"(\uC73C)\uB85C \uB05D\uB098\uC57C \uD569\uB2C8\uB2E4`; - if (_issue.format === "includes") - return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${_issue.includes}"\uC744(\uB97C) \uD3EC\uD568\uD574\uC57C \uD569\uB2C8\uB2E4`; - if (_issue.format === "regex") - return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: \uC815\uADDC\uC2DD ${_issue.pattern} \uD328\uD134\uACFC \uC77C\uCE58\uD574\uC57C \uD569\uB2C8\uB2E4`; - return `\uC798\uBABB\uB41C ${FormatDictionary[_issue.format] ?? issue2.format}`; - } - case "not_multiple_of": - return `\uC798\uBABB\uB41C \uC22B\uC790: ${issue2.divisor}\uC758 \uBC30\uC218\uC5EC\uC57C \uD569\uB2C8\uB2E4`; - case "unrecognized_keys": - return `\uC778\uC2DD\uD560 \uC218 \uC5C6\uB294 \uD0A4: ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return `\uC798\uBABB\uB41C \uD0A4: ${issue2.origin}`; - case "invalid_union": - return `\uC798\uBABB\uB41C \uC785\uB825`; - case "invalid_element": - return `\uC798\uBABB\uB41C \uAC12: ${issue2.origin}`; - default: - return `\uC798\uBABB\uB41C \uC785\uB825`; - } - }; - }; - } -}); - -// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/lt.js -function getUnitTypeFromNumber(number4) { - const abs = Math.abs(number4); - const last = abs % 10; - const last2 = abs % 100; - if (last2 >= 11 && last2 <= 19 || last === 0) - return "many"; - if (last === 1) - return "one"; - return "few"; -} -function lt_default() { - return { - localeError: error27() - }; -} -var capitalizeFirstCharacter, error27; -var init_lt = __esm({ - "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/lt.js"() { - init_util(); - capitalizeFirstCharacter = (text3) => { - return text3.charAt(0).toUpperCase() + text3.slice(1); - }; - error27 = () => { - const Sizable = { - string: { - unit: { - one: "simbolis", - few: "simboliai", - many: "simboli\u0173" - }, - verb: { - smaller: { - inclusive: "turi b\u016Bti ne ilgesn\u0117 kaip", - notInclusive: "turi b\u016Bti trumpesn\u0117 kaip" - }, - bigger: { - inclusive: "turi b\u016Bti ne trumpesn\u0117 kaip", - notInclusive: "turi b\u016Bti ilgesn\u0117 kaip" - } - } - }, - file: { - unit: { - one: "baitas", - few: "baitai", - many: "bait\u0173" - }, - verb: { - smaller: { - inclusive: "turi b\u016Bti ne didesnis kaip", - notInclusive: "turi b\u016Bti ma\u017Eesnis kaip" - }, - bigger: { - inclusive: "turi b\u016Bti ne ma\u017Eesnis kaip", - notInclusive: "turi b\u016Bti didesnis kaip" - } - } - }, - array: { - unit: { - one: "element\u0105", - few: "elementus", - many: "element\u0173" - }, - verb: { - smaller: { - inclusive: "turi tur\u0117ti ne daugiau kaip", - notInclusive: "turi tur\u0117ti ma\u017Eiau kaip" - }, - bigger: { - inclusive: "turi tur\u0117ti ne ma\u017Eiau kaip", - notInclusive: "turi tur\u0117ti daugiau kaip" - } - } - }, - set: { - unit: { - one: "element\u0105", - few: "elementus", - many: "element\u0173" - }, - verb: { - smaller: { - inclusive: "turi tur\u0117ti ne daugiau kaip", - notInclusive: "turi tur\u0117ti ma\u017Eiau kaip" - }, - bigger: { - inclusive: "turi tur\u0117ti ne ma\u017Eiau kaip", - notInclusive: "turi tur\u0117ti daugiau kaip" - } - } - } - }; - function getSizing(origin, unitType, inclusive, targetShouldBe) { - const result = Sizable[origin] ?? null; - if (result === null) - return result; - return { - unit: result.unit[unitType], - verb: result.verb[targetShouldBe][inclusive ? "inclusive" : "notInclusive"] - }; - } - const FormatDictionary = { - regex: "\u012Fvestis", - email: "el. pa\u0161to adresas", - url: "URL", - emoji: "jaustukas", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO data ir laikas", - date: "ISO data", - time: "ISO laikas", - duration: "ISO trukm\u0117", - ipv4: "IPv4 adresas", - ipv6: "IPv6 adresas", - cidrv4: "IPv4 tinklo prefiksas (CIDR)", - cidrv6: "IPv6 tinklo prefiksas (CIDR)", - base64: "base64 u\u017Ekoduota eilut\u0117", - base64url: "base64url u\u017Ekoduota eilut\u0117", - json_string: "JSON eilut\u0117", - e164: "E.164 numeris", - jwt: "JWT", - template_literal: "\u012Fvestis" - }; - const TypeDictionary = { - nan: "NaN", - number: "skai\u010Dius", - bigint: "sveikasis skai\u010Dius", - string: "eilut\u0117", - boolean: "login\u0117 reik\u0161m\u0117", - undefined: "neapibr\u0117\u017Eta reik\u0161m\u0117", - function: "funkcija", - symbol: "simbolis", - array: "masyvas", - object: "objektas", - null: "nulin\u0117 reik\u0161m\u0117" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `Gautas tipas ${received}, o tik\u0117tasi - instanceof ${issue2.expected}`; - } - return `Gautas tipas ${received}, o tik\u0117tasi - ${expected}`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `Privalo b\u016Bti ${stringifyPrimitive(issue2.values[0])}`; - return `Privalo b\u016Bti vienas i\u0161 ${joinValues(issue2.values, "|")} pasirinkim\u0173`; - case "too_big": { - const origin = TypeDictionary[issue2.origin] ?? issue2.origin; - const sizing = getSizing(issue2.origin, getUnitTypeFromNumber(Number(issue2.maximum)), issue2.inclusive ?? false, "smaller"); - if (sizing?.verb) - return `${capitalizeFirstCharacter(origin ?? issue2.origin ?? "reik\u0161m\u0117")} ${sizing.verb} ${issue2.maximum.toString()} ${sizing.unit ?? "element\u0173"}`; - const adj = issue2.inclusive ? "ne didesnis kaip" : "ma\u017Eesnis kaip"; - return `${capitalizeFirstCharacter(origin ?? issue2.origin ?? "reik\u0161m\u0117")} turi b\u016Bti ${adj} ${issue2.maximum.toString()} ${sizing?.unit}`; - } - case "too_small": { - const origin = TypeDictionary[issue2.origin] ?? issue2.origin; - const sizing = getSizing(issue2.origin, getUnitTypeFromNumber(Number(issue2.minimum)), issue2.inclusive ?? false, "bigger"); - if (sizing?.verb) - return `${capitalizeFirstCharacter(origin ?? issue2.origin ?? "reik\u0161m\u0117")} ${sizing.verb} ${issue2.minimum.toString()} ${sizing.unit ?? "element\u0173"}`; - const adj = issue2.inclusive ? "ne ma\u017Eesnis kaip" : "didesnis kaip"; - return `${capitalizeFirstCharacter(origin ?? issue2.origin ?? "reik\u0161m\u0117")} turi b\u016Bti ${adj} ${issue2.minimum.toString()} ${sizing?.unit}`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") { - return `Eilut\u0117 privalo prasid\u0117ti "${_issue.prefix}"`; - } - if (_issue.format === "ends_with") - return `Eilut\u0117 privalo pasibaigti "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Eilut\u0117 privalo \u012Ftraukti "${_issue.includes}"`; - if (_issue.format === "regex") - return `Eilut\u0117 privalo atitikti ${_issue.pattern}`; - return `Neteisingas ${FormatDictionary[_issue.format] ?? issue2.format}`; - } - case "not_multiple_of": - return `Skai\u010Dius privalo b\u016Bti ${issue2.divisor} kartotinis.`; - case "unrecognized_keys": - return `Neatpa\u017Eint${issue2.keys.length > 1 ? "i" : "as"} rakt${issue2.keys.length > 1 ? "ai" : "as"}: ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return "Rastas klaidingas raktas"; - case "invalid_union": - return "Klaidinga \u012Fvestis"; - case "invalid_element": { - const origin = TypeDictionary[issue2.origin] ?? issue2.origin; - return `${capitalizeFirstCharacter(origin ?? issue2.origin ?? "reik\u0161m\u0117")} turi klaiding\u0105 \u012Fvest\u012F`; - } - default: - return "Klaidinga \u012Fvestis"; - } - }; - }; - } -}); - -// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/mk.js -function mk_default() { - return { - localeError: error28() - }; -} -var error28; -var init_mk = __esm({ - "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/mk.js"() { - init_util(); - error28 = () => { - const Sizable = { - string: { unit: "\u0437\u043D\u0430\u0446\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, - file: { unit: "\u0431\u0430\u0458\u0442\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, - array: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, - set: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "\u0432\u043D\u0435\u0441", - email: "\u0430\u0434\u0440\u0435\u0441\u0430 \u043D\u0430 \u0435-\u043F\u043E\u0448\u0442\u0430", - url: "URL", - emoji: "\u0435\u043C\u043E\u045F\u0438", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO \u0434\u0430\u0442\u0443\u043C \u0438 \u0432\u0440\u0435\u043C\u0435", - date: "ISO \u0434\u0430\u0442\u0443\u043C", - time: "ISO \u0432\u0440\u0435\u043C\u0435", - duration: "ISO \u0432\u0440\u0435\u043C\u0435\u0442\u0440\u0430\u0435\u045A\u0435", - ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441\u0430", - ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441\u0430", - cidrv4: "IPv4 \u043E\u043F\u0441\u0435\u0433", - cidrv6: "IPv6 \u043E\u043F\u0441\u0435\u0433", - base64: "base64-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430", - base64url: "base64url-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430", - json_string: "JSON \u043D\u0438\u0437\u0430", - e164: "E.164 \u0431\u0440\u043E\u0458", - jwt: "JWT", - template_literal: "\u0432\u043D\u0435\u0441" - }; - const TypeDictionary = { - nan: "NaN", - number: "\u0431\u0440\u043E\u0458", - array: "\u043D\u0438\u0437\u0430" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 instanceof ${issue2.expected}, \u043F\u0440\u0438\u043C\u0435\u043D\u043E ${received}`; - } - return `\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${expected}, \u043F\u0440\u0438\u043C\u0435\u043D\u043E ${received}`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `Invalid input: expected ${stringifyPrimitive(issue2.values[0])}`; - return `\u0413\u0440\u0435\u0448\u0430\u043D\u0430 \u043E\u043F\u0446\u0438\u0458\u0430: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 \u0435\u0434\u043D\u0430 ${joinValues(issue2.values, "|")}`; - case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; - const sizing = getSizing(issue2.origin); - if (sizing) - return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.origin ?? "\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0438\u043C\u0430 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0438"}`; - return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.origin ?? "\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0431\u0438\u0434\u0435 ${adj}${issue2.maximum.toString()}`; - } - case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.origin} \u0434\u0430 \u0438\u043C\u0430 ${adj}${issue2.minimum.toString()} ${sizing.unit}`; - } - return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.origin} \u0434\u0430 \u0431\u0438\u0434\u0435 ${adj}${issue2.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") { - return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u043F\u043E\u0447\u043D\u0443\u0432\u0430 \u0441\u043E "${_issue.prefix}"`; - } - if (_issue.format === "ends_with") - return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u0432\u0440\u0448\u0443\u0432\u0430 \u0441\u043E "${_issue.suffix}"`; - if (_issue.format === "includes") - return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0432\u043A\u043B\u0443\u0447\u0443\u0432\u0430 "${_issue.includes}"`; - if (_issue.format === "regex") - return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u043E\u0434\u0433\u043E\u0430\u0440\u0430 \u043D\u0430 \u043F\u0430\u0442\u0435\u0440\u043D\u043E\u0442 ${_issue.pattern}`; - return `Invalid ${FormatDictionary[_issue.format] ?? issue2.format}`; - } - case "not_multiple_of": - return `\u0413\u0440\u0435\u0448\u0435\u043D \u0431\u0440\u043E\u0458: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0431\u0438\u0434\u0435 \u0434\u0435\u043B\u0438\u0432 \u0441\u043E ${issue2.divisor}`; - case "unrecognized_keys": - return `${issue2.keys.length > 1 ? "\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D\u0438 \u043A\u043B\u0443\u0447\u0435\u0432\u0438" : "\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D \u043A\u043B\u0443\u0447"}: ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return `\u0413\u0440\u0435\u0448\u0435\u043D \u043A\u043B\u0443\u0447 \u0432\u043E ${issue2.origin}`; - case "invalid_union": - return "\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441"; - case "invalid_element": - return `\u0413\u0440\u0435\u0448\u043D\u0430 \u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442 \u0432\u043E ${issue2.origin}`; - default: - return `\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441`; - } - }; - }; - } -}); - -// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ms.js -function ms_default() { - return { - localeError: error29() - }; -} -var error29; -var init_ms = __esm({ - "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ms.js"() { - init_util(); - error29 = () => { - const Sizable = { - string: { unit: "aksara", verb: "mempunyai" }, - file: { unit: "bait", verb: "mempunyai" }, - array: { unit: "elemen", verb: "mempunyai" }, - set: { unit: "elemen", verb: "mempunyai" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "input", - email: "alamat e-mel", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "tarikh masa ISO", - date: "tarikh ISO", - time: "masa ISO", - duration: "tempoh ISO", - ipv4: "alamat IPv4", - ipv6: "alamat IPv6", - cidrv4: "julat IPv4", - cidrv6: "julat IPv6", - base64: "string dikodkan base64", - base64url: "string dikodkan base64url", - json_string: "string JSON", - e164: "nombor E.164", - jwt: "JWT", - template_literal: "input" - }; - const TypeDictionary = { - nan: "NaN", - number: "nombor" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `Input tidak sah: dijangka instanceof ${issue2.expected}, diterima ${received}`; - } - return `Input tidak sah: dijangka ${expected}, diterima ${received}`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `Input tidak sah: dijangka ${stringifyPrimitive(issue2.values[0])}`; - return `Pilihan tidak sah: dijangka salah satu daripada ${joinValues(issue2.values, "|")}`; - case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; - const sizing = getSizing(issue2.origin); - if (sizing) - return `Terlalu besar: dijangka ${issue2.origin ?? "nilai"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elemen"}`; - return `Terlalu besar: dijangka ${issue2.origin ?? "nilai"} adalah ${adj}${issue2.maximum.toString()}`; - } - case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `Terlalu kecil: dijangka ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; - } - return `Terlalu kecil: dijangka ${issue2.origin} adalah ${adj}${issue2.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") - return `String tidak sah: mesti bermula dengan "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `String tidak sah: mesti berakhir dengan "${_issue.suffix}"`; - if (_issue.format === "includes") - return `String tidak sah: mesti mengandungi "${_issue.includes}"`; - if (_issue.format === "regex") - return `String tidak sah: mesti sepadan dengan corak ${_issue.pattern}`; - return `${FormatDictionary[_issue.format] ?? issue2.format} tidak sah`; - } - case "not_multiple_of": - return `Nombor tidak sah: perlu gandaan ${issue2.divisor}`; - case "unrecognized_keys": - return `Kunci tidak dikenali: ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return `Kunci tidak sah dalam ${issue2.origin}`; - case "invalid_union": - return "Input tidak sah"; - case "invalid_element": - return `Nilai tidak sah dalam ${issue2.origin}`; - default: - return `Input tidak sah`; - } - }; - }; - } -}); - -// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/nl.js -function nl_default() { - return { - localeError: error30() - }; -} -var error30; -var init_nl = __esm({ - "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/nl.js"() { - init_util(); - error30 = () => { - const Sizable = { - string: { unit: "tekens", verb: "heeft" }, - file: { unit: "bytes", verb: "heeft" }, - array: { unit: "elementen", verb: "heeft" }, - set: { unit: "elementen", verb: "heeft" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "invoer", - email: "emailadres", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO datum en tijd", - date: "ISO datum", - time: "ISO tijd", - duration: "ISO duur", - ipv4: "IPv4-adres", - ipv6: "IPv6-adres", - cidrv4: "IPv4-bereik", - cidrv6: "IPv6-bereik", - base64: "base64-gecodeerde tekst", - base64url: "base64 URL-gecodeerde tekst", - json_string: "JSON string", - e164: "E.164-nummer", - jwt: "JWT", - template_literal: "invoer" - }; - const TypeDictionary = { - nan: "NaN", - number: "getal" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `Ongeldige invoer: verwacht instanceof ${issue2.expected}, ontving ${received}`; - } - return `Ongeldige invoer: verwacht ${expected}, ontving ${received}`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `Ongeldige invoer: verwacht ${stringifyPrimitive(issue2.values[0])}`; - return `Ongeldige optie: verwacht \xE9\xE9n van ${joinValues(issue2.values, "|")}`; - case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; - const sizing = getSizing(issue2.origin); - const longName = issue2.origin === "date" ? "laat" : issue2.origin === "string" ? "lang" : "groot"; - if (sizing) - return `Te ${longName}: verwacht dat ${issue2.origin ?? "waarde"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementen"} ${sizing.verb}`; - return `Te ${longName}: verwacht dat ${issue2.origin ?? "waarde"} ${adj}${issue2.maximum.toString()} is`; - } - case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; - const sizing = getSizing(issue2.origin); - const shortName = issue2.origin === "date" ? "vroeg" : issue2.origin === "string" ? "kort" : "klein"; - if (sizing) { - return `Te ${shortName}: verwacht dat ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} ${sizing.verb}`; - } - return `Te ${shortName}: verwacht dat ${issue2.origin} ${adj}${issue2.minimum.toString()} is`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") { - return `Ongeldige tekst: moet met "${_issue.prefix}" beginnen`; - } - if (_issue.format === "ends_with") - return `Ongeldige tekst: moet op "${_issue.suffix}" eindigen`; - if (_issue.format === "includes") - return `Ongeldige tekst: moet "${_issue.includes}" bevatten`; - if (_issue.format === "regex") - return `Ongeldige tekst: moet overeenkomen met patroon ${_issue.pattern}`; - return `Ongeldig: ${FormatDictionary[_issue.format] ?? issue2.format}`; - } - case "not_multiple_of": - return `Ongeldig getal: moet een veelvoud van ${issue2.divisor} zijn`; - case "unrecognized_keys": - return `Onbekende key${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return `Ongeldige key in ${issue2.origin}`; - case "invalid_union": - return "Ongeldige invoer"; - case "invalid_element": - return `Ongeldige waarde in ${issue2.origin}`; - default: - return `Ongeldige invoer`; - } - }; - }; - } -}); - -// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/no.js -function no_default() { - return { - localeError: error31() - }; -} -var error31; -var init_no = __esm({ - "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/no.js"() { - init_util(); - error31 = () => { - const Sizable = { - string: { unit: "tegn", verb: "\xE5 ha" }, - file: { unit: "bytes", verb: "\xE5 ha" }, - array: { unit: "elementer", verb: "\xE5 inneholde" }, - set: { unit: "elementer", verb: "\xE5 inneholde" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "input", - email: "e-postadresse", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO dato- og klokkeslett", - date: "ISO-dato", - time: "ISO-klokkeslett", - duration: "ISO-varighet", - ipv4: "IPv4-omr\xE5de", - ipv6: "IPv6-omr\xE5de", - cidrv4: "IPv4-spekter", - cidrv6: "IPv6-spekter", - base64: "base64-enkodet streng", - base64url: "base64url-enkodet streng", - json_string: "JSON-streng", - e164: "E.164-nummer", - jwt: "JWT", - template_literal: "input" - }; - const TypeDictionary = { - nan: "NaN", - number: "tall", - array: "liste" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `Ugyldig input: forventet instanceof ${issue2.expected}, fikk ${received}`; - } - return `Ugyldig input: forventet ${expected}, fikk ${received}`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `Ugyldig verdi: forventet ${stringifyPrimitive(issue2.values[0])}`; - return `Ugyldig valg: forventet en av ${joinValues(issue2.values, "|")}`; - case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; - const sizing = getSizing(issue2.origin); - if (sizing) - return `For stor(t): forventet ${issue2.origin ?? "value"} til \xE5 ha ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementer"}`; - return `For stor(t): forventet ${issue2.origin ?? "value"} til \xE5 ha ${adj}${issue2.maximum.toString()}`; - } - case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `For lite(n): forventet ${issue2.origin} til \xE5 ha ${adj}${issue2.minimum.toString()} ${sizing.unit}`; - } - return `For lite(n): forventet ${issue2.origin} til \xE5 ha ${adj}${issue2.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") - return `Ugyldig streng: m\xE5 starte med "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `Ugyldig streng: m\xE5 ende med "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Ugyldig streng: m\xE5 inneholde "${_issue.includes}"`; - if (_issue.format === "regex") - return `Ugyldig streng: m\xE5 matche m\xF8nsteret ${_issue.pattern}`; - return `Ugyldig ${FormatDictionary[_issue.format] ?? issue2.format}`; - } - case "not_multiple_of": - return `Ugyldig tall: m\xE5 v\xE6re et multiplum av ${issue2.divisor}`; - case "unrecognized_keys": - return `${issue2.keys.length > 1 ? "Ukjente n\xF8kler" : "Ukjent n\xF8kkel"}: ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return `Ugyldig n\xF8kkel i ${issue2.origin}`; - case "invalid_union": - return "Ugyldig input"; - case "invalid_element": - return `Ugyldig verdi i ${issue2.origin}`; - default: - return `Ugyldig input`; - } - }; - }; - } -}); - -// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ota.js -function ota_default() { - return { - localeError: error32() - }; -} -var error32; -var init_ota = __esm({ - "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ota.js"() { - init_util(); - error32 = () => { - const Sizable = { - string: { unit: "harf", verb: "olmal\u0131d\u0131r" }, - file: { unit: "bayt", verb: "olmal\u0131d\u0131r" }, - array: { unit: "unsur", verb: "olmal\u0131d\u0131r" }, - set: { unit: "unsur", verb: "olmal\u0131d\u0131r" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "giren", - email: "epostag\xE2h", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO heng\xE2m\u0131", - date: "ISO tarihi", - time: "ISO zaman\u0131", - duration: "ISO m\xFCddeti", - ipv4: "IPv4 ni\u015F\xE2n\u0131", - ipv6: "IPv6 ni\u015F\xE2n\u0131", - cidrv4: "IPv4 menzili", - cidrv6: "IPv6 menzili", - base64: "base64-\u015Fifreli metin", - base64url: "base64url-\u015Fifreli metin", - json_string: "JSON metin", - e164: "E.164 say\u0131s\u0131", - jwt: "JWT", - template_literal: "giren" - }; - const TypeDictionary = { - nan: "NaN", - number: "numara", - array: "saf", - null: "gayb" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `F\xE2sit giren: umulan instanceof ${issue2.expected}, al\u0131nan ${received}`; - } - return `F\xE2sit giren: umulan ${expected}, al\u0131nan ${received}`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `F\xE2sit giren: umulan ${stringifyPrimitive(issue2.values[0])}`; - return `F\xE2sit tercih: m\xFBteberler ${joinValues(issue2.values, "|")}`; - case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; - const sizing = getSizing(issue2.origin); - if (sizing) - return `Fazla b\xFCy\xFCk: ${issue2.origin ?? "value"}, ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elements"} sahip olmal\u0131yd\u0131.`; - return `Fazla b\xFCy\xFCk: ${issue2.origin ?? "value"}, ${adj}${issue2.maximum.toString()} olmal\u0131yd\u0131.`; - } - case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `Fazla k\xFC\xE7\xFCk: ${issue2.origin}, ${adj}${issue2.minimum.toString()} ${sizing.unit} sahip olmal\u0131yd\u0131.`; - } - return `Fazla k\xFC\xE7\xFCk: ${issue2.origin}, ${adj}${issue2.minimum.toString()} olmal\u0131yd\u0131.`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") - return `F\xE2sit metin: "${_issue.prefix}" ile ba\u015Flamal\u0131.`; - if (_issue.format === "ends_with") - return `F\xE2sit metin: "${_issue.suffix}" ile bitmeli.`; - if (_issue.format === "includes") - return `F\xE2sit metin: "${_issue.includes}" ihtiv\xE2 etmeli.`; - if (_issue.format === "regex") - return `F\xE2sit metin: ${_issue.pattern} nak\u015F\u0131na uymal\u0131.`; - return `F\xE2sit ${FormatDictionary[_issue.format] ?? issue2.format}`; - } - case "not_multiple_of": - return `F\xE2sit say\u0131: ${issue2.divisor} kat\u0131 olmal\u0131yd\u0131.`; - case "unrecognized_keys": - return `Tan\u0131nmayan anahtar ${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return `${issue2.origin} i\xE7in tan\u0131nmayan anahtar var.`; - case "invalid_union": - return "Giren tan\u0131namad\u0131."; - case "invalid_element": - return `${issue2.origin} i\xE7in tan\u0131nmayan k\u0131ymet var.`; - default: - return `K\u0131ymet tan\u0131namad\u0131.`; - } - }; - }; - } -}); - -// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ps.js -function ps_default() { - return { - localeError: error33() - }; -} -var error33; -var init_ps = __esm({ - "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ps.js"() { - init_util(); - error33 = () => { - const Sizable = { - string: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" }, - file: { unit: "\u0628\u0627\u06CC\u067C\u0633", verb: "\u0648\u0644\u0631\u064A" }, - array: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" }, - set: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "\u0648\u0631\u0648\u062F\u064A", - email: "\u0628\u0631\u06CC\u069A\u0646\u0627\u0644\u06CC\u06A9", - url: "\u06CC\u0648 \u0622\u0631 \u0627\u0644", - emoji: "\u0627\u06CC\u0645\u0648\u062C\u064A", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "\u0646\u06CC\u067C\u0647 \u0627\u0648 \u0648\u062E\u062A", - date: "\u0646\u06D0\u067C\u0647", - time: "\u0648\u062E\u062A", - duration: "\u0645\u0648\u062F\u0647", - ipv4: "\u062F IPv4 \u067E\u062A\u0647", - ipv6: "\u062F IPv6 \u067E\u062A\u0647", - cidrv4: "\u062F IPv4 \u0633\u0627\u062D\u0647", - cidrv6: "\u062F IPv6 \u0633\u0627\u062D\u0647", - base64: "base64-encoded \u0645\u062A\u0646", - base64url: "base64url-encoded \u0645\u062A\u0646", - json_string: "JSON \u0645\u062A\u0646", - e164: "\u062F E.164 \u0634\u0645\u06D0\u0631\u0647", - jwt: "JWT", - template_literal: "\u0648\u0631\u0648\u062F\u064A" - }; - const TypeDictionary = { - nan: "NaN", - number: "\u0639\u062F\u062F", - array: "\u0627\u0631\u06D0" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F instanceof ${issue2.expected} \u0648\u0627\u06CC, \u0645\u06AB\u0631 ${received} \u062A\u0631\u0644\u0627\u0633\u0647 \u0634\u0648`; - } - return `\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${expected} \u0648\u0627\u06CC, \u0645\u06AB\u0631 ${received} \u062A\u0631\u0644\u0627\u0633\u0647 \u0634\u0648`; - } - case "invalid_value": - if (issue2.values.length === 1) { - return `\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${stringifyPrimitive(issue2.values[0])} \u0648\u0627\u06CC`; - } - return `\u0646\u0627\u0633\u0645 \u0627\u0646\u062A\u062E\u0627\u0628: \u0628\u0627\u06CC\u062F \u06CC\u0648 \u0644\u0647 ${joinValues(issue2.values, "|")} \u0685\u062E\u0647 \u0648\u0627\u06CC`; - case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${issue2.origin ?? "\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0639\u0646\u0635\u0631\u0648\u0646\u0647"} \u0648\u0644\u0631\u064A`; - } - return `\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${issue2.origin ?? "\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${adj}${issue2.maximum.toString()} \u0648\u064A`; - } - case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${issue2.origin} \u0628\u0627\u06CC\u062F ${adj}${issue2.minimum.toString()} ${sizing.unit} \u0648\u0644\u0631\u064A`; - } - return `\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${issue2.origin} \u0628\u0627\u06CC\u062F ${adj}${issue2.minimum.toString()} \u0648\u064A`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") { - return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${_issue.prefix}" \u0633\u0631\u0647 \u067E\u06CC\u0644 \u0634\u064A`; - } - if (_issue.format === "ends_with") { - return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${_issue.suffix}" \u0633\u0631\u0647 \u067E\u0627\u06CC \u062A\u0647 \u0648\u0631\u0633\u064A\u0696\u064A`; - } - if (_issue.format === "includes") { - return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F "${_issue.includes}" \u0648\u0644\u0631\u064A`; - } - if (_issue.format === "regex") { - return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F ${_issue.pattern} \u0633\u0631\u0647 \u0645\u0637\u0627\u0628\u0642\u062A \u0648\u0644\u0631\u064A`; - } - return `${FormatDictionary[_issue.format] ?? issue2.format} \u0646\u0627\u0633\u0645 \u062F\u06CC`; - } - case "not_multiple_of": - return `\u0646\u0627\u0633\u0645 \u0639\u062F\u062F: \u0628\u0627\u06CC\u062F \u062F ${issue2.divisor} \u0645\u0636\u0631\u0628 \u0648\u064A`; - case "unrecognized_keys": - return `\u0646\u0627\u0633\u0645 ${issue2.keys.length > 1 ? "\u06A9\u0644\u06CC\u0689\u0648\u0646\u0647" : "\u06A9\u0644\u06CC\u0689"}: ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return `\u0646\u0627\u0633\u0645 \u06A9\u0644\u06CC\u0689 \u067E\u0647 ${issue2.origin} \u06A9\u06D0`; - case "invalid_union": - return `\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A`; - case "invalid_element": - return `\u0646\u0627\u0633\u0645 \u0639\u0646\u0635\u0631 \u067E\u0647 ${issue2.origin} \u06A9\u06D0`; - default: - return `\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A`; - } - }; - }; - } -}); - -// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/pl.js -function pl_default() { - return { - localeError: error34() - }; -} -var error34; -var init_pl = __esm({ - "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/pl.js"() { - init_util(); - error34 = () => { - const Sizable = { - string: { unit: "znak\xF3w", verb: "mie\u0107" }, - file: { unit: "bajt\xF3w", verb: "mie\u0107" }, - array: { unit: "element\xF3w", verb: "mie\u0107" }, - set: { unit: "element\xF3w", verb: "mie\u0107" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "wyra\u017Cenie", - email: "adres email", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "data i godzina w formacie ISO", - date: "data w formacie ISO", - time: "godzina w formacie ISO", - duration: "czas trwania ISO", - ipv4: "adres IPv4", - ipv6: "adres IPv6", - cidrv4: "zakres IPv4", - cidrv6: "zakres IPv6", - base64: "ci\u0105g znak\xF3w zakodowany w formacie base64", - base64url: "ci\u0105g znak\xF3w zakodowany w formacie base64url", - json_string: "ci\u0105g znak\xF3w w formacie JSON", - e164: "liczba E.164", - jwt: "JWT", - template_literal: "wej\u015Bcie" - }; - const TypeDictionary = { - nan: "NaN", - number: "liczba", - array: "tablica" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano instanceof ${issue2.expected}, otrzymano ${received}`; - } - return `Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${expected}, otrzymano ${received}`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${stringifyPrimitive(issue2.values[0])}`; - return `Nieprawid\u0142owa opcja: oczekiwano jednej z warto\u015Bci ${joinValues(issue2.values, "|")}`; - case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `Za du\u017Ca warto\u015B\u0107: oczekiwano, \u017Ce ${issue2.origin ?? "warto\u015B\u0107"} b\u0119dzie mie\u0107 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "element\xF3w"}`; - } - return `Zbyt du\u017C(y/a/e): oczekiwano, \u017Ce ${issue2.origin ?? "warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${adj}${issue2.maximum.toString()}`; - } - case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `Za ma\u0142a warto\u015B\u0107: oczekiwano, \u017Ce ${issue2.origin ?? "warto\u015B\u0107"} b\u0119dzie mie\u0107 ${adj}${issue2.minimum.toString()} ${sizing.unit ?? "element\xF3w"}`; - } - return `Zbyt ma\u0142(y/a/e): oczekiwano, \u017Ce ${issue2.origin ?? "warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${adj}${issue2.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") - return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zaczyna\u0107 si\u0119 od "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi ko\u0144czy\u0107 si\u0119 na "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zawiera\u0107 "${_issue.includes}"`; - if (_issue.format === "regex") - return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi odpowiada\u0107 wzorcowi ${_issue.pattern}`; - return `Nieprawid\u0142ow(y/a/e) ${FormatDictionary[_issue.format] ?? issue2.format}`; - } - case "not_multiple_of": - return `Nieprawid\u0142owa liczba: musi by\u0107 wielokrotno\u015Bci\u0105 ${issue2.divisor}`; - case "unrecognized_keys": - return `Nierozpoznane klucze${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return `Nieprawid\u0142owy klucz w ${issue2.origin}`; - case "invalid_union": - return "Nieprawid\u0142owe dane wej\u015Bciowe"; - case "invalid_element": - return `Nieprawid\u0142owa warto\u015B\u0107 w ${issue2.origin}`; - default: - return `Nieprawid\u0142owe dane wej\u015Bciowe`; - } - }; - }; - } -}); - -// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/pt.js -function pt_default() { - return { - localeError: error35() - }; -} -var error35; -var init_pt = __esm({ - "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/pt.js"() { - init_util(); - error35 = () => { - const Sizable = { - string: { unit: "caracteres", verb: "ter" }, - file: { unit: "bytes", verb: "ter" }, - array: { unit: "itens", verb: "ter" }, - set: { unit: "itens", verb: "ter" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "padr\xE3o", - email: "endere\xE7o de e-mail", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "data e hora ISO", - date: "data ISO", - time: "hora ISO", - duration: "dura\xE7\xE3o ISO", - ipv4: "endere\xE7o IPv4", - ipv6: "endere\xE7o IPv6", - cidrv4: "faixa de IPv4", - cidrv6: "faixa de IPv6", - base64: "texto codificado em base64", - base64url: "URL codificada em base64", - json_string: "texto JSON", - e164: "n\xFAmero E.164", - jwt: "JWT", - template_literal: "entrada" - }; - const TypeDictionary = { - nan: "NaN", - number: "n\xFAmero", - null: "nulo" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `Tipo inv\xE1lido: esperado instanceof ${issue2.expected}, recebido ${received}`; - } - return `Tipo inv\xE1lido: esperado ${expected}, recebido ${received}`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `Entrada inv\xE1lida: esperado ${stringifyPrimitive(issue2.values[0])}`; - return `Op\xE7\xE3o inv\xE1lida: esperada uma das ${joinValues(issue2.values, "|")}`; - case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; - const sizing = getSizing(issue2.origin); - if (sizing) - return `Muito grande: esperado que ${issue2.origin ?? "valor"} tivesse ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementos"}`; - return `Muito grande: esperado que ${issue2.origin ?? "valor"} fosse ${adj}${issue2.maximum.toString()}`; - } - case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `Muito pequeno: esperado que ${issue2.origin} tivesse ${adj}${issue2.minimum.toString()} ${sizing.unit}`; - } - return `Muito pequeno: esperado que ${issue2.origin} fosse ${adj}${issue2.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") - return `Texto inv\xE1lido: deve come\xE7ar com "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `Texto inv\xE1lido: deve terminar com "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Texto inv\xE1lido: deve incluir "${_issue.includes}"`; - if (_issue.format === "regex") - return `Texto inv\xE1lido: deve corresponder ao padr\xE3o ${_issue.pattern}`; - return `${FormatDictionary[_issue.format] ?? issue2.format} inv\xE1lido`; - } - case "not_multiple_of": - return `N\xFAmero inv\xE1lido: deve ser m\xFAltiplo de ${issue2.divisor}`; - case "unrecognized_keys": - return `Chave${issue2.keys.length > 1 ? "s" : ""} desconhecida${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return `Chave inv\xE1lida em ${issue2.origin}`; - case "invalid_union": - return "Entrada inv\xE1lida"; - case "invalid_element": - return `Valor inv\xE1lido em ${issue2.origin}`; - default: - return `Campo inv\xE1lido`; - } - }; - }; - } -}); - -// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ru.js -function getRussianPlural(count2, one, few, many) { - const absCount = Math.abs(count2); - const lastDigit = absCount % 10; - const lastTwoDigits = absCount % 100; - if (lastTwoDigits >= 11 && lastTwoDigits <= 19) { - return many; - } - if (lastDigit === 1) { - return one; - } - if (lastDigit >= 2 && lastDigit <= 4) { - return few; - } - return many; -} -function ru_default() { - return { - localeError: error36() - }; -} -var error36; -var init_ru = __esm({ - "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ru.js"() { - init_util(); - error36 = () => { - const Sizable = { - string: { - unit: { - one: "\u0441\u0438\u043C\u0432\u043E\u043B", - few: "\u0441\u0438\u043C\u0432\u043E\u043B\u0430", - many: "\u0441\u0438\u043C\u0432\u043E\u043B\u043E\u0432" - }, - verb: "\u0438\u043C\u0435\u0442\u044C" - }, - file: { - unit: { - one: "\u0431\u0430\u0439\u0442", - few: "\u0431\u0430\u0439\u0442\u0430", - many: "\u0431\u0430\u0439\u0442" - }, - verb: "\u0438\u043C\u0435\u0442\u044C" - }, - array: { - unit: { - one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442", - few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430", - many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432" - }, - verb: "\u0438\u043C\u0435\u0442\u044C" - }, - set: { - unit: { - one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442", - few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430", - many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432" - }, - verb: "\u0438\u043C\u0435\u0442\u044C" - } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "\u0432\u0432\u043E\u0434", - email: "email \u0430\u0434\u0440\u0435\u0441", - url: "URL", - emoji: "\u044D\u043C\u043E\u0434\u0437\u0438", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO \u0434\u0430\u0442\u0430 \u0438 \u0432\u0440\u0435\u043C\u044F", - date: "ISO \u0434\u0430\u0442\u0430", - time: "ISO \u0432\u0440\u0435\u043C\u044F", - duration: "ISO \u0434\u043B\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u044C", - ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441", - ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441", - cidrv4: "IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", - cidrv6: "IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", - base64: "\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64", - base64url: "\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64url", - json_string: "JSON \u0441\u0442\u0440\u043E\u043A\u0430", - e164: "\u043D\u043E\u043C\u0435\u0440 E.164", - jwt: "JWT", - template_literal: "\u0432\u0432\u043E\u0434" - }; - const TypeDictionary = { - nan: "NaN", - number: "\u0447\u0438\u0441\u043B\u043E", - array: "\u043C\u0430\u0441\u0441\u0438\u0432" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C instanceof ${issue2.expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u043E ${received}`; - } - return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u043E ${received}`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${stringifyPrimitive(issue2.values[0])}`; - return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0430\u0440\u0438\u0430\u043D\u0442: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C \u043E\u0434\u043D\u043E \u0438\u0437 ${joinValues(issue2.values, "|")}`; - case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; - const sizing = getSizing(issue2.origin); - if (sizing) { - const maxValue = Number(issue2.maximum); - const unit = getRussianPlural(maxValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); - return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${adj}${issue2.maximum.toString()} ${unit}`; - } - return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 ${adj}${issue2.maximum.toString()}`; - } - case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; - const sizing = getSizing(issue2.origin); - if (sizing) { - const minValue = Number(issue2.minimum); - const unit = getRussianPlural(minValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); - return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue2.origin} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${adj}${issue2.minimum.toString()} ${unit}`; - } - return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue2.origin} \u0431\u0443\u0434\u0435\u0442 ${adj}${issue2.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") - return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u043D\u0430\u0447\u0438\u043D\u0430\u0442\u044C\u0441\u044F \u0441 "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0437\u0430\u043A\u0430\u043D\u0447\u0438\u0432\u0430\u0442\u044C\u0441\u044F \u043D\u0430 "${_issue.suffix}"`; - if (_issue.format === "includes") - return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u0434\u0435\u0440\u0436\u0430\u0442\u044C "${_issue.includes}"`; - if (_issue.format === "regex") - return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u043E\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u043E\u0432\u0430\u0442\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${_issue.pattern}`; - return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 ${FormatDictionary[_issue.format] ?? issue2.format}`; - } - case "not_multiple_of": - return `\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0447\u0438\u0441\u043B\u043E: \u0434\u043E\u043B\u0436\u043D\u043E \u0431\u044B\u0442\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${issue2.divisor}`; - case "unrecognized_keys": - return `\u041D\u0435\u0440\u0430\u0441\u043F\u043E\u0437\u043D\u0430\u043D\u043D${issue2.keys.length > 1 ? "\u044B\u0435" : "\u044B\u0439"} \u043A\u043B\u044E\u0447${issue2.keys.length > 1 ? "\u0438" : ""}: ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u043A\u043B\u044E\u0447 \u0432 ${issue2.origin}`; - case "invalid_union": - return "\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435"; - case "invalid_element": - return `\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u0432 ${issue2.origin}`; - default: - return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435`; - } - }; - }; - } -}); - -// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/sl.js -function sl_default() { - return { - localeError: error37() - }; -} -var error37; -var init_sl = __esm({ - "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/sl.js"() { - init_util(); - error37 = () => { - const Sizable = { - string: { unit: "znakov", verb: "imeti" }, - file: { unit: "bajtov", verb: "imeti" }, - array: { unit: "elementov", verb: "imeti" }, - set: { unit: "elementov", verb: "imeti" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "vnos", - email: "e-po\u0161tni naslov", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO datum in \u010Das", - date: "ISO datum", - time: "ISO \u010Das", - duration: "ISO trajanje", - ipv4: "IPv4 naslov", - ipv6: "IPv6 naslov", - cidrv4: "obseg IPv4", - cidrv6: "obseg IPv6", - base64: "base64 kodiran niz", - base64url: "base64url kodiran niz", - json_string: "JSON niz", - e164: "E.164 \u0161tevilka", - jwt: "JWT", - template_literal: "vnos" - }; - const TypeDictionary = { - nan: "NaN", - number: "\u0161tevilo", - array: "tabela" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `Neveljaven vnos: pri\u010Dakovano instanceof ${issue2.expected}, prejeto ${received}`; - } - return `Neveljaven vnos: pri\u010Dakovano ${expected}, prejeto ${received}`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `Neveljaven vnos: pri\u010Dakovano ${stringifyPrimitive(issue2.values[0])}`; - return `Neveljavna mo\u017Enost: pri\u010Dakovano eno izmed ${joinValues(issue2.values, "|")}`; - case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; - const sizing = getSizing(issue2.origin); - if (sizing) - return `Preveliko: pri\u010Dakovano, da bo ${issue2.origin ?? "vrednost"} imelo ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementov"}`; - return `Preveliko: pri\u010Dakovano, da bo ${issue2.origin ?? "vrednost"} ${adj}${issue2.maximum.toString()}`; - } - case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `Premajhno: pri\u010Dakovano, da bo ${issue2.origin} imelo ${adj}${issue2.minimum.toString()} ${sizing.unit}`; - } - return `Premajhno: pri\u010Dakovano, da bo ${issue2.origin} ${adj}${issue2.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") { - return `Neveljaven niz: mora se za\u010Deti z "${_issue.prefix}"`; - } - if (_issue.format === "ends_with") - return `Neveljaven niz: mora se kon\u010Dati z "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Neveljaven niz: mora vsebovati "${_issue.includes}"`; - if (_issue.format === "regex") - return `Neveljaven niz: mora ustrezati vzorcu ${_issue.pattern}`; - return `Neveljaven ${FormatDictionary[_issue.format] ?? issue2.format}`; - } - case "not_multiple_of": - return `Neveljavno \u0161tevilo: mora biti ve\u010Dkratnik ${issue2.divisor}`; - case "unrecognized_keys": - return `Neprepoznan${issue2.keys.length > 1 ? "i klju\u010Di" : " klju\u010D"}: ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return `Neveljaven klju\u010D v ${issue2.origin}`; - case "invalid_union": - return "Neveljaven vnos"; - case "invalid_element": - return `Neveljavna vrednost v ${issue2.origin}`; - default: - return "Neveljaven vnos"; - } - }; - }; - } -}); - -// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/sv.js -function sv_default() { - return { - localeError: error38() - }; -} -var error38; -var init_sv = __esm({ - "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/sv.js"() { - init_util(); - error38 = () => { - const Sizable = { - string: { unit: "tecken", verb: "att ha" }, - file: { unit: "bytes", verb: "att ha" }, - array: { unit: "objekt", verb: "att inneh\xE5lla" }, - set: { unit: "objekt", verb: "att inneh\xE5lla" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "regulj\xE4rt uttryck", - email: "e-postadress", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO-datum och tid", - date: "ISO-datum", - time: "ISO-tid", - duration: "ISO-varaktighet", - ipv4: "IPv4-intervall", - ipv6: "IPv6-intervall", - cidrv4: "IPv4-spektrum", - cidrv6: "IPv6-spektrum", - base64: "base64-kodad str\xE4ng", - base64url: "base64url-kodad str\xE4ng", - json_string: "JSON-str\xE4ng", - e164: "E.164-nummer", - jwt: "JWT", - template_literal: "mall-literal" - }; - const TypeDictionary = { - nan: "NaN", - number: "antal", - array: "lista" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `Ogiltig inmatning: f\xF6rv\xE4ntat instanceof ${issue2.expected}, fick ${received}`; - } - return `Ogiltig inmatning: f\xF6rv\xE4ntat ${expected}, fick ${received}`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `Ogiltig inmatning: f\xF6rv\xE4ntat ${stringifyPrimitive(issue2.values[0])}`; - return `Ogiltigt val: f\xF6rv\xE4ntade en av ${joinValues(issue2.values, "|")}`; - case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `F\xF6r stor(t): f\xF6rv\xE4ntade ${issue2.origin ?? "v\xE4rdet"} att ha ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "element"}`; - } - return `F\xF6r stor(t): f\xF6rv\xE4ntat ${issue2.origin ?? "v\xE4rdet"} att ha ${adj}${issue2.maximum.toString()}`; - } - case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `F\xF6r lite(t): f\xF6rv\xE4ntade ${issue2.origin ?? "v\xE4rdet"} att ha ${adj}${issue2.minimum.toString()} ${sizing.unit}`; - } - return `F\xF6r lite(t): f\xF6rv\xE4ntade ${issue2.origin ?? "v\xE4rdet"} att ha ${adj}${issue2.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") { - return `Ogiltig str\xE4ng: m\xE5ste b\xF6rja med "${_issue.prefix}"`; - } - if (_issue.format === "ends_with") - return `Ogiltig str\xE4ng: m\xE5ste sluta med "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Ogiltig str\xE4ng: m\xE5ste inneh\xE5lla "${_issue.includes}"`; - if (_issue.format === "regex") - return `Ogiltig str\xE4ng: m\xE5ste matcha m\xF6nstret "${_issue.pattern}"`; - return `Ogiltig(t) ${FormatDictionary[_issue.format] ?? issue2.format}`; - } - case "not_multiple_of": - return `Ogiltigt tal: m\xE5ste vara en multipel av ${issue2.divisor}`; - case "unrecognized_keys": - return `${issue2.keys.length > 1 ? "Ok\xE4nda nycklar" : "Ok\xE4nd nyckel"}: ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return `Ogiltig nyckel i ${issue2.origin ?? "v\xE4rdet"}`; - case "invalid_union": - return "Ogiltig input"; - case "invalid_element": - return `Ogiltigt v\xE4rde i ${issue2.origin ?? "v\xE4rdet"}`; - default: - return `Ogiltig input`; - } - }; - }; - } -}); - -// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ta.js -function ta_default() { - return { - localeError: error39() - }; -} -var error39; -var init_ta = __esm({ - "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ta.js"() { - init_util(); - error39 = () => { - const Sizable = { - string: { unit: "\u0B8E\u0BB4\u0BC1\u0BA4\u0BCD\u0BA4\u0BC1\u0B95\u0BCD\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, - file: { unit: "\u0BAA\u0BC8\u0B9F\u0BCD\u0B9F\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, - array: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, - set: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "\u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1", - email: "\u0BAE\u0BBF\u0BA9\u0BCD\u0BA9\u0B9E\u0BCD\u0B9A\u0BB2\u0BCD \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO \u0BA4\u0BC7\u0BA4\u0BBF \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD", - date: "ISO \u0BA4\u0BC7\u0BA4\u0BBF", - time: "ISO \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD", - duration: "ISO \u0B95\u0BBE\u0BB2 \u0B85\u0BB3\u0BB5\u0BC1", - ipv4: "IPv4 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF", - ipv6: "IPv6 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF", - cidrv4: "IPv4 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1", - cidrv6: "IPv6 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1", - base64: "base64-encoded \u0B9A\u0BB0\u0BAE\u0BCD", - base64url: "base64url-encoded \u0B9A\u0BB0\u0BAE\u0BCD", - json_string: "JSON \u0B9A\u0BB0\u0BAE\u0BCD", - e164: "E.164 \u0B8E\u0BA3\u0BCD", - jwt: "JWT", - template_literal: "input" - }; - const TypeDictionary = { - nan: "NaN", - number: "\u0B8E\u0BA3\u0BCD", - array: "\u0B85\u0BA3\u0BBF", - null: "\u0BB5\u0BC6\u0BB1\u0BC1\u0BAE\u0BC8" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 instanceof ${issue2.expected}, \u0BAA\u0BC6\u0BB1\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${received}`; - } - return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${expected}, \u0BAA\u0BC6\u0BB1\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${received}`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${stringifyPrimitive(issue2.values[0])}`; - return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0BB0\u0BC1\u0BAA\u0BCD\u0BAA\u0BAE\u0BCD: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${joinValues(issue2.values, "|")} \u0B87\u0BB2\u0BCD \u0B92\u0BA9\u0BCD\u0BB1\u0BC1`; - case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.origin ?? "\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD"} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; - } - return `\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.origin ?? "\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${adj}${issue2.maximum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; - } - case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; - } - return `\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.origin} ${adj}${issue2.minimum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") - return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${_issue.prefix}" \u0B87\u0BB2\u0BCD \u0BA4\u0BCA\u0B9F\u0B99\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; - if (_issue.format === "ends_with") - return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${_issue.suffix}" \u0B87\u0BB2\u0BCD \u0BAE\u0BC1\u0B9F\u0BBF\u0BB5\u0B9F\u0BC8\u0BAF \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; - if (_issue.format === "includes") - return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${_issue.includes}" \u0B90 \u0B89\u0BB3\u0BCD\u0BB3\u0B9F\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; - if (_issue.format === "regex") - return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: ${_issue.pattern} \u0BAE\u0BC1\u0BB1\u0BC8\u0BAA\u0BBE\u0B9F\u0BCD\u0B9F\u0BC1\u0B9F\u0BA9\u0BCD \u0BAA\u0BCA\u0BB0\u0BC1\u0BA8\u0BCD\u0BA4 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; - return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 ${FormatDictionary[_issue.format] ?? issue2.format}`; - } - case "not_multiple_of": - return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B8E\u0BA3\u0BCD: ${issue2.divisor} \u0B87\u0BA9\u0BCD \u0BAA\u0BB2\u0BAE\u0BBE\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; - case "unrecognized_keys": - return `\u0B85\u0B9F\u0BC8\u0BAF\u0BBE\u0BB3\u0BAE\u0BCD \u0BA4\u0BC6\u0BB0\u0BBF\u0BAF\u0BBE\u0BA4 \u0BB5\u0BBF\u0B9A\u0BC8${issue2.keys.length > 1 ? "\u0B95\u0BB3\u0BCD" : ""}: ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return `${issue2.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0B9A\u0BC8`; - case "invalid_union": - return "\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1"; - case "invalid_element": - return `${issue2.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1`; - default: - return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1`; - } - }; - }; - } -}); - -// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/th.js -function th_default() { - return { - localeError: error40() - }; -} -var error40; -var init_th = __esm({ - "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/th.js"() { - init_util(); - error40 = () => { - const Sizable = { - string: { unit: "\u0E15\u0E31\u0E27\u0E2D\u0E31\u0E01\u0E29\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, - file: { unit: "\u0E44\u0E1A\u0E15\u0E4C", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, - array: { unit: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, - set: { unit: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19", - email: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48\u0E2D\u0E35\u0E40\u0E21\u0E25", - url: "URL", - emoji: "\u0E2D\u0E34\u0E42\u0E21\u0E08\u0E34", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO", - date: "\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E41\u0E1A\u0E1A ISO", - time: "\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO", - duration: "\u0E0A\u0E48\u0E27\u0E07\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO", - ipv4: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv4", - ipv6: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv6", - cidrv4: "\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv4", - cidrv6: "\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv6", - base64: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64", - base64url: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64 \u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A URL", - json_string: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A JSON", - e164: "\u0E40\u0E1A\u0E2D\u0E23\u0E4C\u0E42\u0E17\u0E23\u0E28\u0E31\u0E1E\u0E17\u0E4C\u0E23\u0E30\u0E2B\u0E27\u0E48\u0E32\u0E07\u0E1B\u0E23\u0E30\u0E40\u0E17\u0E28 (E.164)", - jwt: "\u0E42\u0E17\u0E40\u0E04\u0E19 JWT", - template_literal: "\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19" - }; - const TypeDictionary = { - nan: "NaN", - number: "\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02", - array: "\u0E2D\u0E32\u0E23\u0E4C\u0E40\u0E23\u0E22\u0E4C (Array)", - null: "\u0E44\u0E21\u0E48\u0E21\u0E35\u0E04\u0E48\u0E32 (null)" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `\u0E1B\u0E23\u0E30\u0E40\u0E20\u0E17\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 instanceof ${issue2.expected} \u0E41\u0E15\u0E48\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A ${received}`; - } - return `\u0E1B\u0E23\u0E30\u0E40\u0E20\u0E17\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${expected} \u0E41\u0E15\u0E48\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A ${received}`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `\u0E04\u0E48\u0E32\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${stringifyPrimitive(issue2.values[0])}`; - return `\u0E15\u0E31\u0E27\u0E40\u0E25\u0E37\u0E2D\u0E01\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19\u0E2B\u0E19\u0E36\u0E48\u0E07\u0E43\u0E19 ${joinValues(issue2.values, "|")}`; - case "too_big": { - const adj = issue2.inclusive ? "\u0E44\u0E21\u0E48\u0E40\u0E01\u0E34\u0E19" : "\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32"; - const sizing = getSizing(issue2.origin); - if (sizing) - return `\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue2.origin ?? "\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23"}`; - return `\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue2.origin ?? "\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue2.maximum.toString()}`; - } - case "too_small": { - const adj = issue2.inclusive ? "\u0E2D\u0E22\u0E48\u0E32\u0E07\u0E19\u0E49\u0E2D\u0E22" : "\u0E21\u0E32\u0E01\u0E01\u0E27\u0E48\u0E32"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue2.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue2.minimum.toString()} ${sizing.unit}`; - } - return `\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue2.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue2.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") { - return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E02\u0E36\u0E49\u0E19\u0E15\u0E49\u0E19\u0E14\u0E49\u0E27\u0E22 "${_issue.prefix}"`; - } - if (_issue.format === "ends_with") - return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E25\u0E07\u0E17\u0E49\u0E32\u0E22\u0E14\u0E49\u0E27\u0E22 "${_issue.suffix}"`; - if (_issue.format === "includes") - return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E21\u0E35 "${_issue.includes}" \u0E2D\u0E22\u0E39\u0E48\u0E43\u0E19\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21`; - if (_issue.format === "regex") - return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14 ${_issue.pattern}`; - return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: ${FormatDictionary[_issue.format] ?? issue2.format}`; - } - case "not_multiple_of": - return `\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E40\u0E1B\u0E47\u0E19\u0E08\u0E33\u0E19\u0E27\u0E19\u0E17\u0E35\u0E48\u0E2B\u0E32\u0E23\u0E14\u0E49\u0E27\u0E22 ${issue2.divisor} \u0E44\u0E14\u0E49\u0E25\u0E07\u0E15\u0E31\u0E27`; - case "unrecognized_keys": - return `\u0E1E\u0E1A\u0E04\u0E35\u0E22\u0E4C\u0E17\u0E35\u0E48\u0E44\u0E21\u0E48\u0E23\u0E39\u0E49\u0E08\u0E31\u0E01: ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return `\u0E04\u0E35\u0E22\u0E4C\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${issue2.origin}`; - case "invalid_union": - return "\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E44\u0E21\u0E48\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E22\u0E39\u0E40\u0E19\u0E35\u0E22\u0E19\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14\u0E44\u0E27\u0E49"; - case "invalid_element": - return `\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${issue2.origin}`; - default: - return `\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07`; - } - }; - }; - } -}); - -// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/tr.js -function tr_default() { - return { - localeError: error41() - }; -} -var error41; -var init_tr = __esm({ - "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/tr.js"() { - init_util(); - error41 = () => { - const Sizable = { - string: { unit: "karakter", verb: "olmal\u0131" }, - file: { unit: "bayt", verb: "olmal\u0131" }, - array: { unit: "\xF6\u011Fe", verb: "olmal\u0131" }, - set: { unit: "\xF6\u011Fe", verb: "olmal\u0131" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "girdi", - email: "e-posta adresi", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO tarih ve saat", - date: "ISO tarih", - time: "ISO saat", - duration: "ISO s\xFCre", - ipv4: "IPv4 adresi", - ipv6: "IPv6 adresi", - cidrv4: "IPv4 aral\u0131\u011F\u0131", - cidrv6: "IPv6 aral\u0131\u011F\u0131", - base64: "base64 ile \u015Fifrelenmi\u015F metin", - base64url: "base64url ile \u015Fifrelenmi\u015F metin", - json_string: "JSON dizesi", - e164: "E.164 say\u0131s\u0131", - jwt: "JWT", - template_literal: "\u015Eablon dizesi" - }; - const TypeDictionary = { - nan: "NaN" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `Ge\xE7ersiz de\u011Fer: beklenen instanceof ${issue2.expected}, al\u0131nan ${received}`; - } - return `Ge\xE7ersiz de\u011Fer: beklenen ${expected}, al\u0131nan ${received}`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `Ge\xE7ersiz de\u011Fer: beklenen ${stringifyPrimitive(issue2.values[0])}`; - return `Ge\xE7ersiz se\xE7enek: a\u015Fa\u011F\u0131dakilerden biri olmal\u0131: ${joinValues(issue2.values, "|")}`; - case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; - const sizing = getSizing(issue2.origin); - if (sizing) - return `\xC7ok b\xFCy\xFCk: beklenen ${issue2.origin ?? "de\u011Fer"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\xF6\u011Fe"}`; - return `\xC7ok b\xFCy\xFCk: beklenen ${issue2.origin ?? "de\u011Fer"} ${adj}${issue2.maximum.toString()}`; - } - case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; - const sizing = getSizing(issue2.origin); - if (sizing) - return `\xC7ok k\xFC\xE7\xFCk: beklenen ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; - return `\xC7ok k\xFC\xE7\xFCk: beklenen ${issue2.origin} ${adj}${issue2.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") - return `Ge\xE7ersiz metin: "${_issue.prefix}" ile ba\u015Flamal\u0131`; - if (_issue.format === "ends_with") - return `Ge\xE7ersiz metin: "${_issue.suffix}" ile bitmeli`; - if (_issue.format === "includes") - return `Ge\xE7ersiz metin: "${_issue.includes}" i\xE7ermeli`; - if (_issue.format === "regex") - return `Ge\xE7ersiz metin: ${_issue.pattern} desenine uymal\u0131`; - return `Ge\xE7ersiz ${FormatDictionary[_issue.format] ?? issue2.format}`; - } - case "not_multiple_of": - return `Ge\xE7ersiz say\u0131: ${issue2.divisor} ile tam b\xF6l\xFCnebilmeli`; - case "unrecognized_keys": - return `Tan\u0131nmayan anahtar${issue2.keys.length > 1 ? "lar" : ""}: ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return `${issue2.origin} i\xE7inde ge\xE7ersiz anahtar`; - case "invalid_union": - return "Ge\xE7ersiz de\u011Fer"; - case "invalid_element": - return `${issue2.origin} i\xE7inde ge\xE7ersiz de\u011Fer`; - default: - return `Ge\xE7ersiz de\u011Fer`; - } - }; - }; - } -}); - -// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/uk.js -function uk_default() { - return { - localeError: error42() - }; -} -var error42; -var init_uk = __esm({ - "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/uk.js"() { - init_util(); - error42 = () => { - const Sizable = { - string: { unit: "\u0441\u0438\u043C\u0432\u043E\u043B\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, - file: { unit: "\u0431\u0430\u0439\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, - array: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, - set: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456", - email: "\u0430\u0434\u0440\u0435\u0441\u0430 \u0435\u043B\u0435\u043A\u0442\u0440\u043E\u043D\u043D\u043E\u0457 \u043F\u043E\u0448\u0442\u0438", - url: "URL", - emoji: "\u0435\u043C\u043E\u0434\u0437\u0456", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "\u0434\u0430\u0442\u0430 \u0442\u0430 \u0447\u0430\u0441 ISO", - date: "\u0434\u0430\u0442\u0430 ISO", - time: "\u0447\u0430\u0441 ISO", - duration: "\u0442\u0440\u0438\u0432\u0430\u043B\u0456\u0441\u0442\u044C ISO", - ipv4: "\u0430\u0434\u0440\u0435\u0441\u0430 IPv4", - ipv6: "\u0430\u0434\u0440\u0435\u0441\u0430 IPv6", - cidrv4: "\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv4", - cidrv6: "\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv6", - base64: "\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64", - base64url: "\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64url", - json_string: "\u0440\u044F\u0434\u043E\u043A JSON", - e164: "\u043D\u043E\u043C\u0435\u0440 E.164", - jwt: "JWT", - template_literal: "\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456" - }; - const TypeDictionary = { - nan: "NaN", - number: "\u0447\u0438\u0441\u043B\u043E", - array: "\u043C\u0430\u0441\u0438\u0432" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F instanceof ${issue2.expected}, \u043E\u0442\u0440\u0438\u043C\u0430\u043D\u043E ${received}`; - } - return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${expected}, \u043E\u0442\u0440\u0438\u043C\u0430\u043D\u043E ${received}`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${stringifyPrimitive(issue2.values[0])}`; - return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0430 \u043E\u043F\u0446\u0456\u044F: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F \u043E\u0434\u043D\u0435 \u0437 ${joinValues(issue2.values, "|")}`; - case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; - const sizing = getSizing(issue2.origin); - if (sizing) - return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432"}`; - return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} \u0431\u0443\u0434\u0435 ${adj}${issue2.maximum.toString()}`; - } - case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; - } - return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue2.origin} \u0431\u0443\u0434\u0435 ${adj}${issue2.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") - return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043F\u043E\u0447\u0438\u043D\u0430\u0442\u0438\u0441\u044F \u0437 "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0437\u0430\u043A\u0456\u043D\u0447\u0443\u0432\u0430\u0442\u0438\u0441\u044F \u043D\u0430 "${_issue.suffix}"`; - if (_issue.format === "includes") - return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043C\u0456\u0441\u0442\u0438\u0442\u0438 "${_issue.includes}"`; - if (_issue.format === "regex") - return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0432\u0456\u0434\u043F\u043E\u0432\u0456\u0434\u0430\u0442\u0438 \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${_issue.pattern}`; - return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 ${FormatDictionary[_issue.format] ?? issue2.format}`; - } - case "not_multiple_of": - return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0447\u0438\u0441\u043B\u043E: \u043F\u043E\u0432\u0438\u043D\u043D\u043E \u0431\u0443\u0442\u0438 \u043A\u0440\u0430\u0442\u043D\u0438\u043C ${issue2.divisor}`; - case "unrecognized_keys": - return `\u041D\u0435\u0440\u043E\u0437\u043F\u0456\u0437\u043D\u0430\u043D\u0438\u0439 \u043A\u043B\u044E\u0447${issue2.keys.length > 1 ? "\u0456" : ""}: ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u043A\u043B\u044E\u0447 \u0443 ${issue2.origin}`; - case "invalid_union": - return "\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456"; - case "invalid_element": - return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F \u0443 ${issue2.origin}`; - default: - return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456`; - } - }; - }; - } -}); - -// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ua.js -function ua_default() { - return uk_default(); -} -var init_ua = __esm({ - "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ua.js"() { - init_uk(); - } -}); - -// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ur.js -function ur_default() { - return { - localeError: error43() - }; -} -var error43; -var init_ur = __esm({ - "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ur.js"() { - init_util(); - error43 = () => { - const Sizable = { - string: { unit: "\u062D\u0631\u0648\u0641", verb: "\u06C1\u0648\u0646\u0627" }, - file: { unit: "\u0628\u0627\u0626\u0679\u0633", verb: "\u06C1\u0648\u0646\u0627" }, - array: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" }, - set: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "\u0627\u0646 \u067E\u0679", - email: "\u0627\u06CC \u0645\u06CC\u0644 \u0627\u06CC\u0688\u0631\u06CC\u0633", - url: "\u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644", - emoji: "\u0627\u06CC\u0645\u0648\u062C\u06CC", - uuid: "\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC", - uuidv4: "\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 4", - uuidv6: "\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 6", - nanoid: "\u0646\u06CC\u0646\u0648 \u0622\u0626\u06CC \u0688\u06CC", - guid: "\u062C\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC", - cuid: "\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC", - cuid2: "\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC 2", - ulid: "\u06CC\u0648 \u0627\u06CC\u0644 \u0622\u0626\u06CC \u0688\u06CC", - xid: "\u0627\u06CC\u06A9\u0633 \u0622\u0626\u06CC \u0688\u06CC", - ksuid: "\u06A9\u06D2 \u0627\u06CC\u0633 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC", - datetime: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0688\u06CC\u0679 \u0679\u0627\u0626\u0645", - date: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u062A\u0627\u0631\u06CC\u062E", - time: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0648\u0642\u062A", - duration: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0645\u062F\u062A", - ipv4: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0627\u06CC\u0688\u0631\u06CC\u0633", - ipv6: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0627\u06CC\u0688\u0631\u06CC\u0633", - cidrv4: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0631\u06CC\u0646\u062C", - cidrv6: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0631\u06CC\u0646\u062C", - base64: "\u0628\u06CC\u0633 64 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF", - base64url: "\u0628\u06CC\u0633 64 \u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF", - json_string: "\u062C\u06D2 \u0627\u06CC\u0633 \u0627\u0648 \u0627\u06CC\u0646 \u0633\u0679\u0631\u0646\u06AF", - e164: "\u0627\u06CC 164 \u0646\u0645\u0628\u0631", - jwt: "\u062C\u06D2 \u0688\u0628\u0644\u06CC\u0648 \u0679\u06CC", - template_literal: "\u0627\u0646 \u067E\u0679" - }; - const TypeDictionary = { - nan: "NaN", - number: "\u0646\u0645\u0628\u0631", - array: "\u0622\u0631\u06D2", - null: "\u0646\u0644" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: instanceof ${issue2.expected} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627\u060C ${received} \u0645\u0648\u0635\u0648\u0644 \u06C1\u0648\u0627`; - } - return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${expected} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627\u060C ${received} \u0645\u0648\u0635\u0648\u0644 \u06C1\u0648\u0627`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${stringifyPrimitive(issue2.values[0])} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`; - return `\u063A\u0644\u0637 \u0622\u067E\u0634\u0646: ${joinValues(issue2.values, "|")} \u0645\u06CC\u06BA \u0633\u06D2 \u0627\u06CC\u06A9 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`; - case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; - const sizing = getSizing(issue2.origin); - if (sizing) - return `\u0628\u06C1\u062A \u0628\u0691\u0627: ${issue2.origin ?? "\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u06D2 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0639\u0646\u0627\u0635\u0631"} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`; - return `\u0628\u06C1\u062A \u0628\u0691\u0627: ${issue2.origin ?? "\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u0627 ${adj}${issue2.maximum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`; - } - case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${issue2.origin} \u06A9\u06D2 ${adj}${issue2.minimum.toString()} ${sizing.unit} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`; - } - return `\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${issue2.origin} \u06A9\u0627 ${adj}${issue2.minimum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") { - return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${_issue.prefix}" \u0633\u06D2 \u0634\u0631\u0648\u0639 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`; - } - if (_issue.format === "ends_with") - return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${_issue.suffix}" \u067E\u0631 \u062E\u062A\u0645 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`; - if (_issue.format === "includes") - return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${_issue.includes}" \u0634\u0627\u0645\u0644 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`; - if (_issue.format === "regex") - return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: \u067E\u06CC\u0679\u0631\u0646 ${_issue.pattern} \u0633\u06D2 \u0645\u06CC\u0686 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`; - return `\u063A\u0644\u0637 ${FormatDictionary[_issue.format] ?? issue2.format}`; - } - case "not_multiple_of": - return `\u063A\u0644\u0637 \u0646\u0645\u0628\u0631: ${issue2.divisor} \u06A9\u0627 \u0645\u0636\u0627\u0639\u0641 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`; - case "unrecognized_keys": - return `\u063A\u06CC\u0631 \u062A\u0633\u0644\u06CC\u0645 \u0634\u062F\u06C1 \u06A9\u06CC${issue2.keys.length > 1 ? "\u0632" : ""}: ${joinValues(issue2.keys, "\u060C ")}`; - case "invalid_key": - return `${issue2.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u06A9\u06CC`; - case "invalid_union": - return "\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679"; - case "invalid_element": - return `${issue2.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u0648\u06CC\u0644\u06CC\u0648`; - default: - return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679`; - } - }; - }; - } -}); - -// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/uz.js -function uz_default() { - return { - localeError: error44() - }; -} -var error44; -var init_uz = __esm({ - "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/uz.js"() { - init_util(); - error44 = () => { - const Sizable = { - string: { unit: "belgi", verb: "bo\u2018lishi kerak" }, - file: { unit: "bayt", verb: "bo\u2018lishi kerak" }, - array: { unit: "element", verb: "bo\u2018lishi kerak" }, - set: { unit: "element", verb: "bo\u2018lishi kerak" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "kirish", - email: "elektron pochta manzili", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO sana va vaqti", - date: "ISO sana", - time: "ISO vaqt", - duration: "ISO davomiylik", - ipv4: "IPv4 manzil", - ipv6: "IPv6 manzil", - mac: "MAC manzil", - cidrv4: "IPv4 diapazon", - cidrv6: "IPv6 diapazon", - base64: "base64 kodlangan satr", - base64url: "base64url kodlangan satr", - json_string: "JSON satr", - e164: "E.164 raqam", - jwt: "JWT", - template_literal: "kirish" - }; - const TypeDictionary = { - nan: "NaN", - number: "raqam", - array: "massiv" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `Noto\u2018g\u2018ri kirish: kutilgan instanceof ${issue2.expected}, qabul qilingan ${received}`; - } - return `Noto\u2018g\u2018ri kirish: kutilgan ${expected}, qabul qilingan ${received}`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `Noto\u2018g\u2018ri kirish: kutilgan ${stringifyPrimitive(issue2.values[0])}`; - return `Noto\u2018g\u2018ri variant: quyidagilardan biri kutilgan ${joinValues(issue2.values, "|")}`; - case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; - const sizing = getSizing(issue2.origin); - if (sizing) - return `Juda katta: kutilgan ${issue2.origin ?? "qiymat"} ${adj}${issue2.maximum.toString()} ${sizing.unit} ${sizing.verb}`; - return `Juda katta: kutilgan ${issue2.origin ?? "qiymat"} ${adj}${issue2.maximum.toString()}`; - } - case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `Juda kichik: kutilgan ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} ${sizing.verb}`; - } - return `Juda kichik: kutilgan ${issue2.origin} ${adj}${issue2.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") - return `Noto\u2018g\u2018ri satr: "${_issue.prefix}" bilan boshlanishi kerak`; - if (_issue.format === "ends_with") - return `Noto\u2018g\u2018ri satr: "${_issue.suffix}" bilan tugashi kerak`; - if (_issue.format === "includes") - return `Noto\u2018g\u2018ri satr: "${_issue.includes}" ni o\u2018z ichiga olishi kerak`; - if (_issue.format === "regex") - return `Noto\u2018g\u2018ri satr: ${_issue.pattern} shabloniga mos kelishi kerak`; - return `Noto\u2018g\u2018ri ${FormatDictionary[_issue.format] ?? issue2.format}`; - } - case "not_multiple_of": - return `Noto\u2018g\u2018ri raqam: ${issue2.divisor} ning karralisi bo\u2018lishi kerak`; - case "unrecognized_keys": - return `Noma\u2019lum kalit${issue2.keys.length > 1 ? "lar" : ""}: ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return `${issue2.origin} dagi kalit noto\u2018g\u2018ri`; - case "invalid_union": - return "Noto\u2018g\u2018ri kirish"; - case "invalid_element": - return `${issue2.origin} da noto\u2018g\u2018ri qiymat`; - default: - return `Noto\u2018g\u2018ri kirish`; - } - }; - }; - } -}); - -// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/vi.js -function vi_default() { - return { - localeError: error45() - }; -} -var error45; -var init_vi = __esm({ - "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/vi.js"() { - init_util(); - error45 = () => { - const Sizable = { - string: { unit: "k\xFD t\u1EF1", verb: "c\xF3" }, - file: { unit: "byte", verb: "c\xF3" }, - array: { unit: "ph\u1EA7n t\u1EED", verb: "c\xF3" }, - set: { unit: "ph\u1EA7n t\u1EED", verb: "c\xF3" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "\u0111\u1EA7u v\xE0o", - email: "\u0111\u1ECBa ch\u1EC9 email", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ng\xE0y gi\u1EDD ISO", - date: "ng\xE0y ISO", - time: "gi\u1EDD ISO", - duration: "kho\u1EA3ng th\u1EDDi gian ISO", - ipv4: "\u0111\u1ECBa ch\u1EC9 IPv4", - ipv6: "\u0111\u1ECBa ch\u1EC9 IPv6", - cidrv4: "d\u1EA3i IPv4", - cidrv6: "d\u1EA3i IPv6", - base64: "chu\u1ED7i m\xE3 h\xF3a base64", - base64url: "chu\u1ED7i m\xE3 h\xF3a base64url", - json_string: "chu\u1ED7i JSON", - e164: "s\u1ED1 E.164", - jwt: "JWT", - template_literal: "\u0111\u1EA7u v\xE0o" - }; - const TypeDictionary = { - nan: "NaN", - number: "s\u1ED1", - array: "m\u1EA3ng" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i instanceof ${issue2.expected}, nh\u1EADn \u0111\u01B0\u1EE3c ${received}`; - } - return `\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${expected}, nh\u1EADn \u0111\u01B0\u1EE3c ${received}`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${stringifyPrimitive(issue2.values[0])}`; - return `T\xF9y ch\u1ECDn kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i m\u1ED9t trong c\xE1c gi\xE1 tr\u1ECB ${joinValues(issue2.values, "|")}`; - case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; - const sizing = getSizing(issue2.origin); - if (sizing) - return `Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${issue2.origin ?? "gi\xE1 tr\u1ECB"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "ph\u1EA7n t\u1EED"}`; - return `Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${issue2.origin ?? "gi\xE1 tr\u1ECB"} ${adj}${issue2.maximum.toString()}`; - } - case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; - } - return `Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${issue2.origin} ${adj}${issue2.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") - return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i b\u1EAFt \u0111\u1EA7u b\u1EB1ng "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i k\u1EBFt th\xFAc b\u1EB1ng "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i bao g\u1ED3m "${_issue.includes}"`; - if (_issue.format === "regex") - return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i kh\u1EDBp v\u1EDBi m\u1EABu ${_issue.pattern}`; - return `${FormatDictionary[_issue.format] ?? issue2.format} kh\xF4ng h\u1EE3p l\u1EC7`; - } - case "not_multiple_of": - return `S\u1ED1 kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i l\xE0 b\u1ED9i s\u1ED1 c\u1EE7a ${issue2.divisor}`; - case "unrecognized_keys": - return `Kh\xF3a kh\xF4ng \u0111\u01B0\u1EE3c nh\u1EADn d\u1EA1ng: ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return `Kh\xF3a kh\xF4ng h\u1EE3p l\u1EC7 trong ${issue2.origin}`; - case "invalid_union": - return "\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7"; - case "invalid_element": - return `Gi\xE1 tr\u1ECB kh\xF4ng h\u1EE3p l\u1EC7 trong ${issue2.origin}`; - default: - return `\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7`; - } - }; - }; - } -}); - -// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/zh-CN.js -function zh_CN_default() { - return { - localeError: error46() - }; -} -var error46; -var init_zh_CN = __esm({ - "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/zh-CN.js"() { - init_util(); - error46 = () => { - const Sizable = { - string: { unit: "\u5B57\u7B26", verb: "\u5305\u542B" }, - file: { unit: "\u5B57\u8282", verb: "\u5305\u542B" }, - array: { unit: "\u9879", verb: "\u5305\u542B" }, - set: { unit: "\u9879", verb: "\u5305\u542B" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "\u8F93\u5165", - email: "\u7535\u5B50\u90AE\u4EF6", - url: "URL", - emoji: "\u8868\u60C5\u7B26\u53F7", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO\u65E5\u671F\u65F6\u95F4", - date: "ISO\u65E5\u671F", - time: "ISO\u65F6\u95F4", - duration: "ISO\u65F6\u957F", - ipv4: "IPv4\u5730\u5740", - ipv6: "IPv6\u5730\u5740", - cidrv4: "IPv4\u7F51\u6BB5", - cidrv6: "IPv6\u7F51\u6BB5", - base64: "base64\u7F16\u7801\u5B57\u7B26\u4E32", - base64url: "base64url\u7F16\u7801\u5B57\u7B26\u4E32", - json_string: "JSON\u5B57\u7B26\u4E32", - e164: "E.164\u53F7\u7801", - jwt: "JWT", - template_literal: "\u8F93\u5165" - }; - const TypeDictionary = { - nan: "NaN", - number: "\u6570\u5B57", - array: "\u6570\u7EC4", - null: "\u7A7A\u503C(null)" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B instanceof ${issue2.expected}\uFF0C\u5B9E\u9645\u63A5\u6536 ${received}`; - } - return `\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${expected}\uFF0C\u5B9E\u9645\u63A5\u6536 ${received}`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${stringifyPrimitive(issue2.values[0])}`; - return `\u65E0\u6548\u9009\u9879\uFF1A\u671F\u671B\u4EE5\u4E0B\u4E4B\u4E00 ${joinValues(issue2.values, "|")}`; - case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; - const sizing = getSizing(issue2.origin); - if (sizing) - return `\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${issue2.origin ?? "\u503C"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u4E2A\u5143\u7D20"}`; - return `\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${issue2.origin ?? "\u503C"} ${adj}${issue2.maximum.toString()}`; - } - case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; - } - return `\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${issue2.origin} ${adj}${issue2.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") - return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${_issue.prefix}" \u5F00\u5934`; - if (_issue.format === "ends_with") - return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${_issue.suffix}" \u7ED3\u5C3E`; - if (_issue.format === "includes") - return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u5305\u542B "${_issue.includes}"`; - if (_issue.format === "regex") - return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u6EE1\u8DB3\u6B63\u5219\u8868\u8FBE\u5F0F ${_issue.pattern}`; - return `\u65E0\u6548${FormatDictionary[_issue.format] ?? issue2.format}`; - } - case "not_multiple_of": - return `\u65E0\u6548\u6570\u5B57\uFF1A\u5FC5\u987B\u662F ${issue2.divisor} \u7684\u500D\u6570`; - case "unrecognized_keys": - return `\u51FA\u73B0\u672A\u77E5\u7684\u952E(key): ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return `${issue2.origin} \u4E2D\u7684\u952E(key)\u65E0\u6548`; - case "invalid_union": - return "\u65E0\u6548\u8F93\u5165"; - case "invalid_element": - return `${issue2.origin} \u4E2D\u5305\u542B\u65E0\u6548\u503C(value)`; - default: - return `\u65E0\u6548\u8F93\u5165`; - } - }; - }; - } -}); - -// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/zh-TW.js -function zh_TW_default() { - return { - localeError: error47() - }; -} -var error47; -var init_zh_TW = __esm({ - "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/zh-TW.js"() { - init_util(); - error47 = () => { - const Sizable = { - string: { unit: "\u5B57\u5143", verb: "\u64C1\u6709" }, - file: { unit: "\u4F4D\u5143\u7D44", verb: "\u64C1\u6709" }, - array: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" }, - set: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "\u8F38\u5165", - email: "\u90F5\u4EF6\u5730\u5740", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO \u65E5\u671F\u6642\u9593", - date: "ISO \u65E5\u671F", - time: "ISO \u6642\u9593", - duration: "ISO \u671F\u9593", - ipv4: "IPv4 \u4F4D\u5740", - ipv6: "IPv6 \u4F4D\u5740", - cidrv4: "IPv4 \u7BC4\u570D", - cidrv6: "IPv6 \u7BC4\u570D", - base64: "base64 \u7DE8\u78BC\u5B57\u4E32", - base64url: "base64url \u7DE8\u78BC\u5B57\u4E32", - json_string: "JSON \u5B57\u4E32", - e164: "E.164 \u6578\u503C", - jwt: "JWT", - template_literal: "\u8F38\u5165" - }; - const TypeDictionary = { - nan: "NaN" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA instanceof ${issue2.expected}\uFF0C\u4F46\u6536\u5230 ${received}`; - } - return `\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${expected}\uFF0C\u4F46\u6536\u5230 ${received}`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${stringifyPrimitive(issue2.values[0])}`; - return `\u7121\u6548\u7684\u9078\u9805\uFF1A\u9810\u671F\u70BA\u4EE5\u4E0B\u5176\u4E2D\u4E4B\u4E00 ${joinValues(issue2.values, "|")}`; - case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; - const sizing = getSizing(issue2.origin); - if (sizing) - return `\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${issue2.origin ?? "\u503C"} \u61C9\u70BA ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u500B\u5143\u7D20"}`; - return `\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${issue2.origin ?? "\u503C"} \u61C9\u70BA ${adj}${issue2.maximum.toString()}`; - } - case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${issue2.origin} \u61C9\u70BA ${adj}${issue2.minimum.toString()} ${sizing.unit}`; - } - return `\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${issue2.origin} \u61C9\u70BA ${adj}${issue2.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") { - return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${_issue.prefix}" \u958B\u982D`; - } - if (_issue.format === "ends_with") - return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${_issue.suffix}" \u7D50\u5C3E`; - if (_issue.format === "includes") - return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u5305\u542B "${_issue.includes}"`; - if (_issue.format === "regex") - return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u7B26\u5408\u683C\u5F0F ${_issue.pattern}`; - return `\u7121\u6548\u7684 ${FormatDictionary[_issue.format] ?? issue2.format}`; - } - case "not_multiple_of": - return `\u7121\u6548\u7684\u6578\u5B57\uFF1A\u5FC5\u9808\u70BA ${issue2.divisor} \u7684\u500D\u6578`; - case "unrecognized_keys": - return `\u7121\u6CD5\u8B58\u5225\u7684\u9375\u503C${issue2.keys.length > 1 ? "\u5011" : ""}\uFF1A${joinValues(issue2.keys, "\u3001")}`; - case "invalid_key": - return `${issue2.origin} \u4E2D\u6709\u7121\u6548\u7684\u9375\u503C`; - case "invalid_union": - return "\u7121\u6548\u7684\u8F38\u5165\u503C"; - case "invalid_element": - return `${issue2.origin} \u4E2D\u6709\u7121\u6548\u7684\u503C`; - default: - return `\u7121\u6548\u7684\u8F38\u5165\u503C`; - } - }; - }; - } -}); - -// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/yo.js -function yo_default() { - return { - localeError: error48() - }; -} -var error48; -var init_yo = __esm({ - "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/yo.js"() { - init_util(); - error48 = () => { - const Sizable = { - string: { unit: "\xE0mi", verb: "n\xED" }, - file: { unit: "bytes", verb: "n\xED" }, - array: { unit: "nkan", verb: "n\xED" }, - set: { unit: "nkan", verb: "n\xED" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "\u1EB9\u0300r\u1ECD \xECb\xE1w\u1ECDl\xE9", - email: "\xE0d\xEDr\u1EB9\u0301s\xEC \xECm\u1EB9\u0301l\xEC", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "\xE0k\xF3k\xF2 ISO", - date: "\u1ECDj\u1ECD\u0301 ISO", - time: "\xE0k\xF3k\xF2 ISO", - duration: "\xE0k\xF3k\xF2 t\xF3 p\xE9 ISO", - ipv4: "\xE0d\xEDr\u1EB9\u0301s\xEC IPv4", - ipv6: "\xE0d\xEDr\u1EB9\u0301s\xEC IPv6", - cidrv4: "\xE0gb\xE8gb\xE8 IPv4", - cidrv6: "\xE0gb\xE8gb\xE8 IPv6", - base64: "\u1ECD\u0300r\u1ECD\u0300 t\xED a k\u1ECD\u0301 n\xED base64", - base64url: "\u1ECD\u0300r\u1ECD\u0300 base64url", - json_string: "\u1ECD\u0300r\u1ECD\u0300 JSON", - e164: "n\u1ECD\u0301mb\xE0 E.164", - jwt: "JWT", - template_literal: "\u1EB9\u0300r\u1ECD \xECb\xE1w\u1ECDl\xE9" - }; - const TypeDictionary = { - nan: "NaN", - number: "n\u1ECD\u0301mb\xE0", - array: "akop\u1ECD" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": { - const expected = TypeDictionary[issue2.expected] ?? issue2.expected; - const receivedType = parsedType(issue2.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue2.expected)) { - return `\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi instanceof ${issue2.expected}, \xE0m\u1ECD\u0300 a r\xED ${received}`; - } - return `\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi ${expected}, \xE0m\u1ECD\u0300 a r\xED ${received}`; - } - case "invalid_value": - if (issue2.values.length === 1) - return `\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi ${stringifyPrimitive(issue2.values[0])}`; - return `\xC0\u1E63\xE0y\xE0n a\u1E63\xEC\u1E63e: yan \u1ECD\u0300kan l\xE1ra ${joinValues(issue2.values, "|")}`; - case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; - const sizing = getSizing(issue2.origin); - if (sizing) - return `T\xF3 p\u1ECD\u0300 j\xF9: a n\xED l\xE1ti j\u1EB9\u0301 p\xE9 ${issue2.origin ?? "iye"} ${sizing.verb} ${adj}${issue2.maximum} ${sizing.unit}`; - return `T\xF3 p\u1ECD\u0300 j\xF9: a n\xED l\xE1ti j\u1EB9\u0301 ${adj}${issue2.maximum}`; - } - case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; - const sizing = getSizing(issue2.origin); - if (sizing) - return `K\xE9r\xE9 ju: a n\xED l\xE1ti j\u1EB9\u0301 p\xE9 ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum} ${sizing.unit}`; - return `K\xE9r\xE9 ju: a n\xED l\xE1ti j\u1EB9\u0301 ${adj}${issue2.minimum}`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") - return `\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 b\u1EB9\u0300r\u1EB9\u0300 p\u1EB9\u0300l\xFA "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 par\xED p\u1EB9\u0300l\xFA "${_issue.suffix}"`; - if (_issue.format === "includes") - return `\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 n\xED "${_issue.includes}"`; - if (_issue.format === "regex") - return `\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 b\xE1 \xE0p\u1EB9\u1EB9r\u1EB9 mu ${_issue.pattern}`; - return `A\u1E63\xEC\u1E63e: ${FormatDictionary[_issue.format] ?? issue2.format}`; - } - case "not_multiple_of": - return `N\u1ECD\u0301mb\xE0 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 j\u1EB9\u0301 \xE8y\xE0 p\xEDp\xEDn ti ${issue2.divisor}`; - case "unrecognized_keys": - return `B\u1ECDt\xECn\xEC \xE0\xECm\u1ECD\u0300: ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return `B\u1ECDt\xECn\xEC a\u1E63\xEC\u1E63e n\xEDn\xFA ${issue2.origin}`; - case "invalid_union": - return "\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e"; - case "invalid_element": - return `Iye a\u1E63\xEC\u1E63e n\xEDn\xFA ${issue2.origin}`; - default: - return "\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e"; - } - }; - }; - } -}); - -// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/index.js -var locales_exports = {}; -__export(locales_exports, { - ar: () => ar_default, - az: () => az_default, - be: () => be_default, - bg: () => bg_default, - ca: () => ca_default, - cs: () => cs_default, - da: () => da_default, - de: () => de_default, - en: () => en_default2, - eo: () => eo_default, - es: () => es_default, - fa: () => fa_default, - fi: () => fi_default, - fr: () => fr_default, - frCA: () => fr_CA_default, - he: () => he_default, - hu: () => hu_default, - hy: () => hy_default, - id: () => id_default, - is: () => is_default, - it: () => it_default, - ja: () => ja_default, - ka: () => ka_default, - kh: () => kh_default, - km: () => km_default, - ko: () => ko_default, - lt: () => lt_default, - mk: () => mk_default, - ms: () => ms_default, - nl: () => nl_default, - no: () => no_default, - ota: () => ota_default, - pl: () => pl_default, - ps: () => ps_default, - pt: () => pt_default, - ru: () => ru_default, - sl: () => sl_default, - sv: () => sv_default, - ta: () => ta_default, - th: () => th_default, - tr: () => tr_default, - ua: () => ua_default, - uk: () => uk_default, - ur: () => ur_default, - uz: () => uz_default, - vi: () => vi_default, - yo: () => yo_default, - zhCN: () => zh_CN_default, - zhTW: () => zh_TW_default -}); -var init_locales = __esm({ - "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/index.js"() { - init_ar(); - init_az(); - init_be(); - init_bg(); - init_ca(); - init_cs(); - init_da(); - init_de(); - init_en(); - init_eo(); - init_es(); - init_fa(); - init_fi(); - init_fr(); - init_fr_CA(); - init_he(); - init_hu(); - init_hy(); - init_id2(); - init_is(); - init_it(); - init_ja(); - init_ka(); - init_kh(); - init_km(); - init_ko(); - init_lt(); - init_mk(); - init_ms(); - init_nl(); - init_no(); - init_ota(); - init_ps(); - init_pl(); - init_pt(); - init_ru(); - init_sl(); - init_sv(); - init_ta(); - init_th(); - init_tr(); - init_ua(); - init_uk(); - init_ur(); - init_uz(); - init_vi(); - init_zh_CN(); - init_zh_TW(); - init_yo(); - } -}); - -// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/registries.js -function registry() { - return new $ZodRegistry(); -} -var _a2, $output, $input, $ZodRegistry, globalRegistry; -var init_registries = __esm({ - "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/registries.js"() { - $output = /* @__PURE__ */ Symbol("ZodOutput"); - $input = /* @__PURE__ */ Symbol("ZodInput"); - $ZodRegistry = class { - constructor() { - this._map = /* @__PURE__ */ new WeakMap(); - this._idmap = /* @__PURE__ */ new Map(); - } - add(schema2, ..._meta) { - const meta3 = _meta[0]; - this._map.set(schema2, meta3); - if (meta3 && typeof meta3 === "object" && "id" in meta3) { - this._idmap.set(meta3.id, schema2); - } - return this; - } - clear() { - this._map = /* @__PURE__ */ new WeakMap(); - this._idmap = /* @__PURE__ */ new Map(); - return this; - } - remove(schema2) { - const meta3 = this._map.get(schema2); - if (meta3 && typeof meta3 === "object" && "id" in meta3) { - this._idmap.delete(meta3.id); - } - this._map.delete(schema2); - return this; - } - get(schema2) { - const p5 = schema2._zod.parent; - if (p5) { - const pm = { ...this.get(p5) ?? {} }; - delete pm.id; - const f5 = { ...pm, ...this._map.get(schema2) }; - return Object.keys(f5).length ? f5 : void 0; - } - return this._map.get(schema2); - } - has(schema2) { - return this._map.has(schema2); - } - }; - (_a2 = globalThis).__zod_globalRegistry ?? (_a2.__zod_globalRegistry = registry()); - globalRegistry = globalThis.__zod_globalRegistry; - } -}); - -// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/api.js -// @__NO_SIDE_EFFECTS__ -function _string(Class2, params) { - return new Class2({ - type: "string", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _coercedString(Class2, params) { - return new Class2({ - type: "string", - coerce: true, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _email(Class2, params) { - return new Class2({ - type: "string", - format: "email", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _guid(Class2, params) { - return new Class2({ - type: "string", - format: "guid", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _uuid(Class2, params) { - return new Class2({ - type: "string", - format: "uuid", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _uuidv4(Class2, params) { - return new Class2({ - type: "string", - format: "uuid", - check: "string_format", - abort: false, - version: "v4", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _uuidv6(Class2, params) { - return new Class2({ - type: "string", - format: "uuid", - check: "string_format", - abort: false, - version: "v6", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _uuidv7(Class2, params) { - return new Class2({ - type: "string", - format: "uuid", - check: "string_format", - abort: false, - version: "v7", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _url(Class2, params) { - return new Class2({ - type: "string", - format: "url", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _emoji2(Class2, params) { - return new Class2({ - type: "string", - format: "emoji", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _nanoid(Class2, params) { - return new Class2({ - type: "string", - format: "nanoid", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _cuid(Class2, params) { - return new Class2({ - type: "string", - format: "cuid", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _cuid2(Class2, params) { - return new Class2({ - type: "string", - format: "cuid2", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _ulid(Class2, params) { - return new Class2({ - type: "string", - format: "ulid", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _xid(Class2, params) { - return new Class2({ - type: "string", - format: "xid", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _ksuid(Class2, params) { - return new Class2({ - type: "string", - format: "ksuid", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _ipv4(Class2, params) { - return new Class2({ - type: "string", - format: "ipv4", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _ipv6(Class2, params) { - return new Class2({ - type: "string", - format: "ipv6", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _mac(Class2, params) { - return new Class2({ - type: "string", - format: "mac", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _cidrv4(Class2, params) { - return new Class2({ - type: "string", - format: "cidrv4", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _cidrv6(Class2, params) { - return new Class2({ - type: "string", - format: "cidrv6", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _base64(Class2, params) { - return new Class2({ - type: "string", - format: "base64", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _base64url(Class2, params) { - return new Class2({ - type: "string", - format: "base64url", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _e164(Class2, params) { - return new Class2({ - type: "string", - format: "e164", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _jwt(Class2, params) { - return new Class2({ - type: "string", - format: "jwt", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _isoDateTime(Class2, params) { - return new Class2({ - type: "string", - format: "datetime", - check: "string_format", - offset: false, - local: false, - precision: null, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _isoDate(Class2, params) { - return new Class2({ - type: "string", - format: "date", - check: "string_format", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _isoTime(Class2, params) { - return new Class2({ - type: "string", - format: "time", - check: "string_format", - precision: null, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _isoDuration(Class2, params) { - return new Class2({ - type: "string", - format: "duration", - check: "string_format", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _number(Class2, params) { - return new Class2({ - type: "number", - checks: [], - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _coercedNumber(Class2, params) { - return new Class2({ - type: "number", - coerce: true, - checks: [], - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _int(Class2, params) { - return new Class2({ - type: "number", - check: "number_format", - abort: false, - format: "safeint", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _float32(Class2, params) { - return new Class2({ - type: "number", - check: "number_format", - abort: false, - format: "float32", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _float64(Class2, params) { - return new Class2({ - type: "number", - check: "number_format", - abort: false, - format: "float64", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _int32(Class2, params) { - return new Class2({ - type: "number", - check: "number_format", - abort: false, - format: "int32", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _uint32(Class2, params) { - return new Class2({ - type: "number", - check: "number_format", - abort: false, - format: "uint32", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _boolean(Class2, params) { - return new Class2({ - type: "boolean", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _coercedBoolean(Class2, params) { - return new Class2({ - type: "boolean", - coerce: true, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _bigint(Class2, params) { - return new Class2({ - type: "bigint", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _coercedBigint(Class2, params) { - return new Class2({ - type: "bigint", - coerce: true, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _int64(Class2, params) { - return new Class2({ - type: "bigint", - check: "bigint_format", - abort: false, - format: "int64", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _uint64(Class2, params) { - return new Class2({ - type: "bigint", - check: "bigint_format", - abort: false, - format: "uint64", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _symbol(Class2, params) { - return new Class2({ - type: "symbol", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _undefined2(Class2, params) { - return new Class2({ - type: "undefined", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _null2(Class2, params) { - return new Class2({ - type: "null", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _any(Class2) { - return new Class2({ - type: "any" - }); -} -// @__NO_SIDE_EFFECTS__ -function _unknown(Class2) { - return new Class2({ - type: "unknown" - }); -} -// @__NO_SIDE_EFFECTS__ -function _never(Class2, params) { - return new Class2({ - type: "never", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _void(Class2, params) { - return new Class2({ - type: "void", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _date(Class2, params) { - return new Class2({ - type: "date", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _coercedDate(Class2, params) { - return new Class2({ - type: "date", - coerce: true, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _nan(Class2, params) { - return new Class2({ - type: "nan", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _lt(value, params) { - return new $ZodCheckLessThan({ - check: "less_than", - ...normalizeParams(params), - value, - inclusive: false - }); -} -// @__NO_SIDE_EFFECTS__ -function _lte(value, params) { - return new $ZodCheckLessThan({ - check: "less_than", - ...normalizeParams(params), - value, - inclusive: true - }); -} -// @__NO_SIDE_EFFECTS__ -function _gt(value, params) { - return new $ZodCheckGreaterThan({ - check: "greater_than", - ...normalizeParams(params), - value, - inclusive: false - }); -} -// @__NO_SIDE_EFFECTS__ -function _gte(value, params) { - return new $ZodCheckGreaterThan({ - check: "greater_than", - ...normalizeParams(params), - value, - inclusive: true - }); -} -// @__NO_SIDE_EFFECTS__ -function _positive(params) { - return /* @__PURE__ */ _gt(0, params); -} -// @__NO_SIDE_EFFECTS__ -function _negative(params) { - return /* @__PURE__ */ _lt(0, params); -} -// @__NO_SIDE_EFFECTS__ -function _nonpositive(params) { - return /* @__PURE__ */ _lte(0, params); -} -// @__NO_SIDE_EFFECTS__ -function _nonnegative(params) { - return /* @__PURE__ */ _gte(0, params); -} -// @__NO_SIDE_EFFECTS__ -function _multipleOf(value, params) { - return new $ZodCheckMultipleOf({ - check: "multiple_of", - ...normalizeParams(params), - value - }); -} -// @__NO_SIDE_EFFECTS__ -function _maxSize(maximum, params) { - return new $ZodCheckMaxSize({ - check: "max_size", - ...normalizeParams(params), - maximum - }); -} -// @__NO_SIDE_EFFECTS__ -function _minSize(minimum, params) { - return new $ZodCheckMinSize({ - check: "min_size", - ...normalizeParams(params), - minimum - }); -} -// @__NO_SIDE_EFFECTS__ -function _size(size2, params) { - return new $ZodCheckSizeEquals({ - check: "size_equals", - ...normalizeParams(params), - size: size2 - }); -} -// @__NO_SIDE_EFFECTS__ -function _maxLength(maximum, params) { - const ch = new $ZodCheckMaxLength({ - check: "max_length", - ...normalizeParams(params), - maximum - }); - return ch; -} -// @__NO_SIDE_EFFECTS__ -function _minLength(minimum, params) { - return new $ZodCheckMinLength({ - check: "min_length", - ...normalizeParams(params), - minimum - }); -} -// @__NO_SIDE_EFFECTS__ -function _length(length, params) { - return new $ZodCheckLengthEquals({ - check: "length_equals", - ...normalizeParams(params), - length - }); -} -// @__NO_SIDE_EFFECTS__ -function _regex(pattern, params) { - return new $ZodCheckRegex({ - check: "string_format", - format: "regex", - ...normalizeParams(params), - pattern - }); -} -// @__NO_SIDE_EFFECTS__ -function _lowercase(params) { - return new $ZodCheckLowerCase({ - check: "string_format", - format: "lowercase", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _uppercase(params) { - return new $ZodCheckUpperCase({ - check: "string_format", - format: "uppercase", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _includes(includes, params) { - return new $ZodCheckIncludes({ - check: "string_format", - format: "includes", - ...normalizeParams(params), - includes - }); -} -// @__NO_SIDE_EFFECTS__ -function _startsWith(prefix, params) { - return new $ZodCheckStartsWith({ - check: "string_format", - format: "starts_with", - ...normalizeParams(params), - prefix - }); -} -// @__NO_SIDE_EFFECTS__ -function _endsWith(suffix, params) { - return new $ZodCheckEndsWith({ - check: "string_format", - format: "ends_with", - ...normalizeParams(params), - suffix - }); -} -// @__NO_SIDE_EFFECTS__ -function _property(property, schema2, params) { - return new $ZodCheckProperty({ - check: "property", - property, - schema: schema2, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _mime(types2, params) { - return new $ZodCheckMimeType({ - check: "mime_type", - mime: types2, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _overwrite(tx) { - return new $ZodCheckOverwrite({ - check: "overwrite", - tx - }); -} -// @__NO_SIDE_EFFECTS__ -function _normalize(form) { - return /* @__PURE__ */ _overwrite((input) => input.normalize(form)); -} -// @__NO_SIDE_EFFECTS__ -function _trim() { - return /* @__PURE__ */ _overwrite((input) => input.trim()); -} -// @__NO_SIDE_EFFECTS__ -function _toLowerCase() { - return /* @__PURE__ */ _overwrite((input) => input.toLowerCase()); -} -// @__NO_SIDE_EFFECTS__ -function _toUpperCase() { - return /* @__PURE__ */ _overwrite((input) => input.toUpperCase()); -} -// @__NO_SIDE_EFFECTS__ -function _slugify() { - return /* @__PURE__ */ _overwrite((input) => slugify2(input)); -} -// @__NO_SIDE_EFFECTS__ -function _array(Class2, element, params) { - return new Class2({ - type: "array", - element, - // get element() { - // return element; - // }, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _union(Class2, options, params) { - return new Class2({ - type: "union", - options, - ...normalizeParams(params) - }); -} -function _xor(Class2, options, params) { - return new Class2({ - type: "union", - options, - inclusive: false, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _discriminatedUnion(Class2, discriminator, options, params) { - return new Class2({ - type: "union", - options, - discriminator, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _intersection(Class2, left, right) { - return new Class2({ - type: "intersection", - left, - right - }); -} -// @__NO_SIDE_EFFECTS__ -function _tuple(Class2, items, _paramsOrRest, _params) { - const hasRest = _paramsOrRest instanceof $ZodType; - const params = hasRest ? _params : _paramsOrRest; - const rest = hasRest ? _paramsOrRest : null; - return new Class2({ - type: "tuple", - items, - rest, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _record(Class2, keyType, valueType, params) { - return new Class2({ - type: "record", - keyType, - valueType, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _map(Class2, keyType, valueType, params) { - return new Class2({ - type: "map", - keyType, - valueType, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _set(Class2, valueType, params) { - return new Class2({ - type: "set", - valueType, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _enum(Class2, values2, params) { - const entries2 = Array.isArray(values2) ? Object.fromEntries(values2.map((v5) => [v5, v5])) : values2; - return new Class2({ - type: "enum", - entries: entries2, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _nativeEnum(Class2, entries2, params) { - return new Class2({ - type: "enum", - entries: entries2, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _literal(Class2, value, params) { - return new Class2({ - type: "literal", - values: Array.isArray(value) ? value : [value], - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _file(Class2, params) { - return new Class2({ - type: "file", - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _transform(Class2, fn) { - return new Class2({ - type: "transform", - transform: fn - }); -} -// @__NO_SIDE_EFFECTS__ -function _optional(Class2, innerType) { - return new Class2({ - type: "optional", - innerType - }); -} -// @__NO_SIDE_EFFECTS__ -function _nullable(Class2, innerType) { - return new Class2({ - type: "nullable", - innerType - }); -} -// @__NO_SIDE_EFFECTS__ -function _default(Class2, innerType, defaultValue) { - return new Class2({ - type: "default", - innerType, - get defaultValue() { - return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue); - } - }); -} -// @__NO_SIDE_EFFECTS__ -function _nonoptional(Class2, innerType, params) { - return new Class2({ - type: "nonoptional", - innerType, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _success(Class2, innerType) { - return new Class2({ - type: "success", - innerType - }); -} -// @__NO_SIDE_EFFECTS__ -function _catch(Class2, innerType, catchValue) { - return new Class2({ - type: "catch", - innerType, - catchValue: typeof catchValue === "function" ? catchValue : () => catchValue - }); -} -// @__NO_SIDE_EFFECTS__ -function _pipe(Class2, in_, out) { - return new Class2({ - type: "pipe", - in: in_, - out - }); -} -// @__NO_SIDE_EFFECTS__ -function _readonly(Class2, innerType) { - return new Class2({ - type: "readonly", - innerType - }); -} -// @__NO_SIDE_EFFECTS__ -function _templateLiteral(Class2, parts, params) { - return new Class2({ - type: "template_literal", - parts, - ...normalizeParams(params) - }); -} -// @__NO_SIDE_EFFECTS__ -function _lazy(Class2, getter) { - return new Class2({ - type: "lazy", - getter - }); -} -// @__NO_SIDE_EFFECTS__ -function _promise(Class2, innerType) { - return new Class2({ - type: "promise", - innerType - }); -} -// @__NO_SIDE_EFFECTS__ -function _custom(Class2, fn, _params) { - const norm = normalizeParams(_params); - norm.abort ?? (norm.abort = true); - const schema2 = new Class2({ - type: "custom", - check: "custom", - fn, - ...norm - }); - return schema2; -} -// @__NO_SIDE_EFFECTS__ -function _refine(Class2, fn, _params) { - const schema2 = new Class2({ - type: "custom", - check: "custom", - fn, - ...normalizeParams(_params) - }); - return schema2; -} -// @__NO_SIDE_EFFECTS__ -function _superRefine(fn) { - const ch = /* @__PURE__ */ _check((payload2) => { - payload2.addIssue = (issue2) => { - if (typeof issue2 === "string") { - payload2.issues.push(issue(issue2, payload2.value, ch._zod.def)); - } else { - const _issue = issue2; - if (_issue.fatal) - _issue.continue = false; - _issue.code ?? (_issue.code = "custom"); - _issue.input ?? (_issue.input = payload2.value); - _issue.inst ?? (_issue.inst = ch); - _issue.continue ?? (_issue.continue = !ch._zod.def.abort); - payload2.issues.push(issue(_issue)); - } - }; - return fn(payload2.value, payload2); - }); - return ch; -} -// @__NO_SIDE_EFFECTS__ -function _check(fn, params) { - const ch = new $ZodCheck({ - check: "custom", - ...normalizeParams(params) - }); - ch._zod.check = fn; - return ch; -} -// @__NO_SIDE_EFFECTS__ -function describe(description) { - const ch = new $ZodCheck({ check: "describe" }); - ch._zod.onattach = [ - (inst) => { - const existing = globalRegistry.get(inst) ?? {}; - globalRegistry.add(inst, { ...existing, description }); - } - ]; - ch._zod.check = () => { - }; - return ch; -} -// @__NO_SIDE_EFFECTS__ -function meta(metadata) { - const ch = new $ZodCheck({ check: "meta" }); - ch._zod.onattach = [ - (inst) => { - const existing = globalRegistry.get(inst) ?? {}; - globalRegistry.add(inst, { ...existing, ...metadata }); - } - ]; - ch._zod.check = () => { - }; - return ch; -} -// @__NO_SIDE_EFFECTS__ -function _stringbool(Classes, _params) { - const params = normalizeParams(_params); - let truthyArray = params.truthy ?? ["true", "1", "yes", "on", "y", "enabled"]; - let falsyArray = params.falsy ?? ["false", "0", "no", "off", "n", "disabled"]; - if (params.case !== "sensitive") { - truthyArray = truthyArray.map((v5) => typeof v5 === "string" ? v5.toLowerCase() : v5); - falsyArray = falsyArray.map((v5) => typeof v5 === "string" ? v5.toLowerCase() : v5); - } - const truthySet = new Set(truthyArray); - const falsySet = new Set(falsyArray); - const _Codec = Classes.Codec ?? $ZodCodec; - const _Boolean = Classes.Boolean ?? $ZodBoolean; - const _String = Classes.String ?? $ZodString; - const stringSchema = new _String({ type: "string", error: params.error }); - const booleanSchema = new _Boolean({ type: "boolean", error: params.error }); - const codec2 = new _Codec({ - type: "pipe", - in: stringSchema, - out: booleanSchema, - transform: ((input, payload2) => { - let data2 = input; - if (params.case !== "sensitive") - data2 = data2.toLowerCase(); - if (truthySet.has(data2)) { - return true; - } else if (falsySet.has(data2)) { - return false; - } else { - payload2.issues.push({ - code: "invalid_value", - expected: "stringbool", - values: [...truthySet, ...falsySet], - input: payload2.value, - inst: codec2, - continue: false - }); - return {}; - } - }), - reverseTransform: ((input, _payload) => { - if (input === true) { - return truthyArray[0] || "true"; - } else { - return falsyArray[0] || "false"; - } - }), - error: params.error - }); - return codec2; -} -// @__NO_SIDE_EFFECTS__ -function _stringFormat(Class2, format2, fnOrRegex, _params = {}) { - const params = normalizeParams(_params); - const def = { - ...normalizeParams(_params), - check: "string_format", - type: "string", - format: format2, - fn: typeof fnOrRegex === "function" ? fnOrRegex : (val) => fnOrRegex.test(val), - ...params - }; - if (fnOrRegex instanceof RegExp) { - def.pattern = fnOrRegex; - } - const inst = new Class2(def); - return inst; -} -var TimePrecision; -var init_api = __esm({ - "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/api.js"() { - init_checks2(); - init_registries(); - init_schemas(); - init_util(); - TimePrecision = { - Any: null, - Minute: -1, - Second: 0, - Millisecond: 3, - Microsecond: 6 - }; - } -}); - -// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/to-json-schema.js -function initializeContext(params) { - let target = params?.target ?? "draft-2020-12"; - if (target === "draft-4") - target = "draft-04"; - if (target === "draft-7") - target = "draft-07"; - return { - processors: params.processors ?? {}, - metadataRegistry: params?.metadata ?? globalRegistry, - target, - unrepresentable: params?.unrepresentable ?? "throw", - override: params?.override ?? (() => { - }), - io: params?.io ?? "output", - counter: 0, - seen: /* @__PURE__ */ new Map(), - cycles: params?.cycles ?? "ref", - reused: params?.reused ?? "inline", - external: params?.external ?? void 0 - }; -} -function process2(schema2, ctx, _params = { path: [], schemaPath: [] }) { - var _a6; - const def = schema2._zod.def; - const seen = ctx.seen.get(schema2); - if (seen) { - seen.count++; - const isCycle = _params.schemaPath.includes(schema2); - if (isCycle) { - seen.cycle = _params.path; - } - return seen.schema; - } - const result = { schema: {}, count: 1, cycle: void 0, path: _params.path }; - ctx.seen.set(schema2, result); - const overrideSchema = schema2._zod.toJSONSchema?.(); - if (overrideSchema) { - result.schema = overrideSchema; - } else { - const params = { - ..._params, - schemaPath: [..._params.schemaPath, schema2], - path: _params.path - }; - if (schema2._zod.processJSONSchema) { - schema2._zod.processJSONSchema(ctx, result.schema, params); - } else { - const _json = result.schema; - const processor = ctx.processors[def.type]; - if (!processor) { - throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`); - } - processor(schema2, ctx, _json, params); - } - const parent = schema2._zod.parent; - if (parent) { - if (!result.ref) - result.ref = parent; - process2(parent, ctx, params); - ctx.seen.get(parent).isParent = true; - } - } - const meta3 = ctx.metadataRegistry.get(schema2); - if (meta3) - Object.assign(result.schema, meta3); - if (ctx.io === "input" && isTransforming(schema2)) { - delete result.schema.examples; - delete result.schema.default; - } - if (ctx.io === "input" && result.schema._prefault) - (_a6 = result.schema).default ?? (_a6.default = result.schema._prefault); - delete result.schema._prefault; - const _result = ctx.seen.get(schema2); - return _result.schema; -} -function extractDefs(ctx, schema2) { - const root = ctx.seen.get(schema2); - if (!root) - throw new Error("Unprocessed schema. This is a bug in Zod."); - const idToSchema = /* @__PURE__ */ new Map(); - for (const entry of ctx.seen.entries()) { - const id = ctx.metadataRegistry.get(entry[0])?.id; - if (id) { - const existing = idToSchema.get(id); - if (existing && existing !== entry[0]) { - throw new Error(`Duplicate schema id "${id}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`); - } - idToSchema.set(id, entry[0]); - } - } - const makeURI = (entry) => { - const defsSegment = ctx.target === "draft-2020-12" ? "$defs" : "definitions"; - if (ctx.external) { - const externalId = ctx.external.registry.get(entry[0])?.id; - const uriGenerator = ctx.external.uri ?? ((id2) => id2); - if (externalId) { - return { ref: uriGenerator(externalId) }; - } - const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`; - entry[1].defId = id; - return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${id}` }; - } - if (entry[1] === root) { - return { ref: "#" }; - } - const uriPrefix = `#`; - const defUriPrefix = `${uriPrefix}/${defsSegment}/`; - const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`; - return { defId, ref: defUriPrefix + defId }; - }; - const extractToDef = (entry) => { - if (entry[1].schema.$ref) { - return; - } - const seen = entry[1]; - const { ref, defId } = makeURI(entry); - seen.def = { ...seen.schema }; - if (defId) - seen.defId = defId; - const schema3 = seen.schema; - for (const key in schema3) { - delete schema3[key]; - } - schema3.$ref = ref; - }; - if (ctx.cycles === "throw") { - for (const entry of ctx.seen.entries()) { - const seen = entry[1]; - if (seen.cycle) { - throw new Error(`Cycle detected: #/${seen.cycle?.join("/")}/ - -Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`); - } - } - } - for (const entry of ctx.seen.entries()) { - const seen = entry[1]; - if (schema2 === entry[0]) { - extractToDef(entry); - continue; - } - if (ctx.external) { - const ext = ctx.external.registry.get(entry[0])?.id; - if (schema2 !== entry[0] && ext) { - extractToDef(entry); - continue; - } - } - const id = ctx.metadataRegistry.get(entry[0])?.id; - if (id) { - extractToDef(entry); - continue; - } - if (seen.cycle) { - extractToDef(entry); - continue; - } - if (seen.count > 1) { - if (ctx.reused === "ref") { - extractToDef(entry); - continue; - } - } - } -} -function finalize(ctx, schema2) { - const root = ctx.seen.get(schema2); - if (!root) - throw new Error("Unprocessed schema. This is a bug in Zod."); - const flattenRef = (zodSchema) => { - const seen = ctx.seen.get(zodSchema); - if (seen.ref === null) - return; - const schema3 = seen.def ?? seen.schema; - const _cached = { ...schema3 }; - const ref = seen.ref; - seen.ref = null; - if (ref) { - flattenRef(ref); - const refSeen = ctx.seen.get(ref); - const refSchema = refSeen.schema; - if (refSchema.$ref && (ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0")) { - schema3.allOf = schema3.allOf ?? []; - schema3.allOf.push(refSchema); - } else { - Object.assign(schema3, refSchema); - } - Object.assign(schema3, _cached); - const isParentRef = zodSchema._zod.parent === ref; - if (isParentRef) { - for (const key in schema3) { - if (key === "$ref" || key === "allOf") - continue; - if (!(key in _cached)) { - delete schema3[key]; - } - } - } - if (refSchema.$ref && refSeen.def) { - for (const key in schema3) { - if (key === "$ref" || key === "allOf") - continue; - if (key in refSeen.def && JSON.stringify(schema3[key]) === JSON.stringify(refSeen.def[key])) { - delete schema3[key]; - } - } - } - } - const parent = zodSchema._zod.parent; - if (parent && parent !== ref) { - flattenRef(parent); - const parentSeen = ctx.seen.get(parent); - if (parentSeen?.schema.$ref) { - schema3.$ref = parentSeen.schema.$ref; - if (parentSeen.def) { - for (const key in schema3) { - if (key === "$ref" || key === "allOf") - continue; - if (key in parentSeen.def && JSON.stringify(schema3[key]) === JSON.stringify(parentSeen.def[key])) { - delete schema3[key]; - } - } - } - } - } - ctx.override({ - zodSchema, - jsonSchema: schema3, - path: seen.path ?? [] - }); - }; - for (const entry of [...ctx.seen.entries()].reverse()) { - flattenRef(entry[0]); - } - const result = {}; - if (ctx.target === "draft-2020-12") { - result.$schema = "https://json-schema.org/draft/2020-12/schema"; - } else if (ctx.target === "draft-07") { - result.$schema = "http://json-schema.org/draft-07/schema#"; - } else if (ctx.target === "draft-04") { - result.$schema = "http://json-schema.org/draft-04/schema#"; - } else if (ctx.target === "openapi-3.0") { - } else { - } - if (ctx.external?.uri) { - const id = ctx.external.registry.get(schema2)?.id; - if (!id) - throw new Error("Schema is missing an `id` property"); - result.$id = ctx.external.uri(id); - } - Object.assign(result, root.def ?? root.schema); - const defs = ctx.external?.defs ?? {}; - for (const entry of ctx.seen.entries()) { - const seen = entry[1]; - if (seen.def && seen.defId) { - defs[seen.defId] = seen.def; - } - } - if (ctx.external) { - } else { - if (Object.keys(defs).length > 0) { - if (ctx.target === "draft-2020-12") { - result.$defs = defs; - } else { - result.definitions = defs; - } - } - } - try { - const finalized = JSON.parse(JSON.stringify(result)); - Object.defineProperty(finalized, "~standard", { - value: { - ...schema2["~standard"], - jsonSchema: { - input: createStandardJSONSchemaMethod(schema2, "input", ctx.processors), - output: createStandardJSONSchemaMethod(schema2, "output", ctx.processors) - } - }, - enumerable: false, - writable: false - }); - return finalized; - } catch (_err) { - throw new Error("Error converting schema to JSON."); - } -} -function isTransforming(_schema, _ctx) { - const ctx = _ctx ?? { seen: /* @__PURE__ */ new Set() }; - if (ctx.seen.has(_schema)) - return false; - ctx.seen.add(_schema); - const def = _schema._zod.def; - if (def.type === "transform") - return true; - if (def.type === "array") - return isTransforming(def.element, ctx); - if (def.type === "set") - return isTransforming(def.valueType, ctx); - if (def.type === "lazy") - return isTransforming(def.getter(), ctx); - if (def.type === "promise" || def.type === "optional" || def.type === "nonoptional" || def.type === "nullable" || def.type === "readonly" || def.type === "default" || def.type === "prefault") { - return isTransforming(def.innerType, ctx); - } - if (def.type === "intersection") { - return isTransforming(def.left, ctx) || isTransforming(def.right, ctx); - } - if (def.type === "record" || def.type === "map") { - return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx); - } - if (def.type === "pipe") { - return isTransforming(def.in, ctx) || isTransforming(def.out, ctx); - } - if (def.type === "object") { - for (const key in def.shape) { - if (isTransforming(def.shape[key], ctx)) - return true; - } - return false; - } - if (def.type === "union") { - for (const option of def.options) { - if (isTransforming(option, ctx)) - return true; - } - return false; - } - if (def.type === "tuple") { - for (const item of def.items) { - if (isTransforming(item, ctx)) - return true; - } - if (def.rest && isTransforming(def.rest, ctx)) - return true; - return false; - } - return false; -} -var createToJSONSchemaMethod, createStandardJSONSchemaMethod; -var init_to_json_schema = __esm({ - "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/to-json-schema.js"() { - init_registries(); - createToJSONSchemaMethod = (schema2, processors = {}) => (params) => { - const ctx = initializeContext({ ...params, processors }); - process2(schema2, ctx); - extractDefs(ctx, schema2); - return finalize(ctx, schema2); - }; - createStandardJSONSchemaMethod = (schema2, io, processors = {}) => (params) => { - const { libraryOptions, target } = params ?? {}; - const ctx = initializeContext({ ...libraryOptions ?? {}, target, io, processors }); - process2(schema2, ctx); - extractDefs(ctx, schema2); - return finalize(ctx, schema2); - }; - } -}); - -// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/json-schema-processors.js -function toJSONSchema(input, params) { - if ("_idmap" in input) { - const registry2 = input; - const ctx2 = initializeContext({ ...params, processors: allProcessors }); - const defs = {}; - for (const entry of registry2._idmap.entries()) { - const [_, schema2] = entry; - process2(schema2, ctx2); - } - const schemas = {}; - const external = { - registry: registry2, - uri: params?.uri, - defs - }; - ctx2.external = external; - for (const entry of registry2._idmap.entries()) { - const [key, schema2] = entry; - extractDefs(ctx2, schema2); - schemas[key] = finalize(ctx2, schema2); - } - if (Object.keys(defs).length > 0) { - const defsSegment = ctx2.target === "draft-2020-12" ? "$defs" : "definitions"; - schemas.__shared = { - [defsSegment]: defs - }; - } - return { schemas }; - } - const ctx = initializeContext({ ...params, processors: allProcessors }); - process2(input, ctx); - extractDefs(ctx, input); - return finalize(ctx, input); -} -var formatMap, stringProcessor, numberProcessor, booleanProcessor, bigintProcessor, symbolProcessor, nullProcessor, undefinedProcessor, voidProcessor, neverProcessor, anyProcessor, unknownProcessor, dateProcessor, enumProcessor, literalProcessor, nanProcessor, templateLiteralProcessor, fileProcessor, successProcessor, customProcessor, functionProcessor, transformProcessor, mapProcessor, setProcessor, arrayProcessor, objectProcessor, unionProcessor, intersectionProcessor, tupleProcessor, recordProcessor, nullableProcessor, nonoptionalProcessor, defaultProcessor, prefaultProcessor, catchProcessor, pipeProcessor, readonlyProcessor, promiseProcessor, optionalProcessor, lazyProcessor, allProcessors; -var init_json_schema_processors = __esm({ - "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/json-schema-processors.js"() { - init_to_json_schema(); - init_util(); - formatMap = { - guid: "uuid", - url: "uri", - datetime: "date-time", - json_string: "json-string", - regex: "" - // do not set - }; - stringProcessor = (schema2, ctx, _json, _params) => { - const json3 = _json; - json3.type = "string"; - const { minimum, maximum, format: format2, patterns, contentEncoding } = schema2._zod.bag; - if (typeof minimum === "number") - json3.minLength = minimum; - if (typeof maximum === "number") - json3.maxLength = maximum; - if (format2) { - json3.format = formatMap[format2] ?? format2; - if (json3.format === "") - delete json3.format; - if (format2 === "time") { - delete json3.format; - } - } - if (contentEncoding) - json3.contentEncoding = contentEncoding; - if (patterns && patterns.size > 0) { - const regexes = [...patterns]; - if (regexes.length === 1) - json3.pattern = regexes[0].source; - else if (regexes.length > 1) { - json3.allOf = [ - ...regexes.map((regex) => ({ - ...ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0" ? { type: "string" } : {}, - pattern: regex.source - })) - ]; - } - } - }; - numberProcessor = (schema2, ctx, _json, _params) => { - const json3 = _json; - const { minimum, maximum, format: format2, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema2._zod.bag; - if (typeof format2 === "string" && format2.includes("int")) - json3.type = "integer"; - else - json3.type = "number"; - if (typeof exclusiveMinimum === "number") { - if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") { - json3.minimum = exclusiveMinimum; - json3.exclusiveMinimum = true; - } else { - json3.exclusiveMinimum = exclusiveMinimum; - } - } - if (typeof minimum === "number") { - json3.minimum = minimum; - if (typeof exclusiveMinimum === "number" && ctx.target !== "draft-04") { - if (exclusiveMinimum >= minimum) - delete json3.minimum; - else - delete json3.exclusiveMinimum; - } - } - if (typeof exclusiveMaximum === "number") { - if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") { - json3.maximum = exclusiveMaximum; - json3.exclusiveMaximum = true; - } else { - json3.exclusiveMaximum = exclusiveMaximum; - } - } - if (typeof maximum === "number") { - json3.maximum = maximum; - if (typeof exclusiveMaximum === "number" && ctx.target !== "draft-04") { - if (exclusiveMaximum <= maximum) - delete json3.maximum; - else - delete json3.exclusiveMaximum; - } - } - if (typeof multipleOf === "number") - json3.multipleOf = multipleOf; - }; - booleanProcessor = (_schema, _ctx, json3, _params) => { - json3.type = "boolean"; - }; - bigintProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("BigInt cannot be represented in JSON Schema"); - } - }; - symbolProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Symbols cannot be represented in JSON Schema"); - } - }; - nullProcessor = (_schema, ctx, json3, _params) => { - if (ctx.target === "openapi-3.0") { - json3.type = "string"; - json3.nullable = true; - json3.enum = [null]; - } else { - json3.type = "null"; - } - }; - undefinedProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Undefined cannot be represented in JSON Schema"); - } - }; - voidProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Void cannot be represented in JSON Schema"); - } - }; - neverProcessor = (_schema, _ctx, json3, _params) => { - json3.not = {}; - }; - anyProcessor = (_schema, _ctx, _json, _params) => { - }; - unknownProcessor = (_schema, _ctx, _json, _params) => { - }; - dateProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Date cannot be represented in JSON Schema"); - } - }; - enumProcessor = (schema2, _ctx, json3, _params) => { - const def = schema2._zod.def; - const values2 = getEnumValues(def.entries); - if (values2.every((v5) => typeof v5 === "number")) - json3.type = "number"; - if (values2.every((v5) => typeof v5 === "string")) - json3.type = "string"; - json3.enum = values2; - }; - literalProcessor = (schema2, ctx, json3, _params) => { - const def = schema2._zod.def; - const vals = []; - for (const val of def.values) { - if (val === void 0) { - if (ctx.unrepresentable === "throw") { - throw new Error("Literal `undefined` cannot be represented in JSON Schema"); - } else { - } - } else if (typeof val === "bigint") { - if (ctx.unrepresentable === "throw") { - throw new Error("BigInt literals cannot be represented in JSON Schema"); - } else { - vals.push(Number(val)); - } - } else { - vals.push(val); - } - } - if (vals.length === 0) { - } else if (vals.length === 1) { - const val = vals[0]; - json3.type = val === null ? "null" : typeof val; - if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") { - json3.enum = [val]; - } else { - json3.const = val; - } - } else { - if (vals.every((v5) => typeof v5 === "number")) - json3.type = "number"; - if (vals.every((v5) => typeof v5 === "string")) - json3.type = "string"; - if (vals.every((v5) => typeof v5 === "boolean")) - json3.type = "boolean"; - if (vals.every((v5) => v5 === null)) - json3.type = "null"; - json3.enum = vals; - } - }; - nanProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("NaN cannot be represented in JSON Schema"); - } - }; - templateLiteralProcessor = (schema2, _ctx, json3, _params) => { - const _json = json3; - const pattern = schema2._zod.pattern; - if (!pattern) - throw new Error("Pattern not found in template literal"); - _json.type = "string"; - _json.pattern = pattern.source; - }; - fileProcessor = (schema2, _ctx, json3, _params) => { - const _json = json3; - const file2 = { - type: "string", - format: "binary", - contentEncoding: "binary" - }; - const { minimum, maximum, mime } = schema2._zod.bag; - if (minimum !== void 0) - file2.minLength = minimum; - if (maximum !== void 0) - file2.maxLength = maximum; - if (mime) { - if (mime.length === 1) { - file2.contentMediaType = mime[0]; - Object.assign(_json, file2); - } else { - Object.assign(_json, file2); - _json.anyOf = mime.map((m5) => ({ contentMediaType: m5 })); - } - } else { - Object.assign(_json, file2); - } - }; - successProcessor = (_schema, _ctx, json3, _params) => { - json3.type = "boolean"; - }; - customProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Custom types cannot be represented in JSON Schema"); - } - }; - functionProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Function types cannot be represented in JSON Schema"); - } - }; - transformProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Transforms cannot be represented in JSON Schema"); - } - }; - mapProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Map cannot be represented in JSON Schema"); - } - }; - setProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Set cannot be represented in JSON Schema"); - } - }; - arrayProcessor = (schema2, ctx, _json, params) => { - const json3 = _json; - const def = schema2._zod.def; - const { minimum, maximum } = schema2._zod.bag; - if (typeof minimum === "number") - json3.minItems = minimum; - if (typeof maximum === "number") - json3.maxItems = maximum; - json3.type = "array"; - json3.items = process2(def.element, ctx, { ...params, path: [...params.path, "items"] }); - }; - objectProcessor = (schema2, ctx, _json, params) => { - const json3 = _json; - const def = schema2._zod.def; - json3.type = "object"; - json3.properties = {}; - const shape = def.shape; - for (const key in shape) { - json3.properties[key] = process2(shape[key], ctx, { - ...params, - path: [...params.path, "properties", key] - }); - } - const allKeys = new Set(Object.keys(shape)); - const requiredKeys = new Set([...allKeys].filter((key) => { - const v5 = def.shape[key]._zod; - if (ctx.io === "input") { - return v5.optin === void 0; - } else { - return v5.optout === void 0; - } - })); - if (requiredKeys.size > 0) { - json3.required = Array.from(requiredKeys); - } - if (def.catchall?._zod.def.type === "never") { - json3.additionalProperties = false; - } else if (!def.catchall) { - if (ctx.io === "output") - json3.additionalProperties = false; - } else if (def.catchall) { - json3.additionalProperties = process2(def.catchall, ctx, { - ...params, - path: [...params.path, "additionalProperties"] - }); - } - }; - unionProcessor = (schema2, ctx, json3, params) => { - const def = schema2._zod.def; - const isExclusive = def.inclusive === false; - const options = def.options.map((x5, i5) => process2(x5, ctx, { - ...params, - path: [...params.path, isExclusive ? "oneOf" : "anyOf", i5] - })); - if (isExclusive) { - json3.oneOf = options; - } else { - json3.anyOf = options; - } - }; - intersectionProcessor = (schema2, ctx, json3, params) => { - const def = schema2._zod.def; - const a5 = process2(def.left, ctx, { - ...params, - path: [...params.path, "allOf", 0] - }); - const b6 = process2(def.right, ctx, { - ...params, - path: [...params.path, "allOf", 1] - }); - const isSimpleIntersection = (val) => "allOf" in val && Object.keys(val).length === 1; - const allOf = [ - ...isSimpleIntersection(a5) ? a5.allOf : [a5], - ...isSimpleIntersection(b6) ? b6.allOf : [b6] - ]; - json3.allOf = allOf; - }; - tupleProcessor = (schema2, ctx, _json, params) => { - const json3 = _json; - const def = schema2._zod.def; - json3.type = "array"; - const prefixPath = ctx.target === "draft-2020-12" ? "prefixItems" : "items"; - const restPath = ctx.target === "draft-2020-12" ? "items" : ctx.target === "openapi-3.0" ? "items" : "additionalItems"; - const prefixItems = def.items.map((x5, i5) => process2(x5, ctx, { - ...params, - path: [...params.path, prefixPath, i5] - })); - const rest = def.rest ? process2(def.rest, ctx, { - ...params, - path: [...params.path, restPath, ...ctx.target === "openapi-3.0" ? [def.items.length] : []] - }) : null; - if (ctx.target === "draft-2020-12") { - json3.prefixItems = prefixItems; - if (rest) { - json3.items = rest; - } - } else if (ctx.target === "openapi-3.0") { - json3.items = { - anyOf: prefixItems - }; - if (rest) { - json3.items.anyOf.push(rest); - } - json3.minItems = prefixItems.length; - if (!rest) { - json3.maxItems = prefixItems.length; - } - } else { - json3.items = prefixItems; - if (rest) { - json3.additionalItems = rest; - } - } - const { minimum, maximum } = schema2._zod.bag; - if (typeof minimum === "number") - json3.minItems = minimum; - if (typeof maximum === "number") - json3.maxItems = maximum; - }; - recordProcessor = (schema2, ctx, _json, params) => { - const json3 = _json; - const def = schema2._zod.def; - json3.type = "object"; - const keyType = def.keyType; - const keyBag = keyType._zod.bag; - const patterns = keyBag?.patterns; - if (def.mode === "loose" && patterns && patterns.size > 0) { - const valueSchema = process2(def.valueType, ctx, { - ...params, - path: [...params.path, "patternProperties", "*"] - }); - json3.patternProperties = {}; - for (const pattern of patterns) { - json3.patternProperties[pattern.source] = valueSchema; - } - } else { - if (ctx.target === "draft-07" || ctx.target === "draft-2020-12") { - json3.propertyNames = process2(def.keyType, ctx, { - ...params, - path: [...params.path, "propertyNames"] - }); - } - json3.additionalProperties = process2(def.valueType, ctx, { - ...params, - path: [...params.path, "additionalProperties"] - }); - } - const keyValues = keyType._zod.values; - if (keyValues) { - const validKeyValues = [...keyValues].filter((v5) => typeof v5 === "string" || typeof v5 === "number"); - if (validKeyValues.length > 0) { - json3.required = validKeyValues; - } - } - }; - nullableProcessor = (schema2, ctx, json3, params) => { - const def = schema2._zod.def; - const inner = process2(def.innerType, ctx, params); - const seen = ctx.seen.get(schema2); - if (ctx.target === "openapi-3.0") { - seen.ref = def.innerType; - json3.nullable = true; - } else { - json3.anyOf = [inner, { type: "null" }]; - } - }; - nonoptionalProcessor = (schema2, ctx, _json, params) => { - const def = schema2._zod.def; - process2(def.innerType, ctx, params); - const seen = ctx.seen.get(schema2); - seen.ref = def.innerType; - }; - defaultProcessor = (schema2, ctx, json3, params) => { - const def = schema2._zod.def; - process2(def.innerType, ctx, params); - const seen = ctx.seen.get(schema2); - seen.ref = def.innerType; - json3.default = JSON.parse(JSON.stringify(def.defaultValue)); - }; - prefaultProcessor = (schema2, ctx, json3, params) => { - const def = schema2._zod.def; - process2(def.innerType, ctx, params); - const seen = ctx.seen.get(schema2); - seen.ref = def.innerType; - if (ctx.io === "input") - json3._prefault = JSON.parse(JSON.stringify(def.defaultValue)); - }; - catchProcessor = (schema2, ctx, json3, params) => { - const def = schema2._zod.def; - process2(def.innerType, ctx, params); - const seen = ctx.seen.get(schema2); - seen.ref = def.innerType; - let catchValue; - try { - catchValue = def.catchValue(void 0); - } catch { - throw new Error("Dynamic catch values are not supported in JSON Schema"); - } - json3.default = catchValue; - }; - pipeProcessor = (schema2, ctx, _json, params) => { - const def = schema2._zod.def; - const innerType = ctx.io === "input" ? def.in._zod.def.type === "transform" ? def.out : def.in : def.out; - process2(innerType, ctx, params); - const seen = ctx.seen.get(schema2); - seen.ref = innerType; - }; - readonlyProcessor = (schema2, ctx, json3, params) => { - const def = schema2._zod.def; - process2(def.innerType, ctx, params); - const seen = ctx.seen.get(schema2); - seen.ref = def.innerType; - json3.readOnly = true; - }; - promiseProcessor = (schema2, ctx, _json, params) => { - const def = schema2._zod.def; - process2(def.innerType, ctx, params); - const seen = ctx.seen.get(schema2); - seen.ref = def.innerType; - }; - optionalProcessor = (schema2, ctx, _json, params) => { - const def = schema2._zod.def; - process2(def.innerType, ctx, params); - const seen = ctx.seen.get(schema2); - seen.ref = def.innerType; - }; - lazyProcessor = (schema2, ctx, _json, params) => { - const innerType = schema2._zod.innerType; - process2(innerType, ctx, params); - const seen = ctx.seen.get(schema2); - seen.ref = innerType; - }; - allProcessors = { - string: stringProcessor, - number: numberProcessor, - boolean: booleanProcessor, - bigint: bigintProcessor, - symbol: symbolProcessor, - null: nullProcessor, - undefined: undefinedProcessor, - void: voidProcessor, - never: neverProcessor, - any: anyProcessor, - unknown: unknownProcessor, - date: dateProcessor, - enum: enumProcessor, - literal: literalProcessor, - nan: nanProcessor, - template_literal: templateLiteralProcessor, - file: fileProcessor, - success: successProcessor, - custom: customProcessor, - function: functionProcessor, - transform: transformProcessor, - map: mapProcessor, - set: setProcessor, - array: arrayProcessor, - object: objectProcessor, - union: unionProcessor, - intersection: intersectionProcessor, - tuple: tupleProcessor, - record: recordProcessor, - nullable: nullableProcessor, - nonoptional: nonoptionalProcessor, - default: defaultProcessor, - prefault: prefaultProcessor, - catch: catchProcessor, - pipe: pipeProcessor, - readonly: readonlyProcessor, - promise: promiseProcessor, - optional: optionalProcessor, - lazy: lazyProcessor - }; - } -}); - -// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/json-schema-generator.js -var JSONSchemaGenerator; -var init_json_schema_generator = __esm({ - "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/json-schema-generator.js"() { - init_json_schema_processors(); - init_to_json_schema(); - JSONSchemaGenerator = class { - /** @deprecated Access via ctx instead */ - get metadataRegistry() { - return this.ctx.metadataRegistry; - } - /** @deprecated Access via ctx instead */ - get target() { - return this.ctx.target; - } - /** @deprecated Access via ctx instead */ - get unrepresentable() { - return this.ctx.unrepresentable; - } - /** @deprecated Access via ctx instead */ - get override() { - return this.ctx.override; - } - /** @deprecated Access via ctx instead */ - get io() { - return this.ctx.io; - } - /** @deprecated Access via ctx instead */ - get counter() { - return this.ctx.counter; - } - set counter(value) { - this.ctx.counter = value; - } - /** @deprecated Access via ctx instead */ - get seen() { - return this.ctx.seen; - } - constructor(params) { - let normalizedTarget = params?.target ?? "draft-2020-12"; - if (normalizedTarget === "draft-4") - normalizedTarget = "draft-04"; - if (normalizedTarget === "draft-7") - normalizedTarget = "draft-07"; - this.ctx = initializeContext({ - processors: allProcessors, - target: normalizedTarget, - ...params?.metadata && { metadata: params.metadata }, - ...params?.unrepresentable && { unrepresentable: params.unrepresentable }, - ...params?.override && { override: params.override }, - ...params?.io && { io: params.io } - }); - } - /** - * Process a schema to prepare it for JSON Schema generation. - * This must be called before emit(). - */ - process(schema2, _params = { path: [], schemaPath: [] }) { - return process2(schema2, this.ctx, _params); - } - /** - * Emit the final JSON Schema after processing. - * Must call process() first. - */ - emit(schema2, _params) { - if (_params) { - if (_params.cycles) - this.ctx.cycles = _params.cycles; - if (_params.reused) - this.ctx.reused = _params.reused; - if (_params.external) - this.ctx.external = _params.external; - } - extractDefs(this.ctx, schema2); - const result = finalize(this.ctx, schema2); - const { "~standard": _, ...plainResult } = result; - return plainResult; - } - }; - } -}); - -// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/json-schema.js -var json_schema_exports = {}; -var init_json_schema = __esm({ - "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/json-schema.js"() { - } -}); - -// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/index.js -var core_exports2 = {}; -__export(core_exports2, { - $ZodAny: () => $ZodAny, - $ZodArray: () => $ZodArray, - $ZodAsyncError: () => $ZodAsyncError, - $ZodBase64: () => $ZodBase64, - $ZodBase64URL: () => $ZodBase64URL, - $ZodBigInt: () => $ZodBigInt, - $ZodBigIntFormat: () => $ZodBigIntFormat, - $ZodBoolean: () => $ZodBoolean, - $ZodCIDRv4: () => $ZodCIDRv4, - $ZodCIDRv6: () => $ZodCIDRv6, - $ZodCUID: () => $ZodCUID, - $ZodCUID2: () => $ZodCUID2, - $ZodCatch: () => $ZodCatch, - $ZodCheck: () => $ZodCheck, - $ZodCheckBigIntFormat: () => $ZodCheckBigIntFormat, - $ZodCheckEndsWith: () => $ZodCheckEndsWith, - $ZodCheckGreaterThan: () => $ZodCheckGreaterThan, - $ZodCheckIncludes: () => $ZodCheckIncludes, - $ZodCheckLengthEquals: () => $ZodCheckLengthEquals, - $ZodCheckLessThan: () => $ZodCheckLessThan, - $ZodCheckLowerCase: () => $ZodCheckLowerCase, - $ZodCheckMaxLength: () => $ZodCheckMaxLength, - $ZodCheckMaxSize: () => $ZodCheckMaxSize, - $ZodCheckMimeType: () => $ZodCheckMimeType, - $ZodCheckMinLength: () => $ZodCheckMinLength, - $ZodCheckMinSize: () => $ZodCheckMinSize, - $ZodCheckMultipleOf: () => $ZodCheckMultipleOf, - $ZodCheckNumberFormat: () => $ZodCheckNumberFormat, - $ZodCheckOverwrite: () => $ZodCheckOverwrite, - $ZodCheckProperty: () => $ZodCheckProperty, - $ZodCheckRegex: () => $ZodCheckRegex, - $ZodCheckSizeEquals: () => $ZodCheckSizeEquals, - $ZodCheckStartsWith: () => $ZodCheckStartsWith, - $ZodCheckStringFormat: () => $ZodCheckStringFormat, - $ZodCheckUpperCase: () => $ZodCheckUpperCase, - $ZodCodec: () => $ZodCodec, - $ZodCustom: () => $ZodCustom, - $ZodCustomStringFormat: () => $ZodCustomStringFormat, - $ZodDate: () => $ZodDate, - $ZodDefault: () => $ZodDefault, - $ZodDiscriminatedUnion: () => $ZodDiscriminatedUnion, - $ZodE164: () => $ZodE164, - $ZodEmail: () => $ZodEmail, - $ZodEmoji: () => $ZodEmoji, - $ZodEncodeError: () => $ZodEncodeError, - $ZodEnum: () => $ZodEnum, - $ZodError: () => $ZodError, - $ZodExactOptional: () => $ZodExactOptional, - $ZodFile: () => $ZodFile, - $ZodFunction: () => $ZodFunction, - $ZodGUID: () => $ZodGUID, - $ZodIPv4: () => $ZodIPv4, - $ZodIPv6: () => $ZodIPv6, - $ZodISODate: () => $ZodISODate, - $ZodISODateTime: () => $ZodISODateTime, - $ZodISODuration: () => $ZodISODuration, - $ZodISOTime: () => $ZodISOTime, - $ZodIntersection: () => $ZodIntersection, - $ZodJWT: () => $ZodJWT, - $ZodKSUID: () => $ZodKSUID, - $ZodLazy: () => $ZodLazy, - $ZodLiteral: () => $ZodLiteral, - $ZodMAC: () => $ZodMAC, - $ZodMap: () => $ZodMap, - $ZodNaN: () => $ZodNaN, - $ZodNanoID: () => $ZodNanoID, - $ZodNever: () => $ZodNever, - $ZodNonOptional: () => $ZodNonOptional, - $ZodNull: () => $ZodNull, - $ZodNullable: () => $ZodNullable, - $ZodNumber: () => $ZodNumber, - $ZodNumberFormat: () => $ZodNumberFormat, - $ZodObject: () => $ZodObject, - $ZodObjectJIT: () => $ZodObjectJIT, - $ZodOptional: () => $ZodOptional, - $ZodPipe: () => $ZodPipe, - $ZodPrefault: () => $ZodPrefault, - $ZodPromise: () => $ZodPromise, - $ZodReadonly: () => $ZodReadonly, - $ZodRealError: () => $ZodRealError, - $ZodRecord: () => $ZodRecord, - $ZodRegistry: () => $ZodRegistry, - $ZodSet: () => $ZodSet, - $ZodString: () => $ZodString, - $ZodStringFormat: () => $ZodStringFormat, - $ZodSuccess: () => $ZodSuccess, - $ZodSymbol: () => $ZodSymbol, - $ZodTemplateLiteral: () => $ZodTemplateLiteral, - $ZodTransform: () => $ZodTransform, - $ZodTuple: () => $ZodTuple, - $ZodType: () => $ZodType, - $ZodULID: () => $ZodULID, - $ZodURL: () => $ZodURL, - $ZodUUID: () => $ZodUUID, - $ZodUndefined: () => $ZodUndefined, - $ZodUnion: () => $ZodUnion, - $ZodUnknown: () => $ZodUnknown, - $ZodVoid: () => $ZodVoid, - $ZodXID: () => $ZodXID, - $ZodXor: () => $ZodXor, - $brand: () => $brand, - $constructor: () => $constructor, - $input: () => $input, - $output: () => $output, - Doc: () => Doc, - JSONSchema: () => json_schema_exports, - JSONSchemaGenerator: () => JSONSchemaGenerator, - NEVER: () => NEVER2, - TimePrecision: () => TimePrecision, - _any: () => _any, - _array: () => _array, - _base64: () => _base64, - _base64url: () => _base64url, - _bigint: () => _bigint, - _boolean: () => _boolean, - _catch: () => _catch, - _check: () => _check, - _cidrv4: () => _cidrv4, - _cidrv6: () => _cidrv6, - _coercedBigint: () => _coercedBigint, - _coercedBoolean: () => _coercedBoolean, - _coercedDate: () => _coercedDate, - _coercedNumber: () => _coercedNumber, - _coercedString: () => _coercedString, - _cuid: () => _cuid, - _cuid2: () => _cuid2, - _custom: () => _custom, - _date: () => _date, - _decode: () => _decode, - _decodeAsync: () => _decodeAsync, - _default: () => _default, - _discriminatedUnion: () => _discriminatedUnion, - _e164: () => _e164, - _email: () => _email, - _emoji: () => _emoji2, - _encode: () => _encode, - _encodeAsync: () => _encodeAsync, - _endsWith: () => _endsWith, - _enum: () => _enum, - _file: () => _file, - _float32: () => _float32, - _float64: () => _float64, - _gt: () => _gt, - _gte: () => _gte, - _guid: () => _guid, - _includes: () => _includes, - _int: () => _int, - _int32: () => _int32, - _int64: () => _int64, - _intersection: () => _intersection, - _ipv4: () => _ipv4, - _ipv6: () => _ipv6, - _isoDate: () => _isoDate, - _isoDateTime: () => _isoDateTime, - _isoDuration: () => _isoDuration, - _isoTime: () => _isoTime, - _jwt: () => _jwt, - _ksuid: () => _ksuid, - _lazy: () => _lazy, - _length: () => _length, - _literal: () => _literal, - _lowercase: () => _lowercase, - _lt: () => _lt, - _lte: () => _lte, - _mac: () => _mac, - _map: () => _map, - _max: () => _lte, - _maxLength: () => _maxLength, - _maxSize: () => _maxSize, - _mime: () => _mime, - _min: () => _gte, - _minLength: () => _minLength, - _minSize: () => _minSize, - _multipleOf: () => _multipleOf, - _nan: () => _nan, - _nanoid: () => _nanoid, - _nativeEnum: () => _nativeEnum, - _negative: () => _negative, - _never: () => _never, - _nonnegative: () => _nonnegative, - _nonoptional: () => _nonoptional, - _nonpositive: () => _nonpositive, - _normalize: () => _normalize, - _null: () => _null2, - _nullable: () => _nullable, - _number: () => _number, - _optional: () => _optional, - _overwrite: () => _overwrite, - _parse: () => _parse, - _parseAsync: () => _parseAsync, - _pipe: () => _pipe, - _positive: () => _positive, - _promise: () => _promise, - _property: () => _property, - _readonly: () => _readonly, - _record: () => _record, - _refine: () => _refine, - _regex: () => _regex, - _safeDecode: () => _safeDecode, - _safeDecodeAsync: () => _safeDecodeAsync, - _safeEncode: () => _safeEncode, - _safeEncodeAsync: () => _safeEncodeAsync, - _safeParse: () => _safeParse, - _safeParseAsync: () => _safeParseAsync, - _set: () => _set, - _size: () => _size, - _slugify: () => _slugify, - _startsWith: () => _startsWith, - _string: () => _string, - _stringFormat: () => _stringFormat, - _stringbool: () => _stringbool, - _success: () => _success, - _superRefine: () => _superRefine, - _symbol: () => _symbol, - _templateLiteral: () => _templateLiteral, - _toLowerCase: () => _toLowerCase, - _toUpperCase: () => _toUpperCase, - _transform: () => _transform, - _trim: () => _trim, - _tuple: () => _tuple, - _uint32: () => _uint32, - _uint64: () => _uint64, - _ulid: () => _ulid, - _undefined: () => _undefined2, - _union: () => _union, - _unknown: () => _unknown, - _uppercase: () => _uppercase, - _url: () => _url, - _uuid: () => _uuid, - _uuidv4: () => _uuidv4, - _uuidv6: () => _uuidv6, - _uuidv7: () => _uuidv7, - _void: () => _void, - _xid: () => _xid, - _xor: () => _xor, - clone: () => clone2, - config: () => config, - createStandardJSONSchemaMethod: () => createStandardJSONSchemaMethod, - createToJSONSchemaMethod: () => createToJSONSchemaMethod, - decode: () => decode3, - decodeAsync: () => decodeAsync, - describe: () => describe, - encode: () => encode4, - encodeAsync: () => encodeAsync, - extractDefs: () => extractDefs, - finalize: () => finalize, - flattenError: () => flattenError, - formatError: () => formatError, - globalConfig: () => globalConfig, - globalRegistry: () => globalRegistry, - initializeContext: () => initializeContext, - isValidBase64: () => isValidBase64, - isValidBase64URL: () => isValidBase64URL, - isValidJWT: () => isValidJWT2, - locales: () => locales_exports, - meta: () => meta, - parse: () => parse2, - parseAsync: () => parseAsync, - prettifyError: () => prettifyError, - process: () => process2, - regexes: () => regexes_exports, - registry: () => registry, - safeDecode: () => safeDecode, - safeDecodeAsync: () => safeDecodeAsync, - safeEncode: () => safeEncode, - safeEncodeAsync: () => safeEncodeAsync, - safeParse: () => safeParse, - safeParseAsync: () => safeParseAsync, - toDotPath: () => toDotPath, - toJSONSchema: () => toJSONSchema, - treeifyError: () => treeifyError, - util: () => util_exports, - version: () => version2 -}); -var init_core2 = __esm({ - "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/index.js"() { - init_core(); - init_parse(); - init_errors8(); - init_schemas(); - init_checks2(); - init_versions(); - init_util(); - init_regexes(); - init_locales(); - init_registries(); - init_doc(); - init_api(); - init_to_json_schema(); - init_json_schema_processors(); - init_json_schema_generator(); - init_json_schema(); - } -}); - -// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/checks.js -var checks_exports2 = {}; -__export(checks_exports2, { - endsWith: () => _endsWith, - gt: () => _gt, - gte: () => _gte, - includes: () => _includes, - length: () => _length, - lowercase: () => _lowercase, - lt: () => _lt, - lte: () => _lte, - maxLength: () => _maxLength, - maxSize: () => _maxSize, - mime: () => _mime, - minLength: () => _minLength, - minSize: () => _minSize, - multipleOf: () => _multipleOf, - negative: () => _negative, - nonnegative: () => _nonnegative, - nonpositive: () => _nonpositive, - normalize: () => _normalize, - overwrite: () => _overwrite, - positive: () => _positive, - property: () => _property, - regex: () => _regex, - size: () => _size, - slugify: () => _slugify, - startsWith: () => _startsWith, - toLowerCase: () => _toLowerCase, - toUpperCase: () => _toUpperCase, - trim: () => _trim, - uppercase: () => _uppercase -}); -var init_checks3 = __esm({ - "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/checks.js"() { - init_core2(); - } -}); - -// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/iso.js -var iso_exports = {}; -__export(iso_exports, { - ZodISODate: () => ZodISODate, - ZodISODateTime: () => ZodISODateTime, - ZodISODuration: () => ZodISODuration, - ZodISOTime: () => ZodISOTime, - date: () => date4, - datetime: () => datetime2, - duration: () => duration2, - time: () => time4 -}); -function datetime2(params) { - return _isoDateTime(ZodISODateTime, params); -} -function date4(params) { - return _isoDate(ZodISODate, params); -} -function time4(params) { - return _isoTime(ZodISOTime, params); -} -function duration2(params) { - return _isoDuration(ZodISODuration, params); -} -var ZodISODateTime, ZodISODate, ZodISOTime, ZodISODuration; -var init_iso = __esm({ - "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/iso.js"() { - init_core2(); - init_schemas2(); - ZodISODateTime = /* @__PURE__ */ $constructor("ZodISODateTime", (inst, def) => { - $ZodISODateTime.init(inst, def); - ZodStringFormat.init(inst, def); - }); - ZodISODate = /* @__PURE__ */ $constructor("ZodISODate", (inst, def) => { - $ZodISODate.init(inst, def); - ZodStringFormat.init(inst, def); - }); - ZodISOTime = /* @__PURE__ */ $constructor("ZodISOTime", (inst, def) => { - $ZodISOTime.init(inst, def); - ZodStringFormat.init(inst, def); - }); - ZodISODuration = /* @__PURE__ */ $constructor("ZodISODuration", (inst, def) => { - $ZodISODuration.init(inst, def); - ZodStringFormat.init(inst, def); - }); - } -}); - -// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/errors.js -var initializer2, ZodError2, ZodRealError; -var init_errors9 = __esm({ - "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/errors.js"() { - init_core2(); - init_core2(); - init_util(); - initializer2 = (inst, issues2) => { - $ZodError.init(inst, issues2); - inst.name = "ZodError"; - Object.defineProperties(inst, { - format: { - value: (mapper) => formatError(inst, mapper) - // enumerable: false, - }, - flatten: { - value: (mapper) => flattenError(inst, mapper) - // enumerable: false, - }, - addIssue: { - value: (issue2) => { - inst.issues.push(issue2); - inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2); - } - // enumerable: false, - }, - addIssues: { - value: (issues3) => { - inst.issues.push(...issues3); - inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2); - } - // enumerable: false, - }, - isEmpty: { - get() { - return inst.issues.length === 0; - } - // enumerable: false, - } - }); - }; - ZodError2 = $constructor("ZodError", initializer2); - ZodRealError = $constructor("ZodError", initializer2, { - Parent: Error - }); - } -}); - -// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/parse.js -var parse3, parseAsync2, safeParse2, safeParseAsync2, encode5, decode4, encodeAsync2, decodeAsync2, safeEncode2, safeDecode2, safeEncodeAsync2, safeDecodeAsync2; -var init_parse2 = __esm({ - "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/parse.js"() { - init_core2(); - init_errors9(); - parse3 = /* @__PURE__ */ _parse(ZodRealError); - parseAsync2 = /* @__PURE__ */ _parseAsync(ZodRealError); - safeParse2 = /* @__PURE__ */ _safeParse(ZodRealError); - safeParseAsync2 = /* @__PURE__ */ _safeParseAsync(ZodRealError); - encode5 = /* @__PURE__ */ _encode(ZodRealError); - decode4 = /* @__PURE__ */ _decode(ZodRealError); - encodeAsync2 = /* @__PURE__ */ _encodeAsync(ZodRealError); - decodeAsync2 = /* @__PURE__ */ _decodeAsync(ZodRealError); - safeEncode2 = /* @__PURE__ */ _safeEncode(ZodRealError); - safeDecode2 = /* @__PURE__ */ _safeDecode(ZodRealError); - safeEncodeAsync2 = /* @__PURE__ */ _safeEncodeAsync(ZodRealError); - safeDecodeAsync2 = /* @__PURE__ */ _safeDecodeAsync(ZodRealError); - } -}); - -// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/schemas.js -var schemas_exports2 = {}; -__export(schemas_exports2, { - ZodAny: () => ZodAny2, - ZodArray: () => ZodArray2, - ZodBase64: () => ZodBase64, - ZodBase64URL: () => ZodBase64URL, - ZodBigInt: () => ZodBigInt2, - ZodBigIntFormat: () => ZodBigIntFormat, - ZodBoolean: () => ZodBoolean2, - ZodCIDRv4: () => ZodCIDRv4, - ZodCIDRv6: () => ZodCIDRv6, - ZodCUID: () => ZodCUID, - ZodCUID2: () => ZodCUID2, - ZodCatch: () => ZodCatch2, - ZodCodec: () => ZodCodec, - ZodCustom: () => ZodCustom, - ZodCustomStringFormat: () => ZodCustomStringFormat, - ZodDate: () => ZodDate2, - ZodDefault: () => ZodDefault2, - ZodDiscriminatedUnion: () => ZodDiscriminatedUnion2, - ZodE164: () => ZodE164, - ZodEmail: () => ZodEmail, - ZodEmoji: () => ZodEmoji, - ZodEnum: () => ZodEnum2, - ZodExactOptional: () => ZodExactOptional, - ZodFile: () => ZodFile, - ZodFunction: () => ZodFunction2, - ZodGUID: () => ZodGUID, - ZodIPv4: () => ZodIPv4, - ZodIPv6: () => ZodIPv6, - ZodIntersection: () => ZodIntersection2, - ZodJWT: () => ZodJWT, - ZodKSUID: () => ZodKSUID, - ZodLazy: () => ZodLazy2, - ZodLiteral: () => ZodLiteral2, - ZodMAC: () => ZodMAC, - ZodMap: () => ZodMap2, - ZodNaN: () => ZodNaN2, - ZodNanoID: () => ZodNanoID, - ZodNever: () => ZodNever2, - ZodNonOptional: () => ZodNonOptional, - ZodNull: () => ZodNull2, - ZodNullable: () => ZodNullable2, - ZodNumber: () => ZodNumber2, - ZodNumberFormat: () => ZodNumberFormat, - ZodObject: () => ZodObject2, - ZodOptional: () => ZodOptional2, - ZodPipe: () => ZodPipe, - ZodPrefault: () => ZodPrefault, - ZodPromise: () => ZodPromise2, - ZodReadonly: () => ZodReadonly2, - ZodRecord: () => ZodRecord2, - ZodSet: () => ZodSet2, - ZodString: () => ZodString2, - ZodStringFormat: () => ZodStringFormat, - ZodSuccess: () => ZodSuccess, - ZodSymbol: () => ZodSymbol2, - ZodTemplateLiteral: () => ZodTemplateLiteral, - ZodTransform: () => ZodTransform, - ZodTuple: () => ZodTuple2, - ZodType: () => ZodType2, - ZodULID: () => ZodULID, - ZodURL: () => ZodURL, - ZodUUID: () => ZodUUID, - ZodUndefined: () => ZodUndefined2, - ZodUnion: () => ZodUnion2, - ZodUnknown: () => ZodUnknown2, - ZodVoid: () => ZodVoid2, - ZodXID: () => ZodXID, - ZodXor: () => ZodXor, - _ZodString: () => _ZodString, - _default: () => _default2, - _function: () => _function, - any: () => any, - array: () => array, - base64: () => base642, - base64url: () => base64url2, - bigint: () => bigint3, - boolean: () => boolean3, - catch: () => _catch2, - check: () => check2, - cidrv4: () => cidrv42, - cidrv6: () => cidrv62, - codec: () => codec, - cuid: () => cuid3, - cuid2: () => cuid22, - custom: () => custom2, - date: () => date5, - describe: () => describe2, - discriminatedUnion: () => discriminatedUnion, - e164: () => e1642, - email: () => email2, - emoji: () => emoji2, - enum: () => _enum2, - exactOptional: () => exactOptional, - file: () => file, - float32: () => float32, - float64: () => float64, - function: () => _function, - guid: () => guid2, - hash: () => hash, - hex: () => hex2, - hostname: () => hostname2, - httpUrl: () => httpUrl, - instanceof: () => _instanceof, - int: () => int, - int32: () => int32, - int64: () => int64, - intersection: () => intersection, - ipv4: () => ipv42, - ipv6: () => ipv62, - json: () => json2, - jwt: () => jwt, - keyof: () => keyof, - ksuid: () => ksuid2, - lazy: () => lazy, - literal: () => literal, - looseObject: () => looseObject, - looseRecord: () => looseRecord, - mac: () => mac2, - map: () => map2, - meta: () => meta2, - nan: () => nan, - nanoid: () => nanoid2, - nativeEnum: () => nativeEnum, - never: () => never, - nonoptional: () => nonoptional, - null: () => _null3, - nullable: () => nullable, - nullish: () => nullish2, - number: () => number2, - object: () => object, - optional: () => optional, - partialRecord: () => partialRecord, - pipe: () => pipe, - prefault: () => prefault, - preprocess: () => preprocess, - promise: () => promise, - readonly: () => readonly, - record: () => record, - refine: () => refine, - set: () => set, - strictObject: () => strictObject, - string: () => string2, - stringFormat: () => stringFormat, - stringbool: () => stringbool, - success: () => success, - superRefine: () => superRefine, - symbol: () => symbol, - templateLiteral: () => templateLiteral, - transform: () => transform, - tuple: () => tuple, - uint32: () => uint32, - uint64: () => uint64, - ulid: () => ulid2, - undefined: () => _undefined3, - union: () => union2, - unknown: () => unknown, - url: () => url, - uuid: () => uuid3, - uuidv4: () => uuidv4, - uuidv6: () => uuidv6, - uuidv7: () => uuidv7, - void: () => _void2, - xid: () => xid2, - xor: () => xor2 -}); -function string2(params) { - return _string(ZodString2, params); -} -function email2(params) { - return _email(ZodEmail, params); -} -function guid2(params) { - return _guid(ZodGUID, params); -} -function uuid3(params) { - return _uuid(ZodUUID, params); -} -function uuidv4(params) { - return _uuidv4(ZodUUID, params); -} -function uuidv6(params) { - return _uuidv6(ZodUUID, params); -} -function uuidv7(params) { - return _uuidv7(ZodUUID, params); -} -function url(params) { - return _url(ZodURL, params); -} -function httpUrl(params) { - return _url(ZodURL, { - protocol: /^https?$/, - hostname: regexes_exports.domain, - ...util_exports.normalizeParams(params) - }); -} -function emoji2(params) { - return _emoji2(ZodEmoji, params); -} -function nanoid2(params) { - return _nanoid(ZodNanoID, params); -} -function cuid3(params) { - return _cuid(ZodCUID, params); -} -function cuid22(params) { - return _cuid2(ZodCUID2, params); -} -function ulid2(params) { - return _ulid(ZodULID, params); -} -function xid2(params) { - return _xid(ZodXID, params); -} -function ksuid2(params) { - return _ksuid(ZodKSUID, params); -} -function ipv42(params) { - return _ipv4(ZodIPv4, params); -} -function mac2(params) { - return _mac(ZodMAC, params); -} -function ipv62(params) { - return _ipv6(ZodIPv6, params); -} -function cidrv42(params) { - return _cidrv4(ZodCIDRv4, params); -} -function cidrv62(params) { - return _cidrv6(ZodCIDRv6, params); -} -function base642(params) { - return _base64(ZodBase64, params); -} -function base64url2(params) { - return _base64url(ZodBase64URL, params); -} -function e1642(params) { - return _e164(ZodE164, params); -} -function jwt(params) { - return _jwt(ZodJWT, params); -} -function stringFormat(format2, fnOrRegex, _params = {}) { - return _stringFormat(ZodCustomStringFormat, format2, fnOrRegex, _params); -} -function hostname2(_params) { - return _stringFormat(ZodCustomStringFormat, "hostname", regexes_exports.hostname, _params); -} -function hex2(_params) { - return _stringFormat(ZodCustomStringFormat, "hex", regexes_exports.hex, _params); -} -function hash(alg2, params) { - const enc2 = params?.enc ?? "hex"; - const format2 = `${alg2}_${enc2}`; - const regex = regexes_exports[format2]; - if (!regex) - throw new Error(`Unrecognized hash format: ${format2}`); - return _stringFormat(ZodCustomStringFormat, format2, regex, params); -} -function number2(params) { - return _number(ZodNumber2, params); -} -function int(params) { - return _int(ZodNumberFormat, params); -} -function float32(params) { - return _float32(ZodNumberFormat, params); -} -function float64(params) { - return _float64(ZodNumberFormat, params); -} -function int32(params) { - return _int32(ZodNumberFormat, params); -} -function uint32(params) { - return _uint32(ZodNumberFormat, params); -} -function boolean3(params) { - return _boolean(ZodBoolean2, params); -} -function bigint3(params) { - return _bigint(ZodBigInt2, params); -} -function int64(params) { - return _int64(ZodBigIntFormat, params); -} -function uint64(params) { - return _uint64(ZodBigIntFormat, params); -} -function symbol(params) { - return _symbol(ZodSymbol2, params); -} -function _undefined3(params) { - return _undefined2(ZodUndefined2, params); -} -function _null3(params) { - return _null2(ZodNull2, params); -} -function any() { - return _any(ZodAny2); -} -function unknown() { - return _unknown(ZodUnknown2); -} -function never(params) { - return _never(ZodNever2, params); -} -function _void2(params) { - return _void(ZodVoid2, params); -} -function date5(params) { - return _date(ZodDate2, params); -} -function array(element, params) { - return _array(ZodArray2, element, params); -} -function keyof(schema2) { - const shape = schema2._zod.def.shape; - return _enum2(Object.keys(shape)); -} -function object(shape, params) { - const def = { - type: "object", - shape: shape ?? {}, - ...util_exports.normalizeParams(params) - }; - return new ZodObject2(def); -} -function strictObject(shape, params) { - return new ZodObject2({ - type: "object", - shape, - catchall: never(), - ...util_exports.normalizeParams(params) - }); -} -function looseObject(shape, params) { - return new ZodObject2({ - type: "object", - shape, - catchall: unknown(), - ...util_exports.normalizeParams(params) - }); -} -function union2(options, params) { - return new ZodUnion2({ - type: "union", - options, - ...util_exports.normalizeParams(params) - }); -} -function xor2(options, params) { - return new ZodXor({ - type: "union", - options, - inclusive: false, - ...util_exports.normalizeParams(params) - }); -} -function discriminatedUnion(discriminator, options, params) { - return new ZodDiscriminatedUnion2({ - type: "union", - options, - discriminator, - ...util_exports.normalizeParams(params) - }); -} -function intersection(left, right) { - return new ZodIntersection2({ - type: "intersection", - left, - right - }); -} -function tuple(items, _paramsOrRest, _params) { - const hasRest = _paramsOrRest instanceof $ZodType; - const params = hasRest ? _params : _paramsOrRest; - const rest = hasRest ? _paramsOrRest : null; - return new ZodTuple2({ - type: "tuple", - items, - rest, - ...util_exports.normalizeParams(params) - }); -} -function record(keyType, valueType, params) { - return new ZodRecord2({ - type: "record", - keyType, - valueType, - ...util_exports.normalizeParams(params) - }); -} -function partialRecord(keyType, valueType, params) { - const k5 = clone2(keyType); - k5._zod.values = void 0; - return new ZodRecord2({ - type: "record", - keyType: k5, - valueType, - ...util_exports.normalizeParams(params) - }); -} -function looseRecord(keyType, valueType, params) { - return new ZodRecord2({ - type: "record", - keyType, - valueType, - mode: "loose", - ...util_exports.normalizeParams(params) - }); -} -function map2(keyType, valueType, params) { - return new ZodMap2({ - type: "map", - keyType, - valueType, - ...util_exports.normalizeParams(params) - }); -} -function set(valueType, params) { - return new ZodSet2({ - type: "set", - valueType, - ...util_exports.normalizeParams(params) - }); -} -function _enum2(values2, params) { - const entries2 = Array.isArray(values2) ? Object.fromEntries(values2.map((v5) => [v5, v5])) : values2; - return new ZodEnum2({ - type: "enum", - entries: entries2, - ...util_exports.normalizeParams(params) - }); -} -function nativeEnum(entries2, params) { - return new ZodEnum2({ - type: "enum", - entries: entries2, - ...util_exports.normalizeParams(params) - }); -} -function literal(value, params) { - return new ZodLiteral2({ - type: "literal", - values: Array.isArray(value) ? value : [value], - ...util_exports.normalizeParams(params) - }); -} -function file(params) { - return _file(ZodFile, params); -} -function transform(fn) { - return new ZodTransform({ - type: "transform", - transform: fn - }); -} -function optional(innerType) { - return new ZodOptional2({ - type: "optional", - innerType - }); -} -function exactOptional(innerType) { - return new ZodExactOptional({ - type: "optional", - innerType - }); -} -function nullable(innerType) { - return new ZodNullable2({ - type: "nullable", - innerType - }); -} -function nullish2(innerType) { - return optional(nullable(innerType)); -} -function _default2(innerType, defaultValue) { - return new ZodDefault2({ - type: "default", - innerType, - get defaultValue() { - return typeof defaultValue === "function" ? defaultValue() : util_exports.shallowClone(defaultValue); - } - }); -} -function prefault(innerType, defaultValue) { - return new ZodPrefault({ - type: "prefault", - innerType, - get defaultValue() { - return typeof defaultValue === "function" ? defaultValue() : util_exports.shallowClone(defaultValue); - } - }); -} -function nonoptional(innerType, params) { - return new ZodNonOptional({ - type: "nonoptional", - innerType, - ...util_exports.normalizeParams(params) - }); -} -function success(innerType) { - return new ZodSuccess({ - type: "success", - innerType - }); -} -function _catch2(innerType, catchValue) { - return new ZodCatch2({ - type: "catch", - innerType, - catchValue: typeof catchValue === "function" ? catchValue : () => catchValue - }); -} -function nan(params) { - return _nan(ZodNaN2, params); -} -function pipe(in_, out) { - return new ZodPipe({ - type: "pipe", - in: in_, - out - // ...util.normalizeParams(params), - }); -} -function codec(in_, out, params) { - return new ZodCodec({ - type: "pipe", - in: in_, - out, - transform: params.decode, - reverseTransform: params.encode - }); -} -function readonly(innerType) { - return new ZodReadonly2({ - type: "readonly", - innerType - }); -} -function templateLiteral(parts, params) { - return new ZodTemplateLiteral({ - type: "template_literal", - parts, - ...util_exports.normalizeParams(params) - }); -} -function lazy(getter) { - return new ZodLazy2({ - type: "lazy", - getter - }); -} -function promise(innerType) { - return new ZodPromise2({ - type: "promise", - innerType - }); -} -function _function(params) { - return new ZodFunction2({ - type: "function", - input: Array.isArray(params?.input) ? tuple(params?.input) : params?.input ?? array(unknown()), - output: params?.output ?? unknown() - }); -} -function check2(fn) { - const ch = new $ZodCheck({ - check: "custom" - // ...util.normalizeParams(params), - }); - ch._zod.check = fn; - return ch; -} -function custom2(fn, _params) { - return _custom(ZodCustom, fn ?? (() => true), _params); -} -function refine(fn, _params = {}) { - return _refine(ZodCustom, fn, _params); -} -function superRefine(fn) { - return _superRefine(fn); -} -function _instanceof(cls, params = {}) { - const inst = new ZodCustom({ - type: "custom", - check: "custom", - fn: (data2) => data2 instanceof cls, - abort: true, - ...util_exports.normalizeParams(params) - }); - inst._zod.bag.Class = cls; - inst._zod.check = (payload2) => { - if (!(payload2.value instanceof cls)) { - payload2.issues.push({ - code: "invalid_type", - expected: cls.name, - input: payload2.value, - inst, - path: [...inst._zod.def.path ?? []] - }); - } - }; - return inst; -} -function json2(params) { - const jsonSchema = lazy(() => { - return union2([string2(params), number2(), boolean3(), _null3(), array(jsonSchema), record(string2(), jsonSchema)]); - }); - return jsonSchema; -} -function preprocess(fn, schema2) { - return pipe(transform(fn), schema2); -} -var ZodType2, _ZodString, ZodString2, ZodStringFormat, ZodEmail, ZodGUID, ZodUUID, ZodURL, ZodEmoji, ZodNanoID, ZodCUID, ZodCUID2, ZodULID, ZodXID, ZodKSUID, ZodIPv4, ZodMAC, ZodIPv6, ZodCIDRv4, ZodCIDRv6, ZodBase64, ZodBase64URL, ZodE164, ZodJWT, ZodCustomStringFormat, ZodNumber2, ZodNumberFormat, ZodBoolean2, ZodBigInt2, ZodBigIntFormat, ZodSymbol2, ZodUndefined2, ZodNull2, ZodAny2, ZodUnknown2, ZodNever2, ZodVoid2, ZodDate2, ZodArray2, ZodObject2, ZodUnion2, ZodXor, ZodDiscriminatedUnion2, ZodIntersection2, ZodTuple2, ZodRecord2, ZodMap2, ZodSet2, ZodEnum2, ZodLiteral2, ZodFile, ZodTransform, ZodOptional2, ZodExactOptional, ZodNullable2, ZodDefault2, ZodPrefault, ZodNonOptional, ZodSuccess, ZodCatch2, ZodNaN2, ZodPipe, ZodCodec, ZodReadonly2, ZodTemplateLiteral, ZodLazy2, ZodPromise2, ZodFunction2, ZodCustom, describe2, meta2, stringbool; -var init_schemas2 = __esm({ - "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/schemas.js"() { - init_core2(); - init_core2(); - init_json_schema_processors(); - init_to_json_schema(); - init_checks3(); - init_iso(); - init_parse2(); - ZodType2 = /* @__PURE__ */ $constructor("ZodType", (inst, def) => { - $ZodType.init(inst, def); - Object.assign(inst["~standard"], { - jsonSchema: { - input: createStandardJSONSchemaMethod(inst, "input"), - output: createStandardJSONSchemaMethod(inst, "output") - } - }); - inst.toJSONSchema = createToJSONSchemaMethod(inst, {}); - inst.def = def; - inst.type = def.type; - Object.defineProperty(inst, "_def", { value: def }); - inst.check = (...checks) => { - return inst.clone(util_exports.mergeDefs(def, { - checks: [ - ...def.checks ?? [], - ...checks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch) - ] - }), { - parent: true - }); - }; - inst.with = inst.check; - inst.clone = (def2, params) => clone2(inst, def2, params); - inst.brand = () => inst; - inst.register = ((reg, meta3) => { - reg.add(inst, meta3); - return inst; - }); - inst.parse = (data2, params) => parse3(inst, data2, params, { callee: inst.parse }); - inst.safeParse = (data2, params) => safeParse2(inst, data2, params); - inst.parseAsync = async (data2, params) => parseAsync2(inst, data2, params, { callee: inst.parseAsync }); - inst.safeParseAsync = async (data2, params) => safeParseAsync2(inst, data2, params); - inst.spa = inst.safeParseAsync; - inst.encode = (data2, params) => encode5(inst, data2, params); - inst.decode = (data2, params) => decode4(inst, data2, params); - inst.encodeAsync = async (data2, params) => encodeAsync2(inst, data2, params); - inst.decodeAsync = async (data2, params) => decodeAsync2(inst, data2, params); - inst.safeEncode = (data2, params) => safeEncode2(inst, data2, params); - inst.safeDecode = (data2, params) => safeDecode2(inst, data2, params); - inst.safeEncodeAsync = async (data2, params) => safeEncodeAsync2(inst, data2, params); - inst.safeDecodeAsync = async (data2, params) => safeDecodeAsync2(inst, data2, params); - inst.refine = (check3, params) => inst.check(refine(check3, params)); - inst.superRefine = (refinement) => inst.check(superRefine(refinement)); - inst.overwrite = (fn) => inst.check(_overwrite(fn)); - inst.optional = () => optional(inst); - inst.exactOptional = () => exactOptional(inst); - inst.nullable = () => nullable(inst); - inst.nullish = () => optional(nullable(inst)); - inst.nonoptional = (params) => nonoptional(inst, params); - inst.array = () => array(inst); - inst.or = (arg) => union2([inst, arg]); - inst.and = (arg) => intersection(inst, arg); - inst.transform = (tx) => pipe(inst, transform(tx)); - inst.default = (def2) => _default2(inst, def2); - inst.prefault = (def2) => prefault(inst, def2); - inst.catch = (params) => _catch2(inst, params); - inst.pipe = (target) => pipe(inst, target); - inst.readonly = () => readonly(inst); - inst.describe = (description) => { - const cl = inst.clone(); - globalRegistry.add(cl, { description }); - return cl; - }; - Object.defineProperty(inst, "description", { - get() { - return globalRegistry.get(inst)?.description; - }, - configurable: true - }); - inst.meta = (...args) => { - if (args.length === 0) { - return globalRegistry.get(inst); - } - const cl = inst.clone(); - globalRegistry.add(cl, args[0]); - return cl; - }; - inst.isOptional = () => inst.safeParse(void 0).success; - inst.isNullable = () => inst.safeParse(null).success; - inst.apply = (fn) => fn(inst); - return inst; - }); - _ZodString = /* @__PURE__ */ $constructor("_ZodString", (inst, def) => { - $ZodString.init(inst, def); - ZodType2.init(inst, def); - inst._zod.processJSONSchema = (ctx, json3, params) => stringProcessor(inst, ctx, json3, params); - const bag = inst._zod.bag; - inst.format = bag.format ?? null; - inst.minLength = bag.minimum ?? null; - inst.maxLength = bag.maximum ?? null; - inst.regex = (...args) => inst.check(_regex(...args)); - inst.includes = (...args) => inst.check(_includes(...args)); - inst.startsWith = (...args) => inst.check(_startsWith(...args)); - inst.endsWith = (...args) => inst.check(_endsWith(...args)); - inst.min = (...args) => inst.check(_minLength(...args)); - inst.max = (...args) => inst.check(_maxLength(...args)); - inst.length = (...args) => inst.check(_length(...args)); - inst.nonempty = (...args) => inst.check(_minLength(1, ...args)); - inst.lowercase = (params) => inst.check(_lowercase(params)); - inst.uppercase = (params) => inst.check(_uppercase(params)); - inst.trim = () => inst.check(_trim()); - inst.normalize = (...args) => inst.check(_normalize(...args)); - inst.toLowerCase = () => inst.check(_toLowerCase()); - inst.toUpperCase = () => inst.check(_toUpperCase()); - inst.slugify = () => inst.check(_slugify()); - }); - ZodString2 = /* @__PURE__ */ $constructor("ZodString", (inst, def) => { - $ZodString.init(inst, def); - _ZodString.init(inst, def); - inst.email = (params) => inst.check(_email(ZodEmail, params)); - inst.url = (params) => inst.check(_url(ZodURL, params)); - inst.jwt = (params) => inst.check(_jwt(ZodJWT, params)); - inst.emoji = (params) => inst.check(_emoji2(ZodEmoji, params)); - inst.guid = (params) => inst.check(_guid(ZodGUID, params)); - inst.uuid = (params) => inst.check(_uuid(ZodUUID, params)); - inst.uuidv4 = (params) => inst.check(_uuidv4(ZodUUID, params)); - inst.uuidv6 = (params) => inst.check(_uuidv6(ZodUUID, params)); - inst.uuidv7 = (params) => inst.check(_uuidv7(ZodUUID, params)); - inst.nanoid = (params) => inst.check(_nanoid(ZodNanoID, params)); - inst.guid = (params) => inst.check(_guid(ZodGUID, params)); - inst.cuid = (params) => inst.check(_cuid(ZodCUID, params)); - inst.cuid2 = (params) => inst.check(_cuid2(ZodCUID2, params)); - inst.ulid = (params) => inst.check(_ulid(ZodULID, params)); - inst.base64 = (params) => inst.check(_base64(ZodBase64, params)); - inst.base64url = (params) => inst.check(_base64url(ZodBase64URL, params)); - inst.xid = (params) => inst.check(_xid(ZodXID, params)); - inst.ksuid = (params) => inst.check(_ksuid(ZodKSUID, params)); - inst.ipv4 = (params) => inst.check(_ipv4(ZodIPv4, params)); - inst.ipv6 = (params) => inst.check(_ipv6(ZodIPv6, params)); - inst.cidrv4 = (params) => inst.check(_cidrv4(ZodCIDRv4, params)); - inst.cidrv6 = (params) => inst.check(_cidrv6(ZodCIDRv6, params)); - inst.e164 = (params) => inst.check(_e164(ZodE164, params)); - inst.datetime = (params) => inst.check(datetime2(params)); - inst.date = (params) => inst.check(date4(params)); - inst.time = (params) => inst.check(time4(params)); - inst.duration = (params) => inst.check(duration2(params)); - }); - ZodStringFormat = /* @__PURE__ */ $constructor("ZodStringFormat", (inst, def) => { - $ZodStringFormat.init(inst, def); - _ZodString.init(inst, def); - }); - ZodEmail = /* @__PURE__ */ $constructor("ZodEmail", (inst, def) => { - $ZodEmail.init(inst, def); - ZodStringFormat.init(inst, def); - }); - ZodGUID = /* @__PURE__ */ $constructor("ZodGUID", (inst, def) => { - $ZodGUID.init(inst, def); - ZodStringFormat.init(inst, def); - }); - ZodUUID = /* @__PURE__ */ $constructor("ZodUUID", (inst, def) => { - $ZodUUID.init(inst, def); - ZodStringFormat.init(inst, def); - }); - ZodURL = /* @__PURE__ */ $constructor("ZodURL", (inst, def) => { - $ZodURL.init(inst, def); - ZodStringFormat.init(inst, def); - }); - ZodEmoji = /* @__PURE__ */ $constructor("ZodEmoji", (inst, def) => { - $ZodEmoji.init(inst, def); - ZodStringFormat.init(inst, def); - }); - ZodNanoID = /* @__PURE__ */ $constructor("ZodNanoID", (inst, def) => { - $ZodNanoID.init(inst, def); - ZodStringFormat.init(inst, def); - }); - ZodCUID = /* @__PURE__ */ $constructor("ZodCUID", (inst, def) => { - $ZodCUID.init(inst, def); - ZodStringFormat.init(inst, def); - }); - ZodCUID2 = /* @__PURE__ */ $constructor("ZodCUID2", (inst, def) => { - $ZodCUID2.init(inst, def); - ZodStringFormat.init(inst, def); - }); - ZodULID = /* @__PURE__ */ $constructor("ZodULID", (inst, def) => { - $ZodULID.init(inst, def); - ZodStringFormat.init(inst, def); - }); - ZodXID = /* @__PURE__ */ $constructor("ZodXID", (inst, def) => { - $ZodXID.init(inst, def); - ZodStringFormat.init(inst, def); - }); - ZodKSUID = /* @__PURE__ */ $constructor("ZodKSUID", (inst, def) => { - $ZodKSUID.init(inst, def); - ZodStringFormat.init(inst, def); - }); - ZodIPv4 = /* @__PURE__ */ $constructor("ZodIPv4", (inst, def) => { - $ZodIPv4.init(inst, def); - ZodStringFormat.init(inst, def); - }); - ZodMAC = /* @__PURE__ */ $constructor("ZodMAC", (inst, def) => { - $ZodMAC.init(inst, def); - ZodStringFormat.init(inst, def); - }); - ZodIPv6 = /* @__PURE__ */ $constructor("ZodIPv6", (inst, def) => { - $ZodIPv6.init(inst, def); - ZodStringFormat.init(inst, def); - }); - ZodCIDRv4 = /* @__PURE__ */ $constructor("ZodCIDRv4", (inst, def) => { - $ZodCIDRv4.init(inst, def); - ZodStringFormat.init(inst, def); - }); - ZodCIDRv6 = /* @__PURE__ */ $constructor("ZodCIDRv6", (inst, def) => { - $ZodCIDRv6.init(inst, def); - ZodStringFormat.init(inst, def); - }); - ZodBase64 = /* @__PURE__ */ $constructor("ZodBase64", (inst, def) => { - $ZodBase64.init(inst, def); - ZodStringFormat.init(inst, def); - }); - ZodBase64URL = /* @__PURE__ */ $constructor("ZodBase64URL", (inst, def) => { - $ZodBase64URL.init(inst, def); - ZodStringFormat.init(inst, def); - }); - ZodE164 = /* @__PURE__ */ $constructor("ZodE164", (inst, def) => { - $ZodE164.init(inst, def); - ZodStringFormat.init(inst, def); - }); - ZodJWT = /* @__PURE__ */ $constructor("ZodJWT", (inst, def) => { - $ZodJWT.init(inst, def); - ZodStringFormat.init(inst, def); - }); - ZodCustomStringFormat = /* @__PURE__ */ $constructor("ZodCustomStringFormat", (inst, def) => { - $ZodCustomStringFormat.init(inst, def); - ZodStringFormat.init(inst, def); - }); - ZodNumber2 = /* @__PURE__ */ $constructor("ZodNumber", (inst, def) => { - $ZodNumber.init(inst, def); - ZodType2.init(inst, def); - inst._zod.processJSONSchema = (ctx, json3, params) => numberProcessor(inst, ctx, json3, params); - inst.gt = (value, params) => inst.check(_gt(value, params)); - inst.gte = (value, params) => inst.check(_gte(value, params)); - inst.min = (value, params) => inst.check(_gte(value, params)); - inst.lt = (value, params) => inst.check(_lt(value, params)); - inst.lte = (value, params) => inst.check(_lte(value, params)); - inst.max = (value, params) => inst.check(_lte(value, params)); - inst.int = (params) => inst.check(int(params)); - inst.safe = (params) => inst.check(int(params)); - inst.positive = (params) => inst.check(_gt(0, params)); - inst.nonnegative = (params) => inst.check(_gte(0, params)); - inst.negative = (params) => inst.check(_lt(0, params)); - inst.nonpositive = (params) => inst.check(_lte(0, params)); - inst.multipleOf = (value, params) => inst.check(_multipleOf(value, params)); - inst.step = (value, params) => inst.check(_multipleOf(value, params)); - inst.finite = () => inst; - const bag = inst._zod.bag; - inst.minValue = Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null; - inst.maxValue = Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null; - inst.isInt = (bag.format ?? "").includes("int") || Number.isSafeInteger(bag.multipleOf ?? 0.5); - inst.isFinite = true; - inst.format = bag.format ?? null; - }); - ZodNumberFormat = /* @__PURE__ */ $constructor("ZodNumberFormat", (inst, def) => { - $ZodNumberFormat.init(inst, def); - ZodNumber2.init(inst, def); - }); - ZodBoolean2 = /* @__PURE__ */ $constructor("ZodBoolean", (inst, def) => { - $ZodBoolean.init(inst, def); - ZodType2.init(inst, def); - inst._zod.processJSONSchema = (ctx, json3, params) => booleanProcessor(inst, ctx, json3, params); - }); - ZodBigInt2 = /* @__PURE__ */ $constructor("ZodBigInt", (inst, def) => { - $ZodBigInt.init(inst, def); - ZodType2.init(inst, def); - inst._zod.processJSONSchema = (ctx, json3, params) => bigintProcessor(inst, ctx, json3, params); - inst.gte = (value, params) => inst.check(_gte(value, params)); - inst.min = (value, params) => inst.check(_gte(value, params)); - inst.gt = (value, params) => inst.check(_gt(value, params)); - inst.gte = (value, params) => inst.check(_gte(value, params)); - inst.min = (value, params) => inst.check(_gte(value, params)); - inst.lt = (value, params) => inst.check(_lt(value, params)); - inst.lte = (value, params) => inst.check(_lte(value, params)); - inst.max = (value, params) => inst.check(_lte(value, params)); - inst.positive = (params) => inst.check(_gt(BigInt(0), params)); - inst.negative = (params) => inst.check(_lt(BigInt(0), params)); - inst.nonpositive = (params) => inst.check(_lte(BigInt(0), params)); - inst.nonnegative = (params) => inst.check(_gte(BigInt(0), params)); - inst.multipleOf = (value, params) => inst.check(_multipleOf(value, params)); - const bag = inst._zod.bag; - inst.minValue = bag.minimum ?? null; - inst.maxValue = bag.maximum ?? null; - inst.format = bag.format ?? null; - }); - ZodBigIntFormat = /* @__PURE__ */ $constructor("ZodBigIntFormat", (inst, def) => { - $ZodBigIntFormat.init(inst, def); - ZodBigInt2.init(inst, def); - }); - ZodSymbol2 = /* @__PURE__ */ $constructor("ZodSymbol", (inst, def) => { - $ZodSymbol.init(inst, def); - ZodType2.init(inst, def); - inst._zod.processJSONSchema = (ctx, json3, params) => symbolProcessor(inst, ctx, json3, params); - }); - ZodUndefined2 = /* @__PURE__ */ $constructor("ZodUndefined", (inst, def) => { - $ZodUndefined.init(inst, def); - ZodType2.init(inst, def); - inst._zod.processJSONSchema = (ctx, json3, params) => undefinedProcessor(inst, ctx, json3, params); - }); - ZodNull2 = /* @__PURE__ */ $constructor("ZodNull", (inst, def) => { - $ZodNull.init(inst, def); - ZodType2.init(inst, def); - inst._zod.processJSONSchema = (ctx, json3, params) => nullProcessor(inst, ctx, json3, params); - }); - ZodAny2 = /* @__PURE__ */ $constructor("ZodAny", (inst, def) => { - $ZodAny.init(inst, def); - ZodType2.init(inst, def); - inst._zod.processJSONSchema = (ctx, json3, params) => anyProcessor(inst, ctx, json3, params); - }); - ZodUnknown2 = /* @__PURE__ */ $constructor("ZodUnknown", (inst, def) => { - $ZodUnknown.init(inst, def); - ZodType2.init(inst, def); - inst._zod.processJSONSchema = (ctx, json3, params) => unknownProcessor(inst, ctx, json3, params); - }); - ZodNever2 = /* @__PURE__ */ $constructor("ZodNever", (inst, def) => { - $ZodNever.init(inst, def); - ZodType2.init(inst, def); - inst._zod.processJSONSchema = (ctx, json3, params) => neverProcessor(inst, ctx, json3, params); - }); - ZodVoid2 = /* @__PURE__ */ $constructor("ZodVoid", (inst, def) => { - $ZodVoid.init(inst, def); - ZodType2.init(inst, def); - inst._zod.processJSONSchema = (ctx, json3, params) => voidProcessor(inst, ctx, json3, params); - }); - ZodDate2 = /* @__PURE__ */ $constructor("ZodDate", (inst, def) => { - $ZodDate.init(inst, def); - ZodType2.init(inst, def); - inst._zod.processJSONSchema = (ctx, json3, params) => dateProcessor(inst, ctx, json3, params); - inst.min = (value, params) => inst.check(_gte(value, params)); - inst.max = (value, params) => inst.check(_lte(value, params)); - const c5 = inst._zod.bag; - inst.minDate = c5.minimum ? new Date(c5.minimum) : null; - inst.maxDate = c5.maximum ? new Date(c5.maximum) : null; - }); - ZodArray2 = /* @__PURE__ */ $constructor("ZodArray", (inst, def) => { - $ZodArray.init(inst, def); - ZodType2.init(inst, def); - inst._zod.processJSONSchema = (ctx, json3, params) => arrayProcessor(inst, ctx, json3, params); - inst.element = def.element; - inst.min = (minLength, params) => inst.check(_minLength(minLength, params)); - inst.nonempty = (params) => inst.check(_minLength(1, params)); - inst.max = (maxLength, params) => inst.check(_maxLength(maxLength, params)); - inst.length = (len, params) => inst.check(_length(len, params)); - inst.unwrap = () => inst.element; - }); - ZodObject2 = /* @__PURE__ */ $constructor("ZodObject", (inst, def) => { - $ZodObjectJIT.init(inst, def); - ZodType2.init(inst, def); - inst._zod.processJSONSchema = (ctx, json3, params) => objectProcessor(inst, ctx, json3, params); - util_exports.defineLazy(inst, "shape", () => { - return def.shape; - }); - inst.keyof = () => _enum2(Object.keys(inst._zod.def.shape)); - inst.catchall = (catchall) => inst.clone({ ...inst._zod.def, catchall }); - inst.passthrough = () => inst.clone({ ...inst._zod.def, catchall: unknown() }); - inst.loose = () => inst.clone({ ...inst._zod.def, catchall: unknown() }); - inst.strict = () => inst.clone({ ...inst._zod.def, catchall: never() }); - inst.strip = () => inst.clone({ ...inst._zod.def, catchall: void 0 }); - inst.extend = (incoming) => { - return util_exports.extend(inst, incoming); - }; - inst.safeExtend = (incoming) => { - return util_exports.safeExtend(inst, incoming); - }; - inst.merge = (other) => util_exports.merge(inst, other); - inst.pick = (mask) => util_exports.pick(inst, mask); - inst.omit = (mask) => util_exports.omit(inst, mask); - inst.partial = (...args) => util_exports.partial(ZodOptional2, inst, args[0]); - inst.required = (...args) => util_exports.required(ZodNonOptional, inst, args[0]); - }); - ZodUnion2 = /* @__PURE__ */ $constructor("ZodUnion", (inst, def) => { - $ZodUnion.init(inst, def); - ZodType2.init(inst, def); - inst._zod.processJSONSchema = (ctx, json3, params) => unionProcessor(inst, ctx, json3, params); - inst.options = def.options; - }); - ZodXor = /* @__PURE__ */ $constructor("ZodXor", (inst, def) => { - ZodUnion2.init(inst, def); - $ZodXor.init(inst, def); - inst._zod.processJSONSchema = (ctx, json3, params) => unionProcessor(inst, ctx, json3, params); - inst.options = def.options; - }); - ZodDiscriminatedUnion2 = /* @__PURE__ */ $constructor("ZodDiscriminatedUnion", (inst, def) => { - ZodUnion2.init(inst, def); - $ZodDiscriminatedUnion.init(inst, def); - }); - ZodIntersection2 = /* @__PURE__ */ $constructor("ZodIntersection", (inst, def) => { - $ZodIntersection.init(inst, def); - ZodType2.init(inst, def); - inst._zod.processJSONSchema = (ctx, json3, params) => intersectionProcessor(inst, ctx, json3, params); - }); - ZodTuple2 = /* @__PURE__ */ $constructor("ZodTuple", (inst, def) => { - $ZodTuple.init(inst, def); - ZodType2.init(inst, def); - inst._zod.processJSONSchema = (ctx, json3, params) => tupleProcessor(inst, ctx, json3, params); - inst.rest = (rest) => inst.clone({ - ...inst._zod.def, - rest - }); - }); - ZodRecord2 = /* @__PURE__ */ $constructor("ZodRecord", (inst, def) => { - $ZodRecord.init(inst, def); - ZodType2.init(inst, def); - inst._zod.processJSONSchema = (ctx, json3, params) => recordProcessor(inst, ctx, json3, params); - inst.keyType = def.keyType; - inst.valueType = def.valueType; - }); - ZodMap2 = /* @__PURE__ */ $constructor("ZodMap", (inst, def) => { - $ZodMap.init(inst, def); - ZodType2.init(inst, def); - inst._zod.processJSONSchema = (ctx, json3, params) => mapProcessor(inst, ctx, json3, params); - inst.keyType = def.keyType; - inst.valueType = def.valueType; - inst.min = (...args) => inst.check(_minSize(...args)); - inst.nonempty = (params) => inst.check(_minSize(1, params)); - inst.max = (...args) => inst.check(_maxSize(...args)); - inst.size = (...args) => inst.check(_size(...args)); - }); - ZodSet2 = /* @__PURE__ */ $constructor("ZodSet", (inst, def) => { - $ZodSet.init(inst, def); - ZodType2.init(inst, def); - inst._zod.processJSONSchema = (ctx, json3, params) => setProcessor(inst, ctx, json3, params); - inst.min = (...args) => inst.check(_minSize(...args)); - inst.nonempty = (params) => inst.check(_minSize(1, params)); - inst.max = (...args) => inst.check(_maxSize(...args)); - inst.size = (...args) => inst.check(_size(...args)); - }); - ZodEnum2 = /* @__PURE__ */ $constructor("ZodEnum", (inst, def) => { - $ZodEnum.init(inst, def); - ZodType2.init(inst, def); - inst._zod.processJSONSchema = (ctx, json3, params) => enumProcessor(inst, ctx, json3, params); - inst.enum = def.entries; - inst.options = Object.values(def.entries); - const keys = new Set(Object.keys(def.entries)); - inst.extract = (values2, params) => { - const newEntries = {}; - for (const value of values2) { - if (keys.has(value)) { - newEntries[value] = def.entries[value]; - } else - throw new Error(`Key ${value} not found in enum`); - } - return new ZodEnum2({ - ...def, - checks: [], - ...util_exports.normalizeParams(params), - entries: newEntries - }); - }; - inst.exclude = (values2, params) => { - const newEntries = { ...def.entries }; - for (const value of values2) { - if (keys.has(value)) { - delete newEntries[value]; - } else - throw new Error(`Key ${value} not found in enum`); - } - return new ZodEnum2({ - ...def, - checks: [], - ...util_exports.normalizeParams(params), - entries: newEntries - }); - }; - }); - ZodLiteral2 = /* @__PURE__ */ $constructor("ZodLiteral", (inst, def) => { - $ZodLiteral.init(inst, def); - ZodType2.init(inst, def); - inst._zod.processJSONSchema = (ctx, json3, params) => literalProcessor(inst, ctx, json3, params); - inst.values = new Set(def.values); - Object.defineProperty(inst, "value", { - get() { - if (def.values.length > 1) { - throw new Error("This schema contains multiple valid literal values. Use `.values` instead."); - } - return def.values[0]; - } - }); - }); - ZodFile = /* @__PURE__ */ $constructor("ZodFile", (inst, def) => { - $ZodFile.init(inst, def); - ZodType2.init(inst, def); - inst._zod.processJSONSchema = (ctx, json3, params) => fileProcessor(inst, ctx, json3, params); - inst.min = (size2, params) => inst.check(_minSize(size2, params)); - inst.max = (size2, params) => inst.check(_maxSize(size2, params)); - inst.mime = (types2, params) => inst.check(_mime(Array.isArray(types2) ? types2 : [types2], params)); - }); - ZodTransform = /* @__PURE__ */ $constructor("ZodTransform", (inst, def) => { - $ZodTransform.init(inst, def); - ZodType2.init(inst, def); - inst._zod.processJSONSchema = (ctx, json3, params) => transformProcessor(inst, ctx, json3, params); - inst._zod.parse = (payload2, _ctx) => { - if (_ctx.direction === "backward") { - throw new $ZodEncodeError(inst.constructor.name); - } - payload2.addIssue = (issue2) => { - if (typeof issue2 === "string") { - payload2.issues.push(util_exports.issue(issue2, payload2.value, def)); - } else { - const _issue = issue2; - if (_issue.fatal) - _issue.continue = false; - _issue.code ?? (_issue.code = "custom"); - _issue.input ?? (_issue.input = payload2.value); - _issue.inst ?? (_issue.inst = inst); - payload2.issues.push(util_exports.issue(_issue)); - } - }; - const output = def.transform(payload2.value, payload2); - if (output instanceof Promise) { - return output.then((output2) => { - payload2.value = output2; - return payload2; - }); - } - payload2.value = output; - return payload2; - }; - }); - ZodOptional2 = /* @__PURE__ */ $constructor("ZodOptional", (inst, def) => { - $ZodOptional.init(inst, def); - ZodType2.init(inst, def); - inst._zod.processJSONSchema = (ctx, json3, params) => optionalProcessor(inst, ctx, json3, params); - inst.unwrap = () => inst._zod.def.innerType; - }); - ZodExactOptional = /* @__PURE__ */ $constructor("ZodExactOptional", (inst, def) => { - $ZodExactOptional.init(inst, def); - ZodType2.init(inst, def); - inst._zod.processJSONSchema = (ctx, json3, params) => optionalProcessor(inst, ctx, json3, params); - inst.unwrap = () => inst._zod.def.innerType; - }); - ZodNullable2 = /* @__PURE__ */ $constructor("ZodNullable", (inst, def) => { - $ZodNullable.init(inst, def); - ZodType2.init(inst, def); - inst._zod.processJSONSchema = (ctx, json3, params) => nullableProcessor(inst, ctx, json3, params); - inst.unwrap = () => inst._zod.def.innerType; - }); - ZodDefault2 = /* @__PURE__ */ $constructor("ZodDefault", (inst, def) => { - $ZodDefault.init(inst, def); - ZodType2.init(inst, def); - inst._zod.processJSONSchema = (ctx, json3, params) => defaultProcessor(inst, ctx, json3, params); - inst.unwrap = () => inst._zod.def.innerType; - inst.removeDefault = inst.unwrap; - }); - ZodPrefault = /* @__PURE__ */ $constructor("ZodPrefault", (inst, def) => { - $ZodPrefault.init(inst, def); - ZodType2.init(inst, def); - inst._zod.processJSONSchema = (ctx, json3, params) => prefaultProcessor(inst, ctx, json3, params); - inst.unwrap = () => inst._zod.def.innerType; - }); - ZodNonOptional = /* @__PURE__ */ $constructor("ZodNonOptional", (inst, def) => { - $ZodNonOptional.init(inst, def); - ZodType2.init(inst, def); - inst._zod.processJSONSchema = (ctx, json3, params) => nonoptionalProcessor(inst, ctx, json3, params); - inst.unwrap = () => inst._zod.def.innerType; - }); - ZodSuccess = /* @__PURE__ */ $constructor("ZodSuccess", (inst, def) => { - $ZodSuccess.init(inst, def); - ZodType2.init(inst, def); - inst._zod.processJSONSchema = (ctx, json3, params) => successProcessor(inst, ctx, json3, params); - inst.unwrap = () => inst._zod.def.innerType; - }); - ZodCatch2 = /* @__PURE__ */ $constructor("ZodCatch", (inst, def) => { - $ZodCatch.init(inst, def); - ZodType2.init(inst, def); - inst._zod.processJSONSchema = (ctx, json3, params) => catchProcessor(inst, ctx, json3, params); - inst.unwrap = () => inst._zod.def.innerType; - inst.removeCatch = inst.unwrap; - }); - ZodNaN2 = /* @__PURE__ */ $constructor("ZodNaN", (inst, def) => { - $ZodNaN.init(inst, def); - ZodType2.init(inst, def); - inst._zod.processJSONSchema = (ctx, json3, params) => nanProcessor(inst, ctx, json3, params); - }); - ZodPipe = /* @__PURE__ */ $constructor("ZodPipe", (inst, def) => { - $ZodPipe.init(inst, def); - ZodType2.init(inst, def); - inst._zod.processJSONSchema = (ctx, json3, params) => pipeProcessor(inst, ctx, json3, params); - inst.in = def.in; - inst.out = def.out; - }); - ZodCodec = /* @__PURE__ */ $constructor("ZodCodec", (inst, def) => { - ZodPipe.init(inst, def); - $ZodCodec.init(inst, def); - }); - ZodReadonly2 = /* @__PURE__ */ $constructor("ZodReadonly", (inst, def) => { - $ZodReadonly.init(inst, def); - ZodType2.init(inst, def); - inst._zod.processJSONSchema = (ctx, json3, params) => readonlyProcessor(inst, ctx, json3, params); - inst.unwrap = () => inst._zod.def.innerType; - }); - ZodTemplateLiteral = /* @__PURE__ */ $constructor("ZodTemplateLiteral", (inst, def) => { - $ZodTemplateLiteral.init(inst, def); - ZodType2.init(inst, def); - inst._zod.processJSONSchema = (ctx, json3, params) => templateLiteralProcessor(inst, ctx, json3, params); - }); - ZodLazy2 = /* @__PURE__ */ $constructor("ZodLazy", (inst, def) => { - $ZodLazy.init(inst, def); - ZodType2.init(inst, def); - inst._zod.processJSONSchema = (ctx, json3, params) => lazyProcessor(inst, ctx, json3, params); - inst.unwrap = () => inst._zod.def.getter(); - }); - ZodPromise2 = /* @__PURE__ */ $constructor("ZodPromise", (inst, def) => { - $ZodPromise.init(inst, def); - ZodType2.init(inst, def); - inst._zod.processJSONSchema = (ctx, json3, params) => promiseProcessor(inst, ctx, json3, params); - inst.unwrap = () => inst._zod.def.innerType; - }); - ZodFunction2 = /* @__PURE__ */ $constructor("ZodFunction", (inst, def) => { - $ZodFunction.init(inst, def); - ZodType2.init(inst, def); - inst._zod.processJSONSchema = (ctx, json3, params) => functionProcessor(inst, ctx, json3, params); - }); - ZodCustom = /* @__PURE__ */ $constructor("ZodCustom", (inst, def) => { - $ZodCustom.init(inst, def); - ZodType2.init(inst, def); - inst._zod.processJSONSchema = (ctx, json3, params) => customProcessor(inst, ctx, json3, params); - }); - describe2 = describe; - meta2 = meta; - stringbool = (...args) => _stringbool({ - Codec: ZodCodec, - Boolean: ZodBoolean2, - String: ZodString2 - }, ...args); - } -}); - -// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/compat.js -function setErrorMap2(map4) { - config({ - customError: map4 - }); -} -function getErrorMap2() { - return config().customError; -} -var ZodIssueCode2, ZodFirstPartyTypeKind2; -var init_compat = __esm({ - "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/compat.js"() { - init_core2(); - init_core2(); - ZodIssueCode2 = { - invalid_type: "invalid_type", - too_big: "too_big", - too_small: "too_small", - invalid_format: "invalid_format", - not_multiple_of: "not_multiple_of", - unrecognized_keys: "unrecognized_keys", - invalid_union: "invalid_union", - invalid_key: "invalid_key", - invalid_element: "invalid_element", - invalid_value: "invalid_value", - custom: "custom" - }; - /* @__PURE__ */ (function(ZodFirstPartyTypeKind3) { - })(ZodFirstPartyTypeKind2 || (ZodFirstPartyTypeKind2 = {})); - } -}); - -// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/from-json-schema.js -function detectVersion(schema2, defaultTarget) { - const $schema = schema2.$schema; - if ($schema === "https://json-schema.org/draft/2020-12/schema") { - return "draft-2020-12"; - } - if ($schema === "http://json-schema.org/draft-07/schema#") { - return "draft-7"; - } - if ($schema === "http://json-schema.org/draft-04/schema#") { - return "draft-4"; - } - return defaultTarget ?? "draft-2020-12"; -} -function resolveRef(ref, ctx) { - if (!ref.startsWith("#")) { - throw new Error("External $ref is not supported, only local refs (#/...) are allowed"); - } - const path53 = ref.slice(1).split("/").filter(Boolean); - if (path53.length === 0) { - return ctx.rootSchema; - } - const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions"; - if (path53[0] === defsKey) { - const key = path53[1]; - if (!key || !ctx.defs[key]) { - throw new Error(`Reference not found: ${ref}`); - } - return ctx.defs[key]; - } - throw new Error(`Reference not found: ${ref}`); -} -function convertBaseSchema(schema2, ctx) { - if (schema2.not !== void 0) { - if (typeof schema2.not === "object" && Object.keys(schema2.not).length === 0) { - return z2.never(); - } - throw new Error("not is not supported in Zod (except { not: {} } for never)"); - } - if (schema2.unevaluatedItems !== void 0) { - throw new Error("unevaluatedItems is not supported"); - } - if (schema2.unevaluatedProperties !== void 0) { - throw new Error("unevaluatedProperties is not supported"); - } - if (schema2.if !== void 0 || schema2.then !== void 0 || schema2.else !== void 0) { - throw new Error("Conditional schemas (if/then/else) are not supported"); - } - if (schema2.dependentSchemas !== void 0 || schema2.dependentRequired !== void 0) { - throw new Error("dependentSchemas and dependentRequired are not supported"); - } - if (schema2.$ref) { - const refPath = schema2.$ref; - if (ctx.refs.has(refPath)) { - return ctx.refs.get(refPath); - } - if (ctx.processing.has(refPath)) { - return z2.lazy(() => { - if (!ctx.refs.has(refPath)) { - throw new Error(`Circular reference not resolved: ${refPath}`); - } - return ctx.refs.get(refPath); - }); - } - ctx.processing.add(refPath); - const resolved = resolveRef(refPath, ctx); - const zodSchema2 = convertSchema(resolved, ctx); - ctx.refs.set(refPath, zodSchema2); - ctx.processing.delete(refPath); - return zodSchema2; - } - if (schema2.enum !== void 0) { - const enumValues = schema2.enum; - if (ctx.version === "openapi-3.0" && schema2.nullable === true && enumValues.length === 1 && enumValues[0] === null) { - return z2.null(); - } - if (enumValues.length === 0) { - return z2.never(); - } - if (enumValues.length === 1) { - return z2.literal(enumValues[0]); - } - if (enumValues.every((v5) => typeof v5 === "string")) { - return z2.enum(enumValues); - } - const literalSchemas = enumValues.map((v5) => z2.literal(v5)); - if (literalSchemas.length < 2) { - return literalSchemas[0]; - } - return z2.union([literalSchemas[0], literalSchemas[1], ...literalSchemas.slice(2)]); - } - if (schema2.const !== void 0) { - return z2.literal(schema2.const); - } - const type = schema2.type; - if (Array.isArray(type)) { - const typeSchemas = type.map((t5) => { - const typeSchema = { ...schema2, type: t5 }; - return convertBaseSchema(typeSchema, ctx); - }); - if (typeSchemas.length === 0) { - return z2.never(); - } - if (typeSchemas.length === 1) { - return typeSchemas[0]; - } - return z2.union(typeSchemas); - } - if (!type) { - return z2.any(); - } - let zodSchema; - switch (type) { - case "string": { - let stringSchema = z2.string(); - if (schema2.format) { - const format2 = schema2.format; - if (format2 === "email") { - stringSchema = stringSchema.check(z2.email()); - } else if (format2 === "uri" || format2 === "uri-reference") { - stringSchema = stringSchema.check(z2.url()); - } else if (format2 === "uuid" || format2 === "guid") { - stringSchema = stringSchema.check(z2.uuid()); - } else if (format2 === "date-time") { - stringSchema = stringSchema.check(z2.iso.datetime()); - } else if (format2 === "date") { - stringSchema = stringSchema.check(z2.iso.date()); - } else if (format2 === "time") { - stringSchema = stringSchema.check(z2.iso.time()); - } else if (format2 === "duration") { - stringSchema = stringSchema.check(z2.iso.duration()); - } else if (format2 === "ipv4") { - stringSchema = stringSchema.check(z2.ipv4()); - } else if (format2 === "ipv6") { - stringSchema = stringSchema.check(z2.ipv6()); - } else if (format2 === "mac") { - stringSchema = stringSchema.check(z2.mac()); - } else if (format2 === "cidr") { - stringSchema = stringSchema.check(z2.cidrv4()); - } else if (format2 === "cidr-v6") { - stringSchema = stringSchema.check(z2.cidrv6()); - } else if (format2 === "base64") { - stringSchema = stringSchema.check(z2.base64()); - } else if (format2 === "base64url") { - stringSchema = stringSchema.check(z2.base64url()); - } else if (format2 === "e164") { - stringSchema = stringSchema.check(z2.e164()); - } else if (format2 === "jwt") { - stringSchema = stringSchema.check(z2.jwt()); - } else if (format2 === "emoji") { - stringSchema = stringSchema.check(z2.emoji()); - } else if (format2 === "nanoid") { - stringSchema = stringSchema.check(z2.nanoid()); - } else if (format2 === "cuid") { - stringSchema = stringSchema.check(z2.cuid()); - } else if (format2 === "cuid2") { - stringSchema = stringSchema.check(z2.cuid2()); - } else if (format2 === "ulid") { - stringSchema = stringSchema.check(z2.ulid()); - } else if (format2 === "xid") { - stringSchema = stringSchema.check(z2.xid()); - } else if (format2 === "ksuid") { - stringSchema = stringSchema.check(z2.ksuid()); - } - } - if (typeof schema2.minLength === "number") { - stringSchema = stringSchema.min(schema2.minLength); - } - if (typeof schema2.maxLength === "number") { - stringSchema = stringSchema.max(schema2.maxLength); - } - if (schema2.pattern) { - stringSchema = stringSchema.regex(new RegExp(schema2.pattern)); - } - zodSchema = stringSchema; - break; - } - case "number": - case "integer": { - let numberSchema = type === "integer" ? z2.number().int() : z2.number(); - if (typeof schema2.minimum === "number") { - numberSchema = numberSchema.min(schema2.minimum); - } - if (typeof schema2.maximum === "number") { - numberSchema = numberSchema.max(schema2.maximum); - } - if (typeof schema2.exclusiveMinimum === "number") { - numberSchema = numberSchema.gt(schema2.exclusiveMinimum); - } else if (schema2.exclusiveMinimum === true && typeof schema2.minimum === "number") { - numberSchema = numberSchema.gt(schema2.minimum); - } - if (typeof schema2.exclusiveMaximum === "number") { - numberSchema = numberSchema.lt(schema2.exclusiveMaximum); - } else if (schema2.exclusiveMaximum === true && typeof schema2.maximum === "number") { - numberSchema = numberSchema.lt(schema2.maximum); - } - if (typeof schema2.multipleOf === "number") { - numberSchema = numberSchema.multipleOf(schema2.multipleOf); - } - zodSchema = numberSchema; - break; - } - case "boolean": { - zodSchema = z2.boolean(); - break; - } - case "null": { - zodSchema = z2.null(); - break; - } - case "object": { - const shape = {}; - const properties = schema2.properties || {}; - const requiredSet = new Set(schema2.required || []); - for (const [key, propSchema] of Object.entries(properties)) { - const propZodSchema = convertSchema(propSchema, ctx); - shape[key] = requiredSet.has(key) ? propZodSchema : propZodSchema.optional(); - } - if (schema2.propertyNames) { - const keySchema = convertSchema(schema2.propertyNames, ctx); - const valueSchema = schema2.additionalProperties && typeof schema2.additionalProperties === "object" ? convertSchema(schema2.additionalProperties, ctx) : z2.any(); - if (Object.keys(shape).length === 0) { - zodSchema = z2.record(keySchema, valueSchema); - break; - } - const objectSchema2 = z2.object(shape).passthrough(); - const recordSchema = z2.looseRecord(keySchema, valueSchema); - zodSchema = z2.intersection(objectSchema2, recordSchema); - break; - } - if (schema2.patternProperties) { - const patternProps = schema2.patternProperties; - const patternKeys = Object.keys(patternProps); - const looseRecords = []; - for (const pattern of patternKeys) { - const patternValue = convertSchema(patternProps[pattern], ctx); - const keySchema = z2.string().regex(new RegExp(pattern)); - looseRecords.push(z2.looseRecord(keySchema, patternValue)); - } - const schemasToIntersect = []; - if (Object.keys(shape).length > 0) { - schemasToIntersect.push(z2.object(shape).passthrough()); - } - schemasToIntersect.push(...looseRecords); - if (schemasToIntersect.length === 0) { - zodSchema = z2.object({}).passthrough(); - } else if (schemasToIntersect.length === 1) { - zodSchema = schemasToIntersect[0]; - } else { - let result = z2.intersection(schemasToIntersect[0], schemasToIntersect[1]); - for (let i5 = 2; i5 < schemasToIntersect.length; i5++) { - result = z2.intersection(result, schemasToIntersect[i5]); - } - zodSchema = result; - } - break; - } - const objectSchema = z2.object(shape); - if (schema2.additionalProperties === false) { - zodSchema = objectSchema.strict(); - } else if (typeof schema2.additionalProperties === "object") { - zodSchema = objectSchema.catchall(convertSchema(schema2.additionalProperties, ctx)); - } else { - zodSchema = objectSchema.passthrough(); - } - break; - } - case "array": { - const prefixItems = schema2.prefixItems; - const items = schema2.items; - if (prefixItems && Array.isArray(prefixItems)) { - const tupleItems = prefixItems.map((item) => convertSchema(item, ctx)); - const rest = items && typeof items === "object" && !Array.isArray(items) ? convertSchema(items, ctx) : void 0; - if (rest) { - zodSchema = z2.tuple(tupleItems).rest(rest); - } else { - zodSchema = z2.tuple(tupleItems); - } - if (typeof schema2.minItems === "number") { - zodSchema = zodSchema.check(z2.minLength(schema2.minItems)); - } - if (typeof schema2.maxItems === "number") { - zodSchema = zodSchema.check(z2.maxLength(schema2.maxItems)); - } - } else if (Array.isArray(items)) { - const tupleItems = items.map((item) => convertSchema(item, ctx)); - const rest = schema2.additionalItems && typeof schema2.additionalItems === "object" ? convertSchema(schema2.additionalItems, ctx) : void 0; - if (rest) { - zodSchema = z2.tuple(tupleItems).rest(rest); - } else { - zodSchema = z2.tuple(tupleItems); - } - if (typeof schema2.minItems === "number") { - zodSchema = zodSchema.check(z2.minLength(schema2.minItems)); - } - if (typeof schema2.maxItems === "number") { - zodSchema = zodSchema.check(z2.maxLength(schema2.maxItems)); - } - } else if (items !== void 0) { - const element = convertSchema(items, ctx); - let arraySchema = z2.array(element); - if (typeof schema2.minItems === "number") { - arraySchema = arraySchema.min(schema2.minItems); - } - if (typeof schema2.maxItems === "number") { - arraySchema = arraySchema.max(schema2.maxItems); - } - zodSchema = arraySchema; - } else { - zodSchema = z2.array(z2.any()); - } - break; - } - default: - throw new Error(`Unsupported type: ${type}`); - } - if (schema2.description) { - zodSchema = zodSchema.describe(schema2.description); - } - if (schema2.default !== void 0) { - zodSchema = zodSchema.default(schema2.default); - } - return zodSchema; -} -function convertSchema(schema2, ctx) { - if (typeof schema2 === "boolean") { - return schema2 ? z2.any() : z2.never(); - } - let baseSchema = convertBaseSchema(schema2, ctx); - const hasExplicitType = schema2.type || schema2.enum !== void 0 || schema2.const !== void 0; - if (schema2.anyOf && Array.isArray(schema2.anyOf)) { - const options = schema2.anyOf.map((s5) => convertSchema(s5, ctx)); - const anyOfUnion = z2.union(options); - baseSchema = hasExplicitType ? z2.intersection(baseSchema, anyOfUnion) : anyOfUnion; - } - if (schema2.oneOf && Array.isArray(schema2.oneOf)) { - const options = schema2.oneOf.map((s5) => convertSchema(s5, ctx)); - const oneOfUnion = z2.xor(options); - baseSchema = hasExplicitType ? z2.intersection(baseSchema, oneOfUnion) : oneOfUnion; - } - if (schema2.allOf && Array.isArray(schema2.allOf)) { - if (schema2.allOf.length === 0) { - baseSchema = hasExplicitType ? baseSchema : z2.any(); - } else { - let result = hasExplicitType ? baseSchema : convertSchema(schema2.allOf[0], ctx); - const startIdx = hasExplicitType ? 0 : 1; - for (let i5 = startIdx; i5 < schema2.allOf.length; i5++) { - result = z2.intersection(result, convertSchema(schema2.allOf[i5], ctx)); - } - baseSchema = result; - } - } - if (schema2.nullable === true && ctx.version === "openapi-3.0") { - baseSchema = z2.nullable(baseSchema); - } - if (schema2.readOnly === true) { - baseSchema = z2.readonly(baseSchema); - } - const extraMeta = {}; - const coreMetadataKeys = ["$id", "id", "$comment", "$anchor", "$vocabulary", "$dynamicRef", "$dynamicAnchor"]; - for (const key of coreMetadataKeys) { - if (key in schema2) { - extraMeta[key] = schema2[key]; - } - } - const contentMetadataKeys = ["contentEncoding", "contentMediaType", "contentSchema"]; - for (const key of contentMetadataKeys) { - if (key in schema2) { - extraMeta[key] = schema2[key]; - } - } - for (const key of Object.keys(schema2)) { - if (!RECOGNIZED_KEYS.has(key)) { - extraMeta[key] = schema2[key]; - } - } - if (Object.keys(extraMeta).length > 0) { - ctx.registry.add(baseSchema, extraMeta); - } - return baseSchema; -} -function fromJSONSchema(schema2, params) { - if (typeof schema2 === "boolean") { - return schema2 ? z2.any() : z2.never(); - } - const version3 = detectVersion(schema2, params?.defaultTarget); - const defs = schema2.$defs || schema2.definitions || {}; - const ctx = { - version: version3, - defs, - refs: /* @__PURE__ */ new Map(), - processing: /* @__PURE__ */ new Set(), - rootSchema: schema2, - registry: params?.registry ?? globalRegistry - }; - return convertSchema(schema2, ctx); -} -var z2, RECOGNIZED_KEYS; -var init_from_json_schema = __esm({ - "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/from-json-schema.js"() { - init_registries(); - init_checks3(); - init_iso(); - init_schemas2(); - z2 = { - ...schemas_exports2, - ...checks_exports2, - iso: iso_exports - }; - RECOGNIZED_KEYS = /* @__PURE__ */ new Set([ - // Schema identification - "$schema", - "$ref", - "$defs", - "definitions", - // Core schema keywords - "$id", - "id", - "$comment", - "$anchor", - "$vocabulary", - "$dynamicRef", - "$dynamicAnchor", - // Type - "type", - "enum", - "const", - // Composition - "anyOf", - "oneOf", - "allOf", - "not", - // Object - "properties", - "required", - "additionalProperties", - "patternProperties", - "propertyNames", - "minProperties", - "maxProperties", - // Array - "items", - "prefixItems", - "additionalItems", - "minItems", - "maxItems", - "uniqueItems", - "contains", - "minContains", - "maxContains", - // String - "minLength", - "maxLength", - "pattern", - "format", - // Number - "minimum", - "maximum", - "exclusiveMinimum", - "exclusiveMaximum", - "multipleOf", - // Already handled metadata - "description", - "default", - // Content - "contentEncoding", - "contentMediaType", - "contentSchema", - // Unsupported (error-throwing) - "unevaluatedItems", - "unevaluatedProperties", - "if", - "then", - "else", - "dependentSchemas", - "dependentRequired", - // OpenAPI - "nullable", - "readOnly" - ]); - } -}); - -// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/coerce.js -var coerce_exports = {}; -__export(coerce_exports, { - bigint: () => bigint4, - boolean: () => boolean4, - date: () => date6, - number: () => number3, - string: () => string3 -}); -function string3(params) { - return _coercedString(ZodString2, params); -} -function number3(params) { - return _coercedNumber(ZodNumber2, params); -} -function boolean4(params) { - return _coercedBoolean(ZodBoolean2, params); -} -function bigint4(params) { - return _coercedBigint(ZodBigInt2, params); -} -function date6(params) { - return _coercedDate(ZodDate2, params); -} -var init_coerce = __esm({ - "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/coerce.js"() { - init_core2(); - init_schemas2(); - } -}); - -// node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/external.js -var external_exports2 = {}; -__export(external_exports2, { - $brand: () => $brand, - $input: () => $input, - $output: () => $output, - NEVER: () => NEVER2, - TimePrecision: () => TimePrecision, - ZodAny: () => ZodAny2, - ZodArray: () => ZodArray2, - ZodBase64: () => ZodBase64, - ZodBase64URL: () => ZodBase64URL, - ZodBigInt: () => ZodBigInt2, - ZodBigIntFormat: () => ZodBigIntFormat, - ZodBoolean: () => ZodBoolean2, - ZodCIDRv4: () => ZodCIDRv4, - ZodCIDRv6: () => ZodCIDRv6, - ZodCUID: () => ZodCUID, - ZodCUID2: () => ZodCUID2, - ZodCatch: () => ZodCatch2, - ZodCodec: () => ZodCodec, - ZodCustom: () => ZodCustom, - ZodCustomStringFormat: () => ZodCustomStringFormat, - ZodDate: () => ZodDate2, - ZodDefault: () => ZodDefault2, - ZodDiscriminatedUnion: () => ZodDiscriminatedUnion2, - ZodE164: () => ZodE164, - ZodEmail: () => ZodEmail, - ZodEmoji: () => ZodEmoji, - ZodEnum: () => ZodEnum2, - ZodError: () => ZodError2, - ZodExactOptional: () => ZodExactOptional, - ZodFile: () => ZodFile, - ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind2, - ZodFunction: () => ZodFunction2, - ZodGUID: () => ZodGUID, - ZodIPv4: () => ZodIPv4, - ZodIPv6: () => ZodIPv6, - ZodISODate: () => ZodISODate, - ZodISODateTime: () => ZodISODateTime, - ZodISODuration: () => ZodISODuration, - ZodISOTime: () => ZodISOTime, - ZodIntersection: () => ZodIntersection2, - ZodIssueCode: () => ZodIssueCode2, - ZodJWT: () => ZodJWT, - ZodKSUID: () => ZodKSUID, - ZodLazy: () => ZodLazy2, - ZodLiteral: () => ZodLiteral2, - ZodMAC: () => ZodMAC, - ZodMap: () => ZodMap2, - ZodNaN: () => ZodNaN2, - ZodNanoID: () => ZodNanoID, - ZodNever: () => ZodNever2, - ZodNonOptional: () => ZodNonOptional, - ZodNull: () => ZodNull2, - ZodNullable: () => ZodNullable2, - ZodNumber: () => ZodNumber2, - ZodNumberFormat: () => ZodNumberFormat, - ZodObject: () => ZodObject2, - ZodOptional: () => ZodOptional2, - ZodPipe: () => ZodPipe, - ZodPrefault: () => ZodPrefault, - ZodPromise: () => ZodPromise2, - ZodReadonly: () => ZodReadonly2, - ZodRealError: () => ZodRealError, - ZodRecord: () => ZodRecord2, - ZodSet: () => ZodSet2, - ZodString: () => ZodString2, - ZodStringFormat: () => ZodStringFormat, - ZodSuccess: () => ZodSuccess, - ZodSymbol: () => ZodSymbol2, - ZodTemplateLiteral: () => ZodTemplateLiteral, - ZodTransform: () => ZodTransform, - ZodTuple: () => ZodTuple2, - ZodType: () => ZodType2, - ZodULID: () => ZodULID, - ZodURL: () => ZodURL, - ZodUUID: () => ZodUUID, - ZodUndefined: () => ZodUndefined2, - ZodUnion: () => ZodUnion2, - ZodUnknown: () => ZodUnknown2, - ZodVoid: () => ZodVoid2, - ZodXID: () => ZodXID, - ZodXor: () => ZodXor, - _ZodString: () => _ZodString, - _default: () => _default2, - _function: () => _function, - any: () => any, - array: () => array, - base64: () => base642, - base64url: () => base64url2, - bigint: () => bigint3, - boolean: () => boolean3, - catch: () => _catch2, - check: () => check2, - cidrv4: () => cidrv42, - cidrv6: () => cidrv62, - clone: () => clone2, - codec: () => codec, - coerce: () => coerce_exports, - config: () => config, - core: () => core_exports2, - cuid: () => cuid3, - cuid2: () => cuid22, - custom: () => custom2, - date: () => date5, - decode: () => decode4, - decodeAsync: () => decodeAsync2, - describe: () => describe2, - discriminatedUnion: () => discriminatedUnion, - e164: () => e1642, - email: () => email2, - emoji: () => emoji2, - encode: () => encode5, - encodeAsync: () => encodeAsync2, - endsWith: () => _endsWith, - enum: () => _enum2, - exactOptional: () => exactOptional, - file: () => file, - flattenError: () => flattenError, - float32: () => float32, - float64: () => float64, - formatError: () => formatError, - fromJSONSchema: () => fromJSONSchema, - function: () => _function, - getErrorMap: () => getErrorMap2, - globalRegistry: () => globalRegistry, - gt: () => _gt, - gte: () => _gte, - guid: () => guid2, - hash: () => hash, - hex: () => hex2, - hostname: () => hostname2, - httpUrl: () => httpUrl, - includes: () => _includes, - instanceof: () => _instanceof, - int: () => int, - int32: () => int32, - int64: () => int64, - intersection: () => intersection, - ipv4: () => ipv42, - ipv6: () => ipv62, - iso: () => iso_exports, - json: () => json2, - jwt: () => jwt, - keyof: () => keyof, - ksuid: () => ksuid2, - lazy: () => lazy, - length: () => _length, - literal: () => literal, - locales: () => locales_exports, - looseObject: () => looseObject, - looseRecord: () => looseRecord, - lowercase: () => _lowercase, - lt: () => _lt, - lte: () => _lte, - mac: () => mac2, - map: () => map2, - maxLength: () => _maxLength, - maxSize: () => _maxSize, - meta: () => meta2, - mime: () => _mime, - minLength: () => _minLength, - minSize: () => _minSize, - multipleOf: () => _multipleOf, - nan: () => nan, - nanoid: () => nanoid2, - nativeEnum: () => nativeEnum, - negative: () => _negative, - never: () => never, - nonnegative: () => _nonnegative, - nonoptional: () => nonoptional, - nonpositive: () => _nonpositive, - normalize: () => _normalize, - null: () => _null3, - nullable: () => nullable, - nullish: () => nullish2, - number: () => number2, - object: () => object, - optional: () => optional, - overwrite: () => _overwrite, - parse: () => parse3, - parseAsync: () => parseAsync2, - partialRecord: () => partialRecord, - pipe: () => pipe, - positive: () => _positive, - prefault: () => prefault, - preprocess: () => preprocess, - prettifyError: () => prettifyError, - promise: () => promise, - property: () => _property, - readonly: () => readonly, - record: () => record, - refine: () => refine, - regex: () => _regex, - regexes: () => regexes_exports, - registry: () => registry, - safeDecode: () => safeDecode2, - safeDecodeAsync: () => safeDecodeAsync2, - safeEncode: () => safeEncode2, - safeEncodeAsync: () => safeEncodeAsync2, - safeParse: () => safeParse2, - safeParseAsync: () => safeParseAsync2, - set: () => set, - setErrorMap: () => setErrorMap2, - size: () => _size, - slugify: () => _slugify, - startsWith: () => _startsWith, - strictObject: () => strictObject, - string: () => string2, - stringFormat: () => stringFormat, - stringbool: () => stringbool, - success: () => success, - superRefine: () => superRefine, - symbol: () => symbol, - templateLiteral: () => templateLiteral, - toJSONSchema: () => toJSONSchema, - toLowerCase: () => _toLowerCase, - toUpperCase: () => _toUpperCase, - transform: () => transform, - treeifyError: () => treeifyError, - trim: () => _trim, - tuple: () => tuple, - uint32: () => uint32, - uint64: () => uint64, - ulid: () => ulid2, - undefined: () => _undefined3, - union: () => union2, - unknown: () => unknown, - uppercase: () => _uppercase, - url: () => url, - util: () => util_exports, - uuid: () => uuid3, - uuidv4: () => uuidv4, - uuidv6: () => uuidv6, - uuidv7: () => uuidv7, - void: () => _void2, - xid: () => xid2, - xor: () => xor2 -}); -var init_external = __esm({ - "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/external.js"() { - init_core2(); - init_schemas2(); - init_checks3(); - init_errors9(); - init_parse2(); - init_compat(); - init_core2(); - init_en(); - init_core2(); - init_json_schema_processors(); - init_from_json_schema(); - init_locales(); - init_iso(); - init_iso(); - init_coerce(); - config(en_default2()); - } -}); - -// node_modules/.pnpm/zod@4.3.6/node_modules/zod/index.js -var zod_exports = {}; -__export(zod_exports, { - $brand: () => $brand, - $input: () => $input, - $output: () => $output, - NEVER: () => NEVER2, - TimePrecision: () => TimePrecision, - ZodAny: () => ZodAny2, - ZodArray: () => ZodArray2, - ZodBase64: () => ZodBase64, - ZodBase64URL: () => ZodBase64URL, - ZodBigInt: () => ZodBigInt2, - ZodBigIntFormat: () => ZodBigIntFormat, - ZodBoolean: () => ZodBoolean2, - ZodCIDRv4: () => ZodCIDRv4, - ZodCIDRv6: () => ZodCIDRv6, - ZodCUID: () => ZodCUID, - ZodCUID2: () => ZodCUID2, - ZodCatch: () => ZodCatch2, - ZodCodec: () => ZodCodec, - ZodCustom: () => ZodCustom, - ZodCustomStringFormat: () => ZodCustomStringFormat, - ZodDate: () => ZodDate2, - ZodDefault: () => ZodDefault2, - ZodDiscriminatedUnion: () => ZodDiscriminatedUnion2, - ZodE164: () => ZodE164, - ZodEmail: () => ZodEmail, - ZodEmoji: () => ZodEmoji, - ZodEnum: () => ZodEnum2, - ZodError: () => ZodError2, - ZodExactOptional: () => ZodExactOptional, - ZodFile: () => ZodFile, - ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind2, - ZodFunction: () => ZodFunction2, - ZodGUID: () => ZodGUID, - ZodIPv4: () => ZodIPv4, - ZodIPv6: () => ZodIPv6, - ZodISODate: () => ZodISODate, - ZodISODateTime: () => ZodISODateTime, - ZodISODuration: () => ZodISODuration, - ZodISOTime: () => ZodISOTime, - ZodIntersection: () => ZodIntersection2, - ZodIssueCode: () => ZodIssueCode2, - ZodJWT: () => ZodJWT, - ZodKSUID: () => ZodKSUID, - ZodLazy: () => ZodLazy2, - ZodLiteral: () => ZodLiteral2, - ZodMAC: () => ZodMAC, - ZodMap: () => ZodMap2, - ZodNaN: () => ZodNaN2, - ZodNanoID: () => ZodNanoID, - ZodNever: () => ZodNever2, - ZodNonOptional: () => ZodNonOptional, - ZodNull: () => ZodNull2, - ZodNullable: () => ZodNullable2, - ZodNumber: () => ZodNumber2, - ZodNumberFormat: () => ZodNumberFormat, - ZodObject: () => ZodObject2, - ZodOptional: () => ZodOptional2, - ZodPipe: () => ZodPipe, - ZodPrefault: () => ZodPrefault, - ZodPromise: () => ZodPromise2, - ZodReadonly: () => ZodReadonly2, - ZodRealError: () => ZodRealError, - ZodRecord: () => ZodRecord2, - ZodSet: () => ZodSet2, - ZodString: () => ZodString2, - ZodStringFormat: () => ZodStringFormat, - ZodSuccess: () => ZodSuccess, - ZodSymbol: () => ZodSymbol2, - ZodTemplateLiteral: () => ZodTemplateLiteral, - ZodTransform: () => ZodTransform, - ZodTuple: () => ZodTuple2, - ZodType: () => ZodType2, - ZodULID: () => ZodULID, - ZodURL: () => ZodURL, - ZodUUID: () => ZodUUID, - ZodUndefined: () => ZodUndefined2, - ZodUnion: () => ZodUnion2, - ZodUnknown: () => ZodUnknown2, - ZodVoid: () => ZodVoid2, - ZodXID: () => ZodXID, - ZodXor: () => ZodXor, - _ZodString: () => _ZodString, - _default: () => _default2, - _function: () => _function, - any: () => any, - array: () => array, - base64: () => base642, - base64url: () => base64url2, - bigint: () => bigint3, - boolean: () => boolean3, - catch: () => _catch2, - check: () => check2, - cidrv4: () => cidrv42, - cidrv6: () => cidrv62, - clone: () => clone2, - codec: () => codec, - coerce: () => coerce_exports, - config: () => config, - core: () => core_exports2, - cuid: () => cuid3, - cuid2: () => cuid22, - custom: () => custom2, - date: () => date5, - decode: () => decode4, - decodeAsync: () => decodeAsync2, - default: () => zod_default, - describe: () => describe2, - discriminatedUnion: () => discriminatedUnion, - e164: () => e1642, - email: () => email2, - emoji: () => emoji2, - encode: () => encode5, - encodeAsync: () => encodeAsync2, - endsWith: () => _endsWith, - enum: () => _enum2, - exactOptional: () => exactOptional, - file: () => file, - flattenError: () => flattenError, - float32: () => float32, - float64: () => float64, - formatError: () => formatError, - fromJSONSchema: () => fromJSONSchema, - function: () => _function, - getErrorMap: () => getErrorMap2, - globalRegistry: () => globalRegistry, - gt: () => _gt, - gte: () => _gte, - guid: () => guid2, - hash: () => hash, - hex: () => hex2, - hostname: () => hostname2, - httpUrl: () => httpUrl, - includes: () => _includes, - instanceof: () => _instanceof, - int: () => int, - int32: () => int32, - int64: () => int64, - intersection: () => intersection, - ipv4: () => ipv42, - ipv6: () => ipv62, - iso: () => iso_exports, - json: () => json2, - jwt: () => jwt, - keyof: () => keyof, - ksuid: () => ksuid2, - lazy: () => lazy, - length: () => _length, - literal: () => literal, - locales: () => locales_exports, - looseObject: () => looseObject, - looseRecord: () => looseRecord, - lowercase: () => _lowercase, - lt: () => _lt, - lte: () => _lte, - mac: () => mac2, - map: () => map2, - maxLength: () => _maxLength, - maxSize: () => _maxSize, - meta: () => meta2, - mime: () => _mime, - minLength: () => _minLength, - minSize: () => _minSize, - multipleOf: () => _multipleOf, - nan: () => nan, - nanoid: () => nanoid2, - nativeEnum: () => nativeEnum, - negative: () => _negative, - never: () => never, - nonnegative: () => _nonnegative, - nonoptional: () => nonoptional, - nonpositive: () => _nonpositive, - normalize: () => _normalize, - null: () => _null3, - nullable: () => nullable, - nullish: () => nullish2, - number: () => number2, - object: () => object, - optional: () => optional, - overwrite: () => _overwrite, - parse: () => parse3, - parseAsync: () => parseAsync2, - partialRecord: () => partialRecord, - pipe: () => pipe, - positive: () => _positive, - prefault: () => prefault, - preprocess: () => preprocess, - prettifyError: () => prettifyError, - promise: () => promise, - property: () => _property, - readonly: () => readonly, - record: () => record, - refine: () => refine, - regex: () => _regex, - regexes: () => regexes_exports, - registry: () => registry, - safeDecode: () => safeDecode2, - safeDecodeAsync: () => safeDecodeAsync2, - safeEncode: () => safeEncode2, - safeEncodeAsync: () => safeEncodeAsync2, - safeParse: () => safeParse2, - safeParseAsync: () => safeParseAsync2, - set: () => set, - setErrorMap: () => setErrorMap2, - size: () => _size, - slugify: () => _slugify, - startsWith: () => _startsWith, - strictObject: () => strictObject, - string: () => string2, - stringFormat: () => stringFormat, - stringbool: () => stringbool, - success: () => success, - superRefine: () => superRefine, - symbol: () => symbol, - templateLiteral: () => templateLiteral, - toJSONSchema: () => toJSONSchema, - toLowerCase: () => _toLowerCase, - toUpperCase: () => _toUpperCase, - transform: () => transform, - treeifyError: () => treeifyError, - trim: () => _trim, - tuple: () => tuple, - uint32: () => uint32, - uint64: () => uint64, - ulid: () => ulid2, - undefined: () => _undefined3, - union: () => union2, - unknown: () => unknown, - uppercase: () => _uppercase, - url: () => url, - util: () => util_exports, - uuid: () => uuid3, - uuidv4: () => uuidv4, - uuidv6: () => uuidv6, - uuidv7: () => uuidv7, - void: () => _void2, - xid: () => xid2, - xor: () => xor2, - z: () => external_exports2 -}); -var zod_default; -var init_zod = __esm({ - "node_modules/.pnpm/zod@4.3.6/node_modules/zod/index.js"() { - init_external(); - init_external(); - zod_default = external_exports2; - } -}); - -// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/utils/ip.mjs -function isValidIP2(ip) { - return ipv42().safeParse(ip).success || ipv62().safeParse(ip).success; -} -function isIPv6(ip) { - return ipv62().safeParse(ip).success; -} -function extractIPv4FromMapped(ipv63) { - const lower = ipv63.toLowerCase(); - if (lower.startsWith("::ffff:")) { - const ipv4Part = lower.substring(7); - if (ipv42().safeParse(ipv4Part).success) return ipv4Part; - } - const parts = ipv63.split(":"); - if (parts.length === 7 && parts[5]?.toLowerCase() === "ffff") { - const ipv4Part = parts[6]; - if (ipv4Part && ipv42().safeParse(ipv4Part).success) return ipv4Part; - } - if (lower.includes("::ffff:") || lower.includes(":ffff:")) { - const groups = expandIPv6(ipv63); - if (groups.length === 8 && groups[0] === "0000" && groups[1] === "0000" && groups[2] === "0000" && groups[3] === "0000" && groups[4] === "0000" && groups[5] === "ffff" && groups[6] && groups[7]) return `${Number.parseInt(groups[6].substring(0, 2), 16)}.${Number.parseInt(groups[6].substring(2, 4), 16)}.${Number.parseInt(groups[7].substring(0, 2), 16)}.${Number.parseInt(groups[7].substring(2, 4), 16)}`; - } - return null; -} -function expandIPv6(ipv63) { - if (ipv63.includes("::")) { - const sides = ipv63.split("::"); - const left = sides[0] ? sides[0].split(":") : []; - const right = sides[1] ? sides[1].split(":") : []; - const missingGroups = 8 - left.length - right.length; - const zeros = Array(missingGroups).fill("0000"); - const paddedLeft = left.map((g5) => g5.padStart(4, "0")); - const paddedRight = right.map((g5) => g5.padStart(4, "0")); - return [ - ...paddedLeft, - ...zeros, - ...paddedRight - ]; - } - return ipv63.split(":").map((g5) => g5.padStart(4, "0")); -} -function normalizeIPv6(ipv63, subnetPrefix) { - const groups = expandIPv6(ipv63); - if (subnetPrefix && subnetPrefix < 128) { - let bitsRemaining = subnetPrefix; - return groups.map((group) => { - if (bitsRemaining <= 0) return "0000"; - if (bitsRemaining >= 16) { - bitsRemaining -= 16; - return group; - } - const masked = Number.parseInt(group, 16) & (65535 << 16 - bitsRemaining & 65535); - bitsRemaining = 0; - return masked.toString(16).padStart(4, "0"); - }).join(":").toLowerCase(); - } - return groups.join(":").toLowerCase(); -} -function normalizeIP(ip, options = {}) { - if (ipv42().safeParse(ip).success) return ip.toLowerCase(); - if (!isIPv6(ip)) return ip.toLowerCase(); - const ipv43 = extractIPv4FromMapped(ip); - if (ipv43) return ipv43.toLowerCase(); - return normalizeIPv6(ip, options.ipv6Subnet || 64); -} -function createRateLimitKey(ip, path53) { - return `${ip}|${path53}`; -} -var init_ip = __esm({ - "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/utils/ip.mjs"() { - init_zod(); - } -}); - -// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/env/env-impl.mjs -function toBoolean(val) { - return val ? val !== "false" : false; -} -function getEnvVar(key, fallback) { - if (typeof process !== "undefined" && process.env) return process.env[key] ?? fallback; - if (typeof Deno !== "undefined") return Deno.env.get(key) ?? fallback; - if (typeof Bun !== "undefined") return Bun.env[key] ?? fallback; - return fallback; -} -function getBooleanEnvVar(key, fallback = true) { - const value = getEnvVar(key); - if (!value) return fallback; - return value !== "0" && value.toLowerCase() !== "false" && value !== ""; -} -var _envShim, _getEnv, env, nodeENV, isProduction, isDevelopment, isTest, ENV; -var init_env_impl = __esm({ - "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/env/env-impl.mjs"() { - _envShim = /* @__PURE__ */ Object.create(null); - _getEnv = (useShim) => globalThis.process?.env || globalThis.Deno?.env.toObject() || globalThis.__env__ || (useShim ? _envShim : globalThis); - env = new Proxy(_envShim, { - get(_, prop) { - return _getEnv()[prop] ?? _envShim[prop]; - }, - has(_, prop) { - return prop in _getEnv() || prop in _envShim; - }, - set(_, prop, value) { - const env$1 = _getEnv(true); - env$1[prop] = value; - return true; - }, - deleteProperty(_, prop) { - if (!prop) return false; - const env$1 = _getEnv(true); - delete env$1[prop]; - return true; - }, - ownKeys() { - const env$1 = _getEnv(true); - return Object.keys(env$1); - } - }); - nodeENV = typeof process !== "undefined" && process.env && "production" || ""; - isProduction = nodeENV === "production"; - isDevelopment = () => nodeENV === "dev" || nodeENV === "development"; - isTest = () => nodeENV === "test" || toBoolean(env.TEST); - ENV = Object.freeze({ - get BETTER_AUTH_SECRET() { - return getEnvVar("BETTER_AUTH_SECRET"); - }, - get AUTH_SECRET() { - return getEnvVar("AUTH_SECRET"); - }, - get BETTER_AUTH_TELEMETRY() { - return getEnvVar("BETTER_AUTH_TELEMETRY"); - }, - get BETTER_AUTH_TELEMETRY_ID() { - return getEnvVar("BETTER_AUTH_TELEMETRY_ID"); - }, - get NODE_ENV() { - return getEnvVar("NODE_ENV", "development"); - }, - get PACKAGE_VERSION() { - return getEnvVar("PACKAGE_VERSION", "0.0.0"); - }, - get BETTER_AUTH_TELEMETRY_ENDPOINT() { - return getEnvVar("BETTER_AUTH_TELEMETRY_ENDPOINT", ""); - } - }); - } -}); - -// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/env/color-depth.mjs -function getColorDepth() { - if (getEnvVar("FORCE_COLOR") !== void 0) switch (getEnvVar("FORCE_COLOR")) { - case "": - case "1": - case "true": - return COLORS_16; - case "2": - return COLORS_256; - case "3": - return COLORS_16m; - default: - return COLORS_2; - } - if (getEnvVar("NODE_DISABLE_COLORS") !== void 0 && getEnvVar("NODE_DISABLE_COLORS") !== "" || getEnvVar("NO_COLOR") !== void 0 && getEnvVar("NO_COLOR") !== "" || getEnvVar("TERM") === "dumb") return COLORS_2; - if (getEnvVar("TMUX")) return COLORS_16m; - if ("TF_BUILD" in env && "AGENT_NAME" in env) return COLORS_16; - if ("CI" in env) { - for (const { 0: envName, 1: colors } of CI_ENVS_MAP) if (envName in env) return colors; - if (getEnvVar("CI_NAME") === "codeship") return COLORS_256; - return COLORS_2; - } - if ("TEAMCITY_VERSION" in env) return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.exec(getEnvVar("TEAMCITY_VERSION")) !== null ? COLORS_16 : COLORS_2; - switch (getEnvVar("TERM_PROGRAM")) { - case "iTerm.app": - if (!getEnvVar("TERM_PROGRAM_VERSION") || /^[0-2]\./.exec(getEnvVar("TERM_PROGRAM_VERSION")) !== null) return COLORS_256; - return COLORS_16m; - case "HyperTerm": - case "MacTerm": - return COLORS_16m; - case "Apple_Terminal": - return COLORS_256; - } - if (getEnvVar("COLORTERM") === "truecolor" || getEnvVar("COLORTERM") === "24bit") return COLORS_16m; - if (getEnvVar("TERM")) { - if (/truecolor/.exec(getEnvVar("TERM")) !== null) return COLORS_16m; - if (/^xterm-256/.exec(getEnvVar("TERM")) !== null) return COLORS_256; - const termEnv = getEnvVar("TERM").toLowerCase(); - if (TERM_ENVS[termEnv]) return TERM_ENVS[termEnv]; - if (TERM_ENVS_REG_EXP.some((term) => term.exec(termEnv) !== null)) return COLORS_16; - } - if (getEnvVar("COLORTERM")) return COLORS_16; - return COLORS_2; -} -var COLORS_2, COLORS_16, COLORS_256, COLORS_16m, TERM_ENVS, CI_ENVS_MAP, TERM_ENVS_REG_EXP; -var init_color_depth = __esm({ - "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/env/color-depth.mjs"() { - init_env_impl(); - COLORS_2 = 1; - COLORS_16 = 4; - COLORS_256 = 8; - COLORS_16m = 24; - TERM_ENVS = { - eterm: COLORS_16, - cons25: COLORS_16, - console: COLORS_16, - cygwin: COLORS_16, - dtterm: COLORS_16, - gnome: COLORS_16, - hurd: COLORS_16, - jfbterm: COLORS_16, - konsole: COLORS_16, - kterm: COLORS_16, - mlterm: COLORS_16, - mosh: COLORS_16m, - putty: COLORS_16, - st: COLORS_16, - "rxvt-unicode-24bit": COLORS_16m, - terminator: COLORS_16m, - "xterm-kitty": COLORS_16m - }; - CI_ENVS_MAP = new Map(Object.entries({ - APPVEYOR: COLORS_256, - BUILDKITE: COLORS_256, - CIRCLECI: COLORS_16m, - DRONE: COLORS_256, - GITEA_ACTIONS: COLORS_16m, - GITHUB_ACTIONS: COLORS_16m, - GITLAB_CI: COLORS_256, - TRAVIS: COLORS_256 - })); - TERM_ENVS_REG_EXP = [ - /ansi/, - /color/, - /linux/, - /direct/, - /^con[0-9]*x[0-9]/, - /^rxvt/, - /^screen/, - /^xterm/, - /^vt100/, - /^vt220/ - ]; - } -}); - -// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/env/logger.mjs -function shouldPublishLog(currentLogLevel, logLevel) { - return levels.indexOf(logLevel) >= levels.indexOf(currentLogLevel); -} -var TTY_COLORS, levels, levelColors, formatMessage, createLogger, logger3; -var init_logger2 = __esm({ - "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/env/logger.mjs"() { - init_color_depth(); - TTY_COLORS = { - reset: "\x1B[0m", - bright: "\x1B[1m", - dim: "\x1B[2m", - undim: "\x1B[22m", - underscore: "\x1B[4m", - blink: "\x1B[5m", - reverse: "\x1B[7m", - hidden: "\x1B[8m", - fg: { - black: "\x1B[30m", - red: "\x1B[31m", - green: "\x1B[32m", - yellow: "\x1B[33m", - blue: "\x1B[34m", - magenta: "\x1B[35m", - cyan: "\x1B[36m", - white: "\x1B[37m" - }, - bg: { - black: "\x1B[40m", - red: "\x1B[41m", - green: "\x1B[42m", - yellow: "\x1B[43m", - blue: "\x1B[44m", - magenta: "\x1B[45m", - cyan: "\x1B[46m", - white: "\x1B[47m" - } - }; - levels = [ - "debug", - "info", - "success", - "warn", - "error" - ]; - levelColors = { - info: TTY_COLORS.fg.blue, - success: TTY_COLORS.fg.green, - warn: TTY_COLORS.fg.yellow, - error: TTY_COLORS.fg.red, - debug: TTY_COLORS.fg.magenta - }; - formatMessage = (level, message2, colorsEnabled) => { - const timestamp2 = (/* @__PURE__ */ new Date()).toISOString(); - if (colorsEnabled) return `${TTY_COLORS.dim}${timestamp2}${TTY_COLORS.reset} ${levelColors[level]}${level.toUpperCase()}${TTY_COLORS.reset} ${TTY_COLORS.bright}[Better Auth]:${TTY_COLORS.reset} ${message2}`; - return `${timestamp2} ${level.toUpperCase()} [Better Auth]: ${message2}`; - }; - createLogger = (options) => { - const enabled = options?.disabled !== true; - const logLevel = options?.level ?? "warn"; - const colorsEnabled = options?.disableColors !== void 0 ? !options.disableColors : getColorDepth() !== 1; - const LogFunc = (level, message2, args = []) => { - if (!enabled || !shouldPublishLog(logLevel, level)) return; - const formattedMessage = formatMessage(level, message2, colorsEnabled); - if (!options || typeof options.log !== "function") { - if (level === "error") console.error(formattedMessage, ...args); - else if (level === "warn") console.warn(formattedMessage, ...args); - else console.log(formattedMessage, ...args); - return; - } - options.log(level === "success" ? "info" : level, message2, ...args); - }; - return { - ...Object.fromEntries(levels.map((level) => [level, (...[message2, ...args]) => LogFunc(level, message2, args)])), - get level() { - return logLevel; - } - }; - }; - logger3 = createLogger(); - } -}); - -// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/env/index.mjs -var init_env = __esm({ - "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/env/index.mjs"() { - init_env_impl(); - init_color_depth(); - init_logger2(); - } -}); - -// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/utils/json.mjs -function safeJSONParse(data2) { - function reviver(_, value) { - if (typeof value === "string") { - if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/.test(value)) { - const date7 = new Date(value); - if (!isNaN(date7.getTime())) return date7; - } - } - return value; - } - try { - if (typeof data2 !== "string") return data2; - return JSON.parse(data2, reviver); - } catch (e5) { - logger3.error("Error parsing JSON", { error: e5 }); - return null; - } -} -var init_json2 = __esm({ - "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/utils/json.mjs"() { - init_logger2(); - init_env(); - } -}); - -// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/utils/string.mjs -var init_string = __esm({ - "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/utils/string.mjs"() { - } -}); - -// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/utils/url.mjs -function normalizePathname(requestUrl, basePath) { - let pathname; - try { - pathname = new URL(requestUrl).pathname.replace(/\/+$/, "") || "/"; - } catch { - return "/"; - } - if (basePath === "/" || basePath === "") return pathname; - if (pathname === basePath) return "/"; - if (pathname.startsWith(basePath + "/")) return pathname.slice(basePath.length).replace(/\/+$/, "") || "/"; - return pathname; -} -var init_url = __esm({ - "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/utils/url.mjs"() { - } -}); - -// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/utils/index.mjs -var init_utils7 = __esm({ - "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/utils/index.mjs"() { - init_db2(); - init_deprecate(); - init_error_codes(); - init_id(); - init_ip(); - init_json2(); - init_string(); - init_url(); - } -}); - -// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/error/codes.mjs -var BASE_ERROR_CODES; -var init_codes = __esm({ - "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/error/codes.mjs"() { - init_error_codes(); - init_utils7(); - BASE_ERROR_CODES = defineErrorCodes({ - USER_NOT_FOUND: "User not found", - FAILED_TO_CREATE_USER: "Failed to create user", - FAILED_TO_CREATE_SESSION: "Failed to create session", - FAILED_TO_UPDATE_USER: "Failed to update user", - FAILED_TO_GET_SESSION: "Failed to get session", - INVALID_PASSWORD: "Invalid password", - INVALID_EMAIL: "Invalid email", - INVALID_EMAIL_OR_PASSWORD: "Invalid email or password", - SOCIAL_ACCOUNT_ALREADY_LINKED: "Social account already linked", - PROVIDER_NOT_FOUND: "Provider not found", - INVALID_TOKEN: "Invalid token", - ID_TOKEN_NOT_SUPPORTED: "id_token not supported", - FAILED_TO_GET_USER_INFO: "Failed to get user info", - USER_EMAIL_NOT_FOUND: "User email not found", - EMAIL_NOT_VERIFIED: "Email not verified", - PASSWORD_TOO_SHORT: "Password too short", - PASSWORD_TOO_LONG: "Password too long", - USER_ALREADY_EXISTS: "User already exists.", - USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL: "User already exists. Use another email.", - EMAIL_CAN_NOT_BE_UPDATED: "Email can not be updated", - CREDENTIAL_ACCOUNT_NOT_FOUND: "Credential account not found", - SESSION_EXPIRED: "Session expired. Re-authenticate to perform this action.", - FAILED_TO_UNLINK_LAST_ACCOUNT: "You can't unlink your last account", - ACCOUNT_NOT_FOUND: "Account not found", - USER_ALREADY_HAS_PASSWORD: "User already has a password. Provide that to delete the account.", - CROSS_SITE_NAVIGATION_LOGIN_BLOCKED: "Cross-site navigation login blocked. This request appears to be a CSRF attack.", - VERIFICATION_EMAIL_NOT_ENABLED: "Verification email isn't enabled", - EMAIL_ALREADY_VERIFIED: "Email is already verified", - EMAIL_MISMATCH: "Email mismatch", - SESSION_NOT_FRESH: "Session is not fresh", - LINKED_ACCOUNT_ALREADY_EXISTS: "Linked account already exists", - INVALID_ORIGIN: "Invalid origin", - INVALID_CALLBACK_URL: "Invalid callbackURL", - INVALID_REDIRECT_URL: "Invalid redirectURL", - INVALID_ERROR_CALLBACK_URL: "Invalid errorCallbackURL", - INVALID_NEW_USER_CALLBACK_URL: "Invalid newUserCallbackURL", - MISSING_OR_NULL_ORIGIN: "Missing or null Origin", - CALLBACK_URL_REQUIRED: "callbackURL is required", - FAILED_TO_CREATE_VERIFICATION: "Unable to create verification", - FIELD_NOT_ALLOWED: "Field not allowed to be set", - ASYNC_VALIDATION_NOT_SUPPORTED: "Async validation is not supported", - VALIDATION_ERROR: "Validation Error", - MISSING_FIELD: "Field is required" - }); - } -}); - -// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/error/index.mjs -var BetterAuthError; -var init_error = __esm({ - "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/error/index.mjs"() { - init_codes(); - BetterAuthError = class extends Error { - constructor(message2, options) { - super(message2, options); - this.name = "BetterAuthError"; - this.message = message2; - this.stack = ""; - } - }; - } -}); - -// node_modules/.pnpm/@better-auth+utils@0.3.0/node_modules/@better-auth/utils/dist/hex.mjs -var hexadecimal, hex3; -var init_hex = __esm({ - "node_modules/.pnpm/@better-auth+utils@0.3.0/node_modules/@better-auth/utils/dist/hex.mjs"() { - hexadecimal = "0123456789abcdef"; - hex3 = { - encode: (data2) => { - if (typeof data2 === "string") { - data2 = new TextEncoder().encode(data2); - } - if (data2.byteLength === 0) { - return ""; - } - const buffer2 = new Uint8Array(data2); - let result = ""; - for (const byte of buffer2) { - result += byte.toString(16).padStart(2, "0"); - } - return result; - }, - decode: (data2) => { - if (!data2) { - return ""; - } - if (typeof data2 === "string") { - if (data2.length % 2 !== 0) { - throw new Error("Invalid hexadecimal string"); - } - if (!new RegExp(`^[${hexadecimal}]+$`).test(data2)) { - throw new Error("Invalid hexadecimal string"); - } - const result = new Uint8Array(data2.length / 2); - for (let i5 = 0; i5 < data2.length; i5 += 2) { - result[i5 / 2] = parseInt(data2.slice(i5, i5 + 2), 16); - } - return new TextDecoder().decode(result); - } - return new TextDecoder().decode(data2); - } - }; - } -}); - -// node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/pbkdf2.js -function pbkdf2Init(hash2, _password, _salt, _opts) { - ahash(hash2); - const opts = checkOpts({ dkLen: 32, asyncTick: 10 }, _opts); - const { c: c5, dkLen, asyncTick } = opts; - anumber(c5, "c"); - anumber(dkLen, "dkLen"); - anumber(asyncTick, "asyncTick"); - if (c5 < 1) - throw new Error("iterations (c) must be >= 1"); - if (dkLen < 1) - throw new Error('"dkLen" must be >= 1'); - if (dkLen > (2 ** 32 - 1) * hash2.outputLen) - throw new Error("derived key too long"); - const password = kdfInputToBytes(_password, "password"); - const salt = kdfInputToBytes(_salt, "salt"); - const DK = new Uint8Array(dkLen); - const PRF = hmac2.create(hash2, password); - const PRFSalt = PRF._cloneInto().update(salt); - return { c: c5, dkLen, asyncTick, DK, PRF, PRFSalt }; -} -function pbkdf2Output(PRF, PRFSalt, DK, prfW, u5) { - PRF.destroy(); - PRFSalt.destroy(); - if (prfW) - prfW.destroy(); - clean(u5); - return DK; -} -function pbkdf2(hash2, password, salt, opts) { - const { c: c5, dkLen, DK, PRF, PRFSalt } = pbkdf2Init(hash2, password, salt, opts); - let prfW; - const arr = new Uint8Array(4); - const view = createView(arr); - const u5 = new Uint8Array(PRF.outputLen); - for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) { - const Ti = DK.subarray(pos, pos + PRF.outputLen); - view.setInt32(0, ti, false); - (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u5); - Ti.set(u5.subarray(0, Ti.length)); - for (let ui = 1; ui < c5; ui++) { - PRF._cloneInto(prfW).update(u5).digestInto(u5); - for (let i5 = 0; i5 < Ti.length; i5++) - Ti[i5] ^= u5[i5]; - } - } - return pbkdf2Output(PRF, PRFSalt, DK, prfW, u5); -} -var init_pbkdf2 = __esm({ - "node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/pbkdf2.js"() { - init_hmac(); - init_utils6(); - } -}); - -// node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/scrypt.js -function XorAndSalsa(prev, pi, input, ii, out, oi) { - let y00 = prev[pi++] ^ input[ii++], y01 = prev[pi++] ^ input[ii++]; - let y02 = prev[pi++] ^ input[ii++], y03 = prev[pi++] ^ input[ii++]; - let y04 = prev[pi++] ^ input[ii++], y05 = prev[pi++] ^ input[ii++]; - let y06 = prev[pi++] ^ input[ii++], y07 = prev[pi++] ^ input[ii++]; - let y08 = prev[pi++] ^ input[ii++], y09 = prev[pi++] ^ input[ii++]; - let y10 = prev[pi++] ^ input[ii++], y11 = prev[pi++] ^ input[ii++]; - let y12 = prev[pi++] ^ input[ii++], y13 = prev[pi++] ^ input[ii++]; - let y14 = prev[pi++] ^ input[ii++], y15 = prev[pi++] ^ input[ii++]; - let x00 = y00, x01 = y01, x02 = y02, x03 = y03, x04 = y04, x05 = y05, x06 = y06, x07 = y07, x08 = y08, x09 = y09, x10 = y10, x11 = y11, x12 = y12, x13 = y13, x14 = y14, x15 = y15; - for (let i5 = 0; i5 < 8; i5 += 2) { - x04 ^= rotl(x00 + x12 | 0, 7); - x08 ^= rotl(x04 + x00 | 0, 9); - x12 ^= rotl(x08 + x04 | 0, 13); - x00 ^= rotl(x12 + x08 | 0, 18); - x09 ^= rotl(x05 + x01 | 0, 7); - x13 ^= rotl(x09 + x05 | 0, 9); - x01 ^= rotl(x13 + x09 | 0, 13); - x05 ^= rotl(x01 + x13 | 0, 18); - x14 ^= rotl(x10 + x06 | 0, 7); - x02 ^= rotl(x14 + x10 | 0, 9); - x06 ^= rotl(x02 + x14 | 0, 13); - x10 ^= rotl(x06 + x02 | 0, 18); - x03 ^= rotl(x15 + x11 | 0, 7); - x07 ^= rotl(x03 + x15 | 0, 9); - x11 ^= rotl(x07 + x03 | 0, 13); - x15 ^= rotl(x11 + x07 | 0, 18); - x01 ^= rotl(x00 + x03 | 0, 7); - x02 ^= rotl(x01 + x00 | 0, 9); - x03 ^= rotl(x02 + x01 | 0, 13); - x00 ^= rotl(x03 + x02 | 0, 18); - x06 ^= rotl(x05 + x04 | 0, 7); - x07 ^= rotl(x06 + x05 | 0, 9); - x04 ^= rotl(x07 + x06 | 0, 13); - x05 ^= rotl(x04 + x07 | 0, 18); - x11 ^= rotl(x10 + x09 | 0, 7); - x08 ^= rotl(x11 + x10 | 0, 9); - x09 ^= rotl(x08 + x11 | 0, 13); - x10 ^= rotl(x09 + x08 | 0, 18); - x12 ^= rotl(x15 + x14 | 0, 7); - x13 ^= rotl(x12 + x15 | 0, 9); - x14 ^= rotl(x13 + x12 | 0, 13); - x15 ^= rotl(x14 + x13 | 0, 18); - } - out[oi++] = y00 + x00 | 0; - out[oi++] = y01 + x01 | 0; - out[oi++] = y02 + x02 | 0; - out[oi++] = y03 + x03 | 0; - out[oi++] = y04 + x04 | 0; - out[oi++] = y05 + x05 | 0; - out[oi++] = y06 + x06 | 0; - out[oi++] = y07 + x07 | 0; - out[oi++] = y08 + x08 | 0; - out[oi++] = y09 + x09 | 0; - out[oi++] = y10 + x10 | 0; - out[oi++] = y11 + x11 | 0; - out[oi++] = y12 + x12 | 0; - out[oi++] = y13 + x13 | 0; - out[oi++] = y14 + x14 | 0; - out[oi++] = y15 + x15 | 0; -} -function BlockMix(input, ii, out, oi, r5) { - let head = oi + 0; - let tail = oi + 16 * r5; - for (let i5 = 0; i5 < 16; i5++) - out[tail + i5] = input[ii + (2 * r5 - 1) * 16 + i5]; - for (let i5 = 0; i5 < r5; i5++, head += 16, ii += 16) { - XorAndSalsa(out, tail, input, ii, out, head); - if (i5 > 0) - tail += 16; - XorAndSalsa(out, head, input, ii += 16, out, tail); - } -} -function scryptInit(password, salt, _opts) { - const opts = checkOpts({ - dkLen: 32, - asyncTick: 10, - maxmem: 1024 ** 3 + 1024 - }, _opts); - const { N, r: r5, p: p5, dkLen, asyncTick, maxmem, onProgress } = opts; - anumber(N, "N"); - anumber(r5, "r"); - anumber(p5, "p"); - anumber(dkLen, "dkLen"); - anumber(asyncTick, "asyncTick"); - anumber(maxmem, "maxmem"); - if (onProgress !== void 0 && typeof onProgress !== "function") - throw new Error("progressCb must be a function"); - const blockSize = 128 * r5; - const blockSize32 = blockSize / 4; - const pow32 = Math.pow(2, 32); - if (N <= 1 || (N & N - 1) !== 0 || N > pow32) - throw new Error('"N" expected a power of 2, and 2^1 <= N <= 2^32'); - if (p5 < 1 || p5 > (pow32 - 1) * 32 / blockSize) - throw new Error('"p" expected integer 1..((2^32 - 1) * 32) / (128 * r)'); - if (dkLen < 1 || dkLen > (pow32 - 1) * 32) - throw new Error('"dkLen" expected integer 1..(2^32 - 1) * 32'); - const memUsed = blockSize * (N + p5 + 1); - if (memUsed > maxmem) - throw new Error('"maxmem" limit was hit: memUsed(128*r*(N+p+1))=' + memUsed + ", maxmem=" + maxmem); - const B2 = pbkdf2(sha2562, password, salt, { c: 1, dkLen: blockSize * p5 }); - const B32 = u32(B2); - const V = u32(new Uint8Array(blockSize * N)); - const tmp = u32(new Uint8Array(blockSize)); - let blockMixCb = () => { - }; - if (onProgress) { - const totalBlockMix = 2 * N * p5; - const callbackPer = Math.max(Math.floor(totalBlockMix / 1e4), 1); - let blockMixCnt = 0; - blockMixCb = () => { - blockMixCnt++; - if (onProgress && (!(blockMixCnt % callbackPer) || blockMixCnt === totalBlockMix)) - onProgress(blockMixCnt / totalBlockMix); - }; - } - return { N, r: r5, p: p5, dkLen, blockSize32, V, B32, B: B2, tmp, blockMixCb, asyncTick }; -} -function scryptOutput(password, dkLen, B2, V, tmp) { - const res = pbkdf2(sha2562, password, B2, { c: 1, dkLen }); - clean(B2, V, tmp); - return res; -} -async function scryptAsync(password, salt, opts) { - const { N, r: r5, p: p5, dkLen, blockSize32, V, B32, B: B2, tmp, blockMixCb, asyncTick } = scryptInit(password, salt, opts); - swap32IfBE(B32); - for (let pi = 0; pi < p5; pi++) { - const Pi = blockSize32 * pi; - for (let i5 = 0; i5 < blockSize32; i5++) - V[i5] = B32[Pi + i5]; - let pos = 0; - await asyncLoop(N - 1, asyncTick, () => { - BlockMix(V, pos, V, pos += blockSize32, r5); - blockMixCb(); - }); - BlockMix(V, (N - 1) * blockSize32, B32, Pi, r5); - blockMixCb(); - await asyncLoop(N, asyncTick, () => { - const j5 = (B32[Pi + blockSize32 - 16] & N - 1) >>> 0; - for (let k5 = 0; k5 < blockSize32; k5++) - tmp[k5] = B32[Pi + k5] ^ V[j5 * blockSize32 + k5]; - BlockMix(tmp, 0, B32, Pi, r5); - blockMixCb(); - }); - } - swap32IfBE(B32); - return scryptOutput(password, dkLen, B2, V, tmp); -} -var init_scrypt = __esm({ - "node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/scrypt.js"() { - init_pbkdf2(); - init_sha2(); - init_utils6(); - } -}); - -// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/crypto/password.mjs -async function generateKey(password, salt) { - return await scryptAsync(password.normalize("NFKC"), salt, { - N: config2.N, - p: config2.p, - r: config2.r, - dkLen: config2.dkLen, - maxmem: 128 * config2.N * config2.r * 2 - }); -} -var config2, hashPassword, verifyPassword; -var init_password = __esm({ - "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/crypto/password.mjs"() { - init_buffer(); - init_error(); - init_hex(); - init_scrypt(); - init_utils6(); - config2 = { - N: 16384, - r: 16, - p: 1, - dkLen: 64 - }; - hashPassword = async (password) => { - const salt = hex3.encode(crypto.getRandomValues(new Uint8Array(16))); - const key = await generateKey(password, salt); - return `${salt}:${hex3.encode(key)}`; - }; - verifyPassword = async ({ hash: hash2, password }) => { - const [salt, key] = hash2.split(":"); - if (!salt || !key) throw new BetterAuthError("Invalid password hash"); - return constantTimeEqual(await generateKey(password, salt), hexToBytes2(key)); - }; - } -}); - -// node_modules/.pnpm/@better-auth+utils@0.3.0/node_modules/@better-auth/utils/dist/index.mjs -function getWebcryptoSubtle() { - const cr = typeof globalThis !== "undefined" && globalThis.crypto; - if (cr && typeof cr.subtle === "object" && cr.subtle != null) - return cr.subtle; - throw new Error("crypto.subtle must be defined"); -} -var init_dist = __esm({ - "node_modules/.pnpm/@better-auth+utils@0.3.0/node_modules/@better-auth/utils/dist/index.mjs"() { - } -}); - -// node_modules/.pnpm/@better-auth+utils@0.3.0/node_modules/@better-auth/utils/dist/base64.mjs -function getAlphabet(urlSafe) { - return urlSafe ? "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_" : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; -} -function base64Encode(data2, alphabet, padding) { - let result = ""; - let buffer2 = 0; - let shift = 0; - for (const byte of data2) { - buffer2 = buffer2 << 8 | byte; - shift += 8; - while (shift >= 6) { - shift -= 6; - result += alphabet[buffer2 >> shift & 63]; - } - } - if (shift > 0) { - result += alphabet[buffer2 << 6 - shift & 63]; - } - if (padding) { - const padCount = (4 - result.length % 4) % 4; - result += "=".repeat(padCount); - } - return result; -} -function base64Decode(data2, alphabet) { - const decodeMap2 = /* @__PURE__ */ new Map(); - for (let i5 = 0; i5 < alphabet.length; i5++) { - decodeMap2.set(alphabet[i5], i5); - } - const result = []; - let buffer2 = 0; - let bitsCollected = 0; - for (const char2 of data2) { - if (char2 === "=") - break; - const value = decodeMap2.get(char2); - if (value === void 0) { - throw new Error(`Invalid Base64 character: ${char2}`); - } - buffer2 = buffer2 << 6 | value; - bitsCollected += 6; - if (bitsCollected >= 8) { - bitsCollected -= 8; - result.push(buffer2 >> bitsCollected & 255); - } - } - return Uint8Array.from(result); -} -var base643, base64Url; -var init_base642 = __esm({ - "node_modules/.pnpm/@better-auth+utils@0.3.0/node_modules/@better-auth/utils/dist/base64.mjs"() { - base643 = { - encode(data2, options = {}) { - const alphabet = getAlphabet(false); - const buffer2 = typeof data2 === "string" ? new TextEncoder().encode(data2) : new Uint8Array(data2); - return base64Encode(buffer2, alphabet, options.padding ?? true); - }, - decode(data2) { - if (typeof data2 !== "string") { - data2 = new TextDecoder().decode(data2); - } - const urlSafe = data2.includes("-") || data2.includes("_"); - const alphabet = getAlphabet(urlSafe); - return base64Decode(data2, alphabet); - } - }; - base64Url = { - encode(data2, options = {}) { - const alphabet = getAlphabet(true); - const buffer2 = typeof data2 === "string" ? new TextEncoder().encode(data2) : new Uint8Array(data2); - return base64Encode(buffer2, alphabet, options.padding ?? true); - }, - decode(data2) { - const urlSafe = data2.includes("-") || data2.includes("_"); - const alphabet = getAlphabet(urlSafe); - return base64Decode(data2, alphabet); - } - }; - } -}); - -// node_modules/.pnpm/@better-auth+utils@0.3.0/node_modules/@better-auth/utils/dist/hash.mjs -function createHash17(algorithm2, encoding) { - return { - digest: async (input) => { - const encoder3 = new TextEncoder(); - const data2 = typeof input === "string" ? encoder3.encode(input) : input; - const hashBuffer2 = await getWebcryptoSubtle().digest(algorithm2, data2); - if (encoding === "hex") { - const hashArray = Array.from(new Uint8Array(hashBuffer2)); - const hashHex = hashArray.map((b6) => b6.toString(16).padStart(2, "0")).join(""); - return hashHex; - } - if (encoding === "base64" || encoding === "base64url" || encoding === "base64urlnopad") { - if (encoding.includes("url")) { - return base64Url.encode(hashBuffer2, { - padding: encoding !== "base64urlnopad" - }); - } - const hashBase64 = base643.encode(hashBuffer2); - return hashBase64; - } - return hashBuffer2; - } - }; -} -var init_hash = __esm({ - "node_modules/.pnpm/@better-auth+utils@0.3.0/node_modules/@better-auth/utils/dist/hash.mjs"() { - init_base642(); - init_dist(); - } -}); - -// node_modules/.pnpm/@noble+ciphers@2.2.0/node_modules/@noble/ciphers/utils.js -function isBytes2(a5) { - return a5 instanceof Uint8Array || ArrayBuffer.isView(a5) && a5.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a5 && a5.BYTES_PER_ELEMENT === 1; -} -function abool(b6) { - if (typeof b6 !== "boolean") - throw new TypeError(`boolean expected, not ${b6}`); -} -function anumber2(n5) { - if (typeof n5 !== "number") - throw new TypeError("number expected, got " + typeof n5); - if (!Number.isSafeInteger(n5) || n5 < 0) - throw new RangeError("positive integer expected, got " + n5); -} -function abytes2(value, length, title = "") { - const bytes = isBytes2(value); - const len = value?.length; - const needsLen = length !== void 0; - if (!bytes || needsLen && len !== length) { - const prefix = title && `"${title}" `; - const ofLen = needsLen ? ` of length ${length}` : ""; - const got = bytes ? `length=${len}` : `type=${typeof value}`; - const message2 = prefix + "expected Uint8Array" + ofLen + ", got " + got; - if (!bytes) - throw new TypeError(message2); - throw new RangeError(message2); - } - return value; -} -function aexists2(instance, checkFinished = true) { - if (instance.destroyed) - throw new Error("Hash instance has been destroyed"); - if (checkFinished && instance.finished) - throw new Error("Hash#digest() has already been called"); -} -function aoutput2(out, instance, onlyAligned = false) { - abytes2(out, void 0, "output"); - const min = instance.outputLen; - if (out.length < min) { - throw new RangeError("digestInto() expects output buffer of length at least " + min); - } - if (onlyAligned && !isAligned32(out)) - throw new Error("invalid output, must be aligned"); -} -function u322(arr) { - return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); -} -function clean2(...arrays) { - for (let i5 = 0; i5 < arrays.length; i5++) { - arrays[i5].fill(0); - } -} -function createView2(arr) { - return new DataView(arr.buffer, arr.byteOffset, arr.byteLength); -} -function bytesToHex(bytes) { - abytes2(bytes); - if (hasHexBuiltin2) - return bytes.toHex(); - let hex4 = ""; - for (let i5 = 0; i5 < bytes.length; i5++) { - hex4 += hexes[bytes[i5]]; - } - return hex4; -} -function asciiToBase162(ch) { - if (ch >= asciis2._0 && ch <= asciis2._9) - return ch - asciis2._0; - if (ch >= asciis2.A && ch <= asciis2.F) - return ch - (asciis2.A - 10); - if (ch >= asciis2.a && ch <= asciis2.f) - return ch - (asciis2.a - 10); - return; -} -function hexToBytes3(hex4) { - if (typeof hex4 !== "string") - throw new TypeError("hex string expected, got " + typeof hex4); - if (hasHexBuiltin2) { - try { - return Uint8Array.fromHex(hex4); - } catch (error50) { - if (error50 instanceof SyntaxError) - throw new RangeError(error50.message); - throw error50; - } - } - const hl = hex4.length; - const al = hl / 2; - if (hl % 2) - throw new RangeError("hex string expected, got unpadded hex of length " + hl); - const array2 = new Uint8Array(al); - for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) { - const n1 = asciiToBase162(hex4.charCodeAt(hi)); - const n22 = asciiToBase162(hex4.charCodeAt(hi + 1)); - if (n1 === void 0 || n22 === void 0) { - const char2 = hex4[hi] + hex4[hi + 1]; - throw new RangeError('hex string expected, got non-hex character "' + char2 + '" at index ' + hi); - } - array2[ai] = n1 * 16 + n22; - } - return array2; -} -function utf8ToBytes2(str) { - if (typeof str !== "string") - throw new TypeError("string expected"); - return new Uint8Array(new TextEncoder().encode(str)); -} -function overlapBytes(a5, b6) { - if (!a5.byteLength || !b6.byteLength) - return false; - return a5.buffer === b6.buffer && // best we can do, may fail with an obscure Proxy - a5.byteOffset < b6.byteOffset + b6.byteLength && // a starts before b end - b6.byteOffset < a5.byteOffset + a5.byteLength; -} -function concatBytes(...arrays) { - let sum = 0; - for (let i5 = 0; i5 < arrays.length; i5++) { - const a5 = arrays[i5]; - abytes2(a5); - sum += a5.length; - } - const res = new Uint8Array(sum); - for (let i5 = 0, pad = 0; i5 < arrays.length; i5++) { - const a5 = arrays[i5]; - res.set(a5, pad); - pad += a5.length; - } - return res; -} -function checkOpts2(defaults, opts) { - if (opts == null || typeof opts !== "object") - throw new Error("options must be defined"); - const merged = Object.assign(defaults, opts); - return merged; -} -function equalBytes(a5, b6) { - if (a5.length !== b6.length) - return false; - let diff = 0; - for (let i5 = 0; i5 < a5.length; i5++) - diff |= a5[i5] ^ b6[i5]; - return diff === 0; -} -function wrapMacConstructor(keyLen, macCons, fromMsg) { - const mac3 = macCons; - const getArgs = fromMsg || (() => []); - const macC = (msg, key) => mac3(key, ...getArgs(msg)).update(msg).digest(); - const tmp = mac3(new Uint8Array(keyLen), ...getArgs(new Uint8Array(0))); - macC.outputLen = tmp.outputLen; - macC.blockLen = tmp.blockLen; - macC.create = (key, ...args) => mac3(key, ...args); - return macC; -} -function getOutput(expectedLength, out, onlyAligned = true) { - if (out === void 0) - return new Uint8Array(expectedLength); - abytes2(out, void 0, "output"); - if (out.length !== expectedLength) - throw new Error('"output" expected Uint8Array of length ' + expectedLength + ", got: " + out.length); - if (onlyAligned && !isAligned32(out)) - throw new Error("invalid output, must be aligned"); - return out; -} -function u64Lengths(dataLength, aadLength, isLE3) { - anumber2(dataLength); - anumber2(aadLength); - abool(isLE3); - const num = new Uint8Array(16); - const view = createView2(num); - view.setBigUint64(0, BigInt(aadLength), isLE3); - view.setBigUint64(8, BigInt(dataLength), isLE3); - return num; -} -function isAligned32(bytes) { - return bytes.byteOffset % 4 === 0; -} -function copyBytes(bytes) { - return Uint8Array.from(abytes2(bytes)); -} -function randomBytes6(bytesLength = 32) { - anumber2(bytesLength); - const cr = typeof globalThis === "object" ? globalThis.crypto : null; - if (typeof cr?.getRandomValues !== "function") - throw new Error("crypto.getRandomValues must be defined"); - return cr.getRandomValues(new Uint8Array(bytesLength)); -} -function managedNonce(fn, randomBytes_ = randomBytes6) { - const { nonceLength } = fn; - anumber2(nonceLength); - const addNonce = (nonce, ciphertext, plaintext) => { - const out = concatBytes(nonce, ciphertext); - if (!overlapBytes(plaintext, ciphertext)) - ciphertext.fill(0); - return out; - }; - const res = ((key, ...args) => ({ - encrypt(plaintext) { - abytes2(plaintext); - const nonce = randomBytes_(nonceLength); - const encrypted = fn(key, nonce, ...args).encrypt(plaintext); - if (encrypted instanceof Promise) - return encrypted.then((ct) => addNonce(nonce, ct, plaintext)); - return addNonce(nonce, encrypted, plaintext); - }, - decrypt(ciphertext) { - abytes2(ciphertext); - const nonce = ciphertext.subarray(0, nonceLength); - const decrypted = ciphertext.subarray(nonceLength); - return fn(key, nonce, ...args).decrypt(decrypted); - } - })); - if ("blockSize" in fn) - res.blockSize = fn.blockSize; - if ("tagLength" in fn) - res.tagLength = fn.tagLength; - return res; -} -var isLE2, byteSwap2, swap8IfBE, byteSwap322, swap32IfBE2, hasHexBuiltin2, hexes, asciis2, wrapCipher; -var init_utils8 = __esm({ - "node_modules/.pnpm/@noble+ciphers@2.2.0/node_modules/@noble/ciphers/utils.js"() { - isLE2 = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)(); - byteSwap2 = (word) => word << 24 & 4278190080 | word << 8 & 16711680 | word >>> 8 & 65280 | word >>> 24 & 255; - swap8IfBE = isLE2 ? (n5) => n5 : (n5) => byteSwap2(n5) >>> 0; - byteSwap322 = (arr) => { - for (let i5 = 0; i5 < arr.length; i5++) - arr[i5] = byteSwap2(arr[i5]); - return arr; - }; - swap32IfBE2 = isLE2 ? (u5) => u5 : byteSwap322; - hasHexBuiltin2 = /* @__PURE__ */ (() => ( - // @ts-ignore - typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function" - ))(); - hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i5) => i5.toString(16).padStart(2, "0")); - asciis2 = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 }; - wrapCipher = /* @__NO_SIDE_EFFECTS__ */ (params, constructor) => { - function wrappedCipher(key, ...args) { - abytes2(key, void 0, "key"); - if (params.nonceLength !== void 0) { - const nonce = args[0]; - abytes2(nonce, params.varSizeNonce ? void 0 : params.nonceLength, "nonce"); - } - const tagl = params.tagLength; - if (tagl && args[1] !== void 0) - abytes2(args[1], void 0, "AAD"); - const cipher = constructor(key, ...args); - const checkOutput = (fnLength, output) => { - if (output !== void 0) { - if (fnLength !== 2) - throw new Error("cipher output not supported"); - abytes2(output, void 0, "output"); - } - }; - let called = false; - const wrCipher = { - encrypt(data2, output) { - if (called) - throw new Error("cannot encrypt() twice with same key + nonce"); - called = true; - abytes2(data2); - checkOutput(cipher.encrypt.length, output); - return cipher.encrypt(data2, output); - }, - decrypt(data2, output) { - abytes2(data2); - if (tagl && data2.length < tagl) - throw new Error('"ciphertext" expected length bigger than tagLength=' + tagl); - checkOutput(cipher.decrypt.length, output); - return cipher.decrypt(data2, output); - } - }; - return wrCipher; - } - Object.assign(wrappedCipher, params); - return wrappedCipher; - }; - } -}); - -// node_modules/.pnpm/@noble+ciphers@2.2.0/node_modules/@noble/ciphers/_arx.js -function rotl2(a5, b6) { - return a5 << b6 | a5 >>> 32 - b6; -} -function runCipher(core, sigma, key, nonce, data2, output, counter, rounds) { - const len = data2.length; - const block = new Uint8Array(BLOCK_LEN); - const b32 = u322(block); - const isAligned = isLE2 && isAligned32(data2) && isAligned32(output); - const d32 = isAligned ? u322(data2) : U32_EMPTY; - const o32 = isAligned ? u322(output) : U32_EMPTY; - if (!isLE2) { - for (let pos = 0; pos < len; counter++) { - core(sigma, key, nonce, b32, counter, rounds); - swap32IfBE2(b32); - if (counter >= MAX_COUNTER) - throw new Error("arx: counter overflow"); - const take = Math.min(BLOCK_LEN, len - pos); - for (let j5 = 0, posj; j5 < take; j5++) { - posj = pos + j5; - output[posj] = data2[posj] ^ block[j5]; - } - pos += take; - } - return; - } - for (let pos = 0; pos < len; counter++) { - core(sigma, key, nonce, b32, counter, rounds); - if (counter >= MAX_COUNTER) - throw new Error("arx: counter overflow"); - const take = Math.min(BLOCK_LEN, len - pos); - if (isAligned && take === BLOCK_LEN) { - const pos32 = pos / 4; - if (pos % 4 !== 0) - throw new Error("arx: invalid block position"); - for (let j5 = 0, posj; j5 < BLOCK_LEN32; j5++) { - posj = pos32 + j5; - o32[posj] = d32[posj] ^ b32[j5]; - } - pos += BLOCK_LEN; - continue; - } - for (let j5 = 0, posj; j5 < take; j5++) { - posj = pos + j5; - output[posj] = data2[posj] ^ block[j5]; - } - pos += take; - } -} -function createCipher(core, opts) { - const { allowShortKeys, extendNonceFn, counterLength, counterRight, rounds } = checkOpts2({ allowShortKeys: false, counterLength: 8, counterRight: false, rounds: 20 }, opts); - if (typeof core !== "function") - throw new Error("core must be a function"); - anumber2(counterLength); - anumber2(rounds); - abool(counterRight); - abool(allowShortKeys); - return (key, nonce, data2, output, counter = 0) => { - abytes2(key, void 0, "key"); - abytes2(nonce, void 0, "nonce"); - abytes2(data2, void 0, "data"); - const len = data2.length; - output = getOutput(len, output, false); - anumber2(counter); - if (counter < 0 || counter >= MAX_COUNTER) - throw new Error("arx: counter overflow"); - const toClean = []; - let l5 = key.length; - let k5; - let sigma; - if (l5 === 32) { - toClean.push(k5 = copyBytes(key)); - sigma = sigma32_32; - } else if (l5 === 16 && allowShortKeys) { - k5 = new Uint8Array(32); - k5.set(key); - k5.set(key, 16); - sigma = sigma16_32; - toClean.push(k5); - } else { - abytes2(key, 32, "arx key"); - throw new Error("invalid key size"); - } - if (!isLE2 || !isAligned32(nonce)) - toClean.push(nonce = copyBytes(nonce)); - let k32 = u322(k5); - if (extendNonceFn) { - if (nonce.length !== 24) - throw new Error(`arx: extended nonce must be 24 bytes`); - const n16 = nonce.subarray(0, 16); - if (isLE2) - extendNonceFn(sigma, k32, u322(n16), k32); - else { - const sigmaRaw = swap32IfBE2(Uint32Array.from(sigma)); - extendNonceFn(sigmaRaw, k32, u322(n16), k32); - clean2(sigmaRaw); - swap32IfBE2(k32); - } - nonce = nonce.subarray(16); - } else if (!isLE2) - swap32IfBE2(k32); - const nonceNcLen = 16 - counterLength; - if (nonceNcLen !== nonce.length) - throw new Error(`arx: nonce must be ${nonceNcLen} or 16 bytes`); - if (nonceNcLen !== 12) { - const nc = new Uint8Array(12); - nc.set(nonce, counterRight ? 0 : 12 - nonce.length); - nonce = nc; - toClean.push(nonce); - } - const n32 = swap32IfBE2(u322(nonce)); - try { - runCipher(core, sigma, k32, n32, data2, output, counter, rounds); - return output; - } finally { - clean2(...toClean); - } - }; -} -var encodeStr, sigma16_32, sigma32_32, BLOCK_LEN, BLOCK_LEN32, MAX_COUNTER, U32_EMPTY; -var init_arx = __esm({ - "node_modules/.pnpm/@noble+ciphers@2.2.0/node_modules/@noble/ciphers/_arx.js"() { - init_utils8(); - encodeStr = (str) => Uint8Array.from(str.split(""), (c5) => c5.charCodeAt(0)); - sigma16_32 = /* @__PURE__ */ (() => swap32IfBE2(u322(encodeStr("expand 16-byte k"))))(); - sigma32_32 = /* @__PURE__ */ (() => swap32IfBE2(u322(encodeStr("expand 32-byte k"))))(); - BLOCK_LEN = 64; - BLOCK_LEN32 = 16; - MAX_COUNTER = /* @__PURE__ */ (() => 2 ** 32 - 1)(); - U32_EMPTY = /* @__PURE__ */ Uint32Array.of(); - } -}); - -// node_modules/.pnpm/@noble+ciphers@2.2.0/node_modules/@noble/ciphers/_poly1305.js -function u8to16(a5, i5) { - return a5[i5++] & 255 | (a5[i5++] & 255) << 8; -} -var Poly1305, poly1305; -var init_poly1305 = __esm({ - "node_modules/.pnpm/@noble+ciphers@2.2.0/node_modules/@noble/ciphers/_poly1305.js"() { - init_utils8(); - Poly1305 = class { - blockLen = 16; - outputLen = 16; - buffer = new Uint8Array(16); - r = new Uint16Array(10); - // Allocating 1 array with .subarray() here is slower than 3 - h = new Uint16Array(10); - pad = new Uint16Array(8); - pos = 0; - finished = false; - destroyed = false; - // Can be speed-up using BigUint64Array, at the cost of complexity - constructor(key) { - key = copyBytes(abytes2(key, 32, "key")); - const t0 = u8to16(key, 0); - const t1 = u8to16(key, 2); - const t22 = u8to16(key, 4); - const t32 = u8to16(key, 6); - const t42 = u8to16(key, 8); - const t5 = u8to16(key, 10); - const t6 = u8to16(key, 12); - const t7 = u8to16(key, 14); - this.r[0] = t0 & 8191; - this.r[1] = (t0 >>> 13 | t1 << 3) & 8191; - this.r[2] = (t1 >>> 10 | t22 << 6) & 7939; - this.r[3] = (t22 >>> 7 | t32 << 9) & 8191; - this.r[4] = (t32 >>> 4 | t42 << 12) & 255; - this.r[5] = t42 >>> 1 & 8190; - this.r[6] = (t42 >>> 14 | t5 << 2) & 8191; - this.r[7] = (t5 >>> 11 | t6 << 5) & 8065; - this.r[8] = (t6 >>> 8 | t7 << 8) & 8191; - this.r[9] = t7 >>> 5 & 127; - for (let i5 = 0; i5 < 8; i5++) - this.pad[i5] = u8to16(key, 16 + 2 * i5); - } - process(data2, offset, isLast = false) { - const hibit = isLast ? 0 : 1 << 11; - const { h: h5, r: r5 } = this; - const r0 = r5[0]; - const r1 = r5[1]; - const r22 = r5[2]; - const r32 = r5[3]; - const r42 = r5[4]; - const r52 = r5[5]; - const r6 = r5[6]; - const r7 = r5[7]; - const r8 = r5[8]; - const r9 = r5[9]; - const t0 = u8to16(data2, offset + 0); - const t1 = u8to16(data2, offset + 2); - const t22 = u8to16(data2, offset + 4); - const t32 = u8to16(data2, offset + 6); - const t42 = u8to16(data2, offset + 8); - const t5 = u8to16(data2, offset + 10); - const t6 = u8to16(data2, offset + 12); - const t7 = u8to16(data2, offset + 14); - let h0 = h5[0] + (t0 & 8191); - let h1 = h5[1] + ((t0 >>> 13 | t1 << 3) & 8191); - let h22 = h5[2] + ((t1 >>> 10 | t22 << 6) & 8191); - let h32 = h5[3] + ((t22 >>> 7 | t32 << 9) & 8191); - let h42 = h5[4] + ((t32 >>> 4 | t42 << 12) & 8191); - let h52 = h5[5] + (t42 >>> 1 & 8191); - let h6 = h5[6] + ((t42 >>> 14 | t5 << 2) & 8191); - let h7 = h5[7] + ((t5 >>> 11 | t6 << 5) & 8191); - let h8 = h5[8] + ((t6 >>> 8 | t7 << 8) & 8191); - let h9 = h5[9] + (t7 >>> 5 | hibit); - let c5 = 0; - let d0 = c5 + h0 * r0 + h1 * (5 * r9) + h22 * (5 * r8) + h32 * (5 * r7) + h42 * (5 * r6); - c5 = d0 >>> 13; - d0 &= 8191; - d0 += h52 * (5 * r52) + h6 * (5 * r42) + h7 * (5 * r32) + h8 * (5 * r22) + h9 * (5 * r1); - c5 += d0 >>> 13; - d0 &= 8191; - let d1 = c5 + h0 * r1 + h1 * r0 + h22 * (5 * r9) + h32 * (5 * r8) + h42 * (5 * r7); - c5 = d1 >>> 13; - d1 &= 8191; - d1 += h52 * (5 * r6) + h6 * (5 * r52) + h7 * (5 * r42) + h8 * (5 * r32) + h9 * (5 * r22); - c5 += d1 >>> 13; - d1 &= 8191; - let d22 = c5 + h0 * r22 + h1 * r1 + h22 * r0 + h32 * (5 * r9) + h42 * (5 * r8); - c5 = d22 >>> 13; - d22 &= 8191; - d22 += h52 * (5 * r7) + h6 * (5 * r6) + h7 * (5 * r52) + h8 * (5 * r42) + h9 * (5 * r32); - c5 += d22 >>> 13; - d22 &= 8191; - let d32 = c5 + h0 * r32 + h1 * r22 + h22 * r1 + h32 * r0 + h42 * (5 * r9); - c5 = d32 >>> 13; - d32 &= 8191; - d32 += h52 * (5 * r8) + h6 * (5 * r7) + h7 * (5 * r6) + h8 * (5 * r52) + h9 * (5 * r42); - c5 += d32 >>> 13; - d32 &= 8191; - let d42 = c5 + h0 * r42 + h1 * r32 + h22 * r22 + h32 * r1 + h42 * r0; - c5 = d42 >>> 13; - d42 &= 8191; - d42 += h52 * (5 * r9) + h6 * (5 * r8) + h7 * (5 * r7) + h8 * (5 * r6) + h9 * (5 * r52); - c5 += d42 >>> 13; - d42 &= 8191; - let d5 = c5 + h0 * r52 + h1 * r42 + h22 * r32 + h32 * r22 + h42 * r1; - c5 = d5 >>> 13; - d5 &= 8191; - d5 += h52 * r0 + h6 * (5 * r9) + h7 * (5 * r8) + h8 * (5 * r7) + h9 * (5 * r6); - c5 += d5 >>> 13; - d5 &= 8191; - let d6 = c5 + h0 * r6 + h1 * r52 + h22 * r42 + h32 * r32 + h42 * r22; - c5 = d6 >>> 13; - d6 &= 8191; - d6 += h52 * r1 + h6 * r0 + h7 * (5 * r9) + h8 * (5 * r8) + h9 * (5 * r7); - c5 += d6 >>> 13; - d6 &= 8191; - let d7 = c5 + h0 * r7 + h1 * r6 + h22 * r52 + h32 * r42 + h42 * r32; - c5 = d7 >>> 13; - d7 &= 8191; - d7 += h52 * r22 + h6 * r1 + h7 * r0 + h8 * (5 * r9) + h9 * (5 * r8); - c5 += d7 >>> 13; - d7 &= 8191; - let d8 = c5 + h0 * r8 + h1 * r7 + h22 * r6 + h32 * r52 + h42 * r42; - c5 = d8 >>> 13; - d8 &= 8191; - d8 += h52 * r32 + h6 * r22 + h7 * r1 + h8 * r0 + h9 * (5 * r9); - c5 += d8 >>> 13; - d8 &= 8191; - let d9 = c5 + h0 * r9 + h1 * r8 + h22 * r7 + h32 * r6 + h42 * r52; - c5 = d9 >>> 13; - d9 &= 8191; - d9 += h52 * r42 + h6 * r32 + h7 * r22 + h8 * r1 + h9 * r0; - c5 += d9 >>> 13; - d9 &= 8191; - c5 = (c5 << 2) + c5 | 0; - c5 = c5 + d0 | 0; - d0 = c5 & 8191; - c5 = c5 >>> 13; - d1 += c5; - h5[0] = d0; - h5[1] = d1; - h5[2] = d22; - h5[3] = d32; - h5[4] = d42; - h5[5] = d5; - h5[6] = d6; - h5[7] = d7; - h5[8] = d8; - h5[9] = d9; - } - finalize() { - const { h: h5, pad } = this; - const g5 = new Uint16Array(10); - let c5 = h5[1] >>> 13; - h5[1] &= 8191; - for (let i5 = 2; i5 < 10; i5++) { - h5[i5] += c5; - c5 = h5[i5] >>> 13; - h5[i5] &= 8191; - } - h5[0] += c5 * 5; - c5 = h5[0] >>> 13; - h5[0] &= 8191; - h5[1] += c5; - c5 = h5[1] >>> 13; - h5[1] &= 8191; - h5[2] += c5; - g5[0] = h5[0] + 5; - c5 = g5[0] >>> 13; - g5[0] &= 8191; - for (let i5 = 1; i5 < 10; i5++) { - g5[i5] = h5[i5] + c5; - c5 = g5[i5] >>> 13; - g5[i5] &= 8191; - } - g5[9] -= 1 << 13; - let mask = (c5 ^ 1) - 1; - for (let i5 = 0; i5 < 10; i5++) - g5[i5] &= mask; - mask = ~mask; - for (let i5 = 0; i5 < 10; i5++) - h5[i5] = h5[i5] & mask | g5[i5]; - h5[0] = (h5[0] | h5[1] << 13) & 65535; - h5[1] = (h5[1] >>> 3 | h5[2] << 10) & 65535; - h5[2] = (h5[2] >>> 6 | h5[3] << 7) & 65535; - h5[3] = (h5[3] >>> 9 | h5[4] << 4) & 65535; - h5[4] = (h5[4] >>> 12 | h5[5] << 1 | h5[6] << 14) & 65535; - h5[5] = (h5[6] >>> 2 | h5[7] << 11) & 65535; - h5[6] = (h5[7] >>> 5 | h5[8] << 8) & 65535; - h5[7] = (h5[8] >>> 8 | h5[9] << 5) & 65535; - let f5 = h5[0] + pad[0]; - h5[0] = f5 & 65535; - for (let i5 = 1; i5 < 8; i5++) { - f5 = (h5[i5] + pad[i5] | 0) + (f5 >>> 16) | 0; - h5[i5] = f5 & 65535; - } - clean2(g5); - } - update(data2) { - aexists2(this); - abytes2(data2); - data2 = copyBytes(data2); - const { buffer: buffer2, blockLen } = this; - const len = data2.length; - for (let pos = 0; pos < len; ) { - const take = Math.min(blockLen - this.pos, len - pos); - if (take === blockLen) { - for (; blockLen <= len - pos; pos += blockLen) - this.process(data2, pos); - continue; - } - buffer2.set(data2.subarray(pos, pos + take), this.pos); - this.pos += take; - pos += take; - if (this.pos === blockLen) { - this.process(buffer2, 0, false); - this.pos = 0; - } - } - return this; - } - destroy() { - this.destroyed = true; - clean2(this.h, this.r, this.buffer, this.pad); - } - digestInto(out) { - aexists2(this); - aoutput2(out, this); - this.finished = true; - const { buffer: buffer2, h: h5 } = this; - let { pos } = this; - if (pos) { - buffer2[pos++] = 1; - for (; pos < 16; pos++) - buffer2[pos] = 0; - this.process(buffer2, 0, true); - } - this.finalize(); - let opos = 0; - for (let i5 = 0; i5 < 8; i5++) { - out[opos++] = h5[i5] >>> 0; - out[opos++] = h5[i5] >>> 8; - } - } - digest() { - const { buffer: buffer2, outputLen } = this; - this.digestInto(buffer2); - const res = buffer2.slice(0, outputLen); - this.destroy(); - return res; - } - }; - poly1305 = /* @__PURE__ */ wrapMacConstructor(32, (key) => new Poly1305(key)); - } -}); - -// node_modules/.pnpm/@noble+ciphers@2.2.0/node_modules/@noble/ciphers/chacha.js -function chachaCore(s5, k5, n5, out, cnt, rounds = 20) { - let y00 = s5[0], y01 = s5[1], y02 = s5[2], y03 = s5[3], y04 = k5[0], y05 = k5[1], y06 = k5[2], y07 = k5[3], y08 = k5[4], y09 = k5[5], y10 = k5[6], y11 = k5[7], y12 = cnt, y13 = n5[0], y14 = n5[1], y15 = n5[2]; - let x00 = y00, x01 = y01, x02 = y02, x03 = y03, x04 = y04, x05 = y05, x06 = y06, x07 = y07, x08 = y08, x09 = y09, x10 = y10, x11 = y11, x12 = y12, x13 = y13, x14 = y14, x15 = y15; - for (let r5 = 0; r5 < rounds; r5 += 2) { - x00 = x00 + x04 | 0; - x12 = rotl2(x12 ^ x00, 16); - x08 = x08 + x12 | 0; - x04 = rotl2(x04 ^ x08, 12); - x00 = x00 + x04 | 0; - x12 = rotl2(x12 ^ x00, 8); - x08 = x08 + x12 | 0; - x04 = rotl2(x04 ^ x08, 7); - x01 = x01 + x05 | 0; - x13 = rotl2(x13 ^ x01, 16); - x09 = x09 + x13 | 0; - x05 = rotl2(x05 ^ x09, 12); - x01 = x01 + x05 | 0; - x13 = rotl2(x13 ^ x01, 8); - x09 = x09 + x13 | 0; - x05 = rotl2(x05 ^ x09, 7); - x02 = x02 + x06 | 0; - x14 = rotl2(x14 ^ x02, 16); - x10 = x10 + x14 | 0; - x06 = rotl2(x06 ^ x10, 12); - x02 = x02 + x06 | 0; - x14 = rotl2(x14 ^ x02, 8); - x10 = x10 + x14 | 0; - x06 = rotl2(x06 ^ x10, 7); - x03 = x03 + x07 | 0; - x15 = rotl2(x15 ^ x03, 16); - x11 = x11 + x15 | 0; - x07 = rotl2(x07 ^ x11, 12); - x03 = x03 + x07 | 0; - x15 = rotl2(x15 ^ x03, 8); - x11 = x11 + x15 | 0; - x07 = rotl2(x07 ^ x11, 7); - x00 = x00 + x05 | 0; - x15 = rotl2(x15 ^ x00, 16); - x10 = x10 + x15 | 0; - x05 = rotl2(x05 ^ x10, 12); - x00 = x00 + x05 | 0; - x15 = rotl2(x15 ^ x00, 8); - x10 = x10 + x15 | 0; - x05 = rotl2(x05 ^ x10, 7); - x01 = x01 + x06 | 0; - x12 = rotl2(x12 ^ x01, 16); - x11 = x11 + x12 | 0; - x06 = rotl2(x06 ^ x11, 12); - x01 = x01 + x06 | 0; - x12 = rotl2(x12 ^ x01, 8); - x11 = x11 + x12 | 0; - x06 = rotl2(x06 ^ x11, 7); - x02 = x02 + x07 | 0; - x13 = rotl2(x13 ^ x02, 16); - x08 = x08 + x13 | 0; - x07 = rotl2(x07 ^ x08, 12); - x02 = x02 + x07 | 0; - x13 = rotl2(x13 ^ x02, 8); - x08 = x08 + x13 | 0; - x07 = rotl2(x07 ^ x08, 7); - x03 = x03 + x04 | 0; - x14 = rotl2(x14 ^ x03, 16); - x09 = x09 + x14 | 0; - x04 = rotl2(x04 ^ x09, 12); - x03 = x03 + x04 | 0; - x14 = rotl2(x14 ^ x03, 8); - x09 = x09 + x14 | 0; - x04 = rotl2(x04 ^ x09, 7); - } - let oi = 0; - out[oi++] = y00 + x00 | 0; - out[oi++] = y01 + x01 | 0; - out[oi++] = y02 + x02 | 0; - out[oi++] = y03 + x03 | 0; - out[oi++] = y04 + x04 | 0; - out[oi++] = y05 + x05 | 0; - out[oi++] = y06 + x06 | 0; - out[oi++] = y07 + x07 | 0; - out[oi++] = y08 + x08 | 0; - out[oi++] = y09 + x09 | 0; - out[oi++] = y10 + x10 | 0; - out[oi++] = y11 + x11 | 0; - out[oi++] = y12 + x12 | 0; - out[oi++] = y13 + x13 | 0; - out[oi++] = y14 + x14 | 0; - out[oi++] = y15 + x15 | 0; -} -function hchacha(s5, k5, i5, out) { - let x00 = swap8IfBE(s5[0]), x01 = swap8IfBE(s5[1]), x02 = swap8IfBE(s5[2]), x03 = swap8IfBE(s5[3]), x04 = swap8IfBE(k5[0]), x05 = swap8IfBE(k5[1]), x06 = swap8IfBE(k5[2]), x07 = swap8IfBE(k5[3]), x08 = swap8IfBE(k5[4]), x09 = swap8IfBE(k5[5]), x10 = swap8IfBE(k5[6]), x11 = swap8IfBE(k5[7]), x12 = swap8IfBE(i5[0]), x13 = swap8IfBE(i5[1]), x14 = swap8IfBE(i5[2]), x15 = swap8IfBE(i5[3]); - for (let r5 = 0; r5 < 20; r5 += 2) { - x00 = x00 + x04 | 0; - x12 = rotl2(x12 ^ x00, 16); - x08 = x08 + x12 | 0; - x04 = rotl2(x04 ^ x08, 12); - x00 = x00 + x04 | 0; - x12 = rotl2(x12 ^ x00, 8); - x08 = x08 + x12 | 0; - x04 = rotl2(x04 ^ x08, 7); - x01 = x01 + x05 | 0; - x13 = rotl2(x13 ^ x01, 16); - x09 = x09 + x13 | 0; - x05 = rotl2(x05 ^ x09, 12); - x01 = x01 + x05 | 0; - x13 = rotl2(x13 ^ x01, 8); - x09 = x09 + x13 | 0; - x05 = rotl2(x05 ^ x09, 7); - x02 = x02 + x06 | 0; - x14 = rotl2(x14 ^ x02, 16); - x10 = x10 + x14 | 0; - x06 = rotl2(x06 ^ x10, 12); - x02 = x02 + x06 | 0; - x14 = rotl2(x14 ^ x02, 8); - x10 = x10 + x14 | 0; - x06 = rotl2(x06 ^ x10, 7); - x03 = x03 + x07 | 0; - x15 = rotl2(x15 ^ x03, 16); - x11 = x11 + x15 | 0; - x07 = rotl2(x07 ^ x11, 12); - x03 = x03 + x07 | 0; - x15 = rotl2(x15 ^ x03, 8); - x11 = x11 + x15 | 0; - x07 = rotl2(x07 ^ x11, 7); - x00 = x00 + x05 | 0; - x15 = rotl2(x15 ^ x00, 16); - x10 = x10 + x15 | 0; - x05 = rotl2(x05 ^ x10, 12); - x00 = x00 + x05 | 0; - x15 = rotl2(x15 ^ x00, 8); - x10 = x10 + x15 | 0; - x05 = rotl2(x05 ^ x10, 7); - x01 = x01 + x06 | 0; - x12 = rotl2(x12 ^ x01, 16); - x11 = x11 + x12 | 0; - x06 = rotl2(x06 ^ x11, 12); - x01 = x01 + x06 | 0; - x12 = rotl2(x12 ^ x01, 8); - x11 = x11 + x12 | 0; - x06 = rotl2(x06 ^ x11, 7); - x02 = x02 + x07 | 0; - x13 = rotl2(x13 ^ x02, 16); - x08 = x08 + x13 | 0; - x07 = rotl2(x07 ^ x08, 12); - x02 = x02 + x07 | 0; - x13 = rotl2(x13 ^ x02, 8); - x08 = x08 + x13 | 0; - x07 = rotl2(x07 ^ x08, 7); - x03 = x03 + x04 | 0; - x14 = rotl2(x14 ^ x03, 16); - x09 = x09 + x14 | 0; - x04 = rotl2(x04 ^ x09, 12); - x03 = x03 + x04 | 0; - x14 = rotl2(x14 ^ x03, 8); - x09 = x09 + x14 | 0; - x04 = rotl2(x04 ^ x09, 7); - } - let oi = 0; - out[oi++] = x00; - out[oi++] = x01; - out[oi++] = x02; - out[oi++] = x03; - out[oi++] = x12; - out[oi++] = x13; - out[oi++] = x14; - out[oi++] = x15; - swap32IfBE2(out); -} -function computeTag(fn, key, nonce, ciphertext, AAD) { - if (AAD !== void 0) - abytes2(AAD, void 0, "AAD"); - const authKey = fn(key, nonce, ZEROS32); - const lengths = u64Lengths(ciphertext.length, AAD ? AAD.length : 0, true); - const h5 = poly1305.create(authKey); - if (AAD) - updatePadded(h5, AAD); - updatePadded(h5, ciphertext); - h5.update(lengths); - const res = h5.digest(); - clean2(authKey, lengths); - return res; -} -var xchacha20, ZEROS16, updatePadded, ZEROS32, _poly1305_aead, xchacha20poly1305; -var init_chacha = __esm({ - "node_modules/.pnpm/@noble+ciphers@2.2.0/node_modules/@noble/ciphers/chacha.js"() { - init_arx(); - init_poly1305(); - init_utils8(); - xchacha20 = /* @__PURE__ */ createCipher(chachaCore, { - counterRight: false, - counterLength: 8, - extendNonceFn: hchacha, - allowShortKeys: false - }); - ZEROS16 = /* @__PURE__ */ new Uint8Array(16); - updatePadded = (h5, msg) => { - h5.update(msg); - const leftover = msg.length % 16; - if (leftover) - h5.update(ZEROS16.subarray(leftover)); - }; - ZEROS32 = /* @__PURE__ */ new Uint8Array(32); - _poly1305_aead = (xorStream) => (key, nonce, AAD) => { - const tagLength = 16; - return { - encrypt(plaintext, output) { - const plength = plaintext.length; - output = getOutput(plength + tagLength, output, false); - output.set(plaintext); - const oPlain = output.subarray(0, -tagLength); - xorStream(key, nonce, oPlain, oPlain, 1); - const tag3 = computeTag(xorStream, key, nonce, oPlain, AAD); - output.set(tag3, plength); - clean2(tag3); - return output; - }, - decrypt(ciphertext, output) { - output = getOutput(ciphertext.length - tagLength, output, false); - const data2 = ciphertext.subarray(0, -tagLength); - const passedTag = ciphertext.subarray(-tagLength); - const tag3 = computeTag(xorStream, key, nonce, data2, AAD); - if (!equalBytes(passedTag, tag3)) { - clean2(tag3); - throw new Error("invalid tag"); - } - output.set(ciphertext.subarray(0, -tagLength)); - xorStream(key, nonce, output, output, 1); - clean2(tag3); - return output; - } - }; - }; - xchacha20poly1305 = /* @__PURE__ */ wrapCipher( - { blockSize: 64, nonceLength: 24, tagLength: 16 }, - /* @__PURE__ */ _poly1305_aead(xchacha20) - ); - } -}); - -// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/crypto/index.mjs -var symmetricEncrypt, symmetricDecrypt; -var init_crypto = __esm({ - "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/crypto/index.mjs"() { - init_buffer(); - init_jwt(); - init_password(); - init_random2(); - init_dist(); - init_hash(); - init_chacha(); - init_utils8(); - symmetricEncrypt = async ({ key, data: data2 }) => { - const keyAsBytes = await createHash17("SHA-256").digest(key); - const dataAsBytes = utf8ToBytes2(data2); - return bytesToHex(managedNonce(xchacha20poly1305)(new Uint8Array(keyAsBytes)).encrypt(dataAsBytes)); - }; - symmetricDecrypt = async ({ key, data: data2 }) => { - const keyAsBytes = await createHash17("SHA-256").digest(key); - const dataAsBytes = hexToBytes3(data2); - const chacha = managedNonce(xchacha20poly1305)(new Uint8Array(keyAsBytes)); - return new TextDecoder().decode(chacha.decrypt(dataAsBytes)); - }; - } -}); - -// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/utils/date.mjs -var getDate; -var init_date2 = __esm({ - "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/utils/date.mjs"() { - getDate = (span, unit = "ms") => { - return new Date(Date.now() + (unit === "sec" ? span * 1e3 : span)); - }; - } -}); - -// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/db/get-tables.mjs -var getAuthTables; -var init_get_tables = __esm({ - "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/db/get-tables.mjs"() { - getAuthTables = (options) => { - const pluginSchema = (options.plugins ?? []).reduce((acc, plugin) => { - const schema2 = plugin.schema; - if (!schema2) return acc; - for (const [key, value] of Object.entries(schema2)) acc[key] = { - fields: { - ...acc[key]?.fields, - ...value.fields - }, - modelName: value.modelName || key - }; - return acc; - }, {}); - const shouldAddRateLimitTable = options.rateLimit?.storage === "database"; - const rateLimitTable = { rateLimit: { - modelName: options.rateLimit?.modelName || "rateLimit", - fields: { - key: { - type: "string", - unique: true, - required: true, - fieldName: options.rateLimit?.fields?.key || "key" - }, - count: { - type: "number", - required: true, - fieldName: options.rateLimit?.fields?.count || "count" - }, - lastRequest: { - type: "number", - bigint: true, - required: true, - fieldName: options.rateLimit?.fields?.lastRequest || "lastRequest", - defaultValue: () => Date.now() - } - } - } }; - const { user, session, account, verification, ...pluginTables } = pluginSchema; - const sessionTable = { session: { - modelName: options.session?.modelName || "session", - fields: { - expiresAt: { - type: "date", - required: true, - fieldName: options.session?.fields?.expiresAt || "expiresAt" - }, - token: { - type: "string", - required: true, - fieldName: options.session?.fields?.token || "token", - unique: true - }, - createdAt: { - type: "date", - required: true, - fieldName: options.session?.fields?.createdAt || "createdAt", - defaultValue: () => /* @__PURE__ */ new Date() - }, - updatedAt: { - type: "date", - required: true, - fieldName: options.session?.fields?.updatedAt || "updatedAt", - onUpdate: () => /* @__PURE__ */ new Date() - }, - ipAddress: { - type: "string", - required: false, - fieldName: options.session?.fields?.ipAddress || "ipAddress" - }, - userAgent: { - type: "string", - required: false, - fieldName: options.session?.fields?.userAgent || "userAgent" - }, - userId: { - type: "string", - fieldName: options.session?.fields?.userId || "userId", - references: { - model: options.user?.modelName || "user", - field: "id", - onDelete: "cascade" - }, - required: true, - index: true - }, - ...session?.fields, - ...options.session?.additionalFields - }, - order: 2 - } }; - return { - user: { - modelName: options.user?.modelName || "user", - fields: { - name: { - type: "string", - required: true, - fieldName: options.user?.fields?.name || "name", - sortable: true - }, - email: { - type: "string", - unique: true, - required: true, - fieldName: options.user?.fields?.email || "email", - sortable: true - }, - emailVerified: { - type: "boolean", - defaultValue: false, - required: true, - fieldName: options.user?.fields?.emailVerified || "emailVerified", - input: false - }, - image: { - type: "string", - required: false, - fieldName: options.user?.fields?.image || "image" - }, - createdAt: { - type: "date", - defaultValue: () => /* @__PURE__ */ new Date(), - required: true, - fieldName: options.user?.fields?.createdAt || "createdAt" - }, - updatedAt: { - type: "date", - defaultValue: () => /* @__PURE__ */ new Date(), - onUpdate: () => /* @__PURE__ */ new Date(), - required: true, - fieldName: options.user?.fields?.updatedAt || "updatedAt" - }, - ...user?.fields, - ...options.user?.additionalFields - }, - order: 1 - }, - ...!options.secondaryStorage || options.session?.storeSessionInDatabase ? sessionTable : {}, - account: { - modelName: options.account?.modelName || "account", - fields: { - accountId: { - type: "string", - required: true, - fieldName: options.account?.fields?.accountId || "accountId" - }, - providerId: { - type: "string", - required: true, - fieldName: options.account?.fields?.providerId || "providerId" - }, - userId: { - type: "string", - references: { - model: options.user?.modelName || "user", - field: "id", - onDelete: "cascade" - }, - required: true, - fieldName: options.account?.fields?.userId || "userId", - index: true - }, - accessToken: { - type: "string", - required: false, - returned: false, - fieldName: options.account?.fields?.accessToken || "accessToken" - }, - refreshToken: { - type: "string", - required: false, - returned: false, - fieldName: options.account?.fields?.refreshToken || "refreshToken" - }, - idToken: { - type: "string", - required: false, - returned: false, - fieldName: options.account?.fields?.idToken || "idToken" - }, - accessTokenExpiresAt: { - type: "date", - required: false, - returned: false, - fieldName: options.account?.fields?.accessTokenExpiresAt || "accessTokenExpiresAt" - }, - refreshTokenExpiresAt: { - type: "date", - required: false, - returned: false, - fieldName: options.account?.fields?.refreshTokenExpiresAt || "refreshTokenExpiresAt" - }, - scope: { - type: "string", - required: false, - fieldName: options.account?.fields?.scope || "scope" - }, - password: { - type: "string", - required: false, - returned: false, - fieldName: options.account?.fields?.password || "password" - }, - createdAt: { - type: "date", - required: true, - fieldName: options.account?.fields?.createdAt || "createdAt", - defaultValue: () => /* @__PURE__ */ new Date() - }, - updatedAt: { - type: "date", - required: true, - fieldName: options.account?.fields?.updatedAt || "updatedAt", - onUpdate: () => /* @__PURE__ */ new Date() - }, - ...account?.fields, - ...options.account?.additionalFields - }, - order: 3 - }, - verification: { - modelName: options.verification?.modelName || "verification", - fields: { - identifier: { - type: "string", - required: true, - fieldName: options.verification?.fields?.identifier || "identifier", - index: true - }, - value: { - type: "string", - required: true, - fieldName: options.verification?.fields?.value || "value" - }, - expiresAt: { - type: "date", - required: true, - fieldName: options.verification?.fields?.expiresAt || "expiresAt" - }, - createdAt: { - type: "date", - required: true, - defaultValue: () => /* @__PURE__ */ new Date(), - fieldName: options.verification?.fields?.createdAt || "createdAt" - }, - updatedAt: { - type: "date", - required: true, - defaultValue: () => /* @__PURE__ */ new Date(), - onUpdate: () => /* @__PURE__ */ new Date(), - fieldName: options.verification?.fields?.updatedAt || "updatedAt" - }, - ...verification?.fields, - ...options.verification?.additionalFields - }, - order: 4 - }, - ...pluginTables, - ...shouldAddRateLimitTable ? rateLimitTable : {} - }; - }; - } -}); - -// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/db/schema/shared.mjs -var coreSchema; -var init_shared = __esm({ - "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/db/schema/shared.mjs"() { - init_zod(); - coreSchema = object({ - id: string2(), - createdAt: date5().default(() => /* @__PURE__ */ new Date()), - updatedAt: date5().default(() => /* @__PURE__ */ new Date()) - }); - } -}); - -// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/db/schema/account.mjs -var accountSchema; -var init_account = __esm({ - "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/db/schema/account.mjs"() { - init_shared(); - init_zod(); - accountSchema = coreSchema.extend({ - providerId: string2(), - accountId: string2(), - userId: coerce_exports.string(), - accessToken: string2().nullish(), - refreshToken: string2().nullish(), - idToken: string2().nullish(), - accessTokenExpiresAt: date5().nullish(), - refreshTokenExpiresAt: date5().nullish(), - scope: string2().nullish(), - password: string2().nullish() - }); - } -}); - -// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/db/schema/rate-limit.mjs -var rateLimitSchema; -var init_rate_limit = __esm({ - "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/db/schema/rate-limit.mjs"() { - init_zod(); - rateLimitSchema = object({ - key: string2(), - count: number2(), - lastRequest: number2() - }); - } -}); - -// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/db/schema/session.mjs -var sessionSchema; -var init_session3 = __esm({ - "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/db/schema/session.mjs"() { - init_shared(); - init_zod(); - sessionSchema = coreSchema.extend({ - userId: coerce_exports.string(), - expiresAt: date5(), - token: string2(), - ipAddress: string2().nullish(), - userAgent: string2().nullish() - }); - } -}); - -// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/db/schema/user.mjs -var userSchema; -var init_user = __esm({ - "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/db/schema/user.mjs"() { - init_shared(); - init_zod(); - userSchema = coreSchema.extend({ - email: string2().transform((val) => val.toLowerCase()), - emailVerified: boolean3().default(false), - name: string2(), - image: string2().nullish() - }); - } -}); - -// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/db/schema/verification.mjs -var verificationSchema; -var init_verification = __esm({ - "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/db/schema/verification.mjs"() { - init_shared(); - init_zod(); - verificationSchema = coreSchema.extend({ - value: string2(), - expiresAt: date5(), - identifier: string2() - }); - } -}); - -// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/db/index.mjs -var db_exports = {}; -__export(db_exports, { - accountSchema: () => accountSchema, - coreSchema: () => coreSchema, - getAuthTables: () => getAuthTables, - rateLimitSchema: () => rateLimitSchema, - sessionSchema: () => sessionSchema, - userSchema: () => userSchema, - verificationSchema: () => verificationSchema -}); -var init_db3 = __esm({ - "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/db/index.mjs"() { - init_get_tables(); - init_shared(); - init_account(); - init_rate_limit(); - init_session3(); - init_user(); - init_verification(); - } -}); - -// node_modules/.pnpm/better-call@1.1.8_zod@4.3.6/node_modules/better-call/dist/error.mjs -function isErrorStackTraceLimitWritable() { - const desc3 = Object.getOwnPropertyDescriptor(Error, "stackTraceLimit"); - if (desc3 === void 0) return Object.isExtensible(Error); - return Object.prototype.hasOwnProperty.call(desc3, "writable") ? desc3.writable : desc3.set !== void 0; -} -function hideInternalStackFrames(stack) { - const lines = stack.split("\n at "); - if (lines.length <= 1) return stack; - lines.splice(1, 1); - return lines.join("\n at "); -} -function makeErrorForHideStackFrame(Base, clazz) { - class HideStackFramesError extends Base { - #hiddenStack; - constructor(...args) { - if (isErrorStackTraceLimitWritable()) { - const limit = Error.stackTraceLimit; - Error.stackTraceLimit = 0; - super(...args); - Error.stackTraceLimit = limit; - } else super(...args); - const stack = (/* @__PURE__ */ new Error()).stack; - if (stack) this.#hiddenStack = hideInternalStackFrames(stack.replace(/^Error/, this.name)); - } - get errorStack() { - return this.#hiddenStack; - } - } - Object.defineProperty(HideStackFramesError.prototype, "constructor", { - get() { - return clazz; - }, - enumerable: false, - configurable: true - }); - return HideStackFramesError; -} -var statusCodes, InternalAPIError, ValidationError, BetterCallError, APIError; -var init_error2 = __esm({ - "node_modules/.pnpm/better-call@1.1.8_zod@4.3.6/node_modules/better-call/dist/error.mjs"() { - statusCodes = { - OK: 200, - CREATED: 201, - ACCEPTED: 202, - NO_CONTENT: 204, - MULTIPLE_CHOICES: 300, - MOVED_PERMANENTLY: 301, - FOUND: 302, - SEE_OTHER: 303, - NOT_MODIFIED: 304, - TEMPORARY_REDIRECT: 307, - BAD_REQUEST: 400, - UNAUTHORIZED: 401, - PAYMENT_REQUIRED: 402, - FORBIDDEN: 403, - NOT_FOUND: 404, - METHOD_NOT_ALLOWED: 405, - NOT_ACCEPTABLE: 406, - PROXY_AUTHENTICATION_REQUIRED: 407, - REQUEST_TIMEOUT: 408, - CONFLICT: 409, - GONE: 410, - LENGTH_REQUIRED: 411, - PRECONDITION_FAILED: 412, - PAYLOAD_TOO_LARGE: 413, - URI_TOO_LONG: 414, - UNSUPPORTED_MEDIA_TYPE: 415, - RANGE_NOT_SATISFIABLE: 416, - EXPECTATION_FAILED: 417, - "I'M_A_TEAPOT": 418, - MISDIRECTED_REQUEST: 421, - UNPROCESSABLE_ENTITY: 422, - LOCKED: 423, - FAILED_DEPENDENCY: 424, - TOO_EARLY: 425, - UPGRADE_REQUIRED: 426, - PRECONDITION_REQUIRED: 428, - TOO_MANY_REQUESTS: 429, - REQUEST_HEADER_FIELDS_TOO_LARGE: 431, - UNAVAILABLE_FOR_LEGAL_REASONS: 451, - INTERNAL_SERVER_ERROR: 500, - NOT_IMPLEMENTED: 501, - BAD_GATEWAY: 502, - SERVICE_UNAVAILABLE: 503, - GATEWAY_TIMEOUT: 504, - HTTP_VERSION_NOT_SUPPORTED: 505, - VARIANT_ALSO_NEGOTIATES: 506, - INSUFFICIENT_STORAGE: 507, - LOOP_DETECTED: 508, - NOT_EXTENDED: 510, - NETWORK_AUTHENTICATION_REQUIRED: 511 - }; - InternalAPIError = class extends Error { - constructor(status = "INTERNAL_SERVER_ERROR", body = void 0, headers = {}, statusCode = typeof status === "number" ? status : statusCodes[status]) { - super(body?.message, body?.cause ? { cause: body.cause } : void 0); - this.status = status; - this.body = body; - this.headers = headers; - this.statusCode = statusCode; - this.name = "APIError"; - this.status = status; - this.headers = headers; - this.statusCode = statusCode; - this.body = body ? { - code: body?.message?.toUpperCase().replace(/ /g, "_").replace(/[^A-Z0-9_]/g, ""), - ...body - } : void 0; - } - }; - ValidationError = class extends InternalAPIError { - constructor(message2, issues2) { - super(400, { - message: message2, - code: "VALIDATION_ERROR" - }); - this.message = message2; - this.issues = issues2; - this.issues = issues2; - } - }; - BetterCallError = class extends Error { - constructor(message2) { - super(message2); - this.name = "BetterCallError"; - } - }; - APIError = makeErrorForHideStackFrame(InternalAPIError, Error); - } -}); - -// node_modules/.pnpm/better-call@1.1.8_zod@4.3.6/node_modules/better-call/dist/utils.mjs -async function getBody(request, allowedMediaTypes) { - const contentType = request.headers.get("content-type") || ""; - const normalizedContentType = contentType.toLowerCase(); - if (!request.body) return; - if (allowedMediaTypes && allowedMediaTypes.length > 0) { - if (!allowedMediaTypes.some((allowed2) => { - const normalizedContentTypeBase = normalizedContentType.split(";")[0].trim(); - const normalizedAllowed = allowed2.toLowerCase().trim(); - return normalizedContentTypeBase === normalizedAllowed || normalizedContentTypeBase.includes(normalizedAllowed); - })) { - if (!normalizedContentType) throw new APIError(415, { - message: `Content-Type is required. Allowed types: ${allowedMediaTypes.join(", ")}`, - code: "UNSUPPORTED_MEDIA_TYPE" - }); - throw new APIError(415, { - message: `Content-Type "${contentType}" is not allowed. Allowed types: ${allowedMediaTypes.join(", ")}`, - code: "UNSUPPORTED_MEDIA_TYPE" - }); - } - } - if (jsonContentTypeRegex.test(normalizedContentType)) return await request.json(); - if (normalizedContentType.includes("application/x-www-form-urlencoded")) { - const formData = await request.formData(); - const result = {}; - formData.forEach((value, key) => { - result[key] = value.toString(); - }); - return result; - } - if (normalizedContentType.includes("multipart/form-data")) { - const formData = await request.formData(); - const result = {}; - formData.forEach((value, key) => { - result[key] = value; - }); - return result; - } - if (normalizedContentType.includes("text/plain")) return await request.text(); - if (normalizedContentType.includes("application/octet-stream")) return await request.arrayBuffer(); - if (normalizedContentType.includes("application/pdf") || normalizedContentType.includes("image/") || normalizedContentType.includes("video/")) return await request.blob(); - if (normalizedContentType.includes("application/stream") || request.body instanceof ReadableStream) return request.body; - return await request.text(); -} -function isAPIError(error50) { - return error50 instanceof APIError || error50?.name === "APIError"; -} -function tryDecode(str) { - try { - return str.includes("%") ? decodeURIComponent(str) : str; - } catch { - return str; - } -} -async function tryCatch(promise2) { - try { - return { - data: await promise2, - error: null - }; - } catch (error50) { - return { - data: null, - error: error50 - }; - } -} -function isRequest(obj) { - return obj instanceof Request || Object.prototype.toString.call(obj) === "[object Request]"; -} -var jsonContentTypeRegex; -var init_utils9 = __esm({ - "node_modules/.pnpm/better-call@1.1.8_zod@4.3.6/node_modules/better-call/dist/utils.mjs"() { - init_error2(); - jsonContentTypeRegex = /^application\/([a-z0-9.+-]*\+)?json/i; - } -}); - -// node_modules/.pnpm/better-call@1.1.8_zod@4.3.6/node_modules/better-call/dist/to-response.mjs -function isJSONSerializable(value) { - if (value === void 0) return false; - const t5 = typeof value; - if (t5 === "string" || t5 === "number" || t5 === "boolean" || t5 === null) return true; - if (t5 !== "object") return false; - if (Array.isArray(value)) return true; - if (value.buffer) return false; - return value.constructor && value.constructor.name === "Object" || typeof value.toJSON === "function"; -} -function safeStringify(obj, replacer, space) { - let id = 0; - const seen = /* @__PURE__ */ new WeakMap(); - const safeReplacer = (key, value) => { - if (typeof value === "bigint") return value.toString(); - if (typeof value === "object" && value !== null) { - if (seen.has(value)) return `[Circular ref-${seen.get(value)}]`; - seen.set(value, id++); - } - if (replacer) return replacer(key, value); - return value; - }; - return JSON.stringify(obj, safeReplacer, space); -} -function isJSONResponse(value) { - if (!value || typeof value !== "object") return false; - return "_flag" in value && value._flag === "json"; -} -function toResponse(data2, init2) { - if (data2 instanceof Response) { - if (init2?.headers instanceof Headers) init2.headers.forEach((value, key) => { - data2.headers.set(key, value); - }); - return data2; - } - if (isJSONResponse(data2)) { - const body$1 = data2.body; - const routerResponse = data2.routerResponse; - if (routerResponse instanceof Response) return routerResponse; - const headers$1 = new Headers(); - if (routerResponse?.headers) { - const headers$2 = new Headers(routerResponse.headers); - for (const [key, value] of headers$2.entries()) headers$2.set(key, value); - } - if (data2.headers) for (const [key, value] of new Headers(data2.headers).entries()) headers$1.set(key, value); - if (init2?.headers) for (const [key, value] of new Headers(init2.headers).entries()) headers$1.set(key, value); - headers$1.set("Content-Type", "application/json"); - return new Response(JSON.stringify(body$1), { - ...routerResponse, - headers: headers$1, - status: data2.status ?? init2?.status ?? routerResponse?.status, - statusText: init2?.statusText ?? routerResponse?.statusText - }); - } - if (isAPIError(data2)) return toResponse(data2.body, { - status: init2?.status ?? data2.statusCode, - statusText: data2.status.toString(), - headers: init2?.headers || data2.headers - }); - let body = data2; - let headers = new Headers(init2?.headers); - if (!data2) { - if (data2 === null) body = JSON.stringify(null); - headers.set("content-type", "application/json"); - } else if (typeof data2 === "string") { - body = data2; - headers.set("Content-Type", "text/plain"); - } else if (data2 instanceof ArrayBuffer || ArrayBuffer.isView(data2)) { - body = data2; - headers.set("Content-Type", "application/octet-stream"); - } else if (data2 instanceof Blob) { - body = data2; - headers.set("Content-Type", data2.type || "application/octet-stream"); - } else if (data2 instanceof FormData) body = data2; - else if (data2 instanceof URLSearchParams) { - body = data2; - headers.set("Content-Type", "application/x-www-form-urlencoded"); - } else if (data2 instanceof ReadableStream) { - body = data2; - headers.set("Content-Type", "application/octet-stream"); - } else if (isJSONSerializable(data2)) { - body = safeStringify(data2); - headers.set("Content-Type", "application/json"); - } - return new Response(body, { - ...init2, - headers - }); -} -var init_to_response = __esm({ - "node_modules/.pnpm/better-call@1.1.8_zod@4.3.6/node_modules/better-call/dist/to-response.mjs"() { - init_error2(); - init_utils9(); - } -}); - -// node_modules/.pnpm/better-call@1.1.8_zod@4.3.6/node_modules/better-call/dist/crypto.mjs -var algorithm, getCryptoKey3, verifySignature, makeSignature, signCookieValue; -var init_crypto2 = __esm({ - "node_modules/.pnpm/better-call@1.1.8_zod@4.3.6/node_modules/better-call/dist/crypto.mjs"() { - init_dist(); - algorithm = { - name: "HMAC", - hash: "SHA-256" - }; - getCryptoKey3 = async (secret) => { - const secretBuf = typeof secret === "string" ? new TextEncoder().encode(secret) : secret; - return await getWebcryptoSubtle().importKey("raw", secretBuf, algorithm, false, ["sign", "verify"]); - }; - verifySignature = async (base64Signature, value, secret) => { - try { - const signatureBinStr = atob(base64Signature); - const signature = new Uint8Array(signatureBinStr.length); - for (let i5 = 0, len = signatureBinStr.length; i5 < len; i5++) signature[i5] = signatureBinStr.charCodeAt(i5); - return await getWebcryptoSubtle().verify(algorithm, secret, signature, new TextEncoder().encode(value)); - } catch (e5) { - return false; - } - }; - makeSignature = async (value, secret) => { - const key = await getCryptoKey3(secret); - const signature = await getWebcryptoSubtle().sign(algorithm.name, key, new TextEncoder().encode(value)); - return btoa(String.fromCharCode(...new Uint8Array(signature))); - }; - signCookieValue = async (value, secret) => { - const signature = await makeSignature(value, secret); - value = `${value}.${signature}`; - value = encodeURIComponent(value); - return value; - }; - } -}); - -// node_modules/.pnpm/better-call@1.1.8_zod@4.3.6/node_modules/better-call/dist/cookies.mjs -function parseCookies(str) { - if (typeof str !== "string") throw new TypeError("argument str must be a string"); - const cookies = /* @__PURE__ */ new Map(); - let index2 = 0; - while (index2 < str.length) { - const eqIdx = str.indexOf("=", index2); - if (eqIdx === -1) break; - let endIdx = str.indexOf(";", index2); - if (endIdx === -1) endIdx = str.length; - else if (endIdx < eqIdx) { - index2 = str.lastIndexOf(";", eqIdx - 1) + 1; - continue; - } - const key = str.slice(index2, eqIdx).trim(); - if (!cookies.has(key)) { - let val = str.slice(eqIdx + 1, endIdx).trim(); - if (val.codePointAt(0) === 34) val = val.slice(1, -1); - cookies.set(key, tryDecode(val)); - } - index2 = endIdx + 1; - } - return cookies; -} -var getCookieKey, _serialize, serializeCookie, serializeSignedCookie; -var init_cookies = __esm({ - "node_modules/.pnpm/better-call@1.1.8_zod@4.3.6/node_modules/better-call/dist/cookies.mjs"() { - init_utils9(); - init_crypto2(); - getCookieKey = (key, prefix) => { - let finalKey = key; - if (prefix) if (prefix === "secure") finalKey = "__Secure-" + key; - else if (prefix === "host") finalKey = "__Host-" + key; - else return; - return finalKey; - }; - _serialize = (key, value, opt = {}) => { - let cookie; - if (opt?.prefix === "secure") cookie = `${`__Secure-${key}`}=${value}`; - else if (opt?.prefix === "host") cookie = `${`__Host-${key}`}=${value}`; - else cookie = `${key}=${value}`; - if (key.startsWith("__Secure-") && !opt.secure) opt.secure = true; - if (key.startsWith("__Host-")) { - if (!opt.secure) opt.secure = true; - if (opt.path !== "/") opt.path = "/"; - if (opt.domain) opt.domain = void 0; - } - if (opt && typeof opt.maxAge === "number" && opt.maxAge >= 0) { - if (opt.maxAge > 3456e4) throw new Error("Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration."); - cookie += `; Max-Age=${Math.floor(opt.maxAge)}`; - } - if (opt.domain && opt.prefix !== "host") cookie += `; Domain=${opt.domain}`; - if (opt.path) cookie += `; Path=${opt.path}`; - if (opt.expires) { - if (opt.expires.getTime() - Date.now() > 3456e7) throw new Error("Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future."); - cookie += `; Expires=${opt.expires.toUTCString()}`; - } - if (opt.httpOnly) cookie += "; HttpOnly"; - if (opt.secure) cookie += "; Secure"; - if (opt.sameSite) cookie += `; SameSite=${opt.sameSite.charAt(0).toUpperCase() + opt.sameSite.slice(1)}`; - if (opt.partitioned) { - if (!opt.secure) opt.secure = true; - cookie += "; Partitioned"; - } - return cookie; - }; - serializeCookie = (key, value, opt) => { - value = encodeURIComponent(value); - return _serialize(key, value, opt); - }; - serializeSignedCookie = async (key, value, secret, opt) => { - value = await signCookieValue(value, secret); - return _serialize(key, value, opt); - }; - } -}); - -// node_modules/.pnpm/better-call@1.1.8_zod@4.3.6/node_modules/better-call/dist/validator.mjs -async function runValidation(options, context = {}) { - let request = { - body: context.body, - query: context.query - }; - if (options.body) { - const result = await options.body["~standard"].validate(context.body); - if (result.issues) return { - data: null, - error: fromError(result.issues, "body") - }; - request.body = result.value; - } - if (options.query) { - const result = await options.query["~standard"].validate(context.query); - if (result.issues) return { - data: null, - error: fromError(result.issues, "query") - }; - request.query = result.value; - } - if (options.requireHeaders && !context.headers) return { - data: null, - error: { - message: "Headers is required", - issues: [] - } - }; - if (options.requireRequest && !context.request) return { - data: null, - error: { - message: "Request is required", - issues: [] - } - }; - return { - data: request, - error: null - }; -} -function fromError(error50, validating) { - return { - message: error50.map((e5) => { - return `[${e5.path?.length ? `${validating}.` + e5.path.map((x5) => typeof x5 === "object" ? x5.key : x5).join(".") : validating}] ${e5.message}`; - }).join("; "), - issues: error50 - }; -} -var init_validator = __esm({ - "node_modules/.pnpm/better-call@1.1.8_zod@4.3.6/node_modules/better-call/dist/validator.mjs"() { - } -}); - -// node_modules/.pnpm/better-call@1.1.8_zod@4.3.6/node_modules/better-call/dist/context.mjs -var createInternalContext; -var init_context = __esm({ - "node_modules/.pnpm/better-call@1.1.8_zod@4.3.6/node_modules/better-call/dist/context.mjs"() { - init_error2(); - init_utils9(); - init_validator(); - init_crypto2(); - init_cookies(); - createInternalContext = async (context, { options, path: path53 }) => { - const headers = new Headers(); - let responseStatus = void 0; - const { data: data2, error: error50 } = await runValidation(options, context); - if (error50) throw new ValidationError(error50.message, error50.issues); - const requestHeaders = "headers" in context ? context.headers instanceof Headers ? context.headers : new Headers(context.headers) : "request" in context && isRequest(context.request) ? context.request.headers : null; - const requestCookies = requestHeaders?.get("cookie"); - const parsedCookies = requestCookies ? parseCookies(requestCookies) : void 0; - const internalContext = { - ...context, - body: data2.body, - query: data2.query, - path: context.path || path53 || "virtual:", - context: "context" in context && context.context ? context.context : {}, - returned: void 0, - headers: context?.headers, - request: context?.request, - params: "params" in context ? context.params : void 0, - method: context.method ?? (Array.isArray(options.method) ? options.method[0] : options.method === "*" ? "GET" : options.method), - setHeader: (key, value) => { - headers.set(key, value); - }, - getHeader: (key) => { - if (!requestHeaders) return null; - return requestHeaders.get(key); - }, - getCookie: (key, prefix) => { - const finalKey = getCookieKey(key, prefix); - if (!finalKey) return null; - return parsedCookies?.get(finalKey) || null; - }, - getSignedCookie: async (key, secret, prefix) => { - const finalKey = getCookieKey(key, prefix); - if (!finalKey) return null; - const value = parsedCookies?.get(finalKey); - if (!value) return null; - const signatureStartPos = value.lastIndexOf("."); - if (signatureStartPos < 1) return null; - const signedValue = value.substring(0, signatureStartPos); - const signature = value.substring(signatureStartPos + 1); - if (signature.length !== 44 || !signature.endsWith("=")) return null; - return await verifySignature(signature, signedValue, await getCryptoKey3(secret)) ? signedValue : false; - }, - setCookie: (key, value, options$1) => { - const cookie = serializeCookie(key, value, options$1); - headers.append("set-cookie", cookie); - return cookie; - }, - setSignedCookie: async (key, value, secret, options$1) => { - const cookie = await serializeSignedCookie(key, value, secret, options$1); - headers.append("set-cookie", cookie); - return cookie; - }, - redirect: (url2) => { - headers.set("location", url2); - return new APIError("FOUND", void 0, headers); - }, - error: (status, body, headers$1) => { - return new APIError(status, body, headers$1); - }, - setStatus: (status) => { - responseStatus = status; - }, - json: (json3, routerResponse) => { - if (!context.asResponse) return json3; - return { - body: routerResponse?.body || json3, - routerResponse, - _flag: "json" - }; - }, - responseHeaders: headers, - get responseStatus() { - return responseStatus; - } - }; - for (const middleware of options.use || []) { - const response = await middleware({ - ...internalContext, - returnHeaders: true, - asResponse: false - }); - if (response.response) Object.assign(internalContext.context, response.response); - if (response.headers) response.headers.forEach((value, key) => { - internalContext.responseHeaders.set(key, value); - }); - } - return internalContext; - }; - } -}); - -// node_modules/.pnpm/better-call@1.1.8_zod@4.3.6/node_modules/better-call/dist/endpoint.mjs -function createEndpoint(pathOrOptions, handlerOrOptions, handlerOrNever) { - const path53 = typeof pathOrOptions === "string" ? pathOrOptions : void 0; - const options = typeof handlerOrOptions === "object" ? handlerOrOptions : pathOrOptions; - const handler = typeof handlerOrOptions === "function" ? handlerOrOptions : handlerOrNever; - if ((options.method === "GET" || options.method === "HEAD") && options.body) throw new BetterCallError("Body is not allowed with GET or HEAD methods"); - if (path53 && /\/{2,}/.test(path53)) throw new BetterCallError("Path cannot contain consecutive slashes"); - const internalHandler = async (...inputCtx) => { - const context = inputCtx[0] || {}; - const { data: internalContext, error: validationError } = await tryCatch(createInternalContext(context, { - options, - path: path53 - })); - if (validationError) { - if (!(validationError instanceof ValidationError)) throw validationError; - if (options.onValidationError) await options.onValidationError({ - message: validationError.message, - issues: validationError.issues - }); - throw new APIError(400, { - message: validationError.message, - code: "VALIDATION_ERROR" - }); - } - const response = await handler(internalContext).catch(async (e5) => { - if (isAPIError(e5)) { - const onAPIError = options.onAPIError; - if (onAPIError) await onAPIError(e5); - if (context.asResponse) return e5; - } - throw e5; - }); - const headers = internalContext.responseHeaders; - const status = internalContext.responseStatus; - return context.asResponse ? toResponse(response, { - headers, - status - }) : context.returnHeaders ? context.returnStatus ? { - headers, - response, - status - } : { - headers, - response - } : context.returnStatus ? { - response, - status - } : response; - }; - internalHandler.options = options; - internalHandler.path = path53; - return internalHandler; -} -var init_endpoint = __esm({ - "node_modules/.pnpm/better-call@1.1.8_zod@4.3.6/node_modules/better-call/dist/endpoint.mjs"() { - init_error2(); - init_utils9(); - init_to_response(); - init_context(); - createEndpoint.create = (opts) => { - return (path53, options, handler) => { - return createEndpoint(path53, { - ...options, - use: [...options?.use || [], ...opts?.use || []] - }, handler); - }; - }; - } -}); - -// node_modules/.pnpm/better-call@1.1.8_zod@4.3.6/node_modules/better-call/dist/middleware.mjs -function createMiddleware(optionsOrHandler, handler) { - const internalHandler = async (inputCtx) => { - const context = inputCtx; - const _handler = typeof optionsOrHandler === "function" ? optionsOrHandler : handler; - const internalContext = await createInternalContext(context, { - options: typeof optionsOrHandler === "function" ? {} : optionsOrHandler, - path: "/" - }); - if (!_handler) throw new Error("handler must be defined"); - const response = await _handler(internalContext); - const headers = internalContext.responseHeaders; - return context.returnHeaders ? { - headers, - response - } : response; - }; - internalHandler.options = typeof optionsOrHandler === "function" ? {} : optionsOrHandler; - return internalHandler; -} -var init_middleware = __esm({ - "node_modules/.pnpm/better-call@1.1.8_zod@4.3.6/node_modules/better-call/dist/middleware.mjs"() { - init_context(); - init_endpoint(); - createMiddleware.create = (opts) => { - function fn(optionsOrHandler, handler) { - if (typeof optionsOrHandler === "function") return createMiddleware({ use: opts?.use }, optionsOrHandler); - if (!handler) throw new Error("Middleware handler is required"); - return createMiddleware({ - ...optionsOrHandler, - method: "*", - use: [...opts?.use || [], ...optionsOrHandler.use || []] - }, handler); - } - return fn; - }; - } -}); - -// node_modules/.pnpm/better-call@1.1.8_zod@4.3.6/node_modules/better-call/dist/openapi.mjs -function getTypeFromZodType(zodType) { - switch (zodType.constructor.name) { - case "ZodString": - return "string"; - case "ZodNumber": - return "number"; - case "ZodBoolean": - return "boolean"; - case "ZodObject": - return "object"; - case "ZodArray": - return "array"; - default: - return "string"; - } -} -function getParameters(options) { - const parameters = []; - if (options.metadata?.openapi?.parameters) { - parameters.push(...options.metadata.openapi.parameters); - return parameters; - } - if (options.query instanceof ZodObject2) Object.entries(options.query.shape).forEach(([key, value]) => { - if (value instanceof ZodObject2) parameters.push({ - name: key, - in: "query", - schema: { - type: getTypeFromZodType(value), - ..."minLength" in value && value.minLength ? { minLength: value.minLength } : {}, - description: value.description - } - }); - }); - return parameters; -} -function getRequestBody(options) { - if (options.metadata?.openapi?.requestBody) return options.metadata.openapi.requestBody; - if (!options.body) return void 0; - if (options.body instanceof ZodObject2 || options.body instanceof ZodOptional2) { - const shape = options.body.shape; - if (!shape) return void 0; - const properties = {}; - const required2 = []; - Object.entries(shape).forEach(([key, value]) => { - if (value instanceof ZodObject2) { - properties[key] = { - type: getTypeFromZodType(value), - description: value.description - }; - if (!(value instanceof ZodOptional2)) required2.push(key); - } - }); - return { - required: options.body instanceof ZodOptional2 ? false : options.body ? true : false, - content: { "application/json": { schema: { - type: "object", - properties, - required: required2 - } } } - }; - } -} -function getResponse(responses) { - return { - "400": { - content: { "application/json": { schema: { - type: "object", - properties: { message: { type: "string" } }, - required: ["message"] - } } }, - description: "Bad Request. Usually due to missing parameters, or invalid parameters." - }, - "401": { - content: { "application/json": { schema: { - type: "object", - properties: { message: { type: "string" } }, - required: ["message"] - } } }, - description: "Unauthorized. Due to missing or invalid authentication." - }, - "403": { - content: { "application/json": { schema: { - type: "object", - properties: { message: { type: "string" } } - } } }, - description: "Forbidden. You do not have permission to access this resource or to perform this action." - }, - "404": { - content: { "application/json": { schema: { - type: "object", - properties: { message: { type: "string" } } - } } }, - description: "Not Found. The requested resource was not found." - }, - "429": { - content: { "application/json": { schema: { - type: "object", - properties: { message: { type: "string" } } - } } }, - description: "Too Many Requests. You have exceeded the rate limit. Try again later." - }, - "500": { - content: { "application/json": { schema: { - type: "object", - properties: { message: { type: "string" } } - } } }, - description: "Internal Server Error. This is a problem with the server that you cannot fix." - }, - ...responses - }; -} -async function generator(endpoints, config3) { - const components = { schemas: {} }; - Object.entries(endpoints).forEach(([_, value]) => { - const options = value.options; - if (!value.path || options.metadata?.SERVER_ONLY) return; - if (options.method === "GET") paths[value.path] = { get: { - tags: ["Default", ...options.metadata?.openapi?.tags || []], - description: options.metadata?.openapi?.description, - operationId: options.metadata?.openapi?.operationId, - security: [{ bearerAuth: [] }], - parameters: getParameters(options), - responses: getResponse(options.metadata?.openapi?.responses) - } }; - if (options.method === "POST") { - const body = getRequestBody(options); - paths[value.path] = { post: { - tags: ["Default", ...options.metadata?.openapi?.tags || []], - description: options.metadata?.openapi?.description, - operationId: options.metadata?.openapi?.operationId, - security: [{ bearerAuth: [] }], - parameters: getParameters(options), - ...body ? { requestBody: body } : { requestBody: { content: { "application/json": { schema: { - type: "object", - properties: {} - } } } } }, - responses: getResponse(options.metadata?.openapi?.responses) - } }; - } - }); - return { - openapi: "3.1.1", - info: { - title: "Better Auth", - description: "API Reference for your Better Auth Instance", - version: "1.1.0" - }, - components, - security: [{ apiKeyCookie: [] }], - servers: [{ url: config3?.url }], - tags: [{ - name: "Default", - description: "Default endpoints that are included with Better Auth by default. These endpoints are not part of any plugin." - }], - paths - }; -} -var paths, getHTML; -var init_openapi = __esm({ - "node_modules/.pnpm/better-call@1.1.8_zod@4.3.6/node_modules/better-call/dist/openapi.mjs"() { - init_zod(); - paths = {}; - getHTML = (apiReference, config3) => ` - - - Scalar API Reference - - - - - - - - -`; - } -}); - -// node_modules/.pnpm/rou3@0.7.12/node_modules/rou3/dist/index.mjs -function createRouter() { - return { - root: { key: "" }, - static: new NullProtoObj() - }; -} -function splitPath(path53) { - const [_, ...s5] = path53.split("/"); - return s5[s5.length - 1] === "" ? s5.slice(0, -1) : s5; -} -function getMatchParams(segments, paramsMap) { - const params = new NullProtoObj(); - for (const [index2, name] of paramsMap) { - const segment = index2 < 0 ? segments.slice(-(index2 + 1)).join("/") : segments[index2]; - if (typeof name === "string") params[name] = segment; - else { - const match = segment.match(name); - if (match) for (const key in match.groups) params[key] = match.groups[key]; - } - } - return params; -} -function addRoute(ctx, method = "", path53, data2) { - method = method.toUpperCase(); - if (path53.charCodeAt(0) !== 47) path53 = `/${path53}`; - path53 = path53.replace(/\\:/g, "%3A"); - const segments = splitPath(path53); - let node = ctx.root; - let _unnamedParamIndex = 0; - const paramsMap = []; - const paramsRegexp = []; - for (let i5 = 0; i5 < segments.length; i5++) { - let segment = segments[i5]; - if (segment.startsWith("**")) { - if (!node.wildcard) node.wildcard = { key: "**" }; - node = node.wildcard; - paramsMap.push([ - -(i5 + 1), - segment.split(":")[1] || "_", - segment.length === 2 - ]); - break; - } - if (segment === "*" || segment.includes(":")) { - if (!node.param) node.param = { key: "*" }; - node = node.param; - if (segment === "*") paramsMap.push([ - i5, - `_${_unnamedParamIndex++}`, - true - ]); - else if (segment.includes(":", 1)) { - const regexp = getParamRegexp(segment); - paramsRegexp[i5] = regexp; - node.hasRegexParam = true; - paramsMap.push([ - i5, - regexp, - false - ]); - } else paramsMap.push([ - i5, - segment.slice(1), - false - ]); - continue; - } - if (segment === "\\*") segment = segments[i5] = "*"; - else if (segment === "\\*\\*") segment = segments[i5] = "**"; - const child = node.static?.[segment]; - if (child) node = child; - else { - const staticNode = { key: segment }; - if (!node.static) node.static = new NullProtoObj(); - node.static[segment] = staticNode; - node = staticNode; - } - } - const hasParams = paramsMap.length > 0; - if (!node.methods) node.methods = new NullProtoObj(); - node.methods[method] ??= []; - node.methods[method].push({ - data: data2 || null, - paramsRegexp, - paramsMap: hasParams ? paramsMap : void 0 - }); - if (!hasParams) ctx.static["/" + segments.join("/")] = node; -} -function getParamRegexp(segment) { - const regex = segment.replace(/:(\w+)/g, (_, id) => `(?<${id}>[^/]+)`).replace(/\./g, "\\."); - return /* @__PURE__ */ new RegExp(`^${regex}$`); -} -function findRoute(ctx, method = "", path53, opts) { - if (path53.charCodeAt(path53.length - 1) === 47) path53 = path53.slice(0, -1); - const staticNode = ctx.static[path53]; - if (staticNode && staticNode.methods) { - const staticMatch = staticNode.methods[method] || staticNode.methods[""]; - if (staticMatch !== void 0) return staticMatch[0]; - } - const segments = splitPath(path53); - const match = _lookupTree(ctx, ctx.root, method, segments, 0)?.[0]; - if (match === void 0) return; - if (opts?.params === false) return match; - return { - data: match.data, - params: match.paramsMap ? getMatchParams(segments, match.paramsMap) : void 0 - }; -} -function _lookupTree(ctx, node, method, segments, index2) { - if (index2 === segments.length) { - if (node.methods) { - const match = node.methods[method] || node.methods[""]; - if (match) return match; - } - if (node.param && node.param.methods) { - const match = node.param.methods[method] || node.param.methods[""]; - if (match) { - const pMap = match[0].paramsMap; - if (pMap?.[pMap?.length - 1]?.[2]) return match; - } - } - if (node.wildcard && node.wildcard.methods) { - const match = node.wildcard.methods[method] || node.wildcard.methods[""]; - if (match) { - const pMap = match[0].paramsMap; - if (pMap?.[pMap?.length - 1]?.[2]) return match; - } - } - return; - } - const segment = segments[index2]; - if (node.static) { - const staticChild = node.static[segment]; - if (staticChild) { - const match = _lookupTree(ctx, staticChild, method, segments, index2 + 1); - if (match) return match; - } - } - if (node.param) { - const match = _lookupTree(ctx, node.param, method, segments, index2 + 1); - if (match) { - if (node.param.hasRegexParam) { - const exactMatch = match.find((m5) => m5.paramsRegexp[index2]?.test(segment)) || match.find((m5) => !m5.paramsRegexp[index2]); - return exactMatch ? [exactMatch] : void 0; - } - return match; - } - } - if (node.wildcard && node.wildcard.methods) return node.wildcard.methods[method] || node.wildcard.methods[""]; -} -function findAllRoutes(ctx, method = "", path53, opts) { - if (path53.charCodeAt(path53.length - 1) === 47) path53 = path53.slice(0, -1); - const segments = splitPath(path53); - const matches = _findAll(ctx, ctx.root, method, segments, 0); - if (opts?.params === false) return matches; - return matches.map((m5) => { - return { - data: m5.data, - params: m5.paramsMap ? getMatchParams(segments, m5.paramsMap) : void 0 - }; - }); -} -function _findAll(ctx, node, method, segments, index2, matches = []) { - const segment = segments[index2]; - if (node.wildcard && node.wildcard.methods) { - const match = node.wildcard.methods[method] || node.wildcard.methods[""]; - if (match) matches.push(...match); - } - if (node.param) { - _findAll(ctx, node.param, method, segments, index2 + 1, matches); - if (index2 === segments.length && node.param.methods) { - const match = node.param.methods[method] || node.param.methods[""]; - if (match) { - const pMap = match[0].paramsMap; - if (pMap?.[pMap?.length - 1]?.[2]) matches.push(...match); - } - } - } - const staticChild = node.static?.[segment]; - if (staticChild) _findAll(ctx, staticChild, method, segments, index2 + 1, matches); - if (index2 === segments.length && node.methods) { - const match = node.methods[method] || node.methods[""]; - if (match) matches.push(...match); - } - return matches; -} -var NullProtoObj; -var init_dist2 = __esm({ - "node_modules/.pnpm/rou3@0.7.12/node_modules/rou3/dist/index.mjs"() { - NullProtoObj = /* @__PURE__ */ (() => { - const e5 = function() { - }; - return e5.prototype = /* @__PURE__ */ Object.create(null), Object.freeze(e5.prototype), e5; - })(); - } -}); - -// node_modules/.pnpm/better-call@1.1.8_zod@4.3.6/node_modules/better-call/dist/router.mjs -var createRouter$1; -var init_router = __esm({ - "node_modules/.pnpm/better-call@1.1.8_zod@4.3.6/node_modules/better-call/dist/router.mjs"() { - init_utils9(); - init_to_response(); - init_endpoint(); - init_openapi(); - init_dist2(); - createRouter$1 = (endpoints, config3) => { - if (!config3?.openapi?.disabled) { - const openapi = { - path: "/api/reference", - ...config3?.openapi - }; - endpoints["openapi"] = createEndpoint(openapi.path, { method: "GET" }, async (c5) => { - const schema2 = await generator(endpoints); - return new Response(getHTML(schema2, openapi.scalar), { headers: { "Content-Type": "text/html" } }); - }); - } - const router2 = createRouter(); - const middlewareRouter = createRouter(); - for (const endpoint of Object.values(endpoints)) { - if (!endpoint.options || !endpoint.path) continue; - if (endpoint.options?.metadata?.SERVER_ONLY) continue; - const methods2 = Array.isArray(endpoint.options?.method) ? endpoint.options.method : [endpoint.options?.method]; - for (const method of methods2) addRoute(router2, method, endpoint.path, endpoint); - } - if (config3?.routerMiddleware?.length) for (const { path: path53, middleware } of config3.routerMiddleware) addRoute(middlewareRouter, "*", path53, middleware); - const processRequest = async (request) => { - const url2 = new URL(request.url); - const pathname = url2.pathname; - const path53 = config3?.basePath && config3.basePath !== "/" ? pathname.split(config3.basePath).reduce((acc, curr, index2) => { - if (index2 !== 0) if (index2 > 1) acc.push(`${config3.basePath}${curr}`); - else acc.push(curr); - return acc; - }, []).join("") : url2.pathname; - if (!path53?.length) return new Response(null, { - status: 404, - statusText: "Not Found" - }); - if (/\/{2,}/.test(path53)) return new Response(null, { - status: 404, - statusText: "Not Found" - }); - const route = findRoute(router2, request.method, path53); - if (path53.endsWith("/") !== route?.data?.path?.endsWith("/") && !config3?.skipTrailingSlashes) return new Response(null, { - status: 404, - statusText: "Not Found" - }); - if (!route?.data) return new Response(null, { - status: 404, - statusText: "Not Found" - }); - const query = {}; - url2.searchParams.forEach((value, key) => { - if (key in query) if (Array.isArray(query[key])) query[key].push(value); - else query[key] = [query[key], value]; - else query[key] = value; - }); - const handler = route.data; - try { - const allowedMediaTypes = handler.options.metadata?.allowedMediaTypes || config3?.allowedMediaTypes; - const context = { - path: path53, - method: request.method, - headers: request.headers, - params: route.params ? JSON.parse(JSON.stringify(route.params)) : {}, - request, - body: handler.options.disableBody ? void 0 : await getBody(handler.options.cloneRequest ? request.clone() : request, allowedMediaTypes), - query, - _flag: "router", - asResponse: true, - context: config3?.routerContext - }; - const middlewareRoutes = findAllRoutes(middlewareRouter, "*", path53); - if (middlewareRoutes?.length) for (const { data: middleware, params } of middlewareRoutes) { - const res = await middleware({ - ...context, - params, - asResponse: false - }); - if (res instanceof Response) return res; - } - return await handler(context); - } catch (error50) { - if (config3?.onError) try { - const errorResponse = await config3.onError(error50); - if (errorResponse instanceof Response) return toResponse(errorResponse); - } catch (error$1) { - if (isAPIError(error$1)) return toResponse(error$1); - throw error$1; - } - if (config3?.throwError) throw error50; - if (isAPIError(error50)) return toResponse(error50); - console.error(`# SERVER_ERROR: `, error50); - return new Response(null, { - status: 500, - statusText: "Internal Server Error" - }); - } - }; - return { - handler: async (request) => { - const onReq = await config3?.onRequest?.(request); - if (onReq instanceof Response) return onReq; - const res = await processRequest(isRequest(onReq) ? onReq : request); - const onRes = await config3?.onResponse?.(res); - if (onRes instanceof Response) return onRes; - return res; - }, - endpoints - }; - }; - } -}); - -// node_modules/.pnpm/better-call@1.1.8_zod@4.3.6/node_modules/better-call/dist/index.mjs -var init_dist3 = __esm({ - "node_modules/.pnpm/better-call@1.1.8_zod@4.3.6/node_modules/better-call/dist/index.mjs"() { - init_error2(); - init_to_response(); - init_cookies(); - init_context(); - init_endpoint(); - init_middleware(); - init_openapi(); - init_router(); - } -}); - -// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/db/schema.mjs -function parseOutputData(data2, schema2) { - const fields = schema2.fields; - const parsedData = {}; - for (const key in data2) { - const field = fields[key]; - if (!field) { - parsedData[key] = data2[key]; - continue; - } - if (field.returned === false && key !== "id") continue; - parsedData[key] = data2[key]; - } - return parsedData; -} -function getFields(options, table, mode) { - const cacheKey = `${table}:${mode}`; - if (!cache6.has(options)) cache6.set(options, /* @__PURE__ */ new Map()); - const tableCache = cache6.get(options); - if (tableCache.has(cacheKey)) return tableCache.get(cacheKey); - const coreSchema2 = mode === "output" ? getAuthTables(options)[table]?.fields ?? {} : {}; - const additionalFields = table === "user" || table === "session" || table === "account" ? options[table]?.additionalFields : void 0; - let schema2 = { - ...coreSchema2, - ...additionalFields ?? {} - }; - for (const plugin of options.plugins || []) if (plugin.schema && plugin.schema[table]) schema2 = { - ...schema2, - ...plugin.schema[table].fields - }; - tableCache.set(cacheKey, schema2); - return schema2; -} -function parseUserOutput(options, user) { - return parseOutputData(user, { fields: getFields(options, "user", "output") }); -} -function parseSessionOutput(options, session) { - return parseOutputData(session, { fields: getFields(options, "session", "output") }); -} -function parseAccountOutput(options, account) { - const { accessToken: _accessToken, refreshToken: _refreshToken, idToken: _idToken, accessTokenExpiresAt: _accessTokenExpiresAt, refreshTokenExpiresAt: _refreshTokenExpiresAt, password: _password, ...rest } = parseOutputData(account, { fields: getFields(options, "account", "output") }); - return rest; -} -function parseInputData(data2, schema2) { - const action = schema2.action || "create"; - const fields = schema2.fields; - const parsedData = Object.assign(/* @__PURE__ */ Object.create(null), null); - for (const key in fields) { - if (key in data2) { - if (fields[key].input === false) { - if (fields[key].defaultValue !== void 0) { - if (action !== "update") { - parsedData[key] = fields[key].defaultValue; - continue; - } - } - if (data2[key]) throw new APIError("BAD_REQUEST", { message: `${key} is not allowed to be set` }); - continue; - } - if (fields[key].validator?.input && data2[key] !== void 0) { - const result = fields[key].validator.input["~standard"].validate(data2[key]); - if (result instanceof Promise) throw new APIError("INTERNAL_SERVER_ERROR", { message: "Async validation is not supported for additional fields" }); - if ("issues" in result && result.issues) throw new APIError("BAD_REQUEST", { message: result.issues[0]?.message || "Validation Error" }); - parsedData[key] = result.value; - continue; - } - if (fields[key].transform?.input && data2[key] !== void 0) { - parsedData[key] = fields[key].transform?.input(data2[key]); - continue; - } - parsedData[key] = data2[key]; - continue; - } - if (fields[key].defaultValue !== void 0 && action === "create") { - if (typeof fields[key].defaultValue === "function") { - parsedData[key] = fields[key].defaultValue(); - continue; - } - parsedData[key] = fields[key].defaultValue; - continue; - } - if (fields[key].required && action === "create") throw new APIError("BAD_REQUEST", { message: `${key} is required` }); - } - return parsedData; -} -function parseUserInput(options, user = {}, action) { - return parseInputData(user, { - fields: getFields(options, "user", "input"), - action - }); -} -function parseAdditionalUserInput(options, user) { - const schema2 = getFields(options, "user", "input"); - return parseInputData(user || {}, { fields: schema2 }); -} -function parseAccountInput(options, account) { - return parseInputData(account, { fields: getFields(options, "account", "input") }); -} -function parseSessionInput(options, session) { - return parseInputData(session, { fields: getFields(options, "session", "input") }); -} -function mergeSchema(schema2, newSchema) { - if (!newSchema) return schema2; - for (const table in newSchema) { - const newModelName = newSchema[table]?.modelName; - if (newModelName) schema2[table].modelName = newModelName; - for (const field in schema2[table].fields) { - const newField = newSchema[table]?.fields?.[field]; - if (!newField) continue; - schema2[table].fields[field].fieldName = newField; - } - } - return schema2; -} -var cache6; -var init_schema4 = __esm({ - "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/db/schema.mjs"() { - init_db3(); - init_dist3(); - cache6 = /* @__PURE__ */ new WeakMap(); - } -}); - -// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/cookies/session-store.mjs -function parseCookiesFromContext(ctx) { - const cookieHeader = ctx.headers?.get("cookie"); - if (!cookieHeader) return {}; - const cookies = {}; - const pairs = cookieHeader.split("; "); - for (const pair of pairs) { - const [name, ...valueParts] = pair.split("="); - if (name && valueParts.length > 0) cookies[name] = valueParts.join("="); - } - return cookies; -} -function getChunkIndex(cookieName) { - const parts = cookieName.split("."); - const lastPart = parts[parts.length - 1]; - const index2 = parseInt(lastPart || "0", 10); - return isNaN(index2) ? 0 : index2; -} -function readExistingChunks(cookieName, ctx) { - const chunks = {}; - const cookies = parseCookiesFromContext(ctx); - for (const [name, value] of Object.entries(cookies)) if (name.startsWith(cookieName)) chunks[name] = value; - return chunks; -} -function joinChunks(chunks) { - return Object.keys(chunks).sort((a5, b6) => { - return getChunkIndex(a5) - getChunkIndex(b6); - }).map((key) => chunks[key]).join(""); -} -function chunkCookie(storeName, cookie, chunks, logger4) { - const chunkCount = Math.ceil(cookie.value.length / CHUNK_SIZE); - if (chunkCount === 1) { - chunks[cookie.name] = cookie.value; - return [cookie]; - } - const cookies = []; - for (let i5 = 0; i5 < chunkCount; i5++) { - const name = `${cookie.name}.${i5}`; - const start = i5 * CHUNK_SIZE; - const value = cookie.value.substring(start, start + CHUNK_SIZE); - cookies.push({ - ...cookie, - name, - value - }); - chunks[name] = value; - } - logger4.debug(`CHUNKING_${storeName.toUpperCase()}_COOKIE`, { - message: `${storeName} cookie exceeds allowed ${ALLOWED_COOKIE_SIZE} bytes.`, - emptyCookieSize: ESTIMATED_EMPTY_COOKIE_SIZE, - valueSize: cookie.value.length, - chunkCount, - chunks: cookies.map((c5) => c5.value.length + ESTIMATED_EMPTY_COOKIE_SIZE) - }); - return cookies; -} -function getCleanCookies(chunks, cookieOptions) { - const cleanedChunks = {}; - for (const name in chunks) cleanedChunks[name] = { - name, - value: "", - attributes: { - ...cookieOptions, - maxAge: 0 - } - }; - return cleanedChunks; -} -function getChunkedCookie(ctx, cookieName) { - const value = ctx.getCookie(cookieName); - if (value) return value; - const chunks = []; - const cookieHeader = ctx.headers?.get("cookie"); - if (!cookieHeader) return null; - const cookies = {}; - const pairs = cookieHeader.split("; "); - for (const pair of pairs) { - const [name, ...valueParts] = pair.split("="); - if (name && valueParts.length > 0) cookies[name] = valueParts.join("="); - } - for (const [name, val] of Object.entries(cookies)) if (name.startsWith(cookieName + ".")) { - const indexStr = name.split(".").at(-1); - const index2 = parseInt(indexStr || "0", 10); - if (!isNaN(index2)) chunks.push({ - index: index2, - value: val - }); - } - if (chunks.length > 0) { - chunks.sort((a5, b6) => a5.index - b6.index); - return chunks.map((c5) => c5.value).join(""); - } - return null; -} -async function setAccountCookie(c5, accountData) { - const accountDataCookie = c5.context.authCookies.accountData; - const options = { - maxAge: 300, - ...accountDataCookie.attributes - }; - const data2 = await symmetricEncodeJWT(accountData, c5.context.secret, "better-auth-account", options.maxAge); - if (data2.length > ALLOWED_COOKIE_SIZE) { - const accountStore = createAccountStore(accountDataCookie.name, options, c5); - const cookies = accountStore.chunk(data2, options); - accountStore.setCookies(cookies); - } else { - const accountStore = createAccountStore(accountDataCookie.name, options, c5); - if (accountStore.hasChunks()) { - const cleanCookies = accountStore.clean(); - accountStore.setCookies(cleanCookies); - } - c5.setCookie(accountDataCookie.name, data2, options); - } -} -async function getAccountCookie(c5) { - const accountCookie = getChunkedCookie(c5, c5.context.authCookies.accountData.name); - if (accountCookie) { - const accountData = safeJSONParse(await symmetricDecodeJWT(accountCookie, c5.context.secret, "better-auth-account")); - if (accountData) return accountData; - } - return null; -} -var ALLOWED_COOKIE_SIZE, ESTIMATED_EMPTY_COOKIE_SIZE, CHUNK_SIZE, storeFactory, createSessionStore, createAccountStore, getSessionQuerySchema; -var init_session_store = __esm({ - "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/cookies/session-store.mjs"() { - init_jwt(); - init_crypto(); - init_utils7(); - init_zod(); - ALLOWED_COOKIE_SIZE = 4096; - ESTIMATED_EMPTY_COOKIE_SIZE = 200; - CHUNK_SIZE = ALLOWED_COOKIE_SIZE - ESTIMATED_EMPTY_COOKIE_SIZE; - storeFactory = (storeName) => (cookieName, cookieOptions, ctx) => { - const chunks = readExistingChunks(cookieName, ctx); - const logger4 = ctx.context.logger; - return { - getValue() { - return joinChunks(chunks); - }, - hasChunks() { - return Object.keys(chunks).length > 0; - }, - chunk(value, options) { - const cleanedChunks = getCleanCookies(chunks, cookieOptions); - for (const name in chunks) delete chunks[name]; - const cookies = cleanedChunks; - const chunked = chunkCookie(storeName, { - name: cookieName, - value, - attributes: { - ...cookieOptions, - ...options - } - }, chunks, logger4); - for (const chunk of chunked) cookies[chunk.name] = chunk; - return Object.values(cookies); - }, - clean() { - const cleanedChunks = getCleanCookies(chunks, cookieOptions); - for (const name in chunks) delete chunks[name]; - return Object.values(cleanedChunks); - }, - setCookies(cookies) { - for (const cookie of cookies) ctx.setCookie(cookie.name, cookie.value, cookie.attributes); - } - }; - }; - createSessionStore = storeFactory("Session"); - createAccountStore = storeFactory("Account"); - getSessionQuerySchema = optional(object({ - disableCookieCache: coerce_exports.boolean().meta({ description: "Disable cookie cache and fetch session from database" }).optional(), - disableRefresh: coerce_exports.boolean().meta({ description: "Disable session refresh. Useful for checking session status, without updating the session" }).optional() - })); - } -}); - -// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/utils/is-promise.mjs -function isPromise(obj) { - return !!obj && (typeof obj === "object" || typeof obj === "function") && typeof obj.then === "function"; -} -var init_is_promise = __esm({ - "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/utils/is-promise.mjs"() { - } -}); - -// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/utils/time.mjs -function parse4(value) { - const match = REGEX2.exec(value); - if (!match || match[4] && match[1]) throw new TypeError(`Invalid time string format: "${value}". Use formats like "7d", "30m", "1 hour", etc.`); - const n5 = parseFloat(match[2]); - const unit = match[3].toLowerCase(); - let result; - switch (unit) { - case "years": - case "year": - case "yrs": - case "yr": - case "y": - result = n5 * YEAR; - break; - case "months": - case "month": - case "mo": - result = n5 * MONTH; - break; - case "weeks": - case "week": - case "w": - result = n5 * WEEK; - break; - case "days": - case "day": - case "d": - result = n5 * DAY; - break; - case "hours": - case "hour": - case "hrs": - case "hr": - case "h": - result = n5 * HOUR; - break; - case "minutes": - case "minute": - case "mins": - case "min": - case "m": - result = n5 * MIN; - break; - case "seconds": - case "second": - case "secs": - case "sec": - case "s": - result = n5 * SEC; - break; - default: - throw new TypeError(`Unknown time unit: "${unit}"`); - } - if (match[1] === "-" || match[4] === "ago") return -result; - return result; -} -function sec(value) { - return Math.round(parse4(value) / 1e3); -} -var SEC, MIN, HOUR, DAY, WEEK, MONTH, YEAR, REGEX2; -var init_time2 = __esm({ - "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/utils/time.mjs"() { - SEC = 1e3; - MIN = SEC * 60; - HOUR = MIN * 60; - DAY = HOUR * 24; - WEEK = DAY * 7; - MONTH = DAY * 30; - YEAR = DAY * 365.25; - REGEX2 = /^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|months?|mo|years?|yrs?|y)(?: (ago|from now))?$/i; - } -}); - -// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/cookies/cookie-utils.mjs -var SECURE_COOKIE_PREFIX; -var init_cookie_utils = __esm({ - "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/cookies/cookie-utils.mjs"() { - SECURE_COOKIE_PREFIX = "__Secure-"; - } -}); - -// node_modules/.pnpm/@better-auth+utils@0.3.0/node_modules/@better-auth/utils/dist/binary.mjs -var decoders, encoder2, binary; -var init_binary = __esm({ - "node_modules/.pnpm/@better-auth+utils@0.3.0/node_modules/@better-auth/utils/dist/binary.mjs"() { - decoders = /* @__PURE__ */ new Map(); - encoder2 = new TextEncoder(); - binary = { - decode: (data2, encoding = "utf-8") => { - if (!decoders.has(encoding)) { - decoders.set(encoding, new TextDecoder(encoding)); - } - const decoder2 = decoders.get(encoding); - return decoder2.decode(data2); - }, - encode: encoder2.encode - }; - } -}); - -// node_modules/.pnpm/@better-auth+utils@0.3.0/node_modules/@better-auth/utils/dist/hmac.mjs -var createHMAC; -var init_hmac2 = __esm({ - "node_modules/.pnpm/@better-auth+utils@0.3.0/node_modules/@better-auth/utils/dist/hmac.mjs"() { - init_hex(); - init_base642(); - init_dist(); - createHMAC = (algorithm2 = "SHA-256", encoding = "none") => { - const hmac3 = { - importKey: async (key, keyUsage) => { - return getWebcryptoSubtle().importKey( - "raw", - typeof key === "string" ? new TextEncoder().encode(key) : key, - { name: "HMAC", hash: { name: algorithm2 } }, - false, - [keyUsage] - ); - }, - sign: async (hmacKey, data2) => { - if (typeof hmacKey === "string") { - hmacKey = await hmac3.importKey(hmacKey, "sign"); - } - const signature = await getWebcryptoSubtle().sign( - "HMAC", - hmacKey, - typeof data2 === "string" ? new TextEncoder().encode(data2) : data2 - ); - if (encoding === "hex") { - return hex3.encode(signature); - } - if (encoding === "base64" || encoding === "base64url" || encoding === "base64urlnopad") { - return base64Url.encode(signature, { - padding: encoding !== "base64urlnopad" - }); - } - return signature; - }, - verify: async (hmacKey, data2, signature) => { - if (typeof hmacKey === "string") { - hmacKey = await hmac3.importKey(hmacKey, "verify"); - } - if (encoding === "hex") { - signature = hex3.decode(signature); - } - if (encoding === "base64" || encoding === "base64url" || encoding === "base64urlnopad") { - signature = await base643.decode(signature); - } - return getWebcryptoSubtle().verify( - "HMAC", - hmacKey, - typeof signature === "string" ? new TextEncoder().encode(signature) : signature, - typeof data2 === "string" ? new TextEncoder().encode(data2) : data2 - ); - } - }; - return hmac3; - }; - } -}); - -// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/cookies/index.mjs -function createCookieGetter(options) { - const secureCookiePrefix = (options.advanced?.useSecureCookies !== void 0 ? options.advanced?.useSecureCookies : options.baseURL ? options.baseURL.startsWith("https://") ? true : false : isProduction) ? SECURE_COOKIE_PREFIX : ""; - const crossSubdomainEnabled = !!options.advanced?.crossSubDomainCookies?.enabled; - const domain2 = crossSubdomainEnabled ? options.advanced?.crossSubDomainCookies?.domain || (options.baseURL ? new URL(options.baseURL).hostname : void 0) : void 0; - if (crossSubdomainEnabled && !domain2) throw new BetterAuthError("baseURL is required when crossSubdomainCookies are enabled"); - function createCookie(cookieName, overrideAttributes = {}) { - const prefix = options.advanced?.cookiePrefix || "better-auth"; - const name = options.advanced?.cookies?.[cookieName]?.name || `${prefix}.${cookieName}`; - const attributes = options.advanced?.cookies?.[cookieName]?.attributes; - return { - name: `${secureCookiePrefix}${name}`, - attributes: { - secure: !!secureCookiePrefix, - sameSite: "lax", - path: "/", - httpOnly: true, - ...crossSubdomainEnabled ? { domain: domain2 } : {}, - ...options.advanced?.defaultCookieAttributes, - ...overrideAttributes, - ...attributes - } - }; - } - return createCookie; -} -function getCookies(options) { - const createCookie = createCookieGetter(options); - const sessionToken = createCookie("session_token", { maxAge: options.session?.expiresIn || sec("7d") }); - const sessionData = createCookie("session_data", { maxAge: options.session?.cookieCache?.maxAge || 300 }); - const accountData = createCookie("account_data", { maxAge: options.session?.cookieCache?.maxAge || 300 }); - const dontRememberToken = createCookie("dont_remember"); - return { - sessionToken: { - name: sessionToken.name, - attributes: sessionToken.attributes - }, - sessionData: { - name: sessionData.name, - attributes: sessionData.attributes - }, - dontRememberToken: { - name: dontRememberToken.name, - attributes: dontRememberToken.attributes - }, - accountData: { - name: accountData.name, - attributes: accountData.attributes - } - }; -} -async function setCookieCache(ctx, session, dontRememberMe) { - if (!ctx.context.options.session?.cookieCache?.enabled) return; - const filteredSession = filterOutputFields(session.session, ctx.context.options.session?.additionalFields); - const filteredUser = parseUserOutput(ctx.context.options, session.user); - const versionConfig = ctx.context.options.session?.cookieCache?.version; - let version3 = "1"; - if (versionConfig) { - if (typeof versionConfig === "string") version3 = versionConfig; - else if (typeof versionConfig === "function") { - const result = versionConfig(session.session, session.user); - version3 = isPromise(result) ? await result : result; - } - } - const sessionData = { - session: filteredSession, - user: filteredUser, - updatedAt: Date.now(), - version: version3 - }; - const options = { - ...ctx.context.authCookies.sessionData.attributes, - maxAge: dontRememberMe ? void 0 : ctx.context.authCookies.sessionData.attributes.maxAge - }; - const expiresAtDate = getDate(options.maxAge || 60, "sec").getTime(); - const strategy = ctx.context.options.session?.cookieCache?.strategy || "compact"; - let data2; - if (strategy === "jwe") data2 = await symmetricEncodeJWT(sessionData, ctx.context.secret, "better-auth-session", options.maxAge || 300); - else if (strategy === "jwt") data2 = await signJWT(sessionData, ctx.context.secret, options.maxAge || 300); - else data2 = base64Url.encode(JSON.stringify({ - session: sessionData, - expiresAt: expiresAtDate, - signature: await createHMAC("SHA-256", "base64urlnopad").sign(ctx.context.secret, JSON.stringify({ - ...sessionData, - expiresAt: expiresAtDate - })) - }), { padding: false }); - if (data2.length > 4093) { - const sessionStore = createSessionStore(ctx.context.authCookies.sessionData.name, options, ctx); - const cookies = sessionStore.chunk(data2, options); - sessionStore.setCookies(cookies); - } else { - const sessionStore = createSessionStore(ctx.context.authCookies.sessionData.name, options, ctx); - if (sessionStore.hasChunks()) { - const cleanCookies = sessionStore.clean(); - sessionStore.setCookies(cleanCookies); - } - ctx.setCookie(ctx.context.authCookies.sessionData.name, data2, options); - } - if (ctx.context.options.account?.storeAccountCookie) { - const accountData = await getAccountCookie(ctx); - if (accountData) await setAccountCookie(ctx, accountData); - } -} -async function setSessionCookie(ctx, session, dontRememberMe, overrides) { - const dontRememberMeCookie = await ctx.getSignedCookie(ctx.context.authCookies.dontRememberToken.name, ctx.context.secret); - dontRememberMe = dontRememberMe !== void 0 ? dontRememberMe : !!dontRememberMeCookie; - const options = ctx.context.authCookies.sessionToken.attributes; - const maxAge = dontRememberMe ? void 0 : ctx.context.sessionConfig.expiresIn; - await ctx.setSignedCookie(ctx.context.authCookies.sessionToken.name, session.session.token, ctx.context.secret, { - ...options, - maxAge, - ...overrides - }); - if (dontRememberMe) await ctx.setSignedCookie(ctx.context.authCookies.dontRememberToken.name, "true", ctx.context.secret, ctx.context.authCookies.dontRememberToken.attributes); - await setCookieCache(ctx, session, dontRememberMe); - ctx.context.setNewSession(session); -} -function expireCookie(ctx, cookie) { - ctx.setCookie(cookie.name, "", { - ...cookie.attributes, - maxAge: 0 - }); -} -function deleteSessionCookie(ctx, skipDontRememberMe) { - expireCookie(ctx, ctx.context.authCookies.sessionToken); - expireCookie(ctx, ctx.context.authCookies.sessionData); - if (ctx.context.options.account?.storeAccountCookie) { - expireCookie(ctx, ctx.context.authCookies.accountData); - const accountStore = createAccountStore(ctx.context.authCookies.accountData.name, ctx.context.authCookies.accountData.attributes, ctx); - const cleanCookies$1 = accountStore.clean(); - accountStore.setCookies(cleanCookies$1); - } - if (ctx.context.oauthConfig.storeStateStrategy === "cookie") expireCookie(ctx, ctx.context.createAuthCookie("oauth_state")); - const sessionStore = createSessionStore(ctx.context.authCookies.sessionData.name, ctx.context.authCookies.sessionData.attributes, ctx); - const cleanCookies = sessionStore.clean(); - sessionStore.setCookies(cleanCookies); - if (!skipDontRememberMe) expireCookie(ctx, ctx.context.authCookies.dontRememberToken); -} -var init_cookies2 = __esm({ - "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/cookies/index.mjs"() { - init_date2(); - init_schema4(); - init_jwt(); - init_session_store(); - init_is_promise(); - init_time2(); - init_cookie_utils(); - init_env(); - init_error(); - init_utils7(); - init_base642(); - init_binary(); - init_hmac2(); - } -}); - -// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/state.mjs -async function generateGenericState(c5, stateData, settings) { - const state2 = generateRandomString(32); - if (c5.context.oauthConfig.storeStateStrategy === "cookie") { - const encryptedData = await symmetricEncrypt({ - key: c5.context.secret, - data: JSON.stringify(stateData) - }); - const stateCookie$1 = c5.context.createAuthCookie(settings?.cookieName ?? "oauth_state", { maxAge: 600 }); - c5.setCookie(stateCookie$1.name, encryptedData, stateCookie$1.attributes); - return { - state: state2, - codeVerifier: stateData.codeVerifier - }; - } - const stateCookie = c5.context.createAuthCookie(settings?.cookieName ?? "state", { maxAge: 300 }); - await c5.setSignedCookie(stateCookie.name, state2, c5.context.secret, stateCookie.attributes); - const expiresAt = /* @__PURE__ */ new Date(); - expiresAt.setMinutes(expiresAt.getMinutes() + 10); - const verification = await c5.context.internalAdapter.createVerificationValue({ - value: JSON.stringify(stateData), - identifier: state2, - expiresAt - }); - if (!verification) throw new StateError("Unable to create verification. Make sure the database adapter is properly working and there is a verification table in the database", { code: "state_generation_error" }); - return { - state: verification.identifier, - codeVerifier: stateData.codeVerifier - }; -} -async function parseGenericState(c5, state2, settings) { - const storeStateStrategy = c5.context.oauthConfig.storeStateStrategy; - let parsedData; - if (storeStateStrategy === "cookie") { - const stateCookie = c5.context.createAuthCookie(settings?.cookieName ?? "oauth_state"); - const encryptedData = c5.getCookie(stateCookie.name); - if (!encryptedData) throw new StateError("State mismatch: auth state cookie not found", { - code: "state_mismatch", - details: { state: state2 } - }); - try { - const decryptedData = await symmetricDecrypt({ - key: c5.context.secret, - data: encryptedData - }); - parsedData = stateDataSchema.parse(JSON.parse(decryptedData)); - } catch (error50) { - throw new StateError("State invalid: Failed to decrypt or parse auth state", { - code: "state_invalid", - details: { state: state2 }, - cause: error50 - }); - } - expireCookie(c5, stateCookie); - } else { - const data2 = await c5.context.internalAdapter.findVerificationValue(state2); - if (!data2) throw new StateError("State mismatch: verification not found", { - code: "state_mismatch", - details: { state: state2 } - }); - parsedData = stateDataSchema.parse(JSON.parse(data2.value)); - const stateCookie = c5.context.createAuthCookie(settings?.cookieName ?? "state"); - const stateCookieValue = await c5.getSignedCookie(stateCookie.name, c5.context.secret); - if (!c5.context.oauthConfig.skipStateCookieCheck && (!stateCookieValue || stateCookieValue !== state2)) throw new StateError("State mismatch: State not persisted correctly", { - code: "state_security_mismatch", - details: { state: state2 } - }); - expireCookie(c5, stateCookie); - await c5.context.internalAdapter.deleteVerificationValue(data2.id); - } - if (parsedData.expiresAt < Date.now()) throw new StateError("Invalid state: request expired", { - code: "state_mismatch", - details: { expiresAt: parsedData.expiresAt } - }); - return parsedData; -} -var stateDataSchema, StateError; -var init_state = __esm({ - "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/state.mjs"() { - init_random2(); - init_crypto(); - init_cookies2(); - init_error(); - init_zod(); - stateDataSchema = looseObject({ - callbackURL: string2(), - codeVerifier: string2(), - errorURL: string2().optional(), - newUserURL: string2().optional(), - expiresAt: number2(), - link: object({ - email: string2(), - userId: coerce_exports.string() - }).optional(), - requestSignUp: boolean3().optional() - }); - StateError = class extends BetterAuthError { - code; - details; - constructor(message2, options) { - super(message2, options); - this.code = options.code; - this.details = options.details; - } - }; - } -}); - -// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/context/global.mjs -function __getBetterAuthGlobal() { - if (!globalThis[symbol2]) { - globalThis[symbol2] = { - version: __betterAuthVersion, - epoch: 1, - context: __context - }; - bind = globalThis[symbol2]; - } - bind = globalThis[symbol2]; - if (bind.version !== __betterAuthVersion) { - bind.version = __betterAuthVersion; - bind.epoch++; - } - return globalThis[symbol2]; -} -function getBetterAuthVersion() { - return __getBetterAuthGlobal().version; -} -var symbol2, bind, __context, __betterAuthVersion; -var init_global = __esm({ - "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/context/global.mjs"() { - symbol2 = /* @__PURE__ */ Symbol.for("better-auth:global"); - bind = null; - __context = {}; - __betterAuthVersion = "1.4.18"; - } -}); - -// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/async_hooks/index.mjs -async function getAsyncLocalStorage() { - const mod = await AsyncLocalStoragePromise; - if (mod === null) throw new Error("getAsyncLocalStorage is only available in server code"); - else return mod; -} -var AsyncLocalStoragePromise; -var init_async_hooks = __esm({ - "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/async_hooks/index.mjs"() { - AsyncLocalStoragePromise = import( - /* @vite-ignore */ - /* webpackIgnore: true */ - "node:async_hooks" - ).then((mod) => mod.AsyncLocalStorage).catch((err) => { - if ("AsyncLocalStorage" in globalThis) return globalThis.AsyncLocalStorage; - if (typeof window !== "undefined") return null; - console.warn("[better-auth] Warning: AsyncLocalStorage is not available in this environment. Some features may not work as expected."); - console.warn("[better-auth] Please read more about this warning at https://better-auth.com/docs/installation#mount-handler"); - console.warn("[better-auth] If you are using Cloudflare Workers, please see: https://developers.cloudflare.com/workers/configuration/compatibility-flags/#nodejs-compatibility-flag"); - throw err; - }); - } -}); - -// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/context/endpoint-context.mjs -async function getCurrentAuthContext() { - const context = (await ensureAsyncStorage()).getStore(); - if (!context) throw new Error("No auth context found. Please make sure you are calling this function within a `runWithEndpointContext` callback."); - return context; -} -async function runWithEndpointContext(context, fn) { - return (await ensureAsyncStorage()).run(context, fn); -} -var ensureAsyncStorage; -var init_endpoint_context = __esm({ - "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/context/endpoint-context.mjs"() { - init_global(); - init_async_hooks(); - ensureAsyncStorage = async () => { - const betterAuthGlobal = __getBetterAuthGlobal(); - if (!betterAuthGlobal.context.endpointContextAsyncStorage) { - const AsyncLocalStorage$1 = await getAsyncLocalStorage(); - betterAuthGlobal.context.endpointContextAsyncStorage = new AsyncLocalStorage$1(); - } - return betterAuthGlobal.context.endpointContextAsyncStorage; - }; - } -}); - -// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/context/request-state.mjs -async function hasRequestState() { - return (await ensureAsyncStorage2()).getStore() !== void 0; -} -async function getCurrentRequestState() { - const store = (await ensureAsyncStorage2()).getStore(); - if (!store) throw new Error("No request state found. Please make sure you are calling this function within a `runWithRequestState` callback."); - return store; -} -async function runWithRequestState(store, fn) { - return (await ensureAsyncStorage2()).run(store, fn); -} -function defineRequestState(initFn) { - const ref = Object.freeze({}); - return { - get ref() { - return ref; - }, - async get() { - const store = await getCurrentRequestState(); - if (!store.has(ref)) { - const initialValue = await initFn(); - store.set(ref, initialValue); - return initialValue; - } - return store.get(ref); - }, - async set(value) { - (await getCurrentRequestState()).set(ref, value); - } - }; -} -var ensureAsyncStorage2; -var init_request_state = __esm({ - "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/context/request-state.mjs"() { - init_global(); - init_async_hooks(); - ensureAsyncStorage2 = async () => { - const betterAuthGlobal = __getBetterAuthGlobal(); - if (!betterAuthGlobal.context.requestStateAsyncStorage) { - const AsyncLocalStorage$1 = await getAsyncLocalStorage(); - betterAuthGlobal.context.requestStateAsyncStorage = new AsyncLocalStorage$1(); - } - return betterAuthGlobal.context.requestStateAsyncStorage; - }; - } -}); - -// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/context/transaction.mjs -var ensureAsyncStorage3, getCurrentAdapter, runWithAdapter, runWithTransaction; -var init_transaction = __esm({ - "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/context/transaction.mjs"() { - init_global(); - init_async_hooks(); - ensureAsyncStorage3 = async () => { - const betterAuthGlobal = __getBetterAuthGlobal(); - if (!betterAuthGlobal.context.adapterAsyncStorage) { - const AsyncLocalStorage$1 = await getAsyncLocalStorage(); - betterAuthGlobal.context.adapterAsyncStorage = new AsyncLocalStorage$1(); - } - return betterAuthGlobal.context.adapterAsyncStorage; - }; - getCurrentAdapter = async (fallback) => { - return ensureAsyncStorage3().then((als) => { - return als.getStore() || fallback; - }).catch(() => { - return fallback; - }); - }; - runWithAdapter = async (adapter, fn) => { - let called = true; - return ensureAsyncStorage3().then((als) => { - called = true; - return als.run(adapter, fn); - }).catch((err) => { - if (!called) return fn(); - throw err; - }); - }; - runWithTransaction = async (adapter, fn) => { - let called = true; - return ensureAsyncStorage3().then((als) => { - called = true; - return adapter.transaction(async (trx) => { - return als.run(trx, fn); - }); - }).catch((err) => { - if (!called) return fn(); - throw err; - }); - }; - } -}); - -// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/context/index.mjs -var init_context2 = __esm({ - "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/context/index.mjs"() { - init_global(); - init_endpoint_context(); - init_request_state(); - init_transaction(); - } -}); - -// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/api/middlewares/oauth.mjs -var getOAuthState, setOAuthState; -var init_oauth = __esm({ - "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/api/middlewares/oauth.mjs"() { - init_context2(); - ({ get: getOAuthState, set: setOAuthState } = defineRequestState(() => null)); - } -}); - -// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/oauth2/state.mjs -async function generateState(c5, link, additionalData) { - const callbackURL = c5.body?.callbackURL || c5.context.options.baseURL; - if (!callbackURL) throw new APIError("BAD_REQUEST", { message: "callbackURL is required" }); - const codeVerifier = generateRandomString(128); - const stateData = { - ...additionalData ? additionalData : {}, - callbackURL, - codeVerifier, - errorURL: c5.body?.errorCallbackURL, - newUserURL: c5.body?.newUserCallbackURL, - link, - expiresAt: Date.now() + 600 * 1e3, - requestSignUp: c5.body?.requestSignUp - }; - await setOAuthState(stateData); - try { - return generateGenericState(c5, stateData); - } catch (error50) { - c5.context.logger.error("Failed to create verification", error50); - throw new APIError("INTERNAL_SERVER_ERROR", { - message: "Unable to create verification", - cause: error50 - }); - } -} -async function parseState(c5) { - const state2 = c5.query.state || c5.body.state; - const errorURL = c5.context.options.onAPIError?.errorURL || `${c5.context.baseURL}/error`; - let parsedData; - try { - parsedData = await parseGenericState(c5, state2); - } catch (error50) { - c5.context.logger.error("Failed to parse state", error50); - if (error50 instanceof StateError && error50.code === "state_security_mismatch") throw c5.redirect(`${errorURL}?error=state_mismatch`); - throw c5.redirect(`${errorURL}?error=please_restart_the_process`); - } - if (!parsedData.errorURL) parsedData.errorURL = errorURL; - if (parsedData) await setOAuthState(parsedData); - return parsedData; -} -var init_state2 = __esm({ - "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/oauth2/state.mjs"() { - init_oauth(); - init_random2(); - init_crypto(); - init_state(); - init_dist3(); - } -}); - -// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/utils/hide-metadata.mjs -var HIDE_METADATA; -var init_hide_metadata = __esm({ - "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/utils/hide-metadata.mjs"() { - HIDE_METADATA = { scope: "server" }; - } -}); - -// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/utils/index.mjs -var init_utils10 = __esm({ - "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/utils/index.mjs"() { - init_state(); - init_state2(); - init_hide_metadata(); - init_utils7(); - } -}); - -// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/utils/get-request-ip.mjs -function getIp(req, options) { - if (options.advanced?.ipAddress?.disableIpTracking) return null; - const headers = "headers" in req ? req.headers : req; - const ipHeaders = options.advanced?.ipAddress?.ipAddressHeaders || ["x-forwarded-for"]; - for (const key of ipHeaders) { - const value = "get" in headers ? headers.get(key) : headers[key]; - if (typeof value === "string") { - const ip = value.split(",")[0].trim(); - if (isValidIP2(ip)) return normalizeIP(ip, { ipv6Subnet: options.advanced?.ipAddress?.ipv6Subnet }); - } - } - if (isTest() || isDevelopment()) return LOCALHOST_IP; - return null; -} -var LOCALHOST_IP; -var init_get_request_ip = __esm({ - "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/utils/get-request-ip.mjs"() { - init_env(); - init_utils7(); - LOCALHOST_IP = "127.0.0.1"; - } -}); - -// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/utils/url.mjs -function checkHasPath(url2) { - try { - return (new URL(url2).pathname.replace(/\/+$/, "") || "/") !== "/"; - } catch { - throw new BetterAuthError(`Invalid base URL: ${url2}. Please provide a valid base URL.`); - } -} -function assertHasProtocol(url2) { - try { - const parsedUrl = new URL(url2); - if (parsedUrl.protocol !== "http:" && parsedUrl.protocol !== "https:") throw new BetterAuthError(`Invalid base URL: ${url2}. URL must include 'http://' or 'https://'`); - } catch (error50) { - if (error50 instanceof BetterAuthError) throw error50; - throw new BetterAuthError(`Invalid base URL: ${url2}. Please provide a valid base URL.`, { cause: error50 }); - } -} -function withPath(url2, path53 = "/api/auth") { - assertHasProtocol(url2); - if (checkHasPath(url2)) return url2; - const trimmedUrl = url2.replace(/\/+$/, ""); - if (!path53 || path53 === "/") return trimmedUrl; - path53 = path53.startsWith("/") ? path53 : `/${path53}`; - return `${trimmedUrl}${path53}`; -} -function validateProxyHeader(header, type) { - if (!header || header.trim() === "") return false; - if (type === "proto") return header === "http" || header === "https"; - if (type === "host") { - if ([ - /\.\./, - /\0/, - /[\s]/, - /^[.]/, - /[<>'"]/, - /javascript:/i, - /file:/i, - /data:/i - ].some((pattern) => pattern.test(header))) return false; - return /^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*(:[0-9]{1,5})?$/.test(header) || /^(\d{1,3}\.){3}\d{1,3}(:[0-9]{1,5})?$/.test(header) || /^\[[0-9a-fA-F:]+\](:[0-9]{1,5})?$/.test(header) || /^localhost(:[0-9]{1,5})?$/i.test(header); - } - return false; -} -function getBaseURL(url2, path53, request, loadEnv, trustedProxyHeaders) { - if (url2) return withPath(url2, path53); - if (loadEnv !== false) { - const fromEnv = env.BETTER_AUTH_URL || env.NEXT_PUBLIC_BETTER_AUTH_URL || env.PUBLIC_BETTER_AUTH_URL || env.NUXT_PUBLIC_BETTER_AUTH_URL || env.NUXT_PUBLIC_AUTH_URL || (env.BASE_URL !== "/" ? env.BASE_URL : void 0); - if (fromEnv) return withPath(fromEnv, path53); - } - const fromRequest = request?.headers.get("x-forwarded-host"); - const fromRequestProto = request?.headers.get("x-forwarded-proto"); - if (fromRequest && fromRequestProto && trustedProxyHeaders) { - if (validateProxyHeader(fromRequestProto, "proto") && validateProxyHeader(fromRequest, "host")) try { - return withPath(`${fromRequestProto}://${fromRequest}`, path53); - } catch (_error) { - } - } - if (request) { - const url$1 = getOrigin(request.url); - if (!url$1) throw new BetterAuthError("Could not get origin from request. Please provide a valid base URL."); - return withPath(url$1, path53); - } - if (typeof window !== "undefined" && window.location) return withPath(window.location.origin, path53); -} -function getOrigin(url2) { - try { - const parsedUrl = new URL(url2); - return parsedUrl.origin === "null" ? null : parsedUrl.origin; - } catch { - return null; - } -} -function getProtocol(url2) { - try { - return new URL(url2).protocol; - } catch { - return null; - } -} -function getHost(url2) { - try { - return new URL(url2).host; - } catch { - return null; - } -} -var init_url2 = __esm({ - "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/utils/url.mjs"() { - init_env(); - init_error(); - } -}); - -// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/utils/wildcard.mjs -function escapeRegExpChar(char2) { - if (char2 === "-" || char2 === "^" || char2 === "$" || char2 === "+" || char2 === "." || char2 === "(" || char2 === ")" || char2 === "|" || char2 === "[" || char2 === "]" || char2 === "{" || char2 === "}" || char2 === "*" || char2 === "?" || char2 === "\\") return `\\${char2}`; - else return char2; -} -function escapeRegExpString(str) { - let result = ""; - for (let i5 = 0; i5 < str.length; i5++) result += escapeRegExpChar(str[i5]); - return result; -} -function transform2(pattern, separator = true) { - if (Array.isArray(pattern)) return `(?:${pattern.map((p5) => `^${transform2(p5, separator)}$`).join("|")})`; - let separatorSplitter = ""; - let separatorMatcher = ""; - let wildcard = "."; - if (separator === true) { - separatorSplitter = "/"; - separatorMatcher = "[/\\\\]"; - wildcard = "[^/\\\\]"; - } else if (separator) { - separatorSplitter = separator; - separatorMatcher = escapeRegExpString(separatorSplitter); - if (separatorMatcher.length > 1) { - separatorMatcher = `(?:${separatorMatcher})`; - wildcard = `((?!${separatorMatcher}).)`; - } else wildcard = `[^${separatorMatcher}]`; - } - const requiredSeparator = separator ? `${separatorMatcher}+?` : ""; - const optionalSeparator = separator ? `${separatorMatcher}*?` : ""; - const segments = separator ? pattern.split(separatorSplitter) : [pattern]; - let result = ""; - for (let s5 = 0; s5 < segments.length; s5++) { - const segment = segments[s5]; - const nextSegment = segments[s5 + 1]; - let currentSeparator = ""; - if (!segment && s5 > 0) continue; - if (separator) if (s5 === segments.length - 1) currentSeparator = optionalSeparator; - else if (nextSegment !== "**") currentSeparator = requiredSeparator; - else currentSeparator = ""; - if (separator && segment === "**") { - if (currentSeparator) { - result += s5 === 0 ? "" : currentSeparator; - result += `(?:${wildcard}*?${currentSeparator})*?`; - } - continue; - } - for (let c5 = 0; c5 < segment.length; c5++) { - const char2 = segment[c5]; - if (char2 === "\\") { - if (c5 < segment.length - 1) { - result += escapeRegExpChar(segment[c5 + 1]); - c5++; - } - } else if (char2 === "?") result += wildcard; - else if (char2 === "*") result += `${wildcard}*?`; - else result += escapeRegExpChar(char2); - } - result += currentSeparator; - } - return result; -} -function isMatch(regexp, sample) { - if (typeof sample !== "string") throw new TypeError(`Sample must be a string, but ${typeof sample} given`); - return regexp.test(sample); -} -function wildcardMatch(pattern, options) { - if (typeof pattern !== "string" && !Array.isArray(pattern)) throw new TypeError(`The first argument must be a single pattern string or an array of patterns, but ${typeof pattern} given`); - if (typeof options === "string" || typeof options === "boolean") options = { separator: options }; - if (arguments.length === 2 && !(typeof options === "undefined" || typeof options === "object" && options !== null && !Array.isArray(options))) throw new TypeError(`The second argument must be an options object or a string/boolean separator, but ${typeof options} given`); - options = options || {}; - if (options.separator === "\\") throw new Error("\\ is not a valid separator because it is used for escaping. Try setting the separator to `true` instead"); - const regexpPattern = transform2(pattern, options.separator); - const regexp = new RegExp(`^${regexpPattern}$`, options.flags); - const fn = isMatch.bind(null, regexp); - fn.options = options; - fn.pattern = pattern; - fn.regexp = regexp; - return fn; -} -var init_wildcard = __esm({ - "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/utils/wildcard.mjs"() { - } -}); - -// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/auth/trusted-origins.mjs -var matchesOriginPattern; -var init_trusted_origins = __esm({ - "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/auth/trusted-origins.mjs"() { - init_url2(); - init_wildcard(); - matchesOriginPattern = (url2, pattern, settings) => { - if (url2.startsWith("/")) { - if (settings?.allowRelativePaths) return url2.startsWith("/") && /^\/(?!\/|\\|%2f|%5c)[\w\-.\+/@]*(?:\?[\w\-.\+/=&%@]*)?$/.test(url2); - return false; - } - if (pattern.includes("*") || pattern.includes("?")) { - if (pattern.includes("://")) return wildcardMatch(pattern)(getOrigin(url2) || url2); - const host = getHost(url2); - if (!host) return false; - return wildcardMatch(pattern)(host); - } - const protocol = getProtocol(url2); - return protocol === "http:" || protocol === "https:" || !protocol ? pattern === getOrigin(url2) : url2.startsWith(pattern); - }; - } -}); - -// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/api/index.mjs -function createAuthEndpoint(pathOrOptions, handlerOrOptions, handlerOrNever) { - const path53 = typeof pathOrOptions === "string" ? pathOrOptions : void 0; - const options = typeof handlerOrOptions === "object" ? handlerOrOptions : pathOrOptions; - const handler = typeof handlerOrOptions === "function" ? handlerOrOptions : handlerOrNever; - if (path53) return createEndpoint(path53, { - ...options, - use: [...options?.use || [], ...use] - }, async (ctx) => runWithEndpointContext(ctx, () => handler(ctx))); - return createEndpoint({ - ...options, - use: [...options?.use || [], ...use] - }, async (ctx) => runWithEndpointContext(ctx, () => handler(ctx))); -} -var optionsMiddleware, createAuthMiddleware, use; -var init_api2 = __esm({ - "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/api/index.mjs"() { - init_endpoint_context(); - init_context2(); - init_dist3(); - optionsMiddleware = createMiddleware(async () => { - return {}; - }); - createAuthMiddleware = createMiddleware.create({ use: [optionsMiddleware, createMiddleware(async () => { - return {}; - })] }); - use = [optionsMiddleware]; - } -}); - -// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/api/middlewares/origin-check.mjs -function shouldSkipCSRFForBackwardCompat(ctx) { - return ctx.context.skipOriginCheck === true && ctx.context.options.advanced?.disableCSRFCheck === void 0; -} -async function validateOrigin(ctx, forceValidate = false) { - const headers = ctx.request?.headers; - if (!headers || !ctx.request) return; - const originHeader = headers.get("origin") || headers.get("referer") || ""; - const useCookies = headers.has("cookie"); - if (ctx.context.skipCSRFCheck) return; - if (shouldSkipCSRFForBackwardCompat(ctx)) { - ctx.context.options.advanced?.disableOriginCheck === true && logBackwardCompatWarning(); - return; - } - const skipOriginCheck = ctx.context.skipOriginCheck; - if (Array.isArray(skipOriginCheck)) try { - const basePath = new URL(ctx.context.baseURL).pathname; - const currentPath = normalizePathname(ctx.request.url, basePath); - if (skipOriginCheck.some((skipPath) => currentPath.startsWith(skipPath))) return; - } catch { - } - if (!(forceValidate || useCookies)) return; - if (!originHeader || originHeader === "null") throw new APIError("FORBIDDEN", { message: BASE_ERROR_CODES.MISSING_OR_NULL_ORIGIN }); - const trustedOrigins = Array.isArray(ctx.context.options.trustedOrigins) ? ctx.context.trustedOrigins : [...ctx.context.trustedOrigins, ...(await ctx.context.options.trustedOrigins?.(ctx.request))?.filter((v5) => Boolean(v5)) || []]; - if (!trustedOrigins.some((origin) => matchesOriginPattern(originHeader, origin))) { - ctx.context.logger.error(`Invalid origin: ${originHeader}`); - ctx.context.logger.info(`If it's a valid URL, please add ${originHeader} to trustedOrigins in your auth config -`, `Current list of trustedOrigins: ${trustedOrigins}`); - throw new APIError("FORBIDDEN", { message: "Invalid origin" }); - } -} -async function validateFormCsrf(ctx) { - const req = ctx.request; - if (!req) return; - if (ctx.context.skipCSRFCheck) return; - if (shouldSkipCSRFForBackwardCompat(ctx)) return; - const headers = req.headers; - if (headers.has("cookie")) return await validateOrigin(ctx); - const site = headers.get("Sec-Fetch-Site"); - const mode = headers.get("Sec-Fetch-Mode"); - const dest = headers.get("Sec-Fetch-Dest"); - if (Boolean(site && site.trim() || mode && mode.trim() || dest && dest.trim())) { - if (site === "cross-site" && mode === "navigate") { - ctx.context.logger.error("Blocked cross-site navigation login attempt (CSRF protection)", { - secFetchSite: site, - secFetchMode: mode, - secFetchDest: dest - }); - throw new APIError("FORBIDDEN", { message: BASE_ERROR_CODES.CROSS_SITE_NAVIGATION_LOGIN_BLOCKED }); - } - return await validateOrigin(ctx, true); - } -} -var logBackwardCompatWarning, originCheckMiddleware, originCheck, formCsrfMiddleware; -var init_origin_check = __esm({ - "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/api/middlewares/origin-check.mjs"() { - init_trusted_origins(); - init_error(); - init_utils7(); - init_dist3(); - init_api2(); - logBackwardCompatWarning = deprecate(function logBackwardCompatWarning$1() { - }, "disableOriginCheck: true currently also disables CSRF checks. In a future version, disableOriginCheck will ONLY disable URL validation. To keep CSRF disabled, add disableCSRFCheck: true to your config."); - originCheckMiddleware = createAuthMiddleware(async (ctx) => { - if (ctx.request?.method === "GET" || ctx.request?.method === "OPTIONS" || ctx.request?.method === "HEAD" || !ctx.request) return; - await validateOrigin(ctx); - if (ctx.context.skipOriginCheck) return; - const { body, query } = ctx; - const callbackURL = body?.callbackURL || query?.callbackURL; - const redirectURL = body?.redirectTo; - const errorCallbackURL = body?.errorCallbackURL; - const newUserCallbackURL = body?.newUserCallbackURL; - const validateURL = (url2, label) => { - if (!url2) return; - if (!ctx.context.isTrustedOrigin(url2, { allowRelativePaths: label !== "origin" })) { - ctx.context.logger.error(`Invalid ${label}: ${url2}`); - ctx.context.logger.info(`If it's a valid URL, please add ${url2} to trustedOrigins in your auth config -`, `Current list of trustedOrigins: ${ctx.context.trustedOrigins}`); - throw new APIError("FORBIDDEN", { message: `Invalid ${label}` }); - } - }; - callbackURL && validateURL(callbackURL, "callbackURL"); - redirectURL && validateURL(redirectURL, "redirectURL"); - errorCallbackURL && validateURL(errorCallbackURL, "errorCallbackURL"); - newUserCallbackURL && validateURL(newUserCallbackURL, "newUserCallbackURL"); - }); - originCheck = (getValue) => createAuthMiddleware(async (ctx) => { - if (!ctx.request) return; - if (ctx.context.skipOriginCheck) return; - const callbackURL = getValue(ctx); - const validateURL = (url2, label) => { - if (!url2) return; - if (!ctx.context.isTrustedOrigin(url2, { allowRelativePaths: label !== "origin" })) { - ctx.context.logger.error(`Invalid ${label}: ${url2}`); - ctx.context.logger.info(`If it's a valid URL, please add ${url2} to trustedOrigins in your auth config -`, `Current list of trustedOrigins: ${ctx.context.trustedOrigins}`); - throw new APIError("FORBIDDEN", { message: `Invalid ${label}` }); - } - }; - const callbacks = Array.isArray(callbackURL) ? callbackURL : [callbackURL]; - for (const url2 of callbacks) validateURL(url2, "callbackURL"); - }); - formCsrfMiddleware = createAuthMiddleware(async (ctx) => { - if (!ctx.request) return; - await validateFormCsrf(ctx); - }); - } -}); - -// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/api/middlewares/index.mjs -var init_middlewares = __esm({ - "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/api/middlewares/index.mjs"() { - init_oauth(); - init_origin_check(); - } -}); - -// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/api/rate-limiter/index.mjs -function shouldRateLimit(max, window2, rateLimitData) { - const now2 = Date.now(); - const windowInMs = window2 * 1e3; - return now2 - rateLimitData.lastRequest < windowInMs && rateLimitData.count >= max; -} -function rateLimitResponse(retryAfter) { - return new Response(JSON.stringify({ message: "Too many requests. Please try again later." }), { - status: 429, - statusText: "Too Many Requests", - headers: { "X-Retry-After": retryAfter.toString() } - }); -} -function getRetryAfter(lastRequest, window2) { - const now2 = Date.now(); - const windowInMs = window2 * 1e3; - return Math.ceil((lastRequest + windowInMs - now2) / 1e3); -} -function createDatabaseStorageWrapper(ctx) { - const model = "rateLimit"; - const db = ctx.adapter; - return { - get: async (key) => { - const data2 = (await db.findMany({ - model, - where: [{ - field: "key", - value: key - }] - }))[0]; - if (typeof data2?.lastRequest === "bigint") data2.lastRequest = Number(data2.lastRequest); - return data2; - }, - set: async (key, value, _update) => { - try { - if (_update) await db.updateMany({ - model, - where: [{ - field: "key", - value: key - }], - update: { - count: value.count, - lastRequest: value.lastRequest - } - }); - else await db.create({ - model, - data: { - key, - count: value.count, - lastRequest: value.lastRequest - } - }); - } catch (e5) { - ctx.logger.error("Error setting rate limit", e5); - } - } - }; -} -function getRateLimitStorage(ctx, rateLimitSettings) { - if (ctx.options.rateLimit?.customStorage) return ctx.options.rateLimit.customStorage; - const storage = ctx.rateLimit.storage; - if (storage === "secondary-storage") return { - get: async (key) => { - const data2 = await ctx.options.secondaryStorage?.get(key); - return data2 ? safeJSONParse(data2) : null; - }, - set: async (key, value, _update) => { - const ttl = rateLimitSettings?.window ?? ctx.options.rateLimit?.window ?? 10; - await ctx.options.secondaryStorage?.set?.(key, JSON.stringify(value), ttl); - } - }; - else if (storage === "memory") return { - async get(key) { - const entry = memory.get(key); - if (!entry) return null; - if (Date.now() >= entry.expiresAt) { - memory.delete(key); - return null; - } - return entry.data; - }, - async set(key, value, _update) { - const ttl = rateLimitSettings?.window ?? ctx.options.rateLimit?.window ?? 10; - const expiresAt = Date.now() + ttl * 1e3; - memory.set(key, { - data: value, - expiresAt - }); - } - }; - return createDatabaseStorageWrapper(ctx); -} -async function onRequestRateLimit(req, ctx) { - if (!ctx.rateLimit.enabled) return; - const basePath = new URL(ctx.baseURL).pathname; - const path53 = normalizePathname(req.url, basePath); - let currentWindow = ctx.rateLimit.window; - let currentMax = ctx.rateLimit.max; - const ip = getIp(req, ctx.options); - if (!ip) return; - const key = createRateLimitKey(ip, path53); - const specialRule = getDefaultSpecialRules().find((rule) => rule.pathMatcher(path53)); - if (specialRule) { - currentWindow = specialRule.window; - currentMax = specialRule.max; - } - for (const plugin of ctx.options.plugins || []) if (plugin.rateLimit) { - const matchedRule = plugin.rateLimit.find((rule) => rule.pathMatcher(path53)); - if (matchedRule) { - currentWindow = matchedRule.window; - currentMax = matchedRule.max; - break; - } - } - if (ctx.rateLimit.customRules) { - const _path = Object.keys(ctx.rateLimit.customRules).find((p5) => { - if (p5.includes("*")) return wildcardMatch(p5)(path53); - return p5 === path53; - }); - if (_path) { - const customRule = ctx.rateLimit.customRules[_path]; - const resolved = typeof customRule === "function" ? await customRule(req, { - window: currentWindow, - max: currentMax - }) : customRule; - if (resolved) { - currentWindow = resolved.window; - currentMax = resolved.max; - } - if (resolved === false) return; - } - } - const storage = getRateLimitStorage(ctx, { window: currentWindow }); - const data2 = await storage.get(key); - const now2 = Date.now(); - if (!data2) await storage.set(key, { - key, - count: 1, - lastRequest: now2 - }); - else { - const timeSinceLastRequest = now2 - data2.lastRequest; - if (shouldRateLimit(currentMax, currentWindow, data2)) return rateLimitResponse(getRetryAfter(data2.lastRequest, currentWindow)); - else if (timeSinceLastRequest > currentWindow * 1e3) await storage.set(key, { - ...data2, - count: 1, - lastRequest: now2 - }, true); - else await storage.set(key, { - ...data2, - count: data2.count + 1, - lastRequest: now2 - }, true); - } -} -function getDefaultSpecialRules() { - return [{ - pathMatcher(path53) { - return path53.startsWith("/sign-in") || path53.startsWith("/sign-up") || path53.startsWith("/change-password") || path53.startsWith("/change-email"); - }, - window: 10, - max: 3 - }]; -} -var memory; -var init_rate_limiter = __esm({ - "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/api/rate-limiter/index.mjs"() { - init_get_request_ip(); - init_wildcard(); - init_utils7(); - memory = /* @__PURE__ */ new Map(); - } -}); - -// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/_virtual/rolldown_runtime.mjs -var __defProp2, __getOwnPropDesc2, __getOwnPropNames2, __hasOwnProp2, __export2, __copyProps2, __reExport; -var init_rolldown_runtime = __esm({ - "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/_virtual/rolldown_runtime.mjs"() { - __defProp2 = Object.defineProperty; - __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - __getOwnPropNames2 = Object.getOwnPropertyNames; - __hasOwnProp2 = Object.prototype.hasOwnProperty; - __export2 = (all, symbols) => { - let target = {}; - for (var name in all) { - __defProp2(target, name, { - get: all[name], - enumerable: true - }); - } - if (symbols) { - __defProp2(target, Symbol.toStringTag, { value: "Module" }); - } - return target; - }; - __copyProps2 = (to, from, except2, desc3) => { - if (from && typeof from === "object" || typeof from === "function") { - for (var keys = __getOwnPropNames2(from), i5 = 0, n5 = keys.length, key; i5 < n5; i5++) { - key = keys[i5]; - if (!__hasOwnProp2.call(to, key) && key !== except2) { - __defProp2(to, key, { - get: ((k5) => from[k5]).bind(null, key), - enumerable: !(desc3 = __getOwnPropDesc2(from, key)) || desc3.enumerable - }); - } - } - } - return to; - }; - __reExport = (target, mod, secondTarget, symbols) => { - if (symbols) { - __defProp2(target, Symbol.toStringTag, { value: "Module" }); - secondTarget && __defProp2(secondTarget, Symbol.toStringTag, { value: "Module" }); - } - __copyProps2(target, mod, "default"), secondTarget && __copyProps2(secondTarget, mod, "default"); - }; - } -}); - -// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/db/adapter/get-default-model-name.mjs -var initGetDefaultModelName; -var init_get_default_model_name = __esm({ - "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/db/adapter/get-default-model-name.mjs"() { - init_error(); - initGetDefaultModelName = ({ usePlural, schema: schema2 }) => { - const getDefaultModelName = (model) => { - if (usePlural && model.charAt(model.length - 1) === "s") { - const pluralessModel = model.slice(0, -1); - let m$1 = schema2[pluralessModel] ? pluralessModel : void 0; - if (!m$1) m$1 = Object.entries(schema2).find(([_, f5]) => f5.modelName === pluralessModel)?.[0]; - if (m$1) return m$1; - } - let m5 = schema2[model] ? model : void 0; - if (!m5) m5 = Object.entries(schema2).find(([_, f5]) => f5.modelName === model)?.[0]; - if (!m5) throw new BetterAuthError(`Model "${model}" not found in schema`); - return m5; - }; - return getDefaultModelName; - }; - } -}); - -// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/db/adapter/get-default-field-name.mjs -var initGetDefaultFieldName; -var init_get_default_field_name = __esm({ - "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/db/adapter/get-default-field-name.mjs"() { - init_error(); - init_get_default_model_name(); - initGetDefaultFieldName = ({ schema: schema2, usePlural }) => { - const getDefaultModelName = initGetDefaultModelName({ - schema: schema2, - usePlural - }); - const getDefaultFieldName = ({ field, model: unsafeModel }) => { - if (field === "id" || field === "_id") return "id"; - const model = getDefaultModelName(unsafeModel); - let f5 = schema2[model]?.fields[field]; - if (!f5) { - const result = Object.entries(schema2[model].fields).find(([_, f$1]) => f$1.fieldName === field); - if (result) { - f5 = result[1]; - field = result[0]; - } - } - if (!f5) throw new BetterAuthError(`Field ${field} not found in model ${model}`); - return field; - }; - return getDefaultFieldName; - }; - } -}); - -// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/db/adapter/get-id-field.mjs -var initGetIdField; -var init_get_id_field = __esm({ - "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/db/adapter/get-id-field.mjs"() { - init_logger2(); - init_env(); - init_id(); - init_utils7(); - init_get_default_model_name(); - initGetIdField = ({ usePlural, schema: schema2, disableIdGeneration, options, customIdGenerator, supportsUUIDs }) => { - const getDefaultModelName = initGetDefaultModelName({ - usePlural, - schema: schema2 - }); - const idField = ({ customModelName, forceAllowId }) => { - const useNumberId = options.advanced?.database?.useNumberId || options.advanced?.database?.generateId === "serial"; - const useUUIDs = options.advanced?.database?.generateId === "uuid"; - const shouldGenerateId = (() => { - if (disableIdGeneration) return false; - else if (useNumberId && !forceAllowId) return false; - else if (useUUIDs) return !supportsUUIDs; - else return true; - })(); - const model = getDefaultModelName(customModelName ?? "id"); - return { - type: useNumberId ? "number" : "string", - required: shouldGenerateId ? true : false, - ...shouldGenerateId ? { defaultValue() { - if (disableIdGeneration) return void 0; - const generateId$1 = options.advanced?.database?.generateId; - if (generateId$1 === false || useNumberId) return void 0; - if (typeof generateId$1 === "function") return generateId$1({ model }); - if (customIdGenerator) return customIdGenerator({ model }); - if (generateId$1 === "uuid") return crypto.randomUUID(); - return generateId(); - } } : {}, - transform: { - input: (value) => { - if (!value) return void 0; - if (useNumberId) { - const numberValue = Number(value); - if (isNaN(numberValue)) return; - return numberValue; - } - if (useUUIDs) { - if (shouldGenerateId && !forceAllowId) return value; - if (disableIdGeneration) return void 0; - if (supportsUUIDs) return void 0; - if (forceAllowId && typeof value === "string") if (/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value)) return value; - else { - const stack = (/* @__PURE__ */ new Error()).stack?.split("\n").filter((_, i5) => i5 !== 1).join("\n").replace("Error:", ""); - logger3.warn("[Adapter Factory] - Invalid UUID value for field `id` provided when `forceAllowId` is true. Generating a new UUID.", stack); - } - if (typeof value !== "string" && !supportsUUIDs) return crypto.randomUUID(); - return; - } - return value; - }, - output: (value) => { - if (!value) return void 0; - return String(value); - } - } - }; - }; - return idField; - }; - } -}); - -// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/db/adapter/get-field-attributes.mjs -var initGetFieldAttributes; -var init_get_field_attributes = __esm({ - "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/db/adapter/get-field-attributes.mjs"() { - init_error(); - init_get_default_model_name(); - init_get_default_field_name(); - init_get_id_field(); - initGetFieldAttributes = ({ usePlural, schema: schema2, options, customIdGenerator, disableIdGeneration }) => { - const getDefaultModelName = initGetDefaultModelName({ - usePlural, - schema: schema2 - }); - const getDefaultFieldName = initGetDefaultFieldName({ - usePlural, - schema: schema2 - }); - const idField = initGetIdField({ - usePlural, - schema: schema2, - options, - customIdGenerator, - disableIdGeneration - }); - const getFieldAttributes = ({ model, field }) => { - const defaultModelName = getDefaultModelName(model); - const defaultFieldName = getDefaultFieldName({ - field, - model: defaultModelName - }); - const fields = schema2[defaultModelName].fields; - fields.id = idField({ customModelName: defaultModelName }); - const fieldAttributes = fields[defaultFieldName]; - if (!fieldAttributes) throw new BetterAuthError(`Field ${field} not found in model ${model}`); - return fieldAttributes; - }; - return getFieldAttributes; - }; - } -}); - -// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/db/adapter/get-field-name.mjs -var initGetFieldName; -var init_get_field_name = __esm({ - "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/db/adapter/get-field-name.mjs"() { - init_get_default_model_name(); - init_get_default_field_name(); - initGetFieldName = ({ schema: schema2, usePlural }) => { - const getDefaultModelName = initGetDefaultModelName({ - schema: schema2, - usePlural - }); - const getDefaultFieldName = initGetDefaultFieldName({ - schema: schema2, - usePlural - }); - function getFieldName({ model: modelName, field: fieldName }) { - const model = getDefaultModelName(modelName); - const field = getDefaultFieldName({ - model, - field: fieldName - }); - return schema2[model]?.fields[field]?.fieldName || field; - } - return getFieldName; - }; - } -}); - -// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/db/adapter/get-model-name.mjs -var initGetModelName; -var init_get_model_name = __esm({ - "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/db/adapter/get-model-name.mjs"() { - init_get_default_model_name(); - initGetModelName = ({ usePlural, schema: schema2 }) => { - const getDefaultModelName = initGetDefaultModelName({ - schema: schema2, - usePlural - }); - const getModelName = (model) => { - const defaultModelKey = getDefaultModelName(model); - if (schema2 && schema2[defaultModelKey] && schema2[defaultModelKey].modelName !== model) return usePlural ? `${schema2[defaultModelKey].modelName}s` : schema2[defaultModelKey].modelName; - return usePlural ? `${model}s` : model; - }; - return getModelName; - }; - } -}); - -// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/db/adapter/utils.mjs -function withApplyDefault(value, field, action) { - if (action === "update") { - if (value === void 0 && field.onUpdate !== void 0) { - if (typeof field.onUpdate === "function") return field.onUpdate(); - return field.onUpdate; - } - return value; - } - if (action === "create") { - if (value === void 0 || field.required === true && value === null) { - if (field.defaultValue !== void 0) { - if (typeof field.defaultValue === "function") return field.defaultValue(); - return field.defaultValue; - } - } - } - return value; -} -var init_utils11 = __esm({ - "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/db/adapter/utils.mjs"() { - } -}); - -// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/db/adapter/factory.mjs -function formatTransactionId(transactionId$1) { - if (getColorDepth() < 8) return `#${transactionId$1}`; - return `${TTY_COLORS.fg.magenta}#${transactionId$1}${TTY_COLORS.reset}`; -} -function formatStep(step, total) { - return `${TTY_COLORS.bg.black}${TTY_COLORS.fg.yellow}[${step}/${total}]${TTY_COLORS.reset}`; -} -function formatMethod(method) { - return `${TTY_COLORS.bright}${method}${TTY_COLORS.reset}`; -} -function formatAction(action) { - return `${TTY_COLORS.dim}(${action})${TTY_COLORS.reset}`; -} -var debugLogs, transactionId, createAsIsTransaction, createAdapterFactory; -var init_factory = __esm({ - "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/db/adapter/factory.mjs"() { - init_get_tables(); - init_color_depth(); - init_logger2(); - init_env(); - init_json2(); - init_error(); - init_get_default_model_name(); - init_get_default_field_name(); - init_get_id_field(); - init_get_field_attributes(); - init_get_field_name(); - init_get_model_name(); - init_utils11(); - debugLogs = []; - transactionId = -1; - createAsIsTransaction = (adapter) => (fn) => fn(adapter); - createAdapterFactory = ({ adapter: customAdapter, config: cfg }) => (options) => { - const uniqueAdapterFactoryInstanceId = Math.random().toString(36).substring(2, 15); - const config3 = { - ...cfg, - supportsBooleans: cfg.supportsBooleans ?? true, - supportsDates: cfg.supportsDates ?? true, - supportsJSON: cfg.supportsJSON ?? false, - adapterName: cfg.adapterName ?? cfg.adapterId, - supportsNumericIds: cfg.supportsNumericIds ?? true, - supportsUUIDs: cfg.supportsUUIDs ?? false, - supportsArrays: cfg.supportsArrays ?? false, - transaction: cfg.transaction ?? false, - disableTransformInput: cfg.disableTransformInput ?? false, - disableTransformOutput: cfg.disableTransformOutput ?? false, - disableTransformJoin: cfg.disableTransformJoin ?? false - }; - if ((options.advanced?.database?.useNumberId === true || options.advanced?.database?.generateId === "serial") && config3.supportsNumericIds === false) throw new BetterAuthError(`[${config3.adapterName}] Your database or database adapter does not support numeric ids. Please disable "useNumberId" in your config.`); - const schema2 = getAuthTables(options); - const debugLog = (...args) => { - if (config3.debugLogs === true || typeof config3.debugLogs === "object") { - const logger$1 = createLogger({ level: "info" }); - if (typeof config3.debugLogs === "object" && "isRunningAdapterTests" in config3.debugLogs) { - if (config3.debugLogs.isRunningAdapterTests) { - args.shift(); - debugLogs.push({ - instance: uniqueAdapterFactoryInstanceId, - args - }); - } - return; - } - if (typeof config3.debugLogs === "object" && config3.debugLogs.logCondition && !config3.debugLogs.logCondition?.()) return; - if (typeof args[0] === "object" && "method" in args[0]) { - const method = args.shift().method; - if (typeof config3.debugLogs === "object") { - if (method === "create" && !config3.debugLogs.create) return; - else if (method === "update" && !config3.debugLogs.update) return; - else if (method === "updateMany" && !config3.debugLogs.updateMany) return; - else if (method === "findOne" && !config3.debugLogs.findOne) return; - else if (method === "findMany" && !config3.debugLogs.findMany) return; - else if (method === "delete" && !config3.debugLogs.delete) return; - else if (method === "deleteMany" && !config3.debugLogs.deleteMany) return; - else if (method === "count" && !config3.debugLogs.count) return; - } - logger$1.info(`[${config3.adapterName}]`, ...args); - } else logger$1.info(`[${config3.adapterName}]`, ...args); - } - }; - const logger4 = createLogger(options.logger); - const getDefaultModelName = initGetDefaultModelName({ - usePlural: config3.usePlural, - schema: schema2 - }); - const getDefaultFieldName = initGetDefaultFieldName({ - usePlural: config3.usePlural, - schema: schema2 - }); - const getModelName = initGetModelName({ - usePlural: config3.usePlural, - schema: schema2 - }); - const getFieldName = initGetFieldName({ - schema: schema2, - usePlural: config3.usePlural - }); - const idField = initGetIdField({ - schema: schema2, - options, - usePlural: config3.usePlural, - disableIdGeneration: config3.disableIdGeneration, - customIdGenerator: config3.customIdGenerator, - supportsUUIDs: config3.supportsUUIDs - }); - const getFieldAttributes = initGetFieldAttributes({ - schema: schema2, - options, - usePlural: config3.usePlural, - disableIdGeneration: config3.disableIdGeneration, - customIdGenerator: config3.customIdGenerator - }); - const transformInput = async (data2, defaultModelName, action, forceAllowId) => { - const transformedData = {}; - const fields = schema2[defaultModelName].fields; - const newMappedKeys = config3.mapKeysTransformInput ?? {}; - const useNumberId = options.advanced?.database?.useNumberId || options.advanced?.database?.generateId === "serial"; - fields.id = idField({ - customModelName: defaultModelName, - forceAllowId: forceAllowId && "id" in data2 - }); - for (const field in fields) { - let value = data2[field]; - const fieldAttributes = fields[field]; - const newFieldName = newMappedKeys[field] || fields[field].fieldName || field; - if (value === void 0 && (fieldAttributes.defaultValue === void 0 && !fieldAttributes.transform?.input && !(action === "update" && fieldAttributes.onUpdate) || action === "update" && !fieldAttributes.onUpdate)) continue; - if (fieldAttributes && fieldAttributes.type === "date" && !(value instanceof Date) && typeof value === "string") try { - value = new Date(value); - } catch { - logger4.error("[Adapter Factory] Failed to convert string to date", { - value, - field - }); - } - let newValue = withApplyDefault(value, fieldAttributes, action); - if (fieldAttributes.transform?.input) newValue = await fieldAttributes.transform.input(newValue); - if (fieldAttributes.references?.field === "id" && useNumberId) if (Array.isArray(newValue)) newValue = newValue.map((x5) => x5 !== null ? Number(x5) : null); - else newValue = newValue !== null ? Number(newValue) : null; - else if (config3.supportsJSON === false && typeof newValue === "object" && fieldAttributes.type === "json") newValue = JSON.stringify(newValue); - else if (config3.supportsArrays === false && Array.isArray(newValue) && (fieldAttributes.type === "string[]" || fieldAttributes.type === "number[]")) newValue = JSON.stringify(newValue); - else if (config3.supportsDates === false && newValue instanceof Date && fieldAttributes.type === "date") newValue = newValue.toISOString(); - else if (config3.supportsBooleans === false && typeof newValue === "boolean") newValue = newValue ? 1 : 0; - if (config3.customTransformInput) newValue = config3.customTransformInput({ - data: newValue, - action, - field: newFieldName, - fieldAttributes, - model: getModelName(defaultModelName), - schema: schema2, - options - }); - if (newValue !== void 0) transformedData[newFieldName] = newValue; - } - return transformedData; - }; - const transformOutput = async (data2, unsafe_model, select2 = [], join4) => { - const transformSingleOutput = async (data$1, unsafe_model$1, select$1 = []) => { - if (!data$1) return null; - const newMappedKeys = config3.mapKeysTransformOutput ?? {}; - const transformedData$1 = {}; - const tableSchema = schema2[getDefaultModelName(unsafe_model$1)].fields; - const idKey = Object.entries(newMappedKeys).find(([_, v5]) => v5 === "id")?.[0]; - tableSchema[idKey ?? "id"] = { type: options.advanced?.database?.useNumberId || options.advanced?.database?.generateId === "serial" ? "number" : "string" }; - for (const key in tableSchema) { - if (select$1.length && !select$1.includes(key)) continue; - const field = tableSchema[key]; - if (field) { - const originalKey = field.fieldName || key; - let newValue = data$1[Object.entries(newMappedKeys).find(([_, v5]) => v5 === originalKey)?.[0] || originalKey]; - if (field.transform?.output) newValue = await field.transform.output(newValue); - const newFieldName = newMappedKeys[key] || key; - if (originalKey === "id" || field.references?.field === "id") { - if (typeof newValue !== "undefined" && newValue !== null) newValue = String(newValue); - } else if (config3.supportsJSON === false && typeof newValue === "string" && field.type === "json") newValue = safeJSONParse(newValue); - else if (config3.supportsArrays === false && typeof newValue === "string" && (field.type === "string[]" || field.type === "number[]")) newValue = safeJSONParse(newValue); - else if (config3.supportsDates === false && typeof newValue === "string" && field.type === "date") newValue = new Date(newValue); - else if (config3.supportsBooleans === false && typeof newValue === "number" && field.type === "boolean") newValue = newValue === 1; - if (config3.customTransformOutput) newValue = config3.customTransformOutput({ - data: newValue, - field: newFieldName, - fieldAttributes: field, - select: select$1, - model: getModelName(unsafe_model$1), - schema: schema2, - options - }); - transformedData$1[newFieldName] = newValue; - } - } - return transformedData$1; - }; - if (!join4 || Object.keys(join4).length === 0) return await transformSingleOutput(data2, unsafe_model, select2); - unsafe_model = getDefaultModelName(unsafe_model); - const transformedData = await transformSingleOutput(data2, unsafe_model, select2); - const requiredModels = Object.entries(join4).map(([model, joinConfig]) => ({ - modelName: getModelName(model), - defaultModelName: getDefaultModelName(model), - joinConfig - })); - if (!data2) return null; - for (const { modelName, defaultModelName, joinConfig } of requiredModels) { - let joinedData = await (async () => { - if (options.experimental?.joins) return data2[modelName]; - else return await handleFallbackJoin({ - baseModel: unsafe_model, - baseData: transformedData, - joinModel: modelName, - specificJoinConfig: joinConfig - }); - })(); - if (joinedData === void 0 || joinedData === null) joinedData = joinConfig.relation === "one-to-one" ? null : []; - if (joinConfig.relation === "one-to-many" && !Array.isArray(joinedData)) joinedData = [joinedData]; - const transformed = []; - if (Array.isArray(joinedData)) for (const item of joinedData) { - const transformedItem = await transformSingleOutput(item, modelName, []); - transformed.push(transformedItem); - } - else { - const transformedItem = await transformSingleOutput(joinedData, modelName, []); - transformed.push(transformedItem); - } - transformedData[defaultModelName] = (joinConfig.relation === "one-to-one" ? transformed[0] : transformed) ?? null; - } - return transformedData; - }; - const transformWhereClause = ({ model, where, action }) => { - if (!where) return void 0; - const newMappedKeys = config3.mapKeysTransformInput ?? {}; - return where.map((w5) => { - const { field: unsafe_field, value, operator = "eq", connector = "AND" } = w5; - if (operator === "in") { - if (!Array.isArray(value)) throw new BetterAuthError("Value must be an array"); - } - let newValue = value; - const defaultModelName = getDefaultModelName(model); - const defaultFieldName = getDefaultFieldName({ - field: unsafe_field, - model - }); - const fieldName = newMappedKeys[defaultFieldName] || getFieldName({ - field: defaultFieldName, - model: defaultModelName - }); - const fieldAttr = getFieldAttributes({ - field: defaultFieldName, - model: defaultModelName - }); - const useNumberId = options.advanced?.database?.useNumberId || options.advanced?.database?.generateId === "serial"; - if (defaultFieldName === "id" || fieldAttr.references?.field === "id") { - if (useNumberId) if (Array.isArray(value)) newValue = value.map(Number); - else newValue = Number(value); - } - if (fieldAttr.type === "date" && value instanceof Date && !config3.supportsDates) newValue = value.toISOString(); - if (fieldAttr.type === "boolean" && typeof value === "boolean" && !config3.supportsBooleans) newValue = value ? 1 : 0; - if (fieldAttr.type === "json" && typeof value === "object" && !config3.supportsJSON) try { - newValue = JSON.stringify(value); - } catch (error50) { - throw new Error(`Failed to stringify JSON value for field ${fieldName}`, { cause: error50 }); - } - if (config3.customTransformInput) newValue = config3.customTransformInput({ - data: newValue, - fieldAttributes: fieldAttr, - field: fieldName, - model: getModelName(model), - schema: schema2, - options, - action - }); - return { - operator, - connector, - field: fieldName, - value: newValue - }; - }); - }; - const transformJoinClause = (baseModel, unsanitizedJoin, select2) => { - if (!unsanitizedJoin) return void 0; - if (Object.keys(unsanitizedJoin).length === 0) return void 0; - const transformedJoin = {}; - for (const [model, join4] of Object.entries(unsanitizedJoin)) { - if (!join4) continue; - const defaultModelName = getDefaultModelName(model); - const defaultBaseModelName = getDefaultModelName(baseModel); - let foreignKeys = Object.entries(schema2[defaultModelName].fields).filter(([field, fieldAttributes]) => fieldAttributes.references && getDefaultModelName(fieldAttributes.references.model) === defaultBaseModelName); - let isForwardJoin = true; - if (!foreignKeys.length) { - foreignKeys = Object.entries(schema2[defaultBaseModelName].fields).filter(([field, fieldAttributes]) => fieldAttributes.references && getDefaultModelName(fieldAttributes.references.model) === defaultModelName); - isForwardJoin = false; - } - if (!foreignKeys.length) throw new BetterAuthError(`No foreign key found for model ${model} and base model ${baseModel} while performing join operation.`); - else if (foreignKeys.length > 1) throw new BetterAuthError(`Multiple foreign keys found for model ${model} and base model ${baseModel} while performing join operation. Only one foreign key is supported.`); - const [foreignKey, foreignKeyAttributes] = foreignKeys[0]; - if (!foreignKeyAttributes.references) throw new BetterAuthError(`No references found for foreign key ${foreignKey} on model ${model} while performing join operation.`); - let from; - let to; - let requiredSelectField; - if (isForwardJoin) { - requiredSelectField = foreignKeyAttributes.references.field; - from = getFieldName({ - model: baseModel, - field: requiredSelectField - }); - to = getFieldName({ - model, - field: foreignKey - }); - } else { - requiredSelectField = foreignKey; - from = getFieldName({ - model: baseModel, - field: requiredSelectField - }); - to = getFieldName({ - model, - field: foreignKeyAttributes.references.field - }); - } - if (select2 && !select2.includes(requiredSelectField)) select2.push(requiredSelectField); - const isUnique = to === "id" ? true : foreignKeyAttributes.unique ?? false; - let limit = options.advanced?.database?.defaultFindManyLimit ?? 100; - if (isUnique) limit = 1; - else if (typeof join4 === "object" && typeof join4.limit === "number") limit = join4.limit; - transformedJoin[getModelName(model)] = { - on: { - from, - to - }, - limit, - relation: isUnique ? "one-to-one" : "one-to-many" - }; - } - return { - join: transformedJoin, - select: select2 - }; - }; - const handleFallbackJoin = async ({ baseModel, baseData, joinModel, specificJoinConfig: joinConfig }) => { - if (!baseData) return baseData; - const modelName = getModelName(joinModel); - const field = joinConfig.on.to; - const value = baseData[getDefaultFieldName({ - field: joinConfig.on.from, - model: baseModel - })]; - if (value === null || value === void 0) return joinConfig.relation === "one-to-one" ? null : []; - let result; - const where = transformWhereClause({ - model: modelName, - where: [{ - field, - value, - operator: "eq", - connector: "AND" - }], - action: "findOne" - }); - try { - if (joinConfig.relation === "one-to-one") result = await adapterInstance.findOne({ - model: modelName, - where - }); - else { - const limit = joinConfig.limit ?? options.advanced?.database?.defaultFindManyLimit ?? 100; - result = await adapterInstance.findMany({ - model: modelName, - where, - limit - }); - } - } catch (error50) { - logger4.error(`Failed to query fallback join for model ${modelName}:`, { - where, - limit: joinConfig.limit - }); - console.error(error50); - throw error50; - } - return result; - }; - const adapterInstance = customAdapter({ - options, - schema: schema2, - debugLog, - getFieldName, - getModelName, - getDefaultModelName, - getDefaultFieldName, - getFieldAttributes, - transformInput, - transformOutput, - transformWhereClause - }); - let lazyLoadTransaction = null; - const adapter = { - transaction: async (cb) => { - if (!lazyLoadTransaction) if (!config3.transaction) lazyLoadTransaction = createAsIsTransaction(adapter); - else { - logger4.debug(`[${config3.adapterName}] - Using provided transaction implementation.`); - lazyLoadTransaction = config3.transaction; - } - return lazyLoadTransaction(cb); - }, - create: async ({ data: unsafeData, model: unsafeModel, select: select2, forceAllowId = false }) => { - transactionId++; - const thisTransactionId = transactionId; - const model = getModelName(unsafeModel); - unsafeModel = getDefaultModelName(unsafeModel); - if ("id" in unsafeData && typeof unsafeData.id !== "undefined" && !forceAllowId) { - logger4.warn(`[${config3.adapterName}] - You are trying to create a record with an id. This is not allowed as we handle id generation for you, unless you pass in the \`forceAllowId\` parameter. The id will be ignored.`); - const stack = (/* @__PURE__ */ new Error()).stack?.split("\n").filter((_, i5) => i5 !== 1).join("\n").replace("Error:", "Create method with `id` being called at:"); - console.log(stack); - unsafeData.id = void 0; - } - debugLog({ method: "create" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 4)}`, `${formatMethod("create")} ${formatAction("Unsafe Input")}:`, { - model, - data: unsafeData - }); - let data2 = unsafeData; - if (!config3.disableTransformInput) data2 = await transformInput(unsafeData, unsafeModel, "create", forceAllowId); - debugLog({ method: "create" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 4)}`, `${formatMethod("create")} ${formatAction("Parsed Input")}:`, { - model, - data: data2 - }); - const res = await adapterInstance.create({ - data: data2, - model - }); - debugLog({ method: "create" }, `${formatTransactionId(thisTransactionId)} ${formatStep(3, 4)}`, `${formatMethod("create")} ${formatAction("DB Result")}:`, { - model, - res - }); - let transformed = res; - if (!config3.disableTransformOutput) transformed = await transformOutput(res, unsafeModel, select2, void 0); - debugLog({ method: "create" }, `${formatTransactionId(thisTransactionId)} ${formatStep(4, 4)}`, `${formatMethod("create")} ${formatAction("Parsed Result")}:`, { - model, - data: transformed - }); - return transformed; - }, - update: async ({ model: unsafeModel, where: unsafeWhere, update: unsafeData }) => { - transactionId++; - const thisTransactionId = transactionId; - unsafeModel = getDefaultModelName(unsafeModel); - const model = getModelName(unsafeModel); - const where = transformWhereClause({ - model: unsafeModel, - where: unsafeWhere, - action: "update" - }); - debugLog({ method: "update" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 4)}`, `${formatMethod("update")} ${formatAction("Unsafe Input")}:`, { - model, - data: unsafeData - }); - let data2 = unsafeData; - if (!config3.disableTransformInput) data2 = await transformInput(unsafeData, unsafeModel, "update"); - debugLog({ method: "update" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 4)}`, `${formatMethod("update")} ${formatAction("Parsed Input")}:`, { - model, - data: data2 - }); - const res = await adapterInstance.update({ - model, - where, - update: data2 - }); - debugLog({ method: "update" }, `${formatTransactionId(thisTransactionId)} ${formatStep(3, 4)}`, `${formatMethod("update")} ${formatAction("DB Result")}:`, { - model, - data: res - }); - let transformed = res; - if (!config3.disableTransformOutput) transformed = await transformOutput(res, unsafeModel, void 0, void 0); - debugLog({ method: "update" }, `${formatTransactionId(thisTransactionId)} ${formatStep(4, 4)}`, `${formatMethod("update")} ${formatAction("Parsed Result")}:`, { - model, - data: transformed - }); - return transformed; - }, - updateMany: async ({ model: unsafeModel, where: unsafeWhere, update: unsafeData }) => { - transactionId++; - const thisTransactionId = transactionId; - const model = getModelName(unsafeModel); - const where = transformWhereClause({ - model: unsafeModel, - where: unsafeWhere, - action: "updateMany" - }); - unsafeModel = getDefaultModelName(unsafeModel); - debugLog({ method: "updateMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 4)}`, `${formatMethod("updateMany")} ${formatAction("Unsafe Input")}:`, { - model, - data: unsafeData - }); - let data2 = unsafeData; - if (!config3.disableTransformInput) data2 = await transformInput(unsafeData, unsafeModel, "update"); - debugLog({ method: "updateMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 4)}`, `${formatMethod("updateMany")} ${formatAction("Parsed Input")}:`, { - model, - data: data2 - }); - const updatedCount = await adapterInstance.updateMany({ - model, - where, - update: data2 - }); - debugLog({ method: "updateMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(3, 4)}`, `${formatMethod("updateMany")} ${formatAction("DB Result")}:`, { - model, - data: updatedCount - }); - debugLog({ method: "updateMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(4, 4)}`, `${formatMethod("updateMany")} ${formatAction("Parsed Result")}:`, { - model, - data: updatedCount - }); - return updatedCount; - }, - findOne: async ({ model: unsafeModel, where: unsafeWhere, select: select2, join: unsafeJoin }) => { - transactionId++; - const thisTransactionId = transactionId; - const model = getModelName(unsafeModel); - const where = transformWhereClause({ - model: unsafeModel, - where: unsafeWhere, - action: "findOne" - }); - unsafeModel = getDefaultModelName(unsafeModel); - let join4; - let passJoinToAdapter = true; - if (!config3.disableTransformJoin) { - const result = transformJoinClause(unsafeModel, unsafeJoin, select2); - if (result) { - join4 = result.join; - select2 = result.select; - } - if (!options.experimental?.joins && join4 && Object.keys(join4).length > 0) passJoinToAdapter = false; - } else join4 = unsafeJoin; - debugLog({ method: "findOne" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 3)}`, `${formatMethod("findOne")}:`, { - model, - where, - select: select2, - join: join4 - }); - const res = await adapterInstance.findOne({ - model, - where, - select: select2, - join: passJoinToAdapter ? join4 : void 0 - }); - debugLog({ method: "findOne" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 3)}`, `${formatMethod("findOne")} ${formatAction("DB Result")}:`, { - model, - data: res - }); - let transformed = res; - if (!config3.disableTransformOutput) transformed = await transformOutput(res, unsafeModel, select2, join4); - debugLog({ method: "findOne" }, `${formatTransactionId(thisTransactionId)} ${formatStep(3, 3)}`, `${formatMethod("findOne")} ${formatAction("Parsed Result")}:`, { - model, - data: transformed - }); - return transformed; - }, - findMany: async ({ model: unsafeModel, where: unsafeWhere, limit: unsafeLimit, sortBy, offset, join: unsafeJoin }) => { - transactionId++; - const thisTransactionId = transactionId; - const limit = unsafeLimit ?? options.advanced?.database?.defaultFindManyLimit ?? 100; - const model = getModelName(unsafeModel); - const where = transformWhereClause({ - model: unsafeModel, - where: unsafeWhere, - action: "findMany" - }); - unsafeModel = getDefaultModelName(unsafeModel); - let join4; - let passJoinToAdapter = true; - if (!config3.disableTransformJoin) { - const result = transformJoinClause(unsafeModel, unsafeJoin, void 0); - if (result) join4 = result.join; - if (!options.experimental?.joins && join4 && Object.keys(join4).length > 0) passJoinToAdapter = false; - } else join4 = unsafeJoin; - debugLog({ method: "findMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 3)}`, `${formatMethod("findMany")}:`, { - model, - where, - limit, - sortBy, - offset, - join: join4 - }); - const res = await adapterInstance.findMany({ - model, - where, - limit, - sortBy, - offset, - join: passJoinToAdapter ? join4 : void 0 - }); - debugLog({ method: "findMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 3)}`, `${formatMethod("findMany")} ${formatAction("DB Result")}:`, { - model, - data: res - }); - let transformed = res; - if (!config3.disableTransformOutput) transformed = await Promise.all(res.map(async (r5) => { - return await transformOutput(r5, unsafeModel, void 0, join4); - })); - debugLog({ method: "findMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(3, 3)}`, `${formatMethod("findMany")} ${formatAction("Parsed Result")}:`, { - model, - data: transformed - }); - return transformed; - }, - delete: async ({ model: unsafeModel, where: unsafeWhere }) => { - transactionId++; - const thisTransactionId = transactionId; - const model = getModelName(unsafeModel); - const where = transformWhereClause({ - model: unsafeModel, - where: unsafeWhere, - action: "delete" - }); - unsafeModel = getDefaultModelName(unsafeModel); - debugLog({ method: "delete" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 2)}`, `${formatMethod("delete")}:`, { - model, - where - }); - await adapterInstance.delete({ - model, - where - }); - debugLog({ method: "delete" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 2)}`, `${formatMethod("delete")} ${formatAction("DB Result")}:`, { model }); - }, - deleteMany: async ({ model: unsafeModel, where: unsafeWhere }) => { - transactionId++; - const thisTransactionId = transactionId; - const model = getModelName(unsafeModel); - const where = transformWhereClause({ - model: unsafeModel, - where: unsafeWhere, - action: "deleteMany" - }); - unsafeModel = getDefaultModelName(unsafeModel); - debugLog({ method: "deleteMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 2)}`, `${formatMethod("deleteMany")} ${formatAction("DeleteMany")}:`, { - model, - where - }); - const res = await adapterInstance.deleteMany({ - model, - where - }); - debugLog({ method: "deleteMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 2)}`, `${formatMethod("deleteMany")} ${formatAction("DB Result")}:`, { - model, - data: res - }); - return res; - }, - count: async ({ model: unsafeModel, where: unsafeWhere }) => { - transactionId++; - const thisTransactionId = transactionId; - const model = getModelName(unsafeModel); - const where = transformWhereClause({ - model: unsafeModel, - where: unsafeWhere, - action: "count" - }); - unsafeModel = getDefaultModelName(unsafeModel); - debugLog({ method: "count" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 2)}`, `${formatMethod("count")}:`, { - model, - where - }); - const res = await adapterInstance.count({ - model, - where - }); - debugLog({ method: "count" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 2)}`, `${formatMethod("count")}:`, { - model, - data: res - }); - return res; - }, - createSchema: adapterInstance.createSchema ? async (_, file2) => { - const tables = getAuthTables(options); - if (options.secondaryStorage && !options.session?.storeSessionInDatabase) delete tables.session; - return adapterInstance.createSchema({ - file: file2, - tables - }); - } : void 0, - options: { - adapterConfig: config3, - ...adapterInstance.options ?? {} - }, - id: config3.adapterId, - ...config3.debugLogs?.isRunningAdapterTests ? { adapterTestDebugLogs: { - resetDebugLogs() { - debugLogs = debugLogs.filter((log2) => log2.instance !== uniqueAdapterFactoryInstanceId); - }, - printDebugLogs() { - const separator = `\u2500`.repeat(80); - const logs = debugLogs.filter((log$1) => log$1.instance === uniqueAdapterFactoryInstanceId); - if (logs.length === 0) return; - const log2 = logs.reverse().map((log$1) => { - log$1.args[0] = ` -${log$1.args[0]}`; - return [...log$1.args, "\n"]; - }).reduce((prev, curr) => { - return [...curr, ...prev]; - }, [` -${separator}`]); - console.log(...log2); - } - } } : {} - }; - return adapter; - }; - } -}); - -// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/db/adapter/index.mjs -var init_adapter = __esm({ - "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/db/adapter/index.mjs"() { - init_get_default_model_name(); - init_get_default_field_name(); - init_get_id_field(); - init_get_field_attributes(); - init_get_field_name(); - init_get_model_name(); - init_utils11(); - init_factory(); - } -}); - -// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/adapters/memory-adapter/memory-adapter.mjs -var memoryAdapter; -var init_memory_adapter = __esm({ - "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/adapters/memory-adapter/memory-adapter.mjs"() { - init_env(); - init_adapter(); - memoryAdapter = (db, config3) => { - let lazyOptions = null; - const adapterCreator = createAdapterFactory({ - config: { - adapterId: "memory", - adapterName: "Memory Adapter", - usePlural: false, - debugLogs: config3?.debugLogs || false, - supportsArrays: true, - customTransformInput(props) { - if ((props.options.advanced?.database?.useNumberId || props.options.advanced?.database?.generateId === "serial") && props.field === "id" && props.action === "create") return db[props.model].length + 1; - return props.data; - }, - transaction: async (cb) => { - const clone3 = structuredClone(db); - try { - return await cb(adapterCreator(lazyOptions)); - } catch (error50) { - Object.keys(db).forEach((key) => { - db[key] = clone3[key]; - }); - throw error50; - } - } - }, - adapter: ({ getFieldName, options, getModelName }) => { - const applySortToRecords = (records, sortBy, model) => { - if (!sortBy) return records; - return records.sort((a5, b6) => { - const field = getFieldName({ - model, - field: sortBy.field - }); - const aValue = a5[field]; - const bValue = b6[field]; - let comparison = 0; - if (aValue == null && bValue == null) comparison = 0; - else if (aValue == null) comparison = -1; - else if (bValue == null) comparison = 1; - else if (typeof aValue === "string" && typeof bValue === "string") comparison = aValue.localeCompare(bValue); - else if (aValue instanceof Date && bValue instanceof Date) comparison = aValue.getTime() - bValue.getTime(); - else if (typeof aValue === "number" && typeof bValue === "number") comparison = aValue - bValue; - else if (typeof aValue === "boolean" && typeof bValue === "boolean") comparison = aValue === bValue ? 0 : aValue ? 1 : -1; - else comparison = String(aValue).localeCompare(String(bValue)); - return sortBy.direction === "asc" ? comparison : -comparison; - }); - }; - function convertWhereClause(where, model, join4) { - const execute11 = (where$1, model$1) => { - const table = db[model$1]; - if (!table) { - logger3.error(`[MemoryAdapter] Model ${model$1} not found in the DB`, Object.keys(db)); - throw new Error(`Model ${model$1} not found`); - } - const evalClause = (record2, clause) => { - const { field, value, operator } = clause; - switch (operator) { - case "in": - if (!Array.isArray(value)) throw new Error("Value must be an array"); - return value.includes(record2[field]); - case "not_in": - if (!Array.isArray(value)) throw new Error("Value must be an array"); - return !value.includes(record2[field]); - case "contains": - return record2[field].includes(value); - case "starts_with": - return record2[field].startsWith(value); - case "ends_with": - return record2[field].endsWith(value); - case "ne": - return record2[field] !== value; - case "gt": - return value != null && Boolean(record2[field] > value); - case "gte": - return value != null && Boolean(record2[field] >= value); - case "lt": - return value != null && Boolean(record2[field] < value); - case "lte": - return value != null && Boolean(record2[field] <= value); - default: - return record2[field] === value; - } - }; - return table.filter((record2) => { - if (!where$1.length || where$1.length === 0) return true; - let result = evalClause(record2, where$1[0]); - for (const clause of where$1) { - const clauseResult = evalClause(record2, clause); - if (clause.connector === "OR") result = result || clauseResult; - else result = result && clauseResult; - } - return result; - }); - }; - if (!join4) return execute11(where, model); - const baseRecords = execute11(where, model); - const grouped = /* @__PURE__ */ new Map(); - const seenIds = /* @__PURE__ */ new Map(); - for (const baseRecord of baseRecords) { - const baseId = String(baseRecord.id); - if (!grouped.has(baseId)) { - const nested = { ...baseRecord }; - for (const [joinModel, joinAttr] of Object.entries(join4)) { - const joinModelName = getModelName(joinModel); - if (joinAttr.relation === "one-to-one") nested[joinModelName] = null; - else { - nested[joinModelName] = []; - seenIds.set(`${baseId}-${joinModel}`, /* @__PURE__ */ new Set()); - } - } - grouped.set(baseId, nested); - } - const nestedEntry = grouped.get(baseId); - for (const [joinModel, joinAttr] of Object.entries(join4)) { - const joinModelName = getModelName(joinModel); - const joinTable = db[joinModelName]; - if (!joinTable) { - logger3.error(`[MemoryAdapter] JoinOption model ${joinModelName} not found in the DB`, Object.keys(db)); - throw new Error(`JoinOption model ${joinModelName} not found`); - } - const matchingRecords = joinTable.filter((joinRecord) => joinRecord[joinAttr.on.to] === baseRecord[joinAttr.on.from]); - if (joinAttr.relation === "one-to-one") nestedEntry[joinModelName] = matchingRecords[0] || null; - else { - const seenSet = seenIds.get(`${baseId}-${joinModel}`); - const limit = joinAttr.limit ?? 100; - let count2 = 0; - for (const matchingRecord of matchingRecords) { - if (count2 >= limit) break; - if (!seenSet.has(matchingRecord.id)) { - nestedEntry[joinModelName].push(matchingRecord); - seenSet.add(matchingRecord.id); - count2++; - } - } - } - } - } - return Array.from(grouped.values()); - } - return { - create: async ({ model, data: data2 }) => { - if (options.advanced?.database?.useNumberId || options.advanced?.database?.generateId === "serial") data2.id = db[getModelName(model)].length + 1; - if (!db[model]) db[model] = []; - db[model].push(data2); - return data2; - }, - findOne: async ({ model, where, join: join4 }) => { - const res = convertWhereClause(where, model, join4); - if (join4) { - const resArray = res; - if (!resArray.length) return null; - return resArray[0]; - } - return res[0] || null; - }, - findMany: async ({ model, where, sortBy, limit, offset, join: join4 }) => { - const res = convertWhereClause(where || [], model, join4); - if (join4) { - const resArray = res; - if (!resArray.length) return []; - applySortToRecords(resArray, sortBy, model); - let paginatedRecords = resArray; - if (offset !== void 0) paginatedRecords = paginatedRecords.slice(offset); - if (limit !== void 0) paginatedRecords = paginatedRecords.slice(0, limit); - return paginatedRecords; - } - let table = applySortToRecords(res, sortBy, model); - if (offset !== void 0) table = table.slice(offset); - if (limit !== void 0) table = table.slice(0, limit); - return table || []; - }, - count: async ({ model, where }) => { - if (where) return convertWhereClause(where, model).length; - return db[model].length; - }, - update: async ({ model, where, update }) => { - const res = convertWhereClause(where, model); - res.forEach((record2) => { - Object.assign(record2, update); - }); - return res[0] || null; - }, - delete: async ({ model, where }) => { - const table = db[model]; - const res = convertWhereClause(where, model); - db[model] = table.filter((record2) => !res.includes(record2)); - }, - deleteMany: async ({ model, where }) => { - const table = db[model]; - const res = convertWhereClause(where, model); - let count2 = 0; - db[model] = table.filter((record2) => { - if (res.includes(record2)) { - count2++; - return false; - } - return !res.includes(record2); - }); - return count2; - }, - updateMany({ model, where, update }) { - const res = convertWhereClause(where, model); - res.forEach((record2) => { - Object.assign(record2, update); - }); - return res[0] || null; - } - }; - } - }); - return (options) => { - lazyOptions = options; - return adapterCreator(options); - }; - }; - } -}); - -// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/adapters/memory-adapter/index.mjs -var memory_adapter_exports = {}; -__export(memory_adapter_exports, { - memoryAdapter: () => memoryAdapter -}); -var init_memory_adapter2 = __esm({ - "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/adapters/memory-adapter/index.mjs"() { - init_memory_adapter(); - } -}); - -// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/db/adapter-base.mjs -async function getBaseAdapter(options, handleDirectDatabase) { - let adapter; - if (!options.database) { - const tables = getAuthTables(options); - const memoryDB = Object.keys(tables).reduce((acc, key) => { - acc[key] = []; - return acc; - }, {}); - const { memoryAdapter: memoryAdapter2 } = await Promise.resolve().then(() => (init_memory_adapter2(), memory_adapter_exports)); - adapter = memoryAdapter2(memoryDB)(options); - } else if (typeof options.database === "function") adapter = options.database(options); - else adapter = await handleDirectDatabase(options); - if (!adapter.transaction) { - logger3.warn("Adapter does not correctly implement transaction function, patching it automatically. Please update your adapter implementation."); - adapter.transaction = async (cb) => { - return cb(adapter); - }; - } - return adapter; -} -var init_adapter_base = __esm({ - "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/db/adapter-base.mjs"() { - init_db3(); - init_env(); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/object-utils.js -function isUndefined(obj) { - return typeof obj === "undefined" || obj === void 0; -} -function isString(obj) { - return typeof obj === "string"; -} -function isNumber(obj) { - return typeof obj === "number"; -} -function isBoolean(obj) { - return typeof obj === "boolean"; -} -function isNull2(obj) { - return obj === null; -} -function isDate(obj) { - return obj instanceof Date; -} -function isBigInt(obj) { - return typeof obj === "bigint"; -} -function isBuffer(obj) { - return typeof Buffer !== "undefined" && Buffer.isBuffer(obj); -} -function isFunction(obj) { - return typeof obj === "function"; -} -function isObject3(obj) { - return typeof obj === "object" && obj !== null; -} -function freeze2(obj) { - return Object.freeze(obj); -} -function asArray(arg) { - if (isReadonlyArray(arg)) { - return arg; - } else { - return [arg]; - } -} -function isReadonlyArray(arg) { - return Array.isArray(arg); -} -function noop3(obj) { - return obj; -} -var init_object_utils = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/object-utils.js"() { - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/alter-table-node.js -var AlterTableNode; -var init_alter_table_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/alter-table-node.js"() { - init_object_utils(); - AlterTableNode = freeze2({ - is(node) { - return node.kind === "AlterTableNode"; - }, - create(table) { - return freeze2({ - kind: "AlterTableNode", - table - }); - }, - cloneWithTableProps(node, props) { - return freeze2({ - ...node, - ...props - }); - }, - cloneWithColumnAlteration(node, columnAlteration) { - return freeze2({ - ...node, - columnAlterations: node.columnAlterations ? [...node.columnAlterations, columnAlteration] : [columnAlteration] - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/identifier-node.js -var IdentifierNode; -var init_identifier_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/identifier-node.js"() { - init_object_utils(); - IdentifierNode = freeze2({ - is(node) { - return node.kind === "IdentifierNode"; - }, - create(name) { - return freeze2({ - kind: "IdentifierNode", - name - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/create-index-node.js -var CreateIndexNode; -var init_create_index_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/create-index-node.js"() { - init_object_utils(); - init_identifier_node(); - CreateIndexNode = freeze2({ - is(node) { - return node.kind === "CreateIndexNode"; - }, - create(name) { - return freeze2({ - kind: "CreateIndexNode", - name: IdentifierNode.create(name) - }); - }, - cloneWith(node, props) { - return freeze2({ - ...node, - ...props - }); - }, - cloneWithColumns(node, columns) { - return freeze2({ - ...node, - columns: [...node.columns || [], ...columns] - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/create-schema-node.js -var CreateSchemaNode; -var init_create_schema_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/create-schema-node.js"() { - init_object_utils(); - init_identifier_node(); - CreateSchemaNode = freeze2({ - is(node) { - return node.kind === "CreateSchemaNode"; - }, - create(schema2, params) { - return freeze2({ - kind: "CreateSchemaNode", - schema: IdentifierNode.create(schema2), - ...params - }); - }, - cloneWith(createSchema, params) { - return freeze2({ - ...createSchema, - ...params - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/create-table-node.js -var ON_COMMIT_ACTIONS, CreateTableNode; -var init_create_table_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/create-table-node.js"() { - init_object_utils(); - ON_COMMIT_ACTIONS = ["preserve rows", "delete rows", "drop"]; - CreateTableNode = freeze2({ - is(node) { - return node.kind === "CreateTableNode"; - }, - create(table) { - return freeze2({ - kind: "CreateTableNode", - table, - columns: freeze2([]) - }); - }, - cloneWithColumn(createTable, column) { - return freeze2({ - ...createTable, - columns: freeze2([...createTable.columns, column]) - }); - }, - cloneWithConstraint(createTable, constraint) { - return freeze2({ - ...createTable, - constraints: createTable.constraints ? freeze2([...createTable.constraints, constraint]) : freeze2([constraint]) - }); - }, - cloneWithFrontModifier(createTable, modifier) { - return freeze2({ - ...createTable, - frontModifiers: createTable.frontModifiers ? freeze2([...createTable.frontModifiers, modifier]) : freeze2([modifier]) - }); - }, - cloneWithEndModifier(createTable, modifier) { - return freeze2({ - ...createTable, - endModifiers: createTable.endModifiers ? freeze2([...createTable.endModifiers, modifier]) : freeze2([modifier]) - }); - }, - cloneWith(createTable, params) { - return freeze2({ - ...createTable, - ...params - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/schemable-identifier-node.js -var SchemableIdentifierNode; -var init_schemable_identifier_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/schemable-identifier-node.js"() { - init_object_utils(); - init_identifier_node(); - SchemableIdentifierNode = freeze2({ - is(node) { - return node.kind === "SchemableIdentifierNode"; - }, - create(identifier) { - return freeze2({ - kind: "SchemableIdentifierNode", - identifier: IdentifierNode.create(identifier) - }); - }, - createWithSchema(schema2, identifier) { - return freeze2({ - kind: "SchemableIdentifierNode", - schema: IdentifierNode.create(schema2), - identifier: IdentifierNode.create(identifier) - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/drop-index-node.js -var DropIndexNode; -var init_drop_index_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/drop-index-node.js"() { - init_object_utils(); - init_schemable_identifier_node(); - DropIndexNode = freeze2({ - is(node) { - return node.kind === "DropIndexNode"; - }, - create(name, params) { - return freeze2({ - kind: "DropIndexNode", - name: SchemableIdentifierNode.create(name), - ...params - }); - }, - cloneWith(dropIndex, props) { - return freeze2({ - ...dropIndex, - ...props - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/drop-schema-node.js -var DropSchemaNode; -var init_drop_schema_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/drop-schema-node.js"() { - init_object_utils(); - init_identifier_node(); - DropSchemaNode = freeze2({ - is(node) { - return node.kind === "DropSchemaNode"; - }, - create(schema2, params) { - return freeze2({ - kind: "DropSchemaNode", - schema: IdentifierNode.create(schema2), - ...params - }); - }, - cloneWith(dropSchema, params) { - return freeze2({ - ...dropSchema, - ...params - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/drop-table-node.js -var DropTableNode; -var init_drop_table_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/drop-table-node.js"() { - init_object_utils(); - DropTableNode = freeze2({ - is(node) { - return node.kind === "DropTableNode"; - }, - create(table, params) { - return freeze2({ - kind: "DropTableNode", - table, - ...params - }); - }, - cloneWith(dropIndex, params) { - return freeze2({ - ...dropIndex, - ...params - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/alias-node.js -var AliasNode; -var init_alias_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/alias-node.js"() { - init_object_utils(); - AliasNode = freeze2({ - is(node) { - return node.kind === "AliasNode"; - }, - create(node, alias) { - return freeze2({ - kind: "AliasNode", - node, - alias - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/table-node.js -var TableNode; -var init_table_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/table-node.js"() { - init_object_utils(); - init_schemable_identifier_node(); - TableNode = freeze2({ - is(node) { - return node.kind === "TableNode"; - }, - create(table) { - return freeze2({ - kind: "TableNode", - table: SchemableIdentifierNode.create(table) - }); - }, - createWithSchema(schema2, table) { - return freeze2({ - kind: "TableNode", - table: SchemableIdentifierNode.createWithSchema(schema2, table) - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/operation-node-source.js -function isOperationNodeSource(obj) { - return isObject3(obj) && isFunction(obj.toOperationNode); -} -var init_operation_node_source = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/operation-node-source.js"() { - init_object_utils(); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/expression/expression.js -function isExpression(obj) { - return isObject3(obj) && "expressionType" in obj && isOperationNodeSource(obj); -} -function isAliasedExpression(obj) { - return isObject3(obj) && "expression" in obj && isString(obj.alias) && isOperationNodeSource(obj); -} -var init_expression = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/expression/expression.js"() { - init_operation_node_source(); - init_object_utils(); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/select-modifier-node.js -var SelectModifierNode; -var init_select_modifier_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/select-modifier-node.js"() { - init_object_utils(); - SelectModifierNode = freeze2({ - is(node) { - return node.kind === "SelectModifierNode"; - }, - create(modifier, of) { - return freeze2({ - kind: "SelectModifierNode", - modifier, - of - }); - }, - createWithExpression(modifier) { - return freeze2({ - kind: "SelectModifierNode", - rawModifier: modifier - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/and-node.js -var AndNode; -var init_and_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/and-node.js"() { - init_object_utils(); - AndNode = freeze2({ - is(node) { - return node.kind === "AndNode"; - }, - create(left, right) { - return freeze2({ - kind: "AndNode", - left, - right - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/or-node.js -var OrNode; -var init_or_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/or-node.js"() { - init_object_utils(); - OrNode = freeze2({ - is(node) { - return node.kind === "OrNode"; - }, - create(left, right) { - return freeze2({ - kind: "OrNode", - left, - right - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/on-node.js -var OnNode; -var init_on_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/on-node.js"() { - init_object_utils(); - init_and_node(); - init_or_node(); - OnNode = freeze2({ - is(node) { - return node.kind === "OnNode"; - }, - create(filter) { - return freeze2({ - kind: "OnNode", - on: filter - }); - }, - cloneWithOperation(onNode, operator, operation2) { - return freeze2({ - ...onNode, - on: operator === "And" ? AndNode.create(onNode.on, operation2) : OrNode.create(onNode.on, operation2) - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/join-node.js -var JoinNode; -var init_join_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/join-node.js"() { - init_object_utils(); - init_on_node(); - JoinNode = freeze2({ - is(node) { - return node.kind === "JoinNode"; - }, - create(joinType, table) { - return freeze2({ - kind: "JoinNode", - joinType, - table, - on: void 0 - }); - }, - createWithOn(joinType, table, on) { - return freeze2({ - kind: "JoinNode", - joinType, - table, - on: OnNode.create(on) - }); - }, - cloneWithOn(joinNode, operation2) { - return freeze2({ - ...joinNode, - on: joinNode.on ? OnNode.cloneWithOperation(joinNode.on, "And", operation2) : OnNode.create(operation2) - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/binary-operation-node.js -var BinaryOperationNode; -var init_binary_operation_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/binary-operation-node.js"() { - init_object_utils(); - BinaryOperationNode = freeze2({ - is(node) { - return node.kind === "BinaryOperationNode"; - }, - create(leftOperand, operator, rightOperand) { - return freeze2({ - kind: "BinaryOperationNode", - leftOperand, - operator, - rightOperand - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/operator-node.js -function isJSONOperator(op2) { - return isString(op2) && JSON_OPERATORS.includes(op2); -} -var COMPARISON_OPERATORS, ARITHMETIC_OPERATORS, JSON_OPERATORS, BINARY_OPERATORS, UNARY_FILTER_OPERATORS, UNARY_OPERATORS, OPERATORS, OperatorNode; -var init_operator_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/operator-node.js"() { - init_object_utils(); - COMPARISON_OPERATORS = [ - "=", - "==", - "!=", - "<>", - ">", - ">=", - "<", - "<=", - "in", - "not in", - "is", - "is not", - "like", - "not like", - "match", - "ilike", - "not ilike", - "@>", - "<@", - "^@", - "&&", - "?", - "?&", - "?|", - "!<", - "!>", - "<=>", - "!~", - "~", - "~*", - "!~*", - "@@", - "@@@", - "!!", - "<->", - "regexp", - "is distinct from", - "is not distinct from" - ]; - ARITHMETIC_OPERATORS = [ - "+", - "-", - "*", - "/", - "%", - "^", - "&", - "|", - "#", - "<<", - ">>" - ]; - JSON_OPERATORS = ["->", "->>"]; - BINARY_OPERATORS = [ - ...COMPARISON_OPERATORS, - ...ARITHMETIC_OPERATORS, - "&&", - "||" - ]; - UNARY_FILTER_OPERATORS = ["exists", "not exists"]; - UNARY_OPERATORS = ["not", "-", ...UNARY_FILTER_OPERATORS]; - OPERATORS = [ - ...BINARY_OPERATORS, - ...JSON_OPERATORS, - ...UNARY_OPERATORS, - "between", - "between symmetric" - ]; - OperatorNode = freeze2({ - is(node) { - return node.kind === "OperatorNode"; - }, - create(operator) { - return freeze2({ - kind: "OperatorNode", - operator - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/column-node.js -var ColumnNode; -var init_column_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/column-node.js"() { - init_object_utils(); - init_identifier_node(); - ColumnNode = freeze2({ - is(node) { - return node.kind === "ColumnNode"; - }, - create(column) { - return freeze2({ - kind: "ColumnNode", - column: IdentifierNode.create(column) - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/select-all-node.js -var SelectAllNode; -var init_select_all_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/select-all-node.js"() { - init_object_utils(); - SelectAllNode = freeze2({ - is(node) { - return node.kind === "SelectAllNode"; - }, - create() { - return freeze2({ - kind: "SelectAllNode" - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/reference-node.js -var ReferenceNode; -var init_reference_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/reference-node.js"() { - init_select_all_node(); - init_object_utils(); - ReferenceNode = freeze2({ - is(node) { - return node.kind === "ReferenceNode"; - }, - create(column, table) { - return freeze2({ - kind: "ReferenceNode", - table, - column - }); - }, - createSelectAll(table) { - return freeze2({ - kind: "ReferenceNode", - table, - column: SelectAllNode.create() - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dynamic/dynamic-reference-builder.js -function isDynamicReferenceBuilder(obj) { - return isObject3(obj) && isOperationNodeSource(obj) && isString(obj.dynamicReference); -} -var DynamicReferenceBuilder; -var init_dynamic_reference_builder = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dynamic/dynamic-reference-builder.js"() { - init_operation_node_source(); - init_reference_parser(); - init_object_utils(); - DynamicReferenceBuilder = class { - #dynamicReference; - get dynamicReference() { - return this.#dynamicReference; - } - /** - * @private - * - * This needs to be here just so that the typings work. Without this - * the generated .d.ts file contains no reference to the type param R - * which causes this type to be equal to DynamicReferenceBuilder with - * any R. - */ - get refType() { - return void 0; - } - constructor(reference) { - this.#dynamicReference = reference; - } - toOperationNode() { - return parseSimpleReferenceExpression(this.#dynamicReference); - } - }; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/order-by-item-node.js -var OrderByItemNode; -var init_order_by_item_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/order-by-item-node.js"() { - init_object_utils(); - OrderByItemNode = freeze2({ - is(node) { - return node.kind === "OrderByItemNode"; - }, - create(orderBy, direction) { - return freeze2({ - kind: "OrderByItemNode", - orderBy, - direction - }); - }, - cloneWith(node, props) { - return freeze2({ - ...node, - ...props - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/raw-node.js -var RawNode; -var init_raw_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/raw-node.js"() { - init_object_utils(); - RawNode = freeze2({ - is(node) { - return node.kind === "RawNode"; - }, - create(sqlFragments, parameters) { - return freeze2({ - kind: "RawNode", - sqlFragments: freeze2(sqlFragments), - parameters: freeze2(parameters) - }); - }, - createWithSql(sql3) { - return RawNode.create([sql3], []); - }, - createWithChild(child) { - return RawNode.create(["", ""], [child]); - }, - createWithChildren(children) { - return RawNode.create(new Array(children.length + 1).fill(""), children); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/collate-node.js -var CollateNode; -var init_collate_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/collate-node.js"() { - init_object_utils(); - init_identifier_node(); - CollateNode = freeze2({ - is(node) { - return node.kind === "CollateNode"; - }, - create(collation) { - return freeze2({ - kind: "CollateNode", - collation: IdentifierNode.create(collation) - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/order-by-item-builder.js -var OrderByItemBuilder; -var init_order_by_item_builder = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/order-by-item-builder.js"() { - init_collate_node(); - init_order_by_item_node(); - init_raw_node(); - init_object_utils(); - OrderByItemBuilder = class _OrderByItemBuilder { - #props; - constructor(props) { - this.#props = freeze2(props); - } - /** - * Adds `desc` to the `order by` item. - * - * See {@link asc} for the opposite. - */ - desc() { - return new _OrderByItemBuilder({ - node: OrderByItemNode.cloneWith(this.#props.node, { - direction: RawNode.createWithSql("desc") - }) - }); - } - /** - * Adds `asc` to the `order by` item. - * - * See {@link desc} for the opposite. - */ - asc() { - return new _OrderByItemBuilder({ - node: OrderByItemNode.cloneWith(this.#props.node, { - direction: RawNode.createWithSql("asc") - }) - }); - } - /** - * Adds `nulls last` to the `order by` item. - * - * This is only supported by some dialects like PostgreSQL and SQLite. - * - * See {@link nullsFirst} for the opposite. - */ - nullsLast() { - return new _OrderByItemBuilder({ - node: OrderByItemNode.cloneWith(this.#props.node, { nulls: "last" }) - }); - } - /** - * Adds `nulls first` to the `order by` item. - * - * This is only supported by some dialects like PostgreSQL and SQLite. - * - * See {@link nullsLast} for the opposite. - */ - nullsFirst() { - return new _OrderByItemBuilder({ - node: OrderByItemNode.cloneWith(this.#props.node, { nulls: "first" }) - }); - } - /** - * Adds `collate ` to the `order by` item. - */ - collate(collation) { - return new _OrderByItemBuilder({ - node: OrderByItemNode.cloneWith(this.#props.node, { - collation: CollateNode.create(collation) - }) - }); - } - toOperationNode() { - return this.#props.node; - } - }; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/log-once.js -function logOnce(message2) { - if (LOGGED_MESSAGES.has(message2)) { - return; - } - LOGGED_MESSAGES.add(message2); - console.log(message2); -} -var LOGGED_MESSAGES; -var init_log_once = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/log-once.js"() { - LOGGED_MESSAGES = /* @__PURE__ */ new Set(); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/order-by-parser.js -function isOrderByDirection(thing) { - return thing === "asc" || thing === "desc"; -} -function parseOrderBy(args) { - if (args.length === 2) { - return [parseOrderByItem(args[0], args[1])]; - } - if (args.length === 1) { - const [orderBy] = args; - if (Array.isArray(orderBy)) { - logOnce("orderBy(array) is deprecated, use multiple orderBy calls instead."); - return orderBy.map((item) => parseOrderByItem(item)); - } - return [parseOrderByItem(orderBy)]; - } - throw new Error(`Invalid number of arguments at order by! expected 1-2, received ${args.length}`); -} -function parseOrderByItem(expr, modifiers) { - const parsedRef = parseOrderByExpression(expr); - if (OrderByItemNode.is(parsedRef)) { - if (modifiers) { - throw new Error("Cannot specify direction twice!"); - } - return parsedRef; - } - return parseOrderByWithModifiers(parsedRef, modifiers); -} -function parseOrderByExpression(expr) { - if (isExpressionOrFactory(expr)) { - return parseExpression(expr); - } - if (isDynamicReferenceBuilder(expr)) { - return expr.toOperationNode(); - } - const [ref, direction] = expr.split(" "); - if (direction) { - logOnce("`orderBy('column asc')` is deprecated. Use `orderBy('column', 'asc')` instead."); - return parseOrderByWithModifiers(parseStringReference(ref), direction); - } - return parseStringReference(expr); -} -function parseOrderByWithModifiers(expr, modifiers) { - if (typeof modifiers === "string") { - if (!isOrderByDirection(modifiers)) { - throw new Error(`Invalid order by direction: ${modifiers}`); - } - return OrderByItemNode.create(expr, RawNode.createWithSql(modifiers)); - } - if (isExpression(modifiers)) { - logOnce("`orderBy(..., expr)` is deprecated. Use `orderBy(..., 'asc')` or `orderBy(..., (ob) => ...)` instead."); - return OrderByItemNode.create(expr, modifiers.toOperationNode()); - } - const node = OrderByItemNode.create(expr); - if (!modifiers) { - return node; - } - return modifiers(new OrderByItemBuilder({ node })).toOperationNode(); -} -var init_order_by_parser = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/order-by-parser.js"() { - init_dynamic_reference_builder(); - init_expression(); - init_order_by_item_node(); - init_raw_node(); - init_order_by_item_builder(); - init_log_once(); - init_expression_parser(); - init_reference_parser(); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/json-reference-node.js -var JSONReferenceNode; -var init_json_reference_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/json-reference-node.js"() { - init_object_utils(); - JSONReferenceNode = freeze2({ - is(node) { - return node.kind === "JSONReferenceNode"; - }, - create(reference, traversal) { - return freeze2({ - kind: "JSONReferenceNode", - reference, - traversal - }); - }, - cloneWithTraversal(node, traversal) { - return freeze2({ - ...node, - traversal - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/json-operator-chain-node.js -var JSONOperatorChainNode; -var init_json_operator_chain_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/json-operator-chain-node.js"() { - init_object_utils(); - JSONOperatorChainNode = freeze2({ - is(node) { - return node.kind === "JSONOperatorChainNode"; - }, - create(operator) { - return freeze2({ - kind: "JSONOperatorChainNode", - operator, - values: freeze2([]) - }); - }, - cloneWithValue(node, value) { - return freeze2({ - ...node, - values: freeze2([...node.values, value]) - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/json-path-node.js -var JSONPathNode; -var init_json_path_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/json-path-node.js"() { - init_object_utils(); - JSONPathNode = freeze2({ - is(node) { - return node.kind === "JSONPathNode"; - }, - create(inOperator) { - return freeze2({ - kind: "JSONPathNode", - inOperator, - pathLegs: freeze2([]) - }); - }, - cloneWithLeg(jsonPathNode, pathLeg) { - return freeze2({ - ...jsonPathNode, - pathLegs: freeze2([...jsonPathNode.pathLegs, pathLeg]) - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/reference-parser.js -function parseSimpleReferenceExpression(exp) { - if (isString(exp)) { - return parseStringReference(exp); - } - return exp.toOperationNode(); -} -function parseReferenceExpressionOrList(arg) { - if (isReadonlyArray(arg)) { - return arg.map((it) => parseReferenceExpression(it)); - } else { - return [parseReferenceExpression(arg)]; - } -} -function parseReferenceExpression(exp) { - if (isExpressionOrFactory(exp)) { - return parseExpression(exp); - } - return parseSimpleReferenceExpression(exp); -} -function parseJSONReference(ref, op2) { - const referenceNode = parseStringReference(ref); - if (isJSONOperator(op2)) { - return JSONReferenceNode.create(referenceNode, JSONOperatorChainNode.create(OperatorNode.create(op2))); - } - const opWithoutLastChar = op2.slice(0, -1); - if (isJSONOperator(opWithoutLastChar)) { - return JSONReferenceNode.create(referenceNode, JSONPathNode.create(OperatorNode.create(opWithoutLastChar))); - } - throw new Error(`Invalid JSON operator: ${op2}`); -} -function parseStringReference(ref) { - const COLUMN_SEPARATOR = "."; - if (!ref.includes(COLUMN_SEPARATOR)) { - return ReferenceNode.create(ColumnNode.create(ref)); - } - const parts = ref.split(COLUMN_SEPARATOR).map(trim); - if (parts.length === 3) { - return parseStringReferenceWithTableAndSchema(parts); - } - if (parts.length === 2) { - return parseStringReferenceWithTable(parts); - } - throw new Error(`invalid column reference ${ref}`); -} -function parseAliasedStringReference(ref) { - const ALIAS_SEPARATOR = " as "; - if (ref.includes(ALIAS_SEPARATOR)) { - const [columnRef, alias] = ref.split(ALIAS_SEPARATOR).map(trim); - return AliasNode.create(parseStringReference(columnRef), IdentifierNode.create(alias)); - } else { - return parseStringReference(ref); - } -} -function parseColumnName(column) { - return ColumnNode.create(column); -} -function parseOrderedColumnName(column) { - const ORDER_SEPARATOR = " "; - if (column.includes(ORDER_SEPARATOR)) { - const [columnName, order] = column.split(ORDER_SEPARATOR).map(trim); - if (!isOrderByDirection(order)) { - throw new Error(`invalid order direction "${order}" next to "${columnName}"`); - } - return parseOrderBy([columnName, order])[0]; - } else { - return parseColumnName(column); - } -} -function parseStringReferenceWithTableAndSchema(parts) { - const [schema2, table, column] = parts; - return ReferenceNode.create(ColumnNode.create(column), TableNode.createWithSchema(schema2, table)); -} -function parseStringReferenceWithTable(parts) { - const [table, column] = parts; - return ReferenceNode.create(ColumnNode.create(column), TableNode.create(table)); -} -function trim(str) { - return str.trim(); -} -var init_reference_parser = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/reference-parser.js"() { - init_alias_node(); - init_column_node(); - init_reference_node(); - init_table_node(); - init_object_utils(); - init_expression_parser(); - init_identifier_node(); - init_order_by_parser(); - init_operator_node(); - init_json_reference_node(); - init_json_operator_chain_node(); - init_json_path_node(); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/primitive-value-list-node.js -var PrimitiveValueListNode; -var init_primitive_value_list_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/primitive-value-list-node.js"() { - init_object_utils(); - PrimitiveValueListNode = freeze2({ - is(node) { - return node.kind === "PrimitiveValueListNode"; - }, - create(values2) { - return freeze2({ - kind: "PrimitiveValueListNode", - values: freeze2([...values2]) - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/value-list-node.js -var ValueListNode; -var init_value_list_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/value-list-node.js"() { - init_object_utils(); - ValueListNode = freeze2({ - is(node) { - return node.kind === "ValueListNode"; - }, - create(values2) { - return freeze2({ - kind: "ValueListNode", - values: freeze2(values2) - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/value-node.js -var ValueNode; -var init_value_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/value-node.js"() { - init_object_utils(); - ValueNode = freeze2({ - is(node) { - return node.kind === "ValueNode"; - }, - create(value) { - return freeze2({ - kind: "ValueNode", - value - }); - }, - createImmediate(value) { - return freeze2({ - kind: "ValueNode", - value, - immediate: true - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/value-parser.js -function parseValueExpressionOrList(arg) { - if (isReadonlyArray(arg)) { - return parseValueExpressionList(arg); - } - return parseValueExpression(arg); -} -function parseValueExpression(exp) { - if (isExpressionOrFactory(exp)) { - return parseExpression(exp); - } - return ValueNode.create(exp); -} -function isSafeImmediateValue(value) { - return isNumber(value) || isBoolean(value) || isNull2(value); -} -function parseSafeImmediateValue(value) { - if (!isSafeImmediateValue(value)) { - throw new Error(`unsafe immediate value ${JSON.stringify(value)}`); - } - return ValueNode.createImmediate(value); -} -function parseValueExpressionList(arg) { - if (arg.some(isExpressionOrFactory)) { - return ValueListNode.create(arg.map((it) => parseValueExpression(it))); - } - return PrimitiveValueListNode.create(arg); -} -var init_value_parser = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/value-parser.js"() { - init_primitive_value_list_node(); - init_value_list_node(); - init_value_node(); - init_object_utils(); - init_expression_parser(); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/parens-node.js -var ParensNode; -var init_parens_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/parens-node.js"() { - init_object_utils(); - ParensNode = freeze2({ - is(node) { - return node.kind === "ParensNode"; - }, - create(node) { - return freeze2({ - kind: "ParensNode", - node - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/binary-operation-parser.js -function parseValueBinaryOperationOrExpression(args) { - if (args.length === 3) { - return parseValueBinaryOperation(args[0], args[1], args[2]); - } else if (args.length === 1) { - return parseValueExpression(args[0]); - } - throw new Error(`invalid arguments: ${JSON.stringify(args)}`); -} -function parseValueBinaryOperation(left, operator, right) { - if (isIsOperator(operator) && needsIsOperator(right)) { - return BinaryOperationNode.create(parseReferenceExpression(left), parseOperator(operator), ValueNode.createImmediate(right)); - } - return BinaryOperationNode.create(parseReferenceExpression(left), parseOperator(operator), parseValueExpressionOrList(right)); -} -function parseReferentialBinaryOperation(left, operator, right) { - return BinaryOperationNode.create(parseReferenceExpression(left), parseOperator(operator), parseReferenceExpression(right)); -} -function parseFilterObject(obj, combinator) { - return parseFilterList(Object.entries(obj).filter(([, v5]) => !isUndefined(v5)).map(([k5, v5]) => parseValueBinaryOperation(k5, needsIsOperator(v5) ? "is" : "=", v5)), combinator); -} -function parseFilterList(list2, combinator, withParens = true) { - const combine = combinator === "and" ? AndNode.create : OrNode.create; - if (list2.length === 0) { - return BinaryOperationNode.create(ValueNode.createImmediate(1), OperatorNode.create("="), ValueNode.createImmediate(combinator === "and" ? 1 : 0)); - } - let node = toOperationNode(list2[0]); - for (let i5 = 1; i5 < list2.length; ++i5) { - node = combine(node, toOperationNode(list2[i5])); - } - if (list2.length > 1 && withParens) { - return ParensNode.create(node); - } - return node; -} -function isIsOperator(operator) { - return operator === "is" || operator === "is not"; -} -function needsIsOperator(value) { - return isNull2(value) || isBoolean(value); -} -function parseOperator(operator) { - if (isString(operator) && OPERATORS.includes(operator)) { - return OperatorNode.create(operator); - } - if (isOperationNodeSource(operator)) { - return operator.toOperationNode(); - } - throw new Error(`invalid operator ${JSON.stringify(operator)}`); -} -function toOperationNode(nodeOrSource) { - return isOperationNodeSource(nodeOrSource) ? nodeOrSource.toOperationNode() : nodeOrSource; -} -var init_binary_operation_parser = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/binary-operation-parser.js"() { - init_binary_operation_node(); - init_object_utils(); - init_operation_node_source(); - init_operator_node(); - init_reference_parser(); - init_value_parser(); - init_value_node(); - init_and_node(); - init_parens_node(); - init_or_node(); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/order-by-node.js -var OrderByNode; -var init_order_by_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/order-by-node.js"() { - init_object_utils(); - OrderByNode = freeze2({ - is(node) { - return node.kind === "OrderByNode"; - }, - create(items) { - return freeze2({ - kind: "OrderByNode", - items: freeze2([...items]) - }); - }, - cloneWithItems(orderBy, items) { - return freeze2({ - ...orderBy, - items: freeze2([...orderBy.items, ...items]) - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/partition-by-node.js -var PartitionByNode; -var init_partition_by_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/partition-by-node.js"() { - init_object_utils(); - PartitionByNode = freeze2({ - is(node) { - return node.kind === "PartitionByNode"; - }, - create(items) { - return freeze2({ - kind: "PartitionByNode", - items: freeze2(items) - }); - }, - cloneWithItems(partitionBy, items) { - return freeze2({ - ...partitionBy, - items: freeze2([...partitionBy.items, ...items]) - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/over-node.js -var OverNode; -var init_over_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/over-node.js"() { - init_object_utils(); - init_order_by_node(); - init_partition_by_node(); - OverNode = freeze2({ - is(node) { - return node.kind === "OverNode"; - }, - create() { - return freeze2({ - kind: "OverNode" - }); - }, - cloneWithOrderByItems(overNode, items) { - return freeze2({ - ...overNode, - orderBy: overNode.orderBy ? OrderByNode.cloneWithItems(overNode.orderBy, items) : OrderByNode.create(items) - }); - }, - cloneWithPartitionByItems(overNode, items) { - return freeze2({ - ...overNode, - partitionBy: overNode.partitionBy ? PartitionByNode.cloneWithItems(overNode.partitionBy, items) : PartitionByNode.create(items) - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/from-node.js -var FromNode; -var init_from_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/from-node.js"() { - init_object_utils(); - FromNode = freeze2({ - is(node) { - return node.kind === "FromNode"; - }, - create(froms) { - return freeze2({ - kind: "FromNode", - froms: freeze2(froms) - }); - }, - cloneWithFroms(from, froms) { - return freeze2({ - ...from, - froms: freeze2([...from.froms, ...froms]) - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/group-by-node.js -var GroupByNode; -var init_group_by_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/group-by-node.js"() { - init_object_utils(); - GroupByNode = freeze2({ - is(node) { - return node.kind === "GroupByNode"; - }, - create(items) { - return freeze2({ - kind: "GroupByNode", - items: freeze2(items) - }); - }, - cloneWithItems(groupBy, items) { - return freeze2({ - ...groupBy, - items: freeze2([...groupBy.items, ...items]) - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/having-node.js -var HavingNode; -var init_having_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/having-node.js"() { - init_object_utils(); - init_and_node(); - init_or_node(); - HavingNode = freeze2({ - is(node) { - return node.kind === "HavingNode"; - }, - create(filter) { - return freeze2({ - kind: "HavingNode", - having: filter - }); - }, - cloneWithOperation(havingNode, operator, operation2) { - return freeze2({ - ...havingNode, - having: operator === "And" ? AndNode.create(havingNode.having, operation2) : OrNode.create(havingNode.having, operation2) - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/insert-query-node.js -var InsertQueryNode; -var init_insert_query_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/insert-query-node.js"() { - init_object_utils(); - InsertQueryNode = freeze2({ - is(node) { - return node.kind === "InsertQueryNode"; - }, - create(into, withNode, replace) { - return freeze2({ - kind: "InsertQueryNode", - into, - ...withNode && { with: withNode }, - replace - }); - }, - createWithoutInto() { - return freeze2({ - kind: "InsertQueryNode" - }); - }, - cloneWith(insertQuery, props) { - return freeze2({ - ...insertQuery, - ...props - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/list-node.js -var ListNode; -var init_list_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/list-node.js"() { - init_object_utils(); - ListNode = freeze2({ - is(node) { - return node.kind === "ListNode"; - }, - create(items) { - return freeze2({ - kind: "ListNode", - items: freeze2(items) - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/update-query-node.js -var UpdateQueryNode; -var init_update_query_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/update-query-node.js"() { - init_object_utils(); - init_from_node(); - init_list_node(); - UpdateQueryNode = freeze2({ - is(node) { - return node.kind === "UpdateQueryNode"; - }, - create(tables, withNode) { - return freeze2({ - kind: "UpdateQueryNode", - // For backwards compatibility, use the raw table node when there's only one table - // and don't rename the property to something like `tables`. - table: tables.length === 1 ? tables[0] : ListNode.create(tables), - ...withNode && { with: withNode } - }); - }, - createWithoutTable() { - return freeze2({ - kind: "UpdateQueryNode" - }); - }, - cloneWithFromItems(updateQuery, fromItems) { - return freeze2({ - ...updateQuery, - from: updateQuery.from ? FromNode.cloneWithFroms(updateQuery.from, fromItems) : FromNode.create(fromItems) - }); - }, - cloneWithUpdates(updateQuery, updates) { - return freeze2({ - ...updateQuery, - updates: updateQuery.updates ? freeze2([...updateQuery.updates, ...updates]) : updates - }); - }, - cloneWithLimit(updateQuery, limit) { - return freeze2({ - ...updateQuery, - limit - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/using-node.js -var UsingNode; -var init_using_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/using-node.js"() { - init_object_utils(); - UsingNode = freeze2({ - is(node) { - return node.kind === "UsingNode"; - }, - create(tables) { - return freeze2({ - kind: "UsingNode", - tables: freeze2(tables) - }); - }, - cloneWithTables(using, tables) { - return freeze2({ - ...using, - tables: freeze2([...using.tables, ...tables]) - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/delete-query-node.js -var DeleteQueryNode; -var init_delete_query_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/delete-query-node.js"() { - init_object_utils(); - init_from_node(); - init_using_node(); - init_query_node(); - DeleteQueryNode = freeze2({ - is(node) { - return node.kind === "DeleteQueryNode"; - }, - create(fromItems, withNode) { - return freeze2({ - kind: "DeleteQueryNode", - from: FromNode.create(fromItems), - ...withNode && { with: withNode } - }); - }, - // TODO: remove in v0.29 - /** - * @deprecated Use `QueryNode.cloneWithoutOrderBy` instead. - */ - cloneWithOrderByItems: (node, items) => QueryNode.cloneWithOrderByItems(node, items), - // TODO: remove in v0.29 - /** - * @deprecated Use `QueryNode.cloneWithoutOrderBy` instead. - */ - cloneWithoutOrderBy: (node) => QueryNode.cloneWithoutOrderBy(node), - cloneWithLimit(deleteNode, limit) { - return freeze2({ - ...deleteNode, - limit - }); - }, - cloneWithoutLimit(deleteNode) { - return freeze2({ - ...deleteNode, - limit: void 0 - }); - }, - cloneWithUsing(deleteNode, tables) { - return freeze2({ - ...deleteNode, - using: deleteNode.using !== void 0 ? UsingNode.cloneWithTables(deleteNode.using, tables) : UsingNode.create(tables) - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/where-node.js -var WhereNode; -var init_where_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/where-node.js"() { - init_object_utils(); - init_and_node(); - init_or_node(); - WhereNode = freeze2({ - is(node) { - return node.kind === "WhereNode"; - }, - create(filter) { - return freeze2({ - kind: "WhereNode", - where: filter - }); - }, - cloneWithOperation(whereNode, operator, operation2) { - return freeze2({ - ...whereNode, - where: operator === "And" ? AndNode.create(whereNode.where, operation2) : OrNode.create(whereNode.where, operation2) - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/returning-node.js -var ReturningNode; -var init_returning_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/returning-node.js"() { - init_object_utils(); - ReturningNode = freeze2({ - is(node) { - return node.kind === "ReturningNode"; - }, - create(selections) { - return freeze2({ - kind: "ReturningNode", - selections: freeze2(selections) - }); - }, - cloneWithSelections(returning, selections) { - return freeze2({ - ...returning, - selections: returning.selections ? freeze2([...returning.selections, ...selections]) : freeze2(selections) - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/explain-node.js -var ExplainNode; -var init_explain_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/explain-node.js"() { - init_object_utils(); - ExplainNode = freeze2({ - is(node) { - return node.kind === "ExplainNode"; - }, - create(format2, options) { - return freeze2({ - kind: "ExplainNode", - format: format2, - options - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/when-node.js -var WhenNode; -var init_when_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/when-node.js"() { - init_object_utils(); - WhenNode = freeze2({ - is(node) { - return node.kind === "WhenNode"; - }, - create(condition) { - return freeze2({ - kind: "WhenNode", - condition - }); - }, - cloneWithResult(whenNode, result) { - return freeze2({ - ...whenNode, - result - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/merge-query-node.js -var MergeQueryNode; -var init_merge_query_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/merge-query-node.js"() { - init_object_utils(); - init_when_node(); - MergeQueryNode = freeze2({ - is(node) { - return node.kind === "MergeQueryNode"; - }, - create(into, withNode) { - return freeze2({ - kind: "MergeQueryNode", - into, - ...withNode && { with: withNode } - }); - }, - cloneWithUsing(mergeNode, using) { - return freeze2({ - ...mergeNode, - using - }); - }, - cloneWithWhen(mergeNode, when) { - return freeze2({ - ...mergeNode, - whens: mergeNode.whens ? freeze2([...mergeNode.whens, when]) : freeze2([when]) - }); - }, - cloneWithThen(mergeNode, then) { - return freeze2({ - ...mergeNode, - whens: mergeNode.whens ? freeze2([ - ...mergeNode.whens.slice(0, -1), - WhenNode.cloneWithResult(mergeNode.whens[mergeNode.whens.length - 1], then) - ]) : void 0 - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/output-node.js -var OutputNode; -var init_output_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/output-node.js"() { - init_object_utils(); - OutputNode = freeze2({ - is(node) { - return node.kind === "OutputNode"; - }, - create(selections) { - return freeze2({ - kind: "OutputNode", - selections: freeze2(selections) - }); - }, - cloneWithSelections(output, selections) { - return freeze2({ - ...output, - selections: output.selections ? freeze2([...output.selections, ...selections]) : freeze2(selections) - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/query-node.js -var QueryNode; -var init_query_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/query-node.js"() { - init_insert_query_node(); - init_select_query_node(); - init_update_query_node(); - init_delete_query_node(); - init_where_node(); - init_object_utils(); - init_returning_node(); - init_explain_node(); - init_merge_query_node(); - init_output_node(); - init_order_by_node(); - QueryNode = freeze2({ - is(node) { - return SelectQueryNode.is(node) || InsertQueryNode.is(node) || UpdateQueryNode.is(node) || DeleteQueryNode.is(node) || MergeQueryNode.is(node); - }, - cloneWithEndModifier(node, modifier) { - return freeze2({ - ...node, - endModifiers: node.endModifiers ? freeze2([...node.endModifiers, modifier]) : freeze2([modifier]) - }); - }, - cloneWithWhere(node, operation2) { - return freeze2({ - ...node, - where: node.where ? WhereNode.cloneWithOperation(node.where, "And", operation2) : WhereNode.create(operation2) - }); - }, - cloneWithJoin(node, join4) { - return freeze2({ - ...node, - joins: node.joins ? freeze2([...node.joins, join4]) : freeze2([join4]) - }); - }, - cloneWithReturning(node, selections) { - return freeze2({ - ...node, - returning: node.returning ? ReturningNode.cloneWithSelections(node.returning, selections) : ReturningNode.create(selections) - }); - }, - cloneWithoutReturning(node) { - return freeze2({ - ...node, - returning: void 0 - }); - }, - cloneWithoutWhere(node) { - return freeze2({ - ...node, - where: void 0 - }); - }, - cloneWithExplain(node, format2, options) { - return freeze2({ - ...node, - explain: ExplainNode.create(format2, options?.toOperationNode()) - }); - }, - cloneWithTop(node, top) { - return freeze2({ - ...node, - top - }); - }, - cloneWithOutput(node, selections) { - return freeze2({ - ...node, - output: node.output ? OutputNode.cloneWithSelections(node.output, selections) : OutputNode.create(selections) - }); - }, - cloneWithOrderByItems(node, items) { - return freeze2({ - ...node, - orderBy: node.orderBy ? OrderByNode.cloneWithItems(node.orderBy, items) : OrderByNode.create(items) - }); - }, - cloneWithoutOrderBy(node) { - return freeze2({ - ...node, - orderBy: void 0 - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/select-query-node.js -var SelectQueryNode; -var init_select_query_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/select-query-node.js"() { - init_object_utils(); - init_from_node(); - init_group_by_node(); - init_having_node(); - init_query_node(); - SelectQueryNode = freeze2({ - is(node) { - return node.kind === "SelectQueryNode"; - }, - create(withNode) { - return freeze2({ - kind: "SelectQueryNode", - ...withNode && { with: withNode } - }); - }, - createFrom(fromItems, withNode) { - return freeze2({ - kind: "SelectQueryNode", - from: FromNode.create(fromItems), - ...withNode && { with: withNode } - }); - }, - cloneWithSelections(select2, selections) { - return freeze2({ - ...select2, - selections: select2.selections ? freeze2([...select2.selections, ...selections]) : freeze2(selections) - }); - }, - cloneWithDistinctOn(select2, expressions) { - return freeze2({ - ...select2, - distinctOn: select2.distinctOn ? freeze2([...select2.distinctOn, ...expressions]) : freeze2(expressions) - }); - }, - cloneWithFrontModifier(select2, modifier) { - return freeze2({ - ...select2, - frontModifiers: select2.frontModifiers ? freeze2([...select2.frontModifiers, modifier]) : freeze2([modifier]) - }); - }, - // TODO: remove in v0.29 - /** - * @deprecated Use `QueryNode.cloneWithoutOrderBy` instead. - */ - cloneWithOrderByItems: (node, items) => QueryNode.cloneWithOrderByItems(node, items), - cloneWithGroupByItems(selectNode, items) { - return freeze2({ - ...selectNode, - groupBy: selectNode.groupBy ? GroupByNode.cloneWithItems(selectNode.groupBy, items) : GroupByNode.create(items) - }); - }, - cloneWithLimit(selectNode, limit) { - return freeze2({ - ...selectNode, - limit - }); - }, - cloneWithOffset(selectNode, offset) { - return freeze2({ - ...selectNode, - offset - }); - }, - cloneWithFetch(selectNode, fetch2) { - return freeze2({ - ...selectNode, - fetch: fetch2 - }); - }, - cloneWithHaving(selectNode, operation2) { - return freeze2({ - ...selectNode, - having: selectNode.having ? HavingNode.cloneWithOperation(selectNode.having, "And", operation2) : HavingNode.create(operation2) - }); - }, - cloneWithSetOperations(selectNode, setOperations) { - return freeze2({ - ...selectNode, - setOperations: selectNode.setOperations ? freeze2([...selectNode.setOperations, ...setOperations]) : freeze2([...setOperations]) - }); - }, - cloneWithoutSelections(select2) { - return freeze2({ - ...select2, - selections: [] - }); - }, - cloneWithoutLimit(select2) { - return freeze2({ - ...select2, - limit: void 0 - }); - }, - cloneWithoutOffset(select2) { - return freeze2({ - ...select2, - offset: void 0 - }); - }, - // TODO: remove in v0.29 - /** - * @deprecated Use `QueryNode.cloneWithoutOrderBy` instead. - */ - cloneWithoutOrderBy: (node) => QueryNode.cloneWithoutOrderBy(node), - cloneWithoutGroupBy(select2) { - return freeze2({ - ...select2, - groupBy: void 0 - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/join-builder.js -var JoinBuilder; -var init_join_builder = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/join-builder.js"() { - init_join_node(); - init_raw_node(); - init_binary_operation_parser(); - init_object_utils(); - JoinBuilder = class _JoinBuilder { - #props; - constructor(props) { - this.#props = freeze2(props); - } - on(...args) { - return new _JoinBuilder({ - ...this.#props, - joinNode: JoinNode.cloneWithOn(this.#props.joinNode, parseValueBinaryOperationOrExpression(args)) - }); - } - /** - * Just like {@link WhereInterface.whereRef} but adds an item to the join's - * `on` clause instead. - * - * See {@link WhereInterface.whereRef} for documentation and examples. - */ - onRef(lhs, op2, rhs) { - return new _JoinBuilder({ - ...this.#props, - joinNode: JoinNode.cloneWithOn(this.#props.joinNode, parseReferentialBinaryOperation(lhs, op2, rhs)) - }); - } - /** - * Adds `on true`. - */ - onTrue() { - return new _JoinBuilder({ - ...this.#props, - joinNode: JoinNode.cloneWithOn(this.#props.joinNode, RawNode.createWithSql("true")) - }); - } - /** - * Simply calls the provided function passing `this` as the only argument. `$call` returns - * what the provided function returns. - */ - $call(func) { - return func(this); - } - toOperationNode() { - return this.#props.joinNode; - } - }; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/partition-by-item-node.js -var PartitionByItemNode; -var init_partition_by_item_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/partition-by-item-node.js"() { - init_object_utils(); - PartitionByItemNode = freeze2({ - is(node) { - return node.kind === "PartitionByItemNode"; - }, - create(partitionBy) { - return freeze2({ - kind: "PartitionByItemNode", - partitionBy - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/partition-by-parser.js -function parsePartitionBy(partitionBy) { - return parseReferenceExpressionOrList(partitionBy).map(PartitionByItemNode.create); -} -var init_partition_by_parser = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/partition-by-parser.js"() { - init_partition_by_item_node(); - init_reference_parser(); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/over-builder.js -var OverBuilder; -var init_over_builder = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/over-builder.js"() { - init_over_node(); - init_query_node(); - init_order_by_parser(); - init_partition_by_parser(); - init_object_utils(); - OverBuilder = class _OverBuilder { - #props; - constructor(props) { - this.#props = freeze2(props); - } - orderBy(...args) { - return new _OverBuilder({ - overNode: OverNode.cloneWithOrderByItems(this.#props.overNode, parseOrderBy(args)) - }); - } - clearOrderBy() { - return new _OverBuilder({ - overNode: QueryNode.cloneWithoutOrderBy(this.#props.overNode) - }); - } - partitionBy(partitionBy) { - return new _OverBuilder({ - overNode: OverNode.cloneWithPartitionByItems(this.#props.overNode, parsePartitionBy(partitionBy)) - }); - } - /** - * Simply calls the provided function passing `this` as the only argument. `$call` returns - * what the provided function returns. - */ - $call(func) { - return func(this); - } - toOperationNode() { - return this.#props.overNode; - } - }; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/selection-node.js -var SelectionNode; -var init_selection_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/selection-node.js"() { - init_object_utils(); - init_reference_node(); - init_select_all_node(); - SelectionNode = freeze2({ - is(node) { - return node.kind === "SelectionNode"; - }, - create(selection) { - return freeze2({ - kind: "SelectionNode", - selection - }); - }, - createSelectAll() { - return freeze2({ - kind: "SelectionNode", - selection: SelectAllNode.create() - }); - }, - createSelectAllFromTable(table) { - return freeze2({ - kind: "SelectionNode", - selection: ReferenceNode.createSelectAll(table) - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/select-parser.js -function parseSelectArg(selection) { - if (isFunction(selection)) { - return parseSelectArg(selection(expressionBuilder())); - } else if (isReadonlyArray(selection)) { - return selection.map((it) => parseSelectExpression(it)); - } else { - return [parseSelectExpression(selection)]; - } -} -function parseSelectExpression(selection) { - if (isString(selection)) { - return SelectionNode.create(parseAliasedStringReference(selection)); - } else if (isDynamicReferenceBuilder(selection)) { - return SelectionNode.create(selection.toOperationNode()); - } else { - return SelectionNode.create(parseAliasedExpression(selection)); - } -} -function parseSelectAll(table) { - if (!table) { - return [SelectionNode.createSelectAll()]; - } else if (Array.isArray(table)) { - return table.map(parseSelectAllArg); - } else { - return [parseSelectAllArg(table)]; - } -} -function parseSelectAllArg(table) { - if (isString(table)) { - return SelectionNode.createSelectAllFromTable(parseTable(table)); - } - throw new Error(`invalid value selectAll expression: ${JSON.stringify(table)}`); -} -var init_select_parser = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/select-parser.js"() { - init_object_utils(); - init_selection_node(); - init_reference_parser(); - init_dynamic_reference_builder(); - init_expression_parser(); - init_table_parser(); - init_expression_builder(); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/values-node.js -var ValuesNode; -var init_values_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/values-node.js"() { - init_object_utils(); - ValuesNode = freeze2({ - is(node) { - return node.kind === "ValuesNode"; - }, - create(values2) { - return freeze2({ - kind: "ValuesNode", - values: freeze2(values2) - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/default-insert-value-node.js -var DefaultInsertValueNode; -var init_default_insert_value_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/default-insert-value-node.js"() { - init_object_utils(); - DefaultInsertValueNode = freeze2({ - is(node) { - return node.kind === "DefaultInsertValueNode"; - }, - create() { - return freeze2({ - kind: "DefaultInsertValueNode" - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/insert-values-parser.js -function parseInsertExpression(arg) { - const objectOrList = isFunction(arg) ? arg(expressionBuilder()) : arg; - const list2 = isReadonlyArray(objectOrList) ? objectOrList : freeze2([objectOrList]); - return parseInsertColumnsAndValues(list2); -} -function parseInsertColumnsAndValues(rows) { - const columns = parseColumnNamesAndIndexes(rows); - return [ - freeze2([...columns.keys()].map(ColumnNode.create)), - ValuesNode.create(rows.map((row) => parseRowValues(row, columns))) - ]; -} -function parseColumnNamesAndIndexes(rows) { - const columns = /* @__PURE__ */ new Map(); - for (const row of rows) { - const cols = Object.keys(row); - for (const col of cols) { - if (!columns.has(col) && row[col] !== void 0) { - columns.set(col, columns.size); - } - } - } - return columns; -} -function parseRowValues(row, columns) { - const rowColumns = Object.keys(row); - const rowValues = Array.from({ - length: columns.size - }); - let hasUndefinedOrComplexColumns = false; - let indexedRowColumns = rowColumns.length; - for (const col of rowColumns) { - const columnIdx = columns.get(col); - if (isUndefined(columnIdx)) { - indexedRowColumns--; - continue; - } - const value = row[col]; - if (isUndefined(value) || isExpressionOrFactory(value)) { - hasUndefinedOrComplexColumns = true; - } - rowValues[columnIdx] = value; - } - const hasMissingColumns = indexedRowColumns < columns.size; - if (hasMissingColumns || hasUndefinedOrComplexColumns) { - const defaultValue = DefaultInsertValueNode.create(); - return ValueListNode.create(rowValues.map((it) => isUndefined(it) ? defaultValue : parseValueExpression(it))); - } - return PrimitiveValueListNode.create(rowValues); -} -var init_insert_values_parser = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/insert-values-parser.js"() { - init_column_node(); - init_primitive_value_list_node(); - init_value_list_node(); - init_object_utils(); - init_value_parser(); - init_values_node(); - init_expression_parser(); - init_default_insert_value_node(); - init_expression_builder(); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/column-update-node.js -var ColumnUpdateNode; -var init_column_update_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/column-update-node.js"() { - init_object_utils(); - ColumnUpdateNode = freeze2({ - is(node) { - return node.kind === "ColumnUpdateNode"; - }, - create(column, value) { - return freeze2({ - kind: "ColumnUpdateNode", - column, - value - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/update-set-parser.js -function parseUpdate(...args) { - if (args.length === 2) { - return [ - ColumnUpdateNode.create(parseReferenceExpression(args[0]), parseValueExpression(args[1])) - ]; - } - return parseUpdateObjectExpression(args[0]); -} -function parseUpdateObjectExpression(update) { - const updateObj = isFunction(update) ? update(expressionBuilder()) : update; - return Object.entries(updateObj).filter(([_, value]) => value !== void 0).map(([key, value]) => { - return ColumnUpdateNode.create(ColumnNode.create(key), parseValueExpression(value)); - }); -} -var init_update_set_parser = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/update-set-parser.js"() { - init_column_node(); - init_column_update_node(); - init_expression_builder(); - init_object_utils(); - init_value_parser(); - init_reference_parser(); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/on-duplicate-key-node.js -var OnDuplicateKeyNode; -var init_on_duplicate_key_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/on-duplicate-key-node.js"() { - init_object_utils(); - OnDuplicateKeyNode = freeze2({ - is(node) { - return node.kind === "OnDuplicateKeyNode"; - }, - create(updates) { - return freeze2({ - kind: "OnDuplicateKeyNode", - updates - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/insert-result.js -var InsertResult; -var init_insert_result = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/insert-result.js"() { - InsertResult = class { - /** - * The auto incrementing primary key of the inserted row. - * - * This property can be undefined when the query contains an `on conflict` - * clause that makes the query succeed even when nothing gets inserted. - * - * This property is always undefined on dialects like PostgreSQL that - * don't return the inserted id by default. On those dialects you need - * to use the {@link ReturningInterface.returning | returning} method. - */ - insertId; - /** - * Affected rows count. - */ - numInsertedOrUpdatedRows; - constructor(insertId, numInsertedOrUpdatedRows) { - this.insertId = insertId; - this.numInsertedOrUpdatedRows = numInsertedOrUpdatedRows; - } - }; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/no-result-error.js -function isNoResultErrorConstructor(fn) { - return Object.prototype.hasOwnProperty.call(fn, "prototype"); -} -var NoResultError; -var init_no_result_error = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/no-result-error.js"() { - NoResultError = class extends Error { - /** - * The operation node tree of the query that was executed. - */ - node; - constructor(node) { - super("no result"); - this.node = node; - } - }; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/on-conflict-node.js -var OnConflictNode; -var init_on_conflict_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/on-conflict-node.js"() { - init_object_utils(); - init_where_node(); - OnConflictNode = freeze2({ - is(node) { - return node.kind === "OnConflictNode"; - }, - create() { - return freeze2({ - kind: "OnConflictNode" - }); - }, - cloneWith(node, props) { - return freeze2({ - ...node, - ...props - }); - }, - cloneWithIndexWhere(node, operation2) { - return freeze2({ - ...node, - indexWhere: node.indexWhere ? WhereNode.cloneWithOperation(node.indexWhere, "And", operation2) : WhereNode.create(operation2) - }); - }, - cloneWithIndexOrWhere(node, operation2) { - return freeze2({ - ...node, - indexWhere: node.indexWhere ? WhereNode.cloneWithOperation(node.indexWhere, "Or", operation2) : WhereNode.create(operation2) - }); - }, - cloneWithUpdateWhere(node, operation2) { - return freeze2({ - ...node, - updateWhere: node.updateWhere ? WhereNode.cloneWithOperation(node.updateWhere, "And", operation2) : WhereNode.create(operation2) - }); - }, - cloneWithUpdateOrWhere(node, operation2) { - return freeze2({ - ...node, - updateWhere: node.updateWhere ? WhereNode.cloneWithOperation(node.updateWhere, "Or", operation2) : WhereNode.create(operation2) - }); - }, - cloneWithoutIndexWhere(node) { - return freeze2({ - ...node, - indexWhere: void 0 - }); - }, - cloneWithoutUpdateWhere(node) { - return freeze2({ - ...node, - updateWhere: void 0 - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/on-conflict-builder.js -var OnConflictBuilder, OnConflictDoNothingBuilder, OnConflictUpdateBuilder; -var init_on_conflict_builder = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/on-conflict-builder.js"() { - init_column_node(); - init_identifier_node(); - init_on_conflict_node(); - init_binary_operation_parser(); - init_update_set_parser(); - init_object_utils(); - OnConflictBuilder = class _OnConflictBuilder { - #props; - constructor(props) { - this.#props = freeze2(props); - } - /** - * Specify a single column as the conflict target. - * - * Also see the {@link columns}, {@link constraint} and {@link expression} - * methods for alternative ways to specify the conflict target. - */ - column(column) { - const columnNode = ColumnNode.create(column); - return new _OnConflictBuilder({ - ...this.#props, - onConflictNode: OnConflictNode.cloneWith(this.#props.onConflictNode, { - columns: this.#props.onConflictNode.columns ? freeze2([...this.#props.onConflictNode.columns, columnNode]) : freeze2([columnNode]) - }) - }); - } - /** - * Specify a list of columns as the conflict target. - * - * Also see the {@link column}, {@link constraint} and {@link expression} - * methods for alternative ways to specify the conflict target. - */ - columns(columns) { - const columnNodes = columns.map(ColumnNode.create); - return new _OnConflictBuilder({ - ...this.#props, - onConflictNode: OnConflictNode.cloneWith(this.#props.onConflictNode, { - columns: this.#props.onConflictNode.columns ? freeze2([...this.#props.onConflictNode.columns, ...columnNodes]) : freeze2(columnNodes) - }) - }); - } - /** - * Specify a specific constraint by name as the conflict target. - * - * Also see the {@link column}, {@link columns} and {@link expression} - * methods for alternative ways to specify the conflict target. - */ - constraint(constraintName) { - return new _OnConflictBuilder({ - ...this.#props, - onConflictNode: OnConflictNode.cloneWith(this.#props.onConflictNode, { - constraint: IdentifierNode.create(constraintName) - }) - }); - } - /** - * Specify an expression as the conflict target. - * - * This can be used if the unique index is an expression index. - * - * Also see the {@link column}, {@link columns} and {@link constraint} - * methods for alternative ways to specify the conflict target. - */ - expression(expression) { - return new _OnConflictBuilder({ - ...this.#props, - onConflictNode: OnConflictNode.cloneWith(this.#props.onConflictNode, { - indexExpression: expression.toOperationNode() - }) - }); - } - where(...args) { - return new _OnConflictBuilder({ - ...this.#props, - onConflictNode: OnConflictNode.cloneWithIndexWhere(this.#props.onConflictNode, parseValueBinaryOperationOrExpression(args)) - }); - } - whereRef(lhs, op2, rhs) { - return new _OnConflictBuilder({ - ...this.#props, - onConflictNode: OnConflictNode.cloneWithIndexWhere(this.#props.onConflictNode, parseReferentialBinaryOperation(lhs, op2, rhs)) - }); - } - clearWhere() { - return new _OnConflictBuilder({ - ...this.#props, - onConflictNode: OnConflictNode.cloneWithoutIndexWhere(this.#props.onConflictNode) - }); - } - /** - * Adds the "do nothing" conflict action. - * - * ### Examples - * - * ```ts - * const id = 1 - * const first_name = 'John' - * - * await db - * .insertInto('person') - * .values({ first_name, id }) - * .onConflict((oc) => oc - * .column('id') - * .doNothing() - * ) - * .execute() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * insert into "person" ("first_name", "id") - * values ($1, $2) - * on conflict ("id") do nothing - * ``` - */ - doNothing() { - return new OnConflictDoNothingBuilder({ - ...this.#props, - onConflictNode: OnConflictNode.cloneWith(this.#props.onConflictNode, { - doNothing: true - }) - }); - } - /** - * Adds the "do update set" conflict action. - * - * ### Examples - * - * ```ts - * const id = 1 - * const first_name = 'John' - * - * await db - * .insertInto('person') - * .values({ first_name, id }) - * .onConflict((oc) => oc - * .column('id') - * .doUpdateSet({ first_name }) - * ) - * .execute() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * insert into "person" ("first_name", "id") - * values ($1, $2) - * on conflict ("id") - * do update set "first_name" = $3 - * ``` - * - * In the next example we use the `ref` method to reference - * columns of the virtual table `excluded` in a type-safe way - * to create an upsert operation: - * - * ```ts - * import type { NewPerson } from 'type-editor' // imaginary module - * - * async function upsertPerson(person: NewPerson): Promise { - * await db.insertInto('person') - * .values(person) - * .onConflict((oc) => oc - * .column('id') - * .doUpdateSet((eb) => ({ - * first_name: eb.ref('excluded.first_name'), - * last_name: eb.ref('excluded.last_name') - * }) - * ) - * ) - * .execute() - * } - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * insert into "person" ("first_name", "last_name") - * values ($1, $2) - * on conflict ("id") - * do update set - * "first_name" = excluded."first_name", - * "last_name" = excluded."last_name" - * ``` - */ - doUpdateSet(update) { - return new OnConflictUpdateBuilder({ - ...this.#props, - onConflictNode: OnConflictNode.cloneWith(this.#props.onConflictNode, { - updates: parseUpdateObjectExpression(update) - }) - }); - } - /** - * Simply calls the provided function passing `this` as the only argument. `$call` returns - * what the provided function returns. - */ - $call(func) { - return func(this); - } - }; - OnConflictDoNothingBuilder = class { - #props; - constructor(props) { - this.#props = freeze2(props); - } - toOperationNode() { - return this.#props.onConflictNode; - } - }; - OnConflictUpdateBuilder = class _OnConflictUpdateBuilder { - #props; - constructor(props) { - this.#props = freeze2(props); - } - where(...args) { - return new _OnConflictUpdateBuilder({ - ...this.#props, - onConflictNode: OnConflictNode.cloneWithUpdateWhere(this.#props.onConflictNode, parseValueBinaryOperationOrExpression(args)) - }); - } - /** - * Specify a where condition for the update operation. - * - * See {@link WhereInterface.whereRef} for more info. - */ - whereRef(lhs, op2, rhs) { - return new _OnConflictUpdateBuilder({ - ...this.#props, - onConflictNode: OnConflictNode.cloneWithUpdateWhere(this.#props.onConflictNode, parseReferentialBinaryOperation(lhs, op2, rhs)) - }); - } - clearWhere() { - return new _OnConflictUpdateBuilder({ - ...this.#props, - onConflictNode: OnConflictNode.cloneWithoutUpdateWhere(this.#props.onConflictNode) - }); - } - /** - * Simply calls the provided function passing `this` as the only argument. `$call` returns - * what the provided function returns. - */ - $call(func) { - return func(this); - } - toOperationNode() { - return this.#props.onConflictNode; - } - }; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/top-node.js -var TopNode; -var init_top_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/top-node.js"() { - init_object_utils(); - TopNode = freeze2({ - is(node) { - return node.kind === "TopNode"; - }, - create(expression, modifiers) { - return freeze2({ - kind: "TopNode", - expression, - modifiers - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/top-parser.js -function parseTop(expression, modifiers) { - if (!isNumber(expression) && !isBigInt(expression)) { - throw new Error(`Invalid top expression: ${expression}`); - } - if (!isUndefined(modifiers) && !isTopModifiers(modifiers)) { - throw new Error(`Invalid top modifiers: ${modifiers}`); - } - return TopNode.create(expression, modifiers); -} -function isTopModifiers(modifiers) { - return modifiers === "percent" || modifiers === "with ties" || modifiers === "percent with ties"; -} -var init_top_parser = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/top-parser.js"() { - init_top_node(); - init_object_utils(); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/or-action-node.js -var OrActionNode; -var init_or_action_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/or-action-node.js"() { - init_object_utils(); - OrActionNode = freeze2({ - is(node) { - return node.kind === "OrActionNode"; - }, - create(action) { - return freeze2({ - kind: "OrActionNode", - action - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/insert-query-builder.js -var InsertQueryBuilder; -var init_insert_query_builder = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/insert-query-builder.js"() { - init_select_parser(); - init_insert_values_parser(); - init_insert_query_node(); - init_query_node(); - init_update_set_parser(); - init_object_utils(); - init_on_duplicate_key_node(); - init_insert_result(); - init_no_result_error(); - init_expression_parser(); - init_column_node(); - init_on_conflict_builder(); - init_on_conflict_node(); - init_top_parser(); - init_or_action_node(); - InsertQueryBuilder = class _InsertQueryBuilder { - #props; - constructor(props) { - this.#props = freeze2(props); - } - /** - * Sets the values to insert for an {@link Kysely.insertInto | insert} query. - * - * This method takes an object whose keys are column names and values are - * values to insert. In addition to the column's type, the values can be - * raw {@link sql} snippets or select queries. - * - * You must provide all fields you haven't explicitly marked as nullable - * or optional using {@link Generated} or {@link ColumnType}. - * - * The return value of an `insert` query is an instance of {@link InsertResult}. The - * {@link InsertResult.insertId | insertId} field holds the auto incremented primary - * key if the database returned one. - * - * On PostgreSQL and some other dialects, you need to call `returning` to get - * something out of the query. - * - * Also see the {@link expression} method for inserting the result of a select - * query or any other expression. - * - * ### Examples - * - * - * - * Insert a single row: - * - * ```ts - * const result = await db - * .insertInto('person') - * .values({ - * first_name: 'Jennifer', - * last_name: 'Aniston', - * age: 40 - * }) - * .executeTakeFirst() - * - * // `insertId` is only available on dialects that - * // automatically return the id of the inserted row - * // such as MySQL and SQLite. On PostgreSQL, for example, - * // you need to add a `returning` clause to the query to - * // get anything out. See the "returning data" example. - * console.log(result.insertId) - * ``` - * - * The generated SQL (MySQL): - * - * ```sql - * insert into `person` (`first_name`, `last_name`, `age`) values (?, ?, ?) - * ``` - * - * - * - * On dialects that support it (for example PostgreSQL) you can insert multiple - * rows by providing an array. Note that the return value is once again very - * dialect-specific. Some databases may only return the id of the *last* inserted - * row and some return nothing at all unless you call `returning`. - * - * ```ts - * await db - * .insertInto('person') - * .values([{ - * first_name: 'Jennifer', - * last_name: 'Aniston', - * age: 40, - * }, { - * first_name: 'Arnold', - * last_name: 'Schwarzenegger', - * age: 70, - * }]) - * .execute() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * insert into "person" ("first_name", "last_name", "age") values (($1, $2, $3), ($4, $5, $6)) - * ``` - * - * - * - * On supported dialects like PostgreSQL you need to chain `returning` to the query to get - * the inserted row's columns (or any other expression) as the return value. `returning` - * works just like `select`. Refer to `select` method's examples and documentation for - * more info. - * - * ```ts - * const result = await db - * .insertInto('person') - * .values({ - * first_name: 'Jennifer', - * last_name: 'Aniston', - * age: 40, - * }) - * .returning(['id', 'first_name as name']) - * .executeTakeFirstOrThrow() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * insert into "person" ("first_name", "last_name", "age") values ($1, $2, $3) returning "id", "first_name" as "name" - * ``` - * - * - * - * In addition to primitives, the values can also be arbitrary expressions. - * You can build the expressions by using a callback and calling the methods - * on the expression builder passed to it: - * - * ```ts - * import { sql } from 'kysely' - * - * const ani = "Ani" - * const ston = "ston" - * - * const result = await db - * .insertInto('person') - * .values(({ ref, selectFrom, fn }) => ({ - * first_name: 'Jennifer', - * last_name: sql`concat(${ani}, ${ston})`, - * middle_name: ref('first_name'), - * age: selectFrom('person') - * .select(fn.avg('age').as('avg_age')), - * })) - * .executeTakeFirst() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * insert into "person" ( - * "first_name", - * "last_name", - * "middle_name", - * "age" - * ) - * values ( - * $1, - * concat($2, $3), - * "first_name", - * (select avg("age") as "avg_age" from "person") - * ) - * ``` - * - * You can also use the callback version of subqueries or raw expressions: - * - * ```ts - * await db.with('jennifer', (db) => db - * .selectFrom('person') - * .where('first_name', '=', 'Jennifer') - * .select(['id', 'first_name', 'gender']) - * .limit(1) - * ).insertInto('pet').values((eb) => ({ - * owner_id: eb.selectFrom('jennifer').select('id'), - * name: eb.selectFrom('jennifer').select('first_name'), - * species: 'cat', - * })) - * .execute() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * with "jennifer" as ( - * select "id", "first_name", "gender" - * from "person" - * where "first_name" = $1 - * limit $2 - * ) - * insert into "pet" ("owner_id", "name", "species") - * values ( - * (select "id" from "jennifer"), - * (select "first_name" from "jennifer"), - * $3 - * ) - * ``` - */ - values(insert) { - const [columns, values2] = parseInsertExpression(insert); - return new _InsertQueryBuilder({ - ...this.#props, - queryNode: InsertQueryNode.cloneWith(this.#props.queryNode, { - columns, - values: values2 - }) - }); - } - /** - * Sets the columns to insert. - * - * The {@link values} method sets both the columns and the values and this method - * is not needed. But if you are using the {@link expression} method, you can use - * this method to set the columns to insert. - * - * ### Examples - * - * ```ts - * await db.insertInto('person') - * .columns(['first_name']) - * .expression((eb) => eb.selectFrom('pet').select('pet.name')) - * .execute() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * insert into "person" ("first_name") - * select "pet"."name" from "pet" - * ``` - */ - columns(columns) { - return new _InsertQueryBuilder({ - ...this.#props, - queryNode: InsertQueryNode.cloneWith(this.#props.queryNode, { - columns: freeze2(columns.map(ColumnNode.create)) - }) - }); - } - /** - * Insert an arbitrary expression. For example the result of a select query. - * - * ### Examples - * - * - * - * You can create an `INSERT INTO SELECT FROM` query using the `expression` method. - * This API doesn't follow our WYSIWYG principles and might be a bit difficult to - * remember. The reasons for this design stem from implementation difficulties. - * - * ```ts - * const result = await db.insertInto('person') - * .columns(['first_name', 'last_name', 'age']) - * .expression((eb) => eb - * .selectFrom('pet') - * .select((eb) => [ - * 'pet.name', - * eb.val('Petson').as('last_name'), - * eb.lit(7).as('age'), - * ]) - * ) - * .execute() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * insert into "person" ("first_name", "last_name", "age") - * select "pet"."name", $1 as "last_name", 7 as "age from "pet" - * ``` - */ - expression(expression) { - return new _InsertQueryBuilder({ - ...this.#props, - queryNode: InsertQueryNode.cloneWith(this.#props.queryNode, { - values: parseExpression(expression) - }) - }); - } - /** - * Creates an `insert into "person" default values` query. - * - * ### Examples - * - * ```ts - * await db.insertInto('person') - * .defaultValues() - * .execute() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * insert into "person" default values - * ``` - */ - defaultValues() { - return new _InsertQueryBuilder({ - ...this.#props, - queryNode: InsertQueryNode.cloneWith(this.#props.queryNode, { - defaultValues: true - }) - }); - } - /** - * This can be used to add any additional SQL to the end of the query. - * - * ### Examples - * - * ```ts - * import { sql } from 'kysely' - * - * await db.insertInto('person') - * .values({ - * first_name: 'John', - * last_name: 'Doe', - * gender: 'male', - * }) - * .modifyEnd(sql`-- This is a comment`) - * .execute() - * ``` - * - * The generated SQL (MySQL): - * - * ```sql - * insert into `person` ("first_name", "last_name", "gender") - * values (?, ?, ?) -- This is a comment - * ``` - */ - modifyEnd(modifier) { - return new _InsertQueryBuilder({ - ...this.#props, - queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, modifier.toOperationNode()) - }); - } - /** - * Changes an `insert into` query to an `insert ignore into` query. - * - * This is only supported by some dialects like MySQL. - * - * To avoid a footgun, when invoked with the SQLite dialect, this method will - * be handled like {@link orIgnore}. See also, {@link orAbort}, {@link orFail}, - * {@link orReplace}, and {@link orRollback}. - * - * If you use the ignore modifier, ignorable errors that occur while executing the - * insert statement are ignored. For example, without ignore, a row that duplicates - * an existing unique index or primary key value in the table causes a duplicate-key - * error and the statement is aborted. With ignore, the row is discarded and no error - * occurs. - * - * ### Examples - * - * ```ts - * await db.insertInto('person') - * .ignore() - * .values({ - * first_name: 'John', - * last_name: 'Doe', - * gender: 'female', - * }) - * .execute() - * ``` - * - * The generated SQL (MySQL): - * - * ```sql - * insert ignore into `person` (`first_name`, `last_name`, `gender`) values (?, ?, ?) - * ``` - * - * The generated SQL (SQLite): - * - * ```sql - * insert or ignore into "person" ("first_name", "last_name", "gender") values (?, ?, ?) - * ``` - */ - ignore() { - return new _InsertQueryBuilder({ - ...this.#props, - queryNode: InsertQueryNode.cloneWith(this.#props.queryNode, { - orAction: OrActionNode.create("ignore") - }) - }); - } - /** - * Changes an `insert into` query to an `insert or ignore into` query. - * - * This is only supported by some dialects like SQLite. - * - * To avoid a footgun, when invoked with the MySQL dialect, this method will - * be handled like {@link ignore}. - * - * See also, {@link orAbort}, {@link orFail}, {@link orReplace}, and {@link orRollback}. - * - * ### Examples - * - * ```ts - * await db.insertInto('person') - * .orIgnore() - * .values({ - * first_name: 'John', - * last_name: 'Doe', - * gender: 'female', - * }) - * .execute() - * ``` - * - * The generated SQL (SQLite): - * - * ```sql - * insert or ignore into "person" ("first_name", "last_name", "gender") values (?, ?, ?) - * ``` - * - * The generated SQL (MySQL): - * - * ```sql - * insert ignore into `person` (`first_name`, `last_name`, `gender`) values (?, ?, ?) - * ``` - */ - orIgnore() { - return new _InsertQueryBuilder({ - ...this.#props, - queryNode: InsertQueryNode.cloneWith(this.#props.queryNode, { - orAction: OrActionNode.create("ignore") - }) - }); - } - /** - * Changes an `insert into` query to an `insert or abort into` query. - * - * This is only supported by some dialects like SQLite. - * - * See also, {@link orIgnore}, {@link orFail}, {@link orReplace}, and {@link orRollback}. - * - * ### Examples - * - * ```ts - * await db.insertInto('person') - * .orAbort() - * .values({ - * first_name: 'John', - * last_name: 'Doe', - * gender: 'female', - * }) - * .execute() - * ``` - * - * The generated SQL (SQLite): - * - * ```sql - * insert or abort into "person" ("first_name", "last_name", "gender") values (?, ?, ?) - * ``` - */ - orAbort() { - return new _InsertQueryBuilder({ - ...this.#props, - queryNode: InsertQueryNode.cloneWith(this.#props.queryNode, { - orAction: OrActionNode.create("abort") - }) - }); - } - /** - * Changes an `insert into` query to an `insert or fail into` query. - * - * This is only supported by some dialects like SQLite. - * - * See also, {@link orIgnore}, {@link orAbort}, {@link orReplace}, and {@link orRollback}. - * - * ### Examples - * - * ```ts - * await db.insertInto('person') - * .orFail() - * .values({ - * first_name: 'John', - * last_name: 'Doe', - * gender: 'female', - * }) - * .execute() - * ``` - * - * The generated SQL (SQLite): - * - * ```sql - * insert or fail into "person" ("first_name", "last_name", "gender") values (?, ?, ?) - * ``` - */ - orFail() { - return new _InsertQueryBuilder({ - ...this.#props, - queryNode: InsertQueryNode.cloneWith(this.#props.queryNode, { - orAction: OrActionNode.create("fail") - }) - }); - } - /** - * Changes an `insert into` query to an `insert or replace into` query. - * - * This is only supported by some dialects like SQLite. - * - * You can also use {@link Kysely.replaceInto} to achieve the same result. - * - * See also, {@link orIgnore}, {@link orAbort}, {@link orFail}, and {@link orRollback}. - * - * ### Examples - * - * ```ts - * await db.insertInto('person') - * .orReplace() - * .values({ - * first_name: 'John', - * last_name: 'Doe', - * gender: 'female', - * }) - * .execute() - * ``` - * - * The generated SQL (SQLite): - * - * ```sql - * insert or replace into "person" ("first_name", "last_name", "gender") values (?, ?, ?) - * ``` - */ - orReplace() { - return new _InsertQueryBuilder({ - ...this.#props, - queryNode: InsertQueryNode.cloneWith(this.#props.queryNode, { - orAction: OrActionNode.create("replace") - }) - }); - } - /** - * Changes an `insert into` query to an `insert or rollback into` query. - * - * This is only supported by some dialects like SQLite. - * - * See also, {@link orIgnore}, {@link orAbort}, {@link orFail}, and {@link orReplace}. - * - * ### Examples - * - * ```ts - * await db.insertInto('person') - * .orRollback() - * .values({ - * first_name: 'John', - * last_name: 'Doe', - * gender: 'female', - * }) - * .execute() - * ``` - * - * The generated SQL (SQLite): - * - * ```sql - * insert or rollback into "person" ("first_name", "last_name", "gender") values (?, ?, ?) - * ``` - */ - orRollback() { - return new _InsertQueryBuilder({ - ...this.#props, - queryNode: InsertQueryNode.cloneWith(this.#props.queryNode, { - orAction: OrActionNode.create("rollback") - }) - }); - } - /** - * Changes an `insert into` query to an `insert top into` query. - * - * `top` clause is only supported by some dialects like MS SQL Server. - * - * ### Examples - * - * Insert the first 5 rows: - * - * ```ts - * import { sql } from 'kysely' - * - * await db.insertInto('person') - * .top(5) - * .columns(['first_name', 'gender']) - * .expression( - * (eb) => eb.selectFrom('pet').select(['name', sql.lit('other').as('gender')]) - * ) - * .execute() - * ``` - * - * The generated SQL (MS SQL Server): - * - * ```sql - * insert top(5) into "person" ("first_name", "gender") select "name", 'other' as "gender" from "pet" - * ``` - * - * Insert the first 50 percent of rows: - * - * ```ts - * import { sql } from 'kysely' - * - * await db.insertInto('person') - * .top(50, 'percent') - * .columns(['first_name', 'gender']) - * .expression( - * (eb) => eb.selectFrom('pet').select(['name', sql.lit('other').as('gender')]) - * ) - * .execute() - * ``` - * - * The generated SQL (MS SQL Server): - * - * ```sql - * insert top(50) percent into "person" ("first_name", "gender") select "name", 'other' as "gender" from "pet" - * ``` - */ - top(expression, modifiers) { - return new _InsertQueryBuilder({ - ...this.#props, - queryNode: QueryNode.cloneWithTop(this.#props.queryNode, parseTop(expression, modifiers)) - }); - } - /** - * Adds an `on conflict` clause to the query. - * - * `on conflict` is only supported by some dialects like PostgreSQL and SQLite. On MySQL - * you can use {@link ignore} and {@link onDuplicateKeyUpdate} to achieve similar results. - * - * ### Examples - * - * ```ts - * await db - * .insertInto('pet') - * .values({ - * name: 'Catto', - * species: 'cat', - * owner_id: 3, - * }) - * .onConflict((oc) => oc - * .column('name') - * .doUpdateSet({ species: 'hamster' }) - * ) - * .execute() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * insert into "pet" ("name", "species", "owner_id") - * values ($1, $2, $3) - * on conflict ("name") - * do update set "species" = $4 - * ``` - * - * You can provide the name of the constraint instead of a column name: - * - * ```ts - * await db - * .insertInto('pet') - * .values({ - * name: 'Catto', - * species: 'cat', - * owner_id: 3, - * }) - * .onConflict((oc) => oc - * .constraint('pet_name_key') - * .doUpdateSet({ species: 'hamster' }) - * ) - * .execute() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * insert into "pet" ("name", "species", "owner_id") - * values ($1, $2, $3) - * on conflict on constraint "pet_name_key" - * do update set "species" = $4 - * ``` - * - * You can also specify an expression as the conflict target in case - * the unique index is an expression index: - * - * ```ts - * import { sql } from 'kysely' - * - * await db - * .insertInto('pet') - * .values({ - * name: 'Catto', - * species: 'cat', - * owner_id: 3, - * }) - * .onConflict((oc) => oc - * .expression(sql`lower(name)`) - * .doUpdateSet({ species: 'hamster' }) - * ) - * .execute() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * insert into "pet" ("name", "species", "owner_id") - * values ($1, $2, $3) - * on conflict (lower(name)) - * do update set "species" = $4 - * ``` - * - * You can add a filter for the update statement like this: - * - * ```ts - * await db - * .insertInto('pet') - * .values({ - * name: 'Catto', - * species: 'cat', - * owner_id: 3, - * }) - * .onConflict((oc) => oc - * .column('name') - * .doUpdateSet({ species: 'hamster' }) - * .where('excluded.name', '!=', 'Catto') - * ) - * .execute() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * insert into "pet" ("name", "species", "owner_id") - * values ($1, $2, $3) - * on conflict ("name") - * do update set "species" = $4 - * where "excluded"."name" != $5 - * ``` - * - * You can create an `on conflict do nothing` clauses like this: - * - * ```ts - * await db - * .insertInto('pet') - * .values({ - * name: 'Catto', - * species: 'cat', - * owner_id: 3, - * }) - * .onConflict((oc) => oc - * .column('name') - * .doNothing() - * ) - * .execute() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * insert into "pet" ("name", "species", "owner_id") - * values ($1, $2, $3) - * on conflict ("name") do nothing - * ``` - * - * You can refer to the columns of the virtual `excluded` table - * in a type-safe way using a callback and the `ref` method of - * `ExpressionBuilder`: - * - * ```ts - * await db.insertInto('person') - * .values({ - * id: 1, - * first_name: 'John', - * last_name: 'Doe', - * gender: 'male', - * }) - * .onConflict(oc => oc - * .column('id') - * .doUpdateSet({ - * first_name: (eb) => eb.ref('excluded.first_name'), - * last_name: (eb) => eb.ref('excluded.last_name') - * }) - * ) - * .execute() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * insert into "person" ("id", "first_name", "last_name", "gender") - * values ($1, $2, $3, $4) - * on conflict ("id") - * do update set - * "first_name" = "excluded"."first_name", - * "last_name" = "excluded"."last_name" - * ``` - */ - onConflict(callback) { - return new _InsertQueryBuilder({ - ...this.#props, - queryNode: InsertQueryNode.cloneWith(this.#props.queryNode, { - onConflict: callback(new OnConflictBuilder({ - onConflictNode: OnConflictNode.create() - })).toOperationNode() - }) - }); - } - /** - * Adds `on duplicate key update` to the query. - * - * If you specify `on duplicate key update`, and a row is inserted that would cause - * a duplicate value in a unique index or primary key, an update of the old row occurs. - * - * This is only implemented by some dialects like MySQL. On most dialects you should - * use {@link onConflict} instead. - * - * ### Examples - * - * ```ts - * await db - * .insertInto('person') - * .values({ - * id: 1, - * first_name: 'John', - * last_name: 'Doe', - * gender: 'male', - * }) - * .onDuplicateKeyUpdate({ updated_at: new Date().toISOString() }) - * .execute() - * ``` - * - * The generated SQL (MySQL): - * - * ```sql - * insert into `person` (`id`, `first_name`, `last_name`, `gender`) - * values (?, ?, ?, ?) - * on duplicate key update `updated_at` = ? - * ``` - */ - onDuplicateKeyUpdate(update) { - return new _InsertQueryBuilder({ - ...this.#props, - queryNode: InsertQueryNode.cloneWith(this.#props.queryNode, { - onDuplicateKey: OnDuplicateKeyNode.create(parseUpdateObjectExpression(update)) - }) - }); - } - returning(selection) { - return new _InsertQueryBuilder({ - ...this.#props, - queryNode: QueryNode.cloneWithReturning(this.#props.queryNode, parseSelectArg(selection)) - }); - } - returningAll() { - return new _InsertQueryBuilder({ - ...this.#props, - queryNode: QueryNode.cloneWithReturning(this.#props.queryNode, parseSelectAll()) - }); - } - output(args) { - return new _InsertQueryBuilder({ - ...this.#props, - queryNode: QueryNode.cloneWithOutput(this.#props.queryNode, parseSelectArg(args)) - }); - } - outputAll(table) { - return new _InsertQueryBuilder({ - ...this.#props, - queryNode: QueryNode.cloneWithOutput(this.#props.queryNode, parseSelectAll(table)) - }); - } - /** - * Clears all `returning` clauses from the query. - * - * ### Examples - * - * ```ts - * await db.insertInto('person') - * .values({ first_name: 'James', last_name: 'Smith', gender: 'male' }) - * .returning(['first_name']) - * .clearReturning() - * .execute() - * ``` - * - * The generated SQL(PostgreSQL): - * - * ```sql - * insert into "person" ("first_name", "last_name", "gender") values ($1, $2, $3) - * ``` - */ - clearReturning() { - return new _InsertQueryBuilder({ - ...this.#props, - queryNode: QueryNode.cloneWithoutReturning(this.#props.queryNode) - }); - } - /** - * Simply calls the provided function passing `this` as the only argument. `$call` returns - * what the provided function returns. - * - * If you want to conditionally call a method on `this`, see - * the {@link $if} method. - * - * ### Examples - * - * The next example uses a helper function `log` to log a query: - * - * ```ts - * import type { Compilable } from 'kysely' - * - * function log(qb: T): T { - * console.log(qb.compile()) - * return qb - * } - * - * await db.insertInto('person') - * .values({ first_name: 'John', last_name: 'Doe', gender: 'male' }) - * .$call(log) - * .execute() - * ``` - */ - $call(func) { - return func(this); - } - /** - * Call `func(this)` if `condition` is true. - * - * This method is especially handy with optional selects. Any `returning` or `returningAll` - * method calls add columns as optional fields to the output type when called inside - * the `func` callback. This is because we can't know if those selections were actually - * made before running the code. - * - * You can also call any other methods inside the callback. - * - * ### Examples - * - * ```ts - * import type { NewPerson } from 'type-editor' // imaginary module - * - * async function insertPerson(values: NewPerson, returnLastName: boolean) { - * return await db - * .insertInto('person') - * .values(values) - * .returning(['id', 'first_name']) - * .$if(returnLastName, (qb) => qb.returning('last_name')) - * .executeTakeFirstOrThrow() - * } - * ``` - * - * Any selections added inside the `if` callback will be added as optional fields to the - * output type since we can't know if the selections were actually made before running - * the code. In the example above the return type of the `insertPerson` function is: - * - * ```ts - * Promise<{ - * id: number - * first_name: string - * last_name?: string - * }> - * ``` - */ - $if(condition, func) { - if (condition) { - return func(this); - } - return new _InsertQueryBuilder({ - ...this.#props - }); - } - /** - * Change the output type of the query. - * - * This method call doesn't change the SQL in any way. This methods simply - * returns a copy of this `InsertQueryBuilder` with a new output type. - */ - $castTo() { - return new _InsertQueryBuilder(this.#props); - } - /** - * Narrows (parts of) the output type of the query. - * - * Kysely tries to be as type-safe as possible, but in some cases we have to make - * compromises for better maintainability and compilation performance. At present, - * Kysely doesn't narrow the output type of the query based on {@link values} input - * when using {@link returning} or {@link returningAll}. - * - * This utility method is very useful for these situations, as it removes unncessary - * runtime assertion/guard code. Its input type is limited to the output type - * of the query, so you can't add a column that doesn't exist, or change a column's - * type to something that doesn't exist in its union type. - * - * ### Examples - * - * Turn this code: - * - * ```ts - * import type { Person } from 'type-editor' // imaginary module - * - * const person = await db.insertInto('person') - * .values({ - * first_name: 'John', - * last_name: 'Doe', - * gender: 'male', - * nullable_column: 'hell yeah!' - * }) - * .returningAll() - * .executeTakeFirstOrThrow() - * - * if (isWithNoNullValue(person)) { - * functionThatExpectsPersonWithNonNullValue(person) - * } - * - * function isWithNoNullValue(person: Person): person is Person & { nullable_column: string } { - * return person.nullable_column != null - * } - * ``` - * - * Into this: - * - * ```ts - * import type { NotNull } from 'kysely' - * - * const person = await db.insertInto('person') - * .values({ - * first_name: 'John', - * last_name: 'Doe', - * gender: 'male', - * nullable_column: 'hell yeah!' - * }) - * .returningAll() - * .$narrowType<{ nullable_column: NotNull }>() - * .executeTakeFirstOrThrow() - * - * functionThatExpectsPersonWithNonNullValue(person) - * ``` - */ - $narrowType() { - return new _InsertQueryBuilder(this.#props); - } - /** - * Asserts that query's output row type equals the given type `T`. - * - * This method can be used to simplify excessively complex types to make TypeScript happy - * and much faster. - * - * Kysely uses complex type magic to achieve its type safety. This complexity is sometimes too much - * for TypeScript and you get errors like this: - * - * ``` - * error TS2589: Type instantiation is excessively deep and possibly infinite. - * ``` - * - * In these case you can often use this method to help TypeScript a little bit. When you use this - * method to assert the output type of a query, Kysely can drop the complex output type that - * consists of multiple nested helper types and replace it with the simple asserted type. - * - * Using this method doesn't reduce type safety at all. You have to pass in a type that is - * structurally equal to the current type. - * - * ### Examples - * - * ```ts - * import type { NewPerson, NewPet, Species } from 'type-editor' // imaginary module - * - * async function insertPersonAndPet(person: NewPerson, pet: Omit) { - * return await db - * .with('new_person', (qb) => qb - * .insertInto('person') - * .values(person) - * .returning('id') - * .$assertType<{ id: number }>() - * ) - * .with('new_pet', (qb) => qb - * .insertInto('pet') - * .values((eb) => ({ - * owner_id: eb.selectFrom('new_person').select('id'), - * ...pet - * })) - * .returning(['name as pet_name', 'species']) - * .$assertType<{ pet_name: string, species: Species }>() - * ) - * .selectFrom(['new_person', 'new_pet']) - * .selectAll() - * .executeTakeFirstOrThrow() - * } - * ``` - */ - $assertType() { - return new _InsertQueryBuilder(this.#props); - } - /** - * Returns a copy of this InsertQueryBuilder instance with the given plugin installed. - */ - withPlugin(plugin) { - return new _InsertQueryBuilder({ - ...this.#props, - executor: this.#props.executor.withPlugin(plugin) - }); - } - toOperationNode() { - return this.#props.executor.transformQuery(this.#props.queryNode, this.#props.queryId); - } - compile() { - return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId); - } - /** - * Executes the query and returns an array of rows. - * - * Also see the {@link executeTakeFirst} and {@link executeTakeFirstOrThrow} methods. - */ - async execute() { - const compiledQuery = this.compile(); - const result = await this.#props.executor.executeQuery(compiledQuery); - const { adapter } = this.#props.executor; - const query = compiledQuery.query; - if (query.returning && adapter.supportsReturning || query.output && adapter.supportsOutput) { - return result.rows; - } - return [ - new InsertResult(result.insertId, result.numAffectedRows ?? BigInt(0)) - ]; - } - /** - * Executes the query and returns the first result or undefined if - * the query returned no result. - */ - async executeTakeFirst() { - const [result] = await this.execute(); - return result; - } - /** - * Executes the query and returns the first result or throws if - * the query returned no result. - * - * By default an instance of {@link NoResultError} is thrown, but you can - * provide a custom error class, or callback as the only argument to throw a different - * error. - */ - async executeTakeFirstOrThrow(errorConstructor = NoResultError) { - const result = await this.executeTakeFirst(); - if (result === void 0) { - const error50 = isNoResultErrorConstructor(errorConstructor) ? new errorConstructor(this.toOperationNode()) : errorConstructor(this.toOperationNode()); - throw error50; - } - return result; - } - async *stream(chunkSize = 100) { - const compiledQuery = this.compile(); - const stream = this.#props.executor.stream(compiledQuery, chunkSize); - for await (const item of stream) { - yield* item.rows; - } - } - async explain(format2, options) { - const builder = new _InsertQueryBuilder({ - ...this.#props, - queryNode: QueryNode.cloneWithExplain(this.#props.queryNode, format2, options) - }); - return await builder.execute(); - } - }; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/delete-result.js -var DeleteResult; -var init_delete_result = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/delete-result.js"() { - DeleteResult = class { - numDeletedRows; - constructor(numDeletedRows) { - this.numDeletedRows = numDeletedRows; - } - }; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/limit-node.js -var LimitNode; -var init_limit_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/limit-node.js"() { - init_object_utils(); - LimitNode = freeze2({ - is(node) { - return node.kind === "LimitNode"; - }, - create(limit) { - return freeze2({ - kind: "LimitNode", - limit - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/delete-query-builder.js -var _a3, DeleteQueryBuilder; -var init_delete_query_builder = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/delete-query-builder.js"() { - init_join_parser(); - init_table_parser(); - init_select_parser(); - init_query_node(); - init_object_utils(); - init_no_result_error(); - init_delete_result(); - init_delete_query_node(); - init_limit_node(); - init_order_by_parser(); - init_binary_operation_parser(); - init_value_parser(); - init_top_parser(); - DeleteQueryBuilder = class { - #props; - constructor(props) { - this.#props = freeze2(props); - } - where(...args) { - return new _a3({ - ...this.#props, - queryNode: QueryNode.cloneWithWhere(this.#props.queryNode, parseValueBinaryOperationOrExpression(args)) - }); - } - whereRef(lhs, op2, rhs) { - return new _a3({ - ...this.#props, - queryNode: QueryNode.cloneWithWhere(this.#props.queryNode, parseReferentialBinaryOperation(lhs, op2, rhs)) - }); - } - clearWhere() { - return new _a3({ - ...this.#props, - queryNode: QueryNode.cloneWithoutWhere(this.#props.queryNode) - }); - } - /** - * Changes a `delete from` query into a `delete top from` query. - * - * `top` clause is only supported by some dialects like MS SQL Server. - * - * ### Examples - * - * Delete the first 5 rows: - * - * ```ts - * await db - * .deleteFrom('person') - * .top(5) - * .where('age', '>', 18) - * .executeTakeFirstOrThrow() - * ``` - * - * The generated SQL (MS SQL Server): - * - * ```sql - * delete top(5) from "person" where "age" > @1 - * ``` - * - * Delete the first 50% of rows: - * - * ```ts - * await db - * .deleteFrom('person') - * .top(50, 'percent') - * .where('age', '>', 18) - * .executeTakeFirstOrThrow() - * ``` - * - * The generated SQL (MS SQL Server): - * - * ```sql - * delete top(50) percent from "person" where "age" > @1 - * ``` - */ - top(expression, modifiers) { - return new _a3({ - ...this.#props, - queryNode: QueryNode.cloneWithTop(this.#props.queryNode, parseTop(expression, modifiers)) - }); - } - using(tables) { - return new _a3({ - ...this.#props, - queryNode: DeleteQueryNode.cloneWithUsing(this.#props.queryNode, parseTableExpressionOrList(tables)) - }); - } - innerJoin(...args) { - return this.#join("InnerJoin", args); - } - leftJoin(...args) { - return this.#join("LeftJoin", args); - } - rightJoin(...args) { - return this.#join("RightJoin", args); - } - fullJoin(...args) { - return this.#join("FullJoin", args); - } - #join(joinType, args) { - return new _a3({ - ...this.#props, - queryNode: QueryNode.cloneWithJoin(this.#props.queryNode, parseJoin(joinType, args)) - }); - } - returning(selection) { - return new _a3({ - ...this.#props, - queryNode: QueryNode.cloneWithReturning(this.#props.queryNode, parseSelectArg(selection)) - }); - } - returningAll(table) { - return new _a3({ - ...this.#props, - queryNode: QueryNode.cloneWithReturning(this.#props.queryNode, parseSelectAll(table)) - }); - } - output(args) { - return new _a3({ - ...this.#props, - queryNode: QueryNode.cloneWithOutput(this.#props.queryNode, parseSelectArg(args)) - }); - } - outputAll(table) { - return new _a3({ - ...this.#props, - queryNode: QueryNode.cloneWithOutput(this.#props.queryNode, parseSelectAll(table)) - }); - } - /** - * Clears all `returning` clauses from the query. - * - * ### Examples - * - * ```ts - * await db.deleteFrom('pet') - * .returningAll() - * .where('name', '=', 'Max') - * .clearReturning() - * .execute() - * ``` - * - * The generated SQL(PostgreSQL): - * - * ```sql - * delete from "pet" where "name" = "Max" - * ``` - */ - clearReturning() { - return new _a3({ - ...this.#props, - queryNode: QueryNode.cloneWithoutReturning(this.#props.queryNode) - }); - } - /** - * Clears the `limit` clause from the query. - * - * ### Examples - * - * ```ts - * await db.deleteFrom('pet') - * .returningAll() - * .where('name', '=', 'Max') - * .limit(5) - * .clearLimit() - * .execute() - * ``` - * - * The generated SQL(PostgreSQL): - * - * ```sql - * delete from "pet" where "name" = "Max" returning * - * ``` - */ - clearLimit() { - return new _a3({ - ...this.#props, - queryNode: DeleteQueryNode.cloneWithoutLimit(this.#props.queryNode) - }); - } - orderBy(...args) { - return new _a3({ - ...this.#props, - queryNode: QueryNode.cloneWithOrderByItems(this.#props.queryNode, parseOrderBy(args)) - }); - } - clearOrderBy() { - return new _a3({ - ...this.#props, - queryNode: QueryNode.cloneWithoutOrderBy(this.#props.queryNode) - }); - } - /** - * Adds a limit clause to the query. - * - * A limit clause in a delete query is only supported by some dialects - * like MySQL. - * - * ### Examples - * - * Delete 5 oldest items in a table: - * - * ```ts - * await db - * .deleteFrom('pet') - * .orderBy('created_at') - * .limit(5) - * .execute() - * ``` - * - * The generated SQL (MySQL): - * - * ```sql - * delete from `pet` order by `created_at` limit ? - * ``` - */ - limit(limit) { - return new _a3({ - ...this.#props, - queryNode: DeleteQueryNode.cloneWithLimit(this.#props.queryNode, LimitNode.create(parseValueExpression(limit))) - }); - } - /** - * This can be used to add any additional SQL to the end of the query. - * - * ### Examples - * - * ```ts - * import { sql } from 'kysely' - * - * await db.deleteFrom('person') - * .where('first_name', '=', 'John') - * .modifyEnd(sql`-- This is a comment`) - * .execute() - * ``` - * - * The generated SQL (MySQL): - * - * ```sql - * delete from `person` - * where `first_name` = "John" -- This is a comment - * ``` - */ - modifyEnd(modifier) { - return new _a3({ - ...this.#props, - queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, modifier.toOperationNode()) - }); - } - /** - * Simply calls the provided function passing `this` as the only argument. `$call` returns - * what the provided function returns. - * - * If you want to conditionally call a method on `this`, see - * the {@link $if} method. - * - * ### Examples - * - * The next example uses a helper function `log` to log a query: - * - * ```ts - * import type { Compilable } from 'kysely' - * - * function log(qb: T): T { - * console.log(qb.compile()) - * return qb - * } - * - * await db.deleteFrom('person') - * .$call(log) - * .execute() - * ``` - */ - $call(func) { - return func(this); - } - /** - * Call `func(this)` if `condition` is true. - * - * This method is especially handy with optional selects. Any `returning` or `returningAll` - * method calls add columns as optional fields to the output type when called inside - * the `func` callback. This is because we can't know if those selections were actually - * made before running the code. - * - * You can also call any other methods inside the callback. - * - * ### Examples - * - * ```ts - * async function deletePerson(id: number, returnLastName: boolean) { - * return await db - * .deleteFrom('person') - * .where('id', '=', id) - * .returning(['id', 'first_name']) - * .$if(returnLastName, (qb) => qb.returning('last_name')) - * .executeTakeFirstOrThrow() - * } - * ``` - * - * Any selections added inside the `if` callback will be added as optional fields to the - * output type since we can't know if the selections were actually made before running - * the code. In the example above the return type of the `deletePerson` function is: - * - * ```ts - * Promise<{ - * id: number - * first_name: string - * last_name?: string - * }> - * ``` - */ - $if(condition, func) { - if (condition) { - return func(this); - } - return new _a3({ - ...this.#props - }); - } - /** - * Change the output type of the query. - * - * This method call doesn't change the SQL in any way. This methods simply - * returns a copy of this `DeleteQueryBuilder` with a new output type. - */ - $castTo() { - return new _a3(this.#props); - } - /** - * Narrows (parts of) the output type of the query. - * - * Kysely tries to be as type-safe as possible, but in some cases we have to make - * compromises for better maintainability and compilation performance. At present, - * Kysely doesn't narrow the output type of the query when using {@link where} and {@link returning} or {@link returningAll}. - * - * This utility method is very useful for these situations, as it removes unncessary - * runtime assertion/guard code. Its input type is limited to the output type - * of the query, so you can't add a column that doesn't exist, or change a column's - * type to something that doesn't exist in its union type. - * - * ### Examples - * - * Turn this code: - * - * ```ts - * import type { Person } from 'type-editor' // imaginary module - * - * const person = await db.deleteFrom('person') - * .where('id', '=', 3) - * .where('nullable_column', 'is not', null) - * .returningAll() - * .executeTakeFirstOrThrow() - * - * if (isWithNoNullValue(person)) { - * functionThatExpectsPersonWithNonNullValue(person) - * } - * - * function isWithNoNullValue(person: Person): person is Person & { nullable_column: string } { - * return person.nullable_column != null - * } - * ``` - * - * Into this: - * - * ```ts - * import type { NotNull } from 'kysely' - * - * const person = await db.deleteFrom('person') - * .where('id', '=', 3) - * .where('nullable_column', 'is not', null) - * .returningAll() - * .$narrowType<{ nullable_column: NotNull }>() - * .executeTakeFirstOrThrow() - * - * functionThatExpectsPersonWithNonNullValue(person) - * ``` - */ - $narrowType() { - return new _a3(this.#props); - } - /** - * Asserts that query's output row type equals the given type `T`. - * - * This method can be used to simplify excessively complex types to make TypeScript happy - * and much faster. - * - * Kysely uses complex type magic to achieve its type safety. This complexity is sometimes too much - * for TypeScript and you get errors like this: - * - * ``` - * error TS2589: Type instantiation is excessively deep and possibly infinite. - * ``` - * - * In these case you can often use this method to help TypeScript a little bit. When you use this - * method to assert the output type of a query, Kysely can drop the complex output type that - * consists of multiple nested helper types and replace it with the simple asserted type. - * - * Using this method doesn't reduce type safety at all. You have to pass in a type that is - * structurally equal to the current type. - * - * ### Examples - * - * ```ts - * import type { Species } from 'type-editor' // imaginary module - * - * async function deletePersonAndPets(personId: number) { - * return await db - * .with('deleted_person', (qb) => qb - * .deleteFrom('person') - * .where('id', '=', personId) - * .returning('first_name') - * .$assertType<{ first_name: string }>() - * ) - * .with('deleted_pets', (qb) => qb - * .deleteFrom('pet') - * .where('owner_id', '=', personId) - * .returning(['name as pet_name', 'species']) - * .$assertType<{ pet_name: string, species: Species }>() - * ) - * .selectFrom(['deleted_person', 'deleted_pets']) - * .selectAll() - * .execute() - * } - * ``` - */ - $assertType() { - return new _a3(this.#props); - } - /** - * Returns a copy of this DeleteQueryBuilder instance with the given plugin installed. - */ - withPlugin(plugin) { - return new _a3({ - ...this.#props, - executor: this.#props.executor.withPlugin(plugin) - }); - } - toOperationNode() { - return this.#props.executor.transformQuery(this.#props.queryNode, this.#props.queryId); - } - compile() { - return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId); - } - /** - * Executes the query and returns an array of rows. - * - * Also see the {@link executeTakeFirst} and {@link executeTakeFirstOrThrow} methods. - */ - async execute() { - const compiledQuery = this.compile(); - const result = await this.#props.executor.executeQuery(compiledQuery); - const { adapter } = this.#props.executor; - const query = compiledQuery.query; - if (query.returning && adapter.supportsReturning || query.output && adapter.supportsOutput) { - return result.rows; - } - return [new DeleteResult(result.numAffectedRows ?? BigInt(0))]; - } - /** - * Executes the query and returns the first result or undefined if - * the query returned no result. - */ - async executeTakeFirst() { - const [result] = await this.execute(); - return result; - } - /** - * Executes the query and returns the first result or throws if - * the query returned no result. - * - * By default an instance of {@link NoResultError} is thrown, but you can - * provide a custom error class, or callback as the only argument to throw a different - * error. - */ - async executeTakeFirstOrThrow(errorConstructor = NoResultError) { - const result = await this.executeTakeFirst(); - if (result === void 0) { - const error50 = isNoResultErrorConstructor(errorConstructor) ? new errorConstructor(this.toOperationNode()) : errorConstructor(this.toOperationNode()); - throw error50; - } - return result; - } - async *stream(chunkSize = 100) { - const compiledQuery = this.compile(); - const stream = this.#props.executor.stream(compiledQuery, chunkSize); - for await (const item of stream) { - yield* item.rows; - } - } - async explain(format2, options) { - const builder = new _a3({ - ...this.#props, - queryNode: QueryNode.cloneWithExplain(this.#props.queryNode, format2, options) - }); - return await builder.execute(); - } - }; - _a3 = DeleteQueryBuilder; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/update-result.js -var UpdateResult; -var init_update_result = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/update-result.js"() { - UpdateResult = class { - /** - * The number of rows the update query updated (even if not changed). - */ - numUpdatedRows; - /** - * The number of rows the update query changed. - * - * This is **optional** and only supported in dialects such as MySQL. - * You would probably use {@link numUpdatedRows} in most cases. - */ - numChangedRows; - constructor(numUpdatedRows, numChangedRows) { - this.numUpdatedRows = numUpdatedRows; - this.numChangedRows = numChangedRows; - } - }; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/update-query-builder.js -var _a4, UpdateQueryBuilder; -var init_update_query_builder = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/update-query-builder.js"() { - init_join_parser(); - init_table_parser(); - init_select_parser(); - init_query_node(); - init_update_query_node(); - init_update_set_parser(); - init_object_utils(); - init_update_result(); - init_no_result_error(); - init_binary_operation_parser(); - init_value_parser(); - init_limit_node(); - init_top_parser(); - init_order_by_parser(); - UpdateQueryBuilder = class { - #props; - constructor(props) { - this.#props = freeze2(props); - } - where(...args) { - return new _a4({ - ...this.#props, - queryNode: QueryNode.cloneWithWhere(this.#props.queryNode, parseValueBinaryOperationOrExpression(args)) - }); - } - whereRef(lhs, op2, rhs) { - return new _a4({ - ...this.#props, - queryNode: QueryNode.cloneWithWhere(this.#props.queryNode, parseReferentialBinaryOperation(lhs, op2, rhs)) - }); - } - clearWhere() { - return new _a4({ - ...this.#props, - queryNode: QueryNode.cloneWithoutWhere(this.#props.queryNode) - }); - } - /** - * Changes an `update` query into a `update top` query. - * - * `top` clause is only supported by some dialects like MS SQL Server. - * - * ### Examples - * - * Update the first row: - * - * ```ts - * await db.updateTable('person') - * .top(1) - * .set({ first_name: 'Foo' }) - * .where('age', '>', 18) - * .executeTakeFirstOrThrow() - * ``` - * - * The generated SQL (MS SQL Server): - * - * ```sql - * update top(1) "person" set "first_name" = @1 where "age" > @2 - * ``` - * - * Update the 50% first rows: - * - * ```ts - * await db.updateTable('person') - * .top(50, 'percent') - * .set({ first_name: 'Foo' }) - * .where('age', '>', 18) - * .executeTakeFirstOrThrow() - * ``` - * - * The generated SQL (MS SQL Server): - * - * ```sql - * update top(50) percent "person" set "first_name" = @1 where "age" > @2 - * ``` - */ - top(expression, modifiers) { - return new _a4({ - ...this.#props, - queryNode: QueryNode.cloneWithTop(this.#props.queryNode, parseTop(expression, modifiers)) - }); - } - from(from) { - return new _a4({ - ...this.#props, - queryNode: UpdateQueryNode.cloneWithFromItems(this.#props.queryNode, parseTableExpressionOrList(from)) - }); - } - innerJoin(...args) { - return this.#join("InnerJoin", args); - } - leftJoin(...args) { - return this.#join("LeftJoin", args); - } - rightJoin(...args) { - return this.#join("RightJoin", args); - } - fullJoin(...args) { - return this.#join("FullJoin", args); - } - #join(joinType, args) { - return new _a4({ - ...this.#props, - queryNode: QueryNode.cloneWithJoin(this.#props.queryNode, parseJoin(joinType, args)) - }); - } - orderBy(...args) { - return new _a4({ - ...this.#props, - queryNode: QueryNode.cloneWithOrderByItems(this.#props.queryNode, parseOrderBy(args)) - }); - } - clearOrderBy() { - return new _a4({ - ...this.#props, - queryNode: QueryNode.cloneWithoutOrderBy(this.#props.queryNode) - }); - } - /** - * Adds a limit clause to the update query for supported databases, such as MySQL. - * - * ### Examples - * - * Update the first 2 rows in the 'person' table: - * - * ```ts - * await db - * .updateTable('person') - * .set({ first_name: 'Foo' }) - * .limit(2) - * .execute() - * ``` - * - * The generated SQL (MySQL): - * - * ```sql - * update `person` set `first_name` = ? limit ? - * ``` - */ - limit(limit) { - return new _a4({ - ...this.#props, - queryNode: UpdateQueryNode.cloneWithLimit(this.#props.queryNode, LimitNode.create(parseValueExpression(limit))) - }); - } - set(...args) { - return new _a4({ - ...this.#props, - queryNode: UpdateQueryNode.cloneWithUpdates(this.#props.queryNode, parseUpdate(...args)) - }); - } - returning(selection) { - return new _a4({ - ...this.#props, - queryNode: QueryNode.cloneWithReturning(this.#props.queryNode, parseSelectArg(selection)) - }); - } - returningAll(table) { - return new _a4({ - ...this.#props, - queryNode: QueryNode.cloneWithReturning(this.#props.queryNode, parseSelectAll(table)) - }); - } - output(args) { - return new _a4({ - ...this.#props, - queryNode: QueryNode.cloneWithOutput(this.#props.queryNode, parseSelectArg(args)) - }); - } - outputAll(table) { - return new _a4({ - ...this.#props, - queryNode: QueryNode.cloneWithOutput(this.#props.queryNode, parseSelectAll(table)) - }); - } - /** - * This can be used to add any additional SQL to the end of the query. - * - * ### Examples - * - * ```ts - * import { sql } from 'kysely' - * - * await db.updateTable('person') - * .set({ age: 39 }) - * .where('first_name', '=', 'John') - * .modifyEnd(sql.raw('-- This is a comment')) - * .execute() - * ``` - * - * The generated SQL (MySQL): - * - * ```sql - * update `person` - * set `age` = 39 - * where `first_name` = "John" -- This is a comment - * ``` - */ - modifyEnd(modifier) { - return new _a4({ - ...this.#props, - queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, modifier.toOperationNode()) - }); - } - /** - * Clears all `returning` clauses from the query. - * - * ### Examples - * - * ```ts - * db.updateTable('person') - * .returningAll() - * .set({ age: 39 }) - * .where('first_name', '=', 'John') - * .clearReturning() - * ``` - * - * The generated SQL(PostgreSQL): - * - * ```sql - * update "person" set "age" = 39 where "first_name" = "John" - * ``` - */ - clearReturning() { - return new _a4({ - ...this.#props, - queryNode: QueryNode.cloneWithoutReturning(this.#props.queryNode) - }); - } - /** - * Simply calls the provided function passing `this` as the only argument. `$call` returns - * what the provided function returns. - * - * If you want to conditionally call a method on `this`, see - * the {@link $if} method. - * - * ### Examples - * - * The next example uses a helper function `log` to log a query: - * - * ```ts - * import type { Compilable } from 'kysely' - * import type { PersonUpdate } from 'type-editor' // imaginary module - * - * function log(qb: T): T { - * console.log(qb.compile()) - * return qb - * } - * - * const values = { - * first_name: 'John', - * } satisfies PersonUpdate - * - * db.updateTable('person') - * .set(values) - * .$call(log) - * .execute() - * ``` - */ - $call(func) { - return func(this); - } - /** - * Call `func(this)` if `condition` is true. - * - * This method is especially handy with optional selects. Any `returning` or `returningAll` - * method calls add columns as optional fields to the output type when called inside - * the `func` callback. This is because we can't know if those selections were actually - * made before running the code. - * - * You can also call any other methods inside the callback. - * - * ### Examples - * - * ```ts - * import type { PersonUpdate } from 'type-editor' // imaginary module - * - * async function updatePerson(id: number, updates: PersonUpdate, returnLastName: boolean) { - * return await db - * .updateTable('person') - * .set(updates) - * .where('id', '=', id) - * .returning(['id', 'first_name']) - * .$if(returnLastName, (qb) => qb.returning('last_name')) - * .executeTakeFirstOrThrow() - * } - * ``` - * - * Any selections added inside the `if` callback will be added as optional fields to the - * output type since we can't know if the selections were actually made before running - * the code. In the example above the return type of the `updatePerson` function is: - * - * ```ts - * Promise<{ - * id: number - * first_name: string - * last_name?: string - * }> - * ``` - */ - $if(condition, func) { - if (condition) { - return func(this); - } - return new _a4({ - ...this.#props - }); - } - /** - * Change the output type of the query. - * - * This method call doesn't change the SQL in any way. This methods simply - * returns a copy of this `UpdateQueryBuilder` with a new output type. - */ - $castTo() { - return new _a4(this.#props); - } - /** - * Narrows (parts of) the output type of the query. - * - * Kysely tries to be as type-safe as possible, but in some cases we have to make - * compromises for better maintainability and compilation performance. At present, - * Kysely doesn't narrow the output type of the query based on {@link set} input - * when using {@link where} and/or {@link returning} or {@link returningAll}. - * - * This utility method is very useful for these situations, as it removes unncessary - * runtime assertion/guard code. Its input type is limited to the output type - * of the query, so you can't add a column that doesn't exist, or change a column's - * type to something that doesn't exist in its union type. - * - * ### Examples - * - * Turn this code: - * - * ```ts - * import type { Person } from 'type-editor' // imaginary module - * - * const id = 1 - * const now = new Date().toISOString() - * - * const person = await db.updateTable('person') - * .set({ deleted_at: now }) - * .where('id', '=', id) - * .where('nullable_column', 'is not', null) - * .returningAll() - * .executeTakeFirstOrThrow() - * - * if (isWithNoNullValue(person)) { - * functionThatExpectsPersonWithNonNullValue(person) - * } - * - * function isWithNoNullValue(person: Person): person is Person & { nullable_column: string } { - * return person.nullable_column != null - * } - * ``` - * - * Into this: - * - * ```ts - * import type { NotNull } from 'kysely' - * - * const id = 1 - * const now = new Date().toISOString() - * - * const person = await db.updateTable('person') - * .set({ deleted_at: now }) - * .where('id', '=', id) - * .where('nullable_column', 'is not', null) - * .returningAll() - * .$narrowType<{ deleted_at: Date; nullable_column: NotNull }>() - * .executeTakeFirstOrThrow() - * - * functionThatExpectsPersonWithNonNullValue(person) - * ``` - */ - $narrowType() { - return new _a4(this.#props); - } - /** - * Asserts that query's output row type equals the given type `T`. - * - * This method can be used to simplify excessively complex types to make TypeScript happy - * and much faster. - * - * Kysely uses complex type magic to achieve its type safety. This complexity is sometimes too much - * for TypeScript and you get errors like this: - * - * ``` - * error TS2589: Type instantiation is excessively deep and possibly infinite. - * ``` - * - * In these case you can often use this method to help TypeScript a little bit. When you use this - * method to assert the output type of a query, Kysely can drop the complex output type that - * consists of multiple nested helper types and replace it with the simple asserted type. - * - * Using this method doesn't reduce type safety at all. You have to pass in a type that is - * structurally equal to the current type. - * - * ### Examples - * - * ```ts - * import type { PersonUpdate, PetUpdate, Species } from 'type-editor' // imaginary module - * - * const person = { - * id: 1, - * gender: 'other', - * } satisfies PersonUpdate - * - * const pet = { - * name: 'Fluffy', - * } satisfies PetUpdate - * - * const result = await db - * .with('updated_person', (qb) => qb - * .updateTable('person') - * .set(person) - * .where('id', '=', person.id) - * .returning('first_name') - * .$assertType<{ first_name: string }>() - * ) - * .with('updated_pet', (qb) => qb - * .updateTable('pet') - * .set(pet) - * .where('owner_id', '=', person.id) - * .returning(['name as pet_name', 'species']) - * .$assertType<{ pet_name: string, species: Species }>() - * ) - * .selectFrom(['updated_person', 'updated_pet']) - * .selectAll() - * .executeTakeFirstOrThrow() - * ``` - */ - $assertType() { - return new _a4(this.#props); - } - /** - * Returns a copy of this UpdateQueryBuilder instance with the given plugin installed. - */ - withPlugin(plugin) { - return new _a4({ - ...this.#props, - executor: this.#props.executor.withPlugin(plugin) - }); - } - toOperationNode() { - return this.#props.executor.transformQuery(this.#props.queryNode, this.#props.queryId); - } - compile() { - return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId); - } - /** - * Executes the query and returns an array of rows. - * - * Also see the {@link executeTakeFirst} and {@link executeTakeFirstOrThrow} methods. - */ - async execute() { - const compiledQuery = this.compile(); - const result = await this.#props.executor.executeQuery(compiledQuery); - const { adapter } = this.#props.executor; - const query = compiledQuery.query; - if (query.returning && adapter.supportsReturning || query.output && adapter.supportsOutput) { - return result.rows; - } - return [ - new UpdateResult(result.numAffectedRows ?? BigInt(0), result.numChangedRows) - ]; - } - /** - * Executes the query and returns the first result or undefined if - * the query returned no result. - */ - async executeTakeFirst() { - const [result] = await this.execute(); - return result; - } - /** - * Executes the query and returns the first result or throws if - * the query returned no result. - * - * By default an instance of {@link NoResultError} is thrown, but you can - * provide a custom error class, or callback as the only argument to throw a different - * error. - */ - async executeTakeFirstOrThrow(errorConstructor = NoResultError) { - const result = await this.executeTakeFirst(); - if (result === void 0) { - const error50 = isNoResultErrorConstructor(errorConstructor) ? new errorConstructor(this.toOperationNode()) : errorConstructor(this.toOperationNode()); - throw error50; - } - return result; - } - async *stream(chunkSize = 100) { - const compiledQuery = this.compile(); - const stream = this.#props.executor.stream(compiledQuery, chunkSize); - for await (const item of stream) { - yield* item.rows; - } - } - async explain(format2, options) { - const builder = new _a4({ - ...this.#props, - queryNode: QueryNode.cloneWithExplain(this.#props.queryNode, format2, options) - }); - return await builder.execute(); - } - }; - _a4 = UpdateQueryBuilder; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/common-table-expression-name-node.js -var CommonTableExpressionNameNode; -var init_common_table_expression_name_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/common-table-expression-name-node.js"() { - init_object_utils(); - init_column_node(); - init_table_node(); - CommonTableExpressionNameNode = freeze2({ - is(node) { - return node.kind === "CommonTableExpressionNameNode"; - }, - create(tableName, columnNames) { - return freeze2({ - kind: "CommonTableExpressionNameNode", - table: TableNode.create(tableName), - columns: columnNames ? freeze2(columnNames.map(ColumnNode.create)) : void 0 - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/common-table-expression-node.js -var CommonTableExpressionNode; -var init_common_table_expression_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/common-table-expression-node.js"() { - init_object_utils(); - CommonTableExpressionNode = freeze2({ - is(node) { - return node.kind === "CommonTableExpressionNode"; - }, - create(name, expression) { - return freeze2({ - kind: "CommonTableExpressionNode", - name, - expression - }); - }, - cloneWith(node, props) { - return freeze2({ - ...node, - ...props - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/cte-builder.js -var CTEBuilder; -var init_cte_builder = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/cte-builder.js"() { - init_common_table_expression_node(); - init_object_utils(); - CTEBuilder = class _CTEBuilder { - #props; - constructor(props) { - this.#props = freeze2(props); - } - /** - * Makes the common table expression materialized. - */ - materialized() { - return new _CTEBuilder({ - ...this.#props, - node: CommonTableExpressionNode.cloneWith(this.#props.node, { - materialized: true - }) - }); - } - /** - * Makes the common table expression not materialized. - */ - notMaterialized() { - return new _CTEBuilder({ - ...this.#props, - node: CommonTableExpressionNode.cloneWith(this.#props.node, { - materialized: false - }) - }); - } - toOperationNode() { - return this.#props.node; - } - }; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/with-parser.js -function parseCommonTableExpression(nameOrBuilderCallback, expression) { - const expressionNode = expression(createQueryCreator()).toOperationNode(); - if (isFunction(nameOrBuilderCallback)) { - return nameOrBuilderCallback(cteBuilderFactory(expressionNode)).toOperationNode(); - } - return CommonTableExpressionNode.create(parseCommonTableExpressionName(nameOrBuilderCallback), expressionNode); -} -function cteBuilderFactory(expressionNode) { - return (name) => { - return new CTEBuilder({ - node: CommonTableExpressionNode.create(parseCommonTableExpressionName(name), expressionNode) - }); - }; -} -function parseCommonTableExpressionName(name) { - if (name.includes("(")) { - const parts = name.split(/[\(\)]/); - const table = parts[0]; - const columns = parts[1].split(",").map((it) => it.trim()); - return CommonTableExpressionNameNode.create(table, columns); - } else { - return CommonTableExpressionNameNode.create(name); - } -} -var init_with_parser = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/with-parser.js"() { - init_common_table_expression_name_node(); - init_parse_utils2(); - init_object_utils(); - init_cte_builder(); - init_common_table_expression_node(); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/with-node.js -var WithNode; -var init_with_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/with-node.js"() { - init_object_utils(); - WithNode = freeze2({ - is(node) { - return node.kind === "WithNode"; - }, - create(expression, params) { - return freeze2({ - kind: "WithNode", - expressions: freeze2([expression]), - ...params - }); - }, - cloneWithExpression(withNode, expression) { - return freeze2({ - ...withNode, - expressions: freeze2([...withNode.expressions, expression]) - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/random-string.js -function randomString2(length) { - let chars = ""; - for (let i5 = 0; i5 < length; ++i5) { - chars += randomChar(); - } - return chars; -} -function randomChar() { - return CHARS[~~(Math.random() * CHARS.length)]; -} -var CHARS; -var init_random_string = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/random-string.js"() { - CHARS = [ - "A", - "B", - "C", - "D", - "E", - "F", - "G", - "H", - "I", - "J", - "K", - "L", - "M", - "N", - "O", - "P", - "Q", - "R", - "S", - "T", - "U", - "V", - "W", - "X", - "Y", - "Z", - "a", - "b", - "c", - "d", - "e", - "f", - "g", - "h", - "i", - "j", - "k", - "l", - "m", - "n", - "o", - "p", - "q", - "r", - "s", - "t", - "u", - "v", - "w", - "x", - "y", - "z", - "0", - "1", - "2", - "3", - "4", - "5", - "6", - "7", - "8", - "9" - ]; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/query-id.js -function createQueryId() { - return new LazyQueryId(); -} -var LazyQueryId; -var init_query_id = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/query-id.js"() { - init_random_string(); - LazyQueryId = class { - #queryId; - get queryId() { - if (this.#queryId === void 0) { - this.#queryId = randomString2(8); - } - return this.#queryId; - } - }; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/require-all-props.js -function requireAllProps(obj) { - return obj; -} -var init_require_all_props = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/require-all-props.js"() { - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/operation-node-transformer.js -var OperationNodeTransformer; -var init_operation_node_transformer = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/operation-node-transformer.js"() { - init_object_utils(); - init_require_all_props(); - OperationNodeTransformer = class { - nodeStack = []; - #transformers = freeze2({ - AliasNode: this.transformAlias.bind(this), - ColumnNode: this.transformColumn.bind(this), - IdentifierNode: this.transformIdentifier.bind(this), - SchemableIdentifierNode: this.transformSchemableIdentifier.bind(this), - RawNode: this.transformRaw.bind(this), - ReferenceNode: this.transformReference.bind(this), - SelectQueryNode: this.transformSelectQuery.bind(this), - SelectionNode: this.transformSelection.bind(this), - TableNode: this.transformTable.bind(this), - FromNode: this.transformFrom.bind(this), - SelectAllNode: this.transformSelectAll.bind(this), - AndNode: this.transformAnd.bind(this), - OrNode: this.transformOr.bind(this), - ValueNode: this.transformValue.bind(this), - ValueListNode: this.transformValueList.bind(this), - PrimitiveValueListNode: this.transformPrimitiveValueList.bind(this), - ParensNode: this.transformParens.bind(this), - JoinNode: this.transformJoin.bind(this), - OperatorNode: this.transformOperator.bind(this), - WhereNode: this.transformWhere.bind(this), - InsertQueryNode: this.transformInsertQuery.bind(this), - DeleteQueryNode: this.transformDeleteQuery.bind(this), - ReturningNode: this.transformReturning.bind(this), - CreateTableNode: this.transformCreateTable.bind(this), - AddColumnNode: this.transformAddColumn.bind(this), - ColumnDefinitionNode: this.transformColumnDefinition.bind(this), - DropTableNode: this.transformDropTable.bind(this), - DataTypeNode: this.transformDataType.bind(this), - OrderByNode: this.transformOrderBy.bind(this), - OrderByItemNode: this.transformOrderByItem.bind(this), - GroupByNode: this.transformGroupBy.bind(this), - GroupByItemNode: this.transformGroupByItem.bind(this), - UpdateQueryNode: this.transformUpdateQuery.bind(this), - ColumnUpdateNode: this.transformColumnUpdate.bind(this), - LimitNode: this.transformLimit.bind(this), - OffsetNode: this.transformOffset.bind(this), - OnConflictNode: this.transformOnConflict.bind(this), - OnDuplicateKeyNode: this.transformOnDuplicateKey.bind(this), - CreateIndexNode: this.transformCreateIndex.bind(this), - DropIndexNode: this.transformDropIndex.bind(this), - ListNode: this.transformList.bind(this), - PrimaryKeyConstraintNode: this.transformPrimaryKeyConstraint.bind(this), - UniqueConstraintNode: this.transformUniqueConstraint.bind(this), - ReferencesNode: this.transformReferences.bind(this), - CheckConstraintNode: this.transformCheckConstraint.bind(this), - WithNode: this.transformWith.bind(this), - CommonTableExpressionNode: this.transformCommonTableExpression.bind(this), - CommonTableExpressionNameNode: this.transformCommonTableExpressionName.bind(this), - HavingNode: this.transformHaving.bind(this), - CreateSchemaNode: this.transformCreateSchema.bind(this), - DropSchemaNode: this.transformDropSchema.bind(this), - AlterTableNode: this.transformAlterTable.bind(this), - DropColumnNode: this.transformDropColumn.bind(this), - RenameColumnNode: this.transformRenameColumn.bind(this), - AlterColumnNode: this.transformAlterColumn.bind(this), - ModifyColumnNode: this.transformModifyColumn.bind(this), - AddConstraintNode: this.transformAddConstraint.bind(this), - DropConstraintNode: this.transformDropConstraint.bind(this), - RenameConstraintNode: this.transformRenameConstraint.bind(this), - ForeignKeyConstraintNode: this.transformForeignKeyConstraint.bind(this), - CreateViewNode: this.transformCreateView.bind(this), - RefreshMaterializedViewNode: this.transformRefreshMaterializedView.bind(this), - DropViewNode: this.transformDropView.bind(this), - GeneratedNode: this.transformGenerated.bind(this), - DefaultValueNode: this.transformDefaultValue.bind(this), - OnNode: this.transformOn.bind(this), - ValuesNode: this.transformValues.bind(this), - SelectModifierNode: this.transformSelectModifier.bind(this), - CreateTypeNode: this.transformCreateType.bind(this), - DropTypeNode: this.transformDropType.bind(this), - ExplainNode: this.transformExplain.bind(this), - DefaultInsertValueNode: this.transformDefaultInsertValue.bind(this), - AggregateFunctionNode: this.transformAggregateFunction.bind(this), - OverNode: this.transformOver.bind(this), - PartitionByNode: this.transformPartitionBy.bind(this), - PartitionByItemNode: this.transformPartitionByItem.bind(this), - SetOperationNode: this.transformSetOperation.bind(this), - BinaryOperationNode: this.transformBinaryOperation.bind(this), - UnaryOperationNode: this.transformUnaryOperation.bind(this), - UsingNode: this.transformUsing.bind(this), - FunctionNode: this.transformFunction.bind(this), - CaseNode: this.transformCase.bind(this), - WhenNode: this.transformWhen.bind(this), - JSONReferenceNode: this.transformJSONReference.bind(this), - JSONPathNode: this.transformJSONPath.bind(this), - JSONPathLegNode: this.transformJSONPathLeg.bind(this), - JSONOperatorChainNode: this.transformJSONOperatorChain.bind(this), - TupleNode: this.transformTuple.bind(this), - MergeQueryNode: this.transformMergeQuery.bind(this), - MatchedNode: this.transformMatched.bind(this), - AddIndexNode: this.transformAddIndex.bind(this), - CastNode: this.transformCast.bind(this), - FetchNode: this.transformFetch.bind(this), - TopNode: this.transformTop.bind(this), - OutputNode: this.transformOutput.bind(this), - OrActionNode: this.transformOrAction.bind(this), - CollateNode: this.transformCollate.bind(this) - }); - transformNode(node, queryId) { - if (!node) { - return node; - } - this.nodeStack.push(node); - const out = this.transformNodeImpl(node, queryId); - this.nodeStack.pop(); - return freeze2(out); - } - transformNodeImpl(node, queryId) { - return this.#transformers[node.kind](node, queryId); - } - transformNodeList(list2, queryId) { - if (!list2) { - return list2; - } - return freeze2(list2.map((node) => this.transformNode(node, queryId))); - } - transformSelectQuery(node, queryId) { - return requireAllProps({ - kind: "SelectQueryNode", - from: this.transformNode(node.from, queryId), - selections: this.transformNodeList(node.selections, queryId), - distinctOn: this.transformNodeList(node.distinctOn, queryId), - joins: this.transformNodeList(node.joins, queryId), - groupBy: this.transformNode(node.groupBy, queryId), - orderBy: this.transformNode(node.orderBy, queryId), - where: this.transformNode(node.where, queryId), - frontModifiers: this.transformNodeList(node.frontModifiers, queryId), - endModifiers: this.transformNodeList(node.endModifiers, queryId), - limit: this.transformNode(node.limit, queryId), - offset: this.transformNode(node.offset, queryId), - with: this.transformNode(node.with, queryId), - having: this.transformNode(node.having, queryId), - explain: this.transformNode(node.explain, queryId), - setOperations: this.transformNodeList(node.setOperations, queryId), - fetch: this.transformNode(node.fetch, queryId), - top: this.transformNode(node.top, queryId) - }); - } - transformSelection(node, queryId) { - return requireAllProps({ - kind: "SelectionNode", - selection: this.transformNode(node.selection, queryId) - }); - } - transformColumn(node, queryId) { - return requireAllProps({ - kind: "ColumnNode", - column: this.transformNode(node.column, queryId) - }); - } - transformAlias(node, queryId) { - return requireAllProps({ - kind: "AliasNode", - node: this.transformNode(node.node, queryId), - alias: this.transformNode(node.alias, queryId) - }); - } - transformTable(node, queryId) { - return requireAllProps({ - kind: "TableNode", - table: this.transformNode(node.table, queryId) - }); - } - transformFrom(node, queryId) { - return requireAllProps({ - kind: "FromNode", - froms: this.transformNodeList(node.froms, queryId) - }); - } - transformReference(node, queryId) { - return requireAllProps({ - kind: "ReferenceNode", - column: this.transformNode(node.column, queryId), - table: this.transformNode(node.table, queryId) - }); - } - transformAnd(node, queryId) { - return requireAllProps({ - kind: "AndNode", - left: this.transformNode(node.left, queryId), - right: this.transformNode(node.right, queryId) - }); - } - transformOr(node, queryId) { - return requireAllProps({ - kind: "OrNode", - left: this.transformNode(node.left, queryId), - right: this.transformNode(node.right, queryId) - }); - } - transformValueList(node, queryId) { - return requireAllProps({ - kind: "ValueListNode", - values: this.transformNodeList(node.values, queryId) - }); - } - transformParens(node, queryId) { - return requireAllProps({ - kind: "ParensNode", - node: this.transformNode(node.node, queryId) - }); - } - transformJoin(node, queryId) { - return requireAllProps({ - kind: "JoinNode", - joinType: node.joinType, - table: this.transformNode(node.table, queryId), - on: this.transformNode(node.on, queryId) - }); - } - transformRaw(node, queryId) { - return requireAllProps({ - kind: "RawNode", - sqlFragments: freeze2([...node.sqlFragments]), - parameters: this.transformNodeList(node.parameters, queryId) - }); - } - transformWhere(node, queryId) { - return requireAllProps({ - kind: "WhereNode", - where: this.transformNode(node.where, queryId) - }); - } - transformInsertQuery(node, queryId) { - return requireAllProps({ - kind: "InsertQueryNode", - into: this.transformNode(node.into, queryId), - columns: this.transformNodeList(node.columns, queryId), - values: this.transformNode(node.values, queryId), - returning: this.transformNode(node.returning, queryId), - onConflict: this.transformNode(node.onConflict, queryId), - onDuplicateKey: this.transformNode(node.onDuplicateKey, queryId), - endModifiers: this.transformNodeList(node.endModifiers, queryId), - with: this.transformNode(node.with, queryId), - ignore: node.ignore, - orAction: this.transformNode(node.orAction, queryId), - replace: node.replace, - explain: this.transformNode(node.explain, queryId), - defaultValues: node.defaultValues, - top: this.transformNode(node.top, queryId), - output: this.transformNode(node.output, queryId) - }); - } - transformValues(node, queryId) { - return requireAllProps({ - kind: "ValuesNode", - values: this.transformNodeList(node.values, queryId) - }); - } - transformDeleteQuery(node, queryId) { - return requireAllProps({ - kind: "DeleteQueryNode", - from: this.transformNode(node.from, queryId), - using: this.transformNode(node.using, queryId), - joins: this.transformNodeList(node.joins, queryId), - where: this.transformNode(node.where, queryId), - returning: this.transformNode(node.returning, queryId), - endModifiers: this.transformNodeList(node.endModifiers, queryId), - with: this.transformNode(node.with, queryId), - orderBy: this.transformNode(node.orderBy, queryId), - limit: this.transformNode(node.limit, queryId), - explain: this.transformNode(node.explain, queryId), - top: this.transformNode(node.top, queryId), - output: this.transformNode(node.output, queryId) - }); - } - transformReturning(node, queryId) { - return requireAllProps({ - kind: "ReturningNode", - selections: this.transformNodeList(node.selections, queryId) - }); - } - transformCreateTable(node, queryId) { - return requireAllProps({ - kind: "CreateTableNode", - table: this.transformNode(node.table, queryId), - columns: this.transformNodeList(node.columns, queryId), - constraints: this.transformNodeList(node.constraints, queryId), - temporary: node.temporary, - ifNotExists: node.ifNotExists, - onCommit: node.onCommit, - frontModifiers: this.transformNodeList(node.frontModifiers, queryId), - endModifiers: this.transformNodeList(node.endModifiers, queryId), - selectQuery: this.transformNode(node.selectQuery, queryId) - }); - } - transformColumnDefinition(node, queryId) { - return requireAllProps({ - kind: "ColumnDefinitionNode", - column: this.transformNode(node.column, queryId), - dataType: this.transformNode(node.dataType, queryId), - references: this.transformNode(node.references, queryId), - primaryKey: node.primaryKey, - autoIncrement: node.autoIncrement, - unique: node.unique, - notNull: node.notNull, - unsigned: node.unsigned, - defaultTo: this.transformNode(node.defaultTo, queryId), - check: this.transformNode(node.check, queryId), - generated: this.transformNode(node.generated, queryId), - frontModifiers: this.transformNodeList(node.frontModifiers, queryId), - endModifiers: this.transformNodeList(node.endModifiers, queryId), - nullsNotDistinct: node.nullsNotDistinct, - identity: node.identity, - ifNotExists: node.ifNotExists - }); - } - transformAddColumn(node, queryId) { - return requireAllProps({ - kind: "AddColumnNode", - column: this.transformNode(node.column, queryId) - }); - } - transformDropTable(node, queryId) { - return requireAllProps({ - kind: "DropTableNode", - table: this.transformNode(node.table, queryId), - ifExists: node.ifExists, - cascade: node.cascade - }); - } - transformOrderBy(node, queryId) { - return requireAllProps({ - kind: "OrderByNode", - items: this.transformNodeList(node.items, queryId) - }); - } - transformOrderByItem(node, queryId) { - return requireAllProps({ - kind: "OrderByItemNode", - orderBy: this.transformNode(node.orderBy, queryId), - direction: this.transformNode(node.direction, queryId), - collation: this.transformNode(node.collation, queryId), - nulls: node.nulls - }); - } - transformGroupBy(node, queryId) { - return requireAllProps({ - kind: "GroupByNode", - items: this.transformNodeList(node.items, queryId) - }); - } - transformGroupByItem(node, queryId) { - return requireAllProps({ - kind: "GroupByItemNode", - groupBy: this.transformNode(node.groupBy, queryId) - }); - } - transformUpdateQuery(node, queryId) { - return requireAllProps({ - kind: "UpdateQueryNode", - table: this.transformNode(node.table, queryId), - from: this.transformNode(node.from, queryId), - joins: this.transformNodeList(node.joins, queryId), - where: this.transformNode(node.where, queryId), - updates: this.transformNodeList(node.updates, queryId), - returning: this.transformNode(node.returning, queryId), - endModifiers: this.transformNodeList(node.endModifiers, queryId), - with: this.transformNode(node.with, queryId), - explain: this.transformNode(node.explain, queryId), - limit: this.transformNode(node.limit, queryId), - top: this.transformNode(node.top, queryId), - output: this.transformNode(node.output, queryId), - orderBy: this.transformNode(node.orderBy, queryId) - }); - } - transformColumnUpdate(node, queryId) { - return requireAllProps({ - kind: "ColumnUpdateNode", - column: this.transformNode(node.column, queryId), - value: this.transformNode(node.value, queryId) - }); - } - transformLimit(node, queryId) { - return requireAllProps({ - kind: "LimitNode", - limit: this.transformNode(node.limit, queryId) - }); - } - transformOffset(node, queryId) { - return requireAllProps({ - kind: "OffsetNode", - offset: this.transformNode(node.offset, queryId) - }); - } - transformOnConflict(node, queryId) { - return requireAllProps({ - kind: "OnConflictNode", - columns: this.transformNodeList(node.columns, queryId), - constraint: this.transformNode(node.constraint, queryId), - indexExpression: this.transformNode(node.indexExpression, queryId), - indexWhere: this.transformNode(node.indexWhere, queryId), - updates: this.transformNodeList(node.updates, queryId), - updateWhere: this.transformNode(node.updateWhere, queryId), - doNothing: node.doNothing - }); - } - transformOnDuplicateKey(node, queryId) { - return requireAllProps({ - kind: "OnDuplicateKeyNode", - updates: this.transformNodeList(node.updates, queryId) - }); - } - transformCreateIndex(node, queryId) { - return requireAllProps({ - kind: "CreateIndexNode", - name: this.transformNode(node.name, queryId), - table: this.transformNode(node.table, queryId), - columns: this.transformNodeList(node.columns, queryId), - unique: node.unique, - using: this.transformNode(node.using, queryId), - ifNotExists: node.ifNotExists, - where: this.transformNode(node.where, queryId), - nullsNotDistinct: node.nullsNotDistinct - }); - } - transformList(node, queryId) { - return requireAllProps({ - kind: "ListNode", - items: this.transformNodeList(node.items, queryId) - }); - } - transformDropIndex(node, queryId) { - return requireAllProps({ - kind: "DropIndexNode", - name: this.transformNode(node.name, queryId), - table: this.transformNode(node.table, queryId), - ifExists: node.ifExists, - cascade: node.cascade - }); - } - transformPrimaryKeyConstraint(node, queryId) { - return requireAllProps({ - kind: "PrimaryKeyConstraintNode", - columns: this.transformNodeList(node.columns, queryId), - name: this.transformNode(node.name, queryId), - deferrable: node.deferrable, - initiallyDeferred: node.initiallyDeferred - }); - } - transformUniqueConstraint(node, queryId) { - return requireAllProps({ - kind: "UniqueConstraintNode", - columns: this.transformNodeList(node.columns, queryId), - name: this.transformNode(node.name, queryId), - nullsNotDistinct: node.nullsNotDistinct, - deferrable: node.deferrable, - initiallyDeferred: node.initiallyDeferred - }); - } - transformForeignKeyConstraint(node, queryId) { - return requireAllProps({ - kind: "ForeignKeyConstraintNode", - columns: this.transformNodeList(node.columns, queryId), - references: this.transformNode(node.references, queryId), - name: this.transformNode(node.name, queryId), - onDelete: node.onDelete, - onUpdate: node.onUpdate, - deferrable: node.deferrable, - initiallyDeferred: node.initiallyDeferred - }); - } - transformSetOperation(node, queryId) { - return requireAllProps({ - kind: "SetOperationNode", - operator: node.operator, - expression: this.transformNode(node.expression, queryId), - all: node.all - }); - } - transformReferences(node, queryId) { - return requireAllProps({ - kind: "ReferencesNode", - table: this.transformNode(node.table, queryId), - columns: this.transformNodeList(node.columns, queryId), - onDelete: node.onDelete, - onUpdate: node.onUpdate - }); - } - transformCheckConstraint(node, queryId) { - return requireAllProps({ - kind: "CheckConstraintNode", - expression: this.transformNode(node.expression, queryId), - name: this.transformNode(node.name, queryId) - }); - } - transformWith(node, queryId) { - return requireAllProps({ - kind: "WithNode", - expressions: this.transformNodeList(node.expressions, queryId), - recursive: node.recursive - }); - } - transformCommonTableExpression(node, queryId) { - return requireAllProps({ - kind: "CommonTableExpressionNode", - name: this.transformNode(node.name, queryId), - materialized: node.materialized, - expression: this.transformNode(node.expression, queryId) - }); - } - transformCommonTableExpressionName(node, queryId) { - return requireAllProps({ - kind: "CommonTableExpressionNameNode", - table: this.transformNode(node.table, queryId), - columns: this.transformNodeList(node.columns, queryId) - }); - } - transformHaving(node, queryId) { - return requireAllProps({ - kind: "HavingNode", - having: this.transformNode(node.having, queryId) - }); - } - transformCreateSchema(node, queryId) { - return requireAllProps({ - kind: "CreateSchemaNode", - schema: this.transformNode(node.schema, queryId), - ifNotExists: node.ifNotExists - }); - } - transformDropSchema(node, queryId) { - return requireAllProps({ - kind: "DropSchemaNode", - schema: this.transformNode(node.schema, queryId), - ifExists: node.ifExists, - cascade: node.cascade - }); - } - transformAlterTable(node, queryId) { - return requireAllProps({ - kind: "AlterTableNode", - table: this.transformNode(node.table, queryId), - renameTo: this.transformNode(node.renameTo, queryId), - setSchema: this.transformNode(node.setSchema, queryId), - columnAlterations: this.transformNodeList(node.columnAlterations, queryId), - addConstraint: this.transformNode(node.addConstraint, queryId), - dropConstraint: this.transformNode(node.dropConstraint, queryId), - renameConstraint: this.transformNode(node.renameConstraint, queryId), - addIndex: this.transformNode(node.addIndex, queryId), - dropIndex: this.transformNode(node.dropIndex, queryId) - }); - } - transformDropColumn(node, queryId) { - return requireAllProps({ - kind: "DropColumnNode", - column: this.transformNode(node.column, queryId) - }); - } - transformRenameColumn(node, queryId) { - return requireAllProps({ - kind: "RenameColumnNode", - column: this.transformNode(node.column, queryId), - renameTo: this.transformNode(node.renameTo, queryId) - }); - } - transformAlterColumn(node, queryId) { - return requireAllProps({ - kind: "AlterColumnNode", - column: this.transformNode(node.column, queryId), - dataType: this.transformNode(node.dataType, queryId), - dataTypeExpression: this.transformNode(node.dataTypeExpression, queryId), - setDefault: this.transformNode(node.setDefault, queryId), - dropDefault: node.dropDefault, - setNotNull: node.setNotNull, - dropNotNull: node.dropNotNull - }); - } - transformModifyColumn(node, queryId) { - return requireAllProps({ - kind: "ModifyColumnNode", - column: this.transformNode(node.column, queryId) - }); - } - transformAddConstraint(node, queryId) { - return requireAllProps({ - kind: "AddConstraintNode", - constraint: this.transformNode(node.constraint, queryId) - }); - } - transformDropConstraint(node, queryId) { - return requireAllProps({ - kind: "DropConstraintNode", - constraintName: this.transformNode(node.constraintName, queryId), - ifExists: node.ifExists, - modifier: node.modifier - }); - } - transformRenameConstraint(node, queryId) { - return requireAllProps({ - kind: "RenameConstraintNode", - oldName: this.transformNode(node.oldName, queryId), - newName: this.transformNode(node.newName, queryId) - }); - } - transformCreateView(node, queryId) { - return requireAllProps({ - kind: "CreateViewNode", - name: this.transformNode(node.name, queryId), - temporary: node.temporary, - orReplace: node.orReplace, - ifNotExists: node.ifNotExists, - materialized: node.materialized, - columns: this.transformNodeList(node.columns, queryId), - as: this.transformNode(node.as, queryId) - }); - } - transformRefreshMaterializedView(node, queryId) { - return requireAllProps({ - kind: "RefreshMaterializedViewNode", - name: this.transformNode(node.name, queryId), - concurrently: node.concurrently, - withNoData: node.withNoData - }); - } - transformDropView(node, queryId) { - return requireAllProps({ - kind: "DropViewNode", - name: this.transformNode(node.name, queryId), - ifExists: node.ifExists, - materialized: node.materialized, - cascade: node.cascade - }); - } - transformGenerated(node, queryId) { - return requireAllProps({ - kind: "GeneratedNode", - byDefault: node.byDefault, - always: node.always, - identity: node.identity, - stored: node.stored, - expression: this.transformNode(node.expression, queryId) - }); - } - transformDefaultValue(node, queryId) { - return requireAllProps({ - kind: "DefaultValueNode", - defaultValue: this.transformNode(node.defaultValue, queryId) - }); - } - transformOn(node, queryId) { - return requireAllProps({ - kind: "OnNode", - on: this.transformNode(node.on, queryId) - }); - } - transformSelectModifier(node, queryId) { - return requireAllProps({ - kind: "SelectModifierNode", - modifier: node.modifier, - rawModifier: this.transformNode(node.rawModifier, queryId), - of: this.transformNodeList(node.of, queryId) - }); - } - transformCreateType(node, queryId) { - return requireAllProps({ - kind: "CreateTypeNode", - name: this.transformNode(node.name, queryId), - enum: this.transformNode(node.enum, queryId) - }); - } - transformDropType(node, queryId) { - return requireAllProps({ - kind: "DropTypeNode", - name: this.transformNode(node.name, queryId), - ifExists: node.ifExists - }); - } - transformExplain(node, queryId) { - return requireAllProps({ - kind: "ExplainNode", - format: node.format, - options: this.transformNode(node.options, queryId) - }); - } - transformSchemableIdentifier(node, queryId) { - return requireAllProps({ - kind: "SchemableIdentifierNode", - schema: this.transformNode(node.schema, queryId), - identifier: this.transformNode(node.identifier, queryId) - }); - } - transformAggregateFunction(node, queryId) { - return requireAllProps({ - kind: "AggregateFunctionNode", - func: node.func, - aggregated: this.transformNodeList(node.aggregated, queryId), - distinct: node.distinct, - orderBy: this.transformNode(node.orderBy, queryId), - withinGroup: this.transformNode(node.withinGroup, queryId), - filter: this.transformNode(node.filter, queryId), - over: this.transformNode(node.over, queryId) - }); - } - transformOver(node, queryId) { - return requireAllProps({ - kind: "OverNode", - orderBy: this.transformNode(node.orderBy, queryId), - partitionBy: this.transformNode(node.partitionBy, queryId) - }); - } - transformPartitionBy(node, queryId) { - return requireAllProps({ - kind: "PartitionByNode", - items: this.transformNodeList(node.items, queryId) - }); - } - transformPartitionByItem(node, queryId) { - return requireAllProps({ - kind: "PartitionByItemNode", - partitionBy: this.transformNode(node.partitionBy, queryId) - }); - } - transformBinaryOperation(node, queryId) { - return requireAllProps({ - kind: "BinaryOperationNode", - leftOperand: this.transformNode(node.leftOperand, queryId), - operator: this.transformNode(node.operator, queryId), - rightOperand: this.transformNode(node.rightOperand, queryId) - }); - } - transformUnaryOperation(node, queryId) { - return requireAllProps({ - kind: "UnaryOperationNode", - operator: this.transformNode(node.operator, queryId), - operand: this.transformNode(node.operand, queryId) - }); - } - transformUsing(node, queryId) { - return requireAllProps({ - kind: "UsingNode", - tables: this.transformNodeList(node.tables, queryId) - }); - } - transformFunction(node, queryId) { - return requireAllProps({ - kind: "FunctionNode", - func: node.func, - arguments: this.transformNodeList(node.arguments, queryId) - }); - } - transformCase(node, queryId) { - return requireAllProps({ - kind: "CaseNode", - value: this.transformNode(node.value, queryId), - when: this.transformNodeList(node.when, queryId), - else: this.transformNode(node.else, queryId), - isStatement: node.isStatement - }); - } - transformWhen(node, queryId) { - return requireAllProps({ - kind: "WhenNode", - condition: this.transformNode(node.condition, queryId), - result: this.transformNode(node.result, queryId) - }); - } - transformJSONReference(node, queryId) { - return requireAllProps({ - kind: "JSONReferenceNode", - reference: this.transformNode(node.reference, queryId), - traversal: this.transformNode(node.traversal, queryId) - }); - } - transformJSONPath(node, queryId) { - return requireAllProps({ - kind: "JSONPathNode", - inOperator: this.transformNode(node.inOperator, queryId), - pathLegs: this.transformNodeList(node.pathLegs, queryId) - }); - } - transformJSONPathLeg(node, _queryId) { - return requireAllProps({ - kind: "JSONPathLegNode", - type: node.type, - value: node.value - }); - } - transformJSONOperatorChain(node, queryId) { - return requireAllProps({ - kind: "JSONOperatorChainNode", - operator: this.transformNode(node.operator, queryId), - values: this.transformNodeList(node.values, queryId) - }); - } - transformTuple(node, queryId) { - return requireAllProps({ - kind: "TupleNode", - values: this.transformNodeList(node.values, queryId) - }); - } - transformMergeQuery(node, queryId) { - return requireAllProps({ - kind: "MergeQueryNode", - into: this.transformNode(node.into, queryId), - using: this.transformNode(node.using, queryId), - whens: this.transformNodeList(node.whens, queryId), - with: this.transformNode(node.with, queryId), - top: this.transformNode(node.top, queryId), - endModifiers: this.transformNodeList(node.endModifiers, queryId), - output: this.transformNode(node.output, queryId), - returning: this.transformNode(node.returning, queryId) - }); - } - transformMatched(node, _queryId) { - return requireAllProps({ - kind: "MatchedNode", - not: node.not, - bySource: node.bySource - }); - } - transformAddIndex(node, queryId) { - return requireAllProps({ - kind: "AddIndexNode", - name: this.transformNode(node.name, queryId), - columns: this.transformNodeList(node.columns, queryId), - unique: node.unique, - using: this.transformNode(node.using, queryId), - ifNotExists: node.ifNotExists - }); - } - transformCast(node, queryId) { - return requireAllProps({ - kind: "CastNode", - expression: this.transformNode(node.expression, queryId), - dataType: this.transformNode(node.dataType, queryId) - }); - } - transformFetch(node, queryId) { - return requireAllProps({ - kind: "FetchNode", - rowCount: this.transformNode(node.rowCount, queryId), - modifier: node.modifier - }); - } - transformTop(node, _queryId) { - return requireAllProps({ - kind: "TopNode", - expression: node.expression, - modifiers: node.modifiers - }); - } - transformOutput(node, queryId) { - return requireAllProps({ - kind: "OutputNode", - selections: this.transformNodeList(node.selections, queryId) - }); - } - transformDataType(node, _queryId) { - return node; - } - transformSelectAll(node, _queryId) { - return node; - } - transformIdentifier(node, _queryId) { - return node; - } - transformValue(node, _queryId) { - return node; - } - transformPrimitiveValueList(node, _queryId) { - return node; - } - transformOperator(node, _queryId) { - return node; - } - transformDefaultInsertValue(node, _queryId) { - return node; - } - transformOrAction(node, _queryId) { - return node; - } - transformCollate(node, _queryId) { - return node; - } - }; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/with-schema/with-schema-transformer.js -var ROOT_OPERATION_NODES, SCHEMALESS_FUNCTIONS, WithSchemaTransformer; -var init_with_schema_transformer = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/with-schema/with-schema-transformer.js"() { - init_alias_node(); - init_identifier_node(); - init_join_node(); - init_list_node(); - init_operation_node_transformer(); - init_schemable_identifier_node(); - init_table_node(); - init_using_node(); - init_object_utils(); - ROOT_OPERATION_NODES = freeze2({ - AlterTableNode: true, - CreateIndexNode: true, - CreateSchemaNode: true, - CreateTableNode: true, - CreateTypeNode: true, - CreateViewNode: true, - RefreshMaterializedViewNode: true, - DeleteQueryNode: true, - DropIndexNode: true, - DropSchemaNode: true, - DropTableNode: true, - DropTypeNode: true, - DropViewNode: true, - InsertQueryNode: true, - RawNode: true, - SelectQueryNode: true, - UpdateQueryNode: true, - MergeQueryNode: true - }); - SCHEMALESS_FUNCTIONS = { - json_agg: true, - to_json: true - }; - WithSchemaTransformer = class extends OperationNodeTransformer { - #schema; - #schemableIds = /* @__PURE__ */ new Set(); - #ctes = /* @__PURE__ */ new Set(); - constructor(schema2) { - super(); - this.#schema = schema2; - } - transformNodeImpl(node, queryId) { - if (!this.#isRootOperationNode(node)) { - return super.transformNodeImpl(node, queryId); - } - const ctes = this.#collectCTEs(node); - for (const cte of ctes) { - this.#ctes.add(cte); - } - const tables = this.#collectSchemableIds(node); - for (const table of tables) { - this.#schemableIds.add(table); - } - const transformed = super.transformNodeImpl(node, queryId); - for (const table of tables) { - this.#schemableIds.delete(table); - } - for (const cte of ctes) { - this.#ctes.delete(cte); - } - return transformed; - } - transformSchemableIdentifier(node, queryId) { - const transformed = super.transformSchemableIdentifier(node, queryId); - if (transformed.schema || !this.#schemableIds.has(node.identifier.name)) { - return transformed; - } - return { - ...transformed, - schema: IdentifierNode.create(this.#schema) - }; - } - transformReferences(node, queryId) { - const transformed = super.transformReferences(node, queryId); - if (transformed.table.table.schema) { - return transformed; - } - return { - ...transformed, - table: TableNode.createWithSchema(this.#schema, transformed.table.table.identifier.name) - }; - } - transformAggregateFunction(node, queryId) { - return { - ...super.transformAggregateFunction({ ...node, aggregated: [] }, queryId), - aggregated: this.#transformTableArgsWithoutSchemas(node, queryId, "aggregated") - }; - } - transformFunction(node, queryId) { - return { - ...super.transformFunction({ ...node, arguments: [] }, queryId), - arguments: this.#transformTableArgsWithoutSchemas(node, queryId, "arguments") - }; - } - transformSelectModifier(node, queryId) { - return { - ...super.transformSelectModifier({ ...node, of: void 0 }, queryId), - of: node.of?.map((item) => TableNode.is(item) && !item.table.schema ? { - ...item, - table: this.transformIdentifier(item.table.identifier, queryId) - } : this.transformNode(item, queryId)) - }; - } - #transformTableArgsWithoutSchemas(node, queryId, argsKey) { - return SCHEMALESS_FUNCTIONS[node.func] ? node[argsKey].map((arg) => !TableNode.is(arg) || arg.table.schema ? this.transformNode(arg, queryId) : { - ...arg, - table: this.transformIdentifier(arg.table.identifier, queryId) - }) : this.transformNodeList(node[argsKey], queryId); - } - #isRootOperationNode(node) { - return node.kind in ROOT_OPERATION_NODES; - } - #collectSchemableIds(node) { - const schemableIds = /* @__PURE__ */ new Set(); - if ("name" in node && node.name && SchemableIdentifierNode.is(node.name)) { - this.#collectSchemableId(node.name, schemableIds); - } - if ("from" in node && node.from) { - for (const from of node.from.froms) { - this.#collectSchemableIdsFromTableExpr(from, schemableIds); - } - } - if ("into" in node && node.into) { - this.#collectSchemableIdsFromTableExpr(node.into, schemableIds); - } - if ("table" in node && node.table) { - this.#collectSchemableIdsFromTableExpr(node.table, schemableIds); - } - if ("joins" in node && node.joins) { - for (const join4 of node.joins) { - this.#collectSchemableIdsFromTableExpr(join4.table, schemableIds); - } - } - if ("using" in node && node.using) { - if (JoinNode.is(node.using)) { - this.#collectSchemableIdsFromTableExpr(node.using.table, schemableIds); - } else { - this.#collectSchemableIdsFromTableExpr(node.using, schemableIds); - } - } - return schemableIds; - } - #collectCTEs(node) { - const ctes = /* @__PURE__ */ new Set(); - if ("with" in node && node.with) { - this.#collectCTEIds(node.with, ctes); - } - return ctes; - } - #collectSchemableIdsFromTableExpr(node, schemableIds) { - if (TableNode.is(node)) { - return this.#collectSchemableId(node.table, schemableIds); - } - if (AliasNode.is(node) && TableNode.is(node.node)) { - return this.#collectSchemableId(node.node.table, schemableIds); - } - if (ListNode.is(node)) { - for (const table of node.items) { - this.#collectSchemableIdsFromTableExpr(table, schemableIds); - } - return; - } - if (UsingNode.is(node)) { - for (const table of node.tables) { - this.#collectSchemableIdsFromTableExpr(table, schemableIds); - } - return; - } - } - #collectSchemableId(node, schemableIds) { - const id = node.identifier.name; - if (!this.#schemableIds.has(id) && !this.#ctes.has(id)) { - schemableIds.add(id); - } - } - #collectCTEIds(node, ctes) { - for (const expr of node.expressions) { - const cteId = expr.name.table.table.identifier.name; - if (!this.#ctes.has(cteId)) { - ctes.add(cteId); - } - } - } - }; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/with-schema/with-schema-plugin.js -var WithSchemaPlugin; -var init_with_schema_plugin = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/with-schema/with-schema-plugin.js"() { - init_with_schema_transformer(); - WithSchemaPlugin = class { - #transformer; - constructor(schema2) { - this.#transformer = new WithSchemaTransformer(schema2); - } - transformQuery(args) { - return this.#transformer.transformNode(args.node, args.queryId); - } - async transformResult(args) { - return args.result; - } - }; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/matched-node.js -var MatchedNode; -var init_matched_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/matched-node.js"() { - init_object_utils(); - MatchedNode = freeze2({ - is(node) { - return node.kind === "MatchedNode"; - }, - create(not2, bySource = false) { - return freeze2({ - kind: "MatchedNode", - not: not2, - bySource - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/merge-parser.js -function parseMergeWhen(type, args, refRight) { - return WhenNode.create(parseFilterList([ - MatchedNode.create(!type.isMatched, type.bySource), - ...args && args.length > 0 ? [ - args.length === 3 && refRight ? parseReferentialBinaryOperation(args[0], args[1], args[2]) : parseValueBinaryOperationOrExpression(args) - ] : [] - ], "and", false)); -} -function parseMergeThen(result) { - if (isString(result)) { - return RawNode.create([result], []); - } - if (isOperationNodeSource(result)) { - return result.toOperationNode(); - } - return result; -} -var init_merge_parser = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/merge-parser.js"() { - init_matched_node(); - init_operation_node_source(); - init_raw_node(); - init_when_node(); - init_object_utils(); - init_binary_operation_parser(); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/deferred.js -var Deferred; -var init_deferred = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/deferred.js"() { - Deferred = class { - #promise; - #resolve; - #reject; - constructor() { - this.#promise = new Promise((resolve4, reject) => { - this.#reject = reject; - this.#resolve = resolve4; - }); - } - get promise() { - return this.#promise; - } - resolve = (value) => { - if (this.#resolve) { - this.#resolve(value); - } - }; - reject = (reason) => { - if (this.#reject) { - this.#reject(reason); - } - }; - }; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/provide-controlled-connection.js -async function provideControlledConnection(connectionProvider) { - const connectionDefer = new Deferred(); - const connectionReleaseDefer = new Deferred(); - connectionProvider.provideConnection(async (connection2) => { - connectionDefer.resolve(connection2); - return await connectionReleaseDefer.promise; - }).catch((ex) => connectionDefer.reject(ex)); - return freeze2({ - connection: await connectionDefer.promise, - release: connectionReleaseDefer.resolve - }); -} -var init_provide_controlled_connection = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/provide-controlled-connection.js"() { - init_deferred(); - init_object_utils(); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-executor/query-executor-base.js -var NO_PLUGINS, QueryExecutorBase; -var init_query_executor_base = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-executor/query-executor-base.js"() { - init_object_utils(); - init_provide_controlled_connection(); - init_log_once(); - NO_PLUGINS = freeze2([]); - QueryExecutorBase = class { - #plugins; - constructor(plugins2 = NO_PLUGINS) { - this.#plugins = plugins2; - } - get plugins() { - return this.#plugins; - } - transformQuery(node, queryId) { - for (const plugin of this.#plugins) { - const transformedNode = plugin.transformQuery({ node, queryId }); - if (transformedNode.kind === node.kind) { - node = transformedNode; - } else { - throw new Error([ - `KyselyPlugin.transformQuery must return a node`, - `of the same kind that was given to it.`, - `The plugin was given a ${node.kind}`, - `but it returned a ${transformedNode.kind}` - ].join(" ")); - } - } - return node; - } - async executeQuery(compiledQuery) { - return await this.provideConnection(async (connection2) => { - const result = await connection2.executeQuery(compiledQuery); - if ("numUpdatedOrDeletedRows" in result) { - logOnce("kysely:warning: outdated driver/plugin detected! `QueryResult.numUpdatedOrDeletedRows` has been replaced with `QueryResult.numAffectedRows`."); - } - return await this.#transformResult(result, compiledQuery.queryId); - }); - } - async *stream(compiledQuery, chunkSize) { - const { connection: connection2, release } = await provideControlledConnection(this); - try { - for await (const result of connection2.streamQuery(compiledQuery, chunkSize)) { - yield await this.#transformResult(result, compiledQuery.queryId); - } - } finally { - release(); - } - } - async #transformResult(result, queryId) { - for (const plugin of this.#plugins) { - result = await plugin.transformResult({ result, queryId }); - } - return result; - } - }; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-executor/noop-query-executor.js -var NoopQueryExecutor, NOOP_QUERY_EXECUTOR; -var init_noop_query_executor = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-executor/noop-query-executor.js"() { - init_query_executor_base(); - NoopQueryExecutor = class _NoopQueryExecutor extends QueryExecutorBase { - get adapter() { - throw new Error("this query cannot be compiled to SQL"); - } - compileQuery() { - throw new Error("this query cannot be compiled to SQL"); - } - provideConnection() { - throw new Error("this query cannot be executed"); - } - withConnectionProvider() { - throw new Error("this query cannot have a connection provider"); - } - withPlugin(plugin) { - return new _NoopQueryExecutor([...this.plugins, plugin]); - } - withPlugins(plugins2) { - return new _NoopQueryExecutor([...this.plugins, ...plugins2]); - } - withPluginAtFront(plugin) { - return new _NoopQueryExecutor([plugin, ...this.plugins]); - } - withoutPlugins() { - return new _NoopQueryExecutor([]); - } - }; - NOOP_QUERY_EXECUTOR = new NoopQueryExecutor(); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/merge-result.js -var MergeResult; -var init_merge_result = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/merge-result.js"() { - MergeResult = class { - numChangedRows; - constructor(numChangedRows) { - this.numChangedRows = numChangedRows; - } - }; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/merge-query-builder.js -var MergeQueryBuilder, WheneableMergeQueryBuilder, MatchedThenableMergeQueryBuilder, NotMatchedThenableMergeQueryBuilder; -var init_merge_query_builder = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/merge-query-builder.js"() { - init_insert_query_node(); - init_merge_query_node(); - init_query_node(); - init_update_query_node(); - init_insert_values_parser(); - init_join_parser(); - init_merge_parser(); - init_select_parser(); - init_top_parser(); - init_noop_query_executor(); - init_object_utils(); - init_merge_result(); - init_no_result_error(); - init_update_query_builder(); - MergeQueryBuilder = class _MergeQueryBuilder { - #props; - constructor(props) { - this.#props = freeze2(props); - } - /** - * This can be used to add any additional SQL to the end of the query. - * - * ### Examples - * - * ```ts - * import { sql } from 'kysely' - * - * await db - * .mergeInto('person') - * .using('pet', 'pet.owner_id', 'person.id') - * .whenMatched() - * .thenDelete() - * .modifyEnd(sql.raw('-- this is a comment')) - * .execute() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * merge into "person" using "pet" on "pet"."owner_id" = "person"."id" when matched then delete -- this is a comment - * ``` - */ - modifyEnd(modifier) { - return new _MergeQueryBuilder({ - ...this.#props, - queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, modifier.toOperationNode()) - }); - } - /** - * Changes a `merge into` query to an `merge top into` query. - * - * `top` clause is only supported by some dialects like MS SQL Server. - * - * ### Examples - * - * Affect 5 matched rows at most: - * - * ```ts - * await db.mergeInto('person') - * .top(5) - * .using('pet', 'person.id', 'pet.owner_id') - * .whenMatched() - * .thenDelete() - * .execute() - * ``` - * - * The generated SQL (MS SQL Server): - * - * ```sql - * merge top(5) into "person" - * using "pet" on "person"."id" = "pet"."owner_id" - * when matched then - * delete - * ``` - * - * Affect 50% of matched rows: - * - * ```ts - * await db.mergeInto('person') - * .top(50, 'percent') - * .using('pet', 'person.id', 'pet.owner_id') - * .whenMatched() - * .thenDelete() - * .execute() - * ``` - * - * The generated SQL (MS SQL Server): - * - * ```sql - * merge top(50) percent into "person" - * using "pet" on "person"."id" = "pet"."owner_id" - * when matched then - * delete - * ``` - */ - top(expression, modifiers) { - return new _MergeQueryBuilder({ - ...this.#props, - queryNode: QueryNode.cloneWithTop(this.#props.queryNode, parseTop(expression, modifiers)) - }); - } - using(...args) { - return new WheneableMergeQueryBuilder({ - ...this.#props, - queryNode: MergeQueryNode.cloneWithUsing(this.#props.queryNode, parseJoin("Using", args)) - }); - } - returning(args) { - return new _MergeQueryBuilder({ - ...this.#props, - queryNode: QueryNode.cloneWithReturning(this.#props.queryNode, parseSelectArg(args)) - }); - } - returningAll(table) { - return new _MergeQueryBuilder({ - ...this.#props, - queryNode: QueryNode.cloneWithReturning(this.#props.queryNode, parseSelectAll(table)) - }); - } - output(args) { - return new _MergeQueryBuilder({ - ...this.#props, - queryNode: QueryNode.cloneWithOutput(this.#props.queryNode, parseSelectArg(args)) - }); - } - outputAll(table) { - return new _MergeQueryBuilder({ - ...this.#props, - queryNode: QueryNode.cloneWithOutput(this.#props.queryNode, parseSelectAll(table)) - }); - } - }; - WheneableMergeQueryBuilder = class _WheneableMergeQueryBuilder { - #props; - constructor(props) { - this.#props = freeze2(props); - } - /** - * This can be used to add any additional SQL to the end of the query. - * - * ### Examples - * - * ```ts - * import { sql } from 'kysely' - * - * await db - * .mergeInto('person') - * .using('pet', 'pet.owner_id', 'person.id') - * .whenMatched() - * .thenDelete() - * .modifyEnd(sql.raw('-- this is a comment')) - * .execute() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * merge into "person" using "pet" on "pet"."owner_id" = "person"."id" when matched then delete -- this is a comment - * ``` - */ - modifyEnd(modifier) { - return new _WheneableMergeQueryBuilder({ - ...this.#props, - queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, modifier.toOperationNode()) - }); - } - /** - * See {@link MergeQueryBuilder.top}. - */ - top(expression, modifiers) { - return new _WheneableMergeQueryBuilder({ - ...this.#props, - queryNode: QueryNode.cloneWithTop(this.#props.queryNode, parseTop(expression, modifiers)) - }); - } - /** - * Adds a simple `when matched` clause to the query. - * - * For a `when matched` clause with an `and` condition, see {@link whenMatchedAnd}. - * - * For a simple `when not matched` clause, see {@link whenNotMatched}. - * - * For a `when not matched` clause with an `and` condition, see {@link whenNotMatchedAnd}. - * - * ### Examples - * - * ```ts - * const result = await db.mergeInto('person') - * .using('pet', 'person.id', 'pet.owner_id') - * .whenMatched() - * .thenDelete() - * .execute() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * merge into "person" - * using "pet" on "person"."id" = "pet"."owner_id" - * when matched then - * delete - * ``` - */ - whenMatched() { - return this.#whenMatched([]); - } - whenMatchedAnd(...args) { - return this.#whenMatched(args); - } - /** - * Adds the `when matched` clause to the query with an `and` condition. But unlike - * {@link whenMatchedAnd}, this method accepts a column reference as the 3rd argument. - * - * This method is similar to {@link SelectQueryBuilder.whereRef}, so see the documentation - * for that method for more examples. - */ - whenMatchedAndRef(lhs, op2, rhs) { - return this.#whenMatched([lhs, op2, rhs], true); - } - #whenMatched(args, refRight) { - return new MatchedThenableMergeQueryBuilder({ - ...this.#props, - queryNode: MergeQueryNode.cloneWithWhen(this.#props.queryNode, parseMergeWhen({ isMatched: true }, args, refRight)) - }); - } - /** - * Adds a simple `when not matched` clause to the query. - * - * For a `when not matched` clause with an `and` condition, see {@link whenNotMatchedAnd}. - * - * For a simple `when matched` clause, see {@link whenMatched}. - * - * For a `when matched` clause with an `and` condition, see {@link whenMatchedAnd}. - * - * ### Examples - * - * ```ts - * const result = await db.mergeInto('person') - * .using('pet', 'person.id', 'pet.owner_id') - * .whenNotMatched() - * .thenInsertValues({ - * first_name: 'John', - * last_name: 'Doe', - * }) - * .execute() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * merge into "person" - * using "pet" on "person"."id" = "pet"."owner_id" - * when not matched then - * insert ("first_name", "last_name") values ($1, $2) - * ``` - */ - whenNotMatched() { - return this.#whenNotMatched([]); - } - whenNotMatchedAnd(...args) { - return this.#whenNotMatched(args); - } - /** - * Adds the `when not matched` clause to the query with an `and` condition. But unlike - * {@link whenNotMatchedAnd}, this method accepts a column reference as the 3rd argument. - * - * Unlike {@link whenMatchedAndRef}, you cannot reference columns from the target table. - * - * This method is similar to {@link SelectQueryBuilder.whereRef}, so see the documentation - * for that method for more examples. - */ - whenNotMatchedAndRef(lhs, op2, rhs) { - return this.#whenNotMatched([lhs, op2, rhs], true); - } - /** - * Adds a simple `when not matched by source` clause to the query. - * - * Supported in MS SQL Server. - * - * Similar to {@link whenNotMatched}, but returns a {@link MatchedThenableMergeQueryBuilder}. - */ - whenNotMatchedBySource() { - return this.#whenNotMatched([], false, true); - } - whenNotMatchedBySourceAnd(...args) { - return this.#whenNotMatched(args, false, true); - } - /** - * Adds the `when not matched by source` clause to the query with an `and` condition. - * - * Similar to {@link whenNotMatchedAndRef}, but you can reference columns from - * the target table, and not from source table and returns a {@link MatchedThenableMergeQueryBuilder}. - */ - whenNotMatchedBySourceAndRef(lhs, op2, rhs) { - return this.#whenNotMatched([lhs, op2, rhs], true, true); - } - returning(args) { - return new _WheneableMergeQueryBuilder({ - ...this.#props, - queryNode: QueryNode.cloneWithReturning(this.#props.queryNode, parseSelectArg(args)) - }); - } - returningAll(table) { - return new _WheneableMergeQueryBuilder({ - ...this.#props, - queryNode: QueryNode.cloneWithReturning(this.#props.queryNode, parseSelectAll(table)) - }); - } - output(args) { - return new _WheneableMergeQueryBuilder({ - ...this.#props, - queryNode: QueryNode.cloneWithOutput(this.#props.queryNode, parseSelectArg(args)) - }); - } - outputAll(table) { - return new _WheneableMergeQueryBuilder({ - ...this.#props, - queryNode: QueryNode.cloneWithOutput(this.#props.queryNode, parseSelectAll(table)) - }); - } - #whenNotMatched(args, refRight = false, bySource = false) { - const props = { - ...this.#props, - queryNode: MergeQueryNode.cloneWithWhen(this.#props.queryNode, parseMergeWhen({ isMatched: false, bySource }, args, refRight)) - }; - const Builder2 = bySource ? MatchedThenableMergeQueryBuilder : NotMatchedThenableMergeQueryBuilder; - return new Builder2(props); - } - /** - * Simply calls the provided function passing `this` as the only argument. `$call` returns - * what the provided function returns. - * - * If you want to conditionally call a method on `this`, see - * the {@link $if} method. - * - * ### Examples - * - * The next example uses a helper function `log` to log a query: - * - * ```ts - * import type { Compilable } from 'kysely' - * - * function log(qb: T): T { - * console.log(qb.compile()) - * return qb - * } - * - * await db.updateTable('person') - * .set({ first_name: 'John' }) - * .$call(log) - * .execute() - * ``` - */ - $call(func) { - return func(this); - } - /** - * Call `func(this)` if `condition` is true. - * - * This method is especially handy with optional selects. Any `returning` or `returningAll` - * method calls add columns as optional fields to the output type when called inside - * the `func` callback. This is because we can't know if those selections were actually - * made before running the code. - * - * You can also call any other methods inside the callback. - * - * ### Examples - * - * ```ts - * import type { PersonUpdate } from 'type-editor' // imaginary module - * - * async function updatePerson(id: number, updates: PersonUpdate, returnLastName: boolean) { - * return await db - * .updateTable('person') - * .set(updates) - * .where('id', '=', id) - * .returning(['id', 'first_name']) - * .$if(returnLastName, (qb) => qb.returning('last_name')) - * .executeTakeFirstOrThrow() - * } - * ``` - * - * Any selections added inside the `if` callback will be added as optional fields to the - * output type since we can't know if the selections were actually made before running - * the code. In the example above the return type of the `updatePerson` function is: - * - * ```ts - * Promise<{ - * id: number - * first_name: string - * last_name?: string - * }> - * ``` - */ - $if(condition, func) { - if (condition) { - return func(this); - } - return new _WheneableMergeQueryBuilder({ - ...this.#props - }); - } - toOperationNode() { - return this.#props.executor.transformQuery(this.#props.queryNode, this.#props.queryId); - } - compile() { - return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId); - } - /** - * Executes the query and returns an array of rows. - * - * Also see the {@link executeTakeFirst} and {@link executeTakeFirstOrThrow} methods. - */ - async execute() { - const compiledQuery = this.compile(); - const result = await this.#props.executor.executeQuery(compiledQuery); - const { adapter } = this.#props.executor; - const query = compiledQuery.query; - if (query.returning && adapter.supportsReturning || query.output && adapter.supportsOutput) { - return result.rows; - } - return [new MergeResult(result.numAffectedRows)]; - } - /** - * Executes the query and returns the first result or undefined if - * the query returned no result. - */ - async executeTakeFirst() { - const [result] = await this.execute(); - return result; - } - /** - * Executes the query and returns the first result or throws if - * the query returned no result. - * - * By default an instance of {@link NoResultError} is thrown, but you can - * provide a custom error class, or callback as the only argument to throw a different - * error. - */ - async executeTakeFirstOrThrow(errorConstructor = NoResultError) { - const result = await this.executeTakeFirst(); - if (result === void 0) { - const error50 = isNoResultErrorConstructor(errorConstructor) ? new errorConstructor(this.toOperationNode()) : errorConstructor(this.toOperationNode()); - throw error50; - } - return result; - } - }; - MatchedThenableMergeQueryBuilder = class { - #props; - constructor(props) { - this.#props = freeze2(props); - } - /** - * Performs the `delete` action. - * - * To perform the `do nothing` action, see {@link thenDoNothing}. - * - * To perform the `update` action, see {@link thenUpdate} or {@link thenUpdateSet}. - * - * ### Examples - * - * ```ts - * const result = await db.mergeInto('person') - * .using('pet', 'person.id', 'pet.owner_id') - * .whenMatched() - * .thenDelete() - * .execute() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * merge into "person" - * using "pet" on "person"."id" = "pet"."owner_id" - * when matched then - * delete - * ``` - */ - thenDelete() { - return new WheneableMergeQueryBuilder({ - ...this.#props, - queryNode: MergeQueryNode.cloneWithThen(this.#props.queryNode, parseMergeThen("delete")) - }); - } - /** - * Performs the `do nothing` action. - * - * This is supported in PostgreSQL. - * - * To perform the `delete` action, see {@link thenDelete}. - * - * To perform the `update` action, see {@link thenUpdate} or {@link thenUpdateSet}. - * - * ### Examples - * - * ```ts - * const result = await db.mergeInto('person') - * .using('pet', 'person.id', 'pet.owner_id') - * .whenMatched() - * .thenDoNothing() - * .execute() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * merge into "person" - * using "pet" on "person"."id" = "pet"."owner_id" - * when matched then - * do nothing - * ``` - */ - thenDoNothing() { - return new WheneableMergeQueryBuilder({ - ...this.#props, - queryNode: MergeQueryNode.cloneWithThen(this.#props.queryNode, parseMergeThen("do nothing")) - }); - } - /** - * Perform an `update` operation with a full-fledged {@link UpdateQueryBuilder}. - * This is handy when multiple `set` invocations are needed. - * - * For a shorthand version of this method, see {@link thenUpdateSet}. - * - * To perform the `delete` action, see {@link thenDelete}. - * - * To perform the `do nothing` action, see {@link thenDoNothing}. - * - * ### Examples - * - * ```ts - * import { sql } from 'kysely' - * - * const result = await db.mergeInto('person') - * .using('pet', 'person.id', 'pet.owner_id') - * .whenMatched() - * .thenUpdate((ub) => ub - * .set(sql`metadata['has_pets']`, 'Y') - * .set({ - * updated_at: new Date().toISOString(), - * }) - * ) - * .execute() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * merge into "person" - * using "pet" on "person"."id" = "pet"."owner_id" - * when matched then - * update set metadata['has_pets'] = $1, "updated_at" = $2 - * ``` - */ - thenUpdate(set2) { - return new WheneableMergeQueryBuilder({ - ...this.#props, - queryNode: MergeQueryNode.cloneWithThen(this.#props.queryNode, parseMergeThen(set2(new UpdateQueryBuilder({ - queryId: this.#props.queryId, - executor: NOOP_QUERY_EXECUTOR, - queryNode: UpdateQueryNode.createWithoutTable() - })))) - }); - } - thenUpdateSet(...args) { - return this.thenUpdate((ub) => ub.set(...args)); - } - }; - NotMatchedThenableMergeQueryBuilder = class { - #props; - constructor(props) { - this.#props = freeze2(props); - } - /** - * Performs the `do nothing` action. - * - * This is supported in PostgreSQL. - * - * To perform the `insert` action, see {@link thenInsertValues}. - * - * ### Examples - * - * ```ts - * const result = await db.mergeInto('person') - * .using('pet', 'person.id', 'pet.owner_id') - * .whenNotMatched() - * .thenDoNothing() - * .execute() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * merge into "person" - * using "pet" on "person"."id" = "pet"."owner_id" - * when not matched then - * do nothing - * ``` - */ - thenDoNothing() { - return new WheneableMergeQueryBuilder({ - ...this.#props, - queryNode: MergeQueryNode.cloneWithThen(this.#props.queryNode, parseMergeThen("do nothing")) - }); - } - thenInsertValues(insert) { - const [columns, values2] = parseInsertExpression(insert); - return new WheneableMergeQueryBuilder({ - ...this.#props, - queryNode: MergeQueryNode.cloneWithThen(this.#props.queryNode, parseMergeThen(InsertQueryNode.cloneWith(InsertQueryNode.createWithoutInto(), { - columns, - values: values2 - }))) - }); - } - }; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-creator.js -var QueryCreator; -var init_query_creator = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-creator.js"() { - init_select_query_builder(); - init_insert_query_builder(); - init_delete_query_builder(); - init_update_query_builder(); - init_delete_query_node(); - init_insert_query_node(); - init_select_query_node(); - init_update_query_node(); - init_table_parser(); - init_with_parser(); - init_with_node(); - init_query_id(); - init_with_schema_plugin(); - init_object_utils(); - init_select_parser(); - init_merge_query_builder(); - init_merge_query_node(); - QueryCreator = class _QueryCreator { - #props; - constructor(props) { - this.#props = freeze2(props); - } - /** - * Creates a `select` query builder for the given table or tables. - * - * The tables passed to this method are built as the query's `from` clause. - * - * ### Examples - * - * Create a select query for one table: - * - * ```ts - * db.selectFrom('person').selectAll() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * select * from "person" - * ``` - * - * Create a select query for one table with an alias: - * - * ```ts - * const persons = await db.selectFrom('person as p') - * .select(['p.id', 'first_name']) - * .execute() - * - * console.log(persons[0].id) - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * select "p"."id", "first_name" from "person" as "p" - * ``` - * - * Create a select query from a subquery: - * - * ```ts - * const persons = await db.selectFrom( - * (eb) => eb.selectFrom('person').select('person.id as identifier').as('p') - * ) - * .select('p.identifier') - * .execute() - * - * console.log(persons[0].identifier) - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * select "p"."identifier", - * from ( - * select "person"."id" as "identifier" from "person" - * ) as p - * ``` - * - * Create a select query from raw sql: - * - * ```ts - * import { sql } from 'kysely' - * - * const items = await db - * .selectFrom(sql<{ one: number }>`(select 1 as one)`.as('q')) - * .select('q.one') - * .execute() - * - * console.log(items[0].one) - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * select "q"."one", - * from ( - * select 1 as one - * ) as q - * ``` - * - * When you use the `sql` tag you need to also provide the result type of the - * raw snippet / query so that Kysely can figure out what columns are - * available for the rest of the query. - * - * The `selectFrom` method also accepts an array for multiple tables. All - * the above examples can also be used in an array. - * - * ```ts - * import { sql } from 'kysely' - * - * const items = await db.selectFrom([ - * 'person as p', - * db.selectFrom('pet').select('pet.species').as('a'), - * sql<{ one: number }>`(select 1 as one)`.as('q') - * ]) - * .select(['p.id', 'a.species', 'q.one']) - * .execute() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * select "p".id, "a"."species", "q"."one" - * from - * "person" as "p", - * (select "pet"."species" from "pet") as a, - * (select 1 as one) as "q" - * ``` - */ - selectFrom(from) { - return createSelectQueryBuilder({ - queryId: createQueryId(), - executor: this.#props.executor, - queryNode: SelectQueryNode.createFrom(parseTableExpressionOrList(from), this.#props.withNode) - }); - } - selectNoFrom(selection) { - return createSelectQueryBuilder({ - queryId: createQueryId(), - executor: this.#props.executor, - queryNode: SelectQueryNode.cloneWithSelections(SelectQueryNode.create(this.#props.withNode), parseSelectArg(selection)) - }); - } - /** - * Creates an insert query. - * - * The return value of this query is an instance of {@link InsertResult}. {@link InsertResult} - * has the {@link InsertResult.insertId | insertId} field that holds the auto incremented id of - * the inserted row if the db returned one. - * - * See the {@link InsertQueryBuilder.values | values} method for more info and examples. Also see - * the {@link ReturningInterface.returning | returning} method for a way to return columns - * on supported databases like PostgreSQL. - * - * ### Examples - * - * ```ts - * const result = await db - * .insertInto('person') - * .values({ - * first_name: 'Jennifer', - * last_name: 'Aniston' - * }) - * .executeTakeFirst() - * - * console.log(result.insertId) - * ``` - * - * Some databases like PostgreSQL support the `returning` method: - * - * ```ts - * const { id } = await db - * .insertInto('person') - * .values({ - * first_name: 'Jennifer', - * last_name: 'Aniston' - * }) - * .returning('id') - * .executeTakeFirstOrThrow() - * ``` - */ - insertInto(table) { - return new InsertQueryBuilder({ - queryId: createQueryId(), - executor: this.#props.executor, - queryNode: InsertQueryNode.create(parseTable(table), this.#props.withNode) - }); - } - /** - * Creates a "replace into" query. - * - * This is only supported by some dialects like MySQL or SQLite. - * - * Similar to MySQL's {@link InsertQueryBuilder.onDuplicateKeyUpdate} that deletes - * and inserts values on collision instead of updating existing rows. - * - * An alias of SQLite's {@link InsertQueryBuilder.orReplace}. - * - * The return value of this query is an instance of {@link InsertResult}. {@link InsertResult} - * has the {@link InsertResult.insertId | insertId} field that holds the auto incremented id of - * the inserted row if the db returned one. - * - * See the {@link InsertQueryBuilder.values | values} method for more info and examples. - * - * ### Examples - * - * ```ts - * const result = await db - * .replaceInto('person') - * .values({ - * first_name: 'Jennifer', - * last_name: 'Aniston' - * }) - * .executeTakeFirstOrThrow() - * - * console.log(result.insertId) - * ``` - * - * The generated SQL (MySQL): - * - * ```sql - * replace into `person` (`first_name`, `last_name`) values (?, ?) - * ``` - */ - replaceInto(table) { - return new InsertQueryBuilder({ - queryId: createQueryId(), - executor: this.#props.executor, - queryNode: InsertQueryNode.create(parseTable(table), this.#props.withNode, true) - }); - } - /** - * Creates a delete query. - * - * See the {@link DeleteQueryBuilder.where} method for examples on how to specify - * a where clause for the delete operation. - * - * The return value of the query is an instance of {@link DeleteResult}. - * - * ### Examples - * - * - * - * Delete a single row: - * - * ```ts - * const result = await db - * .deleteFrom('person') - * .where('person.id', '=', 1) - * .executeTakeFirst() - * - * console.log(result.numDeletedRows) - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * delete from "person" where "person"."id" = $1 - * ``` - * - * Some databases such as MySQL support deleting from multiple tables: - * - * ```ts - * const result = await db - * .deleteFrom(['person', 'pet']) - * .using('person') - * .innerJoin('pet', 'pet.owner_id', 'person.id') - * .where('person.id', '=', 1) - * .executeTakeFirst() - * ``` - * - * The generated SQL (MySQL): - * - * ```sql - * delete from `person`, `pet` - * using `person` - * inner join `pet` on `pet`.`owner_id` = `person`.`id` - * where `person`.`id` = ? - * ``` - */ - deleteFrom(from) { - return new DeleteQueryBuilder({ - queryId: createQueryId(), - executor: this.#props.executor, - queryNode: DeleteQueryNode.create(parseTableExpressionOrList(from), this.#props.withNode) - }); - } - /** - * Creates an update query. - * - * See the {@link UpdateQueryBuilder.where} method for examples on how to specify - * a where clause for the update operation. - * - * See the {@link UpdateQueryBuilder.set} method for examples on how to - * specify the updates. - * - * The return value of the query is an {@link UpdateResult}. - * - * ### Examples - * - * ```ts - * const result = await db - * .updateTable('person') - * .set({ first_name: 'Jennifer' }) - * .where('person.id', '=', 1) - * .executeTakeFirst() - * - * console.log(result.numUpdatedRows) - * ``` - */ - updateTable(tables) { - return new UpdateQueryBuilder({ - queryId: createQueryId(), - executor: this.#props.executor, - queryNode: UpdateQueryNode.create(parseTableExpressionOrList(tables), this.#props.withNode) - }); - } - /** - * Creates a merge query. - * - * The return value of the query is a {@link MergeResult}. - * - * See the {@link MergeQueryBuilder.using} method for examples on how to specify - * the other table. - * - * ### Examples - * - * - * - * Update a target column based on the existence of a source row: - * - * ```ts - * const result = await db - * .mergeInto('person as target') - * .using('pet as source', 'source.owner_id', 'target.id') - * .whenMatchedAnd('target.has_pets', '!=', 'Y') - * .thenUpdateSet({ has_pets: 'Y' }) - * .whenNotMatchedBySourceAnd('target.has_pets', '=', 'Y') - * .thenUpdateSet({ has_pets: 'N' }) - * .executeTakeFirstOrThrow() - * - * console.log(result.numChangedRows) - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * merge into "person" - * using "pet" - * on "pet"."owner_id" = "person"."id" - * when matched and "has_pets" != $1 - * then update set "has_pets" = $2 - * when not matched by source and "has_pets" = $3 - * then update set "has_pets" = $4 - * ``` - * - * - * - * Merge new entries from a temporary changes table: - * - * ```ts - * const result = await db - * .mergeInto('wine as target') - * .using( - * 'wine_stock_change as source', - * 'source.wine_name', - * 'target.name', - * ) - * .whenNotMatchedAnd('source.stock_delta', '>', 0) - * .thenInsertValues(({ ref }) => ({ - * name: ref('source.wine_name'), - * stock: ref('source.stock_delta'), - * })) - * .whenMatchedAnd( - * (eb) => eb('target.stock', '+', eb.ref('source.stock_delta')), - * '>', - * 0, - * ) - * .thenUpdateSet('stock', (eb) => - * eb('target.stock', '+', eb.ref('source.stock_delta')), - * ) - * .whenMatched() - * .thenDelete() - * .executeTakeFirstOrThrow() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * merge into "wine" as "target" - * using "wine_stock_change" as "source" - * on "source"."wine_name" = "target"."name" - * when not matched and "source"."stock_delta" > $1 - * then insert ("name", "stock") values ("source"."wine_name", "source"."stock_delta") - * when matched and "target"."stock" + "source"."stock_delta" > $2 - * then update set "stock" = "target"."stock" + "source"."stock_delta" - * when matched - * then delete - * ``` - */ - mergeInto(targetTable) { - return new MergeQueryBuilder({ - queryId: createQueryId(), - executor: this.#props.executor, - queryNode: MergeQueryNode.create(parseAliasedTable(targetTable), this.#props.withNode) - }); - } - /** - * Creates a `with` query (Common Table Expression). - * - * ### Examples - * - * - * - * Common table expressions (CTE) are a great way to modularize complex queries. - * Essentially they allow you to run multiple separate queries within a - * single roundtrip to the DB. - * - * Since CTEs are a part of the main query, query optimizers inside DB - * engines are able to optimize the overall query. For example, postgres - * is able to inline the CTEs inside the using queries if it decides it's - * faster. - * - * ```ts - * const result = await db - * // Create a CTE called `jennifers` that selects all - * // persons named 'Jennifer'. - * .with('jennifers', (db) => db - * .selectFrom('person') - * .where('first_name', '=', 'Jennifer') - * .select(['id', 'age']) - * ) - * // Select all rows from the `jennifers` CTE and - * // further filter it. - * .with('adult_jennifers', (db) => db - * .selectFrom('jennifers') - * .where('age', '>', 18) - * .select(['id', 'age']) - * ) - * // Finally select all adult jennifers that are - * // also younger than 60. - * .selectFrom('adult_jennifers') - * .where('age', '<', 60) - * .selectAll() - * .execute() - * ``` - * - * - * - * Some databases like postgres also allow you to run other queries than selects - * in CTEs. On these databases CTEs are extremely powerful: - * - * ```ts - * const result = await db - * .with('new_person', (db) => db - * .insertInto('person') - * .values({ - * first_name: 'Jennifer', - * age: 35, - * }) - * .returning('id') - * ) - * .with('new_pet', (db) => db - * .insertInto('pet') - * .values({ - * name: 'Doggo', - * species: 'dog', - * is_favorite: true, - * // Use the id of the person we just inserted. - * owner_id: db - * .selectFrom('new_person') - * .select('id') - * }) - * .returning('id') - * ) - * .selectFrom(['new_person', 'new_pet']) - * .select([ - * 'new_person.id as person_id', - * 'new_pet.id as pet_id' - * ]) - * .execute() - * ``` - * - * The CTE name can optionally specify column names in addition to - * a name. In that case Kysely requires the expression to retun - * rows with the same columns. - * - * ```ts - * await db - * .with('jennifers(id, age)', (db) => db - * .selectFrom('person') - * .where('first_name', '=', 'Jennifer') - * // This is ok since we return columns with the same - * // names as specified by `jennifers(id, age)`. - * .select(['id', 'age']) - * ) - * .selectFrom('jennifers') - * .selectAll() - * .execute() - * ``` - * - * The first argument can also be a callback. The callback is passed - * a `CTEBuilder` instance that can be used to configure the CTE: - * - * ```ts - * await db - * .with( - * (cte) => cte('jennifers').materialized(), - * (db) => db - * .selectFrom('person') - * .where('first_name', '=', 'Jennifer') - * .select(['id', 'age']) - * ) - * .selectFrom('jennifers') - * .selectAll() - * .execute() - * ``` - */ - with(nameOrBuilder, expression) { - const cte = parseCommonTableExpression(nameOrBuilder, expression); - return new _QueryCreator({ - ...this.#props, - withNode: this.#props.withNode ? WithNode.cloneWithExpression(this.#props.withNode, cte) : WithNode.create(cte) - }); - } - /** - * Creates a recursive `with` query (Common Table Expression). - * - * Note that recursiveness is a property of the whole `with` statement. - * You cannot have recursive and non-recursive CTEs in a same `with` statement. - * Therefore the recursiveness is determined by the **first** `with` or - * `withRecusive` call you make. - * - * See the {@link with} method for examples and more documentation. - */ - withRecursive(nameOrBuilder, expression) { - const cte = parseCommonTableExpression(nameOrBuilder, expression); - return new _QueryCreator({ - ...this.#props, - withNode: this.#props.withNode ? WithNode.cloneWithExpression(this.#props.withNode, cte) : WithNode.create(cte, { recursive: true }) - }); - } - /** - * Returns a copy of this query creator instance with the given plugin installed. - */ - withPlugin(plugin) { - return new _QueryCreator({ - ...this.#props, - executor: this.#props.executor.withPlugin(plugin) - }); - } - /** - * Returns a copy of this query creator instance without any plugins. - */ - withoutPlugins() { - return new _QueryCreator({ - ...this.#props, - executor: this.#props.executor.withoutPlugins() - }); - } - /** - * Sets the schema to be used for all table references that don't explicitly - * specify a schema. - * - * This only affects the query created through the builder returned from - * this method and doesn't modify the `db` instance. - * - * See [this recipe](https://github.com/kysely-org/kysely/blob/master/site/docs/recipes/0007-schemas.md) - * for a more detailed explanation. - * - * ### Examples - * - * ``` - * await db - * .withSchema('mammals') - * .selectFrom('pet') - * .selectAll() - * .innerJoin('public.person', 'public.person.id', 'pet.owner_id') - * .execute() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * select * from "mammals"."pet" - * inner join "public"."person" - * on "public"."person"."id" = "mammals"."pet"."owner_id" - * ``` - * - * `withSchema` is smart enough to not add schema for aliases, - * common table expressions or other places where the schema - * doesn't belong to: - * - * ``` - * await db - * .withSchema('mammals') - * .selectFrom('pet as p') - * .select('p.name') - * .execute() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * select "p"."name" from "mammals"."pet" as "p" - * ``` - */ - withSchema(schema2) { - return new _QueryCreator({ - ...this.#props, - executor: this.#props.executor.withPluginAtFront(new WithSchemaPlugin(schema2)) - }); - } - }; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/parse-utils.js -function createQueryCreator() { - return new QueryCreator({ - executor: NOOP_QUERY_EXECUTOR - }); -} -function createJoinBuilder(joinType, table) { - return new JoinBuilder({ - joinNode: JoinNode.create(joinType, parseTableExpression(table)) - }); -} -function createOverBuilder() { - return new OverBuilder({ - overNode: OverNode.create() - }); -} -var init_parse_utils2 = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/parse-utils.js"() { - init_join_node(); - init_over_node(); - init_join_builder(); - init_over_builder(); - init_query_creator(); - init_noop_query_executor(); - init_table_parser(); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/join-parser.js -function parseJoin(joinType, args) { - if (args.length === 3) { - return parseSingleOnJoin(joinType, args[0], args[1], args[2]); - } else if (args.length === 2) { - return parseCallbackJoin(joinType, args[0], args[1]); - } else if (args.length === 1) { - return parseOnlessJoin(joinType, args[0]); - } else { - throw new Error("not implemented"); - } -} -function parseCallbackJoin(joinType, from, callback) { - return callback(createJoinBuilder(joinType, from)).toOperationNode(); -} -function parseSingleOnJoin(joinType, from, lhsColumn, rhsColumn) { - return JoinNode.createWithOn(joinType, parseTableExpression(from), parseReferentialBinaryOperation(lhsColumn, "=", rhsColumn)); -} -function parseOnlessJoin(joinType, from) { - return JoinNode.create(joinType, parseTableExpression(from)); -} -var init_join_parser = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/join-parser.js"() { - init_join_node(); - init_binary_operation_parser(); - init_parse_utils2(); - init_table_parser(); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/offset-node.js -var OffsetNode; -var init_offset_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/offset-node.js"() { - init_object_utils(); - OffsetNode = freeze2({ - is(node) { - return node.kind === "OffsetNode"; - }, - create(offset) { - return freeze2({ - kind: "OffsetNode", - offset - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/group-by-item-node.js -var GroupByItemNode; -var init_group_by_item_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/group-by-item-node.js"() { - init_object_utils(); - GroupByItemNode = freeze2({ - is(node) { - return node.kind === "GroupByItemNode"; - }, - create(groupBy) { - return freeze2({ - kind: "GroupByItemNode", - groupBy - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/group-by-parser.js -function parseGroupBy(groupBy) { - groupBy = isFunction(groupBy) ? groupBy(expressionBuilder()) : groupBy; - return parseReferenceExpressionOrList(groupBy).map(GroupByItemNode.create); -} -var init_group_by_parser = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/group-by-parser.js"() { - init_group_by_item_node(); - init_expression_builder(); - init_object_utils(); - init_reference_parser(); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/set-operation-node.js -var SetOperationNode; -var init_set_operation_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/set-operation-node.js"() { - init_object_utils(); - SetOperationNode = freeze2({ - is(node) { - return node.kind === "SetOperationNode"; - }, - create(operator, expression, all) { - return freeze2({ - kind: "SetOperationNode", - operator, - expression, - all - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/set-operation-parser.js -function parseSetOperations(operator, expression, all) { - if (isFunction(expression)) { - expression = expression(createExpressionBuilder()); - } - if (!isReadonlyArray(expression)) { - expression = [expression]; - } - return expression.map((expr) => SetOperationNode.create(operator, parseExpression(expr), all)); -} -var init_set_operation_parser = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/set-operation-parser.js"() { - init_expression_builder(); - init_set_operation_node(); - init_object_utils(); - init_expression_parser(); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/expression/expression-wrapper.js -var ExpressionWrapper, AliasedExpressionWrapper, OrWrapper, AndWrapper; -var init_expression_wrapper = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/expression/expression-wrapper.js"() { - init_alias_node(); - init_and_node(); - init_identifier_node(); - init_operation_node_source(); - init_or_node(); - init_parens_node(); - init_binary_operation_parser(); - ExpressionWrapper = class _ExpressionWrapper { - #node; - constructor(node) { - this.#node = node; - } - /** @private */ - get expressionType() { - return void 0; - } - as(alias) { - return new AliasedExpressionWrapper(this, alias); - } - or(...args) { - return new OrWrapper(OrNode.create(this.#node, parseValueBinaryOperationOrExpression(args))); - } - and(...args) { - return new AndWrapper(AndNode.create(this.#node, parseValueBinaryOperationOrExpression(args))); - } - /** - * Change the output type of the expression. - * - * This method call doesn't change the SQL in any way. This methods simply - * returns a copy of this `ExpressionWrapper` with a new output type. - */ - $castTo() { - return new _ExpressionWrapper(this.#node); - } - /** - * Omit null from the expression's type. - * - * This function can be useful in cases where you know an expression can't be - * null, but Kysely is unable to infer it. - * - * This method call doesn't change the SQL in any way. This methods simply - * returns a copy of `this` with a new output type. - */ - $notNull() { - return new _ExpressionWrapper(this.#node); - } - toOperationNode() { - return this.#node; - } - }; - AliasedExpressionWrapper = class { - #expr; - #alias; - constructor(expr, alias) { - this.#expr = expr; - this.#alias = alias; - } - /** @private */ - get expression() { - return this.#expr; - } - /** @private */ - get alias() { - return this.#alias; - } - toOperationNode() { - return AliasNode.create(this.#expr.toOperationNode(), isOperationNodeSource(this.#alias) ? this.#alias.toOperationNode() : IdentifierNode.create(this.#alias)); - } - }; - OrWrapper = class _OrWrapper { - #node; - constructor(node) { - this.#node = node; - } - /** @private */ - get expressionType() { - return void 0; - } - as(alias) { - return new AliasedExpressionWrapper(this, alias); - } - or(...args) { - return new _OrWrapper(OrNode.create(this.#node, parseValueBinaryOperationOrExpression(args))); - } - /** - * Change the output type of the expression. - * - * This method call doesn't change the SQL in any way. This methods simply - * returns a copy of this `OrWrapper` with a new output type. - */ - $castTo() { - return new _OrWrapper(this.#node); - } - toOperationNode() { - return ParensNode.create(this.#node); - } - }; - AndWrapper = class _AndWrapper { - #node; - constructor(node) { - this.#node = node; - } - /** @private */ - get expressionType() { - return void 0; - } - as(alias) { - return new AliasedExpressionWrapper(this, alias); - } - and(...args) { - return new _AndWrapper(AndNode.create(this.#node, parseValueBinaryOperationOrExpression(args))); - } - /** - * Change the output type of the expression. - * - * This method call doesn't change the SQL in any way. This methods simply - * returns a copy of this `AndWrapper` with a new output type. - */ - $castTo() { - return new _AndWrapper(this.#node); - } - toOperationNode() { - return ParensNode.create(this.#node); - } - }; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/fetch-node.js -var FetchNode; -var init_fetch_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/fetch-node.js"() { - init_object_utils(); - init_value_node(); - FetchNode = freeze2({ - is(node) { - return node.kind === "FetchNode"; - }, - create(rowCount, modifier) { - return { - kind: "FetchNode", - rowCount: ValueNode.create(rowCount), - modifier - }; - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/fetch-parser.js -function parseFetch(rowCount, modifier) { - if (!isNumber(rowCount) && !isBigInt(rowCount)) { - throw new Error(`Invalid fetch row count: ${rowCount}`); - } - if (!isFetchModifier(modifier)) { - throw new Error(`Invalid fetch modifier: ${modifier}`); - } - return FetchNode.create(rowCount, modifier); -} -function isFetchModifier(value) { - return value === "only" || value === "with ties"; -} -var init_fetch_parser = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/fetch-parser.js"() { - init_fetch_node(); - init_object_utils(); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/select-query-builder.js -function createSelectQueryBuilder(props) { - return new SelectQueryBuilderImpl(props); -} -var _a5, SelectQueryBuilderImpl, AliasedSelectQueryBuilderImpl; -var init_select_query_builder = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/select-query-builder.js"() { - init_alias_node(); - init_select_modifier_node(); - init_join_parser(); - init_table_parser(); - init_select_parser(); - init_reference_parser(); - init_select_query_node(); - init_query_node(); - init_order_by_parser(); - init_limit_node(); - init_offset_node(); - init_object_utils(); - init_group_by_parser(); - init_no_result_error(); - init_identifier_node(); - init_set_operation_parser(); - init_binary_operation_parser(); - init_expression_wrapper(); - init_value_parser(); - init_fetch_parser(); - init_top_parser(); - SelectQueryBuilderImpl = class { - #props; - constructor(props) { - this.#props = freeze2(props); - } - get expressionType() { - return void 0; - } - get isSelectQueryBuilder() { - return true; - } - where(...args) { - return new _a5({ - ...this.#props, - queryNode: QueryNode.cloneWithWhere(this.#props.queryNode, parseValueBinaryOperationOrExpression(args)) - }); - } - whereRef(lhs, op2, rhs) { - return new _a5({ - ...this.#props, - queryNode: QueryNode.cloneWithWhere(this.#props.queryNode, parseReferentialBinaryOperation(lhs, op2, rhs)) - }); - } - having(...args) { - return new _a5({ - ...this.#props, - queryNode: SelectQueryNode.cloneWithHaving(this.#props.queryNode, parseValueBinaryOperationOrExpression(args)) - }); - } - havingRef(lhs, op2, rhs) { - return new _a5({ - ...this.#props, - queryNode: SelectQueryNode.cloneWithHaving(this.#props.queryNode, parseReferentialBinaryOperation(lhs, op2, rhs)) - }); - } - select(selection) { - return new _a5({ - ...this.#props, - queryNode: SelectQueryNode.cloneWithSelections(this.#props.queryNode, parseSelectArg(selection)) - }); - } - distinctOn(selection) { - return new _a5({ - ...this.#props, - queryNode: SelectQueryNode.cloneWithDistinctOn(this.#props.queryNode, parseReferenceExpressionOrList(selection)) - }); - } - modifyFront(modifier) { - return new _a5({ - ...this.#props, - queryNode: SelectQueryNode.cloneWithFrontModifier(this.#props.queryNode, SelectModifierNode.createWithExpression(modifier.toOperationNode())) - }); - } - modifyEnd(modifier) { - return new _a5({ - ...this.#props, - queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, SelectModifierNode.createWithExpression(modifier.toOperationNode())) - }); - } - distinct() { - return new _a5({ - ...this.#props, - queryNode: SelectQueryNode.cloneWithFrontModifier(this.#props.queryNode, SelectModifierNode.create("Distinct")) - }); - } - forUpdate(of) { - return new _a5({ - ...this.#props, - queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, SelectModifierNode.create("ForUpdate", of ? asArray(of).map(parseTable) : void 0)) - }); - } - forShare(of) { - return new _a5({ - ...this.#props, - queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, SelectModifierNode.create("ForShare", of ? asArray(of).map(parseTable) : void 0)) - }); - } - forKeyShare(of) { - return new _a5({ - ...this.#props, - queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, SelectModifierNode.create("ForKeyShare", of ? asArray(of).map(parseTable) : void 0)) - }); - } - forNoKeyUpdate(of) { - return new _a5({ - ...this.#props, - queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, SelectModifierNode.create("ForNoKeyUpdate", of ? asArray(of).map(parseTable) : void 0)) - }); - } - skipLocked() { - return new _a5({ - ...this.#props, - queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, SelectModifierNode.create("SkipLocked")) - }); - } - noWait() { - return new _a5({ - ...this.#props, - queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, SelectModifierNode.create("NoWait")) - }); - } - selectAll(table) { - return new _a5({ - ...this.#props, - queryNode: SelectQueryNode.cloneWithSelections(this.#props.queryNode, parseSelectAll(table)) - }); - } - innerJoin(...args) { - return this.#join("InnerJoin", args); - } - leftJoin(...args) { - return this.#join("LeftJoin", args); - } - rightJoin(...args) { - return this.#join("RightJoin", args); - } - fullJoin(...args) { - return this.#join("FullJoin", args); - } - crossJoin(...args) { - return this.#join("CrossJoin", args); - } - innerJoinLateral(...args) { - return this.#join("LateralInnerJoin", args); - } - leftJoinLateral(...args) { - return this.#join("LateralLeftJoin", args); - } - crossJoinLateral(...args) { - return this.#join("LateralCrossJoin", args); - } - crossApply(...args) { - return this.#join("CrossApply", args); - } - outerApply(...args) { - return this.#join("OuterApply", args); - } - #join(joinType, args) { - return new _a5({ - ...this.#props, - queryNode: QueryNode.cloneWithJoin(this.#props.queryNode, parseJoin(joinType, args)) - }); - } - orderBy(...args) { - return new _a5({ - ...this.#props, - queryNode: QueryNode.cloneWithOrderByItems(this.#props.queryNode, parseOrderBy(args)) - }); - } - groupBy(groupBy) { - return new _a5({ - ...this.#props, - queryNode: SelectQueryNode.cloneWithGroupByItems(this.#props.queryNode, parseGroupBy(groupBy)) - }); - } - limit(limit) { - return new _a5({ - ...this.#props, - queryNode: SelectQueryNode.cloneWithLimit(this.#props.queryNode, LimitNode.create(parseValueExpression(limit))) - }); - } - offset(offset) { - return new _a5({ - ...this.#props, - queryNode: SelectQueryNode.cloneWithOffset(this.#props.queryNode, OffsetNode.create(parseValueExpression(offset))) - }); - } - fetch(rowCount, modifier = "only") { - return new _a5({ - ...this.#props, - queryNode: SelectQueryNode.cloneWithFetch(this.#props.queryNode, parseFetch(rowCount, modifier)) - }); - } - top(expression, modifiers) { - return new _a5({ - ...this.#props, - queryNode: QueryNode.cloneWithTop(this.#props.queryNode, parseTop(expression, modifiers)) - }); - } - union(expression) { - return new _a5({ - ...this.#props, - queryNode: SelectQueryNode.cloneWithSetOperations(this.#props.queryNode, parseSetOperations("union", expression, false)) - }); - } - unionAll(expression) { - return new _a5({ - ...this.#props, - queryNode: SelectQueryNode.cloneWithSetOperations(this.#props.queryNode, parseSetOperations("union", expression, true)) - }); - } - intersect(expression) { - return new _a5({ - ...this.#props, - queryNode: SelectQueryNode.cloneWithSetOperations(this.#props.queryNode, parseSetOperations("intersect", expression, false)) - }); - } - intersectAll(expression) { - return new _a5({ - ...this.#props, - queryNode: SelectQueryNode.cloneWithSetOperations(this.#props.queryNode, parseSetOperations("intersect", expression, true)) - }); - } - except(expression) { - return new _a5({ - ...this.#props, - queryNode: SelectQueryNode.cloneWithSetOperations(this.#props.queryNode, parseSetOperations("except", expression, false)) - }); - } - exceptAll(expression) { - return new _a5({ - ...this.#props, - queryNode: SelectQueryNode.cloneWithSetOperations(this.#props.queryNode, parseSetOperations("except", expression, true)) - }); - } - as(alias) { - return new AliasedSelectQueryBuilderImpl(this, alias); - } - clearSelect() { - return new _a5({ - ...this.#props, - queryNode: SelectQueryNode.cloneWithoutSelections(this.#props.queryNode) - }); - } - clearWhere() { - return new _a5({ - ...this.#props, - queryNode: QueryNode.cloneWithoutWhere(this.#props.queryNode) - }); - } - clearLimit() { - return new _a5({ - ...this.#props, - queryNode: SelectQueryNode.cloneWithoutLimit(this.#props.queryNode) - }); - } - clearOffset() { - return new _a5({ - ...this.#props, - queryNode: SelectQueryNode.cloneWithoutOffset(this.#props.queryNode) - }); - } - clearOrderBy() { - return new _a5({ - ...this.#props, - queryNode: QueryNode.cloneWithoutOrderBy(this.#props.queryNode) - }); - } - clearGroupBy() { - return new _a5({ - ...this.#props, - queryNode: SelectQueryNode.cloneWithoutGroupBy(this.#props.queryNode) - }); - } - $call(func) { - return func(this); - } - $if(condition, func) { - if (condition) { - return func(this); - } - return new _a5({ - ...this.#props - }); - } - $castTo() { - return new _a5(this.#props); - } - $narrowType() { - return new _a5(this.#props); - } - $assertType() { - return new _a5(this.#props); - } - $asTuple() { - return new ExpressionWrapper(this.toOperationNode()); - } - $asScalar() { - return new ExpressionWrapper(this.toOperationNode()); - } - withPlugin(plugin) { - return new _a5({ - ...this.#props, - executor: this.#props.executor.withPlugin(plugin) - }); - } - toOperationNode() { - return this.#props.executor.transformQuery(this.#props.queryNode, this.#props.queryId); - } - compile() { - return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId); - } - async execute() { - const compiledQuery = this.compile(); - const result = await this.#props.executor.executeQuery(compiledQuery); - return result.rows; - } - async executeTakeFirst() { - const [result] = await this.execute(); - return result; - } - async executeTakeFirstOrThrow(errorConstructor = NoResultError) { - const result = await this.executeTakeFirst(); - if (result === void 0) { - const error50 = isNoResultErrorConstructor(errorConstructor) ? new errorConstructor(this.toOperationNode()) : errorConstructor(this.toOperationNode()); - throw error50; - } - return result; - } - async *stream(chunkSize = 100) { - const compiledQuery = this.compile(); - const stream = this.#props.executor.stream(compiledQuery, chunkSize); - for await (const item of stream) { - yield* item.rows; - } - } - async explain(format2, options) { - const builder = new _a5({ - ...this.#props, - queryNode: QueryNode.cloneWithExplain(this.#props.queryNode, format2, options) - }); - return await builder.execute(); - } - }; - _a5 = SelectQueryBuilderImpl; - AliasedSelectQueryBuilderImpl = class { - #queryBuilder; - #alias; - constructor(queryBuilder, alias) { - this.#queryBuilder = queryBuilder; - this.#alias = alias; - } - get expression() { - return this.#queryBuilder; - } - get alias() { - return this.#alias; - } - get isAliasedSelectQueryBuilder() { - return true; - } - toOperationNode() { - return AliasNode.create(this.#queryBuilder.toOperationNode(), IdentifierNode.create(this.#alias)); - } - }; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/aggregate-function-node.js -var AggregateFunctionNode; -var init_aggregate_function_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/aggregate-function-node.js"() { - init_object_utils(); - init_where_node(); - init_order_by_node(); - AggregateFunctionNode = freeze2({ - is(node) { - return node.kind === "AggregateFunctionNode"; - }, - create(aggregateFunction, aggregated = []) { - return freeze2({ - kind: "AggregateFunctionNode", - func: aggregateFunction, - aggregated - }); - }, - cloneWithDistinct(aggregateFunctionNode) { - return freeze2({ - ...aggregateFunctionNode, - distinct: true - }); - }, - cloneWithOrderBy(aggregateFunctionNode, orderItems, withinGroup = false) { - const prop = withinGroup ? "withinGroup" : "orderBy"; - return freeze2({ - ...aggregateFunctionNode, - [prop]: aggregateFunctionNode[prop] ? OrderByNode.cloneWithItems(aggregateFunctionNode[prop], orderItems) : OrderByNode.create(orderItems) - }); - }, - cloneWithFilter(aggregateFunctionNode, filter) { - return freeze2({ - ...aggregateFunctionNode, - filter: aggregateFunctionNode.filter ? WhereNode.cloneWithOperation(aggregateFunctionNode.filter, "And", filter) : WhereNode.create(filter) - }); - }, - cloneWithOrFilter(aggregateFunctionNode, filter) { - return freeze2({ - ...aggregateFunctionNode, - filter: aggregateFunctionNode.filter ? WhereNode.cloneWithOperation(aggregateFunctionNode.filter, "Or", filter) : WhereNode.create(filter) - }); - }, - cloneWithOver(aggregateFunctionNode, over) { - return freeze2({ - ...aggregateFunctionNode, - over - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/function-node.js -var FunctionNode; -var init_function_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/function-node.js"() { - init_object_utils(); - FunctionNode = freeze2({ - is(node) { - return node.kind === "FunctionNode"; - }, - create(func, args) { - return freeze2({ - kind: "FunctionNode", - func, - arguments: args - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/aggregate-function-builder.js -var AggregateFunctionBuilder, AliasedAggregateFunctionBuilder; -var init_aggregate_function_builder = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/aggregate-function-builder.js"() { - init_object_utils(); - init_aggregate_function_node(); - init_alias_node(); - init_identifier_node(); - init_parse_utils2(); - init_binary_operation_parser(); - init_order_by_parser(); - init_query_node(); - AggregateFunctionBuilder = class _AggregateFunctionBuilder { - #props; - constructor(props) { - this.#props = freeze2(props); - } - /** @private */ - get expressionType() { - return void 0; - } - /** - * Returns an aliased version of the function. - * - * In addition to slapping `as "the_alias"` to the end of the SQL, - * this method also provides strict typing: - * - * ```ts - * const result = await db - * .selectFrom('person') - * .select( - * (eb) => eb.fn.count('id').as('person_count') - * ) - * .executeTakeFirstOrThrow() - * - * // `person_count: number` field exists in the result type. - * console.log(result.person_count) - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * select count("id") as "person_count" - * from "person" - * ``` - */ - as(alias) { - return new AliasedAggregateFunctionBuilder(this, alias); - } - /** - * Adds a `distinct` clause inside the function. - * - * ### Examples - * - * ```ts - * const result = await db - * .selectFrom('person') - * .select((eb) => - * eb.fn.count('first_name').distinct().as('first_name_count') - * ) - * .executeTakeFirstOrThrow() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * select count(distinct "first_name") as "first_name_count" - * from "person" - * ``` - */ - distinct() { - return new _AggregateFunctionBuilder({ - ...this.#props, - aggregateFunctionNode: AggregateFunctionNode.cloneWithDistinct(this.#props.aggregateFunctionNode) - }); - } - orderBy(...args) { - return new _AggregateFunctionBuilder({ - ...this.#props, - aggregateFunctionNode: QueryNode.cloneWithOrderByItems(this.#props.aggregateFunctionNode, parseOrderBy(args)) - }); - } - clearOrderBy() { - return new _AggregateFunctionBuilder({ - ...this.#props, - aggregateFunctionNode: QueryNode.cloneWithoutOrderBy(this.#props.aggregateFunctionNode) - }); - } - withinGroupOrderBy(...args) { - return new _AggregateFunctionBuilder({ - ...this.#props, - aggregateFunctionNode: AggregateFunctionNode.cloneWithOrderBy(this.#props.aggregateFunctionNode, parseOrderBy(args), true) - }); - } - filterWhere(...args) { - return new _AggregateFunctionBuilder({ - ...this.#props, - aggregateFunctionNode: AggregateFunctionNode.cloneWithFilter(this.#props.aggregateFunctionNode, parseValueBinaryOperationOrExpression(args)) - }); - } - /** - * Adds a `filter` clause with a nested `where` clause after the function, where - * both sides of the operator are references to columns. - * - * Similar to {@link WhereInterface}'s `whereRef` method. - * - * ### Examples - * - * Count people with same first and last names versus general public: - * - * ```ts - * const result = await db - * .selectFrom('person') - * .select((eb) => [ - * eb.fn - * .count('id') - * .filterWhereRef('first_name', '=', 'last_name') - * .as('repeat_name_count'), - * eb.fn.count('id').as('total_count'), - * ]) - * .executeTakeFirstOrThrow() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * select - * count("id") filter(where "first_name" = "last_name") as "repeat_name_count", - * count("id") as "total_count" - * from "person" - * ``` - */ - filterWhereRef(lhs, op2, rhs) { - return new _AggregateFunctionBuilder({ - ...this.#props, - aggregateFunctionNode: AggregateFunctionNode.cloneWithFilter(this.#props.aggregateFunctionNode, parseReferentialBinaryOperation(lhs, op2, rhs)) - }); - } - /** - * Adds an `over` clause (window functions) after the function. - * - * ### Examples - * - * ```ts - * const result = await db - * .selectFrom('person') - * .select( - * (eb) => eb.fn.avg('age').over().as('average_age') - * ) - * .execute() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * select avg("age") over() as "average_age" - * from "person" - * ``` - * - * Also supports passing a callback that returns an over builder, - * allowing to add partition by and sort by clauses inside over. - * - * ```ts - * const result = await db - * .selectFrom('person') - * .select( - * (eb) => eb.fn.avg('age').over( - * ob => ob.partitionBy('last_name').orderBy('first_name', 'asc') - * ).as('average_age') - * ) - * .execute() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * select avg("age") over(partition by "last_name" order by "first_name" asc) as "average_age" - * from "person" - * ``` - */ - over(over) { - const builder = createOverBuilder(); - return new _AggregateFunctionBuilder({ - ...this.#props, - aggregateFunctionNode: AggregateFunctionNode.cloneWithOver(this.#props.aggregateFunctionNode, (over ? over(builder) : builder).toOperationNode()) - }); - } - /** - * Simply calls the provided function passing `this` as the only argument. `$call` returns - * what the provided function returns. - */ - $call(func) { - return func(this); - } - /** - * Casts the expression to the given type. - * - * This method call doesn't change the SQL in any way. This methods simply - * returns a copy of this `AggregateFunctionBuilder` with a new output type. - */ - $castTo() { - return new _AggregateFunctionBuilder(this.#props); - } - /** - * Omit null from the expression's type. - * - * This function can be useful in cases where you know an expression can't be - * null, but Kysely is unable to infer it. - * - * This method call doesn't change the SQL in any way. This methods simply - * returns a copy of `this` with a new output type. - */ - $notNull() { - return new _AggregateFunctionBuilder(this.#props); - } - toOperationNode() { - return this.#props.aggregateFunctionNode; - } - }; - AliasedAggregateFunctionBuilder = class { - #aggregateFunctionBuilder; - #alias; - constructor(aggregateFunctionBuilder, alias) { - this.#aggregateFunctionBuilder = aggregateFunctionBuilder; - this.#alias = alias; - } - /** @private */ - get expression() { - return this.#aggregateFunctionBuilder; - } - /** @private */ - get alias() { - return this.#alias; - } - toOperationNode() { - return AliasNode.create(this.#aggregateFunctionBuilder.toOperationNode(), IdentifierNode.create(this.#alias)); - } - }; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/function-module.js -function createFunctionModule() { - const fn = (name, args) => { - return new ExpressionWrapper(FunctionNode.create(name, parseReferenceExpressionOrList(args ?? []))); - }; - const agg = (name, args) => { - return new AggregateFunctionBuilder({ - aggregateFunctionNode: AggregateFunctionNode.create(name, args ? parseReferenceExpressionOrList(args) : void 0) - }); - }; - return Object.assign(fn, { - agg, - avg(column) { - return agg("avg", [column]); - }, - coalesce(...values2) { - return fn("coalesce", values2); - }, - count(column) { - return agg("count", [column]); - }, - countAll(table) { - return new AggregateFunctionBuilder({ - aggregateFunctionNode: AggregateFunctionNode.create("count", parseSelectAll(table)) - }); - }, - max(column) { - return agg("max", [column]); - }, - min(column) { - return agg("min", [column]); - }, - sum(column) { - return agg("sum", [column]); - }, - any(column) { - return fn("any", [column]); - }, - jsonAgg(table) { - return new AggregateFunctionBuilder({ - aggregateFunctionNode: AggregateFunctionNode.create("json_agg", [ - isString(table) ? parseTable(table) : table.toOperationNode() - ]) - }); - }, - toJson(table) { - return new ExpressionWrapper(FunctionNode.create("to_json", [ - isString(table) ? parseTable(table) : table.toOperationNode() - ])); - } - }); -} -var init_function_module = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/function-module.js"() { - init_expression_wrapper(); - init_aggregate_function_node(); - init_function_node(); - init_reference_parser(); - init_select_parser(); - init_aggregate_function_builder(); - init_object_utils(); - init_table_parser(); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/unary-operation-node.js -var UnaryOperationNode; -var init_unary_operation_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/unary-operation-node.js"() { - init_object_utils(); - UnaryOperationNode = freeze2({ - is(node) { - return node.kind === "UnaryOperationNode"; - }, - create(operator, operand) { - return freeze2({ - kind: "UnaryOperationNode", - operator, - operand - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/unary-operation-parser.js -function parseUnaryOperation(operator, operand) { - return UnaryOperationNode.create(OperatorNode.create(operator), parseReferenceExpression(operand)); -} -var init_unary_operation_parser = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/unary-operation-parser.js"() { - init_operator_node(); - init_unary_operation_node(); - init_reference_parser(); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/case-node.js -var CaseNode; -var init_case_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/case-node.js"() { - init_object_utils(); - init_when_node(); - CaseNode = freeze2({ - is(node) { - return node.kind === "CaseNode"; - }, - create(value) { - return freeze2({ - kind: "CaseNode", - value - }); - }, - cloneWithWhen(caseNode, when) { - return freeze2({ - ...caseNode, - when: freeze2(caseNode.when ? [...caseNode.when, when] : [when]) - }); - }, - cloneWithThen(caseNode, then) { - return freeze2({ - ...caseNode, - when: caseNode.when ? freeze2([ - ...caseNode.when.slice(0, -1), - WhenNode.cloneWithResult(caseNode.when[caseNode.when.length - 1], then) - ]) : void 0 - }); - }, - cloneWith(caseNode, props) { - return freeze2({ - ...caseNode, - ...props - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/case-builder.js -var CaseBuilder, CaseThenBuilder, CaseWhenBuilder, CaseEndBuilder; -var init_case_builder = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/case-builder.js"() { - init_expression_wrapper(); - init_object_utils(); - init_case_node(); - init_when_node(); - init_binary_operation_parser(); - init_value_parser(); - CaseBuilder = class { - #props; - constructor(props) { - this.#props = freeze2(props); - } - when(...args) { - return new CaseThenBuilder({ - ...this.#props, - node: CaseNode.cloneWithWhen(this.#props.node, WhenNode.create(parseValueBinaryOperationOrExpression(args))) - }); - } - }; - CaseThenBuilder = class { - #props; - constructor(props) { - this.#props = freeze2(props); - } - then(valueExpression) { - return new CaseWhenBuilder({ - ...this.#props, - node: CaseNode.cloneWithThen(this.#props.node, isSafeImmediateValue(valueExpression) ? parseSafeImmediateValue(valueExpression) : parseValueExpression(valueExpression)) - }); - } - }; - CaseWhenBuilder = class { - #props; - constructor(props) { - this.#props = freeze2(props); - } - when(...args) { - return new CaseThenBuilder({ - ...this.#props, - node: CaseNode.cloneWithWhen(this.#props.node, WhenNode.create(parseValueBinaryOperationOrExpression(args))) - }); - } - else(valueExpression) { - return new CaseEndBuilder({ - ...this.#props, - node: CaseNode.cloneWith(this.#props.node, { - else: isSafeImmediateValue(valueExpression) ? parseSafeImmediateValue(valueExpression) : parseValueExpression(valueExpression) - }) - }); - } - end() { - return new ExpressionWrapper(CaseNode.cloneWith(this.#props.node, { isStatement: false })); - } - endCase() { - return new ExpressionWrapper(CaseNode.cloneWith(this.#props.node, { isStatement: true })); - } - }; - CaseEndBuilder = class { - #props; - constructor(props) { - this.#props = freeze2(props); - } - end() { - return new ExpressionWrapper(CaseNode.cloneWith(this.#props.node, { isStatement: false })); - } - endCase() { - return new ExpressionWrapper(CaseNode.cloneWith(this.#props.node, { isStatement: true })); - } - }; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/json-path-leg-node.js -var JSONPathLegNode; -var init_json_path_leg_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/json-path-leg-node.js"() { - init_object_utils(); - JSONPathLegNode = freeze2({ - is(node) { - return node.kind === "JSONPathLegNode"; - }, - create(type, value) { - return freeze2({ - kind: "JSONPathLegNode", - type, - value - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/json-path-builder.js -var JSONPathBuilder, TraversedJSONPathBuilder, AliasedJSONPathBuilder; -var init_json_path_builder = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/json-path-builder.js"() { - init_alias_node(); - init_identifier_node(); - init_json_operator_chain_node(); - init_json_path_leg_node(); - init_json_path_node(); - init_json_reference_node(); - init_operation_node_source(); - init_value_node(); - JSONPathBuilder = class { - #node; - constructor(node) { - this.#node = node; - } - /** - * Access an element of a JSON array in a specific location. - * - * Since there's no guarantee an element exists in the given array location, the - * resulting type is always nullable. If you're sure the element exists, you - * should use {@link SelectQueryBuilder.$assertType} to narrow the type safely. - * - * See also {@link key} to access properties of JSON objects. - * - * ### Examples - * - * ```ts - * await db.selectFrom('person') - * .select(eb => - * eb.ref('nicknames', '->').at(0).as('primary_nickname') - * ) - * .execute() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * select "nicknames"->0 as "primary_nickname" from "person" - *``` - * - * Combined with {@link key}: - * - * ```ts - * db.selectFrom('person').select(eb => - * eb.ref('experience', '->').at(0).key('role').as('first_role') - * ) - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * select "experience"->0->'role' as "first_role" from "person" - * ``` - * - * You can use `'last'` to access the last element of the array in MySQL: - * - * ```ts - * db.selectFrom('person').select(eb => - * eb.ref('nicknames', '->$').at('last').as('last_nickname') - * ) - * ``` - * - * The generated SQL (MySQL): - * - * ```sql - * select `nicknames`->'$[last]' as `last_nickname` from `person` - * ``` - * - * Or `'#-1'` in SQLite: - * - * ```ts - * db.selectFrom('person').select(eb => - * eb.ref('nicknames', '->>$').at('#-1').as('last_nickname') - * ) - * ``` - * - * The generated SQL (SQLite): - * - * ```sql - * select "nicknames"->>'$[#-1]' as `last_nickname` from `person` - * ``` - */ - at(index2) { - return this.#createBuilderWithPathLeg("ArrayLocation", index2); - } - /** - * Access a property of a JSON object. - * - * If a field is optional, the resulting type will be nullable. - * - * See also {@link at} to access elements of JSON arrays. - * - * ### Examples - * - * ```ts - * db.selectFrom('person').select(eb => - * eb.ref('address', '->').key('city').as('city') - * ) - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * select "address"->'city' as "city" from "person" - * ``` - * - * Going deeper: - * - * ```ts - * db.selectFrom('person').select(eb => - * eb.ref('profile', '->$').key('website').key('url').as('website_url') - * ) - * ``` - * - * The generated SQL (MySQL): - * - * ```sql - * select `profile`->'$.website.url' as `website_url` from `person` - * ``` - * - * Combined with {@link at}: - * - * ```ts - * db.selectFrom('person').select(eb => - * eb.ref('profile', '->').key('addresses').at(0).key('city').as('city') - * ) - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * select "profile"->'addresses'->0->'city' as "city" from "person" - * ``` - */ - key(key) { - return this.#createBuilderWithPathLeg("Member", key); - } - #createBuilderWithPathLeg(legType, value) { - if (JSONReferenceNode.is(this.#node)) { - return new TraversedJSONPathBuilder(JSONReferenceNode.cloneWithTraversal(this.#node, JSONPathNode.is(this.#node.traversal) ? JSONPathNode.cloneWithLeg(this.#node.traversal, JSONPathLegNode.create(legType, value)) : JSONOperatorChainNode.cloneWithValue(this.#node.traversal, ValueNode.createImmediate(value)))); - } - return new TraversedJSONPathBuilder(JSONPathNode.cloneWithLeg(this.#node, JSONPathLegNode.create(legType, value))); - } - }; - TraversedJSONPathBuilder = class _TraversedJSONPathBuilder extends JSONPathBuilder { - #node; - constructor(node) { - super(node); - this.#node = node; - } - /** @private */ - get expressionType() { - return void 0; - } - as(alias) { - return new AliasedJSONPathBuilder(this, alias); - } - /** - * Change the output type of the json path. - * - * This method call doesn't change the SQL in any way. This methods simply - * returns a copy of this `JSONPathBuilder` with a new output type. - */ - $castTo() { - return new _TraversedJSONPathBuilder(this.#node); - } - $notNull() { - return new _TraversedJSONPathBuilder(this.#node); - } - toOperationNode() { - return this.#node; - } - }; - AliasedJSONPathBuilder = class { - #jsonPath; - #alias; - constructor(jsonPath, alias) { - this.#jsonPath = jsonPath; - this.#alias = alias; - } - /** @private */ - get expression() { - return this.#jsonPath; - } - /** @private */ - get alias() { - return this.#alias; - } - toOperationNode() { - return AliasNode.create(this.#jsonPath.toOperationNode(), isOperationNodeSource(this.#alias) ? this.#alias.toOperationNode() : IdentifierNode.create(this.#alias)); - } - }; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/tuple-node.js -var TupleNode; -var init_tuple_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/tuple-node.js"() { - init_object_utils(); - TupleNode = freeze2({ - is(node) { - return node.kind === "TupleNode"; - }, - create(values2) { - return freeze2({ - kind: "TupleNode", - values: freeze2(values2) - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/data-type-node.js -function isColumnDataType(dataType) { - if (SIMPLE_COLUMN_DATA_TYPES.includes(dataType)) { - return true; - } - if (COLUMN_DATA_TYPE_REGEX.some((r5) => r5.test(dataType))) { - return true; - } - return false; -} -var SIMPLE_COLUMN_DATA_TYPES, COLUMN_DATA_TYPE_REGEX, DataTypeNode; -var init_data_type_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/data-type-node.js"() { - init_object_utils(); - SIMPLE_COLUMN_DATA_TYPES = [ - "varchar", - "char", - "text", - "integer", - "int2", - "int4", - "int8", - "smallint", - "bigint", - "boolean", - "real", - "double precision", - "float4", - "float8", - "decimal", - "numeric", - "binary", - "bytea", - "date", - "datetime", - "time", - "timetz", - "timestamp", - "timestamptz", - "serial", - "bigserial", - "uuid", - "json", - "jsonb", - "blob", - "varbinary", - "int4range", - "int4multirange", - "int8range", - "int8multirange", - "numrange", - "nummultirange", - "tsrange", - "tsmultirange", - "tstzrange", - "tstzmultirange", - "daterange", - "datemultirange" - ]; - COLUMN_DATA_TYPE_REGEX = [ - /^varchar\(\d+\)$/, - /^char\(\d+\)$/, - /^decimal\(\d+, \d+\)$/, - /^numeric\(\d+, \d+\)$/, - /^binary\(\d+\)$/, - /^datetime\(\d+\)$/, - /^time\(\d+\)$/, - /^timetz\(\d+\)$/, - /^timestamp\(\d+\)$/, - /^timestamptz\(\d+\)$/, - /^varbinary\(\d+\)$/ - ]; - DataTypeNode = freeze2({ - is(node) { - return node.kind === "DataTypeNode"; - }, - create(dataType) { - return freeze2({ - kind: "DataTypeNode", - dataType - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/data-type-parser.js -function parseDataTypeExpression(dataType) { - if (isOperationNodeSource(dataType)) { - return dataType.toOperationNode(); - } - if (isColumnDataType(dataType)) { - return DataTypeNode.create(dataType); - } - throw new Error(`invalid column data type ${JSON.stringify(dataType)}`); -} -var init_data_type_parser = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/data-type-parser.js"() { - init_data_type_node(); - init_operation_node_source(); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/cast-node.js -var CastNode; -var init_cast_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/cast-node.js"() { - init_object_utils(); - CastNode = freeze2({ - is(node) { - return node.kind === "CastNode"; - }, - create(expression, dataType) { - return freeze2({ - kind: "CastNode", - expression, - dataType - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/expression/expression-builder.js -function createExpressionBuilder(executor = NOOP_QUERY_EXECUTOR) { - function binary2(lhs, op2, rhs) { - return new ExpressionWrapper(parseValueBinaryOperation(lhs, op2, rhs)); - } - function unary(op2, expr) { - return new ExpressionWrapper(parseUnaryOperation(op2, expr)); - } - const eb = Object.assign(binary2, { - fn: void 0, - eb: void 0, - selectFrom(table) { - return createSelectQueryBuilder({ - queryId: createQueryId(), - executor, - queryNode: SelectQueryNode.createFrom(parseTableExpressionOrList(table)) - }); - }, - case(reference) { - return new CaseBuilder({ - node: CaseNode.create(isUndefined(reference) ? void 0 : parseReferenceExpression(reference)) - }); - }, - ref(reference, op2) { - if (isUndefined(op2)) { - return new ExpressionWrapper(parseStringReference(reference)); - } - return new JSONPathBuilder(parseJSONReference(reference, op2)); - }, - jsonPath() { - return new JSONPathBuilder(JSONPathNode.create()); - }, - table(table) { - return new ExpressionWrapper(parseTable(table)); - }, - val(value) { - return new ExpressionWrapper(parseValueExpression(value)); - }, - refTuple(...values2) { - return new ExpressionWrapper(TupleNode.create(values2.map(parseReferenceExpression))); - }, - tuple(...values2) { - return new ExpressionWrapper(TupleNode.create(values2.map(parseValueExpression))); - }, - lit(value) { - return new ExpressionWrapper(parseSafeImmediateValue(value)); - }, - unary, - not(expr) { - return unary("not", expr); - }, - exists(expr) { - return unary("exists", expr); - }, - neg(expr) { - return unary("-", expr); - }, - between(expr, start, end) { - return new ExpressionWrapper(BinaryOperationNode.create(parseReferenceExpression(expr), OperatorNode.create("between"), AndNode.create(parseValueExpression(start), parseValueExpression(end)))); - }, - betweenSymmetric(expr, start, end) { - return new ExpressionWrapper(BinaryOperationNode.create(parseReferenceExpression(expr), OperatorNode.create("between symmetric"), AndNode.create(parseValueExpression(start), parseValueExpression(end)))); - }, - and(exprs) { - if (isReadonlyArray(exprs)) { - return new ExpressionWrapper(parseFilterList(exprs, "and")); - } - return new ExpressionWrapper(parseFilterObject(exprs, "and")); - }, - or(exprs) { - if (isReadonlyArray(exprs)) { - return new ExpressionWrapper(parseFilterList(exprs, "or")); - } - return new ExpressionWrapper(parseFilterObject(exprs, "or")); - }, - parens(...args) { - const node = parseValueBinaryOperationOrExpression(args); - if (ParensNode.is(node)) { - return new ExpressionWrapper(node); - } else { - return new ExpressionWrapper(ParensNode.create(node)); - } - }, - cast(expr, dataType) { - return new ExpressionWrapper(CastNode.create(parseReferenceExpression(expr), parseDataTypeExpression(dataType))); - }, - withSchema(schema2) { - return createExpressionBuilder(executor.withPluginAtFront(new WithSchemaPlugin(schema2))); - } - }); - eb.fn = createFunctionModule(); - eb.eb = eb; - return eb; -} -function expressionBuilder(_) { - return createExpressionBuilder(); -} -var init_expression_builder = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/expression/expression-builder.js"() { - init_select_query_builder(); - init_select_query_node(); - init_table_parser(); - init_with_schema_plugin(); - init_query_id(); - init_function_module(); - init_reference_parser(); - init_binary_operation_parser(); - init_parens_node(); - init_expression_wrapper(); - init_operator_node(); - init_unary_operation_parser(); - init_value_parser(); - init_noop_query_executor(); - init_case_builder(); - init_case_node(); - init_object_utils(); - init_json_path_builder(); - init_binary_operation_node(); - init_and_node(); - init_tuple_node(); - init_json_path_node(); - init_data_type_parser(); - init_cast_node(); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/expression-parser.js -function parseExpression(exp) { - if (isOperationNodeSource(exp)) { - return exp.toOperationNode(); - } else if (isFunction(exp)) { - return exp(expressionBuilder()).toOperationNode(); - } - throw new Error(`invalid expression: ${JSON.stringify(exp)}`); -} -function parseAliasedExpression(exp) { - if (isOperationNodeSource(exp)) { - return exp.toOperationNode(); - } else if (isFunction(exp)) { - return exp(expressionBuilder()).toOperationNode(); - } - throw new Error(`invalid aliased expression: ${JSON.stringify(exp)}`); -} -function isExpressionOrFactory(obj) { - return isExpression(obj) || isAliasedExpression(obj) || isFunction(obj); -} -var init_expression_parser = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/expression-parser.js"() { - init_expression(); - init_operation_node_source(); - init_expression_builder(); - init_object_utils(); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dynamic/dynamic-table-builder.js -function isAliasedDynamicTableBuilder(obj) { - return isObject3(obj) && isOperationNodeSource(obj) && isString(obj.table) && isString(obj.alias); -} -var DynamicTableBuilder, AliasedDynamicTableBuilder; -var init_dynamic_table_builder = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dynamic/dynamic-table-builder.js"() { - init_alias_node(); - init_identifier_node(); - init_operation_node_source(); - init_table_parser(); - init_object_utils(); - DynamicTableBuilder = class { - #table; - get table() { - return this.#table; - } - constructor(table) { - this.#table = table; - } - as(alias) { - return new AliasedDynamicTableBuilder(this.#table, alias); - } - }; - AliasedDynamicTableBuilder = class { - #table; - #alias; - get table() { - return this.#table; - } - get alias() { - return this.#alias; - } - constructor(table, alias) { - this.#table = table; - this.#alias = alias; - } - toOperationNode() { - return AliasNode.create(parseTable(this.#table), IdentifierNode.create(this.#alias)); - } - }; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/table-parser.js -function parseTableExpressionOrList(table) { - if (isReadonlyArray(table)) { - return table.map((it) => parseTableExpression(it)); - } else { - return [parseTableExpression(table)]; - } -} -function parseTableExpression(table) { - if (isString(table)) { - return parseAliasedTable(table); - } else if (isAliasedDynamicTableBuilder(table)) { - return table.toOperationNode(); - } else { - return parseAliasedExpression(table); - } -} -function parseAliasedTable(from) { - const ALIAS_SEPARATOR = " as "; - if (from.includes(ALIAS_SEPARATOR)) { - const [table, alias] = from.split(ALIAS_SEPARATOR).map(trim2); - return AliasNode.create(parseTable(table), IdentifierNode.create(alias)); - } else { - return parseTable(from); - } -} -function parseTable(from) { - const SCHEMA_SEPARATOR = "."; - if (from.includes(SCHEMA_SEPARATOR)) { - const [schema2, table] = from.split(SCHEMA_SEPARATOR).map(trim2); - return TableNode.createWithSchema(schema2, table); - } else { - return TableNode.create(from); - } -} -function trim2(str) { - return str.trim(); -} -var init_table_parser = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/table-parser.js"() { - init_object_utils(); - init_alias_node(); - init_table_node(); - init_expression_parser(); - init_identifier_node(); - init_dynamic_table_builder(); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/add-column-node.js -var AddColumnNode; -var init_add_column_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/add-column-node.js"() { - init_object_utils(); - AddColumnNode = freeze2({ - is(node) { - return node.kind === "AddColumnNode"; - }, - create(column) { - return freeze2({ - kind: "AddColumnNode", - column - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/column-definition-node.js -var ColumnDefinitionNode; -var init_column_definition_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/column-definition-node.js"() { - init_object_utils(); - init_column_node(); - ColumnDefinitionNode = freeze2({ - is(node) { - return node.kind === "ColumnDefinitionNode"; - }, - create(column, dataType) { - return freeze2({ - kind: "ColumnDefinitionNode", - column: ColumnNode.create(column), - dataType - }); - }, - cloneWithFrontModifier(node, modifier) { - return freeze2({ - ...node, - frontModifiers: node.frontModifiers ? freeze2([...node.frontModifiers, modifier]) : [modifier] - }); - }, - cloneWithEndModifier(node, modifier) { - return freeze2({ - ...node, - endModifiers: node.endModifiers ? freeze2([...node.endModifiers, modifier]) : [modifier] - }); - }, - cloneWith(node, props) { - return freeze2({ - ...node, - ...props - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/drop-column-node.js -var DropColumnNode; -var init_drop_column_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/drop-column-node.js"() { - init_object_utils(); - init_column_node(); - DropColumnNode = freeze2({ - is(node) { - return node.kind === "DropColumnNode"; - }, - create(column) { - return freeze2({ - kind: "DropColumnNode", - column: ColumnNode.create(column) - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/rename-column-node.js -var RenameColumnNode; -var init_rename_column_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/rename-column-node.js"() { - init_object_utils(); - init_column_node(); - RenameColumnNode = freeze2({ - is(node) { - return node.kind === "RenameColumnNode"; - }, - create(column, newColumn) { - return freeze2({ - kind: "RenameColumnNode", - column: ColumnNode.create(column), - renameTo: ColumnNode.create(newColumn) - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/check-constraint-node.js -var CheckConstraintNode; -var init_check_constraint_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/check-constraint-node.js"() { - init_object_utils(); - init_identifier_node(); - CheckConstraintNode = freeze2({ - is(node) { - return node.kind === "CheckConstraintNode"; - }, - create(expression, constraintName) { - return freeze2({ - kind: "CheckConstraintNode", - expression, - name: constraintName ? IdentifierNode.create(constraintName) : void 0 - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/references-node.js -var ON_MODIFY_FOREIGN_ACTIONS, ReferencesNode; -var init_references_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/references-node.js"() { - init_object_utils(); - ON_MODIFY_FOREIGN_ACTIONS = [ - "no action", - "restrict", - "cascade", - "set null", - "set default" - ]; - ReferencesNode = freeze2({ - is(node) { - return node.kind === "ReferencesNode"; - }, - create(table, columns) { - return freeze2({ - kind: "ReferencesNode", - table, - columns: freeze2([...columns]) - }); - }, - cloneWithOnDelete(references, onDelete) { - return freeze2({ - ...references, - onDelete - }); - }, - cloneWithOnUpdate(references, onUpdate) { - return freeze2({ - ...references, - onUpdate - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/default-value-parser.js -function parseDefaultValueExpression(value) { - return isOperationNodeSource(value) ? value.toOperationNode() : ValueNode.createImmediate(value); -} -var init_default_value_parser = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/default-value-parser.js"() { - init_operation_node_source(); - init_value_node(); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/generated-node.js -var GeneratedNode; -var init_generated_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/generated-node.js"() { - init_object_utils(); - GeneratedNode = freeze2({ - is(node) { - return node.kind === "GeneratedNode"; - }, - create(params) { - return freeze2({ - kind: "GeneratedNode", - ...params - }); - }, - createWithExpression(expression) { - return freeze2({ - kind: "GeneratedNode", - always: true, - expression - }); - }, - cloneWith(node, params) { - return freeze2({ - ...node, - ...params - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/default-value-node.js -var DefaultValueNode; -var init_default_value_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/default-value-node.js"() { - init_object_utils(); - DefaultValueNode = freeze2({ - is(node) { - return node.kind === "DefaultValueNode"; - }, - create(defaultValue) { - return freeze2({ - kind: "DefaultValueNode", - defaultValue - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/on-modify-action-parser.js -function parseOnModifyForeignAction(action) { - if (ON_MODIFY_FOREIGN_ACTIONS.includes(action)) { - return action; - } - throw new Error(`invalid OnModifyForeignAction ${action}`); -} -var init_on_modify_action_parser = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/on-modify-action-parser.js"() { - init_references_node(); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/column-definition-builder.js -var ColumnDefinitionBuilder; -var init_column_definition_builder = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/column-definition-builder.js"() { - init_check_constraint_node(); - init_references_node(); - init_select_all_node(); - init_reference_parser(); - init_column_definition_node(); - init_default_value_parser(); - init_generated_node(); - init_default_value_node(); - init_on_modify_action_parser(); - ColumnDefinitionBuilder = class _ColumnDefinitionBuilder { - #node; - constructor(node) { - this.#node = node; - } - /** - * Adds `auto_increment` or `autoincrement` to the column definition - * depending on the dialect. - * - * Some dialects like PostgreSQL don't support this. On PostgreSQL - * you can use the `serial` or `bigserial` data type instead. - * - * ### Examples - * - * ```ts - * await db.schema - * .createTable('person') - * .addColumn('id', 'integer', col => col.autoIncrement().primaryKey()) - * .execute() - * ``` - * - * The generated SQL (MySQL): - * - * ```sql - * create table `person` ( - * `id` integer primary key auto_increment - * ) - * ``` - */ - autoIncrement() { - return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, { autoIncrement: true })); - } - /** - * Makes the column an identity column. - * - * This only works on some dialects like MS SQL Server (MSSQL). - * - * For PostgreSQL's `generated always as identity` use {@link generatedAlwaysAsIdentity}. - * - * ### Examples - * - * ```ts - * await db.schema - * .createTable('person') - * .addColumn('id', 'integer', col => col.identity().primaryKey()) - * .execute() - * ``` - * - * The generated SQL (MSSQL): - * - * ```sql - * create table "person" ( - * "id" integer identity primary key - * ) - * ``` - */ - identity() { - return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, { identity: true })); - } - /** - * Makes the column the primary key. - * - * If you want to specify a composite primary key use the - * {@link CreateTableBuilder.addPrimaryKeyConstraint} method. - * - * ### Examples - * - * ```ts - * await db.schema - * .createTable('person') - * .addColumn('id', 'integer', col => col.primaryKey()) - * .execute() - * ``` - * - * The generated SQL (MySQL): - * - * ```sql - * create table `person` ( - * `id` integer primary key - * ) - */ - primaryKey() { - return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, { primaryKey: true })); - } - /** - * Adds a foreign key constraint for the column. - * - * If your database engine doesn't support foreign key constraints in the - * column definition (like MySQL 5) you need to call the table level - * {@link CreateTableBuilder.addForeignKeyConstraint} method instead. - * - * ### Examples - * - * ```ts - * await db.schema - * .createTable('pet') - * .addColumn('owner_id', 'integer', (col) => col.references('person.id')) - * .execute() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * create table "pet" ( - * "owner_id" integer references "person" ("id") - * ) - * ``` - */ - references(ref) { - const references = parseStringReference(ref); - if (!references.table || SelectAllNode.is(references.column)) { - throw new Error(`invalid call references('${ref}'). The reference must have format table.column or schema.table.column`); - } - return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, { - references: ReferencesNode.create(references.table, [ - references.column - ]) - })); - } - /** - * Adds an `on delete` constraint for the foreign key column. - * - * If your database engine doesn't support foreign key constraints in the - * column definition (like MySQL 5) you need to call the table level - * {@link CreateTableBuilder.addForeignKeyConstraint} method instead. - * - * ### Examples - * - * ```ts - * await db.schema - * .createTable('pet') - * .addColumn( - * 'owner_id', - * 'integer', - * (col) => col.references('person.id').onDelete('cascade') - * ) - * .execute() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * create table "pet" ( - * "owner_id" integer references "person" ("id") on delete cascade - * ) - * ``` - */ - onDelete(onDelete) { - if (!this.#node.references) { - throw new Error("on delete constraint can only be added for foreign keys"); - } - return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, { - references: ReferencesNode.cloneWithOnDelete(this.#node.references, parseOnModifyForeignAction(onDelete)) - })); - } - /** - * Adds an `on update` constraint for the foreign key column. - * - * If your database engine doesn't support foreign key constraints in the - * column definition (like MySQL 5) you need to call the table level - * {@link CreateTableBuilder.addForeignKeyConstraint} method instead. - * - * ### Examples - * - * ```ts - * await db.schema - * .createTable('pet') - * .addColumn( - * 'owner_id', - * 'integer', - * (col) => col.references('person.id').onUpdate('cascade') - * ) - * .execute() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * create table "pet" ( - * "owner_id" integer references "person" ("id") on update cascade - * ) - * ``` - */ - onUpdate(onUpdate) { - if (!this.#node.references) { - throw new Error("on update constraint can only be added for foreign keys"); - } - return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, { - references: ReferencesNode.cloneWithOnUpdate(this.#node.references, parseOnModifyForeignAction(onUpdate)) - })); - } - /** - * Adds a unique constraint for the column. - * - * ### Examples - * - * ```ts - * await db.schema - * .createTable('person') - * .addColumn('email', 'varchar(255)', col => col.unique()) - * .execute() - * ``` - * - * The generated SQL (MySQL): - * - * ```sql - * create table `person` ( - * `email` varchar(255) unique - * ) - * ``` - */ - unique() { - return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, { unique: true })); - } - /** - * Adds a `not null` constraint for the column. - * - * ### Examples - * - * ```ts - * await db.schema - * .createTable('person') - * .addColumn('first_name', 'varchar(255)', col => col.notNull()) - * .execute() - * ``` - * - * The generated SQL (MySQL): - * - * ```sql - * create table `person` ( - * `first_name` varchar(255) not null - * ) - * ``` - */ - notNull() { - return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, { notNull: true })); - } - /** - * Adds a `unsigned` modifier for the column. - * - * This only works on some dialects like MySQL. - * - * ### Examples - * - * ```ts - * await db.schema - * .createTable('person') - * .addColumn('age', 'integer', col => col.unsigned()) - * .execute() - * ``` - * - * The generated SQL (MySQL): - * - * ```sql - * create table `person` ( - * `age` integer unsigned - * ) - * ``` - */ - unsigned() { - return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, { unsigned: true })); - } - /** - * Adds a default value constraint for the column. - * - * ### Examples - * - * ```ts - * await db.schema - * .createTable('pet') - * .addColumn('number_of_legs', 'integer', (col) => col.defaultTo(4)) - * .execute() - * ``` - * - * The generated SQL (MySQL): - * - * ```sql - * create table `pet` ( - * `number_of_legs` integer default 4 - * ) - * ``` - * - * Values passed to `defaultTo` are interpreted as value literals by default. You can define - * an arbitrary SQL expression using the {@link sql} template tag: - * - * ```ts - * import { sql } from 'kysely' - * - * await db.schema - * .createTable('pet') - * .addColumn( - * 'created_at', - * 'timestamp', - * (col) => col.defaultTo(sql`CURRENT_TIMESTAMP`) - * ) - * .execute() - * ``` - * - * The generated SQL (MySQL): - * - * ```sql - * create table `pet` ( - * `created_at` timestamp default CURRENT_TIMESTAMP - * ) - * ``` - */ - defaultTo(value) { - return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, { - defaultTo: DefaultValueNode.create(parseDefaultValueExpression(value)) - })); - } - /** - * Adds a check constraint for the column. - * - * ### Examples - * - * ```ts - * import { sql } from 'kysely' - * - * await db.schema - * .createTable('pet') - * .addColumn('number_of_legs', 'integer', (col) => - * col.check(sql`number_of_legs < 5`) - * ) - * .execute() - * ``` - * - * The generated SQL (MySQL): - * - * ```sql - * create table `pet` ( - * `number_of_legs` integer check (number_of_legs < 5) - * ) - * ``` - */ - check(expression) { - return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, { - check: CheckConstraintNode.create(expression.toOperationNode()) - })); - } - /** - * Makes the column a generated column using a `generated always as` statement. - * - * ### Examples - * - * ```ts - * import { sql } from 'kysely' - * - * await db.schema - * .createTable('person') - * .addColumn('full_name', 'varchar(255)', - * (col) => col.generatedAlwaysAs(sql`concat(first_name, ' ', last_name)`) - * ) - * .execute() - * ``` - * - * The generated SQL (MySQL): - * - * ```sql - * create table `person` ( - * `full_name` varchar(255) generated always as (concat(first_name, ' ', last_name)) - * ) - * ``` - */ - generatedAlwaysAs(expression) { - return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, { - generated: GeneratedNode.createWithExpression(expression.toOperationNode()) - })); - } - /** - * Adds the `generated always as identity` specifier. - * - * This only works on some dialects like PostgreSQL. - * - * For MS SQL Server (MSSQL)'s identity column use {@link identity}. - * - * ### Examples - * - * ```ts - * await db.schema - * .createTable('person') - * .addColumn('id', 'integer', col => col.generatedAlwaysAsIdentity().primaryKey()) - * .execute() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * create table "person" ( - * "id" integer generated always as identity primary key - * ) - * ``` - */ - generatedAlwaysAsIdentity() { - return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, { - generated: GeneratedNode.create({ identity: true, always: true }) - })); - } - /** - * Adds the `generated by default as identity` specifier on supported dialects. - * - * This only works on some dialects like PostgreSQL. - * - * For MS SQL Server (MSSQL)'s identity column use {@link identity}. - * - * ### Examples - * - * ```ts - * await db.schema - * .createTable('person') - * .addColumn('id', 'integer', col => col.generatedByDefaultAsIdentity().primaryKey()) - * .execute() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * create table "person" ( - * "id" integer generated by default as identity primary key - * ) - * ``` - */ - generatedByDefaultAsIdentity() { - return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, { - generated: GeneratedNode.create({ identity: true, byDefault: true }) - })); - } - /** - * Makes a generated column stored instead of virtual. This method can only - * be used with {@link generatedAlwaysAs} - * - * ### Examples - * - * ```ts - * import { sql } from 'kysely' - * - * await db.schema - * .createTable('person') - * .addColumn('full_name', 'varchar(255)', (col) => col - * .generatedAlwaysAs(sql`concat(first_name, ' ', last_name)`) - * .stored() - * ) - * .execute() - * ``` - * - * The generated SQL (MySQL): - * - * ```sql - * create table `person` ( - * `full_name` varchar(255) generated always as (concat(first_name, ' ', last_name)) stored - * ) - * ``` - */ - stored() { - if (!this.#node.generated) { - throw new Error("stored() can only be called after generatedAlwaysAs"); - } - return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, { - generated: GeneratedNode.cloneWith(this.#node.generated, { - stored: true - }) - })); - } - /** - * This can be used to add any additional SQL right after the column's data type. - * - * ### Examples - * - * ```ts - * import { sql } from 'kysely' - * - * await db.schema - * .createTable('person') - * .addColumn('id', 'integer', col => col.primaryKey()) - * .addColumn( - * 'first_name', - * 'varchar(36)', - * (col) => col.modifyFront(sql`collate utf8mb4_general_ci`).notNull() - * ) - * .execute() - * ``` - * - * The generated SQL (MySQL): - * - * ```sql - * create table `person` ( - * `id` integer primary key, - * `first_name` varchar(36) collate utf8mb4_general_ci not null - * ) - * ``` - */ - modifyFront(modifier) { - return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWithFrontModifier(this.#node, modifier.toOperationNode())); - } - /** - * Adds `nulls not distinct` specifier. - * Should be used with `unique` constraint. - * - * This only works on some dialects like PostgreSQL. - * - * ### Examples - * - * ```ts - * db.schema - * .createTable('person') - * .addColumn('id', 'integer', col => col.primaryKey()) - * .addColumn('first_name', 'varchar(30)', col => col.unique().nullsNotDistinct()) - * .execute() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * create table "person" ( - * "id" integer primary key, - * "first_name" varchar(30) unique nulls not distinct - * ) - * ``` - */ - nullsNotDistinct() { - return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, { nullsNotDistinct: true })); - } - /** - * Adds `if not exists` specifier. This only works for PostgreSQL. - * - * ### Examples - * - * ```ts - * await db.schema - * .alterTable('person') - * .addColumn('email', 'varchar(255)', col => col.unique().ifNotExists()) - * .execute() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * alter table "person" add column if not exists "email" varchar(255) unique - * ``` - */ - ifNotExists() { - return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, { ifNotExists: true })); - } - /** - * This can be used to add any additional SQL to the end of the column definition. - * - * ### Examples - * - * ```ts - * import { sql } from 'kysely' - * - * await db.schema - * .createTable('person') - * .addColumn('id', 'integer', col => col.primaryKey()) - * .addColumn( - * 'age', - * 'integer', - * col => col.unsigned() - * .notNull() - * .modifyEnd(sql`comment ${sql.lit('it is not polite to ask a woman her age')}`) - * ) - * .execute() - * ``` - * - * The generated SQL (MySQL): - * - * ```sql - * create table `person` ( - * `id` integer primary key, - * `age` integer unsigned not null comment 'it is not polite to ask a woman her age' - * ) - * ``` - */ - modifyEnd(modifier) { - return new _ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWithEndModifier(this.#node, modifier.toOperationNode())); - } - /** - * Simply calls the provided function passing `this` as the only argument. `$call` returns - * what the provided function returns. - */ - $call(func) { - return func(this); - } - toOperationNode() { - return this.#node; - } - }; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/modify-column-node.js -var ModifyColumnNode; -var init_modify_column_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/modify-column-node.js"() { - init_object_utils(); - ModifyColumnNode = freeze2({ - is(node) { - return node.kind === "ModifyColumnNode"; - }, - create(column) { - return freeze2({ - kind: "ModifyColumnNode", - column - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/foreign-key-constraint-node.js -var ForeignKeyConstraintNode; -var init_foreign_key_constraint_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/foreign-key-constraint-node.js"() { - init_object_utils(); - init_identifier_node(); - init_references_node(); - ForeignKeyConstraintNode = freeze2({ - is(node) { - return node.kind === "ForeignKeyConstraintNode"; - }, - create(sourceColumns, targetTable, targetColumns, constraintName) { - return freeze2({ - kind: "ForeignKeyConstraintNode", - columns: sourceColumns, - references: ReferencesNode.create(targetTable, targetColumns), - name: constraintName ? IdentifierNode.create(constraintName) : void 0 - }); - }, - cloneWith(node, props) { - return freeze2({ - ...node, - ...props - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/foreign-key-constraint-builder.js -var ForeignKeyConstraintBuilder; -var init_foreign_key_constraint_builder = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/foreign-key-constraint-builder.js"() { - init_foreign_key_constraint_node(); - init_on_modify_action_parser(); - ForeignKeyConstraintBuilder = class _ForeignKeyConstraintBuilder { - #node; - constructor(node) { - this.#node = node; - } - onDelete(onDelete) { - return new _ForeignKeyConstraintBuilder(ForeignKeyConstraintNode.cloneWith(this.#node, { - onDelete: parseOnModifyForeignAction(onDelete) - })); - } - onUpdate(onUpdate) { - return new _ForeignKeyConstraintBuilder(ForeignKeyConstraintNode.cloneWith(this.#node, { - onUpdate: parseOnModifyForeignAction(onUpdate) - })); - } - deferrable() { - return new _ForeignKeyConstraintBuilder(ForeignKeyConstraintNode.cloneWith(this.#node, { deferrable: true })); - } - notDeferrable() { - return new _ForeignKeyConstraintBuilder(ForeignKeyConstraintNode.cloneWith(this.#node, { deferrable: false })); - } - initiallyDeferred() { - return new _ForeignKeyConstraintBuilder(ForeignKeyConstraintNode.cloneWith(this.#node, { - initiallyDeferred: true - })); - } - initiallyImmediate() { - return new _ForeignKeyConstraintBuilder(ForeignKeyConstraintNode.cloneWith(this.#node, { - initiallyDeferred: false - })); - } - /** - * Simply calls the provided function passing `this` as the only argument. `$call` returns - * what the provided function returns. - */ - $call(func) { - return func(this); - } - toOperationNode() { - return this.#node; - } - }; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/add-constraint-node.js -var AddConstraintNode; -var init_add_constraint_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/add-constraint-node.js"() { - init_object_utils(); - AddConstraintNode = freeze2({ - is(node) { - return node.kind === "AddConstraintNode"; - }, - create(constraint) { - return freeze2({ - kind: "AddConstraintNode", - constraint - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/unique-constraint-node.js -var UniqueConstraintNode; -var init_unique_constraint_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/unique-constraint-node.js"() { - init_object_utils(); - init_column_node(); - init_identifier_node(); - UniqueConstraintNode = freeze2({ - is(node) { - return node.kind === "UniqueConstraintNode"; - }, - create(columns, constraintName, nullsNotDistinct) { - return freeze2({ - kind: "UniqueConstraintNode", - columns: freeze2(columns.map(ColumnNode.create)), - name: constraintName ? IdentifierNode.create(constraintName) : void 0, - nullsNotDistinct - }); - }, - cloneWith(node, props) { - return freeze2({ - ...node, - ...props - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/drop-constraint-node.js -var DropConstraintNode; -var init_drop_constraint_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/drop-constraint-node.js"() { - init_object_utils(); - init_identifier_node(); - DropConstraintNode = freeze2({ - is(node) { - return node.kind === "DropConstraintNode"; - }, - create(constraintName) { - return freeze2({ - kind: "DropConstraintNode", - constraintName: IdentifierNode.create(constraintName) - }); - }, - cloneWith(dropConstraint, props) { - return freeze2({ - ...dropConstraint, - ...props - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/alter-column-node.js -var AlterColumnNode; -var init_alter_column_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/alter-column-node.js"() { - init_object_utils(); - init_column_node(); - AlterColumnNode = freeze2({ - is(node) { - return node.kind === "AlterColumnNode"; - }, - create(column, prop, value) { - return freeze2({ - kind: "AlterColumnNode", - column: ColumnNode.create(column), - [prop]: value - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/alter-column-builder.js -var AlterColumnBuilder, AlteredColumnBuilder; -var init_alter_column_builder = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/alter-column-builder.js"() { - init_alter_column_node(); - init_data_type_parser(); - init_default_value_parser(); - AlterColumnBuilder = class { - #column; - constructor(column) { - this.#column = column; - } - setDataType(dataType) { - return new AlteredColumnBuilder(AlterColumnNode.create(this.#column, "dataType", parseDataTypeExpression(dataType))); - } - setDefault(value) { - return new AlteredColumnBuilder(AlterColumnNode.create(this.#column, "setDefault", parseDefaultValueExpression(value))); - } - dropDefault() { - return new AlteredColumnBuilder(AlterColumnNode.create(this.#column, "dropDefault", true)); - } - setNotNull() { - return new AlteredColumnBuilder(AlterColumnNode.create(this.#column, "setNotNull", true)); - } - dropNotNull() { - return new AlteredColumnBuilder(AlterColumnNode.create(this.#column, "dropNotNull", true)); - } - /** - * Simply calls the provided function passing `this` as the only argument. `$call` returns - * what the provided function returns. - */ - $call(func) { - return func(this); - } - }; - AlteredColumnBuilder = class { - #alterColumnNode; - constructor(alterColumnNode) { - this.#alterColumnNode = alterColumnNode; - } - toOperationNode() { - return this.#alterColumnNode; - } - }; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/alter-table-executor.js -var AlterTableExecutor; -var init_alter_table_executor = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/alter-table-executor.js"() { - init_object_utils(); - AlterTableExecutor = class { - #props; - constructor(props) { - this.#props = freeze2(props); - } - toOperationNode() { - return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId); - } - compile() { - return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId); - } - async execute() { - await this.#props.executor.executeQuery(this.compile()); - } - }; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/alter-table-add-foreign-key-constraint-builder.js -var AlterTableAddForeignKeyConstraintBuilder; -var init_alter_table_add_foreign_key_constraint_builder = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/alter-table-add-foreign-key-constraint-builder.js"() { - init_add_constraint_node(); - init_alter_table_node(); - init_object_utils(); - AlterTableAddForeignKeyConstraintBuilder = class _AlterTableAddForeignKeyConstraintBuilder { - #props; - constructor(props) { - this.#props = freeze2(props); - } - onDelete(onDelete) { - return new _AlterTableAddForeignKeyConstraintBuilder({ - ...this.#props, - constraintBuilder: this.#props.constraintBuilder.onDelete(onDelete) - }); - } - onUpdate(onUpdate) { - return new _AlterTableAddForeignKeyConstraintBuilder({ - ...this.#props, - constraintBuilder: this.#props.constraintBuilder.onUpdate(onUpdate) - }); - } - deferrable() { - return new _AlterTableAddForeignKeyConstraintBuilder({ - ...this.#props, - constraintBuilder: this.#props.constraintBuilder.deferrable() - }); - } - notDeferrable() { - return new _AlterTableAddForeignKeyConstraintBuilder({ - ...this.#props, - constraintBuilder: this.#props.constraintBuilder.notDeferrable() - }); - } - initiallyDeferred() { - return new _AlterTableAddForeignKeyConstraintBuilder({ - ...this.#props, - constraintBuilder: this.#props.constraintBuilder.initiallyDeferred() - }); - } - initiallyImmediate() { - return new _AlterTableAddForeignKeyConstraintBuilder({ - ...this.#props, - constraintBuilder: this.#props.constraintBuilder.initiallyImmediate() - }); - } - /** - * Simply calls the provided function passing `this` as the only argument. `$call` returns - * what the provided function returns. - */ - $call(func) { - return func(this); - } - toOperationNode() { - return this.#props.executor.transformQuery(AlterTableNode.cloneWithTableProps(this.#props.node, { - addConstraint: AddConstraintNode.create(this.#props.constraintBuilder.toOperationNode()) - }), this.#props.queryId); - } - compile() { - return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId); - } - async execute() { - await this.#props.executor.executeQuery(this.compile()); - } - }; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/alter-table-drop-constraint-builder.js -var AlterTableDropConstraintBuilder; -var init_alter_table_drop_constraint_builder = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/alter-table-drop-constraint-builder.js"() { - init_alter_table_node(); - init_drop_constraint_node(); - init_object_utils(); - AlterTableDropConstraintBuilder = class _AlterTableDropConstraintBuilder { - #props; - constructor(props) { - this.#props = freeze2(props); - } - ifExists() { - return new _AlterTableDropConstraintBuilder({ - ...this.#props, - node: AlterTableNode.cloneWithTableProps(this.#props.node, { - dropConstraint: DropConstraintNode.cloneWith(this.#props.node.dropConstraint, { - ifExists: true - }) - }) - }); - } - cascade() { - return new _AlterTableDropConstraintBuilder({ - ...this.#props, - node: AlterTableNode.cloneWithTableProps(this.#props.node, { - dropConstraint: DropConstraintNode.cloneWith(this.#props.node.dropConstraint, { - modifier: "cascade" - }) - }) - }); - } - restrict() { - return new _AlterTableDropConstraintBuilder({ - ...this.#props, - node: AlterTableNode.cloneWithTableProps(this.#props.node, { - dropConstraint: DropConstraintNode.cloneWith(this.#props.node.dropConstraint, { - modifier: "restrict" - }) - }) - }); - } - /** - * Simply calls the provided function passing `this` as the only argument. `$call` returns - * what the provided function returns. - */ - $call(func) { - return func(this); - } - toOperationNode() { - return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId); - } - compile() { - return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId); - } - async execute() { - await this.#props.executor.executeQuery(this.compile()); - } - }; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/primary-key-constraint-node.js -var PrimaryKeyConstraintNode; -var init_primary_key_constraint_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/primary-key-constraint-node.js"() { - init_object_utils(); - init_column_node(); - init_identifier_node(); - PrimaryKeyConstraintNode = freeze2({ - is(node) { - return node.kind === "PrimaryKeyConstraintNode"; - }, - create(columns, constraintName) { - return freeze2({ - kind: "PrimaryKeyConstraintNode", - columns: freeze2(columns.map(ColumnNode.create)), - name: constraintName ? IdentifierNode.create(constraintName) : void 0 - }); - }, - cloneWith(node, props) { - return freeze2({ ...node, ...props }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/add-index-node.js -var AddIndexNode; -var init_add_index_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/add-index-node.js"() { - init_object_utils(); - init_identifier_node(); - AddIndexNode = freeze2({ - is(node) { - return node.kind === "AddIndexNode"; - }, - create(name) { - return freeze2({ - kind: "AddIndexNode", - name: IdentifierNode.create(name) - }); - }, - cloneWith(node, props) { - return freeze2({ - ...node, - ...props - }); - }, - cloneWithColumns(node, columns) { - return freeze2({ - ...node, - columns: [...node.columns || [], ...columns] - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/alter-table-add-index-builder.js -var AlterTableAddIndexBuilder; -var init_alter_table_add_index_builder = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/alter-table-add-index-builder.js"() { - init_add_index_node(); - init_alter_table_node(); - init_raw_node(); - init_reference_parser(); - init_object_utils(); - AlterTableAddIndexBuilder = class _AlterTableAddIndexBuilder { - #props; - constructor(props) { - this.#props = freeze2(props); - } - /** - * Makes the index unique. - * - * ### Examples - * - * ```ts - * await db.schema - * .alterTable('person') - * .addIndex('person_first_name_index') - * .unique() - * .column('email') - * .execute() - * ``` - * - * The generated SQL (MySQL): - * - * ```sql - * alter table `person` add unique index `person_first_name_index` (`email`) - * ``` - */ - unique() { - return new _AlterTableAddIndexBuilder({ - ...this.#props, - node: AlterTableNode.cloneWithTableProps(this.#props.node, { - addIndex: AddIndexNode.cloneWith(this.#props.node.addIndex, { - unique: true - }) - }) - }); - } - /** - * Adds a column to the index. - * - * Also see {@link columns} for adding multiple columns at once or {@link expression} - * for specifying an arbitrary expression. - * - * ### Examples - * - * ```ts - * await db.schema - * .alterTable('person') - * .addIndex('person_first_name_and_age_index') - * .column('first_name') - * .column('age desc') - * .execute() - * ``` - * - * The generated SQL (MySQL): - * - * ```sql - * alter table `person` add index `person_first_name_and_age_index` (`first_name`, `age` desc) - * ``` - */ - column(column) { - return new _AlterTableAddIndexBuilder({ - ...this.#props, - node: AlterTableNode.cloneWithTableProps(this.#props.node, { - addIndex: AddIndexNode.cloneWithColumns(this.#props.node.addIndex, [ - parseOrderedColumnName(column) - ]) - }) - }); - } - /** - * Specifies a list of columns for the index. - * - * Also see {@link column} for adding a single column or {@link expression} for - * specifying an arbitrary expression. - * - * ### Examples - * - * ```ts - * await db.schema - * .alterTable('person') - * .addIndex('person_first_name_and_age_index') - * .columns(['first_name', 'age desc']) - * .execute() - * ``` - * - * The generated SQL (MySQL): - * - * ```sql - * alter table `person` add index `person_first_name_and_age_index` (`first_name`, `age` desc) - * ``` - */ - columns(columns) { - return new _AlterTableAddIndexBuilder({ - ...this.#props, - node: AlterTableNode.cloneWithTableProps(this.#props.node, { - addIndex: AddIndexNode.cloneWithColumns(this.#props.node.addIndex, columns.map(parseOrderedColumnName)) - }) - }); - } - /** - * Specifies an arbitrary expression for the index. - * - * ### Examples - * - * ```ts - * import { sql } from 'kysely' - * - * await db.schema - * .alterTable('person') - * .addIndex('person_first_name_index') - * .expression(sql`(first_name < 'Sami')`) - * .execute() - * ``` - * - * The generated SQL (MySQL): - * - * ```sql - * alter table `person` add index `person_first_name_index` ((first_name < 'Sami')) - * ``` - */ - expression(expression) { - return new _AlterTableAddIndexBuilder({ - ...this.#props, - node: AlterTableNode.cloneWithTableProps(this.#props.node, { - addIndex: AddIndexNode.cloneWithColumns(this.#props.node.addIndex, [ - expression.toOperationNode() - ]) - }) - }); - } - using(indexType) { - return new _AlterTableAddIndexBuilder({ - ...this.#props, - node: AlterTableNode.cloneWithTableProps(this.#props.node, { - addIndex: AddIndexNode.cloneWith(this.#props.node.addIndex, { - using: RawNode.createWithSql(indexType) - }) - }) - }); - } - /** - * Simply calls the provided function passing `this` as the only argument. `$call` returns - * what the provided function returns. - */ - $call(func) { - return func(this); - } - toOperationNode() { - return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId); - } - compile() { - return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId); - } - async execute() { - await this.#props.executor.executeQuery(this.compile()); - } - }; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/unique-constraint-builder.js -var UniqueConstraintNodeBuilder; -var init_unique_constraint_builder = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/unique-constraint-builder.js"() { - init_unique_constraint_node(); - UniqueConstraintNodeBuilder = class _UniqueConstraintNodeBuilder { - #node; - constructor(node) { - this.#node = node; - } - /** - * Adds `nulls not distinct` to the unique constraint definition - * - * Supported by PostgreSQL dialect only - */ - nullsNotDistinct() { - return new _UniqueConstraintNodeBuilder(UniqueConstraintNode.cloneWith(this.#node, { nullsNotDistinct: true })); - } - deferrable() { - return new _UniqueConstraintNodeBuilder(UniqueConstraintNode.cloneWith(this.#node, { deferrable: true })); - } - notDeferrable() { - return new _UniqueConstraintNodeBuilder(UniqueConstraintNode.cloneWith(this.#node, { deferrable: false })); - } - initiallyDeferred() { - return new _UniqueConstraintNodeBuilder(UniqueConstraintNode.cloneWith(this.#node, { - initiallyDeferred: true - })); - } - initiallyImmediate() { - return new _UniqueConstraintNodeBuilder(UniqueConstraintNode.cloneWith(this.#node, { - initiallyDeferred: false - })); - } - /** - * Simply calls the provided function passing `this` as the only argument. `$call` returns - * what the provided function returns. - */ - $call(func) { - return func(this); - } - toOperationNode() { - return this.#node; - } - }; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/primary-key-constraint-builder.js -var PrimaryKeyConstraintBuilder; -var init_primary_key_constraint_builder = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/primary-key-constraint-builder.js"() { - init_primary_key_constraint_node(); - PrimaryKeyConstraintBuilder = class _PrimaryKeyConstraintBuilder { - #node; - constructor(node) { - this.#node = node; - } - deferrable() { - return new _PrimaryKeyConstraintBuilder(PrimaryKeyConstraintNode.cloneWith(this.#node, { deferrable: true })); - } - notDeferrable() { - return new _PrimaryKeyConstraintBuilder(PrimaryKeyConstraintNode.cloneWith(this.#node, { deferrable: false })); - } - initiallyDeferred() { - return new _PrimaryKeyConstraintBuilder(PrimaryKeyConstraintNode.cloneWith(this.#node, { - initiallyDeferred: true - })); - } - initiallyImmediate() { - return new _PrimaryKeyConstraintBuilder(PrimaryKeyConstraintNode.cloneWith(this.#node, { - initiallyDeferred: false - })); - } - /** - * Simply calls the provided function passing `this` as the only argument. `$call` returns - * what the provided function returns. - */ - $call(func) { - return func(this); - } - toOperationNode() { - return this.#node; - } - }; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/check-constraint-builder.js -var CheckConstraintBuilder; -var init_check_constraint_builder = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/check-constraint-builder.js"() { - CheckConstraintBuilder = class { - #node; - constructor(node) { - this.#node = node; - } - /** - * Simply calls the provided function passing `this` as the only argument. `$call` returns - * what the provided function returns. - */ - $call(func) { - return func(this); - } - toOperationNode() { - return this.#node; - } - }; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/rename-constraint-node.js -var RenameConstraintNode; -var init_rename_constraint_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/rename-constraint-node.js"() { - init_object_utils(); - init_identifier_node(); - RenameConstraintNode = freeze2({ - is(node) { - return node.kind === "RenameConstraintNode"; - }, - create(oldName, newName) { - return freeze2({ - kind: "RenameConstraintNode", - oldName: IdentifierNode.create(oldName), - newName: IdentifierNode.create(newName) - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/alter-table-builder.js -var AlterTableBuilder, AlterTableColumnAlteringBuilder; -var init_alter_table_builder = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/alter-table-builder.js"() { - init_add_column_node(); - init_alter_table_node(); - init_column_definition_node(); - init_drop_column_node(); - init_identifier_node(); - init_rename_column_node(); - init_object_utils(); - init_column_definition_builder(); - init_modify_column_node(); - init_data_type_parser(); - init_foreign_key_constraint_builder(); - init_add_constraint_node(); - init_unique_constraint_node(); - init_check_constraint_node(); - init_foreign_key_constraint_node(); - init_column_node(); - init_table_parser(); - init_drop_constraint_node(); - init_alter_column_builder(); - init_alter_table_executor(); - init_alter_table_add_foreign_key_constraint_builder(); - init_alter_table_drop_constraint_builder(); - init_primary_key_constraint_node(); - init_drop_index_node(); - init_add_index_node(); - init_alter_table_add_index_builder(); - init_unique_constraint_builder(); - init_primary_key_constraint_builder(); - init_check_constraint_builder(); - init_rename_constraint_node(); - AlterTableBuilder = class { - #props; - constructor(props) { - this.#props = freeze2(props); - } - renameTo(newTableName) { - return new AlterTableExecutor({ - ...this.#props, - node: AlterTableNode.cloneWithTableProps(this.#props.node, { - renameTo: parseTable(newTableName) - }) - }); - } - setSchema(newSchema) { - return new AlterTableExecutor({ - ...this.#props, - node: AlterTableNode.cloneWithTableProps(this.#props.node, { - setSchema: IdentifierNode.create(newSchema) - }) - }); - } - alterColumn(column, alteration) { - const builder = alteration(new AlterColumnBuilder(column)); - return new AlterTableColumnAlteringBuilder({ - ...this.#props, - node: AlterTableNode.cloneWithColumnAlteration(this.#props.node, builder.toOperationNode()) - }); - } - dropColumn(column) { - return new AlterTableColumnAlteringBuilder({ - ...this.#props, - node: AlterTableNode.cloneWithColumnAlteration(this.#props.node, DropColumnNode.create(column)) - }); - } - renameColumn(column, newColumn) { - return new AlterTableColumnAlteringBuilder({ - ...this.#props, - node: AlterTableNode.cloneWithColumnAlteration(this.#props.node, RenameColumnNode.create(column, newColumn)) - }); - } - addColumn(columnName, dataType, build = noop3) { - const builder = build(new ColumnDefinitionBuilder(ColumnDefinitionNode.create(columnName, parseDataTypeExpression(dataType)))); - return new AlterTableColumnAlteringBuilder({ - ...this.#props, - node: AlterTableNode.cloneWithColumnAlteration(this.#props.node, AddColumnNode.create(builder.toOperationNode())) - }); - } - modifyColumn(columnName, dataType, build = noop3) { - const builder = build(new ColumnDefinitionBuilder(ColumnDefinitionNode.create(columnName, parseDataTypeExpression(dataType)))); - return new AlterTableColumnAlteringBuilder({ - ...this.#props, - node: AlterTableNode.cloneWithColumnAlteration(this.#props.node, ModifyColumnNode.create(builder.toOperationNode())) - }); - } - /** - * See {@link CreateTableBuilder.addUniqueConstraint} - */ - addUniqueConstraint(constraintName, columns, build = noop3) { - const uniqueConstraintBuilder = build(new UniqueConstraintNodeBuilder(UniqueConstraintNode.create(columns, constraintName))); - return new AlterTableExecutor({ - ...this.#props, - node: AlterTableNode.cloneWithTableProps(this.#props.node, { - addConstraint: AddConstraintNode.create(uniqueConstraintBuilder.toOperationNode()) - }) - }); - } - /** - * See {@link CreateTableBuilder.addCheckConstraint} - */ - addCheckConstraint(constraintName, checkExpression, build = noop3) { - const constraintBuilder = build(new CheckConstraintBuilder(CheckConstraintNode.create(checkExpression.toOperationNode(), constraintName))); - return new AlterTableExecutor({ - ...this.#props, - node: AlterTableNode.cloneWithTableProps(this.#props.node, { - addConstraint: AddConstraintNode.create(constraintBuilder.toOperationNode()) - }) - }); - } - /** - * See {@link CreateTableBuilder.addForeignKeyConstraint} - * - * Unlike {@link CreateTableBuilder.addForeignKeyConstraint} this method returns - * the constraint builder and doesn't take a callback as the last argument. This - * is because you can only add one column per `ALTER TABLE` query. - */ - addForeignKeyConstraint(constraintName, columns, targetTable, targetColumns, build = noop3) { - const constraintBuilder = build(new ForeignKeyConstraintBuilder(ForeignKeyConstraintNode.create(columns.map(ColumnNode.create), parseTable(targetTable), targetColumns.map(ColumnNode.create), constraintName))); - return new AlterTableAddForeignKeyConstraintBuilder({ - ...this.#props, - constraintBuilder - }); - } - /** - * See {@link CreateTableBuilder.addPrimaryKeyConstraint} - */ - addPrimaryKeyConstraint(constraintName, columns, build = noop3) { - const constraintBuilder = build(new PrimaryKeyConstraintBuilder(PrimaryKeyConstraintNode.create(columns, constraintName))); - return new AlterTableExecutor({ - ...this.#props, - node: AlterTableNode.cloneWithTableProps(this.#props.node, { - addConstraint: AddConstraintNode.create(constraintBuilder.toOperationNode()) - }) - }); - } - dropConstraint(constraintName) { - return new AlterTableDropConstraintBuilder({ - ...this.#props, - node: AlterTableNode.cloneWithTableProps(this.#props.node, { - dropConstraint: DropConstraintNode.create(constraintName) - }) - }); - } - renameConstraint(oldName, newName) { - return new AlterTableDropConstraintBuilder({ - ...this.#props, - node: AlterTableNode.cloneWithTableProps(this.#props.node, { - renameConstraint: RenameConstraintNode.create(oldName, newName) - }) - }); - } - /** - * This can be used to add index to table. - * - * ### Examples - * - * ```ts - * db.schema.alterTable('person') - * .addIndex('person_email_index') - * .column('email') - * .unique() - * .execute() - * ``` - * - * The generated SQL (MySQL): - * - * ```sql - * alter table `person` add unique index `person_email_index` (`email`) - * ``` - */ - addIndex(indexName) { - return new AlterTableAddIndexBuilder({ - ...this.#props, - node: AlterTableNode.cloneWithTableProps(this.#props.node, { - addIndex: AddIndexNode.create(indexName) - }) - }); - } - /** - * This can be used to drop index from table. - * - * ### Examples - * - * ```ts - * db.schema.alterTable('person') - * .dropIndex('person_email_index') - * .execute() - * ``` - * - * The generated SQL (MySQL): - * - * ```sql - * alter table `person` drop index `test_first_name_index` - * ``` - */ - dropIndex(indexName) { - return new AlterTableExecutor({ - ...this.#props, - node: AlterTableNode.cloneWithTableProps(this.#props.node, { - dropIndex: DropIndexNode.create(indexName) - }) - }); - } - /** - * Calls the given function passing `this` as the only argument. - * - * See {@link CreateTableBuilder.$call} - */ - $call(func) { - return func(this); - } - }; - AlterTableColumnAlteringBuilder = class _AlterTableColumnAlteringBuilder { - #props; - constructor(props) { - this.#props = freeze2(props); - } - alterColumn(column, alteration) { - const builder = alteration(new AlterColumnBuilder(column)); - return new _AlterTableColumnAlteringBuilder({ - ...this.#props, - node: AlterTableNode.cloneWithColumnAlteration(this.#props.node, builder.toOperationNode()) - }); - } - dropColumn(column) { - return new _AlterTableColumnAlteringBuilder({ - ...this.#props, - node: AlterTableNode.cloneWithColumnAlteration(this.#props.node, DropColumnNode.create(column)) - }); - } - renameColumn(column, newColumn) { - return new _AlterTableColumnAlteringBuilder({ - ...this.#props, - node: AlterTableNode.cloneWithColumnAlteration(this.#props.node, RenameColumnNode.create(column, newColumn)) - }); - } - addColumn(columnName, dataType, build = noop3) { - const builder = build(new ColumnDefinitionBuilder(ColumnDefinitionNode.create(columnName, parseDataTypeExpression(dataType)))); - return new _AlterTableColumnAlteringBuilder({ - ...this.#props, - node: AlterTableNode.cloneWithColumnAlteration(this.#props.node, AddColumnNode.create(builder.toOperationNode())) - }); - } - modifyColumn(columnName, dataType, build = noop3) { - const builder = build(new ColumnDefinitionBuilder(ColumnDefinitionNode.create(columnName, parseDataTypeExpression(dataType)))); - return new _AlterTableColumnAlteringBuilder({ - ...this.#props, - node: AlterTableNode.cloneWithColumnAlteration(this.#props.node, ModifyColumnNode.create(builder.toOperationNode())) - }); - } - toOperationNode() { - return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId); - } - compile() { - return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId); - } - async execute() { - await this.#props.executor.executeQuery(this.compile()); - } - }; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/immediate-value/immediate-value-transformer.js -var ImmediateValueTransformer; -var init_immediate_value_transformer = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/immediate-value/immediate-value-transformer.js"() { - init_operation_node_transformer(); - init_value_list_node(); - init_value_node(); - ImmediateValueTransformer = class extends OperationNodeTransformer { - transformPrimitiveValueList(node) { - return ValueListNode.create(node.values.map(ValueNode.createImmediate)); - } - transformValue(node) { - return ValueNode.createImmediate(node.value); - } - }; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/create-index-builder.js -var CreateIndexBuilder; -var init_create_index_builder = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/create-index-builder.js"() { - init_create_index_node(); - init_raw_node(); - init_reference_parser(); - init_table_parser(); - init_object_utils(); - init_binary_operation_parser(); - init_query_node(); - init_immediate_value_transformer(); - CreateIndexBuilder = class _CreateIndexBuilder { - #props; - constructor(props) { - this.#props = freeze2(props); - } - /** - * Adds the "if not exists" modifier. - * - * If the index already exists, no error is thrown if this method has been called. - */ - ifNotExists() { - return new _CreateIndexBuilder({ - ...this.#props, - node: CreateIndexNode.cloneWith(this.#props.node, { - ifNotExists: true - }) - }); - } - /** - * Makes the index unique. - */ - unique() { - return new _CreateIndexBuilder({ - ...this.#props, - node: CreateIndexNode.cloneWith(this.#props.node, { - unique: true - }) - }); - } - /** - * Adds `nulls not distinct` specifier to index. - * This only works on some dialects like PostgreSQL. - * - * ### Examples - * - * ```ts - * db.schema.createIndex('person_first_name_index') - * .on('person') - * .column('first_name') - * .nullsNotDistinct() - * .execute() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * create index "person_first_name_index" - * on "test" ("first_name") - * nulls not distinct; - * ``` - */ - nullsNotDistinct() { - return new _CreateIndexBuilder({ - ...this.#props, - node: CreateIndexNode.cloneWith(this.#props.node, { - nullsNotDistinct: true - }) - }); - } - /** - * Specifies the table for the index. - */ - on(table) { - return new _CreateIndexBuilder({ - ...this.#props, - node: CreateIndexNode.cloneWith(this.#props.node, { - table: parseTable(table) - }) - }); - } - /** - * Adds a column to the index. - * - * Also see {@link columns} for adding multiple columns at once or {@link expression} - * for specifying an arbitrary expression. - * - * ### Examples - * - * ```ts - * await db.schema - * .createIndex('person_first_name_and_age_index') - * .on('person') - * .column('first_name') - * .column('age desc') - * .execute() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * create index "person_first_name_and_age_index" on "person" ("first_name", "age" desc) - * ``` - */ - column(column) { - return new _CreateIndexBuilder({ - ...this.#props, - node: CreateIndexNode.cloneWithColumns(this.#props.node, [ - parseOrderedColumnName(column) - ]) - }); - } - /** - * Specifies a list of columns for the index. - * - * Also see {@link column} for adding a single column or {@link expression} for - * specifying an arbitrary expression. - * - * ### Examples - * - * ```ts - * await db.schema - * .createIndex('person_first_name_and_age_index') - * .on('person') - * .columns(['first_name', 'age desc']) - * .execute() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * create index "person_first_name_and_age_index" on "person" ("first_name", "age" desc) - * ``` - */ - columns(columns) { - return new _CreateIndexBuilder({ - ...this.#props, - node: CreateIndexNode.cloneWithColumns(this.#props.node, columns.map(parseOrderedColumnName)) - }); - } - /** - * Specifies an arbitrary expression for the index. - * - * ### Examples - * - * ```ts - * import { sql } from 'kysely' - * - * await db.schema - * .createIndex('person_first_name_index') - * .on('person') - * .expression(sql`first_name COLLATE "fi_FI"`) - * .execute() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * create index "person_first_name_index" on "person" (first_name COLLATE "fi_FI") - * ``` - */ - expression(expression) { - return new _CreateIndexBuilder({ - ...this.#props, - node: CreateIndexNode.cloneWithColumns(this.#props.node, [ - expression.toOperationNode() - ]) - }); - } - using(indexType) { - return new _CreateIndexBuilder({ - ...this.#props, - node: CreateIndexNode.cloneWith(this.#props.node, { - using: RawNode.createWithSql(indexType) - }) - }); - } - where(...args) { - const transformer = new ImmediateValueTransformer(); - return new _CreateIndexBuilder({ - ...this.#props, - node: QueryNode.cloneWithWhere(this.#props.node, transformer.transformNode(parseValueBinaryOperationOrExpression(args), this.#props.queryId)) - }); - } - /** - * Simply calls the provided function passing `this` as the only argument. `$call` returns - * what the provided function returns. - */ - $call(func) { - return func(this); - } - toOperationNode() { - return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId); - } - compile() { - return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId); - } - async execute() { - await this.#props.executor.executeQuery(this.compile()); - } - }; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/create-schema-builder.js -var CreateSchemaBuilder; -var init_create_schema_builder = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/create-schema-builder.js"() { - init_create_schema_node(); - init_object_utils(); - CreateSchemaBuilder = class _CreateSchemaBuilder { - #props; - constructor(props) { - this.#props = freeze2(props); - } - ifNotExists() { - return new _CreateSchemaBuilder({ - ...this.#props, - node: CreateSchemaNode.cloneWith(this.#props.node, { ifNotExists: true }) - }); - } - /** - * Simply calls the provided function passing `this` as the only argument. `$call` returns - * what the provided function returns. - */ - $call(func) { - return func(this); - } - toOperationNode() { - return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId); - } - compile() { - return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId); - } - async execute() { - await this.#props.executor.executeQuery(this.compile()); - } - }; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/on-commit-action-parse.js -function parseOnCommitAction(action) { - if (ON_COMMIT_ACTIONS.includes(action)) { - return action; - } - throw new Error(`invalid OnCommitAction ${action}`); -} -var init_on_commit_action_parse = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/on-commit-action-parse.js"() { - init_create_table_node(); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/create-table-builder.js -var CreateTableBuilder; -var init_create_table_builder = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/create-table-builder.js"() { - init_column_definition_node(); - init_create_table_node(); - init_column_definition_builder(); - init_object_utils(); - init_foreign_key_constraint_node(); - init_column_node(); - init_foreign_key_constraint_builder(); - init_data_type_parser(); - init_primary_key_constraint_node(); - init_unique_constraint_node(); - init_check_constraint_node(); - init_table_parser(); - init_on_commit_action_parse(); - init_unique_constraint_builder(); - init_expression_parser(); - init_primary_key_constraint_builder(); - init_check_constraint_builder(); - CreateTableBuilder = class _CreateTableBuilder { - #props; - constructor(props) { - this.#props = freeze2(props); - } - /** - * Adds the "temporary" modifier. - * - * Use this to create a temporary table. - */ - temporary() { - return new _CreateTableBuilder({ - ...this.#props, - node: CreateTableNode.cloneWith(this.#props.node, { - temporary: true - }) - }); - } - /** - * Adds an "on commit" statement. - * - * This can be used in conjunction with temporary tables on supported databases - * like PostgreSQL. - */ - onCommit(onCommit) { - return new _CreateTableBuilder({ - ...this.#props, - node: CreateTableNode.cloneWith(this.#props.node, { - onCommit: parseOnCommitAction(onCommit) - }) - }); - } - /** - * Adds the "if not exists" modifier. - * - * If the table already exists, no error is thrown if this method has been called. - */ - ifNotExists() { - return new _CreateTableBuilder({ - ...this.#props, - node: CreateTableNode.cloneWith(this.#props.node, { - ifNotExists: true - }) - }); - } - /** - * Adds a column to the table. - * - * ### Examples - * - * ```ts - * import { sql } from 'kysely' - * - * await db.schema - * .createTable('person') - * .addColumn('id', 'integer', (col) => col.autoIncrement().primaryKey()) - * .addColumn('first_name', 'varchar(50)', (col) => col.notNull()) - * .addColumn('last_name', 'varchar(255)') - * .addColumn('bank_balance', 'numeric(8, 2)') - * // You can specify any data type using the `sql` tag if the types - * // don't include it. - * .addColumn('data', sql`any_type_here`) - * .addColumn('parent_id', 'integer', (col) => - * col.references('person.id').onDelete('cascade') - * ) - * ``` - * - * With this method, it's once again good to remember that Kysely just builds the - * query and doesn't provide the same API for all databases. For example, some - * databases like older MySQL don't support the `references` statement in the - * column definition. Instead foreign key constraints need to be defined in the - * `create table` query. See the next example: - * - * ```ts - * await db.schema - * .createTable('person') - * .addColumn('id', 'integer', (col) => col.primaryKey()) - * .addColumn('parent_id', 'integer') - * .addForeignKeyConstraint( - * 'person_parent_id_fk', - * ['parent_id'], - * 'person', - * ['id'], - * (cb) => cb.onDelete('cascade') - * ) - * .execute() - * ``` - * - * Another good example is that PostgreSQL doesn't support the `auto_increment` - * keyword and you need to define an autoincrementing column for example using - * `serial`: - * - * ```ts - * await db.schema - * .createTable('person') - * .addColumn('id', 'serial', (col) => col.primaryKey()) - * .execute() - * ``` - */ - addColumn(columnName, dataType, build = noop3) { - const columnBuilder = build(new ColumnDefinitionBuilder(ColumnDefinitionNode.create(columnName, parseDataTypeExpression(dataType)))); - return new _CreateTableBuilder({ - ...this.#props, - node: CreateTableNode.cloneWithColumn(this.#props.node, columnBuilder.toOperationNode()) - }); - } - /** - * Adds a primary key constraint for one or more columns. - * - * The constraint name can be anything you want, but it must be unique - * across the whole database. - * - * ### Examples - * - * ```ts - * await db.schema - * .createTable('person') - * .addColumn('first_name', 'varchar(64)') - * .addColumn('last_name', 'varchar(64)') - * .addPrimaryKeyConstraint('primary_key', ['first_name', 'last_name']) - * .execute() - * ``` - */ - addPrimaryKeyConstraint(constraintName, columns, build = noop3) { - const constraintBuilder = build(new PrimaryKeyConstraintBuilder(PrimaryKeyConstraintNode.create(columns, constraintName))); - return new _CreateTableBuilder({ - ...this.#props, - node: CreateTableNode.cloneWithConstraint(this.#props.node, constraintBuilder.toOperationNode()) - }); - } - /** - * Adds a unique constraint for one or more columns. - * - * The constraint name can be anything you want, but it must be unique - * across the whole database. - * - * ### Examples - * - * ```ts - * await db.schema - * .createTable('person') - * .addColumn('first_name', 'varchar(64)') - * .addColumn('last_name', 'varchar(64)') - * .addUniqueConstraint( - * 'first_name_last_name_unique', - * ['first_name', 'last_name'] - * ) - * .execute() - * ``` - * - * In dialects such as PostgreSQL you can specify `nulls not distinct` as follows: - * - * ```ts - * await db.schema - * .createTable('person') - * .addColumn('first_name', 'varchar(64)') - * .addColumn('last_name', 'varchar(64)') - * .addUniqueConstraint( - * 'first_name_last_name_unique', - * ['first_name', 'last_name'], - * (cb) => cb.nullsNotDistinct() - * ) - * .execute() - * ``` - */ - addUniqueConstraint(constraintName, columns, build = noop3) { - const uniqueConstraintBuilder = build(new UniqueConstraintNodeBuilder(UniqueConstraintNode.create(columns, constraintName))); - return new _CreateTableBuilder({ - ...this.#props, - node: CreateTableNode.cloneWithConstraint(this.#props.node, uniqueConstraintBuilder.toOperationNode()) - }); - } - /** - * Adds a check constraint. - * - * The constraint name can be anything you want, but it must be unique - * across the whole database. - * - * ### Examples - * - * ```ts - * import { sql } from 'kysely' - * - * await db.schema - * .createTable('animal') - * .addColumn('number_of_legs', 'integer') - * .addCheckConstraint('check_legs', sql`number_of_legs < 5`) - * .execute() - * ``` - */ - addCheckConstraint(constraintName, checkExpression, build = noop3) { - const constraintBuilder = build(new CheckConstraintBuilder(CheckConstraintNode.create(checkExpression.toOperationNode(), constraintName))); - return new _CreateTableBuilder({ - ...this.#props, - node: CreateTableNode.cloneWithConstraint(this.#props.node, constraintBuilder.toOperationNode()) - }); - } - /** - * Adds a foreign key constraint. - * - * The constraint name can be anything you want, but it must be unique - * across the whole database. - * - * ### Examples - * - * ```ts - * await db.schema - * .createTable('pet') - * .addColumn('owner_id', 'integer') - * .addForeignKeyConstraint( - * 'owner_id_foreign', - * ['owner_id'], - * 'person', - * ['id'], - * ) - * .execute() - * ``` - * - * Add constraint for multiple columns: - * - * ```ts - * await db.schema - * .createTable('pet') - * .addColumn('owner_id1', 'integer') - * .addColumn('owner_id2', 'integer') - * .addForeignKeyConstraint( - * 'owner_id_foreign', - * ['owner_id1', 'owner_id2'], - * 'person', - * ['id1', 'id2'], - * (cb) => cb.onDelete('cascade') - * ) - * .execute() - * ``` - */ - addForeignKeyConstraint(constraintName, columns, targetTable, targetColumns, build = noop3) { - const builder = build(new ForeignKeyConstraintBuilder(ForeignKeyConstraintNode.create(columns.map(ColumnNode.create), parseTable(targetTable), targetColumns.map(ColumnNode.create), constraintName))); - return new _CreateTableBuilder({ - ...this.#props, - node: CreateTableNode.cloneWithConstraint(this.#props.node, builder.toOperationNode()) - }); - } - /** - * This can be used to add any additional SQL to the front of the query __after__ the `create` keyword. - * - * Also see {@link temporary}. - * - * ### Examples - * - * ```ts - * import { sql } from 'kysely' - * - * await db.schema - * .createTable('person') - * .modifyFront(sql`global temporary`) - * .addColumn('id', 'integer', col => col.primaryKey()) - * .addColumn('first_name', 'varchar(64)', col => col.notNull()) - * .addColumn('last_name', 'varchar(64)', col => col.notNull()) - * .execute() - * ``` - * - * The generated SQL (Postgres): - * - * ```sql - * create global temporary table "person" ( - * "id" integer primary key, - * "first_name" varchar(64) not null, - * "last_name" varchar(64) not null - * ) - * ``` - */ - modifyFront(modifier) { - return new _CreateTableBuilder({ - ...this.#props, - node: CreateTableNode.cloneWithFrontModifier(this.#props.node, modifier.toOperationNode()) - }); - } - /** - * This can be used to add any additional SQL to the end of the query. - * - * Also see {@link onCommit}. - * - * ### Examples - * - * ```ts - * import { sql } from 'kysely' - * - * await db.schema - * .createTable('person') - * .addColumn('id', 'integer', col => col.primaryKey()) - * .addColumn('first_name', 'varchar(64)', col => col.notNull()) - * .addColumn('last_name', 'varchar(64)', col => col.notNull()) - * .modifyEnd(sql`collate utf8_unicode_ci`) - * .execute() - * ``` - * - * The generated SQL (MySQL): - * - * ```sql - * create table `person` ( - * `id` integer primary key, - * `first_name` varchar(64) not null, - * `last_name` varchar(64) not null - * ) collate utf8_unicode_ci - * ``` - */ - modifyEnd(modifier) { - return new _CreateTableBuilder({ - ...this.#props, - node: CreateTableNode.cloneWithEndModifier(this.#props.node, modifier.toOperationNode()) - }); - } - /** - * Allows to create table from `select` query. - * - * ### Examples - * - * ```ts - * await db.schema - * .createTable('copy') - * .temporary() - * .as(db.selectFrom('person').select(['first_name', 'last_name'])) - * .execute() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * create temporary table "copy" as - * select "first_name", "last_name" from "person" - * ``` - */ - as(expression) { - return new _CreateTableBuilder({ - ...this.#props, - node: CreateTableNode.cloneWith(this.#props.node, { - selectQuery: parseExpression(expression) - }) - }); - } - /** - * Calls the given function passing `this` as the only argument. - * - * ### Examples - * - * ```ts - * await db.schema - * .createTable('test') - * .$call((builder) => builder.addColumn('id', 'integer')) - * .execute() - * ``` - * - * This is useful for creating reusable functions that can be called with a builder. - * - * ```ts - * import { type CreateTableBuilder, sql } from 'kysely' - * - * const addDefaultColumns = (ctb: CreateTableBuilder) => { - * return ctb - * .addColumn('id', 'integer', (col) => col.notNull()) - * .addColumn('created_at', 'date', (col) => - * col.notNull().defaultTo(sql`now()`) - * ) - * .addColumn('updated_at', 'date', (col) => - * col.notNull().defaultTo(sql`now()`) - * ) - * } - * - * await db.schema - * .createTable('test') - * .$call(addDefaultColumns) - * .execute() - * ``` - */ - $call(func) { - return func(this); - } - toOperationNode() { - return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId); - } - compile() { - return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId); - } - async execute() { - await this.#props.executor.executeQuery(this.compile()); - } - }; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/drop-index-builder.js -var DropIndexBuilder; -var init_drop_index_builder = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/drop-index-builder.js"() { - init_drop_index_node(); - init_table_parser(); - init_object_utils(); - DropIndexBuilder = class _DropIndexBuilder { - #props; - constructor(props) { - this.#props = freeze2(props); - } - /** - * Specifies the table the index was created for. This is not needed - * in all dialects. - */ - on(table) { - return new _DropIndexBuilder({ - ...this.#props, - node: DropIndexNode.cloneWith(this.#props.node, { - table: parseTable(table) - }) - }); - } - ifExists() { - return new _DropIndexBuilder({ - ...this.#props, - node: DropIndexNode.cloneWith(this.#props.node, { - ifExists: true - }) - }); - } - cascade() { - return new _DropIndexBuilder({ - ...this.#props, - node: DropIndexNode.cloneWith(this.#props.node, { - cascade: true - }) - }); - } - /** - * Simply calls the provided function passing `this` as the only argument. `$call` returns - * what the provided function returns. - */ - $call(func) { - return func(this); - } - toOperationNode() { - return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId); - } - compile() { - return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId); - } - async execute() { - await this.#props.executor.executeQuery(this.compile()); - } - }; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/drop-schema-builder.js -var DropSchemaBuilder; -var init_drop_schema_builder = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/drop-schema-builder.js"() { - init_drop_schema_node(); - init_object_utils(); - DropSchemaBuilder = class _DropSchemaBuilder { - #props; - constructor(props) { - this.#props = freeze2(props); - } - ifExists() { - return new _DropSchemaBuilder({ - ...this.#props, - node: DropSchemaNode.cloneWith(this.#props.node, { - ifExists: true - }) - }); - } - cascade() { - return new _DropSchemaBuilder({ - ...this.#props, - node: DropSchemaNode.cloneWith(this.#props.node, { - cascade: true - }) - }); - } - /** - * Simply calls the provided function passing `this` as the only argument. `$call` returns - * what the provided function returns. - */ - $call(func) { - return func(this); - } - toOperationNode() { - return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId); - } - compile() { - return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId); - } - async execute() { - await this.#props.executor.executeQuery(this.compile()); - } - }; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/drop-table-builder.js -var DropTableBuilder; -var init_drop_table_builder = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/drop-table-builder.js"() { - init_drop_table_node(); - init_object_utils(); - DropTableBuilder = class _DropTableBuilder { - #props; - constructor(props) { - this.#props = freeze2(props); - } - ifExists() { - return new _DropTableBuilder({ - ...this.#props, - node: DropTableNode.cloneWith(this.#props.node, { - ifExists: true - }) - }); - } - cascade() { - return new _DropTableBuilder({ - ...this.#props, - node: DropTableNode.cloneWith(this.#props.node, { - cascade: true - }) - }); - } - /** - * Simply calls the provided function passing `this` as the only argument. `$call` returns - * what the provided function returns. - */ - $call(func) { - return func(this); - } - toOperationNode() { - return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId); - } - compile() { - return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId); - } - async execute() { - await this.#props.executor.executeQuery(this.compile()); - } - }; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/create-view-node.js -var CreateViewNode; -var init_create_view_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/create-view-node.js"() { - init_object_utils(); - init_schemable_identifier_node(); - CreateViewNode = freeze2({ - is(node) { - return node.kind === "CreateViewNode"; - }, - create(name) { - return freeze2({ - kind: "CreateViewNode", - name: SchemableIdentifierNode.create(name) - }); - }, - cloneWith(createView3, params) { - return freeze2({ - ...createView3, - ...params - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/immediate-value/immediate-value-plugin.js -var ImmediateValuePlugin; -var init_immediate_value_plugin = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/immediate-value/immediate-value-plugin.js"() { - init_immediate_value_transformer(); - ImmediateValuePlugin = class { - #transformer = new ImmediateValueTransformer(); - transformQuery(args) { - return this.#transformer.transformNode(args.node, args.queryId); - } - transformResult(args) { - return Promise.resolve(args.result); - } - }; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/create-view-builder.js -var CreateViewBuilder; -var init_create_view_builder = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/create-view-builder.js"() { - init_object_utils(); - init_create_view_node(); - init_reference_parser(); - init_immediate_value_plugin(); - CreateViewBuilder = class _CreateViewBuilder { - #props; - constructor(props) { - this.#props = freeze2(props); - } - /** - * Adds the "temporary" modifier. - * - * Use this to create a temporary view. - */ - temporary() { - return new _CreateViewBuilder({ - ...this.#props, - node: CreateViewNode.cloneWith(this.#props.node, { - temporary: true - }) - }); - } - materialized() { - return new _CreateViewBuilder({ - ...this.#props, - node: CreateViewNode.cloneWith(this.#props.node, { - materialized: true - }) - }); - } - /** - * Only implemented on some dialects like SQLite. On most dialects, use {@link orReplace}. - */ - ifNotExists() { - return new _CreateViewBuilder({ - ...this.#props, - node: CreateViewNode.cloneWith(this.#props.node, { - ifNotExists: true - }) - }); - } - orReplace() { - return new _CreateViewBuilder({ - ...this.#props, - node: CreateViewNode.cloneWith(this.#props.node, { - orReplace: true - }) - }); - } - columns(columns) { - return new _CreateViewBuilder({ - ...this.#props, - node: CreateViewNode.cloneWith(this.#props.node, { - columns: columns.map(parseColumnName) - }) - }); - } - /** - * Sets the select query or a `values` statement that creates the view. - * - * WARNING! - * Some dialects don't support parameterized queries in DDL statements and therefore - * the query or raw {@link sql } expression passed here is interpolated into a single - * string opening an SQL injection vulnerability. DO NOT pass unchecked user input - * into the query or raw expression passed to this method! - */ - as(query) { - const queryNode = query.withPlugin(new ImmediateValuePlugin()).toOperationNode(); - return new _CreateViewBuilder({ - ...this.#props, - node: CreateViewNode.cloneWith(this.#props.node, { - as: queryNode - }) - }); - } - /** - * Simply calls the provided function passing `this` as the only argument. `$call` returns - * what the provided function returns. - */ - $call(func) { - return func(this); - } - toOperationNode() { - return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId); - } - compile() { - return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId); - } - async execute() { - await this.#props.executor.executeQuery(this.compile()); - } - }; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/drop-view-node.js -var DropViewNode; -var init_drop_view_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/drop-view-node.js"() { - init_object_utils(); - init_schemable_identifier_node(); - DropViewNode = freeze2({ - is(node) { - return node.kind === "DropViewNode"; - }, - create(name) { - return freeze2({ - kind: "DropViewNode", - name: SchemableIdentifierNode.create(name) - }); - }, - cloneWith(dropView, params) { - return freeze2({ - ...dropView, - ...params - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/drop-view-builder.js -var DropViewBuilder; -var init_drop_view_builder = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/drop-view-builder.js"() { - init_object_utils(); - init_drop_view_node(); - DropViewBuilder = class _DropViewBuilder { - #props; - constructor(props) { - this.#props = freeze2(props); - } - materialized() { - return new _DropViewBuilder({ - ...this.#props, - node: DropViewNode.cloneWith(this.#props.node, { - materialized: true - }) - }); - } - ifExists() { - return new _DropViewBuilder({ - ...this.#props, - node: DropViewNode.cloneWith(this.#props.node, { - ifExists: true - }) - }); - } - cascade() { - return new _DropViewBuilder({ - ...this.#props, - node: DropViewNode.cloneWith(this.#props.node, { - cascade: true - }) - }); - } - /** - * Simply calls the provided function passing `this` as the only argument. `$call` returns - * what the provided function returns. - */ - $call(func) { - return func(this); - } - toOperationNode() { - return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId); - } - compile() { - return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId); - } - async execute() { - await this.#props.executor.executeQuery(this.compile()); - } - }; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/create-type-node.js -var CreateTypeNode; -var init_create_type_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/create-type-node.js"() { - init_object_utils(); - init_value_list_node(); - init_value_node(); - CreateTypeNode = freeze2({ - is(node) { - return node.kind === "CreateTypeNode"; - }, - create(name) { - return freeze2({ - kind: "CreateTypeNode", - name - }); - }, - cloneWithEnum(createType, values2) { - return freeze2({ - ...createType, - enum: ValueListNode.create(values2.map(ValueNode.createImmediate)) - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/create-type-builder.js -var CreateTypeBuilder; -var init_create_type_builder = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/create-type-builder.js"() { - init_object_utils(); - init_create_type_node(); - CreateTypeBuilder = class _CreateTypeBuilder { - #props; - constructor(props) { - this.#props = freeze2(props); - } - toOperationNode() { - return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId); - } - /** - * Creates an anum type. - * - * ### Examples - * - * ```ts - * db.schema.createType('species').asEnum(['cat', 'dog', 'frog']) - * ``` - */ - asEnum(values2) { - return new _CreateTypeBuilder({ - ...this.#props, - node: CreateTypeNode.cloneWithEnum(this.#props.node, values2) - }); - } - /** - * Simply calls the provided function passing `this` as the only argument. `$call` returns - * what the provided function returns. - */ - $call(func) { - return func(this); - } - compile() { - return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId); - } - async execute() { - await this.#props.executor.executeQuery(this.compile()); - } - }; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/drop-type-node.js -var DropTypeNode; -var init_drop_type_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/drop-type-node.js"() { - init_object_utils(); - DropTypeNode = freeze2({ - is(node) { - return node.kind === "DropTypeNode"; - }, - create(name) { - return freeze2({ - kind: "DropTypeNode", - name - }); - }, - cloneWith(dropType, params) { - return freeze2({ - ...dropType, - ...params - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/drop-type-builder.js -var DropTypeBuilder; -var init_drop_type_builder = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/drop-type-builder.js"() { - init_drop_type_node(); - init_object_utils(); - DropTypeBuilder = class _DropTypeBuilder { - #props; - constructor(props) { - this.#props = freeze2(props); - } - ifExists() { - return new _DropTypeBuilder({ - ...this.#props, - node: DropTypeNode.cloneWith(this.#props.node, { - ifExists: true - }) - }); - } - /** - * Simply calls the provided function passing `this` as the only argument. `$call` returns - * what the provided function returns. - */ - $call(func) { - return func(this); - } - toOperationNode() { - return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId); - } - compile() { - return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId); - } - async execute() { - await this.#props.executor.executeQuery(this.compile()); - } - }; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/identifier-parser.js -function parseSchemableIdentifier(id) { - const SCHEMA_SEPARATOR = "."; - if (id.includes(SCHEMA_SEPARATOR)) { - const parts = id.split(SCHEMA_SEPARATOR).map(trim3); - if (parts.length === 2) { - return SchemableIdentifierNode.createWithSchema(parts[0], parts[1]); - } else { - throw new Error(`invalid schemable identifier ${id}`); - } - } else { - return SchemableIdentifierNode.create(id); - } -} -function trim3(str) { - return str.trim(); -} -var init_identifier_parser = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/identifier-parser.js"() { - init_schemable_identifier_node(); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/refresh-materialized-view-node.js -var RefreshMaterializedViewNode; -var init_refresh_materialized_view_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/refresh-materialized-view-node.js"() { - init_object_utils(); - init_schemable_identifier_node(); - RefreshMaterializedViewNode = freeze2({ - is(node) { - return node.kind === "RefreshMaterializedViewNode"; - }, - create(name) { - return freeze2({ - kind: "RefreshMaterializedViewNode", - name: SchemableIdentifierNode.create(name) - }); - }, - cloneWith(createView3, params) { - return freeze2({ - ...createView3, - ...params - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/refresh-materialized-view-builder.js -var RefreshMaterializedViewBuilder; -var init_refresh_materialized_view_builder = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/refresh-materialized-view-builder.js"() { - init_object_utils(); - init_refresh_materialized_view_node(); - RefreshMaterializedViewBuilder = class _RefreshMaterializedViewBuilder { - #props; - constructor(props) { - this.#props = freeze2(props); - } - /** - * Adds the "concurrently" modifier. - * - * Use this to refresh the view without locking out concurrent selects on the materialized view. - * - * WARNING! - * This cannot be used with the "with no data" modifier. - */ - concurrently() { - return new _RefreshMaterializedViewBuilder({ - ...this.#props, - node: RefreshMaterializedViewNode.cloneWith(this.#props.node, { - concurrently: true, - withNoData: false - }) - }); - } - /** - * Adds the "with data" modifier. - * - * If specified (or defaults) the backing query is executed to provide the new data, and the materialized view is left in a scannable state - */ - withData() { - return new _RefreshMaterializedViewBuilder({ - ...this.#props, - node: RefreshMaterializedViewNode.cloneWith(this.#props.node, { - withNoData: false - }) - }); - } - /** - * Adds the "with no data" modifier. - * - * If specified, no new data is generated and the materialized view is left in an unscannable state. - * - * WARNING! - * This cannot be used with the "concurrently" modifier. - */ - withNoData() { - return new _RefreshMaterializedViewBuilder({ - ...this.#props, - node: RefreshMaterializedViewNode.cloneWith(this.#props.node, { - withNoData: true, - concurrently: false - }) - }); - } - /** - * Simply calls the provided function passing `this` as the only argument. `$call` returns - * what the provided function returns. - */ - $call(func) { - return func(this); - } - toOperationNode() { - return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId); - } - compile() { - return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId); - } - async execute() { - await this.#props.executor.executeQuery(this.compile()); - } - }; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/schema.js -var SchemaModule; -var init_schema5 = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/schema/schema.js"() { - init_alter_table_node(); - init_create_index_node(); - init_create_schema_node(); - init_create_table_node(); - init_drop_index_node(); - init_drop_schema_node(); - init_drop_table_node(); - init_table_parser(); - init_alter_table_builder(); - init_create_index_builder(); - init_create_schema_builder(); - init_create_table_builder(); - init_drop_index_builder(); - init_drop_schema_builder(); - init_drop_table_builder(); - init_query_id(); - init_with_schema_plugin(); - init_create_view_builder(); - init_create_view_node(); - init_drop_view_builder(); - init_drop_view_node(); - init_create_type_builder(); - init_drop_type_builder(); - init_create_type_node(); - init_drop_type_node(); - init_identifier_parser(); - init_refresh_materialized_view_builder(); - init_refresh_materialized_view_node(); - SchemaModule = class _SchemaModule { - #executor; - constructor(executor) { - this.#executor = executor; - } - /** - * Create a new table. - * - * ### Examples - * - * This example creates a new table with columns `id`, `first_name`, - * `last_name` and `gender`: - * - * ```ts - * await db.schema - * .createTable('person') - * .addColumn('id', 'integer', col => col.primaryKey().autoIncrement()) - * .addColumn('first_name', 'varchar', col => col.notNull()) - * .addColumn('last_name', 'varchar', col => col.notNull()) - * .addColumn('gender', 'varchar') - * .execute() - * ``` - * - * This example creates a table with a foreign key. Not all database - * engines support column-level foreign key constraint definitions. - * For example if you are using MySQL 5.X see the next example after - * this one. - * - * ```ts - * await db.schema - * .createTable('pet') - * .addColumn('id', 'integer', col => col.primaryKey().autoIncrement()) - * .addColumn('owner_id', 'integer', col => col - * .references('person.id') - * .onDelete('cascade') - * ) - * .execute() - * ``` - * - * This example adds a foreign key constraint for a columns just - * like the previous example, but using a table-level statement. - * On MySQL 5.X you need to define foreign key constraints like - * this: - * - * ```ts - * await db.schema - * .createTable('pet') - * .addColumn('id', 'integer', col => col.primaryKey().autoIncrement()) - * .addColumn('owner_id', 'integer') - * .addForeignKeyConstraint( - * 'pet_owner_id_foreign', ['owner_id'], 'person', ['id'], - * (constraint) => constraint.onDelete('cascade') - * ) - * .execute() - * ``` - */ - createTable(table) { - return new CreateTableBuilder({ - queryId: createQueryId(), - executor: this.#executor, - node: CreateTableNode.create(parseTable(table)) - }); - } - /** - * Drop a table. - * - * ### Examples - * - * ```ts - * await db.schema - * .dropTable('person') - * .execute() - * ``` - */ - dropTable(table) { - return new DropTableBuilder({ - queryId: createQueryId(), - executor: this.#executor, - node: DropTableNode.create(parseTable(table)) - }); - } - /** - * Create a new index. - * - * ### Examples - * - * ```ts - * await db.schema - * .createIndex('person_full_name_unique_index') - * .on('person') - * .columns(['first_name', 'last_name']) - * .execute() - * ``` - */ - createIndex(indexName) { - return new CreateIndexBuilder({ - queryId: createQueryId(), - executor: this.#executor, - node: CreateIndexNode.create(indexName) - }); - } - /** - * Drop an index. - * - * ### Examples - * - * ```ts - * await db.schema - * .dropIndex('person_full_name_unique_index') - * .execute() - * ``` - */ - dropIndex(indexName) { - return new DropIndexBuilder({ - queryId: createQueryId(), - executor: this.#executor, - node: DropIndexNode.create(indexName) - }); - } - /** - * Create a new schema. - * - * ### Examples - * - * ```ts - * await db.schema - * .createSchema('some_schema') - * .execute() - * ``` - */ - createSchema(schema2) { - return new CreateSchemaBuilder({ - queryId: createQueryId(), - executor: this.#executor, - node: CreateSchemaNode.create(schema2) - }); - } - /** - * Drop a schema. - * - * ### Examples - * - * ```ts - * await db.schema - * .dropSchema('some_schema') - * .execute() - * ``` - */ - dropSchema(schema2) { - return new DropSchemaBuilder({ - queryId: createQueryId(), - executor: this.#executor, - node: DropSchemaNode.create(schema2) - }); - } - /** - * Alter a table. - * - * ### Examples - * - * ```ts - * await db.schema - * .alterTable('person') - * .alterColumn('first_name', (ac) => ac.setDataType('text')) - * .execute() - * ``` - */ - alterTable(table) { - return new AlterTableBuilder({ - queryId: createQueryId(), - executor: this.#executor, - node: AlterTableNode.create(parseTable(table)) - }); - } - /** - * Create a new view. - * - * ### Examples - * - * ```ts - * await db.schema - * .createView('dogs') - * .orReplace() - * .as(db.selectFrom('pet').selectAll().where('species', '=', 'dog')) - * .execute() - * ``` - */ - createView(viewName) { - return new CreateViewBuilder({ - queryId: createQueryId(), - executor: this.#executor, - node: CreateViewNode.create(viewName) - }); - } - /** - * Refresh a materialized view. - * - * ### Examples - * - * ```ts - * await db.schema - * .refreshMaterializedView('my_view') - * .concurrently() - * .execute() - * ``` - */ - refreshMaterializedView(viewName) { - return new RefreshMaterializedViewBuilder({ - queryId: createQueryId(), - executor: this.#executor, - node: RefreshMaterializedViewNode.create(viewName) - }); - } - /** - * Drop a view. - * - * ### Examples - * - * ```ts - * await db.schema - * .dropView('dogs') - * .ifExists() - * .execute() - * ``` - */ - dropView(viewName) { - return new DropViewBuilder({ - queryId: createQueryId(), - executor: this.#executor, - node: DropViewNode.create(viewName) - }); - } - /** - * Create a new type. - * - * Only some dialects like PostgreSQL have user-defined types. - * - * ### Examples - * - * ```ts - * await db.schema - * .createType('species') - * .asEnum(['dog', 'cat', 'frog']) - * .execute() - * ``` - */ - createType(typeName) { - return new CreateTypeBuilder({ - queryId: createQueryId(), - executor: this.#executor, - node: CreateTypeNode.create(parseSchemableIdentifier(typeName)) - }); - } - /** - * Drop a type. - * - * Only some dialects like PostgreSQL have user-defined types. - * - * ### Examples - * - * ```ts - * await db.schema - * .dropType('species') - * .ifExists() - * .execute() - * ``` - */ - dropType(typeName) { - return new DropTypeBuilder({ - queryId: createQueryId(), - executor: this.#executor, - node: DropTypeNode.create(parseSchemableIdentifier(typeName)) - }); - } - /** - * Returns a copy of this schema module with the given plugin installed. - */ - withPlugin(plugin) { - return new _SchemaModule(this.#executor.withPlugin(plugin)); - } - /** - * Returns a copy of this schema module without any plugins. - */ - withoutPlugins() { - return new _SchemaModule(this.#executor.withoutPlugins()); - } - /** - * See {@link QueryCreator.withSchema} - */ - withSchema(schema2) { - return new _SchemaModule(this.#executor.withPluginAtFront(new WithSchemaPlugin(schema2))); - } - }; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dynamic/dynamic.js -var DynamicModule; -var init_dynamic = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dynamic/dynamic.js"() { - init_dynamic_reference_builder(); - init_dynamic_table_builder(); - DynamicModule = class { - /** - * Creates a dynamic reference to a column that is not know at compile time. - * - * Kysely is built in a way that by default you can't refer to tables or columns - * that are not actually visible in the current query and context. This is all - * done by TypeScript at compile time, which means that you need to know the - * columns and tables at compile time. This is not always the case of course. - * - * This method is meant to be used in those cases where the column names - * come from the user input or are not otherwise known at compile time. - * - * WARNING! Unlike values, column names are not escaped by the database engine - * or Kysely and if you pass in unchecked column names using this method, you - * create an SQL injection vulnerability. Always __always__ validate the user - * input before passing it to this method. - * - * There are couple of examples below for some use cases, but you can pass - * `ref` to other methods as well. If the types allow you to pass a `ref` - * value to some place, it should work. - * - * ### Examples - * - * Filter by a column not know at compile time: - * - * ```ts - * async function someQuery(filterColumn: string, filterValue: string) { - * const { ref } = db.dynamic - * - * return await db - * .selectFrom('person') - * .selectAll() - * .where(ref(filterColumn), '=', filterValue) - * .execute() - * } - * - * someQuery('first_name', 'Arnold') - * someQuery('person.last_name', 'Aniston') - * ``` - * - * Order by a column not know at compile time: - * - * ```ts - * async function someQuery(orderBy: string) { - * const { ref } = db.dynamic - * - * return await db - * .selectFrom('person') - * .select('person.first_name as fn') - * .orderBy(ref(orderBy)) - * .execute() - * } - * - * someQuery('fn') - * ``` - * - * In this example we add selections dynamically: - * - * ```ts - * const { ref } = db.dynamic - * - * // Some column name provided by the user. Value not known at compile time. - * const columnFromUserInput: PossibleColumns = 'birthdate'; - * - * // A type that lists all possible values `columnFromUserInput` can have. - * // You can use `keyof Person` if any column of an interface is allowed. - * type PossibleColumns = 'last_name' | 'first_name' | 'birthdate' - * - * const [person] = await db.selectFrom('person') - * .select([ - * ref(columnFromUserInput), - * 'id' - * ]) - * .execute() - * - * // The resulting type contains all `PossibleColumns` as optional fields - * // because we cannot know which field was actually selected before - * // running the code. - * const lastName: string | null | undefined = person?.last_name - * const firstName: string | undefined = person?.first_name - * const birthDate: Date | null | undefined = person?.birthdate - * - * // The result type also contains the compile time selection `id`. - * person?.id - * ``` - */ - ref(reference) { - return new DynamicReferenceBuilder(reference); - } - /** - * Creates a table reference to a table that's not fully known at compile time. - * - * The type `T` is allowed to be a union of multiple tables. - * - * - * - * A generic type-safe helper function for finding a row by a column value: - * - * ```ts - * import { SelectType } from 'kysely' - * import { Database } from 'type-editor' - * - * async function getRowByColumn< - * T extends keyof Database, - * C extends keyof Database[T] & string, - * V extends SelectType, - * >(t: T, c: C, v: V) { - * // We need to use the dynamic module since the table name - * // is not known at compile time. - * const { table, ref } = db.dynamic - * - * return await db - * .selectFrom(table(t).as('t')) - * .selectAll() - * .where(ref(c), '=', v) - * .orderBy('t.id') - * .executeTakeFirstOrThrow() - * } - * - * const person = await getRowByColumn('person', 'first_name', 'Arnold') - * ``` - */ - table(table) { - return new DynamicTableBuilder(table); - } - }; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/driver/default-connection-provider.js -var DefaultConnectionProvider; -var init_default_connection_provider = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/driver/default-connection-provider.js"() { - DefaultConnectionProvider = class { - #driver; - constructor(driver) { - this.#driver = driver; - } - async provideConnection(consumer) { - const connection2 = await this.#driver.acquireConnection(); - try { - return await consumer(connection2); - } finally { - await this.#driver.releaseConnection(connection2); - } - } - }; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-executor/default-query-executor.js -var DefaultQueryExecutor; -var init_default_query_executor = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-executor/default-query-executor.js"() { - init_query_executor_base(); - DefaultQueryExecutor = class _DefaultQueryExecutor extends QueryExecutorBase { - #compiler; - #adapter; - #connectionProvider; - constructor(compiler, adapter, connectionProvider, plugins2 = []) { - super(plugins2); - this.#compiler = compiler; - this.#adapter = adapter; - this.#connectionProvider = connectionProvider; - } - get adapter() { - return this.#adapter; - } - compileQuery(node, queryId) { - return this.#compiler.compileQuery(node, queryId); - } - provideConnection(consumer) { - return this.#connectionProvider.provideConnection(consumer); - } - withPlugins(plugins2) { - return new _DefaultQueryExecutor(this.#compiler, this.#adapter, this.#connectionProvider, [...this.plugins, ...plugins2]); - } - withPlugin(plugin) { - return new _DefaultQueryExecutor(this.#compiler, this.#adapter, this.#connectionProvider, [...this.plugins, plugin]); - } - withPluginAtFront(plugin) { - return new _DefaultQueryExecutor(this.#compiler, this.#adapter, this.#connectionProvider, [plugin, ...this.plugins]); - } - withConnectionProvider(connectionProvider) { - return new _DefaultQueryExecutor(this.#compiler, this.#adapter, connectionProvider, [...this.plugins]); - } - withoutPlugins() { - return new _DefaultQueryExecutor(this.#compiler, this.#adapter, this.#connectionProvider, []); - } - }; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/performance-now.js -function performanceNow() { - if (typeof performance !== "undefined" && isFunction(performance.now)) { - return performance.now(); - } else { - return Date.now(); - } -} -var init_performance_now = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/performance-now.js"() { - init_object_utils(); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/driver/runtime-driver.js -var RuntimeDriver; -var init_runtime_driver = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/driver/runtime-driver.js"() { - init_performance_now(); - RuntimeDriver = class { - #driver; - #log; - #initPromise; - #initDone; - #destroyPromise; - #connections = /* @__PURE__ */ new WeakSet(); - constructor(driver, log2) { - this.#initDone = false; - this.#driver = driver; - this.#log = log2; - } - async init() { - if (this.#destroyPromise) { - throw new Error("driver has already been destroyed"); - } - if (!this.#initPromise) { - this.#initPromise = this.#driver.init().then(() => { - this.#initDone = true; - }).catch((err) => { - this.#initPromise = void 0; - return Promise.reject(err); - }); - } - await this.#initPromise; - } - async acquireConnection() { - if (this.#destroyPromise) { - throw new Error("driver has already been destroyed"); - } - if (!this.#initDone) { - await this.init(); - } - const connection2 = await this.#driver.acquireConnection(); - if (!this.#connections.has(connection2)) { - if (this.#needsLogging()) { - this.#addLogging(connection2); - } - this.#connections.add(connection2); - } - return connection2; - } - async releaseConnection(connection2) { - await this.#driver.releaseConnection(connection2); - } - beginTransaction(connection2, settings) { - return this.#driver.beginTransaction(connection2, settings); - } - commitTransaction(connection2) { - return this.#driver.commitTransaction(connection2); - } - rollbackTransaction(connection2) { - return this.#driver.rollbackTransaction(connection2); - } - savepoint(connection2, savepointName, compileQuery) { - if (this.#driver.savepoint) { - return this.#driver.savepoint(connection2, savepointName, compileQuery); - } - throw new Error("The `savepoint` method is not supported by this driver"); - } - rollbackToSavepoint(connection2, savepointName, compileQuery) { - if (this.#driver.rollbackToSavepoint) { - return this.#driver.rollbackToSavepoint(connection2, savepointName, compileQuery); - } - throw new Error("The `rollbackToSavepoint` method is not supported by this driver"); - } - releaseSavepoint(connection2, savepointName, compileQuery) { - if (this.#driver.releaseSavepoint) { - return this.#driver.releaseSavepoint(connection2, savepointName, compileQuery); - } - throw new Error("The `releaseSavepoint` method is not supported by this driver"); - } - async destroy() { - if (!this.#initPromise) { - return; - } - await this.#initPromise; - if (!this.#destroyPromise) { - this.#destroyPromise = this.#driver.destroy().catch((err) => { - this.#destroyPromise = void 0; - return Promise.reject(err); - }); - } - await this.#destroyPromise; - } - #needsLogging() { - return this.#log.isLevelEnabled("query") || this.#log.isLevelEnabled("error"); - } - // This method monkey patches the database connection's executeQuery method - // by adding logging code around it. Monkey patching is not pretty, but it's - // the best option in this case. - #addLogging(connection2) { - const executeQuery = connection2.executeQuery; - const streamQuery = connection2.streamQuery; - const dis = this; - connection2.executeQuery = async (compiledQuery) => { - let caughtError; - const startTime = performanceNow(); - try { - return await executeQuery.call(connection2, compiledQuery); - } catch (error50) { - caughtError = error50; - await dis.#logError(error50, compiledQuery, startTime); - throw error50; - } finally { - if (!caughtError) { - await dis.#logQuery(compiledQuery, startTime); - } - } - }; - connection2.streamQuery = async function* (compiledQuery, chunkSize) { - let caughtError; - const startTime = performanceNow(); - try { - for await (const result of streamQuery.call(connection2, compiledQuery, chunkSize)) { - yield result; - } - } catch (error50) { - caughtError = error50; - await dis.#logError(error50, compiledQuery, startTime); - throw error50; - } finally { - if (!caughtError) { - await dis.#logQuery(compiledQuery, startTime, true); - } - } - }; - } - async #logError(error50, compiledQuery, startTime) { - await this.#log.error(() => ({ - level: "error", - error: error50, - query: compiledQuery, - queryDurationMillis: this.#calculateDurationMillis(startTime) - })); - } - async #logQuery(compiledQuery, startTime, isStream = false) { - await this.#log.query(() => ({ - level: "query", - isStream, - query: compiledQuery, - queryDurationMillis: this.#calculateDurationMillis(startTime) - })); - } - #calculateDurationMillis(startTime) { - return performanceNow() - startTime; - } - }; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/driver/single-connection-provider.js -var ignoreError, SingleConnectionProvider; -var init_single_connection_provider = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/driver/single-connection-provider.js"() { - ignoreError = () => { - }; - SingleConnectionProvider = class { - #connection; - #runningPromise; - constructor(connection2) { - this.#connection = connection2; - } - async provideConnection(consumer) { - while (this.#runningPromise) { - await this.#runningPromise.catch(ignoreError); - } - this.#runningPromise = this.#run(consumer).finally(() => { - this.#runningPromise = void 0; - }); - return this.#runningPromise; - } - // Run the runner in an async function to make sure it doesn't - // throw synchronous errors. - async #run(runner) { - return await runner(this.#connection); - } - }; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/driver/driver.js -function validateTransactionSettings(settings) { - if (settings.accessMode && !TRANSACTION_ACCESS_MODES.includes(settings.accessMode)) { - throw new Error(`invalid transaction access mode ${settings.accessMode}`); - } - if (settings.isolationLevel && !TRANSACTION_ISOLATION_LEVELS.includes(settings.isolationLevel)) { - throw new Error(`invalid transaction isolation level ${settings.isolationLevel}`); - } -} -var TRANSACTION_ACCESS_MODES, TRANSACTION_ISOLATION_LEVELS; -var init_driver2 = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/driver/driver.js"() { - TRANSACTION_ACCESS_MODES = ["read only", "read write"]; - TRANSACTION_ISOLATION_LEVELS = [ - "read uncommitted", - "read committed", - "repeatable read", - "serializable", - "snapshot" - ]; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/log.js -function defaultLogger(event) { - if (event.level === "query") { - const prefix = `kysely:query:${event.isStream ? "stream:" : ""}`; - console.log(`${prefix} ${event.query.sql}`); - console.log(`${prefix} duration: ${event.queryDurationMillis.toFixed(1)}ms`); - } else if (event.level === "error") { - if (event.error instanceof Error) { - console.error(`kysely:error: ${event.error.stack ?? event.error.message}`); - } else { - console.error(`kysely:error: ${JSON.stringify({ - error: event.error, - query: event.query.sql, - queryDurationMillis: event.queryDurationMillis - })}`); - } - } -} -var logLevels, LOG_LEVELS, Log; -var init_log = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/log.js"() { - init_object_utils(); - logLevels = ["query", "error"]; - LOG_LEVELS = freeze2(logLevels); - Log = class { - #levels; - #logger; - constructor(config3) { - if (isFunction(config3)) { - this.#logger = config3; - this.#levels = freeze2({ - query: true, - error: true - }); - } else { - this.#logger = defaultLogger; - this.#levels = freeze2({ - query: config3.includes("query"), - error: config3.includes("error") - }); - } - } - isLevelEnabled(level) { - return this.#levels[level]; - } - async query(getEvent) { - if (this.#levels.query) { - await this.#logger(getEvent()); - } - } - async error(getEvent) { - if (this.#levels.error) { - await this.#logger(getEvent()); - } - } - }; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/compilable.js -function isCompilable(value) { - return isObject3(value) && isFunction(value.compile); -} -var init_compilable = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/compilable.js"() { - init_object_utils(); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/kysely.js -function isKyselyProps(obj) { - return isObject3(obj) && isObject3(obj.config) && isObject3(obj.driver) && isObject3(obj.executor) && isObject3(obj.dialect); -} -function assertNotCommittedOrRolledBack(state2) { - if (state2.isCommitted) { - throw new Error("Transaction is already committed"); - } - if (state2.isRolledBack) { - throw new Error("Transaction is already rolled back"); - } -} -var Kysely, Transaction, ConnectionBuilder, TransactionBuilder, ControlledTransactionBuilder, ControlledTransaction, Command, NotCommittedOrRolledBackAssertingExecutor; -var init_kysely = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/kysely.js"() { - init_schema5(); - init_dynamic(); - init_default_connection_provider(); - init_query_creator(); - init_default_query_executor(); - init_object_utils(); - init_runtime_driver(); - init_single_connection_provider(); - init_driver2(); - init_function_module(); - init_log(); - init_query_id(); - init_compilable(); - init_case_builder(); - init_case_node(); - init_expression_parser(); - init_with_schema_plugin(); - init_provide_controlled_connection(); - init_log_once(); - Symbol.asyncDispose ??= /* @__PURE__ */ Symbol("Symbol.asyncDispose"); - Kysely = class _Kysely extends QueryCreator { - #props; - constructor(args) { - let superProps; - let props; - if (isKyselyProps(args)) { - superProps = { executor: args.executor }; - props = { ...args }; - } else { - const dialect = args.dialect; - const driver = dialect.createDriver(); - const compiler = dialect.createQueryCompiler(); - const adapter = dialect.createAdapter(); - const log2 = new Log(args.log ?? []); - const runtimeDriver = new RuntimeDriver(driver, log2); - const connectionProvider = new DefaultConnectionProvider(runtimeDriver); - const executor = new DefaultQueryExecutor(compiler, adapter, connectionProvider, args.plugins ?? []); - superProps = { executor }; - props = { - config: args, - executor, - dialect, - driver: runtimeDriver - }; - } - super(superProps); - this.#props = freeze2(props); - } - /** - * Returns the {@link SchemaModule} module for building database schema. - */ - get schema() { - return new SchemaModule(this.#props.executor); - } - /** - * Returns a the {@link DynamicModule} module. - * - * The {@link DynamicModule} module can be used to bypass strict typing and - * passing in dynamic values for the queries. - */ - get dynamic() { - return new DynamicModule(); - } - /** - * Returns a {@link DatabaseIntrospector | database introspector}. - */ - get introspection() { - return this.#props.dialect.createIntrospector(this.withoutPlugins()); - } - case(value) { - return new CaseBuilder({ - node: CaseNode.create(isUndefined(value) ? void 0 : parseExpression(value)) - }); - } - /** - * Returns a {@link FunctionModule} that can be used to write somewhat type-safe function - * calls. - * - * ```ts - * const { count } = db.fn - * - * await db.selectFrom('person') - * .innerJoin('pet', 'pet.owner_id', 'person.id') - * .select([ - * 'id', - * count('pet.id').as('person_count'), - * ]) - * .groupBy('person.id') - * .having(count('pet.id'), '>', 10) - * .execute() - * ``` - * - * The generated SQL (PostgreSQL): - * - * ```sql - * select "person"."id", count("pet"."id") as "person_count" - * from "person" - * inner join "pet" on "pet"."owner_id" = "person"."id" - * group by "person"."id" - * having count("pet"."id") > $1 - * ``` - * - * Why "somewhat" type-safe? Because the function calls are not bound to the - * current query context. They allow you to reference columns and tables that - * are not in the current query. E.g. remove the `innerJoin` from the previous - * query and TypeScript won't even complain. - * - * If you want to make the function calls fully type-safe, you can use the - * {@link ExpressionBuilder.fn} getter for a query context-aware, stricter {@link FunctionModule}. - * - * ```ts - * await db.selectFrom('person') - * .innerJoin('pet', 'pet.owner_id', 'person.id') - * .select((eb) => [ - * 'person.id', - * eb.fn.count('pet.id').as('pet_count') - * ]) - * .groupBy('person.id') - * .having((eb) => eb.fn.count('pet.id'), '>', 10) - * .execute() - * ``` - */ - get fn() { - return createFunctionModule(); - } - /** - * Creates a {@link TransactionBuilder} that can be used to run queries inside a transaction. - * - * The returned {@link TransactionBuilder} can be used to configure the transaction. The - * {@link TransactionBuilder.execute} method can then be called to run the transaction. - * {@link TransactionBuilder.execute} takes a function that is run inside the - * transaction. If the function throws an exception, - * 1. the exception is caught, - * 2. the transaction is rolled back, and - * 3. the exception is thrown again. - * Otherwise the transaction is committed. - * - * The callback function passed to the {@link TransactionBuilder.execute | execute} - * method gets the transaction object as its only argument. The transaction is - * of type {@link Transaction} which inherits {@link Kysely}. Any query - * started through the transaction object is executed inside the transaction. - * - * To run a controlled transaction, allowing you to commit and rollback manually, - * use {@link startTransaction} instead. - * - * ### Examples - * - * - * - * This example inserts two rows in a transaction. If an exception is thrown inside - * the callback passed to the `execute` method, - * 1. the exception is caught, - * 2. the transaction is rolled back, and - * 3. the exception is thrown again. - * Otherwise the transaction is committed. - * - * ```ts - * const catto = await db.transaction().execute(async (trx) => { - * const jennifer = await trx.insertInto('person') - * .values({ - * first_name: 'Jennifer', - * last_name: 'Aniston', - * age: 40, - * }) - * .returning('id') - * .executeTakeFirstOrThrow() - * - * return await trx.insertInto('pet') - * .values({ - * owner_id: jennifer.id, - * name: 'Catto', - * species: 'cat', - * is_favorite: false, - * }) - * .returningAll() - * .executeTakeFirst() - * }) - * ``` - * - * Setting the isolation level: - * - * ```ts - * import type { Kysely } from 'kysely' - * - * await db - * .transaction() - * .setIsolationLevel('serializable') - * .execute(async (trx) => { - * await doStuff(trx) - * }) - * - * async function doStuff(kysely: typeof db) { - * // ... - * } - * ``` - */ - transaction() { - return new TransactionBuilder({ ...this.#props }); - } - /** - * Creates a {@link ControlledTransactionBuilder} that can be used to run queries inside a controlled transaction. - * - * The returned {@link ControlledTransactionBuilder} can be used to configure the transaction. - * The {@link ControlledTransactionBuilder.execute} method can then be called - * to start the transaction and return a {@link ControlledTransaction}. - * - * A {@link ControlledTransaction} allows you to commit and rollback manually, - * execute savepoint commands. It extends {@link Transaction} which extends {@link Kysely}, - * so you can run queries inside the transaction. Once the transaction is committed, - * or rolled back, it can't be used anymore - all queries will throw an error. - * This is to prevent accidentally running queries outside the transaction - where - * atomicity is not guaranteed anymore. - * - * ### Examples - * - * - * - * A controlled transaction allows you to commit and rollback manually, execute - * savepoint commands, and queries in general. - * - * In this example we start a transaction, use it to insert two rows and then commit - * the transaction. If an error is thrown, we catch it and rollback the transaction. - * - * ```ts - * const trx = await db.startTransaction().execute() - * - * try { - * const jennifer = await trx.insertInto('person') - * .values({ - * first_name: 'Jennifer', - * last_name: 'Aniston', - * age: 40, - * }) - * .returning('id') - * .executeTakeFirstOrThrow() - * - * const catto = await trx.insertInto('pet') - * .values({ - * owner_id: jennifer.id, - * name: 'Catto', - * species: 'cat', - * is_favorite: false, - * }) - * .returningAll() - * .executeTakeFirstOrThrow() - * - * await trx.commit().execute() - * - * // ... - * } catch (error) { - * await trx.rollback().execute() - * } - * ``` - * - * - * - * A controlled transaction allows you to commit and rollback manually, execute - * savepoint commands, and queries in general. - * - * In this example we start a transaction, insert a person, create a savepoint, - * try inserting a toy and a pet, and if an error is thrown, we rollback to the - * savepoint. Eventually we release the savepoint, insert an audit record and - * commit the transaction. If an error is thrown, we catch it and rollback the - * transaction. - * - * ```ts - * const trx = await db.startTransaction().execute() - * - * try { - * const jennifer = await trx - * .insertInto('person') - * .values({ - * first_name: 'Jennifer', - * last_name: 'Aniston', - * age: 40, - * }) - * .returning('id') - * .executeTakeFirstOrThrow() - * - * const trxAfterJennifer = await trx.savepoint('after_jennifer').execute() - * - * try { - * const catto = await trxAfterJennifer - * .insertInto('pet') - * .values({ - * owner_id: jennifer.id, - * name: 'Catto', - * species: 'cat', - * }) - * .returning('id') - * .executeTakeFirstOrThrow() - * - * await trxAfterJennifer - * .insertInto('toy') - * .values({ name: 'Bone', price: 1.99, pet_id: catto.id }) - * .execute() - * } catch (error) { - * await trxAfterJennifer.rollbackToSavepoint('after_jennifer').execute() - * } - * - * await trxAfterJennifer.releaseSavepoint('after_jennifer').execute() - * - * await trx.insertInto('audit').values({ action: 'added Jennifer' }).execute() - * - * await trx.commit().execute() - * } catch (error) { - * await trx.rollback().execute() - * } - * ``` - */ - startTransaction() { - return new ControlledTransactionBuilder({ ...this.#props }); - } - /** - * Provides a kysely instance bound to a single database connection. - * - * ### Examples - * - * ```ts - * await db - * .connection() - * .execute(async (db) => { - * // `db` is an instance of `Kysely` that's bound to a single - * // database connection. All queries executed through `db` use - * // the same connection. - * await doStuff(db) - * }) - * - * async function doStuff(kysely: typeof db) { - * // ... - * } - * ``` - */ - connection() { - return new ConnectionBuilder({ ...this.#props }); - } - /** - * Returns a copy of this Kysely instance with the given plugin installed. - */ - withPlugin(plugin) { - return new _Kysely({ - ...this.#props, - executor: this.#props.executor.withPlugin(plugin) - }); - } - /** - * Returns a copy of this Kysely instance without any plugins. - */ - withoutPlugins() { - return new _Kysely({ - ...this.#props, - executor: this.#props.executor.withoutPlugins() - }); - } - /** - * @override - */ - withSchema(schema2) { - return new _Kysely({ - ...this.#props, - executor: this.#props.executor.withPluginAtFront(new WithSchemaPlugin(schema2)) - }); - } - /** - * Returns a copy of this Kysely instance with tables added to its - * database type. - * - * This method only modifies the types and doesn't affect any of the - * executed queries in any way. - * - * ### Examples - * - * The following example adds and uses a temporary table: - * - * ```ts - * await db.schema - * .createTable('temp_table') - * .temporary() - * .addColumn('some_column', 'integer') - * .execute() - * - * const tempDb = db.withTables<{ - * temp_table: { - * some_column: number - * } - * }>() - * - * await tempDb - * .insertInto('temp_table') - * .values({ some_column: 100 }) - * .execute() - * ``` - */ - withTables() { - return new _Kysely({ ...this.#props }); - } - /** - * Releases all resources and disconnects from the database. - * - * You need to call this when you are done using the `Kysely` instance. - */ - async destroy() { - await this.#props.driver.destroy(); - } - /** - * Returns true if this `Kysely` instance is a transaction. - * - * You can also use `db instanceof Transaction`. - */ - get isTransaction() { - return false; - } - /** - * @internal - * @private - */ - getExecutor() { - return this.#props.executor; - } - /** - * Executes a given compiled query or query builder. - * - * See {@link https://github.com/kysely-org/kysely/blob/master/site/docs/recipes/0004-splitting-query-building-and-execution.md#execute-compiled-queries splitting build, compile and execute code recipe} for more information. - */ - executeQuery(query, queryId) { - if (queryId !== void 0) { - logOnce("Passing `queryId` in `db.executeQuery` is deprecated and will result in a compile-time error in the future."); - } - const compiledQuery = isCompilable(query) ? query.compile() : query; - return this.getExecutor().executeQuery(compiledQuery); - } - async [Symbol.asyncDispose]() { - await this.destroy(); - } - }; - Transaction = class _Transaction extends Kysely { - #props; - constructor(props) { - super(props); - this.#props = props; - } - // The return type is `true` instead of `boolean` to make Kysely - // unassignable to Transaction while allowing assignment the - // other way around. - get isTransaction() { - return true; - } - transaction() { - throw new Error("calling the transaction method for a Transaction is not supported"); - } - connection() { - throw new Error("calling the connection method for a Transaction is not supported"); - } - async destroy() { - throw new Error("calling the destroy method for a Transaction is not supported"); - } - withPlugin(plugin) { - return new _Transaction({ - ...this.#props, - executor: this.#props.executor.withPlugin(plugin) - }); - } - withoutPlugins() { - return new _Transaction({ - ...this.#props, - executor: this.#props.executor.withoutPlugins() - }); - } - withSchema(schema2) { - return new _Transaction({ - ...this.#props, - executor: this.#props.executor.withPluginAtFront(new WithSchemaPlugin(schema2)) - }); - } - withTables() { - return new _Transaction({ ...this.#props }); - } - }; - ConnectionBuilder = class { - #props; - constructor(props) { - this.#props = freeze2(props); - } - async execute(callback) { - return this.#props.executor.provideConnection(async (connection2) => { - const executor = this.#props.executor.withConnectionProvider(new SingleConnectionProvider(connection2)); - const db = new Kysely({ - ...this.#props, - executor - }); - return await callback(db); - }); - } - }; - TransactionBuilder = class _TransactionBuilder { - #props; - constructor(props) { - this.#props = freeze2(props); - } - setAccessMode(accessMode) { - return new _TransactionBuilder({ - ...this.#props, - accessMode - }); - } - setIsolationLevel(isolationLevel) { - return new _TransactionBuilder({ - ...this.#props, - isolationLevel - }); - } - async execute(callback) { - const { isolationLevel, accessMode, ...kyselyProps } = this.#props; - const settings = { isolationLevel, accessMode }; - validateTransactionSettings(settings); - return this.#props.executor.provideConnection(async (connection2) => { - const state2 = { isCommitted: false, isRolledBack: false }; - const executor = new NotCommittedOrRolledBackAssertingExecutor(this.#props.executor.withConnectionProvider(new SingleConnectionProvider(connection2)), state2); - const transaction = new Transaction({ - ...kyselyProps, - executor - }); - let transactionBegun = false; - try { - await this.#props.driver.beginTransaction(connection2, settings); - transactionBegun = true; - const result = await callback(transaction); - await this.#props.driver.commitTransaction(connection2); - state2.isCommitted = true; - return result; - } catch (error50) { - if (transactionBegun) { - await this.#props.driver.rollbackTransaction(connection2); - state2.isRolledBack = true; - } - throw error50; - } - }); - } - }; - ControlledTransactionBuilder = class _ControlledTransactionBuilder { - #props; - constructor(props) { - this.#props = freeze2(props); - } - setAccessMode(accessMode) { - return new _ControlledTransactionBuilder({ - ...this.#props, - accessMode - }); - } - setIsolationLevel(isolationLevel) { - return new _ControlledTransactionBuilder({ - ...this.#props, - isolationLevel - }); - } - async execute() { - const { isolationLevel, accessMode, ...props } = this.#props; - const settings = { isolationLevel, accessMode }; - validateTransactionSettings(settings); - const connection2 = await provideControlledConnection(this.#props.executor); - await this.#props.driver.beginTransaction(connection2.connection, settings); - return new ControlledTransaction({ - ...props, - connection: connection2, - executor: this.#props.executor.withConnectionProvider(new SingleConnectionProvider(connection2.connection)) - }); - } - }; - ControlledTransaction = class _ControlledTransaction extends Transaction { - #props; - #compileQuery; - #state; - constructor(props) { - const state2 = { isCommitted: false, isRolledBack: false }; - props = { - ...props, - executor: new NotCommittedOrRolledBackAssertingExecutor(props.executor, state2) - }; - const { connection: connection2, ...transactionProps } = props; - super(transactionProps); - this.#props = freeze2(props); - this.#state = state2; - const queryId = createQueryId(); - this.#compileQuery = (node) => props.executor.compileQuery(node, queryId); - } - get isCommitted() { - return this.#state.isCommitted; - } - get isRolledBack() { - return this.#state.isRolledBack; - } - /** - * Commits the transaction. - * - * See {@link rollback}. - * - * ### Examples - * - * ```ts - * import type { Kysely } from 'kysely' - * import type { Database } from 'type-editor' // imaginary module - * - * const trx = await db.startTransaction().execute() - * - * try { - * await doSomething(trx) - * - * await trx.commit().execute() - * } catch (error) { - * await trx.rollback().execute() - * } - * - * async function doSomething(kysely: Kysely) {} - * ``` - */ - commit() { - assertNotCommittedOrRolledBack(this.#state); - return new Command(async () => { - await this.#props.driver.commitTransaction(this.#props.connection.connection); - this.#state.isCommitted = true; - this.#props.connection.release(); - }); - } - /** - * Rolls back the transaction. - * - * See {@link commit} and {@link rollbackToSavepoint}. - * - * ### Examples - * - * ```ts - * import type { Kysely } from 'kysely' - * import type { Database } from 'type-editor' // imaginary module - * - * const trx = await db.startTransaction().execute() - * - * try { - * await doSomething(trx) - * - * await trx.commit().execute() - * } catch (error) { - * await trx.rollback().execute() - * } - * - * async function doSomething(kysely: Kysely) {} - * ``` - */ - rollback() { - assertNotCommittedOrRolledBack(this.#state); - return new Command(async () => { - await this.#props.driver.rollbackTransaction(this.#props.connection.connection); - this.#state.isRolledBack = true; - this.#props.connection.release(); - }); - } - /** - * Creates a savepoint with a given name. - * - * See {@link rollbackToSavepoint} and {@link releaseSavepoint}. - * - * For a type-safe experience, you should use the returned instance from now on. - * - * ### Examples - * - * ```ts - * import type { Kysely } from 'kysely' - * import type { Database } from 'type-editor' // imaginary module - * - * const trx = await db.startTransaction().execute() - * - * await insertJennifer(trx) - * - * const trxAfterJennifer = await trx.savepoint('after_jennifer').execute() - * - * try { - * await doSomething(trxAfterJennifer) - * } catch (error) { - * await trxAfterJennifer.rollbackToSavepoint('after_jennifer').execute() - * } - * - * async function insertJennifer(kysely: Kysely) {} - * async function doSomething(kysely: Kysely) {} - * ``` - */ - savepoint(savepointName) { - assertNotCommittedOrRolledBack(this.#state); - return new Command(async () => { - await this.#props.driver.savepoint?.(this.#props.connection.connection, savepointName, this.#compileQuery); - return new _ControlledTransaction({ ...this.#props }); - }); - } - /** - * Rolls back to a savepoint with a given name. - * - * See {@link savepoint} and {@link releaseSavepoint}. - * - * You must use the same instance returned by {@link savepoint}, or - * escape the type-check by using `as any`. - * - * ### Examples - * - * ```ts - * import type { Kysely } from 'kysely' - * import type { Database } from 'type-editor' // imaginary module - * - * const trx = await db.startTransaction().execute() - * - * await insertJennifer(trx) - * - * const trxAfterJennifer = await trx.savepoint('after_jennifer').execute() - * - * try { - * await doSomething(trxAfterJennifer) - * } catch (error) { - * await trxAfterJennifer.rollbackToSavepoint('after_jennifer').execute() - * } - * - * async function insertJennifer(kysely: Kysely) {} - * async function doSomething(kysely: Kysely) {} - * ``` - */ - rollbackToSavepoint(savepointName) { - assertNotCommittedOrRolledBack(this.#state); - return new Command(async () => { - await this.#props.driver.rollbackToSavepoint?.(this.#props.connection.connection, savepointName, this.#compileQuery); - return new _ControlledTransaction({ ...this.#props }); - }); - } - /** - * Releases a savepoint with a given name. - * - * See {@link savepoint} and {@link rollbackToSavepoint}. - * - * You must use the same instance returned by {@link savepoint}, or - * escape the type-check by using `as any`. - * - * ### Examples - * - * ```ts - * import type { Kysely } from 'kysely' - * import type { Database } from 'type-editor' // imaginary module - * - * const trx = await db.startTransaction().execute() - * - * await insertJennifer(trx) - * - * const trxAfterJennifer = await trx.savepoint('after_jennifer').execute() - * - * try { - * await doSomething(trxAfterJennifer) - * } catch (error) { - * await trxAfterJennifer.rollbackToSavepoint('after_jennifer').execute() - * } - * - * await trxAfterJennifer.releaseSavepoint('after_jennifer').execute() - * - * await doSomethingElse(trx) - * - * async function insertJennifer(kysely: Kysely) {} - * async function doSomething(kysely: Kysely) {} - * async function doSomethingElse(kysely: Kysely) {} - * ``` - */ - releaseSavepoint(savepointName) { - assertNotCommittedOrRolledBack(this.#state); - return new Command(async () => { - await this.#props.driver.releaseSavepoint?.(this.#props.connection.connection, savepointName, this.#compileQuery); - return new _ControlledTransaction({ ...this.#props }); - }); - } - withPlugin(plugin) { - return new _ControlledTransaction({ - ...this.#props, - executor: this.#props.executor.withPlugin(plugin) - }); - } - withoutPlugins() { - return new _ControlledTransaction({ - ...this.#props, - executor: this.#props.executor.withoutPlugins() - }); - } - withSchema(schema2) { - return new _ControlledTransaction({ - ...this.#props, - executor: this.#props.executor.withPluginAtFront(new WithSchemaPlugin(schema2)) - }); - } - withTables() { - return new _ControlledTransaction({ ...this.#props }); - } - }; - Command = class { - #cb; - constructor(cb) { - this.#cb = cb; - } - /** - * Executes the command. - */ - async execute() { - return await this.#cb(); - } - }; - NotCommittedOrRolledBackAssertingExecutor = class _NotCommittedOrRolledBackAssertingExecutor { - #executor; - #state; - constructor(executor, state2) { - if (executor instanceof _NotCommittedOrRolledBackAssertingExecutor) { - this.#executor = executor.#executor; - } else { - this.#executor = executor; - } - this.#state = state2; - } - get adapter() { - return this.#executor.adapter; - } - get plugins() { - return this.#executor.plugins; - } - transformQuery(node, queryId) { - return this.#executor.transformQuery(node, queryId); - } - compileQuery(node, queryId) { - return this.#executor.compileQuery(node, queryId); - } - provideConnection(consumer) { - return this.#executor.provideConnection(consumer); - } - executeQuery(compiledQuery) { - assertNotCommittedOrRolledBack(this.#state); - return this.#executor.executeQuery(compiledQuery); - } - stream(compiledQuery, chunkSize) { - assertNotCommittedOrRolledBack(this.#state); - return this.#executor.stream(compiledQuery, chunkSize); - } - withConnectionProvider(connectionProvider) { - return new _NotCommittedOrRolledBackAssertingExecutor(this.#executor.withConnectionProvider(connectionProvider), this.#state); - } - withPlugin(plugin) { - return new _NotCommittedOrRolledBackAssertingExecutor(this.#executor.withPlugin(plugin), this.#state); - } - withPlugins(plugins2) { - return new _NotCommittedOrRolledBackAssertingExecutor(this.#executor.withPlugins(plugins2), this.#state); - } - withPluginAtFront(plugin) { - return new _NotCommittedOrRolledBackAssertingExecutor(this.#executor.withPluginAtFront(plugin), this.#state); - } - withoutPlugins() { - return new _NotCommittedOrRolledBackAssertingExecutor(this.#executor.withoutPlugins(), this.#state); - } - }; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/where-interface.js -var init_where_interface = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/where-interface.js"() { - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/returning-interface.js -var init_returning_interface = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/returning-interface.js"() { - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/output-interface.js -var init_output_interface = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/output-interface.js"() { - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/having-interface.js -var init_having_interface = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/having-interface.js"() { - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/order-by-interface.js -var init_order_by_interface = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/order-by-interface.js"() { - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/raw-builder/raw-builder.js -function createRawBuilder(props) { - return new RawBuilderImpl(props); -} -var RawBuilderImpl, AliasedRawBuilderImpl; -var init_raw_builder = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/raw-builder/raw-builder.js"() { - init_alias_node(); - init_object_utils(); - init_noop_query_executor(); - init_identifier_node(); - init_operation_node_source(); - RawBuilderImpl = class _RawBuilderImpl { - #props; - constructor(props) { - this.#props = freeze2(props); - } - get expressionType() { - return void 0; - } - get isRawBuilder() { - return true; - } - as(alias) { - return new AliasedRawBuilderImpl(this, alias); - } - $castTo() { - return new _RawBuilderImpl({ ...this.#props }); - } - $notNull() { - return new _RawBuilderImpl(this.#props); - } - withPlugin(plugin) { - return new _RawBuilderImpl({ - ...this.#props, - plugins: this.#props.plugins !== void 0 ? freeze2([...this.#props.plugins, plugin]) : freeze2([plugin]) - }); - } - toOperationNode() { - return this.#toOperationNode(this.#getExecutor()); - } - compile(executorProvider) { - return this.#compile(this.#getExecutor(executorProvider)); - } - async execute(executorProvider) { - const executor = this.#getExecutor(executorProvider); - return executor.executeQuery(this.#compile(executor)); - } - #getExecutor(executorProvider) { - const executor = executorProvider !== void 0 ? executorProvider.getExecutor() : NOOP_QUERY_EXECUTOR; - return this.#props.plugins !== void 0 ? executor.withPlugins(this.#props.plugins) : executor; - } - #toOperationNode(executor) { - return executor.transformQuery(this.#props.rawNode, this.#props.queryId); - } - #compile(executor) { - return executor.compileQuery(this.#toOperationNode(executor), this.#props.queryId); - } - }; - AliasedRawBuilderImpl = class { - #rawBuilder; - #alias; - constructor(rawBuilder, alias) { - this.#rawBuilder = rawBuilder; - this.#alias = alias; - } - get expression() { - return this.#rawBuilder; - } - get alias() { - return this.#alias; - } - get rawBuilder() { - return this.#rawBuilder; - } - toOperationNode() { - return AliasNode.create(this.#rawBuilder.toOperationNode(), isOperationNodeSource(this.#alias) ? this.#alias.toOperationNode() : IdentifierNode.create(this.#alias)); - } - }; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/raw-builder/sql.js -function parseParameter(param) { - if (isOperationNodeSource(param)) { - return param.toOperationNode(); - } - return parseValueExpression(param); -} -var sql2; -var init_sql3 = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/raw-builder/sql.js"() { - init_identifier_node(); - init_operation_node_source(); - init_raw_node(); - init_value_node(); - init_reference_parser(); - init_table_parser(); - init_value_parser(); - init_query_id(); - init_raw_builder(); - sql2 = Object.assign((sqlFragments, ...parameters) => { - return createRawBuilder({ - queryId: createQueryId(), - rawNode: RawNode.create(sqlFragments, parameters?.map(parseParameter) ?? []) - }); - }, { - ref(columnReference) { - return createRawBuilder({ - queryId: createQueryId(), - rawNode: RawNode.createWithChild(parseStringReference(columnReference)) - }); - }, - val(value) { - return createRawBuilder({ - queryId: createQueryId(), - rawNode: RawNode.createWithChild(parseValueExpression(value)) - }); - }, - value(value) { - return this.val(value); - }, - table(tableReference) { - return createRawBuilder({ - queryId: createQueryId(), - rawNode: RawNode.createWithChild(parseTable(tableReference)) - }); - }, - id(...ids) { - const fragments = new Array(ids.length + 1).fill("."); - fragments[0] = ""; - fragments[fragments.length - 1] = ""; - return createRawBuilder({ - queryId: createQueryId(), - rawNode: RawNode.create(fragments, ids.map(IdentifierNode.create)) - }); - }, - lit(value) { - return createRawBuilder({ - queryId: createQueryId(), - rawNode: RawNode.createWithChild(ValueNode.createImmediate(value)) - }); - }, - literal(value) { - return this.lit(value); - }, - raw(sql3) { - return createRawBuilder({ - queryId: createQueryId(), - rawNode: RawNode.createWithSql(sql3) - }); - }, - join(array2, separator = sql2`, `) { - const nodes = new Array(Math.max(2 * array2.length - 1, 0)); - const sep = separator.toOperationNode(); - for (let i5 = 0; i5 < array2.length; ++i5) { - nodes[2 * i5] = parseParameter(array2[i5]); - if (i5 !== array2.length - 1) { - nodes[2 * i5 + 1] = sep; - } - } - return createRawBuilder({ - queryId: createQueryId(), - rawNode: RawNode.createWithChildren(nodes) - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-executor/query-executor.js -var init_query_executor = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-executor/query-executor.js"() { - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-executor/query-executor-provider.js -var init_query_executor_provider = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-executor/query-executor-provider.js"() { - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/operation-node-visitor.js -var OperationNodeVisitor; -var init_operation_node_visitor = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/operation-node-visitor.js"() { - init_object_utils(); - OperationNodeVisitor = class { - nodeStack = []; - get parentNode() { - return this.nodeStack[this.nodeStack.length - 2]; - } - #visitors = freeze2({ - AliasNode: this.visitAlias.bind(this), - ColumnNode: this.visitColumn.bind(this), - IdentifierNode: this.visitIdentifier.bind(this), - SchemableIdentifierNode: this.visitSchemableIdentifier.bind(this), - RawNode: this.visitRaw.bind(this), - ReferenceNode: this.visitReference.bind(this), - SelectQueryNode: this.visitSelectQuery.bind(this), - SelectionNode: this.visitSelection.bind(this), - TableNode: this.visitTable.bind(this), - FromNode: this.visitFrom.bind(this), - SelectAllNode: this.visitSelectAll.bind(this), - AndNode: this.visitAnd.bind(this), - OrNode: this.visitOr.bind(this), - ValueNode: this.visitValue.bind(this), - ValueListNode: this.visitValueList.bind(this), - PrimitiveValueListNode: this.visitPrimitiveValueList.bind(this), - ParensNode: this.visitParens.bind(this), - JoinNode: this.visitJoin.bind(this), - OperatorNode: this.visitOperator.bind(this), - WhereNode: this.visitWhere.bind(this), - InsertQueryNode: this.visitInsertQuery.bind(this), - DeleteQueryNode: this.visitDeleteQuery.bind(this), - ReturningNode: this.visitReturning.bind(this), - CreateTableNode: this.visitCreateTable.bind(this), - AddColumnNode: this.visitAddColumn.bind(this), - ColumnDefinitionNode: this.visitColumnDefinition.bind(this), - DropTableNode: this.visitDropTable.bind(this), - DataTypeNode: this.visitDataType.bind(this), - OrderByNode: this.visitOrderBy.bind(this), - OrderByItemNode: this.visitOrderByItem.bind(this), - GroupByNode: this.visitGroupBy.bind(this), - GroupByItemNode: this.visitGroupByItem.bind(this), - UpdateQueryNode: this.visitUpdateQuery.bind(this), - ColumnUpdateNode: this.visitColumnUpdate.bind(this), - LimitNode: this.visitLimit.bind(this), - OffsetNode: this.visitOffset.bind(this), - OnConflictNode: this.visitOnConflict.bind(this), - OnDuplicateKeyNode: this.visitOnDuplicateKey.bind(this), - CreateIndexNode: this.visitCreateIndex.bind(this), - DropIndexNode: this.visitDropIndex.bind(this), - ListNode: this.visitList.bind(this), - PrimaryKeyConstraintNode: this.visitPrimaryKeyConstraint.bind(this), - UniqueConstraintNode: this.visitUniqueConstraint.bind(this), - ReferencesNode: this.visitReferences.bind(this), - CheckConstraintNode: this.visitCheckConstraint.bind(this), - WithNode: this.visitWith.bind(this), - CommonTableExpressionNode: this.visitCommonTableExpression.bind(this), - CommonTableExpressionNameNode: this.visitCommonTableExpressionName.bind(this), - HavingNode: this.visitHaving.bind(this), - CreateSchemaNode: this.visitCreateSchema.bind(this), - DropSchemaNode: this.visitDropSchema.bind(this), - AlterTableNode: this.visitAlterTable.bind(this), - DropColumnNode: this.visitDropColumn.bind(this), - RenameColumnNode: this.visitRenameColumn.bind(this), - AlterColumnNode: this.visitAlterColumn.bind(this), - ModifyColumnNode: this.visitModifyColumn.bind(this), - AddConstraintNode: this.visitAddConstraint.bind(this), - DropConstraintNode: this.visitDropConstraint.bind(this), - RenameConstraintNode: this.visitRenameConstraint.bind(this), - ForeignKeyConstraintNode: this.visitForeignKeyConstraint.bind(this), - CreateViewNode: this.visitCreateView.bind(this), - RefreshMaterializedViewNode: this.visitRefreshMaterializedView.bind(this), - DropViewNode: this.visitDropView.bind(this), - GeneratedNode: this.visitGenerated.bind(this), - DefaultValueNode: this.visitDefaultValue.bind(this), - OnNode: this.visitOn.bind(this), - ValuesNode: this.visitValues.bind(this), - SelectModifierNode: this.visitSelectModifier.bind(this), - CreateTypeNode: this.visitCreateType.bind(this), - DropTypeNode: this.visitDropType.bind(this), - ExplainNode: this.visitExplain.bind(this), - DefaultInsertValueNode: this.visitDefaultInsertValue.bind(this), - AggregateFunctionNode: this.visitAggregateFunction.bind(this), - OverNode: this.visitOver.bind(this), - PartitionByNode: this.visitPartitionBy.bind(this), - PartitionByItemNode: this.visitPartitionByItem.bind(this), - SetOperationNode: this.visitSetOperation.bind(this), - BinaryOperationNode: this.visitBinaryOperation.bind(this), - UnaryOperationNode: this.visitUnaryOperation.bind(this), - UsingNode: this.visitUsing.bind(this), - FunctionNode: this.visitFunction.bind(this), - CaseNode: this.visitCase.bind(this), - WhenNode: this.visitWhen.bind(this), - JSONReferenceNode: this.visitJSONReference.bind(this), - JSONPathNode: this.visitJSONPath.bind(this), - JSONPathLegNode: this.visitJSONPathLeg.bind(this), - JSONOperatorChainNode: this.visitJSONOperatorChain.bind(this), - TupleNode: this.visitTuple.bind(this), - MergeQueryNode: this.visitMergeQuery.bind(this), - MatchedNode: this.visitMatched.bind(this), - AddIndexNode: this.visitAddIndex.bind(this), - CastNode: this.visitCast.bind(this), - FetchNode: this.visitFetch.bind(this), - TopNode: this.visitTop.bind(this), - OutputNode: this.visitOutput.bind(this), - OrActionNode: this.visitOrAction.bind(this), - CollateNode: this.visitCollate.bind(this) - }); - visitNode = (node) => { - this.nodeStack.push(node); - this.#visitors[node.kind](node); - this.nodeStack.pop(); - }; - }; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-compiler/default-query-compiler.js -var LIT_WRAP_REGEX, DefaultQueryCompiler, SELECT_MODIFIER_SQL, SELECT_MODIFIER_PRIORITY, JOIN_TYPE_SQL; -var init_default_query_compiler = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-compiler/default-query-compiler.js"() { - init_create_table_node(); - init_insert_query_node(); - init_operation_node_visitor(); - init_operator_node(); - init_parens_node(); - init_raw_node(); - init_object_utils(); - init_create_view_node(); - init_set_operation_node(); - init_when_node(); - init_log_once(); - LIT_WRAP_REGEX = /'/g; - DefaultQueryCompiler = class extends OperationNodeVisitor { - #sql = ""; - #parameters = []; - get numParameters() { - return this.#parameters.length; - } - compileQuery(node, queryId) { - this.#sql = ""; - this.#parameters = []; - this.nodeStack.splice(0, this.nodeStack.length); - this.visitNode(node); - return freeze2({ - query: node, - queryId, - sql: this.getSql(), - parameters: [...this.#parameters] - }); - } - getSql() { - return this.#sql; - } - visitSelectQuery(node) { - const wrapInParens = this.parentNode !== void 0 && !ParensNode.is(this.parentNode) && !InsertQueryNode.is(this.parentNode) && !CreateTableNode.is(this.parentNode) && !CreateViewNode.is(this.parentNode) && !SetOperationNode.is(this.parentNode); - if (this.parentNode === void 0 && node.explain) { - this.visitNode(node.explain); - this.append(" "); - } - if (wrapInParens) { - this.append("("); - } - if (node.with) { - this.visitNode(node.with); - this.append(" "); - } - this.append("select"); - if (node.distinctOn) { - this.append(" "); - this.compileDistinctOn(node.distinctOn); - } - if (node.frontModifiers?.length) { - this.append(" "); - this.compileList(node.frontModifiers, " "); - } - if (node.top) { - this.append(" "); - this.visitNode(node.top); - } - if (node.selections) { - this.append(" "); - this.compileList(node.selections); - } - if (node.from) { - this.append(" "); - this.visitNode(node.from); - } - if (node.joins) { - this.append(" "); - this.compileList(node.joins, " "); - } - if (node.where) { - this.append(" "); - this.visitNode(node.where); - } - if (node.groupBy) { - this.append(" "); - this.visitNode(node.groupBy); - } - if (node.having) { - this.append(" "); - this.visitNode(node.having); - } - if (node.setOperations) { - this.append(" "); - this.compileList(node.setOperations, " "); - } - if (node.orderBy) { - this.append(" "); - this.visitNode(node.orderBy); - } - if (node.limit) { - this.append(" "); - this.visitNode(node.limit); - } - if (node.offset) { - this.append(" "); - this.visitNode(node.offset); - } - if (node.fetch) { - this.append(" "); - this.visitNode(node.fetch); - } - if (node.endModifiers?.length) { - this.append(" "); - this.compileList(this.sortSelectModifiers([...node.endModifiers]), " "); - } - if (wrapInParens) { - this.append(")"); - } - } - visitFrom(node) { - this.append("from "); - this.compileList(node.froms); - } - visitSelection(node) { - this.visitNode(node.selection); - } - visitColumn(node) { - this.visitNode(node.column); - } - compileDistinctOn(expressions) { - this.append("distinct on ("); - this.compileList(expressions); - this.append(")"); - } - compileList(nodes, separator = ", ") { - const lastIndex = nodes.length - 1; - for (let i5 = 0; i5 <= lastIndex; i5++) { - this.visitNode(nodes[i5]); - if (i5 < lastIndex) { - this.append(separator); - } - } - } - visitWhere(node) { - this.append("where "); - this.visitNode(node.where); - } - visitHaving(node) { - this.append("having "); - this.visitNode(node.having); - } - visitInsertQuery(node) { - const wrapInParens = this.parentNode !== void 0 && !ParensNode.is(this.parentNode) && !RawNode.is(this.parentNode) && !WhenNode.is(this.parentNode); - if (this.parentNode === void 0 && node.explain) { - this.visitNode(node.explain); - this.append(" "); - } - if (wrapInParens) { - this.append("("); - } - if (node.with) { - this.visitNode(node.with); - this.append(" "); - } - this.append(node.replace ? "replace" : "insert"); - if (node.ignore) { - logOnce("`InsertQueryNode.ignore` is deprecated. Use `InsertQueryNode.orAction` instead."); - this.append(" ignore"); - } - if (node.orAction) { - this.append(" "); - this.visitNode(node.orAction); - } - if (node.top) { - this.append(" "); - this.visitNode(node.top); - } - if (node.into) { - this.append(" into "); - this.visitNode(node.into); - } - if (node.columns) { - this.append(" ("); - this.compileList(node.columns); - this.append(")"); - } - if (node.output) { - this.append(" "); - this.visitNode(node.output); - } - if (node.values) { - this.append(" "); - this.visitNode(node.values); - } - if (node.defaultValues) { - this.append(" "); - this.append("default values"); - } - if (node.onConflict) { - this.append(" "); - this.visitNode(node.onConflict); - } - if (node.onDuplicateKey) { - this.append(" "); - this.visitNode(node.onDuplicateKey); - } - if (node.returning) { - this.append(" "); - this.visitNode(node.returning); - } - if (wrapInParens) { - this.append(")"); - } - if (node.endModifiers?.length) { - this.append(" "); - this.compileList(node.endModifiers, " "); - } - } - visitValues(node) { - this.append("values "); - this.compileList(node.values); - } - visitDeleteQuery(node) { - const wrapInParens = this.parentNode !== void 0 && !ParensNode.is(this.parentNode) && !RawNode.is(this.parentNode); - if (this.parentNode === void 0 && node.explain) { - this.visitNode(node.explain); - this.append(" "); - } - if (wrapInParens) { - this.append("("); - } - if (node.with) { - this.visitNode(node.with); - this.append(" "); - } - this.append("delete "); - if (node.top) { - this.visitNode(node.top); - this.append(" "); - } - this.visitNode(node.from); - if (node.output) { - this.append(" "); - this.visitNode(node.output); - } - if (node.using) { - this.append(" "); - this.visitNode(node.using); - } - if (node.joins) { - this.append(" "); - this.compileList(node.joins, " "); - } - if (node.where) { - this.append(" "); - this.visitNode(node.where); - } - if (node.orderBy) { - this.append(" "); - this.visitNode(node.orderBy); - } - if (node.limit) { - this.append(" "); - this.visitNode(node.limit); - } - if (node.returning) { - this.append(" "); - this.visitNode(node.returning); - } - if (wrapInParens) { - this.append(")"); - } - if (node.endModifiers?.length) { - this.append(" "); - this.compileList(node.endModifiers, " "); - } - } - visitReturning(node) { - this.append("returning "); - this.compileList(node.selections); - } - visitAlias(node) { - this.visitNode(node.node); - this.append(" as "); - this.visitNode(node.alias); - } - visitReference(node) { - if (node.table) { - this.visitNode(node.table); - this.append("."); - } - this.visitNode(node.column); - } - visitSelectAll(_) { - this.append("*"); - } - visitIdentifier(node) { - this.append(this.getLeftIdentifierWrapper()); - this.compileUnwrappedIdentifier(node); - this.append(this.getRightIdentifierWrapper()); - } - compileUnwrappedIdentifier(node) { - if (!isString(node.name)) { - throw new Error("a non-string identifier was passed to compileUnwrappedIdentifier."); - } - this.append(this.sanitizeIdentifier(node.name)); - } - visitAnd(node) { - this.visitNode(node.left); - this.append(" and "); - this.visitNode(node.right); - } - visitOr(node) { - this.visitNode(node.left); - this.append(" or "); - this.visitNode(node.right); - } - visitValue(node) { - if (node.immediate) { - this.appendImmediateValue(node.value); - } else { - this.appendValue(node.value); - } - } - visitValueList(node) { - this.append("("); - this.compileList(node.values); - this.append(")"); - } - visitTuple(node) { - this.append("("); - this.compileList(node.values); - this.append(")"); - } - visitPrimitiveValueList(node) { - this.append("("); - const { values: values2 } = node; - for (let i5 = 0; i5 < values2.length; ++i5) { - this.appendValue(values2[i5]); - if (i5 !== values2.length - 1) { - this.append(", "); - } - } - this.append(")"); - } - visitParens(node) { - this.append("("); - this.visitNode(node.node); - this.append(")"); - } - visitJoin(node) { - this.append(JOIN_TYPE_SQL[node.joinType]); - this.append(" "); - this.visitNode(node.table); - if (node.on) { - this.append(" "); - this.visitNode(node.on); - } - } - visitOn(node) { - this.append("on "); - this.visitNode(node.on); - } - visitRaw(node) { - const { sqlFragments, parameters: params } = node; - for (let i5 = 0; i5 < sqlFragments.length; ++i5) { - this.append(sqlFragments[i5]); - if (params.length > i5) { - this.visitNode(params[i5]); - } - } - } - visitOperator(node) { - this.append(node.operator); - } - visitTable(node) { - this.visitNode(node.table); - } - visitSchemableIdentifier(node) { - if (node.schema) { - this.visitNode(node.schema); - this.append("."); - } - this.visitNode(node.identifier); - } - visitCreateTable(node) { - this.append("create "); - if (node.frontModifiers?.length) { - this.compileList(node.frontModifiers, " "); - this.append(" "); - } - if (node.temporary) { - this.append("temporary "); - } - this.append("table "); - if (node.ifNotExists) { - this.append("if not exists "); - } - this.visitNode(node.table); - if (!node.selectQuery) { - this.append(" ("); - this.compileList([...node.columns, ...node.constraints ?? []]); - this.append(")"); - } - if (node.onCommit) { - this.append(" on commit "); - this.append(node.onCommit); - } - if (node.endModifiers?.length) { - this.append(" "); - this.compileList(node.endModifiers, " "); - } - if (node.selectQuery) { - this.append(" as "); - this.visitNode(node.selectQuery); - } - } - visitColumnDefinition(node) { - if (node.ifNotExists) { - this.append("if not exists "); - } - this.visitNode(node.column); - this.append(" "); - this.visitNode(node.dataType); - if (node.unsigned) { - this.append(" unsigned"); - } - if (node.frontModifiers && node.frontModifiers.length > 0) { - this.append(" "); - this.compileList(node.frontModifiers, " "); - } - if (node.generated) { - this.append(" "); - this.visitNode(node.generated); - } - if (node.identity) { - this.append(" identity"); - } - if (node.defaultTo) { - this.append(" "); - this.visitNode(node.defaultTo); - } - if (node.notNull) { - this.append(" not null"); - } - if (node.unique) { - this.append(" unique"); - } - if (node.nullsNotDistinct) { - this.append(" nulls not distinct"); - } - if (node.primaryKey) { - this.append(" primary key"); - } - if (node.autoIncrement) { - this.append(" "); - this.append(this.getAutoIncrement()); - } - if (node.references) { - this.append(" "); - this.visitNode(node.references); - } - if (node.check) { - this.append(" "); - this.visitNode(node.check); - } - if (node.endModifiers && node.endModifiers.length > 0) { - this.append(" "); - this.compileList(node.endModifiers, " "); - } - } - getAutoIncrement() { - return "auto_increment"; - } - visitReferences(node) { - this.append("references "); - this.visitNode(node.table); - this.append(" ("); - this.compileList(node.columns); - this.append(")"); - if (node.onDelete) { - this.append(" on delete "); - this.append(node.onDelete); - } - if (node.onUpdate) { - this.append(" on update "); - this.append(node.onUpdate); - } - } - visitDropTable(node) { - this.append("drop table "); - if (node.ifExists) { - this.append("if exists "); - } - this.visitNode(node.table); - if (node.cascade) { - this.append(" cascade"); - } - } - visitDataType(node) { - this.append(node.dataType); - } - visitOrderBy(node) { - this.append("order by "); - this.compileList(node.items); - } - visitOrderByItem(node) { - this.visitNode(node.orderBy); - if (node.collation) { - this.append(" "); - this.visitNode(node.collation); - } - if (node.direction) { - this.append(" "); - this.visitNode(node.direction); - } - if (node.nulls) { - this.append(" nulls "); - this.append(node.nulls); - } - } - visitGroupBy(node) { - this.append("group by "); - this.compileList(node.items); - } - visitGroupByItem(node) { - this.visitNode(node.groupBy); - } - visitUpdateQuery(node) { - const wrapInParens = this.parentNode !== void 0 && !ParensNode.is(this.parentNode) && !RawNode.is(this.parentNode) && !WhenNode.is(this.parentNode); - if (this.parentNode === void 0 && node.explain) { - this.visitNode(node.explain); - this.append(" "); - } - if (wrapInParens) { - this.append("("); - } - if (node.with) { - this.visitNode(node.with); - this.append(" "); - } - this.append("update "); - if (node.top) { - this.visitNode(node.top); - this.append(" "); - } - if (node.table) { - this.visitNode(node.table); - this.append(" "); - } - this.append("set "); - if (node.updates) { - this.compileList(node.updates); - } - if (node.output) { - this.append(" "); - this.visitNode(node.output); - } - if (node.from) { - this.append(" "); - this.visitNode(node.from); - } - if (node.joins) { - if (!node.from) { - throw new Error("Joins in an update query are only supported as a part of a PostgreSQL 'update set from join' query. If you want to create a MySQL 'update join set' query, see https://kysely.dev/docs/examples/update/my-sql-joins"); - } - this.append(" "); - this.compileList(node.joins, " "); - } - if (node.where) { - this.append(" "); - this.visitNode(node.where); - } - if (node.returning) { - this.append(" "); - this.visitNode(node.returning); - } - if (node.orderBy) { - this.append(" "); - this.visitNode(node.orderBy); - } - if (node.limit) { - this.append(" "); - this.visitNode(node.limit); - } - if (wrapInParens) { - this.append(")"); - } - if (node.endModifiers?.length) { - this.append(" "); - this.compileList(node.endModifiers, " "); - } - } - visitColumnUpdate(node) { - this.visitNode(node.column); - this.append(" = "); - this.visitNode(node.value); - } - visitLimit(node) { - this.append("limit "); - this.visitNode(node.limit); - } - visitOffset(node) { - this.append("offset "); - this.visitNode(node.offset); - } - visitOnConflict(node) { - this.append("on conflict"); - if (node.columns) { - this.append(" ("); - this.compileList(node.columns); - this.append(")"); - } else if (node.constraint) { - this.append(" on constraint "); - this.visitNode(node.constraint); - } else if (node.indexExpression) { - this.append(" ("); - this.visitNode(node.indexExpression); - this.append(")"); - } - if (node.indexWhere) { - this.append(" "); - this.visitNode(node.indexWhere); - } - if (node.doNothing === true) { - this.append(" do nothing"); - } else if (node.updates) { - this.append(" do update set "); - this.compileList(node.updates); - if (node.updateWhere) { - this.append(" "); - this.visitNode(node.updateWhere); - } - } - } - visitOnDuplicateKey(node) { - this.append("on duplicate key update "); - this.compileList(node.updates); - } - visitCreateIndex(node) { - this.append("create "); - if (node.unique) { - this.append("unique "); - } - this.append("index "); - if (node.ifNotExists) { - this.append("if not exists "); - } - this.visitNode(node.name); - if (node.table) { - this.append(" on "); - this.visitNode(node.table); - } - if (node.using) { - this.append(" using "); - this.visitNode(node.using); - } - if (node.columns) { - this.append(" ("); - this.compileList(node.columns); - this.append(")"); - } - if (node.nullsNotDistinct) { - this.append(" nulls not distinct"); - } - if (node.where) { - this.append(" "); - this.visitNode(node.where); - } - } - visitDropIndex(node) { - this.append("drop index "); - if (node.ifExists) { - this.append("if exists "); - } - this.visitNode(node.name); - if (node.table) { - this.append(" on "); - this.visitNode(node.table); - } - if (node.cascade) { - this.append(" cascade"); - } - } - visitCreateSchema(node) { - this.append("create schema "); - if (node.ifNotExists) { - this.append("if not exists "); - } - this.visitNode(node.schema); - } - visitDropSchema(node) { - this.append("drop schema "); - if (node.ifExists) { - this.append("if exists "); - } - this.visitNode(node.schema); - if (node.cascade) { - this.append(" cascade"); - } - } - visitPrimaryKeyConstraint(node) { - if (node.name) { - this.append("constraint "); - this.visitNode(node.name); - this.append(" "); - } - this.append("primary key ("); - this.compileList(node.columns); - this.append(")"); - this.buildDeferrable(node); - } - buildDeferrable(node) { - if (node.deferrable !== void 0) { - if (node.deferrable) { - this.append(" deferrable"); - } else { - this.append(" not deferrable"); - } - } - if (node.initiallyDeferred !== void 0) { - if (node.initiallyDeferred) { - this.append(" initially deferred"); - } else { - this.append(" initially immediate"); - } - } - } - visitUniqueConstraint(node) { - if (node.name) { - this.append("constraint "); - this.visitNode(node.name); - this.append(" "); - } - this.append("unique"); - if (node.nullsNotDistinct) { - this.append(" nulls not distinct"); - } - this.append(" ("); - this.compileList(node.columns); - this.append(")"); - this.buildDeferrable(node); - } - visitCheckConstraint(node) { - if (node.name) { - this.append("constraint "); - this.visitNode(node.name); - this.append(" "); - } - this.append("check ("); - this.visitNode(node.expression); - this.append(")"); - } - visitForeignKeyConstraint(node) { - if (node.name) { - this.append("constraint "); - this.visitNode(node.name); - this.append(" "); - } - this.append("foreign key ("); - this.compileList(node.columns); - this.append(") "); - this.visitNode(node.references); - if (node.onDelete) { - this.append(" on delete "); - this.append(node.onDelete); - } - if (node.onUpdate) { - this.append(" on update "); - this.append(node.onUpdate); - } - this.buildDeferrable(node); - } - visitList(node) { - this.compileList(node.items); - } - visitWith(node) { - this.append("with "); - if (node.recursive) { - this.append("recursive "); - } - this.compileList(node.expressions); - } - visitCommonTableExpression(node) { - this.visitNode(node.name); - this.append(" as "); - if (isBoolean(node.materialized)) { - if (!node.materialized) { - this.append("not "); - } - this.append("materialized "); - } - this.visitNode(node.expression); - } - visitCommonTableExpressionName(node) { - this.visitNode(node.table); - if (node.columns) { - this.append("("); - this.compileList(node.columns); - this.append(")"); - } - } - visitAlterTable(node) { - this.append("alter table "); - this.visitNode(node.table); - this.append(" "); - if (node.renameTo) { - this.append("rename to "); - this.visitNode(node.renameTo); - } - if (node.setSchema) { - this.append("set schema "); - this.visitNode(node.setSchema); - } - if (node.addConstraint) { - this.visitNode(node.addConstraint); - } - if (node.dropConstraint) { - this.visitNode(node.dropConstraint); - } - if (node.renameConstraint) { - this.visitNode(node.renameConstraint); - } - if (node.columnAlterations) { - this.compileColumnAlterations(node.columnAlterations); - } - if (node.addIndex) { - this.visitNode(node.addIndex); - } - if (node.dropIndex) { - this.visitNode(node.dropIndex); - } - } - visitAddColumn(node) { - this.append("add column "); - this.visitNode(node.column); - } - visitRenameColumn(node) { - this.append("rename column "); - this.visitNode(node.column); - this.append(" to "); - this.visitNode(node.renameTo); - } - visitDropColumn(node) { - this.append("drop column "); - this.visitNode(node.column); - } - visitAlterColumn(node) { - this.append("alter column "); - this.visitNode(node.column); - this.append(" "); - if (node.dataType) { - if (this.announcesNewColumnDataType()) { - this.append("type "); - } - this.visitNode(node.dataType); - if (node.dataTypeExpression) { - this.append("using "); - this.visitNode(node.dataTypeExpression); - } - } - if (node.setDefault) { - this.append("set default "); - this.visitNode(node.setDefault); - } - if (node.dropDefault) { - this.append("drop default"); - } - if (node.setNotNull) { - this.append("set not null"); - } - if (node.dropNotNull) { - this.append("drop not null"); - } - } - visitModifyColumn(node) { - this.append("modify column "); - this.visitNode(node.column); - } - visitAddConstraint(node) { - this.append("add "); - this.visitNode(node.constraint); - } - visitDropConstraint(node) { - this.append("drop constraint "); - if (node.ifExists) { - this.append("if exists "); - } - this.visitNode(node.constraintName); - if (node.modifier === "cascade") { - this.append(" cascade"); - } else if (node.modifier === "restrict") { - this.append(" restrict"); - } - } - visitRenameConstraint(node) { - this.append("rename constraint "); - this.visitNode(node.oldName); - this.append(" to "); - this.visitNode(node.newName); - } - visitSetOperation(node) { - this.append(node.operator); - this.append(" "); - if (node.all) { - this.append("all "); - } - this.visitNode(node.expression); - } - visitCreateView(node) { - this.append("create "); - if (node.orReplace) { - this.append("or replace "); - } - if (node.materialized) { - this.append("materialized "); - } - if (node.temporary) { - this.append("temporary "); - } - this.append("view "); - if (node.ifNotExists) { - this.append("if not exists "); - } - this.visitNode(node.name); - this.append(" "); - if (node.columns) { - this.append("("); - this.compileList(node.columns); - this.append(") "); - } - if (node.as) { - this.append("as "); - this.visitNode(node.as); - } - } - visitRefreshMaterializedView(node) { - this.append("refresh materialized view "); - if (node.concurrently) { - this.append("concurrently "); - } - this.visitNode(node.name); - if (node.withNoData) { - this.append(" with no data"); - } else { - this.append(" with data"); - } - } - visitDropView(node) { - this.append("drop "); - if (node.materialized) { - this.append("materialized "); - } - this.append("view "); - if (node.ifExists) { - this.append("if exists "); - } - this.visitNode(node.name); - if (node.cascade) { - this.append(" cascade"); - } - } - visitGenerated(node) { - this.append("generated "); - if (node.always) { - this.append("always "); - } - if (node.byDefault) { - this.append("by default "); - } - this.append("as "); - if (node.identity) { - this.append("identity"); - } - if (node.expression) { - this.append("("); - this.visitNode(node.expression); - this.append(")"); - } - if (node.stored) { - this.append(" stored"); - } - } - visitDefaultValue(node) { - this.append("default "); - this.visitNode(node.defaultValue); - } - visitSelectModifier(node) { - if (node.rawModifier) { - this.visitNode(node.rawModifier); - } else { - this.append(SELECT_MODIFIER_SQL[node.modifier]); - } - if (node.of) { - this.append(" of "); - this.compileList(node.of, ", "); - } - } - visitCreateType(node) { - this.append("create type "); - this.visitNode(node.name); - if (node.enum) { - this.append(" as enum "); - this.visitNode(node.enum); - } - } - visitDropType(node) { - this.append("drop type "); - if (node.ifExists) { - this.append("if exists "); - } - this.visitNode(node.name); - } - visitExplain(node) { - this.append("explain"); - if (node.options || node.format) { - this.append(" "); - this.append(this.getLeftExplainOptionsWrapper()); - if (node.options) { - this.visitNode(node.options); - if (node.format) { - this.append(this.getExplainOptionsDelimiter()); - } - } - if (node.format) { - this.append("format"); - this.append(this.getExplainOptionAssignment()); - this.append(node.format); - } - this.append(this.getRightExplainOptionsWrapper()); - } - } - visitDefaultInsertValue(_) { - this.append("default"); - } - visitAggregateFunction(node) { - this.append(node.func); - this.append("("); - if (node.distinct) { - this.append("distinct "); - } - this.compileList(node.aggregated); - if (node.orderBy) { - this.append(" "); - this.visitNode(node.orderBy); - } - this.append(")"); - if (node.withinGroup) { - this.append(" within group ("); - this.visitNode(node.withinGroup); - this.append(")"); - } - if (node.filter) { - this.append(" filter("); - this.visitNode(node.filter); - this.append(")"); - } - if (node.over) { - this.append(" "); - this.visitNode(node.over); - } - } - visitOver(node) { - this.append("over("); - if (node.partitionBy) { - this.visitNode(node.partitionBy); - if (node.orderBy) { - this.append(" "); - } - } - if (node.orderBy) { - this.visitNode(node.orderBy); - } - this.append(")"); - } - visitPartitionBy(node) { - this.append("partition by "); - this.compileList(node.items); - } - visitPartitionByItem(node) { - this.visitNode(node.partitionBy); - } - visitBinaryOperation(node) { - this.visitNode(node.leftOperand); - this.append(" "); - this.visitNode(node.operator); - this.append(" "); - this.visitNode(node.rightOperand); - } - visitUnaryOperation(node) { - this.visitNode(node.operator); - if (!this.isMinusOperator(node.operator)) { - this.append(" "); - } - this.visitNode(node.operand); - } - isMinusOperator(node) { - return OperatorNode.is(node) && node.operator === "-"; - } - visitUsing(node) { - this.append("using "); - this.compileList(node.tables); - } - visitFunction(node) { - this.append(node.func); - this.append("("); - this.compileList(node.arguments); - this.append(")"); - } - visitCase(node) { - this.append("case"); - if (node.value) { - this.append(" "); - this.visitNode(node.value); - } - if (node.when) { - this.append(" "); - this.compileList(node.when, " "); - } - if (node.else) { - this.append(" else "); - this.visitNode(node.else); - } - this.append(" end"); - if (node.isStatement) { - this.append(" case"); - } - } - visitWhen(node) { - this.append("when "); - this.visitNode(node.condition); - if (node.result) { - this.append(" then "); - this.visitNode(node.result); - } - } - visitJSONReference(node) { - this.visitNode(node.reference); - this.visitNode(node.traversal); - } - visitJSONPath(node) { - if (node.inOperator) { - this.visitNode(node.inOperator); - } - this.append("'$"); - for (const pathLeg of node.pathLegs) { - this.visitNode(pathLeg); - } - this.append("'"); - } - visitJSONPathLeg(node) { - const isArrayLocation = node.type === "ArrayLocation"; - this.append(isArrayLocation ? "[" : "."); - this.append(typeof node.value === "string" ? this.sanitizeStringLiteral(node.value) : String(node.value)); - if (isArrayLocation) { - this.append("]"); - } - } - visitJSONOperatorChain(node) { - for (let i5 = 0, len = node.values.length; i5 < len; i5++) { - if (i5 === len - 1) { - this.visitNode(node.operator); - } else { - this.append("->"); - } - this.visitNode(node.values[i5]); - } - } - visitMergeQuery(node) { - if (node.with) { - this.visitNode(node.with); - this.append(" "); - } - this.append("merge "); - if (node.top) { - this.visitNode(node.top); - this.append(" "); - } - this.append("into "); - this.visitNode(node.into); - if (node.using) { - this.append(" "); - this.visitNode(node.using); - } - if (node.whens) { - this.append(" "); - this.compileList(node.whens, " "); - } - if (node.returning) { - this.append(" "); - this.visitNode(node.returning); - } - if (node.output) { - this.append(" "); - this.visitNode(node.output); - } - if (node.endModifiers?.length) { - this.append(" "); - this.compileList(node.endModifiers, " "); - } - } - visitMatched(node) { - if (node.not) { - this.append("not "); - } - this.append("matched"); - if (node.bySource) { - this.append(" by source"); - } - } - visitAddIndex(node) { - this.append("add "); - if (node.unique) { - this.append("unique "); - } - this.append("index "); - this.visitNode(node.name); - if (node.columns) { - this.append(" ("); - this.compileList(node.columns); - this.append(")"); - } - if (node.using) { - this.append(" using "); - this.visitNode(node.using); - } - } - visitCast(node) { - this.append("cast("); - this.visitNode(node.expression); - this.append(" as "); - this.visitNode(node.dataType); - this.append(")"); - } - visitFetch(node) { - this.append("fetch next "); - this.visitNode(node.rowCount); - this.append(` rows ${node.modifier}`); - } - visitOutput(node) { - this.append("output "); - this.compileList(node.selections); - } - visitTop(node) { - this.append(`top(${node.expression})`); - if (node.modifiers) { - this.append(` ${node.modifiers}`); - } - } - visitOrAction(node) { - this.append(node.action); - } - visitCollate(node) { - this.append("collate "); - this.visitNode(node.collation); - } - append(str) { - this.#sql += str; - } - appendValue(parameter) { - this.addParameter(parameter); - this.append(this.getCurrentParameterPlaceholder()); - } - getLeftIdentifierWrapper() { - return '"'; - } - getRightIdentifierWrapper() { - return '"'; - } - getCurrentParameterPlaceholder() { - return "$" + this.numParameters; - } - getLeftExplainOptionsWrapper() { - return "("; - } - getExplainOptionAssignment() { - return " "; - } - getExplainOptionsDelimiter() { - return ", "; - } - getRightExplainOptionsWrapper() { - return ")"; - } - sanitizeIdentifier(identifier) { - const leftWrap = this.getLeftIdentifierWrapper(); - const rightWrap = this.getRightIdentifierWrapper(); - let sanitized = ""; - for (const c5 of identifier) { - sanitized += c5; - if (c5 === leftWrap) { - sanitized += leftWrap; - } else if (c5 === rightWrap) { - sanitized += rightWrap; - } - } - return sanitized; - } - sanitizeStringLiteral(value) { - return value.replace(LIT_WRAP_REGEX, "''"); - } - addParameter(parameter) { - this.#parameters.push(parameter); - } - appendImmediateValue(value) { - if (isString(value)) { - this.appendStringLiteral(value); - } else if (isNumber(value) || isBoolean(value) || isBigInt(value)) { - this.append(value.toString()); - } else if (isNull2(value)) { - this.append("null"); - } else if (isDate(value)) { - this.appendImmediateValue(value.toISOString()); - } else { - throw new Error(`invalid immediate value ${value}`); - } - } - appendStringLiteral(value) { - this.append("'"); - this.append(this.sanitizeStringLiteral(value)); - this.append("'"); - } - sortSelectModifiers(arr) { - arr.sort((left, right) => left.modifier && right.modifier ? SELECT_MODIFIER_PRIORITY[left.modifier] - SELECT_MODIFIER_PRIORITY[right.modifier] : 1); - return freeze2(arr); - } - compileColumnAlterations(columnAlterations) { - this.compileList(columnAlterations); - } - /** - * controls whether the dialect adds a "type" keyword before a column's new data - * type in an ALTER TABLE statement. - */ - announcesNewColumnDataType() { - return true; - } - }; - SELECT_MODIFIER_SQL = freeze2({ - ForKeyShare: "for key share", - ForNoKeyUpdate: "for no key update", - ForUpdate: "for update", - ForShare: "for share", - NoWait: "nowait", - SkipLocked: "skip locked", - Distinct: "distinct" - }); - SELECT_MODIFIER_PRIORITY = freeze2({ - ForKeyShare: 1, - ForNoKeyUpdate: 1, - ForUpdate: 1, - ForShare: 1, - NoWait: 2, - SkipLocked: 2, - Distinct: 0 - }); - JOIN_TYPE_SQL = freeze2({ - InnerJoin: "inner join", - LeftJoin: "left join", - RightJoin: "right join", - FullJoin: "full join", - CrossJoin: "cross join", - LateralInnerJoin: "inner join lateral", - LateralLeftJoin: "left join lateral", - LateralCrossJoin: "cross join lateral", - OuterApply: "outer apply", - CrossApply: "cross apply", - Using: "using" - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-compiler/compiled-query.js -var CompiledQuery; -var init_compiled_query = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-compiler/compiled-query.js"() { - init_raw_node(); - init_object_utils(); - init_query_id(); - CompiledQuery = freeze2({ - raw(sql3, parameters = []) { - return freeze2({ - sql: sql3, - query: RawNode.createWithSql(sql3), - parameters: freeze2(parameters), - queryId: createQueryId() - }); - } - }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/driver/database-connection.js -var init_database_connection = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/driver/database-connection.js"() { - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/driver/connection-provider.js -var init_connection_provider = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/driver/connection-provider.js"() { - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/driver/dummy-driver.js -var init_dummy_driver = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/driver/dummy-driver.js"() { - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/dialect.js -var init_dialect2 = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/dialect.js"() { - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/dialect-adapter.js -var init_dialect_adapter = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/dialect-adapter.js"() { - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/dialect-adapter-base.js -var DialectAdapterBase; -var init_dialect_adapter_base = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/dialect-adapter-base.js"() { - DialectAdapterBase = class { - get supportsCreateIfNotExists() { - return true; - } - get supportsTransactionalDdl() { - return false; - } - get supportsReturning() { - return false; - } - get supportsOutput() { - return false; - } - }; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/database-introspector.js -var init_database_introspector = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/database-introspector.js"() { - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/savepoint-parser.js -function parseSavepointCommand(command, savepointName) { - return RawNode.createWithChildren([ - RawNode.createWithSql(`${command} `), - IdentifierNode.create(savepointName) - // ensures savepointName gets sanitized - ]); -} -var init_savepoint_parser = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/savepoint-parser.js"() { - init_identifier_node(); - init_raw_node(); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/sqlite/sqlite-driver.js -var SqliteDriver, SqliteConnection, ConnectionMutex; -var init_sqlite_driver = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/sqlite/sqlite-driver.js"() { - init_select_query_node(); - init_savepoint_parser(); - init_compiled_query(); - init_object_utils(); - init_query_id(); - SqliteDriver = class { - #config; - #connectionMutex = new ConnectionMutex(); - #db; - #connection; - constructor(config3) { - this.#config = freeze2({ ...config3 }); - } - async init() { - this.#db = isFunction(this.#config.database) ? await this.#config.database() : this.#config.database; - this.#connection = new SqliteConnection(this.#db); - if (this.#config.onCreateConnection) { - await this.#config.onCreateConnection(this.#connection); - } - } - async acquireConnection() { - await this.#connectionMutex.lock(); - return this.#connection; - } - async beginTransaction(connection2) { - await connection2.executeQuery(CompiledQuery.raw("begin")); - } - async commitTransaction(connection2) { - await connection2.executeQuery(CompiledQuery.raw("commit")); - } - async rollbackTransaction(connection2) { - await connection2.executeQuery(CompiledQuery.raw("rollback")); - } - async savepoint(connection2, savepointName, compileQuery) { - await connection2.executeQuery(compileQuery(parseSavepointCommand("savepoint", savepointName), createQueryId())); - } - async rollbackToSavepoint(connection2, savepointName, compileQuery) { - await connection2.executeQuery(compileQuery(parseSavepointCommand("rollback to", savepointName), createQueryId())); - } - async releaseSavepoint(connection2, savepointName, compileQuery) { - await connection2.executeQuery(compileQuery(parseSavepointCommand("release", savepointName), createQueryId())); - } - async releaseConnection() { - this.#connectionMutex.unlock(); - } - async destroy() { - this.#db?.close(); - } - }; - SqliteConnection = class { - #db; - constructor(db) { - this.#db = db; - } - executeQuery(compiledQuery) { - const { sql: sql3, parameters } = compiledQuery; - const stmt = this.#db.prepare(sql3); - if (stmt.reader) { - return Promise.resolve({ - rows: stmt.all(parameters) - }); - } - const { changes, lastInsertRowid } = stmt.run(parameters); - return Promise.resolve({ - numAffectedRows: changes !== void 0 && changes !== null ? BigInt(changes) : void 0, - insertId: lastInsertRowid !== void 0 && lastInsertRowid !== null ? BigInt(lastInsertRowid) : void 0, - rows: [] - }); - } - async *streamQuery(compiledQuery, _chunkSize) { - const { sql: sql3, parameters, query } = compiledQuery; - const stmt = this.#db.prepare(sql3); - if (SelectQueryNode.is(query)) { - const iter = stmt.iterate(parameters); - for (const row of iter) { - yield { - rows: [row] - }; - } - } else { - throw new Error("Sqlite driver only supports streaming of select queries"); - } - } - }; - ConnectionMutex = class { - #promise; - #resolve; - async lock() { - while (this.#promise) { - await this.#promise; - } - this.#promise = new Promise((resolve4) => { - this.#resolve = resolve4; - }); - } - unlock() { - const resolve4 = this.#resolve; - this.#promise = void 0; - this.#resolve = void 0; - resolve4?.(); - } - }; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/sqlite/sqlite-query-compiler.js -var ID_WRAP_REGEX, SqliteQueryCompiler; -var init_sqlite_query_compiler = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/sqlite/sqlite-query-compiler.js"() { - init_default_query_compiler(); - ID_WRAP_REGEX = /"/g; - SqliteQueryCompiler = class extends DefaultQueryCompiler { - visitOrAction(node) { - this.append("or "); - this.append(node.action); - } - getCurrentParameterPlaceholder() { - return "?"; - } - getLeftExplainOptionsWrapper() { - return ""; - } - getRightExplainOptionsWrapper() { - return ""; - } - getLeftIdentifierWrapper() { - return '"'; - } - getRightIdentifierWrapper() { - return '"'; - } - getAutoIncrement() { - return "autoincrement"; - } - sanitizeIdentifier(identifier) { - return identifier.replace(ID_WRAP_REGEX, '""'); - } - visitDefaultInsertValue(_) { - this.append("null"); - } - }; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/migration/migrator.js -var DEFAULT_MIGRATION_TABLE, DEFAULT_MIGRATION_LOCK_TABLE, NO_MIGRATIONS; -var init_migrator = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/migration/migrator.js"() { - init_object_utils(); - DEFAULT_MIGRATION_TABLE = "kysely_migration"; - DEFAULT_MIGRATION_LOCK_TABLE = "kysely_migration_lock"; - NO_MIGRATIONS = freeze2({ __noMigrations__: true }); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/sqlite/sqlite-introspector.js -var SqliteIntrospector; -var init_sqlite_introspector = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/sqlite/sqlite-introspector.js"() { - init_migrator(); - init_sql3(); - SqliteIntrospector = class { - #db; - constructor(db) { - this.#db = db; - } - async getSchemas() { - return []; - } - async getTables(options = { withInternalKyselyTables: false }) { - return await this.#getTableMetadata(options); - } - async getMetadata(options) { - return { - tables: await this.getTables(options) - }; - } - #tablesQuery(qb, options) { - let tablesQuery = qb.selectFrom("sqlite_master").where("type", "in", ["table", "view"]).where("name", "not like", "sqlite_%").select(["name", "sql", "type"]).orderBy("name"); - if (!options.withInternalKyselyTables) { - tablesQuery = tablesQuery.where("name", "!=", DEFAULT_MIGRATION_TABLE).where("name", "!=", DEFAULT_MIGRATION_LOCK_TABLE); - } - return tablesQuery; - } - async #getTableMetadata(options) { - const tablesResult = await this.#tablesQuery(this.#db, options).execute(); - const tableMetadata = await this.#db.with("table_list", (qb) => this.#tablesQuery(qb, options)).selectFrom([ - "table_list as tl", - sql2`pragma_table_info(tl.name)`.as("p") - ]).select([ - "tl.name as table", - "p.cid", - "p.name", - "p.type", - "p.notnull", - "p.dflt_value", - "p.pk" - ]).orderBy("tl.name").orderBy("p.cid").execute(); - const columnsByTable = {}; - for (const row of tableMetadata) { - columnsByTable[row.table] ??= []; - columnsByTable[row.table].push(row); - } - return tablesResult.map(({ name, sql: sql3, type }) => { - let autoIncrementCol = sql3?.split(/[\(\),]/)?.find((it) => it.toLowerCase().includes("autoincrement"))?.trimStart()?.split(/\s+/)?.[0]?.replace(/["`]/g, ""); - const columns = columnsByTable[name] ?? []; - if (!autoIncrementCol) { - const pkCols = columns.filter((r5) => r5.pk > 0); - if (pkCols.length === 1 && pkCols[0].type.toLowerCase() === "integer") { - autoIncrementCol = pkCols[0].name; - } - } - return { - name, - isView: type === "view", - columns: columns.map((col) => ({ - name: col.name, - dataType: col.type, - isNullable: !col.notnull, - isAutoIncrementing: col.name === autoIncrementCol, - hasDefaultValue: col.dflt_value != null, - comment: void 0 - })) - }; - }); - } - }; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/sqlite/sqlite-adapter.js -var SqliteAdapter; -var init_sqlite_adapter = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/sqlite/sqlite-adapter.js"() { - init_dialect_adapter_base(); - SqliteAdapter = class extends DialectAdapterBase { - get supportsTransactionalDdl() { - return false; - } - get supportsReturning() { - return true; - } - async acquireMigrationLock(_db, _opt) { - } - async releaseMigrationLock(_db, _opt) { - } - }; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/sqlite/sqlite-dialect.js -var SqliteDialect; -var init_sqlite_dialect = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/sqlite/sqlite-dialect.js"() { - init_sqlite_driver(); - init_sqlite_query_compiler(); - init_sqlite_introspector(); - init_sqlite_adapter(); - init_object_utils(); - SqliteDialect = class { - #config; - constructor(config3) { - this.#config = freeze2({ ...config3 }); - } - createDriver() { - return new SqliteDriver(this.#config); - } - createQueryCompiler() { - return new SqliteQueryCompiler(); - } - createAdapter() { - return new SqliteAdapter(); - } - createIntrospector(db) { - return new SqliteIntrospector(db); - } - }; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/sqlite/sqlite-dialect-config.js -var init_sqlite_dialect_config = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/sqlite/sqlite-dialect-config.js"() { - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/postgres/postgres-query-compiler.js -var ID_WRAP_REGEX2, PostgresQueryCompiler; -var init_postgres_query_compiler = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/postgres/postgres-query-compiler.js"() { - init_default_query_compiler(); - ID_WRAP_REGEX2 = /"/g; - PostgresQueryCompiler = class extends DefaultQueryCompiler { - sanitizeIdentifier(identifier) { - return identifier.replace(ID_WRAP_REGEX2, '""'); - } - }; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/postgres/postgres-introspector.js -var PostgresIntrospector; -var init_postgres_introspector = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/postgres/postgres-introspector.js"() { - init_migrator(); - init_object_utils(); - init_sql3(); - PostgresIntrospector = class { - #db; - constructor(db) { - this.#db = db; - } - async getSchemas() { - let rawSchemas = await this.#db.selectFrom("pg_catalog.pg_namespace").select("nspname").$castTo().execute(); - return rawSchemas.map((it) => ({ name: it.nspname })); - } - async getTables(options = { withInternalKyselyTables: false }) { - let query = this.#db.selectFrom("pg_catalog.pg_attribute as a").innerJoin("pg_catalog.pg_class as c", "a.attrelid", "c.oid").innerJoin("pg_catalog.pg_namespace as ns", "c.relnamespace", "ns.oid").innerJoin("pg_catalog.pg_type as typ", "a.atttypid", "typ.oid").innerJoin("pg_catalog.pg_namespace as dtns", "typ.typnamespace", "dtns.oid").select([ - "a.attname as column", - "a.attnotnull as not_null", - "a.atthasdef as has_default", - "c.relname as table", - "c.relkind as table_type", - "ns.nspname as schema", - "typ.typname as type", - "dtns.nspname as type_schema", - sql2`col_description(a.attrelid, a.attnum)`.as("column_description"), - sql2`pg_get_serial_sequence(quote_ident(ns.nspname) || '.' || quote_ident(c.relname), a.attname)`.as("auto_incrementing") - ]).where("c.relkind", "in", [ - "r", - "v", - "p" - ]).where("ns.nspname", "!~", "^pg_").where("ns.nspname", "!=", "information_schema").where("ns.nspname", "!=", "crdb_internal").where(sql2`has_schema_privilege(ns.nspname, 'USAGE')`).where("a.attnum", ">=", 0).where("a.attisdropped", "!=", true).orderBy("ns.nspname").orderBy("c.relname").orderBy("a.attnum").$castTo(); - if (!options.withInternalKyselyTables) { - query = query.where("c.relname", "!=", DEFAULT_MIGRATION_TABLE).where("c.relname", "!=", DEFAULT_MIGRATION_LOCK_TABLE); - } - const rawColumns = await query.execute(); - return this.#parseTableMetadata(rawColumns); - } - async getMetadata(options) { - return { - tables: await this.getTables(options) - }; - } - #parseTableMetadata(columns) { - const tableDictionary = /* @__PURE__ */ new Map(); - for (let i5 = 0, len = columns.length; i5 < len; i5++) { - const column = columns[i5]; - const { schema: schema2, table } = column; - const tableKey = `schema:${schema2};table:${table}`; - if (!tableDictionary.has(tableKey)) { - tableDictionary.set(tableKey, freeze2({ - columns: [], - isView: column.table_type === "v", - name: table, - schema: schema2 - })); - } - tableDictionary.get(tableKey).columns.push(freeze2({ - comment: column.column_description ?? void 0, - dataType: column.type, - dataTypeSchema: column.type_schema, - hasDefaultValue: column.has_default, - isAutoIncrementing: column.auto_incrementing !== null, - isNullable: !column.not_null, - name: column.column - })); - } - return Array.from(tableDictionary.values()); - } - }; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/postgres/postgres-adapter.js -var LOCK_ID, PostgresAdapter; -var init_postgres_adapter = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/postgres/postgres-adapter.js"() { - init_sql3(); - init_dialect_adapter_base(); - LOCK_ID = BigInt("3853314791062309107"); - PostgresAdapter = class extends DialectAdapterBase { - get supportsTransactionalDdl() { - return true; - } - get supportsReturning() { - return true; - } - async acquireMigrationLock(db, _opt) { - await sql2`select pg_advisory_xact_lock(${sql2.lit(LOCK_ID)})`.execute(db); - } - async releaseMigrationLock(_db, _opt) { - } - }; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/stack-trace-utils.js -function extendStackTrace(err, stackError) { - if (isStackHolder(err) && stackError.stack) { - const stackExtension = stackError.stack.split("\n").slice(1).join("\n"); - err.stack += ` -${stackExtension}`; - return err; - } - return err; -} -function isStackHolder(obj) { - return isObject3(obj) && isString(obj.stack); -} -var init_stack_trace_utils = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/stack-trace-utils.js"() { - init_object_utils(); - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mysql/mysql-driver.js -function isOkPacket(obj) { - return isObject3(obj) && "insertId" in obj && "affectedRows" in obj; -} -var PRIVATE_RELEASE_METHOD, MysqlDriver, MysqlConnection; -var init_mysql_driver = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mysql/mysql-driver.js"() { - init_savepoint_parser(); - init_compiled_query(); - init_object_utils(); - init_query_id(); - init_stack_trace_utils(); - PRIVATE_RELEASE_METHOD = /* @__PURE__ */ Symbol(); - MysqlDriver = class { - #config; - #connections = /* @__PURE__ */ new WeakMap(); - #pool; - constructor(configOrPool) { - this.#config = freeze2({ ...configOrPool }); - } - async init() { - this.#pool = isFunction(this.#config.pool) ? await this.#config.pool() : this.#config.pool; - } - async acquireConnection() { - const rawConnection = await this.#acquireConnection(); - let connection2 = this.#connections.get(rawConnection); - if (!connection2) { - connection2 = new MysqlConnection(rawConnection); - this.#connections.set(rawConnection, connection2); - if (this.#config?.onCreateConnection) { - await this.#config.onCreateConnection(connection2); - } - } - if (this.#config?.onReserveConnection) { - await this.#config.onReserveConnection(connection2); - } - return connection2; - } - async #acquireConnection() { - return new Promise((resolve4, reject) => { - this.#pool.getConnection(async (err, rawConnection) => { - if (err) { - reject(err); - } else { - resolve4(rawConnection); - } - }); - }); - } - async beginTransaction(connection2, settings) { - if (settings.isolationLevel || settings.accessMode) { - const parts = []; - if (settings.isolationLevel) { - parts.push(`isolation level ${settings.isolationLevel}`); - } - if (settings.accessMode) { - parts.push(settings.accessMode); - } - const sql3 = `set transaction ${parts.join(", ")}`; - await connection2.executeQuery(CompiledQuery.raw(sql3)); - } - await connection2.executeQuery(CompiledQuery.raw("begin")); - } - async commitTransaction(connection2) { - await connection2.executeQuery(CompiledQuery.raw("commit")); - } - async rollbackTransaction(connection2) { - await connection2.executeQuery(CompiledQuery.raw("rollback")); - } - async savepoint(connection2, savepointName, compileQuery) { - await connection2.executeQuery(compileQuery(parseSavepointCommand("savepoint", savepointName), createQueryId())); - } - async rollbackToSavepoint(connection2, savepointName, compileQuery) { - await connection2.executeQuery(compileQuery(parseSavepointCommand("rollback to", savepointName), createQueryId())); - } - async releaseSavepoint(connection2, savepointName, compileQuery) { - await connection2.executeQuery(compileQuery(parseSavepointCommand("release savepoint", savepointName), createQueryId())); - } - async releaseConnection(connection2) { - connection2[PRIVATE_RELEASE_METHOD](); - } - async destroy() { - return new Promise((resolve4, reject) => { - this.#pool.end((err) => { - if (err) { - reject(err); - } else { - resolve4(); - } - }); - }); - } - }; - MysqlConnection = class { - #rawConnection; - constructor(rawConnection) { - this.#rawConnection = rawConnection; - } - async executeQuery(compiledQuery) { - try { - const result = await this.#executeQuery(compiledQuery); - if (isOkPacket(result)) { - const { insertId, affectedRows, changedRows } = result; - return { - insertId: insertId !== void 0 && insertId !== null && insertId.toString() !== "0" ? BigInt(insertId) : void 0, - numAffectedRows: affectedRows !== void 0 && affectedRows !== null ? BigInt(affectedRows) : void 0, - numChangedRows: changedRows !== void 0 && changedRows !== null ? BigInt(changedRows) : void 0, - rows: [] - }; - } else if (Array.isArray(result)) { - return { - rows: result - }; - } - return { - rows: [] - }; - } catch (err) { - throw extendStackTrace(err, new Error()); - } - } - #executeQuery(compiledQuery) { - return new Promise((resolve4, reject) => { - this.#rawConnection.query(compiledQuery.sql, compiledQuery.parameters, (err, result) => { - if (err) { - reject(err); - } else { - resolve4(result); - } - }); - }); - } - async *streamQuery(compiledQuery, _chunkSize) { - const stream = this.#rawConnection.query(compiledQuery.sql, compiledQuery.parameters).stream({ - objectMode: true - }); - try { - for await (const row of stream) { - yield { - rows: [row] - }; - } - } catch (ex) { - if (ex && typeof ex === "object" && "code" in ex && // @ts-ignore - ex.code === "ERR_STREAM_PREMATURE_CLOSE") { - return; - } - throw ex; - } - } - [PRIVATE_RELEASE_METHOD]() { - this.#rawConnection.release(); - } - }; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mysql/mysql-query-compiler.js -var LITERAL_ESCAPE_REGEX, ID_WRAP_REGEX3, MysqlQueryCompiler; -var init_mysql_query_compiler = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mysql/mysql-query-compiler.js"() { - init_default_query_compiler(); - LITERAL_ESCAPE_REGEX = /\\|'/g; - ID_WRAP_REGEX3 = /`/g; - MysqlQueryCompiler = class extends DefaultQueryCompiler { - getCurrentParameterPlaceholder() { - return "?"; - } - getLeftExplainOptionsWrapper() { - return ""; - } - getExplainOptionAssignment() { - return "="; - } - getExplainOptionsDelimiter() { - return " "; - } - getRightExplainOptionsWrapper() { - return ""; - } - getLeftIdentifierWrapper() { - return ID_WRAP_REGEX3.source; - } - getRightIdentifierWrapper() { - return ID_WRAP_REGEX3.source; - } - sanitizeIdentifier(identifier) { - return identifier.replace(ID_WRAP_REGEX3, "``"); - } - /** - * MySQL requires escaping backslashes in string literals when using the - * default NO_BACKSLASH_ESCAPES=OFF mode. Without this, a backslash - * followed by a quote (\') can break out of the string literal. - * - * @see https://dev.mysql.com/doc/refman/9.6/en/string-literals.html - */ - sanitizeStringLiteral(value) { - return value.replace(LITERAL_ESCAPE_REGEX, (char2) => char2 === "\\" ? "\\\\" : "''"); - } - visitCreateIndex(node) { - this.append("create "); - if (node.unique) { - this.append("unique "); - } - this.append("index "); - if (node.ifNotExists) { - this.append("if not exists "); - } - this.visitNode(node.name); - if (node.using) { - this.append(" using "); - this.visitNode(node.using); - } - if (node.table) { - this.append(" on "); - this.visitNode(node.table); - } - if (node.columns) { - this.append(" ("); - this.compileList(node.columns); - this.append(")"); - } - if (node.where) { - this.append(" "); - this.visitNode(node.where); - } - } - }; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mysql/mysql-introspector.js -var MysqlIntrospector; -var init_mysql_introspector = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mysql/mysql-introspector.js"() { - init_migrator(); - init_object_utils(); - init_sql3(); - MysqlIntrospector = class { - #db; - constructor(db) { - this.#db = db; - } - async getSchemas() { - let rawSchemas = await this.#db.selectFrom("information_schema.schemata").select("schema_name").$castTo().execute(); - return rawSchemas.map((it) => ({ name: it.SCHEMA_NAME })); - } - async getTables(options = { withInternalKyselyTables: false }) { - let query = this.#db.selectFrom("information_schema.columns as columns").innerJoin("information_schema.tables as tables", (b6) => b6.onRef("columns.TABLE_CATALOG", "=", "tables.TABLE_CATALOG").onRef("columns.TABLE_SCHEMA", "=", "tables.TABLE_SCHEMA").onRef("columns.TABLE_NAME", "=", "tables.TABLE_NAME")).select([ - "columns.COLUMN_NAME", - "columns.COLUMN_DEFAULT", - "columns.TABLE_NAME", - "columns.TABLE_SCHEMA", - "tables.TABLE_TYPE", - "columns.IS_NULLABLE", - "columns.DATA_TYPE", - "columns.EXTRA", - "columns.COLUMN_COMMENT" - ]).where("columns.TABLE_SCHEMA", "=", sql2`database()`).orderBy("columns.TABLE_NAME").orderBy("columns.ORDINAL_POSITION").$castTo(); - if (!options.withInternalKyselyTables) { - query = query.where("columns.TABLE_NAME", "!=", DEFAULT_MIGRATION_TABLE).where("columns.TABLE_NAME", "!=", DEFAULT_MIGRATION_LOCK_TABLE); - } - const rawColumns = await query.execute(); - return this.#parseTableMetadata(rawColumns); - } - async getMetadata(options) { - return { - tables: await this.getTables(options) - }; - } - #parseTableMetadata(columns) { - return columns.reduce((tables, it) => { - let table = tables.find((tbl) => tbl.name === it.TABLE_NAME); - if (!table) { - table = freeze2({ - name: it.TABLE_NAME, - isView: it.TABLE_TYPE === "VIEW", - schema: it.TABLE_SCHEMA, - columns: [] - }); - tables.push(table); - } - table.columns.push(freeze2({ - name: it.COLUMN_NAME, - dataType: it.DATA_TYPE, - isNullable: it.IS_NULLABLE === "YES", - isAutoIncrementing: it.EXTRA.toLowerCase().includes("auto_increment"), - hasDefaultValue: it.COLUMN_DEFAULT !== null, - comment: it.COLUMN_COMMENT === "" ? void 0 : it.COLUMN_COMMENT - })); - return tables; - }, []); - } - }; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mysql/mysql-adapter.js -var LOCK_ID2, LOCK_TIMEOUT_SECONDS, MysqlAdapter; -var init_mysql_adapter = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mysql/mysql-adapter.js"() { - init_sql3(); - init_dialect_adapter_base(); - LOCK_ID2 = "ea586330-2c93-47c8-908d-981d9d270f9d"; - LOCK_TIMEOUT_SECONDS = 60 * 60; - MysqlAdapter = class extends DialectAdapterBase { - get supportsTransactionalDdl() { - return false; - } - get supportsReturning() { - return false; - } - async acquireMigrationLock(db, _opt) { - await sql2`select get_lock(${sql2.lit(LOCK_ID2)}, ${sql2.lit(LOCK_TIMEOUT_SECONDS)})`.execute(db); - } - async releaseMigrationLock(db, _opt) { - await sql2`select release_lock(${sql2.lit(LOCK_ID2)})`.execute(db); - } - }; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mysql/mysql-dialect.js -var MysqlDialect; -var init_mysql_dialect = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mysql/mysql-dialect.js"() { - init_mysql_driver(); - init_mysql_query_compiler(); - init_mysql_introspector(); - init_mysql_adapter(); - MysqlDialect = class { - #config; - constructor(config3) { - this.#config = config3; - } - createDriver() { - return new MysqlDriver(this.#config); - } - createQueryCompiler() { - return new MysqlQueryCompiler(); - } - createAdapter() { - return new MysqlAdapter(); - } - createIntrospector(db) { - return new MysqlIntrospector(db); - } - }; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mysql/mysql-dialect-config.js -var init_mysql_dialect_config = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mysql/mysql-dialect-config.js"() { - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/postgres/postgres-driver.js -var PRIVATE_RELEASE_METHOD2, PostgresDriver, PostgresConnection; -var init_postgres_driver = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/postgres/postgres-driver.js"() { - init_savepoint_parser(); - init_compiled_query(); - init_object_utils(); - init_query_id(); - init_stack_trace_utils(); - PRIVATE_RELEASE_METHOD2 = /* @__PURE__ */ Symbol(); - PostgresDriver = class { - #config; - #connections = /* @__PURE__ */ new WeakMap(); - #pool; - constructor(config3) { - this.#config = freeze2({ ...config3 }); - } - async init() { - this.#pool = isFunction(this.#config.pool) ? await this.#config.pool() : this.#config.pool; - } - async acquireConnection() { - const client2 = await this.#pool.connect(); - let connection2 = this.#connections.get(client2); - if (!connection2) { - connection2 = new PostgresConnection(client2, { - cursor: this.#config.cursor ?? null - }); - this.#connections.set(client2, connection2); - if (this.#config.onCreateConnection) { - await this.#config.onCreateConnection(connection2); - } - } - if (this.#config.onReserveConnection) { - await this.#config.onReserveConnection(connection2); - } - return connection2; - } - async beginTransaction(connection2, settings) { - if (settings.isolationLevel || settings.accessMode) { - let sql3 = "start transaction"; - if (settings.isolationLevel) { - sql3 += ` isolation level ${settings.isolationLevel}`; - } - if (settings.accessMode) { - sql3 += ` ${settings.accessMode}`; - } - await connection2.executeQuery(CompiledQuery.raw(sql3)); - } else { - await connection2.executeQuery(CompiledQuery.raw("begin")); - } - } - async commitTransaction(connection2) { - await connection2.executeQuery(CompiledQuery.raw("commit")); - } - async rollbackTransaction(connection2) { - await connection2.executeQuery(CompiledQuery.raw("rollback")); - } - async savepoint(connection2, savepointName, compileQuery) { - await connection2.executeQuery(compileQuery(parseSavepointCommand("savepoint", savepointName), createQueryId())); - } - async rollbackToSavepoint(connection2, savepointName, compileQuery) { - await connection2.executeQuery(compileQuery(parseSavepointCommand("rollback to", savepointName), createQueryId())); - } - async releaseSavepoint(connection2, savepointName, compileQuery) { - await connection2.executeQuery(compileQuery(parseSavepointCommand("release", savepointName), createQueryId())); - } - async releaseConnection(connection2) { - connection2[PRIVATE_RELEASE_METHOD2](); - } - async destroy() { - if (this.#pool) { - const pool = this.#pool; - this.#pool = void 0; - await pool.end(); - } - } - }; - PostgresConnection = class { - #client; - #options; - constructor(client2, options) { - this.#client = client2; - this.#options = options; - } - async executeQuery(compiledQuery) { - try { - const { command, rowCount, rows } = await this.#client.query(compiledQuery.sql, [...compiledQuery.parameters]); - return { - numAffectedRows: command === "INSERT" || command === "UPDATE" || command === "DELETE" || command === "MERGE" ? BigInt(rowCount) : void 0, - rows: rows ?? [] - }; - } catch (err) { - throw extendStackTrace(err, new Error()); - } - } - async *streamQuery(compiledQuery, chunkSize) { - if (!this.#options.cursor) { - throw new Error("'cursor' is not present in your postgres dialect config. It's required to make streaming work in postgres."); - } - if (!Number.isInteger(chunkSize) || chunkSize <= 0) { - throw new Error("chunkSize must be a positive integer"); - } - const cursor2 = this.#client.query(new this.#options.cursor(compiledQuery.sql, compiledQuery.parameters.slice())); - try { - while (true) { - const rows = await cursor2.read(chunkSize); - if (rows.length === 0) { - break; - } - yield { - rows - }; - } - } finally { - await cursor2.close(); - } - } - [PRIVATE_RELEASE_METHOD2]() { - this.#client.release(); - } - }; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/postgres/postgres-dialect-config.js -var init_postgres_dialect_config = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/postgres/postgres-dialect-config.js"() { - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/postgres/postgres-dialect.js -var PostgresDialect; -var init_postgres_dialect = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/postgres/postgres-dialect.js"() { - init_postgres_driver(); - init_postgres_introspector(); - init_postgres_query_compiler(); - init_postgres_adapter(); - PostgresDialect = class { - #config; - constructor(config3) { - this.#config = config3; - } - createDriver() { - return new PostgresDriver(this.#config); - } - createQueryCompiler() { - return new PostgresQueryCompiler(); - } - createAdapter() { - return new PostgresAdapter(); - } - createIntrospector(db) { - return new PostgresIntrospector(db); - } - }; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mssql/mssql-adapter.js -var MssqlAdapter; -var init_mssql_adapter = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mssql/mssql-adapter.js"() { - init_migrator(); - init_sql3(); - init_dialect_adapter_base(); - MssqlAdapter = class extends DialectAdapterBase { - get supportsCreateIfNotExists() { - return false; - } - get supportsTransactionalDdl() { - return true; - } - get supportsOutput() { - return true; - } - async acquireMigrationLock(db) { - await sql2`exec sp_getapplock @DbPrincipal = ${sql2.lit("dbo")}, @Resource = ${sql2.lit(DEFAULT_MIGRATION_TABLE)}, @LockMode = ${sql2.lit("Exclusive")}`.execute(db); - } - async releaseMigrationLock() { - } - }; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mssql/mssql-dialect-config.js -var init_mssql_dialect_config = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mssql/mssql-dialect-config.js"() { - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mssql/mssql-driver.js -var PRIVATE_RESET_METHOD, PRIVATE_DESTROY_METHOD, PRIVATE_VALIDATE_METHOD, MssqlDriver, MssqlConnection, MssqlRequest; -var init_mssql_driver = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mssql/mssql-driver.js"() { - init_object_utils(); - init_compiled_query(); - init_stack_trace_utils(); - init_random_string(); - init_deferred(); - PRIVATE_RESET_METHOD = /* @__PURE__ */ Symbol(); - PRIVATE_DESTROY_METHOD = /* @__PURE__ */ Symbol(); - PRIVATE_VALIDATE_METHOD = /* @__PURE__ */ Symbol(); - MssqlDriver = class { - #config; - #pool; - constructor(config3) { - this.#config = freeze2({ ...config3 }); - const { tarn, tedious, validateConnections } = this.#config; - const { validateConnections: deprecatedValidateConnections, ...poolOptions } = tarn.options; - this.#pool = new tarn.Pool({ - ...poolOptions, - create: async () => { - const connection2 = await tedious.connectionFactory(); - return await new MssqlConnection(connection2, tedious).connect(); - }, - destroy: async (connection2) => { - await connection2[PRIVATE_DESTROY_METHOD](); - }, - // @ts-ignore `tarn` accepts a function that returns a promise here, but - // the types are not aligned and it type errors. - validate: validateConnections === false || deprecatedValidateConnections === false ? void 0 : (connection2) => connection2[PRIVATE_VALIDATE_METHOD]() - }); - } - async init() { - } - async acquireConnection() { - return await this.#pool.acquire().promise; - } - async beginTransaction(connection2, settings) { - await connection2.beginTransaction(settings); - } - async commitTransaction(connection2) { - await connection2.commitTransaction(); - } - async rollbackTransaction(connection2) { - await connection2.rollbackTransaction(); - } - async savepoint(connection2, savepointName) { - await connection2.savepoint(savepointName); - } - async rollbackToSavepoint(connection2, savepointName) { - await connection2.rollbackTransaction(savepointName); - } - async releaseConnection(connection2) { - if (this.#config.resetConnectionsOnRelease || this.#config.tedious.resetConnectionOnRelease) { - await connection2[PRIVATE_RESET_METHOD](); - } - this.#pool.release(connection2); - } - async destroy() { - await this.#pool.destroy(); - } - }; - MssqlConnection = class { - #connection; - #hasSocketError; - #tedious; - constructor(connection2, tedious) { - this.#connection = connection2; - this.#hasSocketError = false; - this.#tedious = tedious; - } - async beginTransaction(settings) { - const { isolationLevel } = settings; - await new Promise((resolve4, reject) => this.#connection.beginTransaction((error50) => { - if (error50) - reject(error50); - else - resolve4(void 0); - }, isolationLevel ? randomString2(8) : void 0, isolationLevel ? this.#getTediousIsolationLevel(isolationLevel) : void 0)); - } - async commitTransaction() { - await new Promise((resolve4, reject) => this.#connection.commitTransaction((error50) => { - if (error50) - reject(error50); - else - resolve4(void 0); - })); - } - async connect() { - const { promise: waitForConnected, reject, resolve: resolve4 } = new Deferred(); - this.#connection.connect((error50) => { - if (error50) { - return reject(error50); - } - resolve4(); - }); - this.#connection.on("error", (error50) => { - if (error50 instanceof Error && "code" in error50 && error50.code === "ESOCKET") { - this.#hasSocketError = true; - } - console.error(error50); - reject(error50); - }); - function endListener() { - reject(new Error("The connection ended without ever completing the connection")); - } - this.#connection.once("end", endListener); - await waitForConnected; - this.#connection.off("end", endListener); - return this; - } - async executeQuery(compiledQuery) { - try { - const deferred = new Deferred(); - const request = new MssqlRequest({ - compiledQuery, - tedious: this.#tedious, - onDone: deferred - }); - this.#connection.execSql(request.request); - const { rowCount, rows } = await deferred.promise; - return { - numAffectedRows: rowCount !== void 0 ? BigInt(rowCount) : void 0, - rows - }; - } catch (err) { - throw extendStackTrace(err, new Error()); - } - } - async rollbackTransaction(savepointName) { - await new Promise((resolve4, reject) => this.#connection.rollbackTransaction((error50) => { - if (error50) - reject(error50); - else - resolve4(void 0); - }, savepointName)); - } - async savepoint(savepointName) { - await new Promise((resolve4, reject) => this.#connection.saveTransaction((error50) => { - if (error50) - reject(error50); - else - resolve4(void 0); - }, savepointName)); - } - async *streamQuery(compiledQuery, chunkSize) { - if (!Number.isInteger(chunkSize) || chunkSize <= 0) { - throw new Error("chunkSize must be a positive integer"); - } - const request = new MssqlRequest({ - compiledQuery, - streamChunkSize: chunkSize, - tedious: this.#tedious - }); - this.#connection.execSql(request.request); - try { - while (true) { - const rows = await request.readChunk(); - if (rows.length === 0) { - break; - } - yield { rows }; - if (rows.length < chunkSize) { - break; - } - } - } finally { - await this.#cancelRequest(request); - } - } - #getTediousIsolationLevel(isolationLevel) { - const { ISOLATION_LEVEL } = this.#tedious; - const mapper = { - "read committed": ISOLATION_LEVEL.READ_COMMITTED, - "read uncommitted": ISOLATION_LEVEL.READ_UNCOMMITTED, - "repeatable read": ISOLATION_LEVEL.REPEATABLE_READ, - serializable: ISOLATION_LEVEL.SERIALIZABLE, - snapshot: ISOLATION_LEVEL.SNAPSHOT - }; - const tediousIsolationLevel = mapper[isolationLevel]; - if (tediousIsolationLevel === void 0) { - throw new Error(`Unknown isolation level: ${isolationLevel}`); - } - return tediousIsolationLevel; - } - #cancelRequest(request) { - return new Promise((resolve4) => { - request.request.once("requestCompleted", resolve4); - const wasCanceled = this.#connection.cancel(); - if (!wasCanceled) { - request.request.off("requestCompleted", resolve4); - resolve4(); - } - }); - } - [PRIVATE_DESTROY_METHOD]() { - if ("closed" in this.#connection && this.#connection.closed) { - return Promise.resolve(); - } - return new Promise((resolve4) => { - this.#connection.once("end", resolve4); - this.#connection.close(); - }); - } - async [PRIVATE_RESET_METHOD]() { - await new Promise((resolve4, reject) => { - this.#connection.reset((error50) => { - if (error50) { - return reject(error50); - } - resolve4(); - }); - }); - } - async [PRIVATE_VALIDATE_METHOD]() { - if (this.#hasSocketError || this.#isConnectionClosed()) { - return false; - } - try { - const deferred = new Deferred(); - const request = new MssqlRequest({ - compiledQuery: CompiledQuery.raw("select 1"), - onDone: deferred, - tedious: this.#tedious - }); - this.#connection.execSql(request.request); - await deferred.promise; - return true; - } catch { - return false; - } - } - #isConnectionClosed() { - return "closed" in this.#connection && Boolean(this.#connection.closed); - } - }; - MssqlRequest = class { - #request; - #rows; - #streamChunkSize; - #subscribers; - #tedious; - #rowCount; - constructor(props) { - const { compiledQuery, onDone, streamChunkSize, tedious } = props; - this.#rows = []; - this.#streamChunkSize = streamChunkSize; - this.#subscribers = {}; - this.#tedious = tedious; - if (onDone) { - const subscriptionKey = "onDone"; - this.#subscribers[subscriptionKey] = (event, error50) => { - if (event === "chunkReady") { - return; - } - delete this.#subscribers[subscriptionKey]; - if (event === "error") { - return onDone.reject(error50); - } - onDone.resolve({ - rowCount: this.#rowCount, - rows: this.#rows - }); - }; - } - this.#request = new this.#tedious.Request(compiledQuery.sql, (err, rowCount) => { - if (err) { - return Object.values(this.#subscribers).forEach((subscriber) => subscriber("error", err instanceof AggregateError ? err.errors : err)); - } - this.#rowCount = rowCount; - }); - this.#addParametersToRequest(compiledQuery.parameters); - this.#attachListeners(); - } - get request() { - return this.#request; - } - readChunk() { - const subscriptionKey = this.readChunk.name; - return new Promise((resolve4, reject) => { - this.#subscribers[subscriptionKey] = (event, error50) => { - delete this.#subscribers[subscriptionKey]; - if (event === "error") { - return reject(error50); - } - resolve4(this.#rows.splice(0, this.#streamChunkSize)); - }; - this.#request.resume(); - }); - } - #addParametersToRequest(parameters) { - for (let i5 = 0; i5 < parameters.length; i5++) { - const parameter = parameters[i5]; - this.#request.addParameter(String(i5 + 1), this.#getTediousDataType(parameter), parameter); - } - } - #attachListeners() { - const pauseAndEmitChunkReady = this.#streamChunkSize ? () => { - if (this.#streamChunkSize <= this.#rows.length) { - this.#request.pause(); - Object.values(this.#subscribers).forEach((subscriber) => subscriber("chunkReady")); - } - } : () => { - }; - const rowListener = (columns) => { - const row = {}; - for (const column of columns) { - row[column.metadata.colName] = column.value; - } - this.#rows.push(row); - pauseAndEmitChunkReady(); - }; - this.#request.on("row", rowListener); - this.#request.once("requestCompleted", () => { - Object.values(this.#subscribers).forEach((subscriber) => subscriber("completed")); - this.#request.off("row", rowListener); - }); - } - #getTediousDataType(value) { - if (isNull2(value) || isUndefined(value) || isString(value)) { - return this.#tedious.TYPES.NVarChar; - } - if (isBigInt(value) || isNumber(value) && value % 1 === 0) { - if (value < -2147483648 || value > 2147483647) { - return this.#tedious.TYPES.BigInt; - } else { - return this.#tedious.TYPES.Int; - } - } - if (isNumber(value)) { - return this.#tedious.TYPES.Float; - } - if (isBoolean(value)) { - return this.#tedious.TYPES.Bit; - } - if (isDate(value)) { - return this.#tedious.TYPES.DateTime; - } - if (isBuffer(value)) { - return this.#tedious.TYPES.VarBinary; - } - return this.#tedious.TYPES.NVarChar; - } - }; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mssql/mssql-introspector.js -var MssqlIntrospector; -var init_mssql_introspector = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mssql/mssql-introspector.js"() { - init_migrator(); - init_object_utils(); - MssqlIntrospector = class { - #db; - constructor(db) { - this.#db = db; - } - async getSchemas() { - return await this.#db.selectFrom("sys.schemas").select("name").execute(); - } - async getTables(options = { withInternalKyselyTables: false }) { - const rawColumns = await this.#db.selectFrom("sys.tables as tables").leftJoin("sys.schemas as table_schemas", "table_schemas.schema_id", "tables.schema_id").innerJoin("sys.columns as columns", "columns.object_id", "tables.object_id").innerJoin("sys.types as types", "types.user_type_id", "columns.user_type_id").leftJoin("sys.schemas as type_schemas", "type_schemas.schema_id", "types.schema_id").leftJoin("sys.extended_properties as comments", (join4) => join4.onRef("comments.major_id", "=", "tables.object_id").onRef("comments.minor_id", "=", "columns.column_id").on("comments.name", "=", "MS_Description")).$if(!options.withInternalKyselyTables, (qb) => qb.where("tables.name", "!=", DEFAULT_MIGRATION_TABLE).where("tables.name", "!=", DEFAULT_MIGRATION_LOCK_TABLE)).select([ - "tables.name as table_name", - (eb) => eb.ref("tables.type").$castTo().as("table_type"), - "table_schemas.name as table_schema_name", - "columns.default_object_id as column_default_object_id", - "columns.generated_always_type_desc as column_generated_always_type", - "columns.is_computed as column_is_computed", - "columns.is_identity as column_is_identity", - "columns.is_nullable as column_is_nullable", - "columns.is_rowguidcol as column_is_rowguidcol", - "columns.name as column_name", - "types.is_nullable as type_is_nullable", - "types.name as type_name", - "type_schemas.name as type_schema_name", - "comments.value as column_comment" - ]).unionAll(this.#db.selectFrom("sys.views as views").leftJoin("sys.schemas as view_schemas", "view_schemas.schema_id", "views.schema_id").innerJoin("sys.columns as columns", "columns.object_id", "views.object_id").innerJoin("sys.types as types", "types.user_type_id", "columns.user_type_id").leftJoin("sys.schemas as type_schemas", "type_schemas.schema_id", "types.schema_id").leftJoin("sys.extended_properties as comments", (join4) => join4.onRef("comments.major_id", "=", "views.object_id").onRef("comments.minor_id", "=", "columns.column_id").on("comments.name", "=", "MS_Description")).select([ - "views.name as table_name", - "views.type as table_type", - "view_schemas.name as table_schema_name", - "columns.default_object_id as column_default_object_id", - "columns.generated_always_type_desc as column_generated_always_type", - "columns.is_computed as column_is_computed", - "columns.is_identity as column_is_identity", - "columns.is_nullable as column_is_nullable", - "columns.is_rowguidcol as column_is_rowguidcol", - "columns.name as column_name", - "types.is_nullable as type_is_nullable", - "types.name as type_name", - "type_schemas.name as type_schema_name", - "comments.value as column_comment" - ])).orderBy("table_schema_name").orderBy("table_name").orderBy("column_name").execute(); - const tableDictionary = {}; - for (const rawColumn of rawColumns) { - const key = `${rawColumn.table_schema_name}.${rawColumn.table_name}`; - const table = tableDictionary[key] = tableDictionary[key] || freeze2({ - columns: [], - isView: rawColumn.table_type === "V ", - name: rawColumn.table_name, - schema: rawColumn.table_schema_name ?? void 0 - }); - table.columns.push(freeze2({ - dataType: rawColumn.type_name, - dataTypeSchema: rawColumn.type_schema_name ?? void 0, - hasDefaultValue: rawColumn.column_default_object_id > 0 || rawColumn.column_generated_always_type !== "NOT_APPLICABLE" || rawColumn.column_is_identity || rawColumn.column_is_computed || rawColumn.column_is_rowguidcol, - isAutoIncrementing: rawColumn.column_is_identity, - isNullable: rawColumn.column_is_nullable && rawColumn.type_is_nullable, - name: rawColumn.column_name, - comment: rawColumn.column_comment ?? void 0 - })); - } - return Object.values(tableDictionary); - } - async getMetadata(options) { - return { - tables: await this.getTables(options) - }; - } - }; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mssql/mssql-query-compiler.js -var COLLATION_CHAR_REGEX, MssqlQueryCompiler; -var init_mssql_query_compiler = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mssql/mssql-query-compiler.js"() { - init_default_query_compiler(); - COLLATION_CHAR_REGEX = /^[a-z0-9_]$/i; - MssqlQueryCompiler = class extends DefaultQueryCompiler { - getCurrentParameterPlaceholder() { - return `@${this.numParameters}`; - } - visitOffset(node) { - super.visitOffset(node); - this.append(" rows"); - } - // mssql allows multi-column alterations in a single statement, - // but you can only use the command keyword/s once. - // it also doesn't support multiple kinds of commands in the same - // alter table statement, but we compile that anyway for the sake - // of WYSIWYG. - compileColumnAlterations(columnAlterations) { - const nodesByKind = {}; - for (const columnAlteration of columnAlterations) { - if (!nodesByKind[columnAlteration.kind]) { - nodesByKind[columnAlteration.kind] = []; - } - nodesByKind[columnAlteration.kind].push(columnAlteration); - } - let first = true; - if (nodesByKind.AddColumnNode) { - this.append("add "); - this.compileList(nodesByKind.AddColumnNode); - first = false; - } - if (nodesByKind.AlterColumnNode) { - if (!first) - this.append(", "); - this.compileList(nodesByKind.AlterColumnNode); - } - if (nodesByKind.DropColumnNode) { - if (!first) - this.append(", "); - this.append("drop column "); - this.compileList(nodesByKind.DropColumnNode); - } - if (nodesByKind.ModifyColumnNode) { - if (!first) - this.append(", "); - this.compileList(nodesByKind.ModifyColumnNode); - } - if (nodesByKind.RenameColumnNode) { - if (!first) - this.append(", "); - this.compileList(nodesByKind.RenameColumnNode); - } - } - visitAddColumn(node) { - this.visitNode(node.column); - } - visitDropColumn(node) { - this.visitNode(node.column); - } - visitMergeQuery(node) { - super.visitMergeQuery(node); - this.append(";"); - } - visitCollate(node) { - this.append("collate "); - const { name } = node.collation; - for (const char2 of name) { - if (!COLLATION_CHAR_REGEX.test(char2)) { - throw new Error(`Invalid collation: ${name}`); - } - } - this.append(name); - } - announcesNewColumnDataType() { - return false; - } - }; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mssql/mssql-dialect.js -var MssqlDialect; -var init_mssql_dialect = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dialect/mssql/mssql-dialect.js"() { - init_mssql_adapter(); - init_mssql_driver(); - init_mssql_introspector(); - init_mssql_query_compiler(); - MssqlDialect = class { - #config; - constructor(config3) { - this.#config = config3; - } - createDriver() { - return new MssqlDriver(this.#config); - } - createQueryCompiler() { - return new MssqlQueryCompiler(); - } - createAdapter() { - return new MssqlAdapter(); - } - createIntrospector(db) { - return new MssqlIntrospector(db); - } - }; - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-compiler/query-compiler.js -var init_query_compiler = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-compiler/query-compiler.js"() { - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/migration/file-migration-provider.js -var init_file_migration_provider = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/migration/file-migration-provider.js"() { - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/kysely-plugin.js -var init_kysely_plugin = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/kysely-plugin.js"() { - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/camel-case/camel-case-plugin.js -var init_camel_case_plugin = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/camel-case/camel-case-plugin.js"() { - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/deduplicate-joins/deduplicate-joins-plugin.js -var init_deduplicate_joins_plugin = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/deduplicate-joins/deduplicate-joins-plugin.js"() { - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/parse-json-results/parse-json-results-plugin.js -var init_parse_json_results_plugin = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/parse-json-results/parse-json-results-plugin.js"() { - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/handle-empty-in-lists/handle-empty-in-lists-plugin.js -var init_handle_empty_in_lists_plugin = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/handle-empty-in-lists/handle-empty-in-lists-plugin.js"() { - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/handle-empty-in-lists/handle-empty-in-lists.js -var init_handle_empty_in_lists = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/handle-empty-in-lists/handle-empty-in-lists.js"() { - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/constraint-node.js -var init_constraint_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/constraint-node.js"() { - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/operation-node.js -var init_operation_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/operation-node.js"() { - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/simple-reference-expression-node.js -var init_simple_reference_expression_node = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/simple-reference-expression-node.js"() { - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/column-type.js -var init_column_type = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/column-type.js"() { - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/explainable.js -var init_explainable = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/explainable.js"() { - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/streamable.js -var init_streamable = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/streamable.js"() { - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/infer-result.js -var init_infer_result = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/infer-result.js"() { - } -}); - -// node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/index.js -var init_esm = __esm({ - "node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/index.js"() { - init_kysely(); - init_query_creator(); - init_expression(); - init_expression_wrapper(); - init_where_interface(); - init_returning_interface(); - init_output_interface(); - init_having_interface(); - init_order_by_interface(); - init_select_query_builder(); - init_insert_query_builder(); - init_update_query_builder(); - init_delete_query_builder(); - init_no_result_error(); - init_join_builder(); - init_function_module(); - init_insert_result(); - init_delete_result(); - init_update_result(); - init_on_conflict_builder(); - init_aggregate_function_builder(); - init_case_builder(); - init_json_path_builder(); - init_merge_query_builder(); - init_merge_result(); - init_order_by_item_builder(); - init_raw_builder(); - init_sql3(); - init_query_executor(); - init_default_query_executor(); - init_noop_query_executor(); - init_query_executor_provider(); - init_default_query_compiler(); - init_compiled_query(); - init_schema5(); - init_create_table_builder(); - init_create_type_builder(); - init_drop_table_builder(); - init_drop_type_builder(); - init_create_index_builder(); - init_drop_index_builder(); - init_create_schema_builder(); - init_drop_schema_builder(); - init_column_definition_builder(); - init_foreign_key_constraint_builder(); - init_alter_table_builder(); - init_create_view_builder(); - init_refresh_materialized_view_builder(); - init_drop_view_builder(); - init_alter_column_builder(); - init_dynamic(); - init_dynamic_reference_builder(); - init_dynamic_table_builder(); - init_driver2(); - init_database_connection(); - init_connection_provider(); - init_default_connection_provider(); - init_single_connection_provider(); - init_dummy_driver(); - init_dialect2(); - init_dialect_adapter(); - init_dialect_adapter_base(); - init_database_introspector(); - init_sqlite_dialect(); - init_sqlite_dialect_config(); - init_sqlite_driver(); - init_postgres_query_compiler(); - init_postgres_introspector(); - init_postgres_adapter(); - init_mysql_dialect(); - init_mysql_dialect_config(); - init_mysql_driver(); - init_mysql_query_compiler(); - init_mysql_introspector(); - init_mysql_adapter(); - init_postgres_driver(); - init_postgres_dialect_config(); - init_postgres_dialect(); - init_sqlite_query_compiler(); - init_sqlite_introspector(); - init_sqlite_adapter(); - init_mssql_adapter(); - init_mssql_dialect_config(); - init_mssql_dialect(); - init_mssql_driver(); - init_mssql_introspector(); - init_mssql_query_compiler(); - init_default_query_compiler(); - init_query_compiler(); - init_migrator(); - init_file_migration_provider(); - init_kysely_plugin(); - init_camel_case_plugin(); - init_deduplicate_joins_plugin(); - init_with_schema_plugin(); - init_parse_json_results_plugin(); - init_handle_empty_in_lists_plugin(); - init_handle_empty_in_lists(); - init_add_column_node(); - init_add_constraint_node(); - init_add_index_node(); - init_aggregate_function_node(); - init_alias_node(); - init_alter_column_node(); - init_alter_table_node(); - init_and_node(); - init_binary_operation_node(); - init_case_node(); - init_cast_node(); - init_check_constraint_node(); - init_collate_node(); - init_column_definition_node(); - init_column_node(); - init_column_update_node(); - init_common_table_expression_name_node(); - init_common_table_expression_node(); - init_constraint_node(); - init_create_index_node(); - init_create_schema_node(); - init_create_table_node(); - init_create_type_node(); - init_create_view_node(); - init_refresh_materialized_view_node(); - init_data_type_node(); - init_default_insert_value_node(); - init_default_value_node(); - init_delete_query_node(); - init_drop_column_node(); - init_drop_constraint_node(); - init_drop_index_node(); - init_drop_schema_node(); - init_drop_table_node(); - init_drop_type_node(); - init_drop_view_node(); - init_explain_node(); - init_fetch_node(); - init_foreign_key_constraint_node(); - init_from_node(); - init_function_node(); - init_generated_node(); - init_group_by_item_node(); - init_group_by_node(); - init_having_node(); - init_identifier_node(); - init_insert_query_node(); - init_join_node(); - init_json_operator_chain_node(); - init_json_path_leg_node(); - init_json_path_node(); - init_json_reference_node(); - init_limit_node(); - init_list_node(); - init_matched_node(); - init_merge_query_node(); - init_modify_column_node(); - init_offset_node(); - init_on_conflict_node(); - init_on_duplicate_key_node(); - init_on_node(); - init_operation_node_source(); - init_operation_node_transformer(); - init_operation_node_visitor(); - init_operation_node(); - init_operator_node(); - init_or_action_node(); - init_or_node(); - init_order_by_item_node(); - init_order_by_node(); - init_output_node(); - init_over_node(); - init_parens_node(); - init_partition_by_item_node(); - init_partition_by_node(); - init_primary_key_constraint_node(); - init_primitive_value_list_node(); - init_query_node(); - init_raw_node(); - init_reference_node(); - init_references_node(); - init_rename_column_node(); - init_rename_constraint_node(); - init_returning_node(); - init_schemable_identifier_node(); - init_select_all_node(); - init_select_modifier_node(); - init_select_query_node(); - init_selection_node(); - init_set_operation_node(); - init_simple_reference_expression_node(); - init_table_node(); - init_top_node(); - init_tuple_node(); - init_unary_operation_node(); - init_unique_constraint_node(); - init_update_query_node(); - init_using_node(); - init_value_list_node(); - init_value_node(); - init_values_node(); - init_when_node(); - init_where_node(); - init_with_node(); - init_column_type(); - init_compilable(); - init_explainable(); - init_streamable(); - init_log(); - init_infer_result(); - } -}); - -// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/adapters/kysely-adapter/bun-sqlite-dialect.mjs -var bun_sqlite_dialect_exports = {}; -__export(bun_sqlite_dialect_exports, { - BunSqliteDialect: () => BunSqliteDialect -}); -var BunSqliteAdapter, BunSqliteDriver, BunSqliteConnection, ConnectionMutex2, BunSqliteIntrospector, BunSqliteQueryCompiler, BunSqliteDialect; -var init_bun_sqlite_dialect = __esm({ - "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/adapters/kysely-adapter/bun-sqlite-dialect.mjs"() { - init_esm(); - BunSqliteAdapter = class { - get supportsCreateIfNotExists() { - return true; - } - get supportsTransactionalDdl() { - return false; - } - get supportsReturning() { - return true; - } - async acquireMigrationLock() { - } - async releaseMigrationLock() { - } - get supportsOutput() { - return true; - } - }; - BunSqliteDriver = class { - #config; - #connectionMutex = new ConnectionMutex2(); - #db; - #connection; - constructor(config3) { - this.#config = { ...config3 }; - } - async init() { - this.#db = this.#config.database; - this.#connection = new BunSqliteConnection(this.#db); - if (this.#config.onCreateConnection) await this.#config.onCreateConnection(this.#connection); - } - async acquireConnection() { - await this.#connectionMutex.lock(); - return this.#connection; - } - async beginTransaction(connection2) { - await connection2.executeQuery(CompiledQuery.raw("begin")); - } - async commitTransaction(connection2) { - await connection2.executeQuery(CompiledQuery.raw("commit")); - } - async rollbackTransaction(connection2) { - await connection2.executeQuery(CompiledQuery.raw("rollback")); - } - async releaseConnection() { - this.#connectionMutex.unlock(); - } - async destroy() { - this.#db?.close(); - } - }; - BunSqliteConnection = class { - #db; - constructor(db) { - this.#db = db; - } - executeQuery(compiledQuery) { - const { sql: sql$1, parameters } = compiledQuery; - const stmt = this.#db.prepare(sql$1); - return Promise.resolve({ rows: stmt.all(parameters) }); - } - async *streamQuery() { - throw new Error("Streaming query is not supported by SQLite driver."); - } - }; - ConnectionMutex2 = class { - #promise; - #resolve; - async lock() { - while (await this.#promise) await this.#promise; - this.#promise = new Promise((resolve4) => { - this.#resolve = resolve4; - }); - } - unlock() { - const resolve4 = this.#resolve; - this.#promise = void 0; - this.#resolve = void 0; - resolve4?.(); - } - }; - BunSqliteIntrospector = class { - #db; - constructor(db) { - this.#db = db; - } - async getSchemas() { - return []; - } - async getTables(options = { withInternalKyselyTables: false }) { - let query = this.#db.selectFrom("sqlite_schema").where("type", "=", "table").where("name", "not like", "sqlite_%").select("name").$castTo(); - if (!options.withInternalKyselyTables) query = query.where("name", "!=", DEFAULT_MIGRATION_TABLE).where("name", "!=", DEFAULT_MIGRATION_LOCK_TABLE); - const tables = await query.execute(); - return Promise.all(tables.map(({ name }) => this.#getTableMetadata(name))); - } - async getMetadata(options) { - return { tables: await this.getTables(options) }; - } - async #getTableMetadata(table) { - const db = this.#db; - const autoIncrementCol = (await db.selectFrom("sqlite_master").where("name", "=", table).select("sql").$castTo().execute())[0]?.sql?.split(/[\(\),]/)?.find((it) => it.toLowerCase().includes("autoincrement"))?.split(/\s+/)?.[0]?.replace(/["`]/g, ""); - return { - name: table, - columns: (await db.selectFrom(sql2`pragma_table_info(${table})`.as("table_info")).select([ - "name", - "type", - "notnull", - "dflt_value" - ]).execute()).map((col) => ({ - name: col.name, - dataType: col.type, - isNullable: !col.notnull, - isAutoIncrementing: col.name === autoIncrementCol, - hasDefaultValue: col.dflt_value != null - })), - isView: true - }; - } - }; - BunSqliteQueryCompiler = class extends DefaultQueryCompiler { - getCurrentParameterPlaceholder() { - return "?"; - } - getLeftIdentifierWrapper() { - return '"'; - } - getRightIdentifierWrapper() { - return '"'; - } - getAutoIncrement() { - return "autoincrement"; - } - }; - BunSqliteDialect = class { - #config; - constructor(config3) { - this.#config = { ...config3 }; - } - createDriver() { - return new BunSqliteDriver(this.#config); - } - createQueryCompiler() { - return new BunSqliteQueryCompiler(); - } - createAdapter() { - return new BunSqliteAdapter(); - } - createIntrospector(db) { - return new BunSqliteIntrospector(db); - } - }; - } -}); - -// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/adapters/kysely-adapter/node-sqlite-dialect.mjs -var node_sqlite_dialect_exports = {}; -__export(node_sqlite_dialect_exports, { - NodeSqliteDialect: () => NodeSqliteDialect -}); -var NodeSqliteAdapter, NodeSqliteDriver, NodeSqliteConnection, ConnectionMutex3, NodeSqliteIntrospector, NodeSqliteQueryCompiler, NodeSqliteDialect; -var init_node_sqlite_dialect = __esm({ - "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/adapters/kysely-adapter/node-sqlite-dialect.mjs"() { - init_esm(); - NodeSqliteAdapter = class { - get supportsCreateIfNotExists() { - return true; - } - get supportsTransactionalDdl() { - return false; - } - get supportsReturning() { - return true; - } - async acquireMigrationLock() { - } - async releaseMigrationLock() { - } - get supportsOutput() { - return true; - } - }; - NodeSqliteDriver = class { - #config; - #connectionMutex = new ConnectionMutex3(); - #db; - #connection; - constructor(config3) { - this.#config = { ...config3 }; - } - async init() { - this.#db = this.#config.database; - this.#connection = new NodeSqliteConnection(this.#db); - if (this.#config.onCreateConnection) await this.#config.onCreateConnection(this.#connection); - } - async acquireConnection() { - await this.#connectionMutex.lock(); - return this.#connection; - } - async beginTransaction(connection2) { - await connection2.executeQuery(CompiledQuery.raw("begin")); - } - async commitTransaction(connection2) { - await connection2.executeQuery(CompiledQuery.raw("commit")); - } - async rollbackTransaction(connection2) { - await connection2.executeQuery(CompiledQuery.raw("rollback")); - } - async releaseConnection() { - this.#connectionMutex.unlock(); - } - async destroy() { - this.#db?.close(); - } - }; - NodeSqliteConnection = class { - #db; - constructor(db) { - this.#db = db; - } - executeQuery(compiledQuery) { - const { sql: sql$1, parameters } = compiledQuery; - const rows = this.#db.prepare(sql$1).all(...parameters); - return Promise.resolve({ rows }); - } - async *streamQuery() { - throw new Error("Streaming query is not supported by SQLite driver."); - } - }; - ConnectionMutex3 = class { - #promise; - #resolve; - async lock() { - while (await this.#promise) await this.#promise; - this.#promise = new Promise((resolve4) => { - this.#resolve = resolve4; - }); - } - unlock() { - const resolve4 = this.#resolve; - this.#promise = void 0; - this.#resolve = void 0; - resolve4?.(); - } - }; - NodeSqliteIntrospector = class { - #db; - constructor(db) { - this.#db = db; - } - async getSchemas() { - return []; - } - async getTables(options = { withInternalKyselyTables: false }) { - let query = this.#db.selectFrom("sqlite_schema").where("type", "=", "table").where("name", "not like", "sqlite_%").select("name").$castTo(); - if (!options.withInternalKyselyTables) query = query.where("name", "!=", DEFAULT_MIGRATION_TABLE).where("name", "!=", DEFAULT_MIGRATION_LOCK_TABLE); - const tables = await query.execute(); - return Promise.all(tables.map(({ name }) => this.#getTableMetadata(name))); - } - async getMetadata(options) { - return { tables: await this.getTables(options) }; - } - async #getTableMetadata(table) { - const db = this.#db; - const autoIncrementCol = (await db.selectFrom("sqlite_master").where("name", "=", table).select("sql").$castTo().execute())[0]?.sql?.split(/[\(\),]/)?.find((it) => it.toLowerCase().includes("autoincrement"))?.split(/\s+/)?.[0]?.replace(/["`]/g, ""); - return { - name: table, - columns: (await db.selectFrom(sql2`pragma_table_info(${table})`.as("table_info")).select([ - "name", - "type", - "notnull", - "dflt_value" - ]).execute()).map((col) => ({ - name: col.name, - dataType: col.type, - isNullable: !col.notnull, - isAutoIncrementing: col.name === autoIncrementCol, - hasDefaultValue: col.dflt_value != null - })), - isView: true - }; - } - }; - NodeSqliteQueryCompiler = class extends DefaultQueryCompiler { - getCurrentParameterPlaceholder() { - return "?"; - } - getLeftIdentifierWrapper() { - return '"'; - } - getRightIdentifierWrapper() { - return '"'; - } - getAutoIncrement() { - return "autoincrement"; - } - }; - NodeSqliteDialect = class { - #config; - constructor(config3) { - this.#config = { ...config3 }; - } - createDriver() { - return new NodeSqliteDriver(this.#config); - } - createQueryCompiler() { - return new NodeSqliteQueryCompiler(); - } - createAdapter() { - return new NodeSqliteAdapter(); - } - createIntrospector(db) { - return new NodeSqliteIntrospector(db); - } - }; - } -}); - -// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/adapters/kysely-adapter/dialect.mjs -function getKyselyDatabaseType(db) { - if (!db) return null; - if ("dialect" in db) return getKyselyDatabaseType(db.dialect); - if ("createDriver" in db) { - if (db instanceof SqliteDialect) return "sqlite"; - if (db instanceof MysqlDialect) return "mysql"; - if (db instanceof PostgresDialect) return "postgres"; - if (db instanceof MssqlDialect) return "mssql"; - } - if ("aggregate" in db) return "sqlite"; - if ("getConnection" in db) return "mysql"; - if ("connect" in db) return "postgres"; - if ("fileControl" in db) return "sqlite"; - if ("open" in db && "close" in db && "prepare" in db) return "sqlite"; - return null; -} -var createKyselyAdapter; -var init_dialect3 = __esm({ - "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/adapters/kysely-adapter/dialect.mjs"() { - init_esm(); - createKyselyAdapter = async (config3) => { - const db = config3.database; - if (!db) return { - kysely: null, - databaseType: null, - transaction: void 0 - }; - if ("db" in db) return { - kysely: db.db, - databaseType: db.type, - transaction: db.transaction - }; - if ("dialect" in db) return { - kysely: new Kysely({ dialect: db.dialect }), - databaseType: db.type, - transaction: db.transaction - }; - let dialect = void 0; - const databaseType = getKyselyDatabaseType(db); - if ("createDriver" in db) dialect = db; - if ("aggregate" in db && !("createSession" in db)) dialect = new SqliteDialect({ database: db }); - if ("getConnection" in db) dialect = new MysqlDialect(db); - if ("connect" in db) dialect = new PostgresDialect({ pool: db }); - if ("fileControl" in db) { - const { BunSqliteDialect: BunSqliteDialect2 } = await Promise.resolve().then(() => (init_bun_sqlite_dialect(), bun_sqlite_dialect_exports)); - dialect = new BunSqliteDialect2({ database: db }); - } - if ("createSession" in db) { - let DatabaseSync = void 0; - try { - const nodeSqlite = "node:sqlite"; - ({ DatabaseSync } = await import( - /* @vite-ignore */ - /* webpackIgnore: true */ - nodeSqlite - )); - } catch (error50) { - if (error50 !== null && typeof error50 === "object" && "code" in error50 && error50.code !== "ERR_UNKNOWN_BUILTIN_MODULE") throw error50; - } - if (DatabaseSync && db instanceof DatabaseSync) { - const { NodeSqliteDialect: NodeSqliteDialect2 } = await Promise.resolve().then(() => (init_node_sqlite_dialect(), node_sqlite_dialect_exports)); - dialect = new NodeSqliteDialect2({ database: db }); - } - } - return { - kysely: dialect ? new Kysely({ dialect }) : null, - databaseType, - transaction: void 0 - }; - }; - } -}); - -// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/adapters/kysely-adapter/kysely-adapter.mjs -var kyselyAdapter; -var init_kysely_adapter = __esm({ - "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/adapters/kysely-adapter/kysely-adapter.mjs"() { - init_esm(); - init_adapter(); - kyselyAdapter = (db, config3) => { - let lazyOptions = null; - const createCustomAdapter = (db$1) => { - return ({ getFieldName, schema: schema2, getDefaultFieldName, getDefaultModelName, getFieldAttributes, getModelName }) => { - const selectAllJoins = (join4) => { - const allSelects = []; - const allSelectsStr = []; - if (join4) for (const [joinModel, _] of Object.entries(join4)) { - const fields = schema2[getDefaultModelName(joinModel)]?.fields; - const [_joinModelSchema, joinModelName] = joinModel.includes(".") ? joinModel.split(".") : [void 0, joinModel]; - if (!fields) continue; - fields.id = { type: "string" }; - for (const [field, fieldAttr] of Object.entries(fields)) { - allSelects.push(sql2`${sql2.ref(`join_${joinModelName}`)}.${sql2.ref(fieldAttr.fieldName || field)} as ${sql2.ref(`_joined_${joinModelName}_${fieldAttr.fieldName || field}`)}`); - allSelectsStr.push({ - joinModel, - joinModelRef: joinModelName, - fieldName: fieldAttr.fieldName || field - }); - } - } - return { - allSelectsStr, - allSelects - }; - }; - const withReturning = async (values2, builder, model, where) => { - let res; - if (config3?.type === "mysql") { - await builder.execute(); - const field = values2.id ? "id" : where.length > 0 && where[0]?.field ? where[0].field : "id"; - if (!values2.id && where.length === 0) { - res = await db$1.selectFrom(model).selectAll().orderBy(getFieldName({ - model, - field - }), "desc").limit(1).executeTakeFirst(); - return res; - } - const value = values2[field] || where[0]?.value; - res = await db$1.selectFrom(model).selectAll().orderBy(getFieldName({ - model, - field - }), "desc").where(getFieldName({ - model, - field - }), "=", value).limit(1).executeTakeFirst(); - return res; - } - if (config3?.type === "mssql") { - res = await builder.outputAll("inserted").executeTakeFirst(); - return res; - } - res = await builder.returningAll().executeTakeFirst(); - return res; - }; - function convertWhereClause(model, w5) { - if (!w5) return { - and: null, - or: null - }; - const conditions = { - and: [], - or: [] - }; - w5.forEach((condition) => { - const { field: _field, value: _value, operator = "=", connector = "AND" } = condition; - const value = _value; - const field = getFieldName({ - model, - field: _field - }); - const expr = (eb) => { - const f5 = `${model}.${field}`; - if (operator.toLowerCase() === "in") return eb(f5, "in", Array.isArray(value) ? value : [value]); - if (operator.toLowerCase() === "not_in") return eb(f5, "not in", Array.isArray(value) ? value : [value]); - if (operator === "contains") return eb(f5, "like", `%${value}%`); - if (operator === "starts_with") return eb(f5, "like", `${value}%`); - if (operator === "ends_with") return eb(f5, "like", `%${value}`); - if (operator === "eq") return eb(f5, "=", value); - if (operator === "ne") return eb(f5, "<>", value); - if (operator === "gt") return eb(f5, ">", value); - if (operator === "gte") return eb(f5, ">=", value); - if (operator === "lt") return eb(f5, "<", value); - if (operator === "lte") return eb(f5, "<=", value); - return eb(f5, operator, value); - }; - if (connector === "OR") conditions.or.push(expr); - else conditions.and.push(expr); - }); - return { - and: conditions.and.length ? conditions.and : null, - or: conditions.or.length ? conditions.or : null - }; - } - function processJoinedResults(rows, joinConfig, allSelectsStr) { - if (!joinConfig || !rows.length) return rows; - const groupedByMainId = /* @__PURE__ */ new Map(); - for (const currentRow of rows) { - const mainModelFields = {}; - const joinedModelFields = {}; - for (const [joinModel] of Object.entries(joinConfig)) joinedModelFields[getModelName(joinModel)] = {}; - for (const [key, value] of Object.entries(currentRow)) { - const keyStr = String(key); - let assigned = false; - for (const { joinModel, fieldName, joinModelRef } of allSelectsStr) if (keyStr === `_joined_${joinModelRef}_${fieldName}`) { - joinedModelFields[getModelName(joinModel)][getFieldName({ - model: joinModel, - field: fieldName - })] = value; - assigned = true; - break; - } - if (!assigned) mainModelFields[key] = value; - } - const mainId = mainModelFields.id; - if (!mainId) continue; - if (!groupedByMainId.has(mainId)) { - const entry$1 = { ...mainModelFields }; - for (const [joinModel, joinAttr] of Object.entries(joinConfig)) entry$1[getModelName(joinModel)] = joinAttr.relation === "one-to-one" ? null : []; - groupedByMainId.set(mainId, entry$1); - } - const entry = groupedByMainId.get(mainId); - for (const [joinModel, joinAttr] of Object.entries(joinConfig)) { - const isUnique = joinAttr.relation === "one-to-one"; - const limit = joinAttr.limit ?? 100; - const joinedObj = joinedModelFields[getModelName(joinModel)]; - const hasData = joinedObj && Object.keys(joinedObj).length > 0 && Object.values(joinedObj).some((value) => value !== null && value !== void 0); - if (isUnique) entry[getModelName(joinModel)] = hasData ? joinedObj : null; - else { - const joinModelName = getModelName(joinModel); - if (Array.isArray(entry[joinModelName]) && hasData) { - if (entry[joinModelName].length >= limit) continue; - const idFieldName = getFieldName({ - model: joinModel, - field: "id" - }); - const joinedId = joinedObj[idFieldName]; - if (joinedId) { - if (!entry[joinModelName].some((item) => item[idFieldName] === joinedId) && entry[joinModelName].length < limit) entry[joinModelName].push(joinedObj); - } else if (entry[joinModelName].length < limit) entry[joinModelName].push(joinedObj); - } - } - } - } - const result = Array.from(groupedByMainId.values()); - for (const entry of result) for (const [joinModel, joinAttr] of Object.entries(joinConfig)) if (joinAttr.relation !== "one-to-one") { - const joinModelName = getModelName(joinModel); - if (Array.isArray(entry[joinModelName])) { - const limit = joinAttr.limit ?? 100; - if (entry[joinModelName].length > limit) entry[joinModelName] = entry[joinModelName].slice(0, limit); - } - } - return result; - } - return { - async create({ data: data2, model }) { - return await withReturning(data2, db$1.insertInto(model).values(data2), model, []); - }, - async findOne({ model, where, select: select2, join: join4 }) { - const { and: and2, or: or3 } = convertWhereClause(model, where); - let query = db$1.selectFrom((eb) => { - let b6 = eb.selectFrom(model); - if (and2) b6 = b6.where((eb$1) => eb$1.and(and2.map((expr) => expr(eb$1)))); - if (or3) b6 = b6.where((eb$1) => eb$1.or(or3.map((expr) => expr(eb$1)))); - return b6.selectAll().as("primary"); - }).selectAll("primary"); - if (join4) for (const [joinModel, joinAttr] of Object.entries(join4)) { - const [_joinModelSchema, joinModelName] = joinModel.includes(".") ? joinModel.split(".") : [void 0, joinModel]; - query = query.leftJoin(`${joinModel} as join_${joinModelName}`, (join$1) => join$1.onRef(`join_${joinModelName}.${joinAttr.on.to}`, "=", `primary.${joinAttr.on.from}`)); - } - const { allSelectsStr, allSelects } = selectAllJoins(join4); - query = query.select(allSelects); - const res = await query.execute(); - if (!res || !Array.isArray(res) || res.length === 0) return null; - const row = res[0]; - if (join4) return processJoinedResults(res, join4, allSelectsStr)[0]; - return row; - }, - async findMany({ model, where, limit, offset, sortBy, join: join4 }) { - const { and: and2, or: or3 } = convertWhereClause(model, where); - let query = db$1.selectFrom((eb) => { - let b6 = eb.selectFrom(model); - if (config3?.type === "mssql") { - if (offset !== void 0) { - if (!sortBy) b6 = b6.orderBy(getFieldName({ - model, - field: "id" - })); - b6 = b6.offset(offset).fetch(limit || 100); - } else if (limit !== void 0) b6 = b6.top(limit); - } else { - if (limit !== void 0) b6 = b6.limit(limit); - if (offset !== void 0) b6 = b6.offset(offset); - } - if (sortBy?.field) b6 = b6.orderBy(`${getFieldName({ - model, - field: sortBy.field - })}`, sortBy.direction); - if (and2) b6 = b6.where((eb$1) => eb$1.and(and2.map((expr) => expr(eb$1)))); - if (or3) b6 = b6.where((eb$1) => eb$1.or(or3.map((expr) => expr(eb$1)))); - return b6.selectAll().as("primary"); - }).selectAll("primary"); - if (join4) for (const [joinModel, joinAttr] of Object.entries(join4)) { - const [_joinModelSchema, joinModelName] = joinModel.includes(".") ? joinModel.split(".") : [void 0, joinModel]; - query = query.leftJoin(`${joinModel} as join_${joinModelName}`, (join$1) => join$1.onRef(`join_${joinModelName}.${joinAttr.on.to}`, "=", `primary.${joinAttr.on.from}`)); - } - const { allSelectsStr, allSelects } = selectAllJoins(join4); - query = query.select(allSelects); - if (sortBy?.field) query = query.orderBy(`${getFieldName({ - model, - field: sortBy.field - })}`, sortBy.direction); - const res = await query.execute(); - if (!res) return []; - if (join4) return processJoinedResults(res, join4, allSelectsStr); - return res; - }, - async update({ model, where, update: values2 }) { - const { and: and2, or: or3 } = convertWhereClause(model, where); - let query = db$1.updateTable(model).set(values2); - if (and2) query = query.where((eb) => eb.and(and2.map((expr) => expr(eb)))); - if (or3) query = query.where((eb) => eb.or(or3.map((expr) => expr(eb)))); - return await withReturning(values2, query, model, where); - }, - async updateMany({ model, where, update: values2 }) { - const { and: and2, or: or3 } = convertWhereClause(model, where); - let query = db$1.updateTable(model).set(values2); - if (and2) query = query.where((eb) => eb.and(and2.map((expr) => expr(eb)))); - if (or3) query = query.where((eb) => eb.or(or3.map((expr) => expr(eb)))); - const res = (await query.executeTakeFirst()).numUpdatedRows; - return res > Number.MAX_SAFE_INTEGER ? Number.MAX_SAFE_INTEGER : Number(res); - }, - async count({ model, where }) { - const { and: and2, or: or3 } = convertWhereClause(model, where); - let query = db$1.selectFrom(model).select(db$1.fn.count("id").as("count")); - if (and2) query = query.where((eb) => eb.and(and2.map((expr) => expr(eb)))); - if (or3) query = query.where((eb) => eb.or(or3.map((expr) => expr(eb)))); - const res = await query.execute(); - if (typeof res[0].count === "number") return res[0].count; - if (typeof res[0].count === "bigint") return Number(res[0].count); - return parseInt(res[0].count); - }, - async delete({ model, where }) { - const { and: and2, or: or3 } = convertWhereClause(model, where); - let query = db$1.deleteFrom(model); - if (and2) query = query.where((eb) => eb.and(and2.map((expr) => expr(eb)))); - if (or3) query = query.where((eb) => eb.or(or3.map((expr) => expr(eb)))); - await query.execute(); - }, - async deleteMany({ model, where }) { - const { and: and2, or: or3 } = convertWhereClause(model, where); - let query = db$1.deleteFrom(model); - if (and2) query = query.where((eb) => eb.and(and2.map((expr) => expr(eb)))); - if (or3) query = query.where((eb) => eb.or(or3.map((expr) => expr(eb)))); - const res = (await query.executeTakeFirst()).numDeletedRows; - return res > Number.MAX_SAFE_INTEGER ? Number.MAX_SAFE_INTEGER : Number(res); - }, - options: config3 - }; - }; - }; - let adapterOptions = null; - adapterOptions = { - config: { - adapterId: "kysely", - adapterName: "Kysely Adapter", - usePlural: config3?.usePlural, - debugLogs: config3?.debugLogs, - supportsBooleans: config3?.type === "sqlite" || config3?.type === "mssql" || config3?.type === "mysql" || !config3?.type ? false : true, - supportsDates: config3?.type === "sqlite" || config3?.type === "mssql" || !config3?.type ? false : true, - supportsJSON: config3?.type === "postgres" ? true : false, - supportsArrays: false, - supportsUUIDs: config3?.type === "postgres" ? true : false, - transaction: config3?.transaction ? (cb) => db.transaction().execute((trx) => { - return cb(createAdapterFactory({ - config: adapterOptions.config, - adapter: createCustomAdapter(trx) - })(lazyOptions)); - }) : false - }, - adapter: createCustomAdapter(db) - }; - const adapter = createAdapterFactory(adapterOptions); - return (options) => { - lazyOptions = options; - return adapter(options); - }; - }; - } -}); - -// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/adapters/kysely-adapter/index.mjs -var kysely_adapter_exports = {}; -__export(kysely_adapter_exports, { - createKyselyAdapter: () => createKyselyAdapter, - getKyselyDatabaseType: () => getKyselyDatabaseType, - kyselyAdapter: () => kyselyAdapter -}); -var init_kysely_adapter2 = __esm({ - "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/adapters/kysely-adapter/index.mjs"() { - init_dialect3(); - init_kysely_adapter(); - } -}); - -// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/db/adapter-kysely.mjs -async function getAdapter(options) { - return getBaseAdapter(options, async (opts) => { - const { createKyselyAdapter: createKyselyAdapter2 } = await Promise.resolve().then(() => (init_kysely_adapter2(), kysely_adapter_exports)); - const { kysely, databaseType, transaction } = await createKyselyAdapter2(opts); - if (!kysely) throw new BetterAuthError("Failed to initialize database adapter"); - const { kyselyAdapter: kyselyAdapter2 } = await Promise.resolve().then(() => (init_kysely_adapter2(), kysely_adapter_exports)); - return kyselyAdapter2(kysely, { - type: databaseType || "sqlite", - debugLogs: opts.database && "debugLogs" in opts.database ? opts.database.debugLogs : false, - transaction - })(opts); - }); -} -var init_adapter_kysely = __esm({ - "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/db/adapter-kysely.mjs"() { - init_adapter_base(); - init_error(); - } -}); - -// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/db/field.mjs -var createFieldAttribute; -var init_field = __esm({ - "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/db/field.mjs"() { - createFieldAttribute = (type, config3) => { - return { - type, - ...config3 - }; - }; - } -}); - -// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/db/field-converter.mjs -function convertToDB(fields, values2) { - const result = values2.id ? { id: values2.id } : {}; - for (const key in fields) { - const field = fields[key]; - const value = values2[key]; - if (value === void 0) continue; - result[field.fieldName || key] = value; - } - return result; -} -function convertFromDB(fields, values2) { - if (!values2) return null; - const result = { id: values2.id }; - for (const [key, value] of Object.entries(fields)) result[key] = values2[value.fieldName || key]; - return result; -} -var init_field_converter = __esm({ - "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/db/field-converter.mjs"() { - } -}); - -// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/db/with-hooks.mjs -function getWithHooks(adapter, ctx) { - const hooks = ctx.hooks; - async function createWithHooks(data2, model, customCreateFn) { - const context = await getCurrentAuthContext().catch(() => null); - let actualData = data2; - for (const hook of hooks || []) { - const toRun = hook[model]?.create?.before; - if (toRun) { - const result = await toRun(actualData, context); - if (result === false) return null; - if (typeof result === "object" && "data" in result) actualData = { - ...actualData, - ...result.data - }; - } - } - const customCreated = customCreateFn ? await customCreateFn.fn(actualData) : null; - const created = !customCreateFn || customCreateFn.executeMainFn ? await (await getCurrentAdapter(adapter)).create({ - model, - data: actualData, - forceAllowId: true - }) : customCreated; - for (const hook of hooks || []) { - const toRun = hook[model]?.create?.after; - if (toRun) await toRun(created, context); - } - return created; - } - async function updateWithHooks(data2, where, model, customUpdateFn) { - const context = await getCurrentAuthContext().catch(() => null); - let actualData = data2; - for (const hook of hooks || []) { - const toRun = hook[model]?.update?.before; - if (toRun) { - const result = await toRun(data2, context); - if (result === false) return null; - if (typeof result === "object" && "data" in result) actualData = { - ...actualData, - ...result.data - }; - } - } - const customUpdated = customUpdateFn ? await customUpdateFn.fn(actualData) : null; - const updated = !customUpdateFn || customUpdateFn.executeMainFn ? await (await getCurrentAdapter(adapter)).update({ - model, - update: actualData, - where - }) : customUpdated; - for (const hook of hooks || []) { - const toRun = hook[model]?.update?.after; - if (toRun) await toRun(updated, context); - } - return updated; - } - async function updateManyWithHooks(data2, where, model, customUpdateFn) { - const context = await getCurrentAuthContext().catch(() => null); - let actualData = data2; - for (const hook of hooks || []) { - const toRun = hook[model]?.update?.before; - if (toRun) { - const result = await toRun(data2, context); - if (result === false) return null; - if (typeof result === "object" && "data" in result) actualData = { - ...actualData, - ...result.data - }; - } - } - const customUpdated = customUpdateFn ? await customUpdateFn.fn(actualData) : null; - const updated = !customUpdateFn || customUpdateFn.executeMainFn ? await (await getCurrentAdapter(adapter)).updateMany({ - model, - update: actualData, - where - }) : customUpdated; - for (const hook of hooks || []) { - const toRun = hook[model]?.update?.after; - if (toRun) await toRun(updated, context); - } - return updated; - } - async function deleteWithHooks(where, model, customDeleteFn) { - const context = await getCurrentAuthContext().catch(() => null); - let entityToDelete = null; - try { - entityToDelete = (await (await getCurrentAdapter(adapter)).findMany({ - model, - where, - limit: 1 - }))[0] || null; - } catch { - } - if (entityToDelete) for (const hook of hooks || []) { - const toRun = hook[model]?.delete?.before; - if (toRun) { - if (await toRun(entityToDelete, context) === false) return null; - } - } - const customDeleted = customDeleteFn ? await customDeleteFn.fn(where) : null; - const deleted = !customDeleteFn || customDeleteFn.executeMainFn ? await (await getCurrentAdapter(adapter)).delete({ - model, - where - }) : customDeleted; - if (entityToDelete) for (const hook of hooks || []) { - const toRun = hook[model]?.delete?.after; - if (toRun) await toRun(entityToDelete, context); - } - return deleted; - } - async function deleteManyWithHooks(where, model, customDeleteFn) { - const context = await getCurrentAuthContext().catch(() => null); - let entitiesToDelete = []; - try { - entitiesToDelete = await (await getCurrentAdapter(adapter)).findMany({ - model, - where - }); - } catch { - } - for (const entity of entitiesToDelete) for (const hook of hooks || []) { - const toRun = hook[model]?.delete?.before; - if (toRun) { - if (await toRun(entity, context) === false) return null; - } - } - const customDeleted = customDeleteFn ? await customDeleteFn.fn(where) : null; - const deleted = !customDeleteFn || customDeleteFn.executeMainFn ? await (await getCurrentAdapter(adapter)).deleteMany({ - model, - where - }) : customDeleted; - for (const entity of entitiesToDelete) for (const hook of hooks || []) { - const toRun = hook[model]?.delete?.after; - if (toRun) await toRun(entity, context); - } - return deleted; - } - return { - createWithHooks, - updateWithHooks, - updateManyWithHooks, - deleteWithHooks, - deleteManyWithHooks - }; -} -var init_with_hooks = __esm({ - "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/db/with-hooks.mjs"() { - init_context2(); - } -}); - -// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/db/internal-adapter.mjs -var createInternalAdapter; -var init_internal_adapter = __esm({ - "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/db/internal-adapter.mjs"() { - init_date2(); - init_get_request_ip(); - init_schema4(); - init_with_hooks(); - init_context2(); - init_utils7(); - createInternalAdapter = (adapter, ctx) => { - const logger4 = ctx.logger; - const options = ctx.options; - const secondaryStorage = options.secondaryStorage; - const sessionExpiration = options.session?.expiresIn || 3600 * 24 * 7; - const { createWithHooks, updateWithHooks, updateManyWithHooks, deleteWithHooks, deleteManyWithHooks } = getWithHooks(adapter, ctx); - async function refreshUserSessions(user) { - if (!secondaryStorage) return; - const listRaw = await secondaryStorage.get(`active-sessions-${user.id}`); - if (!listRaw) return; - const now2 = Date.now(); - const validSessions = (safeJSONParse(listRaw) || []).filter((s5) => s5.expiresAt > now2); - await Promise.all(validSessions.map(async ({ token }) => { - const cached4 = await secondaryStorage.get(token); - if (!cached4) return; - const parsed = safeJSONParse(cached4); - if (!parsed) return; - const sessionTTL = Math.max(Math.floor(new Date(parsed.session.expiresAt).getTime() - now2) / 1e3, 0); - await secondaryStorage.set(token, JSON.stringify({ - session: parsed.session, - user - }), Math.floor(sessionTTL)); - })); - } - return { - createOAuthUser: async (user, account) => { - return runWithTransaction(adapter, async () => { - const createdUser = await createWithHooks({ - createdAt: /* @__PURE__ */ new Date(), - updatedAt: /* @__PURE__ */ new Date(), - ...user - }, "user", void 0); - return { - user: createdUser, - account: await createWithHooks({ - ...account, - userId: createdUser.id, - createdAt: /* @__PURE__ */ new Date(), - updatedAt: /* @__PURE__ */ new Date() - }, "account", void 0) - }; - }); - }, - createUser: async (user) => { - return await createWithHooks({ - createdAt: /* @__PURE__ */ new Date(), - updatedAt: /* @__PURE__ */ new Date(), - ...user, - email: user.email?.toLowerCase() - }, "user", void 0); - }, - createAccount: async (account) => { - return await createWithHooks({ - createdAt: /* @__PURE__ */ new Date(), - updatedAt: /* @__PURE__ */ new Date(), - ...account - }, "account", void 0); - }, - listSessions: async (userId) => { - if (secondaryStorage) { - const currentList = await secondaryStorage.get(`active-sessions-${userId}`); - if (!currentList) return []; - const list2 = safeJSONParse(currentList) || []; - const now2 = Date.now(); - const seenTokens = /* @__PURE__ */ new Set(); - const sessions = []; - for (const { token, expiresAt } of list2) { - if (expiresAt <= now2 || seenTokens.has(token)) continue; - seenTokens.add(token); - const data2 = await secondaryStorage.get(token); - if (!data2) continue; - try { - const parsed = typeof data2 === "string" ? JSON.parse(data2) : data2; - if (!parsed?.session) continue; - sessions.push(parseSessionOutput(ctx.options, { - ...parsed.session, - expiresAt: new Date(parsed.session.expiresAt) - })); - } catch { - continue; - } - } - return sessions; - } - return await (await getCurrentAdapter(adapter)).findMany({ - model: "session", - where: [{ - field: "userId", - value: userId - }] - }); - }, - listUsers: async (limit, offset, sortBy, where) => { - return await (await getCurrentAdapter(adapter)).findMany({ - model: "user", - limit, - offset, - sortBy, - where - }); - }, - countTotalUsers: async (where) => { - const total = await (await getCurrentAdapter(adapter)).count({ - model: "user", - where - }); - if (typeof total === "string") return parseInt(total); - return total; - }, - deleteUser: async (userId) => { - if (!secondaryStorage || options.session?.storeSessionInDatabase) await deleteManyWithHooks([{ - field: "userId", - value: userId - }], "session", void 0); - await deleteManyWithHooks([{ - field: "userId", - value: userId - }], "account", void 0); - await deleteWithHooks([{ - field: "id", - value: userId - }], "user", void 0); - }, - createSession: async (userId, dontRememberMe, override, overrideAll) => { - const ctx$1 = await getCurrentAuthContext().catch(() => null); - const headers = ctx$1?.headers || ctx$1?.request?.headers; - const { id: _, ...rest } = override || {}; - const defaultAdditionalFields = parseSessionInput(ctx$1?.context.options ?? options, {}); - const data2 = { - ipAddress: ctx$1?.request || ctx$1?.headers ? getIp(ctx$1?.request || ctx$1?.headers, ctx$1?.context.options) || "" : "", - userAgent: headers?.get("user-agent") || "", - ...rest, - expiresAt: dontRememberMe ? getDate(3600 * 24, "sec") : getDate(sessionExpiration, "sec"), - userId, - token: generateId(32), - createdAt: /* @__PURE__ */ new Date(), - updatedAt: /* @__PURE__ */ new Date(), - ...defaultAdditionalFields, - ...overrideAll ? rest : {} - }; - return await createWithHooks(data2, "session", secondaryStorage ? { - fn: async (sessionData) => { - const currentList = await secondaryStorage.get(`active-sessions-${userId}`); - let list2 = []; - const now2 = Date.now(); - if (currentList) { - list2 = safeJSONParse(currentList) || []; - list2 = list2.filter((session) => session.expiresAt > now2 && session.token !== data2.token); - } - const sorted = [...list2, { - token: data2.token, - expiresAt: data2.expiresAt.getTime() - }].sort((a5, b6) => a5.expiresAt - b6.expiresAt); - const furthestSessionExp = sorted.at(-1)?.expiresAt ?? data2.expiresAt.getTime(); - const furthestSessionTTL = Math.max(Math.floor((furthestSessionExp - now2) / 1e3), 0); - if (furthestSessionTTL > 0) await secondaryStorage.set(`active-sessions-${userId}`, JSON.stringify(sorted), furthestSessionTTL); - const user = await adapter.findOne({ - model: "user", - where: [{ - field: "id", - value: userId - }] - }); - const sessionTTL = Math.max(Math.floor((data2.expiresAt.getTime() - now2) / 1e3), 0); - if (sessionTTL > 0) await secondaryStorage.set(data2.token, JSON.stringify({ - session: sessionData, - user - }), sessionTTL); - return sessionData; - }, - executeMainFn: options.session?.storeSessionInDatabase - } : void 0); - }, - findSession: async (token) => { - if (secondaryStorage) { - const sessionStringified = await secondaryStorage.get(token); - if (!sessionStringified && !options.session?.storeSessionInDatabase) return null; - if (sessionStringified) { - const s5 = safeJSONParse(sessionStringified); - if (!s5) return null; - return { - session: parseSessionOutput(ctx.options, { - ...s5.session, - expiresAt: new Date(s5.session.expiresAt), - createdAt: new Date(s5.session.createdAt), - updatedAt: new Date(s5.session.updatedAt) - }), - user: parseUserOutput(ctx.options, { - ...s5.user, - createdAt: new Date(s5.user.createdAt), - updatedAt: new Date(s5.user.updatedAt) - }) - }; - } - } - const result = await (await getCurrentAdapter(adapter)).findOne({ - model: "session", - where: [{ - value: token, - field: "token" - }], - join: { user: true } - }); - if (!result) return null; - const { user, ...session } = result; - if (!user) return null; - return { - session: parseSessionOutput(ctx.options, session), - user: parseUserOutput(ctx.options, user) - }; - }, - findSessions: async (sessionTokens) => { - if (secondaryStorage) { - const sessions$1 = []; - for (const sessionToken of sessionTokens) { - const sessionStringified = await secondaryStorage.get(sessionToken); - if (sessionStringified) try { - const s5 = typeof sessionStringified === "string" ? JSON.parse(sessionStringified) : sessionStringified; - if (!s5?.session) continue; - const session = { - session: { - ...s5.session, - expiresAt: new Date(s5.session.expiresAt) - }, - user: { - ...s5.user, - createdAt: new Date(s5.user.createdAt), - updatedAt: new Date(s5.user.updatedAt) - } - }; - sessions$1.push(session); - } catch { - continue; - } - } - return sessions$1; - } - const sessions = await (await getCurrentAdapter(adapter)).findMany({ - model: "session", - where: [{ - field: "token", - value: sessionTokens, - operator: "in" - }], - join: { user: true } - }); - if (!sessions.length) return []; - if (sessions.some((session) => !session.user)) return []; - return sessions.map((_session) => { - const { user, ...session } = _session; - return { - session, - user - }; - }); - }, - updateSession: async (sessionToken, session) => { - return await updateWithHooks(session, [{ - field: "token", - value: sessionToken - }], "session", secondaryStorage ? { - async fn(data2) { - const currentSession = await secondaryStorage.get(sessionToken); - if (!currentSession) return null; - const parsedSession = safeJSONParse(currentSession); - if (!parsedSession) return null; - const mergedSession = { - ...parsedSession.session, - ...data2, - expiresAt: new Date(data2.expiresAt ?? parsedSession.session.expiresAt), - createdAt: new Date(parsedSession.session.createdAt), - updatedAt: new Date(data2.updatedAt ?? parsedSession.session.updatedAt) - }; - const updatedSession = parseSessionOutput(ctx.options, mergedSession); - const now2 = Date.now(); - const expiresMs = new Date(updatedSession.expiresAt).getTime(); - const sessionTTL = Math.max(Math.floor((expiresMs - now2) / 1e3), 0); - if (sessionTTL > 0) { - await secondaryStorage.set(sessionToken, JSON.stringify({ - session: updatedSession, - user: parsedSession.user - }), sessionTTL); - const listKey = `active-sessions-${updatedSession.userId}`; - const listRaw = await secondaryStorage.get(listKey); - const sorted = (listRaw ? safeJSONParse(listRaw) || [] : []).filter((s5) => s5.token !== sessionToken && s5.expiresAt > now2).concat([{ - token: sessionToken, - expiresAt: expiresMs - }]).sort((a5, b6) => a5.expiresAt - b6.expiresAt); - const furthestSessionExp = sorted.at(-1)?.expiresAt; - if (furthestSessionExp && furthestSessionExp > now2) await secondaryStorage.set(listKey, JSON.stringify(sorted), Math.floor((furthestSessionExp - now2) / 1e3)); - else await secondaryStorage.delete(listKey); - } - return updatedSession; - }, - executeMainFn: options.session?.storeSessionInDatabase - } : void 0); - }, - deleteSession: async (token) => { - if (secondaryStorage) { - const data2 = await secondaryStorage.get(token); - if (data2) { - const { session } = safeJSONParse(data2) ?? {}; - if (!session) { - logger4.error("Session not found in secondary storage"); - return; - } - const userId = session.userId; - const currentList = await secondaryStorage.get(`active-sessions-${userId}`); - if (currentList) { - const list2 = safeJSONParse(currentList) || []; - const now2 = Date.now(); - const filtered = list2.filter((session$1) => session$1.expiresAt > now2 && session$1.token !== token); - const furthestSessionExp = filtered.sort((a5, b6) => a5.expiresAt - b6.expiresAt).at(-1)?.expiresAt; - if (filtered.length > 0 && furthestSessionExp && furthestSessionExp > Date.now()) await secondaryStorage.set(`active-sessions-${userId}`, JSON.stringify(filtered), Math.floor((furthestSessionExp - now2) / 1e3)); - else await secondaryStorage.delete(`active-sessions-${userId}`); - } else logger4.error("Active sessions list not found in secondary storage"); - } - await secondaryStorage.delete(token); - if (!options.session?.storeSessionInDatabase || ctx.options.session?.preserveSessionInDatabase) return; - } - await deleteWithHooks([{ - field: "token", - value: token - }], "session", void 0); - }, - deleteAccounts: async (userId) => { - await deleteManyWithHooks([{ - field: "userId", - value: userId - }], "account", void 0); - }, - deleteAccount: async (accountId) => { - await deleteWithHooks([{ - field: "id", - value: accountId - }], "account", void 0); - }, - deleteSessions: async (userIdOrSessionTokens) => { - if (secondaryStorage) { - if (typeof userIdOrSessionTokens === "string") { - const activeSession = await secondaryStorage.get(`active-sessions-${userIdOrSessionTokens}`); - const sessions = activeSession ? safeJSONParse(activeSession) : []; - if (!sessions) return; - for (const session of sessions) await secondaryStorage.delete(session.token); - await secondaryStorage.delete(`active-sessions-${userIdOrSessionTokens}`); - } else for (const sessionToken of userIdOrSessionTokens) if (await secondaryStorage.get(sessionToken)) await secondaryStorage.delete(sessionToken); - if (!options.session?.storeSessionInDatabase || ctx.options.session?.preserveSessionInDatabase) return; - } - await deleteManyWithHooks([{ - field: Array.isArray(userIdOrSessionTokens) ? "token" : "userId", - value: userIdOrSessionTokens, - operator: Array.isArray(userIdOrSessionTokens) ? "in" : void 0 - }], "session", void 0); - }, - findOAuthUser: async (email3, accountId, providerId) => { - const account = await (await getCurrentAdapter(adapter)).findOne({ - model: "account", - where: [{ - value: accountId, - field: "accountId" - }, { - value: providerId, - field: "providerId" - }], - join: { user: true } - }); - if (account) if (account.user) return { - user: account.user, - linkedAccount: account, - accounts: [account] - }; - else { - const user = await (await getCurrentAdapter(adapter)).findOne({ - model: "user", - where: [{ - value: email3.toLowerCase(), - field: "email" - }] - }); - if (user) return { - user, - linkedAccount: account, - accounts: [account] - }; - return null; - } - else { - const user = await (await getCurrentAdapter(adapter)).findOne({ - model: "user", - where: [{ - value: email3.toLowerCase(), - field: "email" - }] - }); - if (user) return { - user, - linkedAccount: null, - accounts: await (await getCurrentAdapter(adapter)).findMany({ - model: "account", - where: [{ - value: user.id, - field: "userId" - }] - }) || [] - }; - else return null; - } - }, - findUserByEmail: async (email3, options$1) => { - const result = await (await getCurrentAdapter(adapter)).findOne({ - model: "user", - where: [{ - value: email3.toLowerCase(), - field: "email" - }], - join: { ...options$1?.includeAccounts ? { account: true } : {} } - }); - if (!result) return null; - const { account: accounts, ...user } = result; - return { - user, - accounts: accounts ?? [] - }; - }, - findUserById: async (userId) => { - if (!userId) return null; - return await (await getCurrentAdapter(adapter)).findOne({ - model: "user", - where: [{ - field: "id", - value: userId - }] - }); - }, - linkAccount: async (account) => { - return await createWithHooks({ - createdAt: /* @__PURE__ */ new Date(), - updatedAt: /* @__PURE__ */ new Date(), - ...account - }, "account", void 0); - }, - updateUser: async (userId, data2) => { - const user = await updateWithHooks(data2, [{ - field: "id", - value: userId - }], "user", void 0); - await refreshUserSessions(user); - return user; - }, - updateUserByEmail: async (email3, data2) => { - const user = await updateWithHooks(data2, [{ - field: "email", - value: email3.toLowerCase() - }], "user", void 0); - await refreshUserSessions(user); - return user; - }, - updatePassword: async (userId, password) => { - await updateManyWithHooks({ password }, [{ - field: "userId", - value: userId - }, { - field: "providerId", - value: "credential" - }], "account", void 0); - }, - findAccounts: async (userId) => { - return await (await getCurrentAdapter(adapter)).findMany({ - model: "account", - where: [{ - field: "userId", - value: userId - }] - }); - }, - findAccount: async (accountId) => { - return await (await getCurrentAdapter(adapter)).findOne({ - model: "account", - where: [{ - field: "accountId", - value: accountId - }] - }); - }, - findAccountByProviderId: async (accountId, providerId) => { - return await (await getCurrentAdapter(adapter)).findOne({ - model: "account", - where: [{ - field: "accountId", - value: accountId - }, { - field: "providerId", - value: providerId - }] - }); - }, - findAccountByUserId: async (userId) => { - return await (await getCurrentAdapter(adapter)).findMany({ - model: "account", - where: [{ - field: "userId", - value: userId - }] - }); - }, - updateAccount: async (id, data2) => { - return await updateWithHooks(data2, [{ - field: "id", - value: id - }], "account", void 0); - }, - createVerificationValue: async (data2) => { - return await createWithHooks({ - createdAt: /* @__PURE__ */ new Date(), - updatedAt: /* @__PURE__ */ new Date(), - ...data2 - }, "verification", void 0); - }, - findVerificationValue: async (identifier) => { - const verification = await (await getCurrentAdapter(adapter)).findMany({ - model: "verification", - where: [{ - field: "identifier", - value: identifier - }], - sortBy: { - field: "createdAt", - direction: "desc" - }, - limit: 1 - }); - if (!options.verification?.disableCleanup) await deleteManyWithHooks([{ - field: "expiresAt", - value: /* @__PURE__ */ new Date(), - operator: "lt" - }], "verification", void 0); - return verification[0]; - }, - deleteVerificationValue: async (id) => { - await deleteWithHooks([{ - field: "id", - value: id - }], "verification", void 0); - }, - deleteVerificationByIdentifier: async (identifier) => { - await deleteWithHooks([{ - field: "identifier", - value: identifier - }], "verification", void 0); - }, - updateVerificationValue: async (id, data2) => { - return await updateWithHooks(data2, [{ - field: "id", - value: id - }], "verification", void 0); - } - }; - }; - } -}); - -// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/db/to-zod.mjs -function toZodSchema({ fields, isClientSide }) { - const zodFields = Object.keys(fields).reduce((acc, key) => { - const field = fields[key]; - if (!field) return acc; - if (isClientSide && field.input === false) return acc; - let schema2; - if (field.type === "json") schema2 = json2 ? json2() : any(); - else if (field.type === "string[]" || field.type === "number[]") schema2 = array(field.type === "string[]" ? string2() : number2()); - else if (Array.isArray(field.type)) schema2 = any(); - else schema2 = zod_exports[field.type](); - if (field?.required === false) schema2 = schema2.optional(); - if (!isClientSide && field?.returned === false) return acc; - return { - ...acc, - [key]: schema2 - }; - }, {}); - return object(zodFields); -} -var init_to_zod = __esm({ - "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/db/to-zod.mjs"() { - init_zod(); - } -}); - -// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/db/get-schema.mjs -function getSchema(config3) { - const tables = (0, db_exports2.getAuthTables)(config3); - const schema2 = {}; - for (const key in tables) { - const table = tables[key]; - const fields = table.fields; - const actualFields = {}; - Object.entries(fields).forEach(([key$1, field]) => { - actualFields[field.fieldName || key$1] = field; - if (field.references) { - const refTable = tables[field.references.model]; - if (refTable) actualFields[field.fieldName || key$1].references = { - ...field.references, - model: refTable.modelName, - field: field.references.field - }; - } - }); - if (schema2[table.modelName]) { - schema2[table.modelName].fields = { - ...schema2[table.modelName].fields, - ...actualFields - }; - continue; - } - schema2[table.modelName] = { - fields: actualFields, - order: table.order || Infinity - }; - } - return schema2; -} -var init_get_schema = __esm({ - "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/db/get-schema.mjs"() { - init_db4(); - } -}); - -// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/db/get-migration.mjs -function matchType(columnDataType, fieldType, dbType) { - function normalize2(type) { - return type.toLowerCase().split("(")[0].trim(); - } - if (fieldType === "string[]" || fieldType === "number[]") return columnDataType.toLowerCase().includes("json"); - const types2 = map3[dbType]; - return (Array.isArray(fieldType) ? types2["string"].map((t5) => t5.toLowerCase()) : types2[fieldType].map((t5) => t5.toLowerCase())).includes(normalize2(columnDataType)); -} -async function getPostgresSchema(db) { - try { - const result = await sql2`SHOW search_path`.execute(db); - if (result.rows[0]?.search_path) return result.rows[0].search_path.split(",").map((s5) => s5.trim()).map((s5) => s5.replace(/^["']|["']$/g, "")).filter((s5) => !s5.startsWith("$"))[0] || "public"; - } catch { - } - return "public"; -} -async function getMigrations(config3) { - const betterAuthSchema = getSchema(config3); - const logger$1 = createLogger(config3.logger); - let { kysely: db, databaseType: dbType } = await createKyselyAdapter(config3); - if (!dbType) { - logger$1.warn("Could not determine database type, defaulting to sqlite. Please provide a type in the database options to avoid this."); - dbType = "sqlite"; - } - if (!db) { - logger$1.error("Only kysely adapter is supported for migrations. You can use `generate` command to generate the schema, if you're using a different adapter."); - process.exit(1); - } - let currentSchema = "public"; - if (dbType === "postgres") { - currentSchema = await getPostgresSchema(db); - logger$1.debug(`PostgreSQL migration: Using schema '${currentSchema}' (from search_path)`); - try { - if (!(await sql2` - SELECT schema_name - FROM information_schema.schemata - WHERE schema_name = ${currentSchema} - `.execute(db)).rows[0]) logger$1.warn(`Schema '${currentSchema}' does not exist. Tables will be inspected from available schemas. Consider creating the schema first or checking your database configuration.`); - } catch (error50) { - logger$1.debug(`Could not verify schema existence: ${error50 instanceof Error ? error50.message : String(error50)}`); - } - } - const allTableMetadata = await db.introspection.getTables(); - let tableMetadata = allTableMetadata; - if (dbType === "postgres") try { - const tablesInSchema = await sql2` - SELECT table_name - FROM information_schema.tables - WHERE table_schema = ${currentSchema} - AND table_type = 'BASE TABLE' - `.execute(db); - const tableNamesInSchema = new Set(tablesInSchema.rows.map((row) => row.table_name)); - tableMetadata = allTableMetadata.filter((table) => table.schema === currentSchema && tableNamesInSchema.has(table.name)); - logger$1.debug(`Found ${tableMetadata.length} table(s) in schema '${currentSchema}': ${tableMetadata.map((t5) => t5.name).join(", ") || "(none)"}`); - } catch (error50) { - logger$1.warn(`Could not filter tables by schema. Using all discovered tables. Error: ${error50 instanceof Error ? error50.message : String(error50)}`); - } - const toBeCreated = []; - const toBeAdded = []; - for (const [key, value] of Object.entries(betterAuthSchema)) { - const table = tableMetadata.find((t5) => t5.name === key); - if (!table) { - const tIndex = toBeCreated.findIndex((t5) => t5.table === key); - const tableData = { - table: key, - fields: value.fields, - order: value.order || Infinity - }; - const insertIndex = toBeCreated.findIndex((t5) => (t5.order || Infinity) > tableData.order); - if (insertIndex === -1) if (tIndex === -1) toBeCreated.push(tableData); - else toBeCreated[tIndex].fields = { - ...toBeCreated[tIndex].fields, - ...value.fields - }; - else toBeCreated.splice(insertIndex, 0, tableData); - continue; - } - const toBeAddedFields = {}; - for (const [fieldName, field] of Object.entries(value.fields)) { - const column = table.columns.find((c5) => c5.name === fieldName); - if (!column) { - toBeAddedFields[fieldName] = field; - continue; - } - if (matchType(column.dataType, field.type, dbType)) continue; - else logger$1.warn(`Field ${fieldName} in table ${key} has a different type in the database. Expected ${field.type} but got ${column.dataType}.`); - } - if (Object.keys(toBeAddedFields).length > 0) toBeAdded.push({ - table: key, - fields: toBeAddedFields, - order: value.order || Infinity - }); - } - const migrations = []; - const useUUIDs = config3.advanced?.database?.generateId === "uuid"; - const useNumberId = config3.advanced?.database?.useNumberId || config3.advanced?.database?.generateId === "serial"; - function getType(field, fieldName) { - const type = field.type; - const provider = dbType || "sqlite"; - const typeMap = { - string: { - sqlite: "text", - postgres: "text", - mysql: field.unique ? "varchar(255)" : field.references ? "varchar(36)" : field.sortable ? "varchar(255)" : field.index ? "varchar(255)" : "text", - mssql: field.unique || field.sortable ? "varchar(255)" : field.references ? "varchar(36)" : "varchar(8000)" - }, - boolean: { - sqlite: "integer", - postgres: "boolean", - mysql: "boolean", - mssql: "smallint" - }, - number: { - sqlite: field.bigint ? "bigint" : "integer", - postgres: field.bigint ? "bigint" : "integer", - mysql: field.bigint ? "bigint" : "integer", - mssql: field.bigint ? "bigint" : "integer" - }, - date: { - sqlite: "date", - postgres: "timestamptz", - mysql: "timestamp(3)", - mssql: sql2`datetime2(3)` - }, - json: { - sqlite: "text", - postgres: "jsonb", - mysql: "json", - mssql: "varchar(8000)" - }, - id: { - postgres: useNumberId ? sql2`integer GENERATED BY DEFAULT AS IDENTITY` : useUUIDs ? "uuid" : "text", - mysql: useNumberId ? "integer" : useUUIDs ? "varchar(36)" : "varchar(36)", - mssql: useNumberId ? "integer" : useUUIDs ? "varchar(36)" : "varchar(36)", - sqlite: useNumberId ? "integer" : "text" - }, - foreignKeyId: { - postgres: useNumberId ? "integer" : useUUIDs ? "uuid" : "text", - mysql: useNumberId ? "integer" : useUUIDs ? "varchar(36)" : "varchar(36)", - mssql: useNumberId ? "integer" : useUUIDs ? "varchar(36)" : "varchar(36)", - sqlite: useNumberId ? "integer" : "text" - }, - "string[]": { - sqlite: "text", - postgres: "jsonb", - mysql: "json", - mssql: "varchar(8000)" - }, - "number[]": { - sqlite: "text", - postgres: "jsonb", - mysql: "json", - mssql: "varchar(8000)" - } - }; - if (fieldName === "id" || field.references?.field === "id") { - if (fieldName === "id") return typeMap.id[provider]; - return typeMap.foreignKeyId[provider]; - } - if (Array.isArray(type)) return "text"; - if (!(type in typeMap)) throw new Error(`Unsupported field type '${String(type)}' for field '${fieldName}'. Allowed types are: string, number, boolean, date, string[], number[]. If you need to store structured data, store it as a JSON string (type: "string") or split it into primitive fields. See https://better-auth.com/docs/advanced/schema#additional-fields`); - return typeMap[type][provider]; - } - const getModelName = initGetModelName({ - schema: getAuthTables(config3), - usePlural: false - }); - const getFieldName = initGetFieldName({ - schema: getAuthTables(config3), - usePlural: false - }); - function getReferencePath(model, field) { - try { - return `${getModelName(model)}.${getFieldName({ - model, - field - })}`; - } catch { - return `${model}.${field}`; - } - } - if (toBeAdded.length) for (const table of toBeAdded) for (const [fieldName, field] of Object.entries(table.fields)) { - const type = getType(field, fieldName); - const builder = db.schema.alterTable(table.table); - if (field.index) { - const index2 = db.schema.alterTable(table.table).addIndex(`${table.table}_${fieldName}_idx`); - migrations.push(index2); - } - const built = builder.addColumn(fieldName, type, (col) => { - col = field.required !== false ? col.notNull() : col; - if (field.references) col = col.references(getReferencePath(field.references.model, field.references.field)).onDelete(field.references.onDelete || "cascade"); - if (field.unique) col = col.unique(); - if (field.type === "date" && typeof field.defaultValue === "function" && (dbType === "postgres" || dbType === "mysql" || dbType === "mssql")) if (dbType === "mysql") col = col.defaultTo(sql2`CURRENT_TIMESTAMP(3)`); - else col = col.defaultTo(sql2`CURRENT_TIMESTAMP`); - return col; - }); - migrations.push(built); - } - const toBeIndexed = []; - if (config3.advanced?.database?.useNumberId) logger$1.warn("`useNumberId` is deprecated. Please use `generateId` with `serial` instead."); - if (toBeCreated.length) for (const table of toBeCreated) { - const idType = getType({ type: useNumberId ? "number" : "string" }, "id"); - let dbT = db.schema.createTable(table.table).addColumn("id", idType, (col) => { - if (useNumberId) { - if (dbType === "postgres") return col.primaryKey().notNull(); - else if (dbType === "sqlite") return col.primaryKey().notNull(); - else if (dbType === "mssql") return col.identity().primaryKey().notNull(); - return col.autoIncrement().primaryKey().notNull(); - } - if (useUUIDs) { - if (dbType === "postgres") return col.primaryKey().defaultTo(sql2`pg_catalog.gen_random_uuid()`).notNull(); - return col.primaryKey().notNull(); - } - return col.primaryKey().notNull(); - }); - for (const [fieldName, field] of Object.entries(table.fields)) { - const type = getType(field, fieldName); - dbT = dbT.addColumn(fieldName, type, (col) => { - col = field.required !== false ? col.notNull() : col; - if (field.references) col = col.references(getReferencePath(field.references.model, field.references.field)).onDelete(field.references.onDelete || "cascade"); - if (field.unique) col = col.unique(); - if (field.type === "date" && typeof field.defaultValue === "function" && (dbType === "postgres" || dbType === "mysql" || dbType === "mssql")) if (dbType === "mysql") col = col.defaultTo(sql2`CURRENT_TIMESTAMP(3)`); - else col = col.defaultTo(sql2`CURRENT_TIMESTAMP`); - return col; - }); - if (field.index) { - const builder = db.schema.createIndex(`${table.table}_${fieldName}_${field.unique ? "uidx" : "idx"}`).on(table.table).columns([fieldName]); - toBeIndexed.push(field.unique ? builder.unique() : builder); - } - } - migrations.push(dbT); - } - if (toBeIndexed.length) for (const index2 of toBeIndexed) migrations.push(index2); - async function runMigrations() { - for (const migration of migrations) await migration.execute(); - } - async function compileMigrations() { - return migrations.map((m5) => m5.compile().sql).join(";\n\n") + ";"; - } - return { - toBeCreated, - toBeAdded, - runMigrations, - compileMigrations - }; -} -var map3; -var init_get_migration = __esm({ - "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/db/get-migration.mjs"() { - init_dialect3(); - init_get_schema(); - init_db3(); - init_env(); - init_esm(); - init_adapter(); - map3 = { - postgres: { - string: [ - "character varying", - "varchar", - "text", - "uuid" - ], - number: [ - "int4", - "integer", - "bigint", - "smallint", - "numeric", - "real", - "double precision" - ], - boolean: ["bool", "boolean"], - date: [ - "timestamptz", - "timestamp", - "date" - ], - json: ["json", "jsonb"] - }, - mysql: { - string: [ - "varchar", - "text", - "uuid" - ], - number: [ - "integer", - "int", - "bigint", - "smallint", - "decimal", - "float", - "double" - ], - boolean: ["boolean", "tinyint"], - date: [ - "timestamp", - "datetime", - "date" - ], - json: ["json"] - }, - sqlite: { - string: ["TEXT"], - number: ["INTEGER", "REAL"], - boolean: ["INTEGER", "BOOLEAN"], - date: ["DATE", "INTEGER"], - json: ["TEXT"] - }, - mssql: { - string: [ - "varchar", - "nvarchar", - "uniqueidentifier" - ], - number: [ - "int", - "bigint", - "smallint", - "decimal", - "float", - "double" - ], - boolean: ["bit", "smallint"], - date: [ - "datetime2", - "date", - "datetime" - ], - json: ["varchar", "nvarchar"] - } - }; - } -}); - -// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/db/index.mjs -var db_exports2; -var init_db4 = __esm({ - "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/db/index.mjs"() { - init_rolldown_runtime(); - init_adapter_base(); - init_adapter_kysely(); - init_field(); - init_field_converter(); - init_schema4(); - init_with_hooks(); - init_internal_adapter(); - init_to_zod(); - init_get_schema(); - init_get_migration(); - init_db3(); - init_db3(); - db_exports2 = /* @__PURE__ */ __export2({ - convertFromDB: () => convertFromDB, - convertToDB: () => convertToDB, - createFieldAttribute: () => createFieldAttribute, - createInternalAdapter: () => createInternalAdapter, - getAdapter: () => getAdapter, - getBaseAdapter: () => getBaseAdapter, - getMigrations: () => getMigrations, - getSchema: () => getSchema, - getWithHooks: () => getWithHooks, - matchType: () => matchType, - mergeSchema: () => mergeSchema, - parseAccountInput: () => parseAccountInput, - parseAccountOutput: () => parseAccountOutput, - parseAdditionalUserInput: () => parseAdditionalUserInput, - parseInputData: () => parseInputData, - parseSessionInput: () => parseSessionInput, - parseSessionOutput: () => parseSessionOutput, - parseUserInput: () => parseUserInput, - parseUserOutput: () => parseUserOutput, - toZodSchema: () => toZodSchema - }); - __reExport(db_exports2, db_exports); - } -}); - -// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/api/routes/session.mjs -var getSession, getSessionFromCtx, sessionMiddleware, sensitiveSessionMiddleware, requestOnlySessionMiddleware, freshSessionMiddleware, listSessions, revokeSession, revokeSessions, revokeOtherSessions; -var init_session4 = __esm({ - "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/api/routes/session.mjs"() { - init_date2(); - init_schema4(); - init_db4(); - init_jwt(); - init_crypto(); - init_session_store(); - init_cookies2(); - init_error(); - init_utils7(); - init_dist3(); - init_zod(); - init_api2(); - init_base642(); - init_binary(); - init_hmac2(); - getSession = () => createAuthEndpoint("/get-session", { - method: "GET", - operationId: "getSession", - query: getSessionQuerySchema, - requireHeaders: true, - metadata: { openapi: { - operationId: "getSession", - description: "Get the current session", - responses: { "200": { - description: "Success", - content: { "application/json": { schema: { - type: "object", - nullable: true, - properties: { - session: { $ref: "#/components/schemas/Session" }, - user: { $ref: "#/components/schemas/User" } - }, - required: ["session", "user"] - } } } - } } - } } - }, async (ctx) => { - try { - const sessionCookieToken = await ctx.getSignedCookie(ctx.context.authCookies.sessionToken.name, ctx.context.secret); - if (!sessionCookieToken) return null; - const sessionDataCookie = getChunkedCookie(ctx, ctx.context.authCookies.sessionData.name); - let sessionDataPayload = null; - if (sessionDataCookie) { - const strategy = ctx.context.options.session?.cookieCache?.strategy || "compact"; - if (strategy === "jwe") { - const payload2 = await symmetricDecodeJWT(sessionDataCookie, ctx.context.secret, "better-auth-session"); - if (payload2 && payload2.session && payload2.user) sessionDataPayload = { - session: { - session: payload2.session, - user: payload2.user, - updatedAt: payload2.updatedAt, - version: payload2.version - }, - expiresAt: payload2.exp ? payload2.exp * 1e3 : Date.now() - }; - else { - expireCookie(ctx, ctx.context.authCookies.sessionData); - return ctx.json(null); - } - } else if (strategy === "jwt") { - const payload2 = await verifyJWT(sessionDataCookie, ctx.context.secret); - if (payload2 && payload2.session && payload2.user) sessionDataPayload = { - session: { - session: payload2.session, - user: payload2.user, - updatedAt: payload2.updatedAt, - version: payload2.version - }, - expiresAt: payload2.exp ? payload2.exp * 1e3 : Date.now() - }; - else { - expireCookie(ctx, ctx.context.authCookies.sessionData); - return ctx.json(null); - } - } else { - const parsed = safeJSONParse(binary.decode(base64Url.decode(sessionDataCookie))); - if (parsed) if (await createHMAC("SHA-256", "base64urlnopad").verify(ctx.context.secret, JSON.stringify({ - ...parsed.session, - expiresAt: parsed.expiresAt - }), parsed.signature)) sessionDataPayload = parsed; - else { - expireCookie(ctx, ctx.context.authCookies.sessionData); - return ctx.json(null); - } - } - } - const dontRememberMe = await ctx.getSignedCookie(ctx.context.authCookies.dontRememberToken.name, ctx.context.secret); - if (sessionDataPayload?.session && ctx.context.options.session?.cookieCache?.enabled && !ctx.query?.disableCookieCache) { - const session$1 = sessionDataPayload.session; - const versionConfig = ctx.context.options.session?.cookieCache?.version; - let expectedVersion = "1"; - if (versionConfig) { - if (typeof versionConfig === "string") expectedVersion = versionConfig; - else if (typeof versionConfig === "function") { - const result = versionConfig(session$1.session, session$1.user); - expectedVersion = result instanceof Promise ? await result : result; - } - } - if ((session$1.version || "1") !== expectedVersion) expireCookie(ctx, ctx.context.authCookies.sessionData); - else { - const cachedSessionExpiresAt = new Date(session$1.session.expiresAt); - if (sessionDataPayload.expiresAt < Date.now() || cachedSessionExpiresAt < /* @__PURE__ */ new Date()) expireCookie(ctx, ctx.context.authCookies.sessionData); - else { - const cookieRefreshCache = ctx.context.sessionConfig.cookieRefreshCache; - if (cookieRefreshCache === false) { - ctx.context.session = session$1; - const parsedSession$2 = parseSessionOutput(ctx.context.options, { - ...session$1.session, - expiresAt: new Date(session$1.session.expiresAt), - createdAt: new Date(session$1.session.createdAt), - updatedAt: new Date(session$1.session.updatedAt) - }); - const parsedUser$2 = parseUserOutput(ctx.context.options, { - ...session$1.user, - createdAt: new Date(session$1.user.createdAt), - updatedAt: new Date(session$1.user.updatedAt) - }); - return ctx.json({ - session: parsedSession$2, - user: parsedUser$2 - }); - } - if (sessionDataPayload.expiresAt - Date.now() < cookieRefreshCache.updateAge * 1e3) { - const newExpiresAt = getDate(ctx.context.options.session?.cookieCache?.maxAge || 300, "sec"); - const refreshedSession = { - session: { - ...session$1.session, - expiresAt: newExpiresAt - }, - user: session$1.user, - updatedAt: Date.now() - }; - await setCookieCache(ctx, refreshedSession, false); - const parsedRefreshedSession = parseSessionOutput(ctx.context.options, { - ...refreshedSession.session, - expiresAt: new Date(refreshedSession.session.expiresAt), - createdAt: new Date(refreshedSession.session.createdAt), - updatedAt: new Date(refreshedSession.session.updatedAt) - }); - const parsedRefreshedUser = parseUserOutput(ctx.context.options, { - ...refreshedSession.user, - createdAt: new Date(refreshedSession.user.createdAt), - updatedAt: new Date(refreshedSession.user.updatedAt) - }); - ctx.context.session = { - session: parsedRefreshedSession, - user: parsedRefreshedUser - }; - return ctx.json({ - session: parsedRefreshedSession, - user: parsedRefreshedUser - }); - } - const parsedSession$1 = parseSessionOutput(ctx.context.options, { - ...session$1.session, - expiresAt: new Date(session$1.session.expiresAt), - createdAt: new Date(session$1.session.createdAt), - updatedAt: new Date(session$1.session.updatedAt) - }); - const parsedUser$1 = parseUserOutput(ctx.context.options, { - ...session$1.user, - createdAt: new Date(session$1.user.createdAt), - updatedAt: new Date(session$1.user.updatedAt) - }); - ctx.context.session = { - session: parsedSession$1, - user: parsedUser$1 - }; - return ctx.json({ - session: parsedSession$1, - user: parsedUser$1 - }); - } - } - } - const session = await ctx.context.internalAdapter.findSession(sessionCookieToken); - ctx.context.session = session; - if (!session || session.session.expiresAt < /* @__PURE__ */ new Date()) { - deleteSessionCookie(ctx); - if (session) - await ctx.context.internalAdapter.deleteSession(session.session.token); - return ctx.json(null); - } - if (dontRememberMe || ctx.query?.disableRefresh) { - const parsedSession$1 = parseSessionOutput(ctx.context.options, session.session); - const parsedUser$1 = parseUserOutput(ctx.context.options, session.user); - return ctx.json({ - session: parsedSession$1, - user: parsedUser$1 - }); - } - const expiresIn = ctx.context.sessionConfig.expiresIn; - const updateAge = ctx.context.sessionConfig.updateAge; - if (session.session.expiresAt.valueOf() - expiresIn * 1e3 + updateAge * 1e3 <= Date.now() && (!ctx.query?.disableRefresh || !ctx.context.options.session?.disableSessionRefresh)) { - const updatedSession = await ctx.context.internalAdapter.updateSession(session.session.token, { - expiresAt: getDate(ctx.context.sessionConfig.expiresIn, "sec"), - updatedAt: /* @__PURE__ */ new Date() - }); - if (!updatedSession) { - deleteSessionCookie(ctx); - return ctx.json(null, { status: 401 }); - } - const maxAge = (updatedSession.expiresAt.valueOf() - Date.now()) / 1e3; - await setSessionCookie(ctx, { - session: updatedSession, - user: session.user - }, false, { maxAge }); - const parsedUpdatedSession = parseSessionOutput(ctx.context.options, updatedSession); - const parsedUser$1 = parseUserOutput(ctx.context.options, session.user); - return ctx.json({ - session: parsedUpdatedSession, - user: parsedUser$1 - }); - } - await setCookieCache(ctx, session, !!dontRememberMe); - const parsedSession = parseSessionOutput(ctx.context.options, session.session); - const parsedUser = parseUserOutput(ctx.context.options, session.user); - return ctx.json({ - session: parsedSession, - user: parsedUser - }); - } catch (error50) { - ctx.context.logger.error("INTERNAL_SERVER_ERROR", error50); - throw new APIError("INTERNAL_SERVER_ERROR", { message: BASE_ERROR_CODES.FAILED_TO_GET_SESSION }); - } - }); - getSessionFromCtx = async (ctx, config3) => { - if (ctx.context.session) return ctx.context.session; - const session = await getSession()({ - ...ctx, - asResponse: false, - headers: ctx.headers, - returnHeaders: false, - returnStatus: false, - query: { - ...config3, - ...ctx.query - } - }).catch((e5) => { - return null; - }); - ctx.context.session = session; - return session; - }; - sessionMiddleware = createAuthMiddleware(async (ctx) => { - const session = await getSessionFromCtx(ctx); - if (!session?.session) throw new APIError("UNAUTHORIZED"); - return { session }; - }); - sensitiveSessionMiddleware = createAuthMiddleware(async (ctx) => { - const session = await getSessionFromCtx(ctx, { disableCookieCache: true }); - if (!session?.session) throw new APIError("UNAUTHORIZED"); - return { session }; - }); - requestOnlySessionMiddleware = createAuthMiddleware(async (ctx) => { - const session = await getSessionFromCtx(ctx); - if (!session?.session && (ctx.request || ctx.headers)) throw new APIError("UNAUTHORIZED"); - return { session }; - }); - freshSessionMiddleware = createAuthMiddleware(async (ctx) => { - const session = await getSessionFromCtx(ctx); - if (!session?.session) throw new APIError("UNAUTHORIZED"); - if (ctx.context.sessionConfig.freshAge === 0) return { session }; - const freshAge = ctx.context.sessionConfig.freshAge; - const lastUpdated = new Date(session.session.updatedAt || session.session.createdAt).getTime(); - if (!(Date.now() - lastUpdated < freshAge * 1e3)) throw new APIError("FORBIDDEN", { message: "Session is not fresh" }); - return { session }; - }); - listSessions = () => createAuthEndpoint("/list-sessions", { - method: "GET", - operationId: "listUserSessions", - use: [sessionMiddleware], - requireHeaders: true, - metadata: { openapi: { - operationId: "listUserSessions", - description: "List all active sessions for the user", - responses: { "200": { - description: "Success", - content: { "application/json": { schema: { - type: "array", - items: { $ref: "#/components/schemas/Session" } - } } } - } } - } } - }, async (ctx) => { - try { - const activeSessions = (await ctx.context.internalAdapter.listSessions(ctx.context.session.user.id)).filter((session) => { - return session.expiresAt > /* @__PURE__ */ new Date(); - }); - return ctx.json(activeSessions.map((session) => parseSessionOutput(ctx.context.options, session))); - } catch (e5) { - ctx.context.logger.error(e5); - throw ctx.error("INTERNAL_SERVER_ERROR"); - } - }); - revokeSession = createAuthEndpoint("/revoke-session", { - method: "POST", - body: object({ token: string2().meta({ description: "The token to revoke" }) }), - use: [sensitiveSessionMiddleware], - requireHeaders: true, - metadata: { openapi: { - description: "Revoke a single session", - requestBody: { content: { "application/json": { schema: { - type: "object", - properties: { token: { - type: "string", - description: "The token to revoke" - } }, - required: ["token"] - } } } }, - responses: { "200": { - description: "Success", - content: { "application/json": { schema: { - type: "object", - properties: { status: { - type: "boolean", - description: "Indicates if the session was revoked successfully" - } }, - required: ["status"] - } } } - } } - } } - }, async (ctx) => { - const token = ctx.body.token; - if ((await ctx.context.internalAdapter.findSession(token))?.session.userId === ctx.context.session.user.id) try { - await ctx.context.internalAdapter.deleteSession(token); - } catch (error50) { - ctx.context.logger.error(error50 && typeof error50 === "object" && "name" in error50 ? error50.name : "", error50); - throw new APIError("INTERNAL_SERVER_ERROR"); - } - return ctx.json({ status: true }); - }); - revokeSessions = createAuthEndpoint("/revoke-sessions", { - method: "POST", - use: [sensitiveSessionMiddleware], - requireHeaders: true, - metadata: { openapi: { - description: "Revoke all sessions for the user", - responses: { "200": { - description: "Success", - content: { "application/json": { schema: { - type: "object", - properties: { status: { - type: "boolean", - description: "Indicates if all sessions were revoked successfully" - } }, - required: ["status"] - } } } - } } - } } - }, async (ctx) => { - try { - await ctx.context.internalAdapter.deleteSessions(ctx.context.session.user.id); - } catch (error50) { - ctx.context.logger.error(error50 && typeof error50 === "object" && "name" in error50 ? error50.name : "", error50); - throw new APIError("INTERNAL_SERVER_ERROR"); - } - return ctx.json({ status: true }); - }); - revokeOtherSessions = createAuthEndpoint("/revoke-other-sessions", { - method: "POST", - requireHeaders: true, - use: [sensitiveSessionMiddleware], - metadata: { openapi: { - description: "Revoke all other sessions for the user except the current one", - responses: { "200": { - description: "Success", - content: { "application/json": { schema: { - type: "object", - properties: { status: { - type: "boolean", - description: "Indicates if all other sessions were revoked successfully" - } }, - required: ["status"] - } } } - } } - } } - }, async (ctx) => { - const session = ctx.context.session; - if (!session.user) throw new APIError("UNAUTHORIZED"); - const otherSessions = (await ctx.context.internalAdapter.listSessions(session.user.id)).filter((session$1) => { - return session$1.expiresAt > /* @__PURE__ */ new Date(); - }).filter((session$1) => session$1.token !== ctx.context.session.session.token); - await Promise.all(otherSessions.map((session$1) => ctx.context.internalAdapter.deleteSession(session$1.token))); - return ctx.json({ status: true }); - }); - } -}); - -// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/oauth2/utils.mjs -function decryptOAuthToken(token, ctx) { - if (!token) return token; - if (ctx.options.account?.encryptOAuthTokens) return symmetricDecrypt({ - key: ctx.secret, - data: token - }); - return token; -} -function setTokenUtil(token, ctx) { - if (ctx.options.account?.encryptOAuthTokens && token) return symmetricEncrypt({ - key: ctx.secret, - data: token - }); - return token; -} -var init_utils12 = __esm({ - "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/oauth2/utils.mjs"() { - init_crypto(); - } -}); - -// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/oauth2/utils.mjs -function getOAuth2Tokens(data2) { - const getDate2 = (seconds) => { - const now2 = /* @__PURE__ */ new Date(); - return new Date(now2.getTime() + seconds * 1e3); - }; - return { - tokenType: data2.token_type, - accessToken: data2.access_token, - refreshToken: data2.refresh_token, - accessTokenExpiresAt: data2.expires_in ? getDate2(data2.expires_in) : void 0, - refreshTokenExpiresAt: data2.refresh_token_expires_in ? getDate2(data2.refresh_token_expires_in) : void 0, - scopes: data2?.scope ? typeof data2.scope === "string" ? data2.scope.split(" ") : data2.scope : [], - idToken: data2.id_token, - raw: data2 - }; -} -async function generateCodeChallenge(codeVerifier) { - const data2 = new TextEncoder().encode(codeVerifier); - const hash2 = await crypto.subtle.digest("SHA-256", data2); - return base64Url.encode(new Uint8Array(hash2), { padding: false }); -} -var init_utils13 = __esm({ - "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/oauth2/utils.mjs"() { - init_base642(); - } -}); - -// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/oauth2/create-authorization-url.mjs -async function createAuthorizationURL({ id, options, authorizationEndpoint, state: state2, codeVerifier, scopes, claims, redirectURI, duration: duration3, prompt, accessType, responseType, display, loginHint, hd, responseMode, additionalParams, scopeJoiner }) { - const url2 = new URL(options.authorizationEndpoint || authorizationEndpoint); - url2.searchParams.set("response_type", responseType || "code"); - const primaryClientId = Array.isArray(options.clientId) ? options.clientId[0] : options.clientId; - url2.searchParams.set("client_id", primaryClientId); - url2.searchParams.set("state", state2); - if (scopes) url2.searchParams.set("scope", scopes.join(scopeJoiner || " ")); - url2.searchParams.set("redirect_uri", options.redirectURI || redirectURI); - duration3 && url2.searchParams.set("duration", duration3); - display && url2.searchParams.set("display", display); - loginHint && url2.searchParams.set("login_hint", loginHint); - prompt && url2.searchParams.set("prompt", prompt); - hd && url2.searchParams.set("hd", hd); - accessType && url2.searchParams.set("access_type", accessType); - responseMode && url2.searchParams.set("response_mode", responseMode); - if (codeVerifier) { - const codeChallenge = await generateCodeChallenge(codeVerifier); - url2.searchParams.set("code_challenge_method", "S256"); - url2.searchParams.set("code_challenge", codeChallenge); - } - if (claims) { - const claimsObj = claims.reduce((acc, claim) => { - acc[claim] = null; - return acc; - }, {}); - url2.searchParams.set("claims", JSON.stringify({ id_token: { - email: null, - email_verified: null, - ...claimsObj - } })); - } - if (additionalParams) Object.entries(additionalParams).forEach(([key, value]) => { - url2.searchParams.set(key, value); - }); - return url2; -} -var init_create_authorization_url = __esm({ - "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/oauth2/create-authorization-url.mjs"() { - init_utils13(); - } -}); - -// node_modules/.pnpm/@better-fetch+fetch@1.1.21/node_modules/@better-fetch/fetch/dist/index.js -function createRetryStrategy(options) { - if (typeof options === "number") { - return new LinearRetryStrategy({ - type: "linear", - attempts: options, - delay: 1e3 - }); - } - switch (options.type) { - case "linear": - return new LinearRetryStrategy(options); - case "exponential": - return new ExponentialRetryStrategy(options); - default: - throw new Error("Invalid retry strategy"); - } -} -function detectResponseType(request) { - const _contentType = request.headers.get("content-type"); - const textTypes = /* @__PURE__ */ new Set([ - "image/svg", - "application/xml", - "application/xhtml", - "application/html" - ]); - if (!_contentType) { - return "json"; - } - const contentType = _contentType.split(";").shift() || ""; - if (JSON_RE.test(contentType)) { - return "json"; - } - if (textTypes.has(contentType) || contentType.startsWith("text/")) { - return "text"; - } - return "blob"; -} -function isJSONParsable(value) { - try { - JSON.parse(value); - return true; - } catch (error50) { - return false; - } -} -function isJSONSerializable2(value) { - if (value === void 0) { - return false; - } - const t5 = typeof value; - if (t5 === "string" || t5 === "number" || t5 === "boolean" || t5 === null) { - return true; - } - if (t5 !== "object") { - return false; - } - if (Array.isArray(value)) { - return true; - } - if (value.buffer) { - return false; - } - return value.constructor && value.constructor.name === "Object" || typeof value.toJSON === "function"; -} -function jsonParse(text3) { - try { - return JSON.parse(text3); - } catch (error50) { - return text3; - } -} -function isFunction2(value) { - return typeof value === "function"; -} -function getFetch(options) { - if (options == null ? void 0 : options.customFetchImpl) { - return options.customFetchImpl; - } - if (typeof globalThis !== "undefined" && isFunction2(globalThis.fetch)) { - return globalThis.fetch; - } - if (typeof window !== "undefined" && isFunction2(window.fetch)) { - return window.fetch; - } - throw new Error("No fetch implementation found"); -} -async function getHeaders(opts) { - const headers = new Headers(opts == null ? void 0 : opts.headers); - const authHeader = await getAuthHeader(opts); - for (const [key, value] of Object.entries(authHeader || {})) { - headers.set(key, value); - } - if (!headers.has("content-type")) { - const t5 = detectContentType(opts == null ? void 0 : opts.body); - if (t5) { - headers.set("content-type", t5); - } - } - return headers; -} -function detectContentType(body) { - if (isJSONSerializable2(body)) { - return "application/json"; - } - return null; -} -function getBody2(options) { - if (!(options == null ? void 0 : options.body)) { - return null; - } - const headers = new Headers(options == null ? void 0 : options.headers); - if (isJSONSerializable2(options.body) && !headers.has("content-type")) { - for (const [key, value] of Object.entries(options == null ? void 0 : options.body)) { - if (value instanceof Date) { - options.body[key] = value.toISOString(); - } - } - return JSON.stringify(options.body); - } - if (headers.has("content-type") && headers.get("content-type") === "application/x-www-form-urlencoded") { - if (isJSONSerializable2(options.body)) { - return new URLSearchParams(options.body).toString(); - } - return options.body; - } - return options.body; -} -function getMethod(url2, options) { - var _a6; - if (options == null ? void 0 : options.method) { - return options.method.toUpperCase(); - } - if (url2.startsWith("@")) { - const pMethod = (_a6 = url2.split("@")[1]) == null ? void 0 : _a6.split("/")[0]; - if (!methods.includes(pMethod)) { - return (options == null ? void 0 : options.body) ? "POST" : "GET"; - } - return pMethod.toUpperCase(); - } - return (options == null ? void 0 : options.body) ? "POST" : "GET"; -} -function getTimeout(options, controller) { - let abortTimeout; - if (!(options == null ? void 0 : options.signal) && (options == null ? void 0 : options.timeout)) { - abortTimeout = setTimeout(() => controller == null ? void 0 : controller.abort(), options == null ? void 0 : options.timeout); - } - return { - abortTimeout, - clearTimeout: () => { - if (abortTimeout) { - clearTimeout(abortTimeout); - } - } - }; -} -async function parseStandardSchema(schema2, input) { - const result = await schema2["~standard"].validate(input); - if (result.issues) { - throw new ValidationError2(result.issues); - } - return result.value; -} -function getURL2(url2, option) { - const { baseURL, params, query } = option || { - query: {}, - params: {}, - baseURL: "" - }; - let basePath = url2.startsWith("http") ? url2.split("/").slice(0, 3).join("/") : baseURL || ""; - if (url2.startsWith("@")) { - const m5 = url2.toString().split("@")[1].split("/")[0]; - if (methods.includes(m5)) { - url2 = url2.replace(`@${m5}/`, "/"); - } - } - if (!basePath.endsWith("/")) basePath += "/"; - let [path53, urlQuery] = url2.replace(basePath, "").split("?"); - const queryParams = new URLSearchParams(urlQuery); - for (const [key, value] of Object.entries(query || {})) { - if (value == null) continue; - let serializedValue; - if (typeof value === "string") { - serializedValue = value; - } else if (Array.isArray(value)) { - for (const val of value) { - queryParams.append(key, val); - } - continue; - } else { - serializedValue = JSON.stringify(value); - } - queryParams.set(key, serializedValue); - } - if (params) { - if (Array.isArray(params)) { - const paramPaths = path53.split("/").filter((p5) => p5.startsWith(":")); - for (const [index2, key] of paramPaths.entries()) { - const value = params[index2]; - path53 = path53.replace(key, value); - } - } else { - for (const [key, value] of Object.entries(params)) { - path53 = path53.replace(`:${key}`, String(value)); - } - } - } - path53 = path53.split("/").map(encodeURIComponent).join("/"); - if (path53.startsWith("/")) path53 = path53.slice(1); - let queryParamString = queryParams.toString(); - queryParamString = queryParamString.length > 0 ? `?${queryParamString}`.replace(/\+/g, "%20") : ""; - if (!basePath.startsWith("http")) { - return `${basePath}${path53}${queryParamString}`; - } - const _url2 = new URL(`${path53}${queryParamString}`, basePath); - return _url2; -} -var __defProp3, __defProps, __getOwnPropDescs, __getOwnPropSymbols, __hasOwnProp3, __propIsEnum, __defNormalProp, __spreadValues, __spreadProps, BetterFetchError, initializePlugins, LinearRetryStrategy, ExponentialRetryStrategy, getAuthHeader, JSON_RE, ValidationError2, methods, betterFetch; -var init_dist4 = __esm({ - "node_modules/.pnpm/@better-fetch+fetch@1.1.21/node_modules/@better-fetch/fetch/dist/index.js"() { - __defProp3 = Object.defineProperty; - __defProps = Object.defineProperties; - __getOwnPropDescs = Object.getOwnPropertyDescriptors; - __getOwnPropSymbols = Object.getOwnPropertySymbols; - __hasOwnProp3 = Object.prototype.hasOwnProperty; - __propIsEnum = Object.prototype.propertyIsEnumerable; - __defNormalProp = (obj, key, value) => key in obj ? __defProp3(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; - __spreadValues = (a5, b6) => { - for (var prop in b6 || (b6 = {})) - if (__hasOwnProp3.call(b6, prop)) - __defNormalProp(a5, prop, b6[prop]); - if (__getOwnPropSymbols) - for (var prop of __getOwnPropSymbols(b6)) { - if (__propIsEnum.call(b6, prop)) - __defNormalProp(a5, prop, b6[prop]); - } - return a5; - }; - __spreadProps = (a5, b6) => __defProps(a5, __getOwnPropDescs(b6)); - BetterFetchError = class extends Error { - constructor(status, statusText, error50) { - super(statusText || status.toString(), { - cause: error50 - }); - this.status = status; - this.statusText = statusText; - this.error = error50; - Error.captureStackTrace(this, this.constructor); - } - }; - initializePlugins = async (url2, options) => { - var _a6, _b, _c5, _d, _e5, _f; - let opts = options || {}; - const hooks = { - onRequest: [options == null ? void 0 : options.onRequest], - onResponse: [options == null ? void 0 : options.onResponse], - onSuccess: [options == null ? void 0 : options.onSuccess], - onError: [options == null ? void 0 : options.onError], - onRetry: [options == null ? void 0 : options.onRetry] - }; - if (!options || !(options == null ? void 0 : options.plugins)) { - return { - url: url2, - options: opts, - hooks - }; - } - for (const plugin of (options == null ? void 0 : options.plugins) || []) { - if (plugin.init) { - const pluginRes = await ((_a6 = plugin.init) == null ? void 0 : _a6.call(plugin, url2.toString(), options)); - opts = pluginRes.options || opts; - url2 = pluginRes.url; - } - hooks.onRequest.push((_b = plugin.hooks) == null ? void 0 : _b.onRequest); - hooks.onResponse.push((_c5 = plugin.hooks) == null ? void 0 : _c5.onResponse); - hooks.onSuccess.push((_d = plugin.hooks) == null ? void 0 : _d.onSuccess); - hooks.onError.push((_e5 = plugin.hooks) == null ? void 0 : _e5.onError); - hooks.onRetry.push((_f = plugin.hooks) == null ? void 0 : _f.onRetry); - } - return { - url: url2, - options: opts, - hooks - }; - }; - LinearRetryStrategy = class { - constructor(options) { - this.options = options; - } - shouldAttemptRetry(attempt, response) { - if (this.options.shouldRetry) { - return Promise.resolve( - attempt < this.options.attempts && this.options.shouldRetry(response) - ); - } - return Promise.resolve(attempt < this.options.attempts); - } - getDelay() { - return this.options.delay; - } - }; - ExponentialRetryStrategy = class { - constructor(options) { - this.options = options; - } - shouldAttemptRetry(attempt, response) { - if (this.options.shouldRetry) { - return Promise.resolve( - attempt < this.options.attempts && this.options.shouldRetry(response) - ); - } - return Promise.resolve(attempt < this.options.attempts); - } - getDelay(attempt) { - const delay3 = Math.min( - this.options.maxDelay, - this.options.baseDelay * 2 ** attempt - ); - return delay3; - } - }; - getAuthHeader = async (options) => { - const headers = {}; - const getValue = async (value) => typeof value === "function" ? await value() : value; - if (options == null ? void 0 : options.auth) { - if (options.auth.type === "Bearer") { - const token = await getValue(options.auth.token); - if (!token) { - return headers; - } - headers["authorization"] = `Bearer ${token}`; - } else if (options.auth.type === "Basic") { - const [username, password] = await Promise.all([ - getValue(options.auth.username), - getValue(options.auth.password) - ]); - if (!username || !password) { - return headers; - } - headers["authorization"] = `Basic ${btoa(`${username}:${password}`)}`; - } else if (options.auth.type === "Custom") { - const [prefix, value] = await Promise.all([ - getValue(options.auth.prefix), - getValue(options.auth.value) - ]); - if (!value) { - return headers; - } - headers["authorization"] = `${prefix != null ? prefix : ""} ${value}`; - } - } - return headers; - }; - JSON_RE = /^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i; - ValidationError2 = class _ValidationError extends Error { - constructor(issues2, message2) { - super(message2 || JSON.stringify(issues2, null, 2)); - this.issues = issues2; - Object.setPrototypeOf(this, _ValidationError.prototype); - } - }; - methods = ["get", "post", "put", "patch", "delete"]; - betterFetch = async (url2, options) => { - var _a6, _b, _c5, _d, _e5, _f, _g, _h4; - const { - hooks, - url: __url, - options: opts - } = await initializePlugins(url2, options); - const fetch2 = getFetch(opts); - const controller = new AbortController(); - const signal = (_a6 = opts.signal) != null ? _a6 : controller.signal; - const _url2 = getURL2(__url, opts); - const body = getBody2(opts); - const headers = await getHeaders(opts); - const method = getMethod(__url, opts); - let context = __spreadProps(__spreadValues({}, opts), { - url: _url2, - headers, - body, - method, - signal - }); - for (const onRequest of hooks.onRequest) { - if (onRequest) { - const res = await onRequest(context); - if (typeof res === "object" && res !== null) { - context = res; - } - } - } - if ("pipeTo" in context && typeof context.pipeTo === "function" || typeof ((_b = options == null ? void 0 : options.body) == null ? void 0 : _b.pipe) === "function") { - if (!("duplex" in context)) { - context.duplex = "half"; - } - } - const { clearTimeout: clearTimeout2 } = getTimeout(opts, controller); - let response = await fetch2(context.url, context); - clearTimeout2(); - const responseContext = { - response, - request: context - }; - for (const onResponse of hooks.onResponse) { - if (onResponse) { - const r5 = await onResponse(__spreadProps(__spreadValues({}, responseContext), { - response: ((_c5 = options == null ? void 0 : options.hookOptions) == null ? void 0 : _c5.cloneResponse) ? response.clone() : response - })); - if (r5 instanceof Response) { - response = r5; - } else if (typeof r5 === "object" && r5 !== null) { - response = r5.response; - } - } - } - if (response.ok) { - const hasBody = context.method !== "HEAD"; - if (!hasBody) { - return { - data: "", - error: null - }; - } - const responseType = detectResponseType(response); - const successContext = { - data: null, - response, - request: context - }; - if (responseType === "json" || responseType === "text") { - const text3 = await response.text(); - const parser2 = (_d = context.jsonParser) != null ? _d : jsonParse; - successContext.data = await parser2(text3); - } else { - successContext.data = await response[responseType](); - } - if (context == null ? void 0 : context.output) { - if (context.output && !context.disableValidation) { - successContext.data = await parseStandardSchema( - context.output, - successContext.data - ); - } - } - for (const onSuccess of hooks.onSuccess) { - if (onSuccess) { - await onSuccess(__spreadProps(__spreadValues({}, successContext), { - response: ((_e5 = options == null ? void 0 : options.hookOptions) == null ? void 0 : _e5.cloneResponse) ? response.clone() : response - })); - } - } - if (options == null ? void 0 : options.throw) { - return successContext.data; - } - return { - data: successContext.data, - error: null - }; - } - const parser = (_f = options == null ? void 0 : options.jsonParser) != null ? _f : jsonParse; - const responseText = await response.text(); - const isJSONResponse2 = isJSONParsable(responseText); - const errorObject = isJSONResponse2 ? await parser(responseText) : null; - const errorContext = { - response, - responseText, - request: context, - error: __spreadProps(__spreadValues({}, errorObject), { - status: response.status, - statusText: response.statusText - }) - }; - for (const onError of hooks.onError) { - if (onError) { - await onError(__spreadProps(__spreadValues({}, errorContext), { - response: ((_g = options == null ? void 0 : options.hookOptions) == null ? void 0 : _g.cloneResponse) ? response.clone() : response - })); - } - } - if (options == null ? void 0 : options.retry) { - const retryStrategy = createRetryStrategy(options.retry); - const _retryAttempt = (_h4 = options.retryAttempt) != null ? _h4 : 0; - if (await retryStrategy.shouldAttemptRetry(_retryAttempt, response)) { - for (const onRetry of hooks.onRetry) { - if (onRetry) { - await onRetry(responseContext); - } - } - const delay3 = retryStrategy.getDelay(_retryAttempt); - await new Promise((resolve4) => setTimeout(resolve4, delay3)); - return await betterFetch(url2, __spreadProps(__spreadValues({}, options), { - retryAttempt: _retryAttempt + 1 - })); - } - } - if (options == null ? void 0 : options.throw) { - throw new BetterFetchError( - response.status, - response.statusText, - isJSONResponse2 ? errorObject : responseText - ); - } - return { - data: null, - error: __spreadProps(__spreadValues({}, errorObject), { - status: response.status, - statusText: response.statusText - }) - }; - }; - } -}); - -// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/oauth2/refresh-access-token.mjs -function createRefreshAccessTokenRequest({ refreshToken: refreshToken2, options, authentication, extraParams, resource }) { - const body = new URLSearchParams(); - const headers = { - "content-type": "application/x-www-form-urlencoded", - accept: "application/json" - }; - body.set("grant_type", "refresh_token"); - body.set("refresh_token", refreshToken2); - if (authentication === "basic") { - const primaryClientId = Array.isArray(options.clientId) ? options.clientId[0] : options.clientId; - if (primaryClientId) headers["authorization"] = "Basic " + base643.encode(`${primaryClientId}:${options.clientSecret ?? ""}`); - else headers["authorization"] = "Basic " + base643.encode(`:${options.clientSecret ?? ""}`); - } else { - const primaryClientId = Array.isArray(options.clientId) ? options.clientId[0] : options.clientId; - body.set("client_id", primaryClientId); - if (options.clientSecret) body.set("client_secret", options.clientSecret); - } - if (resource) if (typeof resource === "string") body.append("resource", resource); - else for (const _resource of resource) body.append("resource", _resource); - if (extraParams) for (const [key, value] of Object.entries(extraParams)) body.set(key, value); - return { - body, - headers - }; -} -async function refreshAccessToken({ refreshToken: refreshToken2, options, tokenEndpoint, authentication, extraParams }) { - const { body, headers } = createRefreshAccessTokenRequest({ - refreshToken: refreshToken2, - options, - authentication, - extraParams - }); - const { data: data2, error: error50 } = await betterFetch(tokenEndpoint, { - method: "POST", - body, - headers - }); - if (error50) throw error50; - const tokens = { - accessToken: data2.access_token, - refreshToken: data2.refresh_token, - tokenType: data2.token_type, - scopes: data2.scope?.split(" "), - idToken: data2.id_token - }; - if (data2.expires_in) { - const now2 = /* @__PURE__ */ new Date(); - tokens.accessTokenExpiresAt = new Date(now2.getTime() + data2.expires_in * 1e3); - } - return tokens; -} -var init_refresh_access_token = __esm({ - "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/oauth2/refresh-access-token.mjs"() { - init_base642(); - init_dist4(); - } -}); - -// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/oauth2/client-credentials-token.mjs -var init_client_credentials_token = __esm({ - "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/oauth2/client-credentials-token.mjs"() { - init_base642(); - init_dist4(); - } -}); - -// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/oauth2/verify.mjs -var init_verify4 = __esm({ - "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/oauth2/verify.mjs"() { - init_logger2(); - init_env(); - init_dist4(); - init_dist3(); - } -}); - -// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/oauth2/index.mjs -var init_oauth2 = __esm({ - "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/oauth2/index.mjs"() { - init_client_credentials_token(); - init_utils13(); - init_create_authorization_url(); - init_refresh_access_token(); - init_validate_authorization_code(); - init_verify4(); - } -}); - -// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/oauth2/validate-authorization-code.mjs -function createAuthorizationCodeRequest({ code, codeVerifier, redirectURI, options, authentication, deviceId, headers, additionalParams = {}, resource }) { - const body = new URLSearchParams(); - const requestHeaders = { - "content-type": "application/x-www-form-urlencoded", - accept: "application/json", - ...headers - }; - body.set("grant_type", "authorization_code"); - body.set("code", code); - codeVerifier && body.set("code_verifier", codeVerifier); - options.clientKey && body.set("client_key", options.clientKey); - deviceId && body.set("device_id", deviceId); - body.set("redirect_uri", options.redirectURI || redirectURI); - if (resource) if (typeof resource === "string") body.append("resource", resource); - else for (const _resource of resource) body.append("resource", _resource); - if (authentication === "basic") { - const primaryClientId = Array.isArray(options.clientId) ? options.clientId[0] : options.clientId; - requestHeaders["authorization"] = `Basic ${base643.encode(`${primaryClientId}:${options.clientSecret ?? ""}`)}`; - } else { - const primaryClientId = Array.isArray(options.clientId) ? options.clientId[0] : options.clientId; - body.set("client_id", primaryClientId); - if (options.clientSecret) body.set("client_secret", options.clientSecret); - } - for (const [key, value] of Object.entries(additionalParams)) if (!body.has(key)) body.append(key, value); - return { - body, - headers: requestHeaders - }; -} -async function validateAuthorizationCode({ code, codeVerifier, redirectURI, options, tokenEndpoint, authentication, deviceId, headers, additionalParams = {}, resource }) { - const { body, headers: requestHeaders } = createAuthorizationCodeRequest({ - code, - codeVerifier, - redirectURI, - options, - authentication, - deviceId, - headers, - additionalParams, - resource - }); - const { data: data2, error: error50 } = await betterFetch(tokenEndpoint, { - method: "POST", - body, - headers: requestHeaders - }); - if (error50) throw error50; - return getOAuth2Tokens(data2); -} -var init_validate_authorization_code = __esm({ - "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/oauth2/validate-authorization-code.mjs"() { - init_utils13(); - init_oauth2(); - init_base642(); - init_dist4(); - } -}); - -// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/apple.mjs -var apple, getApplePublicKey; -var init_apple = __esm({ - "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/apple.mjs"() { - init_create_authorization_url(); - init_refresh_access_token(); - init_validate_authorization_code(); - init_oauth2(); - init_dist4(); - init_webapi(); - init_dist3(); - apple = (options) => { - const tokenEndpoint = "https://appleid.apple.com/auth/token"; - return { - id: "apple", - name: "Apple", - async createAuthorizationURL({ state: state2, scopes, redirectURI }) { - const _scope = options.disableDefaultScope ? [] : ["email", "name"]; - if (options.scope) _scope.push(...options.scope); - if (scopes) _scope.push(...scopes); - return await createAuthorizationURL({ - id: "apple", - options, - authorizationEndpoint: "https://appleid.apple.com/auth/authorize", - scopes: _scope, - state: state2, - redirectURI, - responseMode: "form_post", - responseType: "code id_token" - }); - }, - validateAuthorizationCode: async ({ code, codeVerifier, redirectURI }) => { - return validateAuthorizationCode({ - code, - codeVerifier, - redirectURI, - options, - tokenEndpoint - }); - }, - async verifyIdToken(token, nonce) { - if (options.disableIdTokenSignIn) return false; - if (options.verifyIdToken) return options.verifyIdToken(token, nonce); - const { kid, alg: jwtAlg } = decodeProtectedHeader(token); - if (!kid || !jwtAlg) return false; - const { payload: jwtClaims } = await jwtVerify(token, await getApplePublicKey(kid), { - algorithms: [jwtAlg], - issuer: "https://appleid.apple.com", - audience: options.audience && options.audience.length ? options.audience : options.appBundleIdentifier ? options.appBundleIdentifier : options.clientId, - maxTokenAge: "1h" - }); - ["email_verified", "is_private_email"].forEach((field) => { - if (jwtClaims[field] !== void 0) jwtClaims[field] = Boolean(jwtClaims[field]); - }); - if (nonce && jwtClaims.nonce !== nonce) return false; - return !!jwtClaims; - }, - refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { - return refreshAccessToken({ - refreshToken: refreshToken2, - options: { - clientId: options.clientId, - clientKey: options.clientKey, - clientSecret: options.clientSecret - }, - tokenEndpoint: "https://appleid.apple.com/auth/token" - }); - }, - async getUserInfo(token) { - if (options.getUserInfo) return options.getUserInfo(token); - if (!token.idToken) return null; - const profile = decodeJwt(token.idToken); - if (!profile) return null; - let name; - if (token.user?.name) name = `${token.user.name.firstName || ""} ${token.user.name.lastName || ""}`.trim() || " "; - else name = profile.name || " "; - const emailVerified = typeof profile.email_verified === "boolean" ? profile.email_verified : profile.email_verified === "true"; - const enrichedProfile = { - ...profile, - name - }; - const userMap = await options.mapProfileToUser?.(enrichedProfile); - return { - user: { - id: profile.sub, - name: enrichedProfile.name, - emailVerified, - email: profile.email, - ...userMap - }, - data: enrichedProfile - }; - }, - options - }; - }; - getApplePublicKey = async (kid) => { - const { data: data2 } = await betterFetch(`https://appleid.apple.com/auth/keys`); - if (!data2?.keys) throw new APIError("BAD_REQUEST", { message: "Keys not found" }); - const jwk = data2.keys.find((key) => key.kid === kid); - if (!jwk) throw new Error(`JWK with kid ${kid} not found`); - return await importJWK(jwk, jwk.alg); - }; - } -}); - -// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/atlassian.mjs -var atlassian; -var init_atlassian = __esm({ - "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/atlassian.mjs"() { - init_logger2(); - init_env(); - init_error(); - init_create_authorization_url(); - init_refresh_access_token(); - init_validate_authorization_code(); - init_oauth2(); - init_dist4(); - atlassian = (options) => { - return { - id: "atlassian", - name: "Atlassian", - async createAuthorizationURL({ state: state2, scopes, codeVerifier, redirectURI }) { - if (!options.clientId || !options.clientSecret) { - logger3.error("Client Id and Secret are required for Atlassian"); - throw new BetterAuthError("CLIENT_ID_AND_SECRET_REQUIRED"); - } - if (!codeVerifier) throw new BetterAuthError("codeVerifier is required for Atlassian"); - const _scopes = options.disableDefaultScope ? [] : ["read:jira-user", "offline_access"]; - if (options.scope) _scopes.push(...options.scope); - if (scopes) _scopes.push(...scopes); - return createAuthorizationURL({ - id: "atlassian", - options, - authorizationEndpoint: "https://auth.atlassian.com/authorize", - scopes: _scopes, - state: state2, - codeVerifier, - redirectURI, - additionalParams: { audience: "api.atlassian.com" }, - prompt: options.prompt - }); - }, - validateAuthorizationCode: async ({ code, codeVerifier, redirectURI }) => { - return validateAuthorizationCode({ - code, - codeVerifier, - redirectURI, - options, - tokenEndpoint: "https://auth.atlassian.com/oauth/token" - }); - }, - refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { - return refreshAccessToken({ - refreshToken: refreshToken2, - options: { - clientId: options.clientId, - clientSecret: options.clientSecret - }, - tokenEndpoint: "https://auth.atlassian.com/oauth/token" - }); - }, - async getUserInfo(token) { - if (options.getUserInfo) return options.getUserInfo(token); - if (!token.accessToken) return null; - try { - const { data: profile } = await betterFetch("https://api.atlassian.com/me", { headers: { Authorization: `Bearer ${token.accessToken}` } }); - if (!profile) return null; - const userMap = await options.mapProfileToUser?.(profile); - return { - user: { - id: profile.account_id, - name: profile.name, - email: profile.email, - image: profile.picture, - emailVerified: false, - ...userMap - }, - data: profile - }; - } catch (error50) { - logger3.error("Failed to fetch user info from Figma:", error50); - return null; - } - }, - options - }; - }; - } -}); - -// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/cognito.mjs -var cognito, getCognitoPublicKey; -var init_cognito = __esm({ - "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/cognito.mjs"() { - init_logger2(); - init_env(); - init_error(); - init_create_authorization_url(); - init_refresh_access_token(); - init_validate_authorization_code(); - init_oauth2(); - init_dist4(); - init_webapi(); - init_dist3(); - cognito = (options) => { - if (!options.domain || !options.region || !options.userPoolId) { - logger3.error("Domain, region and userPoolId are required for Amazon Cognito. Make sure to provide them in the options."); - throw new BetterAuthError("DOMAIN_AND_REGION_REQUIRED"); - } - const cleanDomain = options.domain.replace(/^https?:\/\//, ""); - const authorizationEndpoint = `https://${cleanDomain}/oauth2/authorize`; - const tokenEndpoint = `https://${cleanDomain}/oauth2/token`; - const userInfoEndpoint = `https://${cleanDomain}/oauth2/userinfo`; - return { - id: "cognito", - name: "Cognito", - async createAuthorizationURL({ state: state2, scopes, codeVerifier, redirectURI }) { - if (!options.clientId) { - logger3.error("ClientId is required for Amazon Cognito. Make sure to provide them in the options."); - throw new BetterAuthError("CLIENT_ID_AND_SECRET_REQUIRED"); - } - if (options.requireClientSecret && !options.clientSecret) { - logger3.error("Client Secret is required when requireClientSecret is true. Make sure to provide it in the options."); - throw new BetterAuthError("CLIENT_SECRET_REQUIRED"); - } - const _scopes = options.disableDefaultScope ? [] : [ - "openid", - "profile", - "email" - ]; - if (options.scope) _scopes.push(...options.scope); - if (scopes) _scopes.push(...scopes); - const url2 = await createAuthorizationURL({ - id: "cognito", - options: { ...options }, - authorizationEndpoint, - scopes: _scopes, - state: state2, - codeVerifier, - redirectURI, - prompt: options.prompt - }); - const scopeValue = url2.searchParams.get("scope"); - if (scopeValue) { - url2.searchParams.delete("scope"); - const encodedScope = encodeURIComponent(scopeValue); - const urlString = url2.toString(); - const separator = urlString.includes("?") ? "&" : "?"; - return new URL(`${urlString}${separator}scope=${encodedScope}`); - } - return url2; - }, - validateAuthorizationCode: async ({ code, codeVerifier, redirectURI }) => { - return validateAuthorizationCode({ - code, - codeVerifier, - redirectURI, - options, - tokenEndpoint - }); - }, - refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { - return refreshAccessToken({ - refreshToken: refreshToken2, - options: { - clientId: options.clientId, - clientKey: options.clientKey, - clientSecret: options.clientSecret - }, - tokenEndpoint - }); - }, - async verifyIdToken(token, nonce) { - if (options.disableIdTokenSignIn) return false; - if (options.verifyIdToken) return options.verifyIdToken(token, nonce); - try { - const { kid, alg: jwtAlg } = decodeProtectedHeader(token); - if (!kid || !jwtAlg) return false; - const publicKey = await getCognitoPublicKey(kid, options.region, options.userPoolId); - const expectedIssuer = `https://cognito-idp.${options.region}.amazonaws.com/${options.userPoolId}`; - const { payload: jwtClaims } = await jwtVerify(token, publicKey, { - algorithms: [jwtAlg], - issuer: expectedIssuer, - audience: options.clientId, - maxTokenAge: "1h" - }); - if (nonce && jwtClaims.nonce !== nonce) return false; - return true; - } catch (error50) { - logger3.error("Failed to verify ID token:", error50); - return false; - } - }, - async getUserInfo(token) { - if (options.getUserInfo) return options.getUserInfo(token); - if (token.idToken) try { - const profile = decodeJwt(token.idToken); - if (!profile) return null; - const name = profile.name || profile.given_name || profile.username || profile.email; - const enrichedProfile = { - ...profile, - name - }; - const userMap = await options.mapProfileToUser?.(enrichedProfile); - return { - user: { - id: profile.sub, - name: enrichedProfile.name, - email: profile.email, - image: profile.picture, - emailVerified: profile.email_verified, - ...userMap - }, - data: enrichedProfile - }; - } catch (error50) { - logger3.error("Failed to decode ID token:", error50); - } - if (token.accessToken) try { - const { data: userInfo } = await betterFetch(userInfoEndpoint, { headers: { Authorization: `Bearer ${token.accessToken}` } }); - if (userInfo) { - const userMap = await options.mapProfileToUser?.(userInfo); - return { - user: { - id: userInfo.sub, - name: userInfo.name || userInfo.given_name || userInfo.username, - email: userInfo.email, - image: userInfo.picture, - emailVerified: userInfo.email_verified, - ...userMap - }, - data: userInfo - }; - } - } catch (error50) { - logger3.error("Failed to fetch user info from Cognito:", error50); - } - return null; - }, - options - }; - }; - getCognitoPublicKey = async (kid, region, userPoolId) => { - const COGNITO_JWKS_URI = `https://cognito-idp.${region}.amazonaws.com/${userPoolId}/.well-known/jwks.json`; - try { - const { data: data2 } = await betterFetch(COGNITO_JWKS_URI); - if (!data2?.keys) throw new APIError("BAD_REQUEST", { message: "Keys not found" }); - const jwk = data2.keys.find((key) => key.kid === kid); - if (!jwk) throw new Error(`JWK with kid ${kid} not found`); - return await importJWK(jwk, jwk.alg); - } catch (error50) { - logger3.error("Failed to fetch Cognito public key:", error50); - throw error50; - } - }; - } -}); - -// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/discord.mjs -var discord; -var init_discord = __esm({ - "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/discord.mjs"() { - init_refresh_access_token(); - init_validate_authorization_code(); - init_oauth2(); - init_dist4(); - discord = (options) => { - return { - id: "discord", - name: "Discord", - createAuthorizationURL({ state: state2, scopes, redirectURI }) { - const _scopes = options.disableDefaultScope ? [] : ["identify", "email"]; - if (scopes) _scopes.push(...scopes); - if (options.scope) _scopes.push(...options.scope); - const permissionsParam = _scopes.includes("bot") && options.permissions !== void 0 ? `&permissions=${options.permissions}` : ""; - return new URL(`https://discord.com/api/oauth2/authorize?scope=${_scopes.join("+")}&response_type=code&client_id=${options.clientId}&redirect_uri=${encodeURIComponent(options.redirectURI || redirectURI)}&state=${state2}&prompt=${options.prompt || "none"}${permissionsParam}`); - }, - validateAuthorizationCode: async ({ code, redirectURI }) => { - return validateAuthorizationCode({ - code, - redirectURI, - options, - tokenEndpoint: "https://discord.com/api/oauth2/token" - }); - }, - refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { - return refreshAccessToken({ - refreshToken: refreshToken2, - options: { - clientId: options.clientId, - clientKey: options.clientKey, - clientSecret: options.clientSecret - }, - tokenEndpoint: "https://discord.com/api/oauth2/token" - }); - }, - async getUserInfo(token) { - if (options.getUserInfo) return options.getUserInfo(token); - const { data: profile, error: error50 } = await betterFetch("https://discord.com/api/users/@me", { headers: { authorization: `Bearer ${token.accessToken}` } }); - if (error50) return null; - if (profile.avatar === null) profile.image_url = `https://cdn.discordapp.com/embed/avatars/${profile.discriminator === "0" ? Number(BigInt(profile.id) >> BigInt(22)) % 6 : parseInt(profile.discriminator) % 5}.png`; - else { - const format2 = profile.avatar.startsWith("a_") ? "gif" : "png"; - profile.image_url = `https://cdn.discordapp.com/avatars/${profile.id}/${profile.avatar}.${format2}`; - } - const userMap = await options.mapProfileToUser?.(profile); - return { - user: { - id: profile.id, - name: profile.global_name || profile.username || "", - email: profile.email, - emailVerified: profile.verified, - image: profile.image_url, - ...userMap - }, - data: profile - }; - }, - options - }; - }; - } -}); - -// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/dropbox.mjs -var dropbox; -var init_dropbox = __esm({ - "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/dropbox.mjs"() { - init_create_authorization_url(); - init_refresh_access_token(); - init_validate_authorization_code(); - init_oauth2(); - init_dist4(); - dropbox = (options) => { - const tokenEndpoint = "https://api.dropboxapi.com/oauth2/token"; - return { - id: "dropbox", - name: "Dropbox", - createAuthorizationURL: async ({ state: state2, scopes, codeVerifier, redirectURI }) => { - const _scopes = options.disableDefaultScope ? [] : ["account_info.read"]; - if (options.scope) _scopes.push(...options.scope); - if (scopes) _scopes.push(...scopes); - const additionalParams = {}; - if (options.accessType) additionalParams.token_access_type = options.accessType; - return await createAuthorizationURL({ - id: "dropbox", - options, - authorizationEndpoint: "https://www.dropbox.com/oauth2/authorize", - scopes: _scopes, - state: state2, - redirectURI, - codeVerifier, - additionalParams - }); - }, - validateAuthorizationCode: async ({ code, codeVerifier, redirectURI }) => { - return await validateAuthorizationCode({ - code, - codeVerifier, - redirectURI, - options, - tokenEndpoint - }); - }, - refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { - return refreshAccessToken({ - refreshToken: refreshToken2, - options: { - clientId: options.clientId, - clientKey: options.clientKey, - clientSecret: options.clientSecret - }, - tokenEndpoint: "https://api.dropbox.com/oauth2/token" - }); - }, - async getUserInfo(token) { - if (options.getUserInfo) return options.getUserInfo(token); - const { data: profile, error: error50 } = await betterFetch("https://api.dropboxapi.com/2/users/get_current_account", { - method: "POST", - headers: { Authorization: `Bearer ${token.accessToken}` } - }); - if (error50) return null; - const userMap = await options.mapProfileToUser?.(profile); - return { - user: { - id: profile.account_id, - name: profile.name?.display_name, - email: profile.email, - emailVerified: profile.email_verified || false, - image: profile.profile_photo_url, - ...userMap - }, - data: profile - }; - }, - options - }; - }; - } -}); - -// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/facebook.mjs -var facebook; -var init_facebook = __esm({ - "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/facebook.mjs"() { - init_create_authorization_url(); - init_refresh_access_token(); - init_validate_authorization_code(); - init_oauth2(); - init_dist4(); - init_webapi(); - facebook = (options) => { - return { - id: "facebook", - name: "Facebook", - async createAuthorizationURL({ state: state2, scopes, redirectURI, loginHint }) { - const _scopes = options.disableDefaultScope ? [] : ["email", "public_profile"]; - if (options.scope) _scopes.push(...options.scope); - if (scopes) _scopes.push(...scopes); - return await createAuthorizationURL({ - id: "facebook", - options, - authorizationEndpoint: "https://www.facebook.com/v24.0/dialog/oauth", - scopes: _scopes, - state: state2, - redirectURI, - loginHint, - additionalParams: options.configId ? { config_id: options.configId } : {} - }); - }, - validateAuthorizationCode: async ({ code, redirectURI }) => { - return validateAuthorizationCode({ - code, - redirectURI, - options, - tokenEndpoint: "https://graph.facebook.com/v24.0/oauth/access_token" - }); - }, - async verifyIdToken(token, nonce) { - if (options.disableIdTokenSignIn) return false; - if (options.verifyIdToken) return options.verifyIdToken(token, nonce); - if (token.split(".").length === 3) try { - const { payload: jwtClaims } = await jwtVerify(token, createRemoteJWKSet(new URL("https://limited.facebook.com/.well-known/oauth/openid/jwks/")), { - algorithms: ["RS256"], - audience: options.clientId, - issuer: "https://www.facebook.com" - }); - if (nonce && jwtClaims.nonce !== nonce) return false; - return !!jwtClaims; - } catch { - return false; - } - return true; - }, - refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { - return refreshAccessToken({ - refreshToken: refreshToken2, - options: { - clientId: options.clientId, - clientKey: options.clientKey, - clientSecret: options.clientSecret - }, - tokenEndpoint: "https://graph.facebook.com/v24.0/oauth/access_token" - }); - }, - async getUserInfo(token) { - if (options.getUserInfo) return options.getUserInfo(token); - if (token.idToken && token.idToken.split(".").length === 3) { - const profile$1 = decodeJwt(token.idToken); - const user = { - id: profile$1.sub, - name: profile$1.name, - email: profile$1.email, - picture: { data: { - url: profile$1.picture, - height: 100, - width: 100, - is_silhouette: false - } } - }; - const userMap$1 = await options.mapProfileToUser?.({ - ...user, - email_verified: false - }); - return { - user: { - ...user, - emailVerified: false, - ...userMap$1 - }, - data: profile$1 - }; - } - const { data: profile, error: error50 } = await betterFetch("https://graph.facebook.com/me?fields=" + [ - "id", - "name", - "email", - "picture", - ...options?.fields || [] - ].join(","), { auth: { - type: "Bearer", - token: token.accessToken - } }); - if (error50) return null; - const userMap = await options.mapProfileToUser?.(profile); - return { - user: { - id: profile.id, - name: profile.name, - email: profile.email, - image: profile.picture.data.url, - emailVerified: profile.email_verified, - ...userMap - }, - data: profile - }; - }, - options - }; - }; - } -}); - -// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/figma.mjs -var figma; -var init_figma = __esm({ - "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/figma.mjs"() { - init_logger2(); - init_env(); - init_error(); - init_create_authorization_url(); - init_refresh_access_token(); - init_validate_authorization_code(); - init_oauth2(); - init_dist4(); - figma = (options) => { - return { - id: "figma", - name: "Figma", - async createAuthorizationURL({ state: state2, scopes, codeVerifier, redirectURI }) { - if (!options.clientId || !options.clientSecret) { - logger3.error("Client Id and Client Secret are required for Figma. Make sure to provide them in the options."); - throw new BetterAuthError("CLIENT_ID_AND_SECRET_REQUIRED"); - } - if (!codeVerifier) throw new BetterAuthError("codeVerifier is required for Figma"); - const _scopes = options.disableDefaultScope ? [] : ["current_user:read"]; - if (options.scope) _scopes.push(...options.scope); - if (scopes) _scopes.push(...scopes); - return await createAuthorizationURL({ - id: "figma", - options, - authorizationEndpoint: "https://www.figma.com/oauth", - scopes: _scopes, - state: state2, - codeVerifier, - redirectURI - }); - }, - validateAuthorizationCode: async ({ code, codeVerifier, redirectURI }) => { - return validateAuthorizationCode({ - code, - codeVerifier, - redirectURI, - options, - tokenEndpoint: "https://api.figma.com/v1/oauth/token", - authentication: "basic" - }); - }, - refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { - return refreshAccessToken({ - refreshToken: refreshToken2, - options: { - clientId: options.clientId, - clientKey: options.clientKey, - clientSecret: options.clientSecret - }, - tokenEndpoint: "https://api.figma.com/v1/oauth/token", - authentication: "basic" - }); - }, - async getUserInfo(token) { - if (options.getUserInfo) return options.getUserInfo(token); - try { - const { data: profile } = await betterFetch("https://api.figma.com/v1/me", { headers: { Authorization: `Bearer ${token.accessToken}` } }); - if (!profile) { - logger3.error("Failed to fetch user from Figma"); - return null; - } - const userMap = await options.mapProfileToUser?.(profile); - return { - user: { - id: profile.id, - name: profile.handle, - email: profile.email, - image: profile.img_url, - emailVerified: false, - ...userMap - }, - data: profile - }; - } catch (error50) { - logger3.error("Failed to fetch user info from Figma:", error50); - return null; - } - }, - options - }; - }; - } -}); - -// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/github.mjs -var github; -var init_github = __esm({ - "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/github.mjs"() { - init_logger2(); - init_env(); - init_utils13(); - init_create_authorization_url(); - init_refresh_access_token(); - init_validate_authorization_code(); - init_oauth2(); - init_dist4(); - github = (options) => { - const tokenEndpoint = "https://github.com/login/oauth/access_token"; - return { - id: "github", - name: "GitHub", - createAuthorizationURL({ state: state2, scopes, loginHint, codeVerifier, redirectURI }) { - const _scopes = options.disableDefaultScope ? [] : ["read:user", "user:email"]; - if (options.scope) _scopes.push(...options.scope); - if (scopes) _scopes.push(...scopes); - return createAuthorizationURL({ - id: "github", - options, - authorizationEndpoint: "https://github.com/login/oauth/authorize", - scopes: _scopes, - state: state2, - codeVerifier, - redirectURI, - loginHint, - prompt: options.prompt - }); - }, - validateAuthorizationCode: async ({ code, codeVerifier, redirectURI }) => { - const { body, headers: requestHeaders } = createAuthorizationCodeRequest({ - code, - codeVerifier, - redirectURI, - options - }); - const { data: data2, error: error50 } = await betterFetch(tokenEndpoint, { - method: "POST", - body, - headers: requestHeaders - }); - if (error50) { - logger3.error("GitHub OAuth token exchange failed:", error50); - return null; - } - if ("error" in data2) { - logger3.error("GitHub OAuth token exchange failed:", data2); - return null; - } - return getOAuth2Tokens(data2); - }, - refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { - return refreshAccessToken({ - refreshToken: refreshToken2, - options: { - clientId: options.clientId, - clientKey: options.clientKey, - clientSecret: options.clientSecret - }, - tokenEndpoint: "https://github.com/login/oauth/access_token" - }); - }, - async getUserInfo(token) { - if (options.getUserInfo) return options.getUserInfo(token); - const { data: profile, error: error50 } = await betterFetch("https://api.github.com/user", { headers: { - "User-Agent": "better-auth", - authorization: `Bearer ${token.accessToken}` - } }); - if (error50) return null; - const { data: emails } = await betterFetch("https://api.github.com/user/emails", { headers: { - Authorization: `Bearer ${token.accessToken}`, - "User-Agent": "better-auth" - } }); - if (!profile.email && emails) profile.email = (emails.find((e5) => e5.primary) ?? emails[0])?.email; - const emailVerified = emails?.find((e5) => e5.email === profile.email)?.verified ?? false; - const userMap = await options.mapProfileToUser?.(profile); - return { - user: { - id: profile.id, - name: profile.name || profile.login, - email: profile.email, - image: profile.avatar_url, - emailVerified, - ...userMap - }, - data: profile - }; - }, - options - }; - }; - } -}); - -// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/gitlab.mjs -var cleanDoubleSlashes, issuerToEndpoints, gitlab; -var init_gitlab = __esm({ - "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/gitlab.mjs"() { - init_create_authorization_url(); - init_refresh_access_token(); - init_validate_authorization_code(); - init_oauth2(); - init_dist4(); - cleanDoubleSlashes = (input = "") => { - return input.split("://").map((str) => str.replace(/\/{2,}/g, "/")).join("://"); - }; - issuerToEndpoints = (issuer) => { - const baseUrl = issuer || "https://gitlab.com"; - return { - authorizationEndpoint: cleanDoubleSlashes(`${baseUrl}/oauth/authorize`), - tokenEndpoint: cleanDoubleSlashes(`${baseUrl}/oauth/token`), - userinfoEndpoint: cleanDoubleSlashes(`${baseUrl}/api/v4/user`) - }; - }; - gitlab = (options) => { - const { authorizationEndpoint, tokenEndpoint, userinfoEndpoint } = issuerToEndpoints(options.issuer); - const issuerId = "gitlab"; - return { - id: issuerId, - name: "Gitlab", - createAuthorizationURL: async ({ state: state2, scopes, codeVerifier, loginHint, redirectURI }) => { - const _scopes = options.disableDefaultScope ? [] : ["read_user"]; - if (options.scope) _scopes.push(...options.scope); - if (scopes) _scopes.push(...scopes); - return await createAuthorizationURL({ - id: issuerId, - options, - authorizationEndpoint, - scopes: _scopes, - state: state2, - redirectURI, - codeVerifier, - loginHint - }); - }, - validateAuthorizationCode: async ({ code, redirectURI, codeVerifier }) => { - return validateAuthorizationCode({ - code, - redirectURI, - options, - codeVerifier, - tokenEndpoint - }); - }, - refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { - return refreshAccessToken({ - refreshToken: refreshToken2, - options: { - clientId: options.clientId, - clientKey: options.clientKey, - clientSecret: options.clientSecret - }, - tokenEndpoint - }); - }, - async getUserInfo(token) { - if (options.getUserInfo) return options.getUserInfo(token); - const { data: profile, error: error50 } = await betterFetch(userinfoEndpoint, { headers: { authorization: `Bearer ${token.accessToken}` } }); - if (error50 || profile.state !== "active" || profile.locked) return null; - const userMap = await options.mapProfileToUser?.(profile); - return { - user: { - id: profile.id, - name: profile.name ?? profile.username, - email: profile.email, - image: profile.avatar_url, - emailVerified: profile.email_verified ?? false, - ...userMap - }, - data: profile - }; - }, - options - }; - }; - } -}); - -// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/google.mjs -var google, getGooglePublicKey; -var init_google = __esm({ - "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/google.mjs"() { - init_logger2(); - init_env(); - init_error(); - init_create_authorization_url(); - init_refresh_access_token(); - init_validate_authorization_code(); - init_oauth2(); - init_dist4(); - init_webapi(); - init_dist3(); - google = (options) => { - return { - id: "google", - name: "Google", - async createAuthorizationURL({ state: state2, scopes, codeVerifier, redirectURI, loginHint, display }) { - if (!options.clientId || !options.clientSecret) { - logger3.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."); - throw new BetterAuthError("CLIENT_ID_AND_SECRET_REQUIRED"); - } - if (!codeVerifier) throw new BetterAuthError("codeVerifier is required for Google"); - const _scopes = options.disableDefaultScope ? [] : [ - "email", - "profile", - "openid" - ]; - if (options.scope) _scopes.push(...options.scope); - if (scopes) _scopes.push(...scopes); - return await createAuthorizationURL({ - id: "google", - options, - authorizationEndpoint: "https://accounts.google.com/o/oauth2/v2/auth", - scopes: _scopes, - state: state2, - codeVerifier, - redirectURI, - prompt: options.prompt, - accessType: options.accessType, - display: display || options.display, - loginHint, - hd: options.hd, - additionalParams: { include_granted_scopes: "true" } - }); - }, - validateAuthorizationCode: async ({ code, codeVerifier, redirectURI }) => { - return validateAuthorizationCode({ - code, - codeVerifier, - redirectURI, - options, - tokenEndpoint: "https://oauth2.googleapis.com/token" - }); - }, - refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { - return refreshAccessToken({ - refreshToken: refreshToken2, - options: { - clientId: options.clientId, - clientKey: options.clientKey, - clientSecret: options.clientSecret - }, - tokenEndpoint: "https://oauth2.googleapis.com/token" - }); - }, - async verifyIdToken(token, nonce) { - if (options.disableIdTokenSignIn) return false; - if (options.verifyIdToken) return options.verifyIdToken(token, nonce); - const { kid, alg: jwtAlg } = decodeProtectedHeader(token); - if (!kid || !jwtAlg) return false; - const { payload: jwtClaims } = await jwtVerify(token, await getGooglePublicKey(kid), { - algorithms: [jwtAlg], - issuer: ["https://accounts.google.com", "accounts.google.com"], - audience: options.clientId, - maxTokenAge: "1h" - }); - if (nonce && jwtClaims.nonce !== nonce) return false; - return true; - }, - async getUserInfo(token) { - if (options.getUserInfo) return options.getUserInfo(token); - if (!token.idToken) return null; - const user = decodeJwt(token.idToken); - const userMap = await options.mapProfileToUser?.(user); - return { - user: { - id: user.sub, - name: user.name, - email: user.email, - image: user.picture, - emailVerified: user.email_verified, - ...userMap - }, - data: user - }; - }, - options - }; - }; - getGooglePublicKey = async (kid) => { - const { data: data2 } = await betterFetch("https://www.googleapis.com/oauth2/v3/certs"); - if (!data2?.keys) throw new APIError("BAD_REQUEST", { message: "Keys not found" }); - const jwk = data2.keys.find((key) => key.kid === kid); - if (!jwk) throw new Error(`JWK with kid ${kid} not found`); - return await importJWK(jwk, jwk.alg); - }; - } -}); - -// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/huggingface.mjs -var huggingface; -var init_huggingface = __esm({ - "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/huggingface.mjs"() { - init_create_authorization_url(); - init_refresh_access_token(); - init_validate_authorization_code(); - init_oauth2(); - init_dist4(); - huggingface = (options) => { - return { - id: "huggingface", - name: "Hugging Face", - createAuthorizationURL({ state: state2, scopes, codeVerifier, redirectURI }) { - const _scopes = options.disableDefaultScope ? [] : [ - "openid", - "profile", - "email" - ]; - if (options.scope) _scopes.push(...options.scope); - if (scopes) _scopes.push(...scopes); - return createAuthorizationURL({ - id: "huggingface", - options, - authorizationEndpoint: "https://huggingface.co/oauth/authorize", - scopes: _scopes, - state: state2, - codeVerifier, - redirectURI - }); - }, - validateAuthorizationCode: async ({ code, codeVerifier, redirectURI }) => { - return validateAuthorizationCode({ - code, - codeVerifier, - redirectURI, - options, - tokenEndpoint: "https://huggingface.co/oauth/token" - }); - }, - refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { - return refreshAccessToken({ - refreshToken: refreshToken2, - options: { - clientId: options.clientId, - clientKey: options.clientKey, - clientSecret: options.clientSecret - }, - tokenEndpoint: "https://huggingface.co/oauth/token" - }); - }, - async getUserInfo(token) { - if (options.getUserInfo) return options.getUserInfo(token); - const { data: profile, error: error50 } = await betterFetch("https://huggingface.co/oauth/userinfo", { - method: "GET", - headers: { Authorization: `Bearer ${token.accessToken}` } - }); - if (error50) return null; - const userMap = await options.mapProfileToUser?.(profile); - return { - user: { - id: profile.sub, - name: profile.name || profile.preferred_username, - email: profile.email, - image: profile.picture, - emailVerified: profile.email_verified ?? false, - ...userMap - }, - data: profile - }; - }, - options - }; - }; - } -}); - -// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/kakao.mjs -var kakao; -var init_kakao = __esm({ - "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/kakao.mjs"() { - init_create_authorization_url(); - init_refresh_access_token(); - init_validate_authorization_code(); - init_oauth2(); - init_dist4(); - kakao = (options) => { - return { - id: "kakao", - name: "Kakao", - createAuthorizationURL({ state: state2, scopes, redirectURI }) { - const _scopes = options.disableDefaultScope ? [] : [ - "account_email", - "profile_image", - "profile_nickname" - ]; - if (options.scope) _scopes.push(...options.scope); - if (scopes) _scopes.push(...scopes); - return createAuthorizationURL({ - id: "kakao", - options, - authorizationEndpoint: "https://kauth.kakao.com/oauth/authorize", - scopes: _scopes, - state: state2, - redirectURI - }); - }, - validateAuthorizationCode: async ({ code, redirectURI }) => { - return validateAuthorizationCode({ - code, - redirectURI, - options, - tokenEndpoint: "https://kauth.kakao.com/oauth/token" - }); - }, - refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { - return refreshAccessToken({ - refreshToken: refreshToken2, - options: { - clientId: options.clientId, - clientKey: options.clientKey, - clientSecret: options.clientSecret - }, - tokenEndpoint: "https://kauth.kakao.com/oauth/token" - }); - }, - async getUserInfo(token) { - if (options.getUserInfo) return options.getUserInfo(token); - const { data: profile, error: error50 } = await betterFetch("https://kapi.kakao.com/v2/user/me", { headers: { Authorization: `Bearer ${token.accessToken}` } }); - if (error50 || !profile) return null; - const userMap = await options.mapProfileToUser?.(profile); - const account = profile.kakao_account || {}; - const kakaoProfile = account.profile || {}; - return { - user: { - id: String(profile.id), - name: kakaoProfile.nickname || account.name || void 0, - email: account.email, - image: kakaoProfile.profile_image_url || kakaoProfile.thumbnail_image_url, - emailVerified: !!account.is_email_valid && !!account.is_email_verified, - ...userMap - }, - data: profile - }; - }, - options - }; - }; - } -}); - -// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/kick.mjs -var kick; -var init_kick = __esm({ - "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/kick.mjs"() { - init_create_authorization_url(); - init_refresh_access_token(); - init_validate_authorization_code(); - init_oauth2(); - init_dist4(); - kick = (options) => { - return { - id: "kick", - name: "Kick", - createAuthorizationURL({ state: state2, scopes, redirectURI, codeVerifier }) { - const _scopes = options.disableDefaultScope ? [] : ["user:read"]; - if (options.scope) _scopes.push(...options.scope); - if (scopes) _scopes.push(...scopes); - return createAuthorizationURL({ - id: "kick", - redirectURI, - options, - authorizationEndpoint: "https://id.kick.com/oauth/authorize", - scopes: _scopes, - codeVerifier, - state: state2 - }); - }, - async validateAuthorizationCode({ code, redirectURI, codeVerifier }) { - return validateAuthorizationCode({ - code, - redirectURI, - options, - tokenEndpoint: "https://id.kick.com/oauth/token", - codeVerifier - }); - }, - refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { - return refreshAccessToken({ - refreshToken: refreshToken2, - options: { - clientId: options.clientId, - clientSecret: options.clientSecret - }, - tokenEndpoint: "https://id.kick.com/oauth/token" - }); - }, - async getUserInfo(token) { - if (options.getUserInfo) return options.getUserInfo(token); - const { data: data2, error: error50 } = await betterFetch("https://api.kick.com/public/v1/users", { - method: "GET", - headers: { Authorization: `Bearer ${token.accessToken}` } - }); - if (error50) return null; - const profile = data2.data[0]; - const userMap = await options.mapProfileToUser?.(profile); - return { - user: { - id: profile.user_id, - name: profile.name, - email: profile.email, - image: profile.profile_picture, - emailVerified: false, - ...userMap - }, - data: profile - }; - }, - options - }; - }; - } -}); - -// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/line.mjs -var line2; -var init_line2 = __esm({ - "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/line.mjs"() { - init_create_authorization_url(); - init_refresh_access_token(); - init_validate_authorization_code(); - init_oauth2(); - init_dist4(); - init_webapi(); - line2 = (options) => { - const authorizationEndpoint = "https://access.line.me/oauth2/v2.1/authorize"; - const tokenEndpoint = "https://api.line.me/oauth2/v2.1/token"; - const userInfoEndpoint = "https://api.line.me/oauth2/v2.1/userinfo"; - const verifyIdTokenEndpoint = "https://api.line.me/oauth2/v2.1/verify"; - return { - id: "line", - name: "LINE", - async createAuthorizationURL({ state: state2, scopes, codeVerifier, redirectURI, loginHint }) { - const _scopes = options.disableDefaultScope ? [] : [ - "openid", - "profile", - "email" - ]; - if (options.scope) _scopes.push(...options.scope); - if (scopes) _scopes.push(...scopes); - return await createAuthorizationURL({ - id: "line", - options, - authorizationEndpoint, - scopes: _scopes, - state: state2, - codeVerifier, - redirectURI, - loginHint - }); - }, - validateAuthorizationCode: async ({ code, codeVerifier, redirectURI }) => { - return validateAuthorizationCode({ - code, - codeVerifier, - redirectURI, - options, - tokenEndpoint - }); - }, - refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { - return refreshAccessToken({ - refreshToken: refreshToken2, - options: { - clientId: options.clientId, - clientSecret: options.clientSecret - }, - tokenEndpoint - }); - }, - async verifyIdToken(token, nonce) { - if (options.disableIdTokenSignIn) return false; - if (options.verifyIdToken) return options.verifyIdToken(token, nonce); - const body = new URLSearchParams(); - body.set("id_token", token); - body.set("client_id", options.clientId); - if (nonce) body.set("nonce", nonce); - const { data: data2, error: error50 } = await betterFetch(verifyIdTokenEndpoint, { - method: "POST", - headers: { "content-type": "application/x-www-form-urlencoded" }, - body - }); - if (error50 || !data2) return false; - if (data2.aud !== options.clientId) return false; - if (data2.nonce && data2.nonce !== nonce) return false; - return true; - }, - async getUserInfo(token) { - if (options.getUserInfo) return options.getUserInfo(token); - let profile = null; - if (token.idToken) try { - profile = decodeJwt(token.idToken); - } catch { - } - if (!profile) { - const { data: data2 } = await betterFetch(userInfoEndpoint, { headers: { authorization: `Bearer ${token.accessToken}` } }); - profile = data2 || null; - } - if (!profile) return null; - const userMap = await options.mapProfileToUser?.(profile); - const id = profile.sub || profile.userId; - const name = profile.name || profile.displayName; - const image = profile.picture || profile.pictureUrl || void 0; - return { - user: { - id, - name, - email: profile.email, - image, - emailVerified: false, - ...userMap - }, - data: profile - }; - }, - options - }; - }; - } -}); - -// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/linear.mjs -var linear; -var init_linear = __esm({ - "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/linear.mjs"() { - init_create_authorization_url(); - init_refresh_access_token(); - init_validate_authorization_code(); - init_oauth2(); - init_dist4(); - linear = (options) => { - const tokenEndpoint = "https://api.linear.app/oauth/token"; - return { - id: "linear", - name: "Linear", - createAuthorizationURL({ state: state2, scopes, loginHint, redirectURI }) { - const _scopes = options.disableDefaultScope ? [] : ["read"]; - if (options.scope) _scopes.push(...options.scope); - if (scopes) _scopes.push(...scopes); - return createAuthorizationURL({ - id: "linear", - options, - authorizationEndpoint: "https://linear.app/oauth/authorize", - scopes: _scopes, - state: state2, - redirectURI, - loginHint - }); - }, - validateAuthorizationCode: async ({ code, redirectURI }) => { - return validateAuthorizationCode({ - code, - redirectURI, - options, - tokenEndpoint - }); - }, - refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { - return refreshAccessToken({ - refreshToken: refreshToken2, - options: { - clientId: options.clientId, - clientKey: options.clientKey, - clientSecret: options.clientSecret - }, - tokenEndpoint - }); - }, - async getUserInfo(token) { - if (options.getUserInfo) return options.getUserInfo(token); - const { data: profile, error: error50 } = await betterFetch("https://api.linear.app/graphql", { - method: "POST", - headers: { - "Content-Type": "application/json", - Authorization: `Bearer ${token.accessToken}` - }, - body: JSON.stringify({ query: ` - query { - viewer { - id - name - email - avatarUrl - active - createdAt - updatedAt - } - } - ` }) - }); - if (error50 || !profile?.data?.viewer) return null; - const userData = profile.data.viewer; - const userMap = await options.mapProfileToUser?.(userData); - return { - user: { - id: profile.data.viewer.id, - name: profile.data.viewer.name, - email: profile.data.viewer.email, - image: profile.data.viewer.avatarUrl, - emailVerified: false, - ...userMap - }, - data: userData - }; - }, - options - }; - }; - } -}); - -// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/linkedin.mjs -var linkedin; -var init_linkedin = __esm({ - "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/linkedin.mjs"() { - init_create_authorization_url(); - init_refresh_access_token(); - init_validate_authorization_code(); - init_oauth2(); - init_dist4(); - linkedin = (options) => { - const authorizationEndpoint = "https://www.linkedin.com/oauth/v2/authorization"; - const tokenEndpoint = "https://www.linkedin.com/oauth/v2/accessToken"; - return { - id: "linkedin", - name: "Linkedin", - createAuthorizationURL: async ({ state: state2, scopes, redirectURI, loginHint }) => { - const _scopes = options.disableDefaultScope ? [] : [ - "profile", - "email", - "openid" - ]; - if (options.scope) _scopes.push(...options.scope); - if (scopes) _scopes.push(...scopes); - return await createAuthorizationURL({ - id: "linkedin", - options, - authorizationEndpoint, - scopes: _scopes, - state: state2, - loginHint, - redirectURI - }); - }, - validateAuthorizationCode: async ({ code, redirectURI }) => { - return await validateAuthorizationCode({ - code, - redirectURI, - options, - tokenEndpoint - }); - }, - refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { - return refreshAccessToken({ - refreshToken: refreshToken2, - options: { - clientId: options.clientId, - clientKey: options.clientKey, - clientSecret: options.clientSecret - }, - tokenEndpoint - }); - }, - async getUserInfo(token) { - if (options.getUserInfo) return options.getUserInfo(token); - const { data: profile, error: error50 } = await betterFetch("https://api.linkedin.com/v2/userinfo", { - method: "GET", - headers: { Authorization: `Bearer ${token.accessToken}` } - }); - if (error50) return null; - const userMap = await options.mapProfileToUser?.(profile); - return { - user: { - id: profile.sub, - name: profile.name, - email: profile.email, - emailVerified: profile.email_verified || false, - image: profile.picture, - ...userMap - }, - data: profile - }; - }, - options - }; - }; - } -}); - -// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/microsoft-entra-id.mjs -var microsoft; -var init_microsoft_entra_id = __esm({ - "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/microsoft-entra-id.mjs"() { - init_logger2(); - init_env(); - init_create_authorization_url(); - init_refresh_access_token(); - init_validate_authorization_code(); - init_oauth2(); - init_base642(); - init_dist4(); - init_webapi(); - microsoft = (options) => { - const tenant = options.tenantId || "common"; - const authority = options.authority || "https://login.microsoftonline.com"; - const authorizationEndpoint = `${authority}/${tenant}/oauth2/v2.0/authorize`; - const tokenEndpoint = `${authority}/${tenant}/oauth2/v2.0/token`; - return { - id: "microsoft", - name: "Microsoft EntraID", - createAuthorizationURL(data2) { - const scopes = options.disableDefaultScope ? [] : [ - "openid", - "profile", - "email", - "User.Read", - "offline_access" - ]; - if (options.scope) scopes.push(...options.scope); - if (data2.scopes) scopes.push(...data2.scopes); - return createAuthorizationURL({ - id: "microsoft", - options, - authorizationEndpoint, - state: data2.state, - codeVerifier: data2.codeVerifier, - scopes, - redirectURI: data2.redirectURI, - prompt: options.prompt, - loginHint: data2.loginHint - }); - }, - validateAuthorizationCode({ code, codeVerifier, redirectURI }) { - return validateAuthorizationCode({ - code, - codeVerifier, - redirectURI, - options, - tokenEndpoint - }); - }, - async getUserInfo(token) { - if (options.getUserInfo) return options.getUserInfo(token); - if (!token.idToken) return null; - const user = decodeJwt(token.idToken); - const profilePhotoSize = options.profilePhotoSize || 48; - await betterFetch(`https://graph.microsoft.com/v1.0/me/photos/${profilePhotoSize}x${profilePhotoSize}/$value`, { - headers: { Authorization: `Bearer ${token.accessToken}` }, - async onResponse(context) { - if (options.disableProfilePhoto || !context.response.ok) return; - try { - const pictureBuffer = await context.response.clone().arrayBuffer(); - user.picture = `data:image/jpeg;base64, ${base643.encode(pictureBuffer)}`; - } catch (e5) { - logger3.error(e5 && typeof e5 === "object" && "name" in e5 ? e5.name : "", e5); - } - } - }); - const userMap = await options.mapProfileToUser?.(user); - const emailVerified = user.email_verified !== void 0 ? user.email_verified : user.email && (user.verified_primary_email?.includes(user.email) || user.verified_secondary_email?.includes(user.email)) ? true : false; - return { - user: { - id: user.sub, - name: user.name, - email: user.email, - image: user.picture, - emailVerified, - ...userMap - }, - data: user - }; - }, - refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { - const scopes = options.disableDefaultScope ? [] : [ - "openid", - "profile", - "email", - "User.Read", - "offline_access" - ]; - if (options.scope) scopes.push(...options.scope); - return refreshAccessToken({ - refreshToken: refreshToken2, - options: { - clientId: options.clientId, - clientSecret: options.clientSecret - }, - extraParams: { scope: scopes.join(" ") }, - tokenEndpoint - }); - }, - options - }; - }; - } -}); - -// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/naver.mjs -var naver; -var init_naver = __esm({ - "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/naver.mjs"() { - init_create_authorization_url(); - init_refresh_access_token(); - init_validate_authorization_code(); - init_oauth2(); - init_dist4(); - naver = (options) => { - return { - id: "naver", - name: "Naver", - createAuthorizationURL({ state: state2, scopes, redirectURI }) { - const _scopes = options.disableDefaultScope ? [] : ["profile", "email"]; - if (options.scope) _scopes.push(...options.scope); - if (scopes) _scopes.push(...scopes); - return createAuthorizationURL({ - id: "naver", - options, - authorizationEndpoint: "https://nid.naver.com/oauth2.0/authorize", - scopes: _scopes, - state: state2, - redirectURI - }); - }, - validateAuthorizationCode: async ({ code, redirectURI }) => { - return validateAuthorizationCode({ - code, - redirectURI, - options, - tokenEndpoint: "https://nid.naver.com/oauth2.0/token" - }); - }, - refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { - return refreshAccessToken({ - refreshToken: refreshToken2, - options: { - clientId: options.clientId, - clientKey: options.clientKey, - clientSecret: options.clientSecret - }, - tokenEndpoint: "https://nid.naver.com/oauth2.0/token" - }); - }, - async getUserInfo(token) { - if (options.getUserInfo) return options.getUserInfo(token); - const { data: profile, error: error50 } = await betterFetch("https://openapi.naver.com/v1/nid/me", { headers: { Authorization: `Bearer ${token.accessToken}` } }); - if (error50 || !profile || profile.resultcode !== "00") return null; - const userMap = await options.mapProfileToUser?.(profile); - const res = profile.response || {}; - return { - user: { - id: res.id, - name: res.name || res.nickname, - email: res.email, - image: res.profile_image, - emailVerified: false, - ...userMap - }, - data: profile - }; - }, - options - }; - }; - } -}); - -// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/notion.mjs -var notion; -var init_notion = __esm({ - "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/notion.mjs"() { - init_create_authorization_url(); - init_refresh_access_token(); - init_validate_authorization_code(); - init_oauth2(); - init_dist4(); - notion = (options) => { - const tokenEndpoint = "https://api.notion.com/v1/oauth/token"; - return { - id: "notion", - name: "Notion", - createAuthorizationURL({ state: state2, scopes, loginHint, redirectURI }) { - const _scopes = options.disableDefaultScope ? [] : []; - if (options.scope) _scopes.push(...options.scope); - if (scopes) _scopes.push(...scopes); - return createAuthorizationURL({ - id: "notion", - options, - authorizationEndpoint: "https://api.notion.com/v1/oauth/authorize", - scopes: _scopes, - state: state2, - redirectURI, - loginHint, - additionalParams: { owner: "user" } - }); - }, - validateAuthorizationCode: async ({ code, redirectURI }) => { - return validateAuthorizationCode({ - code, - redirectURI, - options, - tokenEndpoint, - authentication: "basic" - }); - }, - refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { - return refreshAccessToken({ - refreshToken: refreshToken2, - options: { - clientId: options.clientId, - clientKey: options.clientKey, - clientSecret: options.clientSecret - }, - tokenEndpoint - }); - }, - async getUserInfo(token) { - if (options.getUserInfo) return options.getUserInfo(token); - const { data: profile, error: error50 } = await betterFetch("https://api.notion.com/v1/users/me", { headers: { - Authorization: `Bearer ${token.accessToken}`, - "Notion-Version": "2022-06-28" - } }); - if (error50 || !profile) return null; - const userProfile = profile.bot?.owner?.user; - if (!userProfile) return null; - const userMap = await options.mapProfileToUser?.(userProfile); - return { - user: { - id: userProfile.id, - name: userProfile.name || "Notion User", - email: userProfile.person?.email || null, - image: userProfile.avatar_url, - emailVerified: false, - ...userMap - }, - data: userProfile - }; - }, - options - }; - }; - } -}); - -// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/paybin.mjs -var paybin; -var init_paybin = __esm({ - "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/paybin.mjs"() { - init_logger2(); - init_env(); - init_error(); - init_create_authorization_url(); - init_refresh_access_token(); - init_validate_authorization_code(); - init_oauth2(); - init_webapi(); - paybin = (options) => { - const issuer = options.issuer || "https://idp.paybin.io"; - const authorizationEndpoint = `${issuer}/oauth2/authorize`; - const tokenEndpoint = `${issuer}/oauth2/token`; - return { - id: "paybin", - name: "Paybin", - async createAuthorizationURL({ state: state2, scopes, codeVerifier, redirectURI, loginHint }) { - if (!options.clientId || !options.clientSecret) { - logger3.error("Client Id and Client Secret is required for Paybin. Make sure to provide them in the options."); - throw new BetterAuthError("CLIENT_ID_AND_SECRET_REQUIRED"); - } - if (!codeVerifier) throw new BetterAuthError("codeVerifier is required for Paybin"); - const _scopes = options.disableDefaultScope ? [] : [ - "openid", - "email", - "profile" - ]; - if (options.scope) _scopes.push(...options.scope); - if (scopes) _scopes.push(...scopes); - return await createAuthorizationURL({ - id: "paybin", - options, - authorizationEndpoint, - scopes: _scopes, - state: state2, - codeVerifier, - redirectURI, - prompt: options.prompt, - loginHint - }); - }, - validateAuthorizationCode: async ({ code, codeVerifier, redirectURI }) => { - return validateAuthorizationCode({ - code, - codeVerifier, - redirectURI, - options, - tokenEndpoint - }); - }, - refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { - return refreshAccessToken({ - refreshToken: refreshToken2, - options: { - clientId: options.clientId, - clientKey: options.clientKey, - clientSecret: options.clientSecret - }, - tokenEndpoint - }); - }, - async getUserInfo(token) { - if (options.getUserInfo) return options.getUserInfo(token); - if (!token.idToken) return null; - const user = decodeJwt(token.idToken); - const userMap = await options.mapProfileToUser?.(user); - return { - user: { - id: user.sub, - name: user.name || user.preferred_username || (user.email ? user.email.split("@")[0] : "User") || "User", - email: user.email, - image: user.picture, - emailVerified: user.email_verified || false, - ...userMap - }, - data: user - }; - }, - options - }; - }; - } -}); - -// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/paypal.mjs -var paypal; -var init_paypal = __esm({ - "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/paypal.mjs"() { - init_logger2(); - init_env(); - init_error(); - init_create_authorization_url(); - init_oauth2(); - init_base642(); - init_dist4(); - init_webapi(); - paypal = (options) => { - const isSandbox = (options.environment || "sandbox") === "sandbox"; - const authorizationEndpoint = isSandbox ? "https://www.sandbox.paypal.com/signin/authorize" : "https://www.paypal.com/signin/authorize"; - const tokenEndpoint = isSandbox ? "https://api-m.sandbox.paypal.com/v1/oauth2/token" : "https://api-m.paypal.com/v1/oauth2/token"; - const userInfoEndpoint = isSandbox ? "https://api-m.sandbox.paypal.com/v1/identity/oauth2/userinfo" : "https://api-m.paypal.com/v1/identity/oauth2/userinfo"; - return { - id: "paypal", - name: "PayPal", - async createAuthorizationURL({ state: state2, codeVerifier, redirectURI }) { - if (!options.clientId || !options.clientSecret) { - logger3.error("Client Id and Client Secret is required for PayPal. Make sure to provide them in the options."); - throw new BetterAuthError("CLIENT_ID_AND_SECRET_REQUIRED"); - } - return await createAuthorizationURL({ - id: "paypal", - options, - authorizationEndpoint, - scopes: [], - state: state2, - codeVerifier, - redirectURI, - prompt: options.prompt - }); - }, - validateAuthorizationCode: async ({ code, redirectURI }) => { - const credentials = base643.encode(`${options.clientId}:${options.clientSecret}`); - try { - const response = await betterFetch(tokenEndpoint, { - method: "POST", - headers: { - Authorization: `Basic ${credentials}`, - Accept: "application/json", - "Accept-Language": "en_US", - "Content-Type": "application/x-www-form-urlencoded" - }, - body: new URLSearchParams({ - grant_type: "authorization_code", - code, - redirect_uri: redirectURI - }).toString() - }); - if (!response.data) throw new BetterAuthError("FAILED_TO_GET_ACCESS_TOKEN"); - const data2 = response.data; - return { - accessToken: data2.access_token, - refreshToken: data2.refresh_token, - accessTokenExpiresAt: data2.expires_in ? new Date(Date.now() + data2.expires_in * 1e3) : void 0, - idToken: data2.id_token - }; - } catch (error50) { - logger3.error("PayPal token exchange failed:", error50); - throw new BetterAuthError("FAILED_TO_GET_ACCESS_TOKEN"); - } - }, - refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { - const credentials = base643.encode(`${options.clientId}:${options.clientSecret}`); - try { - const response = await betterFetch(tokenEndpoint, { - method: "POST", - headers: { - Authorization: `Basic ${credentials}`, - Accept: "application/json", - "Accept-Language": "en_US", - "Content-Type": "application/x-www-form-urlencoded" - }, - body: new URLSearchParams({ - grant_type: "refresh_token", - refresh_token: refreshToken2 - }).toString() - }); - if (!response.data) throw new BetterAuthError("FAILED_TO_REFRESH_ACCESS_TOKEN"); - const data2 = response.data; - return { - accessToken: data2.access_token, - refreshToken: data2.refresh_token, - accessTokenExpiresAt: data2.expires_in ? new Date(Date.now() + data2.expires_in * 1e3) : void 0 - }; - } catch (error50) { - logger3.error("PayPal token refresh failed:", error50); - throw new BetterAuthError("FAILED_TO_REFRESH_ACCESS_TOKEN"); - } - }, - async verifyIdToken(token, nonce) { - if (options.disableIdTokenSignIn) return false; - if (options.verifyIdToken) return options.verifyIdToken(token, nonce); - try { - return !!decodeJwt(token).sub; - } catch (error50) { - logger3.error("Failed to verify PayPal ID token:", error50); - return false; - } - }, - async getUserInfo(token) { - if (options.getUserInfo) return options.getUserInfo(token); - if (!token.accessToken) { - logger3.error("Access token is required to fetch PayPal user info"); - return null; - } - try { - const response = await betterFetch(`${userInfoEndpoint}?schema=paypalv1.1`, { headers: { - Authorization: `Bearer ${token.accessToken}`, - Accept: "application/json" - } }); - if (!response.data) { - logger3.error("Failed to fetch user info from PayPal"); - return null; - } - const userInfo = response.data; - const userMap = await options.mapProfileToUser?.(userInfo); - return { - user: { - id: userInfo.user_id, - name: userInfo.name, - email: userInfo.email, - image: userInfo.picture, - emailVerified: userInfo.email_verified, - ...userMap - }, - data: userInfo - }; - } catch (error50) { - logger3.error("Failed to fetch user info from PayPal:", error50); - return null; - } - }, - options - }; - }; - } -}); - -// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/polar.mjs -var polar; -var init_polar = __esm({ - "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/polar.mjs"() { - init_create_authorization_url(); - init_refresh_access_token(); - init_validate_authorization_code(); - init_oauth2(); - init_dist4(); - polar = (options) => { - return { - id: "polar", - name: "Polar", - createAuthorizationURL({ state: state2, scopes, codeVerifier, redirectURI }) { - const _scopes = options.disableDefaultScope ? [] : [ - "openid", - "profile", - "email" - ]; - if (options.scope) _scopes.push(...options.scope); - if (scopes) _scopes.push(...scopes); - return createAuthorizationURL({ - id: "polar", - options, - authorizationEndpoint: "https://polar.sh/oauth2/authorize", - scopes: _scopes, - state: state2, - codeVerifier, - redirectURI, - prompt: options.prompt - }); - }, - validateAuthorizationCode: async ({ code, codeVerifier, redirectURI }) => { - return validateAuthorizationCode({ - code, - codeVerifier, - redirectURI, - options, - tokenEndpoint: "https://api.polar.sh/v1/oauth2/token" - }); - }, - refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { - return refreshAccessToken({ - refreshToken: refreshToken2, - options: { - clientId: options.clientId, - clientKey: options.clientKey, - clientSecret: options.clientSecret - }, - tokenEndpoint: "https://api.polar.sh/v1/oauth2/token" - }); - }, - async getUserInfo(token) { - if (options.getUserInfo) return options.getUserInfo(token); - const { data: profile, error: error50 } = await betterFetch("https://api.polar.sh/v1/oauth2/userinfo", { headers: { Authorization: `Bearer ${token.accessToken}` } }); - if (error50) return null; - const userMap = await options.mapProfileToUser?.(profile); - return { - user: { - id: profile.id, - name: profile.public_name || profile.username, - email: profile.email, - image: profile.avatar_url, - emailVerified: profile.email_verified ?? false, - ...userMap - }, - data: profile - }; - }, - options - }; - }; - } -}); - -// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/reddit.mjs -var reddit; -var init_reddit = __esm({ - "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/reddit.mjs"() { - init_utils13(); - init_create_authorization_url(); - init_refresh_access_token(); - init_oauth2(); - init_base642(); - init_dist4(); - reddit = (options) => { - return { - id: "reddit", - name: "Reddit", - createAuthorizationURL({ state: state2, scopes, redirectURI }) { - const _scopes = options.disableDefaultScope ? [] : ["identity"]; - if (options.scope) _scopes.push(...options.scope); - if (scopes) _scopes.push(...scopes); - return createAuthorizationURL({ - id: "reddit", - options, - authorizationEndpoint: "https://www.reddit.com/api/v1/authorize", - scopes: _scopes, - state: state2, - redirectURI, - duration: options.duration - }); - }, - validateAuthorizationCode: async ({ code, redirectURI }) => { - const body = new URLSearchParams({ - grant_type: "authorization_code", - code, - redirect_uri: options.redirectURI || redirectURI - }); - const { data: data2, error: error50 } = await betterFetch("https://www.reddit.com/api/v1/access_token", { - method: "POST", - headers: { - "content-type": "application/x-www-form-urlencoded", - accept: "text/plain", - "user-agent": "better-auth", - Authorization: `Basic ${base643.encode(`${options.clientId}:${options.clientSecret}`)}` - }, - body: body.toString() - }); - if (error50) throw error50; - return getOAuth2Tokens(data2); - }, - refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { - return refreshAccessToken({ - refreshToken: refreshToken2, - options: { - clientId: options.clientId, - clientKey: options.clientKey, - clientSecret: options.clientSecret - }, - authentication: "basic", - tokenEndpoint: "https://www.reddit.com/api/v1/access_token" - }); - }, - async getUserInfo(token) { - if (options.getUserInfo) return options.getUserInfo(token); - const { data: profile, error: error50 } = await betterFetch("https://oauth.reddit.com/api/v1/me", { headers: { - Authorization: `Bearer ${token.accessToken}`, - "User-Agent": "better-auth" - } }); - if (error50) return null; - const userMap = await options.mapProfileToUser?.(profile); - return { - user: { - id: profile.id, - name: profile.name, - email: profile.oauth_client_id, - emailVerified: profile.has_verified_email, - image: profile.icon_img?.split("?")[0], - ...userMap - }, - data: profile - }; - }, - options - }; - }; - } -}); - -// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/roblox.mjs -var roblox; -var init_roblox = __esm({ - "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/roblox.mjs"() { - init_refresh_access_token(); - init_validate_authorization_code(); - init_oauth2(); - init_dist4(); - roblox = (options) => { - return { - id: "roblox", - name: "Roblox", - createAuthorizationURL({ state: state2, scopes, redirectURI }) { - const _scopes = options.disableDefaultScope ? [] : ["openid", "profile"]; - if (options.scope) _scopes.push(...options.scope); - if (scopes) _scopes.push(...scopes); - return new URL(`https://apis.roblox.com/oauth/v1/authorize?scope=${_scopes.join("+")}&response_type=code&client_id=${options.clientId}&redirect_uri=${encodeURIComponent(options.redirectURI || redirectURI)}&state=${state2}&prompt=${options.prompt || "select_account consent"}`); - }, - validateAuthorizationCode: async ({ code, redirectURI }) => { - return validateAuthorizationCode({ - code, - redirectURI: options.redirectURI || redirectURI, - options, - tokenEndpoint: "https://apis.roblox.com/oauth/v1/token", - authentication: "post" - }); - }, - refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { - return refreshAccessToken({ - refreshToken: refreshToken2, - options: { - clientId: options.clientId, - clientKey: options.clientKey, - clientSecret: options.clientSecret - }, - tokenEndpoint: "https://apis.roblox.com/oauth/v1/token" - }); - }, - async getUserInfo(token) { - if (options.getUserInfo) return options.getUserInfo(token); - const { data: profile, error: error50 } = await betterFetch("https://apis.roblox.com/oauth/v1/userinfo", { headers: { authorization: `Bearer ${token.accessToken}` } }); - if (error50) return null; - const userMap = await options.mapProfileToUser?.(profile); - return { - user: { - id: profile.sub, - name: profile.nickname || profile.preferred_username || "", - image: profile.picture, - email: profile.preferred_username || null, - emailVerified: false, - ...userMap - }, - data: { ...profile } - }; - }, - options - }; - }; - } -}); - -// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/salesforce.mjs -var salesforce; -var init_salesforce = __esm({ - "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/salesforce.mjs"() { - init_logger2(); - init_env(); - init_error(); - init_create_authorization_url(); - init_refresh_access_token(); - init_validate_authorization_code(); - init_oauth2(); - init_dist4(); - salesforce = (options) => { - const isSandbox = (options.environment ?? "production") === "sandbox"; - const authorizationEndpoint = options.loginUrl ? `https://${options.loginUrl}/services/oauth2/authorize` : isSandbox ? "https://test.salesforce.com/services/oauth2/authorize" : "https://login.salesforce.com/services/oauth2/authorize"; - const tokenEndpoint = options.loginUrl ? `https://${options.loginUrl}/services/oauth2/token` : isSandbox ? "https://test.salesforce.com/services/oauth2/token" : "https://login.salesforce.com/services/oauth2/token"; - const userInfoEndpoint = options.loginUrl ? `https://${options.loginUrl}/services/oauth2/userinfo` : isSandbox ? "https://test.salesforce.com/services/oauth2/userinfo" : "https://login.salesforce.com/services/oauth2/userinfo"; - return { - id: "salesforce", - name: "Salesforce", - async createAuthorizationURL({ state: state2, scopes, codeVerifier, redirectURI }) { - if (!options.clientId || !options.clientSecret) { - logger3.error("Client Id and Client Secret are required for Salesforce. Make sure to provide them in the options."); - throw new BetterAuthError("CLIENT_ID_AND_SECRET_REQUIRED"); - } - if (!codeVerifier) throw new BetterAuthError("codeVerifier is required for Salesforce"); - const _scopes = options.disableDefaultScope ? [] : [ - "openid", - "email", - "profile" - ]; - if (options.scope) _scopes.push(...options.scope); - if (scopes) _scopes.push(...scopes); - return createAuthorizationURL({ - id: "salesforce", - options, - authorizationEndpoint, - scopes: _scopes, - state: state2, - codeVerifier, - redirectURI: options.redirectURI || redirectURI - }); - }, - validateAuthorizationCode: async ({ code, codeVerifier, redirectURI }) => { - return validateAuthorizationCode({ - code, - codeVerifier, - redirectURI: options.redirectURI || redirectURI, - options, - tokenEndpoint - }); - }, - refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { - return refreshAccessToken({ - refreshToken: refreshToken2, - options: { - clientId: options.clientId, - clientSecret: options.clientSecret - }, - tokenEndpoint - }); - }, - async getUserInfo(token) { - if (options.getUserInfo) return options.getUserInfo(token); - try { - const { data: user } = await betterFetch(userInfoEndpoint, { headers: { Authorization: `Bearer ${token.accessToken}` } }); - if (!user) { - logger3.error("Failed to fetch user info from Salesforce"); - return null; - } - const userMap = await options.mapProfileToUser?.(user); - return { - user: { - id: user.user_id, - name: user.name, - email: user.email, - image: user.photos?.picture || user.photos?.thumbnail, - emailVerified: user.email_verified ?? false, - ...userMap - }, - data: user - }; - } catch (error50) { - logger3.error("Failed to fetch user info from Salesforce:", error50); - return null; - } - }, - options - }; - }; - } -}); - -// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/slack.mjs -var slack; -var init_slack = __esm({ - "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/slack.mjs"() { - init_refresh_access_token(); - init_validate_authorization_code(); - init_oauth2(); - init_dist4(); - slack = (options) => { - return { - id: "slack", - name: "Slack", - createAuthorizationURL({ state: state2, scopes, redirectURI }) { - const _scopes = options.disableDefaultScope ? [] : [ - "openid", - "profile", - "email" - ]; - if (scopes) _scopes.push(...scopes); - if (options.scope) _scopes.push(...options.scope); - const url2 = new URL("https://slack.com/openid/connect/authorize"); - url2.searchParams.set("scope", _scopes.join(" ")); - url2.searchParams.set("response_type", "code"); - url2.searchParams.set("client_id", options.clientId); - url2.searchParams.set("redirect_uri", options.redirectURI || redirectURI); - url2.searchParams.set("state", state2); - return url2; - }, - validateAuthorizationCode: async ({ code, redirectURI }) => { - return validateAuthorizationCode({ - code, - redirectURI, - options, - tokenEndpoint: "https://slack.com/api/openid.connect.token" - }); - }, - refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { - return refreshAccessToken({ - refreshToken: refreshToken2, - options: { - clientId: options.clientId, - clientKey: options.clientKey, - clientSecret: options.clientSecret - }, - tokenEndpoint: "https://slack.com/api/openid.connect.token" - }); - }, - async getUserInfo(token) { - if (options.getUserInfo) return options.getUserInfo(token); - const { data: profile, error: error50 } = await betterFetch("https://slack.com/api/openid.connect.userInfo", { headers: { authorization: `Bearer ${token.accessToken}` } }); - if (error50) return null; - const userMap = await options.mapProfileToUser?.(profile); - return { - user: { - id: profile["https://slack.com/user_id"], - name: profile.name || "", - email: profile.email, - emailVerified: profile.email_verified, - image: profile.picture || profile["https://slack.com/user_image_512"], - ...userMap - }, - data: profile - }; - }, - options - }; - }; - } -}); - -// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/spotify.mjs -var spotify; -var init_spotify = __esm({ - "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/spotify.mjs"() { - init_create_authorization_url(); - init_refresh_access_token(); - init_validate_authorization_code(); - init_oauth2(); - init_dist4(); - spotify = (options) => { - return { - id: "spotify", - name: "Spotify", - createAuthorizationURL({ state: state2, scopes, codeVerifier, redirectURI }) { - const _scopes = options.disableDefaultScope ? [] : ["user-read-email"]; - if (options.scope) _scopes.push(...options.scope); - if (scopes) _scopes.push(...scopes); - return createAuthorizationURL({ - id: "spotify", - options, - authorizationEndpoint: "https://accounts.spotify.com/authorize", - scopes: _scopes, - state: state2, - codeVerifier, - redirectURI - }); - }, - validateAuthorizationCode: async ({ code, codeVerifier, redirectURI }) => { - return validateAuthorizationCode({ - code, - codeVerifier, - redirectURI, - options, - tokenEndpoint: "https://accounts.spotify.com/api/token" - }); - }, - refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { - return refreshAccessToken({ - refreshToken: refreshToken2, - options: { - clientId: options.clientId, - clientKey: options.clientKey, - clientSecret: options.clientSecret - }, - tokenEndpoint: "https://accounts.spotify.com/api/token" - }); - }, - async getUserInfo(token) { - if (options.getUserInfo) return options.getUserInfo(token); - const { data: profile, error: error50 } = await betterFetch("https://api.spotify.com/v1/me", { - method: "GET", - headers: { Authorization: `Bearer ${token.accessToken}` } - }); - if (error50) return null; - const userMap = await options.mapProfileToUser?.(profile); - return { - user: { - id: profile.id, - name: profile.display_name, - email: profile.email, - image: profile.images[0]?.url, - emailVerified: false, - ...userMap - }, - data: profile - }; - }, - options - }; - }; - } -}); - -// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/tiktok.mjs -var tiktok; -var init_tiktok = __esm({ - "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/tiktok.mjs"() { - init_refresh_access_token(); - init_validate_authorization_code(); - init_oauth2(); - init_dist4(); - tiktok = (options) => { - return { - id: "tiktok", - name: "TikTok", - createAuthorizationURL({ state: state2, scopes, redirectURI }) { - const _scopes = options.disableDefaultScope ? [] : ["user.info.profile"]; - if (options.scope) _scopes.push(...options.scope); - if (scopes) _scopes.push(...scopes); - return new URL(`https://www.tiktok.com/v2/auth/authorize?scope=${_scopes.join(",")}&response_type=code&client_key=${options.clientKey}&redirect_uri=${encodeURIComponent(options.redirectURI || redirectURI)}&state=${state2}`); - }, - validateAuthorizationCode: async ({ code, redirectURI }) => { - return validateAuthorizationCode({ - code, - redirectURI: options.redirectURI || redirectURI, - options: { - clientKey: options.clientKey, - clientSecret: options.clientSecret - }, - tokenEndpoint: "https://open.tiktokapis.com/v2/oauth/token/" - }); - }, - refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { - return refreshAccessToken({ - refreshToken: refreshToken2, - options: { clientSecret: options.clientSecret }, - tokenEndpoint: "https://open.tiktokapis.com/v2/oauth/token/", - authentication: "post", - extraParams: { client_key: options.clientKey } - }); - }, - async getUserInfo(token) { - if (options.getUserInfo) return options.getUserInfo(token); - const { data: profile, error: error50 } = await betterFetch(`https://open.tiktokapis.com/v2/user/info/?fields=${[ - "open_id", - "avatar_large_url", - "display_name", - "username" - ].join(",")}`, { headers: { authorization: `Bearer ${token.accessToken}` } }); - if (error50) return null; - return { - user: { - email: profile.data.user.email || profile.data.user.username, - id: profile.data.user.open_id, - name: profile.data.user.display_name || profile.data.user.username, - image: profile.data.user.avatar_large_url, - emailVerified: false - }, - data: profile - }; - }, - options - }; - }; - } -}); - -// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/twitch.mjs -var twitch; -var init_twitch = __esm({ - "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/twitch.mjs"() { - init_logger2(); - init_env(); - init_create_authorization_url(); - init_refresh_access_token(); - init_validate_authorization_code(); - init_oauth2(); - init_webapi(); - twitch = (options) => { - return { - id: "twitch", - name: "Twitch", - createAuthorizationURL({ state: state2, scopes, redirectURI }) { - const _scopes = options.disableDefaultScope ? [] : ["user:read:email", "openid"]; - if (options.scope) _scopes.push(...options.scope); - if (scopes) _scopes.push(...scopes); - return createAuthorizationURL({ - id: "twitch", - redirectURI, - options, - authorizationEndpoint: "https://id.twitch.tv/oauth2/authorize", - scopes: _scopes, - state: state2, - claims: options.claims || [ - "email", - "email_verified", - "preferred_username", - "picture" - ] - }); - }, - validateAuthorizationCode: async ({ code, redirectURI }) => { - return validateAuthorizationCode({ - code, - redirectURI, - options, - tokenEndpoint: "https://id.twitch.tv/oauth2/token" - }); - }, - refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { - return refreshAccessToken({ - refreshToken: refreshToken2, - options: { - clientId: options.clientId, - clientKey: options.clientKey, - clientSecret: options.clientSecret - }, - tokenEndpoint: "https://id.twitch.tv/oauth2/token" - }); - }, - async getUserInfo(token) { - if (options.getUserInfo) return options.getUserInfo(token); - const idToken = token.idToken; - if (!idToken) { - logger3.error("No idToken found in token"); - return null; - } - const profile = decodeJwt(idToken); - const userMap = await options.mapProfileToUser?.(profile); - return { - user: { - id: profile.sub, - name: profile.preferred_username, - email: profile.email, - image: profile.picture, - emailVerified: profile.email_verified, - ...userMap - }, - data: profile - }; - }, - options - }; - }; - } -}); - -// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/twitter.mjs -var twitter; -var init_twitter = __esm({ - "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/twitter.mjs"() { - init_create_authorization_url(); - init_refresh_access_token(); - init_validate_authorization_code(); - init_oauth2(); - init_dist4(); - twitter = (options) => { - return { - id: "twitter", - name: "Twitter", - createAuthorizationURL(data2) { - const _scopes = options.disableDefaultScope ? [] : [ - "users.read", - "tweet.read", - "offline.access", - "users.email" - ]; - if (options.scope) _scopes.push(...options.scope); - if (data2.scopes) _scopes.push(...data2.scopes); - return createAuthorizationURL({ - id: "twitter", - options, - authorizationEndpoint: "https://x.com/i/oauth2/authorize", - scopes: _scopes, - state: data2.state, - codeVerifier: data2.codeVerifier, - redirectURI: data2.redirectURI - }); - }, - validateAuthorizationCode: async ({ code, codeVerifier, redirectURI }) => { - return validateAuthorizationCode({ - code, - codeVerifier, - authentication: "basic", - redirectURI, - options, - tokenEndpoint: "https://api.x.com/2/oauth2/token" - }); - }, - refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { - return refreshAccessToken({ - refreshToken: refreshToken2, - options: { - clientId: options.clientId, - clientKey: options.clientKey, - clientSecret: options.clientSecret - }, - authentication: "basic", - tokenEndpoint: "https://api.x.com/2/oauth2/token" - }); - }, - async getUserInfo(token) { - if (options.getUserInfo) return options.getUserInfo(token); - const { data: profile, error: profileError } = await betterFetch("https://api.x.com/2/users/me?user.fields=profile_image_url", { - method: "GET", - headers: { Authorization: `Bearer ${token.accessToken}` } - }); - if (profileError) return null; - const { data: emailData, error: emailError } = await betterFetch("https://api.x.com/2/users/me?user.fields=confirmed_email", { - method: "GET", - headers: { Authorization: `Bearer ${token.accessToken}` } - }); - let emailVerified = false; - if (!emailError && emailData?.data?.confirmed_email) { - profile.data.email = emailData.data.confirmed_email; - emailVerified = true; - } - const userMap = await options.mapProfileToUser?.(profile); - return { - user: { - id: profile.data.id, - name: profile.data.name, - email: profile.data.email || profile.data.username || null, - image: profile.data.profile_image_url, - emailVerified, - ...userMap - }, - data: profile - }; - }, - options - }; - }; - } -}); - -// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/vercel.mjs -var vercel; -var init_vercel = __esm({ - "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/vercel.mjs"() { - init_error(); - init_create_authorization_url(); - init_validate_authorization_code(); - init_oauth2(); - init_dist4(); - vercel = (options) => { - return { - id: "vercel", - name: "Vercel", - createAuthorizationURL({ state: state2, scopes, codeVerifier, redirectURI }) { - if (!codeVerifier) throw new BetterAuthError("codeVerifier is required for Vercel"); - let _scopes = void 0; - if (options.scope !== void 0 || scopes !== void 0) { - _scopes = []; - if (options.scope) _scopes.push(...options.scope); - if (scopes) _scopes.push(...scopes); - } - return createAuthorizationURL({ - id: "vercel", - options, - authorizationEndpoint: "https://vercel.com/oauth/authorize", - scopes: _scopes, - state: state2, - codeVerifier, - redirectURI - }); - }, - validateAuthorizationCode: async ({ code, codeVerifier, redirectURI }) => { - return validateAuthorizationCode({ - code, - codeVerifier, - redirectURI, - options, - tokenEndpoint: "https://api.vercel.com/login/oauth/token" - }); - }, - async getUserInfo(token) { - if (options.getUserInfo) return options.getUserInfo(token); - const { data: profile, error: error50 } = await betterFetch("https://api.vercel.com/login/oauth/userinfo", { headers: { Authorization: `Bearer ${token.accessToken}` } }); - if (error50 || !profile) return null; - const userMap = await options.mapProfileToUser?.(profile); - return { - user: { - id: profile.sub, - name: profile.name ?? profile.preferred_username, - email: profile.email, - image: profile.picture, - emailVerified: profile.email_verified ?? false, - ...userMap - }, - data: profile - }; - }, - options - }; - }; - } -}); - -// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/vk.mjs -var vk; -var init_vk = __esm({ - "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/vk.mjs"() { - init_create_authorization_url(); - init_refresh_access_token(); - init_validate_authorization_code(); - init_oauth2(); - init_dist4(); - vk = (options) => { - return { - id: "vk", - name: "VK", - async createAuthorizationURL({ state: state2, scopes, codeVerifier, redirectURI }) { - const _scopes = options.disableDefaultScope ? [] : ["email", "phone"]; - if (options.scope) _scopes.push(...options.scope); - if (scopes) _scopes.push(...scopes); - return createAuthorizationURL({ - id: "vk", - options, - authorizationEndpoint: "https://id.vk.com/authorize", - scopes: _scopes, - state: state2, - redirectURI, - codeVerifier - }); - }, - validateAuthorizationCode: async ({ code, codeVerifier, redirectURI, deviceId }) => { - return validateAuthorizationCode({ - code, - codeVerifier, - redirectURI: options.redirectURI || redirectURI, - options, - deviceId, - tokenEndpoint: "https://id.vk.com/oauth2/auth" - }); - }, - refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => { - return refreshAccessToken({ - refreshToken: refreshToken2, - options: { - clientId: options.clientId, - clientKey: options.clientKey, - clientSecret: options.clientSecret - }, - tokenEndpoint: "https://id.vk.com/oauth2/auth" - }); - }, - async getUserInfo(data2) { - if (options.getUserInfo) return options.getUserInfo(data2); - if (!data2.accessToken) return null; - const formBody = new URLSearchParams({ - access_token: data2.accessToken, - client_id: options.clientId - }).toString(); - const { data: profile, error: error50 } = await betterFetch("https://id.vk.com/oauth2/user_info", { - method: "POST", - headers: { "Content-Type": "application/x-www-form-urlencoded" }, - body: formBody - }); - if (error50) return null; - const userMap = await options.mapProfileToUser?.(profile); - if (!profile.user.email && !userMap?.email) return null; - return { - user: { - id: profile.user.user_id, - first_name: profile.user.first_name, - last_name: profile.user.last_name, - email: profile.user.email, - image: profile.user.avatar, - emailVerified: false, - birthday: profile.user.birthday, - sex: profile.user.sex, - name: `${profile.user.first_name} ${profile.user.last_name}`, - ...userMap - }, - data: profile - }; - }, - options - }; - }; - } -}); - -// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/zoom.mjs -var zoom; -var init_zoom = __esm({ - "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/zoom.mjs"() { - init_utils13(); - init_refresh_access_token(); - init_validate_authorization_code(); - init_oauth2(); - init_dist4(); - zoom = (userOptions) => { - const options = { - pkce: true, - ...userOptions - }; - return { - id: "zoom", - name: "Zoom", - createAuthorizationURL: async ({ state: state2, redirectURI, codeVerifier }) => { - const params = new URLSearchParams({ - response_type: "code", - redirect_uri: options.redirectURI ? options.redirectURI : redirectURI, - client_id: options.clientId, - state: state2 - }); - if (options.pkce) { - const codeChallenge = await generateCodeChallenge(codeVerifier); - params.set("code_challenge_method", "S256"); - params.set("code_challenge", codeChallenge); - } - const url2 = new URL("https://zoom.us/oauth/authorize"); - url2.search = params.toString(); - return url2; - }, - validateAuthorizationCode: async ({ code, redirectURI, codeVerifier }) => { - return validateAuthorizationCode({ - code, - redirectURI: options.redirectURI || redirectURI, - codeVerifier, - options, - tokenEndpoint: "https://zoom.us/oauth/token", - authentication: "post" - }); - }, - refreshAccessToken: options.refreshAccessToken ? options.refreshAccessToken : async (refreshToken2) => refreshAccessToken({ - refreshToken: refreshToken2, - options: { - clientId: options.clientId, - clientKey: options.clientKey, - clientSecret: options.clientSecret - }, - tokenEndpoint: "https://zoom.us/oauth/token" - }), - async getUserInfo(token) { - if (options.getUserInfo) return options.getUserInfo(token); - const { data: profile, error: error50 } = await betterFetch("https://api.zoom.us/v2/users/me", { headers: { authorization: `Bearer ${token.accessToken}` } }); - if (error50) return null; - const userMap = await options.mapProfileToUser?.(profile); - return { - user: { - id: profile.id, - name: profile.display_name, - image: profile.pic_url, - email: profile.email, - emailVerified: Boolean(profile.verified), - ...userMap - }, - data: { ...profile } - }; - } - }; - }; - } -}); - -// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/index.mjs -var socialProviders, socialProviderList, SocialProviderListEnum; -var init_social_providers = __esm({ - "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/social-providers/index.mjs"() { - init_apple(); - init_atlassian(); - init_cognito(); - init_discord(); - init_dropbox(); - init_facebook(); - init_figma(); - init_github(); - init_gitlab(); - init_google(); - init_huggingface(); - init_kakao(); - init_kick(); - init_line2(); - init_linear(); - init_linkedin(); - init_microsoft_entra_id(); - init_naver(); - init_notion(); - init_paybin(); - init_paypal(); - init_polar(); - init_reddit(); - init_roblox(); - init_salesforce(); - init_slack(); - init_spotify(); - init_tiktok(); - init_twitch(); - init_twitter(); - init_vercel(); - init_vk(); - init_zoom(); - init_zod(); - socialProviders = { - apple, - atlassian, - cognito, - discord, - facebook, - figma, - github, - microsoft, - google, - huggingface, - slack, - spotify, - twitch, - twitter, - dropbox, - kick, - linear, - linkedin, - gitlab, - tiktok, - reddit, - roblox, - salesforce, - vk, - zoom, - notion, - kakao, - naver, - line: line2, - paybin, - paypal, - polar, - vercel - }; - socialProviderList = Object.keys(socialProviders); - SocialProviderListEnum = _enum2(socialProviderList).or(string2()); - } -}); - -// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/api/routes/account.mjs -var listUserAccounts, linkSocialAccount, unlinkAccount, getAccessToken, refreshToken, accountInfoQuerySchema, accountInfo; -var init_account2 = __esm({ - "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/api/routes/account.mjs"() { - init_schema4(); - init_session_store(); - init_state2(); - init_utils12(); - init_session4(); - init_error(); - init_dist3(); - init_zod(); - init_social_providers(); - init_api2(); - listUserAccounts = createAuthEndpoint("/list-accounts", { - method: "GET", - use: [sessionMiddleware], - metadata: { openapi: { - operationId: "listUserAccounts", - description: "List all accounts linked to the user", - responses: { "200": { - description: "Success", - content: { "application/json": { schema: { - type: "array", - items: { - type: "object", - properties: { - id: { type: "string" }, - providerId: { type: "string" }, - createdAt: { - type: "string", - format: "date-time" - }, - updatedAt: { - type: "string", - format: "date-time" - }, - accountId: { type: "string" }, - userId: { type: "string" }, - scopes: { - type: "array", - items: { type: "string" } - } - }, - required: [ - "id", - "providerId", - "createdAt", - "updatedAt", - "accountId", - "userId", - "scopes" - ] - } - } } } - } } - } } - }, async (c5) => { - const session = c5.context.session; - const accounts = await c5.context.internalAdapter.findAccounts(session.user.id); - return c5.json(accounts.map((a5) => { - const { scope, ...parsed } = parseAccountOutput(c5.context.options, a5); - return { - ...parsed, - scopes: scope?.split(",") || [] - }; - })); - }); - linkSocialAccount = createAuthEndpoint("/link-social", { - method: "POST", - requireHeaders: true, - body: object({ - callbackURL: string2().meta({ description: "The URL to redirect to after the user has signed in" }).optional(), - provider: SocialProviderListEnum, - idToken: object({ - token: string2(), - nonce: string2().optional(), - accessToken: string2().optional(), - refreshToken: string2().optional(), - scopes: array(string2()).optional() - }).optional(), - requestSignUp: boolean3().optional(), - scopes: array(string2()).meta({ description: "Additional scopes to request from the provider" }).optional(), - errorCallbackURL: string2().meta({ description: "The URL to redirect to if there is an error during the link process" }).optional(), - disableRedirect: boolean3().meta({ description: "Disable automatic redirection to the provider. Useful for handling the redirection yourself" }).optional(), - additionalData: record(string2(), any()).optional() - }), - use: [sessionMiddleware], - metadata: { openapi: { - description: "Link a social account to the user", - operationId: "linkSocialAccount", - responses: { "200": { - description: "Success", - content: { "application/json": { schema: { - type: "object", - properties: { - url: { - type: "string", - description: "The authorization URL to redirect the user to" - }, - redirect: { - type: "boolean", - description: "Indicates if the user should be redirected to the authorization URL" - }, - status: { type: "boolean" } - }, - required: ["redirect"] - } } } - } } - } } - }, async (c5) => { - const session = c5.context.session; - const provider = c5.context.socialProviders.find((p5) => p5.id === c5.body.provider); - if (!provider) { - c5.context.logger.error("Provider not found. Make sure to add the provider in your auth config", { provider: c5.body.provider }); - throw new APIError("NOT_FOUND", { message: BASE_ERROR_CODES.PROVIDER_NOT_FOUND }); - } - if (c5.body.idToken) { - if (!provider.verifyIdToken) { - c5.context.logger.error("Provider does not support id token verification", { provider: c5.body.provider }); - throw new APIError("NOT_FOUND", { message: BASE_ERROR_CODES.ID_TOKEN_NOT_SUPPORTED }); - } - const { token, nonce } = c5.body.idToken; - if (!await provider.verifyIdToken(token, nonce)) { - c5.context.logger.error("Invalid id token", { provider: c5.body.provider }); - throw new APIError("UNAUTHORIZED", { message: BASE_ERROR_CODES.INVALID_TOKEN }); - } - const linkingUserInfo = await provider.getUserInfo({ - idToken: token, - accessToken: c5.body.idToken.accessToken, - refreshToken: c5.body.idToken.refreshToken - }); - if (!linkingUserInfo || !linkingUserInfo?.user) { - c5.context.logger.error("Failed to get user info", { provider: c5.body.provider }); - throw new APIError("UNAUTHORIZED", { message: BASE_ERROR_CODES.FAILED_TO_GET_USER_INFO }); - } - const linkingUserId = String(linkingUserInfo.user.id); - if (!linkingUserInfo.user.email) { - c5.context.logger.error("User email not found", { provider: c5.body.provider }); - throw new APIError("UNAUTHORIZED", { message: BASE_ERROR_CODES.USER_EMAIL_NOT_FOUND }); - } - if ((await c5.context.internalAdapter.findAccounts(session.user.id)).find((a5) => a5.providerId === provider.id && a5.accountId === linkingUserId)) return c5.json({ - url: "", - status: true, - redirect: false - }); - if (!c5.context.options.account?.accountLinking?.trustedProviders?.includes(provider.id) && !linkingUserInfo.user.emailVerified || c5.context.options.account?.accountLinking?.enabled === false) throw new APIError("UNAUTHORIZED", { message: "Account not linked - linking not allowed" }); - if (linkingUserInfo.user.email !== session.user.email && c5.context.options.account?.accountLinking?.allowDifferentEmails !== true) throw new APIError("UNAUTHORIZED", { message: "Account not linked - different emails not allowed" }); - try { - await c5.context.internalAdapter.createAccount({ - userId: session.user.id, - providerId: provider.id, - accountId: linkingUserId, - accessToken: c5.body.idToken.accessToken, - idToken: token, - refreshToken: c5.body.idToken.refreshToken, - scope: c5.body.idToken.scopes?.join(",") - }); - } catch { - throw new APIError("EXPECTATION_FAILED", { message: "Account not linked - unable to create account" }); - } - if (c5.context.options.account?.accountLinking?.updateUserInfoOnLink === true) try { - await c5.context.internalAdapter.updateUser(session.user.id, { - name: linkingUserInfo.user?.name, - image: linkingUserInfo.user?.image - }); - } catch (e5) { - console.warn("Could not update user - " + e5.toString()); - } - return c5.json({ - url: "", - status: true, - redirect: false - }); - } - const state2 = await generateState(c5, { - userId: session.user.id, - email: session.user.email - }, c5.body.additionalData); - const url2 = await provider.createAuthorizationURL({ - state: state2.state, - codeVerifier: state2.codeVerifier, - redirectURI: `${c5.context.baseURL}/callback/${provider.id}`, - scopes: c5.body.scopes - }); - if (!c5.body.disableRedirect) c5.setHeader("Location", url2.toString()); - return c5.json({ - url: url2.toString(), - redirect: !c5.body.disableRedirect - }); - }); - unlinkAccount = createAuthEndpoint("/unlink-account", { - method: "POST", - body: object({ - providerId: string2(), - accountId: string2().optional() - }), - use: [freshSessionMiddleware], - metadata: { openapi: { - description: "Unlink an account", - responses: { "200": { - description: "Success", - content: { "application/json": { schema: { - type: "object", - properties: { status: { type: "boolean" } } - } } } - } } - } } - }, async (ctx) => { - const { providerId, accountId } = ctx.body; - const accounts = await ctx.context.internalAdapter.findAccounts(ctx.context.session.user.id); - if (accounts.length === 1 && !ctx.context.options.account?.accountLinking?.allowUnlinkingAll) throw new APIError("BAD_REQUEST", { message: BASE_ERROR_CODES.FAILED_TO_UNLINK_LAST_ACCOUNT }); - const accountExist = accounts.find((account) => accountId ? account.accountId === accountId && account.providerId === providerId : account.providerId === providerId); - if (!accountExist) throw new APIError("BAD_REQUEST", { message: BASE_ERROR_CODES.ACCOUNT_NOT_FOUND }); - await ctx.context.internalAdapter.deleteAccount(accountExist.id); - return ctx.json({ status: true }); - }); - getAccessToken = createAuthEndpoint("/get-access-token", { - method: "POST", - body: object({ - providerId: string2().meta({ description: "The provider ID for the OAuth provider" }), - accountId: string2().meta({ description: "The account ID associated with the refresh token" }).optional(), - userId: string2().meta({ description: "The user ID associated with the account" }).optional() - }), - metadata: { openapi: { - description: "Get a valid access token, doing a refresh if needed", - responses: { - 200: { - description: "A Valid access token", - content: { "application/json": { schema: { - type: "object", - properties: { - tokenType: { type: "string" }, - idToken: { type: "string" }, - accessToken: { type: "string" }, - accessTokenExpiresAt: { - type: "string", - format: "date-time" - } - } - } } } - }, - 400: { description: "Invalid refresh token or provider configuration" } - } - } } - }, async (ctx) => { - const { providerId, accountId, userId } = ctx.body || {}; - const req = ctx.request; - const session = await getSessionFromCtx(ctx); - if (req && !session) throw ctx.error("UNAUTHORIZED"); - const resolvedUserId = session?.user?.id || userId; - if (!resolvedUserId) throw ctx.error("UNAUTHORIZED"); - if (!ctx.context.socialProviders.find((p5) => p5.id === providerId)) throw new APIError("BAD_REQUEST", { message: `Provider ${providerId} is not supported.` }); - const accountData = await getAccountCookie(ctx); - let account = void 0; - if (accountData && providerId === accountData.providerId && (!accountId || accountData.id === accountId)) account = accountData; - else account = (await ctx.context.internalAdapter.findAccounts(resolvedUserId)).find((acc) => accountId ? acc.id === accountId && acc.providerId === providerId : acc.providerId === providerId); - if (!account) throw new APIError("BAD_REQUEST", { message: "Account not found" }); - const provider = ctx.context.socialProviders.find((p5) => p5.id === providerId); - if (!provider) throw new APIError("BAD_REQUEST", { message: `Provider ${providerId} not found.` }); - try { - let newTokens = null; - const accessTokenExpired = account.accessTokenExpiresAt && new Date(account.accessTokenExpiresAt).getTime() - Date.now() < 5e3; - if (account.refreshToken && accessTokenExpired && provider.refreshAccessToken) { - const refreshToken$1 = await decryptOAuthToken(account.refreshToken, ctx.context); - newTokens = await provider.refreshAccessToken(refreshToken$1); - const updatedData = { - accessToken: await setTokenUtil(newTokens.accessToken, ctx.context), - accessTokenExpiresAt: newTokens.accessTokenExpiresAt, - refreshToken: await setTokenUtil(newTokens.refreshToken, ctx.context), - refreshTokenExpiresAt: newTokens.refreshTokenExpiresAt - }; - let updatedAccount = null; - if (account.id) updatedAccount = await ctx.context.internalAdapter.updateAccount(account.id, updatedData); - if (ctx.context.options.account?.storeAccountCookie) await setAccountCookie(ctx, { - ...account, - ...updatedAccount ?? updatedData - }); - } - const accessTokenExpiresAt = (() => { - if (newTokens?.accessTokenExpiresAt) { - if (typeof newTokens.accessTokenExpiresAt === "string") return new Date(newTokens.accessTokenExpiresAt); - return newTokens.accessTokenExpiresAt; - } - if (account.accessTokenExpiresAt) { - if (typeof account.accessTokenExpiresAt === "string") return new Date(account.accessTokenExpiresAt); - return account.accessTokenExpiresAt; - } - })(); - const tokens = { - accessToken: newTokens?.accessToken ?? await decryptOAuthToken(account.accessToken ?? "", ctx.context), - accessTokenExpiresAt, - scopes: account.scope?.split(",") ?? [], - idToken: newTokens?.idToken ?? account.idToken ?? void 0 - }; - return ctx.json(tokens); - } catch (error50) { - throw new APIError("BAD_REQUEST", { - message: "Failed to get a valid access token", - cause: error50 - }); - } - }); - refreshToken = createAuthEndpoint("/refresh-token", { - method: "POST", - body: object({ - providerId: string2().meta({ description: "The provider ID for the OAuth provider" }), - accountId: string2().meta({ description: "The account ID associated with the refresh token" }).optional(), - userId: string2().meta({ description: "The user ID associated with the account" }).optional() - }), - metadata: { openapi: { - description: "Refresh the access token using a refresh token", - responses: { - 200: { - description: "Access token refreshed successfully", - content: { "application/json": { schema: { - type: "object", - properties: { - tokenType: { type: "string" }, - idToken: { type: "string" }, - accessToken: { type: "string" }, - refreshToken: { type: "string" }, - accessTokenExpiresAt: { - type: "string", - format: "date-time" - }, - refreshTokenExpiresAt: { - type: "string", - format: "date-time" - } - } - } } } - }, - 400: { description: "Invalid refresh token or provider configuration" } - } - } } - }, async (ctx) => { - const { providerId, accountId, userId } = ctx.body; - const req = ctx.request; - const session = await getSessionFromCtx(ctx); - if (req && !session) throw ctx.error("UNAUTHORIZED"); - const resolvedUserId = session?.user?.id || userId; - if (!resolvedUserId) throw new APIError("BAD_REQUEST", { message: `Either userId or session is required` }); - const provider = ctx.context.socialProviders.find((p5) => p5.id === providerId); - if (!provider) throw new APIError("BAD_REQUEST", { message: `Provider ${providerId} not found.` }); - if (!provider.refreshAccessToken) throw new APIError("BAD_REQUEST", { message: `Provider ${providerId} does not support token refreshing.` }); - let account = void 0; - const accountData = await getAccountCookie(ctx); - if (accountData && (!providerId || providerId === accountData?.providerId)) account = accountData; - else account = (await ctx.context.internalAdapter.findAccounts(resolvedUserId)).find((acc) => accountId ? acc.id === accountId && acc.providerId === providerId : acc.providerId === providerId); - if (!account) throw new APIError("BAD_REQUEST", { message: "Account not found" }); - let refreshToken$1 = void 0; - if (accountData && providerId === accountData.providerId) refreshToken$1 = accountData.refreshToken ?? void 0; - else refreshToken$1 = account.refreshToken ?? void 0; - if (!refreshToken$1) throw new APIError("BAD_REQUEST", { message: "Refresh token not found" }); - try { - const decryptedRefreshToken = await decryptOAuthToken(refreshToken$1, ctx.context); - const tokens = await provider.refreshAccessToken(decryptedRefreshToken); - if (account.id) { - const updateData = { - ...account || {}, - accessToken: await setTokenUtil(tokens.accessToken, ctx.context), - refreshToken: await setTokenUtil(tokens.refreshToken, ctx.context), - accessTokenExpiresAt: tokens.accessTokenExpiresAt, - refreshTokenExpiresAt: tokens.refreshTokenExpiresAt, - scope: tokens.scopes?.join(",") || account.scope, - idToken: tokens.idToken || account.idToken - }; - await ctx.context.internalAdapter.updateAccount(account.id, updateData); - } - if (accountData && providerId === accountData.providerId && ctx.context.options.account?.storeAccountCookie) await setAccountCookie(ctx, { - ...accountData, - accessToken: await setTokenUtil(tokens.accessToken, ctx.context), - refreshToken: await setTokenUtil(tokens.refreshToken, ctx.context), - accessTokenExpiresAt: tokens.accessTokenExpiresAt, - refreshTokenExpiresAt: tokens.refreshTokenExpiresAt, - scope: tokens.scopes?.join(",") || accountData.scope, - idToken: tokens.idToken || accountData.idToken - }); - return ctx.json({ - accessToken: tokens.accessToken, - refreshToken: tokens.refreshToken, - accessTokenExpiresAt: tokens.accessTokenExpiresAt, - refreshTokenExpiresAt: tokens.refreshTokenExpiresAt, - scope: tokens.scopes?.join(",") || account.scope, - idToken: tokens.idToken || account.idToken, - providerId: account.providerId, - accountId: account.accountId - }); - } catch (error50) { - throw new APIError("BAD_REQUEST", { - message: "Failed to refresh access token", - cause: error50 - }); - } - }); - accountInfoQuerySchema = optional(object({ accountId: string2().meta({ description: "The provider given account id for which to get the account info" }).optional() })); - accountInfo = createAuthEndpoint("/account-info", { - method: "GET", - use: [sessionMiddleware], - metadata: { openapi: { - description: "Get the account info provided by the provider", - responses: { "200": { - description: "Success", - content: { "application/json": { schema: { - type: "object", - properties: { - user: { - type: "object", - properties: { - id: { type: "string" }, - name: { type: "string" }, - email: { type: "string" }, - image: { type: "string" }, - emailVerified: { type: "boolean" } - }, - required: ["id", "emailVerified"] - }, - data: { - type: "object", - properties: {}, - additionalProperties: true - } - }, - required: ["user", "data"], - additionalProperties: false - } } } - } } - } }, - query: accountInfoQuerySchema - }, async (ctx) => { - const providedAccountId = ctx.query?.accountId; - let account = void 0; - if (!providedAccountId) { - if (ctx.context.options.account?.storeAccountCookie) { - const accountData = await getAccountCookie(ctx); - if (accountData) account = accountData; - } - } else { - const accountData = await ctx.context.internalAdapter.findAccount(providedAccountId); - if (accountData) account = accountData; - } - if (!account || account.userId !== ctx.context.session.user.id) throw new APIError("BAD_REQUEST", { message: "Account not found" }); - const provider = ctx.context.socialProviders.find((p5) => p5.id === account.providerId); - if (!provider) throw new APIError("INTERNAL_SERVER_ERROR", { message: `Provider account provider is ${account.providerId} but it is not configured` }); - const tokens = await getAccessToken({ - ...ctx, - method: "POST", - body: { - accountId: account.id, - providerId: account.providerId - }, - returnHeaders: false, - returnStatus: false - }); - if (!tokens.accessToken) throw new APIError("BAD_REQUEST", { message: "Access token not found" }); - const info2 = await provider.getUserInfo({ - ...tokens, - accessToken: tokens.accessToken - }); - return ctx.json(info2); - }); - } -}); - -// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/api/routes/email-verification.mjs -async function createEmailVerificationToken(secret, email3, updateTo, expiresIn = 3600, extraPayload) { - return await signJWT({ - email: email3.toLowerCase(), - updateTo, - ...extraPayload - }, secret, expiresIn); -} -async function sendVerificationEmailFn(ctx, user) { - if (!ctx.context.options.emailVerification?.sendVerificationEmail) { - ctx.context.logger.error("Verification email isn't enabled."); - throw new APIError("BAD_REQUEST", { message: "Verification email isn't enabled" }); - } - const token = await createEmailVerificationToken(ctx.context.secret, user.email, void 0, ctx.context.options.emailVerification?.expiresIn); - const callbackURL = ctx.body.callbackURL ? encodeURIComponent(ctx.body.callbackURL) : encodeURIComponent("/"); - const url2 = `${ctx.context.baseURL}/verify-email?token=${token}&callbackURL=${callbackURL}`; - await ctx.context.runInBackgroundOrAwait(ctx.context.options.emailVerification.sendVerificationEmail({ - user, - url: url2, - token - }, ctx.request)); -} -var sendVerificationEmail, verifyEmail; -var init_email_verification = __esm({ - "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/api/routes/email-verification.mjs"() { - init_schema4(); - init_origin_check(); - init_middlewares(); - init_jwt(); - init_cookies2(); - init_session4(); - init_error(); - init_dist3(); - init_zod(); - init_api2(); - init_webapi(); - init_errors7(); - sendVerificationEmail = createAuthEndpoint("/send-verification-email", { - method: "POST", - operationId: "sendVerificationEmail", - body: object({ - email: email2().meta({ description: "The email to send the verification email to" }), - callbackURL: string2().meta({ description: "The URL to use for email verification callback" }).optional() - }), - metadata: { openapi: { - operationId: "sendVerificationEmail", - description: "Send a verification email to the user", - requestBody: { content: { "application/json": { schema: { - type: "object", - properties: { - email: { - type: "string", - description: "The email to send the verification email to", - example: "user@example.com" - }, - callbackURL: { - type: "string", - description: "The URL to use for email verification callback", - example: "https://example.com/callback", - nullable: true - } - }, - required: ["email"] - } } } }, - responses: { - "200": { - description: "Success", - content: { "application/json": { schema: { - type: "object", - properties: { status: { - type: "boolean", - description: "Indicates if the email was sent successfully", - example: true - } } - } } } - }, - "400": { - description: "Bad Request", - content: { "application/json": { schema: { - type: "object", - properties: { message: { - type: "string", - description: "Error message", - example: "Verification email isn't enabled" - } } - } } } - } - } - } } - }, async (ctx) => { - if (!ctx.context.options.emailVerification?.sendVerificationEmail) { - ctx.context.logger.error("Verification email isn't enabled."); - throw new APIError("BAD_REQUEST", { message: "Verification email isn't enabled" }); - } - const { email: email3 } = ctx.body; - const session = await getSessionFromCtx(ctx); - if (!session) { - const user = await ctx.context.internalAdapter.findUserByEmail(email3); - if (!user) { - await createEmailVerificationToken(ctx.context.secret, email3, void 0, ctx.context.options.emailVerification?.expiresIn); - return ctx.json({ status: true }); - } - await sendVerificationEmailFn(ctx, user.user); - return ctx.json({ status: true }); - } - if (session?.user.email !== email3) throw new APIError("BAD_REQUEST", { message: BASE_ERROR_CODES.EMAIL_MISMATCH }); - if (session?.user.emailVerified) throw new APIError("BAD_REQUEST", { message: BASE_ERROR_CODES.EMAIL_ALREADY_VERIFIED }); - await sendVerificationEmailFn(ctx, session.user); - return ctx.json({ status: true }); - }); - verifyEmail = createAuthEndpoint("/verify-email", { - method: "GET", - operationId: "verifyEmail", - query: object({ - token: string2().meta({ description: "The token to verify the email" }), - callbackURL: string2().meta({ description: "The URL to redirect to after email verification" }).optional() - }), - use: [originCheck((ctx) => ctx.query.callbackURL)], - metadata: { openapi: { - description: "Verify the email of the user", - parameters: [{ - name: "token", - in: "query", - description: "The token to verify the email", - required: true, - schema: { type: "string" } - }, { - name: "callbackURL", - in: "query", - description: "The URL to redirect to after email verification", - required: false, - schema: { type: "string" } - }], - responses: { "200": { - description: "Success", - content: { "application/json": { schema: { - type: "object", - properties: { - user: { - type: "object", - $ref: "#/components/schemas/User" - }, - status: { - type: "boolean", - description: "Indicates if the email was verified successfully" - } - }, - required: ["user", "status"] - } } } - } } - } } - }, async (ctx) => { - function redirectOnError(error50) { - if (ctx.query.callbackURL) { - if (ctx.query.callbackURL.includes("?")) throw ctx.redirect(`${ctx.query.callbackURL}&error=${error50}`); - throw ctx.redirect(`${ctx.query.callbackURL}?error=${error50}`); - } - throw new APIError("UNAUTHORIZED", { message: error50 }); - } - const { token } = ctx.query; - let jwt2; - try { - jwt2 = await jwtVerify(token, new TextEncoder().encode(ctx.context.secret), { algorithms: ["HS256"] }); - } catch (e5) { - if (e5 instanceof JWTExpired) return redirectOnError("token_expired"); - return redirectOnError("invalid_token"); - } - const parsed = object({ - email: email2(), - updateTo: string2().optional(), - requestType: string2().optional() - }).parse(jwt2.payload); - const user = await ctx.context.internalAdapter.findUserByEmail(parsed.email); - if (!user) return redirectOnError("user_not_found"); - if (parsed.updateTo) { - const session = await getSessionFromCtx(ctx); - if (session && session.user.email !== parsed.email) return redirectOnError("unauthorized"); - switch (parsed.requestType) { - case "change-email-confirmation": { - const newToken = await createEmailVerificationToken(ctx.context.secret, parsed.email, parsed.updateTo, ctx.context.options.emailVerification?.expiresIn, { requestType: "change-email-verification" }); - const updateCallbackURL = ctx.query.callbackURL ? encodeURIComponent(ctx.query.callbackURL) : encodeURIComponent("/"); - const url2 = `${ctx.context.baseURL}/verify-email?token=${newToken}&callbackURL=${updateCallbackURL}`; - if (ctx.context.options.emailVerification?.sendVerificationEmail) await ctx.context.runInBackgroundOrAwait(ctx.context.options.emailVerification.sendVerificationEmail({ - user: { - ...user.user, - email: parsed.updateTo - }, - url: url2, - token: newToken - }, ctx.request)); - if (ctx.query.callbackURL) throw ctx.redirect(ctx.query.callbackURL); - return ctx.json({ status: true }); - } - case "change-email-verification": { - let activeSession = session; - if (!activeSession) { - const newSession = await ctx.context.internalAdapter.createSession(user.user.id); - if (!newSession) throw new APIError("INTERNAL_SERVER_ERROR", { message: BASE_ERROR_CODES.FAILED_TO_CREATE_SESSION }); - activeSession = { - session: newSession, - user: user.user - }; - } - if (ctx.context.options.emailVerification?.onEmailVerification) await ctx.context.options.emailVerification.onEmailVerification(user.user, ctx.request); - const updatedUser$1 = await ctx.context.internalAdapter.updateUserByEmail(parsed.email, { - email: parsed.updateTo, - emailVerified: true - }); - if (ctx.context.options.emailVerification?.afterEmailVerification) await ctx.context.options.emailVerification.afterEmailVerification(updatedUser$1, ctx.request); - await setSessionCookie(ctx, { - session: activeSession.session, - user: { - ...activeSession.user, - email: parsed.updateTo, - emailVerified: true - } - }); - if (ctx.query.callbackURL) throw ctx.redirect(ctx.query.callbackURL); - return ctx.json({ - status: true, - user: parseUserOutput(ctx.context.options, updatedUser$1) - }); - } - default: { - let activeSession = session; - if (!activeSession) { - const newSession = await ctx.context.internalAdapter.createSession(user.user.id); - if (!newSession) throw new APIError("INTERNAL_SERVER_ERROR", { message: BASE_ERROR_CODES.FAILED_TO_CREATE_SESSION }); - activeSession = { - session: newSession, - user: user.user - }; - } - const updatedUser$1 = await ctx.context.internalAdapter.updateUserByEmail(parsed.email, { - email: parsed.updateTo, - emailVerified: false - }); - const newToken = await createEmailVerificationToken(ctx.context.secret, parsed.updateTo); - const updateCallbackURL = ctx.query.callbackURL ? encodeURIComponent(ctx.query.callbackURL) : encodeURIComponent("/"); - if (ctx.context.options.emailVerification?.sendVerificationEmail) await ctx.context.runInBackgroundOrAwait(ctx.context.options.emailVerification.sendVerificationEmail({ - user: updatedUser$1, - url: `${ctx.context.baseURL}/verify-email?token=${newToken}&callbackURL=${updateCallbackURL}`, - token: newToken - }, ctx.request)); - await setSessionCookie(ctx, { - session: activeSession.session, - user: { - ...activeSession.user, - email: parsed.updateTo, - emailVerified: false - } - }); - if (ctx.query.callbackURL) throw ctx.redirect(ctx.query.callbackURL); - return ctx.json({ - status: true, - user: parseUserOutput(ctx.context.options, updatedUser$1) - }); - } - } - } - if (user.user.emailVerified) { - if (ctx.query.callbackURL) throw ctx.redirect(ctx.query.callbackURL); - return ctx.json({ - status: true, - user: null - }); - } - if (ctx.context.options.emailVerification?.beforeEmailVerification) await ctx.context.options.emailVerification.beforeEmailVerification(user.user, ctx.request); - if (ctx.context.options.emailVerification?.onEmailVerification) await ctx.context.options.emailVerification.onEmailVerification(user.user, ctx.request); - const updatedUser = await ctx.context.internalAdapter.updateUserByEmail(parsed.email, { emailVerified: true }); - if (ctx.context.options.emailVerification?.afterEmailVerification) await ctx.context.options.emailVerification.afterEmailVerification(updatedUser, ctx.request); - if (ctx.context.options.emailVerification?.autoSignInAfterVerification) { - const currentSession = await getSessionFromCtx(ctx); - if (!currentSession || currentSession.user.email !== parsed.email) { - const session = await ctx.context.internalAdapter.createSession(user.user.id); - if (!session) throw new APIError("INTERNAL_SERVER_ERROR", { message: "Failed to create session" }); - await setSessionCookie(ctx, { - session, - user: { - ...user.user, - emailVerified: true - } - }); - } else await setSessionCookie(ctx, { - session: currentSession.session, - user: { - ...currentSession.user, - emailVerified: true - } - }); - } - if (ctx.query.callbackURL) throw ctx.redirect(ctx.query.callbackURL); - return ctx.json({ - status: true, - user: null - }); - }); - } -}); - -// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/oauth2/link-account.mjs -async function handleOAuthUserInfo(c5, opts) { - const { userInfo, account, callbackURL, disableSignUp, overrideUserInfo } = opts; - const dbUser = await c5.context.internalAdapter.findOAuthUser(userInfo.email.toLowerCase(), account.accountId, account.providerId).catch((e5) => { - logger3.error("Better auth was unable to query your database.\nError: ", e5); - const errorURL = c5.context.options.onAPIError?.errorURL || `${c5.context.baseURL}/error`; - throw c5.redirect(`${errorURL}?error=internal_server_error`); - }); - let user = dbUser?.user; - const isRegister = !user; - if (dbUser) { - const linkedAccount = dbUser.linkedAccount ?? dbUser.accounts.find((acc) => acc.providerId === account.providerId && acc.accountId === account.accountId); - if (!linkedAccount) { - const accountLinking = c5.context.options.account?.accountLinking; - const trustedProviders = c5.context.options.account?.accountLinking?.trustedProviders; - if (!(opts.isTrustedProvider || trustedProviders?.includes(account.providerId)) && !userInfo.emailVerified || accountLinking?.enabled === false || accountLinking?.disableImplicitLinking === true) { - if (isDevelopment()) logger3.warn(`User already exist but account isn't linked to ${account.providerId}. To read more about how account linking works in Better Auth see https://www.better-auth.com/docs/concepts/users-accounts#account-linking.`); - return { - error: "account not linked", - data: null - }; - } - try { - await c5.context.internalAdapter.linkAccount({ - providerId: account.providerId, - accountId: userInfo.id.toString(), - userId: dbUser.user.id, - accessToken: await setTokenUtil(account.accessToken, c5.context), - refreshToken: await setTokenUtil(account.refreshToken, c5.context), - idToken: account.idToken, - accessTokenExpiresAt: account.accessTokenExpiresAt, - refreshTokenExpiresAt: account.refreshTokenExpiresAt, - scope: account.scope - }); - } catch (e5) { - logger3.error("Unable to link account", e5); - return { - error: "unable to link account", - data: null - }; - } - if (userInfo.emailVerified && !dbUser.user.emailVerified && userInfo.email.toLowerCase() === dbUser.user.email) await c5.context.internalAdapter.updateUser(dbUser.user.id, { emailVerified: true }); - } else { - const freshTokens = c5.context.options.account?.updateAccountOnSignIn !== false ? Object.fromEntries(Object.entries({ - idToken: account.idToken, - accessToken: await setTokenUtil(account.accessToken, c5.context), - refreshToken: await setTokenUtil(account.refreshToken, c5.context), - accessTokenExpiresAt: account.accessTokenExpiresAt, - refreshTokenExpiresAt: account.refreshTokenExpiresAt, - scope: account.scope - }).filter(([_, value]) => value !== void 0)) : {}; - if (c5.context.options.account?.storeAccountCookie) await setAccountCookie(c5, { - ...linkedAccount, - ...freshTokens - }); - if (Object.keys(freshTokens).length > 0) await c5.context.internalAdapter.updateAccount(linkedAccount.id, freshTokens); - if (userInfo.emailVerified && !dbUser.user.emailVerified && userInfo.email.toLowerCase() === dbUser.user.email) await c5.context.internalAdapter.updateUser(dbUser.user.id, { emailVerified: true }); - } - if (overrideUserInfo) { - const { id: _, ...restUserInfo } = userInfo; - user = await c5.context.internalAdapter.updateUser(dbUser.user.id, { - ...restUserInfo, - email: userInfo.email.toLowerCase(), - emailVerified: userInfo.email.toLowerCase() === dbUser.user.email ? dbUser.user.emailVerified || userInfo.emailVerified : userInfo.emailVerified - }); - } - } else { - if (disableSignUp) return { - error: "signup disabled", - data: null, - isRegister: false - }; - try { - const { id: _, ...restUserInfo } = userInfo; - const accountData = { - accessToken: await setTokenUtil(account.accessToken, c5.context), - refreshToken: await setTokenUtil(account.refreshToken, c5.context), - idToken: account.idToken, - accessTokenExpiresAt: account.accessTokenExpiresAt, - refreshTokenExpiresAt: account.refreshTokenExpiresAt, - scope: account.scope, - providerId: account.providerId, - accountId: userInfo.id.toString() - }; - const { user: createdUser, account: createdAccount } = await c5.context.internalAdapter.createOAuthUser({ - ...restUserInfo, - email: userInfo.email.toLowerCase() - }, accountData); - user = createdUser; - if (c5.context.options.account?.storeAccountCookie) await setAccountCookie(c5, createdAccount); - if (!userInfo.emailVerified && user && c5.context.options.emailVerification?.sendOnSignUp && c5.context.options.emailVerification?.sendVerificationEmail) { - const token = await createEmailVerificationToken(c5.context.secret, user.email, void 0, c5.context.options.emailVerification?.expiresIn); - const url2 = `${c5.context.baseURL}/verify-email?token=${token}&callbackURL=${callbackURL}`; - await c5.context.runInBackgroundOrAwait(c5.context.options.emailVerification.sendVerificationEmail({ - user, - url: url2, - token - }, c5.request)); - } - } catch (e5) { - logger3.error(e5); - if (e5 instanceof APIError) return { - error: e5.message, - data: null, - isRegister: false - }; - return { - error: "unable to create user", - data: null, - isRegister: false - }; - } - } - if (!user) return { - error: "unable to create user", - data: null, - isRegister: false - }; - const session = await c5.context.internalAdapter.createSession(user.id); - if (!session) return { - error: "unable to create session", - data: null, - isRegister: false - }; - return { - data: { - session, - user - }, - error: null, - isRegister - }; -} -var init_link_account = __esm({ - "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/oauth2/link-account.mjs"() { - init_session_store(); - init_utils12(); - init_email_verification(); - init_api3(); - init_env(); - } -}); - -// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/api/routes/callback.mjs -var schema, callbackOAuth; -var init_callback = __esm({ - "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/api/routes/callback.mjs"() { - init_cookies2(); - init_state2(); - init_utils12(); - init_link_account(); - init_hide_metadata(); - init_utils7(); - init_zod(); - init_api2(); - schema = object({ - code: string2().optional(), - error: string2().optional(), - device_id: string2().optional(), - error_description: string2().optional(), - state: string2().optional(), - user: string2().optional() - }); - callbackOAuth = createAuthEndpoint("/callback/:id", { - method: ["GET", "POST"], - operationId: "handleOAuthCallback", - body: schema.optional(), - query: schema.optional(), - metadata: { - ...HIDE_METADATA, - allowedMediaTypes: ["application/x-www-form-urlencoded", "application/json"] - } - }, async (c5) => { - let queryOrBody; - const defaultErrorURL = c5.context.options.onAPIError?.errorURL || `${c5.context.baseURL}/error`; - if (c5.method === "POST") { - const postData = c5.body ? schema.parse(c5.body) : {}; - const queryData = c5.query ? schema.parse(c5.query) : {}; - const mergedData = schema.parse({ - ...postData, - ...queryData - }); - const params = new URLSearchParams(); - for (const [key, value] of Object.entries(mergedData)) if (value !== void 0 && value !== null) params.set(key, String(value)); - const redirectURL = `${c5.context.baseURL}/callback/${c5.params.id}?${params.toString()}`; - throw c5.redirect(redirectURL); - } - try { - if (c5.method === "GET") queryOrBody = schema.parse(c5.query); - else if (c5.method === "POST") queryOrBody = schema.parse(c5.body); - else throw new Error("Unsupported method"); - } catch (e5) { - c5.context.logger.error("INVALID_CALLBACK_REQUEST", e5); - throw c5.redirect(`${defaultErrorURL}?error=invalid_callback_request`); - } - const { code, error: error50, state: state2, error_description, device_id, user: userData } = queryOrBody; - if (!state2) { - c5.context.logger.error("State not found", error50); - const url2 = `${defaultErrorURL}${defaultErrorURL.includes("?") ? "&" : "?"}state=state_not_found`; - throw c5.redirect(url2); - } - const { codeVerifier, callbackURL, link, errorURL, newUserURL, requestSignUp } = await parseState(c5); - function redirectOnError(error$1, description) { - const baseURL = errorURL ?? defaultErrorURL; - const params = new URLSearchParams({ error: error$1 }); - if (description) params.set("error_description", description); - const url2 = `${baseURL}${baseURL.includes("?") ? "&" : "?"}${params.toString()}`; - throw c5.redirect(url2); - } - if (error50) redirectOnError(error50, error_description); - if (!code) { - c5.context.logger.error("Code not found"); - throw redirectOnError("no_code"); - } - const provider = c5.context.socialProviders.find((p5) => p5.id === c5.params.id); - if (!provider) { - c5.context.logger.error("Oauth provider with id", c5.params.id, "not found"); - throw redirectOnError("oauth_provider_not_found"); - } - let tokens; - try { - tokens = await provider.validateAuthorizationCode({ - code, - codeVerifier, - deviceId: device_id, - redirectURI: `${c5.context.baseURL}/callback/${provider.id}` - }); - } catch (e5) { - c5.context.logger.error("", e5); - throw redirectOnError("invalid_code"); - } - if (!tokens) throw redirectOnError("invalid_code"); - const parsedUserData = userData ? safeJSONParse(userData) : null; - const userInfo = await provider.getUserInfo({ - ...tokens, - user: parsedUserData ?? void 0 - }).then((res) => res?.user); - if (!userInfo) { - c5.context.logger.error("Unable to get user info"); - return redirectOnError("unable_to_get_user_info"); - } - if (!callbackURL) { - c5.context.logger.error("No callback URL found"); - throw redirectOnError("no_callback_url"); - } - if (link) { - if (!c5.context.options.account?.accountLinking?.trustedProviders?.includes(provider.id) && !userInfo.emailVerified || c5.context.options.account?.accountLinking?.enabled === false) { - c5.context.logger.error("Unable to link account - untrusted provider"); - return redirectOnError("unable_to_link_account"); - } - if (userInfo.email !== link.email && c5.context.options.account?.accountLinking?.allowDifferentEmails !== true) return redirectOnError("email_doesn't_match"); - const existingAccount = await c5.context.internalAdapter.findAccount(String(userInfo.id)); - if (existingAccount) { - if (existingAccount.userId.toString() !== link.userId.toString()) return redirectOnError("account_already_linked_to_different_user"); - const updateData = Object.fromEntries(Object.entries({ - accessToken: await setTokenUtil(tokens.accessToken, c5.context), - refreshToken: await setTokenUtil(tokens.refreshToken, c5.context), - idToken: tokens.idToken, - accessTokenExpiresAt: tokens.accessTokenExpiresAt, - refreshTokenExpiresAt: tokens.refreshTokenExpiresAt, - scope: tokens.scopes?.join(",") - }).filter(([_, value]) => value !== void 0)); - await c5.context.internalAdapter.updateAccount(existingAccount.id, updateData); - } else if (!await c5.context.internalAdapter.createAccount({ - userId: link.userId, - providerId: provider.id, - accountId: String(userInfo.id), - ...tokens, - accessToken: await setTokenUtil(tokens.accessToken, c5.context), - refreshToken: await setTokenUtil(tokens.refreshToken, c5.context), - scope: tokens.scopes?.join(",") - })) return redirectOnError("unable_to_link_account"); - let toRedirectTo$1; - try { - toRedirectTo$1 = callbackURL.toString(); - } catch { - toRedirectTo$1 = callbackURL; - } - throw c5.redirect(toRedirectTo$1); - } - if (!userInfo.email) { - c5.context.logger.error("Provider did not return email. This could be due to misconfiguration in the provider settings."); - return redirectOnError("email_not_found"); - } - const accountData = { - providerId: provider.id, - accountId: String(userInfo.id), - ...tokens, - scope: tokens.scopes?.join(",") - }; - const result = await handleOAuthUserInfo(c5, { - userInfo: { - ...userInfo, - id: String(userInfo.id), - email: userInfo.email, - name: userInfo.name || userInfo.email - }, - account: accountData, - callbackURL, - disableSignUp: provider.disableImplicitSignUp && !requestSignUp || provider.options?.disableSignUp, - overrideUserInfo: provider.options?.overrideUserInfoOnSignIn - }); - if (result.error) { - c5.context.logger.error(result.error.split(" ").join("_")); - return redirectOnError(result.error.split(" ").join("_")); - } - const { session, user } = result.data; - await setSessionCookie(c5, { - session, - user - }); - let toRedirectTo; - try { - toRedirectTo = (result.isRegister ? newUserURL || callbackURL : callbackURL).toString(); - } catch { - toRedirectTo = result.isRegister ? newUserURL || callbackURL : callbackURL; - } - throw c5.redirect(toRedirectTo); - }); - } -}); - -// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/api/routes/error.mjs -function sanitize(input) { - return input.replace(//g, ">").replace(/"/g, """).replace(/'/g, "'").replace(/&(?!amp;|lt;|gt;|quot;|#39;|#x[0-9a-fA-F]+;|#[0-9]+;)/g, "&"); -} -var html2, error49; -var init_error3 = __esm({ - "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/api/routes/error.mjs"() { - init_hide_metadata(); - init_env(); - init_api2(); - html2 = (options, code = "Unknown", description = null) => { - const custom3 = options.onAPIError?.customizeDefaultErrorPage; - return ` - - - - - Error - - - -
-${custom3?.disableBackgroundGrid ? "" : ` -
-
-`} - -
- ${custom3?.disableCornerDecorations ? "" : ` - -
-
- -
-
`} - -
-
-
-

- ERROR -

-
-
-
- -

- Something went wrong -

- -
- - CODE: - - - ${sanitize(code)} - -
- -

- ${!description ? `We encountered an unexpected error. Please try again or return to the home page. If you're a developer, you can find more information about the error here.` : description} -

-
- - -
-
- -`; - }; - error49 = createAuthEndpoint("/error", { - method: "GET", - metadata: { - ...HIDE_METADATA, - openapi: { - description: "Displays an error page", - responses: { "200": { - description: "Success", - content: { "text/html": { schema: { - type: "string", - description: "The HTML content of the error page" - } } } - } } - } - } - }, async (c5) => { - const url2 = new URL(c5.request?.url || ""); - const unsanitizedCode = url2.searchParams.get("error") || "UNKNOWN"; - const unsanitizedDescription = url2.searchParams.get("error_description") || null; - const safeCode = /^[\'A-Za-z0-9_-]+$/.test(unsanitizedCode || "") ? unsanitizedCode : "UNKNOWN"; - const safeDescription = unsanitizedDescription ? sanitize(unsanitizedDescription) : null; - const queryParams = new URLSearchParams(); - queryParams.set("error", safeCode); - if (unsanitizedDescription) queryParams.set("error_description", unsanitizedDescription); - const options = c5.context.options; - const errorURL = options.onAPIError?.errorURL; - if (errorURL) return new Response(null, { - status: 302, - headers: { Location: `${errorURL}${errorURL.includes("?") ? "&" : "?"}${queryParams.toString()}` } - }); - if (isProduction && !options.onAPIError?.customizeDefaultErrorPage) return new Response(null, { - status: 302, - headers: { Location: `/?${queryParams.toString()}` } - }); - return new Response(html2(c5.context.options, safeCode, safeDescription), { headers: { "Content-Type": "text/html" } }); - }); - } -}); - -// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/api/routes/ok.mjs -var ok; -var init_ok = __esm({ - "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/api/routes/ok.mjs"() { - init_hide_metadata(); - init_api2(); - ok = createAuthEndpoint("/ok", { - method: "GET", - metadata: { - ...HIDE_METADATA, - openapi: { - description: "Check if the API is working", - responses: { "200": { - description: "API is working", - content: { "application/json": { schema: { - type: "object", - properties: { ok: { - type: "boolean", - description: "Indicates if the API is working" - } }, - required: ["ok"] - } } } - } } - } - } - }, async (ctx) => { - return ctx.json({ ok: true }); - }); - } -}); - -// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/utils/password.mjs -async function validatePassword(ctx, data2) { - const credentialAccount = (await ctx.context.internalAdapter.findAccounts(data2.userId))?.find((account) => account.providerId === "credential"); - const currentPassword = credentialAccount?.password; - if (!credentialAccount || !currentPassword) return false; - return await ctx.context.password.verify({ - hash: currentPassword, - password: data2.password - }); -} -async function checkPassword(userId, c5) { - const credentialAccount = (await c5.context.internalAdapter.findAccounts(userId))?.find((account) => account.providerId === "credential"); - const currentPassword = credentialAccount?.password; - if (!credentialAccount || !currentPassword || !c5.body.password) throw new APIError("BAD_REQUEST", { message: "No password credential found" }); - if (!await c5.context.password.verify({ - hash: currentPassword, - password: c5.body.password - })) throw new APIError("BAD_REQUEST", { message: "Invalid password" }); - return true; -} -var init_password2 = __esm({ - "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/utils/password.mjs"() { - init_dist3(); - } -}); - -// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/api/routes/password.mjs -function redirectError(ctx, callbackURL, query) { - const url2 = callbackURL ? new URL(callbackURL, ctx.baseURL) : new URL(`${ctx.baseURL}/error`); - if (query) Object.entries(query).forEach(([k5, v5]) => url2.searchParams.set(k5, v5)); - return url2.href; -} -function redirectCallback(ctx, callbackURL, query) { - const url2 = new URL(callbackURL, ctx.baseURL); - if (query) Object.entries(query).forEach(([k5, v5]) => url2.searchParams.set(k5, v5)); - return url2.href; -} -var requestPasswordReset, requestPasswordResetCallback, resetPassword, verifyPassword2; -var init_password3 = __esm({ - "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/api/routes/password.mjs"() { - init_date2(); - init_origin_check(); - init_middlewares(); - init_session4(); - init_utils10(); - init_password2(); - init_error(); - init_dist3(); - init_zod(); - init_api2(); - requestPasswordReset = createAuthEndpoint("/request-password-reset", { - method: "POST", - body: object({ - email: email2().meta({ description: "The email address of the user to send a password reset email to" }), - redirectTo: string2().meta({ description: "The URL to redirect the user to reset their password. If the token isn't valid or expired, it'll be redirected with a query parameter `?error=INVALID_TOKEN`. If the token is valid, it'll be redirected with a query parameter `?token=VALID_TOKEN" }).optional() - }), - metadata: { openapi: { - operationId: "requestPasswordReset", - description: "Send a password reset email to the user", - responses: { "200": { - description: "Success", - content: { "application/json": { schema: { - type: "object", - properties: { - status: { type: "boolean" }, - message: { type: "string" } - } - } } } - } } - } } - }, async (ctx) => { - if (!ctx.context.options.emailAndPassword?.sendResetPassword) { - ctx.context.logger.error("Reset password isn't enabled.Please pass an emailAndPassword.sendResetPassword function in your auth config!"); - throw new APIError("BAD_REQUEST", { message: "Reset password isn't enabled" }); - } - const { email: email3, redirectTo } = ctx.body; - const user = await ctx.context.internalAdapter.findUserByEmail(email3, { includeAccounts: true }); - if (!user) { - generateId(24); - await ctx.context.internalAdapter.findVerificationValue("dummy-verification-token"); - ctx.context.logger.error("Reset Password: User not found", { email: email3 }); - return ctx.json({ - status: true, - message: "If this email exists in our system, check your email for the reset link" - }); - } - const expiresAt = getDate(ctx.context.options.emailAndPassword.resetPasswordTokenExpiresIn || 3600 * 1, "sec"); - const verificationToken = generateId(24); - await ctx.context.internalAdapter.createVerificationValue({ - value: user.user.id, - identifier: `reset-password:${verificationToken}`, - expiresAt - }); - const callbackURL = redirectTo ? encodeURIComponent(redirectTo) : ""; - const url2 = `${ctx.context.baseURL}/reset-password/${verificationToken}?callbackURL=${callbackURL}`; - await ctx.context.runInBackgroundOrAwait(ctx.context.options.emailAndPassword.sendResetPassword({ - user: user.user, - url: url2, - token: verificationToken - }, ctx.request)); - return ctx.json({ - status: true, - message: "If this email exists in our system, check your email for the reset link" - }); - }); - requestPasswordResetCallback = createAuthEndpoint("/reset-password/:token", { - method: "GET", - operationId: "forgetPasswordCallback", - query: object({ callbackURL: string2().meta({ description: "The URL to redirect the user to reset their password" }) }), - use: [originCheck((ctx) => ctx.query.callbackURL)], - metadata: { openapi: { - operationId: "resetPasswordCallback", - description: "Redirects the user to the callback URL with the token", - parameters: [{ - name: "token", - in: "path", - required: true, - description: "The token to reset the password", - schema: { type: "string" } - }, { - name: "callbackURL", - in: "query", - required: true, - description: "The URL to redirect the user to reset their password", - schema: { type: "string" } - }], - responses: { "200": { - description: "Success", - content: { "application/json": { schema: { - type: "object", - properties: { token: { type: "string" } } - } } } - } } - } } - }, async (ctx) => { - const { token } = ctx.params; - const { callbackURL } = ctx.query; - if (!token || !callbackURL) throw ctx.redirect(redirectError(ctx.context, callbackURL, { error: "INVALID_TOKEN" })); - const verification = await ctx.context.internalAdapter.findVerificationValue(`reset-password:${token}`); - if (!verification || verification.expiresAt < /* @__PURE__ */ new Date()) throw ctx.redirect(redirectError(ctx.context, callbackURL, { error: "INVALID_TOKEN" })); - throw ctx.redirect(redirectCallback(ctx.context, callbackURL, { token })); - }); - resetPassword = createAuthEndpoint("/reset-password", { - method: "POST", - operationId: "resetPassword", - query: object({ token: string2().optional() }).optional(), - body: object({ - newPassword: string2().meta({ description: "The new password to set" }), - token: string2().meta({ description: "The token to reset the password" }).optional() - }), - metadata: { openapi: { - operationId: "resetPassword", - description: "Reset the password for a user", - responses: { "200": { - description: "Success", - content: { "application/json": { schema: { - type: "object", - properties: { status: { type: "boolean" } } - } } } - } } - } } - }, async (ctx) => { - const token = ctx.body.token || ctx.query?.token; - if (!token) throw new APIError("BAD_REQUEST", { message: BASE_ERROR_CODES.INVALID_TOKEN }); - const { newPassword } = ctx.body; - const minLength = ctx.context.password?.config.minPasswordLength; - const maxLength = ctx.context.password?.config.maxPasswordLength; - if (newPassword.length < minLength) throw new APIError("BAD_REQUEST", { message: BASE_ERROR_CODES.PASSWORD_TOO_SHORT }); - if (newPassword.length > maxLength) throw new APIError("BAD_REQUEST", { message: BASE_ERROR_CODES.PASSWORD_TOO_LONG }); - const id = `reset-password:${token}`; - const verification = await ctx.context.internalAdapter.findVerificationValue(id); - if (!verification || verification.expiresAt < /* @__PURE__ */ new Date()) throw new APIError("BAD_REQUEST", { message: BASE_ERROR_CODES.INVALID_TOKEN }); - const userId = verification.value; - const hashedPassword = await ctx.context.password.hash(newPassword); - if (!(await ctx.context.internalAdapter.findAccounts(userId)).find((ac) => ac.providerId === "credential")) await ctx.context.internalAdapter.createAccount({ - userId, - providerId: "credential", - password: hashedPassword, - accountId: userId - }); - else await ctx.context.internalAdapter.updatePassword(userId, hashedPassword); - await ctx.context.internalAdapter.deleteVerificationValue(verification.id); - if (ctx.context.options.emailAndPassword?.onPasswordReset) { - const user = await ctx.context.internalAdapter.findUserById(userId); - if (user) await ctx.context.options.emailAndPassword.onPasswordReset({ user }, ctx.request); - } - if (ctx.context.options.emailAndPassword?.revokeSessionsOnPasswordReset) await ctx.context.internalAdapter.deleteSessions(userId); - return ctx.json({ status: true }); - }); - verifyPassword2 = createAuthEndpoint("/verify-password", { - method: "POST", - body: object({ password: string2().meta({ description: "The password to verify" }) }), - metadata: { - scope: "server", - openapi: { - operationId: "verifyPassword", - description: "Verify the current user's password", - responses: { "200": { - description: "Success", - content: { "application/json": { schema: { - type: "object", - properties: { status: { type: "boolean" } } - } } } - } } - } - }, - use: [sensitiveSessionMiddleware] - }, async (ctx) => { - const { password } = ctx.body; - const session = ctx.context.session; - if (!await validatePassword(ctx, { - password, - userId: session.user.id - })) throw new APIError("BAD_REQUEST", { message: BASE_ERROR_CODES.INVALID_PASSWORD }); - return ctx.json({ status: true }); - }); - } -}); - -// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/api/routes/sign-in.mjs -var socialSignInBodySchema, signInSocial, signInEmail; -var init_sign_in = __esm({ - "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/api/routes/sign-in.mjs"() { - init_schema4(); - init_origin_check(); - init_cookies2(); - init_state2(); - init_link_account(); - init_email_verification(); - init_utils10(); - init_error(); - init_dist3(); - init_zod(); - init_social_providers(); - init_api2(); - socialSignInBodySchema = object({ - callbackURL: string2().meta({ description: "Callback URL to redirect to after the user has signed in" }).optional(), - newUserCallbackURL: string2().optional(), - errorCallbackURL: string2().meta({ description: "Callback URL to redirect to if an error happens" }).optional(), - provider: SocialProviderListEnum, - disableRedirect: boolean3().meta({ description: "Disable automatic redirection to the provider. Useful for handling the redirection yourself" }).optional(), - idToken: optional(object({ - token: string2().meta({ description: "ID token from the provider" }), - nonce: string2().meta({ description: "Nonce used to generate the token" }).optional(), - accessToken: string2().meta({ description: "Access token from the provider" }).optional(), - refreshToken: string2().meta({ description: "Refresh token from the provider" }).optional(), - expiresAt: number2().meta({ description: "Expiry date of the token" }).optional() - })), - scopes: array(string2()).meta({ description: "Array of scopes to request from the provider. This will override the default scopes passed." }).optional(), - requestSignUp: boolean3().meta({ description: "Explicitly request sign-up. Useful when disableImplicitSignUp is true for this provider" }).optional(), - loginHint: string2().meta({ description: "The login hint to use for the authorization code request" }).optional(), - additionalData: record(string2(), any()).optional().meta({ description: "Additional data to be passed through the OAuth flow" }) - }); - signInSocial = () => createAuthEndpoint("/sign-in/social", { - method: "POST", - operationId: "socialSignIn", - body: socialSignInBodySchema, - metadata: { - $Infer: { - body: {}, - returned: {} - }, - openapi: { - description: "Sign in with a social provider", - operationId: "socialSignIn", - responses: { "200": { - description: "Success - Returns either session details or redirect URL", - content: { "application/json": { schema: { - type: "object", - description: "Session response when idToken is provided", - properties: { - token: { type: "string" }, - user: { - type: "object", - $ref: "#/components/schemas/User" - }, - url: { type: "string" }, - redirect: { - type: "boolean", - enum: [false] - } - }, - required: [ - "redirect", - "token", - "user" - ] - } } } - } } - } - } - }, async (c5) => { - const provider = c5.context.socialProviders.find((p5) => p5.id === c5.body.provider); - if (!provider) { - c5.context.logger.error("Provider not found. Make sure to add the provider in your auth config", { provider: c5.body.provider }); - throw new APIError("NOT_FOUND", { message: BASE_ERROR_CODES.PROVIDER_NOT_FOUND }); - } - if (c5.body.idToken) { - if (!provider.verifyIdToken) { - c5.context.logger.error("Provider does not support id token verification", { provider: c5.body.provider }); - throw new APIError("NOT_FOUND", { message: BASE_ERROR_CODES.ID_TOKEN_NOT_SUPPORTED }); - } - const { token, nonce } = c5.body.idToken; - if (!await provider.verifyIdToken(token, nonce)) { - c5.context.logger.error("Invalid id token", { provider: c5.body.provider }); - throw new APIError("UNAUTHORIZED", { message: BASE_ERROR_CODES.INVALID_TOKEN }); - } - const userInfo = await provider.getUserInfo({ - idToken: token, - accessToken: c5.body.idToken.accessToken, - refreshToken: c5.body.idToken.refreshToken - }); - if (!userInfo || !userInfo?.user) { - c5.context.logger.error("Failed to get user info", { provider: c5.body.provider }); - throw new APIError("UNAUTHORIZED", { message: BASE_ERROR_CODES.FAILED_TO_GET_USER_INFO }); - } - if (!userInfo.user.email) { - c5.context.logger.error("User email not found", { provider: c5.body.provider }); - throw new APIError("UNAUTHORIZED", { message: BASE_ERROR_CODES.USER_EMAIL_NOT_FOUND }); - } - const data2 = await handleOAuthUserInfo(c5, { - userInfo: { - ...userInfo.user, - email: userInfo.user.email, - id: String(userInfo.user.id), - name: userInfo.user.name || "", - image: userInfo.user.image, - emailVerified: userInfo.user.emailVerified || false - }, - account: { - providerId: provider.id, - accountId: String(userInfo.user.id), - accessToken: c5.body.idToken.accessToken - }, - callbackURL: c5.body.callbackURL, - disableSignUp: provider.disableImplicitSignUp && !c5.body.requestSignUp || provider.disableSignUp - }); - if (data2.error) throw new APIError("UNAUTHORIZED", { message: data2.error }); - await setSessionCookie(c5, data2.data); - return c5.json({ - redirect: false, - token: data2.data.session.token, - url: void 0, - user: parseUserOutput(c5.context.options, data2.data.user) - }); - } - const { codeVerifier, state: state2 } = await generateState(c5, void 0, c5.body.additionalData); - const url2 = await provider.createAuthorizationURL({ - state: state2, - codeVerifier, - redirectURI: `${c5.context.baseURL}/callback/${provider.id}`, - scopes: c5.body.scopes, - loginHint: c5.body.loginHint - }); - if (!c5.body.disableRedirect) c5.setHeader("Location", url2.toString()); - return c5.json({ - url: url2.toString(), - redirect: !c5.body.disableRedirect - }); - }); - signInEmail = () => createAuthEndpoint("/sign-in/email", { - method: "POST", - operationId: "signInEmail", - use: [formCsrfMiddleware], - body: object({ - email: string2().meta({ description: "Email of the user" }), - password: string2().meta({ description: "Password of the user" }), - callbackURL: string2().meta({ description: "Callback URL to use as a redirect for email verification" }).optional(), - rememberMe: boolean3().meta({ description: "If this is false, the session will not be remembered. Default is `true`." }).default(true).optional() - }), - metadata: { - allowedMediaTypes: ["application/x-www-form-urlencoded", "application/json"], - $Infer: { - body: {}, - returned: {} - }, - openapi: { - operationId: "signInEmail", - description: "Sign in with email and password", - responses: { "200": { - description: "Success - Returns either session details or redirect URL", - content: { "application/json": { schema: { - type: "object", - description: "Session response when idToken is provided", - properties: { - redirect: { - type: "boolean", - enum: [false] - }, - token: { - type: "string", - description: "Session token" - }, - url: { - type: "string", - nullable: true - }, - user: { - type: "object", - $ref: "#/components/schemas/User" - } - }, - required: [ - "redirect", - "token", - "user" - ] - } } } - } } - } - } - }, async (ctx) => { - if (!ctx.context.options?.emailAndPassword?.enabled) { - ctx.context.logger.error("Email and password is not enabled. Make sure to enable it in the options on you `auth.ts` file. Check `https://better-auth.com/docs/authentication/email-password` for more!"); - throw new APIError("BAD_REQUEST", { message: "Email and password is not enabled" }); - } - const { email: email3, password } = ctx.body; - if (!email2().safeParse(email3).success) throw new APIError("BAD_REQUEST", { message: BASE_ERROR_CODES.INVALID_EMAIL }); - const user = await ctx.context.internalAdapter.findUserByEmail(email3, { includeAccounts: true }); - if (!user) { - await ctx.context.password.hash(password); - ctx.context.logger.error("User not found", { email: email3 }); - throw new APIError("UNAUTHORIZED", { message: BASE_ERROR_CODES.INVALID_EMAIL_OR_PASSWORD }); - } - const credentialAccount = user.accounts.find((a5) => a5.providerId === "credential"); - if (!credentialAccount) { - await ctx.context.password.hash(password); - ctx.context.logger.error("Credential account not found", { email: email3 }); - throw new APIError("UNAUTHORIZED", { message: BASE_ERROR_CODES.INVALID_EMAIL_OR_PASSWORD }); - } - const currentPassword = credentialAccount?.password; - if (!currentPassword) { - await ctx.context.password.hash(password); - ctx.context.logger.error("Password not found", { email: email3 }); - throw new APIError("UNAUTHORIZED", { message: BASE_ERROR_CODES.INVALID_EMAIL_OR_PASSWORD }); - } - if (!await ctx.context.password.verify({ - hash: currentPassword, - password - })) { - ctx.context.logger.error("Invalid password"); - throw new APIError("UNAUTHORIZED", { message: BASE_ERROR_CODES.INVALID_EMAIL_OR_PASSWORD }); - } - if (ctx.context.options?.emailAndPassword?.requireEmailVerification && !user.user.emailVerified) { - if (!ctx.context.options?.emailVerification?.sendVerificationEmail) throw new APIError("FORBIDDEN", { message: BASE_ERROR_CODES.EMAIL_NOT_VERIFIED }); - if (ctx.context.options?.emailVerification?.sendOnSignIn) { - const token = await createEmailVerificationToken(ctx.context.secret, user.user.email, void 0, ctx.context.options.emailVerification?.expiresIn); - const callbackURL = ctx.body.callbackURL ? encodeURIComponent(ctx.body.callbackURL) : encodeURIComponent("/"); - const url2 = `${ctx.context.baseURL}/verify-email?token=${token}&callbackURL=${callbackURL}`; - await ctx.context.runInBackgroundOrAwait(ctx.context.options.emailVerification.sendVerificationEmail({ - user: user.user, - url: url2, - token - }, ctx.request)); - } - throw new APIError("FORBIDDEN", { message: BASE_ERROR_CODES.EMAIL_NOT_VERIFIED }); - } - const session = await ctx.context.internalAdapter.createSession(user.user.id, ctx.body.rememberMe === false); - if (!session) { - ctx.context.logger.error("Failed to create session"); - throw new APIError("UNAUTHORIZED", { message: BASE_ERROR_CODES.FAILED_TO_CREATE_SESSION }); - } - await setSessionCookie(ctx, { - session, - user: user.user - }, ctx.body.rememberMe === false); - if (ctx.body.callbackURL) ctx.setHeader("Location", ctx.body.callbackURL); - return ctx.json({ - redirect: !!ctx.body.callbackURL, - token: session.token, - url: ctx.body.callbackURL, - user: parseUserOutput(ctx.context.options, user.user) - }); - }); - } -}); - -// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/api/routes/sign-out.mjs -var signOut; -var init_sign_out = __esm({ - "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/api/routes/sign-out.mjs"() { - init_cookies2(); - init_api2(); - signOut = createAuthEndpoint("/sign-out", { - method: "POST", - operationId: "signOut", - requireHeaders: true, - metadata: { openapi: { - operationId: "signOut", - description: "Sign out the current user", - responses: { "200": { - description: "Success", - content: { "application/json": { schema: { - type: "object", - properties: { success: { type: "boolean" } } - } } } - } } - } } - }, async (ctx) => { - const sessionCookieToken = await ctx.getSignedCookie(ctx.context.authCookies.sessionToken.name, ctx.context.secret); - if (sessionCookieToken) try { - await ctx.context.internalAdapter.deleteSession(sessionCookieToken); - } catch (e5) { - ctx.context.logger.error("Failed to delete session from database", e5); - } - deleteSessionCookie(ctx); - return ctx.json({ success: true }); - }); - } -}); - -// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/api/routes/sign-up.mjs -var signUpEmailBodySchema, signUpEmail; -var init_sign_up = __esm({ - "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/api/routes/sign-up.mjs"() { - init_schema4(); - init_db4(); - init_origin_check(); - init_cookies2(); - init_email_verification(); - init_context2(); - init_env(); - init_error(); - init_dist3(); - init_zod(); - init_api2(); - signUpEmailBodySchema = object({ - name: string2(), - email: email2(), - password: string2().nonempty(), - image: string2().optional(), - callbackURL: string2().optional(), - rememberMe: boolean3().optional() - }).and(record(string2(), any())); - signUpEmail = () => createAuthEndpoint("/sign-up/email", { - method: "POST", - operationId: "signUpWithEmailAndPassword", - use: [formCsrfMiddleware], - body: signUpEmailBodySchema, - metadata: { - allowedMediaTypes: ["application/x-www-form-urlencoded", "application/json"], - $Infer: { - body: {}, - returned: {} - }, - openapi: { - operationId: "signUpWithEmailAndPassword", - description: "Sign up a user using email and password", - requestBody: { content: { "application/json": { schema: { - type: "object", - properties: { - name: { - type: "string", - description: "The name of the user" - }, - email: { - type: "string", - description: "The email of the user" - }, - password: { - type: "string", - description: "The password of the user" - }, - image: { - type: "string", - description: "The profile image URL of the user" - }, - callbackURL: { - type: "string", - description: "The URL to use for email verification callback" - }, - rememberMe: { - type: "boolean", - description: "If this is false, the session will not be remembered. Default is `true`." - } - }, - required: [ - "name", - "email", - "password" - ] - } } } }, - responses: { - "200": { - description: "Successfully created user", - content: { "application/json": { schema: { - type: "object", - properties: { - token: { - type: "string", - nullable: true, - description: "Authentication token for the session" - }, - user: { - type: "object", - properties: { - id: { - type: "string", - description: "The unique identifier of the user" - }, - email: { - type: "string", - format: "email", - description: "The email address of the user" - }, - name: { - type: "string", - description: "The name of the user" - }, - image: { - type: "string", - format: "uri", - nullable: true, - description: "The profile image URL of the user" - }, - emailVerified: { - type: "boolean", - description: "Whether the email has been verified" - }, - createdAt: { - type: "string", - format: "date-time", - description: "When the user was created" - }, - updatedAt: { - type: "string", - format: "date-time", - description: "When the user was last updated" - } - }, - required: [ - "id", - "email", - "name", - "emailVerified", - "createdAt", - "updatedAt" - ] - } - }, - required: ["user"] - } } } - }, - "422": { - description: "Unprocessable Entity. User already exists or failed to create user.", - content: { "application/json": { schema: { - type: "object", - properties: { message: { type: "string" } } - } } } - } - } - } - } - }, async (ctx) => { - return runWithTransaction(ctx.context.adapter, async () => { - if (!ctx.context.options.emailAndPassword?.enabled || ctx.context.options.emailAndPassword?.disableSignUp) throw new APIError("BAD_REQUEST", { message: "Email and password sign up is not enabled" }); - const body = ctx.body; - const { name, email: email3, password, image, callbackURL: _callbackURL, rememberMe, ...rest } = body; - if (!email2().safeParse(email3).success) throw new APIError("BAD_REQUEST", { message: BASE_ERROR_CODES.INVALID_EMAIL }); - if (!password || typeof password !== "string") throw new APIError("BAD_REQUEST", { message: BASE_ERROR_CODES.INVALID_PASSWORD }); - const minPasswordLength = ctx.context.password.config.minPasswordLength; - if (password.length < minPasswordLength) { - ctx.context.logger.error("Password is too short"); - throw new APIError("BAD_REQUEST", { message: BASE_ERROR_CODES.PASSWORD_TOO_SHORT }); - } - const maxPasswordLength = ctx.context.password.config.maxPasswordLength; - if (password.length > maxPasswordLength) { - ctx.context.logger.error("Password is too long"); - throw new APIError("BAD_REQUEST", { message: BASE_ERROR_CODES.PASSWORD_TOO_LONG }); - } - if ((await ctx.context.internalAdapter.findUserByEmail(email3))?.user) { - ctx.context.logger.info(`Sign-up attempt for existing email: ${email3}`); - throw new APIError("UNPROCESSABLE_ENTITY", { message: BASE_ERROR_CODES.USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL }); - } - const hash2 = await ctx.context.password.hash(password); - let createdUser; - try { - const data2 = parseUserInput(ctx.context.options, rest, "create"); - createdUser = await ctx.context.internalAdapter.createUser({ - email: email3.toLowerCase(), - name, - image, - ...data2, - emailVerified: false - }); - if (!createdUser) throw new APIError("BAD_REQUEST", { message: BASE_ERROR_CODES.FAILED_TO_CREATE_USER }); - } catch (e5) { - if (isDevelopment()) ctx.context.logger.error("Failed to create user", e5); - if (e5 instanceof APIError) throw e5; - ctx.context.logger?.error("Failed to create user", e5); - throw new APIError("UNPROCESSABLE_ENTITY", { message: BASE_ERROR_CODES.FAILED_TO_CREATE_USER }); - } - if (!createdUser) throw new APIError("UNPROCESSABLE_ENTITY", { message: BASE_ERROR_CODES.FAILED_TO_CREATE_USER }); - await ctx.context.internalAdapter.linkAccount({ - userId: createdUser.id, - providerId: "credential", - accountId: createdUser.id, - password: hash2 - }); - if (ctx.context.options.emailVerification?.sendOnSignUp ?? ctx.context.options.emailAndPassword.requireEmailVerification) { - const token = await createEmailVerificationToken(ctx.context.secret, createdUser.email, void 0, ctx.context.options.emailVerification?.expiresIn); - const callbackURL = body.callbackURL ? encodeURIComponent(body.callbackURL) : encodeURIComponent("/"); - const url2 = `${ctx.context.baseURL}/verify-email?token=${token}&callbackURL=${callbackURL}`; - if (ctx.context.options.emailVerification?.sendVerificationEmail) await ctx.context.runInBackgroundOrAwait(ctx.context.options.emailVerification.sendVerificationEmail({ - user: createdUser, - url: url2, - token - }, ctx.request)); - } - if (ctx.context.options.emailAndPassword.autoSignIn === false || ctx.context.options.emailAndPassword.requireEmailVerification) return ctx.json({ - token: null, - user: parseUserOutput(ctx.context.options, createdUser) - }); - const session = await ctx.context.internalAdapter.createSession(createdUser.id, rememberMe === false); - if (!session) throw new APIError("BAD_REQUEST", { message: BASE_ERROR_CODES.FAILED_TO_CREATE_SESSION }); - await setSessionCookie(ctx, { - session, - user: createdUser - }, rememberMe === false); - return ctx.json({ - token: session.token, - user: parseUserOutput(ctx.context.options, createdUser) - }); - }); - }); - } -}); - -// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/api/routes/update-user.mjs -var updateUserBodySchema, updateUser, changePassword, setPassword, deleteUser, deleteUserCallback, changeEmail; -var init_update_user = __esm({ - "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/api/routes/update-user.mjs"() { - init_schema4(); - init_origin_check(); - init_middlewares(); - init_random2(); - init_crypto(); - init_cookies2(); - init_session4(); - init_email_verification(); - init_error(); - init_dist3(); - init_zod(); - init_api2(); - updateUserBodySchema = record(string2().meta({ description: "Field name must be a string" }), any()); - updateUser = () => createAuthEndpoint("/update-user", { - method: "POST", - operationId: "updateUser", - body: updateUserBodySchema, - use: [sessionMiddleware], - metadata: { - $Infer: { body: {} }, - openapi: { - operationId: "updateUser", - description: "Update the current user", - requestBody: { content: { "application/json": { schema: { - type: "object", - properties: { - name: { - type: "string", - description: "The name of the user" - }, - image: { - type: "string", - description: "The image of the user", - nullable: true - } - } - } } } }, - responses: { "200": { - description: "Success", - content: { "application/json": { schema: { - type: "object", - properties: { user: { - type: "object", - $ref: "#/components/schemas/User" - } } - } } } - } } - } - } - }, async (ctx) => { - const body = ctx.body; - if (typeof body !== "object" || Array.isArray(body)) throw new APIError("BAD_REQUEST", { message: "Body must be an object" }); - if (body.email) throw new APIError("BAD_REQUEST", { message: BASE_ERROR_CODES.EMAIL_CAN_NOT_BE_UPDATED }); - const { name, image, ...rest } = body; - const session = ctx.context.session; - const additionalFields = parseUserInput(ctx.context.options, rest, "update"); - if (image === void 0 && name === void 0 && Object.keys(additionalFields).length === 0) throw new APIError("BAD_REQUEST", { message: "No fields to update" }); - const updatedUser = await ctx.context.internalAdapter.updateUser(session.user.id, { - name, - image, - ...additionalFields - }) ?? { - ...session.user, - ...name !== void 0 && { name }, - ...image !== void 0 && { image }, - ...additionalFields - }; - await setSessionCookie(ctx, { - session: session.session, - user: updatedUser - }); - return ctx.json({ status: true }); - }); - changePassword = createAuthEndpoint("/change-password", { - method: "POST", - operationId: "changePassword", - body: object({ - newPassword: string2().meta({ description: "The new password to set" }), - currentPassword: string2().meta({ description: "The current password is required" }), - revokeOtherSessions: boolean3().meta({ description: "Must be a boolean value" }).optional() - }), - use: [sensitiveSessionMiddleware], - metadata: { openapi: { - operationId: "changePassword", - description: "Change the password of the user", - responses: { "200": { - description: "Password successfully changed", - content: { "application/json": { schema: { - type: "object", - properties: { - token: { - type: "string", - nullable: true, - description: "New session token if other sessions were revoked" - }, - user: { - type: "object", - properties: { - id: { - type: "string", - description: "The unique identifier of the user" - }, - email: { - type: "string", - format: "email", - description: "The email address of the user" - }, - name: { - type: "string", - description: "The name of the user" - }, - image: { - type: "string", - format: "uri", - nullable: true, - description: "The profile image URL of the user" - }, - emailVerified: { - type: "boolean", - description: "Whether the email has been verified" - }, - createdAt: { - type: "string", - format: "date-time", - description: "When the user was created" - }, - updatedAt: { - type: "string", - format: "date-time", - description: "When the user was last updated" - } - }, - required: [ - "id", - "email", - "name", - "emailVerified", - "createdAt", - "updatedAt" - ] - } - }, - required: ["user"] - } } } - } } - } } - }, async (ctx) => { - const { newPassword, currentPassword, revokeOtherSessions: revokeOtherSessions2 } = ctx.body; - const session = ctx.context.session; - const minPasswordLength = ctx.context.password.config.minPasswordLength; - if (newPassword.length < minPasswordLength) { - ctx.context.logger.error("Password is too short"); - throw new APIError("BAD_REQUEST", { message: BASE_ERROR_CODES.PASSWORD_TOO_SHORT }); - } - const maxPasswordLength = ctx.context.password.config.maxPasswordLength; - if (newPassword.length > maxPasswordLength) { - ctx.context.logger.error("Password is too long"); - throw new APIError("BAD_REQUEST", { message: BASE_ERROR_CODES.PASSWORD_TOO_LONG }); - } - const account = (await ctx.context.internalAdapter.findAccounts(session.user.id)).find((account$1) => account$1.providerId === "credential" && account$1.password); - if (!account || !account.password) throw new APIError("BAD_REQUEST", { message: BASE_ERROR_CODES.CREDENTIAL_ACCOUNT_NOT_FOUND }); - const passwordHash = await ctx.context.password.hash(newPassword); - if (!await ctx.context.password.verify({ - hash: account.password, - password: currentPassword - })) throw new APIError("BAD_REQUEST", { message: BASE_ERROR_CODES.INVALID_PASSWORD }); - await ctx.context.internalAdapter.updateAccount(account.id, { password: passwordHash }); - let token = null; - if (revokeOtherSessions2) { - await ctx.context.internalAdapter.deleteSessions(session.user.id); - const newSession = await ctx.context.internalAdapter.createSession(session.user.id); - if (!newSession) throw new APIError("INTERNAL_SERVER_ERROR", { message: BASE_ERROR_CODES.FAILED_TO_GET_SESSION }); - await setSessionCookie(ctx, { - session: newSession, - user: session.user - }); - token = newSession.token; - } - return ctx.json({ - token, - user: parseUserOutput(ctx.context.options, session.user) - }); - }); - setPassword = createAuthEndpoint({ - method: "POST", - body: object({ newPassword: string2().meta({ description: "The new password to set is required" }) }), - use: [sensitiveSessionMiddleware] - }, async (ctx) => { - const { newPassword } = ctx.body; - const session = ctx.context.session; - const minPasswordLength = ctx.context.password.config.minPasswordLength; - if (newPassword.length < minPasswordLength) { - ctx.context.logger.error("Password is too short"); - throw new APIError("BAD_REQUEST", { message: BASE_ERROR_CODES.PASSWORD_TOO_SHORT }); - } - const maxPasswordLength = ctx.context.password.config.maxPasswordLength; - if (newPassword.length > maxPasswordLength) { - ctx.context.logger.error("Password is too long"); - throw new APIError("BAD_REQUEST", { message: BASE_ERROR_CODES.PASSWORD_TOO_LONG }); - } - const account = (await ctx.context.internalAdapter.findAccounts(session.user.id)).find((account$1) => account$1.providerId === "credential" && account$1.password); - const passwordHash = await ctx.context.password.hash(newPassword); - if (!account) { - await ctx.context.internalAdapter.linkAccount({ - userId: session.user.id, - providerId: "credential", - accountId: session.user.id, - password: passwordHash - }); - return ctx.json({ status: true }); - } - throw new APIError("BAD_REQUEST", { message: "user already has a password" }); - }); - deleteUser = createAuthEndpoint("/delete-user", { - method: "POST", - use: [sensitiveSessionMiddleware], - body: object({ - callbackURL: string2().meta({ description: "The callback URL to redirect to after the user is deleted" }).optional(), - password: string2().meta({ description: "The password of the user is required to delete the user" }).optional(), - token: string2().meta({ description: "The token to delete the user is required" }).optional() - }), - metadata: { openapi: { - operationId: "deleteUser", - description: "Delete the user", - requestBody: { content: { "application/json": { schema: { - type: "object", - properties: { - callbackURL: { - type: "string", - description: "The callback URL to redirect to after the user is deleted" - }, - password: { - type: "string", - description: "The user's password. Required if session is not fresh" - }, - token: { - type: "string", - description: "The deletion verification token" - } - } - } } } }, - responses: { "200": { - description: "User deletion processed successfully", - content: { "application/json": { schema: { - type: "object", - properties: { - success: { - type: "boolean", - description: "Indicates if the operation was successful" - }, - message: { - type: "string", - enum: ["User deleted", "Verification email sent"], - description: "Status message of the deletion process" - } - }, - required: ["success", "message"] - } } } - } } - } } - }, async (ctx) => { - if (!ctx.context.options.user?.deleteUser?.enabled) { - ctx.context.logger.error("Delete user is disabled. Enable it in the options"); - throw new APIError("NOT_FOUND"); - } - const session = ctx.context.session; - if (ctx.body.password) { - const account = (await ctx.context.internalAdapter.findAccounts(session.user.id)).find((account$1) => account$1.providerId === "credential" && account$1.password); - if (!account || !account.password) throw new APIError("BAD_REQUEST", { message: BASE_ERROR_CODES.CREDENTIAL_ACCOUNT_NOT_FOUND }); - if (!await ctx.context.password.verify({ - hash: account.password, - password: ctx.body.password - })) throw new APIError("BAD_REQUEST", { message: BASE_ERROR_CODES.INVALID_PASSWORD }); - } - if (ctx.body.token) { - await deleteUserCallback({ - ...ctx, - query: { token: ctx.body.token } - }); - return ctx.json({ - success: true, - message: "User deleted" - }); - } - if (ctx.context.options.user.deleteUser?.sendDeleteAccountVerification) { - const token = generateRandomString(32, "0-9", "a-z"); - await ctx.context.internalAdapter.createVerificationValue({ - value: session.user.id, - identifier: `delete-account-${token}`, - expiresAt: new Date(Date.now() + (ctx.context.options.user.deleteUser?.deleteTokenExpiresIn || 3600 * 24) * 1e3) - }); - const url2 = `${ctx.context.baseURL}/delete-user/callback?token=${token}&callbackURL=${ctx.body.callbackURL || "/"}`; - await ctx.context.runInBackgroundOrAwait(ctx.context.options.user.deleteUser.sendDeleteAccountVerification({ - user: session.user, - url: url2, - token - }, ctx.request)); - return ctx.json({ - success: true, - message: "Verification email sent" - }); - } - if (!ctx.body.password && ctx.context.sessionConfig.freshAge !== 0) { - const currentAge = new Date(session.session.createdAt).getTime(); - const freshAge = ctx.context.sessionConfig.freshAge * 1e3; - if (Date.now() - currentAge > freshAge * 1e3) throw new APIError("BAD_REQUEST", { message: BASE_ERROR_CODES.SESSION_EXPIRED }); - } - const beforeDelete = ctx.context.options.user.deleteUser?.beforeDelete; - if (beforeDelete) await beforeDelete(session.user, ctx.request); - await ctx.context.internalAdapter.deleteUser(session.user.id); - await ctx.context.internalAdapter.deleteSessions(session.user.id); - deleteSessionCookie(ctx); - const afterDelete = ctx.context.options.user.deleteUser?.afterDelete; - if (afterDelete) await afterDelete(session.user, ctx.request); - return ctx.json({ - success: true, - message: "User deleted" - }); - }); - deleteUserCallback = createAuthEndpoint("/delete-user/callback", { - method: "GET", - query: object({ - token: string2().meta({ description: "The token to verify the deletion request" }), - callbackURL: string2().meta({ description: "The URL to redirect to after deletion" }).optional() - }), - use: [originCheck((ctx) => ctx.query.callbackURL)], - metadata: { openapi: { - description: "Callback to complete user deletion with verification token", - responses: { "200": { - description: "User successfully deleted", - content: { "application/json": { schema: { - type: "object", - properties: { - success: { - type: "boolean", - description: "Indicates if the deletion was successful" - }, - message: { - type: "string", - enum: ["User deleted"], - description: "Confirmation message" - } - }, - required: ["success", "message"] - } } } - } } - } } - }, async (ctx) => { - if (!ctx.context.options.user?.deleteUser?.enabled) { - ctx.context.logger.error("Delete user is disabled. Enable it in the options"); - throw new APIError("NOT_FOUND"); - } - const session = await getSessionFromCtx(ctx); - if (!session) throw new APIError("NOT_FOUND", { message: BASE_ERROR_CODES.FAILED_TO_GET_USER_INFO }); - const token = await ctx.context.internalAdapter.findVerificationValue(`delete-account-${ctx.query.token}`); - if (!token || token.expiresAt < /* @__PURE__ */ new Date()) throw new APIError("NOT_FOUND", { message: BASE_ERROR_CODES.INVALID_TOKEN }); - if (token.value !== session.user.id) throw new APIError("NOT_FOUND", { message: BASE_ERROR_CODES.INVALID_TOKEN }); - const beforeDelete = ctx.context.options.user.deleteUser?.beforeDelete; - if (beforeDelete) await beforeDelete(session.user, ctx.request); - await ctx.context.internalAdapter.deleteUser(session.user.id); - await ctx.context.internalAdapter.deleteSessions(session.user.id); - await ctx.context.internalAdapter.deleteAccounts(session.user.id); - await ctx.context.internalAdapter.deleteVerificationValue(token.id); - deleteSessionCookie(ctx); - const afterDelete = ctx.context.options.user.deleteUser?.afterDelete; - if (afterDelete) await afterDelete(session.user, ctx.request); - if (ctx.query.callbackURL) throw ctx.redirect(ctx.query.callbackURL || "/"); - return ctx.json({ - success: true, - message: "User deleted" - }); - }); - changeEmail = createAuthEndpoint("/change-email", { - method: "POST", - body: object({ - newEmail: email2().meta({ description: "The new email address to set must be a valid email address" }), - callbackURL: string2().meta({ description: "The URL to redirect to after email verification" }).optional() - }), - use: [sensitiveSessionMiddleware], - metadata: { openapi: { - operationId: "changeEmail", - responses: { - "200": { - description: "Email change request processed successfully", - content: { "application/json": { schema: { - type: "object", - properties: { - user: { - type: "object", - $ref: "#/components/schemas/User" - }, - status: { - type: "boolean", - description: "Indicates if the request was successful" - }, - message: { - type: "string", - enum: ["Email updated", "Verification email sent"], - description: "Status message of the email change process", - nullable: true - } - }, - required: ["status"] - } } } - }, - "422": { - description: "Unprocessable Entity. Email already exists", - content: { "application/json": { schema: { - type: "object", - properties: { message: { type: "string" } } - } } } - } - } - } } - }, async (ctx) => { - if (!ctx.context.options.user?.changeEmail?.enabled) { - ctx.context.logger.error("Change email is disabled."); - throw new APIError("BAD_REQUEST", { message: "Change email is disabled" }); - } - const newEmail = ctx.body.newEmail.toLowerCase(); - if (newEmail === ctx.context.session.user.email) { - ctx.context.logger.error("Email is the same"); - throw new APIError("BAD_REQUEST", { message: "Email is the same" }); - } - if (await ctx.context.internalAdapter.findUserByEmail(newEmail)) { - ctx.context.logger.error("Email already exists"); - throw new APIError("UNPROCESSABLE_ENTITY", { message: BASE_ERROR_CODES.USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL }); - } - if (ctx.context.session.user.emailVerified !== true && ctx.context.options.user.changeEmail.updateEmailWithoutVerification) { - await ctx.context.internalAdapter.updateUserByEmail(ctx.context.session.user.email, { email: newEmail }); - await setSessionCookie(ctx, { - session: ctx.context.session.session, - user: { - ...ctx.context.session.user, - email: newEmail - } - }); - if (ctx.context.options.emailVerification?.sendVerificationEmail) { - const token$1 = await createEmailVerificationToken(ctx.context.secret, newEmail, void 0, ctx.context.options.emailVerification?.expiresIn); - const url$1 = `${ctx.context.baseURL}/verify-email?token=${token$1}&callbackURL=${ctx.body.callbackURL || "/"}`; - await ctx.context.runInBackgroundOrAwait(ctx.context.options.emailVerification.sendVerificationEmail({ - user: { - ...ctx.context.session.user, - email: newEmail - }, - url: url$1, - token: token$1 - }, ctx.request)); - } - return ctx.json({ status: true }); - } - if (ctx.context.session.user.emailVerified && (ctx.context.options.user.changeEmail.sendChangeEmailConfirmation || ctx.context.options.user.changeEmail.sendChangeEmailVerification)) { - const token$1 = await createEmailVerificationToken(ctx.context.secret, ctx.context.session.user.email, newEmail, ctx.context.options.emailVerification?.expiresIn, { requestType: "change-email-confirmation" }); - const url$1 = `${ctx.context.baseURL}/verify-email?token=${token$1}&callbackURL=${ctx.body.callbackURL || "/"}`; - const sendFn = ctx.context.options.user.changeEmail.sendChangeEmailConfirmation || ctx.context.options.user.changeEmail.sendChangeEmailVerification; - if (sendFn) await ctx.context.runInBackgroundOrAwait(sendFn({ - user: ctx.context.session.user, - newEmail, - url: url$1, - token: token$1 - }, ctx.request)); - return ctx.json({ status: true }); - } - if (!ctx.context.options.emailVerification?.sendVerificationEmail) { - ctx.context.logger.error("Verification email isn't enabled."); - throw new APIError("BAD_REQUEST", { message: "Verification email isn't enabled" }); - } - const token = await createEmailVerificationToken(ctx.context.secret, ctx.context.session.user.email, newEmail, ctx.context.options.emailVerification?.expiresIn, { requestType: "change-email-verification" }); - const url2 = `${ctx.context.baseURL}/verify-email?token=${token}&callbackURL=${ctx.body.callbackURL || "/"}`; - await ctx.context.runInBackgroundOrAwait(ctx.context.options.emailVerification.sendVerificationEmail({ - user: { - ...ctx.context.session.user, - email: newEmail - }, - url: url2, - token - }, ctx.request)); - return ctx.json({ status: true }); - }); - } -}); - -// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/api/routes/index.mjs -var init_routes = __esm({ - "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/api/routes/index.mjs"() { - init_session4(); - init_account2(); - init_callback(); - init_email_verification(); - init_error3(); - init_ok(); - init_password3(); - init_sign_in(); - init_sign_out(); - init_sign_up(); - init_update_user(); - } -}); - -// node_modules/.pnpm/defu@6.1.7/node_modules/defu/dist/defu.mjs -function isPlainObject6(value) { - if (value === null || typeof value !== "object") { - return false; - } - const prototype = Object.getPrototypeOf(value); - if (prototype !== null && prototype !== Object.prototype && Object.getPrototypeOf(prototype) !== null) { - return false; - } - if (Symbol.iterator in value) { - return false; - } - if (Symbol.toStringTag in value) { - return Object.prototype.toString.call(value) === "[object Module]"; - } - return true; -} -function _defu(baseObject, defaults, namespace = ".", merger) { - if (!isPlainObject6(defaults)) { - return _defu(baseObject, {}, namespace, merger); - } - const object2 = { ...defaults }; - for (const key of Object.keys(baseObject)) { - if (key === "__proto__" || key === "constructor") { - continue; - } - const value = baseObject[key]; - if (value === null || value === void 0) { - continue; - } - if (merger && merger(object2, key, value, namespace)) { - continue; - } - if (Array.isArray(value) && Array.isArray(object2[key])) { - object2[key] = [...value, ...object2[key]]; - } else if (isPlainObject6(value) && isPlainObject6(object2[key])) { - object2[key] = _defu( - value, - object2[key], - (namespace ? `${namespace}.` : "") + key.toString(), - merger - ); - } else { - object2[key] = value; - } - } - return object2; -} -function createDefu(merger) { - return (...arguments_) => ( - // eslint-disable-next-line unicorn/no-array-reduce - arguments_.reduce((p5, c5) => _defu(p5, c5, "", merger), {}) - ); -} -var defu, defuFn, defuArrayFn; -var init_defu = __esm({ - "node_modules/.pnpm/defu@6.1.7/node_modules/defu/dist/defu.mjs"() { - defu = createDefu(); - defuFn = createDefu((object2, key, currentValue) => { - if (object2[key] !== void 0 && typeof currentValue === "function") { - object2[key] = currentValue(object2[key]); - return true; - } - }); - defuArrayFn = createDefu((object2, key, currentValue) => { - if (Array.isArray(object2[key]) && typeof currentValue === "function") { - object2[key] = currentValue(object2[key]); - return true; - } - }); - } -}); - -// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/api/to-auth-endpoints.mjs -function toAuthEndpoints(endpoints, ctx) { - const api = {}; - for (const [key, endpoint] of Object.entries(endpoints)) { - api[key] = async (context) => { - const run = async () => { - const authContext = await ctx; - let internalContext = { - ...context, - context: { - ...authContext, - returned: void 0, - responseHeaders: void 0, - session: null - }, - path: endpoint.path, - headers: context?.headers ? new Headers(context?.headers) : void 0 - }; - return runWithEndpointContext(internalContext, async () => { - const { beforeHooks, afterHooks } = getHooks(authContext); - const before = await runBeforeHooks(internalContext, beforeHooks); - if ("context" in before && before.context && typeof before.context === "object") { - const { headers, ...rest } = before.context; - if (headers) headers.forEach((value, key$1) => { - internalContext.headers.set(key$1, value); - }); - internalContext = defuReplaceArrays(rest, internalContext); - } else if (before) return context?.asResponse ? toResponse(before, { headers: context?.headers }) : context?.returnHeaders ? { - headers: context?.headers, - response: before - } : before; - internalContext.asResponse = false; - internalContext.returnHeaders = true; - internalContext.returnStatus = true; - const result = await runWithEndpointContext(internalContext, () => endpoint(internalContext)).catch((e5) => { - if (e5 instanceof APIError) - return { - response: e5, - status: e5.statusCode, - headers: e5.headers ? new Headers(e5.headers) : null - }; - throw e5; - }); - if (result && result instanceof Response) return result; - internalContext.context.returned = result.response; - internalContext.context.responseHeaders = result.headers; - const after = await runAfterHooks(internalContext, afterHooks); - if (after.response) result.response = after.response; - if (result.response instanceof APIError && shouldPublishLog(authContext.logger.level, "debug")) result.response.stack = result.response.errorStack; - if (result.response instanceof APIError && !context?.asResponse) throw result.response; - return context?.asResponse ? toResponse(result.response, { - headers: result.headers, - status: result.status - }) : context?.returnHeaders ? context?.returnStatus ? { - headers: result.headers, - response: result.response, - status: result.status - } : { - headers: result.headers, - response: result.response - } : context?.returnStatus ? { - response: result.response, - status: result.status - } : result.response; - }); - }; - if (await hasRequestState()) return run(); - else return runWithRequestState(/* @__PURE__ */ new WeakMap(), run); - }; - api[key].path = endpoint.path; - api[key].options = endpoint.options; - } - return api; -} -async function runBeforeHooks(context, hooks) { - let modifiedContext = {}; - for (const hook of hooks) { - let matched = false; - try { - matched = hook.matcher(context); - } catch (error50) { - const hookSource = hooksSourceWeakMap.get(hook.handler) ?? "unknown"; - context.context.logger.error(`An error occurred during ${hookSource} hook matcher execution:`, error50); - throw new APIError("INTERNAL_SERVER_ERROR", { message: `An error occurred during hook matcher execution. Check the logs for more details.` }); - } - if (matched) { - const result = await hook.handler({ - ...context, - returnHeaders: false - }).catch((e5) => { - if (e5 instanceof APIError && shouldPublishLog(context.context.logger.level, "debug")) e5.stack = e5.errorStack; - throw e5; - }); - if (result && typeof result === "object") { - if ("context" in result && typeof result.context === "object") { - const { headers, ...rest } = result.context; - if (headers instanceof Headers) if (modifiedContext.headers) headers.forEach((value, key) => { - modifiedContext.headers?.set(key, value); - }); - else modifiedContext.headers = headers; - modifiedContext = defuReplaceArrays(rest, modifiedContext); - continue; - } - return result; - } - } - } - return { context: modifiedContext }; -} -async function runAfterHooks(context, hooks) { - for (const hook of hooks) if (hook.matcher(context)) { - const result = await hook.handler(context).catch((e5) => { - if (e5 instanceof APIError) { - if (shouldPublishLog(context.context.logger.level, "debug")) e5.stack = e5.errorStack; - return { - response: e5, - headers: e5.headers ? new Headers(e5.headers) : null - }; - } - throw e5; - }); - if (result.headers) result.headers.forEach((value, key) => { - if (!context.context.responseHeaders) context.context.responseHeaders = new Headers({ [key]: value }); - else if (key.toLowerCase() === "set-cookie") context.context.responseHeaders.append(key, value); - else context.context.responseHeaders.set(key, value); - }); - if (result.response) context.context.returned = result.response; - } - return { - response: context.context.returned, - headers: context.context.responseHeaders - }; -} -function getHooks(authContext) { - const plugins2 = authContext.options.plugins || []; - const beforeHooks = []; - const afterHooks = []; - const beforeHookHandler = authContext.options.hooks?.before; - if (beforeHookHandler) { - hooksSourceWeakMap.set(beforeHookHandler, "user"); - beforeHooks.push({ - matcher: () => true, - handler: beforeHookHandler - }); - } - const afterHookHandler = authContext.options.hooks?.after; - if (afterHookHandler) { - hooksSourceWeakMap.set(afterHookHandler, "user"); - afterHooks.push({ - matcher: () => true, - handler: afterHookHandler - }); - } - const pluginBeforeHooks = plugins2.filter((plugin) => plugin.hooks?.before).map((plugin) => plugin.hooks?.before).flat(); - const pluginAfterHooks = plugins2.filter((plugin) => plugin.hooks?.after).map((plugin) => plugin.hooks?.after).flat(); - if (pluginBeforeHooks.length) beforeHooks.push(...pluginBeforeHooks); - if (pluginAfterHooks.length) afterHooks.push(...pluginAfterHooks); - return { - beforeHooks, - afterHooks - }; -} -var defuReplaceArrays, hooksSourceWeakMap; -var init_to_auth_endpoints = __esm({ - "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/api/to-auth-endpoints.mjs"() { - init_context2(); - init_env(); - init_dist3(); - init_defu(); - defuReplaceArrays = createDefu((obj, key, value) => { - if (Array.isArray(obj[key]) && Array.isArray(value)) { - obj[key] = value; - return true; - } - }); - hooksSourceWeakMap = /* @__PURE__ */ new WeakMap(); - } -}); - -// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/api/index.mjs -function checkEndpointConflicts(options, logger$1) { - const endpointRegistry = /* @__PURE__ */ new Map(); - options.plugins?.forEach((plugin) => { - if (plugin.endpoints) { - for (const [key, endpoint] of Object.entries(plugin.endpoints)) if (endpoint && "path" in endpoint && typeof endpoint.path === "string") { - const path53 = endpoint.path; - let methods2 = []; - if (endpoint.options && "method" in endpoint.options) { - if (Array.isArray(endpoint.options.method)) methods2 = endpoint.options.method; - else if (typeof endpoint.options.method === "string") methods2 = [endpoint.options.method]; - } - if (methods2.length === 0) methods2 = ["*"]; - if (!endpointRegistry.has(path53)) endpointRegistry.set(path53, []); - endpointRegistry.get(path53).push({ - pluginId: plugin.id, - endpointKey: key, - methods: methods2 - }); - } - } - }); - const conflicts = []; - for (const [path53, entries2] of endpointRegistry.entries()) if (entries2.length > 1) { - const methodMap = /* @__PURE__ */ new Map(); - let hasConflict = false; - for (const entry of entries2) for (const method of entry.methods) { - if (!methodMap.has(method)) methodMap.set(method, []); - methodMap.get(method).push(entry.pluginId); - if (methodMap.get(method).length > 1) hasConflict = true; - if (method === "*" && entries2.length > 1) hasConflict = true; - else if (method !== "*" && methodMap.has("*")) hasConflict = true; - } - if (hasConflict) { - const uniquePlugins = [...new Set(entries2.map((e5) => e5.pluginId))]; - const conflictingMethods = []; - for (const [method, plugins2] of methodMap.entries()) if (plugins2.length > 1 || method === "*" && entries2.length > 1 || method !== "*" && methodMap.has("*")) conflictingMethods.push(method); - conflicts.push({ - path: path53, - plugins: uniquePlugins, - conflictingMethods - }); - } - } - if (conflicts.length > 0) { - const conflictMessages = conflicts.map((conflict2) => ` - "${conflict2.path}" [${conflict2.conflictingMethods.join(", ")}] used by plugins: ${conflict2.plugins.join(", ")}`).join("\n"); - logger$1.error(`Endpoint path conflicts detected! Multiple plugins are trying to use the same endpoint paths with conflicting HTTP methods: -${conflictMessages} - -To resolve this, you can: - 1. Use only one of the conflicting plugins - 2. Configure the plugins to use different paths (if supported) - 3. Ensure plugins use different HTTP methods for the same path -`); - } -} -function getEndpoints(ctx, options) { - const pluginEndpoints = options.plugins?.reduce((acc, plugin) => { - return { - ...acc, - ...plugin.endpoints - }; - }, {}) ?? {}; - const middlewares = options.plugins?.map((plugin) => plugin.middlewares?.map((m5) => { - const middleware = (async (context) => { - const authContext = await ctx; - return m5.middleware({ - ...context, - context: { - ...authContext, - ...context.context - } - }); - }); - middleware.options = m5.middleware.options; - return { - path: m5.path, - middleware - }; - })).filter((plugin) => plugin !== void 0).flat() || []; - return { - api: toAuthEndpoints({ - signInSocial: signInSocial(), - callbackOAuth, - getSession: getSession(), - signOut, - signUpEmail: signUpEmail(), - signInEmail: signInEmail(), - resetPassword, - verifyPassword: verifyPassword2, - verifyEmail, - sendVerificationEmail, - changeEmail, - changePassword, - setPassword, - updateUser: updateUser(), - deleteUser, - requestPasswordReset, - requestPasswordResetCallback, - listSessions: listSessions(), - revokeSession, - revokeSessions, - revokeOtherSessions, - linkSocialAccount, - listUserAccounts, - deleteUserCallback, - unlinkAccount, - refreshToken, - getAccessToken, - accountInfo, - ...pluginEndpoints, - ok, - error: error49 - }, ctx), - middlewares - }; -} -var router; -var init_api3 = __esm({ - "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/api/index.mjs"() { - init_get_request_ip(); - init_oauth(); - init_origin_check(); - init_middlewares(); - init_rate_limiter(); - init_session4(); - init_account2(); - init_callback(); - init_email_verification(); - init_error3(); - init_ok(); - init_password3(); - init_sign_in(); - init_sign_out(); - init_sign_up(); - init_update_user(); - init_routes(); - init_to_auth_endpoints(); - init_env(); - init_utils7(); - init_dist3(); - init_api2(); - router = (ctx, options) => { - const { api, middlewares } = getEndpoints(ctx, options); - const basePath = new URL(ctx.baseURL).pathname; - return createRouter$1(api, { - routerContext: ctx, - openapi: { disabled: true }, - basePath, - routerMiddleware: [{ - path: "/**", - middleware: originCheckMiddleware - }, ...middlewares], - allowedMediaTypes: ["application/json"], - skipTrailingSlashes: options.advanced?.skipTrailingSlashes ?? false, - async onRequest(req) { - const disabledPaths = ctx.options.disabledPaths || []; - const normalizedPath = normalizePathname(req.url, basePath); - if (disabledPaths.includes(normalizedPath)) return new Response("Not Found", { status: 404 }); - let currentRequest = req; - for (const plugin of ctx.options.plugins || []) if (plugin.onRequest) { - const response = await plugin.onRequest(currentRequest, ctx); - if (response && "response" in response) return response.response; - if (response && "request" in response) currentRequest = response.request; - } - const rateLimitResponse2 = await onRequestRateLimit(currentRequest, ctx); - if (rateLimitResponse2) return rateLimitResponse2; - return currentRequest; - }, - async onResponse(res) { - for (const plugin of ctx.options.plugins || []) if (plugin.onResponse) { - const response = await plugin.onResponse(res, ctx); - if (response) return response.response; - } - return res; - }, - onError(e5) { - if (e5 instanceof APIError && e5.status === "FOUND") return; - if (options.onAPIError?.throw) throw e5; - if (options.onAPIError?.onError) { - options.onAPIError.onError(e5, ctx); - return; - } - const optLogLevel = options.logger?.level; - const log2 = optLogLevel === "error" || optLogLevel === "warn" || optLogLevel === "debug" ? logger3 : void 0; - if (options.logger?.disabled !== true) { - if (e5 && typeof e5 === "object" && "message" in e5 && typeof e5.message === "string") { - if (e5.message.includes("no column") || e5.message.includes("column") || e5.message.includes("relation") || e5.message.includes("table") || e5.message.includes("does not exist")) { - ctx.logger?.error(e5.message); - return; - } - } - if (e5 instanceof APIError) { - if (e5.status === "INTERNAL_SERVER_ERROR") ctx.logger.error(e5.status, e5); - log2?.error(e5.message); - } else ctx.logger?.error(e5 && typeof e5 === "object" && "name" in e5 ? e5.name : "", e5); - } - } - }); - }; - } -}); - -// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/utils/constants.mjs -var DEFAULT_SECRET; -var init_constants = __esm({ - "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/utils/constants.mjs"() { - DEFAULT_SECRET = "better-auth-secret-12345678901234567890"; - } -}); - -// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/context/helpers.mjs -async function runPluginInit(ctx) { - let options = ctx.options; - const plugins2 = options.plugins || []; - let context = ctx; - const dbHooks = []; - for (const plugin of plugins2) if (plugin.init) { - const initPromise = plugin.init(context); - let result; - if (isPromise(initPromise)) result = await initPromise; - else result = initPromise; - if (typeof result === "object") { - if (result.options) { - const { databaseHooks, ...restOpts } = result.options; - if (databaseHooks) dbHooks.push(databaseHooks); - options = defu(options, restOpts); - } - if (result.context) context = { - ...context, - ...result.context - }; - } - } - dbHooks.push(options.databaseHooks); - context.internalAdapter = createInternalAdapter(context.adapter, { - options, - logger: context.logger, - hooks: dbHooks.filter((u5) => u5 !== void 0), - generateId: context.generateId - }); - context.options = options; - return { context }; -} -function getInternalPlugins(options) { - const plugins2 = []; - if (options.advanced?.crossSubDomainCookies?.enabled) { - } - return plugins2; -} -async function getTrustedOrigins(options, request) { - const baseURL = getBaseURL(options.baseURL, options.basePath, request); - const trustedOrigins = baseURL ? [new URL(baseURL).origin] : []; - if (options.trustedOrigins) { - if (Array.isArray(options.trustedOrigins)) trustedOrigins.push(...options.trustedOrigins); - if (typeof options.trustedOrigins === "function") { - const validOrigins = await options.trustedOrigins(request); - trustedOrigins.push(...validOrigins); - } - } - const envTrustedOrigins = env.BETTER_AUTH_TRUSTED_ORIGINS; - if (envTrustedOrigins) trustedOrigins.push(...envTrustedOrigins.split(",")); - return trustedOrigins.filter((v5) => Boolean(v5)); -} -var init_helpers2 = __esm({ - "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/context/helpers.mjs"() { - init_internal_adapter(); - init_url2(); - init_is_promise(); - init_env(); - init_defu(); - } -}); - -// node_modules/.pnpm/@better-auth+telemetry@1.4.18_@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch_psxvmkd33sibviw74qwagmhkji/node_modules/@better-auth/telemetry/dist/index.mjs -function getTelemetryAuthConfig(options, context) { - return { - database: context?.database, - adapter: context?.adapter, - emailVerification: { - sendVerificationEmail: !!options.emailVerification?.sendVerificationEmail, - sendOnSignUp: !!options.emailVerification?.sendOnSignUp, - sendOnSignIn: !!options.emailVerification?.sendOnSignIn, - autoSignInAfterVerification: !!options.emailVerification?.autoSignInAfterVerification, - expiresIn: options.emailVerification?.expiresIn, - onEmailVerification: !!options.emailVerification?.onEmailVerification, - afterEmailVerification: !!options.emailVerification?.afterEmailVerification - }, - emailAndPassword: { - enabled: !!options.emailAndPassword?.enabled, - disableSignUp: !!options.emailAndPassword?.disableSignUp, - requireEmailVerification: !!options.emailAndPassword?.requireEmailVerification, - maxPasswordLength: options.emailAndPassword?.maxPasswordLength, - minPasswordLength: options.emailAndPassword?.minPasswordLength, - sendResetPassword: !!options.emailAndPassword?.sendResetPassword, - resetPasswordTokenExpiresIn: options.emailAndPassword?.resetPasswordTokenExpiresIn, - onPasswordReset: !!options.emailAndPassword?.onPasswordReset, - password: { - hash: !!options.emailAndPassword?.password?.hash, - verify: !!options.emailAndPassword?.password?.verify - }, - autoSignIn: !!options.emailAndPassword?.autoSignIn, - revokeSessionsOnPasswordReset: !!options.emailAndPassword?.revokeSessionsOnPasswordReset - }, - socialProviders: Object.keys(options.socialProviders || {}).map((p5) => { - const provider = options.socialProviders?.[p5]; - if (!provider) return {}; - return { - id: p5, - mapProfileToUser: !!provider.mapProfileToUser, - disableDefaultScope: !!provider.disableDefaultScope, - disableIdTokenSignIn: !!provider.disableIdTokenSignIn, - disableImplicitSignUp: provider.disableImplicitSignUp, - disableSignUp: provider.disableSignUp, - getUserInfo: !!provider.getUserInfo, - overrideUserInfoOnSignIn: !!provider.overrideUserInfoOnSignIn, - prompt: provider.prompt, - verifyIdToken: !!provider.verifyIdToken, - scope: provider.scope, - refreshAccessToken: !!provider.refreshAccessToken - }; - }), - plugins: options.plugins?.map((p5) => p5.id.toString()), - user: { - modelName: options.user?.modelName, - fields: options.user?.fields, - additionalFields: options.user?.additionalFields, - changeEmail: { - enabled: options.user?.changeEmail?.enabled, - sendChangeEmailVerification: !!options.user?.changeEmail?.sendChangeEmailVerification - } - }, - verification: { - modelName: options.verification?.modelName, - disableCleanup: options.verification?.disableCleanup, - fields: options.verification?.fields - }, - session: { - modelName: options.session?.modelName, - additionalFields: options.session?.additionalFields, - cookieCache: { - enabled: options.session?.cookieCache?.enabled, - maxAge: options.session?.cookieCache?.maxAge, - strategy: options.session?.cookieCache?.strategy - }, - disableSessionRefresh: options.session?.disableSessionRefresh, - expiresIn: options.session?.expiresIn, - fields: options.session?.fields, - freshAge: options.session?.freshAge, - preserveSessionInDatabase: options.session?.preserveSessionInDatabase, - storeSessionInDatabase: options.session?.storeSessionInDatabase, - updateAge: options.session?.updateAge - }, - account: { - modelName: options.account?.modelName, - fields: options.account?.fields, - encryptOAuthTokens: options.account?.encryptOAuthTokens, - updateAccountOnSignIn: options.account?.updateAccountOnSignIn, - accountLinking: { - enabled: options.account?.accountLinking?.enabled, - trustedProviders: options.account?.accountLinking?.trustedProviders, - updateUserInfoOnLink: options.account?.accountLinking?.updateUserInfoOnLink, - allowUnlinkingAll: options.account?.accountLinking?.allowUnlinkingAll - } - }, - hooks: { - after: !!options.hooks?.after, - before: !!options.hooks?.before - }, - secondaryStorage: !!options.secondaryStorage, - advanced: { - cookiePrefix: !!options.advanced?.cookiePrefix, - cookies: !!options.advanced?.cookies, - crossSubDomainCookies: { - domain: !!options.advanced?.crossSubDomainCookies?.domain, - enabled: options.advanced?.crossSubDomainCookies?.enabled, - additionalCookies: options.advanced?.crossSubDomainCookies?.additionalCookies - }, - database: { - useNumberId: !!options.advanced?.database?.useNumberId || options.advanced?.database?.generateId === "serial", - generateId: options.advanced?.database?.generateId, - defaultFindManyLimit: options.advanced?.database?.defaultFindManyLimit - }, - useSecureCookies: options.advanced?.useSecureCookies, - ipAddress: { - disableIpTracking: options.advanced?.ipAddress?.disableIpTracking, - ipAddressHeaders: options.advanced?.ipAddress?.ipAddressHeaders - }, - disableCSRFCheck: options.advanced?.disableCSRFCheck, - cookieAttributes: { - expires: options.advanced?.defaultCookieAttributes?.expires, - secure: options.advanced?.defaultCookieAttributes?.secure, - sameSite: options.advanced?.defaultCookieAttributes?.sameSite, - domain: !!options.advanced?.defaultCookieAttributes?.domain, - path: options.advanced?.defaultCookieAttributes?.path, - httpOnly: options.advanced?.defaultCookieAttributes?.httpOnly - } - }, - trustedOrigins: options.trustedOrigins?.length, - rateLimit: { - storage: options.rateLimit?.storage, - modelName: options.rateLimit?.modelName, - window: options.rateLimit?.window, - customStorage: !!options.rateLimit?.customStorage, - enabled: options.rateLimit?.enabled, - max: options.rateLimit?.max - }, - onAPIError: { - errorURL: options.onAPIError?.errorURL, - onError: !!options.onAPIError?.onError, - throw: options.onAPIError?.throw - }, - logger: { - disabled: options.logger?.disabled, - level: options.logger?.level, - log: !!options.logger?.log - }, - databaseHooks: { - user: { - create: { - after: !!options.databaseHooks?.user?.create?.after, - before: !!options.databaseHooks?.user?.create?.before - }, - update: { - after: !!options.databaseHooks?.user?.update?.after, - before: !!options.databaseHooks?.user?.update?.before - } - }, - session: { - create: { - after: !!options.databaseHooks?.session?.create?.after, - before: !!options.databaseHooks?.session?.create?.before - }, - update: { - after: !!options.databaseHooks?.session?.update?.after, - before: !!options.databaseHooks?.session?.update?.before - } - }, - account: { - create: { - after: !!options.databaseHooks?.account?.create?.after, - before: !!options.databaseHooks?.account?.create?.before - }, - update: { - after: !!options.databaseHooks?.account?.update?.after, - before: !!options.databaseHooks?.account?.update?.before - } - }, - verification: { - create: { - after: !!options.databaseHooks?.verification?.create?.after, - before: !!options.databaseHooks?.verification?.create?.before - }, - update: { - after: !!options.databaseHooks?.verification?.update?.after, - before: !!options.databaseHooks?.verification?.update?.before - } - } - } - }; -} -async function readRootPackageJson() { - if (packageJSONCache) return packageJSONCache; - try { - const cwd = typeof process !== "undefined" && typeof process.cwd === "function" ? process.cwd() : ""; - if (!cwd) return void 0; - const importRuntime$1 = (m5) => Function("mm", "return import(mm)")(m5); - const [{ default: fs41 }, { default: path53 }] = await Promise.all([importRuntime$1("fs/promises"), importRuntime$1("path")]); - const raw = await fs41.readFile(path53.join(cwd, "package.json"), "utf-8"); - packageJSONCache = JSON.parse(raw); - return packageJSONCache; - } catch { - } -} -async function getPackageVersion(pkg2) { - if (packageJSONCache) return packageJSONCache.dependencies?.[pkg2] || packageJSONCache.devDependencies?.[pkg2] || packageJSONCache.peerDependencies?.[pkg2]; - try { - const cwd = typeof process !== "undefined" && typeof process.cwd === "function" ? process.cwd() : ""; - if (!cwd) throw new Error("no-cwd"); - const importRuntime$1 = (m5) => Function("mm", "return import(mm)")(m5); - const [{ default: fs41 }, { default: path53 }] = await Promise.all([importRuntime$1("fs/promises"), importRuntime$1("path")]); - const pkgJsonPath = path53.join(cwd, "node_modules", pkg2, "package.json"); - const raw = await fs41.readFile(pkgJsonPath, "utf-8"); - return JSON.parse(raw).version || await getVersionFromLocalPackageJson(pkg2) || void 0; - } catch { - } - return await getVersionFromLocalPackageJson(pkg2); -} -async function getVersionFromLocalPackageJson(pkg2) { - const json3 = await readRootPackageJson(); - if (!json3) return void 0; - return { - ...json3.dependencies, - ...json3.devDependencies, - ...json3.peerDependencies - }[pkg2]; -} -async function getNameFromLocalPackageJson() { - return (await readRootPackageJson())?.name; -} -async function detectDatabase() { - for (const [pkg2, name] of Object.entries(DATABASES)) { - const version3 = await getPackageVersion(pkg2); - if (version3) return { - name, - version: version3 - }; - } -} -async function detectFramework() { - for (const [pkg2, name] of Object.entries(FRAMEWORKS)) { - const version3 = await getPackageVersion(pkg2); - if (version3) return { - name, - version: version3 - }; - } -} -function detectPackageManager() { - const userAgent = env.npm_config_user_agent; - if (!userAgent) return; - const pmSpec = userAgent.split(" ")[0]; - const separatorPos = pmSpec.lastIndexOf("/"); - const name = pmSpec.substring(0, separatorPos); - return { - name: name === "npminstall" ? "cnpm" : name, - version: pmSpec.substring(separatorPos + 1) - }; -} -function getVendor() { - const hasAny = (...keys) => keys.some((k5) => Boolean(env[k5])); - if (hasAny("CF_PAGES", "CF_PAGES_URL", "CF_ACCOUNT_ID") || typeof navigator !== "undefined" && navigator.userAgent === "Cloudflare-Workers") return "cloudflare"; - if (hasAny("VERCEL", "VERCEL_URL", "VERCEL_ENV")) return "vercel"; - if (hasAny("NETLIFY", "NETLIFY_URL")) return "netlify"; - if (hasAny("RENDER", "RENDER_URL", "RENDER_INTERNAL_HOSTNAME", "RENDER_SERVICE_ID")) return "render"; - if (hasAny("AWS_LAMBDA_FUNCTION_NAME", "AWS_EXECUTION_ENV", "LAMBDA_TASK_ROOT")) return "aws"; - if (hasAny("GOOGLE_CLOUD_FUNCTION_NAME", "GOOGLE_CLOUD_PROJECT", "GCP_PROJECT", "K_SERVICE")) return "gcp"; - if (hasAny("AZURE_FUNCTION_NAME", "FUNCTIONS_WORKER_RUNTIME", "WEBSITE_INSTANCE_ID", "WEBSITE_SITE_NAME")) return "azure"; - if (hasAny("DENO_DEPLOYMENT_ID", "DENO_REGION")) return "deno-deploy"; - if (hasAny("FLY_APP_NAME", "FLY_REGION", "FLY_ALLOC_ID")) return "fly-io"; - if (hasAny("RAILWAY_STATIC_URL", "RAILWAY_ENVIRONMENT_NAME")) return "railway"; - if (hasAny("DYNO", "HEROKU_APP_NAME")) return "heroku"; - if (hasAny("DO_DEPLOYMENT_ID", "DO_APP_NAME", "DIGITALOCEAN")) return "digitalocean"; - if (hasAny("KOYEB", "KOYEB_DEPLOYMENT_ID", "KOYEB_APP_NAME")) return "koyeb"; - return null; -} -async function detectSystemInfo() { - try { - if (getVendor() === "cloudflare") return "cloudflare"; - const os24 = await importRuntime("os"); - const cpus = os24.cpus(); - return { - deploymentVendor: getVendor(), - systemPlatform: os24.platform(), - systemRelease: os24.release(), - systemArchitecture: os24.arch(), - cpuCount: cpus.length, - cpuModel: cpus.length ? cpus[0].model : null, - cpuSpeed: cpus.length ? cpus[0].speed : null, - memory: os24.totalmem(), - isWSL: await isWsl(), - isDocker: await isDocker(), - isTTY: typeof process !== "undefined" && process.stdout ? process.stdout.isTTY : null - }; - } catch { - return { - systemPlatform: null, - systemRelease: null, - systemArchitecture: null, - cpuCount: null, - cpuModel: null, - cpuSpeed: null, - memory: null, - isWSL: null, - isDocker: null, - isTTY: null - }; - } -} -async function hasDockerEnv() { - if (getVendor() === "cloudflare") return false; - try { - (await importRuntime("fs")).statSync("/.dockerenv"); - return true; - } catch { - return false; - } -} -async function hasDockerCGroup() { - if (getVendor() === "cloudflare") return false; - try { - return (await importRuntime("fs")).readFileSync("/proc/self/cgroup", "utf8").includes("docker"); - } catch { - return false; - } -} -async function isDocker() { - if (getVendor() === "cloudflare") return false; - if (isDockerCached === void 0) isDockerCached = await hasDockerEnv() || await hasDockerCGroup(); - return isDockerCached; -} -async function isWsl() { - try { - if (getVendor() === "cloudflare") return false; - if (typeof process === "undefined" || process?.platform !== "linux") return false; - const fs41 = await importRuntime("fs"); - if ((await importRuntime("os")).release().toLowerCase().includes("microsoft")) { - if (await isInsideContainer()) return false; - return true; - } - return fs41.readFileSync("/proc/version", "utf8").toLowerCase().includes("microsoft") ? !await isInsideContainer() : false; - } catch { - return false; - } -} -async function isInsideContainer() { - if (isInsideContainerCached === void 0) isInsideContainerCached = await hasContainerEnv() || await isDocker(); - return isInsideContainerCached; -} -function isCI() { - return env.CI !== "false" && ("BUILD_ID" in env || "BUILD_NUMBER" in env || "CI" in env || "CI_APP_ID" in env || "CI_BUILD_ID" in env || "CI_BUILD_NUMBER" in env || "CI_NAME" in env || "CONTINUOUS_INTEGRATION" in env || "RUN_ID" in env); -} -function detectRuntime() { - if (typeof Deno !== "undefined") return { - name: "deno", - version: Deno?.version?.deno ?? null - }; - if (typeof Bun !== "undefined") return { - name: "bun", - version: Bun?.version ?? null - }; - if (typeof process !== "undefined" && process?.versions?.node) return { - name: "node", - version: process.versions.node ?? null - }; - return { - name: "edge", - version: null - }; -} -function detectEnvironment() { - return getEnvVar("NODE_ENV") === "production" ? "production" : isCI() ? "ci" : isTest() ? "test" : "development"; -} -async function hashToBase64(data2) { - const buffer2 = await createHash17("SHA-256").digest(data2); - return base643.encode(buffer2); -} -async function getProjectId(baseUrl) { - if (projectIdCached) return projectIdCached; - const projectName = await getNameFromLocalPackageJson(); - if (projectName) { - projectIdCached = await hashToBase64(baseUrl ? baseUrl + projectName : projectName); - return projectIdCached; - } - if (baseUrl) { - projectIdCached = await hashToBase64(baseUrl); - return projectIdCached; - } - projectIdCached = generateId2(32); - return projectIdCached; -} -async function createTelemetry(options, context) { - const debugEnabled = options.telemetry?.debug || getBooleanEnvVar("BETTER_AUTH_TELEMETRY_DEBUG", false); - const telemetryEndpoint = ENV.BETTER_AUTH_TELEMETRY_ENDPOINT; - if (!telemetryEndpoint && !context?.customTrack) return { publish: noop4 }; - const track = async (event) => { - if (context?.customTrack) await context.customTrack(event).catch(logger3.error); - else if (telemetryEndpoint) if (debugEnabled) logger3.info("telemetry event", JSON.stringify(event, null, 2)); - else await betterFetch(telemetryEndpoint, { - method: "POST", - body: event - }).catch(logger3.error); - }; - const isEnabled = async () => { - const telemetryEnabled = options.telemetry?.enabled !== void 0 ? options.telemetry.enabled : false; - return (getBooleanEnvVar("BETTER_AUTH_TELEMETRY", false) || telemetryEnabled) && (context?.skipTestCheck || !isTest()); - }; - const enabled = await isEnabled(); - let anonymousId; - if (enabled) { - anonymousId = await getProjectId(options.baseURL); - track({ - type: "init", - payload: { - config: getTelemetryAuthConfig(options, context), - runtime: detectRuntime(), - database: await detectDatabase(), - framework: await detectFramework(), - environment: detectEnvironment(), - systemInfo: await detectSystemInfo(), - packageManager: detectPackageManager() - }, - anonymousId - }); - } - return { publish: async (event) => { - if (!enabled) return; - if (!anonymousId) anonymousId = await getProjectId(options.baseURL); - await track({ - type: event.type, - payload: event.payload, - anonymousId - }); - } }; -} -var packageJSONCache, DATABASES, FRAMEWORKS, importRuntime, isDockerCached, isInsideContainerCached, hasContainerEnv, generateId2, projectIdCached, noop4; -var init_dist5 = __esm({ - "node_modules/.pnpm/@better-auth+telemetry@1.4.18_@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch_psxvmkd33sibviw74qwagmhkji/node_modules/@better-auth/telemetry/dist/index.mjs"() { - init_env(); - init_dist4(); - init_base642(); - init_hash(); - init_random(); - DATABASES = { - pg: "postgresql", - mysql: "mysql", - mariadb: "mariadb", - sqlite3: "sqlite", - "better-sqlite3": "sqlite", - "@prisma/client": "prisma", - mongoose: "mongodb", - mongodb: "mongodb", - "drizzle-orm": "drizzle" - }; - FRAMEWORKS = { - next: "next", - nuxt: "nuxt", - "@remix-run/server-runtime": "remix", - astro: "astro", - "@sveltejs/kit": "sveltekit", - "solid-start": "solid-start", - "tanstack-start": "tanstack-start", - hono: "hono", - express: "express", - elysia: "elysia", - expo: "expo" - }; - importRuntime = (m5) => { - return Function("mm", "return import(mm)")(m5); - }; - hasContainerEnv = async () => { - if (getVendor() === "cloudflare") return false; - try { - (await importRuntime("fs")).statSync("/run/.containerenv"); - return true; - } catch { - return false; - } - }; - generateId2 = (size2) => { - return createRandomStringGenerator("a-z", "A-Z", "0-9")(size2 || 32); - }; - projectIdCached = null; - noop4 = async function noop$1() { - }; - } -}); - -// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/context/create-context.mjs -function estimateEntropy(str) { - const unique2 = new Set(str).size; - if (unique2 === 0) return 0; - return Math.log2(Math.pow(unique2, str.length)); -} -function validateSecret(secret, logger$1) { - const isDefaultSecret = secret === DEFAULT_SECRET; - if (isTest()) return; - if (isDefaultSecret && isProduction) throw new BetterAuthError("You are using the default secret. Please set `BETTER_AUTH_SECRET` in your environment variables or pass `secret` in your auth config."); - if (!secret) throw new BetterAuthError("BETTER_AUTH_SECRET is missing. Set it in your environment or pass `secret` to betterAuth({ secret })."); - if (secret.length < 32) logger$1.warn(`[better-auth] Warning: your BETTER_AUTH_SECRET should be at least 32 characters long for adequate security. Generate one with \`npx @better-auth/cli secret\` or \`openssl rand -base64 32\`.`); - if (estimateEntropy(secret) < 120) logger$1.warn("[better-auth] Warning: your BETTER_AUTH_SECRET appears low-entropy. Use a randomly generated secret for production."); -} -async function createAuthContext(adapter, options, getDatabaseType) { - if (!options.database) options = defu(options, { - session: { cookieCache: { - enabled: true, - strategy: "jwe", - refreshCache: true - } }, - account: { - storeStateStrategy: "cookie", - storeAccountCookie: true - } - }); - const plugins2 = options.plugins || []; - const internalPlugins = getInternalPlugins(options); - const logger$1 = createLogger(options.logger); - const baseURL = getBaseURL(options.baseURL, options.basePath); - if (!baseURL) logger$1.warn(`[better-auth] Base URL could not be determined. Please set a valid base URL using the baseURL config option or the BETTER_AUTH_BASE_URL environment variable. Without this, callbacks and redirects may not work correctly.`); - if (adapter.id === "memory" && options.advanced?.database?.generateId === false) logger$1.error(`[better-auth] Misconfiguration detected. -You are using the memory DB with generateId: false. -This will cause no id to be generated for any model. -Most of the features of Better Auth will not work correctly.`); - const secret = options.secret || env.BETTER_AUTH_SECRET || env.AUTH_SECRET || DEFAULT_SECRET; - validateSecret(secret, logger$1); - options = { - ...options, - secret, - baseURL: baseURL ? new URL(baseURL).origin : "", - basePath: options.basePath || "/api/auth", - plugins: plugins2.concat(internalPlugins) - }; - checkEndpointConflicts(options, logger$1); - const cookies = getCookies(options); - const tables = getAuthTables(options); - const providers2 = Object.entries(options.socialProviders || {}).map(([key, config3]) => { - if (config3 == null) return null; - if (config3.enabled === false) return null; - if (!config3.clientId) logger$1.warn(`Social provider ${key} is missing clientId or clientSecret`); - const provider = socialProviders[key](config3); - provider.disableImplicitSignUp = config3.disableImplicitSignUp; - return provider; - }).filter((x5) => x5 !== null); - const generateIdFunc = ({ model, size: size2 }) => { - if (typeof options.advanced?.generateId === "function") return options.advanced.generateId({ - model, - size: size2 - }); - const dbGenerateId = options?.advanced?.database?.generateId; - if (typeof dbGenerateId === "function") return dbGenerateId({ - model, - size: size2 - }); - if (dbGenerateId === "uuid") return crypto.randomUUID(); - if (dbGenerateId === "serial" || dbGenerateId === false) return false; - return generateId(size2); - }; - const { publish } = await createTelemetry(options, { - adapter: adapter.id, - database: typeof options.database === "function" ? "adapter" : getDatabaseType(options.database) - }); - const trustedOrigins = await getTrustedOrigins(options); - const initOrPromise = runPluginInit({ - appName: options.appName || "Better Auth", - baseURL: baseURL || "", - version: getBetterAuthVersion(), - socialProviders: providers2, - options, - oauthConfig: { - storeStateStrategy: options.account?.storeStateStrategy || (options.database ? "database" : "cookie"), - skipStateCookieCheck: !!options.account?.skipStateCookieCheck - }, - tables, - trustedOrigins, - isTrustedOrigin(url2, settings) { - return this.trustedOrigins.some((origin) => matchesOriginPattern(url2, origin, settings)); - }, - sessionConfig: { - updateAge: options.session?.updateAge !== void 0 ? options.session.updateAge : 1440 * 60, - expiresIn: options.session?.expiresIn || 3600 * 24 * 7, - freshAge: options.session?.freshAge === void 0 ? 3600 * 24 : options.session.freshAge, - cookieRefreshCache: (() => { - const refreshCache = options.session?.cookieCache?.refreshCache; - const maxAge = options.session?.cookieCache?.maxAge || 300; - if ((!!options.database || !!options.secondaryStorage) && refreshCache) { - logger$1.warn("[better-auth] `session.cookieCache.refreshCache` is enabled while `database` or `secondaryStorage` is configured. `refreshCache` is meant for stateless (DB-less) setups. Disabling `refreshCache` \u2014 remove it from your config to silence this warning."); - return false; - } - if (refreshCache === false || refreshCache === void 0) return false; - if (refreshCache === true) return { - enabled: true, - updateAge: Math.floor(maxAge * 0.2) - }; - return { - enabled: true, - updateAge: refreshCache.updateAge !== void 0 ? refreshCache.updateAge : Math.floor(maxAge * 0.2) - }; - })() - }, - secret, - rateLimit: { - ...options.rateLimit, - enabled: options.rateLimit?.enabled ?? isProduction, - window: options.rateLimit?.window || 10, - max: options.rateLimit?.max || 100, - storage: options.rateLimit?.storage || (options.secondaryStorage ? "secondary-storage" : "memory") - }, - authCookies: cookies, - logger: logger$1, - generateId: generateIdFunc, - session: null, - secondaryStorage: options.secondaryStorage, - password: { - hash: options.emailAndPassword?.password?.hash || hashPassword, - verify: options.emailAndPassword?.password?.verify || verifyPassword, - config: { - minPasswordLength: options.emailAndPassword?.minPasswordLength || 8, - maxPasswordLength: options.emailAndPassword?.maxPasswordLength || 128 - }, - checkPassword - }, - setNewSession(session) { - this.newSession = session; - }, - newSession: null, - adapter, - internalAdapter: createInternalAdapter(adapter, { - options, - logger: logger$1, - hooks: options.databaseHooks ? [options.databaseHooks] : [], - generateId: generateIdFunc - }), - createAuthCookie: createCookieGetter(options), - async runMigrations() { - throw new BetterAuthError("runMigrations will be set by the specific init implementation"); - }, - publishTelemetry: publish, - skipCSRFCheck: !!options.advanced?.disableCSRFCheck, - skipOriginCheck: options.advanced?.disableOriginCheck !== void 0 ? options.advanced.disableOriginCheck : isTest() ? true : false, - runInBackground: options.advanced?.backgroundTasks?.handler ?? ((p5) => { - p5.catch(() => { - }); - }), - async runInBackgroundOrAwait(promise2) { - try { - if (options.advanced?.backgroundTasks?.handler) { - if (promise2 instanceof Promise) options.advanced.backgroundTasks.handler(promise2.catch((e5) => { - logger$1.error("Failed to run background task:", e5); - })); - } else await promise2; - } catch (e5) { - logger$1.error("Failed to run background task:", e5); - } - }, - getPlugin: (id) => options.plugins.find((p5) => p5.id === id) ?? null - }); - let context; - if (isPromise(initOrPromise)) ({ context } = await initOrPromise); - else ({ context } = initOrPromise); - if (typeof context.options.emailVerification?.onEmailVerification === "function") context.options.emailVerification.onEmailVerification = deprecate(context.options.emailVerification.onEmailVerification, "Use `afterEmailVerification` instead. This will be removed in 1.5", context.logger); - return context; -} -var init_create_context = __esm({ - "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/context/create-context.mjs"() { - init_internal_adapter(); - init_url2(); - init_trusted_origins(); - init_password(); - init_is_promise(); - init_cookies2(); - init_utils10(); - init_password2(); - init_api3(); - init_constants(); - init_helpers2(); - init_context2(); - init_db3(); - init_env(); - init_error(); - init_utils7(); - init_social_providers(); - init_dist5(); - init_defu(); - } -}); - -// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/context/init.mjs -var init; -var init_init = __esm({ - "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/context/init.mjs"() { - init_dialect3(); - init_adapter_kysely(); - init_get_migration(); - init_create_context(); - init_error(); - init = async (options) => { - const adapter = await getAdapter(options); - const getDatabaseType = (database) => getKyselyDatabaseType(database) || "unknown"; - const ctx = await createAuthContext(adapter, options, getDatabaseType); - ctx.runMigrations = async function() { - if (!options.database || "updateMany" in options.database) throw new BetterAuthError("Database is not provided or it's an adapter. Migrations are only supported with a database instance."); - const { runMigrations } = await getMigrations(options); - await runMigrations(); - }; - return ctx; - }; - } -}); - -// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/auth/base.mjs -var createBetterAuth; -var init_base = __esm({ - "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/auth/base.mjs"() { - init_url2(); - init_api3(); - init_helpers2(); - init_context2(); - init_error(); - createBetterAuth = (options, initFn) => { - const authContext = initFn(options); - const { api } = getEndpoints(authContext, options); - return { - handler: async (request) => { - const ctx = await authContext; - const basePath = ctx.options.basePath || "/api/auth"; - if (!ctx.options.baseURL) { - const baseURL = getBaseURL(void 0, basePath, request, void 0, ctx.options.advanced?.trustedProxyHeaders); - if (baseURL) { - ctx.baseURL = baseURL; - ctx.options.baseURL = getOrigin(ctx.baseURL) || void 0; - } else throw new BetterAuthError("Could not get base URL from request. Please provide a valid base URL."); - } - ctx.trustedOrigins = await getTrustedOrigins(ctx.options, request); - const { handler } = router(ctx, options); - return runWithAdapter(ctx.adapter, () => handler(request)); - }, - api, - options, - $context: authContext, - $ERROR_CODES: { - ...options.plugins?.reduce((acc, plugin) => { - if (plugin.$ERROR_CODES) return { - ...acc, - ...plugin.$ERROR_CODES - }; - return acc; - }, {}), - ...BASE_ERROR_CODES - } - }; - }; - } -}); - -// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/auth/full.mjs -var betterAuth; -var init_full = __esm({ - "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/auth/full.mjs"() { - init_init(); - init_base(); - betterAuth = (options) => { - return createBetterAuth(options, init); - }; - } -}); - -// node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/index.mjs -var init_dist6 = __esm({ - "node_modules/.pnpm/@better-auth+core@1.4.18_@better-auth+utils@0.3.0_@better-fetch+fetch@1.1.21_better-call@1.1._6tfpsbb4hsrpkf6l6f6fnjcdma/node_modules/@better-auth/core/dist/index.mjs"() { - } -}); - -// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/index.mjs -var init_dist7 = __esm({ - "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/index.mjs"() { - init_state(); - init_state2(); - init_hide_metadata(); - init_utils10(); - init_api3(); - init_full(); - init_context2(); - init_dist5(); - init_dist6(); - init_db3(); - init_env(); - init_error(); - init_oauth2(); - init_utils7(); - } -}); - -// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/adapters/drizzle-adapter/drizzle-adapter.mjs -var drizzleAdapter; -var init_drizzle_adapter = __esm({ - "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/adapters/drizzle-adapter/drizzle-adapter.mjs"() { - init_env(); - init_error(); - init_adapter(); - init_drizzle_orm(); - drizzleAdapter = (db, config3) => { - let lazyOptions = null; - const createCustomAdapter = (db$1) => ({ getFieldName, options }) => { - function getSchema2(model) { - const schema2 = config3.schema || db$1._.fullSchema; - if (!schema2) throw new BetterAuthError("Drizzle adapter failed to initialize. Schema not found. Please provide a schema object in the adapter options object."); - const schemaModel = schema2[model]; - if (!schemaModel) throw new BetterAuthError(`[# Drizzle Adapter]: The model "${model}" was not found in the schema object. Please pass the schema directly to the adapter options.`); - return schemaModel; - } - const withReturning = async (model, builder, data2, where) => { - if (config3.provider !== "mysql") return (await builder.returning())[0]; - await builder.execute(); - const schemaModel = getSchema2(model); - const builderVal = builder.config?.values; - if (where?.length) { - const clause = convertWhereClause(where.map((w5) => { - if (data2[w5.field] !== void 0) return { - ...w5, - value: data2[w5.field] - }; - return w5; - }), model); - return (await db$1.select().from(schemaModel).where(...clause))[0]; - } else if (builderVal && builderVal[0]?.id?.value) { - let tId = builderVal[0]?.id?.value; - if (!tId) tId = (await db$1.select({ id: sql`LAST_INSERT_ID()` }).from(schemaModel).orderBy(desc(schemaModel.id)).limit(1))[0].id; - return (await db$1.select().from(schemaModel).where(eq(schemaModel.id, tId)).limit(1).execute())[0]; - } else if (data2.id) return (await db$1.select().from(schemaModel).where(eq(schemaModel.id, data2.id)).limit(1).execute())[0]; - else { - if (!("id" in schemaModel)) throw new BetterAuthError(`The model "${model}" does not have an "id" field. Please use the "id" field as your primary key.`); - return (await db$1.select().from(schemaModel).orderBy(desc(schemaModel.id)).limit(1).execute())[0]; - } - }; - function convertWhereClause(where, model) { - const schemaModel = getSchema2(model); - if (!where) return []; - if (where.length === 1) { - const w5 = where[0]; - if (!w5) return []; - const field = getFieldName({ - model, - field: w5.field - }); - if (!schemaModel[field]) throw new BetterAuthError(`The field "${w5.field}" does not exist in the schema for the model "${model}". Please update your schema.`); - if (w5.operator === "in") { - if (!Array.isArray(w5.value)) throw new BetterAuthError(`The value for the field "${w5.field}" must be an array when using the "in" operator.`); - return [inArray(schemaModel[field], w5.value)]; - } - if (w5.operator === "not_in") { - if (!Array.isArray(w5.value)) throw new BetterAuthError(`The value for the field "${w5.field}" must be an array when using the "not_in" operator.`); - return [notInArray(schemaModel[field], w5.value)]; - } - if (w5.operator === "contains") return [like(schemaModel[field], `%${w5.value}%`)]; - if (w5.operator === "starts_with") return [like(schemaModel[field], `${w5.value}%`)]; - if (w5.operator === "ends_with") return [like(schemaModel[field], `%${w5.value}`)]; - if (w5.operator === "lt") return [lt(schemaModel[field], w5.value)]; - if (w5.operator === "lte") return [lte(schemaModel[field], w5.value)]; - if (w5.operator === "ne") return [ne(schemaModel[field], w5.value)]; - if (w5.operator === "gt") return [gt(schemaModel[field], w5.value)]; - if (w5.operator === "gte") return [gte(schemaModel[field], w5.value)]; - return [eq(schemaModel[field], w5.value)]; - } - const andGroup = where.filter((w5) => w5.connector === "AND" || !w5.connector); - const orGroup = where.filter((w5) => w5.connector === "OR"); - const andClause = and(...andGroup.map((w5) => { - const field = getFieldName({ - model, - field: w5.field - }); - if (w5.operator === "in") { - if (!Array.isArray(w5.value)) throw new BetterAuthError(`The value for the field "${w5.field}" must be an array when using the "in" operator.`); - return inArray(schemaModel[field], w5.value); - } - if (w5.operator === "not_in") { - if (!Array.isArray(w5.value)) throw new BetterAuthError(`The value for the field "${w5.field}" must be an array when using the "not_in" operator.`); - return notInArray(schemaModel[field], w5.value); - } - if (w5.operator === "contains") return like(schemaModel[field], `%${w5.value}%`); - if (w5.operator === "starts_with") return like(schemaModel[field], `${w5.value}%`); - if (w5.operator === "ends_with") return like(schemaModel[field], `%${w5.value}`); - if (w5.operator === "lt") return lt(schemaModel[field], w5.value); - if (w5.operator === "lte") return lte(schemaModel[field], w5.value); - if (w5.operator === "gt") return gt(schemaModel[field], w5.value); - if (w5.operator === "gte") return gte(schemaModel[field], w5.value); - if (w5.operator === "ne") return ne(schemaModel[field], w5.value); - return eq(schemaModel[field], w5.value); - })); - const orClause = or(...orGroup.map((w5) => { - const field = getFieldName({ - model, - field: w5.field - }); - if (w5.operator === "in") { - if (!Array.isArray(w5.value)) throw new BetterAuthError(`The value for the field "${w5.field}" must be an array when using the "in" operator.`); - return inArray(schemaModel[field], w5.value); - } - if (w5.operator === "not_in") { - if (!Array.isArray(w5.value)) throw new BetterAuthError(`The value for the field "${w5.field}" must be an array when using the "not_in" operator.`); - return notInArray(schemaModel[field], w5.value); - } - if (w5.operator === "contains") return like(schemaModel[field], `%${w5.value}%`); - if (w5.operator === "starts_with") return like(schemaModel[field], `${w5.value}%`); - if (w5.operator === "ends_with") return like(schemaModel[field], `%${w5.value}`); - if (w5.operator === "lt") return lt(schemaModel[field], w5.value); - if (w5.operator === "lte") return lte(schemaModel[field], w5.value); - if (w5.operator === "gt") return gt(schemaModel[field], w5.value); - if (w5.operator === "gte") return gte(schemaModel[field], w5.value); - if (w5.operator === "ne") return ne(schemaModel[field], w5.value); - return eq(schemaModel[field], w5.value); - })); - const clause = []; - if (andGroup.length) clause.push(andClause); - if (orGroup.length) clause.push(orClause); - return clause; - } - function checkMissingFields(schema2, model, values2) { - if (!schema2) throw new BetterAuthError("Drizzle adapter failed to initialize. Drizzle Schema not found. Please provide a schema object in the adapter options object."); - for (const key in values2) if (!schema2[key]) throw new BetterAuthError(`The field "${key}" does not exist in the "${model}" Drizzle schema. Please update your drizzle schema or re-generate using "npx @better-auth/cli@latest generate".`); - } - return { - async create({ model, data: values2 }) { - const schemaModel = getSchema2(model); - checkMissingFields(schemaModel, model, values2); - return await withReturning(model, db$1.insert(schemaModel).values(values2), values2); - }, - async findOne({ model, where, join: join4 }) { - const schemaModel = getSchema2(model); - const clause = convertWhereClause(where, model); - if (options.experimental?.joins) if (!db$1.query || !db$1.query[model]) { - logger3.error(`[# Drizzle Adapter]: The model "${model}" was not found in the query object. Please update your Drizzle schema to include relations or re-generate using "npx @better-auth/cli@latest generate".`); - logger3.info("Falling back to regular query"); - } else { - let includes; - const pluralJoinResults = []; - if (join4) { - includes = {}; - const joinEntries = Object.entries(join4); - for (const [model$1, joinAttr] of joinEntries) { - const limit = joinAttr.limit ?? options.advanced?.database?.defaultFindManyLimit ?? 100; - const isUnique = joinAttr.relation === "one-to-one"; - const pluralSuffix = isUnique || config3.usePlural ? "" : "s"; - includes[`${model$1}${pluralSuffix}`] = isUnique ? true : { limit }; - if (!isUnique) pluralJoinResults.push(`${model$1}${pluralSuffix}`); - } - } - const res$1 = await db$1.query[model].findFirst({ - where: clause[0], - with: includes - }); - if (res$1) for (const pluralJoinResult of pluralJoinResults) { - const singularKey = !config3.usePlural ? pluralJoinResult.slice(0, -1) : pluralJoinResult; - res$1[singularKey] = res$1[pluralJoinResult]; - if (pluralJoinResult !== singularKey) delete res$1[pluralJoinResult]; - } - return res$1; - } - const res = await db$1.select().from(schemaModel).where(...clause); - if (!res.length) return null; - return res[0]; - }, - async findMany({ model, where, sortBy, limit, offset, join: join4 }) { - const schemaModel = getSchema2(model); - const clause = where ? convertWhereClause(where, model) : []; - const sortFn = sortBy?.direction === "desc" ? desc : asc; - if (options.experimental?.joins) if (!db$1.query[model]) { - logger3.error(`[# Drizzle Adapter]: The model "${model}" was not found in the query object. Please update your Drizzle schema to include relations or re-generate using "npx @better-auth/cli@latest generate".`); - logger3.info("Falling back to regular query"); - } else { - let includes; - const pluralJoinResults = []; - if (join4) { - includes = {}; - const joinEntries = Object.entries(join4); - for (const [model$1, joinAttr] of joinEntries) { - const isUnique = joinAttr.relation === "one-to-one"; - const limit$1 = joinAttr.limit ?? options.advanced?.database?.defaultFindManyLimit ?? 100; - const pluralSuffix = isUnique || config3.usePlural ? "" : "s"; - includes[`${model$1}${pluralSuffix}`] = isUnique ? true : { limit: limit$1 }; - if (!isUnique) pluralJoinResults.push(`${model$1}${pluralSuffix}`); - } - } - let orderBy = void 0; - if (sortBy?.field) orderBy = [sortFn(schemaModel[getFieldName({ - model, - field: sortBy?.field - })])]; - const res = await db$1.query[model].findMany({ - where: clause[0], - with: includes, - limit: limit ?? 100, - offset: offset ?? 0, - orderBy - }); - if (res) for (const item of res) for (const pluralJoinResult of pluralJoinResults) { - const singularKey = !config3.usePlural ? pluralJoinResult.slice(0, -1) : pluralJoinResult; - if (singularKey === pluralJoinResult) continue; - item[singularKey] = item[pluralJoinResult]; - delete item[pluralJoinResult]; - } - return res; - } - let builder = db$1.select().from(schemaModel); - const effectiveLimit = limit; - const effectiveOffset = offset; - if (typeof effectiveLimit !== "undefined") builder = builder.limit(effectiveLimit); - if (typeof effectiveOffset !== "undefined") builder = builder.offset(effectiveOffset); - if (sortBy?.field) builder = builder.orderBy(sortFn(schemaModel[getFieldName({ - model, - field: sortBy?.field - })])); - return await builder.where(...clause); - }, - async count({ model, where }) { - const schemaModel = getSchema2(model); - const clause = where ? convertWhereClause(where, model) : []; - return (await db$1.select({ count: count() }).from(schemaModel).where(...clause))[0].count; - }, - async update({ model, where, update: values2 }) { - const schemaModel = getSchema2(model); - const clause = convertWhereClause(where, model); - return await withReturning(model, db$1.update(schemaModel).set(values2).where(...clause), values2, where); - }, - async updateMany({ model, where, update: values2 }) { - const schemaModel = getSchema2(model); - const clause = convertWhereClause(where, model); - return await db$1.update(schemaModel).set(values2).where(...clause); - }, - async delete({ model, where }) { - const schemaModel = getSchema2(model); - const clause = convertWhereClause(where, model); - return await db$1.delete(schemaModel).where(...clause); - }, - async deleteMany({ model, where }) { - const schemaModel = getSchema2(model); - const clause = convertWhereClause(where, model); - const res = await db$1.delete(schemaModel).where(...clause); - let count$1 = 0; - if (res && "rowCount" in res) count$1 = res.rowCount; - else if (Array.isArray(res)) count$1 = res.length; - else if (res && ("affectedRows" in res || "rowsAffected" in res || "changes" in res)) count$1 = res.affectedRows ?? res.rowsAffected ?? res.changes; - if (typeof count$1 !== "number") logger3.error("[Drizzle Adapter] The result of the deleteMany operation is not a number. This is likely a bug in the adapter. Please report this issue to the Better Auth team.", { - res, - model, - where - }); - return count$1; - }, - options: config3 - }; - }; - let adapterOptions = null; - adapterOptions = { - config: { - adapterId: "drizzle", - adapterName: "Drizzle Adapter", - usePlural: config3.usePlural ?? false, - debugLogs: config3.debugLogs ?? false, - supportsUUIDs: config3.provider === "pg" ? true : false, - supportsJSON: config3.provider === "pg" ? true : false, - supportsArrays: config3.provider === "pg" ? true : false, - transaction: config3.transaction ?? false ? (cb) => db.transaction((tx) => { - return cb(createAdapterFactory({ - config: adapterOptions.config, - adapter: createCustomAdapter(tx) - })(lazyOptions)); - }) : false - }, - adapter: createCustomAdapter(db) - }; - const adapter = createAdapterFactory(adapterOptions); - return (options) => { - lazyOptions = options; - return adapter(options); - }; - }; - } -}); - -// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/adapters/drizzle-adapter/index.mjs -var init_drizzle_adapter2 = __esm({ - "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/adapters/drizzle-adapter/index.mjs"() { - init_drizzle_adapter(); - } -}); - -// node_modules/.pnpm/set-cookie-parser@2.7.2/node_modules/set-cookie-parser/lib/set-cookie.js -var require_set_cookie = __commonJS({ - "node_modules/.pnpm/set-cookie-parser@2.7.2/node_modules/set-cookie-parser/lib/set-cookie.js"(exports, module) { - "use strict"; - var defaultParseOptions = { - decodeValues: true, - map: false, - silent: false - }; - function isForbiddenKey(key) { - return typeof key !== "string" || key in {}; - } - function createNullObj() { - return /* @__PURE__ */ Object.create(null); - } - function isNonEmptyString(str) { - return typeof str === "string" && !!str.trim(); - } - function parseString(setCookieValue, options) { - var parts = setCookieValue.split(";").filter(isNonEmptyString); - var nameValuePairStr = parts.shift(); - var parsed = parseNameValuePair(nameValuePairStr); - var name = parsed.name; - var value = parsed.value; - options = options ? Object.assign({}, defaultParseOptions, options) : defaultParseOptions; - if (isForbiddenKey(name)) { - return null; - } - try { - value = options.decodeValues ? decodeURIComponent(value) : value; - } catch (e5) { - console.error( - "set-cookie-parser: failed to decode cookie value. Set options.decodeValues=false to disable decoding.", - e5 - ); - } - var cookie = createNullObj(); - cookie.name = name; - cookie.value = value; - parts.forEach(function(part) { - var sides = part.split("="); - var key = sides.shift().trimLeft().toLowerCase(); - if (isForbiddenKey(key)) { - return; - } - var value2 = sides.join("="); - if (key === "expires") { - cookie.expires = new Date(value2); - } else if (key === "max-age") { - var n5 = parseInt(value2, 10); - if (!Number.isNaN(n5)) cookie.maxAge = n5; - } else if (key === "secure") { - cookie.secure = true; - } else if (key === "httponly") { - cookie.httpOnly = true; - } else if (key === "samesite") { - cookie.sameSite = value2; - } else if (key === "partitioned") { - cookie.partitioned = true; - } else if (key) { - cookie[key] = value2; - } - }); - return cookie; - } - function parseNameValuePair(nameValuePairStr) { - var name = ""; - var value = ""; - var nameValueArr = nameValuePairStr.split("="); - if (nameValueArr.length > 1) { - name = nameValueArr.shift(); - value = nameValueArr.join("="); - } else { - value = nameValuePairStr; - } - return { name, value }; - } - function parse5(input, options) { - options = options ? Object.assign({}, defaultParseOptions, options) : defaultParseOptions; - if (!input) { - if (!options.map) { - return []; - } else { - return createNullObj(); - } - } - if (input.headers) { - if (typeof input.headers.getSetCookie === "function") { - input = input.headers.getSetCookie(); - } else if (input.headers["set-cookie"]) { - input = input.headers["set-cookie"]; - } else { - var sch = input.headers[Object.keys(input.headers).find(function(key) { - return key.toLowerCase() === "set-cookie"; - })]; - if (!sch && input.headers.cookie && !options.silent) { - console.warn( - "Warning: set-cookie-parser appears to have been called on a request object. It is designed to parse Set-Cookie headers from responses, not Cookie headers from requests. Set the option {silent: true} to suppress this warning." - ); - } - input = sch; - } - } - if (!Array.isArray(input)) { - input = [input]; - } - if (!options.map) { - return input.filter(isNonEmptyString).map(function(str) { - return parseString(str, options); - }).filter(Boolean); - } else { - var cookies = createNullObj(); - return input.filter(isNonEmptyString).reduce(function(cookies2, str) { - var cookie = parseString(str, options); - if (cookie && !isForbiddenKey(cookie.name)) { - cookies2[cookie.name] = cookie; - } - return cookies2; - }, cookies); - } - } - function splitCookiesString2(cookiesString) { - if (Array.isArray(cookiesString)) { - return cookiesString; - } - if (typeof cookiesString !== "string") { - return []; - } - var cookiesStrings = []; - var pos = 0; - var start; - var ch; - var lastComma; - var nextStart; - var cookiesSeparatorFound; - function skipWhitespace() { - while (pos < cookiesString.length && /\s/.test(cookiesString.charAt(pos))) { - pos += 1; - } - return pos < cookiesString.length; - } - function notSpecialChar() { - ch = cookiesString.charAt(pos); - return ch !== "=" && ch !== ";" && ch !== ","; - } - while (pos < cookiesString.length) { - start = pos; - cookiesSeparatorFound = false; - while (skipWhitespace()) { - ch = cookiesString.charAt(pos); - if (ch === ",") { - lastComma = pos; - pos += 1; - skipWhitespace(); - nextStart = pos; - while (pos < cookiesString.length && notSpecialChar()) { - pos += 1; - } - if (pos < cookiesString.length && cookiesString.charAt(pos) === "=") { - cookiesSeparatorFound = true; - pos = nextStart; - cookiesStrings.push(cookiesString.substring(start, lastComma)); - start = pos; - } else { - pos = lastComma + 1; - } - } else { - pos += 1; - } - } - if (!cookiesSeparatorFound || pos >= cookiesString.length) { - cookiesStrings.push(cookiesString.substring(start, cookiesString.length)); - } - } - return cookiesStrings; - } - module.exports = parse5; - module.exports.parse = parse5; - module.exports.parseString = parseString; - module.exports.splitCookiesString = splitCookiesString2; - } -}); - -// node_modules/.pnpm/better-call@1.1.8_zod@4.3.6/node_modules/better-call/dist/adapters/node/request.mjs -function get_raw_body(req, body_size_limit) { - const h5 = req.headers; - if (!h5["content-type"]) return null; - const content_length = Number(h5["content-length"]); - if (req.httpVersionMajor === 1 && isNaN(content_length) && h5["transfer-encoding"] == null || content_length === 0) return null; - let length = content_length; - if (body_size_limit) { - if (!length) length = body_size_limit; - else if (length > body_size_limit) throw Error(`Received content-length of ${length}, but only accept up to ${body_size_limit} bytes.`); - } - if (req.destroyed) { - const readable = new ReadableStream(); - readable.cancel(); - return readable; - } - let size2 = 0; - let cancelled = false; - return new ReadableStream({ - start(controller) { - req.on("error", (error50) => { - cancelled = true; - controller.error(error50); - }); - req.on("end", () => { - if (cancelled) return; - controller.close(); - }); - req.on("data", (chunk) => { - if (cancelled) return; - size2 += chunk.length; - if (size2 > length) { - cancelled = true; - controller.error(/* @__PURE__ */ new Error(`request body size exceeded ${content_length ? "'content-length'" : "BODY_SIZE_LIMIT"} of ${length}`)); - return; - } - controller.enqueue(chunk); - if (controller.desiredSize === null || controller.desiredSize <= 0) req.pause(); - }); - }, - pull() { - req.resume(); - }, - cancel(reason) { - cancelled = true; - req.destroy(reason); - } - }); -} -function getRequest({ request, base, bodySizeLimit }) { - const baseUrl = request?.baseUrl; - const fullPath = baseUrl ? baseUrl + request.url : request.url; - const maybeConsumedReq = request; - let body = void 0; - const method = request.method; - if (method !== "GET" && method !== "HEAD") if (maybeConsumedReq.body !== void 0) { - const bodyContent = typeof maybeConsumedReq.body === "string" ? maybeConsumedReq.body : JSON.stringify(maybeConsumedReq.body); - body = new ReadableStream({ start(controller) { - controller.enqueue(new TextEncoder().encode(bodyContent)); - controller.close(); - } }); - } else body = get_raw_body(request, bodySizeLimit); - return new Request(base + fullPath, { - duplex: "half", - method: request.method, - body, - headers: request.headers - }); -} -async function setResponse(res, response) { - for (const [key, value] of response.headers) try { - res.setHeader(key, key === "set-cookie" ? set_cookie_parser.splitCookiesString(response.headers.get(key)) : value); - } catch (error50) { - res.getHeaderNames().forEach((name) => res.removeHeader(name)); - res.writeHead(500).end(String(error50)); - return; - } - res.writeHead(response.status); - if (!response.body) { - res.end(); - return; - } - if (response.body.locked) { - res.end("Fatal error: Response body is locked. This can happen when the response was already read (for example through 'response.json()' or 'response.text()')."); - return; - } - const reader = response.body.getReader(); - if (res.destroyed) { - reader.cancel(); - return; - } - const cancel = (error50) => { - res.off("close", cancel); - res.off("error", cancel); - reader.cancel(error50).catch(() => { - }); - if (error50) res.destroy(error50); - }; - res.on("close", cancel); - res.on("error", cancel); - next(); - async function next() { - try { - for (; ; ) { - const { done, value } = await reader.read(); - if (done) break; - if (!res.write(value)) { - res.once("drain", next); - return; - } - } - res.end(); - } catch (error50) { - cancel(error50 instanceof Error ? error50 : new Error(String(error50))); - } - } -} -var set_cookie_parser; -var init_request = __esm({ - "node_modules/.pnpm/better-call@1.1.8_zod@4.3.6/node_modules/better-call/dist/adapters/node/request.mjs"() { - set_cookie_parser = __toESM(require_set_cookie(), 1); - } -}); - -// node_modules/.pnpm/better-call@1.1.8_zod@4.3.6/node_modules/better-call/dist/node.mjs -function toNodeHandler(handler) { - return async (req, res) => { - return setResponse(res, await handler(getRequest({ - base: `${req.headers["x-forwarded-proto"] || (req.socket.encrypted ? "https" : "http")}://${req.headers[":authority"] || req.headers.host}`, - request: req - }))); - }; -} -var init_node = __esm({ - "node_modules/.pnpm/better-call@1.1.8_zod@4.3.6/node_modules/better-call/dist/node.mjs"() { - init_request(); - } -}); - -// node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/integrations/node.mjs -var toNodeHandler2; -var init_node2 = __esm({ - "node_modules/.pnpm/better-auth@1.4.18_drizzle-kit@0.31.10_drizzle-orm@0.38.4_@types+react@19.2.14_kysely@0.28.16_edntoulm5xqabcpzr35grsk3wq/node_modules/better-auth/dist/integrations/node.mjs"() { - init_node(); - toNodeHandler2 = (auth) => { - return "handler" in auth ? toNodeHandler(auth.handler) : toNodeHandler(auth); - }; - } -}); - -// server/src/auth/better-auth.ts -var better_auth_exports = {}; -__export(better_auth_exports, { - createBetterAuthHandler: () => createBetterAuthHandler, - createBetterAuthInstance: () => createBetterAuthInstance, - deriveAuthTrustedOrigins: () => deriveAuthTrustedOrigins, - resolveBetterAuthSession: () => resolveBetterAuthSession, - resolveBetterAuthSessionFromHeaders: () => resolveBetterAuthSessionFromHeaders -}); -function headersFromNodeHeaders(rawHeaders) { - const headers = new Headers(); - for (const [key, raw] of Object.entries(rawHeaders)) { - if (!raw) continue; - if (Array.isArray(raw)) { - for (const value of raw) headers.append(key, value); - continue; - } - headers.set(key, raw); - } - return headers; -} -function headersFromExpressRequest(req) { - return headersFromNodeHeaders(req.headers); -} -function deriveAuthTrustedOrigins(config3) { - const baseUrl = config3.authBaseUrlMode === "explicit" ? config3.authPublicBaseUrl : void 0; - const trustedOrigins = /* @__PURE__ */ new Set(); - if (baseUrl) { - try { - trustedOrigins.add(new URL(baseUrl).origin); - } catch { - } - } - if (config3.deploymentMode === "authenticated") { - for (const hostname3 of config3.allowedHostnames) { - const trimmed = hostname3.trim().toLowerCase(); - if (!trimmed) continue; - trustedOrigins.add(`https://${trimmed}`); - trustedOrigins.add(`http://${trimmed}`); - } - } - return Array.from(trustedOrigins); -} -function createBetterAuthInstance(db, config3, trustedOrigins) { - const baseUrl = config3.authBaseUrlMode === "explicit" ? config3.authPublicBaseUrl : void 0; - const secret = process.env.BETTER_AUTH_SECRET ?? process.env.TASKCORE_AGENT_JWT_SECRET; - if (!secret) { - throw new Error( - "BETTER_AUTH_SECRET (or TASKCORE_AGENT_JWT_SECRET) must be set. For local development, set BETTER_AUTH_SECRET=taskcore-dev-secret in your .env file." - ); - } - const effectiveTrustedOrigins = trustedOrigins ?? deriveAuthTrustedOrigins(config3); - const publicUrl = process.env.TASKCORE_PUBLIC_URL ?? baseUrl; - const isHttpOnly = publicUrl ? publicUrl.startsWith("http://") : false; - const authConfig = { - baseURL: baseUrl, - secret, - trustedOrigins: effectiveTrustedOrigins, - database: drizzleAdapter(db, { - provider: "pg", - schema: { - user: authUsers, - session: authSessions, - account: authAccounts, - verification: authVerifications - } - }), - emailAndPassword: { - enabled: true, - requireEmailVerification: false, - disableSignUp: config3.authDisableSignUp - }, - ...isHttpOnly ? { advanced: { useSecureCookies: false } } : {} - }; - if (!baseUrl) { - delete authConfig.baseURL; - } - return betterAuth(authConfig); -} -function createBetterAuthHandler(auth) { - const handler = toNodeHandler2(auth); - return (req, res, next) => { - void Promise.resolve(handler(req, res)).catch(next); - }; -} -async function resolveBetterAuthSessionFromHeaders(auth, headers) { - const api = auth.api; - if (!api?.getSession) return null; - const sessionValue = await api.getSession({ - headers - }); - if (!sessionValue || typeof sessionValue !== "object") return null; - const value = sessionValue; - const session = value.session?.id && value.session.userId ? { id: value.session.id, userId: value.session.userId } : null; - const user = value.user?.id ? { - id: value.user.id, - email: value.user.email ?? null, - name: value.user.name ?? null - } : null; - if (!session || !user) return null; - return { session, user }; -} -async function resolveBetterAuthSession(auth, req) { - return resolveBetterAuthSessionFromHeaders(auth, headersFromExpressRequest(req)); -} -var init_better_auth = __esm({ - "server/src/auth/better-auth.ts"() { - "use strict"; - init_dist7(); - init_drizzle_adapter2(); - init_node2(); - init_src2(); - } -}); - -// server/src/vercel.ts -init_src2(); - -// server/src/app.ts -var import_express25 = __toESM(require_express2(), 1); -import path52 from "node:path"; -import fs40 from "node:fs"; -import { fileURLToPath as fileURLToPath19 } from "node:url"; - -// server/src/middleware/logger.ts -var import_pino = __toESM(require_pino(), 1); -var import_pino_http = __toESM(require_logger(), 1); -import path3 from "node:path"; - -// server/src/config-file.ts -import fs3 from "node:fs"; - -// node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/external.js -var external_exports = {}; -__export(external_exports, { - BRAND: () => BRAND, - DIRTY: () => DIRTY, - EMPTY_PATH: () => EMPTY_PATH, - INVALID: () => INVALID, - NEVER: () => NEVER, - OK: () => OK, - ParseStatus: () => ParseStatus, - Schema: () => ZodType, - ZodAny: () => ZodAny, - ZodArray: () => ZodArray, - ZodBigInt: () => ZodBigInt, - ZodBoolean: () => ZodBoolean, - ZodBranded: () => ZodBranded, - ZodCatch: () => ZodCatch, - ZodDate: () => ZodDate, - ZodDefault: () => ZodDefault, - ZodDiscriminatedUnion: () => ZodDiscriminatedUnion, - ZodEffects: () => ZodEffects, - ZodEnum: () => ZodEnum, - ZodError: () => ZodError, - ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind, - ZodFunction: () => ZodFunction, - ZodIntersection: () => ZodIntersection, - ZodIssueCode: () => ZodIssueCode, - ZodLazy: () => ZodLazy, - ZodLiteral: () => ZodLiteral, - ZodMap: () => ZodMap, - ZodNaN: () => ZodNaN, - ZodNativeEnum: () => ZodNativeEnum, - ZodNever: () => ZodNever, - ZodNull: () => ZodNull, - ZodNullable: () => ZodNullable, - ZodNumber: () => ZodNumber, - ZodObject: () => ZodObject, - ZodOptional: () => ZodOptional, - ZodParsedType: () => ZodParsedType, - ZodPipeline: () => ZodPipeline, - ZodPromise: () => ZodPromise, - ZodReadonly: () => ZodReadonly, - ZodRecord: () => ZodRecord, - ZodSchema: () => ZodType, - ZodSet: () => ZodSet, - ZodString: () => ZodString, - ZodSymbol: () => ZodSymbol, - ZodTransformer: () => ZodEffects, - ZodTuple: () => ZodTuple, - ZodType: () => ZodType, - ZodUndefined: () => ZodUndefined, - ZodUnion: () => ZodUnion, - ZodUnknown: () => ZodUnknown, - ZodVoid: () => ZodVoid, - addIssueToContext: () => addIssueToContext, - any: () => anyType, - array: () => arrayType, - bigint: () => bigIntType, - boolean: () => booleanType, - coerce: () => coerce, - custom: () => custom, - date: () => dateType, - datetimeRegex: () => datetimeRegex, - defaultErrorMap: () => en_default, - discriminatedUnion: () => discriminatedUnionType, - effect: () => effectsType, - enum: () => enumType, - function: () => functionType, - getErrorMap: () => getErrorMap, - getParsedType: () => getParsedType, - instanceof: () => instanceOfType, - intersection: () => intersectionType, - isAborted: () => isAborted, - isAsync: () => isAsync, - isDirty: () => isDirty, - isValid: () => isValid, - late: () => late, - lazy: () => lazyType, - literal: () => literalType, - makeIssue: () => makeIssue, - map: () => mapType, - nan: () => nanType, - nativeEnum: () => nativeEnumType, - never: () => neverType, - null: () => nullType, - nullable: () => nullableType, - number: () => numberType, - object: () => objectType, - objectUtil: () => objectUtil, - oboolean: () => oboolean, - onumber: () => onumber, - optional: () => optionalType, - ostring: () => ostring, - pipeline: () => pipelineType, - preprocess: () => preprocessType, - promise: () => promiseType, - quotelessJson: () => quotelessJson, - record: () => recordType, - set: () => setType, - setErrorMap: () => setErrorMap, - strictObject: () => strictObjectType, - string: () => stringType, - symbol: () => symbolType, - transformer: () => effectsType, - tuple: () => tupleType, - undefined: () => undefinedType, - union: () => unionType, - unknown: () => unknownType, - util: () => util, - void: () => voidType -}); - -// node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/util.js -var util; -(function(util2) { - util2.assertEqual = (_) => { - }; - function assertIs2(_arg) { - } - util2.assertIs = assertIs2; - function assertNever2(_x) { - throw new Error(); - } - util2.assertNever = assertNever2; - util2.arrayToEnum = (items) => { - const obj = {}; - for (const item of items) { - obj[item] = item; - } - return obj; - }; - util2.getValidEnumValues = (obj) => { - const validKeys = util2.objectKeys(obj).filter((k5) => typeof obj[obj[k5]] !== "number"); - const filtered = {}; - for (const k5 of validKeys) { - filtered[k5] = obj[k5]; - } - return util2.objectValues(filtered); - }; - util2.objectValues = (obj) => { - return util2.objectKeys(obj).map(function(e5) { - return obj[e5]; - }); - }; - util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object2) => { - const keys = []; - for (const key in object2) { - if (Object.prototype.hasOwnProperty.call(object2, key)) { - keys.push(key); - } - } - return keys; - }; - util2.find = (arr, checker) => { - for (const item of arr) { - if (checker(item)) - return item; - } - return void 0; - }; - util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val; - function joinValues2(array2, separator = " | ") { - return array2.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator); - } - util2.joinValues = joinValues2; - util2.jsonStringifyReplacer = (_, value) => { - if (typeof value === "bigint") { - return value.toString(); - } - return value; - }; -})(util || (util = {})); -var objectUtil; -(function(objectUtil2) { - objectUtil2.mergeShapes = (first, second) => { - return { - ...first, - ...second - // second overwrites first - }; - }; -})(objectUtil || (objectUtil = {})); -var ZodParsedType = util.arrayToEnum([ - "string", - "nan", - "number", - "integer", - "float", - "boolean", - "date", - "bigint", - "symbol", - "function", - "undefined", - "null", - "array", - "object", - "unknown", - "promise", - "void", - "never", - "map", - "set" -]); -var getParsedType = (data2) => { - const t5 = typeof data2; - switch (t5) { - case "undefined": - return ZodParsedType.undefined; - case "string": - return ZodParsedType.string; - case "number": - return Number.isNaN(data2) ? ZodParsedType.nan : ZodParsedType.number; - case "boolean": - return ZodParsedType.boolean; - case "function": - return ZodParsedType.function; - case "bigint": - return ZodParsedType.bigint; - case "symbol": - return ZodParsedType.symbol; - case "object": - if (Array.isArray(data2)) { - return ZodParsedType.array; - } - if (data2 === null) { - return ZodParsedType.null; - } - if (data2.then && typeof data2.then === "function" && data2.catch && typeof data2.catch === "function") { - return ZodParsedType.promise; - } - if (typeof Map !== "undefined" && data2 instanceof Map) { - return ZodParsedType.map; - } - if (typeof Set !== "undefined" && data2 instanceof Set) { - return ZodParsedType.set; - } - if (typeof Date !== "undefined" && data2 instanceof Date) { - return ZodParsedType.date; - } - return ZodParsedType.object; - default: - return ZodParsedType.unknown; - } -}; - -// node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/ZodError.js -var ZodIssueCode = util.arrayToEnum([ - "invalid_type", - "invalid_literal", - "custom", - "invalid_union", - "invalid_union_discriminator", - "invalid_enum_value", - "unrecognized_keys", - "invalid_arguments", - "invalid_return_type", - "invalid_date", - "invalid_string", - "too_small", - "too_big", - "invalid_intersection_types", - "not_multiple_of", - "not_finite" -]); -var quotelessJson = (obj) => { - const json3 = JSON.stringify(obj, null, 2); - return json3.replace(/"([^"]+)":/g, "$1:"); -}; -var ZodError = class _ZodError extends Error { - get errors() { - return this.issues; - } - constructor(issues2) { - super(); - this.issues = []; - this.addIssue = (sub) => { - this.issues = [...this.issues, sub]; - }; - this.addIssues = (subs = []) => { - this.issues = [...this.issues, ...subs]; - }; - const actualProto = new.target.prototype; - if (Object.setPrototypeOf) { - Object.setPrototypeOf(this, actualProto); - } else { - this.__proto__ = actualProto; - } - this.name = "ZodError"; - this.issues = issues2; - } - format(_mapper) { - const mapper = _mapper || function(issue2) { - return issue2.message; - }; - const fieldErrors = { _errors: [] }; - const processError = (error50) => { - for (const issue2 of error50.issues) { - if (issue2.code === "invalid_union") { - issue2.unionErrors.map(processError); - } else if (issue2.code === "invalid_return_type") { - processError(issue2.returnTypeError); - } else if (issue2.code === "invalid_arguments") { - processError(issue2.argumentsError); - } else if (issue2.path.length === 0) { - fieldErrors._errors.push(mapper(issue2)); - } else { - let curr = fieldErrors; - let i5 = 0; - while (i5 < issue2.path.length) { - const el = issue2.path[i5]; - const terminal = i5 === issue2.path.length - 1; - if (!terminal) { - curr[el] = curr[el] || { _errors: [] }; - } else { - curr[el] = curr[el] || { _errors: [] }; - curr[el]._errors.push(mapper(issue2)); - } - curr = curr[el]; - i5++; - } - } - } - }; - processError(this); - return fieldErrors; - } - static assert(value) { - if (!(value instanceof _ZodError)) { - throw new Error(`Not a ZodError: ${value}`); - } - } - toString() { - return this.message; - } - get message() { - return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2); - } - get isEmpty() { - return this.issues.length === 0; - } - flatten(mapper = (issue2) => issue2.message) { - const fieldErrors = {}; - const formErrors = []; - for (const sub of this.issues) { - if (sub.path.length > 0) { - const firstEl = sub.path[0]; - fieldErrors[firstEl] = fieldErrors[firstEl] || []; - fieldErrors[firstEl].push(mapper(sub)); - } else { - formErrors.push(mapper(sub)); - } - } - return { formErrors, fieldErrors }; - } - get formErrors() { - return this.flatten(); - } -}; -ZodError.create = (issues2) => { - const error50 = new ZodError(issues2); - return error50; -}; - -// node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/locales/en.js -var errorMap = (issue2, _ctx) => { - let message2; - switch (issue2.code) { - case ZodIssueCode.invalid_type: - if (issue2.received === ZodParsedType.undefined) { - message2 = "Required"; - } else { - message2 = `Expected ${issue2.expected}, received ${issue2.received}`; - } - break; - case ZodIssueCode.invalid_literal: - message2 = `Invalid literal value, expected ${JSON.stringify(issue2.expected, util.jsonStringifyReplacer)}`; - break; - case ZodIssueCode.unrecognized_keys: - message2 = `Unrecognized key(s) in object: ${util.joinValues(issue2.keys, ", ")}`; - break; - case ZodIssueCode.invalid_union: - message2 = `Invalid input`; - break; - case ZodIssueCode.invalid_union_discriminator: - message2 = `Invalid discriminator value. Expected ${util.joinValues(issue2.options)}`; - break; - case ZodIssueCode.invalid_enum_value: - message2 = `Invalid enum value. Expected ${util.joinValues(issue2.options)}, received '${issue2.received}'`; - break; - case ZodIssueCode.invalid_arguments: - message2 = `Invalid function arguments`; - break; - case ZodIssueCode.invalid_return_type: - message2 = `Invalid function return type`; - break; - case ZodIssueCode.invalid_date: - message2 = `Invalid date`; - break; - case ZodIssueCode.invalid_string: - if (typeof issue2.validation === "object") { - if ("includes" in issue2.validation) { - message2 = `Invalid input: must include "${issue2.validation.includes}"`; - if (typeof issue2.validation.position === "number") { - message2 = `${message2} at one or more positions greater than or equal to ${issue2.validation.position}`; - } - } else if ("startsWith" in issue2.validation) { - message2 = `Invalid input: must start with "${issue2.validation.startsWith}"`; - } else if ("endsWith" in issue2.validation) { - message2 = `Invalid input: must end with "${issue2.validation.endsWith}"`; - } else { - util.assertNever(issue2.validation); - } - } else if (issue2.validation !== "regex") { - message2 = `Invalid ${issue2.validation}`; - } else { - message2 = "Invalid"; - } - break; - case ZodIssueCode.too_small: - if (issue2.type === "array") - message2 = `Array must contain ${issue2.exact ? "exactly" : issue2.inclusive ? `at least` : `more than`} ${issue2.minimum} element(s)`; - else if (issue2.type === "string") - message2 = `String must contain ${issue2.exact ? "exactly" : issue2.inclusive ? `at least` : `over`} ${issue2.minimum} character(s)`; - else if (issue2.type === "number") - message2 = `Number must be ${issue2.exact ? `exactly equal to ` : issue2.inclusive ? `greater than or equal to ` : `greater than `}${issue2.minimum}`; - else if (issue2.type === "bigint") - message2 = `Number must be ${issue2.exact ? `exactly equal to ` : issue2.inclusive ? `greater than or equal to ` : `greater than `}${issue2.minimum}`; - else if (issue2.type === "date") - message2 = `Date must be ${issue2.exact ? `exactly equal to ` : issue2.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue2.minimum))}`; - else - message2 = "Invalid input"; - break; - case ZodIssueCode.too_big: - if (issue2.type === "array") - message2 = `Array must contain ${issue2.exact ? `exactly` : issue2.inclusive ? `at most` : `less than`} ${issue2.maximum} element(s)`; - else if (issue2.type === "string") - message2 = `String must contain ${issue2.exact ? `exactly` : issue2.inclusive ? `at most` : `under`} ${issue2.maximum} character(s)`; - else if (issue2.type === "number") - message2 = `Number must be ${issue2.exact ? `exactly` : issue2.inclusive ? `less than or equal to` : `less than`} ${issue2.maximum}`; - else if (issue2.type === "bigint") - message2 = `BigInt must be ${issue2.exact ? `exactly` : issue2.inclusive ? `less than or equal to` : `less than`} ${issue2.maximum}`; - else if (issue2.type === "date") - message2 = `Date must be ${issue2.exact ? `exactly` : issue2.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue2.maximum))}`; - else - message2 = "Invalid input"; - break; - case ZodIssueCode.custom: - message2 = `Invalid input`; - break; - case ZodIssueCode.invalid_intersection_types: - message2 = `Intersection results could not be merged`; - break; - case ZodIssueCode.not_multiple_of: - message2 = `Number must be a multiple of ${issue2.multipleOf}`; - break; - case ZodIssueCode.not_finite: - message2 = "Number must be finite"; - break; - default: - message2 = _ctx.defaultError; - util.assertNever(issue2); - } - return { message: message2 }; -}; -var en_default = errorMap; - -// node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/errors.js -var overrideErrorMap = en_default; -function setErrorMap(map4) { - overrideErrorMap = map4; -} -function getErrorMap() { - return overrideErrorMap; -} - -// node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/parseUtil.js -var makeIssue = (params) => { - const { data: data2, path: path53, errorMaps, issueData } = params; - const fullPath = [...path53, ...issueData.path || []]; - const fullIssue = { - ...issueData, - path: fullPath - }; - if (issueData.message !== void 0) { - return { - ...issueData, - path: fullPath, - message: issueData.message - }; - } - let errorMessage = ""; - const maps = errorMaps.filter((m5) => !!m5).slice().reverse(); - for (const map4 of maps) { - errorMessage = map4(fullIssue, { data: data2, defaultError: errorMessage }).message; - } - return { - ...issueData, - path: fullPath, - message: errorMessage - }; -}; -var EMPTY_PATH = []; -function addIssueToContext(ctx, issueData) { - const overrideMap = getErrorMap(); - const issue2 = makeIssue({ - issueData, - data: ctx.data, - path: ctx.path, - errorMaps: [ - ctx.common.contextualErrorMap, - // contextual error map is first priority - ctx.schemaErrorMap, - // then schema-bound map if available - overrideMap, - // then global override map - overrideMap === en_default ? void 0 : en_default - // then global default map - ].filter((x5) => !!x5) - }); - ctx.common.issues.push(issue2); -} -var ParseStatus = class _ParseStatus { - constructor() { - this.value = "valid"; - } - dirty() { - if (this.value === "valid") - this.value = "dirty"; - } - abort() { - if (this.value !== "aborted") - this.value = "aborted"; - } - static mergeArray(status, results) { - const arrayValue = []; - for (const s5 of results) { - if (s5.status === "aborted") - return INVALID; - if (s5.status === "dirty") - status.dirty(); - arrayValue.push(s5.value); - } - return { status: status.value, value: arrayValue }; - } - static async mergeObjectAsync(status, pairs) { - const syncPairs = []; - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - syncPairs.push({ - key, - value - }); - } - return _ParseStatus.mergeObjectSync(status, syncPairs); - } - static mergeObjectSync(status, pairs) { - const finalObject = {}; - for (const pair of pairs) { - const { key, value } = pair; - if (key.status === "aborted") - return INVALID; - if (value.status === "aborted") - return INVALID; - if (key.status === "dirty") - status.dirty(); - if (value.status === "dirty") - status.dirty(); - if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) { - finalObject[key.value] = value.value; - } - } - return { status: status.value, value: finalObject }; - } -}; -var INVALID = Object.freeze({ - status: "aborted" -}); -var DIRTY = (value) => ({ status: "dirty", value }); -var OK = (value) => ({ status: "valid", value }); -var isAborted = (x5) => x5.status === "aborted"; -var isDirty = (x5) => x5.status === "dirty"; -var isValid = (x5) => x5.status === "valid"; -var isAsync = (x5) => typeof Promise !== "undefined" && x5 instanceof Promise; - -// node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/errorUtil.js -var errorUtil; -(function(errorUtil2) { - errorUtil2.errToObj = (message2) => typeof message2 === "string" ? { message: message2 } : message2 || {}; - errorUtil2.toString = (message2) => typeof message2 === "string" ? message2 : message2?.message; -})(errorUtil || (errorUtil = {})); - -// node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/types.js -var ParseInputLazyPath = class { - constructor(parent, value, path53, key) { - this._cachedPath = []; - this.parent = parent; - this.data = value; - this._path = path53; - this._key = key; - } - get path() { - if (!this._cachedPath.length) { - if (Array.isArray(this._key)) { - this._cachedPath.push(...this._path, ...this._key); - } else { - this._cachedPath.push(...this._path, this._key); - } - } - return this._cachedPath; - } -}; -var handleResult = (ctx, result) => { - if (isValid(result)) { - return { success: true, data: result.value }; - } else { - if (!ctx.common.issues.length) { - throw new Error("Validation failed but no issues detected."); - } - return { - success: false, - get error() { - if (this._error) - return this._error; - const error50 = new ZodError(ctx.common.issues); - this._error = error50; - return this._error; - } - }; - } -}; -function processCreateParams(params) { - if (!params) - return {}; - const { errorMap: errorMap2, invalid_type_error, required_error, description } = params; - if (errorMap2 && (invalid_type_error || required_error)) { - throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`); - } - if (errorMap2) - return { errorMap: errorMap2, description }; - const customMap = (iss, ctx) => { - const { message: message2 } = params; - if (iss.code === "invalid_enum_value") { - return { message: message2 ?? ctx.defaultError }; - } - if (typeof ctx.data === "undefined") { - return { message: message2 ?? required_error ?? ctx.defaultError }; - } - if (iss.code !== "invalid_type") - return { message: ctx.defaultError }; - return { message: message2 ?? invalid_type_error ?? ctx.defaultError }; - }; - return { errorMap: customMap, description }; -} -var ZodType = class { - get description() { - return this._def.description; - } - _getType(input) { - return getParsedType(input.data); - } - _getOrReturnCtx(input, ctx) { - return ctx || { - common: input.parent.common, - data: input.data, - parsedType: getParsedType(input.data), - schemaErrorMap: this._def.errorMap, - path: input.path, - parent: input.parent - }; - } - _processInputParams(input) { - return { - status: new ParseStatus(), - ctx: { - common: input.parent.common, - data: input.data, - parsedType: getParsedType(input.data), - schemaErrorMap: this._def.errorMap, - path: input.path, - parent: input.parent - } - }; - } - _parseSync(input) { - const result = this._parse(input); - if (isAsync(result)) { - throw new Error("Synchronous parse encountered promise."); - } - return result; - } - _parseAsync(input) { - const result = this._parse(input); - return Promise.resolve(result); - } - parse(data2, params) { - const result = this.safeParse(data2, params); - if (result.success) - return result.data; - throw result.error; - } - safeParse(data2, params) { - const ctx = { - common: { - issues: [], - async: params?.async ?? false, - contextualErrorMap: params?.errorMap - }, - path: params?.path || [], - schemaErrorMap: this._def.errorMap, - parent: null, - data: data2, - parsedType: getParsedType(data2) - }; - const result = this._parseSync({ data: data2, path: ctx.path, parent: ctx }); - return handleResult(ctx, result); - } - "~validate"(data2) { - const ctx = { - common: { - issues: [], - async: !!this["~standard"].async - }, - path: [], - schemaErrorMap: this._def.errorMap, - parent: null, - data: data2, - parsedType: getParsedType(data2) - }; - if (!this["~standard"].async) { - try { - const result = this._parseSync({ data: data2, path: [], parent: ctx }); - return isValid(result) ? { - value: result.value - } : { - issues: ctx.common.issues - }; - } catch (err) { - if (err?.message?.toLowerCase()?.includes("encountered")) { - this["~standard"].async = true; - } - ctx.common = { - issues: [], - async: true - }; - } - } - return this._parseAsync({ data: data2, path: [], parent: ctx }).then((result) => isValid(result) ? { - value: result.value - } : { - issues: ctx.common.issues - }); - } - async parseAsync(data2, params) { - const result = await this.safeParseAsync(data2, params); - if (result.success) - return result.data; - throw result.error; - } - async safeParseAsync(data2, params) { - const ctx = { - common: { - issues: [], - contextualErrorMap: params?.errorMap, - async: true - }, - path: params?.path || [], - schemaErrorMap: this._def.errorMap, - parent: null, - data: data2, - parsedType: getParsedType(data2) - }; - const maybeAsyncResult = this._parse({ data: data2, path: ctx.path, parent: ctx }); - const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult)); - return handleResult(ctx, result); - } - refine(check3, message2) { - const getIssueProperties = (val) => { - if (typeof message2 === "string" || typeof message2 === "undefined") { - return { message: message2 }; - } else if (typeof message2 === "function") { - return message2(val); - } else { - return message2; - } - }; - return this._refinement((val, ctx) => { - const result = check3(val); - const setError = () => ctx.addIssue({ - code: ZodIssueCode.custom, - ...getIssueProperties(val) - }); - if (typeof Promise !== "undefined" && result instanceof Promise) { - return result.then((data2) => { - if (!data2) { - setError(); - return false; - } else { - return true; - } - }); - } - if (!result) { - setError(); - return false; - } else { - return true; - } - }); - } - refinement(check3, refinementData) { - return this._refinement((val, ctx) => { - if (!check3(val)) { - ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData); - return false; - } else { - return true; - } - }); - } - _refinement(refinement) { - return new ZodEffects({ - schema: this, - typeName: ZodFirstPartyTypeKind.ZodEffects, - effect: { type: "refinement", refinement } - }); - } - superRefine(refinement) { - return this._refinement(refinement); - } - constructor(def) { - this.spa = this.safeParseAsync; - this._def = def; - this.parse = this.parse.bind(this); - this.safeParse = this.safeParse.bind(this); - this.parseAsync = this.parseAsync.bind(this); - this.safeParseAsync = this.safeParseAsync.bind(this); - this.spa = this.spa.bind(this); - this.refine = this.refine.bind(this); - this.refinement = this.refinement.bind(this); - this.superRefine = this.superRefine.bind(this); - this.optional = this.optional.bind(this); - this.nullable = this.nullable.bind(this); - this.nullish = this.nullish.bind(this); - this.array = this.array.bind(this); - this.promise = this.promise.bind(this); - this.or = this.or.bind(this); - this.and = this.and.bind(this); - this.transform = this.transform.bind(this); - this.brand = this.brand.bind(this); - this.default = this.default.bind(this); - this.catch = this.catch.bind(this); - this.describe = this.describe.bind(this); - this.pipe = this.pipe.bind(this); - this.readonly = this.readonly.bind(this); - this.isNullable = this.isNullable.bind(this); - this.isOptional = this.isOptional.bind(this); - this["~standard"] = { - version: 1, - vendor: "zod", - validate: (data2) => this["~validate"](data2) - }; - } - optional() { - return ZodOptional.create(this, this._def); - } - nullable() { - return ZodNullable.create(this, this._def); - } - nullish() { - return this.nullable().optional(); - } - array() { - return ZodArray.create(this); - } - promise() { - return ZodPromise.create(this, this._def); - } - or(option) { - return ZodUnion.create([this, option], this._def); - } - and(incoming) { - return ZodIntersection.create(this, incoming, this._def); - } - transform(transform3) { - return new ZodEffects({ - ...processCreateParams(this._def), - schema: this, - typeName: ZodFirstPartyTypeKind.ZodEffects, - effect: { type: "transform", transform: transform3 } - }); - } - default(def) { - const defaultValueFunc = typeof def === "function" ? def : () => def; - return new ZodDefault({ - ...processCreateParams(this._def), - innerType: this, - defaultValue: defaultValueFunc, - typeName: ZodFirstPartyTypeKind.ZodDefault - }); - } - brand() { - return new ZodBranded({ - typeName: ZodFirstPartyTypeKind.ZodBranded, - type: this, - ...processCreateParams(this._def) - }); - } - catch(def) { - const catchValueFunc = typeof def === "function" ? def : () => def; - return new ZodCatch({ - ...processCreateParams(this._def), - innerType: this, - catchValue: catchValueFunc, - typeName: ZodFirstPartyTypeKind.ZodCatch - }); - } - describe(description) { - const This = this.constructor; - return new This({ - ...this._def, - description - }); - } - pipe(target) { - return ZodPipeline.create(this, target); - } - readonly() { - return ZodReadonly.create(this); - } - isOptional() { - return this.safeParse(void 0).success; - } - isNullable() { - return this.safeParse(null).success; - } -}; -var cuidRegex = /^c[^\s-]{8,}$/i; -var cuid2Regex = /^[0-9a-z]+$/; -var ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i; -var uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i; -var nanoidRegex = /^[a-z0-9_-]{21}$/i; -var jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/; -var durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; -var emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i; -var _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; -var emojiRegex; -var ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/; -var ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/; -var ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/; -var ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; -var base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/; -var base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/; -var dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`; -var dateRegex = new RegExp(`^${dateRegexSource}$`); -function timeRegexSource(args) { - let secondsRegexSource = `[0-5]\\d`; - if (args.precision) { - secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`; - } else if (args.precision == null) { - secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`; - } - const secondsQuantifier = args.precision ? "+" : "?"; - return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`; -} -function timeRegex(args) { - return new RegExp(`^${timeRegexSource(args)}$`); -} -function datetimeRegex(args) { - let regex = `${dateRegexSource}T${timeRegexSource(args)}`; - const opts = []; - opts.push(args.local ? `Z?` : `Z`); - if (args.offset) - opts.push(`([+-]\\d{2}:?\\d{2})`); - regex = `${regex}(${opts.join("|")})`; - return new RegExp(`^${regex}$`); -} -function isValidIP(ip, version3) { - if ((version3 === "v4" || !version3) && ipv4Regex.test(ip)) { - return true; - } - if ((version3 === "v6" || !version3) && ipv6Regex.test(ip)) { - return true; - } - return false; -} -function isValidJWT(jwt2, alg2) { - if (!jwtRegex.test(jwt2)) - return false; - try { - const [header] = jwt2.split("."); - if (!header) - return false; - const base644 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "="); - const decoded = JSON.parse(atob(base644)); - if (typeof decoded !== "object" || decoded === null) - return false; - if ("typ" in decoded && decoded?.typ !== "JWT") - return false; - if (!decoded.alg) - return false; - if (alg2 && decoded.alg !== alg2) - return false; - return true; - } catch { - return false; - } -} -function isValidCidr(ip, version3) { - if ((version3 === "v4" || !version3) && ipv4CidrRegex.test(ip)) { - return true; - } - if ((version3 === "v6" || !version3) && ipv6CidrRegex.test(ip)) { - return true; - } - return false; -} -var ZodString = class _ZodString2 extends ZodType { - _parse(input) { - if (this._def.coerce) { - input.data = String(input.data); - } - const parsedType2 = this._getType(input); - if (parsedType2 !== ZodParsedType.string) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext(ctx2, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.string, - received: ctx2.parsedType - }); - return INVALID; - } - const status = new ParseStatus(); - let ctx = void 0; - for (const check3 of this._def.checks) { - if (check3.kind === "min") { - if (input.data.length < check3.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: check3.value, - type: "string", - inclusive: true, - exact: false, - message: check3.message - }); - status.dirty(); - } - } else if (check3.kind === "max") { - if (input.data.length > check3.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: check3.value, - type: "string", - inclusive: true, - exact: false, - message: check3.message - }); - status.dirty(); - } - } else if (check3.kind === "length") { - const tooBig = input.data.length > check3.value; - const tooSmall = input.data.length < check3.value; - if (tooBig || tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - if (tooBig) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: check3.value, - type: "string", - inclusive: true, - exact: true, - message: check3.message - }); - } else if (tooSmall) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: check3.value, - type: "string", - inclusive: true, - exact: true, - message: check3.message - }); - } - status.dirty(); - } - } else if (check3.kind === "email") { - if (!emailRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "email", - code: ZodIssueCode.invalid_string, - message: check3.message - }); - status.dirty(); - } - } else if (check3.kind === "emoji") { - if (!emojiRegex) { - emojiRegex = new RegExp(_emojiRegex, "u"); - } - if (!emojiRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "emoji", - code: ZodIssueCode.invalid_string, - message: check3.message - }); - status.dirty(); - } - } else if (check3.kind === "uuid") { - if (!uuidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "uuid", - code: ZodIssueCode.invalid_string, - message: check3.message - }); - status.dirty(); - } - } else if (check3.kind === "nanoid") { - if (!nanoidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "nanoid", - code: ZodIssueCode.invalid_string, - message: check3.message - }); - status.dirty(); - } - } else if (check3.kind === "cuid") { - if (!cuidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "cuid", - code: ZodIssueCode.invalid_string, - message: check3.message - }); - status.dirty(); - } - } else if (check3.kind === "cuid2") { - if (!cuid2Regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "cuid2", - code: ZodIssueCode.invalid_string, - message: check3.message - }); - status.dirty(); - } - } else if (check3.kind === "ulid") { - if (!ulidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "ulid", - code: ZodIssueCode.invalid_string, - message: check3.message - }); - status.dirty(); - } - } else if (check3.kind === "url") { - try { - new URL(input.data); - } catch { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "url", - code: ZodIssueCode.invalid_string, - message: check3.message - }); - status.dirty(); - } - } else if (check3.kind === "regex") { - check3.regex.lastIndex = 0; - const testResult = check3.regex.test(input.data); - if (!testResult) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "regex", - code: ZodIssueCode.invalid_string, - message: check3.message - }); - status.dirty(); - } - } else if (check3.kind === "trim") { - input.data = input.data.trim(); - } else if (check3.kind === "includes") { - if (!input.data.includes(check3.value, check3.position)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: { includes: check3.value, position: check3.position }, - message: check3.message - }); - status.dirty(); - } - } else if (check3.kind === "toLowerCase") { - input.data = input.data.toLowerCase(); - } else if (check3.kind === "toUpperCase") { - input.data = input.data.toUpperCase(); - } else if (check3.kind === "startsWith") { - if (!input.data.startsWith(check3.value)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: { startsWith: check3.value }, - message: check3.message - }); - status.dirty(); - } - } else if (check3.kind === "endsWith") { - if (!input.data.endsWith(check3.value)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: { endsWith: check3.value }, - message: check3.message - }); - status.dirty(); - } - } else if (check3.kind === "datetime") { - const regex = datetimeRegex(check3); - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: "datetime", - message: check3.message - }); - status.dirty(); - } - } else if (check3.kind === "date") { - const regex = dateRegex; - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: "date", - message: check3.message - }); - status.dirty(); - } - } else if (check3.kind === "time") { - const regex = timeRegex(check3); - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: "time", - message: check3.message - }); - status.dirty(); - } - } else if (check3.kind === "duration") { - if (!durationRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "duration", - code: ZodIssueCode.invalid_string, - message: check3.message - }); - status.dirty(); - } - } else if (check3.kind === "ip") { - if (!isValidIP(input.data, check3.version)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "ip", - code: ZodIssueCode.invalid_string, - message: check3.message - }); - status.dirty(); - } - } else if (check3.kind === "jwt") { - if (!isValidJWT(input.data, check3.alg)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "jwt", - code: ZodIssueCode.invalid_string, - message: check3.message - }); - status.dirty(); - } - } else if (check3.kind === "cidr") { - if (!isValidCidr(input.data, check3.version)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "cidr", - code: ZodIssueCode.invalid_string, - message: check3.message - }); - status.dirty(); - } - } else if (check3.kind === "base64") { - if (!base64Regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "base64", - code: ZodIssueCode.invalid_string, - message: check3.message - }); - status.dirty(); - } - } else if (check3.kind === "base64url") { - if (!base64urlRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "base64url", - code: ZodIssueCode.invalid_string, - message: check3.message - }); - status.dirty(); - } - } else { - util.assertNever(check3); - } - } - return { status: status.value, value: input.data }; - } - _regex(regex, validation, message2) { - return this.refinement((data2) => regex.test(data2), { - validation, - code: ZodIssueCode.invalid_string, - ...errorUtil.errToObj(message2) - }); - } - _addCheck(check3) { - return new _ZodString2({ - ...this._def, - checks: [...this._def.checks, check3] - }); - } - email(message2) { - return this._addCheck({ kind: "email", ...errorUtil.errToObj(message2) }); - } - url(message2) { - return this._addCheck({ kind: "url", ...errorUtil.errToObj(message2) }); - } - emoji(message2) { - return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message2) }); - } - uuid(message2) { - return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message2) }); - } - nanoid(message2) { - return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message2) }); - } - cuid(message2) { - return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message2) }); - } - cuid2(message2) { - return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message2) }); - } - ulid(message2) { - return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message2) }); - } - base64(message2) { - return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message2) }); - } - base64url(message2) { - return this._addCheck({ - kind: "base64url", - ...errorUtil.errToObj(message2) - }); - } - jwt(options) { - return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) }); - } - ip(options) { - return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) }); - } - cidr(options) { - return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) }); - } - datetime(options) { - if (typeof options === "string") { - return this._addCheck({ - kind: "datetime", - precision: null, - offset: false, - local: false, - message: options - }); - } - return this._addCheck({ - kind: "datetime", - precision: typeof options?.precision === "undefined" ? null : options?.precision, - offset: options?.offset ?? false, - local: options?.local ?? false, - ...errorUtil.errToObj(options?.message) - }); - } - date(message2) { - return this._addCheck({ kind: "date", message: message2 }); - } - time(options) { - if (typeof options === "string") { - return this._addCheck({ - kind: "time", - precision: null, - message: options - }); - } - return this._addCheck({ - kind: "time", - precision: typeof options?.precision === "undefined" ? null : options?.precision, - ...errorUtil.errToObj(options?.message) - }); - } - duration(message2) { - return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message2) }); - } - regex(regex, message2) { - return this._addCheck({ - kind: "regex", - regex, - ...errorUtil.errToObj(message2) - }); - } - includes(value, options) { - return this._addCheck({ - kind: "includes", - value, - position: options?.position, - ...errorUtil.errToObj(options?.message) - }); - } - startsWith(value, message2) { - return this._addCheck({ - kind: "startsWith", - value, - ...errorUtil.errToObj(message2) - }); - } - endsWith(value, message2) { - return this._addCheck({ - kind: "endsWith", - value, - ...errorUtil.errToObj(message2) - }); - } - min(minLength, message2) { - return this._addCheck({ - kind: "min", - value: minLength, - ...errorUtil.errToObj(message2) - }); - } - max(maxLength, message2) { - return this._addCheck({ - kind: "max", - value: maxLength, - ...errorUtil.errToObj(message2) - }); - } - length(len, message2) { - return this._addCheck({ - kind: "length", - value: len, - ...errorUtil.errToObj(message2) - }); - } - /** - * Equivalent to `.min(1)` - */ - nonempty(message2) { - return this.min(1, errorUtil.errToObj(message2)); - } - trim() { - return new _ZodString2({ - ...this._def, - checks: [...this._def.checks, { kind: "trim" }] - }); - } - toLowerCase() { - return new _ZodString2({ - ...this._def, - checks: [...this._def.checks, { kind: "toLowerCase" }] - }); - } - toUpperCase() { - return new _ZodString2({ - ...this._def, - checks: [...this._def.checks, { kind: "toUpperCase" }] - }); - } - get isDatetime() { - return !!this._def.checks.find((ch) => ch.kind === "datetime"); - } - get isDate() { - return !!this._def.checks.find((ch) => ch.kind === "date"); - } - get isTime() { - return !!this._def.checks.find((ch) => ch.kind === "time"); - } - get isDuration() { - return !!this._def.checks.find((ch) => ch.kind === "duration"); - } - get isEmail() { - return !!this._def.checks.find((ch) => ch.kind === "email"); - } - get isURL() { - return !!this._def.checks.find((ch) => ch.kind === "url"); - } - get isEmoji() { - return !!this._def.checks.find((ch) => ch.kind === "emoji"); - } - get isUUID() { - return !!this._def.checks.find((ch) => ch.kind === "uuid"); - } - get isNANOID() { - return !!this._def.checks.find((ch) => ch.kind === "nanoid"); - } - get isCUID() { - return !!this._def.checks.find((ch) => ch.kind === "cuid"); - } - get isCUID2() { - return !!this._def.checks.find((ch) => ch.kind === "cuid2"); - } - get isULID() { - return !!this._def.checks.find((ch) => ch.kind === "ulid"); - } - get isIP() { - return !!this._def.checks.find((ch) => ch.kind === "ip"); - } - get isCIDR() { - return !!this._def.checks.find((ch) => ch.kind === "cidr"); - } - get isBase64() { - return !!this._def.checks.find((ch) => ch.kind === "base64"); - } - get isBase64url() { - return !!this._def.checks.find((ch) => ch.kind === "base64url"); - } - get minLength() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min; - } - get maxLength() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max; - } -}; -ZodString.create = (params) => { - return new ZodString({ - checks: [], - typeName: ZodFirstPartyTypeKind.ZodString, - coerce: params?.coerce ?? false, - ...processCreateParams(params) - }); -}; -function floatSafeRemainder(val, step) { - const valDecCount = (val.toString().split(".")[1] || "").length; - const stepDecCount = (step.toString().split(".")[1] || "").length; - const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; - const valInt = Number.parseInt(val.toFixed(decCount).replace(".", "")); - const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", "")); - return valInt % stepInt / 10 ** decCount; -} -var ZodNumber = class _ZodNumber extends ZodType { - constructor() { - super(...arguments); - this.min = this.gte; - this.max = this.lte; - this.step = this.multipleOf; - } - _parse(input) { - if (this._def.coerce) { - input.data = Number(input.data); - } - const parsedType2 = this._getType(input); - if (parsedType2 !== ZodParsedType.number) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext(ctx2, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.number, - received: ctx2.parsedType - }); - return INVALID; - } - let ctx = void 0; - const status = new ParseStatus(); - for (const check3 of this._def.checks) { - if (check3.kind === "int") { - if (!util.isInteger(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: "integer", - received: "float", - message: check3.message - }); - status.dirty(); - } - } else if (check3.kind === "min") { - const tooSmall = check3.inclusive ? input.data < check3.value : input.data <= check3.value; - if (tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: check3.value, - type: "number", - inclusive: check3.inclusive, - exact: false, - message: check3.message - }); - status.dirty(); - } - } else if (check3.kind === "max") { - const tooBig = check3.inclusive ? input.data > check3.value : input.data >= check3.value; - if (tooBig) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: check3.value, - type: "number", - inclusive: check3.inclusive, - exact: false, - message: check3.message - }); - status.dirty(); - } - } else if (check3.kind === "multipleOf") { - if (floatSafeRemainder(input.data, check3.value) !== 0) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.not_multiple_of, - multipleOf: check3.value, - message: check3.message - }); - status.dirty(); - } - } else if (check3.kind === "finite") { - if (!Number.isFinite(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.not_finite, - message: check3.message - }); - status.dirty(); - } - } else { - util.assertNever(check3); - } - } - return { status: status.value, value: input.data }; - } - gte(value, message2) { - return this.setLimit("min", value, true, errorUtil.toString(message2)); - } - gt(value, message2) { - return this.setLimit("min", value, false, errorUtil.toString(message2)); - } - lte(value, message2) { - return this.setLimit("max", value, true, errorUtil.toString(message2)); - } - lt(value, message2) { - return this.setLimit("max", value, false, errorUtil.toString(message2)); - } - setLimit(kind, value, inclusive, message2) { - return new _ZodNumber({ - ...this._def, - checks: [ - ...this._def.checks, - { - kind, - value, - inclusive, - message: errorUtil.toString(message2) - } - ] - }); - } - _addCheck(check3) { - return new _ZodNumber({ - ...this._def, - checks: [...this._def.checks, check3] - }); - } - int(message2) { - return this._addCheck({ - kind: "int", - message: errorUtil.toString(message2) - }); - } - positive(message2) { - return this._addCheck({ - kind: "min", - value: 0, - inclusive: false, - message: errorUtil.toString(message2) - }); - } - negative(message2) { - return this._addCheck({ - kind: "max", - value: 0, - inclusive: false, - message: errorUtil.toString(message2) - }); - } - nonpositive(message2) { - return this._addCheck({ - kind: "max", - value: 0, - inclusive: true, - message: errorUtil.toString(message2) - }); - } - nonnegative(message2) { - return this._addCheck({ - kind: "min", - value: 0, - inclusive: true, - message: errorUtil.toString(message2) - }); - } - multipleOf(value, message2) { - return this._addCheck({ - kind: "multipleOf", - value, - message: errorUtil.toString(message2) - }); - } - finite(message2) { - return this._addCheck({ - kind: "finite", - message: errorUtil.toString(message2) - }); - } - safe(message2) { - return this._addCheck({ - kind: "min", - inclusive: true, - value: Number.MIN_SAFE_INTEGER, - message: errorUtil.toString(message2) - })._addCheck({ - kind: "max", - inclusive: true, - value: Number.MAX_SAFE_INTEGER, - message: errorUtil.toString(message2) - }); - } - get minValue() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min; - } - get maxValue() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max; - } - get isInt() { - return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value)); - } - get isFinite() { - let max = null; - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") { - return true; - } else if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } else if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return Number.isFinite(min) && Number.isFinite(max); - } -}; -ZodNumber.create = (params) => { - return new ZodNumber({ - checks: [], - typeName: ZodFirstPartyTypeKind.ZodNumber, - coerce: params?.coerce || false, - ...processCreateParams(params) - }); -}; -var ZodBigInt = class _ZodBigInt extends ZodType { - constructor() { - super(...arguments); - this.min = this.gte; - this.max = this.lte; - } - _parse(input) { - if (this._def.coerce) { - try { - input.data = BigInt(input.data); - } catch { - return this._getInvalidInput(input); - } - } - const parsedType2 = this._getType(input); - if (parsedType2 !== ZodParsedType.bigint) { - return this._getInvalidInput(input); - } - let ctx = void 0; - const status = new ParseStatus(); - for (const check3 of this._def.checks) { - if (check3.kind === "min") { - const tooSmall = check3.inclusive ? input.data < check3.value : input.data <= check3.value; - if (tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - type: "bigint", - minimum: check3.value, - inclusive: check3.inclusive, - message: check3.message - }); - status.dirty(); - } - } else if (check3.kind === "max") { - const tooBig = check3.inclusive ? input.data > check3.value : input.data >= check3.value; - if (tooBig) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - type: "bigint", - maximum: check3.value, - inclusive: check3.inclusive, - message: check3.message - }); - status.dirty(); - } - } else if (check3.kind === "multipleOf") { - if (input.data % check3.value !== BigInt(0)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.not_multiple_of, - multipleOf: check3.value, - message: check3.message - }); - status.dirty(); - } - } else { - util.assertNever(check3); - } - } - return { status: status.value, value: input.data }; - } - _getInvalidInput(input) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.bigint, - received: ctx.parsedType - }); - return INVALID; - } - gte(value, message2) { - return this.setLimit("min", value, true, errorUtil.toString(message2)); - } - gt(value, message2) { - return this.setLimit("min", value, false, errorUtil.toString(message2)); - } - lte(value, message2) { - return this.setLimit("max", value, true, errorUtil.toString(message2)); - } - lt(value, message2) { - return this.setLimit("max", value, false, errorUtil.toString(message2)); - } - setLimit(kind, value, inclusive, message2) { - return new _ZodBigInt({ - ...this._def, - checks: [ - ...this._def.checks, - { - kind, - value, - inclusive, - message: errorUtil.toString(message2) - } - ] - }); - } - _addCheck(check3) { - return new _ZodBigInt({ - ...this._def, - checks: [...this._def.checks, check3] - }); - } - positive(message2) { - return this._addCheck({ - kind: "min", - value: BigInt(0), - inclusive: false, - message: errorUtil.toString(message2) - }); - } - negative(message2) { - return this._addCheck({ - kind: "max", - value: BigInt(0), - inclusive: false, - message: errorUtil.toString(message2) - }); - } - nonpositive(message2) { - return this._addCheck({ - kind: "max", - value: BigInt(0), - inclusive: true, - message: errorUtil.toString(message2) - }); - } - nonnegative(message2) { - return this._addCheck({ - kind: "min", - value: BigInt(0), - inclusive: true, - message: errorUtil.toString(message2) - }); - } - multipleOf(value, message2) { - return this._addCheck({ - kind: "multipleOf", - value, - message: errorUtil.toString(message2) - }); - } - get minValue() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min; - } - get maxValue() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max; - } -}; -ZodBigInt.create = (params) => { - return new ZodBigInt({ - checks: [], - typeName: ZodFirstPartyTypeKind.ZodBigInt, - coerce: params?.coerce ?? false, - ...processCreateParams(params) - }); -}; -var ZodBoolean = class extends ZodType { - _parse(input) { - if (this._def.coerce) { - input.data = Boolean(input.data); - } - const parsedType2 = this._getType(input); - if (parsedType2 !== ZodParsedType.boolean) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.boolean, - received: ctx.parsedType - }); - return INVALID; - } - return OK(input.data); - } -}; -ZodBoolean.create = (params) => { - return new ZodBoolean({ - typeName: ZodFirstPartyTypeKind.ZodBoolean, - coerce: params?.coerce || false, - ...processCreateParams(params) - }); -}; -var ZodDate = class _ZodDate extends ZodType { - _parse(input) { - if (this._def.coerce) { - input.data = new Date(input.data); - } - const parsedType2 = this._getType(input); - if (parsedType2 !== ZodParsedType.date) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext(ctx2, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.date, - received: ctx2.parsedType - }); - return INVALID; - } - if (Number.isNaN(input.data.getTime())) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext(ctx2, { - code: ZodIssueCode.invalid_date - }); - return INVALID; - } - const status = new ParseStatus(); - let ctx = void 0; - for (const check3 of this._def.checks) { - if (check3.kind === "min") { - if (input.data.getTime() < check3.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - message: check3.message, - inclusive: true, - exact: false, - minimum: check3.value, - type: "date" - }); - status.dirty(); - } - } else if (check3.kind === "max") { - if (input.data.getTime() > check3.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - message: check3.message, - inclusive: true, - exact: false, - maximum: check3.value, - type: "date" - }); - status.dirty(); - } - } else { - util.assertNever(check3); - } - } - return { - status: status.value, - value: new Date(input.data.getTime()) - }; - } - _addCheck(check3) { - return new _ZodDate({ - ...this._def, - checks: [...this._def.checks, check3] - }); - } - min(minDate, message2) { - return this._addCheck({ - kind: "min", - value: minDate.getTime(), - message: errorUtil.toString(message2) - }); - } - max(maxDate, message2) { - return this._addCheck({ - kind: "max", - value: maxDate.getTime(), - message: errorUtil.toString(message2) - }); - } - get minDate() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min != null ? new Date(min) : null; - } - get maxDate() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max != null ? new Date(max) : null; - } -}; -ZodDate.create = (params) => { - return new ZodDate({ - checks: [], - coerce: params?.coerce || false, - typeName: ZodFirstPartyTypeKind.ZodDate, - ...processCreateParams(params) - }); -}; -var ZodSymbol = class extends ZodType { - _parse(input) { - const parsedType2 = this._getType(input); - if (parsedType2 !== ZodParsedType.symbol) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.symbol, - received: ctx.parsedType - }); - return INVALID; - } - return OK(input.data); - } -}; -ZodSymbol.create = (params) => { - return new ZodSymbol({ - typeName: ZodFirstPartyTypeKind.ZodSymbol, - ...processCreateParams(params) - }); -}; -var ZodUndefined = class extends ZodType { - _parse(input) { - const parsedType2 = this._getType(input); - if (parsedType2 !== ZodParsedType.undefined) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.undefined, - received: ctx.parsedType - }); - return INVALID; - } - return OK(input.data); - } -}; -ZodUndefined.create = (params) => { - return new ZodUndefined({ - typeName: ZodFirstPartyTypeKind.ZodUndefined, - ...processCreateParams(params) - }); -}; -var ZodNull = class extends ZodType { - _parse(input) { - const parsedType2 = this._getType(input); - if (parsedType2 !== ZodParsedType.null) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.null, - received: ctx.parsedType - }); - return INVALID; - } - return OK(input.data); - } -}; -ZodNull.create = (params) => { - return new ZodNull({ - typeName: ZodFirstPartyTypeKind.ZodNull, - ...processCreateParams(params) - }); -}; -var ZodAny = class extends ZodType { - constructor() { - super(...arguments); - this._any = true; - } - _parse(input) { - return OK(input.data); - } -}; -ZodAny.create = (params) => { - return new ZodAny({ - typeName: ZodFirstPartyTypeKind.ZodAny, - ...processCreateParams(params) - }); -}; -var ZodUnknown = class extends ZodType { - constructor() { - super(...arguments); - this._unknown = true; - } - _parse(input) { - return OK(input.data); - } -}; -ZodUnknown.create = (params) => { - return new ZodUnknown({ - typeName: ZodFirstPartyTypeKind.ZodUnknown, - ...processCreateParams(params) - }); -}; -var ZodNever = class extends ZodType { - _parse(input) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.never, - received: ctx.parsedType - }); - return INVALID; - } -}; -ZodNever.create = (params) => { - return new ZodNever({ - typeName: ZodFirstPartyTypeKind.ZodNever, - ...processCreateParams(params) - }); -}; -var ZodVoid = class extends ZodType { - _parse(input) { - const parsedType2 = this._getType(input); - if (parsedType2 !== ZodParsedType.undefined) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.void, - received: ctx.parsedType - }); - return INVALID; - } - return OK(input.data); - } -}; -ZodVoid.create = (params) => { - return new ZodVoid({ - typeName: ZodFirstPartyTypeKind.ZodVoid, - ...processCreateParams(params) - }); -}; -var ZodArray = class _ZodArray extends ZodType { - _parse(input) { - const { ctx, status } = this._processInputParams(input); - const def = this._def; - if (ctx.parsedType !== ZodParsedType.array) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.array, - received: ctx.parsedType - }); - return INVALID; - } - if (def.exactLength !== null) { - const tooBig = ctx.data.length > def.exactLength.value; - const tooSmall = ctx.data.length < def.exactLength.value; - if (tooBig || tooSmall) { - addIssueToContext(ctx, { - code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small, - minimum: tooSmall ? def.exactLength.value : void 0, - maximum: tooBig ? def.exactLength.value : void 0, - type: "array", - inclusive: true, - exact: true, - message: def.exactLength.message - }); - status.dirty(); - } - } - if (def.minLength !== null) { - if (ctx.data.length < def.minLength.value) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: def.minLength.value, - type: "array", - inclusive: true, - exact: false, - message: def.minLength.message - }); - status.dirty(); - } - } - if (def.maxLength !== null) { - if (ctx.data.length > def.maxLength.value) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: def.maxLength.value, - type: "array", - inclusive: true, - exact: false, - message: def.maxLength.message - }); - status.dirty(); - } - } - if (ctx.common.async) { - return Promise.all([...ctx.data].map((item, i5) => { - return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i5)); - })).then((result2) => { - return ParseStatus.mergeArray(status, result2); - }); - } - const result = [...ctx.data].map((item, i5) => { - return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i5)); - }); - return ParseStatus.mergeArray(status, result); - } - get element() { - return this._def.type; - } - min(minLength, message2) { - return new _ZodArray({ - ...this._def, - minLength: { value: minLength, message: errorUtil.toString(message2) } - }); - } - max(maxLength, message2) { - return new _ZodArray({ - ...this._def, - maxLength: { value: maxLength, message: errorUtil.toString(message2) } - }); - } - length(len, message2) { - return new _ZodArray({ - ...this._def, - exactLength: { value: len, message: errorUtil.toString(message2) } - }); - } - nonempty(message2) { - return this.min(1, message2); - } -}; -ZodArray.create = (schema2, params) => { - return new ZodArray({ - type: schema2, - minLength: null, - maxLength: null, - exactLength: null, - typeName: ZodFirstPartyTypeKind.ZodArray, - ...processCreateParams(params) - }); -}; -function deepPartialify(schema2) { - if (schema2 instanceof ZodObject) { - const newShape = {}; - for (const key in schema2.shape) { - const fieldSchema = schema2.shape[key]; - newShape[key] = ZodOptional.create(deepPartialify(fieldSchema)); - } - return new ZodObject({ - ...schema2._def, - shape: () => newShape - }); - } else if (schema2 instanceof ZodArray) { - return new ZodArray({ - ...schema2._def, - type: deepPartialify(schema2.element) - }); - } else if (schema2 instanceof ZodOptional) { - return ZodOptional.create(deepPartialify(schema2.unwrap())); - } else if (schema2 instanceof ZodNullable) { - return ZodNullable.create(deepPartialify(schema2.unwrap())); - } else if (schema2 instanceof ZodTuple) { - return ZodTuple.create(schema2.items.map((item) => deepPartialify(item))); - } else { - return schema2; - } -} -var ZodObject = class _ZodObject extends ZodType { - constructor() { - super(...arguments); - this._cached = null; - this.nonstrict = this.passthrough; - this.augment = this.extend; - } - _getCached() { - if (this._cached !== null) - return this._cached; - const shape = this._def.shape(); - const keys = util.objectKeys(shape); - this._cached = { shape, keys }; - return this._cached; - } - _parse(input) { - const parsedType2 = this._getType(input); - if (parsedType2 !== ZodParsedType.object) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext(ctx2, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.object, - received: ctx2.parsedType - }); - return INVALID; - } - const { status, ctx } = this._processInputParams(input); - const { shape, keys: shapeKeys } = this._getCached(); - const extraKeys = []; - if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) { - for (const key in ctx.data) { - if (!shapeKeys.includes(key)) { - extraKeys.push(key); - } - } - } - const pairs = []; - for (const key of shapeKeys) { - const keyValidator = shape[key]; - const value = ctx.data[key]; - pairs.push({ - key: { status: "valid", value: key }, - value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)), - alwaysSet: key in ctx.data - }); - } - if (this._def.catchall instanceof ZodNever) { - const unknownKeys = this._def.unknownKeys; - if (unknownKeys === "passthrough") { - for (const key of extraKeys) { - pairs.push({ - key: { status: "valid", value: key }, - value: { status: "valid", value: ctx.data[key] } - }); - } - } else if (unknownKeys === "strict") { - if (extraKeys.length > 0) { - addIssueToContext(ctx, { - code: ZodIssueCode.unrecognized_keys, - keys: extraKeys - }); - status.dirty(); - } - } else if (unknownKeys === "strip") { - } else { - throw new Error(`Internal ZodObject error: invalid unknownKeys value.`); - } - } else { - const catchall = this._def.catchall; - for (const key of extraKeys) { - const value = ctx.data[key]; - pairs.push({ - key: { status: "valid", value: key }, - value: catchall._parse( - new ParseInputLazyPath(ctx, value, ctx.path, key) - //, ctx.child(key), value, getParsedType(value) - ), - alwaysSet: key in ctx.data - }); - } - } - if (ctx.common.async) { - return Promise.resolve().then(async () => { - const syncPairs = []; - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - syncPairs.push({ - key, - value, - alwaysSet: pair.alwaysSet - }); - } - return syncPairs; - }).then((syncPairs) => { - return ParseStatus.mergeObjectSync(status, syncPairs); - }); - } else { - return ParseStatus.mergeObjectSync(status, pairs); - } - } - get shape() { - return this._def.shape(); - } - strict(message2) { - errorUtil.errToObj; - return new _ZodObject({ - ...this._def, - unknownKeys: "strict", - ...message2 !== void 0 ? { - errorMap: (issue2, ctx) => { - const defaultError = this._def.errorMap?.(issue2, ctx).message ?? ctx.defaultError; - if (issue2.code === "unrecognized_keys") - return { - message: errorUtil.errToObj(message2).message ?? defaultError - }; - return { - message: defaultError - }; - } - } : {} - }); - } - strip() { - return new _ZodObject({ - ...this._def, - unknownKeys: "strip" - }); - } - passthrough() { - return new _ZodObject({ - ...this._def, - unknownKeys: "passthrough" - }); - } - // const AugmentFactory = - // (def: Def) => - // ( - // augmentation: Augmentation - // ): ZodObject< - // extendShape, Augmentation>, - // Def["unknownKeys"], - // Def["catchall"] - // > => { - // return new ZodObject({ - // ...def, - // shape: () => ({ - // ...def.shape(), - // ...augmentation, - // }), - // }) as any; - // }; - extend(augmentation) { - return new _ZodObject({ - ...this._def, - shape: () => ({ - ...this._def.shape(), - ...augmentation - }) - }); - } - /** - * Prior to zod@1.0.12 there was a bug in the - * inferred type of merged objects. Please - * upgrade if you are experiencing issues. - */ - merge(merging) { - const merged = new _ZodObject({ - unknownKeys: merging._def.unknownKeys, - catchall: merging._def.catchall, - shape: () => ({ - ...this._def.shape(), - ...merging._def.shape() - }), - typeName: ZodFirstPartyTypeKind.ZodObject - }); - return merged; - } - // merge< - // Incoming extends AnyZodObject, - // Augmentation extends Incoming["shape"], - // NewOutput extends { - // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation - // ? Augmentation[k]["_output"] - // : k extends keyof Output - // ? Output[k] - // : never; - // }, - // NewInput extends { - // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation - // ? Augmentation[k]["_input"] - // : k extends keyof Input - // ? Input[k] - // : never; - // } - // >( - // merging: Incoming - // ): ZodObject< - // extendShape>, - // Incoming["_def"]["unknownKeys"], - // Incoming["_def"]["catchall"], - // NewOutput, - // NewInput - // > { - // const merged: any = new ZodObject({ - // unknownKeys: merging._def.unknownKeys, - // catchall: merging._def.catchall, - // shape: () => - // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), - // typeName: ZodFirstPartyTypeKind.ZodObject, - // }) as any; - // return merged; - // } - setKey(key, schema2) { - return this.augment({ [key]: schema2 }); - } - // merge( - // merging: Incoming - // ): //ZodObject = (merging) => { - // ZodObject< - // extendShape>, - // Incoming["_def"]["unknownKeys"], - // Incoming["_def"]["catchall"] - // > { - // // const mergedShape = objectUtil.mergeShapes( - // // this._def.shape(), - // // merging._def.shape() - // // ); - // const merged: any = new ZodObject({ - // unknownKeys: merging._def.unknownKeys, - // catchall: merging._def.catchall, - // shape: () => - // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), - // typeName: ZodFirstPartyTypeKind.ZodObject, - // }) as any; - // return merged; - // } - catchall(index2) { - return new _ZodObject({ - ...this._def, - catchall: index2 - }); - } - pick(mask) { - const shape = {}; - for (const key of util.objectKeys(mask)) { - if (mask[key] && this.shape[key]) { - shape[key] = this.shape[key]; - } - } - return new _ZodObject({ - ...this._def, - shape: () => shape - }); - } - omit(mask) { - const shape = {}; - for (const key of util.objectKeys(this.shape)) { - if (!mask[key]) { - shape[key] = this.shape[key]; - } - } - return new _ZodObject({ - ...this._def, - shape: () => shape - }); - } - /** - * @deprecated - */ - deepPartial() { - return deepPartialify(this); - } - partial(mask) { - const newShape = {}; - for (const key of util.objectKeys(this.shape)) { - const fieldSchema = this.shape[key]; - if (mask && !mask[key]) { - newShape[key] = fieldSchema; - } else { - newShape[key] = fieldSchema.optional(); - } - } - return new _ZodObject({ - ...this._def, - shape: () => newShape - }); - } - required(mask) { - const newShape = {}; - for (const key of util.objectKeys(this.shape)) { - if (mask && !mask[key]) { - newShape[key] = this.shape[key]; - } else { - const fieldSchema = this.shape[key]; - let newField = fieldSchema; - while (newField instanceof ZodOptional) { - newField = newField._def.innerType; - } - newShape[key] = newField; - } - } - return new _ZodObject({ - ...this._def, - shape: () => newShape - }); - } - keyof() { - return createZodEnum(util.objectKeys(this.shape)); - } -}; -ZodObject.create = (shape, params) => { - return new ZodObject({ - shape: () => shape, - unknownKeys: "strip", - catchall: ZodNever.create(), - typeName: ZodFirstPartyTypeKind.ZodObject, - ...processCreateParams(params) - }); -}; -ZodObject.strictCreate = (shape, params) => { - return new ZodObject({ - shape: () => shape, - unknownKeys: "strict", - catchall: ZodNever.create(), - typeName: ZodFirstPartyTypeKind.ZodObject, - ...processCreateParams(params) - }); -}; -ZodObject.lazycreate = (shape, params) => { - return new ZodObject({ - shape, - unknownKeys: "strip", - catchall: ZodNever.create(), - typeName: ZodFirstPartyTypeKind.ZodObject, - ...processCreateParams(params) - }); -}; -var ZodUnion = class extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - const options = this._def.options; - function handleResults(results) { - for (const result of results) { - if (result.result.status === "valid") { - return result.result; - } - } - for (const result of results) { - if (result.result.status === "dirty") { - ctx.common.issues.push(...result.ctx.common.issues); - return result.result; - } - } - const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues)); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_union, - unionErrors - }); - return INVALID; - } - if (ctx.common.async) { - return Promise.all(options.map(async (option) => { - const childCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [] - }, - parent: null - }; - return { - result: await option._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: childCtx - }), - ctx: childCtx - }; - })).then(handleResults); - } else { - let dirty = void 0; - const issues2 = []; - for (const option of options) { - const childCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [] - }, - parent: null - }; - const result = option._parseSync({ - data: ctx.data, - path: ctx.path, - parent: childCtx - }); - if (result.status === "valid") { - return result; - } else if (result.status === "dirty" && !dirty) { - dirty = { result, ctx: childCtx }; - } - if (childCtx.common.issues.length) { - issues2.push(childCtx.common.issues); - } - } - if (dirty) { - ctx.common.issues.push(...dirty.ctx.common.issues); - return dirty.result; - } - const unionErrors = issues2.map((issues3) => new ZodError(issues3)); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_union, - unionErrors - }); - return INVALID; - } - } - get options() { - return this._def.options; - } -}; -ZodUnion.create = (types2, params) => { - return new ZodUnion({ - options: types2, - typeName: ZodFirstPartyTypeKind.ZodUnion, - ...processCreateParams(params) - }); -}; -var getDiscriminator = (type) => { - if (type instanceof ZodLazy) { - return getDiscriminator(type.schema); - } else if (type instanceof ZodEffects) { - return getDiscriminator(type.innerType()); - } else if (type instanceof ZodLiteral) { - return [type.value]; - } else if (type instanceof ZodEnum) { - return type.options; - } else if (type instanceof ZodNativeEnum) { - return util.objectValues(type.enum); - } else if (type instanceof ZodDefault) { - return getDiscriminator(type._def.innerType); - } else if (type instanceof ZodUndefined) { - return [void 0]; - } else if (type instanceof ZodNull) { - return [null]; - } else if (type instanceof ZodOptional) { - return [void 0, ...getDiscriminator(type.unwrap())]; - } else if (type instanceof ZodNullable) { - return [null, ...getDiscriminator(type.unwrap())]; - } else if (type instanceof ZodBranded) { - return getDiscriminator(type.unwrap()); - } else if (type instanceof ZodReadonly) { - return getDiscriminator(type.unwrap()); - } else if (type instanceof ZodCatch) { - return getDiscriminator(type._def.innerType); - } else { - return []; - } -}; -var ZodDiscriminatedUnion = class _ZodDiscriminatedUnion extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.object) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.object, - received: ctx.parsedType - }); - return INVALID; - } - const discriminator = this.discriminator; - const discriminatorValue = ctx.data[discriminator]; - const option = this.optionsMap.get(discriminatorValue); - if (!option) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_union_discriminator, - options: Array.from(this.optionsMap.keys()), - path: [discriminator] - }); - return INVALID; - } - if (ctx.common.async) { - return option._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - } else { - return option._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - } - } - get discriminator() { - return this._def.discriminator; - } - get options() { - return this._def.options; - } - get optionsMap() { - return this._def.optionsMap; - } - /** - * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor. - * However, it only allows a union of objects, all of which need to share a discriminator property. This property must - * have a different value for each object in the union. - * @param discriminator the name of the discriminator property - * @param types an array of object schemas - * @param params - */ - static create(discriminator, options, params) { - const optionsMap = /* @__PURE__ */ new Map(); - for (const type of options) { - const discriminatorValues = getDiscriminator(type.shape[discriminator]); - if (!discriminatorValues.length) { - throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`); - } - for (const value of discriminatorValues) { - if (optionsMap.has(value)) { - throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`); - } - optionsMap.set(value, type); - } - } - return new _ZodDiscriminatedUnion({ - typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion, - discriminator, - options, - optionsMap, - ...processCreateParams(params) - }); - } -}; -function mergeValues(a5, b6) { - const aType = getParsedType(a5); - const bType = getParsedType(b6); - if (a5 === b6) { - return { valid: true, data: a5 }; - } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) { - const bKeys = util.objectKeys(b6); - const sharedKeys = util.objectKeys(a5).filter((key) => bKeys.indexOf(key) !== -1); - const newObj = { ...a5, ...b6 }; - for (const key of sharedKeys) { - const sharedValue = mergeValues(a5[key], b6[key]); - if (!sharedValue.valid) { - return { valid: false }; - } - newObj[key] = sharedValue.data; - } - return { valid: true, data: newObj }; - } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) { - if (a5.length !== b6.length) { - return { valid: false }; - } - const newArray = []; - for (let index2 = 0; index2 < a5.length; index2++) { - const itemA = a5[index2]; - const itemB = b6[index2]; - const sharedValue = mergeValues(itemA, itemB); - if (!sharedValue.valid) { - return { valid: false }; - } - newArray.push(sharedValue.data); - } - return { valid: true, data: newArray }; - } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a5 === +b6) { - return { valid: true, data: a5 }; - } else { - return { valid: false }; - } -} -var ZodIntersection = class extends ZodType { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - const handleParsed = (parsedLeft, parsedRight) => { - if (isAborted(parsedLeft) || isAborted(parsedRight)) { - return INVALID; - } - const merged = mergeValues(parsedLeft.value, parsedRight.value); - if (!merged.valid) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_intersection_types - }); - return INVALID; - } - if (isDirty(parsedLeft) || isDirty(parsedRight)) { - status.dirty(); - } - return { status: status.value, value: merged.data }; - }; - if (ctx.common.async) { - return Promise.all([ - this._def.left._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }), - this._def.right._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }) - ]).then(([left, right]) => handleParsed(left, right)); - } else { - return handleParsed(this._def.left._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }), this._def.right._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - })); - } - } -}; -ZodIntersection.create = (left, right, params) => { - return new ZodIntersection({ - left, - right, - typeName: ZodFirstPartyTypeKind.ZodIntersection, - ...processCreateParams(params) - }); -}; -var ZodTuple = class _ZodTuple extends ZodType { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.array) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.array, - received: ctx.parsedType - }); - return INVALID; - } - if (ctx.data.length < this._def.items.length) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: this._def.items.length, - inclusive: true, - exact: false, - type: "array" - }); - return INVALID; - } - const rest = this._def.rest; - if (!rest && ctx.data.length > this._def.items.length) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: this._def.items.length, - inclusive: true, - exact: false, - type: "array" - }); - status.dirty(); - } - const items = [...ctx.data].map((item, itemIndex) => { - const schema2 = this._def.items[itemIndex] || this._def.rest; - if (!schema2) - return null; - return schema2._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex)); - }).filter((x5) => !!x5); - if (ctx.common.async) { - return Promise.all(items).then((results) => { - return ParseStatus.mergeArray(status, results); - }); - } else { - return ParseStatus.mergeArray(status, items); - } - } - get items() { - return this._def.items; - } - rest(rest) { - return new _ZodTuple({ - ...this._def, - rest - }); - } -}; -ZodTuple.create = (schemas, params) => { - if (!Array.isArray(schemas)) { - throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); - } - return new ZodTuple({ - items: schemas, - typeName: ZodFirstPartyTypeKind.ZodTuple, - rest: null, - ...processCreateParams(params) - }); -}; -var ZodRecord = class _ZodRecord extends ZodType { - get keySchema() { - return this._def.keyType; - } - get valueSchema() { - return this._def.valueType; - } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.object) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.object, - received: ctx.parsedType - }); - return INVALID; - } - const pairs = []; - const keyType = this._def.keyType; - const valueType = this._def.valueType; - for (const key in ctx.data) { - pairs.push({ - key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)), - value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)), - alwaysSet: key in ctx.data - }); - } - if (ctx.common.async) { - return ParseStatus.mergeObjectAsync(status, pairs); - } else { - return ParseStatus.mergeObjectSync(status, pairs); - } - } - get element() { - return this._def.valueType; - } - static create(first, second, third) { - if (second instanceof ZodType) { - return new _ZodRecord({ - keyType: first, - valueType: second, - typeName: ZodFirstPartyTypeKind.ZodRecord, - ...processCreateParams(third) - }); - } - return new _ZodRecord({ - keyType: ZodString.create(), - valueType: first, - typeName: ZodFirstPartyTypeKind.ZodRecord, - ...processCreateParams(second) - }); - } -}; -var ZodMap = class extends ZodType { - get keySchema() { - return this._def.keyType; - } - get valueSchema() { - return this._def.valueType; - } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.map) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.map, - received: ctx.parsedType - }); - return INVALID; - } - const keyType = this._def.keyType; - const valueType = this._def.valueType; - const pairs = [...ctx.data.entries()].map(([key, value], index2) => { - return { - key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index2, "key"])), - value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index2, "value"])) - }; - }); - if (ctx.common.async) { - const finalMap = /* @__PURE__ */ new Map(); - return Promise.resolve().then(async () => { - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - if (key.status === "aborted" || value.status === "aborted") { - return INVALID; - } - if (key.status === "dirty" || value.status === "dirty") { - status.dirty(); - } - finalMap.set(key.value, value.value); - } - return { status: status.value, value: finalMap }; - }); - } else { - const finalMap = /* @__PURE__ */ new Map(); - for (const pair of pairs) { - const key = pair.key; - const value = pair.value; - if (key.status === "aborted" || value.status === "aborted") { - return INVALID; - } - if (key.status === "dirty" || value.status === "dirty") { - status.dirty(); - } - finalMap.set(key.value, value.value); - } - return { status: status.value, value: finalMap }; - } - } -}; -ZodMap.create = (keyType, valueType, params) => { - return new ZodMap({ - valueType, - keyType, - typeName: ZodFirstPartyTypeKind.ZodMap, - ...processCreateParams(params) - }); -}; -var ZodSet = class _ZodSet extends ZodType { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.set) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.set, - received: ctx.parsedType - }); - return INVALID; - } - const def = this._def; - if (def.minSize !== null) { - if (ctx.data.size < def.minSize.value) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: def.minSize.value, - type: "set", - inclusive: true, - exact: false, - message: def.minSize.message - }); - status.dirty(); - } - } - if (def.maxSize !== null) { - if (ctx.data.size > def.maxSize.value) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: def.maxSize.value, - type: "set", - inclusive: true, - exact: false, - message: def.maxSize.message - }); - status.dirty(); - } - } - const valueType = this._def.valueType; - function finalizeSet(elements2) { - const parsedSet = /* @__PURE__ */ new Set(); - for (const element of elements2) { - if (element.status === "aborted") - return INVALID; - if (element.status === "dirty") - status.dirty(); - parsedSet.add(element.value); - } - return { status: status.value, value: parsedSet }; - } - const elements = [...ctx.data.values()].map((item, i5) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i5))); - if (ctx.common.async) { - return Promise.all(elements).then((elements2) => finalizeSet(elements2)); - } else { - return finalizeSet(elements); - } - } - min(minSize, message2) { - return new _ZodSet({ - ...this._def, - minSize: { value: minSize, message: errorUtil.toString(message2) } - }); - } - max(maxSize, message2) { - return new _ZodSet({ - ...this._def, - maxSize: { value: maxSize, message: errorUtil.toString(message2) } - }); - } - size(size2, message2) { - return this.min(size2, message2).max(size2, message2); - } - nonempty(message2) { - return this.min(1, message2); - } -}; -ZodSet.create = (valueType, params) => { - return new ZodSet({ - valueType, - minSize: null, - maxSize: null, - typeName: ZodFirstPartyTypeKind.ZodSet, - ...processCreateParams(params) - }); -}; -var ZodFunction = class _ZodFunction extends ZodType { - constructor() { - super(...arguments); - this.validate = this.implement; - } - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.function) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.function, - received: ctx.parsedType - }); - return INVALID; - } - function makeArgsIssue(args, error50) { - return makeIssue({ - data: args, - path: ctx.path, - errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x5) => !!x5), - issueData: { - code: ZodIssueCode.invalid_arguments, - argumentsError: error50 - } - }); - } - function makeReturnsIssue(returns, error50) { - return makeIssue({ - data: returns, - path: ctx.path, - errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x5) => !!x5), - issueData: { - code: ZodIssueCode.invalid_return_type, - returnTypeError: error50 - } - }); - } - const params = { errorMap: ctx.common.contextualErrorMap }; - const fn = ctx.data; - if (this._def.returns instanceof ZodPromise) { - const me = this; - return OK(async function(...args) { - const error50 = new ZodError([]); - const parsedArgs = await me._def.args.parseAsync(args, params).catch((e5) => { - error50.addIssue(makeArgsIssue(args, e5)); - throw error50; - }); - const result = await Reflect.apply(fn, this, parsedArgs); - const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e5) => { - error50.addIssue(makeReturnsIssue(result, e5)); - throw error50; - }); - return parsedReturns; - }); - } else { - const me = this; - return OK(function(...args) { - const parsedArgs = me._def.args.safeParse(args, params); - if (!parsedArgs.success) { - throw new ZodError([makeArgsIssue(args, parsedArgs.error)]); - } - const result = Reflect.apply(fn, this, parsedArgs.data); - const parsedReturns = me._def.returns.safeParse(result, params); - if (!parsedReturns.success) { - throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]); - } - return parsedReturns.data; - }); - } - } - parameters() { - return this._def.args; - } - returnType() { - return this._def.returns; - } - args(...items) { - return new _ZodFunction({ - ...this._def, - args: ZodTuple.create(items).rest(ZodUnknown.create()) - }); - } - returns(returnType) { - return new _ZodFunction({ - ...this._def, - returns: returnType - }); - } - implement(func) { - const validatedFunc = this.parse(func); - return validatedFunc; - } - strictImplement(func) { - const validatedFunc = this.parse(func); - return validatedFunc; - } - static create(args, returns, params) { - return new _ZodFunction({ - args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()), - returns: returns || ZodUnknown.create(), - typeName: ZodFirstPartyTypeKind.ZodFunction, - ...processCreateParams(params) - }); - } -}; -var ZodLazy = class extends ZodType { - get schema() { - return this._def.getter(); - } - _parse(input) { - const { ctx } = this._processInputParams(input); - const lazySchema = this._def.getter(); - return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx }); - } -}; -ZodLazy.create = (getter, params) => { - return new ZodLazy({ - getter, - typeName: ZodFirstPartyTypeKind.ZodLazy, - ...processCreateParams(params) - }); -}; -var ZodLiteral = class extends ZodType { - _parse(input) { - if (input.data !== this._def.value) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - received: ctx.data, - code: ZodIssueCode.invalid_literal, - expected: this._def.value - }); - return INVALID; - } - return { status: "valid", value: input.data }; - } - get value() { - return this._def.value; - } -}; -ZodLiteral.create = (value, params) => { - return new ZodLiteral({ - value, - typeName: ZodFirstPartyTypeKind.ZodLiteral, - ...processCreateParams(params) - }); -}; -function createZodEnum(values2, params) { - return new ZodEnum({ - values: values2, - typeName: ZodFirstPartyTypeKind.ZodEnum, - ...processCreateParams(params) - }); -} -var ZodEnum = class _ZodEnum extends ZodType { - _parse(input) { - if (typeof input.data !== "string") { - const ctx = this._getOrReturnCtx(input); - const expectedValues = this._def.values; - addIssueToContext(ctx, { - expected: util.joinValues(expectedValues), - received: ctx.parsedType, - code: ZodIssueCode.invalid_type - }); - return INVALID; - } - if (!this._cache) { - this._cache = new Set(this._def.values); - } - if (!this._cache.has(input.data)) { - const ctx = this._getOrReturnCtx(input); - const expectedValues = this._def.values; - addIssueToContext(ctx, { - received: ctx.data, - code: ZodIssueCode.invalid_enum_value, - options: expectedValues - }); - return INVALID; - } - return OK(input.data); - } - get options() { - return this._def.values; - } - get enum() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; - } - get Values() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; - } - get Enum() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; - } - extract(values2, newDef = this._def) { - return _ZodEnum.create(values2, { - ...this._def, - ...newDef - }); - } - exclude(values2, newDef = this._def) { - return _ZodEnum.create(this.options.filter((opt) => !values2.includes(opt)), { - ...this._def, - ...newDef - }); - } -}; -ZodEnum.create = createZodEnum; -var ZodNativeEnum = class extends ZodType { - _parse(input) { - const nativeEnumValues = util.getValidEnumValues(this._def.values); - const ctx = this._getOrReturnCtx(input); - if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) { - const expectedValues = util.objectValues(nativeEnumValues); - addIssueToContext(ctx, { - expected: util.joinValues(expectedValues), - received: ctx.parsedType, - code: ZodIssueCode.invalid_type - }); - return INVALID; - } - if (!this._cache) { - this._cache = new Set(util.getValidEnumValues(this._def.values)); - } - if (!this._cache.has(input.data)) { - const expectedValues = util.objectValues(nativeEnumValues); - addIssueToContext(ctx, { - received: ctx.data, - code: ZodIssueCode.invalid_enum_value, - options: expectedValues - }); - return INVALID; - } - return OK(input.data); - } - get enum() { - return this._def.values; - } -}; -ZodNativeEnum.create = (values2, params) => { - return new ZodNativeEnum({ - values: values2, - typeName: ZodFirstPartyTypeKind.ZodNativeEnum, - ...processCreateParams(params) - }); -}; -var ZodPromise = class extends ZodType { - unwrap() { - return this._def.type; - } - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.promise, - received: ctx.parsedType - }); - return INVALID; - } - const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data); - return OK(promisified.then((data2) => { - return this._def.type.parseAsync(data2, { - path: ctx.path, - errorMap: ctx.common.contextualErrorMap - }); - })); - } -}; -ZodPromise.create = (schema2, params) => { - return new ZodPromise({ - type: schema2, - typeName: ZodFirstPartyTypeKind.ZodPromise, - ...processCreateParams(params) - }); -}; -var ZodEffects = class extends ZodType { - innerType() { - return this._def.schema; - } - sourceType() { - return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema; - } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - const effect = this._def.effect || null; - const checkCtx = { - addIssue: (arg) => { - addIssueToContext(ctx, arg); - if (arg.fatal) { - status.abort(); - } else { - status.dirty(); - } - }, - get path() { - return ctx.path; - } - }; - checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx); - if (effect.type === "preprocess") { - const processed = effect.transform(ctx.data, checkCtx); - if (ctx.common.async) { - return Promise.resolve(processed).then(async (processed2) => { - if (status.value === "aborted") - return INVALID; - const result = await this._def.schema._parseAsync({ - data: processed2, - path: ctx.path, - parent: ctx - }); - if (result.status === "aborted") - return INVALID; - if (result.status === "dirty") - return DIRTY(result.value); - if (status.value === "dirty") - return DIRTY(result.value); - return result; - }); - } else { - if (status.value === "aborted") - return INVALID; - const result = this._def.schema._parseSync({ - data: processed, - path: ctx.path, - parent: ctx - }); - if (result.status === "aborted") - return INVALID; - if (result.status === "dirty") - return DIRTY(result.value); - if (status.value === "dirty") - return DIRTY(result.value); - return result; - } - } - if (effect.type === "refinement") { - const executeRefinement = (acc) => { - const result = effect.refinement(acc, checkCtx); - if (ctx.common.async) { - return Promise.resolve(result); - } - if (result instanceof Promise) { - throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead."); - } - return acc; - }; - if (ctx.common.async === false) { - const inner = this._def.schema._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (inner.status === "aborted") - return INVALID; - if (inner.status === "dirty") - status.dirty(); - executeRefinement(inner.value); - return { status: status.value, value: inner.value }; - } else { - return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => { - if (inner.status === "aborted") - return INVALID; - if (inner.status === "dirty") - status.dirty(); - return executeRefinement(inner.value).then(() => { - return { status: status.value, value: inner.value }; - }); - }); - } - } - if (effect.type === "transform") { - if (ctx.common.async === false) { - const base = this._def.schema._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (!isValid(base)) - return INVALID; - const result = effect.transform(base.value, checkCtx); - if (result instanceof Promise) { - throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`); - } - return { status: status.value, value: result }; - } else { - return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => { - if (!isValid(base)) - return INVALID; - return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ - status: status.value, - value: result - })); - }); - } - } - util.assertNever(effect); - } -}; -ZodEffects.create = (schema2, effect, params) => { - return new ZodEffects({ - schema: schema2, - typeName: ZodFirstPartyTypeKind.ZodEffects, - effect, - ...processCreateParams(params) - }); -}; -ZodEffects.createWithPreprocess = (preprocess2, schema2, params) => { - return new ZodEffects({ - schema: schema2, - effect: { type: "preprocess", transform: preprocess2 }, - typeName: ZodFirstPartyTypeKind.ZodEffects, - ...processCreateParams(params) - }); -}; -var ZodOptional = class extends ZodType { - _parse(input) { - const parsedType2 = this._getType(input); - if (parsedType2 === ZodParsedType.undefined) { - return OK(void 0); - } - return this._def.innerType._parse(input); - } - unwrap() { - return this._def.innerType; - } -}; -ZodOptional.create = (type, params) => { - return new ZodOptional({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodOptional, - ...processCreateParams(params) - }); -}; -var ZodNullable = class extends ZodType { - _parse(input) { - const parsedType2 = this._getType(input); - if (parsedType2 === ZodParsedType.null) { - return OK(null); - } - return this._def.innerType._parse(input); - } - unwrap() { - return this._def.innerType; - } -}; -ZodNullable.create = (type, params) => { - return new ZodNullable({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodNullable, - ...processCreateParams(params) - }); -}; -var ZodDefault = class extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - let data2 = ctx.data; - if (ctx.parsedType === ZodParsedType.undefined) { - data2 = this._def.defaultValue(); - } - return this._def.innerType._parse({ - data: data2, - path: ctx.path, - parent: ctx - }); - } - removeDefault() { - return this._def.innerType; - } -}; -ZodDefault.create = (type, params) => { - return new ZodDefault({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodDefault, - defaultValue: typeof params.default === "function" ? params.default : () => params.default, - ...processCreateParams(params) - }); -}; -var ZodCatch = class extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - const newCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [] - } - }; - const result = this._def.innerType._parse({ - data: newCtx.data, - path: newCtx.path, - parent: { - ...newCtx - } - }); - if (isAsync(result)) { - return result.then((result2) => { - return { - status: "valid", - value: result2.status === "valid" ? result2.value : this._def.catchValue({ - get error() { - return new ZodError(newCtx.common.issues); - }, - input: newCtx.data - }) - }; - }); - } else { - return { - status: "valid", - value: result.status === "valid" ? result.value : this._def.catchValue({ - get error() { - return new ZodError(newCtx.common.issues); - }, - input: newCtx.data - }) - }; - } - } - removeCatch() { - return this._def.innerType; - } -}; -ZodCatch.create = (type, params) => { - return new ZodCatch({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodCatch, - catchValue: typeof params.catch === "function" ? params.catch : () => params.catch, - ...processCreateParams(params) - }); -}; -var ZodNaN = class extends ZodType { - _parse(input) { - const parsedType2 = this._getType(input); - if (parsedType2 !== ZodParsedType.nan) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.nan, - received: ctx.parsedType - }); - return INVALID; - } - return { status: "valid", value: input.data }; - } -}; -ZodNaN.create = (params) => { - return new ZodNaN({ - typeName: ZodFirstPartyTypeKind.ZodNaN, - ...processCreateParams(params) - }); -}; -var BRAND = /* @__PURE__ */ Symbol("zod_brand"); -var ZodBranded = class extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - const data2 = ctx.data; - return this._def.type._parse({ - data: data2, - path: ctx.path, - parent: ctx - }); - } - unwrap() { - return this._def.type; - } -}; -var ZodPipeline = class _ZodPipeline extends ZodType { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.common.async) { - const handleAsync = async () => { - const inResult = await this._def.in._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (inResult.status === "aborted") - return INVALID; - if (inResult.status === "dirty") { - status.dirty(); - return DIRTY(inResult.value); - } else { - return this._def.out._parseAsync({ - data: inResult.value, - path: ctx.path, - parent: ctx - }); - } - }; - return handleAsync(); - } else { - const inResult = this._def.in._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (inResult.status === "aborted") - return INVALID; - if (inResult.status === "dirty") { - status.dirty(); - return { - status: "dirty", - value: inResult.value - }; - } else { - return this._def.out._parseSync({ - data: inResult.value, - path: ctx.path, - parent: ctx - }); - } - } - } - static create(a5, b6) { - return new _ZodPipeline({ - in: a5, - out: b6, - typeName: ZodFirstPartyTypeKind.ZodPipeline - }); - } -}; -var ZodReadonly = class extends ZodType { - _parse(input) { - const result = this._def.innerType._parse(input); - const freeze3 = (data2) => { - if (isValid(data2)) { - data2.value = Object.freeze(data2.value); - } - return data2; - }; - return isAsync(result) ? result.then((data2) => freeze3(data2)) : freeze3(result); - } - unwrap() { - return this._def.innerType; - } -}; -ZodReadonly.create = (type, params) => { - return new ZodReadonly({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodReadonly, - ...processCreateParams(params) - }); -}; -function cleanParams(params, data2) { - const p5 = typeof params === "function" ? params(data2) : typeof params === "string" ? { message: params } : params; - const p22 = typeof p5 === "string" ? { message: p5 } : p5; - return p22; -} -function custom(check3, _params = {}, fatal) { - if (check3) - return ZodAny.create().superRefine((data2, ctx) => { - const r5 = check3(data2); - if (r5 instanceof Promise) { - return r5.then((r6) => { - if (!r6) { - const params = cleanParams(_params, data2); - const _fatal = params.fatal ?? fatal ?? true; - ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); - } - }); - } - if (!r5) { - const params = cleanParams(_params, data2); - const _fatal = params.fatal ?? fatal ?? true; - ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); - } - return; - }); - return ZodAny.create(); -} -var late = { - object: ZodObject.lazycreate -}; -var ZodFirstPartyTypeKind; -(function(ZodFirstPartyTypeKind3) { - ZodFirstPartyTypeKind3["ZodString"] = "ZodString"; - ZodFirstPartyTypeKind3["ZodNumber"] = "ZodNumber"; - ZodFirstPartyTypeKind3["ZodNaN"] = "ZodNaN"; - ZodFirstPartyTypeKind3["ZodBigInt"] = "ZodBigInt"; - ZodFirstPartyTypeKind3["ZodBoolean"] = "ZodBoolean"; - ZodFirstPartyTypeKind3["ZodDate"] = "ZodDate"; - ZodFirstPartyTypeKind3["ZodSymbol"] = "ZodSymbol"; - ZodFirstPartyTypeKind3["ZodUndefined"] = "ZodUndefined"; - ZodFirstPartyTypeKind3["ZodNull"] = "ZodNull"; - ZodFirstPartyTypeKind3["ZodAny"] = "ZodAny"; - ZodFirstPartyTypeKind3["ZodUnknown"] = "ZodUnknown"; - ZodFirstPartyTypeKind3["ZodNever"] = "ZodNever"; - ZodFirstPartyTypeKind3["ZodVoid"] = "ZodVoid"; - ZodFirstPartyTypeKind3["ZodArray"] = "ZodArray"; - ZodFirstPartyTypeKind3["ZodObject"] = "ZodObject"; - ZodFirstPartyTypeKind3["ZodUnion"] = "ZodUnion"; - ZodFirstPartyTypeKind3["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion"; - ZodFirstPartyTypeKind3["ZodIntersection"] = "ZodIntersection"; - ZodFirstPartyTypeKind3["ZodTuple"] = "ZodTuple"; - ZodFirstPartyTypeKind3["ZodRecord"] = "ZodRecord"; - ZodFirstPartyTypeKind3["ZodMap"] = "ZodMap"; - ZodFirstPartyTypeKind3["ZodSet"] = "ZodSet"; - ZodFirstPartyTypeKind3["ZodFunction"] = "ZodFunction"; - ZodFirstPartyTypeKind3["ZodLazy"] = "ZodLazy"; - ZodFirstPartyTypeKind3["ZodLiteral"] = "ZodLiteral"; - ZodFirstPartyTypeKind3["ZodEnum"] = "ZodEnum"; - ZodFirstPartyTypeKind3["ZodEffects"] = "ZodEffects"; - ZodFirstPartyTypeKind3["ZodNativeEnum"] = "ZodNativeEnum"; - ZodFirstPartyTypeKind3["ZodOptional"] = "ZodOptional"; - ZodFirstPartyTypeKind3["ZodNullable"] = "ZodNullable"; - ZodFirstPartyTypeKind3["ZodDefault"] = "ZodDefault"; - ZodFirstPartyTypeKind3["ZodCatch"] = "ZodCatch"; - ZodFirstPartyTypeKind3["ZodPromise"] = "ZodPromise"; - ZodFirstPartyTypeKind3["ZodBranded"] = "ZodBranded"; - ZodFirstPartyTypeKind3["ZodPipeline"] = "ZodPipeline"; - ZodFirstPartyTypeKind3["ZodReadonly"] = "ZodReadonly"; -})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {})); -var instanceOfType = (cls, params = { - message: `Input not instance of ${cls.name}` -}) => custom((data2) => data2 instanceof cls, params); -var stringType = ZodString.create; -var numberType = ZodNumber.create; -var nanType = ZodNaN.create; -var bigIntType = ZodBigInt.create; -var booleanType = ZodBoolean.create; -var dateType = ZodDate.create; -var symbolType = ZodSymbol.create; -var undefinedType = ZodUndefined.create; -var nullType = ZodNull.create; -var anyType = ZodAny.create; -var unknownType = ZodUnknown.create; -var neverType = ZodNever.create; -var voidType = ZodVoid.create; -var arrayType = ZodArray.create; -var objectType = ZodObject.create; -var strictObjectType = ZodObject.strictCreate; -var unionType = ZodUnion.create; -var discriminatedUnionType = ZodDiscriminatedUnion.create; -var intersectionType = ZodIntersection.create; -var tupleType = ZodTuple.create; -var recordType = ZodRecord.create; -var mapType = ZodMap.create; -var setType = ZodSet.create; -var functionType = ZodFunction.create; -var lazyType = ZodLazy.create; -var literalType = ZodLiteral.create; -var enumType = ZodEnum.create; -var nativeEnumType = ZodNativeEnum.create; -var promiseType = ZodPromise.create; -var effectsType = ZodEffects.create; -var optionalType = ZodOptional.create; -var nullableType = ZodNullable.create; -var preprocessType = ZodEffects.createWithPreprocess; -var pipelineType = ZodPipeline.create; -var ostring = () => stringType().optional(); -var onumber = () => numberType().optional(); -var oboolean = () => booleanType().optional(); -var coerce = { - string: ((arg) => ZodString.create({ ...arg, coerce: true })), - number: ((arg) => ZodNumber.create({ ...arg, coerce: true })), - boolean: ((arg) => ZodBoolean.create({ - ...arg, - coerce: true - })), - bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })), - date: ((arg) => ZodDate.create({ ...arg, coerce: true })) -}; -var NEVER = INVALID; - -// packages/shared/src/constants.ts -var COMPANY_STATUSES = ["active", "paused", "archived"]; -var DEPLOYMENT_MODES = ["local_trusted", "authenticated"]; -var DEPLOYMENT_EXPOSURES = ["private", "public"]; -var BIND_MODES = ["loopback", "lan", "tailnet", "custom"]; -var AUTH_BASE_URL_MODES = ["auto", "explicit"]; -var AGENT_STATUSES = [ - "active", - "paused", - "idle", - "running", - "error", - "pending_approval", - "terminated" -]; -var AGENT_ADAPTER_TYPES = [ - "process", - "http", - "claude_local", - "codex_local", - "gemini_local", - "opencode_local", - "pi_local", - "cursor", - "openclaw_gateway" -]; -var AGENT_ROLES = [ - "ceo", - "cto", - "cmo", - "cfo", - "engineer", - "designer", - "pm", - "qa", - "devops", - "researcher", - "general" -]; -var AGENT_ICON_NAMES = [ - "bot", - "cpu", - "brain", - "zap", - "rocket", - "code", - "terminal", - "shield", - "eye", - "search", - "wrench", - "hammer", - "lightbulb", - "sparkles", - "star", - "heart", - "flame", - "bug", - "cog", - "database", - "globe", - "lock", - "mail", - "message-square", - "file-code", - "git-branch", - "package", - "puzzle", - "target", - "wand", - "atom", - "circuit-board", - "radar", - "swords", - "telescope", - "microscope", - "crown", - "gem", - "hexagon", - "pentagon", - "fingerprint" -]; -var ISSUE_STATUSES = [ - "backlog", - "todo", - "in_progress", - "in_review", - "done", - "blocked", - "cancelled" -]; -var INBOX_MINE_ISSUE_STATUSES = [ - "backlog", - "todo", - "in_progress", - "in_review", - "blocked", - "done" -]; -var INBOX_MINE_ISSUE_STATUS_FILTER = INBOX_MINE_ISSUE_STATUSES.join(","); -var ISSUE_PRIORITIES = ["critical", "high", "medium", "low"]; -var ISSUE_EXECUTION_POLICY_MODES = ["normal", "auto"]; -var ISSUE_EXECUTION_STAGE_TYPES = ["review", "approval"]; -var ISSUE_EXECUTION_STATE_STATUSES = ["idle", "pending", "changes_requested", "completed"]; -var ISSUE_EXECUTION_DECISION_OUTCOMES = ["approved", "changes_requested"]; -var GOAL_LEVELS = ["company", "team", "agent", "task"]; -var GOAL_STATUSES = ["planned", "active", "achieved", "cancelled"]; -var PROJECT_STATUSES = [ - "backlog", - "planned", - "in_progress", - "completed", - "cancelled" -]; -var ROUTINE_STATUSES = ["active", "paused", "archived"]; -var ROUTINE_CONCURRENCY_POLICIES = ["coalesce_if_active", "always_enqueue", "skip_if_active"]; -var ROUTINE_CATCH_UP_POLICIES = ["skip_missed", "enqueue_missed_with_cap"]; -var ROUTINE_TRIGGER_KINDS = ["schedule", "webhook", "api"]; -var ROUTINE_TRIGGER_SIGNING_MODES = ["bearer", "hmac_sha256", "github_hmac", "none"]; -var ROUTINE_VARIABLE_TYPES = ["text", "textarea", "number", "boolean", "select"]; -var PROJECT_COLORS = [ - "#6366f1", - // indigo - "#8b5cf6", - // violet - "#ec4899", - // pink - "#ef4444", - // red - "#f97316", - // orange - "#eab308", - // yellow - "#22c55e", - // green - "#14b8a6", - // teal - "#06b6d4", - // cyan - "#3b82f6" - // blue -]; -var APPROVAL_TYPES = [ - "hire_agent", - "approve_ceo_strategy", - "budget_override_required", - "request_board_approval" -]; -var SECRET_PROVIDERS = [ - "local_encrypted", - "aws_secrets_manager", - "gcp_secret_manager", - "vault" -]; -var STORAGE_PROVIDERS = ["local_disk", "s3"]; -var BILLING_TYPES = [ - "metered_api", - "subscription_included", - "subscription_overage", - "credits", - "fixed", - "unknown" -]; -var FINANCE_EVENT_KINDS = [ - "inference_charge", - "platform_fee", - "credit_purchase", - "credit_refund", - "credit_expiry", - "byok_fee", - "gateway_overhead", - "log_storage_charge", - "logpush_charge", - "provisioned_capacity_charge", - "training_charge", - "custom_model_import_charge", - "custom_model_storage_charge", - "manual_adjustment" -]; -var FINANCE_DIRECTIONS = ["debit", "credit"]; -var FINANCE_UNITS = [ - "input_token", - "output_token", - "cached_input_token", - "request", - "credit_usd", - "credit_unit", - "model_unit_minute", - "model_unit_hour", - "gb_month", - "train_token", - "unknown" -]; -var BUDGET_SCOPE_TYPES = ["company", "agent", "project"]; -var BUDGET_METRICS = ["billed_cents"]; -var BUDGET_WINDOW_KINDS = ["calendar_month_utc", "lifetime"]; -var BUDGET_INCIDENT_RESOLUTION_ACTIONS = [ - "keep_paused", - "raise_budget_and_resume" -]; -var INVITE_JOIN_TYPES = ["human", "agent", "both"]; -var JOIN_REQUEST_TYPES = ["human", "agent"]; -var JOIN_REQUEST_STATUSES = ["pending_approval", "approved", "rejected"]; -var PERMISSION_KEYS = [ - "agents:create", - "users:invite", - "users:manage_permissions", - "tasks:assign", - "tasks:assign_scope", - "joins:approve" -]; -var PLUGIN_API_VERSION = 1; -var PLUGIN_STATUSES = [ - "installed", - "ready", - "disabled", - "error", - "upgrade_pending", - "uninstalled" -]; -var PLUGIN_CATEGORIES = [ - "connector", - "workspace", - "automation", - "ui" -]; -var PLUGIN_CAPABILITIES = [ - // Data Read - "companies.read", - "projects.read", - "project.workspaces.read", - "issues.read", - "issue.comments.read", - "issue.documents.read", - "agents.read", - "goals.read", - "goals.create", - "goals.update", - "activity.read", - "costs.read", - // Data Write - "issues.create", - "issues.update", - "issue.comments.create", - "issue.documents.write", - "agents.pause", - "agents.resume", - "agents.invoke", - "agent.sessions.create", - "agent.sessions.list", - "agent.sessions.send", - "agent.sessions.close", - "activity.log.write", - "metrics.write", - "telemetry.track", - // Plugin State - "plugin.state.read", - "plugin.state.write", - // Runtime / Integration - "events.subscribe", - "events.emit", - "jobs.schedule", - "webhooks.receive", - "http.outbound", - "secrets.read-ref", - // Agent Tools - "agent.tools.register", - // UI - "instance.settings.register", - "ui.sidebar.register", - "ui.page.register", - "ui.detailTab.register", - "ui.dashboardWidget.register", - "ui.commentAnnotation.register", - "ui.action.register" -]; -var PLUGIN_UI_SLOT_TYPES = [ - "page", - "detailTab", - "taskDetailView", - "dashboardWidget", - "sidebar", - "sidebarPanel", - "projectSidebarItem", - "globalToolbarButton", - "toolbarButton", - "contextMenuItem", - "commentAnnotation", - "commentContextMenuItem", - "settingsPage" -]; -var PLUGIN_RESERVED_COMPANY_ROUTE_SEGMENTS = [ - "dashboard", - "onboarding", - "companies", - "company", - "settings", - "plugins", - "org", - "agents", - "projects", - "issues", - "goals", - "approvals", - "costs", - "activity", - "inbox", - "design-guide", - "tests" -]; -var PLUGIN_LAUNCHER_PLACEMENT_ZONES = [ - "page", - "detailTab", - "taskDetailView", - "dashboardWidget", - "sidebar", - "sidebarPanel", - "projectSidebarItem", - "globalToolbarButton", - "toolbarButton", - "contextMenuItem", - "commentAnnotation", - "commentContextMenuItem", - "settingsPage" -]; -var PLUGIN_LAUNCHER_ACTIONS = [ - "navigate", - "openModal", - "openDrawer", - "openPopover", - "performAction", - "deepLink" -]; -var PLUGIN_LAUNCHER_BOUNDS = [ - "inline", - "compact", - "default", - "wide", - "full" -]; -var PLUGIN_LAUNCHER_RENDER_ENVIRONMENTS = [ - "hostInline", - "hostOverlay", - "hostRoute", - "external", - "iframe" -]; -var PLUGIN_UI_SLOT_ENTITY_TYPES = [ - "project", - "issue", - "agent", - "goal", - "run", - "comment" -]; -var PLUGIN_STATE_SCOPE_KINDS = [ - "instance", - "company", - "project", - "project_workspace", - "agent", - "issue", - "goal", - "run" -]; -var PLUGIN_EVENT_TYPES = [ - "company.created", - "company.updated", - "project.created", - "project.updated", - "project.workspace_created", - "project.workspace_updated", - "project.workspace_deleted", - "issue.created", - "issue.updated", - "issue.comment.created", - "agent.created", - "agent.updated", - "agent.status_changed", - "agent.run.started", - "agent.run.finished", - "agent.run.failed", - "agent.run.cancelled", - "goal.created", - "goal.updated", - "approval.created", - "approval.decided", - "cost_event.created", - "activity.logged" -]; - -// packages/shared/src/adapter-type.ts -var agentAdapterTypeSchema = external_exports.string().trim().min(1).default("process").describe(`Known built-in adapters: ${AGENT_ADAPTER_TYPES.join(", ")}. External adapters may register additional non-empty string types at runtime.`); -var optionalAgentAdapterTypeSchema = external_exports.string().trim().min(1).optional(); - -// packages/shared/src/vercel-postgres.ts -function resolvePostgresUrlFromEnv() { - const direct = process.env.DATABASE_URL?.trim(); - if (direct) return direct; - const pooled = process.env.POSTGRES_URL?.trim(); - if (pooled) return pooled; - const nonPooling = process.env.POSTGRES_URL_NON_POOLING?.trim(); - if (nonPooling) return nonPooling; - const host = process.env.PGHOST?.trim(); - const database = process.env.PGDATABASE?.trim(); - if (!host || !database) return void 0; - const user = encodeURIComponent(process.env.PGUSER?.trim() || "postgres"); - const password = process.env.PGPASSWORD ? encodeURIComponent(process.env.PGPASSWORD) : ""; - const port = process.env.PGPORT?.trim() || "5432"; - const auth = `${user}${password ? `:${password}` : ""}`; - let url2 = `postgres://${auth}@${host}:${port}/${database}`; - const sslMode = process.env.PGSSLMODE?.trim(); - if (sslMode && sslMode !== "disable") { - url2 += "?sslmode=require"; - } - return url2; -} - -// packages/shared/src/network-bind.ts -var LOOPBACK_BIND_HOST = "127.0.0.1"; -var ALL_INTERFACES_BIND_HOST = "0.0.0.0"; -function normalizeHost(host) { - const trimmed = host?.trim(); - return trimmed ? trimmed : void 0; -} -function isLoopbackHost(host) { - const normalized = normalizeHost(host)?.toLowerCase(); - return normalized === "127.0.0.1" || normalized === "localhost" || normalized === "::1"; -} -function isAllInterfacesHost(host) { - const normalized = normalizeHost(host)?.toLowerCase(); - return normalized === "0.0.0.0" || normalized === "::"; -} -function inferBindModeFromHost(host, opts) { - const normalized = normalizeHost(host); - const tailnetBindHost = normalizeHost(opts?.tailnetBindHost); - if (!normalized || isLoopbackHost(normalized)) return "loopback"; - if (isAllInterfacesHost(normalized)) return "lan"; - if (tailnetBindHost && normalized === tailnetBindHost) return "tailnet"; - return "custom"; -} -function validateConfiguredBindMode(input) { - const bind2 = input.bind ?? inferBindModeFromHost(input.host); - const customBindHost = normalizeHost(input.customBindHost); - const errors = []; - if (input.deploymentMode === "local_trusted" && bind2 !== "loopback") { - errors.push("local_trusted requires server.bind=loopback"); - } - if (bind2 === "custom" && !customBindHost) { - const legacyHost = normalizeHost(input.host); - if (!legacyHost || isLoopbackHost(legacyHost) || isAllInterfacesHost(legacyHost)) { - errors.push("server.customBindHost is required when server.bind=custom"); - } - } - if (input.deploymentMode === "authenticated" && input.deploymentExposure === "public" && bind2 === "tailnet") { - errors.push("server.bind=tailnet is only supported for authenticated/private deployments"); - } - return errors; -} -function resolveRuntimeBind(input) { - const bind2 = input.bind ?? inferBindModeFromHost(input.host, { tailnetBindHost: input.tailnetBindHost }); - const legacyHost = normalizeHost(input.host); - const customBindHost = normalizeHost(input.customBindHost) ?? (bind2 === "custom" && legacyHost && !isLoopbackHost(legacyHost) && !isAllInterfacesHost(legacyHost) ? legacyHost : void 0); - switch (bind2) { - case "loopback": - return { bind: bind2, host: LOOPBACK_BIND_HOST, customBindHost, errors: [] }; - case "lan": - return { bind: bind2, host: ALL_INTERFACES_BIND_HOST, customBindHost, errors: [] }; - case "custom": - return customBindHost ? { bind: bind2, host: customBindHost, customBindHost, errors: [] } : { bind: bind2, host: legacyHost ?? LOOPBACK_BIND_HOST, errors: ["server.customBindHost is required when server.bind=custom"] }; - case "tailnet": { - const tailnetBindHost = normalizeHost(input.tailnetBindHost); - return tailnetBindHost ? { bind: bind2, host: tailnetBindHost, customBindHost, errors: [] } : { - bind: bind2, - host: legacyHost ?? LOOPBACK_BIND_HOST, - customBindHost, - errors: [ - "server.bind=tailnet requires a detected Tailscale address or TASKCORE_TAILNET_BIND_HOST" - ] - }; - } - } -} - -// packages/shared/src/validators/sidebar-preferences.ts -var sidebarOrderedIdSchema = external_exports.string().uuid(); -var sidebarOrderPreferenceSchema = external_exports.object({ - orderedIds: external_exports.array(sidebarOrderedIdSchema), - updatedAt: external_exports.coerce.date().nullable() -}); -var upsertSidebarOrderPreferenceSchema = external_exports.object({ - orderedIds: external_exports.array(sidebarOrderedIdSchema) -}); - -// packages/shared/src/validators/execution-workspace.ts -var executionWorkspaceStatusSchema = external_exports.enum([ - "active", - "idle", - "in_review", - "archived", - "cleanup_failed" -]); -var executionWorkspaceConfigSchema = external_exports.object({ - provisionCommand: external_exports.string().optional().nullable(), - teardownCommand: external_exports.string().optional().nullable(), - cleanupCommand: external_exports.string().optional().nullable(), - workspaceRuntime: external_exports.record(external_exports.unknown()).optional().nullable(), - desiredState: external_exports.enum(["running", "stopped"]).optional().nullable(), - serviceStates: external_exports.record(external_exports.enum(["running", "stopped"])).optional().nullable() -}).strict(); -var workspaceRuntimeControlTargetSchema = external_exports.object({ - workspaceCommandId: external_exports.string().min(1).optional().nullable(), - runtimeServiceId: external_exports.string().uuid().optional().nullable(), - serviceIndex: external_exports.number().int().nonnegative().optional().nullable() -}).strict(); -var executionWorkspaceCloseReadinessStateSchema = external_exports.enum([ - "ready", - "ready_with_warnings", - "blocked" -]); -var executionWorkspaceCloseActionKindSchema = external_exports.enum([ - "archive_record", - "stop_runtime_services", - "cleanup_command", - "teardown_command", - "git_worktree_remove", - "git_branch_delete", - "remove_local_directory" -]); -var executionWorkspaceCloseActionSchema = external_exports.object({ - kind: executionWorkspaceCloseActionKindSchema, - label: external_exports.string(), - description: external_exports.string(), - command: external_exports.string().nullable() -}).strict(); -var executionWorkspaceCloseLinkedIssueSchema = external_exports.object({ - id: external_exports.string().uuid(), - identifier: external_exports.string().nullable(), - title: external_exports.string(), - status: external_exports.string(), - isTerminal: external_exports.boolean() -}).strict(); -var executionWorkspaceCloseGitReadinessSchema = external_exports.object({ - repoRoot: external_exports.string().nullable(), - workspacePath: external_exports.string().nullable(), - branchName: external_exports.string().nullable(), - baseRef: external_exports.string().nullable(), - hasDirtyTrackedFiles: external_exports.boolean(), - hasUntrackedFiles: external_exports.boolean(), - dirtyEntryCount: external_exports.number().int().nonnegative(), - untrackedEntryCount: external_exports.number().int().nonnegative(), - aheadCount: external_exports.number().int().nonnegative().nullable(), - behindCount: external_exports.number().int().nonnegative().nullable(), - isMergedIntoBase: external_exports.boolean().nullable(), - createdByRuntime: external_exports.boolean() -}).strict(); -var workspaceRuntimeServiceSchema = external_exports.object({ - id: external_exports.string(), - companyId: external_exports.string().uuid(), - projectId: external_exports.string().uuid().nullable(), - projectWorkspaceId: external_exports.string().uuid().nullable(), - executionWorkspaceId: external_exports.string().uuid().nullable(), - issueId: external_exports.string().uuid().nullable(), - scopeType: external_exports.enum(["project_workspace", "execution_workspace", "run", "agent"]), - scopeId: external_exports.string().nullable(), - serviceName: external_exports.string(), - status: external_exports.enum(["starting", "running", "stopped", "failed"]), - lifecycle: external_exports.enum(["shared", "ephemeral"]), - reuseKey: external_exports.string().nullable(), - command: external_exports.string().nullable(), - cwd: external_exports.string().nullable(), - port: external_exports.number().int().nullable(), - url: external_exports.string().nullable(), - provider: external_exports.enum(["local_process", "adapter_managed"]), - providerRef: external_exports.string().nullable(), - ownerAgentId: external_exports.string().uuid().nullable(), - startedByRunId: external_exports.string().uuid().nullable(), - lastUsedAt: external_exports.coerce.date(), - startedAt: external_exports.coerce.date(), - stoppedAt: external_exports.coerce.date().nullable(), - stopPolicy: external_exports.record(external_exports.unknown()).nullable(), - healthStatus: external_exports.enum(["unknown", "healthy", "unhealthy"]), - configIndex: external_exports.number().int().nonnegative().nullable().optional(), - createdAt: external_exports.coerce.date(), - updatedAt: external_exports.coerce.date() -}).strict(); -var executionWorkspaceCloseReadinessSchema = external_exports.object({ - workspaceId: external_exports.string().uuid(), - state: executionWorkspaceCloseReadinessStateSchema, - blockingReasons: external_exports.array(external_exports.string()), - warnings: external_exports.array(external_exports.string()), - linkedIssues: external_exports.array(executionWorkspaceCloseLinkedIssueSchema), - plannedActions: external_exports.array(executionWorkspaceCloseActionSchema), - isDestructiveCloseAllowed: external_exports.boolean(), - isSharedWorkspace: external_exports.boolean(), - isProjectPrimaryWorkspace: external_exports.boolean(), - git: executionWorkspaceCloseGitReadinessSchema.nullable(), - runtimeServices: external_exports.array(workspaceRuntimeServiceSchema) -}).strict(); -var updateExecutionWorkspaceSchema = external_exports.object({ - name: external_exports.string().min(1).optional(), - cwd: external_exports.string().optional().nullable(), - repoUrl: external_exports.string().optional().nullable(), - baseRef: external_exports.string().optional().nullable(), - branchName: external_exports.string().optional().nullable(), - providerRef: external_exports.string().optional().nullable(), - status: executionWorkspaceStatusSchema.optional(), - cleanupEligibleAt: external_exports.string().datetime().optional().nullable(), - cleanupReason: external_exports.string().optional().nullable(), - config: executionWorkspaceConfigSchema.optional().nullable(), - metadata: external_exports.record(external_exports.unknown()).optional().nullable() -}).strict(); - -// packages/shared/src/workspace-commands.ts -function isRecord(value) { - return typeof value === "object" && value !== null && !Array.isArray(value); -} -function readNonEmptyString(value) { - if (typeof value !== "string") return null; - const trimmed = value.trim(); - return trimmed.length > 0 ? trimmed : null; -} -function slugify(value) { - const normalized = (value ?? "").trim().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/-+/g, "-").replace(/^-+|-+$/g, ""); - return normalized.length > 0 ? normalized : null; -} -function deriveWorkspaceCommandId(input) { - const explicitId = slugify(input.explicitId); - if (explicitId) return explicitId; - const nameSlug = slugify(input.name); - return nameSlug ? `${input.kind}:${nameSlug}` : `${input.kind}:${input.index + 1}`; -} -function buildWorkspaceCommandDefinition(input) { - return { - id: deriveWorkspaceCommandId({ - kind: input.kind, - explicitId: readNonEmptyString(input.entry.id), - name: readNonEmptyString(input.entry.name) ?? readNonEmptyString(input.entry.label) ?? readNonEmptyString(input.entry.title) ?? input.fallbackName, - index: input.sourceIndex - }), - name: readNonEmptyString(input.entry.name) ?? readNonEmptyString(input.entry.label) ?? readNonEmptyString(input.entry.title) ?? input.fallbackName, - kind: input.kind, - command: readNonEmptyString(input.entry.command), - cwd: readNonEmptyString(input.entry.cwd), - lifecycle: input.kind === "service" ? input.entry.lifecycle === "ephemeral" ? "ephemeral" : "shared" : null, - serviceIndex: input.serviceIndex, - disabledReason: readNonEmptyString(input.entry.disabledReason), - rawConfig: { ...input.entry }, - source: { - type: "taskcore", - key: input.sourceKey, - index: input.sourceIndex - } - }; -} -function uniqueWorkspaceCommandId(seen, commandId, sourceKey, sourceIndex) { - if (!seen.has(commandId)) { - seen.add(commandId); - return commandId; - } - const fallbackId = `${commandId}-${sourceKey}-${sourceIndex + 1}`; - seen.add(fallbackId); - return fallbackId; -} -function readCommandEntries(workspaceRuntime, key) { - const raw = workspaceRuntime?.[key]; - return Array.isArray(raw) ? raw.filter((entry) => isRecord(entry)) : []; -} -function listWorkspaceCommandDefinitions(workspaceRuntime) { - if (!workspaceRuntime) return []; - const commandEntries = readCommandEntries(workspaceRuntime, "commands"); - const seenIds = /* @__PURE__ */ new Set(); - let nextServiceIndex = 0; - const finalize2 = (command) => ({ - ...command, - id: uniqueWorkspaceCommandId(seenIds, command.id, command.source.key, command.source.index) - }); - if (commandEntries.length > 0) { - return commandEntries.map((entry, index2) => finalize2(buildWorkspaceCommandDefinition({ - entry, - kind: entry.kind === "job" ? "job" : "service", - sourceKey: "commands", - sourceIndex: index2, - serviceIndex: entry.kind === "job" ? null : nextServiceIndex++, - fallbackName: entry.kind === "job" ? `Job ${index2 + 1}` : `Service ${index2 + 1}` - }))); - } - const serviceDefinitions = readCommandEntries(workspaceRuntime, "services").map((entry, index2) => finalize2(buildWorkspaceCommandDefinition({ - entry, - kind: "service", - sourceKey: "services", - sourceIndex: index2, - serviceIndex: nextServiceIndex++, - fallbackName: `Service ${index2 + 1}` - }))); - const jobDefinitions = readCommandEntries(workspaceRuntime, "jobs").map((entry, index2) => finalize2(buildWorkspaceCommandDefinition({ - entry, - kind: "job", - sourceKey: "jobs", - sourceIndex: index2, - serviceIndex: null, - fallbackName: `Job ${index2 + 1}` - }))); - return [...serviceDefinitions, ...jobDefinitions]; -} -function listWorkspaceServiceCommandDefinitions(workspaceRuntime) { - return listWorkspaceCommandDefinitions(workspaceRuntime).filter((command) => command.kind === "service"); -} -function findWorkspaceCommandDefinition(workspaceRuntime, workspaceCommandId) { - const normalizedId = readNonEmptyString(workspaceCommandId); - if (!normalizedId) return null; - return listWorkspaceCommandDefinitions(workspaceRuntime).find((command) => command.id === normalizedId) ?? null; -} -function scoreWorkspaceRuntimeServiceMatch(command, runtimeService) { - if (command.serviceIndex !== null && runtimeService.configIndex !== null && runtimeService.configIndex !== void 0) { - return runtimeService.configIndex === command.serviceIndex ? 100 : -1; - } - let score = 0; - if (runtimeService.serviceName === command.name) score += 4; - if ((runtimeService.command ?? null) === (command.command ?? null)) score += 4; - if (command.cwd && runtimeService.cwd && (runtimeService.cwd === command.cwd || runtimeService.cwd.endsWith(`/${command.cwd}`))) { - score += 2; - } - return score; -} -function matchWorkspaceRuntimeServiceToCommand(command, runtimeServices) { - let bestMatch = null; - let bestScore = -1; - for (const runtimeService of runtimeServices ?? []) { - const score = scoreWorkspaceRuntimeServiceMatch(command, runtimeService); - if (score > bestScore) { - bestMatch = runtimeService; - bestScore = score; - } - } - return bestScore > 0 ? bestMatch : null; -} - -// packages/shared/src/types/feedback.ts -var FEEDBACK_TARGET_TYPES = ["issue_comment", "issue_document_revision"]; -var FEEDBACK_VOTE_VALUES = ["up", "down"]; -var FEEDBACK_DATA_SHARING_PREFERENCES = ["allowed", "not_allowed", "prompt"]; -var DEFAULT_FEEDBACK_DATA_SHARING_PREFERENCE = "prompt"; -var FEEDBACK_TRACE_STATUSES = ["local_only", "pending", "sent", "failed"]; -var DEFAULT_FEEDBACK_DATA_SHARING_TERMS_VERSION = "feedback-data-sharing-v1"; - -// packages/shared/src/types/instance.ts -var DAILY_RETENTION_PRESETS = [3, 7, 14]; -var WEEKLY_RETENTION_PRESETS = [1, 2, 4]; -var MONTHLY_RETENTION_PRESETS = [1, 3, 6]; -var DEFAULT_BACKUP_RETENTION = { - dailyDays: 7, - weeklyWeeks: 4, - monthlyMonths: 1 -}; - -// packages/shared/src/execution-workspace-guards.ts -var CLOSED_EXECUTION_WORKSPACE_STATUSES = /* @__PURE__ */ new Set(["archived", "cleanup_failed"]); -function isClosedIsolatedExecutionWorkspace(workspace) { - if (!workspace) return false; - if (workspace.mode !== "isolated_workspace") return false; - return workspace.closedAt != null || CLOSED_EXECUTION_WORKSPACE_STATUSES.has(workspace.status); -} -function getClosedIsolatedExecutionWorkspaceMessage(workspace) { - return `This issue is linked to the closed workspace "${workspace.name}". Move it to an open workspace before adding comments or resuming work.`; -} - -// packages/shared/src/validators/feedback.ts -var feedbackTargetTypeSchema = external_exports.enum(FEEDBACK_TARGET_TYPES); -var feedbackTraceStatusSchema = external_exports.enum(FEEDBACK_TRACE_STATUSES); -var feedbackVoteValueSchema = external_exports.enum(FEEDBACK_VOTE_VALUES); -var feedbackDataSharingPreferenceSchema = external_exports.enum(FEEDBACK_DATA_SHARING_PREFERENCES); -var upsertIssueFeedbackVoteSchema = external_exports.object({ - targetType: feedbackTargetTypeSchema, - targetId: external_exports.string().uuid(), - vote: feedbackVoteValueSchema, - reason: external_exports.string().trim().max(1e3).optional(), - allowSharing: external_exports.boolean().optional() -}); - -// packages/shared/src/validators/instance.ts -function presetSchema(presets, label) { - return external_exports.number().refine( - (v5) => presets.includes(v5), - { message: `${label} must be one of: ${presets.join(", ")}` } - ); -} -var backupRetentionPolicySchema = external_exports.object({ - dailyDays: presetSchema(DAILY_RETENTION_PRESETS, "dailyDays").default(DEFAULT_BACKUP_RETENTION.dailyDays), - weeklyWeeks: presetSchema(WEEKLY_RETENTION_PRESETS, "weeklyWeeks").default(DEFAULT_BACKUP_RETENTION.weeklyWeeks), - monthlyMonths: presetSchema(MONTHLY_RETENTION_PRESETS, "monthlyMonths").default(DEFAULT_BACKUP_RETENTION.monthlyMonths) -}); -var instanceGeneralSettingsSchema = external_exports.object({ - censorUsernameInLogs: external_exports.boolean().default(false), - keyboardShortcuts: external_exports.boolean().default(false), - feedbackDataSharingPreference: feedbackDataSharingPreferenceSchema.default( - DEFAULT_FEEDBACK_DATA_SHARING_PREFERENCE - ), - backupRetention: backupRetentionPolicySchema.default(DEFAULT_BACKUP_RETENTION) -}).strict(); -var patchInstanceGeneralSettingsSchema = instanceGeneralSettingsSchema.partial(); -var instanceExperimentalSettingsSchema = external_exports.object({ - enableIsolatedWorkspaces: external_exports.boolean().default(false), - autoRestartDevServerWhenIdle: external_exports.boolean().default(false) -}).strict(); -var patchInstanceExperimentalSettingsSchema = instanceExperimentalSettingsSchema.partial(); - -// packages/shared/src/validators/budget.ts -var upsertBudgetPolicySchema = external_exports.object({ - scopeType: external_exports.enum(BUDGET_SCOPE_TYPES), - scopeId: external_exports.string().uuid(), - metric: external_exports.enum(BUDGET_METRICS).optional().default("billed_cents"), - windowKind: external_exports.enum(BUDGET_WINDOW_KINDS).optional().default("calendar_month_utc"), - amount: external_exports.number().int().nonnegative(), - warnPercent: external_exports.number().int().min(1).max(99).optional().default(80), - hardStopEnabled: external_exports.boolean().optional().default(true), - notifyEnabled: external_exports.boolean().optional().default(true), - isActive: external_exports.boolean().optional().default(true) -}); -var resolveBudgetIncidentSchema = external_exports.object({ - action: external_exports.enum(BUDGET_INCIDENT_RESOLUTION_ACTIONS), - amount: external_exports.number().int().nonnegative().optional(), - decisionNote: external_exports.string().optional().nullable() -}).superRefine((value, ctx) => { - if (value.action === "raise_budget_and_resume" && typeof value.amount !== "number") { - ctx.addIssue({ - code: external_exports.ZodIssueCode.custom, - message: "amount is required when raising a budget", - path: ["amount"] - }); - } -}); - -// packages/shared/src/validators/company.ts -var logoAssetIdSchema = external_exports.string().uuid().nullable().optional(); -var brandColorSchema = external_exports.string().regex(/^#[0-9a-fA-F]{6}$/).nullable().optional(); -var feedbackDataSharingTermsVersionSchema = external_exports.string().min(1).nullable().optional(); -var createCompanySchema = external_exports.object({ - name: external_exports.string().min(1), - description: external_exports.string().optional().nullable(), - budgetMonthlyCents: external_exports.number().int().nonnegative().optional().default(0) -}); -var updateCompanySchema = createCompanySchema.partial().extend({ - status: external_exports.enum(COMPANY_STATUSES).optional(), - spentMonthlyCents: external_exports.number().int().nonnegative().optional(), - requireBoardApprovalForNewAgents: external_exports.boolean().optional(), - feedbackDataSharingEnabled: external_exports.boolean().optional(), - feedbackDataSharingConsentAt: external_exports.coerce.date().nullable().optional(), - feedbackDataSharingConsentByUserId: external_exports.string().min(1).nullable().optional(), - feedbackDataSharingTermsVersion: feedbackDataSharingTermsVersionSchema, - brandColor: brandColorSchema, - logoAssetId: logoAssetIdSchema -}); -var updateCompanyBrandingSchema = external_exports.object({ - name: external_exports.string().min(1).optional(), - description: external_exports.string().nullable().optional(), - brandColor: brandColorSchema, - logoAssetId: logoAssetIdSchema -}).strict().refine( - (value) => value.name !== void 0 || value.description !== void 0 || value.brandColor !== void 0 || value.logoAssetId !== void 0, - "At least one branding field must be provided" -); - -// packages/shared/src/validators/company-skill.ts -var companySkillSourceTypeSchema = external_exports.enum(["local_path", "github", "url", "catalog", "skills_sh"]); -var companySkillTrustLevelSchema = external_exports.enum(["markdown_only", "assets", "scripts_executables"]); -var companySkillCompatibilitySchema = external_exports.enum(["compatible", "unknown", "invalid"]); -var companySkillSourceBadgeSchema = external_exports.enum(["taskcore", "github", "local", "url", "catalog", "skills_sh"]); -var companySkillFileInventoryEntrySchema = external_exports.object({ - path: external_exports.string().min(1), - kind: external_exports.enum(["skill", "markdown", "reference", "script", "asset", "other"]) -}); -var companySkillSchema = external_exports.object({ - id: external_exports.string().uuid(), - companyId: external_exports.string().uuid(), - key: external_exports.string().min(1), - slug: external_exports.string().min(1), - name: external_exports.string().min(1), - description: external_exports.string().nullable(), - markdown: external_exports.string(), - sourceType: companySkillSourceTypeSchema, - sourceLocator: external_exports.string().nullable(), - sourceRef: external_exports.string().nullable(), - trustLevel: companySkillTrustLevelSchema, - compatibility: companySkillCompatibilitySchema, - fileInventory: external_exports.array(companySkillFileInventoryEntrySchema).default([]), - metadata: external_exports.record(external_exports.unknown()).nullable(), - createdAt: external_exports.coerce.date(), - updatedAt: external_exports.coerce.date() -}); -var companySkillListItemSchema = companySkillSchema.extend({ - attachedAgentCount: external_exports.number().int().nonnegative(), - editable: external_exports.boolean(), - editableReason: external_exports.string().nullable(), - sourceLabel: external_exports.string().nullable(), - sourceBadge: companySkillSourceBadgeSchema -}); -var companySkillUsageAgentSchema = external_exports.object({ - id: external_exports.string().uuid(), - name: external_exports.string().min(1), - urlKey: external_exports.string().min(1), - adapterType: external_exports.string().min(1), - desired: external_exports.boolean(), - actualState: external_exports.string().nullable() -}); -var companySkillDetailSchema = companySkillSchema.extend({ - attachedAgentCount: external_exports.number().int().nonnegative(), - usedByAgents: external_exports.array(companySkillUsageAgentSchema).default([]), - editable: external_exports.boolean(), - editableReason: external_exports.string().nullable(), - sourceLabel: external_exports.string().nullable(), - sourceBadge: companySkillSourceBadgeSchema -}); -var companySkillUpdateStatusSchema = external_exports.object({ - supported: external_exports.boolean(), - reason: external_exports.string().nullable(), - trackingRef: external_exports.string().nullable(), - currentRef: external_exports.string().nullable(), - latestRef: external_exports.string().nullable(), - hasUpdate: external_exports.boolean() -}); -var companySkillImportSchema = external_exports.object({ - source: external_exports.string().min(1) -}); -var companySkillProjectScanRequestSchema = external_exports.object({ - projectIds: external_exports.array(external_exports.string().uuid()).optional(), - workspaceIds: external_exports.array(external_exports.string().uuid()).optional() -}); -var companySkillProjectScanSkippedSchema = external_exports.object({ - projectId: external_exports.string().uuid(), - projectName: external_exports.string().min(1), - workspaceId: external_exports.string().uuid().nullable(), - workspaceName: external_exports.string().nullable(), - path: external_exports.string().nullable(), - reason: external_exports.string().min(1) -}); -var companySkillProjectScanConflictSchema = external_exports.object({ - slug: external_exports.string().min(1), - key: external_exports.string().min(1), - projectId: external_exports.string().uuid(), - projectName: external_exports.string().min(1), - workspaceId: external_exports.string().uuid(), - workspaceName: external_exports.string().min(1), - path: external_exports.string().min(1), - existingSkillId: external_exports.string().uuid(), - existingSkillKey: external_exports.string().min(1), - existingSourceLocator: external_exports.string().nullable(), - reason: external_exports.string().min(1) -}); -var companySkillProjectScanResultSchema = external_exports.object({ - scannedProjects: external_exports.number().int().nonnegative(), - scannedWorkspaces: external_exports.number().int().nonnegative(), - discovered: external_exports.number().int().nonnegative(), - imported: external_exports.array(companySkillSchema), - updated: external_exports.array(companySkillSchema), - skipped: external_exports.array(companySkillProjectScanSkippedSchema), - conflicts: external_exports.array(companySkillProjectScanConflictSchema), - warnings: external_exports.array(external_exports.string()) -}); -var companySkillCreateSchema = external_exports.object({ - name: external_exports.string().min(1), - slug: external_exports.string().min(1).nullable().optional(), - description: external_exports.string().nullable().optional(), - markdown: external_exports.string().nullable().optional() -}); -var companySkillFileDetailSchema = external_exports.object({ - skillId: external_exports.string().uuid(), - path: external_exports.string().min(1), - kind: external_exports.enum(["skill", "markdown", "reference", "script", "asset", "other"]), - content: external_exports.string(), - language: external_exports.string().nullable(), - markdown: external_exports.boolean(), - editable: external_exports.boolean() -}); -var companySkillFileUpdateSchema = external_exports.object({ - path: external_exports.string().min(1), - content: external_exports.string() -}); - -// packages/shared/src/validators/adapter-skills.ts -var agentSkillStateSchema = external_exports.enum([ - "available", - "configured", - "installed", - "missing", - "stale", - "external" -]); -var agentSkillOriginSchema = external_exports.enum([ - "company_managed", - "taskcore_required", - "user_installed", - "external_unknown" -]); -var agentSkillSyncModeSchema = external_exports.enum([ - "unsupported", - "persistent", - "ephemeral" -]); -var agentSkillEntrySchema = external_exports.object({ - key: external_exports.string().min(1), - runtimeName: external_exports.string().min(1).nullable(), - desired: external_exports.boolean(), - managed: external_exports.boolean(), - required: external_exports.boolean().optional(), - requiredReason: external_exports.string().nullable().optional(), - state: agentSkillStateSchema, - origin: agentSkillOriginSchema.optional(), - originLabel: external_exports.string().nullable().optional(), - locationLabel: external_exports.string().nullable().optional(), - readOnly: external_exports.boolean().optional(), - sourcePath: external_exports.string().nullable().optional(), - targetPath: external_exports.string().nullable().optional(), - detail: external_exports.string().nullable().optional() -}); -var agentSkillSnapshotSchema = external_exports.object({ - adapterType: external_exports.string().min(1), - supported: external_exports.boolean(), - mode: agentSkillSyncModeSchema, - desiredSkills: external_exports.array(external_exports.string().min(1)), - entries: external_exports.array(agentSkillEntrySchema), - warnings: external_exports.array(external_exports.string()) -}); -var agentSkillSyncSchema = external_exports.object({ - desiredSkills: external_exports.array(external_exports.string().min(1)) -}); - -// packages/shared/src/validators/issue.ts -var ISSUE_EXECUTION_WORKSPACE_PREFERENCES = [ - "inherit", - "shared_workspace", - "isolated_workspace", - "operator_branch", - "reuse_existing", - "agent_default" -]; -var executionWorkspaceStrategySchema = external_exports.object({ - type: external_exports.enum(["project_primary", "git_worktree", "adapter_managed", "cloud_sandbox"]).optional(), - baseRef: external_exports.string().optional().nullable(), - branchTemplate: external_exports.string().optional().nullable(), - worktreeParentDir: external_exports.string().optional().nullable(), - provisionCommand: external_exports.string().optional().nullable(), - teardownCommand: external_exports.string().optional().nullable() -}).strict(); -var issueExecutionWorkspaceSettingsSchema = external_exports.object({ - mode: external_exports.enum(ISSUE_EXECUTION_WORKSPACE_PREFERENCES).optional(), - workspaceStrategy: executionWorkspaceStrategySchema.optional().nullable(), - workspaceRuntime: external_exports.record(external_exports.unknown()).optional().nullable() -}).strict(); -var issueAssigneeAdapterOverridesSchema = external_exports.object({ - adapterConfig: external_exports.record(external_exports.unknown()).optional(), - useProjectWorkspace: external_exports.boolean().optional() -}).strict(); -var issueExecutionStagePrincipalBaseSchema = external_exports.object({ - type: external_exports.enum(["agent", "user"]), - agentId: external_exports.string().uuid().optional().nullable(), - userId: external_exports.string().optional().nullable() -}); -var issueExecutionStagePrincipalSchema = issueExecutionStagePrincipalBaseSchema.superRefine((value, ctx) => { - if (value.type === "agent") { - if (!value.agentId) { - ctx.addIssue({ code: external_exports.ZodIssueCode.custom, message: "Agent participants require agentId", path: ["agentId"] }); - } - if (value.userId) { - ctx.addIssue({ code: external_exports.ZodIssueCode.custom, message: "Agent participants cannot set userId", path: ["userId"] }); - } - return; - } - if (!value.userId) { - ctx.addIssue({ code: external_exports.ZodIssueCode.custom, message: "User participants require userId", path: ["userId"] }); - } - if (value.agentId) { - ctx.addIssue({ code: external_exports.ZodIssueCode.custom, message: "User participants cannot set agentId", path: ["agentId"] }); - } -}); -var issueExecutionStageParticipantSchema = issueExecutionStagePrincipalBaseSchema.extend({ - id: external_exports.string().uuid().optional() -}).superRefine((value, ctx) => { - if (value.type === "agent") { - if (!value.agentId) { - ctx.addIssue({ code: external_exports.ZodIssueCode.custom, message: "Agent participants require agentId", path: ["agentId"] }); - } - if (value.userId) { - ctx.addIssue({ code: external_exports.ZodIssueCode.custom, message: "Agent participants cannot set userId", path: ["userId"] }); - } - return; - } - if (!value.userId) { - ctx.addIssue({ code: external_exports.ZodIssueCode.custom, message: "User participants require userId", path: ["userId"] }); - } - if (value.agentId) { - ctx.addIssue({ code: external_exports.ZodIssueCode.custom, message: "User participants cannot set agentId", path: ["agentId"] }); - } -}); -var issueExecutionStageSchema = external_exports.object({ - id: external_exports.string().uuid().optional(), - type: external_exports.enum(ISSUE_EXECUTION_STAGE_TYPES), - approvalsNeeded: external_exports.literal(1).optional().default(1), - participants: external_exports.array(issueExecutionStageParticipantSchema).default([]) -}); -var issueExecutionPolicySchema = external_exports.object({ - mode: external_exports.enum(ISSUE_EXECUTION_POLICY_MODES).optional().default("normal"), - commentRequired: external_exports.boolean().optional().default(true), - stages: external_exports.array(issueExecutionStageSchema).default([]) -}); -var issueExecutionStateSchema = external_exports.object({ - status: external_exports.enum(ISSUE_EXECUTION_STATE_STATUSES), - currentStageId: external_exports.string().uuid().nullable(), - currentStageIndex: external_exports.number().int().nonnegative().nullable(), - currentStageType: external_exports.enum(ISSUE_EXECUTION_STAGE_TYPES).nullable(), - currentParticipant: issueExecutionStagePrincipalSchema.nullable(), - returnAssignee: issueExecutionStagePrincipalSchema.nullable(), - completedStageIds: external_exports.array(external_exports.string().uuid()).default([]), - lastDecisionId: external_exports.string().uuid().nullable(), - lastDecisionOutcome: external_exports.enum(ISSUE_EXECUTION_DECISION_OUTCOMES).nullable() -}); -var createIssueSchema = external_exports.object({ - projectId: external_exports.string().uuid().optional().nullable(), - projectWorkspaceId: external_exports.string().uuid().optional().nullable(), - goalId: external_exports.string().uuid().optional().nullable(), - parentId: external_exports.string().uuid().optional().nullable(), - blockedByIssueIds: external_exports.array(external_exports.string().uuid()).optional(), - inheritExecutionWorkspaceFromIssueId: external_exports.string().uuid().optional().nullable(), - title: external_exports.string().min(1), - description: external_exports.string().optional().nullable(), - status: external_exports.enum(ISSUE_STATUSES).optional().default("backlog"), - priority: external_exports.enum(ISSUE_PRIORITIES).optional().default("medium"), - assigneeAgentId: external_exports.string().uuid().optional().nullable(), - assigneeUserId: external_exports.string().optional().nullable(), - requestDepth: external_exports.number().int().nonnegative().optional().default(0), - billingCode: external_exports.string().optional().nullable(), - assigneeAdapterOverrides: issueAssigneeAdapterOverridesSchema.optional().nullable(), - executionPolicy: issueExecutionPolicySchema.optional().nullable(), - executionWorkspaceId: external_exports.string().uuid().optional().nullable(), - executionWorkspacePreference: external_exports.enum(ISSUE_EXECUTION_WORKSPACE_PREFERENCES).optional().nullable(), - executionWorkspaceSettings: issueExecutionWorkspaceSettingsSchema.optional().nullable(), - labelIds: external_exports.array(external_exports.string().uuid()).optional() -}); -var createIssueLabelSchema = external_exports.object({ - name: external_exports.string().trim().min(1).max(48), - color: external_exports.string().regex(/^#(?:[0-9a-fA-F]{6})$/, "Color must be a 6-digit hex value") -}); -var updateIssueSchema = createIssueSchema.partial().extend({ - assigneeAgentId: external_exports.string().trim().min(1).optional().nullable(), - comment: external_exports.string().min(1).optional(), - reopen: external_exports.boolean().optional(), - interrupt: external_exports.boolean().optional(), - hiddenAt: external_exports.string().datetime().nullable().optional() -}); -var checkoutIssueSchema = external_exports.object({ - agentId: external_exports.string().uuid(), - expectedStatuses: external_exports.array(external_exports.enum(ISSUE_STATUSES)).nonempty() -}); -var addIssueCommentSchema = external_exports.object({ - body: external_exports.string().min(1), - reopen: external_exports.boolean().optional(), - interrupt: external_exports.boolean().optional() -}); -var linkIssueApprovalSchema = external_exports.object({ - approvalId: external_exports.string().uuid() -}); -var createIssueAttachmentMetadataSchema = external_exports.object({ - issueCommentId: external_exports.string().uuid().optional().nullable() -}); -var ISSUE_DOCUMENT_FORMATS = ["markdown"]; -var issueDocumentFormatSchema = external_exports.enum(ISSUE_DOCUMENT_FORMATS); -var issueDocumentKeySchema = external_exports.string().trim().min(1).max(64).regex(/^[a-z0-9][a-z0-9_-]*$/, "Document key must be lowercase letters, numbers, _ or -"); -var upsertIssueDocumentSchema = external_exports.object({ - title: external_exports.string().trim().max(200).nullable().optional(), - format: issueDocumentFormatSchema, - body: external_exports.string().max(524288), - changeSummary: external_exports.string().trim().max(500).nullable().optional(), - baseRevisionId: external_exports.string().uuid().nullable().optional() -}); -var restoreIssueDocumentRevisionSchema = external_exports.object({}); - -// packages/shared/src/validators/routine.ts -var routineVariableValueSchema = external_exports.union([external_exports.string(), external_exports.number().finite(), external_exports.boolean()]); -var routineVariableSchema = external_exports.object({ - name: external_exports.string().trim().regex(/^[A-Za-z][A-Za-z0-9_]*$/), - label: external_exports.string().trim().max(120).optional().nullable(), - type: external_exports.enum(ROUTINE_VARIABLE_TYPES).optional().default("text"), - defaultValue: routineVariableValueSchema.optional().nullable(), - required: external_exports.boolean().optional().default(true), - options: external_exports.array(external_exports.string().trim().min(1).max(120)).max(50).optional().default([]) -}).superRefine((value, ctx) => { - if (value.type === "select" && value.options.length === 0) { - ctx.addIssue({ - code: external_exports.ZodIssueCode.custom, - path: ["options"], - message: "Select variables require at least one option" - }); - } - if (value.type !== "select" && value.options.length > 0) { - ctx.addIssue({ - code: external_exports.ZodIssueCode.custom, - path: ["options"], - message: "Only select variables can define options" - }); - } - if (value.type === "select" && value.defaultValue != null) { - if (typeof value.defaultValue !== "string" || !value.options.includes(value.defaultValue)) { - ctx.addIssue({ - code: external_exports.ZodIssueCode.custom, - path: ["defaultValue"], - message: "Select variable defaults must match one of the allowed options" - }); - } - } -}); -var createRoutineSchema = external_exports.object({ - projectId: external_exports.string().uuid().optional().nullable(), - goalId: external_exports.string().uuid().optional().nullable(), - parentIssueId: external_exports.string().uuid().optional().nullable(), - title: external_exports.string().trim().min(1).max(200), - description: external_exports.string().optional().nullable(), - assigneeAgentId: external_exports.string().uuid().optional().nullable(), - priority: external_exports.enum(ISSUE_PRIORITIES).optional().default("medium"), - status: external_exports.enum(ROUTINE_STATUSES).optional().default("active"), - concurrencyPolicy: external_exports.enum(ROUTINE_CONCURRENCY_POLICIES).optional().default("coalesce_if_active"), - catchUpPolicy: external_exports.enum(ROUTINE_CATCH_UP_POLICIES).optional().default("skip_missed"), - variables: external_exports.array(routineVariableSchema).optional().default([]) -}); -var updateRoutineSchema = createRoutineSchema.partial(); -var baseTriggerSchema = external_exports.object({ - label: external_exports.string().trim().max(120).optional().nullable(), - enabled: external_exports.boolean().optional().default(true) -}); -var createRoutineTriggerSchema = external_exports.discriminatedUnion("kind", [ - baseTriggerSchema.extend({ - kind: external_exports.literal("schedule"), - cronExpression: external_exports.string().trim().min(1), - timezone: external_exports.string().trim().min(1).default("UTC") - }), - baseTriggerSchema.extend({ - kind: external_exports.literal("webhook"), - signingMode: external_exports.enum(ROUTINE_TRIGGER_SIGNING_MODES).optional().default("bearer"), - replayWindowSec: external_exports.number().int().min(30).max(86400).optional().default(300) - }), - baseTriggerSchema.extend({ - kind: external_exports.literal("api") - }) -]); -var updateRoutineTriggerSchema = external_exports.object({ - label: external_exports.string().trim().max(120).optional().nullable(), - enabled: external_exports.boolean().optional(), - cronExpression: external_exports.string().trim().min(1).optional().nullable(), - timezone: external_exports.string().trim().min(1).optional().nullable(), - signingMode: external_exports.enum(ROUTINE_TRIGGER_SIGNING_MODES).optional().nullable(), - replayWindowSec: external_exports.number().int().min(30).max(86400).optional().nullable() -}); -var runRoutineSchema = external_exports.object({ - triggerId: external_exports.string().uuid().optional().nullable(), - payload: external_exports.record(external_exports.unknown()).optional().nullable(), - variables: external_exports.record(routineVariableValueSchema).optional().nullable(), - projectId: external_exports.string().uuid().optional().nullable(), - assigneeAgentId: external_exports.string().uuid().optional().nullable(), - idempotencyKey: external_exports.string().trim().max(255).optional().nullable(), - source: external_exports.enum(["manual", "api"]).optional().default("manual"), - executionWorkspaceId: external_exports.string().uuid().optional().nullable(), - executionWorkspacePreference: external_exports.enum(ISSUE_EXECUTION_WORKSPACE_PREFERENCES).optional().nullable(), - executionWorkspaceSettings: issueExecutionWorkspaceSettingsSchema.optional().nullable() -}); -var rotateRoutineTriggerSecretSchema = external_exports.object({}); - -// packages/shared/src/validators/company-portability.ts -var portabilityIncludeSchema = external_exports.object({ - company: external_exports.boolean().optional(), - agents: external_exports.boolean().optional(), - projects: external_exports.boolean().optional(), - issues: external_exports.boolean().optional(), - skills: external_exports.boolean().optional() -}).partial(); -var portabilityEnvInputSchema = external_exports.object({ - key: external_exports.string().min(1), - description: external_exports.string().nullable(), - agentSlug: external_exports.string().min(1).nullable(), - projectSlug: external_exports.string().min(1).nullable(), - kind: external_exports.enum(["secret", "plain"]), - requirement: external_exports.enum(["required", "optional"]), - defaultValue: external_exports.string().nullable(), - portability: external_exports.enum(["portable", "system_dependent"]) -}); -var portabilityFileEntrySchema = external_exports.union([ - external_exports.string(), - external_exports.object({ - encoding: external_exports.literal("base64"), - data: external_exports.string(), - contentType: external_exports.string().min(1).optional().nullable() - }) -]); -var portabilityCompanyManifestEntrySchema = external_exports.object({ - path: external_exports.string().min(1), - name: external_exports.string().min(1), - description: external_exports.string().nullable(), - brandColor: external_exports.string().nullable(), - logoPath: external_exports.string().nullable(), - requireBoardApprovalForNewAgents: external_exports.boolean(), - feedbackDataSharingEnabled: external_exports.boolean().default(false), - feedbackDataSharingConsentAt: external_exports.string().datetime().nullable().default(null), - feedbackDataSharingConsentByUserId: external_exports.string().nullable().default(null), - feedbackDataSharingTermsVersion: external_exports.string().nullable().default(null) -}); -var portabilitySidebarOrderSchema = external_exports.object({ - agents: external_exports.array(external_exports.string().min(1)).default([]), - projects: external_exports.array(external_exports.string().min(1)).default([]) -}); -var portabilityAgentManifestEntrySchema = external_exports.object({ - slug: external_exports.string().min(1), - name: external_exports.string().min(1), - path: external_exports.string().min(1), - skills: external_exports.array(external_exports.string().min(1)).default([]), - role: external_exports.string().min(1), - title: external_exports.string().nullable(), - icon: external_exports.string().nullable(), - capabilities: external_exports.string().nullable(), - reportsToSlug: external_exports.string().min(1).nullable(), - adapterType: external_exports.string().min(1), - adapterConfig: external_exports.record(external_exports.unknown()), - runtimeConfig: external_exports.record(external_exports.unknown()), - permissions: external_exports.record(external_exports.unknown()), - budgetMonthlyCents: external_exports.number().int().nonnegative(), - metadata: external_exports.record(external_exports.unknown()).nullable() -}); -var portabilitySkillManifestEntrySchema = external_exports.object({ - key: external_exports.string().min(1), - slug: external_exports.string().min(1), - name: external_exports.string().min(1), - path: external_exports.string().min(1), - description: external_exports.string().nullable(), - sourceType: external_exports.string().min(1), - sourceLocator: external_exports.string().nullable(), - sourceRef: external_exports.string().nullable(), - trustLevel: external_exports.string().nullable(), - compatibility: external_exports.string().nullable(), - metadata: external_exports.record(external_exports.unknown()).nullable(), - fileInventory: external_exports.array(external_exports.object({ - path: external_exports.string().min(1), - kind: external_exports.string().min(1) - })).default([]) -}); -var portabilityProjectManifestEntrySchema = external_exports.object({ - slug: external_exports.string().min(1), - name: external_exports.string().min(1), - path: external_exports.string().min(1), - description: external_exports.string().nullable(), - ownerAgentSlug: external_exports.string().min(1).nullable(), - leadAgentSlug: external_exports.string().min(1).nullable(), - targetDate: external_exports.string().nullable(), - color: external_exports.string().nullable(), - status: external_exports.string().nullable(), - executionWorkspacePolicy: external_exports.record(external_exports.unknown()).nullable(), - workspaces: external_exports.array(external_exports.object({ - key: external_exports.string().min(1), - name: external_exports.string().min(1), - sourceType: external_exports.string().nullable(), - repoUrl: external_exports.string().nullable(), - repoRef: external_exports.string().nullable(), - defaultRef: external_exports.string().nullable(), - visibility: external_exports.string().nullable(), - setupCommand: external_exports.string().nullable(), - cleanupCommand: external_exports.string().nullable(), - metadata: external_exports.record(external_exports.unknown()).nullable(), - isPrimary: external_exports.boolean() - })).default([]), - metadata: external_exports.record(external_exports.unknown()).nullable() -}); -var portabilityIssueRoutineTriggerManifestEntrySchema = external_exports.object({ - kind: external_exports.string().min(1), - label: external_exports.string().nullable(), - enabled: external_exports.boolean(), - cronExpression: external_exports.string().nullable(), - timezone: external_exports.string().nullable(), - signingMode: external_exports.string().nullable(), - replayWindowSec: external_exports.number().int().nullable() -}); -var portabilityIssueRoutineManifestEntrySchema = external_exports.object({ - concurrencyPolicy: external_exports.string().nullable(), - catchUpPolicy: external_exports.string().nullable(), - variables: external_exports.array(routineVariableSchema).nullable().optional(), - triggers: external_exports.array(portabilityIssueRoutineTriggerManifestEntrySchema).default([]) -}); -var portabilityIssueManifestEntrySchema = external_exports.object({ - slug: external_exports.string().min(1), - identifier: external_exports.string().min(1).nullable(), - title: external_exports.string().min(1), - path: external_exports.string().min(1), - projectSlug: external_exports.string().min(1).nullable(), - projectWorkspaceKey: external_exports.string().min(1).nullable(), - assigneeAgentSlug: external_exports.string().min(1).nullable(), - description: external_exports.string().nullable(), - recurring: external_exports.boolean().default(false), - routine: portabilityIssueRoutineManifestEntrySchema.nullable(), - legacyRecurrence: external_exports.record(external_exports.unknown()).nullable(), - status: external_exports.string().nullable(), - priority: external_exports.string().nullable(), - labelIds: external_exports.array(external_exports.string().min(1)).default([]), - billingCode: external_exports.string().nullable(), - executionWorkspaceSettings: external_exports.record(external_exports.unknown()).nullable(), - assigneeAdapterOverrides: external_exports.record(external_exports.unknown()).nullable(), - metadata: external_exports.record(external_exports.unknown()).nullable() -}); -var portabilityManifestSchema = external_exports.object({ - schemaVersion: external_exports.number().int().positive(), - generatedAt: external_exports.string().datetime(), - source: external_exports.object({ - companyId: external_exports.string().uuid(), - companyName: external_exports.string().min(1) - }).nullable(), - includes: external_exports.object({ - company: external_exports.boolean(), - agents: external_exports.boolean(), - projects: external_exports.boolean(), - issues: external_exports.boolean(), - skills: external_exports.boolean() - }), - company: portabilityCompanyManifestEntrySchema.nullable(), - sidebar: portabilitySidebarOrderSchema.nullable(), - agents: external_exports.array(portabilityAgentManifestEntrySchema), - skills: external_exports.array(portabilitySkillManifestEntrySchema).default([]), - projects: external_exports.array(portabilityProjectManifestEntrySchema).default([]), - issues: external_exports.array(portabilityIssueManifestEntrySchema).default([]), - envInputs: external_exports.array(portabilityEnvInputSchema).default([]) -}); -var portabilitySourceSchema = external_exports.discriminatedUnion("type", [ - external_exports.object({ - type: external_exports.literal("inline"), - rootPath: external_exports.string().min(1).optional().nullable(), - files: external_exports.record(portabilityFileEntrySchema) - }), - external_exports.object({ - type: external_exports.literal("github"), - url: external_exports.string().url() - }) -]); -var portabilityTargetSchema = external_exports.discriminatedUnion("mode", [ - external_exports.object({ - mode: external_exports.literal("new_company"), - newCompanyName: external_exports.string().min(1).optional().nullable() - }), - external_exports.object({ - mode: external_exports.literal("existing_company"), - companyId: external_exports.string().uuid() - }) -]); -var portabilityAgentSelectionSchema = external_exports.union([ - external_exports.literal("all"), - external_exports.array(external_exports.string().min(1)) -]); -var portabilityCollisionStrategySchema = external_exports.enum(["rename", "skip", "replace"]); -var companyPortabilityExportSchema = external_exports.object({ - include: portabilityIncludeSchema.optional(), - agents: external_exports.array(external_exports.string().min(1)).optional(), - skills: external_exports.array(external_exports.string().min(1)).optional(), - projects: external_exports.array(external_exports.string().min(1)).optional(), - issues: external_exports.array(external_exports.string().min(1)).optional(), - projectIssues: external_exports.array(external_exports.string().min(1)).optional(), - selectedFiles: external_exports.array(external_exports.string().min(1)).optional(), - expandReferencedSkills: external_exports.boolean().optional(), - sidebarOrder: portabilitySidebarOrderSchema.partial().optional() -}); -var companyPortabilityPreviewSchema = external_exports.object({ - source: portabilitySourceSchema, - include: portabilityIncludeSchema.optional(), - target: portabilityTargetSchema, - agents: portabilityAgentSelectionSchema.optional(), - collisionStrategy: portabilityCollisionStrategySchema.optional(), - nameOverrides: external_exports.record(external_exports.string().min(1), external_exports.string().min(1)).optional(), - selectedFiles: external_exports.array(external_exports.string().min(1)).optional() -}); -var portabilityAdapterOverrideSchema = external_exports.object({ - adapterType: external_exports.string().min(1), - adapterConfig: external_exports.record(external_exports.unknown()).optional() -}); -var companyPortabilityImportSchema = companyPortabilityPreviewSchema.extend({ - adapterOverrides: external_exports.record(external_exports.string().min(1), portabilityAdapterOverrideSchema).optional() -}); - -// packages/shared/src/validators/secret.ts -var envBindingPlainSchema = external_exports.object({ - type: external_exports.literal("plain"), - value: external_exports.string() -}); -var envBindingSecretRefSchema = external_exports.object({ - type: external_exports.literal("secret_ref"), - secretId: external_exports.string().uuid(), - version: external_exports.union([external_exports.literal("latest"), external_exports.number().int().positive()]).optional() -}); -var envBindingSchema = external_exports.union([ - external_exports.string(), - envBindingPlainSchema, - envBindingSecretRefSchema -]); -var envConfigSchema = external_exports.record(envBindingSchema); -var createSecretSchema = external_exports.object({ - name: external_exports.string().min(1), - provider: external_exports.enum(SECRET_PROVIDERS).optional(), - value: external_exports.string().min(1), - description: external_exports.string().optional().nullable(), - externalRef: external_exports.string().optional().nullable() -}); -var rotateSecretSchema = external_exports.object({ - value: external_exports.string().min(1), - externalRef: external_exports.string().optional().nullable() -}); -var updateSecretSchema = external_exports.object({ - name: external_exports.string().min(1).optional(), - description: external_exports.string().optional().nullable(), - externalRef: external_exports.string().optional().nullable() -}); - -// packages/shared/src/validators/agent.ts -var agentPermissionsSchema = external_exports.object({ - canCreateAgents: external_exports.boolean().optional().default(false) -}); -var agentInstructionsBundleModeSchema = external_exports.enum(["managed", "external"]); -var updateAgentInstructionsBundleSchema = external_exports.object({ - mode: agentInstructionsBundleModeSchema.optional(), - rootPath: external_exports.string().trim().min(1).nullable().optional(), - entryFile: external_exports.string().trim().min(1).optional(), - clearLegacyPromptTemplate: external_exports.boolean().optional().default(false) -}); -var upsertAgentInstructionsFileSchema = external_exports.object({ - path: external_exports.string().trim().min(1), - content: external_exports.string(), - clearLegacyPromptTemplate: external_exports.boolean().optional().default(false) -}); -var adapterConfigSchema = external_exports.record(external_exports.unknown()).superRefine((value, ctx) => { - const envValue = value.env; - if (envValue === void 0) return; - const parsed = envConfigSchema.safeParse(envValue); - if (!parsed.success) { - ctx.addIssue({ - code: external_exports.ZodIssueCode.custom, - message: "adapterConfig.env must be a map of valid env bindings", - path: ["env"] - }); - } -}); -var createAgentSchema = external_exports.object({ - name: external_exports.string().min(1), - role: external_exports.enum(AGENT_ROLES).optional().default("general"), - title: external_exports.string().optional().nullable(), - icon: external_exports.enum(AGENT_ICON_NAMES).optional().nullable(), - reportsTo: external_exports.string().uuid().optional().nullable(), - capabilities: external_exports.string().optional().nullable(), - desiredSkills: external_exports.array(external_exports.string().min(1)).optional(), - adapterType: agentAdapterTypeSchema, - adapterConfig: adapterConfigSchema.optional().default({}), - runtimeConfig: external_exports.record(external_exports.unknown()).optional().default({}), - budgetMonthlyCents: external_exports.number().int().nonnegative().optional().default(0), - permissions: agentPermissionsSchema.optional(), - metadata: external_exports.record(external_exports.unknown()).optional().nullable() -}); -var createAgentHireSchema = createAgentSchema.extend({ - sourceIssueId: external_exports.string().uuid().optional().nullable(), - sourceIssueIds: external_exports.array(external_exports.string().uuid()).optional() -}); -var updateAgentSchema = createAgentSchema.omit({ permissions: true }).partial().extend({ - permissions: external_exports.never().optional(), - replaceAdapterConfig: external_exports.boolean().optional(), - status: external_exports.enum(AGENT_STATUSES).optional(), - spentMonthlyCents: external_exports.number().int().nonnegative().optional() -}); -var updateAgentInstructionsPathSchema = external_exports.object({ - path: external_exports.string().trim().min(1).nullable(), - adapterConfigKey: external_exports.string().trim().min(1).optional() -}); -var createAgentKeySchema = external_exports.object({ - name: external_exports.string().min(1).default("default") -}); -var agentMineInboxQuerySchema = external_exports.object({ - userId: external_exports.string().trim().min(1), - status: external_exports.string().trim().min(1).optional().default(INBOX_MINE_ISSUE_STATUS_FILTER) -}); -var wakeAgentSchema = external_exports.object({ - source: external_exports.enum(["timer", "assignment", "on_demand", "automation"]).optional().default("on_demand"), - triggerDetail: external_exports.enum(["manual", "ping", "callback", "system"]).optional(), - reason: external_exports.string().optional().nullable(), - payload: external_exports.record(external_exports.unknown()).optional().nullable(), - idempotencyKey: external_exports.string().optional().nullable(), - forceFreshSession: external_exports.preprocess( - (value) => value === null ? void 0 : value, - external_exports.boolean().optional().default(false) - ) -}); -var resetAgentSessionSchema = external_exports.object({ - taskKey: external_exports.string().min(1).optional().nullable() -}); -var testAdapterEnvironmentSchema = external_exports.object({ - adapterConfig: adapterConfigSchema.optional().default({}) -}); -var updateAgentPermissionsSchema = external_exports.object({ - canCreateAgents: external_exports.boolean(), - canAssignTasks: external_exports.boolean() -}); - -// packages/shared/src/validators/project.ts -var executionWorkspaceStrategySchema2 = external_exports.object({ - type: external_exports.enum(["project_primary", "git_worktree", "adapter_managed", "cloud_sandbox"]).optional(), - baseRef: external_exports.string().optional().nullable(), - branchTemplate: external_exports.string().optional().nullable(), - worktreeParentDir: external_exports.string().optional().nullable(), - provisionCommand: external_exports.string().optional().nullable(), - teardownCommand: external_exports.string().optional().nullable() -}).strict(); -var projectExecutionWorkspacePolicySchema = external_exports.object({ - enabled: external_exports.boolean(), - defaultMode: external_exports.enum(["shared_workspace", "isolated_workspace", "operator_branch", "adapter_default"]).optional(), - allowIssueOverride: external_exports.boolean().optional(), - defaultProjectWorkspaceId: external_exports.string().uuid().optional().nullable(), - workspaceStrategy: executionWorkspaceStrategySchema2.optional().nullable(), - workspaceRuntime: external_exports.record(external_exports.unknown()).optional().nullable(), - branchPolicy: external_exports.record(external_exports.unknown()).optional().nullable(), - pullRequestPolicy: external_exports.record(external_exports.unknown()).optional().nullable(), - runtimePolicy: external_exports.record(external_exports.unknown()).optional().nullable(), - cleanupPolicy: external_exports.record(external_exports.unknown()).optional().nullable() -}).strict(); -var projectWorkspaceRuntimeConfigSchema = external_exports.object({ - workspaceRuntime: external_exports.record(external_exports.unknown()).optional().nullable(), - desiredState: external_exports.enum(["running", "stopped"]).optional().nullable(), - serviceStates: external_exports.record(external_exports.enum(["running", "stopped"])).optional().nullable() -}).strict(); -var projectWorkspaceSourceTypeSchema = external_exports.enum(["local_path", "git_repo", "remote_managed", "non_git_path"]); -var projectWorkspaceVisibilitySchema = external_exports.enum(["default", "advanced"]); -var projectWorkspaceFields = { - name: external_exports.string().min(1).optional(), - sourceType: projectWorkspaceSourceTypeSchema.optional(), - cwd: external_exports.string().min(1).optional().nullable(), - repoUrl: external_exports.string().url().optional().nullable(), - repoRef: external_exports.string().optional().nullable(), - defaultRef: external_exports.string().optional().nullable(), - visibility: projectWorkspaceVisibilitySchema.optional(), - setupCommand: external_exports.string().optional().nullable(), - cleanupCommand: external_exports.string().optional().nullable(), - remoteProvider: external_exports.string().optional().nullable(), - remoteWorkspaceRef: external_exports.string().optional().nullable(), - sharedWorkspaceKey: external_exports.string().optional().nullable(), - metadata: external_exports.record(external_exports.unknown()).optional().nullable(), - runtimeConfig: projectWorkspaceRuntimeConfigSchema.optional().nullable() -}; -function validateProjectWorkspace(value, ctx) { - const sourceType = value.sourceType ?? "local_path"; - const hasCwd = typeof value.cwd === "string" && value.cwd.trim().length > 0; - const hasRepo = typeof value.repoUrl === "string" && value.repoUrl.trim().length > 0; - const hasRemoteRef = typeof value.remoteWorkspaceRef === "string" && value.remoteWorkspaceRef.trim().length > 0; - if (sourceType === "remote_managed") { - if (!hasRemoteRef && !hasRepo) { - ctx.addIssue({ - code: external_exports.ZodIssueCode.custom, - message: "Remote-managed workspace requires remoteWorkspaceRef or repoUrl.", - path: ["remoteWorkspaceRef"] - }); - } - return; - } - if (!hasCwd && !hasRepo) { - ctx.addIssue({ - code: external_exports.ZodIssueCode.custom, - message: "Workspace requires at least one of cwd or repoUrl.", - path: ["cwd"] - }); - } -} -var createProjectWorkspaceSchema = external_exports.object({ - ...projectWorkspaceFields, - isPrimary: external_exports.boolean().optional().default(false) -}).superRefine(validateProjectWorkspace); -var updateProjectWorkspaceSchema = external_exports.object({ - ...projectWorkspaceFields, - isPrimary: external_exports.boolean().optional() -}).partial(); -var projectFields = { - /** @deprecated Use goalIds instead */ - goalId: external_exports.string().uuid().optional().nullable(), - goalIds: external_exports.array(external_exports.string().uuid()).optional(), - name: external_exports.string().min(1), - description: external_exports.string().optional().nullable(), - status: external_exports.enum(PROJECT_STATUSES).optional().default("backlog"), - leadAgentId: external_exports.string().uuid().optional().nullable(), - targetDate: external_exports.string().optional().nullable(), - color: external_exports.string().optional().nullable(), - env: envConfigSchema.optional().nullable(), - executionWorkspacePolicy: projectExecutionWorkspacePolicySchema.optional().nullable(), - archivedAt: external_exports.string().datetime().optional().nullable() -}; -var createProjectSchema = external_exports.object({ - ...projectFields, - workspace: createProjectWorkspaceSchema.optional() -}); -var updateProjectSchema = external_exports.object(projectFields).partial(); - -// packages/shared/src/validators/work-product.ts -var issueWorkProductTypeSchema = external_exports.enum([ - "preview_url", - "runtime_service", - "pull_request", - "branch", - "commit", - "artifact", - "document" -]); -var issueWorkProductStatusSchema = external_exports.enum([ - "active", - "ready_for_review", - "approved", - "changes_requested", - "merged", - "closed", - "failed", - "archived", - "draft" -]); -var issueWorkProductReviewStateSchema = external_exports.enum([ - "none", - "needs_board_review", - "approved", - "changes_requested" -]); -var createIssueWorkProductSchema = external_exports.object({ - projectId: external_exports.string().uuid().optional().nullable(), - executionWorkspaceId: external_exports.string().uuid().optional().nullable(), - runtimeServiceId: external_exports.string().uuid().optional().nullable(), - type: issueWorkProductTypeSchema, - provider: external_exports.string().min(1), - externalId: external_exports.string().optional().nullable(), - title: external_exports.string().min(1), - url: external_exports.string().url().optional().nullable(), - status: issueWorkProductStatusSchema.default("active"), - reviewState: issueWorkProductReviewStateSchema.optional().default("none"), - isPrimary: external_exports.boolean().optional().default(false), - healthStatus: external_exports.enum(["unknown", "healthy", "unhealthy"]).optional().default("unknown"), - summary: external_exports.string().optional().nullable(), - metadata: external_exports.record(external_exports.unknown()).optional().nullable(), - createdByRunId: external_exports.string().uuid().optional().nullable() -}); -var updateIssueWorkProductSchema = createIssueWorkProductSchema.partial(); - -// packages/shared/src/validators/goal.ts -var createGoalSchema = external_exports.object({ - title: external_exports.string().min(1), - description: external_exports.string().optional().nullable(), - level: external_exports.enum(GOAL_LEVELS).optional().default("task"), - status: external_exports.enum(GOAL_STATUSES).optional().default("planned"), - parentId: external_exports.string().uuid().optional().nullable(), - ownerAgentId: external_exports.string().uuid().optional().nullable() -}); -var updateGoalSchema = createGoalSchema.partial(); - -// packages/shared/src/validators/approval.ts -var createApprovalSchema = external_exports.object({ - type: external_exports.enum(APPROVAL_TYPES), - requestedByAgentId: external_exports.string().uuid().optional().nullable(), - payload: external_exports.record(external_exports.unknown()), - issueIds: external_exports.array(external_exports.string().uuid()).optional() -}); -var resolveApprovalSchema = external_exports.object({ - decisionNote: external_exports.string().optional().nullable(), - decidedByUserId: external_exports.string().optional().default("board") -}); -var requestApprovalRevisionSchema = external_exports.object({ - decisionNote: external_exports.string().optional().nullable(), - decidedByUserId: external_exports.string().optional().default("board") -}); -var resubmitApprovalSchema = external_exports.object({ - payload: external_exports.record(external_exports.unknown()).optional() -}); -var addApprovalCommentSchema = external_exports.object({ - body: external_exports.string().min(1) -}); - -// packages/shared/src/validators/cost.ts -var createCostEventSchema = external_exports.object({ - agentId: external_exports.string().uuid(), - issueId: external_exports.string().uuid().optional().nullable(), - projectId: external_exports.string().uuid().optional().nullable(), - goalId: external_exports.string().uuid().optional().nullable(), - heartbeatRunId: external_exports.string().uuid().optional().nullable(), - billingCode: external_exports.string().optional().nullable(), - provider: external_exports.string().min(1), - biller: external_exports.string().min(1).optional(), - billingType: external_exports.enum(BILLING_TYPES).optional().default("unknown"), - model: external_exports.string().min(1), - inputTokens: external_exports.number().int().nonnegative().optional().default(0), - cachedInputTokens: external_exports.number().int().nonnegative().optional().default(0), - outputTokens: external_exports.number().int().nonnegative().optional().default(0), - costCents: external_exports.number().int().nonnegative(), - occurredAt: external_exports.string().datetime() -}).transform((value) => ({ - ...value, - biller: value.biller ?? value.provider -})); -var updateBudgetSchema = external_exports.object({ - budgetMonthlyCents: external_exports.number().int().nonnegative() -}); - -// packages/shared/src/validators/finance.ts -var createFinanceEventSchema = external_exports.object({ - agentId: external_exports.string().uuid().optional().nullable(), - issueId: external_exports.string().uuid().optional().nullable(), - projectId: external_exports.string().uuid().optional().nullable(), - goalId: external_exports.string().uuid().optional().nullable(), - heartbeatRunId: external_exports.string().uuid().optional().nullable(), - costEventId: external_exports.string().uuid().optional().nullable(), - billingCode: external_exports.string().optional().nullable(), - description: external_exports.string().max(500).optional().nullable(), - eventKind: external_exports.enum(FINANCE_EVENT_KINDS), - direction: external_exports.enum(FINANCE_DIRECTIONS).optional().default("debit"), - biller: external_exports.string().min(1), - provider: external_exports.string().min(1).optional().nullable(), - executionAdapterType: external_exports.enum(AGENT_ADAPTER_TYPES).optional().nullable(), - pricingTier: external_exports.string().min(1).optional().nullable(), - region: external_exports.string().min(1).optional().nullable(), - model: external_exports.string().min(1).optional().nullable(), - quantity: external_exports.number().int().nonnegative().optional().nullable(), - unit: external_exports.enum(FINANCE_UNITS).optional().nullable(), - amountCents: external_exports.number().int().nonnegative(), - currency: external_exports.string().length(3).optional().default("USD"), - estimated: external_exports.boolean().optional().default(false), - externalInvoiceId: external_exports.string().optional().nullable(), - metadataJson: external_exports.record(external_exports.string(), external_exports.unknown()).optional().nullable(), - occurredAt: external_exports.string().datetime() -}).transform((value) => ({ - ...value, - currency: value.currency.toUpperCase() -})); - -// packages/shared/src/validators/asset.ts -var createAssetImageMetadataSchema = external_exports.object({ - namespace: external_exports.string().trim().min(1).max(120).regex(/^[a-zA-Z0-9/_-]+$/).optional() -}); - -// packages/shared/src/validators/access.ts -var createCompanyInviteSchema = external_exports.object({ - allowedJoinTypes: external_exports.enum(INVITE_JOIN_TYPES).default("both"), - defaultsPayload: external_exports.record(external_exports.string(), external_exports.unknown()).optional().nullable(), - agentMessage: external_exports.string().max(4e3).optional().nullable() -}); -var createOpenClawInvitePromptSchema = external_exports.object({ - agentMessage: external_exports.string().max(4e3).optional().nullable() -}); -var acceptInviteSchema = external_exports.object({ - requestType: external_exports.enum(JOIN_REQUEST_TYPES), - agentName: external_exports.string().min(1).max(120).optional(), - adapterType: optionalAgentAdapterTypeSchema, - capabilities: external_exports.string().max(4e3).optional().nullable(), - agentDefaultsPayload: external_exports.record(external_exports.string(), external_exports.unknown()).optional().nullable(), - // OpenClaw join compatibility fields accepted at top level. - responsesWebhookUrl: external_exports.string().max(4e3).optional().nullable(), - responsesWebhookMethod: external_exports.string().max(32).optional().nullable(), - responsesWebhookHeaders: external_exports.record(external_exports.string(), external_exports.unknown()).optional().nullable(), - taskcoreApiUrl: external_exports.string().max(4e3).optional().nullable(), - webhookAuthHeader: external_exports.string().max(4e3).optional().nullable() -}); -var listJoinRequestsQuerySchema = external_exports.object({ - status: external_exports.enum(JOIN_REQUEST_STATUSES).optional(), - requestType: external_exports.enum(JOIN_REQUEST_TYPES).optional() -}); -var claimJoinRequestApiKeySchema = external_exports.object({ - claimSecret: external_exports.string().min(16).max(256) -}); -var boardCliAuthAccessLevelSchema = external_exports.enum([ - "board", - "instance_admin_required" -]); -var createCliAuthChallengeSchema = external_exports.object({ - command: external_exports.string().min(1).max(240), - clientName: external_exports.string().max(120).optional().nullable(), - requestedAccess: boardCliAuthAccessLevelSchema.default("board"), - requestedCompanyId: external_exports.string().uuid().optional().nullable() -}); -var resolveCliAuthChallengeSchema = external_exports.object({ - token: external_exports.string().min(16).max(256) -}); -var updateMemberPermissionsSchema = external_exports.object({ - grants: external_exports.array( - external_exports.object({ - permissionKey: external_exports.enum(PERMISSION_KEYS), - scope: external_exports.record(external_exports.string(), external_exports.unknown()).optional().nullable() - }) - ) -}); -var updateUserCompanyAccessSchema = external_exports.object({ - companyIds: external_exports.array(external_exports.string().uuid()).default([]) -}); - -// packages/shared/src/validators/plugin.ts -var jsonSchemaSchema = external_exports.record(external_exports.unknown()).refine( - (val) => { - if (Object.keys(val).length === 0) return true; - return typeof val.type === "string" || val.$ref !== void 0 || val.oneOf !== void 0 || val.anyOf !== void 0 || val.allOf !== void 0; - }, - { message: "Must be a valid JSON Schema object (requires at least a 'type', '$ref', or composition keyword)" } -); -var CRON_FIELD_PATTERN = /^(\*(?:\/[0-9]+)?|[0-9]+(?:-[0-9]+)?(?:\/[0-9]+)?)(?:,(\*(?:\/[0-9]+)?|[0-9]+(?:-[0-9]+)?(?:\/[0-9]+)?))*$/; -function isValidCronExpression(expression) { - const trimmed = expression.trim(); - if (!trimmed) return false; - const fields = trimmed.split(/\s+/); - if (fields.length !== 5) return false; - return fields.every((f5) => CRON_FIELD_PATTERN.test(f5)); -} -var pluginJobDeclarationSchema = external_exports.object({ - jobKey: external_exports.string().min(1), - displayName: external_exports.string().min(1), - description: external_exports.string().optional(), - schedule: external_exports.string().refine( - (val) => isValidCronExpression(val), - { message: "schedule must be a valid 5-field cron expression (e.g. '*/15 * * * *')" } - ).optional() -}); -var pluginWebhookDeclarationSchema = external_exports.object({ - endpointKey: external_exports.string().min(1), - displayName: external_exports.string().min(1), - description: external_exports.string().optional() -}); -var pluginToolDeclarationSchema = external_exports.object({ - name: external_exports.string().min(1), - displayName: external_exports.string().min(1), - description: external_exports.string().min(1), - parametersSchema: jsonSchemaSchema -}); -var pluginUiSlotDeclarationSchema = external_exports.object({ - type: external_exports.enum(PLUGIN_UI_SLOT_TYPES), - id: external_exports.string().min(1), - displayName: external_exports.string().min(1), - exportName: external_exports.string().min(1), - entityTypes: external_exports.array(external_exports.enum(PLUGIN_UI_SLOT_ENTITY_TYPES)).optional(), - routePath: external_exports.string().regex(/^[a-z0-9][a-z0-9-]*$/, { - message: "routePath must be a lowercase single-segment slug (letters, numbers, hyphens)" - }).optional(), - order: external_exports.number().int().optional() -}).superRefine((value, ctx) => { - const entityScopedTypes = ["detailTab", "taskDetailView", "contextMenuItem", "commentAnnotation", "commentContextMenuItem", "projectSidebarItem"]; - if (entityScopedTypes.includes(value.type) && (!value.entityTypes || value.entityTypes.length === 0)) { - ctx.addIssue({ - code: external_exports.ZodIssueCode.custom, - message: `${value.type} slots require at least one entityType`, - path: ["entityTypes"] - }); - } - if (value.type === "projectSidebarItem" && value.entityTypes && !value.entityTypes.includes("project")) { - ctx.addIssue({ - code: external_exports.ZodIssueCode.custom, - message: 'projectSidebarItem slots require entityTypes to include "project"', - path: ["entityTypes"] - }); - } - if (value.type === "commentAnnotation" && value.entityTypes && !value.entityTypes.includes("comment")) { - ctx.addIssue({ - code: external_exports.ZodIssueCode.custom, - message: 'commentAnnotation slots require entityTypes to include "comment"', - path: ["entityTypes"] - }); - } - if (value.type === "commentContextMenuItem" && value.entityTypes && !value.entityTypes.includes("comment")) { - ctx.addIssue({ - code: external_exports.ZodIssueCode.custom, - message: 'commentContextMenuItem slots require entityTypes to include "comment"', - path: ["entityTypes"] - }); - } - if (value.routePath && value.type !== "page") { - ctx.addIssue({ - code: external_exports.ZodIssueCode.custom, - message: "routePath is only supported for page slots", - path: ["routePath"] - }); - } - if (value.routePath && PLUGIN_RESERVED_COMPANY_ROUTE_SEGMENTS.includes(value.routePath)) { - ctx.addIssue({ - code: external_exports.ZodIssueCode.custom, - message: `routePath "${value.routePath}" is reserved by the host`, - path: ["routePath"] - }); - } -}); -var entityScopedLauncherPlacementZones = [ - "detailTab", - "taskDetailView", - "contextMenuItem", - "commentAnnotation", - "commentContextMenuItem", - "projectSidebarItem" -]; -var launcherBoundsByEnvironment = { - hostInline: ["inline", "compact", "default"], - hostOverlay: ["compact", "default", "wide", "full"], - hostRoute: ["default", "wide", "full"], - external: [], - iframe: ["compact", "default", "wide", "full"] -}; -var pluginLauncherActionDeclarationSchema = external_exports.object({ - type: external_exports.enum(PLUGIN_LAUNCHER_ACTIONS), - target: external_exports.string().min(1), - params: external_exports.record(external_exports.unknown()).optional() -}).superRefine((value, ctx) => { - if (value.type === "performAction" && value.target.includes("/")) { - ctx.addIssue({ - code: external_exports.ZodIssueCode.custom, - message: "performAction launchers must target an action key, not a route or URL", - path: ["target"] - }); - } - if (value.type === "navigate" && /^https?:\/\//.test(value.target)) { - ctx.addIssue({ - code: external_exports.ZodIssueCode.custom, - message: "navigate launchers must target a host route, not an absolute URL", - path: ["target"] - }); - } -}); -var pluginLauncherRenderDeclarationSchema = external_exports.object({ - environment: external_exports.enum(PLUGIN_LAUNCHER_RENDER_ENVIRONMENTS), - bounds: external_exports.enum(PLUGIN_LAUNCHER_BOUNDS).optional() -}).superRefine((value, ctx) => { - if (!value.bounds) { - return; - } - const supportedBounds = launcherBoundsByEnvironment[value.environment]; - if (!supportedBounds.includes(value.bounds)) { - ctx.addIssue({ - code: external_exports.ZodIssueCode.custom, - message: `bounds "${value.bounds}" is not supported for render environment "${value.environment}"`, - path: ["bounds"] - }); - } -}); -var pluginLauncherDeclarationSchema = external_exports.object({ - id: external_exports.string().min(1), - displayName: external_exports.string().min(1), - description: external_exports.string().optional(), - placementZone: external_exports.enum(PLUGIN_LAUNCHER_PLACEMENT_ZONES), - exportName: external_exports.string().min(1).optional(), - entityTypes: external_exports.array(external_exports.enum(PLUGIN_UI_SLOT_ENTITY_TYPES)).optional(), - order: external_exports.number().int().optional(), - action: pluginLauncherActionDeclarationSchema, - render: pluginLauncherRenderDeclarationSchema.optional() -}).superRefine((value, ctx) => { - if (entityScopedLauncherPlacementZones.some((zone) => zone === value.placementZone) && (!value.entityTypes || value.entityTypes.length === 0)) { - ctx.addIssue({ - code: external_exports.ZodIssueCode.custom, - message: `${value.placementZone} launchers require at least one entityType`, - path: ["entityTypes"] - }); - } - if (value.placementZone === "projectSidebarItem" && value.entityTypes && !value.entityTypes.includes("project")) { - ctx.addIssue({ - code: external_exports.ZodIssueCode.custom, - message: 'projectSidebarItem launchers require entityTypes to include "project"', - path: ["entityTypes"] - }); - } - if (value.action.type === "performAction" && value.render) { - ctx.addIssue({ - code: external_exports.ZodIssueCode.custom, - message: "performAction launchers cannot declare render hints", - path: ["render"] - }); - } - if (["openModal", "openDrawer", "openPopover"].includes(value.action.type) && !value.render) { - ctx.addIssue({ - code: external_exports.ZodIssueCode.custom, - message: `${value.action.type} launchers require render metadata`, - path: ["render"] - }); - } - if (value.action.type === "openModal" && value.render?.environment === "hostInline") { - ctx.addIssue({ - code: external_exports.ZodIssueCode.custom, - message: "openModal launchers cannot use the hostInline render environment", - path: ["render", "environment"] - }); - } - if (value.action.type === "openDrawer" && value.render && !["hostOverlay", "iframe"].includes(value.render.environment)) { - ctx.addIssue({ - code: external_exports.ZodIssueCode.custom, - message: "openDrawer launchers must use hostOverlay or iframe render environments", - path: ["render", "environment"] - }); - } - if (value.action.type === "openPopover" && value.render?.environment === "hostRoute") { - ctx.addIssue({ - code: external_exports.ZodIssueCode.custom, - message: "openPopover launchers cannot use the hostRoute render environment", - path: ["render", "environment"] - }); - } -}); -var pluginManifestV1Schema = external_exports.object({ - id: external_exports.string().min(1).regex( - /^[a-z0-9][a-z0-9._-]*$/, - "Plugin id must start with a lowercase alphanumeric and contain only lowercase letters, digits, dots, hyphens, or underscores" - ), - apiVersion: external_exports.literal(1), - version: external_exports.string().min(1).regex( - /^\d+\.\d+\.\d+(-[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?(\+[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?$/, - "Version must follow semver (e.g. 1.0.0 or 1.0.0-beta.1)" - ), - displayName: external_exports.string().min(1).max(100), - description: external_exports.string().min(1).max(500), - author: external_exports.string().min(1).max(200), - categories: external_exports.array(external_exports.enum(PLUGIN_CATEGORIES)).min(1), - minimumHostVersion: external_exports.string().regex( - /^\d+\.\d+\.\d+(-[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?(\+[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?$/, - "minimumHostVersion must follow semver (e.g. 1.0.0)" - ).optional(), - minimumTaskcoreVersion: external_exports.string().regex( - /^\d+\.\d+\.\d+(-[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?(\+[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?$/, - "minimumTaskcoreVersion must follow semver (e.g. 1.0.0)" - ).optional(), - capabilities: external_exports.array(external_exports.enum(PLUGIN_CAPABILITIES)).min(1), - entrypoints: external_exports.object({ - worker: external_exports.string().min(1), - ui: external_exports.string().min(1).optional() - }), - instanceConfigSchema: jsonSchemaSchema.optional(), - jobs: external_exports.array(pluginJobDeclarationSchema).optional(), - webhooks: external_exports.array(pluginWebhookDeclarationSchema).optional(), - tools: external_exports.array(pluginToolDeclarationSchema).optional(), - launchers: external_exports.array(pluginLauncherDeclarationSchema).optional(), - ui: external_exports.object({ - slots: external_exports.array(pluginUiSlotDeclarationSchema).min(1).optional(), - launchers: external_exports.array(pluginLauncherDeclarationSchema).optional() - }).optional() -}).superRefine((manifest, ctx) => { - const hasUiSlots = (manifest.ui?.slots?.length ?? 0) > 0; - const hasUiLaunchers = (manifest.ui?.launchers?.length ?? 0) > 0; - if ((hasUiSlots || hasUiLaunchers) && !manifest.entrypoints.ui) { - ctx.addIssue({ - code: external_exports.ZodIssueCode.custom, - message: "entrypoints.ui is required when ui.slots or ui.launchers are declared", - path: ["entrypoints", "ui"] - }); - } - if (manifest.minimumHostVersion && manifest.minimumTaskcoreVersion && manifest.minimumHostVersion !== manifest.minimumTaskcoreVersion) { - ctx.addIssue({ - code: external_exports.ZodIssueCode.custom, - message: "minimumHostVersion and minimumTaskcoreVersion must match when both are declared", - path: ["minimumHostVersion"] - }); - } - if (manifest.tools && manifest.tools.length > 0) { - if (!manifest.capabilities.includes("agent.tools.register")) { - ctx.addIssue({ - code: external_exports.ZodIssueCode.custom, - message: "Capability 'agent.tools.register' is required when tools are declared", - path: ["capabilities"] - }); - } - } - if (manifest.jobs && manifest.jobs.length > 0) { - if (!manifest.capabilities.includes("jobs.schedule")) { - ctx.addIssue({ - code: external_exports.ZodIssueCode.custom, - message: "Capability 'jobs.schedule' is required when jobs are declared", - path: ["capabilities"] - }); - } - } - if (manifest.webhooks && manifest.webhooks.length > 0) { - if (!manifest.capabilities.includes("webhooks.receive")) { - ctx.addIssue({ - code: external_exports.ZodIssueCode.custom, - message: "Capability 'webhooks.receive' is required when webhooks are declared", - path: ["capabilities"] - }); - } - } - if (manifest.jobs) { - const jobKeys = manifest.jobs.map((j5) => j5.jobKey); - const duplicates = jobKeys.filter((key, i5) => jobKeys.indexOf(key) !== i5); - if (duplicates.length > 0) { - ctx.addIssue({ - code: external_exports.ZodIssueCode.custom, - message: `Duplicate job keys: ${[...new Set(duplicates)].join(", ")}`, - path: ["jobs"] - }); - } - } - if (manifest.webhooks) { - const endpointKeys = manifest.webhooks.map((w5) => w5.endpointKey); - const duplicates = endpointKeys.filter((key, i5) => endpointKeys.indexOf(key) !== i5); - if (duplicates.length > 0) { - ctx.addIssue({ - code: external_exports.ZodIssueCode.custom, - message: `Duplicate webhook endpoint keys: ${[...new Set(duplicates)].join(", ")}`, - path: ["webhooks"] - }); - } - } - if (manifest.tools) { - const toolNames = manifest.tools.map((t5) => t5.name); - const duplicates = toolNames.filter((name, i5) => toolNames.indexOf(name) !== i5); - if (duplicates.length > 0) { - ctx.addIssue({ - code: external_exports.ZodIssueCode.custom, - message: `Duplicate tool names: ${[...new Set(duplicates)].join(", ")}`, - path: ["tools"] - }); - } - } - if (manifest.ui) { - if (manifest.ui.slots) { - const slotIds = manifest.ui.slots.map((s5) => s5.id); - const duplicates = slotIds.filter((id, i5) => slotIds.indexOf(id) !== i5); - if (duplicates.length > 0) { - ctx.addIssue({ - code: external_exports.ZodIssueCode.custom, - message: `Duplicate UI slot ids: ${[...new Set(duplicates)].join(", ")}`, - path: ["ui", "slots"] - }); - } - } - } - const allLaunchers = [ - ...manifest.launchers ?? [], - ...manifest.ui?.launchers ?? [] - ]; - if (allLaunchers.length > 0) { - const launcherIds = allLaunchers.map((launcher) => launcher.id); - const duplicates = launcherIds.filter((id, i5) => launcherIds.indexOf(id) !== i5); - if (duplicates.length > 0) { - ctx.addIssue({ - code: external_exports.ZodIssueCode.custom, - message: `Duplicate launcher ids: ${[...new Set(duplicates)].join(", ")}`, - path: manifest.ui?.launchers ? ["ui", "launchers"] : ["launchers"] - }); - } - } -}); -var installPluginSchema = external_exports.object({ - packageName: external_exports.string().min(1), - version: external_exports.string().min(1).optional(), - /** Set by loader for local-path installs so the worker can be resolved. */ - packagePath: external_exports.string().min(1).optional() -}); -var upsertPluginConfigSchema = external_exports.object({ - configJson: external_exports.record(external_exports.unknown()) -}); -var patchPluginConfigSchema = external_exports.object({ - configJson: external_exports.record(external_exports.unknown()) -}); -var updatePluginStatusSchema = external_exports.object({ - status: external_exports.enum(PLUGIN_STATUSES), - lastError: external_exports.string().nullable().optional() -}); -var uninstallPluginSchema = external_exports.object({ - removeData: external_exports.boolean().optional().default(false) -}); -var pluginStateScopeKeySchema = external_exports.object({ - scopeKind: external_exports.enum(PLUGIN_STATE_SCOPE_KINDS), - scopeId: external_exports.string().min(1).optional(), - namespace: external_exports.string().min(1).optional(), - stateKey: external_exports.string().min(1) -}); -var setPluginStateSchema = external_exports.object({ - scopeKind: external_exports.enum(PLUGIN_STATE_SCOPE_KINDS), - scopeId: external_exports.string().min(1).optional(), - namespace: external_exports.string().min(1).optional(), - stateKey: external_exports.string().min(1), - /** JSON-serializable value to store. */ - value: external_exports.unknown() -}); -var listPluginStateSchema = external_exports.object({ - scopeKind: external_exports.enum(PLUGIN_STATE_SCOPE_KINDS).optional(), - scopeId: external_exports.string().min(1).optional(), - namespace: external_exports.string().min(1).optional() -}); - -// packages/shared/src/api.ts -var API_PREFIX = "/api"; -var API = { - health: `${API_PREFIX}/health`, - companies: `${API_PREFIX}/companies`, - agents: `${API_PREFIX}/agents`, - projects: `${API_PREFIX}/projects`, - issues: `${API_PREFIX}/issues`, - goals: `${API_PREFIX}/goals`, - approvals: `${API_PREFIX}/approvals`, - secrets: `${API_PREFIX}/secrets`, - costs: `${API_PREFIX}/costs`, - activity: `${API_PREFIX}/activity`, - dashboard: `${API_PREFIX}/dashboard`, - sidebarBadges: `${API_PREFIX}/sidebar-badges`, - sidebarPreferences: `${API_PREFIX}/sidebar-preferences`, - invites: `${API_PREFIX}/invites`, - joinRequests: `${API_PREFIX}/join-requests`, - members: `${API_PREFIX}/members`, - admin: `${API_PREFIX}/admin` -}; - -// packages/shared/src/agent-url-key.ts -var AGENT_URL_KEY_DELIM_RE = /[^a-z0-9]+/g; -var AGENT_URL_KEY_TRIM_RE = /^-+|-+$/g; -var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i; -function isUuidLike(value) { - if (typeof value !== "string") return false; - return UUID_RE.test(value.trim()); -} -function normalizeAgentUrlKey(value) { - if (typeof value !== "string") return null; - const normalized = value.trim().toLowerCase().replace(AGENT_URL_KEY_DELIM_RE, "-").replace(AGENT_URL_KEY_TRIM_RE, ""); - return normalized.length > 0 ? normalized : null; -} -function deriveAgentUrlKey(name, fallback) { - return normalizeAgentUrlKey(name) ?? normalizeAgentUrlKey(fallback) ?? "agent"; -} - -// packages/shared/src/project-url-key.ts -var PROJECT_URL_KEY_DELIM_RE = /[^a-z0-9]+/g; -var PROJECT_URL_KEY_TRIM_RE = /^-+|-+$/g; -var NON_ASCII_RE = /[^\x00-\x7F]/; -var UUID_RE2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i; -function normalizeProjectUrlKey(value) { - if (typeof value !== "string") return null; - const normalized = value.trim().toLowerCase().replace(PROJECT_URL_KEY_DELIM_RE, "-").replace(PROJECT_URL_KEY_TRIM_RE, ""); - return normalized.length > 0 ? normalized : null; -} -function hasNonAsciiContent(value) { - if (typeof value !== "string") return false; - return NON_ASCII_RE.test(value); -} -function shortIdFromUuid(value) { - if (typeof value !== "string" || !UUID_RE2.test(value.trim())) return null; - return value.trim().replace(/-/g, "").slice(0, 8).toLowerCase(); -} -function deriveProjectUrlKey(name, fallback) { - const base = normalizeProjectUrlKey(name); - if (base && !hasNonAsciiContent(name)) return base; - const shortId = shortIdFromUuid(fallback); - if (base && shortId) return `${base}-${shortId}`; - if (shortId) return shortId; - return base ?? normalizeProjectUrlKey(fallback) ?? "project"; -} - -// packages/shared/src/project-mentions.ts -var PROJECT_MENTION_SCHEME = "project://"; -var AGENT_MENTION_SCHEME = "agent://"; -var SKILL_MENTION_SCHEME = "skill://"; -var HEX_COLOR_RE = /^[0-9a-f]{6}$/i; -var HEX_COLOR_SHORT_RE = /^[0-9a-f]{3}$/i; -var HEX_COLOR_WITH_HASH_RE = /^#[0-9a-f]{6}$/i; -var HEX_COLOR_SHORT_WITH_HASH_RE = /^#[0-9a-f]{3}$/i; -var PROJECT_MENTION_LINK_RE = /\[[^\]]*]\((project:\/\/[^)\s]+)\)/gi; -var AGENT_MENTION_LINK_RE = /\[[^\]]*]\((agent:\/\/[^)\s]+)\)/gi; -var SKILL_MENTION_LINK_RE = /\[[^\]]*]\((skill:\/\/[^)\s]+)\)/gi; -var AGENT_ICON_NAME_RE = /^[a-z0-9-]+$/i; -var SKILL_SLUG_RE = /^[a-z0-9][a-z0-9-]*$/i; -function normalizeHexColor(input) { - if (!input) return null; - const trimmed = input.trim(); - if (!trimmed) return null; - if (HEX_COLOR_WITH_HASH_RE.test(trimmed)) { - return trimmed.toLowerCase(); - } - if (HEX_COLOR_RE.test(trimmed)) { - return `#${trimmed.toLowerCase()}`; - } - if (HEX_COLOR_SHORT_WITH_HASH_RE.test(trimmed)) { - const raw = trimmed.slice(1).toLowerCase(); - return `#${raw[0]}${raw[0]}${raw[1]}${raw[1]}${raw[2]}${raw[2]}`; - } - if (HEX_COLOR_SHORT_RE.test(trimmed)) { - const raw = trimmed.toLowerCase(); - return `#${raw[0]}${raw[0]}${raw[1]}${raw[1]}${raw[2]}${raw[2]}`; - } - return null; -} -function parseProjectMentionHref(href) { - if (!href.startsWith(PROJECT_MENTION_SCHEME)) return null; - let url2; - try { - url2 = new URL(href); - } catch { - return null; - } - if (url2.protocol !== "project:") return null; - const projectId = `${url2.hostname}${url2.pathname}`.replace(/^\/+/, "").trim(); - if (!projectId) return null; - const color = normalizeHexColor(url2.searchParams.get("c") ?? url2.searchParams.get("color")); - return { - projectId, - color - }; -} -function parseAgentMentionHref(href) { - if (!href.startsWith(AGENT_MENTION_SCHEME)) return null; - let url2; - try { - url2 = new URL(href); - } catch { - return null; - } - if (url2.protocol !== "agent:") return null; - const agentId = `${url2.hostname}${url2.pathname}`.replace(/^\/+/, "").trim(); - if (!agentId) return null; - return { - agentId, - icon: normalizeAgentIcon(url2.searchParams.get("i") ?? url2.searchParams.get("icon")) - }; -} -function parseSkillMentionHref(href) { - if (!href.startsWith(SKILL_MENTION_SCHEME)) return null; - let url2; - try { - url2 = new URL(href); - } catch { - return null; - } - if (url2.protocol !== "skill:") return null; - const skillId = `${url2.hostname}${url2.pathname}`.replace(/^\/+/, "").trim(); - if (!skillId) return null; - return { - skillId, - slug: normalizeSkillSlug(url2.searchParams.get("s") ?? url2.searchParams.get("slug")) - }; -} -function extractProjectMentionIds(markdown) { - if (!markdown) return []; - const ids = /* @__PURE__ */ new Set(); - const re = new RegExp(PROJECT_MENTION_LINK_RE); - let match; - while ((match = re.exec(markdown)) !== null) { - const parsed = parseProjectMentionHref(match[1]); - if (parsed) ids.add(parsed.projectId); - } - return [...ids]; -} -function extractAgentMentionIds(markdown) { - if (!markdown) return []; - const ids = /* @__PURE__ */ new Set(); - const re = new RegExp(AGENT_MENTION_LINK_RE); - let match; - while ((match = re.exec(markdown)) !== null) { - const parsed = parseAgentMentionHref(match[1]); - if (parsed) ids.add(parsed.agentId); - } - return [...ids]; -} -function extractSkillMentionIds(markdown) { - if (!markdown) return []; - const ids = /* @__PURE__ */ new Set(); - const re = new RegExp(SKILL_MENTION_LINK_RE); - let match; - while ((match = re.exec(markdown)) !== null) { - const parsed = parseSkillMentionHref(match[1]); - if (parsed) ids.add(parsed.skillId); - } - return [...ids]; -} -function normalizeAgentIcon(input) { - if (!input) return null; - const trimmed = input.trim().toLowerCase(); - if (!trimmed || !AGENT_ICON_NAME_RE.test(trimmed)) return null; - return trimmed; -} -function normalizeSkillSlug(input) { - if (!input) return null; - const trimmed = input.trim().toLowerCase(); - if (!trimmed || !SKILL_SLUG_RE.test(trimmed)) return null; - return trimmed; -} - -// packages/shared/src/routine-variables.ts -var ROUTINE_VARIABLE_MATCHER = /\{\{\s*([A-Za-z][A-Za-z0-9_]*)\s*\}\}/g; -var BUILTIN_ROUTINE_VARIABLE_NAMES = /* @__PURE__ */ new Set(["date"]); -function isBuiltinRoutineVariable(name) { - return BUILTIN_ROUTINE_VARIABLE_NAMES.has(name); -} -function getBuiltinRoutineVariableValues() { - return { - date: (/* @__PURE__ */ new Date()).toISOString().slice(0, 10) - }; -} -function normalizeRoutineTemplateInput(input) { - const templates = Array.isArray(input) ? input : [input]; - return templates.filter((template) => typeof template === "string" && template.length > 0); -} -function extractRoutineVariableNames(template) { - const found = /* @__PURE__ */ new Set(); - for (const source of normalizeRoutineTemplateInput(template)) { - for (const match of source.matchAll(ROUTINE_VARIABLE_MATCHER)) { - const name = match[1]; - if (name && !found.has(name)) { - found.add(name); - } - } - } - return [...found]; -} -function defaultRoutineVariable(name) { - return { - name, - label: null, - type: "text", - defaultValue: null, - required: true, - options: [] - }; -} -function syncRoutineVariablesWithTemplate(template, existing) { - const names = extractRoutineVariableNames(template).filter((name) => !isBuiltinRoutineVariable(name)); - const existingByName = new Map((existing ?? []).map((variable) => [variable.name, variable])); - return names.map((name) => existingByName.get(name) ?? defaultRoutineVariable(name)); -} -function stringifyRoutineVariableValue(value) { - if (typeof value === "string") return value; - if (typeof value === "number" || typeof value === "boolean") return String(value); - if (value == null) return ""; - try { - return JSON.stringify(value); - } catch { - return String(value); - } -} -function interpolateRoutineTemplate(template, values2) { - if (template == null) return null; - if (!values2 || Object.keys(values2).length === 0) return template; - return template.replace(ROUTINE_VARIABLE_MATCHER, (match, rawName) => { - if (!(rawName in values2)) return match; - return stringifyRoutineVariableValue(values2[rawName]); - }); -} - -// packages/shared/src/config-schema.ts -var configMetaSchema = external_exports.object({ - version: external_exports.literal(1), - updatedAt: external_exports.string(), - source: external_exports.enum(["onboard", "configure", "doctor"]) -}); -var llmConfigSchema = external_exports.object({ - provider: external_exports.enum(["claude", "openai"]), - apiKey: external_exports.string().optional() -}); -var databaseBackupConfigSchema = external_exports.object({ - enabled: external_exports.boolean().default(true), - intervalMinutes: external_exports.number().int().min(1).max(7 * 24 * 60).default(60), - retentionDays: external_exports.number().int().min(1).max(3650).default(7), - dir: external_exports.string().default("~/.taskcore/instances/default/data/backups") -}); -var databaseConfigSchema = external_exports.object({ - mode: external_exports.enum(["embedded-postgres", "postgres"]).default("embedded-postgres"), - connectionString: external_exports.string().optional(), - embeddedPostgresDataDir: external_exports.string().default("~/.taskcore/instances/default/db"), - embeddedPostgresPort: external_exports.number().int().min(1).max(65535).default(54329), - backup: databaseBackupConfigSchema.default({ - enabled: true, - intervalMinutes: 60, - retentionDays: 7, - dir: "~/.taskcore/instances/default/data/backups" - }) -}); -var loggingConfigSchema = external_exports.object({ - mode: external_exports.enum(["file", "cloud"]), - logDir: external_exports.string().default("~/.taskcore/instances/default/logs") -}); -var serverConfigSchema = external_exports.object({ - deploymentMode: external_exports.enum(DEPLOYMENT_MODES).default("local_trusted"), - exposure: external_exports.enum(DEPLOYMENT_EXPOSURES).default("private"), - bind: external_exports.enum(BIND_MODES).optional(), - customBindHost: external_exports.string().optional(), - host: external_exports.string().default("127.0.0.1"), - port: external_exports.number().int().min(1).max(65535).default(3100), - allowedHostnames: external_exports.array(external_exports.string().min(1)).default([]), - serveUi: external_exports.boolean().default(true) -}); -var authConfigSchema = external_exports.object({ - baseUrlMode: external_exports.enum(AUTH_BASE_URL_MODES).default("auto"), - publicBaseUrl: external_exports.string().url().optional(), - disableSignUp: external_exports.boolean().default(false) -}); -var storageLocalDiskConfigSchema = external_exports.object({ - baseDir: external_exports.string().default("~/.taskcore/instances/default/data/storage") -}); -var storageS3ConfigSchema = external_exports.object({ - bucket: external_exports.string().min(1).default("taskcore"), - region: external_exports.string().min(1).default("us-east-1"), - endpoint: external_exports.string().optional(), - prefix: external_exports.string().default(""), - forcePathStyle: external_exports.boolean().default(false) -}); -var storageConfigSchema = external_exports.object({ - provider: external_exports.enum(STORAGE_PROVIDERS).default("local_disk"), - localDisk: storageLocalDiskConfigSchema.default({ - baseDir: "~/.taskcore/instances/default/data/storage" - }), - s3: storageS3ConfigSchema.default({ - bucket: "taskcore", - region: "us-east-1", - prefix: "", - forcePathStyle: false - }) -}); -var secretsLocalEncryptedConfigSchema = external_exports.object({ - keyFilePath: external_exports.string().default("~/.taskcore/instances/default/secrets/master.key") -}); -var secretsConfigSchema = external_exports.object({ - provider: external_exports.enum(SECRET_PROVIDERS).default("local_encrypted"), - strictMode: external_exports.boolean().default(false), - localEncrypted: secretsLocalEncryptedConfigSchema.default({ - keyFilePath: "~/.taskcore/instances/default/secrets/master.key" - }) -}); -var telemetryConfigSchema = external_exports.object({ - enabled: external_exports.boolean().default(true) -}).default({}); -var taskcoreConfigSchema = external_exports.object({ - $meta: configMetaSchema, - llm: llmConfigSchema.optional(), - database: databaseConfigSchema, - logging: loggingConfigSchema, - server: serverConfigSchema, - telemetry: telemetryConfigSchema, - auth: authConfigSchema.default({ - baseUrlMode: "auto", - disableSignUp: false - }), - storage: storageConfigSchema.default({ - provider: "local_disk", - localDisk: { - baseDir: "~/.taskcore/instances/default/data/storage" - }, - s3: { - bucket: "taskcore", - region: "us-east-1", - prefix: "", - forcePathStyle: false - } - }), - secrets: secretsConfigSchema.default({ - provider: "local_encrypted", - strictMode: false, - localEncrypted: { - keyFilePath: "~/.taskcore/instances/default/secrets/master.key" - } - }) -}).superRefine((value, ctx) => { - if (value.server.deploymentMode === "local_trusted" && value.server.exposure !== "private") { - ctx.addIssue({ - code: external_exports.ZodIssueCode.custom, - message: "server.exposure must be private when deploymentMode is local_trusted", - path: ["server", "exposure"] - }); - } - for (const message2 of validateConfiguredBindMode({ - deploymentMode: value.server.deploymentMode, - deploymentExposure: value.server.exposure, - bind: value.server.bind, - host: value.server.host, - customBindHost: value.server.customBindHost - })) { - ctx.addIssue({ - code: external_exports.ZodIssueCode.custom, - message: message2, - path: message2.includes("customBindHost") ? ["server", "customBindHost"] : ["server", "bind"] - }); - } - if (value.auth.baseUrlMode === "explicit" && !value.auth.publicBaseUrl) { - ctx.addIssue({ - code: external_exports.ZodIssueCode.custom, - message: "auth.publicBaseUrl is required when auth.baseUrlMode is explicit", - path: ["auth", "publicBaseUrl"] - }); - } - if (value.server.exposure === "public" && value.auth.baseUrlMode !== "explicit") { - ctx.addIssue({ - code: external_exports.ZodIssueCode.custom, - message: "auth.baseUrlMode must be explicit when deploymentMode=authenticated and exposure=public", - path: ["auth", "baseUrlMode"] - }); - } - if (value.server.exposure === "public" && !value.auth.publicBaseUrl) { - ctx.addIssue({ - code: external_exports.ZodIssueCode.custom, - message: "auth.publicBaseUrl is required when deploymentMode=authenticated and exposure=public", - path: ["auth", "publicBaseUrl"] - }); - } -}); - -// server/src/paths.ts -import fs2 from "node:fs"; -import path2 from "node:path"; - -// server/src/home-paths.ts -import os2 from "node:os"; -import path from "node:path"; -var DEFAULT_INSTANCE_ID = "default"; -var INSTANCE_ID_RE = /^[a-zA-Z0-9_-]+$/; -var PATH_SEGMENT_RE = /^[a-zA-Z0-9_-]+$/; -var FRIENDLY_PATH_SEGMENT_RE = /[^a-zA-Z0-9._-]+/g; -function expandHomePrefix(value) { - if (value === "~") return os2.homedir(); - if (value.startsWith("~/")) return path.resolve(os2.homedir(), value.slice(2)); - return value; -} -function resolveTaskcoreHomeDir() { - const envHome = process.env.TASKCORE_HOME?.trim(); - if (envHome) return path.resolve(expandHomePrefix(envHome)); - return path.resolve(os2.homedir(), ".taskcore"); -} -function resolveTaskcoreInstanceId() { - const raw = process.env.TASKCORE_INSTANCE_ID?.trim() || DEFAULT_INSTANCE_ID; - if (!INSTANCE_ID_RE.test(raw)) { - throw new Error(`Invalid TASKCORE_INSTANCE_ID '${raw}'.`); - } - return raw; -} -function resolveTaskcoreInstanceRoot() { - return path.resolve(resolveTaskcoreHomeDir(), "instances", resolveTaskcoreInstanceId()); -} -function resolveDefaultConfigPath() { - return path.resolve(resolveTaskcoreInstanceRoot(), "config.json"); -} -function resolveDefaultEmbeddedPostgresDir() { - return path.resolve(resolveTaskcoreInstanceRoot(), "db"); -} -function resolveDefaultLogsDir() { - return path.resolve(resolveTaskcoreInstanceRoot(), "logs"); -} -function resolveDefaultSecretsKeyFilePath() { - return path.resolve(resolveTaskcoreInstanceRoot(), "secrets", "master.key"); -} -function resolveDefaultStorageDir() { - return path.resolve(resolveTaskcoreInstanceRoot(), "data", "storage"); -} -function resolveDefaultBackupDir() { - return path.resolve(resolveTaskcoreInstanceRoot(), "data", "backups"); -} -function resolveDefaultAgentWorkspaceDir(agentId) { - const trimmed = agentId.trim(); - if (!PATH_SEGMENT_RE.test(trimmed)) { - throw new Error(`Invalid agent id for workspace path '${agentId}'.`); - } - return path.resolve(resolveTaskcoreInstanceRoot(), "workspaces", trimmed); -} -function sanitizeFriendlyPathSegment(value, fallback = "_default") { - const trimmed = value?.trim() ?? ""; - if (!trimmed) return fallback; - const sanitized = trimmed.replace(FRIENDLY_PATH_SEGMENT_RE, "-").replace(/^-+|-+$/g, ""); - return sanitized || fallback; -} -function resolveManagedProjectWorkspaceDir(input) { - const companyId = input.companyId.trim(); - const projectId = input.projectId.trim(); - if (!companyId || !projectId) { - throw new Error("Managed project workspace path requires companyId and projectId."); - } - return path.resolve( - resolveTaskcoreInstanceRoot(), - "projects", - sanitizeFriendlyPathSegment(companyId, "company"), - sanitizeFriendlyPathSegment(projectId, "project"), - sanitizeFriendlyPathSegment(input.repoName, "_default") - ); -} -function resolveHomeAwarePath(value) { - return path.resolve(expandHomePrefix(value)); -} - -// server/src/paths.ts -var TASKCORE_CONFIG_BASENAME = "config.json"; -var TASKCORE_ENV_FILENAME = ".env"; -function findConfigFileFromAncestors(startDir) { - const absoluteStartDir = path2.resolve(startDir); - let currentDir = absoluteStartDir; - while (true) { - const candidate = path2.resolve(currentDir, ".taskcore", TASKCORE_CONFIG_BASENAME); - if (fs2.existsSync(candidate)) { - return candidate; - } - const nextDir = path2.resolve(currentDir, ".."); - if (nextDir === currentDir) break; - currentDir = nextDir; - } - return null; -} -function resolveTaskcoreConfigPath(overridePath) { - if (overridePath) return path2.resolve(overridePath); - if (process.env.TASKCORE_CONFIG) return path2.resolve(process.env.TASKCORE_CONFIG); - return findConfigFileFromAncestors(process.cwd()) ?? resolveDefaultConfigPath(); -} -function resolveTaskcoreEnvPath(overrideConfigPath) { - return path2.resolve(path2.dirname(resolveTaskcoreConfigPath(overrideConfigPath)), TASKCORE_ENV_FILENAME); -} - -// server/src/config-file.ts -function readConfigFile() { - const configPath = resolveTaskcoreConfigPath(); - if (!fs3.existsSync(configPath)) return null; - try { - const raw = JSON.parse(fs3.readFileSync(configPath, "utf-8")); - return taskcoreConfigSchema.parse(raw); - } catch { - return null; - } -} - -// server/src/middleware/http-log-policy.ts -var SILENCED_SUCCESS_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD"]); -var SILENCED_SUCCESS_API_PATHS = [ - /^\/api\/health(?:\/|$)/, - /^\/api\/companies\/[^/]+\/activity(?:\/|$)/, - /^\/api\/companies\/[^/]+\/dashboard(?:\/|$)/, - /^\/api\/companies\/[^/]+\/heartbeat-runs(?:\/|$)/, - /^\/api\/companies\/[^/]+\/issues(?:\/|$)/, - /^\/api\/companies\/[^/]+\/live-runs(?:\/|$)/, - /^\/api\/companies\/[^/]+\/sidebar-badges(?:\/|$)/, - /^\/api\/heartbeat-runs\/[^/]+\/log(?:\/|$)/ -]; -var SILENCED_SUCCESS_STATIC_PREFIXES = [ - "/@fs/", - "/@id/", - "/@react-refresh", - "/@vite/", - "/_plugins/", - "/assets/", - "/node_modules/", - "/src/" -]; -var SILENCED_SUCCESS_STATIC_PATHS = /* @__PURE__ */ new Set([ - "/favicon.ico", - "/site.webmanifest" -]); -function normalizePath(url2) { - const trimmed = url2.trim(); - if (trimmed.length === 0) return "/"; - const pathname = trimmed.split("?")[0]?.trim() ?? "/"; - return pathname.length > 0 ? pathname : "/"; -} -function shouldSilenceHttpSuccessLog(method, url2, statusCode) { - if (statusCode >= 400) return false; - if (statusCode === 304) return true; - if (!method || !url2) return false; - if (!SILENCED_SUCCESS_METHODS.has(method.toUpperCase())) return false; - const pathname = normalizePath(url2); - if (SILENCED_SUCCESS_STATIC_PATHS.has(pathname)) return true; - if (SILENCED_SUCCESS_STATIC_PREFIXES.some((prefix) => pathname.startsWith(prefix))) return true; - return SILENCED_SUCCESS_API_PATHS.some((pattern) => pattern.test(pathname)); -} - -// server/src/middleware/logger.ts -function isServerlessRuntime() { - return process.env.VERCEL === "1" || process.env.NOW === "1"; -} -function resolveServerLogDir() { - const envOverride = process.env.TASKCORE_LOG_DIR?.trim(); - if (envOverride) return resolveHomeAwarePath(envOverride); - const fileLogDir = readConfigFile()?.logging.logDir?.trim(); - if (fileLogDir) return resolveHomeAwarePath(fileLogDir); - return resolveDefaultLogsDir(); -} -var logDir = resolveServerLogDir(); -var sharedOpts = { - translateTime: "SYS:HH:MM:ss", - ignore: "pid,hostname", - singleLine: true -}; -var logger = isServerlessRuntime() ? (0, import_pino.default)({ - level: process.env.LOG_LEVEL?.trim() || "info", - redact: ["req.headers.authorization"] -}) : (0, import_pino.default)({ - level: "debug", - redact: ["req.headers.authorization"] -}, import_pino.default.transport({ - targets: [ - { - target: "pino-pretty", - options: { ...sharedOpts, ignore: "pid,hostname,req,res,responseTime", colorize: true, destination: 1 }, - level: "info" - }, - { - target: "pino-pretty", - options: { ...sharedOpts, colorize: false, destination: path3.join(logDir, "server.log"), mkdir: true }, - level: "debug" - } - ] -})); -var httpLogger = (0, import_pino_http.pinoHttp)({ - logger, - customLogLevel(_req, res, err) { - if (shouldSilenceHttpSuccessLog(_req.method, _req.url, res.statusCode)) { - return "silent"; - } - if (err || res.statusCode >= 500) return "error"; - if (res.statusCode >= 400) return "warn"; - return "info"; - }, - customSuccessMessage(req, res) { - return `${req.method} ${req.url} ${res.statusCode}`; - }, - customErrorMessage(req, res, err) { - const ctx = res.__errorContext; - const errMsg = ctx?.error?.message || err?.message || res.err?.message || "unknown error"; - return `${req.method} ${req.url} ${res.statusCode} \u2014 ${errMsg}`; - }, - customProps(req, res) { - if (res.statusCode >= 400) { - const ctx = res.__errorContext; - if (ctx) { - return { - errorContext: ctx.error, - reqBody: ctx.reqBody, - reqParams: ctx.reqParams, - reqQuery: ctx.reqQuery - }; - } - const props = {}; - const { body, params, query } = req; - if (body && typeof body === "object" && Object.keys(body).length > 0) { - props.reqBody = body; - } - if (params && typeof params === "object" && Object.keys(params).length > 0) { - props.reqParams = params; - } - if (query && typeof query === "object" && Object.keys(query).length > 0) { - props.reqQuery = query; - } - if (req.route?.path) { - props.routePath = req.route.path; - } - return props; - } - return {}; - } -}); - -// server/src/errors.ts -var HttpError = class extends Error { - status; - details; - constructor(status, message2, details) { - super(message2); - this.status = status; - this.details = details; - } -}; -function badRequest(message2, details) { - return new HttpError(400, message2, details); -} -function unauthorized(message2 = "Unauthorized") { - return new HttpError(401, message2); -} -function forbidden(message2 = "Forbidden") { - return new HttpError(403, message2); -} -function notFound(message2 = "Not found") { - return new HttpError(404, message2); -} -function conflict(message2, details) { - return new HttpError(409, message2, details); -} -function unprocessable(message2, details) { - return new HttpError(422, message2, details); -} - -// packages/shared/src/telemetry/events.ts -function trackProjectCreated(client2) { - client2.track("project.created"); -} -function trackRoutineCreated(client2) { - client2.track("routine.created"); -} -function trackRoutineRun(client2, dims) { - client2.track("routine.run", { - source: dims.source, - status: dims.status - }); -} -function trackGoalCreated(client2, dims) { - client2.track("goal.created", dims?.goalLevel ? { goal_level: dims.goalLevel } : void 0); -} -function trackAgentCreated(client2, dims) { - client2.track("agent.created", { - agent_role: dims.agentRole, - ...dims.agentId ? { agent_id: dims.agentId } : {} - }); -} -function trackSkillImported(client2, dims) { - client2.track("skill.imported", { - source_type: dims.sourceType, - ...dims.skillRef ? { skill_ref: dims.skillRef } : {} - }); -} -function trackAgentFirstHeartbeat(client2, dims) { - client2.track("agent.first_heartbeat", { - agent_role: dims.agentRole, - ...dims.agentId ? { agent_id: dims.agentId } : {} - }); -} -function trackAgentTaskCompleted(client2, dims) { - client2.track("agent.task_completed", { - agent_role: dims.agentRole, - ...dims.agentId ? { agent_id: dims.agentId } : {}, - ...dims.adapterType ? { adapter_type: dims.adapterType } : {}, - ...dims.model ? { model: dims.model } : {} - }); -} -function trackErrorHandlerCrash(client2, dims) { - client2.track("error.handler_crash", { error_code: dims.errorCode }); -} - -// server/src/version.ts -import { createRequire } from "node:module"; -var require2 = createRequire(import.meta.url); -var pkg = require2("../package.json"); -var serverVersion = pkg.version ?? "0.0.0"; - -// server/src/telemetry.ts -var client = null; -function getTelemetryClient() { - return client; -} - -// server/src/middleware/error-handler.ts -function attachErrorContext(req, res, payload2, rawError) { - res.__errorContext = { - error: payload2, - method: req.method, - url: req.originalUrl, - reqBody: req.body, - reqParams: req.params, - reqQuery: req.query - }; - if (rawError) { - res.err = rawError; - } -} -function errorHandler(err, req, res, _next) { - if (err instanceof HttpError) { - if (err.status >= 500) { - attachErrorContext( - req, - res, - { message: err.message, stack: err.stack, name: err.name, details: err.details }, - err - ); - const tc2 = getTelemetryClient(); - if (tc2) trackErrorHandlerCrash(tc2, { errorCode: err.name }); - } - res.status(err.status).json({ - error: err.message, - ...err.details ? { details: err.details } : {} - }); - return; - } - if (err instanceof ZodError) { - res.status(400).json({ error: "Validation error", details: err.errors }); - return; - } - const rootError = err instanceof Error ? err : new Error(String(err)); - attachErrorContext( - req, - res, - err instanceof Error ? { message: err.message, stack: err.stack, name: err.name } : { message: String(err), raw: err, stack: rootError.stack, name: rootError.name }, - rootError - ); - const tc = getTelemetryClient(); - if (tc) trackErrorHandlerCrash(tc, { errorCode: rootError.name }); - res.status(500).json({ error: "Internal server error" }); -} - -// server/src/middleware/validate.ts -function validate(schema2) { - return (req, _res, next) => { - req.body = schema2.parse(req.body); - next(); - }; -} - -// server/src/middleware/auth.ts -init_drizzle_orm(); -init_src2(); -import { createHash as createHash2 } from "node:crypto"; - -// server/src/agent-auth-jwt.ts -import { createHmac, timingSafeEqual } from "node:crypto"; -var JWT_ALGORITHM = "HS256"; -function parseNumber(value, fallback) { - const parsed = Number(value); - if (!Number.isFinite(parsed) || parsed <= 0) return fallback; - return Math.floor(parsed); -} -function jwtConfig() { - const secret = process.env.TASKCORE_AGENT_JWT_SECRET?.trim() || process.env.BETTER_AUTH_SECRET?.trim(); - if (!secret) return null; - return { - secret, - ttlSeconds: parseNumber(process.env.TASKCORE_AGENT_JWT_TTL_SECONDS, 60 * 60 * 48), - issuer: process.env.TASKCORE_AGENT_JWT_ISSUER ?? "taskcore", - audience: process.env.TASKCORE_AGENT_JWT_AUDIENCE ?? "taskcore-api" - }; -} -function base64UrlEncode(value) { - return Buffer.from(value, "utf8").toString("base64url"); -} -function base64UrlDecode(value) { - return Buffer.from(value, "base64url").toString("utf8"); -} -function signPayload(secret, signingInput) { - return createHmac("sha256", secret).update(signingInput).digest("base64url"); -} -function parseJson(value) { - try { - const parsed = JSON.parse(value); - return parsed && typeof parsed === "object" ? parsed : null; - } catch { - return null; - } -} -function safeCompare(a5, b6) { - const left = Buffer.from(a5); - const right = Buffer.from(b6); - if (left.length !== right.length) return false; - return timingSafeEqual(left, right); -} -function createLocalAgentJwt(agentId, companyId, adapterType, runId) { - const config3 = jwtConfig(); - if (!config3) return null; - const now2 = Math.floor(Date.now() / 1e3); - const claims = { - sub: agentId, - company_id: companyId, - adapter_type: adapterType, - run_id: runId, - iat: now2, - exp: now2 + config3.ttlSeconds, - iss: config3.issuer, - aud: config3.audience - }; - const header = { - alg: JWT_ALGORITHM, - typ: "JWT" - }; - const signingInput = `${base64UrlEncode(JSON.stringify(header))}.${base64UrlEncode(JSON.stringify(claims))}`; - const signature = signPayload(config3.secret, signingInput); - return `${signingInput}.${signature}`; -} -function verifyLocalAgentJwt(token) { - if (!token) return null; - const config3 = jwtConfig(); - if (!config3) return null; - const parts = token.split("."); - if (parts.length !== 3) return null; - const [headerB64, claimsB64, signature] = parts; - const header = parseJson(base64UrlDecode(headerB64)); - if (!header || header.alg !== JWT_ALGORITHM) return null; - const signingInput = `${headerB64}.${claimsB64}`; - const expectedSig = signPayload(config3.secret, signingInput); - if (!safeCompare(signature, expectedSig)) return null; - const claims = parseJson(base64UrlDecode(claimsB64)); - if (!claims) return null; - const sub = typeof claims.sub === "string" ? claims.sub : null; - const companyId = typeof claims.company_id === "string" ? claims.company_id : null; - const adapterType = typeof claims.adapter_type === "string" ? claims.adapter_type : null; - const runId = typeof claims.run_id === "string" ? claims.run_id : null; - const iat = typeof claims.iat === "number" ? claims.iat : null; - const exp = typeof claims.exp === "number" ? claims.exp : null; - if (!sub || !companyId || !adapterType || !runId || !iat || !exp) return null; - const now2 = Math.floor(Date.now() / 1e3); - if (exp < now2) return null; - const issuer = typeof claims.iss === "string" ? claims.iss : void 0; - const audience = typeof claims.aud === "string" ? claims.aud : void 0; - if (issuer && issuer !== config3.issuer) return null; - if (audience && audience !== config3.audience) return null; - return { - sub, - company_id: companyId, - adapter_type: adapterType, - run_id: runId, - iat, - exp, - ...issuer ? { iss: issuer } : {}, - ...audience ? { aud: audience } : {}, - jti: typeof claims.jti === "string" ? claims.jti : void 0 - }; -} - -// server/src/services/board-auth.ts -init_drizzle_orm(); -init_src2(); -import { createHash, randomBytes, timingSafeEqual as timingSafeEqual2 } from "node:crypto"; -var BOARD_API_KEY_TTL_MS = 30 * 24 * 60 * 60 * 1e3; -var CLI_AUTH_CHALLENGE_TTL_MS = 10 * 60 * 1e3; -function hashBearerToken(token) { - return createHash("sha256").update(token).digest("hex"); -} -function tokenHashesMatch(left, right) { - const leftBytes = Buffer.from(left, "utf8"); - const rightBytes = Buffer.from(right, "utf8"); - return leftBytes.length === rightBytes.length && timingSafeEqual2(leftBytes, rightBytes); -} -function createBoardApiToken() { - return `pcp_board_${randomBytes(24).toString("hex")}`; -} -function createCliAuthSecret() { - return `pcp_cli_auth_${randomBytes(24).toString("hex")}`; -} -function boardApiKeyExpiresAt(nowMs = Date.now()) { - return new Date(nowMs + BOARD_API_KEY_TTL_MS); -} -function cliAuthChallengeExpiresAt(nowMs = Date.now()) { - return new Date(nowMs + CLI_AUTH_CHALLENGE_TTL_MS); -} -function challengeStatusForRow(row) { - if (row.cancelledAt) return "cancelled"; - if (row.expiresAt.getTime() <= Date.now()) return "expired"; - if (row.approvedAt && row.boardApiKeyId) return "approved"; - return "pending"; -} -function boardAuthService(db) { - async function resolveBoardAccess(userId) { - const [user, memberships, adminRole] = await Promise.all([ - db.select({ - id: authUsers.id, - name: authUsers.name, - email: authUsers.email - }).from(authUsers).where(eq(authUsers.id, userId)).then((rows) => rows[0] ?? null), - db.select({ companyId: companyMemberships.companyId }).from(companyMemberships).where( - and( - eq(companyMemberships.principalType, "user"), - eq(companyMemberships.principalId, userId), - eq(companyMemberships.status, "active") - ) - ).then((rows) => rows.map((row) => row.companyId)), - db.select({ id: instanceUserRoles.id }).from(instanceUserRoles).where(and(eq(instanceUserRoles.userId, userId), eq(instanceUserRoles.role, "instance_admin"))).then((rows) => rows[0] ?? null) - ]); - return { - user, - companyIds: memberships, - isInstanceAdmin: Boolean(adminRole) - }; - } - async function resolveBoardActivityCompanyIds(input) { - const access = await resolveBoardAccess(input.userId); - const companyIds = new Set(access.companyIds); - if (companyIds.size === 0 && input.requestedCompanyId?.trim()) { - companyIds.add(input.requestedCompanyId.trim()); - } - if (companyIds.size === 0 && input.boardApiKeyId?.trim()) { - const challengeCompanyIds = await db.select({ requestedCompanyId: cliAuthChallenges.requestedCompanyId }).from(cliAuthChallenges).where(eq(cliAuthChallenges.boardApiKeyId, input.boardApiKeyId.trim())).then( - (rows) => rows.map((row) => row.requestedCompanyId?.trim() ?? null).filter((value) => Boolean(value)) - ); - for (const companyId of challengeCompanyIds) { - companyIds.add(companyId); - } - } - if (companyIds.size === 0 && access.isInstanceAdmin) { - const allCompanyIds = await db.select({ id: companies.id }).from(companies).then((rows) => rows.map((row) => row.id)); - for (const companyId of allCompanyIds) { - companyIds.add(companyId); - } - } - return Array.from(companyIds); - } - async function findBoardApiKeyByToken(token) { - const tokenHash = hashBearerToken(token); - const now2 = /* @__PURE__ */ new Date(); - return db.select().from(boardApiKeys).where( - and( - eq(boardApiKeys.keyHash, tokenHash), - isNull(boardApiKeys.revokedAt) - ) - ).then((rows) => rows.find((row) => !row.expiresAt || row.expiresAt.getTime() > now2.getTime()) ?? null); - } - async function touchBoardApiKey(id) { - await db.update(boardApiKeys).set({ lastUsedAt: /* @__PURE__ */ new Date() }).where(eq(boardApiKeys.id, id)); - } - async function revokeBoardApiKey(id) { - const now2 = /* @__PURE__ */ new Date(); - return db.update(boardApiKeys).set({ revokedAt: now2, lastUsedAt: now2 }).where(and(eq(boardApiKeys.id, id), isNull(boardApiKeys.revokedAt))).returning().then((rows) => rows[0] ?? null); - } - async function createCliAuthChallenge(input) { - const challengeSecret = createCliAuthSecret(); - const pendingBoardToken = createBoardApiToken(); - const expiresAt = cliAuthChallengeExpiresAt(); - const labelBase = input.clientName?.trim() || "taskcore cli"; - const pendingKeyName = input.requestedAccess === "instance_admin_required" ? `${labelBase} (instance admin)` : `${labelBase} (board)`; - const created = await db.insert(cliAuthChallenges).values({ - secretHash: hashBearerToken(challengeSecret), - command: input.command.trim(), - clientName: input.clientName?.trim() || null, - requestedAccess: input.requestedAccess, - requestedCompanyId: input.requestedCompanyId?.trim() || null, - pendingKeyHash: hashBearerToken(pendingBoardToken), - pendingKeyName, - expiresAt - }).returning().then((rows) => rows[0]); - return { - challenge: created, - challengeSecret, - pendingBoardToken - }; - } - async function getCliAuthChallenge(id) { - return db.select().from(cliAuthChallenges).where(eq(cliAuthChallenges.id, id)).then((rows) => rows[0] ?? null); - } - async function getCliAuthChallengeBySecret(id, token) { - const challenge = await getCliAuthChallenge(id); - if (!challenge) return null; - if (!tokenHashesMatch(challenge.secretHash, hashBearerToken(token))) return null; - return challenge; - } - async function describeCliAuthChallenge(id, token) { - const challenge = await getCliAuthChallengeBySecret(id, token); - if (!challenge) return null; - const [company, approvedBy] = await Promise.all([ - challenge.requestedCompanyId ? db.select({ id: companies.id, name: companies.name }).from(companies).where(eq(companies.id, challenge.requestedCompanyId)).then((rows) => rows[0] ?? null) : Promise.resolve(null), - challenge.approvedByUserId ? db.select({ id: authUsers.id, name: authUsers.name, email: authUsers.email }).from(authUsers).where(eq(authUsers.id, challenge.approvedByUserId)).then((rows) => rows[0] ?? null) : Promise.resolve(null) - ]); - return { - id: challenge.id, - status: challengeStatusForRow(challenge), - command: challenge.command, - clientName: challenge.clientName ?? null, - requestedAccess: challenge.requestedAccess, - requestedCompanyId: challenge.requestedCompanyId ?? null, - requestedCompanyName: company?.name ?? null, - approvedAt: challenge.approvedAt?.toISOString() ?? null, - cancelledAt: challenge.cancelledAt?.toISOString() ?? null, - expiresAt: challenge.expiresAt.toISOString(), - approvedByUser: approvedBy ? { - id: approvedBy.id, - name: approvedBy.name, - email: approvedBy.email - } : null - }; - } - async function approveCliAuthChallenge(id, token, userId) { - const access = await resolveBoardAccess(userId); - return db.transaction(async (tx) => { - await tx.execute( - sql`select ${cliAuthChallenges.id} from ${cliAuthChallenges} where ${cliAuthChallenges.id} = ${id} for update` - ); - const challenge = await tx.select().from(cliAuthChallenges).where(eq(cliAuthChallenges.id, id)).then((rows) => rows[0] ?? null); - if (!challenge || !tokenHashesMatch(challenge.secretHash, hashBearerToken(token))) { - throw notFound("CLI auth challenge not found"); - } - const status = challengeStatusForRow(challenge); - if (status === "expired") return { status, challenge }; - if (status === "cancelled") return { status, challenge }; - if (challenge.requestedAccess === "instance_admin_required" && !access.isInstanceAdmin) { - throw forbidden("Instance admin required"); - } - let boardKeyId = challenge.boardApiKeyId; - if (!boardKeyId) { - const createdKey = await tx.insert(boardApiKeys).values({ - userId, - name: challenge.pendingKeyName, - keyHash: challenge.pendingKeyHash, - expiresAt: boardApiKeyExpiresAt() - }).returning().then((rows) => rows[0]); - boardKeyId = createdKey.id; - } - const approvedAt = challenge.approvedAt ?? /* @__PURE__ */ new Date(); - const updated = await tx.update(cliAuthChallenges).set({ - approvedByUserId: userId, - boardApiKeyId: boardKeyId, - approvedAt, - updatedAt: /* @__PURE__ */ new Date() - }).where(eq(cliAuthChallenges.id, challenge.id)).returning().then((rows) => rows[0] ?? challenge); - return { status: "approved", challenge: updated }; - }); - } - async function cancelCliAuthChallenge(id, token) { - const challenge = await getCliAuthChallengeBySecret(id, token); - if (!challenge) throw notFound("CLI auth challenge not found"); - const status = challengeStatusForRow(challenge); - if (status === "approved") return { status, challenge }; - if (status === "expired") return { status, challenge }; - if (status === "cancelled") return { status, challenge }; - const updated = await db.update(cliAuthChallenges).set({ - cancelledAt: /* @__PURE__ */ new Date(), - updatedAt: /* @__PURE__ */ new Date() - }).where(eq(cliAuthChallenges.id, challenge.id)).returning().then((rows) => rows[0] ?? challenge); - return { status: "cancelled", challenge: updated }; - } - async function assertCurrentBoardKey(keyId, userId) { - if (!keyId || !userId) throw conflict("Board API key context is required"); - const key = await db.select().from(boardApiKeys).where(and(eq(boardApiKeys.id, keyId), eq(boardApiKeys.userId, userId))).then((rows) => rows[0] ?? null); - if (!key || key.revokedAt) throw notFound("Board API key not found"); - return key; - } - return { - resolveBoardAccess, - findBoardApiKeyByToken, - touchBoardApiKey, - revokeBoardApiKey, - createCliAuthChallenge, - getCliAuthChallengeBySecret, - describeCliAuthChallenge, - approveCliAuthChallenge, - cancelCliAuthChallenge, - assertCurrentBoardKey, - resolveBoardActivityCompanyIds - }; -} - -// server/src/middleware/auth.ts -function hashToken(token) { - return createHash2("sha256").update(token).digest("hex"); -} -function actorMiddleware(db, opts) { - const boardAuth = boardAuthService(db); - return async (req, _res, next) => { - req.actor = opts.deploymentMode === "local_trusted" ? { type: "board", userId: "local-board", isInstanceAdmin: true, source: "local_implicit" } : { type: "none", source: "none" }; - const runIdHeader = req.header("x-taskcore-run-id"); - const authHeader = req.header("authorization"); - if (!authHeader?.toLowerCase().startsWith("bearer ")) { - if (opts.deploymentMode === "authenticated" && opts.resolveSession) { - let session = null; - try { - session = await opts.resolveSession(req); - } catch (err) { - logger.warn( - { err, method: req.method, url: req.originalUrl }, - "Failed to resolve auth session from request headers" - ); - } - if (session?.user?.id) { - const userId = session.user.id; - const [roleRow, memberships] = await Promise.all([ - db.select({ id: instanceUserRoles.id }).from(instanceUserRoles).where(and(eq(instanceUserRoles.userId, userId), eq(instanceUserRoles.role, "instance_admin"))).then((rows) => rows[0] ?? null), - db.select({ companyId: companyMemberships.companyId }).from(companyMemberships).where( - and( - eq(companyMemberships.principalType, "user"), - eq(companyMemberships.principalId, userId), - eq(companyMemberships.status, "active") - ) - ) - ]); - req.actor = { - type: "board", - userId, - companyIds: memberships.map((row) => row.companyId), - isInstanceAdmin: Boolean(roleRow), - runId: runIdHeader ?? void 0, - source: "session" - }; - next(); - return; - } - } - if (runIdHeader) req.actor.runId = runIdHeader; - next(); - return; - } - const token = authHeader.slice("bearer ".length).trim(); - if (!token) { - next(); - return; - } - const boardKey = await boardAuth.findBoardApiKeyByToken(token); - if (boardKey) { - const access = await boardAuth.resolveBoardAccess(boardKey.userId); - if (access.user) { - await boardAuth.touchBoardApiKey(boardKey.id); - req.actor = { - type: "board", - userId: boardKey.userId, - companyIds: access.companyIds, - isInstanceAdmin: access.isInstanceAdmin, - keyId: boardKey.id, - runId: runIdHeader || void 0, - source: "board_key" - }; - next(); - return; - } - } - const tokenHash = hashToken(token); - const key = await db.select().from(agentApiKeys).where(and(eq(agentApiKeys.keyHash, tokenHash), isNull(agentApiKeys.revokedAt))).then((rows) => rows[0] ?? null); - if (!key) { - const claims = verifyLocalAgentJwt(token); - if (!claims) { - next(); - return; - } - const agentRecord2 = await db.select().from(agents).where(eq(agents.id, claims.sub)).then((rows) => rows[0] ?? null); - if (!agentRecord2 || agentRecord2.companyId !== claims.company_id) { - next(); - return; - } - if (agentRecord2.status === "terminated" || agentRecord2.status === "pending_approval") { - next(); - return; - } - req.actor = { - type: "agent", - agentId: claims.sub, - companyId: claims.company_id, - keyId: void 0, - runId: runIdHeader || claims.run_id || void 0, - source: "agent_jwt" - }; - next(); - return; - } - await db.update(agentApiKeys).set({ lastUsedAt: /* @__PURE__ */ new Date() }).where(eq(agentApiKeys.id, key.id)); - const agentRecord = await db.select().from(agents).where(eq(agents.id, key.agentId)).then((rows) => rows[0] ?? null); - if (!agentRecord || agentRecord.status === "terminated" || agentRecord.status === "pending_approval") { - next(); - return; - } - req.actor = { - type: "agent", - agentId: key.agentId, - companyId: key.companyId, - keyId: key.id, - runId: runIdHeader || void 0, - source: "agent_key" - }; - next(); - }; -} - -// server/src/middleware/board-mutation-guard.ts -var SAFE_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD", "OPTIONS"]); -var DEFAULT_DEV_ORIGINS = [ - "http://localhost:3100", - "http://127.0.0.1:3100" -]; -function parseOrigin(value) { - if (!value) return null; - try { - const url2 = new URL(value); - return `${url2.protocol}//${url2.host}`.toLowerCase(); - } catch { - return null; - } -} -function trustedOriginsForRequest(req) { - const origins = new Set(DEFAULT_DEV_ORIGINS.map((value) => value.toLowerCase())); - const forwardedHost = req.header("x-forwarded-host")?.split(",")[0]?.trim(); - const host = forwardedHost || req.header("host")?.trim(); - if (host) { - origins.add(`http://${host}`.toLowerCase()); - origins.add(`https://${host}`.toLowerCase()); - } - return origins; -} -function isTrustedBoardMutationRequest(req) { - const allowedOrigins = trustedOriginsForRequest(req); - const origin = parseOrigin(req.header("origin")); - if (origin && allowedOrigins.has(origin)) return true; - const refererOrigin = parseOrigin(req.header("referer")); - if (refererOrigin && allowedOrigins.has(refererOrigin)) return true; - return false; -} -function boardMutationGuard() { - return (req, res, next) => { - if (SAFE_METHODS.has(req.method.toUpperCase())) { - next(); - return; - } - if (req.actor.type !== "board") { - next(); - return; - } - if (req.actor.source === "local_implicit" || req.actor.source === "board_key") { - next(); - return; - } - if (!isTrustedBoardMutationRequest(req)) { - res.status(403).json({ error: "Board mutation requires trusted browser origin" }); - return; - } - next(); - }; -} - -// server/src/middleware/private-hostname-guard.ts -function isLoopbackHostname(hostname3) { - const normalized = hostname3.trim().toLowerCase(); - return normalized === "localhost" || normalized === "127.0.0.1" || normalized === "::1"; -} -function extractHostname(req) { - const forwardedHost = req.header("x-forwarded-host")?.split(",")[0]?.trim(); - const hostHeader = req.header("host")?.trim(); - const raw = forwardedHost || hostHeader; - if (!raw) return null; - try { - return new URL(`http://${raw}`).hostname.trim().toLowerCase(); - } catch { - return raw.trim().toLowerCase(); - } -} -function normalizeAllowedHostnames(values2) { - const unique2 = /* @__PURE__ */ new Set(); - for (const value of values2) { - const trimmed = value.trim().toLowerCase(); - if (!trimmed) continue; - unique2.add(trimmed); - } - return Array.from(unique2); -} -function resolvePrivateHostnameAllowSet(opts) { - const configuredAllow = normalizeAllowedHostnames(opts.allowedHostnames); - const bindHost = opts.bindHost.trim().toLowerCase(); - const allowSet = new Set(configuredAllow); - if (bindHost && bindHost !== "0.0.0.0") { - allowSet.add(bindHost); - } - allowSet.add("localhost"); - allowSet.add("127.0.0.1"); - allowSet.add("::1"); - return allowSet; -} -function blockedHostnameMessage(hostname3) { - return `Hostname '${hostname3}' is not allowed for this Taskcore instance. If you want to allow this hostname, please run pnpm taskcore allowed-hostname ${hostname3}`; -} -function privateHostnameGuard(opts) { - if (!opts.enabled) { - return (_req, _res, next) => next(); - } - const allowSet = resolvePrivateHostnameAllowSet({ - allowedHostnames: opts.allowedHostnames, - bindHost: opts.bindHost - }); - return (req, res, next) => { - const hostname3 = extractHostname(req); - const wantsJson = req.path.startsWith("/api") || req.accepts(["json", "html", "text"]) === "json"; - if (!hostname3) { - const error51 = "Missing Host header. If you want to allow a hostname, run pnpm taskcore allowed-hostname ."; - if (wantsJson) { - res.status(403).json({ error: error51 }); - } else { - res.status(403).type("text/plain").send(error51); - } - return; - } - if (isLoopbackHostname(hostname3) || allowSet.has(hostname3)) { - next(); - return; - } - const error50 = blockedHostnameMessage(hostname3); - if (wantsJson) { - res.status(403).json({ error: error50 }); - } else { - res.status(403).type("text/plain").send(error50); - } - }; -} - -// server/src/routes/health.ts -var import_express = __toESM(require_express2(), 1); -init_drizzle_orm(); -init_src2(); - -// server/src/dev-server-status.ts -import { existsSync, readFileSync, statSync } from "node:fs"; -var MAX_PERSISTED_DEV_SERVER_STATUS_BYTES = 64 * 1024; -function normalizeStringArray(value) { - if (!Array.isArray(value)) return []; - return value.filter((entry) => typeof entry === "string").map((entry) => entry.trim()).filter((entry) => entry.length > 0); -} -function normalizeTimestamp(value) { - if (typeof value !== "string") return null; - const trimmed = value.trim(); - return trimmed.length > 0 ? trimmed : null; -} -function readPersistedDevServerStatus(env2 = process.env) { - const filePath = env2.TASKCORE_DEV_SERVER_STATUS_FILE?.trim(); - if (!filePath || !existsSync(filePath)) return null; - try { - if (statSync(filePath).size > MAX_PERSISTED_DEV_SERVER_STATUS_BYTES) { - return null; - } - const raw = JSON.parse(readFileSync(filePath, "utf8")); - const changedPathsSample = normalizeStringArray(raw.changedPathsSample).slice(0, 5); - const pendingMigrations = normalizeStringArray(raw.pendingMigrations); - const changedPathCountRaw = raw.changedPathCount; - const changedPathCount = typeof changedPathCountRaw === "number" && Number.isFinite(changedPathCountRaw) ? Math.max(0, Math.trunc(changedPathCountRaw)) : changedPathsSample.length; - const dirtyRaw = raw.dirty; - const dirty = typeof dirtyRaw === "boolean" ? dirtyRaw : changedPathCount > 0 || pendingMigrations.length > 0; - return { - dirty, - lastChangedAt: normalizeTimestamp(raw.lastChangedAt), - changedPathCount, - changedPathsSample, - pendingMigrations, - lastRestartAt: normalizeTimestamp(raw.lastRestartAt) - }; - } catch { - return null; - } -} -function toDevServerHealthStatus(persisted, opts) { - const hasPathChanges = persisted.changedPathCount > 0; - const hasPendingMigrations = persisted.pendingMigrations.length > 0; - const reason = hasPathChanges && hasPendingMigrations ? "backend_changes_and_pending_migrations" : hasPendingMigrations ? "pending_migrations" : hasPathChanges ? "backend_changes" : null; - const restartRequired = persisted.dirty || reason !== null; - return { - enabled: true, - restartRequired, - reason, - lastChangedAt: persisted.lastChangedAt, - changedPathCount: persisted.changedPathCount, - changedPathsSample: persisted.changedPathsSample, - pendingMigrations: persisted.pendingMigrations, - autoRestartEnabled: opts.autoRestartEnabled, - activeRunCount: opts.activeRunCount, - waitingForIdle: restartRequired && opts.autoRestartEnabled && opts.activeRunCount > 0, - lastRestartAt: persisted.lastRestartAt - }; -} - -// server/src/services/instance-settings.ts -init_src2(); -init_drizzle_orm(); -var DEFAULT_SINGLETON_KEY = "default"; -function normalizeGeneralSettings(raw) { - const parsed = instanceGeneralSettingsSchema.safeParse(raw ?? {}); - if (parsed.success) { - return { - censorUsernameInLogs: parsed.data.censorUsernameInLogs ?? false, - keyboardShortcuts: parsed.data.keyboardShortcuts ?? false, - feedbackDataSharingPreference: parsed.data.feedbackDataSharingPreference ?? DEFAULT_FEEDBACK_DATA_SHARING_PREFERENCE, - backupRetention: parsed.data.backupRetention ?? DEFAULT_BACKUP_RETENTION - }; - } - return { - censorUsernameInLogs: false, - keyboardShortcuts: false, - feedbackDataSharingPreference: DEFAULT_FEEDBACK_DATA_SHARING_PREFERENCE, - backupRetention: DEFAULT_BACKUP_RETENTION - }; -} -function normalizeExperimentalSettings(raw) { - const parsed = instanceExperimentalSettingsSchema.safeParse(raw ?? {}); - if (parsed.success) { - return { - enableIsolatedWorkspaces: parsed.data.enableIsolatedWorkspaces ?? false, - autoRestartDevServerWhenIdle: parsed.data.autoRestartDevServerWhenIdle ?? false - }; - } - return { - enableIsolatedWorkspaces: false, - autoRestartDevServerWhenIdle: false - }; -} -function toInstanceSettings(row) { - return { - id: row.id, - general: normalizeGeneralSettings(row.general), - experimental: normalizeExperimentalSettings(row.experimental), - createdAt: row.createdAt, - updatedAt: row.updatedAt - }; -} -function instanceSettingsService(db) { - async function getOrCreateRow() { - const existing = await db.select().from(instanceSettings).where(eq(instanceSettings.singletonKey, DEFAULT_SINGLETON_KEY)).then((rows) => rows[0] ?? null); - if (existing) return existing; - const now2 = /* @__PURE__ */ new Date(); - const [created] = await db.insert(instanceSettings).values({ - singletonKey: DEFAULT_SINGLETON_KEY, - general: {}, - experimental: {}, - createdAt: now2, - updatedAt: now2 - }).onConflictDoUpdate({ - target: [instanceSettings.singletonKey], - set: { - updatedAt: now2 - } - }).returning(); - return created; - } - return { - get: async () => toInstanceSettings(await getOrCreateRow()), - getGeneral: async () => { - const row = await getOrCreateRow(); - return normalizeGeneralSettings(row.general); - }, - getExperimental: async () => { - const row = await getOrCreateRow(); - return normalizeExperimentalSettings(row.experimental); - }, - updateGeneral: async (patch) => { - const current = await getOrCreateRow(); - const nextGeneral = normalizeGeneralSettings({ - ...normalizeGeneralSettings(current.general), - ...patch - }); - const now2 = /* @__PURE__ */ new Date(); - const [updated] = await db.update(instanceSettings).set({ - general: { ...nextGeneral }, - updatedAt: now2 - }).where(eq(instanceSettings.id, current.id)).returning(); - return toInstanceSettings(updated ?? current); - }, - updateExperimental: async (patch) => { - const current = await getOrCreateRow(); - const nextExperimental = normalizeExperimentalSettings({ - ...normalizeExperimentalSettings(current.experimental), - ...patch - }); - const now2 = /* @__PURE__ */ new Date(); - const [updated] = await db.update(instanceSettings).set({ - experimental: { ...nextExperimental }, - updatedAt: now2 - }).where(eq(instanceSettings.id, current.id)).returning(); - return toInstanceSettings(updated ?? current); - }, - listCompanyIds: async () => db.select({ id: companies.id }).from(companies).then((rows) => rows.map((row) => row.id)) - }; -} - -// server/src/routes/health.ts -function healthRoutes(db, opts = { - deploymentMode: "local_trusted", - deploymentExposure: "private", - authReady: true, - companyDeletionEnabled: true -}) { - const router2 = (0, import_express.Router)(); - router2.get("/", async (_req, res) => { - if (!db) { - res.json({ status: "ok", version: serverVersion }); - return; - } - try { - await db.execute(sql`SELECT 1`); - } catch { - res.status(503).json({ - status: "unhealthy", - version: serverVersion, - error: "database_unreachable" - }); - return; - } - let bootstrapStatus = "ready"; - let bootstrapInviteActive = false; - if (opts.deploymentMode === "authenticated") { - const roleCount = await db.select({ count: count() }).from(instanceUserRoles).where(sql`${instanceUserRoles.role} = 'instance_admin'`).then((rows) => Number(rows[0]?.count ?? 0)); - bootstrapStatus = roleCount > 0 ? "ready" : "bootstrap_pending"; - if (bootstrapStatus === "bootstrap_pending") { - const now2 = /* @__PURE__ */ new Date(); - const inviteCount = await db.select({ count: count() }).from(invites).where( - and( - eq(invites.inviteType, "bootstrap_ceo"), - isNull(invites.revokedAt), - isNull(invites.acceptedAt), - gt(invites.expiresAt, now2) - ) - ).then((rows) => Number(rows[0]?.count ?? 0)); - bootstrapInviteActive = inviteCount > 0; - } - } - const persistedDevServerStatus = readPersistedDevServerStatus(); - let devServer; - if (persistedDevServerStatus) { - const instanceSettings2 = instanceSettingsService(db); - const experimentalSettings = await instanceSettings2.getExperimental(); - const activeRunCount = await db.select({ count: count() }).from(heartbeatRuns).where(inArray(heartbeatRuns.status, ["queued", "running"])).then((rows) => Number(rows[0]?.count ?? 0)); - devServer = toDevServerHealthStatus(persistedDevServerStatus, { - autoRestartEnabled: experimentalSettings.autoRestartDevServerWhenIdle ?? false, - activeRunCount - }); - } - res.json({ - status: "ok", - version: serverVersion, - deploymentMode: opts.deploymentMode, - deploymentExposure: opts.deploymentExposure, - authReady: opts.authReady, - bootstrapStatus, - bootstrapInviteActive, - features: { - companyDeletionEnabled: opts.companyDeletionEnabled - }, - ...devServer ? { devServer } : {} - }); - }); - return router2; -} - -// server/src/routes/companies.ts -var import_express2 = __toESM(require_express2(), 1); - -// server/src/services/companies.ts -init_drizzle_orm(); -init_src2(); -function companyService(db) { - const ISSUE_PREFIX_FALLBACK = "CMP"; - const companySelection = { - id: companies.id, - name: companies.name, - description: companies.description, - status: companies.status, - issuePrefix: companies.issuePrefix, - issueCounter: companies.issueCounter, - budgetMonthlyCents: companies.budgetMonthlyCents, - spentMonthlyCents: companies.spentMonthlyCents, - requireBoardApprovalForNewAgents: companies.requireBoardApprovalForNewAgents, - feedbackDataSharingEnabled: companies.feedbackDataSharingEnabled, - feedbackDataSharingConsentAt: companies.feedbackDataSharingConsentAt, - feedbackDataSharingConsentByUserId: companies.feedbackDataSharingConsentByUserId, - feedbackDataSharingTermsVersion: companies.feedbackDataSharingTermsVersion, - brandColor: companies.brandColor, - logoAssetId: companyLogos.assetId, - createdAt: companies.createdAt, - updatedAt: companies.updatedAt - }; - function enrichCompany(company) { - return { - ...company, - logoUrl: company.logoAssetId ? `/api/assets/${company.logoAssetId}/content` : null - }; - } - function currentUtcMonthWindow3(now2 = /* @__PURE__ */ new Date()) { - const year3 = now2.getUTCFullYear(); - const month = now2.getUTCMonth(); - return { - start: new Date(Date.UTC(year3, month, 1, 0, 0, 0, 0)), - end: new Date(Date.UTC(year3, month + 1, 1, 0, 0, 0, 0)) - }; - } - async function getMonthlySpendByCompanyIds(companyIds, database = db) { - if (companyIds.length === 0) return /* @__PURE__ */ new Map(); - const { start, end } = currentUtcMonthWindow3(); - const rows = await database.select({ - companyId: costEvents.companyId, - spentMonthlyCents: sql`coalesce(sum(${costEvents.costCents}), 0)::int` - }).from(costEvents).where( - and( - inArray(costEvents.companyId, companyIds), - gte(costEvents.occurredAt, start), - lt(costEvents.occurredAt, end) - ) - ).groupBy(costEvents.companyId); - return new Map(rows.map((row) => [row.companyId, Number(row.spentMonthlyCents ?? 0)])); - } - async function hydrateCompanySpend(rows, database = db) { - const spendByCompanyId = await getMonthlySpendByCompanyIds(rows.map((row) => row.id), database); - return rows.map((row) => ({ - ...row, - spentMonthlyCents: spendByCompanyId.get(row.id) ?? 0 - })); - } - function getCompanyQuery(database) { - return database.select(companySelection).from(companies).leftJoin(companyLogos, eq(companyLogos.companyId, companies.id)); - } - function deriveIssuePrefixBase(name) { - const normalized = name.toUpperCase().replace(/[^A-Z]/g, ""); - return normalized.slice(0, 3) || ISSUE_PREFIX_FALLBACK; - } - function suffixForAttempt(attempt) { - if (attempt <= 1) return ""; - return "A".repeat(attempt - 1); - } - function isIssuePrefixConflict(error50) { - const constraint = typeof error50 === "object" && error50 !== null && "constraint" in error50 ? error50.constraint : typeof error50 === "object" && error50 !== null && "constraint_name" in error50 ? error50.constraint_name : void 0; - return typeof error50 === "object" && error50 !== null && "code" in error50 && error50.code === "23505" && constraint === "companies_issue_prefix_idx"; - } - async function createCompanyWithUniquePrefix(data2) { - const base = deriveIssuePrefixBase(data2.name); - let suffix = 1; - while (suffix < 1e4) { - const candidate = `${base}${suffixForAttempt(suffix)}`; - try { - const rows = await db.insert(companies).values({ ...data2, issuePrefix: candidate }).returning(); - return rows[0]; - } catch (error50) { - if (!isIssuePrefixConflict(error50)) throw error50; - } - suffix += 1; - } - throw new Error("Unable to allocate unique issue prefix"); - } - return { - list: async () => { - const rows = await getCompanyQuery(db); - const hydrated = await hydrateCompanySpend(rows); - return hydrated.map((row) => enrichCompany(row)); - }, - getById: async (id) => { - const row = await getCompanyQuery(db).where(eq(companies.id, id)).then((rows) => rows[0] ?? null); - if (!row) return null; - const [hydrated] = await hydrateCompanySpend([row], db); - return enrichCompany(hydrated); - }, - create: async (data2) => { - const created = await createCompanyWithUniquePrefix(data2); - const row = await getCompanyQuery(db).where(eq(companies.id, created.id)).then((rows) => rows[0] ?? null); - if (!row) throw notFound("Company not found after creation"); - const [hydrated] = await hydrateCompanySpend([row], db); - return enrichCompany(hydrated); - }, - update: (id, data2) => db.transaction(async (tx) => { - const existing = await getCompanyQuery(tx).where(eq(companies.id, id)).then((rows) => rows[0] ?? null); - if (!existing) return null; - const { logoAssetId, ...companyPatch } = data2; - if (logoAssetId !== void 0 && logoAssetId !== null) { - const nextLogoAsset = await tx.select({ id: assets.id, companyId: assets.companyId }).from(assets).where(eq(assets.id, logoAssetId)).then((rows) => rows[0] ?? null); - if (!nextLogoAsset) throw notFound("Logo asset not found"); - if (nextLogoAsset.companyId !== existing.id) { - throw unprocessable("Logo asset must belong to the same company"); - } - } - const updated = await tx.update(companies).set({ ...companyPatch, updatedAt: /* @__PURE__ */ new Date() }).where(eq(companies.id, id)).returning().then((rows) => rows[0] ?? null); - if (!updated) return null; - if (logoAssetId === null) { - await tx.delete(companyLogos).where(eq(companyLogos.companyId, id)); - } else if (logoAssetId !== void 0) { - await tx.insert(companyLogos).values({ - companyId: id, - assetId: logoAssetId - }).onConflictDoUpdate({ - target: companyLogos.companyId, - set: { - assetId: logoAssetId, - updatedAt: /* @__PURE__ */ new Date() - } - }); - } - if (logoAssetId !== void 0 && existing.logoAssetId && existing.logoAssetId !== logoAssetId) { - await tx.delete(assets).where(eq(assets.id, existing.logoAssetId)); - } - const [hydrated] = await hydrateCompanySpend([{ - ...updated, - logoAssetId: logoAssetId === void 0 ? existing.logoAssetId : logoAssetId - }], tx); - return enrichCompany(hydrated); - }), - archive: (id) => db.transaction(async (tx) => { - const updated = await tx.update(companies).set({ status: "archived", updatedAt: /* @__PURE__ */ new Date() }).where(eq(companies.id, id)).returning().then((rows) => rows[0] ?? null); - if (!updated) return null; - const row = await getCompanyQuery(tx).where(eq(companies.id, id)).then((rows) => rows[0] ?? null); - if (!row) return null; - const [hydrated] = await hydrateCompanySpend([row], tx); - return enrichCompany(hydrated); - }), - remove: (id) => db.transaction(async (tx) => { - await tx.delete(heartbeatRunEvents).where(eq(heartbeatRunEvents.companyId, id)); - await tx.delete(agentTaskSessions).where(eq(agentTaskSessions.companyId, id)); - await tx.delete(activityLog).where(eq(activityLog.companyId, id)); - await tx.delete(heartbeatRuns).where(eq(heartbeatRuns.companyId, id)); - await tx.delete(agentWakeupRequests).where(eq(agentWakeupRequests.companyId, id)); - await tx.delete(agentApiKeys).where(eq(agentApiKeys.companyId, id)); - await tx.delete(agentRuntimeState).where(eq(agentRuntimeState.companyId, id)); - await tx.delete(issueComments).where(eq(issueComments.companyId, id)); - await tx.delete(costEvents).where(eq(costEvents.companyId, id)); - await tx.delete(financeEvents).where(eq(financeEvents.companyId, id)); - await tx.delete(approvalComments).where(eq(approvalComments.companyId, id)); - await tx.delete(approvals).where(eq(approvals.companyId, id)); - await tx.delete(companySecrets).where(eq(companySecrets.companyId, id)); - await tx.delete(joinRequests).where(eq(joinRequests.companyId, id)); - await tx.delete(invites).where(eq(invites.companyId, id)); - await tx.delete(principalPermissionGrants).where(eq(principalPermissionGrants.companyId, id)); - await tx.delete(companyMemberships).where(eq(companyMemberships.companyId, id)); - await tx.delete(companySkills).where(eq(companySkills.companyId, id)); - await tx.delete(issueReadStates).where(eq(issueReadStates.companyId, id)); - await tx.delete(issues).where(eq(issues.companyId, id)); - await tx.delete(companyLogos).where(eq(companyLogos.companyId, id)); - await tx.delete(assets).where(eq(assets.companyId, id)); - await tx.delete(goals).where(eq(goals.companyId, id)); - await tx.delete(projects).where(eq(projects.companyId, id)); - await tx.delete(agents).where(eq(agents.companyId, id)); - const rows = await tx.delete(companies).where(eq(companies.id, id)).returning(); - return rows[0] ?? null; - }), - stats: () => Promise.all([ - db.select({ companyId: agents.companyId, count: count() }).from(agents).groupBy(agents.companyId), - db.select({ companyId: issues.companyId, count: count() }).from(issues).groupBy(issues.companyId) - ]).then(([agentRows, issueRows]) => { - const result = {}; - for (const row of agentRows) { - result[row.companyId] = { agentCount: row.count, issueCount: 0 }; - } - for (const row of issueRows) { - if (result[row.companyId]) { - result[row.companyId].issueCount = row.count; - } else { - result[row.companyId] = { agentCount: 0, issueCount: row.count }; - } - } - return result; - }) - }; -} - -// server/src/services/feedback.ts -init_drizzle_orm(); -init_src2(); -import { readFile, readdir } from "node:fs/promises"; -import path20 from "node:path"; - -// packages/adapter-utils/src/server-utils.ts -import { spawn } from "node:child_process"; -import { constants as fsConstants, promises as fs4 } from "node:fs"; -import path4 from "node:path"; -function resolveProcessGroupId(child) { - if (process.platform === "win32") return null; - return typeof child.pid === "number" && child.pid > 0 ? child.pid : null; -} -function signalRunningProcess(running, signal) { - if (process.platform !== "win32" && running.processGroupId && running.processGroupId > 0) { - try { - process.kill(-running.processGroupId, signal); - return; - } catch { - } - } - if (!running.child.killed) { - running.child.kill(signal); - } -} -var runningProcesses = /* @__PURE__ */ new Map(); -var MAX_CAPTURE_BYTES = 4 * 1024 * 1024; -var MAX_EXCERPT_BYTES = 32 * 1024; -var SENSITIVE_ENV_KEY = /(key|token|secret|password|passwd|authorization|cookie)/i; -var TASKCORE_SKILL_ROOT_RELATIVE_CANDIDATES = [ - "../../skills", - "../../../../../skills" -]; -function normalizePathSlashes(value) { - return value.replaceAll("\\", "/"); -} -function isMaintainerOnlySkillTarget(candidate) { - return normalizePathSlashes(candidate).includes("/.agents/skills/"); -} -function skillLocationLabel(value) { - if (typeof value !== "string") return null; - const trimmed = value.trim(); - return trimmed.length > 0 ? trimmed : null; -} -function buildManagedSkillOrigin(entry) { - if (entry.required) { - return { - origin: "taskcore_required", - originLabel: "Required by Taskcore", - readOnly: false - }; - } - return { - origin: "company_managed", - originLabel: "Managed by Taskcore", - readOnly: false - }; -} -function resolveInstalledEntryTarget(skillsHome, entryName, dirent, linkedPath) { - const fullPath = path4.join(skillsHome, entryName); - if (dirent.isSymbolicLink()) { - return { - targetPath: linkedPath ? path4.resolve(path4.dirname(fullPath), linkedPath) : null, - kind: "symlink" - }; - } - if (dirent.isDirectory()) { - return { targetPath: fullPath, kind: "directory" }; - } - return { targetPath: fullPath, kind: "file" }; -} -function parseObject(value) { - if (typeof value !== "object" || value === null || Array.isArray(value)) { - return {}; - } - return value; -} -function asString(value, fallback) { - return typeof value === "string" && value.length > 0 ? value : fallback; -} -function asNumber(value, fallback) { - return typeof value === "number" && Number.isFinite(value) ? value : fallback; -} -function asBoolean(value, fallback) { - return typeof value === "boolean" ? value : fallback; -} -function asStringArray(value) { - return Array.isArray(value) ? value.filter((item) => typeof item === "string") : []; -} -function parseJson2(value) { - try { - return JSON.parse(value); - } catch { - return null; - } -} -function appendWithCap(prev, chunk, cap = MAX_CAPTURE_BYTES) { - const combined = prev + chunk; - return combined.length > cap ? combined.slice(combined.length - cap) : combined; -} -function resolvePathValue(obj, dottedPath) { - const parts = dottedPath.split("."); - let cursor2 = obj; - for (const part of parts) { - if (typeof cursor2 !== "object" || cursor2 === null || Array.isArray(cursor2)) { - return ""; - } - cursor2 = cursor2[part]; - } - if (cursor2 === null || cursor2 === void 0) return ""; - if (typeof cursor2 === "string") return cursor2; - if (typeof cursor2 === "number" || typeof cursor2 === "boolean") return String(cursor2); - try { - return JSON.stringify(cursor2); - } catch { - return ""; - } -} -function renderTemplate(template, data2) { - return template.replace(/{{\s*([a-zA-Z0-9_.-]+)\s*}}/g, (_, path53) => resolvePathValue(data2, path53)); -} -function joinPromptSections(sections, separator = "\n\n") { - return sections.map((value) => typeof value === "string" ? value.trim() : "").filter(Boolean).join(separator); -} -function normalizeTaskcoreWakeIssue(value) { - const issue2 = parseObject(value); - const id = asString(issue2.id, "").trim() || null; - const identifier = asString(issue2.identifier, "").trim() || null; - const title = asString(issue2.title, "").trim() || null; - const status = asString(issue2.status, "").trim() || null; - const priority = asString(issue2.priority, "").trim() || null; - if (!id && !identifier && !title) return null; - return { - id, - identifier, - title, - status, - priority - }; -} -function normalizeTaskcoreWakeComment(value) { - const comment = parseObject(value); - const author = parseObject(comment.author); - const body = asString(comment.body, ""); - if (!body.trim()) return null; - return { - id: asString(comment.id, "").trim() || null, - issueId: asString(comment.issueId, "").trim() || null, - body, - bodyTruncated: asBoolean(comment.bodyTruncated, false), - createdAt: asString(comment.createdAt, "").trim() || null, - authorType: asString(author.type, "").trim() || null, - authorId: asString(author.id, "").trim() || null - }; -} -function normalizeTaskcoreWakeExecutionPrincipal(value) { - const principal = parseObject(value); - const typeRaw = asString(principal.type, "").trim().toLowerCase(); - if (typeRaw !== "agent" && typeRaw !== "user") return null; - return { - type: typeRaw, - agentId: asString(principal.agentId, "").trim() || null, - userId: asString(principal.userId, "").trim() || null - }; -} -function normalizeTaskcoreWakeExecutionStage(value) { - const stage = parseObject(value); - const wakeRoleRaw = asString(stage.wakeRole, "").trim().toLowerCase(); - const wakeRole = wakeRoleRaw === "reviewer" || wakeRoleRaw === "approver" || wakeRoleRaw === "executor" ? wakeRoleRaw : null; - const allowedActions = Array.isArray(stage.allowedActions) ? stage.allowedActions.filter((entry) => typeof entry === "string" && entry.trim().length > 0).map((entry) => entry.trim()) : []; - const currentParticipant = normalizeTaskcoreWakeExecutionPrincipal(stage.currentParticipant); - const returnAssignee = normalizeTaskcoreWakeExecutionPrincipal(stage.returnAssignee); - const stageId = asString(stage.stageId, "").trim() || null; - const stageType = asString(stage.stageType, "").trim() || null; - const lastDecisionOutcome = asString(stage.lastDecisionOutcome, "").trim() || null; - if (!wakeRole && !stageId && !stageType && !currentParticipant && !returnAssignee && !lastDecisionOutcome && allowedActions.length === 0) { - return null; - } - return { - wakeRole, - stageId, - stageType, - currentParticipant, - returnAssignee, - lastDecisionOutcome, - allowedActions - }; -} -function normalizeTaskcoreWakePayload(value) { - const payload2 = parseObject(value); - const comments = Array.isArray(payload2.comments) ? payload2.comments.map((entry) => normalizeTaskcoreWakeComment(entry)).filter((entry) => Boolean(entry)) : []; - const commentWindow = parseObject(payload2.commentWindow); - const commentIds = Array.isArray(payload2.commentIds) ? payload2.commentIds.filter((entry) => typeof entry === "string" && entry.trim().length > 0).map((entry) => entry.trim()) : []; - const executionStage = normalizeTaskcoreWakeExecutionStage(payload2.executionStage); - if (comments.length === 0 && commentIds.length === 0 && !executionStage && !normalizeTaskcoreWakeIssue(payload2.issue)) { - return null; - } - return { - reason: asString(payload2.reason, "").trim() || null, - issue: normalizeTaskcoreWakeIssue(payload2.issue), - checkedOutByHarness: asBoolean(payload2.checkedOutByHarness, false), - executionStage, - commentIds, - latestCommentId: asString(payload2.latestCommentId, "").trim() || null, - comments, - requestedCount: asNumber(commentWindow.requestedCount, comments.length || commentIds.length), - includedCount: asNumber(commentWindow.includedCount, comments.length), - missingCount: asNumber(commentWindow.missingCount, 0), - truncated: asBoolean(payload2.truncated, false), - fallbackFetchNeeded: asBoolean(payload2.fallbackFetchNeeded, false) - }; -} -function stringifyTaskcoreWakePayload(value) { - const normalized = normalizeTaskcoreWakePayload(value); - if (!normalized) return null; - return JSON.stringify(normalized); -} -function renderTaskcoreWakePrompt(value, options = {}) { - const normalized = normalizeTaskcoreWakePayload(value); - if (!normalized) return ""; - const resumedSession = options.resumedSession === true; - const executionStage = normalized.executionStage; - const principalLabel = (principal) => { - if (!principal || !principal.type) return "unknown"; - if (principal.type === "agent") return principal.agentId ? `agent ${principal.agentId}` : "agent"; - return principal.userId ? `user ${principal.userId}` : "user"; - }; - const lines = resumedSession ? [ - "## Taskcore Resume Delta", - "", - "You are resuming an existing Taskcore session.", - "This heartbeat is scoped to the issue below. Do not switch to another issue until you have handled this wake.", - "Focus on the new wake delta below and continue the current task without restating the full heartbeat boilerplate.", - "Fetch the API thread only when `fallbackFetchNeeded` is true or you need broader history than this batch.", - "", - `- reason: ${normalized.reason ?? "unknown"}`, - `- issue: ${normalized.issue?.identifier ?? normalized.issue?.id ?? "unknown"}${normalized.issue?.title ? ` ${normalized.issue.title}` : ""}`, - `- pending comments: ${normalized.includedCount}/${normalized.requestedCount}`, - `- latest comment id: ${normalized.latestCommentId ?? "unknown"}`, - `- fallback fetch needed: ${normalized.fallbackFetchNeeded ? "yes" : "no"}` - ] : [ - "## Taskcore Wake Payload", - "", - "Treat this wake payload as the highest-priority change for the current heartbeat.", - "This heartbeat is scoped to the issue below. Do not switch to another issue until you have handled this wake.", - "Before generic repo exploration or boilerplate heartbeat updates, acknowledge the latest comment and explain how it changes your next action.", - "Use this inline wake data first before refetching the issue thread.", - "Only fetch the API thread when `fallbackFetchNeeded` is true or you need broader history than this batch.", - "", - `- reason: ${normalized.reason ?? "unknown"}`, - `- issue: ${normalized.issue?.identifier ?? normalized.issue?.id ?? "unknown"}${normalized.issue?.title ? ` ${normalized.issue.title}` : ""}`, - `- pending comments: ${normalized.includedCount}/${normalized.requestedCount}`, - `- latest comment id: ${normalized.latestCommentId ?? "unknown"}`, - `- fallback fetch needed: ${normalized.fallbackFetchNeeded ? "yes" : "no"}` - ]; - if (normalized.issue?.status) { - lines.push(`- issue status: ${normalized.issue.status}`); - } - if (normalized.issue?.priority) { - lines.push(`- issue priority: ${normalized.issue.priority}`); - } - if (normalized.checkedOutByHarness) { - lines.push("- checkout: already claimed by the harness for this run"); - } - if (normalized.missingCount > 0) { - lines.push(`- omitted comments: ${normalized.missingCount}`); - } - if (executionStage) { - lines.push( - `- execution wake role: ${executionStage.wakeRole ?? "unknown"}`, - `- execution stage: ${executionStage.stageType ?? "unknown"}`, - `- execution participant: ${principalLabel(executionStage.currentParticipant)}`, - `- execution return assignee: ${principalLabel(executionStage.returnAssignee)}`, - `- last decision outcome: ${executionStage.lastDecisionOutcome ?? "none"}` - ); - if (executionStage.allowedActions.length > 0) { - lines.push(`- allowed actions: ${executionStage.allowedActions.join(", ")}`); - } - lines.push(""); - if (executionStage.wakeRole === "reviewer" || executionStage.wakeRole === "approver") { - lines.push( - `You are waking as the active ${executionStage.wakeRole} for this issue.`, - "Do not execute the task itself or continue executor work.", - "Review the issue and choose one of the allowed actions above.", - "If you request changes, the workflow routes back to the stored return assignee.", - "" - ); - } else if (executionStage.wakeRole === "executor") { - lines.push( - "You are waking because changes were requested in the execution workflow.", - "Address the requested changes on this issue and resubmit when the work is ready.", - "" - ); - } - } - if (normalized.checkedOutByHarness) { - lines.push( - "", - "The harness already checked out this issue for the current run.", - "Do not call `/api/issues/{id}/checkout` again unless you intentionally switch to a different task.", - "" - ); - } - if (normalized.comments.length > 0) { - lines.push("New comments in order:"); - } - for (const [index2, comment] of normalized.comments.entries()) { - const authorLabel = comment.authorId ? `${comment.authorType ?? "unknown"} ${comment.authorId}` : comment.authorType ?? "unknown"; - lines.push( - `${index2 + 1}. comment ${comment.id ?? "unknown"} at ${comment.createdAt ?? "unknown"} by ${authorLabel}`, - comment.body - ); - if (comment.bodyTruncated) { - lines.push("[comment body truncated]"); - } - lines.push(""); - } - return lines.join("\n").trim(); -} -function redactEnvForLogs(env2) { - const redacted = {}; - for (const [key, value] of Object.entries(env2)) { - redacted[key] = SENSITIVE_ENV_KEY.test(key) ? "***REDACTED***" : value; - } - return redacted; -} -function buildInvocationEnvForLogs(env2, options = {}) { - const merged = { ...env2 }; - const runtimeEnv = options.runtimeEnv ?? {}; - for (const key of options.includeRuntimeKeys ?? []) { - if (key in merged) continue; - const value = runtimeEnv[key]; - if (typeof value !== "string" || value.length === 0) continue; - merged[key] = value; - } - const resolvedCommand = options.resolvedCommand?.trim(); - if (resolvedCommand) { - merged[options.resolvedCommandEnvKey ?? "TASKCORE_RESOLVED_COMMAND"] = resolvedCommand; - } - return redactEnvForLogs(merged); -} -function buildTaskcoreEnv(agent) { - const resolveHostForUrl = (rawHost) => { - const host = rawHost.trim(); - if (!host || host === "0.0.0.0" || host === "::") return "localhost"; - if (host.includes(":") && !host.startsWith("[") && !host.endsWith("]")) return `[${host}]`; - return host; - }; - const vars = { - TASKCORE_AGENT_ID: agent.id, - TASKCORE_COMPANY_ID: agent.companyId - }; - const runtimeHost = resolveHostForUrl( - process.env.TASKCORE_LISTEN_HOST ?? process.env.HOST ?? "localhost" - ); - const runtimePort = process.env.TASKCORE_LISTEN_PORT ?? process.env.PORT ?? "3100"; - const apiUrl = process.env.TASKCORE_API_URL ?? `http://${runtimeHost}:${runtimePort}`; - vars.TASKCORE_API_URL = apiUrl; - return vars; -} -function defaultPathForPlatform() { - if (process.platform === "win32") { - return "C:\\Windows\\System32;C:\\Windows;C:\\Windows\\System32\\Wbem"; - } - return "/usr/local/bin:/opt/homebrew/bin:/usr/local/sbin:/usr/bin:/bin:/usr/sbin:/sbin"; -} -function windowsPathExts(env2) { - return (env2.PATHEXT ?? ".EXE;.CMD;.BAT;.COM").split(";").filter(Boolean); -} -async function pathExists(candidate) { - try { - await fs4.access(candidate, process.platform === "win32" ? fsConstants.F_OK : fsConstants.X_OK); - return true; - } catch { - return false; - } -} -async function resolveCommandPath(command, cwd, env2) { - const hasPathSeparator = command.includes("/") || command.includes("\\"); - if (hasPathSeparator) { - const absolute = path4.isAbsolute(command) ? command : path4.resolve(cwd, command); - return await pathExists(absolute) ? absolute : null; - } - const pathValue = env2.PATH ?? env2.Path ?? ""; - const delimiter = process.platform === "win32" ? ";" : ":"; - const dirs = pathValue.split(delimiter).filter(Boolean); - const exts = process.platform === "win32" ? windowsPathExts(env2) : [""]; - const hasExtension = process.platform === "win32" && path4.extname(command).length > 0; - for (const dir of dirs) { - const candidates = process.platform === "win32" ? hasExtension ? [path4.join(dir, command)] : exts.map((ext) => path4.join(dir, `${command}${ext}`)) : [path4.join(dir, command)]; - for (const candidate of candidates) { - if (await pathExists(candidate)) return candidate; - } - } - return null; -} -async function resolveCommandForLogs(command, cwd, env2) { - return await resolveCommandPath(command, cwd, env2) ?? command; -} -function quoteForCmd(arg) { - if (!arg.length) return '""'; - const escaped = arg.replace(/"/g, '""'); - return /[\s"&<>|^()]/.test(escaped) ? `"${escaped}"` : escaped; -} -function resolveWindowsCmdShell(env2) { - const fallbackRoot = env2.SystemRoot || process.env.SystemRoot || "C:\\Windows"; - return path4.join(fallbackRoot, "System32", "cmd.exe"); -} -async function resolveSpawnTarget(command, args, cwd, env2) { - const resolved = await resolveCommandPath(command, cwd, env2); - const executable = resolved ?? command; - if (process.platform !== "win32") { - return { command: executable, args }; - } - if (/\.(cmd|bat)$/i.test(executable)) { - const shell = resolveWindowsCmdShell(env2); - const commandLine = [quoteForCmd(executable), ...args.map(quoteForCmd)].join(" "); - return { - command: shell, - args: ["/d", "/s", "/c", commandLine] - }; - } - return { command: executable, args }; -} -function ensurePathInEnv(env2) { - if (typeof env2.PATH === "string" && env2.PATH.length > 0) return env2; - if (typeof env2.Path === "string" && env2.Path.length > 0) return env2; - return { ...env2, PATH: defaultPathForPlatform() }; -} -async function ensureAbsoluteDirectory(cwd, opts = {}) { - if (!path4.isAbsolute(cwd)) { - throw new Error(`Working directory must be an absolute path: "${cwd}"`); - } - const assertDirectory = async () => { - const stats = await fs4.stat(cwd); - if (!stats.isDirectory()) { - throw new Error(`Working directory is not a directory: "${cwd}"`); - } - }; - try { - await assertDirectory(); - return; - } catch (err) { - const code = err.code; - if (!opts.createIfMissing || code !== "ENOENT") { - if (code === "ENOENT") { - throw new Error(`Working directory does not exist: "${cwd}"`); - } - throw err instanceof Error ? err : new Error(String(err)); - } - } - try { - await fs4.mkdir(cwd, { recursive: true }); - await assertDirectory(); - } catch (err) { - const reason = err instanceof Error ? err.message : String(err); - throw new Error(`Could not create working directory "${cwd}": ${reason}`); - } -} -async function resolveTaskcoreSkillsDir(moduleDir, additionalCandidates = []) { - const candidates = [ - ...TASKCORE_SKILL_ROOT_RELATIVE_CANDIDATES.map((relativePath) => path4.resolve(moduleDir, relativePath)), - ...additionalCandidates.map((candidate) => path4.resolve(candidate)) - ]; - const seenRoots = /* @__PURE__ */ new Set(); - for (const root of candidates) { - if (seenRoots.has(root)) continue; - seenRoots.add(root); - const isDirectory = await fs4.stat(root).then((stats) => stats.isDirectory()).catch(() => false); - if (isDirectory) return root; - } - return null; -} -async function listTaskcoreSkillEntries(moduleDir, additionalCandidates = []) { - const root = await resolveTaskcoreSkillsDir(moduleDir, additionalCandidates); - if (!root) return []; - try { - const entries2 = await fs4.readdir(root, { withFileTypes: true }); - return entries2.filter((entry) => entry.isDirectory()).map((entry) => ({ - key: `taskcore/taskcore/${entry.name}`, - runtimeName: entry.name, - source: path4.join(root, entry.name), - required: true, - requiredReason: "Bundled Taskcore skills are always available for local adapters." - })); - } catch { - return []; - } -} -async function readInstalledSkillTargets(skillsHome) { - const entries2 = await fs4.readdir(skillsHome, { withFileTypes: true }).catch(() => []); - const out = /* @__PURE__ */ new Map(); - for (const entry of entries2) { - const fullPath = path4.join(skillsHome, entry.name); - const linkedPath = entry.isSymbolicLink() ? await fs4.readlink(fullPath).catch(() => null) : null; - out.set(entry.name, resolveInstalledEntryTarget(skillsHome, entry.name, entry, linkedPath)); - } - return out; -} -function buildPersistentSkillSnapshot(options) { - const { - adapterType, - availableEntries, - desiredSkills, - installed, - skillsHome, - locationLabel, - installedDetail, - missingDetail, - externalConflictDetail, - externalDetail - } = options; - const availableByKey = new Map(availableEntries.map((entry) => [entry.key, entry])); - const desiredSet = new Set(desiredSkills); - const entries2 = []; - const warnings = [...options.warnings ?? []]; - for (const available of availableEntries) { - const installedEntry = installed.get(available.runtimeName) ?? null; - const desired = desiredSet.has(available.key); - let state2 = "available"; - let managed = false; - let detail = null; - if (installedEntry?.targetPath === available.source) { - managed = true; - state2 = desired ? "installed" : "stale"; - detail = installedDetail ?? null; - } else if (installedEntry) { - state2 = "external"; - detail = desired ? externalConflictDetail : externalDetail; - } else if (desired) { - state2 = "missing"; - detail = missingDetail; - } - entries2.push({ - key: available.key, - runtimeName: available.runtimeName, - desired, - managed, - state: state2, - sourcePath: available.source, - targetPath: path4.join(skillsHome, available.runtimeName), - detail, - required: Boolean(available.required), - requiredReason: available.requiredReason ?? null, - ...buildManagedSkillOrigin(available) - }); - } - for (const desiredSkill of desiredSkills) { - if (availableByKey.has(desiredSkill)) continue; - warnings.push(`Desired skill "${desiredSkill}" is not available from the Taskcore skills directory.`); - entries2.push({ - key: desiredSkill, - runtimeName: null, - desired: true, - managed: true, - state: "missing", - sourcePath: null, - targetPath: null, - detail: "Taskcore cannot find this skill in the local runtime skills directory.", - origin: "external_unknown", - originLabel: "External or unavailable", - readOnly: false - }); - } - for (const [name, installedEntry] of installed.entries()) { - if (availableEntries.some((entry) => entry.runtimeName === name)) continue; - entries2.push({ - key: name, - runtimeName: name, - desired: false, - managed: false, - state: "external", - origin: "user_installed", - originLabel: "User-installed", - locationLabel: skillLocationLabel(locationLabel), - readOnly: true, - sourcePath: null, - targetPath: installedEntry.targetPath ?? path4.join(skillsHome, name), - detail: externalDetail - }); - } - entries2.sort((left, right) => left.key.localeCompare(right.key)); - return { - adapterType, - supported: true, - mode: "persistent", - desiredSkills, - entries: entries2, - warnings - }; -} -function normalizeConfiguredTaskcoreRuntimeSkills(value) { - if (!Array.isArray(value)) return []; - const out = []; - for (const rawEntry of value) { - const entry = parseObject(rawEntry); - const key = asString(entry.key, asString(entry.name, "")).trim(); - const runtimeName = asString(entry.runtimeName, asString(entry.name, "")).trim(); - const source = asString(entry.source, "").trim(); - if (!key || !runtimeName || !source) continue; - out.push({ - key, - runtimeName, - source, - required: asBoolean(entry.required, false), - requiredReason: typeof entry.requiredReason === "string" && entry.requiredReason.trim().length > 0 ? entry.requiredReason.trim() : null - }); - } - return out; -} -async function readTaskcoreRuntimeSkillEntries(config3, moduleDir, additionalCandidates = []) { - const configuredEntries = normalizeConfiguredTaskcoreRuntimeSkills(config3.taskcoreRuntimeSkills); - if (configuredEntries.length > 0) return configuredEntries; - return listTaskcoreSkillEntries(moduleDir, additionalCandidates); -} -function readTaskcoreSkillSyncPreference(config3) { - const raw = config3.taskcoreSkillSync; - if (typeof raw !== "object" || raw === null || Array.isArray(raw)) { - return { explicit: false, desiredSkills: [] }; - } - const syncConfig = raw; - const desiredValues = syncConfig.desiredSkills; - const desired = Array.isArray(desiredValues) ? desiredValues.filter((value) => typeof value === "string").map((value) => value.trim()).filter(Boolean) : []; - return { - explicit: Object.prototype.hasOwnProperty.call(raw, "desiredSkills"), - desiredSkills: Array.from(new Set(desired)) - }; -} -function canonicalizeDesiredTaskcoreSkillReference(reference, availableEntries) { - const normalizedReference = reference.trim().toLowerCase(); - if (!normalizedReference) return ""; - const exactKey = availableEntries.find((entry) => entry.key.trim().toLowerCase() === normalizedReference); - if (exactKey) return exactKey.key; - const byRuntimeName = availableEntries.filter( - (entry) => typeof entry.runtimeName === "string" && entry.runtimeName.trim().toLowerCase() === normalizedReference - ); - if (byRuntimeName.length === 1) return byRuntimeName[0].key; - const slugMatches = availableEntries.filter( - (entry) => entry.key.trim().toLowerCase().split("/").pop() === normalizedReference - ); - if (slugMatches.length === 1) return slugMatches[0].key; - return normalizedReference; -} -function resolveTaskcoreDesiredSkillNames(config3, availableEntries) { - const preference = readTaskcoreSkillSyncPreference(config3); - const requiredSkills = availableEntries.filter((entry) => entry.required).map((entry) => entry.key); - if (!preference.explicit) { - return Array.from(new Set(requiredSkills)); - } - const desiredSkills = preference.desiredSkills.map((reference) => canonicalizeDesiredTaskcoreSkillReference(reference, availableEntries)).filter(Boolean); - return Array.from(/* @__PURE__ */ new Set([...requiredSkills, ...desiredSkills])); -} -function writeTaskcoreSkillSyncPreference(config3, desiredSkills) { - const next = { ...config3 }; - const raw = next.taskcoreSkillSync; - const current = typeof raw === "object" && raw !== null && !Array.isArray(raw) ? { ...raw } : {}; - current.desiredSkills = Array.from( - new Set( - desiredSkills.map((value) => value.trim()).filter(Boolean) - ) - ); - next.taskcoreSkillSync = current; - return next; -} -async function ensureTaskcoreSkillSymlink(source, target, linkSkill = (linkSource, linkTarget) => fs4.symlink(linkSource, linkTarget)) { - const existing = await fs4.lstat(target).catch(() => null); - if (!existing) { - await linkSkill(source, target); - return "created"; - } - if (!existing.isSymbolicLink()) { - return "skipped"; - } - const linkedPath = await fs4.readlink(target).catch(() => null); - if (!linkedPath) return "skipped"; - const resolvedLinkedPath = path4.resolve(path4.dirname(target), linkedPath); - if (resolvedLinkedPath === source) { - return "skipped"; - } - const linkedPathExists = await fs4.stat(resolvedLinkedPath).then(() => true).catch(() => false); - if (linkedPathExists) { - return "skipped"; - } - await fs4.unlink(target); - await linkSkill(source, target); - return "repaired"; -} -async function removeMaintainerOnlySkillSymlinks(skillsHome, allowedSkillNames) { - const allowed2 = new Set(Array.from(allowedSkillNames)); - try { - const entries2 = await fs4.readdir(skillsHome, { withFileTypes: true }); - const removed = []; - for (const entry of entries2) { - if (allowed2.has(entry.name)) continue; - const target = path4.join(skillsHome, entry.name); - const existing = await fs4.lstat(target).catch(() => null); - if (!existing?.isSymbolicLink()) continue; - const linkedPath = await fs4.readlink(target).catch(() => null); - if (!linkedPath) continue; - const resolvedLinkedPath = path4.isAbsolute(linkedPath) ? linkedPath : path4.resolve(path4.dirname(target), linkedPath); - if (!isMaintainerOnlySkillTarget(linkedPath) && !isMaintainerOnlySkillTarget(resolvedLinkedPath)) { - continue; - } - await fs4.unlink(target); - removed.push(entry.name); - } - return removed; - } catch { - return []; - } -} -async function ensureCommandResolvable(command, cwd, env2) { - const resolved = await resolveCommandPath(command, cwd, env2); - if (resolved) return; - if (command.includes("/") || command.includes("\\")) { - const absolute = path4.isAbsolute(command) ? command : path4.resolve(cwd, command); - throw new Error(`Command is not executable: "${command}" (resolved: "${absolute}")`); - } - throw new Error(`Command not found in PATH: "${command}"`); -} -async function runChildProcess(runId, command, args, opts) { - const onLogError = opts.onLogError ?? ((err, id, msg) => console.warn({ err, runId: id }, msg)); - return new Promise((resolve4, reject) => { - const rawMerged = { ...process.env, ...opts.env }; - const CLAUDE_CODE_NESTING_VARS = [ - "CLAUDECODE", - "CLAUDE_CODE_ENTRYPOINT", - "CLAUDE_CODE_SESSION", - "CLAUDE_CODE_PARENT_SESSION" - ]; - for (const key of CLAUDE_CODE_NESTING_VARS) { - delete rawMerged[key]; - } - const mergedEnv = ensurePathInEnv(rawMerged); - void resolveSpawnTarget(command, args, opts.cwd, mergedEnv).then((target) => { - const child = spawn(target.command, target.args, { - cwd: opts.cwd, - env: mergedEnv, - detached: process.platform !== "win32", - shell: false, - stdio: [opts.stdin != null ? "pipe" : "ignore", "pipe", "pipe"] - }); - const startedAt = (/* @__PURE__ */ new Date()).toISOString(); - const processGroupId = resolveProcessGroupId(child); - const spawnPersistPromise = typeof child.pid === "number" && child.pid > 0 && opts.onSpawn ? opts.onSpawn({ pid: child.pid, processGroupId, startedAt }).catch((err) => { - onLogError(err, runId, "failed to record child process metadata"); - }) : Promise.resolve(); - runningProcesses.set(runId, { child, graceSec: opts.graceSec, processGroupId }); - let timedOut = false; - let stdout = ""; - let stderr = ""; - let logChain = Promise.resolve(); - const timeout = opts.timeoutSec > 0 ? setTimeout(() => { - timedOut = true; - signalRunningProcess({ child, processGroupId }, "SIGTERM"); - setTimeout(() => { - signalRunningProcess({ child, processGroupId }, "SIGKILL"); - }, Math.max(1, opts.graceSec) * 1e3); - }, opts.timeoutSec * 1e3) : null; - child.stdout?.on("data", (chunk) => { - const text3 = String(chunk); - stdout = appendWithCap(stdout, text3); - logChain = logChain.then(() => opts.onLog("stdout", text3)).catch((err) => onLogError(err, runId, "failed to append stdout log chunk")); - }); - child.stderr?.on("data", (chunk) => { - const text3 = String(chunk); - stderr = appendWithCap(stderr, text3); - logChain = logChain.then(() => opts.onLog("stderr", text3)).catch((err) => onLogError(err, runId, "failed to append stderr log chunk")); - }); - const stdin = child.stdin; - if (opts.stdin != null && stdin) { - void spawnPersistPromise.finally(() => { - if (child.killed || stdin.destroyed) return; - stdin.write(opts.stdin); - stdin.end(); - }); - } - child.on("error", (err) => { - if (timeout) clearTimeout(timeout); - runningProcesses.delete(runId); - const errno = err.code; - const pathValue = mergedEnv.PATH ?? mergedEnv.Path ?? ""; - const msg = errno === "ENOENT" ? `Failed to start command "${command}" in "${opts.cwd}". Verify adapter command, working directory, and PATH (${pathValue}).` : `Failed to start command "${command}" in "${opts.cwd}": ${err.message}`; - reject(new Error(msg)); - }); - child.on("close", (code, signal) => { - if (timeout) clearTimeout(timeout); - runningProcesses.delete(runId); - void logChain.finally(() => { - resolve4({ - exitCode: code, - signal, - timedOut, - stdout, - stderr, - pid: child.pid ?? null, - startedAt - }); - }); - }); - }).catch(reject); - }); -} - -// packages/adapters/claude-local/src/server/execute.ts -import fs6 from "node:fs/promises"; -import path7 from "node:path"; -import { fileURLToPath as fileURLToPath3 } from "node:url"; - -// packages/adapters/claude-local/src/server/parse.ts -var CLAUDE_AUTH_REQUIRED_RE = /(?:not\s+logged\s+in|please\s+log\s+in|please\s+run\s+`?claude\s+login`?|login\s+required|requires\s+login|unauthorized|authentication\s+required)/i; -var URL_RE = /(https?:\/\/[^\s'"`<>()[\]{};,!?]+[^\s'"`<>()[\]{};,!.?:]+)/gi; -function parseClaudeStreamJson(stdout) { - let sessionId = null; - let model = ""; - let finalResult = null; - const assistantTexts = []; - for (const rawLine of stdout.split(/\r?\n/)) { - const line3 = rawLine.trim(); - if (!line3) continue; - const event = parseJson2(line3); - if (!event) continue; - const type = asString(event.type, ""); - if (type === "system" && asString(event.subtype, "") === "init") { - sessionId = asString(event.session_id, sessionId ?? "") || sessionId; - model = asString(event.model, model); - continue; - } - if (type === "assistant") { - sessionId = asString(event.session_id, sessionId ?? "") || sessionId; - const message2 = parseObject(event.message); - const content = Array.isArray(message2.content) ? message2.content : []; - for (const entry of content) { - if (typeof entry !== "object" || entry === null || Array.isArray(entry)) continue; - const block = entry; - if (asString(block.type, "") === "text") { - const text3 = asString(block.text, ""); - if (text3) assistantTexts.push(text3); - } - } - continue; - } - if (type === "result") { - finalResult = event; - sessionId = asString(event.session_id, sessionId ?? "") || sessionId; - } - } - if (!finalResult) { - return { - sessionId, - model, - costUsd: null, - usage: null, - summary: assistantTexts.join("\n\n").trim(), - resultJson: null - }; - } - const usageObj = parseObject(finalResult.usage); - const usage = { - inputTokens: asNumber(usageObj.input_tokens, 0), - cachedInputTokens: asNumber(usageObj.cache_read_input_tokens, 0), - outputTokens: asNumber(usageObj.output_tokens, 0) - }; - const costRaw = finalResult.total_cost_usd; - const costUsd = typeof costRaw === "number" && Number.isFinite(costRaw) ? costRaw : null; - const summary = asString(finalResult.result, assistantTexts.join("\n\n")).trim(); - return { - sessionId, - model, - costUsd, - usage, - summary, - resultJson: finalResult - }; -} -function extractClaudeErrorMessages(parsed) { - const raw = Array.isArray(parsed.errors) ? parsed.errors : []; - const messages2 = []; - for (const entry of raw) { - if (typeof entry === "string") { - const msg2 = entry.trim(); - if (msg2) messages2.push(msg2); - continue; - } - if (typeof entry !== "object" || entry === null || Array.isArray(entry)) { - continue; - } - const obj = entry; - const msg = asString(obj.message, "") || asString(obj.error, "") || asString(obj.code, ""); - if (msg) { - messages2.push(msg); - continue; - } - try { - messages2.push(JSON.stringify(obj)); - } catch { - } - } - return messages2; -} -function extractClaudeLoginUrl(text3) { - const match = text3.match(URL_RE); - if (!match || match.length === 0) return null; - for (const rawUrl of match) { - const cleaned = rawUrl.replace(/[\])}.!,?;:'\"]+$/g, ""); - if (cleaned.includes("claude") || cleaned.includes("anthropic") || cleaned.includes("auth")) { - return cleaned; - } - } - return match[0]?.replace(/[\])}.!,?;:'\"]+$/g, "") ?? null; -} -function detectClaudeLoginRequired(input) { - const resultText = asString(input.parsed?.result, "").trim(); - const messages2 = [resultText, ...extractClaudeErrorMessages(input.parsed ?? {}), input.stdout, input.stderr].join("\n").split(/\r?\n/).map((line3) => line3.trim()).filter(Boolean); - const requiresLogin = messages2.some((line3) => CLAUDE_AUTH_REQUIRED_RE.test(line3)); - return { - requiresLogin, - loginUrl: extractClaudeLoginUrl([input.stdout, input.stderr].join("\n")) - }; -} -function describeClaudeFailure(parsed) { - const subtype = asString(parsed.subtype, ""); - const resultText = asString(parsed.result, "").trim(); - const errors = extractClaudeErrorMessages(parsed); - let detail = resultText; - if (!detail && errors.length > 0) { - detail = errors[0] ?? ""; - } - const parts = ["Claude run failed"]; - if (subtype) parts.push(`subtype=${subtype}`); - if (detail) parts.push(detail); - return parts.length > 1 ? parts.join(": ") : null; -} -function isClaudeMaxTurnsResult(parsed) { - if (!parsed) return false; - const subtype = asString(parsed.subtype, "").trim().toLowerCase(); - if (subtype === "error_max_turns") return true; - const stopReason = asString(parsed.stop_reason, "").trim().toLowerCase(); - if (stopReason === "max_turns") return true; - const resultText = asString(parsed.result, "").trim(); - return /max(?:imum)?\s+turns?/i.test(resultText); -} -function isClaudeUnknownSessionError(parsed) { - const resultText = asString(parsed.result, "").trim(); - const allMessages = [resultText, ...extractClaudeErrorMessages(parsed)].map((msg) => msg.trim()).filter(Boolean); - return allMessages.some( - (msg) => /no conversation found with session id|unknown session|session .* not found/i.test(msg) - ); -} - -// packages/adapters/claude-local/src/server/skills.ts -import os3 from "node:os"; -import path5 from "node:path"; -import { fileURLToPath as fileURLToPath2 } from "node:url"; -var __moduleDir = path5.dirname(fileURLToPath2(import.meta.url)); -function asString2(value) { - return typeof value === "string" && value.trim().length > 0 ? value.trim() : null; -} -function resolveClaudeSkillsHome(config3) { - const env2 = typeof config3.env === "object" && config3.env !== null && !Array.isArray(config3.env) ? config3.env : {}; - const configuredHome = asString2(env2.HOME); - const home = configuredHome ? path5.resolve(configuredHome) : os3.homedir(); - return path5.join(home, ".claude", "skills"); -} -async function buildClaudeSkillSnapshot(config3) { - const availableEntries = await readTaskcoreRuntimeSkillEntries(config3, __moduleDir); - const availableByKey = new Map(availableEntries.map((entry) => [entry.key, entry])); - const desiredSkills = resolveTaskcoreDesiredSkillNames(config3, availableEntries); - const desiredSet = new Set(desiredSkills); - const skillsHome = resolveClaudeSkillsHome(config3); - const installed = await readInstalledSkillTargets(skillsHome); - const entries2 = availableEntries.map((entry) => ({ - key: entry.key, - runtimeName: entry.runtimeName, - desired: desiredSet.has(entry.key), - managed: true, - state: desiredSet.has(entry.key) ? "configured" : "available", - origin: entry.required ? "taskcore_required" : "company_managed", - originLabel: entry.required ? "Required by Taskcore" : "Managed by Taskcore", - readOnly: false, - sourcePath: entry.source, - targetPath: null, - detail: desiredSet.has(entry.key) ? "Will be materialized into the stable Taskcore-managed Claude prompt bundle on the next run." : null, - required: Boolean(entry.required), - requiredReason: entry.requiredReason ?? null - })); - const warnings = []; - for (const desiredSkill of desiredSkills) { - if (availableByKey.has(desiredSkill)) continue; - warnings.push(`Desired skill "${desiredSkill}" is not available from the Taskcore skills directory.`); - entries2.push({ - key: desiredSkill, - runtimeName: null, - desired: true, - managed: true, - state: "missing", - origin: "external_unknown", - originLabel: "External or unavailable", - readOnly: false, - sourcePath: void 0, - targetPath: void 0, - detail: "Taskcore cannot find this skill in the local runtime skills directory." - }); - } - for (const [name, installedEntry] of installed.entries()) { - if (availableEntries.some((entry) => entry.runtimeName === name)) continue; - entries2.push({ - key: name, - runtimeName: name, - desired: false, - managed: false, - state: "external", - origin: "user_installed", - originLabel: "User-installed", - locationLabel: "~/.claude/skills", - readOnly: true, - sourcePath: null, - targetPath: installedEntry.targetPath ?? path5.join(skillsHome, name), - detail: "Installed outside Taskcore management in the Claude skills home." - }); - } - entries2.sort((left, right) => left.key.localeCompare(right.key)); - return { - adapterType: "claude_local", - supported: true, - mode: "ephemeral", - desiredSkills, - entries: entries2, - warnings - }; -} -async function listClaudeSkills(ctx) { - return buildClaudeSkillSnapshot(ctx.config); -} -async function syncClaudeSkills(ctx, _desiredSkills) { - return buildClaudeSkillSnapshot(ctx.config); -} -function resolveClaudeDesiredSkillNames(config3, availableEntries) { - return resolveTaskcoreDesiredSkillNames(config3, availableEntries); -} - -// packages/adapters/claude-local/src/index.ts -var models = [ - { id: "claude-opus-4-6", label: "Claude Opus 4.6" }, - { id: "claude-sonnet-4-6", label: "Claude Sonnet 4.6" }, - { id: "claude-haiku-4-6", label: "Claude Haiku 4.6" }, - { id: "claude-sonnet-4-5-20250929", label: "Claude Sonnet 4.5" }, - { id: "claude-haiku-4-5-20251001", label: "Claude Haiku 4.5" } -]; -var agentConfigurationDoc = `# claude_local agent configuration - -Adapter: claude_local - -Core fields: -- cwd (string, optional): default absolute working directory fallback for the agent process (created if missing when possible) -- instructionsFilePath (string, optional): absolute path to a markdown instructions file injected at runtime -- model (string, optional): Claude model id -- effort (string, optional): reasoning effort passed via --effort (low|medium|high) -- chrome (boolean, optional): pass --chrome when running Claude -- promptTemplate (string, optional): run prompt template -- maxTurnsPerRun (number, optional): max turns for one run -- dangerouslySkipPermissions (boolean, optional, default true): pass --dangerously-skip-permissions to claude; defaults to true because Taskcore runs Claude in headless --print mode where interactive permission prompts cannot be answered -- command (string, optional): defaults to "claude" -- extraArgs (string[], optional): additional CLI args -- env (object, optional): KEY=VALUE environment variables -- workspaceStrategy (object, optional): execution workspace strategy; currently supports { type: "git_worktree", baseRef?, branchTemplate?, worktreeParentDir? } -- workspaceRuntime (object, optional): reserved for workspace runtime metadata; workspace runtime services are manually controlled from the workspace UI and are not auto-started by heartbeats - -Operational fields: -- timeoutSec (number, optional): run timeout in seconds -- graceSec (number, optional): SIGTERM grace period in seconds - -Notes: -- When Taskcore realizes a workspace/runtime for a run, it injects TASKCORE_WORKSPACE_* and TASKCORE_RUNTIME_* env vars for agent-side tooling. -`; - -// packages/adapters/claude-local/src/server/models.ts -var BEDROCK_MODELS = [ - { id: "us.anthropic.claude-opus-4-6-v1", label: "Bedrock Opus 4.6" }, - { id: "us.anthropic.claude-sonnet-4-5-20250929-v2:0", label: "Bedrock Sonnet 4.5" }, - { id: "us.anthropic.claude-haiku-4-5-20251001-v1:0", label: "Bedrock Haiku 4.5" } -]; -function isBedrockEnv() { - return process.env.CLAUDE_CODE_USE_BEDROCK === "1" || process.env.CLAUDE_CODE_USE_BEDROCK === "true" || typeof process.env.ANTHROPIC_BEDROCK_BASE_URL === "string" && process.env.ANTHROPIC_BEDROCK_BASE_URL.trim().length > 0; -} -async function listClaudeModels() { - return isBedrockEnv() ? BEDROCK_MODELS : models; -} -function isBedrockModelId(model) { - return /^\w+\.anthropic\./.test(model) || model.startsWith("arn:aws:bedrock:"); -} - -// packages/adapters/claude-local/src/server/prompt-cache.ts -import { constants as fsConstants2 } from "node:fs"; -import fs5 from "node:fs/promises"; -import os4 from "node:os"; -import path6 from "node:path"; -import { createHash as createHash3 } from "node:crypto"; -var DEFAULT_TASKCORE_INSTANCE_ID = "default"; -function nonEmpty(value) { - return typeof value === "string" && value.trim().length > 0 ? value.trim() : null; -} -function resolveManagedClaudePromptCacheRoot(env2, companyId) { - const taskcoreHome = nonEmpty(env2.TASKCORE_HOME) ?? path6.resolve(os4.homedir(), ".taskcore"); - const instanceId = nonEmpty(env2.TASKCORE_INSTANCE_ID) ?? DEFAULT_TASKCORE_INSTANCE_ID; - return path6.resolve( - taskcoreHome, - "instances", - instanceId, - "companies", - companyId, - "claude-prompt-cache" - ); -} -async function hashPathContents(candidate, hash2, relativePath, seenDirectories) { - const stat5 = await fs5.lstat(candidate); - if (stat5.isSymbolicLink()) { - hash2.update(`symlink:${relativePath} -`); - const resolved = await fs5.realpath(candidate).catch(() => null); - if (!resolved) { - hash2.update("missing\n"); - return; - } - await hashPathContents(resolved, hash2, relativePath, seenDirectories); - return; - } - if (stat5.isDirectory()) { - const realDir = await fs5.realpath(candidate).catch(() => candidate); - hash2.update(`dir:${relativePath} -`); - if (seenDirectories.has(realDir)) { - hash2.update("loop\n"); - return; - } - seenDirectories.add(realDir); - const entries2 = await fs5.readdir(candidate, { withFileTypes: true }); - entries2.sort((left, right) => left.name.localeCompare(right.name)); - for (const entry of entries2) { - const childRelativePath = relativePath.length > 0 ? `${relativePath}/${entry.name}` : entry.name; - await hashPathContents(path6.join(candidate, entry.name), hash2, childRelativePath, seenDirectories); - } - return; - } - if (stat5.isFile()) { - hash2.update(`file:${relativePath} -`); - hash2.update(await fs5.readFile(candidate)); - hash2.update("\n"); - return; - } - hash2.update(`other:${relativePath}:${stat5.mode} -`); -} -async function buildClaudePromptBundleKey(input) { - const hash2 = createHash3("sha256"); - hash2.update("taskcore-claude-prompt-bundle:v1\n"); - if (input.instructionsContents) { - hash2.update("instructions\n"); - hash2.update(input.instructionsContents); - hash2.update("\n"); - } else { - hash2.update("instructions:none\n"); - } - const sortedSkills = [...input.skills].sort((left, right) => left.runtimeName.localeCompare(right.runtimeName)); - for (const entry of sortedSkills) { - hash2.update(`skill:${entry.key}:${entry.runtimeName} -`); - await hashPathContents(entry.source, hash2, entry.runtimeName, /* @__PURE__ */ new Set()); - } - return hash2.digest("hex"); -} -async function ensureReadableFile(targetPath, contents) { - try { - await fs5.access(targetPath, fsConstants2.R_OK); - return; - } catch { - } - await fs5.mkdir(path6.dirname(targetPath), { recursive: true }); - const tempPath = `${targetPath}.${process.pid}.${Date.now()}.tmp`; - try { - await fs5.writeFile(tempPath, contents, "utf8"); - await fs5.rename(tempPath, targetPath); - } catch (err) { - const targetReadable = await fs5.access(targetPath, fsConstants2.R_OK).then(() => true).catch(() => false); - if (!targetReadable) { - throw err; - } - } finally { - await fs5.rm(tempPath, { force: true }).catch(() => { - }); - } -} -async function prepareClaudePromptBundle(input) { - const { companyId, skills, instructionsContents, onLog } = input; - const bundleKey = await buildClaudePromptBundleKey({ - skills, - instructionsContents - }); - const rootDir = path6.join(resolveManagedClaudePromptCacheRoot(process.env, companyId), bundleKey); - const skillsHome = path6.join(rootDir, ".claude", "skills"); - await fs5.mkdir(skillsHome, { recursive: true }); - for (const entry of skills) { - const target = path6.join(skillsHome, entry.runtimeName); - try { - await ensureTaskcoreSkillSymlink(entry.source, target); - } catch (err) { - await onLog( - "stderr", - `[taskcore] Failed to materialize Claude skill "${entry.key}" into ${skillsHome}: ${err instanceof Error ? err.message : String(err)} -` - ); - } - } - const instructionsFilePath = instructionsContents ? path6.join(rootDir, "agent-instructions.md") : null; - if (instructionsFilePath && instructionsContents) { - await ensureReadableFile(instructionsFilePath, instructionsContents); - } - return { - bundleKey, - rootDir, - addDir: rootDir, - instructionsFilePath - }; -} - -// packages/adapters/claude-local/src/server/execute.ts -var __moduleDir2 = path7.dirname(fileURLToPath3(import.meta.url)); -function buildLoginResult(input) { - return { - exitCode: input.proc.exitCode, - signal: input.proc.signal, - timedOut: input.proc.timedOut, - stdout: input.proc.stdout, - stderr: input.proc.stderr, - loginUrl: input.loginUrl - }; -} -function hasNonEmptyEnvValue(env2, key) { - const raw = env2[key]; - return typeof raw === "string" && raw.trim().length > 0; -} -function isBedrockAuth(env2) { - return env2.CLAUDE_CODE_USE_BEDROCK === "1" || env2.CLAUDE_CODE_USE_BEDROCK === "true" || hasNonEmptyEnvValue(env2, "ANTHROPIC_BEDROCK_BASE_URL"); -} -function resolveClaudeBillingType(env2) { - if (isBedrockAuth(env2)) return "metered_api"; - return hasNonEmptyEnvValue(env2, "ANTHROPIC_API_KEY") ? "api" : "subscription"; -} -async function buildClaudeRuntimeConfig(input) { - const { runId, agent, config: config3, context, authToken } = input; - const command = asString(config3.command, "claude"); - const workspaceContext = parseObject(context.taskcoreWorkspace); - const workspaceCwd = asString(workspaceContext.cwd, ""); - const workspaceSource = asString(workspaceContext.source, ""); - const workspaceStrategy = asString(workspaceContext.strategy, ""); - const workspaceId = asString(workspaceContext.workspaceId, "") || null; - const workspaceRepoUrl = asString(workspaceContext.repoUrl, "") || null; - const workspaceRepoRef = asString(workspaceContext.repoRef, "") || null; - const workspaceBranch = asString(workspaceContext.branchName, "") || null; - const workspaceWorktreePath = asString(workspaceContext.worktreePath, "") || null; - const agentHome = asString(workspaceContext.agentHome, "") || null; - const workspaceHints = Array.isArray(context.taskcoreWorkspaces) ? context.taskcoreWorkspaces.filter( - (value) => typeof value === "object" && value !== null - ) : []; - const runtimeServiceIntents = Array.isArray(context.taskcoreRuntimeServiceIntents) ? context.taskcoreRuntimeServiceIntents.filter( - (value) => typeof value === "object" && value !== null - ) : []; - const runtimeServices = Array.isArray(context.taskcoreRuntimeServices) ? context.taskcoreRuntimeServices.filter( - (value) => typeof value === "object" && value !== null - ) : []; - const runtimePrimaryUrl = asString(context.taskcoreRuntimePrimaryUrl, ""); - const configuredCwd = asString(config3.cwd, ""); - const useConfiguredInsteadOfAgentHome = workspaceSource === "agent_home" && configuredCwd.length > 0; - const effectiveWorkspaceCwd = useConfiguredInsteadOfAgentHome ? "" : workspaceCwd; - const cwd = effectiveWorkspaceCwd || configuredCwd || process.cwd(); - await ensureAbsoluteDirectory(cwd, { createIfMissing: true }); - const envConfig = parseObject(config3.env); - const hasExplicitApiKey = typeof envConfig.TASKCORE_API_KEY === "string" && envConfig.TASKCORE_API_KEY.trim().length > 0; - const env2 = { ...buildTaskcoreEnv(agent) }; - env2.TASKCORE_RUN_ID = runId; - const wakeTaskId = typeof context.taskId === "string" && context.taskId.trim().length > 0 && context.taskId.trim() || typeof context.issueId === "string" && context.issueId.trim().length > 0 && context.issueId.trim() || null; - const wakeReason = typeof context.wakeReason === "string" && context.wakeReason.trim().length > 0 ? context.wakeReason.trim() : null; - const wakeCommentId = typeof context.wakeCommentId === "string" && context.wakeCommentId.trim().length > 0 && context.wakeCommentId.trim() || typeof context.commentId === "string" && context.commentId.trim().length > 0 && context.commentId.trim() || null; - const approvalId = typeof context.approvalId === "string" && context.approvalId.trim().length > 0 ? context.approvalId.trim() : null; - const approvalStatus = typeof context.approvalStatus === "string" && context.approvalStatus.trim().length > 0 ? context.approvalStatus.trim() : null; - const linkedIssueIds = Array.isArray(context.issueIds) ? context.issueIds.filter((value) => typeof value === "string" && value.trim().length > 0) : []; - const wakePayloadJson = stringifyTaskcoreWakePayload(context.taskcoreWake); - if (wakeTaskId) { - env2.TASKCORE_TASK_ID = wakeTaskId; - } - if (wakeReason) { - env2.TASKCORE_WAKE_REASON = wakeReason; - } - if (wakeCommentId) { - env2.TASKCORE_WAKE_COMMENT_ID = wakeCommentId; - } - if (approvalId) { - env2.TASKCORE_APPROVAL_ID = approvalId; - } - if (approvalStatus) { - env2.TASKCORE_APPROVAL_STATUS = approvalStatus; - } - if (linkedIssueIds.length > 0) { - env2.TASKCORE_LINKED_ISSUE_IDS = linkedIssueIds.join(","); - } - if (wakePayloadJson) { - env2.TASKCORE_WAKE_PAYLOAD_JSON = wakePayloadJson; - } - if (effectiveWorkspaceCwd) { - env2.TASKCORE_WORKSPACE_CWD = effectiveWorkspaceCwd; - } - if (workspaceSource) { - env2.TASKCORE_WORKSPACE_SOURCE = workspaceSource; - } - if (workspaceStrategy) { - env2.TASKCORE_WORKSPACE_STRATEGY = workspaceStrategy; - } - if (workspaceId) { - env2.TASKCORE_WORKSPACE_ID = workspaceId; - } - if (workspaceRepoUrl) { - env2.TASKCORE_WORKSPACE_REPO_URL = workspaceRepoUrl; - } - if (workspaceRepoRef) { - env2.TASKCORE_WORKSPACE_REPO_REF = workspaceRepoRef; - } - if (workspaceBranch) { - env2.TASKCORE_WORKSPACE_BRANCH = workspaceBranch; - } - if (workspaceWorktreePath) { - env2.TASKCORE_WORKSPACE_WORKTREE_PATH = workspaceWorktreePath; - } - if (agentHome) { - env2.AGENT_HOME = agentHome; - } - if (workspaceHints.length > 0) { - env2.TASKCORE_WORKSPACES_JSON = JSON.stringify(workspaceHints); - } - if (runtimeServiceIntents.length > 0) { - env2.TASKCORE_RUNTIME_SERVICE_INTENTS_JSON = JSON.stringify(runtimeServiceIntents); - } - if (runtimeServices.length > 0) { - env2.TASKCORE_RUNTIME_SERVICES_JSON = JSON.stringify(runtimeServices); - } - if (runtimePrimaryUrl) { - env2.TASKCORE_RUNTIME_PRIMARY_URL = runtimePrimaryUrl; - } - for (const [key, value] of Object.entries(envConfig)) { - if (typeof value === "string") env2[key] = value; - } - if (!hasExplicitApiKey && authToken) { - env2.TASKCORE_API_KEY = authToken; - } - const runtimeEnv = ensurePathInEnv({ ...process.env, ...env2 }); - await ensureCommandResolvable(command, cwd, runtimeEnv); - const resolvedCommand = await resolveCommandForLogs(command, cwd, runtimeEnv); - const loggedEnv = buildInvocationEnvForLogs(env2, { - runtimeEnv, - includeRuntimeKeys: ["HOME", "CLAUDE_CONFIG_DIR"], - resolvedCommand - }); - const timeoutSec = asNumber(config3.timeoutSec, 0); - const graceSec = asNumber(config3.graceSec, 20); - const extraArgs = (() => { - const fromExtraArgs = asStringArray(config3.extraArgs); - if (fromExtraArgs.length > 0) return fromExtraArgs; - return asStringArray(config3.args); - })(); - return { - command, - resolvedCommand, - cwd, - workspaceId, - workspaceRepoUrl, - workspaceRepoRef, - env: env2, - loggedEnv, - timeoutSec, - graceSec, - extraArgs - }; -} -async function runClaudeLogin(input) { - const onLog = input.onLog ?? (async () => { - }); - const runtime = await buildClaudeRuntimeConfig({ - runId: input.runId, - agent: input.agent, - config: input.config, - context: input.context ?? {}, - authToken: input.authToken - }); - const proc = await runChildProcess(input.runId, runtime.command, ["login"], { - cwd: runtime.cwd, - env: runtime.env, - timeoutSec: runtime.timeoutSec, - graceSec: runtime.graceSec, - onLog - }); - const loginMeta = detectClaudeLoginRequired({ - parsed: null, - stdout: proc.stdout, - stderr: proc.stderr - }); - return buildLoginResult({ - proc, - loginUrl: loginMeta.loginUrl - }); -} -async function execute(ctx) { - const { runId, agent, runtime, config: config3, context, onLog, onMeta, onSpawn, authToken } = ctx; - const promptTemplate = asString( - config3.promptTemplate, - "You are agent {{agent.id}} ({{agent.name}}). Continue your Taskcore work." - ); - const model = asString(config3.model, ""); - const effort = asString(config3.effort, ""); - const chrome = asBoolean(config3.chrome, false); - const maxTurns = asNumber(config3.maxTurnsPerRun, 0); - const dangerouslySkipPermissions = asBoolean(config3.dangerouslySkipPermissions, true); - const instructionsFilePath = asString(config3.instructionsFilePath, "").trim(); - const instructionsFileDir = instructionsFilePath ? `${path7.dirname(instructionsFilePath)}/` : ""; - const runtimeConfig = await buildClaudeRuntimeConfig({ - runId, - agent, - config: config3, - context, - authToken - }); - const { - command, - resolvedCommand, - cwd, - workspaceId, - workspaceRepoUrl, - workspaceRepoRef, - env: env2, - loggedEnv, - timeoutSec, - graceSec, - extraArgs - } = runtimeConfig; - const effectiveEnv = Object.fromEntries( - Object.entries({ ...process.env, ...env2 }).filter( - (entry) => typeof entry[1] === "string" - ) - ); - const billingType = resolveClaudeBillingType(effectiveEnv); - const claudeSkillEntries = await readTaskcoreRuntimeSkillEntries(config3, __moduleDir2); - const desiredSkillNames = new Set(resolveClaudeDesiredSkillNames(config3, claudeSkillEntries)); - let combinedInstructionsContents = null; - if (instructionsFilePath) { - try { - const instructionsContent = await fs6.readFile(instructionsFilePath, "utf-8"); - const pathDirective = ` -The above agent instructions were loaded from ${instructionsFilePath}. Resolve any relative file references from ${instructionsFileDir}. This base directory is authoritative for sibling instruction files such as ./HEARTBEAT.md, ./SOUL.md, and ./TOOLS.md; do not resolve those from the parent agent directory.`; - combinedInstructionsContents = instructionsContent + pathDirective; - } catch (err) { - const reason = err instanceof Error ? err.message : String(err); - await onLog( - "stderr", - `[taskcore] Warning: could not read agent instructions file "${instructionsFilePath}": ${reason} -` - ); - } - } - const promptBundle = await prepareClaudePromptBundle({ - companyId: agent.companyId, - skills: claudeSkillEntries.filter((entry) => desiredSkillNames.has(entry.key)), - instructionsContents: combinedInstructionsContents, - onLog - }); - const effectiveInstructionsFilePath = promptBundle.instructionsFilePath ?? void 0; - const runtimeSessionParams = parseObject(runtime.sessionParams); - const runtimeSessionId = asString(runtimeSessionParams.sessionId, runtime.sessionId ?? ""); - const runtimeSessionCwd = asString(runtimeSessionParams.cwd, ""); - const runtimePromptBundleKey = asString(runtimeSessionParams.promptBundleKey, ""); - const hasMatchingPromptBundle = runtimePromptBundleKey.length === 0 || runtimePromptBundleKey === promptBundle.bundleKey; - const canResumeSession = runtimeSessionId.length > 0 && hasMatchingPromptBundle && (runtimeSessionCwd.length === 0 || path7.resolve(runtimeSessionCwd) === path7.resolve(cwd)); - const sessionId = canResumeSession ? runtimeSessionId : null; - if (runtimeSessionId && runtimeSessionCwd.length > 0 && path7.resolve(runtimeSessionCwd) !== path7.resolve(cwd)) { - await onLog( - "stdout", - `[taskcore] Claude session "${runtimeSessionId}" was saved for cwd "${runtimeSessionCwd}" and will not be resumed in "${cwd}". -` - ); - } - if (runtimeSessionId && runtimePromptBundleKey.length > 0 && runtimePromptBundleKey !== promptBundle.bundleKey) { - await onLog( - "stdout", - `[taskcore] Claude session "${runtimeSessionId}" was saved for prompt bundle "${runtimePromptBundleKey}" and will not be resumed with "${promptBundle.bundleKey}". -` - ); - } - const bootstrapPromptTemplate = asString(config3.bootstrapPromptTemplate, ""); - const templateData = { - agentId: agent.id, - companyId: agent.companyId, - runId, - company: { id: agent.companyId }, - agent, - run: { id: runId, source: "on_demand" }, - context - }; - const renderedBootstrapPrompt = !sessionId && bootstrapPromptTemplate.trim().length > 0 ? renderTemplate(bootstrapPromptTemplate, templateData).trim() : ""; - const wakePrompt = renderTaskcoreWakePrompt(context.taskcoreWake, { resumedSession: Boolean(sessionId) }); - const shouldUseResumeDeltaPrompt = Boolean(sessionId) && wakePrompt.length > 0; - const renderedPrompt = shouldUseResumeDeltaPrompt ? "" : renderTemplate(promptTemplate, templateData); - const sessionHandoffNote = asString(context.taskcoreSessionHandoffMarkdown, "").trim(); - const prompt = joinPromptSections([ - renderedBootstrapPrompt, - wakePrompt, - sessionHandoffNote, - renderedPrompt - ]); - const promptMetrics = { - promptChars: prompt.length, - bootstrapPromptChars: renderedBootstrapPrompt.length, - wakePromptChars: wakePrompt.length, - sessionHandoffChars: sessionHandoffNote.length, - heartbeatPromptChars: renderedPrompt.length - }; - const buildClaudeArgs = (resumeSessionId, attemptInstructionsFilePath) => { - const args = ["--print", "-", "--output-format", "stream-json", "--verbose"]; - if (resumeSessionId) args.push("--resume", resumeSessionId); - if (dangerouslySkipPermissions) args.push("--dangerously-skip-permissions"); - if (chrome) args.push("--chrome"); - if (model && (!isBedrockAuth(effectiveEnv) || isBedrockModelId(model))) { - args.push("--model", model); - } - if (effort) args.push("--effort", effort); - if (maxTurns > 0) args.push("--max-turns", String(maxTurns)); - if (attemptInstructionsFilePath && !resumeSessionId) { - args.push("--append-system-prompt-file", attemptInstructionsFilePath); - } - args.push("--add-dir", promptBundle.addDir); - if (extraArgs.length > 0) args.push(...extraArgs); - return args; - }; - const parseFallbackErrorMessage = (proc) => { - const stderrLine = proc.stderr.split(/\r?\n/).map((line3) => line3.trim()).find(Boolean) ?? ""; - if ((proc.exitCode ?? 0) === 0) { - return "Failed to parse claude JSON output"; - } - return stderrLine ? `Claude exited with code ${proc.exitCode ?? -1}: ${stderrLine}` : `Claude exited with code ${proc.exitCode ?? -1}`; - }; - const runAttempt = async (resumeSessionId) => { - const attemptInstructionsFilePath = resumeSessionId ? void 0 : effectiveInstructionsFilePath; - const args = buildClaudeArgs(resumeSessionId, attemptInstructionsFilePath); - const commandNotes = []; - if (!resumeSessionId) { - commandNotes.push(`Using stable Claude prompt bundle ${promptBundle.bundleKey}.`); - } - if (attemptInstructionsFilePath && !resumeSessionId) { - commandNotes.push( - `Injected agent instructions via --append-system-prompt-file ${instructionsFilePath} (with path directive appended)` - ); - } - if (onMeta) { - await onMeta({ - adapterType: "claude_local", - command: resolvedCommand, - cwd, - commandArgs: args, - commandNotes, - env: loggedEnv, - prompt, - promptMetrics, - context - }); - } - const proc = await runChildProcess(runId, command, args, { - cwd, - env: env2, - stdin: prompt, - timeoutSec, - graceSec, - onSpawn, - onLog - }); - const parsedStream = parseClaudeStreamJson(proc.stdout); - const parsed = parsedStream.resultJson ?? parseJson2(proc.stdout); - return { proc, parsedStream, parsed }; - }; - const toAdapterResult = (attempt, opts) => { - const { proc, parsedStream, parsed } = attempt; - const loginMeta = detectClaudeLoginRequired({ - parsed, - stdout: proc.stdout, - stderr: proc.stderr - }); - const errorMeta = loginMeta.loginUrl != null ? { - loginUrl: loginMeta.loginUrl - } : void 0; - if (proc.timedOut) { - return { - exitCode: proc.exitCode, - signal: proc.signal, - timedOut: true, - errorMessage: `Timed out after ${timeoutSec}s`, - errorCode: "timeout", - errorMeta, - clearSession: Boolean(opts.clearSessionOnMissingSession) - }; - } - if (!parsed) { - return { - exitCode: proc.exitCode, - signal: proc.signal, - timedOut: false, - errorMessage: parseFallbackErrorMessage(proc), - errorCode: loginMeta.requiresLogin ? "claude_auth_required" : null, - errorMeta, - resultJson: { - stdout: proc.stdout, - stderr: proc.stderr - }, - clearSession: Boolean(opts.clearSessionOnMissingSession) - }; - } - const usage = parsedStream.usage ?? (() => { - const usageObj = parseObject(parsed.usage); - return { - inputTokens: asNumber(usageObj.input_tokens, 0), - cachedInputTokens: asNumber(usageObj.cache_read_input_tokens, 0), - outputTokens: asNumber(usageObj.output_tokens, 0) - }; - })(); - const resolvedSessionId = parsedStream.sessionId ?? (asString(parsed.session_id, opts.fallbackSessionId ?? "") || opts.fallbackSessionId); - const resolvedSessionParams = resolvedSessionId ? { - sessionId: resolvedSessionId, - cwd, - promptBundleKey: promptBundle.bundleKey, - ...workspaceId ? { workspaceId } : {}, - ...workspaceRepoUrl ? { repoUrl: workspaceRepoUrl } : {}, - ...workspaceRepoRef ? { repoRef: workspaceRepoRef } : {} - } : null; - const clearSessionForMaxTurns = isClaudeMaxTurnsResult(parsed); - return { - exitCode: proc.exitCode, - signal: proc.signal, - timedOut: false, - errorMessage: (proc.exitCode ?? 0) === 0 ? null : describeClaudeFailure(parsed) ?? `Claude exited with code ${proc.exitCode ?? -1}`, - errorCode: loginMeta.requiresLogin ? "claude_auth_required" : null, - errorMeta, - usage, - sessionId: resolvedSessionId, - sessionParams: resolvedSessionParams, - sessionDisplayId: resolvedSessionId, - provider: "anthropic", - biller: isBedrockAuth(effectiveEnv) ? "aws_bedrock" : "anthropic", - model: parsedStream.model || asString(parsed.model, model), - billingType, - costUsd: parsedStream.costUsd ?? asNumber(parsed.total_cost_usd, 0), - resultJson: parsed, - summary: parsedStream.summary || asString(parsed.result, ""), - clearSession: clearSessionForMaxTurns || Boolean(opts.clearSessionOnMissingSession && !resolvedSessionId) - }; - }; - const initial = await runAttempt(sessionId ?? null); - if (sessionId && !initial.proc.timedOut && (initial.proc.exitCode ?? 0) !== 0 && initial.parsed && isClaudeUnknownSessionError(initial.parsed)) { - await onLog( - "stdout", - `[taskcore] Claude resume session "${sessionId}" is unavailable; retrying with a fresh session. -` - ); - const retry = await runAttempt(null); - return toAdapterResult(retry, { fallbackSessionId: null, clearSessionOnMissingSession: true }); - } - return toAdapterResult(initial, { fallbackSessionId: runtimeSessionId || runtime.sessionId }); -} - -// packages/adapters/claude-local/src/server/test.ts -import path8 from "node:path"; -function summarizeStatus(checks) { - if (checks.some((check3) => check3.level === "error")) return "fail"; - if (checks.some((check3) => check3.level === "warn")) return "warn"; - return "pass"; -} -function isNonEmpty(value) { - return typeof value === "string" && value.trim().length > 0; -} -function firstNonEmptyLine(text3) { - return text3.split(/\r?\n/).map((line3) => line3.trim()).find(Boolean) ?? ""; -} -function commandLooksLike(command, expected) { - const base = path8.basename(command).toLowerCase(); - return base === expected || base === `${expected}.cmd` || base === `${expected}.exe`; -} -function summarizeProbeDetail(stdout, stderr) { - const raw = firstNonEmptyLine(stderr) || firstNonEmptyLine(stdout); - if (!raw) return null; - const clean3 = raw.replace(/\s+/g, " ").trim(); - const max = 240; - return clean3.length > max ? `${clean3.slice(0, max - 1)}\u2026` : clean3; -} -async function testEnvironment(ctx) { - const checks = []; - const config3 = parseObject(ctx.config); - const command = asString(config3.command, "claude"); - const cwd = asString(config3.cwd, process.cwd()); - try { - await ensureAbsoluteDirectory(cwd, { createIfMissing: true }); - checks.push({ - code: "claude_cwd_valid", - level: "info", - message: `Working directory is valid: ${cwd}` - }); - } catch (err) { - checks.push({ - code: "claude_cwd_invalid", - level: "error", - message: err instanceof Error ? err.message : "Invalid working directory", - detail: cwd - }); - } - const envConfig = parseObject(config3.env); - const env2 = {}; - for (const [key, value] of Object.entries(envConfig)) { - if (typeof value === "string") env2[key] = value; - } - const runtimeEnv = ensurePathInEnv({ ...process.env, ...env2 }); - try { - await ensureCommandResolvable(command, cwd, runtimeEnv); - checks.push({ - code: "claude_command_resolvable", - level: "info", - message: `Command is executable: ${command}` - }); - } catch (err) { - checks.push({ - code: "claude_command_unresolvable", - level: "error", - message: err instanceof Error ? err.message : "Command is not executable", - detail: command - }); - } - const hasBedrock = env2.CLAUDE_CODE_USE_BEDROCK === "1" || env2.CLAUDE_CODE_USE_BEDROCK === "true" || process.env.CLAUDE_CODE_USE_BEDROCK === "1" || process.env.CLAUDE_CODE_USE_BEDROCK === "true" || isNonEmpty(env2.ANTHROPIC_BEDROCK_BASE_URL) || isNonEmpty(process.env.ANTHROPIC_BEDROCK_BASE_URL); - const configApiKey = env2.ANTHROPIC_API_KEY; - const hostApiKey = process.env.ANTHROPIC_API_KEY; - if (hasBedrock) { - const source = env2.CLAUDE_CODE_USE_BEDROCK === "1" || env2.CLAUDE_CODE_USE_BEDROCK === "true" || isNonEmpty(env2.ANTHROPIC_BEDROCK_BASE_URL) ? "adapter config env" : "server environment"; - checks.push({ - code: "claude_bedrock_auth", - level: "info", - message: "AWS Bedrock auth detected. Claude will use Bedrock for inference.", - detail: `Detected in ${source}.`, - hint: "Ensure AWS credentials (AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY or AWS_PROFILE) and AWS_REGION are configured." - }); - } else if (isNonEmpty(configApiKey) || isNonEmpty(hostApiKey)) { - const source = isNonEmpty(configApiKey) ? "adapter config env" : "server environment"; - checks.push({ - code: "claude_anthropic_api_key_overrides_subscription", - level: "warn", - message: "ANTHROPIC_API_KEY is set. Claude will use API-key auth instead of subscription credentials.", - detail: `Detected in ${source}.`, - hint: "Unset ANTHROPIC_API_KEY if you want subscription-based Claude login behavior." - }); - } else { - checks.push({ - code: "claude_subscription_mode_possible", - level: "info", - message: "ANTHROPIC_API_KEY is not set; subscription-based auth can be used if Claude is logged in." - }); - } - const canRunProbe = checks.every((check3) => check3.code !== "claude_cwd_invalid" && check3.code !== "claude_command_unresolvable"); - if (canRunProbe) { - if (!commandLooksLike(command, "claude")) { - checks.push({ - code: "claude_hello_probe_skipped_custom_command", - level: "info", - message: "Skipped hello probe because command is not `claude`.", - detail: command, - hint: "Use the `claude` CLI command to run the automatic login and installation probe." - }); - } else { - const model = asString(config3.model, "").trim(); - const effort = asString(config3.effort, "").trim(); - const chrome = asBoolean(config3.chrome, false); - const maxTurns = asNumber(config3.maxTurnsPerRun, 0); - const dangerouslySkipPermissions = asBoolean(config3.dangerouslySkipPermissions, true); - const extraArgs = (() => { - const fromExtraArgs = asStringArray(config3.extraArgs); - if (fromExtraArgs.length > 0) return fromExtraArgs; - return asStringArray(config3.args); - })(); - const args = ["--print", "-", "--output-format", "stream-json", "--verbose"]; - if (dangerouslySkipPermissions) args.push("--dangerously-skip-permissions"); - if (chrome) args.push("--chrome"); - if (model && (!hasBedrock || isBedrockModelId(model))) { - args.push("--model", model); - } - if (effort) args.push("--effort", effort); - if (maxTurns > 0) args.push("--max-turns", String(maxTurns)); - if (extraArgs.length > 0) args.push(...extraArgs); - const probe = await runChildProcess( - `claude-envtest-${Date.now()}-${Math.random().toString(16).slice(2)}`, - command, - args, - { - cwd, - env: env2, - timeoutSec: 45, - graceSec: 5, - stdin: "Respond with hello.", - onLog: async () => { - } - } - ); - const parsedStream = parseClaudeStreamJson(probe.stdout); - const parsed = parsedStream.resultJson; - const loginMeta = detectClaudeLoginRequired({ - parsed, - stdout: probe.stdout, - stderr: probe.stderr - }); - const detail = summarizeProbeDetail(probe.stdout, probe.stderr); - if (probe.timedOut) { - checks.push({ - code: "claude_hello_probe_timed_out", - level: "warn", - message: "Claude hello probe timed out.", - hint: "Retry the probe. If this persists, verify Claude can run `Respond with hello` from this directory manually." - }); - } else if (loginMeta.requiresLogin) { - checks.push({ - code: "claude_hello_probe_auth_required", - level: "warn", - message: "Claude CLI is installed, but login is required.", - ...detail ? { detail } : {}, - hint: loginMeta.loginUrl ? `Run \`claude login\` and complete sign-in at ${loginMeta.loginUrl}, then retry.` : "Run `claude login` in this environment, then retry the probe." - }); - } else if ((probe.exitCode ?? 1) === 0) { - const summary = parsedStream.summary.trim(); - const hasHello = /\bhello\b/i.test(summary); - checks.push({ - code: hasHello ? "claude_hello_probe_passed" : "claude_hello_probe_unexpected_output", - level: hasHello ? "info" : "warn", - message: hasHello ? "Claude hello probe succeeded." : "Claude probe ran but did not return `hello` as expected.", - ...summary ? { detail: summary.replace(/\s+/g, " ").trim().slice(0, 240) } : {}, - ...hasHello ? {} : { - hint: "Try the probe manually (`claude --print - --output-format stream-json --verbose`) and prompt `Respond with hello`." - } - }); - } else { - checks.push({ - code: "claude_hello_probe_failed", - level: "error", - message: "Claude hello probe failed.", - ...detail ? { detail } : {}, - hint: "Run `claude --print - --output-format stream-json --verbose` manually in this directory and prompt `Respond with hello` to debug." - }); - } - } - } - return { - adapterType: ctx.adapterType, - status: summarizeStatus(checks), - checks, - testedAt: (/* @__PURE__ */ new Date()).toISOString() - }; -} - -// packages/adapters/claude-local/src/server/quota.ts -import { execFile } from "node:child_process"; -import fs7 from "node:fs/promises"; -import os5 from "node:os"; -import path9 from "node:path"; -import { promisify } from "node:util"; -var execFileAsync = promisify(execFile); -var CLAUDE_USAGE_SOURCE_OAUTH = "anthropic-oauth"; -var CLAUDE_USAGE_SOURCE_CLI = "claude-cli"; -function claudeConfigDir() { - const fromEnv = process.env.CLAUDE_CONFIG_DIR; - if (typeof fromEnv === "string" && fromEnv.trim().length > 0) return fromEnv.trim(); - return path9.join(os5.homedir(), ".claude"); -} -function hasNonEmptyProcessEnv(key) { - const value = process.env[key]; - return typeof value === "string" && value.trim().length > 0; -} -function createClaudeQuotaEnv() { - const env2 = {}; - for (const [key, value] of Object.entries(process.env)) { - if (typeof value !== "string") continue; - if (key.startsWith("ANTHROPIC_")) continue; - env2[key] = value; - } - return env2; -} -function stripBackspaces(text3) { - let out = ""; - for (const char2 of text3) { - if (char2 === "\b") { - out = out.slice(0, -1); - } else { - out += char2; - } - } - return out; -} -function stripAnsi(text3) { - return text3.replace(/\u001B\][^\u0007]*(?:\u0007|\u001B\\)/g, "").replace(/\u001B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g, ""); -} -function cleanTerminalText(text3) { - return stripAnsi(stripBackspaces(text3)).replace(/\u0000/g, "").replace(/\r/g, "\n"); -} -function normalizeForLabelSearch(text3) { - return text3.toLowerCase().replace(/[^a-z0-9]+/g, ""); -} -function trimToLatestUsagePanel(text3) { - const lower = text3.toLowerCase(); - const settingsIndex = lower.lastIndexOf("settings:"); - if (settingsIndex < 0) return null; - let tail = text3.slice(settingsIndex); - const tailLower = tail.toLowerCase(); - if (!tailLower.includes("usage")) return null; - if (!tailLower.includes("current session") && !tailLower.includes("loading usage")) return null; - const stopMarkers = [ - "status dialog dismissed", - "checking for updates", - "press ctrl-c again to exit" - ]; - let stopIndex = -1; - for (const marker of stopMarkers) { - const markerIndex = tailLower.indexOf(marker); - if (markerIndex >= 0 && (stopIndex === -1 || markerIndex < stopIndex)) { - stopIndex = markerIndex; - } - } - if (stopIndex >= 0) { - tail = tail.slice(0, stopIndex); - } - return tail; -} -async function readClaudeTokenFromFile(credPath) { - let raw; - try { - raw = await fs7.readFile(credPath, "utf8"); - } catch { - return null; - } - let parsed; - try { - parsed = JSON.parse(raw); - } catch { - return null; - } - if (typeof parsed !== "object" || parsed === null) return null; - const obj = parsed; - const oauth = obj["claudeAiOauth"]; - if (typeof oauth !== "object" || oauth === null) return null; - const token = oauth["accessToken"]; - return typeof token === "string" && token.length > 0 ? token : null; -} -async function readClaudeAuthStatus() { - try { - const { stdout } = await execFileAsync("claude", ["auth", "status"], { - env: process.env, - timeout: 5e3, - maxBuffer: 1024 * 1024 - }); - const parsed = JSON.parse(stdout); - return { - loggedIn: parsed.loggedIn === true, - authMethod: typeof parsed.authMethod === "string" ? parsed.authMethod : null, - subscriptionType: typeof parsed.subscriptionType === "string" ? parsed.subscriptionType : null - }; - } catch { - return null; - } -} -function describeClaudeSubscriptionAuth(status) { - if (!status?.loggedIn || status.authMethod !== "claude.ai") return null; - return status.subscriptionType ? `Claude is logged in via claude.ai (${status.subscriptionType})` : "Claude is logged in via claude.ai"; -} -async function readClaudeToken() { - const configDir = claudeConfigDir(); - for (const filename of [".credentials.json", "credentials.json"]) { - const token = await readClaudeTokenFromFile(path9.join(configDir, filename)); - if (token) return token; - } - return null; -} -function formatCurrencyAmount(value, currency) { - const code = typeof currency === "string" && currency.trim().length > 0 ? currency.trim().toUpperCase() : "USD"; - return new Intl.NumberFormat("en-US", { - style: "currency", - currency: code, - maximumFractionDigits: 2 - }).format(value); -} -function formatExtraUsageLabel(extraUsage) { - const monthlyLimit = extraUsage.monthly_limit; - const usedCredits = extraUsage.used_credits; - if (typeof monthlyLimit !== "number" || !Number.isFinite(monthlyLimit) || typeof usedCredits !== "number" || !Number.isFinite(usedCredits)) { - return null; - } - return `${formatCurrencyAmount(usedCredits, extraUsage.currency)} / ${formatCurrencyAmount(monthlyLimit, extraUsage.currency)}`; -} -function toPercent(utilization) { - if (utilization == null) return null; - return Math.min(100, Math.round(utilization * 100)); -} -async function fetchWithTimeout(url2, init2, ms = 8e3) { - const controller = new AbortController(); - const timer2 = setTimeout(() => controller.abort(), ms); - try { - return await fetch(url2, { ...init2, signal: controller.signal }); - } finally { - clearTimeout(timer2); - } -} -async function fetchClaudeQuota(token) { - const resp = await fetchWithTimeout("https://api.anthropic.com/api/oauth/usage", { - headers: { - Authorization: `Bearer ${token}`, - "anthropic-beta": "oauth-2025-04-20" - } - }); - if (!resp.ok) throw new Error(`anthropic usage api returned ${resp.status}`); - const body = await resp.json(); - const windows = []; - if (body.five_hour != null) { - windows.push({ - label: "Current session", - usedPercent: toPercent(body.five_hour.utilization), - resetsAt: body.five_hour.resets_at ?? null, - valueLabel: null, - detail: null - }); - } - if (body.seven_day != null) { - windows.push({ - label: "Current week (all models)", - usedPercent: toPercent(body.seven_day.utilization), - resetsAt: body.seven_day.resets_at ?? null, - valueLabel: null, - detail: null - }); - } - if (body.seven_day_sonnet != null) { - windows.push({ - label: "Current week (Sonnet only)", - usedPercent: toPercent(body.seven_day_sonnet.utilization), - resetsAt: body.seven_day_sonnet.resets_at ?? null, - valueLabel: null, - detail: null - }); - } - if (body.seven_day_opus != null) { - windows.push({ - label: "Current week (Opus only)", - usedPercent: toPercent(body.seven_day_opus.utilization), - resetsAt: body.seven_day_opus.resets_at ?? null, - valueLabel: null, - detail: null - }); - } - if (body.extra_usage != null) { - windows.push({ - label: "Extra usage", - usedPercent: body.extra_usage.is_enabled === false ? null : toPercent(body.extra_usage.utilization), - resetsAt: null, - valueLabel: body.extra_usage.is_enabled === false ? "Not enabled" : formatExtraUsageLabel(body.extra_usage), - detail: body.extra_usage.is_enabled === false ? "Extra usage not enabled" : "Monthly extra usage pool" - }); - } - return windows; -} -function usageOutputLooksRelevant(text3) { - const normalized = normalizeForLabelSearch(text3); - return normalized.includes("currentsession") || normalized.includes("currentweek") || normalized.includes("loadingusage") || normalized.includes("failedtoloadusagedata") || normalized.includes("tokenexpired") || normalized.includes("authenticationerror") || normalized.includes("ratelimited"); -} -function usageOutputLooksComplete(text3) { - const normalized = normalizeForLabelSearch(text3); - if (normalized.includes("failedtoloadusagedata") || normalized.includes("tokenexpired") || normalized.includes("authenticationerror") || normalized.includes("ratelimited")) { - return true; - } - return normalized.includes("currentsession") && (normalized.includes("currentweek") || normalized.includes("extrausage")) && /[0-9]{1,3}(?:\.[0-9]+)?%/i.test(text3); -} -function extractUsageError(text3) { - const lower = text3.toLowerCase(); - const compact = lower.replace(/\s+/g, ""); - if (lower.includes("token_expired") || lower.includes("token has expired")) { - return "Claude CLI token expired. Run `claude login` to refresh."; - } - if (lower.includes("authentication_error")) { - return "Claude CLI authentication error. Run `claude login`."; - } - if (lower.includes("rate_limit_error") || lower.includes("rate limited") || compact.includes("ratelimited")) { - return "Claude CLI usage endpoint is rate limited right now. Please try again later."; - } - if (lower.includes("failed to load usage data") || compact.includes("failedtoloadusagedata")) { - return "Claude CLI could not load usage data. Open the CLI and retry `/usage`."; - } - return null; -} -function percentFromLine(line3) { - const match = line3.match(/([0-9]{1,3}(?:\.[0-9]+)?)\s*%/i); - if (!match) return null; - const rawValue = Number(match[1]); - if (!Number.isFinite(rawValue)) return null; - const clamped = Math.min(100, Math.max(0, rawValue)); - const lower = line3.toLowerCase(); - if (lower.includes("remaining") || lower.includes("left") || lower.includes("available")) { - return Math.max(0, Math.min(100, Math.round(100 - clamped))); - } - return Math.round(clamped); -} -function isQuotaLabel(line3) { - const normalized = normalizeForLabelSearch(line3); - return normalized === "currentsession" || normalized === "currentweekallmodels" || normalized === "currentweeksonnetonly" || normalized === "currentweeksonnet" || normalized === "currentweekopusonly" || normalized === "currentweekopus" || normalized === "extrausage"; -} -function canonicalQuotaLabel(line3) { - switch (normalizeForLabelSearch(line3)) { - case "currentsession": - return "Current session"; - case "currentweekallmodels": - return "Current week (all models)"; - case "currentweeksonnetonly": - case "currentweeksonnet": - return "Current week (Sonnet only)"; - case "currentweekopusonly": - case "currentweekopus": - return "Current week (Opus only)"; - case "extrausage": - return "Extra usage"; - default: - return line3; - } -} -function formatClaudeCliDetail(label, lines) { - const normalizedLabel = normalizeForLabelSearch(label); - if (normalizedLabel === "extrausage") { - const compact = lines.join(" ").replace(/\s+/g, "").toLowerCase(); - if (compact.includes("extrausagenotenabled")) { - return "Extra usage not enabled \u2022 /extra-usage to enable"; - } - const firstLine = lines.find((line3) => line3.trim().length > 0) ?? null; - return firstLine; - } - const resetLine = lines.find((line3) => /^resets/i.test(line3) || normalizeForLabelSearch(line3).startsWith("resets")); - if (!resetLine) return null; - return resetLine.replace(/^Resets/i, "Resets ").replace(/([A-Z][a-z]{2})(\d)/g, "$1 $2").replace(/(\d)at(\d)/g, "$1 at $2").replace(/(am|pm)\(/gi, "$1 (").replace(/([A-Za-z])\(/g, "$1 (").replace(/\s+/g, " ").trim(); -} -function parseClaudeCliUsageText(text3) { - const cleaned = trimToLatestUsagePanel(cleanTerminalText(text3)) ?? cleanTerminalText(text3); - const usageError = extractUsageError(cleaned); - if (usageError) throw new Error(usageError); - const lines = cleaned.split("\n").map((line3) => line3.trim()).filter((line3) => line3.length > 0); - const sections = []; - let current = null; - for (const line3 of lines) { - if (isQuotaLabel(line3)) { - if (current) sections.push(current); - current = { label: canonicalQuotaLabel(line3), lines: [] }; - continue; - } - if (current) current.lines.push(line3); - } - if (current) sections.push(current); - const windows = sections.map((section) => { - const usedPercent = section.lines.map(percentFromLine).find((value) => value != null) ?? null; - return { - label: section.label, - usedPercent, - resetsAt: null, - valueLabel: null, - detail: formatClaudeCliDetail(section.label, section.lines) - }; - }); - if (!windows.some((window2) => normalizeForLabelSearch(window2.label) === "currentsession")) { - throw new Error("Could not parse Claude CLI usage output."); - } - return windows; -} -function quoteForShell(value) { - return `'${value.replace(/'/g, `'\\''`)}'`; -} -function buildClaudeCliShellProbeCommand() { - const feed = "(sleep 2; printf '/usage\\r'; sleep 6; printf '\\033'; sleep 1; printf '\\003')"; - const claudeCommand = 'claude --tools ""'; - if (process.platform === "darwin") { - return `${feed} | script -q /dev/null ${claudeCommand}`; - } - return `${feed} | script -q -e -f -c ${quoteForShell(claudeCommand)} /dev/null`; -} -async function captureClaudeCliUsageText(timeoutMs = 12e3) { - const command = buildClaudeCliShellProbeCommand(); - try { - const { stdout, stderr } = await execFileAsync("sh", ["-c", command], { - env: createClaudeQuotaEnv(), - timeout: timeoutMs, - maxBuffer: 8 * 1024 * 1024 - }); - const output = `${stdout}${stderr}`; - const cleaned = cleanTerminalText(output); - if (usageOutputLooksComplete(cleaned)) return output; - throw new Error("Claude CLI usage probe ended before rendering usage."); - } catch (error50) { - const stdout = typeof error50 === "object" && error50 !== null && "stdout" in error50 && typeof error50.stdout === "string" ? error50.stdout : ""; - const stderr = typeof error50 === "object" && error50 !== null && "stderr" in error50 && typeof error50.stderr === "string" ? error50.stderr : ""; - const output = `${stdout}${stderr}`; - const cleaned = cleanTerminalText(output); - if (usageOutputLooksComplete(cleaned)) return output; - if (usageOutputLooksRelevant(cleaned)) { - throw new Error("Claude CLI usage probe ended before rendering usage."); - } - throw error50 instanceof Error ? error50 : new Error(String(error50)); - } -} -async function fetchClaudeCliQuota() { - const rawText = await captureClaudeCliUsageText(); - return parseClaudeCliUsageText(rawText); -} -function formatProviderError(source, error50) { - const message2 = error50 instanceof Error ? error50.message : String(error50); - return `${source}: ${message2}`; -} -async function getQuotaWindows() { - if (process.env.CLAUDE_CODE_USE_BEDROCK === "1" || process.env.CLAUDE_CODE_USE_BEDROCK === "true" || hasNonEmptyProcessEnv("ANTHROPIC_BEDROCK_BASE_URL")) { - return { provider: "anthropic", source: "bedrock", ok: true, windows: [] }; - } - const authStatus = await readClaudeAuthStatus(); - const authDescription = describeClaudeSubscriptionAuth(authStatus); - const token = await readClaudeToken(); - const errors = []; - if (token) { - try { - const windows = await fetchClaudeQuota(token); - return { provider: "anthropic", source: CLAUDE_USAGE_SOURCE_OAUTH, ok: true, windows }; - } catch (error50) { - errors.push(formatProviderError("Anthropic OAuth usage", error50)); - } - } - try { - const windows = await fetchClaudeCliQuota(); - return { provider: "anthropic", source: CLAUDE_USAGE_SOURCE_CLI, ok: true, windows }; - } catch (error50) { - errors.push(formatProviderError("Claude CLI /usage", error50)); - } - if (hasNonEmptyProcessEnv("ANTHROPIC_API_KEY") && !authDescription) { - return { - provider: "anthropic", - ok: false, - error: errors[0] ?? "ANTHROPIC_API_KEY is set and no local Claude subscription session is available for quota polling", - windows: [] - }; - } - if (authDescription) { - return { - provider: "anthropic", - ok: false, - error: errors.length > 0 ? `${authDescription}, but quota polling failed (${errors.join("; ")})` : `${authDescription}, but Taskcore could not load subscription quota data`, - windows: [] - }; - } - return { - provider: "anthropic", - ok: false, - error: errors[0] ?? "no local claude auth token", - windows: [] - }; -} - -// packages/adapters/claude-local/src/server/index.ts -function readNonEmptyString2(value) { - return typeof value === "string" && value.trim().length > 0 ? value.trim() : null; -} -var sessionCodec = { - deserialize(raw) { - if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return null; - const record2 = raw; - const sessionId = readNonEmptyString2(record2.sessionId) ?? readNonEmptyString2(record2.session_id); - if (!sessionId) return null; - const cwd = readNonEmptyString2(record2.cwd) ?? readNonEmptyString2(record2.workdir) ?? readNonEmptyString2(record2.folder); - const promptBundleKey = readNonEmptyString2(record2.promptBundleKey) ?? readNonEmptyString2(record2.prompt_bundle_key); - const workspaceId = readNonEmptyString2(record2.workspaceId) ?? readNonEmptyString2(record2.workspace_id); - const repoUrl = readNonEmptyString2(record2.repoUrl) ?? readNonEmptyString2(record2.repo_url); - const repoRef = readNonEmptyString2(record2.repoRef) ?? readNonEmptyString2(record2.repo_ref); - return { - sessionId, - ...cwd ? { cwd } : {}, - ...promptBundleKey ? { promptBundleKey } : {}, - ...workspaceId ? { workspaceId } : {}, - ...repoUrl ? { repoUrl } : {}, - ...repoRef ? { repoRef } : {} - }; - }, - serialize(params) { - if (!params) return null; - const sessionId = readNonEmptyString2(params.sessionId) ?? readNonEmptyString2(params.session_id); - if (!sessionId) return null; - const cwd = readNonEmptyString2(params.cwd) ?? readNonEmptyString2(params.workdir) ?? readNonEmptyString2(params.folder); - const promptBundleKey = readNonEmptyString2(params.promptBundleKey) ?? readNonEmptyString2(params.prompt_bundle_key); - const workspaceId = readNonEmptyString2(params.workspaceId) ?? readNonEmptyString2(params.workspace_id); - const repoUrl = readNonEmptyString2(params.repoUrl) ?? readNonEmptyString2(params.repo_url); - const repoRef = readNonEmptyString2(params.repoRef) ?? readNonEmptyString2(params.repo_ref); - return { - sessionId, - ...cwd ? { cwd } : {}, - ...promptBundleKey ? { promptBundleKey } : {}, - ...workspaceId ? { workspaceId } : {}, - ...repoUrl ? { repoUrl } : {}, - ...repoRef ? { repoRef } : {} - }; - }, - getDisplayId(params) { - if (!params) return null; - return readNonEmptyString2(params.sessionId) ?? readNonEmptyString2(params.session_id); - } -}; - -// packages/adapters/codex-local/src/server/execute.ts -import fs9 from "node:fs/promises"; -import path12 from "node:path"; -import { fileURLToPath as fileURLToPath5 } from "node:url"; - -// packages/adapter-utils/src/session-compaction.ts -var DEFAULT_SESSION_COMPACTION_POLICY = { - enabled: true, - maxSessionRuns: 200, - maxRawInputTokens: 2e6, - maxSessionAgeHours: 72 -}; -var ADAPTER_MANAGED_SESSION_POLICY = { - enabled: true, - maxSessionRuns: 0, - maxRawInputTokens: 0, - maxSessionAgeHours: 0 -}; -var LEGACY_SESSIONED_ADAPTER_TYPES = /* @__PURE__ */ new Set([ - "claude_local", - "codex_local", - "cursor", - "gemini_local", - "hermes_local", - "opencode_local", - "pi_local" -]); -var ADAPTER_SESSION_MANAGEMENT = { - claude_local: { - supportsSessionResume: true, - nativeContextManagement: "confirmed", - defaultSessionCompaction: ADAPTER_MANAGED_SESSION_POLICY - }, - codex_local: { - supportsSessionResume: true, - nativeContextManagement: "confirmed", - defaultSessionCompaction: ADAPTER_MANAGED_SESSION_POLICY - }, - cursor: { - supportsSessionResume: true, - nativeContextManagement: "unknown", - defaultSessionCompaction: DEFAULT_SESSION_COMPACTION_POLICY - }, - gemini_local: { - supportsSessionResume: true, - nativeContextManagement: "unknown", - defaultSessionCompaction: DEFAULT_SESSION_COMPACTION_POLICY - }, - opencode_local: { - supportsSessionResume: true, - nativeContextManagement: "unknown", - defaultSessionCompaction: DEFAULT_SESSION_COMPACTION_POLICY - }, - pi_local: { - supportsSessionResume: true, - nativeContextManagement: "unknown", - defaultSessionCompaction: DEFAULT_SESSION_COMPACTION_POLICY - }, - hermes_local: { - supportsSessionResume: true, - nativeContextManagement: "confirmed", - defaultSessionCompaction: ADAPTER_MANAGED_SESSION_POLICY - } -}; -function isRecord2(value) { - return typeof value === "object" && value !== null && !Array.isArray(value); -} -function readBoolean(value) { - if (typeof value === "boolean") return value; - if (typeof value === "number") { - if (value === 1) return true; - if (value === 0) return false; - return void 0; - } - if (typeof value !== "string") return void 0; - const normalized = value.trim().toLowerCase(); - if (normalized === "true" || normalized === "1" || normalized === "yes" || normalized === "on") { - return true; - } - if (normalized === "false" || normalized === "0" || normalized === "no" || normalized === "off") { - return false; - } - return void 0; -} -function readNumber(value) { - if (typeof value === "number" && Number.isFinite(value)) { - return Math.max(0, Math.floor(value)); - } - if (typeof value !== "string") return void 0; - const parsed = Number(value.trim()); - return Number.isFinite(parsed) ? Math.max(0, Math.floor(parsed)) : void 0; -} -function getAdapterSessionManagement(adapterType) { - if (!adapterType) return null; - return ADAPTER_SESSION_MANAGEMENT[adapterType] ?? null; -} -function readSessionCompactionOverride(runtimeConfig) { - const runtime = isRecord2(runtimeConfig) ? runtimeConfig : {}; - const heartbeat = isRecord2(runtime.heartbeat) ? runtime.heartbeat : {}; - const compaction = isRecord2( - heartbeat.sessionCompaction ?? heartbeat.sessionRotation ?? runtime.sessionCompaction - ) ? heartbeat.sessionCompaction ?? heartbeat.sessionRotation ?? runtime.sessionCompaction : {}; - const explicit = {}; - const enabled = readBoolean(compaction.enabled); - const maxSessionRuns = readNumber(compaction.maxSessionRuns); - const maxRawInputTokens = readNumber(compaction.maxRawInputTokens); - const maxSessionAgeHours = readNumber(compaction.maxSessionAgeHours); - if (enabled !== void 0) explicit.enabled = enabled; - if (maxSessionRuns !== void 0) explicit.maxSessionRuns = maxSessionRuns; - if (maxRawInputTokens !== void 0) explicit.maxRawInputTokens = maxRawInputTokens; - if (maxSessionAgeHours !== void 0) explicit.maxSessionAgeHours = maxSessionAgeHours; - return explicit; -} -function resolveSessionCompactionPolicy(adapterType, runtimeConfig) { - const adapterSessionManagement = getAdapterSessionManagement(adapterType); - const explicitOverride = readSessionCompactionOverride(runtimeConfig); - const hasExplicitOverride = Object.keys(explicitOverride).length > 0; - const fallbackEnabled = Boolean(adapterType && LEGACY_SESSIONED_ADAPTER_TYPES.has(adapterType)); - const basePolicy = adapterSessionManagement?.defaultSessionCompaction ?? { - ...DEFAULT_SESSION_COMPACTION_POLICY, - enabled: fallbackEnabled - }; - return { - policy: { - enabled: explicitOverride.enabled ?? basePolicy.enabled, - maxSessionRuns: explicitOverride.maxSessionRuns ?? basePolicy.maxSessionRuns, - maxRawInputTokens: explicitOverride.maxRawInputTokens ?? basePolicy.maxRawInputTokens, - maxSessionAgeHours: explicitOverride.maxSessionAgeHours ?? basePolicy.maxSessionAgeHours - }, - adapterSessionManagement, - explicitOverride, - source: hasExplicitOverride ? "agent_override" : adapterSessionManagement ? "adapter_default" : "legacy_fallback" - }; -} -function hasSessionCompactionThresholds(policy) { - return policy.maxSessionRuns > 0 || policy.maxRawInputTokens > 0 || policy.maxSessionAgeHours > 0; -} - -// packages/adapter-utils/src/billing.ts -function readEnv(env2, key) { - const value = env2[key]; - return typeof value === "string" && value.trim().length > 0 ? value.trim() : null; -} -function inferOpenAiCompatibleBiller(env2, fallback = "openai") { - const explicitOpenRouterKey = readEnv(env2, "OPENROUTER_API_KEY"); - if (explicitOpenRouterKey) return "openrouter"; - const baseUrl = readEnv(env2, "OPENAI_BASE_URL") ?? readEnv(env2, "OPENAI_API_BASE") ?? readEnv(env2, "OPENAI_API_BASE_URL"); - if (baseUrl && /openrouter\.ai/i.test(baseUrl)) return "openrouter"; - return fallback; -} - -// packages/adapters/codex-local/src/server/parse.ts -function parseCodexJsonl(stdout) { - let sessionId = null; - let finalMessage = null; - let errorMessage = null; - const usage = { - inputTokens: 0, - cachedInputTokens: 0, - outputTokens: 0 - }; - for (const rawLine of stdout.split(/\r?\n/)) { - const line3 = rawLine.trim(); - if (!line3) continue; - const event = parseJson2(line3); - if (!event) continue; - const type = asString(event.type, ""); - if (type === "thread.started") { - sessionId = asString(event.thread_id, sessionId ?? "") || sessionId; - continue; - } - if (type === "error") { - const msg = asString(event.message, "").trim(); - if (msg) errorMessage = msg; - continue; - } - if (type === "item.completed") { - const item = parseObject(event.item); - if (asString(item.type, "") === "agent_message") { - const text3 = asString(item.text, ""); - if (text3) finalMessage = text3; - } - continue; - } - if (type === "turn.completed") { - const usageObj = parseObject(event.usage); - usage.inputTokens = asNumber(usageObj.input_tokens, usage.inputTokens); - usage.cachedInputTokens = asNumber(usageObj.cached_input_tokens, usage.cachedInputTokens); - usage.outputTokens = asNumber(usageObj.output_tokens, usage.outputTokens); - continue; - } - if (type === "turn.failed") { - const err = parseObject(event.error); - const msg = asString(err.message, "").trim(); - if (msg) errorMessage = msg; - } - } - return { - sessionId, - summary: finalMessage?.trim() ?? "", - usage, - errorMessage - }; -} -function isCodexUnknownSessionError(stdout, stderr) { - const haystack = `${stdout} -${stderr}`.split(/\r?\n/).map((line3) => line3.trim()).filter(Boolean).join("\n"); - return /unknown (session|thread)|session .* not found|thread .* not found|conversation .* not found|missing rollout path for thread|state db missing rollout path|no rollout found for thread id/i.test( - haystack - ); -} - -// packages/adapters/codex-local/src/server/codex-home.ts -import fs8 from "node:fs/promises"; -import os6 from "node:os"; -import path10 from "node:path"; -var TRUTHY_ENV_RE = /^(1|true|yes|on)$/i; -var COPIED_SHARED_FILES = ["config.json", "config.toml", "instructions.md"]; -var SYMLINKED_SHARED_FILES = ["auth.json"]; -var DEFAULT_TASKCORE_INSTANCE_ID2 = "default"; -function nonEmpty2(value) { - return typeof value === "string" && value.trim().length > 0 ? value.trim() : null; -} -async function pathExists2(candidate) { - return fs8.access(candidate).then(() => true).catch(() => false); -} -function resolveSharedCodexHomeDir(env2 = process.env) { - const fromEnv = nonEmpty2(env2.CODEX_HOME); - return fromEnv ? path10.resolve(fromEnv) : path10.join(os6.homedir(), ".codex"); -} -function isWorktreeMode(env2) { - return TRUTHY_ENV_RE.test(env2.TASKCORE_IN_WORKTREE ?? ""); -} -function resolveManagedCodexHomeDir(env2, companyId) { - const taskcoreHome = nonEmpty2(env2.TASKCORE_HOME) ?? path10.resolve(os6.homedir(), ".taskcore"); - const instanceId = nonEmpty2(env2.TASKCORE_INSTANCE_ID) ?? DEFAULT_TASKCORE_INSTANCE_ID2; - return companyId ? path10.resolve(taskcoreHome, "instances", instanceId, "companies", companyId, "codex-home") : path10.resolve(taskcoreHome, "instances", instanceId, "codex-home"); -} -async function ensureParentDir(target) { - await fs8.mkdir(path10.dirname(target), { recursive: true }); -} -async function ensureSymlink(target, source) { - const existing = await fs8.lstat(target).catch(() => null); - if (!existing) { - await ensureParentDir(target); - await fs8.symlink(source, target); - return; - } - if (!existing.isSymbolicLink()) { - return; - } - const linkedPath = await fs8.readlink(target).catch(() => null); - if (!linkedPath) return; - const resolvedLinkedPath = path10.resolve(path10.dirname(target), linkedPath); - if (resolvedLinkedPath === source) return; - await fs8.unlink(target); - await fs8.symlink(source, target); -} -async function ensureCopiedFile(target, source) { - const existing = await fs8.lstat(target).catch(() => null); - if (existing) return; - await ensureParentDir(target); - await fs8.copyFile(source, target); -} -async function prepareManagedCodexHome(env2, onLog, companyId) { - const targetHome = resolveManagedCodexHomeDir(env2, companyId); - const sourceHome = resolveSharedCodexHomeDir(env2); - if (path10.resolve(sourceHome) === path10.resolve(targetHome)) return targetHome; - await fs8.mkdir(targetHome, { recursive: true }); - for (const name of SYMLINKED_SHARED_FILES) { - const source = path10.join(sourceHome, name); - if (!await pathExists2(source)) continue; - await ensureSymlink(path10.join(targetHome, name), source); - } - for (const name of COPIED_SHARED_FILES) { - const source = path10.join(sourceHome, name); - if (!await pathExists2(source)) continue; - await ensureCopiedFile(path10.join(targetHome, name), source); - } - await onLog( - "stdout", - `[taskcore] Using ${isWorktreeMode(env2) ? "worktree-isolated" : "Taskcore-managed"} Codex home "${targetHome}" (seeded from "${sourceHome}"). -` - ); - return targetHome; -} - -// packages/adapters/codex-local/src/server/skills.ts -import path11 from "node:path"; -import { fileURLToPath as fileURLToPath4 } from "node:url"; -var __moduleDir3 = path11.dirname(fileURLToPath4(import.meta.url)); -async function buildCodexSkillSnapshot(config3) { - const availableEntries = await readTaskcoreRuntimeSkillEntries(config3, __moduleDir3); - const availableByKey = new Map(availableEntries.map((entry) => [entry.key, entry])); - const desiredSkills = resolveTaskcoreDesiredSkillNames(config3, availableEntries); - const desiredSet = new Set(desiredSkills); - const entries2 = availableEntries.map((entry) => ({ - key: entry.key, - runtimeName: entry.runtimeName, - desired: desiredSet.has(entry.key), - managed: true, - state: desiredSet.has(entry.key) ? "configured" : "available", - origin: entry.required ? "taskcore_required" : "company_managed", - originLabel: entry.required ? "Required by Taskcore" : "Managed by Taskcore", - readOnly: false, - sourcePath: entry.source, - targetPath: null, - detail: desiredSet.has(entry.key) ? "Will be linked into the effective CODEX_HOME/skills/ directory on the next run." : null, - required: Boolean(entry.required), - requiredReason: entry.requiredReason ?? null - })); - const warnings = []; - for (const desiredSkill of desiredSkills) { - if (availableByKey.has(desiredSkill)) continue; - warnings.push(`Desired skill "${desiredSkill}" is not available from the Taskcore skills directory.`); - entries2.push({ - key: desiredSkill, - runtimeName: null, - desired: true, - managed: true, - state: "missing", - origin: "external_unknown", - originLabel: "External or unavailable", - readOnly: false, - sourcePath: null, - targetPath: null, - detail: "Taskcore cannot find this skill in the local runtime skills directory." - }); - } - entries2.sort((left, right) => left.key.localeCompare(right.key)); - return { - adapterType: "codex_local", - supported: true, - mode: "ephemeral", - desiredSkills, - entries: entries2, - warnings - }; -} -async function listCodexSkills(ctx) { - return buildCodexSkillSnapshot(ctx.config); -} -async function syncCodexSkills(ctx, _desiredSkills) { - return buildCodexSkillSnapshot(ctx.config); -} -function resolveCodexDesiredSkillNames(config3, availableEntries) { - return resolveTaskcoreDesiredSkillNames(config3, availableEntries); -} - -// packages/adapters/codex-local/src/index.ts -var DEFAULT_CODEX_LOCAL_MODEL = "gpt-5.3-codex"; -var DEFAULT_CODEX_LOCAL_BYPASS_APPROVALS_AND_SANDBOX = true; -var CODEX_LOCAL_FAST_MODE_SUPPORTED_MODELS = ["gpt-5.4"]; -function isCodexLocalFastModeSupported(model) { - const normalizedModel = typeof model === "string" ? model.trim() : ""; - return CODEX_LOCAL_FAST_MODE_SUPPORTED_MODELS.includes( - normalizedModel - ); -} -var models2 = [ - { id: "gpt-5.4", label: "gpt-5.4" }, - { id: DEFAULT_CODEX_LOCAL_MODEL, label: DEFAULT_CODEX_LOCAL_MODEL }, - { id: "gpt-5.3-codex-spark", label: "gpt-5.3-codex-spark" }, - { id: "gpt-5", label: "gpt-5" }, - { id: "o3", label: "o3" }, - { id: "o4-mini", label: "o4-mini" }, - { id: "gpt-5-mini", label: "gpt-5-mini" }, - { id: "gpt-5-nano", label: "gpt-5-nano" }, - { id: "o3-mini", label: "o3-mini" }, - { id: "codex-mini-latest", label: "Codex Mini" } -]; -var agentConfigurationDoc2 = `# codex_local agent configuration - -Adapter: codex_local - -Core fields: -- cwd (string, optional): default absolute working directory fallback for the agent process (created if missing when possible) -- instructionsFilePath (string, optional): absolute path to a markdown instructions file prepended to stdin prompt at runtime -- model (string, optional): Codex model id -- modelReasoningEffort (string, optional): reasoning effort override (minimal|low|medium|high|xhigh) passed via -c model_reasoning_effort=... -- promptTemplate (string, optional): run prompt template -- search (boolean, optional): run codex with --search -- fastMode (boolean, optional): enable Codex Fast mode; currently supported on GPT-5.4 only and consumes credits faster -- dangerouslyBypassApprovalsAndSandbox (boolean, optional): run with bypass flag -- command (string, optional): defaults to "codex" -- extraArgs (string[], optional): additional CLI args -- env (object, optional): KEY=VALUE environment variables -- workspaceStrategy (object, optional): execution workspace strategy; currently supports { type: "git_worktree", baseRef?, branchTemplate?, worktreeParentDir? } -- workspaceRuntime (object, optional): reserved for workspace runtime metadata; workspace runtime services are manually controlled from the workspace UI and are not auto-started by heartbeats - -Operational fields: -- timeoutSec (number, optional): run timeout in seconds -- graceSec (number, optional): SIGTERM grace period in seconds - -Notes: -- Prompts are piped via stdin (Codex receives "-" prompt argument). -- If instructionsFilePath is configured, Taskcore prepends that file's contents to the stdin prompt on every run. -- Codex exec automatically applies repo-scoped AGENTS.md instructions from the active workspace. Taskcore cannot suppress that discovery in exec mode, so repo AGENTS.md files may still apply even when you only configured an explicit instructionsFilePath. -- Taskcore injects desired local skills into the effective CODEX_HOME/skills/ directory at execution time so Codex can discover "$taskcore" and related skills without polluting the project working directory. In managed-home mode (the default) this is ~/.taskcore/instances//companies//codex-home/skills/; when CODEX_HOME is explicitly overridden in adapter config, that override is used instead. -- Unless explicitly overridden in adapter config, Taskcore runs Codex with a per-company managed CODEX_HOME under the active Taskcore instance and seeds auth/config from the shared Codex home (the CODEX_HOME env var, when set, or ~/.codex). -- Some model/tool combinations reject certain effort levels (for example minimal with web search enabled). -- Fast mode is currently supported on GPT-5.4 only. When enabled, Taskcore applies \`service_tier="fast"\` and \`features.fast_mode=true\`. -- When Taskcore realizes a workspace/runtime for a run, it injects TASKCORE_WORKSPACE_* and TASKCORE_RUNTIME_* env vars for agent-side tooling. -`; - -// packages/adapters/codex-local/src/server/codex-args.ts -function readExtraArgs(config3) { - const fromExtraArgs = asStringArray(asRecord(config3).extraArgs); - if (fromExtraArgs.length > 0) return fromExtraArgs; - return asStringArray(asRecord(config3).args); -} -function asRecord(value) { - return typeof value === "object" && value !== null && !Array.isArray(value) ? value : {}; -} -function formatFastModeSupportedModels() { - return CODEX_LOCAL_FAST_MODE_SUPPORTED_MODELS.join(", "); -} -function buildCodexExecArgs(config3, options = {}) { - const record2 = asRecord(config3); - const model = asString(record2.model, "").trim(); - const modelReasoningEffort = asString( - record2.modelReasoningEffort, - asString(record2.reasoningEffort, "") - ).trim(); - const search = asBoolean(record2.search, false); - const fastModeRequested = asBoolean(record2.fastMode, false); - const fastModeApplied = fastModeRequested && isCodexLocalFastModeSupported(model); - const bypass = asBoolean( - record2.dangerouslyBypassApprovalsAndSandbox, - asBoolean(record2.dangerouslyBypassSandbox, false) - ); - const extraArgs = readExtraArgs(record2); - const args = ["exec", "--json"]; - if (search) args.unshift("--search"); - if (bypass) args.push("--dangerously-bypass-approvals-and-sandbox"); - if (model) args.push("--model", model); - if (modelReasoningEffort) { - args.push("-c", `model_reasoning_effort=${JSON.stringify(modelReasoningEffort)}`); - } - if (fastModeApplied) { - args.push("-c", 'service_tier="fast"', "-c", "features.fast_mode=true"); - } - if (extraArgs.length > 0) args.push(...extraArgs); - if (options.resumeSessionId) args.push("resume", options.resumeSessionId, "-"); - else args.push("-"); - return { - args, - model, - fastModeRequested, - fastModeApplied, - fastModeIgnoredReason: fastModeRequested && !fastModeApplied ? `Configured fast mode is currently only supported on ${formatFastModeSupportedModels()}; Taskcore will ignore it for model ${model || "(default)"}.` : null - }; -} - -// packages/adapters/codex-local/src/server/execute.ts -var __moduleDir4 = path12.dirname(fileURLToPath5(import.meta.url)); -var CODEX_ROLLOUT_NOISE_RE = /^\d{4}-\d{2}-\d{2}T[^\s]+\s+ERROR\s+codex_core::rollout::list:\s+state db missing rollout path for thread\s+[a-z0-9-]+$/i; -function stripCodexRolloutNoise(text3) { - const parts = text3.split(/\r?\n/); - const kept = []; - for (const part of parts) { - const trimmed = part.trim(); - if (!trimmed) { - kept.push(part); - continue; - } - if (CODEX_ROLLOUT_NOISE_RE.test(trimmed)) continue; - kept.push(part); - } - return kept.join("\n"); -} -function firstNonEmptyLine2(text3) { - return text3.split(/\r?\n/).map((line3) => line3.trim()).find(Boolean) ?? ""; -} -function hasNonEmptyEnvValue2(env2, key) { - const raw = env2[key]; - return typeof raw === "string" && raw.trim().length > 0; -} -function resolveCodexBillingType(env2) { - return hasNonEmptyEnvValue2(env2, "OPENAI_API_KEY") ? "api" : "subscription"; -} -function resolveCodexBiller(env2, billingType) { - const openAiCompatibleBiller = inferOpenAiCompatibleBiller(env2, "openai"); - if (openAiCompatibleBiller === "openrouter") return "openrouter"; - return billingType === "subscription" ? "chatgpt" : openAiCompatibleBiller ?? "openai"; -} -async function isLikelyTaskcoreRepoRoot(candidate) { - const [hasWorkspace, hasPackageJson, hasServerDir, hasAdapterUtilsDir] = await Promise.all([ - pathExists2(path12.join(candidate, "pnpm-workspace.yaml")), - pathExists2(path12.join(candidate, "package.json")), - pathExists2(path12.join(candidate, "server")), - pathExists2(path12.join(candidate, "packages", "adapter-utils")) - ]); - return hasWorkspace && hasPackageJson && hasServerDir && hasAdapterUtilsDir; -} -async function isLikelyTaskcoreRuntimeSkillPath(candidate, skillName, options = {}) { - if (path12.basename(candidate) !== skillName) return false; - const skillsRoot = path12.dirname(candidate); - if (path12.basename(skillsRoot) !== "skills") return false; - if (options.requireSkillMarkdown !== false && !await pathExists2(path12.join(candidate, "SKILL.md"))) { - return false; - } - let cursor2 = path12.dirname(skillsRoot); - for (let depth = 0; depth < 6; depth += 1) { - if (await isLikelyTaskcoreRepoRoot(cursor2)) return true; - const parent = path12.dirname(cursor2); - if (parent === cursor2) break; - cursor2 = parent; - } - return false; -} -async function pruneBrokenUnavailableTaskcoreSkillSymlinks(skillsHome, allowedSkillNames, onLog) { - const allowed2 = new Set(Array.from(allowedSkillNames)); - const entries2 = await fs9.readdir(skillsHome, { withFileTypes: true }).catch(() => []); - for (const entry of entries2) { - if (allowed2.has(entry.name) || !entry.isSymbolicLink()) continue; - const target = path12.join(skillsHome, entry.name); - const linkedPath = await fs9.readlink(target).catch(() => null); - if (!linkedPath) continue; - const resolvedLinkedPath = path12.resolve(path12.dirname(target), linkedPath); - if (await pathExists2(resolvedLinkedPath)) continue; - if (!await isLikelyTaskcoreRuntimeSkillPath(resolvedLinkedPath, entry.name, { - requireSkillMarkdown: false - })) { - continue; - } - await fs9.unlink(target).catch(() => { - }); - await onLog( - "stdout", - `[taskcore] Removed stale Codex skill "${entry.name}" from ${skillsHome} -` - ); - } -} -function resolveCodexSkillsDir(codexHome) { - return path12.join(codexHome, "skills"); -} -async function ensureCodexSkillsInjected(onLog, options = {}) { - const allSkillsEntries = options.skillsEntries ?? await readTaskcoreRuntimeSkillEntries({}, __moduleDir4); - const desiredSkillNames = options.desiredSkillNames ?? allSkillsEntries.map((entry) => entry.key); - const desiredSet = new Set(desiredSkillNames); - const skillsEntries = allSkillsEntries.filter((entry) => desiredSet.has(entry.key)); - if (skillsEntries.length === 0) return; - const skillsHome = options.skillsHome ?? resolveCodexSkillsDir(resolveSharedCodexHomeDir()); - await fs9.mkdir(skillsHome, { recursive: true }); - const linkSkill = options.linkSkill; - for (const entry of skillsEntries) { - const target = path12.join(skillsHome, entry.runtimeName); - try { - const existing = await fs9.lstat(target).catch(() => null); - if (existing?.isSymbolicLink()) { - const linkedPath = await fs9.readlink(target).catch(() => null); - const resolvedLinkedPath = linkedPath ? path12.resolve(path12.dirname(target), linkedPath) : null; - if (resolvedLinkedPath && resolvedLinkedPath !== entry.source && await isLikelyTaskcoreRuntimeSkillPath(resolvedLinkedPath, entry.runtimeName)) { - await fs9.unlink(target); - if (linkSkill) { - await linkSkill(entry.source, target); - } else { - await fs9.symlink(entry.source, target); - } - await onLog( - "stdout", - `[taskcore] Repaired Codex skill "${entry.runtimeName}" into ${skillsHome} -` - ); - continue; - } - } - const result = await ensureTaskcoreSkillSymlink(entry.source, target, linkSkill); - if (result === "skipped") continue; - await onLog( - "stdout", - `[taskcore] ${result === "repaired" ? "Repaired" : "Injected"} Codex skill "${entry.runtimeName}" into ${skillsHome} -` - ); - } catch (err) { - await onLog( - "stderr", - `[taskcore] Failed to inject Codex skill "${entry.key}" into ${skillsHome}: ${err instanceof Error ? err.message : String(err)} -` - ); - } - } - await pruneBrokenUnavailableTaskcoreSkillSymlinks( - skillsHome, - skillsEntries.map((entry) => entry.runtimeName), - onLog - ); -} -async function execute2(ctx) { - const { runId, agent, runtime, config: config3, context, onLog, onMeta, onSpawn, authToken } = ctx; - const promptTemplate = asString( - config3.promptTemplate, - "You are agent {{agent.id}} ({{agent.name}}). Continue your Taskcore work." - ); - const command = asString(config3.command, "codex"); - const model = asString(config3.model, ""); - const workspaceContext = parseObject(context.taskcoreWorkspace); - const workspaceCwd = asString(workspaceContext.cwd, ""); - const workspaceSource = asString(workspaceContext.source, ""); - const workspaceStrategy = asString(workspaceContext.strategy, ""); - const workspaceId = asString(workspaceContext.workspaceId, ""); - const workspaceRepoUrl = asString(workspaceContext.repoUrl, ""); - const workspaceRepoRef = asString(workspaceContext.repoRef, ""); - const workspaceBranch = asString(workspaceContext.branchName, ""); - const workspaceWorktreePath = asString(workspaceContext.worktreePath, ""); - const agentHome = asString(workspaceContext.agentHome, ""); - const workspaceHints = Array.isArray(context.taskcoreWorkspaces) ? context.taskcoreWorkspaces.filter( - (value) => typeof value === "object" && value !== null - ) : []; - const runtimeServiceIntents = Array.isArray(context.taskcoreRuntimeServiceIntents) ? context.taskcoreRuntimeServiceIntents.filter( - (value) => typeof value === "object" && value !== null - ) : []; - const runtimeServices = Array.isArray(context.taskcoreRuntimeServices) ? context.taskcoreRuntimeServices.filter( - (value) => typeof value === "object" && value !== null - ) : []; - const runtimePrimaryUrl = asString(context.taskcoreRuntimePrimaryUrl, ""); - const configuredCwd = asString(config3.cwd, ""); - const useConfiguredInsteadOfAgentHome = workspaceSource === "agent_home" && configuredCwd.length > 0; - const effectiveWorkspaceCwd = useConfiguredInsteadOfAgentHome ? "" : workspaceCwd; - const cwd = effectiveWorkspaceCwd || configuredCwd || process.cwd(); - const envConfig = parseObject(config3.env); - const configuredCodexHome = typeof envConfig.CODEX_HOME === "string" && envConfig.CODEX_HOME.trim().length > 0 ? path12.resolve(envConfig.CODEX_HOME.trim()) : null; - const codexSkillEntries = await readTaskcoreRuntimeSkillEntries(config3, __moduleDir4); - const desiredSkillNames = resolveCodexDesiredSkillNames(config3, codexSkillEntries); - await ensureAbsoluteDirectory(cwd, { createIfMissing: true }); - const preparedManagedCodexHome = configuredCodexHome ? null : await prepareManagedCodexHome(process.env, onLog, agent.companyId); - const defaultCodexHome = resolveManagedCodexHomeDir(process.env, agent.companyId); - const effectiveCodexHome = configuredCodexHome ?? preparedManagedCodexHome ?? defaultCodexHome; - await fs9.mkdir(effectiveCodexHome, { recursive: true }); - const codexSkillsDir = resolveCodexSkillsDir(effectiveCodexHome); - await ensureCodexSkillsInjected( - onLog, - { - skillsHome: codexSkillsDir, - skillsEntries: codexSkillEntries, - desiredSkillNames - } - ); - const hasExplicitApiKey = typeof envConfig.TASKCORE_API_KEY === "string" && envConfig.TASKCORE_API_KEY.trim().length > 0; - const env2 = { ...buildTaskcoreEnv(agent) }; - env2.CODEX_HOME = effectiveCodexHome; - env2.TASKCORE_RUN_ID = runId; - const wakeTaskId = typeof context.taskId === "string" && context.taskId.trim().length > 0 && context.taskId.trim() || typeof context.issueId === "string" && context.issueId.trim().length > 0 && context.issueId.trim() || null; - const wakeReason = typeof context.wakeReason === "string" && context.wakeReason.trim().length > 0 ? context.wakeReason.trim() : null; - const wakeCommentId = typeof context.wakeCommentId === "string" && context.wakeCommentId.trim().length > 0 && context.wakeCommentId.trim() || typeof context.commentId === "string" && context.commentId.trim().length > 0 && context.commentId.trim() || null; - const approvalId = typeof context.approvalId === "string" && context.approvalId.trim().length > 0 ? context.approvalId.trim() : null; - const approvalStatus = typeof context.approvalStatus === "string" && context.approvalStatus.trim().length > 0 ? context.approvalStatus.trim() : null; - const linkedIssueIds = Array.isArray(context.issueIds) ? context.issueIds.filter((value) => typeof value === "string" && value.trim().length > 0) : []; - const wakePayloadJson = stringifyTaskcoreWakePayload(context.taskcoreWake); - if (wakeTaskId) { - env2.TASKCORE_TASK_ID = wakeTaskId; - } - if (wakeReason) { - env2.TASKCORE_WAKE_REASON = wakeReason; - } - if (wakeCommentId) { - env2.TASKCORE_WAKE_COMMENT_ID = wakeCommentId; - } - if (approvalId) { - env2.TASKCORE_APPROVAL_ID = approvalId; - } - if (approvalStatus) { - env2.TASKCORE_APPROVAL_STATUS = approvalStatus; - } - if (linkedIssueIds.length > 0) { - env2.TASKCORE_LINKED_ISSUE_IDS = linkedIssueIds.join(","); - } - if (wakePayloadJson) { - env2.TASKCORE_WAKE_PAYLOAD_JSON = wakePayloadJson; - } - if (effectiveWorkspaceCwd) { - env2.TASKCORE_WORKSPACE_CWD = effectiveWorkspaceCwd; - } - if (workspaceSource) { - env2.TASKCORE_WORKSPACE_SOURCE = workspaceSource; - } - if (workspaceStrategy) { - env2.TASKCORE_WORKSPACE_STRATEGY = workspaceStrategy; - } - if (workspaceId) { - env2.TASKCORE_WORKSPACE_ID = workspaceId; - } - if (workspaceRepoUrl) { - env2.TASKCORE_WORKSPACE_REPO_URL = workspaceRepoUrl; - } - if (workspaceRepoRef) { - env2.TASKCORE_WORKSPACE_REPO_REF = workspaceRepoRef; - } - if (workspaceBranch) { - env2.TASKCORE_WORKSPACE_BRANCH = workspaceBranch; - } - if (workspaceWorktreePath) { - env2.TASKCORE_WORKSPACE_WORKTREE_PATH = workspaceWorktreePath; - } - if (agentHome) { - env2.AGENT_HOME = agentHome; - } - if (workspaceHints.length > 0) { - env2.TASKCORE_WORKSPACES_JSON = JSON.stringify(workspaceHints); - } - if (runtimeServiceIntents.length > 0) { - env2.TASKCORE_RUNTIME_SERVICE_INTENTS_JSON = JSON.stringify(runtimeServiceIntents); - } - if (runtimeServices.length > 0) { - env2.TASKCORE_RUNTIME_SERVICES_JSON = JSON.stringify(runtimeServices); - } - if (runtimePrimaryUrl) { - env2.TASKCORE_RUNTIME_PRIMARY_URL = runtimePrimaryUrl; - } - for (const [k5, v5] of Object.entries(envConfig)) { - if (typeof v5 === "string") env2[k5] = v5; - } - if (!hasExplicitApiKey && authToken) { - env2.TASKCORE_API_KEY = authToken; - } - const effectiveEnv = Object.fromEntries( - Object.entries({ ...process.env, ...env2 }).filter( - (entry) => typeof entry[1] === "string" - ) - ); - const billingType = resolveCodexBillingType(effectiveEnv); - const runtimeEnv = ensurePathInEnv(effectiveEnv); - await ensureCommandResolvable(command, cwd, runtimeEnv); - const resolvedCommand = await resolveCommandForLogs(command, cwd, runtimeEnv); - const loggedEnv = buildInvocationEnvForLogs(env2, { - runtimeEnv, - includeRuntimeKeys: ["HOME"], - resolvedCommand - }); - const timeoutSec = asNumber(config3.timeoutSec, 0); - const graceSec = asNumber(config3.graceSec, 20); - const runtimeSessionParams = parseObject(runtime.sessionParams); - const runtimeSessionId = asString(runtimeSessionParams.sessionId, runtime.sessionId ?? ""); - const runtimeSessionCwd = asString(runtimeSessionParams.cwd, ""); - const canResumeSession = runtimeSessionId.length > 0 && (runtimeSessionCwd.length === 0 || path12.resolve(runtimeSessionCwd) === path12.resolve(cwd)); - const sessionId = canResumeSession ? runtimeSessionId : null; - if (runtimeSessionId && !canResumeSession) { - await onLog( - "stdout", - `[taskcore] Codex session "${runtimeSessionId}" was saved for cwd "${runtimeSessionCwd}" and will not be resumed in "${cwd}". -` - ); - } - const instructionsFilePath = asString(config3.instructionsFilePath, "").trim(); - const instructionsDir = instructionsFilePath ? `${path12.dirname(instructionsFilePath)}/` : ""; - let instructionsPrefix = ""; - let instructionsChars = 0; - if (instructionsFilePath) { - try { - const instructionsContents = await fs9.readFile(instructionsFilePath, "utf8"); - instructionsPrefix = `${instructionsContents} - -The above agent instructions were loaded from ${instructionsFilePath}. Resolve any relative file references from ${instructionsDir}. - -`; - instructionsChars = instructionsPrefix.length; - } catch (err) { - const reason = err instanceof Error ? err.message : String(err); - await onLog( - "stdout", - `[taskcore] Warning: could not read agent instructions file "${instructionsFilePath}": ${reason} -` - ); - } - } - const repoAgentsNote = "Codex exec automatically applies repo-scoped AGENTS.md instructions from the current workspace; Taskcore does not currently suppress that discovery."; - const bootstrapPromptTemplate = asString(config3.bootstrapPromptTemplate, ""); - const templateData = { - agentId: agent.id, - companyId: agent.companyId, - runId, - company: { id: agent.companyId }, - agent, - run: { id: runId, source: "on_demand" }, - context - }; - const renderedBootstrapPrompt = !sessionId && bootstrapPromptTemplate.trim().length > 0 ? renderTemplate(bootstrapPromptTemplate, templateData).trim() : ""; - const wakePrompt = renderTaskcoreWakePrompt(context.taskcoreWake, { resumedSession: Boolean(sessionId) }); - const shouldUseResumeDeltaPrompt = Boolean(sessionId) && wakePrompt.length > 0; - const promptInstructionsPrefix = shouldUseResumeDeltaPrompt ? "" : instructionsPrefix; - instructionsChars = promptInstructionsPrefix.length; - const commandNotes = (() => { - if (!instructionsFilePath) { - return [repoAgentsNote]; - } - if (instructionsPrefix.length > 0) { - if (shouldUseResumeDeltaPrompt) { - return [ - `Loaded agent instructions from ${instructionsFilePath}`, - "Skipped stdin instruction reinjection because an existing Codex session is being resumed with a wake delta.", - repoAgentsNote - ]; - } - return [ - `Loaded agent instructions from ${instructionsFilePath}`, - `Prepended instructions + path directive to stdin prompt (relative references from ${instructionsDir}).`, - repoAgentsNote - ]; - } - return [ - `Configured instructionsFilePath ${instructionsFilePath}, but file could not be read; continuing without injected instructions.`, - repoAgentsNote - ]; - })(); - const renderedPrompt = shouldUseResumeDeltaPrompt ? "" : renderTemplate(promptTemplate, templateData); - const sessionHandoffNote = asString(context.taskcoreSessionHandoffMarkdown, "").trim(); - const prompt = joinPromptSections([ - promptInstructionsPrefix, - renderedBootstrapPrompt, - wakePrompt, - sessionHandoffNote, - renderedPrompt - ]); - const promptMetrics = { - promptChars: prompt.length, - instructionsChars, - bootstrapPromptChars: renderedBootstrapPrompt.length, - wakePromptChars: wakePrompt.length, - sessionHandoffChars: sessionHandoffNote.length, - heartbeatPromptChars: renderedPrompt.length - }; - const runAttempt = async (resumeSessionId) => { - const execArgs = buildCodexExecArgs(config3, { resumeSessionId }); - const args = execArgs.args; - const commandNotesWithFastMode = execArgs.fastModeIgnoredReason == null ? commandNotes : [...commandNotes, execArgs.fastModeIgnoredReason]; - if (onMeta) { - await onMeta({ - adapterType: "codex_local", - command: resolvedCommand, - cwd, - commandNotes: commandNotesWithFastMode, - commandArgs: args.map((value, idx) => { - if (idx === args.length - 1 && value !== "-") return ``; - return value; - }), - env: loggedEnv, - prompt, - promptMetrics, - context - }); - } - const proc = await runChildProcess(runId, command, args, { - cwd, - env: env2, - stdin: prompt, - timeoutSec, - graceSec, - onSpawn, - onLog: async (stream, chunk) => { - if (stream !== "stderr") { - await onLog(stream, chunk); - return; - } - const cleaned = stripCodexRolloutNoise(chunk); - if (!cleaned.trim()) return; - await onLog(stream, cleaned); - } - }); - const cleanedStderr = stripCodexRolloutNoise(proc.stderr); - return { - proc: { - ...proc, - stderr: cleanedStderr - }, - rawStderr: proc.stderr, - parsed: parseCodexJsonl(proc.stdout) - }; - }; - const toResult = (attempt, clearSessionOnMissingSession = false) => { - if (attempt.proc.timedOut) { - return { - exitCode: attempt.proc.exitCode, - signal: attempt.proc.signal, - timedOut: true, - errorMessage: `Timed out after ${timeoutSec}s`, - clearSession: clearSessionOnMissingSession - }; - } - const resolvedSessionId = attempt.parsed.sessionId ?? runtimeSessionId ?? runtime.sessionId ?? null; - const resolvedSessionParams = resolvedSessionId ? { - sessionId: resolvedSessionId, - cwd, - ...workspaceId ? { workspaceId } : {}, - ...workspaceRepoUrl ? { repoUrl: workspaceRepoUrl } : {}, - ...workspaceRepoRef ? { repoRef: workspaceRepoRef } : {} - } : null; - const parsedError = typeof attempt.parsed.errorMessage === "string" ? attempt.parsed.errorMessage.trim() : ""; - const stderrLine = firstNonEmptyLine2(attempt.proc.stderr); - const fallbackErrorMessage = parsedError || stderrLine || `Codex exited with code ${attempt.proc.exitCode ?? -1}`; - return { - exitCode: attempt.proc.exitCode, - signal: attempt.proc.signal, - timedOut: false, - errorMessage: (attempt.proc.exitCode ?? 0) === 0 ? null : fallbackErrorMessage, - usage: attempt.parsed.usage, - sessionId: resolvedSessionId, - sessionParams: resolvedSessionParams, - sessionDisplayId: resolvedSessionId, - provider: "openai", - biller: resolveCodexBiller(effectiveEnv, billingType), - model, - billingType, - costUsd: null, - resultJson: { - stdout: attempt.proc.stdout, - stderr: attempt.proc.stderr - }, - summary: attempt.parsed.summary, - clearSession: Boolean(clearSessionOnMissingSession && !resolvedSessionId) - }; - }; - const initial = await runAttempt(sessionId); - if (sessionId && !initial.proc.timedOut && (initial.proc.exitCode ?? 0) !== 0 && isCodexUnknownSessionError(initial.proc.stdout, initial.rawStderr)) { - await onLog( - "stdout", - `[taskcore] Codex resume session "${sessionId}" is unavailable; retrying with a fresh session. -` - ); - const retry = await runAttempt(null); - return toResult(retry, true); - } - return toResult(initial); -} - -// packages/adapters/codex-local/src/server/test.ts -import path14 from "node:path"; - -// packages/adapters/codex-local/src/server/quota.ts -import { spawn as spawn2 } from "node:child_process"; -import fs10 from "node:fs/promises"; -import os7 from "node:os"; -import path13 from "node:path"; -var CODEX_USAGE_SOURCE_RPC = "codex-rpc"; -var CODEX_USAGE_SOURCE_WHAM = "codex-wham"; -function codexHomeDir() { - const fromEnv = process.env.CODEX_HOME; - if (typeof fromEnv === "string" && fromEnv.trim().length > 0) return fromEnv.trim(); - return path13.join(os7.homedir(), ".codex"); -} -function base64UrlDecode2(input) { - try { - let normalized = input.replace(/-/g, "+").replace(/_/g, "/"); - const remainder = normalized.length % 4; - if (remainder > 0) normalized += "=".repeat(4 - remainder); - return Buffer.from(normalized, "base64").toString("utf8"); - } catch { - return null; - } -} -function decodeJwtPayload(token) { - if (typeof token !== "string" || token.trim().length === 0) return null; - const parts = token.split("."); - if (parts.length < 2) return null; - const decoded = base64UrlDecode2(parts[1] ?? ""); - if (!decoded) return null; - try { - const parsed = JSON.parse(decoded); - return typeof parsed === "object" && parsed !== null ? parsed : null; - } catch { - return null; - } -} -function readNestedString(record2, pathSegments) { - let current = record2; - for (const segment of pathSegments) { - if (typeof current !== "object" || current === null || Array.isArray(current)) return null; - current = current[segment]; - } - return typeof current === "string" && current.trim().length > 0 ? current.trim() : null; -} -function parsePlanAndEmailFromToken(idToken, accessToken) { - const payloads = [decodeJwtPayload(idToken), decodeJwtPayload(accessToken)].filter( - (value) => value != null - ); - for (const payload2 of payloads) { - const directEmail = typeof payload2.email === "string" ? payload2.email : null; - const authBlock = typeof payload2["https://api.openai.com/auth"] === "object" && payload2["https://api.openai.com/auth"] !== null && !Array.isArray(payload2["https://api.openai.com/auth"]) ? payload2["https://api.openai.com/auth"] : null; - const profileBlock = typeof payload2["https://api.openai.com/profile"] === "object" && payload2["https://api.openai.com/profile"] !== null && !Array.isArray(payload2["https://api.openai.com/profile"]) ? payload2["https://api.openai.com/profile"] : null; - const email3 = directEmail ?? (typeof profileBlock?.email === "string" ? profileBlock.email : null) ?? (typeof authBlock?.chatgpt_user_email === "string" ? authBlock.chatgpt_user_email : null); - const planType = typeof authBlock?.chatgpt_plan_type === "string" ? authBlock.chatgpt_plan_type : null; - if (email3 || planType) return { email: email3 ?? null, planType }; - } - return { email: null, planType: null }; -} -async function readCodexAuthInfo(codexHome) { - const authPath = path13.join(codexHome ?? codexHomeDir(), "auth.json"); - let raw; - try { - raw = await fs10.readFile(authPath, "utf8"); - } catch { - return null; - } - let parsed; - try { - parsed = JSON.parse(raw); - } catch { - return null; - } - if (typeof parsed !== "object" || parsed === null) return null; - const obj = parsed; - const modern = obj; - const legacy = obj; - const accessToken = legacy.accessToken ?? modern.tokens?.access_token ?? readNestedString(obj, ["tokens", "access_token"]); - if (typeof accessToken !== "string" || accessToken.length === 0) return null; - const accountId = legacy.accountId ?? modern.tokens?.account_id ?? readNestedString(obj, ["tokens", "account_id"]); - const refreshToken2 = modern.tokens?.refresh_token ?? readNestedString(obj, ["tokens", "refresh_token"]); - const idToken = modern.tokens?.id_token ?? readNestedString(obj, ["tokens", "id_token"]); - const { email: email3, planType } = parsePlanAndEmailFromToken(idToken, accessToken); - return { - accessToken, - accountId: typeof accountId === "string" && accountId.trim().length > 0 ? accountId.trim() : null, - refreshToken: typeof refreshToken2 === "string" && refreshToken2.trim().length > 0 ? refreshToken2.trim() : null, - idToken: typeof idToken === "string" && idToken.trim().length > 0 ? idToken.trim() : null, - email: email3, - planType, - lastRefresh: typeof modern.last_refresh === "string" && modern.last_refresh.trim().length > 0 ? modern.last_refresh.trim() : null - }; -} -async function readCodexToken() { - const auth = await readCodexAuthInfo(); - if (!auth) return null; - return { token: auth.accessToken, accountId: auth.accountId }; -} -async function fetchWithTimeout2(url2, init2, ms = 8e3) { - const controller = new AbortController(); - const timer2 = setTimeout(() => controller.abort(), ms); - try { - return await fetch(url2, { ...init2, signal: controller.signal }); - } finally { - clearTimeout(timer2); - } -} -function normalizeCodexUsedPercent(rawPct) { - if (rawPct == null) return null; - return Math.min(100, Math.round(rawPct < 1 ? rawPct * 100 : rawPct)); -} -async function fetchCodexQuota(token, accountId) { - const headers = { - Authorization: `Bearer ${token}` - }; - if (accountId) headers["ChatGPT-Account-Id"] = accountId; - const resp = await fetchWithTimeout2("https://chatgpt.com/backend-api/wham/usage", { headers }); - if (!resp.ok) throw new Error(`chatgpt wham api returned ${resp.status}`); - const body = await resp.json(); - const windows = []; - const rateLimit = body.rate_limit; - if (rateLimit?.primary_window != null) { - const w5 = rateLimit.primary_window; - windows.push({ - label: "5h limit", - usedPercent: normalizeCodexUsedPercent(w5.used_percent), - resetsAt: typeof w5.reset_at === "number" ? unixSecondsToIso(w5.reset_at) : w5.reset_at ?? null, - valueLabel: null, - detail: null - }); - } - if (rateLimit?.secondary_window != null) { - const w5 = rateLimit.secondary_window; - windows.push({ - label: "Weekly limit", - usedPercent: normalizeCodexUsedPercent(w5.used_percent), - resetsAt: typeof w5.reset_at === "number" ? unixSecondsToIso(w5.reset_at) : w5.reset_at ?? null, - valueLabel: null, - detail: null - }); - } - if (body.credits != null && body.credits.unlimited !== true) { - const balance = body.credits.balance; - const valueLabel = balance != null ? `$${(balance / 100).toFixed(2)} remaining` : "N/A"; - windows.push({ - label: "Credits", - usedPercent: null, - resetsAt: null, - valueLabel, - detail: null - }); - } - return windows; -} -function unixSecondsToIso(value) { - if (typeof value !== "number" || !Number.isFinite(value)) return null; - return new Date(value * 1e3).toISOString(); -} -function buildCodexRpcWindow(label, window2) { - if (!window2) return null; - return { - label, - usedPercent: normalizeCodexUsedPercent(window2.usedPercent), - resetsAt: unixSecondsToIso(window2.resetsAt), - valueLabel: null, - detail: null - }; -} -function parseCreditBalance(value) { - if (typeof value === "number" && Number.isFinite(value)) { - return `$${value.toFixed(2)} remaining`; - } - if (typeof value === "string" && value.trim().length > 0) { - const parsed = Number(value); - if (Number.isFinite(parsed)) { - return `$${parsed.toFixed(2)} remaining`; - } - return value.trim(); - } - return null; -} -function mapCodexRpcQuota(result, account) { - const windows = []; - const limitOrder = ["codex"]; - const limitsById = result.rateLimitsByLimitId ?? {}; - for (const key of Object.keys(limitsById)) { - if (!limitOrder.includes(key)) limitOrder.push(key); - } - const rootLimit = result.rateLimits ?? null; - const allLimits = /* @__PURE__ */ new Map(); - if (rootLimit?.limitId) allLimits.set(rootLimit.limitId, rootLimit); - for (const [key, value] of Object.entries(limitsById)) { - allLimits.set(key, value); - } - if (!allLimits.has("codex") && rootLimit) allLimits.set("codex", rootLimit); - for (const limitId of limitOrder) { - const limit = allLimits.get(limitId); - if (!limit) continue; - const prefix = limitId === "codex" ? "" : `${limit.limitName ?? limitId} \xB7 `; - const primary = buildCodexRpcWindow(`${prefix}5h limit`, limit.primary); - if (primary) windows.push(primary); - const secondary = buildCodexRpcWindow(`${prefix}Weekly limit`, limit.secondary); - if (secondary) windows.push(secondary); - if (limitId === "codex" && limit.credits && limit.credits.unlimited !== true) { - windows.push({ - label: "Credits", - usedPercent: null, - resetsAt: null, - valueLabel: parseCreditBalance(limit.credits.balance) ?? "N/A", - detail: null - }); - } - } - return { - windows, - email: typeof account?.account?.email === "string" && account.account.email.trim().length > 0 ? account.account.email.trim() : null, - planType: typeof account?.account?.planType === "string" && account.account.planType.trim().length > 0 ? account.account.planType.trim() : typeof rootLimit?.planType === "string" && rootLimit.planType.trim().length > 0 ? rootLimit.planType.trim() : null - }; -} -var CodexRpcClient = class { - proc = spawn2( - "codex", - ["-s", "read-only", "-a", "untrusted", "app-server"], - { stdio: ["pipe", "pipe", "pipe"], env: process.env } - ); - nextId = 1; - buffer = ""; - pending = /* @__PURE__ */ new Map(); - stderr = ""; - constructor() { - this.proc.stdout.setEncoding("utf8"); - this.proc.stderr.setEncoding("utf8"); - this.proc.stdout.on("data", (chunk) => this.onStdout(chunk)); - this.proc.stderr.on("data", (chunk) => { - this.stderr += chunk; - }); - this.proc.on("exit", () => { - for (const request of this.pending.values()) { - clearTimeout(request.timer); - request.reject(new Error(this.stderr.trim() || "codex app-server closed unexpectedly")); - } - this.pending.clear(); - }); - this.proc.on("error", (err) => { - for (const request of this.pending.values()) { - clearTimeout(request.timer); - request.reject(err); - } - this.pending.clear(); - }); - } - onStdout(chunk) { - this.buffer += chunk; - while (true) { - const newlineIndex = this.buffer.indexOf("\n"); - if (newlineIndex < 0) break; - const line3 = this.buffer.slice(0, newlineIndex).trim(); - this.buffer = this.buffer.slice(newlineIndex + 1); - if (!line3) continue; - let parsed; - try { - parsed = JSON.parse(line3); - } catch { - continue; - } - const id = typeof parsed.id === "number" ? parsed.id : null; - if (id == null) continue; - const pending = this.pending.get(id); - if (!pending) continue; - this.pending.delete(id); - clearTimeout(pending.timer); - pending.resolve(parsed); - } - } - request(method, params = {}, timeoutMs = 6e3) { - const id = this.nextId++; - const payload2 = JSON.stringify({ id, method, params }) + "\n"; - return new Promise((resolve4, reject) => { - const timer2 = setTimeout(() => { - this.pending.delete(id); - reject(new Error(`codex app-server timed out on ${method}`)); - }, timeoutMs); - this.pending.set(id, { resolve: resolve4, reject, timer: timer2 }); - this.proc.stdin.write(payload2); - }); - } - notify(method, params = {}) { - this.proc.stdin.write(JSON.stringify({ method, params }) + "\n"); - } - async initialize() { - await this.request("initialize", { - clientInfo: { - name: "taskcore", - version: "0.0.0" - } - }); - this.notify("initialized", {}); - } - async fetchRateLimits() { - const message2 = await this.request("account/rateLimits/read"); - return message2.result ?? {}; - } - async fetchAccount() { - try { - const message2 = await this.request("account/read"); - return message2.result ?? null; - } catch { - return null; - } - } - async shutdown() { - this.proc.kill("SIGTERM"); - } -}; -async function fetchCodexRpcQuota() { - const client2 = new CodexRpcClient(); - try { - await client2.initialize(); - const [limits, account] = await Promise.all([ - client2.fetchRateLimits(), - client2.fetchAccount() - ]); - return mapCodexRpcQuota(limits, account); - } finally { - await client2.shutdown(); - } -} -function formatProviderError2(source, error50) { - const message2 = error50 instanceof Error ? error50.message : String(error50); - return `${source}: ${message2}`; -} -async function getQuotaWindows2() { - const errors = []; - try { - const rpc = await fetchCodexRpcQuota(); - if (rpc.windows.length > 0) { - return { provider: "openai", source: CODEX_USAGE_SOURCE_RPC, ok: true, windows: rpc.windows }; - } - } catch (error50) { - errors.push(formatProviderError2("Codex app-server", error50)); - } - const auth = await readCodexToken(); - if (auth) { - try { - const windows = await fetchCodexQuota(auth.token, auth.accountId); - return { provider: "openai", source: CODEX_USAGE_SOURCE_WHAM, ok: true, windows }; - } catch (error50) { - errors.push(formatProviderError2("ChatGPT WHAM usage", error50)); - } - } else { - errors.push("no local codex auth token"); - } - return { - provider: "openai", - ok: false, - error: errors.join("; "), - windows: [] - }; -} - -// packages/adapters/codex-local/src/server/test.ts -function summarizeStatus2(checks) { - if (checks.some((check3) => check3.level === "error")) return "fail"; - if (checks.some((check3) => check3.level === "warn")) return "warn"; - return "pass"; -} -function isNonEmpty2(value) { - return typeof value === "string" && value.trim().length > 0; -} -function firstNonEmptyLine3(text3) { - return text3.split(/\r?\n/).map((line3) => line3.trim()).find(Boolean) ?? ""; -} -function commandLooksLike2(command, expected) { - const base = path14.basename(command).toLowerCase(); - return base === expected || base === `${expected}.cmd` || base === `${expected}.exe`; -} -function summarizeProbeDetail2(stdout, stderr, parsedError) { - const raw = parsedError?.trim() || firstNonEmptyLine3(stderr) || firstNonEmptyLine3(stdout); - if (!raw) return null; - const clean3 = raw.replace(/\s+/g, " ").trim(); - const max = 240; - return clean3.length > max ? `${clean3.slice(0, max - 1)}\u2026` : clean3; -} -var CODEX_AUTH_REQUIRED_RE = /(?:not\s+logged\s+in|login\s+required|authentication\s+required|unauthorized|invalid(?:\s+or\s+missing)?\s+api(?:[_\s-]?key)?|openai[_\s-]?api[_\s-]?key|api[_\s-]?key.*required|please\s+run\s+`?codex\s+login`?)/i; -async function testEnvironment2(ctx) { - const checks = []; - const config3 = parseObject(ctx.config); - const command = asString(config3.command, "codex"); - const cwd = asString(config3.cwd, process.cwd()); - try { - await ensureAbsoluteDirectory(cwd, { createIfMissing: true }); - checks.push({ - code: "codex_cwd_valid", - level: "info", - message: `Working directory is valid: ${cwd}` - }); - } catch (err) { - checks.push({ - code: "codex_cwd_invalid", - level: "error", - message: err instanceof Error ? err.message : "Invalid working directory", - detail: cwd - }); - } - const envConfig = parseObject(config3.env); - const env2 = {}; - for (const [key, value] of Object.entries(envConfig)) { - if (typeof value === "string") env2[key] = value; - } - const runtimeEnv = ensurePathInEnv({ ...process.env, ...env2 }); - try { - await ensureCommandResolvable(command, cwd, runtimeEnv); - checks.push({ - code: "codex_command_resolvable", - level: "info", - message: `Command is executable: ${command}` - }); - } catch (err) { - checks.push({ - code: "codex_command_unresolvable", - level: "error", - message: err instanceof Error ? err.message : "Command is not executable", - detail: command - }); - } - const configOpenAiKey = env2.OPENAI_API_KEY; - const hostOpenAiKey = process.env.OPENAI_API_KEY; - if (isNonEmpty2(configOpenAiKey) || isNonEmpty2(hostOpenAiKey)) { - const source = isNonEmpty2(configOpenAiKey) ? "adapter config env" : "server environment"; - checks.push({ - code: "codex_openai_api_key_present", - level: "info", - message: "OPENAI_API_KEY is set for Codex authentication.", - detail: `Detected in ${source}.` - }); - } else { - const codexHome = isNonEmpty2(env2.CODEX_HOME) ? env2.CODEX_HOME : void 0; - const codexAuth = await readCodexAuthInfo(codexHome).catch(() => null); - if (codexAuth) { - checks.push({ - code: "codex_native_auth_present", - level: "info", - message: "Codex is authenticated via its own auth configuration.", - detail: codexAuth.email ? `Logged in as ${codexAuth.email}.` : `Credentials found in ${path14.join(codexHome ?? codexHomeDir(), "auth.json")}.` - }); - } else { - checks.push({ - code: "codex_openai_api_key_missing", - level: "warn", - message: "OPENAI_API_KEY is not set. Codex runs may fail until authentication is configured.", - hint: "Set OPENAI_API_KEY in adapter env, shell environment, or run `codex auth` to log in." - }); - } - } - const canRunProbe = checks.every((check3) => check3.code !== "codex_cwd_invalid" && check3.code !== "codex_command_unresolvable"); - if (canRunProbe) { - if (!commandLooksLike2(command, "codex")) { - checks.push({ - code: "codex_hello_probe_skipped_custom_command", - level: "info", - message: "Skipped hello probe because command is not `codex`.", - detail: command, - hint: "Use the `codex` CLI command to run the automatic login and installation probe." - }); - } else { - const execArgs = buildCodexExecArgs({ ...config3, fastMode: false }); - const args = execArgs.args; - if (execArgs.fastModeIgnoredReason) { - checks.push({ - code: "codex_fast_mode_unsupported_model", - level: "warn", - message: execArgs.fastModeIgnoredReason, - hint: "Switch the agent model to GPT-5.4 to enable Codex Fast mode." - }); - } - const probe = await runChildProcess( - `codex-envtest-${Date.now()}-${Math.random().toString(16).slice(2)}`, - command, - args, - { - cwd, - env: env2, - timeoutSec: 45, - graceSec: 5, - stdin: "Respond with hello.", - onLog: async () => { - } - } - ); - const parsed = parseCodexJsonl(probe.stdout); - const detail = summarizeProbeDetail2(probe.stdout, probe.stderr, parsed.errorMessage); - const authEvidence = `${parsed.errorMessage ?? ""} -${probe.stdout} -${probe.stderr}`.trim(); - if (probe.timedOut) { - checks.push({ - code: "codex_hello_probe_timed_out", - level: "warn", - message: "Codex hello probe timed out.", - hint: "Retry the probe. If this persists, verify Codex can run `Respond with hello` from this directory manually." - }); - } else if ((probe.exitCode ?? 1) === 0) { - const summary = parsed.summary.trim(); - const hasHello = /\bhello\b/i.test(summary); - checks.push({ - code: hasHello ? "codex_hello_probe_passed" : "codex_hello_probe_unexpected_output", - level: hasHello ? "info" : "warn", - message: hasHello ? "Codex hello probe succeeded." : "Codex probe ran but did not return `hello` as expected.", - ...summary ? { detail: summary.replace(/\s+/g, " ").trim().slice(0, 240) } : {}, - ...hasHello ? {} : { - hint: "Try the probe manually (`codex exec --json -` then prompt: Respond with hello) to inspect full output." - } - }); - } else if (CODEX_AUTH_REQUIRED_RE.test(authEvidence)) { - checks.push({ - code: "codex_hello_probe_auth_required", - level: "warn", - message: "Codex CLI is installed, but authentication is not ready.", - ...detail ? { detail } : {}, - hint: "Configure OPENAI_API_KEY in adapter env/shell or run `codex login`, then retry the probe." - }); - } else { - checks.push({ - code: "codex_hello_probe_failed", - level: "error", - message: "Codex hello probe failed.", - ...detail ? { detail } : {}, - hint: "Run `codex exec --json -` manually in this working directory and prompt `Respond with hello` to debug." - }); - } - } - } - return { - adapterType: ctx.adapterType, - status: summarizeStatus2(checks), - checks, - testedAt: (/* @__PURE__ */ new Date()).toISOString() - }; -} - -// packages/adapters/codex-local/src/server/index.ts -function readNonEmptyString3(value) { - return typeof value === "string" && value.trim().length > 0 ? value.trim() : null; -} -var sessionCodec2 = { - deserialize(raw) { - if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return null; - const record2 = raw; - const sessionId = readNonEmptyString3(record2.sessionId) ?? readNonEmptyString3(record2.session_id); - if (!sessionId) return null; - const cwd = readNonEmptyString3(record2.cwd) ?? readNonEmptyString3(record2.workdir) ?? readNonEmptyString3(record2.folder); - const workspaceId = readNonEmptyString3(record2.workspaceId) ?? readNonEmptyString3(record2.workspace_id); - const repoUrl = readNonEmptyString3(record2.repoUrl) ?? readNonEmptyString3(record2.repo_url); - const repoRef = readNonEmptyString3(record2.repoRef) ?? readNonEmptyString3(record2.repo_ref); - return { - sessionId, - ...cwd ? { cwd } : {}, - ...workspaceId ? { workspaceId } : {}, - ...repoUrl ? { repoUrl } : {}, - ...repoRef ? { repoRef } : {} - }; - }, - serialize(params) { - if (!params) return null; - const sessionId = readNonEmptyString3(params.sessionId) ?? readNonEmptyString3(params.session_id); - if (!sessionId) return null; - const cwd = readNonEmptyString3(params.cwd) ?? readNonEmptyString3(params.workdir) ?? readNonEmptyString3(params.folder); - const workspaceId = readNonEmptyString3(params.workspaceId) ?? readNonEmptyString3(params.workspace_id); - const repoUrl = readNonEmptyString3(params.repoUrl) ?? readNonEmptyString3(params.repo_url); - const repoRef = readNonEmptyString3(params.repoRef) ?? readNonEmptyString3(params.repo_ref); - return { - sessionId, - ...cwd ? { cwd } : {}, - ...workspaceId ? { workspaceId } : {}, - ...repoUrl ? { repoUrl } : {}, - ...repoRef ? { repoRef } : {} - }; - }, - getDisplayId(params) { - if (!params) return null; - return readNonEmptyString3(params.sessionId) ?? readNonEmptyString3(params.session_id); - } -}; - -// packages/adapters/opencode-local/src/server/execute.ts -import fs12 from "node:fs/promises"; -import os10 from "node:os"; -import path16 from "node:path"; -import { fileURLToPath as fileURLToPath6 } from "node:url"; - -// packages/adapters/opencode-local/src/server/parse.ts -function errorText(value) { - if (typeof value === "string") return value; - const rec = parseObject(value); - const message2 = asString(rec.message, "").trim(); - if (message2) return message2; - const data2 = parseObject(rec.data); - const nestedMessage = asString(data2.message, "").trim(); - if (nestedMessage) return nestedMessage; - const name = asString(rec.name, "").trim(); - if (name) return name; - const code = asString(rec.code, "").trim(); - if (code) return code; - try { - return JSON.stringify(rec); - } catch { - return ""; - } -} -function parseOpenCodeJsonl(stdout) { - let sessionId = null; - const messages2 = []; - const errors = []; - const usage = { - inputTokens: 0, - cachedInputTokens: 0, - outputTokens: 0 - }; - let costUsd = 0; - for (const rawLine of stdout.split(/\r?\n/)) { - const line3 = rawLine.trim(); - if (!line3) continue; - const event = parseJson2(line3); - if (!event) continue; - const currentSessionId = asString(event.sessionID, "").trim(); - if (currentSessionId) sessionId = currentSessionId; - const type = asString(event.type, ""); - if (type === "text") { - const part = parseObject(event.part); - const text3 = asString(part.text, "").trim(); - if (text3) messages2.push(text3); - continue; - } - if (type === "step_finish") { - const part = parseObject(event.part); - const tokens = parseObject(part.tokens); - const cache7 = parseObject(tokens.cache); - usage.inputTokens += asNumber(tokens.input, 0); - usage.cachedInputTokens += asNumber(cache7.read, 0); - usage.outputTokens += asNumber(tokens.output, 0) + asNumber(tokens.reasoning, 0); - costUsd += asNumber(part.cost, 0); - continue; - } - if (type === "tool_use") { - const part = parseObject(event.part); - const state2 = parseObject(part.state); - if (asString(state2.status, "") === "error") { - const text3 = asString(state2.error, "").trim(); - if (text3) errors.push(text3); - } - continue; - } - if (type === "error") { - const text3 = errorText(event.error ?? event.message).trim(); - if (text3) errors.push(text3); - continue; - } - } - return { - sessionId, - summary: messages2.join("\n\n").trim(), - usage, - costUsd, - errorMessage: errors.length > 0 ? errors.join("\n") : null - }; -} -function isOpenCodeUnknownSessionError(stdout, stderr) { - const haystack = `${stdout} -${stderr}`.split(/\r?\n/).map((line3) => line3.trim()).filter(Boolean).join("\n"); - return /unknown\s+session|session\b.*\bnot\s+found|resource\s+not\s+found:.*[\\/]session[\\/].*\.json|notfounderror|no session/i.test( - haystack - ); -} - -// packages/adapters/opencode-local/src/server/models.ts -import { createHash as createHash4 } from "node:crypto"; -import os8 from "node:os"; -var MODELS_CACHE_TTL_MS = 6e4; -var MODELS_DISCOVERY_TIMEOUT_MS = 2e4; -function resolveOpenCodeCommand(input) { - const envOverride = typeof process.env.TASKCORE_OPENCODE_COMMAND === "string" && process.env.TASKCORE_OPENCODE_COMMAND.trim().length > 0 ? process.env.TASKCORE_OPENCODE_COMMAND.trim() : "opencode"; - return asString(input, envOverride); -} -var discoveryCache = /* @__PURE__ */ new Map(); -var VOLATILE_ENV_KEY_PREFIXES = ["TASKCORE_", "npm_", "NPM_"]; -var VOLATILE_ENV_KEY_EXACT = /* @__PURE__ */ new Set(["PWD", "OLDPWD", "SHLVL", "_", "TERM_SESSION_ID", "HOME"]); -function dedupeModels(models8) { - const seen = /* @__PURE__ */ new Set(); - const deduped = []; - for (const model of models8) { - const id = model.id.trim(); - if (!id || seen.has(id)) continue; - seen.add(id); - deduped.push({ id, label: model.label.trim() || id }); - } - return deduped; -} -function sortModels(models8) { - return [...models8].sort( - (a5, b6) => a5.id.localeCompare(b6.id, "en", { numeric: true, sensitivity: "base" }) - ); -} -function firstNonEmptyLine4(text3) { - return text3.split(/\r?\n/).map((line3) => line3.trim()).find(Boolean) ?? ""; -} -function parseModelsOutput(stdout) { - const parsed = []; - for (const raw of stdout.split(/\r?\n/)) { - const line3 = raw.trim(); - if (!line3) continue; - const firstToken = line3.split(/\s+/)[0]?.trim() ?? ""; - if (!firstToken.includes("/")) continue; - const provider = firstToken.slice(0, firstToken.indexOf("/")).trim(); - const model = firstToken.slice(firstToken.indexOf("/") + 1).trim(); - if (!provider || !model) continue; - parsed.push({ id: `${provider}/${model}`, label: `${provider}/${model}` }); - } - return dedupeModels(parsed); -} -function normalizeEnv(input) { - const envInput = typeof input === "object" && input !== null && !Array.isArray(input) ? input : {}; - const env2 = {}; - for (const [key, value] of Object.entries(envInput)) { - if (typeof value === "string") env2[key] = value; - } - return env2; -} -function isVolatileEnvKey(key) { - if (VOLATILE_ENV_KEY_EXACT.has(key)) return true; - return VOLATILE_ENV_KEY_PREFIXES.some((prefix) => key.startsWith(prefix)); -} -function hashValue(value) { - return createHash4("sha256").update(value).digest("hex"); -} -function discoveryCacheKey(command, cwd, env2) { - const envKey = Object.entries(env2).filter(([key]) => !isVolatileEnvKey(key)).sort(([a5], [b6]) => a5.localeCompare(b6)).map(([key, value]) => `${key}=${hashValue(value)}`).join("\n"); - return `${command} -${cwd} -${envKey}`; -} -function pruneExpiredDiscoveryCache(now2) { - for (const [key, value] of discoveryCache.entries()) { - if (value.expiresAt <= now2) discoveryCache.delete(key); - } -} -async function discoverOpenCodeModels(input = {}) { - const command = resolveOpenCodeCommand(input.command); - const cwd = asString(input.cwd, process.cwd()); - const env2 = normalizeEnv(input.env); - let resolvedHome; - try { - resolvedHome = os8.userInfo().homedir || void 0; - } catch { - } - const runtimeEnv = normalizeEnv(ensurePathInEnv({ ...process.env, ...env2, ...resolvedHome ? { HOME: resolvedHome } : {}, OPENCODE_DISABLE_PROJECT_CONFIG: "true" })); - const result = await runChildProcess( - `opencode-models-${Date.now()}-${Math.random().toString(16).slice(2)}`, - command, - ["models"], - { - cwd, - env: runtimeEnv, - timeoutSec: MODELS_DISCOVERY_TIMEOUT_MS / 1e3, - graceSec: 3, - onLog: async () => { - } - } - ); - if (result.timedOut) { - throw new Error(`\`opencode models\` timed out after ${MODELS_DISCOVERY_TIMEOUT_MS / 1e3}s.`); - } - if ((result.exitCode ?? 1) !== 0) { - const detail = firstNonEmptyLine4(result.stderr) || firstNonEmptyLine4(result.stdout); - throw new Error(detail ? `\`opencode models\` failed: ${detail}` : "`opencode models` failed."); - } - return sortModels(parseModelsOutput(result.stdout)); -} -async function discoverOpenCodeModelsCached(input = {}) { - const command = resolveOpenCodeCommand(input.command); - const cwd = asString(input.cwd, process.cwd()); - const env2 = normalizeEnv(input.env); - const key = discoveryCacheKey(command, cwd, env2); - const now2 = Date.now(); - pruneExpiredDiscoveryCache(now2); - const cached4 = discoveryCache.get(key); - if (cached4 && cached4.expiresAt > now2) return cached4.models; - const models8 = await discoverOpenCodeModels({ command, cwd, env: env2 }); - discoveryCache.set(key, { expiresAt: now2 + MODELS_CACHE_TTL_MS, models: models8 }); - return models8; -} -async function ensureOpenCodeModelConfiguredAndAvailable(input) { - const model = asString(input.model, "").trim(); - if (!model) { - throw new Error("OpenCode requires `adapterConfig.model` in provider/model format."); - } - const models8 = await discoverOpenCodeModelsCached({ - command: input.command, - cwd: input.cwd, - env: input.env - }); - if (models8.length === 0) { - throw new Error("OpenCode returned no models. Run `opencode models` and verify provider auth."); - } - if (!models8.some((entry) => entry.id === model)) { - const sample = models8.slice(0, 12).map((entry) => entry.id).join(", "); - throw new Error( - `Configured OpenCode model is unavailable: ${model}. Available models: ${sample}${models8.length > 12 ? ", ..." : ""}` - ); - } - return models8; -} -async function listOpenCodeModels() { - try { - return await discoverOpenCodeModelsCached(); - } catch { - return []; - } -} - -// packages/adapters/opencode-local/src/server/runtime-config.ts -import fs11 from "node:fs/promises"; -import os9 from "node:os"; -import path15 from "node:path"; -function resolveXdgConfigHome(env2) { - return typeof env2.XDG_CONFIG_HOME === "string" && env2.XDG_CONFIG_HOME.trim() || typeof process.env.XDG_CONFIG_HOME === "string" && process.env.XDG_CONFIG_HOME.trim() || path15.join(os9.homedir(), ".config"); -} -function isPlainObject(value) { - return typeof value === "object" && value !== null && !Array.isArray(value); -} -async function readJsonObject(filepath) { - try { - const raw = await fs11.readFile(filepath, "utf8"); - const parsed = JSON.parse(raw); - return isPlainObject(parsed) ? parsed : {}; - } catch { - return {}; - } -} -async function prepareOpenCodeRuntimeConfig(input) { - const skipPermissions = asBoolean(input.config.dangerouslySkipPermissions, true); - if (!skipPermissions) { - return { - env: input.env, - notes: [], - cleanup: async () => { - } - }; - } - const sourceConfigDir = path15.join(resolveXdgConfigHome(input.env), "opencode"); - const runtimeConfigHome = await fs11.mkdtemp(path15.join(os9.tmpdir(), "taskcore-opencode-config-")); - const runtimeConfigDir = path15.join(runtimeConfigHome, "opencode"); - const runtimeConfigPath = path15.join(runtimeConfigDir, "opencode.json"); - await fs11.mkdir(runtimeConfigDir, { recursive: true }); - try { - await fs11.cp(sourceConfigDir, runtimeConfigDir, { - recursive: true, - force: true, - errorOnExist: false, - dereference: false - }); - } catch (err) { - if (err?.code !== "ENOENT") { - throw err; - } - } - const existingConfig = await readJsonObject(runtimeConfigPath); - const existingPermission = isPlainObject(existingConfig.permission) ? existingConfig.permission : {}; - const nextConfig = { - ...existingConfig, - permission: { - ...existingPermission, - external_directory: "allow" - } - }; - await fs11.writeFile(runtimeConfigPath, `${JSON.stringify(nextConfig, null, 2)} -`, "utf8"); - return { - env: { - ...input.env, - XDG_CONFIG_HOME: runtimeConfigHome - }, - notes: [ - "Injected runtime OpenCode config with permission.external_directory=allow to avoid headless approval prompts." - ], - cleanup: async () => { - await fs11.rm(runtimeConfigHome, { recursive: true, force: true }); - } - }; -} - -// packages/adapters/opencode-local/src/server/execute.ts -var __moduleDir5 = path16.dirname(fileURLToPath6(import.meta.url)); -function firstNonEmptyLine5(text3) { - return text3.split(/\r?\n/).map((line3) => line3.trim()).find(Boolean) ?? ""; -} -function parseModelProvider(model) { - if (!model) return null; - const trimmed = model.trim(); - if (!trimmed.includes("/")) return null; - return trimmed.slice(0, trimmed.indexOf("/")).trim() || null; -} -function resolveOpenCodeBiller(env2, provider) { - return inferOpenAiCompatibleBiller(env2, null) ?? provider ?? "unknown"; -} -function claudeSkillsHome() { - return path16.join(os10.homedir(), ".claude", "skills"); -} -async function ensureOpenCodeSkillsInjected(onLog, skillsEntries, desiredSkillNames) { - const skillsHome = claudeSkillsHome(); - await fs12.mkdir(skillsHome, { recursive: true }); - const desiredSet = new Set(desiredSkillNames ?? skillsEntries.map((entry) => entry.key)); - const selectedEntries = skillsEntries.filter((entry) => desiredSet.has(entry.key)); - const removedSkills = await removeMaintainerOnlySkillSymlinks( - skillsHome, - selectedEntries.map((entry) => entry.runtimeName) - ); - for (const skillName of removedSkills) { - await onLog( - "stderr", - `[taskcore] Removed maintainer-only OpenCode skill "${skillName}" from ${skillsHome} -` - ); - } - for (const entry of selectedEntries) { - const target = path16.join(skillsHome, entry.runtimeName); - try { - const result = await ensureTaskcoreSkillSymlink(entry.source, target); - if (result === "skipped") continue; - await onLog( - "stderr", - `[taskcore] ${result === "repaired" ? "Repaired" : "Injected"} OpenCode skill "${entry.key}" into ${skillsHome} -` - ); - } catch (err) { - await onLog( - "stderr", - `[taskcore] Failed to inject OpenCode skill "${entry.key}" into ${skillsHome}: ${err instanceof Error ? err.message : String(err)} -` - ); - } - } -} -async function execute3(ctx) { - const { runId, agent, runtime, config: config3, context, onLog, onMeta, onSpawn, authToken } = ctx; - const promptTemplate = asString( - config3.promptTemplate, - "You are agent {{agent.id}} ({{agent.name}}). Continue your Taskcore work." - ); - const command = asString(config3.command, "opencode"); - const model = asString(config3.model, "").trim(); - const variant = asString(config3.variant, "").trim(); - const workspaceContext = parseObject(context.taskcoreWorkspace); - const workspaceCwd = asString(workspaceContext.cwd, ""); - const workspaceSource = asString(workspaceContext.source, ""); - const workspaceId = asString(workspaceContext.workspaceId, ""); - const workspaceRepoUrl = asString(workspaceContext.repoUrl, ""); - const workspaceRepoRef = asString(workspaceContext.repoRef, ""); - const agentHome = asString(workspaceContext.agentHome, ""); - const workspaceHints = Array.isArray(context.taskcoreWorkspaces) ? context.taskcoreWorkspaces.filter( - (value) => typeof value === "object" && value !== null - ) : []; - const configuredCwd = asString(config3.cwd, ""); - const useConfiguredInsteadOfAgentHome = workspaceSource === "agent_home" && configuredCwd.length > 0; - const effectiveWorkspaceCwd = useConfiguredInsteadOfAgentHome ? "" : workspaceCwd; - const cwd = effectiveWorkspaceCwd || configuredCwd || process.cwd(); - await ensureAbsoluteDirectory(cwd, { createIfMissing: true }); - const openCodeSkillEntries = await readTaskcoreRuntimeSkillEntries(config3, __moduleDir5); - const desiredOpenCodeSkillNames = resolveTaskcoreDesiredSkillNames(config3, openCodeSkillEntries); - await ensureOpenCodeSkillsInjected( - onLog, - openCodeSkillEntries, - desiredOpenCodeSkillNames - ); - const envConfig = parseObject(config3.env); - const hasExplicitApiKey = typeof envConfig.TASKCORE_API_KEY === "string" && envConfig.TASKCORE_API_KEY.trim().length > 0; - const env2 = { ...buildTaskcoreEnv(agent) }; - env2.TASKCORE_RUN_ID = runId; - const wakeTaskId = typeof context.taskId === "string" && context.taskId.trim().length > 0 && context.taskId.trim() || typeof context.issueId === "string" && context.issueId.trim().length > 0 && context.issueId.trim() || null; - const wakeReason = typeof context.wakeReason === "string" && context.wakeReason.trim().length > 0 ? context.wakeReason.trim() : null; - const wakeCommentId = typeof context.wakeCommentId === "string" && context.wakeCommentId.trim().length > 0 && context.wakeCommentId.trim() || typeof context.commentId === "string" && context.commentId.trim().length > 0 && context.commentId.trim() || null; - const approvalId = typeof context.approvalId === "string" && context.approvalId.trim().length > 0 ? context.approvalId.trim() : null; - const approvalStatus = typeof context.approvalStatus === "string" && context.approvalStatus.trim().length > 0 ? context.approvalStatus.trim() : null; - const linkedIssueIds = Array.isArray(context.issueIds) ? context.issueIds.filter((value) => typeof value === "string" && value.trim().length > 0) : []; - const wakePayloadJson = stringifyTaskcoreWakePayload(context.taskcoreWake); - if (wakeTaskId) env2.TASKCORE_TASK_ID = wakeTaskId; - if (wakeReason) env2.TASKCORE_WAKE_REASON = wakeReason; - if (wakeCommentId) env2.TASKCORE_WAKE_COMMENT_ID = wakeCommentId; - if (approvalId) env2.TASKCORE_APPROVAL_ID = approvalId; - if (approvalStatus) env2.TASKCORE_APPROVAL_STATUS = approvalStatus; - if (linkedIssueIds.length > 0) env2.TASKCORE_LINKED_ISSUE_IDS = linkedIssueIds.join(","); - if (wakePayloadJson) env2.TASKCORE_WAKE_PAYLOAD_JSON = wakePayloadJson; - if (effectiveWorkspaceCwd) env2.TASKCORE_WORKSPACE_CWD = effectiveWorkspaceCwd; - if (workspaceSource) env2.TASKCORE_WORKSPACE_SOURCE = workspaceSource; - if (workspaceId) env2.TASKCORE_WORKSPACE_ID = workspaceId; - if (workspaceRepoUrl) env2.TASKCORE_WORKSPACE_REPO_URL = workspaceRepoUrl; - if (workspaceRepoRef) env2.TASKCORE_WORKSPACE_REPO_REF = workspaceRepoRef; - if (agentHome) env2.AGENT_HOME = agentHome; - if (workspaceHints.length > 0) env2.TASKCORE_WORKSPACES_JSON = JSON.stringify(workspaceHints); - for (const [key, value] of Object.entries(envConfig)) { - if (typeof value === "string") env2[key] = value; - } - env2.OPENCODE_DISABLE_PROJECT_CONFIG = "true"; - if (!hasExplicitApiKey && authToken) { - env2.TASKCORE_API_KEY = authToken; - } - const preparedRuntimeConfig = await prepareOpenCodeRuntimeConfig({ env: env2, config: config3 }); - try { - const runtimeEnv = Object.fromEntries( - Object.entries(ensurePathInEnv({ ...process.env, ...preparedRuntimeConfig.env })).filter( - (entry) => typeof entry[1] === "string" - ) - ); - await ensureCommandResolvable(command, cwd, runtimeEnv); - const resolvedCommand = await resolveCommandForLogs(command, cwd, runtimeEnv); - const loggedEnv = buildInvocationEnvForLogs(preparedRuntimeConfig.env, { - runtimeEnv, - includeRuntimeKeys: ["HOME"], - resolvedCommand - }); - await ensureOpenCodeModelConfiguredAndAvailable({ - model, - command, - cwd, - env: runtimeEnv - }); - const timeoutSec = asNumber(config3.timeoutSec, 0); - const graceSec = asNumber(config3.graceSec, 20); - const extraArgs = (() => { - const fromExtraArgs = asStringArray(config3.extraArgs); - if (fromExtraArgs.length > 0) return fromExtraArgs; - return asStringArray(config3.args); - })(); - const runtimeSessionParams = parseObject(runtime.sessionParams); - const runtimeSessionId = asString(runtimeSessionParams.sessionId, runtime.sessionId ?? ""); - const runtimeSessionCwd = asString(runtimeSessionParams.cwd, ""); - const canResumeSession = runtimeSessionId.length > 0 && (runtimeSessionCwd.length === 0 || path16.resolve(runtimeSessionCwd) === path16.resolve(cwd)); - const sessionId = canResumeSession ? runtimeSessionId : null; - if (runtimeSessionId && !canResumeSession) { - await onLog( - "stdout", - `[taskcore] OpenCode session "${runtimeSessionId}" was saved for cwd "${runtimeSessionCwd}" and will not be resumed in "${cwd}". -` - ); - } - const instructionsFilePath = asString(config3.instructionsFilePath, "").trim(); - const resolvedInstructionsFilePath = instructionsFilePath ? path16.resolve(cwd, instructionsFilePath) : ""; - const instructionsDir = resolvedInstructionsFilePath ? `${path16.dirname(resolvedInstructionsFilePath)}/` : ""; - let instructionsPrefix = ""; - if (resolvedInstructionsFilePath) { - try { - const instructionsContents = await fs12.readFile(resolvedInstructionsFilePath, "utf8"); - instructionsPrefix = `${instructionsContents} - -The above agent instructions were loaded from ${resolvedInstructionsFilePath}. Resolve any relative file references from ${instructionsDir}. - -`; - } catch (err) { - const reason = err instanceof Error ? err.message : String(err); - await onLog( - "stdout", - `[taskcore] Warning: could not read agent instructions file "${resolvedInstructionsFilePath}": ${reason} -` - ); - } - } - const commandNotes = (() => { - const notes = [...preparedRuntimeConfig.notes]; - if (!resolvedInstructionsFilePath) return notes; - if (instructionsPrefix.length > 0) { - notes.push(`Loaded agent instructions from ${resolvedInstructionsFilePath}`); - notes.push( - `Prepended instructions + path directive to stdin prompt (relative references from ${instructionsDir}).` - ); - return notes; - } - notes.push( - `Configured instructionsFilePath ${resolvedInstructionsFilePath}, but file could not be read; continuing without injected instructions.` - ); - return notes; - })(); - const bootstrapPromptTemplate = asString(config3.bootstrapPromptTemplate, ""); - const templateData = { - agentId: agent.id, - companyId: agent.companyId, - runId, - company: { id: agent.companyId }, - agent, - run: { id: runId, source: "on_demand" }, - context - }; - const renderedBootstrapPrompt = !sessionId && bootstrapPromptTemplate.trim().length > 0 ? renderTemplate(bootstrapPromptTemplate, templateData).trim() : ""; - const wakePrompt = renderTaskcoreWakePrompt(context.taskcoreWake, { resumedSession: Boolean(sessionId) }); - const shouldUseResumeDeltaPrompt = Boolean(sessionId) && wakePrompt.length > 0; - const renderedPrompt = shouldUseResumeDeltaPrompt ? "" : renderTemplate(promptTemplate, templateData); - const sessionHandoffNote = asString(context.taskcoreSessionHandoffMarkdown, "").trim(); - const prompt = joinPromptSections([ - instructionsPrefix, - renderedBootstrapPrompt, - wakePrompt, - sessionHandoffNote, - renderedPrompt - ]); - const promptMetrics = { - promptChars: prompt.length, - instructionsChars: instructionsPrefix.length, - bootstrapPromptChars: renderedBootstrapPrompt.length, - wakePromptChars: wakePrompt.length, - sessionHandoffChars: sessionHandoffNote.length, - heartbeatPromptChars: renderedPrompt.length - }; - const buildArgs = (resumeSessionId) => { - const args = ["run", "--format", "json"]; - if (resumeSessionId) args.push("--session", resumeSessionId); - if (model) args.push("--model", model); - if (variant) args.push("--variant", variant); - if (extraArgs.length > 0) args.push(...extraArgs); - return args; - }; - const runAttempt = async (resumeSessionId) => { - const args = buildArgs(resumeSessionId); - if (onMeta) { - await onMeta({ - adapterType: "opencode_local", - command: resolvedCommand, - cwd, - commandNotes, - commandArgs: [...args, ``], - env: loggedEnv, - prompt, - promptMetrics, - context - }); - } - const proc = await runChildProcess(runId, command, args, { - cwd, - env: runtimeEnv, - stdin: prompt, - timeoutSec, - graceSec, - onSpawn, - onLog - }); - return { - proc, - rawStderr: proc.stderr, - parsed: parseOpenCodeJsonl(proc.stdout) - }; - }; - const toResult = (attempt, clearSessionOnMissingSession = false) => { - if (attempt.proc.timedOut) { - return { - exitCode: attempt.proc.exitCode, - signal: attempt.proc.signal, - timedOut: true, - errorMessage: `Timed out after ${timeoutSec}s`, - clearSession: clearSessionOnMissingSession - }; - } - const resolvedSessionId = attempt.parsed.sessionId ?? (clearSessionOnMissingSession ? null : runtimeSessionId ?? runtime.sessionId ?? null); - const resolvedSessionParams = resolvedSessionId ? { - sessionId: resolvedSessionId, - cwd, - ...workspaceId ? { workspaceId } : {}, - ...workspaceRepoUrl ? { repoUrl: workspaceRepoUrl } : {}, - ...workspaceRepoRef ? { repoRef: workspaceRepoRef } : {} - } : null; - const parsedError = typeof attempt.parsed.errorMessage === "string" ? attempt.parsed.errorMessage.trim() : ""; - const stderrLine = firstNonEmptyLine5(attempt.proc.stderr); - const rawExitCode = attempt.proc.exitCode; - const synthesizedExitCode = parsedError && (rawExitCode ?? 0) === 0 ? 1 : rawExitCode; - const fallbackErrorMessage = parsedError || stderrLine || `OpenCode exited with code ${synthesizedExitCode ?? -1}`; - const modelId = model || null; - return { - exitCode: synthesizedExitCode, - signal: attempt.proc.signal, - timedOut: false, - errorMessage: (synthesizedExitCode ?? 0) === 0 ? null : fallbackErrorMessage, - usage: { - inputTokens: attempt.parsed.usage.inputTokens, - outputTokens: attempt.parsed.usage.outputTokens, - cachedInputTokens: attempt.parsed.usage.cachedInputTokens - }, - sessionId: resolvedSessionId, - sessionParams: resolvedSessionParams, - sessionDisplayId: resolvedSessionId, - provider: parseModelProvider(modelId), - biller: resolveOpenCodeBiller(runtimeEnv, parseModelProvider(modelId)), - model: modelId, - billingType: "unknown", - costUsd: attempt.parsed.costUsd, - resultJson: { - stdout: attempt.proc.stdout, - stderr: attempt.proc.stderr - }, - summary: attempt.parsed.summary, - clearSession: Boolean(clearSessionOnMissingSession && !attempt.parsed.sessionId) - }; - }; - const initial = await runAttempt(sessionId); - const initialFailed = !initial.proc.timedOut && ((initial.proc.exitCode ?? 0) !== 0 || Boolean(initial.parsed.errorMessage)); - if (sessionId && initialFailed && isOpenCodeUnknownSessionError(initial.proc.stdout, initial.rawStderr)) { - await onLog( - "stdout", - `[taskcore] OpenCode session "${sessionId}" is unavailable; retrying with a fresh session. -` - ); - const retry = await runAttempt(null); - return toResult(retry, true); - } - return toResult(initial); - } finally { - await preparedRuntimeConfig.cleanup(); - } -} - -// packages/adapters/opencode-local/src/server/skills.ts -import fs13 from "node:fs/promises"; -import os11 from "node:os"; -import path17 from "node:path"; -import { fileURLToPath as fileURLToPath7 } from "node:url"; -var __moduleDir6 = path17.dirname(fileURLToPath7(import.meta.url)); -function asString3(value) { - return typeof value === "string" && value.trim().length > 0 ? value.trim() : null; -} -function resolveOpenCodeSkillsHome(config3) { - const env2 = typeof config3.env === "object" && config3.env !== null && !Array.isArray(config3.env) ? config3.env : {}; - const configuredHome = asString3(env2.HOME); - const home = configuredHome ? path17.resolve(configuredHome) : os11.homedir(); - return path17.join(home, ".claude", "skills"); -} -async function buildOpenCodeSkillSnapshot(config3) { - const availableEntries = await readTaskcoreRuntimeSkillEntries(config3, __moduleDir6); - const desiredSkills = resolveTaskcoreDesiredSkillNames(config3, availableEntries); - const skillsHome = resolveOpenCodeSkillsHome(config3); - const installed = await readInstalledSkillTargets(skillsHome); - return buildPersistentSkillSnapshot({ - adapterType: "opencode_local", - availableEntries, - desiredSkills, - installed, - skillsHome, - locationLabel: "~/.claude/skills", - installedDetail: "Installed in the shared Claude/OpenCode skills home.", - missingDetail: "Configured but not currently linked into the shared Claude/OpenCode skills home.", - externalConflictDetail: "Skill name is occupied by an external installation in the shared skills home.", - externalDetail: "Installed outside Taskcore management in the shared skills home.", - warnings: [ - "OpenCode currently uses the shared Claude skills home (~/.claude/skills)." - ] - }); -} -async function listOpenCodeSkills(ctx) { - return buildOpenCodeSkillSnapshot(ctx.config); -} -async function syncOpenCodeSkills(ctx, desiredSkills) { - const availableEntries = await readTaskcoreRuntimeSkillEntries(ctx.config, __moduleDir6); - const desiredSet = /* @__PURE__ */ new Set([ - ...desiredSkills, - ...availableEntries.filter((entry) => entry.required).map((entry) => entry.key) - ]); - const skillsHome = resolveOpenCodeSkillsHome(ctx.config); - await fs13.mkdir(skillsHome, { recursive: true }); - const installed = await readInstalledSkillTargets(skillsHome); - const availableByRuntimeName = new Map(availableEntries.map((entry) => [entry.runtimeName, entry])); - for (const available of availableEntries) { - if (!desiredSet.has(available.key)) continue; - const target = path17.join(skillsHome, available.runtimeName); - await ensureTaskcoreSkillSymlink(available.source, target); - } - for (const [name, installedEntry] of installed.entries()) { - const available = availableByRuntimeName.get(name); - if (!available) continue; - if (desiredSet.has(available.key)) continue; - if (installedEntry.targetPath !== available.source) continue; - await fs13.unlink(path17.join(skillsHome, name)).catch(() => { - }); - } - return buildOpenCodeSkillSnapshot(ctx.config); -} - -// packages/adapters/opencode-local/src/server/test.ts -function summarizeStatus3(checks) { - if (checks.some((check3) => check3.level === "error")) return "fail"; - if (checks.some((check3) => check3.level === "warn")) return "warn"; - return "pass"; -} -function firstNonEmptyLine6(text3) { - return text3.split(/\r?\n/).map((line3) => line3.trim()).find(Boolean) ?? ""; -} -function summarizeProbeDetail3(stdout, stderr, parsedError) { - const raw = parsedError?.trim() || firstNonEmptyLine6(stderr) || firstNonEmptyLine6(stdout); - if (!raw) return null; - const clean3 = raw.replace(/\s+/g, " ").trim(); - const max = 240; - return clean3.length > max ? `${clean3.slice(0, max - 1)}...` : clean3; -} -function normalizeEnv2(input) { - if (typeof input !== "object" || input === null || Array.isArray(input)) return {}; - const env2 = {}; - for (const [key, value] of Object.entries(input)) { - if (typeof value === "string") env2[key] = value; - } - return env2; -} -var OPENCODE_AUTH_REQUIRED_RE = /(?:auth(?:entication)?\s+required|api\s*key|invalid\s*api\s*key|not\s+logged\s+in|opencode\s+auth\s+login|free\s+usage\s+exceeded)/i; -async function testEnvironment3(ctx) { - const checks = []; - const config3 = parseObject(ctx.config); - const command = asString(config3.command, "opencode"); - const cwd = asString(config3.cwd, process.cwd()); - try { - await ensureAbsoluteDirectory(cwd, { createIfMissing: false }); - checks.push({ - code: "opencode_cwd_valid", - level: "info", - message: `Working directory is valid: ${cwd}` - }); - } catch (err) { - checks.push({ - code: "opencode_cwd_invalid", - level: "error", - message: err instanceof Error ? err.message : "Invalid working directory", - detail: cwd - }); - } - const envConfig = parseObject(config3.env); - const env2 = {}; - for (const [key, value] of Object.entries(envConfig)) { - if (typeof value === "string") env2[key] = value; - } - const openaiKeyOverride = "OPENAI_API_KEY" in envConfig ? asString(envConfig.OPENAI_API_KEY, "") : null; - if (openaiKeyOverride !== null && openaiKeyOverride.trim() === "") { - checks.push({ - code: "opencode_openai_api_key_missing", - level: "warn", - message: "OPENAI_API_KEY override is empty.", - hint: "The OPENAI_API_KEY override is empty. Set a valid key or remove the override." - }); - } - env2.OPENCODE_DISABLE_PROJECT_CONFIG = "true"; - const preparedRuntimeConfig = await prepareOpenCodeRuntimeConfig({ env: env2, config: config3 }); - if (asBoolean(config3.dangerouslySkipPermissions, true)) { - checks.push({ - code: "opencode_headless_permissions_enabled", - level: "info", - message: "Headless OpenCode external-directory permissions are auto-approved for unattended runs." - }); - } - try { - const runtimeEnv = normalizeEnv2(ensurePathInEnv({ ...process.env, ...preparedRuntimeConfig.env })); - const cwdInvalid = checks.some((check3) => check3.code === "opencode_cwd_invalid"); - if (cwdInvalid) { - checks.push({ - code: "opencode_command_skipped", - level: "warn", - message: "Skipped command check because working directory validation failed.", - detail: command - }); - } else { - try { - await ensureCommandResolvable(command, cwd, runtimeEnv); - checks.push({ - code: "opencode_command_resolvable", - level: "info", - message: `Command is executable: ${command}` - }); - } catch (err) { - checks.push({ - code: "opencode_command_unresolvable", - level: "error", - message: err instanceof Error ? err.message : "Command is not executable", - detail: command - }); - } - } - const canRunProbe = checks.every((check3) => check3.code !== "opencode_cwd_invalid" && check3.code !== "opencode_command_unresolvable"); - let modelValidationPassed = false; - const configuredModel = asString(config3.model, "").trim(); - if (canRunProbe && configuredModel) { - try { - const discovered = await discoverOpenCodeModels({ command, cwd, env: runtimeEnv }); - if (discovered.length > 0) { - checks.push({ - code: "opencode_models_discovered", - level: "info", - message: `Discovered ${discovered.length} model(s) from OpenCode providers.` - }); - } else { - checks.push({ - code: "opencode_models_empty", - level: "error", - message: "OpenCode returned no models.", - hint: "Run `opencode models` and verify provider authentication." - }); - } - } catch (err) { - const errMsg = err instanceof Error ? err.message : String(err); - if (/ProviderModelNotFoundError/i.test(errMsg)) { - checks.push({ - code: "opencode_hello_probe_model_unavailable", - level: "warn", - message: "The configured model was not found by the provider.", - detail: errMsg, - hint: "Run `opencode models` and choose an available provider/model ID." - }); - } else { - checks.push({ - code: "opencode_models_discovery_failed", - level: "error", - message: errMsg || "OpenCode model discovery failed.", - hint: "Run `opencode models` manually to verify provider auth and config." - }); - } - } - } else if (canRunProbe && !configuredModel) { - try { - const discovered = await discoverOpenCodeModels({ command, cwd, env: runtimeEnv }); - if (discovered.length > 0) { - checks.push({ - code: "opencode_models_discovered", - level: "info", - message: `Discovered ${discovered.length} model(s) from OpenCode providers.` - }); - } - } catch (err) { - const errMsg = err instanceof Error ? err.message : String(err); - if (/ProviderModelNotFoundError/i.test(errMsg)) { - checks.push({ - code: "opencode_hello_probe_model_unavailable", - level: "warn", - message: "The configured model was not found by the provider.", - detail: errMsg, - hint: "Run `opencode models` and choose an available provider/model ID." - }); - } else { - checks.push({ - code: "opencode_models_discovery_failed", - level: "warn", - message: errMsg || "OpenCode model discovery failed (best-effort, no model configured).", - hint: "Run `opencode models` manually to verify provider auth and config." - }); - } - } - } - const modelUnavailable = checks.some((check3) => check3.code === "opencode_hello_probe_model_unavailable"); - if (!configuredModel && !modelUnavailable) { - } else if (configuredModel && canRunProbe) { - try { - await ensureOpenCodeModelConfiguredAndAvailable({ - model: configuredModel, - command, - cwd, - env: runtimeEnv - }); - checks.push({ - code: "opencode_model_configured", - level: "info", - message: `Configured model: ${configuredModel}` - }); - modelValidationPassed = true; - } catch (err) { - checks.push({ - code: "opencode_model_invalid", - level: "error", - message: err instanceof Error ? err.message : "Configured model is unavailable.", - hint: "Run `opencode models` and choose a currently available provider/model ID." - }); - } - } - if (canRunProbe && modelValidationPassed) { - const extraArgs = (() => { - const fromExtraArgs = asStringArray(config3.extraArgs); - if (fromExtraArgs.length > 0) return fromExtraArgs; - return asStringArray(config3.args); - })(); - const variant = asString(config3.variant, "").trim(); - const probeModel = configuredModel; - const args = ["run", "--format", "json"]; - args.push("--model", probeModel); - if (variant) args.push("--variant", variant); - if (extraArgs.length > 0) args.push(...extraArgs); - try { - const probe = await runChildProcess( - `opencode-envtest-${Date.now()}-${Math.random().toString(16).slice(2)}`, - command, - args, - { - cwd, - env: runtimeEnv, - timeoutSec: 60, - graceSec: 5, - stdin: "Respond with hello.", - onLog: async () => { - } - } - ); - const parsed = parseOpenCodeJsonl(probe.stdout); - const detail = summarizeProbeDetail3(probe.stdout, probe.stderr, parsed.errorMessage); - const authEvidence = `${parsed.errorMessage ?? ""} -${probe.stdout} -${probe.stderr}`.trim(); - if (probe.timedOut) { - checks.push({ - code: "opencode_hello_probe_timed_out", - level: "warn", - message: "OpenCode hello probe timed out.", - hint: "Retry the probe. If this persists, run OpenCode manually in this working directory." - }); - } else if ((probe.exitCode ?? 1) === 0 && !parsed.errorMessage) { - const summary = parsed.summary.trim(); - const hasHello = /\bhello\b/i.test(summary); - checks.push({ - code: hasHello ? "opencode_hello_probe_passed" : "opencode_hello_probe_unexpected_output", - level: hasHello ? "info" : "warn", - message: hasHello ? "OpenCode hello probe succeeded." : "OpenCode probe ran but did not return `hello` as expected.", - ...summary ? { detail: summary.replace(/\s+/g, " ").trim().slice(0, 240) } : {}, - ...hasHello ? {} : { - hint: "Run `opencode run --format json` manually and prompt `Respond with hello` to inspect output." - } - }); - } else if (/ProviderModelNotFoundError/i.test(authEvidence)) { - checks.push({ - code: "opencode_hello_probe_model_unavailable", - level: "warn", - message: "The configured model was not found by the provider.", - ...detail ? { detail } : {}, - hint: "Run `opencode models` and choose an available provider/model ID." - }); - } else if (OPENCODE_AUTH_REQUIRED_RE.test(authEvidence)) { - checks.push({ - code: "opencode_hello_probe_auth_required", - level: "warn", - message: "OpenCode is installed, but provider authentication is not ready.", - ...detail ? { detail } : {}, - hint: "Run `opencode auth login` or set provider credentials, then retry the probe." - }); - } else { - checks.push({ - code: "opencode_hello_probe_failed", - level: "error", - message: "OpenCode hello probe failed.", - ...detail ? { detail } : {}, - hint: "Run `opencode run --format json` manually in this working directory to debug." - }); - } - } catch (err) { - checks.push({ - code: "opencode_hello_probe_failed", - level: "error", - message: "OpenCode hello probe failed.", - detail: err instanceof Error ? err.message : String(err), - hint: "Run `opencode run --format json` manually in this working directory to debug." - }); - } - } - } finally { - await preparedRuntimeConfig.cleanup(); - } - return { - adapterType: ctx.adapterType, - status: summarizeStatus3(checks), - checks, - testedAt: (/* @__PURE__ */ new Date()).toISOString() - }; -} - -// packages/adapters/opencode-local/src/server/index.ts -function readNonEmptyString4(value) { - return typeof value === "string" && value.trim().length > 0 ? value.trim() : null; -} -var sessionCodec3 = { - deserialize(raw) { - if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return null; - const record2 = raw; - const sessionId = readNonEmptyString4(record2.sessionId) ?? readNonEmptyString4(record2.session_id) ?? readNonEmptyString4(record2.sessionID); - if (!sessionId) return null; - const cwd = readNonEmptyString4(record2.cwd) ?? readNonEmptyString4(record2.workdir) ?? readNonEmptyString4(record2.folder); - const workspaceId = readNonEmptyString4(record2.workspaceId) ?? readNonEmptyString4(record2.workspace_id); - const repoUrl = readNonEmptyString4(record2.repoUrl) ?? readNonEmptyString4(record2.repo_url); - const repoRef = readNonEmptyString4(record2.repoRef) ?? readNonEmptyString4(record2.repo_ref); - return { - sessionId, - ...cwd ? { cwd } : {}, - ...workspaceId ? { workspaceId } : {}, - ...repoUrl ? { repoUrl } : {}, - ...repoRef ? { repoRef } : {} - }; - }, - serialize(params) { - if (!params) return null; - const sessionId = readNonEmptyString4(params.sessionId) ?? readNonEmptyString4(params.session_id) ?? readNonEmptyString4(params.sessionID); - if (!sessionId) return null; - const cwd = readNonEmptyString4(params.cwd) ?? readNonEmptyString4(params.workdir) ?? readNonEmptyString4(params.folder); - const workspaceId = readNonEmptyString4(params.workspaceId) ?? readNonEmptyString4(params.workspace_id); - const repoUrl = readNonEmptyString4(params.repoUrl) ?? readNonEmptyString4(params.repo_url); - const repoRef = readNonEmptyString4(params.repoRef) ?? readNonEmptyString4(params.repo_ref); - return { - sessionId, - ...cwd ? { cwd } : {}, - ...workspaceId ? { workspaceId } : {}, - ...repoUrl ? { repoUrl } : {}, - ...repoRef ? { repoRef } : {} - }; - }, - getDisplayId(params) { - if (!params) return null; - return readNonEmptyString4(params.sessionId) ?? readNonEmptyString4(params.session_id) ?? readNonEmptyString4(params.sessionID); - } -}; - -// server/src/services/agent-instructions.ts -import fs14 from "node:fs/promises"; -import path18 from "node:path"; -var ENTRY_FILE_DEFAULT = "AGENTS.md"; -var MODE_KEY = "instructionsBundleMode"; -var ROOT_KEY = "instructionsRootPath"; -var ENTRY_KEY = "instructionsEntryFile"; -var FILE_KEY = "instructionsFilePath"; -var PROMPT_KEY = "promptTemplate"; -var BOOTSTRAP_PROMPT_KEY = "bootstrapPromptTemplate"; -var LEGACY_PROMPT_TEMPLATE_PATH = "promptTemplate.legacy.md"; -var IGNORED_INSTRUCTIONS_FILE_NAMES = /* @__PURE__ */ new Set([".DS_Store", "Thumbs.db", "Desktop.ini"]); -var IGNORED_INSTRUCTIONS_DIRECTORY_NAMES = /* @__PURE__ */ new Set([ - ".git", - ".nox", - ".pytest_cache", - ".ruff_cache", - ".tox", - ".venv", - "__pycache__", - "node_modules", - "venv" -]); -function asRecord2(value) { - if (typeof value !== "object" || value === null || Array.isArray(value)) return {}; - return value; -} -function asString4(value) { - if (typeof value !== "string") return null; - const trimmed = value.trim(); - return trimmed.length > 0 ? trimmed : null; -} -function isBundleMode(value) { - return value === "managed" || value === "external"; -} -function inferLanguage(relativePath) { - const lower = relativePath.toLowerCase(); - if (lower.endsWith(".md")) return "markdown"; - if (lower.endsWith(".json")) return "json"; - if (lower.endsWith(".yaml") || lower.endsWith(".yml")) return "yaml"; - if (lower.endsWith(".ts") || lower.endsWith(".tsx")) return "typescript"; - if (lower.endsWith(".js") || lower.endsWith(".jsx") || lower.endsWith(".mjs") || lower.endsWith(".cjs")) { - return "javascript"; - } - if (lower.endsWith(".sh")) return "bash"; - if (lower.endsWith(".py")) return "python"; - if (lower.endsWith(".toml")) return "toml"; - if (lower.endsWith(".txt")) return "text"; - return "text"; -} -function isMarkdown(relativePath) { - return relativePath.toLowerCase().endsWith(".md"); -} -function normalizeRelativeFilePath(candidatePath) { - const normalized = path18.posix.normalize(candidatePath.replaceAll("\\", "/")).replace(/^\/+/, ""); - if (!normalized || normalized === "." || normalized === ".." || normalized.startsWith("../")) { - throw unprocessable("Instructions file path must stay within the bundle root"); - } - return normalized; -} -function resolvePathWithinRoot(rootPath, relativePath) { - const normalizedRelativePath = normalizeRelativeFilePath(relativePath); - const absoluteRoot = path18.resolve(rootPath); - const absolutePath = path18.resolve(absoluteRoot, normalizedRelativePath); - const relativeToRoot = path18.relative(absoluteRoot, absolutePath); - if (relativeToRoot === ".." || relativeToRoot.startsWith(`..${path18.sep}`)) { - throw unprocessable("Instructions file path must stay within the bundle root"); - } - return absolutePath; -} -function resolveManagedInstructionsRoot(agent) { - return path18.resolve( - resolveTaskcoreInstanceRoot(), - "companies", - agent.companyId, - "agents", - agent.id, - "instructions" - ); -} -function resolveLegacyInstructionsPath(candidatePath, config3) { - if (path18.isAbsolute(candidatePath)) return candidatePath; - const cwd = asString4(config3.cwd); - if (!cwd || !path18.isAbsolute(cwd)) { - throw unprocessable( - "Legacy relative instructionsFilePath requires adapterConfig.cwd to be set to an absolute path" - ); - } - return path18.resolve(cwd, candidatePath); -} -async function statIfExists(targetPath) { - return fs14.stat(targetPath).catch(() => null); -} -function shouldIgnoreInstructionsEntry(entry) { - if (entry.name === "." || entry.name === "..") return true; - if (entry.isDirectory()) { - return IGNORED_INSTRUCTIONS_DIRECTORY_NAMES.has(entry.name); - } - if (!entry.isFile()) return false; - return IGNORED_INSTRUCTIONS_FILE_NAMES.has(entry.name) || entry.name.startsWith("._") || entry.name.endsWith(".pyc") || entry.name.endsWith(".pyo"); -} -async function listFilesRecursive(rootPath) { - const output = []; - async function walk(currentPath, relativeDir) { - const entries2 = await fs14.readdir(currentPath, { withFileTypes: true }).catch(() => []); - for (const entry of entries2) { - if (shouldIgnoreInstructionsEntry(entry)) continue; - const absolutePath = path18.join(currentPath, entry.name); - const relativePath = normalizeRelativeFilePath( - relativeDir ? path18.posix.join(relativeDir, entry.name) : entry.name - ); - if (entry.isDirectory()) { - await walk(absolutePath, relativePath); - continue; - } - if (!entry.isFile()) continue; - output.push(relativePath); - } - } - await walk(rootPath, ""); - return output.sort((left, right) => left.localeCompare(right)); -} -async function readFileSummary(rootPath, relativePath, entryFile) { - const absolutePath = resolvePathWithinRoot(rootPath, relativePath); - const stat5 = await fs14.stat(absolutePath); - return { - path: relativePath, - size: stat5.size, - language: inferLanguage(relativePath), - markdown: isMarkdown(relativePath), - isEntryFile: relativePath === entryFile, - editable: true, - deprecated: false, - virtual: false - }; -} -async function readLegacyInstructions(agent, config3) { - const instructionsFilePath = asString4(config3[FILE_KEY]); - if (instructionsFilePath) { - try { - const resolvedPath2 = resolveLegacyInstructionsPath(instructionsFilePath, config3); - return await fs14.readFile(resolvedPath2, "utf8"); - } catch { - } - } - return asString4(config3[PROMPT_KEY]) ?? ""; -} -function deriveBundleState(agent) { - const config3 = asRecord2(agent.adapterConfig); - const warnings = []; - const storedModeRaw = config3[MODE_KEY]; - const storedRootRaw = asString4(config3[ROOT_KEY]); - const legacyInstructionsPath = asString4(config3[FILE_KEY]); - let mode = isBundleMode(storedModeRaw) ? storedModeRaw : null; - let rootPath = storedRootRaw ? resolveHomeAwarePath(storedRootRaw) : null; - let entryFile = ENTRY_FILE_DEFAULT; - const storedEntryRaw = asString4(config3[ENTRY_KEY]); - if (storedEntryRaw) { - try { - entryFile = normalizeRelativeFilePath(storedEntryRaw); - } catch { - warnings.push(`Ignored invalid instructions entry file "${storedEntryRaw}".`); - } - } - if (!rootPath && legacyInstructionsPath) { - try { - const resolvedLegacyPath = resolveLegacyInstructionsPath(legacyInstructionsPath, config3); - rootPath = path18.dirname(resolvedLegacyPath); - entryFile = path18.basename(resolvedLegacyPath); - mode = resolvedLegacyPath.startsWith(`${resolveManagedInstructionsRoot(agent)}${path18.sep}`) || resolvedLegacyPath === path18.join(resolveManagedInstructionsRoot(agent), entryFile) ? "managed" : "external"; - if (!path18.isAbsolute(legacyInstructionsPath)) { - warnings.push("Using legacy relative instructionsFilePath; migrate this agent to a managed or absolute external bundle."); - } - } catch (err) { - warnings.push(err instanceof Error ? err.message : String(err)); - } - } - const resolvedEntryPath = rootPath ? path18.resolve(rootPath, entryFile) : null; - return { - config: config3, - mode, - rootPath, - entryFile, - resolvedEntryPath, - warnings, - legacyPromptTemplateActive: Boolean(asString4(config3[PROMPT_KEY])), - legacyBootstrapPromptTemplateActive: Boolean(asString4(config3[BOOTSTRAP_PROMPT_KEY])) - }; -} -async function recoverManagedBundleState(agent, state2) { - const managedRootPath = resolveManagedInstructionsRoot(agent); - const stat5 = await statIfExists(managedRootPath); - if (!stat5?.isDirectory()) return state2; - const files = await listFilesRecursive(managedRootPath); - if (files.length === 0) return state2; - const recoveredEntryFile = files.includes(state2.entryFile) ? state2.entryFile : files.includes(ENTRY_FILE_DEFAULT) ? ENTRY_FILE_DEFAULT : files[0]; - if (!state2.rootPath) { - return { - ...state2, - mode: "managed", - rootPath: managedRootPath, - entryFile: recoveredEntryFile, - resolvedEntryPath: path18.resolve(managedRootPath, recoveredEntryFile) - }; - } - if (state2.mode === "external") return state2; - const resolvedConfiguredRoot = path18.resolve(state2.rootPath); - const configuredRootMatchesManaged = resolvedConfiguredRoot === managedRootPath; - const hasEntryMismatch = recoveredEntryFile !== state2.entryFile; - if (configuredRootMatchesManaged && !hasEntryMismatch) { - return state2; - } - const warnings = [...state2.warnings]; - if (!configuredRootMatchesManaged) { - warnings.push( - `Recovered managed instructions from disk at ${managedRootPath}; ignoring stale configured root ${state2.rootPath}.` - ); - } - if (hasEntryMismatch) { - warnings.push( - `Recovered managed instructions entry file from disk as ${recoveredEntryFile}; previous entry ${state2.entryFile} was missing.` - ); - } - return { - ...state2, - mode: "managed", - rootPath: managedRootPath, - entryFile: recoveredEntryFile, - resolvedEntryPath: path18.resolve(managedRootPath, recoveredEntryFile), - warnings - }; -} -function toBundle(agent, state2, files) { - const nextFiles = [...files]; - if (state2.legacyPromptTemplateActive && !nextFiles.some((file2) => file2.path === LEGACY_PROMPT_TEMPLATE_PATH)) { - const legacyPromptTemplate = asString4(state2.config[PROMPT_KEY]) ?? ""; - nextFiles.push({ - path: LEGACY_PROMPT_TEMPLATE_PATH, - size: legacyPromptTemplate.length, - language: "markdown", - markdown: true, - isEntryFile: false, - editable: true, - deprecated: true, - virtual: true - }); - } - nextFiles.sort((left, right) => left.path.localeCompare(right.path)); - return { - agentId: agent.id, - companyId: agent.companyId, - mode: state2.mode, - rootPath: state2.rootPath, - managedRootPath: resolveManagedInstructionsRoot(agent), - entryFile: state2.entryFile, - resolvedEntryPath: state2.resolvedEntryPath, - editable: Boolean(state2.rootPath), - warnings: state2.warnings, - legacyPromptTemplateActive: state2.legacyPromptTemplateActive, - legacyBootstrapPromptTemplateActive: state2.legacyBootstrapPromptTemplateActive, - files: nextFiles - }; -} -function applyBundleConfig(config3, input) { - const next = { - ...config3, - [MODE_KEY]: input.mode, - [ROOT_KEY]: input.rootPath, - [ENTRY_KEY]: input.entryFile, - [FILE_KEY]: path18.resolve(input.rootPath, input.entryFile) - }; - if (input.clearLegacyPromptTemplate) { - delete next[PROMPT_KEY]; - delete next[BOOTSTRAP_PROMPT_KEY]; - } - return next; -} -function buildPersistedBundleConfig(derived, current, options) { - const currentRootPath = current.rootPath ? path18.resolve(current.rootPath) : null; - const derivedRootPath = derived.rootPath ? path18.resolve(derived.rootPath) : null; - const configMatchesRecoveredState = derived.mode === current.mode && derivedRootPath !== null && currentRootPath !== null && derivedRootPath === currentRootPath && derived.entryFile === current.entryFile; - if (configMatchesRecoveredState && !options?.clearLegacyPromptTemplate) { - return current.config; - } - if (!current.rootPath || !current.mode) { - return current.config; - } - return applyBundleConfig(current.config, { - mode: current.mode, - rootPath: current.rootPath, - entryFile: current.entryFile, - clearLegacyPromptTemplate: options?.clearLegacyPromptTemplate - }); -} -async function writeBundleFiles(rootPath, files, options) { - for (const [relativePath, content] of Object.entries(files)) { - const normalizedPath = normalizeRelativeFilePath(relativePath); - const absolutePath = resolvePathWithinRoot(rootPath, normalizedPath); - const existingStat = await statIfExists(absolutePath); - if (existingStat?.isFile() && !options?.overwriteExisting) continue; - await fs14.mkdir(path18.dirname(absolutePath), { recursive: true }); - await fs14.writeFile(absolutePath, content, "utf8"); - } -} -function syncInstructionsBundleConfigFromFilePath(agent, adapterConfig) { - const instructionsFilePath = asString4(adapterConfig[FILE_KEY]); - const next = { ...adapterConfig }; - if (!instructionsFilePath) { - delete next[MODE_KEY]; - delete next[ROOT_KEY]; - delete next[ENTRY_KEY]; - return next; - } - const resolvedPath2 = resolveLegacyInstructionsPath(instructionsFilePath, adapterConfig); - const rootPath = path18.dirname(resolvedPath2); - const entryFile = path18.basename(resolvedPath2); - const mode = resolvedPath2.startsWith(`${resolveManagedInstructionsRoot(agent)}${path18.sep}`) || resolvedPath2 === path18.join(resolveManagedInstructionsRoot(agent), entryFile) ? "managed" : "external"; - return applyBundleConfig(next, { mode, rootPath, entryFile }); -} -function agentInstructionsService() { - async function getBundle(agent) { - const state2 = await recoverManagedBundleState(agent, deriveBundleState(agent)); - if (!state2.rootPath) return toBundle(agent, state2, []); - const stat5 = await statIfExists(state2.rootPath); - if (!stat5?.isDirectory()) { - return toBundle(agent, { - ...state2, - warnings: [...state2.warnings, `Instructions root does not exist: ${state2.rootPath}`] - }, []); - } - const files = await listFilesRecursive(state2.rootPath); - const summaries = await Promise.all(files.map((relativePath) => readFileSummary(state2.rootPath, relativePath, state2.entryFile))); - return toBundle(agent, state2, summaries); - } - async function readFile5(agent, relativePath) { - const state2 = await recoverManagedBundleState(agent, deriveBundleState(agent)); - if (relativePath === LEGACY_PROMPT_TEMPLATE_PATH) { - const content2 = asString4(state2.config[PROMPT_KEY]); - if (content2 === null) throw notFound("Instructions file not found"); - return { - path: LEGACY_PROMPT_TEMPLATE_PATH, - size: content2.length, - language: "markdown", - markdown: true, - isEntryFile: false, - editable: true, - deprecated: true, - virtual: true, - content: content2 - }; - } - if (!state2.rootPath) throw notFound("Agent instructions bundle is not configured"); - const absolutePath = resolvePathWithinRoot(state2.rootPath, relativePath); - const [content, stat5] = await Promise.all([ - fs14.readFile(absolutePath, "utf8").catch(() => null), - fs14.stat(absolutePath).catch(() => null) - ]); - if (content === null || !stat5?.isFile()) throw notFound("Instructions file not found"); - const normalizedPath = normalizeRelativeFilePath(relativePath); - return { - path: normalizedPath, - size: stat5.size, - language: inferLanguage(normalizedPath), - markdown: isMarkdown(normalizedPath), - isEntryFile: normalizedPath === state2.entryFile, - editable: true, - deprecated: false, - virtual: false, - content - }; - } - async function ensureWritableBundle(agent, options) { - const derived = deriveBundleState(agent); - const current = await recoverManagedBundleState(agent, derived); - if (current.rootPath && current.mode) { - const adapterConfig = buildPersistedBundleConfig(derived, current, options); - return { - adapterConfig, - state: deriveBundleState({ ...agent, adapterConfig }) - }; - } - const managedRoot = resolveManagedInstructionsRoot(agent); - const entryFile = current.entryFile || ENTRY_FILE_DEFAULT; - const nextConfig = applyBundleConfig(current.config, { - mode: "managed", - rootPath: managedRoot, - entryFile, - clearLegacyPromptTemplate: options?.clearLegacyPromptTemplate - }); - await fs14.mkdir(managedRoot, { recursive: true }); - const entryPath = resolvePathWithinRoot(managedRoot, entryFile); - const entryStat = await statIfExists(entryPath); - if (!entryStat?.isFile()) { - const legacyInstructions = await readLegacyInstructions(agent, current.config); - if (legacyInstructions.trim().length > 0) { - await fs14.mkdir(path18.dirname(entryPath), { recursive: true }); - await fs14.writeFile(entryPath, legacyInstructions, "utf8"); - } - } - return { - adapterConfig: nextConfig, - state: deriveBundleState({ ...agent, adapterConfig: nextConfig }) - }; - } - async function updateBundle(agent, input) { - const state2 = await recoverManagedBundleState(agent, deriveBundleState(agent)); - const nextMode = input.mode ?? state2.mode ?? "managed"; - const nextEntryFile = input.entryFile ? normalizeRelativeFilePath(input.entryFile) : state2.entryFile; - let nextRootPath; - if (nextMode === "managed") { - nextRootPath = resolveManagedInstructionsRoot(agent); - } else { - const rootPath = asString4(input.rootPath) ?? state2.rootPath; - if (!rootPath) { - throw unprocessable("External instructions bundles require an absolute rootPath"); - } - const resolvedRoot = resolveHomeAwarePath(rootPath); - if (!path18.isAbsolute(resolvedRoot)) { - throw unprocessable("External instructions bundles require an absolute rootPath"); - } - nextRootPath = resolvedRoot; - } - await fs14.mkdir(nextRootPath, { recursive: true }); - const existingFiles = await listFilesRecursive(nextRootPath); - const exported = await exportFiles(agent); - if (existingFiles.length === 0) { - await writeBundleFiles(nextRootPath, exported.files); - } - const refreshedFiles = existingFiles.length === 0 ? await listFilesRecursive(nextRootPath) : existingFiles; - if (!refreshedFiles.includes(nextEntryFile)) { - const nextEntryContent = exported.files[nextEntryFile] ?? exported.files[exported.entryFile] ?? ""; - await writeBundleFiles(nextRootPath, { [nextEntryFile]: nextEntryContent }); - } - const nextConfig = applyBundleConfig(state2.config, { - mode: nextMode, - rootPath: nextRootPath, - entryFile: nextEntryFile, - clearLegacyPromptTemplate: input.clearLegacyPromptTemplate - }); - const nextBundle = await getBundle({ ...agent, adapterConfig: nextConfig }); - return { bundle: nextBundle, adapterConfig: nextConfig }; - } - async function writeFile(agent, relativePath, content, options) { - const current = deriveBundleState(agent); - if (relativePath === LEGACY_PROMPT_TEMPLATE_PATH) { - const adapterConfig = { - ...current.config, - [PROMPT_KEY]: content - }; - const nextAgent2 = { ...agent, adapterConfig }; - const [bundle2, file3] = await Promise.all([ - getBundle(nextAgent2), - readFile5(nextAgent2, LEGACY_PROMPT_TEMPLATE_PATH) - ]); - return { bundle: bundle2, file: file3, adapterConfig }; - } - const prepared = await ensureWritableBundle(agent, options); - const absolutePath = resolvePathWithinRoot(prepared.state.rootPath, relativePath); - await fs14.mkdir(path18.dirname(absolutePath), { recursive: true }); - await fs14.writeFile(absolutePath, content, "utf8"); - const nextAgent = { ...agent, adapterConfig: prepared.adapterConfig }; - const [bundle, file2] = await Promise.all([ - getBundle(nextAgent), - readFile5(nextAgent, relativePath) - ]); - return { bundle, file: file2, adapterConfig: prepared.adapterConfig }; - } - async function deleteFile(agent, relativePath) { - const derived = deriveBundleState(agent); - const state2 = await recoverManagedBundleState(agent, derived); - if (relativePath === LEGACY_PROMPT_TEMPLATE_PATH) { - throw unprocessable("Cannot delete the legacy promptTemplate pseudo-file"); - } - if (!state2.rootPath) throw notFound("Agent instructions bundle is not configured"); - const normalizedPath = normalizeRelativeFilePath(relativePath); - if (normalizedPath === state2.entryFile) { - throw unprocessable("Cannot delete the bundle entry file"); - } - const absolutePath = resolvePathWithinRoot(state2.rootPath, normalizedPath); - await fs14.rm(absolutePath, { force: true }); - const adapterConfig = buildPersistedBundleConfig(derived, state2); - const bundle = await getBundle({ ...agent, adapterConfig }); - return { bundle, adapterConfig }; - } - async function exportFiles(agent) { - const state2 = await recoverManagedBundleState(agent, deriveBundleState(agent)); - if (state2.rootPath) { - const stat5 = await statIfExists(state2.rootPath); - if (stat5?.isDirectory()) { - const relativePaths = await listFilesRecursive(state2.rootPath); - const files = Object.fromEntries(await Promise.all(relativePaths.map(async (relativePath) => { - const absolutePath = resolvePathWithinRoot(state2.rootPath, relativePath); - const content = await fs14.readFile(absolutePath, "utf8"); - return [relativePath, content]; - }))); - if (Object.keys(files).length > 0) { - return { files, entryFile: state2.entryFile, warnings: state2.warnings }; - } - } - } - const legacyBody = await readLegacyInstructions(agent, state2.config); - return { - files: { [state2.entryFile]: legacyBody || "_No AGENTS instructions were resolved from current agent config._" }, - entryFile: state2.entryFile, - warnings: state2.warnings - }; - } - async function materializeManagedBundle(agent, files, options) { - const rootPath = resolveManagedInstructionsRoot(agent); - const entryFile = options?.entryFile ? normalizeRelativeFilePath(options.entryFile) : ENTRY_FILE_DEFAULT; - if (options?.replaceExisting) { - await fs14.rm(rootPath, { recursive: true, force: true }); - } - await fs14.mkdir(rootPath, { recursive: true }); - const normalizedEntries = Object.entries(files).map(([relativePath, content]) => [ - normalizeRelativeFilePath(relativePath), - content - ]); - for (const [relativePath, content] of normalizedEntries) { - const absolutePath = resolvePathWithinRoot(rootPath, relativePath); - await fs14.mkdir(path18.dirname(absolutePath), { recursive: true }); - await fs14.writeFile(absolutePath, content, "utf8"); - } - if (!normalizedEntries.some(([relativePath]) => relativePath === entryFile)) { - await fs14.writeFile(resolvePathWithinRoot(rootPath, entryFile), "", "utf8"); - } - const adapterConfig = applyBundleConfig(asRecord2(agent.adapterConfig), { - mode: "managed", - rootPath, - entryFile, - clearLegacyPromptTemplate: options?.clearLegacyPromptTemplate - }); - const bundle = await getBundle({ ...agent, adapterConfig }); - return { bundle, adapterConfig }; - } - return { - getBundle, - readFile: readFile5, - updateBundle, - writeFile, - deleteFile, - exportFiles, - ensureManagedBundle: ensureWritableBundle, - materializeManagedBundle - }; -} - -// server/src/services/feedback-redaction.ts -import { createHash as createHash5 } from "node:crypto"; - -// server/src/log-redaction.ts -import os12 from "node:os"; -var CURRENT_USER_REDACTION_TOKEN = "*"; -function isPlainObject2(value) { - if (typeof value !== "object" || value === null || Array.isArray(value)) return false; - const proto = Object.getPrototypeOf(value); - return proto === Object.prototype || proto === null; -} -function escapeRegExp(value) { - return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); -} -function uniqueNonEmpty(values2) { - return Array.from(new Set(values2.map((value) => value?.trim() ?? "").filter(Boolean))); -} -function splitPathSegments(value) { - return value.replace(/[\\/]+$/, "").split(/[\\/]+/).filter(Boolean); -} -function replaceLastPathSegment(pathValue, replacement) { - const normalized = pathValue.replace(/[\\/]+$/, ""); - const lastSeparator = Math.max(normalized.lastIndexOf("/"), normalized.lastIndexOf("\\")); - if (lastSeparator < 0) return replacement; - return `${normalized.slice(0, lastSeparator + 1)}${replacement}`; -} -function maskUserNameForLogs(value, fallback = CURRENT_USER_REDACTION_TOKEN) { - const trimmed = value.trim(); - if (!trimmed) return fallback; - return `${trimmed[0]}${"*".repeat(Math.max(1, Array.from(trimmed).length - 1))}`; -} -function defaultUserNames() { - const candidates = [ - process.env.USER, - process.env.LOGNAME, - process.env.USERNAME - ]; - try { - candidates.push(os12.userInfo().username); - } catch { - } - return uniqueNonEmpty(candidates); -} -function defaultHomeDirs(userNames) { - const candidates = [ - process.env.HOME, - process.env.USERPROFILE - ]; - try { - candidates.push(os12.homedir()); - } catch { - } - for (const userName of userNames) { - candidates.push(`/Users/${userName}`); - candidates.push(`/home/${userName}`); - candidates.push(`C:\\Users\\${userName}`); - } - return uniqueNonEmpty(candidates); -} -var cachedCurrentUserCandidates = null; -function getDefaultCurrentUserCandidates() { - if (cachedCurrentUserCandidates) return cachedCurrentUserCandidates; - const userNames = defaultUserNames(); - cachedCurrentUserCandidates = { - userNames, - homeDirs: defaultHomeDirs(userNames), - replacement: CURRENT_USER_REDACTION_TOKEN - }; - return cachedCurrentUserCandidates; -} -function resolveCurrentUserCandidates(opts) { - const defaults = getDefaultCurrentUserCandidates(); - const userNames = uniqueNonEmpty(opts?.userNames ?? defaults.userNames); - const homeDirs = uniqueNonEmpty(opts?.homeDirs ?? defaults.homeDirs); - const replacement = opts?.replacement?.trim() || defaults.replacement; - return { userNames, homeDirs, replacement }; -} -function redactCurrentUserText(input, opts) { - if (!input) return input; - if (opts?.enabled === false) return input; - const { userNames, homeDirs, replacement } = resolveCurrentUserCandidates(opts); - let result = input; - for (const homeDir of [...homeDirs].sort((a5, b6) => b6.length - a5.length)) { - const lastSegment = splitPathSegments(homeDir).pop() ?? ""; - const replacementDir = lastSegment ? replaceLastPathSegment(homeDir, maskUserNameForLogs(lastSegment, replacement)) : replacement; - result = result.split(homeDir).join(replacementDir); - } - for (const userName of [...userNames].sort((a5, b6) => b6.length - a5.length)) { - const pattern = new RegExp(`(? redactCurrentUserValue(entry, opts)); - } - if (!isPlainObject2(value)) { - return value; - } - const redacted = {}; - for (const [key, entry] of Object.entries(value)) { - redacted[key] = redactCurrentUserValue(entry, opts); - } - return redacted; -} - -// server/src/redaction.ts -var SECRET_PAYLOAD_KEY_RE = /(api[-_]?key|access[-_]?token|auth(?:_?token)?|authorization|bearer|secret|passwd|password|credential|jwt|private[-_]?key|cookie|connectionstring)/i; -var JWT_VALUE_RE = /^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)?$/; -var REDACTED_EVENT_VALUE = "***REDACTED***"; -function isPlainObject3(value) { - if (typeof value !== "object" || value === null || Array.isArray(value)) return false; - const proto = Object.getPrototypeOf(value); - return proto === Object.prototype || proto === null; -} -function sanitizeValue(value) { - if (value === null || value === void 0) return value; - if (Array.isArray(value)) return value.map(sanitizeValue); - if (isSecretRefBinding(value)) return value; - if (isPlainBinding(value)) return { type: "plain", value: sanitizeValue(value.value) }; - if (!isPlainObject3(value)) return value; - return sanitizeRecord(value); -} -function isSecretRefBinding(value) { - if (!isPlainObject3(value)) return false; - return value.type === "secret_ref" && typeof value.secretId === "string"; -} -function isPlainBinding(value) { - if (!isPlainObject3(value)) return false; - return value.type === "plain" && "value" in value; -} -function sanitizeRecord(record2) { - const redacted = {}; - for (const [key, value] of Object.entries(record2)) { - if (SECRET_PAYLOAD_KEY_RE.test(key)) { - if (isSecretRefBinding(value)) { - redacted[key] = sanitizeValue(value); - continue; - } - if (isPlainBinding(value)) { - redacted[key] = { type: "plain", value: REDACTED_EVENT_VALUE }; - continue; - } - redacted[key] = REDACTED_EVENT_VALUE; - continue; - } - if (typeof value === "string" && JWT_VALUE_RE.test(value)) { - redacted[key] = REDACTED_EVENT_VALUE; - continue; - } - redacted[key] = sanitizeValue(value); - } - return redacted; -} -function redactEventPayload(payload2) { - if (!payload2) return null; - if (!isPlainObject3(payload2)) return payload2; - return sanitizeRecord(payload2); -} - -// server/src/services/feedback-redaction.ts -var SECRET_ASSIGNMENT_RE = /\b(api[-_]?key|access[-_]?token|auth(?:_?token)?|authorization|bearer|secret|passwd|password|credential|jwt|private[-_]?key|cookie|connectionstring)\s*[:=]\s*([^\s,;]+)/gi; -var FREE_TEXT_PATTERNS = [ - { - kind: "pem_block", - regex: /-----BEGIN [^-]+-----[\s\S]+?-----END [^-]+-----/g, - replacement: "[REDACTED_PEM_BLOCK]" - }, - { - kind: "secret_assignment", - regex: SECRET_ASSIGNMENT_RE, - replacement: (_match, key) => `${key}=[REDACTED]` - }, - { - kind: "bearer_token", - regex: /Bearer\s+[A-Za-z0-9._~+/-]+=*/gi, - replacement: "Bearer [REDACTED_TOKEN]" - }, - { - kind: "github_token", - regex: /\bgh[pousr]_[A-Za-z0-9_]{20,}\b/g, - replacement: "[REDACTED_GITHUB_TOKEN]" - }, - { - kind: "provider_api_key", - regex: /\bsk-(?:ant-)?[A-Za-z0-9_-]{12,}\b/g, - replacement: "[REDACTED_API_KEY]" - }, - { - kind: "jwt", - regex: /\b[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)?\b/g, - replacement: "[REDACTED_JWT]" - }, - { - kind: "dsn", - regex: /\b(?:postgres(?:ql)?|mysql|mongodb(?:\+srv)?|redis|amqp|kafka|nats|mssql):\/\/[^\s<>'")]+/gi, - replacement: "[REDACTED_CONNECTION_STRING]" - }, - { - kind: "email", - regex: /\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/gi, - replacement: "[REDACTED_EMAIL]" - }, - { - kind: "phone", - regex: /(? 0) { - output = result.output; - recordField(state2, fieldPath); - increment(state2, pattern.kind, result.matches); - } - } - if (output.length > maxLength) { - output = `${output.slice(0, Math.max(0, maxLength - 1))}...`; - state2.truncatedFields.add(fieldPath); - } - return output; -} -function sanitizeFeedbackValue(value, state2, fieldPath, maxStringLength) { - if (typeof value === "string") { - return sanitizeFeedbackText(value, state2, fieldPath, maxStringLength); - } - if (Array.isArray(value)) { - return value.map((entry, index2) => sanitizeFeedbackValue(entry, state2, `${fieldPath}[${index2}]`, maxStringLength)); - } - if (!isPlainRecord(value)) { - return value; - } - const structurallySanitized = sanitizeRecord(value); - if (stableStringify(structurallySanitized) !== stableStringify(value)) { - recordField(state2, fieldPath); - increment(state2, "structured_secret", 1); - } - const output = {}; - for (const [key, entry] of Object.entries(structurallySanitized)) { - output[key] = sanitizeFeedbackValue(entry, state2, `${fieldPath}.${key}`, maxStringLength); - } - return output; -} -function finalizeFeedbackRedactionSummary(state2) { - return { - strategy: "deterministic_feedback_v2", - redactedFields: Array.from(state2.redactedFields).sort(), - truncatedFields: Array.from(state2.truncatedFields).sort(), - omittedFields: Array.from(state2.omittedFields).sort(), - notes: Array.from(state2.notes).sort(), - counts: Object.fromEntries(Array.from(state2.counts.entries()).sort(([left], [right]) => left.localeCompare(right))) - }; -} -function stableStringify(value) { - if (value === null || typeof value !== "object") { - return JSON.stringify(value); - } - if (Array.isArray(value)) { - return `[${value.map((entry) => stableStringify(entry)).join(",")}]`; - } - const entries2 = Object.entries(value).sort(([left], [right]) => left.localeCompare(right)).map(([key, entry]) => `${JSON.stringify(key)}:${stableStringify(entry)}`); - return `{${entries2.join(",")}}`; -} -function sha256Digest(value) { - return createHash5("sha256").update(stableStringify(value)).digest("hex"); -} - -// server/src/services/run-log-store.ts -import { createReadStream, promises as fs15 } from "node:fs"; -import path19 from "node:path"; -import { createHash as createHash6 } from "node:crypto"; -function safeSegments(...segments) { - return segments.map((segment) => segment.replace(/[^a-zA-Z0-9._-]/g, "_")); -} -function resolveWithin(basePath, relativePath) { - const resolved = path19.resolve(basePath, relativePath); - const base = path19.resolve(basePath) + path19.sep; - if (!resolved.startsWith(base) && resolved !== path19.resolve(basePath)) { - throw new Error("Invalid log path"); - } - return resolved; -} -function createLocalFileRunLogStore(basePath) { - async function ensureDir(relativeDir) { - const dir = resolveWithin(basePath, relativeDir); - await fs15.mkdir(dir, { recursive: true }); - } - async function readFileRange(filePath, offset, limitBytes) { - const stat5 = await fs15.stat(filePath).catch(() => null); - if (!stat5) throw notFound("Run log not found"); - const start = Math.max(0, Math.min(offset, stat5.size)); - const end = Math.max(start, Math.min(start + limitBytes - 1, stat5.size - 1)); - if (start > end) { - return { content: "", nextOffset: start }; - } - const chunks = []; - await new Promise((resolve4, reject) => { - const stream = createReadStream(filePath, { start, end }); - stream.on("data", (chunk) => { - chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)); - }); - stream.on("error", reject); - stream.on("end", () => resolve4()); - }); - const content = Buffer.concat(chunks).toString("utf8"); - const nextOffset = end + 1 < stat5.size ? end + 1 : void 0; - return { content, nextOffset }; - } - async function sha256File(filePath) { - return new Promise((resolve4, reject) => { - const hash2 = createHash6("sha256"); - const stream = createReadStream(filePath); - stream.on("data", (chunk) => hash2.update(chunk)); - stream.on("error", reject); - stream.on("end", () => resolve4(hash2.digest("hex"))); - }); - } - return { - async begin(input) { - const [companyId, agentId] = safeSegments(input.companyId, input.agentId); - const runId = safeSegments(input.runId)[0]; - const relDir = path19.join(companyId, agentId); - const relPath = path19.join(relDir, `${runId}.ndjson`); - await ensureDir(relDir); - const absPath = resolveWithin(basePath, relPath); - await fs15.writeFile(absPath, "", "utf8"); - return { store: "local_file", logRef: relPath }; - }, - async append(handle, event) { - if (handle.store !== "local_file") return; - const absPath = resolveWithin(basePath, handle.logRef); - const line3 = JSON.stringify({ - ts: event.ts, - stream: event.stream, - chunk: event.chunk - }); - await fs15.appendFile(absPath, `${line3} -`, "utf8"); - }, - async finalize(handle) { - if (handle.store !== "local_file") { - return { bytes: 0, compressed: false }; - } - const absPath = resolveWithin(basePath, handle.logRef); - const stat5 = await fs15.stat(absPath).catch(() => null); - if (!stat5) throw notFound("Run log not found"); - const hash2 = await sha256File(absPath); - return { - bytes: stat5.size, - sha256: hash2, - compressed: false - }; - }, - async read(handle, opts) { - if (handle.store !== "local_file") { - throw notFound("Run log not found"); - } - const absPath = resolveWithin(basePath, handle.logRef); - const offset = opts?.offset ?? 0; - const limitBytes = opts?.limitBytes ?? 256e3; - return readFileRange(absPath, offset, limitBytes); - } - }; -} -var cachedStore = null; -function getRunLogStore() { - if (cachedStore) return cachedStore; - const basePath = process.env.RUN_LOG_BASE_PATH ?? path19.resolve(resolveTaskcoreInstanceRoot(), "data", "run-logs"); - cachedStore = createLocalFileRunLogStore(basePath); - return cachedStore; -} - -// server/src/services/feedback.ts -var FEEDBACK_SCHEMA_VERSION = "taskcore-feedback-envelope-v2"; -var FEEDBACK_BUNDLE_VERSION = "taskcore-feedback-bundle-v2"; -var FEEDBACK_PAYLOAD_VERSION = "taskcore-feedback-v1"; -var FEEDBACK_DESTINATION = "taskcore_labs_feedback_v1"; -var FEEDBACK_CONTEXT_WINDOW = 3; -var MAX_EXCERPT_CHARS = 200; -var MAX_PRIMARY_CONTENT_CHARS = 8e3; -var MAX_CONTEXT_ITEM_BODY_CHARS = 3e3; -var MAX_TOTAL_CONTEXT_CHARS = 12e3; -var MAX_DESCRIPTION_CHARS = 1200; -var MAX_INSTRUCTIONS_BODY_CHARS = 8e3; -var MAX_PATH_CHARS = 600; -var MAX_SKILLS = 20; -var MAX_INSTRUCTION_FILES = 20; -var MAX_TRACE_FILE_CHARS = 1e7; -var DEFAULT_INSTANCE_SETTINGS_SINGLETON_KEY = "default"; -var FEEDBACK_EXPORT_BACKEND_NOT_CONFIGURED = "Feedback export backend is not configured"; -var feedbackExportColumns = getTableColumns(feedbackExports); -var instructionsSvc = agentInstructionsService(); -function asRecord3(value) { - if (!value || typeof value !== "object" || Array.isArray(value)) return null; - return value; -} -function asString5(value) { - if (typeof value !== "string") return null; - const trimmed = value.trim(); - return trimmed.length > 0 ? trimmed : null; -} -function asNumber2(value) { - if (typeof value !== "number" || !Number.isFinite(value)) return null; - return value; -} -function asBoolean2(value) { - return typeof value === "boolean" ? value : null; -} -function uniqueNonEmpty2(values2) { - return Array.from(new Set(values2.map((value) => value?.trim() ?? "").filter(Boolean))); -} -function truncateExcerpt(text3, max = MAX_EXCERPT_CHARS) { - const normalized = text3.replace(/\s+/g, " ").trim(); - if (!normalized) return null; - return normalized.length <= max ? normalized : `${normalized.slice(0, max - 1)}...`; -} -function contentTypeForPath(filePath) { - const lower = filePath.toLowerCase(); - if (lower.endsWith(".jsonl") || lower.endsWith(".ndjson")) return "application/x-ndjson"; - if (lower.endsWith(".json")) return "application/json"; - if (lower.endsWith(".md")) return "text/markdown; charset=utf-8"; - return "text/plain; charset=utf-8"; -} -function normalizeInstanceGeneralSettings(raw) { - const parsed = instanceGeneralSettingsSchema.safeParse(raw ?? {}); - if (parsed.success) return parsed.data; - return { - censorUsernameInLogs: false, - feedbackDataSharingPreference: DEFAULT_FEEDBACK_DATA_SHARING_PREFERENCE - }; -} -function buildIssuePath(identifier) { - if (!identifier) return null; - const prefix = identifier.split("-")[0]?.trim(); - if (!prefix) return null; - return `/${prefix}/issues/${identifier}`; -} -function buildTargetSummary(input) { - return { - label: input.label, - excerpt: input.excerpt, - authorAgentId: input.authorAgentId, - authorUserId: input.authorUserId, - createdAt: input.createdAt, - documentKey: input.documentKey ?? null, - documentTitle: input.documentTitle ?? null, - revisionNumber: input.revisionNumber ?? null - }; -} -function normalizeReason(vote, reason) { - if (vote !== "down" || typeof reason !== "string") return null; - const trimmed = reason.trim(); - return trimmed.length > 0 ? trimmed : null; -} -function normalizeSkillReference(value) { - return value.trim().toLowerCase(); -} -function matchesSkillReference(skill, reference) { - const normalized = normalizeSkillReference(reference); - if (!normalized) return false; - if (skill.key.toLowerCase() === normalized) return true; - if (skill.slug.toLowerCase() === normalized) return true; - if (skill.name.toLowerCase() === normalized) return true; - const keyTail = skill.key.split("/").pop()?.toLowerCase(); - return keyTail === normalized; -} -function buildExportId(feedbackVoteId, sharedAt) { - return `fbexp_${sha256Digest(`${feedbackVoteId}:${sharedAt.toISOString()}`).slice(0, 24)}`; -} -function resolveSourceRunId(payloadSnapshot) { - const targetRunId = asString5(asRecord3(payloadSnapshot?.target)?.createdByRunId); - if (targetRunId) return targetRunId; - const bundle = asRecord3(payloadSnapshot?.bundle); - const agentContext = asRecord3(bundle?.agentContext); - const runtime = asRecord3(agentContext?.runtime); - return asString5(asRecord3(runtime?.sourceRun)?.id); -} -function makeBundleFile(input) { - return { - path: input.path, - contentType: input.contentType, - encoding: "utf8", - byteLength: Buffer.byteLength(input.contents, "utf8"), - sha256: sha256Digest(input.contents), - source: input.source, - contents: input.contents - }; -} -function appendNote(notes, note) { - if (note.trim().length === 0 || notes.includes(note)) return; - notes.push(note); -} -async function readTextFileIfPresent(filePath, state2, fieldPath) { - if (!filePath) return null; - const raw = await readFile(filePath, "utf8").catch(() => null); - if (raw == null) return null; - return sanitizeFeedbackText(raw, state2, fieldPath, MAX_TRACE_FILE_CHARS); -} -async function listChildFiles(dirPath) { - const entries2 = await readdir(dirPath, { withFileTypes: true }).catch(() => []); - return entries2.filter((entry) => entry.isFile()).map((entry) => path20.join(dirPath, entry.name)).sort((left, right) => left.localeCompare(right)); -} -async function listNestedFiles(dirPath, maxDepth = 4) { - async function walk(currentPath, depth) { - const entries2 = await readdir(currentPath, { withFileTypes: true }).catch(() => []); - const files = entries2.filter((entry) => entry.isFile()).map((entry) => path20.join(currentPath, entry.name)).sort((left, right) => left.localeCompare(right)); - if (depth >= maxDepth) return files; - const childDirs = entries2.filter((entry) => entry.isDirectory()).map((entry) => path20.join(currentPath, entry.name)).sort((left, right) => left.localeCompare(right)); - const nested = await Promise.all(childDirs.map((childDir) => walk(childDir, depth + 1))); - return [...files, ...nested.flat()]; - } - return walk(dirPath, 0); -} -async function findMatchingFile(rootDir, matcher, maxDepth = 5) { - async function search(dirPath, depth) { - const entries2 = await readdir(dirPath, { withFileTypes: true }).catch(() => []); - for (const entry of entries2) { - const absolutePath = path20.join(dirPath, entry.name); - if (entry.isFile() && matcher(absolutePath, entry.name)) { - return absolutePath; - } - } - if (depth >= maxDepth) return null; - for (const entry of entries2) { - if (!entry.isDirectory()) continue; - const found = await search(path20.join(dirPath, entry.name), depth + 1); - if (found) return found; - } - return null; - } - return search(rootDir, 0); -} -async function readFullRunLog(run) { - if (run.logStore !== "local_file" || !run.logRef) return null; - const store = getRunLogStore(); - let offset = 0; - let combined = ""; - while (true) { - const result = await store.read({ store: "local_file", logRef: run.logRef }, { - offset, - limitBytes: 512e3 - }).catch(() => null); - if (!result) return combined || null; - combined += result.content; - if (result.nextOffset == null) break; - offset = result.nextOffset; - } - return combined || null; -} -function parseRunLogEntries(logText) { - if (!logText) return []; - const entries2 = []; - for (const rawLine of logText.split(/\r?\n/)) { - const line3 = rawLine.trim(); - if (!line3) continue; - try { - const parsed = JSON.parse(line3); - const ts = asString5(parsed.ts) ?? (/* @__PURE__ */ new Date(0)).toISOString(); - const stream = asString5(parsed.stream) ?? "stdout"; - const chunk = typeof parsed.chunk === "string" ? parsed.chunk : ""; - entries2.push({ ts, stream, chunk }); - } catch { - } - } - return entries2; -} -function captureStatusFromFiles(files) { - const sources = new Set(files.map((file2) => file2.source)); - if (sources.has("codex_session")) return "full"; - if (sources.has("claude_project_session") || sources.has("claude_debug_log")) return "full"; - if (sources.has("opencode_session") && sources.has("opencode_message") && sources.has("opencode_message_part")) { - return "full"; - } - const hasAdapterFiles = files.some( - (file2) => file2.source !== "taskcore_run" && file2.source !== "taskcore_run_events" && file2.source !== "taskcore_run_log" - ); - if (hasAdapterFiles) return "partial"; - return files.length > 0 ? "partial" : "unavailable"; -} -async function buildCodexTraceFiles(input) { - const files = []; - if (!input.sessionId) { - appendNote(input.notes, "codex_session_id_missing"); - return { files, raw: null, normalized: null }; - } - const managedRoot = path20.join( - resolveTaskcoreInstanceRoot(), - "companies", - input.companyId, - "codex-home", - "sessions" - ); - const sharedRoot = path20.join(codexHomeDir(), "sessions"); - const sessionFile = await findMatchingFile(managedRoot, (_absolutePath, name) => name.includes(input.sessionId), 6) ?? await findMatchingFile(sharedRoot, (_absolutePath, name) => name.includes(input.sessionId), 6); - const sessionText = await readTextFileIfPresent(sessionFile, input.state, "bundle.rawAdapterTrace.codex.session"); - if (!sessionText) { - appendNote(input.notes, "codex_session_file_missing"); - return { files, raw: null, normalized: null }; - } - files.push(makeBundleFile({ - path: "adapter/codex/session.jsonl", - contentType: "application/x-ndjson", - source: "codex_session", - contents: sessionText - })); - return { - files, - raw: { - adapterType: "codex_local", - sessionId: input.sessionId, - sessionFile: sessionFile ? path20.basename(sessionFile) : null - }, - normalized: sanitizeFeedbackValue( - { - adapterType: "codex_local", - sessionId: input.sessionId, - summary: parseCodexJsonl(sessionText) - }, - input.state, - "bundle.normalizedAdapterTrace.codex", - MAX_TRACE_FILE_CHARS - ) - }; -} -async function buildClaudeTraceFiles(input) { - const files = []; - const sanitizedStdout = sanitizeFeedbackText( - input.stdoutText, - input.state, - "bundle.rawAdapterTrace.claude.stdout", - MAX_TRACE_FILE_CHARS - ); - if (sanitizedStdout.trim().length > 0) { - files.push(makeBundleFile({ - path: "adapter/claude/stream-json.ndjson", - contentType: "application/x-ndjson", - source: "claude_stream_json", - contents: sanitizedStdout - })); - } - const projectsRoot = path20.join(claudeConfigDir(), "projects"); - const projectSessionFile = input.sessionId ? await findMatchingFile(projectsRoot, (_absolutePath, name) => name === `${input.sessionId}.jsonl`, 6) : null; - const projectSessionText = await readTextFileIfPresent( - projectSessionFile, - input.state, - "bundle.rawAdapterTrace.claude.projectSession" - ); - if (projectSessionText) { - files.push(makeBundleFile({ - path: "adapter/claude/session.jsonl", - contentType: "application/x-ndjson", - source: "claude_project_session", - contents: projectSessionText - })); - } else if (input.sessionId) { - appendNote(input.notes, "claude_project_session_missing"); - } - const projectSessionArtifactsDir = projectSessionFile ? path20.join(path20.dirname(projectSessionFile), input.sessionId ?? "") : null; - const projectSessionArtifactFiles = projectSessionArtifactsDir ? await listNestedFiles(projectSessionArtifactsDir, 4) : []; - for (const filePath of projectSessionArtifactFiles) { - const relativePath = path20.relative(projectSessionArtifactsDir, filePath).split(path20.sep).join("/"); - const fileText = await readTextFileIfPresent( - filePath, - input.state, - `bundle.rawAdapterTrace.claude.projectArtifacts.${relativePath}` - ); - if (!fileText) continue; - files.push(makeBundleFile({ - path: `adapter/claude/session/${relativePath}`, - contentType: contentTypeForPath(filePath), - source: "claude_project_artifact", - contents: fileText - })); - } - const debugLogText = await readTextFileIfPresent( - input.sessionId ? path20.join(claudeConfigDir(), "debug", `${input.sessionId}.txt`) : null, - input.state, - "bundle.rawAdapterTrace.claude.debugLog" - ); - if (debugLogText) { - files.push(makeBundleFile({ - path: "adapter/claude/debug.txt", - contentType: "text/plain; charset=utf-8", - source: "claude_debug_log", - contents: debugLogText - })); - } - const taskDir = input.sessionId ? path20.join(claudeConfigDir(), "tasks", input.sessionId) : null; - const taskFiles = taskDir ? await listChildFiles(taskDir) : []; - const metadataPieces = []; - for (const filePath of taskFiles) { - const fileText = await readTextFileIfPresent( - filePath, - input.state, - `bundle.rawAdapterTrace.claude.taskMetadata.${path20.basename(filePath)}` - ); - if (!fileText) continue; - metadataPieces.push(`# ${path20.basename(filePath)} -${fileText}`); - } - if (metadataPieces.length > 0) { - files.push(makeBundleFile({ - path: "adapter/claude/task-metadata.txt", - contentType: "text/plain; charset=utf-8", - source: "claude_task_metadata", - contents: `${metadataPieces.join("\n\n")} -` - })); - } else if (input.sessionId) { - appendNote(input.notes, "claude_task_metadata_missing"); - } - if (files.length === 0) { - appendNote(input.notes, "claude_stream_trace_missing"); - } - return { - files, - raw: { - adapterType: "claude_local", - sessionId: input.sessionId, - projectSessionFound: Boolean(projectSessionText), - projectArtifactsCount: projectSessionArtifactFiles.length, - debugLogFound: Boolean(debugLogText), - taskDirPresent: taskFiles.length > 0 - }, - normalized: sanitizeFeedbackValue( - { - adapterType: "claude_local", - sessionId: input.sessionId, - summary: parseClaudeStreamJson(input.stdoutText) - }, - input.state, - "bundle.normalizedAdapterTrace.claude", - MAX_TRACE_FILE_CHARS - ) - }; -} -async function buildOpenCodeTraceFiles(input) { - const files = []; - if (!input.sessionId) { - appendNote(input.notes, "opencode_session_id_missing"); - return { - files, - raw: null, - normalized: sanitizeFeedbackValue( - { - adapterType: "opencode_local", - summary: parseOpenCodeJsonl(input.stdoutText) - }, - input.state, - "bundle.normalizedAdapterTrace.opencode", - MAX_TRACE_FILE_CHARS - ) - }; - } - const opencodeRoot = resolveHomeAwarePath( - process.env.TASKCORE_OPENCODE_STORAGE_DIR ?? "~/.local/share/opencode" - ); - const sessionRoot = path20.join(opencodeRoot, "storage", "session"); - const diffRoot = path20.join(opencodeRoot, "storage", "session_diff"); - const messageRoot = path20.join(opencodeRoot, "storage", "message"); - const partRoot = path20.join(opencodeRoot, "storage", "part"); - const todoRoot = path20.join(opencodeRoot, "storage", "todo"); - const projectRoot = path20.join(opencodeRoot, "storage", "project"); - const sessionFile = await findMatchingFile( - sessionRoot, - (_absolutePath, name) => name === `${input.sessionId}.json`, - 6 - ); - const diffFile = path20.join(diffRoot, `${input.sessionId}.json`); - const sessionRaw = sessionFile ? await readFile(sessionFile, "utf8").catch(() => null) : null; - const sessionText = sessionRaw == null ? null : sanitizeFeedbackText(sessionRaw, input.state, "bundle.rawAdapterTrace.opencode.session", MAX_TRACE_FILE_CHARS); - if (sessionText) { - files.push(makeBundleFile({ - path: "adapter/opencode/session.json", - contentType: "application/json", - source: "opencode_session", - contents: sessionText - })); - } else { - appendNote(input.notes, "opencode_session_file_missing"); - } - const diffText = await readTextFileIfPresent( - diffFile, - input.state, - "bundle.rawAdapterTrace.opencode.sessionDiff" - ); - if (diffText) { - files.push(makeBundleFile({ - path: "adapter/opencode/session-diff.json", - contentType: "application/json", - source: "opencode_session_diff", - contents: diffText - })); - } - const messageFiles = await listChildFiles(path20.join(messageRoot, input.sessionId)); - const messageIds = []; - for (const filePath of messageFiles) { - const messageText = await readTextFileIfPresent( - filePath, - input.state, - `bundle.rawAdapterTrace.opencode.messages.${path20.basename(filePath)}` - ); - if (!messageText) continue; - messageIds.push(path20.basename(filePath, path20.extname(filePath))); - files.push(makeBundleFile({ - path: `adapter/opencode/messages/${path20.basename(filePath)}`, - contentType: "application/json", - source: "opencode_message", - contents: messageText - })); - } - if (messageFiles.length === 0) { - appendNote(input.notes, "opencode_message_files_missing"); - } - let partFilesCount = 0; - for (const messageId of messageIds) { - const partFiles = await listChildFiles(path20.join(partRoot, messageId)); - for (const filePath of partFiles) { - const partText = await readTextFileIfPresent( - filePath, - input.state, - `bundle.rawAdapterTrace.opencode.parts.${messageId}.${path20.basename(filePath)}` - ); - if (!partText) continue; - partFilesCount += 1; - files.push(makeBundleFile({ - path: `adapter/opencode/parts/${messageId}/${path20.basename(filePath)}`, - contentType: "application/json", - source: "opencode_message_part", - contents: partText - })); - } - } - if (messageIds.length > 0 && partFilesCount === 0) { - appendNote(input.notes, "opencode_message_parts_missing"); - } - const parsedSession = (() => { - if (!sessionRaw) return null; - try { - return JSON.parse(sessionRaw); - } catch { - return null; - } - })(); - const projectId = asString5(parsedSession?.projectID) ?? asString5(parsedSession?.projectId); - const projectText = await readTextFileIfPresent( - projectId ? path20.join(projectRoot, `${projectId}.json`) : null, - input.state, - "bundle.rawAdapterTrace.opencode.project" - ); - if (projectText) { - files.push(makeBundleFile({ - path: "adapter/opencode/project.json", - contentType: "application/json", - source: "opencode_project", - contents: projectText - })); - } - const todoText = await readTextFileIfPresent( - path20.join(todoRoot, `${input.sessionId}.json`), - input.state, - "bundle.rawAdapterTrace.opencode.todo" - ); - if (todoText) { - files.push(makeBundleFile({ - path: "adapter/opencode/todo.json", - contentType: "application/json", - source: "opencode_todo", - contents: todoText - })); - } - return { - files, - raw: { - adapterType: "opencode_local", - sessionId: input.sessionId, - sessionFileFound: Boolean(sessionText), - sessionDiffFound: Boolean(diffText), - messageFilesCount: messageFiles.length, - partFilesCount, - projectFound: Boolean(projectText), - todoFound: Boolean(todoText) - }, - normalized: sanitizeFeedbackValue( - { - adapterType: "opencode_local", - sessionId: input.sessionId, - summary: parseOpenCodeJsonl(input.stdoutText) - }, - input.state, - "bundle.normalizedAdapterTrace.opencode", - MAX_TRACE_FILE_CHARS - ) - }; -} -function truncateFailureReason(error50) { - const message2 = error50 instanceof Error ? error50.message : String(error50); - return message2.trim().slice(0, 1e3) || "Feedback export failed"; -} -function mapTraceRow(row, includePayload) { - const targetSummary = asRecord3(row.targetSummary); - return { - id: row.id, - companyId: row.companyId, - feedbackVoteId: row.feedbackVoteId, - issueId: row.issueId, - projectId: row.projectId ?? null, - issueIdentifier: row.issueIdentifier, - issueTitle: row.issueTitle, - authorUserId: row.authorUserId, - targetType: row.targetType, - targetId: row.targetId, - vote: row.vote, - status: row.status, - destination: row.destination ?? null, - exportId: row.exportId ?? null, - consentVersion: row.consentVersion ?? null, - schemaVersion: row.schemaVersion, - bundleVersion: row.bundleVersion, - payloadVersion: row.payloadVersion, - payloadDigest: row.payloadDigest ?? null, - payloadSnapshot: includePayload ? asRecord3(row.payloadSnapshot) : null, - targetSummary: targetSummary ?? buildTargetSummary({ - label: row.targetType, - excerpt: null, - authorAgentId: null, - authorUserId: null, - createdAt: null - }), - redactionSummary: asRecord3(row.redactionSummary), - attemptCount: row.attemptCount, - lastAttemptedAt: row.lastAttemptedAt ?? null, - exportedAt: row.exportedAt ?? null, - failureReason: row.failureReason ?? null, - createdAt: row.createdAt, - updatedAt: row.updatedAt - }; -} -async function resolveFeedbackTarget(db, issue2, targetType, targetId) { - const issuePath = buildIssuePath(issue2.identifier); - if (targetType === "issue_comment") { - const targetComment = await db.select({ - id: issueComments.id, - issueId: issueComments.issueId, - companyId: issueComments.companyId, - authorAgentId: issueComments.authorAgentId, - authorUserId: issueComments.authorUserId, - createdByRunId: issueComments.createdByRunId, - body: issueComments.body, - createdAt: issueComments.createdAt - }).from(issueComments).where(eq(issueComments.id, targetId)).then((rows) => rows[0] ?? null); - if (!targetComment || targetComment.issueId !== issue2.id || targetComment.companyId !== issue2.companyId) { - throw notFound("Feedback target not found"); - } - if (!targetComment.authorAgentId) { - throw unprocessable("Feedback voting is only available on agent-authored issue comments"); - } - const record2 = { - targetType, - targetId, - label: "Comment", - body: targetComment.body, - createdAt: targetComment.createdAt, - authorAgentId: targetComment.authorAgentId, - authorUserId: targetComment.authorUserId, - createdByRunId: targetComment.createdByRunId ?? null, - documentId: null, - documentKey: null, - documentTitle: null, - revisionNumber: null, - issuePath, - targetPath: issuePath ? `${issuePath}#comment-${targetComment.id}` : null, - payloadTarget: { - type: targetType, - id: targetComment.id, - createdAt: targetComment.createdAt.toISOString(), - authorAgentId: targetComment.authorAgentId, - authorUserId: targetComment.authorUserId, - createdByRunId: targetComment.createdByRunId ?? null, - issuePath, - targetPath: issuePath ? `${issuePath}#comment-${targetComment.id}` : null - } - }; - return record2; - } - if (targetType === "issue_document_revision") { - const targetRevision = await db.select({ - id: documentRevisions.id, - companyId: documentRevisions.companyId, - documentId: documentRevisions.documentId, - revisionNumber: documentRevisions.revisionNumber, - body: documentRevisions.body, - createdByAgentId: documentRevisions.createdByAgentId, - createdByUserId: documentRevisions.createdByUserId, - createdByRunId: documentRevisions.createdByRunId, - createdAt: documentRevisions.createdAt, - issueId: issueDocuments.issueId, - key: issueDocuments.key, - title: documents.title - }).from(documentRevisions).innerJoin(documents, eq(documentRevisions.documentId, documents.id)).innerJoin(issueDocuments, eq(issueDocuments.documentId, documents.id)).where(eq(documentRevisions.id, targetId)).then((rows) => rows.find((row) => row.issueId === issue2.id) ?? null); - if (!targetRevision || targetRevision.companyId !== issue2.companyId) { - throw notFound("Feedback target not found"); - } - if (!targetRevision.createdByAgentId) { - throw unprocessable("Feedback voting is only available on agent-authored document revisions"); - } - const record2 = { - targetType, - targetId, - label: `${targetRevision.key} rev ${targetRevision.revisionNumber}`, - body: targetRevision.body, - createdAt: targetRevision.createdAt, - authorAgentId: targetRevision.createdByAgentId, - authorUserId: targetRevision.createdByUserId, - createdByRunId: targetRevision.createdByRunId ?? null, - documentId: targetRevision.documentId, - documentKey: targetRevision.key, - documentTitle: targetRevision.title ?? null, - revisionNumber: targetRevision.revisionNumber, - issuePath, - targetPath: issuePath ? `${issuePath}#document-${encodeURIComponent(targetRevision.key)}` : null, - payloadTarget: { - type: targetType, - id: targetRevision.id, - documentId: targetRevision.documentId, - documentKey: targetRevision.key, - documentTitle: targetRevision.title ?? null, - revisionNumber: targetRevision.revisionNumber, - createdAt: targetRevision.createdAt.toISOString(), - authorAgentId: targetRevision.createdByAgentId, - authorUserId: targetRevision.createdByUserId, - createdByRunId: targetRevision.createdByRunId ?? null, - issuePath, - targetPath: issuePath ? `${issuePath}#document-${encodeURIComponent(targetRevision.key)}` : null - } - }; - return record2; - } - throw unprocessable("Unsupported feedback target type"); -} -async function listIssueContextItems(db, issue2) { - const [commentRows, revisionRows] = await Promise.all([ - db.select({ - targetId: issueComments.id, - body: issueComments.body, - createdAt: issueComments.createdAt, - authorAgentId: issueComments.authorAgentId, - authorUserId: issueComments.authorUserId, - createdByRunId: issueComments.createdByRunId - }).from(issueComments).where(and(eq(issueComments.companyId, issue2.companyId), eq(issueComments.issueId, issue2.id))), - db.select({ - targetId: documentRevisions.id, - body: documentRevisions.body, - createdAt: documentRevisions.createdAt, - authorAgentId: documentRevisions.createdByAgentId, - authorUserId: documentRevisions.createdByUserId, - createdByRunId: documentRevisions.createdByRunId, - documentId: documentRevisions.documentId, - documentKey: issueDocuments.key, - documentTitle: documents.title, - revisionNumber: documentRevisions.revisionNumber - }).from(documentRevisions).innerJoin(documents, eq(documentRevisions.documentId, documents.id)).innerJoin(issueDocuments, eq(issueDocuments.documentId, documents.id)).where(and(eq(documentRevisions.companyId, issue2.companyId), eq(issueDocuments.issueId, issue2.id))) - ]); - const issuePath = buildIssuePath(issue2.identifier); - const items = [ - ...commentRows.map((row) => ({ - targetType: "issue_comment", - targetId: row.targetId, - label: "Comment", - body: row.body, - createdAt: row.createdAt, - authorAgentId: row.authorAgentId, - authorUserId: row.authorUserId, - createdByRunId: row.createdByRunId ?? null, - documentId: null, - documentKey: null, - documentTitle: null, - revisionNumber: null, - issuePath, - targetPath: issuePath ? `${issuePath}#comment-${row.targetId}` : null - })), - ...revisionRows.map((row) => ({ - targetType: "issue_document_revision", - targetId: row.targetId, - label: `${row.documentKey} rev ${row.revisionNumber}`, - body: row.body, - createdAt: row.createdAt, - authorAgentId: row.authorAgentId, - authorUserId: row.authorUserId, - createdByRunId: row.createdByRunId ?? null, - documentId: row.documentId, - documentKey: row.documentKey, - documentTitle: row.documentTitle ?? null, - revisionNumber: row.revisionNumber, - issuePath, - targetPath: issuePath ? `${issuePath}#document-${encodeURIComponent(row.documentKey)}` : null - })) - ]; - return items.sort((left, right) => { - const byDate = left.createdAt.getTime() - right.createdAt.getTime(); - if (byDate !== 0) return byDate; - return left.targetId.localeCompare(right.targetId); - }); -} -async function buildIssueContext(db, issue2, target, state2) { - const items = await listIssueContextItems(db, issue2); - const targetIndex = items.findIndex((item) => item.targetType === target.targetType && item.targetId === target.targetId); - const before = targetIndex >= 0 ? items.slice(Math.max(0, targetIndex - FEEDBACK_CONTEXT_WINDOW), targetIndex) : []; - const after = targetIndex >= 0 ? items.slice(targetIndex + 1, targetIndex + 1 + FEEDBACK_CONTEXT_WINDOW) : []; - let remainingChars = MAX_TOTAL_CONTEXT_CHARS; - const serializedItems = [...before, ...after].map((item, index2) => { - const relation = index2 < before.length ? "before" : "after"; - if (remainingChars <= 0) { - state2.omittedFields.add("bundle.issueContext.items"); - return null; - } - const maxChars = Math.min(MAX_CONTEXT_ITEM_BODY_CHARS, remainingChars); - const body = sanitizeFeedbackText( - item.body, - state2, - `bundle.issueContext.items.${index2}.body`, - maxChars - ); - remainingChars -= body.length; - return { - type: item.targetType, - id: item.targetId, - label: item.label, - relation, - createdAt: item.createdAt.toISOString(), - authorAgentId: item.authorAgentId, - authorUserId: item.authorUserId, - createdByRunId: item.createdByRunId, - documentKey: item.documentKey, - documentTitle: item.documentTitle, - revisionNumber: item.revisionNumber, - targetPath: item.targetPath, - body, - excerpt: truncateExcerpt(body) - }; - }).filter((item) => item !== null); - const descriptionExcerpt = issue2.description ? sanitizeFeedbackText(issue2.description, state2, "bundle.issueContext.issue.description", MAX_DESCRIPTION_CHARS) : null; - return { - issue: { - id: issue2.id, - identifier: issue2.identifier, - title: issue2.title, - projectId: issue2.projectId, - path: buildIssuePath(issue2.identifier), - descriptionExcerpt: descriptionExcerpt ? truncateExcerpt(descriptionExcerpt, MAX_DESCRIPTION_CHARS) : null - }, - items: serializedItems - }; -} -async function buildAgentContext(db, companyId, authorAgentId, createdByRunId, state2) { - if (!authorAgentId) { - state2.notes.add("author_agent_missing"); - return null; - } - const agent = await db.select({ - id: agents.id, - companyId: agents.companyId, - name: agents.name, - role: agents.role, - title: agents.title, - status: agents.status, - adapterType: agents.adapterType, - adapterConfig: agents.adapterConfig, - runtimeConfig: agents.runtimeConfig - }).from(agents).where(eq(agents.id, authorAgentId)).then((rows) => rows[0] ?? null); - if (!agent || agent.companyId !== companyId) { - state2.notes.add("author_agent_unavailable"); - return null; - } - const adapterConfig = asRecord3(agent.adapterConfig) ?? {}; - const runtimeConfig = asRecord3(agent.runtimeConfig) ?? {}; - const desiredSkillRefs = uniqueNonEmpty2(readTaskcoreSkillSyncPreference(adapterConfig).desiredSkills).slice(0, MAX_SKILLS); - const availableSkills = desiredSkillRefs.length === 0 ? [] : await db.select().from(companySkills).where(eq(companySkills.companyId, companyId)); - const matchedSkills = availableSkills.filter((skill) => desiredSkillRefs.some((reference) => matchesSkillReference(skill, reference))).slice(0, MAX_SKILLS); - const unresolvedSkillRefs = desiredSkillRefs.filter( - (reference) => !matchedSkills.some((skill) => matchesSkillReference(skill, reference)) - ); - if (availableSkills.length > MAX_SKILLS || desiredSkillRefs.length > MAX_SKILLS) { - state2.omittedFields.add("bundle.agentContext.skills"); - } - const run = createdByRunId ? await db.select({ - id: heartbeatRuns.id, - companyId: heartbeatRuns.companyId, - agentId: heartbeatRuns.agentId, - invocationSource: heartbeatRuns.invocationSource, - status: heartbeatRuns.status, - startedAt: heartbeatRuns.startedAt, - finishedAt: heartbeatRuns.finishedAt, - usageJson: heartbeatRuns.usageJson, - sessionIdBefore: heartbeatRuns.sessionIdBefore, - sessionIdAfter: heartbeatRuns.sessionIdAfter, - externalRunId: heartbeatRuns.externalRunId - }).from(heartbeatRuns).where(eq(heartbeatRuns.id, createdByRunId)).then((rows) => rows[0] ?? null) : null; - const runCosts = run ? await db.select({ - provider: costEvents.provider, - biller: costEvents.biller, - billingType: costEvents.billingType, - model: costEvents.model, - inputTokens: costEvents.inputTokens, - cachedInputTokens: costEvents.cachedInputTokens, - outputTokens: costEvents.outputTokens, - costCents: costEvents.costCents - }).from(costEvents).where(and(eq(costEvents.companyId, companyId), eq(costEvents.heartbeatRunId, run.id))) : []; - const usage = asRecord3(run?.usageJson) ?? {}; - const runtime = { - configuredModel: asString5(adapterConfig.model), - configuredInstructionsBundleMode: asString5(adapterConfig.instructionsBundleMode), - configuredInstructionsEntryFile: asString5(adapterConfig.instructionsEntryFile), - configuredInstructionsFilePath: asString5(adapterConfig.instructionsFilePath), - configuredInstructionsRootPath: asString5(adapterConfig.instructionsRootPath), - heartbeatPolicy: sanitizeFeedbackValue(runtimeConfig.heartbeat ?? null, state2, "bundle.agentContext.runtime.heartbeatPolicy", 400), - provenanceMode: run ? "source_run" : "vote_time_snapshot", - sourceRun: run ? sanitizeFeedbackValue({ - id: run.id, - invocationSource: run.invocationSource, - status: run.status, - startedAt: run.startedAt?.toISOString() ?? null, - finishedAt: run.finishedAt?.toISOString() ?? null, - externalRunId: run.externalRunId ?? null, - sessionIdBefore: run.sessionIdBefore ?? null, - sessionIdAfter: run.sessionIdAfter ?? null, - usage: { - provider: asString5(usage.provider), - biller: asString5(usage.biller), - billingType: asString5(usage.billingType), - model: asString5(usage.model), - inputTokens: asNumber2(usage.inputTokens) ?? asNumber2(usage.rawInputTokens), - cachedInputTokens: asNumber2(usage.cachedInputTokens) ?? asNumber2(usage.rawCachedInputTokens), - outputTokens: asNumber2(usage.outputTokens) ?? asNumber2(usage.rawOutputTokens), - costUsd: asNumber2(usage.costUsd), - usageSource: asString5(usage.usageSource), - sessionReused: asBoolean2(usage.sessionReused), - taskSessionReused: asBoolean2(usage.taskSessionReused), - freshSession: asBoolean2(usage.freshSession), - sessionRotated: asBoolean2(usage.sessionRotated), - sessionRotationReason: asString5(usage.sessionRotationReason) - } - }, state2, "bundle.agentContext.runtime.sourceRun", 400) : null, - costSummary: runCosts.length > 0 ? { - providers: uniqueNonEmpty2(runCosts.map((row) => row.provider)), - billers: uniqueNonEmpty2(runCosts.map((row) => row.biller)), - billingTypes: uniqueNonEmpty2(runCosts.map((row) => row.billingType)), - models: uniqueNonEmpty2(runCosts.map((row) => row.model)), - inputTokens: runCosts.reduce((sum, row) => sum + row.inputTokens, 0), - cachedInputTokens: runCosts.reduce((sum, row) => sum + row.cachedInputTokens, 0), - outputTokens: runCosts.reduce((sum, row) => sum + row.outputTokens, 0), - costCents: runCosts.reduce((sum, row) => sum + row.costCents, 0) - } : null - }; - const instructionsBundle = await instructionsSvc.getBundle({ - id: agent.id, - companyId: agent.companyId, - name: agent.name, - adapterConfig: agent.adapterConfig - }).catch(() => null); - let entryDigest = null; - let entryBody = null; - if (instructionsBundle) { - const readableEntryPath = instructionsBundle.files.find((file2) => file2.path === instructionsBundle.entryFile)?.path ?? instructionsBundle.files[0]?.path ?? null; - if (readableEntryPath) { - const entryFile = await instructionsSvc.readFile({ - id: agent.id, - companyId: agent.companyId, - name: agent.name, - adapterConfig: agent.adapterConfig - }, readableEntryPath).catch(() => null); - if (entryFile) { - entryDigest = sha256Digest(entryFile.content); - entryBody = sanitizeFeedbackText( - entryFile.content, - state2, - "bundle.agentContext.instructions.entryBody", - MAX_INSTRUCTIONS_BODY_CHARS - ); - } - } - if (instructionsBundle.files.length > MAX_INSTRUCTION_FILES) { - state2.omittedFields.add("bundle.agentContext.instructions.files"); - } - } - return { - agent: { - id: agent.id, - name: agent.name, - role: agent.role, - title: agent.title, - status: agent.status, - adapterType: agent.adapterType - }, - runtime: sanitizeFeedbackValue(runtime, state2, "bundle.agentContext.runtime", 400), - skills: { - desiredRefs: desiredSkillRefs, - unresolvedRefs: unresolvedSkillRefs, - items: matchedSkills.map((skill, index2) => ({ - key: skill.key, - slug: skill.slug, - name: skill.name, - sourceType: skill.sourceType, - sourceLocator: skill.sourceLocator == null ? null : skill.sourceType === "github" || skill.sourceType === "skills_sh" || skill.sourceType === "url" ? skill.sourceLocator : sanitizeFeedbackText( - skill.sourceLocator, - state2, - `bundle.agentContext.skills.items.${index2}.sourceLocator`, - MAX_PATH_CHARS - ), - sourceRef: skill.sourceRef, - trustLevel: skill.trustLevel, - compatibility: skill.compatibility, - fileInventory: skill.fileInventory - })) - }, - instructions: instructionsBundle ? { - mode: instructionsBundle.mode, - entryFile: instructionsBundle.entryFile, - resolvedEntryPath: instructionsBundle.resolvedEntryPath ? sanitizeFeedbackText( - instructionsBundle.resolvedEntryPath, - state2, - "bundle.agentContext.instructions.resolvedEntryPath", - MAX_PATH_CHARS - ) : null, - warnings: instructionsBundle.warnings.map((warning, index2) => sanitizeFeedbackText( - warning, - state2, - `bundle.agentContext.instructions.warnings.${index2}`, - 400 - )), - legacyPromptTemplateActive: instructionsBundle.legacyPromptTemplateActive, - legacyBootstrapPromptTemplateActive: instructionsBundle.legacyBootstrapPromptTemplateActive, - fileCount: instructionsBundle.files.length, - files: instructionsBundle.files.slice(0, MAX_INSTRUCTION_FILES).map((file2) => ({ - path: file2.path, - size: file2.size, - language: file2.language, - markdown: file2.markdown, - isEntryFile: file2.isEntryFile, - virtual: file2.virtual - })), - entryDigest, - entryBody - } : null, - taskcore: { - schemaVersion: FEEDBACK_SCHEMA_VERSION, - bundleVersion: FEEDBACK_BUNDLE_VERSION - } - }; -} -async function buildPayloadArtifacts(db, input) { - const state2 = createFeedbackRedactionState(); - const primaryBody = sanitizeFeedbackText( - input.target.body, - state2, - "bundle.primaryContent.body", - MAX_PRIMARY_CONTENT_CHARS - ); - const primaryContent = { - type: input.target.targetType, - id: input.target.targetId, - label: input.target.label, - createdAt: input.target.createdAt.toISOString(), - authorAgentId: input.target.authorAgentId, - authorUserId: input.target.authorUserId, - createdByRunId: input.target.createdByRunId, - documentId: input.target.documentId, - documentKey: input.target.documentKey, - documentTitle: input.target.documentTitle, - revisionNumber: input.target.revisionNumber, - targetPath: input.target.targetPath, - body: primaryBody, - excerpt: truncateExcerpt(primaryBody) - }; - const targetSummary = buildTargetSummary({ - label: input.target.label, - excerpt: primaryContent.excerpt, - authorAgentId: input.target.authorAgentId, - authorUserId: input.target.authorUserId, - createdAt: input.target.createdAt, - documentKey: input.target.documentKey, - documentTitle: input.target.documentTitle, - revisionNumber: input.target.revisionNumber - }); - const basePayload = { - schemaVersion: FEEDBACK_SCHEMA_VERSION, - bundleVersion: FEEDBACK_BUNDLE_VERSION, - sourceApp: "taskcore", - capturedAt: input.now.toISOString(), - consentVersion: input.consentVersion, - vote: { - id: input.voteId, - value: input.vote, - reason: input.reason, - authorUserId: input.authorUserId, - sharedWithLabs: input.sharedWithLabs, - sharedAt: input.sharedWithLabs ? input.now.toISOString() : null - }, - target: input.target.payloadTarget - }; - if (!input.sharedWithLabs) { - state2.notes.add("local_only_trace_stores_metadata_only"); - const payloadSnapshot2 = { - ...basePayload, - exportId: null, - exportEligible: false, - bundle: null - }; - const redactionSummary2 = finalizeFeedbackRedactionSummary(state2); - return { - exportId: null, - targetSummary, - redactionSummary: redactionSummary2, - payloadSnapshot: { - ...payloadSnapshot2, - redactionSummary: redactionSummary2 - }, - payloadDigest: sha256Digest({ - ...payloadSnapshot2, - redactionSummary: redactionSummary2 - }) - }; - } - const exportId = buildExportId(input.voteId, input.now); - const [issueContext, agentContext] = await Promise.all([ - buildIssueContext(db, input.issue, input.target, state2), - buildAgentContext(db, input.issue.companyId, input.target.authorAgentId, input.target.createdByRunId, state2) - ]); - const payloadSnapshot = { - ...basePayload, - exportId, - exportEligible: true, - bundle: { - primaryContent, - issueContext, - agentContext - } - }; - const redactionSummary = finalizeFeedbackRedactionSummary(state2); - const payloadWithSummary = { - ...payloadSnapshot, - redactionSummary - }; - return { - exportId, - targetSummary, - redactionSummary, - payloadSnapshot: payloadWithSummary, - payloadDigest: sha256Digest(payloadWithSummary) - }; -} -async function buildFeedbackTraceBundleFromRow(db, row) { - const trace = mapTraceRow(row, true); - const payloadSnapshot = asRecord3(trace.payloadSnapshot); - const notes = []; - const state2 = createFeedbackRedactionState(); - const files = []; - const sourceRunId = resolveSourceRunId(payloadSnapshot); - let taskcoreRun = null; - let rawAdapterTrace = null; - let normalizedAdapterTrace = null; - let adapterType = null; - if (!sourceRunId) { - appendNote(notes, "source_run_missing"); - } else { - const run = await db.select({ - id: heartbeatRuns.id, - companyId: heartbeatRuns.companyId, - agentId: heartbeatRuns.agentId, - invocationSource: heartbeatRuns.invocationSource, - status: heartbeatRuns.status, - startedAt: heartbeatRuns.startedAt, - finishedAt: heartbeatRuns.finishedAt, - createdAt: heartbeatRuns.createdAt, - updatedAt: heartbeatRuns.updatedAt, - error: heartbeatRuns.error, - errorCode: heartbeatRuns.errorCode, - usageJson: heartbeatRuns.usageJson, - resultJson: heartbeatRuns.resultJson, - sessionIdBefore: heartbeatRuns.sessionIdBefore, - sessionIdAfter: heartbeatRuns.sessionIdAfter, - externalRunId: heartbeatRuns.externalRunId, - contextSnapshot: heartbeatRuns.contextSnapshot, - logStore: heartbeatRuns.logStore, - logRef: heartbeatRuns.logRef, - logBytes: heartbeatRuns.logBytes, - logSha256: heartbeatRuns.logSha256, - agentName: agents.name, - agentRole: agents.role, - agentTitle: agents.title, - adapterType: agents.adapterType - }).from(heartbeatRuns).innerJoin(agents, eq(heartbeatRuns.agentId, agents.id)).where(eq(heartbeatRuns.id, sourceRunId)).then((rows) => rows[0] ?? null); - if (!run || run.companyId !== row.companyId) { - appendNote(notes, "source_run_unavailable"); - } else { - adapterType = run.adapterType; - const events = await db.select().from(heartbeatRunEvents).where(eq(heartbeatRunEvents.runId, run.id)).orderBy(asc(heartbeatRunEvents.seq)); - const logText = await readFullRunLog(run); - const logEntries = parseRunLogEntries(logText); - const stdoutText = logEntries.filter((entry) => entry.stream === "stdout").map((entry) => entry.chunk).join(""); - taskcoreRun = sanitizeFeedbackValue( - { - id: run.id, - companyId: run.companyId, - agentId: run.agentId, - agentName: run.agentName, - agentRole: run.agentRole, - agentTitle: run.agentTitle, - adapterType: run.adapterType, - invocationSource: run.invocationSource, - status: run.status, - startedAt: run.startedAt?.toISOString() ?? null, - finishedAt: run.finishedAt?.toISOString() ?? null, - createdAt: run.createdAt.toISOString(), - updatedAt: run.updatedAt.toISOString(), - error: run.error, - errorCode: run.errorCode, - usage: asRecord3(run.usageJson), - result: asRecord3(run.resultJson), - sessionIdBefore: run.sessionIdBefore, - sessionIdAfter: run.sessionIdAfter, - externalRunId: run.externalRunId, - contextSnapshot: asRecord3(run.contextSnapshot), - logStore: run.logStore, - logRef: run.logRef, - logBytes: run.logBytes, - logSha256: run.logSha256, - eventCount: events.length - }, - state2, - "bundle.taskcoreRun", - MAX_TRACE_FILE_CHARS - ); - files.push(makeBundleFile({ - path: "taskcore/run.json", - contentType: "application/json", - source: "taskcore_run", - contents: `${JSON.stringify(taskcoreRun, null, 2)} -` - })); - const sanitizedEvents = sanitizeFeedbackValue( - events, - state2, - "bundle.taskcoreRun.events", - MAX_TRACE_FILE_CHARS - ); - files.push(makeBundleFile({ - path: "taskcore/run-events.json", - contentType: "application/json", - source: "taskcore_run_events", - contents: `${JSON.stringify(sanitizedEvents, null, 2)} -` - })); - if (logText) { - files.push(makeBundleFile({ - path: "taskcore/run-log.ndjson", - contentType: "application/x-ndjson", - source: "taskcore_run_log", - contents: `${sanitizeFeedbackText(logText, state2, "bundle.taskcoreRun.log", MAX_TRACE_FILE_CHARS)} -` - })); - } else { - appendNote(notes, "run_log_missing"); - } - if (run.adapterType === "codex_local") { - const adapter = await buildCodexTraceFiles({ - companyId: row.companyId, - sessionId: run.sessionIdAfter ?? run.sessionIdBefore, - state: state2, - notes - }); - files.push(...adapter.files); - rawAdapterTrace = adapter.raw; - normalizedAdapterTrace = adapter.normalized; - } else if (run.adapterType === "claude_local") { - const adapter = await buildClaudeTraceFiles({ - sessionId: run.sessionIdAfter ?? run.sessionIdBefore, - stdoutText, - state: state2, - notes - }); - files.push(...adapter.files); - rawAdapterTrace = adapter.raw; - normalizedAdapterTrace = adapter.normalized; - } else if (run.adapterType === "opencode_local") { - const adapter = await buildOpenCodeTraceFiles({ - sessionId: run.sessionIdAfter ?? run.sessionIdBefore, - stdoutText, - state: state2, - notes - }); - files.push(...adapter.files); - rawAdapterTrace = adapter.raw; - normalizedAdapterTrace = adapter.normalized; - } else { - appendNote(notes, "adapter_specific_trace_not_supported"); - } - } - } - const privacy = { - ...asRecord3(trace.redactionSummary) ?? {}, - bundleRedactionSummary: finalizeFeedbackRedactionSummary(state2) - }; - const captureStatus = captureStatusFromFiles(files); - if (captureStatus !== "full" && files.length > 0) { - appendNote(notes, "adapter_trace_partial"); - } - const envelope = sanitizeFeedbackValue( - { - traceId: trace.id, - exportId: trace.exportId, - companyId: trace.companyId, - feedbackVoteId: trace.feedbackVoteId, - issueId: trace.issueId, - issueIdentifier: trace.issueIdentifier, - issueTitle: trace.issueTitle, - projectId: trace.projectId, - authorUserId: trace.authorUserId, - targetType: trace.targetType, - targetId: trace.targetId, - vote: trace.vote, - status: trace.status, - destination: trace.destination, - consentVersion: trace.consentVersion, - schemaVersion: trace.schemaVersion, - bundleVersion: trace.bundleVersion, - payloadVersion: trace.payloadVersion, - payloadDigest: trace.payloadDigest, - createdAt: trace.createdAt.toISOString(), - exportedAt: trace.exportedAt?.toISOString() ?? null - }, - state2, - "bundle.envelope", - MAX_TRACE_FILE_CHARS - ); - const surface = sanitizeFeedbackValue( - { - target: asRecord3(payloadSnapshot?.target), - summary: trace.targetSummary - }, - state2, - "bundle.surface", - MAX_TRACE_FILE_CHARS - ); - const bundle = { - traceId: trace.id, - exportId: trace.exportId, - companyId: trace.companyId, - issueId: trace.issueId, - issueIdentifier: trace.issueIdentifier, - adapterType, - captureStatus, - notes, - envelope, - surface, - taskcoreRun, - rawAdapterTrace, - normalizedAdapterTrace, - privacy, - integrity: { - payloadDigest: trace.payloadDigest, - bundleDigest: sha256Digest({ - traceId: trace.id, - files: files.map((file2) => ({ - path: file2.path, - source: file2.source, - sha256: file2.sha256 - })), - captureStatus - }) - }, - files - }; - return bundle; -} -function feedbackService(db, options = {}) { - return { - listIssueVotesForUser: async (issueId, authorUserId) => db.select().from(feedbackVotes).where(and(eq(feedbackVotes.issueId, issueId), eq(feedbackVotes.authorUserId, authorUserId))), - listFeedbackTraces: async (input) => { - const filters = [eq(feedbackExports.companyId, input.companyId)]; - if (input.issueId) filters.push(eq(feedbackExports.issueId, input.issueId)); - if (input.projectId) filters.push(eq(feedbackExports.projectId, input.projectId)); - if (input.targetType) filters.push(eq(feedbackExports.targetType, input.targetType)); - if (input.vote) filters.push(eq(feedbackExports.vote, input.vote)); - if (input.status) filters.push(eq(feedbackExports.status, input.status)); - if (input.sharedOnly) filters.push(ne(feedbackExports.status, "local_only")); - if (input.from) filters.push(gte(feedbackExports.createdAt, input.from)); - if (input.to) filters.push(lte(feedbackExports.createdAt, input.to)); - const rows = await db.select({ - ...feedbackExportColumns, - issueIdentifier: issues.identifier, - issueTitle: issues.title - }).from(feedbackExports).innerJoin(issues, eq(feedbackExports.issueId, issues.id)).where(and(...filters)).orderBy(desc(feedbackExports.createdAt)); - return rows.map((row) => mapTraceRow(row, input.includePayload === true)); - }, - getFeedbackTraceById: async (traceId, includePayload = true) => { - const row = await db.select({ - ...feedbackExportColumns, - issueIdentifier: issues.identifier, - issueTitle: issues.title - }).from(feedbackExports).innerJoin(issues, eq(feedbackExports.issueId, issues.id)).where(eq(feedbackExports.id, traceId)).then((rows) => rows[0] ?? null); - return row ? mapTraceRow(row, includePayload) : null; - }, - getFeedbackTraceBundle: async (traceId) => { - const row = await db.select({ - ...feedbackExportColumns, - issueIdentifier: issues.identifier, - issueTitle: issues.title - }).from(feedbackExports).innerJoin(issues, eq(feedbackExports.issueId, issues.id)).where(eq(feedbackExports.id, traceId)).then((rows) => rows[0] ?? null); - return row ? buildFeedbackTraceBundleFromRow(db, row) : null; - }, - flushPendingFeedbackTraces: async (input) => { - const shareClient = options.shareClient; - if (!shareClient) { - const filters2 = [eq(feedbackExports.status, "pending")]; - if (input?.companyId) { - filters2.push(eq(feedbackExports.companyId, input.companyId)); - } - if (input?.traceId) { - filters2.push(eq(feedbackExports.id, input.traceId)); - } - const rows2 = await db.select({ - id: feedbackExports.id, - attemptCount: feedbackExports.attemptCount - }).from(feedbackExports).where(and(...filters2)).orderBy(asc(feedbackExports.createdAt), asc(feedbackExports.id)).limit(Math.max(1, Math.min(input?.limit ?? 25, 200))); - const attemptAt = input?.now ?? /* @__PURE__ */ new Date(); - for (const row of rows2) { - await db.update(feedbackExports).set({ - status: "failed", - attemptCount: row.attemptCount + 1, - lastAttemptedAt: attemptAt, - failureReason: FEEDBACK_EXPORT_BACKEND_NOT_CONFIGURED, - updatedAt: attemptAt - }).where(eq(feedbackExports.id, row.id)); - } - return { - attempted: rows2.length, - sent: 0, - failed: rows2.length - }; - } - const limit = Math.max(1, Math.min(input?.limit ?? 25, 200)); - const filters = [ - or(eq(feedbackExports.status, "pending"), eq(feedbackExports.status, "failed")) - ]; - if (input?.companyId) { - filters.push(eq(feedbackExports.companyId, input.companyId)); - } - if (input?.traceId) { - filters.push(eq(feedbackExports.id, input.traceId)); - } - const rows = await db.select({ - ...feedbackExportColumns, - issueIdentifier: issues.identifier, - issueTitle: issues.title - }).from(feedbackExports).innerJoin(issues, eq(feedbackExports.issueId, issues.id)).where(and(...filters)).orderBy(asc(feedbackExports.createdAt), asc(feedbackExports.id)).limit(limit); - let attempted = 0; - let sent = 0; - let failed = 0; - for (const row of rows) { - const attemptAt = input?.now ?? /* @__PURE__ */ new Date(); - attempted += 1; - try { - const bundle = await buildFeedbackTraceBundleFromRow(db, row); - await shareClient.uploadTraceBundle(bundle); - await db.update(feedbackExports).set({ - status: "sent", - attemptCount: row.attemptCount + 1, - lastAttemptedAt: attemptAt, - exportedAt: attemptAt, - failureReason: null, - updatedAt: attemptAt - }).where(eq(feedbackExports.id, row.id)); - sent += 1; - } catch (error50) { - await db.update(feedbackExports).set({ - status: "failed", - attemptCount: row.attemptCount + 1, - lastAttemptedAt: attemptAt, - failureReason: truncateFailureReason(error50), - updatedAt: attemptAt - }).where(eq(feedbackExports.id, row.id)); - failed += 1; - } - } - return { - attempted, - sent, - failed - }; - }, - saveIssueVote: async (input) => db.transaction(async (tx) => { - const issue2 = await tx.select({ - id: issues.id, - companyId: issues.companyId, - projectId: issues.projectId, - identifier: issues.identifier, - title: issues.title, - description: issues.description - }).from(issues).where(eq(issues.id, input.issueId)).then((rows) => rows[0] ?? null); - if (!issue2) throw notFound("Issue not found"); - const target = await resolveFeedbackTarget(tx, issue2, input.targetType, input.targetId); - const existingCompany = await tx.select({ - feedbackDataSharingEnabled: companies.feedbackDataSharingEnabled, - feedbackDataSharingTermsVersion: companies.feedbackDataSharingTermsVersion - }).from(companies).where(eq(companies.id, issue2.companyId)).then((rows) => rows[0] ?? null); - if (!existingCompany) throw notFound("Company not found"); - const now2 = /* @__PURE__ */ new Date(); - const normalizedReason = normalizeReason(input.vote, input.reason); - const sharedWithLabs = input.allowSharing === true; - let consentEnabledNow = false; - let consentVersion = existingCompany.feedbackDataSharingTermsVersion ?? null; - let persistedSharingPreference = null; - if (sharedWithLabs && !existingCompany.feedbackDataSharingEnabled) { - consentEnabledNow = true; - consentVersion = DEFAULT_FEEDBACK_DATA_SHARING_TERMS_VERSION; - await tx.update(companies).set({ - feedbackDataSharingEnabled: true, - feedbackDataSharingConsentAt: now2, - feedbackDataSharingConsentByUserId: input.authorUserId, - feedbackDataSharingTermsVersion: consentVersion, - updatedAt: now2 - }).where(eq(companies.id, issue2.companyId)); - } - const existingInstanceSettings = await tx.select({ - id: instanceSettings.id, - general: instanceSettings.general - }).from(instanceSettings).where(eq(instanceSettings.singletonKey, DEFAULT_INSTANCE_SETTINGS_SINGLETON_KEY)).then((rows) => rows[0] ?? null); - const currentInstanceSettings = existingInstanceSettings ?? await tx.insert(instanceSettings).values({ - singletonKey: DEFAULT_INSTANCE_SETTINGS_SINGLETON_KEY, - general: {}, - experimental: {}, - createdAt: now2, - updatedAt: now2 - }).onConflictDoUpdate({ - target: [instanceSettings.singletonKey], - set: { - updatedAt: now2 - } - }).returning({ - id: instanceSettings.id, - general: instanceSettings.general - }).then((rows) => rows[0] ?? null); - const currentGeneral = normalizeInstanceGeneralSettings(currentInstanceSettings?.general); - if (currentInstanceSettings && currentGeneral.feedbackDataSharingPreference === "prompt") { - const nextSharingPreference = sharedWithLabs ? "allowed" : "not_allowed"; - const currentGeneralRaw = asRecord3(currentInstanceSettings.general) ?? {}; - await tx.update(instanceSettings).set({ - general: { - ...currentGeneralRaw, - censorUsernameInLogs: currentGeneral.censorUsernameInLogs, - feedbackDataSharingPreference: nextSharingPreference - }, - updatedAt: now2 - }).where(eq(instanceSettings.id, currentInstanceSettings.id)); - persistedSharingPreference = nextSharingPreference; - } - const [savedVote] = await tx.insert(feedbackVotes).values({ - companyId: issue2.companyId, - issueId: issue2.id, - targetType: input.targetType, - targetId: input.targetId, - authorUserId: input.authorUserId, - vote: input.vote, - reason: normalizedReason, - sharedWithLabs, - sharedAt: sharedWithLabs ? now2 : null, - consentVersion: sharedWithLabs ? consentVersion ?? DEFAULT_FEEDBACK_DATA_SHARING_TERMS_VERSION : null, - redactionSummary: null, - updatedAt: now2 - }).onConflictDoUpdate({ - target: [ - feedbackVotes.companyId, - feedbackVotes.targetType, - feedbackVotes.targetId, - feedbackVotes.authorUserId - ], - set: { - vote: input.vote, - reason: normalizedReason, - sharedWithLabs, - sharedAt: sharedWithLabs ? now2 : null, - consentVersion: sharedWithLabs ? consentVersion ?? DEFAULT_FEEDBACK_DATA_SHARING_TERMS_VERSION : null, - redactionSummary: null, - updatedAt: now2 - } - }).returning(); - const artifacts = await buildPayloadArtifacts(tx, { - issue: issue2, - target, - voteId: savedVote.id, - vote: input.vote, - reason: normalizedReason, - authorUserId: input.authorUserId, - consentVersion: sharedWithLabs ? consentVersion ?? DEFAULT_FEEDBACK_DATA_SHARING_TERMS_VERSION : null, - sharedWithLabs, - now: now2 - }); - await tx.update(feedbackVotes).set({ - redactionSummary: artifacts.redactionSummary, - updatedAt: now2 - }).where(eq(feedbackVotes.id, savedVote.id)); - const [savedTrace] = await tx.insert(feedbackExports).values({ - companyId: issue2.companyId, - feedbackVoteId: savedVote.id, - issueId: issue2.id, - projectId: issue2.projectId, - authorUserId: input.authorUserId, - targetType: input.targetType, - targetId: input.targetId, - vote: input.vote, - status: sharedWithLabs ? "pending" : "local_only", - destination: sharedWithLabs ? FEEDBACK_DESTINATION : null, - exportId: artifacts.exportId, - consentVersion: sharedWithLabs ? consentVersion ?? DEFAULT_FEEDBACK_DATA_SHARING_TERMS_VERSION : null, - schemaVersion: FEEDBACK_SCHEMA_VERSION, - bundleVersion: FEEDBACK_BUNDLE_VERSION, - payloadVersion: FEEDBACK_PAYLOAD_VERSION, - payloadDigest: artifacts.payloadDigest, - payloadSnapshot: artifacts.payloadSnapshot, - targetSummary: artifacts.targetSummary, - redactionSummary: artifacts.redactionSummary, - updatedAt: now2 - }).onConflictDoUpdate({ - target: [feedbackExports.feedbackVoteId], - set: { - issueId: issue2.id, - projectId: issue2.projectId, - authorUserId: input.authorUserId, - targetType: input.targetType, - targetId: input.targetId, - vote: input.vote, - status: sharedWithLabs ? "pending" : "local_only", - destination: sharedWithLabs ? FEEDBACK_DESTINATION : null, - exportId: artifacts.exportId, - consentVersion: sharedWithLabs ? consentVersion ?? DEFAULT_FEEDBACK_DATA_SHARING_TERMS_VERSION : null, - schemaVersion: FEEDBACK_SCHEMA_VERSION, - bundleVersion: FEEDBACK_BUNDLE_VERSION, - payloadVersion: FEEDBACK_PAYLOAD_VERSION, - payloadDigest: artifacts.payloadDigest, - payloadSnapshot: artifacts.payloadSnapshot, - targetSummary: artifacts.targetSummary, - redactionSummary: artifacts.redactionSummary, - failureReason: null, - updatedAt: now2 - } - }).returning({ - id: feedbackExports.id - }); - return { - vote: { - ...savedVote, - redactionSummary: artifacts.redactionSummary - }, - traceId: savedTrace?.id ?? null, - consentEnabledNow, - persistedSharingPreference, - sharingEnabled: sharedWithLabs - }; - }) - }; -} - -// server/src/services/company-skills.ts -init_drizzle_orm(); -init_src2(); -import { createHash as createHash10 } from "node:crypto"; -import { promises as fs27 } from "node:fs"; -import path34 from "node:path"; -import { fileURLToPath as fileURLToPath15 } from "node:url"; - -// packages/adapters/cursor-local/src/server/execute.ts -import fs16 from "node:fs/promises"; -import os13 from "node:os"; -import path21 from "node:path"; -import { fileURLToPath as fileURLToPath8 } from "node:url"; - -// packages/adapters/cursor-local/src/index.ts -var DEFAULT_CURSOR_LOCAL_MODEL = "auto"; -var CURSOR_FALLBACK_MODEL_IDS = [ - "auto", - "composer-1.5", - "composer-1", - "gpt-5.3-codex-low", - "gpt-5.3-codex-low-fast", - "gpt-5.3-codex", - "gpt-5.3-codex-fast", - "gpt-5.3-codex-high", - "gpt-5.3-codex-high-fast", - "gpt-5.3-codex-xhigh", - "gpt-5.3-codex-xhigh-fast", - "gpt-5.3-codex-spark-preview", - "gpt-5.2", - "gpt-5.2-codex-low", - "gpt-5.2-codex-low-fast", - "gpt-5.2-codex", - "gpt-5.2-codex-fast", - "gpt-5.2-codex-high", - "gpt-5.2-codex-high-fast", - "gpt-5.2-codex-xhigh", - "gpt-5.2-codex-xhigh-fast", - "gpt-5.1-codex-max", - "gpt-5.1-codex-max-high", - "gpt-5.2-high", - "gpt-5.1-high", - "gpt-5.1-codex-mini", - "opus-4.6-thinking", - "opus-4.6", - "opus-4.5", - "opus-4.5-thinking", - "sonnet-4.6", - "sonnet-4.6-thinking", - "sonnet-4.5", - "sonnet-4.5-thinking", - "gemini-3.1-pro", - "gemini-3-pro", - "gemini-3-flash", - "grok", - "kimi-k2.5" -]; -var models3 = CURSOR_FALLBACK_MODEL_IDS.map((id) => ({ id, label: id })); -var agentConfigurationDoc3 = `# cursor agent configuration - -Adapter: cursor - -Use when: -- You want Taskcore to run Cursor Agent CLI locally as the agent runtime -- You want Cursor chat session resume across heartbeats via --resume -- You want structured stream output in run logs via --output-format stream-json - -Don't use when: -- You need webhook-style external invocation (use openclaw_gateway or http) -- You only need one-shot shell commands (use process) -- Cursor Agent CLI is not installed on the machine - -Core fields: -- cwd (string, optional): default absolute working directory fallback for the agent process (created if missing when possible) -- instructionsFilePath (string, optional): absolute path to a markdown instructions file prepended to the run prompt -- promptTemplate (string, optional): run prompt template -- model (string, optional): Cursor model id (for example auto or gpt-5.3-codex) -- mode (string, optional): Cursor execution mode passed as --mode (plan|ask). Leave unset for normal autonomous runs. -- command (string, optional): defaults to "agent" -- extraArgs (string[], optional): additional CLI args -- env (object, optional): KEY=VALUE environment variables - -Operational fields: -- timeoutSec (number, optional): run timeout in seconds -- graceSec (number, optional): SIGTERM grace period in seconds - -Notes: -- Runs are executed with: agent -p --output-format stream-json ... -- Prompts are piped to Cursor via stdin. -- Sessions are resumed with --resume when stored session cwd matches current cwd. -- Taskcore auto-injects local skills into "~/.cursor/skills" when missing, so Cursor can discover "$taskcore" and related skills on local runs. -- Taskcore auto-adds --yolo unless one of --trust/--yolo/-f is already present in extraArgs. -`; - -// packages/adapters/cursor-local/src/shared/stream.ts -function normalizeCursorStreamLine(rawLine) { - const trimmed = rawLine.trim(); - if (!trimmed) return { stream: null, line: "" }; - const prefixed = trimmed.match(/^(stdout|stderr)\s*[:=]?\s*([\[{].*)$/i); - if (!prefixed) { - return { stream: null, line: trimmed }; - } - const stream = prefixed[1]?.toLowerCase() === "stderr" ? "stderr" : "stdout"; - const line3 = (prefixed[2] ?? "").trim(); - return { stream, line: line3 }; -} - -// packages/adapters/cursor-local/src/server/parse.ts -function asErrorText(value) { - if (typeof value === "string") return value; - const rec = parseObject(value); - const message2 = asString(rec.message, "") || asString(rec.error, "") || asString(rec.code, "") || asString(rec.detail, ""); - if (message2) return message2; - try { - return JSON.stringify(rec); - } catch { - return ""; - } -} -function collectAssistantText(message2) { - if (typeof message2 === "string") { - const trimmed = message2.trim(); - return trimmed ? [trimmed] : []; - } - const rec = parseObject(message2); - const direct = asString(rec.text, "").trim(); - const lines = direct ? [direct] : []; - const content = Array.isArray(rec.content) ? rec.content : []; - for (const partRaw of content) { - const part = parseObject(partRaw); - const type = asString(part.type, "").trim(); - if (type === "output_text" || type === "text") { - const text3 = asString(part.text, "").trim(); - if (text3) lines.push(text3); - } - } - return lines; -} -function readSessionId(event) { - return asString(event.session_id, "").trim() || asString(event.sessionId, "").trim() || asString(event.sessionID, "").trim() || null; -} -function parseCursorJsonl(stdout) { - let sessionId = null; - const messages2 = []; - let errorMessage = null; - let totalCostUsd = 0; - const usage = { - inputTokens: 0, - cachedInputTokens: 0, - outputTokens: 0 - }; - for (const rawLine of stdout.split(/\r?\n/)) { - const line3 = normalizeCursorStreamLine(rawLine).line; - if (!line3) continue; - const event = parseJson2(line3); - if (!event) continue; - const foundSession = readSessionId(event); - if (foundSession) sessionId = foundSession; - const type = asString(event.type, "").trim(); - if (type === "assistant") { - messages2.push(...collectAssistantText(event.message)); - continue; - } - if (type === "result") { - const usageObj = parseObject(event.usage); - usage.inputTokens += asNumber( - usageObj.input_tokens, - asNumber(usageObj.inputTokens, 0) - ); - usage.cachedInputTokens += asNumber( - usageObj.cached_input_tokens, - asNumber(usageObj.cachedInputTokens, asNumber(usageObj.cache_read_input_tokens, 0)) - ); - usage.outputTokens += asNumber( - usageObj.output_tokens, - asNumber(usageObj.outputTokens, 0) - ); - totalCostUsd += asNumber(event.total_cost_usd, asNumber(event.cost_usd, asNumber(event.cost, 0))); - const isError = event.is_error === true || asString(event.subtype, "").toLowerCase() === "error"; - const resultText = asString(event.result, "").trim(); - if (resultText && messages2.length === 0) { - messages2.push(resultText); - } - if (isError) { - const resultError = asErrorText(event.error ?? event.message ?? event.result).trim(); - if (resultError) errorMessage = resultError; - } - continue; - } - if (type === "error") { - const message2 = asErrorText(event.message ?? event.error ?? event.detail).trim(); - if (message2) errorMessage = message2; - continue; - } - if (type === "system") { - const subtype = asString(event.subtype, "").trim().toLowerCase(); - if (subtype === "error") { - const message2 = asErrorText(event.message ?? event.error ?? event.detail).trim(); - if (message2) errorMessage = message2; - } - continue; - } - if (type === "text") { - const part = parseObject(event.part); - const text3 = asString(part.text, "").trim(); - if (text3) messages2.push(text3); - continue; - } - if (type === "step_finish") { - const part = parseObject(event.part); - const tokens = parseObject(part.tokens); - const cache7 = parseObject(tokens.cache); - usage.inputTokens += asNumber(tokens.input, 0); - usage.cachedInputTokens += asNumber(cache7.read, 0); - usage.outputTokens += asNumber(tokens.output, 0); - totalCostUsd += asNumber(part.cost, 0); - continue; - } - } - return { - sessionId, - summary: messages2.join("\n\n").trim(), - usage, - costUsd: totalCostUsd > 0 ? totalCostUsd : null, - errorMessage - }; -} -function isCursorUnknownSessionError(stdout, stderr) { - const haystack = `${stdout} -${stderr}`.split(/\r?\n/).map((line3) => line3.trim()).filter(Boolean).join("\n"); - return /unknown\s+(session|chat)|session\s+.*\s+not\s+found|chat\s+.*\s+not\s+found|resume\s+.*\s+not\s+found|could\s+not\s+resume/i.test( - haystack - ); -} - -// packages/adapters/cursor-local/src/shared/trust.ts -function hasCursorTrustBypassArg(args) { - return args.some( - (arg) => arg === "--trust" || arg === "--yolo" || arg === "-f" || arg.startsWith("--trust=") - ); -} - -// packages/adapters/cursor-local/src/server/execute.ts -var __moduleDir7 = path21.dirname(fileURLToPath8(import.meta.url)); -function firstNonEmptyLine7(text3) { - return text3.split(/\r?\n/).map((line3) => line3.trim()).find(Boolean) ?? ""; -} -function hasNonEmptyEnvValue3(env2, key) { - const raw = env2[key]; - return typeof raw === "string" && raw.trim().length > 0; -} -function resolveCursorBillingType(env2) { - return hasNonEmptyEnvValue3(env2, "CURSOR_API_KEY") || hasNonEmptyEnvValue3(env2, "OPENAI_API_KEY") ? "api" : "subscription"; -} -function resolveCursorBiller(env2, billingType, provider) { - const openAiCompatibleBiller = inferOpenAiCompatibleBiller(env2, null); - if (openAiCompatibleBiller === "openrouter") return "openrouter"; - if (billingType === "subscription") return "cursor"; - return provider ?? "cursor"; -} -function resolveProviderFromModel(model) { - const trimmed = model.trim().toLowerCase(); - if (!trimmed) return null; - const slash = trimmed.indexOf("/"); - if (slash > 0) return trimmed.slice(0, slash); - if (trimmed.includes("sonnet") || trimmed.includes("claude")) return "anthropic"; - if (trimmed.startsWith("gpt") || trimmed.startsWith("o")) return "openai"; - return null; -} -function normalizeMode(rawMode) { - const mode = rawMode.trim().toLowerCase(); - if (mode === "plan" || mode === "ask") return mode; - return null; -} -function renderTaskcoreEnvNote(env2) { - const taskcoreKeys = Object.keys(env2).filter((key) => key.startsWith("TASKCORE_")).sort(); - if (taskcoreKeys.length === 0) return ""; - return [ - "Taskcore runtime note:", - `The following TASKCORE_* environment variables are available in this run: ${taskcoreKeys.join(", ")}`, - "Do not assume these variables are missing without checking your shell environment.", - "", - "" - ].join("\n"); -} -function cursorSkillsHome() { - return path21.join(os13.homedir(), ".cursor", "skills"); -} -async function ensureCursorSkillsInjected(onLog, options = {}) { - const skillsEntries = options.skillsEntries ?? (options.skillsDir ? (await fs16.readdir(options.skillsDir, { withFileTypes: true })).filter((entry) => entry.isDirectory()).map((entry) => ({ - key: entry.name, - runtimeName: entry.name, - source: path21.join(options.skillsDir, entry.name) - })) : await readTaskcoreRuntimeSkillEntries({}, __moduleDir7)); - if (skillsEntries.length === 0) return; - const skillsHome = options.skillsHome ?? cursorSkillsHome(); - try { - await fs16.mkdir(skillsHome, { recursive: true }); - } catch (err) { - await onLog( - "stderr", - `[taskcore] Failed to prepare Cursor skills directory ${skillsHome}: ${err instanceof Error ? err.message : String(err)} -` - ); - return; - } - const removedSkills = await removeMaintainerOnlySkillSymlinks( - skillsHome, - skillsEntries.map((entry) => entry.runtimeName) - ); - for (const skillName of removedSkills) { - await onLog( - "stderr", - `[taskcore] Removed maintainer-only Cursor skill "${skillName}" from ${skillsHome} -` - ); - } - const linkSkill = options.linkSkill ?? ((source, target) => fs16.symlink(source, target)); - for (const entry of skillsEntries) { - const target = path21.join(skillsHome, entry.runtimeName); - try { - const result = await ensureTaskcoreSkillSymlink(entry.source, target, linkSkill); - if (result === "skipped") continue; - await onLog( - "stderr", - `[taskcore] ${result === "repaired" ? "Repaired" : "Injected"} Cursor skill "${entry.key}" into ${skillsHome} -` - ); - } catch (err) { - await onLog( - "stderr", - `[taskcore] Failed to inject Cursor skill "${entry.key}" into ${skillsHome}: ${err instanceof Error ? err.message : String(err)} -` - ); - } - } -} -async function execute4(ctx) { - const { runId, agent, runtime, config: config3, context, onLog, onMeta, onSpawn, authToken } = ctx; - const promptTemplate = asString( - config3.promptTemplate, - "You are agent {{agent.id}} ({{agent.name}}). Continue your Taskcore work." - ); - const command = asString(config3.command, "agent"); - const model = asString(config3.model, DEFAULT_CURSOR_LOCAL_MODEL).trim(); - const mode = normalizeMode(asString(config3.mode, "")); - const workspaceContext = parseObject(context.taskcoreWorkspace); - const workspaceCwd = asString(workspaceContext.cwd, ""); - const workspaceSource = asString(workspaceContext.source, ""); - const workspaceId = asString(workspaceContext.workspaceId, ""); - const workspaceRepoUrl = asString(workspaceContext.repoUrl, ""); - const workspaceRepoRef = asString(workspaceContext.repoRef, ""); - const agentHome = asString(workspaceContext.agentHome, ""); - const workspaceHints = Array.isArray(context.taskcoreWorkspaces) ? context.taskcoreWorkspaces.filter( - (value) => typeof value === "object" && value !== null - ) : []; - const configuredCwd = asString(config3.cwd, ""); - const useConfiguredInsteadOfAgentHome = workspaceSource === "agent_home" && configuredCwd.length > 0; - const effectiveWorkspaceCwd = useConfiguredInsteadOfAgentHome ? "" : workspaceCwd; - const cwd = effectiveWorkspaceCwd || configuredCwd || process.cwd(); - await ensureAbsoluteDirectory(cwd, { createIfMissing: true }); - const cursorSkillEntries = await readTaskcoreRuntimeSkillEntries(config3, __moduleDir7); - const desiredCursorSkillNames = resolveTaskcoreDesiredSkillNames(config3, cursorSkillEntries); - await ensureCursorSkillsInjected(onLog, { - skillsEntries: cursorSkillEntries.filter((entry) => desiredCursorSkillNames.includes(entry.key)) - }); - const envConfig = parseObject(config3.env); - const hasExplicitApiKey = typeof envConfig.TASKCORE_API_KEY === "string" && envConfig.TASKCORE_API_KEY.trim().length > 0; - const env2 = { ...buildTaskcoreEnv(agent) }; - env2.TASKCORE_RUN_ID = runId; - const wakeTaskId = typeof context.taskId === "string" && context.taskId.trim().length > 0 && context.taskId.trim() || typeof context.issueId === "string" && context.issueId.trim().length > 0 && context.issueId.trim() || null; - const wakeReason = typeof context.wakeReason === "string" && context.wakeReason.trim().length > 0 ? context.wakeReason.trim() : null; - const wakeCommentId = typeof context.wakeCommentId === "string" && context.wakeCommentId.trim().length > 0 && context.wakeCommentId.trim() || typeof context.commentId === "string" && context.commentId.trim().length > 0 && context.commentId.trim() || null; - const approvalId = typeof context.approvalId === "string" && context.approvalId.trim().length > 0 ? context.approvalId.trim() : null; - const approvalStatus = typeof context.approvalStatus === "string" && context.approvalStatus.trim().length > 0 ? context.approvalStatus.trim() : null; - const linkedIssueIds = Array.isArray(context.issueIds) ? context.issueIds.filter((value) => typeof value === "string" && value.trim().length > 0) : []; - const wakePayloadJson = stringifyTaskcoreWakePayload(context.taskcoreWake); - if (wakeTaskId) { - env2.TASKCORE_TASK_ID = wakeTaskId; - } - if (wakeReason) { - env2.TASKCORE_WAKE_REASON = wakeReason; - } - if (wakeCommentId) { - env2.TASKCORE_WAKE_COMMENT_ID = wakeCommentId; - } - if (approvalId) { - env2.TASKCORE_APPROVAL_ID = approvalId; - } - if (approvalStatus) { - env2.TASKCORE_APPROVAL_STATUS = approvalStatus; - } - if (linkedIssueIds.length > 0) { - env2.TASKCORE_LINKED_ISSUE_IDS = linkedIssueIds.join(","); - } - if (wakePayloadJson) { - env2.TASKCORE_WAKE_PAYLOAD_JSON = wakePayloadJson; - } - if (effectiveWorkspaceCwd) { - env2.TASKCORE_WORKSPACE_CWD = effectiveWorkspaceCwd; - } - if (workspaceSource) { - env2.TASKCORE_WORKSPACE_SOURCE = workspaceSource; - } - if (workspaceId) { - env2.TASKCORE_WORKSPACE_ID = workspaceId; - } - if (workspaceRepoUrl) { - env2.TASKCORE_WORKSPACE_REPO_URL = workspaceRepoUrl; - } - if (workspaceRepoRef) { - env2.TASKCORE_WORKSPACE_REPO_REF = workspaceRepoRef; - } - if (agentHome) { - env2.AGENT_HOME = agentHome; - } - if (workspaceHints.length > 0) { - env2.TASKCORE_WORKSPACES_JSON = JSON.stringify(workspaceHints); - } - for (const [k5, v5] of Object.entries(envConfig)) { - if (typeof v5 === "string") env2[k5] = v5; - } - if (!hasExplicitApiKey && authToken) { - env2.TASKCORE_API_KEY = authToken; - } - const effectiveEnv = Object.fromEntries( - Object.entries({ ...process.env, ...env2 }).filter( - (entry) => typeof entry[1] === "string" - ) - ); - const billingType = resolveCursorBillingType(effectiveEnv); - const runtimeEnv = ensurePathInEnv(effectiveEnv); - await ensureCommandResolvable(command, cwd, runtimeEnv); - const resolvedCommand = await resolveCommandForLogs(command, cwd, runtimeEnv); - const loggedEnv = buildInvocationEnvForLogs(env2, { - runtimeEnv, - includeRuntimeKeys: ["HOME"], - resolvedCommand - }); - const timeoutSec = asNumber(config3.timeoutSec, 0); - const graceSec = asNumber(config3.graceSec, 20); - const extraArgs = (() => { - const fromExtraArgs = asStringArray(config3.extraArgs); - if (fromExtraArgs.length > 0) return fromExtraArgs; - return asStringArray(config3.args); - })(); - const autoTrustEnabled = !hasCursorTrustBypassArg(extraArgs); - const runtimeSessionParams = parseObject(runtime.sessionParams); - const runtimeSessionId = asString(runtimeSessionParams.sessionId, runtime.sessionId ?? ""); - const runtimeSessionCwd = asString(runtimeSessionParams.cwd, ""); - const canResumeSession = runtimeSessionId.length > 0 && (runtimeSessionCwd.length === 0 || path21.resolve(runtimeSessionCwd) === path21.resolve(cwd)); - const sessionId = canResumeSession ? runtimeSessionId : null; - if (runtimeSessionId && !canResumeSession) { - await onLog( - "stdout", - `[taskcore] Cursor session "${runtimeSessionId}" was saved for cwd "${runtimeSessionCwd}" and will not be resumed in "${cwd}". -` - ); - } - const instructionsFilePath = asString(config3.instructionsFilePath, "").trim(); - const instructionsDir = instructionsFilePath ? `${path21.dirname(instructionsFilePath)}/` : ""; - let instructionsPrefix = ""; - let instructionsChars = 0; - if (instructionsFilePath) { - try { - const instructionsContents = await fs16.readFile(instructionsFilePath, "utf8"); - instructionsPrefix = `${instructionsContents} - -The above agent instructions were loaded from ${instructionsFilePath}. Resolve any relative file references from ${instructionsDir}. - -`; - instructionsChars = instructionsPrefix.length; - } catch (err) { - const reason = err instanceof Error ? err.message : String(err); - await onLog( - "stdout", - `[taskcore] Warning: could not read agent instructions file "${instructionsFilePath}": ${reason} -` - ); - } - } - const commandNotes = (() => { - const notes = []; - if (autoTrustEnabled) { - notes.push("Auto-added --yolo to bypass interactive prompts."); - } - notes.push("Prompt is piped to Cursor via stdin."); - if (!instructionsFilePath) return notes; - if (instructionsPrefix.length > 0) { - notes.push( - `Loaded agent instructions from ${instructionsFilePath}`, - `Prepended instructions + path directive to prompt (relative references from ${instructionsDir}).` - ); - return notes; - } - notes.push( - `Configured instructionsFilePath ${instructionsFilePath}, but file could not be read; continuing without injected instructions.` - ); - return notes; - })(); - const bootstrapPromptTemplate = asString(config3.bootstrapPromptTemplate, ""); - const templateData = { - agentId: agent.id, - companyId: agent.companyId, - runId, - company: { id: agent.companyId }, - agent, - run: { id: runId, source: "on_demand" }, - context - }; - const renderedBootstrapPrompt = !sessionId && bootstrapPromptTemplate.trim().length > 0 ? renderTemplate(bootstrapPromptTemplate, templateData).trim() : ""; - const wakePrompt = renderTaskcoreWakePrompt(context.taskcoreWake, { resumedSession: Boolean(sessionId) }); - const shouldUseResumeDeltaPrompt = Boolean(sessionId) && wakePrompt.length > 0; - const renderedPrompt = shouldUseResumeDeltaPrompt ? "" : renderTemplate(promptTemplate, templateData); - const sessionHandoffNote = asString(context.taskcoreSessionHandoffMarkdown, "").trim(); - const taskcoreEnvNote = renderTaskcoreEnvNote(env2); - const prompt = joinPromptSections([ - instructionsPrefix, - renderedBootstrapPrompt, - wakePrompt, - sessionHandoffNote, - taskcoreEnvNote, - renderedPrompt - ]); - const promptMetrics = { - promptChars: prompt.length, - instructionsChars, - bootstrapPromptChars: renderedBootstrapPrompt.length, - wakePromptChars: wakePrompt.length, - sessionHandoffChars: sessionHandoffNote.length, - runtimeNoteChars: taskcoreEnvNote.length, - heartbeatPromptChars: renderedPrompt.length - }; - const buildArgs = (resumeSessionId) => { - const args = ["-p", "--output-format", "stream-json", "--workspace", cwd]; - if (resumeSessionId) args.push("--resume", resumeSessionId); - if (model) args.push("--model", model); - if (mode) args.push("--mode", mode); - if (autoTrustEnabled) args.push("--yolo"); - if (extraArgs.length > 0) args.push(...extraArgs); - return args; - }; - const runAttempt = async (resumeSessionId) => { - const args = buildArgs(resumeSessionId); - if (onMeta) { - await onMeta({ - adapterType: "cursor", - command: resolvedCommand, - cwd, - commandNotes, - commandArgs: args, - env: loggedEnv, - prompt, - promptMetrics, - context - }); - } - let stdoutLineBuffer = ""; - const emitNormalizedStdoutLine = async (rawLine) => { - const normalized = normalizeCursorStreamLine(rawLine); - if (!normalized.line) return; - await onLog(normalized.stream ?? "stdout", `${normalized.line} -`); - }; - const flushStdoutChunk = async (chunk, finalize2 = false) => { - const combined = `${stdoutLineBuffer}${chunk}`; - const lines = combined.split(/\r?\n/); - stdoutLineBuffer = lines.pop() ?? ""; - for (const line3 of lines) { - await emitNormalizedStdoutLine(line3); - } - if (finalize2) { - const trailing = stdoutLineBuffer.trim(); - stdoutLineBuffer = ""; - if (trailing) { - await emitNormalizedStdoutLine(trailing); - } - } - }; - const proc = await runChildProcess(runId, command, args, { - cwd, - env: env2, - timeoutSec, - graceSec, - stdin: prompt, - onSpawn, - onLog: async (stream, chunk) => { - if (stream !== "stdout") { - await onLog(stream, chunk); - return; - } - await flushStdoutChunk(chunk); - } - }); - await flushStdoutChunk("", true); - return { - proc, - parsed: parseCursorJsonl(proc.stdout) - }; - }; - const providerFromModel = resolveProviderFromModel(model); - const toResult = (attempt, clearSessionOnMissingSession = false) => { - if (attempt.proc.timedOut) { - return { - exitCode: attempt.proc.exitCode, - signal: attempt.proc.signal, - timedOut: true, - errorMessage: `Timed out after ${timeoutSec}s`, - clearSession: clearSessionOnMissingSession - }; - } - const resolvedSessionId = attempt.parsed.sessionId ?? runtimeSessionId ?? runtime.sessionId ?? null; - const resolvedSessionParams = resolvedSessionId ? { - sessionId: resolvedSessionId, - cwd, - ...workspaceId ? { workspaceId } : {}, - ...workspaceRepoUrl ? { repoUrl: workspaceRepoUrl } : {}, - ...workspaceRepoRef ? { repoRef: workspaceRepoRef } : {} - } : null; - const parsedError = typeof attempt.parsed.errorMessage === "string" ? attempt.parsed.errorMessage.trim() : ""; - const stderrLine = firstNonEmptyLine7(attempt.proc.stderr); - const fallbackErrorMessage = parsedError || stderrLine || `Cursor exited with code ${attempt.proc.exitCode ?? -1}`; - return { - exitCode: attempt.proc.exitCode, - signal: attempt.proc.signal, - timedOut: false, - errorMessage: (attempt.proc.exitCode ?? 0) === 0 ? null : fallbackErrorMessage, - usage: attempt.parsed.usage, - sessionId: resolvedSessionId, - sessionParams: resolvedSessionParams, - sessionDisplayId: resolvedSessionId, - provider: providerFromModel, - biller: resolveCursorBiller(effectiveEnv, billingType, providerFromModel), - model, - billingType, - costUsd: attempt.parsed.costUsd, - resultJson: { - stdout: attempt.proc.stdout, - stderr: attempt.proc.stderr - }, - summary: attempt.parsed.summary, - clearSession: Boolean(clearSessionOnMissingSession && !resolvedSessionId) - }; - }; - const initial = await runAttempt(sessionId); - if (sessionId && !initial.proc.timedOut && (initial.proc.exitCode ?? 0) !== 0 && isCursorUnknownSessionError(initial.proc.stdout, initial.proc.stderr)) { - await onLog( - "stdout", - `[taskcore] Cursor resume session "${sessionId}" is unavailable; retrying with a fresh session. -` - ); - const retry = await runAttempt(null); - return toResult(retry, true); - } - return toResult(initial); -} - -// packages/adapters/cursor-local/src/server/skills.ts -import fs17 from "node:fs/promises"; -import os14 from "node:os"; -import path22 from "node:path"; -import { fileURLToPath as fileURLToPath9 } from "node:url"; -var __moduleDir8 = path22.dirname(fileURLToPath9(import.meta.url)); -function asString6(value) { - return typeof value === "string" && value.trim().length > 0 ? value.trim() : null; -} -function resolveCursorSkillsHome(config3) { - const env2 = typeof config3.env === "object" && config3.env !== null && !Array.isArray(config3.env) ? config3.env : {}; - const configuredHome = asString6(env2.HOME); - const home = configuredHome ? path22.resolve(configuredHome) : os14.homedir(); - return path22.join(home, ".cursor", "skills"); -} -async function buildCursorSkillSnapshot(config3) { - const availableEntries = await readTaskcoreRuntimeSkillEntries(config3, __moduleDir8); - const desiredSkills = resolveTaskcoreDesiredSkillNames(config3, availableEntries); - const skillsHome = resolveCursorSkillsHome(config3); - const installed = await readInstalledSkillTargets(skillsHome); - return buildPersistentSkillSnapshot({ - adapterType: "cursor", - availableEntries, - desiredSkills, - installed, - skillsHome, - locationLabel: "~/.cursor/skills", - missingDetail: "Configured but not currently linked into the Cursor skills home.", - externalConflictDetail: "Skill name is occupied by an external installation.", - externalDetail: "Installed outside Taskcore management." - }); -} -async function listCursorSkills(ctx) { - return buildCursorSkillSnapshot(ctx.config); -} -async function syncCursorSkills(ctx, desiredSkills) { - const availableEntries = await readTaskcoreRuntimeSkillEntries(ctx.config, __moduleDir8); - const desiredSet = /* @__PURE__ */ new Set([ - ...desiredSkills, - ...availableEntries.filter((entry) => entry.required).map((entry) => entry.key) - ]); - const skillsHome = resolveCursorSkillsHome(ctx.config); - await fs17.mkdir(skillsHome, { recursive: true }); - const installed = await readInstalledSkillTargets(skillsHome); - const availableByRuntimeName = new Map(availableEntries.map((entry) => [entry.runtimeName, entry])); - for (const available of availableEntries) { - if (!desiredSet.has(available.key)) continue; - const target = path22.join(skillsHome, available.runtimeName); - await ensureTaskcoreSkillSymlink(available.source, target); - } - for (const [name, installedEntry] of installed.entries()) { - const available = availableByRuntimeName.get(name); - if (!available) continue; - if (desiredSet.has(available.key)) continue; - if (installedEntry.targetPath !== available.source) continue; - await fs17.unlink(path22.join(skillsHome, name)).catch(() => { - }); - } - return buildCursorSkillSnapshot(ctx.config); -} - -// packages/adapters/cursor-local/src/server/test.ts -import fs18 from "node:fs/promises"; -import os15 from "node:os"; -import path23 from "node:path"; -function summarizeStatus4(checks) { - if (checks.some((check3) => check3.level === "error")) return "fail"; - if (checks.some((check3) => check3.level === "warn")) return "warn"; - return "pass"; -} -function isNonEmpty3(value) { - return typeof value === "string" && value.trim().length > 0; -} -function firstNonEmptyLine8(text3) { - return text3.split(/\r?\n/).map((line3) => line3.trim()).find(Boolean) ?? ""; -} -function commandLooksLike3(command, expected) { - const base = path23.basename(command).toLowerCase(); - return base === expected || base === `${expected}.cmd` || base === `${expected}.exe`; -} -function summarizeProbeDetail4(stdout, stderr, parsedError) { - const raw = parsedError?.trim() || firstNonEmptyLine8(stderr) || firstNonEmptyLine8(stdout); - if (!raw) return null; - const clean3 = raw.replace(/\s+/g, " ").trim(); - const max = 240; - return clean3.length > max ? `${clean3.slice(0, max - 1)}\u2026` : clean3; -} -function cursorConfigPath(cursorHome) { - return path23.join(cursorHome ?? path23.join(os15.homedir(), ".cursor"), "cli-config.json"); -} -async function readCursorAuthInfo(cursorHome) { - let raw; - try { - raw = await fs18.readFile(cursorConfigPath(cursorHome), "utf8"); - } catch { - return null; - } - let parsed; - try { - parsed = JSON.parse(raw); - } catch { - return null; - } - if (typeof parsed !== "object" || parsed === null) return null; - const obj = parsed; - const authInfo = obj.authInfo; - if (typeof authInfo !== "object" || authInfo === null) return null; - const info2 = authInfo; - const email3 = typeof info2.email === "string" && info2.email.trim().length > 0 ? info2.email.trim() : null; - const displayName = typeof info2.displayName === "string" && info2.displayName.trim().length > 0 ? info2.displayName.trim() : null; - const userId = typeof info2.userId === "number" ? info2.userId : null; - if (!email3 && !displayName && userId == null) return null; - return { email: email3, displayName, userId }; -} -var CURSOR_AUTH_REQUIRED_RE = /(?:authentication\s+required|not\s+authenticated|not\s+logged\s+in|unauthorized|invalid(?:\s+or\s+missing)?\s+api(?:[_\s-]?key)?|cursor[_\s-]?api[_\s-]?key|run\s+'?agent\s+login'?\s+first|api(?:[_\s-]?key)?(?:\s+is)?\s+required)/i; -async function testEnvironment4(ctx) { - const checks = []; - const config3 = parseObject(ctx.config); - const command = asString(config3.command, "agent"); - const cwd = asString(config3.cwd, process.cwd()); - try { - await ensureAbsoluteDirectory(cwd, { createIfMissing: true }); - checks.push({ - code: "cursor_cwd_valid", - level: "info", - message: `Working directory is valid: ${cwd}` - }); - } catch (err) { - checks.push({ - code: "cursor_cwd_invalid", - level: "error", - message: err instanceof Error ? err.message : "Invalid working directory", - detail: cwd - }); - } - const envConfig = parseObject(config3.env); - const env2 = {}; - for (const [key, value] of Object.entries(envConfig)) { - if (typeof value === "string") env2[key] = value; - } - const runtimeEnv = ensurePathInEnv({ ...process.env, ...env2 }); - try { - await ensureCommandResolvable(command, cwd, runtimeEnv); - checks.push({ - code: "cursor_command_resolvable", - level: "info", - message: `Command is executable: ${command}` - }); - } catch (err) { - checks.push({ - code: "cursor_command_unresolvable", - level: "error", - message: err instanceof Error ? err.message : "Command is not executable", - detail: command - }); - } - const configCursorApiKey = env2.CURSOR_API_KEY; - const hostCursorApiKey = process.env.CURSOR_API_KEY; - if (isNonEmpty3(configCursorApiKey) || isNonEmpty3(hostCursorApiKey)) { - const source = isNonEmpty3(configCursorApiKey) ? "adapter config env" : "server environment"; - checks.push({ - code: "cursor_api_key_present", - level: "info", - message: "CURSOR_API_KEY is set for Cursor authentication.", - detail: `Detected in ${source}.` - }); - } else { - const cursorHome = isNonEmpty3(env2.CURSOR_HOME) ? env2.CURSOR_HOME : void 0; - const cursorAuth = await readCursorAuthInfo(cursorHome).catch(() => null); - if (cursorAuth) { - checks.push({ - code: "cursor_native_auth_present", - level: "info", - message: "Cursor is authenticated via `agent login`.", - detail: cursorAuth.email ? `Logged in as ${cursorAuth.email}.` : `Credentials found in ${cursorConfigPath(cursorHome)}.` - }); - } else { - checks.push({ - code: "cursor_api_key_missing", - level: "warn", - message: "CURSOR_API_KEY is not set. Cursor runs may fail until authentication is configured.", - hint: "Set CURSOR_API_KEY in adapter env or run `agent login`." - }); - } - } - const canRunProbe = checks.every((check3) => check3.code !== "cursor_cwd_invalid" && check3.code !== "cursor_command_unresolvable"); - if (canRunProbe) { - if (!commandLooksLike3(command, "agent")) { - checks.push({ - code: "cursor_hello_probe_skipped_custom_command", - level: "info", - message: "Skipped hello probe because command is not `agent`.", - detail: command, - hint: "Use the `agent` CLI command to run the automatic installation and auth probe." - }); - } else { - const model = asString(config3.model, DEFAULT_CURSOR_LOCAL_MODEL).trim(); - const extraArgs = (() => { - const fromExtraArgs = asStringArray(config3.extraArgs); - if (fromExtraArgs.length > 0) return fromExtraArgs; - return asStringArray(config3.args); - })(); - const autoTrustEnabled = !hasCursorTrustBypassArg(extraArgs); - const args = ["-p", "--mode", "ask", "--output-format", "json", "--workspace", cwd]; - if (model) args.push("--model", model); - if (autoTrustEnabled) args.push("--yolo"); - if (extraArgs.length > 0) args.push(...extraArgs); - args.push("Respond with hello."); - const probe = await runChildProcess( - `cursor-envtest-${Date.now()}-${Math.random().toString(16).slice(2)}`, - command, - args, - { - cwd, - env: env2, - timeoutSec: 45, - graceSec: 5, - onLog: async () => { - } - } - ); - const parsed = parseCursorJsonl(probe.stdout); - const detail = summarizeProbeDetail4(probe.stdout, probe.stderr, parsed.errorMessage); - const authEvidence = `${parsed.errorMessage ?? ""} -${probe.stdout} -${probe.stderr}`.trim(); - if (probe.timedOut) { - checks.push({ - code: "cursor_hello_probe_timed_out", - level: "warn", - message: "Cursor hello probe timed out.", - hint: 'Retry the probe. If this persists, verify `agent -p --mode ask --output-format json "Respond with hello."` manually.' - }); - } else if ((probe.exitCode ?? 1) === 0) { - const summary = parsed.summary.trim(); - const hasHello = /\bhello\b/i.test(summary); - checks.push({ - code: hasHello ? "cursor_hello_probe_passed" : "cursor_hello_probe_unexpected_output", - level: hasHello ? "info" : "warn", - message: hasHello ? "Cursor hello probe succeeded." : "Cursor probe ran but did not return `hello` as expected.", - ...summary ? { detail: summary.replace(/\s+/g, " ").trim().slice(0, 240) } : {}, - ...hasHello ? {} : { - hint: 'Try `agent -p --mode ask --output-format json "Respond with hello."` manually to inspect full output.' - } - }); - } else if (CURSOR_AUTH_REQUIRED_RE.test(authEvidence)) { - checks.push({ - code: "cursor_hello_probe_auth_required", - level: "warn", - message: "Cursor CLI is installed, but authentication is not ready.", - ...detail ? { detail } : {}, - hint: "Run `agent login` or configure CURSOR_API_KEY in adapter env/shell, then retry the probe." - }); - } else { - checks.push({ - code: "cursor_hello_probe_failed", - level: "error", - message: "Cursor hello probe failed.", - ...detail ? { detail } : {}, - hint: 'Run `agent -p --mode ask --output-format json "Respond with hello."` manually in this working directory to debug.' - }); - } - } - } - return { - adapterType: ctx.adapterType, - status: summarizeStatus4(checks), - checks, - testedAt: (/* @__PURE__ */ new Date()).toISOString() - }; -} - -// packages/adapters/cursor-local/src/server/index.ts -function readNonEmptyString5(value) { - return typeof value === "string" && value.trim().length > 0 ? value.trim() : null; -} -var sessionCodec4 = { - deserialize(raw) { - if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return null; - const record2 = raw; - const sessionId = readNonEmptyString5(record2.sessionId) ?? readNonEmptyString5(record2.session_id) ?? readNonEmptyString5(record2.sessionID); - if (!sessionId) return null; - const cwd = readNonEmptyString5(record2.cwd) ?? readNonEmptyString5(record2.workdir) ?? readNonEmptyString5(record2.folder); - const workspaceId = readNonEmptyString5(record2.workspaceId) ?? readNonEmptyString5(record2.workspace_id); - const repoUrl = readNonEmptyString5(record2.repoUrl) ?? readNonEmptyString5(record2.repo_url); - const repoRef = readNonEmptyString5(record2.repoRef) ?? readNonEmptyString5(record2.repo_ref); - return { - sessionId, - ...cwd ? { cwd } : {}, - ...workspaceId ? { workspaceId } : {}, - ...repoUrl ? { repoUrl } : {}, - ...repoRef ? { repoRef } : {} - }; - }, - serialize(params) { - if (!params) return null; - const sessionId = readNonEmptyString5(params.sessionId) ?? readNonEmptyString5(params.session_id) ?? readNonEmptyString5(params.sessionID); - if (!sessionId) return null; - const cwd = readNonEmptyString5(params.cwd) ?? readNonEmptyString5(params.workdir) ?? readNonEmptyString5(params.folder); - const workspaceId = readNonEmptyString5(params.workspaceId) ?? readNonEmptyString5(params.workspace_id); - const repoUrl = readNonEmptyString5(params.repoUrl) ?? readNonEmptyString5(params.repo_url); - const repoRef = readNonEmptyString5(params.repoRef) ?? readNonEmptyString5(params.repo_ref); - return { - sessionId, - ...cwd ? { cwd } : {}, - ...workspaceId ? { workspaceId } : {}, - ...repoUrl ? { repoUrl } : {}, - ...repoRef ? { repoRef } : {} - }; - }, - getDisplayId(params) { - if (!params) return null; - return readNonEmptyString5(params.sessionId) ?? readNonEmptyString5(params.session_id) ?? readNonEmptyString5(params.sessionID); - } -}; - -// packages/adapters/gemini-local/src/server/execute.ts -import fs19 from "node:fs/promises"; -import os16 from "node:os"; -import path24 from "node:path"; -import { fileURLToPath as fileURLToPath10 } from "node:url"; - -// packages/adapters/gemini-local/src/index.ts -var DEFAULT_GEMINI_LOCAL_MODEL = "auto"; -var models4 = [ - { id: DEFAULT_GEMINI_LOCAL_MODEL, label: "Auto" }, - { id: "gemini-2.5-pro", label: "Gemini 2.5 Pro" }, - { id: "gemini-2.5-flash", label: "Gemini 2.5 Flash" }, - { id: "gemini-2.5-flash-lite", label: "Gemini 2.5 Flash Lite" }, - { id: "gemini-2.0-flash", label: "Gemini 2.0 Flash" }, - { id: "gemini-2.0-flash-lite", label: "Gemini 2.0 Flash Lite" } -]; -var agentConfigurationDoc4 = `# gemini_local agent configuration - -Adapter: gemini_local - -Use when: -- You want Taskcore to run the Gemini CLI locally on the host machine -- You want Gemini chat sessions resumed across heartbeats with --resume -- You want Taskcore skills injected locally without polluting the global environment - -Don't use when: -- You need webhook-style external invocation (use http or openclaw_gateway) -- You only need a one-shot script without an AI coding agent loop (use process) -- Gemini CLI is not installed on the machine that runs Taskcore - -Core fields: -- cwd (string, optional): default absolute working directory fallback for the agent process (created if missing when possible) -- instructionsFilePath (string, optional): absolute path to a markdown instructions file prepended to the run prompt -- promptTemplate (string, optional): run prompt template -- model (string, optional): Gemini model id. Defaults to auto. -- sandbox (boolean, optional): run in sandbox mode (default: false, passes --sandbox=none) -- command (string, optional): defaults to "gemini" -- extraArgs (string[], optional): additional CLI args -- env (object, optional): KEY=VALUE environment variables - -Operational fields: -- timeoutSec (number, optional): run timeout in seconds -- graceSec (number, optional): SIGTERM grace period in seconds - -Notes: -- Runs use positional prompt arguments, not stdin. -- Sessions resume with --resume when stored session cwd matches the current cwd. -- Taskcore auto-injects local skills into \`~/.gemini/skills/\` via symlinks, so the CLI can discover both credentials and skills in their natural location. -- Authentication can use GEMINI_API_KEY / GOOGLE_API_KEY or local Gemini CLI login. -`; - -// packages/adapters/gemini-local/src/server/parse.ts -function collectMessageText(message2) { - if (typeof message2 === "string") { - const trimmed = message2.trim(); - return trimmed ? [trimmed] : []; - } - const record2 = parseObject(message2); - const direct = asString(record2.text, "").trim(); - const lines = direct ? [direct] : []; - const content = Array.isArray(record2.content) ? record2.content : []; - for (const partRaw of content) { - const part = parseObject(partRaw); - const type = asString(part.type, "").trim(); - if (type === "output_text" || type === "text" || type === "content") { - const text3 = asString(part.text, "").trim() || asString(part.content, "").trim(); - if (text3) lines.push(text3); - } - } - return lines; -} -function readSessionId2(event) { - return asString(event.session_id, "").trim() || asString(event.sessionId, "").trim() || asString(event.sessionID, "").trim() || asString(event.checkpoint_id, "").trim() || asString(event.thread_id, "").trim() || null; -} -function asErrorText2(value) { - if (typeof value === "string") return value; - const rec = parseObject(value); - const message2 = asString(rec.message, "") || asString(rec.error, "") || asString(rec.code, "") || asString(rec.detail, ""); - if (message2) return message2; - try { - return JSON.stringify(rec); - } catch { - return ""; - } -} -function accumulateUsage(target, usageRaw) { - const usage = parseObject(usageRaw); - const usageMetadata = parseObject(usage.usageMetadata); - const source = Object.keys(usageMetadata).length > 0 ? usageMetadata : usage; - target.inputTokens += asNumber( - source.input_tokens, - asNumber(source.inputTokens, asNumber(source.promptTokenCount, 0)) - ); - target.cachedInputTokens += asNumber( - source.cached_input_tokens, - asNumber(source.cachedInputTokens, asNumber(source.cachedContentTokenCount, 0)) - ); - target.outputTokens += asNumber( - source.output_tokens, - asNumber(source.outputTokens, asNumber(source.candidatesTokenCount, 0)) - ); -} -function parseGeminiJsonl(stdout) { - let sessionId = null; - const messages2 = []; - let errorMessage = null; - let costUsd = null; - let resultEvent = null; - let question = null; - const usage = { - inputTokens: 0, - cachedInputTokens: 0, - outputTokens: 0 - }; - for (const rawLine of stdout.split(/\r?\n/)) { - const line3 = rawLine.trim(); - if (!line3) continue; - const event = parseJson2(line3); - if (!event) continue; - const foundSessionId = readSessionId2(event); - if (foundSessionId) sessionId = foundSessionId; - const type = asString(event.type, "").trim(); - if (type === "assistant") { - messages2.push(...collectMessageText(event.message)); - const messageObj = parseObject(event.message); - const content = Array.isArray(messageObj.content) ? messageObj.content : []; - for (const partRaw of content) { - const part = parseObject(partRaw); - if (asString(part.type, "").trim() === "question") { - question = { - prompt: asString(part.prompt, "").trim(), - choices: (Array.isArray(part.choices) ? part.choices : []).map((choiceRaw) => { - const choice = parseObject(choiceRaw); - return { - key: asString(choice.key, "").trim(), - label: asString(choice.label, "").trim(), - description: asString(choice.description, "").trim() || void 0 - }; - }) - }; - break; - } - } - continue; - } - if (type === "result") { - resultEvent = event; - accumulateUsage(usage, event.usage ?? event.usageMetadata); - const resultText = asString(event.result, "").trim() || asString(event.text, "").trim() || asString(event.response, "").trim(); - if (resultText && messages2.length === 0) messages2.push(resultText); - costUsd = asNumber(event.total_cost_usd, asNumber(event.cost_usd, asNumber(event.cost, costUsd ?? 0))) || costUsd; - const isError = event.is_error === true || asString(event.subtype, "").toLowerCase() === "error"; - if (isError) { - const text3 = asErrorText2(event.error ?? event.message ?? event.result).trim(); - if (text3) errorMessage = text3; - } - continue; - } - if (type === "error") { - const text3 = asErrorText2(event.error ?? event.message ?? event.detail).trim(); - if (text3) errorMessage = text3; - continue; - } - if (type === "system") { - const subtype = asString(event.subtype, "").trim().toLowerCase(); - if (subtype === "error") { - const text3 = asErrorText2(event.error ?? event.message ?? event.detail).trim(); - if (text3) errorMessage = text3; - } - continue; - } - if (type === "text") { - const part = parseObject(event.part); - const text3 = asString(part.text, "").trim(); - if (text3) messages2.push(text3); - continue; - } - if (type === "step_finish" || event.usage || event.usageMetadata) { - accumulateUsage(usage, event.usage ?? event.usageMetadata); - costUsd = asNumber(event.total_cost_usd, asNumber(event.cost_usd, asNumber(event.cost, costUsd ?? 0))) || costUsd; - continue; - } - } - return { - sessionId, - summary: messages2.join("\n\n").trim(), - usage, - costUsd, - errorMessage, - resultEvent, - question - }; -} -function isGeminiUnknownSessionError(stdout, stderr) { - const haystack = `${stdout} -${stderr}`.split(/\r?\n/).map((line3) => line3.trim()).filter(Boolean).join("\n"); - return /unknown\s+session|session\s+.*\s+not\s+found|resume\s+.*\s+not\s+found|checkpoint\s+.*\s+not\s+found|cannot\s+resume|failed\s+to\s+resume/i.test( - haystack - ); -} -function extractGeminiErrorMessages(parsed) { - const messages2 = []; - const errorMsg = asString(parsed.error, "").trim(); - if (errorMsg) messages2.push(errorMsg); - const raw = Array.isArray(parsed.errors) ? parsed.errors : []; - for (const entry of raw) { - if (typeof entry === "string") { - const msg2 = entry.trim(); - if (msg2) messages2.push(msg2); - continue; - } - if (typeof entry !== "object" || entry === null || Array.isArray(entry)) continue; - const obj = entry; - const msg = asString(obj.message, "") || asString(obj.error, "") || asString(obj.code, ""); - if (msg) { - messages2.push(msg); - continue; - } - try { - messages2.push(JSON.stringify(obj)); - } catch { - } - } - return messages2; -} -function describeGeminiFailure(parsed) { - const status = asString(parsed.status, ""); - const errors = extractGeminiErrorMessages(parsed); - const detail = errors[0] ?? ""; - const parts = ["Gemini run failed"]; - if (status) parts.push(`status=${status}`); - if (detail) parts.push(detail); - return parts.length > 1 ? parts.join(": ") : null; -} -var GEMINI_AUTH_REQUIRED_RE = /(?:not\s+authenticated|please\s+authenticate|api[_ ]?key\s+(?:required|missing|invalid)|authentication\s+required|unauthorized|invalid\s+credentials|not\s+logged\s+in|login\s+required|run\s+`?gemini\s+auth(?:\s+login)?`?\s+first)/i; -var GEMINI_QUOTA_EXHAUSTED_RE = /(?:resource_exhausted|quota|rate[-\s]?limit|too many requests|\b429\b|billing details)/i; -function detectGeminiAuthRequired(input) { - const errors = extractGeminiErrorMessages(input.parsed ?? {}); - const messages2 = [...errors, input.stdout, input.stderr].join("\n").split(/\r?\n/).map((line3) => line3.trim()).filter(Boolean); - const requiresAuth = messages2.some((line3) => GEMINI_AUTH_REQUIRED_RE.test(line3)); - return { requiresAuth }; -} -function detectGeminiQuotaExhausted(input) { - const errors = extractGeminiErrorMessages(input.parsed ?? {}); - const messages2 = [...errors, input.stdout, input.stderr].join("\n").split(/\r?\n/).map((line3) => line3.trim()).filter(Boolean); - const exhausted = messages2.some((line3) => GEMINI_QUOTA_EXHAUSTED_RE.test(line3)); - return { exhausted }; -} -function isGeminiTurnLimitResult(parsed, exitCode) { - if (exitCode === 53) return true; - if (!parsed) return false; - const status = asString(parsed.status, "").trim().toLowerCase(); - if (status === "turn_limit" || status === "max_turns") return true; - const error50 = asString(parsed.error, "").trim(); - return /turn\s*limit|max(?:imum)?\s+turns?/i.test(error50); -} - -// packages/adapters/gemini-local/src/server/utils.ts -function firstNonEmptyLine9(text3) { - return text3.split(/\r?\n/).map((line3) => line3.trim()).find(Boolean) ?? ""; -} - -// packages/adapters/gemini-local/src/server/execute.ts -var __moduleDir9 = path24.dirname(fileURLToPath10(import.meta.url)); -function hasNonEmptyEnvValue4(env2, key) { - const raw = env2[key]; - return typeof raw === "string" && raw.trim().length > 0; -} -function resolveGeminiBillingType(env2) { - return hasNonEmptyEnvValue4(env2, "GEMINI_API_KEY") || hasNonEmptyEnvValue4(env2, "GOOGLE_API_KEY") ? "api" : "subscription"; -} -function renderTaskcoreEnvNote2(env2) { - const taskcoreKeys = Object.keys(env2).filter((key) => key.startsWith("TASKCORE_")).sort(); - if (taskcoreKeys.length === 0) return ""; - return [ - "Taskcore runtime note:", - `The following TASKCORE_* environment variables are available in this run: ${taskcoreKeys.join(", ")}`, - "Do not assume these variables are missing without checking your shell environment.", - "", - "" - ].join("\n"); -} -function renderApiAccessNote(env2) { - if (!hasNonEmptyEnvValue4(env2, "TASKCORE_API_URL") || !hasNonEmptyEnvValue4(env2, "TASKCORE_API_KEY")) return ""; - return [ - "Taskcore API access note:", - "Use run_shell_command with curl to make Taskcore API requests.", - "GET example:", - ` run_shell_command({ command: "curl -s -H \\"Authorization: Bearer $TASKCORE_API_KEY\\" \\"$TASKCORE_API_URL/api/agents/me\\"" })`, - "POST/PATCH example:", - ` run_shell_command({ command: "curl -s -X POST -H \\"Authorization: Bearer $TASKCORE_API_KEY\\" -H 'Content-Type: application/json' -H \\"X-Taskcore-Run-Id: $TASKCORE_RUN_ID\\" -d '{...}' \\"$TASKCORE_API_URL/api/issues/{id}/checkout\\"" })`, - "", - "" - ].join("\n"); -} -function geminiSkillsHome() { - return path24.join(os16.homedir(), ".gemini", "skills"); -} -async function ensureGeminiSkillsInjected(onLog, skillsEntries, desiredSkillNames) { - const desiredSet = new Set(desiredSkillNames ?? skillsEntries.map((entry) => entry.key)); - const selectedEntries = skillsEntries.filter((entry) => desiredSet.has(entry.key)); - if (selectedEntries.length === 0) return; - const skillsHome = geminiSkillsHome(); - try { - await fs19.mkdir(skillsHome, { recursive: true }); - } catch (err) { - await onLog( - "stderr", - `[taskcore] Failed to prepare Gemini skills directory ${skillsHome}: ${err instanceof Error ? err.message : String(err)} -` - ); - return; - } - const removedSkills = await removeMaintainerOnlySkillSymlinks( - skillsHome, - selectedEntries.map((entry) => entry.runtimeName) - ); - for (const skillName of removedSkills) { - await onLog( - "stderr", - `[taskcore] Removed maintainer-only Gemini skill "${skillName}" from ${skillsHome} -` - ); - } - for (const entry of selectedEntries) { - const target = path24.join(skillsHome, entry.runtimeName); - try { - const result = await ensureTaskcoreSkillSymlink(entry.source, target); - if (result === "skipped") continue; - await onLog( - "stderr", - `[taskcore] ${result === "repaired" ? "Repaired" : "Linked"} Gemini skill: ${entry.key} -` - ); - } catch (err) { - await onLog( - "stderr", - `[taskcore] Failed to link Gemini skill "${entry.key}": ${err instanceof Error ? err.message : String(err)} -` - ); - } - } -} -async function execute5(ctx) { - const { runId, agent, runtime, config: config3, context, onLog, onMeta, onSpawn, authToken } = ctx; - const promptTemplate = asString( - config3.promptTemplate, - "You are agent {{agent.id}} ({{agent.name}}). Continue your Taskcore work." - ); - const command = asString(config3.command, "gemini"); - const model = asString(config3.model, DEFAULT_GEMINI_LOCAL_MODEL).trim(); - const sandbox = asBoolean(config3.sandbox, false); - const workspaceContext = parseObject(context.taskcoreWorkspace); - const workspaceCwd = asString(workspaceContext.cwd, ""); - const workspaceSource = asString(workspaceContext.source, ""); - const workspaceId = asString(workspaceContext.workspaceId, ""); - const workspaceRepoUrl = asString(workspaceContext.repoUrl, ""); - const workspaceRepoRef = asString(workspaceContext.repoRef, ""); - const agentHome = asString(workspaceContext.agentHome, ""); - const workspaceHints = Array.isArray(context.taskcoreWorkspaces) ? context.taskcoreWorkspaces.filter( - (value) => typeof value === "object" && value !== null - ) : []; - const configuredCwd = asString(config3.cwd, ""); - const useConfiguredInsteadOfAgentHome = workspaceSource === "agent_home" && configuredCwd.length > 0; - const effectiveWorkspaceCwd = useConfiguredInsteadOfAgentHome ? "" : workspaceCwd; - const cwd = effectiveWorkspaceCwd || configuredCwd || process.cwd(); - await ensureAbsoluteDirectory(cwd, { createIfMissing: true }); - const geminiSkillEntries = await readTaskcoreRuntimeSkillEntries(config3, __moduleDir9); - const desiredGeminiSkillNames = resolveTaskcoreDesiredSkillNames(config3, geminiSkillEntries); - await ensureGeminiSkillsInjected(onLog, geminiSkillEntries, desiredGeminiSkillNames); - const envConfig = parseObject(config3.env); - const hasExplicitApiKey = typeof envConfig.TASKCORE_API_KEY === "string" && envConfig.TASKCORE_API_KEY.trim().length > 0; - const env2 = { ...buildTaskcoreEnv(agent) }; - env2.TASKCORE_RUN_ID = runId; - const wakeTaskId = typeof context.taskId === "string" && context.taskId.trim().length > 0 && context.taskId.trim() || typeof context.issueId === "string" && context.issueId.trim().length > 0 && context.issueId.trim() || null; - const wakeReason = typeof context.wakeReason === "string" && context.wakeReason.trim().length > 0 ? context.wakeReason.trim() : null; - const wakeCommentId = typeof context.wakeCommentId === "string" && context.wakeCommentId.trim().length > 0 && context.wakeCommentId.trim() || typeof context.commentId === "string" && context.commentId.trim().length > 0 && context.commentId.trim() || null; - const approvalId = typeof context.approvalId === "string" && context.approvalId.trim().length > 0 ? context.approvalId.trim() : null; - const approvalStatus = typeof context.approvalStatus === "string" && context.approvalStatus.trim().length > 0 ? context.approvalStatus.trim() : null; - const linkedIssueIds = Array.isArray(context.issueIds) ? context.issueIds.filter((value) => typeof value === "string" && value.trim().length > 0) : []; - const wakePayloadJson = stringifyTaskcoreWakePayload(context.taskcoreWake); - if (wakeTaskId) env2.TASKCORE_TASK_ID = wakeTaskId; - if (wakeReason) env2.TASKCORE_WAKE_REASON = wakeReason; - if (wakeCommentId) env2.TASKCORE_WAKE_COMMENT_ID = wakeCommentId; - if (approvalId) env2.TASKCORE_APPROVAL_ID = approvalId; - if (approvalStatus) env2.TASKCORE_APPROVAL_STATUS = approvalStatus; - if (linkedIssueIds.length > 0) env2.TASKCORE_LINKED_ISSUE_IDS = linkedIssueIds.join(","); - if (wakePayloadJson) env2.TASKCORE_WAKE_PAYLOAD_JSON = wakePayloadJson; - if (effectiveWorkspaceCwd) env2.TASKCORE_WORKSPACE_CWD = effectiveWorkspaceCwd; - if (workspaceSource) env2.TASKCORE_WORKSPACE_SOURCE = workspaceSource; - if (workspaceId) env2.TASKCORE_WORKSPACE_ID = workspaceId; - if (workspaceRepoUrl) env2.TASKCORE_WORKSPACE_REPO_URL = workspaceRepoUrl; - if (workspaceRepoRef) env2.TASKCORE_WORKSPACE_REPO_REF = workspaceRepoRef; - if (agentHome) env2.AGENT_HOME = agentHome; - if (workspaceHints.length > 0) env2.TASKCORE_WORKSPACES_JSON = JSON.stringify(workspaceHints); - for (const [key, value] of Object.entries(envConfig)) { - if (typeof value === "string") env2[key] = value; - } - if (!hasExplicitApiKey && authToken) { - env2.TASKCORE_API_KEY = authToken; - } - const effectiveEnv = Object.fromEntries( - Object.entries({ ...process.env, ...env2 }).filter( - (entry) => typeof entry[1] === "string" - ) - ); - const billingType = resolveGeminiBillingType(effectiveEnv); - const runtimeEnv = ensurePathInEnv(effectiveEnv); - await ensureCommandResolvable(command, cwd, runtimeEnv); - const resolvedCommand = await resolveCommandForLogs(command, cwd, runtimeEnv); - const loggedEnv = buildInvocationEnvForLogs(env2, { - runtimeEnv, - includeRuntimeKeys: ["HOME"], - resolvedCommand - }); - const timeoutSec = asNumber(config3.timeoutSec, 0); - const graceSec = asNumber(config3.graceSec, 20); - const extraArgs = (() => { - const fromExtraArgs = asStringArray(config3.extraArgs); - if (fromExtraArgs.length > 0) return fromExtraArgs; - return asStringArray(config3.args); - })(); - const runtimeSessionParams = parseObject(runtime.sessionParams); - const runtimeSessionId = asString(runtimeSessionParams.sessionId, runtime.sessionId ?? ""); - const runtimeSessionCwd = asString(runtimeSessionParams.cwd, ""); - const canResumeSession = runtimeSessionId.length > 0 && (runtimeSessionCwd.length === 0 || path24.resolve(runtimeSessionCwd) === path24.resolve(cwd)); - const sessionId = canResumeSession ? runtimeSessionId : null; - if (runtimeSessionId && !canResumeSession) { - await onLog( - "stdout", - `[taskcore] Gemini session "${runtimeSessionId}" was saved for cwd "${runtimeSessionCwd}" and will not be resumed in "${cwd}". -` - ); - } - const instructionsFilePath = asString(config3.instructionsFilePath, "").trim(); - const instructionsDir = instructionsFilePath ? `${path24.dirname(instructionsFilePath)}/` : ""; - let instructionsPrefix = ""; - if (instructionsFilePath) { - try { - const instructionsContents = await fs19.readFile(instructionsFilePath, "utf8"); - instructionsPrefix = `${instructionsContents} - -The above agent instructions were loaded from ${instructionsFilePath}. Resolve any relative file references from ${instructionsDir}. - -`; - } catch (err) { - const reason = err instanceof Error ? err.message : String(err); - await onLog( - "stdout", - `[taskcore] Warning: could not read agent instructions file "${instructionsFilePath}": ${reason} -` - ); - } - } - const commandNotes = (() => { - const notes = ["Prompt is passed to Gemini via --prompt for non-interactive execution."]; - notes.push("Added --approval-mode yolo for unattended execution."); - if (!instructionsFilePath) return notes; - if (instructionsPrefix.length > 0) { - notes.push( - `Loaded agent instructions from ${instructionsFilePath}`, - `Prepended instructions + path directive to prompt (relative references from ${instructionsDir}).` - ); - return notes; - } - notes.push( - `Configured instructionsFilePath ${instructionsFilePath}, but file could not be read; continuing without injected instructions.` - ); - return notes; - })(); - const bootstrapPromptTemplate = asString(config3.bootstrapPromptTemplate, ""); - const templateData = { - agentId: agent.id, - companyId: agent.companyId, - runId, - company: { id: agent.companyId }, - agent, - run: { id: runId, source: "on_demand" }, - context - }; - const renderedBootstrapPrompt = !sessionId && bootstrapPromptTemplate.trim().length > 0 ? renderTemplate(bootstrapPromptTemplate, templateData).trim() : ""; - const wakePrompt = renderTaskcoreWakePrompt(context.taskcoreWake, { resumedSession: Boolean(sessionId) }); - const shouldUseResumeDeltaPrompt = Boolean(sessionId) && wakePrompt.length > 0; - const renderedPrompt = shouldUseResumeDeltaPrompt ? "" : renderTemplate(promptTemplate, templateData); - const sessionHandoffNote = asString(context.taskcoreSessionHandoffMarkdown, "").trim(); - const taskcoreEnvNote = renderTaskcoreEnvNote2(env2); - const apiAccessNote = renderApiAccessNote(env2); - const prompt = joinPromptSections([ - instructionsPrefix, - renderedBootstrapPrompt, - wakePrompt, - sessionHandoffNote, - taskcoreEnvNote, - apiAccessNote, - renderedPrompt - ]); - const promptMetrics = { - promptChars: prompt.length, - instructionsChars: instructionsPrefix.length, - bootstrapPromptChars: renderedBootstrapPrompt.length, - wakePromptChars: wakePrompt.length, - sessionHandoffChars: sessionHandoffNote.length, - runtimeNoteChars: taskcoreEnvNote.length + apiAccessNote.length, - heartbeatPromptChars: renderedPrompt.length - }; - const buildArgs = (resumeSessionId) => { - const args = ["--output-format", "stream-json"]; - if (resumeSessionId) args.push("--resume", resumeSessionId); - if (model && model !== DEFAULT_GEMINI_LOCAL_MODEL) args.push("--model", model); - args.push("--approval-mode", "yolo"); - if (sandbox) { - args.push("--sandbox"); - } else { - args.push("--sandbox=none"); - } - if (extraArgs.length > 0) args.push(...extraArgs); - args.push("--prompt", prompt); - return args; - }; - const runAttempt = async (resumeSessionId) => { - const args = buildArgs(resumeSessionId); - if (onMeta) { - await onMeta({ - adapterType: "gemini_local", - command: resolvedCommand, - cwd, - commandNotes, - commandArgs: args.map((value, index2) => index2 === args.length - 1 ? `` : value), - env: loggedEnv, - prompt, - promptMetrics, - context - }); - } - const proc = await runChildProcess(runId, command, args, { - cwd, - env: env2, - timeoutSec, - graceSec, - onSpawn, - onLog - }); - return { - proc, - parsed: parseGeminiJsonl(proc.stdout) - }; - }; - const toResult = (attempt, clearSessionOnMissingSession = false, isRetry = false) => { - const authMeta = detectGeminiAuthRequired({ - parsed: attempt.parsed.resultEvent, - stdout: attempt.proc.stdout, - stderr: attempt.proc.stderr - }); - if (attempt.proc.timedOut) { - return { - exitCode: attempt.proc.exitCode, - signal: attempt.proc.signal, - timedOut: true, - errorMessage: `Timed out after ${timeoutSec}s`, - errorCode: authMeta.requiresAuth ? "gemini_auth_required" : null, - clearSession: clearSessionOnMissingSession - }; - } - const clearSessionForTurnLimit = isGeminiTurnLimitResult(attempt.parsed.resultEvent, attempt.proc.exitCode); - const canFallbackToRuntimeSession = !isRetry; - const resolvedSessionId = attempt.parsed.sessionId ?? (canFallbackToRuntimeSession ? runtimeSessionId ?? runtime.sessionId ?? null : null); - const resolvedSessionParams = resolvedSessionId ? { - sessionId: resolvedSessionId, - cwd, - ...workspaceId ? { workspaceId } : {}, - ...workspaceRepoUrl ? { repoUrl: workspaceRepoUrl } : {}, - ...workspaceRepoRef ? { repoRef: workspaceRepoRef } : {} - } : null; - const parsedError = typeof attempt.parsed.errorMessage === "string" ? attempt.parsed.errorMessage.trim() : ""; - const stderrLine = firstNonEmptyLine9(attempt.proc.stderr); - const structuredFailure = attempt.parsed.resultEvent ? describeGeminiFailure(attempt.parsed.resultEvent) : null; - const fallbackErrorMessage = parsedError || structuredFailure || stderrLine || `Gemini exited with code ${attempt.proc.exitCode ?? -1}`; - return { - exitCode: attempt.proc.exitCode, - signal: attempt.proc.signal, - timedOut: false, - errorMessage: (attempt.proc.exitCode ?? 0) === 0 ? null : fallbackErrorMessage, - errorCode: (attempt.proc.exitCode ?? 0) !== 0 && authMeta.requiresAuth ? "gemini_auth_required" : null, - usage: attempt.parsed.usage, - sessionId: resolvedSessionId, - sessionParams: resolvedSessionParams, - sessionDisplayId: resolvedSessionId, - provider: "google", - biller: "google", - model, - billingType, - costUsd: attempt.parsed.costUsd, - resultJson: attempt.parsed.resultEvent ?? { - stdout: attempt.proc.stdout, - stderr: attempt.proc.stderr - }, - summary: attempt.parsed.summary, - question: attempt.parsed.question, - clearSession: clearSessionForTurnLimit || Boolean(clearSessionOnMissingSession && !resolvedSessionId) - }; - }; - const initial = await runAttempt(sessionId); - if (sessionId && !initial.proc.timedOut && (initial.proc.exitCode ?? 0) !== 0 && isGeminiUnknownSessionError(initial.proc.stdout, initial.proc.stderr)) { - await onLog( - "stdout", - `[taskcore] Gemini resume session "${sessionId}" is unavailable; retrying with a fresh session. -` - ); - const retry = await runAttempt(null); - return toResult(retry, true, true); - } - return toResult(initial); -} - -// packages/adapters/gemini-local/src/server/skills.ts -import fs20 from "node:fs/promises"; -import os17 from "node:os"; -import path25 from "node:path"; -import { fileURLToPath as fileURLToPath11 } from "node:url"; -var __moduleDir10 = path25.dirname(fileURLToPath11(import.meta.url)); -function asString7(value) { - return typeof value === "string" && value.trim().length > 0 ? value.trim() : null; -} -function resolveGeminiSkillsHome(config3) { - const env2 = typeof config3.env === "object" && config3.env !== null && !Array.isArray(config3.env) ? config3.env : {}; - const configuredHome = asString7(env2.HOME); - const home = configuredHome ? path25.resolve(configuredHome) : os17.homedir(); - return path25.join(home, ".gemini", "skills"); -} -async function buildGeminiSkillSnapshot(config3) { - const availableEntries = await readTaskcoreRuntimeSkillEntries(config3, __moduleDir10); - const desiredSkills = resolveTaskcoreDesiredSkillNames(config3, availableEntries); - const skillsHome = resolveGeminiSkillsHome(config3); - const installed = await readInstalledSkillTargets(skillsHome); - return buildPersistentSkillSnapshot({ - adapterType: "gemini_local", - availableEntries, - desiredSkills, - installed, - skillsHome, - locationLabel: "~/.gemini/skills", - missingDetail: "Configured but not currently linked into the Gemini skills home.", - externalConflictDetail: "Skill name is occupied by an external installation.", - externalDetail: "Installed outside Taskcore management." - }); -} -async function listGeminiSkills(ctx) { - return buildGeminiSkillSnapshot(ctx.config); -} -async function syncGeminiSkills(ctx, desiredSkills) { - const availableEntries = await readTaskcoreRuntimeSkillEntries(ctx.config, __moduleDir10); - const desiredSet = /* @__PURE__ */ new Set([ - ...desiredSkills, - ...availableEntries.filter((entry) => entry.required).map((entry) => entry.key) - ]); - const skillsHome = resolveGeminiSkillsHome(ctx.config); - await fs20.mkdir(skillsHome, { recursive: true }); - const installed = await readInstalledSkillTargets(skillsHome); - const availableByRuntimeName = new Map(availableEntries.map((entry) => [entry.runtimeName, entry])); - for (const available of availableEntries) { - if (!desiredSet.has(available.key)) continue; - const target = path25.join(skillsHome, available.runtimeName); - await ensureTaskcoreSkillSymlink(available.source, target); - } - for (const [name, installedEntry] of installed.entries()) { - const available = availableByRuntimeName.get(name); - if (!available) continue; - if (desiredSet.has(available.key)) continue; - if (installedEntry.targetPath !== available.source) continue; - await fs20.unlink(path25.join(skillsHome, name)).catch(() => { - }); - } - return buildGeminiSkillSnapshot(ctx.config); -} - -// packages/adapters/gemini-local/src/server/test.ts -import path26 from "node:path"; -function summarizeStatus5(checks) { - if (checks.some((check3) => check3.level === "error")) return "fail"; - if (checks.some((check3) => check3.level === "warn")) return "warn"; - return "pass"; -} -function isNonEmpty4(value) { - return typeof value === "string" && value.trim().length > 0; -} -function commandLooksLike4(command, expected) { - const base = path26.basename(command).toLowerCase(); - return base === expected || base === `${expected}.cmd` || base === `${expected}.exe`; -} -function summarizeProbeDetail5(stdout, stderr, parsedError) { - const raw = parsedError?.trim() || firstNonEmptyLine9(stderr) || firstNonEmptyLine9(stdout); - if (!raw) return null; - const clean3 = raw.replace(/\s+/g, " ").trim(); - const max = 240; - return clean3.length > max ? `${clean3.slice(0, max - 1)}\u2026` : clean3; -} -async function testEnvironment5(ctx) { - const checks = []; - const config3 = parseObject(ctx.config); - const command = asString(config3.command, "gemini"); - const cwd = asString(config3.cwd, process.cwd()); - try { - await ensureAbsoluteDirectory(cwd, { createIfMissing: true }); - checks.push({ - code: "gemini_cwd_valid", - level: "info", - message: `Working directory is valid: ${cwd}` - }); - } catch (err) { - checks.push({ - code: "gemini_cwd_invalid", - level: "error", - message: err instanceof Error ? err.message : "Invalid working directory", - detail: cwd - }); - } - const envConfig = parseObject(config3.env); - const env2 = {}; - for (const [key, value] of Object.entries(envConfig)) { - if (typeof value === "string") env2[key] = value; - } - const runtimeEnv = ensurePathInEnv({ ...process.env, ...env2 }); - try { - await ensureCommandResolvable(command, cwd, runtimeEnv); - checks.push({ - code: "gemini_command_resolvable", - level: "info", - message: `Command is executable: ${command}` - }); - } catch (err) { - checks.push({ - code: "gemini_command_unresolvable", - level: "error", - message: err instanceof Error ? err.message : "Command is not executable", - detail: command - }); - } - const configGeminiApiKey = env2.GEMINI_API_KEY; - const hostGeminiApiKey = process.env.GEMINI_API_KEY; - const configGoogleApiKey = env2.GOOGLE_API_KEY; - const hostGoogleApiKey = process.env.GOOGLE_API_KEY; - const hasGca = env2.GOOGLE_GENAI_USE_GCA === "true" || process.env.GOOGLE_GENAI_USE_GCA === "true"; - if (isNonEmpty4(configGeminiApiKey) || isNonEmpty4(hostGeminiApiKey) || isNonEmpty4(configGoogleApiKey) || isNonEmpty4(hostGoogleApiKey) || hasGca) { - const source = hasGca ? "Google account login (GCA)" : isNonEmpty4(configGeminiApiKey) || isNonEmpty4(configGoogleApiKey) ? "adapter config env" : "server environment"; - checks.push({ - code: "gemini_api_key_present", - level: "info", - message: "Gemini API credentials are set for CLI authentication.", - detail: `Detected in ${source}.` - }); - } else { - checks.push({ - code: "gemini_api_key_missing", - level: "info", - message: "No explicit API key detected. Gemini CLI may still authenticate via `gemini auth login` (OAuth).", - hint: "If the hello probe fails with an auth error, set GEMINI_API_KEY or GOOGLE_API_KEY in adapter env, or run `gemini auth login`." - }); - } - const canRunProbe = checks.every((check3) => check3.code !== "gemini_cwd_invalid" && check3.code !== "gemini_command_unresolvable"); - if (canRunProbe) { - if (!commandLooksLike4(command, "gemini")) { - checks.push({ - code: "gemini_hello_probe_skipped_custom_command", - level: "info", - message: "Skipped hello probe because command is not `gemini`.", - detail: command, - hint: "Use the `gemini` CLI command to run the automatic installation and auth probe." - }); - } else { - const model = asString(config3.model, DEFAULT_GEMINI_LOCAL_MODEL).trim(); - const approvalMode = asString(config3.approvalMode, asBoolean(config3.yolo, false) ? "yolo" : "default"); - const sandbox = asBoolean(config3.sandbox, false); - const helloProbeTimeoutSec = Math.max(1, asNumber(config3.helloProbeTimeoutSec, 10)); - const extraArgs = (() => { - const fromExtraArgs = asStringArray(config3.extraArgs); - if (fromExtraArgs.length > 0) return fromExtraArgs; - return asStringArray(config3.args); - })(); - const args = ["--output-format", "stream-json", "--prompt", "Respond with hello."]; - if (model && model !== DEFAULT_GEMINI_LOCAL_MODEL) args.push("--model", model); - if (approvalMode !== "default") args.push("--approval-mode", approvalMode); - if (sandbox) { - args.push("--sandbox"); - } else { - args.push("--sandbox=none"); - } - if (extraArgs.length > 0) args.push(...extraArgs); - const probe = await runChildProcess( - `gemini-envtest-${Date.now()}-${Math.random().toString(16).slice(2)}`, - command, - args, - { - cwd, - env: env2, - timeoutSec: helloProbeTimeoutSec, - graceSec: 5, - onLog: async () => { - } - } - ); - const parsed = parseGeminiJsonl(probe.stdout); - const detail = summarizeProbeDetail5(probe.stdout, probe.stderr, parsed.errorMessage); - const authMeta = detectGeminiAuthRequired({ - parsed: parsed.resultEvent, - stdout: probe.stdout, - stderr: probe.stderr - }); - const quotaMeta = detectGeminiQuotaExhausted({ - parsed: parsed.resultEvent, - stdout: probe.stdout, - stderr: probe.stderr - }); - if (quotaMeta.exhausted) { - checks.push({ - code: "gemini_hello_probe_quota_exhausted", - level: "warn", - message: probe.timedOut ? "Gemini CLI is retrying after quota exhaustion." : "Gemini CLI authentication is configured, but the current account or API key is over quota.", - ...detail ? { detail } : {}, - hint: "The configured Gemini account or API key is over quota. Check ai.google.dev usage/billing, then retry the probe." - }); - } else if (probe.timedOut) { - checks.push({ - code: "gemini_hello_probe_timed_out", - level: "warn", - message: "Gemini hello probe timed out.", - hint: "Retry the probe. If this persists, verify Gemini can run `Respond with hello.` from this directory manually." - }); - } else if ((probe.exitCode ?? 1) === 0) { - const summary = parsed.summary.trim(); - const hasHello = /\bhello\b/i.test(summary); - checks.push({ - code: hasHello ? "gemini_hello_probe_passed" : "gemini_hello_probe_unexpected_output", - level: hasHello ? "info" : "warn", - message: hasHello ? "Gemini hello probe succeeded." : "Gemini probe ran but did not return `hello` as expected.", - ...summary ? { detail: summary.replace(/\s+/g, " ").trim().slice(0, 240) } : {}, - ...hasHello ? {} : { - hint: 'Try `gemini --output-format json "Respond with hello."` manually to inspect full output.' - } - }); - } else if (authMeta.requiresAuth) { - checks.push({ - code: "gemini_hello_probe_auth_required", - level: "warn", - message: "Gemini CLI is installed, but authentication is not ready.", - ...detail ? { detail } : {}, - hint: "Run `gemini auth` or configure GEMINI_API_KEY / GOOGLE_API_KEY in adapter env/shell, then retry the probe." - }); - } else { - checks.push({ - code: "gemini_hello_probe_failed", - level: "error", - message: "Gemini hello probe failed.", - ...detail ? { detail } : {}, - hint: 'Run `gemini --output-format json "Respond with hello."` manually in this working directory to debug.' - }); - } - } - } - return { - adapterType: ctx.adapterType, - status: summarizeStatus5(checks), - checks, - testedAt: (/* @__PURE__ */ new Date()).toISOString() - }; -} - -// packages/adapters/gemini-local/src/server/index.ts -function readNonEmptyString6(value) { - return typeof value === "string" && value.trim().length > 0 ? value.trim() : null; -} -var sessionCodec5 = { - deserialize(raw) { - if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return null; - const record2 = raw; - const sessionId = readNonEmptyString6(record2.sessionId) ?? readNonEmptyString6(record2.session_id) ?? readNonEmptyString6(record2.sessionID); - if (!sessionId) return null; - const cwd = readNonEmptyString6(record2.cwd) ?? readNonEmptyString6(record2.workdir) ?? readNonEmptyString6(record2.folder); - const workspaceId = readNonEmptyString6(record2.workspaceId) ?? readNonEmptyString6(record2.workspace_id); - const repoUrl = readNonEmptyString6(record2.repoUrl) ?? readNonEmptyString6(record2.repo_url); - const repoRef = readNonEmptyString6(record2.repoRef) ?? readNonEmptyString6(record2.repo_ref); - return { - sessionId, - ...cwd ? { cwd } : {}, - ...workspaceId ? { workspaceId } : {}, - ...repoUrl ? { repoUrl } : {}, - ...repoRef ? { repoRef } : {} - }; - }, - serialize(params) { - if (!params) return null; - const sessionId = readNonEmptyString6(params.sessionId) ?? readNonEmptyString6(params.session_id) ?? readNonEmptyString6(params.sessionID); - if (!sessionId) return null; - const cwd = readNonEmptyString6(params.cwd) ?? readNonEmptyString6(params.workdir) ?? readNonEmptyString6(params.folder); - const workspaceId = readNonEmptyString6(params.workspaceId) ?? readNonEmptyString6(params.workspace_id); - const repoUrl = readNonEmptyString6(params.repoUrl) ?? readNonEmptyString6(params.repo_url); - const repoRef = readNonEmptyString6(params.repoRef) ?? readNonEmptyString6(params.repo_ref); - return { - sessionId, - ...cwd ? { cwd } : {}, - ...workspaceId ? { workspaceId } : {}, - ...repoUrl ? { repoUrl } : {}, - ...repoRef ? { repoRef } : {} - }; - }, - getDisplayId(params) { - if (!params) return null; - return readNonEmptyString6(params.sessionId) ?? readNonEmptyString6(params.session_id) ?? readNonEmptyString6(params.sessionID); - } -}; - -// packages/adapters/opencode-local/src/index.ts -var DEFAULT_OPENCODE_LOCAL_MODEL = "openai/gpt-5.2-codex"; -var models5 = [ - { id: DEFAULT_OPENCODE_LOCAL_MODEL, label: DEFAULT_OPENCODE_LOCAL_MODEL }, - { id: "openai/gpt-5.4", label: "openai/gpt-5.4" }, - { id: "openai/gpt-5.2", label: "openai/gpt-5.2" }, - { id: "openai/gpt-5.1-codex-max", label: "openai/gpt-5.1-codex-max" }, - { id: "openai/gpt-5.1-codex-mini", label: "openai/gpt-5.1-codex-mini" } -]; -var agentConfigurationDoc5 = `# opencode_local agent configuration - -Adapter: opencode_local - -Use when: -- You want Taskcore to run OpenCode locally as the agent runtime -- You want provider/model routing in OpenCode format (provider/model) -- You want OpenCode session resume across heartbeats via --session - -Don't use when: -- You need webhook-style external invocation (use openclaw_gateway or http) -- You only need one-shot shell commands (use process) -- OpenCode CLI is not installed on the machine - -Core fields: -- cwd (string, optional): default absolute working directory fallback for the agent process (created if missing when possible) -- instructionsFilePath (string, optional): absolute path to a markdown instructions file prepended to the run prompt -- model (string, required): OpenCode model id in provider/model format (for example anthropic/claude-sonnet-4-5) -- variant (string, optional): provider-specific reasoning/profile variant passed as --variant (for example minimal|low|medium|high|xhigh|max) -- dangerouslySkipPermissions (boolean, optional): inject a runtime OpenCode config that allows \`external_directory\` access without interactive prompts; defaults to true for unattended Taskcore runs -- promptTemplate (string, optional): run prompt template -- command (string, optional): defaults to "opencode" -- extraArgs (string[], optional): additional CLI args -- env (object, optional): KEY=VALUE environment variables - -Operational fields: -- timeoutSec (number, optional): run timeout in seconds -- graceSec (number, optional): SIGTERM grace period in seconds - -Notes: -- OpenCode supports multiple providers and models. Use \`opencode models\` to list available options in provider/model format. -- Taskcore requires an explicit \`model\` value for \`opencode_local\` agents. -- Runs are executed with: opencode run --format json ... -- Sessions are resumed with --session when stored session cwd matches current cwd. -- The adapter sets OPENCODE_DISABLE_PROJECT_CONFIG=true to prevent OpenCode from writing an opencode.json config file into the project working directory. Model selection is passed via the --model CLI flag instead. -- When \`dangerouslySkipPermissions\` is enabled, Taskcore injects a temporary runtime config with \`permission.external_directory=allow\` so headless runs do not stall on approval prompts. -`; - -// packages/adapters/openclaw-gateway/src/server/execute.ts -import crypto3, { randomUUID } from "node:crypto"; - -// node_modules/.pnpm/ws@8.20.0/node_modules/ws/wrapper.mjs -var import_stream5 = __toESM(require_stream(), 1); -var import_extension = __toESM(require_extension(), 1); -var import_permessage_deflate = __toESM(require_permessage_deflate(), 1); -var import_receiver = __toESM(require_receiver(), 1); -var import_sender = __toESM(require_sender(), 1); -var import_subprotocol = __toESM(require_subprotocol(), 1); -var import_websocket = __toESM(require_websocket(), 1); -var import_websocket_server = __toESM(require_websocket_server(), 1); - -// packages/adapters/openclaw-gateway/src/server/execute.ts -var PROTOCOL_VERSION = 3; -var DEFAULT_SCOPES = ["operator.admin"]; -var DEFAULT_CLIENT_ID = "gateway-client"; -var DEFAULT_CLIENT_MODE = "backend"; -var DEFAULT_CLIENT_VERSION = "taskcore"; -var DEFAULT_ROLE = "operator"; -var SENSITIVE_LOG_KEY_PATTERN = /(^|[_-])(auth|authorization|token|secret|password|api[_-]?key|private[_-]?key)([_-]|$)|^x-openclaw-(auth|token)$/i; -var ED25519_SPKI_PREFIX = Buffer.from("302a300506032b6570032100", "hex"); -function asRecord4(value) { - if (typeof value !== "object" || value === null || Array.isArray(value)) return null; - return value; -} -function nonEmpty3(value) { - return typeof value === "string" && value.trim().length > 0 ? value.trim() : null; -} -function parseOptionalPositiveInteger(value) { - if (typeof value === "number" && Number.isFinite(value)) { - return Math.max(1, Math.floor(value)); - } - if (typeof value === "string" && value.trim().length > 0) { - const parsed = Number.parseInt(value.trim(), 10); - if (Number.isFinite(parsed)) return Math.max(1, Math.floor(parsed)); - } - return null; -} -function parseBoolean(value, fallback = false) { - if (typeof value === "boolean") return value; - if (typeof value === "string") { - const normalized = value.trim().toLowerCase(); - if (normalized === "true" || normalized === "1") return true; - if (normalized === "false" || normalized === "0") return false; - } - return fallback; -} -function normalizeSessionKeyStrategy(value) { - const normalized = asString(value, "issue").trim().toLowerCase(); - if (normalized === "fixed" || normalized === "run") return normalized; - return "issue"; -} -function prefixSessionKeyForAgent(sessionKey, agentId) { - if (!agentId || sessionKey.startsWith("agent:")) return sessionKey; - return `agent:${agentId}:${sessionKey}`; -} -function resolveSessionKey(input) { - const fallback = input.configuredSessionKey ?? "taskcore"; - if (input.strategy === "run") { - return prefixSessionKeyForAgent(`taskcore:run:${input.runId}`, input.agentId); - } - if (input.strategy === "issue" && input.issueId) { - return prefixSessionKeyForAgent(`taskcore:issue:${input.issueId}`, input.agentId); - } - return prefixSessionKeyForAgent(fallback, input.agentId); -} -function isLoopbackHost2(hostname3) { - const value = hostname3.trim().toLowerCase(); - return value === "localhost" || value === "127.0.0.1" || value === "::1"; -} -function toStringRecord(value) { - const parsed = parseObject(value); - const out = {}; - for (const [key, entry] of Object.entries(parsed)) { - if (typeof entry === "string") out[key] = entry; - } - return out; -} -function toStringArray(value) { - if (Array.isArray(value)) { - return value.filter((entry) => typeof entry === "string").map((entry) => entry.trim()).filter(Boolean); - } - if (typeof value === "string") { - return value.split(",").map((entry) => entry.trim()).filter(Boolean); - } - return []; -} -function normalizeScopes(value) { - const parsed = toStringArray(value); - return parsed.length > 0 ? parsed : [...DEFAULT_SCOPES]; -} -function uniqueScopes(scopes) { - return Array.from(new Set(scopes.map((scope) => scope.trim()).filter(Boolean))); -} -function headerMapGetIgnoreCase(headers, key) { - const match = Object.entries(headers).find(([entryKey]) => entryKey.toLowerCase() === key.toLowerCase()); - return match ? match[1] : null; -} -function headerMapHasIgnoreCase(headers, key) { - return Object.keys(headers).some((entryKey) => entryKey.toLowerCase() === key.toLowerCase()); -} -function getGatewayErrorDetails(err) { - if (!err || typeof err !== "object") return null; - const candidate = err.gatewayDetails; - return asRecord4(candidate); -} -function extractPairingRequestId(err) { - const details = getGatewayErrorDetails(err); - const fromDetails = nonEmpty3(details?.requestId); - if (fromDetails) return fromDetails; - const message2 = err instanceof Error ? err.message : String(err); - const match = message2.match(/requestId\s*[:=]\s*([A-Za-z0-9_-]+)/i); - return match?.[1] ?? null; -} -function toAuthorizationHeaderValue(rawToken) { - const trimmed = rawToken.trim(); - if (!trimmed) return trimmed; - return /^bearer\s+/i.test(trimmed) ? trimmed : `Bearer ${trimmed}`; -} -function tokenFromAuthHeader(rawHeader) { - if (!rawHeader) return null; - const trimmed = rawHeader.trim(); - if (!trimmed) return null; - const match = trimmed.match(/^bearer\s+(.+)$/i); - return match ? nonEmpty3(match[1]) : trimmed; -} -function resolveAuthToken(config3, headers) { - const explicit = nonEmpty3(config3.authToken) ?? nonEmpty3(config3.token); - if (explicit) return explicit; - const tokenHeader = headerMapGetIgnoreCase(headers, "x-openclaw-token"); - if (nonEmpty3(tokenHeader)) return nonEmpty3(tokenHeader); - const authHeader = headerMapGetIgnoreCase(headers, "x-openclaw-auth") ?? headerMapGetIgnoreCase(headers, "authorization"); - return tokenFromAuthHeader(authHeader); -} -function isSensitiveLogKey(key) { - return SENSITIVE_LOG_KEY_PATTERN.test(key.trim()); -} -function sha256Prefix(value) { - return crypto3.createHash("sha256").update(value).digest("hex").slice(0, 12); -} -function redactSecretForLog(value) { - return `[redacted len=${value.length} sha256=${sha256Prefix(value)}]`; -} -function truncateForLog(value, maxChars = 320) { - if (value.length <= maxChars) return value; - return `${value.slice(0, maxChars)}... [truncated ${value.length - maxChars} chars]`; -} -function redactForLog(value, keyPath = [], depth = 0) { - const currentKey = keyPath[keyPath.length - 1] ?? ""; - if (typeof value === "string") { - if (isSensitiveLogKey(currentKey)) return redactSecretForLog(value); - return truncateForLog(value); - } - if (typeof value === "number" || typeof value === "boolean" || value == null) { - return value; - } - if (Array.isArray(value)) { - if (depth >= 6) return "[array-truncated]"; - const out = value.slice(0, 20).map((entry, index2) => redactForLog(entry, [...keyPath, `${index2}`], depth + 1)); - if (value.length > 20) out.push(`[+${value.length - 20} more items]`); - return out; - } - if (typeof value === "object") { - if (depth >= 6) return "[object-truncated]"; - const entries2 = Object.entries(value); - const out = {}; - for (const [key, entry] of entries2.slice(0, 80)) { - out[key] = redactForLog(entry, [...keyPath, key], depth + 1); - } - if (entries2.length > 80) { - out.__truncated__ = `+${entries2.length - 80} keys`; - } - return out; - } - return String(value); -} -function stringifyForLog(value, maxChars) { - const text3 = JSON.stringify(value); - if (text3.length <= maxChars) return text3; - return `${text3.slice(0, maxChars)}... [truncated ${text3.length - maxChars} chars]`; -} -function buildWakePayload(ctx) { - const { runId, agent, context } = ctx; - return { - runId, - agentId: agent.id, - companyId: agent.companyId, - taskId: nonEmpty3(context.taskId) ?? nonEmpty3(context.issueId), - issueId: nonEmpty3(context.issueId), - wakeReason: nonEmpty3(context.wakeReason), - wakeCommentId: nonEmpty3(context.wakeCommentId) ?? nonEmpty3(context.commentId), - approvalId: nonEmpty3(context.approvalId), - approvalStatus: nonEmpty3(context.approvalStatus), - issueIds: Array.isArray(context.issueIds) ? context.issueIds.filter( - (value) => typeof value === "string" && value.trim().length > 0 - ) : [] - }; -} -function resolveTaskcoreApiUrlOverride(value) { - const raw = nonEmpty3(value); - if (!raw) return null; - try { - const parsed = new URL(raw); - if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return null; - return parsed.toString(); - } catch { - return null; - } -} -function buildTaskcoreEnvForWake(ctx, wakePayload) { - const taskcoreApiUrlOverride = resolveTaskcoreApiUrlOverride(ctx.config.taskcoreApiUrl); - const taskcoreEnv = { - ...buildTaskcoreEnv(ctx.agent), - TASKCORE_RUN_ID: ctx.runId - }; - if (taskcoreApiUrlOverride) { - taskcoreEnv.TASKCORE_API_URL = taskcoreApiUrlOverride; - } - if (wakePayload.taskId) taskcoreEnv.TASKCORE_TASK_ID = wakePayload.taskId; - if (wakePayload.wakeReason) taskcoreEnv.TASKCORE_WAKE_REASON = wakePayload.wakeReason; - if (wakePayload.wakeCommentId) taskcoreEnv.TASKCORE_WAKE_COMMENT_ID = wakePayload.wakeCommentId; - if (wakePayload.approvalId) taskcoreEnv.TASKCORE_APPROVAL_ID = wakePayload.approvalId; - if (wakePayload.approvalStatus) taskcoreEnv.TASKCORE_APPROVAL_STATUS = wakePayload.approvalStatus; - if (wakePayload.issueIds.length > 0) { - taskcoreEnv.TASKCORE_LINKED_ISSUE_IDS = wakePayload.issueIds.join(","); - } - return taskcoreEnv; -} -function buildWakeText(payload2, taskcoreEnv, structuredWakePrompt) { - const claimedApiKeyPath = "~/.openclaw/workspace/taskcore-claimed-api-key.json"; - const orderedKeys = [ - "TASKCORE_RUN_ID", - "TASKCORE_AGENT_ID", - "TASKCORE_COMPANY_ID", - "TASKCORE_API_URL", - "TASKCORE_TASK_ID", - "TASKCORE_WAKE_REASON", - "TASKCORE_WAKE_COMMENT_ID", - "TASKCORE_APPROVAL_ID", - "TASKCORE_APPROVAL_STATUS", - "TASKCORE_LINKED_ISSUE_IDS" - ]; - const envLines = []; - for (const key of orderedKeys) { - const value = taskcoreEnv[key]; - if (!value) continue; - envLines.push(`${key}=${value}`); - } - const issueIdHint = payload2.taskId ?? payload2.issueId ?? ""; - const apiBaseHint = taskcoreEnv.TASKCORE_API_URL ?? ""; - const lines = [ - "Taskcore wake event for a cloud adapter.", - "", - "Run this procedure now. Do not guess undocumented endpoints and do not ask for additional heartbeat docs.", - "", - "Set these values in your run context:", - ...envLines, - `TASKCORE_API_KEY=`, - "", - `Load TASKCORE_API_KEY from ${claimedApiKeyPath} (the token you saved after claim-api-key).`, - "", - `api_base=${apiBaseHint}`, - `task_id=${payload2.taskId ?? ""}`, - `issue_id=${payload2.issueId ?? ""}`, - `wake_reason=${payload2.wakeReason ?? ""}`, - `wake_comment_id=${payload2.wakeCommentId ?? ""}`, - `approval_id=${payload2.approvalId ?? ""}`, - `approval_status=${payload2.approvalStatus ?? ""}`, - `linked_issue_ids=${payload2.issueIds.join(",")}`, - "", - "HTTP rules:", - "- Use Authorization: Bearer $TASKCORE_API_KEY on every API call.", - "- Use X-Taskcore-Run-Id: $TASKCORE_RUN_ID on every mutating API call.", - "- Use only /api endpoints listed below.", - "- Do NOT call guessed endpoints like /api/cloud-adapter/*, /api/cloud-adapters/*, /api/adapters/cloud/*, or /api/heartbeat.", - "", - "Workflow:", - "1) GET /api/agents/me", - `2) Determine issueId: TASKCORE_TASK_ID if present, otherwise issue_id (${issueIdHint}).`, - "3) If issueId exists:", - ' - POST /api/issues/{issueId}/checkout with {"agentId":"$TASKCORE_AGENT_ID","expectedStatuses":["todo","backlog","blocked","in_review"]}', - " - GET /api/issues/{issueId}", - " - GET /api/issues/{issueId}/comments", - " - Execute the issue instructions exactly.", - ' - If instructions require a comment, POST /api/issues/{issueId}/comments with {"body":"..."}.', - ' - PATCH /api/issues/{issueId} with {"status":"done","comment":"what changed and why"}.', - "4) If issueId does not exist:", - " - GET /api/companies/$TASKCORE_COMPANY_ID/issues?assigneeAgentId=$TASKCORE_AGENT_ID&status=todo,in_progress,in_review,blocked", - " - Pick in_progress first, then in_review when you were woken by a comment, then todo, then blocked, then execute step 3.", - "", - "Useful endpoints for issue work:", - "- POST /api/issues/{issueId}/comments", - "- PATCH /api/issues/{issueId}", - "- POST /api/companies/{companyId}/issues (when asked to create a new issue)", - ...structuredWakePrompt ? [ - "", - structuredWakePrompt - ] : [], - "", - "Complete the workflow in this run." - ]; - return lines.join("\n"); -} -function appendWakeText(baseText, wakeText) { - const trimmedBase = baseText.trim(); - return trimmedBase.length > 0 ? `${trimmedBase} - -${wakeText}` : wakeText; -} -function joinWakePayloadSections(structuredWakePrompt, structuredWakeJson) { - const sections = [ - structuredWakePrompt.trim(), - "Structured wake payload JSON:", - "```json", - structuredWakeJson, - "```" - ].filter((entry) => entry.trim().length > 0); - return sections.join("\n"); -} -function buildStandardTaskcorePayload(ctx, wakePayload, taskcoreEnv, payloadTemplate) { - const templateTaskcore = parseObject(payloadTemplate.taskcore); - const workspace = asRecord4(ctx.context.taskcoreWorkspace); - const workspaces = Array.isArray(ctx.context.taskcoreWorkspaces) ? ctx.context.taskcoreWorkspaces.filter((entry) => Boolean(asRecord4(entry))) : []; - const configuredWorkspaceRuntime = parseObject(ctx.config.workspaceRuntime); - const runtimeServiceIntents = Array.isArray(ctx.context.taskcoreRuntimeServiceIntents) ? ctx.context.taskcoreRuntimeServiceIntents.filter( - (entry) => Boolean(asRecord4(entry)) - ) : []; - const standardTaskcore = { - runId: ctx.runId, - companyId: ctx.agent.companyId, - agentId: ctx.agent.id, - agentName: ctx.agent.name, - taskId: wakePayload.taskId, - issueId: wakePayload.issueId, - issueIds: wakePayload.issueIds, - wakeReason: wakePayload.wakeReason, - wakeCommentId: wakePayload.wakeCommentId, - approvalId: wakePayload.approvalId, - approvalStatus: wakePayload.approvalStatus, - apiUrl: taskcoreEnv.TASKCORE_API_URL ?? null - }; - const structuredWake = parseObject(ctx.context.taskcoreWake); - if (Object.keys(structuredWake).length > 0) { - standardTaskcore.wake = structuredWake; - } - if (workspace) { - standardTaskcore.workspace = workspace; - } - if (workspaces.length > 0) { - standardTaskcore.workspaces = workspaces; - } - if (runtimeServiceIntents.length > 0 || Object.keys(configuredWorkspaceRuntime).length > 0) { - standardTaskcore.workspaceRuntime = { - ...configuredWorkspaceRuntime, - ...runtimeServiceIntents.length > 0 ? { services: runtimeServiceIntents } : {} - }; - } - return { - ...templateTaskcore, - ...standardTaskcore - }; -} -function normalizeUrl(input) { - try { - return new URL(input); - } catch { - return null; - } -} -function rawDataToString(data2) { - if (typeof data2 === "string") return data2; - if (Buffer.isBuffer(data2)) return data2.toString("utf8"); - if (data2 instanceof ArrayBuffer) return Buffer.from(data2).toString("utf8"); - if (Array.isArray(data2)) { - return Buffer.concat( - data2.map((entry) => Buffer.isBuffer(entry) ? entry : Buffer.from(String(entry), "utf8")) - ).toString("utf8"); - } - return String(data2 ?? ""); -} -function withTimeout(promise2, timeoutMs, message2) { - if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) return promise2; - return new Promise((resolve4, reject) => { - const timer2 = setTimeout(() => reject(new Error(message2)), timeoutMs); - promise2.then((value) => { - clearTimeout(timer2); - resolve4(value); - }).catch((err) => { - clearTimeout(timer2); - reject(err); - }); - }); -} -function derivePublicKeyRaw(publicKeyPem) { - const key = crypto3.createPublicKey(publicKeyPem); - const spki = key.export({ type: "spki", format: "der" }); - if (spki.length === ED25519_SPKI_PREFIX.length + 32 && spki.subarray(0, ED25519_SPKI_PREFIX.length).equals(ED25519_SPKI_PREFIX)) { - return spki.subarray(ED25519_SPKI_PREFIX.length); - } - return spki; -} -function base64UrlEncode2(buf) { - return buf.toString("base64").replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/g, ""); -} -function signDevicePayload(privateKeyPem, payload2) { - const key = crypto3.createPrivateKey(privateKeyPem); - const sig = crypto3.sign(null, Buffer.from(payload2, "utf8"), key); - return base64UrlEncode2(sig); -} -function buildDeviceAuthPayloadV3(params) { - const scopes = params.scopes.join(","); - const token = params.token ?? ""; - const platform = params.platform?.trim() ?? ""; - const deviceFamily = params.deviceFamily?.trim() ?? ""; - return [ - "v3", - params.deviceId, - params.clientId, - params.clientMode, - params.role, - scopes, - String(params.signedAtMs), - token, - params.nonce, - platform, - deviceFamily - ].join("|"); -} -function resolveDeviceIdentity(config3) { - const configuredPrivateKey = nonEmpty3(config3.devicePrivateKeyPem); - if (configuredPrivateKey) { - const privateKey = crypto3.createPrivateKey(configuredPrivateKey); - const publicKey = crypto3.createPublicKey(privateKey); - const publicKeyPem2 = publicKey.export({ type: "spki", format: "pem" }).toString(); - const raw2 = derivePublicKeyRaw(publicKeyPem2); - return { - deviceId: crypto3.createHash("sha256").update(raw2).digest("hex"), - publicKeyRawBase64Url: base64UrlEncode2(raw2), - privateKeyPem: configuredPrivateKey, - source: "configured" - }; - } - const generated = crypto3.generateKeyPairSync("ed25519"); - const publicKeyPem = generated.publicKey.export({ type: "spki", format: "pem" }).toString(); - const privateKeyPem = generated.privateKey.export({ type: "pkcs8", format: "pem" }).toString(); - const raw = derivePublicKeyRaw(publicKeyPem); - return { - deviceId: crypto3.createHash("sha256").update(raw).digest("hex"), - publicKeyRawBase64Url: base64UrlEncode2(raw), - privateKeyPem, - source: "ephemeral" - }; -} -function isResponseFrame(value) { - const record2 = asRecord4(value); - return Boolean(record2 && record2.type === "res" && typeof record2.id === "string" && typeof record2.ok === "boolean"); -} -function isEventFrame(value) { - const record2 = asRecord4(value); - return Boolean(record2 && record2.type === "event" && typeof record2.event === "string"); -} -var GatewayWsClient = class { - constructor(opts) { - this.opts = opts; - this.challengePromise = new Promise((resolve4, reject) => { - this.resolveChallenge = resolve4; - this.rejectChallenge = reject; - }); - this.challengePromise.catch(() => { - }); - } - opts; - ws = null; - pending = /* @__PURE__ */ new Map(); - challengePromise; - resolveChallenge; - rejectChallenge; - async connect(buildConnectParams, timeoutMs) { - this.ws = new import_websocket.default(this.opts.url, { - headers: this.opts.headers, - maxPayload: 25 * 1024 * 1024 - }); - const ws = this.ws; - ws.on("message", (data2) => { - this.handleMessage(rawDataToString(data2)); - }); - ws.on("close", (code, reason) => { - const reasonText = rawDataToString(reason); - const err = new Error(`gateway closed (${code}): ${reasonText}`); - this.failPending(err); - this.rejectChallenge(err); - }); - ws.on("error", (err) => { - const message2 = err instanceof Error ? err.message : String(err); - void this.opts.onLog("stderr", `[openclaw-gateway] websocket error: ${message2} -`); - }); - await withTimeout( - new Promise((resolve4, reject) => { - const onOpen = () => { - cleanup(); - resolve4(); - }; - const onError = (err) => { - cleanup(); - reject(err); - }; - const onClose = (code, reason) => { - cleanup(); - reject(new Error(`gateway closed before open (${code}): ${rawDataToString(reason)}`)); - }; - const cleanup = () => { - ws.off("open", onOpen); - ws.off("error", onError); - ws.off("close", onClose); - }; - ws.once("open", onOpen); - ws.once("error", onError); - ws.once("close", onClose); - }), - timeoutMs, - "gateway websocket open timeout" - ); - const nonce = await withTimeout(this.challengePromise, timeoutMs, "gateway connect challenge timeout"); - const signedConnectParams = buildConnectParams(nonce); - const hello = await this.request("connect", signedConnectParams, { - timeoutMs - }); - return hello; - } - async request(method, params, opts) { - if (!this.ws || this.ws.readyState !== import_websocket.default.OPEN) { - throw new Error("gateway not connected"); - } - const id = randomUUID(); - const frame = { - type: "req", - id, - method, - params - }; - const payload2 = JSON.stringify(frame); - const requestPromise = new Promise((resolve4, reject) => { - const timer2 = opts.timeoutMs > 0 ? setTimeout(() => { - this.pending.delete(id); - reject(new Error(`gateway request timeout (${method})`)); - }, opts.timeoutMs) : null; - this.pending.set(id, { - resolve: (value) => resolve4(value), - reject, - expectFinal: opts.expectFinal === true, - timer: timer2 - }); - }); - this.ws.send(payload2); - return requestPromise; - } - close() { - if (!this.ws) return; - this.ws.close(1e3, "taskcore-complete"); - this.ws = null; - } - failPending(err) { - for (const [, pending] of this.pending) { - if (pending.timer) clearTimeout(pending.timer); - pending.reject(err); - } - this.pending.clear(); - } - handleMessage(raw) { - let parsed; - try { - parsed = JSON.parse(raw); - } catch { - return; - } - if (isEventFrame(parsed)) { - if (parsed.event === "connect.challenge") { - const payload3 = asRecord4(parsed.payload); - const nonce = nonEmpty3(payload3?.nonce); - if (nonce) { - this.resolveChallenge(nonce); - return; - } - } - void Promise.resolve(this.opts.onEvent(parsed)).catch(() => { - }); - return; - } - if (!isResponseFrame(parsed)) return; - const pending = this.pending.get(parsed.id); - if (!pending) return; - const payload2 = asRecord4(parsed.payload); - const status = nonEmpty3(payload2?.status)?.toLowerCase(); - if (pending.expectFinal && status === "accepted") { - return; - } - if (pending.timer) clearTimeout(pending.timer); - this.pending.delete(parsed.id); - if (parsed.ok) { - pending.resolve(parsed.payload ?? null); - return; - } - const errorRecord = asRecord4(parsed.error); - const message2 = nonEmpty3(errorRecord?.message) ?? nonEmpty3(errorRecord?.code) ?? "gateway request failed"; - const err = new Error(message2); - const code = nonEmpty3(errorRecord?.code); - const details = asRecord4(errorRecord?.details); - if (code) err.gatewayCode = code; - if (details) err.gatewayDetails = details; - pending.reject(err); - } -}; -async function autoApproveDevicePairing(params) { - if (!params.authToken && !params.password) { - return { ok: false, reason: "shared auth token/password is missing" }; - } - const approvalScopes = uniqueScopes([...params.scopes, "operator.pairing"]); - const client2 = new GatewayWsClient({ - url: params.url, - headers: params.headers, - onEvent: () => { - }, - onLog: params.onLog - }); - try { - await params.onLog( - "stdout", - "[openclaw-gateway] pairing required; attempting automatic pairing approval via gateway methods\n" - ); - await client2.connect( - () => ({ - minProtocol: PROTOCOL_VERSION, - maxProtocol: PROTOCOL_VERSION, - client: { - id: params.clientId, - version: params.clientVersion, - platform: process.platform, - mode: params.clientMode - }, - role: params.role, - scopes: approvalScopes, - auth: { - ...params.authToken ? { token: params.authToken } : {}, - ...params.password ? { password: params.password } : {} - } - }), - params.connectTimeoutMs - ); - let requestId = params.requestId; - if (!requestId) { - const listPayload = await client2.request("device.pair.list", {}, { - timeoutMs: params.connectTimeoutMs - }); - const pending = Array.isArray(listPayload.pending) ? listPayload.pending : []; - const pendingRecords = pending.map((entry) => asRecord4(entry)).filter((entry) => Boolean(entry)); - const matching = (params.deviceId ? pendingRecords.find((entry) => nonEmpty3(entry.deviceId) === params.deviceId) : null) ?? pendingRecords[pendingRecords.length - 1]; - requestId = nonEmpty3(matching?.requestId); - } - if (!requestId) { - return { ok: false, reason: "no pending device pairing request found" }; - } - await client2.request( - "device.pair.approve", - { requestId }, - { - timeoutMs: params.connectTimeoutMs - } - ); - return { ok: true, requestId }; - } catch (err) { - return { ok: false, reason: err instanceof Error ? err.message : String(err) }; - } finally { - client2.close(); - } -} -function parseUsage(value) { - const record2 = asRecord4(value); - if (!record2) return void 0; - const inputTokens = asNumber(record2.inputTokens ?? record2.input, 0); - const outputTokens = asNumber(record2.outputTokens ?? record2.output, 0); - const cachedInputTokens = asNumber( - record2.cachedInputTokens ?? record2.cached_input_tokens ?? record2.cacheRead ?? record2.cache_read, - 0 - ); - if (inputTokens <= 0 && outputTokens <= 0 && cachedInputTokens <= 0) { - return void 0; - } - return { - inputTokens, - outputTokens, - ...cachedInputTokens > 0 ? { cachedInputTokens } : {} - }; -} -function extractRuntimeServicesFromMeta(meta3) { - if (!meta3) return []; - const reports = []; - const runtimeServices = Array.isArray(meta3.runtimeServices) ? meta3.runtimeServices.filter((entry) => Boolean(asRecord4(entry))) : []; - for (const entry of runtimeServices) { - const serviceName = nonEmpty3(entry.serviceName) ?? nonEmpty3(entry.name); - if (!serviceName) continue; - const rawStatus = nonEmpty3(entry.status)?.toLowerCase(); - const status = rawStatus === "starting" || rawStatus === "running" || rawStatus === "stopped" || rawStatus === "failed" ? rawStatus : "running"; - const rawLifecycle = nonEmpty3(entry.lifecycle)?.toLowerCase(); - const lifecycle = rawLifecycle === "shared" ? "shared" : "ephemeral"; - const rawScopeType = nonEmpty3(entry.scopeType)?.toLowerCase(); - const scopeType = rawScopeType === "project_workspace" || rawScopeType === "execution_workspace" || rawScopeType === "agent" ? rawScopeType : "run"; - const rawHealth = nonEmpty3(entry.healthStatus)?.toLowerCase(); - const healthStatus = rawHealth === "healthy" || rawHealth === "unhealthy" || rawHealth === "unknown" ? rawHealth : status === "running" ? "healthy" : "unknown"; - reports.push({ - id: nonEmpty3(entry.id), - projectId: nonEmpty3(entry.projectId), - projectWorkspaceId: nonEmpty3(entry.projectWorkspaceId), - issueId: nonEmpty3(entry.issueId), - scopeType, - scopeId: nonEmpty3(entry.scopeId), - serviceName, - status, - lifecycle, - reuseKey: nonEmpty3(entry.reuseKey), - command: nonEmpty3(entry.command), - cwd: nonEmpty3(entry.cwd), - port: parseOptionalPositiveInteger(entry.port), - url: nonEmpty3(entry.url), - providerRef: nonEmpty3(entry.providerRef) ?? nonEmpty3(entry.previewId), - ownerAgentId: nonEmpty3(entry.ownerAgentId), - stopPolicy: asRecord4(entry.stopPolicy), - healthStatus - }); - } - const previewUrl = nonEmpty3(meta3.previewUrl); - if (previewUrl) { - reports.push({ - serviceName: "preview", - status: "running", - lifecycle: "ephemeral", - scopeType: "run", - url: previewUrl, - providerRef: nonEmpty3(meta3.previewId) ?? previewUrl, - healthStatus: "healthy" - }); - } - const previewUrls = Array.isArray(meta3.previewUrls) ? meta3.previewUrls.filter((entry) => typeof entry === "string" && entry.trim().length > 0) : []; - previewUrls.forEach((url2, index2) => { - reports.push({ - serviceName: index2 === 0 ? "preview" : `preview-${index2 + 1}`, - status: "running", - lifecycle: "ephemeral", - scopeType: "run", - url: url2, - providerRef: `${url2}#${index2}`, - healthStatus: "healthy" - }); - }); - return reports; -} -function extractResultText(value) { - const record2 = asRecord4(value); - if (!record2) return null; - const payloads = Array.isArray(record2.payloads) ? record2.payloads : []; - const texts = payloads.map((entry) => { - const payload2 = asRecord4(entry); - return nonEmpty3(payload2?.text); - }).filter((entry) => Boolean(entry)); - if (texts.length > 0) return texts.join("\n\n"); - return nonEmpty3(record2.text) ?? nonEmpty3(record2.summary) ?? null; -} -async function execute6(ctx) { - const urlValue = asString(ctx.config.url, "").trim(); - if (!urlValue) { - return { - exitCode: 1, - signal: null, - timedOut: false, - errorMessage: "OpenClaw gateway adapter missing url", - errorCode: "openclaw_gateway_url_missing" - }; - } - const parsedUrl = normalizeUrl(urlValue); - if (!parsedUrl) { - return { - exitCode: 1, - signal: null, - timedOut: false, - errorMessage: `Invalid gateway URL: ${urlValue}`, - errorCode: "openclaw_gateway_url_invalid" - }; - } - if (parsedUrl.protocol !== "ws:" && parsedUrl.protocol !== "wss:") { - return { - exitCode: 1, - signal: null, - timedOut: false, - errorMessage: `Unsupported gateway URL protocol: ${parsedUrl.protocol}`, - errorCode: "openclaw_gateway_url_protocol" - }; - } - const timeoutSec = Math.max(0, Math.floor(asNumber(ctx.config.timeoutSec, 120))); - const timeoutMs = timeoutSec > 0 ? timeoutSec * 1e3 : 0; - const connectTimeoutMs = timeoutMs > 0 ? Math.min(timeoutMs, 15e3) : 1e4; - const waitTimeoutMs = parseOptionalPositiveInteger(ctx.config.waitTimeoutMs) ?? (timeoutMs > 0 ? timeoutMs : 3e4); - const payloadTemplate = parseObject(ctx.config.payloadTemplate); - const transportHint = nonEmpty3(ctx.config.streamTransport) ?? nonEmpty3(ctx.config.transport); - const headers = toStringRecord(ctx.config.headers); - const authToken = resolveAuthToken(parseObject(ctx.config), headers); - const password = nonEmpty3(ctx.config.password); - const deviceToken = nonEmpty3(ctx.config.deviceToken); - if (authToken && !headerMapHasIgnoreCase(headers, "authorization")) { - headers.authorization = toAuthorizationHeaderValue(authToken); - } - const clientId = nonEmpty3(ctx.config.clientId) ?? DEFAULT_CLIENT_ID; - const clientMode = nonEmpty3(ctx.config.clientMode) ?? DEFAULT_CLIENT_MODE; - const clientVersion = nonEmpty3(ctx.config.clientVersion) ?? DEFAULT_CLIENT_VERSION; - const role = nonEmpty3(ctx.config.role) ?? DEFAULT_ROLE; - const scopes = normalizeScopes(ctx.config.scopes); - const deviceFamily = nonEmpty3(ctx.config.deviceFamily); - const disableDeviceAuth = parseBoolean(ctx.config.disableDeviceAuth, false); - const wakePayload = buildWakePayload(ctx); - const taskcoreEnv = buildTaskcoreEnvForWake(ctx, wakePayload); - const structuredWakePrompt = renderTaskcoreWakePrompt(ctx.context.taskcoreWake); - const structuredWakeJson = stringifyTaskcoreWakePayload(ctx.context.taskcoreWake); - const wakeText = buildWakeText( - wakePayload, - taskcoreEnv, - structuredWakeJson ? joinWakePayloadSections(structuredWakePrompt, structuredWakeJson) : structuredWakePrompt - ); - const sessionKeyStrategy = normalizeSessionKeyStrategy(ctx.config.sessionKeyStrategy); - const configuredSessionKey = nonEmpty3(ctx.config.sessionKey); - const sessionKey = resolveSessionKey({ - strategy: sessionKeyStrategy, - configuredSessionKey, - agentId: nonEmpty3(ctx.config.agentId), - runId: ctx.runId, - issueId: wakePayload.issueId - }); - const templateMessage = nonEmpty3(payloadTemplate.message) ?? nonEmpty3(payloadTemplate.text); - const message2 = templateMessage ? appendWakeText(templateMessage, wakeText) : wakeText; - const taskcorePayload = buildStandardTaskcorePayload(ctx, wakePayload, taskcoreEnv, payloadTemplate); - const agentParams = { - ...payloadTemplate, - message: message2, - sessionKey, - idempotencyKey: ctx.runId - }; - delete agentParams.text; - agentParams.taskcore = taskcorePayload; - const configuredAgentId = nonEmpty3(ctx.config.agentId); - if (configuredAgentId && !nonEmpty3(agentParams.agentId)) { - agentParams.agentId = configuredAgentId; - } - if (typeof agentParams.timeout !== "number") { - agentParams.timeout = waitTimeoutMs; - } - if (ctx.onMeta) { - await ctx.onMeta({ - adapterType: "openclaw_gateway", - command: "gateway", - commandArgs: ["ws", parsedUrl.toString(), "agent"], - context: ctx.context - }); - } - const outboundHeaderKeys = Object.keys(headers).sort(); - await ctx.onLog( - "stdout", - `[openclaw-gateway] outbound headers (redacted): ${stringifyForLog(redactForLog(headers), 4e3)} -` - ); - await ctx.onLog( - "stdout", - `[openclaw-gateway] outbound payload (redacted): ${stringifyForLog(redactForLog(agentParams), 12e3)} -` - ); - await ctx.onLog("stdout", `[openclaw-gateway] outbound header keys: ${outboundHeaderKeys.join(", ")} -`); - if (transportHint) { - await ctx.onLog( - "stdout", - `[openclaw-gateway] ignoring streamTransport=${transportHint}; gateway adapter always uses websocket protocol -` - ); - } - if (parsedUrl.protocol === "ws:" && !isLoopbackHost2(parsedUrl.hostname)) { - await ctx.onLog( - "stdout", - "[openclaw-gateway] warning: using plaintext ws:// to a non-loopback host; prefer wss:// for remote endpoints\n" - ); - } - const autoPairOnFirstConnect = parseBoolean(ctx.config.autoPairOnFirstConnect, true); - let autoPairAttempted = false; - let latestResultPayload = null; - while (true) { - const trackedRunIds = /* @__PURE__ */ new Set([ctx.runId]); - const assistantChunks = []; - let lifecycleError = null; - let deviceIdentity = null; - const onEvent = async (frame) => { - if (frame.event !== "agent") { - if (frame.event === "shutdown") { - await ctx.onLog( - "stdout", - `[openclaw-gateway] gateway shutdown notice: ${stringifyForLog(frame.payload ?? {}, 2e3)} -` - ); - } - return; - } - const payload2 = asRecord4(frame.payload); - if (!payload2) return; - const runId = nonEmpty3(payload2.runId); - if (!runId || !trackedRunIds.has(runId)) return; - const stream = nonEmpty3(payload2.stream) ?? "unknown"; - const data2 = asRecord4(payload2.data) ?? {}; - await ctx.onLog( - "stdout", - `[openclaw-gateway:event] run=${runId} stream=${stream} data=${stringifyForLog(data2, 8e3)} -` - ); - if (stream === "assistant") { - const delta = nonEmpty3(data2.delta); - const text3 = nonEmpty3(data2.text); - if (delta) { - assistantChunks.push(delta); - } else if (text3) { - assistantChunks.push(text3); - } - return; - } - if (stream === "error") { - lifecycleError = nonEmpty3(data2.error) ?? nonEmpty3(data2.message) ?? lifecycleError; - return; - } - if (stream === "lifecycle") { - const phase = nonEmpty3(data2.phase)?.toLowerCase(); - if (phase === "error" || phase === "failed" || phase === "cancelled") { - lifecycleError = nonEmpty3(data2.error) ?? nonEmpty3(data2.message) ?? lifecycleError; - } - } - }; - const client2 = new GatewayWsClient({ - url: parsedUrl.toString(), - headers, - onEvent, - onLog: ctx.onLog - }); - try { - deviceIdentity = disableDeviceAuth ? null : resolveDeviceIdentity(parseObject(ctx.config)); - if (deviceIdentity) { - await ctx.onLog( - "stdout", - `[openclaw-gateway] device auth enabled keySource=${deviceIdentity.source} deviceId=${deviceIdentity.deviceId} -` - ); - } else { - await ctx.onLog("stdout", "[openclaw-gateway] device auth disabled\n"); - } - await ctx.onLog("stdout", `[openclaw-gateway] connecting to ${parsedUrl.toString()} -`); - const hello = await client2.connect((nonce) => { - const signedAtMs = Date.now(); - const connectParams = { - minProtocol: PROTOCOL_VERSION, - maxProtocol: PROTOCOL_VERSION, - client: { - id: clientId, - version: clientVersion, - platform: process.platform, - ...deviceFamily ? { deviceFamily } : {}, - mode: clientMode - }, - role, - scopes, - auth: authToken || password || deviceToken ? { - ...authToken ? { token: authToken } : {}, - ...deviceToken ? { deviceToken } : {}, - ...password ? { password } : {} - } : void 0 - }; - if (deviceIdentity) { - const payload2 = buildDeviceAuthPayloadV3({ - deviceId: deviceIdentity.deviceId, - clientId, - clientMode, - role, - scopes, - signedAtMs, - token: authToken, - nonce, - platform: process.platform, - deviceFamily - }); - connectParams.device = { - id: deviceIdentity.deviceId, - publicKey: deviceIdentity.publicKeyRawBase64Url, - signature: signDevicePayload(deviceIdentity.privateKeyPem, payload2), - signedAt: signedAtMs, - nonce - }; - } - return connectParams; - }, connectTimeoutMs); - await ctx.onLog( - "stdout", - `[openclaw-gateway] connected protocol=${asNumber(asRecord4(hello)?.protocol, PROTOCOL_VERSION)} -` - ); - const acceptedPayload = await client2.request("agent", agentParams, { - timeoutMs: connectTimeoutMs - }); - latestResultPayload = acceptedPayload; - const acceptedStatus = nonEmpty3(acceptedPayload?.status)?.toLowerCase() ?? ""; - const acceptedRunId = nonEmpty3(acceptedPayload?.runId) ?? ctx.runId; - trackedRunIds.add(acceptedRunId); - await ctx.onLog( - "stdout", - `[openclaw-gateway] agent accepted runId=${acceptedRunId} status=${acceptedStatus || "unknown"} -` - ); - if (acceptedStatus === "error") { - const errorMessage = nonEmpty3(acceptedPayload?.summary) ?? lifecycleError ?? "OpenClaw gateway agent request failed"; - return { - exitCode: 1, - signal: null, - timedOut: false, - errorMessage, - errorCode: "openclaw_gateway_agent_error", - resultJson: acceptedPayload - }; - } - if (acceptedStatus !== "ok") { - const waitPayload = await client2.request( - "agent.wait", - { runId: acceptedRunId, timeoutMs: waitTimeoutMs }, - { timeoutMs: waitTimeoutMs + connectTimeoutMs } - ); - latestResultPayload = waitPayload; - const waitStatus = nonEmpty3(waitPayload?.status)?.toLowerCase() ?? ""; - if (waitStatus === "timeout") { - return { - exitCode: 1, - signal: null, - timedOut: true, - errorMessage: `OpenClaw gateway run timed out after ${waitTimeoutMs}ms`, - errorCode: "openclaw_gateway_wait_timeout", - resultJson: waitPayload - }; - } - if (waitStatus === "error") { - return { - exitCode: 1, - signal: null, - timedOut: false, - errorMessage: nonEmpty3(waitPayload?.error) ?? lifecycleError ?? "OpenClaw gateway run failed", - errorCode: "openclaw_gateway_wait_error", - resultJson: waitPayload - }; - } - if (waitStatus && waitStatus !== "ok") { - return { - exitCode: 1, - signal: null, - timedOut: false, - errorMessage: `Unexpected OpenClaw gateway agent.wait status: ${waitStatus}`, - errorCode: "openclaw_gateway_wait_status_unexpected", - resultJson: waitPayload - }; - } - } - const summaryFromEvents = assistantChunks.join("").trim(); - const summaryFromPayload = extractResultText(asRecord4(acceptedPayload?.result)) ?? extractResultText(acceptedPayload) ?? extractResultText(asRecord4(latestResultPayload)) ?? null; - const summary = summaryFromEvents || summaryFromPayload || null; - const acceptedResult = asRecord4(acceptedPayload?.result); - const latestPayload = asRecord4(latestResultPayload); - const latestResult = asRecord4(latestPayload?.result); - const acceptedMeta = asRecord4(acceptedResult?.meta) ?? asRecord4(acceptedPayload?.meta); - const latestMeta = asRecord4(latestResult?.meta) ?? asRecord4(latestPayload?.meta); - const mergedMeta = { - ...acceptedMeta ?? {}, - ...latestMeta ?? {} - }; - const agentMeta = asRecord4(mergedMeta.agentMeta) ?? asRecord4(acceptedMeta?.agentMeta) ?? asRecord4(latestMeta?.agentMeta); - const usage = parseUsage(agentMeta?.usage ?? mergedMeta.usage); - const runtimeServices = extractRuntimeServicesFromMeta(agentMeta ?? mergedMeta); - const provider = nonEmpty3(agentMeta?.provider) ?? nonEmpty3(mergedMeta.provider) ?? "openclaw"; - const model = nonEmpty3(agentMeta?.model) ?? nonEmpty3(mergedMeta.model) ?? null; - const costUsd = asNumber(agentMeta?.costUsd ?? mergedMeta.costUsd, 0); - await ctx.onLog( - "stdout", - `[openclaw-gateway] run completed runId=${Array.from(trackedRunIds).join(",")} status=ok -` - ); - return { - exitCode: 0, - signal: null, - timedOut: false, - provider, - ...model ? { model } : {}, - ...usage ? { usage } : {}, - ...costUsd > 0 ? { costUsd } : {}, - resultJson: asRecord4(latestResultPayload), - ...runtimeServices.length > 0 ? { runtimeServices } : {}, - ...summary ? { summary } : {} - }; - } catch (err) { - const message3 = err instanceof Error ? err.message : String(err); - const lower = message3.toLowerCase(); - const timedOut = lower.includes("timeout"); - const pairingRequired = lower.includes("pairing required"); - if (pairingRequired && !disableDeviceAuth && autoPairOnFirstConnect && !autoPairAttempted && (authToken || password)) { - autoPairAttempted = true; - const pairResult = await autoApproveDevicePairing({ - url: parsedUrl.toString(), - headers, - connectTimeoutMs, - clientId, - clientMode, - clientVersion, - role, - scopes, - authToken, - password, - requestId: extractPairingRequestId(err), - deviceId: deviceIdentity?.deviceId ?? null, - onLog: ctx.onLog - }); - if (pairResult.ok) { - await ctx.onLog( - "stdout", - `[openclaw-gateway] auto-approved pairing request ${pairResult.requestId}; retrying -` - ); - continue; - } - await ctx.onLog( - "stderr", - `[openclaw-gateway] auto-pairing failed: ${pairResult.reason} -` - ); - } - const detailedMessage = pairingRequired ? `${message3}. Approve the pending device in OpenClaw (for example: openclaw devices approve --latest --url --token ) and retry. Ensure this agent has a persisted adapterConfig.devicePrivateKeyPem so approvals are reused.` : message3; - await ctx.onLog("stderr", `[openclaw-gateway] request failed: ${detailedMessage} -`); - return { - exitCode: 1, - signal: null, - timedOut, - errorMessage: detailedMessage, - errorCode: timedOut ? "openclaw_gateway_timeout" : pairingRequired ? "openclaw_gateway_pairing_required" : "openclaw_gateway_request_failed", - resultJson: asRecord4(latestResultPayload) - }; - } finally { - client2.close(); - } - } -} - -// packages/adapters/openclaw-gateway/src/server/test.ts -import { randomUUID as randomUUID2 } from "node:crypto"; -function summarizeStatus6(checks) { - if (checks.some((check3) => check3.level === "error")) return "fail"; - if (checks.some((check3) => check3.level === "warn")) return "warn"; - return "pass"; -} -function nonEmpty4(value) { - return typeof value === "string" && value.trim().length > 0 ? value.trim() : null; -} -function isLoopbackHost3(hostname3) { - const value = hostname3.trim().toLowerCase(); - return value === "localhost" || value === "127.0.0.1" || value === "::1"; -} -function toStringRecord2(value) { - const parsed = parseObject(value); - const out = {}; - for (const [key, entry] of Object.entries(parsed)) { - if (typeof entry === "string") out[key] = entry; - } - return out; -} -function toStringArray2(value) { - if (Array.isArray(value)) { - return value.filter((entry) => typeof entry === "string").map((entry) => entry.trim()).filter(Boolean); - } - if (typeof value === "string") { - return value.split(",").map((entry) => entry.trim()).filter(Boolean); - } - return []; -} -function headerMapGetIgnoreCase2(headers, key) { - const match = Object.entries(headers).find(([entryKey]) => entryKey.toLowerCase() === key.toLowerCase()); - return match ? match[1] : null; -} -function tokenFromAuthHeader2(rawHeader) { - if (!rawHeader) return null; - const trimmed = rawHeader.trim(); - if (!trimmed) return null; - const match = trimmed.match(/^bearer\s+(.+)$/i); - return match ? nonEmpty4(match[1]) : trimmed; -} -function resolveAuthToken2(config3, headers) { - const explicit = nonEmpty4(config3.authToken) ?? nonEmpty4(config3.token); - if (explicit) return explicit; - const tokenHeader = headerMapGetIgnoreCase2(headers, "x-openclaw-token"); - if (nonEmpty4(tokenHeader)) return nonEmpty4(tokenHeader); - const authHeader = headerMapGetIgnoreCase2(headers, "x-openclaw-auth") ?? headerMapGetIgnoreCase2(headers, "authorization"); - return tokenFromAuthHeader2(authHeader); -} -function asRecord5(value) { - if (typeof value !== "object" || value === null || Array.isArray(value)) return null; - return value; -} -function rawDataToString2(data2) { - if (typeof data2 === "string") return data2; - if (Buffer.isBuffer(data2)) return data2.toString("utf8"); - if (data2 instanceof ArrayBuffer) return Buffer.from(data2).toString("utf8"); - if (Array.isArray(data2)) { - return Buffer.concat( - data2.map((entry) => Buffer.isBuffer(entry) ? entry : Buffer.from(String(entry), "utf8")) - ).toString("utf8"); - } - return String(data2 ?? ""); -} -async function probeGateway(input) { - return await new Promise((resolve4) => { - const ws = new import_websocket.default(input.url, { headers: input.headers, maxPayload: 2 * 1024 * 1024 }); - const timeout = setTimeout(() => { - try { - ws.close(); - } catch { - } - resolve4("failed"); - }, input.timeoutMs); - let completed = false; - const finish = (status) => { - if (completed) return; - completed = true; - clearTimeout(timeout); - try { - ws.close(); - } catch { - } - resolve4(status); - }; - ws.on("message", (raw) => { - let parsed; - try { - parsed = JSON.parse(rawDataToString2(raw)); - } catch { - return; - } - const event = asRecord5(parsed); - if (event?.type === "event" && event.event === "connect.challenge") { - const nonce = nonEmpty4(asRecord5(event.payload)?.nonce); - if (!nonce) { - finish("failed"); - return; - } - const connectId = randomUUID2(); - ws.send( - JSON.stringify({ - type: "req", - id: connectId, - method: "connect", - params: { - minProtocol: 3, - maxProtocol: 3, - client: { - id: "gateway-client", - version: "taskcore-probe", - platform: process.platform, - mode: "probe" - }, - role: input.role, - scopes: input.scopes, - ...input.authToken ? { - auth: { - token: input.authToken - } - } : {} - } - }) - ); - return; - } - if (event?.type === "res") { - if (event.ok === true) { - finish("ok"); - } else { - finish("challenge_only"); - } - } - }); - ws.on("error", () => { - finish("failed"); - }); - ws.on("close", () => { - if (!completed) finish("failed"); - }); - }); -} -async function testEnvironment6(ctx) { - const checks = []; - const config3 = parseObject(ctx.config); - const urlValue = asString(config3.url, "").trim(); - if (!urlValue) { - checks.push({ - code: "openclaw_gateway_url_missing", - level: "error", - message: "OpenClaw gateway adapter requires a WebSocket URL.", - hint: "Set adapterConfig.url to ws://host:port (or wss://)." - }); - return { - adapterType: ctx.adapterType, - status: summarizeStatus6(checks), - checks, - testedAt: (/* @__PURE__ */ new Date()).toISOString() - }; - } - let url2 = null; - try { - url2 = new URL(urlValue); - } catch { - checks.push({ - code: "openclaw_gateway_url_invalid", - level: "error", - message: `Invalid URL: ${urlValue}` - }); - } - if (url2 && url2.protocol !== "ws:" && url2.protocol !== "wss:") { - checks.push({ - code: "openclaw_gateway_url_protocol_invalid", - level: "error", - message: `Unsupported URL protocol: ${url2.protocol}`, - hint: "Use ws:// or wss://." - }); - } - if (url2) { - checks.push({ - code: "openclaw_gateway_url_valid", - level: "info", - message: `Configured gateway URL: ${url2.toString()}` - }); - if (url2.protocol === "ws:" && !isLoopbackHost3(url2.hostname)) { - checks.push({ - code: "openclaw_gateway_plaintext_remote_ws", - level: "warn", - message: "Gateway URL uses plaintext ws:// on a non-loopback host.", - hint: "Prefer wss:// for remote gateways." - }); - } - } - const headers = toStringRecord2(config3.headers); - const authToken = resolveAuthToken2(config3, headers); - const password = nonEmpty4(config3.password); - const role = nonEmpty4(config3.role) ?? "operator"; - const scopes = toStringArray2(config3.scopes); - if (authToken || password) { - checks.push({ - code: "openclaw_gateway_auth_present", - level: "info", - message: "Gateway credentials are configured." - }); - } else { - checks.push({ - code: "openclaw_gateway_auth_missing", - level: "warn", - message: "No gateway credentials detected in adapter config.", - hint: "Set authToken/password or headers.x-openclaw-token for authenticated gateways." - }); - } - if (url2 && (url2.protocol === "ws:" || url2.protocol === "wss:")) { - try { - const probeResult = await probeGateway({ - url: url2.toString(), - headers, - authToken, - role, - scopes: scopes.length > 0 ? scopes : ["operator.admin"], - timeoutMs: 3e3 - }); - if (probeResult === "ok") { - checks.push({ - code: "openclaw_gateway_probe_ok", - level: "info", - message: "Gateway connect probe succeeded." - }); - } else if (probeResult === "challenge_only") { - checks.push({ - code: "openclaw_gateway_probe_challenge_only", - level: "warn", - message: "Gateway challenge was received, but connect probe was rejected.", - hint: "Check gateway credentials, scopes, role, and device-auth requirements." - }); - } else { - checks.push({ - code: "openclaw_gateway_probe_failed", - level: "warn", - message: "Gateway probe failed.", - hint: "Verify network reachability and gateway URL from the Taskcore server host." - }); - } - } catch (err) { - checks.push({ - code: "openclaw_gateway_probe_error", - level: "warn", - message: err instanceof Error ? err.message : "Gateway probe failed" - }); - } - } - return { - adapterType: ctx.adapterType, - status: summarizeStatus6(checks), - checks, - testedAt: (/* @__PURE__ */ new Date()).toISOString() - }; -} - -// packages/adapters/openclaw-gateway/src/index.ts -var models6 = []; -var agentConfigurationDoc6 = `# openclaw_gateway agent configuration - -Adapter: openclaw_gateway - -Use when: -- You want Taskcore to invoke OpenClaw over the Gateway WebSocket protocol. -- You want native gateway auth/connect semantics instead of HTTP /v1/responses or /hooks/*. - -Don't use when: -- You only expose OpenClaw HTTP endpoints. -- Your deployment does not permit outbound WebSocket access from the Taskcore server. - -Core fields: -- url (string, required): OpenClaw gateway WebSocket URL (ws:// or wss://) -- headers (object, optional): handshake headers; supports x-openclaw-token / x-openclaw-auth -- authToken (string, optional): shared gateway token override -- password (string, optional): gateway shared password, if configured - -Gateway connect identity fields: -- clientId (string, optional): gateway client id (default gateway-client) -- clientMode (string, optional): gateway client mode (default backend) -- clientVersion (string, optional): client version string -- role (string, optional): gateway role (default operator) -- scopes (string[] | comma string, optional): gateway scopes (default ["operator.admin"]) -- disableDeviceAuth (boolean, optional): disable signed device payload in connect params (default false) - -Request behavior fields: -- payloadTemplate (object, optional): additional fields merged into gateway agent params -- workspaceRuntime (object, optional): reserved workspace runtime metadata; workspace runtime services are manually controlled from the workspace UI and are not auto-started by heartbeats -- timeoutSec (number, optional): adapter timeout in seconds (default 120) -- waitTimeoutMs (number, optional): agent.wait timeout override (default timeoutSec * 1000) -- autoPairOnFirstConnect (boolean, optional): on first "pairing required", attempt device.pair.list/device.pair.approve via shared auth, then retry once (default true) -- taskcoreApiUrl (string, optional): absolute Taskcore base URL advertised in wake text -- claimedApiKeyPath (string, optional): path to the claimed API key JSON file read by the agent at wake time (default ~/.openclaw/workspace/taskcore-claimed-api-key.json) - -Session routing fields: -- sessionKeyStrategy (string, optional): issue (default), fixed, or run -- sessionKey (string, optional): fixed session key when strategy=fixed (default taskcore) - -Standard outbound payload additions: -- taskcore (object): standardized Taskcore context added to every gateway agent request -- taskcore.workspace (object, optional): resolved execution workspace for this run -- taskcore.workspaces (array, optional): additional workspace hints Taskcore exposed to the run -- taskcore.workspaceRuntime (object, optional): reserved workspace runtime metadata when explicitly supplied outside normal heartbeat execution - -Standard result metadata supported: -- meta.runtimeServices (array, optional): normalized adapter-managed runtime service reports -- meta.previewUrl (string, optional): shorthand single preview URL -- meta.previewUrls (string[], optional): shorthand multiple preview URLs -`; - -// server/src/adapters/codex-models.ts -var OPENAI_MODELS_ENDPOINT = "https://api.openai.com/v1/models"; -var OPENAI_MODELS_TIMEOUT_MS = 5e3; -var OPENAI_MODELS_CACHE_TTL_MS = 6e4; -var cached = null; -function fingerprint(apiKey) { - return `${apiKey.length}:${apiKey.slice(-6)}`; -} -function dedupeModels2(models8) { - const seen = /* @__PURE__ */ new Set(); - const deduped = []; - for (const model of models8) { - const id = model.id.trim(); - if (!id || seen.has(id)) continue; - seen.add(id); - deduped.push({ id, label: model.label.trim() || id }); - } - return deduped; -} -function mergedWithFallback(models8) { - return dedupeModels2([ - ...models8, - ...models2 - ]).sort((a5, b6) => a5.id.localeCompare(b6.id, "en", { numeric: true, sensitivity: "base" })); -} -function resolveOpenAiApiKey() { - const envKey = process.env.OPENAI_API_KEY?.trim(); - if (envKey) return envKey; - const config3 = readConfigFile(); - if (config3?.llm?.provider !== "openai") return null; - const configKey = config3.llm.apiKey?.trim(); - return configKey && configKey.length > 0 ? configKey : null; -} -async function fetchOpenAiModels(apiKey) { - const controller = new AbortController(); - const timeout = setTimeout(() => controller.abort(), OPENAI_MODELS_TIMEOUT_MS); - try { - const response = await fetch(OPENAI_MODELS_ENDPOINT, { - headers: { - Authorization: `Bearer ${apiKey}` - }, - signal: controller.signal - }); - if (!response.ok) return []; - const payload2 = await response.json(); - const data2 = Array.isArray(payload2.data) ? payload2.data : []; - const models8 = []; - for (const item of data2) { - if (typeof item !== "object" || item === null) continue; - const id = item.id; - if (typeof id !== "string" || id.trim().length === 0) continue; - models8.push({ id, label: id }); - } - return dedupeModels2(models8); - } catch { - return []; - } finally { - clearTimeout(timeout); - } -} -async function listCodexModels() { - const apiKey = resolveOpenAiApiKey(); - const fallback = dedupeModels2(models2); - if (!apiKey) return fallback; - const now2 = Date.now(); - const keyFingerprint = fingerprint(apiKey); - if (cached && cached.keyFingerprint === keyFingerprint && cached.expiresAt > now2) { - return cached.models; - } - const fetched = await fetchOpenAiModels(apiKey); - if (fetched.length > 0) { - const merged = mergedWithFallback(fetched); - cached = { - keyFingerprint, - expiresAt: now2 + OPENAI_MODELS_CACHE_TTL_MS, - models: merged - }; - return merged; - } - if (cached && cached.keyFingerprint === keyFingerprint && cached.models.length > 0) { - return cached.models; - } - return fallback; -} - -// server/src/adapters/cursor-models.ts -import { spawnSync } from "node:child_process"; -var CURSOR_MODELS_TIMEOUT_MS = 5e3; -var CURSOR_MODELS_CACHE_TTL_MS = 6e4; -var MAX_BUFFER_BYTES = 512 * 1024; -var cached2 = null; -function dedupeModels3(models8) { - const seen = /* @__PURE__ */ new Set(); - const deduped = []; - for (const model of models8) { - const id = model.id.trim(); - if (!id || seen.has(id)) continue; - seen.add(id); - deduped.push({ id, label: model.label.trim() || id }); - } - return deduped; -} -function sanitizeModelId(raw) { - return raw.trim().replace(/^["'`]+|["'`]+$/g, "").replace(/\(.*\)\s*$/g, "").trim(); -} -function isLikelyModelId(raw) { - const value = sanitizeModelId(raw); - if (!value) return false; - return /^[A-Za-z0-9][A-Za-z0-9._/-]*$/.test(value); -} -function pushModelId(target, raw) { - const id = sanitizeModelId(raw); - if (!isLikelyModelId(id)) return; - target.push({ id, label: id }); -} -function collectFromJsonValue(value, target) { - if (typeof value === "string") { - pushModelId(target, value); - return; - } - if (!Array.isArray(value)) return; - for (const item of value) { - if (typeof item === "string") { - pushModelId(target, item); - continue; - } - if (typeof item !== "object" || item === null) continue; - const id = item.id; - if (typeof id === "string") { - pushModelId(target, id); - } - } -} -function parseCursorModelsOutput(stdout, stderr) { - const models8 = []; - const combined = `${stdout} -${stderr}`; - const trimmedStdout = stdout.trim(); - if (trimmedStdout.startsWith("{") || trimmedStdout.startsWith("[")) { - try { - const parsed = JSON.parse(trimmedStdout); - if (Array.isArray(parsed)) { - collectFromJsonValue(parsed, models8); - } else if (typeof parsed === "object" && parsed !== null) { - const rec = parsed; - collectFromJsonValue(rec.models, models8); - collectFromJsonValue(rec.data, models8); - } - } catch { - } - } - for (const match of combined.matchAll(/available models?:\s*([^\n]+)/gi)) { - const list2 = match[1] ?? ""; - for (const token of list2.split(",")) { - pushModelId(models8, token); - } - } - for (const lineRaw of combined.split(/\r?\n/)) { - const line3 = lineRaw.trim(); - if (!line3) continue; - const bullet = line3.replace(/^[-*]\s+/, "").trim(); - if (!bullet || bullet.includes(" ")) continue; - pushModelId(models8, bullet); - } - return dedupeModels3(models8); -} -function mergedWithFallback2(models8) { - return dedupeModels3([...models8, ...models3]); -} -function defaultCursorModelsRunner() { - const result = spawnSync("agent", ["models"], { - encoding: "utf8", - timeout: CURSOR_MODELS_TIMEOUT_MS, - maxBuffer: MAX_BUFFER_BYTES - }); - return { - status: result.status, - stdout: typeof result.stdout === "string" ? result.stdout : "", - stderr: typeof result.stderr === "string" ? result.stderr : "", - hasError: Boolean(result.error) - }; -} -var cursorModelsRunner = defaultCursorModelsRunner; -function fetchCursorModelsFromCli() { - const result = cursorModelsRunner(); - const { stdout, stderr } = result; - if (result.hasError && stdout.trim().length === 0 && stderr.trim().length === 0) { - return []; - } - if ((result.status ?? 1) !== 0 && !/available models?:/i.test(`${stdout} -${stderr}`)) { - return []; - } - return parseCursorModelsOutput(stdout, stderr); -} -async function listCursorModels() { - const now2 = Date.now(); - if (cached2 && cached2.expiresAt > now2) { - return cached2.models; - } - const discovered = fetchCursorModelsFromCli(); - if (discovered.length > 0) { - const merged = mergedWithFallback2(discovered); - cached2 = { - expiresAt: now2 + CURSOR_MODELS_CACHE_TTL_MS, - models: merged - }; - return merged; - } - if (cached2 && cached2.models.length > 0) { - return cached2.models; - } - return dedupeModels3(models3); -} - -// packages/adapters/pi-local/src/server/execute.ts -import fs21 from "node:fs/promises"; -import os18 from "node:os"; -import path27 from "node:path"; -import { fileURLToPath as fileURLToPath12 } from "node:url"; - -// packages/adapters/pi-local/src/server/parse.ts -function asRecord6(value) { - if (typeof value !== "object" || value === null || Array.isArray(value)) return null; - return value; -} -function extractTextContent(content) { - if (typeof content === "string") return content; - if (!Array.isArray(content)) return ""; - return content.filter((c5) => c5.type === "text" && c5.text).map((c5) => c5.text).join(""); -} -function parsePiJsonl(stdout) { - const result = { - sessionId: null, - messages: [], - errors: [], - usage: { - inputTokens: 0, - outputTokens: 0, - cachedInputTokens: 0, - costUsd: 0 - }, - finalMessage: null, - toolCalls: [] - }; - let currentToolCall = null; - for (const rawLine of stdout.split(/\r?\n/)) { - const line3 = rawLine.trim(); - if (!line3) continue; - const event = parseJson2(line3); - if (!event) continue; - const eventType = asString(event.type, ""); - if (eventType === "response" || eventType === "extension_ui_request" || eventType === "extension_ui_response" || eventType === "extension_error") { - continue; - } - if (eventType === "agent_start") { - continue; - } - if (eventType === "agent_end") { - const messages2 = event.messages; - if (messages2 && messages2.length > 0) { - const lastMessage = messages2[messages2.length - 1]; - if (lastMessage?.role === "assistant") { - const content = lastMessage.content; - result.finalMessage = extractTextContent(content); - } - } - continue; - } - if (eventType === "auto_retry_end") { - const succeeded = event.success === true; - if (!succeeded) { - const finalError = asString(event.finalError, "").trim(); - result.errors.push(finalError || "Pi exhausted automatic retries without producing a response."); - } - continue; - } - if (eventType === "turn_start") { - continue; - } - if (eventType === "turn_end") { - const message2 = asRecord6(event.message); - if (message2) { - const content = message2.content; - const text3 = extractTextContent(content); - if (text3) { - result.finalMessage = text3; - result.messages.push(text3); - } - const usage = asRecord6(message2.usage); - if (usage) { - result.usage.inputTokens += asNumber(usage.input, 0); - result.usage.outputTokens += asNumber(usage.output, 0); - result.usage.cachedInputTokens += asNumber(usage.cacheRead, 0); - const cost = asRecord6(usage.cost); - if (cost) { - result.usage.costUsd += asNumber(cost.total, 0); - } - } - } - const toolResults = event.toolResults; - if (toolResults) { - for (const tr of toolResults) { - const toolCallId = asString(tr.toolCallId, ""); - const content = tr.content; - const isError = tr.isError === true; - const existingCall = result.toolCalls.find((tc) => tc.toolCallId === toolCallId); - if (existingCall) { - existingCall.result = typeof content === "string" ? content : JSON.stringify(content); - existingCall.isError = isError; - } - } - } - continue; - } - if (eventType === "message_update") { - const assistantEvent = asRecord6(event.assistantMessageEvent); - if (assistantEvent) { - const msgType = asString(assistantEvent.type, ""); - if (msgType === "text_delta") { - const delta = asString(assistantEvent.delta, ""); - if (delta) { - if (result.messages.length === 0) { - result.messages.push(delta); - } else { - result.messages[result.messages.length - 1] += delta; - } - } - } - } - continue; - } - if (eventType === "error") { - const message2 = asString(event.message, "").trim(); - if (message2) { - result.errors.push(message2); - } - continue; - } - if (eventType === "tool_execution_start") { - const toolCallId = asString(event.toolCallId, ""); - const toolName = asString(event.toolName, ""); - const args = event.args; - currentToolCall = { toolCallId, toolName, args }; - result.toolCalls.push({ - toolCallId, - toolName, - args, - result: null, - isError: false - }); - continue; - } - if (eventType === "tool_execution_end") { - const toolCallId = asString(event.toolCallId, ""); - const toolName = asString(event.toolName, ""); - const toolResult = event.result; - const isError = event.isError === true; - const existingCall = result.toolCalls.find((tc) => tc.toolCallId === toolCallId); - if (existingCall) { - existingCall.result = typeof toolResult === "string" ? toolResult : JSON.stringify(toolResult); - existingCall.isError = isError; - } - currentToolCall = null; - continue; - } - if (eventType === "usage" || event.usage) { - const usage = asRecord6(event.usage); - if (usage) { - result.usage.inputTokens += asNumber(usage.inputTokens ?? usage.input, 0); - result.usage.outputTokens += asNumber(usage.outputTokens ?? usage.output, 0); - result.usage.cachedInputTokens += asNumber(usage.cachedInputTokens ?? usage.cacheRead, 0); - const cost = asRecord6(usage.cost); - if (cost) { - result.usage.costUsd += asNumber(cost.total ?? usage.costUsd, 0); - } else { - result.usage.costUsd += asNumber(usage.costUsd, 0); - } - } - } - } - return result; -} -function isPiUnknownSessionError(stdout, stderr) { - const haystack = `${stdout} -${stderr}`.split(/\r?\n/).map((line3) => line3.trim()).filter(Boolean).join("\n"); - return /unknown\s+session|session\s+not\s+found|session\s+.*\s+not\s+found|no\s+session/i.test(haystack); -} - -// packages/adapters/pi-local/src/server/models.ts -import { createHash as createHash7 } from "node:crypto"; -var MODELS_CACHE_TTL_MS2 = 6e4; -function firstNonEmptyLine10(text3) { - return text3.split(/\r?\n/).map((line3) => line3.trim()).find(Boolean) ?? ""; -} -function parseModelsOutput2(stdout) { - const parsed = []; - const lines = stdout.split(/\r?\n/); - let startIndex = 0; - if (lines.length > 0 && (lines[0].includes("provider") || lines[0].includes("model"))) { - startIndex = 1; - } - for (let i5 = startIndex; i5 < lines.length; i5++) { - const line3 = lines[i5].trim(); - if (!line3) continue; - const parts = line3.split(/\s{2,}/); - if (parts.length < 2) continue; - const provider = parts[0].trim(); - const model = parts[1].trim(); - if (!provider || !model) continue; - if (provider === "provider" && model === "model") continue; - const id = `${provider}/${model}`; - parsed.push({ id, label: id }); - } - return parsed; -} -function dedupeModels4(models8) { - const seen = /* @__PURE__ */ new Set(); - const deduped = []; - for (const model of models8) { - const id = model.id.trim(); - if (!id || seen.has(id)) continue; - seen.add(id); - deduped.push({ id, label: model.label.trim() || id }); - } - return deduped; -} -function sortModels2(models8) { - return [...models8].sort( - (a5, b6) => a5.id.localeCompare(b6.id, "en", { numeric: true, sensitivity: "base" }) - ); -} -function resolvePiCommand(input) { - const envOverride = typeof process.env.TASKCORE_PI_COMMAND === "string" && process.env.TASKCORE_PI_COMMAND.trim().length > 0 ? process.env.TASKCORE_PI_COMMAND.trim() : "pi"; - return asString(input, envOverride); -} -var discoveryCache2 = /* @__PURE__ */ new Map(); -var VOLATILE_ENV_KEY_PREFIXES2 = ["TASKCORE_", "npm_", "NPM_"]; -var VOLATILE_ENV_KEY_EXACT2 = /* @__PURE__ */ new Set(["PWD", "OLDPWD", "SHLVL", "_", "TERM_SESSION_ID"]); -function isVolatileEnvKey2(key) { - if (VOLATILE_ENV_KEY_EXACT2.has(key)) return true; - return VOLATILE_ENV_KEY_PREFIXES2.some((prefix) => key.startsWith(prefix)); -} -function hashValue2(value) { - return createHash7("sha256").update(value).digest("hex"); -} -function discoveryCacheKey2(command, cwd, env2) { - const envKey = Object.entries(env2).filter(([key]) => !isVolatileEnvKey2(key)).sort(([a5], [b6]) => a5.localeCompare(b6)).map(([key, value]) => `${key}=${hashValue2(value)}`).join("\n"); - return `${command} -${cwd} -${envKey}`; -} -function pruneExpiredDiscoveryCache2(now2) { - for (const [key, value] of discoveryCache2.entries()) { - if (value.expiresAt <= now2) discoveryCache2.delete(key); - } -} -async function discoverPiModels(input = {}) { - const command = resolvePiCommand(input.command); - const cwd = asString(input.cwd, process.cwd()); - const env2 = normalizeEnv3(input.env); - const runtimeEnv = normalizeEnv3({ ...process.env, ...env2 }); - const result = await runChildProcess( - `pi-models-${Date.now()}-${Math.random().toString(16).slice(2)}`, - command, - ["--list-models"], - { - cwd, - env: runtimeEnv, - timeoutSec: 20, - graceSec: 3, - onLog: async () => { - } - } - ); - if (result.timedOut) { - throw new Error("`pi --list-models` timed out."); - } - if ((result.exitCode ?? 1) !== 0) { - const detail = firstNonEmptyLine10(result.stderr) || firstNonEmptyLine10(result.stdout); - throw new Error(detail ? `\`pi --list-models\` failed: ${detail}` : "`pi --list-models` failed."); - } - const output = result.stderr || result.stdout; - return sortModels2(dedupeModels4(parseModelsOutput2(output))); -} -function normalizeEnv3(input) { - const envInput = typeof input === "object" && input !== null && !Array.isArray(input) ? input : {}; - const env2 = {}; - for (const [key, value] of Object.entries(envInput)) { - if (typeof value === "string") env2[key] = value; - } - return env2; -} -async function discoverPiModelsCached(input = {}) { - const command = resolvePiCommand(input.command); - const cwd = asString(input.cwd, process.cwd()); - const env2 = normalizeEnv3(input.env); - const key = discoveryCacheKey2(command, cwd, env2); - const now2 = Date.now(); - pruneExpiredDiscoveryCache2(now2); - const cached4 = discoveryCache2.get(key); - if (cached4 && cached4.expiresAt > now2) return cached4.models; - const models8 = await discoverPiModels({ command, cwd, env: env2 }); - discoveryCache2.set(key, { expiresAt: now2 + MODELS_CACHE_TTL_MS2, models: models8 }); - return models8; -} -async function ensurePiModelConfiguredAndAvailable(input) { - const model = asString(input.model, "").trim(); - if (!model) { - throw new Error("Pi requires `adapterConfig.model` in provider/model format."); - } - const models8 = await discoverPiModelsCached({ - command: input.command, - cwd: input.cwd, - env: input.env - }); - if (models8.length === 0) { - throw new Error("Pi returned no models. Run `pi --list-models` and verify provider auth."); - } - if (!models8.some((entry) => entry.id === model)) { - const sample = models8.slice(0, 12).map((entry) => entry.id).join(", "); - throw new Error( - `Configured Pi model is unavailable: ${model}. Available models: ${sample}${models8.length > 12 ? ", ..." : ""}` - ); - } - return models8; -} -async function listPiModels() { - try { - return await discoverPiModelsCached(); - } catch { - return []; - } -} - -// packages/adapters/pi-local/src/server/execute.ts -var __moduleDir11 = path27.dirname(fileURLToPath12(import.meta.url)); -var TASKCORE_SESSIONS_DIR = path27.join(os18.homedir(), ".pi", "taskcores"); -var PI_AGENT_SKILLS_DIR = path27.join(os18.homedir(), ".pi", "agent", "skills"); -function firstNonEmptyLine11(text3) { - return text3.split(/\r?\n/).map((line3) => line3.trim()).find(Boolean) ?? ""; -} -function parseModelProvider2(model) { - if (!model) return null; - const trimmed = model.trim(); - if (!trimmed.includes("/")) return null; - return trimmed.slice(0, trimmed.indexOf("/")).trim() || null; -} -function parseModelId(model) { - if (!model) return null; - const trimmed = model.trim(); - if (!trimmed.includes("/")) return trimmed || null; - return trimmed.slice(trimmed.indexOf("/") + 1).trim() || null; -} -async function ensurePiSkillsInjected(onLog, skillsEntries, desiredSkillNames) { - const desiredSet = new Set(desiredSkillNames ?? skillsEntries.map((entry) => entry.key)); - const selectedEntries = skillsEntries.filter((entry) => desiredSet.has(entry.key)); - if (selectedEntries.length === 0) return; - await fs21.mkdir(PI_AGENT_SKILLS_DIR, { recursive: true }); - const removedSkills = await removeMaintainerOnlySkillSymlinks( - PI_AGENT_SKILLS_DIR, - selectedEntries.map((entry) => entry.runtimeName) - ); - for (const skillName of removedSkills) { - await onLog( - "stderr", - `[taskcore] Removed maintainer-only Pi skill "${skillName}" from ${PI_AGENT_SKILLS_DIR} -` - ); - } - for (const entry of selectedEntries) { - const target = path27.join(PI_AGENT_SKILLS_DIR, entry.runtimeName); - try { - const result = await ensureTaskcoreSkillSymlink(entry.source, target); - if (result === "skipped") continue; - await onLog( - "stderr", - `[taskcore] ${result === "repaired" ? "Repaired" : "Injected"} Pi skill "${entry.runtimeName}" into ${PI_AGENT_SKILLS_DIR} -` - ); - } catch (err) { - await onLog( - "stderr", - `[taskcore] Failed to inject Pi skill "${entry.runtimeName}" into ${PI_AGENT_SKILLS_DIR}: ${err instanceof Error ? err.message : String(err)} -` - ); - } - } -} -function resolvePiBiller(env2, provider) { - return inferOpenAiCompatibleBiller(env2, null) ?? provider ?? "unknown"; -} -async function ensureSessionsDir() { - await fs21.mkdir(TASKCORE_SESSIONS_DIR, { recursive: true }); - return TASKCORE_SESSIONS_DIR; -} -function buildSessionPath(agentId, timestamp2) { - const safeTimestamp = timestamp2.replace(/[:.]/g, "-"); - return path27.join(TASKCORE_SESSIONS_DIR, `${safeTimestamp}-${agentId}.jsonl`); -} -async function execute7(ctx) { - const { runId, agent, runtime, config: config3, context, onLog, onMeta, onSpawn, authToken } = ctx; - const promptTemplate = asString( - config3.promptTemplate, - "You are agent {{agent.id}} ({{agent.name}}). Continue your Taskcore work." - ); - const command = asString(config3.command, "pi"); - const model = asString(config3.model, "").trim(); - const thinking = asString(config3.thinking, "").trim(); - const provider = parseModelProvider2(model); - const modelId = parseModelId(model); - const workspaceContext = parseObject(context.taskcoreWorkspace); - const workspaceCwd = asString(workspaceContext.cwd, ""); - const workspaceSource = asString(workspaceContext.source, ""); - const workspaceId = asString(workspaceContext.workspaceId, ""); - const workspaceRepoUrl = asString(workspaceContext.repoUrl, ""); - const workspaceRepoRef = asString(workspaceContext.repoRef, ""); - const agentHome = asString(workspaceContext.agentHome, ""); - const workspaceHints = Array.isArray(context.taskcoreWorkspaces) ? context.taskcoreWorkspaces.filter( - (value) => typeof value === "object" && value !== null - ) : []; - const configuredCwd = asString(config3.cwd, ""); - const useConfiguredInsteadOfAgentHome = workspaceSource === "agent_home" && configuredCwd.length > 0; - const effectiveWorkspaceCwd = useConfiguredInsteadOfAgentHome ? "" : workspaceCwd; - const cwd = effectiveWorkspaceCwd || configuredCwd || process.cwd(); - await ensureAbsoluteDirectory(cwd, { createIfMissing: true }); - await ensureSessionsDir(); - const piSkillEntries = await readTaskcoreRuntimeSkillEntries(config3, __moduleDir11); - const desiredPiSkillNames = resolveTaskcoreDesiredSkillNames(config3, piSkillEntries); - await ensurePiSkillsInjected(onLog, piSkillEntries, desiredPiSkillNames); - const envConfig = parseObject(config3.env); - const hasExplicitApiKey = typeof envConfig.TASKCORE_API_KEY === "string" && envConfig.TASKCORE_API_KEY.trim().length > 0; - const env2 = { ...buildTaskcoreEnv(agent) }; - env2.TASKCORE_RUN_ID = runId; - const wakeTaskId = typeof context.taskId === "string" && context.taskId.trim().length > 0 && context.taskId.trim() || typeof context.issueId === "string" && context.issueId.trim().length > 0 && context.issueId.trim() || null; - const wakeReason = typeof context.wakeReason === "string" && context.wakeReason.trim().length > 0 ? context.wakeReason.trim() : null; - const wakeCommentId = typeof context.wakeCommentId === "string" && context.wakeCommentId.trim().length > 0 && context.wakeCommentId.trim() || typeof context.commentId === "string" && context.commentId.trim().length > 0 && context.commentId.trim() || null; - const approvalId = typeof context.approvalId === "string" && context.approvalId.trim().length > 0 ? context.approvalId.trim() : null; - const approvalStatus = typeof context.approvalStatus === "string" && context.approvalStatus.trim().length > 0 ? context.approvalStatus.trim() : null; - const linkedIssueIds = Array.isArray(context.issueIds) ? context.issueIds.filter((value) => typeof value === "string" && value.trim().length > 0) : []; - const wakePayloadJson = stringifyTaskcoreWakePayload(context.taskcoreWake); - if (wakeTaskId) env2.TASKCORE_TASK_ID = wakeTaskId; - if (wakeReason) env2.TASKCORE_WAKE_REASON = wakeReason; - if (wakeCommentId) env2.TASKCORE_WAKE_COMMENT_ID = wakeCommentId; - if (approvalId) env2.TASKCORE_APPROVAL_ID = approvalId; - if (approvalStatus) env2.TASKCORE_APPROVAL_STATUS = approvalStatus; - if (linkedIssueIds.length > 0) env2.TASKCORE_LINKED_ISSUE_IDS = linkedIssueIds.join(","); - if (wakePayloadJson) env2.TASKCORE_WAKE_PAYLOAD_JSON = wakePayloadJson; - if (workspaceCwd) env2.TASKCORE_WORKSPACE_CWD = workspaceCwd; - if (workspaceSource) env2.TASKCORE_WORKSPACE_SOURCE = workspaceSource; - if (workspaceId) env2.TASKCORE_WORKSPACE_ID = workspaceId; - if (workspaceRepoUrl) env2.TASKCORE_WORKSPACE_REPO_URL = workspaceRepoUrl; - if (workspaceRepoRef) env2.TASKCORE_WORKSPACE_REPO_REF = workspaceRepoRef; - if (agentHome) env2.AGENT_HOME = agentHome; - if (workspaceHints.length > 0) env2.TASKCORE_WORKSPACES_JSON = JSON.stringify(workspaceHints); - for (const [key, value] of Object.entries(envConfig)) { - if (typeof value === "string") env2[key] = value; - } - if (!hasExplicitApiKey && authToken) { - env2.TASKCORE_API_KEY = authToken; - } - const runtimeEnv = Object.fromEntries( - Object.entries(ensurePathInEnv({ ...process.env, ...env2 })).filter( - (entry) => typeof entry[1] === "string" - ) - ); - await ensureCommandResolvable(command, cwd, runtimeEnv); - const resolvedCommand = await resolveCommandForLogs(command, cwd, runtimeEnv); - const loggedEnv = buildInvocationEnvForLogs(env2, { - runtimeEnv, - includeRuntimeKeys: ["HOME"], - resolvedCommand - }); - await ensurePiModelConfiguredAndAvailable({ - model, - command, - cwd, - env: runtimeEnv - }); - const timeoutSec = asNumber(config3.timeoutSec, 0); - const graceSec = asNumber(config3.graceSec, 20); - const extraArgs = (() => { - const fromExtraArgs = asStringArray(config3.extraArgs); - if (fromExtraArgs.length > 0) return fromExtraArgs; - return asStringArray(config3.args); - })(); - const runtimeSessionParams = parseObject(runtime.sessionParams); - const runtimeSessionId = asString(runtimeSessionParams.sessionId, runtime.sessionId ?? ""); - const runtimeSessionCwd = asString(runtimeSessionParams.cwd, ""); - const canResumeSession = runtimeSessionId.length > 0 && (runtimeSessionCwd.length === 0 || path27.resolve(runtimeSessionCwd) === path27.resolve(cwd)); - const sessionPath = canResumeSession ? runtimeSessionId : buildSessionPath(agent.id, (/* @__PURE__ */ new Date()).toISOString()); - if (runtimeSessionId && !canResumeSession) { - await onLog( - "stdout", - `[taskcore] Pi session "${runtimeSessionId}" was saved for cwd "${runtimeSessionCwd}" and will not be resumed in "${cwd}". -` - ); - } - if (!canResumeSession) { - try { - await fs21.writeFile(sessionPath, "", { flag: "wx" }); - } catch (err) { - if (err.code !== "EEXIST") { - throw err; - } - } - } - const instructionsFilePath = asString(config3.instructionsFilePath, "").trim(); - const resolvedInstructionsFilePath = instructionsFilePath ? path27.resolve(cwd, instructionsFilePath) : ""; - const instructionsFileDir = instructionsFilePath ? `${path27.dirname(instructionsFilePath)}/` : ""; - let systemPromptExtension = ""; - let instructionsReadFailed = false; - if (resolvedInstructionsFilePath) { - try { - const instructionsContents = await fs21.readFile(resolvedInstructionsFilePath, "utf8"); - systemPromptExtension = `${instructionsContents} - -The above agent instructions were loaded from ${resolvedInstructionsFilePath}. Resolve any relative file references from ${instructionsFileDir}. - -You are agent {{agent.id}} ({{agent.name}}). Continue your Taskcore work.`; - } catch (err) { - instructionsReadFailed = true; - const reason = err instanceof Error ? err.message : String(err); - await onLog( - "stdout", - `[taskcore] Warning: could not read agent instructions file "${resolvedInstructionsFilePath}": ${reason} -` - ); - systemPromptExtension = promptTemplate; - } - } else { - systemPromptExtension = promptTemplate; - } - const bootstrapPromptTemplate = asString(config3.bootstrapPromptTemplate, ""); - const templateData = { - agentId: agent.id, - companyId: agent.companyId, - runId, - company: { id: agent.companyId }, - agent, - run: { id: runId, source: "on_demand" }, - context - }; - const renderedSystemPromptExtension = renderTemplate(systemPromptExtension, templateData); - const renderedBootstrapPrompt = !canResumeSession && bootstrapPromptTemplate.trim().length > 0 ? renderTemplate(bootstrapPromptTemplate, templateData).trim() : ""; - const wakePrompt = renderTaskcoreWakePrompt(context.taskcoreWake, { resumedSession: canResumeSession }); - const shouldUseResumeDeltaPrompt = canResumeSession && wakePrompt.length > 0; - const renderedHeartbeatPrompt = shouldUseResumeDeltaPrompt ? "" : renderTemplate(promptTemplate, templateData); - const sessionHandoffNote = asString(context.taskcoreSessionHandoffMarkdown, "").trim(); - const userPrompt = joinPromptSections([ - renderedBootstrapPrompt, - wakePrompt, - sessionHandoffNote, - renderedHeartbeatPrompt - ]); - const promptMetrics = { - systemPromptChars: renderedSystemPromptExtension.length, - promptChars: userPrompt.length, - bootstrapPromptChars: renderedBootstrapPrompt.length, - wakePromptChars: wakePrompt.length, - sessionHandoffChars: sessionHandoffNote.length, - heartbeatPromptChars: renderedHeartbeatPrompt.length - }; - const commandNotes = (() => { - if (!resolvedInstructionsFilePath) return []; - if (instructionsReadFailed) { - return [ - `Configured instructionsFilePath ${resolvedInstructionsFilePath}, but file could not be read; continuing without injected instructions.` - ]; - } - return [ - `Loaded agent instructions from ${resolvedInstructionsFilePath}`, - `Appended instructions + path directive to system prompt (relative references from ${instructionsFileDir}).` - ]; - })(); - const buildArgs = (sessionFile) => { - const args = []; - args.push("--mode", "json"); - args.push("-p"); - args.push("--append-system-prompt", renderedSystemPromptExtension); - if (provider) args.push("--provider", provider); - if (modelId) args.push("--model", modelId); - if (thinking) args.push("--thinking", thinking); - args.push("--tools", "read,bash,edit,write,grep,find,ls"); - args.push("--session", sessionFile); - args.push("--skill", PI_AGENT_SKILLS_DIR); - if (extraArgs.length > 0) args.push(...extraArgs); - args.push(userPrompt); - return args; - }; - const runAttempt = async (sessionFile) => { - const args = buildArgs(sessionFile); - if (onMeta) { - await onMeta({ - adapterType: "pi_local", - command: resolvedCommand, - cwd, - commandNotes, - commandArgs: args, - env: loggedEnv, - prompt: userPrompt, - promptMetrics, - context - }); - } - let stdoutBuffer = ""; - const bufferedOnLog = async (stream, chunk) => { - if (stream === "stderr") { - await onLog(stream, chunk); - return; - } - stdoutBuffer += chunk; - const lines = stdoutBuffer.split("\n"); - stdoutBuffer = lines.pop() || ""; - for (const line3 of lines) { - if (line3) { - await onLog(stream, line3 + "\n"); - } - } - }; - const proc = await runChildProcess(runId, command, args, { - cwd, - env: runtimeEnv, - timeoutSec, - graceSec, - onSpawn, - onLog: bufferedOnLog - }); - if (stdoutBuffer) { - await onLog("stdout", stdoutBuffer); - } - return { - proc, - rawStderr: proc.stderr, - parsed: parsePiJsonl(proc.stdout) - }; - }; - const toResult = (attempt, clearSessionOnMissingSession = false) => { - if (attempt.proc.timedOut) { - return { - exitCode: attempt.proc.exitCode, - signal: attempt.proc.signal, - timedOut: true, - errorMessage: `Timed out after ${timeoutSec}s`, - clearSession: clearSessionOnMissingSession - }; - } - const resolvedSessionId = clearSessionOnMissingSession ? null : sessionPath; - const resolvedSessionParams = resolvedSessionId ? { sessionId: resolvedSessionId, cwd } : null; - const stderrLine = firstNonEmptyLine11(attempt.proc.stderr); - const rawExitCode = attempt.proc.exitCode; - const parsedError = attempt.parsed.errors.find((error50) => error50.trim().length > 0) ?? ""; - const effectiveExitCode = (rawExitCode ?? 0) === 0 && parsedError ? 1 : rawExitCode; - const fallbackErrorMessage = parsedError || stderrLine || `Pi exited with code ${rawExitCode ?? -1}`; - return { - exitCode: effectiveExitCode, - signal: attempt.proc.signal, - timedOut: false, - errorMessage: (effectiveExitCode ?? 0) === 0 ? null : fallbackErrorMessage, - usage: { - inputTokens: attempt.parsed.usage.inputTokens, - outputTokens: attempt.parsed.usage.outputTokens, - cachedInputTokens: attempt.parsed.usage.cachedInputTokens - }, - sessionId: resolvedSessionId, - sessionParams: resolvedSessionParams, - sessionDisplayId: resolvedSessionId, - provider, - biller: resolvePiBiller(runtimeEnv, provider), - model, - billingType: "unknown", - costUsd: attempt.parsed.usage.costUsd, - resultJson: { - stdout: attempt.proc.stdout, - stderr: attempt.proc.stderr - }, - summary: attempt.parsed.finalMessage ?? attempt.parsed.messages.join("\n\n").trim(), - clearSession: Boolean(clearSessionOnMissingSession) - }; - }; - const initial = await runAttempt(sessionPath); - const initialFailed = !initial.proc.timedOut && ((initial.proc.exitCode ?? 0) !== 0 || initial.parsed.errors.length > 0); - if (canResumeSession && initialFailed && isPiUnknownSessionError(initial.proc.stdout, initial.rawStderr)) { - await onLog( - "stdout", - `[taskcore] Pi session "${runtimeSessionId}" is unavailable; retrying with a fresh session. -` - ); - const newSessionPath = buildSessionPath(agent.id, (/* @__PURE__ */ new Date()).toISOString()); - try { - await fs21.writeFile(newSessionPath, "", { flag: "wx" }); - } catch (err) { - if (err.code !== "EEXIST") { - throw err; - } - } - const retry = await runAttempt(newSessionPath); - return toResult(retry, true); - } - return toResult(initial); -} - -// packages/adapters/pi-local/src/server/skills.ts -import fs22 from "node:fs/promises"; -import os19 from "node:os"; -import path28 from "node:path"; -import { fileURLToPath as fileURLToPath13 } from "node:url"; -var __moduleDir12 = path28.dirname(fileURLToPath13(import.meta.url)); -function asString8(value) { - return typeof value === "string" && value.trim().length > 0 ? value.trim() : null; -} -function resolvePiSkillsHome(config3) { - const env2 = typeof config3.env === "object" && config3.env !== null && !Array.isArray(config3.env) ? config3.env : {}; - const configuredHome = asString8(env2.HOME); - const home = configuredHome ? path28.resolve(configuredHome) : os19.homedir(); - return path28.join(home, ".pi", "agent", "skills"); -} -async function buildPiSkillSnapshot(config3) { - const availableEntries = await readTaskcoreRuntimeSkillEntries(config3, __moduleDir12); - const desiredSkills = resolveTaskcoreDesiredSkillNames(config3, availableEntries); - const skillsHome = resolvePiSkillsHome(config3); - const installed = await readInstalledSkillTargets(skillsHome); - return buildPersistentSkillSnapshot({ - adapterType: "pi_local", - availableEntries, - desiredSkills, - installed, - skillsHome, - locationLabel: "~/.pi/agent/skills", - missingDetail: "Configured but not currently linked into the Pi skills home.", - externalConflictDetail: "Skill name is occupied by an external installation.", - externalDetail: "Installed outside Taskcore management." - }); -} -async function listPiSkills(ctx) { - return buildPiSkillSnapshot(ctx.config); -} -async function syncPiSkills(ctx, desiredSkills) { - const availableEntries = await readTaskcoreRuntimeSkillEntries(ctx.config, __moduleDir12); - const desiredSet = /* @__PURE__ */ new Set([ - ...desiredSkills, - ...availableEntries.filter((entry) => entry.required).map((entry) => entry.key) - ]); - const skillsHome = resolvePiSkillsHome(ctx.config); - await fs22.mkdir(skillsHome, { recursive: true }); - const installed = await readInstalledSkillTargets(skillsHome); - const availableByRuntimeName = new Map(availableEntries.map((entry) => [entry.runtimeName, entry])); - for (const available of availableEntries) { - if (!desiredSet.has(available.key)) continue; - const target = path28.join(skillsHome, available.runtimeName); - await ensureTaskcoreSkillSymlink(available.source, target); - } - for (const [name, installedEntry] of installed.entries()) { - const available = availableByRuntimeName.get(name); - if (!available) continue; - if (desiredSet.has(available.key)) continue; - if (installedEntry.targetPath !== available.source) continue; - await fs22.unlink(path28.join(skillsHome, name)).catch(() => { - }); - } - return buildPiSkillSnapshot(ctx.config); -} - -// packages/adapters/pi-local/src/server/test.ts -function summarizeStatus7(checks) { - if (checks.some((check3) => check3.level === "error")) return "fail"; - if (checks.some((check3) => check3.level === "warn")) return "warn"; - return "pass"; -} -function firstNonEmptyLine12(text3) { - return text3.split(/\r?\n/).map((line3) => line3.trim()).find(Boolean) ?? ""; -} -function summarizeProbeDetail6(stdout, stderr, parsedError) { - const raw = parsedError?.trim() || firstNonEmptyLine12(stderr) || firstNonEmptyLine12(stdout); - if (!raw) return null; - const clean3 = raw.replace(/\s+/g, " ").trim(); - const max = 240; - return clean3.length > max ? `${clean3.slice(0, max - 1)}...` : clean3; -} -function normalizeEnv4(input) { - if (typeof input !== "object" || input === null || Array.isArray(input)) return {}; - const env2 = {}; - for (const [key, value] of Object.entries(input)) { - if (typeof value === "string") env2[key] = value; - } - return env2; -} -var PI_AUTH_REQUIRED_RE = /(?:auth(?:entication)?\s+required|api\s*key|invalid\s*api\s*key|not\s+logged\s+in|free\s+usage\s+exceeded)/i; -var PI_STALE_PACKAGE_RE = /pi-driver|npm:\s*pi-driver/i; -function buildPiModelDiscoveryFailureCheck(message2) { - if (PI_STALE_PACKAGE_RE.test(message2)) { - return { - code: "pi_package_install_failed", - level: "warn", - message: "Pi startup failed while installing configured package `npm:pi-driver`.", - detail: message2, - hint: "Remove `npm:pi-driver` from ~/.pi/agent/settings.json or set adapter env HOME to a clean Pi profile, then retry `pi --list-models`." - }; - } - return { - code: "pi_models_discovery_failed", - level: "warn", - message: message2, - hint: "Run `pi --list-models` manually to verify provider auth and config." - }; -} -async function testEnvironment7(ctx) { - const checks = []; - const config3 = parseObject(ctx.config); - const command = asString(config3.command, "pi"); - const cwd = asString(config3.cwd, process.cwd()); - try { - await ensureAbsoluteDirectory(cwd, { createIfMissing: false }); - checks.push({ - code: "pi_cwd_valid", - level: "info", - message: `Working directory is valid: ${cwd}` - }); - } catch (err) { - checks.push({ - code: "pi_cwd_invalid", - level: "error", - message: err instanceof Error ? err.message : "Invalid working directory", - detail: cwd - }); - } - const envConfig = parseObject(config3.env); - const env2 = {}; - for (const [key, value] of Object.entries(envConfig)) { - if (typeof value === "string") env2[key] = value; - } - const runtimeEnv = normalizeEnv4(ensurePathInEnv({ ...process.env, ...env2 })); - const cwdInvalid = checks.some((check3) => check3.code === "pi_cwd_invalid"); - if (cwdInvalid) { - checks.push({ - code: "pi_command_skipped", - level: "warn", - message: "Skipped command check because working directory validation failed.", - detail: command - }); - } else { - try { - await ensureCommandResolvable(command, cwd, runtimeEnv); - checks.push({ - code: "pi_command_resolvable", - level: "info", - message: `Command is executable: ${command}` - }); - } catch (err) { - checks.push({ - code: "pi_command_unresolvable", - level: "error", - message: err instanceof Error ? err.message : "Command is not executable", - detail: command - }); - } - } - const canRunProbe = checks.every((check3) => check3.code !== "pi_cwd_invalid" && check3.code !== "pi_command_unresolvable"); - if (canRunProbe) { - try { - const discovered = await discoverPiModelsCached({ command, cwd, env: runtimeEnv }); - if (discovered.length > 0) { - checks.push({ - code: "pi_models_discovered", - level: "info", - message: `Discovered ${discovered.length} model(s) from Pi.` - }); - } else { - checks.push({ - code: "pi_models_empty", - level: "warn", - message: "Pi returned no models.", - hint: "Run `pi --list-models` and verify provider authentication." - }); - } - } catch (err) { - checks.push( - buildPiModelDiscoveryFailureCheck( - err instanceof Error ? err.message : "Pi model discovery failed." - ) - ); - } - } - const configuredModel = asString(config3.model, "").trim(); - if (!configuredModel) { - checks.push({ - code: "pi_model_required", - level: "error", - message: "Pi requires a configured model in provider/model format.", - hint: "Set adapterConfig.model using an ID from `pi --list-models`." - }); - } else if (canRunProbe) { - try { - const discovered = await discoverPiModelsCached({ command, cwd, env: runtimeEnv }); - const modelExists = discovered.some((m5) => m5.id === configuredModel); - if (modelExists) { - checks.push({ - code: "pi_model_configured", - level: "info", - message: `Configured model: ${configuredModel}` - }); - } else { - checks.push({ - code: "pi_model_not_found", - level: "warn", - message: `Configured model "${configuredModel}" not found in available models.`, - hint: "Run `pi --list-models` and choose a currently available provider/model ID." - }); - } - } catch { - checks.push({ - code: "pi_model_configured", - level: "info", - message: `Configured model: ${configuredModel}` - }); - } - } - if (canRunProbe && configuredModel) { - const provider = configuredModel.includes("/") ? configuredModel.slice(0, configuredModel.indexOf("/")) : ""; - const modelId = configuredModel.includes("/") ? configuredModel.slice(configuredModel.indexOf("/") + 1) : configuredModel; - const thinking = asString(config3.thinking, "").trim(); - const extraArgs = (() => { - const fromExtraArgs = asStringArray(config3.extraArgs); - if (fromExtraArgs.length > 0) return fromExtraArgs; - return asStringArray(config3.args); - })(); - const args = ["-p", "Respond with hello.", "--mode", "json"]; - if (provider) args.push("--provider", provider); - if (modelId) args.push("--model", modelId); - if (thinking) args.push("--thinking", thinking); - args.push("--tools", "read"); - if (extraArgs.length > 0) args.push(...extraArgs); - try { - const probe = await runChildProcess( - `pi-envtest-${Date.now()}-${Math.random().toString(16).slice(2)}`, - command, - args, - { - cwd, - env: runtimeEnv, - timeoutSec: 60, - graceSec: 5, - onLog: async () => { - } - } - ); - const parsed = parsePiJsonl(probe.stdout); - const detail = summarizeProbeDetail6(probe.stdout, probe.stderr, parsed.errors[0] ?? null); - const authEvidence = `${parsed.errors.join("\n")} -${probe.stdout} -${probe.stderr}`.trim(); - if (probe.timedOut) { - checks.push({ - code: "pi_hello_probe_timed_out", - level: "warn", - message: "Pi hello probe timed out.", - hint: "Retry the probe. If this persists, run Pi manually in this working directory." - }); - } else if ((probe.exitCode ?? 1) === 0 && parsed.errors.length === 0) { - const summary = (parsed.finalMessage || parsed.messages.join(" ")).trim(); - const hasHello = /\bhello\b/i.test(summary); - checks.push({ - code: hasHello ? "pi_hello_probe_passed" : "pi_hello_probe_unexpected_output", - level: hasHello ? "info" : "warn", - message: hasHello ? "Pi hello probe succeeded." : "Pi probe ran but did not return `hello` as expected.", - ...summary ? { detail: summary.replace(/\s+/g, " ").trim().slice(0, 240) } : {}, - ...hasHello ? {} : { - hint: "Run `pi --mode json` manually and prompt `Respond with hello` to inspect output." - } - }); - } else if (PI_AUTH_REQUIRED_RE.test(authEvidence)) { - checks.push({ - code: "pi_hello_probe_auth_required", - level: "warn", - message: "Pi is installed, but provider authentication is not ready.", - ...detail ? { detail } : {}, - hint: "Set provider API key environment variable (e.g., ANTHROPIC_API_KEY, XAI_API_KEY) and retry." - }); - } else { - checks.push({ - code: "pi_hello_probe_failed", - level: "error", - message: "Pi hello probe failed.", - ...detail ? { detail } : {}, - hint: "Run `pi --mode json` manually in this working directory to debug." - }); - } - } catch (err) { - checks.push({ - code: "pi_hello_probe_failed", - level: "error", - message: "Pi hello probe failed.", - detail: err instanceof Error ? err.message : String(err), - hint: "Run `pi --mode json` manually in this working directory to debug." - }); - } - } - return { - adapterType: ctx.adapterType, - status: summarizeStatus7(checks), - checks, - testedAt: (/* @__PURE__ */ new Date()).toISOString() - }; -} - -// packages/adapters/pi-local/src/server/index.ts -function readNonEmptyString7(value) { - return typeof value === "string" && value.trim().length > 0 ? value.trim() : null; -} -var sessionCodec6 = { - deserialize(raw) { - if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return null; - const record2 = raw; - const sessionId = readNonEmptyString7(record2.sessionId) ?? readNonEmptyString7(record2.session_id) ?? readNonEmptyString7(record2.session); - if (!sessionId) return null; - const cwd = readNonEmptyString7(record2.cwd) ?? readNonEmptyString7(record2.workdir) ?? readNonEmptyString7(record2.folder); - return { - sessionId, - ...cwd ? { cwd } : {} - }; - }, - serialize(params) { - if (!params) return null; - const sessionId = readNonEmptyString7(params.sessionId) ?? readNonEmptyString7(params.session_id) ?? readNonEmptyString7(params.session); - if (!sessionId) return null; - const cwd = readNonEmptyString7(params.cwd) ?? readNonEmptyString7(params.workdir) ?? readNonEmptyString7(params.folder); - return { - sessionId, - ...cwd ? { cwd } : {} - }; - }, - getDisplayId(params) { - if (!params) return null; - return readNonEmptyString7(params.sessionId) ?? readNonEmptyString7(params.session_id) ?? readNonEmptyString7(params.session); - } -}; - -// packages/adapters/pi-local/src/index.ts -var agentConfigurationDoc7 = `# pi_local agent configuration - -Adapter: pi_local - -Use when: -- You want Taskcore to run Pi (the AI coding agent) locally as the agent runtime -- You want provider/model routing in Pi format (--provider --model ) -- You want Pi session resume across heartbeats via --session -- You need Pi's tool set (read, bash, edit, write, grep, find, ls) - -Don't use when: -- You need webhook-style external invocation (use openclaw_gateway or http) -- You only need one-shot shell commands (use process) -- Pi CLI is not installed on the machine - -Core fields: -- cwd (string, optional): default absolute working directory fallback for the agent process (created if missing when possible) -- instructionsFilePath (string, optional): absolute path to a markdown instructions file appended to system prompt via --append-system-prompt -- promptTemplate (string, optional): user prompt template passed via -p flag -- model (string, required): Pi model id in provider/model format (for example xai/grok-4) -- thinking (string, optional): thinking level (off, minimal, low, medium, high, xhigh) -- command (string, optional): defaults to "pi" -- env (object, optional): KEY=VALUE environment variables - -Operational fields: -- timeoutSec (number, optional): run timeout in seconds -- graceSec (number, optional): SIGTERM grace period in seconds - -Notes: -- Pi supports multiple providers and models. Use \`pi --list-models\` to list available options. -- Taskcore requires an explicit \`model\` value for \`pi_local\` agents. -- Sessions are stored in ~/.pi/taskcores/ and resumed with --session. -- All tools (read, bash, edit, write, grep, find, ls) are enabled by default. -- Agent instructions are appended to Pi's system prompt via --append-system-prompt, while the user task is sent via -p. -`; - -// node_modules/.pnpm/@paperclipai+adapter-utils@2026.403.0/node_modules/@paperclipai/adapter-utils/dist/server-utils.js -import { spawn as spawn3 } from "node:child_process"; -import { constants as fsConstants3, promises as fs23 } from "node:fs"; -import path29 from "node:path"; -var runningProcesses2 = /* @__PURE__ */ new Map(); -var MAX_CAPTURE_BYTES2 = 4 * 1024 * 1024; -var MAX_EXCERPT_BYTES2 = 32 * 1024; -var PAPERCLIP_SKILL_ROOT_RELATIVE_CANDIDATES = [ - "../../skills", - "../../../../../skills" -]; -function parseObject3(value) { - if (typeof value !== "object" || value === null || Array.isArray(value)) { - return {}; - } - return value; -} -function asString9(value, fallback) { - return typeof value === "string" && value.length > 0 ? value : fallback; -} -function asBoolean3(value, fallback) { - return typeof value === "boolean" ? value : fallback; -} -function appendWithCap2(prev, chunk, cap = MAX_CAPTURE_BYTES2) { - const combined = prev + chunk; - return combined.length > cap ? combined.slice(combined.length - cap) : combined; -} -function resolvePathValue2(obj, dottedPath) { - const parts = dottedPath.split("."); - let cursor2 = obj; - for (const part of parts) { - if (typeof cursor2 !== "object" || cursor2 === null || Array.isArray(cursor2)) { - return ""; - } - cursor2 = cursor2[part]; - } - if (cursor2 === null || cursor2 === void 0) - return ""; - if (typeof cursor2 === "string") - return cursor2; - if (typeof cursor2 === "number" || typeof cursor2 === "boolean") - return String(cursor2); - try { - return JSON.stringify(cursor2); - } catch { - return ""; - } -} -function renderTemplate2(template, data2) { - return template.replace(/{{\s*([a-zA-Z0-9_.-]+)\s*}}/g, (_, path53) => resolvePathValue2(data2, path53)); -} -function buildPaperclipEnv(agent) { - const resolveHostForUrl = (rawHost) => { - const host = rawHost.trim(); - if (!host || host === "0.0.0.0" || host === "::") - return "localhost"; - if (host.includes(":") && !host.startsWith("[") && !host.endsWith("]")) - return `[${host}]`; - return host; - }; - const vars = { - PAPERCLIP_AGENT_ID: agent.id, - PAPERCLIP_COMPANY_ID: agent.companyId - }; - const runtimeHost = resolveHostForUrl(process.env.PAPERCLIP_LISTEN_HOST ?? process.env.HOST ?? "localhost"); - const runtimePort = process.env.PAPERCLIP_LISTEN_PORT ?? process.env.PORT ?? "3100"; - const apiUrl = process.env.PAPERCLIP_API_URL ?? `http://${runtimeHost}:${runtimePort}`; - vars.PAPERCLIP_API_URL = apiUrl; - return vars; -} -function defaultPathForPlatform2() { - if (process.platform === "win32") { - return "C:\\Windows\\System32;C:\\Windows;C:\\Windows\\System32\\Wbem"; - } - return "/usr/local/bin:/opt/homebrew/bin:/usr/local/sbin:/usr/bin:/bin:/usr/sbin:/sbin"; -} -function windowsPathExts2(env2) { - return (env2.PATHEXT ?? ".EXE;.CMD;.BAT;.COM").split(";").filter(Boolean); -} -async function pathExists3(candidate) { - try { - await fs23.access(candidate, process.platform === "win32" ? fsConstants3.F_OK : fsConstants3.X_OK); - return true; - } catch { - return false; - } -} -async function resolveCommandPath2(command, cwd, env2) { - const hasPathSeparator = command.includes("/") || command.includes("\\"); - if (hasPathSeparator) { - const absolute = path29.isAbsolute(command) ? command : path29.resolve(cwd, command); - return await pathExists3(absolute) ? absolute : null; - } - const pathValue = env2.PATH ?? env2.Path ?? ""; - const delimiter = process.platform === "win32" ? ";" : ":"; - const dirs = pathValue.split(delimiter).filter(Boolean); - const exts = process.platform === "win32" ? windowsPathExts2(env2) : [""]; - const hasExtension = process.platform === "win32" && path29.extname(command).length > 0; - for (const dir of dirs) { - const candidates = process.platform === "win32" ? hasExtension ? [path29.join(dir, command)] : exts.map((ext) => path29.join(dir, `${command}${ext}`)) : [path29.join(dir, command)]; - for (const candidate of candidates) { - if (await pathExists3(candidate)) - return candidate; - } - } - return null; -} -function quoteForCmd2(arg) { - if (!arg.length) - return '""'; - const escaped = arg.replace(/"/g, '""'); - return /[\s"&<>|^()]/.test(escaped) ? `"${escaped}"` : escaped; -} -async function resolveSpawnTarget2(command, args, cwd, env2) { - const resolved = await resolveCommandPath2(command, cwd, env2); - const executable = resolved ?? command; - if (process.platform !== "win32") { - return { command: executable, args }; - } - if (/\.(cmd|bat)$/i.test(executable)) { - const shell = env2.ComSpec || process.env.ComSpec || "cmd.exe"; - const commandLine = [quoteForCmd2(executable), ...args.map(quoteForCmd2)].join(" "); - return { - command: shell, - args: ["/d", "/s", "/c", commandLine] - }; - } - return { command: executable, args }; -} -function ensurePathInEnv2(env2) { - if (typeof env2.PATH === "string" && env2.PATH.length > 0) - return env2; - if (typeof env2.Path === "string" && env2.Path.length > 0) - return env2; - return { ...env2, PATH: defaultPathForPlatform2() }; -} -async function ensureAbsoluteDirectory2(cwd, opts = {}) { - if (!path29.isAbsolute(cwd)) { - throw new Error(`Working directory must be an absolute path: "${cwd}"`); - } - const assertDirectory = async () => { - const stats = await fs23.stat(cwd); - if (!stats.isDirectory()) { - throw new Error(`Working directory is not a directory: "${cwd}"`); - } - }; - try { - await assertDirectory(); - return; - } catch (err) { - const code = err.code; - if (!opts.createIfMissing || code !== "ENOENT") { - if (code === "ENOENT") { - throw new Error(`Working directory does not exist: "${cwd}"`); - } - throw err instanceof Error ? err : new Error(String(err)); - } - } - try { - await fs23.mkdir(cwd, { recursive: true }); - await assertDirectory(); - } catch (err) { - const reason = err instanceof Error ? err.message : String(err); - throw new Error(`Could not create working directory "${cwd}": ${reason}`); - } -} -async function resolvePaperclipSkillsDir(moduleDir, additionalCandidates = []) { - const candidates = [ - ...PAPERCLIP_SKILL_ROOT_RELATIVE_CANDIDATES.map((relativePath) => path29.resolve(moduleDir, relativePath)), - ...additionalCandidates.map((candidate) => path29.resolve(candidate)) - ]; - const seenRoots = /* @__PURE__ */ new Set(); - for (const root of candidates) { - if (seenRoots.has(root)) - continue; - seenRoots.add(root); - const isDirectory = await fs23.stat(root).then((stats) => stats.isDirectory()).catch(() => false); - if (isDirectory) - return root; - } - return null; -} -async function listPaperclipSkillEntries(moduleDir, additionalCandidates = []) { - const root = await resolvePaperclipSkillsDir(moduleDir, additionalCandidates); - if (!root) - return []; - try { - const entries2 = await fs23.readdir(root, { withFileTypes: true }); - return entries2.filter((entry) => entry.isDirectory()).map((entry) => ({ - key: `paperclipai/paperclip/${entry.name}`, - runtimeName: entry.name, - source: path29.join(root, entry.name), - required: true, - requiredReason: "Bundled Paperclip skills are always available for local adapters." - })); - } catch { - return []; - } -} -function normalizeConfiguredPaperclipRuntimeSkills(value) { - if (!Array.isArray(value)) - return []; - const out = []; - for (const rawEntry of value) { - const entry = parseObject3(rawEntry); - const key = asString9(entry.key, asString9(entry.name, "")).trim(); - const runtimeName = asString9(entry.runtimeName, asString9(entry.name, "")).trim(); - const source = asString9(entry.source, "").trim(); - if (!key || !runtimeName || !source) - continue; - out.push({ - key, - runtimeName, - source, - required: asBoolean3(entry.required, false), - requiredReason: typeof entry.requiredReason === "string" && entry.requiredReason.trim().length > 0 ? entry.requiredReason.trim() : null - }); - } - return out; -} -async function readPaperclipRuntimeSkillEntries(config3, moduleDir, additionalCandidates = []) { - const configuredEntries = normalizeConfiguredPaperclipRuntimeSkills(config3.paperclipRuntimeSkills); - if (configuredEntries.length > 0) - return configuredEntries; - return listPaperclipSkillEntries(moduleDir, additionalCandidates); -} -function readPaperclipSkillSyncPreference(config3) { - const raw = config3.paperclipSkillSync; - if (typeof raw !== "object" || raw === null || Array.isArray(raw)) { - return { explicit: false, desiredSkills: [] }; - } - const syncConfig = raw; - const desiredValues = syncConfig.desiredSkills; - const desired = Array.isArray(desiredValues) ? desiredValues.filter((value) => typeof value === "string").map((value) => value.trim()).filter(Boolean) : []; - return { - explicit: Object.prototype.hasOwnProperty.call(raw, "desiredSkills"), - desiredSkills: Array.from(new Set(desired)) - }; -} -function canonicalizeDesiredPaperclipSkillReference(reference, availableEntries) { - const normalizedReference = reference.trim().toLowerCase(); - if (!normalizedReference) - return ""; - const exactKey = availableEntries.find((entry) => entry.key.trim().toLowerCase() === normalizedReference); - if (exactKey) - return exactKey.key; - const byRuntimeName = availableEntries.filter((entry) => typeof entry.runtimeName === "string" && entry.runtimeName.trim().toLowerCase() === normalizedReference); - if (byRuntimeName.length === 1) - return byRuntimeName[0].key; - const slugMatches = availableEntries.filter((entry) => entry.key.trim().toLowerCase().split("/").pop() === normalizedReference); - if (slugMatches.length === 1) - return slugMatches[0].key; - return normalizedReference; -} -function resolvePaperclipDesiredSkillNames(config3, availableEntries) { - const preference = readPaperclipSkillSyncPreference(config3); - const requiredSkills = availableEntries.filter((entry) => entry.required).map((entry) => entry.key); - if (!preference.explicit) { - return Array.from(new Set(requiredSkills)); - } - const desiredSkills = preference.desiredSkills.map((reference) => canonicalizeDesiredPaperclipSkillReference(reference, availableEntries)).filter(Boolean); - return Array.from(/* @__PURE__ */ new Set([...requiredSkills, ...desiredSkills])); -} -async function runChildProcess2(runId, command, args, opts) { - const onLogError = opts.onLogError ?? ((err, id, msg) => console.warn({ err, runId: id }, msg)); - return new Promise((resolve4, reject) => { - const rawMerged = { ...process.env, ...opts.env }; - const CLAUDE_CODE_NESTING_VARS = [ - "CLAUDECODE", - "CLAUDE_CODE_ENTRYPOINT", - "CLAUDE_CODE_SESSION", - "CLAUDE_CODE_PARENT_SESSION" - ]; - for (const key of CLAUDE_CODE_NESTING_VARS) { - delete rawMerged[key]; - } - const mergedEnv = ensurePathInEnv2(rawMerged); - void resolveSpawnTarget2(command, args, opts.cwd, mergedEnv).then((target) => { - const child = spawn3(target.command, target.args, { - cwd: opts.cwd, - env: mergedEnv, - shell: false, - stdio: [opts.stdin != null ? "pipe" : "ignore", "pipe", "pipe"] - }); - const startedAt = (/* @__PURE__ */ new Date()).toISOString(); - if (opts.stdin != null && child.stdin) { - child.stdin.write(opts.stdin); - child.stdin.end(); - } - if (typeof child.pid === "number" && child.pid > 0 && opts.onSpawn) { - void opts.onSpawn({ pid: child.pid, startedAt }).catch((err) => { - onLogError(err, runId, "failed to record child process metadata"); - }); - } - runningProcesses2.set(runId, { child, graceSec: opts.graceSec }); - let timedOut = false; - let stdout = ""; - let stderr = ""; - let logChain = Promise.resolve(); - const timeout = opts.timeoutSec > 0 ? setTimeout(() => { - timedOut = true; - child.kill("SIGTERM"); - setTimeout(() => { - if (!child.killed) { - child.kill("SIGKILL"); - } - }, Math.max(1, opts.graceSec) * 1e3); - }, opts.timeoutSec * 1e3) : null; - child.stdout?.on("data", (chunk) => { - const text3 = String(chunk); - stdout = appendWithCap2(stdout, text3); - logChain = logChain.then(() => opts.onLog("stdout", text3)).catch((err) => onLogError(err, runId, "failed to append stdout log chunk")); - }); - child.stderr?.on("data", (chunk) => { - const text3 = String(chunk); - stderr = appendWithCap2(stderr, text3); - logChain = logChain.then(() => opts.onLog("stderr", text3)).catch((err) => onLogError(err, runId, "failed to append stderr log chunk")); - }); - child.on("error", (err) => { - if (timeout) - clearTimeout(timeout); - runningProcesses2.delete(runId); - const errno = err.code; - const pathValue = mergedEnv.PATH ?? mergedEnv.Path ?? ""; - const msg = errno === "ENOENT" ? `Failed to start command "${command}" in "${opts.cwd}". Verify adapter command, working directory, and PATH (${pathValue}).` : `Failed to start command "${command}" in "${opts.cwd}": ${err.message}`; - reject(new Error(msg)); - }); - child.on("close", (code, signal) => { - if (timeout) - clearTimeout(timeout); - runningProcesses2.delete(runId); - void logChain.finally(() => { - resolve4({ - exitCode: code, - signal, - timedOut, - stdout, - stderr, - pid: child.pid ?? null, - startedAt - }); - }); - }); - }).catch(reject); - }); -} - -// node_modules/.pnpm/hermes-paperclip-adapter@0.2.1/node_modules/hermes-paperclip-adapter/dist/shared/constants.js -var ADAPTER_TYPE = "hermes_local"; -var HERMES_CLI = "hermes"; -var DEFAULT_TIMEOUT_SEC = 300; -var DEFAULT_GRACE_SEC = 10; -var DEFAULT_MODEL = "anthropic/claude-sonnet-4"; -var VALID_PROVIDERS = [ - "auto", - "openrouter", - "nous", - "openai-codex", - "copilot", - "copilot-acp", - "anthropic", - "huggingface", - "zai", - "kimi-coding", - "minimax", - "minimax-cn", - "kilocode" -]; -var MODEL_PREFIX_PROVIDER_HINTS = [ - // OpenAI-native models - ["gpt-4", "openai-codex"], - ["gpt-5", "copilot"], - ["o1-", "openai-codex"], - ["o3-", "openai-codex"], - ["o4-", "openai-codex"], - // Anthropic models - ["claude", "anthropic"], - // Google models (via openrouter or direct) - ["gemini", "auto"], - // Nous models - ["hermes-", "nous"], - // Z.AI / GLM models - ["glm-", "zai"], - // Kimi / Moonshot - ["moonshot", "kimi-coding"], - ["kimi", "kimi-coding"], - // MiniMax - ["minimax", "minimax"], - // DeepSeek - ["deepseek", "auto"], - // Meta Llama - ["llama", "auto"], - // Qwen - ["qwen", "auto"], - // Mistral - ["mistral", "auto"], - // HuggingFace models (org/model format) - ["huggingface/", "huggingface"] -]; - -// node_modules/.pnpm/hermes-paperclip-adapter@0.2.1/node_modules/hermes-paperclip-adapter/dist/server/detect-model.js -import { readFile as readFile2 } from "node:fs/promises"; -import { join } from "node:path"; -import { homedir } from "node:os"; -async function detectModel(configPath) { - const filePath = configPath ?? join(homedir(), ".hermes", "config.yaml"); - let content; - try { - content = await readFile2(filePath, "utf-8"); - } catch { - return null; - } - return parseModelFromConfig(content); -} -function parseModelFromConfig(content) { - const lines = content.split("\n"); - let model = ""; - let provider = ""; - let baseUrl = ""; - let apiMode = ""; - let inModelSection = false; - let modelSectionIndent = 0; - for (const line3 of lines) { - const trimmed = line3.trimEnd(); - const indent = line3.length - line3.trimStart().length; - if (/^model:\s*$/.test(trimmed) && indent === 0) { - inModelSection = true; - modelSectionIndent = 0; - continue; - } - if (inModelSection && indent <= modelSectionIndent && trimmed && !trimmed.startsWith("#")) { - inModelSection = false; - } - if (inModelSection) { - const match = trimmed.match(/^\s*(\w+)\s*:\s*(.+)$/); - if (match) { - const key = match[1]; - const val = match[2].trim().replace(/#.*$/, "").trim().replace(/^['"]|['"]$/g, ""); - if (key === "default") - model = val; - if (key === "provider") - provider = val; - if (key === "base_url") - baseUrl = val; - if (key === "api_mode") - apiMode = val; - } - } - } - if (!model) - return null; - return { model, provider, baseUrl, apiMode, source: "config" }; -} -function inferProviderFromModel(model) { - const lower = model.toLowerCase(); - const bareName = lower.includes("/") ? lower.split("/").pop() : lower; - for (const [prefix, hint] of MODEL_PREFIX_PROVIDER_HINTS) { - if (bareName.startsWith(prefix)) { - return hint; - } - } - return void 0; -} -function resolveProvider(options) { - const { explicitProvider, detectedProvider, detectedModel, model } = options; - if (explicitProvider && VALID_PROVIDERS.includes(explicitProvider)) { - return { provider: explicitProvider, resolvedFrom: "adapterConfig" }; - } - if (detectedProvider && detectedModel && VALID_PROVIDERS.includes(detectedProvider) && // Config model matches requested model (exact or case-insensitive) - detectedModel.toLowerCase() === model?.toLowerCase()) { - return { provider: detectedProvider, resolvedFrom: "hermesConfig" }; - } - if (model) { - const inferred = inferProviderFromModel(model); - if (inferred) { - return { provider: inferred, resolvedFrom: "modelInference" }; - } - } - return { provider: "auto", resolvedFrom: "auto" }; -} - -// node_modules/.pnpm/hermes-paperclip-adapter@0.2.1/node_modules/hermes-paperclip-adapter/dist/server/execute.js -function cfgString(v5) { - return typeof v5 === "string" && v5.length > 0 ? v5 : void 0; -} -function cfgNumber(v5) { - return typeof v5 === "number" ? v5 : void 0; -} -function cfgBoolean(v5) { - return typeof v5 === "boolean" ? v5 : void 0; -} -function cfgStringArray(v5) { - return Array.isArray(v5) && v5.every((i5) => typeof i5 === "string") ? v5 : void 0; -} -var DEFAULT_PROMPT_TEMPLATE = `You are "{{agentName}}", an AI agent employee in a Paperclip-managed company. - -IMPORTANT: Use \`terminal\` tool with \`curl\` for ALL Paperclip API calls (web_extract and browser cannot access localhost). - -Your Paperclip identity: - Agent ID: {{agentId}} - Company ID: {{companyId}} - API Base: {{paperclipApiUrl}} - -{{#taskId}} -## Assigned Task - -Issue ID: {{taskId}} -Title: {{taskTitle}} - -{{taskBody}} - -## Workflow - -1. Work on the task using your tools -2. When done, mark the issue as completed: - \`curl -s -X PATCH "{{paperclipApiUrl}}/issues/{{taskId}}" -H "Content-Type: application/json" -d '{"status":"done"}'\` -3. Post a completion comment on the issue summarizing what you did: - \`curl -s -X POST "{{paperclipApiUrl}}/issues/{{taskId}}/comments" -H "Content-Type: application/json" -d '{"body":"DONE: "}'\` -4. If this issue has a parent (check the issue body or comments for references like TRA-XX), post a brief notification on the parent issue so the parent owner knows: - \`curl -s -X POST "{{paperclipApiUrl}}/issues/PARENT_ISSUE_ID/comments" -H "Content-Type: application/json" -d '{"body":"{{agentName}} completed {{taskId}}. Summary: "}'\` -{{/taskId}} - -{{#commentId}} -## Comment on This Issue - -Someone commented. Read it: - \`curl -s "{{paperclipApiUrl}}/issues/{{taskId}}/comments/{{commentId}}" | python3 -m json.tool\` - -Address the comment, POST a reply if needed, then continue working. -{{/commentId}} - -{{#noTask}} -## Heartbeat Wake \u2014 Check for Work - -1. List ALL open issues assigned to you (todo, backlog, in_progress): - \`curl -s "{{paperclipApiUrl}}/companies/{{companyId}}/issues?assigneeAgentId={{agentId}}" | python3 -c "import sys,json;issues=json.loads(sys.stdin.read());[print(f'{i["identifier"]} {i["status"]:>12} {i["priority"]:>6} {i["title"]}') for i in issues if i['status'] not in ('done','cancelled')]" \` - -2. If issues found, pick the highest priority one that is not done/cancelled and work on it: - - Read the issue details: \`curl -s "{{paperclipApiUrl}}/issues/ISSUE_ID"\` - - Do the work in the project directory: {{projectName}} - - When done, mark complete and post a comment (see Workflow steps 2-4 above) - -3. If no issues assigned to you, check for unassigned issues: - \`curl -s "{{paperclipApiUrl}}/companies/{{companyId}}/issues?status=backlog" | python3 -c "import sys,json;issues=json.loads(sys.stdin.read());[print(f'{i["identifier"]} {i["title"]}') for i in issues if not i.get('assigneeAgentId')]" \` - If you find a relevant issue, assign it to yourself: - \`curl -s -X PATCH "{{paperclipApiUrl}}/issues/ISSUE_ID" -H "Content-Type: application/json" -d '{"assigneeAgentId":"{{agentId}}","status":"todo"}'\` - -4. If truly nothing to do, report briefly what you checked. -{{/noTask}}`; -function buildPrompt(ctx, config3) { - const template = cfgString(config3.promptTemplate) || DEFAULT_PROMPT_TEMPLATE; - const taskId = cfgString(ctx.config?.taskId); - const taskTitle = cfgString(ctx.config?.taskTitle) || ""; - const taskBody = cfgString(ctx.config?.taskBody) || ""; - const commentId = cfgString(ctx.config?.commentId) || ""; - const wakeReason = cfgString(ctx.config?.wakeReason) || ""; - const agentName = ctx.agent?.name || "Hermes Agent"; - const companyName = cfgString(ctx.config?.companyName) || ""; - const projectName = cfgString(ctx.config?.projectName) || ""; - let paperclipApiUrl = cfgString(config3.paperclipApiUrl) || process.env.PAPERCLIP_API_URL || "http://127.0.0.1:3100/api"; - if (!paperclipApiUrl.endsWith("/api")) { - paperclipApiUrl = paperclipApiUrl.replace(/\/+$/, "") + "/api"; - } - const vars = { - agentId: ctx.agent?.id || "", - agentName, - companyId: ctx.agent?.companyId || "", - companyName, - runId: ctx.runId || "", - taskId: taskId || "", - taskTitle, - taskBody, - commentId, - wakeReason, - projectName, - paperclipApiUrl - }; - let rendered = template; - rendered = rendered.replace(/\{\{#taskId\}\}([\s\S]*?)\{\{\/taskId\}\}/g, taskId ? "$1" : ""); - rendered = rendered.replace(/\{\{#noTask\}\}([\s\S]*?)\{\{\/noTask\}\}/g, taskId ? "" : "$1"); - rendered = rendered.replace(/\{\{#commentId\}\}([\s\S]*?)\{\{\/commentId\}\}/g, commentId ? "$1" : ""); - return renderTemplate2(rendered, vars); -} -var SESSION_ID_REGEX = /^session_id:\s*(\S+)/m; -var SESSION_ID_REGEX_LEGACY = /session[_ ](?:id|saved)[:\s]+([a-zA-Z0-9_-]+)/i; -var TOKEN_USAGE_REGEX = /tokens?[:\s]+(\d+)\s*(?:input|in)\b.*?(\d+)\s*(?:output|out)\b/i; -var COST_REGEX = /(?:cost|spent)[:\s]*\$?([\d.]+)/i; -function cleanResponse(raw) { - return raw.split("\n").filter((line3) => { - const t5 = line3.trim(); - if (!t5) - return true; - if (t5.startsWith("[tool]") || t5.startsWith("[hermes]") || t5.startsWith("[paperclip]")) - return false; - if (t5.startsWith("session_id:")) - return false; - if (/^\[\d{4}-\d{2}-\d{2}T/.test(t5)) - return false; - if (/^\[done\]\s*┊/.test(t5)) - return false; - if (/^┊\s*[\p{Emoji_Presentation}]/u.test(t5) && !/^┊\s*💬/.test(t5)) - return false; - if (new RegExp("^\\p{Emoji_Presentation}\\s*(Completed|Running|Error)?\\s*$", "u").test(t5)) - return false; - return true; - }).map((line3) => { - let t5 = line3.replace(/^[\s]*┊\s*💬\s*/, "").trim(); - t5 = t5.replace(/^\[done\]\s*/, "").trim(); - return t5; - }).join("\n").replace(/\n{3,}/g, "\n\n").trim(); -} -function parseHermesOutput(stdout, stderr) { - const combined = stdout + "\n" + stderr; - const result = {}; - const sessionMatch = stdout.match(SESSION_ID_REGEX); - if (sessionMatch?.[1]) { - result.sessionId = sessionMatch?.[1] ?? null; - const sessionLineIdx = stdout.lastIndexOf("\nsession_id:"); - if (sessionLineIdx > 0) { - result.response = cleanResponse(stdout.slice(0, sessionLineIdx)); - } - } else { - const legacyMatch = combined.match(SESSION_ID_REGEX_LEGACY); - if (legacyMatch?.[1]) { - result.sessionId = legacyMatch?.[1] ?? null; - } - const cleaned = cleanResponse(stdout); - if (cleaned.length > 0) { - result.response = cleaned; - } - } - const usageMatch = combined.match(TOKEN_USAGE_REGEX); - if (usageMatch) { - result.usage = { - inputTokens: parseInt(usageMatch[1], 10) || 0, - outputTokens: parseInt(usageMatch[2], 10) || 0 - }; - } - const costMatch = combined.match(COST_REGEX); - if (costMatch?.[1]) { - result.costUsd = parseFloat(costMatch[1]); - } - if (stderr.trim()) { - const errorLines = stderr.split("\n").filter((line3) => /error|exception|traceback|failed/i.test(line3)).filter((line3) => !/INFO|DEBUG|warn/i.test(line3)); - if (errorLines.length > 0) { - result.errorMessage = errorLines.slice(0, 5).join("\n"); - } - } - return result; -} -async function execute8(ctx) { - const config3 = ctx.agent?.adapterConfig ?? {}; - const hermesCmd = cfgString(config3.hermesCommand) || HERMES_CLI; - const model = cfgString(config3.model) || DEFAULT_MODEL; - const timeoutSec = cfgNumber(config3.timeoutSec) || DEFAULT_TIMEOUT_SEC; - const graceSec = cfgNumber(config3.graceSec) || DEFAULT_GRACE_SEC; - const toolsets = cfgString(config3.toolsets) || cfgStringArray(config3.enabledToolsets)?.join(","); - const extraArgs = cfgStringArray(config3.extraArgs); - const persistSession = cfgBoolean(config3.persistSession) !== false; - const worktreeMode = cfgBoolean(config3.worktreeMode) === true; - const checkpoints = cfgBoolean(config3.checkpoints) === true; - let detectedConfig = null; - const explicitProvider = cfgString(config3.provider); - if (!explicitProvider) { - try { - detectedConfig = await detectModel(); - } catch { - } - } - const { provider: resolvedProvider, resolvedFrom } = resolveProvider({ - explicitProvider, - detectedProvider: detectedConfig?.provider, - detectedModel: detectedConfig?.model, - model - }); - const prompt = buildPrompt(ctx, config3); - const useQuiet = cfgBoolean(config3.quiet) !== false; - const args = ["chat", "-q", prompt]; - if (useQuiet) - args.push("-Q"); - if (model) { - args.push("-m", model); - } - if (resolvedProvider !== "auto") { - args.push("--provider", resolvedProvider); - } - if (toolsets) { - args.push("-t", toolsets); - } - if (worktreeMode) - args.push("-w"); - if (checkpoints) - args.push("--checkpoints"); - if (cfgBoolean(config3.verbose) === true) - args.push("-v"); - args.push("--source", "tool"); - args.push("--yolo"); - const prevSessionId = cfgString(ctx.runtime?.sessionParams?.sessionId); - if (persistSession && prevSessionId) { - args.push("--resume", prevSessionId); - } - if (extraArgs?.length) { - args.push(...extraArgs); - } - const env2 = { - ...process.env, - ...buildPaperclipEnv(ctx.agent) - }; - if (ctx.runId) - env2.PAPERCLIP_RUN_ID = ctx.runId; - const taskId = cfgString(ctx.config?.taskId); - if (taskId) - env2.PAPERCLIP_TASK_ID = taskId; - const userEnv = config3.env; - if (userEnv && typeof userEnv === "object") { - Object.assign(env2, userEnv); - } - const cwd = cfgString(config3.cwd) || cfgString(ctx.config?.workspaceDir) || "."; - try { - await ensureAbsoluteDirectory2(cwd); - } catch { - } - await ctx.onLog("stdout", `[hermes] Starting Hermes Agent (model=${model}, provider=${resolvedProvider} [${resolvedFrom}], timeout=${timeoutSec}s) -`); - if (prevSessionId) { - await ctx.onLog("stdout", `[hermes] Resuming session: ${prevSessionId} -`); - } - const wrappedOnLog = async (stream, chunk) => { - if (stream === "stderr") { - const trimmed = chunk.trimEnd(); - const isBenign = /^\[?\d{4}[-/]\d{2}[-/]\d{2}T/.test(trimmed) || // structured timestamps - /^[A-Z]+:\s+(INFO|DEBUG|WARN|WARNING)\b/.test(trimmed) || // log levels - /Successfully registered all tools/.test(trimmed) || /MCP [Ss]erver/.test(trimmed) || /tool registered successfully/.test(trimmed) || /Application initialized/.test(trimmed); - if (isBenign) { - return ctx.onLog("stdout", chunk); - } - } - return ctx.onLog(stream, chunk); - }; - const result = await runChildProcess2(ctx.runId, hermesCmd, args, { - cwd, - env: env2, - timeoutSec, - graceSec, - onLog: wrappedOnLog - }); - const parsed = parseHermesOutput(result.stdout || "", result.stderr || ""); - await ctx.onLog("stdout", `[hermes] Exit code: ${result.exitCode ?? "null"}, timed out: ${result.timedOut} -`); - if (parsed.sessionId) { - await ctx.onLog("stdout", `[hermes] Session: ${parsed.sessionId} -`); - } - const executionResult = { - exitCode: result.exitCode, - signal: result.signal, - timedOut: result.timedOut, - provider: resolvedProvider, - model - }; - if (parsed.errorMessage) { - executionResult.errorMessage = parsed.errorMessage; - } - if (parsed.usage) { - executionResult.usage = parsed.usage; - } - if (parsed.costUsd !== void 0) { - executionResult.costUsd = parsed.costUsd; - } - if (parsed.response) { - executionResult.summary = parsed.response.slice(0, 2e3); - } - executionResult.resultJson = { - result: parsed.response || "", - session_id: parsed.sessionId || null, - usage: parsed.usage || null, - cost_usd: parsed.costUsd ?? null - }; - if (persistSession && parsed.sessionId) { - executionResult.sessionParams = { sessionId: parsed.sessionId }; - executionResult.sessionDisplayId = parsed.sessionId.slice(0, 16); - } - return executionResult; -} - -// node_modules/.pnpm/hermes-paperclip-adapter@0.2.1/node_modules/hermes-paperclip-adapter/dist/server/test.js -import { execFile as execFile2 } from "node:child_process"; -import { promisify as promisify2 } from "node:util"; -var execFileAsync2 = promisify2(execFile2); -function asString10(v5) { - return typeof v5 === "string" ? v5 : void 0; -} -async function checkCliInstalled(command) { - try { - await execFileAsync2(command, ["--version"], { timeout: 1e4 }); - return null; - } catch (err) { - const e5 = err; - if (e5.code === "ENOENT") { - return { - level: "error", - message: `Hermes CLI "${command}" not found in PATH`, - hint: "Install Hermes Agent: pip install hermes-agent", - code: "hermes_cli_not_found" - }; - } - return null; - } -} -async function checkCliVersion(command) { - try { - const { stdout } = await execFileAsync2(command, ["--version"], { - timeout: 1e4 - }); - const version3 = stdout.trim(); - if (version3) { - return { - level: "info", - message: `Hermes Agent version: ${version3}`, - code: "hermes_version" - }; - } - return { - level: "warn", - message: "Could not determine Hermes Agent version", - code: "hermes_version_unknown" - }; - } catch { - return { - level: "warn", - message: "Could not determine Hermes Agent version (hermes --version failed)", - hint: "Make sure the hermes CLI is properly installed and functional", - code: "hermes_version_failed" - }; - } -} -async function checkPython() { - try { - const { stdout } = await execFileAsync2("python3", ["--version"], { - timeout: 5e3 - }); - const version3 = stdout.trim(); - const match = version3.match(/(\d+)\.(\d+)/); - if (match) { - const major = parseInt(match[1], 10); - const minor = parseInt(match[2], 10); - if (major < 3 || major === 3 && minor < 10) { - return { - level: "error", - message: `Python ${version3} found \u2014 Hermes requires Python 3.10+`, - hint: "Upgrade Python to 3.10 or later", - code: "hermes_python_old" - }; - } - } - return null; - } catch { - return { - level: "warn", - message: "python3 not found in PATH", - hint: "Hermes Agent requires Python 3.10+. Install it from python.org", - code: "hermes_python_missing" - }; - } -} -function checkModel(config3) { - const model = asString10(config3.model); - if (!model) { - return { - level: "info", - message: "No model specified \u2014 Hermes will use its configured default model", - hint: "Set a model explicitly in Paperclip only if you want to override your local Hermes configuration.", - code: "hermes_configured_default_model" - }; - } - return { - level: "info", - message: `Model: ${model}`, - code: "hermes_model_configured" - }; -} -function checkApiKeys(config3) { - const envConfig = config3.env ?? {}; - const resolvedEnv = {}; - for (const [key, value] of Object.entries(envConfig)) { - if (typeof value === "string" && value.length > 0) - resolvedEnv[key] = value; - } - const has = (key) => !!(resolvedEnv[key] ?? process.env[key]); - const hasAnthropic = has("ANTHROPIC_API_KEY"); - const hasOpenRouter = has("OPENROUTER_API_KEY"); - const hasOpenAI = has("OPENAI_API_KEY"); - const hasZai = has("ZAI_API_KEY"); - const hasKimi = has("KIMI_API_KEY"); - const hasMiniMax = has("MINIMAX_API_KEY"); - if (!hasAnthropic && !hasOpenRouter && !hasOpenAI && !hasZai && !hasKimi && !hasMiniMax) { - return { - level: "warn", - message: "No LLM API keys found in environment", - hint: "Set API keys in the agent's env secrets or ~/.hermes/.env. Hermes supports: ANTHROPIC_API_KEY, OPENROUTER_API_KEY, OPENAI_API_KEY, ZAI_API_KEY, KIMI_API_KEY, MINIMAX_API_KEY", - code: "hermes_no_api_keys" - }; - } - const providers2 = []; - if (hasAnthropic) - providers2.push("Anthropic"); - if (hasOpenRouter) - providers2.push("OpenRouter"); - if (hasOpenAI) - providers2.push("OpenAI"); - if (hasZai) - providers2.push("Z.AI"); - if (hasKimi) - providers2.push("Kimi"); - if (hasMiniMax) - providers2.push("MiniMax"); - return { - level: "info", - message: `API keys found: ${providers2.join(", ")}`, - code: "hermes_api_keys_found" - }; -} -async function checkProviderConsistency(config3) { - const model = asString10(config3.model); - if (!model) - return null; - const explicitProvider = asString10(config3.provider); - let detectedConfig = null; - try { - detectedConfig = await detectModel(); - } catch { - } - const { provider: resolved, resolvedFrom } = resolveProvider({ - explicitProvider, - detectedProvider: detectedConfig?.provider, - detectedModel: detectedConfig?.model, - model - }); - if (explicitProvider && detectedConfig?.provider && explicitProvider !== detectedConfig.provider) { - return { - level: "warn", - message: `Provider mismatch: adapterConfig has "${explicitProvider}" but ~/.hermes/config.yaml has "${detectedConfig.provider}". Using adapterConfig value.`, - hint: `Model "${model}" may not work correctly with provider "${explicitProvider}". Consider aligning with your Hermes config or removing the explicit provider to use auto-detection.`, - code: "hermes_provider_mismatch" - }; - } - if (!explicitProvider && resolvedFrom !== "auto") { - return { - level: "info", - message: `Provider auto-detected as "${resolved}" (from ${resolvedFrom}) for model "${model}"`, - code: "hermes_provider_detected" - }; - } - if (resolvedFrom === "auto" && !explicitProvider) { - return { - level: "warn", - message: `Could not determine provider for model "${model}" \u2014 will use Hermes auto-detection`, - hint: "Set an explicit provider in the agent config or ensure ~/.hermes/config.yaml has a matching provider for this model.", - code: "hermes_provider_unknown" - }; - } - return null; -} -async function testEnvironment8(ctx) { - const config3 = ctx.config ?? {}; - const command = asString10(config3.hermesCommand) || HERMES_CLI; - const checks = []; - const cliCheck = await checkCliInstalled(command); - if (cliCheck) { - checks.push(cliCheck); - if (cliCheck.level === "error") { - return { - adapterType: ADAPTER_TYPE, - status: "fail", - checks, - testedAt: (/* @__PURE__ */ new Date()).toISOString() - }; - } - } - const versionCheck = await checkCliVersion(command); - if (versionCheck) - checks.push(versionCheck); - const pythonCheck = await checkPython(); - if (pythonCheck) - checks.push(pythonCheck); - const modelCheck = checkModel(config3); - if (modelCheck) - checks.push(modelCheck); - const apiKeyCheck = checkApiKeys(config3); - if (apiKeyCheck) - checks.push(apiKeyCheck); - const providerCheck = await checkProviderConsistency(config3); - if (providerCheck) - checks.push(providerCheck); - const hasErrors = checks.some((c5) => c5.level === "error"); - const hasWarnings = checks.some((c5) => c5.level === "warn"); - return { - adapterType: ADAPTER_TYPE, - status: hasErrors ? "fail" : hasWarnings ? "warn" : "pass", - checks, - testedAt: (/* @__PURE__ */ new Date()).toISOString() - }; -} - -// node_modules/.pnpm/hermes-paperclip-adapter@0.2.1/node_modules/hermes-paperclip-adapter/dist/server/skills.js -import fs24 from "node:fs/promises"; -import os20 from "node:os"; -import path30 from "node:path"; -import { fileURLToPath as fileURLToPath14 } from "node:url"; -var __moduleDir13 = path30.dirname(fileURLToPath14(import.meta.url)); -function asString11(value) { - return typeof value === "string" && value.trim().length > 0 ? value.trim() : null; -} -function resolveHermesHome(config3) { - const env2 = typeof config3.env === "object" && config3.env !== null && !Array.isArray(config3.env) ? config3.env : {}; - const configuredHome = asString11(env2.HOME); - return configuredHome ? path30.resolve(configuredHome) : os20.homedir(); -} -function parseSkillFrontmatter(content) { - const match = content.match(/^---\s*\n([\s\S]*?)\n---/); - if (!match) - return {}; - const frontmatter = {}; - for (const line3 of match[1].split("\n")) { - const idx = line3.indexOf(":"); - if (idx === -1) - continue; - const key = line3.slice(0, idx).trim(); - let val = line3.slice(idx + 1).trim(); - if (typeof val === "string" && (val.startsWith('"') && val.endsWith('"') || val.startsWith("'") && val.endsWith("'"))) { - val = val.slice(1, -1); - } - frontmatter[key] = val; - } - return frontmatter; -} -async function scanHermesSkills(skillsHome) { - const entries2 = []; - try { - const categories = await fs24.readdir(skillsHome, { withFileTypes: true }); - for (const cat of categories) { - if (!cat.isDirectory()) - continue; - const catPath = path30.join(skillsHome, cat.name); - const topLevelSkillMd = path30.join(catPath, "SKILL.md"); - if (await fs24.stat(topLevelSkillMd).catch(() => null)) { - entries2.push(await buildSkillEntry(cat.name, topLevelSkillMd, cat.name)); - } - const items = await fs24.readdir(catPath, { withFileTypes: true }).catch(() => []); - for (const item of items) { - if (!item.isDirectory()) - continue; - const skillMd = path30.join(catPath, item.name, "SKILL.md"); - if (await fs24.stat(skillMd).catch(() => null)) { - const key = item.name; - entries2.push(await buildSkillEntry(key, skillMd, `${cat.name}/${item.name}`)); - } - } - } - } catch { - } - return entries2.sort((a5, b6) => a5.key.localeCompare(b6.key)); -} -async function buildSkillEntry(key, skillMdPath, categoryPath) { - let description = null; - try { - const content = await fs24.readFile(skillMdPath, "utf8"); - const fm = parseSkillFrontmatter(content); - description = fm.description ?? null; - } catch { - } - return { - key, - runtimeName: key, - desired: true, - // Hermes loads all available skills - managed: false, - state: "installed", - origin: "user_installed", - originLabel: "Hermes skill", - locationLabel: `~/.hermes/skills/${categoryPath}`, - readOnly: true, - // Hermes manages its own skills — Paperclip can't toggle them - sourcePath: skillMdPath, - targetPath: null, - detail: description - }; -} -async function buildHermesSkillSnapshot(config3) { - const home = resolveHermesHome(config3); - const hermesSkillsHome = path30.join(home, ".hermes", "skills"); - const paperclipEntries = await readPaperclipRuntimeSkillEntries(config3, __moduleDir13); - const desiredSkills = resolvePaperclipDesiredSkillNames(config3, paperclipEntries); - const desiredSet = new Set(desiredSkills); - const availableByKey = new Map(paperclipEntries.map((e5) => [e5.key, e5])); - const hermesSkillEntries = await scanHermesSkills(hermesSkillsHome); - const hermesKeys = new Set(hermesSkillEntries.map((e5) => e5.key)); - const entries2 = []; - const warnings = []; - for (const entry of paperclipEntries) { - const desired = desiredSet.has(entry.key); - entries2.push({ - key: entry.key, - runtimeName: entry.runtimeName, - desired, - managed: true, - state: desired ? "configured" : "available", - origin: entry.required ? "paperclip_required" : "company_managed", - originLabel: entry.required ? "Required by Paperclip" : "Managed by Paperclip", - readOnly: false, - sourcePath: entry.source, - targetPath: null, - detail: desired ? "Will be available on the next run via Hermes skill loading." : null, - required: Boolean(entry.required), - requiredReason: entry.requiredReason ?? null - }); - } - for (const entry of hermesSkillEntries) { - if (availableByKey.has(entry.key)) - continue; - entries2.push(entry); - } - for (const desiredSkill of desiredSkills) { - if (availableByKey.has(desiredSkill) || hermesKeys.has(desiredSkill)) - continue; - warnings.push(`Desired skill "${desiredSkill}" is not available in Paperclip or Hermes skills.`); - entries2.push({ - key: desiredSkill, - runtimeName: null, - desired: true, - managed: true, - state: "missing", - origin: "external_unknown", - originLabel: "External or unavailable", - readOnly: false, - sourcePath: null, - targetPath: null, - detail: "Cannot find this skill in Paperclip or ~/.hermes/skills/." - }); - } - return { - adapterType: "hermes_local", - supported: true, - mode: "persistent", - desiredSkills, - entries: entries2, - warnings - }; -} -async function listHermesSkills(ctx) { - return buildHermesSkillSnapshot(ctx.config); -} -async function syncHermesSkills(ctx, _desiredSkills) { - return buildHermesSkillSnapshot(ctx.config); -} - -// node_modules/.pnpm/hermes-paperclip-adapter@0.2.1/node_modules/hermes-paperclip-adapter/dist/server/index.js -function readNonEmptyString8(value) { - return typeof value === "string" && value.trim().length > 0 ? value.trim() : null; -} -var sessionCodec7 = { - deserialize(raw) { - if (typeof raw !== "object" || raw === null || Array.isArray(raw)) - return null; - const record2 = raw; - const sessionId = readNonEmptyString8(record2.sessionId) ?? readNonEmptyString8(record2.session_id); - if (!sessionId) - return null; - return { sessionId }; - }, - serialize(params) { - if (!params) - return null; - const sessionId = readNonEmptyString8(params.sessionId) ?? readNonEmptyString8(params.session_id); - if (!sessionId) - return null; - return { sessionId }; - }, - getDisplayId(params) { - if (!params) - return null; - return readNonEmptyString8(params.sessionId) ?? readNonEmptyString8(params.session_id); - } -}; - -// node_modules/.pnpm/hermes-paperclip-adapter@0.2.1/node_modules/hermes-paperclip-adapter/dist/index.js -var models7 = []; -var agentConfigurationDoc8 = `# Hermes Agent Configuration - -Hermes Agent is a full-featured AI agent by Nous Research with 30+ native -tools, persistent memory, session persistence, skills, and MCP support. - -## Prerequisites - -- Python 3.10+ installed -- Hermes Agent installed: \`pip install hermes-agent\` -- At least one LLM API key configured in ~/.hermes/.env - -## Core Configuration - -| Field | Type | Default | Description | -|-------|------|---------|-------------| -| model | string | (Hermes configured default) | Optional explicit model in provider/model format. Leave blank to use Hermes's configured default model. | -| provider | string | (auto) | API provider: auto, openrouter, nous, openai-codex, zai, kimi-coding, minimax, minimax-cn. Usually not needed \u2014 Hermes auto-detects from model name. | -| timeoutSec | number | 300 | Execution timeout in seconds | -| graceSec | number | 10 | Grace period after SIGTERM before SIGKILL | - -## Tool Configuration - -| Field | Type | Default | Description | -|-------|------|---------|-------------| -| toolsets | string | (all) | Comma-separated toolsets to enable (e.g. "terminal,file,web") | - -## Session & Workspace - -| Field | Type | Default | Description | -|-------|------|---------|-------------| -| persistSession | boolean | true | Resume sessions across heartbeats | -| worktreeMode | boolean | false | Use git worktree for isolated changes | -| checkpoints | boolean | false | Enable filesystem checkpoints | - -## Advanced - -| Field | Type | Default | Description | -|-------|------|---------|-------------| -| hermesCommand | string | hermes | Path to hermes CLI binary | -| verbose | boolean | false | Enable verbose output | -| extraArgs | string[] | [] | Additional CLI arguments | -| env | object | {} | Extra environment variables | -| promptTemplate | string | (default) | Custom prompt template with {{variable}} placeholders | - -## Available Template Variables - -- \`{{agentId}}\` \u2014 Paperclip agent ID -- \`{{agentName}}\` \u2014 Agent display name -- \`{{companyId}}\` \u2014 Paperclip company ID -- \`{{companyName}}\` \u2014 Company display name -- \`{{runId}}\` \u2014 Current heartbeat run ID -- \`{{taskId}}\` \u2014 Current task/issue ID (if assigned) -- \`{{taskTitle}}\` \u2014 Task title (if assigned) -- \`{{taskBody}}\` \u2014 Task description (if assigned) -- \`{{projectName}}\` \u2014 Project name (if scoped to a project) -`; - -// server/src/adapters/builtin-adapter-types.ts -var BUILTIN_ADAPTER_TYPES = /* @__PURE__ */ new Set([ - "claude_local", - "codex_local", - "cursor", - "gemini_local", - "openclaw_gateway", - "opencode_local", - "pi_local", - "hermes_local", - "process", - "http" -]); - -// server/src/adapters/plugin-loader.ts -import fs26 from "node:fs"; -import path32 from "node:path"; - -// server/src/services/adapter-plugin-store.ts -import fs25 from "node:fs"; -import path31 from "node:path"; -import os21 from "node:os"; -var TASKCORE_DIR = path31.join(os21.homedir(), ".taskcore"); -var ADAPTER_PLUGINS_DIR = path31.join(TASKCORE_DIR, "adapter-plugins"); -var ADAPTER_PLUGINS_STORE_PATH = path31.join(TASKCORE_DIR, "adapter-plugins.json"); -var ADAPTER_SETTINGS_PATH = path31.join(TASKCORE_DIR, "adapter-settings.json"); -var storeCache = null; -var settingsCache = null; -function ensureDirs() { - fs25.mkdirSync(ADAPTER_PLUGINS_DIR, { recursive: true }); - const pkgJsonPath = path31.join(ADAPTER_PLUGINS_DIR, "package.json"); - if (!fs25.existsSync(pkgJsonPath)) { - fs25.writeFileSync(pkgJsonPath, JSON.stringify({ - name: "taskcore-adapter-plugins", - version: "0.0.0", - private: true, - description: "Managed directory for Taskcore external adapter plugins. Do not edit manually." - }, null, 2) + "\n"); - } -} -function readStore() { - if (storeCache) return storeCache; - try { - const raw = fs25.readFileSync(ADAPTER_PLUGINS_STORE_PATH, "utf-8"); - const parsed = JSON.parse(raw); - storeCache = Array.isArray(parsed) ? parsed : []; - } catch { - storeCache = []; - } - return storeCache; -} -function writeStore(records) { - ensureDirs(); - fs25.writeFileSync(ADAPTER_PLUGINS_STORE_PATH, JSON.stringify(records, null, 2), "utf-8"); - storeCache = records; -} -function readSettings() { - if (settingsCache) return settingsCache; - try { - const raw = fs25.readFileSync(ADAPTER_SETTINGS_PATH, "utf-8"); - const parsed = JSON.parse(raw); - settingsCache = parsed && Array.isArray(parsed.disabledTypes) ? parsed : { disabledTypes: [] }; - } catch { - settingsCache = { disabledTypes: [] }; - } - return settingsCache; -} -function writeSettings(settings) { - ensureDirs(); - fs25.writeFileSync(ADAPTER_SETTINGS_PATH, JSON.stringify(settings, null, 2), "utf-8"); - settingsCache = settings; -} -function listAdapterPlugins() { - return readStore(); -} -function addAdapterPlugin(record2) { - const store = [...readStore()]; - const idx = store.findIndex((r5) => r5.type === record2.type); - if (idx >= 0) { - store[idx] = record2; - } else { - store.push(record2); - } - writeStore(store); -} -function removeAdapterPlugin(type) { - const store = [...readStore()]; - const idx = store.findIndex((r5) => r5.type === type); - if (idx < 0) return false; - store.splice(idx, 1); - writeStore(store); - return true; -} -function getAdapterPluginByType(type) { - return readStore().find((r5) => r5.type === type); -} -function getAdapterPluginsDir() { - ensureDirs(); - return ADAPTER_PLUGINS_DIR; -} -function getDisabledAdapterTypes() { - return readSettings().disabledTypes; -} -function setAdapterDisabled(type, disabled) { - const settings = { ...readSettings(), disabledTypes: [...readSettings().disabledTypes] }; - const idx = settings.disabledTypes.indexOf(type); - if (disabled && idx < 0) { - settings.disabledTypes.push(type); - writeSettings(settings); - return true; - } - if (!disabled && idx >= 0) { - settings.disabledTypes.splice(idx, 1); - writeSettings(settings); - return true; - } - return false; -} - -// server/src/adapters/plugin-loader.ts -var uiParserCache = /* @__PURE__ */ new Map(); -function getOrExtractUiParserSource(adapterType) { - const cached4 = uiParserCache.get(adapterType); - if (cached4) return cached4; - const record2 = getAdapterPluginByType(adapterType); - if (!record2) return void 0; - const packageDir = resolvePackageDir(record2); - const source = extractUiParserSource(packageDir, record2.packageName); - if (source) { - uiParserCache.set(adapterType, source); - logger.info( - { type: adapterType, packageName: record2.packageName, origin: "lazy" }, - "UI parser extracted on-demand (cache miss)" - ); - } - return source; -} -function resolvePackageDir(record2) { - return record2.localPath ? path32.resolve(record2.localPath) : path32.resolve(getAdapterPluginsDir(), "node_modules", record2.packageName); -} -function resolvePackageEntryPoint(packageDir) { - const pkgJsonPath = path32.join(packageDir, "package.json"); - const pkg2 = JSON.parse(fs26.readFileSync(pkgJsonPath, "utf-8")); - if (pkg2.exports && typeof pkg2.exports === "object" && pkg2.exports["."]) { - const exp = pkg2.exports["."]; - return typeof exp === "string" ? exp : exp.import ?? exp.default ?? "index.js"; - } - return pkg2.main ?? "index.js"; -} -var SUPPORTED_PARSER_CONTRACT = "1"; -function extractUiParserSource(packageDir, packageName) { - const pkgJsonPath = path32.join(packageDir, "package.json"); - const pkg2 = JSON.parse(fs26.readFileSync(pkgJsonPath, "utf-8")); - if (!pkg2.exports || typeof pkg2.exports !== "object" || !pkg2.exports["./ui-parser"]) { - return void 0; - } - const contractVersion = pkg2.taskcore?.adapterUiParser; - if (contractVersion) { - const major = contractVersion.split(".")[0]; - if (major !== SUPPORTED_PARSER_CONTRACT) { - logger.warn( - { packageName, contractVersion, supported: `${SUPPORTED_PARSER_CONTRACT}.x` }, - "Adapter declares unsupported UI parser contract version \u2014 skipping UI parser" - ); - return void 0; - } - } else { - logger.info( - { packageName }, - "Adapter has ./ui-parser export but no taskcore.adapterUiParser version \u2014 loading anyway (future versions may require it)" - ); - } - const uiParserExp = pkg2.exports["./ui-parser"]; - const uiParserFile = typeof uiParserExp === "string" ? uiParserExp : uiParserExp.import ?? uiParserExp.default; - const uiParserPath = path32.resolve(packageDir, uiParserFile); - if (!uiParserPath.startsWith(packageDir + path32.sep) && uiParserPath !== packageDir) { - logger.warn( - { packageName, uiParserFile }, - "UI parser path escapes package directory \u2014 skipping" - ); - return void 0; - } - if (!fs26.existsSync(uiParserPath)) { - return void 0; - } - try { - const source = fs26.readFileSync(uiParserPath, "utf-8"); - logger.info( - { packageName, uiParserFile, size: source.length }, - `Loaded UI parser from adapter package${contractVersion ? "" : " (no version declared)"}` - ); - return source; - } catch (err) { - logger.warn({ err, packageName, uiParserFile }, "Failed to read UI parser from adapter package"); - return void 0; - } -} -function validateAdapterModule(mod, packageName) { - const m5 = mod; - const createServerAdapter = m5.createServerAdapter; - if (typeof createServerAdapter !== "function") { - throw new Error( - `Package "${packageName}" does not export createServerAdapter(). Ensure the package's main entry exports a createServerAdapter function.` - ); - } - const adapterModule = createServerAdapter(); - if (!adapterModule || !adapterModule.type) { - throw new Error( - `createServerAdapter() from "${packageName}" returned an invalid module (missing "type").` - ); - } - return adapterModule; -} -async function loadExternalAdapterPackage(packageName, localPath) { - const packageDir = localPath ? path32.resolve(localPath) : path32.resolve(getAdapterPluginsDir(), "node_modules", packageName); - const entryPoint = resolvePackageEntryPoint(packageDir); - const modulePath = path32.resolve(packageDir, entryPoint); - const uiParserSource = extractUiParserSource(packageDir, packageName); - logger.info({ packageName, packageDir, entryPoint, modulePath, hasUiParser: !!uiParserSource }, "Loading external adapter package"); - const mod = await import(modulePath); - const adapterModule = validateAdapterModule(mod, packageName); - if (uiParserSource) { - uiParserCache.set(adapterModule.type, uiParserSource); - } - return adapterModule; -} -async function loadFromRecord(record2) { - try { - return await loadExternalAdapterPackage(record2.packageName, record2.localPath); - } catch (err) { - logger.warn( - { err, packageName: record2.packageName, type: record2.type }, - "Failed to dynamically load external adapter; skipping" - ); - return null; - } -} -async function reloadExternalAdapter(type) { - const record2 = getAdapterPluginByType(type); - if (!record2) return null; - const packageDir = resolvePackageDir(record2); - const entryPoint = resolvePackageEntryPoint(packageDir); - const modulePath = path32.resolve(packageDir, entryPoint); - const fileUrl = `file://${modulePath}`; - try { - const bunCache = globalThis.Bun?.__moduleCache; - if (bunCache) { - bunCache.delete(fileUrl); - bunCache.delete(modulePath); - } - } catch { - } - const cacheBustUrl = `${fileUrl}?t=${Date.now()}`; - logger.info( - { type, packageName: record2.packageName, modulePath, cacheBustUrl }, - "Reloading external adapter (cache bust)" - ); - const mod = await import(cacheBustUrl); - const adapterModule = validateAdapterModule(mod, record2.packageName); - uiParserCache.delete(type); - const uiParserSource = extractUiParserSource(packageDir, record2.packageName); - if (uiParserSource) { - uiParserCache.set(adapterModule.type, uiParserSource); - } - logger.info( - { type, packageName: record2.packageName, hasUiParser: !!uiParserSource }, - "Successfully reloaded external adapter" - ); - return adapterModule; -} -async function buildExternalAdapters() { - const results = []; - const storeRecords = listAdapterPlugins(); - for (const record2 of storeRecords) { - const adapter = await loadFromRecord(record2); - if (adapter) { - results.push(adapter); - } - } - if (results.length > 0) { - logger.info( - { count: results.length, adapters: results.map((a5) => a5.type) }, - "Loaded external adapters from plugin store" - ); - } - return results; -} - -// server/src/adapters/utils.ts -var runningProcesses3 = runningProcesses; -var MAX_EXCERPT_BYTES3 = MAX_EXCERPT_BYTES; -var parseObject4 = parseObject; -var asString12 = asString; -var asNumber3 = asNumber; -var asBoolean4 = asBoolean; -var asStringArray2 = asStringArray; -var appendWithCap3 = appendWithCap; -var renderTemplate3 = renderTemplate; -var redactEnvForLogs2 = redactEnvForLogs; -var buildTaskcoreEnv2 = buildTaskcoreEnv; -var ensurePathInEnv3 = ensurePathInEnv; -var ensureAbsoluteDirectory3 = ensureAbsoluteDirectory; -var ensureCommandResolvable2 = ensureCommandResolvable; -var resolveCommandForLogs2 = resolveCommandForLogs; -function buildInvocationEnvForLogs2(env2, options = {}) { - const maybeBuildInvocationEnvForLogs = buildInvocationEnvForLogs; - if (typeof maybeBuildInvocationEnvForLogs === "function") { - return maybeBuildInvocationEnvForLogs(env2, options); - } - const merged = { ...env2 }; - const runtimeEnv = options.runtimeEnv ?? {}; - for (const key of options.includeRuntimeKeys ?? []) { - if (key in merged) continue; - const value = runtimeEnv[key]; - if (typeof value !== "string" || value.length === 0) continue; - merged[key] = value; - } - const resolvedCommand = options.resolvedCommand?.trim(); - if (resolvedCommand) { - merged[options.resolvedCommandEnvKey ?? "TASKCORE_RESOLVED_COMMAND"] = resolvedCommand; - } - return redactEnvForLogs2(merged); -} -var _runChildProcess = runChildProcess; -async function runChildProcess3(runId, command, args, opts) { - return _runChildProcess(runId, command, args, { - ...opts, - onLogError: (err, id, msg) => logger.warn({ err, runId: id }, msg) - }); -} - -// server/src/adapters/process/execute.ts -async function execute9(ctx) { - const { runId, agent, config: config3, onLog, onMeta } = ctx; - const command = asString12(config3.command, ""); - if (!command) throw new Error("Process adapter missing command"); - const args = asStringArray2(config3.args); - const cwd = asString12(config3.cwd, process.cwd()); - const envConfig = parseObject4(config3.env); - const env2 = { ...buildTaskcoreEnv2(agent) }; - for (const [k5, v5] of Object.entries(envConfig)) { - if (typeof v5 === "string") env2[k5] = v5; - } - const runtimeEnv = ensurePathInEnv3({ ...process.env, ...env2 }); - const resolvedCommand = await resolveCommandForLogs2(command, cwd, runtimeEnv); - const loggedEnv = buildInvocationEnvForLogs2(env2, { - runtimeEnv, - includeRuntimeKeys: ["HOME"], - resolvedCommand - }); - const timeoutSec = asNumber3(config3.timeoutSec, 0); - const graceSec = asNumber3(config3.graceSec, 15); - if (onMeta) { - await onMeta({ - adapterType: "process", - command: resolvedCommand, - cwd, - commandArgs: args, - env: loggedEnv - }); - } - const proc = await runChildProcess3(runId, command, args, { - cwd, - env: env2, - timeoutSec, - graceSec, - onLog - }); - if (proc.timedOut) { - return { - exitCode: proc.exitCode, - signal: proc.signal, - timedOut: true, - errorMessage: `Timed out after ${timeoutSec}s` - }; - } - if ((proc.exitCode ?? 0) !== 0) { - return { - exitCode: proc.exitCode, - signal: proc.signal, - timedOut: false, - errorMessage: `Process exited with code ${proc.exitCode ?? -1}`, - resultJson: { - stdout: proc.stdout, - stderr: proc.stderr - } - }; - } - return { - exitCode: proc.exitCode, - signal: proc.signal, - timedOut: false, - resultJson: { - stdout: proc.stdout, - stderr: proc.stderr - } - }; -} - -// server/src/adapters/process/test.ts -function summarizeStatus8(checks) { - if (checks.some((check3) => check3.level === "error")) return "fail"; - if (checks.some((check3) => check3.level === "warn")) return "warn"; - return "pass"; -} -async function testEnvironment9(ctx) { - const checks = []; - const config3 = parseObject4(ctx.config); - const command = asString12(config3.command, ""); - const cwd = asString12(config3.cwd, process.cwd()); - if (!command) { - checks.push({ - code: "process_command_missing", - level: "error", - message: "Process adapter requires a command.", - hint: "Set adapterConfig.command to an executable command." - }); - } else { - checks.push({ - code: "process_command_present", - level: "info", - message: `Configured command: ${command}` - }); - } - try { - await ensureAbsoluteDirectory3(cwd); - checks.push({ - code: "process_cwd_valid", - level: "info", - message: `Working directory is valid: ${cwd}` - }); - } catch (err) { - checks.push({ - code: "process_cwd_invalid", - level: "error", - message: err instanceof Error ? err.message : "Invalid working directory", - detail: cwd - }); - } - if (command) { - const envConfig = parseObject4(config3.env); - const env2 = {}; - for (const [key, value] of Object.entries(envConfig)) { - if (typeof value === "string") env2[key] = value; - } - const runtimeEnv = ensurePathInEnv3({ ...process.env, ...env2 }); - try { - await ensureCommandResolvable2(command, cwd, runtimeEnv); - checks.push({ - code: "process_command_resolvable", - level: "info", - message: `Command is executable: ${command}` - }); - } catch (err) { - checks.push({ - code: "process_command_unresolvable", - level: "error", - message: err instanceof Error ? err.message : "Command is not executable", - detail: command - }); - } - } - return { - adapterType: ctx.adapterType, - status: summarizeStatus8(checks), - checks, - testedAt: (/* @__PURE__ */ new Date()).toISOString() - }; -} - -// server/src/adapters/process/index.ts -var processAdapter = { - type: "process", - execute: execute9, - testEnvironment: testEnvironment9, - models: [], - agentConfigurationDoc: `# process agent configuration - -Adapter: process - -Core fields: -- command (string, required): command to execute -- args (string[] | string, optional): command arguments -- cwd (string, optional): absolute working directory -- env (object, optional): KEY=VALUE environment variables - -Operational fields: -- timeoutSec (number, optional): run timeout in seconds -- graceSec (number, optional): SIGTERM grace period in seconds -` -}; - -// server/src/adapters/http/execute.ts -async function execute10(ctx) { - const { config: config3, runId, agent, context } = ctx; - const url2 = asString12(config3.url, ""); - if (!url2) throw new Error("HTTP adapter missing url"); - const method = asString12(config3.method, "POST"); - const timeoutMs = asNumber3(config3.timeoutMs, 0); - const headers = parseObject4(config3.headers); - const payloadTemplate = parseObject4(config3.payloadTemplate); - const body = { ...payloadTemplate, agentId: agent.id, runId, context }; - const controller = new AbortController(); - const timer2 = timeoutMs > 0 ? setTimeout(() => controller.abort(), timeoutMs) : null; - try { - const res = await fetch(url2, { - method, - headers: { - "content-type": "application/json", - ...headers - }, - body: JSON.stringify(body), - ...timer2 ? { signal: controller.signal } : {} - }); - if (!res.ok) { - throw new Error(`HTTP invoke failed with status ${res.status}`); - } - return { - exitCode: 0, - signal: null, - timedOut: false, - summary: `HTTP ${method} ${url2}` - }; - } finally { - if (timer2) clearTimeout(timer2); - } -} - -// server/src/adapters/http/test.ts -function summarizeStatus9(checks) { - if (checks.some((check3) => check3.level === "error")) return "fail"; - if (checks.some((check3) => check3.level === "warn")) return "warn"; - return "pass"; -} -function normalizeMethod(input) { - const trimmed = input.trim(); - return trimmed.length > 0 ? trimmed.toUpperCase() : "POST"; -} -async function testEnvironment10(ctx) { - const checks = []; - const config3 = parseObject4(ctx.config); - const urlValue = asString12(config3.url, ""); - const method = normalizeMethod(asString12(config3.method, "POST")); - if (!urlValue) { - checks.push({ - code: "http_url_missing", - level: "error", - message: "HTTP adapter requires a URL.", - hint: "Set adapterConfig.url to an absolute http(s) endpoint." - }); - return { - adapterType: ctx.adapterType, - status: summarizeStatus9(checks), - checks, - testedAt: (/* @__PURE__ */ new Date()).toISOString() - }; - } - let url2 = null; - try { - url2 = new URL(urlValue); - } catch { - checks.push({ - code: "http_url_invalid", - level: "error", - message: `Invalid URL: ${urlValue}` - }); - } - if (url2 && url2.protocol !== "http:" && url2.protocol !== "https:") { - checks.push({ - code: "http_url_protocol_invalid", - level: "error", - message: `Unsupported URL protocol: ${url2.protocol}`, - hint: "Use an http:// or https:// endpoint." - }); - } - if (url2) { - checks.push({ - code: "http_url_valid", - level: "info", - message: `Configured endpoint: ${url2.toString()}` - }); - } - checks.push({ - code: "http_method_configured", - level: "info", - message: `Configured method: ${method}` - }); - if (url2 && (url2.protocol === "http:" || url2.protocol === "https:")) { - const controller = new AbortController(); - const timeout = setTimeout(() => controller.abort(), 3e3); - try { - const response = await fetch(url2, { - method: "HEAD", - signal: controller.signal - }); - if (!response.ok && response.status !== 405 && response.status !== 501) { - checks.push({ - code: "http_endpoint_probe_unexpected_status", - level: "warn", - message: `Endpoint probe returned HTTP ${response.status}.`, - hint: "Verify the endpoint is reachable from the Taskcore server host." - }); - } else { - checks.push({ - code: "http_endpoint_probe_ok", - level: "info", - message: "Endpoint responded to a HEAD probe." - }); - } - } catch (err) { - checks.push({ - code: "http_endpoint_probe_failed", - level: "warn", - message: err instanceof Error ? err.message : "Endpoint probe failed", - hint: "This may be expected in restricted networks; verify connectivity when invoking runs." - }); - } finally { - clearTimeout(timeout); - } - } - return { - adapterType: ctx.adapterType, - status: summarizeStatus9(checks), - checks, - testedAt: (/* @__PURE__ */ new Date()).toISOString() - }; -} - -// server/src/adapters/http/index.ts -var httpAdapter = { - type: "http", - execute: execute10, - testEnvironment: testEnvironment10, - models: [], - agentConfigurationDoc: `# http agent configuration - -Adapter: http - -Core fields: -- url (string, required): endpoint to invoke -- method (string, optional): HTTP method, default POST -- headers (object, optional): request headers -- payloadTemplate (object, optional): JSON payload template -- timeoutSec (number, optional): request timeout in seconds -` -}; - -// server/src/adapters/registry.ts -var claudeLocalAdapter = { - type: "claude_local", - execute, - testEnvironment, - listSkills: listClaudeSkills, - syncSkills: syncClaudeSkills, - sessionCodec, - sessionManagement: getAdapterSessionManagement("claude_local") ?? void 0, - models, - listModels: listClaudeModels, - supportsLocalAgentJwt: true, - agentConfigurationDoc, - getQuotaWindows -}; -var codexLocalAdapter = { - type: "codex_local", - execute: execute2, - testEnvironment: testEnvironment2, - listSkills: listCodexSkills, - syncSkills: syncCodexSkills, - sessionCodec: sessionCodec2, - sessionManagement: getAdapterSessionManagement("codex_local") ?? void 0, - models: models2, - listModels: listCodexModels, - supportsLocalAgentJwt: true, - agentConfigurationDoc: agentConfigurationDoc2, - getQuotaWindows: getQuotaWindows2 -}; -var cursorLocalAdapter = { - type: "cursor", - execute: execute4, - testEnvironment: testEnvironment4, - listSkills: listCursorSkills, - syncSkills: syncCursorSkills, - sessionCodec: sessionCodec4, - sessionManagement: getAdapterSessionManagement("cursor") ?? void 0, - models: models3, - listModels: listCursorModels, - supportsLocalAgentJwt: true, - agentConfigurationDoc: agentConfigurationDoc3 -}; -var geminiLocalAdapter = { - type: "gemini_local", - execute: execute5, - testEnvironment: testEnvironment5, - listSkills: listGeminiSkills, - syncSkills: syncGeminiSkills, - sessionCodec: sessionCodec5, - sessionManagement: getAdapterSessionManagement("gemini_local") ?? void 0, - models: models4, - supportsLocalAgentJwt: true, - agentConfigurationDoc: agentConfigurationDoc4 -}; -var openclawGatewayAdapter = { - type: "openclaw_gateway", - execute: execute6, - testEnvironment: testEnvironment6, - models: models6, - supportsLocalAgentJwt: false, - agentConfigurationDoc: agentConfigurationDoc6 -}; -var openCodeLocalAdapter = { - type: "opencode_local", - execute: execute3, - testEnvironment: testEnvironment3, - listSkills: listOpenCodeSkills, - syncSkills: syncOpenCodeSkills, - sessionCodec: sessionCodec3, - models: models5, - sessionManagement: getAdapterSessionManagement("opencode_local") ?? void 0, - listModels: listOpenCodeModels, - supportsLocalAgentJwt: true, - agentConfigurationDoc: agentConfigurationDoc5 -}; -var piLocalAdapter = { - type: "pi_local", - execute: execute7, - testEnvironment: testEnvironment7, - listSkills: listPiSkills, - syncSkills: syncPiSkills, - sessionCodec: sessionCodec6, - sessionManagement: getAdapterSessionManagement("pi_local") ?? void 0, - models: [], - listModels: listPiModels, - supportsLocalAgentJwt: true, - agentConfigurationDoc: agentConfigurationDoc7 -}; -var hermesLocalAdapter = { - type: "hermes_local", - execute: execute8, - testEnvironment: testEnvironment8, - sessionCodec: sessionCodec7, - listSkills: listHermesSkills, - syncSkills: syncHermesSkills, - models: models7, - supportsLocalAgentJwt: true, - agentConfigurationDoc: agentConfigurationDoc8, - detectModel: () => detectModel() -}; -var adaptersByType = /* @__PURE__ */ new Map(); -var builtinFallbacks = /* @__PURE__ */ new Map(); -var pausedOverrides = /* @__PURE__ */ new Set(); -function registerBuiltInAdapters() { - for (const adapter of [ - claudeLocalAdapter, - codexLocalAdapter, - openCodeLocalAdapter, - piLocalAdapter, - cursorLocalAdapter, - geminiLocalAdapter, - openclawGatewayAdapter, - hermesLocalAdapter, - processAdapter, - httpAdapter - ]) { - adaptersByType.set(adapter.type, adapter); - } -} -registerBuiltInAdapters(); -var externalAdaptersReady = (async () => { - try { - const externalAdapters = await buildExternalAdapters(); - for (const externalAdapter of externalAdapters) { - const overriding = BUILTIN_ADAPTER_TYPES.has(externalAdapter.type); - if (overriding) { - console.log( - `[taskcore] External adapter "${externalAdapter.type}" overrides built-in adapter` - ); - const existing = adaptersByType.get(externalAdapter.type); - if (existing && !builtinFallbacks.has(externalAdapter.type)) { - builtinFallbacks.set(externalAdapter.type, existing); - } - } - adaptersByType.set( - externalAdapter.type, - { - ...externalAdapter, - sessionManagement: getAdapterSessionManagement(externalAdapter.type) ?? void 0 - } - ); - } - } catch (err) { - console.error("[taskcore] Failed to load external adapters:", err); - } -})(); -function registerServerAdapter(adapter) { - if (BUILTIN_ADAPTER_TYPES.has(adapter.type) && !builtinFallbacks.has(adapter.type)) { - const existing = adaptersByType.get(adapter.type); - if (existing) { - builtinFallbacks.set(adapter.type, existing); - } - } - adaptersByType.set(adapter.type, adapter); -} -function unregisterServerAdapter(type) { - if (type === processAdapter.type || type === httpAdapter.type) return; - if (builtinFallbacks.has(type)) { - pausedOverrides.delete(type); - const fallback = builtinFallbacks.get(type); - if (fallback) { - adaptersByType.set(type, fallback); - } - return; - } - if (BUILTIN_ADAPTER_TYPES.has(type)) { - return; - } - adaptersByType.delete(type); -} -function requireServerAdapter(type) { - const adapter = findActiveServerAdapter(type); - if (!adapter) { - throw new Error(`Unknown adapter type: ${type}`); - } - return adapter; -} -function getServerAdapter(type) { - return findActiveServerAdapter(type) ?? processAdapter; -} -async function listAdapterModels(type) { - const adapter = findActiveServerAdapter(type); - if (!adapter) return []; - if (adapter.listModels) { - const discovered = await adapter.listModels(); - if (discovered.length > 0) return discovered; - } - return adapter.models ?? []; -} -function listServerAdapters() { - return Array.from(adaptersByType.values()); -} -async function detectAdapterModel(type) { - const adapter = findActiveServerAdapter(type); - if (!adapter?.detectModel) return null; - const detected = await adapter.detectModel(); - if (!detected) return null; - return { - model: detected.model, - provider: detected.provider, - source: detected.source, - ...detected.candidates?.length ? { candidates: detected.candidates } : {} - }; -} -function setOverridePaused(type, paused) { - if (!builtinFallbacks.has(type)) return false; - const wasPaused = pausedOverrides.has(type); - if (paused && !wasPaused) { - pausedOverrides.add(type); - console.log(`[taskcore] Override paused for "${type}" \u2014 builtin adapter restored`); - return true; - } - if (!paused && wasPaused) { - pausedOverrides.delete(type); - console.log(`[taskcore] Override resumed for "${type}" \u2014 external adapter active`); - return true; - } - return false; -} -function isOverridePaused(type) { - return pausedOverrides.has(type); -} -function findServerAdapter(type) { - return adaptersByType.get(type) ?? null; -} -function findActiveServerAdapter(type) { - if (pausedOverrides.has(type)) { - const fallback = builtinFallbacks.get(type); - if (fallback) return fallback; - } - return adaptersByType.get(type) ?? null; -} - -// server/src/services/github-fetch.ts -function isGitHubDotCom(hostname3) { - const h5 = hostname3.toLowerCase(); - return h5 === "github.com" || h5 === "www.github.com"; -} -function gitHubApiBase(hostname3) { - return isGitHubDotCom(hostname3) ? "https://api.github.com" : `https://${hostname3}/api/v3`; -} -function resolveRawGitHubUrl(hostname3, owner, repo, ref, filePath) { - const p5 = filePath.replace(/^\/+/, ""); - return isGitHubDotCom(hostname3) ? `https://raw.githubusercontent.com/${owner}/${repo}/${ref}/${p5}` : `https://${hostname3}/raw/${owner}/${repo}/${ref}/${p5}`; -} -async function ghFetch(url2, init2) { - try { - return await fetch(url2, init2); - } catch { - throw unprocessable(`Could not connect to ${new URL(url2).hostname} \u2014 ensure the URL points to a GitHub or GitHub Enterprise instance`); - } -} - -// server/src/services/agents.ts -init_drizzle_orm(); -init_src2(); -import { createHash as createHash8, randomBytes as randomBytes2 } from "node:crypto"; - -// server/src/services/agent-permissions.ts -function defaultPermissionsForRole(role) { - return { - canCreateAgents: role === "ceo" - }; -} -function normalizeAgentPermissions(permissions, role) { - const defaults = defaultPermissionsForRole(role); - if (typeof permissions !== "object" || permissions === null || Array.isArray(permissions)) { - return defaults; - } - const record2 = permissions; - return { - canCreateAgents: typeof record2.canCreateAgents === "boolean" ? record2.canCreateAgents : defaults.canCreateAgents - }; -} - -// server/src/services/agents.ts -function hashToken2(token) { - return createHash8("sha256").update(token).digest("hex"); -} -function createToken() { - return `pcp_${randomBytes2(24).toString("hex")}`; -} -var CONFIG_REVISION_FIELDS = [ - "name", - "role", - "title", - "reportsTo", - "capabilities", - "adapterType", - "adapterConfig", - "runtimeConfig", - "budgetMonthlyCents", - "metadata" -]; -function isPlainRecord2(value) { - return typeof value === "object" && value !== null && !Array.isArray(value); -} -function jsonEqual(left, right) { - return JSON.stringify(left) === JSON.stringify(right); -} -function buildConfigSnapshot(row) { - const adapterConfig = typeof row.adapterConfig === "object" && row.adapterConfig !== null && !Array.isArray(row.adapterConfig) ? sanitizeRecord(row.adapterConfig) : {}; - const runtimeConfig = typeof row.runtimeConfig === "object" && row.runtimeConfig !== null && !Array.isArray(row.runtimeConfig) ? sanitizeRecord(row.runtimeConfig) : {}; - const metadata = typeof row.metadata === "object" && row.metadata !== null && !Array.isArray(row.metadata) ? sanitizeRecord(row.metadata) : row.metadata ?? null; - return { - name: row.name, - role: row.role, - title: row.title, - reportsTo: row.reportsTo, - capabilities: row.capabilities, - adapterType: row.adapterType, - adapterConfig, - runtimeConfig, - budgetMonthlyCents: row.budgetMonthlyCents, - metadata - }; -} -function containsRedactedMarker(value) { - if (value === REDACTED_EVENT_VALUE) return true; - if (Array.isArray(value)) return value.some((item) => containsRedactedMarker(item)); - if (typeof value !== "object" || value === null) return false; - return Object.values(value).some((entry) => containsRedactedMarker(entry)); -} -function hasConfigPatchFields(data2) { - return CONFIG_REVISION_FIELDS.some((field) => Object.prototype.hasOwnProperty.call(data2, field)); -} -function diffConfigSnapshot(before, after) { - return CONFIG_REVISION_FIELDS.filter((field) => !jsonEqual(before[field], after[field])); -} -function configPatchFromSnapshot(snapshot) { - if (!isPlainRecord2(snapshot)) throw unprocessable("Invalid revision snapshot"); - if (typeof snapshot.name !== "string" || snapshot.name.length === 0) { - throw unprocessable("Invalid revision snapshot: name"); - } - if (typeof snapshot.role !== "string" || snapshot.role.length === 0) { - throw unprocessable("Invalid revision snapshot: role"); - } - if (typeof snapshot.adapterType !== "string" || snapshot.adapterType.length === 0) { - throw unprocessable("Invalid revision snapshot: adapterType"); - } - if (typeof snapshot.budgetMonthlyCents !== "number" || !Number.isFinite(snapshot.budgetMonthlyCents)) { - throw unprocessable("Invalid revision snapshot: budgetMonthlyCents"); - } - return { - name: snapshot.name, - role: snapshot.role, - title: typeof snapshot.title === "string" || snapshot.title === null ? snapshot.title : null, - reportsTo: typeof snapshot.reportsTo === "string" || snapshot.reportsTo === null ? snapshot.reportsTo : null, - capabilities: typeof snapshot.capabilities === "string" || snapshot.capabilities === null ? snapshot.capabilities : null, - adapterType: snapshot.adapterType, - adapterConfig: isPlainRecord2(snapshot.adapterConfig) ? snapshot.adapterConfig : {}, - runtimeConfig: isPlainRecord2(snapshot.runtimeConfig) ? snapshot.runtimeConfig : {}, - budgetMonthlyCents: Math.max(0, Math.floor(snapshot.budgetMonthlyCents)), - metadata: isPlainRecord2(snapshot.metadata) || snapshot.metadata === null ? snapshot.metadata : null - }; -} -function hasAgentShortnameCollision(candidateName, existingAgents, options) { - const candidateShortname = normalizeAgentUrlKey(candidateName); - if (!candidateShortname) return false; - return existingAgents.some((agent) => { - if (agent.status === "terminated") return false; - if (options?.excludeAgentId && agent.id === options.excludeAgentId) return false; - return normalizeAgentUrlKey(agent.name) === candidateShortname; - }); -} -function deduplicateAgentName(candidateName, existingAgents) { - if (!hasAgentShortnameCollision(candidateName, existingAgents)) { - return candidateName; - } - for (let i5 = 2; i5 <= 100; i5++) { - const suffixed = `${candidateName} ${i5}`; - if (!hasAgentShortnameCollision(suffixed, existingAgents)) { - return suffixed; - } - } - return `${candidateName} ${Date.now()}`; -} -function agentService(db) { - function currentUtcMonthWindow3(now2 = /* @__PURE__ */ new Date()) { - const year3 = now2.getUTCFullYear(); - const month = now2.getUTCMonth(); - return { - start: new Date(Date.UTC(year3, month, 1, 0, 0, 0, 0)), - end: new Date(Date.UTC(year3, month + 1, 1, 0, 0, 0, 0)) - }; - } - function withUrlKey(row) { - return { - ...row, - urlKey: normalizeAgentUrlKey(row.name) ?? row.id - }; - } - function normalizeAgentRow(row) { - return withUrlKey({ - ...row, - permissions: normalizeAgentPermissions(row.permissions, row.role) - }); - } - async function getMonthlySpendByAgentIds(companyId, agentIds) { - if (agentIds.length === 0) return /* @__PURE__ */ new Map(); - const { start, end } = currentUtcMonthWindow3(); - const rows = await db.select({ - agentId: costEvents.agentId, - spentMonthlyCents: sql`coalesce(sum(${costEvents.costCents}), 0)::int` - }).from(costEvents).where( - and( - eq(costEvents.companyId, companyId), - inArray(costEvents.agentId, agentIds), - gte(costEvents.occurredAt, start), - lt(costEvents.occurredAt, end) - ) - ).groupBy(costEvents.agentId); - return new Map(rows.map((row) => [row.agentId, Number(row.spentMonthlyCents ?? 0)])); - } - async function hydrateAgentSpend(rows) { - const agentIds = rows.map((row) => row.id); - const companyId = rows[0]?.companyId; - if (!companyId || agentIds.length === 0) return rows; - const spendByAgentId = await getMonthlySpendByAgentIds(companyId, agentIds); - return rows.map((row) => ({ - ...row, - spentMonthlyCents: spendByAgentId.get(row.id) ?? 0 - })); - } - async function getById(id) { - const row = await db.select().from(agents).where(eq(agents.id, id)).then((rows) => rows[0] ?? null); - if (!row) return null; - const [hydrated] = await hydrateAgentSpend([row]); - return normalizeAgentRow(hydrated); - } - async function ensureManager(companyId, managerId) { - const manager = await getById(managerId); - if (!manager) throw notFound("Manager not found"); - if (manager.companyId !== companyId) { - throw unprocessable("Manager must belong to same company"); - } - return manager; - } - async function assertNoCycle(agentId, reportsTo) { - if (!reportsTo) return; - if (reportsTo === agentId) throw unprocessable("Agent cannot report to itself"); - let cursor2 = reportsTo; - while (cursor2) { - if (cursor2 === agentId) throw unprocessable("Reporting relationship would create cycle"); - const next = await getById(cursor2); - cursor2 = next?.reportsTo ?? null; - } - } - async function assertCompanyShortnameAvailable(companyId, candidateName, options) { - const candidateShortname = normalizeAgentUrlKey(candidateName); - if (!candidateShortname) return; - const existingAgents = await db.select({ - id: agents.id, - name: agents.name, - status: agents.status - }).from(agents).where(eq(agents.companyId, companyId)); - const hasCollision = hasAgentShortnameCollision(candidateName, existingAgents, options); - if (hasCollision) { - throw conflict( - `Agent shortname '${candidateShortname}' is already in use in this company` - ); - } - } - async function updateAgent(id, data2, options) { - const existing = await getById(id); - if (!existing) return null; - if (existing.status === "terminated" && data2.status && data2.status !== "terminated") { - throw conflict("Terminated agents cannot be resumed"); - } - if (existing.status === "pending_approval" && data2.status && data2.status !== "pending_approval" && data2.status !== "terminated") { - throw conflict("Pending approval agents cannot be activated directly"); - } - if (data2.reportsTo !== void 0) { - if (data2.reportsTo) { - await ensureManager(existing.companyId, data2.reportsTo); - } - await assertNoCycle(id, data2.reportsTo); - } - if (data2.name !== void 0) { - const previousShortname = normalizeAgentUrlKey(existing.name); - const nextShortname = normalizeAgentUrlKey(data2.name); - if (previousShortname !== nextShortname) { - await assertCompanyShortnameAvailable(existing.companyId, data2.name, { excludeAgentId: id }); - } - } - const normalizedPatch = { ...data2 }; - if (data2.permissions !== void 0) { - const role = data2.role ?? existing.role; - normalizedPatch.permissions = normalizeAgentPermissions(data2.permissions, role); - } - const shouldRecordRevision = Boolean(options?.recordRevision) && hasConfigPatchFields(normalizedPatch); - const beforeConfig = shouldRecordRevision ? buildConfigSnapshot(existing) : null; - const updated = await db.update(agents).set({ ...normalizedPatch, updatedAt: /* @__PURE__ */ new Date() }).where(eq(agents.id, id)).returning().then((rows) => rows[0] ?? null); - const normalizedUpdated = updated ? normalizeAgentRow(updated) : null; - if (normalizedUpdated && shouldRecordRevision && beforeConfig) { - const afterConfig = buildConfigSnapshot(normalizedUpdated); - const changedKeys = diffConfigSnapshot(beforeConfig, afterConfig); - if (changedKeys.length > 0) { - await db.insert(agentConfigRevisions).values({ - companyId: normalizedUpdated.companyId, - agentId: normalizedUpdated.id, - createdByAgentId: options?.recordRevision?.createdByAgentId ?? null, - createdByUserId: options?.recordRevision?.createdByUserId ?? null, - source: options?.recordRevision?.source ?? "patch", - rolledBackFromRevisionId: options?.recordRevision?.rolledBackFromRevisionId ?? null, - changedKeys, - beforeConfig, - afterConfig - }); - } - } - return normalizedUpdated; - } - return { - list: async (companyId, options) => { - const conditions = [eq(agents.companyId, companyId)]; - if (!options?.includeTerminated) { - conditions.push(ne(agents.status, "terminated")); - } - const rows = await db.select().from(agents).where(and(...conditions)); - const hydrated = await hydrateAgentSpend(rows); - return hydrated.map(normalizeAgentRow); - }, - getById, - create: async (companyId, data2) => { - if (data2.reportsTo) { - await ensureManager(companyId, data2.reportsTo); - } - const existingAgents = await db.select({ id: agents.id, name: agents.name, status: agents.status }).from(agents).where(eq(agents.companyId, companyId)); - const uniqueName = deduplicateAgentName(data2.name, existingAgents); - const role = data2.role ?? "general"; - const normalizedPermissions = normalizeAgentPermissions(data2.permissions, role); - const created = await db.insert(agents).values({ ...data2, name: uniqueName, companyId, role, permissions: normalizedPermissions }).returning().then((rows) => rows[0]); - return normalizeAgentRow(created); - }, - update: updateAgent, - pause: async (id, reason = "manual") => { - const existing = await getById(id); - if (!existing) return null; - if (existing.status === "terminated") throw conflict("Cannot pause terminated agent"); - const updated = await db.update(agents).set({ - status: "paused", - pauseReason: reason, - pausedAt: /* @__PURE__ */ new Date(), - updatedAt: /* @__PURE__ */ new Date() - }).where(eq(agents.id, id)).returning().then((rows) => rows[0] ?? null); - return updated ? normalizeAgentRow(updated) : null; - }, - resume: async (id) => { - const existing = await getById(id); - if (!existing) return null; - if (existing.status === "terminated") throw conflict("Cannot resume terminated agent"); - if (existing.status === "pending_approval") { - throw conflict("Pending approval agents cannot be resumed"); - } - const updated = await db.update(agents).set({ - status: "idle", - pauseReason: null, - pausedAt: null, - updatedAt: /* @__PURE__ */ new Date() - }).where(eq(agents.id, id)).returning().then((rows) => rows[0] ?? null); - return updated ? normalizeAgentRow(updated) : null; - }, - terminate: async (id) => { - const existing = await getById(id); - if (!existing) return null; - await db.update(agents).set({ - status: "terminated", - pauseReason: null, - pausedAt: null, - updatedAt: /* @__PURE__ */ new Date() - }).where(eq(agents.id, id)); - await db.update(agentApiKeys).set({ revokedAt: /* @__PURE__ */ new Date() }).where(eq(agentApiKeys.agentId, id)); - return getById(id); - }, - remove: async (id) => { - const existing = await getById(id); - if (!existing) return null; - return db.transaction(async (tx) => { - await tx.update(agents).set({ reportsTo: null }).where(eq(agents.reportsTo, id)); - await tx.update(issues).set({ assigneeAgentId: null, createdByAgentId: null }).where(or(eq(issues.assigneeAgentId, id), eq(issues.createdByAgentId, id))); - await tx.delete(heartbeatRunEvents).where(eq(heartbeatRunEvents.agentId, id)); - await tx.delete(agentTaskSessions).where(eq(agentTaskSessions.agentId, id)); - await tx.delete(activityLog).where( - or( - eq(activityLog.agentId, id), - sql`${activityLog.runId} in (select ${heartbeatRuns.id} from ${heartbeatRuns} where ${heartbeatRuns.agentId} = ${id})` - ) - ); - await tx.delete(issueExecutionDecisions).where(eq(issueExecutionDecisions.actorAgentId, id)); - await tx.delete(issueComments).where(eq(issueComments.authorAgentId, id)); - await tx.delete(heartbeatRuns).where(eq(heartbeatRuns.agentId, id)); - await tx.delete(agentWakeupRequests).where(eq(agentWakeupRequests.agentId, id)); - await tx.delete(agentApiKeys).where(eq(agentApiKeys.agentId, id)); - await tx.delete(agentRuntimeState).where(eq(agentRuntimeState.agentId, id)); - const deleted = await tx.delete(agents).where(eq(agents.id, id)).returning().then((rows) => rows[0] ?? null); - return deleted ? normalizeAgentRow(deleted) : null; - }); - }, - activatePendingApproval: async (id) => { - const existing = await getById(id); - if (!existing) return null; - if (existing.status !== "pending_approval") return existing; - const updated = await db.update(agents).set({ status: "idle", updatedAt: /* @__PURE__ */ new Date() }).where(eq(agents.id, id)).returning().then((rows) => rows[0] ?? null); - return updated ? normalizeAgentRow(updated) : null; - }, - updatePermissions: async (id, permissions) => { - const existing = await getById(id); - if (!existing) return null; - const updated = await db.update(agents).set({ - permissions: normalizeAgentPermissions(permissions, existing.role), - updatedAt: /* @__PURE__ */ new Date() - }).where(eq(agents.id, id)).returning().then((rows) => rows[0] ?? null); - return updated ? normalizeAgentRow(updated) : null; - }, - listConfigRevisions: async (id) => db.select().from(agentConfigRevisions).where(eq(agentConfigRevisions.agentId, id)).orderBy(desc(agentConfigRevisions.createdAt)), - getConfigRevision: async (id, revisionId) => db.select().from(agentConfigRevisions).where(and(eq(agentConfigRevisions.agentId, id), eq(agentConfigRevisions.id, revisionId))).then((rows) => rows[0] ?? null), - rollbackConfigRevision: async (id, revisionId, actor) => { - const revision = await db.select().from(agentConfigRevisions).where(and(eq(agentConfigRevisions.agentId, id), eq(agentConfigRevisions.id, revisionId))).then((rows) => rows[0] ?? null); - if (!revision) return null; - if (containsRedactedMarker(revision.afterConfig)) { - throw unprocessable("Cannot roll back a revision that contains redacted secret values"); - } - const patch = configPatchFromSnapshot(revision.afterConfig); - return updateAgent(id, patch, { - recordRevision: { - createdByAgentId: actor.agentId ?? null, - createdByUserId: actor.userId ?? null, - source: "rollback", - rolledBackFromRevisionId: revision.id - } - }); - }, - createApiKey: async (id, name) => { - const existing = await getById(id); - if (!existing) throw notFound("Agent not found"); - if (existing.status === "pending_approval") { - throw conflict("Cannot create keys for pending approval agents"); - } - if (existing.status === "terminated") { - throw conflict("Cannot create keys for terminated agents"); - } - const token = createToken(); - const keyHash = hashToken2(token); - const created = await db.insert(agentApiKeys).values({ - agentId: id, - companyId: existing.companyId, - name, - keyHash - }).returning().then((rows) => rows[0]); - return { - id: created.id, - name: created.name, - token, - createdAt: created.createdAt - }; - }, - listKeys: (id) => db.select({ - id: agentApiKeys.id, - name: agentApiKeys.name, - createdAt: agentApiKeys.createdAt, - revokedAt: agentApiKeys.revokedAt - }).from(agentApiKeys).where(eq(agentApiKeys.agentId, id)), - revokeKey: async (keyId) => { - const rows = await db.update(agentApiKeys).set({ revokedAt: /* @__PURE__ */ new Date() }).where(eq(agentApiKeys.id, keyId)).returning(); - return rows[0] ?? null; - }, - orgForCompany: async (companyId) => { - const rows = await db.select().from(agents).where(and(eq(agents.companyId, companyId), ne(agents.status, "terminated"))); - const normalizedRows = rows.map(normalizeAgentRow); - const byManager = /* @__PURE__ */ new Map(); - for (const row of normalizedRows) { - const key = row.reportsTo ?? null; - const group = byManager.get(key) ?? []; - group.push(row); - byManager.set(key, group); - } - const build = (managerId) => { - const members = byManager.get(managerId) ?? []; - return members.map((member2) => ({ - ...member2, - reports: build(member2.id) - })); - }; - return build(null); - }, - getChainOfCommand: async (agentId) => { - const chain = []; - const visited = /* @__PURE__ */ new Set([agentId]); - const start = await getById(agentId); - let currentId = start?.reportsTo ?? null; - while (currentId && !visited.has(currentId) && chain.length < 50) { - visited.add(currentId); - const mgr = await getById(currentId); - if (!mgr) break; - chain.push({ id: mgr.id, name: mgr.name, role: mgr.role, title: mgr.title ?? null }); - currentId = mgr.reportsTo ?? null; - } - return chain; - }, - runningForAgent: (agentId) => db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.agentId, agentId), inArray(heartbeatRuns.status, ["queued", "running"]))), - resolveByReference: async (companyId, reference) => { - const raw = reference.trim(); - if (raw.length === 0) { - return { agent: null, ambiguous: false }; - } - if (isUuidLike(raw)) { - const byId = await getById(raw); - if (!byId || byId.companyId !== companyId) { - return { agent: null, ambiguous: false }; - } - return { agent: byId, ambiguous: false }; - } - const urlKey = normalizeAgentUrlKey(raw); - if (!urlKey) { - return { agent: null, ambiguous: false }; - } - const rows = await db.select().from(agents).where(eq(agents.companyId, companyId)); - const matches = rows.map(normalizeAgentRow).filter((agent) => agent.urlKey === urlKey && agent.status !== "terminated"); - if (matches.length === 1) { - return { agent: matches[0] ?? null, ambiguous: false }; - } - if (matches.length > 1) { - return { agent: null, ambiguous: true }; - } - return { agent: null, ambiguous: false }; - } - }; -} - -// server/src/services/projects.ts -init_drizzle_orm(); -init_src2(); - -// server/src/services/workspace-runtime-read-model.ts -init_src2(); -init_drizzle_orm(); -function runtimeServiceIdentityKey(row) { - if (row.reuseKey) return row.reuseKey; - return [ - row.scopeType, - row.scopeId ?? "", - row.projectWorkspaceId ?? "", - row.executionWorkspaceId ?? "", - row.serviceName, - row.command ?? "", - row.cwd ?? "" - ].join(":"); -} -function selectCurrentRuntimeServiceRows(rows) { - const current = /* @__PURE__ */ new Map(); - for (const row of rows) { - const identity = runtimeServiceIdentityKey(row); - if (!current.has(identity)) current.set(identity, row); - } - return [...current.values()]; -} -async function listCurrentRuntimeServicesForProjectWorkspaces(db, companyId, projectWorkspaceIds) { - if (projectWorkspaceIds.length === 0) return /* @__PURE__ */ new Map(); - const rows = await db.select().from(workspaceRuntimeServices).where( - and( - eq(workspaceRuntimeServices.companyId, companyId), - inArray(workspaceRuntimeServices.projectWorkspaceId, projectWorkspaceIds), - eq(workspaceRuntimeServices.scopeType, "project_workspace") - ) - ).orderBy(desc(workspaceRuntimeServices.updatedAt), desc(workspaceRuntimeServices.createdAt)); - const grouped = /* @__PURE__ */ new Map(); - for (const row of rows) { - if (!row.projectWorkspaceId) continue; - const existing = grouped.get(row.projectWorkspaceId) ?? []; - existing.push(row); - grouped.set(row.projectWorkspaceId, existing); - } - return new Map( - Array.from(grouped.entries()).map(([workspaceId, workspaceRows]) => [ - workspaceId, - selectCurrentRuntimeServiceRows(workspaceRows) - ]) - ); -} -async function listCurrentRuntimeServicesForExecutionWorkspaces(db, companyId, executionWorkspaceIds) { - if (executionWorkspaceIds.length === 0) return /* @__PURE__ */ new Map(); - const rows = await db.select().from(workspaceRuntimeServices).where( - and( - eq(workspaceRuntimeServices.companyId, companyId), - inArray(workspaceRuntimeServices.executionWorkspaceId, executionWorkspaceIds) - ) - ).orderBy(desc(workspaceRuntimeServices.updatedAt), desc(workspaceRuntimeServices.createdAt)); - const grouped = /* @__PURE__ */ new Map(); - for (const row of rows) { - if (!row.executionWorkspaceId) continue; - const existing = grouped.get(row.executionWorkspaceId) ?? []; - existing.push(row); - grouped.set(row.executionWorkspaceId, existing); - } - return new Map( - Array.from(grouped.entries()).map(([workspaceId, workspaceRows]) => [ - workspaceId, - selectCurrentRuntimeServiceRows(workspaceRows) - ]) - ); -} - -// server/src/services/execution-workspace-policy.ts -function cloneRecord(value) { - if (!value) return null; - return { ...value }; -} -function parseExecutionWorkspaceStrategy(raw) { - const parsed = parseObject4(raw); - const type = asString12(parsed.type, ""); - if (type !== "project_primary" && type !== "git_worktree" && type !== "adapter_managed" && type !== "cloud_sandbox") { - return null; - } - return { - type, - ...typeof parsed.baseRef === "string" ? { baseRef: parsed.baseRef } : {}, - ...typeof parsed.branchTemplate === "string" ? { branchTemplate: parsed.branchTemplate } : {}, - ...typeof parsed.worktreeParentDir === "string" ? { worktreeParentDir: parsed.worktreeParentDir } : {}, - ...typeof parsed.provisionCommand === "string" ? { provisionCommand: parsed.provisionCommand } : {}, - ...typeof parsed.teardownCommand === "string" ? { teardownCommand: parsed.teardownCommand } : {} - }; -} -function parseProjectExecutionWorkspacePolicy(raw) { - const parsed = parseObject4(raw); - if (Object.keys(parsed).length === 0) return null; - const enabled = typeof parsed.enabled === "boolean" ? parsed.enabled : false; - const workspaceStrategy = parseExecutionWorkspaceStrategy(parsed.workspaceStrategy); - const defaultMode = asString12(parsed.defaultMode, ""); - const defaultProjectWorkspaceId = typeof parsed.defaultProjectWorkspaceId === "string" ? parsed.defaultProjectWorkspaceId : void 0; - const allowIssueOverride = typeof parsed.allowIssueOverride === "boolean" ? parsed.allowIssueOverride : void 0; - const normalizedDefaultMode = (() => { - if (defaultMode === "shared_workspace" || defaultMode === "isolated_workspace" || defaultMode === "operator_branch" || defaultMode === "adapter_default") { - return defaultMode; - } - if (defaultMode === "project_primary") return "shared_workspace"; - if (defaultMode === "isolated") return "isolated_workspace"; - return void 0; - })(); - return { - enabled, - ...normalizedDefaultMode ? { defaultMode: normalizedDefaultMode } : {}, - ...allowIssueOverride !== void 0 ? { allowIssueOverride } : {}, - ...defaultProjectWorkspaceId ? { defaultProjectWorkspaceId } : {}, - ...workspaceStrategy ? { workspaceStrategy } : {}, - ...parsed.workspaceRuntime && typeof parsed.workspaceRuntime === "object" && !Array.isArray(parsed.workspaceRuntime) ? { workspaceRuntime: { ...parsed.workspaceRuntime } } : {}, - ...parsed.branchPolicy && typeof parsed.branchPolicy === "object" && !Array.isArray(parsed.branchPolicy) ? { branchPolicy: { ...parsed.branchPolicy } } : {}, - ...parsed.pullRequestPolicy && typeof parsed.pullRequestPolicy === "object" && !Array.isArray(parsed.pullRequestPolicy) ? { pullRequestPolicy: { ...parsed.pullRequestPolicy } } : {}, - ...parsed.runtimePolicy && typeof parsed.runtimePolicy === "object" && !Array.isArray(parsed.runtimePolicy) ? { runtimePolicy: { ...parsed.runtimePolicy } } : {}, - ...parsed.cleanupPolicy && typeof parsed.cleanupPolicy === "object" && !Array.isArray(parsed.cleanupPolicy) ? { cleanupPolicy: { ...parsed.cleanupPolicy } } : {} - }; -} -function gateProjectExecutionWorkspacePolicy(projectPolicy, isolatedWorkspacesEnabled) { - if (!isolatedWorkspacesEnabled) return null; - return projectPolicy; -} -function parseIssueExecutionWorkspaceSettings(raw) { - const parsed = parseObject4(raw); - if (Object.keys(parsed).length === 0) return null; - const workspaceStrategy = parseExecutionWorkspaceStrategy(parsed.workspaceStrategy); - const mode = asString12(parsed.mode, ""); - const normalizedMode = (() => { - if (mode === "inherit" || mode === "shared_workspace" || mode === "isolated_workspace" || mode === "operator_branch" || mode === "reuse_existing" || mode === "agent_default") { - return mode; - } - if (mode === "project_primary") return "shared_workspace"; - if (mode === "isolated") return "isolated_workspace"; - return ""; - })(); - return { - ...normalizedMode ? { mode: normalizedMode } : {}, - ...workspaceStrategy ? { workspaceStrategy } : {}, - ...parsed.workspaceRuntime && typeof parsed.workspaceRuntime === "object" && !Array.isArray(parsed.workspaceRuntime) ? { workspaceRuntime: { ...parsed.workspaceRuntime } } : {} - }; -} -function defaultIssueExecutionWorkspaceSettingsForProject(projectPolicy) { - if (!projectPolicy?.enabled) return null; - return { - mode: projectPolicy.defaultMode === "isolated_workspace" ? "isolated_workspace" : projectPolicy.defaultMode === "operator_branch" ? "operator_branch" : projectPolicy.defaultMode === "adapter_default" ? "agent_default" : "shared_workspace" - }; -} -function issueExecutionWorkspaceModeForPersistedWorkspace(mode) { - if (mode === null || mode === void 0) { - return "agent_default"; - } - if (mode === "isolated_workspace" || mode === "operator_branch" || mode === "shared_workspace") { - return mode; - } - if (mode === "adapter_managed" || mode === "cloud_sandbox") { - return "agent_default"; - } - return "shared_workspace"; -} -function resolveExecutionWorkspaceMode(input) { - const issueMode = input.issueSettings?.mode; - if (issueMode && issueMode !== "inherit" && issueMode !== "reuse_existing") { - return issueMode; - } - if (input.projectPolicy?.enabled) { - if (input.projectPolicy.defaultMode === "isolated_workspace") return "isolated_workspace"; - if (input.projectPolicy.defaultMode === "operator_branch") return "operator_branch"; - if (input.projectPolicy.defaultMode === "adapter_default") return "agent_default"; - return "shared_workspace"; - } - if (input.legacyUseProjectWorkspace === false) { - return "agent_default"; - } - return "shared_workspace"; -} -function buildExecutionWorkspaceAdapterConfig(input) { - const nextConfig = { ...input.agentConfig }; - const projectHasPolicy = Boolean(input.projectPolicy?.enabled); - const issueHasWorkspaceOverrides = Boolean( - input.issueSettings?.mode || input.issueSettings?.workspaceStrategy || input.issueSettings?.workspaceRuntime - ); - const hasWorkspaceControl = projectHasPolicy || issueHasWorkspaceOverrides || input.legacyUseProjectWorkspace === false; - if (hasWorkspaceControl) { - if (input.mode === "isolated_workspace") { - const strategy = input.issueSettings?.workspaceStrategy ?? input.projectPolicy?.workspaceStrategy ?? parseExecutionWorkspaceStrategy(nextConfig.workspaceStrategy) ?? { type: "git_worktree" }; - nextConfig.workspaceStrategy = strategy; - } else { - delete nextConfig.workspaceStrategy; - } - if (input.mode === "agent_default") { - delete nextConfig.workspaceRuntime; - } else if (input.issueSettings?.workspaceRuntime) { - nextConfig.workspaceRuntime = cloneRecord(input.issueSettings.workspaceRuntime) ?? void 0; - } else if (input.projectPolicy?.workspaceRuntime) { - nextConfig.workspaceRuntime = cloneRecord(input.projectPolicy.workspaceRuntime) ?? void 0; - } - } - return nextConfig; -} - -// server/src/services/project-workspace-runtime-config.ts -function isRecord3(value) { - return typeof value === "object" && value !== null && !Array.isArray(value); -} -function cloneRecord2(value) { - return isRecord3(value) ? { ...value } : null; -} -function readDesiredState(value) { - return value === "running" || value === "stopped" ? value : null; -} -function readServiceStates(value) { - if (!isRecord3(value)) return null; - const entries2 = Object.entries(value).filter(([, state2]) => state2 === "running" || state2 === "stopped"); - if (entries2.length === 0) return null; - return Object.fromEntries(entries2); -} -function readProjectWorkspaceRuntimeConfig(metadata) { - const raw = isRecord3(metadata?.runtimeConfig) ? metadata.runtimeConfig : null; - if (!raw) return null; - const config3 = { - workspaceRuntime: cloneRecord2(raw.workspaceRuntime), - desiredState: readDesiredState(raw.desiredState), - serviceStates: readServiceStates(raw.serviceStates) - }; - const hasConfig = config3.workspaceRuntime !== null || config3.desiredState !== null || config3.serviceStates !== null; - return hasConfig ? config3 : null; -} -function mergeProjectWorkspaceRuntimeConfig(metadata, patch) { - const nextMetadata = isRecord3(metadata) ? { ...metadata } : {}; - const current = readProjectWorkspaceRuntimeConfig(metadata) ?? { - workspaceRuntime: null, - desiredState: null, - serviceStates: null - }; - if (patch === null) { - delete nextMetadata.runtimeConfig; - return Object.keys(nextMetadata).length > 0 ? nextMetadata : null; - } - const nextConfig = { - workspaceRuntime: patch.workspaceRuntime !== void 0 ? cloneRecord2(patch.workspaceRuntime) : current.workspaceRuntime, - desiredState: patch.desiredState !== void 0 ? readDesiredState(patch.desiredState) : current.desiredState, - serviceStates: patch.serviceStates !== void 0 ? readServiceStates(patch.serviceStates) : current.serviceStates - }; - if (nextConfig.workspaceRuntime === null && nextConfig.desiredState === null && nextConfig.serviceStates === null) { - delete nextMetadata.runtimeConfig; - } else { - nextMetadata.runtimeConfig = nextConfig; - } - return Object.keys(nextMetadata).length > 0 ? nextMetadata : null; -} - -// server/src/services/projects.ts -var REPO_ONLY_CWD_SENTINEL = "/__taskcore_repo_only__"; -async function attachGoals(db, rows) { - if (rows.length === 0) return []; - const projectIds = rows.map((r5) => r5.id); - const links = await db.select({ - projectId: projectGoals.projectId, - goalId: projectGoals.goalId, - goalTitle: goals.title - }).from(projectGoals).innerJoin(goals, eq(projectGoals.goalId, goals.id)).where(inArray(projectGoals.projectId, projectIds)); - const map4 = /* @__PURE__ */ new Map(); - for (const link of links) { - let arr = map4.get(link.projectId); - if (!arr) { - arr = []; - map4.set(link.projectId, arr); - } - arr.push({ id: link.goalId, title: link.goalTitle }); - } - return rows.map((r5) => { - const g5 = map4.get(r5.id) ?? []; - return { - ...r5, - urlKey: deriveProjectUrlKey(r5.name, r5.id), - goalIds: g5.map((x5) => x5.id), - goals: g5, - executionWorkspacePolicy: parseProjectExecutionWorkspacePolicy(r5.executionWorkspacePolicy) - }; - }); -} -function toRuntimeService(row) { - return { - id: row.id, - companyId: row.companyId, - projectId: row.projectId ?? null, - projectWorkspaceId: row.projectWorkspaceId ?? null, - executionWorkspaceId: row.executionWorkspaceId ?? null, - issueId: row.issueId ?? null, - scopeType: row.scopeType, - scopeId: row.scopeId ?? null, - serviceName: row.serviceName, - status: row.status, - lifecycle: row.lifecycle, - reuseKey: row.reuseKey ?? null, - command: row.command ?? null, - cwd: row.cwd ?? null, - port: row.port ?? null, - url: row.url ?? null, - provider: row.provider, - providerRef: row.providerRef ?? null, - ownerAgentId: row.ownerAgentId ?? null, - startedByRunId: row.startedByRunId ?? null, - lastUsedAt: row.lastUsedAt, - startedAt: row.startedAt, - stoppedAt: row.stoppedAt ?? null, - stopPolicy: row.stopPolicy ?? null, - healthStatus: row.healthStatus, - createdAt: row.createdAt, - updatedAt: row.updatedAt - }; -} -function toWorkspace(row, runtimeServices = []) { - return { - id: row.id, - companyId: row.companyId, - projectId: row.projectId, - name: row.name, - sourceType: row.sourceType, - cwd: normalizeWorkspaceCwd(row.cwd), - repoUrl: row.repoUrl ?? null, - repoRef: row.repoRef ?? null, - defaultRef: row.defaultRef ?? row.repoRef ?? null, - visibility: row.visibility, - setupCommand: row.setupCommand ?? null, - cleanupCommand: row.cleanupCommand ?? null, - remoteProvider: row.remoteProvider ?? null, - remoteWorkspaceRef: row.remoteWorkspaceRef ?? null, - sharedWorkspaceKey: row.sharedWorkspaceKey ?? null, - metadata: row.metadata ?? null, - runtimeConfig: readProjectWorkspaceRuntimeConfig(row.metadata ?? null), - isPrimary: row.isPrimary, - runtimeServices, - createdAt: row.createdAt, - updatedAt: row.updatedAt - }; -} -function deriveRepoNameFromRepoUrl(repoUrl) { - const raw = readNonEmptyString9(repoUrl); - if (!raw) return null; - try { - const parsed = new URL(raw); - const cleanedPath = parsed.pathname.replace(/\/+$/, ""); - const repoName = cleanedPath.split("/").filter(Boolean).pop()?.replace(/\.git$/i, "") ?? ""; - return repoName || null; - } catch { - return null; - } -} -function deriveProjectCodebase(input) { - const primaryWorkspace = input.primaryWorkspace ?? input.fallbackWorkspaces[0] ?? null; - const repoUrl = primaryWorkspace?.repoUrl ?? null; - const repoName = deriveRepoNameFromRepoUrl(repoUrl); - const localFolder = primaryWorkspace?.cwd ?? null; - const managedFolder = resolveManagedProjectWorkspaceDir({ - companyId: input.companyId, - projectId: input.projectId, - repoName - }); - return { - workspaceId: primaryWorkspace?.id ?? null, - repoUrl, - repoRef: primaryWorkspace?.repoRef ?? null, - defaultRef: primaryWorkspace?.defaultRef ?? null, - repoName, - localFolder, - managedFolder, - effectiveLocalFolder: localFolder ?? managedFolder, - origin: localFolder ? "local_folder" : "managed_checkout" - }; -} -function pickPrimaryWorkspace(rows, runtimeServicesByWorkspaceId) { - if (rows.length === 0) return null; - const explicitPrimary = rows.find((row) => row.isPrimary); - const primary = explicitPrimary ?? rows[0]; - return toWorkspace(primary, runtimeServicesByWorkspaceId?.get(primary.id) ?? []); -} -async function attachWorkspaces(db, rows) { - if (rows.length === 0) return []; - const projectIds = rows.map((r5) => r5.id); - const workspaceRows = await db.select().from(projectWorkspaces).where(inArray(projectWorkspaces.projectId, projectIds)).orderBy(desc(projectWorkspaces.isPrimary), asc(projectWorkspaces.createdAt), asc(projectWorkspaces.id)); - const runtimeServicesByWorkspaceId = await listCurrentRuntimeServicesForProjectWorkspaces( - db, - rows[0].companyId, - workspaceRows.map((workspace) => workspace.id) - ); - const sharedRuntimeServicesByWorkspaceId = new Map( - Array.from(runtimeServicesByWorkspaceId.entries()).map(([workspaceId, services]) => [ - workspaceId, - services.map(toRuntimeService) - ]) - ); - const map4 = /* @__PURE__ */ new Map(); - for (const row of workspaceRows) { - let arr = map4.get(row.projectId); - if (!arr) { - arr = []; - map4.set(row.projectId, arr); - } - arr.push(row); - } - return rows.map((row) => { - const projectWorkspaceRows = map4.get(row.id) ?? []; - const workspaces = projectWorkspaceRows.map( - (workspace) => toWorkspace( - workspace, - sharedRuntimeServicesByWorkspaceId.get(workspace.id) ?? [] - ) - ); - const primaryWorkspace = pickPrimaryWorkspace(projectWorkspaceRows, sharedRuntimeServicesByWorkspaceId); - return { - ...row, - codebase: deriveProjectCodebase({ - companyId: row.companyId, - projectId: row.id, - primaryWorkspace, - fallbackWorkspaces: workspaces - }), - workspaces, - primaryWorkspace - }; - }); -} -async function syncGoalLinks(db, projectId, companyId, goalIds) { - await db.delete(projectGoals).where(eq(projectGoals.projectId, projectId)); - if (goalIds.length > 0) { - await db.insert(projectGoals).values( - goalIds.map((goalId) => ({ projectId, goalId, companyId })) - ); - } -} -function resolveGoalIds(data2) { - if (data2.goalIds !== void 0) return data2.goalIds; - if (data2.goalId !== void 0) { - return data2.goalId ? [data2.goalId] : []; - } - return void 0; -} -function readNonEmptyString9(value) { - if (typeof value !== "string") return null; - const trimmed = value.trim(); - return trimmed.length > 0 ? trimmed : null; -} -function normalizeWorkspaceCwd(value) { - const cwd = readNonEmptyString9(value); - if (!cwd) return null; - return cwd === REPO_ONLY_CWD_SENTINEL ? null : cwd; -} -function deriveNameFromCwd(cwd) { - const normalized = cwd.replace(/[\\/]+$/, ""); - const segments = normalized.split(/[\\/]/).filter(Boolean); - return segments[segments.length - 1] ?? "Local folder"; -} -function deriveNameFromRepoUrl(repoUrl) { - try { - const url2 = new URL(repoUrl); - const cleanedPath = url2.pathname.replace(/\/+$/, ""); - const lastSegment = cleanedPath.split("/").filter(Boolean).pop() ?? ""; - const noGitSuffix = lastSegment.replace(/\.git$/i, ""); - return noGitSuffix || repoUrl; - } catch { - return repoUrl; - } -} -function deriveWorkspaceName(input) { - const explicit = readNonEmptyString9(input.name); - if (explicit) return explicit; - const cwd = readNonEmptyString9(input.cwd); - if (cwd) return deriveNameFromCwd(cwd); - const repoUrl = readNonEmptyString9(input.repoUrl); - if (repoUrl) return deriveNameFromRepoUrl(repoUrl); - return "Workspace"; -} -function resolveProjectNameForUniqueShortname(requestedName, existingProjects, options) { - const requestedShortname = normalizeProjectUrlKey(requestedName); - if (!requestedShortname) return requestedName; - if (hasNonAsciiContent(requestedName)) return requestedName; - const usedShortnames = new Set( - existingProjects.filter((project) => !(options?.excludeProjectId && project.id === options.excludeProjectId)).map((project) => normalizeProjectUrlKey(project.name)).filter((value) => value !== null) - ); - if (!usedShortnames.has(requestedShortname)) return requestedName; - for (let suffix = 2; suffix < 1e4; suffix += 1) { - const candidateName = `${requestedName} ${suffix}`; - const candidateShortname = normalizeProjectUrlKey(candidateName); - if (candidateShortname && !usedShortnames.has(candidateShortname)) { - return candidateName; - } - } - return `${requestedName} ${Date.now()}`; -} -async function ensureSinglePrimaryWorkspace(dbOrTx, input) { - await dbOrTx.update(projectWorkspaces).set({ isPrimary: false, updatedAt: /* @__PURE__ */ new Date() }).where( - and( - eq(projectWorkspaces.companyId, input.companyId), - eq(projectWorkspaces.projectId, input.projectId) - ) - ); - await dbOrTx.update(projectWorkspaces).set({ isPrimary: true, updatedAt: /* @__PURE__ */ new Date() }).where( - and( - eq(projectWorkspaces.companyId, input.companyId), - eq(projectWorkspaces.projectId, input.projectId), - eq(projectWorkspaces.id, input.keepWorkspaceId) - ) - ); -} -function projectService(db) { - return { - list: async (companyId) => { - const rows = await db.select().from(projects).where(eq(projects.companyId, companyId)); - const withGoals = await attachGoals(db, rows); - return attachWorkspaces(db, withGoals); - }, - listByIds: async (companyId, ids) => { - const dedupedIds = [...new Set(ids)]; - if (dedupedIds.length === 0) return []; - const rows = await db.select().from(projects).where(and(eq(projects.companyId, companyId), inArray(projects.id, dedupedIds))); - const withGoals = await attachGoals(db, rows); - const withWorkspaces = await attachWorkspaces(db, withGoals); - const byId = new Map(withWorkspaces.map((project) => [project.id, project])); - return dedupedIds.map((id) => byId.get(id)).filter((project) => Boolean(project)); - }, - getById: async (id) => { - const row = await db.select().from(projects).where(eq(projects.id, id)).then((rows) => rows[0] ?? null); - if (!row) return null; - const [withGoals] = await attachGoals(db, [row]); - if (!withGoals) return null; - const [enriched] = await attachWorkspaces(db, [withGoals]); - return enriched ?? null; - }, - create: async (companyId, data2) => { - const { goalIds: inputGoalIds, ...projectData } = data2; - const ids = resolveGoalIds({ goalIds: inputGoalIds, goalId: projectData.goalId }); - if (!projectData.color) { - const existing = await db.select({ color: projects.color }).from(projects).where(eq(projects.companyId, companyId)); - const usedColors = new Set(existing.map((r5) => r5.color).filter(Boolean)); - const nextColor = PROJECT_COLORS.find((c5) => !usedColors.has(c5)) ?? PROJECT_COLORS[existing.length % PROJECT_COLORS.length]; - projectData.color = nextColor; - } - const existingProjects = await db.select({ id: projects.id, name: projects.name }).from(projects).where(eq(projects.companyId, companyId)); - projectData.name = resolveProjectNameForUniqueShortname(projectData.name, existingProjects); - const legacyGoalId = ids && ids.length > 0 ? ids[0] : projectData.goalId ?? null; - const row = await db.insert(projects).values({ ...projectData, goalId: legacyGoalId, companyId }).returning().then((rows) => rows[0]); - if (ids && ids.length > 0) { - await syncGoalLinks(db, row.id, companyId, ids); - } - const [withGoals] = await attachGoals(db, [row]); - const [enriched] = withGoals ? await attachWorkspaces(db, [withGoals]) : []; - return enriched; - }, - update: async (id, data2) => { - const { goalIds: inputGoalIds, ...projectData } = data2; - const ids = resolveGoalIds({ goalIds: inputGoalIds, goalId: projectData.goalId }); - const existingProject = await db.select({ id: projects.id, companyId: projects.companyId, name: projects.name }).from(projects).where(eq(projects.id, id)).then((rows) => rows[0] ?? null); - if (!existingProject) return null; - if (projectData.name !== void 0) { - const existingShortname = normalizeProjectUrlKey(existingProject.name); - const nextShortname = normalizeProjectUrlKey(projectData.name); - if (existingShortname !== nextShortname) { - const existingProjects = await db.select({ id: projects.id, name: projects.name }).from(projects).where(eq(projects.companyId, existingProject.companyId)); - projectData.name = resolveProjectNameForUniqueShortname(projectData.name, existingProjects, { - excludeProjectId: id - }); - } - } - const updates = { - ...projectData, - updatedAt: /* @__PURE__ */ new Date() - }; - if (ids !== void 0) { - updates.goalId = ids.length > 0 ? ids[0] : null; - } - const row = await db.update(projects).set(updates).where(eq(projects.id, id)).returning().then((rows) => rows[0] ?? null); - if (!row) return null; - if (ids !== void 0) { - await syncGoalLinks(db, id, row.companyId, ids); - } - const [withGoals] = await attachGoals(db, [row]); - const [enriched] = withGoals ? await attachWorkspaces(db, [withGoals]) : []; - return enriched ?? null; - }, - remove: (id) => db.delete(projects).where(eq(projects.id, id)).returning().then((rows) => { - const row = rows[0] ?? null; - if (!row) return null; - return { ...row, urlKey: deriveProjectUrlKey(row.name, row.id) }; - }), - listWorkspaces: async (projectId) => { - const rows = await db.select().from(projectWorkspaces).where(eq(projectWorkspaces.projectId, projectId)).orderBy(desc(projectWorkspaces.isPrimary), asc(projectWorkspaces.createdAt), asc(projectWorkspaces.id)); - if (rows.length === 0) return []; - const runtimeServicesByWorkspaceId = await listCurrentRuntimeServicesForProjectWorkspaces( - db, - rows[0].companyId, - rows.map((workspace) => workspace.id) - ); - return rows.map( - (row) => toWorkspace( - row, - (runtimeServicesByWorkspaceId.get(row.id) ?? []).map(toRuntimeService) - ) - ); - }, - createWorkspace: async (projectId, data2) => { - const project = await db.select().from(projects).where(eq(projects.id, projectId)).then((rows) => rows[0] ?? null); - if (!project) return null; - const cwd = normalizeWorkspaceCwd(data2.cwd); - const repoUrl = readNonEmptyString9(data2.repoUrl); - const sourceType = readNonEmptyString9(data2.sourceType) ?? (repoUrl ? "git_repo" : cwd ? "local_path" : "remote_managed"); - const remoteWorkspaceRef = readNonEmptyString9(data2.remoteWorkspaceRef); - if (sourceType === "remote_managed") { - if (!remoteWorkspaceRef && !repoUrl) return null; - } else if (!cwd && !repoUrl) { - return null; - } - const name = deriveWorkspaceName({ - name: data2.name, - cwd, - repoUrl - }); - const existing = await db.select().from(projectWorkspaces).where(eq(projectWorkspaces.projectId, projectId)).orderBy(asc(projectWorkspaces.createdAt)).then((rows) => rows); - const shouldBePrimary = data2.isPrimary === true || existing.length === 0; - const created = await db.transaction(async (tx) => { - if (shouldBePrimary) { - await tx.update(projectWorkspaces).set({ isPrimary: false, updatedAt: /* @__PURE__ */ new Date() }).where( - and( - eq(projectWorkspaces.companyId, project.companyId), - eq(projectWorkspaces.projectId, projectId) - ) - ); - } - const row = await tx.insert(projectWorkspaces).values({ - companyId: project.companyId, - projectId, - name, - sourceType, - cwd: cwd ?? null, - repoUrl: repoUrl ?? null, - repoRef: readNonEmptyString9(data2.repoRef), - defaultRef: readNonEmptyString9(data2.defaultRef) ?? readNonEmptyString9(data2.repoRef), - visibility: readNonEmptyString9(data2.visibility) ?? "default", - setupCommand: readNonEmptyString9(data2.setupCommand), - cleanupCommand: readNonEmptyString9(data2.cleanupCommand), - remoteProvider: readNonEmptyString9(data2.remoteProvider), - remoteWorkspaceRef, - sharedWorkspaceKey: readNonEmptyString9(data2.sharedWorkspaceKey), - metadata: data2.runtimeConfig !== void 0 ? mergeProjectWorkspaceRuntimeConfig( - data2.metadata ?? null, - data2.runtimeConfig ?? null - ) : data2.metadata ?? null, - isPrimary: shouldBePrimary - }).returning().then((rows) => rows[0] ?? null); - return row; - }); - return created ? toWorkspace(created) : null; - }, - updateWorkspace: async (projectId, workspaceId, data2) => { - const existing = await db.select().from(projectWorkspaces).where( - and( - eq(projectWorkspaces.id, workspaceId), - eq(projectWorkspaces.projectId, projectId) - ) - ).then((rows) => rows[0] ?? null); - if (!existing) return null; - const nextCwd = data2.cwd !== void 0 ? normalizeWorkspaceCwd(data2.cwd) : normalizeWorkspaceCwd(existing.cwd); - const nextRepoUrl = data2.repoUrl !== void 0 ? readNonEmptyString9(data2.repoUrl) : readNonEmptyString9(existing.repoUrl); - const nextSourceType = data2.sourceType !== void 0 ? readNonEmptyString9(data2.sourceType) : readNonEmptyString9(existing.sourceType); - const nextRemoteWorkspaceRef = data2.remoteWorkspaceRef !== void 0 ? readNonEmptyString9(data2.remoteWorkspaceRef) : readNonEmptyString9(existing.remoteWorkspaceRef); - if (nextSourceType === "remote_managed") { - if (!nextRemoteWorkspaceRef && !nextRepoUrl) return null; - } else if (!nextCwd && !nextRepoUrl) { - return null; - } - const patch = { - updatedAt: /* @__PURE__ */ new Date() - }; - if (data2.name !== void 0) patch.name = deriveWorkspaceName({ name: data2.name, cwd: nextCwd, repoUrl: nextRepoUrl }); - if (data2.name === void 0 && (data2.cwd !== void 0 || data2.repoUrl !== void 0)) { - patch.name = deriveWorkspaceName({ cwd: nextCwd, repoUrl: nextRepoUrl }); - } - if (data2.cwd !== void 0) patch.cwd = nextCwd ?? null; - if (data2.repoUrl !== void 0) patch.repoUrl = nextRepoUrl ?? null; - if (data2.repoRef !== void 0) patch.repoRef = readNonEmptyString9(data2.repoRef); - if (data2.sourceType !== void 0 && nextSourceType) patch.sourceType = nextSourceType; - if (data2.defaultRef !== void 0) patch.defaultRef = readNonEmptyString9(data2.defaultRef); - if (data2.visibility !== void 0 && readNonEmptyString9(data2.visibility)) { - patch.visibility = readNonEmptyString9(data2.visibility); - } - if (data2.setupCommand !== void 0) patch.setupCommand = readNonEmptyString9(data2.setupCommand); - if (data2.cleanupCommand !== void 0) patch.cleanupCommand = readNonEmptyString9(data2.cleanupCommand); - if (data2.remoteProvider !== void 0) patch.remoteProvider = readNonEmptyString9(data2.remoteProvider); - if (data2.remoteWorkspaceRef !== void 0) patch.remoteWorkspaceRef = nextRemoteWorkspaceRef; - if (data2.sharedWorkspaceKey !== void 0) patch.sharedWorkspaceKey = readNonEmptyString9(data2.sharedWorkspaceKey); - if (data2.metadata !== void 0 || data2.runtimeConfig !== void 0) { - patch.metadata = data2.runtimeConfig !== void 0 ? mergeProjectWorkspaceRuntimeConfig( - data2.metadata !== void 0 ? data2.metadata : existing.metadata ?? null, - data2.runtimeConfig ?? null - ) : data2.metadata; - } - const updated = await db.transaction(async (tx) => { - if (data2.isPrimary === true) { - await tx.update(projectWorkspaces).set({ isPrimary: false, updatedAt: /* @__PURE__ */ new Date() }).where( - and( - eq(projectWorkspaces.companyId, existing.companyId), - eq(projectWorkspaces.projectId, projectId) - ) - ); - patch.isPrimary = true; - } else if (data2.isPrimary === false) { - patch.isPrimary = false; - } - const row = await tx.update(projectWorkspaces).set(patch).where(eq(projectWorkspaces.id, workspaceId)).returning().then((rows) => rows[0] ?? null); - if (!row) return null; - if (row.isPrimary) return row; - const hasPrimary = await tx.select({ id: projectWorkspaces.id }).from(projectWorkspaces).where( - and( - eq(projectWorkspaces.companyId, row.companyId), - eq(projectWorkspaces.projectId, row.projectId), - eq(projectWorkspaces.isPrimary, true) - ) - ).then((rows) => rows[0] ?? null); - if (!hasPrimary) { - const nextPrimaryCandidate = await tx.select({ id: projectWorkspaces.id }).from(projectWorkspaces).where( - and( - eq(projectWorkspaces.companyId, row.companyId), - eq(projectWorkspaces.projectId, row.projectId), - eq(projectWorkspaces.id, row.id) - ) - ).then((rows) => rows[0] ?? null); - const alternateCandidate = await tx.select({ id: projectWorkspaces.id }).from(projectWorkspaces).where( - and( - eq(projectWorkspaces.companyId, row.companyId), - eq(projectWorkspaces.projectId, row.projectId) - ) - ).orderBy(asc(projectWorkspaces.createdAt), asc(projectWorkspaces.id)).then((rows) => rows.find((candidate) => candidate.id !== row.id) ?? null); - await ensureSinglePrimaryWorkspace(tx, { - companyId: row.companyId, - projectId: row.projectId, - keepWorkspaceId: alternateCandidate?.id ?? nextPrimaryCandidate?.id ?? row.id - }); - const refreshed = await tx.select().from(projectWorkspaces).where(eq(projectWorkspaces.id, row.id)).then((rows) => rows[0] ?? row); - return refreshed; - } - return row; - }); - return updated ? toWorkspace(updated) : null; - }, - removeWorkspace: async (projectId, workspaceId) => { - const existing = await db.select().from(projectWorkspaces).where( - and( - eq(projectWorkspaces.id, workspaceId), - eq(projectWorkspaces.projectId, projectId) - ) - ).then((rows) => rows[0] ?? null); - if (!existing) return null; - const removed = await db.transaction(async (tx) => { - const row = await tx.delete(projectWorkspaces).where(eq(projectWorkspaces.id, workspaceId)).returning().then((rows) => rows[0] ?? null); - if (!row) return null; - if (!row.isPrimary) return row; - const next = await tx.select().from(projectWorkspaces).where( - and( - eq(projectWorkspaces.companyId, row.companyId), - eq(projectWorkspaces.projectId, row.projectId) - ) - ).orderBy(asc(projectWorkspaces.createdAt), asc(projectWorkspaces.id)).limit(1).then((rows) => rows[0] ?? null); - if (next) { - await ensureSinglePrimaryWorkspace(tx, { - companyId: row.companyId, - projectId: row.projectId, - keepWorkspaceId: next.id - }); - } - return row; - }); - return removed ? toWorkspace(removed) : null; - }, - resolveByReference: async (companyId, reference) => { - const raw = reference.trim(); - if (raw.length === 0) { - return { project: null, ambiguous: false }; - } - if (isUuidLike(raw)) { - const row = await db.select({ id: projects.id, companyId: projects.companyId, name: projects.name }).from(projects).where(and(eq(projects.id, raw), eq(projects.companyId, companyId))).then((rows2) => rows2[0] ?? null); - if (!row) return { project: null, ambiguous: false }; - return { - project: { id: row.id, companyId: row.companyId, urlKey: deriveProjectUrlKey(row.name, row.id) }, - ambiguous: false - }; - } - const urlKey = normalizeProjectUrlKey(raw); - if (!urlKey) { - return { project: null, ambiguous: false }; - } - const rows = await db.select({ id: projects.id, companyId: projects.companyId, name: projects.name }).from(projects).where(eq(projects.companyId, companyId)); - const matches = rows.filter((row) => deriveProjectUrlKey(row.name, row.id) === urlKey); - if (matches.length === 1) { - const match = matches[0]; - return { - project: { id: match.id, companyId: match.companyId, urlKey: deriveProjectUrlKey(match.name, match.id) }, - ambiguous: false - }; - } - if (matches.length > 1) { - return { project: null, ambiguous: true }; - } - return { project: null, ambiguous: false }; - } - }; -} - -// server/src/services/secrets.ts -init_drizzle_orm(); -init_src2(); - -// server/src/secrets/local-encrypted-provider.ts -import { createCipheriv, createDecipheriv, createHash as createHash9, randomBytes as randomBytes3 } from "node:crypto"; -import { mkdirSync, readFileSync as readFileSync2, writeFileSync, existsSync as existsSync2, chmodSync } from "node:fs"; -import path33 from "node:path"; -function resolveMasterKeyFilePath() { - const fromEnv = process.env.TASKCORE_SECRETS_MASTER_KEY_FILE; - if (fromEnv && fromEnv.trim().length > 0) return path33.resolve(fromEnv.trim()); - return path33.resolve(process.cwd(), "data/secrets/master.key"); -} -function decodeMasterKey(raw) { - const trimmed = raw.trim(); - if (!trimmed) return null; - if (/^[A-Fa-f0-9]{64}$/.test(trimmed)) { - return Buffer.from(trimmed, "hex"); - } - try { - const decoded = Buffer.from(trimmed, "base64"); - if (decoded.length === 32) return decoded; - } catch { - } - if (Buffer.byteLength(trimmed, "utf8") === 32) { - return Buffer.from(trimmed, "utf8"); - } - return null; -} -function loadOrCreateMasterKey() { - const envKeyRaw = process.env.TASKCORE_SECRETS_MASTER_KEY; - if (envKeyRaw && envKeyRaw.trim().length > 0) { - const fromEnv = decodeMasterKey(envKeyRaw); - if (!fromEnv) { - throw badRequest( - "Invalid TASKCORE_SECRETS_MASTER_KEY (expected 32-byte base64, 64-char hex, or raw 32-char string)" - ); - } - return fromEnv; - } - const keyPath = resolveMasterKeyFilePath(); - if (existsSync2(keyPath)) { - const raw = readFileSync2(keyPath, "utf8"); - const decoded = decodeMasterKey(raw); - if (!decoded) { - throw badRequest(`Invalid secrets master key at ${keyPath}`); - } - return decoded; - } - const dir = path33.dirname(keyPath); - mkdirSync(dir, { recursive: true }); - const generated = randomBytes3(32); - writeFileSync(keyPath, generated.toString("base64"), { encoding: "utf8", mode: 384 }); - try { - chmodSync(keyPath, 384); - } catch { - } - return generated; -} -function sha256Hex(value) { - return createHash9("sha256").update(value).digest("hex"); -} -function encryptValue(masterKey, value) { - const iv = randomBytes3(12); - const cipher = createCipheriv("aes-256-gcm", masterKey, iv); - const ciphertext = Buffer.concat([cipher.update(value, "utf8"), cipher.final()]); - const tag3 = cipher.getAuthTag(); - return { - scheme: "local_encrypted_v1", - iv: iv.toString("base64"), - tag: tag3.toString("base64"), - ciphertext: ciphertext.toString("base64") - }; -} -function decryptValue(masterKey, material) { - const iv = Buffer.from(material.iv, "base64"); - const tag3 = Buffer.from(material.tag, "base64"); - const ciphertext = Buffer.from(material.ciphertext, "base64"); - const decipher = createDecipheriv("aes-256-gcm", masterKey, iv); - decipher.setAuthTag(tag3); - const plain = Buffer.concat([decipher.update(ciphertext), decipher.final()]); - return plain.toString("utf8"); -} -function asLocalEncryptedMaterial(value) { - if (value && typeof value === "object" && value.scheme === "local_encrypted_v1" && typeof value.iv === "string" && typeof value.tag === "string" && typeof value.ciphertext === "string") { - return value; - } - throw badRequest("Invalid local_encrypted secret material"); -} -var localEncryptedProvider = { - id: "local_encrypted", - descriptor: { - id: "local_encrypted", - label: "Local encrypted (default)", - requiresExternalRef: false - }, - async createVersion(input) { - const masterKey = loadOrCreateMasterKey(); - return { - material: encryptValue(masterKey, input.value), - valueSha256: sha256Hex(input.value), - externalRef: null - }; - }, - async resolveVersion(input) { - const masterKey = loadOrCreateMasterKey(); - return decryptValue(masterKey, asLocalEncryptedMaterial(input.material)); - } -}; - -// server/src/secrets/external-stub-providers.ts -function unavailableProvider(id, label) { - return { - id, - descriptor: { - id, - label, - requiresExternalRef: true - }, - async createVersion() { - throw unprocessable(`${id} provider is not configured in this deployment`); - }, - async resolveVersion() { - throw unprocessable(`${id} provider is not configured in this deployment`); - } - }; -} -var awsSecretsManagerProvider = unavailableProvider( - "aws_secrets_manager", - "AWS Secrets Manager" -); -var gcpSecretManagerProvider = unavailableProvider( - "gcp_secret_manager", - "GCP Secret Manager" -); -var vaultProvider = unavailableProvider("vault", "HashiCorp Vault"); - -// server/src/secrets/provider-registry.ts -var providers = [ - localEncryptedProvider, - awsSecretsManagerProvider, - gcpSecretManagerProvider, - vaultProvider -]; -var providerById = new Map( - providers.map((provider) => [provider.id, provider]) -); -function getSecretProvider(id) { - const provider = providerById.get(id); - if (!provider) throw unprocessable(`Unsupported secret provider: ${id}`); - return provider; -} -function listSecretProviders() { - return providers.map((provider) => provider.descriptor); -} - -// server/src/services/secrets.ts -var ENV_KEY_RE = /^[A-Za-z_][A-Za-z0-9_]*$/; -var SENSITIVE_ENV_KEY_RE = /(api[-_]?key|access[-_]?token|auth(?:_?token)?|authorization|bearer|secret|passwd|password|credential|jwt|private[-_]?key|cookie|connectionstring)/i; -var REDACTED_SENTINEL = "***REDACTED***"; -function asRecord7(value) { - if (typeof value !== "object" || value === null || Array.isArray(value)) return null; - return value; -} -function isSensitiveEnvKey(key) { - return SENSITIVE_ENV_KEY_RE.test(key); -} -function canonicalizeBinding(binding) { - if (typeof binding === "string") { - return { type: "plain", value: binding }; - } - if (binding.type === "plain") { - return { type: "plain", value: String(binding.value) }; - } - return { - type: "secret_ref", - secretId: binding.secretId, - version: binding.version ?? "latest" - }; -} -function secretService(db) { - async function getById(id) { - return db.select().from(companySecrets).where(eq(companySecrets.id, id)).then((rows) => rows[0] ?? null); - } - async function getByName(companyId, name) { - return db.select().from(companySecrets).where(and(eq(companySecrets.companyId, companyId), eq(companySecrets.name, name))).then((rows) => rows[0] ?? null); - } - async function getSecretVersion(secretId, version3) { - return db.select().from(companySecretVersions).where( - and( - eq(companySecretVersions.secretId, secretId), - eq(companySecretVersions.version, version3) - ) - ).then((rows) => rows[0] ?? null); - } - async function assertSecretInCompany(companyId, secretId) { - const secret = await getById(secretId); - if (!secret) throw notFound("Secret not found"); - if (secret.companyId !== companyId) throw unprocessable("Secret must belong to same company"); - return secret; - } - async function resolveSecretValue(companyId, secretId, version3) { - const secret = await assertSecretInCompany(companyId, secretId); - const resolvedVersion = version3 === "latest" ? secret.latestVersion : version3; - const versionRow = await getSecretVersion(secret.id, resolvedVersion); - if (!versionRow) throw notFound("Secret version not found"); - const provider = getSecretProvider(secret.provider); - return provider.resolveVersion({ - material: versionRow.material, - externalRef: secret.externalRef - }); - } - async function normalizeEnvConfig(companyId, envValue, opts) { - const record2 = asRecord7(envValue); - if (!record2) throw unprocessable(`${opts?.fieldPath ?? "env"} must be an object`); - const normalized = {}; - for (const [key, rawBinding] of Object.entries(record2)) { - if (!ENV_KEY_RE.test(key)) { - throw unprocessable(`Invalid environment variable name: ${key}`); - } - const parsed = envBindingSchema.safeParse(rawBinding); - if (!parsed.success) { - throw unprocessable(`Invalid environment binding for key: ${key}`); - } - const binding = canonicalizeBinding(parsed.data); - if (binding.type === "plain") { - if (opts?.strictMode && isSensitiveEnvKey(key) && binding.value.trim().length > 0) { - throw unprocessable( - `Strict secret mode requires secret references for sensitive key: ${key}` - ); - } - if (binding.value === REDACTED_SENTINEL) { - throw unprocessable(`Refusing to persist redacted placeholder for key: ${key}`); - } - normalized[key] = binding; - continue; - } - await assertSecretInCompany(companyId, binding.secretId); - normalized[key] = { - type: "secret_ref", - secretId: binding.secretId, - version: binding.version - }; - } - return normalized; - } - async function normalizeAdapterConfigForPersistenceInternal(companyId, adapterConfig, opts) { - const normalized = { ...adapterConfig }; - if (!Object.prototype.hasOwnProperty.call(adapterConfig, "env")) { - return normalized; - } - normalized.env = await normalizeEnvConfig(companyId, adapterConfig.env, opts); - return normalized; - } - return { - listProviders: () => listSecretProviders(), - list: (companyId) => db.select().from(companySecrets).where(eq(companySecrets.companyId, companyId)).orderBy(desc(companySecrets.createdAt)), - getById, - getByName, - resolveSecretValue, - create: async (companyId, input, actor) => { - const existing = await getByName(companyId, input.name); - if (existing) throw conflict(`Secret already exists: ${input.name}`); - const provider = getSecretProvider(input.provider); - const prepared = await provider.createVersion({ - value: input.value, - externalRef: input.externalRef ?? null - }); - return db.transaction(async (tx) => { - const secret = await tx.insert(companySecrets).values({ - companyId, - name: input.name, - provider: input.provider, - externalRef: prepared.externalRef, - latestVersion: 1, - description: input.description ?? null, - createdByAgentId: actor?.agentId ?? null, - createdByUserId: actor?.userId ?? null - }).returning().then((rows) => rows[0]); - await tx.insert(companySecretVersions).values({ - secretId: secret.id, - version: 1, - material: prepared.material, - valueSha256: prepared.valueSha256, - createdByAgentId: actor?.agentId ?? null, - createdByUserId: actor?.userId ?? null - }); - return secret; - }); - }, - rotate: async (secretId, input, actor) => { - const secret = await getById(secretId); - if (!secret) throw notFound("Secret not found"); - const provider = getSecretProvider(secret.provider); - const nextVersion = secret.latestVersion + 1; - const prepared = await provider.createVersion({ - value: input.value, - externalRef: input.externalRef ?? secret.externalRef ?? null - }); - return db.transaction(async (tx) => { - await tx.insert(companySecretVersions).values({ - secretId: secret.id, - version: nextVersion, - material: prepared.material, - valueSha256: prepared.valueSha256, - createdByAgentId: actor?.agentId ?? null, - createdByUserId: actor?.userId ?? null - }); - const updated = await tx.update(companySecrets).set({ - latestVersion: nextVersion, - externalRef: prepared.externalRef, - updatedAt: /* @__PURE__ */ new Date() - }).where(eq(companySecrets.id, secret.id)).returning().then((rows) => rows[0] ?? null); - if (!updated) throw notFound("Secret not found"); - return updated; - }); - }, - update: async (secretId, patch) => { - const secret = await getById(secretId); - if (!secret) throw notFound("Secret not found"); - if (patch.name && patch.name !== secret.name) { - const duplicate = await getByName(secret.companyId, patch.name); - if (duplicate && duplicate.id !== secret.id) { - throw conflict(`Secret already exists: ${patch.name}`); - } - } - return db.update(companySecrets).set({ - name: patch.name ?? secret.name, - description: patch.description === void 0 ? secret.description : patch.description, - externalRef: patch.externalRef === void 0 ? secret.externalRef : patch.externalRef, - updatedAt: /* @__PURE__ */ new Date() - }).where(eq(companySecrets.id, secret.id)).returning().then((rows) => rows[0] ?? null); - }, - remove: async (secretId) => { - const secret = await getById(secretId); - if (!secret) return null; - await db.delete(companySecrets).where(eq(companySecrets.id, secretId)); - return secret; - }, - normalizeAdapterConfigForPersistence: async (companyId, adapterConfig, opts) => normalizeAdapterConfigForPersistenceInternal(companyId, adapterConfig, opts), - normalizeEnvBindingsForPersistence: async (companyId, envValue, opts) => normalizeEnvConfig(companyId, envValue, opts), - normalizeHireApprovalPayloadForPersistence: async (companyId, payload2, opts) => { - const normalized = { ...payload2 }; - const adapterConfig = asRecord7(payload2.adapterConfig); - if (adapterConfig) { - normalized.adapterConfig = await normalizeAdapterConfigForPersistenceInternal( - companyId, - adapterConfig, - opts - ); - } - return normalized; - }, - resolveEnvBindings: async (companyId, envValue) => { - const record2 = asRecord7(envValue); - if (!record2) return { env: {}, secretKeys: /* @__PURE__ */ new Set() }; - const resolved = {}; - const secretKeys = /* @__PURE__ */ new Set(); - for (const [key, rawBinding] of Object.entries(record2)) { - if (!ENV_KEY_RE.test(key)) { - throw unprocessable(`Invalid environment variable name: ${key}`); - } - const parsed = envBindingSchema.safeParse(rawBinding); - if (!parsed.success) { - throw unprocessable(`Invalid environment binding for key: ${key}`); - } - const binding = canonicalizeBinding(parsed.data); - if (binding.type === "plain") { - resolved[key] = binding.value; - } else { - resolved[key] = await resolveSecretValue(companyId, binding.secretId, binding.version); - secretKeys.add(key); - } - } - return { env: resolved, secretKeys }; - }, - resolveAdapterConfigForRuntime: async (companyId, adapterConfig) => { - const resolved = { ...adapterConfig }; - const secretKeys = /* @__PURE__ */ new Set(); - if (!Object.prototype.hasOwnProperty.call(adapterConfig, "env")) { - return { config: resolved, secretKeys }; - } - const record2 = asRecord7(adapterConfig.env); - if (!record2) { - resolved.env = {}; - return { config: resolved, secretKeys }; - } - const env2 = {}; - for (const [key, rawBinding] of Object.entries(record2)) { - if (!ENV_KEY_RE.test(key)) { - throw unprocessable(`Invalid environment variable name: ${key}`); - } - const parsed = envBindingSchema.safeParse(rawBinding); - if (!parsed.success) { - throw unprocessable(`Invalid environment binding for key: ${key}`); - } - const binding = canonicalizeBinding(parsed.data); - if (binding.type === "plain") { - env2[key] = binding.value; - } else { - env2[key] = await resolveSecretValue(companyId, binding.secretId, binding.version); - secretKeys.add(key); - } - } - resolved.env = env2; - return { config: resolved, secretKeys }; - } - }; -} - -// server/src/services/company-skills.ts -var skillInventoryRefreshPromises = /* @__PURE__ */ new Map(); -var PROJECT_SCAN_DIRECTORY_ROOTS = [ - "skills", - "skills/.curated", - "skills/.experimental", - "skills/.system", - ".agents/skills", - ".agent/skills", - ".augment/skills", - ".claude/skills", - ".codebuddy/skills", - ".commandcode/skills", - ".continue/skills", - ".cortex/skills", - ".crush/skills", - ".factory/skills", - ".goose/skills", - ".junie/skills", - ".iflow/skills", - ".kilocode/skills", - ".kiro/skills", - ".kode/skills", - ".mcpjam/skills", - ".vibe/skills", - ".mux/skills", - ".openhands/skills", - ".pi/skills", - ".qoder/skills", - ".qwen/skills", - ".roo/skills", - ".trae/skills", - ".windsurf/skills", - ".zencoder/skills", - ".neovate/skills", - ".pochi/skills", - ".adal/skills" -]; -var PROJECT_ROOT_SKILL_SUBDIRECTORIES = [ - "references", - "scripts", - "assets" -]; -function asString13(value) { - if (typeof value !== "string") return null; - const trimmed = value.trim(); - return trimmed.length > 0 ? trimmed : null; -} -function isPlainRecord3(value) { - return typeof value === "object" && value !== null && !Array.isArray(value); -} -function normalizePortablePath(input) { - const parts = []; - for (const segment of input.replace(/\\/g, "/").replace(/^\.\/+/, "").replace(/^\/+/, "").split("/")) { - if (!segment || segment === ".") continue; - if (segment === "..") { - if (parts.length > 0) parts.pop(); - continue; - } - parts.push(segment); - } - return parts.join("/"); -} -function normalizePackageFileMap(files) { - const out = {}; - for (const [rawPath, content] of Object.entries(files)) { - const nextPath = normalizePortablePath(rawPath); - if (!nextPath) continue; - out[nextPath] = content; - } - return out; -} -function normalizeSkillSlug2(value) { - return value ? normalizeAgentUrlKey(value) ?? null : null; -} -function normalizeSkillKey(value) { - if (!value) return null; - const segments = value.split("/").map((segment) => normalizeSkillSlug2(segment)).filter((segment) => Boolean(segment)); - return segments.length > 0 ? segments.join("/") : null; -} -function normalizeGitHubSkillDirectory(value, fallback) { - const normalized = normalizePortablePath(value ?? ""); - if (!normalized) return normalizePortablePath(fallback); - if (path34.posix.basename(normalized).toLowerCase() === "skill.md") { - return normalizePortablePath(path34.posix.dirname(normalized)); - } - return normalized; -} -function hashSkillValue(value) { - return createHash10("sha256").update(value).digest("hex").slice(0, 10); -} -function uniqueSkillSlug(baseSlug, usedSlugs) { - if (!usedSlugs.has(baseSlug)) return baseSlug; - let attempt = 2; - let candidate = `${baseSlug}-${attempt}`; - while (usedSlugs.has(candidate)) { - attempt += 1; - candidate = `${baseSlug}-${attempt}`; - } - return candidate; -} -function uniqueImportedSkillKey(companyId, baseSlug, usedKeys) { - const initial = `company/${companyId}/${baseSlug}`; - if (!usedKeys.has(initial)) return initial; - let attempt = 2; - let candidate = `company/${companyId}/${baseSlug}-${attempt}`; - while (usedKeys.has(candidate)) { - attempt += 1; - candidate = `company/${companyId}/${baseSlug}-${attempt}`; - } - return candidate; -} -function buildSkillRuntimeName(key, slug) { - if (key.startsWith("taskcore/taskcore/")) return slug; - return `${slug}--${hashSkillValue(key)}`; -} -function readCanonicalSkillKey(frontmatter, metadata) { - const direct = normalizeSkillKey( - asString13(frontmatter.key) ?? asString13(frontmatter.skillKey) ?? asString13(metadata?.skillKey) ?? asString13(metadata?.canonicalKey) ?? asString13(metadata?.taskcoreSkillKey) - ); - if (direct) return direct; - const taskcore = isPlainRecord3(metadata?.taskcore) ? metadata?.taskcore : null; - return normalizeSkillKey( - asString13(taskcore?.skillKey) ?? asString13(taskcore?.key) - ); -} -function deriveCanonicalSkillKey(companyId, input) { - const slug = normalizeSkillSlug2(input.slug) ?? "skill"; - const metadata = isPlainRecord3(input.metadata) ? input.metadata : null; - const explicitKey = readCanonicalSkillKey({}, metadata); - if (explicitKey) return explicitKey; - const sourceKind = asString13(metadata?.sourceKind); - if (sourceKind === "taskcore_bundled") { - return `taskcore/taskcore/${slug}`; - } - const owner = normalizeSkillSlug2(asString13(metadata?.owner)); - const repo = normalizeSkillSlug2(asString13(metadata?.repo)); - if ((input.sourceType === "github" || input.sourceType === "skills_sh" || sourceKind === "github" || sourceKind === "skills_sh") && owner && repo) { - return `${owner}/${repo}/${slug}`; - } - if (input.sourceType === "url" || sourceKind === "url") { - const locator = asString13(input.sourceLocator); - if (locator) { - try { - const url2 = new URL(locator); - const host = normalizeSkillSlug2(url2.host) ?? "url"; - return `url/${host}/${hashSkillValue(locator)}/${slug}`; - } catch { - return `url/unknown/${hashSkillValue(locator)}/${slug}`; - } - } - } - if (input.sourceType === "local_path") { - if (sourceKind === "managed_local") { - return `company/${companyId}/${slug}`; - } - const locator = asString13(input.sourceLocator); - if (locator) { - return `local/${hashSkillValue(path34.resolve(locator))}/${slug}`; - } - } - return `company/${companyId}/${slug}`; -} -function classifyInventoryKind(relativePath) { - const normalized = normalizePortablePath(relativePath).toLowerCase(); - if (normalized.endsWith("/skill.md") || normalized === "skill.md") return "skill"; - if (normalized.startsWith("references/")) return "reference"; - if (normalized.startsWith("scripts/")) return "script"; - if (normalized.startsWith("assets/")) return "asset"; - if (normalized.endsWith(".md")) return "markdown"; - const fileName = path34.posix.basename(normalized); - if (fileName.endsWith(".sh") || fileName.endsWith(".js") || fileName.endsWith(".mjs") || fileName.endsWith(".cjs") || fileName.endsWith(".ts") || fileName.endsWith(".py") || fileName.endsWith(".rb") || fileName.endsWith(".bash")) { - return "script"; - } - if (fileName.endsWith(".png") || fileName.endsWith(".jpg") || fileName.endsWith(".jpeg") || fileName.endsWith(".gif") || fileName.endsWith(".svg") || fileName.endsWith(".webp") || fileName.endsWith(".pdf")) { - return "asset"; - } - return "other"; -} -function deriveTrustLevel(fileInventory) { - if (fileInventory.some((entry) => entry.kind === "script")) return "scripts_executables"; - if (fileInventory.some((entry) => entry.kind === "asset" || entry.kind === "other")) return "assets"; - return "markdown_only"; -} -function prepareYamlLines(raw) { - return raw.split("\n").map((line3) => ({ - indent: line3.match(/^ */)?.[0].length ?? 0, - content: line3.trim() - })).filter((line3) => line3.content.length > 0 && !line3.content.startsWith("#")); -} -function parseYamlScalar(rawValue) { - const trimmed = rawValue.trim(); - if (trimmed === "") return ""; - if (trimmed === "null" || trimmed === "~") return null; - if (trimmed === "true") return true; - if (trimmed === "false") return false; - if (trimmed === "[]") return []; - if (trimmed === "{}") return {}; - if (/^-?\d+(\.\d+)?$/.test(trimmed)) return Number(trimmed); - if (trimmed.startsWith('"') || trimmed.startsWith("[") || trimmed.startsWith("{")) { - try { - return JSON.parse(trimmed); - } catch { - return trimmed; - } - } - return trimmed; -} -function parseYamlBlock(lines, startIndex, indentLevel) { - let index2 = startIndex; - while (index2 < lines.length && lines[index2].content.length === 0) index2 += 1; - if (index2 >= lines.length || lines[index2].indent < indentLevel) { - return { value: {}, nextIndex: index2 }; - } - const isArray = lines[index2].indent === indentLevel && lines[index2].content.startsWith("-"); - if (isArray) { - const values2 = []; - while (index2 < lines.length) { - const line3 = lines[index2]; - if (line3.indent < indentLevel) break; - if (line3.indent !== indentLevel || !line3.content.startsWith("-")) break; - const remainder = line3.content.slice(1).trim(); - index2 += 1; - if (!remainder) { - const nested = parseYamlBlock(lines, index2, indentLevel + 2); - values2.push(nested.value); - index2 = nested.nextIndex; - continue; - } - const inlineObjectSeparator = remainder.indexOf(":"); - if (inlineObjectSeparator > 0 && !remainder.startsWith('"') && !remainder.startsWith("{") && !remainder.startsWith("[")) { - const key = remainder.slice(0, inlineObjectSeparator).trim(); - const rawValue = remainder.slice(inlineObjectSeparator + 1).trim(); - const nextObject = { - [key]: parseYamlScalar(rawValue) - }; - if (index2 < lines.length && lines[index2].indent > indentLevel) { - const nested = parseYamlBlock(lines, index2, indentLevel + 2); - if (isPlainRecord3(nested.value)) { - Object.assign(nextObject, nested.value); - } - index2 = nested.nextIndex; - } - values2.push(nextObject); - continue; - } - values2.push(parseYamlScalar(remainder)); - } - return { value: values2, nextIndex: index2 }; - } - const record2 = {}; - while (index2 < lines.length) { - const line3 = lines[index2]; - if (line3.indent < indentLevel) break; - if (line3.indent !== indentLevel) { - index2 += 1; - continue; - } - const separatorIndex = line3.content.indexOf(":"); - if (separatorIndex <= 0) { - index2 += 1; - continue; - } - const key = line3.content.slice(0, separatorIndex).trim(); - const remainder = line3.content.slice(separatorIndex + 1).trim(); - index2 += 1; - if (!remainder) { - const nested = parseYamlBlock(lines, index2, indentLevel + 2); - record2[key] = nested.value; - index2 = nested.nextIndex; - continue; - } - record2[key] = parseYamlScalar(remainder); - } - return { value: record2, nextIndex: index2 }; -} -function parseYamlFrontmatter(raw) { - const prepared = prepareYamlLines(raw); - if (prepared.length === 0) return {}; - const parsed = parseYamlBlock(prepared, 0, prepared[0].indent); - return isPlainRecord3(parsed.value) ? parsed.value : {}; -} -function parseFrontmatterMarkdown(raw) { - const normalized = raw.replace(/\r\n/g, "\n"); - if (!normalized.startsWith("---\n")) { - return { frontmatter: {}, body: normalized.trim() }; - } - const closing = normalized.indexOf("\n---\n", 4); - if (closing < 0) { - return { frontmatter: {}, body: normalized.trim() }; - } - const frontmatterRaw = normalized.slice(4, closing).trim(); - const body = normalized.slice(closing + 5).trim(); - return { - frontmatter: parseYamlFrontmatter(frontmatterRaw), - body - }; -} -async function fetchText(url2) { - const response = await ghFetch(url2); - if (!response.ok) { - throw unprocessable(`Failed to fetch ${url2}: ${response.status}`); - } - return response.text(); -} -async function fetchJson(url2) { - const response = await ghFetch(url2, { - headers: { - accept: "application/vnd.github+json" - } - }); - if (!response.ok) { - throw unprocessable(`Failed to fetch ${url2}: ${response.status}`); - } - return response.json(); -} -async function resolveGitHubDefaultBranch(owner, repo, apiBase) { - const response = await fetchJson( - `${apiBase}/repos/${owner}/${repo}` - ); - return asString13(response.default_branch) ?? "main"; -} -async function resolveGitHubCommitSha(owner, repo, ref, apiBase) { - const response = await fetchJson( - `${apiBase}/repos/${owner}/${repo}/commits/${encodeURIComponent(ref)}` - ); - const sha = asString13(response.sha); - if (!sha) { - throw unprocessable(`Failed to resolve GitHub ref ${ref}`); - } - return sha; -} -function parseGitHubSourceUrl(rawUrl) { - const url2 = new URL(rawUrl); - if (url2.protocol !== "https:") { - throw unprocessable("GitHub source URL must use HTTPS"); - } - const parts = url2.pathname.split("/").filter(Boolean); - if (parts.length < 2) { - throw unprocessable("Invalid GitHub URL"); - } - const owner = parts[0]; - const repo = parts[1].replace(/\.git$/i, ""); - let ref = "main"; - let basePath = ""; - let filePath = null; - let explicitRef = false; - if (parts[2] === "tree") { - ref = parts[3] ?? "main"; - basePath = parts.slice(4).join("/"); - explicitRef = true; - } else if (parts[2] === "blob") { - ref = parts[3] ?? "main"; - filePath = parts.slice(4).join("/"); - basePath = filePath ? path34.posix.dirname(filePath) : ""; - explicitRef = true; - } - return { hostname: url2.hostname, owner, repo, ref, basePath, filePath, explicitRef }; -} -async function resolveGitHubPinnedRef(parsed) { - const apiBase = gitHubApiBase(parsed.hostname); - if (/^[0-9a-f]{40}$/i.test(parsed.ref.trim())) { - return { - pinnedRef: parsed.ref, - trackingRef: parsed.explicitRef ? parsed.ref : null - }; - } - const trackingRef = parsed.explicitRef ? parsed.ref : await resolveGitHubDefaultBranch(parsed.owner, parsed.repo, apiBase); - const pinnedRef = await resolveGitHubCommitSha(parsed.owner, parsed.repo, trackingRef, apiBase); - return { pinnedRef, trackingRef }; -} -function extractCommandTokens(raw) { - const matches = raw.match(/"[^"]*"|'[^']*'|\S+/g) ?? []; - return matches.map((token) => token.replace(/^['"]|['"]$/g, "")); -} -function parseSkillImportSourceInput(rawInput) { - const trimmed = rawInput.trim(); - if (!trimmed) { - throw unprocessable("Skill source is required."); - } - const warnings = []; - let source = trimmed; - let requestedSkillSlug = null; - if (/^npx\s+skills\s+add\s+/i.test(trimmed)) { - const tokens = extractCommandTokens(trimmed); - const addIndex = tokens.findIndex( - (token, index2) => token === "add" && index2 > 0 && tokens[index2 - 1]?.toLowerCase() === "skills" - ); - if (addIndex >= 0) { - source = tokens[addIndex + 1] ?? ""; - for (let index2 = addIndex + 2; index2 < tokens.length; index2 += 1) { - const token = tokens[index2]; - if (token === "--skill") { - requestedSkillSlug = normalizeSkillSlug2(tokens[index2 + 1] ?? null); - index2 += 1; - continue; - } - if (token.startsWith("--skill=")) { - requestedSkillSlug = normalizeSkillSlug2(token.slice("--skill=".length)); - } - } - } - } - const normalizedSource = source.trim(); - if (!normalizedSource) { - throw unprocessable("Skill source is required."); - } - if (!/^https?:\/\//i.test(normalizedSource) && /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(normalizedSource)) { - const [owner, repo, skillSlugRaw] = normalizedSource.split("/"); - return { - resolvedSource: `https://github.com/${owner}/${repo}`, - requestedSkillSlug: normalizeSkillSlug2(skillSlugRaw), - originalSkillsShUrl: `https://skills.sh/${owner}/${repo}/${skillSlugRaw}`, - warnings - }; - } - if (!/^https?:\/\//i.test(normalizedSource) && /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(normalizedSource)) { - return { - resolvedSource: `https://github.com/${normalizedSource}`, - requestedSkillSlug, - originalSkillsShUrl: null, - warnings - }; - } - const skillsShMatch = normalizedSource.match(/^https?:\/\/(?:www\.)?skills\.sh\/([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)(?:\/([A-Za-z0-9_.-]+))?(?:[?#].*)?$/i); - if (skillsShMatch) { - const [, owner, repo, skillSlugRaw] = skillsShMatch; - return { - resolvedSource: `https://github.com/${owner}/${repo}`, - requestedSkillSlug: skillSlugRaw ? normalizeSkillSlug2(skillSlugRaw) : requestedSkillSlug, - originalSkillsShUrl: normalizedSource, - warnings - }; - } - return { - resolvedSource: normalizedSource, - requestedSkillSlug, - originalSkillsShUrl: null, - warnings - }; -} -function resolveBundledSkillsRoot() { - const moduleDir = path34.dirname(fileURLToPath15(import.meta.url)); - return [ - path34.resolve(moduleDir, "../../skills"), - path34.resolve(process.cwd(), "skills"), - path34.resolve(moduleDir, "../../../skills") - ]; -} -function matchesRequestedSkill(relativeSkillPath, requestedSkillSlug) { - if (!requestedSkillSlug) return true; - const skillDir = path34.posix.dirname(relativeSkillPath); - return normalizeSkillSlug2(path34.posix.basename(skillDir)) === requestedSkillSlug; -} -function deriveImportedSkillSlug(frontmatter, fallback) { - return normalizeSkillSlug2(asString13(frontmatter.slug)) ?? normalizeSkillSlug2(asString13(frontmatter.name)) ?? normalizeAgentUrlKey(fallback) ?? "skill"; -} -function deriveImportedSkillSource(frontmatter, fallbackSlug) { - const metadata = isPlainRecord3(frontmatter.metadata) ? frontmatter.metadata : null; - const canonicalKey = readCanonicalSkillKey(frontmatter, metadata); - const rawSources = metadata && Array.isArray(metadata.sources) ? metadata.sources : []; - const sourceEntry = rawSources.find((entry) => isPlainRecord3(entry)); - const kind = asString13(sourceEntry?.kind); - if (kind === "github-dir" || kind === "github-file") { - const repo = asString13(sourceEntry?.repo); - const repoPath = asString13(sourceEntry?.path); - const commit = asString13(sourceEntry?.commit); - const trackingRef = asString13(sourceEntry?.trackingRef); - const sourceHostname = asString13(sourceEntry?.hostname) || "github.com"; - const url2 = asString13(sourceEntry?.url) ?? (repo ? `https://${sourceHostname}/${repo}${repoPath ? `/tree/${trackingRef ?? commit ?? "main"}/${repoPath}` : ""}` : null); - const [owner, repoName] = (repo ?? "").split("/"); - if (repo && owner && repoName) { - return { - sourceType: "github", - sourceLocator: url2, - sourceRef: commit, - metadata: { - ...canonicalKey ? { skillKey: canonicalKey } : {}, - sourceKind: "github", - ...sourceHostname !== "github.com" ? { hostname: sourceHostname } : {}, - owner, - repo: repoName, - ref: commit, - trackingRef, - repoSkillDir: repoPath ?? `skills/${fallbackSlug}` - } - }; - } - } - if (kind === "url") { - const url2 = asString13(sourceEntry?.url) ?? asString13(sourceEntry?.rawUrl); - if (url2) { - return { - sourceType: "url", - sourceLocator: url2, - sourceRef: null, - metadata: { - ...canonicalKey ? { skillKey: canonicalKey } : {}, - sourceKind: "url" - } - }; - } - } - return { - sourceType: "catalog", - sourceLocator: null, - sourceRef: null, - metadata: { - ...canonicalKey ? { skillKey: canonicalKey } : {}, - sourceKind: "catalog" - } - }; -} -function readInlineSkillImports(companyId, files) { - const normalizedFiles = normalizePackageFileMap(files); - const skillPaths = Object.keys(normalizedFiles).filter( - (entry) => path34.posix.basename(entry).toLowerCase() === "skill.md" - ); - const imports = []; - for (const skillPath of skillPaths) { - const dir = path34.posix.dirname(skillPath); - const skillDir = dir === "." ? "" : dir; - const slugFallback = path34.posix.basename(skillDir || path34.posix.dirname(skillPath)); - const markdown = normalizedFiles[skillPath]; - const parsed = parseFrontmatterMarkdown(markdown); - const slug = deriveImportedSkillSlug(parsed.frontmatter, slugFallback); - const source = deriveImportedSkillSource(parsed.frontmatter, slug); - const inventory = Object.keys(normalizedFiles).filter((entry) => entry === skillPath || (skillDir ? entry.startsWith(`${skillDir}/`) : false)).map((entry) => { - const relative3 = entry === skillPath ? "SKILL.md" : entry.slice(skillDir.length + 1); - return { - path: normalizePortablePath(relative3), - kind: classifyInventoryKind(relative3) - }; - }).sort((left, right) => left.path.localeCompare(right.path)); - imports.push({ - key: "", - slug, - name: asString13(parsed.frontmatter.name) ?? slug, - description: asString13(parsed.frontmatter.description), - markdown, - packageDir: skillDir, - sourceType: source.sourceType, - sourceLocator: source.sourceLocator, - sourceRef: source.sourceRef, - trustLevel: deriveTrustLevel(inventory), - compatibility: "compatible", - fileInventory: inventory, - metadata: source.metadata - }); - imports[imports.length - 1].key = deriveCanonicalSkillKey(companyId, imports[imports.length - 1]); - } - return imports; -} -async function walkLocalFiles(root, current, out) { - const entries2 = await fs27.readdir(current, { withFileTypes: true }); - for (const entry of entries2) { - if (entry.name === ".git" || entry.name === "node_modules") continue; - const absolutePath = path34.join(current, entry.name); - if (entry.isDirectory()) { - await walkLocalFiles(root, absolutePath, out); - continue; - } - if (!entry.isFile()) continue; - out.push(normalizePortablePath(path34.relative(root, absolutePath))); - } -} -async function statPath(targetPath) { - return fs27.stat(targetPath).catch(() => null); -} -async function collectLocalSkillInventory(skillDir, mode = "full") { - const skillFilePath = path34.join(skillDir, "SKILL.md"); - const skillFileStat = await statPath(skillFilePath); - if (!skillFileStat?.isFile()) { - throw unprocessable(`No SKILL.md file was found in ${skillDir}.`); - } - const allFiles = /* @__PURE__ */ new Set(["SKILL.md"]); - if (mode === "full") { - const discoveredFiles = []; - await walkLocalFiles(skillDir, skillDir, discoveredFiles); - for (const relativePath of discoveredFiles) { - allFiles.add(relativePath); - } - } else { - for (const relativeDir of PROJECT_ROOT_SKILL_SUBDIRECTORIES) { - const absoluteDir = path34.join(skillDir, relativeDir); - const dirStat = await statPath(absoluteDir); - if (!dirStat?.isDirectory()) continue; - const discoveredFiles = []; - await walkLocalFiles(skillDir, absoluteDir, discoveredFiles); - for (const relativePath of discoveredFiles) { - allFiles.add(relativePath); - } - } - } - return Array.from(allFiles).map((relativePath) => ({ - path: normalizePortablePath(relativePath), - kind: classifyInventoryKind(relativePath) - })).sort((left, right) => left.path.localeCompare(right.path)); -} -async function readLocalSkillImportFromDirectory(companyId, skillDir, options) { - const resolvedSkillDir = path34.resolve(skillDir); - const skillFilePath = path34.join(resolvedSkillDir, "SKILL.md"); - const markdown = await fs27.readFile(skillFilePath, "utf8"); - const parsed = parseFrontmatterMarkdown(markdown); - const slug = deriveImportedSkillSlug(parsed.frontmatter, path34.basename(resolvedSkillDir)); - const parsedMetadata = isPlainRecord3(parsed.frontmatter.metadata) ? parsed.frontmatter.metadata : null; - const skillKey = readCanonicalSkillKey(parsed.frontmatter, parsedMetadata); - const metadata = { - ...skillKey ? { skillKey } : {}, - ...parsedMetadata ?? {}, - sourceKind: "local_path", - ...options?.metadata ?? {} - }; - const inventory = await collectLocalSkillInventory(resolvedSkillDir, options?.inventoryMode ?? "full"); - return { - key: deriveCanonicalSkillKey(companyId, { - slug, - sourceType: "local_path", - sourceLocator: resolvedSkillDir, - metadata - }), - slug, - name: asString13(parsed.frontmatter.name) ?? slug, - description: asString13(parsed.frontmatter.description), - markdown, - packageDir: resolvedSkillDir, - sourceType: "local_path", - sourceLocator: resolvedSkillDir, - sourceRef: null, - trustLevel: deriveTrustLevel(inventory), - compatibility: "compatible", - fileInventory: inventory, - metadata - }; -} -async function discoverProjectWorkspaceSkillDirectories(target) { - const discovered = /* @__PURE__ */ new Map(); - const rootSkillPath = path34.join(target.workspaceCwd, "SKILL.md"); - if ((await statPath(rootSkillPath))?.isFile()) { - discovered.set(path34.resolve(target.workspaceCwd), "project_root"); - } - for (const relativeRoot of PROJECT_SCAN_DIRECTORY_ROOTS) { - const absoluteRoot = path34.join(target.workspaceCwd, relativeRoot); - const rootStat = await statPath(absoluteRoot); - if (!rootStat?.isDirectory()) continue; - const entries2 = await fs27.readdir(absoluteRoot, { withFileTypes: true }).catch(() => []); - for (const entry of entries2) { - if (!entry.isDirectory()) continue; - const absoluteSkillDir = path34.resolve(absoluteRoot, entry.name); - if (!(await statPath(path34.join(absoluteSkillDir, "SKILL.md")))?.isFile()) continue; - discovered.set(absoluteSkillDir, "full"); - } - } - return Array.from(discovered.entries()).map(([skillDir, inventoryMode]) => ({ skillDir, inventoryMode })).sort((left, right) => left.skillDir.localeCompare(right.skillDir)); -} -async function readLocalSkillImports(companyId, sourcePath) { - const resolvedPath2 = path34.resolve(sourcePath); - const stat5 = await fs27.stat(resolvedPath2).catch(() => null); - if (!stat5) { - throw unprocessable(`Skill source path does not exist: ${sourcePath}`); - } - if (stat5.isFile()) { - const markdown = await fs27.readFile(resolvedPath2, "utf8"); - const parsed = parseFrontmatterMarkdown(markdown); - const slug = deriveImportedSkillSlug(parsed.frontmatter, path34.basename(path34.dirname(resolvedPath2))); - const parsedMetadata = isPlainRecord3(parsed.frontmatter.metadata) ? parsed.frontmatter.metadata : null; - const skillKey = readCanonicalSkillKey(parsed.frontmatter, parsedMetadata); - const metadata = { - ...skillKey ? { skillKey } : {}, - ...parsedMetadata ?? {}, - sourceKind: "local_path" - }; - const inventory = [ - { path: "SKILL.md", kind: "skill" } - ]; - return [{ - key: deriveCanonicalSkillKey(companyId, { - slug, - sourceType: "local_path", - sourceLocator: path34.dirname(resolvedPath2), - metadata - }), - slug, - name: asString13(parsed.frontmatter.name) ?? slug, - description: asString13(parsed.frontmatter.description), - markdown, - packageDir: path34.dirname(resolvedPath2), - sourceType: "local_path", - sourceLocator: path34.dirname(resolvedPath2), - sourceRef: null, - trustLevel: deriveTrustLevel(inventory), - compatibility: "compatible", - fileInventory: inventory, - metadata - }]; - } - const root = resolvedPath2; - const allFiles = []; - await walkLocalFiles(root, root, allFiles); - const skillPaths = allFiles.filter((entry) => path34.posix.basename(entry).toLowerCase() === "skill.md"); - if (skillPaths.length === 0) { - throw unprocessable("No SKILL.md files were found in the provided path."); - } - const imports = []; - for (const skillPath of skillPaths) { - const skillDir = path34.posix.dirname(skillPath); - const inventory = allFiles.filter((entry) => entry === skillPath || entry.startsWith(`${skillDir}/`)).map((entry) => { - const relative3 = entry === skillPath ? "SKILL.md" : entry.slice(skillDir.length + 1); - return { - path: normalizePortablePath(relative3), - kind: classifyInventoryKind(relative3) - }; - }).sort((left, right) => left.path.localeCompare(right.path)); - const imported = await readLocalSkillImportFromDirectory(companyId, path34.join(root, skillDir)); - imported.fileInventory = inventory; - imported.trustLevel = deriveTrustLevel(inventory); - imports.push(imported); - } - return imports; -} -async function readUrlSkillImports(companyId, sourceUrl, requestedSkillSlug = null) { - const url2 = sourceUrl.trim(); - const warnings = []; - const looksLikeRepoUrl = (() => { - try { - const parsed = new URL(url2); - if (parsed.protocol !== "https:") return false; - const h5 = parsed.hostname.toLowerCase(); - if (h5.endsWith(".githubusercontent.com") || h5 === "gist.github.com") return false; - const segments = parsed.pathname.split("/").filter(Boolean); - return segments.length >= 2 && !parsed.pathname.endsWith(".md"); - } catch { - return false; - } - })(); - if (looksLikeRepoUrl) { - const parsed = parseGitHubSourceUrl(url2); - const apiBase = gitHubApiBase(parsed.hostname); - const { pinnedRef, trackingRef } = await resolveGitHubPinnedRef(parsed); - let ref = pinnedRef; - const tree = await fetchJson( - `${apiBase}/repos/${parsed.owner}/${parsed.repo}/git/trees/${ref}?recursive=1` - ).catch(() => { - throw unprocessable(`Failed to read GitHub tree for ${url2}`); - }); - const allPaths = (tree.tree ?? []).filter((entry) => entry.type === "blob").map((entry) => entry.path).filter((entry) => typeof entry === "string"); - const basePrefix = parsed.basePath ? `${parsed.basePath.replace(/^\/+|\/+$/g, "")}/` : ""; - const scopedPaths = basePrefix ? allPaths.filter((entry) => entry.startsWith(basePrefix)) : allPaths; - const relativePaths = scopedPaths.map((entry) => basePrefix ? entry.slice(basePrefix.length) : entry); - const filteredPaths = parsed.filePath ? relativePaths.filter((entry) => entry === path34.posix.relative(parsed.basePath || ".", parsed.filePath)) : relativePaths; - const skillPaths = filteredPaths.filter( - (entry) => path34.posix.basename(entry).toLowerCase() === "skill.md" - ); - if (skillPaths.length === 0) { - throw unprocessable( - "No SKILL.md files were found in the provided GitHub source." - ); - } - const skills = []; - for (const relativeSkillPath of skillPaths) { - const repoSkillPath = basePrefix ? `${basePrefix}${relativeSkillPath}` : relativeSkillPath; - const markdown = await fetchText(resolveRawGitHubUrl(parsed.hostname, parsed.owner, parsed.repo, ref, repoSkillPath)); - const parsedMarkdown = parseFrontmatterMarkdown(markdown); - const skillDir = path34.posix.dirname(relativeSkillPath); - const slug = deriveImportedSkillSlug(parsedMarkdown.frontmatter, path34.posix.basename(skillDir)); - const skillKey = readCanonicalSkillKey( - parsedMarkdown.frontmatter, - isPlainRecord3(parsedMarkdown.frontmatter.metadata) ? parsedMarkdown.frontmatter.metadata : null - ); - if (requestedSkillSlug && !matchesRequestedSkill(relativeSkillPath, requestedSkillSlug) && slug !== requestedSkillSlug) { - continue; - } - const metadata = { - ...skillKey ? { skillKey } : {}, - sourceKind: "github", - ...parsed.hostname !== "github.com" ? { hostname: parsed.hostname } : {}, - owner: parsed.owner, - repo: parsed.repo, - ref, - trackingRef, - repoSkillDir: normalizeGitHubSkillDirectory( - basePrefix ? `${basePrefix}${skillDir}` : skillDir, - slug - ) - }; - const inventory = filteredPaths.filter((entry) => entry === relativeSkillPath || entry.startsWith(`${skillDir}/`)).map((entry) => ({ - path: entry === relativeSkillPath ? "SKILL.md" : entry.slice(skillDir.length + 1), - kind: classifyInventoryKind(entry === relativeSkillPath ? "SKILL.md" : entry.slice(skillDir.length + 1)) - })).sort((left, right) => left.path.localeCompare(right.path)); - skills.push({ - key: deriveCanonicalSkillKey(companyId, { - slug, - sourceType: "github", - sourceLocator: sourceUrl, - metadata - }), - slug, - name: asString13(parsedMarkdown.frontmatter.name) ?? slug, - description: asString13(parsedMarkdown.frontmatter.description), - markdown, - sourceType: "github", - sourceLocator: sourceUrl, - sourceRef: ref, - trustLevel: deriveTrustLevel(inventory), - compatibility: "compatible", - fileInventory: inventory, - metadata - }); - } - if (skills.length === 0) { - throw unprocessable( - requestedSkillSlug ? `Skill ${requestedSkillSlug} was not found in the provided GitHub source.` : "No SKILL.md files were found in the provided GitHub source." - ); - } - return { skills, warnings }; - } - if (url2.startsWith("http://") || url2.startsWith("https://")) { - const markdown = await fetchText(url2); - const parsedMarkdown = parseFrontmatterMarkdown(markdown); - const urlObj = new URL(url2); - const fileName = path34.posix.basename(urlObj.pathname); - const slug = deriveImportedSkillSlug(parsedMarkdown.frontmatter, fileName.replace(/\.md$/i, "")); - const skillKey = readCanonicalSkillKey( - parsedMarkdown.frontmatter, - isPlainRecord3(parsedMarkdown.frontmatter.metadata) ? parsedMarkdown.frontmatter.metadata : null - ); - const metadata = { - ...skillKey ? { skillKey } : {}, - sourceKind: "url" - }; - const inventory = [{ path: "SKILL.md", kind: "skill" }]; - return { - skills: [{ - key: deriveCanonicalSkillKey(companyId, { - slug, - sourceType: "url", - sourceLocator: url2, - metadata - }), - slug, - name: asString13(parsedMarkdown.frontmatter.name) ?? slug, - description: asString13(parsedMarkdown.frontmatter.description), - markdown, - sourceType: "url", - sourceLocator: url2, - sourceRef: null, - trustLevel: deriveTrustLevel(inventory), - compatibility: "compatible", - fileInventory: inventory, - metadata - }], - warnings - }; - } - throw unprocessable("Unsupported skill source. Use a local path or URL."); -} -function toCompanySkill(row) { - return { - ...row, - description: row.description ?? null, - sourceType: row.sourceType, - sourceLocator: row.sourceLocator ?? null, - sourceRef: row.sourceRef ?? null, - trustLevel: row.trustLevel, - compatibility: row.compatibility, - fileInventory: Array.isArray(row.fileInventory) ? row.fileInventory.flatMap((entry) => { - if (!isPlainRecord3(entry)) return []; - return [{ - path: String(entry.path ?? ""), - kind: String(entry.kind ?? "other") - }]; - }) : [], - metadata: isPlainRecord3(row.metadata) ? row.metadata : null - }; -} -function serializeFileInventory(fileInventory) { - return fileInventory.map((entry) => ({ - path: entry.path, - kind: entry.kind - })); -} -function getSkillMeta(skill) { - return isPlainRecord3(skill.metadata) ? skill.metadata : {}; -} -function resolveSkillReference(skills, reference) { - const trimmed = reference.trim(); - if (!trimmed) { - return { skill: null, ambiguous: false }; - } - const byId = skills.find((skill) => skill.id === trimmed); - if (byId) { - return { skill: byId, ambiguous: false }; - } - const normalizedKey = normalizeSkillKey(trimmed); - if (normalizedKey) { - const byKey = skills.find((skill) => skill.key === normalizedKey); - if (byKey) { - return { skill: byKey, ambiguous: false }; - } - } - const normalizedSlug = normalizeSkillSlug2(trimmed); - if (!normalizedSlug) { - return { skill: null, ambiguous: false }; - } - const bySlug = skills.filter((skill) => skill.slug === normalizedSlug); - if (bySlug.length === 1) { - return { skill: bySlug[0] ?? null, ambiguous: false }; - } - if (bySlug.length > 1) { - return { skill: null, ambiguous: true }; - } - return { skill: null, ambiguous: false }; -} -function resolveRequestedSkillKeysOrThrow(skills, requestedReferences) { - const missing = /* @__PURE__ */ new Set(); - const ambiguous = /* @__PURE__ */ new Set(); - const resolved = /* @__PURE__ */ new Set(); - for (const reference of requestedReferences) { - const trimmed = reference.trim(); - if (!trimmed) continue; - const match = resolveSkillReference(skills, trimmed); - if (match.skill) { - resolved.add(match.skill.key); - continue; - } - if (match.ambiguous) { - ambiguous.add(trimmed); - continue; - } - missing.add(trimmed); - } - if (ambiguous.size > 0 || missing.size > 0) { - const problems = []; - if (ambiguous.size > 0) { - problems.push(`ambiguous references: ${Array.from(ambiguous).sort().join(", ")}`); - } - if (missing.size > 0) { - problems.push(`unknown references: ${Array.from(missing).sort().join(", ")}`); - } - throw unprocessable(`Invalid company skill selection (${problems.join("; ")}).`); - } - return Array.from(resolved); -} -function resolveDesiredSkillKeys(skills, config3) { - const preference = readTaskcoreSkillSyncPreference(config3); - return Array.from(new Set( - preference.desiredSkills.map((reference) => resolveSkillReference(skills, reference).skill?.key ?? normalizeSkillKey(reference)).filter((value) => Boolean(value)) - )); -} -function normalizeSkillDirectory(skill) { - if (skill.sourceType !== "local_path" && skill.sourceType !== "catalog" || !skill.sourceLocator) return null; - const resolved = path34.resolve(skill.sourceLocator); - if (path34.basename(resolved).toLowerCase() === "skill.md") { - return path34.dirname(resolved); - } - return resolved; -} -function normalizeSourceLocatorDirectory(sourceLocator) { - if (!sourceLocator) return null; - const resolved = path34.resolve(sourceLocator); - return path34.basename(resolved).toLowerCase() === "skill.md" ? path34.dirname(resolved) : resolved; -} -async function findMissingLocalSkillIds(skills) { - const missingIds = []; - for (const skill of skills) { - if (skill.sourceType !== "local_path") continue; - const skillDir = normalizeSourceLocatorDirectory(skill.sourceLocator); - if (!skillDir) { - missingIds.push(skill.id); - continue; - } - const skillDirStat = await statPath(skillDir); - const skillFileStat = await statPath(path34.join(skillDir, "SKILL.md")); - if (!skillDirStat?.isDirectory() || !skillFileStat?.isFile()) { - missingIds.push(skill.id); - } - } - return missingIds; -} -function resolveManagedSkillsRoot(companyId) { - return path34.resolve(resolveTaskcoreInstanceRoot(), "skills", companyId); -} -function resolveLocalSkillFilePath(skill, relativePath) { - const normalized = normalizePortablePath(relativePath); - const skillDir = normalizeSkillDirectory(skill); - if (skillDir) { - return path34.resolve(skillDir, normalized); - } - if (!skill.sourceLocator) return null; - const fallbackRoot = path34.resolve(skill.sourceLocator); - const directPath = path34.resolve(fallbackRoot, normalized); - return directPath; -} -function inferLanguageFromPath(filePath) { - const fileName = path34.posix.basename(filePath).toLowerCase(); - if (fileName === "skill.md" || fileName.endsWith(".md")) return "markdown"; - if (fileName.endsWith(".ts")) return "typescript"; - if (fileName.endsWith(".tsx")) return "tsx"; - if (fileName.endsWith(".js")) return "javascript"; - if (fileName.endsWith(".jsx")) return "jsx"; - if (fileName.endsWith(".json")) return "json"; - if (fileName.endsWith(".yml") || fileName.endsWith(".yaml")) return "yaml"; - if (fileName.endsWith(".sh")) return "bash"; - if (fileName.endsWith(".py")) return "python"; - if (fileName.endsWith(".html")) return "html"; - if (fileName.endsWith(".css")) return "css"; - return null; -} -function isMarkdownPath(filePath) { - const fileName = path34.posix.basename(filePath).toLowerCase(); - return fileName === "skill.md" || fileName.endsWith(".md"); -} -function deriveSkillSourceInfo(skill) { - const metadata = getSkillMeta(skill); - const localSkillDir = normalizeSkillDirectory(skill); - if (metadata.sourceKind === "taskcore_bundled") { - return { - editable: false, - editableReason: "Bundled Taskcore skills are read-only.", - sourceLabel: "Taskcore bundled", - sourceBadge: "taskcore", - sourcePath: null - }; - } - if (skill.sourceType === "skills_sh") { - const owner = asString13(metadata.owner) ?? null; - const repo = asString13(metadata.repo) ?? null; - return { - editable: false, - editableReason: "Skills.sh-managed skills are read-only.", - sourceLabel: skill.sourceLocator ?? (owner && repo ? `${owner}/${repo}` : null), - sourceBadge: "skills_sh", - sourcePath: null - }; - } - if (skill.sourceType === "github") { - const owner = asString13(metadata.owner) ?? null; - const repo = asString13(metadata.repo) ?? null; - return { - editable: false, - editableReason: "Remote GitHub skills are read-only. Fork or import locally to edit them.", - sourceLabel: owner && repo ? `${owner}/${repo}` : skill.sourceLocator, - sourceBadge: "github", - sourcePath: null - }; - } - if (skill.sourceType === "url") { - return { - editable: false, - editableReason: "URL-based skills are read-only. Save them locally to edit them.", - sourceLabel: skill.sourceLocator, - sourceBadge: "url", - sourcePath: null - }; - } - if (skill.sourceType === "local_path") { - const managedRoot = resolveManagedSkillsRoot(skill.companyId); - const projectName = asString13(metadata.projectName); - const workspaceName = asString13(metadata.workspaceName); - const isProjectScan = metadata.sourceKind === "project_scan"; - if (localSkillDir && localSkillDir.startsWith(managedRoot)) { - return { - editable: true, - editableReason: null, - sourceLabel: "Taskcore workspace", - sourceBadge: "taskcore", - sourcePath: managedRoot - }; - } - return { - editable: true, - editableReason: null, - sourceLabel: isProjectScan ? [projectName, workspaceName].filter((value) => Boolean(value)).join(" / ") || skill.sourceLocator : skill.sourceLocator, - sourceBadge: "local", - sourcePath: null - }; - } - return { - editable: false, - editableReason: "This skill source is read-only.", - sourceLabel: skill.sourceLocator, - sourceBadge: "catalog", - sourcePath: null - }; -} -function enrichSkill(skill, attachedAgentCount, usedByAgents = []) { - const source = deriveSkillSourceInfo(skill); - return { - ...skill, - attachedAgentCount, - usedByAgents, - ...source - }; -} -function toCompanySkillListItem(skill, attachedAgentCount) { - const source = deriveSkillSourceInfo(skill); - return { - id: skill.id, - companyId: skill.companyId, - key: skill.key, - slug: skill.slug, - name: skill.name, - description: skill.description, - sourceType: skill.sourceType, - sourceLocator: skill.sourceLocator, - sourceRef: skill.sourceRef, - trustLevel: skill.trustLevel, - compatibility: skill.compatibility, - fileInventory: skill.fileInventory, - createdAt: skill.createdAt, - updatedAt: skill.updatedAt, - attachedAgentCount, - editable: source.editable, - editableReason: source.editableReason, - sourceLabel: source.sourceLabel, - sourceBadge: source.sourceBadge, - sourcePath: source.sourcePath - }; -} -function companySkillService(db) { - const agents2 = agentService(db); - const projects2 = projectService(db); - const secretsSvc = secretService(db); - async function ensureBundledSkills(companyId) { - for (const skillsRoot of resolveBundledSkillsRoot()) { - const stats = await fs27.stat(skillsRoot).catch(() => null); - if (!stats?.isDirectory()) continue; - const bundledSkills = await readLocalSkillImports(companyId, skillsRoot).then((skills) => skills.map((skill) => ({ - ...skill, - key: deriveCanonicalSkillKey(companyId, { - ...skill, - metadata: { - ...skill.metadata ?? {}, - sourceKind: "taskcore_bundled" - } - }), - metadata: { - ...skill.metadata ?? {}, - sourceKind: "taskcore_bundled" - } - }))).catch(() => []); - if (bundledSkills.length === 0) continue; - return upsertImportedSkills(companyId, bundledSkills); - } - return []; - } - async function pruneMissingLocalPathSkills(companyId) { - const rows = await db.select().from(companySkills).where(eq(companySkills.companyId, companyId)); - const skills = rows.map((row) => toCompanySkill(row)); - const missingIds = new Set(await findMissingLocalSkillIds(skills)); - if (missingIds.size === 0) return; - for (const skill of skills) { - if (!missingIds.has(skill.id)) continue; - await db.delete(companySkills).where(eq(companySkills.id, skill.id)); - await fs27.rm(resolveRuntimeSkillMaterializedPath(companyId, skill), { recursive: true, force: true }); - } - } - async function ensureSkillInventoryCurrent(companyId) { - const existingRefresh = skillInventoryRefreshPromises.get(companyId); - if (existingRefresh) { - await existingRefresh; - return; - } - const refreshPromise = (async () => { - await ensureBundledSkills(companyId); - await pruneMissingLocalPathSkills(companyId); - })(); - skillInventoryRefreshPromises.set(companyId, refreshPromise); - try { - await refreshPromise; - } finally { - if (skillInventoryRefreshPromises.get(companyId) === refreshPromise) { - skillInventoryRefreshPromises.delete(companyId); - } - } - } - async function list2(companyId) { - const rows = await listFull(companyId); - const agentRows = await agents2.list(companyId); - return rows.map((skill) => { - const attachedAgentCount = agentRows.filter((agent) => { - const desiredSkills = resolveDesiredSkillKeys(rows, agent.adapterConfig); - return desiredSkills.includes(skill.key); - }).length; - return toCompanySkillListItem(skill, attachedAgentCount); - }); - } - async function listFull(companyId) { - await ensureSkillInventoryCurrent(companyId); - const rows = await db.select().from(companySkills).where(eq(companySkills.companyId, companyId)).orderBy(asc(companySkills.name), asc(companySkills.key)); - return rows.map((row) => toCompanySkill(row)); - } - async function getById(id) { - const row = await db.select().from(companySkills).where(eq(companySkills.id, id)).then((rows) => rows[0] ?? null); - return row ? toCompanySkill(row) : null; - } - async function getByKey(companyId, key) { - const row = await db.select().from(companySkills).where(and(eq(companySkills.companyId, companyId), eq(companySkills.key, key))).then((rows) => rows[0] ?? null); - return row ? toCompanySkill(row) : null; - } - async function usage(companyId, key) { - const skills = await listFull(companyId); - const agentRows = await agents2.list(companyId); - const desiredAgents = agentRows.filter((agent) => { - const desiredSkills = resolveDesiredSkillKeys(skills, agent.adapterConfig); - return desiredSkills.includes(key); - }); - return Promise.all( - desiredAgents.map(async (agent) => { - const adapter = findActiveServerAdapter(agent.adapterType); - let actualState = null; - if (!adapter?.listSkills) { - actualState = "unsupported"; - } else { - try { - const { config: runtimeConfig } = await secretsSvc.resolveAdapterConfigForRuntime( - agent.companyId, - agent.adapterConfig - ); - const runtimeSkillEntries = await listRuntimeSkillEntries(agent.companyId); - const snapshot = await adapter.listSkills({ - agentId: agent.id, - companyId: agent.companyId, - adapterType: agent.adapterType, - config: { - ...runtimeConfig, - taskcoreRuntimeSkills: runtimeSkillEntries - } - }); - actualState = snapshot.entries.find((entry) => entry.key === key)?.state ?? (snapshot.supported ? "missing" : "unsupported"); - } catch { - actualState = "unknown"; - } - } - return { - id: agent.id, - name: agent.name, - urlKey: agent.urlKey, - adapterType: agent.adapterType, - desired: true, - actualState - }; - }) - ); - } - async function detail(companyId, id) { - await ensureSkillInventoryCurrent(companyId); - const skill = await getById(id); - if (!skill || skill.companyId !== companyId) return null; - const usedByAgents = await usage(companyId, skill.key); - return enrichSkill(skill, usedByAgents.length, usedByAgents); - } - async function updateStatus(companyId, skillId) { - await ensureSkillInventoryCurrent(companyId); - const skill = await getById(skillId); - if (!skill || skill.companyId !== companyId) return null; - if (skill.sourceType !== "github" && skill.sourceType !== "skills_sh") { - return { - supported: false, - reason: "Only GitHub-managed skills support update checks.", - trackingRef: null, - currentRef: skill.sourceRef ?? null, - latestRef: null, - hasUpdate: false - }; - } - const metadata = getSkillMeta(skill); - const owner = asString13(metadata.owner); - const repo = asString13(metadata.repo); - const trackingRef = asString13(metadata.trackingRef) ?? asString13(metadata.ref); - if (!owner || !repo || !trackingRef) { - return { - supported: false, - reason: "This GitHub skill does not have enough metadata to track updates.", - trackingRef: trackingRef ?? null, - currentRef: skill.sourceRef ?? null, - latestRef: null, - hasUpdate: false - }; - } - const hostname3 = asString13(metadata.hostname) || "github.com"; - const apiBase = gitHubApiBase(hostname3); - const latestRef = await resolveGitHubCommitSha(owner, repo, trackingRef, apiBase); - return { - supported: true, - reason: null, - trackingRef, - currentRef: skill.sourceRef ?? null, - latestRef, - hasUpdate: latestRef !== (skill.sourceRef ?? null) - }; - } - async function readFile5(companyId, skillId, relativePath) { - await ensureSkillInventoryCurrent(companyId); - const skill = await getById(skillId); - if (!skill || skill.companyId !== companyId) return null; - const normalizedPath = normalizePortablePath(relativePath || "SKILL.md"); - const fileEntry = skill.fileInventory.find((entry) => entry.path === normalizedPath); - if (!fileEntry) { - throw notFound("Skill file not found"); - } - const source = deriveSkillSourceInfo(skill); - let content = ""; - if (skill.sourceType === "local_path" || skill.sourceType === "catalog") { - const absolutePath = resolveLocalSkillFilePath(skill, normalizedPath); - if (absolutePath) { - content = await fs27.readFile(absolutePath, "utf8"); - } else if (normalizedPath === "SKILL.md") { - content = skill.markdown; - } else { - throw notFound("Skill file not found"); - } - } else if (skill.sourceType === "github" || skill.sourceType === "skills_sh") { - const metadata = getSkillMeta(skill); - const owner = asString13(metadata.owner); - const repo = asString13(metadata.repo); - const hostname3 = asString13(metadata.hostname) || "github.com"; - const ref = skill.sourceRef ?? asString13(metadata.ref) ?? "main"; - const repoSkillDir = normalizeGitHubSkillDirectory(asString13(metadata.repoSkillDir), skill.slug); - if (!owner || !repo) { - throw unprocessable("Skill source metadata is incomplete."); - } - const repoPath = normalizePortablePath(path34.posix.join(repoSkillDir, normalizedPath)); - content = await fetchText(resolveRawGitHubUrl(hostname3, owner, repo, ref, repoPath)); - } else if (skill.sourceType === "url") { - if (normalizedPath !== "SKILL.md") { - throw notFound("This skill source only exposes SKILL.md"); - } - content = skill.markdown; - } else { - throw unprocessable("Unsupported skill source."); - } - return { - skillId: skill.id, - path: normalizedPath, - kind: fileEntry.kind, - content, - language: inferLanguageFromPath(normalizedPath), - markdown: isMarkdownPath(normalizedPath), - editable: source.editable - }; - } - async function createLocalSkill(companyId, input) { - const slug = normalizeSkillSlug2(input.slug ?? input.name) ?? "skill"; - const managedRoot = resolveManagedSkillsRoot(companyId); - const skillDir = path34.resolve(managedRoot, slug); - const skillFilePath = path34.resolve(skillDir, "SKILL.md"); - await fs27.mkdir(skillDir, { recursive: true }); - const markdown = input.markdown?.trim().length ? input.markdown : [ - "---", - `name: ${input.name}`, - ...input.description?.trim() ? [`description: ${input.description.trim()}`] : [], - "---", - "", - `# ${input.name}`, - "", - input.description?.trim() ? input.description.trim() : "Describe what this skill does.", - "" - ].join("\n"); - await fs27.writeFile(skillFilePath, markdown, "utf8"); - const parsed = parseFrontmatterMarkdown(markdown); - const imported = await upsertImportedSkills(companyId, [{ - key: `company/${companyId}/${slug}`, - slug, - name: asString13(parsed.frontmatter.name) ?? input.name, - description: asString13(parsed.frontmatter.description) ?? input.description?.trim() ?? null, - markdown, - sourceType: "local_path", - sourceLocator: skillDir, - sourceRef: null, - trustLevel: "markdown_only", - compatibility: "compatible", - fileInventory: [{ path: "SKILL.md", kind: "skill" }], - metadata: { sourceKind: "managed_local" } - }]); - return imported[0]; - } - async function updateFile(companyId, skillId, relativePath, content) { - await ensureSkillInventoryCurrent(companyId); - const skill = await getById(skillId); - if (!skill || skill.companyId !== companyId) throw notFound("Skill not found"); - const source = deriveSkillSourceInfo(skill); - if (!source.editable || skill.sourceType !== "local_path") { - throw unprocessable(source.editableReason ?? "This skill cannot be edited."); - } - const normalizedPath = normalizePortablePath(relativePath); - const absolutePath = resolveLocalSkillFilePath(skill, normalizedPath); - if (!absolutePath) throw notFound("Skill file not found"); - await fs27.mkdir(path34.dirname(absolutePath), { recursive: true }); - await fs27.writeFile(absolutePath, content, "utf8"); - if (normalizedPath === "SKILL.md") { - const parsed = parseFrontmatterMarkdown(content); - await db.update(companySkills).set({ - name: asString13(parsed.frontmatter.name) ?? skill.name, - description: asString13(parsed.frontmatter.description) ?? skill.description, - markdown: content, - updatedAt: /* @__PURE__ */ new Date() - }).where(eq(companySkills.id, skill.id)); - } else { - await db.update(companySkills).set({ updatedAt: /* @__PURE__ */ new Date() }).where(eq(companySkills.id, skill.id)); - } - const detail2 = await readFile5(companyId, skillId, normalizedPath); - if (!detail2) throw notFound("Skill file not found"); - return detail2; - } - async function installUpdate(companyId, skillId) { - await ensureSkillInventoryCurrent(companyId); - const skill = await getById(skillId); - if (!skill || skill.companyId !== companyId) return null; - const status = await updateStatus(companyId, skillId); - if (!status?.supported) { - throw unprocessable(status?.reason ?? "This skill does not support updates."); - } - if (!skill.sourceLocator) { - throw unprocessable("Skill source locator is missing."); - } - const result = await readUrlSkillImports(companyId, skill.sourceLocator, skill.slug); - const matching = result.skills.find((entry) => entry.key === skill.key) ?? result.skills[0] ?? null; - if (!matching) { - throw unprocessable(`Skill ${skill.key} could not be re-imported from its source.`); - } - const imported = await upsertImportedSkills(companyId, [matching]); - return imported[0] ?? null; - } - async function scanProjectWorkspaces(companyId, input = {}) { - await ensureSkillInventoryCurrent(companyId); - const projectRows = input.projectIds?.length ? await projects2.listByIds(companyId, input.projectIds) : await projects2.list(companyId); - const workspaceFilter = new Set(input.workspaceIds ?? []); - const skipped = []; - const conflicts = []; - const warnings = []; - const imported = []; - const updated = []; - const availableSkills = await listFull(companyId); - const acceptedSkills = [...availableSkills]; - const acceptedByKey = new Map(acceptedSkills.map((skill) => [skill.key, skill])); - const scanTargets = []; - const scannedProjectIds = /* @__PURE__ */ new Set(); - let discovered = 0; - const trackWarning = (message2) => { - warnings.push(message2); - return message2; - }; - const upsertAcceptedSkill = (skill) => { - const nextIndex = acceptedSkills.findIndex((entry) => entry.id === skill.id || entry.key === skill.key); - if (nextIndex >= 0) acceptedSkills[nextIndex] = skill; - else acceptedSkills.push(skill); - acceptedByKey.set(skill.key, skill); - }; - for (const project of projectRows) { - for (const workspace of project.workspaces) { - if (workspaceFilter.size > 0 && !workspaceFilter.has(workspace.id)) continue; - const workspaceCwd = asString13(workspace.cwd); - if (!workspaceCwd) { - skipped.push({ - projectId: project.id, - projectName: project.name, - workspaceId: workspace.id, - workspaceName: workspace.name, - path: null, - reason: trackWarning(`Skipped ${project.name} / ${workspace.name}: no local workspace path is configured.`) - }); - continue; - } - const workspaceStat = await statPath(workspaceCwd); - if (!workspaceStat?.isDirectory()) { - skipped.push({ - projectId: project.id, - projectName: project.name, - workspaceId: workspace.id, - workspaceName: workspace.name, - path: workspaceCwd, - reason: trackWarning(`Skipped ${project.name} / ${workspace.name}: local workspace path is not available at ${workspaceCwd}.`) - }); - continue; - } - scanTargets.push({ - projectId: project.id, - projectName: project.name, - workspaceId: workspace.id, - workspaceName: workspace.name, - workspaceCwd - }); - } - } - for (const target of scanTargets) { - scannedProjectIds.add(target.projectId); - const directories = await discoverProjectWorkspaceSkillDirectories(target); - for (const directory of directories) { - discovered += 1; - let nextSkill; - try { - nextSkill = await readLocalSkillImportFromDirectory(companyId, directory.skillDir, { - inventoryMode: directory.inventoryMode, - metadata: { - sourceKind: "project_scan", - projectId: target.projectId, - projectName: target.projectName, - workspaceId: target.workspaceId, - workspaceName: target.workspaceName, - workspaceCwd: target.workspaceCwd - } - }); - } catch (error50) { - const message2 = error50 instanceof Error ? error50.message : String(error50); - skipped.push({ - projectId: target.projectId, - projectName: target.projectName, - workspaceId: target.workspaceId, - workspaceName: target.workspaceName, - path: directory.skillDir, - reason: trackWarning(`Skipped ${directory.skillDir}: ${message2}`) - }); - continue; - } - const normalizedSourceDir = normalizeSourceLocatorDirectory(nextSkill.sourceLocator); - const existingByKey = acceptedByKey.get(nextSkill.key) ?? null; - if (existingByKey) { - const existingSourceDir = normalizeSkillDirectory(existingByKey); - if (existingByKey.sourceType !== "local_path" || !existingSourceDir || !normalizedSourceDir || existingSourceDir !== normalizedSourceDir) { - conflicts.push({ - slug: nextSkill.slug, - key: nextSkill.key, - projectId: target.projectId, - projectName: target.projectName, - workspaceId: target.workspaceId, - workspaceName: target.workspaceName, - path: directory.skillDir, - existingSkillId: existingByKey.id, - existingSkillKey: existingByKey.key, - existingSourceLocator: existingByKey.sourceLocator, - reason: `Skill key ${nextSkill.key} already points at ${existingByKey.sourceLocator ?? "another source"}.` - }); - continue; - } - const persisted2 = (await upsertImportedSkills(companyId, [nextSkill]))[0]; - if (!persisted2) continue; - updated.push(persisted2); - upsertAcceptedSkill(persisted2); - continue; - } - const slugConflict = acceptedSkills.find((skill) => { - if (skill.slug !== nextSkill.slug) return false; - return normalizeSkillDirectory(skill) !== normalizedSourceDir; - }); - if (slugConflict) { - conflicts.push({ - slug: nextSkill.slug, - key: nextSkill.key, - projectId: target.projectId, - projectName: target.projectName, - workspaceId: target.workspaceId, - workspaceName: target.workspaceName, - path: directory.skillDir, - existingSkillId: slugConflict.id, - existingSkillKey: slugConflict.key, - existingSourceLocator: slugConflict.sourceLocator, - reason: `Slug ${nextSkill.slug} is already in use by ${slugConflict.sourceLocator ?? slugConflict.key}.` - }); - continue; - } - const persisted = (await upsertImportedSkills(companyId, [nextSkill]))[0]; - if (!persisted) continue; - imported.push(persisted); - upsertAcceptedSkill(persisted); - } - } - return { - scannedProjects: scannedProjectIds.size, - scannedWorkspaces: scanTargets.length, - discovered, - imported, - updated, - skipped, - conflicts, - warnings - }; - } - async function materializeCatalogSkillFiles(companyId, skill, normalizedFiles) { - const packageDir = skill.packageDir ? normalizePortablePath(skill.packageDir) : null; - if (!packageDir) return null; - const catalogRoot = path34.resolve(resolveManagedSkillsRoot(companyId), "__catalog__"); - const skillDir = path34.resolve(catalogRoot, buildSkillRuntimeName(skill.key, skill.slug)); - await fs27.rm(skillDir, { recursive: true, force: true }); - await fs27.mkdir(skillDir, { recursive: true }); - for (const entry of skill.fileInventory) { - const sourcePath = entry.path === "SKILL.md" ? `${packageDir}/SKILL.md` : `${packageDir}/${entry.path}`; - const content = normalizedFiles[sourcePath]; - if (typeof content !== "string") continue; - const targetPath = path34.resolve(skillDir, entry.path); - await fs27.mkdir(path34.dirname(targetPath), { recursive: true }); - await fs27.writeFile(targetPath, content, "utf8"); - } - return skillDir; - } - async function materializeRuntimeSkillFiles(companyId, skill) { - const runtimeRoot = path34.resolve(resolveManagedSkillsRoot(companyId), "__runtime__"); - const skillDir = path34.resolve(runtimeRoot, buildSkillRuntimeName(skill.key, skill.slug)); - await fs27.rm(skillDir, { recursive: true, force: true }); - await fs27.mkdir(skillDir, { recursive: true }); - for (const entry of skill.fileInventory) { - const detail2 = await readFile5(companyId, skill.id, entry.path).catch(() => null); - if (!detail2) continue; - const targetPath = path34.resolve(skillDir, entry.path); - await fs27.mkdir(path34.dirname(targetPath), { recursive: true }); - await fs27.writeFile(targetPath, detail2.content, "utf8"); - } - return skillDir; - } - function resolveRuntimeSkillMaterializedPath(companyId, skill) { - const runtimeRoot = path34.resolve(resolveManagedSkillsRoot(companyId), "__runtime__"); - return path34.resolve(runtimeRoot, buildSkillRuntimeName(skill.key, skill.slug)); - } - async function listRuntimeSkillEntries(companyId, options = {}) { - const skills = await listFull(companyId); - const out = []; - for (const skill of skills) { - const sourceKind = asString13(getSkillMeta(skill).sourceKind); - let source = normalizeSkillDirectory(skill); - if (!source) { - source = options.materializeMissing === false ? resolveRuntimeSkillMaterializedPath(companyId, skill) : await materializeRuntimeSkillFiles(companyId, skill).catch(() => null); - } - if (!source) continue; - const required2 = sourceKind === "taskcore_bundled"; - out.push({ - key: skill.key, - runtimeName: buildSkillRuntimeName(skill.key, skill.slug), - source, - required: required2, - requiredReason: required2 ? "Bundled Taskcore skills are always available for local adapters." : null - }); - } - out.sort((left, right) => left.key.localeCompare(right.key)); - return out; - } - async function importPackageFiles(companyId, files, options) { - await ensureSkillInventoryCurrent(companyId); - const normalizedFiles = normalizePackageFileMap(files); - const importedSkills = readInlineSkillImports(companyId, normalizedFiles); - if (importedSkills.length === 0) return []; - for (const skill of importedSkills) { - if (skill.sourceType !== "catalog") continue; - const materializedDir = await materializeCatalogSkillFiles(companyId, skill, normalizedFiles); - if (materializedDir) { - skill.sourceLocator = materializedDir; - } - } - const conflictStrategy = options?.onConflict ?? "replace"; - const existingSkills = await listFull(companyId); - const existingByKey = new Map(existingSkills.map((skill) => [skill.key, skill])); - const existingBySlug = new Map( - existingSkills.map((skill) => [normalizeSkillSlug2(skill.slug) ?? skill.slug, skill]) - ); - const usedSlugs = new Set(existingBySlug.keys()); - const usedKeys = new Set(existingByKey.keys()); - const toPersist = []; - const prepared = []; - const out = []; - for (const importedSkill of importedSkills) { - const originalKey = importedSkill.key; - const originalSlug = importedSkill.slug; - const normalizedSlug = normalizeSkillSlug2(importedSkill.slug) ?? importedSkill.slug; - const existingByIncomingKey = existingByKey.get(importedSkill.key) ?? null; - const existingByIncomingSlug = existingBySlug.get(normalizedSlug) ?? null; - const conflict2 = existingByIncomingKey ?? existingByIncomingSlug; - if (!conflict2 || conflictStrategy === "replace") { - toPersist.push(importedSkill); - prepared.push({ - skill: importedSkill, - originalKey, - originalSlug, - existingBefore: existingByIncomingKey, - actionHint: existingByIncomingKey ? "updated" : "created", - reason: existingByIncomingKey ? "Existing skill key matched; replace strategy." : null - }); - usedSlugs.add(normalizedSlug); - usedKeys.add(importedSkill.key); - continue; - } - if (conflictStrategy === "skip") { - out.push({ - skill: conflict2, - action: "skipped", - originalKey, - originalSlug, - requestedRefs: Array.from(/* @__PURE__ */ new Set([originalKey, originalSlug])), - reason: "Existing skill matched; skip strategy." - }); - continue; - } - const renamedSlug = uniqueSkillSlug(normalizedSlug || "skill", usedSlugs); - const renamedKey = uniqueImportedSkillKey(companyId, renamedSlug, usedKeys); - const renamedSkill = { - ...importedSkill, - slug: renamedSlug, - key: renamedKey, - metadata: { - ...importedSkill.metadata ?? {}, - skillKey: renamedKey, - importedFromSkillKey: originalKey, - importedFromSkillSlug: originalSlug - } - }; - toPersist.push(renamedSkill); - prepared.push({ - skill: renamedSkill, - originalKey, - originalSlug, - existingBefore: null, - actionHint: "created", - reason: `Existing skill matched; renamed to ${renamedSlug}.` - }); - usedSlugs.add(renamedSlug); - usedKeys.add(renamedKey); - } - if (toPersist.length === 0) return out; - const persisted = await upsertImportedSkills(companyId, toPersist); - for (let index2 = 0; index2 < prepared.length; index2 += 1) { - const persistedSkill = persisted[index2]; - const preparedSkill = prepared[index2]; - if (!persistedSkill || !preparedSkill) continue; - out.push({ - skill: persistedSkill, - action: preparedSkill.actionHint, - originalKey: preparedSkill.originalKey, - originalSlug: preparedSkill.originalSlug, - requestedRefs: Array.from(/* @__PURE__ */ new Set([preparedSkill.originalKey, preparedSkill.originalSlug])), - reason: preparedSkill.reason - }); - } - return out; - } - async function upsertImportedSkills(companyId, imported) { - const out = []; - for (const skill of imported) { - const existing = await getByKey(companyId, skill.key); - const existingMeta = existing ? getSkillMeta(existing) : {}; - const incomingMeta = skill.metadata && isPlainRecord3(skill.metadata) ? skill.metadata : {}; - const incomingOwner = asString13(incomingMeta.owner); - const incomingRepo = asString13(incomingMeta.repo); - const incomingKind = asString13(incomingMeta.sourceKind); - if (existing && existingMeta.sourceKind === "taskcore_bundled" && incomingKind === "github" && incomingOwner === "taskcore" && incomingRepo === "taskcore") { - out.push(existing); - continue; - } - const metadata = { - ...skill.metadata ?? {}, - skillKey: skill.key - }; - const values2 = { - companyId, - key: skill.key, - slug: skill.slug, - name: skill.name, - description: skill.description, - markdown: skill.markdown, - sourceType: skill.sourceType, - sourceLocator: skill.sourceLocator, - sourceRef: skill.sourceRef, - trustLevel: skill.trustLevel, - compatibility: skill.compatibility, - fileInventory: serializeFileInventory(skill.fileInventory), - metadata, - updatedAt: /* @__PURE__ */ new Date() - }; - const row = existing ? await db.update(companySkills).set(values2).where(eq(companySkills.id, existing.id)).returning().then((rows) => rows[0] ?? null) : await db.insert(companySkills).values(values2).returning().then((rows) => rows[0] ?? null); - if (!row) throw notFound("Failed to persist company skill"); - out.push(toCompanySkill(row)); - } - return out; - } - async function importFromSource(companyId, source) { - await ensureSkillInventoryCurrent(companyId); - const parsed = parseSkillImportSourceInput(source); - const local = !/^https?:\/\//i.test(parsed.resolvedSource); - const { skills, warnings } = local ? { - skills: (await readLocalSkillImports(companyId, parsed.resolvedSource)).filter((skill) => !parsed.requestedSkillSlug || skill.slug === parsed.requestedSkillSlug), - warnings: parsed.warnings - } : await readUrlSkillImports(companyId, parsed.resolvedSource, parsed.requestedSkillSlug).then((result) => ({ - skills: result.skills, - warnings: [...parsed.warnings, ...result.warnings] - })); - const filteredSkills = parsed.requestedSkillSlug ? skills.filter((skill) => skill.slug === parsed.requestedSkillSlug) : skills; - if (filteredSkills.length === 0) { - throw unprocessable( - parsed.requestedSkillSlug ? `Skill ${parsed.requestedSkillSlug} was not found in the provided source.` : "No skills were found in the provided source." - ); - } - if (parsed.originalSkillsShUrl) { - for (const skill of filteredSkills) { - skill.sourceType = "skills_sh"; - skill.sourceLocator = parsed.originalSkillsShUrl; - if (skill.metadata) { - skill.metadata.sourceKind = "skills_sh"; - } - skill.key = deriveCanonicalSkillKey(companyId, skill); - } - } - const imported = await upsertImportedSkills(companyId, filteredSkills); - return { imported, warnings }; - } - async function deleteSkill(companyId, skillId) { - const row = await db.select().from(companySkills).where(and(eq(companySkills.id, skillId), eq(companySkills.companyId, companyId))).then((rows) => rows[0] ?? null); - if (!row) return null; - const skill = toCompanySkill(row); - const usedByAgents = await usage(companyId, skill.key); - if (usedByAgents.length > 0) { - const agentNames = usedByAgents.map((agent) => agent.name).sort((left, right) => left.localeCompare(right)); - throw unprocessable( - `Cannot delete skill "${skill.name}" while it is still used by ${agentNames.join(", ")}. Detach it from those agents first.`, - { - skillId: skill.id, - skillKey: skill.key, - usedByAgents: usedByAgents.map((agent) => ({ - id: agent.id, - name: agent.name, - urlKey: agent.urlKey, - adapterType: agent.adapterType - })) - } - ); - } - await db.delete(companySkills).where(eq(companySkills.id, skillId)); - await fs27.rm(resolveRuntimeSkillMaterializedPath(companyId, skill), { recursive: true, force: true }); - return skill; - } - return { - list: list2, - listFull, - getById, - getByKey, - resolveRequestedSkillKeys: async (companyId, requestedReferences) => { - const skills = await listFull(companyId); - return resolveRequestedSkillKeysOrThrow(skills, requestedReferences); - }, - detail, - updateStatus, - readFile: readFile5, - updateFile, - createLocalSkill, - deleteSkill, - importFromSource, - scanProjectWorkspaces, - importPackageFiles, - installUpdate, - listRuntimeSkillEntries - }; -} - -// server/src/services/assets.ts -init_drizzle_orm(); -init_src2(); -function assetService(db) { - return { - create: (companyId, data2) => db.insert(assets).values({ ...data2, companyId }).returning().then((rows) => rows[0]), - getById: (id) => db.select().from(assets).where(eq(assets.id, id)).then((rows) => rows[0] ?? null) - }; -} - -// server/src/services/documents.ts -init_drizzle_orm(); -init_src2(); -function normalizeDocumentKey(key) { - const normalized = key.trim().toLowerCase(); - const parsed = issueDocumentKeySchema.safeParse(normalized); - if (!parsed.success) { - throw unprocessable("Invalid document key", parsed.error.issues); - } - return parsed.data; -} -function isUniqueViolation(error50) { - return !!error50 && typeof error50 === "object" && "code" in error50 && error50.code === "23505"; -} -function extractLegacyPlanBody(description) { - if (!description) return null; - const match = /\s*([\s\S]*?)\s*<\/plan>/i.exec(description); - if (!match) return null; - const body = match[1]?.trim(); - return body ? body : null; -} -function mapIssueDocumentRow(row, includeBody) { - return { - id: row.id, - companyId: row.companyId, - issueId: row.issueId, - key: row.key, - title: row.title, - format: row.format, - ...includeBody ? { body: row.latestBody } : {}, - latestRevisionId: row.latestRevisionId ?? null, - latestRevisionNumber: row.latestRevisionNumber, - createdByAgentId: row.createdByAgentId, - createdByUserId: row.createdByUserId, - updatedByAgentId: row.updatedByAgentId, - updatedByUserId: row.updatedByUserId, - createdAt: row.createdAt, - updatedAt: row.updatedAt - }; -} -var issueDocumentSelect = { - id: documents.id, - companyId: documents.companyId, - issueId: issueDocuments.issueId, - key: issueDocuments.key, - title: documents.title, - format: documents.format, - latestBody: documents.latestBody, - latestRevisionId: documents.latestRevisionId, - latestRevisionNumber: documents.latestRevisionNumber, - createdByAgentId: documents.createdByAgentId, - createdByUserId: documents.createdByUserId, - updatedByAgentId: documents.updatedByAgentId, - updatedByUserId: documents.updatedByUserId, - createdAt: documents.createdAt, - updatedAt: documents.updatedAt -}; -function documentService(db) { - return { - getIssueDocumentPayload: async (issue2) => { - const [planDocument, documentSummaries] = await Promise.all([ - db.select(issueDocumentSelect).from(issueDocuments).innerJoin(documents, eq(issueDocuments.documentId, documents.id)).where(and(eq(issueDocuments.issueId, issue2.id), eq(issueDocuments.key, "plan"))).then((rows) => rows[0] ?? null), - db.select(issueDocumentSelect).from(issueDocuments).innerJoin(documents, eq(issueDocuments.documentId, documents.id)).where(eq(issueDocuments.issueId, issue2.id)).orderBy(asc(issueDocuments.key), desc(documents.updatedAt)) - ]); - const legacyPlanBody = planDocument ? null : extractLegacyPlanBody(issue2.description); - return { - planDocument: planDocument ? mapIssueDocumentRow(planDocument, true) : null, - documentSummaries: documentSummaries.map((row) => mapIssueDocumentRow(row, false)), - legacyPlanDocument: legacyPlanBody ? { - key: "plan", - body: legacyPlanBody, - source: "issue_description" - } : null - }; - }, - listIssueDocuments: async (issueId) => { - const rows = await db.select(issueDocumentSelect).from(issueDocuments).innerJoin(documents, eq(issueDocuments.documentId, documents.id)).where(eq(issueDocuments.issueId, issueId)).orderBy(asc(issueDocuments.key), desc(documents.updatedAt)); - return rows.map((row) => mapIssueDocumentRow(row, true)); - }, - getIssueDocumentByKey: async (issueId, rawKey) => { - const key = normalizeDocumentKey(rawKey); - const row = await db.select(issueDocumentSelect).from(issueDocuments).innerJoin(documents, eq(issueDocuments.documentId, documents.id)).where(and(eq(issueDocuments.issueId, issueId), eq(issueDocuments.key, key))).then((rows) => rows[0] ?? null); - return row ? mapIssueDocumentRow(row, true) : null; - }, - listIssueDocumentRevisions: async (issueId, rawKey) => { - const key = normalizeDocumentKey(rawKey); - return db.select({ - id: documentRevisions.id, - companyId: documentRevisions.companyId, - documentId: documentRevisions.documentId, - issueId: issueDocuments.issueId, - key: issueDocuments.key, - revisionNumber: documentRevisions.revisionNumber, - title: documentRevisions.title, - format: documentRevisions.format, - body: documentRevisions.body, - changeSummary: documentRevisions.changeSummary, - createdByAgentId: documentRevisions.createdByAgentId, - createdByUserId: documentRevisions.createdByUserId, - createdAt: documentRevisions.createdAt - }).from(issueDocuments).innerJoin(documents, eq(issueDocuments.documentId, documents.id)).innerJoin(documentRevisions, eq(documentRevisions.documentId, documents.id)).where(and(eq(issueDocuments.issueId, issueId), eq(issueDocuments.key, key))).orderBy(desc(documentRevisions.revisionNumber)); - }, - upsertIssueDocument: async (input) => { - const key = normalizeDocumentKey(input.key); - const issue2 = await db.select({ id: issues.id, companyId: issues.companyId }).from(issues).where(eq(issues.id, input.issueId)).then((rows) => rows[0] ?? null); - if (!issue2) throw notFound("Issue not found"); - try { - return await db.transaction(async (tx) => { - const now2 = /* @__PURE__ */ new Date(); - const existing = await tx.select({ - id: documents.id, - companyId: documents.companyId, - issueId: issueDocuments.issueId, - key: issueDocuments.key, - title: documents.title, - format: documents.format, - latestBody: documents.latestBody, - latestRevisionId: documents.latestRevisionId, - latestRevisionNumber: documents.latestRevisionNumber, - createdByAgentId: documents.createdByAgentId, - createdByUserId: documents.createdByUserId, - updatedByAgentId: documents.updatedByAgentId, - updatedByUserId: documents.updatedByUserId, - createdAt: documents.createdAt, - updatedAt: documents.updatedAt - }).from(issueDocuments).innerJoin(documents, eq(issueDocuments.documentId, documents.id)).where(and(eq(issueDocuments.issueId, issue2.id), eq(issueDocuments.key, key))).then((rows) => rows[0] ?? null); - if (existing) { - if (!input.baseRevisionId) { - throw conflict("Document update requires baseRevisionId", { - currentRevisionId: existing.latestRevisionId - }); - } - if (input.baseRevisionId !== existing.latestRevisionId) { - throw conflict("Document was updated by someone else", { - currentRevisionId: existing.latestRevisionId - }); - } - const nextRevisionNumber = existing.latestRevisionNumber + 1; - const [revision2] = await tx.insert(documentRevisions).values({ - companyId: issue2.companyId, - documentId: existing.id, - revisionNumber: nextRevisionNumber, - title: input.title ?? null, - format: input.format, - body: input.body, - changeSummary: input.changeSummary ?? null, - createdByAgentId: input.createdByAgentId ?? null, - createdByUserId: input.createdByUserId ?? null, - createdByRunId: input.createdByRunId ?? null, - createdAt: now2 - }).returning(); - await tx.update(documents).set({ - title: input.title ?? null, - format: input.format, - latestBody: input.body, - latestRevisionId: revision2.id, - latestRevisionNumber: nextRevisionNumber, - updatedByAgentId: input.createdByAgentId ?? null, - updatedByUserId: input.createdByUserId ?? null, - updatedAt: now2 - }).where(eq(documents.id, existing.id)); - await tx.update(issueDocuments).set({ updatedAt: now2 }).where(eq(issueDocuments.documentId, existing.id)); - return { - created: false, - document: { - ...existing, - title: input.title ?? null, - format: input.format, - body: input.body, - latestRevisionId: revision2.id, - latestRevisionNumber: nextRevisionNumber, - updatedByAgentId: input.createdByAgentId ?? null, - updatedByUserId: input.createdByUserId ?? null, - updatedAt: now2 - } - }; - } - if (input.baseRevisionId) { - throw conflict("Document does not exist yet", { key }); - } - const [document2] = await tx.insert(documents).values({ - companyId: issue2.companyId, - title: input.title ?? null, - format: input.format, - latestBody: input.body, - latestRevisionId: null, - latestRevisionNumber: 1, - createdByAgentId: input.createdByAgentId ?? null, - createdByUserId: input.createdByUserId ?? null, - updatedByAgentId: input.createdByAgentId ?? null, - updatedByUserId: input.createdByUserId ?? null, - createdAt: now2, - updatedAt: now2 - }).returning(); - const [revision] = await tx.insert(documentRevisions).values({ - companyId: issue2.companyId, - documentId: document2.id, - revisionNumber: 1, - title: input.title ?? null, - format: input.format, - body: input.body, - changeSummary: input.changeSummary ?? null, - createdByAgentId: input.createdByAgentId ?? null, - createdByUserId: input.createdByUserId ?? null, - createdByRunId: input.createdByRunId ?? null, - createdAt: now2 - }).returning(); - await tx.update(documents).set({ latestRevisionId: revision.id }).where(eq(documents.id, document2.id)); - await tx.insert(issueDocuments).values({ - companyId: issue2.companyId, - issueId: issue2.id, - documentId: document2.id, - key, - createdAt: now2, - updatedAt: now2 - }); - return { - created: true, - document: { - id: document2.id, - companyId: issue2.companyId, - issueId: issue2.id, - key, - title: document2.title, - format: document2.format, - body: document2.latestBody, - latestRevisionId: revision.id, - latestRevisionNumber: 1, - createdByAgentId: document2.createdByAgentId, - createdByUserId: document2.createdByUserId, - updatedByAgentId: document2.updatedByAgentId, - updatedByUserId: document2.updatedByUserId, - createdAt: document2.createdAt, - updatedAt: document2.updatedAt - } - }; - }); - } catch (error50) { - if (isUniqueViolation(error50)) { - throw conflict("Document key already exists on this issue", { key }); - } - throw error50; - } - }, - restoreIssueDocumentRevision: async (input) => { - const key = normalizeDocumentKey(input.key); - return db.transaction(async (tx) => { - const existing = await tx.select(issueDocumentSelect).from(issueDocuments).innerJoin(documents, eq(issueDocuments.documentId, documents.id)).where(and(eq(issueDocuments.issueId, input.issueId), eq(issueDocuments.key, key))).then((rows) => rows[0] ?? null); - if (!existing) throw notFound("Document not found"); - const revision = await tx.select({ - id: documentRevisions.id, - companyId: documentRevisions.companyId, - documentId: documentRevisions.documentId, - revisionNumber: documentRevisions.revisionNumber, - title: documentRevisions.title, - format: documentRevisions.format, - body: documentRevisions.body - }).from(documentRevisions).where(and(eq(documentRevisions.id, input.revisionId), eq(documentRevisions.documentId, existing.id))).then((rows) => rows[0] ?? null); - if (!revision) throw notFound("Document revision not found"); - if (existing.latestRevisionId === revision.id) { - throw conflict("Selected revision is already the latest revision", { - currentRevisionId: existing.latestRevisionId - }); - } - const now2 = /* @__PURE__ */ new Date(); - const nextRevisionNumber = existing.latestRevisionNumber + 1; - const [restoredRevision] = await tx.insert(documentRevisions).values({ - companyId: existing.companyId, - documentId: existing.id, - revisionNumber: nextRevisionNumber, - title: revision.title ?? null, - format: revision.format, - body: revision.body, - changeSummary: `Restored from revision ${revision.revisionNumber}`, - createdByAgentId: input.createdByAgentId ?? null, - createdByUserId: input.createdByUserId ?? null, - createdAt: now2 - }).returning(); - await tx.update(documents).set({ - title: revision.title ?? null, - format: revision.format, - latestBody: revision.body, - latestRevisionId: restoredRevision.id, - latestRevisionNumber: nextRevisionNumber, - updatedByAgentId: input.createdByAgentId ?? null, - updatedByUserId: input.createdByUserId ?? null, - updatedAt: now2 - }).where(eq(documents.id, existing.id)); - await tx.update(issueDocuments).set({ updatedAt: now2 }).where(eq(issueDocuments.documentId, existing.id)); - return { - restoredFromRevisionId: revision.id, - restoredFromRevisionNumber: revision.revisionNumber, - document: { - ...existing, - title: revision.title ?? null, - format: revision.format, - body: revision.body, - latestRevisionId: restoredRevision.id, - latestRevisionNumber: nextRevisionNumber, - updatedByAgentId: input.createdByAgentId ?? null, - updatedByUserId: input.createdByUserId ?? null, - updatedAt: now2 - } - }; - }); - }, - deleteIssueDocument: async (issueId, rawKey) => { - const key = normalizeDocumentKey(rawKey); - return db.transaction(async (tx) => { - const existing = await tx.select(issueDocumentSelect).from(issueDocuments).innerJoin(documents, eq(issueDocuments.documentId, documents.id)).where(and(eq(issueDocuments.issueId, issueId), eq(issueDocuments.key, key))).then((rows) => rows[0] ?? null); - if (!existing) return null; - await tx.delete(issueDocuments).where(eq(issueDocuments.documentId, existing.id)); - await tx.delete(documents).where(eq(documents.id, existing.id)); - return { - ...existing, - body: existing.latestBody, - latestRevisionId: existing.latestRevisionId ?? null - }; - }); - } - }; -} - -// server/src/services/issues.ts -init_drizzle_orm(); -init_src2(); - -// server/src/services/issue-goal-fallback.ts -function resolveIssueGoalId(input) { - if (input.goalId) return input.goalId; - if (input.projectId) return input.projectGoalId ?? null; - return input.defaultGoalId ?? null; -} -function resolveNextIssueGoalId(input) { - const projectId = input.projectId !== void 0 ? input.projectId : input.currentProjectId; - const projectGoalId = input.projectGoalId !== void 0 ? input.projectGoalId : projectId ? input.currentProjectGoalId : null; - const resolveFallbackGoalId = (targetProjectId, targetProjectGoalId) => { - if (targetProjectId) return targetProjectGoalId ?? null; - return input.defaultGoalId ?? null; - }; - if (input.goalId !== void 0) { - return input.goalId ?? resolveFallbackGoalId(projectId, projectGoalId); - } - const currentFallbackGoalId = resolveFallbackGoalId( - input.currentProjectId, - input.currentProjectGoalId - ); - const nextFallbackGoalId = resolveFallbackGoalId(projectId, projectGoalId); - if (!input.currentGoalId) { - return nextFallbackGoalId; - } - if (input.currentGoalId === currentFallbackGoalId) { - return nextFallbackGoalId; - } - return input.currentGoalId; -} - -// server/src/services/goals.ts -init_drizzle_orm(); -init_src2(); -async function getDefaultCompanyGoal(db, companyId) { - const activeRootGoal = await db.select().from(goals).where( - and( - eq(goals.companyId, companyId), - eq(goals.level, "company"), - eq(goals.status, "active"), - isNull(goals.parentId) - ) - ).orderBy(asc(goals.createdAt)).then((rows) => rows[0] ?? null); - if (activeRootGoal) return activeRootGoal; - const anyRootGoal = await db.select().from(goals).where( - and( - eq(goals.companyId, companyId), - eq(goals.level, "company"), - isNull(goals.parentId) - ) - ).orderBy(asc(goals.createdAt)).then((rows) => rows[0] ?? null); - if (anyRootGoal) return anyRootGoal; - return db.select().from(goals).where(and(eq(goals.companyId, companyId), eq(goals.level, "company"))).orderBy(asc(goals.createdAt)).then((rows) => rows[0] ?? null); -} -function goalService(db) { - return { - list: (companyId) => db.select().from(goals).where(eq(goals.companyId, companyId)), - getById: (id) => db.select().from(goals).where(eq(goals.id, id)).then((rows) => rows[0] ?? null), - getDefaultCompanyGoal: (companyId) => getDefaultCompanyGoal(db, companyId), - create: (companyId, data2) => db.insert(goals).values({ ...data2, companyId }).returning().then((rows) => rows[0]), - update: (id, data2) => db.update(goals).set({ ...data2, updatedAt: /* @__PURE__ */ new Date() }).where(eq(goals.id, id)).returning().then((rows) => rows[0] ?? null), - remove: (id) => db.delete(goals).where(eq(goals.id, id)).returning().then((rows) => rows[0] ?? null) - }; -} - -// server/src/services/issues.ts -var ALL_ISSUE_STATUSES = ["backlog", "todo", "in_progress", "in_review", "blocked", "done", "cancelled"]; -var MAX_ISSUE_COMMENT_PAGE_LIMIT = 500; -function assertTransition(from, to) { - if (from === to) return; - if (!ALL_ISSUE_STATUSES.includes(to)) { - throw conflict(`Unknown issue status: ${to}`); - } -} -function applyStatusSideEffects(status, patch) { - if (!status) return patch; - if (status === "in_progress" && !patch.startedAt) { - patch.startedAt = /* @__PURE__ */ new Date(); - } - if (status === "done") { - patch.completedAt = /* @__PURE__ */ new Date(); - } - if (status === "cancelled") { - patch.cancelledAt = /* @__PURE__ */ new Date(); - } - return patch; -} -function sameRunLock(checkoutRunId, actorRunId) { - if (actorRunId) return checkoutRunId === actorRunId; - return checkoutRunId == null; -} -var TERMINAL_HEARTBEAT_RUN_STATUSES = /* @__PURE__ */ new Set(["succeeded", "failed", "cancelled", "timed_out"]); -function escapeLikePattern(value) { - return value.replace(/[\\%_]/g, "\\$&"); -} -async function getProjectDefaultGoalId(db, companyId, projectId) { - if (!projectId) return null; - const row = await db.select({ goalId: projects.goalId }).from(projects).where(and(eq(projects.id, projectId), eq(projects.companyId, companyId))).then((rows) => rows[0] ?? null); - return row?.goalId ?? null; -} -async function getWorkspaceInheritanceIssue(db, companyId, issueId) { - const issue2 = await db.select({ - id: issues.id, - projectId: issues.projectId, - projectWorkspaceId: issues.projectWorkspaceId, - executionWorkspaceId: issues.executionWorkspaceId, - executionWorkspaceSettings: issues.executionWorkspaceSettings - }).from(issues).where(and(eq(issues.id, issueId), eq(issues.companyId, companyId))).then((rows) => rows[0] ?? null); - if (!issue2) { - throw notFound("Workspace inheritance issue not found"); - } - return issue2; -} -function touchedByUserCondition(companyId, userId) { - return sql` - ( - ${issues.createdByUserId} = ${userId} - OR ${issues.assigneeUserId} = ${userId} - OR EXISTS ( - SELECT 1 - FROM ${issueReadStates} - WHERE ${issueReadStates.issueId} = ${issues.id} - AND ${issueReadStates.companyId} = ${companyId} - AND ${issueReadStates.userId} = ${userId} - ) - OR EXISTS ( - SELECT 1 - FROM ${issueComments} - WHERE ${issueComments.issueId} = ${issues.id} - AND ${issueComments.companyId} = ${companyId} - AND ${issueComments.authorUserId} = ${userId} - ) - ) - `; -} -function participatedByAgentCondition(companyId, agentId) { - return sql` - ( - ${issues.createdByAgentId} = ${agentId} - OR ${issues.assigneeAgentId} = ${agentId} - OR EXISTS ( - SELECT 1 - FROM ${issueComments} - WHERE ${issueComments.issueId} = ${issues.id} - AND ${issueComments.companyId} = ${companyId} - AND ${issueComments.authorAgentId} = ${agentId} - ) - OR EXISTS ( - SELECT 1 - FROM ${activityLog} - WHERE ${activityLog.companyId} = ${companyId} - AND ${activityLog.entityType} = 'issue' - AND ${activityLog.entityId} = ${issues.id}::text - AND ${activityLog.agentId} = ${agentId} - ) - ) - `; -} -function myLastCommentAtExpr(companyId, userId) { - return sql` - ( - SELECT MAX(${issueComments.createdAt}) - FROM ${issueComments} - WHERE ${issueComments.issueId} = ${issues.id} - AND ${issueComments.companyId} = ${companyId} - AND ${issueComments.authorUserId} = ${userId} - ) - `; -} -function myLastReadAtExpr(companyId, userId) { - return sql` - ( - SELECT MAX(${issueReadStates.lastReadAt}) - FROM ${issueReadStates} - WHERE ${issueReadStates.issueId} = ${issues.id} - AND ${issueReadStates.companyId} = ${companyId} - AND ${issueReadStates.userId} = ${userId} - ) - `; -} -function myLastTouchAtExpr(companyId, userId) { - const myLastCommentAt = myLastCommentAtExpr(companyId, userId); - const myLastReadAt = myLastReadAtExpr(companyId, userId); - return sql` - GREATEST( - COALESCE(${myLastCommentAt}, to_timestamp(0)), - COALESCE(${myLastReadAt}, to_timestamp(0)), - COALESCE(CASE WHEN ${issues.createdByUserId} = ${userId} THEN ${issues.createdAt} ELSE NULL END, to_timestamp(0)), - COALESCE(CASE WHEN ${issues.assigneeUserId} = ${userId} THEN ${issues.updatedAt} ELSE NULL END, to_timestamp(0)) - ) - `; -} -function lastExternalCommentAtExpr(companyId, userId) { - return sql` - ( - SELECT MAX(${issueComments.createdAt}) - FROM ${issueComments} - WHERE ${issueComments.issueId} = ${issues.id} - AND ${issueComments.companyId} = ${companyId} - AND ( - ${issueComments.authorUserId} IS NULL - OR ${issueComments.authorUserId} <> ${userId} - ) - ) - `; -} -function issueLastActivityAtExpr(companyId, userId) { - const lastExternalCommentAt = lastExternalCommentAtExpr(companyId, userId); - const myLastTouchAt = myLastTouchAtExpr(companyId, userId); - return sql` - GREATEST( - COALESCE(${lastExternalCommentAt}, to_timestamp(0)), - CASE - WHEN ${issues.updatedAt} > COALESCE(${myLastTouchAt}, to_timestamp(0)) - THEN ${issues.updatedAt} - ELSE to_timestamp(0) - END - ) - `; -} -var ISSUE_LOCAL_INBOX_ACTIVITY_ACTIONS = [ - "issue.read_marked", - "issue.read_unmarked", - "issue.inbox_archived", - "issue.inbox_unarchived" -]; -function issueLatestCommentAtExpr(companyId) { - return sql` - ( - SELECT MAX(${issueComments.createdAt}) - FROM ${issueComments} - WHERE ${issueComments.issueId} = ${issues.id} - AND ${issueComments.companyId} = ${companyId} - ) - `; -} -function issueLatestLogAtExpr(companyId) { - return sql` - ( - SELECT MAX(${activityLog.createdAt}) - FROM ${activityLog} - WHERE ${activityLog.companyId} = ${companyId} - AND ${activityLog.entityType} = 'issue' - AND ${activityLog.entityId} = ${issues.id}::text - AND ${activityLog.action} NOT IN (${sql.join( - ISSUE_LOCAL_INBOX_ACTIVITY_ACTIONS.map((action) => sql`${action}`), - sql`, ` - )}) - ) - `; -} -function issueCanonicalLastActivityAtExpr(companyId) { - const latestCommentAt = issueLatestCommentAtExpr(companyId); - const latestLogAt = issueLatestLogAtExpr(companyId); - return sql` - GREATEST( - ${issues.updatedAt}, - COALESCE(${latestCommentAt}, to_timestamp(0)), - COALESCE(${latestLogAt}, to_timestamp(0)) - ) - `; -} -function unreadForUserCondition(companyId, userId) { - const touchedCondition = touchedByUserCondition(companyId, userId); - const myLastTouchAt = myLastTouchAtExpr(companyId, userId); - return sql` - ( - ${touchedCondition} - AND EXISTS ( - SELECT 1 - FROM ${issueComments} - WHERE ${issueComments.issueId} = ${issues.id} - AND ${issueComments.companyId} = ${companyId} - AND ( - ${issueComments.authorUserId} IS NULL - OR ${issueComments.authorUserId} <> ${userId} - ) - AND ${issueComments.createdAt} > ${myLastTouchAt} - ) - ) - `; -} -function inboxVisibleForUserCondition(companyId, userId) { - const issueLastActivityAt = issueLastActivityAtExpr(companyId, userId); - return sql` - NOT EXISTS ( - SELECT 1 - FROM ${issueInboxArchives} - WHERE ${issueInboxArchives.issueId} = ${issues.id} - AND ${issueInboxArchives.companyId} = ${companyId} - AND ${issueInboxArchives.userId} = ${userId} - AND ${issueInboxArchives.archivedAt} >= ${issueLastActivityAt} - ) - `; -} -var WELL_KNOWN_NAMED_HTML_ENTITIES = { - amp: "&", - apos: "'", - copy: "\xA9", - gt: ">", - lt: "<", - nbsp: "\xA0", - quot: '"', - ensp: "\u2002", - emsp: "\u2003", - thinsp: "\u2009" -}; -function decodeNumericHtmlEntity(digits, radix) { - const n5 = Number.parseInt(digits, radix); - if (Number.isNaN(n5) || n5 < 0 || n5 > 1114111) return null; - try { - return String.fromCodePoint(n5); - } catch { - return null; - } -} -function normalizeAgentMentionToken(raw) { - let s5 = raw.replace(/&#x([0-9a-fA-F]+);/gi, (full, hex4) => decodeNumericHtmlEntity(hex4, 16) ?? full); - s5 = s5.replace(/&#([0-9]+);/g, (full, dec) => decodeNumericHtmlEntity(dec, 10) ?? full); - s5 = s5.replace(/&([a-z][a-z0-9]*);/gi, (full, name) => { - const decoded = WELL_KNOWN_NAMED_HTML_ENTITIES[name.toLowerCase()]; - return decoded !== void 0 ? decoded : full; - }); - return s5.trim(); -} -function deriveIssueUserContext(issue2, userId, stats) { - const normalizeDate = (value) => { - if (!value) return null; - if (value instanceof Date) return Number.isNaN(value.getTime()) ? null : value; - const parsed = new Date(value); - return Number.isNaN(parsed.getTime()) ? null : parsed; - }; - const myLastCommentAt = normalizeDate(stats?.myLastCommentAt); - const myLastReadAt = normalizeDate(stats?.myLastReadAt); - const createdTouchAt = issue2.createdByUserId === userId ? normalizeDate(issue2.createdAt) : null; - const assignedTouchAt = issue2.assigneeUserId === userId ? normalizeDate(issue2.updatedAt) : null; - const myLastTouchAt = [myLastCommentAt, myLastReadAt, createdTouchAt, assignedTouchAt].filter((value) => value instanceof Date).sort((a5, b6) => b6.getTime() - a5.getTime())[0] ?? null; - const lastExternalCommentAt = normalizeDate(stats?.lastExternalCommentAt); - const isUnreadForMe = Boolean( - myLastTouchAt && lastExternalCommentAt && lastExternalCommentAt.getTime() > myLastTouchAt.getTime() - ); - return { - myLastTouchAt, - lastExternalCommentAt, - isUnreadForMe - }; -} -function latestIssueActivityAt(...values2) { - const normalized = values2.map((value) => { - if (!value) return null; - if (value instanceof Date) return Number.isNaN(value.getTime()) ? null : value; - const parsed = new Date(value); - return Number.isNaN(parsed.getTime()) ? null : parsed; - }).filter((value) => value instanceof Date).sort((a5, b6) => b6.getTime() - a5.getTime()); - return normalized[0] ?? null; -} -async function labelMapForIssues(dbOrTx, issueIds) { - const map4 = /* @__PURE__ */ new Map(); - if (issueIds.length === 0) return map4; - const rows = await dbOrTx.select({ - issueId: issueLabels.issueId, - label: labels - }).from(issueLabels).innerJoin(labels, eq(issueLabels.labelId, labels.id)).where(inArray(issueLabels.issueId, issueIds)).orderBy(asc(labels.name), asc(labels.id)); - for (const row of rows) { - const existing = map4.get(row.issueId); - if (existing) existing.push(row.label); - else map4.set(row.issueId, [row.label]); - } - return map4; -} -async function withIssueLabels(dbOrTx, rows) { - if (rows.length === 0) return []; - const labelsByIssueId = await labelMapForIssues(dbOrTx, rows.map((row) => row.id)); - return rows.map((row) => { - const issueLabels2 = labelsByIssueId.get(row.id) ?? []; - return { - ...row, - labels: issueLabels2, - labelIds: issueLabels2.map((label) => label.id) - }; - }); -} -var ACTIVE_RUN_STATUSES = ["queued", "running"]; -async function activeRunMapForIssues(dbOrTx, issueRows) { - const map4 = /* @__PURE__ */ new Map(); - const runIds = issueRows.map((row) => row.executionRunId).filter((id) => id != null); - if (runIds.length === 0) return map4; - const rows = await dbOrTx.select({ - id: heartbeatRuns.id, - status: heartbeatRuns.status, - agentId: heartbeatRuns.agentId, - invocationSource: heartbeatRuns.invocationSource, - triggerDetail: heartbeatRuns.triggerDetail, - startedAt: heartbeatRuns.startedAt, - finishedAt: heartbeatRuns.finishedAt, - createdAt: heartbeatRuns.createdAt - }).from(heartbeatRuns).where( - and( - inArray(heartbeatRuns.id, runIds), - inArray(heartbeatRuns.status, ACTIVE_RUN_STATUSES) - ) - ); - for (const row of rows) { - map4.set(row.id, row); - } - return map4; -} -function withActiveRuns(issueRows, runMap) { - return issueRows.map((row) => ({ - ...row, - activeRun: row.executionRunId ? runMap.get(row.executionRunId) ?? null : null - })); -} -function issueService(db) { - const instanceSettings2 = instanceSettingsService(db); - async function getIssueByUuid(id) { - const row = await db.select().from(issues).where(eq(issues.id, id)).then((rows) => rows[0] ?? null); - if (!row) return null; - const [enriched] = await withIssueLabels(db, [row]); - return enriched; - } - async function getIssueByIdentifier(identifier) { - const row = await db.select().from(issues).where(eq(issues.identifier, identifier.toUpperCase())).then((rows) => rows[0] ?? null); - if (!row) return null; - const [enriched] = await withIssueLabels(db, [row]); - return enriched; - } - function redactIssueComment(comment, censorUsernameInLogs) { - return { - ...comment, - body: redactCurrentUserText(comment.body, { enabled: censorUsernameInLogs }) - }; - } - async function assertAssignableAgent(companyId, agentId) { - const assignee = await db.select({ - id: agents.id, - companyId: agents.companyId, - status: agents.status - }).from(agents).where(eq(agents.id, agentId)).then((rows) => rows[0] ?? null); - if (!assignee) throw notFound("Assignee agent not found"); - if (assignee.companyId !== companyId) { - throw unprocessable("Assignee must belong to same company"); - } - if (assignee.status === "pending_approval") { - throw conflict("Cannot assign work to pending approval agents"); - } - if (assignee.status === "terminated") { - throw conflict("Cannot assign work to terminated agents"); - } - } - async function assertAssignableUser(companyId, userId) { - const membership = await db.select({ id: companyMemberships.id }).from(companyMemberships).where( - and( - eq(companyMemberships.companyId, companyId), - eq(companyMemberships.principalType, "user"), - eq(companyMemberships.principalId, userId), - eq(companyMemberships.status, "active") - ) - ).then((rows) => rows[0] ?? null); - if (!membership) { - throw notFound("Assignee user not found"); - } - } - async function assertValidProjectWorkspace(companyId, projectId, projectWorkspaceId, dbOrTx = db) { - const workspace = await dbOrTx.select({ - id: projectWorkspaces.id, - companyId: projectWorkspaces.companyId, - projectId: projectWorkspaces.projectId - }).from(projectWorkspaces).where(eq(projectWorkspaces.id, projectWorkspaceId)).then((rows) => rows[0] ?? null); - if (!workspace) throw notFound("Project workspace not found"); - if (workspace.companyId !== companyId) throw unprocessable("Project workspace must belong to same company"); - if (projectId && workspace.projectId !== projectId) { - throw unprocessable("Project workspace must belong to the selected project"); - } - } - async function assertValidExecutionWorkspace(companyId, projectId, executionWorkspaceId, dbOrTx = db) { - const workspace = await dbOrTx.select({ - id: executionWorkspaces.id, - companyId: executionWorkspaces.companyId, - projectId: executionWorkspaces.projectId - }).from(executionWorkspaces).where(eq(executionWorkspaces.id, executionWorkspaceId)).then((rows) => rows[0] ?? null); - if (!workspace) throw notFound("Execution workspace not found"); - if (workspace.companyId !== companyId) throw unprocessable("Execution workspace must belong to same company"); - if (projectId && workspace.projectId !== projectId) { - throw unprocessable("Execution workspace must belong to the selected project"); - } - } - async function assertValidLabelIds(companyId, labelIds, dbOrTx = db) { - if (labelIds.length === 0) return; - const existing = await dbOrTx.select({ id: labels.id }).from(labels).where(and(eq(labels.companyId, companyId), inArray(labels.id, labelIds))); - if (existing.length !== new Set(labelIds).size) { - throw unprocessable("One or more labels are invalid for this company"); - } - } - async function syncIssueLabels(issueId, companyId, labelIds, dbOrTx = db) { - const deduped = [...new Set(labelIds)]; - await assertValidLabelIds(companyId, deduped, dbOrTx); - await dbOrTx.delete(issueLabels).where(eq(issueLabels.issueId, issueId)); - if (deduped.length === 0) return; - await dbOrTx.insert(issueLabels).values( - deduped.map((labelId) => ({ - issueId, - labelId, - companyId - })) - ); - } - async function getIssueRelationSummaryMap(companyId, issueIds, dbOrTx = db) { - const uniqueIssueIds = [...new Set(issueIds)]; - const empty = /* @__PURE__ */ new Map(); - for (const issueId of uniqueIssueIds) { - empty.set(issueId, { blockedBy: [], blocks: [] }); - } - if (uniqueIssueIds.length === 0) return empty; - const [blockedByRows, blockingRows] = await Promise.all([ - dbOrTx.select({ - currentIssueId: issueRelations.relatedIssueId, - relatedId: issues.id, - identifier: issues.identifier, - title: issues.title, - status: issues.status, - priority: issues.priority, - assigneeAgentId: issues.assigneeAgentId, - assigneeUserId: issues.assigneeUserId - }).from(issueRelations).innerJoin(issues, eq(issueRelations.issueId, issues.id)).where( - and( - eq(issueRelations.companyId, companyId), - eq(issueRelations.type, "blocks"), - inArray(issueRelations.relatedIssueId, uniqueIssueIds) - ) - ), - dbOrTx.select({ - currentIssueId: issueRelations.issueId, - relatedId: issues.id, - identifier: issues.identifier, - title: issues.title, - status: issues.status, - priority: issues.priority, - assigneeAgentId: issues.assigneeAgentId, - assigneeUserId: issues.assigneeUserId - }).from(issueRelations).innerJoin(issues, eq(issueRelations.relatedIssueId, issues.id)).where( - and( - eq(issueRelations.companyId, companyId), - eq(issueRelations.type, "blocks"), - inArray(issueRelations.issueId, uniqueIssueIds) - ) - ) - ]); - for (const row of blockedByRows) { - empty.get(row.currentIssueId)?.blockedBy.push({ - id: row.relatedId, - identifier: row.identifier, - title: row.title, - status: row.status, - priority: row.priority, - assigneeAgentId: row.assigneeAgentId, - assigneeUserId: row.assigneeUserId - }); - } - for (const row of blockingRows) { - empty.get(row.currentIssueId)?.blocks.push({ - id: row.relatedId, - identifier: row.identifier, - title: row.title, - status: row.status, - priority: row.priority, - assigneeAgentId: row.assigneeAgentId, - assigneeUserId: row.assigneeUserId - }); - } - for (const relations of empty.values()) { - relations.blockedBy.sort((a5, b6) => a5.title.localeCompare(b6.title)); - relations.blocks.sort((a5, b6) => a5.title.localeCompare(b6.title)); - } - return empty; - } - async function assertNoBlockingCycles(companyId, issueId, blockerIssueIds, dbOrTx = db) { - if (blockerIssueIds.length === 0) return; - const rows = await dbOrTx.select({ - blockerIssueId: issueRelations.issueId, - blockedIssueId: issueRelations.relatedIssueId - }).from(issueRelations).where(and(eq(issueRelations.companyId, companyId), eq(issueRelations.type, "blocks"))); - const adjacency = /* @__PURE__ */ new Map(); - for (const row of rows) { - const list2 = adjacency.get(row.blockerIssueId) ?? []; - list2.push(row.blockedIssueId); - adjacency.set(row.blockerIssueId, list2); - } - for (const blockerIssueId of blockerIssueIds) { - const queue = [...adjacency.get(issueId) ?? []]; - const visited = /* @__PURE__ */ new Set([issueId]); - while (queue.length > 0) { - const current = queue.shift(); - if (current === blockerIssueId) { - throw unprocessable("Blocking relations cannot contain cycles"); - } - if (visited.has(current)) continue; - visited.add(current); - queue.push(...adjacency.get(current) ?? []); - } - } - } - async function syncBlockedByIssueIds(issueId, companyId, blockedByIssueIds, actor = {}, dbOrTx = db) { - const deduped = [...new Set(blockedByIssueIds)]; - if (deduped.some((candidate) => candidate === issueId)) { - throw unprocessable("Issue cannot be blocked by itself"); - } - if (deduped.length > 0) { - const lockedIssueIds = [issueId, ...deduped].sort(); - await dbOrTx.execute( - sql`SELECT ${issues.id} FROM ${issues} - WHERE ${and(eq(issues.companyId, companyId), inArray(issues.id, lockedIssueIds))} - ORDER BY ${issues.id} - FOR UPDATE` - ); - const relatedIssues = await dbOrTx.select({ id: issues.id }).from(issues).where(and(eq(issues.companyId, companyId), inArray(issues.id, deduped))); - if (relatedIssues.length !== deduped.length) { - throw unprocessable("Blocked-by issues must belong to the same company"); - } - await assertNoBlockingCycles(companyId, issueId, deduped, dbOrTx); - } - await dbOrTx.delete(issueRelations).where( - and( - eq(issueRelations.companyId, companyId), - eq(issueRelations.relatedIssueId, issueId), - eq(issueRelations.type, "blocks") - ) - ); - if (deduped.length === 0) return; - await dbOrTx.insert(issueRelations).values( - deduped.map((blockerIssueId) => ({ - companyId, - issueId: blockerIssueId, - relatedIssueId: issueId, - type: "blocks", - createdByAgentId: actor.agentId ?? null, - createdByUserId: actor.userId ?? null - })) - ); - } - async function isTerminalOrMissingHeartbeatRun(runId) { - const run = await db.select({ status: heartbeatRuns.status }).from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)).then((rows) => rows[0] ?? null); - if (!run) return true; - return TERMINAL_HEARTBEAT_RUN_STATUSES.has(run.status); - } - async function adoptStaleCheckoutRun(input) { - const stale = await isTerminalOrMissingHeartbeatRun(input.expectedCheckoutRunId); - if (!stale) return null; - const now2 = /* @__PURE__ */ new Date(); - const adopted = await db.update(issues).set({ - checkoutRunId: input.actorRunId, - executionRunId: input.actorRunId, - executionLockedAt: now2, - updatedAt: now2 - }).where( - and( - eq(issues.id, input.issueId), - eq(issues.status, "in_progress"), - eq(issues.assigneeAgentId, input.actorAgentId), - eq(issues.checkoutRunId, input.expectedCheckoutRunId) - ) - ).returning({ - id: issues.id, - status: issues.status, - assigneeAgentId: issues.assigneeAgentId, - checkoutRunId: issues.checkoutRunId, - executionRunId: issues.executionRunId - }).then((rows) => rows[0] ?? null); - return adopted; - } - return { - list: async (companyId, filters) => { - const conditions = [eq(issues.companyId, companyId)]; - const limit = typeof filters?.limit === "number" && Number.isFinite(filters.limit) ? Math.max(1, Math.floor(filters.limit)) : void 0; - const touchedByUserId = filters?.touchedByUserId?.trim() || void 0; - const inboxArchivedByUserId = filters?.inboxArchivedByUserId?.trim() || void 0; - const unreadForUserId = filters?.unreadForUserId?.trim() || void 0; - const contextUserId = unreadForUserId ?? touchedByUserId ?? inboxArchivedByUserId; - const rawSearch = filters?.q?.trim() ?? ""; - const hasSearch = rawSearch.length > 0; - const escapedSearch = hasSearch ? escapeLikePattern(rawSearch) : ""; - const startsWithPattern = `${escapedSearch}%`; - const containsPattern = `%${escapedSearch}%`; - const titleStartsWithMatch = sql`${issues.title} ILIKE ${startsWithPattern} ESCAPE '\\'`; - const titleContainsMatch = sql`${issues.title} ILIKE ${containsPattern} ESCAPE '\\'`; - const identifierStartsWithMatch = sql`${issues.identifier} ILIKE ${startsWithPattern} ESCAPE '\\'`; - const identifierContainsMatch = sql`${issues.identifier} ILIKE ${containsPattern} ESCAPE '\\'`; - const descriptionContainsMatch = sql`${issues.description} ILIKE ${containsPattern} ESCAPE '\\'`; - const commentContainsMatch = sql` - EXISTS ( - SELECT 1 - FROM ${issueComments} - WHERE ${issueComments.issueId} = ${issues.id} - AND ${issueComments.companyId} = ${companyId} - AND ${issueComments.body} ILIKE ${containsPattern} ESCAPE '\\' - ) - `; - if (filters?.status) { - const statuses = filters.status.split(",").map((s5) => s5.trim()); - conditions.push(statuses.length === 1 ? eq(issues.status, statuses[0]) : inArray(issues.status, statuses)); - } - if (filters?.assigneeAgentId) { - conditions.push(eq(issues.assigneeAgentId, filters.assigneeAgentId)); - } - if (filters?.participantAgentId) { - conditions.push(participatedByAgentCondition(companyId, filters.participantAgentId)); - } - if (filters?.assigneeUserId) { - conditions.push(eq(issues.assigneeUserId, filters.assigneeUserId)); - } - if (touchedByUserId) { - conditions.push(touchedByUserCondition(companyId, touchedByUserId)); - } - if (inboxArchivedByUserId) { - conditions.push(inboxVisibleForUserCondition(companyId, inboxArchivedByUserId)); - } - if (unreadForUserId) { - conditions.push(unreadForUserCondition(companyId, unreadForUserId)); - } - if (filters?.projectId) conditions.push(eq(issues.projectId, filters.projectId)); - if (filters?.executionWorkspaceId) { - conditions.push(eq(issues.executionWorkspaceId, filters.executionWorkspaceId)); - } - if (filters?.parentId) conditions.push(eq(issues.parentId, filters.parentId)); - if (filters?.originKind) conditions.push(eq(issues.originKind, filters.originKind)); - if (filters?.originId) conditions.push(eq(issues.originId, filters.originId)); - if (filters?.labelId) { - const labeledIssueIds = await db.select({ issueId: issueLabels.issueId }).from(issueLabels).where(and(eq(issueLabels.companyId, companyId), eq(issueLabels.labelId, filters.labelId))); - if (labeledIssueIds.length === 0) return []; - conditions.push(inArray(issues.id, labeledIssueIds.map((row) => row.issueId))); - } - if (hasSearch) { - conditions.push( - or( - titleContainsMatch, - identifierContainsMatch, - descriptionContainsMatch, - commentContainsMatch - ) - ); - } - if (!filters?.includeRoutineExecutions && !filters?.originKind && !filters?.originId) { - conditions.push(ne(issues.originKind, "routine_execution")); - } - conditions.push(isNull(issues.hiddenAt)); - const priorityOrder = sql`CASE ${issues.priority} WHEN 'critical' THEN 0 WHEN 'high' THEN 1 WHEN 'medium' THEN 2 WHEN 'low' THEN 3 ELSE 4 END`; - const searchOrder = sql` - CASE - WHEN ${titleStartsWithMatch} THEN 0 - WHEN ${titleContainsMatch} THEN 1 - WHEN ${identifierStartsWithMatch} THEN 2 - WHEN ${identifierContainsMatch} THEN 3 - WHEN ${commentContainsMatch} THEN 4 - WHEN ${descriptionContainsMatch} THEN 5 - ELSE 6 - END - `; - const canonicalLastActivityAt = issueCanonicalLastActivityAtExpr(companyId); - const baseQuery = db.select().from(issues).where(and(...conditions)).orderBy( - hasSearch ? asc(searchOrder) : asc(priorityOrder), - asc(priorityOrder), - desc(canonicalLastActivityAt), - desc(issues.updatedAt) - ); - const rows = limit === void 0 ? await baseQuery : await baseQuery.limit(limit); - const withLabels = await withIssueLabels(db, rows); - const runMap = await activeRunMapForIssues(db, withLabels); - const withRuns = withActiveRuns(withLabels, runMap); - if (withRuns.length === 0) { - return withRuns; - } - const issueIds = withRuns.map((row) => row.id); - const [statsRows, readRows, lastActivityRows] = await Promise.all([ - contextUserId ? db.select({ - issueId: issueComments.issueId, - myLastCommentAt: sql` - MAX(CASE WHEN ${issueComments.authorUserId} = ${contextUserId} THEN ${issueComments.createdAt} END) - `, - lastExternalCommentAt: sql` - MAX( - CASE - WHEN ${issueComments.authorUserId} IS NULL OR ${issueComments.authorUserId} <> ${contextUserId} - THEN ${issueComments.createdAt} - END - ) - ` - }).from(issueComments).where( - and( - eq(issueComments.companyId, companyId), - inArray(issueComments.issueId, issueIds) - ) - ).groupBy(issueComments.issueId) : Promise.resolve([]), - contextUserId ? db.select({ - issueId: issueReadStates.issueId, - myLastReadAt: issueReadStates.lastReadAt - }).from(issueReadStates).where( - and( - eq(issueReadStates.companyId, companyId), - eq(issueReadStates.userId, contextUserId), - inArray(issueReadStates.issueId, issueIds) - ) - ) : Promise.resolve([]), - Promise.all([ - db.select({ - issueId: issueComments.issueId, - latestCommentAt: sql`MAX(${issueComments.createdAt})` - }).from(issueComments).where( - and( - eq(issueComments.companyId, companyId), - inArray(issueComments.issueId, issueIds) - ) - ).groupBy(issueComments.issueId), - db.select({ - issueId: activityLog.entityId, - latestLogAt: sql`MAX(${activityLog.createdAt})` - }).from(activityLog).where( - and( - eq(activityLog.companyId, companyId), - eq(activityLog.entityType, "issue"), - inArray(activityLog.entityId, issueIds), - sql`${activityLog.action} NOT IN (${sql.join( - ISSUE_LOCAL_INBOX_ACTIVITY_ACTIONS.map((action) => sql`${action}`), - sql`, ` - )})` - ) - ).groupBy(activityLog.entityId) - ]).then(([commentRows, logRows]) => { - const byIssueId = /* @__PURE__ */ new Map(); - for (const row of commentRows) { - byIssueId.set(row.issueId, { - issueId: row.issueId, - latestCommentAt: row.latestCommentAt, - latestLogAt: null - }); - } - for (const row of logRows) { - const existing = byIssueId.get(row.issueId); - if (existing) existing.latestLogAt = row.latestLogAt; - else { - byIssueId.set(row.issueId, { - issueId: row.issueId, - latestCommentAt: null, - latestLogAt: row.latestLogAt - }); - } - } - return [...byIssueId.values()]; - }) - ]); - const statsByIssueId = new Map(statsRows.map((row) => [row.issueId, row])); - const lastActivityByIssueId = new Map(lastActivityRows.map((row) => [row.issueId, row])); - if (!contextUserId) { - return withRuns.map((row) => { - const activity = lastActivityByIssueId.get(row.id); - const lastActivityAt = latestIssueActivityAt( - row.updatedAt, - activity?.latestCommentAt ?? null, - activity?.latestLogAt ?? null - ) ?? row.updatedAt; - return { - ...row, - lastActivityAt - }; - }); - } - const readByIssueId = new Map(readRows.map((row) => [row.issueId, row.myLastReadAt])); - return withRuns.map((row) => { - const activity = lastActivityByIssueId.get(row.id); - const lastActivityAt = latestIssueActivityAt( - row.updatedAt, - activity?.latestCommentAt ?? null, - activity?.latestLogAt ?? null - ) ?? row.updatedAt; - return { - ...row, - lastActivityAt, - ...deriveIssueUserContext(row, contextUserId, { - myLastCommentAt: statsByIssueId.get(row.id)?.myLastCommentAt ?? null, - myLastReadAt: readByIssueId.get(row.id) ?? null, - lastExternalCommentAt: statsByIssueId.get(row.id)?.lastExternalCommentAt ?? null - }) - }; - }); - }, - countUnreadTouchedByUser: async (companyId, userId, status) => { - const conditions = [ - eq(issues.companyId, companyId), - isNull(issues.hiddenAt), - unreadForUserCondition(companyId, userId), - ne(issues.originKind, "routine_execution") - ]; - if (status) { - const statuses = status.split(",").map((s5) => s5.trim()).filter(Boolean); - if (statuses.length === 1) { - conditions.push(eq(issues.status, statuses[0])); - } else if (statuses.length > 1) { - conditions.push(inArray(issues.status, statuses)); - } - } - const [row] = await db.select({ count: sql`count(*)` }).from(issues).where(and(...conditions)); - return Number(row?.count ?? 0); - }, - markRead: async (companyId, issueId, userId, readAt = /* @__PURE__ */ new Date()) => { - const now2 = /* @__PURE__ */ new Date(); - const [row] = await db.insert(issueReadStates).values({ - companyId, - issueId, - userId, - lastReadAt: readAt, - updatedAt: now2 - }).onConflictDoUpdate({ - target: [issueReadStates.companyId, issueReadStates.issueId, issueReadStates.userId], - set: { - lastReadAt: readAt, - updatedAt: now2 - } - }).returning(); - return row; - }, - markUnread: async (companyId, issueId, userId) => { - const deleted = await db.delete(issueReadStates).where( - and( - eq(issueReadStates.companyId, companyId), - eq(issueReadStates.issueId, issueId), - eq(issueReadStates.userId, userId) - ) - ).returning(); - return deleted.length > 0; - }, - archiveInbox: async (companyId, issueId, userId, archivedAt = /* @__PURE__ */ new Date()) => { - const now2 = /* @__PURE__ */ new Date(); - const [row] = await db.insert(issueInboxArchives).values({ - companyId, - issueId, - userId, - archivedAt, - updatedAt: now2 - }).onConflictDoUpdate({ - target: [issueInboxArchives.companyId, issueInboxArchives.issueId, issueInboxArchives.userId], - set: { - archivedAt, - updatedAt: now2 - } - }).returning(); - return row; - }, - unarchiveInbox: async (companyId, issueId, userId) => { - const [row] = await db.delete(issueInboxArchives).where( - and( - eq(issueInboxArchives.companyId, companyId), - eq(issueInboxArchives.issueId, issueId), - eq(issueInboxArchives.userId, userId) - ) - ).returning(); - return row ?? null; - }, - getById: async (raw) => { - const id = raw.trim(); - if (/^[A-Z]+-\d+$/i.test(id)) { - return getIssueByIdentifier(id); - } - if (!isUuidLike(id)) { - return null; - } - return getIssueByUuid(id); - }, - getByIdentifier: async (identifier) => { - return getIssueByIdentifier(identifier); - }, - getRelationSummaries: async (issueId) => { - const issue2 = await db.select({ id: issues.id, companyId: issues.companyId }).from(issues).where(eq(issues.id, issueId)).then((rows) => rows[0] ?? null); - if (!issue2) throw notFound("Issue not found"); - const relations = await getIssueRelationSummaryMap(issue2.companyId, [issueId], db); - return relations.get(issueId) ?? { blockedBy: [], blocks: [] }; - }, - listWakeableBlockedDependents: async (blockerIssueId) => { - const blockerIssue = await db.select({ id: issues.id, companyId: issues.companyId }).from(issues).where(eq(issues.id, blockerIssueId)).then((rows) => rows[0] ?? null); - if (!blockerIssue) return []; - const candidates = await db.select({ - id: issues.id, - assigneeAgentId: issues.assigneeAgentId, - status: issues.status - }).from(issueRelations).innerJoin(issues, eq(issueRelations.relatedIssueId, issues.id)).where( - and( - eq(issueRelations.companyId, blockerIssue.companyId), - eq(issueRelations.type, "blocks"), - eq(issueRelations.issueId, blockerIssueId) - ) - ); - if (candidates.length === 0) return []; - const candidateIds = candidates.map((candidate) => candidate.id); - const blockerRows = await db.select({ - issueId: issueRelations.relatedIssueId, - blockerIssueId: issueRelations.issueId, - blockerStatus: issues.status - }).from(issueRelations).innerJoin(issues, eq(issueRelations.issueId, issues.id)).where( - and( - eq(issueRelations.companyId, blockerIssue.companyId), - eq(issueRelations.type, "blocks"), - inArray(issueRelations.relatedIssueId, candidateIds) - ) - ); - const blockersByIssueId = /* @__PURE__ */ new Map(); - for (const row of blockerRows) { - const list2 = blockersByIssueId.get(row.issueId) ?? []; - list2.push({ blockerIssueId: row.blockerIssueId, blockerStatus: row.blockerStatus }); - blockersByIssueId.set(row.issueId, list2); - } - return candidates.filter((candidate) => candidate.assigneeAgentId && !["backlog", "done", "cancelled"].includes(candidate.status)).map((candidate) => { - const blockers = blockersByIssueId.get(candidate.id) ?? []; - return { - ...candidate, - blockerIssueIds: blockers.map((blocker) => blocker.blockerIssueId), - allBlockersDone: blockers.length > 0 && blockers.every((blocker) => blocker.blockerStatus === "done") - }; - }).filter((candidate) => candidate.allBlockersDone).map((candidate) => ({ - id: candidate.id, - assigneeAgentId: candidate.assigneeAgentId, - blockerIssueIds: candidate.blockerIssueIds - })); - }, - getWakeableParentAfterChildCompletion: async (parentIssueId) => { - const parent = await db.select({ - id: issues.id, - assigneeAgentId: issues.assigneeAgentId, - status: issues.status, - companyId: issues.companyId - }).from(issues).where(eq(issues.id, parentIssueId)).then((rows) => rows[0] ?? null); - if (!parent || !parent.assigneeAgentId || ["backlog", "done", "cancelled"].includes(parent.status)) { - return null; - } - const children = await db.select({ id: issues.id, status: issues.status }).from(issues).where(and(eq(issues.companyId, parent.companyId), eq(issues.parentId, parentIssueId))); - if (children.length === 0) return null; - if (!children.every((child) => child.status === "done" || child.status === "cancelled")) { - return null; - } - return { - id: parent.id, - assigneeAgentId: parent.assigneeAgentId, - childIssueIds: children.map((child) => child.id) - }; - }, - create: async (companyId, data2) => { - const { - labelIds: inputLabelIds, - blockedByIssueIds, - inheritExecutionWorkspaceFromIssueId, - ...issueData - } = data2; - const isolatedWorkspacesEnabled = (await instanceSettings2.getExperimental()).enableIsolatedWorkspaces; - if (!isolatedWorkspacesEnabled) { - delete issueData.executionWorkspaceId; - delete issueData.executionWorkspacePreference; - delete issueData.executionWorkspaceSettings; - } - if (data2.assigneeAgentId && data2.assigneeUserId) { - throw unprocessable("Issue can only have one assignee"); - } - if (data2.assigneeAgentId) { - await assertAssignableAgent(companyId, data2.assigneeAgentId); - } - if (data2.assigneeUserId) { - await assertAssignableUser(companyId, data2.assigneeUserId); - } - if (data2.status === "in_progress" && !data2.assigneeAgentId && !data2.assigneeUserId) { - throw unprocessable("in_progress issues require an assignee"); - } - return db.transaction(async (tx) => { - const defaultCompanyGoal = await getDefaultCompanyGoal(tx, companyId); - const projectGoalId = await getProjectDefaultGoalId(tx, companyId, issueData.projectId); - let projectWorkspaceId = issueData.projectWorkspaceId ?? null; - let executionWorkspaceId = issueData.executionWorkspaceId ?? null; - let executionWorkspacePreference = issueData.executionWorkspacePreference ?? null; - let executionWorkspaceSettings = issueData.executionWorkspaceSettings ?? null; - const workspaceInheritanceIssueId = inheritExecutionWorkspaceFromIssueId ?? issueData.parentId ?? null; - const hasExplicitExecutionWorkspaceOverride = issueData.executionWorkspaceId !== void 0 || issueData.executionWorkspacePreference !== void 0 || issueData.executionWorkspaceSettings !== void 0; - if (workspaceInheritanceIssueId) { - const workspaceSource = await getWorkspaceInheritanceIssue(tx, companyId, workspaceInheritanceIssueId); - if (projectWorkspaceId == null && workspaceSource.projectWorkspaceId) { - projectWorkspaceId = workspaceSource.projectWorkspaceId; - } - if (isolatedWorkspacesEnabled && !hasExplicitExecutionWorkspaceOverride && workspaceSource.executionWorkspaceId) { - const sourceWorkspace = await tx.select({ - id: executionWorkspaces.id, - mode: executionWorkspaces.mode - }).from(executionWorkspaces).where(eq(executionWorkspaces.id, workspaceSource.executionWorkspaceId)).then((rows) => rows[0] ?? null); - if (sourceWorkspace) { - executionWorkspaceId = sourceWorkspace.id; - executionWorkspacePreference = "reuse_existing"; - executionWorkspaceSettings = { - ...workspaceSource.executionWorkspaceSettings ?? {}, - mode: issueExecutionWorkspaceModeForPersistedWorkspace(sourceWorkspace.mode) - }; - } - } - } - if (executionWorkspaceSettings == null && executionWorkspaceId == null && issueData.projectId) { - const project = await tx.select({ executionWorkspacePolicy: projects.executionWorkspacePolicy }).from(projects).where(and(eq(projects.id, issueData.projectId), eq(projects.companyId, companyId))).then((rows) => rows[0] ?? null); - executionWorkspaceSettings = defaultIssueExecutionWorkspaceSettingsForProject( - gateProjectExecutionWorkspacePolicy( - parseProjectExecutionWorkspacePolicy(project?.executionWorkspacePolicy), - isolatedWorkspacesEnabled - ) - ); - } - if (!projectWorkspaceId && issueData.projectId) { - const project = await tx.select({ - executionWorkspacePolicy: projects.executionWorkspacePolicy - }).from(projects).where(and(eq(projects.id, issueData.projectId), eq(projects.companyId, companyId))).then((rows) => rows[0] ?? null); - const projectPolicy = parseProjectExecutionWorkspacePolicy(project?.executionWorkspacePolicy); - projectWorkspaceId = projectPolicy?.defaultProjectWorkspaceId ?? null; - if (!projectWorkspaceId) { - projectWorkspaceId = await tx.select({ id: projectWorkspaces.id }).from(projectWorkspaces).where(and(eq(projectWorkspaces.projectId, issueData.projectId), eq(projectWorkspaces.companyId, companyId))).orderBy(desc(projectWorkspaces.isPrimary), asc(projectWorkspaces.createdAt), asc(projectWorkspaces.id)).then((rows) => rows[0]?.id ?? null); - } - } - if (projectWorkspaceId) { - await assertValidProjectWorkspace(companyId, issueData.projectId, projectWorkspaceId, tx); - } - if (executionWorkspaceId) { - await assertValidExecutionWorkspace(companyId, issueData.projectId, executionWorkspaceId, tx); - } - const [maxRow] = await tx.select({ maxNum: sql`coalesce(max(${issues.issueNumber}), 0)` }).from(issues).where(eq(issues.companyId, companyId)); - const currentMax = maxRow?.maxNum ?? 0; - const [company] = await tx.update(companies).set({ - issueCounter: sql`greatest(${companies.issueCounter}, ${currentMax}) + 1` - }).where(eq(companies.id, companyId)).returning({ issueCounter: companies.issueCounter, issuePrefix: companies.issuePrefix }); - const issueNumber = company.issueCounter; - const identifier = `${company.issuePrefix}-${issueNumber}`; - const values2 = { - ...issueData, - originKind: issueData.originKind ?? "manual", - goalId: resolveIssueGoalId({ - projectId: issueData.projectId, - goalId: issueData.goalId, - projectGoalId, - defaultGoalId: defaultCompanyGoal?.id ?? null - }), - ...projectWorkspaceId ? { projectWorkspaceId } : {}, - ...executionWorkspaceId ? { executionWorkspaceId } : {}, - ...executionWorkspacePreference ? { executionWorkspacePreference } : {}, - ...executionWorkspaceSettings ? { executionWorkspaceSettings } : {}, - companyId, - issueNumber, - identifier - }; - if (values2.status === "in_progress" && !values2.startedAt) { - values2.startedAt = /* @__PURE__ */ new Date(); - } - if (values2.status === "done") { - values2.completedAt = /* @__PURE__ */ new Date(); - } - if (values2.status === "cancelled") { - values2.cancelledAt = /* @__PURE__ */ new Date(); - } - const [issue2] = await tx.insert(issues).values(values2).returning(); - if (inputLabelIds) { - await syncIssueLabels(issue2.id, companyId, inputLabelIds, tx); - } - if (blockedByIssueIds !== void 0) { - await syncBlockedByIssueIds( - issue2.id, - companyId, - blockedByIssueIds, - { - agentId: issueData.createdByAgentId ?? null, - userId: issueData.createdByUserId ?? null - }, - tx - ); - } - const [enriched] = await withIssueLabels(tx, [issue2]); - return enriched; - }); - }, - update: async (id, data2, dbOrTx = db) => { - const existing = await dbOrTx.select().from(issues).where(eq(issues.id, id)).then((rows) => rows[0] ?? null); - if (!existing) return null; - const { - labelIds: nextLabelIds, - blockedByIssueIds, - actorAgentId, - actorUserId, - ...issueData - } = data2; - const isolatedWorkspacesEnabled = (await instanceSettings2.getExperimental()).enableIsolatedWorkspaces; - if (!isolatedWorkspacesEnabled) { - delete issueData.executionWorkspaceId; - delete issueData.executionWorkspacePreference; - delete issueData.executionWorkspaceSettings; - } - if (issueData.status) { - assertTransition(existing.status, issueData.status); - } - const patch = { - ...issueData, - updatedAt: /* @__PURE__ */ new Date() - }; - const nextAssigneeAgentId = issueData.assigneeAgentId !== void 0 ? issueData.assigneeAgentId : existing.assigneeAgentId; - const nextAssigneeUserId = issueData.assigneeUserId !== void 0 ? issueData.assigneeUserId : existing.assigneeUserId; - if (nextAssigneeAgentId && nextAssigneeUserId) { - throw unprocessable("Issue can only have one assignee"); - } - if (patch.status === "in_progress" && !nextAssigneeAgentId && !nextAssigneeUserId) { - throw unprocessable("in_progress issues require an assignee"); - } - if (issueData.assigneeAgentId) { - await assertAssignableAgent(existing.companyId, issueData.assigneeAgentId); - } - if (issueData.assigneeUserId) { - await assertAssignableUser(existing.companyId, issueData.assigneeUserId); - } - const nextProjectId = issueData.projectId !== void 0 ? issueData.projectId : existing.projectId; - const nextProjectWorkspaceId = issueData.projectWorkspaceId !== void 0 ? issueData.projectWorkspaceId : existing.projectWorkspaceId; - const nextExecutionWorkspaceId = issueData.executionWorkspaceId !== void 0 ? issueData.executionWorkspaceId : existing.executionWorkspaceId; - if (nextProjectWorkspaceId) { - await assertValidProjectWorkspace(existing.companyId, nextProjectId, nextProjectWorkspaceId); - } - if (nextExecutionWorkspaceId) { - await assertValidExecutionWorkspace(existing.companyId, nextProjectId, nextExecutionWorkspaceId); - } - applyStatusSideEffects(issueData.status, patch); - if (issueData.status && issueData.status !== "done") { - patch.completedAt = null; - } - if (issueData.status && issueData.status !== "cancelled") { - patch.cancelledAt = null; - } - if (issueData.status && issueData.status !== "in_progress") { - patch.checkoutRunId = null; - patch.executionRunId = null; - patch.executionAgentNameKey = null; - patch.executionLockedAt = null; - } - if (issueData.assigneeAgentId !== void 0 && issueData.assigneeAgentId !== existing.assigneeAgentId || issueData.assigneeUserId !== void 0 && issueData.assigneeUserId !== existing.assigneeUserId) { - patch.checkoutRunId = null; - patch.executionRunId = null; - patch.executionAgentNameKey = null; - patch.executionLockedAt = null; - } - const runUpdate = async (tx) => { - const defaultCompanyGoal = await getDefaultCompanyGoal(tx, existing.companyId); - const [currentProjectGoalId, nextProjectGoalId] = await Promise.all([ - getProjectDefaultGoalId(tx, existing.companyId, existing.projectId), - getProjectDefaultGoalId( - tx, - existing.companyId, - issueData.projectId !== void 0 ? issueData.projectId : existing.projectId - ) - ]); - patch.goalId = resolveNextIssueGoalId({ - currentProjectId: existing.projectId, - currentGoalId: existing.goalId, - currentProjectGoalId, - projectId: issueData.projectId, - goalId: issueData.goalId, - projectGoalId: nextProjectGoalId, - defaultGoalId: defaultCompanyGoal?.id ?? null - }); - const updated = await tx.update(issues).set(patch).where(eq(issues.id, id)).returning().then((rows) => rows[0] ?? null); - if (!updated) return null; - if (nextLabelIds !== void 0) { - await syncIssueLabels(updated.id, existing.companyId, nextLabelIds, tx); - } - if (blockedByIssueIds !== void 0) { - await syncBlockedByIssueIds( - updated.id, - existing.companyId, - blockedByIssueIds, - { - agentId: actorAgentId ?? null, - userId: actorUserId ?? null - }, - tx - ); - } - const [enriched] = await withIssueLabels(tx, [updated]); - return enriched; - }; - return dbOrTx === db ? db.transaction(runUpdate) : runUpdate(dbOrTx); - }, - remove: (id) => db.transaction(async (tx) => { - const attachmentAssetIds = await tx.select({ assetId: issueAttachments.assetId }).from(issueAttachments).where(eq(issueAttachments.issueId, id)); - const issueDocumentIds = await tx.select({ documentId: issueDocuments.documentId }).from(issueDocuments).where(eq(issueDocuments.issueId, id)); - const removedIssue = await tx.delete(issues).where(eq(issues.id, id)).returning().then((rows) => rows[0] ?? null); - if (removedIssue && attachmentAssetIds.length > 0) { - await tx.delete(assets).where(inArray(assets.id, attachmentAssetIds.map((row) => row.assetId))); - } - if (removedIssue && issueDocumentIds.length > 0) { - await tx.delete(documents).where(inArray(documents.id, issueDocumentIds.map((row) => row.documentId))); - } - if (!removedIssue) return null; - const [enriched] = await withIssueLabels(tx, [removedIssue]); - return enriched; - }), - checkout: async (id, agentId, expectedStatuses, checkoutRunId) => { - const issueCompany = await db.select({ companyId: issues.companyId }).from(issues).where(eq(issues.id, id)).then((rows) => rows[0] ?? null); - if (!issueCompany) throw notFound("Issue not found"); - await assertAssignableAgent(issueCompany.companyId, agentId); - const now2 = /* @__PURE__ */ new Date(); - await db.transaction(async (tx) => { - await tx.execute( - sql`select id from issues where id = ${id} for update` - ); - const preCheckRow = await tx.select({ executionRunId: issues.executionRunId }).from(issues).where(eq(issues.id, id)).then((rows) => rows[0] ?? null); - if (!preCheckRow?.executionRunId) return; - const lockRun = await tx.select({ id: heartbeatRuns.id, status: heartbeatRuns.status }).from(heartbeatRuns).where(eq(heartbeatRuns.id, preCheckRow.executionRunId)).then((rows) => rows[0] ?? null); - if (!lockRun || lockRun.status !== "queued" && lockRun.status !== "running") { - await tx.update(issues).set({ executionRunId: null, executionAgentNameKey: null, executionLockedAt: null, updatedAt: now2 }).where( - and( - eq(issues.id, id), - eq(issues.executionRunId, preCheckRow.executionRunId) - ) - ); - } - }); - const sameRunAssigneeCondition = checkoutRunId ? and( - eq(issues.assigneeAgentId, agentId), - or(isNull(issues.checkoutRunId), eq(issues.checkoutRunId, checkoutRunId)) - ) : and(eq(issues.assigneeAgentId, agentId), isNull(issues.checkoutRunId)); - const executionLockCondition = checkoutRunId ? or(isNull(issues.executionRunId), eq(issues.executionRunId, checkoutRunId)) : isNull(issues.executionRunId); - const updated = await db.update(issues).set({ - assigneeAgentId: agentId, - assigneeUserId: null, - checkoutRunId, - executionRunId: checkoutRunId, - status: "in_progress", - startedAt: now2, - updatedAt: now2 - }).where( - and( - eq(issues.id, id), - inArray(issues.status, expectedStatuses), - or(isNull(issues.assigneeAgentId), sameRunAssigneeCondition), - executionLockCondition - ) - ).returning().then((rows) => rows[0] ?? null); - if (updated) { - const [enriched] = await withIssueLabels(db, [updated]); - return enriched; - } - const current = await db.select({ - id: issues.id, - status: issues.status, - assigneeAgentId: issues.assigneeAgentId, - checkoutRunId: issues.checkoutRunId, - executionRunId: issues.executionRunId - }).from(issues).where(eq(issues.id, id)).then((rows) => rows[0] ?? null); - if (!current) throw notFound("Issue not found"); - if (current.assigneeAgentId === agentId && current.status === "in_progress" && current.checkoutRunId == null && (current.executionRunId == null || current.executionRunId === checkoutRunId) && checkoutRunId) { - const adopted = await db.update(issues).set({ - checkoutRunId, - executionRunId: checkoutRunId, - updatedAt: /* @__PURE__ */ new Date() - }).where( - and( - eq(issues.id, id), - eq(issues.status, "in_progress"), - eq(issues.assigneeAgentId, agentId), - isNull(issues.checkoutRunId), - or(isNull(issues.executionRunId), eq(issues.executionRunId, checkoutRunId)) - ) - ).returning().then((rows) => rows[0] ?? null); - if (adopted) return adopted; - } - if (checkoutRunId && current.assigneeAgentId === agentId && current.status === "in_progress" && current.checkoutRunId && current.checkoutRunId !== checkoutRunId) { - const adopted = await adoptStaleCheckoutRun({ - issueId: id, - actorAgentId: agentId, - actorRunId: checkoutRunId, - expectedCheckoutRunId: current.checkoutRunId - }); - if (adopted) { - const row = await db.select().from(issues).where(eq(issues.id, id)).then((rows) => rows[0] ?? null); - if (!row) throw notFound("Issue not found"); - const [enriched] = await withIssueLabels(db, [row]); - return enriched; - } - } - if (current.assigneeAgentId === agentId && current.status === "in_progress" && sameRunLock(current.checkoutRunId, checkoutRunId)) { - const row = await db.select().from(issues).where(eq(issues.id, id)).then((rows) => rows[0] ?? null); - if (!row) throw notFound("Issue not found"); - const [enriched] = await withIssueLabels(db, [row]); - return enriched; - } - throw conflict("Issue checkout conflict", { - issueId: current.id, - status: current.status, - assigneeAgentId: current.assigneeAgentId, - checkoutRunId: current.checkoutRunId, - executionRunId: current.executionRunId - }); - }, - assertCheckoutOwner: async (id, actorAgentId, actorRunId) => { - const current = await db.select({ - id: issues.id, - status: issues.status, - assigneeAgentId: issues.assigneeAgentId, - checkoutRunId: issues.checkoutRunId - }).from(issues).where(eq(issues.id, id)).then((rows) => rows[0] ?? null); - if (!current) throw notFound("Issue not found"); - if (current.status === "in_progress" && current.assigneeAgentId === actorAgentId && sameRunLock(current.checkoutRunId, actorRunId)) { - return { ...current, adoptedFromRunId: null }; - } - if (actorRunId && current.status === "in_progress" && current.assigneeAgentId === actorAgentId && current.checkoutRunId && current.checkoutRunId !== actorRunId) { - const adopted = await adoptStaleCheckoutRun({ - issueId: id, - actorAgentId, - actorRunId, - expectedCheckoutRunId: current.checkoutRunId - }); - if (adopted) { - return { - ...adopted, - adoptedFromRunId: current.checkoutRunId - }; - } - } - throw conflict("Issue run ownership conflict", { - issueId: current.id, - status: current.status, - assigneeAgentId: current.assigneeAgentId, - checkoutRunId: current.checkoutRunId, - actorAgentId, - actorRunId - }); - }, - release: async (id, actorAgentId, actorRunId) => { - const existing = await db.select().from(issues).where(eq(issues.id, id)).then((rows) => rows[0] ?? null); - if (!existing) return null; - if (actorAgentId && existing.assigneeAgentId && existing.assigneeAgentId !== actorAgentId) { - throw conflict("Only assignee can release issue"); - } - if (actorAgentId && existing.status === "in_progress" && existing.assigneeAgentId === actorAgentId && existing.checkoutRunId && !sameRunLock(existing.checkoutRunId, actorRunId ?? null)) { - throw conflict("Only checkout run can release issue", { - issueId: existing.id, - assigneeAgentId: existing.assigneeAgentId, - checkoutRunId: existing.checkoutRunId, - actorRunId: actorRunId ?? null - }); - } - const updated = await db.update(issues).set({ - status: "todo", - assigneeAgentId: null, - checkoutRunId: null, - updatedAt: /* @__PURE__ */ new Date() - }).where(eq(issues.id, id)).returning().then((rows) => rows[0] ?? null); - if (!updated) return null; - const [enriched] = await withIssueLabels(db, [updated]); - return enriched; - }, - listLabels: (companyId) => db.select().from(labels).where(eq(labels.companyId, companyId)).orderBy(asc(labels.name), asc(labels.id)), - getLabelById: (id) => db.select().from(labels).where(eq(labels.id, id)).then((rows) => rows[0] ?? null), - createLabel: async (companyId, data2) => { - const [created] = await db.insert(labels).values({ - companyId, - name: data2.name.trim(), - color: data2.color - }).returning(); - return created; - }, - deleteLabel: async (id) => db.delete(labels).where(eq(labels.id, id)).returning().then((rows) => rows[0] ?? null), - listComments: async (issueId, opts) => { - const order = opts?.order === "asc" ? "asc" : "desc"; - const afterCommentId = opts?.afterCommentId?.trim() || null; - const limit = opts?.limit && opts.limit > 0 ? Math.min(Math.floor(opts.limit), MAX_ISSUE_COMMENT_PAGE_LIMIT) : null; - const conditions = [eq(issueComments.issueId, issueId)]; - if (afterCommentId) { - const anchor = await db.select({ - id: issueComments.id, - createdAt: issueComments.createdAt - }).from(issueComments).where(and(eq(issueComments.issueId, issueId), eq(issueComments.id, afterCommentId))).then((rows) => rows[0] ?? null); - if (!anchor) return []; - conditions.push( - order === "asc" ? sql`( - ${issueComments.createdAt} > ${anchor.createdAt} - OR (${issueComments.createdAt} = ${anchor.createdAt} AND ${issueComments.id} > ${anchor.id}) - )` : sql`( - ${issueComments.createdAt} < ${anchor.createdAt} - OR (${issueComments.createdAt} = ${anchor.createdAt} AND ${issueComments.id} < ${anchor.id}) - )` - ); - } - const query = db.select().from(issueComments).where(and(...conditions)).orderBy( - order === "asc" ? asc(issueComments.createdAt) : desc(issueComments.createdAt), - order === "asc" ? asc(issueComments.id) : desc(issueComments.id) - ); - const comments = limit ? await query.limit(limit) : await query; - const { censorUsernameInLogs } = await instanceSettings2.getGeneral(); - return comments.map((comment) => redactIssueComment(comment, censorUsernameInLogs)); - }, - getCommentCursor: async (issueId) => { - const [latest, countRow] = await Promise.all([ - db.select({ - latestCommentId: issueComments.id, - latestCommentAt: issueComments.createdAt - }).from(issueComments).where(eq(issueComments.issueId, issueId)).orderBy(desc(issueComments.createdAt), desc(issueComments.id)).limit(1).then((rows) => rows[0] ?? null), - db.select({ - totalComments: sql`count(*)::int` - }).from(issueComments).where(eq(issueComments.issueId, issueId)).then((rows) => rows[0] ?? null) - ]); - return { - totalComments: Number(countRow?.totalComments ?? 0), - latestCommentId: latest?.latestCommentId ?? null, - latestCommentAt: latest?.latestCommentAt ?? null - }; - }, - getComment: (commentId) => instanceSettings2.getGeneral().then(({ censorUsernameInLogs }) => db.select().from(issueComments).where(eq(issueComments.id, commentId)).then((rows) => { - const comment = rows[0] ?? null; - return comment ? redactIssueComment(comment, censorUsernameInLogs) : null; - })), - removeComment: async (commentId) => { - const currentUserRedactionOptions = { - enabled: (await instanceSettings2.getGeneral()).censorUsernameInLogs - }; - return db.transaction(async (tx) => { - const [comment] = await tx.delete(issueComments).where(eq(issueComments.id, commentId)).returning(); - if (!comment) return null; - await tx.update(issues).set({ updatedAt: /* @__PURE__ */ new Date() }).where(eq(issues.id, comment.issueId)); - return redactIssueComment(comment, currentUserRedactionOptions.enabled); - }); - }, - addComment: async (issueId, body, actor) => { - const issue2 = await db.select({ companyId: issues.companyId }).from(issues).where(eq(issues.id, issueId)).then((rows) => rows[0] ?? null); - if (!issue2) throw notFound("Issue not found"); - const currentUserRedactionOptions = { - enabled: (await instanceSettings2.getGeneral()).censorUsernameInLogs - }; - const redactedBody = redactCurrentUserText(body, currentUserRedactionOptions); - const [comment] = await db.insert(issueComments).values({ - companyId: issue2.companyId, - issueId, - authorAgentId: actor.agentId ?? null, - authorUserId: actor.userId ?? null, - createdByRunId: actor.runId ?? null, - body: redactedBody - }).returning(); - await db.update(issues).set({ updatedAt: /* @__PURE__ */ new Date() }).where(eq(issues.id, issueId)); - return redactIssueComment(comment, currentUserRedactionOptions.enabled); - }, - createAttachment: async (input) => { - const issue2 = await db.select({ id: issues.id, companyId: issues.companyId }).from(issues).where(eq(issues.id, input.issueId)).then((rows) => rows[0] ?? null); - if (!issue2) throw notFound("Issue not found"); - if (input.issueCommentId) { - const comment = await db.select({ id: issueComments.id, companyId: issueComments.companyId, issueId: issueComments.issueId }).from(issueComments).where(eq(issueComments.id, input.issueCommentId)).then((rows) => rows[0] ?? null); - if (!comment) throw notFound("Issue comment not found"); - if (comment.companyId !== issue2.companyId || comment.issueId !== issue2.id) { - throw unprocessable("Attachment comment must belong to same issue and company"); - } - } - return db.transaction(async (tx) => { - const [asset] = await tx.insert(assets).values({ - companyId: issue2.companyId, - provider: input.provider, - objectKey: input.objectKey, - contentType: input.contentType, - byteSize: input.byteSize, - sha256: input.sha256, - originalFilename: input.originalFilename ?? null, - createdByAgentId: input.createdByAgentId ?? null, - createdByUserId: input.createdByUserId ?? null - }).returning(); - const [attachment] = await tx.insert(issueAttachments).values({ - companyId: issue2.companyId, - issueId: issue2.id, - assetId: asset.id, - issueCommentId: input.issueCommentId ?? null - }).returning(); - return { - id: attachment.id, - companyId: attachment.companyId, - issueId: attachment.issueId, - issueCommentId: attachment.issueCommentId, - assetId: attachment.assetId, - provider: asset.provider, - objectKey: asset.objectKey, - contentType: asset.contentType, - byteSize: asset.byteSize, - sha256: asset.sha256, - originalFilename: asset.originalFilename, - createdByAgentId: asset.createdByAgentId, - createdByUserId: asset.createdByUserId, - createdAt: attachment.createdAt, - updatedAt: attachment.updatedAt - }; - }); - }, - listAttachments: async (issueId) => db.select({ - id: issueAttachments.id, - companyId: issueAttachments.companyId, - issueId: issueAttachments.issueId, - issueCommentId: issueAttachments.issueCommentId, - assetId: issueAttachments.assetId, - provider: assets.provider, - objectKey: assets.objectKey, - contentType: assets.contentType, - byteSize: assets.byteSize, - sha256: assets.sha256, - originalFilename: assets.originalFilename, - createdByAgentId: assets.createdByAgentId, - createdByUserId: assets.createdByUserId, - createdAt: issueAttachments.createdAt, - updatedAt: issueAttachments.updatedAt - }).from(issueAttachments).innerJoin(assets, eq(issueAttachments.assetId, assets.id)).where(eq(issueAttachments.issueId, issueId)).orderBy(desc(issueAttachments.createdAt)), - getAttachmentById: async (id) => db.select({ - id: issueAttachments.id, - companyId: issueAttachments.companyId, - issueId: issueAttachments.issueId, - issueCommentId: issueAttachments.issueCommentId, - assetId: issueAttachments.assetId, - provider: assets.provider, - objectKey: assets.objectKey, - contentType: assets.contentType, - byteSize: assets.byteSize, - sha256: assets.sha256, - originalFilename: assets.originalFilename, - createdByAgentId: assets.createdByAgentId, - createdByUserId: assets.createdByUserId, - createdAt: issueAttachments.createdAt, - updatedAt: issueAttachments.updatedAt - }).from(issueAttachments).innerJoin(assets, eq(issueAttachments.assetId, assets.id)).where(eq(issueAttachments.id, id)).then((rows) => rows[0] ?? null), - removeAttachment: async (id) => db.transaction(async (tx) => { - const existing = await tx.select({ - id: issueAttachments.id, - companyId: issueAttachments.companyId, - issueId: issueAttachments.issueId, - issueCommentId: issueAttachments.issueCommentId, - assetId: issueAttachments.assetId, - provider: assets.provider, - objectKey: assets.objectKey, - contentType: assets.contentType, - byteSize: assets.byteSize, - sha256: assets.sha256, - originalFilename: assets.originalFilename, - createdByAgentId: assets.createdByAgentId, - createdByUserId: assets.createdByUserId, - createdAt: issueAttachments.createdAt, - updatedAt: issueAttachments.updatedAt - }).from(issueAttachments).innerJoin(assets, eq(issueAttachments.assetId, assets.id)).where(eq(issueAttachments.id, id)).then((rows) => rows[0] ?? null); - if (!existing) return null; - await tx.delete(issueAttachments).where(eq(issueAttachments.id, id)); - await tx.delete(assets).where(eq(assets.id, existing.assetId)); - return existing; - }), - findMentionedAgents: async (companyId, body) => { - const re = /\B@([^\s@,!?.]+)/g; - const tokens = /* @__PURE__ */ new Set(); - let m5; - while ((m5 = re.exec(body)) !== null) { - const normalized = normalizeAgentMentionToken(m5[1]); - if (normalized) tokens.add(normalized.toLowerCase()); - } - const explicitAgentMentionIds = extractAgentMentionIds(body); - if (tokens.size === 0 && explicitAgentMentionIds.length === 0) return []; - const rows = await db.select({ id: agents.id, name: agents.name }).from(agents).where(eq(agents.companyId, companyId)); - const resolved = new Set(explicitAgentMentionIds); - for (const agent of rows) { - if (tokens.has(agent.name.toLowerCase())) { - resolved.add(agent.id); - } - } - return [...resolved]; - }, - findMentionedProjectIds: async (issueId) => { - const issue2 = await db.select({ - companyId: issues.companyId, - title: issues.title, - description: issues.description - }).from(issues).where(eq(issues.id, issueId)).then((rows2) => rows2[0] ?? null); - if (!issue2) return []; - const comments = await db.select({ body: issueComments.body }).from(issueComments).where(eq(issueComments.issueId, issueId)); - const mentionedIds = /* @__PURE__ */ new Set(); - for (const source of [ - issue2.title, - issue2.description ?? "", - ...comments.map((comment) => comment.body) - ]) { - for (const projectId of extractProjectMentionIds(source)) { - mentionedIds.add(projectId); - } - } - if (mentionedIds.size === 0) return []; - const rows = await db.select({ id: projects.id }).from(projects).where( - and( - eq(projects.companyId, issue2.companyId), - inArray(projects.id, [...mentionedIds]) - ) - ); - const valid = new Set(rows.map((row) => row.id)); - return [...mentionedIds].filter((projectId) => valid.has(projectId)); - }, - getAncestors: async (issueId) => { - const raw = []; - const visited = /* @__PURE__ */ new Set([issueId]); - const start = await db.select().from(issues).where(eq(issues.id, issueId)).then((r5) => r5[0] ?? null); - let currentId = start?.parentId ?? null; - while (currentId && !visited.has(currentId) && raw.length < 50) { - visited.add(currentId); - const parent = await db.select({ - id: issues.id, - identifier: issues.identifier, - title: issues.title, - description: issues.description, - status: issues.status, - priority: issues.priority, - assigneeAgentId: issues.assigneeAgentId, - projectId: issues.projectId, - goalId: issues.goalId, - parentId: issues.parentId - }).from(issues).where(eq(issues.id, currentId)).then((r5) => r5[0] ?? null); - if (!parent) break; - raw.push({ - id: parent.id, - identifier: parent.identifier ?? null, - title: parent.title, - description: parent.description ?? null, - status: parent.status, - priority: parent.priority, - assigneeAgentId: parent.assigneeAgentId ?? null, - projectId: parent.projectId ?? null, - goalId: parent.goalId ?? null - }); - currentId = parent.parentId ?? null; - } - const projectIds = [...new Set(raw.map((a5) => a5.projectId).filter((id) => id != null))]; - const goalIds = [...new Set(raw.map((a5) => a5.goalId).filter((id) => id != null))]; - const projectMap = /* @__PURE__ */ new Map(); - const goalMap = /* @__PURE__ */ new Map(); - if (projectIds.length > 0) { - const workspaceRows = await db.select().from(projectWorkspaces).where(inArray(projectWorkspaces.projectId, projectIds)).orderBy(desc(projectWorkspaces.isPrimary), asc(projectWorkspaces.createdAt), asc(projectWorkspaces.id)); - const workspaceMap = /* @__PURE__ */ new Map(); - for (const workspace of workspaceRows) { - const existing = workspaceMap.get(workspace.projectId); - if (existing) existing.push(workspace); - else workspaceMap.set(workspace.projectId, [workspace]); - } - const rows = await db.select({ - id: projects.id, - name: projects.name, - description: projects.description, - status: projects.status, - goalId: projects.goalId - }).from(projects).where(inArray(projects.id, projectIds)); - for (const r5 of rows) { - const projectWorkspaceRows = workspaceMap.get(r5.id) ?? []; - const workspaces = projectWorkspaceRows.map((workspace) => ({ - id: workspace.id, - companyId: workspace.companyId, - projectId: workspace.projectId, - name: workspace.name, - cwd: workspace.cwd, - repoUrl: workspace.repoUrl ?? null, - repoRef: workspace.repoRef ?? null, - metadata: workspace.metadata ?? null, - isPrimary: workspace.isPrimary, - createdAt: workspace.createdAt, - updatedAt: workspace.updatedAt - })); - const primaryWorkspace = workspaces.find((workspace) => workspace.isPrimary) ?? workspaces[0] ?? null; - projectMap.set(r5.id, { - ...r5, - workspaces, - primaryWorkspace - }); - if (r5.goalId && !goalIds.includes(r5.goalId)) goalIds.push(r5.goalId); - } - } - if (goalIds.length > 0) { - const rows = await db.select({ - id: goals.id, - title: goals.title, - description: goals.description, - level: goals.level, - status: goals.status - }).from(goals).where(inArray(goals.id, goalIds)); - for (const r5 of rows) goalMap.set(r5.id, r5); - } - return raw.map((a5) => ({ - ...a5, - project: a5.projectId ? projectMap.get(a5.projectId) ?? null : null, - goal: a5.goalId ? goalMap.get(a5.goalId) ?? null : null - })); - } - }; -} - -// server/src/services/issue-approvals.ts -init_drizzle_orm(); -init_src2(); -function issueApprovalService(db) { - async function getIssue(issueId) { - return db.select().from(issues).where(eq(issues.id, issueId)).then((rows) => rows[0] ?? null); - } - async function getApproval(approvalId) { - return db.select().from(approvals).where(eq(approvals.id, approvalId)).then((rows) => rows[0] ?? null); - } - async function assertIssueAndApprovalSameCompany(issueId, approvalId) { - const issue2 = await getIssue(issueId); - if (!issue2) throw notFound("Issue not found"); - const approval = await getApproval(approvalId); - if (!approval) throw notFound("Approval not found"); - if (issue2.companyId !== approval.companyId) { - throw unprocessable("Issue and approval must belong to the same company"); - } - return { issue: issue2, approval }; - } - return { - listApprovalsForIssue: async (issueId) => { - const issue2 = await getIssue(issueId); - if (!issue2) throw notFound("Issue not found"); - const result = await db.select({ - id: approvals.id, - companyId: approvals.companyId, - type: approvals.type, - requestedByAgentId: approvals.requestedByAgentId, - requestedByUserId: approvals.requestedByUserId, - status: approvals.status, - payload: approvals.payload, - decisionNote: approvals.decisionNote, - decidedByUserId: approvals.decidedByUserId, - decidedAt: approvals.decidedAt, - createdAt: approvals.createdAt, - updatedAt: approvals.updatedAt - }).from(issueApprovals).innerJoin(approvals, eq(issueApprovals.approvalId, approvals.id)).where(eq(issueApprovals.issueId, issueId)).orderBy(desc(issueApprovals.createdAt)); - return result.map((approval) => ({ - ...approval, - payload: redactEventPayload(approval.payload) ?? {} - })); - }, - listIssuesForApproval: async (approvalId) => { - const approval = await getApproval(approvalId); - if (!approval) throw notFound("Approval not found"); - return db.select({ - id: issues.id, - companyId: issues.companyId, - projectId: issues.projectId, - goalId: issues.goalId, - parentId: issues.parentId, - title: issues.title, - description: issues.description, - status: issues.status, - priority: issues.priority, - assigneeAgentId: issues.assigneeAgentId, - createdByAgentId: issues.createdByAgentId, - createdByUserId: issues.createdByUserId, - issueNumber: issues.issueNumber, - identifier: issues.identifier, - requestDepth: issues.requestDepth, - billingCode: issues.billingCode, - startedAt: issues.startedAt, - completedAt: issues.completedAt, - cancelledAt: issues.cancelledAt, - createdAt: issues.createdAt, - updatedAt: issues.updatedAt - }).from(issueApprovals).innerJoin(issues, eq(issueApprovals.issueId, issues.id)).where(eq(issueApprovals.approvalId, approvalId)).orderBy(desc(issueApprovals.createdAt)); - }, - link: async (issueId, approvalId, actor) => { - const { issue: issue2 } = await assertIssueAndApprovalSameCompany(issueId, approvalId); - await db.insert(issueApprovals).values({ - companyId: issue2.companyId, - issueId, - approvalId, - linkedByAgentId: actor?.agentId ?? null, - linkedByUserId: actor?.userId ?? null - }).onConflictDoNothing(); - return db.select().from(issueApprovals).where(and(eq(issueApprovals.issueId, issueId), eq(issueApprovals.approvalId, approvalId))).then((rows) => rows[0] ?? null); - }, - unlink: async (issueId, approvalId) => { - await assertIssueAndApprovalSameCompany(issueId, approvalId); - await db.delete(issueApprovals).where(and(eq(issueApprovals.issueId, issueId), eq(issueApprovals.approvalId, approvalId))); - }, - linkManyForApproval: async (approvalId, issueIds, actor) => { - if (issueIds.length === 0) return; - const approval = await getApproval(approvalId); - if (!approval) throw notFound("Approval not found"); - const uniqueIssueIds = Array.from(new Set(issueIds)); - const rows = await db.select({ - id: issues.id, - companyId: issues.companyId - }).from(issues).where(inArray(issues.id, uniqueIssueIds)); - if (rows.length !== uniqueIssueIds.length) { - throw notFound("One or more issues not found"); - } - for (const row of rows) { - if (row.companyId !== approval.companyId) { - throw unprocessable("Issue and approval must belong to the same company"); - } - } - await db.insert(issueApprovals).values( - uniqueIssueIds.map((issueId) => ({ - companyId: approval.companyId, - issueId, - approvalId, - linkedByAgentId: actor?.agentId ?? null, - linkedByUserId: actor?.userId ?? null - })) - ).onConflictDoNothing(); - } - }; -} - -// server/src/services/activity.ts -init_drizzle_orm(); -init_src2(); -function activityService(db) { - const issueIdAsText = sql`${issues.id}::text`; - const summarizedUsageJson = sql` - case - when ${heartbeatRuns.usageJson} is null then null - else jsonb_strip_nulls(jsonb_build_object( - 'inputTokens', coalesce(${heartbeatRuns.usageJson} -> 'inputTokens', ${heartbeatRuns.usageJson} -> 'input_tokens'), - 'input_tokens', coalesce(${heartbeatRuns.usageJson} -> 'input_tokens', ${heartbeatRuns.usageJson} -> 'inputTokens'), - 'outputTokens', coalesce(${heartbeatRuns.usageJson} -> 'outputTokens', ${heartbeatRuns.usageJson} -> 'output_tokens'), - 'output_tokens', coalesce(${heartbeatRuns.usageJson} -> 'output_tokens', ${heartbeatRuns.usageJson} -> 'outputTokens'), - 'cachedInputTokens', coalesce( - ${heartbeatRuns.usageJson} -> 'cachedInputTokens', - ${heartbeatRuns.usageJson} -> 'cached_input_tokens', - ${heartbeatRuns.usageJson} -> 'cache_read_input_tokens' - ), - 'cached_input_tokens', coalesce( - ${heartbeatRuns.usageJson} -> 'cached_input_tokens', - ${heartbeatRuns.usageJson} -> 'cachedInputTokens', - ${heartbeatRuns.usageJson} -> 'cache_read_input_tokens' - ), - 'cache_read_input_tokens', coalesce( - ${heartbeatRuns.usageJson} -> 'cache_read_input_tokens', - ${heartbeatRuns.usageJson} -> 'cached_input_tokens', - ${heartbeatRuns.usageJson} -> 'cachedInputTokens' - ), - 'billingType', coalesce(${heartbeatRuns.usageJson} -> 'billingType', ${heartbeatRuns.usageJson} -> 'billing_type'), - 'billing_type', coalesce(${heartbeatRuns.usageJson} -> 'billing_type', ${heartbeatRuns.usageJson} -> 'billingType'), - 'costUsd', coalesce( - ${heartbeatRuns.usageJson} -> 'costUsd', - ${heartbeatRuns.usageJson} -> 'cost_usd', - ${heartbeatRuns.usageJson} -> 'total_cost_usd' - ), - 'cost_usd', coalesce( - ${heartbeatRuns.usageJson} -> 'cost_usd', - ${heartbeatRuns.usageJson} -> 'costUsd', - ${heartbeatRuns.usageJson} -> 'total_cost_usd' - ), - 'total_cost_usd', coalesce( - ${heartbeatRuns.usageJson} -> 'total_cost_usd', - ${heartbeatRuns.usageJson} -> 'cost_usd', - ${heartbeatRuns.usageJson} -> 'costUsd' - ) - )) - end - `.as("usageJson"); - const summarizedResultJson = sql` - case - when ${heartbeatRuns.resultJson} is null then null - else jsonb_strip_nulls(jsonb_build_object( - 'billingType', coalesce(${heartbeatRuns.resultJson} -> 'billingType', ${heartbeatRuns.resultJson} -> 'billing_type'), - 'billing_type', coalesce(${heartbeatRuns.resultJson} -> 'billing_type', ${heartbeatRuns.resultJson} -> 'billingType'), - 'costUsd', coalesce( - ${heartbeatRuns.resultJson} -> 'costUsd', - ${heartbeatRuns.resultJson} -> 'cost_usd', - ${heartbeatRuns.resultJson} -> 'total_cost_usd' - ), - 'cost_usd', coalesce( - ${heartbeatRuns.resultJson} -> 'cost_usd', - ${heartbeatRuns.resultJson} -> 'costUsd', - ${heartbeatRuns.resultJson} -> 'total_cost_usd' - ), - 'total_cost_usd', coalesce( - ${heartbeatRuns.resultJson} -> 'total_cost_usd', - ${heartbeatRuns.resultJson} -> 'cost_usd', - ${heartbeatRuns.resultJson} -> 'costUsd' - ) - )) - end - `.as("resultJson"); - return { - list: (filters) => { - const conditions = [eq(activityLog.companyId, filters.companyId)]; - if (filters.agentId) { - conditions.push(eq(activityLog.agentId, filters.agentId)); - } - if (filters.entityType) { - conditions.push(eq(activityLog.entityType, filters.entityType)); - } - if (filters.entityId) { - conditions.push(eq(activityLog.entityId, filters.entityId)); - } - return db.select({ activityLog }).from(activityLog).leftJoin( - issues, - and( - eq(activityLog.entityType, sql`'issue'`), - eq(activityLog.entityId, issueIdAsText) - ) - ).where( - and( - ...conditions, - or( - sql`${activityLog.entityType} != 'issue'`, - isNull(issues.hiddenAt) - ) - ) - ).orderBy(desc(activityLog.createdAt)).then((rows) => rows.map((r5) => r5.activityLog)); - }, - forIssue: (issueId) => db.select().from(activityLog).where( - and( - eq(activityLog.entityType, "issue"), - eq(activityLog.entityId, issueId) - ) - ).orderBy(desc(activityLog.createdAt)), - runsForIssue: (companyId, issueId) => db.select({ - runId: heartbeatRuns.id, - status: heartbeatRuns.status, - agentId: heartbeatRuns.agentId, - adapterType: agents.adapterType, - startedAt: heartbeatRuns.startedAt, - finishedAt: heartbeatRuns.finishedAt, - createdAt: heartbeatRuns.createdAt, - invocationSource: heartbeatRuns.invocationSource, - usageJson: summarizedUsageJson, - resultJson: summarizedResultJson, - logBytes: heartbeatRuns.logBytes - }).from(heartbeatRuns).innerJoin( - agents, - and( - eq(agents.id, heartbeatRuns.agentId), - eq(agents.companyId, heartbeatRuns.companyId) - ) - ).where( - and( - eq(heartbeatRuns.companyId, companyId), - or( - sql`${heartbeatRuns.contextSnapshot} ->> 'issueId' = ${issueId}`, - sql`exists ( - select 1 - from ${activityLog} - where ${activityLog.companyId} = ${companyId} - and ${activityLog.entityType} = 'issue' - and ${activityLog.entityId} = ${issueId} - and ${activityLog.runId} = ${heartbeatRuns.id} - )` - ) - ) - ).orderBy(desc(heartbeatRuns.createdAt)), - issuesForRun: async (runId) => { - const run = await db.select({ - companyId: heartbeatRuns.companyId, - contextSnapshot: heartbeatRuns.contextSnapshot - }).from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)).then((rows) => rows[0] ?? null); - if (!run) return []; - const fromActivity = await db.selectDistinctOn([issueIdAsText], { - issueId: issues.id, - identifier: issues.identifier, - title: issues.title, - status: issues.status, - priority: issues.priority - }).from(activityLog).innerJoin(issues, eq(activityLog.entityId, issueIdAsText)).where( - and( - eq(activityLog.companyId, run.companyId), - eq(activityLog.runId, runId), - eq(activityLog.entityType, "issue"), - isNull(issues.hiddenAt) - ) - ).orderBy(issueIdAsText); - const context = run.contextSnapshot; - const contextIssueId = context && typeof context === "object" && typeof context.issueId === "string" ? context.issueId : null; - if (!contextIssueId) return fromActivity; - if (fromActivity.some((issue2) => issue2.issueId === contextIssueId)) return fromActivity; - const fromContext = await db.select({ - issueId: issues.id, - identifier: issues.identifier, - title: issues.title, - status: issues.status, - priority: issues.priority - }).from(issues).where( - and( - eq(issues.companyId, run.companyId), - eq(issues.id, contextIssueId), - isNull(issues.hiddenAt) - ) - ).then((rows) => rows[0] ?? null); - if (!fromContext) return fromActivity; - return [fromContext, ...fromActivity]; - }, - create: (data2) => db.insert(activityLog).values(data2).returning().then((rows) => rows[0]) - }; -} - -// server/src/services/approvals.ts -init_drizzle_orm(); -init_src2(); - -// server/src/services/budgets.ts -init_drizzle_orm(); -init_src2(); - -// server/src/services/activity-log.ts -init_src2(); -import { randomUUID as randomUUID3 } from "node:crypto"; - -// server/src/services/live-events.ts -import { EventEmitter } from "node:events"; -var emitter = new EventEmitter(); -emitter.setMaxListeners(0); -var nextEventId = 0; -function toLiveEvent(input) { - nextEventId += 1; - return { - id: nextEventId, - companyId: input.companyId, - type: input.type, - createdAt: (/* @__PURE__ */ new Date()).toISOString(), - payload: input.payload ?? {} - }; -} -function publishLiveEvent(input) { - const event = toLiveEvent(input); - emitter.emit(input.companyId, event); - return event; -} -function publishGlobalLiveEvent(input) { - const event = toLiveEvent({ companyId: "*", type: input.type, payload: input.payload }); - emitter.emit("*", event); - return event; -} -function subscribeCompanyLiveEvents(companyId, listener) { - emitter.on(companyId, listener); - return () => emitter.off(companyId, listener); -} - -// server/src/services/activity-log.ts -var PLUGIN_EVENT_SET = new Set(PLUGIN_EVENT_TYPES); -var _pluginEventBus = null; -function setPluginEventBus(bus) { - if (_pluginEventBus) { - logger.warn("setPluginEventBus called more than once, replacing existing bus"); - } - _pluginEventBus = bus; -} -async function logActivity(db, input) { - const currentUserRedactionOptions = { - enabled: (await instanceSettingsService(db).getGeneral()).censorUsernameInLogs - }; - const sanitizedDetails = input.details ? sanitizeRecord(input.details) : null; - const redactedDetails = sanitizedDetails ? redactCurrentUserValue(sanitizedDetails, currentUserRedactionOptions) : null; - await db.insert(activityLog).values({ - companyId: input.companyId, - actorType: input.actorType, - actorId: input.actorId, - action: input.action, - entityType: input.entityType, - entityId: input.entityId, - agentId: input.agentId ?? null, - runId: input.runId ?? null, - details: redactedDetails - }); - publishLiveEvent({ - companyId: input.companyId, - type: "activity.logged", - payload: { - actorType: input.actorType, - actorId: input.actorId, - action: input.action, - entityType: input.entityType, - entityId: input.entityId, - agentId: input.agentId ?? null, - runId: input.runId ?? null, - details: redactedDetails - } - }); - if (_pluginEventBus && PLUGIN_EVENT_SET.has(input.action)) { - const event = { - eventId: randomUUID3(), - eventType: input.action, - occurredAt: (/* @__PURE__ */ new Date()).toISOString(), - actorId: input.actorId, - actorType: input.actorType, - entityId: input.entityId, - entityType: input.entityType, - companyId: input.companyId, - payload: { - ...redactedDetails, - agentId: input.agentId ?? null, - runId: input.runId ?? null - } - }; - void _pluginEventBus.emit(event).then(({ errors }) => { - for (const { pluginId, error: error50 } of errors) { - logger.warn({ pluginId, eventType: event.eventType, err: error50 }, "plugin event handler failed"); - } - }).catch(() => { - }); - } -} - -// server/src/services/budgets.ts -function currentUtcMonthWindow(now2 = /* @__PURE__ */ new Date()) { - const year3 = now2.getUTCFullYear(); - const month = now2.getUTCMonth(); - const start = new Date(Date.UTC(year3, month, 1, 0, 0, 0, 0)); - const end = new Date(Date.UTC(year3, month + 1, 1, 0, 0, 0, 0)); - return { start, end }; -} -function resolveWindow(windowKind, now2 = /* @__PURE__ */ new Date()) { - if (windowKind === "lifetime") { - return { - start: new Date(Date.UTC(1970, 0, 1, 0, 0, 0, 0)), - end: new Date(Date.UTC(9999, 0, 1, 0, 0, 0, 0)) - }; - } - return currentUtcMonthWindow(now2); -} -function budgetStatusFromObserved(observedAmount, amount, warnPercent) { - if (amount <= 0) return "ok"; - if (observedAmount >= amount) return "hard_stop"; - if (observedAmount >= Math.ceil(amount * warnPercent / 100)) return "warning"; - return "ok"; -} -function normalizeScopeName(scopeType, name) { - if (scopeType === "company") return name; - return name.trim().length > 0 ? name : scopeType; -} -async function resolveScopeRecord(db, scopeType, scopeId) { - if (scopeType === "company") { - const row2 = await db.select({ - companyId: companies.id, - name: companies.name, - status: companies.status, - pauseReason: companies.pauseReason, - pausedAt: companies.pausedAt - }).from(companies).where(eq(companies.id, scopeId)).then((rows) => rows[0] ?? null); - if (!row2) throw notFound("Company not found"); - return { - companyId: row2.companyId, - name: row2.name, - paused: row2.status === "paused" || Boolean(row2.pausedAt), - pauseReason: row2.pauseReason ?? null - }; - } - if (scopeType === "agent") { - const row2 = await db.select({ - companyId: agents.companyId, - name: agents.name, - status: agents.status, - pauseReason: agents.pauseReason - }).from(agents).where(eq(agents.id, scopeId)).then((rows) => rows[0] ?? null); - if (!row2) throw notFound("Agent not found"); - return { - companyId: row2.companyId, - name: row2.name, - paused: row2.status === "paused", - pauseReason: row2.pauseReason ?? null - }; - } - const row = await db.select({ - companyId: projects.companyId, - name: projects.name, - pauseReason: projects.pauseReason, - pausedAt: projects.pausedAt - }).from(projects).where(eq(projects.id, scopeId)).then((rows) => rows[0] ?? null); - if (!row) throw notFound("Project not found"); - return { - companyId: row.companyId, - name: row.name, - paused: Boolean(row.pausedAt), - pauseReason: row.pauseReason ?? null - }; -} -async function computeObservedAmount(db, policy) { - if (policy.metric !== "billed_cents") return 0; - const conditions = [eq(costEvents.companyId, policy.companyId)]; - if (policy.scopeType === "agent") conditions.push(eq(costEvents.agentId, policy.scopeId)); - if (policy.scopeType === "project") conditions.push(eq(costEvents.projectId, policy.scopeId)); - const { start, end } = resolveWindow(policy.windowKind); - if (policy.windowKind === "calendar_month_utc") { - conditions.push(gte(costEvents.occurredAt, start)); - conditions.push(lt(costEvents.occurredAt, end)); - } - const [row] = await db.select({ - total: sql`coalesce(sum(${costEvents.costCents}), 0)::int` - }).from(costEvents).where(and(...conditions)); - return Number(row?.total ?? 0); -} -function buildApprovalPayload(input) { - return { - scopeType: input.policy.scopeType, - scopeId: input.policy.scopeId, - scopeName: input.scopeName, - metric: input.policy.metric, - windowKind: input.policy.windowKind, - thresholdType: input.thresholdType, - budgetAmount: input.policy.amount, - observedAmount: input.amountObserved, - warnPercent: input.policy.warnPercent, - windowStart: input.windowStart.toISOString(), - windowEnd: input.windowEnd.toISOString(), - policyId: input.policy.id, - guidance: "Raise the budget and resume the scope, or keep the scope paused." - }; -} -async function markApprovalStatus(db, approvalId, status, decisionNote, decidedByUserId) { - if (!approvalId) return; - await db.update(approvals).set({ - status, - decisionNote: decisionNote ?? null, - decidedByUserId, - decidedAt: /* @__PURE__ */ new Date(), - updatedAt: /* @__PURE__ */ new Date() - }).where(eq(approvals.id, approvalId)); -} -function budgetService(db, hooks = {}) { - async function pauseScopeForBudget(policy) { - const now2 = /* @__PURE__ */ new Date(); - if (policy.scopeType === "agent") { - await db.update(agents).set({ - status: "paused", - pauseReason: "budget", - pausedAt: now2, - updatedAt: now2 - }).where(and(eq(agents.id, policy.scopeId), inArray(agents.status, ["active", "idle", "running", "error"]))); - return; - } - if (policy.scopeType === "project") { - await db.update(projects).set({ - pauseReason: "budget", - pausedAt: now2, - updatedAt: now2 - }).where(eq(projects.id, policy.scopeId)); - return; - } - await db.update(companies).set({ - status: "paused", - pauseReason: "budget", - pausedAt: now2, - updatedAt: now2 - }).where(eq(companies.id, policy.scopeId)); - } - async function pauseAndCancelScopeForBudget(policy) { - await pauseScopeForBudget(policy); - await hooks.cancelWorkForScope?.({ - companyId: policy.companyId, - scopeType: policy.scopeType, - scopeId: policy.scopeId - }); - } - async function resumeScopeFromBudget(policy) { - const now2 = /* @__PURE__ */ new Date(); - if (policy.scopeType === "agent") { - await db.update(agents).set({ - status: "idle", - pauseReason: null, - pausedAt: null, - updatedAt: now2 - }).where(and(eq(agents.id, policy.scopeId), eq(agents.pauseReason, "budget"))); - return; - } - if (policy.scopeType === "project") { - await db.update(projects).set({ - pauseReason: null, - pausedAt: null, - updatedAt: now2 - }).where(and(eq(projects.id, policy.scopeId), eq(projects.pauseReason, "budget"))); - return; - } - await db.update(companies).set({ - status: "active", - pauseReason: null, - pausedAt: null, - updatedAt: now2 - }).where(and(eq(companies.id, policy.scopeId), eq(companies.pauseReason, "budget"))); - } - async function getPolicyRow(policyId) { - const policy = await db.select().from(budgetPolicies).where(eq(budgetPolicies.id, policyId)).then((rows) => rows[0] ?? null); - if (!policy) throw notFound("Budget policy not found"); - return policy; - } - async function listPolicyRows(companyId) { - return db.select().from(budgetPolicies).where(eq(budgetPolicies.companyId, companyId)).orderBy(desc(budgetPolicies.updatedAt)); - } - async function buildPolicySummary(policy) { - const scope = await resolveScopeRecord(db, policy.scopeType, policy.scopeId); - const observedAmount = await computeObservedAmount(db, policy); - const { start, end } = resolveWindow(policy.windowKind); - const amount = policy.isActive ? policy.amount : 0; - const utilizationPercent = amount > 0 ? Number((observedAmount / amount * 100).toFixed(2)) : 0; - return { - policyId: policy.id, - companyId: policy.companyId, - scopeType: policy.scopeType, - scopeId: policy.scopeId, - scopeName: normalizeScopeName(policy.scopeType, scope.name), - metric: policy.metric, - windowKind: policy.windowKind, - amount, - observedAmount, - remainingAmount: amount > 0 ? Math.max(0, amount - observedAmount) : 0, - utilizationPercent, - warnPercent: policy.warnPercent, - hardStopEnabled: policy.hardStopEnabled, - notifyEnabled: policy.notifyEnabled, - isActive: policy.isActive, - status: policy.isActive ? budgetStatusFromObserved(observedAmount, amount, policy.warnPercent) : "ok", - paused: scope.paused, - pauseReason: scope.pauseReason, - windowStart: start, - windowEnd: end - }; - } - async function createIncidentIfNeeded(policy, thresholdType, amountObserved) { - const { start, end } = resolveWindow(policy.windowKind); - const existing = await db.select().from(budgetIncidents).where( - and( - eq(budgetIncidents.policyId, policy.id), - eq(budgetIncidents.windowStart, start), - eq(budgetIncidents.thresholdType, thresholdType), - ne(budgetIncidents.status, "dismissed") - ) - ).then((rows) => rows[0] ?? null); - if (existing) return existing; - const scope = await resolveScopeRecord(db, policy.scopeType, policy.scopeId); - const payload2 = buildApprovalPayload({ - policy, - scopeName: normalizeScopeName(policy.scopeType, scope.name), - thresholdType, - amountObserved, - windowStart: start, - windowEnd: end - }); - const approval = thresholdType === "hard" ? await db.insert(approvals).values({ - companyId: policy.companyId, - type: "budget_override_required", - requestedByUserId: null, - requestedByAgentId: null, - status: "pending", - payload: payload2 - }).returning().then((rows) => rows[0] ?? null) : null; - return db.insert(budgetIncidents).values({ - companyId: policy.companyId, - policyId: policy.id, - scopeType: policy.scopeType, - scopeId: policy.scopeId, - metric: policy.metric, - windowKind: policy.windowKind, - windowStart: start, - windowEnd: end, - thresholdType, - amountLimit: policy.amount, - amountObserved, - status: "open", - approvalId: approval?.id ?? null - }).returning().then((rows) => rows[0] ?? null); - } - async function resolveOpenSoftIncidents(policyId) { - await db.update(budgetIncidents).set({ - status: "resolved", - resolvedAt: /* @__PURE__ */ new Date(), - updatedAt: /* @__PURE__ */ new Date() - }).where( - and( - eq(budgetIncidents.policyId, policyId), - eq(budgetIncidents.thresholdType, "soft"), - eq(budgetIncidents.status, "open") - ) - ); - } - async function resolveOpenIncidentsForPolicy(policyId, approvalStatus, decidedByUserId) { - const openRows = await db.select().from(budgetIncidents).where(and(eq(budgetIncidents.policyId, policyId), eq(budgetIncidents.status, "open"))); - await db.update(budgetIncidents).set({ - status: "resolved", - resolvedAt: /* @__PURE__ */ new Date(), - updatedAt: /* @__PURE__ */ new Date() - }).where(and(eq(budgetIncidents.policyId, policyId), eq(budgetIncidents.status, "open"))); - if (!approvalStatus || !decidedByUserId) return; - for (const row of openRows) { - await markApprovalStatus(db, row.approvalId ?? null, approvalStatus, "Resolved via budget update", decidedByUserId); - } - } - async function hydrateIncidentRows(rows) { - const approvalIds = rows.map((row) => row.approvalId).filter((value) => Boolean(value)); - const approvalRows = approvalIds.length > 0 ? await db.select({ id: approvals.id, status: approvals.status }).from(approvals).where(inArray(approvals.id, approvalIds)) : []; - const approvalStatusById = new Map(approvalRows.map((row) => [row.id, row.status])); - return Promise.all( - rows.map(async (row) => { - const scope = await resolveScopeRecord(db, row.scopeType, row.scopeId); - return { - id: row.id, - companyId: row.companyId, - policyId: row.policyId, - scopeType: row.scopeType, - scopeId: row.scopeId, - scopeName: normalizeScopeName(row.scopeType, scope.name), - metric: row.metric, - windowKind: row.windowKind, - windowStart: row.windowStart, - windowEnd: row.windowEnd, - thresholdType: row.thresholdType, - amountLimit: row.amountLimit, - amountObserved: row.amountObserved, - status: row.status, - approvalId: row.approvalId ?? null, - approvalStatus: row.approvalId ? approvalStatusById.get(row.approvalId) ?? null : null, - resolvedAt: row.resolvedAt ?? null, - createdAt: row.createdAt, - updatedAt: row.updatedAt - }; - }) - ); - } - return { - listPolicies: async (companyId) => { - const rows = await listPolicyRows(companyId); - return rows.map((row) => ({ - ...row, - scopeType: row.scopeType, - metric: row.metric, - windowKind: row.windowKind - })); - }, - upsertPolicy: async (companyId, input, actorUserId) => { - const scope = await resolveScopeRecord(db, input.scopeType, input.scopeId); - if (scope.companyId !== companyId) { - throw unprocessable("Budget scope does not belong to company"); - } - const metric = input.metric ?? "billed_cents"; - const windowKind = input.windowKind ?? (input.scopeType === "project" ? "lifetime" : "calendar_month_utc"); - const amount = Math.max(0, Math.floor(input.amount)); - const nextIsActive = amount > 0 && (input.isActive ?? true); - const existing = await db.select().from(budgetPolicies).where( - and( - eq(budgetPolicies.companyId, companyId), - eq(budgetPolicies.scopeType, input.scopeType), - eq(budgetPolicies.scopeId, input.scopeId), - eq(budgetPolicies.metric, metric), - eq(budgetPolicies.windowKind, windowKind) - ) - ).then((rows) => rows[0] ?? null); - const now2 = /* @__PURE__ */ new Date(); - const row = existing ? await db.update(budgetPolicies).set({ - amount, - warnPercent: input.warnPercent ?? existing.warnPercent, - hardStopEnabled: input.hardStopEnabled ?? existing.hardStopEnabled, - notifyEnabled: input.notifyEnabled ?? existing.notifyEnabled, - isActive: nextIsActive, - updatedByUserId: actorUserId, - updatedAt: now2 - }).where(eq(budgetPolicies.id, existing.id)).returning().then((rows) => rows[0]) : await db.insert(budgetPolicies).values({ - companyId, - scopeType: input.scopeType, - scopeId: input.scopeId, - metric, - windowKind, - amount, - warnPercent: input.warnPercent ?? 80, - hardStopEnabled: input.hardStopEnabled ?? true, - notifyEnabled: input.notifyEnabled ?? true, - isActive: nextIsActive, - createdByUserId: actorUserId, - updatedByUserId: actorUserId - }).returning().then((rows) => rows[0]); - if (input.scopeType === "company" && windowKind === "calendar_month_utc") { - await db.update(companies).set({ - budgetMonthlyCents: amount, - updatedAt: now2 - }).where(eq(companies.id, input.scopeId)); - } - if (input.scopeType === "agent" && windowKind === "calendar_month_utc") { - await db.update(agents).set({ - budgetMonthlyCents: amount, - updatedAt: now2 - }).where(eq(agents.id, input.scopeId)); - } - if (amount > 0) { - const observedAmount = await computeObservedAmount(db, row); - if (observedAmount < amount) { - await resumeScopeFromBudget(row); - await resolveOpenIncidentsForPolicy(row.id, actorUserId ? "approved" : null, actorUserId); - } else { - const softThreshold = Math.ceil(row.amount * row.warnPercent / 100); - if (row.notifyEnabled && observedAmount >= softThreshold) { - await createIncidentIfNeeded(row, "soft", observedAmount); - } - if (row.hardStopEnabled && observedAmount >= row.amount) { - await resolveOpenSoftIncidents(row.id); - await createIncidentIfNeeded(row, "hard", observedAmount); - await pauseAndCancelScopeForBudget(row); - } - } - } else { - await resumeScopeFromBudget(row); - await resolveOpenIncidentsForPolicy(row.id, actorUserId ? "approved" : null, actorUserId); - } - await logActivity(db, { - companyId, - actorType: "user", - actorId: actorUserId ?? "board", - action: "budget.policy_upserted", - entityType: "budget_policy", - entityId: row.id, - details: { - scopeType: row.scopeType, - scopeId: row.scopeId, - amount: row.amount, - windowKind: row.windowKind - } - }); - return buildPolicySummary(row); - }, - overview: async (companyId) => { - const rows = await listPolicyRows(companyId); - const policies = await Promise.all(rows.map((row) => buildPolicySummary(row))); - const activeIncidentRows = await db.select().from(budgetIncidents).where(and(eq(budgetIncidents.companyId, companyId), eq(budgetIncidents.status, "open"))).orderBy(desc(budgetIncidents.createdAt)); - const activeIncidents = await hydrateIncidentRows(activeIncidentRows); - return { - companyId, - policies, - activeIncidents, - pausedAgentCount: policies.filter((policy) => policy.scopeType === "agent" && policy.paused).length, - pausedProjectCount: policies.filter((policy) => policy.scopeType === "project" && policy.paused).length, - pendingApprovalCount: activeIncidents.filter((incident) => incident.approvalStatus === "pending").length - }; - }, - evaluateCostEvent: async (event) => { - const candidatePolicies = await db.select().from(budgetPolicies).where( - and( - eq(budgetPolicies.companyId, event.companyId), - eq(budgetPolicies.isActive, true), - inArray(budgetPolicies.scopeType, ["company", "agent", "project"]) - ) - ); - const relevantPolicies = candidatePolicies.filter((policy) => { - if (policy.scopeType === "company") return policy.scopeId === event.companyId; - if (policy.scopeType === "agent") return policy.scopeId === event.agentId; - if (policy.scopeType === "project") return Boolean(event.projectId) && policy.scopeId === event.projectId; - return false; - }); - for (const policy of relevantPolicies) { - if (policy.metric !== "billed_cents" || policy.amount <= 0) continue; - const observedAmount = await computeObservedAmount(db, policy); - const softThreshold = Math.ceil(policy.amount * policy.warnPercent / 100); - if (policy.notifyEnabled && observedAmount >= softThreshold) { - const softIncident = await createIncidentIfNeeded(policy, "soft", observedAmount); - if (softIncident) { - await logActivity(db, { - companyId: policy.companyId, - actorType: "system", - actorId: "budget_service", - action: "budget.soft_threshold_crossed", - entityType: "budget_incident", - entityId: softIncident.id, - details: { - scopeType: policy.scopeType, - scopeId: policy.scopeId, - amountObserved: observedAmount, - amountLimit: policy.amount - } - }); - } - } - if (policy.hardStopEnabled && observedAmount >= policy.amount) { - await resolveOpenSoftIncidents(policy.id); - const hardIncident = await createIncidentIfNeeded(policy, "hard", observedAmount); - await pauseAndCancelScopeForBudget(policy); - if (hardIncident) { - await logActivity(db, { - companyId: policy.companyId, - actorType: "system", - actorId: "budget_service", - action: "budget.hard_threshold_crossed", - entityType: "budget_incident", - entityId: hardIncident.id, - details: { - scopeType: policy.scopeType, - scopeId: policy.scopeId, - amountObserved: observedAmount, - amountLimit: policy.amount, - approvalId: hardIncident.approvalId ?? null - } - }); - } - } - } - }, - getInvocationBlock: async (companyId, agentId, context) => { - const agent = await db.select({ - status: agents.status, - pauseReason: agents.pauseReason, - companyId: agents.companyId, - name: agents.name - }).from(agents).where(eq(agents.id, agentId)).then((rows) => rows[0] ?? null); - if (!agent || agent.companyId !== companyId) throw notFound("Agent not found"); - const company = await db.select({ - status: companies.status, - pauseReason: companies.pauseReason, - name: companies.name - }).from(companies).where(eq(companies.id, companyId)).then((rows) => rows[0] ?? null); - if (!company) throw notFound("Company not found"); - if (company.status === "paused") { - return { - scopeType: "company", - scopeId: companyId, - scopeName: company.name, - reason: company.pauseReason === "budget" ? "Company is paused because its budget hard-stop was reached." : "Company is paused and cannot start new work." - }; - } - const companyPolicy = await db.select().from(budgetPolicies).where( - and( - eq(budgetPolicies.companyId, companyId), - eq(budgetPolicies.scopeType, "company"), - eq(budgetPolicies.scopeId, companyId), - eq(budgetPolicies.isActive, true), - eq(budgetPolicies.metric, "billed_cents") - ) - ).then((rows) => rows[0] ?? null); - if (companyPolicy && companyPolicy.hardStopEnabled && companyPolicy.amount > 0) { - const observed = await computeObservedAmount(db, companyPolicy); - if (observed >= companyPolicy.amount) { - return { - scopeType: "company", - scopeId: companyId, - scopeName: company.name, - reason: "Company cannot start new work because its budget hard-stop is exceeded." - }; - } - } - if (agent.status === "paused" && agent.pauseReason === "budget") { - return { - scopeType: "agent", - scopeId: agentId, - scopeName: agent.name, - reason: "Agent is paused because its budget hard-stop was reached." - }; - } - const agentPolicy = await db.select().from(budgetPolicies).where( - and( - eq(budgetPolicies.companyId, companyId), - eq(budgetPolicies.scopeType, "agent"), - eq(budgetPolicies.scopeId, agentId), - eq(budgetPolicies.isActive, true), - eq(budgetPolicies.metric, "billed_cents") - ) - ).then((rows) => rows[0] ?? null); - if (agentPolicy && agentPolicy.hardStopEnabled && agentPolicy.amount > 0) { - const observed = await computeObservedAmount(db, agentPolicy); - if (observed >= agentPolicy.amount) { - return { - scopeType: "agent", - scopeId: agentId, - scopeName: agent.name, - reason: "Agent cannot start because its budget hard-stop is still exceeded." - }; - } - } - const candidateProjectId = context?.projectId ?? null; - if (!candidateProjectId) return null; - const project = await db.select({ - id: projects.id, - name: projects.name, - companyId: projects.companyId, - pauseReason: projects.pauseReason, - pausedAt: projects.pausedAt - }).from(projects).where(eq(projects.id, candidateProjectId)).then((rows) => rows[0] ?? null); - if (!project || project.companyId !== companyId) return null; - const projectPolicy = await db.select().from(budgetPolicies).where( - and( - eq(budgetPolicies.companyId, companyId), - eq(budgetPolicies.scopeType, "project"), - eq(budgetPolicies.scopeId, project.id), - eq(budgetPolicies.isActive, true), - eq(budgetPolicies.metric, "billed_cents") - ) - ).then((rows) => rows[0] ?? null); - if (projectPolicy && projectPolicy.hardStopEnabled && projectPolicy.amount > 0) { - const observed = await computeObservedAmount(db, projectPolicy); - if (observed >= projectPolicy.amount) { - return { - scopeType: "project", - scopeId: project.id, - scopeName: project.name, - reason: "Project cannot start work because its budget hard-stop is still exceeded." - }; - } - } - if (!project.pausedAt || project.pauseReason !== "budget") return null; - return { - scopeType: "project", - scopeId: project.id, - scopeName: project.name, - reason: "Project is paused because its budget hard-stop was reached." - }; - }, - resolveIncident: async (companyId, incidentId, input, actorUserId) => { - const incident = await db.select().from(budgetIncidents).where(eq(budgetIncidents.id, incidentId)).then((rows) => rows[0] ?? null); - if (!incident) throw notFound("Budget incident not found"); - if (incident.companyId !== companyId) throw notFound("Budget incident not found"); - const policy = await getPolicyRow(incident.policyId); - if (input.action === "raise_budget_and_resume") { - const nextAmount = Math.max(0, Math.floor(input.amount ?? 0)); - const currentObserved = await computeObservedAmount(db, policy); - if (nextAmount <= currentObserved) { - throw unprocessable("New budget must exceed current observed spend"); - } - const now2 = /* @__PURE__ */ new Date(); - await db.update(budgetPolicies).set({ - amount: nextAmount, - isActive: true, - updatedByUserId: actorUserId, - updatedAt: now2 - }).where(eq(budgetPolicies.id, policy.id)); - if (policy.scopeType === "company" && policy.windowKind === "calendar_month_utc") { - await db.update(companies).set({ budgetMonthlyCents: nextAmount, updatedAt: now2 }).where(eq(companies.id, policy.scopeId)); - } - if (policy.scopeType === "agent" && policy.windowKind === "calendar_month_utc") { - await db.update(agents).set({ budgetMonthlyCents: nextAmount, updatedAt: now2 }).where(eq(agents.id, policy.scopeId)); - } - await resumeScopeFromBudget(policy); - await db.update(budgetIncidents).set({ - status: "resolved", - resolvedAt: now2, - updatedAt: now2 - }).where(and(eq(budgetIncidents.policyId, policy.id), eq(budgetIncidents.status, "open"))); - await markApprovalStatus(db, incident.approvalId ?? null, "approved", input.decisionNote, actorUserId); - } else { - await db.update(budgetIncidents).set({ - status: "dismissed", - resolvedAt: /* @__PURE__ */ new Date(), - updatedAt: /* @__PURE__ */ new Date() - }).where(eq(budgetIncidents.id, incident.id)); - await markApprovalStatus(db, incident.approvalId ?? null, "rejected", input.decisionNote, actorUserId); - } - await logActivity(db, { - companyId: incident.companyId, - actorType: "user", - actorId: actorUserId, - action: "budget.incident_resolved", - entityType: "budget_incident", - entityId: incident.id, - details: { - action: input.action, - amount: input.amount ?? null, - scopeType: incident.scopeType, - scopeId: incident.scopeId - } - }); - const [updated] = await hydrateIncidentRows([{ - ...incident, - status: input.action === "raise_budget_and_resume" ? "resolved" : "dismissed", - resolvedAt: /* @__PURE__ */ new Date(), - updatedAt: /* @__PURE__ */ new Date() - }]); - return updated; - } - }; -} - -// server/src/services/hire-hook.ts -init_drizzle_orm(); -init_src2(); -var HIRE_APPROVED_MESSAGE = "Tell your user that your hire was approved, now they should assign you a task in Taskcore or ask you to create issues."; -async function notifyHireApproved(db, input) { - const { companyId, agentId, source, sourceId } = input; - const approvedAt = input.approvedAt ?? /* @__PURE__ */ new Date(); - const row = await db.select().from(agents).where(and(eq(agents.id, agentId), eq(agents.companyId, companyId))).then((rows) => rows[0] ?? null); - if (!row) { - logger.warn({ companyId, agentId, source, sourceId }, "hire hook: agent not found in company, skipping"); - return; - } - const adapterType = row.adapterType ?? "process"; - const adapter = findActiveServerAdapter(adapterType); - const onHireApproved = adapter?.onHireApproved; - if (!onHireApproved) { - return; - } - const payload2 = { - companyId, - agentId, - agentName: row.name, - adapterType, - source, - sourceId, - approvedAt: approvedAt.toISOString(), - message: HIRE_APPROVED_MESSAGE - }; - const adapterConfig = typeof row.adapterConfig === "object" && row.adapterConfig !== null && !Array.isArray(row.adapterConfig) ? row.adapterConfig : {}; - try { - const result = await onHireApproved(payload2, adapterConfig); - if (result.ok) { - await logActivity(db, { - companyId, - actorType: "system", - actorId: "hire_hook", - action: "hire_hook.succeeded", - entityType: "agent", - entityId: agentId, - details: { source, sourceId, adapterType } - }); - return; - } - logger.warn( - { companyId, agentId, adapterType, source, sourceId, error: result.error, detail: result.detail }, - "hire hook: adapter returned failure" - ); - await logActivity(db, { - companyId, - actorType: "system", - actorId: "hire_hook", - action: "hire_hook.failed", - entityType: "agent", - entityId: agentId, - details: { source, sourceId, adapterType, error: result.error, detail: result.detail } - }); - } catch (err) { - logger.error( - { err, companyId, agentId, adapterType, source, sourceId }, - "hire hook: adapter threw" - ); - await logActivity(db, { - companyId, - actorType: "system", - actorId: "hire_hook", - action: "hire_hook.error", - entityType: "agent", - entityId: agentId, - details: { - source, - sourceId, - adapterType, - error: err instanceof Error ? err.message : String(err) - } - }); - } -} - -// server/src/services/approvals.ts -function approvalService(db) { - const agentsSvc = agentService(db); - const budgets = budgetService(db); - const instanceSettings2 = instanceSettingsService(db); - const canResolveStatuses = /* @__PURE__ */ new Set(["pending", "revision_requested"]); - const resolvableStatuses = Array.from(canResolveStatuses); - function redactApprovalComment(comment, censorUsernameInLogs) { - return { - ...comment, - body: redactCurrentUserText(comment.body, { enabled: censorUsernameInLogs }) - }; - } - async function getExistingApproval(id) { - const existing = await db.select().from(approvals).where(eq(approvals.id, id)).then((rows) => rows[0] ?? null); - if (!existing) throw notFound("Approval not found"); - return existing; - } - async function resolveApproval(id, targetStatus, decidedByUserId, decisionNote) { - const existing = await getExistingApproval(id); - if (!canResolveStatuses.has(existing.status)) { - if (existing.status === targetStatus) { - return { approval: existing, applied: false }; - } - throw unprocessable( - `Only pending or revision requested approvals can be ${targetStatus === "approved" ? "approved" : "rejected"}` - ); - } - const now2 = /* @__PURE__ */ new Date(); - const updated = await db.update(approvals).set({ - status: targetStatus, - decidedByUserId, - decisionNote: decisionNote ?? null, - decidedAt: now2, - updatedAt: now2 - }).where(and(eq(approvals.id, id), inArray(approvals.status, resolvableStatuses))).returning().then((rows) => rows[0] ?? null); - if (updated) { - return { approval: updated, applied: true }; - } - const latest = await getExistingApproval(id); - if (latest.status === targetStatus) { - return { approval: latest, applied: false }; - } - throw unprocessable( - `Only pending or revision requested approvals can be ${targetStatus === "approved" ? "approved" : "rejected"}` - ); - } - return { - list: (companyId, status) => { - const conditions = [eq(approvals.companyId, companyId)]; - if (status) conditions.push(eq(approvals.status, status)); - return db.select().from(approvals).where(and(...conditions)); - }, - getById: (id) => db.select().from(approvals).where(eq(approvals.id, id)).then((rows) => rows[0] ?? null), - create: (companyId, data2) => db.insert(approvals).values({ ...data2, companyId }).returning().then((rows) => rows[0]), - approve: async (id, decidedByUserId, decisionNote) => { - const { approval: updated, applied } = await resolveApproval( - id, - "approved", - decidedByUserId, - decisionNote - ); - let hireApprovedAgentId = null; - const now2 = /* @__PURE__ */ new Date(); - if (applied && updated.type === "hire_agent") { - const payload2 = updated.payload; - const payloadAgentId = typeof payload2.agentId === "string" ? payload2.agentId : null; - if (payloadAgentId) { - await agentsSvc.activatePendingApproval(payloadAgentId); - hireApprovedAgentId = payloadAgentId; - } else { - const created = await agentsSvc.create(updated.companyId, { - name: String(payload2.name ?? "New Agent"), - role: String(payload2.role ?? "general"), - title: typeof payload2.title === "string" ? payload2.title : null, - reportsTo: typeof payload2.reportsTo === "string" ? payload2.reportsTo : null, - capabilities: typeof payload2.capabilities === "string" ? payload2.capabilities : null, - adapterType: String(payload2.adapterType ?? "process"), - adapterConfig: typeof payload2.adapterConfig === "object" && payload2.adapterConfig !== null ? payload2.adapterConfig : {}, - budgetMonthlyCents: typeof payload2.budgetMonthlyCents === "number" ? payload2.budgetMonthlyCents : 0, - metadata: typeof payload2.metadata === "object" && payload2.metadata !== null ? payload2.metadata : null, - status: "idle", - spentMonthlyCents: 0, - permissions: void 0, - lastHeartbeatAt: null - }); - hireApprovedAgentId = created?.id ?? null; - } - if (hireApprovedAgentId) { - const budgetMonthlyCents = typeof payload2.budgetMonthlyCents === "number" ? payload2.budgetMonthlyCents : 0; - if (budgetMonthlyCents > 0) { - await budgets.upsertPolicy( - updated.companyId, - { - scopeType: "agent", - scopeId: hireApprovedAgentId, - amount: budgetMonthlyCents, - windowKind: "calendar_month_utc" - }, - decidedByUserId - ); - } - void notifyHireApproved(db, { - companyId: updated.companyId, - agentId: hireApprovedAgentId, - source: "approval", - sourceId: id, - approvedAt: now2 - }).catch(() => { - }); - } - } - return { approval: updated, applied }; - }, - reject: async (id, decidedByUserId, decisionNote) => { - const { approval: updated, applied } = await resolveApproval( - id, - "rejected", - decidedByUserId, - decisionNote - ); - if (applied && updated.type === "hire_agent") { - const payload2 = updated.payload; - const payloadAgentId = typeof payload2.agentId === "string" ? payload2.agentId : null; - if (payloadAgentId) { - await agentsSvc.terminate(payloadAgentId); - } - } - return { approval: updated, applied }; - }, - requestRevision: async (id, decidedByUserId, decisionNote) => { - const existing = await getExistingApproval(id); - if (existing.status !== "pending") { - throw unprocessable("Only pending approvals can request revision"); - } - const now2 = /* @__PURE__ */ new Date(); - return db.update(approvals).set({ - status: "revision_requested", - decidedByUserId, - decisionNote: decisionNote ?? null, - decidedAt: now2, - updatedAt: now2 - }).where(eq(approvals.id, id)).returning().then((rows) => rows[0]); - }, - resubmit: async (id, payload2) => { - const existing = await getExistingApproval(id); - if (existing.status !== "revision_requested") { - throw unprocessable("Only revision requested approvals can be resubmitted"); - } - const now2 = /* @__PURE__ */ new Date(); - return db.update(approvals).set({ - status: "pending", - payload: payload2 ?? existing.payload, - decisionNote: null, - decidedByUserId: null, - decidedAt: null, - updatedAt: now2 - }).where(eq(approvals.id, id)).returning().then((rows) => rows[0]); - }, - listComments: async (approvalId) => { - const existing = await getExistingApproval(approvalId); - const { censorUsernameInLogs } = await instanceSettings2.getGeneral(); - return db.select().from(approvalComments).where( - and( - eq(approvalComments.approvalId, approvalId), - eq(approvalComments.companyId, existing.companyId) - ) - ).orderBy(asc(approvalComments.createdAt)).then((comments) => comments.map((comment) => redactApprovalComment(comment, censorUsernameInLogs))); - }, - addComment: async (approvalId, body, actor) => { - const existing = await getExistingApproval(approvalId); - const currentUserRedactionOptions = { - enabled: (await instanceSettings2.getGeneral()).censorUsernameInLogs - }; - const redactedBody = redactCurrentUserText(body, currentUserRedactionOptions); - return db.insert(approvalComments).values({ - companyId: existing.companyId, - approvalId, - authorAgentId: actor.agentId ?? null, - authorUserId: actor.userId ?? null, - body: redactedBody - }).returning().then((rows) => redactApprovalComment(rows[0], currentUserRedactionOptions.enabled)); - } - }; -} - -// server/src/services/routines.ts -init_drizzle_orm(); -init_src2(); -import crypto4 from "node:crypto"; - -// server/src/services/cron.ts -var FIELD_SPECS = [ - { min: 0, max: 59, name: "minute" }, - { min: 0, max: 23, name: "hour" }, - { min: 1, max: 31, name: "day of month" }, - { min: 1, max: 12, name: "month" }, - { min: 0, max: 6, name: "day of week" } -]; -function parseField(token, spec) { - const values2 = /* @__PURE__ */ new Set(); - const parts = token.split(","); - for (const part of parts) { - const trimmed = part.trim(); - if (trimmed === "") { - throw new Error(`Empty element in cron ${spec.name} field`); - } - const slashIdx = trimmed.indexOf("/"); - if (slashIdx !== -1) { - const base = trimmed.slice(0, slashIdx); - const stepStr = trimmed.slice(slashIdx + 1); - const step = parseInt(stepStr, 10); - if (isNaN(step) || step <= 0) { - throw new Error( - `Invalid step "${stepStr}" in cron ${spec.name} field` - ); - } - let rangeStart = spec.min; - let rangeEnd = spec.max; - if (base === "*") { - } else if (base.includes("-")) { - const [a5, b6] = base.split("-").map((s5) => parseInt(s5, 10)); - if (isNaN(a5) || isNaN(b6)) { - throw new Error( - `Invalid range "${base}" in cron ${spec.name} field` - ); - } - rangeStart = a5; - rangeEnd = b6; - } else { - const start = parseInt(base, 10); - if (isNaN(start)) { - throw new Error( - `Invalid start "${base}" in cron ${spec.name} field` - ); - } - rangeStart = start; - } - validateBounds(rangeStart, spec); - validateBounds(rangeEnd, spec); - for (let i5 = rangeStart; i5 <= rangeEnd; i5 += step) { - values2.add(i5); - } - continue; - } - if (trimmed.includes("-")) { - const [aStr, bStr] = trimmed.split("-"); - const a5 = parseInt(aStr, 10); - const b6 = parseInt(bStr, 10); - if (isNaN(a5) || isNaN(b6)) { - throw new Error( - `Invalid range "${trimmed}" in cron ${spec.name} field` - ); - } - validateBounds(a5, spec); - validateBounds(b6, spec); - if (a5 > b6) { - throw new Error( - `Invalid range ${a5}-${b6} in cron ${spec.name} field (start > end)` - ); - } - for (let i5 = a5; i5 <= b6; i5++) { - values2.add(i5); - } - continue; - } - if (trimmed === "*") { - for (let i5 = spec.min; i5 <= spec.max; i5++) { - values2.add(i5); - } - continue; - } - const val = parseInt(trimmed, 10); - if (isNaN(val)) { - throw new Error( - `Invalid value "${trimmed}" in cron ${spec.name} field` - ); - } - validateBounds(val, spec); - values2.add(val); - } - if (values2.size === 0) { - throw new Error(`Empty result for cron ${spec.name} field`); - } - return [...values2].sort((a5, b6) => a5 - b6); -} -function validateBounds(value, spec) { - if (value < spec.min || value > spec.max) { - throw new Error( - `Value ${value} out of range [${spec.min}\u2013${spec.max}] for cron ${spec.name} field` - ); - } -} -function parseCron(expression) { - const trimmed = expression.trim(); - if (!trimmed) { - throw new Error("Cron expression must not be empty"); - } - const tokens = trimmed.split(/\s+/); - if (tokens.length !== 5) { - throw new Error( - `Cron expression must have exactly 5 fields, got ${tokens.length}: "${trimmed}"` - ); - } - return { - minutes: parseField(tokens[0], FIELD_SPECS[0]), - hours: parseField(tokens[1], FIELD_SPECS[1]), - daysOfMonth: parseField(tokens[2], FIELD_SPECS[2]), - months: parseField(tokens[3], FIELD_SPECS[3]), - daysOfWeek: parseField(tokens[4], FIELD_SPECS[4]) - }; -} -function validateCron(expression) { - try { - parseCron(expression); - return null; - } catch (err) { - return err instanceof Error ? err.message : String(err); - } -} -function nextCronTick(cron, after) { - const d5 = new Date(after.getTime()); - d5.setUTCSeconds(0, 0); - d5.setUTCMinutes(d5.getUTCMinutes() + 1); - const MAX_CRON_SEARCH_YEARS = 4; - const maxIterations = MAX_CRON_SEARCH_YEARS * 366 * 24 * 60; - for (let i5 = 0; i5 < maxIterations; i5++) { - const month = d5.getUTCMonth() + 1; - const dayOfMonth = d5.getUTCDate(); - const dayOfWeek = d5.getUTCDay(); - const hour2 = d5.getUTCHours(); - const minute2 = d5.getUTCMinutes(); - if (!cron.months.includes(month)) { - advanceToNextMonth(d5, cron.months); - continue; - } - if (!cron.daysOfMonth.includes(dayOfMonth) || !cron.daysOfWeek.includes(dayOfWeek)) { - d5.setUTCDate(d5.getUTCDate() + 1); - d5.setUTCHours(0, 0, 0, 0); - continue; - } - if (!cron.hours.includes(hour2)) { - const nextHour = findNext(cron.hours, hour2); - if (nextHour !== null) { - d5.setUTCHours(nextHour, 0, 0, 0); - } else { - d5.setUTCDate(d5.getUTCDate() + 1); - d5.setUTCHours(0, 0, 0, 0); - } - continue; - } - if (!cron.minutes.includes(minute2)) { - const nextMin = findNext(cron.minutes, minute2); - if (nextMin !== null) { - d5.setUTCMinutes(nextMin, 0, 0); - } else { - d5.setUTCHours(d5.getUTCHours() + 1, 0, 0, 0); - } - continue; - } - return new Date(d5.getTime()); - } - return null; -} -function findNext(sortedValues, current) { - for (const v5 of sortedValues) { - if (v5 > current) return v5; - } - return null; -} -function advanceToNextMonth(d5, months2) { - let year3 = d5.getUTCFullYear(); - let month = d5.getUTCMonth() + 1; - for (let i5 = 0; i5 < 48; i5++) { - month++; - if (month > 12) { - month = 1; - year3++; - } - if (months2.includes(month)) { - d5.setUTCFullYear(year3, month - 1, 1); - d5.setUTCHours(0, 0, 0, 0); - return; - } - } -} - -// server/src/services/heartbeat.ts -init_drizzle_orm(); -init_src2(); -import fs32 from "node:fs/promises"; -import path39 from "node:path"; -import { execFile as execFileCallback } from "node:child_process"; -import { promisify as promisify5 } from "node:util"; - -// server/src/services/costs.ts -init_drizzle_orm(); -init_src2(); -var METERED_BILLING_TYPE = "metered_api"; -var SUBSCRIPTION_BILLING_TYPES = ["subscription_included", "subscription_overage"]; -function currentUtcMonthWindow2(now2 = /* @__PURE__ */ new Date()) { - const year3 = now2.getUTCFullYear(); - const month = now2.getUTCMonth(); - return { - start: new Date(Date.UTC(year3, month, 1, 0, 0, 0, 0)), - end: new Date(Date.UTC(year3, month + 1, 1, 0, 0, 0, 0)) - }; -} -async function getMonthlySpendTotal(db, scope) { - const { start, end } = currentUtcMonthWindow2(); - const conditions = [ - eq(costEvents.companyId, scope.companyId), - gte(costEvents.occurredAt, start), - lt(costEvents.occurredAt, end) - ]; - if (scope.agentId) { - conditions.push(eq(costEvents.agentId, scope.agentId)); - } - const [row] = await db.select({ - total: sql`coalesce(sum(${costEvents.costCents}), 0)::int` - }).from(costEvents).where(and(...conditions)); - return Number(row?.total ?? 0); -} -function costService(db, budgetHooks = {}) { - const budgets = budgetService(db, budgetHooks); - return { - createEvent: async (companyId, data2) => { - const agent = await db.select().from(agents).where(eq(agents.id, data2.agentId)).then((rows) => rows[0] ?? null); - if (!agent) throw notFound("Agent not found"); - if (agent.companyId !== companyId) { - throw unprocessable("Agent does not belong to company"); - } - const event = await db.insert(costEvents).values({ - ...data2, - companyId, - biller: data2.biller ?? data2.provider, - billingType: data2.billingType ?? "unknown", - cachedInputTokens: data2.cachedInputTokens ?? 0 - }).returning().then((rows) => rows[0]); - const [agentMonthSpend, companyMonthSpend] = await Promise.all([ - getMonthlySpendTotal(db, { companyId, agentId: event.agentId }), - getMonthlySpendTotal(db, { companyId }) - ]); - await db.update(agents).set({ - spentMonthlyCents: agentMonthSpend, - updatedAt: /* @__PURE__ */ new Date() - }).where(eq(agents.id, event.agentId)); - await db.update(companies).set({ - spentMonthlyCents: companyMonthSpend, - updatedAt: /* @__PURE__ */ new Date() - }).where(eq(companies.id, companyId)); - await budgets.evaluateCostEvent(event); - return event; - }, - summary: async (companyId, range2) => { - const company = await db.select().from(companies).where(eq(companies.id, companyId)).then((rows) => rows[0] ?? null); - if (!company) throw notFound("Company not found"); - const conditions = [eq(costEvents.companyId, companyId)]; - if (range2?.from) conditions.push(gte(costEvents.occurredAt, range2.from)); - if (range2?.to) conditions.push(lte(costEvents.occurredAt, range2.to)); - const [{ total }] = await db.select({ - total: sql`coalesce(sum(${costEvents.costCents}), 0)::int` - }).from(costEvents).where(and(...conditions)); - const spendCents = Number(total); - const utilization = company.budgetMonthlyCents > 0 ? spendCents / company.budgetMonthlyCents * 100 : 0; - return { - companyId, - spendCents, - budgetCents: company.budgetMonthlyCents, - utilizationPercent: Number(utilization.toFixed(2)) - }; - }, - byAgent: async (companyId, range2) => { - const conditions = [eq(costEvents.companyId, companyId)]; - if (range2?.from) conditions.push(gte(costEvents.occurredAt, range2.from)); - if (range2?.to) conditions.push(lte(costEvents.occurredAt, range2.to)); - return db.select({ - agentId: costEvents.agentId, - agentName: agents.name, - agentStatus: agents.status, - costCents: sql`coalesce(sum(${costEvents.costCents}), 0)::int`, - inputTokens: sql`coalesce(sum(${costEvents.inputTokens}), 0)::int`, - cachedInputTokens: sql`coalesce(sum(${costEvents.cachedInputTokens}), 0)::int`, - outputTokens: sql`coalesce(sum(${costEvents.outputTokens}), 0)::int`, - apiRunCount: sql`count(distinct case when ${costEvents.billingType} = ${METERED_BILLING_TYPE} then ${costEvents.heartbeatRunId} end)::int`, - subscriptionRunCount: sql`count(distinct case when ${costEvents.billingType} in (${sql.join(SUBSCRIPTION_BILLING_TYPES.map((value) => sql`${value}`), sql`, `)}) then ${costEvents.heartbeatRunId} end)::int`, - subscriptionCachedInputTokens: sql`coalesce(sum(case when ${costEvents.billingType} in (${sql.join(SUBSCRIPTION_BILLING_TYPES.map((value) => sql`${value}`), sql`, `)}) then ${costEvents.cachedInputTokens} else 0 end), 0)::int`, - subscriptionInputTokens: sql`coalesce(sum(case when ${costEvents.billingType} in (${sql.join(SUBSCRIPTION_BILLING_TYPES.map((value) => sql`${value}`), sql`, `)}) then ${costEvents.inputTokens} else 0 end), 0)::int`, - subscriptionOutputTokens: sql`coalesce(sum(case when ${costEvents.billingType} in (${sql.join(SUBSCRIPTION_BILLING_TYPES.map((value) => sql`${value}`), sql`, `)}) then ${costEvents.outputTokens} else 0 end), 0)::int` - }).from(costEvents).leftJoin(agents, eq(costEvents.agentId, agents.id)).where(and(...conditions)).groupBy(costEvents.agentId, agents.name, agents.status).orderBy(desc(sql`coalesce(sum(${costEvents.costCents}), 0)::int`)); - }, - byProvider: async (companyId, range2) => { - const conditions = [eq(costEvents.companyId, companyId)]; - if (range2?.from) conditions.push(gte(costEvents.occurredAt, range2.from)); - if (range2?.to) conditions.push(lte(costEvents.occurredAt, range2.to)); - return db.select({ - provider: costEvents.provider, - biller: costEvents.biller, - billingType: costEvents.billingType, - model: costEvents.model, - costCents: sql`coalesce(sum(${costEvents.costCents}), 0)::int`, - inputTokens: sql`coalesce(sum(${costEvents.inputTokens}), 0)::int`, - cachedInputTokens: sql`coalesce(sum(${costEvents.cachedInputTokens}), 0)::int`, - outputTokens: sql`coalesce(sum(${costEvents.outputTokens}), 0)::int`, - apiRunCount: sql`count(distinct case when ${costEvents.billingType} = ${METERED_BILLING_TYPE} then ${costEvents.heartbeatRunId} end)::int`, - subscriptionRunCount: sql`count(distinct case when ${costEvents.billingType} in (${sql.join(SUBSCRIPTION_BILLING_TYPES.map((value) => sql`${value}`), sql`, `)}) then ${costEvents.heartbeatRunId} end)::int`, - subscriptionCachedInputTokens: sql`coalesce(sum(case when ${costEvents.billingType} in (${sql.join(SUBSCRIPTION_BILLING_TYPES.map((value) => sql`${value}`), sql`, `)}) then ${costEvents.cachedInputTokens} else 0 end), 0)::int`, - subscriptionInputTokens: sql`coalesce(sum(case when ${costEvents.billingType} in (${sql.join(SUBSCRIPTION_BILLING_TYPES.map((value) => sql`${value}`), sql`, `)}) then ${costEvents.inputTokens} else 0 end), 0)::int`, - subscriptionOutputTokens: sql`coalesce(sum(case when ${costEvents.billingType} in (${sql.join(SUBSCRIPTION_BILLING_TYPES.map((value) => sql`${value}`), sql`, `)}) then ${costEvents.outputTokens} else 0 end), 0)::int` - }).from(costEvents).where(and(...conditions)).groupBy(costEvents.provider, costEvents.biller, costEvents.billingType, costEvents.model).orderBy(desc(sql`coalesce(sum(${costEvents.costCents}), 0)::int`)); - }, - byBiller: async (companyId, range2) => { - const conditions = [eq(costEvents.companyId, companyId)]; - if (range2?.from) conditions.push(gte(costEvents.occurredAt, range2.from)); - if (range2?.to) conditions.push(lte(costEvents.occurredAt, range2.to)); - return db.select({ - biller: costEvents.biller, - costCents: sql`coalesce(sum(${costEvents.costCents}), 0)::int`, - inputTokens: sql`coalesce(sum(${costEvents.inputTokens}), 0)::int`, - cachedInputTokens: sql`coalesce(sum(${costEvents.cachedInputTokens}), 0)::int`, - outputTokens: sql`coalesce(sum(${costEvents.outputTokens}), 0)::int`, - apiRunCount: sql`count(distinct case when ${costEvents.billingType} = ${METERED_BILLING_TYPE} then ${costEvents.heartbeatRunId} end)::int`, - subscriptionRunCount: sql`count(distinct case when ${costEvents.billingType} in (${sql.join(SUBSCRIPTION_BILLING_TYPES.map((value) => sql`${value}`), sql`, `)}) then ${costEvents.heartbeatRunId} end)::int`, - subscriptionCachedInputTokens: sql`coalesce(sum(case when ${costEvents.billingType} in (${sql.join(SUBSCRIPTION_BILLING_TYPES.map((value) => sql`${value}`), sql`, `)}) then ${costEvents.cachedInputTokens} else 0 end), 0)::int`, - subscriptionInputTokens: sql`coalesce(sum(case when ${costEvents.billingType} in (${sql.join(SUBSCRIPTION_BILLING_TYPES.map((value) => sql`${value}`), sql`, `)}) then ${costEvents.inputTokens} else 0 end), 0)::int`, - subscriptionOutputTokens: sql`coalesce(sum(case when ${costEvents.billingType} in (${sql.join(SUBSCRIPTION_BILLING_TYPES.map((value) => sql`${value}`), sql`, `)}) then ${costEvents.outputTokens} else 0 end), 0)::int`, - providerCount: sql`count(distinct ${costEvents.provider})::int`, - modelCount: sql`count(distinct ${costEvents.model})::int` - }).from(costEvents).where(and(...conditions)).groupBy(costEvents.biller).orderBy(desc(sql`coalesce(sum(${costEvents.costCents}), 0)::int`)); - }, - /** - * aggregates cost_events by provider for each of three rolling windows: - * last 5 hours, last 24 hours, last 7 days. - * purely internal consumption data, no external rate-limit sources. - */ - windowSpend: async (companyId) => { - const windows = [ - { label: "5h", hours: 5 }, - { label: "24h", hours: 24 }, - { label: "7d", hours: 168 } - ]; - const results = await Promise.all( - windows.map(async ({ label, hours }) => { - const since = new Date(Date.now() - hours * 60 * 60 * 1e3); - const rows = await db.select({ - provider: costEvents.provider, - biller: sql`case when count(distinct ${costEvents.biller}) = 1 then min(${costEvents.biller}) else 'mixed' end`, - costCents: sql`coalesce(sum(${costEvents.costCents}), 0)::int`, - inputTokens: sql`coalesce(sum(${costEvents.inputTokens}), 0)::int`, - cachedInputTokens: sql`coalesce(sum(${costEvents.cachedInputTokens}), 0)::int`, - outputTokens: sql`coalesce(sum(${costEvents.outputTokens}), 0)::int` - }).from(costEvents).where( - and( - eq(costEvents.companyId, companyId), - gte(costEvents.occurredAt, since) - ) - ).groupBy(costEvents.provider).orderBy(desc(sql`coalesce(sum(${costEvents.costCents}), 0)::int`)); - return rows.map((row) => ({ - provider: row.provider, - biller: row.biller, - window: label, - windowHours: hours, - costCents: row.costCents, - inputTokens: row.inputTokens, - cachedInputTokens: row.cachedInputTokens, - outputTokens: row.outputTokens - })); - }) - ); - return results.flat(); - }, - byAgentModel: async (companyId, range2) => { - const conditions = [eq(costEvents.companyId, companyId)]; - if (range2?.from) conditions.push(gte(costEvents.occurredAt, range2.from)); - if (range2?.to) conditions.push(lte(costEvents.occurredAt, range2.to)); - return db.select({ - agentId: costEvents.agentId, - agentName: agents.name, - provider: costEvents.provider, - biller: costEvents.biller, - billingType: costEvents.billingType, - model: costEvents.model, - costCents: sql`coalesce(sum(${costEvents.costCents}), 0)::int`, - inputTokens: sql`coalesce(sum(${costEvents.inputTokens}), 0)::int`, - cachedInputTokens: sql`coalesce(sum(${costEvents.cachedInputTokens}), 0)::int`, - outputTokens: sql`coalesce(sum(${costEvents.outputTokens}), 0)::int` - }).from(costEvents).leftJoin(agents, eq(costEvents.agentId, agents.id)).where(and(...conditions)).groupBy( - costEvents.agentId, - agents.name, - costEvents.provider, - costEvents.biller, - costEvents.billingType, - costEvents.model - ).orderBy(costEvents.provider, costEvents.biller, costEvents.billingType, costEvents.model); - }, - byProject: async (companyId, range2) => { - const issueIdAsText = sql`${issues.id}::text`; - const runProjectLinks = db.selectDistinctOn([activityLog.runId, issues.projectId], { - runId: activityLog.runId, - projectId: issues.projectId - }).from(activityLog).innerJoin( - issues, - and( - eq(activityLog.entityType, "issue"), - eq(activityLog.entityId, issueIdAsText) - ) - ).where( - and( - eq(activityLog.companyId, companyId), - eq(issues.companyId, companyId), - isNotNull(activityLog.runId), - isNotNull(issues.projectId) - ) - ).orderBy(activityLog.runId, issues.projectId, desc(activityLog.createdAt)).as("run_project_links"); - const effectiveProjectId = sql`coalesce(${costEvents.projectId}, ${runProjectLinks.projectId})`; - const conditions = [eq(costEvents.companyId, companyId)]; - if (range2?.from) conditions.push(gte(costEvents.occurredAt, range2.from)); - if (range2?.to) conditions.push(lte(costEvents.occurredAt, range2.to)); - const costCentsExpr = sql`coalesce(sum(${costEvents.costCents}), 0)::int`; - return db.select({ - projectId: effectiveProjectId, - projectName: projects.name, - costCents: costCentsExpr, - inputTokens: sql`coalesce(sum(${costEvents.inputTokens}), 0)::int`, - cachedInputTokens: sql`coalesce(sum(${costEvents.cachedInputTokens}), 0)::int`, - outputTokens: sql`coalesce(sum(${costEvents.outputTokens}), 0)::int` - }).from(costEvents).leftJoin(runProjectLinks, eq(costEvents.heartbeatRunId, runProjectLinks.runId)).innerJoin(projects, sql`${projects.id} = ${effectiveProjectId}`).where(and(...conditions, sql`${effectiveProjectId} is not null`)).groupBy(effectiveProjectId, projects.name).orderBy(desc(costCentsExpr)); - } - }; -} - -// server/src/services/heartbeat-run-summary.ts -function truncateSummaryText(value, maxLength = 500) { - if (typeof value !== "string") return null; - return value.length > maxLength ? value.slice(0, maxLength) : value; -} -function readNumericField(record2, key) { - return key in record2 ? record2[key] ?? null : void 0; -} -function readCommentText(value) { - if (typeof value !== "string") return null; - const trimmed = value.trim(); - return trimmed.length > 0 ? trimmed : null; -} -function mergeHeartbeatRunResultJson(resultJson, summary) { - const normalizedSummary = readCommentText(summary); - const baseResult = resultJson && typeof resultJson === "object" && !Array.isArray(resultJson) ? resultJson : null; - if (!baseResult) { - return normalizedSummary ? { summary: normalizedSummary } : null; - } - if (!normalizedSummary) { - return baseResult; - } - if (readCommentText(baseResult.summary)) { - return baseResult; - } - return { - ...baseResult, - summary: normalizedSummary - }; -} -function summarizeHeartbeatRunResultJson(resultJson) { - if (!resultJson || typeof resultJson !== "object" || Array.isArray(resultJson)) { - return null; - } - const summary = {}; - const textFields = ["summary", "result", "message", "error"]; - for (const key of textFields) { - const value = truncateSummaryText(resultJson[key]); - if (value !== null) { - summary[key] = value; - } - } - const numericFieldAliases = ["total_cost_usd", "cost_usd", "costUsd"]; - for (const key of numericFieldAliases) { - const value = readNumericField(resultJson, key); - if (value !== void 0 && value !== null) { - summary[key] = value; - } - } - return Object.keys(summary).length > 0 ? summary : null; -} -function buildHeartbeatRunIssueComment(resultJson) { - if (!resultJson || typeof resultJson !== "object" || Array.isArray(resultJson)) { - return null; - } - return readCommentText(resultJson.summary) ?? readCommentText(resultJson.result) ?? readCommentText(resultJson.message) ?? null; -} - -// server/src/services/workspace-runtime.ts -init_src2(); -import { spawn as spawn4 } from "node:child_process"; -import { existsSync as existsSync3, lstatSync, readdirSync, readFileSync as readFileSync3, realpathSync } from "node:fs"; -import fs30 from "node:fs/promises"; -import net2 from "node:net"; -import { createHash as createHash12, randomUUID as randomUUID4 } from "node:crypto"; -import path37 from "node:path"; -import { setTimeout as delay2 } from "node:timers/promises"; -init_drizzle_orm(); - -// server/src/services/local-service-supervisor.ts -import { execFile as execFile3 } from "node:child_process"; -import { createHash as createHash11 } from "node:crypto"; -import fs28 from "node:fs/promises"; -import path35 from "node:path"; -import { setTimeout as delay } from "node:timers/promises"; -import { promisify as promisify3 } from "node:util"; -var execFileAsync3 = promisify3(execFile3); -function stableStringify2(value) { - if (Array.isArray(value)) { - return `[${value.map((entry) => stableStringify2(entry)).join(",")}]`; - } - if (value && typeof value === "object") { - const rec = value; - return `{${Object.keys(rec).sort().map((key) => `${JSON.stringify(key)}:${stableStringify2(rec[key])}`).join(",")}}`; - } - return JSON.stringify(value); -} -function sanitizeServiceKeySegment(value, fallback) { - const normalized = value.trim().toLowerCase().replace(/[^a-z0-9._-]+/g, "-").replace(/-+/g, "-").replace(/^-+|-+$/g, ""); - return normalized || fallback; -} -function getRuntimeServicesDir() { - return path35.resolve(resolveTaskcoreInstanceRoot(), "runtime-services"); -} -function getRuntimeServiceRegistryPath(serviceKey) { - return path35.resolve(getRuntimeServicesDir(), `${serviceKey}.json`); -} -function normalizeRegistryRecord(raw) { - if (!raw || typeof raw !== "object") return null; - const rec = raw; - if (rec.version !== 1 || typeof rec.serviceKey !== "string" || typeof rec.profileKind !== "string" || typeof rec.serviceName !== "string" || typeof rec.command !== "string" || typeof rec.cwd !== "string" || typeof rec.envFingerprint !== "string" || typeof rec.pid !== "number") { - return null; - } - return { - version: 1, - serviceKey: rec.serviceKey, - profileKind: rec.profileKind, - serviceName: rec.serviceName, - command: rec.command, - cwd: rec.cwd, - envFingerprint: rec.envFingerprint, - port: typeof rec.port === "number" ? rec.port : null, - url: typeof rec.url === "string" ? rec.url : null, - pid: rec.pid, - processGroupId: typeof rec.processGroupId === "number" ? rec.processGroupId : null, - provider: "local_process", - runtimeServiceId: typeof rec.runtimeServiceId === "string" ? rec.runtimeServiceId : null, - reuseKey: typeof rec.reuseKey === "string" ? rec.reuseKey : null, - startedAt: typeof rec.startedAt === "string" ? rec.startedAt : (/* @__PURE__ */ new Date()).toISOString(), - lastSeenAt: typeof rec.lastSeenAt === "string" ? rec.lastSeenAt : (/* @__PURE__ */ new Date()).toISOString(), - metadata: rec.metadata && typeof rec.metadata === "object" && !Array.isArray(rec.metadata) ? rec.metadata : null - }; -} -async function safeReadRegistryRecord(filePath) { - try { - const raw = JSON.parse(await fs28.readFile(filePath, "utf8")); - return normalizeRegistryRecord(raw); - } catch { - return null; - } -} -function createLocalServiceKey(input) { - const digest2 = createHash11("sha256").update( - stableStringify2({ - profileKind: input.profileKind, - serviceName: input.serviceName, - cwd: path35.resolve(input.cwd), - command: input.command, - envFingerprint: input.envFingerprint, - port: input.port, - scope: input.scope ?? null - }) - ).digest("hex").slice(0, 24); - return `${sanitizeServiceKeySegment(input.profileKind, "service")}-${sanitizeServiceKeySegment(input.serviceName, "service")}-${digest2}`; -} -async function writeLocalServiceRegistryRecord(record2) { - await fs28.mkdir(getRuntimeServicesDir(), { recursive: true }); - await fs28.writeFile( - getRuntimeServiceRegistryPath(record2.serviceKey), - `${JSON.stringify(record2, null, 2)} -`, - "utf8" - ); -} -async function removeLocalServiceRegistryRecord(serviceKey) { - await fs28.rm(getRuntimeServiceRegistryPath(serviceKey), { force: true }); -} -async function readLocalServiceRegistryRecord(serviceKey) { - return await safeReadRegistryRecord(getRuntimeServiceRegistryPath(serviceKey)); -} -function isPidAlive(pid) { - if (!Number.isInteger(pid) || pid <= 0) return false; - try { - process.kill(pid, 0); - return true; - } catch { - return false; - } -} -function isProcessGroupAlive(processGroupId) { - if (process.platform === "win32") return false; - if (typeof processGroupId !== "number" || !Number.isInteger(processGroupId) || processGroupId <= 0) return false; - try { - process.kill(-processGroupId, 0); - return true; - } catch { - return false; - } -} -async function isLikelyMatchingCommand(record2) { - if (process.platform === "win32") return true; - try { - const { stdout } = await execFileAsync3("ps", ["-o", "command=", "-p", String(record2.pid)]); - const commandLine = stdout.trim(); - if (!commandLine) return false; - const normalize2 = (value) => value.replace(/["']/g, "").replace(/\s+/g, " ").trim(); - const normalizedCommandLine = normalize2(commandLine); - const normalizedRecordedCommand = normalize2(record2.command); - return normalizedCommandLine.includes(normalizedRecordedCommand) || normalizedCommandLine.includes(record2.serviceName); - } catch { - return true; - } -} -async function findAdoptableLocalService(input) { - const record2 = await readLocalServiceRegistryRecord(input.serviceKey); - if (!record2) return null; - if (!isPidAlive(record2.pid)) { - await removeLocalServiceRegistryRecord(input.serviceKey); - return null; - } - if (!await isLikelyMatchingCommand(record2)) { - await removeLocalServiceRegistryRecord(input.serviceKey); - return null; - } - if (input.command && record2.command !== input.command) return null; - if (input.cwd && path35.resolve(record2.cwd) !== path35.resolve(input.cwd)) return null; - if (input.envFingerprint && record2.envFingerprint !== input.envFingerprint) return null; - if (input.port !== void 0 && input.port !== null && record2.port !== input.port) return null; - return record2; -} -async function touchLocalServiceRegistryRecord(serviceKey, patch) { - const existing = await readLocalServiceRegistryRecord(serviceKey); - if (!existing) return null; - const next = { - ...existing, - ...patch, - version: 1, - serviceKey, - lastSeenAt: patch?.lastSeenAt ?? (/* @__PURE__ */ new Date()).toISOString() - }; - await writeLocalServiceRegistryRecord(next); - return next; -} -async function terminateLocalService(record2, opts) { - const signal = opts?.signal ?? "SIGTERM"; - const targetProcessGroup = process.platform !== "win32" && record2.processGroupId && record2.processGroupId > 0; - try { - if (targetProcessGroup) { - process.kill(-record2.processGroupId, signal); - } else { - process.kill(record2.pid, signal); - } - } catch { - return; - } - const deadline = Date.now() + (opts?.forceAfterMs ?? 2e3); - while (Date.now() < deadline) { - const targetAlive = targetProcessGroup ? isProcessGroupAlive(record2.processGroupId) : isPidAlive(record2.pid); - if (!targetAlive) { - return; - } - await delay(100); - } - const stillAlive = targetProcessGroup ? isProcessGroupAlive(record2.processGroupId) : isPidAlive(record2.pid); - if (!stillAlive) return; - try { - if (targetProcessGroup) { - process.kill(-record2.processGroupId, "SIGKILL"); - } else { - process.kill(record2.pid, "SIGKILL"); - } - } catch { - } -} -async function readLocalServicePortOwner(port) { - if (!Number.isInteger(port) || port <= 0 || process.platform === "win32") return null; - try { - const { stdout } = await execFileAsync3("lsof", ["-nPiTCP", `:${port}`, "-sTCP:LISTEN", "-t"]); - const firstPid = stdout.split("\n").map((line3) => Number.parseInt(line3.trim(), 10)).find((value) => Number.isInteger(value) && value > 0); - return firstPid ?? null; - } catch { - return null; - } -} - -// server/src/services/execution-workspaces.ts -init_drizzle_orm(); -init_src2(); -import { execFile as execFile4 } from "node:child_process"; -import fs29 from "node:fs/promises"; -import path36 from "node:path"; -import { promisify as promisify4 } from "node:util"; -var execFileAsync4 = promisify4(execFile4); -var TERMINAL_ISSUE_STATUSES = /* @__PURE__ */ new Set(["done", "cancelled"]); -function isRecord4(value) { - return typeof value === "object" && value !== null && !Array.isArray(value); -} -function readNullableString(value) { - if (typeof value !== "string") return null; - const trimmed = value.trim(); - return trimmed.length > 0 ? trimmed : null; -} -function cloneRecord3(value) { - if (!isRecord4(value)) return null; - return { ...value }; -} -async function pathExists4(value) { - if (!value) return false; - try { - await fs29.access(value); - return true; - } catch { - return false; - } -} -async function runGit(args, cwd) { - return await execFileAsync4("git", ["-C", cwd, ...args], { cwd }); -} -async function inspectGitCloseReadiness(workspace) { - const warnings = []; - const workspacePath = readNullableString(workspace.providerRef) ?? readNullableString(workspace.cwd); - const createdByRuntime = workspace.metadata?.createdByRuntime === true; - const expectsGitInspection = workspace.providerType === "git_worktree" || Boolean(workspace.repoUrl || workspace.baseRef || workspace.branchName || workspacePath); - if (!expectsGitInspection) { - return { git: null, warnings }; - } - if (!workspacePath) { - warnings.push("Workspace has no local path, so Taskcore cannot inspect git status before close."); - return { git: null, warnings }; - } - if (!await pathExists4(workspacePath)) { - warnings.push(`Workspace path "${workspacePath}" does not exist, so Taskcore cannot inspect git status before close.`); - return { - git: { - repoRoot: null, - workspacePath, - branchName: workspace.branchName, - baseRef: workspace.baseRef, - hasDirtyTrackedFiles: false, - hasUntrackedFiles: false, - dirtyEntryCount: 0, - untrackedEntryCount: 0, - aheadCount: null, - behindCount: null, - isMergedIntoBase: null, - createdByRuntime - }, - warnings - }; - } - let repoRoot = null; - try { - repoRoot = (await runGit(["rev-parse", "--show-toplevel"], workspacePath)).stdout.trim() || null; - } catch (error50) { - warnings.push( - `Could not inspect git status for "${workspacePath}": ${error50 instanceof Error ? error50.message : String(error50)}` - ); - } - let branchName = workspace.branchName; - if (repoRoot && !branchName) { - try { - branchName = (await runGit(["rev-parse", "--abbrev-ref", "HEAD"], workspacePath)).stdout.trim() || null; - } catch { - branchName = workspace.branchName; - } - } - let dirtyEntryCount = 0; - let untrackedEntryCount = 0; - if (repoRoot) { - try { - const statusOutput = (await runGit(["status", "--porcelain=v1", "--untracked-files=all"], workspacePath)).stdout; - for (const line3 of statusOutput.split(/\r?\n/)) { - if (!line3) continue; - if (line3.startsWith("??")) { - untrackedEntryCount += 1; - continue; - } - dirtyEntryCount += 1; - } - } catch (error50) { - warnings.push( - `Could not read git working tree status for "${workspacePath}": ${error50 instanceof Error ? error50.message : String(error50)}` - ); - } - } - let aheadCount = null; - let behindCount = null; - let isMergedIntoBase = null; - const baseRef = workspace.baseRef; - if (repoRoot && baseRef) { - try { - const counts = (await runGit(["rev-list", "--left-right", "--count", `${baseRef}...HEAD`], workspacePath)).stdout.trim(); - const [behindRaw, aheadRaw] = counts.split(/\s+/); - behindCount = behindRaw ? Number.parseInt(behindRaw, 10) : 0; - aheadCount = aheadRaw ? Number.parseInt(aheadRaw, 10) : 0; - } catch (error50) { - warnings.push( - `Could not compare this workspace against ${baseRef}: ${error50 instanceof Error ? error50.message : String(error50)}` - ); - } - try { - await runGit(["merge-base", "--is-ancestor", "HEAD", baseRef], workspacePath); - isMergedIntoBase = true; - } catch (error50) { - const code = typeof error50 === "object" && error50 && "code" in error50 ? error50.code : null; - if (code === 1) isMergedIntoBase = false; - else { - warnings.push( - `Could not determine whether this workspace is merged into ${baseRef}: ${error50 instanceof Error ? error50.message : String(error50)}` - ); - } - } - } - return { - git: { - repoRoot, - workspacePath, - branchName, - baseRef, - hasDirtyTrackedFiles: dirtyEntryCount > 0, - hasUntrackedFiles: untrackedEntryCount > 0, - dirtyEntryCount, - untrackedEntryCount, - aheadCount, - behindCount, - isMergedIntoBase, - createdByRuntime - }, - warnings - }; -} -function readExecutionWorkspaceConfig(metadata) { - const raw = isRecord4(metadata?.config) ? metadata.config : null; - if (!raw) return null; - const config3 = { - provisionCommand: readNullableString(raw.provisionCommand), - teardownCommand: readNullableString(raw.teardownCommand), - cleanupCommand: readNullableString(raw.cleanupCommand), - workspaceRuntime: cloneRecord3(raw.workspaceRuntime), - desiredState: raw.desiredState === "running" || raw.desiredState === "stopped" ? raw.desiredState : null, - serviceStates: isRecord4(raw.serviceStates) ? Object.fromEntries( - Object.entries(raw.serviceStates).filter(([, state2]) => state2 === "running" || state2 === "stopped") - ) : null - }; - const hasConfig = Object.values(config3).some((value) => { - if (value === null) return false; - if (typeof value === "object") return Object.keys(value).length > 0; - return true; - }); - return hasConfig ? config3 : null; -} -function mergeExecutionWorkspaceConfig(metadata, patch) { - const nextMetadata = isRecord4(metadata) ? { ...metadata } : {}; - const current = readExecutionWorkspaceConfig(metadata) ?? { - provisionCommand: null, - teardownCommand: null, - cleanupCommand: null, - workspaceRuntime: null, - desiredState: null, - serviceStates: null - }; - if (patch === null) { - delete nextMetadata.config; - return Object.keys(nextMetadata).length > 0 ? nextMetadata : null; - } - const nextConfig = { - provisionCommand: patch.provisionCommand !== void 0 ? readNullableString(patch.provisionCommand) : current.provisionCommand, - teardownCommand: patch.teardownCommand !== void 0 ? readNullableString(patch.teardownCommand) : current.teardownCommand, - cleanupCommand: patch.cleanupCommand !== void 0 ? readNullableString(patch.cleanupCommand) : current.cleanupCommand, - workspaceRuntime: patch.workspaceRuntime !== void 0 ? cloneRecord3(patch.workspaceRuntime) : current.workspaceRuntime, - desiredState: patch.desiredState !== void 0 ? patch.desiredState === "running" || patch.desiredState === "stopped" ? patch.desiredState : null : current.desiredState, - serviceStates: patch.serviceStates !== void 0 && isRecord4(patch.serviceStates) ? Object.fromEntries( - Object.entries(patch.serviceStates).filter(([, state2]) => state2 === "running" || state2 === "stopped") - ) : patch.serviceStates !== void 0 ? null : current.serviceStates - }; - const hasConfig = Object.values(nextConfig).some((value) => { - if (value === null) return false; - if (typeof value === "object") return Object.keys(value).length > 0; - return true; - }); - if (hasConfig) { - nextMetadata.config = { - provisionCommand: nextConfig.provisionCommand, - teardownCommand: nextConfig.teardownCommand, - cleanupCommand: nextConfig.cleanupCommand, - workspaceRuntime: nextConfig.workspaceRuntime, - desiredState: nextConfig.desiredState, - serviceStates: nextConfig.serviceStates ?? null - }; - } else { - delete nextMetadata.config; - } - return Object.keys(nextMetadata).length > 0 ? nextMetadata : null; -} -function toRuntimeService2(row) { - return { - id: row.id, - companyId: row.companyId, - projectId: row.projectId ?? null, - projectWorkspaceId: row.projectWorkspaceId ?? null, - executionWorkspaceId: row.executionWorkspaceId ?? null, - issueId: row.issueId ?? null, - scopeType: row.scopeType, - scopeId: row.scopeId ?? null, - serviceName: row.serviceName, - status: row.status, - lifecycle: row.lifecycle, - reuseKey: row.reuseKey ?? null, - command: row.command ?? null, - cwd: row.cwd ?? null, - port: row.port ?? null, - url: row.url ?? null, - provider: row.provider, - providerRef: row.providerRef ?? null, - ownerAgentId: row.ownerAgentId ?? null, - startedByRunId: row.startedByRunId ?? null, - lastUsedAt: row.lastUsedAt, - startedAt: row.startedAt, - stoppedAt: row.stoppedAt ?? null, - stopPolicy: row.stopPolicy ?? null, - healthStatus: row.healthStatus, - createdAt: row.createdAt, - updatedAt: row.updatedAt - }; -} -function toExecutionWorkspace(row, runtimeServices = []) { - return { - id: row.id, - companyId: row.companyId, - projectId: row.projectId, - projectWorkspaceId: row.projectWorkspaceId ?? null, - sourceIssueId: row.sourceIssueId ?? null, - mode: row.mode, - strategyType: row.strategyType, - name: row.name, - status: row.status, - cwd: row.cwd ?? null, - repoUrl: row.repoUrl ?? null, - baseRef: row.baseRef ?? null, - branchName: row.branchName ?? null, - providerType: row.providerType, - providerRef: row.providerRef ?? null, - derivedFromExecutionWorkspaceId: row.derivedFromExecutionWorkspaceId ?? null, - lastUsedAt: row.lastUsedAt, - openedAt: row.openedAt, - closedAt: row.closedAt ?? null, - cleanupEligibleAt: row.cleanupEligibleAt ?? null, - cleanupReason: row.cleanupReason ?? null, - config: readExecutionWorkspaceConfig(row.metadata ?? null), - metadata: row.metadata ?? null, - runtimeServices, - createdAt: row.createdAt, - updatedAt: row.updatedAt - }; -} -function usesInheritedProjectRuntimeServices(row) { - if (row.mode !== "shared_workspace" || !row.projectWorkspaceId) return false; - return !readExecutionWorkspaceConfig(row.metadata ?? null)?.workspaceRuntime; -} -async function loadEffectiveRuntimeServicesByExecutionWorkspace(db, companyId, rows) { - const executionRuntimeServices = await listCurrentRuntimeServicesForExecutionWorkspaces( - db, - companyId, - rows.map((row) => row.id) - ); - const projectWorkspaceIds = rows.filter((row) => usesInheritedProjectRuntimeServices(row)).map((row) => row.projectWorkspaceId).filter((value) => Boolean(value)); - const projectRuntimeServices = await listCurrentRuntimeServicesForProjectWorkspaces( - db, - companyId, - [...new Set(projectWorkspaceIds)] - ); - return new Map( - rows.map((row) => [ - row.id, - usesInheritedProjectRuntimeServices(row) ? projectRuntimeServices.get(row.projectWorkspaceId) ?? [] : executionRuntimeServices.get(row.id) ?? [] - ]) - ); -} -function executionWorkspaceService(db) { - return { - list: async (companyId, filters) => { - const conditions = [eq(executionWorkspaces.companyId, companyId)]; - if (filters?.projectId) conditions.push(eq(executionWorkspaces.projectId, filters.projectId)); - if (filters?.projectWorkspaceId) { - conditions.push(eq(executionWorkspaces.projectWorkspaceId, filters.projectWorkspaceId)); - } - if (filters?.issueId) conditions.push(eq(executionWorkspaces.sourceIssueId, filters.issueId)); - if (filters?.status) { - const statuses = filters.status.split(",").map((value) => value.trim()).filter(Boolean); - if (statuses.length === 1) conditions.push(eq(executionWorkspaces.status, statuses[0])); - else if (statuses.length > 1) conditions.push(inArray(executionWorkspaces.status, statuses)); - } - if (filters?.reuseEligible) { - conditions.push(inArray(executionWorkspaces.status, ["active", "idle", "in_review"])); - } - const rows = await db.select().from(executionWorkspaces).where(and(...conditions)).orderBy(desc(executionWorkspaces.lastUsedAt), desc(executionWorkspaces.createdAt)); - const runtimeServicesByWorkspaceId = await loadEffectiveRuntimeServicesByExecutionWorkspace(db, companyId, rows); - return rows.map( - (row) => toExecutionWorkspace( - row, - (runtimeServicesByWorkspaceId.get(row.id) ?? []).map(toRuntimeService2) - ) - ); - }, - getById: async (id) => { - const row = await db.select().from(executionWorkspaces).where(eq(executionWorkspaces.id, id)).then((rows) => rows[0] ?? null); - if (!row) return null; - const runtimeServicesByWorkspaceId = await loadEffectiveRuntimeServicesByExecutionWorkspace(db, row.companyId, [row]); - return toExecutionWorkspace( - row, - (runtimeServicesByWorkspaceId.get(row.id) ?? []).map(toRuntimeService2) - ); - }, - getCloseReadiness: async (id) => { - const workspace = await db.select().from(executionWorkspaces).where(eq(executionWorkspaces.id, id)).then((rows) => rows[0] ?? null); - if (!workspace) return null; - const runtimeServicesByWorkspaceId = await loadEffectiveRuntimeServicesByExecutionWorkspace(db, workspace.companyId, [workspace]); - const runtimeServices = (runtimeServicesByWorkspaceId.get(workspace.id) ?? []).map(toRuntimeService2); - const linkedIssues = await db.select({ - id: issues.id, - identifier: issues.identifier, - title: issues.title, - status: issues.status - }).from(issues).where(and(eq(issues.companyId, workspace.companyId), eq(issues.executionWorkspaceId, workspace.id))); - const projectWorkspace = workspace.projectWorkspaceId ? await db.select({ - id: projectWorkspaces.id, - cwd: projectWorkspaces.cwd, - cleanupCommand: projectWorkspaces.cleanupCommand, - isPrimary: projectWorkspaces.isPrimary - }).from(projectWorkspaces).where( - and( - eq(projectWorkspaces.companyId, workspace.companyId), - eq(projectWorkspaces.id, workspace.projectWorkspaceId) - ) - ).then((rows) => rows[0] ?? null) : null; - const primaryProjectWorkspace = workspace.projectId ? await db.select({ - id: projectWorkspaces.id - }).from(projectWorkspaces).where( - and( - eq(projectWorkspaces.companyId, workspace.companyId), - eq(projectWorkspaces.projectId, workspace.projectId), - eq(projectWorkspaces.isPrimary, true) - ) - ).then((rows) => rows[0] ?? null) : null; - const projectPolicy = workspace.projectId ? await db.select({ - executionWorkspacePolicy: projects.executionWorkspacePolicy - }).from(projects).where(and(eq(projects.id, workspace.projectId), eq(projects.companyId, workspace.companyId))).then((rows) => parseProjectExecutionWorkspacePolicy(rows[0]?.executionWorkspacePolicy)) : null; - const executionWorkspace = toExecutionWorkspace(workspace, runtimeServices); - const config3 = readExecutionWorkspaceConfig(workspace.metadata ?? null); - const { git, warnings: gitWarnings } = await inspectGitCloseReadiness(executionWorkspace); - const warnings = [...gitWarnings]; - const blockingReasons = []; - const isSharedWorkspace = executionWorkspace.mode === "shared_workspace"; - const workspacePath = readNullableString(executionWorkspace.providerRef) ?? readNullableString(executionWorkspace.cwd); - const resolvedWorkspacePath = workspacePath ? path36.resolve(workspacePath) : null; - const resolvedPrimaryWorkspacePath = projectWorkspace?.cwd ? path36.resolve(projectWorkspace.cwd) : null; - const isProjectPrimaryWorkspace = workspace.projectWorkspaceId != null && workspace.projectWorkspaceId === primaryProjectWorkspace?.id && resolvedWorkspacePath != null && resolvedPrimaryWorkspacePath != null && resolvedWorkspacePath === resolvedPrimaryWorkspacePath; - const linkedIssueSummaries = linkedIssues.map((issue2) => ({ - ...issue2, - isTerminal: TERMINAL_ISSUE_STATUSES.has(issue2.status) - })); - const blockingIssues = linkedIssueSummaries.filter((issue2) => !issue2.isTerminal); - if (blockingIssues.length > 0) { - const linkedIssueMessage = blockingIssues.length === 1 ? "This workspace is still linked to an open issue." : `This workspace is still linked to ${blockingIssues.length} open issues.`; - if (isSharedWorkspace) { - warnings.push(`${linkedIssueMessage} Archiving it will detach this shared workspace session from those issues, but keep the underlying project workspace available.`); - } else { - blockingReasons.push(linkedIssueMessage); - } - } - if (isSharedWorkspace) { - warnings.push("This shared workspace session points at project workspace infrastructure. Archiving it only removes the session record."); - } - if (runtimeServices.some((service) => service.status !== "stopped")) { - warnings.push( - runtimeServices.length === 1 ? "Closing this workspace will stop 1 attached runtime service." : `Closing this workspace will stop ${runtimeServices.length} attached runtime services.` - ); - } - if (git?.hasDirtyTrackedFiles) { - warnings.push( - git.dirtyEntryCount === 1 ? "The workspace has 1 modified tracked file." : `The workspace has ${git.dirtyEntryCount} modified tracked files.` - ); - } - if (git?.hasUntrackedFiles) { - warnings.push( - git.untrackedEntryCount === 1 ? "The workspace has 1 untracked file." : `The workspace has ${git.untrackedEntryCount} untracked files.` - ); - } - if (git?.aheadCount && git.aheadCount > 0 && git.isMergedIntoBase === false) { - warnings.push( - git.aheadCount === 1 ? `This workspace is 1 commit ahead of ${git.baseRef ?? "the base ref"} and is not merged.` : `This workspace is ${git.aheadCount} commits ahead of ${git.baseRef ?? "the base ref"} and is not merged.` - ); - } - if (git?.behindCount && git.behindCount > 0) { - warnings.push( - git.behindCount === 1 ? `This workspace is 1 commit behind ${git.baseRef ?? "the base ref"}.` : `This workspace is ${git.behindCount} commits behind ${git.baseRef ?? "the base ref"}.` - ); - } - const plannedActions = [ - { - kind: "archive_record", - label: "Archive workspace record", - description: "Keep the execution workspace history and issue linkage, but remove it from active workspace lists.", - command: null - } - ]; - if (runtimeServices.some((service) => service.status !== "stopped")) { - plannedActions.push({ - kind: "stop_runtime_services", - label: runtimeServices.length === 1 ? "Stop attached runtime service" : "Stop attached runtime services", - description: runtimeServices.length === 1 ? `${runtimeServices[0]?.serviceName ?? "A runtime service"} will be stopped before cleanup.` : `${runtimeServices.length} runtime services will be stopped before cleanup.`, - command: null - }); - } - const configuredCleanupCommands = [ - { - kind: "cleanup_command", - label: "Run workspace cleanup command", - description: "Workspace-specific cleanup runs before teardown.", - command: config3?.cleanupCommand ?? null - }, - { - kind: "cleanup_command", - label: "Run project workspace cleanup command", - description: "Project workspace cleanup runs before execution workspace teardown.", - command: projectWorkspace?.cleanupCommand ?? null - } - ]; - for (const action of configuredCleanupCommands) { - if (!action.command) continue; - plannedActions.push(action); - } - const teardownCommand = config3?.teardownCommand ?? projectPolicy?.workspaceStrategy?.teardownCommand ?? null; - if (teardownCommand) { - plannedActions.push({ - kind: "teardown_command", - label: "Run teardown command", - description: "Teardown runs after cleanup commands during workspace close.", - command: teardownCommand - }); - } - if (executionWorkspace.providerType === "git_worktree" && workspacePath) { - plannedActions.push({ - kind: "git_worktree_remove", - label: "Remove git worktree", - description: `Taskcore will run git worktree cleanup for ${workspacePath}.`, - command: `git worktree remove --force ${workspacePath}` - }); - } - if (git?.createdByRuntime && executionWorkspace.branchName) { - plannedActions.push({ - kind: "git_branch_delete", - label: "Delete runtime-created branch", - description: "Taskcore will try to delete the runtime-created branch after removing the worktree.", - command: `git branch -d ${executionWorkspace.branchName}` - }); - } - if (executionWorkspace.providerType === "local_fs" && git?.createdByRuntime && workspacePath) { - const resolvedWorkspacePath2 = path36.resolve(workspacePath); - const resolvedProjectWorkspacePath = projectWorkspace?.cwd ? path36.resolve(projectWorkspace.cwd) : null; - const containsProjectWorkspace = resolvedProjectWorkspacePath ? resolvedWorkspacePath2 === resolvedProjectWorkspacePath || resolvedProjectWorkspacePath.startsWith(`${resolvedWorkspacePath2}${path36.sep}`) : false; - if (containsProjectWorkspace) { - warnings.push(`Taskcore will archive this workspace but keep "${workspacePath}" because it contains the project workspace.`); - } else { - plannedActions.push({ - kind: "remove_local_directory", - label: "Remove runtime-created directory", - description: `Taskcore will remove the runtime-created directory at ${workspacePath}.`, - command: `rm -rf ${workspacePath}` - }); - } - } - const state2 = blockingReasons.length > 0 ? "blocked" : warnings.length > 0 ? "ready_with_warnings" : "ready"; - return { - workspaceId: workspace.id, - state: state2, - blockingReasons, - warnings, - linkedIssues: linkedIssueSummaries, - plannedActions, - isDestructiveCloseAllowed: blockingReasons.length === 0, - isSharedWorkspace, - isProjectPrimaryWorkspace, - git, - runtimeServices - }; - }, - create: async (data2) => { - const row = await db.insert(executionWorkspaces).values(data2).returning().then((rows) => rows[0] ?? null); - return row ? toExecutionWorkspace(row) : null; - }, - update: async (id, patch) => { - const row = await db.update(executionWorkspaces).set({ ...patch, updatedAt: /* @__PURE__ */ new Date() }).where(eq(executionWorkspaces.id, id)).returning().then((rows) => rows[0] ?? null); - return row ? toExecutionWorkspace(row) : null; - } - }; -} - -// server/src/services/workspace-runtime.ts -function resolveShell() { - const fallback = process.platform === "win32" ? "sh" : "/bin/sh"; - const shell = process.env.SHELL?.trim(); - if (!shell) return fallback; - if (path37.isAbsolute(shell) && !existsSync3(shell)) return fallback; - return shell; -} -var runtimeServicesById = /* @__PURE__ */ new Map(); -var runtimeServicesByReuseKey = /* @__PURE__ */ new Map(); -var runtimeServiceLeasesByRun = /* @__PURE__ */ new Map(); -var DEFAULT_EXECUTE_PROCESS_OUTPUT_BYTES = 256 * 1024; -function stableStringify3(value) { - if (Array.isArray(value)) { - return `[${value.map((entry) => stableStringify3(entry)).join(",")}]`; - } - if (value && typeof value === "object") { - const rec = value; - return `{${Object.keys(rec).sort().map((key) => `${JSON.stringify(key)}:${stableStringify3(rec[key])}`).join(",")}}`; - } - return JSON.stringify(value); -} -function readJsonFile(filePath) { - return JSON.parse(readFileSync3(filePath, "utf8")); -} -function findWorkspaceRoot(startCwd) { - let current = path37.resolve(startCwd); - while (true) { - if (existsSync3(path37.join(current, "pnpm-workspace.yaml"))) { - return current; - } - const parent = path37.dirname(current); - if (parent === current) return null; - current = parent; - } -} -function isLinkedGitWorktreeCheckout(rootDir) { - const gitMetadataPath = path37.join(rootDir, ".git"); - if (!existsSync3(gitMetadataPath)) return false; - const stat5 = lstatSync(gitMetadataPath); - if (!stat5.isFile()) return false; - return readFileSync3(gitMetadataPath, "utf8").trimStart().startsWith("gitdir:"); -} -function discoverWorkspacePackagePaths(rootDir) { - const packagePaths = /* @__PURE__ */ new Map(); - const ignoredDirNames = /* @__PURE__ */ new Set([".git", ".taskcore", "dist", "node_modules"]); - function visit(dirPath) { - if (!existsSync3(dirPath)) return; - const packageJsonPath = path37.join(dirPath, "package.json"); - if (existsSync3(packageJsonPath)) { - const packageJson = readJsonFile(packageJsonPath); - if (typeof packageJson.name === "string" && packageJson.name.length > 0) { - packagePaths.set(packageJson.name, dirPath); - } - } - for (const entry of readdirSync(dirPath, { withFileTypes: true })) { - if (!entry.isDirectory()) continue; - if (ignoredDirNames.has(entry.name)) continue; - visit(path37.join(dirPath, entry.name)); - } - } - visit(path37.join(rootDir, "packages")); - visit(path37.join(rootDir, "server")); - visit(path37.join(rootDir, "ui")); - visit(path37.join(rootDir, "cli")); - return packagePaths; -} -function findServerWorkspaceLinkMismatches(rootDir) { - const serverPackageJsonPath = path37.join(rootDir, "server", "package.json"); - if (!existsSync3(serverPackageJsonPath)) return []; - const serverPackageJson = readJsonFile(serverPackageJsonPath); - const dependencies = { - ...serverPackageJson.dependencies, - ...serverPackageJson.devDependencies - }; - const workspacePackagePaths = discoverWorkspacePackagePaths(rootDir); - const mismatches = []; - for (const [packageName, version3] of Object.entries(dependencies)) { - if (typeof version3 !== "string" || !version3.startsWith("workspace:")) continue; - const expectedPath = workspacePackagePaths.get(packageName); - if (!expectedPath) continue; - const normalizedExpectedPath = existsSync3(expectedPath) ? path37.resolve(realpathSync(expectedPath)) : path37.resolve(expectedPath); - const linkPath = path37.join(rootDir, "server", "node_modules", ...packageName.split("/")); - const actualPath = existsSync3(linkPath) ? path37.resolve(realpathSync(linkPath)) : null; - if (actualPath === normalizedExpectedPath) continue; - mismatches.push({ - packageName, - expectedPath: normalizedExpectedPath, - actualPath - }); - } - return mismatches; -} -async function ensureServerWorkspaceLinksCurrent(startCwd, opts) { - const workspaceRoot = findWorkspaceRoot(startCwd); - if (!workspaceRoot) return; - if (!isLinkedGitWorktreeCheckout(workspaceRoot)) return; - const mismatches = findServerWorkspaceLinkMismatches(workspaceRoot); - if (mismatches.length === 0) return; - if (opts?.onLog) { - await opts.onLog("stdout", "[runtime] detected stale workspace package links for server; relinking dependencies...\n"); - for (const mismatch of mismatches) { - await opts.onLog( - "stdout", - `[runtime] ${mismatch.packageName}: ${mismatch.actualPath ?? "missing"} -> ${mismatch.expectedPath} -` - ); - } - } - for (const mismatch of mismatches) { - const linkPath = path37.join(workspaceRoot, "server", "node_modules", ...mismatch.packageName.split("/")); - await fs30.mkdir(path37.dirname(linkPath), { recursive: true }); - await fs30.rm(linkPath, { recursive: true, force: true }); - await fs30.symlink(mismatch.expectedPath, linkPath); - } - const remainingMismatches = findServerWorkspaceLinkMismatches(workspaceRoot); - if (remainingMismatches.length === 0) return; - throw new Error( - `Workspace relink did not repair all server package links: ${remainingMismatches.map((item) => item.packageName).join(", ")}` - ); -} -function sanitizeRuntimeServiceBaseEnv(baseEnv) { - const env2 = { ...baseEnv }; - for (const key of Object.keys(env2)) { - if (key.startsWith("TASKCORE_")) { - delete env2[key]; - } - } - delete env2.DATABASE_URL; - delete env2.npm_config_tailscale_auth; - delete env2.npm_config_authenticated_private; - return env2; -} -function stableRuntimeServiceId(input) { - if (input.reportId) return input.reportId; - const digest2 = createHash12("sha256").update( - stableStringify3({ - adapterType: input.adapterType, - runId: input.runId, - scopeType: input.scopeType, - scopeId: input.scopeId, - serviceName: input.serviceName, - providerRef: input.providerRef, - reuseKey: input.reuseKey - }) - ).digest("hex").slice(0, 32); - return `${input.adapterType}-${digest2}`; -} -function toRuntimeServiceRef(record2, overrides) { - return { - id: record2.id, - companyId: record2.companyId, - projectId: record2.projectId, - projectWorkspaceId: record2.projectWorkspaceId, - executionWorkspaceId: record2.executionWorkspaceId, - issueId: record2.issueId, - serviceName: record2.serviceName, - status: record2.status, - lifecycle: record2.lifecycle, - scopeType: record2.scopeType, - scopeId: record2.scopeId, - reuseKey: record2.reuseKey, - command: record2.command, - cwd: record2.cwd, - port: record2.port, - url: record2.url, - provider: record2.provider, - providerRef: record2.providerRef, - ownerAgentId: record2.ownerAgentId, - startedByRunId: record2.startedByRunId, - lastUsedAt: record2.lastUsedAt, - startedAt: record2.startedAt, - stoppedAt: record2.stoppedAt, - stopPolicy: record2.stopPolicy, - healthStatus: record2.healthStatus, - reused: record2.reused, - ...overrides - }; -} -function sanitizeSlugPart(value, fallback) { - const raw = (value ?? "").trim().toLowerCase(); - const normalized = raw.replace(/[^a-z0-9_-]+/g, "-").replace(/-+/g, "-").replace(/^[-_]+|[-_]+$/g, ""); - return normalized.length > 0 ? normalized : fallback; -} -function renderWorkspaceTemplate(template, input) { - const issueIdentifier = input.issue?.identifier ?? input.issue?.id ?? "issue"; - const slug = sanitizeSlugPart(input.issue?.title, sanitizeSlugPart(issueIdentifier, "issue")); - return renderTemplate3(template, { - issue: { - id: input.issue?.id ?? "", - identifier: input.issue?.identifier ?? "", - title: input.issue?.title ?? "" - }, - agent: { - id: input.agent.id ?? "", - name: input.agent.name - }, - project: { - id: input.projectId ?? "" - }, - workspace: { - repoRef: input.repoRef ?? "" - }, - slug - }); -} -function sanitizeBranchName(value) { - return value.trim().replace(/[^A-Za-z0-9._/-]+/g, "-").replace(/-+/g, "-").replace(/^[-/.]+|[-/.]+$/g, "").slice(0, 120) || "taskcore-work"; -} -function isAbsolutePath(value) { - return path37.isAbsolute(value) || value.startsWith("~"); -} -function resolveConfiguredPath(value, baseDir) { - if (isAbsolutePath(value)) { - return resolveHomeAwarePath(value); - } - return path37.resolve(baseDir, value); -} -function formatCommandForDisplay(command, args) { - return [command, ...args].map((part) => /^[A-Za-z0-9_./:-]+$/.test(part) ? part : JSON.stringify(part)).join(" "); -} -function createProcessOutputCapture(maxBytes) { - const limit = Math.max(1, Math.trunc(maxBytes)); - let chunks = []; - let truncated = false; - let totalBytes = 0; - return { - append(chunk) { - if (!chunk) return; - chunks.push(chunk); - totalBytes += Buffer.byteLength(chunk, "utf8"); - let currentBytes = chunks.reduce((sum, value) => sum + Buffer.byteLength(value, "utf8"), 0); - if (currentBytes <= limit) return; - const combined = Buffer.from(chunks.join(""), "utf8"); - const tail = combined.subarray(Math.max(0, combined.length - limit)).toString("utf8"); - chunks = [tail]; - truncated = true; - currentBytes = Buffer.byteLength(tail, "utf8"); - if (currentBytes > limit) { - chunks = [Buffer.from(tail, "utf8").subarray(Math.max(0, currentBytes - limit)).toString("utf8")]; - } - }, - finish() { - const text3 = chunks.join(""); - if (!truncated) { - return { - text: text3, - truncated: false, - totalBytes - }; - } - return { - text: `[output truncated to last ${limit} bytes; total ${totalBytes} bytes] -${text3}`, - truncated: true, - totalBytes - }; - } - }; -} -async function executeProcess(input) { - const proc = await new Promise((resolve4, reject) => { - const child = spawn4(input.command, input.args, { - cwd: input.cwd, - stdio: ["ignore", "pipe", "pipe"], - env: input.env ?? process.env - }); - const stdout2 = createProcessOutputCapture(input.maxStdoutBytes ?? DEFAULT_EXECUTE_PROCESS_OUTPUT_BYTES); - const stderr2 = createProcessOutputCapture(input.maxStderrBytes ?? DEFAULT_EXECUTE_PROCESS_OUTPUT_BYTES); - child.stdout?.on("data", (chunk) => { - stdout2.append(String(chunk)); - }); - child.stderr?.on("data", (chunk) => { - stderr2.append(String(chunk)); - }); - child.on("error", reject); - child.on("close", (code) => resolve4({ stdout: stdout2, stderr: stderr2, code })); - }); - const stdout = proc.stdout.finish(); - const stderr = proc.stderr.finish(); - return { - stdout: stdout.text, - stderr: stderr.text, - code: proc.code, - stdoutTruncated: stdout.truncated, - stderrTruncated: stderr.truncated, - stdoutBytes: stdout.totalBytes, - stderrBytes: stderr.totalBytes - }; -} -async function runGit2(args, cwd) { - const proc = await executeProcess({ - command: "git", - args, - cwd - }); - if (proc.code !== 0) { - throw new Error(proc.stderr.trim() || proc.stdout.trim() || `git ${args.join(" ")} failed`); - } - return proc.stdout.trim(); -} -function gitErrorIncludes(error50, needle) { - const message2 = error50 instanceof Error ? error50.message : String(error50); - return message2.toLowerCase().includes(needle.toLowerCase()); -} -function parseGitWorktreeListPorcelain(raw) { - const entries2 = []; - let current = {}; - for (const line3 of raw.split(/\r?\n/)) { - if (line3.startsWith("worktree ")) { - current = { worktree: line3.slice("worktree ".length) }; - continue; - } - if (line3.startsWith("branch ")) { - current.branch = line3.slice("branch ".length); - continue; - } - if (line3 === "" && current.worktree) { - entries2.push({ - worktree: current.worktree, - branch: current.branch ?? null - }); - current = {}; - } - } - if (current.worktree) { - entries2.push({ - worktree: current.worktree, - branch: current.branch ?? null - }); - } - return entries2; -} -async function resolveGitOwnerRepoRoot(cwd) { - const checkoutRoot = path37.resolve(await runGit2(["rev-parse", "--show-toplevel"], cwd)); - const commonDir = await runGit2(["rev-parse", "--git-common-dir"], checkoutRoot).catch(() => null); - if (!commonDir) return checkoutRoot; - return path37.dirname(path37.resolve(checkoutRoot, commonDir)); -} -async function findRegisteredGitWorktreeByBranch(repoRoot, branchName) { - const raw = await runGit2(["worktree", "list", "--porcelain"], repoRoot).catch(() => null); - if (!raw) return null; - const expectedBranchRef = `refs/heads/${branchName}`; - for (const entry of parseGitWorktreeListPorcelain(raw)) { - if (entry.branch !== expectedBranchRef) continue; - return path37.resolve(entry.worktree); - } - return null; -} -async function isGitCheckout(cwd) { - return Boolean(await runGit2(["rev-parse", "--git-dir"], cwd).catch(() => null)); -} -async function detectDefaultBranch(repoRoot) { - try { - const remoteHead = await runGit2( - ["symbolic-ref", "--quiet", "--short", "refs/remotes/origin/HEAD"], - repoRoot - ); - const branch = remoteHead?.startsWith("origin/") ? remoteHead.slice("origin/".length) : remoteHead; - if (branch) return branch; - } catch { - } - for (const candidate of ["main", "master"]) { - try { - await runGit2(["rev-parse", "--verify", `refs/remotes/origin/${candidate}`], repoRoot); - return candidate; - } catch { - } - } - return null; -} -async function directoryExists(value) { - return fs30.stat(value).then((stats) => stats.isDirectory()).catch(() => false); -} -async function listLinkedGitWorktreePaths(repoRoot) { - const output = await runGit2(["worktree", "list", "--porcelain"], repoRoot); - const paths2 = /* @__PURE__ */ new Set(); - for (const line3 of output.split("\n")) { - if (!line3.startsWith("worktree ")) continue; - const worktree = line3.slice("worktree ".length).trim(); - if (!worktree) continue; - paths2.add(path37.resolve(worktree)); - } - return paths2; -} -async function validateLinkedGitWorktree(input) { - const resolvedWorktreePath = path37.resolve(input.worktreePath); - const listedWorktrees = await listLinkedGitWorktreePaths(input.repoRoot); - if (!listedWorktrees.has(resolvedWorktreePath)) { - return { - valid: false, - reason: "path is not registered in `git worktree list`" - }; - } - const worktreeTopLevel = await runGit2(["rev-parse", "--show-toplevel"], resolvedWorktreePath).catch(() => null); - if (!worktreeTopLevel || path37.resolve(worktreeTopLevel) !== resolvedWorktreePath) { - return { - valid: false, - reason: "git resolves this path to a different repository root" - }; - } - if (input.expectedBranchName) { - const currentBranch = await runGit2( - ["symbolic-ref", "--quiet", "--short", "HEAD"], - resolvedWorktreePath - ).catch(() => null); - if (currentBranch !== input.expectedBranchName) { - return { - valid: false, - reason: `worktree HEAD is on "${currentBranch ?? ""}" instead of "${input.expectedBranchName}"` - }; - } - } - return { valid: true }; -} -function terminateChildProcess(child) { - if (!child.pid) return; - if (process.platform !== "win32") { - try { - process.kill(-child.pid, "SIGTERM"); - return; - } catch { - } - } - if (!child.killed) { - child.kill("SIGTERM"); - } -} -function buildWorkspaceCommandEnv(input) { - const env2 = { ...process.env }; - env2.TASKCORE_WORKSPACE_CWD = input.worktreePath; - env2.TASKCORE_WORKSPACE_PATH = input.worktreePath; - env2.TASKCORE_WORKSPACE_WORKTREE_PATH = input.worktreePath; - env2.TASKCORE_WORKSPACE_BRANCH = input.branchName; - env2.TASKCORE_WORKSPACE_BASE_CWD = input.base.baseCwd; - env2.TASKCORE_WORKSPACE_REPO_ROOT = input.repoRoot; - env2.TASKCORE_WORKSPACE_SOURCE = input.base.source; - env2.TASKCORE_WORKSPACE_REPO_REF = input.base.repoRef ?? ""; - env2.TASKCORE_WORKSPACE_REPO_URL = input.base.repoUrl ?? ""; - env2.TASKCORE_WORKSPACE_CREATED = input.created ? "true" : "false"; - env2.TASKCORE_PROJECT_ID = input.base.projectId ?? ""; - env2.TASKCORE_PROJECT_WORKSPACE_ID = input.base.workspaceId ?? ""; - env2.TASKCORE_AGENT_ID = input.agent.id ?? ""; - env2.TASKCORE_AGENT_NAME = input.agent.name; - env2.TASKCORE_COMPANY_ID = input.agent.companyId; - env2.TASKCORE_ISSUE_ID = input.issue?.id ?? ""; - env2.TASKCORE_ISSUE_IDENTIFIER = input.issue?.identifier ?? ""; - env2.TASKCORE_ISSUE_TITLE = input.issue?.title ?? ""; - return env2; -} -function quoteShellArg(value) { - return `'${value.replace(/'/g, `'\\''`)}'`; -} -function resolveRepoManagedWorkspaceCommand(command, repoRoot) { - const patterns = [ - /^(?(?:bash|sh|zsh)\s+)(?["']?)(?\.\/[^"'\s]+)\k(?(?:\s.*)?)$/s, - /^(?["']?)(?\.\/[^"'\s]+)\k(?(?:\s.*)?)$/s - ]; - for (const pattern of patterns) { - const match = command.match(pattern); - if (!match?.groups) continue; - const relativePath = match.groups.relative; - const repoManagedPath = path37.join(repoRoot, relativePath.slice(2)); - if (!existsSync3(repoManagedPath)) continue; - const prefix = match.groups.prefix ?? ""; - const suffix = match.groups.suffix ?? ""; - return `${prefix}${quoteShellArg(repoManagedPath)}${suffix}`; - } - return command; -} -async function runWorkspaceCommand(input) { - const shell = resolveShell(); - const proc = await executeProcess({ - command: shell, - args: ["-c", input.resolvedCommand ?? input.command], - cwd: input.cwd, - env: input.env - }); - if (proc.code === 0) return; - const details = [proc.stderr.trim(), proc.stdout.trim()].filter(Boolean).join("\n"); - throw new Error( - details.length > 0 ? `${input.label} failed: ${details}` : `${input.label} failed with exit code ${proc.code ?? -1}` - ); -} -async function recordGitOperation(recorder, input) { - if (!recorder) { - return runGit2(input.args, input.cwd); - } - let stdout = ""; - let stderr = ""; - let code = null; - await recorder.recordOperation({ - phase: input.phase, - command: formatCommandForDisplay("git", input.args), - cwd: input.cwd, - metadata: input.metadata ?? null, - run: async () => { - const result = await executeProcess({ - command: "git", - args: input.args, - cwd: input.cwd - }); - stdout = result.stdout; - stderr = result.stderr; - code = result.code; - return { - status: result.code === 0 ? "succeeded" : "failed", - exitCode: result.code, - stdout: result.stdout, - stderr: result.stderr, - system: result.code === 0 ? input.successMessage ?? null : null, - metadata: result.stdoutTruncated || result.stderrTruncated ? { - stdoutTruncated: result.stdoutTruncated, - stderrTruncated: result.stderrTruncated, - stdoutBytes: result.stdoutBytes, - stderrBytes: result.stderrBytes - } : null - }; - } - }); - if (code !== 0) { - const details = [stderr.trim(), stdout.trim()].filter(Boolean).join("\n"); - throw new Error( - details.length > 0 ? `${input.failureLabel ?? `git ${input.args.join(" ")}`} failed: ${details}` : `${input.failureLabel ?? `git ${input.args.join(" ")}`} failed with exit code ${code ?? -1}` - ); - } - return stdout.trim(); -} -async function recordWorkspaceCommandOperation(recorder, input) { - if (!recorder) { - await runWorkspaceCommand(input); - return null; - } - let stdout = ""; - let stderr = ""; - let code = null; - const operation2 = await recorder.recordOperation({ - phase: input.phase, - command: input.command, - cwd: input.cwd, - metadata: input.metadata ?? null, - run: async () => { - const shell = resolveShell(); - const result = await executeProcess({ - command: shell, - args: ["-c", input.resolvedCommand ?? input.command], - cwd: input.cwd, - env: input.env - }); - stdout = result.stdout; - stderr = result.stderr; - code = result.code; - return { - status: result.code === 0 ? "succeeded" : "failed", - exitCode: result.code, - stdout: result.stdout, - stderr: result.stderr, - system: result.code === 0 ? input.successMessage ?? null : null, - metadata: result.stdoutTruncated || result.stderrTruncated ? { - stdoutTruncated: result.stdoutTruncated, - stderrTruncated: result.stderrTruncated, - stdoutBytes: result.stdoutBytes, - stderrBytes: result.stderrBytes - } : null - }; - } - }); - if (code === 0) return operation2; - const details = [stderr.trim(), stdout.trim()].filter(Boolean).join("\n"); - throw new Error( - details.length > 0 ? `${input.label} failed: ${details}` : `${input.label} failed with exit code ${code ?? -1}` - ); -} -async function provisionExecutionWorktree(input) { - const provisionCommand = asString12(input.strategy.provisionCommand, "").trim(); - if (!provisionCommand) return; - const resolvedProvisionCommand = resolveRepoManagedWorkspaceCommand(provisionCommand, input.repoRoot); - await recordWorkspaceCommandOperation(input.recorder, { - phase: "workspace_provision", - command: provisionCommand, - resolvedCommand: resolvedProvisionCommand, - cwd: input.worktreePath, - env: buildWorkspaceCommandEnv({ - base: input.base, - repoRoot: input.repoRoot, - worktreePath: input.worktreePath, - branchName: input.branchName, - issue: input.issue, - agent: input.agent, - created: input.created - }), - label: `Execution workspace provision command "${provisionCommand}"`, - metadata: { - repoRoot: input.repoRoot, - worktreePath: input.worktreePath, - branchName: input.branchName, - created: input.created, - resolvedCommand: resolvedProvisionCommand === provisionCommand ? null : resolvedProvisionCommand - }, - successMessage: `Provisioned workspace at ${input.worktreePath} -` - }); -} -function buildExecutionWorkspaceCleanupEnv(input) { - const env2 = sanitizeRuntimeServiceBaseEnv(process.env); - env2.TASKCORE_WORKSPACE_CWD = input.workspace.cwd ?? ""; - env2.TASKCORE_WORKSPACE_PATH = input.workspace.cwd ?? ""; - env2.TASKCORE_WORKSPACE_WORKTREE_PATH = input.workspace.providerRef ?? input.workspace.cwd ?? ""; - env2.TASKCORE_WORKSPACE_BRANCH = input.workspace.branchName ?? ""; - env2.TASKCORE_WORKSPACE_BASE_CWD = input.projectWorkspaceCwd ?? ""; - env2.TASKCORE_WORKSPACE_REPO_ROOT = input.projectWorkspaceCwd ?? ""; - env2.TASKCORE_WORKSPACE_REPO_URL = input.workspace.repoUrl ?? ""; - env2.TASKCORE_WORKSPACE_REPO_REF = input.workspace.baseRef ?? ""; - env2.TASKCORE_PROJECT_ID = input.workspace.projectId ?? ""; - env2.TASKCORE_PROJECT_WORKSPACE_ID = input.workspace.projectWorkspaceId ?? ""; - env2.TASKCORE_ISSUE_ID = input.workspace.sourceIssueId ?? ""; - return env2; -} -async function resolveGitRepoRootForWorkspaceCleanup(worktreePath, projectWorkspaceCwd) { - if (projectWorkspaceCwd) { - const resolvedProjectWorkspaceCwd = path37.resolve(projectWorkspaceCwd); - const gitDir2 = await runGit2(["rev-parse", "--git-common-dir"], resolvedProjectWorkspaceCwd).catch(() => null); - if (gitDir2) { - const resolvedGitDir2 = path37.resolve(resolvedProjectWorkspaceCwd, gitDir2); - return path37.dirname(resolvedGitDir2); - } - } - const gitDir = await runGit2(["rev-parse", "--git-common-dir"], worktreePath).catch(() => null); - if (!gitDir) return null; - const resolvedGitDir = path37.resolve(worktreePath, gitDir); - return path37.dirname(resolvedGitDir); -} -async function realizeExecutionWorkspace(input) { - const rawStrategy = parseObject4(input.config.workspaceStrategy); - const strategyType = asString12(rawStrategy.type, "project_primary"); - if (strategyType !== "git_worktree") { - return { - ...input.base, - strategy: "project_primary", - cwd: input.base.baseCwd, - branchName: null, - worktreePath: null, - warnings: [], - created: false - }; - } - const repoRoot = await resolveGitOwnerRepoRoot(input.base.baseCwd); - const branchTemplate = asString12(rawStrategy.branchTemplate, "{{issue.identifier}}-{{slug}}"); - const renderedBranch = renderWorkspaceTemplate(branchTemplate, { - issue: input.issue, - agent: input.agent, - projectId: input.base.projectId, - repoRef: input.base.repoRef - }); - const branchName = sanitizeBranchName(renderedBranch); - const configuredParentDir = asString12(rawStrategy.worktreeParentDir, ""); - const worktreeParentDir = configuredParentDir ? resolveConfiguredPath(configuredParentDir, repoRoot) : path37.join(repoRoot, ".taskcore", "worktrees"); - const worktreePath = path37.join(worktreeParentDir, branchName); - const configuredBaseRef = typeof rawStrategy.baseRef === "string" && rawStrategy.baseRef.length > 0 ? rawStrategy.baseRef : input.base.repoRef ?? null; - const baseRef = configuredBaseRef ?? await detectDefaultBranch(repoRoot) ?? "HEAD"; - await fs30.mkdir(worktreeParentDir, { recursive: true }); - async function reuseExistingWorktree(reusablePath) { - if (input.recorder) { - await input.recorder.recordOperation({ - phase: "worktree_prepare", - cwd: repoRoot, - metadata: { - repoRoot, - worktreePath: reusablePath, - branchName, - baseRef, - created: false, - reused: true - }, - run: async () => ({ - status: "succeeded", - exitCode: 0, - system: `Reused existing git worktree at ${reusablePath} -` - }) - }); - } - await provisionExecutionWorktree({ - strategy: rawStrategy, - base: input.base, - repoRoot, - worktreePath: reusablePath, - branchName, - issue: input.issue, - agent: input.agent, - created: false, - recorder: input.recorder ?? null - }); - return { - ...input.base, - strategy: "git_worktree", - cwd: reusablePath, - branchName, - worktreePath: reusablePath, - warnings: [], - created: false - }; - } - async function validateReusableWorktree(reusablePath) { - return await validateLinkedGitWorktree({ - repoRoot, - worktreePath: reusablePath, - expectedBranchName: branchName - }).catch(() => null); - } - const existingWorktree = await directoryExists(worktreePath); - if (existingWorktree) { - const validation = await validateReusableWorktree(worktreePath); - if (validation?.valid) { - return await reuseExistingWorktree(worktreePath); - } - const reason = validation && !validation.valid ? ` (${validation.reason})` : ""; - throw new Error(`Configured worktree path "${worktreePath}" already exists and is not a reusable git worktree${reason}.`); - } - const registeredBranchWorktree = await findRegisteredGitWorktreeByBranch(repoRoot, branchName); - if (registeredBranchWorktree) { - const validation = await validateReusableWorktree(registeredBranchWorktree); - if (validation?.valid) { - return await reuseExistingWorktree(registeredBranchWorktree); - } - const reason = validation && !validation.valid ? ` (${validation.reason})` : ""; - throw new Error(`Registered worktree for branch "${branchName}" at "${registeredBranchWorktree}" is not reusable${reason}.`); - } - try { - await recordGitOperation(input.recorder, { - phase: "worktree_prepare", - args: ["worktree", "add", "-b", branchName, worktreePath, baseRef], - cwd: repoRoot, - metadata: { - repoRoot, - worktreePath, - branchName, - baseRef, - created: true - }, - successMessage: `Created git worktree at ${worktreePath} -`, - failureLabel: `git worktree add ${worktreePath}` - }); - } catch (error50) { - if (!gitErrorIncludes(error50, "already exists")) { - throw error50; - } - try { - await recordGitOperation(input.recorder, { - phase: "worktree_prepare", - args: ["worktree", "add", worktreePath, branchName], - cwd: repoRoot, - metadata: { - repoRoot, - worktreePath, - branchName, - baseRef, - created: false, - reusedExistingBranch: true - }, - successMessage: `Attached existing branch ${branchName} at ${worktreePath} -`, - failureLabel: `git worktree add ${worktreePath}` - }); - } catch (attachError) { - if (!gitErrorIncludes(attachError, "already checked out")) { - throw attachError; - } - const reusablePath = await findRegisteredGitWorktreeByBranch(repoRoot, branchName); - if (!reusablePath || !await isGitCheckout(reusablePath)) { - throw attachError; - } - return await reuseExistingWorktree(reusablePath); - } - } - await provisionExecutionWorktree({ - strategy: rawStrategy, - base: input.base, - repoRoot, - worktreePath, - branchName, - issue: input.issue, - agent: input.agent, - created: true, - recorder: input.recorder ?? null - }); - return { - ...input.base, - strategy: "git_worktree", - cwd: worktreePath, - branchName, - worktreePath, - warnings: [], - created: true - }; -} -async function ensurePersistedExecutionWorkspaceAvailable(input) { - const cwd = asString12(input.workspace.cwd ?? input.workspace.providerRef, "").trim(); - if (!cwd) return null; - const strategy = input.workspace.strategyType === "git_worktree" ? "git_worktree" : "project_primary"; - const realized = { - baseCwd: input.base.baseCwd, - source: input.workspace.mode === "shared_workspace" ? "project_primary" : "task_session", - projectId: input.workspace.projectId ?? input.base.projectId, - workspaceId: input.workspace.projectWorkspaceId ?? input.base.workspaceId, - repoUrl: input.workspace.repoUrl ?? input.base.repoUrl, - repoRef: input.workspace.baseRef ?? input.base.repoRef, - strategy, - cwd, - branchName: input.workspace.branchName ?? null, - worktreePath: strategy === "git_worktree" ? input.workspace.providerRef ?? cwd : null, - warnings: [], - created: false - }; - const provisionCommand = asString12(input.workspace.config?.provisionCommand, "").trim(); - if (strategy !== "git_worktree") { - return realized; - } - if (await directoryExists(cwd)) { - if (provisionCommand) { - const repoRoot2 = await runGit2(["rev-parse", "--show-toplevel"], input.base.baseCwd); - await provisionExecutionWorktree({ - strategy: { - type: "git_worktree", - provisionCommand - }, - base: input.base, - repoRoot: repoRoot2, - worktreePath: realized.worktreePath ?? cwd, - branchName: realized.branchName ?? "", - issue: input.issue, - agent: input.agent, - created: false, - recorder: input.recorder ?? null - }); - } - return realized; - } - const repoRoot = await runGit2(["rev-parse", "--show-toplevel"], input.base.baseCwd); - const worktreePath = realized.worktreePath ?? cwd; - const branchName = asString12(input.workspace.branchName, "").trim(); - if (!branchName) { - throw new Error(`Execution workspace "${cwd}" is missing and cannot be restored because no branch name is recorded.`); - } - await fs30.mkdir(path37.dirname(worktreePath), { recursive: true }); - await runGit2(["worktree", "prune"], repoRoot).catch(() => { - }); - let created = false; - try { - await recordGitOperation(input.recorder, { - phase: "worktree_prepare", - args: ["worktree", "add", worktreePath, branchName], - cwd: repoRoot, - metadata: { - repoRoot, - worktreePath, - branchName, - baseRef: input.workspace.baseRef ?? input.base.repoRef ?? null, - created: false, - restored: true - }, - successMessage: `Reattached missing git worktree at ${worktreePath} -`, - failureLabel: `git worktree add ${worktreePath}` - }); - } catch (error50) { - if (!gitErrorIncludes(error50, "invalid reference") && !gitErrorIncludes(error50, "not a commit") && !gitErrorIncludes(error50, "unknown revision")) { - throw error50; - } - const baseRef = input.workspace.baseRef ?? await detectDefaultBranch(repoRoot) ?? "HEAD"; - await recordGitOperation(input.recorder, { - phase: "worktree_prepare", - args: ["worktree", "add", "-b", branchName, worktreePath, baseRef], - cwd: repoRoot, - metadata: { - repoRoot, - worktreePath, - branchName, - baseRef, - created: true, - restored: true - }, - successMessage: `Recreated missing git worktree at ${worktreePath} -`, - failureLabel: `git worktree add ${worktreePath}` - }); - created = true; - } - await provisionExecutionWorktree({ - strategy: { - type: "git_worktree", - ...provisionCommand ? { provisionCommand } : {} - }, - base: input.base, - repoRoot, - worktreePath, - branchName, - issue: input.issue, - agent: input.agent, - created, - recorder: input.recorder ?? null - }); - return { - ...realized, - cwd: worktreePath, - worktreePath, - created - }; -} -async function cleanupExecutionWorkspaceArtifacts(input) { - const warnings = []; - const workspacePath = input.workspace.providerRef ?? input.workspace.cwd; - const repoRoot = input.workspace.providerType === "git_worktree" && workspacePath ? await resolveGitRepoRootForWorkspaceCleanup( - workspacePath, - input.projectWorkspace?.cwd ?? null - ) : null; - const cleanupEnv = buildExecutionWorkspaceCleanupEnv({ - workspace: input.workspace, - projectWorkspaceCwd: input.projectWorkspace?.cwd ?? null - }); - const createdByRuntime = input.workspace.metadata?.createdByRuntime === true; - const cleanupCommands = [ - input.cleanupCommand ?? null, - input.projectWorkspace?.cleanupCommand ?? null, - input.teardownCommand ?? null - ].map((value) => asString12(value, "").trim()).filter(Boolean); - for (const command of cleanupCommands) { - try { - const resolvedCommand = repoRoot ? resolveRepoManagedWorkspaceCommand(command, repoRoot) : command; - await recordWorkspaceCommandOperation(input.recorder, { - phase: "workspace_teardown", - command, - resolvedCommand, - cwd: workspacePath ?? input.projectWorkspace?.cwd ?? process.cwd(), - env: cleanupEnv, - label: `Execution workspace cleanup command "${command}"`, - metadata: { - workspaceId: input.workspace.id, - workspacePath, - branchName: input.workspace.branchName, - providerType: input.workspace.providerType, - resolvedCommand: resolvedCommand === command ? null : resolvedCommand - }, - successMessage: `Completed cleanup command "${command}" -` - }); - } catch (err) { - warnings.push(err instanceof Error ? err.message : String(err)); - } - } - if (input.workspace.providerType === "git_worktree" && workspacePath) { - const worktreeExists = await directoryExists(workspacePath); - if (worktreeExists) { - if (!repoRoot) { - warnings.push(`Could not resolve git repo root for "${workspacePath}".`); - } else { - try { - await recordGitOperation(input.recorder, { - phase: "worktree_cleanup", - args: ["worktree", "remove", "--force", workspacePath], - cwd: repoRoot, - metadata: { - workspaceId: input.workspace.id, - workspacePath, - branchName: input.workspace.branchName, - cleanupAction: "worktree_remove" - }, - successMessage: `Removed git worktree ${workspacePath} -`, - failureLabel: `git worktree remove ${workspacePath}` - }); - } catch (err) { - warnings.push(err instanceof Error ? err.message : String(err)); - } - } - } - if (createdByRuntime && input.workspace.branchName) { - if (!repoRoot) { - warnings.push(`Could not resolve git repo root to delete branch "${input.workspace.branchName}".`); - } else { - try { - await recordGitOperation(input.recorder, { - phase: "worktree_cleanup", - args: ["branch", "-d", input.workspace.branchName], - cwd: repoRoot, - metadata: { - workspaceId: input.workspace.id, - workspacePath, - branchName: input.workspace.branchName, - cleanupAction: "branch_delete" - }, - successMessage: `Deleted branch ${input.workspace.branchName} -`, - failureLabel: `git branch -d ${input.workspace.branchName}` - }); - } catch (err) { - const message2 = err instanceof Error ? err.message : String(err); - warnings.push(`Skipped deleting branch "${input.workspace.branchName}": ${message2}`); - } - } - } - } else if (input.workspace.providerType === "local_fs" && createdByRuntime && workspacePath) { - const projectWorkspaceCwd = input.projectWorkspace?.cwd ? path37.resolve(input.projectWorkspace.cwd) : null; - const resolvedWorkspacePath = path37.resolve(workspacePath); - const containsProjectWorkspace = projectWorkspaceCwd ? resolvedWorkspacePath === projectWorkspaceCwd || projectWorkspaceCwd.startsWith(`${resolvedWorkspacePath}${path37.sep}`) : false; - if (containsProjectWorkspace) { - warnings.push(`Refusing to remove path "${workspacePath}" because it contains the project workspace.`); - } else { - await fs30.rm(resolvedWorkspacePath, { recursive: true, force: true }); - if (input.recorder) { - await input.recorder.recordOperation({ - phase: "workspace_teardown", - cwd: projectWorkspaceCwd ?? process.cwd(), - metadata: { - workspaceId: input.workspace.id, - workspacePath: resolvedWorkspacePath, - cleanupAction: "remove_local_fs" - }, - run: async () => ({ - status: "succeeded", - exitCode: 0, - system: `Removed local workspace directory ${resolvedWorkspacePath} -` - }) - }); - } - } - } - const cleaned = !workspacePath || !await directoryExists(workspacePath); - return { - cleanedPath: workspacePath, - cleaned, - warnings - }; -} -async function allocatePort() { - return await new Promise((resolve4, reject) => { - const server = net2.createServer(); - server.listen(0, "127.0.0.1", () => { - const address = server.address(); - server.close((err) => { - if (err) { - reject(err); - return; - } - if (!address || typeof address === "string") { - reject(new Error("Failed to allocate port")); - return; - } - resolve4(address.port); - }); - }); - server.on("error", reject); - }); -} -function buildTemplateData(input) { - return { - workspace: { - cwd: input.workspace.cwd, - branchName: input.workspace.branchName ?? "", - worktreePath: input.workspace.worktreePath ?? "", - repoUrl: input.workspace.repoUrl ?? "", - repoRef: input.workspace.repoRef ?? "", - env: input.adapterEnv - }, - issue: { - id: input.issue?.id ?? "", - identifier: input.issue?.identifier ?? "", - title: input.issue?.title ?? "" - }, - agent: { - id: input.agent.id ?? "", - name: input.agent.name - }, - port: input.port ?? "" - }; -} -function renderRuntimeServiceEnv(input) { - const rendered = {}; - for (const [key, value] of Object.entries(input.envConfig)) { - if (typeof value !== "string") continue; - rendered[key] = renderTemplate3(value, input.templateData); - } - return rendered; -} -function resolveRuntimeServiceReuseIdentity(input) { - const serviceName = asString12(input.service.name, "service"); - const lifecycle = asString12(input.service.lifecycle, "shared") === "ephemeral" ? "ephemeral" : "shared"; - const command = asString12(input.service.command, ""); - const serviceCwdTemplate = asString12(input.service.cwd, "."); - const portConfig = parseObject4(input.service.port); - const envConfig = parseObject4(input.service.env); - const explicitPort = asNumber3(portConfig.value, asNumber3(input.service.port, 0)); - const identityPort = explicitPort > 0 ? explicitPort : null; - const templateData = buildTemplateData({ - workspace: input.workspace, - agent: input.agent, - issue: input.issue, - adapterEnv: input.adapterEnv, - port: identityPort - }); - const serviceCwd = resolveConfiguredPath(renderTemplate3(serviceCwdTemplate, templateData), input.workspace.cwd); - const renderedEnv = renderRuntimeServiceEnv({ - envConfig, - templateData - }); - const envFingerprint = createHash12("sha256").update(stableStringify3(renderedEnv)).digest("hex"); - const reuseKey = lifecycle === "shared" ? createHash12("sha256").update( - stableStringify3({ - scopeType: input.scopeType, - scopeId: input.scopeId, - serviceName, - command, - cwd: serviceCwd, - port: identityPort, - env: renderedEnv - }) - ).digest("hex") : null; - return { - serviceName, - lifecycle, - command, - serviceCwd, - envConfig, - envFingerprint, - explicitPort, - identityPort, - reuseKey - }; -} -function resolveWorkspaceCommandExecution(input) { - const name = asString12(input.command.name, "") || asString12(input.command.label, "") || asString12(input.command.title, "") || "workspace command"; - const command = asString12(input.command.command, ""); - const templateData = buildTemplateData({ - workspace: input.workspace, - agent: input.agent, - issue: input.issue, - adapterEnv: input.adapterEnv, - port: null - }); - const cwd = resolveConfiguredPath( - renderTemplate3(asString12(input.command.cwd, "."), templateData), - input.workspace.cwd - ); - const env2 = { - ...sanitizeRuntimeServiceBaseEnv(process.env), - ...input.adapterEnv, - ...renderRuntimeServiceEnv({ - envConfig: parseObject4(input.command.env), - templateData - }) - }; - return { - name, - command, - cwd, - env: env2 - }; -} -async function runWorkspaceJobForControl(input) { - const resolved = resolveWorkspaceCommandExecution({ - command: input.command, - workspace: input.workspace, - agent: input.actor, - issue: input.issue, - adapterEnv: input.adapterEnv ?? {} - }); - if (!resolved.command) { - throw new Error(`Workspace job "${resolved.name}" is missing command`); - } - await ensureServerWorkspaceLinksCurrent(resolved.cwd); - return await recordWorkspaceCommandOperation(input.recorder, { - phase: "workspace_provision", - command: resolved.command, - cwd: resolved.cwd, - env: resolved.env, - label: `Workspace job "${resolved.name}"`, - metadata: { - workspaceCommandKind: "job", - workspaceCommandName: resolved.name, - ...input.metadata ?? {} - }, - successMessage: `Completed workspace job "${resolved.name}" -` - }); -} -function resolveServiceScopeId(input) { - const scopeTypeRaw = asString12(input.service.reuseScope, input.service.lifecycle === "shared" ? "project_workspace" : "run"); - const scopeType = scopeTypeRaw === "project_workspace" || scopeTypeRaw === "execution_workspace" || scopeTypeRaw === "agent" ? scopeTypeRaw : "run"; - if (scopeType === "project_workspace") return { scopeType, scopeId: input.workspace.workspaceId ?? input.workspace.projectId }; - if (scopeType === "execution_workspace") { - return { scopeType, scopeId: input.executionWorkspaceId ?? input.workspace.cwd }; - } - if (scopeType === "agent") return { scopeType, scopeId: input.agent.id }; - return { scopeType: "run", scopeId: input.runId }; -} -function looksLikeWorkspaceDevServerCommand(command) { - const normalized = command.trim().toLowerCase(); - if (!normalized) return false; - return /(?:^|\s)(?:pnpm|npm|yarn|bun)\s+(?:run\s+)?dev(?:\s|$)/.test(normalized); -} -function resolveWorkspaceRuntimeReadinessTimeoutSec(service) { - const readiness = parseObject4(service.readiness); - const explicitTimeoutSec = asNumber3(readiness.timeoutSec, 0); - if (explicitTimeoutSec > 0) { - return Math.max(1, explicitTimeoutSec); - } - return looksLikeWorkspaceDevServerCommand(asString12(service.command, "")) ? 90 : 30; -} -async function waitForReadiness(input) { - const readiness = parseObject4(input.service.readiness); - const readinessType = asString12(readiness.type, ""); - if (readinessType !== "http" || !input.url) return; - const timeoutSec = resolveWorkspaceRuntimeReadinessTimeoutSec(input.service); - const intervalMs = Math.max(100, asNumber3(readiness.intervalMs, 500)); - const deadline = Date.now() + timeoutSec * 1e3; - let lastError = "service did not become ready"; - while (Date.now() < deadline) { - try { - const response = await fetch(input.url); - if (response.ok) return; - lastError = `received HTTP ${response.status}`; - } catch (err) { - lastError = err instanceof Error ? err.message : String(err); - } - await delay2(intervalMs); - } - throw new Error(`Readiness check failed for ${input.url}: ${lastError}`); -} -function toPersistedWorkspaceRuntimeService(record2) { - return { - id: record2.id, - companyId: record2.companyId, - projectId: record2.projectId, - projectWorkspaceId: record2.projectWorkspaceId, - executionWorkspaceId: record2.executionWorkspaceId, - issueId: record2.issueId, - scopeType: record2.scopeType, - scopeId: record2.scopeId, - serviceName: record2.serviceName, - status: record2.status, - lifecycle: record2.lifecycle, - reuseKey: record2.reuseKey, - command: record2.command, - cwd: record2.cwd, - port: record2.port, - url: record2.url, - provider: record2.provider, - providerRef: record2.providerRef, - ownerAgentId: record2.ownerAgentId, - startedByRunId: record2.startedByRunId, - lastUsedAt: new Date(record2.lastUsedAt), - startedAt: new Date(record2.startedAt), - stoppedAt: record2.stoppedAt ? new Date(record2.stoppedAt) : null, - stopPolicy: record2.stopPolicy, - healthStatus: record2.healthStatus, - updatedAt: /* @__PURE__ */ new Date() - }; -} -async function persistRuntimeServiceRecord(db, record2) { - if (!db) return; - const values2 = toPersistedWorkspaceRuntimeService(record2); - await db.insert(workspaceRuntimeServices).values(values2).onConflictDoUpdate({ - target: workspaceRuntimeServices.id, - set: { - projectId: values2.projectId, - projectWorkspaceId: values2.projectWorkspaceId, - executionWorkspaceId: values2.executionWorkspaceId, - issueId: values2.issueId, - scopeType: values2.scopeType, - scopeId: values2.scopeId, - serviceName: values2.serviceName, - status: values2.status, - lifecycle: values2.lifecycle, - reuseKey: values2.reuseKey, - command: values2.command, - cwd: values2.cwd, - port: values2.port, - url: values2.url, - provider: values2.provider, - providerRef: values2.providerRef, - ownerAgentId: values2.ownerAgentId, - startedByRunId: values2.startedByRunId, - lastUsedAt: values2.lastUsedAt, - startedAt: values2.startedAt, - stoppedAt: values2.stoppedAt, - stopPolicy: values2.stopPolicy, - healthStatus: values2.healthStatus, - updatedAt: values2.updatedAt - } - }); -} -function clearIdleTimer(record2) { - if (!record2.idleTimer) return; - clearTimeout(record2.idleTimer); - record2.idleTimer = null; -} -function normalizeAdapterManagedRuntimeServices(input) { - const nowIso = (input.now ?? /* @__PURE__ */ new Date()).toISOString(); - return input.reports.map((report) => { - const scopeType = report.scopeType ?? "run"; - const scopeId = report.scopeId ?? (scopeType === "project_workspace" ? input.workspace.workspaceId : scopeType === "execution_workspace" ? input.executionWorkspaceId ?? input.workspace.cwd : scopeType === "agent" ? input.agent.id : input.runId) ?? null; - const serviceName = asString12(report.serviceName, "").trim() || "service"; - const status = report.status ?? "running"; - const lifecycle = report.lifecycle ?? "ephemeral"; - const healthStatus = report.healthStatus ?? (status === "running" ? "healthy" : status === "failed" ? "unhealthy" : "unknown"); - return { - id: stableRuntimeServiceId({ - adapterType: input.adapterType, - runId: input.runId, - scopeType, - scopeId, - serviceName, - reportId: report.id ?? null, - providerRef: report.providerRef ?? null, - reuseKey: report.reuseKey ?? null - }), - companyId: input.agent.companyId, - projectId: report.projectId ?? input.workspace.projectId, - projectWorkspaceId: report.projectWorkspaceId ?? input.workspace.workspaceId, - executionWorkspaceId: input.executionWorkspaceId ?? null, - issueId: report.issueId ?? input.issue?.id ?? null, - serviceName, - status, - lifecycle, - scopeType, - scopeId, - reuseKey: report.reuseKey ?? null, - command: report.command ?? null, - cwd: report.cwd ?? null, - port: report.port ?? null, - url: report.url ?? null, - provider: "adapter_managed", - providerRef: report.providerRef ?? null, - ownerAgentId: report.ownerAgentId ?? input.agent.id ?? null, - startedByRunId: input.runId, - lastUsedAt: nowIso, - startedAt: nowIso, - stoppedAt: status === "running" || status === "starting" ? null : nowIso, - stopPolicy: report.stopPolicy ?? null, - healthStatus, - reused: false - }; - }); -} -async function startLocalRuntimeService(input) { - const leaseRunId = input.leaseRunId === void 0 ? input.runId : input.leaseRunId; - const startedByRunId = input.startedByRunId === void 0 ? input.runId : input.startedByRunId; - const identity = resolveRuntimeServiceReuseIdentity({ - service: input.service, - workspace: input.workspace, - agent: input.agent, - issue: input.issue, - adapterEnv: input.adapterEnv, - scopeType: input.scopeType, - scopeId: input.scopeId - }); - const serviceName = identity.serviceName; - const lifecycle = identity.lifecycle; - const command = identity.command; - if (!command) throw new Error(`Runtime service "${serviceName}" is missing command`); - const portConfig = parseObject4(input.service.port); - const envConfig = identity.envConfig; - const envFingerprint = identity.envFingerprint; - const serviceIdentityFingerprint = input.reuseKey ?? envFingerprint; - const explicitPort = identity.explicitPort; - const identityPort = identity.identityPort; - const port = asString12(portConfig.type, "") === "auto" ? await allocatePort() : explicitPort > 0 ? explicitPort : null; - const templateData = buildTemplateData({ - workspace: input.workspace, - agent: input.agent, - issue: input.issue, - adapterEnv: input.adapterEnv, - port - }); - const serviceCwd = port === identityPort ? identity.serviceCwd : resolveConfiguredPath(renderTemplate3(asString12(input.service.cwd, "."), templateData), input.workspace.cwd); - const env2 = { - ...sanitizeRuntimeServiceBaseEnv(process.env), - ...input.adapterEnv - }; - for (const [key, value] of Object.entries(renderRuntimeServiceEnv({ envConfig, templateData }))) { - env2[key] = value; - } - if (port) { - const portEnvKey = asString12(portConfig.envKey, "PORT"); - env2[portEnvKey] = String(port); - } - const expose = parseObject4(input.service.expose); - const readiness = parseObject4(input.service.readiness); - const urlTemplate = asString12(expose.urlTemplate, "") || asString12(readiness.urlTemplate, ""); - const url2 = urlTemplate ? renderTemplate3(urlTemplate, templateData) : null; - const stopPolicy = parseObject4(input.service.stopPolicy); - const serviceKey = createLocalServiceKey({ - profileKind: "workspace-runtime", - serviceName, - cwd: serviceCwd, - command, - envFingerprint: serviceIdentityFingerprint, - port: identityPort, - scope: { - scopeType: input.scopeType, - scopeId: input.scopeId, - executionWorkspaceId: input.executionWorkspaceId ?? null, - reuseKey: input.reuseKey - } - }); - const adoptedRecord = await findAdoptableLocalService({ - serviceKey, - command, - cwd: serviceCwd, - envFingerprint: serviceIdentityFingerprint, - port: identityPort - }); - if (adoptedRecord) { - return { - id: adoptedRecord.runtimeServiceId ?? randomUUID4(), - companyId: input.agent.companyId, - projectId: input.workspace.projectId, - projectWorkspaceId: input.workspace.workspaceId, - executionWorkspaceId: input.executionWorkspaceId ?? null, - issueId: input.issue?.id ?? null, - serviceName, - status: "running", - lifecycle, - scopeType: input.scopeType, - scopeId: input.scopeId, - reuseKey: input.reuseKey, - command, - cwd: serviceCwd, - port: adoptedRecord.port ?? port, - url: adoptedRecord.url ?? url2, - provider: "local_process", - providerRef: String(adoptedRecord.pid), - ownerAgentId: input.agent.id ?? null, - startedByRunId, - lastUsedAt: (/* @__PURE__ */ new Date()).toISOString(), - startedAt: adoptedRecord.startedAt, - stoppedAt: null, - stopPolicy, - healthStatus: "healthy", - reused: true, - db: input.db, - child: null, - leaseRunIds: leaseRunId ? /* @__PURE__ */ new Set([leaseRunId]) : /* @__PURE__ */ new Set(), - idleTimer: null, - envFingerprint, - serviceKey, - profileKind: "workspace-runtime", - processGroupId: adoptedRecord.processGroupId ?? null - }; - } - if (identityPort) { - const ownerPid = await readLocalServicePortOwner(identityPort); - if (ownerPid) { - throw new Error( - `Runtime service "${serviceName}" could not start because port ${identityPort} is already in use by pid ${ownerPid}` - ); - } - } - await ensureServerWorkspaceLinksCurrent(serviceCwd, { - onLog: input.onLog - }); - const shell = resolveShell(); - const child = spawn4(shell, ["-lc", command], { - cwd: serviceCwd, - env: env2, - detached: process.platform !== "win32", - stdio: ["ignore", "pipe", "pipe"] - }); - const spawnErrorPromise = new Promise((_, reject) => { - child.once("error", (err) => { - reject(err); - }); - }); - let stderrExcerpt = ""; - let stdoutExcerpt = ""; - child.stdout?.on("data", async (chunk) => { - const text3 = String(chunk); - stdoutExcerpt = (stdoutExcerpt + text3).slice(-4096); - if (input.onLog) await input.onLog("stdout", `[service:${serviceName}] ${text3}`); - }); - child.stderr?.on("data", async (chunk) => { - const text3 = String(chunk); - stderrExcerpt = (stderrExcerpt + text3).slice(-4096); - if (input.onLog) await input.onLog("stderr", `[service:${serviceName}] ${text3}`); - }); - try { - await Promise.race([ - waitForReadiness({ service: input.service, url: url2 }), - spawnErrorPromise - ]); - } catch (err) { - terminateChildProcess(child); - throw new Error( - `Failed to start runtime service "${serviceName}": ${err instanceof Error ? err.message : String(err)}${stderrExcerpt ? ` | stderr: ${stderrExcerpt.trim()}` : ""}` - ); - } - const record2 = { - id: randomUUID4(), - companyId: input.agent.companyId, - projectId: input.workspace.projectId, - projectWorkspaceId: input.workspace.workspaceId, - executionWorkspaceId: input.executionWorkspaceId ?? null, - issueId: input.issue?.id ?? null, - serviceName, - status: "running", - lifecycle, - scopeType: input.scopeType, - scopeId: input.scopeId, - reuseKey: input.reuseKey, - command, - cwd: serviceCwd, - port, - url: url2, - provider: "local_process", - providerRef: child.pid ? String(child.pid) : null, - ownerAgentId: input.agent.id ?? null, - startedByRunId, - lastUsedAt: (/* @__PURE__ */ new Date()).toISOString(), - startedAt: (/* @__PURE__ */ new Date()).toISOString(), - stoppedAt: null, - stopPolicy, - healthStatus: "healthy", - reused: false, - db: input.db, - child, - leaseRunIds: leaseRunId ? /* @__PURE__ */ new Set([leaseRunId]) : /* @__PURE__ */ new Set(), - idleTimer: null, - envFingerprint, - serviceKey, - profileKind: "workspace-runtime", - processGroupId: child.pid ?? null - }; - if (child.pid) { - await writeLocalServiceRegistryRecord({ - version: 1, - serviceKey, - profileKind: "workspace-runtime", - serviceName, - command, - cwd: serviceCwd, - envFingerprint: serviceIdentityFingerprint, - port, - url: url2, - pid: child.pid, - processGroupId: child.pid, - provider: "local_process", - runtimeServiceId: record2.id, - reuseKey: input.reuseKey, - startedAt: record2.startedAt, - lastSeenAt: record2.lastUsedAt, - metadata: { - projectId: record2.projectId, - projectWorkspaceId: record2.projectWorkspaceId, - executionWorkspaceId: record2.executionWorkspaceId, - issueId: record2.issueId, - scopeType: record2.scopeType, - scopeId: record2.scopeId - } - }); - } - return record2; -} -function scheduleIdleStop(record2) { - clearIdleTimer(record2); - const stopType = asString12(record2.stopPolicy?.type, "manual"); - if (stopType !== "idle_timeout") return; - const idleSeconds = Math.max(1, asNumber3(record2.stopPolicy?.idleSeconds, 1800)); - record2.idleTimer = setTimeout(() => { - stopRuntimeService(record2.id).catch(() => void 0); - }, idleSeconds * 1e3); -} -async function stopRuntimeService(serviceId) { - const record2 = runtimeServicesById.get(serviceId); - if (!record2) return; - clearIdleTimer(record2); - record2.status = "stopped"; - record2.healthStatus = "unknown"; - record2.lastUsedAt = (/* @__PURE__ */ new Date()).toISOString(); - record2.stoppedAt = (/* @__PURE__ */ new Date()).toISOString(); - runtimeServicesById.delete(serviceId); - if (record2.reuseKey && runtimeServicesByReuseKey.get(record2.reuseKey) === record2.id) { - runtimeServicesByReuseKey.delete(record2.reuseKey); - } - if (record2.child && record2.child.pid) { - await terminateLocalService({ - pid: record2.child.pid, - processGroupId: record2.processGroupId ?? record2.child.pid - }); - } else if (record2.providerRef) { - const pid = Number.parseInt(record2.providerRef, 10); - if (Number.isInteger(pid) && pid > 0) { - await terminateLocalService({ - pid, - processGroupId: record2.processGroupId - }); - } - } - await removeLocalServiceRegistryRecord(record2.serviceKey); - await persistRuntimeServiceRecord(record2.db, record2); -} -async function markPersistedRuntimeServicesStoppedForExecutionWorkspace(input) { - const now2 = /* @__PURE__ */ new Date(); - await input.db.update(workspaceRuntimeServices).set({ - status: "stopped", - healthStatus: "unknown", - stoppedAt: now2, - lastUsedAt: now2, - updatedAt: now2 - }).where( - and( - eq(workspaceRuntimeServices.executionWorkspaceId, input.executionWorkspaceId), - inArray(workspaceRuntimeServices.status, ["starting", "running"]) - ) - ); -} -function registerRuntimeService(db, record2) { - record2.db = db; - runtimeServicesById.set(record2.id, record2); - if (record2.reuseKey) { - runtimeServicesByReuseKey.set(record2.reuseKey, record2.id); - } - record2.child?.on("exit", (code, signal) => { - const current = runtimeServicesById.get(record2.id); - if (!current) return; - clearIdleTimer(current); - current.status = code === 0 || signal === "SIGTERM" ? "stopped" : "failed"; - current.healthStatus = current.status === "failed" ? "unhealthy" : "unknown"; - current.lastUsedAt = (/* @__PURE__ */ new Date()).toISOString(); - current.stoppedAt = (/* @__PURE__ */ new Date()).toISOString(); - runtimeServicesById.delete(current.id); - if (current.reuseKey && runtimeServicesByReuseKey.get(current.reuseKey) === current.id) { - runtimeServicesByReuseKey.delete(current.reuseKey); - } - void removeLocalServiceRegistryRecord(current.serviceKey); - void persistRuntimeServiceRecord(db, current); - }); -} -function readRuntimeServiceEntries(config3) { - return listWorkspaceServiceCommandDefinitions(parseObject4(config3.workspaceRuntime)).map((command) => command.rawConfig); -} -function listConfiguredRuntimeServiceEntries(config3) { - return readRuntimeServiceEntries(config3); -} -function readConfiguredServiceStates(config3) { - const raw = parseObject4(config3.serviceStates); - const states = {}; - for (const [key, value] of Object.entries(raw)) { - if (value === "running" || value === "stopped") { - states[key] = value; - } - } - return states; -} -function buildWorkspaceRuntimeDesiredStatePatch(input) { - const configuredServices = listConfiguredRuntimeServiceEntries(input.config); - const fallbackState = input.currentDesiredState === "running" ? "running" : "stopped"; - const nextServiceStates = {}; - for (let index2 = 0; index2 < configuredServices.length; index2 += 1) { - nextServiceStates[String(index2)] = input.currentServiceStates?.[String(index2)] ?? fallbackState; - } - const nextState = input.action === "stop" ? "stopped" : "running"; - if (input.serviceIndex === void 0 || input.serviceIndex === null) { - for (let index2 = 0; index2 < configuredServices.length; index2 += 1) { - nextServiceStates[String(index2)] = nextState; - } - } else if (input.serviceIndex >= 0 && input.serviceIndex < configuredServices.length) { - nextServiceStates[String(input.serviceIndex)] = nextState; - } - const desiredState = Object.values(nextServiceStates).some((state2) => state2 === "running") ? "running" : "stopped"; - return { - desiredState, - serviceStates: Object.keys(nextServiceStates).length > 0 ? nextServiceStates : null - }; -} -function selectRuntimeServiceEntries(input) { - const entries2 = listConfiguredRuntimeServiceEntries(input.config); - const states = input.serviceStates ?? readConfiguredServiceStates(input.config); - const fallbackState = input.defaultDesiredState === "running" ? "running" : "stopped"; - return entries2.filter((_, index2) => { - if (input.serviceIndex !== void 0 && input.serviceIndex !== null) { - return index2 === input.serviceIndex; - } - if (!input.respectDesiredStates) return true; - return (states[String(index2)] ?? fallbackState) === "running"; - }); -} -async function ensureRuntimeServicesForRun(input) { - const rawServices = readRuntimeServiceEntries(input.config); - const acquiredServiceIds = []; - const refs = []; - runtimeServiceLeasesByRun.set(input.runId, acquiredServiceIds); - try { - for (const service of rawServices) { - const { scopeType, scopeId } = resolveServiceScopeId({ - service, - workspace: input.workspace, - executionWorkspaceId: input.executionWorkspaceId, - issue: input.issue, - runId: input.runId, - agent: input.agent - }); - const reuseKey = resolveRuntimeServiceReuseIdentity({ - service, - workspace: input.workspace, - agent: input.agent, - issue: input.issue, - adapterEnv: input.adapterEnv, - scopeType, - scopeId - }).reuseKey; - if (reuseKey) { - const existingId = runtimeServicesByReuseKey.get(reuseKey); - const existing = existingId ? runtimeServicesById.get(existingId) : null; - if (existing && existing.status === "running") { - existing.leaseRunIds.add(input.runId); - existing.lastUsedAt = (/* @__PURE__ */ new Date()).toISOString(); - existing.stoppedAt = null; - clearIdleTimer(existing); - void touchLocalServiceRegistryRecord(existing.serviceKey, { - runtimeServiceId: existing.id, - lastSeenAt: existing.lastUsedAt - }); - await persistRuntimeServiceRecord(input.db, existing); - acquiredServiceIds.push(existing.id); - refs.push(toRuntimeServiceRef(existing, { reused: true })); - continue; - } - } - const record2 = await startLocalRuntimeService({ - db: input.db, - runId: input.runId, - agent: input.agent, - issue: input.issue, - workspace: input.workspace, - executionWorkspaceId: input.executionWorkspaceId, - adapterEnv: input.adapterEnv, - service, - onLog: input.onLog, - reuseKey, - scopeType, - scopeId - }); - registerRuntimeService(input.db, record2); - await persistRuntimeServiceRecord(input.db, record2); - acquiredServiceIds.push(record2.id); - refs.push(toRuntimeServiceRef(record2)); - } - } catch (err) { - await releaseRuntimeServicesForRun(input.runId); - throw err; - } - return refs; -} -async function startRuntimeServicesForWorkspaceControl(input) { - const rawServices = selectRuntimeServiceEntries({ - config: input.config, - serviceIndex: input.serviceIndex, - respectDesiredStates: input.respectDesiredStates, - defaultDesiredState: input.config.desiredState === "running" ? "running" : "stopped", - serviceStates: readConfiguredServiceStates(input.config) - }); - const refs = []; - const invocationId = input.invocationId ?? randomUUID4(); - for (const service of rawServices) { - const { scopeType, scopeId } = resolveServiceScopeId({ - service, - workspace: input.workspace, - executionWorkspaceId: input.executionWorkspaceId, - issue: input.issue, - runId: invocationId, - agent: input.actor - }); - const reuseKey = resolveRuntimeServiceReuseIdentity({ - service, - workspace: input.workspace, - agent: input.actor, - issue: input.issue, - adapterEnv: input.adapterEnv, - scopeType, - scopeId - }).reuseKey; - if (reuseKey) { - const existingId = runtimeServicesByReuseKey.get(reuseKey); - const existing = existingId ? runtimeServicesById.get(existingId) : null; - if (existing && existing.status === "running") { - existing.lastUsedAt = (/* @__PURE__ */ new Date()).toISOString(); - existing.stoppedAt = null; - clearIdleTimer(existing); - void touchLocalServiceRegistryRecord(existing.serviceKey, { - runtimeServiceId: existing.id, - lastSeenAt: existing.lastUsedAt - }); - await persistRuntimeServiceRecord(input.db, existing); - refs.push(toRuntimeServiceRef(existing, { reused: true })); - continue; - } - } - const record2 = await startLocalRuntimeService({ - db: input.db, - runId: invocationId, - leaseRunId: null, - startedByRunId: null, - agent: input.actor, - issue: input.issue, - workspace: input.workspace, - executionWorkspaceId: input.executionWorkspaceId, - adapterEnv: input.adapterEnv, - service, - onLog: input.onLog, - reuseKey, - scopeType, - scopeId - }); - registerRuntimeService(input.db, record2); - await persistRuntimeServiceRecord(input.db, record2); - refs.push(toRuntimeServiceRef(record2)); - } - return refs; -} -async function releaseRuntimeServicesForRun(runId) { - const acquired = runtimeServiceLeasesByRun.get(runId) ?? []; - runtimeServiceLeasesByRun.delete(runId); - for (const serviceId of acquired) { - const record2 = runtimeServicesById.get(serviceId); - if (!record2) continue; - record2.leaseRunIds.delete(runId); - record2.lastUsedAt = (/* @__PURE__ */ new Date()).toISOString(); - const stopType = asString12(record2.stopPolicy?.type, record2.lifecycle === "ephemeral" ? "on_run_finish" : "manual"); - await persistRuntimeServiceRecord(record2.db, record2); - if (record2.leaseRunIds.size === 0) { - if (record2.lifecycle === "ephemeral" || stopType === "on_run_finish") { - await stopRuntimeService(serviceId); - continue; - } - scheduleIdleStop(record2); - } - } -} -async function stopRuntimeServicesForExecutionWorkspace(input) { - const normalizedWorkspaceCwd = input.workspaceCwd ? path37.resolve(input.workspaceCwd) : null; - const matchingServiceIds = Array.from(runtimeServicesById.values()).filter((record2) => { - if (input.runtimeServiceId) return record2.id === input.runtimeServiceId; - if (record2.executionWorkspaceId === input.executionWorkspaceId) return true; - if (!normalizedWorkspaceCwd || !record2.cwd) return false; - const resolvedCwd = path37.resolve(record2.cwd); - return resolvedCwd === normalizedWorkspaceCwd || resolvedCwd.startsWith(`${normalizedWorkspaceCwd}${path37.sep}`); - }).map((record2) => record2.id); - for (const serviceId of matchingServiceIds) { - await stopRuntimeService(serviceId); - } - if (input.db) { - if (input.runtimeServiceId) { - const now2 = /* @__PURE__ */ new Date(); - await input.db.update(workspaceRuntimeServices).set({ - status: "stopped", - healthStatus: "unknown", - stoppedAt: now2, - lastUsedAt: now2, - updatedAt: now2 - }).where(eq(workspaceRuntimeServices.id, input.runtimeServiceId)); - } else { - await markPersistedRuntimeServicesStoppedForExecutionWorkspace({ - db: input.db, - executionWorkspaceId: input.executionWorkspaceId - }); - } - } -} -async function stopRuntimeServicesForProjectWorkspace(input) { - const matchingServiceIds = Array.from(runtimeServicesById.values()).filter((record2) => { - if (input.runtimeServiceId) return record2.id === input.runtimeServiceId; - return record2.projectWorkspaceId === input.projectWorkspaceId && record2.scopeType === "project_workspace"; - }).map((record2) => record2.id); - for (const serviceId of matchingServiceIds) { - await stopRuntimeService(serviceId); - } - if (input.db) { - const now2 = /* @__PURE__ */ new Date(); - await input.db.update(workspaceRuntimeServices).set({ - status: "stopped", - healthStatus: "unknown", - stoppedAt: now2, - lastUsedAt: now2, - updatedAt: now2 - }).where( - input.runtimeServiceId ? eq(workspaceRuntimeServices.id, input.runtimeServiceId) : and( - eq(workspaceRuntimeServices.projectWorkspaceId, input.projectWorkspaceId), - eq(workspaceRuntimeServices.scopeType, "project_workspace"), - inArray(workspaceRuntimeServices.status, ["starting", "running"]) - ) - ); - } -} -async function persistAdapterManagedRuntimeServices(input) { - const refs = normalizeAdapterManagedRuntimeServices(input); - if (refs.length === 0) return refs; - const existingRows = await input.db.select().from(workspaceRuntimeServices).where(inArray(workspaceRuntimeServices.id, refs.map((ref) => ref.id))); - const existingById = new Map(existingRows.map((row) => [row.id, row])); - for (const ref of refs) { - const existing = existingById.get(ref.id); - const startedAt = existing?.startedAt ?? new Date(ref.startedAt); - const createdAt = existing?.createdAt ?? /* @__PURE__ */ new Date(); - await input.db.insert(workspaceRuntimeServices).values({ - id: ref.id, - companyId: ref.companyId, - projectId: ref.projectId, - projectWorkspaceId: ref.projectWorkspaceId, - executionWorkspaceId: ref.executionWorkspaceId, - issueId: ref.issueId, - scopeType: ref.scopeType, - scopeId: ref.scopeId, - serviceName: ref.serviceName, - status: ref.status, - lifecycle: ref.lifecycle, - reuseKey: ref.reuseKey, - command: ref.command, - cwd: ref.cwd, - port: ref.port, - url: ref.url, - provider: ref.provider, - providerRef: ref.providerRef, - ownerAgentId: ref.ownerAgentId, - startedByRunId: ref.startedByRunId, - lastUsedAt: new Date(ref.lastUsedAt), - startedAt, - stoppedAt: ref.stoppedAt ? new Date(ref.stoppedAt) : null, - stopPolicy: ref.stopPolicy, - healthStatus: ref.healthStatus, - createdAt, - updatedAt: /* @__PURE__ */ new Date() - }).onConflictDoUpdate({ - target: workspaceRuntimeServices.id, - set: { - projectId: ref.projectId, - projectWorkspaceId: ref.projectWorkspaceId, - executionWorkspaceId: ref.executionWorkspaceId, - issueId: ref.issueId, - scopeType: ref.scopeType, - scopeId: ref.scopeId, - serviceName: ref.serviceName, - status: ref.status, - lifecycle: ref.lifecycle, - reuseKey: ref.reuseKey, - command: ref.command, - cwd: ref.cwd, - port: ref.port, - url: ref.url, - provider: ref.provider, - providerRef: ref.providerRef, - ownerAgentId: ref.ownerAgentId, - startedByRunId: ref.startedByRunId, - lastUsedAt: new Date(ref.lastUsedAt), - startedAt, - stoppedAt: ref.stoppedAt ? new Date(ref.stoppedAt) : null, - stopPolicy: ref.stopPolicy, - healthStatus: ref.healthStatus, - updatedAt: /* @__PURE__ */ new Date() - } - }); - } - return refs; -} -function buildWorkspaceReadyComment(input) { - const lines = ["## Workspace Ready", ""]; - lines.push(`- Strategy: \`${input.workspace.strategy}\``); - if (input.workspace.branchName) lines.push(`- Branch: \`${input.workspace.branchName}\``); - lines.push(`- CWD: \`${input.workspace.cwd}\``); - if (input.workspace.worktreePath && input.workspace.worktreePath !== input.workspace.cwd) { - lines.push(`- Worktree: \`${input.workspace.worktreePath}\``); - } - for (const service of input.runtimeServices) { - const detail = service.url ? `${service.serviceName}: ${service.url}` : `${service.serviceName}: running`; - const suffix = service.reused ? " (reused)" : ""; - lines.push(`- Service: ${detail}${suffix}`); - } - return lines.join("\n"); -} - -// server/src/services/workspace-operations.ts -init_src2(); -init_drizzle_orm(); -import { randomUUID as randomUUID5 } from "node:crypto"; - -// server/src/services/workspace-operation-log-store.ts -import { createReadStream as createReadStream2, promises as fs31 } from "node:fs"; -import path38 from "node:path"; -import { createHash as createHash13 } from "node:crypto"; -function safeSegments2(...segments) { - return segments.map((segment) => segment.replace(/[^a-zA-Z0-9._-]/g, "_")); -} -function resolveWithin2(basePath, relativePath) { - const resolved = path38.resolve(basePath, relativePath); - const base = path38.resolve(basePath) + path38.sep; - if (!resolved.startsWith(base) && resolved !== path38.resolve(basePath)) { - throw new Error("Invalid log path"); - } - return resolved; -} -function createLocalFileWorkspaceOperationLogStore(basePath) { - async function ensureDir(relativeDir) { - const dir = resolveWithin2(basePath, relativeDir); - await fs31.mkdir(dir, { recursive: true }); - } - async function readFileRange(filePath, offset, limitBytes) { - const stat5 = await fs31.stat(filePath).catch(() => null); - if (!stat5) throw notFound("Workspace operation log not found"); - const start = Math.max(0, Math.min(offset, stat5.size)); - const end = Math.max(start, Math.min(start + limitBytes - 1, stat5.size - 1)); - if (start > end) { - return { content: "", nextOffset: start }; - } - const chunks = []; - await new Promise((resolve4, reject) => { - const stream = createReadStream2(filePath, { start, end }); - stream.on("data", (chunk) => { - chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)); - }); - stream.on("error", reject); - stream.on("end", () => resolve4()); - }); - const content = Buffer.concat(chunks).toString("utf8"); - const nextOffset = end + 1 < stat5.size ? end + 1 : void 0; - return { content, nextOffset }; - } - async function sha256File(filePath) { - return new Promise((resolve4, reject) => { - const hash2 = createHash13("sha256"); - const stream = createReadStream2(filePath); - stream.on("data", (chunk) => hash2.update(chunk)); - stream.on("error", reject); - stream.on("end", () => resolve4(hash2.digest("hex"))); - }); - } - return { - async begin(input) { - const [companyId] = safeSegments2(input.companyId); - const operationId = safeSegments2(input.operationId)[0]; - const relDir = companyId; - const relPath = path38.join(relDir, `${operationId}.ndjson`); - await ensureDir(relDir); - const absPath = resolveWithin2(basePath, relPath); - await fs31.writeFile(absPath, "", "utf8"); - return { store: "local_file", logRef: relPath }; - }, - async append(handle, event) { - if (handle.store !== "local_file") return; - const absPath = resolveWithin2(basePath, handle.logRef); - const line3 = JSON.stringify({ - ts: event.ts, - stream: event.stream, - chunk: event.chunk - }); - await fs31.appendFile(absPath, `${line3} -`, "utf8"); - }, - async finalize(handle) { - if (handle.store !== "local_file") { - return { bytes: 0, compressed: false }; - } - const absPath = resolveWithin2(basePath, handle.logRef); - const stat5 = await fs31.stat(absPath).catch(() => null); - if (!stat5) throw notFound("Workspace operation log not found"); - const hash2 = await sha256File(absPath); - return { - bytes: stat5.size, - sha256: hash2, - compressed: false - }; - }, - async read(handle, opts) { - if (handle.store !== "local_file") { - throw notFound("Workspace operation log not found"); - } - const absPath = resolveWithin2(basePath, handle.logRef); - const offset = opts?.offset ?? 0; - const limitBytes = opts?.limitBytes ?? 256e3; - return readFileRange(absPath, offset, limitBytes); - } - }; -} -var cachedStore2 = null; -function getWorkspaceOperationLogStore() { - if (cachedStore2) return cachedStore2; - const basePath = process.env.WORKSPACE_OPERATION_LOG_BASE_PATH ?? path38.resolve(resolveTaskcoreInstanceRoot(), "data", "workspace-operation-logs"); - cachedStore2 = createLocalFileWorkspaceOperationLogStore(basePath); - return cachedStore2; -} - -// server/src/services/workspace-operations.ts -function toWorkspaceOperation(row) { - return { - id: row.id, - companyId: row.companyId, - executionWorkspaceId: row.executionWorkspaceId ?? null, - heartbeatRunId: row.heartbeatRunId ?? null, - phase: row.phase, - command: row.command ?? null, - cwd: row.cwd ?? null, - status: row.status, - exitCode: row.exitCode ?? null, - logStore: row.logStore ?? null, - logRef: row.logRef ?? null, - logBytes: row.logBytes ?? null, - logSha256: row.logSha256 ?? null, - logCompressed: row.logCompressed, - stdoutExcerpt: row.stdoutExcerpt ?? null, - stderrExcerpt: row.stderrExcerpt ?? null, - metadata: row.metadata ?? null, - startedAt: row.startedAt, - finishedAt: row.finishedAt ?? null, - createdAt: row.createdAt, - updatedAt: row.updatedAt - }; -} -function appendExcerpt(current, chunk) { - return `${current}${chunk}`.slice(-4096); -} -function combineMetadata(base, patch) { - if (!base && !patch) return null; - return { - ...base ?? {}, - ...patch ?? {} - }; -} -function workspaceOperationService(db) { - const instanceSettings2 = instanceSettingsService(db); - const logStore = getWorkspaceOperationLogStore(); - async function getById(id) { - const row = await db.select().from(workspaceOperations).where(eq(workspaceOperations.id, id)).then((rows) => rows[0] ?? null); - return row ? toWorkspaceOperation(row) : null; - } - return { - getById, - createRecorder(input) { - let executionWorkspaceId = input.executionWorkspaceId ?? null; - const createdIds = []; - return { - async attachExecutionWorkspaceId(nextExecutionWorkspaceId) { - executionWorkspaceId = nextExecutionWorkspaceId ?? null; - if (!executionWorkspaceId || createdIds.length === 0) return; - await db.update(workspaceOperations).set({ - executionWorkspaceId, - updatedAt: /* @__PURE__ */ new Date() - }).where(inArray(workspaceOperations.id, createdIds)); - }, - async recordOperation(recordInput) { - const currentUserRedactionOptions = { - enabled: (await instanceSettings2.getGeneral()).censorUsernameInLogs - }; - const startedAt = /* @__PURE__ */ new Date(); - const id = randomUUID5(); - const handle = await logStore.begin({ - companyId: input.companyId, - operationId: id - }); - let stdoutExcerpt = ""; - let stderrExcerpt = ""; - const append = async (stream, chunk) => { - if (!chunk) return; - const sanitizedChunk = redactCurrentUserText(chunk, currentUserRedactionOptions); - if (stream === "stdout") stdoutExcerpt = appendExcerpt(stdoutExcerpt, sanitizedChunk); - if (stream === "stderr") stderrExcerpt = appendExcerpt(stderrExcerpt, sanitizedChunk); - await logStore.append(handle, { - stream, - chunk: sanitizedChunk, - ts: (/* @__PURE__ */ new Date()).toISOString() - }); - }; - await db.insert(workspaceOperations).values({ - id, - companyId: input.companyId, - executionWorkspaceId, - heartbeatRunId: input.heartbeatRunId ?? null, - phase: recordInput.phase, - command: recordInput.command ?? null, - cwd: recordInput.cwd ?? null, - status: "running", - logStore: handle.store, - logRef: handle.logRef, - metadata: redactCurrentUserValue( - recordInput.metadata ?? null, - currentUserRedactionOptions - ), - startedAt - }); - createdIds.push(id); - try { - const result = await recordInput.run(); - await append("system", result.system ?? null); - await append("stdout", result.stdout ?? null); - await append("stderr", result.stderr ?? null); - const finalized = await logStore.finalize(handle); - const finishedAt = /* @__PURE__ */ new Date(); - const row = await db.update(workspaceOperations).set({ - executionWorkspaceId, - status: result.status ?? "succeeded", - exitCode: result.exitCode ?? null, - stdoutExcerpt: stdoutExcerpt || null, - stderrExcerpt: stderrExcerpt || null, - logBytes: finalized.bytes, - logSha256: finalized.sha256, - logCompressed: finalized.compressed, - metadata: redactCurrentUserValue( - combineMetadata(recordInput.metadata, result.metadata), - currentUserRedactionOptions - ), - finishedAt, - updatedAt: finishedAt - }).where(eq(workspaceOperations.id, id)).returning().then((rows) => rows[0] ?? null); - if (!row) throw notFound("Workspace operation not found"); - return toWorkspaceOperation(row); - } catch (error50) { - await append("stderr", error50 instanceof Error ? error50.message : String(error50)); - const finalized = await logStore.finalize(handle).catch(() => null); - const finishedAt = /* @__PURE__ */ new Date(); - await db.update(workspaceOperations).set({ - executionWorkspaceId, - status: "failed", - stdoutExcerpt: stdoutExcerpt || null, - stderrExcerpt: stderrExcerpt || null, - logBytes: finalized?.bytes ?? null, - logSha256: finalized?.sha256 ?? null, - logCompressed: finalized?.compressed ?? false, - finishedAt, - updatedAt: finishedAt - }).where(eq(workspaceOperations.id, id)); - throw error50; - } - } - }; - }, - listForRun: async (runId, executionWorkspaceId) => { - const conditions = [eq(workspaceOperations.heartbeatRunId, runId)]; - if (executionWorkspaceId) { - const cleanupCondition = and( - eq(workspaceOperations.executionWorkspaceId, executionWorkspaceId), - isNull(workspaceOperations.heartbeatRunId) - ); - if (cleanupCondition) conditions.push(cleanupCondition); - } - const rows = await db.select().from(workspaceOperations).where(conditions.length === 1 ? conditions[0] : or(...conditions)).orderBy(asc(workspaceOperations.startedAt), asc(workspaceOperations.createdAt), asc(workspaceOperations.id)); - return rows.map(toWorkspaceOperation); - }, - listForExecutionWorkspace: async (executionWorkspaceId) => { - const rows = await db.select().from(workspaceOperations).where(eq(workspaceOperations.executionWorkspaceId, executionWorkspaceId)).orderBy(desc(workspaceOperations.startedAt), desc(workspaceOperations.createdAt)); - return rows.map(toWorkspaceOperation); - }, - readLog: async (operationId, opts) => { - const operation2 = await getById(operationId); - if (!operation2) throw notFound("Workspace operation not found"); - if (!operation2.logStore || !operation2.logRef) throw notFound("Workspace operation log not found"); - const result = await logStore.read( - { - store: operation2.logStore, - logRef: operation2.logRef - }, - opts - ); - return { - operationId, - store: operation2.logStore, - logRef: operation2.logRef, - ...result, - content: redactCurrentUserText(result.content, { - enabled: (await instanceSettings2.getGeneral()).censorUsernameInLogs - }) - }; - } - }; -} - -// server/src/services/heartbeat.ts -var MAX_LIVE_LOG_CHUNK_BYTES = 8 * 1024; -var MAX_PERSISTED_LOG_CHUNK_CHARS = 64 * 1024; -var HEARTBEAT_MAX_CONCURRENT_RUNS_DEFAULT = 1; -var HEARTBEAT_MAX_CONCURRENT_RUNS_MAX = 10; -var DEFERRED_WAKE_CONTEXT_KEY = "_taskcoreWakeContext"; -var WAKE_COMMENT_IDS_KEY = "wakeCommentIds"; -var TASKCORE_WAKE_PAYLOAD_KEY = "taskcoreWake"; -var TASKCORE_HARNESS_CHECKOUT_KEY = "taskcoreHarnessCheckedOut"; -var DETACHED_PROCESS_ERROR_CODE = "process_detached"; -var startLocksByAgent = /* @__PURE__ */ new Map(); -var REPO_ONLY_CWD_SENTINEL2 = "/__taskcore_repo_only__"; -var MANAGED_WORKSPACE_GIT_CLONE_TIMEOUT_MS = 10 * 60 * 1e3; -var MAX_INLINE_WAKE_COMMENTS = 8; -var MAX_INLINE_WAKE_COMMENT_BODY_CHARS = 4e3; -var MAX_INLINE_WAKE_COMMENT_BODY_TOTAL_CHARS = 12e3; -var execFile5 = promisify5(execFileCallback); -var ACTIVE_HEARTBEAT_RUN_STATUSES = ["queued", "running"]; -var SESSIONED_LOCAL_ADAPTERS = /* @__PURE__ */ new Set([ - "claude_local", - "codex_local", - "cursor", - "gemini_local", - "opencode_local", - "pi_local" -]); -var INLINE_BASE64_IMAGE_DATA_RE = /("type":"image","source":\{"type":"base64","data":")([A-Za-z0-9+/=]{1024,})(")/g; -async function resolveExecutionRunAdapterConfig(input) { - const { config: resolvedConfig, secretKeys } = await input.secretsSvc.resolveAdapterConfigForRuntime( - input.companyId, - input.executionRunConfig - ); - const projectEnvResolution = input.projectEnv ? await input.secretsSvc.resolveEnvBindings(input.companyId, input.projectEnv) : { env: {}, secretKeys: /* @__PURE__ */ new Set() }; - if (Object.keys(projectEnvResolution.env).length > 0) { - resolvedConfig.env = { - ...parseObject4(resolvedConfig.env), - ...projectEnvResolution.env - }; - for (const key of projectEnvResolution.secretKeys) { - secretKeys.add(key); - } - } - return { resolvedConfig, secretKeys }; -} -function extractMentionedSkillIdsFromSources(sources) { - const mentionedIds = /* @__PURE__ */ new Set(); - for (const source of sources) { - if (typeof source !== "string" || source.length === 0) continue; - for (const skillId of extractSkillMentionIds(source)) { - mentionedIds.add(skillId); - } - } - return [...mentionedIds]; -} -function applyRunScopedMentionedSkillKeys(config3, skillKeys) { - const normalizedSkillKeys = Array.from( - new Set( - skillKeys.map((value) => value.trim()).filter(Boolean) - ) - ); - if (normalizedSkillKeys.length === 0) return config3; - const existingPreference = readTaskcoreSkillSyncPreference(config3); - return writeTaskcoreSkillSyncPreference(config3, [ - ...existingPreference.desiredSkills, - ...normalizedSkillKeys - ]); -} -async function resolveRunScopedMentionedSkillKeys(input) { - if (!input.issueId) return []; - const issue2 = await input.db.select({ - title: issues.title, - description: issues.description - }).from(issues).where(and(eq(issues.id, input.issueId), eq(issues.companyId, input.companyId))).then((rows) => rows[0] ?? null); - if (!issue2) return []; - const comments = await input.db.select({ body: issueComments.body }).from(issueComments).where( - and( - eq(issueComments.issueId, input.issueId), - eq(issueComments.companyId, input.companyId) - ) - ); - const mentionedSkillIds = extractMentionedSkillIdsFromSources([ - issue2.title, - issue2.description ?? "", - ...comments.map((comment) => comment.body) - ]); - if (mentionedSkillIds.length === 0) return []; - const skillRows = await input.db.select({ - id: companySkills.id, - key: companySkills.key - }).from(companySkills).where( - and( - eq(companySkills.companyId, input.companyId), - inArray(companySkills.id, mentionedSkillIds) - ) - ); - const skillKeyById = new Map(skillRows.map((row) => [row.id, row.key])); - return mentionedSkillIds.map((skillId) => skillKeyById.get(skillId) ?? null).filter((skillKey) => Boolean(skillKey)); -} -function applyPersistedExecutionWorkspaceConfig(input) { - const nextConfig = { ...input.config }; - if (input.mode !== "agent_default") { - if (input.workspaceConfig?.workspaceRuntime === null) { - delete nextConfig.workspaceRuntime; - } else if (input.workspaceConfig?.workspaceRuntime) { - nextConfig.workspaceRuntime = { ...input.workspaceConfig.workspaceRuntime }; - } - } - if (input.workspaceConfig && input.mode === "isolated_workspace") { - const nextStrategy = parseObject4(nextConfig.workspaceStrategy); - if (input.workspaceConfig.provisionCommand === null) delete nextStrategy.provisionCommand; - else nextStrategy.provisionCommand = input.workspaceConfig.provisionCommand; - if (input.workspaceConfig.teardownCommand === null) delete nextStrategy.teardownCommand; - else nextStrategy.teardownCommand = input.workspaceConfig.teardownCommand; - nextConfig.workspaceStrategy = nextStrategy; - } - return nextConfig; -} -function stripWorkspaceRuntimeFromExecutionRunConfig(config3) { - const nextConfig = { ...config3 }; - delete nextConfig.workspaceRuntime; - return nextConfig; -} -function buildRealizedExecutionWorkspaceFromPersisted(input) { - const cwd = readNonEmptyString10(input.workspace.cwd) ?? readNonEmptyString10(input.workspace.providerRef); - if (!cwd) { - return null; - } - const strategy = input.workspace.strategyType === "git_worktree" ? "git_worktree" : "project_primary"; - return { - baseCwd: input.base.baseCwd, - source: input.workspace.mode === "shared_workspace" ? "project_primary" : "task_session", - projectId: input.workspace.projectId ?? input.base.projectId, - workspaceId: input.workspace.projectWorkspaceId ?? input.base.workspaceId, - repoUrl: input.workspace.repoUrl ?? input.base.repoUrl, - repoRef: input.workspace.baseRef ?? input.base.repoRef, - strategy, - cwd, - branchName: input.workspace.branchName ?? null, - worktreePath: strategy === "git_worktree" ? readNonEmptyString10(input.workspace.providerRef) ?? cwd : null, - warnings: [], - created: false - }; -} -function buildExecutionWorkspaceConfigSnapshot(config3) { - const strategy = parseObject4(config3.workspaceStrategy); - const snapshot = {}; - if ("workspaceStrategy" in config3) { - snapshot.provisionCommand = typeof strategy.provisionCommand === "string" ? strategy.provisionCommand : null; - snapshot.teardownCommand = typeof strategy.teardownCommand === "string" ? strategy.teardownCommand : null; - } - if ("workspaceRuntime" in config3) { - const workspaceRuntime = parseObject4(config3.workspaceRuntime); - snapshot.workspaceRuntime = Object.keys(workspaceRuntime).length > 0 ? workspaceRuntime : null; - } - const hasSnapshot = Object.values(snapshot).some((value) => { - if (value === null) return false; - if (typeof value === "object") return Object.keys(value).length > 0; - return true; - }); - return hasSnapshot ? snapshot : null; -} -function deriveRepoNameFromRepoUrl2(repoUrl) { - const trimmed = repoUrl?.trim() ?? ""; - if (!trimmed) return null; - try { - const parsed = new URL(trimmed); - const cleanedPath = parsed.pathname.replace(/\/+$/, ""); - const repoName = cleanedPath.split("/").filter(Boolean).pop()?.replace(/\.git$/i, "") ?? ""; - return repoName || null; - } catch { - return null; - } -} -async function ensureManagedProjectWorkspace(input) { - const cwd = resolveManagedProjectWorkspaceDir({ - companyId: input.companyId, - projectId: input.projectId, - repoName: deriveRepoNameFromRepoUrl2(input.repoUrl) - }); - await fs32.mkdir(path39.dirname(cwd), { recursive: true }); - const stats = await fs32.stat(cwd).catch(() => null); - if (!input.repoUrl) { - if (!stats) { - await fs32.mkdir(cwd, { recursive: true }); - } - return { cwd, warning: null }; - } - const gitDirExists = await fs32.stat(path39.resolve(cwd, ".git")).then((entry) => entry.isDirectory()).catch(() => false); - if (gitDirExists) { - return { cwd, warning: null }; - } - if (stats) { - const entries2 = await fs32.readdir(cwd).catch(() => []); - if (entries2.length > 0) { - return { - cwd, - warning: `Managed workspace path "${cwd}" already exists but is not a git checkout. Using it as-is.` - }; - } - await fs32.rm(cwd, { recursive: true, force: true }); - } - try { - await execFile5("git", ["clone", input.repoUrl, cwd], { - env: sanitizeRuntimeServiceBaseEnv(process.env), - timeout: MANAGED_WORKSPACE_GIT_CLONE_TIMEOUT_MS - }); - return { cwd, warning: null }; - } catch (error50) { - const reason = error50 instanceof Error ? error50.message : String(error50); - throw new Error(`Failed to prepare managed checkout for "${input.repoUrl}" at "${cwd}": ${reason}`); - } -} -var heartbeatRunProcessGroupIdColumn = heartbeatRuns.processGroupId ?? sql`NULL`.as("processGroupId"); -var heartbeatRunListColumns = { - id: heartbeatRuns.id, - companyId: heartbeatRuns.companyId, - agentId: heartbeatRuns.agentId, - invocationSource: heartbeatRuns.invocationSource, - triggerDetail: heartbeatRuns.triggerDetail, - status: heartbeatRuns.status, - startedAt: heartbeatRuns.startedAt, - finishedAt: heartbeatRuns.finishedAt, - error: heartbeatRuns.error, - wakeupRequestId: heartbeatRuns.wakeupRequestId, - exitCode: heartbeatRuns.exitCode, - signal: heartbeatRuns.signal, - usageJson: heartbeatRuns.usageJson, - resultJson: heartbeatRuns.resultJson, - sessionIdBefore: heartbeatRuns.sessionIdBefore, - sessionIdAfter: heartbeatRuns.sessionIdAfter, - logStore: heartbeatRuns.logStore, - logRef: heartbeatRuns.logRef, - logBytes: heartbeatRuns.logBytes, - logSha256: heartbeatRuns.logSha256, - logCompressed: heartbeatRuns.logCompressed, - stdoutExcerpt: sql`NULL`.as("stdoutExcerpt"), - stderrExcerpt: sql`NULL`.as("stderrExcerpt"), - errorCode: heartbeatRuns.errorCode, - externalRunId: heartbeatRuns.externalRunId, - processPid: heartbeatRuns.processPid, - processGroupId: heartbeatRunProcessGroupIdColumn, - processStartedAt: heartbeatRuns.processStartedAt, - retryOfRunId: heartbeatRuns.retryOfRunId, - processLossRetryCount: heartbeatRuns.processLossRetryCount, - contextSnapshot: heartbeatRuns.contextSnapshot, - createdAt: heartbeatRuns.createdAt, - updatedAt: heartbeatRuns.updatedAt -}; -var heartbeatRunIssueSummaryColumns = { - id: heartbeatRuns.id, - status: heartbeatRuns.status, - invocationSource: heartbeatRuns.invocationSource, - triggerDetail: heartbeatRuns.triggerDetail, - startedAt: heartbeatRuns.startedAt, - finishedAt: heartbeatRuns.finishedAt, - createdAt: heartbeatRuns.createdAt, - agentId: heartbeatRuns.agentId, - issueId: sql`${heartbeatRuns.contextSnapshot} ->> 'issueId'`.as("issueId") -}; -function appendExcerpt2(prev, chunk) { - return appendWithCap3(prev, chunk, MAX_EXCERPT_BYTES3); -} -function redactInlineBase64ImageData(chunk) { - return chunk.replace( - INLINE_BASE64_IMAGE_DATA_RE, - (_match, prefix, data2, suffix) => `${prefix}[omitted base64 image data: ${data2.length} chars]${suffix}` - ); -} -function compactRunLogChunk(chunk, maxChars = MAX_PERSISTED_LOG_CHUNK_CHARS) { - const normalized = redactInlineBase64ImageData(chunk); - if (normalized.length <= maxChars) return normalized; - const headChars = Math.max(0, Math.floor(maxChars * 0.6)); - const tailChars = Math.max(0, Math.floor(maxChars * 0.25)); - const omittedChars = Math.max(0, normalized.length - headChars - tailChars); - const marker = ` -[taskcore truncated run log chunk: omitted ${omittedChars} chars] -`; - return `${normalized.slice(0, headChars)}${marker}${normalized.slice(normalized.length - tailChars)}`; -} -function normalizeMaxConcurrentRuns(value) { - const parsed = Math.floor(asNumber3(value, HEARTBEAT_MAX_CONCURRENT_RUNS_DEFAULT)); - if (!Number.isFinite(parsed)) return HEARTBEAT_MAX_CONCURRENT_RUNS_DEFAULT; - return Math.max(HEARTBEAT_MAX_CONCURRENT_RUNS_DEFAULT, Math.min(HEARTBEAT_MAX_CONCURRENT_RUNS_MAX, parsed)); -} -async function withAgentStartLock(agentId, fn) { - const previous = startLocksByAgent.get(agentId) ?? Promise.resolve(); - const run = previous.then(fn); - const marker = run.then( - () => void 0, - () => void 0 - ); - startLocksByAgent.set(agentId, marker); - try { - return await run; - } finally { - if (startLocksByAgent.get(agentId) === marker) { - startLocksByAgent.delete(agentId); - } - } -} -function prioritizeProjectWorkspaceCandidatesForRun(rows, preferredWorkspaceId) { - if (!preferredWorkspaceId) return rows; - const preferredIndex = rows.findIndex((row) => row.id === preferredWorkspaceId); - if (preferredIndex <= 0) return rows; - return [rows[preferredIndex], ...rows.slice(0, preferredIndex), ...rows.slice(preferredIndex + 1)]; -} -function readNonEmptyString10(value) { - return typeof value === "string" && value.trim().length > 0 ? value : null; -} -function normalizeLedgerBillingType(value) { - const raw = readNonEmptyString10(value); - switch (raw) { - case "api": - case "metered_api": - return "metered_api"; - case "subscription": - case "subscription_included": - return "subscription_included"; - case "subscription_overage": - return "subscription_overage"; - case "credits": - return "credits"; - case "fixed": - return "fixed"; - default: - return "unknown"; - } -} -function resolveLedgerBiller(result) { - return readNonEmptyString10(result.biller) ?? readNonEmptyString10(result.provider) ?? "unknown"; -} -function normalizeBilledCostCents(costUsd, billingType) { - if (billingType === "subscription_included") return 0; - if (typeof costUsd !== "number" || !Number.isFinite(costUsd)) return 0; - return Math.max(0, Math.round(costUsd * 100)); -} -async function resolveLedgerScopeForRun(db, companyId, run) { - const context = parseObject4(run.contextSnapshot); - const contextIssueId = readNonEmptyString10(context.issueId); - const contextProjectId = readNonEmptyString10(context.projectId); - if (!contextIssueId) { - return { - issueId: null, - projectId: contextProjectId - }; - } - const issue2 = await db.select({ - id: issues.id, - projectId: issues.projectId - }).from(issues).where(and(eq(issues.id, contextIssueId), eq(issues.companyId, companyId))).then((rows) => rows[0] ?? null); - return { - issueId: issue2?.id ?? null, - projectId: issue2?.projectId ?? contextProjectId - }; -} -function buildExplicitResumeSessionOverride(input) { - const desiredDisplayId = truncateDisplayId( - input.resumeRunSessionIdAfter ?? input.resumeRunSessionIdBefore - ); - const taskSessionParams = normalizeSessionParams( - input.sessionCodec.deserialize(input.taskSession?.sessionParamsJson ?? null) - ); - const taskSessionDisplayId = truncateDisplayId( - input.taskSession?.sessionDisplayId ?? (input.sessionCodec.getDisplayId ? input.sessionCodec.getDisplayId(taskSessionParams) : null) ?? readNonEmptyString10(taskSessionParams?.sessionId) - ); - const canReuseTaskSessionParams = input.taskSession != null && (input.taskSession.lastRunId === input.resumeFromRunId || !!desiredDisplayId && taskSessionDisplayId === desiredDisplayId); - const sessionParams = canReuseTaskSessionParams ? taskSessionParams : desiredDisplayId ? { sessionId: desiredDisplayId } : null; - const sessionDisplayId = desiredDisplayId ?? (canReuseTaskSessionParams ? taskSessionDisplayId : null); - if (!sessionDisplayId && !sessionParams) return null; - return { - sessionDisplayId, - sessionParams - }; -} -function normalizeUsageTotals(usage) { - if (!usage) return null; - return { - inputTokens: Math.max(0, Math.floor(asNumber3(usage.inputTokens, 0))), - cachedInputTokens: Math.max(0, Math.floor(asNumber3(usage.cachedInputTokens, 0))), - outputTokens: Math.max(0, Math.floor(asNumber3(usage.outputTokens, 0))) - }; -} -function readRawUsageTotals(usageJson) { - const parsed = parseObject4(usageJson); - if (Object.keys(parsed).length === 0) return null; - const inputTokens = Math.max( - 0, - Math.floor(asNumber3(parsed.rawInputTokens, asNumber3(parsed.inputTokens, 0))) - ); - const cachedInputTokens = Math.max( - 0, - Math.floor(asNumber3(parsed.rawCachedInputTokens, asNumber3(parsed.cachedInputTokens, 0))) - ); - const outputTokens = Math.max( - 0, - Math.floor(asNumber3(parsed.rawOutputTokens, asNumber3(parsed.outputTokens, 0))) - ); - if (inputTokens <= 0 && cachedInputTokens <= 0 && outputTokens <= 0) { - return null; - } - return { - inputTokens, - cachedInputTokens, - outputTokens - }; -} -function deriveNormalizedUsageDelta(current, previous) { - if (!current) return null; - if (!previous) return { ...current }; - const inputTokens = current.inputTokens >= previous.inputTokens ? current.inputTokens - previous.inputTokens : current.inputTokens; - const cachedInputTokens = current.cachedInputTokens >= previous.cachedInputTokens ? current.cachedInputTokens - previous.cachedInputTokens : current.cachedInputTokens; - const outputTokens = current.outputTokens >= previous.outputTokens ? current.outputTokens - previous.outputTokens : current.outputTokens; - return { - inputTokens: Math.max(0, inputTokens), - cachedInputTokens: Math.max(0, cachedInputTokens), - outputTokens: Math.max(0, outputTokens) - }; -} -function formatCount(value) { - if (typeof value !== "number" || !Number.isFinite(value)) return "0"; - return value.toLocaleString("en-US"); -} -function parseSessionCompactionPolicy(agent) { - return resolveSessionCompactionPolicy(agent.adapterType, agent.runtimeConfig).policy; -} -function resolveRuntimeSessionParamsForWorkspace(input) { - const { agentId, previousSessionParams, resolvedWorkspace } = input; - const previousSessionId = readNonEmptyString10(previousSessionParams?.sessionId); - const previousCwd = readNonEmptyString10(previousSessionParams?.cwd); - if (!previousSessionId || !previousCwd) { - return { - sessionParams: previousSessionParams, - warning: null - }; - } - if (resolvedWorkspace.source !== "project_primary") { - return { - sessionParams: previousSessionParams, - warning: null - }; - } - const projectCwd = readNonEmptyString10(resolvedWorkspace.cwd); - if (!projectCwd) { - return { - sessionParams: previousSessionParams, - warning: null - }; - } - const fallbackAgentHomeCwd = resolveDefaultAgentWorkspaceDir(agentId); - if (path39.resolve(previousCwd) !== path39.resolve(fallbackAgentHomeCwd)) { - return { - sessionParams: previousSessionParams, - warning: null - }; - } - if (path39.resolve(projectCwd) === path39.resolve(previousCwd)) { - return { - sessionParams: previousSessionParams, - warning: null - }; - } - const previousWorkspaceId = readNonEmptyString10(previousSessionParams?.workspaceId); - if (previousWorkspaceId && resolvedWorkspace.workspaceId && previousWorkspaceId !== resolvedWorkspace.workspaceId) { - return { - sessionParams: previousSessionParams, - warning: null - }; - } - const migratedSessionParams = { - ...previousSessionParams ?? {}, - cwd: projectCwd - }; - if (resolvedWorkspace.workspaceId) migratedSessionParams.workspaceId = resolvedWorkspace.workspaceId; - if (resolvedWorkspace.repoUrl) migratedSessionParams.repoUrl = resolvedWorkspace.repoUrl; - if (resolvedWorkspace.repoRef) migratedSessionParams.repoRef = resolvedWorkspace.repoRef; - return { - sessionParams: migratedSessionParams, - warning: `Project workspace "${projectCwd}" is now available. Attempting to resume session "${previousSessionId}" that was previously saved in fallback workspace "${previousCwd}".` - }; -} -function parseIssueAssigneeAdapterOverrides(raw) { - const parsed = parseObject4(raw); - const parsedAdapterConfig = parseObject4(parsed.adapterConfig); - const adapterConfig = Object.keys(parsedAdapterConfig).length > 0 ? parsedAdapterConfig : null; - const useProjectWorkspace = typeof parsed.useProjectWorkspace === "boolean" ? parsed.useProjectWorkspace : null; - if (!adapterConfig && useProjectWorkspace === null) return null; - return { - adapterConfig, - useProjectWorkspace - }; -} -var HEARTBEAT_TASK_KEY = "__heartbeat__"; -function deriveTaskKey(contextSnapshot, payload2) { - return readNonEmptyString10(contextSnapshot?.taskKey) ?? readNonEmptyString10(contextSnapshot?.taskId) ?? readNonEmptyString10(contextSnapshot?.issueId) ?? readNonEmptyString10(payload2?.taskKey) ?? readNonEmptyString10(payload2?.taskId) ?? readNonEmptyString10(payload2?.issueId) ?? null; -} -function deriveTaskKeyWithHeartbeatFallback(contextSnapshot, payload2) { - const explicit = deriveTaskKey(contextSnapshot, payload2); - if (explicit) return explicit; - const wakeSource = readNonEmptyString10(contextSnapshot?.wakeSource); - if (wakeSource === "timer") return HEARTBEAT_TASK_KEY; - return null; -} -function shouldResetTaskSessionForWake(contextSnapshot) { - if (contextSnapshot?.forceFreshSession === true) return true; - const wakeReason = readNonEmptyString10(contextSnapshot?.wakeReason); - if (wakeReason === "issue_assigned" || wakeReason === "execution_review_requested" || wakeReason === "execution_approval_requested" || wakeReason === "execution_changes_requested") { - return true; - } - return false; -} -function shouldRequireIssueCommentForWake(contextSnapshot) { - const wakeReason = readNonEmptyString10(contextSnapshot?.wakeReason); - return wakeReason === "issue_assigned" || wakeReason === "execution_review_requested" || wakeReason === "execution_approval_requested" || wakeReason === "execution_changes_requested"; -} -function formatRuntimeWorkspaceWarningLog(warning) { - return { - stream: "stdout", - chunk: `[taskcore] ${warning} -` - }; -} -function describeSessionResetReason(contextSnapshot) { - if (contextSnapshot?.forceFreshSession === true) return "forceFreshSession was requested"; - const wakeReason = readNonEmptyString10(contextSnapshot?.wakeReason); - if (wakeReason === "issue_assigned") return "wake reason is issue_assigned"; - if (wakeReason === "execution_review_requested") return "wake reason is execution_review_requested"; - if (wakeReason === "execution_approval_requested") return "wake reason is execution_approval_requested"; - if (wakeReason === "execution_changes_requested") return "wake reason is execution_changes_requested"; - return null; -} -function shouldAutoCheckoutIssueForWake(input) { - if (input.issueAssigneeAgentId !== input.agentId) return false; - const issueStatus = readNonEmptyString10(input.issueStatus); - if (issueStatus !== "todo" && issueStatus !== "backlog" && issueStatus !== "blocked" && issueStatus !== "in_progress") { - return false; - } - const wakeReason = readNonEmptyString10(input.contextSnapshot?.wakeReason); - if (!wakeReason) return false; - if (wakeReason === "issue_comment_mentioned") return false; - if (wakeReason.startsWith("execution_")) return false; - return true; -} -function isCheckoutConflictError(error50) { - return error50 instanceof HttpError && error50.status === 409 && error50.message === "Issue checkout conflict"; -} -function deriveCommentId(contextSnapshot, payload2) { - const batchedCommentId = extractWakeCommentIds(contextSnapshot).at(-1); - return batchedCommentId ?? readNonEmptyString10(contextSnapshot?.wakeCommentId) ?? readNonEmptyString10(contextSnapshot?.commentId) ?? readNonEmptyString10(payload2?.commentId) ?? null; -} -function extractWakeCommentIds(contextSnapshot) { - const raw = contextSnapshot?.[WAKE_COMMENT_IDS_KEY]; - if (!Array.isArray(raw)) return []; - const out = []; - for (const entry of raw) { - const value = readNonEmptyString10(entry); - if (!value || out.includes(value)) continue; - out.push(value); - } - return out; -} -function mergeWakeCommentIds(...values2) { - const merged = []; - const append = (value) => { - const normalized = readNonEmptyString10(value); - if (!normalized || merged.includes(normalized)) return; - merged.push(normalized); - }; - for (const value of values2) { - if (Array.isArray(value)) { - for (const entry of value) append(entry); - continue; - } - if (typeof value === "object" && value !== null) { - const candidate = value; - const batched = extractWakeCommentIds(candidate); - if (batched.length > 0) { - for (const entry of batched) append(entry); - continue; - } - append(candidate.wakeCommentId); - append(candidate.commentId); - continue; - } - append(value); - } - return merged; -} -function enrichWakeContextSnapshot(input) { - const { contextSnapshot, reason, source, triggerDetail, payload: payload2 } = input; - const issueIdFromPayload = readNonEmptyString10(payload2?.["issueId"]); - const commentIdFromPayload = readNonEmptyString10(payload2?.["commentId"]); - const taskKey = deriveTaskKey(contextSnapshot, payload2); - const wakeCommentId = deriveCommentId(contextSnapshot, payload2); - const wakeCommentIds = mergeWakeCommentIds(contextSnapshot, commentIdFromPayload); - if (!readNonEmptyString10(contextSnapshot["wakeReason"]) && reason) { - contextSnapshot.wakeReason = reason; - } - if (!readNonEmptyString10(contextSnapshot["issueId"]) && issueIdFromPayload) { - contextSnapshot.issueId = issueIdFromPayload; - } - if (!readNonEmptyString10(contextSnapshot["taskId"]) && issueIdFromPayload) { - contextSnapshot.taskId = issueIdFromPayload; - } - if (!readNonEmptyString10(contextSnapshot["taskKey"]) && taskKey) { - contextSnapshot.taskKey = taskKey; - } - if (!readNonEmptyString10(contextSnapshot["commentId"]) && commentIdFromPayload) { - contextSnapshot.commentId = commentIdFromPayload; - } - if (wakeCommentIds.length > 0) { - const latestCommentId = wakeCommentIds[wakeCommentIds.length - 1]; - contextSnapshot[WAKE_COMMENT_IDS_KEY] = wakeCommentIds; - contextSnapshot.commentId = latestCommentId; - contextSnapshot.wakeCommentId = latestCommentId; - delete contextSnapshot[TASKCORE_WAKE_PAYLOAD_KEY]; - } else if (!readNonEmptyString10(contextSnapshot["wakeCommentId"]) && wakeCommentId) { - contextSnapshot.wakeCommentId = wakeCommentId; - } - if (!readNonEmptyString10(contextSnapshot["wakeSource"]) && source) { - contextSnapshot.wakeSource = source; - } - if (!readNonEmptyString10(contextSnapshot["wakeTriggerDetail"]) && triggerDetail) { - contextSnapshot.wakeTriggerDetail = triggerDetail; - } - return { - contextSnapshot, - issueIdFromPayload, - commentIdFromPayload, - taskKey, - wakeCommentId - }; -} -function mergeCoalescedContextSnapshot(existingRaw, incoming) { - const existing = parseObject4(existingRaw); - const merged = { - ...existing, - ...incoming - }; - const mergedCommentIds = mergeWakeCommentIds(existing, incoming); - if (mergedCommentIds.length > 0) { - const latestCommentId = mergedCommentIds[mergedCommentIds.length - 1]; - merged[WAKE_COMMENT_IDS_KEY] = mergedCommentIds; - merged.commentId = latestCommentId; - merged.wakeCommentId = latestCommentId; - delete merged[TASKCORE_WAKE_PAYLOAD_KEY]; - } - return merged; -} -async function buildTaskcoreWakePayload(input) { - const executionStage = parseObject4(input.contextSnapshot.executionStage); - const commentIds = extractWakeCommentIds(input.contextSnapshot); - const issueId = readNonEmptyString10(input.contextSnapshot.issueId); - const issueSummary = input.issueSummary ?? (issueId ? await input.db.select({ - id: issues.id, - identifier: issues.identifier, - title: issues.title, - status: issues.status, - priority: issues.priority - }).from(issues).where(and(eq(issues.id, issueId), eq(issues.companyId, input.companyId))).then((rows) => rows[0] ?? null) : null); - if (commentIds.length === 0 && Object.keys(executionStage).length === 0 && !issueSummary) return null; - const commentRows = commentIds.length === 0 ? [] : await input.db.select({ - id: issueComments.id, - issueId: issueComments.issueId, - body: issueComments.body, - authorAgentId: issueComments.authorAgentId, - authorUserId: issueComments.authorUserId, - createdAt: issueComments.createdAt - }).from(issueComments).where( - and( - eq(issueComments.companyId, input.companyId), - inArray(issueComments.id, commentIds) - ) - ); - const commentsById = new Map(commentRows.map((comment) => [comment.id, comment])); - const comments = []; - let remainingBodyChars = MAX_INLINE_WAKE_COMMENT_BODY_TOTAL_CHARS; - let truncated = false; - let missingCommentCount = 0; - for (const commentId of commentIds) { - const row = commentsById.get(commentId); - if (!row) { - truncated = true; - missingCommentCount += 1; - continue; - } - if (comments.length >= MAX_INLINE_WAKE_COMMENTS) { - truncated = true; - break; - } - const fullBody = row.body; - const allowedBodyChars = Math.min(MAX_INLINE_WAKE_COMMENT_BODY_CHARS, remainingBodyChars); - if (allowedBodyChars <= 0) { - truncated = true; - break; - } - const body = fullBody.length > allowedBodyChars ? fullBody.slice(0, allowedBodyChars) : fullBody; - const bodyTruncated = body.length < fullBody.length; - if (bodyTruncated) truncated = true; - remainingBodyChars -= body.length; - comments.push({ - id: row.id, - issueId: row.issueId, - body, - bodyTruncated, - createdAt: row.createdAt.toISOString(), - author: row.authorAgentId ? { type: "agent", id: row.authorAgentId } : row.authorUserId ? { type: "user", id: row.authorUserId } : { type: "system", id: null } - }); - } - return { - reason: readNonEmptyString10(input.contextSnapshot.wakeReason), - issue: issueSummary ? { - id: issueSummary.id, - identifier: issueSummary.identifier, - title: issueSummary.title, - status: issueSummary.status, - priority: issueSummary.priority - } : null, - checkedOutByHarness: input.contextSnapshot[TASKCORE_HARNESS_CHECKOUT_KEY] === true, - executionStage: Object.keys(executionStage).length > 0 ? executionStage : null, - commentIds, - latestCommentId: commentIds[commentIds.length - 1] ?? null, - comments, - commentWindow: { - requestedCount: commentIds.length, - includedCount: comments.length, - missingCount: missingCommentCount - }, - truncated, - fallbackFetchNeeded: truncated || missingCommentCount > 0 - }; -} -function runTaskKey(run) { - return deriveTaskKey(run.contextSnapshot, null); -} -function isSameTaskScope(left, right) { - return (left ?? null) === (right ?? null); -} -function isTrackedLocalChildProcessAdapter(adapterType) { - return SESSIONED_LOCAL_ADAPTERS.has(adapterType); -} -function isProcessAlive(pid) { - if (typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0) return false; - try { - process.kill(pid, 0); - return true; - } catch (error50) { - const code = error50?.code; - if (code === "EPERM") return true; - if (code === "ESRCH") return false; - return false; - } -} -async function terminateHeartbeatRunProcess(input) { - const pid = input.pid ?? null; - const processGroupId = input.processGroupId ?? null; - if (typeof pid !== "number" && typeof processGroupId !== "number") return; - await terminateLocalService( - { - pid: typeof pid === "number" && Number.isInteger(pid) && pid > 0 ? pid : processGroupId ?? 0, - processGroupId: typeof processGroupId === "number" && Number.isInteger(processGroupId) && processGroupId > 0 ? processGroupId : null - }, - input.graceMs ? { forceAfterMs: input.graceMs } : void 0 - ); -} -function buildProcessLossMessage(run, options) { - if (options?.descendantOnly && run.processGroupId) { - return `Process lost -- parent pid ${run.processPid ?? "unknown"} exited, but descendant process group ${run.processGroupId} was still alive and was terminated`; - } - if (run.processPid) { - return `Process lost -- child pid ${run.processPid} is no longer running`; - } - if (run.processGroupId) { - return `Process lost -- process group ${run.processGroupId} is no longer running`; - } - return "Process lost -- server may have restarted"; -} -function truncateDisplayId(value, max = 128) { - if (!value) return null; - return value.length > max ? value.slice(0, max) : value; -} -function normalizeAgentNameKey(value) { - if (typeof value !== "string") return null; - const normalized = value.trim().toLowerCase(); - return normalized.length > 0 ? normalized : null; -} -var defaultSessionCodec = { - deserialize(raw) { - const asObj = parseObject4(raw); - if (Object.keys(asObj).length > 0) return asObj; - const sessionId = readNonEmptyString10(raw?.sessionId); - if (sessionId) return { sessionId }; - return null; - }, - serialize(params) { - if (!params || Object.keys(params).length === 0) return null; - return params; - }, - getDisplayId(params) { - return readNonEmptyString10(params?.sessionId); - } -}; -function getAdapterSessionCodec(adapterType) { - const adapter = getServerAdapter(adapterType); - return adapter.sessionCodec ?? defaultSessionCodec; -} -function normalizeSessionParams(params) { - if (!params) return null; - return Object.keys(params).length > 0 ? params : null; -} -function resolveNextSessionState(input) { - const { codec: codec2, adapterResult, previousParams, previousDisplayId, previousLegacySessionId } = input; - if (adapterResult.clearSession) { - return { - params: null, - displayId: null, - legacySessionId: null - }; - } - const explicitParams = adapterResult.sessionParams; - const hasExplicitParams = adapterResult.sessionParams !== void 0; - const hasExplicitSessionId = adapterResult.sessionId !== void 0; - const explicitSessionId = readNonEmptyString10(adapterResult.sessionId); - const hasExplicitDisplay = adapterResult.sessionDisplayId !== void 0; - const explicitDisplayId = readNonEmptyString10(adapterResult.sessionDisplayId); - const shouldUsePrevious = !hasExplicitParams && !hasExplicitSessionId && !hasExplicitDisplay; - const candidateParams = hasExplicitParams ? explicitParams : hasExplicitSessionId ? explicitSessionId ? { sessionId: explicitSessionId } : null : previousParams; - const serialized = normalizeSessionParams(codec2.serialize(normalizeSessionParams(candidateParams) ?? null)); - const deserialized = normalizeSessionParams(codec2.deserialize(serialized)); - const displayId = truncateDisplayId( - explicitDisplayId ?? (codec2.getDisplayId ? codec2.getDisplayId(deserialized) : null) ?? readNonEmptyString10(deserialized?.sessionId) ?? (shouldUsePrevious ? previousDisplayId : null) ?? explicitSessionId ?? (shouldUsePrevious ? previousLegacySessionId : null) - ); - const legacySessionId = explicitSessionId ?? readNonEmptyString10(deserialized?.sessionId) ?? displayId ?? (shouldUsePrevious ? previousLegacySessionId : null); - return { - params: serialized, - displayId, - legacySessionId - }; -} -function heartbeatService(db) { - const instanceSettings2 = instanceSettingsService(db); - const getCurrentUserRedactionOptions = async () => ({ - enabled: (await instanceSettings2.getGeneral()).censorUsernameInLogs - }); - const runLogStore = getRunLogStore(); - const secretsSvc = secretService(db); - const companySkills2 = companySkillService(db); - const issuesSvc = issueService(db); - const executionWorkspacesSvc = executionWorkspaceService(db); - const workspaceOperationsSvc = workspaceOperationService(db); - const activeRunExecutions = /* @__PURE__ */ new Set(); - const budgetHooks = { - cancelWorkForScope: cancelBudgetScopeWork - }; - const budgets = budgetService(db, budgetHooks); - async function getAgent(agentId) { - return db.select().from(agents).where(eq(agents.id, agentId)).then((rows) => rows[0] ?? null); - } - async function getRun(runId) { - return db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)).then((rows) => rows[0] ?? null); - } - async function getIssueExecutionContext(companyId, issueId) { - return db.select({ - id: issues.id, - identifier: issues.identifier, - title: issues.title, - status: issues.status, - priority: issues.priority, - projectId: issues.projectId, - projectWorkspaceId: issues.projectWorkspaceId, - executionWorkspaceId: issues.executionWorkspaceId, - executionWorkspacePreference: issues.executionWorkspacePreference, - assigneeAgentId: issues.assigneeAgentId, - assigneeAdapterOverrides: issues.assigneeAdapterOverrides, - executionWorkspaceSettings: issues.executionWorkspaceSettings - }).from(issues).where(and(eq(issues.id, issueId), eq(issues.companyId, companyId))).then((rows) => rows[0] ?? null); - } - async function getRuntimeState(agentId) { - return db.select().from(agentRuntimeState).where(eq(agentRuntimeState.agentId, agentId)).then((rows) => rows[0] ?? null); - } - async function getTaskSession(companyId, agentId, adapterType, taskKey) { - return db.select().from(agentTaskSessions).where( - and( - eq(agentTaskSessions.companyId, companyId), - eq(agentTaskSessions.agentId, agentId), - eq(agentTaskSessions.adapterType, adapterType), - eq(agentTaskSessions.taskKey, taskKey) - ) - ).then((rows) => rows[0] ?? null); - } - async function getLatestRunForSession(agentId, sessionId, opts) { - const conditions = [ - eq(heartbeatRuns.agentId, agentId), - eq(heartbeatRuns.sessionIdAfter, sessionId) - ]; - if (opts?.excludeRunId) { - conditions.push(sql`${heartbeatRuns.id} <> ${opts.excludeRunId}`); - } - return db.select().from(heartbeatRuns).where(and(...conditions)).orderBy(desc(heartbeatRuns.createdAt)).limit(1).then((rows) => rows[0] ?? null); - } - async function getOldestRunForSession(agentId, sessionId) { - return db.select({ - id: heartbeatRuns.id, - createdAt: heartbeatRuns.createdAt - }).from(heartbeatRuns).where(and(eq(heartbeatRuns.agentId, agentId), eq(heartbeatRuns.sessionIdAfter, sessionId))).orderBy(asc(heartbeatRuns.createdAt), asc(heartbeatRuns.id)).limit(1).then((rows) => rows[0] ?? null); - } - async function resolveNormalizedUsageForSession(input) { - const { agentId, runId, sessionId, rawUsage } = input; - if (!sessionId || !rawUsage) { - return { - normalizedUsage: rawUsage, - previousRawUsage: null, - derivedFromSessionTotals: false - }; - } - const previousRun = await getLatestRunForSession(agentId, sessionId, { excludeRunId: runId }); - const previousRawUsage = readRawUsageTotals(previousRun?.usageJson); - return { - normalizedUsage: deriveNormalizedUsageDelta(rawUsage, previousRawUsage), - previousRawUsage, - derivedFromSessionTotals: previousRawUsage !== null - }; - } - async function evaluateSessionCompaction(input) { - const { agent, sessionId, issueId } = input; - if (!sessionId) { - return { - rotate: false, - reason: null, - handoffMarkdown: null, - previousRunId: null - }; - } - const policy = parseSessionCompactionPolicy(agent); - if (!policy.enabled || !hasSessionCompactionThresholds(policy)) { - return { - rotate: false, - reason: null, - handoffMarkdown: null, - previousRunId: null - }; - } - const fetchLimit = Math.max(policy.maxSessionRuns > 0 ? policy.maxSessionRuns + 1 : 0, 4); - const runs = await db.select({ - id: heartbeatRuns.id, - createdAt: heartbeatRuns.createdAt, - usageJson: heartbeatRuns.usageJson, - resultJson: heartbeatRuns.resultJson, - error: heartbeatRuns.error - }).from(heartbeatRuns).where(and(eq(heartbeatRuns.agentId, agent.id), eq(heartbeatRuns.sessionIdAfter, sessionId))).orderBy(desc(heartbeatRuns.createdAt)).limit(fetchLimit); - if (runs.length === 0) { - return { - rotate: false, - reason: null, - handoffMarkdown: null, - previousRunId: null - }; - } - const latestRun = runs[0] ?? null; - const oldestRun = policy.maxSessionAgeHours > 0 ? await getOldestRunForSession(agent.id, sessionId) : runs[runs.length - 1] ?? latestRun; - const latestRawUsage = readRawUsageTotals(latestRun?.usageJson); - const sessionAgeHours = latestRun && oldestRun ? Math.max( - 0, - (new Date(latestRun.createdAt).getTime() - new Date(oldestRun.createdAt).getTime()) / (1e3 * 60 * 60) - ) : 0; - let reason = null; - if (policy.maxSessionRuns > 0 && runs.length > policy.maxSessionRuns) { - reason = `session exceeded ${policy.maxSessionRuns} runs`; - } else if (policy.maxRawInputTokens > 0 && latestRawUsage && latestRawUsage.inputTokens >= policy.maxRawInputTokens) { - reason = `session raw input reached ${formatCount(latestRawUsage.inputTokens)} tokens (threshold ${formatCount(policy.maxRawInputTokens)})`; - } else if (policy.maxSessionAgeHours > 0 && sessionAgeHours >= policy.maxSessionAgeHours) { - reason = `session age reached ${Math.floor(sessionAgeHours)} hours`; - } - if (!reason || !latestRun) { - return { - rotate: false, - reason: null, - handoffMarkdown: null, - previousRunId: latestRun?.id ?? null - }; - } - const latestSummary = summarizeHeartbeatRunResultJson(latestRun.resultJson); - const latestTextSummary = readNonEmptyString10(latestSummary?.summary) ?? readNonEmptyString10(latestSummary?.result) ?? readNonEmptyString10(latestSummary?.message) ?? readNonEmptyString10(latestRun.error); - const handoffMarkdown = [ - "Taskcore session handoff:", - `- Previous session: ${sessionId}`, - issueId ? `- Issue: ${issueId}` : "", - `- Rotation reason: ${reason}`, - latestTextSummary ? `- Last run summary: ${latestTextSummary}` : "", - "Continue from the current task state. Rebuild only the minimum context you need." - ].filter(Boolean).join("\n"); - return { - rotate: true, - reason, - handoffMarkdown, - previousRunId: latestRun.id - }; - } - async function resolveSessionBeforeForWakeup(agent, taskKey) { - if (taskKey) { - const codec2 = getAdapterSessionCodec(agent.adapterType); - const existingTaskSession = await getTaskSession( - agent.companyId, - agent.id, - agent.adapterType, - taskKey - ); - const parsedParams = normalizeSessionParams( - codec2.deserialize(existingTaskSession?.sessionParamsJson ?? null) - ); - return truncateDisplayId( - existingTaskSession?.sessionDisplayId ?? (codec2.getDisplayId ? codec2.getDisplayId(parsedParams) : null) ?? readNonEmptyString10(parsedParams?.sessionId) - ); - } - const runtimeForRun = await getRuntimeState(agent.id); - return runtimeForRun?.sessionId ?? null; - } - async function resolveExplicitResumeSessionOverride(agent, payload2, taskKey) { - const resumeFromRunId = readNonEmptyString10(payload2?.resumeFromRunId); - if (!resumeFromRunId) return null; - const resumeRun = await db.select({ - id: heartbeatRuns.id, - contextSnapshot: heartbeatRuns.contextSnapshot, - sessionIdBefore: heartbeatRuns.sessionIdBefore, - sessionIdAfter: heartbeatRuns.sessionIdAfter - }).from(heartbeatRuns).where( - and( - eq(heartbeatRuns.id, resumeFromRunId), - eq(heartbeatRuns.companyId, agent.companyId), - eq(heartbeatRuns.agentId, agent.id) - ) - ).then((rows) => rows[0] ?? null); - if (!resumeRun) return null; - const resumeContext = parseObject4(resumeRun.contextSnapshot); - const resumeTaskKey = deriveTaskKey(resumeContext, null) ?? taskKey; - const resumeTaskSession = resumeTaskKey ? await getTaskSession(agent.companyId, agent.id, agent.adapterType, resumeTaskKey) : null; - const sessionCodec8 = getAdapterSessionCodec(agent.adapterType); - const sessionOverride = buildExplicitResumeSessionOverride({ - resumeFromRunId, - resumeRunSessionIdBefore: resumeRun.sessionIdBefore, - resumeRunSessionIdAfter: resumeRun.sessionIdAfter, - taskSession: resumeTaskSession, - sessionCodec: sessionCodec8 - }); - if (!sessionOverride) return null; - return { - resumeFromRunId, - taskKey: resumeTaskKey, - issueId: readNonEmptyString10(resumeContext.issueId), - taskId: readNonEmptyString10(resumeContext.taskId) ?? readNonEmptyString10(resumeContext.issueId), - sessionDisplayId: sessionOverride.sessionDisplayId, - sessionParams: sessionOverride.sessionParams - }; - } - async function resolveWorkspaceForRun(agent, context, previousSessionParams, opts) { - const issueId = readNonEmptyString10(context.issueId); - const contextProjectId = readNonEmptyString10(context.projectId); - const contextProjectWorkspaceId = readNonEmptyString10(context.projectWorkspaceId); - const issueProjectRef = issueId ? await db.select({ - projectId: issues.projectId, - projectWorkspaceId: issues.projectWorkspaceId - }).from(issues).where(and(eq(issues.id, issueId), eq(issues.companyId, agent.companyId))).then((rows) => rows[0] ?? null) : null; - const issueProjectId = issueProjectRef?.projectId ?? null; - const preferredProjectWorkspaceId = issueProjectRef?.projectWorkspaceId ?? contextProjectWorkspaceId ?? null; - const resolvedProjectId = issueProjectId ?? contextProjectId; - const useProjectWorkspace = opts?.useProjectWorkspace !== false; - const workspaceProjectId = useProjectWorkspace ? resolvedProjectId : null; - const unorderedProjectWorkspaceRows = workspaceProjectId ? await db.select().from(projectWorkspaces).where( - and( - eq(projectWorkspaces.companyId, agent.companyId), - eq(projectWorkspaces.projectId, workspaceProjectId) - ) - ).orderBy(asc(projectWorkspaces.createdAt), asc(projectWorkspaces.id)) : []; - const projectWorkspaceRows = prioritizeProjectWorkspaceCandidatesForRun( - unorderedProjectWorkspaceRows, - preferredProjectWorkspaceId - ); - const workspaceHints = projectWorkspaceRows.map((workspace) => ({ - workspaceId: workspace.id, - cwd: readNonEmptyString10(workspace.cwd), - repoUrl: readNonEmptyString10(workspace.repoUrl), - repoRef: readNonEmptyString10(workspace.repoRef) - })); - if (projectWorkspaceRows.length > 0) { - const preferredWorkspace = preferredProjectWorkspaceId ? projectWorkspaceRows.find((workspace) => workspace.id === preferredProjectWorkspaceId) ?? null : null; - const missingProjectCwds = []; - let hasConfiguredProjectCwd = false; - let preferredWorkspaceWarning = null; - if (preferredProjectWorkspaceId && !preferredWorkspace) { - preferredWorkspaceWarning = `Selected project workspace "${preferredProjectWorkspaceId}" is not available on this project.`; - } - for (const workspace of projectWorkspaceRows) { - let projectCwd = readNonEmptyString10(workspace.cwd); - let managedWorkspaceWarning = null; - if (!projectCwd || projectCwd === REPO_ONLY_CWD_SENTINEL2) { - try { - const managedWorkspace = await ensureManagedProjectWorkspace({ - companyId: agent.companyId, - projectId: workspaceProjectId ?? resolvedProjectId ?? workspace.projectId, - repoUrl: readNonEmptyString10(workspace.repoUrl) - }); - projectCwd = managedWorkspace.cwd; - managedWorkspaceWarning = managedWorkspace.warning; - } catch (error50) { - if (preferredWorkspace?.id === workspace.id) { - preferredWorkspaceWarning = error50 instanceof Error ? error50.message : String(error50); - } - continue; - } - } - hasConfiguredProjectCwd = true; - const projectCwdExists = await fs32.stat(projectCwd).then((stats) => stats.isDirectory()).catch(() => false); - if (projectCwdExists) { - return { - cwd: projectCwd, - source: "project_primary", - projectId: resolvedProjectId, - workspaceId: workspace.id, - repoUrl: workspace.repoUrl, - repoRef: workspace.repoRef, - workspaceHints, - warnings: [preferredWorkspaceWarning, managedWorkspaceWarning].filter( - (value) => Boolean(value) - ) - }; - } - if (preferredWorkspace?.id === workspace.id) { - preferredWorkspaceWarning = `Selected project workspace path "${projectCwd}" is not available yet.`; - } - missingProjectCwds.push(projectCwd); - } - const fallbackCwd = resolveDefaultAgentWorkspaceDir(agent.id); - await fs32.mkdir(fallbackCwd, { recursive: true }); - const warnings2 = []; - if (preferredWorkspaceWarning) { - warnings2.push(preferredWorkspaceWarning); - } - if (missingProjectCwds.length > 0) { - const firstMissing = missingProjectCwds[0]; - const extraMissingCount = Math.max(0, missingProjectCwds.length - 1); - warnings2.push( - extraMissingCount > 0 ? `Project workspace path "${firstMissing}" and ${extraMissingCount} other configured path(s) are not available yet. Using fallback workspace "${fallbackCwd}" for this run.` : `Project workspace path "${firstMissing}" is not available yet. Using fallback workspace "${fallbackCwd}" for this run.` - ); - } else if (!hasConfiguredProjectCwd) { - warnings2.push( - `Project workspace has no local cwd configured. Using fallback workspace "${fallbackCwd}" for this run.` - ); - } - return { - cwd: fallbackCwd, - source: "project_primary", - projectId: resolvedProjectId, - workspaceId: projectWorkspaceRows[0]?.id ?? null, - repoUrl: projectWorkspaceRows[0]?.repoUrl ?? null, - repoRef: projectWorkspaceRows[0]?.repoRef ?? null, - workspaceHints, - warnings: warnings2 - }; - } - if (workspaceProjectId) { - const managedWorkspace = await ensureManagedProjectWorkspace({ - companyId: agent.companyId, - projectId: workspaceProjectId, - repoUrl: null - }); - return { - cwd: managedWorkspace.cwd, - source: "project_primary", - projectId: resolvedProjectId, - workspaceId: null, - repoUrl: null, - repoRef: null, - workspaceHints, - warnings: managedWorkspace.warning ? [managedWorkspace.warning] : [] - }; - } - const sessionCwd = readNonEmptyString10(previousSessionParams?.cwd); - if (sessionCwd) { - const sessionCwdExists = await fs32.stat(sessionCwd).then((stats) => stats.isDirectory()).catch(() => false); - if (sessionCwdExists) { - return { - cwd: sessionCwd, - source: "task_session", - projectId: resolvedProjectId, - workspaceId: readNonEmptyString10(previousSessionParams?.workspaceId), - repoUrl: readNonEmptyString10(previousSessionParams?.repoUrl), - repoRef: readNonEmptyString10(previousSessionParams?.repoRef), - workspaceHints, - warnings: [] - }; - } - } - const cwd = resolveDefaultAgentWorkspaceDir(agent.id); - await fs32.mkdir(cwd, { recursive: true }); - const warnings = []; - if (sessionCwd) { - warnings.push( - `Saved session workspace "${sessionCwd}" is not available. Using fallback workspace "${cwd}" for this run.` - ); - } else if (resolvedProjectId) { - warnings.push( - `No project workspace directory is currently available for this issue. Using fallback workspace "${cwd}" for this run.` - ); - } else { - warnings.push( - `No project or prior session workspace was available. Using fallback workspace "${cwd}" for this run.` - ); - } - return { - cwd, - source: "agent_home", - projectId: resolvedProjectId, - workspaceId: null, - repoUrl: null, - repoRef: null, - workspaceHints, - warnings - }; - } - async function upsertTaskSession(input) { - const existing = await getTaskSession( - input.companyId, - input.agentId, - input.adapterType, - input.taskKey - ); - if (existing) { - return db.update(agentTaskSessions).set({ - sessionParamsJson: input.sessionParamsJson, - sessionDisplayId: input.sessionDisplayId, - lastRunId: input.lastRunId, - lastError: input.lastError, - updatedAt: /* @__PURE__ */ new Date() - }).where(eq(agentTaskSessions.id, existing.id)).returning().then((rows) => rows[0] ?? null); - } - return db.insert(agentTaskSessions).values({ - companyId: input.companyId, - agentId: input.agentId, - adapterType: input.adapterType, - taskKey: input.taskKey, - sessionParamsJson: input.sessionParamsJson, - sessionDisplayId: input.sessionDisplayId, - lastRunId: input.lastRunId, - lastError: input.lastError - }).returning().then((rows) => rows[0] ?? null); - } - async function clearTaskSessions(companyId, agentId, opts) { - const conditions = [ - eq(agentTaskSessions.companyId, companyId), - eq(agentTaskSessions.agentId, agentId) - ]; - if (opts?.taskKey) { - conditions.push(eq(agentTaskSessions.taskKey, opts.taskKey)); - } - if (opts?.adapterType) { - conditions.push(eq(agentTaskSessions.adapterType, opts.adapterType)); - } - return db.delete(agentTaskSessions).where(and(...conditions)).returning().then((rows) => rows.length); - } - async function ensureRuntimeState(agent) { - const existing = await getRuntimeState(agent.id); - if (existing) return existing; - return db.insert(agentRuntimeState).values({ - agentId: agent.id, - companyId: agent.companyId, - adapterType: agent.adapterType, - stateJson: {} - }).returning().then((rows) => rows[0]); - } - async function setRunStatus(runId, status, patch) { - const updated = await db.update(heartbeatRuns).set({ status, ...patch, updatedAt: /* @__PURE__ */ new Date() }).where(eq(heartbeatRuns.id, runId)).returning().then((rows) => rows[0] ?? null); - if (updated) { - publishLiveEvent({ - companyId: updated.companyId, - type: "heartbeat.run.status", - payload: { - runId: updated.id, - agentId: updated.agentId, - status: updated.status, - invocationSource: updated.invocationSource, - triggerDetail: updated.triggerDetail, - error: updated.error ?? null, - errorCode: updated.errorCode ?? null, - startedAt: updated.startedAt ? new Date(updated.startedAt).toISOString() : null, - finishedAt: updated.finishedAt ? new Date(updated.finishedAt).toISOString() : null - } - }); - } - return updated; - } - async function setWakeupStatus(wakeupRequestId, status, patch) { - if (!wakeupRequestId) return; - await db.update(agentWakeupRequests).set({ status, ...patch, updatedAt: /* @__PURE__ */ new Date() }).where(eq(agentWakeupRequests.id, wakeupRequestId)); - } - async function appendRunEvent(run, seq, event) { - const currentUserRedactionOptions = await getCurrentUserRedactionOptions(); - const sanitizedMessage = event.message ? redactCurrentUserText(event.message, currentUserRedactionOptions) : event.message; - const sanitizedPayload = event.payload ? redactCurrentUserValue(event.payload, currentUserRedactionOptions) : event.payload; - await db.insert(heartbeatRunEvents).values({ - companyId: run.companyId, - runId: run.id, - agentId: run.agentId, - seq, - eventType: event.eventType, - stream: event.stream, - level: event.level, - color: event.color, - message: sanitizedMessage, - payload: sanitizedPayload - }); - publishLiveEvent({ - companyId: run.companyId, - type: "heartbeat.run.event", - payload: { - runId: run.id, - agentId: run.agentId, - seq, - eventType: event.eventType, - stream: event.stream ?? null, - level: event.level ?? null, - color: event.color ?? null, - message: sanitizedMessage ?? null, - payload: sanitizedPayload ?? null - } - }); - } - async function nextRunEventSeq(runId) { - const [row] = await db.select({ maxSeq: sql`max(${heartbeatRunEvents.seq})` }).from(heartbeatRunEvents).where(eq(heartbeatRunEvents.runId, runId)); - return Number(row?.maxSeq ?? 0) + 1; - } - async function persistRunProcessMetadata(runId, meta3) { - const startedAt = new Date(meta3.startedAt); - return db.update(heartbeatRuns).set({ - processPid: meta3.pid, - processGroupId: meta3.processGroupId, - processStartedAt: Number.isNaN(startedAt.getTime()) ? /* @__PURE__ */ new Date() : startedAt, - updatedAt: /* @__PURE__ */ new Date() - }).where(eq(heartbeatRuns.id, runId)).returning().then((rows) => rows[0] ?? null); - } - async function clearDetachedRunWarning(runId) { - const updated = await db.update(heartbeatRuns).set({ - error: null, - errorCode: null, - updatedAt: /* @__PURE__ */ new Date() - }).where(and(eq(heartbeatRuns.id, runId), eq(heartbeatRuns.status, "running"), eq(heartbeatRuns.errorCode, DETACHED_PROCESS_ERROR_CODE))).returning().then((rows) => rows[0] ?? null); - if (!updated) return null; - await appendRunEvent(updated, await nextRunEventSeq(updated.id), { - eventType: "lifecycle", - stream: "system", - level: "info", - message: "Detached child process reported activity; cleared detached warning" - }); - return updated; - } - async function patchRunIssueCommentStatus(runId, patch) { - return db.update(heartbeatRuns).set({ ...patch, updatedAt: /* @__PURE__ */ new Date() }).where(eq(heartbeatRuns.id, runId)).returning().then((rows) => rows[0] ?? null); - } - async function findRunIssueComment(runId, companyId, issueId) { - return db.select({ - id: issueComments.id - }).from(issueComments).where( - and( - eq(issueComments.companyId, companyId), - eq(issueComments.issueId, issueId), - eq(issueComments.createdByRunId, runId) - ) - ).orderBy(desc(issueComments.createdAt), desc(issueComments.id)).limit(1).then((rows) => rows[0] ?? null); - } - async function enqueueMissingIssueCommentRetry(run, agent, issueId) { - const contextSnapshot = parseObject4(run.contextSnapshot); - const taskKey = deriveTaskKeyWithHeartbeatFallback(contextSnapshot, null); - const sessionBefore = await resolveSessionBeforeForWakeup(agent, taskKey); - const retryContextSnapshot = { - ...contextSnapshot, - retryOfRunId: run.id, - wakeReason: "missing_issue_comment", - retryReason: "missing_issue_comment", - missingIssueCommentForRunId: run.id - }; - const now2 = /* @__PURE__ */ new Date(); - const retryRun = await db.transaction(async (tx) => { - await tx.execute( - sql`select id from issues where company_id = ${run.companyId} and execution_run_id = ${run.id} for update` - ); - const issue2 = await tx.select({ id: issues.id }).from(issues).where(and(eq(issues.companyId, run.companyId), eq(issues.executionRunId, run.id))).then((rows) => rows[0] ?? null); - if (!issue2) return null; - const wakeupRequest = await tx.insert(agentWakeupRequests).values({ - companyId: run.companyId, - agentId: run.agentId, - source: "automation", - triggerDetail: "system", - reason: "missing_issue_comment", - payload: { - issueId, - retryOfRunId: run.id, - retryReason: "missing_issue_comment" - }, - status: "queued", - requestedByActorType: "system", - requestedByActorId: null, - updatedAt: now2 - }).returning().then((rows) => rows[0]); - const queuedRun = await tx.insert(heartbeatRuns).values({ - companyId: run.companyId, - agentId: run.agentId, - invocationSource: "automation", - triggerDetail: "system", - status: "queued", - wakeupRequestId: wakeupRequest.id, - contextSnapshot: retryContextSnapshot, - sessionIdBefore: sessionBefore, - retryOfRunId: run.id, - issueCommentStatus: "not_applicable", - updatedAt: now2 - }).returning().then((rows) => rows[0]); - await tx.update(agentWakeupRequests).set({ - runId: queuedRun.id, - updatedAt: now2 - }).where(eq(agentWakeupRequests.id, wakeupRequest.id)); - await tx.update(issues).set({ - executionRunId: queuedRun.id, - executionAgentNameKey: normalizeAgentNameKey(agent.name), - executionLockedAt: now2, - updatedAt: now2 - }).where(eq(issues.id, issue2.id)); - await tx.update(heartbeatRuns).set({ - issueCommentStatus: "retry_queued", - issueCommentRetryQueuedAt: now2, - updatedAt: now2 - }).where(eq(heartbeatRuns.id, run.id)); - return queuedRun; - }); - if (!retryRun) return null; - publishLiveEvent({ - companyId: retryRun.companyId, - type: "heartbeat.run.queued", - payload: { - runId: retryRun.id, - agentId: retryRun.agentId, - invocationSource: retryRun.invocationSource, - triggerDetail: retryRun.triggerDetail, - wakeupRequestId: retryRun.wakeupRequestId - } - }); - return retryRun; - } - async function finalizeIssueCommentPolicy(run, agent) { - const contextSnapshot = parseObject4(run.contextSnapshot); - const issueId = readNonEmptyString10(contextSnapshot.issueId); - if (!issueId) { - if (run.issueCommentStatus !== "not_applicable") { - await patchRunIssueCommentStatus(run.id, { - issueCommentStatus: "not_applicable", - issueCommentSatisfiedByCommentId: null, - issueCommentRetryQueuedAt: null - }); - } - return { outcome: "not_applicable", queuedRun: null }; - } - const postedComment = await findRunIssueComment(run.id, run.companyId, issueId); - if (postedComment) { - await patchRunIssueCommentStatus(run.id, { - issueCommentStatus: "satisfied", - issueCommentSatisfiedByCommentId: postedComment.id, - issueCommentRetryQueuedAt: null - }); - return { outcome: "satisfied", queuedRun: null }; - } - if (readNonEmptyString10(contextSnapshot.retryReason) === "missing_issue_comment") { - await patchRunIssueCommentStatus(run.id, { - issueCommentStatus: "retry_exhausted", - issueCommentSatisfiedByCommentId: null - }); - await appendRunEvent(run, await nextRunEventSeq(run.id), { - eventType: "lifecycle", - stream: "system", - level: "warn", - message: "Run ended without an issue comment after one retry; no further comment wake will be queued" - }); - return { outcome: "retry_exhausted", queuedRun: null }; - } - if (!shouldRequireIssueCommentForWake(contextSnapshot)) { - if (run.issueCommentStatus !== "not_applicable") { - await patchRunIssueCommentStatus(run.id, { - issueCommentStatus: "not_applicable", - issueCommentSatisfiedByCommentId: null, - issueCommentRetryQueuedAt: null - }); - } - return { outcome: "not_applicable", queuedRun: null }; - } - const queuedRun = await enqueueMissingIssueCommentRetry(run, agent, issueId); - if (queuedRun) { - await appendRunEvent(run, await nextRunEventSeq(run.id), { - eventType: "lifecycle", - stream: "system", - level: "warn", - message: "Run ended without an issue comment; queued one follow-up wake to require a comment" - }); - return { outcome: "retry_queued", queuedRun }; - } - await patchRunIssueCommentStatus(run.id, { - issueCommentStatus: "retry_exhausted", - issueCommentSatisfiedByCommentId: null - }); - return { outcome: "retry_exhausted", queuedRun: null }; - } - async function enqueueProcessLossRetry(run, agent, now2) { - const contextSnapshot = parseObject4(run.contextSnapshot); - const issueId = readNonEmptyString10(contextSnapshot.issueId); - const taskKey = deriveTaskKeyWithHeartbeatFallback(contextSnapshot, null); - const sessionBefore = await resolveSessionBeforeForWakeup(agent, taskKey); - const retryContextSnapshot = { - ...contextSnapshot, - retryOfRunId: run.id, - wakeReason: "process_lost_retry", - retryReason: "process_lost" - }; - const queued = await db.transaction(async (tx) => { - const wakeupRequest = await tx.insert(agentWakeupRequests).values({ - companyId: run.companyId, - agentId: run.agentId, - source: "automation", - triggerDetail: "system", - reason: "process_lost_retry", - payload: { - ...issueId ? { issueId } : {}, - retryOfRunId: run.id - }, - status: "queued", - requestedByActorType: "system", - requestedByActorId: null, - updatedAt: now2 - }).returning().then((rows) => rows[0]); - const retryRun = await tx.insert(heartbeatRuns).values({ - companyId: run.companyId, - agentId: run.agentId, - invocationSource: "automation", - triggerDetail: "system", - status: "queued", - wakeupRequestId: wakeupRequest.id, - contextSnapshot: retryContextSnapshot, - sessionIdBefore: sessionBefore, - retryOfRunId: run.id, - processLossRetryCount: (run.processLossRetryCount ?? 0) + 1, - updatedAt: now2 - }).returning().then((rows) => rows[0]); - await tx.update(agentWakeupRequests).set({ - runId: retryRun.id, - updatedAt: now2 - }).where(eq(agentWakeupRequests.id, wakeupRequest.id)); - if (issueId) { - await tx.update(issues).set({ - executionRunId: retryRun.id, - executionAgentNameKey: normalizeAgentNameKey(agent.name), - executionLockedAt: now2, - updatedAt: now2 - }).where(and(eq(issues.id, issueId), eq(issues.companyId, run.companyId), eq(issues.executionRunId, run.id))); - } - return retryRun; - }); - publishLiveEvent({ - companyId: queued.companyId, - type: "heartbeat.run.queued", - payload: { - runId: queued.id, - agentId: queued.agentId, - invocationSource: queued.invocationSource, - triggerDetail: queued.triggerDetail, - wakeupRequestId: queued.wakeupRequestId - } - }); - await appendRunEvent(queued, 1, { - eventType: "lifecycle", - stream: "system", - level: "warn", - message: "Queued automatic retry after orphaned child process was confirmed dead", - payload: { - retryOfRunId: run.id - } - }); - return queued; - } - function parseHeartbeatPolicy(agent) { - const runtimeConfig = parseObject4(agent.runtimeConfig); - const heartbeat = parseObject4(runtimeConfig.heartbeat); - return { - enabled: asBoolean4(heartbeat.enabled, false), - intervalSec: Math.max(0, asNumber3(heartbeat.intervalSec, 0)), - wakeOnDemand: asBoolean4(heartbeat.wakeOnDemand ?? heartbeat.wakeOnAssignment ?? heartbeat.wakeOnOnDemand ?? heartbeat.wakeOnAutomation, true), - maxConcurrentRuns: normalizeMaxConcurrentRuns(heartbeat.maxConcurrentRuns) - }; - } - async function countRunningRunsForAgent(agentId) { - const [{ count: count2 }] = await db.select({ count: sql`count(*)` }).from(heartbeatRuns).where(and(eq(heartbeatRuns.agentId, agentId), eq(heartbeatRuns.status, "running"))); - return Number(count2 ?? 0); - } - async function claimQueuedRun(run) { - if (run.status !== "queued") return run; - const agent = await getAgent(run.agentId); - if (!agent) { - await cancelRunInternal(run.id, "Cancelled because the agent no longer exists"); - return null; - } - if (agent.status === "paused" || agent.status === "terminated" || agent.status === "pending_approval") { - await cancelRunInternal(run.id, "Cancelled because the agent is not invokable"); - return null; - } - const context = parseObject4(run.contextSnapshot); - const budgetBlock = await budgets.getInvocationBlock(run.companyId, run.agentId, { - issueId: readNonEmptyString10(context.issueId), - projectId: readNonEmptyString10(context.projectId) - }); - if (budgetBlock) { - await cancelRunInternal(run.id, budgetBlock.reason); - return null; - } - const claimedAt = /* @__PURE__ */ new Date(); - const claimed = await db.update(heartbeatRuns).set({ - status: "running", - startedAt: run.startedAt ?? claimedAt, - updatedAt: claimedAt - }).where(and(eq(heartbeatRuns.id, run.id), eq(heartbeatRuns.status, "queued"))).returning().then((rows) => rows[0] ?? null); - if (!claimed) return null; - publishLiveEvent({ - companyId: claimed.companyId, - type: "heartbeat.run.status", - payload: { - runId: claimed.id, - agentId: claimed.agentId, - status: claimed.status, - invocationSource: claimed.invocationSource, - triggerDetail: claimed.triggerDetail, - error: claimed.error ?? null, - errorCode: claimed.errorCode ?? null, - startedAt: claimed.startedAt ? new Date(claimed.startedAt).toISOString() : null, - finishedAt: claimed.finishedAt ? new Date(claimed.finishedAt).toISOString() : null - } - }); - await setWakeupStatus(claimed.wakeupRequestId, "claimed", { claimedAt }); - const claimedIssueId = readNonEmptyString10(parseObject4(claimed.contextSnapshot).issueId); - if (claimedIssueId) { - const claimedAgent = await getAgent(claimed.agentId); - await db.update(issues).set({ - executionRunId: claimed.id, - executionAgentNameKey: normalizeAgentNameKey(claimedAgent?.name), - executionLockedAt: claimedAt, - updatedAt: claimedAt - }).where( - and( - eq(issues.id, claimedIssueId), - eq(issues.companyId, claimed.companyId), - or(isNull(issues.executionRunId), eq(issues.executionRunId, claimed.id)) - ) - ); - } - return claimed; - } - async function finalizeAgentStatus(agentId, outcome) { - const existing = await getAgent(agentId); - if (!existing) return; - if (existing.status === "paused" || existing.status === "terminated") { - return; - } - const isFirstHeartbeat = !existing.lastHeartbeatAt; - const runningCount = await countRunningRunsForAgent(agentId); - const nextStatus = runningCount > 0 ? "running" : outcome === "succeeded" || outcome === "cancelled" ? "idle" : "error"; - const updated = await db.update(agents).set({ - status: nextStatus, - lastHeartbeatAt: /* @__PURE__ */ new Date(), - updatedAt: /* @__PURE__ */ new Date() - }).where(eq(agents.id, agentId)).returning().then((rows) => rows[0] ?? null); - if (isFirstHeartbeat && updated) { - const tc = getTelemetryClient(); - if (tc) trackAgentFirstHeartbeat(tc, { agentRole: updated.role, agentId: updated.id }); - } - if (updated) { - publishLiveEvent({ - companyId: updated.companyId, - type: "agent.status", - payload: { - agentId: updated.id, - status: updated.status, - lastHeartbeatAt: updated.lastHeartbeatAt ? new Date(updated.lastHeartbeatAt).toISOString() : null, - outcome - } - }); - } - } - async function reapOrphanedRuns(opts) { - const staleThresholdMs = opts?.staleThresholdMs ?? 0; - const now2 = /* @__PURE__ */ new Date(); - const activeRuns = await db.select({ - run: heartbeatRuns, - adapterType: agents.adapterType - }).from(heartbeatRuns).innerJoin(agents, eq(heartbeatRuns.agentId, agents.id)).where(eq(heartbeatRuns.status, "running")); - const reaped = []; - for (const { run, adapterType } of activeRuns) { - if (runningProcesses3.has(run.id) || activeRunExecutions.has(run.id)) continue; - if (staleThresholdMs > 0) { - const refTime = run.updatedAt ? new Date(run.updatedAt).getTime() : 0; - if (now2.getTime() - refTime < staleThresholdMs) continue; - } - const tracksLocalChild = isTrackedLocalChildProcessAdapter(adapterType); - const processPidAlive = tracksLocalChild && run.processPid && isProcessAlive(run.processPid); - const processGroupAlive = tracksLocalChild && run.processGroupId && isProcessGroupAlive(run.processGroupId); - if (processPidAlive) { - if (run.errorCode !== DETACHED_PROCESS_ERROR_CODE) { - const detachedMessage = `Lost in-memory process handle, but child pid ${run.processPid} is still alive`; - const detachedRun = await setRunStatus(run.id, "running", { - error: detachedMessage, - errorCode: DETACHED_PROCESS_ERROR_CODE - }); - if (detachedRun) { - await appendRunEvent(detachedRun, await nextRunEventSeq(detachedRun.id), { - eventType: "lifecycle", - stream: "system", - level: "warn", - message: detachedMessage, - payload: { - processPid: run.processPid - } - }); - } - } - continue; - } - let descendantOnlyCleanup = false; - if (processGroupAlive) { - descendantOnlyCleanup = true; - await terminateHeartbeatRunProcess({ - pid: run.processPid, - processGroupId: run.processGroupId - }); - } - const shouldRetry = tracksLocalChild && (!!run.processPid || !!run.processGroupId) && (run.processLossRetryCount ?? 0) < 1; - const baseMessage = buildProcessLossMessage(run, descendantOnlyCleanup ? { descendantOnly: true } : void 0); - let finalizedRun = await setRunStatus(run.id, "failed", { - error: shouldRetry ? `${baseMessage}; retrying once` : baseMessage, - errorCode: "process_lost", - finishedAt: now2 - }); - await setWakeupStatus(run.wakeupRequestId, "failed", { - finishedAt: now2, - error: shouldRetry ? `${baseMessage}; retrying once` : baseMessage - }); - if (!finalizedRun) finalizedRun = await getRun(run.id); - if (!finalizedRun) continue; - let retriedRun = null; - if (shouldRetry) { - const agent = await getAgent(run.agentId); - if (agent) { - retriedRun = await enqueueProcessLossRetry(finalizedRun, agent, now2); - } - } else { - await releaseIssueExecutionAndPromote(finalizedRun); - } - await appendRunEvent(finalizedRun, await nextRunEventSeq(finalizedRun.id), { - eventType: "lifecycle", - stream: "system", - level: "error", - message: shouldRetry ? `${baseMessage}; queued retry ${retriedRun?.id ?? ""}`.trim() : baseMessage, - payload: { - ...run.processPid ? { processPid: run.processPid } : {}, - ...run.processGroupId ? { processGroupId: run.processGroupId } : {}, - ...descendantOnlyCleanup ? { descendantOnlyCleanup: true } : {}, - ...retriedRun ? { retryRunId: retriedRun.id } : {} - } - }); - await finalizeAgentStatus(run.agentId, "failed"); - await startNextQueuedRunForAgent(run.agentId); - runningProcesses3.delete(run.id); - reaped.push(run.id); - } - if (reaped.length > 0) { - logger.warn({ reapedCount: reaped.length, runIds: reaped }, "reaped orphaned heartbeat runs"); - } - return { reaped: reaped.length, runIds: reaped }; - } - async function resumeQueuedRuns() { - const queuedRuns = await db.select({ agentId: heartbeatRuns.agentId }).from(heartbeatRuns).where(eq(heartbeatRuns.status, "queued")); - const agentIds = [...new Set(queuedRuns.map((r5) => r5.agentId))]; - for (const agentId of agentIds) { - await startNextQueuedRunForAgent(agentId); - } - } - async function getLatestIssueRun(companyId, issueId) { - return db.select().from(heartbeatRuns).where( - and( - eq(heartbeatRuns.companyId, companyId), - sql`${heartbeatRuns.contextSnapshot} ->> 'issueId' = ${issueId}` - ) - ).orderBy(desc(heartbeatRuns.createdAt), desc(heartbeatRuns.id)).limit(1).then((rows) => rows[0] ?? null); - } - async function hasActiveExecutionPath(companyId, issueId) { - const [run, deferredWake] = await Promise.all([ - db.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where( - and( - eq(heartbeatRuns.companyId, companyId), - inArray(heartbeatRuns.status, [...ACTIVE_HEARTBEAT_RUN_STATUSES]), - sql`${heartbeatRuns.contextSnapshot} ->> 'issueId' = ${issueId}` - ) - ).limit(1).then((rows) => rows[0] ?? null), - db.select({ id: agentWakeupRequests.id }).from(agentWakeupRequests).where( - and( - eq(agentWakeupRequests.companyId, companyId), - eq(agentWakeupRequests.status, "deferred_issue_execution"), - sql`${agentWakeupRequests.payload} ->> 'issueId' = ${issueId}` - ) - ).limit(1).then((rows) => rows[0] ?? null) - ]); - return Boolean(run || deferredWake); - } - async function enqueueStrandedIssueRecovery(input) { - const queued = await enqueueWakeup(input.agentId, { - source: "automation", - triggerDetail: "system", - reason: input.reason, - payload: { - issueId: input.issueId, - ...input.retryOfRunId ? { retryOfRunId: input.retryOfRunId } : {} - }, - requestedByActorType: "system", - requestedByActorId: null, - contextSnapshot: { - issueId: input.issueId, - taskId: input.issueId, - wakeReason: input.reason, - retryReason: input.retryReason, - source: input.source, - ...input.retryOfRunId ? { retryOfRunId: input.retryOfRunId } : {} - } - }); - if (queued && input.retryOfRunId) { - return db.update(heartbeatRuns).set({ - retryOfRunId: input.retryOfRunId, - updatedAt: /* @__PURE__ */ new Date() - }).where(eq(heartbeatRuns.id, queued.id)).returning().then((rows) => rows[0] ?? queued); - } - return queued; - } - async function escalateStrandedAssignedIssue(input) { - const updated = await issuesSvc.update(input.issue.id, { - status: "blocked" - }); - if (!updated) return null; - await issuesSvc.addComment(input.issue.id, input.comment, {}); - await logActivity(db, { - companyId: input.issue.companyId, - actorType: "system", - actorId: "system", - agentId: null, - runId: null, - action: "issue.updated", - entityType: "issue", - entityId: input.issue.id, - details: { - identifier: input.issue.identifier, - status: "blocked", - previousStatus: input.previousStatus, - source: "heartbeat.reconcile_stranded_assigned_issue", - latestRunId: input.latestRun?.id ?? null, - latestRunStatus: input.latestRun?.status ?? null, - latestRunErrorCode: input.latestRun?.errorCode ?? null - } - }); - return updated; - } - async function reconcileStrandedAssignedIssues() { - const candidates = await db.select().from(issues).where( - and( - isNull(issues.assigneeUserId), - inArray(issues.status, ["todo", "in_progress"]), - sql`${issues.assigneeAgentId} is not null` - ) - ); - const result = { - dispatchRequeued: 0, - continuationRequeued: 0, - escalated: 0, - skipped: 0, - issueIds: [] - }; - for (const issue2 of candidates) { - const agentId = issue2.assigneeAgentId; - if (!agentId) { - result.skipped += 1; - continue; - } - const agent = await getAgent(agentId); - if (!agent || agent.companyId !== issue2.companyId) { - result.skipped += 1; - continue; - } - if (agent.status === "paused" || agent.status === "terminated" || agent.status === "pending_approval") { - result.skipped += 1; - continue; - } - if (await hasActiveExecutionPath(issue2.companyId, issue2.id)) { - result.skipped += 1; - continue; - } - const latestRun = await getLatestIssueRun(issue2.companyId, issue2.id); - const latestContext = parseObject4(latestRun?.contextSnapshot); - const latestRetryReason = readNonEmptyString10(latestContext.retryReason); - if (issue2.status === "todo") { - if (!latestRun || latestRun.status === "succeeded") { - result.skipped += 1; - continue; - } - if (latestRetryReason === "assignment_recovery") { - const updated = await escalateStrandedAssignedIssue({ - issue: issue2, - previousStatus: "todo", - latestRun, - comment: "Taskcore automatically retried dispatch for this assigned `todo` issue after a lost wake/run, but it still has no live execution path. Moving it to `blocked` so it is visible for intervention." - }); - if (updated) { - result.escalated += 1; - result.issueIds.push(issue2.id); - } else { - result.skipped += 1; - } - continue; - } - const queued2 = await enqueueStrandedIssueRecovery({ - issueId: issue2.id, - agentId, - reason: "issue_assignment_recovery", - retryReason: "assignment_recovery", - source: "issue.assignment_recovery", - retryOfRunId: latestRun.id - }); - if (queued2) { - result.dispatchRequeued += 1; - result.issueIds.push(issue2.id); - } else { - result.skipped += 1; - } - continue; - } - if (latestRetryReason === "issue_continuation_needed") { - const updated = await escalateStrandedAssignedIssue({ - issue: issue2, - previousStatus: "in_progress", - latestRun, - comment: "Taskcore automatically retried continuation for this assigned `in_progress` issue after its live execution disappeared, but it still has no live execution path. Moving it to `blocked` so it is visible for intervention." - }); - if (updated) { - result.escalated += 1; - result.issueIds.push(issue2.id); - } else { - result.skipped += 1; - } - continue; - } - const queued = await enqueueStrandedIssueRecovery({ - issueId: issue2.id, - agentId, - reason: "issue_continuation_needed", - retryReason: "issue_continuation_needed", - source: "issue.continuation_recovery", - retryOfRunId: latestRun?.id ?? issue2.checkoutRunId ?? null - }); - if (queued) { - result.continuationRequeued += 1; - result.issueIds.push(issue2.id); - } else { - result.skipped += 1; - } - } - return result; - } - async function updateRuntimeState(agent, run, result, session, normalizedUsage) { - await ensureRuntimeState(agent); - const usage = normalizedUsage ?? normalizeUsageTotals(result.usage); - const inputTokens = usage?.inputTokens ?? 0; - const outputTokens = usage?.outputTokens ?? 0; - const cachedInputTokens = usage?.cachedInputTokens ?? 0; - const billingType = normalizeLedgerBillingType(result.billingType); - const additionalCostCents = normalizeBilledCostCents(result.costUsd, billingType); - const hasTokenUsage = inputTokens > 0 || outputTokens > 0 || cachedInputTokens > 0; - const provider = result.provider ?? "unknown"; - const biller = resolveLedgerBiller(result); - const ledgerScope = await resolveLedgerScopeForRun(db, agent.companyId, run); - await db.update(agentRuntimeState).set({ - adapterType: agent.adapterType, - sessionId: session.legacySessionId, - lastRunId: run.id, - lastRunStatus: run.status, - lastError: result.errorMessage ?? null, - totalInputTokens: sql`${agentRuntimeState.totalInputTokens} + ${inputTokens}`, - totalOutputTokens: sql`${agentRuntimeState.totalOutputTokens} + ${outputTokens}`, - totalCachedInputTokens: sql`${agentRuntimeState.totalCachedInputTokens} + ${cachedInputTokens}`, - totalCostCents: sql`${agentRuntimeState.totalCostCents} + ${additionalCostCents}`, - updatedAt: /* @__PURE__ */ new Date() - }).where(eq(agentRuntimeState.agentId, agent.id)); - if (additionalCostCents > 0 || hasTokenUsage) { - const costs = costService(db, budgetHooks); - await costs.createEvent(agent.companyId, { - heartbeatRunId: run.id, - agentId: agent.id, - issueId: ledgerScope.issueId, - projectId: ledgerScope.projectId, - provider, - biller, - billingType, - model: result.model ?? "unknown", - inputTokens, - cachedInputTokens, - outputTokens, - costCents: additionalCostCents, - occurredAt: /* @__PURE__ */ new Date() - }); - } - } - async function startNextQueuedRunForAgent(agentId) { - return withAgentStartLock(agentId, async () => { - const agent = await getAgent(agentId); - if (!agent) return []; - if (agent.status === "paused" || agent.status === "terminated" || agent.status === "pending_approval") { - return []; - } - const policy = parseHeartbeatPolicy(agent); - const runningCount = await countRunningRunsForAgent(agentId); - const availableSlots = Math.max(0, policy.maxConcurrentRuns - runningCount); - if (availableSlots <= 0) return []; - const queuedRuns = await db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.agentId, agentId), eq(heartbeatRuns.status, "queued"))).orderBy(asc(heartbeatRuns.createdAt)).limit(availableSlots); - if (queuedRuns.length === 0) return []; - const claimedRuns = []; - for (const queuedRun of queuedRuns) { - const claimed = await claimQueuedRun(queuedRun); - if (claimed) claimedRuns.push(claimed); - } - if (claimedRuns.length === 0) return []; - for (const claimedRun of claimedRuns) { - void executeRun(claimedRun.id).catch((err) => { - logger.error({ err, runId: claimedRun.id }, "queued heartbeat execution failed"); - }); - } - return claimedRuns; - }); - } - async function executeRun(runId) { - let run = await getRun(runId); - if (!run) return; - if (run.status !== "queued" && run.status !== "running") return; - if (run.status === "queued") { - const claimed = await claimQueuedRun(run); - if (!claimed) { - return; - } - run = claimed; - } - activeRunExecutions.add(run.id); - try { - const agent = await getAgent(run.agentId); - if (!agent) { - await setRunStatus(runId, "failed", { - error: "Agent not found", - errorCode: "agent_not_found", - finishedAt: /* @__PURE__ */ new Date() - }); - await setWakeupStatus(run.wakeupRequestId, "failed", { - finishedAt: /* @__PURE__ */ new Date(), - error: "Agent not found" - }); - const failedRun = await getRun(runId); - if (failedRun) await releaseIssueExecutionAndPromote(failedRun); - return; - } - const runtime = await ensureRuntimeState(agent); - const context = parseObject4(run.contextSnapshot); - const taskKey = deriveTaskKeyWithHeartbeatFallback(context, null); - const sessionCodec8 = getAdapterSessionCodec(agent.adapterType); - const issueId = readNonEmptyString10(context.issueId); - let issueContext = issueId ? await getIssueExecutionContext(agent.companyId, issueId) : null; - if (issueId && issueContext && shouldAutoCheckoutIssueForWake({ - contextSnapshot: context, - issueStatus: issueContext.status, - issueAssigneeAgentId: issueContext.assigneeAgentId, - agentId: agent.id - })) { - try { - await issuesSvc.checkout(issueId, agent.id, ["todo", "backlog", "blocked"], run.id); - context[TASKCORE_HARNESS_CHECKOUT_KEY] = true; - } catch (error50) { - if (!isCheckoutConflictError(error50)) throw error50; - context[TASKCORE_HARNESS_CHECKOUT_KEY] = false; - } - issueContext = await getIssueExecutionContext(agent.companyId, issueId); - } - const issueAssigneeOverrides = issueContext && issueContext.assigneeAgentId === agent.id ? parseIssueAssigneeAdapterOverrides( - issueContext.assigneeAdapterOverrides - ) : null; - const isolatedWorkspacesEnabled = (await instanceSettings2.getExperimental()).enableIsolatedWorkspaces; - const issueExecutionWorkspaceSettings = isolatedWorkspacesEnabled ? parseIssueExecutionWorkspaceSettings(issueContext?.executionWorkspaceSettings) : null; - const contextProjectId = readNonEmptyString10(context.projectId); - const executionProjectId = issueContext?.projectId ?? contextProjectId; - const projectContext = executionProjectId ? await db.select({ - executionWorkspacePolicy: projects.executionWorkspacePolicy, - env: projects.env - }).from(projects).where(and(eq(projects.id, executionProjectId), eq(projects.companyId, agent.companyId))).then((rows) => rows[0] ?? null) : null; - const projectExecutionWorkspacePolicy = gateProjectExecutionWorkspacePolicy( - parseProjectExecutionWorkspacePolicy(projectContext?.executionWorkspacePolicy), - isolatedWorkspacesEnabled - ); - const taskSession = taskKey ? await getTaskSession(agent.companyId, agent.id, agent.adapterType, taskKey) : null; - const resetTaskSession = shouldResetTaskSessionForWake(context); - const sessionResetReason = describeSessionResetReason(context); - const taskSessionForRun = resetTaskSession ? null : taskSession; - const explicitResumeSessionParams = normalizeSessionParams( - sessionCodec8.deserialize(parseObject4(context.resumeSessionParams)) - ); - const explicitResumeSessionDisplayId = truncateDisplayId( - readNonEmptyString10(context.resumeSessionDisplayId) ?? (sessionCodec8.getDisplayId ? sessionCodec8.getDisplayId(explicitResumeSessionParams) : null) ?? readNonEmptyString10(explicitResumeSessionParams?.sessionId) - ); - const previousSessionParams = explicitResumeSessionParams ?? (explicitResumeSessionDisplayId ? { sessionId: explicitResumeSessionDisplayId } : null) ?? normalizeSessionParams(sessionCodec8.deserialize(taskSessionForRun?.sessionParamsJson ?? null)); - const config3 = parseObject4(agent.adapterConfig); - const requestedExecutionWorkspaceMode = resolveExecutionWorkspaceMode({ - projectPolicy: projectExecutionWorkspacePolicy, - issueSettings: issueExecutionWorkspaceSettings, - legacyUseProjectWorkspace: issueAssigneeOverrides?.useProjectWorkspace ?? null - }); - const resolvedWorkspace = await resolveWorkspaceForRun( - agent, - context, - previousSessionParams, - { useProjectWorkspace: requestedExecutionWorkspaceMode !== "agent_default" } - ); - const issueRef = issueContext ? { - id: issueContext.id, - identifier: issueContext.identifier, - title: issueContext.title, - status: issueContext.status, - priority: issueContext.priority, - projectId: issueContext.projectId, - projectWorkspaceId: issueContext.projectWorkspaceId, - executionWorkspaceId: issueContext.executionWorkspaceId, - executionWorkspacePreference: issueContext.executionWorkspacePreference - } : null; - const taskcoreWakePayload = await buildTaskcoreWakePayload({ - db, - companyId: agent.companyId, - contextSnapshot: context, - issueSummary: issueRef ? { - id: issueRef.id, - identifier: issueRef.identifier, - title: issueRef.title, - status: issueRef.status, - priority: issueRef.priority - } : null - }); - if (taskcoreWakePayload) { - context[TASKCORE_WAKE_PAYLOAD_KEY] = taskcoreWakePayload; - } else { - delete context[TASKCORE_WAKE_PAYLOAD_KEY]; - } - const existingExecutionWorkspace = issueRef?.executionWorkspaceId ? await executionWorkspacesSvc.getById(issueRef.executionWorkspaceId) : null; - const shouldReuseExisting = issueRef?.executionWorkspacePreference === "reuse_existing" && existingExecutionWorkspace && existingExecutionWorkspace.status !== "archived"; - const persistedExecutionWorkspaceMode = shouldReuseExisting && existingExecutionWorkspace ? issueExecutionWorkspaceModeForPersistedWorkspace(existingExecutionWorkspace.mode) : null; - const effectiveExecutionWorkspaceMode = persistedExecutionWorkspaceMode === "isolated_workspace" || persistedExecutionWorkspaceMode === "operator_branch" || persistedExecutionWorkspaceMode === "agent_default" ? persistedExecutionWorkspaceMode : requestedExecutionWorkspaceMode; - const workspaceManagedConfig = shouldReuseExisting ? { ...config3 } : buildExecutionWorkspaceAdapterConfig({ - agentConfig: config3, - projectPolicy: projectExecutionWorkspacePolicy, - issueSettings: issueExecutionWorkspaceSettings, - mode: requestedExecutionWorkspaceMode, - legacyUseProjectWorkspace: issueAssigneeOverrides?.useProjectWorkspace ?? null - }); - const persistedWorkspaceManagedConfig = applyPersistedExecutionWorkspaceConfig({ - config: workspaceManagedConfig, - workspaceConfig: existingExecutionWorkspace?.config ?? null, - mode: effectiveExecutionWorkspaceMode - }); - const mergedConfig = issueAssigneeOverrides?.adapterConfig ? { ...persistedWorkspaceManagedConfig, ...issueAssigneeOverrides.adapterConfig } : persistedWorkspaceManagedConfig; - const configSnapshot = buildExecutionWorkspaceConfigSnapshot(mergedConfig); - const executionRunConfig = stripWorkspaceRuntimeFromExecutionRunConfig(mergedConfig); - const { resolvedConfig, secretKeys } = await resolveExecutionRunAdapterConfig({ - companyId: agent.companyId, - executionRunConfig, - projectEnv: projectContext?.env ?? null, - secretsSvc - }); - const runScopedMentionedSkillKeys = await resolveRunScopedMentionedSkillKeys({ - db, - companyId: agent.companyId, - issueId - }); - const effectiveResolvedConfig = applyRunScopedMentionedSkillKeys( - resolvedConfig, - runScopedMentionedSkillKeys - ); - const runtimeSkillEntries = await companySkills2.listRuntimeSkillEntries(agent.companyId); - const runtimeConfig = { - ...effectiveResolvedConfig, - taskcoreRuntimeSkills: runtimeSkillEntries - }; - const workspaceOperationRecorder = workspaceOperationsSvc.createRecorder({ - companyId: agent.companyId, - heartbeatRunId: run.id, - executionWorkspaceId: existingExecutionWorkspace?.id ?? null - }); - const executionWorkspaceBase = { - baseCwd: resolvedWorkspace.cwd, - source: resolvedWorkspace.source, - projectId: resolvedWorkspace.projectId, - workspaceId: resolvedWorkspace.workspaceId, - repoUrl: resolvedWorkspace.repoUrl, - repoRef: resolvedWorkspace.repoRef - }; - const reusedExecutionWorkspace = shouldReuseExisting && existingExecutionWorkspace ? buildRealizedExecutionWorkspaceFromPersisted({ - base: executionWorkspaceBase, - workspace: existingExecutionWorkspace - }) : null; - const executionWorkspace = reusedExecutionWorkspace ?? await realizeExecutionWorkspace({ - base: executionWorkspaceBase, - config: runtimeConfig, - issue: issueRef, - agent: { - id: agent.id, - name: agent.name, - companyId: agent.companyId - }, - recorder: workspaceOperationRecorder - }); - const resolvedProjectId = executionWorkspace.projectId ?? issueRef?.projectId ?? executionProjectId ?? null; - const resolvedProjectWorkspaceId = issueRef?.projectWorkspaceId ?? resolvedWorkspace.workspaceId ?? null; - let persistedExecutionWorkspace = null; - const nextExecutionWorkspaceMetadataBase = { - ...existingExecutionWorkspace?.metadata ?? {}, - source: executionWorkspace.source, - createdByRuntime: executionWorkspace.created - }; - const nextExecutionWorkspaceMetadata = shouldReuseExisting ? nextExecutionWorkspaceMetadataBase : configSnapshot ? mergeExecutionWorkspaceConfig(nextExecutionWorkspaceMetadataBase, configSnapshot) : nextExecutionWorkspaceMetadataBase; - try { - persistedExecutionWorkspace = shouldReuseExisting && existingExecutionWorkspace ? await executionWorkspacesSvc.update(existingExecutionWorkspace.id, { - cwd: executionWorkspace.cwd, - repoUrl: executionWorkspace.repoUrl, - baseRef: executionWorkspace.repoRef, - branchName: executionWorkspace.branchName, - providerType: executionWorkspace.strategy === "git_worktree" ? "git_worktree" : "local_fs", - providerRef: executionWorkspace.worktreePath, - status: "active", - lastUsedAt: /* @__PURE__ */ new Date(), - metadata: nextExecutionWorkspaceMetadata - }) : resolvedProjectId ? await executionWorkspacesSvc.create({ - companyId: agent.companyId, - projectId: resolvedProjectId, - projectWorkspaceId: resolvedProjectWorkspaceId, - sourceIssueId: issueRef?.id ?? null, - mode: requestedExecutionWorkspaceMode === "isolated_workspace" ? "isolated_workspace" : requestedExecutionWorkspaceMode === "operator_branch" ? "operator_branch" : requestedExecutionWorkspaceMode === "agent_default" ? "adapter_managed" : "shared_workspace", - strategyType: executionWorkspace.strategy === "git_worktree" ? "git_worktree" : "project_primary", - name: executionWorkspace.branchName ?? issueRef?.identifier ?? `workspace-${agent.id.slice(0, 8)}`, - status: "active", - cwd: executionWorkspace.cwd, - repoUrl: executionWorkspace.repoUrl, - baseRef: executionWorkspace.repoRef, - branchName: executionWorkspace.branchName, - providerType: executionWorkspace.strategy === "git_worktree" ? "git_worktree" : "local_fs", - providerRef: executionWorkspace.worktreePath, - lastUsedAt: /* @__PURE__ */ new Date(), - openedAt: /* @__PURE__ */ new Date(), - metadata: nextExecutionWorkspaceMetadata - }) : null; - } catch (error50) { - if (executionWorkspace.created) { - try { - await cleanupExecutionWorkspaceArtifacts({ - workspace: { - id: existingExecutionWorkspace?.id ?? `transient-${run.id}`, - cwd: executionWorkspace.cwd, - providerType: executionWorkspace.strategy === "git_worktree" ? "git_worktree" : "local_fs", - providerRef: executionWorkspace.worktreePath, - branchName: executionWorkspace.branchName, - repoUrl: executionWorkspace.repoUrl, - baseRef: executionWorkspace.repoRef, - projectId: resolvedProjectId, - projectWorkspaceId: resolvedProjectWorkspaceId, - sourceIssueId: issueRef?.id ?? null, - metadata: { - createdByRuntime: true, - source: executionWorkspace.source - } - }, - projectWorkspace: { - cwd: resolvedWorkspace.cwd, - cleanupCommand: null - }, - cleanupCommand: configSnapshot?.cleanupCommand ?? null, - teardownCommand: configSnapshot?.teardownCommand ?? projectExecutionWorkspacePolicy?.workspaceStrategy?.teardownCommand ?? null, - recorder: workspaceOperationRecorder - }); - } catch (cleanupError) { - logger.warn( - { - runId: run.id, - issueId, - executionWorkspaceCwd: executionWorkspace.cwd, - cleanupError: cleanupError instanceof Error ? cleanupError.message : String(cleanupError) - }, - "Failed to cleanup realized execution workspace after persistence failure" - ); - } - } - throw error50; - } - await workspaceOperationRecorder.attachExecutionWorkspaceId(persistedExecutionWorkspace?.id ?? null); - if (existingExecutionWorkspace && persistedExecutionWorkspace && existingExecutionWorkspace.id !== persistedExecutionWorkspace.id && existingExecutionWorkspace.status === "active") { - await executionWorkspacesSvc.update(existingExecutionWorkspace.id, { - status: "idle", - cleanupReason: null - }); - } - if (issueId && persistedExecutionWorkspace) { - const nextIssueWorkspaceMode = issueExecutionWorkspaceModeForPersistedWorkspace(persistedExecutionWorkspace.mode); - const shouldSwitchIssueToExistingWorkspace = issueRef?.executionWorkspacePreference === "reuse_existing" || requestedExecutionWorkspaceMode === "isolated_workspace" || requestedExecutionWorkspaceMode === "operator_branch"; - const nextIssuePatch = {}; - if (issueRef?.executionWorkspaceId !== persistedExecutionWorkspace.id) { - nextIssuePatch.executionWorkspaceId = persistedExecutionWorkspace.id; - } - if (resolvedProjectWorkspaceId && issueRef?.projectWorkspaceId !== resolvedProjectWorkspaceId) { - nextIssuePatch.projectWorkspaceId = resolvedProjectWorkspaceId; - } - if (shouldSwitchIssueToExistingWorkspace) { - nextIssuePatch.executionWorkspacePreference = "reuse_existing"; - nextIssuePatch.executionWorkspaceSettings = { - ...issueExecutionWorkspaceSettings ?? {}, - mode: nextIssueWorkspaceMode - }; - } - if (Object.keys(nextIssuePatch).length > 0) { - await issuesSvc.update(issueId, nextIssuePatch); - } - } - if (persistedExecutionWorkspace) { - context.executionWorkspaceId = persistedExecutionWorkspace.id; - await db.update(heartbeatRuns).set({ - contextSnapshot: context, - updatedAt: /* @__PURE__ */ new Date() - }).where(eq(heartbeatRuns.id, run.id)); - } - const runtimeSessionResolution = resolveRuntimeSessionParamsForWorkspace({ - agentId: agent.id, - previousSessionParams, - resolvedWorkspace: { - ...resolvedWorkspace, - cwd: executionWorkspace.cwd - } - }); - const runtimeSessionParams = runtimeSessionResolution.sessionParams; - const runtimeWorkspaceWarnings = [ - ...resolvedWorkspace.warnings, - ...executionWorkspace.warnings, - ...runtimeSessionResolution.warning ? [runtimeSessionResolution.warning] : [], - ...resetTaskSession && sessionResetReason ? [ - taskKey ? `Skipping saved session resume for task "${taskKey}" because ${sessionResetReason}.` : `Skipping saved session resume because ${sessionResetReason}.` - ] : [] - ]; - context.taskcoreWorkspace = { - cwd: executionWorkspace.cwd, - source: executionWorkspace.source, - mode: effectiveExecutionWorkspaceMode, - strategy: executionWorkspace.strategy, - projectId: executionWorkspace.projectId, - workspaceId: executionWorkspace.workspaceId, - repoUrl: executionWorkspace.repoUrl, - repoRef: executionWorkspace.repoRef, - branchName: executionWorkspace.branchName, - worktreePath: executionWorkspace.worktreePath, - agentHome: await (async () => { - const home = resolveDefaultAgentWorkspaceDir(agent.id); - await fs32.mkdir(home, { recursive: true }); - return home; - })() - }; - context.taskcoreWorkspaces = resolvedWorkspace.workspaceHints; - const runtimeServiceIntents = (() => { - const runtimeConfig2 = parseObject4(resolvedConfig.workspaceRuntime); - return Array.isArray(runtimeConfig2.services) ? runtimeConfig2.services.filter( - (value) => typeof value === "object" && value !== null - ) : []; - })(); - if (runtimeServiceIntents.length > 0) { - context.taskcoreRuntimeServiceIntents = runtimeServiceIntents; - } else { - delete context.taskcoreRuntimeServiceIntents; - } - if (executionWorkspace.projectId && !readNonEmptyString10(context.projectId)) { - context.projectId = executionWorkspace.projectId; - } - const runtimeSessionFallback = taskKey || resetTaskSession ? null : runtime.sessionId; - let previousSessionDisplayId = truncateDisplayId( - explicitResumeSessionDisplayId ?? taskSessionForRun?.sessionDisplayId ?? (sessionCodec8.getDisplayId ? sessionCodec8.getDisplayId(runtimeSessionParams) : null) ?? readNonEmptyString10(runtimeSessionParams?.sessionId) ?? runtimeSessionFallback - ); - let runtimeSessionIdForAdapter = readNonEmptyString10(runtimeSessionParams?.sessionId) ?? runtimeSessionFallback; - let runtimeSessionParamsForAdapter = runtimeSessionParams; - const sessionCompaction = await evaluateSessionCompaction({ - agent, - sessionId: previousSessionDisplayId ?? runtimeSessionIdForAdapter, - issueId - }); - if (sessionCompaction.rotate) { - context.taskcoreSessionHandoffMarkdown = sessionCompaction.handoffMarkdown; - context.taskcoreSessionRotationReason = sessionCompaction.reason; - context.taskcorePreviousSessionId = previousSessionDisplayId ?? runtimeSessionIdForAdapter; - runtimeSessionIdForAdapter = null; - runtimeSessionParamsForAdapter = null; - previousSessionDisplayId = null; - if (sessionCompaction.reason) { - runtimeWorkspaceWarnings.push( - `Starting a fresh session because ${sessionCompaction.reason}.` - ); - } - } else { - delete context.taskcoreSessionHandoffMarkdown; - delete context.taskcoreSessionRotationReason; - delete context.taskcorePreviousSessionId; - } - const runtimeForAdapter = { - sessionId: runtimeSessionIdForAdapter, - sessionParams: runtimeSessionParamsForAdapter, - sessionDisplayId: previousSessionDisplayId, - taskKey - }; - let seq = 1; - let handle = null; - let stdoutExcerpt = ""; - let stderrExcerpt = ""; - try { - const startedAt = run.startedAt ?? /* @__PURE__ */ new Date(); - const runningWithSession = await db.update(heartbeatRuns).set({ - startedAt, - sessionIdBefore: runtimeForAdapter.sessionDisplayId ?? runtimeForAdapter.sessionId, - contextSnapshot: context, - updatedAt: /* @__PURE__ */ new Date() - }).where(eq(heartbeatRuns.id, run.id)).returning().then((rows) => rows[0] ?? null); - if (runningWithSession) run = runningWithSession; - const runningAgent = await db.update(agents).set({ status: "running", updatedAt: /* @__PURE__ */ new Date() }).where(eq(agents.id, agent.id)).returning().then((rows) => rows[0] ?? null); - if (runningAgent) { - publishLiveEvent({ - companyId: runningAgent.companyId, - type: "agent.status", - payload: { - agentId: runningAgent.id, - status: runningAgent.status, - outcome: "running" - } - }); - } - const currentRun = run; - await appendRunEvent(currentRun, seq++, { - eventType: "lifecycle", - stream: "system", - level: "info", - message: "run started" - }); - handle = await runLogStore.begin({ - companyId: run.companyId, - agentId: run.agentId, - runId - }); - await db.update(heartbeatRuns).set({ - logStore: handle.store, - logRef: handle.logRef, - updatedAt: /* @__PURE__ */ new Date() - }).where(eq(heartbeatRuns.id, runId)); - const currentUserRedactionOptions = await getCurrentUserRedactionOptions(); - const onLog = async (stream, chunk) => { - const sanitizedChunk = compactRunLogChunk( - redactCurrentUserText(chunk, currentUserRedactionOptions) - ); - if (stream === "stdout") stdoutExcerpt = appendExcerpt2(stdoutExcerpt, sanitizedChunk); - if (stream === "stderr") stderrExcerpt = appendExcerpt2(stderrExcerpt, sanitizedChunk); - const ts = (/* @__PURE__ */ new Date()).toISOString(); - if (handle) { - await runLogStore.append(handle, { - stream, - chunk: sanitizedChunk, - ts - }); - } - const payloadChunk = sanitizedChunk.length > MAX_LIVE_LOG_CHUNK_BYTES ? sanitizedChunk.slice(sanitizedChunk.length - MAX_LIVE_LOG_CHUNK_BYTES) : sanitizedChunk; - publishLiveEvent({ - companyId: run.companyId, - type: "heartbeat.run.log", - payload: { - runId: run.id, - agentId: run.agentId, - ts, - stream, - chunk: payloadChunk, - truncated: payloadChunk.length !== sanitizedChunk.length - } - }); - }; - if (runScopedMentionedSkillKeys.length > 0) { - await onLog( - "stdout", - `[taskcore] Enabled run-scoped skills from issue mentions: ${runScopedMentionedSkillKeys.join(", ")} -` - ); - } - for (const warning of runtimeWorkspaceWarnings) { - const logEntry = formatRuntimeWorkspaceWarningLog(warning); - await onLog(logEntry.stream, logEntry.chunk); - } - const adapterEnv = Object.fromEntries( - Object.entries(parseObject4(resolvedConfig.env)).filter( - (entry) => typeof entry[0] === "string" && typeof entry[1] === "string" - ) - ); - const runtimeServices = await ensureRuntimeServicesForRun({ - db, - runId: run.id, - agent: { - id: agent.id, - name: agent.name, - companyId: agent.companyId - }, - issue: issueRef, - workspace: executionWorkspace, - executionWorkspaceId: persistedExecutionWorkspace?.id ?? issueRef?.executionWorkspaceId ?? null, - config: effectiveResolvedConfig, - adapterEnv, - onLog - }); - if (runtimeServices.length > 0) { - context.taskcoreRuntimeServices = runtimeServices; - context.taskcoreRuntimePrimaryUrl = runtimeServices.find((service) => readNonEmptyString10(service.url))?.url ?? null; - await db.update(heartbeatRuns).set({ - contextSnapshot: context, - updatedAt: /* @__PURE__ */ new Date() - }).where(eq(heartbeatRuns.id, run.id)); - } - if (issueId && (executionWorkspace.created || runtimeServices.some((service) => !service.reused))) { - try { - await issuesSvc.addComment( - issueId, - buildWorkspaceReadyComment({ - workspace: executionWorkspace, - runtimeServices - }), - { agentId: agent.id, runId: run.id } - ); - } catch (err) { - await onLog( - "stderr", - `[taskcore] Failed to post workspace-ready comment: ${err instanceof Error ? err.message : String(err)} -` - ); - } - } - const onAdapterMeta = async (meta3) => { - if (meta3.env && secretKeys.size > 0) { - for (const key of secretKeys) { - if (key in meta3.env) meta3.env[key] = "***REDACTED***"; - } - } - await appendRunEvent(currentRun, seq++, { - eventType: "adapter.invoke", - stream: "system", - level: "info", - message: "adapter invocation", - payload: meta3 - }); - }; - const adapter = getServerAdapter(agent.adapterType); - const authToken = adapter.supportsLocalAgentJwt ? createLocalAgentJwt(agent.id, agent.companyId, agent.adapterType, run.id) : null; - if (adapter.supportsLocalAgentJwt && !authToken) { - logger.warn( - { - companyId: agent.companyId, - agentId: agent.id, - runId: run.id, - adapterType: agent.adapterType - }, - "local agent jwt secret missing or invalid; running without injected TASKCORE_API_KEY" - ); - } - const adapterResult = await adapter.execute({ - runId: run.id, - agent, - runtime: runtimeForAdapter, - config: runtimeConfig, - context, - onLog, - onMeta: onAdapterMeta, - onSpawn: async (meta3) => { - await persistRunProcessMetadata(run.id, { - pid: meta3.pid, - processGroupId: "processGroupId" in meta3 && typeof meta3.processGroupId === "number" ? meta3.processGroupId : null, - startedAt: meta3.startedAt - }); - }, - authToken: authToken ?? void 0 - }); - const adapterManagedRuntimeServices = adapterResult.runtimeServices ? await persistAdapterManagedRuntimeServices({ - db, - adapterType: agent.adapterType, - runId: run.id, - agent: { - id: agent.id, - name: agent.name, - companyId: agent.companyId - }, - issue: issueRef, - workspace: executionWorkspace, - reports: adapterResult.runtimeServices - }) : []; - if (adapterManagedRuntimeServices.length > 0) { - const combinedRuntimeServices = [ - ...runtimeServices, - ...adapterManagedRuntimeServices - ]; - context.taskcoreRuntimeServices = combinedRuntimeServices; - context.taskcoreRuntimePrimaryUrl = combinedRuntimeServices.find((service) => readNonEmptyString10(service.url))?.url ?? null; - await db.update(heartbeatRuns).set({ - contextSnapshot: context, - updatedAt: /* @__PURE__ */ new Date() - }).where(eq(heartbeatRuns.id, run.id)); - if (issueId) { - try { - await issuesSvc.addComment( - issueId, - buildWorkspaceReadyComment({ - workspace: executionWorkspace, - runtimeServices: adapterManagedRuntimeServices - }), - { agentId: agent.id, runId: run.id } - ); - } catch (err) { - await onLog( - "stderr", - `[taskcore] Failed to post adapter-managed runtime comment: ${err instanceof Error ? err.message : String(err)} -` - ); - } - } - } - const nextSessionState = resolveNextSessionState({ - codec: sessionCodec8, - adapterResult, - previousParams: previousSessionParams, - previousDisplayId: runtimeForAdapter.sessionDisplayId, - previousLegacySessionId: runtimeForAdapter.sessionId - }); - const rawUsage = normalizeUsageTotals(adapterResult.usage); - const sessionUsageResolution = await resolveNormalizedUsageForSession({ - agentId: agent.id, - runId: run.id, - sessionId: nextSessionState.displayId ?? nextSessionState.legacySessionId, - rawUsage - }); - const normalizedUsage = sessionUsageResolution.normalizedUsage; - let outcome; - const latestRun = await getRun(run.id); - if (latestRun?.status === "cancelled") { - outcome = "cancelled"; - } else if (adapterResult.timedOut) { - outcome = "timed_out"; - } else if ((adapterResult.exitCode ?? 0) === 0 && !adapterResult.errorMessage) { - outcome = "succeeded"; - } else { - outcome = "failed"; - } - let logSummary = null; - if (handle) { - logSummary = await runLogStore.finalize(handle); - } - const status = outcome === "succeeded" ? "succeeded" : outcome === "cancelled" ? "cancelled" : outcome === "timed_out" ? "timed_out" : "failed"; - const usageJson = normalizedUsage || adapterResult.costUsd != null ? { - ...normalizedUsage ?? {}, - ...rawUsage ? { - rawInputTokens: rawUsage.inputTokens, - rawCachedInputTokens: rawUsage.cachedInputTokens, - rawOutputTokens: rawUsage.outputTokens - } : {}, - ...sessionUsageResolution.derivedFromSessionTotals ? { usageSource: "session_delta" } : {}, - ...nextSessionState.displayId ?? nextSessionState.legacySessionId ? { persistedSessionId: nextSessionState.displayId ?? nextSessionState.legacySessionId } : {}, - sessionReused: runtimeForAdapter.sessionId != null || runtimeForAdapter.sessionDisplayId != null, - taskSessionReused: taskSessionForRun != null, - freshSession: runtimeForAdapter.sessionId == null && runtimeForAdapter.sessionDisplayId == null, - sessionRotated: sessionCompaction.rotate, - sessionRotationReason: sessionCompaction.reason, - provider: readNonEmptyString10(adapterResult.provider) ?? "unknown", - biller: resolveLedgerBiller(adapterResult), - model: readNonEmptyString10(adapterResult.model) ?? "unknown", - ...adapterResult.costUsd != null ? { costUsd: adapterResult.costUsd } : {}, - billingType: normalizeLedgerBillingType(adapterResult.billingType) - } : null; - const persistedResultJson = mergeHeartbeatRunResultJson( - adapterResult.resultJson ?? null, - adapterResult.summary ?? null - ); - await setRunStatus(run.id, status, { - finishedAt: /* @__PURE__ */ new Date(), - error: outcome === "succeeded" ? null : redactCurrentUserText( - adapterResult.errorMessage ?? (outcome === "timed_out" ? "Timed out" : "Adapter failed"), - currentUserRedactionOptions - ), - errorCode: outcome === "timed_out" ? "timeout" : outcome === "cancelled" ? "cancelled" : outcome === "failed" ? adapterResult.errorCode ?? "adapter_failed" : null, - exitCode: adapterResult.exitCode, - signal: adapterResult.signal, - usageJson, - resultJson: persistedResultJson, - sessionIdAfter: nextSessionState.displayId ?? nextSessionState.legacySessionId, - stdoutExcerpt, - stderrExcerpt, - logBytes: logSummary?.bytes, - logSha256: logSummary?.sha256, - logCompressed: logSummary?.compressed ?? false - }); - await setWakeupStatus(run.wakeupRequestId, outcome === "succeeded" ? "completed" : status, { - finishedAt: /* @__PURE__ */ new Date(), - error: adapterResult.errorMessage ?? null - }); - const finalizedRun = await getRun(run.id); - if (finalizedRun) { - await appendRunEvent(finalizedRun, seq++, { - eventType: "lifecycle", - stream: "system", - level: outcome === "succeeded" ? "info" : "error", - message: `run ${outcome}`, - payload: { - status, - exitCode: adapterResult.exitCode - } - }); - if (issueId && outcome === "succeeded") { - try { - const existingRunComment = await findRunIssueComment(finalizedRun.id, finalizedRun.companyId, issueId); - if (!existingRunComment) { - const issueComment = buildHeartbeatRunIssueComment(persistedResultJson); - if (issueComment) { - await issuesSvc.addComment(issueId, issueComment, { agentId: agent.id, runId: finalizedRun.id }); - } - } - } catch (err) { - await onLog( - "stderr", - `[taskcore] Failed to post run summary comment: ${err instanceof Error ? err.message : String(err)} -` - ); - } - } - await finalizeIssueCommentPolicy(finalizedRun, agent); - await releaseIssueExecutionAndPromote(finalizedRun); - } - if (finalizedRun) { - await updateRuntimeState(agent, finalizedRun, adapterResult, { - legacySessionId: nextSessionState.legacySessionId - }, normalizedUsage); - if (taskKey) { - if (adapterResult.clearSession || !nextSessionState.params && !nextSessionState.displayId) { - await clearTaskSessions(agent.companyId, agent.id, { - taskKey, - adapterType: agent.adapterType - }); - } else { - await upsertTaskSession({ - companyId: agent.companyId, - agentId: agent.id, - adapterType: agent.adapterType, - taskKey, - sessionParamsJson: nextSessionState.params, - sessionDisplayId: nextSessionState.displayId, - lastRunId: finalizedRun.id, - lastError: outcome === "succeeded" ? null : adapterResult.errorMessage ?? "run_failed" - }); - } - } - } - await finalizeAgentStatus(agent.id, outcome); - } catch (err) { - const message2 = redactCurrentUserText( - err instanceof Error ? err.message : "Unknown adapter failure", - await getCurrentUserRedactionOptions() - ); - logger.error({ err, runId }, "heartbeat execution failed"); - let logSummary = null; - if (handle) { - try { - logSummary = await runLogStore.finalize(handle); - } catch (finalizeErr) { - logger.warn({ err: finalizeErr, runId }, "failed to finalize run log after error"); - } - } - const failedRun = await setRunStatus(run.id, "failed", { - error: message2, - errorCode: "adapter_failed", - finishedAt: /* @__PURE__ */ new Date(), - stdoutExcerpt, - stderrExcerpt, - logBytes: logSummary?.bytes, - logSha256: logSummary?.sha256, - logCompressed: logSummary?.compressed ?? false - }); - await setWakeupStatus(run.wakeupRequestId, "failed", { - finishedAt: /* @__PURE__ */ new Date(), - error: message2 - }); - if (failedRun) { - await appendRunEvent(failedRun, seq++, { - eventType: "error", - stream: "system", - level: "error", - message: message2 - }); - await finalizeIssueCommentPolicy(failedRun, agent); - await releaseIssueExecutionAndPromote(failedRun); - await updateRuntimeState(agent, failedRun, { - exitCode: null, - signal: null, - timedOut: false, - errorMessage: message2 - }, { - legacySessionId: runtimeForAdapter.sessionId - }); - if (taskKey && (previousSessionParams || previousSessionDisplayId || taskSession)) { - await upsertTaskSession({ - companyId: agent.companyId, - agentId: agent.id, - adapterType: agent.adapterType, - taskKey, - sessionParamsJson: previousSessionParams, - sessionDisplayId: previousSessionDisplayId, - lastRunId: failedRun.id, - lastError: message2 - }); - } - } - await finalizeAgentStatus(agent.id, "failed"); - } - } catch (outerErr) { - const message2 = outerErr instanceof Error ? outerErr.message : "Unknown setup failure"; - logger.error({ err: outerErr, runId }, "heartbeat execution setup failed"); - await setRunStatus(runId, "failed", { - error: message2, - errorCode: "adapter_failed", - finishedAt: /* @__PURE__ */ new Date() - }).catch(() => void 0); - await setWakeupStatus(run.wakeupRequestId, "failed", { - finishedAt: /* @__PURE__ */ new Date(), - error: message2 - }).catch(() => void 0); - const failedRun = await getRun(runId).catch(() => null); - if (failedRun) { - await appendRunEvent(failedRun, 1, { - eventType: "error", - stream: "system", - level: "error", - message: message2 - }).catch(() => void 0); - const failedAgent = await getAgent(run.agentId).catch(() => null); - if (failedAgent) { - await finalizeIssueCommentPolicy(failedRun, failedAgent).catch(() => void 0); - } - await releaseIssueExecutionAndPromote(failedRun).catch(() => void 0); - } - await finalizeAgentStatus(run.agentId, "failed").catch(() => void 0); - } finally { - await releaseRuntimeServicesForRun(run.id).catch(() => void 0); - activeRunExecutions.delete(run.id); - await startNextQueuedRunForAgent(run.agentId); - } - } - async function releaseIssueExecutionAndPromote(run) { - const runContext = parseObject4(run.contextSnapshot); - const contextIssueId = readNonEmptyString10(runContext.issueId); - const promotionResult = await db.transaction(async (tx) => { - if (contextIssueId) { - await tx.execute( - sql`select id from issues where company_id = ${run.companyId} and id = ${contextIssueId} for update` - ); - } else { - await tx.execute( - sql`select id from issues where company_id = ${run.companyId} and execution_run_id = ${run.id} for update` - ); - } - let issue2 = await tx.select({ - id: issues.id, - companyId: issues.companyId, - identifier: issues.identifier, - status: issues.status, - executionRunId: issues.executionRunId - }).from(issues).where( - and( - eq(issues.companyId, run.companyId), - contextIssueId ? eq(issues.id, contextIssueId) : eq(issues.executionRunId, run.id) - ) - ).then((rows) => rows[0] ?? null); - if (!issue2) return null; - if (issue2.executionRunId && issue2.executionRunId !== run.id) return null; - if (issue2.executionRunId === run.id) { - await tx.update(issues).set({ - executionRunId: null, - executionAgentNameKey: null, - executionLockedAt: null, - updatedAt: /* @__PURE__ */ new Date() - }).where(eq(issues.id, issue2.id)); - } - while (true) { - const deferred = await tx.select().from(agentWakeupRequests).where( - and( - eq(agentWakeupRequests.companyId, issue2.companyId), - eq(agentWakeupRequests.status, "deferred_issue_execution"), - sql`${agentWakeupRequests.payload} ->> 'issueId' = ${issue2.id}` - ) - ).orderBy(asc(agentWakeupRequests.requestedAt)).limit(1).then((rows) => rows[0] ?? null); - if (!deferred) return null; - const deferredAgent = await tx.select().from(agents).where(eq(agents.id, deferred.agentId)).then((rows) => rows[0] ?? null); - if (!deferredAgent || deferredAgent.companyId !== issue2.companyId || deferredAgent.status === "paused" || deferredAgent.status === "terminated" || deferredAgent.status === "pending_approval") { - await tx.update(agentWakeupRequests).set({ - status: "failed", - finishedAt: /* @__PURE__ */ new Date(), - error: "Deferred wake could not be promoted: agent is not invokable", - updatedAt: /* @__PURE__ */ new Date() - }).where(eq(agentWakeupRequests.id, deferred.id)); - continue; - } - const deferredPayload = parseObject4(deferred.payload); - const deferredContextSeed = parseObject4(deferredPayload[DEFERRED_WAKE_CONTEXT_KEY]); - const promotedContextSeed = { ...deferredContextSeed }; - const deferredCommentIds = extractWakeCommentIds(deferredContextSeed); - const shouldReopenDeferredCommentWake = deferredCommentIds.length > 0 && (issue2.status === "done" || issue2.status === "cancelled"); - let reopenedActivity = null; - if (shouldReopenDeferredCommentWake) { - const reopenedFromStatus = issue2.status; - const reopenedIssue = await issuesSvc.update( - issue2.id, - { - status: "todo", - executionState: null - }, - tx - ); - if (reopenedIssue) { - issue2 = { - ...issue2, - identifier: reopenedIssue.identifier, - status: reopenedIssue.status, - executionRunId: reopenedIssue.executionRunId - }; - if (!readNonEmptyString10(promotedContextSeed.reopenedFrom)) { - promotedContextSeed.reopenedFrom = reopenedFromStatus; - } - reopenedActivity = { - companyId: issue2.companyId, - actorType: "system", - actorId: "heartbeat", - agentId: deferred.agentId, - runId: run.id, - action: "issue.updated", - entityType: "issue", - entityId: issue2.id, - details: { - status: "todo", - reopened: true, - reopenedFrom: reopenedFromStatus, - source: "deferred_comment_wake", - identifier: issue2.identifier - } - }; - } - } - const promotedReason = readNonEmptyString10(deferred.reason) ?? "issue_execution_promoted"; - const promotedSource = readNonEmptyString10(deferred.source) ?? "automation"; - const promotedTriggerDetail = readNonEmptyString10(deferred.triggerDetail) ?? null; - const promotedPayload = deferredPayload; - delete promotedPayload[DEFERRED_WAKE_CONTEXT_KEY]; - const { - contextSnapshot: promotedContextSnapshot, - taskKey: promotedTaskKey - } = enrichWakeContextSnapshot({ - contextSnapshot: promotedContextSeed, - reason: promotedReason, - source: promotedSource, - triggerDetail: promotedTriggerDetail, - payload: promotedPayload - }); - const sessionBefore = readNonEmptyString10(promotedContextSnapshot.resumeSessionDisplayId) ?? await resolveSessionBeforeForWakeup(deferredAgent, promotedTaskKey); - const now2 = /* @__PURE__ */ new Date(); - const newRun = await tx.insert(heartbeatRuns).values({ - companyId: deferredAgent.companyId, - agentId: deferredAgent.id, - invocationSource: promotedSource, - triggerDetail: promotedTriggerDetail, - status: "queued", - wakeupRequestId: deferred.id, - contextSnapshot: promotedContextSnapshot, - sessionIdBefore: sessionBefore - }).returning().then((rows) => rows[0]); - await tx.update(agentWakeupRequests).set({ - status: "queued", - reason: "issue_execution_promoted", - runId: newRun.id, - claimedAt: null, - finishedAt: null, - error: null, - updatedAt: now2 - }).where(eq(agentWakeupRequests.id, deferred.id)); - await tx.update(issues).set({ - executionRunId: newRun.id, - executionAgentNameKey: normalizeAgentNameKey(deferredAgent.name), - executionLockedAt: now2, - updatedAt: now2 - }).where(eq(issues.id, issue2.id)); - return { - run: newRun, - reopenedActivity - }; - } - }); - const promotedRun = promotionResult?.run ?? null; - if (!promotedRun) return; - if (promotionResult?.reopenedActivity) { - await logActivity(db, promotionResult.reopenedActivity); - } - publishLiveEvent({ - companyId: promotedRun.companyId, - type: "heartbeat.run.queued", - payload: { - runId: promotedRun.id, - agentId: promotedRun.agentId, - invocationSource: promotedRun.invocationSource, - triggerDetail: promotedRun.triggerDetail, - wakeupRequestId: promotedRun.wakeupRequestId - } - }); - await startNextQueuedRunForAgent(promotedRun.agentId); - } - async function enqueueWakeup(agentId, opts = {}) { - const source = opts.source ?? "on_demand"; - const triggerDetail = opts.triggerDetail ?? null; - const contextSnapshot = { ...opts.contextSnapshot ?? {} }; - const reason = opts.reason ?? null; - const payload2 = opts.payload ?? null; - const { - contextSnapshot: enrichedContextSnapshot, - issueIdFromPayload, - taskKey, - wakeCommentId - } = enrichWakeContextSnapshot({ - contextSnapshot, - reason, - source, - triggerDetail, - payload: payload2 - }); - let issueId = readNonEmptyString10(enrichedContextSnapshot.issueId) ?? issueIdFromPayload; - const agent = await getAgent(agentId); - if (!agent) throw notFound("Agent not found"); - const explicitResumeSession = await resolveExplicitResumeSessionOverride(agent, payload2, taskKey); - if (explicitResumeSession) { - enrichedContextSnapshot.resumeFromRunId = explicitResumeSession.resumeFromRunId; - enrichedContextSnapshot.resumeSessionDisplayId = explicitResumeSession.sessionDisplayId; - enrichedContextSnapshot.resumeSessionParams = explicitResumeSession.sessionParams; - if (!readNonEmptyString10(enrichedContextSnapshot.issueId) && explicitResumeSession.issueId) { - enrichedContextSnapshot.issueId = explicitResumeSession.issueId; - } - if (!readNonEmptyString10(enrichedContextSnapshot.taskId) && explicitResumeSession.taskId) { - enrichedContextSnapshot.taskId = explicitResumeSession.taskId; - } - if (!readNonEmptyString10(enrichedContextSnapshot.taskKey) && explicitResumeSession.taskKey) { - enrichedContextSnapshot.taskKey = explicitResumeSession.taskKey; - } - issueId = readNonEmptyString10(enrichedContextSnapshot.issueId) ?? issueId; - } - const effectiveTaskKey = readNonEmptyString10(enrichedContextSnapshot.taskKey) ?? taskKey; - const sessionBefore = explicitResumeSession?.sessionDisplayId ?? await resolveSessionBeforeForWakeup(agent, effectiveTaskKey); - const writeSkippedRequest = async (skipReason) => { - await db.insert(agentWakeupRequests).values({ - companyId: agent.companyId, - agentId, - source, - triggerDetail, - reason: skipReason, - payload: payload2, - status: "skipped", - requestedByActorType: opts.requestedByActorType ?? null, - requestedByActorId: opts.requestedByActorId ?? null, - idempotencyKey: opts.idempotencyKey ?? null, - finishedAt: /* @__PURE__ */ new Date() - }); - }; - let projectId = readNonEmptyString10(enrichedContextSnapshot.projectId); - if (!projectId && issueId) { - projectId = await db.select({ projectId: issues.projectId }).from(issues).where(and(eq(issues.id, issueId), eq(issues.companyId, agent.companyId))).then((rows) => rows[0]?.projectId ?? null); - } - const budgetBlock = await budgets.getInvocationBlock(agent.companyId, agentId, { - issueId, - projectId - }); - if (budgetBlock) { - await writeSkippedRequest("budget.blocked"); - throw conflict(budgetBlock.reason, { - scopeType: budgetBlock.scopeType, - scopeId: budgetBlock.scopeId - }); - } - if (agent.status === "paused" || agent.status === "terminated" || agent.status === "pending_approval") { - throw conflict("Agent is not invokable in its current state", { status: agent.status }); - } - const policy = parseHeartbeatPolicy(agent); - if (source === "timer" && !policy.enabled) { - await writeSkippedRequest("heartbeat.disabled"); - return null; - } - if (source !== "timer" && !policy.wakeOnDemand) { - await writeSkippedRequest("heartbeat.wakeOnDemand.disabled"); - return null; - } - if (issueId) { - const agentNameKey = normalizeAgentNameKey(agent.name); - const outcome = await db.transaction(async (tx) => { - await tx.execute( - sql`select id from issues where id = ${issueId} and company_id = ${agent.companyId} for update` - ); - const issue2 = await tx.select({ - id: issues.id, - companyId: issues.companyId, - executionRunId: issues.executionRunId, - executionAgentNameKey: issues.executionAgentNameKey - }).from(issues).where(and(eq(issues.id, issueId), eq(issues.companyId, agent.companyId))).then((rows) => rows[0] ?? null); - if (!issue2) { - await tx.insert(agentWakeupRequests).values({ - companyId: agent.companyId, - agentId, - source, - triggerDetail, - reason: "issue_execution_issue_not_found", - payload: payload2, - status: "skipped", - requestedByActorType: opts.requestedByActorType ?? null, - requestedByActorId: opts.requestedByActorId ?? null, - idempotencyKey: opts.idempotencyKey ?? null, - finishedAt: /* @__PURE__ */ new Date() - }); - return { kind: "skipped" }; - } - let activeExecutionRun = issue2.executionRunId ? await tx.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, issue2.executionRunId)).then((rows) => rows[0] ?? null) : null; - if (activeExecutionRun && activeExecutionRun.status !== "queued" && activeExecutionRun.status !== "running") { - activeExecutionRun = null; - } - if (!activeExecutionRun && issue2.executionRunId) { - await tx.update(issues).set({ - executionRunId: null, - executionAgentNameKey: null, - executionLockedAt: null, - updatedAt: /* @__PURE__ */ new Date() - }).where(eq(issues.id, issue2.id)); - } - if (!activeExecutionRun) { - const legacyRun = await tx.select().from(heartbeatRuns).where( - and( - eq(heartbeatRuns.companyId, issue2.companyId), - inArray(heartbeatRuns.status, ["queued", "running"]), - sql`${heartbeatRuns.contextSnapshot} ->> 'issueId' = ${issue2.id}` - ) - ).orderBy( - sql`case when ${heartbeatRuns.status} = 'running' then 0 else 1 end`, - asc(heartbeatRuns.createdAt) - ).limit(1).then((rows) => rows[0] ?? null); - if (legacyRun) { - activeExecutionRun = legacyRun; - const legacyAgent = await tx.select({ name: agents.name }).from(agents).where(eq(agents.id, legacyRun.agentId)).then((rows) => rows[0] ?? null); - await tx.update(issues).set({ - executionRunId: legacyRun.id, - executionAgentNameKey: normalizeAgentNameKey(legacyAgent?.name), - executionLockedAt: /* @__PURE__ */ new Date(), - updatedAt: /* @__PURE__ */ new Date() - }).where(eq(issues.id, issue2.id)); - } - } - if (activeExecutionRun) { - const executionAgent = await tx.select({ name: agents.name }).from(agents).where(eq(agents.id, activeExecutionRun.agentId)).then((rows) => rows[0] ?? null); - const executionAgentNameKey = normalizeAgentNameKey(issue2.executionAgentNameKey) ?? normalizeAgentNameKey(executionAgent?.name); - const isSameExecutionAgent = Boolean(executionAgentNameKey) && executionAgentNameKey === agentNameKey; - const shouldQueueFollowupForCommentWake2 = Boolean(wakeCommentId) && activeExecutionRun.status === "running" && isSameExecutionAgent; - if (isSameExecutionAgent && !shouldQueueFollowupForCommentWake2) { - const mergedContextSnapshot = mergeCoalescedContextSnapshot( - activeExecutionRun.contextSnapshot, - enrichedContextSnapshot - ); - const mergedRun = await tx.update(heartbeatRuns).set({ - contextSnapshot: mergedContextSnapshot, - updatedAt: /* @__PURE__ */ new Date() - }).where(eq(heartbeatRuns.id, activeExecutionRun.id)).returning().then((rows) => rows[0] ?? activeExecutionRun); - await tx.insert(agentWakeupRequests).values({ - companyId: agent.companyId, - agentId, - source, - triggerDetail, - reason: "issue_execution_same_name", - payload: payload2, - status: "coalesced", - coalescedCount: 1, - requestedByActorType: opts.requestedByActorType ?? null, - requestedByActorId: opts.requestedByActorId ?? null, - idempotencyKey: opts.idempotencyKey ?? null, - runId: mergedRun.id, - finishedAt: /* @__PURE__ */ new Date() - }); - return { kind: "coalesced", run: mergedRun }; - } - const deferredPayload = { - ...payload2 ?? {}, - issueId, - [DEFERRED_WAKE_CONTEXT_KEY]: enrichedContextSnapshot - }; - const existingDeferred = await tx.select().from(agentWakeupRequests).where( - and( - eq(agentWakeupRequests.companyId, agent.companyId), - eq(agentWakeupRequests.agentId, agentId), - eq(agentWakeupRequests.status, "deferred_issue_execution"), - sql`${agentWakeupRequests.payload} ->> 'issueId' = ${issue2.id}` - ) - ).orderBy(asc(agentWakeupRequests.requestedAt)).limit(1).then((rows) => rows[0] ?? null); - if (existingDeferred) { - const existingDeferredPayload = parseObject4(existingDeferred.payload); - const existingDeferredContext = parseObject4(existingDeferredPayload[DEFERRED_WAKE_CONTEXT_KEY]); - const mergedDeferredContext = mergeCoalescedContextSnapshot( - existingDeferredContext, - enrichedContextSnapshot - ); - const mergedDeferredPayload = { - ...existingDeferredPayload, - ...payload2 ?? {}, - issueId, - [DEFERRED_WAKE_CONTEXT_KEY]: mergedDeferredContext - }; - await tx.update(agentWakeupRequests).set({ - payload: mergedDeferredPayload, - coalescedCount: (existingDeferred.coalescedCount ?? 0) + 1, - updatedAt: /* @__PURE__ */ new Date() - }).where(eq(agentWakeupRequests.id, existingDeferred.id)); - return { kind: "deferred" }; - } - await tx.insert(agentWakeupRequests).values({ - companyId: agent.companyId, - agentId, - source, - triggerDetail, - reason: "issue_execution_deferred", - payload: deferredPayload, - status: "deferred_issue_execution", - requestedByActorType: opts.requestedByActorType ?? null, - requestedByActorId: opts.requestedByActorId ?? null, - idempotencyKey: opts.idempotencyKey ?? null - }); - return { kind: "deferred" }; - } - const wakeupRequest2 = await tx.insert(agentWakeupRequests).values({ - companyId: agent.companyId, - agentId, - source, - triggerDetail, - reason, - payload: payload2, - status: "queued", - requestedByActorType: opts.requestedByActorType ?? null, - requestedByActorId: opts.requestedByActorId ?? null, - idempotencyKey: opts.idempotencyKey ?? null - }).returning().then((rows) => rows[0]); - const newRun3 = await tx.insert(heartbeatRuns).values({ - companyId: agent.companyId, - agentId, - invocationSource: source, - triggerDetail, - status: "queued", - wakeupRequestId: wakeupRequest2.id, - contextSnapshot: enrichedContextSnapshot, - sessionIdBefore: sessionBefore - }).returning().then((rows) => rows[0]); - await tx.update(agentWakeupRequests).set({ - runId: newRun3.id, - updatedAt: /* @__PURE__ */ new Date() - }).where(eq(agentWakeupRequests.id, wakeupRequest2.id)); - return { kind: "queued", run: newRun3 }; - }); - if (outcome.kind === "deferred" || outcome.kind === "skipped") return null; - if (outcome.kind === "coalesced") return outcome.run; - const newRun2 = outcome.run; - publishLiveEvent({ - companyId: newRun2.companyId, - type: "heartbeat.run.queued", - payload: { - runId: newRun2.id, - agentId: newRun2.agentId, - invocationSource: newRun2.invocationSource, - triggerDetail: newRun2.triggerDetail, - wakeupRequestId: newRun2.wakeupRequestId - } - }); - await startNextQueuedRunForAgent(agent.id); - return newRun2; - } - const activeRuns = await db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.agentId, agentId), inArray(heartbeatRuns.status, ["queued", "running"]))).orderBy(desc(heartbeatRuns.createdAt)); - const sameScopeQueuedRun = activeRuns.find( - (candidate) => candidate.status === "queued" && isSameTaskScope(runTaskKey(candidate), taskKey) - ); - const sameScopeRunningRun = activeRuns.find( - (candidate) => candidate.status === "running" && isSameTaskScope(runTaskKey(candidate), taskKey) - ); - const shouldQueueFollowupForCommentWake = Boolean(wakeCommentId) && Boolean(sameScopeRunningRun) && !sameScopeQueuedRun; - const coalescedTargetRun = sameScopeQueuedRun ?? (shouldQueueFollowupForCommentWake ? null : sameScopeRunningRun ?? null); - if (coalescedTargetRun) { - const mergedContextSnapshot = mergeCoalescedContextSnapshot( - coalescedTargetRun.contextSnapshot, - contextSnapshot - ); - const mergedRun = await db.update(heartbeatRuns).set({ - contextSnapshot: mergedContextSnapshot, - updatedAt: /* @__PURE__ */ new Date() - }).where(eq(heartbeatRuns.id, coalescedTargetRun.id)).returning().then((rows) => rows[0] ?? coalescedTargetRun); - await db.insert(agentWakeupRequests).values({ - companyId: agent.companyId, - agentId, - source, - triggerDetail, - reason, - payload: payload2, - status: "coalesced", - coalescedCount: 1, - requestedByActorType: opts.requestedByActorType ?? null, - requestedByActorId: opts.requestedByActorId ?? null, - idempotencyKey: opts.idempotencyKey ?? null, - runId: mergedRun.id, - finishedAt: /* @__PURE__ */ new Date() - }); - return mergedRun; - } - const wakeupRequest = await db.insert(agentWakeupRequests).values({ - companyId: agent.companyId, - agentId, - source, - triggerDetail, - reason, - payload: payload2, - status: "queued", - requestedByActorType: opts.requestedByActorType ?? null, - requestedByActorId: opts.requestedByActorId ?? null, - idempotencyKey: opts.idempotencyKey ?? null - }).returning().then((rows) => rows[0]); - const newRun = await db.insert(heartbeatRuns).values({ - companyId: agent.companyId, - agentId, - invocationSource: source, - triggerDetail, - status: "queued", - wakeupRequestId: wakeupRequest.id, - contextSnapshot: enrichedContextSnapshot, - sessionIdBefore: sessionBefore - }).returning().then((rows) => rows[0]); - await db.update(agentWakeupRequests).set({ - runId: newRun.id, - updatedAt: /* @__PURE__ */ new Date() - }).where(eq(agentWakeupRequests.id, wakeupRequest.id)); - publishLiveEvent({ - companyId: newRun.companyId, - type: "heartbeat.run.queued", - payload: { - runId: newRun.id, - agentId: newRun.agentId, - invocationSource: newRun.invocationSource, - triggerDetail: newRun.triggerDetail, - wakeupRequestId: newRun.wakeupRequestId - } - }); - await startNextQueuedRunForAgent(agent.id); - return newRun; - } - async function listProjectScopedRunIds(companyId, projectId) { - const runIssueId = sql`${heartbeatRuns.contextSnapshot} ->> 'issueId'`; - const effectiveProjectId = sql`coalesce(${heartbeatRuns.contextSnapshot} ->> 'projectId', ${issues.projectId}::text)`; - const rows = await db.selectDistinctOn([heartbeatRuns.id], { id: heartbeatRuns.id }).from(heartbeatRuns).leftJoin( - issues, - and( - eq(issues.companyId, companyId), - sql`${issues.id}::text = ${runIssueId}` - ) - ).where( - and( - eq(heartbeatRuns.companyId, companyId), - inArray(heartbeatRuns.status, ["queued", "running"]), - sql`${effectiveProjectId} = ${projectId}` - ) - ); - return rows.map((row) => row.id); - } - async function listProjectScopedWakeupIds(companyId, projectId) { - const wakeIssueId = sql`${agentWakeupRequests.payload} ->> 'issueId'`; - const effectiveProjectId = sql`coalesce(${agentWakeupRequests.payload} ->> 'projectId', ${issues.projectId}::text)`; - const rows = await db.selectDistinctOn([agentWakeupRequests.id], { id: agentWakeupRequests.id }).from(agentWakeupRequests).leftJoin( - issues, - and( - eq(issues.companyId, companyId), - sql`${issues.id}::text = ${wakeIssueId}` - ) - ).where( - and( - eq(agentWakeupRequests.companyId, companyId), - inArray(agentWakeupRequests.status, ["queued", "deferred_issue_execution"]), - sql`${agentWakeupRequests.runId} is null`, - sql`${effectiveProjectId} = ${projectId}` - ) - ); - return rows.map((row) => row.id); - } - async function cancelPendingWakeupsForBudgetScope(scope) { - const now2 = /* @__PURE__ */ new Date(); - let wakeupIds = []; - if (scope.scopeType === "company") { - wakeupIds = await db.select({ id: agentWakeupRequests.id }).from(agentWakeupRequests).where( - and( - eq(agentWakeupRequests.companyId, scope.companyId), - inArray(agentWakeupRequests.status, ["queued", "deferred_issue_execution"]), - sql`${agentWakeupRequests.runId} is null` - ) - ).then((rows) => rows.map((row) => row.id)); - } else if (scope.scopeType === "agent") { - wakeupIds = await db.select({ id: agentWakeupRequests.id }).from(agentWakeupRequests).where( - and( - eq(agentWakeupRequests.companyId, scope.companyId), - eq(agentWakeupRequests.agentId, scope.scopeId), - inArray(agentWakeupRequests.status, ["queued", "deferred_issue_execution"]), - sql`${agentWakeupRequests.runId} is null` - ) - ).then((rows) => rows.map((row) => row.id)); - } else { - wakeupIds = await listProjectScopedWakeupIds(scope.companyId, scope.scopeId); - } - if (wakeupIds.length === 0) return 0; - await db.update(agentWakeupRequests).set({ - status: "cancelled", - finishedAt: now2, - error: "Cancelled due to budget pause", - updatedAt: now2 - }).where(inArray(agentWakeupRequests.id, wakeupIds)); - return wakeupIds.length; - } - async function cancelRunInternal(runId, reason = "Cancelled by control plane") { - const run = await getRun(runId); - if (!run) throw notFound("Heartbeat run not found"); - if (run.status !== "running" && run.status !== "queued") return run; - const running = runningProcesses3.get(run.id); - if (running) { - await terminateHeartbeatRunProcess({ - pid: running.child.pid ?? run.processPid, - processGroupId: running.processGroupId ?? run.processGroupId, - graceMs: Math.max(1, running.graceSec) * 1e3 - }); - } else if (run.processPid || run.processGroupId) { - await terminateHeartbeatRunProcess({ - pid: run.processPid, - processGroupId: run.processGroupId - }); - } - const cancelled = await setRunStatus(run.id, "cancelled", { - finishedAt: /* @__PURE__ */ new Date(), - error: reason, - errorCode: "cancelled" - }); - await setWakeupStatus(run.wakeupRequestId, "cancelled", { - finishedAt: /* @__PURE__ */ new Date(), - error: reason - }); - if (cancelled) { - await appendRunEvent(cancelled, 1, { - eventType: "lifecycle", - stream: "system", - level: "warn", - message: "run cancelled" - }); - await releaseIssueExecutionAndPromote(cancelled); - } - runningProcesses3.delete(run.id); - await finalizeAgentStatus(run.agentId, "cancelled"); - await startNextQueuedRunForAgent(run.agentId); - return cancelled; - } - async function cancelActiveForAgentInternal(agentId, reason = "Cancelled due to agent pause") { - const runs = await db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.agentId, agentId), inArray(heartbeatRuns.status, ["queued", "running"]))); - for (const run of runs) { - await setRunStatus(run.id, "cancelled", { - finishedAt: /* @__PURE__ */ new Date(), - error: reason, - errorCode: "cancelled" - }); - await setWakeupStatus(run.wakeupRequestId, "cancelled", { - finishedAt: /* @__PURE__ */ new Date(), - error: reason - }); - const running = runningProcesses3.get(run.id); - if (running) { - await terminateHeartbeatRunProcess({ - pid: running.child.pid ?? run.processPid, - processGroupId: running.processGroupId ?? run.processGroupId, - graceMs: Math.max(1, running.graceSec) * 1e3 - }); - runningProcesses3.delete(run.id); - } else if (run.processPid || run.processGroupId) { - await terminateHeartbeatRunProcess({ - pid: run.processPid, - processGroupId: run.processGroupId - }); - } - await releaseIssueExecutionAndPromote(run); - } - return runs.length; - } - async function cancelBudgetScopeWork(scope) { - if (scope.scopeType === "agent") { - await cancelActiveForAgentInternal(scope.scopeId, "Cancelled due to budget pause"); - await cancelPendingWakeupsForBudgetScope(scope); - return; - } - const runIds = scope.scopeType === "company" ? await db.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where( - and( - eq(heartbeatRuns.companyId, scope.companyId), - inArray(heartbeatRuns.status, ["queued", "running"]) - ) - ).then((rows) => rows.map((row) => row.id)) : await listProjectScopedRunIds(scope.companyId, scope.scopeId); - for (const runId of runIds) { - await cancelRunInternal(runId, "Cancelled due to budget pause"); - } - await cancelPendingWakeupsForBudgetScope(scope); - } - return { - list: async (companyId, agentId, limit) => { - const query = db.select(heartbeatRunListColumns).from(heartbeatRuns).where( - agentId ? and(eq(heartbeatRuns.companyId, companyId), eq(heartbeatRuns.agentId, agentId)) : eq(heartbeatRuns.companyId, companyId) - ).orderBy(desc(heartbeatRuns.createdAt)); - const rows = limit ? await query.limit(limit) : await query; - return rows.map((row) => ({ - ...row, - resultJson: summarizeHeartbeatRunResultJson(row.resultJson) - })); - }, - getRun, - getRuntimeState: async (agentId) => { - const state2 = await getRuntimeState(agentId); - const agent = await getAgent(agentId); - if (!agent) return null; - const ensured = state2 ?? await ensureRuntimeState(agent); - const latestTaskSession = await db.select().from(agentTaskSessions).where(and(eq(agentTaskSessions.companyId, agent.companyId), eq(agentTaskSessions.agentId, agent.id))).orderBy(desc(agentTaskSessions.updatedAt)).limit(1).then((rows) => rows[0] ?? null); - return { - ...ensured, - sessionDisplayId: latestTaskSession?.sessionDisplayId ?? ensured.sessionId, - sessionParamsJson: latestTaskSession?.sessionParamsJson ?? null - }; - }, - listTaskSessions: async (agentId) => { - const agent = await getAgent(agentId); - if (!agent) throw notFound("Agent not found"); - return db.select().from(agentTaskSessions).where(and(eq(agentTaskSessions.companyId, agent.companyId), eq(agentTaskSessions.agentId, agentId))).orderBy(desc(agentTaskSessions.updatedAt), desc(agentTaskSessions.createdAt)); - }, - resetRuntimeSession: async (agentId, opts) => { - const agent = await getAgent(agentId); - if (!agent) throw notFound("Agent not found"); - await ensureRuntimeState(agent); - const taskKey = readNonEmptyString10(opts?.taskKey); - const clearedTaskSessions = await clearTaskSessions( - agent.companyId, - agent.id, - taskKey ? { taskKey, adapterType: agent.adapterType } : void 0 - ); - const runtimePatch = { - sessionId: null, - lastError: null, - updatedAt: /* @__PURE__ */ new Date() - }; - if (!taskKey) { - runtimePatch.stateJson = {}; - } - const updated = await db.update(agentRuntimeState).set(runtimePatch).where(eq(agentRuntimeState.agentId, agentId)).returning().then((rows) => rows[0] ?? null); - if (!updated) return null; - return { - ...updated, - sessionDisplayId: null, - sessionParamsJson: null, - clearedTaskSessions - }; - }, - listEvents: (runId, afterSeq = 0, limit = 200) => db.select().from(heartbeatRunEvents).where(and(eq(heartbeatRunEvents.runId, runId), gt(heartbeatRunEvents.seq, afterSeq))).orderBy(asc(heartbeatRunEvents.seq)).limit(Math.max(1, Math.min(limit, 1e3))), - readLog: async (runId, opts) => { - const run = await getRun(runId); - if (!run) throw notFound("Heartbeat run not found"); - if (!run.logStore || !run.logRef) throw notFound("Run log not found"); - const result = await runLogStore.read( - { - store: run.logStore, - logRef: run.logRef - }, - opts - ); - return { - runId, - store: run.logStore, - logRef: run.logRef, - ...result, - content: redactCurrentUserText(result.content, await getCurrentUserRedactionOptions()) - }; - }, - invoke: async (agentId, source = "on_demand", contextSnapshot = {}, triggerDetail = "manual", actor) => enqueueWakeup(agentId, { - source, - triggerDetail, - contextSnapshot, - requestedByActorType: actor?.actorType, - requestedByActorId: actor?.actorId ?? null - }), - wakeup: enqueueWakeup, - reportRunActivity: clearDetachedRunWarning, - reapOrphanedRuns, - resumeQueuedRuns, - reconcileStrandedAssignedIssues, - tickTimers: async (now2 = /* @__PURE__ */ new Date()) => { - const allAgents = await db.select().from(agents); - let checked = 0; - let enqueued = 0; - let skipped = 0; - for (const agent of allAgents) { - if (agent.status === "paused" || agent.status === "terminated" || agent.status === "pending_approval") continue; - const policy = parseHeartbeatPolicy(agent); - if (!policy.enabled || policy.intervalSec <= 0) continue; - checked += 1; - const baseline = new Date(agent.lastHeartbeatAt ?? agent.createdAt).getTime(); - const elapsedMs = now2.getTime() - baseline; - if (elapsedMs < policy.intervalSec * 1e3) continue; - const run = await enqueueWakeup(agent.id, { - source: "timer", - triggerDetail: "system", - reason: "heartbeat_timer", - requestedByActorType: "system", - requestedByActorId: "heartbeat_scheduler", - contextSnapshot: { - source: "scheduler", - reason: "interval_elapsed", - now: now2.toISOString() - } - }); - if (run) enqueued += 1; - else skipped += 1; - } - return { checked, enqueued, skipped }; - }, - cancelRun: (runId) => cancelRunInternal(runId), - cancelActiveForAgent: (agentId) => cancelActiveForAgentInternal(agentId), - cancelBudgetScopeWork, - getRunIssueSummary: async (runId) => { - const [run] = await db.select(heartbeatRunIssueSummaryColumns).from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)).limit(1); - return run ?? null; - }, - getActiveRunForAgent: async (agentId) => { - const [run] = await db.select().from(heartbeatRuns).where( - and( - eq(heartbeatRuns.agentId, agentId), - eq(heartbeatRuns.status, "running") - ) - ).orderBy(desc(heartbeatRuns.startedAt)).limit(1); - return run ?? null; - }, - getActiveRunIssueSummaryForAgent: async (agentId) => { - const [run] = await db.select(heartbeatRunIssueSummaryColumns).from(heartbeatRuns).where( - and( - eq(heartbeatRuns.agentId, agentId), - eq(heartbeatRuns.status, "running") - ) - ).orderBy(desc(heartbeatRuns.startedAt)).limit(1); - return run ?? null; - } - }; -} - -// server/src/services/issue-assignment-wakeup.ts -function queueIssueAssignmentWakeup(input) { - if (!input.issue.assigneeAgentId || input.issue.status === "backlog") return; - return input.heartbeat.wakeup(input.issue.assigneeAgentId, { - source: "assignment", - triggerDetail: "system", - reason: input.reason, - payload: { issueId: input.issue.id, mutation: input.mutation }, - requestedByActorType: input.requestedByActorType, - requestedByActorId: input.requestedByActorId ?? null, - contextSnapshot: { issueId: input.issue.id, source: input.contextSource } - }).catch((err) => { - logger.warn({ err, issueId: input.issue.id }, "failed to wake assignee on issue assignment"); - if (input.rethrowOnError) throw err; - return null; - }); -} - -// server/src/services/routines.ts -var OPEN_ISSUE_STATUSES = ["backlog", "todo", "in_progress", "in_review", "blocked"]; -var LIVE_HEARTBEAT_RUN_STATUSES = ["queued", "running"]; -var MAX_CATCH_UP_RUNS = 25; -var WEEKDAY_INDEX = { - Sun: 0, - Mon: 1, - Tue: 2, - Wed: 3, - Thu: 4, - Fri: 5, - Sat: 6 -}; -function assertTimeZone(timeZone) { - try { - new Intl.DateTimeFormat("en-US", { timeZone }).format(/* @__PURE__ */ new Date()); - } catch { - throw unprocessable(`Invalid timezone: ${timeZone}`); - } -} -function floorToMinute(date7) { - const copy = new Date(date7.getTime()); - copy.setUTCSeconds(0, 0); - return copy; -} -function getZonedMinuteParts(date7, timeZone) { - const formatter = new Intl.DateTimeFormat("en-US", { - timeZone, - hour12: false, - year: "numeric", - month: "numeric", - day: "numeric", - hour: "numeric", - minute: "numeric", - weekday: "short" - }); - const parts = formatter.formatToParts(date7); - const map4 = Object.fromEntries(parts.map((part) => [part.type, part.value])); - const weekday = WEEKDAY_INDEX[map4.weekday ?? ""]; - if (weekday == null) { - throw new Error(`Unable to resolve weekday for timezone ${timeZone}`); - } - return { - year: Number(map4.year), - month: Number(map4.month), - day: Number(map4.day), - hour: Number(map4.hour), - minute: Number(map4.minute), - weekday - }; -} -function matchesCronMinute(expression, timeZone, date7) { - const cron = parseCron(expression); - const parts = getZonedMinuteParts(date7, timeZone); - return cron.minutes.includes(parts.minute) && cron.hours.includes(parts.hour) && cron.daysOfMonth.includes(parts.day) && cron.months.includes(parts.month) && cron.daysOfWeek.includes(parts.weekday); -} -function nextCronTickInTimeZone(expression, timeZone, after) { - const trimmed = expression.trim(); - assertTimeZone(timeZone); - const error50 = validateCron(trimmed); - if (error50) { - throw unprocessable(error50); - } - const cursor2 = floorToMinute(after); - cursor2.setUTCMinutes(cursor2.getUTCMinutes() + 1); - const limit = 366 * 24 * 60 * 5; - for (let i5 = 0; i5 < limit; i5 += 1) { - if (matchesCronMinute(trimmed, timeZone, cursor2)) { - return new Date(cursor2.getTime()); - } - cursor2.setUTCMinutes(cursor2.getUTCMinutes() + 1); - } - return null; -} -function nextResultText(status, issueId) { - if (status === "issue_created" && issueId) return `Created execution issue ${issueId}`; - if (status === "coalesced") return "Coalesced into an existing live execution issue"; - if (status === "skipped") return "Skipped because a live execution issue already exists"; - if (status === "completed") return "Execution issue completed"; - if (status === "failed") return "Execution failed"; - return status; -} -function normalizeWebhookTimestampMs(rawTimestamp) { - const parsed = Number(rawTimestamp); - if (!Number.isFinite(parsed)) return null; - return parsed > 1e12 ? parsed : parsed * 1e3; -} -function isPlainRecord4(value) { - return typeof value === "object" && value !== null && !Array.isArray(value); -} -function parseBooleanVariableValue(name, raw) { - if (typeof raw === "boolean") return raw; - if (typeof raw === "number" && (raw === 0 || raw === 1)) return raw === 1; - if (typeof raw === "string") { - const normalized = raw.trim().toLowerCase(); - if (["true", "1", "yes", "y", "on"].includes(normalized)) return true; - if (["false", "0", "no", "n", "off"].includes(normalized)) return false; - } - throw unprocessable(`Variable "${name}" must be a boolean`); -} -function parseNumberVariableValue(name, raw) { - if (typeof raw === "number" && Number.isFinite(raw)) return raw; - if (typeof raw === "string" && raw.trim().length > 0) { - const parsed = Number(raw); - if (Number.isFinite(parsed)) return parsed; - } - throw unprocessable(`Variable "${name}" must be a number`); -} -function normalizeRoutineVariableValue(variable, raw) { - if (raw == null) return null; - if (variable.type === "boolean") return parseBooleanVariableValue(variable.name, raw); - if (variable.type === "number") return parseNumberVariableValue(variable.name, raw); - const normalized = stringifyRoutineVariableValue(raw); - if (variable.type === "select") { - if (!variable.options.includes(normalized)) { - throw unprocessable(`Variable "${variable.name}" must match one of: ${variable.options.join(", ")}`); - } - } - return normalized; -} -function isMissingRoutineVariableValue(value) { - return value == null || typeof value === "string" && value.trim().length === 0; -} -function assertRoutineVariableDefinitions(variables) { - for (const variable of variables) { - if (variable.defaultValue != null) { - normalizeRoutineVariableValue(variable, variable.defaultValue); - } - if (variable.type === "select" && variable.options.length === 0) { - throw unprocessable(`Variable "${variable.name}" must define at least one option`); - } - } -} -function sanitizeRoutineVariableInputs(variables) { - return (variables ?? []).map((variable) => ({ - name: variable.name, - label: variable.label ?? null, - type: variable.type ?? "text", - defaultValue: variable.defaultValue ?? null, - required: variable.required ?? true, - options: variable.options ?? [] - })); -} -function assertScheduleCompatibleVariables(variables) { - const missingDefaults = variables.filter((variable) => variable.required).filter((variable) => { - try { - return isMissingRoutineVariableValue(normalizeRoutineVariableValue(variable, variable.defaultValue)); - } catch { - return true; - } - }).map((variable) => variable.name); - if (missingDefaults.length > 0) { - throw unprocessable( - `Scheduled routines require defaults for required variables: ${missingDefaults.join(", ")}` - ); - } -} -function statusRequiresDefaultAgent(status) { - return status === "active"; -} -function normalizeDraftRoutineStatus(status, assigneeAgentId) { - if (statusRequiresDefaultAgent(status) && !assigneeAgentId) { - return "paused"; - } - return status; -} -function assertRoutineCanEnable(status, assigneeAgentId) { - if (statusRequiresDefaultAgent(status) && !assigneeAgentId) { - throw unprocessable("Default agent required"); - } -} -function collectProvidedRoutineVariables(source, payload2, variables) { - const nestedVariables = isPlainRecord4(payload2) && isPlainRecord4(payload2.variables) ? payload2.variables : {}; - const provided = { - ...source === "webhook" && payload2 ? payload2 : {}, - ...nestedVariables, - ...variables ?? {} - }; - delete provided.variables; - return provided; -} -function resolveRoutineVariableValues(variables, input) { - if (variables.length === 0) return {}; - const provided = collectProvidedRoutineVariables(input.source, input.payload, input.variables); - const resolved = {}; - const missing = []; - for (const variable of variables) { - const candidate = provided[variable.name] !== void 0 ? provided[variable.name] : variable.defaultValue; - const normalized = normalizeRoutineVariableValue(variable, candidate); - if (normalized == null || typeof normalized === "string" && normalized.trim().length === 0) { - if (variable.required) missing.push(variable.name); - continue; - } - resolved[variable.name] = normalized; - } - if (missing.length > 0) { - throw unprocessable(`Missing routine variables: ${missing.join(", ")}`); - } - return resolved; -} -function mergeRoutineRunPayload(payload2, variables) { - if (Object.keys(variables).length === 0) return payload2 ?? null; - if (!payload2) return { variables }; - const existingVariables = isPlainRecord4(payload2.variables) ? payload2.variables : {}; - return { - ...payload2, - variables: { - ...existingVariables, - ...variables - } - }; -} -function routineService(db, deps = {}) { - const issueSvc = issueService(db); - const secretsSvc = secretService(db); - const heartbeat = deps.heartbeat ?? heartbeatService(db); - async function getRoutineById(id) { - return db.select().from(routines).where(eq(routines.id, id)).then((rows) => rows[0] ?? null); - } - async function getTriggerById(id) { - return db.select().from(routineTriggers).where(eq(routineTriggers.id, id)).then((rows) => rows[0] ?? null); - } - async function assertRoutineAccess(companyId, routineId) { - const routine = await getRoutineById(routineId); - if (!routine) throw notFound("Routine not found"); - if (routine.companyId !== companyId) throw forbidden("Routine must belong to same company"); - return routine; - } - async function assertAssignableAgent(companyId, agentId) { - if (!agentId) return; - const agent = await db.select({ id: agents.id, companyId: agents.companyId, status: agents.status }).from(agents).where(eq(agents.id, agentId)).then((rows) => rows[0] ?? null); - if (!agent) throw notFound("Assignee agent not found"); - if (agent.companyId !== companyId) throw unprocessable("Assignee must belong to same company"); - if (agent.status === "pending_approval") throw conflict("Cannot assign routines to pending approval agents"); - if (agent.status === "terminated") throw conflict("Cannot assign routines to terminated agents"); - } - async function assertProject(companyId, projectId) { - if (!projectId) return; - const project = await db.select({ id: projects.id, companyId: projects.companyId }).from(projects).where(eq(projects.id, projectId)).then((rows) => rows[0] ?? null); - if (!project) throw notFound("Project not found"); - if (project.companyId !== companyId) throw unprocessable("Project must belong to same company"); - } - async function assertGoal(companyId, goalId) { - const goal = await db.select({ id: goals.id, companyId: goals.companyId }).from(goals).where(eq(goals.id, goalId)).then((rows) => rows[0] ?? null); - if (!goal) throw notFound("Goal not found"); - if (goal.companyId !== companyId) throw unprocessable("Goal must belong to same company"); - } - async function assertParentIssue(companyId, issueId) { - const parentIssue = await db.select({ id: issues.id, companyId: issues.companyId }).from(issues).where(eq(issues.id, issueId)).then((rows) => rows[0] ?? null); - if (!parentIssue) throw notFound("Parent issue not found"); - if (parentIssue.companyId !== companyId) throw unprocessable("Parent issue must belong to same company"); - } - async function listTriggersForRoutineIds(companyId, routineIds) { - if (routineIds.length === 0) return /* @__PURE__ */ new Map(); - const rows = await db.select().from(routineTriggers).where(and(eq(routineTriggers.companyId, companyId), inArray(routineTriggers.routineId, routineIds))).orderBy(asc(routineTriggers.createdAt), asc(routineTriggers.id)); - const map4 = /* @__PURE__ */ new Map(); - for (const row of rows) { - const list2 = map4.get(row.routineId) ?? []; - list2.push(row); - map4.set(row.routineId, list2); - } - return map4; - } - async function listLatestRunByRoutineIds(companyId, routineIds) { - if (routineIds.length === 0) return /* @__PURE__ */ new Map(); - const rows = await db.selectDistinctOn([routineRuns.routineId], { - id: routineRuns.id, - companyId: routineRuns.companyId, - routineId: routineRuns.routineId, - triggerId: routineRuns.triggerId, - source: routineRuns.source, - status: routineRuns.status, - triggeredAt: routineRuns.triggeredAt, - idempotencyKey: routineRuns.idempotencyKey, - triggerPayload: routineRuns.triggerPayload, - linkedIssueId: routineRuns.linkedIssueId, - coalescedIntoRunId: routineRuns.coalescedIntoRunId, - failureReason: routineRuns.failureReason, - completedAt: routineRuns.completedAt, - createdAt: routineRuns.createdAt, - updatedAt: routineRuns.updatedAt, - triggerKind: routineTriggers.kind, - triggerLabel: routineTriggers.label, - issueIdentifier: issues.identifier, - issueTitle: issues.title, - issueStatus: issues.status, - issuePriority: issues.priority, - issueUpdatedAt: issues.updatedAt - }).from(routineRuns).leftJoin(routineTriggers, eq(routineRuns.triggerId, routineTriggers.id)).leftJoin(issues, eq(routineRuns.linkedIssueId, issues.id)).where(and(eq(routineRuns.companyId, companyId), inArray(routineRuns.routineId, routineIds))).orderBy(routineRuns.routineId, desc(routineRuns.createdAt), desc(routineRuns.id)); - const map4 = /* @__PURE__ */ new Map(); - for (const row of rows) { - map4.set(row.routineId, { - id: row.id, - companyId: row.companyId, - routineId: row.routineId, - triggerId: row.triggerId, - source: row.source, - status: row.status, - triggeredAt: row.triggeredAt, - idempotencyKey: row.idempotencyKey, - triggerPayload: row.triggerPayload, - linkedIssueId: row.linkedIssueId, - coalescedIntoRunId: row.coalescedIntoRunId, - failureReason: row.failureReason, - completedAt: row.completedAt, - createdAt: row.createdAt, - updatedAt: row.updatedAt, - linkedIssue: row.linkedIssueId ? { - id: row.linkedIssueId, - identifier: row.issueIdentifier, - title: row.issueTitle ?? "Routine execution", - status: row.issueStatus ?? "todo", - priority: row.issuePriority ?? "medium", - updatedAt: row.issueUpdatedAt ?? row.updatedAt - } : null, - trigger: row.triggerId ? { - id: row.triggerId, - kind: row.triggerKind, - label: row.triggerLabel - } : null - }); - } - return map4; - } - async function listLiveIssueByRoutineIds(companyId, routineIds) { - if (routineIds.length === 0) return /* @__PURE__ */ new Map(); - const executionBoundRows = await db.selectDistinctOn([issues.originId], { - originId: issues.originId, - id: issues.id, - identifier: issues.identifier, - title: issues.title, - status: issues.status, - priority: issues.priority, - updatedAt: issues.updatedAt - }).from(issues).innerJoin( - heartbeatRuns, - and( - eq(heartbeatRuns.id, issues.executionRunId), - inArray(heartbeatRuns.status, LIVE_HEARTBEAT_RUN_STATUSES) - ) - ).where( - and( - eq(issues.companyId, companyId), - eq(issues.originKind, "routine_execution"), - inArray(issues.originId, routineIds), - inArray(issues.status, OPEN_ISSUE_STATUSES), - isNull(issues.hiddenAt) - ) - ).orderBy(issues.originId, desc(issues.updatedAt), desc(issues.createdAt)); - const rowsByOriginId = /* @__PURE__ */ new Map(); - for (const row of executionBoundRows) { - if (!row.originId) continue; - rowsByOriginId.set(row.originId, row); - } - const missingRoutineIds = routineIds.filter((routineId) => !rowsByOriginId.has(routineId)); - if (missingRoutineIds.length > 0) { - const legacyRows = await db.selectDistinctOn([issues.originId], { - originId: issues.originId, - id: issues.id, - identifier: issues.identifier, - title: issues.title, - status: issues.status, - priority: issues.priority, - updatedAt: issues.updatedAt - }).from(issues).innerJoin( - heartbeatRuns, - and( - eq(heartbeatRuns.companyId, issues.companyId), - inArray(heartbeatRuns.status, LIVE_HEARTBEAT_RUN_STATUSES), - sql`${heartbeatRuns.contextSnapshot} ->> 'issueId' = cast(${issues.id} as text)` - ) - ).where( - and( - eq(issues.companyId, companyId), - eq(issues.originKind, "routine_execution"), - inArray(issues.originId, missingRoutineIds), - inArray(issues.status, OPEN_ISSUE_STATUSES), - isNull(issues.hiddenAt) - ) - ).orderBy(issues.originId, desc(issues.updatedAt), desc(issues.createdAt)); - for (const row of legacyRows) { - if (!row.originId) continue; - rowsByOriginId.set(row.originId, row); - } - } - const map4 = /* @__PURE__ */ new Map(); - for (const row of rowsByOriginId.values()) { - if (!row.originId) continue; - map4.set(row.originId, { - id: row.id, - identifier: row.identifier, - title: row.title, - status: row.status, - priority: row.priority, - updatedAt: row.updatedAt - }); - } - return map4; - } - async function updateRoutineTouchedState(input, executor = db) { - await executor.update(routines).set({ - lastTriggeredAt: input.triggeredAt, - lastEnqueuedAt: input.issueId ? input.triggeredAt : void 0, - updatedAt: /* @__PURE__ */ new Date() - }).where(eq(routines.id, input.routineId)); - if (input.triggerId) { - await executor.update(routineTriggers).set({ - lastFiredAt: input.triggeredAt, - lastResult: nextResultText(input.status, input.issueId), - nextRunAt: input.nextRunAt === void 0 ? void 0 : input.nextRunAt, - updatedAt: /* @__PURE__ */ new Date() - }).where(eq(routineTriggers.id, input.triggerId)); - } - } - async function findLiveExecutionIssue(routine, executor = db) { - const executionBoundIssue = await executor.select().from(issues).innerJoin( - heartbeatRuns, - and( - eq(heartbeatRuns.id, issues.executionRunId), - inArray(heartbeatRuns.status, LIVE_HEARTBEAT_RUN_STATUSES) - ) - ).where( - and( - eq(issues.companyId, routine.companyId), - eq(issues.originKind, "routine_execution"), - eq(issues.originId, routine.id), - inArray(issues.status, OPEN_ISSUE_STATUSES), - isNull(issues.hiddenAt) - ) - ).orderBy(desc(issues.updatedAt), desc(issues.createdAt)).limit(1).then((rows) => rows[0]?.issues ?? null); - if (executionBoundIssue) return executionBoundIssue; - return executor.select().from(issues).innerJoin( - heartbeatRuns, - and( - eq(heartbeatRuns.companyId, issues.companyId), - inArray(heartbeatRuns.status, LIVE_HEARTBEAT_RUN_STATUSES), - sql`${heartbeatRuns.contextSnapshot} ->> 'issueId' = cast(${issues.id} as text)` - ) - ).where( - and( - eq(issues.companyId, routine.companyId), - eq(issues.originKind, "routine_execution"), - eq(issues.originId, routine.id), - inArray(issues.status, OPEN_ISSUE_STATUSES), - isNull(issues.hiddenAt) - ) - ).orderBy(desc(issues.updatedAt), desc(issues.createdAt)).limit(1).then((rows) => rows[0]?.issues ?? null); - } - async function finalizeRun(runId, patch, executor = db) { - return executor.update(routineRuns).set({ - ...patch, - updatedAt: /* @__PURE__ */ new Date() - }).where(eq(routineRuns.id, runId)).returning().then((rows) => rows[0] ?? null); - } - async function createWebhookSecret(companyId, routineId, actor) { - const secretValue = crypto4.randomBytes(24).toString("hex"); - const secret = await secretsSvc.create( - companyId, - { - name: `routine-${routineId}-${crypto4.randomBytes(6).toString("hex")}`, - provider: "local_encrypted", - value: secretValue, - description: `Webhook auth for routine ${routineId}` - }, - actor - ); - return { secret, secretValue }; - } - async function resolveTriggerSecret(trigger, companyId) { - if (!trigger.secretId) throw notFound("Routine trigger secret not found"); - const secret = await db.select().from(companySecrets).where(eq(companySecrets.id, trigger.secretId)).then((rows) => rows[0] ?? null); - if (!secret || secret.companyId !== companyId) throw notFound("Routine trigger secret not found"); - const value = await secretsSvc.resolveSecretValue(companyId, trigger.secretId, "latest"); - return value; - } - async function dispatchRoutineRun(input) { - const projectId = input.projectId ?? input.routine.projectId ?? null; - const assigneeAgentId = input.assigneeAgentId ?? input.routine.assigneeAgentId ?? null; - if (!assigneeAgentId) { - throw unprocessable("Default agent required"); - } - const resolvedVariables = resolveRoutineVariableValues(input.routine.variables ?? [], input); - const allVariables = { ...getBuiltinRoutineVariableValues(), ...resolvedVariables }; - const title = interpolateRoutineTemplate(input.routine.title, allVariables) ?? input.routine.title; - const description = interpolateRoutineTemplate(input.routine.description, allVariables); - const triggerPayload = mergeRoutineRunPayload(input.payload, resolvedVariables); - const run = await db.transaction(async (tx) => { - const txDb = tx; - await tx.execute( - sql`select id from ${routines} where ${routines.id} = ${input.routine.id} and ${routines.companyId} = ${input.routine.companyId} for update` - ); - if (input.idempotencyKey) { - const existing = await txDb.select().from(routineRuns).where( - and( - eq(routineRuns.companyId, input.routine.companyId), - eq(routineRuns.routineId, input.routine.id), - eq(routineRuns.source, input.source), - eq(routineRuns.idempotencyKey, input.idempotencyKey), - input.trigger ? eq(routineRuns.triggerId, input.trigger.id) : isNull(routineRuns.triggerId) - ) - ).orderBy(desc(routineRuns.createdAt)).limit(1).then((rows) => rows[0] ?? null); - if (existing) return existing; - } - const triggeredAt = /* @__PURE__ */ new Date(); - const [createdRun] = await txDb.insert(routineRuns).values({ - companyId: input.routine.companyId, - routineId: input.routine.id, - triggerId: input.trigger?.id ?? null, - source: input.source, - status: "received", - triggeredAt, - idempotencyKey: input.idempotencyKey ?? null, - triggerPayload - }).returning(); - const nextRunAt = input.trigger?.kind === "schedule" && input.trigger.cronExpression && input.trigger.timezone ? nextCronTickInTimeZone(input.trigger.cronExpression, input.trigger.timezone, triggeredAt) : void 0; - let createdIssue = null; - try { - const activeIssue = await findLiveExecutionIssue(input.routine, txDb); - if (activeIssue && input.routine.concurrencyPolicy !== "always_enqueue") { - const status = input.routine.concurrencyPolicy === "skip_if_active" ? "skipped" : "coalesced"; - const updated2 = await finalizeRun(createdRun.id, { - status, - linkedIssueId: activeIssue.id, - coalescedIntoRunId: activeIssue.originRunId, - completedAt: triggeredAt - }, txDb); - await updateRoutineTouchedState({ - routineId: input.routine.id, - triggerId: input.trigger?.id ?? null, - triggeredAt, - status, - issueId: activeIssue.id, - nextRunAt - }, txDb); - return updated2 ?? createdRun; - } - try { - createdIssue = await issueSvc.create(input.routine.companyId, { - projectId, - goalId: input.routine.goalId, - parentId: input.routine.parentIssueId, - title, - description, - status: "todo", - priority: input.routine.priority, - assigneeAgentId, - originKind: "routine_execution", - originId: input.routine.id, - originRunId: createdRun.id, - executionWorkspaceId: input.executionWorkspaceId ?? null, - executionWorkspacePreference: input.executionWorkspacePreference ?? null, - executionWorkspaceSettings: input.executionWorkspaceSettings ?? null - }); - } catch (error50) { - const isOpenExecutionConflict = !!error50 && typeof error50 === "object" && "code" in error50 && error50.code === "23505" && "constraint" in error50 && error50.constraint === "issues_open_routine_execution_uq"; - if (!isOpenExecutionConflict || input.routine.concurrencyPolicy === "always_enqueue") { - throw error50; - } - const existingIssue = await findLiveExecutionIssue(input.routine, txDb); - if (!existingIssue) throw error50; - const status = input.routine.concurrencyPolicy === "skip_if_active" ? "skipped" : "coalesced"; - const updated2 = await finalizeRun(createdRun.id, { - status, - linkedIssueId: existingIssue.id, - coalescedIntoRunId: existingIssue.originRunId, - completedAt: triggeredAt - }, txDb); - await updateRoutineTouchedState({ - routineId: input.routine.id, - triggerId: input.trigger?.id ?? null, - triggeredAt, - status, - issueId: existingIssue.id, - nextRunAt - }, txDb); - return updated2 ?? createdRun; - } - await queueIssueAssignmentWakeup({ - heartbeat, - issue: createdIssue, - reason: "issue_assigned", - mutation: "create", - contextSource: "routine.dispatch", - requestedByActorType: input.source === "schedule" ? "system" : void 0, - rethrowOnError: true - }); - const updated = await finalizeRun(createdRun.id, { - status: "issue_created", - linkedIssueId: createdIssue.id - }, txDb); - await updateRoutineTouchedState({ - routineId: input.routine.id, - triggerId: input.trigger?.id ?? null, - triggeredAt, - status: "issue_created", - issueId: createdIssue.id, - nextRunAt - }, txDb); - return updated ?? createdRun; - } catch (error50) { - if (createdIssue) { - await txDb.delete(issues).where(eq(issues.id, createdIssue.id)); - } - const failureReason = error50 instanceof Error ? error50.message : String(error50); - const failed = await finalizeRun(createdRun.id, { - status: "failed", - failureReason, - completedAt: /* @__PURE__ */ new Date() - }, txDb); - await updateRoutineTouchedState({ - routineId: input.routine.id, - triggerId: input.trigger?.id ?? null, - triggeredAt, - status: "failed", - nextRunAt - }, txDb); - return failed ?? createdRun; - } - }); - if (input.source === "schedule" || input.source === "webhook") { - const actorId = input.source === "schedule" ? "routine-scheduler" : "routine-webhook"; - try { - await logActivity(db, { - companyId: input.routine.companyId, - actorType: "system", - actorId, - action: "routine.run_triggered", - entityType: "routine_run", - entityId: run.id, - details: { - routineId: input.routine.id, - triggerId: input.trigger?.id ?? null, - source: run.source, - status: run.status - } - }); - } catch (err) { - logger.warn({ err, routineId: input.routine.id, runId: run.id }, "failed to log automated routine run"); - } - } - const telemetryClient = getTelemetryClient(); - if (telemetryClient) { - trackRoutineRun(telemetryClient, { - source: run.source, - status: run.status - }); - } - return run; - } - return { - get: getRoutineById, - getTrigger: getTriggerById, - list: async (companyId) => { - const rows = await db.select().from(routines).where(eq(routines.companyId, companyId)).orderBy(desc(routines.updatedAt), asc(routines.title)); - const routineIds = rows.map((row) => row.id); - const [triggersByRoutine, latestRunByRoutine, activeIssueByRoutine] = await Promise.all([ - listTriggersForRoutineIds(companyId, routineIds), - listLatestRunByRoutineIds(companyId, routineIds), - listLiveIssueByRoutineIds(companyId, routineIds) - ]); - return rows.map((row) => ({ - ...row, - triggers: (triggersByRoutine.get(row.id) ?? []).map((trigger) => ({ - id: trigger.id, - kind: trigger.kind, - label: trigger.label, - enabled: trigger.enabled, - nextRunAt: trigger.nextRunAt, - lastFiredAt: trigger.lastFiredAt, - lastResult: trigger.lastResult - })), - lastRun: latestRunByRoutine.get(row.id) ?? null, - activeIssue: activeIssueByRoutine.get(row.id) ?? null - })); - }, - getDetail: async (id) => { - const row = await getRoutineById(id); - if (!row) return null; - const [project, assignee, parentIssue, triggers, recentRuns, activeIssue] = await Promise.all([ - row.projectId ? db.select().from(projects).where(eq(projects.id, row.projectId)).then((rows) => rows[0] ?? null) : null, - row.assigneeAgentId ? db.select().from(agents).where(eq(agents.id, row.assigneeAgentId)).then((rows) => rows[0] ?? null) : null, - row.parentIssueId ? issueSvc.getById(row.parentIssueId) : null, - db.select().from(routineTriggers).where(eq(routineTriggers.routineId, row.id)).orderBy(asc(routineTriggers.createdAt)), - db.select({ - id: routineRuns.id, - companyId: routineRuns.companyId, - routineId: routineRuns.routineId, - triggerId: routineRuns.triggerId, - source: routineRuns.source, - status: routineRuns.status, - triggeredAt: routineRuns.triggeredAt, - idempotencyKey: routineRuns.idempotencyKey, - triggerPayload: routineRuns.triggerPayload, - linkedIssueId: routineRuns.linkedIssueId, - coalescedIntoRunId: routineRuns.coalescedIntoRunId, - failureReason: routineRuns.failureReason, - completedAt: routineRuns.completedAt, - createdAt: routineRuns.createdAt, - updatedAt: routineRuns.updatedAt, - triggerKind: routineTriggers.kind, - triggerLabel: routineTriggers.label, - issueIdentifier: issues.identifier, - issueTitle: issues.title, - issueStatus: issues.status, - issuePriority: issues.priority, - issueUpdatedAt: issues.updatedAt - }).from(routineRuns).leftJoin(routineTriggers, eq(routineRuns.triggerId, routineTriggers.id)).leftJoin(issues, eq(routineRuns.linkedIssueId, issues.id)).where(eq(routineRuns.routineId, row.id)).orderBy(desc(routineRuns.createdAt)).limit(25).then( - (runs) => runs.map((run) => ({ - id: run.id, - companyId: run.companyId, - routineId: run.routineId, - triggerId: run.triggerId, - source: run.source, - status: run.status, - triggeredAt: run.triggeredAt, - idempotencyKey: run.idempotencyKey, - triggerPayload: run.triggerPayload, - linkedIssueId: run.linkedIssueId, - coalescedIntoRunId: run.coalescedIntoRunId, - failureReason: run.failureReason, - completedAt: run.completedAt, - createdAt: run.createdAt, - updatedAt: run.updatedAt, - linkedIssue: run.linkedIssueId ? { - id: run.linkedIssueId, - identifier: run.issueIdentifier, - title: run.issueTitle ?? "Routine execution", - status: run.issueStatus ?? "todo", - priority: run.issuePriority ?? "medium", - updatedAt: run.issueUpdatedAt ?? run.updatedAt - } : null, - trigger: run.triggerId ? { - id: run.triggerId, - kind: run.triggerKind, - label: run.triggerLabel - } : null - })) - ), - findLiveExecutionIssue(row) - ]); - return { - ...row, - project, - assignee, - parentIssue, - triggers, - recentRuns, - activeIssue - }; - }, - create: async (companyId, input, actor) => { - await assertProject(companyId, input.projectId ?? null); - await assertAssignableAgent(companyId, input.assigneeAgentId ?? null); - if (input.goalId) await assertGoal(companyId, input.goalId); - if (input.parentIssueId) await assertParentIssue(companyId, input.parentIssueId); - const variables = syncRoutineVariablesWithTemplate( - [input.title, input.description], - sanitizeRoutineVariableInputs(input.variables) - ); - assertRoutineVariableDefinitions(variables); - const status = normalizeDraftRoutineStatus(input.status, input.assigneeAgentId); - const [created] = await db.insert(routines).values({ - companyId, - projectId: input.projectId ?? null, - goalId: input.goalId ?? null, - parentIssueId: input.parentIssueId ?? null, - title: input.title, - description: input.description ?? null, - assigneeAgentId: input.assigneeAgentId ?? null, - priority: input.priority, - status, - concurrencyPolicy: input.concurrencyPolicy, - catchUpPolicy: input.catchUpPolicy, - variables, - createdByAgentId: actor.agentId ?? null, - createdByUserId: actor.userId ?? null, - updatedByAgentId: actor.agentId ?? null, - updatedByUserId: actor.userId ?? null - }).returning(); - return created; - }, - update: async (id, patch, actor) => { - const existing = await getRoutineById(id); - if (!existing) return null; - const nextProjectId = patch.projectId === void 0 ? existing.projectId : patch.projectId; - const nextAssigneeAgentId = patch.assigneeAgentId === void 0 ? existing.assigneeAgentId : patch.assigneeAgentId; - const nextTitle = patch.title ?? existing.title; - const nextDescription = patch.description === void 0 ? existing.description : patch.description; - const requestedStatus = patch.status ?? existing.status; - if (patch.status === "active") { - assertRoutineCanEnable(patch.status, nextAssigneeAgentId); - } - const nextStatus = patch.assigneeAgentId === void 0 ? requestedStatus : normalizeDraftRoutineStatus(requestedStatus, nextAssigneeAgentId); - const nextVariables = syncRoutineVariablesWithTemplate( - [nextTitle, nextDescription], - patch.variables === void 0 ? existing.variables : sanitizeRoutineVariableInputs(patch.variables) - ); - if (patch.projectId !== void 0) await assertProject(existing.companyId, nextProjectId); - if (patch.assigneeAgentId !== void 0) await assertAssignableAgent(existing.companyId, nextAssigneeAgentId); - if (patch.goalId) await assertGoal(existing.companyId, patch.goalId); - if (patch.parentIssueId) await assertParentIssue(existing.companyId, patch.parentIssueId); - assertRoutineVariableDefinitions(nextVariables); - const enabledScheduleTriggers = await db.select({ id: routineTriggers.id }).from(routineTriggers).where( - and( - eq(routineTriggers.routineId, existing.id), - eq(routineTriggers.kind, "schedule"), - eq(routineTriggers.enabled, true) - ) - ).limit(1).then((rows) => rows.length > 0); - if (enabledScheduleTriggers) { - assertScheduleCompatibleVariables(nextVariables); - } - const [updated] = await db.update(routines).set({ - projectId: nextProjectId, - goalId: patch.goalId === void 0 ? existing.goalId : patch.goalId, - parentIssueId: patch.parentIssueId === void 0 ? existing.parentIssueId : patch.parentIssueId, - title: nextTitle, - description: nextDescription, - assigneeAgentId: nextAssigneeAgentId, - priority: patch.priority ?? existing.priority, - status: nextStatus, - concurrencyPolicy: patch.concurrencyPolicy ?? existing.concurrencyPolicy, - catchUpPolicy: patch.catchUpPolicy ?? existing.catchUpPolicy, - variables: nextVariables, - updatedByAgentId: actor.agentId ?? null, - updatedByUserId: actor.userId ?? null, - updatedAt: /* @__PURE__ */ new Date() - }).where(eq(routines.id, id)).returning(); - return updated ?? null; - }, - createTrigger: async (routineId, input, actor) => { - const routine = await getRoutineById(routineId); - if (!routine) throw notFound("Routine not found"); - let secretMaterial = null; - let secretId = null; - let publicId = null; - let nextRunAt = null; - if (input.kind === "schedule") { - assertScheduleCompatibleVariables(routine.variables ?? []); - const timeZone = input.timezone || "UTC"; - assertTimeZone(timeZone); - const error50 = validateCron(input.cronExpression); - if (error50) throw unprocessable(error50); - nextRunAt = nextCronTickInTimeZone(input.cronExpression, timeZone, /* @__PURE__ */ new Date()); - } - if (input.kind === "webhook") { - publicId = crypto4.randomBytes(12).toString("hex"); - const created = await createWebhookSecret(routine.companyId, routine.id, actor); - secretId = created.secret.id; - secretMaterial = { - webhookUrl: `${process.env.TASKCORE_API_URL}/api/routine-triggers/public/${publicId}/fire`, - webhookSecret: created.secretValue - }; - } - const [trigger] = await db.insert(routineTriggers).values({ - companyId: routine.companyId, - routineId: routine.id, - kind: input.kind, - label: input.label ?? null, - enabled: input.enabled ?? true, - cronExpression: input.kind === "schedule" ? input.cronExpression : null, - timezone: input.kind === "schedule" ? input.timezone || "UTC" : null, - nextRunAt, - publicId, - secretId, - signingMode: input.kind === "webhook" ? input.signingMode : null, - replayWindowSec: input.kind === "webhook" ? input.replayWindowSec : null, - lastRotatedAt: input.kind === "webhook" ? /* @__PURE__ */ new Date() : null, - createdByAgentId: actor.agentId ?? null, - createdByUserId: actor.userId ?? null, - updatedByAgentId: actor.agentId ?? null, - updatedByUserId: actor.userId ?? null - }).returning(); - return { - trigger, - secretMaterial - }; - }, - updateTrigger: async (id, patch, actor) => { - const existing = await getTriggerById(id); - if (!existing) return null; - let nextRunAt = existing.nextRunAt; - let cronExpression = existing.cronExpression; - let timezone = existing.timezone; - if (existing.kind === "schedule") { - const routine = await getRoutineById(existing.routineId); - if (!routine) throw notFound("Routine not found"); - if (patch.cronExpression !== void 0) { - if (patch.cronExpression == null) throw unprocessable("Scheduled triggers require cronExpression"); - const error50 = validateCron(patch.cronExpression); - if (error50) throw unprocessable(error50); - cronExpression = patch.cronExpression; - } - if (patch.timezone !== void 0) { - if (patch.timezone == null) throw unprocessable("Scheduled triggers require timezone"); - assertTimeZone(patch.timezone); - timezone = patch.timezone; - } - if (cronExpression && timezone) { - nextRunAt = nextCronTickInTimeZone(cronExpression, timezone, /* @__PURE__ */ new Date()); - } - if ((patch.enabled ?? existing.enabled) === true) { - assertScheduleCompatibleVariables(routine.variables ?? []); - } - } - const [updated] = await db.update(routineTriggers).set({ - label: patch.label === void 0 ? existing.label : patch.label, - enabled: patch.enabled ?? existing.enabled, - cronExpression, - timezone, - nextRunAt, - signingMode: patch.signingMode === void 0 ? existing.signingMode : patch.signingMode, - replayWindowSec: patch.replayWindowSec === void 0 ? existing.replayWindowSec : patch.replayWindowSec, - updatedByAgentId: actor.agentId ?? null, - updatedByUserId: actor.userId ?? null, - updatedAt: /* @__PURE__ */ new Date() - }).where(eq(routineTriggers.id, id)).returning(); - return updated ?? null; - }, - deleteTrigger: async (id) => { - const existing = await getTriggerById(id); - if (!existing) return false; - await db.delete(routineTriggers).where(eq(routineTriggers.id, id)); - return true; - }, - rotateTriggerSecret: async (id, actor) => { - const existing = await getTriggerById(id); - if (!existing) throw notFound("Routine trigger not found"); - if (existing.kind !== "webhook" || !existing.publicId || !existing.secretId) { - throw unprocessable("Only webhook triggers can rotate secrets"); - } - const secretValue = crypto4.randomBytes(24).toString("hex"); - await secretsSvc.rotate(existing.secretId, { value: secretValue }, actor); - const [updated] = await db.update(routineTriggers).set({ - lastRotatedAt: /* @__PURE__ */ new Date(), - updatedByAgentId: actor.agentId ?? null, - updatedByUserId: actor.userId ?? null, - updatedAt: /* @__PURE__ */ new Date() - }).where(eq(routineTriggers.id, id)).returning(); - return { - trigger: updated, - secretMaterial: { - webhookUrl: `${process.env.TASKCORE_API_URL}/api/routine-triggers/public/${existing.publicId}/fire`, - webhookSecret: secretValue - } - }; - }, - runRoutine: async (id, input) => { - const routine = await getRoutineById(id); - if (!routine) throw notFound("Routine not found"); - if (routine.status === "archived") throw conflict("Routine is archived"); - await assertProject(routine.companyId, input.projectId ?? null); - await assertAssignableAgent(routine.companyId, input.assigneeAgentId ?? null); - const trigger = input.triggerId ? await getTriggerById(input.triggerId) : null; - if (trigger && trigger.routineId !== routine.id) throw forbidden("Trigger does not belong to routine"); - if (trigger && !trigger.enabled) throw conflict("Routine trigger is not active"); - return dispatchRoutineRun({ - routine, - trigger, - source: input.source, - payload: input.payload, - variables: input.variables, - projectId: input.projectId ?? null, - assigneeAgentId: input.assigneeAgentId ?? null, - idempotencyKey: input.idempotencyKey, - executionWorkspaceId: input.executionWorkspaceId ?? null, - executionWorkspacePreference: input.executionWorkspacePreference ?? null, - executionWorkspaceSettings: input.executionWorkspaceSettings ?? null - }); - }, - firePublicTrigger: async (publicId, input) => { - const trigger = await db.select().from(routineTriggers).where(and(eq(routineTriggers.publicId, publicId), eq(routineTriggers.kind, "webhook"))).then((rows) => rows[0] ?? null); - if (!trigger) throw notFound("Routine trigger not found"); - const routine = await getRoutineById(trigger.routineId); - if (!routine) throw notFound("Routine not found"); - if (!trigger.enabled || routine.status !== "active") throw conflict("Routine trigger is not active"); - if (trigger.signingMode === "none") { - } else if (trigger.signingMode === "github_hmac") { - const secretValue = await resolveTriggerSecret(trigger, routine.companyId); - const rawBody = input.rawBody ?? Buffer.from(JSON.stringify(input.payload ?? {})); - const providedSignature = (input.hubSignatureHeader ?? input.signatureHeader)?.trim() ?? ""; - if (!providedSignature) throw unauthorized(); - const expectedHmac = crypto4.createHmac("sha256", secretValue).update(rawBody).digest("hex"); - const normalizedSignature = providedSignature.replace(/^sha256=/, ""); - const normalizedBuf = Buffer.from(normalizedSignature); - const expectedBuf = Buffer.from(expectedHmac); - const valid = normalizedBuf.length === expectedBuf.length && crypto4.timingSafeEqual(normalizedBuf, expectedBuf); - if (!valid) throw unauthorized(); - } else if (trigger.signingMode === "bearer") { - const secretValue = await resolveTriggerSecret(trigger, routine.companyId); - const expected = `Bearer ${secretValue}`; - const provided = input.authorizationHeader?.trim() ?? ""; - const expectedBuf = Buffer.from(expected); - const providedBuf = Buffer.alloc(expectedBuf.length); - providedBuf.write(provided.slice(0, expectedBuf.length)); - const valid = provided.length === expected.length && crypto4.timingSafeEqual(providedBuf, expectedBuf); - if (!valid) { - throw unauthorized(); - } - } else { - const secretValue = await resolveTriggerSecret(trigger, routine.companyId); - const rawBody = input.rawBody ?? Buffer.from(JSON.stringify(input.payload ?? {})); - const providedSignature = input.signatureHeader?.trim() ?? ""; - const providedTimestamp = input.timestampHeader?.trim() ?? ""; - if (!providedSignature || !providedTimestamp) throw unauthorized(); - const tsMillis = normalizeWebhookTimestampMs(providedTimestamp); - if (tsMillis == null) throw unauthorized(); - const replayWindowSec = trigger.replayWindowSec ?? 300; - if (Math.abs(Date.now() - tsMillis) > replayWindowSec * 1e3) { - throw unauthorized(); - } - const expectedHmac = crypto4.createHmac("sha256", secretValue).update(`${providedTimestamp}.`).update(rawBody).digest("hex"); - const normalizedSignature = providedSignature.replace(/^sha256=/, ""); - const valid = normalizedSignature.length === expectedHmac.length && crypto4.timingSafeEqual(Buffer.from(normalizedSignature), Buffer.from(expectedHmac)); - if (!valid) throw unauthorized(); - } - return dispatchRoutineRun({ - routine, - trigger, - source: "webhook", - payload: input.payload, - variables: isPlainRecord4(input.payload) && isPlainRecord4(input.payload.variables) ? input.payload.variables : null, - idempotencyKey: input.idempotencyKey - }); - }, - listRuns: async (routineId, limit = 50) => { - const cappedLimit = Math.max(1, Math.min(limit, 200)); - const rows = await db.select({ - id: routineRuns.id, - companyId: routineRuns.companyId, - routineId: routineRuns.routineId, - triggerId: routineRuns.triggerId, - source: routineRuns.source, - status: routineRuns.status, - triggeredAt: routineRuns.triggeredAt, - idempotencyKey: routineRuns.idempotencyKey, - triggerPayload: routineRuns.triggerPayload, - linkedIssueId: routineRuns.linkedIssueId, - coalescedIntoRunId: routineRuns.coalescedIntoRunId, - failureReason: routineRuns.failureReason, - completedAt: routineRuns.completedAt, - createdAt: routineRuns.createdAt, - updatedAt: routineRuns.updatedAt, - triggerKind: routineTriggers.kind, - triggerLabel: routineTriggers.label, - issueIdentifier: issues.identifier, - issueTitle: issues.title, - issueStatus: issues.status, - issuePriority: issues.priority, - issueUpdatedAt: issues.updatedAt - }).from(routineRuns).leftJoin(routineTriggers, eq(routineRuns.triggerId, routineTriggers.id)).leftJoin(issues, eq(routineRuns.linkedIssueId, issues.id)).where(eq(routineRuns.routineId, routineId)).orderBy(desc(routineRuns.createdAt)).limit(cappedLimit); - return rows.map((row) => ({ - id: row.id, - companyId: row.companyId, - routineId: row.routineId, - triggerId: row.triggerId, - source: row.source, - status: row.status, - triggeredAt: row.triggeredAt, - idempotencyKey: row.idempotencyKey, - triggerPayload: row.triggerPayload, - linkedIssueId: row.linkedIssueId, - coalescedIntoRunId: row.coalescedIntoRunId, - failureReason: row.failureReason, - completedAt: row.completedAt, - createdAt: row.createdAt, - updatedAt: row.updatedAt, - linkedIssue: row.linkedIssueId ? { - id: row.linkedIssueId, - identifier: row.issueIdentifier, - title: row.issueTitle ?? "Routine execution", - status: row.issueStatus ?? "todo", - priority: row.issuePriority ?? "medium", - updatedAt: row.issueUpdatedAt ?? row.updatedAt - } : null, - trigger: row.triggerId ? { - id: row.triggerId, - kind: row.triggerKind, - label: row.triggerLabel - } : null - })); - }, - tickScheduledTriggers: async (now2 = /* @__PURE__ */ new Date()) => { - const due = await db.select({ - trigger: routineTriggers, - routine: routines - }).from(routineTriggers).innerJoin(routines, eq(routineTriggers.routineId, routines.id)).where( - and( - eq(routineTriggers.kind, "schedule"), - eq(routineTriggers.enabled, true), - eq(routines.status, "active"), - isNotNull(routineTriggers.nextRunAt), - lte(routineTriggers.nextRunAt, now2) - ) - ).orderBy(asc(routineTriggers.nextRunAt), asc(routineTriggers.createdAt)); - let triggered = 0; - for (const row of due) { - if (!row.trigger.nextRunAt || !row.trigger.cronExpression || !row.trigger.timezone) continue; - let runCount = 1; - let claimedNextRunAt = nextCronTickInTimeZone(row.trigger.cronExpression, row.trigger.timezone, now2); - if (row.routine.catchUpPolicy === "enqueue_missed_with_cap") { - let cursor2 = row.trigger.nextRunAt; - runCount = 0; - while (cursor2 && cursor2 <= now2 && runCount < MAX_CATCH_UP_RUNS) { - runCount += 1; - claimedNextRunAt = nextCronTickInTimeZone(row.trigger.cronExpression, row.trigger.timezone, cursor2); - cursor2 = claimedNextRunAt; - } - } - const claimed = await db.update(routineTriggers).set({ - nextRunAt: claimedNextRunAt, - updatedAt: /* @__PURE__ */ new Date() - }).where( - and( - eq(routineTriggers.id, row.trigger.id), - eq(routineTriggers.enabled, true), - eq(routineTriggers.nextRunAt, row.trigger.nextRunAt) - ) - ).returning({ id: routineTriggers.id }).then((rows) => rows[0] ?? null); - if (!claimed) continue; - for (let i5 = 0; i5 < runCount; i5 += 1) { - await dispatchRoutineRun({ - routine: row.routine, - trigger: row.trigger, - source: "schedule" - }); - triggered += 1; - } - } - return { triggered }; - }, - syncRunStatusForIssue: async (issueId) => { - const issue2 = await db.select({ - id: issues.id, - status: issues.status, - originKind: issues.originKind, - originRunId: issues.originRunId - }).from(issues).where(eq(issues.id, issueId)).then((rows) => rows[0] ?? null); - if (!issue2 || issue2.originKind !== "routine_execution" || !issue2.originRunId) return null; - if (issue2.status === "done") { - return finalizeRun(issue2.originRunId, { - status: "completed", - completedAt: /* @__PURE__ */ new Date() - }); - } - if (issue2.status === "blocked" || issue2.status === "cancelled") { - return finalizeRun(issue2.originRunId, { - status: "failed", - failureReason: `Execution issue moved to ${issue2.status}`, - completedAt: /* @__PURE__ */ new Date() - }); - } - return null; - } - }; -} - -// server/src/services/finance.ts -init_drizzle_orm(); -init_src2(); -async function assertBelongsToCompany(db, table, id, companyId, label) { - const row = await db.select().from(table).where(eq(table.id, id)).then((rows) => rows[0] ?? null); - if (!row) throw notFound(`${label} not found`); - if (row.companyId !== companyId) { - throw unprocessable(`${label} does not belong to company`); - } -} -function rangeConditions(companyId, range2) { - const conditions = [eq(financeEvents.companyId, companyId)]; - if (range2?.from) conditions.push(gte(financeEvents.occurredAt, range2.from)); - if (range2?.to) conditions.push(lte(financeEvents.occurredAt, range2.to)); - return conditions; -} -function financeService(db) { - const debitExpr = sql`coalesce(sum(case when ${financeEvents.direction} = 'debit' then ${financeEvents.amountCents} else 0 end), 0)::int`; - const creditExpr = sql`coalesce(sum(case when ${financeEvents.direction} = 'credit' then ${financeEvents.amountCents} else 0 end), 0)::int`; - const estimatedDebitExpr = sql`coalesce(sum(case when ${financeEvents.direction} = 'debit' and ${financeEvents.estimated} = true then ${financeEvents.amountCents} else 0 end), 0)::int`; - return { - createEvent: async (companyId, data2) => { - if (data2.agentId) await assertBelongsToCompany(db, agents, data2.agentId, companyId, "Agent"); - if (data2.issueId) await assertBelongsToCompany(db, issues, data2.issueId, companyId, "Issue"); - if (data2.projectId) await assertBelongsToCompany(db, projects, data2.projectId, companyId, "Project"); - if (data2.goalId) await assertBelongsToCompany(db, goals, data2.goalId, companyId, "Goal"); - if (data2.heartbeatRunId) await assertBelongsToCompany(db, heartbeatRuns, data2.heartbeatRunId, companyId, "Heartbeat run"); - if (data2.costEventId) await assertBelongsToCompany(db, costEvents, data2.costEventId, companyId, "Cost event"); - const event = await db.insert(financeEvents).values({ - ...data2, - companyId, - currency: data2.currency ?? "USD", - direction: data2.direction ?? "debit", - estimated: data2.estimated ?? false - }).returning().then((rows) => rows[0]); - return event; - }, - summary: async (companyId, range2) => { - const conditions = rangeConditions(companyId, range2); - const [row] = await db.select({ - debitCents: debitExpr, - creditCents: creditExpr, - estimatedDebitCents: estimatedDebitExpr, - eventCount: sql`count(*)::int` - }).from(financeEvents).where(and(...conditions)); - return { - companyId, - debitCents: Number(row?.debitCents ?? 0), - creditCents: Number(row?.creditCents ?? 0), - netCents: Number(row?.debitCents ?? 0) - Number(row?.creditCents ?? 0), - estimatedDebitCents: Number(row?.estimatedDebitCents ?? 0), - eventCount: Number(row?.eventCount ?? 0) - }; - }, - byBiller: async (companyId, range2) => { - const conditions = rangeConditions(companyId, range2); - return db.select({ - biller: financeEvents.biller, - debitCents: debitExpr, - creditCents: creditExpr, - estimatedDebitCents: estimatedDebitExpr, - eventCount: sql`count(*)::int`, - kindCount: sql`count(distinct ${financeEvents.eventKind})::int`, - netCents: sql`(${debitExpr} - ${creditExpr})::int` - }).from(financeEvents).where(and(...conditions)).groupBy(financeEvents.biller).orderBy(desc(sql`(${debitExpr} - ${creditExpr})::int`), financeEvents.biller); - }, - byKind: async (companyId, range2) => { - const conditions = rangeConditions(companyId, range2); - return db.select({ - eventKind: financeEvents.eventKind, - debitCents: debitExpr, - creditCents: creditExpr, - estimatedDebitCents: estimatedDebitExpr, - eventCount: sql`count(*)::int`, - billerCount: sql`count(distinct ${financeEvents.biller})::int`, - netCents: sql`(${debitExpr} - ${creditExpr})::int` - }).from(financeEvents).where(and(...conditions)).groupBy(financeEvents.eventKind).orderBy(desc(sql`(${debitExpr} - ${creditExpr})::int`), financeEvents.eventKind); - }, - list: async (companyId, range2, limit = 100) => { - const conditions = rangeConditions(companyId, range2); - return db.select().from(financeEvents).where(and(...conditions)).orderBy(desc(financeEvents.occurredAt), desc(financeEvents.createdAt)).limit(limit); - } - }; -} - -// server/src/services/dashboard.ts -init_drizzle_orm(); -init_src2(); -function dashboardService(db) { - const budgets = budgetService(db); - return { - summary: async (companyId) => { - const company = await db.select().from(companies).where(eq(companies.id, companyId)).then((rows) => rows[0] ?? null); - if (!company) throw notFound("Company not found"); - const agentRows = await db.select({ status: agents.status, count: sql`count(*)` }).from(agents).where(eq(agents.companyId, companyId)).groupBy(agents.status); - const taskRows = await db.select({ status: issues.status, count: sql`count(*)` }).from(issues).where(eq(issues.companyId, companyId)).groupBy(issues.status); - const pendingApprovals = await db.select({ count: sql`count(*)` }).from(approvals).where(and(eq(approvals.companyId, companyId), eq(approvals.status, "pending"))).then((rows) => Number(rows[0]?.count ?? 0)); - const agentCounts = { - active: 0, - running: 0, - paused: 0, - error: 0 - }; - for (const row of agentRows) { - const count2 = Number(row.count); - const bucket = row.status === "idle" ? "active" : row.status; - agentCounts[bucket] = (agentCounts[bucket] ?? 0) + count2; - } - const taskCounts = { - open: 0, - inProgress: 0, - blocked: 0, - done: 0 - }; - for (const row of taskRows) { - const count2 = Number(row.count); - if (row.status === "in_progress") taskCounts.inProgress += count2; - if (row.status === "blocked") taskCounts.blocked += count2; - if (row.status === "done") taskCounts.done += count2; - if (row.status !== "done" && row.status !== "cancelled") taskCounts.open += count2; - } - const now2 = /* @__PURE__ */ new Date(); - const monthStart = new Date(now2.getFullYear(), now2.getMonth(), 1); - const [{ monthSpend }] = await db.select({ - monthSpend: sql`coalesce(sum(${costEvents.costCents}), 0)::int` - }).from(costEvents).where( - and( - eq(costEvents.companyId, companyId), - gte(costEvents.occurredAt, monthStart) - ) - ); - const monthSpendCents = Number(monthSpend); - const utilization = company.budgetMonthlyCents > 0 ? monthSpendCents / company.budgetMonthlyCents * 100 : 0; - const budgetOverview = await budgets.overview(companyId); - return { - companyId, - agents: { - active: agentCounts.active, - running: agentCounts.running, - paused: agentCounts.paused, - error: agentCounts.error - }, - tasks: taskCounts, - costs: { - monthSpendCents, - monthBudgetCents: company.budgetMonthlyCents, - monthUtilizationPercent: Number(utilization.toFixed(2)) - }, - pendingApprovals, - budgets: { - activeIncidents: budgetOverview.activeIncidents.length, - pendingApprovals: budgetOverview.pendingApprovalCount, - pausedAgents: budgetOverview.pausedAgentCount, - pausedProjects: budgetOverview.pausedProjectCount - } - }; - } - }; -} - -// server/src/services/sidebar-badges.ts -init_drizzle_orm(); -init_src2(); -var ACTIONABLE_APPROVAL_STATUSES = ["pending", "revision_requested"]; -var FAILED_HEARTBEAT_STATUSES = ["failed", "timed_out"]; -function normalizeTimestamp2(value) { - if (!value) return 0; - const timestamp2 = new Date(value).getTime(); - return Number.isFinite(timestamp2) ? timestamp2 : 0; -} -function isDismissed(dismissedAtByKey, itemKey, activityAt) { - const dismissedAt = dismissedAtByKey.get(itemKey); - if (dismissedAt == null) return false; - return dismissedAt >= normalizeTimestamp2(activityAt); -} -function sidebarBadgeService(db) { - return { - get: async (companyId, extra) => { - const actionableApprovals = await db.select({ id: approvals.id, updatedAt: approvals.updatedAt }).from(approvals).where( - and( - eq(approvals.companyId, companyId), - inArray(approvals.status, ACTIONABLE_APPROVAL_STATUSES) - ) - ).then( - (rows) => rows.filter((row) => !isDismissed(extra?.dismissals ?? /* @__PURE__ */ new Map(), `approval:${row.id}`, row.updatedAt)).length - ); - const latestRunByAgent = await db.selectDistinctOn([heartbeatRuns.agentId], { - id: heartbeatRuns.id, - runStatus: heartbeatRuns.status, - createdAt: heartbeatRuns.createdAt - }).from(heartbeatRuns).innerJoin(agents, eq(heartbeatRuns.agentId, agents.id)).where( - and( - eq(heartbeatRuns.companyId, companyId), - eq(agents.companyId, companyId), - not(eq(agents.status, "terminated")) - ) - ).orderBy(heartbeatRuns.agentId, desc(heartbeatRuns.createdAt)); - const failedRuns = latestRunByAgent.filter( - (row) => FAILED_HEARTBEAT_STATUSES.includes(row.runStatus) && !isDismissed(extra?.dismissals ?? /* @__PURE__ */ new Map(), `run:${row.id}`, row.createdAt) - ).length; - const joinRequests2 = (extra?.joinRequests ?? []).filter( - (row) => !isDismissed( - extra?.dismissals ?? /* @__PURE__ */ new Map(), - `join:${row.id}`, - row.updatedAt ?? row.createdAt - ) - ).length; - const unreadTouchedIssues = extra?.unreadTouchedIssues ?? 0; - return { - inbox: actionableApprovals + failedRuns + joinRequests2 + unreadTouchedIssues, - approvals: actionableApprovals, - failedRuns, - joinRequests: joinRequests2 - }; - } - }; -} - -// server/src/services/sidebar-preferences.ts -init_drizzle_orm(); -init_src2(); -function normalizeOrderedIds(value) { - if (!Array.isArray(value)) return []; - const orderedIds = []; - const seen = /* @__PURE__ */ new Set(); - for (const item of value) { - if (typeof item !== "string") continue; - const trimmed = item.trim(); - if (!trimmed || seen.has(trimmed)) continue; - seen.add(trimmed); - orderedIds.push(trimmed); - } - return orderedIds; -} -function toPreference(orderedIds, updatedAt) { - return { - orderedIds: normalizeOrderedIds(orderedIds), - updatedAt - }; -} -function sidebarPreferenceService(db) { - return { - async getCompanyOrder(userId) { - const row = await db.query.userSidebarPreferences.findFirst({ - where: eq(userSidebarPreferences.userId, userId) - }); - return toPreference(row?.companyOrder ?? [], row?.updatedAt ?? null); - }, - async upsertCompanyOrder(userId, orderedIds) { - const now2 = /* @__PURE__ */ new Date(); - const normalized = normalizeOrderedIds(orderedIds); - const [row] = await db.insert(userSidebarPreferences).values({ - userId, - companyOrder: normalized, - updatedAt: now2 - }).onConflictDoUpdate({ - target: [userSidebarPreferences.userId], - set: { - companyOrder: normalized, - updatedAt: now2 - } - }).returning(); - return toPreference(row?.companyOrder ?? normalized, row?.updatedAt ?? now2); - }, - async getProjectOrder(companyId, userId) { - const row = await db.query.companyUserSidebarPreferences.findFirst({ - where: and( - eq(companyUserSidebarPreferences.companyId, companyId), - eq(companyUserSidebarPreferences.userId, userId) - ) - }); - return toPreference(row?.projectOrder ?? [], row?.updatedAt ?? null); - }, - async upsertProjectOrder(companyId, userId, orderedIds) { - const now2 = /* @__PURE__ */ new Date(); - const normalized = normalizeOrderedIds(orderedIds); - const [row] = await db.insert(companyUserSidebarPreferences).values({ - companyId, - userId, - projectOrder: normalized, - updatedAt: now2 - }).onConflictDoUpdate({ - target: [companyUserSidebarPreferences.companyId, companyUserSidebarPreferences.userId], - set: { - projectOrder: normalized, - updatedAt: now2 - } - }).returning(); - return toPreference(row?.projectOrder ?? normalized, row?.updatedAt ?? now2); - } - }; -} - -// server/src/services/inbox-dismissals.ts -init_drizzle_orm(); -init_src2(); -function inboxDismissalService(db) { - return { - list: async (companyId, userId) => db.select().from(inboxDismissals).where(and(eq(inboxDismissals.companyId, companyId), eq(inboxDismissals.userId, userId))).orderBy(desc(inboxDismissals.updatedAt)), - dismiss: async (companyId, userId, itemKey, dismissedAt = /* @__PURE__ */ new Date()) => { - const now2 = /* @__PURE__ */ new Date(); - const [row] = await db.insert(inboxDismissals).values({ - companyId, - userId, - itemKey, - dismissedAt, - updatedAt: now2 - }).onConflictDoUpdate({ - target: [inboxDismissals.companyId, inboxDismissals.userId, inboxDismissals.itemKey], - set: { - dismissedAt, - updatedAt: now2 - } - }).returning(); - return row; - } - }; -} - -// server/src/services/access.ts -init_drizzle_orm(); -init_src2(); -function accessService(db) { - async function isInstanceAdmin(userId) { - if (!userId) return false; - const row = await db.select({ id: instanceUserRoles.id }).from(instanceUserRoles).where(and(eq(instanceUserRoles.userId, userId), eq(instanceUserRoles.role, "instance_admin"))).then((rows) => rows[0] ?? null); - return Boolean(row); - } - async function getMembership(companyId, principalType, principalId) { - return db.select().from(companyMemberships).where( - and( - eq(companyMemberships.companyId, companyId), - eq(companyMemberships.principalType, principalType), - eq(companyMemberships.principalId, principalId) - ) - ).then((rows) => rows[0] ?? null); - } - async function hasPermission(companyId, principalType, principalId, permissionKey) { - const membership = await getMembership(companyId, principalType, principalId); - if (!membership || membership.status !== "active") return false; - const grant = await db.select({ id: principalPermissionGrants.id }).from(principalPermissionGrants).where( - and( - eq(principalPermissionGrants.companyId, companyId), - eq(principalPermissionGrants.principalType, principalType), - eq(principalPermissionGrants.principalId, principalId), - eq(principalPermissionGrants.permissionKey, permissionKey) - ) - ).then((rows) => rows[0] ?? null); - return Boolean(grant); - } - async function canUser(companyId, userId, permissionKey) { - if (!userId) return false; - if (await isInstanceAdmin(userId)) return true; - return hasPermission(companyId, "user", userId, permissionKey); - } - async function listMembers(companyId) { - return db.select().from(companyMemberships).where(eq(companyMemberships.companyId, companyId)).orderBy(sql`${companyMemberships.createdAt} desc`); - } - async function listActiveUserMemberships(companyId) { - return db.select().from(companyMemberships).where( - and( - eq(companyMemberships.companyId, companyId), - eq(companyMemberships.principalType, "user"), - eq(companyMemberships.status, "active") - ) - ).orderBy(sql`${companyMemberships.createdAt} asc`); - } - async function setMemberPermissions(companyId, memberId, grants, grantedByUserId) { - const member2 = await db.select().from(companyMemberships).where(and(eq(companyMemberships.companyId, companyId), eq(companyMemberships.id, memberId))).then((rows) => rows[0] ?? null); - if (!member2) return null; - await db.transaction(async (tx) => { - await tx.delete(principalPermissionGrants).where( - and( - eq(principalPermissionGrants.companyId, companyId), - eq(principalPermissionGrants.principalType, member2.principalType), - eq(principalPermissionGrants.principalId, member2.principalId) - ) - ); - if (grants.length > 0) { - await tx.insert(principalPermissionGrants).values( - grants.map((grant) => ({ - companyId, - principalType: member2.principalType, - principalId: member2.principalId, - permissionKey: grant.permissionKey, - scope: grant.scope ?? null, - grantedByUserId, - createdAt: /* @__PURE__ */ new Date(), - updatedAt: /* @__PURE__ */ new Date() - })) - ); - } - }); - return member2; - } - async function promoteInstanceAdmin(userId) { - const existing = await db.select().from(instanceUserRoles).where(and(eq(instanceUserRoles.userId, userId), eq(instanceUserRoles.role, "instance_admin"))).then((rows) => rows[0] ?? null); - if (existing) return existing; - return db.insert(instanceUserRoles).values({ - userId, - role: "instance_admin" - }).returning().then((rows) => rows[0]); - } - async function demoteInstanceAdmin(userId) { - return db.delete(instanceUserRoles).where(and(eq(instanceUserRoles.userId, userId), eq(instanceUserRoles.role, "instance_admin"))).returning().then((rows) => rows[0] ?? null); - } - async function listUserCompanyAccess(userId) { - return db.select().from(companyMemberships).where(and(eq(companyMemberships.principalType, "user"), eq(companyMemberships.principalId, userId))).orderBy(sql`${companyMemberships.createdAt} desc`); - } - async function setUserCompanyAccess(userId, companyIds) { - const existing = await listUserCompanyAccess(userId); - const existingByCompany = new Map(existing.map((row) => [row.companyId, row])); - const target = new Set(companyIds); - await db.transaction(async (tx) => { - const toDelete = existing.filter((row) => !target.has(row.companyId)).map((row) => row.id); - if (toDelete.length > 0) { - await tx.delete(companyMemberships).where(inArray(companyMemberships.id, toDelete)); - } - for (const companyId of target) { - if (existingByCompany.has(companyId)) continue; - await tx.insert(companyMemberships).values({ - companyId, - principalType: "user", - principalId: userId, - status: "active", - membershipRole: "member" - }); - } - }); - return listUserCompanyAccess(userId); - } - async function ensureMembership(companyId, principalType, principalId, membershipRole = "member", status = "active") { - const existing = await getMembership(companyId, principalType, principalId); - if (existing) { - if (existing.status !== status || existing.membershipRole !== membershipRole) { - const updated = await db.update(companyMemberships).set({ status, membershipRole, updatedAt: /* @__PURE__ */ new Date() }).where(eq(companyMemberships.id, existing.id)).returning().then((rows) => rows[0] ?? null); - return updated ?? existing; - } - return existing; - } - return db.insert(companyMemberships).values({ - companyId, - principalType, - principalId, - status, - membershipRole - }).returning().then((rows) => rows[0]); - } - async function setPrincipalGrants(companyId, principalType, principalId, grants, grantedByUserId) { - await db.transaction(async (tx) => { - await tx.delete(principalPermissionGrants).where( - and( - eq(principalPermissionGrants.companyId, companyId), - eq(principalPermissionGrants.principalType, principalType), - eq(principalPermissionGrants.principalId, principalId) - ) - ); - if (grants.length === 0) return; - await tx.insert(principalPermissionGrants).values( - grants.map((grant) => ({ - companyId, - principalType, - principalId, - permissionKey: grant.permissionKey, - scope: grant.scope ?? null, - grantedByUserId, - createdAt: /* @__PURE__ */ new Date(), - updatedAt: /* @__PURE__ */ new Date() - })) - ); - }); - } - async function copyActiveUserMemberships(sourceCompanyId, targetCompanyId) { - const sourceMemberships = await listActiveUserMemberships(sourceCompanyId); - for (const membership of sourceMemberships) { - await ensureMembership( - targetCompanyId, - "user", - membership.principalId, - membership.membershipRole, - "active" - ); - } - return sourceMemberships; - } - async function listPrincipalGrants(companyId, principalType, principalId) { - return db.select().from(principalPermissionGrants).where( - and( - eq(principalPermissionGrants.companyId, companyId), - eq(principalPermissionGrants.principalType, principalType), - eq(principalPermissionGrants.principalId, principalId) - ) - ).orderBy(principalPermissionGrants.permissionKey); - } - async function setPrincipalPermission(companyId, principalType, principalId, permissionKey, enabled, grantedByUserId, scope = null) { - if (!enabled) { - await db.delete(principalPermissionGrants).where( - and( - eq(principalPermissionGrants.companyId, companyId), - eq(principalPermissionGrants.principalType, principalType), - eq(principalPermissionGrants.principalId, principalId), - eq(principalPermissionGrants.permissionKey, permissionKey) - ) - ); - return; - } - await ensureMembership(companyId, principalType, principalId, "member", "active"); - const existing = await db.select().from(principalPermissionGrants).where( - and( - eq(principalPermissionGrants.companyId, companyId), - eq(principalPermissionGrants.principalType, principalType), - eq(principalPermissionGrants.principalId, principalId), - eq(principalPermissionGrants.permissionKey, permissionKey) - ) - ).then((rows) => rows[0] ?? null); - if (existing) { - await db.update(principalPermissionGrants).set({ - scope, - grantedByUserId, - updatedAt: /* @__PURE__ */ new Date() - }).where(eq(principalPermissionGrants.id, existing.id)); - return; - } - await db.insert(principalPermissionGrants).values({ - companyId, - principalType, - principalId, - permissionKey, - scope, - grantedByUserId, - createdAt: /* @__PURE__ */ new Date(), - updatedAt: /* @__PURE__ */ new Date() - }); - } - return { - isInstanceAdmin, - canUser, - hasPermission, - getMembership, - ensureMembership, - listMembers, - listActiveUserMemberships, - copyActiveUserMemberships, - setMemberPermissions, - promoteInstanceAdmin, - demoteInstanceAdmin, - listUserCompanyAccess, - setUserCompanyAccess, - setPrincipalGrants, - listPrincipalGrants, - setPrincipalPermission - }; -} - -// server/src/services/company-portability.ts -import { createHash as createHash14 } from "node:crypto"; -import { execFile as execFile6 } from "node:child_process"; -import path40 from "node:path"; -import { promisify as promisify6 } from "node:util"; - -// server/src/services/company-export-readme.ts -var ROLE_LABELS = { - ceo: "CEO", - cto: "CTO", - cmo: "CMO", - cfo: "CFO", - coo: "COO", - vp: "VP", - manager: "Manager", - engineer: "Engineer", - agent: "Agent" -}; -function skillSourceLabel(skill) { - if (skill.sourceLocator) { - if (skill.sourceType === "github" || skill.sourceType === "skills_sh" || skill.sourceType === "url") { - return `[${skill.sourceType}](${skill.sourceLocator})`; - } - return skill.sourceLocator; - } - if (skill.sourceType === "local") return "local"; - return skill.sourceType ?? "\u2014"; -} -function generateReadme(manifest, options) { - const lines = []; - lines.push(`# ${options.companyName}`); - lines.push(""); - if (options.companyDescription) { - lines.push(`> ${options.companyDescription}`); - lines.push(""); - } - if (manifest.agents.length > 0) { - lines.push("![Org Chart](images/org-chart.png)"); - lines.push(""); - } - lines.push("## What's Inside"); - lines.push(""); - lines.push("> This is an [Agent Company](https://agentcompanies.io) package from [Taskcore](https://taskcore.khulnasoft.com)"); - lines.push(""); - const counts = []; - if (manifest.agents.length > 0) counts.push(["Agents", manifest.agents.length]); - if (manifest.projects.length > 0) counts.push(["Projects", manifest.projects.length]); - if (manifest.skills.length > 0) counts.push(["Skills", manifest.skills.length]); - if (manifest.issues.length > 0) counts.push(["Tasks", manifest.issues.length]); - if (counts.length > 0) { - lines.push("| Content | Count |"); - lines.push("|---------|-------|"); - for (const [label, count2] of counts) { - lines.push(`| ${label} | ${count2} |`); - } - lines.push(""); - } - if (manifest.agents.length > 0) { - lines.push("### Agents"); - lines.push(""); - lines.push("| Agent | Role | Reports To |"); - lines.push("|-------|------|------------|"); - for (const agent of manifest.agents) { - const roleLabel = ROLE_LABELS[agent.role] ?? agent.role; - const reportsTo = agent.reportsToSlug ?? "\u2014"; - lines.push(`| ${agent.name} | ${roleLabel} | ${reportsTo} |`); - } - lines.push(""); - } - if (manifest.projects.length > 0) { - lines.push("### Projects"); - lines.push(""); - for (const project of manifest.projects) { - const desc3 = project.description ? ` \u2014 ${project.description}` : ""; - lines.push(`- **${project.name}**${desc3}`); - } - lines.push(""); - } - if (manifest.skills.length > 0) { - lines.push("### Skills"); - lines.push(""); - lines.push("| Skill | Description | Source |"); - lines.push("|-------|-------------|--------|"); - for (const skill of manifest.skills) { - const desc3 = skill.description ?? "\u2014"; - const source = skillSourceLabel(skill); - lines.push(`| ${skill.name} | ${desc3} | ${source} |`); - } - lines.push(""); - } - lines.push("## Getting Started"); - lines.push(""); - lines.push("```bash"); - lines.push("pnpm taskcore company import this-github-url-or-folder"); - lines.push("```"); - lines.push(""); - lines.push("See [Taskcore](https://taskcore.khulnasoft.com) for more information."); - lines.push(""); - lines.push("---"); - lines.push(`Exported from [Taskcore](https://taskcore.khulnasoft.com) on ${(/* @__PURE__ */ new Date()).toISOString().split("T")[0]}`); - lines.push(""); - return lines.join("\n"); -} - -// server/src/routes/org-chart-svg.ts -var ORG_CHART_STYLES = ["monochrome", "nebula", "circuit", "warmth", "schematic"]; -var ROLE_ICONS = { - ceo: { - bg: "#fef3c7", - roleLabel: "Chief Executive", - accentColor: "#f0883e", - iconColor: "#92400e", - iconPath: "M8 1l2.2 4.5L15 6.2l-3.5 3.4.8 4.9L8 12.2 3.7 14.5l.8-4.9L1 6.2l4.8-.7z", - // 👑 Crown - emojiSvg: `` - }, - cto: { - bg: "#dbeafe", - roleLabel: "Technology", - accentColor: "#58a6ff", - iconColor: "#1e40af", - iconPath: "M2 3l5 5-5 5M9 13h5", - // 💻 Laptop - emojiSvg: `` - }, - cmo: { - bg: "#dcfce7", - roleLabel: "Marketing", - accentColor: "#3fb950", - iconColor: "#166534", - iconPath: "M8 1a7 7 0 1 0 0 14A7 7 0 0 0 8 1zM1 8h14M8 1c-2 2-3 4.5-3 7s1 5 3 7c2-2 3-4.5 3-7s-1-5-3-7z", - // 🌐 Globe with meridians - emojiSvg: `` - }, - cfo: { - bg: "#fef3c7", - roleLabel: "Finance", - accentColor: "#f0883e", - iconColor: "#92400e", - iconPath: "M8 1v14M5 4.5C5 3.1 6.3 2 8 2s3 1.1 3 2.5S9.7 7 8 7 5 8.1 5 9.5 6.3 12 8 12s3-1.1 3-2.5", - // 📊 Bar chart - emojiSvg: `` - }, - coo: { - bg: "#e0f2fe", - roleLabel: "Operations", - accentColor: "#58a6ff", - iconColor: "#075985", - iconPath: "M8 5.5a2.5 2.5 0 1 0 0 5 2.5 2.5 0 0 0 0-5z", - // ⚙️ Gear - emojiSvg: `` - }, - engineer: { - bg: "#f3e8ff", - roleLabel: "Engineering", - accentColor: "#bc8cff", - iconColor: "#6b21a8", - iconPath: "M5 3L1 8l4 5M11 3l4 5-4 5", - // ⌨️ Keyboard - emojiSvg: `` - }, - quality: { - bg: "#ffe4e6", - roleLabel: "Quality", - accentColor: "#f778ba", - iconColor: "#9f1239", - iconPath: "M4 8l3 3 5-6M8 1L2 4v4c0 3.5 2.6 6.8 6 8 3.4-1.2 6-4.5 6-8V4z", - // 🔬 Microscope - emojiSvg: `` - }, - design: { - bg: "#fce7f3", - roleLabel: "Design", - accentColor: "#79c0ff", - iconColor: "#9d174d", - iconPath: "M12 2l2 2-9 9H3v-2zM9.5 4.5l2 2", - // 🪄 Magic wand - emojiSvg: `` - }, - finance: { - bg: "#fef3c7", - roleLabel: "Finance", - accentColor: "#f0883e", - iconColor: "#92400e", - iconPath: "M8 1v14M5 4.5C5 3.1 6.3 2 8 2s3 1.1 3 2.5S9.7 7 8 7 5 8.1 5 9.5 6.3 12 8 12s3-1.1 3-2.5", - // 📊 Bar chart (same as CFO) - emojiSvg: `` - }, - operations: { - bg: "#e0f2fe", - roleLabel: "Operations", - accentColor: "#58a6ff", - iconColor: "#075985", - iconPath: "M8 5.5a2.5 2.5 0 1 0 0 5 2.5 2.5 0 0 0 0-5z", - // ⚙️ Gear (same as COO) - emojiSvg: `` - }, - default: { - bg: "#f3e8ff", - roleLabel: "Agent", - accentColor: "#bc8cff", - iconColor: "#6b21a8", - iconPath: "M8 8a3 3 0 1 0 0-6 3 3 0 0 0 0 6zM2 14c0-3.3 2.7-4 6-4s6 .7 6 4", - // 👤 Person silhouette - emojiSvg: `` - } -}; -function guessRoleTag(node) { - const name = node.name.toLowerCase(); - const role = node.role.toLowerCase(); - if (name === "ceo" || role.includes("chief executive")) return "ceo"; - if (name === "cto" || role.includes("chief technology") || role.includes("technology")) return "cto"; - if (name === "cmo" || role.includes("chief marketing") || role.includes("marketing")) return "cmo"; - if (name === "cfo" || role.includes("chief financial")) return "cfo"; - if (name === "coo" || role.includes("chief operating")) return "coo"; - if (role.includes("engineer") || role.includes("eng")) return "engineer"; - if (role.includes("quality") || role.includes("qa")) return "quality"; - if (role.includes("design")) return "design"; - if (role.includes("finance")) return "finance"; - if (role.includes("operations") || role.includes("ops")) return "operations"; - return "default"; -} -function getRoleInfo(node) { - const tag3 = guessRoleTag(node); - return { tag: tag3, ...ROLE_ICONS[tag3] || ROLE_ICONS.default }; -} -var THEMES = { - // 01 — Monochrome (Vercel-inspired, dark minimal) - monochrome: { - bgColor: "#18181b", - cardBg: "#18181b", - cardBorder: "#27272a", - cardRadius: 6, - cardShadow: null, - lineColor: "#3f3f46", - lineWidth: 1.5, - nameColor: "#fafafa", - roleColor: "#71717a", - font: "'Inter', system-ui, sans-serif", - watermarkColor: "rgba(255,255,255,0.25)", - defs: () => "", - bgExtras: () => "", - renderCard: null, - cardAccent: null - }, - // 02 — Nebula (glassmorphism on cosmic gradient) - nebula: { - bgColor: "#0f0c29", - cardBg: "rgba(255,255,255,0.07)", - cardBorder: "rgba(255,255,255,0.12)", - cardRadius: 6, - cardShadow: null, - lineColor: "rgba(255,255,255,0.25)", - lineWidth: 1.5, - nameColor: "#ffffff", - roleColor: "rgba(255,255,255,0.45)", - font: "'Inter', system-ui, sans-serif", - watermarkColor: "rgba(255,255,255,0.2)", - defs: (_w, _h4) => ` - - - - - - - - - - - - - `, - bgExtras: (w5, h5) => ` - - - `, - renderCard: null, - cardAccent: null - }, - // 03 — Circuit (Linear/Raycast — indigo traces, amethyst CEO) - circuit: { - bgColor: "#0c0c0e", - cardBg: "rgba(99,102,241,0.04)", - cardBorder: "rgba(99,102,241,0.18)", - cardRadius: 5, - cardShadow: null, - lineColor: "rgba(99,102,241,0.35)", - lineWidth: 1.5, - nameColor: "#e4e4e7", - roleColor: "#6366f1", - font: "'Inter', system-ui, sans-serif", - watermarkColor: "rgba(99,102,241,0.3)", - defs: () => "", - bgExtras: () => "", - renderCard: (ln, theme) => { - const { tag: tag3, roleLabel, emojiSvg } = getRoleInfo(ln.node); - const cx = ln.x + ln.width / 2; - const isCeo = tag3 === "ceo"; - const borderColor = isCeo ? "rgba(168,85,247,0.35)" : theme.cardBorder; - const bgColor = isCeo ? "rgba(168,85,247,0.06)" : theme.cardBg; - const avatarCY = ln.y + 27; - const nameY = ln.y + 66; - const roleY = ln.y + 82; - return ` - - ${renderEmojiAvatar(cx, avatarCY, 17, "rgba(99,102,241,0.08)", emojiSvg, "rgba(99,102,241,0.15)")} - ${escapeXml(ln.node.name)} - ${escapeXml(roleLabel).toUpperCase()} - `; - }, - cardAccent: null - }, - // 04 — Warmth (Airbnb — light, colored avatars, soft shadows) - warmth: { - bgColor: "#fafaf9", - cardBg: "#ffffff", - cardBorder: "#e7e5e4", - cardRadius: 6, - cardShadow: "rgba(0,0,0,0.05)", - lineColor: "#d6d3d1", - lineWidth: 2, - nameColor: "#1c1917", - roleColor: "#78716c", - font: "'Inter', -apple-system, BlinkMacSystemFont, sans-serif", - watermarkColor: "rgba(0,0,0,0.25)", - defs: () => "", - bgExtras: () => "", - renderCard: null, - cardAccent: null - }, - // 05 — Schematic (Blueprint — grid bg, monospace, colored top-bars) - schematic: { - bgColor: "#0d1117", - cardBg: "rgba(13,17,23,0.92)", - cardBorder: "#30363d", - cardRadius: 4, - cardShadow: null, - lineColor: "#30363d", - lineWidth: 1.5, - nameColor: "#c9d1d9", - roleColor: "#8b949e", - font: "'JetBrains Mono', 'SF Mono', monospace", - watermarkColor: "rgba(139,148,158,0.3)", - defs: (w5, h5) => ` - - - `, - bgExtras: (w5, h5) => ``, - renderCard: (ln, theme) => { - const { tag: tag3, accentColor, emojiSvg } = getRoleInfo(ln.node); - const cx = ln.x + ln.width / 2; - const schemaRoles = { - ceo: "chief_executive", - cto: "chief_technology", - cmo: "chief_marketing", - cfo: "chief_financial", - coo: "chief_operating", - engineer: "engineer", - quality: "quality_assurance", - design: "designer", - finance: "finance", - operations: "operations", - default: "agent" - }; - const roleText = schemaRoles[tag3] || schemaRoles.default; - const avatarCY = ln.y + 27; - const nameY = ln.y + 66; - const roleY = ln.y + 82; - return ` - - - ${renderEmojiAvatar(cx, avatarCY, 17, "rgba(48,54,61,0.3)", emojiSvg, theme.cardBorder)} - ${escapeXml(ln.node.name)} - ${escapeXml(roleText)} - `; - }, - cardAccent: null - } -}; -var CARD_H = 96; -var CARD_MIN_W = 150; -var CARD_PAD_X = 22; -var AVATAR_SIZE = 34; -var GAP_X = 24; -var GAP_Y = 56; -var MINI_AVATAR_SIZE = 14; -var MINI_AVATAR_GAP = 6; -var MINI_AVATAR_PADDING = 10; -var MINI_AVATAR_MAX_COLS = 8; -var PADDING = 48; -var LOGO_PADDING = 16; -function measureText(text3, fontSize) { - return text3.length * fontSize * 0.58; -} -function avatarGridRows(count2) { - return Math.ceil(count2 / MINI_AVATAR_MAX_COLS); -} -function avatarGridWidth(count2) { - const cols = Math.min(count2, MINI_AVATAR_MAX_COLS); - return cols * (MINI_AVATAR_SIZE + MINI_AVATAR_GAP) - MINI_AVATAR_GAP + MINI_AVATAR_PADDING * 2; -} -function avatarGridHeight(count2) { - if (count2 === 0) return 0; - const rows = avatarGridRows(count2); - return rows * (MINI_AVATAR_SIZE + MINI_AVATAR_GAP) - MINI_AVATAR_GAP + MINI_AVATAR_PADDING * 2; -} -function cardWidth(node) { - const { roleLabel: defaultRoleLabel } = getRoleInfo(node); - const roleLabel = node.role.startsWith("\xD7") ? node.role : defaultRoleLabel; - const nameW = measureText(node.name, 14) + CARD_PAD_X * 2; - const roleW = measureText(roleLabel, 11) + CARD_PAD_X * 2; - let w5 = Math.max(CARD_MIN_W, Math.max(nameW, roleW)); - if (node.collapsedReports && node.collapsedReports.length > 0) { - w5 = Math.max(w5, avatarGridWidth(node.collapsedReports.length)); - } - return w5; -} -function cardHeight(node) { - if (node.collapsedReports && node.collapsedReports.length > 0) { - return CARD_H + avatarGridHeight(node.collapsedReports.length); - } - return CARD_H; -} -function subtreeWidth(node) { - const cw = cardWidth(node); - if (!node.reports || node.reports.length === 0) return cw; - const childrenW = node.reports.reduce( - (sum, child, i5) => sum + subtreeWidth(child) + (i5 > 0 ? GAP_X : 0), - 0 - ); - return Math.max(cw, childrenW); -} -function layoutTree(node, x5, y2) { - const w5 = cardWidth(node); - const sw = subtreeWidth(node); - const cardX = x5 + (sw - w5) / 2; - const h5 = cardHeight(node); - const layoutNode = { - node, - x: cardX, - y: y2, - width: w5, - height: h5, - children: [] - }; - if (node.reports && node.reports.length > 0) { - let childX = x5; - const childY = y2 + h5 + GAP_Y; - for (let i5 = 0; i5 < node.reports.length; i5++) { - const child = node.reports[i5]; - const childSW = subtreeWidth(child); - layoutNode.children.push(layoutTree(child, childX, childY)); - childX += childSW + GAP_X; - } - } - return layoutNode; -} -function escapeXml(s5) { - return s5.replace(/&/g, "&").replace(//g, ">").replace(/"/g, """); -} -function renderEmojiAvatar(cx, cy, radius, bgFill, emojiSvg, bgStroke) { - const emojiSize = radius * 1.3; - const emojiX = cx - emojiSize / 2; - const emojiY = cy - emojiSize / 2; - const stroke = bgStroke ? `stroke="${bgStroke}" stroke-width="1"` : ""; - return ` - ${emojiSvg}`; -} -function defaultRenderCard(ln, theme) { - if (ln.node.role === "overflow") { - const cx2 = ln.x + ln.width / 2; - const cy = ln.y + ln.height / 2; - return ` - - ${escapeXml(ln.node.name)} - `; - } - const { roleLabel: defaultRoleLabel, bg, emojiSvg } = getRoleInfo(ln.node); - const roleLabel = ln.node.role.startsWith("\xD7") ? ln.node.role : defaultRoleLabel; - const cx = ln.x + ln.width / 2; - const avatarCY = ln.y + 27; - const nameY = ln.y + 66; - const roleY = ln.y + 82; - const filterId = `shadow-${ln.node.id}`; - const shadowFilter = theme.cardShadow ? `filter="url(#${filterId})"` : ""; - const shadowDef = theme.cardShadow ? ` - - - ` : ""; - const isLight = theme.bgColor === "#fafaf9" || theme.bgColor === "#ffffff"; - const avatarBg = isLight ? bg : "rgba(255,255,255,0.06)"; - const avatarStroke = isLight ? void 0 : "rgba(255,255,255,0.08)"; - let avatarGridSvg = ""; - const collapsed = ln.node.collapsedReports; - if (collapsed && collapsed.length > 0) { - const gridTop = ln.y + CARD_H + MINI_AVATAR_PADDING; - const cols = Math.min(collapsed.length, MINI_AVATAR_MAX_COLS); - const gridTotalW = cols * (MINI_AVATAR_SIZE + MINI_AVATAR_GAP) - MINI_AVATAR_GAP; - const gridStartX = ln.x + (ln.width - gridTotalW) / 2; - for (let i5 = 0; i5 < collapsed.length; i5++) { - const col = i5 % MINI_AVATAR_MAX_COLS; - const row = Math.floor(i5 / MINI_AVATAR_MAX_COLS); - const dotCx = gridStartX + col * (MINI_AVATAR_SIZE + MINI_AVATAR_GAP) + MINI_AVATAR_SIZE / 2; - const dotCy = gridTop + row * (MINI_AVATAR_SIZE + MINI_AVATAR_GAP) + MINI_AVATAR_SIZE / 2; - const { bg: dotBg } = getRoleInfo(collapsed[i5]); - const dotFill = isLight ? dotBg : "rgba(255,255,255,0.1)"; - avatarGridSvg += ``; - } - } - return ` - ${shadowDef} - - ${renderEmojiAvatar(cx, avatarCY, AVATAR_SIZE / 2, avatarBg, emojiSvg, avatarStroke)} - ${escapeXml(ln.node.name)} - ${escapeXml(roleLabel)} - ${avatarGridSvg} - `; -} -function renderConnectors(ln, theme) { - if (ln.children.length === 0) return ""; - const parentCx = ln.x + ln.width / 2; - const parentBottom = ln.y + ln.height; - const midY = parentBottom + GAP_Y / 2; - const lc = theme.lineColor; - const lw = theme.lineWidth; - let svg2 = ""; - svg2 += ``; - if (ln.children.length === 1) { - const childCx = ln.children[0].x + ln.children[0].width / 2; - svg2 += ``; - } else { - const leftCx = ln.children[0].x + ln.children[0].width / 2; - const rightCx = ln.children[ln.children.length - 1].x + ln.children[ln.children.length - 1].width / 2; - svg2 += ``; - for (const child of ln.children) { - const childCx = child.x + child.width / 2; - svg2 += ``; - } - } - for (const child of ln.children) { - svg2 += renderConnectors(child, theme); - } - return svg2; -} -function renderCards(ln, theme) { - const render = theme.renderCard || defaultRenderCard; - let svg2 = render(ln, theme); - for (const child of ln.children) { - svg2 += renderCards(child, theme); - } - return svg2; -} -function treeBounds(ln) { - let minX = ln.x; - let minY = ln.y; - let maxX = ln.x + ln.width; - let maxY = ln.y + ln.height; - for (const child of ln.children) { - const cb = treeBounds(child); - minX = Math.min(minX, cb.minX); - minY = Math.min(minY, cb.minY); - maxX = Math.max(maxX, cb.maxX); - maxY = Math.max(maxY, cb.maxY); - } - return { minX, minY, maxX, maxY }; -} -var TASKCORE_LOGO_SVG = ` - - - - Taskcore -`; -var TARGET_W = 1280; -var TARGET_H = 640; -function countNodes(nodes) { - let count2 = 0; - for (const n5 of nodes) { - count2 += 1 + countNodes(n5.reports ?? []); - } - return count2; -} -var COLLAPSE_THRESHOLD = 20; -var MAX_LEVEL_WIDTH = 8; -var MAX_CHILDREN_SHOWN = 6; -function flattenDescendants(nodes) { - const result = []; - for (const n5 of nodes) { - result.push(n5); - result.push(...flattenDescendants(n5.reports ?? [])); - } - return result; -} -function nodesAtDepth(nodes, depth) { - if (depth === 0) return nodes; - const result = []; - for (const n5 of nodes) { - result.push(...nodesAtDepth(n5.reports ?? [], depth - 1)); - } - return result; -} -function estimateNextLevelWidth(parentNodes) { - let total = 0; - for (const p5 of parentNodes) { - const childCount = (p5.reports ?? []).length; - if (childCount === 0) continue; - total += Math.min(childCount, MAX_CHILDREN_SHOWN + 1); - } - return total; -} -function collapseToAvatars(node) { - const childCount = countNodes(node.reports ?? []); - if (childCount === 0) return node; - return { - ...node, - role: `\xD7${childCount} reports`, - collapsedReports: flattenDescendants(node.reports ?? []), - reports: [] - }; -} -function truncateChildren(node) { - const children = node.reports ?? []; - if (children.length <= MAX_CHILDREN_SHOWN) return node; - const kept = children.slice(0, MAX_CHILDREN_SHOWN); - const hiddenCount = children.length - MAX_CHILDREN_SHOWN; - const placeholder = { - id: `${node.id}-more`, - name: `+${hiddenCount} more`, - role: "overflow", - status: "active", - reports: [] - }; - return { ...node, reports: [...kept, placeholder] }; -} -function smartCollapseTree(roots) { - const clone3 = (nodes) => nodes.map((n5) => ({ ...n5, reports: clone3(n5.reports ?? []) })); - const tree = clone3(roots); - for (let depth = 0; depth < 10; depth++) { - const parents = nodesAtDepth(tree, depth); - const parentsWithChildren = parents.filter((p5) => (p5.reports ?? []).length > 0); - if (parentsWithChildren.length === 0) break; - const nextWidth = estimateNextLevelWidth(parentsWithChildren); - if (nextWidth <= MAX_LEVEL_WIDTH) { - for (const p5 of parentsWithChildren) { - if ((p5.reports ?? []).length > MAX_CHILDREN_SHOWN) { - const truncated = truncateChildren(p5); - p5.reports = truncated.reports; - } - } - continue; - } - for (const p5 of parentsWithChildren) { - const collapsed = collapseToAvatars(p5); - p5.role = collapsed.role; - p5.collapsedReports = collapsed.collapsedReports; - p5.reports = []; - } - break; - } - return tree; -} -function renderOrgChartSvg(orgTree, style = "warmth", overlay) { - const theme = THEMES[style] || THEMES.warmth; - const totalNodes = countNodes(orgTree); - const effectiveTree = totalNodes > COLLAPSE_THRESHOLD ? smartCollapseTree(orgTree) : orgTree; - let root; - if (effectiveTree.length === 1) { - root = effectiveTree[0]; - } else { - root = { - id: "virtual-root", - name: "Organization", - role: "Root", - status: "active", - reports: effectiveTree - }; - } - const layout = layoutTree(root, PADDING, PADDING + 24); - const bounds = treeBounds(layout); - const contentW = bounds.maxX + PADDING; - const contentH = bounds.maxY + PADDING; - const scale = Math.min(TARGET_W / contentW, TARGET_H / contentH, 1); - const scaledW = contentW * scale; - const scaledH = contentH * scale; - const offsetX = (TARGET_W - scaledW) / 2; - const offsetY = (TARGET_H - scaledH) / 2; - const logoX = TARGET_W - 110 - LOGO_PADDING; - const logoY = LOGO_PADDING; - const overlayNameSvg = overlay?.companyName ? `${svgEscape(overlay.companyName)}` : ""; - const overlayStatsSvg = overlay?.stats ? `${svgEscape(overlay.stats)}` : ""; - return ` - ${theme.defs(TARGET_W, TARGET_H)} - - ${theme.bgExtras(TARGET_W, TARGET_H)} - - ${TASKCORE_LOGO_SVG} - - ${overlayNameSvg} - ${overlayStatsSvg} - - ${renderConnectors(layout, theme)} - ${renderCards(layout, theme)} - -`; -} -function svgEscape(s5) { - return s5.replace(/&/g, "&").replace(//g, ">").replace(/"/g, """); -} -async function renderOrgChartPng(orgTree, style = "warmth", overlay) { - const svg2 = renderOrgChartSvg(orgTree, style, overlay); - const sharpModule = await import("sharp"); - const sharp = sharpModule.default; - return sharp(Buffer.from(svg2), { density: 144 }).resize(TARGET_W, TARGET_H).png().toBuffer(); -} - -// server/src/services/company-portability.ts -function buildOrgTreeFromManifest(agents2) { - const ROLE_LABELS2 = { - ceo: "Chief Executive", - cto: "Technology", - cmo: "Marketing", - cfo: "Finance", - coo: "Operations", - vp: "VP", - manager: "Manager", - engineer: "Engineer", - agent: "Agent" - }; - const bySlug = new Map(agents2.map((a5) => [a5.slug, a5])); - const childrenOf = /* @__PURE__ */ new Map(); - for (const a5 of agents2) { - const parent = a5.reportsToSlug ?? null; - const list2 = childrenOf.get(parent) ?? []; - list2.push(a5); - childrenOf.set(parent, list2); - } - const build = (parentSlug) => { - const members = childrenOf.get(parentSlug) ?? []; - return members.map((m5) => ({ - id: m5.slug, - name: m5.name, - role: ROLE_LABELS2[m5.role] ?? m5.role, - status: "active", - reports: build(m5.slug) - })); - }; - const roots = agents2.filter((a5) => !a5.reportsToSlug || !bySlug.has(a5.reportsToSlug)); - const rootSlugs = new Set(roots.map((r5) => r5.slug)); - const tree = build(null); - for (const root of roots) { - if (root.reportsToSlug && !bySlug.has(root.reportsToSlug)) { - tree.push({ - id: root.slug, - name: root.name, - role: ROLE_LABELS2[root.role] ?? root.role, - status: "active", - reports: build(root.slug) - }); - } - } - return tree; -} -var DEFAULT_INCLUDE = { - company: true, - agents: true, - projects: false, - issues: false, - skills: false -}; -var DEFAULT_COLLISION_STRATEGY = "rename"; -var execFileAsync5 = promisify6(execFile6); -var bundledSkillsCommitPromise = null; -function resolveImportMode(options) { - return options?.mode ?? "board_full"; -} -function resolveSkillConflictStrategy(mode, collisionStrategy) { - if (mode === "board_full") return "replace"; - return collisionStrategy === "skip" ? "skip" : "rename"; -} -function classifyPortableFileKind(pathValue) { - const normalized = normalizePortablePath2(pathValue); - if (normalized === "COMPANY.md") return "company"; - if (normalized === ".taskcore.yaml" || normalized === ".taskcore.yml") return "extension"; - if (normalized === "README.md") return "readme"; - if (normalized.startsWith("agents/")) return "agent"; - if (normalized.startsWith("skills/")) return "skill"; - if (normalized.startsWith("projects/")) return "project"; - if (normalized.startsWith("tasks/")) return "issue"; - return "other"; -} -function normalizeSkillSlug3(value) { - return value ? normalizeAgentUrlKey(value) ?? null : null; -} -function normalizeSkillKey2(value) { - if (!value) return null; - const segments = value.split("/").map((segment) => normalizeSkillSlug3(segment)).filter((segment) => Boolean(segment)); - return segments.length > 0 ? segments.join("/") : null; -} -function readSkillKey(frontmatter) { - const metadata = isPlainRecord5(frontmatter.metadata) ? frontmatter.metadata : null; - const taskcore = isPlainRecord5(metadata?.taskcore) ? metadata?.taskcore : null; - return normalizeSkillKey2( - asString14(frontmatter.key) ?? asString14(frontmatter.skillKey) ?? asString14(metadata?.skillKey) ?? asString14(metadata?.canonicalKey) ?? asString14(metadata?.taskcoreSkillKey) ?? asString14(taskcore?.skillKey) ?? asString14(taskcore?.key) - ); -} -function deriveManifestSkillKey(frontmatter, fallbackSlug, metadata, sourceType, sourceLocator) { - const explicit = readSkillKey(frontmatter); - if (explicit) return explicit; - const slug = normalizeSkillSlug3(asString14(frontmatter.slug) ?? fallbackSlug) ?? "skill"; - const sourceKind = asString14(metadata?.sourceKind); - const owner = normalizeSkillSlug3(asString14(metadata?.owner)); - const repo = normalizeSkillSlug3(asString14(metadata?.repo)); - if ((sourceType === "github" || sourceType === "skills_sh" || sourceKind === "github" || sourceKind === "skills_sh") && owner && repo) { - return `${owner}/${repo}/${slug}`; - } - if (sourceKind === "taskcore_bundled") { - return `taskcore/taskcore/${slug}`; - } - if (sourceType === "url" || sourceKind === "url") { - try { - const host = normalizeSkillSlug3(sourceLocator ? new URL(sourceLocator).host : null) ?? "url"; - return `url/${host}/${slug}`; - } catch { - return `url/unknown/${slug}`; - } - } - return slug; -} -function hashSkillValue2(value) { - return createHash14("sha256").update(value).digest("hex").slice(0, 8); -} -function normalizeExportPathSegment(value, preserveCase = false) { - if (!value) return null; - const trimmed = value.trim(); - if (!trimmed) return null; - const normalized = trimmed.replace(/[^A-Za-z0-9._-]+/g, "-").replace(/-+/g, "-").replace(/^-+|-+$/g, ""); - if (!normalized) return null; - return preserveCase ? normalized : normalized.toLowerCase(); -} -function readSkillSourceKind(skill) { - const metadata = isPlainRecord5(skill.metadata) ? skill.metadata : null; - return asString14(metadata?.sourceKind); -} -function deriveLocalExportNamespace(skill, slug) { - const metadata = isPlainRecord5(skill.metadata) ? skill.metadata : null; - const candidates = [ - asString14(metadata?.projectName), - asString14(metadata?.workspaceName) - ]; - if (skill.sourceLocator) { - const basename3 = path40.basename(skill.sourceLocator); - candidates.push(basename3.toLowerCase() === "skill.md" ? path40.basename(path40.dirname(skill.sourceLocator)) : basename3); - } - for (const value of candidates) { - const normalized = normalizeSkillSlug3(value); - if (normalized && normalized !== slug) return normalized; - } - return null; -} -function derivePrimarySkillExportDir(skill, slug, companyIssuePrefix) { - const normalizedKey = normalizeSkillKey2(skill.key); - const keySegments = normalizedKey?.split("/") ?? []; - const primaryNamespace = keySegments[0] ?? null; - if (primaryNamespace === "company") { - const companySegment = normalizeExportPathSegment(companyIssuePrefix, true) ?? normalizeExportPathSegment(keySegments[1], true) ?? "company"; - return `skills/company/${companySegment}/${slug}`; - } - if (primaryNamespace === "local") { - const localNamespace = deriveLocalExportNamespace(skill, slug); - return localNamespace ? `skills/local/${localNamespace}/${slug}` : `skills/local/${slug}`; - } - if (primaryNamespace === "url") { - let derivedHost = keySegments[1] ?? null; - if (!derivedHost) { - try { - derivedHost = normalizeSkillSlug3(skill.sourceLocator ? new URL(skill.sourceLocator).host : null); - } catch { - derivedHost = null; - } - } - const host = derivedHost ?? "url"; - return `skills/url/${host}/${slug}`; - } - if (keySegments.length > 1) { - return `skills/${keySegments.join("/")}`; - } - return `skills/${slug}`; -} -function appendSkillExportDirSuffix(packageDir, suffix) { - const lastSeparator = packageDir.lastIndexOf("/"); - if (lastSeparator < 0) return `${packageDir}--${suffix}`; - return `${packageDir.slice(0, lastSeparator + 1)}${packageDir.slice(lastSeparator + 1)}--${suffix}`; -} -function deriveSkillExportDirCandidates(skill, slug, companyIssuePrefix) { - const primaryDir = derivePrimarySkillExportDir(skill, slug, companyIssuePrefix); - const metadata = isPlainRecord5(skill.metadata) ? skill.metadata : null; - const sourceKind = readSkillSourceKind(skill); - const suffixes = /* @__PURE__ */ new Set(); - const pushSuffix = (value, preserveCase = false) => { - const normalized = normalizeExportPathSegment(value, preserveCase); - if (normalized && normalized !== slug) { - suffixes.add(normalized); - } - }; - if (sourceKind === "taskcore_bundled") { - pushSuffix("taskcore"); - } - if (skill.sourceType === "github" || skill.sourceType === "skills_sh") { - pushSuffix(asString14(metadata?.repo)); - pushSuffix(asString14(metadata?.owner)); - pushSuffix(skill.sourceType === "skills_sh" ? "skills_sh" : "github"); - } else if (skill.sourceType === "url") { - try { - pushSuffix(skill.sourceLocator ? new URL(skill.sourceLocator).host : null); - } catch { - } - pushSuffix("url"); - } else if (skill.sourceType === "local_path") { - pushSuffix(asString14(metadata?.projectName)); - pushSuffix(asString14(metadata?.workspaceName)); - pushSuffix(deriveLocalExportNamespace(skill, slug)); - if (sourceKind === "managed_local") pushSuffix("company"); - if (sourceKind === "project_scan") pushSuffix("project"); - pushSuffix("local"); - } else { - pushSuffix(sourceKind); - pushSuffix("skill"); - } - return [primaryDir, ...Array.from(suffixes, (suffix) => appendSkillExportDirSuffix(primaryDir, suffix))]; -} -function buildSkillExportDirMap(skills, companyIssuePrefix) { - const usedDirs = /* @__PURE__ */ new Set(); - const keyToDir = /* @__PURE__ */ new Map(); - const orderedSkills = [...skills].sort((left, right) => left.key.localeCompare(right.key)); - for (const skill of orderedSkills) { - const slug = normalizeSkillSlug3(skill.slug) ?? "skill"; - const candidates = deriveSkillExportDirCandidates(skill, slug, companyIssuePrefix); - let packageDir = candidates.find((candidate) => !usedDirs.has(candidate)) ?? null; - if (!packageDir) { - packageDir = appendSkillExportDirSuffix(candidates[0] ?? `skills/${slug}`, hashSkillValue2(skill.key)); - while (usedDirs.has(packageDir)) { - packageDir = appendSkillExportDirSuffix( - candidates[0] ?? `skills/${slug}`, - hashSkillValue2(`${skill.key}:${packageDir}`) - ); - } - } - usedDirs.add(packageDir); - keyToDir.set(skill.key, packageDir); - } - return keyToDir; -} -function isSensitiveEnvKey2(key) { - const normalized = key.trim().toLowerCase(); - return normalized === "token" || normalized.endsWith("_token") || normalized.endsWith("-token") || normalized.includes("apikey") || normalized.includes("api_key") || normalized.includes("api-key") || normalized.includes("access_token") || normalized.includes("access-token") || normalized.includes("auth") || normalized.includes("auth_token") || normalized.includes("auth-token") || normalized.includes("authorization") || normalized.includes("bearer") || normalized.includes("secret") || normalized.includes("passwd") || normalized.includes("password") || normalized.includes("credential") || normalized.includes("jwt") || normalized.includes("privatekey") || normalized.includes("private_key") || normalized.includes("private-key") || normalized.includes("cookie") || normalized.includes("connectionstring"); -} -function normalizePortableProjectEnv(value) { - const parsed = envConfigSchema.safeParse(value); - return parsed.success ? parsed.data : null; -} -function extractPortableScopedEnvInputs(scope, envValue, warnings) { - if (!isPlainRecord5(envValue)) return []; - const env2 = envValue; - const inputs = []; - for (const [key, binding] of Object.entries(env2)) { - if (key.toUpperCase() === "PATH") { - warnings.push(`${scope.warningPrefix} PATH override was omitted from export because it is system-dependent.`); - continue; - } - if (isPlainRecord5(binding) && binding.type === "secret_ref") { - inputs.push({ - key, - description: `Provide ${key} for ${scope.label}`, - agentSlug: scope.agentSlug, - projectSlug: scope.projectSlug, - kind: "secret", - requirement: "optional", - defaultValue: "", - portability: "portable" - }); - continue; - } - if (isPlainRecord5(binding) && binding.type === "plain") { - const defaultValue = asString14(binding.value); - const isSensitive = isSensitiveEnvKey2(key); - const portability = defaultValue && isAbsoluteCommand(defaultValue) ? "system_dependent" : "portable"; - if (portability === "system_dependent") { - warnings.push(`${scope.warningPrefix} env ${key} default was exported as system-dependent.`); - } - inputs.push({ - key, - description: `Optional default for ${key} on ${scope.label}`, - agentSlug: scope.agentSlug, - projectSlug: scope.projectSlug, - kind: isSensitive ? "secret" : "plain", - requirement: "optional", - defaultValue: isSensitive ? "" : defaultValue ?? "", - portability - }); - continue; - } - if (typeof binding === "string") { - const portability = isAbsoluteCommand(binding) ? "system_dependent" : "portable"; - if (portability === "system_dependent") { - warnings.push(`${scope.warningPrefix} env ${key} default was exported as system-dependent.`); - } - inputs.push({ - key, - description: `Optional default for ${key} on ${scope.label}`, - agentSlug: scope.agentSlug, - projectSlug: scope.projectSlug, - kind: isSensitiveEnvKey2(key) ? "secret" : "plain", - requirement: "optional", - defaultValue: isSensitiveEnvKey2(key) ? "" : binding, - portability - }); - } - } - return inputs; -} -var COMPANY_LOGO_CONTENT_TYPE_EXTENSIONS = { - "image/gif": ".gif", - "image/jpeg": ".jpg", - "image/png": ".png", - "image/svg+xml": ".svg", - "image/webp": ".webp" -}; -var COMPANY_LOGO_FILE_NAME = "company-logo"; -var RUNTIME_DEFAULT_RULES = [ - { path: ["heartbeat", "cooldownSec"], value: 10 }, - { path: ["heartbeat", "intervalSec"], value: 3600 }, - { path: ["heartbeat", "wakeOnOnDemand"], value: true }, - { path: ["heartbeat", "wakeOnAssignment"], value: true }, - { path: ["heartbeat", "wakeOnAutomation"], value: true }, - { path: ["heartbeat", "wakeOnDemand"], value: true }, - { path: ["heartbeat", "maxConcurrentRuns"], value: 3 } -]; -var ADAPTER_DEFAULT_RULES_BY_TYPE = { - codex_local: [ - { path: ["timeoutSec"], value: 0 }, - { path: ["graceSec"], value: 15 } - ], - gemini_local: [ - { path: ["timeoutSec"], value: 0 }, - { path: ["graceSec"], value: 15 } - ], - opencode_local: [ - { path: ["timeoutSec"], value: 0 }, - { path: ["graceSec"], value: 15 } - ], - cursor: [ - { path: ["timeoutSec"], value: 0 }, - { path: ["graceSec"], value: 15 } - ], - claude_local: [ - { path: ["timeoutSec"], value: 0 }, - { path: ["graceSec"], value: 15 }, - { path: ["maxTurnsPerRun"], value: 1e3 } - ], - openclaw_gateway: [ - { path: ["timeoutSec"], value: 120 }, - { path: ["waitTimeoutMs"], value: 12e4 }, - { path: ["sessionKeyStrategy"], value: "fixed" }, - { path: ["sessionKey"], value: "taskcore" }, - { path: ["role"], value: "operator" }, - { path: ["scopes"], value: ["operator.admin"] } - ] -}; -function isPlainRecord5(value) { - return typeof value === "object" && value !== null && !Array.isArray(value); -} -function asString14(value) { - if (typeof value !== "string") return null; - const trimmed = value.trim(); - return trimmed.length > 0 ? trimmed : null; -} -function asBoolean5(value) { - return typeof value === "boolean" ? value : null; -} -function asInteger(value) { - return typeof value === "number" && Number.isInteger(value) ? value : null; -} -function normalizeRoutineTriggerExtension(value) { - if (!isPlainRecord5(value)) return null; - const kind = asString14(value.kind); - if (!kind) return null; - return { - kind, - label: asString14(value.label), - enabled: asBoolean5(value.enabled) ?? true, - cronExpression: asString14(value.cronExpression), - timezone: asString14(value.timezone), - signingMode: asString14(value.signingMode), - replayWindowSec: asInteger(value.replayWindowSec) - }; -} -function normalizeRoutineVariableExtension(value) { - if (!isPlainRecord5(value)) return null; - const name = asString14(value.name); - if (!name) return null; - const type = asString14(value.type) ?? "text"; - if (!["text", "textarea", "number", "boolean", "select"].includes(type)) return null; - const options = Array.isArray(value.options) ? value.options.map((entry) => asString14(entry)).filter((entry) => Boolean(entry)) : []; - const defaultValue = typeof value.defaultValue === "string" || typeof value.defaultValue === "number" || typeof value.defaultValue === "boolean" ? value.defaultValue : null; - return { - name, - label: asString14(value.label), - type, - defaultValue, - required: asBoolean5(value.required) ?? true, - options - }; -} -function normalizeRoutineExtension(value) { - if (!isPlainRecord5(value)) return null; - const triggers = Array.isArray(value.triggers) ? value.triggers.map((entry) => normalizeRoutineTriggerExtension(entry)).filter((entry) => entry !== null) : []; - const variables = Array.isArray(value.variables) ? value.variables.map((entry) => normalizeRoutineVariableExtension(entry)).filter((entry) => entry !== null) : null; - const routine = { - concurrencyPolicy: asString14(value.concurrencyPolicy), - catchUpPolicy: asString14(value.catchUpPolicy), - variables, - triggers - }; - return stripEmptyValues(routine) ? routine : null; -} -function containsAbsolutePathFragment(value) { - return /(^|\s)(\/[^/\s]|[A-Za-z]:[\\/])/.test(value); -} -function containsSystemDependentPathValue(value) { - if (typeof value === "string") { - return path40.isAbsolute(value) || /^[A-Za-z]:[\\/]/.test(value) || containsAbsolutePathFragment(value); - } - if (Array.isArray(value)) { - return value.some((entry) => containsSystemDependentPathValue(entry)); - } - if (isPlainRecord5(value)) { - return Object.values(value).some((entry) => containsSystemDependentPathValue(entry)); - } - return false; -} -function clonePortableRecord(value) { - if (!isPlainRecord5(value)) return null; - return structuredClone(value); -} -function disableImportedTimerHeartbeat(runtimeConfig) { - const next = clonePortableRecord(runtimeConfig) ?? {}; - const heartbeat = isPlainRecord5(next.heartbeat) ? { ...next.heartbeat } : {}; - heartbeat.enabled = false; - next.heartbeat = heartbeat; - return next; -} -function normalizePortableProjectWorkspaceExtension(workspaceKey, value) { - if (!isPlainRecord5(value)) return null; - const normalizedKey = normalizeAgentUrlKey(workspaceKey) ?? workspaceKey.trim(); - if (!normalizedKey) return null; - return { - key: normalizedKey, - name: asString14(value.name) ?? normalizedKey, - sourceType: asString14(value.sourceType), - repoUrl: asString14(value.repoUrl), - repoRef: asString14(value.repoRef), - defaultRef: asString14(value.defaultRef), - visibility: asString14(value.visibility), - setupCommand: asString14(value.setupCommand), - cleanupCommand: asString14(value.cleanupCommand), - metadata: isPlainRecord5(value.metadata) ? value.metadata : null, - isPrimary: asBoolean5(value.isPrimary) ?? false - }; -} -function derivePortableProjectWorkspaceKey(workspace, usedKeys) { - const baseKey = normalizeAgentUrlKey(workspace.name) ?? normalizeAgentUrlKey(asString14(workspace.repoUrl)?.split("/").pop()?.replace(/\.git$/i, "") ?? "") ?? "workspace"; - return uniqueSlug(baseKey, usedKeys); -} -function exportPortableProjectExecutionWorkspacePolicy(projectSlug, policy, workspaceKeyById, warnings) { - const next = clonePortableRecord(policy); - if (!next) return null; - const defaultWorkspaceId = asString14(next.defaultProjectWorkspaceId); - if (defaultWorkspaceId) { - const defaultWorkspaceKey = workspaceKeyById.get(defaultWorkspaceId); - if (defaultWorkspaceKey) { - next.defaultProjectWorkspaceKey = defaultWorkspaceKey; - } else { - warnings.push(`Project ${projectSlug} default workspace ${defaultWorkspaceId} was omitted from export because that workspace is not portable.`); - } - delete next.defaultProjectWorkspaceId; - } - const cleaned = stripEmptyValues(next); - return isPlainRecord5(cleaned) ? cleaned : null; -} -function importPortableProjectExecutionWorkspacePolicy(projectSlug, policy, workspaceIdByKey, warnings) { - const next = clonePortableRecord(policy); - if (!next) return null; - const defaultWorkspaceKey = asString14(next.defaultProjectWorkspaceKey); - if (defaultWorkspaceKey) { - const defaultWorkspaceId = workspaceIdByKey.get(defaultWorkspaceKey); - if (defaultWorkspaceId) { - next.defaultProjectWorkspaceId = defaultWorkspaceId; - } else { - warnings.push(`Project ${projectSlug} references missing workspace key ${defaultWorkspaceKey}; imported execution workspace policy without a default workspace.`); - } - } - delete next.defaultProjectWorkspaceKey; - const cleaned = stripEmptyValues(next); - return isPlainRecord5(cleaned) ? cleaned : null; -} -function stripPortableProjectExecutionWorkspaceRefs(policy) { - const next = clonePortableRecord(policy); - if (!next) return null; - delete next.defaultProjectWorkspaceId; - delete next.defaultProjectWorkspaceKey; - const cleaned = stripEmptyValues(next); - return isPlainRecord5(cleaned) ? cleaned : null; -} -async function readGitOutput(cwd, args) { - const { stdout } = await execFileAsync5("git", ["-C", cwd, ...args], { cwd }); - const trimmed = stdout.trim(); - return trimmed.length > 0 ? trimmed : null; -} -async function inferPortableWorkspaceGitMetadata(workspace) { - const cwd = asString14(workspace.cwd); - if (!cwd) { - return { - repoUrl: null, - repoRef: null, - defaultRef: null - }; - } - let repoUrl = null; - try { - repoUrl = await readGitOutput(cwd, ["remote", "get-url", "origin"]); - } catch { - try { - const firstRemote = await readGitOutput(cwd, ["remote"]); - const remoteName = firstRemote?.split("\n").map((entry) => entry.trim()).find(Boolean) ?? null; - if (remoteName) { - repoUrl = await readGitOutput(cwd, ["remote", "get-url", remoteName]); - } - } catch { - repoUrl = null; - } - } - let repoRef = null; - try { - repoRef = await readGitOutput(cwd, ["branch", "--show-current"]); - } catch { - repoRef = null; - } - let defaultRef = null; - try { - const remoteHead = await readGitOutput(cwd, ["symbolic-ref", "--quiet", "--short", "refs/remotes/origin/HEAD"]); - defaultRef = remoteHead?.startsWith("origin/") ? remoteHead.slice("origin/".length) : remoteHead; - } catch { - defaultRef = null; - } - return { - repoUrl, - repoRef, - defaultRef - }; -} -async function buildPortableProjectWorkspaces(projectSlug, workspaces, warnings) { - const exportedWorkspaces = {}; - const manifestWorkspaces = []; - const workspaceKeyById = /* @__PURE__ */ new Map(); - const workspaceKeyBySignature = /* @__PURE__ */ new Map(); - const manifestWorkspaceByKey = /* @__PURE__ */ new Map(); - const usedKeys = /* @__PURE__ */ new Set(); - for (const workspace of workspaces ?? []) { - const inferredGitMetadata = !asString14(workspace.repoUrl) || !asString14(workspace.repoRef) || !asString14(workspace.defaultRef) ? await inferPortableWorkspaceGitMetadata(workspace) : { repoUrl: null, repoRef: null, defaultRef: null }; - const repoUrl = asString14(workspace.repoUrl) ?? inferredGitMetadata.repoUrl; - if (!repoUrl) { - warnings.push(`Project ${projectSlug} workspace ${workspace.name} was omitted from export because it does not have a portable repoUrl.`); - continue; - } - const repoRef = asString14(workspace.repoRef) ?? inferredGitMetadata.repoRef; - const defaultRef = asString14(workspace.defaultRef) ?? inferredGitMetadata.defaultRef ?? repoRef; - const workspaceSignature = JSON.stringify({ - name: workspace.name, - repoUrl, - repoRef, - defaultRef - }); - const existingWorkspaceKey = workspaceKeyBySignature.get(workspaceSignature); - if (existingWorkspaceKey) { - workspaceKeyById.set(workspace.id, existingWorkspaceKey); - const existingManifestWorkspace = manifestWorkspaceByKey.get(existingWorkspaceKey); - if (existingManifestWorkspace && workspace.isPrimary) { - existingManifestWorkspace.isPrimary = true; - const existingExtensionWorkspace = exportedWorkspaces[existingWorkspaceKey]; - if (isPlainRecord5(existingExtensionWorkspace)) existingExtensionWorkspace.isPrimary = true; - } - continue; - } - const workspaceKey = derivePortableProjectWorkspaceKey(workspace, usedKeys); - workspaceKeyById.set(workspace.id, workspaceKey); - workspaceKeyBySignature.set(workspaceSignature, workspaceKey); - let setupCommand = asString14(workspace.setupCommand); - if (setupCommand && containsAbsolutePathFragment(setupCommand)) { - warnings.push(`Project ${projectSlug} workspace ${workspaceKey} setupCommand was omitted from export because it is system-dependent.`); - setupCommand = null; - } - let cleanupCommand = asString14(workspace.cleanupCommand); - if (cleanupCommand && containsAbsolutePathFragment(cleanupCommand)) { - warnings.push(`Project ${projectSlug} workspace ${workspaceKey} cleanupCommand was omitted from export because it is system-dependent.`); - cleanupCommand = null; - } - const metadata = isPlainRecord5(workspace.metadata) && !containsSystemDependentPathValue(workspace.metadata) ? workspace.metadata : null; - if (isPlainRecord5(workspace.metadata) && metadata == null) { - warnings.push(`Project ${projectSlug} workspace ${workspaceKey} metadata was omitted from export because it contains system-dependent paths.`); - } - const portableWorkspace = stripEmptyValues({ - name: workspace.name, - sourceType: workspace.sourceType, - repoUrl, - repoRef, - defaultRef, - visibility: asString14(workspace.visibility), - setupCommand, - cleanupCommand, - metadata, - isPrimary: workspace.isPrimary ? true : void 0 - }); - if (!isPlainRecord5(portableWorkspace)) continue; - exportedWorkspaces[workspaceKey] = portableWorkspace; - const manifestWorkspace = { - key: workspaceKey, - name: workspace.name, - sourceType: asString14(workspace.sourceType), - repoUrl, - repoRef, - defaultRef, - visibility: asString14(workspace.visibility), - setupCommand, - cleanupCommand, - metadata, - isPrimary: workspace.isPrimary - }; - manifestWorkspaces.push(manifestWorkspace); - manifestWorkspaceByKey.set(workspaceKey, manifestWorkspace); - } - return { - extension: Object.keys(exportedWorkspaces).length > 0 ? exportedWorkspaces : void 0, - manifest: manifestWorkspaces, - workspaceKeyById - }; -} -var WEEKDAY_TO_CRON = { - sunday: "0", - monday: "1", - tuesday: "2", - wednesday: "3", - thursday: "4", - friday: "5", - saturday: "6" -}; -function readZonedDateParts(startsAt, timeZone) { - try { - const date7 = new Date(startsAt); - if (Number.isNaN(date7.getTime())) return null; - const formatter = new Intl.DateTimeFormat("en-US", { - timeZone, - hour12: false, - weekday: "long", - month: "numeric", - day: "numeric", - hour: "numeric", - minute: "numeric" - }); - const parts = Object.fromEntries( - formatter.formatToParts(date7).filter((entry) => entry.type !== "literal").map((entry) => [entry.type, entry.value]) - ); - const weekday = WEEKDAY_TO_CRON[parts.weekday?.toLowerCase() ?? ""]; - const month = Number(parts.month); - const day2 = Number(parts.day); - const hour2 = Number(parts.hour); - const minute2 = Number(parts.minute); - if (!weekday || !Number.isFinite(month) || !Number.isFinite(day2) || !Number.isFinite(hour2) || !Number.isFinite(minute2)) { - return null; - } - return { weekday, month, day: day2, hour: hour2, minute: minute2 }; - } catch { - return null; - } -} -function normalizeCronList(values2) { - return Array.from(new Set(values2)).sort((left, right) => Number(left) - Number(right)).join(","); -} -function buildLegacyRoutineTriggerFromRecurrence(issue2, scheduleValue) { - const warnings = []; - const errors = []; - if (!issue2.legacyRecurrence || !isPlainRecord5(issue2.legacyRecurrence)) { - return { trigger: null, warnings, errors }; - } - const schedule = isPlainRecord5(scheduleValue) ? scheduleValue : null; - const frequency = asString14(issue2.legacyRecurrence.frequency); - const interval2 = asInteger(issue2.legacyRecurrence.interval) ?? 1; - if (!frequency) { - errors.push(`Recurring task ${issue2.slug} uses legacy recurrence without frequency; add .taskcore.yaml routines.${issue2.slug}.triggers.`); - return { trigger: null, warnings, errors }; - } - if (interval2 < 1) { - errors.push(`Recurring task ${issue2.slug} uses legacy recurrence with an invalid interval; add .taskcore.yaml routines.${issue2.slug}.triggers.`); - return { trigger: null, warnings, errors }; - } - const timezone = asString14(schedule?.timezone) ?? "UTC"; - const startsAt = asString14(schedule?.startsAt); - const zonedStartsAt = startsAt ? readZonedDateParts(startsAt, timezone) : null; - if (startsAt && !zonedStartsAt) { - errors.push(`Recurring task ${issue2.slug} has an invalid legacy startsAt/timezone combination; add .taskcore.yaml routines.${issue2.slug}.triggers.`); - return { trigger: null, warnings, errors }; - } - const time5 = isPlainRecord5(issue2.legacyRecurrence.time) ? issue2.legacyRecurrence.time : null; - const hour2 = asInteger(time5?.hour) ?? zonedStartsAt?.hour ?? 0; - const minute2 = asInteger(time5?.minute) ?? zonedStartsAt?.minute ?? 0; - if (hour2 < 0 || hour2 > 23 || minute2 < 0 || minute2 > 59) { - errors.push(`Recurring task ${issue2.slug} uses legacy recurrence with an invalid time; add .taskcore.yaml routines.${issue2.slug}.triggers.`); - return { trigger: null, warnings, errors }; - } - if (issue2.legacyRecurrence.until != null || issue2.legacyRecurrence.count != null) { - warnings.push(`Recurring task ${issue2.slug} uses legacy recurrence end bounds; Taskcore will import the routine trigger without those limits.`); - } - let cronExpression = null; - if (frequency === "hourly") { - const hourField = interval2 === 1 ? "*" : zonedStartsAt ? `${zonedStartsAt.hour}-23/${interval2}` : `*/${interval2}`; - cronExpression = `${minute2} ${hourField} * * *`; - } else if (frequency === "daily") { - if (Array.isArray(issue2.legacyRecurrence.weekdays) || Array.isArray(issue2.legacyRecurrence.monthDays) || Array.isArray(issue2.legacyRecurrence.months)) { - errors.push(`Recurring task ${issue2.slug} uses unsupported legacy daily recurrence constraints; add .taskcore.yaml routines.${issue2.slug}.triggers.`); - return { trigger: null, warnings, errors }; - } - const dayField = interval2 === 1 ? "*" : `*/${interval2}`; - cronExpression = `${minute2} ${hour2} ${dayField} * *`; - } else if (frequency === "weekly") { - if (interval2 !== 1) { - errors.push(`Recurring task ${issue2.slug} uses legacy weekly recurrence with interval > 1; add .taskcore.yaml routines.${issue2.slug}.triggers.`); - return { trigger: null, warnings, errors }; - } - const weekdays = Array.isArray(issue2.legacyRecurrence.weekdays) ? issue2.legacyRecurrence.weekdays.map((entry) => asString14(entry)).filter((entry) => Boolean(entry)) : []; - const cronWeekdays = weekdays.map((entry) => WEEKDAY_TO_CRON[entry.toLowerCase()]).filter((entry) => Boolean(entry)); - if (cronWeekdays.length === 0 && zonedStartsAt?.weekday) { - cronWeekdays.push(zonedStartsAt.weekday); - } - if (cronWeekdays.length === 0) { - errors.push(`Recurring task ${issue2.slug} uses legacy weekly recurrence without weekdays; add .taskcore.yaml routines.${issue2.slug}.triggers.`); - return { trigger: null, warnings, errors }; - } - cronExpression = `${minute2} ${hour2} * * ${normalizeCronList(cronWeekdays)}`; - } else if (frequency === "monthly") { - if (interval2 !== 1) { - errors.push(`Recurring task ${issue2.slug} uses legacy monthly recurrence with interval > 1; add .taskcore.yaml routines.${issue2.slug}.triggers.`); - return { trigger: null, warnings, errors }; - } - if (Array.isArray(issue2.legacyRecurrence.ordinalWeekdays) && issue2.legacyRecurrence.ordinalWeekdays.length > 0) { - errors.push(`Recurring task ${issue2.slug} uses legacy ordinal monthly recurrence; add .taskcore.yaml routines.${issue2.slug}.triggers.`); - return { trigger: null, warnings, errors }; - } - const monthDays = Array.isArray(issue2.legacyRecurrence.monthDays) ? issue2.legacyRecurrence.monthDays.map((entry) => asInteger(entry)).filter((entry) => entry != null && entry >= 1 && entry <= 31) : []; - if (monthDays.length === 0 && zonedStartsAt?.day) { - monthDays.push(zonedStartsAt.day); - } - if (monthDays.length === 0) { - errors.push(`Recurring task ${issue2.slug} uses legacy monthly recurrence without monthDays; add .taskcore.yaml routines.${issue2.slug}.triggers.`); - return { trigger: null, warnings, errors }; - } - const months2 = Array.isArray(issue2.legacyRecurrence.months) ? issue2.legacyRecurrence.months.map((entry) => asInteger(entry)).filter((entry) => entry != null && entry >= 1 && entry <= 12) : []; - const monthField = months2.length > 0 ? normalizeCronList(months2.map(String)) : "*"; - cronExpression = `${minute2} ${hour2} ${normalizeCronList(monthDays.map(String))} ${monthField} *`; - } else if (frequency === "yearly") { - if (interval2 !== 1) { - errors.push(`Recurring task ${issue2.slug} uses legacy yearly recurrence with interval > 1; add .taskcore.yaml routines.${issue2.slug}.triggers.`); - return { trigger: null, warnings, errors }; - } - const months2 = Array.isArray(issue2.legacyRecurrence.months) ? issue2.legacyRecurrence.months.map((entry) => asInteger(entry)).filter((entry) => entry != null && entry >= 1 && entry <= 12) : []; - if (months2.length === 0 && zonedStartsAt?.month) { - months2.push(zonedStartsAt.month); - } - const monthDays = Array.isArray(issue2.legacyRecurrence.monthDays) ? issue2.legacyRecurrence.monthDays.map((entry) => asInteger(entry)).filter((entry) => entry != null && entry >= 1 && entry <= 31) : []; - if (monthDays.length === 0 && zonedStartsAt?.day) { - monthDays.push(zonedStartsAt.day); - } - if (months2.length === 0 || monthDays.length === 0) { - errors.push(`Recurring task ${issue2.slug} uses legacy yearly recurrence without month/monthDay anchors; add .taskcore.yaml routines.${issue2.slug}.triggers.`); - return { trigger: null, warnings, errors }; - } - cronExpression = `${minute2} ${hour2} ${normalizeCronList(monthDays.map(String))} ${normalizeCronList(months2.map(String))} *`; - } else { - errors.push(`Recurring task ${issue2.slug} uses unsupported legacy recurrence frequency "${frequency}"; add .taskcore.yaml routines.${issue2.slug}.triggers.`); - return { trigger: null, warnings, errors }; - } - return { - trigger: { - kind: "schedule", - label: "Migrated legacy recurrence", - enabled: true, - cronExpression, - timezone, - signingMode: null, - replayWindowSec: null - }, - warnings, - errors - }; -} -function resolvePortableRoutineDefinition(issue2, scheduleValue) { - const warnings = []; - const errors = []; - if (!issue2.recurring) { - return { routine: null, warnings, errors }; - } - const routine = issue2.routine ? { - concurrencyPolicy: issue2.routine.concurrencyPolicy, - catchUpPolicy: issue2.routine.catchUpPolicy, - variables: issue2.routine.variables ?? null, - triggers: [...issue2.routine.triggers] - } : { - concurrencyPolicy: null, - catchUpPolicy: null, - variables: null, - triggers: [] - }; - if (routine.concurrencyPolicy && !ROUTINE_CONCURRENCY_POLICIES.includes(routine.concurrencyPolicy)) { - errors.push(`Recurring task ${issue2.slug} uses unsupported routine concurrencyPolicy "${routine.concurrencyPolicy}".`); - } - if (routine.catchUpPolicy && !ROUTINE_CATCH_UP_POLICIES.includes(routine.catchUpPolicy)) { - errors.push(`Recurring task ${issue2.slug} uses unsupported routine catchUpPolicy "${routine.catchUpPolicy}".`); - } - for (const trigger of routine.triggers) { - if (!ROUTINE_TRIGGER_KINDS.includes(trigger.kind)) { - errors.push(`Recurring task ${issue2.slug} uses unsupported trigger kind "${trigger.kind}".`); - continue; - } - if (trigger.kind === "schedule") { - if (!trigger.cronExpression || !trigger.timezone) { - errors.push(`Recurring task ${issue2.slug} has a schedule trigger missing cronExpression/timezone.`); - continue; - } - const cronError = validateCron(trigger.cronExpression); - if (cronError) { - errors.push(`Recurring task ${issue2.slug} has an invalid schedule trigger: ${cronError}`); - } - continue; - } - if (trigger.kind === "webhook" && trigger.signingMode && !ROUTINE_TRIGGER_SIGNING_MODES.includes(trigger.signingMode)) { - errors.push(`Recurring task ${issue2.slug} uses unsupported webhook signingMode "${trigger.signingMode}".`); - } - } - if (routine.triggers.length === 0 && issue2.legacyRecurrence) { - const migrated = buildLegacyRoutineTriggerFromRecurrence(issue2, scheduleValue); - warnings.push(...migrated.warnings); - errors.push(...migrated.errors); - if (migrated.trigger) { - routine.triggers.push(migrated.trigger); - } - } - return { routine, warnings, errors }; -} -function toSafeSlug(input, fallback) { - return normalizeAgentUrlKey(input) ?? fallback; -} -function uniqueSlug(base, used) { - if (!used.has(base)) { - used.add(base); - return base; - } - let idx = 2; - while (true) { - const candidate = `${base}-${idx}`; - if (!used.has(candidate)) { - used.add(candidate); - return candidate; - } - idx += 1; - } -} -function uniqueNameBySlug(baseName, existingSlugs) { - const baseSlug = normalizeAgentUrlKey(baseName) ?? "agent"; - if (!existingSlugs.has(baseSlug)) return baseName; - let idx = 2; - while (true) { - const candidateName = `${baseName} ${idx}`; - const candidateSlug = normalizeAgentUrlKey(candidateName) ?? `agent-${idx}`; - if (!existingSlugs.has(candidateSlug)) return candidateName; - idx += 1; - } -} -function uniqueProjectName(baseName, existingProjectSlugs) { - const baseSlug = deriveProjectUrlKey(baseName, baseName); - if (!existingProjectSlugs.has(baseSlug)) return baseName; - let idx = 2; - while (true) { - const candidateName = `${baseName} ${idx}`; - const candidateSlug = deriveProjectUrlKey(candidateName, candidateName); - if (!existingProjectSlugs.has(candidateSlug)) return candidateName; - idx += 1; - } -} -function normalizeInclude(input) { - return { - company: input?.company ?? DEFAULT_INCLUDE.company, - agents: input?.agents ?? DEFAULT_INCLUDE.agents, - projects: input?.projects ?? DEFAULT_INCLUDE.projects, - issues: input?.issues ?? DEFAULT_INCLUDE.issues, - skills: input?.skills ?? DEFAULT_INCLUDE.skills - }; -} -function normalizePortablePath2(input) { - const normalized = input.replace(/\\/g, "/").replace(/^\.\/+/, ""); - const parts = []; - for (const segment of normalized.split("/")) { - if (!segment || segment === ".") continue; - if (segment === "..") { - if (parts.length > 0) parts.pop(); - continue; - } - parts.push(segment); - } - return parts.join("/"); -} -function resolvePortablePath(fromPath, targetPath) { - const baseDir = path40.posix.dirname(fromPath.replace(/\\/g, "/")); - return normalizePortablePath2(path40.posix.join(baseDir, targetPath.replace(/\\/g, "/"))); -} -function isPortableBinaryFile(value) { - return typeof value === "object" && value !== null && value.encoding === "base64" && typeof value.data === "string"; -} -function readPortableTextFile(files, filePath) { - const value = files[filePath]; - return typeof value === "string" ? value : null; -} -function inferContentTypeFromPath(filePath) { - const extension2 = path40.posix.extname(filePath).toLowerCase(); - switch (extension2) { - case ".gif": - return "image/gif"; - case ".jpeg": - case ".jpg": - return "image/jpeg"; - case ".png": - return "image/png"; - case ".svg": - return "image/svg+xml"; - case ".webp": - return "image/webp"; - default: - return null; - } -} -function resolveCompanyLogoExtension(contentType, originalFilename) { - const fromContentType = contentType ? COMPANY_LOGO_CONTENT_TYPE_EXTENSIONS[contentType.toLowerCase()] : null; - if (fromContentType) return fromContentType; - const extension2 = originalFilename ? path40.extname(originalFilename).toLowerCase() : ""; - return extension2 || ".png"; -} -function portableBinaryFileToBuffer(entry) { - return Buffer.from(entry.data, "base64"); -} -function portableFileToBuffer(entry, filePath) { - if (typeof entry === "string") { - return Buffer.from(entry, "utf8"); - } - if (isPortableBinaryFile(entry)) { - return portableBinaryFileToBuffer(entry); - } - throw unprocessable(`Unsupported file entry encoding for ${filePath}`); -} -function bufferToPortableBinaryFile(buffer2, contentType) { - return { - encoding: "base64", - data: buffer2.toString("base64"), - contentType - }; -} -async function streamToBuffer(stream) { - const chunks = []; - for await (const chunk of stream) { - chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)); - } - return Buffer.concat(chunks); -} -function normalizeFileMap(files, rootPath) { - const normalizedRoot = rootPath ? normalizePortablePath2(rootPath) : null; - const out = {}; - for (const [rawPath, content] of Object.entries(files)) { - let nextPath = normalizePortablePath2(rawPath); - if (normalizedRoot && nextPath === normalizedRoot) { - continue; - } - if (normalizedRoot && nextPath.startsWith(`${normalizedRoot}/`)) { - nextPath = nextPath.slice(normalizedRoot.length + 1); - } - if (!nextPath) continue; - out[nextPath] = content; - } - return out; -} -function pickTextFiles(files) { - const out = {}; - for (const [filePath, content] of Object.entries(files)) { - if (typeof content === "string") { - out[filePath] = content; - } - } - return out; -} -function collectSelectedExportSlugs(selectedFiles) { - const agents2 = /* @__PURE__ */ new Set(); - const projects2 = /* @__PURE__ */ new Set(); - const tasks = /* @__PURE__ */ new Set(); - for (const filePath of selectedFiles) { - const agentMatch = filePath.match(/^agents\/([^/]+)\//); - if (agentMatch) agents2.add(agentMatch[1]); - const projectMatch = filePath.match(/^projects\/([^/]+)\//); - if (projectMatch) projects2.add(projectMatch[1]); - const taskMatch = filePath.match(/^tasks\/([^/]+)\//); - if (taskMatch) tasks.add(taskMatch[1]); - } - return { agents: agents2, projects: projects2, tasks, routines: new Set(tasks) }; -} -function normalizePortableSlugList(value) { - if (!Array.isArray(value)) return []; - const seen = /* @__PURE__ */ new Set(); - const normalized = []; - for (const entry of value) { - if (typeof entry !== "string") continue; - const trimmed = entry.trim(); - if (!trimmed || seen.has(trimmed)) continue; - seen.add(trimmed); - normalized.push(trimmed); - } - return normalized; -} -function normalizePortableSidebarOrder(value) { - if (!isPlainRecord5(value)) return null; - const sidebar = { - agents: normalizePortableSlugList(value.agents), - projects: normalizePortableSlugList(value.projects) - }; - return sidebar.agents.length > 0 || sidebar.projects.length > 0 ? sidebar : null; -} -function sortAgentsBySidebarOrder(agents2) { - if (agents2.length === 0) return []; - const byId = new Map(agents2.map((agent) => [agent.id, agent])); - const childrenOf = /* @__PURE__ */ new Map(); - for (const agent of agents2) { - const parentId = agent.reportsTo && byId.has(agent.reportsTo) ? agent.reportsTo : null; - const siblings = childrenOf.get(parentId) ?? []; - siblings.push(agent); - childrenOf.set(parentId, siblings); - } - for (const siblings of childrenOf.values()) { - siblings.sort((left, right) => left.name.localeCompare(right.name)); - } - const sorted = []; - const queue = [...childrenOf.get(null) ?? []]; - while (queue.length > 0) { - const agent = queue.shift(); - if (!agent) continue; - sorted.push(agent); - const children = childrenOf.get(agent.id); - if (children) queue.push(...children); - } - return sorted; -} -function filterPortableExtensionYaml(yaml, selectedFiles) { - const selected = collectSelectedExportSlugs(selectedFiles); - const parsed = parseYamlFile(yaml); - for (const section of ["agents", "projects", "tasks", "routines"]) { - const sectionValue = parsed[section]; - if (!isPlainRecord5(sectionValue)) continue; - const sectionSlugs = selected[section]; - const filteredEntries = Object.fromEntries( - Object.entries(sectionValue).filter(([slug]) => sectionSlugs.has(slug)) - ); - if (Object.keys(filteredEntries).length > 0) { - parsed[section] = filteredEntries; - } else { - delete parsed[section]; - } - } - const companySection = parsed.company; - if (isPlainRecord5(companySection)) { - const logoPath = asString14(companySection.logoPath) ?? asString14(companySection.logo); - if (logoPath && !selectedFiles.has(logoPath)) { - delete companySection.logoPath; - delete companySection.logo; - } - } - const sidebarOrder = normalizePortableSidebarOrder(parsed.sidebar); - if (sidebarOrder) { - const filteredSidebar = stripEmptyValues({ - agents: sidebarOrder.agents.filter((slug) => selected.agents.has(slug)), - projects: sidebarOrder.projects.filter((slug) => selected.projects.has(slug)) - }); - if (isPlainRecord5(filteredSidebar)) { - parsed.sidebar = filteredSidebar; - } else { - delete parsed.sidebar; - } - } else { - delete parsed.sidebar; - } - return buildYamlFile(parsed, { preserveEmptyStrings: true }); -} -function filterExportFiles(files, selectedFilesInput, taskcoreExtensionPath) { - if (!selectedFilesInput || selectedFilesInput.length === 0) { - return files; - } - const selectedFiles = new Set( - selectedFilesInput.map((entry) => normalizePortablePath2(entry)).filter((entry) => entry.length > 0) - ); - const filtered = {}; - for (const [filePath, content] of Object.entries(files)) { - if (!selectedFiles.has(filePath)) continue; - filtered[filePath] = content; - } - const extensionEntry = filtered[taskcoreExtensionPath]; - if (selectedFiles.has(taskcoreExtensionPath) && typeof extensionEntry === "string") { - filtered[taskcoreExtensionPath] = filterPortableExtensionYaml(extensionEntry, selectedFiles); - } - return filtered; -} -function findTaskcoreExtensionPath(files) { - if (typeof files[".taskcore.yaml"] === "string") return ".taskcore.yaml"; - if (typeof files[".taskcore.yml"] === "string") return ".taskcore.yml"; - return Object.keys(files).find((entry) => entry.endsWith("/.taskcore.yaml") || entry.endsWith("/.taskcore.yml")) ?? null; -} -function ensureMarkdownPath(pathValue) { - const normalized = pathValue.replace(/\\/g, "/"); - if (!normalized.endsWith(".md")) { - throw unprocessable(`Manifest file path must end in .md: ${pathValue}`); - } - return normalized; -} -function normalizePortableConfig(value) { - if (typeof value !== "object" || value === null || Array.isArray(value)) return {}; - const input = value; - const next = {}; - for (const [key, entry] of Object.entries(input)) { - if (key === "cwd" || key === "instructionsFilePath" || key === "instructionsBundleMode" || key === "instructionsRootPath" || key === "instructionsEntryFile" || key === "promptTemplate" || key === "bootstrapPromptTemplate" || // deprecated — kept for backward compat - key === "taskcoreSkillSync") continue; - if (key === "env") continue; - next[key] = entry; - } - return next; -} -function isAbsoluteCommand(value) { - return path40.isAbsolute(value) || /^[A-Za-z]:[\\/]/.test(value); -} -function extractPortableEnvInputs(agentSlug, envValue, warnings) { - return extractPortableScopedEnvInputs( - { - label: `agent ${agentSlug}`, - warningPrefix: `Agent ${agentSlug}`, - agentSlug, - projectSlug: null - }, - envValue, - warnings - ); -} -function extractPortableProjectEnvInputs(projectSlug, envValue, warnings) { - return extractPortableScopedEnvInputs( - { - label: `project ${projectSlug}`, - warningPrefix: `Project ${projectSlug}`, - agentSlug: null, - projectSlug - }, - envValue, - warnings - ); -} -function jsonEqual2(left, right) { - return JSON.stringify(left) === JSON.stringify(right); -} -function isPathDefault(pathSegments, value, rules) { - return rules.some((rule) => jsonEqual2(rule.path, pathSegments) && jsonEqual2(rule.value, value)); -} -function pruneDefaultLikeValue(value, opts) { - const pathSegments = opts.path ?? []; - if (opts.defaultRules && isPathDefault(pathSegments, value, opts.defaultRules)) { - return void 0; - } - if (Array.isArray(value)) { - return value.map((entry) => pruneDefaultLikeValue(entry, { ...opts, path: pathSegments })); - } - if (isPlainRecord5(value)) { - const out = {}; - for (const [key, entry] of Object.entries(value)) { - const next = pruneDefaultLikeValue(entry, { - ...opts, - path: [...pathSegments, key] - }); - if (next === void 0) continue; - out[key] = next; - } - return out; - } - if (value === void 0) return void 0; - if (opts.dropFalseBooleans && value === false) return void 0; - return value; -} -function renderYamlScalar(value) { - if (value === null) return "null"; - if (typeof value === "boolean" || typeof value === "number") return String(value); - if (typeof value === "string") return JSON.stringify(value); - return JSON.stringify(value); -} -function isEmptyObject(value) { - return isPlainRecord5(value) && Object.keys(value).length === 0; -} -function isEmptyArray(value) { - return Array.isArray(value) && value.length === 0; -} -function stripEmptyValues(value, opts) { - if (Array.isArray(value)) { - const next = value.map((entry) => stripEmptyValues(entry, opts)).filter((entry) => entry !== void 0); - return next.length > 0 ? next : void 0; - } - if (isPlainRecord5(value)) { - const next = {}; - for (const [key, entry] of Object.entries(value)) { - const cleaned = stripEmptyValues(entry, opts); - if (cleaned === void 0) continue; - next[key] = cleaned; - } - return Object.keys(next).length > 0 ? next : void 0; - } - if (value === void 0 || value === null || !opts?.preserveEmptyStrings && value === "" || isEmptyArray(value) || isEmptyObject(value)) { - return void 0; - } - return value; -} -var YAML_KEY_PRIORITY = [ - "name", - "description", - "title", - "schema", - "kind", - "slug", - "reportsTo", - "skills", - "owner", - "assignee", - "project", - "schedule", - "version", - "license", - "authors", - "homepage", - "tags", - "includes", - "requirements", - "role", - "icon", - "capabilities", - "brandColor", - "logoPath", - "adapter", - "runtime", - "permissions", - "budgetMonthlyCents", - "metadata" -]; -var YAML_KEY_PRIORITY_INDEX = new Map( - YAML_KEY_PRIORITY.map((key, index2) => [key, index2]) -); -function compareYamlKeys(left, right) { - const leftPriority = YAML_KEY_PRIORITY_INDEX.get(left); - const rightPriority = YAML_KEY_PRIORITY_INDEX.get(right); - if (leftPriority !== void 0 || rightPriority !== void 0) { - if (leftPriority === void 0) return 1; - if (rightPriority === void 0) return -1; - if (leftPriority !== rightPriority) return leftPriority - rightPriority; - } - return left.localeCompare(right); -} -function orderedYamlEntries(value) { - return Object.entries(value).sort(([leftKey], [rightKey]) => compareYamlKeys(leftKey, rightKey)); -} -function renderYamlBlock(value, indentLevel) { - const indent = " ".repeat(indentLevel); - if (Array.isArray(value)) { - if (value.length === 0) return [`${indent}[]`]; - const lines = []; - for (const entry of value) { - const scalar = entry === null || typeof entry === "string" || typeof entry === "boolean" || typeof entry === "number" || Array.isArray(entry) && entry.length === 0 || isEmptyObject(entry); - if (scalar) { - lines.push(`${indent}- ${renderYamlScalar(entry)}`); - continue; - } - lines.push(`${indent}-`); - lines.push(...renderYamlBlock(entry, indentLevel + 1)); - } - return lines; - } - if (isPlainRecord5(value)) { - const entries2 = orderedYamlEntries(value); - if (entries2.length === 0) return [`${indent}{}`]; - const lines = []; - for (const [key, entry] of entries2) { - const scalar = entry === null || typeof entry === "string" || typeof entry === "boolean" || typeof entry === "number" || Array.isArray(entry) && entry.length === 0 || isEmptyObject(entry); - if (scalar) { - lines.push(`${indent}${key}: ${renderYamlScalar(entry)}`); - continue; - } - lines.push(`${indent}${key}:`); - lines.push(...renderYamlBlock(entry, indentLevel + 1)); - } - return lines; - } - return [`${indent}${renderYamlScalar(value)}`]; -} -function renderFrontmatter(frontmatter) { - const lines = ["---"]; - for (const [key, value] of orderedYamlEntries(frontmatter)) { - if (value === null || value === void 0) continue; - const scalar = typeof value === "string" || typeof value === "boolean" || typeof value === "number" || Array.isArray(value) && value.length === 0 || isEmptyObject(value); - if (scalar) { - lines.push(`${key}: ${renderYamlScalar(value)}`); - continue; - } - lines.push(`${key}:`); - lines.push(...renderYamlBlock(value, 1)); - } - lines.push("---"); - return `${lines.join("\n")} -`; -} -function buildMarkdown(frontmatter, body) { - const cleanBody = body.replace(/\r\n/g, "\n").trim(); - if (!cleanBody) { - return `${renderFrontmatter(frontmatter)} -`; - } - return `${renderFrontmatter(frontmatter)} -${cleanBody} -`; -} -function normalizeSelectedFiles(selectedFiles) { - if (!selectedFiles) return null; - return new Set( - selectedFiles.map((entry) => normalizePortablePath2(entry)).filter((entry) => entry.length > 0) - ); -} -function filterCompanyMarkdownIncludes(companyPath, markdown, selectedFiles) { - const parsed = parseFrontmatterMarkdown2(markdown); - const includeEntries = readIncludeEntries(parsed.frontmatter); - const filteredIncludes = includeEntries.filter( - (entry) => selectedFiles.has(resolvePortablePath(companyPath, entry.path)) - ); - const nextFrontmatter = { ...parsed.frontmatter }; - if (filteredIncludes.length > 0) { - nextFrontmatter.includes = filteredIncludes.map((entry) => entry.path); - } else { - delete nextFrontmatter.includes; - } - return buildMarkdown(nextFrontmatter, parsed.body); -} -function applySelectedFilesToSource(source, selectedFiles) { - const normalizedSelection = normalizeSelectedFiles(selectedFiles); - if (!normalizedSelection) return source; - const companyPath = source.manifest.company ? ensureMarkdownPath(source.manifest.company.path) : Object.keys(source.files).find((entry) => entry.endsWith("/COMPANY.md") || entry === "COMPANY.md") ?? null; - if (!companyPath) { - throw unprocessable("Company package is missing COMPANY.md"); - } - const companyMarkdown = source.files[companyPath]; - if (typeof companyMarkdown !== "string") { - throw unprocessable("Company package is missing COMPANY.md"); - } - const effectiveFiles = {}; - for (const [filePath, content] of Object.entries(source.files)) { - const normalizedPath = normalizePortablePath2(filePath); - if (!normalizedSelection.has(normalizedPath)) continue; - effectiveFiles[normalizedPath] = content; - } - effectiveFiles[companyPath] = filterCompanyMarkdownIncludes( - companyPath, - companyMarkdown, - normalizedSelection - ); - const filtered = buildManifestFromPackageFiles(effectiveFiles, { - sourceLabel: source.manifest.source - }); - if (!normalizedSelection.has(companyPath)) { - filtered.manifest.company = null; - } - filtered.manifest.includes = { - company: filtered.manifest.company !== null, - agents: filtered.manifest.agents.length > 0, - projects: filtered.manifest.projects.length > 0, - issues: filtered.manifest.issues.length > 0, - skills: filtered.manifest.skills.length > 0 - }; - return filtered; -} -async function resolveBundledSkillsCommit() { - if (!bundledSkillsCommitPromise) { - bundledSkillsCommitPromise = execFileAsync5("git", ["rev-parse", "HEAD"], { - cwd: process.cwd(), - encoding: "utf8" - }).then(({ stdout }) => stdout.trim() || null).catch(() => null); - } - return bundledSkillsCommitPromise; -} -async function buildSkillSourceEntry(skill) { - const metadata = isPlainRecord5(skill.metadata) ? skill.metadata : null; - if (asString14(metadata?.sourceKind) === "taskcore_bundled") { - const commit = await resolveBundledSkillsCommit(); - return { - kind: "github-dir", - repo: "khulnasoft/taskcore", - path: `skills/${skill.slug}`, - commit, - trackingRef: "master", - url: `https://github.com/khulnasoft/taskcore/tree/master/skills/${skill.slug}` - }; - } - if (skill.sourceType === "github" || skill.sourceType === "skills_sh") { - const owner = asString14(metadata?.owner); - const repo = asString14(metadata?.repo); - const repoSkillDir = asString14(metadata?.repoSkillDir); - if (!owner || !repo || !repoSkillDir) return null; - return { - kind: "github-dir", - repo: `${owner}/${repo}`, - path: repoSkillDir, - commit: skill.sourceRef ?? null, - trackingRef: asString14(metadata?.trackingRef), - url: skill.sourceLocator - }; - } - if (skill.sourceType === "url" && skill.sourceLocator) { - return { - kind: "url", - url: skill.sourceLocator - }; - } - return null; -} -function shouldReferenceSkillOnExport(skill, expandReferencedSkills) { - if (expandReferencedSkills) return false; - const metadata = isPlainRecord5(skill.metadata) ? skill.metadata : null; - if (asString14(metadata?.sourceKind) === "taskcore_bundled") return true; - return skill.sourceType === "github" || skill.sourceType === "skills_sh" || skill.sourceType === "url"; -} -async function buildReferencedSkillMarkdown(skill) { - const sourceEntry = await buildSkillSourceEntry(skill); - const frontmatter = { - key: skill.key, - slug: skill.slug, - name: skill.name, - description: skill.description ?? null - }; - if (sourceEntry) { - frontmatter.metadata = { - sources: [sourceEntry] - }; - } - return buildMarkdown(frontmatter, ""); -} -async function withSkillSourceMetadata(skill, markdown) { - const sourceEntry = await buildSkillSourceEntry(skill); - const parsed = parseFrontmatterMarkdown2(markdown); - const metadata = isPlainRecord5(parsed.frontmatter.metadata) ? { ...parsed.frontmatter.metadata } : {}; - const existingSources = Array.isArray(metadata.sources) ? metadata.sources.filter((entry) => isPlainRecord5(entry)) : []; - if (sourceEntry) { - metadata.sources = [...existingSources, sourceEntry]; - } - metadata.skillKey = skill.key; - metadata.taskcoreSkillKey = skill.key; - metadata.taskcore = { - ...isPlainRecord5(metadata.taskcore) ? metadata.taskcore : {}, - skillKey: skill.key, - slug: skill.slug - }; - const frontmatter = { - ...parsed.frontmatter, - key: skill.key, - slug: skill.slug, - metadata - }; - return buildMarkdown(frontmatter, parsed.body); -} -function parseYamlScalar2(rawValue) { - const trimmed = rawValue.trim(); - if (trimmed === "") return ""; - if (trimmed === "null" || trimmed === "~") return null; - if (trimmed === "true") return true; - if (trimmed === "false") return false; - if (trimmed === "[]") return []; - if (trimmed === "{}") return {}; - if (/^-?\d+(\.\d+)?$/.test(trimmed)) return Number(trimmed); - if (trimmed.startsWith('"') || trimmed.startsWith("[") || trimmed.startsWith("{")) { - try { - return JSON.parse(trimmed); - } catch { - return trimmed; - } - } - return trimmed; -} -function prepareYamlLines2(raw) { - return raw.split("\n").map((line3) => ({ - indent: line3.match(/^ */)?.[0].length ?? 0, - content: line3.trim() - })).filter((line3) => line3.content.length > 0 && !line3.content.startsWith("#")); -} -function parseYamlBlock2(lines, startIndex, indentLevel) { - let index2 = startIndex; - while (index2 < lines.length && lines[index2].content.length === 0) { - index2 += 1; - } - if (index2 >= lines.length || lines[index2].indent < indentLevel) { - return { value: {}, nextIndex: index2 }; - } - const isArray = lines[index2].indent === indentLevel && lines[index2].content.startsWith("-"); - if (isArray) { - const values2 = []; - while (index2 < lines.length) { - const line3 = lines[index2]; - if (line3.indent < indentLevel) break; - if (line3.indent !== indentLevel || !line3.content.startsWith("-")) break; - const remainder = line3.content.slice(1).trim(); - index2 += 1; - if (!remainder) { - const nested = parseYamlBlock2(lines, index2, indentLevel + 2); - values2.push(nested.value); - index2 = nested.nextIndex; - continue; - } - const inlineObjectSeparator = remainder.indexOf(":"); - if (inlineObjectSeparator > 0 && !remainder.startsWith('"') && !remainder.startsWith("{") && !remainder.startsWith("[")) { - const key = remainder.slice(0, inlineObjectSeparator).trim(); - const rawValue = remainder.slice(inlineObjectSeparator + 1).trim(); - const nextObject = { - [key]: parseYamlScalar2(rawValue) - }; - if (index2 < lines.length && lines[index2].indent > indentLevel) { - const nested = parseYamlBlock2(lines, index2, indentLevel + 2); - if (isPlainRecord5(nested.value)) { - Object.assign(nextObject, nested.value); - } - index2 = nested.nextIndex; - } - values2.push(nextObject); - continue; - } - values2.push(parseYamlScalar2(remainder)); - } - return { value: values2, nextIndex: index2 }; - } - const record2 = {}; - while (index2 < lines.length) { - const line3 = lines[index2]; - if (line3.indent < indentLevel) break; - if (line3.indent !== indentLevel) { - index2 += 1; - continue; - } - const separatorIndex = line3.content.indexOf(":"); - if (separatorIndex <= 0) { - index2 += 1; - continue; - } - const key = line3.content.slice(0, separatorIndex).trim(); - const remainder = line3.content.slice(separatorIndex + 1).trim(); - index2 += 1; - if (!remainder) { - const nested = parseYamlBlock2(lines, index2, indentLevel + 2); - record2[key] = nested.value; - index2 = nested.nextIndex; - continue; - } - record2[key] = parseYamlScalar2(remainder); - } - return { value: record2, nextIndex: index2 }; -} -function parseYamlFrontmatter2(raw) { - const prepared = prepareYamlLines2(raw); - if (prepared.length === 0) return {}; - const parsed = parseYamlBlock2(prepared, 0, prepared[0].indent); - return isPlainRecord5(parsed.value) ? parsed.value : {}; -} -function parseYamlFile(raw) { - return parseYamlFrontmatter2(raw); -} -function buildYamlFile(value, opts) { - const cleaned = stripEmptyValues(value, opts); - if (!isPlainRecord5(cleaned)) return "{}\n"; - return renderYamlBlock(cleaned, 0).join("\n") + "\n"; -} -function parseFrontmatterMarkdown2(raw) { - const normalized = raw.replace(/\r\n/g, "\n"); - if (!normalized.startsWith("---\n")) { - return { frontmatter: {}, body: normalized.trim() }; - } - const closing = normalized.indexOf("\n---\n", 4); - if (closing < 0) { - return { frontmatter: {}, body: normalized.trim() }; - } - const frontmatterRaw = normalized.slice(4, closing).trim(); - const body = normalized.slice(closing + 5).trim(); - return { - frontmatter: parseYamlFrontmatter2(frontmatterRaw), - body - }; -} -async function fetchText2(url2) { - const response = await ghFetch(url2); - if (!response.ok) { - throw unprocessable(`Failed to fetch ${url2}: ${response.status}`); - } - return response.text(); -} -async function fetchOptionalText(url2) { - const response = await ghFetch(url2); - if (response.status === 404) return null; - if (!response.ok) { - throw unprocessable(`Failed to fetch ${url2}: ${response.status}`); - } - return response.text(); -} -async function fetchBinary(url2) { - const response = await ghFetch(url2); - if (!response.ok) { - throw unprocessable(`Failed to fetch ${url2}: ${response.status}`); - } - return Buffer.from(await response.arrayBuffer()); -} -async function fetchJson2(url2) { - const response = await ghFetch(url2, { - headers: { - accept: "application/vnd.github+json" - } - }); - if (!response.ok) { - throw unprocessable(`Failed to fetch ${url2}: ${response.status}`); - } - return response.json(); -} -function dedupeEnvInputs(values2) { - const seen = /* @__PURE__ */ new Set(); - const out = []; - for (const value of values2) { - const key = `${value.agentSlug ?? ""}:${value.projectSlug ?? ""}:${value.key.toUpperCase()}`; - if (seen.has(key)) continue; - seen.add(key); - out.push(value); - } - return out; -} -function buildEnvInputMap(inputs) { - const env2 = {}; - for (const input of inputs) { - const entry = { - kind: input.kind, - requirement: input.requirement - }; - if (input.defaultValue !== null) entry.default = input.defaultValue; - if (input.description) entry.description = input.description; - if (input.portability === "system_dependent") entry.portability = "system_dependent"; - env2[input.key] = entry; - } - return env2; -} -function readCompanyApprovalDefault(_frontmatter) { - return true; -} -function readIncludeEntries(frontmatter) { - const includes = frontmatter.includes; - if (!Array.isArray(includes)) return []; - return includes.flatMap((entry) => { - if (typeof entry === "string") { - return [{ path: entry }]; - } - if (isPlainRecord5(entry)) { - const pathValue = asString14(entry.path); - return pathValue ? [{ path: pathValue }] : []; - } - return []; - }); -} -function readAgentEnvInputs(extension2, agentSlug) { - const inputs = isPlainRecord5(extension2.inputs) ? extension2.inputs : null; - const env2 = inputs && isPlainRecord5(inputs.env) ? inputs.env : null; - if (!env2) return []; - return Object.entries(env2).flatMap(([key, value]) => { - if (!isPlainRecord5(value)) return []; - const record2 = value; - return [{ - key, - description: asString14(record2.description) ?? null, - agentSlug, - projectSlug: null, - kind: record2.kind === "plain" ? "plain" : "secret", - requirement: record2.requirement === "required" ? "required" : "optional", - defaultValue: typeof record2.default === "string" ? record2.default : null, - portability: record2.portability === "system_dependent" ? "system_dependent" : "portable" - }]; - }); -} -function readProjectEnvInputs(extension2, projectSlug) { - const inputs = isPlainRecord5(extension2.inputs) ? extension2.inputs : null; - const env2 = inputs && isPlainRecord5(inputs.env) ? inputs.env : null; - if (!env2) return []; - return Object.entries(env2).flatMap(([key, value]) => { - if (!isPlainRecord5(value)) return []; - const record2 = value; - return [{ - key, - description: asString14(record2.description) ?? null, - agentSlug: null, - projectSlug, - kind: record2.kind === "plain" ? "plain" : "secret", - requirement: record2.requirement === "required" ? "required" : "optional", - defaultValue: typeof record2.default === "string" ? record2.default : null, - portability: record2.portability === "system_dependent" ? "system_dependent" : "portable" - }]; - }); -} -function readAgentSkillRefs(frontmatter) { - const skills = frontmatter.skills; - if (!Array.isArray(skills)) return []; - return Array.from(new Set( - skills.filter((entry) => typeof entry === "string").map((entry) => normalizeSkillKey2(entry) ?? entry.trim()).filter(Boolean) - )); -} -function buildManifestFromPackageFiles(files, opts) { - const normalizedFiles = normalizeFileMap(files); - const companyPath = typeof normalizedFiles["COMPANY.md"] === "string" ? normalizedFiles["COMPANY.md"] : void 0; - const resolvedCompanyPath = companyPath !== void 0 ? "COMPANY.md" : Object.keys(normalizedFiles).find((entry) => entry.endsWith("/COMPANY.md") || entry === "COMPANY.md"); - if (!resolvedCompanyPath) { - throw unprocessable("Company package is missing COMPANY.md"); - } - const companyMarkdown = readPortableTextFile(normalizedFiles, resolvedCompanyPath); - if (typeof companyMarkdown !== "string") { - throw unprocessable(`Company package file is not readable as text: ${resolvedCompanyPath}`); - } - const companyDoc = parseFrontmatterMarkdown2(companyMarkdown); - const companyFrontmatter = companyDoc.frontmatter; - const taskcoreExtensionPath = findTaskcoreExtensionPath(normalizedFiles); - const taskcoreExtension = taskcoreExtensionPath ? parseYamlFile(readPortableTextFile(normalizedFiles, taskcoreExtensionPath) ?? "") : {}; - const taskcoreCompany = isPlainRecord5(taskcoreExtension.company) ? taskcoreExtension.company : {}; - const taskcoreSidebar = normalizePortableSidebarOrder(taskcoreExtension.sidebar); - const taskcoreAgents = isPlainRecord5(taskcoreExtension.agents) ? taskcoreExtension.agents : {}; - const taskcoreProjects = isPlainRecord5(taskcoreExtension.projects) ? taskcoreExtension.projects : {}; - const taskcoreTasks = isPlainRecord5(taskcoreExtension.tasks) ? taskcoreExtension.tasks : {}; - const taskcoreRoutines = isPlainRecord5(taskcoreExtension.routines) ? taskcoreExtension.routines : {}; - const companyName = asString14(companyFrontmatter.name) ?? opts?.sourceLabel?.companyName ?? "Imported Company"; - const companySlug = asString14(companyFrontmatter.slug) ?? normalizeAgentUrlKey(companyName) ?? "company"; - const includeEntries = readIncludeEntries(companyFrontmatter); - const referencedAgentPaths = includeEntries.map((entry) => resolvePortablePath(resolvedCompanyPath, entry.path)).filter((entry) => entry.endsWith("/AGENTS.md") || entry === "AGENTS.md"); - const referencedProjectPaths = includeEntries.map((entry) => resolvePortablePath(resolvedCompanyPath, entry.path)).filter((entry) => entry.endsWith("/PROJECT.md") || entry === "PROJECT.md"); - const referencedTaskPaths = includeEntries.map((entry) => resolvePortablePath(resolvedCompanyPath, entry.path)).filter((entry) => entry.endsWith("/TASK.md") || entry === "TASK.md"); - const referencedSkillPaths = includeEntries.map((entry) => resolvePortablePath(resolvedCompanyPath, entry.path)).filter((entry) => entry.endsWith("/SKILL.md") || entry === "SKILL.md"); - const discoveredAgentPaths = Object.keys(normalizedFiles).filter( - (entry) => entry.endsWith("/AGENTS.md") || entry === "AGENTS.md" - ); - const discoveredProjectPaths = Object.keys(normalizedFiles).filter( - (entry) => entry.endsWith("/PROJECT.md") || entry === "PROJECT.md" - ); - const discoveredTaskPaths = Object.keys(normalizedFiles).filter( - (entry) => entry.endsWith("/TASK.md") || entry === "TASK.md" - ); - const discoveredSkillPaths = Object.keys(normalizedFiles).filter( - (entry) => entry.endsWith("/SKILL.md") || entry === "SKILL.md" - ); - const agentPaths = Array.from(/* @__PURE__ */ new Set([...referencedAgentPaths, ...discoveredAgentPaths])).sort(); - const projectPaths = Array.from(/* @__PURE__ */ new Set([...referencedProjectPaths, ...discoveredProjectPaths])).sort(); - const taskPaths = Array.from(/* @__PURE__ */ new Set([...referencedTaskPaths, ...discoveredTaskPaths])).sort(); - const skillPaths = Array.from(/* @__PURE__ */ new Set([...referencedSkillPaths, ...discoveredSkillPaths])).sort(); - const manifest = { - schemaVersion: 5, - generatedAt: (/* @__PURE__ */ new Date()).toISOString(), - source: opts?.sourceLabel ?? null, - includes: { - company: true, - agents: true, - projects: projectPaths.length > 0, - issues: taskPaths.length > 0, - skills: skillPaths.length > 0 - }, - company: { - path: resolvedCompanyPath, - name: companyName, - description: asString14(companyFrontmatter.description), - brandColor: asString14(taskcoreCompany.brandColor), - logoPath: asString14(taskcoreCompany.logoPath) ?? asString14(taskcoreCompany.logo), - requireBoardApprovalForNewAgents: typeof taskcoreCompany.requireBoardApprovalForNewAgents === "boolean" ? taskcoreCompany.requireBoardApprovalForNewAgents : readCompanyApprovalDefault(companyFrontmatter), - feedbackDataSharingEnabled: typeof taskcoreCompany.feedbackDataSharingEnabled === "boolean" ? taskcoreCompany.feedbackDataSharingEnabled : false, - feedbackDataSharingConsentAt: typeof taskcoreCompany.feedbackDataSharingConsentAt === "string" ? taskcoreCompany.feedbackDataSharingConsentAt : null, - feedbackDataSharingConsentByUserId: asString14(taskcoreCompany.feedbackDataSharingConsentByUserId), - feedbackDataSharingTermsVersion: asString14(taskcoreCompany.feedbackDataSharingTermsVersion) - }, - sidebar: taskcoreSidebar, - agents: [], - skills: [], - projects: [], - issues: [], - envInputs: [] - }; - const warnings = []; - if (manifest.company?.logoPath && !normalizedFiles[manifest.company.logoPath]) { - warnings.push(`Referenced company logo file is missing from package: ${manifest.company.logoPath}`); - } - for (const agentPath of agentPaths) { - const markdownRaw = readPortableTextFile(normalizedFiles, agentPath); - if (typeof markdownRaw !== "string") { - warnings.push(`Referenced agent file is missing from package: ${agentPath}`); - continue; - } - const agentDoc = parseFrontmatterMarkdown2(markdownRaw); - const frontmatter = agentDoc.frontmatter; - const fallbackSlug = normalizeAgentUrlKey(path40.posix.basename(path40.posix.dirname(agentPath))) ?? "agent"; - const slug = asString14(frontmatter.slug) ?? fallbackSlug; - const extension2 = isPlainRecord5(taskcoreAgents[slug]) ? taskcoreAgents[slug] : {}; - const extensionAdapter = isPlainRecord5(extension2.adapter) ? extension2.adapter : null; - const extensionRuntime = isPlainRecord5(extension2.runtime) ? extension2.runtime : null; - const extensionPermissions = isPlainRecord5(extension2.permissions) ? extension2.permissions : null; - const extensionMetadata = isPlainRecord5(extension2.metadata) ? extension2.metadata : null; - const adapterConfig = isPlainRecord5(extensionAdapter?.config) ? extensionAdapter.config : {}; - const runtimeConfig = extensionRuntime ?? {}; - const title = asString14(frontmatter.title); - manifest.agents.push({ - slug, - name: asString14(frontmatter.name) ?? title ?? slug, - path: agentPath, - skills: readAgentSkillRefs(frontmatter), - role: asString14(extension2.role) ?? asString14(frontmatter.role) ?? "agent", - title, - icon: asString14(extension2.icon), - capabilities: asString14(extension2.capabilities), - reportsToSlug: asString14(frontmatter.reportsTo) ?? asString14(extension2.reportsTo), - adapterType: asString14(extensionAdapter?.type) ?? "process", - adapterConfig, - runtimeConfig, - permissions: extensionPermissions ?? {}, - budgetMonthlyCents: typeof extension2.budgetMonthlyCents === "number" && Number.isFinite(extension2.budgetMonthlyCents) ? Math.max(0, Math.floor(extension2.budgetMonthlyCents)) : 0, - metadata: extensionMetadata - }); - manifest.envInputs.push(...readAgentEnvInputs(extension2, slug)); - if (frontmatter.kind && frontmatter.kind !== "agent") { - warnings.push(`Agent markdown ${agentPath} does not declare kind: agent in frontmatter.`); - } - } - for (const skillPath of skillPaths) { - const markdownRaw = readPortableTextFile(normalizedFiles, skillPath); - if (typeof markdownRaw !== "string") { - warnings.push(`Referenced skill file is missing from package: ${skillPath}`); - continue; - } - const skillDoc = parseFrontmatterMarkdown2(markdownRaw); - const frontmatter = skillDoc.frontmatter; - const skillDir = path40.posix.dirname(skillPath); - const fallbackSlug = normalizeAgentUrlKey(path40.posix.basename(skillDir)) ?? "skill"; - const slug = asString14(frontmatter.slug) ?? normalizeAgentUrlKey(asString14(frontmatter.name) ?? "") ?? fallbackSlug; - const inventory = Object.keys(normalizedFiles).filter((entry) => entry === skillPath || entry.startsWith(`${skillDir}/`)).map((entry) => ({ - path: entry === skillPath ? "SKILL.md" : entry.slice(skillDir.length + 1), - kind: entry === skillPath ? "skill" : entry.startsWith(`${skillDir}/references/`) ? "reference" : entry.startsWith(`${skillDir}/scripts/`) ? "script" : entry.startsWith(`${skillDir}/assets/`) ? "asset" : entry.endsWith(".md") ? "markdown" : "other" - })); - const metadata = isPlainRecord5(frontmatter.metadata) ? frontmatter.metadata : null; - const sources = metadata && Array.isArray(metadata.sources) ? metadata.sources : []; - const primarySource = sources.find((entry) => isPlainRecord5(entry)); - const sourceKind = asString14(primarySource?.kind); - let sourceType = "catalog"; - let sourceLocator = null; - let sourceRef = null; - let normalizedMetadata = null; - if (sourceKind === "github-dir" || sourceKind === "github-file") { - const repo = asString14(primarySource?.repo); - const repoPath = asString14(primarySource?.path); - const commit = asString14(primarySource?.commit); - const trackingRef = asString14(primarySource?.trackingRef); - const sourceHostname = asString14(primarySource?.hostname) || "github.com"; - const [owner, repoName] = (repo ?? "").split("/"); - sourceType = "github"; - sourceLocator = asString14(primarySource?.url) ?? (repo ? `https://${sourceHostname}/${repo}${repoPath ? `/tree/${trackingRef ?? commit ?? "main"}/${repoPath}` : ""}` : null); - sourceRef = commit; - normalizedMetadata = owner && repoName ? { - sourceKind: "github", - ...sourceHostname !== "github.com" ? { hostname: sourceHostname } : {}, - owner, - repo: repoName, - ref: commit, - trackingRef, - repoSkillDir: repoPath ?? `skills/${slug}` - } : null; - } else if (sourceKind === "url") { - sourceType = "url"; - sourceLocator = asString14(primarySource?.url) ?? asString14(primarySource?.rawUrl); - normalizedMetadata = { - sourceKind: "url" - }; - } else if (metadata) { - normalizedMetadata = { - sourceKind: "catalog" - }; - } - const key = deriveManifestSkillKey(frontmatter, slug, normalizedMetadata, sourceType, sourceLocator); - manifest.skills.push({ - key, - slug, - name: asString14(frontmatter.name) ?? slug, - path: skillPath, - description: asString14(frontmatter.description), - sourceType, - sourceLocator, - sourceRef, - trustLevel: null, - compatibility: "compatible", - metadata: normalizedMetadata, - fileInventory: inventory - }); - } - for (const projectPath of projectPaths) { - const markdownRaw = readPortableTextFile(normalizedFiles, projectPath); - if (typeof markdownRaw !== "string") { - warnings.push(`Referenced project file is missing from package: ${projectPath}`); - continue; - } - const projectDoc = parseFrontmatterMarkdown2(markdownRaw); - const frontmatter = projectDoc.frontmatter; - const fallbackSlug = deriveProjectUrlKey( - asString14(frontmatter.name) ?? path40.posix.basename(path40.posix.dirname(projectPath)) ?? "project", - projectPath - ); - const slug = asString14(frontmatter.slug) ?? fallbackSlug; - const extension2 = isPlainRecord5(taskcoreProjects[slug]) ? taskcoreProjects[slug] : {}; - const workspaceExtensions = isPlainRecord5(extension2.workspaces) ? extension2.workspaces : {}; - const workspaces = Object.entries(workspaceExtensions).map(([workspaceKey, entry]) => normalizePortableProjectWorkspaceExtension(workspaceKey, entry)).filter((entry) => entry !== null); - manifest.projects.push({ - slug, - name: asString14(frontmatter.name) ?? slug, - path: projectPath, - description: asString14(frontmatter.description), - ownerAgentSlug: asString14(frontmatter.owner), - leadAgentSlug: asString14(extension2.leadAgentSlug), - targetDate: asString14(extension2.targetDate), - color: asString14(extension2.color), - status: asString14(extension2.status), - env: normalizePortableProjectEnv(extension2.env), - executionWorkspacePolicy: isPlainRecord5(extension2.executionWorkspacePolicy) ? extension2.executionWorkspacePolicy : null, - workspaces, - metadata: isPlainRecord5(extension2.metadata) ? extension2.metadata : null - }); - manifest.envInputs.push(...readProjectEnvInputs(extension2, slug)); - if (frontmatter.kind && frontmatter.kind !== "project") { - warnings.push(`Project markdown ${projectPath} does not declare kind: project in frontmatter.`); - } - } - for (const taskPath of taskPaths) { - const markdownRaw = readPortableTextFile(normalizedFiles, taskPath); - if (typeof markdownRaw !== "string") { - warnings.push(`Referenced task file is missing from package: ${taskPath}`); - continue; - } - const taskDoc = parseFrontmatterMarkdown2(markdownRaw); - const frontmatter = taskDoc.frontmatter; - const fallbackSlug = normalizeAgentUrlKey(path40.posix.basename(path40.posix.dirname(taskPath))) ?? "task"; - const slug = asString14(frontmatter.slug) ?? fallbackSlug; - const extension2 = isPlainRecord5(taskcoreTasks[slug]) ? taskcoreTasks[slug] : {}; - const routineExtension = normalizeRoutineExtension(taskcoreRoutines[slug]); - const routineExtensionRaw = isPlainRecord5(taskcoreRoutines[slug]) ? taskcoreRoutines[slug] : {}; - const schedule = isPlainRecord5(frontmatter.schedule) ? frontmatter.schedule : null; - const legacyRecurrence = schedule && isPlainRecord5(schedule.recurrence) ? schedule.recurrence : isPlainRecord5(extension2.recurrence) ? extension2.recurrence : null; - const recurring = asBoolean5(frontmatter.recurring) === true || routineExtension !== null || legacyRecurrence !== null; - manifest.issues.push({ - slug, - identifier: asString14(extension2.identifier), - title: asString14(frontmatter.name) ?? asString14(frontmatter.title) ?? slug, - path: taskPath, - projectSlug: asString14(frontmatter.project), - projectWorkspaceKey: asString14(extension2.projectWorkspaceKey), - assigneeAgentSlug: asString14(frontmatter.assignee), - description: taskDoc.body || asString14(frontmatter.description), - recurring, - routine: routineExtension, - legacyRecurrence, - status: asString14(extension2.status) ?? asString14(routineExtensionRaw.status), - priority: asString14(extension2.priority) ?? asString14(routineExtensionRaw.priority), - labelIds: Array.isArray(extension2.labelIds) ? extension2.labelIds.filter((entry) => typeof entry === "string") : [], - billingCode: asString14(extension2.billingCode), - executionWorkspaceSettings: isPlainRecord5(extension2.executionWorkspaceSettings) ? extension2.executionWorkspaceSettings : null, - assigneeAdapterOverrides: isPlainRecord5(extension2.assigneeAdapterOverrides) ? extension2.assigneeAdapterOverrides : null, - metadata: isPlainRecord5(extension2.metadata) ? extension2.metadata : null - }); - if (frontmatter.kind && frontmatter.kind !== "task") { - warnings.push(`Task markdown ${taskPath} does not declare kind: task in frontmatter.`); - } - } - manifest.envInputs = dedupeEnvInputs(manifest.envInputs); - return { - manifest, - files: normalizedFiles, - warnings - }; -} -function normalizeGitHubSourcePath(value) { - if (!value) return ""; - return value.trim().replace(/\\/g, "/").replace(/^\/+|\/+$/g, ""); -} -function parseGitHubSourceUrl2(rawUrl) { - const url2 = new URL(rawUrl); - if (url2.protocol !== "https:") { - throw unprocessable("GitHub source URL must use HTTPS"); - } - const hostname3 = url2.hostname; - const parts = url2.pathname.split("/").filter(Boolean); - if (parts.length < 2) { - throw unprocessable("Invalid GitHub URL"); - } - const owner = parts[0]; - const repo = parts[1].replace(/\.git$/i, ""); - const queryRef = url2.searchParams.get("ref")?.trim(); - const queryPath = normalizeGitHubSourcePath(url2.searchParams.get("path")); - const queryCompanyPath = normalizeGitHubSourcePath(url2.searchParams.get("companyPath")); - if (queryRef || queryPath || queryCompanyPath) { - const companyPath2 = queryCompanyPath || [queryPath, "COMPANY.md"].filter(Boolean).join("/") || "COMPANY.md"; - let basePath2 = queryPath; - if (!basePath2 && companyPath2 !== "COMPANY.md") { - basePath2 = path40.posix.dirname(companyPath2); - if (basePath2 === ".") basePath2 = ""; - } - return { - hostname: hostname3, - owner, - repo, - ref: queryRef || "main", - basePath: basePath2, - companyPath: companyPath2 - }; - } - let ref = "main"; - let basePath = ""; - let companyPath = "COMPANY.md"; - if (parts[2] === "tree") { - ref = parts[3] ?? "main"; - basePath = parts.slice(4).join("/"); - } else if (parts[2] === "blob") { - ref = parts[3] ?? "main"; - const blobPath = parts.slice(4).join("/"); - if (!blobPath) { - throw unprocessable("Invalid GitHub blob URL"); - } - companyPath = blobPath; - basePath = path40.posix.dirname(blobPath); - if (basePath === ".") basePath = ""; - } - return { hostname: hostname3, owner, repo, ref, basePath, companyPath }; -} -function companyPortabilityService(db, storage) { - const companies2 = companyService(db); - const agents2 = agentService(db); - const assetRecords = assetService(db); - const instructions = agentInstructionsService(); - const access = accessService(db); - const projects2 = projectService(db); - const issues2 = issueService(db); - const companySkills2 = companySkillService(db); - async function resolveSource(source) { - if (source.type === "inline") { - return buildManifestFromPackageFiles( - normalizeFileMap(source.files, source.rootPath) - ); - } - const parsed = parseGitHubSourceUrl2(source.url); - let ref = parsed.ref; - const warnings = []; - const companyRelativePath = parsed.companyPath === "COMPANY.md" ? [parsed.basePath, "COMPANY.md"].filter(Boolean).join("/") : parsed.companyPath; - let companyMarkdown = null; - try { - companyMarkdown = await fetchOptionalText( - resolveRawGitHubUrl(parsed.hostname, parsed.owner, parsed.repo, ref, companyRelativePath) - ); - } catch (err) { - if (ref === "main") { - ref = "master"; - warnings.push("GitHub ref main not found; falling back to master."); - companyMarkdown = await fetchOptionalText( - resolveRawGitHubUrl(parsed.hostname, parsed.owner, parsed.repo, ref, companyRelativePath) - ); - } else { - throw err; - } - } - if (!companyMarkdown) { - throw unprocessable("GitHub company package is missing COMPANY.md"); - } - const companyPath = parsed.companyPath === "COMPANY.md" ? "COMPANY.md" : normalizePortablePath2(path40.posix.relative(parsed.basePath || ".", parsed.companyPath)); - const files = { - [companyPath]: companyMarkdown - }; - const apiBase = gitHubApiBase(parsed.hostname); - const tree = await fetchJson2( - `${apiBase}/repos/${parsed.owner}/${parsed.repo}/git/trees/${ref}?recursive=1` - ).catch(() => ({ tree: [] })); - const basePrefix = parsed.basePath ? `${parsed.basePath.replace(/^\/+|\/+$/g, "")}/` : ""; - const candidatePaths = (tree.tree ?? []).filter((entry) => entry.type === "blob").map((entry) => entry.path).filter((entry) => typeof entry === "string").filter((entry) => { - if (basePrefix && !entry.startsWith(basePrefix)) return false; - const relative3 = basePrefix ? entry.slice(basePrefix.length) : entry; - return relative3.endsWith(".md") || relative3.startsWith("skills/") || relative3 === ".taskcore.yaml" || relative3 === ".taskcore.yml"; - }); - for (const repoPath of candidatePaths) { - const relativePath = basePrefix ? repoPath.slice(basePrefix.length) : repoPath; - if (files[relativePath] !== void 0) continue; - files[normalizePortablePath2(relativePath)] = await fetchText2( - resolveRawGitHubUrl(parsed.hostname, parsed.owner, parsed.repo, ref, repoPath) - ); - } - const companyDoc = parseFrontmatterMarkdown2(companyMarkdown); - const includeEntries = readIncludeEntries(companyDoc.frontmatter); - for (const includeEntry of includeEntries) { - const repoPath = [parsed.basePath, includeEntry.path].filter(Boolean).join("/"); - const relativePath = normalizePortablePath2(includeEntry.path); - if (files[relativePath] !== void 0) continue; - if (!(repoPath.endsWith(".md") || repoPath.endsWith(".yaml") || repoPath.endsWith(".yml"))) continue; - files[relativePath] = await fetchText2( - resolveRawGitHubUrl(parsed.hostname, parsed.owner, parsed.repo, ref, repoPath) - ); - } - const resolved = buildManifestFromPackageFiles(files); - const companyLogoPath = resolved.manifest.company?.logoPath; - if (companyLogoPath && !resolved.files[companyLogoPath]) { - const repoPath = [parsed.basePath, companyLogoPath].filter(Boolean).join("/"); - try { - const binary2 = await fetchBinary( - resolveRawGitHubUrl(parsed.hostname, parsed.owner, parsed.repo, ref, repoPath) - ); - resolved.files[companyLogoPath] = bufferToPortableBinaryFile(binary2, inferContentTypeFromPath(companyLogoPath)); - } catch (err) { - warnings.push(`Failed to fetch company logo ${companyLogoPath} from GitHub: ${err instanceof Error ? err.message : String(err)}`); - } - } - resolved.warnings.unshift(...warnings); - return resolved; - } - async function exportBundle(companyId, input) { - const include = normalizeInclude({ - ...input.include, - agents: input.agents && input.agents.length > 0 ? true : input.include?.agents, - projects: input.projects && input.projects.length > 0 ? true : input.include?.projects, - issues: input.issues && input.issues.length > 0 || input.projectIssues && input.projectIssues.length > 0 ? true : input.include?.issues, - skills: input.skills && input.skills.length > 0 ? true : input.include?.skills - }); - const company = await companies2.getById(companyId); - if (!company) throw notFound("Company not found"); - const files = {}; - const warnings = []; - const envInputs = []; - const requestedSidebarOrder = normalizePortableSidebarOrder(input.sidebarOrder); - const rootPath = normalizeAgentUrlKey(company.name) ?? "company-package"; - let companyLogoPath = null; - const allAgentRows = include.agents ? await agents2.list(companyId, { includeTerminated: true }) : []; - const liveAgentRows = allAgentRows.filter((agent) => agent.status !== "terminated"); - const companySkillRows = include.skills || include.agents ? await companySkills2.listFull(companyId) : []; - if (include.agents) { - const skipped = allAgentRows.length - liveAgentRows.length; - if (skipped > 0) { - warnings.push(`Skipped ${skipped} terminated agent${skipped === 1 ? "" : "s"} from export.`); - } - } - const agentByReference = /* @__PURE__ */ new Map(); - for (const agent of liveAgentRows) { - agentByReference.set(agent.id, agent); - agentByReference.set(agent.name, agent); - const normalizedName = normalizeAgentUrlKey(agent.name); - if (normalizedName) { - agentByReference.set(normalizedName, agent); - } - } - const selectedAgents = /* @__PURE__ */ new Map(); - for (const selector of input.agents ?? []) { - const trimmed = selector.trim(); - if (!trimmed) continue; - const normalized = normalizeAgentUrlKey(trimmed) ?? trimmed; - const match = agentByReference.get(trimmed) ?? agentByReference.get(normalized); - if (!match) { - warnings.push(`Agent selector "${selector}" was not found and was skipped.`); - continue; - } - selectedAgents.set(match.id, match); - } - if (include.agents && selectedAgents.size === 0) { - for (const agent of liveAgentRows) { - selectedAgents.set(agent.id, agent); - } - } - const agentRows = Array.from(selectedAgents.values()).sort((left, right) => left.name.localeCompare(right.name)); - const usedSlugs = /* @__PURE__ */ new Set(); - const idToSlug = /* @__PURE__ */ new Map(); - for (const agent of agentRows) { - const baseSlug = toSafeSlug(agent.name, "agent"); - const slug = uniqueSlug(baseSlug, usedSlugs); - idToSlug.set(agent.id, slug); - } - const projectsSvc = projectService(db); - const issuesSvc = issueService(db); - const routinesSvc = routineService(db); - const allProjectsRaw = include.projects || include.issues ? await projectsSvc.list(companyId) : []; - const allProjects = allProjectsRaw.filter((project) => !project.archivedAt); - const allRoutines = include.issues ? await routinesSvc.list(companyId) : []; - const projectById = new Map(allProjects.map((project) => [project.id, project])); - const projectByReference = /* @__PURE__ */ new Map(); - for (const project of allProjects) { - projectByReference.set(project.id, project); - projectByReference.set(project.urlKey, project); - } - const selectedProjects = /* @__PURE__ */ new Map(); - const normalizeProjectSelector = (selector) => selector.trim().toLowerCase(); - for (const selector of input.projects ?? []) { - const match = projectByReference.get(selector) ?? projectByReference.get(normalizeProjectSelector(selector)); - if (!match) { - warnings.push(`Project selector "${selector}" was not found and was skipped.`); - continue; - } - selectedProjects.set(match.id, match); - } - const selectedIssues = /* @__PURE__ */ new Map(); - const selectedRoutines = /* @__PURE__ */ new Map(); - const routineById = new Map(allRoutines.map((routine) => [routine.id, routine])); - const resolveIssueBySelector = async (selector) => { - const trimmed = selector.trim(); - if (!trimmed) return null; - return trimmed.includes("-") ? issuesSvc.getByIdentifier(trimmed) : issuesSvc.getById(trimmed); - }; - for (const selector of input.issues ?? []) { - const issue2 = await resolveIssueBySelector(selector); - if (!issue2 || issue2.companyId !== companyId) { - const routine = routineById.get(selector.trim()); - if (routine) { - selectedRoutines.set(routine.id, routine); - if (routine.projectId) { - const parentProject = projectById.get(routine.projectId); - if (parentProject) selectedProjects.set(parentProject.id, parentProject); - } - continue; - } - warnings.push(`Issue selector "${selector}" was not found and was skipped.`); - continue; - } - selectedIssues.set(issue2.id, issue2); - if (issue2.projectId) { - const parentProject = projectById.get(issue2.projectId); - if (parentProject) selectedProjects.set(parentProject.id, parentProject); - } - } - for (const selector of input.projectIssues ?? []) { - const match = projectByReference.get(selector) ?? projectByReference.get(normalizeProjectSelector(selector)); - if (!match) { - warnings.push(`Project-issues selector "${selector}" was not found and was skipped.`); - continue; - } - selectedProjects.set(match.id, match); - const projectIssues = await issuesSvc.list(companyId, { projectId: match.id }); - for (const issue2 of projectIssues) { - selectedIssues.set(issue2.id, issue2); - } - for (const routine of allRoutines.filter((entry) => entry.projectId === match.id)) { - selectedRoutines.set(routine.id, routine); - } - } - if (include.projects && selectedProjects.size === 0) { - for (const project of allProjects) { - selectedProjects.set(project.id, project); - } - } - if (include.issues && selectedIssues.size === 0) { - const allIssues = await issuesSvc.list(companyId); - for (const issue2 of allIssues) { - selectedIssues.set(issue2.id, issue2); - if (issue2.projectId) { - const parentProject = projectById.get(issue2.projectId); - if (parentProject) selectedProjects.set(parentProject.id, parentProject); - } - } - if (selectedRoutines.size === 0) { - for (const routine of allRoutines) { - selectedRoutines.set(routine.id, routine); - if (routine.projectId) { - const parentProject = projectById.get(routine.projectId); - if (parentProject) selectedProjects.set(parentProject.id, parentProject); - } - } - } - } - const selectedProjectRows = Array.from(selectedProjects.values()).sort((left, right) => left.name.localeCompare(right.name)); - const selectedIssueRows = Array.from(selectedIssues.values()).filter((issue2) => issue2 != null).sort((left, right) => (left.identifier ?? left.title).localeCompare(right.identifier ?? right.title)); - const selectedRoutineSummaries = Array.from(selectedRoutines.values()).sort((left, right) => left.title.localeCompare(right.title)); - const selectedRoutineRows = (await Promise.all(selectedRoutineSummaries.map((routine) => routinesSvc.getDetail(routine.id)))).filter((routine) => routine !== null); - const taskSlugByIssueId = /* @__PURE__ */ new Map(); - const taskSlugByRoutineId = /* @__PURE__ */ new Map(); - const usedTaskSlugs = /* @__PURE__ */ new Set(); - for (const issue2 of selectedIssueRows) { - const baseSlug = normalizeAgentUrlKey(issue2.identifier ?? issue2.title) ?? "task"; - taskSlugByIssueId.set(issue2.id, uniqueSlug(baseSlug, usedTaskSlugs)); - } - for (const routine of selectedRoutineRows) { - const baseSlug = normalizeAgentUrlKey(routine.title) ?? "task"; - taskSlugByRoutineId.set(routine.id, uniqueSlug(baseSlug, usedTaskSlugs)); - } - const projectSlugById = /* @__PURE__ */ new Map(); - const projectWorkspaceKeyByProjectId = /* @__PURE__ */ new Map(); - const usedProjectSlugs = /* @__PURE__ */ new Set(); - for (const project of selectedProjectRows) { - const baseSlug = deriveProjectUrlKey(project.name, project.name); - projectSlugById.set(project.id, uniqueSlug(baseSlug, usedProjectSlugs)); - } - const sidebarOrder = requestedSidebarOrder ?? stripEmptyValues({ - agents: sortAgentsBySidebarOrder(Array.from(selectedAgents.values())).map((agent) => idToSlug.get(agent.id)).filter((slug) => Boolean(slug)), - projects: selectedProjectRows.map((project) => projectSlugById.get(project.id)).filter((slug) => Boolean(slug)) - }); - const companyPath = "COMPANY.md"; - files[companyPath] = buildMarkdown( - { - name: company.name, - description: company.description ?? null, - schema: "agentcompanies/v1", - slug: rootPath - }, - "" - ); - if (include.company && company.logoAssetId) { - if (!storage) { - warnings.push("Skipped company logo from export because storage is unavailable."); - } else { - const logoAsset = await assetRecords.getById(company.logoAssetId); - if (!logoAsset) { - warnings.push(`Skipped company logo ${company.logoAssetId} because the asset record was not found.`); - } else { - try { - const object2 = await storage.getObject(company.id, logoAsset.objectKey); - const body = await streamToBuffer(object2.stream); - companyLogoPath = `images/${COMPANY_LOGO_FILE_NAME}${resolveCompanyLogoExtension(logoAsset.contentType, logoAsset.originalFilename)}`; - files[companyLogoPath] = bufferToPortableBinaryFile(body, logoAsset.contentType); - } catch (err) { - warnings.push(`Failed to export company logo ${company.logoAssetId}: ${err instanceof Error ? err.message : String(err)}`); - } - } - } - } - const taskcoreAgentsOut = {}; - const taskcoreProjectsOut = {}; - const taskcoreTasksOut = {}; - const unportableTaskWorkspaceRefs = /* @__PURE__ */ new Map(); - const taskcoreRoutinesOut = {}; - const skillByReference = /* @__PURE__ */ new Map(); - for (const skill of companySkillRows) { - skillByReference.set(skill.id, skill); - skillByReference.set(skill.key, skill); - skillByReference.set(skill.slug, skill); - skillByReference.set(skill.name, skill); - } - const selectedSkills = /* @__PURE__ */ new Map(); - for (const selector of input.skills ?? []) { - const trimmed = selector.trim(); - if (!trimmed) continue; - const normalized = normalizeSkillKey2(trimmed) ?? normalizeSkillSlug3(trimmed) ?? trimmed; - const match = skillByReference.get(trimmed) ?? skillByReference.get(normalized); - if (!match) { - warnings.push(`Skill selector "${selector}" was not found and was skipped.`); - continue; - } - selectedSkills.set(match.id, match); - } - if (selectedSkills.size === 0) { - for (const skill of companySkillRows) { - selectedSkills.set(skill.id, skill); - } - } - const selectedSkillRows = Array.from(selectedSkills.values()).sort((left, right) => left.key.localeCompare(right.key)); - const skillExportDirs = buildSkillExportDirMap(selectedSkillRows, company.issuePrefix); - for (const skill of selectedSkillRows) { - const packageDir = skillExportDirs.get(skill.key) ?? `skills/${normalizeSkillSlug3(skill.slug) ?? "skill"}`; - if (shouldReferenceSkillOnExport(skill, Boolean(input.expandReferencedSkills))) { - files[`${packageDir}/SKILL.md`] = await buildReferencedSkillMarkdown(skill); - continue; - } - for (const inventoryEntry of skill.fileInventory) { - const fileDetail = await companySkills2.readFile(companyId, skill.id, inventoryEntry.path).catch(() => null); - if (!fileDetail) continue; - const filePath = `${packageDir}/${inventoryEntry.path}`; - files[filePath] = inventoryEntry.path === "SKILL.md" ? await withSkillSourceMetadata(skill, fileDetail.content) : fileDetail.content; - } - } - if (include.agents) { - for (const agent of agentRows) { - const slug = idToSlug.get(agent.id); - const exportedInstructions = await instructions.exportFiles(agent); - warnings.push(...exportedInstructions.warnings); - const envInputsStart = envInputs.length; - const exportedEnvInputs = extractPortableEnvInputs( - slug, - agent.adapterConfig.env, - warnings - ); - envInputs.push(...exportedEnvInputs); - const adapterDefaultRules = ADAPTER_DEFAULT_RULES_BY_TYPE[agent.adapterType] ?? []; - const portableAdapterConfig = pruneDefaultLikeValue( - normalizePortableConfig(agent.adapterConfig), - { - dropFalseBooleans: true, - defaultRules: adapterDefaultRules - } - ); - const portableRuntimeConfig = pruneDefaultLikeValue( - normalizePortableConfig(agent.runtimeConfig), - { - dropFalseBooleans: true, - defaultRules: RUNTIME_DEFAULT_RULES - } - ); - const portablePermissions = pruneDefaultLikeValue(agent.permissions ?? {}, { dropFalseBooleans: true }); - const agentEnvInputs = dedupeEnvInputs( - envInputs.slice(envInputsStart).filter((inputValue) => inputValue.agentSlug === slug) - ); - const reportsToSlug = agent.reportsTo ? idToSlug.get(agent.reportsTo) ?? null : null; - const desiredSkills = readTaskcoreSkillSyncPreference( - agent.adapterConfig ?? {} - ).desiredSkills; - const commandValue = asString14(portableAdapterConfig.command); - if (commandValue && isAbsoluteCommand(commandValue)) { - warnings.push(`Agent ${slug} command ${commandValue} was omitted from export because it is system-dependent.`); - delete portableAdapterConfig.command; - } - for (const [relativePath, content] of Object.entries(exportedInstructions.files)) { - const targetPath = `agents/${slug}/${relativePath}`; - if (relativePath === exportedInstructions.entryFile) { - files[targetPath] = buildMarkdown( - stripEmptyValues({ - name: agent.name, - title: agent.title ?? null, - reportsTo: reportsToSlug, - skills: desiredSkills.length > 0 ? desiredSkills : void 0 - }), - content - ); - } else { - files[targetPath] = content; - } - } - const extension2 = stripEmptyValues({ - role: agent.role !== "agent" ? agent.role : void 0, - icon: agent.icon ?? null, - capabilities: agent.capabilities ?? null, - adapter: { - type: agent.adapterType, - config: portableAdapterConfig - }, - runtime: portableRuntimeConfig, - permissions: portablePermissions, - budgetMonthlyCents: (agent.budgetMonthlyCents ?? 0) > 0 ? agent.budgetMonthlyCents : void 0, - metadata: agent.metadata ?? null - }); - if (isPlainRecord5(extension2) && agentEnvInputs.length > 0) { - extension2.inputs = { - env: buildEnvInputMap(agentEnvInputs) - }; - } - taskcoreAgentsOut[slug] = isPlainRecord5(extension2) ? extension2 : {}; - } - } - for (const project of selectedProjectRows) { - const slug = projectSlugById.get(project.id); - const projectPath = `projects/${slug}/PROJECT.md`; - const envInputsStart = envInputs.length; - const exportedEnvInputs = extractPortableProjectEnvInputs(slug, project.env, warnings); - envInputs.push(...exportedEnvInputs); - const projectEnvInputs = dedupeEnvInputs( - envInputs.slice(envInputsStart).filter((inputValue) => inputValue.projectSlug === slug) - ); - const portableWorkspaces = await buildPortableProjectWorkspaces(slug, project.workspaces, warnings); - projectWorkspaceKeyByProjectId.set(project.id, portableWorkspaces.workspaceKeyById); - files[projectPath] = buildMarkdown( - { - name: project.name, - description: project.description ?? null, - owner: project.leadAgentId ? idToSlug.get(project.leadAgentId) ?? null : null - }, - project.description ?? "" - ); - const extension2 = stripEmptyValues({ - leadAgentSlug: project.leadAgentId ? idToSlug.get(project.leadAgentId) ?? null : null, - targetDate: project.targetDate ?? null, - color: project.color ?? null, - status: project.status, - executionWorkspacePolicy: exportPortableProjectExecutionWorkspacePolicy( - slug, - project.executionWorkspacePolicy, - portableWorkspaces.workspaceKeyById, - warnings - ) ?? void 0, - workspaces: portableWorkspaces.extension - }); - if (isPlainRecord5(extension2) && projectEnvInputs.length > 0) { - extension2.inputs = { - env: buildEnvInputMap(projectEnvInputs) - }; - } - taskcoreProjectsOut[slug] = isPlainRecord5(extension2) ? extension2 : {}; - } - for (const issue2 of selectedIssueRows) { - const taskSlug = taskSlugByIssueId.get(issue2.id); - const projectSlug = issue2.projectId ? projectSlugById.get(issue2.projectId) ?? null : null; - const taskPath = `tasks/${taskSlug}/TASK.md`; - const assigneeSlug = issue2.assigneeAgentId ? idToSlug.get(issue2.assigneeAgentId) ?? null : null; - const projectWorkspaceKey = issue2.projectId && issue2.projectWorkspaceId ? projectWorkspaceKeyByProjectId.get(issue2.projectId)?.get(issue2.projectWorkspaceId) ?? null : null; - if (issue2.projectWorkspaceId && !projectWorkspaceKey) { - const aggregateKey = `${issue2.projectId ?? "no-project"}:${issue2.projectWorkspaceId}`; - const existing = unportableTaskWorkspaceRefs.get(aggregateKey); - if (existing) { - existing.taskSlugs.push(taskSlug); - } else { - unportableTaskWorkspaceRefs.set(aggregateKey, { - workspaceId: issue2.projectWorkspaceId, - taskSlugs: [taskSlug] - }); - } - } - files[taskPath] = buildMarkdown( - { - name: issue2.title, - project: projectSlug, - assignee: assigneeSlug - }, - issue2.description ?? "" - ); - const extension2 = stripEmptyValues({ - identifier: issue2.identifier, - status: issue2.status, - priority: issue2.priority, - labelIds: issue2.labelIds ?? void 0, - billingCode: issue2.billingCode ?? null, - projectWorkspaceKey: projectWorkspaceKey ?? void 0, - executionWorkspaceSettings: issue2.executionWorkspaceSettings ?? void 0, - assigneeAdapterOverrides: issue2.assigneeAdapterOverrides ?? void 0 - }); - taskcoreTasksOut[taskSlug] = isPlainRecord5(extension2) ? extension2 : {}; - } - for (const { workspaceId, taskSlugs } of unportableTaskWorkspaceRefs.values()) { - const preview = taskSlugs.slice(0, 4).join(", "); - const remainder = taskSlugs.length > 4 ? ` and ${taskSlugs.length - 4} more` : ""; - warnings.push(`Tasks ${preview}${remainder} reference workspace ${workspaceId}, but that workspace could not be exported portably.`); - } - for (const routine of selectedRoutineRows) { - const taskSlug = taskSlugByRoutineId.get(routine.id); - const projectSlug = routine.projectId ? projectSlugById.get(routine.projectId) ?? null : null; - const taskPath = `tasks/${taskSlug}/TASK.md`; - const assigneeSlug = routine.assigneeAgentId ? idToSlug.get(routine.assigneeAgentId) ?? null : null; - files[taskPath] = buildMarkdown( - { - name: routine.title, - project: projectSlug, - assignee: assigneeSlug, - recurring: true - }, - routine.description ?? "" - ); - const extension2 = stripEmptyValues({ - status: routine.status !== "active" ? routine.status : void 0, - priority: routine.priority !== "medium" ? routine.priority : void 0, - concurrencyPolicy: routine.concurrencyPolicy !== "coalesce_if_active" ? routine.concurrencyPolicy : void 0, - catchUpPolicy: routine.catchUpPolicy !== "skip_missed" ? routine.catchUpPolicy : void 0, - variables: (routine.variables ?? []).length > 0 ? routine.variables : void 0, - triggers: routine.triggers.map((trigger) => stripEmptyValues({ - kind: trigger.kind, - label: trigger.label ?? null, - enabled: trigger.enabled ? void 0 : false, - cronExpression: trigger.kind === "schedule" ? trigger.cronExpression ?? null : void 0, - timezone: trigger.kind === "schedule" ? trigger.timezone ?? null : void 0, - signingMode: trigger.kind === "webhook" && trigger.signingMode !== "bearer" ? trigger.signingMode ?? null : void 0, - replayWindowSec: trigger.kind === "webhook" && trigger.replayWindowSec !== 300 ? trigger.replayWindowSec ?? null : void 0 - })) - }); - taskcoreRoutinesOut[taskSlug] = isPlainRecord5(extension2) ? extension2 : {}; - } - const taskcoreExtensionPath = ".taskcore.yaml"; - const taskcoreAgents = Object.fromEntries( - Object.entries(taskcoreAgentsOut).filter(([, value]) => isPlainRecord5(value) && Object.keys(value).length > 0) - ); - const taskcoreProjects = Object.fromEntries( - Object.entries(taskcoreProjectsOut).filter(([, value]) => isPlainRecord5(value) && Object.keys(value).length > 0) - ); - const taskcoreTasks = Object.fromEntries( - Object.entries(taskcoreTasksOut).filter(([, value]) => isPlainRecord5(value) && Object.keys(value).length > 0) - ); - const taskcoreRoutines = Object.fromEntries( - Object.entries(taskcoreRoutinesOut).filter(([, value]) => isPlainRecord5(value) && Object.keys(value).length > 0) - ); - files[taskcoreExtensionPath] = buildYamlFile( - { - schema: "taskcore/v1", - company: stripEmptyValues({ - brandColor: company.brandColor ?? null, - logoPath: companyLogoPath, - requireBoardApprovalForNewAgents: company.requireBoardApprovalForNewAgents ? void 0 : false, - feedbackDataSharingEnabled: company.feedbackDataSharingEnabled ? true : void 0, - feedbackDataSharingConsentAt: company.feedbackDataSharingConsentAt?.toISOString() ?? null, - feedbackDataSharingConsentByUserId: company.feedbackDataSharingConsentByUserId ?? null, - feedbackDataSharingTermsVersion: company.feedbackDataSharingTermsVersion ?? null - }), - sidebar: stripEmptyValues(sidebarOrder), - agents: Object.keys(taskcoreAgents).length > 0 ? taskcoreAgents : void 0, - projects: Object.keys(taskcoreProjects).length > 0 ? taskcoreProjects : void 0, - tasks: Object.keys(taskcoreTasks).length > 0 ? taskcoreTasks : void 0, - routines: Object.keys(taskcoreRoutines).length > 0 ? taskcoreRoutines : void 0 - }, - { preserveEmptyStrings: true } - ); - let finalFiles = filterExportFiles(files, input.selectedFiles, taskcoreExtensionPath); - let resolved = buildManifestFromPackageFiles(finalFiles, { - sourceLabel: { - companyId: company.id, - companyName: company.name - } - }); - resolved.manifest.includes = { - company: resolved.manifest.company !== null, - agents: resolved.manifest.agents.length > 0, - projects: resolved.manifest.projects.length > 0, - issues: resolved.manifest.issues.length > 0, - skills: resolved.manifest.skills.length > 0 - }; - resolved.manifest.envInputs = dedupeEnvInputs(envInputs); - resolved.warnings.unshift(...warnings); - if (resolved.manifest.agents.length > 0) { - try { - const orgNodes = buildOrgTreeFromManifest(resolved.manifest.agents); - const pngBuffer = await renderOrgChartPng(orgNodes); - finalFiles["images/org-chart.png"] = bufferToPortableBinaryFile(pngBuffer, "image/png"); - } catch { - } - } - if (!input.selectedFiles || input.selectedFiles.some((entry) => normalizePortablePath2(entry) === "README.md")) { - finalFiles["README.md"] = generateReadme(resolved.manifest, { - companyName: company.name, - companyDescription: company.description ?? null - }); - } - resolved = buildManifestFromPackageFiles(finalFiles, { - sourceLabel: { - companyId: company.id, - companyName: company.name - } - }); - resolved.manifest.includes = { - company: resolved.manifest.company !== null, - agents: resolved.manifest.agents.length > 0, - projects: resolved.manifest.projects.length > 0, - issues: resolved.manifest.issues.length > 0, - skills: resolved.manifest.skills.length > 0 - }; - resolved.manifest.envInputs = dedupeEnvInputs(envInputs); - resolved.warnings.unshift(...warnings); - return { - rootPath, - manifest: resolved.manifest, - files: finalFiles, - warnings: resolved.warnings, - taskcoreExtensionPath - }; - } - async function previewExport(companyId, input) { - const previewInput = { - ...input, - include: { - ...input.include, - issues: input.include?.issues ?? Boolean(input.issues && input.issues.length > 0 || input.projectIssues && input.projectIssues.length > 0) ?? false - } - }; - if (previewInput.include && previewInput.include.issues === void 0) { - previewInput.include.issues = false; - } - const exported = await exportBundle(companyId, previewInput); - return { - ...exported, - fileInventory: Object.keys(exported.files).sort((left, right) => left.localeCompare(right)).map((filePath) => ({ - path: filePath, - kind: classifyPortableFileKind(filePath) - })), - counts: { - files: Object.keys(exported.files).length, - agents: exported.manifest.agents.length, - skills: exported.manifest.skills.length, - projects: exported.manifest.projects.length, - issues: exported.manifest.issues.length - } - }; - } - async function buildPreview(input, options) { - const mode = resolveImportMode(options); - const requestedInclude = normalizeInclude(input.include); - const source = applySelectedFilesToSource(await resolveSource(input.source), input.selectedFiles); - const manifest = source.manifest; - const include = { - company: requestedInclude.company && manifest.company !== null, - agents: requestedInclude.agents && manifest.agents.length > 0, - projects: requestedInclude.projects && manifest.projects.length > 0, - issues: requestedInclude.issues && manifest.issues.length > 0, - skills: requestedInclude.skills && manifest.skills.length > 0 - }; - const collisionStrategy = input.collisionStrategy ?? DEFAULT_COLLISION_STRATEGY; - if (mode === "agent_safe" && collisionStrategy === "replace") { - throw unprocessable("Safe import routes do not allow replace collision strategy."); - } - const warnings = [...source.warnings]; - const errors = []; - if (include.company && !manifest.company) { - errors.push("Manifest does not include company metadata."); - } - const selectedSlugs = include.agents ? input.agents && input.agents !== "all" ? Array.from(new Set(input.agents)) : manifest.agents.map((agent) => agent.slug) : []; - const selectedAgents = include.agents ? manifest.agents.filter((agent) => selectedSlugs.includes(agent.slug)) : []; - const selectedMissing = selectedSlugs.filter((slug) => !manifest.agents.some((agent) => agent.slug === slug)); - for (const missing of selectedMissing) { - errors.push(`Selected agent slug not found in manifest: ${missing}`); - } - if (include.agents && selectedAgents.length === 0) { - warnings.push("No agents selected for import."); - } - const availableSkillKeys = new Set(source.manifest.skills.map((skill) => skill.key)); - const availableSkillSlugs = /* @__PURE__ */ new Map(); - for (const skill of source.manifest.skills) { - const existing = availableSkillSlugs.get(skill.slug) ?? []; - existing.push(skill); - availableSkillSlugs.set(skill.slug, existing); - } - for (const agent of selectedAgents) { - const filePath = ensureMarkdownPath(agent.path); - const markdown = readPortableTextFile(source.files, filePath); - if (typeof markdown !== "string") { - errors.push(`Missing markdown file for agent ${agent.slug}: ${filePath}`); - continue; - } - const parsed = parseFrontmatterMarkdown2(markdown); - if (parsed.frontmatter.kind && parsed.frontmatter.kind !== "agent") { - warnings.push(`Agent markdown ${filePath} does not declare kind: agent in frontmatter.`); - } - for (const skillRef of agent.skills) { - const slugMatches = availableSkillSlugs.get(skillRef) ?? []; - if (!availableSkillKeys.has(skillRef) && slugMatches.length !== 1) { - warnings.push(`Agent ${agent.slug} references skill ${skillRef}, but that skill is not present in the package.`); - } - } - } - if (include.projects) { - for (const project of manifest.projects) { - const markdown = readPortableTextFile(source.files, ensureMarkdownPath(project.path)); - if (typeof markdown !== "string") { - errors.push(`Missing markdown file for project ${project.slug}: ${project.path}`); - continue; - } - const parsed = parseFrontmatterMarkdown2(markdown); - if (parsed.frontmatter.kind && parsed.frontmatter.kind !== "project") { - warnings.push(`Project markdown ${project.path} does not declare kind: project in frontmatter.`); - } - } - } - if (include.issues) { - const projectBySlug = new Map(manifest.projects.map((project) => [project.slug, project])); - for (const issue2 of manifest.issues) { - const markdown = readPortableTextFile(source.files, ensureMarkdownPath(issue2.path)); - if (typeof markdown !== "string") { - errors.push(`Missing markdown file for task ${issue2.slug}: ${issue2.path}`); - continue; - } - const parsed = parseFrontmatterMarkdown2(markdown); - if (parsed.frontmatter.kind && parsed.frontmatter.kind !== "task") { - warnings.push(`Task markdown ${issue2.path} does not declare kind: task in frontmatter.`); - } - if (issue2.projectWorkspaceKey) { - const project = issue2.projectSlug ? projectBySlug.get(issue2.projectSlug) ?? null : null; - if (!project) { - warnings.push(`Task ${issue2.slug} references workspace key ${issue2.projectWorkspaceKey}, but its project is not present in the package.`); - } else if (!project.workspaces.some((workspace) => workspace.key === issue2.projectWorkspaceKey)) { - warnings.push(`Task ${issue2.slug} references missing project workspace key ${issue2.projectWorkspaceKey}.`); - } - } - if (issue2.recurring) { - if (!issue2.projectSlug) { - errors.push(`Recurring task ${issue2.slug} must declare a project to import as a routine.`); - } - if (!issue2.assigneeAgentSlug) { - errors.push(`Recurring task ${issue2.slug} must declare an assignee to import as a routine.`); - } - const resolvedRoutine = resolvePortableRoutineDefinition(issue2, parsed.frontmatter.schedule); - warnings.push(...resolvedRoutine.warnings); - errors.push(...resolvedRoutine.errors); - } - } - } - for (const envInput of manifest.envInputs) { - if (envInput.portability === "system_dependent") { - const scope = envInput.agentSlug ? ` for agent ${envInput.agentSlug}` : envInput.projectSlug ? ` for project ${envInput.projectSlug}` : ""; - warnings.push(`Environment input ${envInput.key}${scope} is system-dependent and may need manual adjustment after import.`); - } - } - let targetCompanyId = null; - let targetCompanyName = null; - if (input.target.mode === "existing_company") { - const targetCompany = await companies2.getById(input.target.companyId); - if (!targetCompany) throw notFound("Target company not found"); - targetCompanyId = targetCompany.id; - targetCompanyName = targetCompany.name; - } - const agentPlans = []; - const existingSlugToAgent = /* @__PURE__ */ new Map(); - const existingSlugs = /* @__PURE__ */ new Set(); - const projectPlans = []; - const issuePlans = []; - const existingProjectSlugToProject = /* @__PURE__ */ new Map(); - const existingProjectSlugs = /* @__PURE__ */ new Set(); - if (input.target.mode === "existing_company") { - const existingAgents = await agents2.list(input.target.companyId); - for (const existing of existingAgents) { - const slug = normalizeAgentUrlKey(existing.name) ?? existing.id; - if (!existingSlugToAgent.has(slug)) existingSlugToAgent.set(slug, existing); - existingSlugs.add(slug); - } - const existingProjects = await projects2.list(input.target.companyId); - for (const existing of existingProjects) { - if (!existingProjectSlugToProject.has(existing.urlKey)) { - existingProjectSlugToProject.set(existing.urlKey, { id: existing.id, name: existing.name }); - } - existingProjectSlugs.add(existing.urlKey); - } - const existingSkills = await companySkills2.listFull(input.target.companyId); - const existingSkillKeys = new Set(existingSkills.map((skill) => skill.key)); - const existingSkillSlugs = new Set(existingSkills.map((skill) => normalizeSkillSlug3(skill.slug) ?? skill.slug)); - for (const skill of manifest.skills) { - const skillSlug = normalizeSkillSlug3(skill.slug) ?? skill.slug; - if (existingSkillKeys.has(skill.key) || existingSkillSlugs.has(skillSlug)) { - if (mode === "agent_safe") { - warnings.push(`Existing skill "${skill.slug}" matched during safe import and will ${collisionStrategy === "skip" ? "be skipped" : "be renamed"} instead of overwritten.`); - } else if (collisionStrategy === "replace") { - warnings.push(`Existing skill "${skill.slug}" (${skill.key}) will be overwritten by import.`); - } - } - } - } - for (const manifestAgent of selectedAgents) { - const existing = existingSlugToAgent.get(manifestAgent.slug) ?? null; - if (!existing) { - agentPlans.push({ - slug: manifestAgent.slug, - action: "create", - plannedName: manifestAgent.name, - existingAgentId: null, - reason: null - }); - continue; - } - if (mode === "board_full" && collisionStrategy === "replace") { - agentPlans.push({ - slug: manifestAgent.slug, - action: "update", - plannedName: existing.name, - existingAgentId: existing.id, - reason: "Existing slug matched; replace strategy." - }); - continue; - } - if (collisionStrategy === "skip") { - agentPlans.push({ - slug: manifestAgent.slug, - action: "skip", - plannedName: existing.name, - existingAgentId: existing.id, - reason: "Existing slug matched; skip strategy." - }); - continue; - } - const renamed = uniqueNameBySlug(manifestAgent.name, existingSlugs); - existingSlugs.add(normalizeAgentUrlKey(renamed) ?? manifestAgent.slug); - agentPlans.push({ - slug: manifestAgent.slug, - action: "create", - plannedName: renamed, - existingAgentId: existing.id, - reason: "Existing slug matched; rename strategy." - }); - } - if (include.projects) { - for (const manifestProject of manifest.projects) { - const existing = existingProjectSlugToProject.get(manifestProject.slug) ?? null; - if (!existing) { - projectPlans.push({ - slug: manifestProject.slug, - action: "create", - plannedName: manifestProject.name, - existingProjectId: null, - reason: null - }); - continue; - } - if (mode === "board_full" && collisionStrategy === "replace") { - projectPlans.push({ - slug: manifestProject.slug, - action: "update", - plannedName: existing.name, - existingProjectId: existing.id, - reason: "Existing slug matched; replace strategy." - }); - continue; - } - if (collisionStrategy === "skip") { - projectPlans.push({ - slug: manifestProject.slug, - action: "skip", - plannedName: existing.name, - existingProjectId: existing.id, - reason: "Existing slug matched; skip strategy." - }); - continue; - } - const renamed = uniqueProjectName(manifestProject.name, existingProjectSlugs); - existingProjectSlugs.add(deriveProjectUrlKey(renamed, renamed)); - projectPlans.push({ - slug: manifestProject.slug, - action: "create", - plannedName: renamed, - existingProjectId: existing.id, - reason: "Existing slug matched; rename strategy." - }); - } - } - if (input.nameOverrides) { - for (const ap of agentPlans) { - const override = input.nameOverrides[ap.slug]; - if (override) { - ap.plannedName = override; - } - } - for (const pp of projectPlans) { - const override = input.nameOverrides[pp.slug]; - if (override) { - pp.plannedName = override; - } - } - for (const ip of issuePlans) { - const override = input.nameOverrides[ip.slug]; - if (override) { - ip.plannedTitle = override; - } - } - } - for (const ap of agentPlans) { - if (ap.action === "update") { - warnings.push(`Existing agent "${ap.plannedName}" (${ap.slug}) will be overwritten by import.`); - } - } - for (const pp of projectPlans) { - if (pp.action === "update") { - warnings.push(`Existing project "${pp.plannedName}" (${pp.slug}) will be overwritten by import.`); - } - } - if (include.issues) { - for (const manifestIssue of manifest.issues) { - issuePlans.push({ - slug: manifestIssue.slug, - action: "create", - plannedTitle: manifestIssue.title, - reason: manifestIssue.recurring ? "Recurring task will be imported as a routine." : null - }); - } - } - const preview = { - include, - targetCompanyId, - targetCompanyName, - collisionStrategy, - selectedAgentSlugs: selectedAgents.map((agent) => agent.slug), - plan: { - companyAction: input.target.mode === "new_company" ? "create" : include.company && mode === "board_full" ? "update" : "none", - agentPlans, - projectPlans, - issuePlans - }, - manifest, - files: source.files, - envInputs: manifest.envInputs ?? [], - warnings, - errors - }; - return { - preview, - source, - include, - collisionStrategy, - selectedAgents - }; - } - async function previewImport(input, options) { - const plan = await buildPreview(input, options); - return plan.preview; - } - async function importBundle(input, actorUserId, options) { - const mode = resolveImportMode(options); - const plan = await buildPreview(input, options); - if (plan.preview.errors.length > 0) { - throw unprocessable(`Import preview has errors: ${plan.preview.errors.join("; ")}`); - } - if (mode === "agent_safe" && (plan.preview.plan.companyAction === "update" || plan.preview.plan.agentPlans.some((entry) => entry.action === "update") || plan.preview.plan.projectPlans.some((entry) => entry.action === "update"))) { - throw unprocessable("Safe import routes only allow create or skip actions."); - } - const sourceManifest = plan.source.manifest; - const warnings = [...plan.preview.warnings]; - const include = plan.include; - let targetCompany = null; - let companyAction = "unchanged"; - if (input.target.mode === "new_company") { - if (mode === "agent_safe" && !options?.sourceCompanyId) { - throw unprocessable("Safe new-company imports require a source company context."); - } - if (mode === "agent_safe" && options?.sourceCompanyId) { - const sourceMemberships = await access.listActiveUserMemberships(options.sourceCompanyId); - if (sourceMemberships.length === 0) { - throw unprocessable("Safe new-company import requires at least one active user membership on the source company."); - } - } - const companyName = asString14(input.target.newCompanyName) ?? sourceManifest.company?.name ?? sourceManifest.source?.companyName ?? "Imported Company"; - const created = await companies2.create({ - name: companyName, - description: include.company ? sourceManifest.company?.description ?? null : null, - brandColor: include.company ? sourceManifest.company?.brandColor ?? null : null, - requireBoardApprovalForNewAgents: include.company ? sourceManifest.company?.requireBoardApprovalForNewAgents ?? true : true, - feedbackDataSharingEnabled: include.company ? sourceManifest.company?.feedbackDataSharingEnabled ?? false : false, - feedbackDataSharingConsentAt: include.company && sourceManifest.company?.feedbackDataSharingConsentAt ? new Date(sourceManifest.company.feedbackDataSharingConsentAt) : null, - feedbackDataSharingConsentByUserId: include.company ? sourceManifest.company?.feedbackDataSharingConsentByUserId ?? null : null, - feedbackDataSharingTermsVersion: include.company ? sourceManifest.company?.feedbackDataSharingTermsVersion ?? null : null - }); - if (mode === "agent_safe" && options?.sourceCompanyId) { - await access.copyActiveUserMemberships(options.sourceCompanyId, created.id); - } else { - await access.ensureMembership(created.id, "user", actorUserId ?? "board", "owner", "active"); - } - targetCompany = created; - companyAction = "created"; - } else { - targetCompany = await companies2.getById(input.target.companyId); - if (!targetCompany) throw notFound("Target company not found"); - if (include.company && sourceManifest.company && mode === "board_full") { - const updated = await companies2.update(targetCompany.id, { - name: sourceManifest.company.name, - description: sourceManifest.company.description, - brandColor: sourceManifest.company.brandColor, - requireBoardApprovalForNewAgents: sourceManifest.company.requireBoardApprovalForNewAgents, - feedbackDataSharingEnabled: sourceManifest.company.feedbackDataSharingEnabled, - feedbackDataSharingConsentAt: sourceManifest.company.feedbackDataSharingConsentAt ? new Date(sourceManifest.company.feedbackDataSharingConsentAt) : null, - feedbackDataSharingConsentByUserId: sourceManifest.company.feedbackDataSharingConsentByUserId, - feedbackDataSharingTermsVersion: sourceManifest.company.feedbackDataSharingTermsVersion - }); - targetCompany = updated ?? targetCompany; - companyAction = "updated"; - } - } - if (!targetCompany) throw notFound("Target company not found"); - if (include.company) { - const logoPath = sourceManifest.company?.logoPath ?? null; - if (!logoPath) { - const cleared = await companies2.update(targetCompany.id, { logoAssetId: null }); - targetCompany = cleared ?? targetCompany; - } else { - const logoFile = plan.source.files[logoPath]; - if (!logoFile) { - warnings.push(`Skipped company logo import because ${logoPath} is missing from the package.`); - } else if (!storage) { - warnings.push("Skipped company logo import because storage is unavailable."); - } else { - const contentType = isPortableBinaryFile(logoFile) ? logoFile.contentType ?? inferContentTypeFromPath(logoPath) : inferContentTypeFromPath(logoPath); - if (!contentType || !COMPANY_LOGO_CONTENT_TYPE_EXTENSIONS[contentType]) { - warnings.push(`Skipped company logo import for ${logoPath} because the file type is unsupported.`); - } else { - try { - const body = portableFileToBuffer(logoFile, logoPath); - const stored = await storage.putFile({ - companyId: targetCompany.id, - namespace: "assets/companies", - originalFilename: path40.posix.basename(logoPath), - contentType, - body - }); - const createdAsset = await assetRecords.create(targetCompany.id, { - provider: stored.provider, - objectKey: stored.objectKey, - contentType: stored.contentType, - byteSize: stored.byteSize, - sha256: stored.sha256, - originalFilename: stored.originalFilename, - createdByAgentId: null, - createdByUserId: actorUserId ?? null - }); - const updated = await companies2.update(targetCompany.id, { - logoAssetId: createdAsset.id - }); - targetCompany = updated ?? targetCompany; - } catch (err) { - warnings.push(`Failed to import company logo ${logoPath}: ${err instanceof Error ? err.message : String(err)}`); - } - } - } - } - } - const resultAgents = []; - const resultProjects = []; - const importedSlugToAgentId = /* @__PURE__ */ new Map(); - const existingSlugToAgentId = /* @__PURE__ */ new Map(); - const existingAgents = await agents2.list(targetCompany.id); - for (const existing of existingAgents) { - existingSlugToAgentId.set(normalizeAgentUrlKey(existing.name) ?? existing.id, existing.id); - } - const importedSlugToProjectId = /* @__PURE__ */ new Map(); - const importedProjectWorkspaceIdByProjectSlug = /* @__PURE__ */ new Map(); - const existingProjectSlugToId = /* @__PURE__ */ new Map(); - const existingProjects = await projects2.list(targetCompany.id); - for (const existing of existingProjects) { - existingProjectSlugToId.set(existing.urlKey, existing.id); - } - const importedSkills = include.skills || include.agents ? await companySkills2.importPackageFiles(targetCompany.id, pickTextFiles(plan.source.files), { - onConflict: resolveSkillConflictStrategy(mode, plan.collisionStrategy) - }) : []; - const desiredSkillRefMap = /* @__PURE__ */ new Map(); - for (const importedSkill of importedSkills) { - desiredSkillRefMap.set(importedSkill.originalKey, importedSkill.skill.key); - desiredSkillRefMap.set(importedSkill.originalSlug, importedSkill.skill.key); - if (importedSkill.action === "skipped") { - warnings.push(`Skipped skill ${importedSkill.originalSlug}; existing skill ${importedSkill.skill.slug} was kept.`); - } else if (importedSkill.originalKey !== importedSkill.skill.key) { - warnings.push(`Imported skill ${importedSkill.originalSlug} as ${importedSkill.skill.slug} to avoid overwriting an existing skill.`); - } - } - if (include.agents) { - for (const planAgent of plan.preview.plan.agentPlans) { - const manifestAgent = plan.selectedAgents.find((agent) => agent.slug === planAgent.slug); - if (!manifestAgent) continue; - if (planAgent.action === "skip") { - resultAgents.push({ - slug: planAgent.slug, - id: planAgent.existingAgentId, - action: "skipped", - name: planAgent.plannedName, - reason: planAgent.reason - }); - continue; - } - const bundlePrefix = `agents/${manifestAgent.slug}/`; - const bundleFiles = Object.fromEntries( - Object.entries(plan.source.files).filter(([filePath]) => filePath.startsWith(bundlePrefix)).flatMap(([filePath, content]) => typeof content === "string" ? [[normalizePortablePath2(filePath.slice(bundlePrefix.length)), content]] : []) - ); - const markdownRaw = bundleFiles["AGENTS.md"] ?? readPortableTextFile(plan.source.files, manifestAgent.path); - const entryRelativePath = normalizePortablePath2(manifestAgent.path).startsWith(bundlePrefix) ? normalizePortablePath2(manifestAgent.path).slice(bundlePrefix.length) : "AGENTS.md"; - if (typeof markdownRaw === "string") { - const importedInstructionsBody = parseFrontmatterMarkdown2(markdownRaw).body; - bundleFiles[entryRelativePath] = importedInstructionsBody; - if (entryRelativePath !== "AGENTS.md") { - bundleFiles["AGENTS.md"] = importedInstructionsBody; - } - } - const fallbackPromptTemplate = asString14(manifestAgent.adapterConfig.promptTemplate) || ""; - if (!markdownRaw && fallbackPromptTemplate) { - bundleFiles["AGENTS.md"] = fallbackPromptTemplate; - } - if (!markdownRaw && !fallbackPromptTemplate) { - warnings.push(`Missing AGENTS markdown for ${manifestAgent.slug}; imported with an empty managed bundle.`); - } - const adapterOverride = input.adapterOverrides?.[planAgent.slug]; - const effectiveAdapterType = adapterOverride?.adapterType ?? manifestAgent.adapterType; - const baseAdapterConfig = adapterOverride?.adapterConfig ? { ...adapterOverride.adapterConfig } : { ...manifestAgent.adapterConfig }; - const desiredSkills = (manifestAgent.skills ?? []).map((skillRef) => desiredSkillRefMap.get(skillRef) ?? skillRef); - const adapterConfigWithSkills = writeTaskcoreSkillSyncPreference( - baseAdapterConfig, - desiredSkills - ); - delete adapterConfigWithSkills.promptTemplate; - delete adapterConfigWithSkills.bootstrapPromptTemplate; - delete adapterConfigWithSkills.instructionsFilePath; - delete adapterConfigWithSkills.instructionsBundleMode; - delete adapterConfigWithSkills.instructionsRootPath; - delete adapterConfigWithSkills.instructionsEntryFile; - const patch = { - name: planAgent.plannedName, - role: manifestAgent.role, - title: manifestAgent.title, - icon: manifestAgent.icon, - capabilities: manifestAgent.capabilities, - reportsTo: null, - adapterType: effectiveAdapterType, - adapterConfig: adapterConfigWithSkills, - runtimeConfig: disableImportedTimerHeartbeat(manifestAgent.runtimeConfig), - budgetMonthlyCents: manifestAgent.budgetMonthlyCents, - permissions: manifestAgent.permissions, - metadata: manifestAgent.metadata - }; - if (planAgent.action === "update" && planAgent.existingAgentId) { - let updated = await agents2.update(planAgent.existingAgentId, patch); - if (!updated) { - warnings.push(`Skipped update for missing agent ${planAgent.existingAgentId}.`); - resultAgents.push({ - slug: planAgent.slug, - id: null, - action: "skipped", - name: planAgent.plannedName, - reason: "Existing target agent not found." - }); - continue; - } - try { - const materialized = await instructions.materializeManagedBundle(updated, bundleFiles, { - clearLegacyPromptTemplate: true, - replaceExisting: true - }); - updated = await agents2.update(updated.id, { adapterConfig: materialized.adapterConfig }) ?? updated; - } catch (err) { - warnings.push(`Failed to materialize instructions bundle for ${manifestAgent.slug}: ${err instanceof Error ? err.message : String(err)}`); - } - importedSlugToAgentId.set(planAgent.slug, updated.id); - existingSlugToAgentId.set(normalizeAgentUrlKey(updated.name) ?? updated.id, updated.id); - resultAgents.push({ - slug: planAgent.slug, - id: updated.id, - action: "updated", - name: updated.name, - reason: planAgent.reason - }); - continue; - } - let created = await agents2.create(targetCompany.id, patch); - await access.ensureMembership(targetCompany.id, "agent", created.id, "member", "active"); - await access.setPrincipalPermission( - targetCompany.id, - "agent", - created.id, - "tasks:assign", - true, - actorUserId ?? null - ); - try { - const materialized = await instructions.materializeManagedBundle(created, bundleFiles, { - clearLegacyPromptTemplate: true, - replaceExisting: true - }); - created = await agents2.update(created.id, { adapterConfig: materialized.adapterConfig }) ?? created; - } catch (err) { - warnings.push(`Failed to materialize instructions bundle for ${manifestAgent.slug}: ${err instanceof Error ? err.message : String(err)}`); - } - importedSlugToAgentId.set(planAgent.slug, created.id); - existingSlugToAgentId.set(normalizeAgentUrlKey(created.name) ?? created.id, created.id); - resultAgents.push({ - slug: planAgent.slug, - id: created.id, - action: "created", - name: created.name, - reason: planAgent.reason - }); - } - for (const manifestAgent of plan.selectedAgents) { - const agentId = importedSlugToAgentId.get(manifestAgent.slug); - if (!agentId) continue; - const managerSlug = manifestAgent.reportsToSlug; - if (!managerSlug) continue; - const managerId = importedSlugToAgentId.get(managerSlug) ?? existingSlugToAgentId.get(managerSlug) ?? null; - if (!managerId || managerId === agentId) continue; - try { - await agents2.update(agentId, { reportsTo: managerId }); - } catch { - warnings.push(`Could not assign manager ${managerSlug} for imported agent ${manifestAgent.slug}.`); - } - } - } - if (include.projects) { - for (const planProject of plan.preview.plan.projectPlans) { - const manifestProject = sourceManifest.projects.find((project) => project.slug === planProject.slug); - if (!manifestProject) continue; - if (planProject.action === "skip") { - resultProjects.push({ - slug: planProject.slug, - id: planProject.existingProjectId, - action: "skipped", - name: planProject.plannedName, - reason: planProject.reason - }); - continue; - } - const projectLeadAgentId = manifestProject.leadAgentSlug ? importedSlugToAgentId.get(manifestProject.leadAgentSlug) ?? existingSlugToAgentId.get(manifestProject.leadAgentSlug) ?? null : null; - const projectWorkspaceIdByKey = /* @__PURE__ */ new Map(); - const projectPatch = { - name: planProject.plannedName, - description: manifestProject.description, - leadAgentId: projectLeadAgentId, - targetDate: manifestProject.targetDate, - color: manifestProject.color, - status: manifestProject.status && PROJECT_STATUSES.includes(manifestProject.status) ? manifestProject.status : "backlog", - env: manifestProject.env, - executionWorkspacePolicy: stripPortableProjectExecutionWorkspaceRefs(manifestProject.executionWorkspacePolicy) - }; - let projectId = null; - if (planProject.action === "update" && planProject.existingProjectId) { - const updated = await projects2.update(planProject.existingProjectId, projectPatch); - if (!updated) { - warnings.push(`Skipped update for missing project ${planProject.existingProjectId}.`); - resultProjects.push({ - slug: planProject.slug, - id: null, - action: "skipped", - name: planProject.plannedName, - reason: "Existing target project not found." - }); - continue; - } - projectId = updated.id; - importedSlugToProjectId.set(planProject.slug, updated.id); - existingProjectSlugToId.set(updated.urlKey, updated.id); - resultProjects.push({ - slug: planProject.slug, - id: updated.id, - action: "updated", - name: updated.name, - reason: planProject.reason - }); - } else { - const created = await projects2.create(targetCompany.id, projectPatch); - projectId = created.id; - importedSlugToProjectId.set(planProject.slug, created.id); - existingProjectSlugToId.set(created.urlKey, created.id); - resultProjects.push({ - slug: planProject.slug, - id: created.id, - action: "created", - name: created.name, - reason: planProject.reason - }); - } - if (!projectId) continue; - for (const workspace of manifestProject.workspaces) { - const createdWorkspace = await projects2.createWorkspace(projectId, { - name: workspace.name, - sourceType: workspace.sourceType ?? void 0, - repoUrl: workspace.repoUrl ?? void 0, - repoRef: workspace.repoRef ?? void 0, - defaultRef: workspace.defaultRef ?? void 0, - visibility: workspace.visibility ?? void 0, - setupCommand: workspace.setupCommand ?? void 0, - cleanupCommand: workspace.cleanupCommand ?? void 0, - metadata: workspace.metadata ?? void 0, - isPrimary: workspace.isPrimary - }); - if (!createdWorkspace) { - warnings.push(`Project ${planProject.slug} workspace ${workspace.key} could not be created during import.`); - continue; - } - projectWorkspaceIdByKey.set(workspace.key, createdWorkspace.id); - } - importedProjectWorkspaceIdByProjectSlug.set(planProject.slug, projectWorkspaceIdByKey); - const hydratedProjectExecutionWorkspacePolicy = importPortableProjectExecutionWorkspacePolicy( - planProject.slug, - manifestProject.executionWorkspacePolicy, - projectWorkspaceIdByKey, - warnings - ); - if (hydratedProjectExecutionWorkspacePolicy) { - await projects2.update(projectId, { - executionWorkspacePolicy: hydratedProjectExecutionWorkspacePolicy - }); - } - } - } - if (include.issues) { - const routines2 = routineService(db); - for (const manifestIssue of sourceManifest.issues) { - const markdownRaw = readPortableTextFile(plan.source.files, manifestIssue.path); - const parsed = markdownRaw ? parseFrontmatterMarkdown2(markdownRaw) : null; - const description = parsed?.body || manifestIssue.description || null; - const assigneeAgentId = manifestIssue.assigneeAgentSlug ? importedSlugToAgentId.get(manifestIssue.assigneeAgentSlug) ?? existingSlugToAgentId.get(manifestIssue.assigneeAgentSlug) ?? null : null; - const projectId = manifestIssue.projectSlug ? importedSlugToProjectId.get(manifestIssue.projectSlug) ?? existingProjectSlugToId.get(manifestIssue.projectSlug) ?? null : null; - const projectWorkspaceId = manifestIssue.projectSlug && manifestIssue.projectWorkspaceKey ? importedProjectWorkspaceIdByProjectSlug.get(manifestIssue.projectSlug)?.get(manifestIssue.projectWorkspaceKey) ?? null : null; - if (manifestIssue.projectWorkspaceKey && !projectWorkspaceId) { - warnings.push(`Task ${manifestIssue.slug} references workspace key ${manifestIssue.projectWorkspaceKey}, but that workspace was not imported.`); - } - if (manifestIssue.recurring) { - if (!projectId || !assigneeAgentId) { - throw unprocessable(`Recurring task ${manifestIssue.slug} is missing the project or assignee required to create a routine.`); - } - const resolvedRoutine = resolvePortableRoutineDefinition(manifestIssue, parsed?.frontmatter.schedule); - if (resolvedRoutine.errors.length > 0) { - throw unprocessable(`Recurring task ${manifestIssue.slug} could not be imported as a routine: ${resolvedRoutine.errors.join("; ")}`); - } - warnings.push(...resolvedRoutine.warnings); - const routineDefinition = resolvedRoutine.routine ?? { - concurrencyPolicy: null, - catchUpPolicy: null, - variables: null, - triggers: [] - }; - const createdRoutine = await routines2.create(targetCompany.id, { - projectId, - goalId: null, - parentIssueId: null, - title: manifestIssue.title, - description, - assigneeAgentId, - priority: manifestIssue.priority && ISSUE_PRIORITIES.includes(manifestIssue.priority) ? manifestIssue.priority : "medium", - status: manifestIssue.status && ROUTINE_STATUSES.includes(manifestIssue.status) ? manifestIssue.status : "active", - concurrencyPolicy: routineDefinition.concurrencyPolicy && ROUTINE_CONCURRENCY_POLICIES.includes(routineDefinition.concurrencyPolicy) ? routineDefinition.concurrencyPolicy : "coalesce_if_active", - catchUpPolicy: routineDefinition.catchUpPolicy && ROUTINE_CATCH_UP_POLICIES.includes(routineDefinition.catchUpPolicy) ? routineDefinition.catchUpPolicy : "skip_missed", - variables: routineDefinition.variables ?? [] - }, { - agentId: null, - userId: actorUserId ?? null - }); - for (const trigger of routineDefinition.triggers) { - if (trigger.kind === "schedule") { - await routines2.createTrigger(createdRoutine.id, { - kind: "schedule", - label: trigger.label, - enabled: trigger.enabled, - cronExpression: trigger.cronExpression, - timezone: trigger.timezone - }, { - agentId: null, - userId: actorUserId ?? null - }); - continue; - } - if (trigger.kind === "webhook") { - await routines2.createTrigger(createdRoutine.id, { - kind: "webhook", - label: trigger.label, - enabled: trigger.enabled, - signingMode: trigger.signingMode && ROUTINE_TRIGGER_SIGNING_MODES.includes(trigger.signingMode) ? trigger.signingMode : "bearer", - replayWindowSec: trigger.replayWindowSec ?? 300 - }, { - agentId: null, - userId: actorUserId ?? null - }); - continue; - } - await routines2.createTrigger(createdRoutine.id, { - kind: "api", - label: trigger.label, - enabled: trigger.enabled - }, { - agentId: null, - userId: actorUserId ?? null - }); - } - continue; - } - await issues2.create(targetCompany.id, { - projectId, - projectWorkspaceId, - title: manifestIssue.title, - description, - assigneeAgentId, - status: manifestIssue.status && ISSUE_STATUSES.includes(manifestIssue.status) ? manifestIssue.status : "backlog", - priority: manifestIssue.priority && ISSUE_PRIORITIES.includes(manifestIssue.priority) ? manifestIssue.priority : "medium", - billingCode: manifestIssue.billingCode, - assigneeAdapterOverrides: manifestIssue.assigneeAdapterOverrides, - executionWorkspaceSettings: manifestIssue.executionWorkspaceSettings, - labelIds: manifestIssue.labelIds ?? [] - }); - } - } - return { - company: { - id: targetCompany.id, - name: targetCompany.name, - action: companyAction - }, - agents: resultAgents, - projects: resultProjects, - envInputs: sourceManifest.envInputs ?? [], - warnings - }; - } - return { - exportBundle, - previewExport, - previewImport, - importBundle - }; -} - -// server/src/services/work-products.ts -init_drizzle_orm(); -init_src2(); -function toIssueWorkProduct(row) { - return { - id: row.id, - companyId: row.companyId, - projectId: row.projectId ?? null, - issueId: row.issueId, - executionWorkspaceId: row.executionWorkspaceId ?? null, - runtimeServiceId: row.runtimeServiceId ?? null, - type: row.type, - provider: row.provider, - externalId: row.externalId ?? null, - title: row.title, - url: row.url ?? null, - status: row.status, - reviewState: row.reviewState, - isPrimary: row.isPrimary, - healthStatus: row.healthStatus, - summary: row.summary ?? null, - metadata: row.metadata ?? null, - createdByRunId: row.createdByRunId ?? null, - createdAt: row.createdAt, - updatedAt: row.updatedAt - }; -} -function workProductService(db) { - return { - listForIssue: async (issueId) => { - const rows = await db.select().from(issueWorkProducts).where(eq(issueWorkProducts.issueId, issueId)).orderBy(desc(issueWorkProducts.isPrimary), desc(issueWorkProducts.updatedAt)); - return rows.map(toIssueWorkProduct); - }, - getById: async (id) => { - const row = await db.select().from(issueWorkProducts).where(eq(issueWorkProducts.id, id)).then((rows) => rows[0] ?? null); - return row ? toIssueWorkProduct(row) : null; - }, - createForIssue: async (issueId, companyId, data2) => { - const row = await db.transaction(async (tx) => { - if (data2.isPrimary) { - await tx.update(issueWorkProducts).set({ isPrimary: false, updatedAt: /* @__PURE__ */ new Date() }).where( - and( - eq(issueWorkProducts.companyId, companyId), - eq(issueWorkProducts.issueId, issueId), - eq(issueWorkProducts.type, data2.type) - ) - ); - } - return await tx.insert(issueWorkProducts).values({ - ...data2, - companyId, - issueId - }).returning().then((rows) => rows[0] ?? null); - }); - return row ? toIssueWorkProduct(row) : null; - }, - update: async (id, patch) => { - const row = await db.transaction(async (tx) => { - const existing = await tx.select().from(issueWorkProducts).where(eq(issueWorkProducts.id, id)).then((rows) => rows[0] ?? null); - if (!existing) return null; - if (patch.isPrimary === true) { - await tx.update(issueWorkProducts).set({ isPrimary: false, updatedAt: /* @__PURE__ */ new Date() }).where( - and( - eq(issueWorkProducts.companyId, existing.companyId), - eq(issueWorkProducts.issueId, existing.issueId), - eq(issueWorkProducts.type, existing.type) - ) - ); - } - return await tx.update(issueWorkProducts).set({ ...patch, updatedAt: /* @__PURE__ */ new Date() }).where(eq(issueWorkProducts.id, id)).returning().then((rows) => rows[0] ?? null); - }); - return row ? toIssueWorkProduct(row) : null; - }, - remove: async (id) => { - const row = await db.delete(issueWorkProducts).where(eq(issueWorkProducts.id, id)).returning().then((rows) => rows[0] ?? null); - return row ? toIssueWorkProduct(row) : null; - } - }; -} - -// server/src/config.ts -var import_dotenv = __toESM(require_main(), 1); -import { execFileSync } from "node:child_process"; -import { existsSync as existsSync4, realpathSync as realpathSync2 } from "node:fs"; -import { resolve } from "node:path"; - -// server/src/worktree-config.ts -import fs33 from "node:fs"; -import os22 from "node:os"; -import path41 from "node:path"; -function nonEmpty5(value) { - return typeof value === "string" && value.trim().length > 0 ? value.trim() : null; -} -function expandHomePrefix2(value) { - if (value === "~") return os22.homedir(); - if (value.startsWith("~/")) return path41.resolve(os22.homedir(), value.slice(2)); - return value; -} -function resolveHomeAwarePath2(value) { - return path41.resolve(expandHomePrefix2(value)); -} -function sanitizeWorktreeInstanceId(rawValue) { - const trimmed = rawValue.trim().toLowerCase(); - const normalized = trimmed.replace(/[^a-z0-9_-]+/g, "-").replace(/-+/g, "-").replace(/^[-_]+|[-_]+$/g, ""); - return normalized || "worktree"; -} -function isLoopbackHost4(hostname3) { - const value = hostname3.trim().toLowerCase(); - return value === "127.0.0.1" || value === "localhost" || value === "::1"; -} -function rewriteLocalUrlPort(rawUrl, port) { - if (!rawUrl) return void 0; - try { - const parsed = new URL(rawUrl); - if (!isLoopbackHost4(parsed.hostname)) return rawUrl; - parsed.port = String(port); - return parsed.toString(); - } catch { - return rawUrl; - } -} -function parseEnvFile(contents) { - const entries2 = {}; - for (const rawLine of contents.split(/\r?\n/)) { - const line3 = rawLine.trim(); - if (!line3 || line3.startsWith("#")) continue; - const match = rawLine.match(/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)\s*$/); - if (!match) continue; - const [, key, rawValue] = match; - const value = rawValue.trim(); - if (!value) { - entries2[key] = ""; - continue; - } - if (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'")) { - entries2[key] = value.slice(1, -1); - continue; - } - entries2[key] = value.replace(/\s+#.*$/, "").trim(); - } - return entries2; -} -function readEnvEntries(envPath) { - if (!fs33.existsSync(envPath)) return {}; - return parseEnvFile(fs33.readFileSync(envPath, "utf8")); -} -function formatEnvEntries(entries2) { - return [ - "# Taskcore environment variables", - "# Generated by Taskcore worktree repair", - ...Object.entries(entries2).map(([key, value]) => `${key}=${JSON.stringify(value)}`), - "" - ].join("\n"); -} -function isPathInside(candidatePath, rootPath) { - const candidate = path41.resolve(candidatePath); - const root = path41.resolve(rootPath); - return candidate === root || candidate.startsWith(`${root}${path41.sep}`); -} -function resolveWorktreeRuntimeContext(env2, overrideConfigPath) { - if (env2.TASKCORE_IN_WORKTREE !== "true") return null; - const configPath = resolveTaskcoreConfigPath(overrideConfigPath); - const envPath = resolveTaskcoreEnvPath(configPath); - const worktreeRoot = path41.resolve(path41.dirname(configPath), ".."); - const worktreeName = nonEmpty5(env2.TASKCORE_WORKTREE_NAME) ?? path41.basename(worktreeRoot); - const instanceId = nonEmpty5(env2.TASKCORE_INSTANCE_ID) ?? sanitizeWorktreeInstanceId(worktreeName); - const homeDir = resolveHomeAwarePath2( - nonEmpty5(env2.TASKCORE_HOME) ?? nonEmpty5(env2.TASKCORE_WORKTREES_DIR) ?? "~/.taskcore-worktrees" - ); - const instanceRoot = path41.resolve(homeDir, "instances", instanceId); - return { - configPath, - envPath, - worktreeName, - instanceId, - homeDir, - instanceRoot, - contextPath: path41.resolve(homeDir, "context.json"), - embeddedPostgresDataDir: path41.resolve(instanceRoot, "db"), - backupDir: path41.resolve(instanceRoot, "data", "backups"), - logDir: path41.resolve(instanceRoot, "logs"), - storageDir: path41.resolve(instanceRoot, "data", "storage"), - secretsKeyFilePath: path41.resolve(instanceRoot, "secrets", "master.key") - }; -} -function writeConfigFile(configPath, config3) { - fs33.mkdirSync(path41.dirname(configPath), { recursive: true }); - fs33.writeFileSync(configPath, JSON.stringify(config3, null, 2) + "\n", { mode: 384 }); -} -function resolveRepoManagedWorktreesRoot(worktreeRoot) { - const normalized = path41.resolve(worktreeRoot); - const marker = `${path41.sep}.taskcore${path41.sep}worktrees${path41.sep}`; - const index2 = normalized.indexOf(marker); - if (index2 === -1) return null; - const repoRoot = normalized.slice(0, index2); - return path41.resolve(repoRoot, ".taskcore", "worktrees"); -} -function collectSiblingWorktreePorts(context) { - const serverPorts = /* @__PURE__ */ new Set(); - const databasePorts = /* @__PURE__ */ new Set(); - const siblingConfigPaths = /* @__PURE__ */ new Set(); - const instancesDir = path41.resolve(context.homeDir, "instances"); - if (fs33.existsSync(instancesDir)) { - for (const entry of fs33.readdirSync(instancesDir, { withFileTypes: true })) { - if (!entry.isDirectory() || entry.name === context.instanceId) continue; - const siblingConfigPath = path41.resolve(instancesDir, entry.name, "config.json"); - if (fs33.existsSync(siblingConfigPath)) { - siblingConfigPaths.add(siblingConfigPath); - } - } - } - const repoManagedWorktreesRoot = resolveRepoManagedWorktreesRoot(path41.dirname(context.configPath)); - if (repoManagedWorktreesRoot && fs33.existsSync(repoManagedWorktreesRoot)) { - for (const entry of fs33.readdirSync(repoManagedWorktreesRoot, { withFileTypes: true })) { - if (!entry.isDirectory()) continue; - const siblingConfigPath = path41.resolve(repoManagedWorktreesRoot, entry.name, ".taskcore", "config.json"); - if (path41.resolve(siblingConfigPath) === path41.resolve(context.configPath)) continue; - if (fs33.existsSync(siblingConfigPath)) { - siblingConfigPaths.add(siblingConfigPath); - } - } - } - for (const siblingConfigPath of siblingConfigPaths) { - try { - const siblingConfig = JSON.parse(fs33.readFileSync(siblingConfigPath, "utf8")); - if (Number.isInteger(siblingConfig.server.port) && siblingConfig.server.port > 0) { - serverPorts.add(siblingConfig.server.port); - } - if (siblingConfig.database.mode === "embedded-postgres" && Number.isInteger(siblingConfig.database.embeddedPostgresPort) && siblingConfig.database.embeddedPostgresPort > 0) { - databasePorts.add(siblingConfig.database.embeddedPostgresPort); - } - } catch { - } - } - return { serverPorts, databasePorts }; -} -function findNextUnclaimedPort(preferredPort, claimedPorts) { - let port = Math.max(1, Math.trunc(preferredPort)); - while (claimedPorts.has(port)) { - port += 1; - } - return port; -} -function buildIsolatedWorktreeConfig(config3, context, portOverrides) { - const serverPort = portOverrides?.serverPort ?? config3.server.port; - const databasePort = config3.database.mode === "embedded-postgres" ? portOverrides?.databasePort ?? config3.database.embeddedPostgresPort : void 0; - const nextConfig = { - ...config3, - database: { - ...config3.database, - ...config3.database.mode === "embedded-postgres" ? { - embeddedPostgresDataDir: context.embeddedPostgresDataDir, - embeddedPostgresPort: databasePort ?? config3.database.embeddedPostgresPort, - backup: { - ...config3.database.backup, - dir: context.backupDir - } - } : {} - }, - server: { - ...config3.server, - port: serverPort - }, - logging: { - ...config3.logging, - logDir: context.logDir - }, - storage: { - ...config3.storage, - localDisk: { - ...config3.storage.localDisk, - baseDir: context.storageDir - } - }, - secrets: { - ...config3.secrets, - localEncrypted: { - ...config3.secrets.localEncrypted, - keyFilePath: context.secretsKeyFilePath - } - } - }; - if (config3.auth.baseUrlMode === "explicit" && config3.auth.publicBaseUrl) { - nextConfig.auth = { - ...config3.auth, - publicBaseUrl: rewriteLocalUrlPort(config3.auth.publicBaseUrl, serverPort) - }; - } - return nextConfig; -} -function needsWorktreeConfigRepair(config3, context) { - if (config3.database.mode === "embedded-postgres") { - if (!isPathInside(config3.database.embeddedPostgresDataDir, context.instanceRoot)) { - return true; - } - if (!isPathInside(config3.database.backup.dir, context.instanceRoot)) { - return true; - } - } - if (!isPathInside(config3.logging.logDir, context.instanceRoot)) { - return true; - } - if (!isPathInside(config3.storage.localDisk.baseDir, context.instanceRoot)) { - return true; - } - if (!isPathInside(config3.secrets.localEncrypted.keyFilePath, context.instanceRoot)) { - return true; - } - return false; -} -function maybeRepairLegacyWorktreeConfigAndEnvFiles() { - const context = resolveWorktreeRuntimeContext(process.env); - if (!context) { - return { repairedConfig: false, repairedEnv: false }; - } - process.env.TASKCORE_HOME = context.homeDir; - process.env.TASKCORE_INSTANCE_ID = context.instanceId; - process.env.TASKCORE_CONFIG = context.configPath; - process.env.TASKCORE_CONTEXT = context.contextPath; - process.env.TASKCORE_WORKTREE_NAME = context.worktreeName; - let repairedConfig = false; - if (fs33.existsSync(context.configPath)) { - try { - const parsed = JSON.parse(fs33.readFileSync(context.configPath, "utf8")); - const siblingPorts = collectSiblingWorktreePorts(context); - const hasSiblingPortCollision = siblingPorts.serverPorts.has(parsed.server.port) || parsed.database.mode === "embedded-postgres" && siblingPorts.databasePorts.has(parsed.database.embeddedPostgresPort); - if (needsWorktreeConfigRepair(parsed, context) || hasSiblingPortCollision) { - const selectedServerPort = findNextUnclaimedPort( - parsed.server.port === 3100 ? 3101 : parsed.server.port, - siblingPorts.serverPorts - ); - const selectedDatabasePort = parsed.database.mode === "embedded-postgres" ? findNextUnclaimedPort( - parsed.database.embeddedPostgresPort === 54329 ? 54330 : parsed.database.embeddedPostgresPort, - /* @__PURE__ */ new Set([...siblingPorts.databasePorts, selectedServerPort]) - ) : void 0; - writeConfigFile( - context.configPath, - buildIsolatedWorktreeConfig(parsed, context, { - serverPort: selectedServerPort, - databasePort: selectedDatabasePort - }) - ); - repairedConfig = true; - } - } catch { - } - } - const existingEnvEntries = readEnvEntries(context.envPath); - const desiredEnvEntries = { - ...existingEnvEntries, - TASKCORE_HOME: context.homeDir, - TASKCORE_INSTANCE_ID: context.instanceId, - TASKCORE_CONFIG: context.configPath, - TASKCORE_CONTEXT: context.contextPath, - TASKCORE_IN_WORKTREE: "true", - TASKCORE_WORKTREE_NAME: context.worktreeName - }; - const repairedEnv = Object.entries(desiredEnvEntries).some( - ([key, value]) => existingEnvEntries[key] !== value - ); - if (repairedEnv) { - fs33.mkdirSync(path41.dirname(context.envPath), { recursive: true }); - fs33.writeFileSync(context.envPath, formatEnvEntries(desiredEnvEntries), { mode: 384 }); - } - return { repairedConfig, repairedEnv }; -} - -// server/src/config.ts -var TASKCORE_ENV_FILE_PATH = resolveTaskcoreEnvPath(); -if (existsSync4(TASKCORE_ENV_FILE_PATH)) { - (0, import_dotenv.config)({ path: TASKCORE_ENV_FILE_PATH, override: false, quiet: true }); -} -var CWD_ENV_PATH = resolve(process.cwd(), ".env"); -var isSameFile = existsSync4(CWD_ENV_PATH) && existsSync4(TASKCORE_ENV_FILE_PATH) ? realpathSync2(CWD_ENV_PATH) === realpathSync2(TASKCORE_ENV_FILE_PATH) : CWD_ENV_PATH === TASKCORE_ENV_FILE_PATH; -if (!isSameFile && existsSync4(CWD_ENV_PATH)) { - (0, import_dotenv.config)({ path: CWD_ENV_PATH, override: false, quiet: true }); -} -maybeRepairLegacyWorktreeConfigAndEnvFiles(); -var TAILSCALE_DETECT_TIMEOUT_MS = 3e3; -function detectTailnetBindHost() { - const explicit = process.env.TASKCORE_TAILNET_BIND_HOST?.trim(); - if (explicit) return explicit; - try { - const stdout = execFileSync("tailscale", ["ip", "-4"], { - encoding: "utf8", - stdio: ["ignore", "pipe", "ignore"], - timeout: TAILSCALE_DETECT_TIMEOUT_MS - }); - return stdout.split(/\r?\n/).map((line3) => line3.trim()).find(Boolean); - } catch { - return void 0; - } -} -function loadConfig() { - const fileConfig = readConfigFile(); - const fileDatabaseMode = fileConfig?.database.mode === "postgres" ? "postgres" : "embedded-postgres"; - const fileDbUrl = fileDatabaseMode === "postgres" ? fileConfig?.database.connectionString : void 0; - const fileDatabaseBackup = fileConfig?.database.backup; - const fileSecrets = fileConfig?.secrets; - const fileStorage = fileConfig?.storage; - const strictModeFromEnv = process.env.TASKCORE_SECRETS_STRICT_MODE; - const secretsStrictMode = strictModeFromEnv !== void 0 ? strictModeFromEnv === "true" : fileSecrets?.strictMode ?? false; - const providerFromEnvRaw = process.env.TASKCORE_SECRETS_PROVIDER; - const providerFromEnv = providerFromEnvRaw && SECRET_PROVIDERS.includes(providerFromEnvRaw) ? providerFromEnvRaw : null; - const providerFromFile = fileSecrets?.provider; - const secretsProvider = providerFromEnv ?? providerFromFile ?? "local_encrypted"; - const storageProviderFromEnvRaw = process.env.TASKCORE_STORAGE_PROVIDER; - const storageProviderFromEnv = storageProviderFromEnvRaw && STORAGE_PROVIDERS.includes(storageProviderFromEnvRaw) ? storageProviderFromEnvRaw : null; - const storageProvider = storageProviderFromEnv ?? fileStorage?.provider ?? "local_disk"; - const storageLocalDiskBaseDir = resolveHomeAwarePath( - process.env.TASKCORE_STORAGE_LOCAL_DIR ?? fileStorage?.localDisk?.baseDir ?? resolveDefaultStorageDir() - ); - const storageS3Bucket = process.env.TASKCORE_STORAGE_S3_BUCKET ?? fileStorage?.s3?.bucket ?? "taskcore"; - const storageS3Region = process.env.TASKCORE_STORAGE_S3_REGION ?? fileStorage?.s3?.region ?? "us-east-1"; - const storageS3Endpoint = process.env.TASKCORE_STORAGE_S3_ENDPOINT ?? fileStorage?.s3?.endpoint ?? void 0; - const storageS3Prefix = process.env.TASKCORE_STORAGE_S3_PREFIX ?? fileStorage?.s3?.prefix ?? ""; - const storageS3ForcePathStyle = process.env.TASKCORE_STORAGE_S3_FORCE_PATH_STYLE !== void 0 ? process.env.TASKCORE_STORAGE_S3_FORCE_PATH_STYLE === "true" : fileStorage?.s3?.forcePathStyle ?? false; - const feedbackExportBackendUrl = process.env.TASKCORE_FEEDBACK_EXPORT_BACKEND_URL?.trim() || process.env.TASKCORE_TELEMETRY_BACKEND_URL?.trim() || void 0; - const feedbackExportBackendToken = process.env.TASKCORE_FEEDBACK_EXPORT_BACKEND_TOKEN?.trim() || process.env.TASKCORE_TELEMETRY_BACKEND_TOKEN?.trim() || void 0; - const deploymentModeFromEnvRaw = process.env.TASKCORE_DEPLOYMENT_MODE; - const deploymentModeFromEnv = deploymentModeFromEnvRaw && DEPLOYMENT_MODES.includes(deploymentModeFromEnvRaw) ? deploymentModeFromEnvRaw : null; - const deploymentMode = deploymentModeFromEnv ?? fileConfig?.server.deploymentMode ?? "local_trusted"; - const deploymentExposureFromEnvRaw = process.env.TASKCORE_DEPLOYMENT_EXPOSURE; - const deploymentExposureFromEnv = deploymentExposureFromEnvRaw && DEPLOYMENT_EXPOSURES.includes(deploymentExposureFromEnvRaw) ? deploymentExposureFromEnvRaw : null; - const deploymentExposure = deploymentMode === "local_trusted" ? "private" : deploymentExposureFromEnv ?? fileConfig?.server.exposure ?? "private"; - const bindFromEnvRaw = process.env.TASKCORE_BIND; - const bindFromEnv = bindFromEnvRaw && BIND_MODES.includes(bindFromEnvRaw) ? bindFromEnvRaw : null; - const configuredHost = process.env.HOST ?? fileConfig?.server.host ?? "127.0.0.1"; - const tailnetBindHost = detectTailnetBindHost(); - const bind2 = bindFromEnv ?? fileConfig?.server.bind ?? inferBindModeFromHost(configuredHost, { tailnetBindHost }); - const customBindHost = process.env.TASKCORE_BIND_HOST ?? fileConfig?.server.customBindHost; - const authBaseUrlModeFromEnvRaw = process.env.TASKCORE_AUTH_BASE_URL_MODE; - const authBaseUrlModeFromEnv = authBaseUrlModeFromEnvRaw && AUTH_BASE_URL_MODES.includes(authBaseUrlModeFromEnvRaw) ? authBaseUrlModeFromEnvRaw : null; - const publicUrlFromEnv = process.env.TASKCORE_PUBLIC_URL; - const authPublicBaseUrlRaw = process.env.TASKCORE_AUTH_PUBLIC_BASE_URL ?? process.env.BETTER_AUTH_URL ?? process.env.BETTER_AUTH_BASE_URL ?? publicUrlFromEnv ?? fileConfig?.auth?.publicBaseUrl; - const authPublicBaseUrl = authPublicBaseUrlRaw?.trim() || void 0; - const authBaseUrlMode = authBaseUrlModeFromEnv ?? fileConfig?.auth?.baseUrlMode ?? (authPublicBaseUrl ? "explicit" : "auto"); - const disableSignUpFromEnv = process.env.TASKCORE_AUTH_DISABLE_SIGN_UP; - const authDisableSignUp = disableSignUpFromEnv !== void 0 ? disableSignUpFromEnv === "true" : fileConfig?.auth?.disableSignUp ?? false; - const allowedHostnamesFromEnvRaw = process.env.TASKCORE_ALLOWED_HOSTNAMES; - const allowedHostnamesFromEnv = allowedHostnamesFromEnvRaw ? allowedHostnamesFromEnvRaw.split(",").map((value) => value.trim().toLowerCase()).filter((value) => value.length > 0) : null; - const publicUrlHostname = authPublicBaseUrl ? (() => { - try { - return new URL(authPublicBaseUrl).hostname.trim().toLowerCase(); - } catch { - return null; - } - })() : null; - const allowedHostnames = Array.from( - new Set( - [ - ...allowedHostnamesFromEnv ?? fileConfig?.server.allowedHostnames ?? [], - ...publicUrlHostname ? [publicUrlHostname] : [] - ].map((value) => value.trim().toLowerCase()).filter(Boolean) - ) - ); - const companyDeletionEnvRaw = process.env.TASKCORE_ENABLE_COMPANY_DELETION; - const companyDeletionEnabled = companyDeletionEnvRaw !== void 0 ? companyDeletionEnvRaw === "true" : deploymentMode === "local_trusted"; - const databaseBackupEnabled = process.env.TASKCORE_DB_BACKUP_ENABLED !== void 0 ? process.env.TASKCORE_DB_BACKUP_ENABLED === "true" : fileDatabaseBackup?.enabled ?? true; - const databaseBackupIntervalMinutes = Math.max( - 1, - Number(process.env.TASKCORE_DB_BACKUP_INTERVAL_MINUTES) || fileDatabaseBackup?.intervalMinutes || 60 - ); - const databaseBackupRetentionDays = Math.max( - 1, - Number(process.env.TASKCORE_DB_BACKUP_RETENTION_DAYS) || fileDatabaseBackup?.retentionDays || 7 - ); - const databaseBackupDir = resolveHomeAwarePath( - process.env.TASKCORE_DB_BACKUP_DIR ?? fileDatabaseBackup?.dir ?? resolveDefaultBackupDir() - ); - const bindValidationErrors = validateConfiguredBindMode({ - deploymentMode, - deploymentExposure, - bind: bind2, - host: configuredHost, - customBindHost - }); - if (bindValidationErrors.length > 0) { - throw new Error(bindValidationErrors[0]); - } - const resolvedBind = resolveRuntimeBind({ - bind: bind2, - host: configuredHost, - customBindHost, - tailnetBindHost - }); - if (resolvedBind.errors.length > 0) { - throw new Error(resolvedBind.errors[0]); - } - return { - deploymentMode, - deploymentExposure, - bind: resolvedBind.bind, - customBindHost: resolvedBind.customBindHost, - host: resolvedBind.host, - port: Number(process.env.PORT) || fileConfig?.server.port || 3100, - allowedHostnames, - authBaseUrlMode, - authPublicBaseUrl, - authDisableSignUp, - databaseMode: fileDatabaseMode, - databaseUrl: resolvePostgresUrlFromEnv() ?? fileDbUrl, - embeddedPostgresDataDir: resolveHomeAwarePath( - fileConfig?.database.embeddedPostgresDataDir ?? resolveDefaultEmbeddedPostgresDir() - ), - embeddedPostgresPort: fileConfig?.database.embeddedPostgresPort ?? 54329, - databaseBackupEnabled, - databaseBackupIntervalMinutes, - databaseBackupRetentionDays, - databaseBackupDir, - serveUi: process.env.SERVE_UI !== void 0 ? process.env.SERVE_UI === "true" : fileConfig?.server.serveUi ?? true, - uiDevMiddleware: process.env.TASKCORE_UI_DEV_MIDDLEWARE === "true", - secretsProvider, - secretsStrictMode, - secretsMasterKeyFilePath: resolveHomeAwarePath( - process.env.TASKCORE_SECRETS_MASTER_KEY_FILE ?? fileSecrets?.localEncrypted.keyFilePath ?? resolveDefaultSecretsKeyFilePath() - ), - storageProvider, - storageLocalDiskBaseDir, - storageS3Bucket, - storageS3Region, - storageS3Endpoint, - storageS3Prefix, - storageS3ForcePathStyle, - feedbackExportBackendUrl, - feedbackExportBackendToken, - heartbeatSchedulerEnabled: process.env.HEARTBEAT_SCHEDULER_ENABLED !== "false", - heartbeatSchedulerIntervalMs: Math.max(1e4, Number(process.env.HEARTBEAT_SCHEDULER_INTERVAL_MS) || 3e4), - companyDeletionEnabled, - telemetryEnabled: fileConfig?.telemetry?.enabled ?? true - }; -} - -// server/src/storage/local-disk-provider.ts -import { createReadStream as createReadStream3, promises as fs34 } from "node:fs"; -import path42 from "node:path"; -function normalizeObjectKey(objectKey) { - const normalized = objectKey.replace(/\\/g, "/").trim(); - if (!normalized || normalized.startsWith("/")) { - throw badRequest("Invalid object key"); - } - const parts = normalized.split("/").filter((part) => part.length > 0); - if (parts.length === 0 || parts.some((part) => part === "." || part === "..")) { - throw badRequest("Invalid object key"); - } - return parts.join("/"); -} -function resolveWithin3(baseDir, objectKey) { - const normalizedKey = normalizeObjectKey(objectKey); - const resolved = path42.resolve(baseDir, normalizedKey); - const base = path42.resolve(baseDir); - if (resolved !== base && !resolved.startsWith(base + path42.sep)) { - throw badRequest("Invalid object key path"); - } - return resolved; -} -async function statOrNull(filePath) { - try { - return await fs34.stat(filePath); - } catch { - return null; - } -} -function createLocalDiskStorageProvider(baseDir) { - const root = path42.resolve(baseDir); - return { - id: "local_disk", - async putObject(input) { - const targetPath = resolveWithin3(root, input.objectKey); - const dir = path42.dirname(targetPath); - await fs34.mkdir(dir, { recursive: true }); - const tempPath = `${targetPath}.tmp-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`; - await fs34.writeFile(tempPath, input.body); - await fs34.rename(tempPath, targetPath); - }, - async getObject(input) { - const filePath = resolveWithin3(root, input.objectKey); - const stat5 = await statOrNull(filePath); - if (!stat5 || !stat5.isFile()) { - throw notFound("Object not found"); - } - return { - stream: createReadStream3(filePath), - contentLength: stat5.size, - lastModified: stat5.mtime - }; - }, - async headObject(input) { - const filePath = resolveWithin3(root, input.objectKey); - const stat5 = await statOrNull(filePath); - if (!stat5 || !stat5.isFile()) { - return { exists: false }; - } - return { - exists: true, - contentLength: stat5.size, - lastModified: stat5.mtime - }; - }, - async deleteObject(input) { - const filePath = resolveWithin3(root, input.objectKey); - try { - await fs34.unlink(filePath); - } catch { - } - } - }; -} - -// server/src/storage/s3-provider.ts -var import_client_s3 = __toESM(require_dist_cjs71(), 1); -import { Readable } from "node:stream"; -function normalizePrefix(prefix) { - if (!prefix) return ""; - return prefix.trim().replace(/^\/+/, "").replace(/\/+$/, ""); -} -function buildKey(prefix, objectKey) { - if (!prefix) return objectKey; - return `${prefix}/${objectKey}`; -} -async function toReadableStream(body) { - if (!body) throw notFound("Object not found"); - if (body instanceof Readable) return body; - const candidate = body; - if (typeof candidate.transformToWebStream === "function") { - const webStream = candidate.transformToWebStream(); - const reader = webStream.getReader(); - return Readable.from((async function* () { - while (true) { - const { done, value } = await reader.read(); - if (done) break; - if (value) yield value; - } - })()); - } - if (typeof candidate.arrayBuffer === "function") { - const buffer2 = Buffer.from(await candidate.arrayBuffer()); - return Readable.from(buffer2); - } - throw unprocessable("Unsupported S3 body stream type"); -} -function toDate(value) { - return value instanceof Date ? value : void 0; -} -function createS3StorageProvider(config3) { - const bucket = config3.bucket.trim(); - const region = config3.region.trim(); - if (!bucket) throw unprocessable("S3 storage bucket is required"); - if (!region) throw unprocessable("S3 storage region is required"); - const prefix = normalizePrefix(config3.prefix); - const client2 = new import_client_s3.S3Client({ - region, - endpoint: config3.endpoint, - forcePathStyle: Boolean(config3.forcePathStyle) - }); - return { - id: "s3", - async putObject(input) { - const key = buildKey(prefix, input.objectKey); - await client2.send( - new import_client_s3.PutObjectCommand({ - Bucket: bucket, - Key: key, - Body: input.body, - ContentType: input.contentType, - ContentLength: input.contentLength - }) - ); - }, - async getObject(input) { - const key = buildKey(prefix, input.objectKey); - try { - const output = await client2.send( - new import_client_s3.GetObjectCommand({ - Bucket: bucket, - Key: key - }) - ); - return { - stream: await toReadableStream(output.Body), - contentType: output.ContentType, - contentLength: output.ContentLength, - etag: output.ETag, - lastModified: toDate(output.LastModified) - }; - } catch (err) { - const code = err.name; - if (code === "NoSuchKey" || code === "NotFound") throw notFound("Object not found"); - throw err; - } - }, - async headObject(input) { - const key = buildKey(prefix, input.objectKey); - try { - const output = await client2.send( - new import_client_s3.HeadObjectCommand({ - Bucket: bucket, - Key: key - }) - ); - return { - exists: true, - contentType: output.ContentType, - contentLength: output.ContentLength, - etag: output.ETag, - lastModified: toDate(output.LastModified) - }; - } catch (err) { - const code = err.name; - if (code === "NoSuchKey" || code === "NotFound") return { exists: false }; - throw err; - } - }, - async deleteObject(input) { - const key = buildKey(prefix, input.objectKey); - await client2.send( - new import_client_s3.DeleteObjectCommand({ - Bucket: bucket, - Key: key - }) - ); - } - }; -} - -// server/src/storage/provider-registry.ts -function createStorageProviderFromConfig(config3) { - if (config3.storageProvider === "local_disk") { - return createLocalDiskStorageProvider(config3.storageLocalDiskBaseDir); - } - return createS3StorageProvider({ - bucket: config3.storageS3Bucket, - region: config3.storageS3Region, - endpoint: config3.storageS3Endpoint, - prefix: config3.storageS3Prefix, - forcePathStyle: config3.storageS3ForcePathStyle - }); -} - -// server/src/storage/service.ts -import { createHash as createHash15, randomUUID as randomUUID6 } from "node:crypto"; -import path43 from "node:path"; -var MAX_SEGMENT_LENGTH = 120; -function sanitizeSegment(value) { - const cleaned = value.trim().replace(/[^a-zA-Z0-9._-]+/g, "_").replace(/_{2,}/g, "_").replace(/^_+|_+$/g, ""); - if (!cleaned) return "file"; - return cleaned.slice(0, MAX_SEGMENT_LENGTH); -} -function normalizeNamespace(namespace) { - const normalized = namespace.split("/").map((entry) => entry.trim()).filter((entry) => entry.length > 0).map((entry) => sanitizeSegment(entry)); - if (normalized.length === 0) return "misc"; - return normalized.join("/"); -} -function splitFilename(filename) { - if (!filename) return { stem: "file", ext: "" }; - const base = path43.basename(filename).trim(); - if (!base) return { stem: "file", ext: "" }; - const extRaw = path43.extname(base); - const stemRaw = extRaw ? base.slice(0, base.length - extRaw.length) : base; - const stem = sanitizeSegment(stemRaw); - const ext = extRaw.toLowerCase().replace(/[^a-z0-9.]/g, "").slice(0, 16); - return { - stem, - ext - }; -} -function ensureCompanyPrefix(companyId, objectKey) { - const expectedPrefix = `${companyId}/`; - if (!objectKey.startsWith(expectedPrefix)) { - throw forbidden("Object does not belong to company"); - } - if (objectKey.includes("..")) { - throw badRequest("Invalid object key"); - } -} -function hashBuffer(input) { - return createHash15("sha256").update(input).digest("hex"); -} -function buildObjectKey(companyId, namespace, originalFilename) { - const ns = normalizeNamespace(namespace); - const now2 = /* @__PURE__ */ new Date(); - const year3 = String(now2.getUTCFullYear()); - const month = String(now2.getUTCMonth() + 1).padStart(2, "0"); - const day2 = String(now2.getUTCDate()).padStart(2, "0"); - const { stem, ext } = splitFilename(originalFilename); - const suffix = randomUUID6(); - const filename = `${suffix}-${stem}${ext}`; - return `${companyId}/${ns}/${year3}/${month}/${day2}/${filename}`; -} -function assertPutFileInput(input) { - if (!input.companyId || input.companyId.trim().length === 0) { - throw unprocessable("companyId is required"); - } - if (!input.namespace || input.namespace.trim().length === 0) { - throw unprocessable("namespace is required"); - } - if (!input.contentType || input.contentType.trim().length === 0) { - throw unprocessable("contentType is required"); - } - if (!(input.body instanceof Buffer)) { - throw unprocessable("body must be a Buffer"); - } - if (input.body.length <= 0) { - throw unprocessable("File is empty"); - } -} -function createStorageService(provider) { - return { - provider: provider.id, - async putFile(input) { - assertPutFileInput(input); - const objectKey = buildObjectKey(input.companyId, input.namespace, input.originalFilename); - const byteSize = input.body.length; - const contentType = input.contentType.trim().toLowerCase(); - await provider.putObject({ - objectKey, - body: input.body, - contentType, - contentLength: byteSize - }); - return { - provider: provider.id, - objectKey, - contentType, - byteSize, - sha256: hashBuffer(input.body), - originalFilename: input.originalFilename - }; - }, - async getObject(companyId, objectKey) { - ensureCompanyPrefix(companyId, objectKey); - return provider.getObject({ objectKey }); - }, - async headObject(companyId, objectKey) { - ensureCompanyPrefix(companyId, objectKey); - return provider.headObject({ objectKey }); - }, - async deleteObject(companyId, objectKey) { - ensureCompanyPrefix(companyId, objectKey); - await provider.deleteObject({ objectKey }); - } - }; -} - -// server/src/storage/index.ts -function createStorageServiceFromConfig(config3) { - return createStorageService(createStorageProviderFromConfig(config3)); -} - -// server/src/routes/authz.ts -function assertBoard(req) { - if (req.actor.type !== "board") { - throw forbidden("Board access required"); - } -} -function assertInstanceAdmin(req) { - assertBoard(req); - if (req.actor.source === "local_implicit" || req.actor.isInstanceAdmin) { - return; - } - throw forbidden("Instance admin access required"); -} -function assertCompanyAccess(req, companyId) { - if (req.actor.type === "none") { - throw unauthorized(); - } - if (req.actor.type === "agent" && req.actor.companyId !== companyId) { - throw forbidden("Agent key cannot access another company"); - } - if (req.actor.type === "board" && req.actor.source !== "local_implicit" && !req.actor.isInstanceAdmin) { - const allowedCompanies = req.actor.companyIds ?? []; - if (!allowedCompanies.includes(companyId)) { - throw forbidden("User does not have access to this company"); - } - } -} -function getActorInfo(req) { - if (req.actor.type === "none") { - throw unauthorized(); - } - if (req.actor.type === "agent") { - return { - actorType: "agent", - actorId: req.actor.agentId ?? "unknown-agent", - agentId: req.actor.agentId ?? null, - runId: req.actor.runId ?? null - }; - } - return { - actorType: "user", - actorId: req.actor.userId ?? "board", - agentId: null, - runId: req.actor.runId ?? null - }; -} - -// server/src/routes/companies.ts -function companyRoutes(db, storage) { - const router2 = (0, import_express2.Router)(); - const svc = companyService(db); - const agents2 = agentService(db); - const portability = companyPortabilityService(db, storage); - const access = accessService(db); - const budgets = budgetService(db); - const feedback = feedbackService(db); - function parseBooleanQuery(value) { - return value === true || value === "true" || value === "1"; - } - function parseDateQuery(value, field) { - if (typeof value !== "string" || value.trim().length === 0) return void 0; - const parsed = new Date(value); - if (Number.isNaN(parsed.getTime())) { - throw badRequest(`Invalid ${field} query value`); - } - return parsed; - } - function assertImportTargetAccess(req, target) { - if (target.mode === "new_company") { - assertInstanceAdmin(req); - return; - } - assertCompanyAccess(req, target.companyId); - } - async function assertCanUpdateBranding(req, companyId) { - assertCompanyAccess(req, companyId); - if (req.actor.type === "board") return; - if (!req.actor.agentId) throw forbidden("Agent authentication required"); - const actorAgent = await agents2.getById(req.actor.agentId); - if (!actorAgent || actorAgent.companyId !== companyId) { - throw forbidden("Agent key cannot access another company"); - } - if (actorAgent.role !== "ceo") { - throw forbidden("Only CEO agents can update company branding"); - } - } - async function assertCanManagePortability(req, companyId, capability) { - assertCompanyAccess(req, companyId); - if (req.actor.type === "board") return; - if (!req.actor.agentId) throw forbidden("Agent authentication required"); - const actorAgent = await agents2.getById(req.actor.agentId); - if (!actorAgent || actorAgent.companyId !== companyId) { - throw forbidden("Agent key cannot access another company"); - } - if (actorAgent.role !== "ceo") { - throw forbidden(`Only CEO agents can manage company ${capability}`); - } - } - router2.get("/", async (req, res) => { - assertBoard(req); - const result = await svc.list(); - if (req.actor.source === "local_implicit" || req.actor.isInstanceAdmin) { - res.json(result); - return; - } - const allowed2 = new Set(req.actor.companyIds ?? []); - res.json(result.filter((company) => allowed2.has(company.id))); - }); - router2.get("/stats", async (req, res) => { - assertBoard(req); - const allowed2 = req.actor.source === "local_implicit" || req.actor.isInstanceAdmin ? null : new Set(req.actor.companyIds ?? []); - const stats = await svc.stats(); - if (!allowed2) { - res.json(stats); - return; - } - const filtered = Object.fromEntries(Object.entries(stats).filter(([companyId]) => allowed2.has(companyId))); - res.json(filtered); - }); - router2.get("/issues", (_req, res) => { - res.status(400).json({ - error: "Missing companyId in path. Use /api/companies/{companyId}/issues." - }); - }); - router2.get("/:companyId", async (req, res) => { - const companyId = req.params.companyId; - assertCompanyAccess(req, companyId); - if (req.actor.type !== "agent") { - assertBoard(req); - } - const company = await svc.getById(companyId); - if (!company) { - res.status(404).json({ error: "Company not found" }); - return; - } - res.json(company); - }); - router2.get("/:companyId/feedback-traces", async (req, res) => { - const companyId = req.params.companyId; - assertCompanyAccess(req, companyId); - assertBoard(req); - const targetTypeRaw = typeof req.query.targetType === "string" ? req.query.targetType : void 0; - const voteRaw = typeof req.query.vote === "string" ? req.query.vote : void 0; - const statusRaw = typeof req.query.status === "string" ? req.query.status : void 0; - const issueId = typeof req.query.issueId === "string" && req.query.issueId.trim().length > 0 ? req.query.issueId : void 0; - const projectId = typeof req.query.projectId === "string" && req.query.projectId.trim().length > 0 ? req.query.projectId : void 0; - const traces = await feedback.listFeedbackTraces({ - companyId, - issueId, - projectId, - targetType: targetTypeRaw ? feedbackTargetTypeSchema.parse(targetTypeRaw) : void 0, - vote: voteRaw ? feedbackVoteValueSchema.parse(voteRaw) : void 0, - status: statusRaw ? feedbackTraceStatusSchema.parse(statusRaw) : void 0, - from: parseDateQuery(req.query.from, "from"), - to: parseDateQuery(req.query.to, "to"), - sharedOnly: parseBooleanQuery(req.query.sharedOnly), - includePayload: parseBooleanQuery(req.query.includePayload) - }); - res.json(traces); - }); - router2.post("/:companyId/export", validate(companyPortabilityExportSchema), async (req, res) => { - const companyId = req.params.companyId; - assertCompanyAccess(req, companyId); - const result = await portability.exportBundle(companyId, req.body); - res.json(result); - }); - router2.post("/import/preview", validate(companyPortabilityPreviewSchema), async (req, res) => { - assertBoard(req); - assertImportTargetAccess(req, req.body.target); - const preview = await portability.previewImport(req.body); - res.json(preview); - }); - router2.post("/import", validate(companyPortabilityImportSchema), async (req, res) => { - assertBoard(req); - assertImportTargetAccess(req, req.body.target); - const actor = getActorInfo(req); - const result = await portability.importBundle(req.body, req.actor.type === "board" ? req.actor.userId : null); - await logActivity(db, { - companyId: result.company.id, - actorType: actor.actorType, - actorId: actor.actorId, - action: "company.imported", - entityType: "company", - entityId: result.company.id, - agentId: actor.agentId, - runId: actor.runId, - details: { - include: req.body.include ?? null, - agentCount: result.agents.length, - warningCount: result.warnings.length, - companyAction: result.company.action - } - }); - res.json(result); - }); - router2.post("/:companyId/exports/preview", validate(companyPortabilityExportSchema), async (req, res) => { - const companyId = req.params.companyId; - await assertCanManagePortability(req, companyId, "exports"); - const preview = await portability.previewExport(companyId, req.body); - res.json(preview); - }); - router2.post("/:companyId/exports", validate(companyPortabilityExportSchema), async (req, res) => { - const companyId = req.params.companyId; - await assertCanManagePortability(req, companyId, "exports"); - const result = await portability.exportBundle(companyId, req.body); - res.json(result); - }); - router2.post("/:companyId/imports/preview", validate(companyPortabilityPreviewSchema), async (req, res) => { - const companyId = req.params.companyId; - await assertCanManagePortability(req, companyId, "imports"); - if (req.body.target.mode === "existing_company" && req.body.target.companyId !== companyId) { - throw forbidden("Safe import route can only target the route company"); - } - if (req.body.collisionStrategy === "replace") { - throw forbidden("Safe import route does not allow replace collision strategy"); - } - const preview = await portability.previewImport(req.body, { - mode: "agent_safe", - sourceCompanyId: companyId - }); - res.json(preview); - }); - router2.post("/:companyId/imports/apply", validate(companyPortabilityImportSchema), async (req, res) => { - const companyId = req.params.companyId; - await assertCanManagePortability(req, companyId, "imports"); - if (req.body.target.mode === "existing_company" && req.body.target.companyId !== companyId) { - throw forbidden("Safe import route can only target the route company"); - } - if (req.body.collisionStrategy === "replace") { - throw forbidden("Safe import route does not allow replace collision strategy"); - } - const actor = getActorInfo(req); - const result = await portability.importBundle(req.body, req.actor.type === "board" ? req.actor.userId : null, { - mode: "agent_safe", - sourceCompanyId: companyId - }); - await logActivity(db, { - companyId: result.company.id, - actorType: actor.actorType, - actorId: actor.actorId, - entityType: "company", - entityId: result.company.id, - agentId: actor.agentId, - runId: actor.runId, - action: "company.imported", - details: { - include: req.body.include ?? null, - agentCount: result.agents.length, - warningCount: result.warnings.length, - companyAction: result.company.action, - importMode: "agent_safe" - } - }); - res.json(result); - }); - router2.post("/", validate(createCompanySchema), async (req, res) => { - assertBoard(req); - if (!(req.actor.source === "local_implicit" || req.actor.isInstanceAdmin)) { - throw forbidden("Instance admin required"); - } - const company = await svc.create(req.body); - await access.ensureMembership(company.id, "user", req.actor.userId ?? "local-board", "owner", "active"); - await logActivity(db, { - companyId: company.id, - actorType: "user", - actorId: req.actor.userId ?? "board", - action: "company.created", - entityType: "company", - entityId: company.id, - details: { name: company.name } - }); - if (company.budgetMonthlyCents > 0) { - await budgets.upsertPolicy( - company.id, - { - scopeType: "company", - scopeId: company.id, - amount: company.budgetMonthlyCents, - windowKind: "calendar_month_utc" - }, - req.actor.userId ?? "board" - ); - } - res.status(201).json(company); - }); - router2.patch("/:companyId", async (req, res) => { - const companyId = req.params.companyId; - assertCompanyAccess(req, companyId); - const actor = getActorInfo(req); - const existingCompany = await svc.getById(companyId); - if (!existingCompany) { - res.status(404).json({ error: "Company not found" }); - return; - } - let body; - if (req.actor.type === "agent") { - const agentSvc = agentService(db); - const actorAgent = req.actor.agentId ? await agentSvc.getById(req.actor.agentId) : null; - if (!actorAgent || actorAgent.role !== "ceo") { - throw forbidden("Only CEO agents or board users may update company settings"); - } - if (actorAgent.companyId !== companyId) { - throw forbidden("Agent key cannot access another company"); - } - body = updateCompanyBrandingSchema.parse(req.body); - } else { - assertBoard(req); - body = updateCompanySchema.parse(req.body); - if (body.feedbackDataSharingEnabled === true && !existingCompany.feedbackDataSharingEnabled) { - body = { - ...body, - feedbackDataSharingConsentAt: /* @__PURE__ */ new Date(), - feedbackDataSharingConsentByUserId: req.actor.userId ?? "local-board", - feedbackDataSharingTermsVersion: typeof body.feedbackDataSharingTermsVersion === "string" && body.feedbackDataSharingTermsVersion.length > 0 ? body.feedbackDataSharingTermsVersion : DEFAULT_FEEDBACK_DATA_SHARING_TERMS_VERSION - }; - } - } - const company = await svc.update(companyId, body); - if (!company) { - res.status(404).json({ error: "Company not found" }); - return; - } - await logActivity(db, { - companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - runId: actor.runId, - action: "company.updated", - entityType: "company", - entityId: companyId, - details: body - }); - res.json(company); - }); - router2.patch("/:companyId/branding", validate(updateCompanyBrandingSchema), async (req, res) => { - const companyId = req.params.companyId; - await assertCanUpdateBranding(req, companyId); - const company = await svc.update(companyId, req.body); - if (!company) { - res.status(404).json({ error: "Company not found" }); - return; - } - const actor = getActorInfo(req); - await logActivity(db, { - companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - runId: actor.runId, - action: "company.branding_updated", - entityType: "company", - entityId: companyId, - details: req.body - }); - res.json(company); - }); - router2.post("/:companyId/archive", async (req, res) => { - assertBoard(req); - const companyId = req.params.companyId; - assertCompanyAccess(req, companyId); - const company = await svc.archive(companyId); - if (!company) { - res.status(404).json({ error: "Company not found" }); - return; - } - await logActivity(db, { - companyId, - actorType: "user", - actorId: req.actor.userId ?? "board", - action: "company.archived", - entityType: "company", - entityId: companyId - }); - res.json(company); - }); - router2.delete("/:companyId", async (req, res) => { - assertBoard(req); - const companyId = req.params.companyId; - assertCompanyAccess(req, companyId); - const company = await svc.remove(companyId); - if (!company) { - res.status(404).json({ error: "Company not found" }); - return; - } - res.json({ ok: true }); - }); - return router2; -} - -// server/src/routes/company-skills.ts -var import_express3 = __toESM(require_express2(), 1); -function companySkillRoutes(db) { - const router2 = (0, import_express3.Router)(); - const agents2 = agentService(db); - const access = accessService(db); - const svc = companySkillService(db); - function canCreateAgents(agent) { - if (!agent.permissions || typeof agent.permissions !== "object") return false; - return Boolean(agent.permissions.canCreateAgents); - } - function asString15(value) { - if (typeof value !== "string") return null; - const trimmed = value.trim(); - return trimmed.length > 0 ? trimmed : null; - } - function deriveTrackedSkillRef(skill) { - if (skill.sourceType === "skills_sh") { - return skill.key; - } - if (skill.sourceType !== "github") { - return null; - } - const hostname3 = asString15(skill.metadata?.hostname); - if (hostname3 !== "github.com") { - return null; - } - return skill.key; - } - async function assertCanMutateCompanySkills(req, companyId) { - assertCompanyAccess(req, companyId); - if (req.actor.type === "board") { - if (req.actor.source === "local_implicit" || req.actor.isInstanceAdmin) return; - const allowed2 = await access.canUser(companyId, req.actor.userId, "agents:create"); - if (!allowed2) { - throw forbidden("Missing permission: agents:create"); - } - return; - } - if (!req.actor.agentId) { - throw forbidden("Agent authentication required"); - } - const actorAgent = await agents2.getById(req.actor.agentId); - if (!actorAgent || actorAgent.companyId !== companyId) { - throw forbidden("Agent key cannot access another company"); - } - const allowedByGrant = await access.hasPermission(companyId, "agent", actorAgent.id, "agents:create"); - if (allowedByGrant || canCreateAgents(actorAgent)) { - return; - } - throw forbidden("Missing permission: can create agents"); - } - router2.get("/companies/:companyId/skills", async (req, res) => { - const companyId = req.params.companyId; - assertCompanyAccess(req, companyId); - const result = await svc.list(companyId); - res.json(result); - }); - router2.get("/companies/:companyId/skills/:skillId", async (req, res) => { - const companyId = req.params.companyId; - const skillId = req.params.skillId; - assertCompanyAccess(req, companyId); - const result = await svc.detail(companyId, skillId); - if (!result) { - res.status(404).json({ error: "Skill not found" }); - return; - } - res.json(result); - }); - router2.get("/companies/:companyId/skills/:skillId/update-status", async (req, res) => { - const companyId = req.params.companyId; - const skillId = req.params.skillId; - assertCompanyAccess(req, companyId); - const result = await svc.updateStatus(companyId, skillId); - if (!result) { - res.status(404).json({ error: "Skill not found" }); - return; - } - res.json(result); - }); - router2.get("/companies/:companyId/skills/:skillId/files", async (req, res) => { - const companyId = req.params.companyId; - const skillId = req.params.skillId; - const relativePath = String(req.query.path ?? "SKILL.md"); - assertCompanyAccess(req, companyId); - const result = await svc.readFile(companyId, skillId, relativePath); - if (!result) { - res.status(404).json({ error: "Skill not found" }); - return; - } - res.json(result); - }); - router2.post( - "/companies/:companyId/skills", - validate(companySkillCreateSchema), - async (req, res) => { - const companyId = req.params.companyId; - await assertCanMutateCompanySkills(req, companyId); - const result = await svc.createLocalSkill(companyId, req.body); - const actor = getActorInfo(req); - await logActivity(db, { - companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - runId: actor.runId, - action: "company.skill_created", - entityType: "company_skill", - entityId: result.id, - details: { - slug: result.slug, - name: result.name - } - }); - res.status(201).json(result); - } - ); - router2.patch( - "/companies/:companyId/skills/:skillId/files", - validate(companySkillFileUpdateSchema), - async (req, res) => { - const companyId = req.params.companyId; - const skillId = req.params.skillId; - await assertCanMutateCompanySkills(req, companyId); - const result = await svc.updateFile( - companyId, - skillId, - String(req.body.path ?? ""), - String(req.body.content ?? "") - ); - const actor = getActorInfo(req); - await logActivity(db, { - companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - runId: actor.runId, - action: "company.skill_file_updated", - entityType: "company_skill", - entityId: skillId, - details: { - path: result.path, - markdown: result.markdown - } - }); - res.json(result); - } - ); - router2.post( - "/companies/:companyId/skills/import", - validate(companySkillImportSchema), - async (req, res) => { - const companyId = req.params.companyId; - await assertCanMutateCompanySkills(req, companyId); - const source = String(req.body.source ?? ""); - const result = await svc.importFromSource(companyId, source); - const actor = getActorInfo(req); - await logActivity(db, { - companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - runId: actor.runId, - action: "company.skills_imported", - entityType: "company", - entityId: companyId, - details: { - source, - importedCount: result.imported.length, - importedSlugs: result.imported.map((skill) => skill.slug), - warningCount: result.warnings.length - } - }); - const telemetryClient = getTelemetryClient(); - if (telemetryClient) { - for (const skill of result.imported) { - trackSkillImported(telemetryClient, { - sourceType: skill.sourceType, - skillRef: deriveTrackedSkillRef(skill) - }); - } - } - res.status(201).json(result); - } - ); - router2.post( - "/companies/:companyId/skills/scan-projects", - validate(companySkillProjectScanRequestSchema), - async (req, res) => { - const companyId = req.params.companyId; - await assertCanMutateCompanySkills(req, companyId); - const result = await svc.scanProjectWorkspaces(companyId, req.body); - const actor = getActorInfo(req); - await logActivity(db, { - companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - runId: actor.runId, - action: "company.skills_scanned", - entityType: "company", - entityId: companyId, - details: { - scannedProjects: result.scannedProjects, - scannedWorkspaces: result.scannedWorkspaces, - discovered: result.discovered, - importedCount: result.imported.length, - updatedCount: result.updated.length, - conflictCount: result.conflicts.length, - warningCount: result.warnings.length - } - }); - res.json(result); - } - ); - router2.delete("/companies/:companyId/skills/:skillId", async (req, res) => { - const companyId = req.params.companyId; - const skillId = req.params.skillId; - await assertCanMutateCompanySkills(req, companyId); - const result = await svc.deleteSkill(companyId, skillId); - if (!result) { - res.status(404).json({ error: "Skill not found" }); - return; - } - const actor = getActorInfo(req); - await logActivity(db, { - companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - runId: actor.runId, - action: "company.skill_deleted", - entityType: "company_skill", - entityId: result.id, - details: { - slug: result.slug, - name: result.name - } - }); - res.json(result); - }); - router2.post("/companies/:companyId/skills/:skillId/install-update", async (req, res) => { - const companyId = req.params.companyId; - const skillId = req.params.skillId; - await assertCanMutateCompanySkills(req, companyId); - const result = await svc.installUpdate(companyId, skillId); - if (!result) { - res.status(404).json({ error: "Skill not found" }); - return; - } - const actor = getActorInfo(req); - await logActivity(db, { - companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - runId: actor.runId, - action: "company.skill_update_installed", - entityType: "company_skill", - entityId: result.id, - details: { - slug: result.slug, - sourceRef: result.sourceRef - } - }); - res.json(result); - }); - return router2; -} - -// server/src/routes/agents.ts -var import_express4 = __toESM(require_express2(), 1); -init_src2(); -init_drizzle_orm(); -import { generateKeyPairSync, randomUUID as randomUUID7 } from "node:crypto"; -import path44 from "node:path"; - -// server/src/services/default-agent-instructions.ts -import fs35 from "node:fs/promises"; -var DEFAULT_AGENT_BUNDLE_FILES = { - default: ["AGENTS.md"], - ceo: ["AGENTS.md", "HEARTBEAT.md", "SOUL.md", "TOOLS.md"] -}; -function resolveDefaultAgentBundleUrl(role, fileName) { - return new URL(`../onboarding-assets/${role}/${fileName}`, import.meta.url); -} -async function loadDefaultAgentInstructionsBundle(role) { - const fileNames = DEFAULT_AGENT_BUNDLE_FILES[role]; - const entries2 = await Promise.all( - fileNames.map(async (fileName) => { - const content = await fs35.readFile(resolveDefaultAgentBundleUrl(role, fileName), "utf8"); - return [fileName, content]; - }) - ); - return Object.fromEntries(entries2); -} -function resolveDefaultAgentInstructionsBundleRole(role) { - return role === "ceo" ? "ceo" : "default"; -} - -// server/src/routes/agents.ts -function agentRoutes(db) { - const DEFAULT_INSTRUCTIONS_PATH_KEYS = { - claude_local: "instructionsFilePath", - codex_local: "instructionsFilePath", - droid_local: "instructionsFilePath", - gemini_local: "instructionsFilePath", - hermes_local: "instructionsFilePath", - opencode_local: "instructionsFilePath", - cursor: "instructionsFilePath", - pi_local: "instructionsFilePath" - }; - const DEFAULT_MANAGED_INSTRUCTIONS_ADAPTER_TYPES = new Set(Object.keys(DEFAULT_INSTRUCTIONS_PATH_KEYS)); - const KNOWN_INSTRUCTIONS_PATH_KEYS = /* @__PURE__ */ new Set(["instructionsFilePath", "agentsMdPath"]); - const KNOWN_INSTRUCTIONS_BUNDLE_KEYS = [ - "instructionsBundleMode", - "instructionsRootPath", - "instructionsEntryFile", - "instructionsFilePath", - "agentsMdPath" - ]; - const router2 = (0, import_express4.Router)(); - const svc = agentService(db); - const access = accessService(db); - const approvalsSvc = approvalService(db); - const budgets = budgetService(db); - const heartbeat = heartbeatService(db); - const issueApprovalsSvc = issueApprovalService(db); - const secretsSvc = secretService(db); - const instructions = agentInstructionsService(); - const companySkills2 = companySkillService(db); - const workspaceOperations2 = workspaceOperationService(db); - const instanceSettings2 = instanceSettingsService(db); - const strictSecretsMode = process.env.TASKCORE_SECRETS_STRICT_MODE === "true"; - async function getCurrentUserRedactionOptions() { - return { - enabled: (await instanceSettings2.getGeneral()).censorUsernameInLogs - }; - } - function canCreateAgents(agent) { - if (!agent.permissions || typeof agent.permissions !== "object") return false; - return Boolean(agent.permissions.canCreateAgents); - } - async function buildAgentAccessState(agent) { - const membership = await access.getMembership(agent.companyId, "agent", agent.id); - const grants = membership ? await access.listPrincipalGrants(agent.companyId, "agent", agent.id) : []; - const hasExplicitTaskAssignGrant = grants.some((grant) => grant.permissionKey === "tasks:assign"); - if (agent.role === "ceo") { - return { - canAssignTasks: true, - taskAssignSource: "ceo_role", - membership, - grants - }; - } - if (canCreateAgents(agent)) { - return { - canAssignTasks: true, - taskAssignSource: "agent_creator", - membership, - grants - }; - } - if (hasExplicitTaskAssignGrant) { - return { - canAssignTasks: true, - taskAssignSource: "explicit_grant", - membership, - grants - }; - } - return { - canAssignTasks: false, - taskAssignSource: "none", - membership, - grants - }; - } - async function buildAgentDetail(agent, options) { - const [chainOfCommand, accessState] = await Promise.all([ - svc.getChainOfCommand(agent.id), - buildAgentAccessState(agent) - ]); - return { - ...options?.restricted ? redactForRestrictedAgentView(agent) : agent, - chainOfCommand, - access: accessState - }; - } - async function applyDefaultAgentTaskAssignGrant(companyId, agentId, grantedByUserId) { - await access.ensureMembership(companyId, "agent", agentId, "member", "active"); - await access.setPrincipalPermission( - companyId, - "agent", - agentId, - "tasks:assign", - true, - grantedByUserId - ); - } - async function assertCanCreateAgentsForCompany(req, companyId) { - assertCompanyAccess(req, companyId); - if (req.actor.type === "board") { - if (req.actor.source === "local_implicit" || req.actor.isInstanceAdmin) return null; - const allowed2 = await access.canUser(companyId, req.actor.userId, "agents:create"); - if (!allowed2) { - throw forbidden("Missing permission: agents:create"); - } - return null; - } - if (!req.actor.agentId) throw forbidden("Agent authentication required"); - const actorAgent = await svc.getById(req.actor.agentId); - if (!actorAgent || actorAgent.companyId !== companyId) { - throw forbidden("Agent key cannot access another company"); - } - const allowedByGrant = await access.hasPermission(companyId, "agent", actorAgent.id, "agents:create"); - if (!allowedByGrant && !canCreateAgents(actorAgent)) { - throw forbidden("Missing permission: can create agents"); - } - return actorAgent; - } - async function assertCanReadConfigurations(req, companyId) { - return assertCanCreateAgentsForCompany(req, companyId); - } - async function actorCanReadConfigurationsForCompany(req, companyId) { - assertCompanyAccess(req, companyId); - if (req.actor.type === "board") { - if (req.actor.source === "local_implicit" || req.actor.isInstanceAdmin) return true; - return access.canUser(companyId, req.actor.userId, "agents:create"); - } - if (!req.actor.agentId) return false; - const actorAgent = await svc.getById(req.actor.agentId); - if (!actorAgent || actorAgent.companyId !== companyId) return false; - const allowedByGrant = await access.hasPermission(companyId, "agent", actorAgent.id, "agents:create"); - return allowedByGrant || canCreateAgents(actorAgent); - } - async function buildSkippedWakeupResponse(agent, payload2) { - const issueId = typeof payload2?.issueId === "string" && payload2.issueId.trim() ? payload2.issueId : null; - if (!issueId) { - return { - status: "skipped", - reason: "wakeup_skipped", - message: "Wakeup was skipped.", - issueId: null, - executionRunId: null, - executionAgentId: null, - executionAgentName: null - }; - } - const issue2 = await db.select({ - id: issues.id, - executionRunId: issues.executionRunId - }).from(issues).where(and(eq(issues.id, issueId), eq(issues.companyId, agent.companyId))).then((rows) => rows[0] ?? null); - if (!issue2?.executionRunId) { - return { - status: "skipped", - reason: "wakeup_skipped", - message: "Wakeup was skipped.", - issueId, - executionRunId: null, - executionAgentId: null, - executionAgentName: null - }; - } - const executionRun = await heartbeat.getRun(issue2.executionRunId); - if (!executionRun || executionRun.status !== "queued" && executionRun.status !== "running") { - return { - status: "skipped", - reason: "wakeup_skipped", - message: "Wakeup was skipped.", - issueId, - executionRunId: issue2.executionRunId, - executionAgentId: null, - executionAgentName: null - }; - } - const executionAgent = await svc.getById(executionRun.agentId); - const executionAgentName = executionAgent?.name ?? null; - return { - status: "skipped", - reason: "issue_execution_deferred", - message: executionAgentName ? `Wakeup was deferred because this issue is already being executed by ${executionAgentName}.` : "Wakeup was deferred because this issue already has an active execution run.", - issueId, - executionRunId: executionRun.id, - executionAgentId: executionRun.agentId, - executionAgentName - }; - } - async function assertCanUpdateAgent(req, targetAgent) { - assertCompanyAccess(req, targetAgent.companyId); - if (req.actor.type === "board") return; - if (!req.actor.agentId) throw forbidden("Agent authentication required"); - const actorAgent = await svc.getById(req.actor.agentId); - if (!actorAgent || actorAgent.companyId !== targetAgent.companyId) { - throw forbidden("Agent key cannot access another company"); - } - if (actorAgent.id === targetAgent.id) return; - if (actorAgent.role === "ceo") return; - const allowedByGrant = await access.hasPermission( - targetAgent.companyId, - "agent", - actorAgent.id, - "agents:create" - ); - if (allowedByGrant || canCreateAgents(actorAgent)) return; - throw forbidden("Only CEO or agent creators can modify other agents"); - } - async function assertCanReadAgent(req, targetAgent) { - assertCompanyAccess(req, targetAgent.companyId); - if (req.actor.type === "board") return; - if (!req.actor.agentId) throw forbidden("Agent authentication required"); - const actorAgent = await svc.getById(req.actor.agentId); - if (!actorAgent || actorAgent.companyId !== targetAgent.companyId) { - throw forbidden("Agent key cannot access another company"); - } - } - function assertKnownAdapterType(type) { - const adapterType = typeof type === "string" ? type.trim() : ""; - if (!adapterType) { - throw unprocessable("Adapter type is required"); - } - if (!findServerAdapter(adapterType)) { - throw unprocessable(`Unknown adapter type: ${adapterType}`); - } - return adapterType; - } - function hasOwn(value, key) { - return Object.hasOwn(value, key); - } - async function resolveCompanyIdForAgentReference(req) { - const companyIdQuery = req.query.companyId; - const requestedCompanyId = typeof companyIdQuery === "string" && companyIdQuery.trim().length > 0 ? companyIdQuery.trim() : null; - if (requestedCompanyId) { - assertCompanyAccess(req, requestedCompanyId); - return requestedCompanyId; - } - if (req.actor.type === "agent" && req.actor.companyId) { - return req.actor.companyId; - } - return null; - } - async function normalizeAgentReference(req, rawId) { - const raw = rawId.trim(); - if (isUuidLike(raw)) return raw; - const companyId = await resolveCompanyIdForAgentReference(req); - if (!companyId) { - throw unprocessable("Agent shortname lookup requires companyId query parameter"); - } - const resolved = await svc.resolveByReference(companyId, raw); - if (resolved.ambiguous) { - throw conflict("Agent shortname is ambiguous in this company. Use the agent ID."); - } - if (!resolved.agent) { - throw notFound("Agent not found"); - } - return resolved.agent.id; - } - function parseSourceIssueIds(input) { - const values2 = []; - if (Array.isArray(input.sourceIssueIds)) values2.push(...input.sourceIssueIds); - if (typeof input.sourceIssueId === "string" && input.sourceIssueId.length > 0) { - values2.push(input.sourceIssueId); - } - return Array.from(new Set(values2)); - } - function asRecord8(value) { - if (typeof value !== "object" || value === null || Array.isArray(value)) return null; - return value; - } - function asNonEmptyString(value) { - if (typeof value !== "string") return null; - const trimmed = value.trim(); - return trimmed.length > 0 ? trimmed : null; - } - function preserveInstructionsBundleConfig(existingAdapterConfig, nextAdapterConfig) { - const nextKeys = new Set(Object.keys(nextAdapterConfig)); - if (KNOWN_INSTRUCTIONS_BUNDLE_KEYS.some((key) => nextKeys.has(key))) { - return nextAdapterConfig; - } - const merged = { ...nextAdapterConfig }; - for (const key of KNOWN_INSTRUCTIONS_BUNDLE_KEYS) { - if (merged[key] === void 0 && existingAdapterConfig[key] !== void 0) { - merged[key] = existingAdapterConfig[key]; - } - } - return merged; - } - function parseBooleanLike2(value) { - if (typeof value === "boolean") return value; - if (typeof value === "number") { - if (value === 1) return true; - if (value === 0) return false; - return null; - } - if (typeof value !== "string") return null; - const normalized = value.trim().toLowerCase(); - if (normalized === "true" || normalized === "1" || normalized === "yes" || normalized === "on") { - return true; - } - if (normalized === "false" || normalized === "0" || normalized === "no" || normalized === "off") { - return false; - } - return null; - } - function parseNumberLike(value) { - if (typeof value === "number" && Number.isFinite(value)) return value; - if (typeof value !== "string") return null; - const parsed = Number(value.trim()); - return Number.isFinite(parsed) ? parsed : null; - } - function parseSchedulerHeartbeatPolicy(runtimeConfig) { - const heartbeat2 = asRecord8(asRecord8(runtimeConfig)?.heartbeat) ?? {}; - return { - enabled: parseBooleanLike2(heartbeat2.enabled) ?? false, - intervalSec: Math.max(0, parseNumberLike(heartbeat2.intervalSec) ?? 0) - }; - } - function normalizeNewAgentRuntimeConfig(runtimeConfig) { - const parsedRuntimeConfig = asRecord8(runtimeConfig); - const normalizedRuntimeConfig = parsedRuntimeConfig ? { ...parsedRuntimeConfig } : {}; - const parsedHeartbeat = asRecord8(normalizedRuntimeConfig.heartbeat); - const heartbeat2 = parsedHeartbeat ? { ...parsedHeartbeat } : {}; - if (parseBooleanLike2(heartbeat2.enabled) == null) { - heartbeat2.enabled = false; - } - normalizedRuntimeConfig.heartbeat = heartbeat2; - return normalizedRuntimeConfig; - } - function generateEd25519PrivateKeyPem2() { - const { privateKey } = generateKeyPairSync("ed25519"); - return privateKey.export({ type: "pkcs8", format: "pem" }).toString(); - } - function ensureGatewayDeviceKey(adapterType, adapterConfig) { - if (adapterType !== "openclaw_gateway") return adapterConfig; - const disableDeviceAuth = parseBooleanLike2(adapterConfig.disableDeviceAuth) === true; - if (disableDeviceAuth) return adapterConfig; - if (asNonEmptyString(adapterConfig.devicePrivateKeyPem)) return adapterConfig; - return { ...adapterConfig, devicePrivateKeyPem: generateEd25519PrivateKeyPem2() }; - } - function applyCreateDefaultsByAdapterType(adapterType, adapterConfig) { - const next = { ...adapterConfig }; - if (adapterType === "codex_local") { - if (!asNonEmptyString(next.model)) { - next.model = DEFAULT_CODEX_LOCAL_MODEL; - } - const hasBypassFlag = typeof next.dangerouslyBypassApprovalsAndSandbox === "boolean" || typeof next.dangerouslyBypassSandbox === "boolean"; - if (!hasBypassFlag) { - next.dangerouslyBypassApprovalsAndSandbox = DEFAULT_CODEX_LOCAL_BYPASS_APPROVALS_AND_SANDBOX; - } - return ensureGatewayDeviceKey(adapterType, next); - } - if (adapterType === "gemini_local" && !asNonEmptyString(next.model)) { - next.model = DEFAULT_GEMINI_LOCAL_MODEL; - return ensureGatewayDeviceKey(adapterType, next); - } - if (adapterType === "cursor" && !asNonEmptyString(next.model)) { - next.model = DEFAULT_CURSOR_LOCAL_MODEL; - } - return ensureGatewayDeviceKey(adapterType, next); - } - async function assertAdapterConfigConstraints(companyId, adapterType, adapterConfig) { - if (adapterType !== "opencode_local") return; - const { config: runtimeConfig } = await secretsSvc.resolveAdapterConfigForRuntime(companyId, adapterConfig); - const runtimeEnv = asRecord8(runtimeConfig.env) ?? {}; - try { - await ensureOpenCodeModelConfiguredAndAvailable({ - model: runtimeConfig.model, - command: runtimeConfig.command, - cwd: runtimeConfig.cwd, - env: runtimeEnv - }); - } catch (err) { - const reason = err instanceof Error ? err.message : String(err); - throw unprocessable(`Invalid opencode_local adapterConfig: ${reason}`); - } - } - function resolveInstructionsFilePath(candidatePath, adapterConfig) { - const trimmed = candidatePath.trim(); - if (path44.isAbsolute(trimmed)) return trimmed; - const cwd = asNonEmptyString(adapterConfig.cwd); - if (!cwd) { - throw unprocessable( - "Relative instructions path requires adapterConfig.cwd to be set to an absolute path" - ); - } - if (!path44.isAbsolute(cwd)) { - throw unprocessable("adapterConfig.cwd must be an absolute path to resolve relative instructions path"); - } - return path44.resolve(cwd, trimmed); - } - async function materializeDefaultInstructionsBundleForNewAgent(agent) { - if (!DEFAULT_MANAGED_INSTRUCTIONS_ADAPTER_TYPES.has(agent.adapterType)) { - return agent; - } - const adapterConfig = asRecord8(agent.adapterConfig) ?? {}; - const hasExplicitInstructionsBundle = Boolean(asNonEmptyString(adapterConfig.instructionsBundleMode)) || Boolean(asNonEmptyString(adapterConfig.instructionsRootPath)) || Boolean(asNonEmptyString(adapterConfig.instructionsEntryFile)) || Boolean(asNonEmptyString(adapterConfig.instructionsFilePath)) || Boolean(asNonEmptyString(adapterConfig.agentsMdPath)); - if (hasExplicitInstructionsBundle) { - return agent; - } - const promptTemplate = typeof adapterConfig.promptTemplate === "string" ? adapterConfig.promptTemplate : ""; - const files = promptTemplate.trim().length === 0 ? await loadDefaultAgentInstructionsBundle(resolveDefaultAgentInstructionsBundleRole(agent.role)) : { "AGENTS.md": promptTemplate }; - const materialized = await instructions.materializeManagedBundle( - agent, - files, - { entryFile: "AGENTS.md", replaceExisting: false } - ); - const nextAdapterConfig = { ...materialized.adapterConfig }; - delete nextAdapterConfig.promptTemplate; - const updated = await svc.update(agent.id, { adapterConfig: nextAdapterConfig }); - return updated ?? { ...agent, adapterConfig: nextAdapterConfig }; - } - async function assertCanManageInstructionsPath(req, targetAgent) { - assertCompanyAccess(req, targetAgent.companyId); - if (req.actor.type === "board") return; - if (!req.actor.agentId) throw forbidden("Agent authentication required"); - const actorAgent = await svc.getById(req.actor.agentId); - if (!actorAgent || actorAgent.companyId !== targetAgent.companyId) { - throw forbidden("Agent key cannot access another company"); - } - if (actorAgent.id === targetAgent.id) return; - const chainOfCommand = await svc.getChainOfCommand(targetAgent.id); - if (chainOfCommand.some((manager) => manager.id === actorAgent.id)) return; - throw forbidden("Only the target agent or an ancestor manager can update instructions path"); - } - function summarizeAgentUpdateDetails(patch) { - const changedTopLevelKeys = Object.keys(patch).sort(); - const details = { changedTopLevelKeys }; - const adapterConfigPatch = asRecord8(patch.adapterConfig); - if (adapterConfigPatch) { - details.changedAdapterConfigKeys = Object.keys(adapterConfigPatch).sort(); - } - const runtimeConfigPatch = asRecord8(patch.runtimeConfig); - if (runtimeConfigPatch) { - details.changedRuntimeConfigKeys = Object.keys(runtimeConfigPatch).sort(); - } - return details; - } - function buildUnsupportedSkillSnapshot(adapterType, desiredSkills = []) { - return { - adapterType, - supported: false, - mode: "unsupported", - desiredSkills, - entries: [], - warnings: ["This adapter does not implement skill sync yet."] - }; - } - const ADAPTERS_REQUIRING_MATERIALIZED_RUNTIME_SKILLS = /* @__PURE__ */ new Set([ - "cursor", - "gemini_local", - "opencode_local", - "pi_local" - ]); - function shouldMaterializeRuntimeSkillsForAdapter(adapterType) { - return ADAPTERS_REQUIRING_MATERIALIZED_RUNTIME_SKILLS.has(adapterType); - } - async function buildRuntimeSkillConfig(companyId, adapterType, config3) { - const runtimeSkillEntries = await companySkills2.listRuntimeSkillEntries(companyId, { - materializeMissing: shouldMaterializeRuntimeSkillsForAdapter(adapterType) - }); - return { - ...config3, - taskcoreRuntimeSkills: runtimeSkillEntries - }; - } - async function resolveDesiredSkillAssignment(companyId, adapterType, adapterConfig, requestedDesiredSkills) { - if (!requestedDesiredSkills) { - return { - adapterConfig, - desiredSkills: null, - runtimeSkillEntries: null - }; - } - const resolvedRequestedSkills = await companySkills2.resolveRequestedSkillKeys( - companyId, - requestedDesiredSkills - ); - const runtimeSkillEntries = await companySkills2.listRuntimeSkillEntries(companyId, { - materializeMissing: shouldMaterializeRuntimeSkillsForAdapter(adapterType) - }); - const requiredSkills = runtimeSkillEntries.filter((entry) => entry.required).map((entry) => entry.key); - const desiredSkills = Array.from(/* @__PURE__ */ new Set([...requiredSkills, ...resolvedRequestedSkills])); - return { - adapterConfig: writeTaskcoreSkillSyncPreference(adapterConfig, desiredSkills), - desiredSkills, - runtimeSkillEntries - }; - } - function redactForRestrictedAgentView(agent) { - if (!agent) return null; - return { - ...agent, - adapterConfig: {}, - runtimeConfig: {} - }; - } - function redactAgentConfiguration(agent) { - if (!agent) return null; - return { - id: agent.id, - companyId: agent.companyId, - name: agent.name, - role: agent.role, - title: agent.title, - status: agent.status, - reportsTo: agent.reportsTo, - adapterType: agent.adapterType, - adapterConfig: redactEventPayload(agent.adapterConfig), - runtimeConfig: redactEventPayload(agent.runtimeConfig), - permissions: agent.permissions, - updatedAt: agent.updatedAt - }; - } - function redactRevisionSnapshot(snapshot) { - if (!snapshot || typeof snapshot !== "object" || Array.isArray(snapshot)) return {}; - const record2 = snapshot; - return { - ...record2, - adapterConfig: redactEventPayload( - typeof record2.adapterConfig === "object" && record2.adapterConfig !== null ? record2.adapterConfig : {} - ), - runtimeConfig: redactEventPayload( - typeof record2.runtimeConfig === "object" && record2.runtimeConfig !== null ? record2.runtimeConfig : {} - ), - metadata: typeof record2.metadata === "object" && record2.metadata !== null ? redactEventPayload(record2.metadata) : record2.metadata ?? null - }; - } - function redactConfigRevision(revision) { - return { - ...revision, - beforeConfig: redactRevisionSnapshot(revision.beforeConfig), - afterConfig: redactRevisionSnapshot(revision.afterConfig) - }; - } - function toLeanOrgNode(node) { - const reports = Array.isArray(node.reports) ? node.reports.map((report) => toLeanOrgNode(report)) : []; - return { - id: String(node.id), - name: String(node.name), - role: String(node.role), - status: String(node.status), - reports - }; - } - router2.param("id", async (req, _res, next, rawId) => { - try { - req.params.id = await normalizeAgentReference(req, String(rawId)); - next(); - } catch (err) { - next(err); - } - }); - router2.get("/companies/:companyId/adapters/:type/models", async (req, res) => { - const companyId = req.params.companyId; - assertCompanyAccess(req, companyId); - const type = assertKnownAdapterType(req.params.type); - const models8 = await listAdapterModels(type); - res.json(models8); - }); - router2.get("/companies/:companyId/adapters/:type/detect-model", async (req, res) => { - const companyId = req.params.companyId; - assertCompanyAccess(req, companyId); - const type = assertKnownAdapterType(req.params.type); - const detected = await detectAdapterModel(type); - res.json(detected); - }); - router2.post( - "/companies/:companyId/adapters/:type/test-environment", - validate(testAdapterEnvironmentSchema), - async (req, res) => { - const companyId = req.params.companyId; - const type = assertKnownAdapterType(req.params.type); - await assertCanReadConfigurations(req, companyId); - const adapter = requireServerAdapter(type); - const inputAdapterConfig = req.body?.adapterConfig ?? {}; - const normalizedAdapterConfig = await secretsSvc.normalizeAdapterConfigForPersistence( - companyId, - inputAdapterConfig, - { strictMode: strictSecretsMode } - ); - const { config: runtimeAdapterConfig } = await secretsSvc.resolveAdapterConfigForRuntime( - companyId, - normalizedAdapterConfig - ); - const result = await adapter.testEnvironment({ - companyId, - adapterType: type, - config: runtimeAdapterConfig - }); - res.json(result); - } - ); - router2.get("/agents/:id/skills", async (req, res) => { - const id = req.params.id; - const agent = await svc.getById(id); - if (!agent) { - res.status(404).json({ error: "Agent not found" }); - return; - } - await assertCanReadConfigurations(req, agent.companyId); - const adapter = findActiveServerAdapter(agent.adapterType); - if (!adapter?.listSkills) { - const preference = readTaskcoreSkillSyncPreference( - agent.adapterConfig - ); - const runtimeSkillEntries = await companySkills2.listRuntimeSkillEntries(agent.companyId, { - materializeMissing: false - }); - const requiredSkills = runtimeSkillEntries.filter((entry) => entry.required).map((entry) => entry.key); - res.json(buildUnsupportedSkillSnapshot(agent.adapterType, Array.from(/* @__PURE__ */ new Set([...requiredSkills, ...preference.desiredSkills])))); - return; - } - const { config: runtimeConfig } = await secretsSvc.resolveAdapterConfigForRuntime( - agent.companyId, - agent.adapterConfig - ); - const runtimeSkillConfig = await buildRuntimeSkillConfig( - agent.companyId, - agent.adapterType, - runtimeConfig - ); - const snapshot = await adapter.listSkills({ - agentId: agent.id, - companyId: agent.companyId, - adapterType: agent.adapterType, - config: runtimeSkillConfig - }); - res.json(snapshot); - }); - router2.post( - "/agents/:id/skills/sync", - validate(agentSkillSyncSchema), - async (req, res) => { - const id = req.params.id; - const agent = await svc.getById(id); - if (!agent) { - res.status(404).json({ error: "Agent not found" }); - return; - } - await assertCanUpdateAgent(req, agent); - const requestedSkills = Array.from( - new Set( - req.body.desiredSkills.map((value) => value.trim()).filter(Boolean) - ) - ); - const { - adapterConfig: nextAdapterConfig, - desiredSkills, - runtimeSkillEntries - } = await resolveDesiredSkillAssignment( - agent.companyId, - agent.adapterType, - agent.adapterConfig, - requestedSkills - ); - if (!desiredSkills || !runtimeSkillEntries) { - throw unprocessable("Skill sync requires desiredSkills."); - } - const actor = getActorInfo(req); - const updated = await svc.update(agent.id, { - adapterConfig: nextAdapterConfig - }, { - recordRevision: { - createdByAgentId: actor.agentId, - createdByUserId: actor.actorType === "user" ? actor.actorId : null, - source: "skill-sync" - } - }); - if (!updated) { - res.status(404).json({ error: "Agent not found" }); - return; - } - const adapter = findActiveServerAdapter(updated.adapterType); - const { config: runtimeConfig } = await secretsSvc.resolveAdapterConfigForRuntime( - updated.companyId, - updated.adapterConfig - ); - const runtimeSkillConfig = { - ...runtimeConfig, - taskcoreRuntimeSkills: runtimeSkillEntries - }; - const snapshot = adapter?.syncSkills ? await adapter.syncSkills({ - agentId: updated.id, - companyId: updated.companyId, - adapterType: updated.adapterType, - config: runtimeSkillConfig - }, desiredSkills) : adapter?.listSkills ? await adapter.listSkills({ - agentId: updated.id, - companyId: updated.companyId, - adapterType: updated.adapterType, - config: runtimeSkillConfig - }) : buildUnsupportedSkillSnapshot(updated.adapterType, desiredSkills); - await logActivity(db, { - companyId: updated.companyId, - actorType: actor.actorType, - actorId: actor.actorId, - action: "agent.skills_synced", - entityType: "agent", - entityId: updated.id, - agentId: actor.agentId, - runId: actor.runId, - details: { - adapterType: updated.adapterType, - desiredSkills, - mode: snapshot.mode, - supported: snapshot.supported, - entryCount: snapshot.entries.length, - warningCount: snapshot.warnings.length - } - }); - res.json(snapshot); - } - ); - router2.get("/companies/:companyId/agents", async (req, res) => { - const companyId = req.params.companyId; - assertCompanyAccess(req, companyId); - const unsupportedQueryParams = Object.keys(req.query).sort(); - if (unsupportedQueryParams.length > 0) { - res.status(400).json({ - error: `Unsupported query parameter${unsupportedQueryParams.length === 1 ? "" : "s"}: ${unsupportedQueryParams.join(", ")}` - }); - return; - } - const result = await svc.list(companyId); - const canReadConfigs = await actorCanReadConfigurationsForCompany(req, companyId); - if (canReadConfigs || req.actor.type === "board") { - res.json(result); - return; - } - res.json(result.map((agent) => redactForRestrictedAgentView(agent))); - }); - router2.get("/instance/scheduler-heartbeats", async (req, res) => { - assertInstanceAdmin(req); - const rows = await db.select({ - id: agents.id, - companyId: agents.companyId, - agentName: agents.name, - role: agents.role, - title: agents.title, - status: agents.status, - adapterType: agents.adapterType, - runtimeConfig: agents.runtimeConfig, - lastHeartbeatAt: agents.lastHeartbeatAt, - companyName: companies.name, - companyIssuePrefix: companies.issuePrefix - }).from(agents).innerJoin(companies, eq(agents.companyId, companies.id)).orderBy(companies.name, agents.name); - const items = rows.map((row) => { - const policy = parseSchedulerHeartbeatPolicy(row.runtimeConfig); - const statusEligible = row.status !== "paused" && row.status !== "terminated" && row.status !== "pending_approval"; - return { - id: row.id, - companyId: row.companyId, - companyName: row.companyName, - companyIssuePrefix: row.companyIssuePrefix, - agentName: row.agentName, - agentUrlKey: deriveAgentUrlKey(row.agentName, row.id), - role: row.role, - title: row.title, - status: row.status, - adapterType: row.adapterType, - intervalSec: policy.intervalSec, - heartbeatEnabled: policy.enabled, - schedulerActive: statusEligible && policy.enabled && policy.intervalSec > 0, - lastHeartbeatAt: row.lastHeartbeatAt - }; - }).filter( - (item) => item.status !== "paused" && item.status !== "terminated" && item.status !== "pending_approval" - ).sort((left, right) => { - if (left.schedulerActive !== right.schedulerActive) { - return left.schedulerActive ? -1 : 1; - } - const companyOrder = left.companyName.localeCompare(right.companyName); - if (companyOrder !== 0) return companyOrder; - return left.agentName.localeCompare(right.agentName); - }); - res.json(items); - }); - router2.get("/companies/:companyId/org", async (req, res) => { - const companyId = req.params.companyId; - assertCompanyAccess(req, companyId); - const tree = await svc.orgForCompany(companyId); - const leanTree = tree.map((node) => toLeanOrgNode(node)); - res.json(leanTree); - }); - router2.get("/companies/:companyId/org.svg", async (req, res) => { - const companyId = req.params.companyId; - assertCompanyAccess(req, companyId); - const style = ORG_CHART_STYLES.includes(req.query.style) ? req.query.style : "warmth"; - const tree = await svc.orgForCompany(companyId); - const leanTree = tree.map((node) => toLeanOrgNode(node)); - const svg2 = renderOrgChartSvg(leanTree, style); - res.setHeader("Content-Type", "image/svg+xml"); - res.setHeader("Cache-Control", "no-cache"); - res.send(svg2); - }); - router2.get("/companies/:companyId/org.png", async (req, res) => { - const companyId = req.params.companyId; - assertCompanyAccess(req, companyId); - const style = ORG_CHART_STYLES.includes(req.query.style) ? req.query.style : "warmth"; - const tree = await svc.orgForCompany(companyId); - const leanTree = tree.map((node) => toLeanOrgNode(node)); - const png = await renderOrgChartPng(leanTree, style); - res.setHeader("Content-Type", "image/png"); - res.setHeader("Cache-Control", "no-cache"); - res.send(png); - }); - router2.get("/companies/:companyId/agent-configurations", async (req, res) => { - const companyId = req.params.companyId; - await assertCanReadConfigurations(req, companyId); - const rows = await svc.list(companyId); - res.json(rows.map((row) => redactAgentConfiguration(row))); - }); - router2.get("/agents/me", async (req, res) => { - if (req.actor.type !== "agent" || !req.actor.agentId) { - res.status(401).json({ error: "Agent authentication required" }); - return; - } - const agent = await svc.getById(req.actor.agentId); - if (!agent) { - res.status(404).json({ error: "Agent not found" }); - return; - } - res.json(await buildAgentDetail(agent)); - }); - router2.get("/agents/me/inbox-lite", async (req, res) => { - if (req.actor.type !== "agent" || !req.actor.agentId || !req.actor.companyId) { - res.status(401).json({ error: "Agent authentication required" }); - return; - } - const issuesSvc = issueService(db); - const rows = await issuesSvc.list(req.actor.companyId, { - assigneeAgentId: req.actor.agentId, - status: "todo,in_progress,blocked" - }); - res.json( - rows.map((issue2) => ({ - id: issue2.id, - identifier: issue2.identifier, - title: issue2.title, - status: issue2.status, - priority: issue2.priority, - projectId: issue2.projectId, - goalId: issue2.goalId, - parentId: issue2.parentId, - updatedAt: issue2.updatedAt, - activeRun: issue2.activeRun - })) - ); - }); - router2.get("/agents/me/inbox/mine", async (req, res) => { - if (req.actor.type !== "agent" || !req.actor.agentId || !req.actor.companyId) { - res.status(401).json({ error: "Agent authentication required" }); - return; - } - const query = agentMineInboxQuerySchema.parse(req.query); - const issuesSvc = issueService(db); - const rows = await issuesSvc.list(req.actor.companyId, { - touchedByUserId: query.userId, - inboxArchivedByUserId: query.userId, - status: query.status - }); - res.json(rows); - }); - router2.get("/agents/:id", async (req, res) => { - const id = req.params.id; - const agent = await svc.getById(id); - if (!agent) { - res.status(404).json({ error: "Agent not found" }); - return; - } - assertCompanyAccess(req, agent.companyId); - if (req.actor.type === "agent" && req.actor.agentId !== id) { - const canRead = await actorCanReadConfigurationsForCompany(req, agent.companyId); - if (!canRead) { - res.json(await buildAgentDetail(agent, { restricted: true })); - return; - } - } - res.json(await buildAgentDetail(agent)); - }); - router2.get("/agents/:id/configuration", async (req, res) => { - const id = req.params.id; - const agent = await svc.getById(id); - if (!agent) { - res.status(404).json({ error: "Agent not found" }); - return; - } - await assertCanReadConfigurations(req, agent.companyId); - res.json(redactAgentConfiguration(agent)); - }); - router2.get("/agents/:id/config-revisions", async (req, res) => { - const id = req.params.id; - const agent = await svc.getById(id); - if (!agent) { - res.status(404).json({ error: "Agent not found" }); - return; - } - await assertCanReadConfigurations(req, agent.companyId); - const revisions = await svc.listConfigRevisions(id); - res.json(revisions.map((revision) => redactConfigRevision(revision))); - }); - router2.get("/agents/:id/config-revisions/:revisionId", async (req, res) => { - const id = req.params.id; - const revisionId = req.params.revisionId; - const agent = await svc.getById(id); - if (!agent) { - res.status(404).json({ error: "Agent not found" }); - return; - } - await assertCanReadConfigurations(req, agent.companyId); - const revision = await svc.getConfigRevision(id, revisionId); - if (!revision) { - res.status(404).json({ error: "Revision not found" }); - return; - } - res.json(redactConfigRevision(revision)); - }); - router2.post("/agents/:id/config-revisions/:revisionId/rollback", async (req, res) => { - const id = req.params.id; - const revisionId = req.params.revisionId; - const existing = await svc.getById(id); - if (!existing) { - res.status(404).json({ error: "Agent not found" }); - return; - } - await assertCanUpdateAgent(req, existing); - const actor = getActorInfo(req); - const updated = await svc.rollbackConfigRevision(id, revisionId, { - agentId: actor.agentId, - userId: actor.actorType === "user" ? actor.actorId : null - }); - if (!updated) { - res.status(404).json({ error: "Revision not found" }); - return; - } - await logActivity(db, { - companyId: updated.companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - runId: actor.runId, - action: "agent.config_rolled_back", - entityType: "agent", - entityId: updated.id, - details: { revisionId } - }); - res.json(updated); - }); - router2.get("/agents/:id/runtime-state", async (req, res) => { - assertBoard(req); - const id = req.params.id; - const agent = await svc.getById(id); - if (!agent) { - res.status(404).json({ error: "Agent not found" }); - return; - } - assertCompanyAccess(req, agent.companyId); - const state2 = await heartbeat.getRuntimeState(id); - res.json(state2); - }); - router2.get("/agents/:id/task-sessions", async (req, res) => { - assertBoard(req); - const id = req.params.id; - const agent = await svc.getById(id); - if (!agent) { - res.status(404).json({ error: "Agent not found" }); - return; - } - assertCompanyAccess(req, agent.companyId); - const sessions = await heartbeat.listTaskSessions(id); - res.json( - sessions.map((session) => ({ - ...session, - sessionParamsJson: redactEventPayload(session.sessionParamsJson ?? null) - })) - ); - }); - router2.post("/agents/:id/runtime-state/reset-session", validate(resetAgentSessionSchema), async (req, res) => { - assertBoard(req); - const id = req.params.id; - const agent = await svc.getById(id); - if (!agent) { - res.status(404).json({ error: "Agent not found" }); - return; - } - assertCompanyAccess(req, agent.companyId); - const taskKey = typeof req.body.taskKey === "string" && req.body.taskKey.trim().length > 0 ? req.body.taskKey.trim() : null; - const state2 = await heartbeat.resetRuntimeSession(id, { taskKey }); - await logActivity(db, { - companyId: agent.companyId, - actorType: "user", - actorId: req.actor.userId ?? "board", - action: "agent.runtime_session_reset", - entityType: "agent", - entityId: id, - details: { taskKey: taskKey ?? null } - }); - res.json(state2); - }); - router2.post("/companies/:companyId/agent-hires", validate(createAgentHireSchema), async (req, res) => { - const companyId = req.params.companyId; - await assertCanCreateAgentsForCompany(req, companyId); - const sourceIssueIds = parseSourceIssueIds(req.body); - const { - desiredSkills: requestedDesiredSkills, - sourceIssueId: _sourceIssueId, - sourceIssueIds: _sourceIssueIds, - ...hireInput - } = req.body; - hireInput.adapterType = assertKnownAdapterType(hireInput.adapterType); - const requestedAdapterConfig = applyCreateDefaultsByAdapterType( - hireInput.adapterType, - hireInput.adapterConfig ?? {} - ); - const desiredSkillAssignment = await resolveDesiredSkillAssignment( - companyId, - hireInput.adapterType, - requestedAdapterConfig, - Array.isArray(requestedDesiredSkills) ? requestedDesiredSkills : void 0 - ); - const normalizedAdapterConfig = await secretsSvc.normalizeAdapterConfigForPersistence( - companyId, - desiredSkillAssignment.adapterConfig, - { strictMode: strictSecretsMode } - ); - await assertAdapterConfigConstraints( - companyId, - hireInput.adapterType, - normalizedAdapterConfig - ); - const normalizedHireInput = { - ...hireInput, - adapterConfig: normalizedAdapterConfig, - runtimeConfig: normalizeNewAgentRuntimeConfig(hireInput.runtimeConfig) - }; - const company = await db.select().from(companies).where(eq(companies.id, companyId)).then((rows) => rows[0] ?? null); - if (!company) { - res.status(404).json({ error: "Company not found" }); - return; - } - const requiresApproval = company.requireBoardApprovalForNewAgents; - const status = requiresApproval ? "pending_approval" : "idle"; - const createdAgent = await svc.create(companyId, { - ...normalizedHireInput, - status, - spentMonthlyCents: 0, - lastHeartbeatAt: null - }); - const agent = await materializeDefaultInstructionsBundleForNewAgent(createdAgent); - let approval = null; - const actor = getActorInfo(req); - if (requiresApproval) { - const requestedAdapterType = normalizedHireInput.adapterType ?? agent.adapterType; - const requestedAdapterConfig2 = redactEventPayload( - agent.adapterConfig ?? normalizedHireInput.adapterConfig - ) ?? {}; - const requestedRuntimeConfig = redactEventPayload( - normalizedHireInput.runtimeConfig ?? agent.runtimeConfig - ) ?? {}; - const requestedMetadata = redactEventPayload( - normalizedHireInput.metadata ?? agent.metadata ?? {} - ) ?? {}; - approval = await approvalsSvc.create(companyId, { - type: "hire_agent", - requestedByAgentId: actor.actorType === "agent" ? actor.actorId : null, - requestedByUserId: actor.actorType === "user" ? actor.actorId : null, - status: "pending", - payload: { - name: normalizedHireInput.name, - role: normalizedHireInput.role, - title: normalizedHireInput.title ?? null, - icon: normalizedHireInput.icon ?? null, - reportsTo: normalizedHireInput.reportsTo ?? null, - capabilities: normalizedHireInput.capabilities ?? null, - adapterType: requestedAdapterType, - adapterConfig: requestedAdapterConfig2, - runtimeConfig: requestedRuntimeConfig, - budgetMonthlyCents: typeof normalizedHireInput.budgetMonthlyCents === "number" ? normalizedHireInput.budgetMonthlyCents : agent.budgetMonthlyCents, - desiredSkills: desiredSkillAssignment.desiredSkills, - metadata: requestedMetadata, - agentId: agent.id, - requestedByAgentId: actor.actorType === "agent" ? actor.actorId : null, - requestedConfigurationSnapshot: { - adapterType: requestedAdapterType, - adapterConfig: requestedAdapterConfig2, - runtimeConfig: requestedRuntimeConfig, - desiredSkills: desiredSkillAssignment.desiredSkills - } - }, - decisionNote: null, - decidedByUserId: null, - decidedAt: null, - updatedAt: /* @__PURE__ */ new Date() - }); - if (sourceIssueIds.length > 0) { - await issueApprovalsSvc.linkManyForApproval(approval.id, sourceIssueIds, { - agentId: actor.actorType === "agent" ? actor.actorId : null, - userId: actor.actorType === "user" ? actor.actorId : null - }); - } - } - await logActivity(db, { - companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - runId: actor.runId, - action: "agent.hire_created", - entityType: "agent", - entityId: agent.id, - details: { - name: agent.name, - role: agent.role, - requiresApproval, - approvalId: approval?.id ?? null, - issueIds: sourceIssueIds, - desiredSkills: desiredSkillAssignment.desiredSkills - } - }); - const telemetryClient = getTelemetryClient(); - if (telemetryClient) { - trackAgentCreated(telemetryClient, { agentRole: agent.role, agentId: agent.id }); - } - await applyDefaultAgentTaskAssignGrant( - companyId, - agent.id, - actor.actorType === "user" ? actor.actorId : null - ); - if (approval) { - await logActivity(db, { - companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - runId: actor.runId, - action: "approval.created", - entityType: "approval", - entityId: approval.id, - details: { type: approval.type, linkedAgentId: agent.id } - }); - } - res.status(201).json({ agent, approval }); - }); - router2.post("/companies/:companyId/agents", validate(createAgentSchema), async (req, res) => { - const companyId = req.params.companyId; - assertCompanyAccess(req, companyId); - if (req.actor.type === "agent") { - assertBoard(req); - } - const { - desiredSkills: requestedDesiredSkills, - ...createInput - } = req.body; - createInput.adapterType = assertKnownAdapterType(createInput.adapterType); - const requestedAdapterConfig = applyCreateDefaultsByAdapterType( - createInput.adapterType, - createInput.adapterConfig ?? {} - ); - const desiredSkillAssignment = await resolveDesiredSkillAssignment( - companyId, - createInput.adapterType, - requestedAdapterConfig, - Array.isArray(requestedDesiredSkills) ? requestedDesiredSkills : void 0 - ); - const normalizedAdapterConfig = await secretsSvc.normalizeAdapterConfigForPersistence( - companyId, - desiredSkillAssignment.adapterConfig, - { strictMode: strictSecretsMode } - ); - await assertAdapterConfigConstraints( - companyId, - createInput.adapterType, - normalizedAdapterConfig - ); - const createdAgent = await svc.create(companyId, { - ...createInput, - adapterConfig: normalizedAdapterConfig, - runtimeConfig: normalizeNewAgentRuntimeConfig(createInput.runtimeConfig), - status: "idle", - spentMonthlyCents: 0, - lastHeartbeatAt: null - }); - const agent = await materializeDefaultInstructionsBundleForNewAgent(createdAgent); - const actor = getActorInfo(req); - await logActivity(db, { - companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - runId: actor.runId, - action: "agent.created", - entityType: "agent", - entityId: agent.id, - details: { - name: agent.name, - role: agent.role, - desiredSkills: desiredSkillAssignment.desiredSkills - } - }); - const telemetryClient = getTelemetryClient(); - if (telemetryClient) { - trackAgentCreated(telemetryClient, { agentRole: agent.role, agentId: agent.id }); - } - await applyDefaultAgentTaskAssignGrant( - companyId, - agent.id, - req.actor.type === "board" ? req.actor.userId ?? null : null - ); - if (agent.budgetMonthlyCents > 0) { - await budgets.upsertPolicy( - companyId, - { - scopeType: "agent", - scopeId: agent.id, - amount: agent.budgetMonthlyCents, - windowKind: "calendar_month_utc" - }, - actor.actorType === "user" ? actor.actorId : null - ); - } - res.status(201).json(agent); - }); - router2.patch("/agents/:id/permissions", validate(updateAgentPermissionsSchema), async (req, res) => { - const id = req.params.id; - const existing = await svc.getById(id); - if (!existing) { - res.status(404).json({ error: "Agent not found" }); - return; - } - assertCompanyAccess(req, existing.companyId); - if (req.actor.type === "agent") { - const actorAgent = req.actor.agentId ? await svc.getById(req.actor.agentId) : null; - if (!actorAgent || actorAgent.companyId !== existing.companyId) { - res.status(403).json({ error: "Forbidden" }); - return; - } - if (actorAgent.role !== "ceo") { - res.status(403).json({ error: "Only CEO can manage permissions" }); - return; - } - } - const agent = await svc.updatePermissions(id, req.body); - if (!agent) { - res.status(404).json({ error: "Agent not found" }); - return; - } - const effectiveCanAssignTasks = agent.role === "ceo" || Boolean(agent.permissions?.canCreateAgents) || req.body.canAssignTasks; - await access.ensureMembership(agent.companyId, "agent", agent.id, "member", "active"); - await access.setPrincipalPermission( - agent.companyId, - "agent", - agent.id, - "tasks:assign", - effectiveCanAssignTasks, - req.actor.type === "board" ? req.actor.userId ?? null : null - ); - const actor = getActorInfo(req); - await logActivity(db, { - companyId: agent.companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - runId: actor.runId, - action: "agent.permissions_updated", - entityType: "agent", - entityId: agent.id, - details: { - canCreateAgents: agent.permissions?.canCreateAgents ?? false, - canAssignTasks: effectiveCanAssignTasks - } - }); - res.json(await buildAgentDetail(agent)); - }); - router2.patch("/agents/:id/instructions-path", validate(updateAgentInstructionsPathSchema), async (req, res) => { - const id = req.params.id; - const existing = await svc.getById(id); - if (!existing) { - res.status(404).json({ error: "Agent not found" }); - return; - } - await assertCanManageInstructionsPath(req, existing); - const existingAdapterConfig = asRecord8(existing.adapterConfig) ?? {}; - const explicitKey = asNonEmptyString(req.body.adapterConfigKey); - const defaultKey = DEFAULT_INSTRUCTIONS_PATH_KEYS[existing.adapterType] ?? null; - const adapterConfigKey = explicitKey ?? defaultKey; - if (!adapterConfigKey) { - res.status(422).json({ - error: `No default instructions path key for adapter type '${existing.adapterType}'. Provide adapterConfigKey.` - }); - return; - } - const nextAdapterConfig = { ...existingAdapterConfig }; - if (req.body.path === null) { - delete nextAdapterConfig[adapterConfigKey]; - } else { - nextAdapterConfig[adapterConfigKey] = resolveInstructionsFilePath(req.body.path, existingAdapterConfig); - } - const syncedAdapterConfig = syncInstructionsBundleConfigFromFilePath(existing, nextAdapterConfig); - const normalizedAdapterConfig = await secretsSvc.normalizeAdapterConfigForPersistence( - existing.companyId, - syncedAdapterConfig, - { strictMode: strictSecretsMode } - ); - const actor = getActorInfo(req); - const agent = await svc.update( - id, - { adapterConfig: normalizedAdapterConfig }, - { - recordRevision: { - createdByAgentId: actor.agentId, - createdByUserId: actor.actorType === "user" ? actor.actorId : null, - source: "instructions_path_patch" - } - } - ); - if (!agent) { - res.status(404).json({ error: "Agent not found" }); - return; - } - const updatedAdapterConfig = asRecord8(agent.adapterConfig) ?? {}; - const pathValue = asNonEmptyString(updatedAdapterConfig[adapterConfigKey]); - await logActivity(db, { - companyId: agent.companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - runId: actor.runId, - action: "agent.instructions_path_updated", - entityType: "agent", - entityId: agent.id, - details: { - adapterConfigKey, - path: pathValue, - cleared: req.body.path === null - } - }); - res.json({ - agentId: agent.id, - adapterType: agent.adapterType, - adapterConfigKey, - path: pathValue - }); - }); - router2.get("/agents/:id/instructions-bundle", async (req, res) => { - const id = req.params.id; - const existing = await svc.getById(id); - if (!existing) { - res.status(404).json({ error: "Agent not found" }); - return; - } - await assertCanReadAgent(req, existing); - res.json(await instructions.getBundle(existing)); - }); - router2.patch("/agents/:id/instructions-bundle", validate(updateAgentInstructionsBundleSchema), async (req, res) => { - const id = req.params.id; - const existing = await svc.getById(id); - if (!existing) { - res.status(404).json({ error: "Agent not found" }); - return; - } - await assertCanManageInstructionsPath(req, existing); - const actor = getActorInfo(req); - const { bundle, adapterConfig } = await instructions.updateBundle(existing, req.body); - const normalizedAdapterConfig = await secretsSvc.normalizeAdapterConfigForPersistence( - existing.companyId, - adapterConfig, - { strictMode: strictSecretsMode } - ); - await svc.update( - id, - { adapterConfig: normalizedAdapterConfig }, - { - recordRevision: { - createdByAgentId: actor.agentId, - createdByUserId: actor.actorType === "user" ? actor.actorId : null, - source: "instructions_bundle_patch" - } - } - ); - await logActivity(db, { - companyId: existing.companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - runId: actor.runId, - action: "agent.instructions_bundle_updated", - entityType: "agent", - entityId: existing.id, - details: { - mode: bundle.mode, - rootPath: bundle.rootPath, - entryFile: bundle.entryFile, - clearLegacyPromptTemplate: req.body.clearLegacyPromptTemplate === true - } - }); - res.json(bundle); - }); - router2.get("/agents/:id/instructions-bundle/file", async (req, res) => { - const id = req.params.id; - const existing = await svc.getById(id); - if (!existing) { - res.status(404).json({ error: "Agent not found" }); - return; - } - await assertCanReadAgent(req, existing); - const relativePath = typeof req.query.path === "string" ? req.query.path : ""; - if (!relativePath.trim()) { - res.status(422).json({ error: "Query parameter 'path' is required" }); - return; - } - res.json(await instructions.readFile(existing, relativePath)); - }); - router2.put("/agents/:id/instructions-bundle/file", validate(upsertAgentInstructionsFileSchema), async (req, res) => { - const id = req.params.id; - const existing = await svc.getById(id); - if (!existing) { - res.status(404).json({ error: "Agent not found" }); - return; - } - await assertCanManageInstructionsPath(req, existing); - const actor = getActorInfo(req); - const result = await instructions.writeFile(existing, req.body.path, req.body.content, { - clearLegacyPromptTemplate: req.body.clearLegacyPromptTemplate - }); - const normalizedAdapterConfig = await secretsSvc.normalizeAdapterConfigForPersistence( - existing.companyId, - result.adapterConfig, - { strictMode: strictSecretsMode } - ); - await svc.update( - id, - { adapterConfig: normalizedAdapterConfig }, - { - recordRevision: { - createdByAgentId: actor.agentId, - createdByUserId: actor.actorType === "user" ? actor.actorId : null, - source: "instructions_bundle_file_put" - } - } - ); - await logActivity(db, { - companyId: existing.companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - runId: actor.runId, - action: "agent.instructions_file_updated", - entityType: "agent", - entityId: existing.id, - details: { - path: result.file.path, - size: result.file.size, - clearLegacyPromptTemplate: req.body.clearLegacyPromptTemplate === true - } - }); - res.json(result.file); - }); - router2.delete("/agents/:id/instructions-bundle/file", async (req, res) => { - const id = req.params.id; - const existing = await svc.getById(id); - if (!existing) { - res.status(404).json({ error: "Agent not found" }); - return; - } - await assertCanManageInstructionsPath(req, existing); - const relativePath = typeof req.query.path === "string" ? req.query.path : ""; - if (!relativePath.trim()) { - res.status(422).json({ error: "Query parameter 'path' is required" }); - return; - } - const actor = getActorInfo(req); - const result = await instructions.deleteFile(existing, relativePath); - await logActivity(db, { - companyId: existing.companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - runId: actor.runId, - action: "agent.instructions_file_deleted", - entityType: "agent", - entityId: existing.id, - details: { - path: relativePath - } - }); - res.json(result.bundle); - }); - router2.patch("/agents/:id", validate(updateAgentSchema), async (req, res) => { - const id = req.params.id; - const existing = await svc.getById(id); - if (!existing) { - res.status(404).json({ error: "Agent not found" }); - return; - } - await assertCanUpdateAgent(req, existing); - if (hasOwn(req.body, "permissions")) { - res.status(422).json({ error: "Use /api/agents/:id/permissions for permission changes" }); - return; - } - const patchData = { ...req.body }; - const replaceAdapterConfig = patchData.replaceAdapterConfig === true; - delete patchData.replaceAdapterConfig; - if (hasOwn(patchData, "adapterConfig")) { - const adapterConfig = asRecord8(patchData.adapterConfig); - if (!adapterConfig) { - res.status(422).json({ error: "adapterConfig must be an object" }); - return; - } - const changingInstructionsPath = Object.keys(adapterConfig).some( - (key) => KNOWN_INSTRUCTIONS_PATH_KEYS.has(key) - ); - if (changingInstructionsPath) { - await assertCanManageInstructionsPath(req, existing); - } - patchData.adapterConfig = adapterConfig; - } - const requestedAdapterType = hasOwn(patchData, "adapterType") ? assertKnownAdapterType(patchData.adapterType) : existing.adapterType; - const touchesAdapterConfiguration = hasOwn(patchData, "adapterType") || hasOwn(patchData, "adapterConfig"); - if (touchesAdapterConfiguration) { - const existingAdapterConfig = asRecord8(existing.adapterConfig) ?? {}; - const changingAdapterType = typeof patchData.adapterType === "string" && patchData.adapterType !== existing.adapterType; - const requestedAdapterConfig = hasOwn(patchData, "adapterConfig") ? asRecord8(patchData.adapterConfig) ?? {} : null; - if (requestedAdapterConfig && replaceAdapterConfig && KNOWN_INSTRUCTIONS_BUNDLE_KEYS.some( - (key) => existingAdapterConfig[key] !== void 0 && requestedAdapterConfig[key] === void 0 - )) { - await assertCanManageInstructionsPath(req, existing); - } - let rawEffectiveAdapterConfig = requestedAdapterConfig ?? existingAdapterConfig; - if (requestedAdapterConfig && !changingAdapterType && !replaceAdapterConfig) { - rawEffectiveAdapterConfig = { ...existingAdapterConfig, ...requestedAdapterConfig }; - } - if (changingAdapterType) { - const ADAPTER_AGNOSTIC_KEYS = [ - "env", - "cwd", - "timeoutSec", - "graceSec", - "promptTemplate", - "bootstrapPromptTemplate" - ]; - for (const key of ADAPTER_AGNOSTIC_KEYS) { - if (rawEffectiveAdapterConfig[key] === void 0 && existingAdapterConfig[key] !== void 0) { - rawEffectiveAdapterConfig = { ...rawEffectiveAdapterConfig, [key]: existingAdapterConfig[key] }; - } - } - rawEffectiveAdapterConfig = preserveInstructionsBundleConfig( - existingAdapterConfig, - rawEffectiveAdapterConfig - ); - } - const effectiveAdapterConfig = applyCreateDefaultsByAdapterType( - requestedAdapterType, - rawEffectiveAdapterConfig - ); - const normalizedEffectiveAdapterConfig = await secretsSvc.normalizeAdapterConfigForPersistence( - existing.companyId, - effectiveAdapterConfig, - { strictMode: strictSecretsMode } - ); - patchData.adapterConfig = syncInstructionsBundleConfigFromFilePath(existing, normalizedEffectiveAdapterConfig); - } - if (touchesAdapterConfiguration && requestedAdapterType === "opencode_local") { - const effectiveAdapterConfig = asRecord8(patchData.adapterConfig) ?? {}; - await assertAdapterConfigConstraints( - existing.companyId, - requestedAdapterType, - effectiveAdapterConfig - ); - } - const actor = getActorInfo(req); - const agent = await svc.update(id, patchData, { - recordRevision: { - createdByAgentId: actor.agentId, - createdByUserId: actor.actorType === "user" ? actor.actorId : null, - source: "patch" - } - }); - if (!agent) { - res.status(404).json({ error: "Agent not found" }); - return; - } - await logActivity(db, { - companyId: agent.companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - runId: actor.runId, - action: "agent.updated", - entityType: "agent", - entityId: agent.id, - details: summarizeAgentUpdateDetails(patchData) - }); - res.json(agent); - }); - router2.post("/agents/:id/pause", async (req, res) => { - assertBoard(req); - const id = req.params.id; - const agent = await svc.pause(id); - if (!agent) { - res.status(404).json({ error: "Agent not found" }); - return; - } - await heartbeat.cancelActiveForAgent(id); - await logActivity(db, { - companyId: agent.companyId, - actorType: "user", - actorId: req.actor.userId ?? "board", - action: "agent.paused", - entityType: "agent", - entityId: agent.id - }); - res.json(agent); - }); - router2.post("/agents/:id/resume", async (req, res) => { - assertBoard(req); - const id = req.params.id; - const agent = await svc.resume(id); - if (!agent) { - res.status(404).json({ error: "Agent not found" }); - return; - } - await logActivity(db, { - companyId: agent.companyId, - actorType: "user", - actorId: req.actor.userId ?? "board", - action: "agent.resumed", - entityType: "agent", - entityId: agent.id - }); - res.json(agent); - }); - router2.post("/agents/:id/terminate", async (req, res) => { - assertBoard(req); - const id = req.params.id; - const agent = await svc.terminate(id); - if (!agent) { - res.status(404).json({ error: "Agent not found" }); - return; - } - await heartbeat.cancelActiveForAgent(id); - await logActivity(db, { - companyId: agent.companyId, - actorType: "user", - actorId: req.actor.userId ?? "board", - action: "agent.terminated", - entityType: "agent", - entityId: agent.id - }); - res.json(agent); - }); - router2.delete("/agents/:id", async (req, res) => { - assertBoard(req); - const id = req.params.id; - const agent = await svc.remove(id); - if (!agent) { - res.status(404).json({ error: "Agent not found" }); - return; - } - await logActivity(db, { - companyId: agent.companyId, - actorType: "user", - actorId: req.actor.userId ?? "board", - action: "agent.deleted", - entityType: "agent", - entityId: agent.id - }); - res.json({ ok: true }); - }); - router2.get("/agents/:id/keys", async (req, res) => { - assertBoard(req); - const id = req.params.id; - const keys = await svc.listKeys(id); - res.json(keys); - }); - router2.post("/agents/:id/keys", validate(createAgentKeySchema), async (req, res) => { - assertBoard(req); - const id = req.params.id; - const key = await svc.createApiKey(id, req.body.name); - const agent = await svc.getById(id); - if (agent) { - await logActivity(db, { - companyId: agent.companyId, - actorType: "user", - actorId: req.actor.userId ?? "board", - action: "agent.key_created", - entityType: "agent", - entityId: agent.id, - details: { keyId: key.id, name: key.name } - }); - } - res.status(201).json(key); - }); - router2.delete("/agents/:id/keys/:keyId", async (req, res) => { - assertBoard(req); - const keyId = req.params.keyId; - const revoked = await svc.revokeKey(keyId); - if (!revoked) { - res.status(404).json({ error: "Key not found" }); - return; - } - res.json({ ok: true }); - }); - router2.post("/agents/:id/wakeup", validate(wakeAgentSchema), async (req, res) => { - const id = req.params.id; - const agent = await svc.getById(id); - if (!agent) { - res.status(404).json({ error: "Agent not found" }); - return; - } - assertCompanyAccess(req, agent.companyId); - if (req.actor.type === "agent" && req.actor.agentId !== id) { - res.status(403).json({ error: "Agent can only invoke itself" }); - return; - } - const run = await heartbeat.wakeup(id, { - source: req.body.source, - triggerDetail: req.body.triggerDetail ?? "manual", - reason: req.body.reason ?? null, - payload: req.body.payload ?? null, - idempotencyKey: req.body.idempotencyKey ?? null, - requestedByActorType: req.actor.type === "agent" ? "agent" : "user", - requestedByActorId: req.actor.type === "agent" ? req.actor.agentId ?? null : req.actor.userId ?? null, - contextSnapshot: { - triggeredBy: req.actor.type, - actorId: req.actor.type === "agent" ? req.actor.agentId : req.actor.userId, - forceFreshSession: req.body.forceFreshSession === true - } - }); - if (!run) { - res.status(202).json(await buildSkippedWakeupResponse(agent, req.body.payload ?? null)); - return; - } - const actor = getActorInfo(req); - await logActivity(db, { - companyId: agent.companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - runId: actor.runId, - action: "heartbeat.invoked", - entityType: "heartbeat_run", - entityId: run.id, - details: { agentId: id } - }); - res.status(202).json(run); - }); - router2.post("/agents/:id/heartbeat/invoke", async (req, res) => { - const id = req.params.id; - const agent = await svc.getById(id); - if (!agent) { - res.status(404).json({ error: "Agent not found" }); - return; - } - assertCompanyAccess(req, agent.companyId); - if (req.actor.type === "agent" && req.actor.agentId !== id) { - res.status(403).json({ error: "Agent can only invoke itself" }); - return; - } - const run = await heartbeat.invoke( - id, - "on_demand", - { - triggeredBy: req.actor.type, - actorId: req.actor.type === "agent" ? req.actor.agentId : req.actor.userId - }, - "manual", - { - actorType: req.actor.type === "agent" ? "agent" : "user", - actorId: req.actor.type === "agent" ? req.actor.agentId ?? null : req.actor.userId ?? null - } - ); - if (!run) { - res.status(202).json({ status: "skipped" }); - return; - } - const actor = getActorInfo(req); - await logActivity(db, { - companyId: agent.companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - runId: actor.runId, - action: "heartbeat.invoked", - entityType: "heartbeat_run", - entityId: run.id, - details: { agentId: id } - }); - res.status(202).json(run); - }); - router2.post("/agents/:id/claude-login", async (req, res) => { - assertBoard(req); - const id = req.params.id; - const agent = await svc.getById(id); - if (!agent) { - res.status(404).json({ error: "Agent not found" }); - return; - } - assertCompanyAccess(req, agent.companyId); - if (agent.adapterType !== "claude_local") { - res.status(400).json({ error: "Login is only supported for claude_local agents" }); - return; - } - const config3 = asRecord8(agent.adapterConfig) ?? {}; - const { config: runtimeConfig } = await secretsSvc.resolveAdapterConfigForRuntime(agent.companyId, config3); - const result = await runClaudeLogin({ - runId: `claude-login-${randomUUID7()}`, - agent: { - id: agent.id, - companyId: agent.companyId, - name: agent.name, - adapterType: agent.adapterType, - adapterConfig: agent.adapterConfig - }, - config: runtimeConfig - }); - res.json(result); - }); - router2.get("/companies/:companyId/heartbeat-runs", async (req, res) => { - const companyId = req.params.companyId; - assertCompanyAccess(req, companyId); - const agentId = req.query.agentId; - const limitParam = req.query.limit; - const limit = limitParam ? Math.max(1, Math.min(1e3, parseInt(limitParam, 10) || 200)) : void 0; - const runs = await heartbeat.list(companyId, agentId, limit); - res.json(runs); - }); - router2.get("/companies/:companyId/live-runs", async (req, res) => { - const companyId = req.params.companyId; - assertCompanyAccess(req, companyId); - const minCountParam = req.query.minCount; - const minCount = minCountParam ? Math.max(0, Math.min(20, parseInt(minCountParam, 10) || 0)) : 0; - const columns = { - id: heartbeatRuns.id, - status: heartbeatRuns.status, - invocationSource: heartbeatRuns.invocationSource, - triggerDetail: heartbeatRuns.triggerDetail, - startedAt: heartbeatRuns.startedAt, - finishedAt: heartbeatRuns.finishedAt, - createdAt: heartbeatRuns.createdAt, - agentId: heartbeatRuns.agentId, - agentName: agents.name, - adapterType: agents.adapterType, - issueId: sql`${heartbeatRuns.contextSnapshot} ->> 'issueId'`.as("issueId") - }; - const liveRuns = await db.select(columns).from(heartbeatRuns).innerJoin(agents, eq(heartbeatRuns.agentId, agents.id)).where( - and( - eq(heartbeatRuns.companyId, companyId), - inArray(heartbeatRuns.status, ["queued", "running"]) - ) - ).orderBy(desc(heartbeatRuns.createdAt)); - if (minCount > 0 && liveRuns.length < minCount) { - const activeIds = liveRuns.map((r5) => r5.id); - const recentRuns = await db.select(columns).from(heartbeatRuns).innerJoin(agents, eq(heartbeatRuns.agentId, agents.id)).where( - and( - eq(heartbeatRuns.companyId, companyId), - not(inArray(heartbeatRuns.status, ["queued", "running"])), - ...activeIds.length > 0 ? [not(inArray(heartbeatRuns.id, activeIds))] : [] - ) - ).orderBy(desc(heartbeatRuns.createdAt)).limit(minCount - liveRuns.length); - res.json([...liveRuns, ...recentRuns]); - return; - } - res.json(liveRuns); - }); - router2.get("/heartbeat-runs/:runId", async (req, res) => { - const runId = req.params.runId; - const run = await heartbeat.getRun(runId); - if (!run) { - res.status(404).json({ error: "Heartbeat run not found" }); - return; - } - assertCompanyAccess(req, run.companyId); - res.json(redactCurrentUserValue(run, await getCurrentUserRedactionOptions())); - }); - router2.post("/heartbeat-runs/:runId/cancel", async (req, res) => { - assertBoard(req); - const runId = req.params.runId; - const existing = await heartbeat.getRun(runId); - if (existing) { - assertCompanyAccess(req, existing.companyId); - } - const run = await heartbeat.cancelRun(runId); - if (run) { - await logActivity(db, { - companyId: run.companyId, - actorType: "user", - actorId: req.actor.userId ?? "board", - action: "heartbeat.cancelled", - entityType: "heartbeat_run", - entityId: run.id, - details: { agentId: run.agentId } - }); - } - res.json(run); - }); - router2.get("/heartbeat-runs/:runId/events", async (req, res) => { - const runId = req.params.runId; - const run = await heartbeat.getRun(runId); - if (!run) { - res.status(404).json({ error: "Heartbeat run not found" }); - return; - } - assertCompanyAccess(req, run.companyId); - const afterSeq = Number(req.query.afterSeq ?? 0); - const limit = Number(req.query.limit ?? 200); - const events = await heartbeat.listEvents(runId, Number.isFinite(afterSeq) ? afterSeq : 0, Number.isFinite(limit) ? limit : 200); - const currentUserRedactionOptions = await getCurrentUserRedactionOptions(); - const redactedEvents = events.map( - (event) => redactCurrentUserValue({ - ...event, - payload: redactEventPayload(event.payload) - }, currentUserRedactionOptions) - ); - res.json(redactedEvents); - }); - router2.get("/heartbeat-runs/:runId/log", async (req, res) => { - const runId = req.params.runId; - const run = await heartbeat.getRun(runId); - if (!run) { - res.status(404).json({ error: "Heartbeat run not found" }); - return; - } - assertCompanyAccess(req, run.companyId); - const offset = Number(req.query.offset ?? 0); - const limitBytes = Number(req.query.limitBytes ?? 256e3); - const result = await heartbeat.readLog(runId, { - offset: Number.isFinite(offset) ? offset : 0, - limitBytes: Number.isFinite(limitBytes) ? limitBytes : 256e3 - }); - res.json(result); - }); - router2.get("/heartbeat-runs/:runId/workspace-operations", async (req, res) => { - const runId = req.params.runId; - const run = await heartbeat.getRun(runId); - if (!run) { - res.status(404).json({ error: "Heartbeat run not found" }); - return; - } - assertCompanyAccess(req, run.companyId); - const context = asRecord8(run.contextSnapshot); - const executionWorkspaceId = asNonEmptyString(context?.executionWorkspaceId); - const operations = await workspaceOperations2.listForRun(runId, executionWorkspaceId); - res.json(redactCurrentUserValue(operations, await getCurrentUserRedactionOptions())); - }); - router2.get("/workspace-operations/:operationId/log", async (req, res) => { - const operationId = req.params.operationId; - const operation2 = await workspaceOperations2.getById(operationId); - if (!operation2) { - res.status(404).json({ error: "Workspace operation not found" }); - return; - } - assertCompanyAccess(req, operation2.companyId); - const offset = Number(req.query.offset ?? 0); - const limitBytes = Number(req.query.limitBytes ?? 256e3); - const result = await workspaceOperations2.readLog(operationId, { - offset: Number.isFinite(offset) ? offset : 0, - limitBytes: Number.isFinite(limitBytes) ? limitBytes : 256e3 - }); - res.json(result); - }); - router2.get("/issues/:issueId/live-runs", async (req, res) => { - const rawId = req.params.issueId; - const issueSvc = issueService(db); - const isIdentifier = /^[A-Z]+-\d+$/i.test(rawId); - const issue2 = isIdentifier ? await issueSvc.getByIdentifier(rawId) : await issueSvc.getById(rawId); - if (!issue2) { - res.status(404).json({ error: "Issue not found" }); - return; - } - assertCompanyAccess(req, issue2.companyId); - const liveRuns = await db.select({ - id: heartbeatRuns.id, - status: heartbeatRuns.status, - invocationSource: heartbeatRuns.invocationSource, - triggerDetail: heartbeatRuns.triggerDetail, - startedAt: heartbeatRuns.startedAt, - finishedAt: heartbeatRuns.finishedAt, - createdAt: heartbeatRuns.createdAt, - agentId: heartbeatRuns.agentId, - agentName: agents.name, - adapterType: agents.adapterType - }).from(heartbeatRuns).innerJoin(agents, eq(heartbeatRuns.agentId, agents.id)).where( - and( - eq(heartbeatRuns.companyId, issue2.companyId), - inArray(heartbeatRuns.status, ["queued", "running"]), - sql`${heartbeatRuns.contextSnapshot} ->> 'issueId' = ${issue2.id}` - ) - ).orderBy(desc(heartbeatRuns.createdAt)); - res.json(liveRuns); - }); - router2.get("/issues/:issueId/active-run", async (req, res) => { - const rawId = req.params.issueId; - const issueSvc = issueService(db); - const isIdentifier = /^[A-Z]+-\d+$/i.test(rawId); - const issue2 = isIdentifier ? await issueSvc.getByIdentifier(rawId) : await issueSvc.getById(rawId); - if (!issue2) { - res.status(404).json({ error: "Issue not found" }); - return; - } - assertCompanyAccess(req, issue2.companyId); - let run = issue2.executionRunId ? await heartbeat.getRunIssueSummary(issue2.executionRunId) : null; - if (run && (run.status !== "queued" && run.status !== "running" || run.issueId !== issue2.id)) { - run = null; - } - if (!run && issue2.assigneeAgentId && issue2.status === "in_progress") { - const candidateRun = await heartbeat.getActiveRunIssueSummaryForAgent(issue2.assigneeAgentId); - const candidateIssueId = asNonEmptyString(candidateRun?.issueId); - if (candidateRun && candidateIssueId === issue2.id) { - run = candidateRun; - } - } - if (!run) { - res.json(null); - return; - } - const agent = await svc.getById(run.agentId); - if (!agent) { - res.json(null); - return; - } - res.json({ - ...run, - agentId: agent.id, - agentName: agent.name, - adapterType: agent.adapterType - }); - }); - return router2; -} - -// server/src/routes/projects.ts -var import_express5 = __toESM(require_express2(), 1); -function projectRoutes(db) { - const router2 = (0, import_express5.Router)(); - const svc = projectService(db); - const secretsSvc = secretService(db); - const workspaceOperations2 = workspaceOperationService(db); - const strictSecretsMode = process.env.TASKCORE_SECRETS_STRICT_MODE === "true"; - async function resolveCompanyIdForProjectReference(req) { - const companyIdQuery = req.query.companyId; - const requestedCompanyId = typeof companyIdQuery === "string" && companyIdQuery.trim().length > 0 ? companyIdQuery.trim() : null; - if (requestedCompanyId) { - assertCompanyAccess(req, requestedCompanyId); - return requestedCompanyId; - } - if (req.actor.type === "agent" && req.actor.companyId) { - return req.actor.companyId; - } - return null; - } - async function normalizeProjectReference(req, rawId) { - if (isUuidLike(rawId)) return rawId; - const companyId = await resolveCompanyIdForProjectReference(req); - if (!companyId) return rawId; - const resolved = await svc.resolveByReference(companyId, rawId); - if (resolved.ambiguous) { - throw conflict("Project shortname is ambiguous in this company. Use the project ID."); - } - return resolved.project?.id ?? rawId; - } - router2.param("id", async (req, _res, next, rawId) => { - try { - req.params.id = await normalizeProjectReference(req, rawId); - next(); - } catch (err) { - next(err); - } - }); - router2.get("/companies/:companyId/projects", async (req, res) => { - const companyId = req.params.companyId; - assertCompanyAccess(req, companyId); - const result = await svc.list(companyId); - res.json(result); - }); - router2.get("/projects/:id", async (req, res) => { - const id = req.params.id; - const project = await svc.getById(id); - if (!project) { - res.status(404).json({ error: "Project not found" }); - return; - } - assertCompanyAccess(req, project.companyId); - res.json(project); - }); - router2.post("/companies/:companyId/projects", validate(createProjectSchema), async (req, res) => { - const companyId = req.params.companyId; - assertCompanyAccess(req, companyId); - const { workspace, ...projectData } = req.body; - if (projectData.env !== void 0) { - projectData.env = await secretsSvc.normalizeEnvBindingsForPersistence( - companyId, - projectData.env, - { strictMode: strictSecretsMode, fieldPath: "env" } - ); - } - const project = await svc.create(companyId, projectData); - let createdWorkspaceId = null; - if (workspace) { - const createdWorkspace = await svc.createWorkspace(project.id, workspace); - if (!createdWorkspace) { - await svc.remove(project.id); - res.status(422).json({ error: "Invalid project workspace payload" }); - return; - } - createdWorkspaceId = createdWorkspace.id; - } - const hydratedProject = workspace ? await svc.getById(project.id) : project; - const actor = getActorInfo(req); - await logActivity(db, { - companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - action: "project.created", - entityType: "project", - entityId: project.id, - details: { - name: project.name, - workspaceId: createdWorkspaceId, - envKeys: project.env ? Object.keys(project.env).sort() : [] - } - }); - const telemetryClient = getTelemetryClient(); - if (telemetryClient) { - trackProjectCreated(telemetryClient); - } - res.status(201).json(hydratedProject ?? project); - }); - router2.patch("/projects/:id", validate(updateProjectSchema), async (req, res) => { - const id = req.params.id; - const existing = await svc.getById(id); - if (!existing) { - res.status(404).json({ error: "Project not found" }); - return; - } - assertCompanyAccess(req, existing.companyId); - const body = { ...req.body }; - if (typeof body.archivedAt === "string") { - body.archivedAt = new Date(body.archivedAt); - } - if (body.env !== void 0) { - body.env = await secretsSvc.normalizeEnvBindingsForPersistence(existing.companyId, body.env, { - strictMode: strictSecretsMode, - fieldPath: "env" - }); - } - const project = await svc.update(id, body); - if (!project) { - res.status(404).json({ error: "Project not found" }); - return; - } - const actor = getActorInfo(req); - await logActivity(db, { - companyId: project.companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - action: "project.updated", - entityType: "project", - entityId: project.id, - details: { - changedKeys: Object.keys(req.body).sort(), - envKeys: body.env && typeof body.env === "object" && !Array.isArray(body.env) ? Object.keys(body.env).sort() : void 0 - } - }); - res.json(project); - }); - router2.get("/projects/:id/workspaces", async (req, res) => { - const id = req.params.id; - const existing = await svc.getById(id); - if (!existing) { - res.status(404).json({ error: "Project not found" }); - return; - } - assertCompanyAccess(req, existing.companyId); - const workspaces = await svc.listWorkspaces(id); - res.json(workspaces); - }); - router2.post("/projects/:id/workspaces", validate(createProjectWorkspaceSchema), async (req, res) => { - const id = req.params.id; - const existing = await svc.getById(id); - if (!existing) { - res.status(404).json({ error: "Project not found" }); - return; - } - assertCompanyAccess(req, existing.companyId); - const workspace = await svc.createWorkspace(id, req.body); - if (!workspace) { - res.status(422).json({ error: "Invalid project workspace payload" }); - return; - } - const actor = getActorInfo(req); - await logActivity(db, { - companyId: existing.companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - action: "project.workspace_created", - entityType: "project", - entityId: id, - details: { - workspaceId: workspace.id, - name: workspace.name, - cwd: workspace.cwd, - isPrimary: workspace.isPrimary - } - }); - res.status(201).json(workspace); - }); - router2.patch( - "/projects/:id/workspaces/:workspaceId", - validate(updateProjectWorkspaceSchema), - async (req, res) => { - const id = req.params.id; - const workspaceId = req.params.workspaceId; - const existing = await svc.getById(id); - if (!existing) { - res.status(404).json({ error: "Project not found" }); - return; - } - assertCompanyAccess(req, existing.companyId); - const workspaceExists = (await svc.listWorkspaces(id)).some((workspace2) => workspace2.id === workspaceId); - if (!workspaceExists) { - res.status(404).json({ error: "Project workspace not found" }); - return; - } - const workspace = await svc.updateWorkspace(id, workspaceId, req.body); - if (!workspace) { - res.status(422).json({ error: "Invalid project workspace payload" }); - return; - } - const actor = getActorInfo(req); - await logActivity(db, { - companyId: existing.companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - action: "project.workspace_updated", - entityType: "project", - entityId: id, - details: { - workspaceId: workspace.id, - changedKeys: Object.keys(req.body).sort() - } - }); - res.json(workspace); - } - ); - async function handleProjectWorkspaceRuntimeCommand(req, res) { - const id = req.params.id; - const workspaceId = req.params.workspaceId; - const action = String(req.params.action ?? "").trim().toLowerCase(); - if (action !== "start" && action !== "stop" && action !== "restart" && action !== "run") { - res.status(404).json({ error: "Workspace command action not found" }); - return; - } - const project = await svc.getById(id); - if (!project) { - res.status(404).json({ error: "Project not found" }); - return; - } - assertCompanyAccess(req, project.companyId); - const workspace = project.workspaces.find((entry) => entry.id === workspaceId) ?? null; - if (!workspace) { - res.status(404).json({ error: "Project workspace not found" }); - return; - } - const workspaceCwd = workspace.cwd; - if (!workspaceCwd) { - res.status(422).json({ error: "Project workspace needs a local path before Taskcore can run workspace commands" }); - return; - } - const runtimeConfig = workspace.runtimeConfig?.workspaceRuntime ?? null; - const target = req.body; - const configuredServices = runtimeConfig ? listConfiguredRuntimeServiceEntries({ workspaceRuntime: runtimeConfig }) : []; - const workspaceCommand = runtimeConfig ? findWorkspaceCommandDefinition(runtimeConfig, target.workspaceCommandId ?? null) : null; - if (target.workspaceCommandId && !workspaceCommand) { - res.status(404).json({ error: "Workspace command not found for this project workspace" }); - return; - } - if (target.runtimeServiceId && !(workspace.runtimeServices ?? []).some((service) => service.id === target.runtimeServiceId)) { - res.status(404).json({ error: "Runtime service not found for this project workspace" }); - return; - } - const matchedRuntimeService = workspaceCommand?.kind === "service" && !target.runtimeServiceId ? matchWorkspaceRuntimeServiceToCommand(workspaceCommand, workspace.runtimeServices ?? []) : null; - const selectedRuntimeServiceId = target.runtimeServiceId ?? matchedRuntimeService?.id ?? null; - const selectedServiceIndex = workspaceCommand?.kind === "service" ? workspaceCommand.serviceIndex : target.serviceIndex ?? null; - if (selectedServiceIndex !== void 0 && selectedServiceIndex !== null && (selectedServiceIndex < 0 || selectedServiceIndex >= configuredServices.length)) { - res.status(422).json({ error: "Selected runtime service is not defined in this project workspace runtime config" }); - return; - } - if (workspaceCommand?.kind === "job" && action !== "run") { - res.status(422).json({ error: `Workspace job "${workspaceCommand.name}" can only be run` }); - return; - } - if (workspaceCommand?.kind === "service" && action === "run") { - res.status(422).json({ error: `Workspace service "${workspaceCommand.name}" should be started or restarted, not run` }); - return; - } - if (action === "run" && !workspaceCommand) { - res.status(422).json({ error: "Select a workspace job to run" }); - return; - } - if ((action === "start" || action === "restart") && !runtimeConfig) { - res.status(422).json({ error: "Project workspace has no workspace command configuration" }); - return; - } - const actor = getActorInfo(req); - const recorder = workspaceOperations2.createRecorder({ companyId: project.companyId }); - let runtimeServiceCount = workspace.runtimeServices?.length ?? 0; - const stdout = []; - const stderr = []; - const operation2 = await recorder.recordOperation({ - phase: action === "stop" ? "workspace_teardown" : "workspace_provision", - command: workspaceCommand?.command ?? `workspace command ${action}`, - cwd: workspace.cwd, - metadata: { - action, - projectId: project.id, - projectWorkspaceId: workspace.id, - workspaceCommandId: workspaceCommand?.id ?? target.workspaceCommandId ?? null, - workspaceCommandKind: workspaceCommand?.kind ?? null, - workspaceCommandName: workspaceCommand?.name ?? null, - runtimeServiceId: selectedRuntimeServiceId, - serviceIndex: selectedServiceIndex - }, - run: async () => { - if (action === "run") { - if (!workspaceCommand || workspaceCommand.kind !== "job") { - throw new Error("Workspace job selection is required"); - } - return await runWorkspaceJobForControl({ - actor: { - id: actor.agentId ?? null, - name: actor.actorType === "user" ? "Board" : "Agent", - companyId: project.companyId - }, - issue: null, - workspace: { - baseCwd: workspaceCwd, - source: "project_primary", - projectId: project.id, - workspaceId: workspace.id, - repoUrl: workspace.repoUrl, - repoRef: workspace.repoRef, - strategy: "project_primary", - cwd: workspaceCwd, - branchName: workspace.defaultRef ?? workspace.repoRef ?? null, - worktreePath: null, - warnings: [], - created: false - }, - command: workspaceCommand.rawConfig, - adapterEnv: {}, - recorder, - metadata: { - action, - projectId: project.id, - projectWorkspaceId: workspace.id, - workspaceCommandId: workspaceCommand.id - } - }).then((nestedOperation) => ({ - status: "succeeded", - exitCode: 0, - metadata: { - nestedOperationId: nestedOperation?.id ?? null, - runtimeServiceCount - } - })); - } - const onLog = async (stream, chunk) => { - if (stream === "stdout") stdout.push(chunk); - else stderr.push(chunk); - }; - if (action === "stop" || action === "restart") { - await stopRuntimeServicesForProjectWorkspace({ - db, - projectWorkspaceId: workspace.id, - runtimeServiceId: selectedRuntimeServiceId - }); - } - if (action === "start" || action === "restart") { - const startedServices = await startRuntimeServicesForWorkspaceControl({ - db, - actor: { - id: actor.agentId ?? null, - name: actor.actorType === "user" ? "Board" : "Agent", - companyId: project.companyId - }, - issue: null, - workspace: { - baseCwd: workspaceCwd, - source: "project_primary", - projectId: project.id, - workspaceId: workspace.id, - repoUrl: workspace.repoUrl, - repoRef: workspace.repoRef, - strategy: "project_primary", - cwd: workspaceCwd, - branchName: workspace.defaultRef ?? workspace.repoRef ?? null, - worktreePath: null, - warnings: [], - created: false - }, - config: { workspaceRuntime: runtimeConfig }, - adapterEnv: {}, - onLog, - serviceIndex: selectedServiceIndex - }); - runtimeServiceCount = startedServices.length; - } else { - runtimeServiceCount = selectedRuntimeServiceId ? Math.max(0, (workspace.runtimeServices?.length ?? 1) - 1) : 0; - } - const currentDesiredState = workspace.runtimeConfig?.desiredState ?? ((workspace.runtimeServices ?? []).some((service) => service.status === "starting" || service.status === "running") ? "running" : "stopped"); - const nextRuntimeState = selectedRuntimeServiceId && (selectedServiceIndex === void 0 || selectedServiceIndex === null) ? { - desiredState: currentDesiredState, - serviceStates: workspace.runtimeConfig?.serviceStates ?? null - } : buildWorkspaceRuntimeDesiredStatePatch({ - config: { workspaceRuntime: runtimeConfig }, - currentDesiredState, - currentServiceStates: workspace.runtimeConfig?.serviceStates ?? null, - action, - serviceIndex: selectedServiceIndex - }); - await svc.updateWorkspace(project.id, workspace.id, { - runtimeConfig: { - desiredState: nextRuntimeState.desiredState, - serviceStates: nextRuntimeState.serviceStates - } - }); - return { - status: "succeeded", - stdout: stdout.join(""), - stderr: stderr.join(""), - system: action === "stop" ? "Stopped project workspace runtime services.\n" : action === "restart" ? "Restarted project workspace runtime services.\n" : "Started project workspace runtime services.\n", - metadata: { - runtimeServiceCount, - workspaceCommandId: workspaceCommand?.id ?? target.workspaceCommandId ?? null, - runtimeServiceId: selectedRuntimeServiceId, - serviceIndex: selectedServiceIndex - } - }; - } - }); - const updatedWorkspace = (await svc.listWorkspaces(project.id)).find((entry) => entry.id === workspace.id) ?? workspace; - await logActivity(db, { - companyId: project.companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - action: `project.workspace_runtime_${action}`, - entityType: "project", - entityId: project.id, - details: { - projectWorkspaceId: workspace.id, - runtimeServiceCount, - workspaceCommandId: workspaceCommand?.id ?? target.workspaceCommandId ?? null, - workspaceCommandKind: workspaceCommand?.kind ?? null, - workspaceCommandName: workspaceCommand?.name ?? null, - runtimeServiceId: selectedRuntimeServiceId, - serviceIndex: selectedServiceIndex - } - }); - res.json({ - workspace: updatedWorkspace, - operation: operation2 - }); - } - router2.post("/projects/:id/workspaces/:workspaceId/runtime-services/:action", validate(workspaceRuntimeControlTargetSchema), handleProjectWorkspaceRuntimeCommand); - router2.post("/projects/:id/workspaces/:workspaceId/runtime-commands/:action", validate(workspaceRuntimeControlTargetSchema), handleProjectWorkspaceRuntimeCommand); - router2.delete("/projects/:id/workspaces/:workspaceId", async (req, res) => { - const id = req.params.id; - const workspaceId = req.params.workspaceId; - const existing = await svc.getById(id); - if (!existing) { - res.status(404).json({ error: "Project not found" }); - return; - } - assertCompanyAccess(req, existing.companyId); - const workspace = await svc.removeWorkspace(id, workspaceId); - if (!workspace) { - res.status(404).json({ error: "Project workspace not found" }); - return; - } - const actor = getActorInfo(req); - await logActivity(db, { - companyId: existing.companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - action: "project.workspace_deleted", - entityType: "project", - entityId: id, - details: { - workspaceId: workspace.id, - name: workspace.name - } - }); - res.json(workspace); - }); - router2.delete("/projects/:id", async (req, res) => { - const id = req.params.id; - const existing = await svc.getById(id); - if (!existing) { - res.status(404).json({ error: "Project not found" }); - return; - } - assertCompanyAccess(req, existing.companyId); - const project = await svc.remove(id); - if (!project) { - res.status(404).json({ error: "Project not found" }); - return; - } - const actor = getActorInfo(req); - await logActivity(db, { - companyId: project.companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - action: "project.deleted", - entityType: "project", - entityId: project.id - }); - res.json(project); - }); - return router2; -} - -// server/src/routes/issues.ts -var import_express6 = __toESM(require_express2(), 1); -var import_multer = __toESM(require_multer(), 1); -import { randomUUID as randomUUID9 } from "node:crypto"; -init_src2(); - -// server/src/routes/issues-checkout-wakeup.ts -function shouldWakeAssigneeOnCheckout(input) { - if (input.actorType !== "agent") return true; - if (!input.actorAgentId) return true; - if (input.actorAgentId !== input.checkoutAgentId) return true; - if (!input.checkoutRunId) return true; - return false; -} - -// server/src/attachment-types.ts -var DEFAULT_ALLOWED_TYPES = [ - "image/png", - "image/jpeg", - "image/jpg", - "image/webp", - "image/gif", - "application/pdf", - "text/markdown", - "text/plain", - "application/json", - "text/csv", - "text/html" -]; -var DEFAULT_ATTACHMENT_CONTENT_TYPE = "application/octet-stream"; -var SVG_CONTENT_TYPE = "image/svg+xml"; -var INLINE_ATTACHMENT_TYPES = [ - "image/*", - "application/pdf", - "text/plain", - "text/markdown", - "application/json", - "text/csv" -]; -function parseAllowedTypes(raw) { - if (!raw) return [...DEFAULT_ALLOWED_TYPES]; - const parsed = raw.split(",").map((s5) => s5.trim().toLowerCase()).filter((s5) => s5.length > 0); - return parsed.length > 0 ? parsed : [...DEFAULT_ALLOWED_TYPES]; -} -function matchesContentType(contentType, allowedPatterns2) { - const ct = contentType.toLowerCase(); - return allowedPatterns2.some((pattern) => { - if (pattern === "*") return true; - if (pattern.endsWith("/*") || pattern.endsWith(".*")) { - return ct.startsWith(pattern.slice(0, -1)); - } - return ct === pattern; - }); -} -function normalizeContentType(contentType) { - const normalized = (contentType ?? "").trim().toLowerCase(); - return normalized || DEFAULT_ATTACHMENT_CONTENT_TYPE; -} -function isInlineAttachmentContentType(contentType) { - return matchesContentType(contentType, [...INLINE_ATTACHMENT_TYPES]); -} -var allowedPatterns = parseAllowedTypes( - process.env.TASKCORE_ALLOWED_ATTACHMENT_TYPES -); -function isAllowedContentType(contentType) { - return matchesContentType(contentType, allowedPatterns); -} -var MAX_ATTACHMENT_BYTES = Number(process.env.TASKCORE_ATTACHMENT_MAX_BYTES) || 10 * 1024 * 1024; - -// server/src/services/issue-execution-policy.ts -import { randomUUID as randomUUID8 } from "node:crypto"; -var COMPLETED_STATUS = "completed"; -var PENDING_STATUS = "pending"; -var CHANGES_REQUESTED_STATUS = "changes_requested"; -function normalizeIssueExecutionPolicy(input) { - if (input == null) return null; - const parsed = issueExecutionPolicySchema.safeParse(input); - if (!parsed.success) { - throw unprocessable("Invalid execution policy", parsed.error.flatten()); - } - const stages = parsed.data.stages.map((stage) => { - const participants = stage.participants.map((participant) => ({ - id: participant.id ?? randomUUID8(), - type: participant.type, - agentId: participant.type === "agent" ? participant.agentId ?? null : null, - userId: participant.type === "user" ? participant.userId ?? null : null - })).filter((participant) => participant.type === "agent" ? Boolean(participant.agentId) : Boolean(participant.userId)); - const dedupedParticipants = []; - const seen = /* @__PURE__ */ new Set(); - for (const participant of participants) { - const key = participant.type === "agent" ? `agent:${participant.agentId}` : `user:${participant.userId}`; - if (seen.has(key)) continue; - seen.add(key); - dedupedParticipants.push(participant); - } - if (dedupedParticipants.length === 0) return null; - return { - id: stage.id ?? randomUUID8(), - type: stage.type, - approvalsNeeded: 1, - participants: dedupedParticipants - }; - }).filter((stage) => stage !== null); - if (stages.length === 0) return null; - return { - mode: parsed.data.mode ?? "normal", - commentRequired: true, - stages - }; -} -function parseIssueExecutionState(input) { - if (input == null) return null; - const parsed = issueExecutionStateSchema.safeParse(input); - if (!parsed.success) return null; - return parsed.data; -} -function assigneePrincipal(input) { - if (input.assigneeAgentId) { - return { type: "agent", agentId: input.assigneeAgentId, userId: null }; - } - if (input.assigneeUserId) { - return { type: "user", userId: input.assigneeUserId, agentId: null }; - } - return null; -} -function actorPrincipal(actor) { - if (actor.agentId) return { type: "agent", agentId: actor.agentId, userId: null }; - if (actor.userId) return { type: "user", userId: actor.userId, agentId: null }; - return null; -} -function principalsEqual(a5, b6) { - if (!a5 || !b6) return false; - if (a5.type !== b6.type) return false; - return a5.type === "agent" ? a5.agentId === b6.agentId : a5.userId === b6.userId; -} -function findStageById(policy, stageId) { - if (!stageId) return null; - return policy.stages.find((stage) => stage.id === stageId) ?? null; -} -function nextPendingStage(policy, state2) { - const completed = new Set(state2?.completedStageIds ?? []); - return policy.stages.find((stage) => !completed.has(stage.id)) ?? null; -} -function selectStageParticipant(stage, opts) { - const participants = stage.participants.filter((participant) => !principalsEqual(participant, opts?.exclude ?? null)); - if (participants.length === 0) return null; - if (opts?.preferred) { - const preferred = participants.find((participant) => principalsEqual(participant, opts.preferred ?? null)); - if (preferred) return preferred; - } - const first = participants[0]; - return first ? { type: first.type, agentId: first.agentId ?? null, userId: first.userId ?? null } : null; -} -function stageHasParticipant(stage, participant) { - if (!participant) return false; - return stage.participants.some((candidate) => principalsEqual(candidate, participant)); -} -function patchForPrincipal(principal) { - if (!principal) { - return { assigneeAgentId: null, assigneeUserId: null }; - } - return principal.type === "agent" ? { assigneeAgentId: principal.agentId ?? null, assigneeUserId: null } : { assigneeAgentId: null, assigneeUserId: principal.userId ?? null }; -} -function buildCompletedState(previous, currentStage) { - const completedStageIds = Array.from(/* @__PURE__ */ new Set([...previous?.completedStageIds ?? [], currentStage.id])); - return { - status: COMPLETED_STATUS, - currentStageId: null, - currentStageIndex: null, - currentStageType: null, - currentParticipant: null, - returnAssignee: previous?.returnAssignee ?? null, - completedStageIds, - lastDecisionId: previous?.lastDecisionId ?? null, - lastDecisionOutcome: "approved" - }; -} -function buildStateWithCompletedStages(input) { - return { - status: input.previous?.status ?? PENDING_STATUS, - currentStageId: input.previous?.currentStageId ?? null, - currentStageIndex: input.previous?.currentStageIndex ?? null, - currentStageType: input.previous?.currentStageType ?? null, - currentParticipant: input.previous?.currentParticipant ?? null, - returnAssignee: input.previous?.returnAssignee ?? input.returnAssignee, - completedStageIds: input.completedStageIds, - lastDecisionId: input.previous?.lastDecisionId ?? null, - lastDecisionOutcome: input.previous?.lastDecisionOutcome ?? null - }; -} -function buildSkippedStageCompletedState(input) { - return { - status: COMPLETED_STATUS, - currentStageId: null, - currentStageIndex: null, - currentStageType: null, - currentParticipant: null, - returnAssignee: input.previous?.returnAssignee ?? input.returnAssignee, - completedStageIds: input.completedStageIds, - lastDecisionId: input.previous?.lastDecisionId ?? null, - lastDecisionOutcome: input.previous?.lastDecisionOutcome ?? null - }; -} -function buildPendingState(input) { - return { - status: PENDING_STATUS, - currentStageId: input.stage.id, - currentStageIndex: input.stageIndex, - currentStageType: input.stage.type, - currentParticipant: input.participant, - returnAssignee: input.returnAssignee, - completedStageIds: input.previous?.completedStageIds ?? [], - lastDecisionId: input.previous?.lastDecisionId ?? null, - lastDecisionOutcome: input.previous?.lastDecisionOutcome ?? null - }; -} -function buildChangesRequestedState(previous, currentStage) { - return { - ...previous, - status: CHANGES_REQUESTED_STATUS, - currentStageId: currentStage.id, - currentStageType: currentStage.type, - lastDecisionOutcome: "changes_requested" - }; -} -function buildPendingStagePatch(input) { - input.patch.status = "in_review"; - Object.assign(input.patch, patchForPrincipal(input.participant)); - input.patch.executionState = buildPendingState({ - previous: input.previous, - stage: input.stage, - stageIndex: input.policy.stages.findIndex((candidate) => candidate.id === input.stage.id), - participant: input.participant, - returnAssignee: input.returnAssignee - }); -} -function clearExecutionStatePatch(input) { - input.patch.executionState = null; - if (input.requestedStatus === void 0 && input.issueStatus === "in_review" && input.returnAssignee) { - input.patch.status = "in_progress"; - Object.assign(input.patch, patchForPrincipal(input.returnAssignee)); - } -} -function canAutoSkipPendingStage(input) { - if (input.requestedStatus !== "done" || input.stage.type !== "review" || !input.returnAssignee) { - return false; - } - return input.stage.participants.length > 0 && input.stage.participants.every((participant) => principalsEqual(participant, input.returnAssignee)); -} -function applyIssueExecutionPolicyTransition(input) { - const patch = {}; - const existingState = parseIssueExecutionState(input.issue.executionState); - const currentAssignee = assigneePrincipal(input.issue); - const actor = actorPrincipal(input.actor); - const requestedAssigneePatchProvided = input.requestedAssigneePatch.assigneeAgentId !== void 0 || input.requestedAssigneePatch.assigneeUserId !== void 0; - const explicitAssignee = assigneePrincipal(input.requestedAssigneePatch); - const currentStage = input.policy ? findStageById(input.policy, existingState?.currentStageId) : null; - const requestedStatus = input.requestedStatus; - const activeStage = currentStage && existingState?.status === PENDING_STATUS ? currentStage : null; - if (!input.policy) { - if (existingState) { - patch.executionState = null; - if (input.issue.status === "in_review" && existingState.returnAssignee) { - patch.status = "in_progress"; - Object.assign(patch, patchForPrincipal(existingState.returnAssignee)); - } - } - return { patch }; - } - if ((input.issue.status === "done" || input.issue.status === "cancelled") && requestedStatus && requestedStatus !== "done" && requestedStatus !== "cancelled") { - patch.executionState = null; - return { patch }; - } - if (existingState?.currentStageId && !currentStage) { - clearExecutionStatePatch({ - patch, - issueStatus: input.issue.status, - requestedStatus, - returnAssignee: existingState.returnAssignee - }); - return { patch }; - } - if (activeStage) { - const currentParticipant = existingState?.currentParticipant ?? selectStageParticipant(activeStage, { - exclude: existingState?.returnAssignee ?? null - }); - if (!currentParticipant) { - throw unprocessable(`No eligible ${activeStage.type} participant is configured for this issue`); - } - if (!stageHasParticipant(activeStage, currentParticipant)) { - const participant2 = selectStageParticipant(activeStage, { - preferred: explicitAssignee ?? existingState?.currentParticipant ?? null, - exclude: existingState?.returnAssignee ?? null - }); - if (!participant2) { - clearExecutionStatePatch({ - patch, - issueStatus: input.issue.status, - requestedStatus, - returnAssignee: existingState?.returnAssignee ?? null - }); - return { patch }; - } - buildPendingStagePatch({ - patch, - previous: existingState, - policy: input.policy, - stage: activeStage, - participant: participant2, - returnAssignee: existingState?.returnAssignee ?? currentAssignee ?? actor - }); - return { - patch, - workflowControlledAssignment: true - }; - } - if (principalsEqual(currentParticipant, actor)) { - if (requestedStatus === "done") { - if (!input.commentBody?.trim()) { - throw unprocessable("Approving a review or approval stage requires a comment"); - } - const approvedState = buildCompletedState(existingState, activeStage); - const nextStage = nextPendingStage( - input.policy, - { ...approvedState, completedStageIds: approvedState.completedStageIds } - ); - if (!nextStage) { - patch.executionState = approvedState; - return { - patch, - decision: { - stageId: activeStage.id, - stageType: activeStage.type, - outcome: "approved", - body: input.commentBody.trim() - } - }; - } - const participant2 = selectStageParticipant(nextStage, { - preferred: explicitAssignee, - exclude: existingState?.returnAssignee ?? null - }); - if (!participant2) { - throw unprocessable(`No eligible ${nextStage.type} participant is configured for this issue`); - } - buildPendingStagePatch({ - patch, - previous: approvedState, - policy: input.policy, - stage: nextStage, - participant: participant2, - returnAssignee: existingState?.returnAssignee ?? currentAssignee ?? actor - }); - return { - patch, - decision: { - stageId: activeStage.id, - stageType: activeStage.type, - outcome: "approved", - body: input.commentBody.trim() - }, - workflowControlledAssignment: true - }; - } - if (requestedStatus && requestedStatus !== "in_review") { - if (!input.commentBody?.trim()) { - throw unprocessable("Requesting changes requires a comment"); - } - if (!existingState?.returnAssignee) { - throw unprocessable("This execution stage has no return assignee"); - } - patch.status = "in_progress"; - Object.assign(patch, patchForPrincipal(existingState.returnAssignee)); - patch.executionState = buildChangesRequestedState(existingState, activeStage); - return { - patch, - decision: { - stageId: activeStage.id, - stageType: activeStage.type, - outcome: "changes_requested", - body: input.commentBody.trim() - }, - workflowControlledAssignment: true - }; - } - } - const attemptedStageAdvance = requestedStatus !== void 0 && requestedStatus !== "in_review" || requestedAssigneePatchProvided && !principalsEqual(explicitAssignee, currentParticipant); - const stageStateDrifted = input.issue.status !== "in_review" || !principalsEqual(currentAssignee, currentParticipant) || !principalsEqual(existingState?.currentParticipant ?? null, currentParticipant); - if (attemptedStageAdvance && !stageStateDrifted) { - throw unprocessable("Only the active reviewer or approver can advance the current execution stage"); - } - if (stageStateDrifted) { - buildPendingStagePatch({ - patch, - previous: existingState, - policy: input.policy, - stage: activeStage, - participant: currentParticipant, - returnAssignee: existingState?.returnAssignee ?? currentAssignee ?? actor - }); - return { - patch, - workflowControlledAssignment: true - }; - } - return { patch }; - } - const shouldStartWorkflow = requestedStatus === "done" || requestedStatus === "in_review"; - if (!shouldStartWorkflow) { - return { patch }; - } - let pendingStage = existingState?.status === CHANGES_REQUESTED_STATUS && currentStage ? currentStage : nextPendingStage(input.policy, existingState); - if (!pendingStage) return { patch }; - const returnAssignee = existingState?.returnAssignee ?? currentAssignee; - const skippedStageIds = [...existingState?.completedStageIds ?? []]; - let participant = selectStageParticipant(pendingStage, { - preferred: existingState?.status === CHANGES_REQUESTED_STATUS ? explicitAssignee ?? existingState.currentParticipant ?? null : explicitAssignee, - exclude: returnAssignee - }); - while (!participant && canAutoSkipPendingStage({ stage: pendingStage, returnAssignee, requestedStatus })) { - skippedStageIds.push(pendingStage.id); - pendingStage = nextPendingStage( - input.policy, - buildStateWithCompletedStages({ - previous: existingState, - completedStageIds: skippedStageIds, - returnAssignee - }) - ); - if (!pendingStage) { - patch.executionState = buildSkippedStageCompletedState({ - previous: existingState, - completedStageIds: skippedStageIds, - returnAssignee - }); - return { patch }; - } - participant = selectStageParticipant(pendingStage, { - preferred: existingState?.status === CHANGES_REQUESTED_STATUS ? explicitAssignee ?? existingState.currentParticipant ?? null : explicitAssignee, - exclude: returnAssignee - }); - } - if (!participant) { - throw unprocessable(`No eligible ${pendingStage.type} participant is configured for this issue`); - } - buildPendingStagePatch({ - patch, - previous: skippedStageIds.length === (existingState?.completedStageIds ?? []).length ? existingState : buildStateWithCompletedStages({ - previous: existingState, - completedStageIds: skippedStageIds, - returnAssignee - }), - policy: input.policy, - stage: pendingStage, - participant, - returnAssignee - }); - return { - patch, - workflowControlledAssignment: true - }; -} - -// server/src/routes/issues.ts -var MAX_ISSUE_COMMENT_LIMIT = 500; -var updateIssueRouteSchema = updateIssueSchema.extend({ - interrupt: external_exports.boolean().optional() -}); -function executionPrincipalsEqual(left, right) { - if (!left || !right || left.type !== right.type) return false; - return left.type === "agent" ? left.agentId === right.agentId : left.userId === right.userId; -} -function buildExecutionStageWakeContext(input) { - return { - wakeRole: input.wakeRole, - stageId: input.state.currentStageId, - stageType: input.state.currentStageType, - currentParticipant: input.state.currentParticipant, - returnAssignee: input.state.returnAssignee, - lastDecisionOutcome: input.state.lastDecisionOutcome, - allowedActions: input.allowedActions - }; -} -function summarizeIssueRelationForActivity(relation) { - return { - id: relation.id, - identifier: relation.identifier, - title: relation.title - }; -} -function activityExecutionParticipantKey(participant) { - return participant.type === "agent" ? `agent:${participant.agentId}` : `user:${participant.userId}`; -} -function summarizeExecutionParticipants(policy, stageType) { - const stage = policy?.stages.find((candidate) => candidate.type === stageType); - return stage?.participants.map((participant) => ({ - type: participant.type, - agentId: participant.agentId ?? null, - userId: participant.userId ?? null - })) ?? []; -} -function isClosedIssueStatus(status) { - return status === "done" || status === "cancelled"; -} -function shouldImplicitlyReopenCommentForAgent(input) { - if (!isClosedIssueStatus(input.issueStatus)) return false; - if (typeof input.assigneeAgentId !== "string" || input.assigneeAgentId.length === 0) return false; - if (input.actorType === "agent" && input.actorId === input.assigneeAgentId) return false; - return true; -} -function diffExecutionParticipants(previousPolicy, nextPolicy, stageType) { - const previousParticipants = summarizeExecutionParticipants(previousPolicy, stageType); - const nextParticipants = summarizeExecutionParticipants(nextPolicy, stageType); - const previousByKey = new Map(previousParticipants.map((participant) => [ - activityExecutionParticipantKey(participant), - participant - ])); - const nextByKey = new Map(nextParticipants.map((participant) => [ - activityExecutionParticipantKey(participant), - participant - ])); - return { - participants: nextParticipants, - addedParticipants: nextParticipants.filter((participant) => !previousByKey.has(activityExecutionParticipantKey(participant))), - removedParticipants: previousParticipants.filter((participant) => !nextByKey.has(activityExecutionParticipantKey(participant))) - }; -} -function buildExecutionStageWakeup(input) { - const { issueId, previousState, nextState, interruptedRunId } = input; - if (!nextState) return null; - if (nextState.status === "pending") { - const agentId = nextState.currentParticipant?.type === "agent" ? nextState.currentParticipant.agentId ?? null : null; - const stageChanged = previousState?.status !== "pending" || previousState?.currentStageId !== nextState.currentStageId || !executionPrincipalsEqual(previousState?.currentParticipant ?? null, nextState.currentParticipant ?? null); - if (!agentId || !stageChanged) return null; - const reason = nextState.currentStageType === "approval" ? "execution_approval_requested" : "execution_review_requested"; - const executionStage = buildExecutionStageWakeContext({ - state: nextState, - wakeRole: nextState.currentStageType === "approval" ? "approver" : "reviewer", - allowedActions: ["approve", "request_changes"] - }); - return { - agentId, - wakeup: { - source: "assignment", - triggerDetail: "system", - reason, - payload: { - issueId, - mutation: "update", - executionStage, - ...interruptedRunId ? { interruptedRunId } : {} - }, - requestedByActorType: input.requestedByActorType, - requestedByActorId: input.requestedByActorId, - contextSnapshot: { - issueId, - taskId: issueId, - wakeReason: reason, - source: "issue.execution_stage", - executionStage, - ...interruptedRunId ? { interruptedRunId } : {} - } - } - }; - } - if (nextState.status === "changes_requested") { - const agentId = nextState.returnAssignee?.type === "agent" ? nextState.returnAssignee.agentId ?? null : null; - const becameChangesRequested = previousState?.status !== "changes_requested" || previousState?.lastDecisionId !== nextState.lastDecisionId || !executionPrincipalsEqual(previousState?.returnAssignee ?? null, nextState.returnAssignee ?? null); - if (!agentId || !becameChangesRequested) return null; - const executionStage = buildExecutionStageWakeContext({ - state: nextState, - wakeRole: "executor", - allowedActions: ["address_changes", "resubmit"] - }); - return { - agentId, - wakeup: { - source: "assignment", - triggerDetail: "system", - reason: "execution_changes_requested", - payload: { - issueId, - mutation: "update", - executionStage, - ...interruptedRunId ? { interruptedRunId } : {} - }, - requestedByActorType: input.requestedByActorType, - requestedByActorId: input.requestedByActorId, - contextSnapshot: { - issueId, - taskId: issueId, - wakeReason: "execution_changes_requested", - source: "issue.execution_stage", - executionStage, - ...interruptedRunId ? { interruptedRunId } : {} - } - } - }; - } - return null; -} -function issueRoutes(db, storage, opts) { - const router2 = (0, import_express6.Router)(); - const svc = issueService(db); - const access = accessService(db); - const heartbeat = heartbeatService(db); - const feedback = feedbackService(db); - const instanceSettings2 = instanceSettingsService(db); - const agentsSvc = agentService(db); - const projectsSvc = projectService(db); - const goalsSvc = goalService(db); - const issueApprovalsSvc = issueApprovalService(db); - const executionWorkspacesSvc = executionWorkspaceService(db); - const workProductsSvc = workProductService(db); - const documentsSvc = documentService(db); - const routinesSvc = routineService(db); - const feedbackExportService = opts?.feedbackExportService; - const upload = (0, import_multer.default)({ - storage: import_multer.default.memoryStorage(), - limits: { fileSize: MAX_ATTACHMENT_BYTES, files: 1 } - }); - function withContentPath(attachment) { - return { - ...attachment, - contentPath: `/api/attachments/${attachment.id}/content` - }; - } - function parseBooleanQuery(value) { - return value === true || value === "true" || value === "1"; - } - function parseDateQuery(value, field) { - if (typeof value !== "string" || value.trim().length === 0) return void 0; - const parsed = new Date(value); - if (Number.isNaN(parsed.getTime())) { - throw new HttpError(400, `Invalid ${field} query value`); - } - return parsed; - } - async function runSingleFileUpload(req, res) { - await new Promise((resolve4, reject) => { - upload.single("file")(req, res, (err) => { - if (err) reject(err); - else resolve4(); - }); - }); - } - async function assertCanManageIssueApprovalLinks(req, res, companyId) { - assertCompanyAccess(req, companyId); - if (req.actor.type === "board") return true; - if (!req.actor.agentId) { - res.status(403).json({ error: "Agent authentication required" }); - return false; - } - const actorAgent = await agentsSvc.getById(req.actor.agentId); - if (!actorAgent || actorAgent.companyId !== companyId) { - res.status(403).json({ error: "Forbidden" }); - return false; - } - if (actorAgent.role === "ceo" || Boolean(actorAgent.permissions?.canCreateAgents)) return true; - res.status(403).json({ error: "Missing permission to link approvals" }); - return false; - } - function actorCanAccessCompany(req, companyId) { - if (req.actor.type === "none") return false; - if (req.actor.type === "agent") return req.actor.companyId === companyId; - if (req.actor.source === "local_implicit" || req.actor.isInstanceAdmin) return true; - return (req.actor.companyIds ?? []).includes(companyId); - } - function canCreateAgentsLegacy(agent) { - if (agent.role === "ceo") return true; - if (!agent.permissions || typeof agent.permissions !== "object") return false; - return Boolean(agent.permissions.canCreateAgents); - } - async function assertCanAssignTasks(req, companyId) { - assertCompanyAccess(req, companyId); - if (req.actor.type === "board") { - if (req.actor.source === "local_implicit" || req.actor.isInstanceAdmin) return; - const allowed2 = await access.canUser(companyId, req.actor.userId, "tasks:assign"); - if (!allowed2) throw forbidden("Missing permission: tasks:assign"); - return; - } - if (req.actor.type === "agent") { - if (!req.actor.agentId) throw forbidden("Agent authentication required"); - const allowedByGrant = await access.hasPermission(companyId, "agent", req.actor.agentId, "tasks:assign"); - if (allowedByGrant) return; - const actorAgent = await agentsSvc.getById(req.actor.agentId); - if (actorAgent && actorAgent.companyId === companyId && canCreateAgentsLegacy(actorAgent)) return; - throw forbidden("Missing permission: tasks:assign"); - } - throw unauthorized(); - } - function requireAgentRunId(req, res) { - if (req.actor.type !== "agent") return null; - const runId = req.actor.runId?.trim(); - if (runId) return runId; - res.status(401).json({ error: "Agent run id required" }); - return null; - } - async function assertAgentRunCheckoutOwnership(req, res, issue2) { - if (req.actor.type !== "agent") return true; - const actorAgentId = req.actor.agentId; - if (!actorAgentId) { - res.status(403).json({ error: "Agent authentication required" }); - return false; - } - if (issue2.status !== "in_progress" || issue2.assigneeAgentId !== actorAgentId) { - return true; - } - const runId = requireAgentRunId(req, res); - if (!runId) return false; - const ownership = await svc.assertCheckoutOwner(issue2.id, actorAgentId, runId); - if (ownership.adoptedFromRunId) { - const actor = getActorInfo(req); - await logActivity(db, { - companyId: issue2.companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - runId: actor.runId, - action: "issue.checkout_lock_adopted", - entityType: "issue", - entityId: issue2.id, - details: { - previousCheckoutRunId: ownership.adoptedFromRunId, - checkoutRunId: runId, - reason: "stale_checkout_run" - } - }); - } - return true; - } - async function resolveActiveIssueRun(issue2) { - let runToInterrupt = issue2.executionRunId ? await heartbeat.getRun(issue2.executionRunId) : null; - if ((!runToInterrupt || runToInterrupt.status !== "running") && issue2.assigneeAgentId) { - const activeRun = await heartbeat.getActiveRunForAgent(issue2.assigneeAgentId); - const activeIssueId = activeRun && activeRun.contextSnapshot && typeof activeRun.contextSnapshot === "object" && typeof activeRun.contextSnapshot.issueId === "string" ? activeRun.contextSnapshot.issueId : null; - if (activeRun && activeRun.status === "running" && activeIssueId === issue2.id) { - runToInterrupt = activeRun; - } - } - return runToInterrupt?.status === "running" ? runToInterrupt : null; - } - async function normalizeIssueAssigneeAgentReference(companyId, rawAssigneeAgentId) { - if (rawAssigneeAgentId === void 0 || rawAssigneeAgentId === null) { - return rawAssigneeAgentId; - } - const raw = rawAssigneeAgentId.trim(); - if (raw.length === 0) { - return rawAssigneeAgentId; - } - const resolved = await agentsSvc.resolveByReference(companyId, raw); - if (resolved.ambiguous) { - throw conflict("Agent shortname is ambiguous in this company. Use the agent ID."); - } - if (!resolved.agent) { - throw notFound("Agent not found"); - } - return resolved.agent.id; - } - function toValidTimestamp(value) { - if (!value) return null; - const timestamp2 = value instanceof Date ? value.getTime() : new Date(value).getTime(); - return Number.isFinite(timestamp2) ? timestamp2 : null; - } - function isQueuedIssueCommentForActiveRun(params) { - const activeRunStartedAtMs = toValidTimestamp(params.activeRun.startedAt) ?? toValidTimestamp(params.activeRun.createdAt); - const commentCreatedAtMs = toValidTimestamp(params.comment.createdAt); - if (activeRunStartedAtMs === null || commentCreatedAtMs === null) return false; - if (params.comment.authorAgentId && params.comment.authorAgentId === params.activeRun.agentId) return false; - return commentCreatedAtMs >= activeRunStartedAtMs; - } - async function getClosedIssueExecutionWorkspace(issue2) { - if (!issue2.executionWorkspaceId) return null; - const workspace = await executionWorkspacesSvc.getById(issue2.executionWorkspaceId); - if (!workspace || !isClosedIsolatedExecutionWorkspace(workspace)) return null; - return workspace; - } - function respondClosedIssueExecutionWorkspace(res, workspace) { - res.status(409).json({ - error: getClosedIsolatedExecutionWorkspaceMessage(workspace), - executionWorkspace: workspace - }); - } - async function normalizeIssueIdentifier(rawId) { - if (/^[A-Z]+-\d+$/i.test(rawId)) { - const issue2 = await svc.getByIdentifier(rawId); - if (issue2) { - return issue2.id; - } - } - return rawId; - } - async function resolveIssueProjectAndGoal(issue2) { - const projectPromise = issue2.projectId ? projectsSvc.getById(issue2.projectId) : Promise.resolve(null); - const directGoalPromise = issue2.goalId ? goalsSvc.getById(issue2.goalId) : Promise.resolve(null); - const [project, directGoal] = await Promise.all([projectPromise, directGoalPromise]); - if (directGoal) { - return { project, goal: directGoal }; - } - const projectGoalId = project?.goalId ?? project?.goalIds[0] ?? null; - if (projectGoalId) { - const projectGoal = await goalsSvc.getById(projectGoalId); - return { project, goal: projectGoal }; - } - if (!issue2.projectId) { - const defaultGoal = await goalsSvc.getDefaultCompanyGoal(issue2.companyId); - return { project, goal: defaultGoal }; - } - return { project, goal: null }; - } - router2.param("id", async (req, res, next, rawId) => { - try { - req.params.id = await normalizeIssueIdentifier(rawId); - next(); - } catch (err) { - next(err); - } - }); - router2.param("issueId", async (req, res, next, rawId) => { - try { - req.params.issueId = await normalizeIssueIdentifier(rawId); - next(); - } catch (err) { - next(err); - } - }); - router2.get("/issues", (_req, res) => { - res.status(400).json({ - error: "Missing companyId in path. Use /api/companies/{companyId}/issues." - }); - }); - router2.get("/companies/:companyId/issues", async (req, res) => { - const companyId = req.params.companyId; - assertCompanyAccess(req, companyId); - const assigneeUserFilterRaw = req.query.assigneeUserId; - const touchedByUserFilterRaw = req.query.touchedByUserId; - const inboxArchivedByUserFilterRaw = req.query.inboxArchivedByUserId; - const unreadForUserFilterRaw = req.query.unreadForUserId; - const assigneeUserId = assigneeUserFilterRaw === "me" && req.actor.type === "board" ? req.actor.userId : assigneeUserFilterRaw; - const touchedByUserId = touchedByUserFilterRaw === "me" && req.actor.type === "board" ? req.actor.userId : touchedByUserFilterRaw; - const inboxArchivedByUserId = inboxArchivedByUserFilterRaw === "me" && req.actor.type === "board" ? req.actor.userId : inboxArchivedByUserFilterRaw; - const unreadForUserId = unreadForUserFilterRaw === "me" && req.actor.type === "board" ? req.actor.userId : unreadForUserFilterRaw; - const rawLimit = req.query.limit; - const parsedLimit = rawLimit ? Number.parseInt(rawLimit, 10) : null; - const limit = parsedLimit ?? void 0; - if (assigneeUserFilterRaw === "me" && (!assigneeUserId || req.actor.type !== "board")) { - res.status(403).json({ error: "assigneeUserId=me requires board authentication" }); - return; - } - if (touchedByUserFilterRaw === "me" && (!touchedByUserId || req.actor.type !== "board")) { - res.status(403).json({ error: "touchedByUserId=me requires board authentication" }); - return; - } - if (inboxArchivedByUserFilterRaw === "me" && (!inboxArchivedByUserId || req.actor.type !== "board")) { - res.status(403).json({ error: "inboxArchivedByUserId=me requires board authentication" }); - return; - } - if (unreadForUserFilterRaw === "me" && (!unreadForUserId || req.actor.type !== "board")) { - res.status(403).json({ error: "unreadForUserId=me requires board authentication" }); - return; - } - if (rawLimit !== void 0 && (parsedLimit === null || !Number.isInteger(parsedLimit) || parsedLimit <= 0)) { - res.status(400).json({ error: "limit must be a positive integer" }); - return; - } - const result = await svc.list(companyId, { - status: req.query.status, - assigneeAgentId: req.query.assigneeAgentId, - participantAgentId: req.query.participantAgentId, - assigneeUserId, - touchedByUserId, - inboxArchivedByUserId, - unreadForUserId, - projectId: req.query.projectId, - executionWorkspaceId: req.query.executionWorkspaceId, - parentId: req.query.parentId, - labelId: req.query.labelId, - originKind: req.query.originKind, - originId: req.query.originId, - includeRoutineExecutions: req.query.includeRoutineExecutions === "true" || req.query.includeRoutineExecutions === "1", - q: req.query.q, - limit - }); - res.json(result); - }); - router2.get("/companies/:companyId/labels", async (req, res) => { - const companyId = req.params.companyId; - assertCompanyAccess(req, companyId); - const result = await svc.listLabels(companyId); - res.json(result); - }); - router2.post("/companies/:companyId/labels", validate(createIssueLabelSchema), async (req, res) => { - const companyId = req.params.companyId; - assertCompanyAccess(req, companyId); - const label = await svc.createLabel(companyId, req.body); - const actor = getActorInfo(req); - await logActivity(db, { - companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - runId: actor.runId, - action: "label.created", - entityType: "label", - entityId: label.id, - details: { name: label.name, color: label.color } - }); - res.status(201).json(label); - }); - router2.delete("/labels/:labelId", async (req, res) => { - const labelId = req.params.labelId; - const existing = await svc.getLabelById(labelId); - if (!existing) { - res.status(404).json({ error: "Label not found" }); - return; - } - assertCompanyAccess(req, existing.companyId); - const removed = await svc.deleteLabel(labelId); - if (!removed) { - res.status(404).json({ error: "Label not found" }); - return; - } - const actor = getActorInfo(req); - await logActivity(db, { - companyId: removed.companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - runId: actor.runId, - action: "label.deleted", - entityType: "label", - entityId: removed.id, - details: { name: removed.name, color: removed.color } - }); - res.json(removed); - }); - router2.get("/issues/:id", async (req, res) => { - const id = req.params.id; - const issue2 = await svc.getById(id); - if (!issue2) { - res.status(404).json({ error: "Issue not found" }); - return; - } - assertCompanyAccess(req, issue2.companyId); - const [{ project, goal }, ancestors, mentionedProjectIds, documentPayload, relations] = await Promise.all([ - resolveIssueProjectAndGoal(issue2), - svc.getAncestors(issue2.id), - svc.findMentionedProjectIds(issue2.id), - documentsSvc.getIssueDocumentPayload(issue2), - svc.getRelationSummaries(issue2.id) - ]); - const mentionedProjects = mentionedProjectIds.length > 0 ? await projectsSvc.listByIds(issue2.companyId, mentionedProjectIds) : []; - const currentExecutionWorkspace = issue2.executionWorkspaceId ? await executionWorkspacesSvc.getById(issue2.executionWorkspaceId) : null; - const workProducts = await workProductsSvc.listForIssue(issue2.id); - res.json({ - ...issue2, - goalId: goal?.id ?? issue2.goalId, - ancestors, - blockedBy: relations.blockedBy, - blocks: relations.blocks, - ...documentPayload, - project: project ?? null, - goal: goal ?? null, - mentionedProjects, - currentExecutionWorkspace, - workProducts - }); - }); - router2.get("/issues/:id/heartbeat-context", async (req, res) => { - const id = req.params.id; - const issue2 = await svc.getById(id); - if (!issue2) { - res.status(404).json({ error: "Issue not found" }); - return; - } - assertCompanyAccess(req, issue2.companyId); - const wakeCommentId = typeof req.query.wakeCommentId === "string" && req.query.wakeCommentId.trim().length > 0 ? req.query.wakeCommentId.trim() : null; - const [{ project, goal }, ancestors, commentCursor, wakeComment, relations, attachments] = await Promise.all([ - resolveIssueProjectAndGoal(issue2), - svc.getAncestors(issue2.id), - svc.getCommentCursor(issue2.id), - wakeCommentId ? svc.getComment(wakeCommentId) : null, - svc.getRelationSummaries(issue2.id), - svc.listAttachments(issue2.id) - ]); - res.json({ - issue: { - id: issue2.id, - identifier: issue2.identifier, - title: issue2.title, - description: issue2.description, - status: issue2.status, - priority: issue2.priority, - projectId: issue2.projectId, - goalId: goal?.id ?? issue2.goalId, - parentId: issue2.parentId, - blockedBy: relations.blockedBy, - blocks: relations.blocks, - assigneeAgentId: issue2.assigneeAgentId, - assigneeUserId: issue2.assigneeUserId, - updatedAt: issue2.updatedAt - }, - ancestors: ancestors.map((ancestor) => ({ - id: ancestor.id, - identifier: ancestor.identifier, - title: ancestor.title, - status: ancestor.status, - priority: ancestor.priority - })), - project: project ? { - id: project.id, - name: project.name, - status: project.status, - targetDate: project.targetDate - } : null, - goal: goal ? { - id: goal.id, - title: goal.title, - status: goal.status, - level: goal.level, - parentId: goal.parentId - } : null, - commentCursor, - wakeComment: wakeComment && wakeComment.issueId === issue2.id ? wakeComment : null, - attachments: attachments.map((a5) => ({ - id: a5.id, - filename: a5.originalFilename, - contentType: a5.contentType, - byteSize: a5.byteSize, - contentPath: withContentPath(a5).contentPath, - createdAt: a5.createdAt - })) - }); - }); - router2.get("/issues/:id/work-products", async (req, res) => { - const id = req.params.id; - const issue2 = await svc.getById(id); - if (!issue2) { - res.status(404).json({ error: "Issue not found" }); - return; - } - assertCompanyAccess(req, issue2.companyId); - const workProducts = await workProductsSvc.listForIssue(issue2.id); - res.json(workProducts); - }); - router2.get("/issues/:id/documents", async (req, res) => { - const id = req.params.id; - const issue2 = await svc.getById(id); - if (!issue2) { - res.status(404).json({ error: "Issue not found" }); - return; - } - assertCompanyAccess(req, issue2.companyId); - const docs = await documentsSvc.listIssueDocuments(issue2.id); - res.json(docs); - }); - router2.get("/issues/:id/documents/:key", async (req, res) => { - const id = req.params.id; - const issue2 = await svc.getById(id); - if (!issue2) { - res.status(404).json({ error: "Issue not found" }); - return; - } - assertCompanyAccess(req, issue2.companyId); - const keyParsed = issueDocumentKeySchema.safeParse(String(req.params.key ?? "").trim().toLowerCase()); - if (!keyParsed.success) { - res.status(400).json({ error: "Invalid document key", details: keyParsed.error.issues }); - return; - } - const doc = await documentsSvc.getIssueDocumentByKey(issue2.id, keyParsed.data); - if (!doc) { - res.status(404).json({ error: "Document not found" }); - return; - } - res.json(doc); - }); - router2.put("/issues/:id/documents/:key", validate(upsertIssueDocumentSchema), async (req, res) => { - const id = req.params.id; - const issue2 = await svc.getById(id); - if (!issue2) { - res.status(404).json({ error: "Issue not found" }); - return; - } - assertCompanyAccess(req, issue2.companyId); - const keyParsed = issueDocumentKeySchema.safeParse(String(req.params.key ?? "").trim().toLowerCase()); - if (!keyParsed.success) { - res.status(400).json({ error: "Invalid document key", details: keyParsed.error.issues }); - return; - } - const actor = getActorInfo(req); - const result = await documentsSvc.upsertIssueDocument({ - issueId: issue2.id, - key: keyParsed.data, - title: req.body.title ?? null, - format: req.body.format, - body: req.body.body, - changeSummary: req.body.changeSummary ?? null, - baseRevisionId: req.body.baseRevisionId ?? null, - createdByAgentId: actor.agentId ?? null, - createdByUserId: actor.actorType === "user" ? actor.actorId : null, - createdByRunId: actor.runId ?? null - }); - const doc = result.document; - await logActivity(db, { - companyId: issue2.companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - runId: actor.runId, - action: result.created ? "issue.document_created" : "issue.document_updated", - entityType: "issue", - entityId: issue2.id, - details: { - key: doc.key, - documentId: doc.id, - title: doc.title, - format: doc.format, - revisionNumber: doc.latestRevisionNumber - } - }); - res.status(result.created ? 201 : 200).json(doc); - }); - router2.get("/issues/:id/documents/:key/revisions", async (req, res) => { - const id = req.params.id; - const issue2 = await svc.getById(id); - if (!issue2) { - res.status(404).json({ error: "Issue not found" }); - return; - } - assertCompanyAccess(req, issue2.companyId); - const keyParsed = issueDocumentKeySchema.safeParse(String(req.params.key ?? "").trim().toLowerCase()); - if (!keyParsed.success) { - res.status(400).json({ error: "Invalid document key", details: keyParsed.error.issues }); - return; - } - const revisions = await documentsSvc.listIssueDocumentRevisions(issue2.id, keyParsed.data); - res.json(revisions); - }); - router2.post( - "/issues/:id/documents/:key/revisions/:revisionId/restore", - validate(restoreIssueDocumentRevisionSchema), - async (req, res) => { - const id = req.params.id; - const revisionId = req.params.revisionId; - const issue2 = await svc.getById(id); - if (!issue2) { - res.status(404).json({ error: "Issue not found" }); - return; - } - assertCompanyAccess(req, issue2.companyId); - const keyParsed = issueDocumentKeySchema.safeParse(String(req.params.key ?? "").trim().toLowerCase()); - if (!keyParsed.success) { - res.status(400).json({ error: "Invalid document key", details: keyParsed.error.issues }); - return; - } - const actor = getActorInfo(req); - const result = await documentsSvc.restoreIssueDocumentRevision({ - issueId: issue2.id, - key: keyParsed.data, - revisionId, - createdByAgentId: actor.agentId ?? null, - createdByUserId: actor.actorType === "user" ? actor.actorId : null - }); - await logActivity(db, { - companyId: issue2.companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - runId: actor.runId, - action: "issue.document_restored", - entityType: "issue", - entityId: issue2.id, - details: { - key: result.document.key, - documentId: result.document.id, - title: result.document.title, - format: result.document.format, - revisionNumber: result.document.latestRevisionNumber, - restoredFromRevisionId: result.restoredFromRevisionId, - restoredFromRevisionNumber: result.restoredFromRevisionNumber - } - }); - res.json(result.document); - } - ); - router2.delete("/issues/:id/documents/:key", async (req, res) => { - const id = req.params.id; - const issue2 = await svc.getById(id); - if (!issue2) { - res.status(404).json({ error: "Issue not found" }); - return; - } - assertCompanyAccess(req, issue2.companyId); - if (req.actor.type !== "board") { - res.status(403).json({ error: "Board authentication required" }); - return; - } - const keyParsed = issueDocumentKeySchema.safeParse(String(req.params.key ?? "").trim().toLowerCase()); - if (!keyParsed.success) { - res.status(400).json({ error: "Invalid document key", details: keyParsed.error.issues }); - return; - } - const removed = await documentsSvc.deleteIssueDocument(issue2.id, keyParsed.data); - if (!removed) { - res.status(404).json({ error: "Document not found" }); - return; - } - const actor = getActorInfo(req); - await logActivity(db, { - companyId: issue2.companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - runId: actor.runId, - action: "issue.document_deleted", - entityType: "issue", - entityId: issue2.id, - details: { - key: removed.key, - documentId: removed.id, - title: removed.title - } - }); - res.json({ ok: true }); - }); - router2.post("/issues/:id/work-products", validate(createIssueWorkProductSchema), async (req, res) => { - const id = req.params.id; - const issue2 = await svc.getById(id); - if (!issue2) { - res.status(404).json({ error: "Issue not found" }); - return; - } - assertCompanyAccess(req, issue2.companyId); - const product = await workProductsSvc.createForIssue(issue2.id, issue2.companyId, { - ...req.body, - projectId: req.body.projectId ?? issue2.projectId ?? null - }); - if (!product) { - res.status(422).json({ error: "Invalid work product payload" }); - return; - } - const actor = getActorInfo(req); - await logActivity(db, { - companyId: issue2.companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - runId: actor.runId, - action: "issue.work_product_created", - entityType: "issue", - entityId: issue2.id, - details: { workProductId: product.id, type: product.type, provider: product.provider } - }); - res.status(201).json(product); - }); - router2.patch("/work-products/:id", validate(updateIssueWorkProductSchema), async (req, res) => { - const id = req.params.id; - const existing = await workProductsSvc.getById(id); - if (!existing) { - res.status(404).json({ error: "Work product not found" }); - return; - } - assertCompanyAccess(req, existing.companyId); - const product = await workProductsSvc.update(id, req.body); - if (!product) { - res.status(404).json({ error: "Work product not found" }); - return; - } - const actor = getActorInfo(req); - await logActivity(db, { - companyId: existing.companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - runId: actor.runId, - action: "issue.work_product_updated", - entityType: "issue", - entityId: existing.issueId, - details: { workProductId: product.id, changedKeys: Object.keys(req.body).sort() } - }); - res.json(product); - }); - router2.delete("/work-products/:id", async (req, res) => { - const id = req.params.id; - const existing = await workProductsSvc.getById(id); - if (!existing) { - res.status(404).json({ error: "Work product not found" }); - return; - } - assertCompanyAccess(req, existing.companyId); - const removed = await workProductsSvc.remove(id); - if (!removed) { - res.status(404).json({ error: "Work product not found" }); - return; - } - const actor = getActorInfo(req); - await logActivity(db, { - companyId: existing.companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - runId: actor.runId, - action: "issue.work_product_deleted", - entityType: "issue", - entityId: existing.issueId, - details: { workProductId: removed.id, type: removed.type } - }); - res.json(removed); - }); - router2.post("/issues/:id/read", async (req, res) => { - const id = req.params.id; - const issue2 = await svc.getById(id); - if (!issue2) { - res.status(404).json({ error: "Issue not found" }); - return; - } - assertCompanyAccess(req, issue2.companyId); - if (req.actor.type !== "board") { - res.status(403).json({ error: "Board authentication required" }); - return; - } - if (!req.actor.userId) { - res.status(403).json({ error: "Board user context required" }); - return; - } - const readState = await svc.markRead(issue2.companyId, issue2.id, req.actor.userId, /* @__PURE__ */ new Date()); - const actor = getActorInfo(req); - await logActivity(db, { - companyId: issue2.companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - runId: actor.runId, - action: "issue.read_marked", - entityType: "issue", - entityId: issue2.id, - details: { userId: req.actor.userId, lastReadAt: readState.lastReadAt } - }); - res.json(readState); - }); - router2.delete("/issues/:id/read", async (req, res) => { - const id = req.params.id; - const issue2 = await svc.getById(id); - if (!issue2) { - res.status(404).json({ error: "Issue not found" }); - return; - } - assertCompanyAccess(req, issue2.companyId); - if (req.actor.type !== "board") { - res.status(403).json({ error: "Board authentication required" }); - return; - } - if (!req.actor.userId) { - res.status(403).json({ error: "Board user context required" }); - return; - } - const removed = await svc.markUnread(issue2.companyId, issue2.id, req.actor.userId); - const actor = getActorInfo(req); - await logActivity(db, { - companyId: issue2.companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - runId: actor.runId, - action: "issue.read_unmarked", - entityType: "issue", - entityId: issue2.id, - details: { userId: req.actor.userId } - }); - res.json({ id: issue2.id, removed }); - }); - router2.post("/issues/:id/inbox-archive", async (req, res) => { - const id = req.params.id; - const issue2 = await svc.getById(id); - if (!issue2) { - res.status(404).json({ error: "Issue not found" }); - return; - } - assertCompanyAccess(req, issue2.companyId); - if (req.actor.type !== "board") { - res.status(403).json({ error: "Board authentication required" }); - return; - } - if (!req.actor.userId) { - res.status(403).json({ error: "Board user context required" }); - return; - } - const archiveState = await svc.archiveInbox(issue2.companyId, issue2.id, req.actor.userId, /* @__PURE__ */ new Date()); - const actor = getActorInfo(req); - await logActivity(db, { - companyId: issue2.companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - runId: actor.runId, - action: "issue.inbox_archived", - entityType: "issue", - entityId: issue2.id, - details: { userId: req.actor.userId, archivedAt: archiveState.archivedAt } - }); - res.json(archiveState); - }); - router2.delete("/issues/:id/inbox-archive", async (req, res) => { - const id = req.params.id; - const issue2 = await svc.getById(id); - if (!issue2) { - res.status(404).json({ error: "Issue not found" }); - return; - } - assertCompanyAccess(req, issue2.companyId); - if (req.actor.type !== "board") { - res.status(403).json({ error: "Board authentication required" }); - return; - } - if (!req.actor.userId) { - res.status(403).json({ error: "Board user context required" }); - return; - } - const removed = await svc.unarchiveInbox(issue2.companyId, issue2.id, req.actor.userId); - const actor = getActorInfo(req); - await logActivity(db, { - companyId: issue2.companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - runId: actor.runId, - action: "issue.inbox_unarchived", - entityType: "issue", - entityId: issue2.id, - details: { userId: req.actor.userId } - }); - res.json(removed ?? { ok: true }); - }); - router2.get("/issues/:id/approvals", async (req, res) => { - const id = req.params.id; - const issue2 = await svc.getById(id); - if (!issue2) { - res.status(404).json({ error: "Issue not found" }); - return; - } - assertCompanyAccess(req, issue2.companyId); - const approvals2 = await issueApprovalsSvc.listApprovalsForIssue(id); - res.json(approvals2); - }); - router2.post("/issues/:id/approvals", validate(linkIssueApprovalSchema), async (req, res) => { - const id = req.params.id; - const issue2 = await svc.getById(id); - if (!issue2) { - res.status(404).json({ error: "Issue not found" }); - return; - } - if (!await assertCanManageIssueApprovalLinks(req, res, issue2.companyId)) return; - const actor = getActorInfo(req); - await issueApprovalsSvc.link(id, req.body.approvalId, { - agentId: actor.agentId, - userId: actor.actorType === "user" ? actor.actorId : null - }); - await logActivity(db, { - companyId: issue2.companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - runId: actor.runId, - action: "issue.approval_linked", - entityType: "issue", - entityId: issue2.id, - details: { approvalId: req.body.approvalId } - }); - const approvals2 = await issueApprovalsSvc.listApprovalsForIssue(id); - res.status(201).json(approvals2); - }); - router2.delete("/issues/:id/approvals/:approvalId", async (req, res) => { - const id = req.params.id; - const approvalId = req.params.approvalId; - const issue2 = await svc.getById(id); - if (!issue2) { - res.status(404).json({ error: "Issue not found" }); - return; - } - if (!await assertCanManageIssueApprovalLinks(req, res, issue2.companyId)) return; - await issueApprovalsSvc.unlink(id, approvalId); - const actor = getActorInfo(req); - await logActivity(db, { - companyId: issue2.companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - runId: actor.runId, - action: "issue.approval_unlinked", - entityType: "issue", - entityId: issue2.id, - details: { approvalId } - }); - res.json({ ok: true }); - }); - router2.post("/companies/:companyId/issues", validate(createIssueSchema), async (req, res) => { - const companyId = req.params.companyId; - assertCompanyAccess(req, companyId); - if (req.body.assigneeAgentId || req.body.assigneeUserId) { - await assertCanAssignTasks(req, companyId); - } - const actor = getActorInfo(req); - const executionPolicy = normalizeIssueExecutionPolicy(req.body.executionPolicy); - const issue2 = await svc.create(companyId, { - ...req.body, - executionPolicy, - createdByAgentId: actor.agentId, - createdByUserId: actor.actorType === "user" ? actor.actorId : null - }); - await logActivity(db, { - companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - runId: actor.runId, - action: "issue.created", - entityType: "issue", - entityId: issue2.id, - details: { - title: issue2.title, - identifier: issue2.identifier, - ...Array.isArray(req.body.blockedByIssueIds) ? { blockedByIssueIds: req.body.blockedByIssueIds } : {} - } - }); - void queueIssueAssignmentWakeup({ - heartbeat, - issue: issue2, - reason: "issue_assigned", - mutation: "create", - contextSource: "issue.create", - requestedByActorType: actor.actorType, - requestedByActorId: actor.actorId - }); - res.status(201).json(issue2); - }); - router2.patch("/issues/:id", validate(updateIssueRouteSchema), async (req, res) => { - const id = req.params.id; - const existing = await svc.getById(id); - if (!existing) { - res.status(404).json({ error: "Issue not found" }); - return; - } - assertCompanyAccess(req, existing.companyId); - if (!await assertAgentRunCheckoutOwnership(req, res, existing)) return; - const actor = getActorInfo(req); - const isClosed = isClosedIssueStatus(existing.status); - const normalizedAssigneeAgentId = await normalizeIssueAssigneeAgentReference( - existing.companyId, - req.body.assigneeAgentId - ); - const existingRelations = Array.isArray(req.body.blockedByIssueIds) ? await svc.getRelationSummaries(existing.id) : null; - const { - comment: commentBody, - reopen: reopenRequested, - interrupt: interruptRequested, - hiddenAt: hiddenAtRaw, - ...updateFields - } = req.body; - const requestedAssigneeAgentId = normalizedAssigneeAgentId === void 0 ? existing.assigneeAgentId : normalizedAssigneeAgentId; - const effectiveReopenRequested = reopenRequested || !!commentBody && shouldImplicitlyReopenCommentForAgent({ - issueStatus: existing.status, - assigneeAgentId: requestedAssigneeAgentId, - actorType: actor.actorType, - actorId: actor.actorId - }); - let interruptedRunId = null; - const closedExecutionWorkspace = await getClosedIssueExecutionWorkspace(existing); - const isAgentWorkUpdate = req.actor.type === "agent" && Object.keys(updateFields).length > 0; - if (closedExecutionWorkspace && (commentBody || isAgentWorkUpdate)) { - respondClosedIssueExecutionWorkspace(res, closedExecutionWorkspace); - return; - } - if (interruptRequested) { - if (!commentBody) { - res.status(400).json({ error: "Interrupt is only supported when posting a comment" }); - return; - } - if (req.actor.type !== "board") { - res.status(403).json({ error: "Only board users can interrupt active runs from issue comments" }); - return; - } - const runToInterrupt = await resolveActiveIssueRun(existing); - if (runToInterrupt) { - const cancelled = await heartbeat.cancelRun(runToInterrupt.id); - if (cancelled) { - interruptedRunId = cancelled.id; - await logActivity(db, { - companyId: cancelled.companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - runId: actor.runId, - action: "heartbeat.cancelled", - entityType: "heartbeat_run", - entityId: cancelled.id, - details: { agentId: cancelled.agentId, source: "issue_comment_interrupt", issueId: existing.id } - }); - } - } - } - if (hiddenAtRaw !== void 0) { - updateFields.hiddenAt = hiddenAtRaw ? new Date(hiddenAtRaw) : null; - } - if (commentBody && effectiveReopenRequested && isClosed && updateFields.status === void 0) { - updateFields.status = "todo"; - } - if (req.body.executionPolicy !== void 0) { - updateFields.executionPolicy = normalizeIssueExecutionPolicy(req.body.executionPolicy); - } - const previousExecutionPolicy = normalizeIssueExecutionPolicy(existing.executionPolicy ?? null); - const nextExecutionPolicy = updateFields.executionPolicy !== void 0 ? updateFields.executionPolicy : previousExecutionPolicy; - if (normalizedAssigneeAgentId !== void 0) { - updateFields.assigneeAgentId = normalizedAssigneeAgentId; - } - const transition = applyIssueExecutionPolicyTransition({ - issue: existing, - policy: nextExecutionPolicy, - requestedStatus: typeof updateFields.status === "string" ? updateFields.status : void 0, - requestedAssigneePatch: { - assigneeAgentId: normalizedAssigneeAgentId, - assigneeUserId: req.body.assigneeUserId === void 0 ? void 0 : req.body.assigneeUserId - }, - actor: { - agentId: actor.agentId ?? null, - userId: actor.actorType === "user" ? actor.actorId : null - }, - commentBody - }); - const decisionId = transition.decision ? randomUUID9() : null; - if (decisionId) { - const nextExecutionState2 = transition.patch.executionState; - if (!nextExecutionState2 || typeof nextExecutionState2 !== "object") { - throw new Error("Execution policy decision patch is missing executionState"); - } - transition.patch.executionState = { - ...nextExecutionState2, - lastDecisionId: decisionId - }; - } - Object.assign(updateFields, transition.patch); - const nextAssigneeAgentId = updateFields.assigneeAgentId === void 0 ? existing.assigneeAgentId : updateFields.assigneeAgentId; - const nextAssigneeUserId = updateFields.assigneeUserId === void 0 ? existing.assigneeUserId : updateFields.assigneeUserId; - const assigneeWillChange = nextAssigneeAgentId !== existing.assigneeAgentId || nextAssigneeUserId !== existing.assigneeUserId; - const isAgentReturningIssueToCreator = req.actor.type === "agent" && !!req.actor.agentId && existing.assigneeAgentId === req.actor.agentId && nextAssigneeAgentId === null && typeof nextAssigneeUserId === "string" && !!existing.createdByUserId && nextAssigneeUserId === existing.createdByUserId; - if (assigneeWillChange && !transition.workflowControlledAssignment) { - if (!isAgentReturningIssueToCreator) { - await assertCanAssignTasks(req, existing.companyId); - } - } - let issue2; - try { - if (transition.decision && decisionId) { - const decision = transition.decision; - issue2 = await db.transaction(async (tx) => { - const updated = await svc.update( - id, - { - ...updateFields, - actorAgentId: actor.agentId ?? null, - actorUserId: actor.actorType === "user" ? actor.actorId : null - }, - tx - ); - if (!updated) return null; - await tx.insert(issueExecutionDecisions).values({ - id: decisionId, - companyId: updated.companyId, - issueId: updated.id, - stageId: decision.stageId, - stageType: decision.stageType, - actorAgentId: actor.agentId ?? null, - actorUserId: actor.actorType === "user" ? actor.actorId : null, - outcome: decision.outcome, - body: decision.body, - createdByRunId: actor.runId ?? null - }); - return updated; - }); - } else { - issue2 = await svc.update(id, { - ...updateFields, - actorAgentId: actor.agentId ?? null, - actorUserId: actor.actorType === "user" ? actor.actorId : null - }); - } - } catch (err) { - if (err instanceof HttpError && err.status === 422) { - logger.warn( - { - issueId: id, - companyId: existing.companyId, - assigneePatch: { - assigneeAgentId: normalizedAssigneeAgentId === void 0 ? "__omitted__" : normalizedAssigneeAgentId, - assigneeUserId: req.body.assigneeUserId === void 0 ? "__omitted__" : req.body.assigneeUserId - }, - currentAssignee: { - assigneeAgentId: existing.assigneeAgentId, - assigneeUserId: existing.assigneeUserId - }, - error: err.message, - details: err.details - }, - "issue update rejected with 422" - ); - } - throw err; - } - if (!issue2) { - res.status(404).json({ error: "Issue not found" }); - return; - } - let issueResponse = issue2; - let updatedRelations = null; - if (issue2 && Array.isArray(req.body.blockedByIssueIds)) { - updatedRelations = await svc.getRelationSummaries(issue2.id); - issueResponse = { - ...issue2, - blockedBy: updatedRelations.blockedBy, - blocks: updatedRelations.blocks - }; - } - await routinesSvc.syncRunStatusForIssue(issue2.id); - if (actor.runId) { - await heartbeat.reportRunActivity(actor.runId).catch((err) => logger.warn({ err, runId: actor.runId }, "failed to clear detached run warning after issue activity")); - } - const previous = {}; - for (const key of Object.keys(updateFields)) { - if (key in existing && existing[key] !== updateFields[key]) { - previous[key] = existing[key]; - } - } - if (Array.isArray(req.body.blockedByIssueIds)) { - previous.blockedByIssueIds = existingRelations?.blockedBy.map((relation) => relation.id) ?? []; - } - const hasFieldChanges = Object.keys(previous).length > 0; - const reopened = commentBody && effectiveReopenRequested && isClosed && previous.status !== void 0 && issue2.status === "todo"; - const reopenFromStatus = reopened ? existing.status : null; - await logActivity(db, { - companyId: issue2.companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - runId: actor.runId, - action: "issue.updated", - entityType: "issue", - entityId: issue2.id, - details: { - ...updateFields, - identifier: issue2.identifier, - ...commentBody ? { source: "comment" } : {}, - ...reopened ? { reopened: true, reopenedFrom: reopenFromStatus } : {}, - ...interruptedRunId ? { interruptedRunId } : {}, - _previous: hasFieldChanges ? previous : void 0 - } - }); - if (Array.isArray(req.body.blockedByIssueIds)) { - const previousBlockedByIds = new Set((existingRelations?.blockedBy ?? []).map((relation) => relation.id)); - const nextBlockedByIds = new Set(req.body.blockedByIssueIds); - const addedBlockedByIssueIds = [...nextBlockedByIds].filter((candidate) => !previousBlockedByIds.has(candidate)); - const removedBlockedByIssueIds = [...previousBlockedByIds].filter((candidate) => !nextBlockedByIds.has(candidate)); - const nextBlockedByRelations = updatedRelations?.blockedBy ?? []; - const previousBlockedByRelations = existingRelations?.blockedBy ?? []; - if (addedBlockedByIssueIds.length > 0 || removedBlockedByIssueIds.length > 0) { - await logActivity(db, { - companyId: issue2.companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - runId: actor.runId, - action: "issue.blockers_updated", - entityType: "issue", - entityId: issue2.id, - details: { - identifier: issue2.identifier, - blockedByIssueIds: req.body.blockedByIssueIds, - addedBlockedByIssueIds, - removedBlockedByIssueIds, - blockedByIssues: nextBlockedByRelations.map(summarizeIssueRelationForActivity), - addedBlockedByIssues: nextBlockedByRelations.filter((relation) => addedBlockedByIssueIds.includes(relation.id)).map(summarizeIssueRelationForActivity), - removedBlockedByIssues: previousBlockedByRelations.filter((relation) => removedBlockedByIssueIds.includes(relation.id)).map(summarizeIssueRelationForActivity) - } - }); - } - } - const reviewerChanges = diffExecutionParticipants(previousExecutionPolicy, nextExecutionPolicy, "review"); - if (reviewerChanges.addedParticipants.length > 0 || reviewerChanges.removedParticipants.length > 0) { - await logActivity(db, { - companyId: issue2.companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - runId: actor.runId, - action: "issue.reviewers_updated", - entityType: "issue", - entityId: issue2.id, - details: { - identifier: issue2.identifier, - participants: reviewerChanges.participants, - addedParticipants: reviewerChanges.addedParticipants, - removedParticipants: reviewerChanges.removedParticipants - } - }); - } - const approverChanges = diffExecutionParticipants(previousExecutionPolicy, nextExecutionPolicy, "approval"); - if (approverChanges.addedParticipants.length > 0 || approverChanges.removedParticipants.length > 0) { - await logActivity(db, { - companyId: issue2.companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - runId: actor.runId, - action: "issue.approvers_updated", - entityType: "issue", - entityId: issue2.id, - details: { - identifier: issue2.identifier, - participants: approverChanges.participants, - addedParticipants: approverChanges.addedParticipants, - removedParticipants: approverChanges.removedParticipants - } - }); - } - if (issue2.status === "done" && existing.status !== "done") { - const tc = getTelemetryClient(); - if (tc && actor.agentId) { - const actorAgent = await agentsSvc.getById(actor.agentId); - if (actorAgent) { - const model = typeof actorAgent.adapterConfig?.model === "string" ? actorAgent.adapterConfig.model : void 0; - trackAgentTaskCompleted(tc, { - agentRole: actorAgent.role, - agentId: actorAgent.id, - adapterType: actorAgent.adapterType, - model - }); - } - } - } - let comment = null; - if (commentBody) { - comment = await svc.addComment(id, commentBody, { - agentId: actor.agentId ?? void 0, - userId: actor.actorType === "user" ? actor.actorId : void 0, - runId: actor.runId - }); - await logActivity(db, { - companyId: issue2.companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - runId: actor.runId, - action: "issue.comment_added", - entityType: "issue", - entityId: issue2.id, - details: { - commentId: comment.id, - bodySnippet: comment.body.slice(0, 120), - identifier: issue2.identifier, - issueTitle: issue2.title, - ...reopened ? { reopened: true, reopenedFrom: reopenFromStatus, source: "comment" } : {}, - ...interruptedRunId ? { interruptedRunId } : {}, - ...hasFieldChanges ? { updated: true } : {} - } - }); - } - const assigneeChanged = issue2.assigneeAgentId !== existing.assigneeAgentId || issue2.assigneeUserId !== existing.assigneeUserId; - const statusChangedFromBacklog = existing.status === "backlog" && issue2.status !== "backlog" && req.body.status !== void 0; - const statusChangedFromBlockedToTodo = existing.status === "blocked" && issue2.status === "todo" && req.body.status !== void 0; - const previousExecutionState = parseIssueExecutionState(existing.executionState); - const nextExecutionState = parseIssueExecutionState(issue2.executionState); - const executionStageWakeup = buildExecutionStageWakeup({ - issueId: issue2.id, - previousState: previousExecutionState, - nextState: nextExecutionState, - interruptedRunId, - requestedByActorType: actor.actorType, - requestedByActorId: actor.actorId - }); - void (async () => { - const wakeups = /* @__PURE__ */ new Map(); - const addWakeup = (agentId, wakeup) => { - const wakeIssueId = wakeup.payload && typeof wakeup.payload === "object" && typeof wakeup.payload.issueId === "string" ? wakeup.payload.issueId : issue2.id; - wakeups.set(`${agentId}:${wakeIssueId}`, { agentId, wakeup }); - }; - if (executionStageWakeup) { - addWakeup(executionStageWakeup.agentId, executionStageWakeup.wakeup); - } else if (assigneeChanged && issue2.assigneeAgentId && issue2.status !== "backlog") { - addWakeup(issue2.assigneeAgentId, { - source: "assignment", - triggerDetail: "system", - reason: "issue_assigned", - payload: { - issueId: issue2.id, - ...comment ? { commentId: comment.id } : {}, - mutation: "update", - ...interruptedRunId ? { interruptedRunId } : {} - }, - requestedByActorType: actor.actorType, - requestedByActorId: actor.actorId, - contextSnapshot: { - issueId: issue2.id, - ...comment ? { - taskId: issue2.id, - commentId: comment.id, - wakeCommentId: comment.id - } : {}, - source: "issue.update", - ...interruptedRunId ? { interruptedRunId } : {} - } - }); - } - if (!assigneeChanged && (statusChangedFromBacklog || statusChangedFromBlockedToTodo) && issue2.assigneeAgentId) { - addWakeup(issue2.assigneeAgentId, { - source: "automation", - triggerDetail: "system", - reason: "issue_status_changed", - payload: { - issueId: issue2.id, - mutation: "update", - ...interruptedRunId ? { interruptedRunId } : {} - }, - requestedByActorType: actor.actorType, - requestedByActorId: actor.actorId, - contextSnapshot: { - issueId: issue2.id, - source: "issue.status_change", - ...interruptedRunId ? { interruptedRunId } : {} - } - }); - } - if (commentBody && comment) { - const assigneeId = issue2.assigneeAgentId; - const actorIsAgent = actor.actorType === "agent"; - const selfComment = actorIsAgent && actor.actorId === assigneeId; - const skipAssigneeCommentWake = selfComment || isClosed; - if (assigneeId && !assigneeChanged && (reopened || !skipAssigneeCommentWake)) { - addWakeup(assigneeId, { - source: "automation", - triggerDetail: "system", - reason: reopened ? "issue_reopened_via_comment" : "issue_commented", - payload: { - issueId: id, - commentId: comment.id, - mutation: "comment", - ...reopened ? { reopenedFrom: reopenFromStatus } : {}, - ...interruptedRunId ? { interruptedRunId } : {} - }, - requestedByActorType: actor.actorType, - requestedByActorId: actor.actorId, - contextSnapshot: { - issueId: id, - taskId: id, - commentId: comment.id, - wakeCommentId: comment.id, - source: reopened ? "issue.comment.reopen" : "issue.comment", - wakeReason: reopened ? "issue_reopened_via_comment" : "issue_commented", - ...reopened ? { reopenedFrom: reopenFromStatus } : {}, - ...interruptedRunId ? { interruptedRunId } : {} - } - }); - } - let mentionedIds = []; - try { - mentionedIds = await svc.findMentionedAgents(issue2.companyId, commentBody); - } catch (err) { - logger.warn({ err, issueId: id }, "failed to resolve @-mentions"); - } - for (const mentionedId of mentionedIds) { - if (actor.actorType === "agent" && actor.actorId === mentionedId) continue; - addWakeup(mentionedId, { - source: "automation", - triggerDetail: "system", - reason: "issue_comment_mentioned", - payload: { issueId: id, commentId: comment.id }, - requestedByActorType: actor.actorType, - requestedByActorId: actor.actorId, - contextSnapshot: { - issueId: id, - taskId: id, - commentId: comment.id, - wakeCommentId: comment.id, - wakeReason: "issue_comment_mentioned", - source: "comment.mention" - } - }); - } - } - const becameDone = existing.status !== "done" && issue2.status === "done"; - if (becameDone) { - const dependents = await svc.listWakeableBlockedDependents(issue2.id); - for (const dependent of dependents) { - addWakeup(dependent.assigneeAgentId, { - source: "automation", - triggerDetail: "system", - reason: "issue_blockers_resolved", - payload: { - issueId: dependent.id, - resolvedBlockerIssueId: issue2.id, - blockerIssueIds: dependent.blockerIssueIds - }, - requestedByActorType: actor.actorType, - requestedByActorId: actor.actorId, - contextSnapshot: { - issueId: dependent.id, - taskId: dependent.id, - wakeReason: "issue_blockers_resolved", - source: "issue.blockers_resolved", - resolvedBlockerIssueId: issue2.id, - blockerIssueIds: dependent.blockerIssueIds - } - }); - } - } - const becameTerminal = !["done", "cancelled"].includes(existing.status) && ["done", "cancelled"].includes(issue2.status); - if (becameTerminal && issue2.parentId) { - const parent = await svc.getWakeableParentAfterChildCompletion(issue2.parentId); - if (parent) { - addWakeup(parent.assigneeAgentId, { - source: "automation", - triggerDetail: "system", - reason: "issue_children_completed", - payload: { - issueId: parent.id, - completedChildIssueId: issue2.id, - childIssueIds: parent.childIssueIds - }, - requestedByActorType: actor.actorType, - requestedByActorId: actor.actorId, - contextSnapshot: { - issueId: parent.id, - taskId: parent.id, - wakeReason: "issue_children_completed", - source: "issue.children_completed", - completedChildIssueId: issue2.id, - childIssueIds: parent.childIssueIds - } - }); - } - } - for (const { agentId, wakeup } of wakeups.values()) { - heartbeat.wakeup(agentId, wakeup).catch((err) => logger.warn({ err, issueId: issue2.id, agentId }, "failed to wake agent on issue update")); - } - })(); - res.json({ ...issueResponse, comment }); - }); - router2.delete("/issues/:id", async (req, res) => { - const id = req.params.id; - const existing = await svc.getById(id); - if (!existing) { - res.status(404).json({ error: "Issue not found" }); - return; - } - assertCompanyAccess(req, existing.companyId); - const attachments = await svc.listAttachments(id); - const issue2 = await svc.remove(id); - if (!issue2) { - res.status(404).json({ error: "Issue not found" }); - return; - } - for (const attachment of attachments) { - try { - await storage.deleteObject(attachment.companyId, attachment.objectKey); - } catch (err) { - logger.warn({ err, issueId: id, attachmentId: attachment.id }, "failed to delete attachment object during issue delete"); - } - } - const actor = getActorInfo(req); - await logActivity(db, { - companyId: issue2.companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - runId: actor.runId, - action: "issue.deleted", - entityType: "issue", - entityId: issue2.id - }); - res.json(issue2); - }); - router2.post("/issues/:id/checkout", validate(checkoutIssueSchema), async (req, res) => { - const id = req.params.id; - const issue2 = await svc.getById(id); - if (!issue2) { - res.status(404).json({ error: "Issue not found" }); - return; - } - assertCompanyAccess(req, issue2.companyId); - if (issue2.projectId) { - const project = await projectsSvc.getById(issue2.projectId); - if (project?.pausedAt) { - res.status(409).json({ - error: project.pauseReason === "budget" ? "Project is paused because its budget hard-stop was reached" : "Project is paused" - }); - return; - } - } - if (req.actor.type === "agent" && req.actor.agentId !== req.body.agentId) { - res.status(403).json({ error: "Agent can only checkout as itself" }); - return; - } - const closedExecutionWorkspace = await getClosedIssueExecutionWorkspace(issue2); - if (closedExecutionWorkspace) { - respondClosedIssueExecutionWorkspace(res, closedExecutionWorkspace); - return; - } - const checkoutRunId = requireAgentRunId(req, res); - if (req.actor.type === "agent" && !checkoutRunId) return; - const updated = await svc.checkout(id, req.body.agentId, req.body.expectedStatuses, checkoutRunId); - const actor = getActorInfo(req); - await logActivity(db, { - companyId: issue2.companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - runId: actor.runId, - action: "issue.checked_out", - entityType: "issue", - entityId: issue2.id, - details: { agentId: req.body.agentId } - }); - if (shouldWakeAssigneeOnCheckout({ - actorType: req.actor.type, - actorAgentId: req.actor.type === "agent" ? req.actor.agentId ?? null : null, - checkoutAgentId: req.body.agentId, - checkoutRunId - })) { - void heartbeat.wakeup(req.body.agentId, { - source: "assignment", - triggerDetail: "system", - reason: "issue_checked_out", - payload: { issueId: issue2.id, mutation: "checkout" }, - requestedByActorType: actor.actorType, - requestedByActorId: actor.actorId, - contextSnapshot: { issueId: issue2.id, source: "issue.checkout" } - }).catch((err) => logger.warn({ err, issueId: issue2.id }, "failed to wake assignee on issue checkout")); - } - res.json(updated); - }); - router2.post("/issues/:id/release", async (req, res) => { - const id = req.params.id; - const existing = await svc.getById(id); - if (!existing) { - res.status(404).json({ error: "Issue not found" }); - return; - } - assertCompanyAccess(req, existing.companyId); - if (!await assertAgentRunCheckoutOwnership(req, res, existing)) return; - const actorRunId = requireAgentRunId(req, res); - if (req.actor.type === "agent" && !actorRunId) return; - const released = await svc.release( - id, - req.actor.type === "agent" ? req.actor.agentId : void 0, - actorRunId - ); - if (!released) { - res.status(404).json({ error: "Issue not found" }); - return; - } - const actor = getActorInfo(req); - await logActivity(db, { - companyId: released.companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - runId: actor.runId, - action: "issue.released", - entityType: "issue", - entityId: released.id - }); - res.json(released); - }); - router2.get("/issues/:id/comments", async (req, res) => { - const id = req.params.id; - const issue2 = await svc.getById(id); - if (!issue2) { - res.status(404).json({ error: "Issue not found" }); - return; - } - assertCompanyAccess(req, issue2.companyId); - const afterCommentId = typeof req.query.after === "string" && req.query.after.trim().length > 0 ? req.query.after.trim() : typeof req.query.afterCommentId === "string" && req.query.afterCommentId.trim().length > 0 ? req.query.afterCommentId.trim() : null; - const order = typeof req.query.order === "string" && req.query.order.trim().toLowerCase() === "asc" ? "asc" : "desc"; - const limitRaw = typeof req.query.limit === "string" && req.query.limit.trim().length > 0 ? Number(req.query.limit) : null; - const limit = limitRaw && Number.isFinite(limitRaw) && limitRaw > 0 ? Math.min(Math.floor(limitRaw), MAX_ISSUE_COMMENT_LIMIT) : null; - const comments = await svc.listComments(id, { - afterCommentId, - order, - limit - }); - res.json(comments); - }); - router2.get("/issues/:id/comments/:commentId", async (req, res) => { - const id = req.params.id; - const commentId = req.params.commentId; - const issue2 = await svc.getById(id); - if (!issue2) { - res.status(404).json({ error: "Issue not found" }); - return; - } - assertCompanyAccess(req, issue2.companyId); - const comment = await svc.getComment(commentId); - if (!comment || comment.issueId !== id) { - res.status(404).json({ error: "Comment not found" }); - return; - } - res.json(comment); - }); - router2.delete("/issues/:id/comments/:commentId", async (req, res) => { - const id = req.params.id; - const commentId = req.params.commentId; - const issue2 = await svc.getById(id); - if (!issue2) { - res.status(404).json({ error: "Issue not found" }); - return; - } - assertCompanyAccess(req, issue2.companyId); - if (!await assertAgentRunCheckoutOwnership(req, res, issue2)) return; - const comment = await svc.getComment(commentId); - if (!comment || comment.issueId !== id) { - res.status(404).json({ error: "Comment not found" }); - return; - } - const actor = getActorInfo(req); - const actorOwnsComment = actor.actorType === "agent" ? comment.authorAgentId === actor.agentId : comment.authorUserId === actor.actorId; - if (!actorOwnsComment) { - res.status(403).json({ error: "Only the comment author can cancel queued comments" }); - return; - } - const activeRun = await resolveActiveIssueRun(issue2); - if (!activeRun) { - res.status(409).json({ error: "Queued comment can no longer be canceled" }); - return; - } - if (!isQueuedIssueCommentForActiveRun({ comment, activeRun })) { - res.status(409).json({ error: "Only queued comments can be canceled" }); - return; - } - const removed = await svc.removeComment(commentId); - if (!removed) { - res.status(404).json({ error: "Comment not found" }); - return; - } - await logActivity(db, { - companyId: issue2.companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - runId: actor.runId, - action: "issue.comment_cancelled", - entityType: "issue", - entityId: issue2.id, - details: { - commentId: removed.id, - bodySnippet: removed.body.slice(0, 120), - identifier: issue2.identifier, - issueTitle: issue2.title, - source: "queue_cancel", - queueTargetRunId: activeRun.id - } - }); - res.json(removed); - }); - router2.get("/issues/:id/feedback-votes", async (req, res) => { - const id = req.params.id; - const issue2 = await svc.getById(id); - if (!issue2) { - res.status(404).json({ error: "Issue not found" }); - return; - } - assertCompanyAccess(req, issue2.companyId); - if (req.actor.type !== "board") { - res.status(403).json({ error: "Only board users can view feedback votes" }); - return; - } - const votes = await feedback.listIssueVotesForUser(id, req.actor.userId ?? "local-board"); - res.json(votes); - }); - router2.get("/issues/:id/feedback-traces", async (req, res) => { - const id = req.params.id; - const issue2 = await svc.getById(id); - if (!issue2) { - res.status(404).json({ error: "Issue not found" }); - return; - } - assertCompanyAccess(req, issue2.companyId); - if (req.actor.type !== "board") { - res.status(403).json({ error: "Only board users can view feedback traces" }); - return; - } - const targetTypeRaw = typeof req.query.targetType === "string" ? req.query.targetType : void 0; - const voteRaw = typeof req.query.vote === "string" ? req.query.vote : void 0; - const statusRaw = typeof req.query.status === "string" ? req.query.status : void 0; - const targetType = targetTypeRaw ? feedbackTargetTypeSchema.parse(targetTypeRaw) : void 0; - const vote = voteRaw ? feedbackVoteValueSchema.parse(voteRaw) : void 0; - const status = statusRaw ? feedbackTraceStatusSchema.parse(statusRaw) : void 0; - const traces = await feedback.listFeedbackTraces({ - companyId: issue2.companyId, - issueId: issue2.id, - targetType, - vote, - status, - from: parseDateQuery(req.query.from, "from"), - to: parseDateQuery(req.query.to, "to"), - sharedOnly: parseBooleanQuery(req.query.sharedOnly), - includePayload: parseBooleanQuery(req.query.includePayload) - }); - res.json(traces); - }); - router2.get("/feedback-traces/:traceId", async (req, res) => { - const traceId = req.params.traceId; - if (req.actor.type !== "board") { - res.status(403).json({ error: "Only board users can view feedback traces" }); - return; - } - const includePayload = parseBooleanQuery(req.query.includePayload) || req.query.includePayload === void 0; - const trace = await feedback.getFeedbackTraceById(traceId, includePayload); - if (!trace || !actorCanAccessCompany(req, trace.companyId)) { - res.status(404).json({ error: "Feedback trace not found" }); - return; - } - res.json(trace); - }); - router2.get("/feedback-traces/:traceId/bundle", async (req, res) => { - const traceId = req.params.traceId; - if (req.actor.type !== "board") { - res.status(403).json({ error: "Only board users can view feedback trace bundles" }); - return; - } - const bundle = await feedback.getFeedbackTraceBundle(traceId); - if (!bundle || !actorCanAccessCompany(req, bundle.companyId)) { - res.status(404).json({ error: "Feedback trace not found" }); - return; - } - res.json(bundle); - }); - router2.post("/issues/:id/comments", validate(addIssueCommentSchema), async (req, res) => { - const id = req.params.id; - const issue2 = await svc.getById(id); - if (!issue2) { - res.status(404).json({ error: "Issue not found" }); - return; - } - assertCompanyAccess(req, issue2.companyId); - if (!await assertAgentRunCheckoutOwnership(req, res, issue2)) return; - const closedExecutionWorkspace = await getClosedIssueExecutionWorkspace(issue2); - if (closedExecutionWorkspace) { - respondClosedIssueExecutionWorkspace(res, closedExecutionWorkspace); - return; - } - const actor = getActorInfo(req); - const reopenRequested = req.body.reopen === true; - const interruptRequested = req.body.interrupt === true; - const isClosed = isClosedIssueStatus(issue2.status); - const effectiveReopenRequested = reopenRequested || shouldImplicitlyReopenCommentForAgent({ - issueStatus: issue2.status, - assigneeAgentId: issue2.assigneeAgentId, - actorType: actor.actorType, - actorId: actor.actorId - }); - let reopened = false; - let reopenFromStatus = null; - let interruptedRunId = null; - let currentIssue = issue2; - if (effectiveReopenRequested && isClosed) { - const reopenedIssue = await svc.update(id, { status: "todo" }); - if (!reopenedIssue) { - res.status(404).json({ error: "Issue not found" }); - return; - } - reopened = true; - reopenFromStatus = issue2.status; - currentIssue = reopenedIssue; - await logActivity(db, { - companyId: currentIssue.companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - runId: actor.runId, - action: "issue.updated", - entityType: "issue", - entityId: currentIssue.id, - details: { - status: "todo", - reopened: true, - reopenedFrom: reopenFromStatus, - source: "comment", - identifier: currentIssue.identifier - } - }); - } - if (interruptRequested) { - if (req.actor.type !== "board") { - res.status(403).json({ error: "Only board users can interrupt active runs from issue comments" }); - return; - } - const runToInterrupt = await resolveActiveIssueRun(currentIssue); - if (runToInterrupt) { - const cancelled = await heartbeat.cancelRun(runToInterrupt.id); - if (cancelled) { - interruptedRunId = cancelled.id; - await logActivity(db, { - companyId: cancelled.companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - runId: actor.runId, - action: "heartbeat.cancelled", - entityType: "heartbeat_run", - entityId: cancelled.id, - details: { agentId: cancelled.agentId, source: "issue_comment_interrupt", issueId: currentIssue.id } - }); - } - } - } - const comment = await svc.addComment(id, req.body.body, { - agentId: actor.agentId ?? void 0, - userId: actor.actorType === "user" ? actor.actorId : void 0, - runId: actor.runId - }); - if (actor.runId) { - await heartbeat.reportRunActivity(actor.runId).catch((err) => logger.warn({ err, runId: actor.runId }, "failed to clear detached run warning after issue comment")); - } - await logActivity(db, { - companyId: currentIssue.companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - runId: actor.runId, - action: "issue.comment_added", - entityType: "issue", - entityId: currentIssue.id, - details: { - commentId: comment.id, - bodySnippet: comment.body.slice(0, 120), - identifier: currentIssue.identifier, - issueTitle: currentIssue.title, - ...reopened ? { reopened: true, reopenedFrom: reopenFromStatus, source: "comment" } : {}, - ...interruptedRunId ? { interruptedRunId } : {} - } - }); - void (async () => { - const wakeups = /* @__PURE__ */ new Map(); - const assigneeId = currentIssue.assigneeAgentId; - const actorIsAgent = actor.actorType === "agent"; - const selfComment = actorIsAgent && actor.actorId === assigneeId; - const skipWake = selfComment || isClosed; - if (assigneeId && (reopened || !skipWake)) { - if (reopened) { - wakeups.set(assigneeId, { - source: "automation", - triggerDetail: "system", - reason: "issue_reopened_via_comment", - payload: { - issueId: currentIssue.id, - commentId: comment.id, - reopenedFrom: reopenFromStatus, - mutation: "comment", - ...interruptedRunId ? { interruptedRunId } : {} - }, - requestedByActorType: actor.actorType, - requestedByActorId: actor.actorId, - contextSnapshot: { - issueId: currentIssue.id, - taskId: currentIssue.id, - commentId: comment.id, - wakeCommentId: comment.id, - source: "issue.comment.reopen", - wakeReason: "issue_reopened_via_comment", - reopenedFrom: reopenFromStatus, - ...interruptedRunId ? { interruptedRunId } : {} - } - }); - } else { - wakeups.set(assigneeId, { - source: "automation", - triggerDetail: "system", - reason: "issue_commented", - payload: { - issueId: currentIssue.id, - commentId: comment.id, - mutation: "comment", - ...interruptedRunId ? { interruptedRunId } : {} - }, - requestedByActorType: actor.actorType, - requestedByActorId: actor.actorId, - contextSnapshot: { - issueId: currentIssue.id, - taskId: currentIssue.id, - commentId: comment.id, - wakeCommentId: comment.id, - source: "issue.comment", - wakeReason: "issue_commented", - ...interruptedRunId ? { interruptedRunId } : {} - } - }); - } - } - let mentionedIds = []; - try { - mentionedIds = await svc.findMentionedAgents(issue2.companyId, req.body.body); - } catch (err) { - logger.warn({ err, issueId: id }, "failed to resolve @-mentions"); - } - for (const mentionedId of mentionedIds) { - if (wakeups.has(mentionedId)) continue; - if (actorIsAgent && actor.actorId === mentionedId) continue; - wakeups.set(mentionedId, { - source: "automation", - triggerDetail: "system", - reason: "issue_comment_mentioned", - payload: { issueId: id, commentId: comment.id }, - requestedByActorType: actor.actorType, - requestedByActorId: actor.actorId, - contextSnapshot: { - issueId: id, - taskId: id, - commentId: comment.id, - wakeCommentId: comment.id, - wakeReason: "issue_comment_mentioned", - source: "comment.mention" - } - }); - } - for (const [agentId, wakeup] of wakeups.entries()) { - heartbeat.wakeup(agentId, wakeup).catch((err) => logger.warn({ err, issueId: currentIssue.id, agentId }, "failed to wake agent on issue comment")); - } - })(); - res.status(201).json(comment); - }); - router2.post("/issues/:id/feedback-votes", validate(upsertIssueFeedbackVoteSchema), async (req, res) => { - const id = req.params.id; - const issue2 = await svc.getById(id); - if (!issue2) { - res.status(404).json({ error: "Issue not found" }); - return; - } - assertCompanyAccess(req, issue2.companyId); - if (req.actor.type !== "board") { - res.status(403).json({ error: "Only board users can vote on AI feedback" }); - return; - } - const actor = getActorInfo(req); - const result = await feedback.saveIssueVote({ - issueId: id, - targetType: req.body.targetType, - targetId: req.body.targetId, - vote: req.body.vote, - reason: req.body.reason, - authorUserId: req.actor.userId ?? "local-board", - allowSharing: req.body.allowSharing === true - }); - await logActivity(db, { - companyId: issue2.companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - runId: actor.runId, - action: "issue.feedback_vote_saved", - entityType: "issue", - entityId: issue2.id, - details: { - identifier: issue2.identifier, - targetType: result.vote.targetType, - targetId: result.vote.targetId, - vote: result.vote.vote, - hasReason: Boolean(result.vote.reason), - sharingEnabled: result.sharingEnabled - } - }); - if (result.consentEnabledNow) { - await logActivity(db, { - companyId: issue2.companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - runId: actor.runId, - action: "company.feedback_data_sharing_updated", - entityType: "company", - entityId: issue2.companyId, - details: { - feedbackDataSharingEnabled: true, - source: "issue_feedback_vote" - } - }); - } - if (result.persistedSharingPreference) { - const settings = await instanceSettings2.get(); - const companyIds = await instanceSettings2.listCompanyIds(); - await Promise.all( - companyIds.map( - (companyId) => logActivity(db, { - companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - runId: actor.runId, - action: "instance.settings.general_updated", - entityType: "instance_settings", - entityId: settings.id, - details: { - general: settings.general, - changedKeys: ["feedbackDataSharingPreference"], - source: "issue_feedback_vote" - } - }) - ) - ); - } - if (result.sharingEnabled && result.traceId && feedbackExportService) { - try { - await feedbackExportService.flushPendingFeedbackTraces({ - companyId: issue2.companyId, - traceId: result.traceId, - limit: 1 - }); - } catch (err) { - logger.warn({ err, issueId: issue2.id, traceId: result.traceId }, "failed to flush shared feedback trace immediately"); - } - } - res.status(201).json(result.vote); - }); - router2.get("/issues/:id/attachments", async (req, res) => { - const issueId = req.params.id; - const issue2 = await svc.getById(issueId); - if (!issue2) { - res.status(404).json({ error: "Issue not found" }); - return; - } - assertCompanyAccess(req, issue2.companyId); - const attachments = await svc.listAttachments(issueId); - res.json(attachments.map(withContentPath)); - }); - router2.post("/companies/:companyId/issues/:issueId/attachments", async (req, res) => { - const companyId = req.params.companyId; - const issueId = req.params.issueId; - assertCompanyAccess(req, companyId); - const issue2 = await svc.getById(issueId); - if (!issue2) { - res.status(404).json({ error: "Issue not found" }); - return; - } - if (issue2.companyId !== companyId) { - res.status(422).json({ error: "Issue does not belong to company" }); - return; - } - try { - await runSingleFileUpload(req, res); - } catch (err) { - if (err instanceof import_multer.default.MulterError) { - if (err.code === "LIMIT_FILE_SIZE") { - res.status(422).json({ error: `Attachment exceeds ${MAX_ATTACHMENT_BYTES} bytes` }); - return; - } - res.status(400).json({ error: err.message }); - return; - } - throw err; - } - const file2 = req.file; - if (!file2) { - res.status(400).json({ error: "Missing file field 'file'" }); - return; - } - const contentType = normalizeContentType(file2.mimetype); - if (file2.buffer.length <= 0) { - res.status(422).json({ error: "Attachment is empty" }); - return; - } - const parsedMeta = createIssueAttachmentMetadataSchema.safeParse(req.body ?? {}); - if (!parsedMeta.success) { - res.status(400).json({ error: "Invalid attachment metadata", details: parsedMeta.error.issues }); - return; - } - const actor = getActorInfo(req); - const stored = await storage.putFile({ - companyId, - namespace: `issues/${issueId}`, - originalFilename: file2.originalname || null, - contentType, - body: file2.buffer - }); - const attachment = await svc.createAttachment({ - issueId, - issueCommentId: parsedMeta.data.issueCommentId ?? null, - provider: stored.provider, - objectKey: stored.objectKey, - contentType: stored.contentType, - byteSize: stored.byteSize, - sha256: stored.sha256, - originalFilename: stored.originalFilename, - createdByAgentId: actor.agentId, - createdByUserId: actor.actorType === "user" ? actor.actorId : null - }); - await logActivity(db, { - companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - runId: actor.runId, - action: "issue.attachment_added", - entityType: "issue", - entityId: issueId, - details: { - attachmentId: attachment.id, - originalFilename: attachment.originalFilename, - contentType: attachment.contentType, - byteSize: attachment.byteSize - } - }); - res.status(201).json(withContentPath(attachment)); - }); - router2.get("/attachments/:attachmentId/content", async (req, res, next) => { - const attachmentId = req.params.attachmentId; - const attachment = await svc.getAttachmentById(attachmentId); - if (!attachment) { - res.status(404).json({ error: "Attachment not found" }); - return; - } - assertCompanyAccess(req, attachment.companyId); - const object2 = await storage.getObject(attachment.companyId, attachment.objectKey); - const responseContentType = normalizeContentType(attachment.contentType || object2.contentType); - res.setHeader("Content-Type", responseContentType); - res.setHeader("Content-Length", String(attachment.byteSize || object2.contentLength || 0)); - res.setHeader("Cache-Control", "private, max-age=60"); - res.setHeader("X-Content-Type-Options", "nosniff"); - if (responseContentType === SVG_CONTENT_TYPE) { - res.setHeader("Content-Security-Policy", "sandbox; default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'"); - } - const filename = attachment.originalFilename ?? "attachment"; - const disposition = isInlineAttachmentContentType(responseContentType) ? "inline" : "attachment"; - res.setHeader("Content-Disposition", `${disposition}; filename="${filename.replaceAll('"', "")}"`); - object2.stream.on("error", (err) => { - next(err); - }); - object2.stream.pipe(res); - }); - router2.delete("/attachments/:attachmentId", async (req, res) => { - const attachmentId = req.params.attachmentId; - const attachment = await svc.getAttachmentById(attachmentId); - if (!attachment) { - res.status(404).json({ error: "Attachment not found" }); - return; - } - assertCompanyAccess(req, attachment.companyId); - try { - await storage.deleteObject(attachment.companyId, attachment.objectKey); - } catch (err) { - logger.warn({ err, attachmentId }, "storage delete failed while removing attachment"); - } - const removed = await svc.removeAttachment(attachmentId); - if (!removed) { - res.status(404).json({ error: "Attachment not found" }); - return; - } - const actor = getActorInfo(req); - await logActivity(db, { - companyId: removed.companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - runId: actor.runId, - action: "issue.attachment_removed", - entityType: "issue", - entityId: removed.issueId, - details: { - attachmentId: removed.id - } - }); - res.json({ ok: true }); - }); - return router2; -} - -// server/src/routes/routines.ts -var import_express7 = __toESM(require_express2(), 1); -function routineRoutes(db) { - const router2 = (0, import_express7.Router)(); - const svc = routineService(db); - const access = accessService(db); - async function assertBoardCanAssignTasks(req, companyId) { - assertCompanyAccess(req, companyId); - if (req.actor.type !== "board") return; - if (req.actor.source === "local_implicit" || req.actor.isInstanceAdmin) return; - const allowed2 = await access.canUser(companyId, req.actor.userId, "tasks:assign"); - if (!allowed2) { - throw forbidden("Missing permission: tasks:assign"); - } - } - function assertCanManageCompanyRoutine(req, companyId, assigneeAgentId) { - assertCompanyAccess(req, companyId); - if (req.actor.type === "board") return; - if (req.actor.type !== "agent" || !req.actor.agentId) throw unauthorized(); - if (assigneeAgentId !== req.actor.agentId) { - throw forbidden("Agents can only manage routines assigned to themselves"); - } - } - async function assertCanManageExistingRoutine(req, routineId) { - const routine = await svc.get(routineId); - if (!routine) return null; - assertCompanyAccess(req, routine.companyId); - if (req.actor.type === "board") return routine; - if (req.actor.type !== "agent" || !req.actor.agentId) throw unauthorized(); - if (routine.assigneeAgentId !== req.actor.agentId) { - throw forbidden("Agents can only manage routines assigned to themselves"); - } - return routine; - } - router2.get("/companies/:companyId/routines", async (req, res) => { - const companyId = req.params.companyId; - assertCompanyAccess(req, companyId); - const result = await svc.list(companyId); - res.json(result); - }); - router2.post("/companies/:companyId/routines", validate(createRoutineSchema), async (req, res) => { - const companyId = req.params.companyId; - await assertBoardCanAssignTasks(req, companyId); - assertCanManageCompanyRoutine(req, companyId, req.body.assigneeAgentId); - const created = await svc.create(companyId, req.body, { - agentId: req.actor.type === "agent" ? req.actor.agentId : null, - userId: req.actor.type === "board" ? req.actor.userId ?? "board" : null - }); - const actor = getActorInfo(req); - await logActivity(db, { - companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - runId: actor.runId, - action: "routine.created", - entityType: "routine", - entityId: created.id, - details: { title: created.title, assigneeAgentId: created.assigneeAgentId } - }); - const telemetryClient = getTelemetryClient(); - if (telemetryClient) { - trackRoutineCreated(telemetryClient); - } - res.status(201).json(created); - }); - router2.get("/routines/:id", async (req, res) => { - const detail = await svc.getDetail(req.params.id); - if (!detail) { - res.status(404).json({ error: "Routine not found" }); - return; - } - assertCompanyAccess(req, detail.companyId); - res.json(detail); - }); - router2.patch("/routines/:id", validate(updateRoutineSchema), async (req, res) => { - const routine = await assertCanManageExistingRoutine(req, req.params.id); - if (!routine) { - res.status(404).json({ error: "Routine not found" }); - return; - } - const assigneeWillChange = req.body.assigneeAgentId !== void 0 && req.body.assigneeAgentId !== routine.assigneeAgentId; - if (assigneeWillChange) { - await assertBoardCanAssignTasks(req, routine.companyId); - } - const statusWillActivate = req.body.status !== void 0 && req.body.status === "active" && routine.status !== "active"; - if (statusWillActivate) { - await assertBoardCanAssignTasks(req, routine.companyId); - } - if (req.actor.type === "agent" && req.body.assigneeAgentId !== void 0 && req.body.assigneeAgentId !== req.actor.agentId) { - throw forbidden("Agents can only assign routines to themselves"); - } - const updated = await svc.update(routine.id, req.body, { - agentId: req.actor.type === "agent" ? req.actor.agentId : null, - userId: req.actor.type === "board" ? req.actor.userId ?? "board" : null - }); - const actor = getActorInfo(req); - await logActivity(db, { - companyId: routine.companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - runId: actor.runId, - action: "routine.updated", - entityType: "routine", - entityId: routine.id, - details: { title: updated?.title ?? routine.title } - }); - res.json(updated); - }); - router2.get("/routines/:id/runs", async (req, res) => { - const routine = await svc.get(req.params.id); - if (!routine) { - res.status(404).json({ error: "Routine not found" }); - return; - } - assertCompanyAccess(req, routine.companyId); - const limit = Number(req.query.limit ?? 50); - const result = await svc.listRuns(routine.id, Number.isFinite(limit) ? limit : 50); - res.json(result); - }); - router2.post("/routines/:id/triggers", validate(createRoutineTriggerSchema), async (req, res) => { - const routine = await assertCanManageExistingRoutine(req, req.params.id); - if (!routine) { - res.status(404).json({ error: "Routine not found" }); - return; - } - await assertBoardCanAssignTasks(req, routine.companyId); - const created = await svc.createTrigger(routine.id, req.body, { - agentId: req.actor.type === "agent" ? req.actor.agentId : null, - userId: req.actor.type === "board" ? req.actor.userId ?? "board" : null - }); - const actor = getActorInfo(req); - await logActivity(db, { - companyId: routine.companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - runId: actor.runId, - action: "routine.trigger_created", - entityType: "routine_trigger", - entityId: created.trigger.id, - details: { routineId: routine.id, kind: created.trigger.kind } - }); - res.status(201).json(created); - }); - router2.patch("/routine-triggers/:id", validate(updateRoutineTriggerSchema), async (req, res) => { - const trigger = await svc.getTrigger(req.params.id); - if (!trigger) { - res.status(404).json({ error: "Routine trigger not found" }); - return; - } - const routine = await assertCanManageExistingRoutine(req, trigger.routineId); - if (!routine) { - res.status(404).json({ error: "Routine not found" }); - return; - } - await assertBoardCanAssignTasks(req, routine.companyId); - const updated = await svc.updateTrigger(trigger.id, req.body, { - agentId: req.actor.type === "agent" ? req.actor.agentId : null, - userId: req.actor.type === "board" ? req.actor.userId ?? "board" : null - }); - const actor = getActorInfo(req); - await logActivity(db, { - companyId: routine.companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - runId: actor.runId, - action: "routine.trigger_updated", - entityType: "routine_trigger", - entityId: trigger.id, - details: { routineId: routine.id, kind: updated?.kind ?? trigger.kind } - }); - res.json(updated); - }); - router2.delete("/routine-triggers/:id", async (req, res) => { - const trigger = await svc.getTrigger(req.params.id); - if (!trigger) { - res.status(404).json({ error: "Routine trigger not found" }); - return; - } - const routine = await assertCanManageExistingRoutine(req, trigger.routineId); - if (!routine) { - res.status(404).json({ error: "Routine not found" }); - return; - } - await svc.deleteTrigger(trigger.id); - const actor = getActorInfo(req); - await logActivity(db, { - companyId: routine.companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - runId: actor.runId, - action: "routine.trigger_deleted", - entityType: "routine_trigger", - entityId: trigger.id, - details: { routineId: routine.id, kind: trigger.kind } - }); - res.status(204).end(); - }); - router2.post( - "/routine-triggers/:id/rotate-secret", - validate(rotateRoutineTriggerSecretSchema), - async (req, res) => { - const trigger = await svc.getTrigger(req.params.id); - if (!trigger) { - res.status(404).json({ error: "Routine trigger not found" }); - return; - } - const routine = await assertCanManageExistingRoutine(req, trigger.routineId); - if (!routine) { - res.status(404).json({ error: "Routine not found" }); - return; - } - const rotated = await svc.rotateTriggerSecret(trigger.id, { - agentId: req.actor.type === "agent" ? req.actor.agentId : null, - userId: req.actor.type === "board" ? req.actor.userId ?? "board" : null - }); - const actor = getActorInfo(req); - await logActivity(db, { - companyId: routine.companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - runId: actor.runId, - action: "routine.trigger_secret_rotated", - entityType: "routine_trigger", - entityId: trigger.id, - details: { routineId: routine.id } - }); - res.json(rotated); - } - ); - router2.post("/routines/:id/run", validate(runRoutineSchema), async (req, res) => { - const routine = await assertCanManageExistingRoutine(req, req.params.id); - if (!routine) { - res.status(404).json({ error: "Routine not found" }); - return; - } - await assertBoardCanAssignTasks(req, routine.companyId); - const run = await svc.runRoutine(routine.id, req.body); - const actor = getActorInfo(req); - await logActivity(db, { - companyId: routine.companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - runId: actor.runId, - action: "routine.run_triggered", - entityType: "routine_run", - entityId: run.id, - details: { routineId: routine.id, source: run.source, status: run.status } - }); - res.status(202).json(run); - }); - router2.post("/routine-triggers/public/:publicId/fire", async (req, res) => { - const result = await svc.firePublicTrigger(req.params.publicId, { - authorizationHeader: req.header("authorization"), - signatureHeader: req.header("x-taskcore-signature"), - hubSignatureHeader: req.header("x-hub-signature-256"), - timestampHeader: req.header("x-taskcore-timestamp"), - idempotencyKey: req.header("idempotency-key"), - rawBody: req.rawBody ?? null, - payload: typeof req.body === "object" && req.body !== null ? req.body : null - }); - res.status(202).json(result); - }); - return router2; -} - -// server/src/routes/execution-workspaces.ts -init_drizzle_orm(); -var import_express8 = __toESM(require_express2(), 1); -init_src2(); -function executionWorkspaceRoutes(db) { - const router2 = (0, import_express8.Router)(); - const svc = executionWorkspaceService(db); - const workspaceOperationsSvc = workspaceOperationService(db); - router2.get("/companies/:companyId/execution-workspaces", async (req, res) => { - const companyId = req.params.companyId; - assertCompanyAccess(req, companyId); - const workspaces = await svc.list(companyId, { - projectId: req.query.projectId, - projectWorkspaceId: req.query.projectWorkspaceId, - issueId: req.query.issueId, - status: req.query.status, - reuseEligible: req.query.reuseEligible === "true" - }); - res.json(workspaces); - }); - router2.get("/execution-workspaces/:id", async (req, res) => { - const id = req.params.id; - const workspace = await svc.getById(id); - if (!workspace) { - res.status(404).json({ error: "Execution workspace not found" }); - return; - } - assertCompanyAccess(req, workspace.companyId); - res.json(workspace); - }); - router2.get("/execution-workspaces/:id/close-readiness", async (req, res) => { - const id = req.params.id; - const workspace = await svc.getById(id); - if (!workspace) { - res.status(404).json({ error: "Execution workspace not found" }); - return; - } - assertCompanyAccess(req, workspace.companyId); - const readiness = await svc.getCloseReadiness(id); - if (!readiness) { - res.status(404).json({ error: "Execution workspace not found" }); - return; - } - res.json(readiness); - }); - router2.get("/execution-workspaces/:id/workspace-operations", async (req, res) => { - const id = req.params.id; - const workspace = await svc.getById(id); - if (!workspace) { - res.status(404).json({ error: "Execution workspace not found" }); - return; - } - assertCompanyAccess(req, workspace.companyId); - const operations = await workspaceOperationsSvc.listForExecutionWorkspace(id); - res.json(operations); - }); - async function handleExecutionWorkspaceRuntimeCommand(req, res) { - const id = req.params.id; - const action = String(req.params.action ?? "").trim().toLowerCase(); - if (action !== "start" && action !== "stop" && action !== "restart" && action !== "run") { - res.status(404).json({ error: "Workspace command action not found" }); - return; - } - const existing = await svc.getById(id); - if (!existing) { - res.status(404).json({ error: "Execution workspace not found" }); - return; - } - assertCompanyAccess(req, existing.companyId); - const workspaceCwd = existing.cwd; - if (!workspaceCwd) { - res.status(422).json({ error: "Execution workspace needs a local path before Taskcore can run workspace commands" }); - return; - } - const projectWorkspace = existing.projectWorkspaceId ? await db.select({ - id: projectWorkspaces.id, - cwd: projectWorkspaces.cwd, - repoUrl: projectWorkspaces.repoUrl, - repoRef: projectWorkspaces.repoRef, - defaultRef: projectWorkspaces.defaultRef, - metadata: projectWorkspaces.metadata - }).from(projectWorkspaces).where( - and( - eq(projectWorkspaces.id, existing.projectWorkspaceId), - eq(projectWorkspaces.companyId, existing.companyId) - ) - ).then((rows) => rows[0] ?? null) : null; - const projectWorkspaceRuntime = readProjectWorkspaceRuntimeConfig( - projectWorkspace?.metadata ?? null - )?.workspaceRuntime ?? null; - const projectPolicy = existing.projectId ? await db.select({ - executionWorkspacePolicy: projects.executionWorkspacePolicy - }).from(projects).where( - and( - eq(projects.id, existing.projectId), - eq(projects.companyId, existing.companyId) - ) - ).then((rows) => parseProjectExecutionWorkspacePolicy(rows[0]?.executionWorkspacePolicy)) : null; - const effectiveRuntimeConfig = existing.config?.workspaceRuntime ?? projectWorkspaceRuntime ?? null; - const target = req.body; - const configuredServices = effectiveRuntimeConfig ? listConfiguredRuntimeServiceEntries({ workspaceRuntime: effectiveRuntimeConfig }) : []; - const workspaceCommand = effectiveRuntimeConfig ? findWorkspaceCommandDefinition(effectiveRuntimeConfig, target.workspaceCommandId ?? null) : null; - if (target.workspaceCommandId && !workspaceCommand) { - res.status(404).json({ error: "Workspace command not found for this execution workspace" }); - return; - } - if (target.runtimeServiceId && !(existing.runtimeServices ?? []).some((service) => service.id === target.runtimeServiceId)) { - res.status(404).json({ error: "Runtime service not found for this execution workspace" }); - return; - } - const matchedRuntimeService = workspaceCommand?.kind === "service" && !target.runtimeServiceId ? matchWorkspaceRuntimeServiceToCommand(workspaceCommand, existing.runtimeServices ?? []) : null; - const selectedRuntimeServiceId = target.runtimeServiceId ?? matchedRuntimeService?.id ?? null; - const selectedServiceIndex = workspaceCommand?.kind === "service" ? workspaceCommand.serviceIndex : target.serviceIndex ?? null; - if (selectedServiceIndex !== void 0 && selectedServiceIndex !== null && (selectedServiceIndex < 0 || selectedServiceIndex >= configuredServices.length)) { - res.status(422).json({ error: "Selected runtime service is not defined in this execution workspace runtime config" }); - return; - } - if (workspaceCommand?.kind === "job" && action !== "run") { - res.status(422).json({ error: `Workspace job "${workspaceCommand.name}" can only be run` }); - return; - } - if (workspaceCommand?.kind === "service" && action === "run") { - res.status(422).json({ error: `Workspace service "${workspaceCommand.name}" should be started or restarted, not run` }); - return; - } - if (action === "run" && !workspaceCommand) { - res.status(422).json({ error: "Select a workspace job to run" }); - return; - } - if ((action === "start" || action === "restart") && !effectiveRuntimeConfig) { - res.status(422).json({ error: "Execution workspace has no workspace command configuration or inherited project workspace default" }); - return; - } - const actor = getActorInfo(req); - const recorder = workspaceOperationsSvc.createRecorder({ - companyId: existing.companyId, - executionWorkspaceId: existing.id - }); - let runtimeServiceCount = existing.runtimeServices?.length ?? 0; - const stdout = []; - const stderr = []; - const operation2 = await recorder.recordOperation({ - phase: action === "stop" ? "workspace_teardown" : "workspace_provision", - command: workspaceCommand?.command ?? `workspace command ${action}`, - cwd: existing.cwd, - metadata: { - action, - executionWorkspaceId: existing.id, - workspaceCommandId: workspaceCommand?.id ?? target.workspaceCommandId ?? null, - workspaceCommandKind: workspaceCommand?.kind ?? null, - workspaceCommandName: workspaceCommand?.name ?? null, - runtimeServiceId: selectedRuntimeServiceId, - serviceIndex: selectedServiceIndex - }, - run: async () => { - const ensureWorkspaceAvailable = async () => await ensurePersistedExecutionWorkspaceAvailable({ - base: { - baseCwd: projectWorkspace?.cwd ?? workspaceCwd, - source: existing.mode === "shared_workspace" ? "project_primary" : "task_session", - projectId: existing.projectId, - workspaceId: existing.projectWorkspaceId, - repoUrl: existing.repoUrl, - repoRef: existing.baseRef - }, - workspace: { - mode: existing.mode, - strategyType: existing.strategyType, - cwd: existing.cwd, - providerRef: existing.providerRef, - projectId: existing.projectId, - projectWorkspaceId: existing.projectWorkspaceId, - repoUrl: existing.repoUrl, - baseRef: existing.baseRef, - branchName: existing.branchName, - config: { - ...existing.config, - provisionCommand: existing.config?.provisionCommand ?? projectPolicy?.workspaceStrategy?.provisionCommand ?? null - } - }, - issue: existing.sourceIssueId ? { - id: existing.sourceIssueId, - identifier: null, - title: existing.name - } : null, - agent: { - id: actor.agentId ?? null, - name: actor.actorType === "user" ? "Board" : "Agent", - companyId: existing.companyId - }, - recorder - }); - if (action === "run") { - if (!workspaceCommand || workspaceCommand.kind !== "job") { - throw new Error("Workspace job selection is required"); - } - const availableWorkspace = await ensureWorkspaceAvailable(); - if (!availableWorkspace) { - throw new Error("Execution workspace needs a local path before Taskcore can run workspace commands"); - } - return await runWorkspaceJobForControl({ - actor: { - id: actor.agentId ?? null, - name: actor.actorType === "user" ? "Board" : "Agent", - companyId: existing.companyId - }, - issue: existing.sourceIssueId ? { - id: existing.sourceIssueId, - identifier: null, - title: existing.name - } : null, - workspace: availableWorkspace, - command: workspaceCommand.rawConfig, - adapterEnv: {}, - recorder, - metadata: { - action, - executionWorkspaceId: existing.id, - workspaceCommandId: workspaceCommand.id - } - }).then((nestedOperation) => ({ - status: "succeeded", - exitCode: 0, - metadata: { - nestedOperationId: nestedOperation?.id ?? null, - runtimeServiceCount - } - })); - } - const onLog = async (stream, chunk) => { - if (stream === "stdout") stdout.push(chunk); - else stderr.push(chunk); - }; - if (action === "stop" || action === "restart") { - await stopRuntimeServicesForExecutionWorkspace({ - db, - executionWorkspaceId: existing.id, - workspaceCwd, - runtimeServiceId: selectedRuntimeServiceId - }); - } - if (action === "start" || action === "restart") { - const availableWorkspace = await ensureWorkspaceAvailable(); - if (!availableWorkspace) { - throw new Error("Execution workspace needs a local path before Taskcore can manage local runtime services"); - } - const startedServices = await startRuntimeServicesForWorkspaceControl({ - db, - actor: { - id: actor.agentId ?? null, - name: actor.actorType === "user" ? "Board" : "Agent", - companyId: existing.companyId - }, - issue: existing.sourceIssueId ? { - id: existing.sourceIssueId, - identifier: null, - title: existing.name - } : null, - workspace: availableWorkspace, - executionWorkspaceId: existing.id, - config: { workspaceRuntime: effectiveRuntimeConfig }, - adapterEnv: {}, - onLog, - serviceIndex: selectedServiceIndex - }); - runtimeServiceCount = startedServices.length; - } else { - runtimeServiceCount = selectedRuntimeServiceId ? Math.max(0, (existing.runtimeServices?.length ?? 1) - 1) : 0; - } - const currentDesiredState = existing.config?.desiredState ?? ((existing.runtimeServices ?? []).some((service) => service.status === "starting" || service.status === "running") ? "running" : "stopped"); - const nextRuntimeState = selectedRuntimeServiceId && (selectedServiceIndex === void 0 || selectedServiceIndex === null) ? { - desiredState: currentDesiredState, - serviceStates: existing.config?.serviceStates ?? null - } : buildWorkspaceRuntimeDesiredStatePatch({ - config: { workspaceRuntime: effectiveRuntimeConfig }, - currentDesiredState, - currentServiceStates: existing.config?.serviceStates ?? null, - action, - serviceIndex: selectedServiceIndex - }); - const metadata = mergeExecutionWorkspaceConfig(existing.metadata, { - desiredState: nextRuntimeState.desiredState, - serviceStates: nextRuntimeState.serviceStates - }); - await svc.update(existing.id, { metadata }); - return { - status: "succeeded", - stdout: stdout.join(""), - stderr: stderr.join(""), - system: action === "stop" ? "Stopped execution workspace runtime services.\n" : action === "restart" ? "Restarted execution workspace runtime services.\n" : "Started execution workspace runtime services.\n", - metadata: { - runtimeServiceCount, - workspaceCommandId: workspaceCommand?.id ?? target.workspaceCommandId ?? null, - runtimeServiceId: selectedRuntimeServiceId, - serviceIndex: selectedServiceIndex - } - }; - } - }); - const workspace = await svc.getById(id); - if (!workspace) { - res.status(404).json({ error: "Execution workspace not found" }); - return; - } - await logActivity(db, { - companyId: existing.companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - runId: actor.runId, - action: `execution_workspace.runtime_${action}`, - entityType: "execution_workspace", - entityId: existing.id, - details: { - runtimeServiceCount, - workspaceCommandId: workspaceCommand?.id ?? target.workspaceCommandId ?? null, - workspaceCommandKind: workspaceCommand?.kind ?? null, - workspaceCommandName: workspaceCommand?.name ?? null, - runtimeServiceId: selectedRuntimeServiceId, - serviceIndex: selectedServiceIndex - } - }); - res.json({ - workspace, - operation: operation2 - }); - } - router2.post("/execution-workspaces/:id/runtime-services/:action", validate(workspaceRuntimeControlTargetSchema), handleExecutionWorkspaceRuntimeCommand); - router2.post("/execution-workspaces/:id/runtime-commands/:action", validate(workspaceRuntimeControlTargetSchema), handleExecutionWorkspaceRuntimeCommand); - router2.patch("/execution-workspaces/:id", validate(updateExecutionWorkspaceSchema), async (req, res) => { - const id = req.params.id; - const existing = await svc.getById(id); - if (!existing) { - res.status(404).json({ error: "Execution workspace not found" }); - return; - } - assertCompanyAccess(req, existing.companyId); - const patch = { - ...req.body.name === void 0 ? {} : { name: req.body.name }, - ...req.body.cwd === void 0 ? {} : { cwd: req.body.cwd }, - ...req.body.repoUrl === void 0 ? {} : { repoUrl: req.body.repoUrl }, - ...req.body.baseRef === void 0 ? {} : { baseRef: req.body.baseRef }, - ...req.body.branchName === void 0 ? {} : { branchName: req.body.branchName }, - ...req.body.providerRef === void 0 ? {} : { providerRef: req.body.providerRef }, - ...req.body.status === void 0 ? {} : { status: req.body.status }, - ...req.body.cleanupReason === void 0 ? {} : { cleanupReason: req.body.cleanupReason }, - ...req.body.cleanupEligibleAt !== void 0 ? { cleanupEligibleAt: req.body.cleanupEligibleAt ? new Date(req.body.cleanupEligibleAt) : null } : {} - }; - if (req.body.metadata !== void 0 || req.body.config !== void 0) { - const requestedMetadata = req.body.metadata === void 0 ? existing.metadata : req.body.metadata; - patch.metadata = req.body.config === void 0 ? requestedMetadata : mergeExecutionWorkspaceConfig(requestedMetadata, req.body.config ?? null); - } - let workspace = existing; - let cleanupWarnings = []; - const configForCleanup = readExecutionWorkspaceConfig( - patch.metadata ?? existing.metadata ?? null - ); - if (req.body.status === "archived" && existing.status !== "archived") { - const readiness = await svc.getCloseReadiness(existing.id); - if (!readiness) { - res.status(404).json({ error: "Execution workspace not found" }); - return; - } - if (readiness.state === "blocked") { - res.status(409).json({ - error: readiness.blockingReasons[0] ?? "Execution workspace cannot be closed right now", - closeReadiness: readiness - }); - return; - } - const closedAt = /* @__PURE__ */ new Date(); - const archivedWorkspace = await svc.update(id, { - ...patch, - status: "archived", - closedAt, - cleanupReason: null - }); - if (!archivedWorkspace) { - res.status(404).json({ error: "Execution workspace not found" }); - return; - } - workspace = archivedWorkspace; - if (existing.mode === "shared_workspace") { - await db.update(issues).set({ - executionWorkspaceId: null, - updatedAt: /* @__PURE__ */ new Date() - }).where( - and( - eq(issues.companyId, existing.companyId), - eq(issues.executionWorkspaceId, existing.id) - ) - ); - } - try { - await stopRuntimeServicesForExecutionWorkspace({ - db, - executionWorkspaceId: existing.id, - workspaceCwd: existing.cwd - }); - const projectWorkspace = existing.projectWorkspaceId ? await db.select({ - cwd: projectWorkspaces.cwd, - cleanupCommand: projectWorkspaces.cleanupCommand - }).from(projectWorkspaces).where( - and( - eq(projectWorkspaces.id, existing.projectWorkspaceId), - eq(projectWorkspaces.companyId, existing.companyId) - ) - ).then((rows) => rows[0] ?? null) : null; - const projectPolicy = existing.projectId ? await db.select({ - executionWorkspacePolicy: projects.executionWorkspacePolicy - }).from(projects).where(and(eq(projects.id, existing.projectId), eq(projects.companyId, existing.companyId))).then((rows) => parseProjectExecutionWorkspacePolicy(rows[0]?.executionWorkspacePolicy)) : null; - const cleanupResult = await cleanupExecutionWorkspaceArtifacts({ - workspace: existing, - projectWorkspace, - teardownCommand: configForCleanup?.teardownCommand ?? projectPolicy?.workspaceStrategy?.teardownCommand ?? null, - cleanupCommand: configForCleanup?.cleanupCommand ?? null, - recorder: workspaceOperationsSvc.createRecorder({ - companyId: existing.companyId, - executionWorkspaceId: existing.id - }) - }); - cleanupWarnings = cleanupResult.warnings; - const cleanupPatch = { - closedAt, - cleanupReason: cleanupWarnings.length > 0 ? cleanupWarnings.join(" | ") : null - }; - if (!cleanupResult.cleaned) { - cleanupPatch.status = "cleanup_failed"; - } - if (cleanupResult.warnings.length > 0 || !cleanupResult.cleaned) { - workspace = await svc.update(id, cleanupPatch) ?? workspace; - } - } catch (error50) { - const failureReason = error50 instanceof Error ? error50.message : String(error50); - workspace = await svc.update(id, { - status: "cleanup_failed", - closedAt, - cleanupReason: failureReason - }) ?? workspace; - res.status(500).json({ - error: `Failed to archive execution workspace: ${failureReason}` - }); - return; - } - } else { - const updatedWorkspace = await svc.update(id, patch); - if (!updatedWorkspace) { - res.status(404).json({ error: "Execution workspace not found" }); - return; - } - workspace = updatedWorkspace; - } - const actor = getActorInfo(req); - await logActivity(db, { - companyId: existing.companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - runId: actor.runId, - action: "execution_workspace.updated", - entityType: "execution_workspace", - entityId: workspace.id, - details: { - changedKeys: Object.keys(req.body).sort(), - ...cleanupWarnings.length > 0 ? { cleanupWarnings } : {} - } - }); - res.json(workspace); - }); - return router2; -} - -// server/src/routes/goals.ts -var import_express9 = __toESM(require_express2(), 1); -function goalRoutes(db) { - const router2 = (0, import_express9.Router)(); - const svc = goalService(db); - router2.get("/companies/:companyId/goals", async (req, res) => { - const companyId = req.params.companyId; - assertCompanyAccess(req, companyId); - const result = await svc.list(companyId); - res.json(result); - }); - router2.get("/goals/:id", async (req, res) => { - const id = req.params.id; - const goal = await svc.getById(id); - if (!goal) { - res.status(404).json({ error: "Goal not found" }); - return; - } - assertCompanyAccess(req, goal.companyId); - res.json(goal); - }); - router2.post("/companies/:companyId/goals", validate(createGoalSchema), async (req, res) => { - const companyId = req.params.companyId; - assertCompanyAccess(req, companyId); - const goal = await svc.create(companyId, req.body); - const actor = getActorInfo(req); - await logActivity(db, { - companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - action: "goal.created", - entityType: "goal", - entityId: goal.id, - details: { title: goal.title } - }); - const telemetryClient = getTelemetryClient(); - if (telemetryClient) { - trackGoalCreated(telemetryClient, { goalLevel: goal.level }); - } - res.status(201).json(goal); - }); - router2.patch("/goals/:id", validate(updateGoalSchema), async (req, res) => { - const id = req.params.id; - const existing = await svc.getById(id); - if (!existing) { - res.status(404).json({ error: "Goal not found" }); - return; - } - assertCompanyAccess(req, existing.companyId); - const goal = await svc.update(id, req.body); - if (!goal) { - res.status(404).json({ error: "Goal not found" }); - return; - } - const actor = getActorInfo(req); - await logActivity(db, { - companyId: goal.companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - action: "goal.updated", - entityType: "goal", - entityId: goal.id, - details: req.body - }); - res.json(goal); - }); - router2.delete("/goals/:id", async (req, res) => { - const id = req.params.id; - const existing = await svc.getById(id); - if (!existing) { - res.status(404).json({ error: "Goal not found" }); - return; - } - assertCompanyAccess(req, existing.companyId); - const goal = await svc.remove(id); - if (!goal) { - res.status(404).json({ error: "Goal not found" }); - return; - } - const actor = getActorInfo(req); - await logActivity(db, { - companyId: goal.companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - action: "goal.deleted", - entityType: "goal", - entityId: goal.id - }); - res.json(goal); - }); - return router2; -} - -// server/src/routes/approvals.ts -var import_express10 = __toESM(require_express2(), 1); -function redactApprovalPayload(approval) { - return { - ...approval, - payload: redactEventPayload(approval.payload) ?? {} - }; -} -function approvalRoutes(db) { - const router2 = (0, import_express10.Router)(); - const svc = approvalService(db); - const heartbeat = heartbeatService(db); - const issueApprovalsSvc = issueApprovalService(db); - const secretsSvc = secretService(db); - const strictSecretsMode = process.env.TASKCORE_SECRETS_STRICT_MODE === "true"; - async function requireApprovalAccess(req, id) { - const approval = await svc.getById(id); - if (!approval) { - return null; - } - assertCompanyAccess(req, approval.companyId); - return approval; - } - router2.get("/companies/:companyId/approvals", async (req, res) => { - const companyId = req.params.companyId; - assertCompanyAccess(req, companyId); - const status = req.query.status; - const result = await svc.list(companyId, status); - res.json(result.map((approval) => redactApprovalPayload(approval))); - }); - router2.get("/approvals/:id", async (req, res) => { - const id = req.params.id; - const approval = await svc.getById(id); - if (!approval) { - res.status(404).json({ error: "Approval not found" }); - return; - } - assertCompanyAccess(req, approval.companyId); - res.json(redactApprovalPayload(approval)); - }); - router2.post("/companies/:companyId/approvals", validate(createApprovalSchema), async (req, res) => { - const companyId = req.params.companyId; - assertCompanyAccess(req, companyId); - const rawIssueIds = req.body.issueIds; - const issueIds = Array.isArray(rawIssueIds) ? rawIssueIds.filter((value) => typeof value === "string") : []; - const uniqueIssueIds = Array.from(new Set(issueIds)); - const { issueIds: _issueIds, ...approvalInput } = req.body; - const normalizedPayload = approvalInput.type === "hire_agent" ? await secretsSvc.normalizeHireApprovalPayloadForPersistence( - companyId, - approvalInput.payload, - { strictMode: strictSecretsMode } - ) : approvalInput.payload; - const actor = getActorInfo(req); - const approval = await svc.create(companyId, { - ...approvalInput, - payload: normalizedPayload, - requestedByUserId: actor.actorType === "user" ? actor.actorId : null, - requestedByAgentId: approvalInput.requestedByAgentId ?? (actor.actorType === "agent" ? actor.actorId : null), - status: "pending", - decisionNote: null, - decidedByUserId: null, - decidedAt: null, - updatedAt: /* @__PURE__ */ new Date() - }); - if (uniqueIssueIds.length > 0) { - await issueApprovalsSvc.linkManyForApproval(approval.id, uniqueIssueIds, { - agentId: actor.agentId, - userId: actor.actorType === "user" ? actor.actorId : null - }); - } - await logActivity(db, { - companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - action: "approval.created", - entityType: "approval", - entityId: approval.id, - details: { type: approval.type, issueIds: uniqueIssueIds } - }); - res.status(201).json(redactApprovalPayload(approval)); - }); - router2.get("/approvals/:id/issues", async (req, res) => { - const id = req.params.id; - const approval = await svc.getById(id); - if (!approval) { - res.status(404).json({ error: "Approval not found" }); - return; - } - assertCompanyAccess(req, approval.companyId); - const issues2 = await issueApprovalsSvc.listIssuesForApproval(id); - res.json(issues2); - }); - router2.post("/approvals/:id/approve", validate(resolveApprovalSchema), async (req, res) => { - assertBoard(req); - const id = req.params.id; - if (!await requireApprovalAccess(req, id)) { - res.status(404).json({ error: "Approval not found" }); - return; - } - const { approval, applied } = await svc.approve( - id, - req.body.decidedByUserId ?? "board", - req.body.decisionNote - ); - if (applied) { - const linkedIssues = await issueApprovalsSvc.listIssuesForApproval(approval.id); - const linkedIssueIds = linkedIssues.map((issue2) => issue2.id); - const primaryIssueId = linkedIssueIds[0] ?? null; - await logActivity(db, { - companyId: approval.companyId, - actorType: "user", - actorId: req.actor.userId ?? "board", - action: "approval.approved", - entityType: "approval", - entityId: approval.id, - details: { - type: approval.type, - requestedByAgentId: approval.requestedByAgentId, - linkedIssueIds - } - }); - if (approval.requestedByAgentId) { - try { - const wakeRun = await heartbeat.wakeup(approval.requestedByAgentId, { - source: "automation", - triggerDetail: "system", - reason: "approval_approved", - payload: { - approvalId: approval.id, - approvalStatus: approval.status, - issueId: primaryIssueId, - issueIds: linkedIssueIds - }, - requestedByActorType: "user", - requestedByActorId: req.actor.userId ?? "board", - contextSnapshot: { - source: "approval.approved", - approvalId: approval.id, - approvalStatus: approval.status, - issueId: primaryIssueId, - issueIds: linkedIssueIds, - taskId: primaryIssueId, - wakeReason: "approval_approved" - } - }); - await logActivity(db, { - companyId: approval.companyId, - actorType: "user", - actorId: req.actor.userId ?? "board", - action: "approval.requester_wakeup_queued", - entityType: "approval", - entityId: approval.id, - details: { - requesterAgentId: approval.requestedByAgentId, - wakeRunId: wakeRun?.id ?? null, - linkedIssueIds - } - }); - } catch (err) { - logger.warn( - { - err, - approvalId: approval.id, - requestedByAgentId: approval.requestedByAgentId - }, - "failed to queue requester wakeup after approval" - ); - await logActivity(db, { - companyId: approval.companyId, - actorType: "user", - actorId: req.actor.userId ?? "board", - action: "approval.requester_wakeup_failed", - entityType: "approval", - entityId: approval.id, - details: { - requesterAgentId: approval.requestedByAgentId, - linkedIssueIds, - error: err instanceof Error ? err.message : String(err) - } - }); - } - } - } - res.json(redactApprovalPayload(approval)); - }); - router2.post("/approvals/:id/reject", validate(resolveApprovalSchema), async (req, res) => { - assertBoard(req); - const id = req.params.id; - if (!await requireApprovalAccess(req, id)) { - res.status(404).json({ error: "Approval not found" }); - return; - } - const { approval, applied } = await svc.reject( - id, - req.body.decidedByUserId ?? "board", - req.body.decisionNote - ); - if (applied) { - await logActivity(db, { - companyId: approval.companyId, - actorType: "user", - actorId: req.actor.userId ?? "board", - action: "approval.rejected", - entityType: "approval", - entityId: approval.id, - details: { type: approval.type } - }); - } - res.json(redactApprovalPayload(approval)); - }); - router2.post( - "/approvals/:id/request-revision", - validate(requestApprovalRevisionSchema), - async (req, res) => { - assertBoard(req); - const id = req.params.id; - if (!await requireApprovalAccess(req, id)) { - res.status(404).json({ error: "Approval not found" }); - return; - } - const approval = await svc.requestRevision( - id, - req.body.decidedByUserId ?? "board", - req.body.decisionNote - ); - await logActivity(db, { - companyId: approval.companyId, - actorType: "user", - actorId: req.actor.userId ?? "board", - action: "approval.revision_requested", - entityType: "approval", - entityId: approval.id, - details: { type: approval.type } - }); - res.json(redactApprovalPayload(approval)); - } - ); - router2.post("/approvals/:id/resubmit", validate(resubmitApprovalSchema), async (req, res) => { - const id = req.params.id; - const existing = await svc.getById(id); - if (!existing) { - res.status(404).json({ error: "Approval not found" }); - return; - } - assertCompanyAccess(req, existing.companyId); - if (req.actor.type === "agent" && req.actor.agentId !== existing.requestedByAgentId) { - res.status(403).json({ error: "Only requesting agent can resubmit this approval" }); - return; - } - const normalizedPayload = req.body.payload ? existing.type === "hire_agent" ? await secretsSvc.normalizeHireApprovalPayloadForPersistence( - existing.companyId, - req.body.payload, - { strictMode: strictSecretsMode } - ) : req.body.payload : void 0; - const approval = await svc.resubmit(id, normalizedPayload); - const actor = getActorInfo(req); - await logActivity(db, { - companyId: approval.companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - action: "approval.resubmitted", - entityType: "approval", - entityId: approval.id, - details: { type: approval.type } - }); - res.json(redactApprovalPayload(approval)); - }); - router2.get("/approvals/:id/comments", async (req, res) => { - const id = req.params.id; - const approval = await svc.getById(id); - if (!approval) { - res.status(404).json({ error: "Approval not found" }); - return; - } - assertCompanyAccess(req, approval.companyId); - const comments = await svc.listComments(id); - res.json(comments); - }); - router2.post("/approvals/:id/comments", validate(addApprovalCommentSchema), async (req, res) => { - const id = req.params.id; - const approval = await svc.getById(id); - if (!approval) { - res.status(404).json({ error: "Approval not found" }); - return; - } - assertCompanyAccess(req, approval.companyId); - const actor = getActorInfo(req); - const comment = await svc.addComment(id, req.body.body, { - agentId: actor.agentId ?? void 0, - userId: actor.actorType === "user" ? actor.actorId : void 0 - }); - await logActivity(db, { - companyId: approval.companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - action: "approval.comment_added", - entityType: "approval", - entityId: approval.id, - details: { commentId: comment.id } - }); - res.status(201).json(comment); - }); - return router2; -} - -// server/src/routes/secrets.ts -var import_express11 = __toESM(require_express2(), 1); -function secretRoutes(db) { - const router2 = (0, import_express11.Router)(); - const svc = secretService(db); - const configuredDefaultProvider = process.env.TASKCORE_SECRETS_PROVIDER; - const defaultProvider = configuredDefaultProvider && SECRET_PROVIDERS.includes(configuredDefaultProvider) ? configuredDefaultProvider : "local_encrypted"; - router2.get("/companies/:companyId/secret-providers", (req, res) => { - assertBoard(req); - const companyId = req.params.companyId; - assertCompanyAccess(req, companyId); - res.json(svc.listProviders()); - }); - router2.get("/companies/:companyId/secrets", async (req, res) => { - assertBoard(req); - const companyId = req.params.companyId; - assertCompanyAccess(req, companyId); - const secrets = await svc.list(companyId); - res.json(secrets); - }); - router2.post("/companies/:companyId/secrets", validate(createSecretSchema), async (req, res) => { - assertBoard(req); - const companyId = req.params.companyId; - assertCompanyAccess(req, companyId); - const created = await svc.create( - companyId, - { - name: req.body.name, - provider: req.body.provider ?? defaultProvider, - value: req.body.value, - description: req.body.description, - externalRef: req.body.externalRef - }, - { userId: req.actor.userId ?? "board", agentId: null } - ); - await logActivity(db, { - companyId, - actorType: "user", - actorId: req.actor.userId ?? "board", - action: "secret.created", - entityType: "secret", - entityId: created.id, - details: { name: created.name, provider: created.provider } - }); - res.status(201).json(created); - }); - router2.post("/secrets/:id/rotate", validate(rotateSecretSchema), async (req, res) => { - assertBoard(req); - const id = req.params.id; - const existing = await svc.getById(id); - if (!existing) { - res.status(404).json({ error: "Secret not found" }); - return; - } - assertCompanyAccess(req, existing.companyId); - const rotated = await svc.rotate( - id, - { - value: req.body.value, - externalRef: req.body.externalRef - }, - { userId: req.actor.userId ?? "board", agentId: null } - ); - await logActivity(db, { - companyId: rotated.companyId, - actorType: "user", - actorId: req.actor.userId ?? "board", - action: "secret.rotated", - entityType: "secret", - entityId: rotated.id, - details: { version: rotated.latestVersion } - }); - res.json(rotated); - }); - router2.patch("/secrets/:id", validate(updateSecretSchema), async (req, res) => { - assertBoard(req); - const id = req.params.id; - const existing = await svc.getById(id); - if (!existing) { - res.status(404).json({ error: "Secret not found" }); - return; - } - assertCompanyAccess(req, existing.companyId); - const updated = await svc.update(id, { - name: req.body.name, - description: req.body.description, - externalRef: req.body.externalRef - }); - if (!updated) { - res.status(404).json({ error: "Secret not found" }); - return; - } - await logActivity(db, { - companyId: updated.companyId, - actorType: "user", - actorId: req.actor.userId ?? "board", - action: "secret.updated", - entityType: "secret", - entityId: updated.id, - details: { name: updated.name } - }); - res.json(updated); - }); - router2.delete("/secrets/:id", async (req, res) => { - assertBoard(req); - const id = req.params.id; - const existing = await svc.getById(id); - if (!existing) { - res.status(404).json({ error: "Secret not found" }); - return; - } - assertCompanyAccess(req, existing.companyId); - const removed = await svc.remove(id); - if (!removed) { - res.status(404).json({ error: "Secret not found" }); - return; - } - await logActivity(db, { - companyId: removed.companyId, - actorType: "user", - actorId: req.actor.userId ?? "board", - action: "secret.deleted", - entityType: "secret", - entityId: removed.id, - details: { name: removed.name } - }); - res.json({ ok: true }); - }); - return router2; -} - -// server/src/routes/costs.ts -var import_express12 = __toESM(require_express2(), 1); - -// server/src/services/quota-windows.ts -var QUOTA_PROVIDER_TIMEOUT_MS = 2e4; -function providerSlugForAdapterType(type) { - switch (type) { - case "claude_local": - return "anthropic"; - case "codex_local": - return "openai"; - default: - return type; - } -} -async function fetchAllQuotaWindows() { - const adapters = listServerAdapters().filter((a5) => a5.getQuotaWindows != null); - const settled = await Promise.allSettled( - adapters.map((adapter) => withQuotaTimeout(adapter.type, adapter.getQuotaWindows())) - ); - return settled.map((result, i5) => { - if (result.status === "fulfilled") return result.value; - const adapterType = adapters[i5].type; - return { - provider: providerSlugForAdapterType(adapterType), - ok: false, - error: String(result.reason), - windows: [] - }; - }); -} -async function withQuotaTimeout(adapterType, task) { - let timeoutId = null; - try { - return await Promise.race([ - task, - new Promise((resolve4) => { - timeoutId = setTimeout(() => { - resolve4({ - provider: providerSlugForAdapterType(adapterType), - ok: false, - error: `quota polling timed out after ${Math.round(QUOTA_PROVIDER_TIMEOUT_MS / 1e3)}s`, - windows: [] - }); - }, QUOTA_PROVIDER_TIMEOUT_MS); - }) - ]); - } finally { - if (timeoutId) clearTimeout(timeoutId); - } -} - -// server/src/routes/costs.ts -function parseCostDateRange(query) { - const fromRaw = query.from; - const toRaw = query.to; - const from = fromRaw ? new Date(fromRaw) : void 0; - const to = toRaw ? new Date(toRaw) : void 0; - if (from && isNaN(from.getTime())) throw badRequest("invalid 'from' date"); - if (to && isNaN(to.getTime())) throw badRequest("invalid 'to' date"); - return from || to ? { from, to } : void 0; -} -function parseCostLimit(query) { - const raw = Array.isArray(query.limit) ? query.limit[0] : query.limit; - if (raw == null || raw === "") return 100; - const limit = typeof raw === "number" ? raw : Number.parseInt(String(raw), 10); - if (!Number.isFinite(limit) || limit <= 0 || limit > 500) { - throw badRequest("invalid 'limit' value"); - } - return limit; -} -function costRoutes(db) { - const router2 = (0, import_express12.Router)(); - const heartbeat = heartbeatService(db); - const budgetHooks = { - cancelWorkForScope: heartbeat.cancelBudgetScopeWork - }; - const costs = costService(db, budgetHooks); - const finance = financeService(db); - const budgets = budgetService(db, budgetHooks); - const companies2 = companyService(db); - const agents2 = agentService(db); - router2.post("/companies/:companyId/cost-events", validate(createCostEventSchema), async (req, res) => { - const companyId = req.params.companyId; - assertCompanyAccess(req, companyId); - if (req.actor.type === "agent" && req.actor.agentId !== req.body.agentId) { - res.status(403).json({ error: "Agent can only report its own costs" }); - return; - } - const event = await costs.createEvent(companyId, { - ...req.body, - occurredAt: new Date(req.body.occurredAt) - }); - const actor = getActorInfo(req); - await logActivity(db, { - companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - action: "cost.reported", - entityType: "cost_event", - entityId: event.id, - details: { costCents: event.costCents, model: event.model } - }); - res.status(201).json(event); - }); - router2.post("/companies/:companyId/finance-events", validate(createFinanceEventSchema), async (req, res) => { - const companyId = req.params.companyId; - assertCompanyAccess(req, companyId); - assertBoard(req); - const event = await finance.createEvent(companyId, { - ...req.body, - occurredAt: new Date(req.body.occurredAt) - }); - const actor = getActorInfo(req); - await logActivity(db, { - companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - action: "finance_event.reported", - entityType: "finance_event", - entityId: event.id, - details: { - amountCents: event.amountCents, - biller: event.biller, - eventKind: event.eventKind, - direction: event.direction - } - }); - res.status(201).json(event); - }); - router2.get("/companies/:companyId/costs/summary", async (req, res) => { - const companyId = req.params.companyId; - assertCompanyAccess(req, companyId); - const range2 = parseCostDateRange(req.query); - const summary = await costs.summary(companyId, range2); - res.json(summary); - }); - router2.get("/companies/:companyId/costs/by-agent", async (req, res) => { - const companyId = req.params.companyId; - assertCompanyAccess(req, companyId); - const range2 = parseCostDateRange(req.query); - const rows = await costs.byAgent(companyId, range2); - res.json(rows); - }); - router2.get("/companies/:companyId/costs/by-agent-model", async (req, res) => { - const companyId = req.params.companyId; - assertCompanyAccess(req, companyId); - const range2 = parseCostDateRange(req.query); - const rows = await costs.byAgentModel(companyId, range2); - res.json(rows); - }); - router2.get("/companies/:companyId/costs/by-provider", async (req, res) => { - const companyId = req.params.companyId; - assertCompanyAccess(req, companyId); - const range2 = parseCostDateRange(req.query); - const rows = await costs.byProvider(companyId, range2); - res.json(rows); - }); - router2.get("/companies/:companyId/costs/by-biller", async (req, res) => { - const companyId = req.params.companyId; - assertCompanyAccess(req, companyId); - const range2 = parseCostDateRange(req.query); - const rows = await costs.byBiller(companyId, range2); - res.json(rows); - }); - router2.get("/companies/:companyId/costs/finance-summary", async (req, res) => { - const companyId = req.params.companyId; - assertCompanyAccess(req, companyId); - const range2 = parseCostDateRange(req.query); - const summary = await finance.summary(companyId, range2); - res.json(summary); - }); - router2.get("/companies/:companyId/costs/finance-by-biller", async (req, res) => { - const companyId = req.params.companyId; - assertCompanyAccess(req, companyId); - const range2 = parseCostDateRange(req.query); - const rows = await finance.byBiller(companyId, range2); - res.json(rows); - }); - router2.get("/companies/:companyId/costs/finance-by-kind", async (req, res) => { - const companyId = req.params.companyId; - assertCompanyAccess(req, companyId); - const range2 = parseCostDateRange(req.query); - const rows = await finance.byKind(companyId, range2); - res.json(rows); - }); - router2.get("/companies/:companyId/costs/finance-events", async (req, res) => { - const companyId = req.params.companyId; - assertCompanyAccess(req, companyId); - const range2 = parseCostDateRange(req.query); - const limit = parseCostLimit(req.query); - const rows = await finance.list(companyId, range2, limit); - res.json(rows); - }); - router2.get("/companies/:companyId/costs/window-spend", async (req, res) => { - const companyId = req.params.companyId; - assertCompanyAccess(req, companyId); - const rows = await costs.windowSpend(companyId); - res.json(rows); - }); - router2.get("/companies/:companyId/costs/quota-windows", async (req, res) => { - const companyId = req.params.companyId; - assertCompanyAccess(req, companyId); - assertBoard(req); - const company = await companies2.getById(companyId); - if (!company) { - res.status(404).json({ error: "Company not found" }); - return; - } - const results = await fetchAllQuotaWindows(); - res.json(results); - }); - router2.get("/companies/:companyId/budgets/overview", async (req, res) => { - const companyId = req.params.companyId; - assertCompanyAccess(req, companyId); - const overview = await budgets.overview(companyId); - res.json(overview); - }); - router2.post( - "/companies/:companyId/budgets/policies", - validate(upsertBudgetPolicySchema), - async (req, res) => { - assertBoard(req); - const companyId = req.params.companyId; - assertCompanyAccess(req, companyId); - const summary = await budgets.upsertPolicy(companyId, req.body, req.actor.userId ?? "board"); - res.json(summary); - } - ); - router2.post( - "/companies/:companyId/budget-incidents/:incidentId/resolve", - validate(resolveBudgetIncidentSchema), - async (req, res) => { - assertBoard(req); - const companyId = req.params.companyId; - const incidentId = req.params.incidentId; - assertCompanyAccess(req, companyId); - const incident = await budgets.resolveIncident(companyId, incidentId, req.body, req.actor.userId ?? "board"); - res.json(incident); - } - ); - router2.get("/companies/:companyId/costs/by-project", async (req, res) => { - const companyId = req.params.companyId; - assertCompanyAccess(req, companyId); - const range2 = parseCostDateRange(req.query); - const rows = await costs.byProject(companyId, range2); - res.json(rows); - }); - router2.patch("/companies/:companyId/budgets", validate(updateBudgetSchema), async (req, res) => { - assertBoard(req); - const companyId = req.params.companyId; - assertCompanyAccess(req, companyId); - const company = await companies2.update(companyId, { budgetMonthlyCents: req.body.budgetMonthlyCents }); - if (!company) { - res.status(404).json({ error: "Company not found" }); - return; - } - await logActivity(db, { - companyId, - actorType: "user", - actorId: req.actor.userId ?? "board", - action: "company.budget_updated", - entityType: "company", - entityId: companyId, - details: { budgetMonthlyCents: req.body.budgetMonthlyCents } - }); - await budgets.upsertPolicy( - companyId, - { - scopeType: "company", - scopeId: companyId, - amount: req.body.budgetMonthlyCents, - windowKind: "calendar_month_utc" - }, - req.actor.userId ?? "board" - ); - res.json(company); - }); - router2.patch("/agents/:agentId/budgets", validate(updateBudgetSchema), async (req, res) => { - const agentId = req.params.agentId; - const agent = await agents2.getById(agentId); - if (!agent) { - res.status(404).json({ error: "Agent not found" }); - return; - } - assertCompanyAccess(req, agent.companyId); - if (req.actor.type === "agent") { - if (req.actor.agentId !== agentId) { - res.status(403).json({ error: "Agent can only change its own budget" }); - return; - } - } - const updated = await agents2.update(agentId, { budgetMonthlyCents: req.body.budgetMonthlyCents }); - if (!updated) { - res.status(404).json({ error: "Agent not found" }); - return; - } - const actor = getActorInfo(req); - await logActivity(db, { - companyId: updated.companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - action: "agent.budget_updated", - entityType: "agent", - entityId: updated.id, - details: { budgetMonthlyCents: updated.budgetMonthlyCents } - }); - await budgets.upsertPolicy( - updated.companyId, - { - scopeType: "agent", - scopeId: updated.id, - amount: updated.budgetMonthlyCents, - windowKind: "calendar_month_utc" - }, - req.actor.type === "board" ? req.actor.userId ?? "board" : null - ); - res.json(updated); - }); - return router2; -} - -// server/src/routes/activity.ts -var import_express13 = __toESM(require_express2(), 1); -var createActivitySchema = external_exports.object({ - actorType: external_exports.enum(["agent", "user", "system"]).optional().default("system"), - actorId: external_exports.string().min(1), - action: external_exports.string().min(1), - entityType: external_exports.string().min(1), - entityId: external_exports.string().min(1), - agentId: external_exports.string().uuid().optional().nullable(), - details: external_exports.record(external_exports.unknown()).optional().nullable() -}); -function activityRoutes(db) { - const router2 = (0, import_express13.Router)(); - const svc = activityService(db); - const heartbeat = heartbeatService(db); - const issueSvc = issueService(db); - async function resolveIssueByRef(rawId) { - if (/^[A-Z]+-\d+$/i.test(rawId)) { - return issueSvc.getByIdentifier(rawId); - } - return issueSvc.getById(rawId); - } - router2.get("/companies/:companyId/activity", async (req, res) => { - const companyId = req.params.companyId; - assertCompanyAccess(req, companyId); - const filters = { - companyId, - agentId: req.query.agentId, - entityType: req.query.entityType, - entityId: req.query.entityId - }; - const result = await svc.list(filters); - res.json(result); - }); - router2.post("/companies/:companyId/activity", validate(createActivitySchema), async (req, res) => { - assertBoard(req); - const companyId = req.params.companyId; - assertCompanyAccess(req, companyId); - const event = await svc.create({ - companyId, - ...req.body, - details: req.body.details ? sanitizeRecord(req.body.details) : null - }); - res.status(201).json(event); - }); - router2.get("/issues/:id/activity", async (req, res) => { - const rawId = req.params.id; - const issue2 = await resolveIssueByRef(rawId); - if (!issue2) { - res.status(404).json({ error: "Issue not found" }); - return; - } - assertCompanyAccess(req, issue2.companyId); - const result = await svc.forIssue(issue2.id); - res.json(result); - }); - router2.get("/issues/:id/runs", async (req, res) => { - const rawId = req.params.id; - const issue2 = await resolveIssueByRef(rawId); - if (!issue2) { - res.status(404).json({ error: "Issue not found" }); - return; - } - assertCompanyAccess(req, issue2.companyId); - const result = await svc.runsForIssue(issue2.companyId, issue2.id); - res.json(result); - }); - router2.get("/heartbeat-runs/:runId/issues", async (req, res) => { - const runId = req.params.runId; - const run = await heartbeat.getRun(runId); - if (!run) { - res.json([]); - return; - } - assertCompanyAccess(req, run.companyId); - const result = await svc.issuesForRun(runId); - res.json(result); - }); - return router2; -} - -// server/src/routes/dashboard.ts -var import_express14 = __toESM(require_express2(), 1); -function dashboardRoutes(db) { - const router2 = (0, import_express14.Router)(); - const svc = dashboardService(db); - router2.get("/companies/:companyId/dashboard", async (req, res) => { - const companyId = req.params.companyId; - assertCompanyAccess(req, companyId); - const summary = await svc.summary(companyId); - res.json(summary); - }); - return router2; -} - -// server/src/routes/sidebar-badges.ts -var import_express15 = __toESM(require_express2(), 1); -init_drizzle_orm(); -init_src2(); -function buildDismissedAtByKey(dismissals) { - return new Map( - dismissals.map((dismissal) => [dismissal.itemKey, new Date(dismissal.dismissedAt).getTime()]) - ); -} -function sidebarBadgeRoutes(db) { - const router2 = (0, import_express15.Router)(); - const svc = sidebarBadgeService(db); - const access = accessService(db); - const dashboard = dashboardService(db); - router2.get("/companies/:companyId/sidebar-badges", async (req, res) => { - const companyId = req.params.companyId; - assertCompanyAccess(req, companyId); - let canApproveJoins = false; - if (req.actor.type === "board") { - canApproveJoins = req.actor.source === "local_implicit" || Boolean(req.actor.isInstanceAdmin) || await access.canUser(companyId, req.actor.userId, "joins:approve"); - } else if (req.actor.type === "agent" && req.actor.agentId) { - canApproveJoins = await access.hasPermission(companyId, "agent", req.actor.agentId, "joins:approve"); - } - const visibleJoinRequests = canApproveJoins ? await db.select({ - id: joinRequests.id, - updatedAt: joinRequests.updatedAt, - createdAt: joinRequests.createdAt - }).from(joinRequests).where(and(eq(joinRequests.companyId, companyId), eq(joinRequests.status, "pending_approval"))) : []; - const dismissedAtByKey = req.actor.type === "board" && req.actor.userId ? await db.select({ itemKey: inboxDismissals.itemKey, dismissedAt: inboxDismissals.dismissedAt }).from(inboxDismissals).where(and(eq(inboxDismissals.companyId, companyId), eq(inboxDismissals.userId, req.actor.userId))).then(buildDismissedAtByKey) : /* @__PURE__ */ new Map(); - const badges = await svc.get(companyId, { - dismissals: dismissedAtByKey, - joinRequests: visibleJoinRequests - }); - const summary = await dashboard.summary(companyId); - const hasFailedRuns = badges.failedRuns > 0; - const alertsCount = (summary.agents.error > 0 && !hasFailedRuns ? 1 : 0) + (summary.costs.monthBudgetCents > 0 && summary.costs.monthUtilizationPercent >= 80 ? 1 : 0); - badges.inbox = badges.failedRuns + alertsCount + badges.joinRequests + badges.approvals; - res.json(badges); - }); - return router2; -} - -// server/src/routes/sidebar-preferences.ts -var import_express16 = __toESM(require_express2(), 1); -function requireBoardUserId(req, res) { - assertBoard(req); - if (!req.actor.userId) { - res.status(403).json({ error: "Board user context required" }); - return null; - } - return req.actor.userId; -} -function sidebarPreferenceRoutes(db) { - const router2 = (0, import_express16.Router)(); - const svc = sidebarPreferenceService(db); - router2.get("/sidebar-preferences/me", async (req, res) => { - const userId = requireBoardUserId(req, res); - if (!userId) return; - res.json(await svc.getCompanyOrder(userId)); - }); - router2.put("/sidebar-preferences/me", validate(upsertSidebarOrderPreferenceSchema), async (req, res) => { - const userId = requireBoardUserId(req, res); - if (!userId) return; - res.json(await svc.upsertCompanyOrder(userId, req.body.orderedIds)); - }); - router2.get("/companies/:companyId/sidebar-preferences/me", async (req, res) => { - const companyId = req.params.companyId; - assertCompanyAccess(req, companyId); - const userId = requireBoardUserId(req, res); - if (!userId) return; - res.json(await svc.getProjectOrder(companyId, userId)); - }); - router2.put( - "/companies/:companyId/sidebar-preferences/me", - validate(upsertSidebarOrderPreferenceSchema), - async (req, res) => { - const companyId = req.params.companyId; - assertCompanyAccess(req, companyId); - const userId = requireBoardUserId(req, res); - if (!userId) return; - const result = await svc.upsertProjectOrder(companyId, userId, req.body.orderedIds); - const actor = getActorInfo(req); - await logActivity(db, { - companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - runId: actor.runId, - action: "sidebar_preferences.project_order_updated", - entityType: "company", - entityId: companyId, - details: { - userId, - orderedIds: result.orderedIds - } - }); - res.json(result); - } - ); - return router2; -} - -// server/src/routes/inbox-dismissals.ts -var import_express17 = __toESM(require_express2(), 1); -var inboxDismissalSchema = external_exports.object({ - itemKey: external_exports.string().trim().min(1).regex(/^(approval|join|run):.+$/, "Unsupported inbox item key") -}); -function inboxDismissalRoutes(db) { - const router2 = (0, import_express17.Router)(); - const svc = inboxDismissalService(db); - router2.get("/companies/:companyId/inbox-dismissals", async (req, res) => { - const companyId = req.params.companyId; - assertCompanyAccess(req, companyId); - if (req.actor.type !== "board") { - res.status(403).json({ error: "Board authentication required" }); - return; - } - if (!req.actor.userId) { - res.status(403).json({ error: "Board user context required" }); - return; - } - const dismissals = await svc.list(companyId, req.actor.userId); - res.json(dismissals); - }); - router2.post( - "/companies/:companyId/inbox-dismissals", - validate(inboxDismissalSchema), - async (req, res) => { - const companyId = req.params.companyId; - assertCompanyAccess(req, companyId); - if (req.actor.type !== "board") { - res.status(403).json({ error: "Board authentication required" }); - return; - } - if (!req.actor.userId) { - res.status(403).json({ error: "Board user context required" }); - return; - } - const dismissal = await svc.dismiss(companyId, req.actor.userId, req.body.itemKey, /* @__PURE__ */ new Date()); - const actor = getActorInfo(req); - await logActivity(db, { - companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - runId: actor.runId, - action: "inbox.dismissed", - entityType: "company", - entityId: companyId, - details: { - userId: req.actor.userId, - itemKey: dismissal.itemKey, - dismissedAt: dismissal.dismissedAt - } - }); - res.status(201).json(dismissal); - } - ); - return router2; -} - -// server/src/routes/instance-settings.ts -var import_express18 = __toESM(require_express2(), 1); -function assertCanManageInstanceSettings(req) { - if (req.actor.type !== "board") { - throw forbidden("Board access required"); - } - if (req.actor.source === "local_implicit" || req.actor.isInstanceAdmin) { - return; - } - throw forbidden("Instance admin access required"); -} -function instanceSettingsRoutes(db) { - const router2 = (0, import_express18.Router)(); - const svc = instanceSettingsService(db); - router2.get("/instance/settings/general", async (req, res) => { - if (req.actor.type !== "board") { - throw forbidden("Board access required"); - } - res.json(await svc.getGeneral()); - }); - router2.patch( - "/instance/settings/general", - validate(patchInstanceGeneralSettingsSchema), - async (req, res) => { - assertCanManageInstanceSettings(req); - const updated = await svc.updateGeneral(req.body); - const actor = getActorInfo(req); - const companyIds = await svc.listCompanyIds(); - await Promise.all( - companyIds.map( - (companyId) => logActivity(db, { - companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - runId: actor.runId, - action: "instance.settings.general_updated", - entityType: "instance_settings", - entityId: updated.id, - details: { - general: updated.general, - changedKeys: Object.keys(req.body).sort() - } - }) - ) - ); - res.json(updated.general); - } - ); - router2.get("/instance/settings/experimental", async (req, res) => { - if (req.actor.type !== "board") { - throw forbidden("Board access required"); - } - res.json(await svc.getExperimental()); - }); - router2.patch( - "/instance/settings/experimental", - validate(patchInstanceExperimentalSettingsSchema), - async (req, res) => { - assertCanManageInstanceSettings(req); - const updated = await svc.updateExperimental(req.body); - const actor = getActorInfo(req); - const companyIds = await svc.listCompanyIds(); - await Promise.all( - companyIds.map( - (companyId) => logActivity(db, { - companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - runId: actor.runId, - action: "instance.settings.experimental_updated", - entityType: "instance_settings", - entityId: updated.id, - details: { - experimental: updated.experimental, - changedKeys: Object.keys(req.body).sort() - } - }) - ) - ); - res.json(updated.experimental); - } - ); - return router2; -} - -// server/src/routes/llms.ts -var import_express19 = __toESM(require_express2(), 1); -function hasCreatePermission(agent) { - if (!agent.permissions || typeof agent.permissions !== "object") return false; - return Boolean(agent.permissions.canCreateAgents); -} -function llmRoutes(db) { - const router2 = (0, import_express19.Router)(); - const agentsSvc = agentService(db); - async function assertCanRead(req) { - if (req.actor.type === "board") return; - if (req.actor.type !== "agent" || !req.actor.agentId) { - throw forbidden("Board or permitted agent authentication required"); - } - const actorAgent = await agentsSvc.getById(req.actor.agentId); - if (!actorAgent || !hasCreatePermission(actorAgent)) { - throw forbidden("Missing permission to read agent configuration reflection"); - } - } - router2.get("/llms/agent-configuration.txt", async (req, res) => { - await assertCanRead(req); - const adapters = listServerAdapters().sort((a5, b6) => a5.type.localeCompare(b6.type)); - const lines = [ - "# Taskcore Agent Configuration Index", - "", - "Installed adapters:", - ...adapters.map((adapter) => `- ${adapter.type}: /llms/agent-configuration/${adapter.type}.txt`), - "", - "Related API endpoints:", - "- GET /api/companies/:companyId/agent-configurations", - "- GET /api/agents/:id/configuration", - "- POST /api/companies/:companyId/agent-hires", - "", - "Agent identity references:", - "- GET /llms/agent-icons.txt", - "", - "Notes:", - "- Sensitive values are redacted in configuration read APIs.", - "- New hires may be created in pending_approval state depending on company settings.", - "- Timer heartbeats are opt-in for new hires. Leave runtimeConfig.heartbeat.enabled false unless the role truly needs scheduled work or the user explicitly asked for it.", - "" - ]; - res.type("text/plain").send(lines.join("\n")); - }); - router2.get("/llms/agent-icons.txt", async (req, res) => { - await assertCanRead(req); - const lines = [ - "# Taskcore Agent Icon Names", - "", - "Set the `icon` field on hire/create payloads to one of:", - ...AGENT_ICON_NAMES.map((name) => `- ${name}`), - "", - "Example:", - '{ "name": "SearchOps", "role": "researcher", "icon": "search" }', - "" - ]; - res.type("text/plain").send(lines.join("\n")); - }); - router2.get("/llms/agent-configuration/:adapterType.txt", async (req, res) => { - await assertCanRead(req); - const adapterType = req.params.adapterType; - const adapter = listServerAdapters().find((entry) => entry.type === adapterType); - if (!adapter) { - res.status(404).type("text/plain").send(`Unknown adapter type: ${adapterType}`); - return; - } - res.type("text/plain").send( - adapter.agentConfigurationDoc ?? `# ${adapterType} agent configuration - -No adapter-specific documentation registered.` - ); - }); - return router2; -} - -// server/src/routes/assets.ts -var import_express20 = __toESM(require_express2(), 1); -var import_multer2 = __toESM(require_multer(), 1); - -// node_modules/.pnpm/dompurify@3.4.0/node_modules/dompurify/dist/purify.es.mjs -var { - entries, - setPrototypeOf, - isFrozen, - getPrototypeOf, - getOwnPropertyDescriptor -} = Object; -var { - freeze, - seal, - create -} = Object; -var { - apply, - construct: construct2 -} = typeof Reflect !== "undefined" && Reflect; -if (!freeze) { - freeze = function freeze3(x5) { - return x5; - }; -} -if (!seal) { - seal = function seal2(x5) { - return x5; - }; -} -if (!apply) { - apply = function apply2(func, thisArg) { - for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { - args[_key - 2] = arguments[_key]; - } - return func.apply(thisArg, args); - }; -} -if (!construct2) { - construct2 = function construct3(Func) { - for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { - args[_key2 - 1] = arguments[_key2]; - } - return new Func(...args); - }; -} -var arrayForEach = unapply(Array.prototype.forEach); -var arrayLastIndexOf = unapply(Array.prototype.lastIndexOf); -var arrayPop = unapply(Array.prototype.pop); -var arrayPush = unapply(Array.prototype.push); -var arraySplice = unapply(Array.prototype.splice); -var stringToLowerCase = unapply(String.prototype.toLowerCase); -var stringToString = unapply(String.prototype.toString); -var stringMatch = unapply(String.prototype.match); -var stringReplace = unapply(String.prototype.replace); -var stringIndexOf = unapply(String.prototype.indexOf); -var stringTrim = unapply(String.prototype.trim); -var objectHasOwnProperty = unapply(Object.prototype.hasOwnProperty); -var regExpTest = unapply(RegExp.prototype.test); -var typeErrorCreate = unconstruct(TypeError); -function unapply(func) { - return function(thisArg) { - if (thisArg instanceof RegExp) { - thisArg.lastIndex = 0; - } - for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) { - args[_key3 - 1] = arguments[_key3]; - } - return apply(func, thisArg, args); - }; -} -function unconstruct(Func) { - return function() { - for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { - args[_key4] = arguments[_key4]; - } - return construct2(Func, args); - }; -} -function addToSet(set2, array2) { - let transformCaseFunc = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : stringToLowerCase; - if (setPrototypeOf) { - setPrototypeOf(set2, null); - } - let l5 = array2.length; - while (l5--) { - let element = array2[l5]; - if (typeof element === "string") { - const lcElement = transformCaseFunc(element); - if (lcElement !== element) { - if (!isFrozen(array2)) { - array2[l5] = lcElement; - } - element = lcElement; - } - } - set2[element] = true; - } - return set2; -} -function cleanArray(array2) { - for (let index2 = 0; index2 < array2.length; index2++) { - const isPropertyExist = objectHasOwnProperty(array2, index2); - if (!isPropertyExist) { - array2[index2] = null; - } - } - return array2; -} -function clone(object2) { - const newObject = create(null); - for (const [property, value] of entries(object2)) { - const isPropertyExist = objectHasOwnProperty(object2, property); - if (isPropertyExist) { - if (Array.isArray(value)) { - newObject[property] = cleanArray(value); - } else if (value && typeof value === "object" && value.constructor === Object) { - newObject[property] = clone(value); - } else { - newObject[property] = value; - } - } - } - return newObject; -} -function lookupGetter(object2, prop) { - while (object2 !== null) { - const desc3 = getOwnPropertyDescriptor(object2, prop); - if (desc3) { - if (desc3.get) { - return unapply(desc3.get); - } - if (typeof desc3.value === "function") { - return unapply(desc3.value); - } - } - object2 = getPrototypeOf(object2); - } - function fallbackValue() { - return null; - } - return fallbackValue; -} -var html$1 = freeze(["a", "abbr", "acronym", "address", "area", "article", "aside", "audio", "b", "bdi", "bdo", "big", "blink", "blockquote", "body", "br", "button", "canvas", "caption", "center", "cite", "code", "col", "colgroup", "content", "data", "datalist", "dd", "decorator", "del", "details", "dfn", "dialog", "dir", "div", "dl", "dt", "element", "em", "fieldset", "figcaption", "figure", "font", "footer", "form", "h1", "h2", "h3", "h4", "h5", "h6", "head", "header", "hgroup", "hr", "html", "i", "img", "input", "ins", "kbd", "label", "legend", "li", "main", "map", "mark", "marquee", "menu", "menuitem", "meter", "nav", "nobr", "ol", "optgroup", "option", "output", "p", "picture", "pre", "progress", "q", "rp", "rt", "ruby", "s", "samp", "search", "section", "select", "shadow", "slot", "small", "source", "spacer", "span", "strike", "strong", "style", "sub", "summary", "sup", "table", "tbody", "td", "template", "textarea", "tfoot", "th", "thead", "time", "tr", "track", "tt", "u", "ul", "var", "video", "wbr"]); -var svg$1 = freeze(["svg", "a", "altglyph", "altglyphdef", "altglyphitem", "animatecolor", "animatemotion", "animatetransform", "circle", "clippath", "defs", "desc", "ellipse", "enterkeyhint", "exportparts", "filter", "font", "g", "glyph", "glyphref", "hkern", "image", "inputmode", "line", "lineargradient", "marker", "mask", "metadata", "mpath", "part", "path", "pattern", "polygon", "polyline", "radialgradient", "rect", "stop", "style", "switch", "symbol", "text", "textpath", "title", "tref", "tspan", "view", "vkern"]); -var svgFilters = freeze(["feBlend", "feColorMatrix", "feComponentTransfer", "feComposite", "feConvolveMatrix", "feDiffuseLighting", "feDisplacementMap", "feDistantLight", "feDropShadow", "feFlood", "feFuncA", "feFuncB", "feFuncG", "feFuncR", "feGaussianBlur", "feImage", "feMerge", "feMergeNode", "feMorphology", "feOffset", "fePointLight", "feSpecularLighting", "feSpotLight", "feTile", "feTurbulence"]); -var svgDisallowed = freeze(["animate", "color-profile", "cursor", "discard", "font-face", "font-face-format", "font-face-name", "font-face-src", "font-face-uri", "foreignobject", "hatch", "hatchpath", "mesh", "meshgradient", "meshpatch", "meshrow", "missing-glyph", "script", "set", "solidcolor", "unknown", "use"]); -var mathMl$1 = freeze(["math", "menclose", "merror", "mfenced", "mfrac", "mglyph", "mi", "mlabeledtr", "mmultiscripts", "mn", "mo", "mover", "mpadded", "mphantom", "mroot", "mrow", "ms", "mspace", "msqrt", "mstyle", "msub", "msup", "msubsup", "mtable", "mtd", "mtext", "mtr", "munder", "munderover", "mprescripts"]); -var mathMlDisallowed = freeze(["maction", "maligngroup", "malignmark", "mlongdiv", "mscarries", "mscarry", "msgroup", "mstack", "msline", "msrow", "semantics", "annotation", "annotation-xml", "mprescripts", "none"]); -var text2 = freeze(["#text"]); -var html = freeze(["accept", "action", "align", "alt", "autocapitalize", "autocomplete", "autopictureinpicture", "autoplay", "background", "bgcolor", "border", "capture", "cellpadding", "cellspacing", "checked", "cite", "class", "clear", "color", "cols", "colspan", "controls", "controlslist", "coords", "crossorigin", "datetime", "decoding", "default", "dir", "disabled", "disablepictureinpicture", "disableremoteplayback", "download", "draggable", "enctype", "enterkeyhint", "exportparts", "face", "for", "headers", "height", "hidden", "high", "href", "hreflang", "id", "inert", "inputmode", "integrity", "ismap", "kind", "label", "lang", "list", "loading", "loop", "low", "max", "maxlength", "media", "method", "min", "minlength", "multiple", "muted", "name", "nonce", "noshade", "novalidate", "nowrap", "open", "optimum", "part", "pattern", "placeholder", "playsinline", "popover", "popovertarget", "popovertargetaction", "poster", "preload", "pubdate", "radiogroup", "readonly", "rel", "required", "rev", "reversed", "role", "rows", "rowspan", "spellcheck", "scope", "selected", "shape", "size", "sizes", "slot", "span", "srclang", "start", "src", "srcset", "step", "style", "summary", "tabindex", "title", "translate", "type", "usemap", "valign", "value", "width", "wrap", "xmlns", "slot"]); -var svg = freeze(["accent-height", "accumulate", "additive", "alignment-baseline", "amplitude", "ascent", "attributename", "attributetype", "azimuth", "basefrequency", "baseline-shift", "begin", "bias", "by", "class", "clip", "clippathunits", "clip-path", "clip-rule", "color", "color-interpolation", "color-interpolation-filters", "color-profile", "color-rendering", "cx", "cy", "d", "dx", "dy", "diffuseconstant", "direction", "display", "divisor", "dur", "edgemode", "elevation", "end", "exponent", "fill", "fill-opacity", "fill-rule", "filter", "filterunits", "flood-color", "flood-opacity", "font-family", "font-size", "font-size-adjust", "font-stretch", "font-style", "font-variant", "font-weight", "fx", "fy", "g1", "g2", "glyph-name", "glyphref", "gradientunits", "gradienttransform", "height", "href", "id", "image-rendering", "in", "in2", "intercept", "k", "k1", "k2", "k3", "k4", "kerning", "keypoints", "keysplines", "keytimes", "lang", "lengthadjust", "letter-spacing", "kernelmatrix", "kernelunitlength", "lighting-color", "local", "marker-end", "marker-mid", "marker-start", "markerheight", "markerunits", "markerwidth", "maskcontentunits", "maskunits", "max", "mask", "mask-type", "media", "method", "mode", "min", "name", "numoctaves", "offset", "operator", "opacity", "order", "orient", "orientation", "origin", "overflow", "paint-order", "path", "pathlength", "patterncontentunits", "patterntransform", "patternunits", "points", "preservealpha", "preserveaspectratio", "primitiveunits", "r", "rx", "ry", "radius", "refx", "refy", "repeatcount", "repeatdur", "restart", "result", "rotate", "scale", "seed", "shape-rendering", "slope", "specularconstant", "specularexponent", "spreadmethod", "startoffset", "stddeviation", "stitchtiles", "stop-color", "stop-opacity", "stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin", "stroke-miterlimit", "stroke-opacity", "stroke", "stroke-width", "style", "surfacescale", "systemlanguage", "tabindex", "tablevalues", "targetx", "targety", "transform", "transform-origin", "text-anchor", "text-decoration", "text-rendering", "textlength", "type", "u1", "u2", "unicode", "values", "viewbox", "visibility", "version", "vert-adv-y", "vert-origin-x", "vert-origin-y", "width", "word-spacing", "wrap", "writing-mode", "xchannelselector", "ychannelselector", "x", "x1", "x2", "xmlns", "y", "y1", "y2", "z", "zoomandpan"]); -var mathMl = freeze(["accent", "accentunder", "align", "bevelled", "close", "columnalign", "columnlines", "columnspacing", "columnspan", "denomalign", "depth", "dir", "display", "displaystyle", "encoding", "fence", "frame", "height", "href", "id", "largeop", "length", "linethickness", "lquote", "lspace", "mathbackground", "mathcolor", "mathsize", "mathvariant", "maxsize", "minsize", "movablelimits", "notation", "numalign", "open", "rowalign", "rowlines", "rowspacing", "rowspan", "rspace", "rquote", "scriptlevel", "scriptminsize", "scriptsizemultiplier", "selection", "separator", "separators", "stretchy", "subscriptshift", "supscriptshift", "symmetric", "voffset", "width", "xmlns"]); -var xml = freeze(["xlink:href", "xml:id", "xlink:title", "xml:space", "xmlns:xlink"]); -var MUSTACHE_EXPR = seal(/\{\{[\w\W]*|[\w\W]*\}\}/gm); -var ERB_EXPR = seal(/<%[\w\W]*|[\w\W]*%>/gm); -var TMPLIT_EXPR = seal(/\$\{[\w\W]*/gm); -var DATA_ATTR = seal(/^data-[\-\w.\u00B7-\uFFFF]+$/); -var ARIA_ATTR = seal(/^aria-[\-\w]+$/); -var IS_ALLOWED_URI = seal( - /^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i - // eslint-disable-line no-useless-escape -); -var IS_SCRIPT_OR_DATA = seal(/^(?:\w+script|data):/i); -var ATTR_WHITESPACE = seal( - /[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g - // eslint-disable-line no-control-regex -); -var DOCTYPE_NAME = seal(/^html$/i); -var CUSTOM_ELEMENT = seal(/^[a-z][.\w]*(-[.\w]+)+$/i); -var EXPRESSIONS = /* @__PURE__ */ Object.freeze({ - __proto__: null, - ARIA_ATTR, - ATTR_WHITESPACE, - CUSTOM_ELEMENT, - DATA_ATTR, - DOCTYPE_NAME, - ERB_EXPR, - IS_ALLOWED_URI, - IS_SCRIPT_OR_DATA, - MUSTACHE_EXPR, - TMPLIT_EXPR -}); -var NODE_TYPE = { - element: 1, - text: 3, - // Deprecated - progressingInstruction: 7, - comment: 8, - document: 9 -}; -var getGlobal = function getGlobal2() { - return typeof window === "undefined" ? null : window; -}; -var _createTrustedTypesPolicy = function _createTrustedTypesPolicy2(trustedTypes, purifyHostElement) { - if (typeof trustedTypes !== "object" || typeof trustedTypes.createPolicy !== "function") { - return null; - } - let suffix = null; - const ATTR_NAME = "data-tt-policy-suffix"; - if (purifyHostElement && purifyHostElement.hasAttribute(ATTR_NAME)) { - suffix = purifyHostElement.getAttribute(ATTR_NAME); - } - const policyName = "dompurify" + (suffix ? "#" + suffix : ""); - try { - return trustedTypes.createPolicy(policyName, { - createHTML(html3) { - return html3; - }, - createScriptURL(scriptUrl) { - return scriptUrl; - } - }); - } catch (_) { - console.warn("TrustedTypes policy " + policyName + " could not be created."); - return null; - } -}; -var _createHooksMap = function _createHooksMap2() { - return { - afterSanitizeAttributes: [], - afterSanitizeElements: [], - afterSanitizeShadowDOM: [], - beforeSanitizeAttributes: [], - beforeSanitizeElements: [], - beforeSanitizeShadowDOM: [], - uponSanitizeAttribute: [], - uponSanitizeElement: [], - uponSanitizeShadowNode: [] - }; -}; -function createDOMPurify() { - let window2 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : getGlobal(); - const DOMPurify = (root) => createDOMPurify(root); - DOMPurify.version = "3.4.0"; - DOMPurify.removed = []; - if (!window2 || !window2.document || window2.document.nodeType !== NODE_TYPE.document || !window2.Element) { - DOMPurify.isSupported = false; - return DOMPurify; - } - let { - document: document2 - } = window2; - const originalDocument = document2; - const currentScript = originalDocument.currentScript; - const { - DocumentFragment, - HTMLTemplateElement, - Node, - Element, - NodeFilter, - NamedNodeMap = window2.NamedNodeMap || window2.MozNamedAttrMap, - HTMLFormElement, - DOMParser, - trustedTypes - } = window2; - const ElementPrototype = Element.prototype; - const cloneNode = lookupGetter(ElementPrototype, "cloneNode"); - const remove = lookupGetter(ElementPrototype, "remove"); - const getNextSibling = lookupGetter(ElementPrototype, "nextSibling"); - const getChildNodes = lookupGetter(ElementPrototype, "childNodes"); - const getParentNode = lookupGetter(ElementPrototype, "parentNode"); - if (typeof HTMLTemplateElement === "function") { - const template = document2.createElement("template"); - if (template.content && template.content.ownerDocument) { - document2 = template.content.ownerDocument; - } - } - let trustedTypesPolicy; - let emptyHTML = ""; - const { - implementation, - createNodeIterator, - createDocumentFragment, - getElementsByTagName - } = document2; - const { - importNode - } = originalDocument; - let hooks = _createHooksMap(); - DOMPurify.isSupported = typeof entries === "function" && typeof getParentNode === "function" && implementation && implementation.createHTMLDocument !== void 0; - const { - MUSTACHE_EXPR: MUSTACHE_EXPR2, - ERB_EXPR: ERB_EXPR2, - TMPLIT_EXPR: TMPLIT_EXPR2, - DATA_ATTR: DATA_ATTR2, - ARIA_ATTR: ARIA_ATTR2, - IS_SCRIPT_OR_DATA: IS_SCRIPT_OR_DATA2, - ATTR_WHITESPACE: ATTR_WHITESPACE2, - CUSTOM_ELEMENT: CUSTOM_ELEMENT2 - } = EXPRESSIONS; - let { - IS_ALLOWED_URI: IS_ALLOWED_URI$1 - } = EXPRESSIONS; - let ALLOWED_TAGS = null; - const DEFAULT_ALLOWED_TAGS = addToSet({}, [...html$1, ...svg$1, ...svgFilters, ...mathMl$1, ...text2]); - let ALLOWED_ATTR = null; - const DEFAULT_ALLOWED_ATTR = addToSet({}, [...html, ...svg, ...mathMl, ...xml]); - let CUSTOM_ELEMENT_HANDLING = Object.seal(create(null, { - tagNameCheck: { - writable: true, - configurable: false, - enumerable: true, - value: null - }, - attributeNameCheck: { - writable: true, - configurable: false, - enumerable: true, - value: null - }, - allowCustomizedBuiltInElements: { - writable: true, - configurable: false, - enumerable: true, - value: false - } - })); - let FORBID_TAGS = null; - let FORBID_ATTR = null; - const EXTRA_ELEMENT_HANDLING = Object.seal(create(null, { - tagCheck: { - writable: true, - configurable: false, - enumerable: true, - value: null - }, - attributeCheck: { - writable: true, - configurable: false, - enumerable: true, - value: null - } - })); - let ALLOW_ARIA_ATTR = true; - let ALLOW_DATA_ATTR = true; - let ALLOW_UNKNOWN_PROTOCOLS = false; - let ALLOW_SELF_CLOSE_IN_ATTR = true; - let SAFE_FOR_TEMPLATES = false; - let SAFE_FOR_XML = true; - let WHOLE_DOCUMENT = false; - let SET_CONFIG = false; - let FORCE_BODY = false; - let RETURN_DOM = false; - let RETURN_DOM_FRAGMENT = false; - let RETURN_TRUSTED_TYPE = false; - let SANITIZE_DOM = true; - let SANITIZE_NAMED_PROPS = false; - const SANITIZE_NAMED_PROPS_PREFIX = "user-content-"; - let KEEP_CONTENT = true; - let IN_PLACE = false; - let USE_PROFILES = {}; - let FORBID_CONTENTS = null; - const DEFAULT_FORBID_CONTENTS = addToSet({}, ["annotation-xml", "audio", "colgroup", "desc", "foreignobject", "head", "iframe", "math", "mi", "mn", "mo", "ms", "mtext", "noembed", "noframes", "noscript", "plaintext", "script", "style", "svg", "template", "thead", "title", "video", "xmp"]); - let DATA_URI_TAGS = null; - const DEFAULT_DATA_URI_TAGS = addToSet({}, ["audio", "video", "img", "source", "image", "track"]); - let URI_SAFE_ATTRIBUTES = null; - const DEFAULT_URI_SAFE_ATTRIBUTES = addToSet({}, ["alt", "class", "for", "id", "label", "name", "pattern", "placeholder", "role", "summary", "title", "value", "style", "xmlns"]); - const MATHML_NAMESPACE = "http://www.w3.org/1998/Math/MathML"; - const SVG_NAMESPACE = "http://www.w3.org/2000/svg"; - const HTML_NAMESPACE = "http://www.w3.org/1999/xhtml"; - let NAMESPACE = HTML_NAMESPACE; - let IS_EMPTY_INPUT = false; - let ALLOWED_NAMESPACES = null; - const DEFAULT_ALLOWED_NAMESPACES = addToSet({}, [MATHML_NAMESPACE, SVG_NAMESPACE, HTML_NAMESPACE], stringToString); - let MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, ["mi", "mo", "mn", "ms", "mtext"]); - let HTML_INTEGRATION_POINTS = addToSet({}, ["annotation-xml"]); - const COMMON_SVG_AND_HTML_ELEMENTS = addToSet({}, ["title", "style", "font", "a", "script"]); - let PARSER_MEDIA_TYPE = null; - const SUPPORTED_PARSER_MEDIA_TYPES = ["application/xhtml+xml", "text/html"]; - const DEFAULT_PARSER_MEDIA_TYPE = "text/html"; - let transformCaseFunc = null; - let CONFIG = null; - const formElement = document2.createElement("form"); - const isRegexOrFunction = function isRegexOrFunction2(testValue) { - return testValue instanceof RegExp || testValue instanceof Function; - }; - const _parseConfig = function _parseConfig2() { - let cfg = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {}; - if (CONFIG && CONFIG === cfg) { - return; - } - if (!cfg || typeof cfg !== "object") { - cfg = {}; - } - cfg = clone(cfg); - PARSER_MEDIA_TYPE = // eslint-disable-next-line unicorn/prefer-includes - SUPPORTED_PARSER_MEDIA_TYPES.indexOf(cfg.PARSER_MEDIA_TYPE) === -1 ? DEFAULT_PARSER_MEDIA_TYPE : cfg.PARSER_MEDIA_TYPE; - transformCaseFunc = PARSER_MEDIA_TYPE === "application/xhtml+xml" ? stringToString : stringToLowerCase; - ALLOWED_TAGS = objectHasOwnProperty(cfg, "ALLOWED_TAGS") ? addToSet({}, cfg.ALLOWED_TAGS, transformCaseFunc) : DEFAULT_ALLOWED_TAGS; - ALLOWED_ATTR = objectHasOwnProperty(cfg, "ALLOWED_ATTR") ? addToSet({}, cfg.ALLOWED_ATTR, transformCaseFunc) : DEFAULT_ALLOWED_ATTR; - ALLOWED_NAMESPACES = objectHasOwnProperty(cfg, "ALLOWED_NAMESPACES") ? addToSet({}, cfg.ALLOWED_NAMESPACES, stringToString) : DEFAULT_ALLOWED_NAMESPACES; - URI_SAFE_ATTRIBUTES = objectHasOwnProperty(cfg, "ADD_URI_SAFE_ATTR") ? addToSet(clone(DEFAULT_URI_SAFE_ATTRIBUTES), cfg.ADD_URI_SAFE_ATTR, transformCaseFunc) : DEFAULT_URI_SAFE_ATTRIBUTES; - DATA_URI_TAGS = objectHasOwnProperty(cfg, "ADD_DATA_URI_TAGS") ? addToSet(clone(DEFAULT_DATA_URI_TAGS), cfg.ADD_DATA_URI_TAGS, transformCaseFunc) : DEFAULT_DATA_URI_TAGS; - FORBID_CONTENTS = objectHasOwnProperty(cfg, "FORBID_CONTENTS") ? addToSet({}, cfg.FORBID_CONTENTS, transformCaseFunc) : DEFAULT_FORBID_CONTENTS; - FORBID_TAGS = objectHasOwnProperty(cfg, "FORBID_TAGS") ? addToSet({}, cfg.FORBID_TAGS, transformCaseFunc) : clone({}); - FORBID_ATTR = objectHasOwnProperty(cfg, "FORBID_ATTR") ? addToSet({}, cfg.FORBID_ATTR, transformCaseFunc) : clone({}); - USE_PROFILES = objectHasOwnProperty(cfg, "USE_PROFILES") ? cfg.USE_PROFILES : false; - ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false; - ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false; - ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false; - ALLOW_SELF_CLOSE_IN_ATTR = cfg.ALLOW_SELF_CLOSE_IN_ATTR !== false; - SAFE_FOR_TEMPLATES = cfg.SAFE_FOR_TEMPLATES || false; - SAFE_FOR_XML = cfg.SAFE_FOR_XML !== false; - WHOLE_DOCUMENT = cfg.WHOLE_DOCUMENT || false; - RETURN_DOM = cfg.RETURN_DOM || false; - RETURN_DOM_FRAGMENT = cfg.RETURN_DOM_FRAGMENT || false; - RETURN_TRUSTED_TYPE = cfg.RETURN_TRUSTED_TYPE || false; - FORCE_BODY = cfg.FORCE_BODY || false; - SANITIZE_DOM = cfg.SANITIZE_DOM !== false; - SANITIZE_NAMED_PROPS = cfg.SANITIZE_NAMED_PROPS || false; - KEEP_CONTENT = cfg.KEEP_CONTENT !== false; - IN_PLACE = cfg.IN_PLACE || false; - IS_ALLOWED_URI$1 = cfg.ALLOWED_URI_REGEXP || IS_ALLOWED_URI; - NAMESPACE = cfg.NAMESPACE || HTML_NAMESPACE; - MATHML_TEXT_INTEGRATION_POINTS = cfg.MATHML_TEXT_INTEGRATION_POINTS || MATHML_TEXT_INTEGRATION_POINTS; - HTML_INTEGRATION_POINTS = cfg.HTML_INTEGRATION_POINTS || HTML_INTEGRATION_POINTS; - CUSTOM_ELEMENT_HANDLING = cfg.CUSTOM_ELEMENT_HANDLING || create(null); - if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck)) { - CUSTOM_ELEMENT_HANDLING.tagNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck; - } - if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)) { - CUSTOM_ELEMENT_HANDLING.attributeNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck; - } - if (cfg.CUSTOM_ELEMENT_HANDLING && typeof cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements === "boolean") { - CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements = cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements; - } - if (SAFE_FOR_TEMPLATES) { - ALLOW_DATA_ATTR = false; - } - if (RETURN_DOM_FRAGMENT) { - RETURN_DOM = true; - } - if (USE_PROFILES) { - ALLOWED_TAGS = addToSet({}, text2); - ALLOWED_ATTR = create(null); - if (USE_PROFILES.html === true) { - addToSet(ALLOWED_TAGS, html$1); - addToSet(ALLOWED_ATTR, html); - } - if (USE_PROFILES.svg === true) { - addToSet(ALLOWED_TAGS, svg$1); - addToSet(ALLOWED_ATTR, svg); - addToSet(ALLOWED_ATTR, xml); - } - if (USE_PROFILES.svgFilters === true) { - addToSet(ALLOWED_TAGS, svgFilters); - addToSet(ALLOWED_ATTR, svg); - addToSet(ALLOWED_ATTR, xml); - } - if (USE_PROFILES.mathMl === true) { - addToSet(ALLOWED_TAGS, mathMl$1); - addToSet(ALLOWED_ATTR, mathMl); - addToSet(ALLOWED_ATTR, xml); - } - } - EXTRA_ELEMENT_HANDLING.tagCheck = null; - EXTRA_ELEMENT_HANDLING.attributeCheck = null; - if (cfg.ADD_TAGS) { - if (typeof cfg.ADD_TAGS === "function") { - EXTRA_ELEMENT_HANDLING.tagCheck = cfg.ADD_TAGS; - } else { - if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) { - ALLOWED_TAGS = clone(ALLOWED_TAGS); - } - addToSet(ALLOWED_TAGS, cfg.ADD_TAGS, transformCaseFunc); - } - } - if (cfg.ADD_ATTR) { - if (typeof cfg.ADD_ATTR === "function") { - EXTRA_ELEMENT_HANDLING.attributeCheck = cfg.ADD_ATTR; - } else { - if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) { - ALLOWED_ATTR = clone(ALLOWED_ATTR); - } - addToSet(ALLOWED_ATTR, cfg.ADD_ATTR, transformCaseFunc); - } - } - if (cfg.ADD_URI_SAFE_ATTR) { - addToSet(URI_SAFE_ATTRIBUTES, cfg.ADD_URI_SAFE_ATTR, transformCaseFunc); - } - if (cfg.FORBID_CONTENTS) { - if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) { - FORBID_CONTENTS = clone(FORBID_CONTENTS); - } - addToSet(FORBID_CONTENTS, cfg.FORBID_CONTENTS, transformCaseFunc); - } - if (cfg.ADD_FORBID_CONTENTS) { - if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) { - FORBID_CONTENTS = clone(FORBID_CONTENTS); - } - addToSet(FORBID_CONTENTS, cfg.ADD_FORBID_CONTENTS, transformCaseFunc); - } - if (KEEP_CONTENT) { - ALLOWED_TAGS["#text"] = true; - } - if (WHOLE_DOCUMENT) { - addToSet(ALLOWED_TAGS, ["html", "head", "body"]); - } - if (ALLOWED_TAGS.table) { - addToSet(ALLOWED_TAGS, ["tbody"]); - delete FORBID_TAGS.tbody; - } - if (cfg.TRUSTED_TYPES_POLICY) { - if (typeof cfg.TRUSTED_TYPES_POLICY.createHTML !== "function") { - throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.'); - } - if (typeof cfg.TRUSTED_TYPES_POLICY.createScriptURL !== "function") { - throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.'); - } - trustedTypesPolicy = cfg.TRUSTED_TYPES_POLICY; - emptyHTML = trustedTypesPolicy.createHTML(""); - } else { - if (trustedTypesPolicy === void 0) { - trustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, currentScript); - } - if (trustedTypesPolicy !== null && typeof emptyHTML === "string") { - emptyHTML = trustedTypesPolicy.createHTML(""); - } - } - if (freeze) { - freeze(cfg); - } - CONFIG = cfg; - }; - const ALL_SVG_TAGS = addToSet({}, [...svg$1, ...svgFilters, ...svgDisallowed]); - const ALL_MATHML_TAGS = addToSet({}, [...mathMl$1, ...mathMlDisallowed]); - const _checkValidNamespace = function _checkValidNamespace2(element) { - let parent = getParentNode(element); - if (!parent || !parent.tagName) { - parent = { - namespaceURI: NAMESPACE, - tagName: "template" - }; - } - const tagName = stringToLowerCase(element.tagName); - const parentTagName = stringToLowerCase(parent.tagName); - if (!ALLOWED_NAMESPACES[element.namespaceURI]) { - return false; - } - if (element.namespaceURI === SVG_NAMESPACE) { - if (parent.namespaceURI === HTML_NAMESPACE) { - return tagName === "svg"; - } - if (parent.namespaceURI === MATHML_NAMESPACE) { - return tagName === "svg" && (parentTagName === "annotation-xml" || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]); - } - return Boolean(ALL_SVG_TAGS[tagName]); - } - if (element.namespaceURI === MATHML_NAMESPACE) { - if (parent.namespaceURI === HTML_NAMESPACE) { - return tagName === "math"; - } - if (parent.namespaceURI === SVG_NAMESPACE) { - return tagName === "math" && HTML_INTEGRATION_POINTS[parentTagName]; - } - return Boolean(ALL_MATHML_TAGS[tagName]); - } - if (element.namespaceURI === HTML_NAMESPACE) { - if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) { - return false; - } - if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) { - return false; - } - return !ALL_MATHML_TAGS[tagName] && (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName]); - } - if (PARSER_MEDIA_TYPE === "application/xhtml+xml" && ALLOWED_NAMESPACES[element.namespaceURI]) { - return true; - } - return false; - }; - const _forceRemove = function _forceRemove2(node) { - arrayPush(DOMPurify.removed, { - element: node - }); - try { - getParentNode(node).removeChild(node); - } catch (_) { - remove(node); - } - }; - const _removeAttribute = function _removeAttribute2(name, element) { - try { - arrayPush(DOMPurify.removed, { - attribute: element.getAttributeNode(name), - from: element - }); - } catch (_) { - arrayPush(DOMPurify.removed, { - attribute: null, - from: element - }); - } - element.removeAttribute(name); - if (name === "is") { - if (RETURN_DOM || RETURN_DOM_FRAGMENT) { - try { - _forceRemove(element); - } catch (_) { - } - } else { - try { - element.setAttribute(name, ""); - } catch (_) { - } - } - } - }; - const _initDocument = function _initDocument2(dirty) { - let doc = null; - let leadingWhitespace = null; - if (FORCE_BODY) { - dirty = "" + dirty; - } else { - const matches = stringMatch(dirty, /^[\r\n\t ]+/); - leadingWhitespace = matches && matches[0]; - } - if (PARSER_MEDIA_TYPE === "application/xhtml+xml" && NAMESPACE === HTML_NAMESPACE) { - dirty = '' + dirty + ""; - } - const dirtyPayload = trustedTypesPolicy ? trustedTypesPolicy.createHTML(dirty) : dirty; - if (NAMESPACE === HTML_NAMESPACE) { - try { - doc = new DOMParser().parseFromString(dirtyPayload, PARSER_MEDIA_TYPE); - } catch (_) { - } - } - if (!doc || !doc.documentElement) { - doc = implementation.createDocument(NAMESPACE, "template", null); - try { - doc.documentElement.innerHTML = IS_EMPTY_INPUT ? emptyHTML : dirtyPayload; - } catch (_) { - } - } - const body = doc.body || doc.documentElement; - if (dirty && leadingWhitespace) { - body.insertBefore(document2.createTextNode(leadingWhitespace), body.childNodes[0] || null); - } - if (NAMESPACE === HTML_NAMESPACE) { - return getElementsByTagName.call(doc, WHOLE_DOCUMENT ? "html" : "body")[0]; - } - return WHOLE_DOCUMENT ? doc.documentElement : body; - }; - const _createNodeIterator = function _createNodeIterator2(root) { - return createNodeIterator.call( - root.ownerDocument || root, - root, - // eslint-disable-next-line no-bitwise - NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT | NodeFilter.SHOW_PROCESSING_INSTRUCTION | NodeFilter.SHOW_CDATA_SECTION, - null - ); - }; - const _isClobbered = function _isClobbered2(element) { - return element instanceof HTMLFormElement && (typeof element.nodeName !== "string" || typeof element.textContent !== "string" || typeof element.removeChild !== "function" || !(element.attributes instanceof NamedNodeMap) || typeof element.removeAttribute !== "function" || typeof element.setAttribute !== "function" || typeof element.namespaceURI !== "string" || typeof element.insertBefore !== "function" || typeof element.hasChildNodes !== "function"); - }; - const _isNode = function _isNode2(value) { - return typeof Node === "function" && value instanceof Node; - }; - function _executeHooks(hooks2, currentNode, data2) { - arrayForEach(hooks2, (hook) => { - hook.call(DOMPurify, currentNode, data2, CONFIG); - }); - } - const _sanitizeElements = function _sanitizeElements2(currentNode) { - let content = null; - _executeHooks(hooks.beforeSanitizeElements, currentNode, null); - if (_isClobbered(currentNode)) { - _forceRemove(currentNode); - return true; - } - const tagName = transformCaseFunc(currentNode.nodeName); - _executeHooks(hooks.uponSanitizeElement, currentNode, { - tagName, - allowedTags: ALLOWED_TAGS - }); - if (SAFE_FOR_XML && currentNode.hasChildNodes() && !_isNode(currentNode.firstElementChild) && regExpTest(/<[/\w!]/g, currentNode.innerHTML) && regExpTest(/<[/\w!]/g, currentNode.textContent)) { - _forceRemove(currentNode); - return true; - } - if (SAFE_FOR_XML && currentNode.namespaceURI === HTML_NAMESPACE && tagName === "style" && _isNode(currentNode.firstElementChild)) { - _forceRemove(currentNode); - return true; - } - if (currentNode.nodeType === NODE_TYPE.progressingInstruction) { - _forceRemove(currentNode); - return true; - } - if (SAFE_FOR_XML && currentNode.nodeType === NODE_TYPE.comment && regExpTest(/<[/\w]/g, currentNode.data)) { - _forceRemove(currentNode); - return true; - } - if (FORBID_TAGS[tagName] || !(EXTRA_ELEMENT_HANDLING.tagCheck instanceof Function && EXTRA_ELEMENT_HANDLING.tagCheck(tagName)) && !ALLOWED_TAGS[tagName]) { - if (!FORBID_TAGS[tagName] && _isBasicCustomElement(tagName)) { - if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)) { - return false; - } - if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(tagName)) { - return false; - } - } - if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) { - const parentNode = getParentNode(currentNode) || currentNode.parentNode; - const childNodes = getChildNodes(currentNode) || currentNode.childNodes; - if (childNodes && parentNode) { - const childCount = childNodes.length; - for (let i5 = childCount - 1; i5 >= 0; --i5) { - const childClone = cloneNode(childNodes[i5], true); - childClone.__removalCount = (currentNode.__removalCount || 0) + 1; - parentNode.insertBefore(childClone, getNextSibling(currentNode)); - } - } - } - _forceRemove(currentNode); - return true; - } - if (currentNode instanceof Element && !_checkValidNamespace(currentNode)) { - _forceRemove(currentNode); - return true; - } - if ((tagName === "noscript" || tagName === "noembed" || tagName === "noframes") && regExpTest(/<\/no(script|embed|frames)/i, currentNode.innerHTML)) { - _forceRemove(currentNode); - return true; - } - if (SAFE_FOR_TEMPLATES && currentNode.nodeType === NODE_TYPE.text) { - content = currentNode.textContent; - arrayForEach([MUSTACHE_EXPR2, ERB_EXPR2, TMPLIT_EXPR2], (expr) => { - content = stringReplace(content, expr, " "); - }); - if (currentNode.textContent !== content) { - arrayPush(DOMPurify.removed, { - element: currentNode.cloneNode() - }); - currentNode.textContent = content; - } - } - _executeHooks(hooks.afterSanitizeElements, currentNode, null); - return false; - }; - const _isValidAttribute = function _isValidAttribute2(lcTag, lcName, value) { - if (FORBID_ATTR[lcName]) { - return false; - } - if (SANITIZE_DOM && (lcName === "id" || lcName === "name") && (value in document2 || value in formElement)) { - return false; - } - if (ALLOW_DATA_ATTR && !FORBID_ATTR[lcName] && regExpTest(DATA_ATTR2, lcName)) ; - else if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR2, lcName)) ; - else if (EXTRA_ELEMENT_HANDLING.attributeCheck instanceof Function && EXTRA_ELEMENT_HANDLING.attributeCheck(lcName, lcTag)) ; - else if (!ALLOWED_ATTR[lcName] || FORBID_ATTR[lcName]) { - if ( - // First condition does a very basic check if a) it's basically a valid custom element tagname AND - // b) if the tagName passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck - // and c) if the attribute name passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.attributeNameCheck - _isBasicCustomElement(lcTag) && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, lcTag) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(lcTag)) && (CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.attributeNameCheck, lcName) || CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.attributeNameCheck(lcName, lcTag)) || // Alternative, second condition checks if it's an `is`-attribute, AND - // the value passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck - lcName === "is" && CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, value) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(value)) - ) ; - else { - return false; - } - } else if (URI_SAFE_ATTRIBUTES[lcName]) ; - else if (regExpTest(IS_ALLOWED_URI$1, stringReplace(value, ATTR_WHITESPACE2, ""))) ; - else if ((lcName === "src" || lcName === "xlink:href" || lcName === "href") && lcTag !== "script" && stringIndexOf(value, "data:") === 0 && DATA_URI_TAGS[lcTag]) ; - else if (ALLOW_UNKNOWN_PROTOCOLS && !regExpTest(IS_SCRIPT_OR_DATA2, stringReplace(value, ATTR_WHITESPACE2, ""))) ; - else if (value) { - return false; - } else ; - return true; - }; - const _isBasicCustomElement = function _isBasicCustomElement2(tagName) { - return tagName !== "annotation-xml" && stringMatch(tagName, CUSTOM_ELEMENT2); - }; - const _sanitizeAttributes = function _sanitizeAttributes2(currentNode) { - _executeHooks(hooks.beforeSanitizeAttributes, currentNode, null); - const { - attributes - } = currentNode; - if (!attributes || _isClobbered(currentNode)) { - return; - } - const hookEvent = { - attrName: "", - attrValue: "", - keepAttr: true, - allowedAttributes: ALLOWED_ATTR, - forceKeepAttr: void 0 - }; - let l5 = attributes.length; - while (l5--) { - const attr = attributes[l5]; - const { - name, - namespaceURI, - value: attrValue - } = attr; - const lcName = transformCaseFunc(name); - const initValue = attrValue; - let value = name === "value" ? initValue : stringTrim(initValue); - hookEvent.attrName = lcName; - hookEvent.attrValue = value; - hookEvent.keepAttr = true; - hookEvent.forceKeepAttr = void 0; - _executeHooks(hooks.uponSanitizeAttribute, currentNode, hookEvent); - value = hookEvent.attrValue; - if (SANITIZE_NAMED_PROPS && (lcName === "id" || lcName === "name")) { - _removeAttribute(name, currentNode); - value = SANITIZE_NAMED_PROPS_PREFIX + value; - } - if (SAFE_FOR_XML && regExpTest(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i, value)) { - _removeAttribute(name, currentNode); - continue; - } - if (lcName === "attributename" && stringMatch(value, "href")) { - _removeAttribute(name, currentNode); - continue; - } - if (hookEvent.forceKeepAttr) { - continue; - } - if (!hookEvent.keepAttr) { - _removeAttribute(name, currentNode); - continue; - } - if (!ALLOW_SELF_CLOSE_IN_ATTR && regExpTest(/\/>/i, value)) { - _removeAttribute(name, currentNode); - continue; - } - if (SAFE_FOR_TEMPLATES) { - arrayForEach([MUSTACHE_EXPR2, ERB_EXPR2, TMPLIT_EXPR2], (expr) => { - value = stringReplace(value, expr, " "); - }); - } - const lcTag = transformCaseFunc(currentNode.nodeName); - if (!_isValidAttribute(lcTag, lcName, value)) { - _removeAttribute(name, currentNode); - continue; - } - if (trustedTypesPolicy && typeof trustedTypes === "object" && typeof trustedTypes.getAttributeType === "function") { - if (namespaceURI) ; - else { - switch (trustedTypes.getAttributeType(lcTag, lcName)) { - case "TrustedHTML": { - value = trustedTypesPolicy.createHTML(value); - break; - } - case "TrustedScriptURL": { - value = trustedTypesPolicy.createScriptURL(value); - break; - } - } - } - } - if (value !== initValue) { - try { - if (namespaceURI) { - currentNode.setAttributeNS(namespaceURI, name, value); - } else { - currentNode.setAttribute(name, value); - } - if (_isClobbered(currentNode)) { - _forceRemove(currentNode); - } else { - arrayPop(DOMPurify.removed); - } - } catch (_) { - _removeAttribute(name, currentNode); - } - } - } - _executeHooks(hooks.afterSanitizeAttributes, currentNode, null); - }; - const _sanitizeShadowDOM2 = function _sanitizeShadowDOM(fragment2) { - let shadowNode = null; - const shadowIterator = _createNodeIterator(fragment2); - _executeHooks(hooks.beforeSanitizeShadowDOM, fragment2, null); - while (shadowNode = shadowIterator.nextNode()) { - _executeHooks(hooks.uponSanitizeShadowNode, shadowNode, null); - _sanitizeElements(shadowNode); - _sanitizeAttributes(shadowNode); - if (shadowNode.content instanceof DocumentFragment) { - _sanitizeShadowDOM2(shadowNode.content); - } - } - _executeHooks(hooks.afterSanitizeShadowDOM, fragment2, null); - }; - DOMPurify.sanitize = function(dirty) { - let cfg = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}; - let body = null; - let importedNode = null; - let currentNode = null; - let returnNode = null; - IS_EMPTY_INPUT = !dirty; - if (IS_EMPTY_INPUT) { - dirty = ""; - } - if (typeof dirty !== "string" && !_isNode(dirty)) { - if (typeof dirty.toString === "function") { - dirty = dirty.toString(); - if (typeof dirty !== "string") { - throw typeErrorCreate("dirty is not a string, aborting"); - } - } else { - throw typeErrorCreate("toString is not a function"); - } - } - if (!DOMPurify.isSupported) { - return dirty; - } - if (!SET_CONFIG) { - _parseConfig(cfg); - } - DOMPurify.removed = []; - if (typeof dirty === "string") { - IN_PLACE = false; - } - if (IN_PLACE) { - if (dirty.nodeName) { - const tagName = transformCaseFunc(dirty.nodeName); - if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) { - throw typeErrorCreate("root node is forbidden and cannot be sanitized in-place"); - } - } - } else if (dirty instanceof Node) { - body = _initDocument(""); - importedNode = body.ownerDocument.importNode(dirty, true); - if (importedNode.nodeType === NODE_TYPE.element && importedNode.nodeName === "BODY") { - body = importedNode; - } else if (importedNode.nodeName === "HTML") { - body = importedNode; - } else { - body.appendChild(importedNode); - } - } else { - if (!RETURN_DOM && !SAFE_FOR_TEMPLATES && !WHOLE_DOCUMENT && // eslint-disable-next-line unicorn/prefer-includes - dirty.indexOf("<") === -1) { - return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(dirty) : dirty; - } - body = _initDocument(dirty); - if (!body) { - return RETURN_DOM ? null : RETURN_TRUSTED_TYPE ? emptyHTML : ""; - } - } - if (body && FORCE_BODY) { - _forceRemove(body.firstChild); - } - const nodeIterator = _createNodeIterator(IN_PLACE ? dirty : body); - while (currentNode = nodeIterator.nextNode()) { - _sanitizeElements(currentNode); - _sanitizeAttributes(currentNode); - if (currentNode.content instanceof DocumentFragment) { - _sanitizeShadowDOM2(currentNode.content); - } - } - if (IN_PLACE) { - return dirty; - } - if (RETURN_DOM) { - if (SAFE_FOR_TEMPLATES) { - body.normalize(); - let html3 = body.innerHTML; - arrayForEach([MUSTACHE_EXPR2, ERB_EXPR2, TMPLIT_EXPR2], (expr) => { - html3 = stringReplace(html3, expr, " "); - }); - body.innerHTML = html3; - } - if (RETURN_DOM_FRAGMENT) { - returnNode = createDocumentFragment.call(body.ownerDocument); - while (body.firstChild) { - returnNode.appendChild(body.firstChild); - } - } else { - returnNode = body; - } - if (ALLOWED_ATTR.shadowroot || ALLOWED_ATTR.shadowrootmode) { - returnNode = importNode.call(originalDocument, returnNode, true); - } - return returnNode; - } - let serializedHTML = WHOLE_DOCUMENT ? body.outerHTML : body.innerHTML; - if (WHOLE_DOCUMENT && ALLOWED_TAGS["!doctype"] && body.ownerDocument && body.ownerDocument.doctype && body.ownerDocument.doctype.name && regExpTest(DOCTYPE_NAME, body.ownerDocument.doctype.name)) { - serializedHTML = "\n" + serializedHTML; - } - if (SAFE_FOR_TEMPLATES) { - arrayForEach([MUSTACHE_EXPR2, ERB_EXPR2, TMPLIT_EXPR2], (expr) => { - serializedHTML = stringReplace(serializedHTML, expr, " "); - }); - } - return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(serializedHTML) : serializedHTML; - }; - DOMPurify.setConfig = function() { - let cfg = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {}; - _parseConfig(cfg); - SET_CONFIG = true; - }; - DOMPurify.clearConfig = function() { - CONFIG = null; - SET_CONFIG = false; - }; - DOMPurify.isValidAttribute = function(tag3, attr, value) { - if (!CONFIG) { - _parseConfig({}); - } - const lcTag = transformCaseFunc(tag3); - const lcName = transformCaseFunc(attr); - return _isValidAttribute(lcTag, lcName, value); - }; - DOMPurify.addHook = function(entryPoint, hookFunction) { - if (typeof hookFunction !== "function") { - return; - } - arrayPush(hooks[entryPoint], hookFunction); - }; - DOMPurify.removeHook = function(entryPoint, hookFunction) { - if (hookFunction !== void 0) { - const index2 = arrayLastIndexOf(hooks[entryPoint], hookFunction); - return index2 === -1 ? void 0 : arraySplice(hooks[entryPoint], index2, 1)[0]; - } - return arrayPop(hooks[entryPoint]); - }; - DOMPurify.removeHooks = function(entryPoint) { - hooks[entryPoint] = []; - }; - DOMPurify.removeAllHooks = function() { - hooks = _createHooksMap(); - }; - return DOMPurify; -} -var purify = createDOMPurify(); - -// server/src/routes/assets.ts -import { JSDOM } from "jsdom"; -var SVG_CONTENT_TYPE2 = "image/svg+xml"; -var ALLOWED_COMPANY_LOGO_CONTENT_TYPES = /* @__PURE__ */ new Set([ - "image/png", - "image/jpeg", - "image/jpg", - "image/webp", - "image/gif", - SVG_CONTENT_TYPE2 -]); -function sanitizeSvgBuffer(input) { - const raw = input.toString("utf8").trim(); - if (!raw) return null; - const baseDom = new JSDOM(""); - const domPurify = purify( - baseDom.window - ); - domPurify.addHook("uponSanitizeAttribute", (_node, data2) => { - const attrName = data2.attrName.toLowerCase(); - const attrValue = (data2.attrValue ?? "").trim(); - if (attrName.startsWith("on")) { - data2.keepAttr = false; - return; - } - if ((attrName === "href" || attrName === "xlink:href") && attrValue && !attrValue.startsWith("#")) { - data2.keepAttr = false; - } - }); - let parsedDom = null; - try { - const sanitized = domPurify.sanitize(raw, { - USE_PROFILES: { svg: true, svgFilters: true, html: false }, - FORBID_TAGS: ["script", "foreignObject"], - FORBID_CONTENTS: ["script", "foreignObject"], - RETURN_TRUSTED_TYPE: false - }); - parsedDom = new JSDOM(sanitized, { contentType: SVG_CONTENT_TYPE2 }); - const document2 = parsedDom.window.document; - const root = document2.documentElement; - if (!root || root.tagName.toLowerCase() !== "svg") return null; - for (const el of Array.from(root.querySelectorAll("script, foreignObject"))) { - el.remove(); - } - for (const el of Array.from(root.querySelectorAll("*"))) { - for (const attr of Array.from(el.attributes)) { - const attrName = attr.name.toLowerCase(); - const attrValue = attr.value.trim(); - if (attrName.startsWith("on")) { - el.removeAttribute(attr.name); - continue; - } - if ((attrName === "href" || attrName === "xlink:href") && attrValue && !attrValue.startsWith("#")) { - el.removeAttribute(attr.name); - } - } - } - const output = root.outerHTML.trim(); - if (!output || !/^]/i.test(output)) return null; - return Buffer.from(output, "utf8"); - } catch { - return null; - } finally { - parsedDom?.window.close(); - baseDom.window.close(); - } -} -function assetRoutes(db, storage) { - const router2 = (0, import_express20.Router)(); - const svc = assetService(db); - const assetUpload = (0, import_multer2.default)({ - storage: import_multer2.default.memoryStorage(), - limits: { fileSize: MAX_ATTACHMENT_BYTES, files: 1 } - }); - const companyLogoUpload = (0, import_multer2.default)({ - storage: import_multer2.default.memoryStorage(), - limits: { fileSize: MAX_ATTACHMENT_BYTES, files: 1 } - }); - async function runSingleFileUpload(upload, req, res) { - await new Promise((resolve4, reject) => { - upload.single("file")(req, res, (err) => { - if (err) reject(err); - else resolve4(); - }); - }); - } - router2.post("/companies/:companyId/assets/images", async (req, res) => { - const companyId = req.params.companyId; - assertCompanyAccess(req, companyId); - try { - await runSingleFileUpload(assetUpload, req, res); - } catch (err) { - if (err instanceof import_multer2.default.MulterError) { - if (err.code === "LIMIT_FILE_SIZE") { - res.status(422).json({ error: `File exceeds ${MAX_ATTACHMENT_BYTES} bytes` }); - return; - } - res.status(400).json({ error: err.message }); - return; - } - throw err; - } - const file2 = req.file; - if (!file2) { - res.status(400).json({ error: "Missing file field 'file'" }); - return; - } - const parsedMeta = createAssetImageMetadataSchema.safeParse(req.body ?? {}); - if (!parsedMeta.success) { - res.status(400).json({ error: "Invalid image metadata", details: parsedMeta.error.issues }); - return; - } - const namespaceSuffix = parsedMeta.data.namespace ?? "general"; - const contentType = (file2.mimetype || "").toLowerCase(); - if (contentType !== SVG_CONTENT_TYPE2 && !isAllowedContentType(contentType)) { - res.status(422).json({ error: `Unsupported file type: ${contentType || "unknown"}` }); - return; - } - let fileBody = file2.buffer; - if (contentType === SVG_CONTENT_TYPE2) { - const sanitized = sanitizeSvgBuffer(file2.buffer); - if (!sanitized || sanitized.length <= 0) { - res.status(422).json({ error: "SVG could not be sanitized" }); - return; - } - fileBody = sanitized; - } - if (fileBody.length <= 0) { - res.status(422).json({ error: "Image is empty" }); - return; - } - const actor = getActorInfo(req); - const stored = await storage.putFile({ - companyId, - namespace: `assets/${namespaceSuffix}`, - originalFilename: file2.originalname || null, - contentType, - body: fileBody - }); - const asset = await svc.create(companyId, { - provider: stored.provider, - objectKey: stored.objectKey, - contentType: stored.contentType, - byteSize: stored.byteSize, - sha256: stored.sha256, - originalFilename: stored.originalFilename, - createdByAgentId: actor.agentId, - createdByUserId: actor.actorType === "user" ? actor.actorId : null - }); - await logActivity(db, { - companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - runId: actor.runId, - action: "asset.created", - entityType: "asset", - entityId: asset.id, - details: { - originalFilename: asset.originalFilename, - contentType: asset.contentType, - byteSize: asset.byteSize - } - }); - res.status(201).json({ - assetId: asset.id, - companyId: asset.companyId, - provider: asset.provider, - objectKey: asset.objectKey, - contentType: asset.contentType, - byteSize: asset.byteSize, - sha256: asset.sha256, - originalFilename: asset.originalFilename, - createdByAgentId: asset.createdByAgentId, - createdByUserId: asset.createdByUserId, - createdAt: asset.createdAt, - updatedAt: asset.updatedAt, - contentPath: `/api/assets/${asset.id}/content` - }); - }); - router2.post("/companies/:companyId/logo", async (req, res) => { - const companyId = req.params.companyId; - assertCompanyAccess(req, companyId); - try { - await runSingleFileUpload(companyLogoUpload, req, res); - } catch (err) { - if (err instanceof import_multer2.default.MulterError) { - if (err.code === "LIMIT_FILE_SIZE") { - res.status(422).json({ error: `Image exceeds ${MAX_ATTACHMENT_BYTES} bytes` }); - return; - } - res.status(400).json({ error: err.message }); - return; - } - throw err; - } - const file2 = req.file; - if (!file2) { - res.status(400).json({ error: "Missing file field 'file'" }); - return; - } - const contentType = (file2.mimetype || "").toLowerCase(); - if (!ALLOWED_COMPANY_LOGO_CONTENT_TYPES.has(contentType)) { - res.status(422).json({ error: `Unsupported image type: ${contentType || "unknown"}` }); - return; - } - let fileBody = file2.buffer; - if (contentType === SVG_CONTENT_TYPE2) { - const sanitized = sanitizeSvgBuffer(file2.buffer); - if (!sanitized || sanitized.length <= 0) { - res.status(422).json({ error: "SVG could not be sanitized" }); - return; - } - fileBody = sanitized; - } - if (fileBody.length <= 0) { - res.status(422).json({ error: "Image is empty" }); - return; - } - const actor = getActorInfo(req); - const stored = await storage.putFile({ - companyId, - namespace: "assets/companies", - originalFilename: file2.originalname || null, - contentType, - body: fileBody - }); - const asset = await svc.create(companyId, { - provider: stored.provider, - objectKey: stored.objectKey, - contentType: stored.contentType, - byteSize: stored.byteSize, - sha256: stored.sha256, - originalFilename: stored.originalFilename, - createdByAgentId: actor.agentId, - createdByUserId: actor.actorType === "user" ? actor.actorId : null - }); - await logActivity(db, { - companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - runId: actor.runId, - action: "asset.created", - entityType: "asset", - entityId: asset.id, - details: { - originalFilename: asset.originalFilename, - contentType: asset.contentType, - byteSize: asset.byteSize, - namespace: "assets/companies" - } - }); - res.status(201).json({ - assetId: asset.id, - companyId: asset.companyId, - provider: asset.provider, - objectKey: asset.objectKey, - contentType: asset.contentType, - byteSize: asset.byteSize, - sha256: asset.sha256, - originalFilename: asset.originalFilename, - createdByAgentId: asset.createdByAgentId, - createdByUserId: asset.createdByUserId, - createdAt: asset.createdAt, - updatedAt: asset.updatedAt, - contentPath: `/api/assets/${asset.id}/content` - }); - }); - router2.get("/assets/:assetId/content", async (req, res, next) => { - const assetId = req.params.assetId; - const asset = await svc.getById(assetId); - if (!asset) { - res.status(404).json({ error: "Asset not found" }); - return; - } - assertCompanyAccess(req, asset.companyId); - const object2 = await storage.getObject(asset.companyId, asset.objectKey); - const responseContentType = asset.contentType || object2.contentType || "application/octet-stream"; - res.setHeader("Content-Type", responseContentType); - res.setHeader("Content-Length", String(asset.byteSize || object2.contentLength || 0)); - res.setHeader("Cache-Control", "private, max-age=60"); - res.setHeader("X-Content-Type-Options", "nosniff"); - if (responseContentType === SVG_CONTENT_TYPE2) { - res.setHeader("Content-Security-Policy", "sandbox; default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'"); - } - const filename = asset.originalFilename ?? "asset"; - res.setHeader("Content-Disposition", `inline; filename="${filename.replaceAll('"', "")}"`); - object2.stream.on("error", (err) => { - next(err); - }); - object2.stream.pipe(res); - }); - return router2; -} - -// server/src/routes/access.ts -var import_express21 = __toESM(require_express2(), 1); -init_drizzle_orm(); -init_src2(); -import { - createHash as createHash16, - generateKeyPairSync as generateKeyPairSync2, - randomBytes as randomBytes5, - timingSafeEqual as timingSafeEqual3 -} from "node:crypto"; -import fs36 from "node:fs"; -import path45 from "node:path"; -import { fileURLToPath as fileURLToPath16 } from "node:url"; - -// server/src/board-claim.ts -init_drizzle_orm(); -init_src2(); -import { randomBytes as randomBytes4 } from "node:crypto"; -var LOCAL_BOARD_USER_ID = "local-board"; -var CLAIM_TTL_MS = 1e3 * 60 * 60 * 24; -var activeChallenge = null; -function createChallenge(now2 = /* @__PURE__ */ new Date()) { - return { - token: randomBytes4(24).toString("hex"), - code: randomBytes4(12).toString("hex"), - createdAt: now2, - expiresAt: new Date(now2.getTime() + CLAIM_TTL_MS), - claimedAt: null, - claimedByUserId: null - }; -} -function getChallengeStatus(token, code) { - if (!activeChallenge) return "invalid"; - if (activeChallenge.token !== token) return "invalid"; - if (activeChallenge.code !== (code ?? "")) return "invalid"; - if (activeChallenge.claimedAt) return "claimed"; - if (activeChallenge.expiresAt.getTime() <= Date.now()) return "expired"; - return "available"; -} -async function initializeBoardClaimChallenge(db, opts) { - if (opts.deploymentMode !== "authenticated") { - activeChallenge = null; - return; - } - const admins = await db.select({ userId: instanceUserRoles.userId }).from(instanceUserRoles).where(eq(instanceUserRoles.role, "instance_admin")); - const onlyLocalBoardAdmin = admins.length === 1 && admins[0]?.userId === LOCAL_BOARD_USER_ID; - if (!onlyLocalBoardAdmin) { - activeChallenge = null; - return; - } - if (!activeChallenge || activeChallenge.expiresAt.getTime() <= Date.now() || activeChallenge.claimedAt) { - activeChallenge = createChallenge(); - } -} -function inspectBoardClaimChallenge(token, code) { - const status = getChallengeStatus(token, code); - return { - status, - requiresSignIn: true, - expiresAt: activeChallenge?.expiresAt?.toISOString() ?? null, - claimedByUserId: activeChallenge?.claimedByUserId ?? null - }; -} -async function claimBoardOwnership(db, opts) { - const status = getChallengeStatus(opts.token, opts.code); - if (status !== "available") return { status }; - await db.transaction(async (tx) => { - const existingTargetAdmin = await tx.select({ id: instanceUserRoles.id }).from(instanceUserRoles).where(and(eq(instanceUserRoles.userId, opts.userId), eq(instanceUserRoles.role, "instance_admin"))).then((rows) => rows[0] ?? null); - if (!existingTargetAdmin) { - await tx.insert(instanceUserRoles).values({ - userId: opts.userId, - role: "instance_admin" - }); - } - await tx.delete(instanceUserRoles).where(and(eq(instanceUserRoles.userId, LOCAL_BOARD_USER_ID), eq(instanceUserRoles.role, "instance_admin"))); - const allCompanies = await tx.select({ id: companies.id }).from(companies); - for (const company of allCompanies) { - const existing = await tx.select({ id: companyMemberships.id, status: companyMemberships.status }).from(companyMemberships).where( - and( - eq(companyMemberships.companyId, company.id), - eq(companyMemberships.principalType, "user"), - eq(companyMemberships.principalId, opts.userId) - ) - ).then((rows) => rows[0] ?? null); - if (!existing) { - await tx.insert(companyMemberships).values({ - companyId: company.id, - principalType: "user", - principalId: opts.userId, - status: "active", - membershipRole: "owner" - }); - continue; - } - if (existing.status !== "active") { - await tx.update(companyMemberships).set({ status: "active", membershipRole: "owner", updatedAt: /* @__PURE__ */ new Date() }).where(eq(companyMemberships.id, existing.id)); - } - } - }); - if (activeChallenge && activeChallenge.token === opts.token) { - activeChallenge.claimedAt = /* @__PURE__ */ new Date(); - activeChallenge.claimedByUserId = opts.userId; - } - return { status: "claimed", claimedByUserId: opts.userId }; -} - -// server/src/routes/access.ts -function hashToken3(token) { - return createHash16("sha256").update(token).digest("hex"); -} -var INVITE_TOKEN_PREFIX = "pcp_invite_"; -var INVITE_TOKEN_ALPHABET = "abcdefghijklmnopqrstuvwxyz0123456789"; -var INVITE_TOKEN_SUFFIX_LENGTH = 8; -var INVITE_TOKEN_MAX_RETRIES = 5; -var COMPANY_INVITE_TTL_MS = 10 * 60 * 1e3; -function createInviteToken() { - const bytes = randomBytes5(INVITE_TOKEN_SUFFIX_LENGTH); - let suffix = ""; - for (let idx = 0; idx < INVITE_TOKEN_SUFFIX_LENGTH; idx += 1) { - suffix += INVITE_TOKEN_ALPHABET[bytes[idx] % INVITE_TOKEN_ALPHABET.length]; - } - return `${INVITE_TOKEN_PREFIX}${suffix}`; -} -function createClaimSecret() { - return `pcp_claim_${randomBytes5(24).toString("hex")}`; -} -function companyInviteExpiresAt(nowMs = Date.now()) { - return new Date(nowMs + COMPANY_INVITE_TTL_MS); -} -function tokenHashesMatch2(left, right) { - const leftBytes = Buffer.from(left, "utf8"); - const rightBytes = Buffer.from(right, "utf8"); - return leftBytes.length === rightBytes.length && timingSafeEqual3(leftBytes, rightBytes); -} -function requestBaseUrl(req) { - const forwardedProto = req.header("x-forwarded-proto"); - const proto = forwardedProto?.split(",")[0]?.trim() || req.protocol || "http"; - const host = req.header("x-forwarded-host")?.split(",")[0]?.trim() || req.header("host"); - if (!host) return ""; - return `${proto}://${host}`; -} -function buildCliAuthApprovalPath(challengeId, token) { - return `/cli-auth/${challengeId}?token=${encodeURIComponent(token)}`; -} -function readSkillMarkdown(skillName) { - const normalized = skillName.trim().toLowerCase(); - if (normalized !== "taskcore" && normalized !== "taskcore-create-agent" && normalized !== "taskcore-create-plugin" && normalized !== "para-memory-files") - return null; - const moduleDir = path45.dirname(fileURLToPath16(import.meta.url)); - const candidates = [ - path45.resolve(moduleDir, "../../skills", normalized, "SKILL.md"), - // published: dist/routes/ -> /skills/ - path45.resolve(process.cwd(), "skills", normalized, "SKILL.md"), - // cwd (e.g. monorepo root) - path45.resolve(moduleDir, "../../../skills", normalized, "SKILL.md") - // dev: src/routes/ -> repo root/skills/ - ]; - for (const skillPath of candidates) { - try { - return fs36.readFileSync(skillPath, "utf8"); - } catch { - } - } - return null; -} -function resolveTaskcoreSkillsDir2() { - const moduleDir = path45.dirname(fileURLToPath16(import.meta.url)); - const candidates = [ - path45.resolve(moduleDir, "../../skills"), - // published - path45.resolve(process.cwd(), "skills"), - // cwd (monorepo root) - path45.resolve(moduleDir, "../../../skills") - // dev - ]; - for (const candidate of candidates) { - try { - if (fs36.statSync(candidate).isDirectory()) return candidate; - } catch { - } - } - return null; -} -function parseSkillFrontmatter2(markdown) { - const match = markdown.match(/^---\n([\s\S]*?)\n---/); - if (!match) return { description: "" }; - const yaml = match[1]; - const descMatch = yaml.match( - /^description:\s*(?:>\s*\n((?:\s{2,}[^\n]*\n?)+)|[|]\s*\n((?:\s{2,}[^\n]*\n?)+)|["']?(.*?)["']?\s*$)/m - ); - if (!descMatch) return { description: "" }; - const raw = descMatch[1] ?? descMatch[2] ?? descMatch[3] ?? ""; - return { - description: raw.split("\n").map((l5) => l5.trim()).filter(Boolean).join(" ").trim() - }; -} -function listAvailableSkills() { - const homeDir = process.env.HOME || process.env.USERPROFILE || ""; - const claudeSkillsDir = path45.join(homeDir, ".claude", "skills"); - const taskcoreSkillsDir = resolveTaskcoreSkillsDir2(); - const taskcoreSkillNames = /* @__PURE__ */ new Set(); - if (taskcoreSkillsDir) { - try { - for (const entry of fs36.readdirSync(taskcoreSkillsDir, { withFileTypes: true })) { - if (entry.isDirectory()) taskcoreSkillNames.add(entry.name); - } - } catch { - } - } - const skills = []; - try { - const entries2 = fs36.readdirSync(claudeSkillsDir, { withFileTypes: true }); - for (const entry of entries2) { - if (!entry.isDirectory() && !entry.isSymbolicLink()) continue; - if (entry.name.startsWith(".")) continue; - const skillMdPath = path45.join(claudeSkillsDir, entry.name, "SKILL.md"); - let description = ""; - try { - const md = fs36.readFileSync(skillMdPath, "utf8"); - description = parseSkillFrontmatter2(md).description; - } catch { - } - skills.push({ - name: entry.name, - description, - isTaskcoreManaged: taskcoreSkillNames.has(entry.name) - }); - } - } catch { - } - skills.sort((a5, b6) => a5.name.localeCompare(b6.name)); - return skills; -} -function toJoinRequestResponse(row) { - const { claimSecretHash: _claimSecretHash, ...safe } = row; - return safe; -} -function isPlainObject4(value) { - return typeof value === "object" && value !== null && !Array.isArray(value); -} -function isLoopbackHost5(hostname3) { - const value = hostname3.trim().toLowerCase(); - return value === "localhost" || value === "127.0.0.1" || value === "::1"; -} -function normalizeHostname(value) { - if (!value) return null; - const trimmed = value.trim(); - if (!trimmed) return null; - if (trimmed.startsWith("[")) { - const end = trimmed.indexOf("]"); - return end > 1 ? trimmed.slice(1, end).toLowerCase() : trimmed.toLowerCase(); - } - const firstColon = trimmed.indexOf(":"); - if (firstColon > -1) return trimmed.slice(0, firstColon).toLowerCase(); - return trimmed.toLowerCase(); -} -function normalizeHeaderValue(value, depth = 0) { - const direct = nonEmptyTrimmedString(value); - if (direct) return direct; - if (!isPlainObject4(value) || depth >= 3) return null; - const candidateKeys = [ - "value", - "token", - "secret", - "apiKey", - "api_key", - "auth", - "authToken", - "auth_token", - "accessToken", - "access_token", - "authorization", - "bearer", - "header", - "raw", - "text", - "string" - ]; - for (const key of candidateKeys) { - if (!Object.prototype.hasOwnProperty.call(value, key)) continue; - const normalized = normalizeHeaderValue( - value[key], - depth + 1 - ); - if (normalized) return normalized; - } - const entries2 = Object.entries(value); - if (entries2.length === 1) { - const [singleKey, singleValue] = entries2[0]; - const normalizedKey = singleKey.trim().toLowerCase(); - if (normalizedKey !== "type" && normalizedKey !== "version" && normalizedKey !== "secretid" && normalizedKey !== "secret_id") { - const normalized = normalizeHeaderValue(singleValue, depth + 1); - if (normalized) return normalized; - } - } - return null; -} -function extractHeaderEntries(input) { - if (isPlainObject4(input)) { - return Object.entries(input); - } - if (!Array.isArray(input)) { - return []; - } - const entries2 = []; - for (const item of input) { - if (Array.isArray(item)) { - const key = nonEmptyTrimmedString(item[0]); - if (!key) continue; - entries2.push([key, item[1]]); - continue; - } - if (!isPlainObject4(item)) continue; - const mapped = item; - const explicitKey = nonEmptyTrimmedString(mapped.key) ?? nonEmptyTrimmedString(mapped.name) ?? nonEmptyTrimmedString(mapped.header); - if (explicitKey) { - const explicitValue = Object.prototype.hasOwnProperty.call( - mapped, - "value" - ) ? mapped.value : Object.prototype.hasOwnProperty.call(mapped, "token") ? mapped.token : Object.prototype.hasOwnProperty.call(mapped, "secret") ? mapped.secret : mapped; - entries2.push([explicitKey, explicitValue]); - continue; - } - const singleEntry = Object.entries(mapped); - if (singleEntry.length === 1) { - entries2.push(singleEntry[0]); - } - } - return entries2; -} -function normalizeHeaderMap(input) { - const entries2 = extractHeaderEntries(input); - if (entries2.length === 0) return void 0; - const out = {}; - for (const [key, value] of entries2) { - const normalizedValue = normalizeHeaderValue(value); - if (!normalizedValue) continue; - const trimmedKey = key.trim(); - const trimmedValue = normalizedValue.trim(); - if (!trimmedKey || !trimmedValue) continue; - out[trimmedKey] = trimmedValue; - } - return Object.keys(out).length > 0 ? out : void 0; -} -function nonEmptyTrimmedString(value) { - if (typeof value !== "string") return null; - const trimmed = value.trim(); - return trimmed.length > 0 ? trimmed : null; -} -function headerMapHasKeyIgnoreCase(headers, targetKey) { - const normalizedTarget = targetKey.trim().toLowerCase(); - return Object.keys(headers).some( - (key) => key.trim().toLowerCase() === normalizedTarget - ); -} -function headerMapGetIgnoreCase3(headers, targetKey) { - const normalizedTarget = targetKey.trim().toLowerCase(); - const key = Object.keys(headers).find( - (candidate) => candidate.trim().toLowerCase() === normalizedTarget - ); - if (!key) return null; - const value = headers[key]; - return typeof value === "string" ? value : null; -} -function tokenFromAuthorizationHeader(rawHeader) { - const trimmed = nonEmptyTrimmedString(rawHeader); - if (!trimmed) return null; - const bearerMatch = trimmed.match(/^bearer\s+(.+)$/i); - if (bearerMatch?.[1]) { - return nonEmptyTrimmedString(bearerMatch[1]); - } - return trimmed; -} -function parseBooleanLike(value) { - if (typeof value === "boolean") return value; - if (typeof value !== "string") return null; - const normalized = value.trim().toLowerCase(); - if (normalized === "true" || normalized === "1") return true; - if (normalized === "false" || normalized === "0") return false; - return null; -} -function generateEd25519PrivateKeyPem() { - const generated = generateKeyPairSync2("ed25519"); - return generated.privateKey.export({ type: "pkcs8", format: "pem" }).toString(); -} -function buildJoinDefaultsPayloadForAccept(input) { - if (input.adapterType !== "openclaw_gateway") { - return input.defaultsPayload; - } - const merged = isPlainObject4(input.defaultsPayload) ? { ...input.defaultsPayload } : {}; - if (!nonEmptyTrimmedString(merged.taskcoreApiUrl)) { - const legacyTaskcoreApiUrl = nonEmptyTrimmedString(input.taskcoreApiUrl); - if (legacyTaskcoreApiUrl) merged.taskcoreApiUrl = legacyTaskcoreApiUrl; - } - const mergedHeaders = normalizeHeaderMap(merged.headers) ?? {}; - const inboundOpenClawAuthHeader = nonEmptyTrimmedString( - input.inboundOpenClawAuthHeader - ); - const inboundOpenClawTokenHeader = nonEmptyTrimmedString( - input.inboundOpenClawTokenHeader - ); - if (inboundOpenClawTokenHeader && !headerMapHasKeyIgnoreCase(mergedHeaders, "x-openclaw-token")) { - mergedHeaders["x-openclaw-token"] = inboundOpenClawTokenHeader; - } - if (inboundOpenClawAuthHeader && !headerMapHasKeyIgnoreCase(mergedHeaders, "x-openclaw-auth")) { - mergedHeaders["x-openclaw-auth"] = inboundOpenClawAuthHeader; - } - if (Object.keys(mergedHeaders).length > 0) { - merged.headers = mergedHeaders; - } else { - delete merged.headers; - } - const discoveredToken = headerMapGetIgnoreCase3(mergedHeaders, "x-openclaw-token") ?? headerMapGetIgnoreCase3(mergedHeaders, "x-openclaw-auth") ?? tokenFromAuthorizationHeader( - headerMapGetIgnoreCase3(mergedHeaders, "authorization") - ); - if (discoveredToken && !headerMapHasKeyIgnoreCase(mergedHeaders, "x-openclaw-token")) { - mergedHeaders["x-openclaw-token"] = discoveredToken; - } - return Object.keys(merged).length > 0 ? merged : null; -} -function mergeJoinDefaultsPayloadForReplay(existingDefaultsPayload, nextDefaultsPayload) { - if (!isPlainObject4(existingDefaultsPayload) && !isPlainObject4(nextDefaultsPayload)) { - return nextDefaultsPayload ?? existingDefaultsPayload; - } - if (!isPlainObject4(existingDefaultsPayload)) { - return nextDefaultsPayload; - } - if (!isPlainObject4(nextDefaultsPayload)) { - return existingDefaultsPayload; - } - const merged = { - ...existingDefaultsPayload, - ...nextDefaultsPayload - }; - const existingHeaders = normalizeHeaderMap( - existingDefaultsPayload.headers - ); - const nextHeaders = normalizeHeaderMap( - nextDefaultsPayload.headers - ); - if (existingHeaders || nextHeaders) { - merged.headers = { - ...existingHeaders ?? {}, - ...nextHeaders ?? {} - }; - } else if (Object.prototype.hasOwnProperty.call(merged, "headers")) { - delete merged.headers; - } - return merged; -} -function canReplayOpenClawGatewayInviteAccept(input) { - if (input.requestType !== "agent" || input.adapterType !== "openclaw_gateway") { - return false; - } - if (!input.existingJoinRequest) { - return false; - } - if (input.existingJoinRequest.requestType !== "agent" || input.existingJoinRequest.adapterType !== "openclaw_gateway") { - return false; - } - return input.existingJoinRequest.status === "pending_approval" || input.existingJoinRequest.status === "approved"; -} -function summarizeSecretForLog(value) { - const trimmed = nonEmptyTrimmedString(value); - if (!trimmed) return null; - return { - present: true, - length: trimmed.length, - sha256Prefix: hashToken3(trimmed).slice(0, 12) - }; -} -function summarizeOpenClawGatewayDefaultsForLog(defaultsPayload) { - const defaults = isPlainObject4(defaultsPayload) ? defaultsPayload : null; - const headers = defaults ? normalizeHeaderMap(defaults.headers) : void 0; - const gatewayTokenValue = headers ? headerMapGetIgnoreCase3(headers, "x-openclaw-token") ?? headerMapGetIgnoreCase3(headers, "x-openclaw-auth") ?? tokenFromAuthorizationHeader( - headerMapGetIgnoreCase3(headers, "authorization") - ) : null; - return { - present: Boolean(defaults), - keys: defaults ? Object.keys(defaults).sort() : [], - url: defaults ? nonEmptyTrimmedString(defaults.url) : null, - taskcoreApiUrl: defaults ? nonEmptyTrimmedString(defaults.taskcoreApiUrl) : null, - headerKeys: headers ? Object.keys(headers).sort() : [], - sessionKeyStrategy: defaults ? nonEmptyTrimmedString(defaults.sessionKeyStrategy) : null, - disableDeviceAuth: defaults ? parseBooleanLike(defaults.disableDeviceAuth) : null, - waitTimeoutMs: defaults && typeof defaults.waitTimeoutMs === "number" ? defaults.waitTimeoutMs : null, - devicePrivateKeyPem: defaults ? summarizeSecretForLog(defaults.devicePrivateKeyPem) : null, - gatewayToken: summarizeSecretForLog(gatewayTokenValue) - }; -} -function normalizeAgentDefaultsForJoin(input) { - const fatalErrors = []; - const diagnostics = []; - if (input.adapterType !== "openclaw_gateway") { - const normalized2 = isPlainObject4(input.defaultsPayload) ? input.defaultsPayload : null; - return { normalized: normalized2, diagnostics, fatalErrors }; - } - if (!isPlainObject4(input.defaultsPayload)) { - diagnostics.push({ - code: "openclaw_gateway_defaults_missing", - level: "warn", - message: "No OpenClaw gateway config was provided in agentDefaultsPayload.", - hint: "Include agentDefaultsPayload.url and headers.x-openclaw-token for OpenClaw gateway joins." - }); - fatalErrors.push( - "agentDefaultsPayload is required for adapterType=openclaw_gateway" - ); - return { - normalized: null, - diagnostics, - fatalErrors - }; - } - const defaults = input.defaultsPayload; - const normalized = {}; - let gatewayUrl = null; - const rawGatewayUrl = nonEmptyTrimmedString(defaults.url); - if (!rawGatewayUrl) { - diagnostics.push({ - code: "openclaw_gateway_url_missing", - level: "warn", - message: "OpenClaw gateway URL is missing.", - hint: "Set agentDefaultsPayload.url to ws:// or wss:// gateway URL." - }); - fatalErrors.push("agentDefaultsPayload.url is required"); - } else { - try { - gatewayUrl = new URL(rawGatewayUrl); - if (gatewayUrl.protocol !== "ws:" && gatewayUrl.protocol !== "wss:") { - diagnostics.push({ - code: "openclaw_gateway_url_protocol", - level: "warn", - message: `OpenClaw gateway URL must use ws:// or wss:// (got ${gatewayUrl.protocol}).` - }); - fatalErrors.push( - "agentDefaultsPayload.url must use ws:// or wss:// for openclaw_gateway" - ); - } else { - normalized.url = gatewayUrl.toString(); - diagnostics.push({ - code: "openclaw_gateway_url_configured", - level: "info", - message: `Gateway endpoint set to ${gatewayUrl.toString()}` - }); - } - } catch { - diagnostics.push({ - code: "openclaw_gateway_url_invalid", - level: "warn", - message: `Invalid OpenClaw gateway URL: ${rawGatewayUrl}` - }); - fatalErrors.push("agentDefaultsPayload.url is not a valid URL"); - } - } - const headers = normalizeHeaderMap(defaults.headers) ?? {}; - const gatewayToken = headerMapGetIgnoreCase3(headers, "x-openclaw-token") ?? headerMapGetIgnoreCase3(headers, "x-openclaw-auth") ?? tokenFromAuthorizationHeader(headerMapGetIgnoreCase3(headers, "authorization")); - if (gatewayToken && !headerMapHasKeyIgnoreCase(headers, "x-openclaw-token")) { - headers["x-openclaw-token"] = gatewayToken; - } - if (Object.keys(headers).length > 0) { - normalized.headers = headers; - } - if (!gatewayToken) { - diagnostics.push({ - code: "openclaw_gateway_auth_header_missing", - level: "warn", - message: "Gateway auth token is missing from agent defaults.", - hint: "Set agentDefaultsPayload.headers.x-openclaw-token (or legacy x-openclaw-auth)." - }); - fatalErrors.push( - "agentDefaultsPayload.headers.x-openclaw-token (or x-openclaw-auth) is required" - ); - } else if (gatewayToken.trim().length < 16) { - diagnostics.push({ - code: "openclaw_gateway_auth_header_too_short", - level: "warn", - message: `Gateway auth token appears too short (${gatewayToken.trim().length} chars).`, - hint: "Use the full gateway auth token from ~/.openclaw/openclaw.json (typically long random string)." - }); - fatalErrors.push( - "agentDefaultsPayload.headers.x-openclaw-token is too short; expected a full gateway token" - ); - } else { - diagnostics.push({ - code: "openclaw_gateway_auth_header_configured", - level: "info", - message: "Gateway auth token configured." - }); - } - if (isPlainObject4(defaults.payloadTemplate)) { - normalized.payloadTemplate = defaults.payloadTemplate; - } - const parsedDisableDeviceAuth = parseBooleanLike(defaults.disableDeviceAuth); - const disableDeviceAuth = parsedDisableDeviceAuth === true; - if (parsedDisableDeviceAuth !== null) { - normalized.disableDeviceAuth = parsedDisableDeviceAuth; - } - const configuredDevicePrivateKeyPem = nonEmptyTrimmedString( - defaults.devicePrivateKeyPem - ); - if (configuredDevicePrivateKeyPem) { - normalized.devicePrivateKeyPem = configuredDevicePrivateKeyPem; - diagnostics.push({ - code: "openclaw_gateway_device_key_configured", - level: "info", - message: "Gateway device key configured. Pairing approvals should persist for this agent." - }); - } else if (!disableDeviceAuth) { - try { - normalized.devicePrivateKeyPem = generateEd25519PrivateKeyPem(); - diagnostics.push({ - code: "openclaw_gateway_device_key_generated", - level: "info", - message: "Generated persistent gateway device key for this join. Pairing approvals should persist for this agent." - }); - } catch (err) { - diagnostics.push({ - code: "openclaw_gateway_device_key_generate_failed", - level: "warn", - message: `Failed to generate gateway device key: ${err instanceof Error ? err.message : String(err)}`, - hint: "Set agentDefaultsPayload.devicePrivateKeyPem explicitly or set disableDeviceAuth=true." - }); - fatalErrors.push( - "Failed to generate gateway device key. Set devicePrivateKeyPem or disableDeviceAuth=true." - ); - } - } - const waitTimeoutMs = typeof defaults.waitTimeoutMs === "number" && Number.isFinite(defaults.waitTimeoutMs) ? Math.floor(defaults.waitTimeoutMs) : typeof defaults.waitTimeoutMs === "string" ? Number.parseInt(defaults.waitTimeoutMs.trim(), 10) : NaN; - if (Number.isFinite(waitTimeoutMs) && waitTimeoutMs > 0) { - normalized.waitTimeoutMs = waitTimeoutMs; - } - const timeoutSec = typeof defaults.timeoutSec === "number" && Number.isFinite(defaults.timeoutSec) ? Math.floor(defaults.timeoutSec) : typeof defaults.timeoutSec === "string" ? Number.parseInt(defaults.timeoutSec.trim(), 10) : NaN; - if (Number.isFinite(timeoutSec) && timeoutSec > 0) { - normalized.timeoutSec = timeoutSec; - } - const sessionKeyStrategy = nonEmptyTrimmedString(defaults.sessionKeyStrategy); - if (sessionKeyStrategy === "fixed" || sessionKeyStrategy === "issue" || sessionKeyStrategy === "run") { - normalized.sessionKeyStrategy = sessionKeyStrategy; - } - const sessionKey = nonEmptyTrimmedString(defaults.sessionKey); - if (sessionKey) { - normalized.sessionKey = sessionKey; - } - const role = nonEmptyTrimmedString(defaults.role); - if (role) { - normalized.role = role; - } - if (Array.isArray(defaults.scopes)) { - const scopes = defaults.scopes.filter((entry) => typeof entry === "string").map((entry) => entry.trim()).filter(Boolean); - if (scopes.length > 0) { - normalized.scopes = scopes; - } - } - const rawTaskcoreApiUrl = typeof defaults.taskcoreApiUrl === "string" ? defaults.taskcoreApiUrl.trim() : ""; - if (rawTaskcoreApiUrl) { - try { - const parsedTaskcoreApiUrl = new URL(rawTaskcoreApiUrl); - if (parsedTaskcoreApiUrl.protocol !== "http:" && parsedTaskcoreApiUrl.protocol !== "https:") { - diagnostics.push({ - code: "openclaw_gateway_taskcore_api_url_protocol", - level: "warn", - message: `taskcoreApiUrl must use http:// or https:// (got ${parsedTaskcoreApiUrl.protocol}).` - }); - } else { - normalized.taskcoreApiUrl = parsedTaskcoreApiUrl.toString(); - diagnostics.push({ - code: "openclaw_gateway_taskcore_api_url_configured", - level: "info", - message: `taskcoreApiUrl set to ${parsedTaskcoreApiUrl.toString()}` - }); - } - } catch { - diagnostics.push({ - code: "openclaw_gateway_taskcore_api_url_invalid", - level: "warn", - message: `Invalid taskcoreApiUrl: ${rawTaskcoreApiUrl}` - }); - } - } - return { normalized, diagnostics, fatalErrors }; -} -function toInviteSummaryResponse(req, token, invite, companyName = null) { - const baseUrl = requestBaseUrl(req); - const onboardingPath = `/api/invites/${token}/onboarding`; - const onboardingTextPath = `/api/invites/${token}/onboarding.txt`; - const inviteMessage = extractInviteMessage(invite); - return { - id: invite.id, - companyId: invite.companyId, - companyName, - inviteType: invite.inviteType, - allowedJoinTypes: invite.allowedJoinTypes, - expiresAt: invite.expiresAt, - onboardingPath, - onboardingUrl: baseUrl ? `${baseUrl}${onboardingPath}` : onboardingPath, - onboardingTextPath, - onboardingTextUrl: baseUrl ? `${baseUrl}${onboardingTextPath}` : onboardingTextPath, - skillIndexPath: "/api/skills/index", - skillIndexUrl: baseUrl ? `${baseUrl}/api/skills/index` : "/api/skills/index", - inviteMessage - }; -} -function buildOnboardingDiscoveryDiagnostics(input) { - const diagnostics = []; - let apiHost = null; - if (input.apiBaseUrl) { - try { - apiHost = normalizeHostname(new URL(input.apiBaseUrl).hostname); - } catch { - apiHost = null; - } - } - const bindHost = normalizeHostname(input.bindHost); - const allowSet = new Set( - input.allowedHostnames.map((entry) => normalizeHostname(entry)).filter((entry) => Boolean(entry)) - ); - if (apiHost && isLoopbackHost5(apiHost)) { - diagnostics.push({ - code: "openclaw_onboarding_api_loopback", - level: "warn", - message: "Onboarding URL resolves to loopback hostname. Remote OpenClaw agents cannot reach localhost on your Taskcore host.", - hint: "Use a reachable hostname/IP (for example Tailscale hostname, Docker host alias, or public domain)." - }); - } - if (input.deploymentMode === "authenticated" && input.deploymentExposure === "private" && (!bindHost || isLoopbackHost5(bindHost))) { - diagnostics.push({ - code: "openclaw_onboarding_private_loopback_bind", - level: "warn", - message: "Taskcore is bound to loopback in authenticated/private mode.", - hint: "Use a reachable private bind mode such as `pnpm dev --bind lan` or `pnpm dev --bind tailnet` for private-network onboarding." - }); - } - if (input.deploymentMode === "authenticated" && input.deploymentExposure === "private" && apiHost && !isLoopbackHost5(apiHost) && allowSet.size > 0 && !allowSet.has(apiHost)) { - diagnostics.push({ - code: "openclaw_onboarding_private_host_not_allowed", - level: "warn", - message: `Onboarding host "${apiHost}" is not in allowed hostnames for authenticated/private mode.`, - hint: `Run pnpm taskcore allowed-hostname ${apiHost}` - }); - } - return diagnostics; -} -function buildOnboardingConnectionCandidates(input) { - let base = null; - try { - if (input.apiBaseUrl) { - base = new URL(input.apiBaseUrl); - } - } catch { - base = null; - } - const protocol = base?.protocol ?? "http:"; - const port = base?.port ? `:${base.port}` : ""; - const candidates = /* @__PURE__ */ new Set(); - if (base) { - candidates.add(base.origin); - } - const bindHost = normalizeHostname(input.bindHost); - if (bindHost && !isLoopbackHost5(bindHost)) { - candidates.add(`${protocol}//${bindHost}${port}`); - } - for (const rawHost of input.allowedHostnames) { - const host = normalizeHostname(rawHost); - if (!host) continue; - candidates.add(`${protocol}//${host}${port}`); - } - if (base && isLoopbackHost5(base.hostname)) { - candidates.add(`${protocol}//host.docker.internal${port}`); - } - return Array.from(candidates); -} -function buildInviteOnboardingManifest(req, token, invite, opts) { - const baseUrl = requestBaseUrl(req); - const skillPath = "/api/skills/taskcore"; - const skillUrl = baseUrl ? `${baseUrl}${skillPath}` : skillPath; - const registrationEndpointPath = `/api/invites/${token}/accept`; - const registrationEndpointUrl = baseUrl ? `${baseUrl}${registrationEndpointPath}` : registrationEndpointPath; - const onboardingTextPath = `/api/invites/${token}/onboarding.txt`; - const onboardingTextUrl = baseUrl ? `${baseUrl}${onboardingTextPath}` : onboardingTextPath; - const discoveryDiagnostics = buildOnboardingDiscoveryDiagnostics({ - apiBaseUrl: baseUrl, - deploymentMode: opts.deploymentMode, - deploymentExposure: opts.deploymentExposure, - bindHost: opts.bindHost, - allowedHostnames: opts.allowedHostnames - }); - const connectionCandidates = buildOnboardingConnectionCandidates({ - apiBaseUrl: baseUrl, - bindHost: opts.bindHost, - allowedHostnames: opts.allowedHostnames - }); - return { - invite: toInviteSummaryResponse( - req, - token, - invite, - opts.companyName ?? null - ), - onboarding: { - instructions: "Join as an OpenClaw Gateway agent, save your one-time claim secret, wait for board approval, then claim your API key. Save the claim response token to ~/.openclaw/workspace/taskcore-claimed-api-key.json and load TASKCORE_API_KEY from that file before starting heartbeat loops. You MUST submit adapterType='openclaw_gateway', set agentDefaultsPayload.url to your ws:// or wss:// OpenClaw gateway endpoint, and include agentDefaultsPayload.headers.x-openclaw-token (or legacy x-openclaw-auth).", - inviteMessage: extractInviteMessage(invite), - recommendedAdapterType: "openclaw_gateway", - requiredFields: { - requestType: "agent", - agentName: "Display name for this agent", - adapterType: "Use 'openclaw_gateway' for OpenClaw Gateway agents", - capabilities: "Optional capability summary", - agentDefaultsPayload: "Adapter config for OpenClaw gateway. MUST include url (ws:// or wss://) and headers.x-openclaw-token (or legacy x-openclaw-auth). Optional fields: taskcoreApiUrl, waitTimeoutMs, sessionKeyStrategy, sessionKey, role, scopes, disableDeviceAuth, devicePrivateKeyPem." - }, - registrationEndpoint: { - method: "POST", - path: registrationEndpointPath, - url: registrationEndpointUrl - }, - claimEndpointTemplate: { - method: "POST", - path: "/api/join-requests/{requestId}/claim-api-key", - body: { - claimSecret: "one-time claim secret returned when the join request is created" - } - }, - connectivity: { - deploymentMode: opts.deploymentMode, - deploymentExposure: opts.deploymentExposure, - bindHost: opts.bindHost, - allowedHostnames: opts.allowedHostnames, - connectionCandidates, - diagnostics: discoveryDiagnostics, - guidance: opts.deploymentMode === "authenticated" && opts.deploymentExposure === "private" ? "If OpenClaw runs on another machine, ensure the Taskcore hostname is reachable and allowed via `pnpm taskcore allowed-hostname `." : "Ensure OpenClaw can reach this Taskcore API base URL for invite, claim, and skill bootstrap calls." - }, - textInstructions: { - path: onboardingTextPath, - url: onboardingTextUrl, - contentType: "text/plain" - }, - skill: { - name: "taskcore", - path: skillPath, - url: skillUrl, - installPath: "~/.openclaw/skills/taskcore/SKILL.md" - } - } - }; -} -function buildInviteOnboardingTextDocument(req, token, invite, opts) { - const manifest = buildInviteOnboardingManifest(req, token, invite, opts); - const onboarding = manifest.onboarding; - const diagnostics = Array.isArray(onboarding.connectivity?.diagnostics) ? onboarding.connectivity.diagnostics : []; - const lines = []; - const appendBlock = (block) => { - const trimmed = block.replace(/^\n/, "").replace(/\n\s*$/, ""); - const lineIndentation = trimmed.split("\n").filter((line3) => line3.trim().length > 0).map((line3) => line3.match(/^(\s*)/)?.[0].length ?? 0); - const minIndent = lineIndentation.length > 0 ? Math.min(...lineIndentation) : 0; - for (const line3 of trimmed.split("\n")) { - lines.push(line3.slice(minIndent)); - } - }; - appendBlock(` - # Taskcore OpenClaw Gateway Onboarding - - This document is meant to be readable by both humans and agents. - - ## Invite - - inviteType: ${invite.inviteType} - - allowedJoinTypes: ${invite.allowedJoinTypes} - - expiresAt: ${invite.expiresAt.toISOString()} - `); - if (manifest.invite.companyName) { - lines.push(`- companyName: ${manifest.invite.companyName}`); - } - if (onboarding.inviteMessage) { - appendBlock(` - ## Message from inviter - ${onboarding.inviteMessage} - `); - } - appendBlock(` - ## Step 0 - - Get the OpenClaw gateway auth token (THIS MUST BE SENT) - Token lives in: - - ~/.openclaw/openclaw.json -> gateway.auth.token - Extract: - - TOKEN="$(node -p 'require(process.env.HOME+"/.openclaw/openclaw.json").gateway.auth.token')" - test -n "$TOKEN" || (echo "Missing TOKEN" && exit 1) - test "\${#TOKEN}" -ge 16 || (echo "Gateway token unexpectedly short (\${#TOKEN})" && exit 1) - - 3) IMPORTANT: Don't accidentally drop the token when generating JSON - If you build JSON with Node, pass the token explicitly (argv), don't rely on an un-exported env var. - - Safe payload build looks sort of like this (substitute where necessary): - - BODY="$(node -e ' - const token = process.argv[1]; - if (!token) process.exit(2); - const body = { - requestType: "agent", - agentName: "OpenClaw", - adapterType: "openclaw_gateway", - capabilities: "OpenClaw agent adapter", - agentDefaultsPayload: { - url: "ws://127.0.0.1:18789", - taskcoreApiUrl: "http://host.docker.internal:3100", - headers: { "x-openclaw-token": token }, - waitTimeoutMs: 120000, - sessionKeyStrategy: "issue", - role: "operator", - scopes: ["operator.admin"] - } - }; - process.stdout.write(JSON.stringify(body)); - ' "$TOKEN")" - - ## Step 1: Submit agent join request - ${onboarding.registrationEndpoint.method} ${onboarding.registrationEndpoint.url} - - IMPORTANT: You MUST include agentDefaultsPayload.headers.x-openclaw-token with your gateway token. - Legacy x-openclaw-auth is also accepted, but x-openclaw-token is preferred. - Use adapterType "openclaw_gateway" and a ws:// or wss:// gateway URL. - Pairing mode requirement: - - Keep device auth enabled (recommended). If devicePrivateKeyPem is omitted, Taskcore generates and persists one during join so pairing approvals are stable. - - You may set disableDeviceAuth=true only for special environments that cannot support pairing. - - First run may return "pairing required" once; approve the pending pairing request in OpenClaw, then retry. - Do NOT use /v1/responses or /hooks/* in this gateway join flow. - - Body (JSON): - { - "requestType": "agent", - "agentName": "My OpenClaw Agent", - "adapterType": "openclaw_gateway", - "capabilities": "Optional summary", - "agentDefaultsPayload": { - "url": "wss://your-openclaw-gateway.example", - "taskcoreApiUrl": "https://taskcore-hostname-your-agent-can-reach:3100", - "headers": { "x-openclaw-token": "replace-me" }, - "waitTimeoutMs": 120000, - "sessionKeyStrategy": "issue", - "role": "operator", - "scopes": ["operator.admin"] - } - } - - Expected response includes: - - request id - - one-time claimSecret - - claimApiKeyPath - - ## Step 2: Wait for board approval - The board approves the join request in Taskcore before key claim is allowed. - - ## Step 3: Claim API key (one-time) - ${onboarding.claimEndpointTemplate.method} /api/join-requests/{requestId}/claim-api-key - - Body (JSON): - { - "claimSecret": "" - } - - On successful claim, save the full JSON response to: - - - ~/.openclaw/workspace/taskcore-claimed-api-key.json - chmod 600 ~/.openclaw/workspace/taskcore-claimed-api-key.json - - And set the TASKCORE_API_KEY and TASKCORE_API_URL in your environment variables as specified here: - https://docs.openclaw.ai/help/environment - - e.g. - - { - env: { - TASKCORE_API_KEY: "...", - TASKCORE_API_URL: "...", - }, - } - - Then set TASKCORE_API_KEY and TASKCORE_API_URL from the saved token field for every heartbeat run. - - Important: - - claim secrets expire - - claim secrets are single-use - - claim fails before board approval - - ## Step 4: Install Taskcore skill in OpenClaw - GET ${onboarding.skill.url} - Install path: ${onboarding.skill.installPath} - - Be sure to prepend your TASKCORE_API_URL to the top of your skill and note the path to your TASKCORE_API_URL - - ## Text onboarding URL - ${onboarding.textInstructions.url} - - ## Connectivity guidance - ${onboarding.connectivity?.guidance ?? "Ensure Taskcore is reachable from your OpenClaw runtime."} - `); - const connectionCandidates = Array.isArray( - onboarding.connectivity?.connectionCandidates - ) ? onboarding.connectivity.connectionCandidates.filter( - (entry) => Boolean(entry) - ) : []; - if (connectionCandidates.length > 0) { - lines.push("## Suggested Taskcore base URLs to try"); - for (const candidate of connectionCandidates) { - lines.push(`- ${candidate}`); - } - appendBlock(` - - Test each candidate with: - - GET /api/health - - set the first reachable candidate as agentDefaultsPayload.taskcoreApiUrl when submitting your join request - - If none are reachable: ask your human operator for a reachable hostname/address and help them update network configuration. - For authenticated/private mode, they may need: - - pnpm taskcore allowed-hostname - - then restart Taskcore and retry onboarding. - `); - } - if (diagnostics.length > 0) { - lines.push("## Connectivity diagnostics"); - for (const diag of diagnostics) { - lines.push(`- [${diag.level}] ${diag.message}`); - if (diag.hint) lines.push(` hint: ${diag.hint}`); - } - } - appendBlock(` - - ## Helpful endpoints - ${onboarding.registrationEndpoint.path} - ${onboarding.claimEndpointTemplate.path} - ${onboarding.skill.path} - ${manifest.invite.onboardingPath} - `); - return `${lines.join("\n")} -`; -} -function extractInviteMessage(invite) { - const rawDefaults = invite.defaultsPayload; - if (!rawDefaults || typeof rawDefaults !== "object" || Array.isArray(rawDefaults)) { - return null; - } - const rawMessage = rawDefaults.agentMessage; - if (typeof rawMessage !== "string") { - return null; - } - const trimmed = rawMessage.trim(); - return trimmed.length ? trimmed : null; -} -function mergeInviteDefaults(defaultsPayload, agentMessage) { - const merged = defaultsPayload && typeof defaultsPayload === "object" ? { ...defaultsPayload } : {}; - if (agentMessage) { - merged.agentMessage = agentMessage; - } - return Object.keys(merged).length ? merged : null; -} -function requestIp(req) { - const forwarded = req.header("x-forwarded-for"); - if (forwarded) { - const first = forwarded.split(",")[0]?.trim(); - if (first) return first; - } - return req.ip || "unknown"; -} -function inviteExpired(invite) { - return invite.expiresAt.getTime() <= Date.now(); -} -function isLocalImplicit(req) { - return req.actor.type === "board" && req.actor.source === "local_implicit"; -} -async function resolveActorEmail(db, req) { - if (isLocalImplicit(req)) return "local@taskcore.local"; - const userId = req.actor.userId; - if (!userId) return null; - const user = await db.select({ email: authUsers.email }).from(authUsers).where(eq(authUsers.id, userId)).then((rows) => rows[0] ?? null); - return user?.email ?? null; -} -function grantsFromDefaults(defaultsPayload, key) { - if (!defaultsPayload || typeof defaultsPayload !== "object") return []; - const scoped = defaultsPayload[key]; - if (!scoped || typeof scoped !== "object") return []; - const grants = scoped.grants; - if (!Array.isArray(grants)) return []; - const validPermissionKeys = new Set(PERMISSION_KEYS); - const result = []; - for (const item of grants) { - if (!item || typeof item !== "object") continue; - const record2 = item; - if (typeof record2.permissionKey !== "string") continue; - if (!validPermissionKeys.has(record2.permissionKey)) continue; - result.push({ - permissionKey: record2.permissionKey, - scope: record2.scope && typeof record2.scope === "object" && !Array.isArray(record2.scope) ? record2.scope : null - }); - } - return result; -} -function agentJoinGrantsFromDefaults(defaultsPayload) { - const grants = grantsFromDefaults(defaultsPayload, "agent"); - if (grants.some((grant) => grant.permissionKey === "tasks:assign")) { - return grants; - } - return [ - ...grants, - { - permissionKey: "tasks:assign", - scope: null - } - ]; -} -function resolveJoinRequestAgentManagerId(candidates) { - const ceoCandidates = candidates.filter( - (candidate) => candidate.role === "ceo" - ); - if (ceoCandidates.length === 0) return null; - const rootCeo = ceoCandidates.find( - (candidate) => candidate.reportsTo === null - ); - return (rootCeo ?? ceoCandidates[0] ?? null)?.id ?? null; -} -function isInviteTokenHashCollisionError(error50) { - const candidates = [ - error50, - error50?.cause ?? null - ]; - for (const candidate of candidates) { - if (!candidate || typeof candidate !== "object") continue; - const code = "code" in candidate && typeof candidate.code === "string" ? candidate.code : null; - const message2 = "message" in candidate && typeof candidate.message === "string" ? candidate.message : ""; - const constraint = "constraint" in candidate && typeof candidate.constraint === "string" ? candidate.constraint : null; - if (code !== "23505") continue; - if (constraint === "invites_token_hash_unique_idx") return true; - if (message2.includes("invites_token_hash_unique_idx")) return true; - } - return false; -} -function isAbortError(error50) { - return error50 instanceof Error && error50.name === "AbortError"; -} -async function probeInviteResolutionTarget(url2, timeoutMs) { - const startedAt = Date.now(); - const controller = new AbortController(); - const timeout = setTimeout(() => controller.abort(), timeoutMs); - try { - const response = await fetch(url2, { - method: "HEAD", - redirect: "manual", - signal: controller.signal - }); - const durationMs = Date.now() - startedAt; - if (response.ok || response.status === 401 || response.status === 403 || response.status === 404 || response.status === 405 || response.status === 422 || response.status === 500 || response.status === 501) { - return { - status: "reachable", - method: "HEAD", - durationMs, - httpStatus: response.status, - message: `Webhook endpoint responded to HEAD with HTTP ${response.status}.` - }; - } - return { - status: "unreachable", - method: "HEAD", - durationMs, - httpStatus: response.status, - message: `Webhook endpoint probe returned HTTP ${response.status}.` - }; - } catch (error50) { - const durationMs = Date.now() - startedAt; - if (isAbortError(error50)) { - return { - status: "timeout", - method: "HEAD", - durationMs, - httpStatus: null, - message: `Webhook endpoint probe timed out after ${timeoutMs}ms.` - }; - } - return { - status: "unreachable", - method: "HEAD", - durationMs, - httpStatus: null, - message: error50 instanceof Error ? error50.message : "Webhook endpoint probe failed." - }; - } finally { - clearTimeout(timeout); - } -} -function accessRoutes(db, opts) { - const router2 = (0, import_express21.Router)(); - const access = accessService(db); - const boardAuth = boardAuthService(db); - const agents2 = agentService(db); - async function assertInstanceAdmin2(req) { - if (req.actor.type !== "board") throw unauthorized(); - if (isLocalImplicit(req)) return; - const allowed2 = await access.isInstanceAdmin(req.actor.userId); - if (!allowed2) throw forbidden("Instance admin required"); - } - router2.get("/board-claim/:token", async (req, res) => { - const token = req.params.token.trim(); - const code = typeof req.query.code === "string" ? req.query.code.trim() : void 0; - if (!token) throw notFound("Board claim challenge not found"); - const challenge = inspectBoardClaimChallenge(token, code); - if (challenge.status === "invalid") - throw notFound("Board claim challenge not found"); - res.json(challenge); - }); - router2.post("/board-claim/:token/claim", async (req, res) => { - const token = req.params.token.trim(); - const code = typeof req.body?.code === "string" ? req.body.code.trim() : void 0; - if (!token) throw notFound("Board claim challenge not found"); - if (!code) throw badRequest("Claim code is required"); - if (req.actor.type !== "board" || req.actor.source !== "session" || !req.actor.userId) { - throw unauthorized("Sign in before claiming board ownership"); - } - const claimed = await claimBoardOwnership(db, { - token, - code, - userId: req.actor.userId - }); - if (claimed.status === "invalid") - throw notFound("Board claim challenge not found"); - if (claimed.status === "expired") - throw conflict( - "Board claim challenge expired. Restart server to generate a new one." - ); - if (claimed.status === "claimed") { - res.json({ - claimed: true, - userId: claimed.claimedByUserId ?? req.actor.userId - }); - return; - } - throw conflict("Board claim challenge is no longer available"); - }); - router2.post( - "/cli-auth/challenges", - validate(createCliAuthChallengeSchema), - async (req, res) => { - const created = await boardAuth.createCliAuthChallenge(req.body); - const approvalPath = buildCliAuthApprovalPath( - created.challenge.id, - created.challengeSecret - ); - const baseUrl = requestBaseUrl(req); - res.status(201).json({ - id: created.challenge.id, - token: created.challengeSecret, - boardApiToken: created.pendingBoardToken, - approvalPath, - approvalUrl: baseUrl ? `${baseUrl}${approvalPath}` : null, - pollPath: `/cli-auth/challenges/${created.challenge.id}`, - expiresAt: created.challenge.expiresAt.toISOString(), - suggestedPollIntervalMs: 1e3 - }); - } - ); - router2.get("/cli-auth/challenges/:id", async (req, res) => { - const id = req.params.id.trim(); - const token = typeof req.query.token === "string" ? req.query.token.trim() : ""; - if (!id || !token) throw notFound("CLI auth challenge not found"); - const challenge = await boardAuth.describeCliAuthChallenge(id, token); - if (!challenge) throw notFound("CLI auth challenge not found"); - const isSignedInBoardUser = req.actor.type === "board" && (req.actor.source === "session" || isLocalImplicit(req)) && Boolean(req.actor.userId); - const canApprove = isSignedInBoardUser && (challenge.requestedAccess !== "instance_admin_required" || isLocalImplicit(req) || Boolean(req.actor.isInstanceAdmin)); - res.json({ - ...challenge, - requiresSignIn: !isSignedInBoardUser, - canApprove, - currentUserId: req.actor.type === "board" ? req.actor.userId ?? null : null - }); - }); - router2.post( - "/cli-auth/challenges/:id/approve", - validate(resolveCliAuthChallengeSchema), - async (req, res) => { - const id = req.params.id.trim(); - if (req.actor.type !== "board" || !req.actor.userId && !isLocalImplicit(req)) { - throw unauthorized("Sign in before approving CLI access"); - } - const userId = req.actor.userId ?? "local-board"; - const approved = await boardAuth.approveCliAuthChallenge( - id, - req.body.token, - userId - ); - if (approved.status === "approved") { - const companyIds = await boardAuth.resolveBoardActivityCompanyIds({ - userId, - requestedCompanyId: approved.challenge.requestedCompanyId, - boardApiKeyId: approved.challenge.boardApiKeyId - }); - for (const companyId of companyIds) { - await logActivity(db, { - companyId, - actorType: "user", - actorId: userId, - action: "board_api_key.created", - entityType: "user", - entityId: userId, - details: { - boardApiKeyId: approved.challenge.boardApiKeyId, - requestedAccess: approved.challenge.requestedAccess, - requestedCompanyId: approved.challenge.requestedCompanyId, - challengeId: approved.challenge.id - } - }); - } - } - res.json({ - approved: approved.status === "approved", - status: approved.status, - userId, - keyId: approved.challenge.boardApiKeyId ?? null, - expiresAt: approved.challenge.expiresAt.toISOString() - }); - } - ); - router2.post( - "/cli-auth/challenges/:id/cancel", - validate(resolveCliAuthChallengeSchema), - async (req, res) => { - const id = req.params.id.trim(); - const cancelled = await boardAuth.cancelCliAuthChallenge(id, req.body.token); - res.json({ - status: cancelled.status, - cancelled: cancelled.status === "cancelled" - }); - } - ); - router2.get("/cli-auth/me", async (req, res) => { - if (req.actor.type !== "board" || !req.actor.userId) { - throw unauthorized("Board authentication required"); - } - const accessSnapshot = await boardAuth.resolveBoardAccess(req.actor.userId); - res.json({ - user: accessSnapshot.user, - userId: req.actor.userId, - isInstanceAdmin: accessSnapshot.isInstanceAdmin, - companyIds: accessSnapshot.companyIds, - source: req.actor.source ?? "none", - keyId: req.actor.source === "board_key" ? req.actor.keyId ?? null : null - }); - }); - router2.post("/cli-auth/revoke-current", async (req, res) => { - if (req.actor.type !== "board" || req.actor.source !== "board_key") { - throw badRequest("Current board API key context is required"); - } - const key = await boardAuth.assertCurrentBoardKey( - req.actor.keyId, - req.actor.userId - ); - await boardAuth.revokeBoardApiKey(key.id); - const companyIds = await boardAuth.resolveBoardActivityCompanyIds({ - userId: key.userId, - boardApiKeyId: key.id - }); - for (const companyId of companyIds) { - await logActivity(db, { - companyId, - actorType: "user", - actorId: key.userId, - action: "board_api_key.revoked", - entityType: "user", - entityId: key.userId, - details: { - boardApiKeyId: key.id, - revokedVia: "cli_auth_logout" - } - }); - } - res.json({ revoked: true, keyId: key.id }); - }); - async function assertCompanyPermission(req, companyId, permissionKey) { - assertCompanyAccess(req, companyId); - if (req.actor.type === "agent") { - if (!req.actor.agentId) throw forbidden(); - const allowed3 = await access.hasPermission( - companyId, - "agent", - req.actor.agentId, - permissionKey - ); - if (!allowed3) throw forbidden("Permission denied"); - return; - } - if (req.actor.type !== "board") throw unauthorized(); - if (isLocalImplicit(req)) return; - const allowed2 = await access.canUser( - companyId, - req.actor.userId, - permissionKey - ); - if (!allowed2) throw forbidden("Permission denied"); - } - async function assertCanGenerateOpenClawInvitePrompt(req, companyId) { - assertCompanyAccess(req, companyId); - if (req.actor.type === "agent") { - if (!req.actor.agentId) throw forbidden("Agent authentication required"); - const actorAgent = await agents2.getById(req.actor.agentId); - if (!actorAgent || actorAgent.companyId !== companyId) { - throw forbidden("Agent key cannot access another company"); - } - if (actorAgent.role !== "ceo") { - throw forbidden("Only CEO agents can generate OpenClaw invite prompts"); - } - return; - } - if (req.actor.type !== "board") throw unauthorized(); - if (isLocalImplicit(req)) return; - const allowed2 = await access.canUser(companyId, req.actor.userId, "users:invite"); - if (!allowed2) throw forbidden("Permission denied"); - } - async function createCompanyInviteForCompany(input) { - const normalizedAgentMessage = typeof input.agentMessage === "string" ? input.agentMessage.trim() || null : null; - const insertValues = { - companyId: input.companyId, - inviteType: "company_join", - allowedJoinTypes: input.allowedJoinTypes, - defaultsPayload: mergeInviteDefaults( - input.defaultsPayload ?? null, - normalizedAgentMessage - ), - expiresAt: companyInviteExpiresAt(), - invitedByUserId: input.req.actor.userId ?? null - }; - let token = null; - let created = null; - for (let attempt = 0; attempt < INVITE_TOKEN_MAX_RETRIES; attempt += 1) { - const candidateToken = createInviteToken(); - try { - const row = await db.insert(invites).values({ - ...insertValues, - tokenHash: hashToken3(candidateToken) - }).returning().then((rows) => rows[0]); - token = candidateToken; - created = row; - break; - } catch (error50) { - if (!isInviteTokenHashCollisionError(error50)) { - throw error50; - } - } - } - if (!token || !created) { - throw conflict("Failed to generate a unique invite token. Please retry."); - } - return { token, created, normalizedAgentMessage }; - } - async function getInviteCompanyName(companyId) { - if (!companyId) return null; - const company = await db.select({ name: companies.name }).from(companies).where(eq(companies.id, companyId)).then((rows) => rows[0] ?? null); - return company?.name ?? null; - } - router2.get("/skills/available", (_req, res) => { - res.json({ skills: listAvailableSkills() }); - }); - router2.get("/skills/index", (_req, res) => { - res.json({ - skills: [ - { name: "taskcore", path: "/api/skills/taskcore" }, - { - name: "para-memory-files", - path: "/api/skills/para-memory-files" - }, - { - name: "taskcore-create-agent", - path: "/api/skills/taskcore-create-agent" - } - ] - }); - }); - router2.get("/skills/:skillName", (req, res) => { - const skillName = req.params.skillName.trim().toLowerCase(); - const markdown = readSkillMarkdown(skillName); - if (!markdown) throw notFound("Skill not found"); - res.type("text/markdown").send(markdown); - }); - router2.post( - "/companies/:companyId/invites", - validate(createCompanyInviteSchema), - async (req, res) => { - const companyId = req.params.companyId; - await assertCompanyPermission(req, companyId, "users:invite"); - const { token, created, normalizedAgentMessage } = await createCompanyInviteForCompany({ - req, - companyId, - allowedJoinTypes: req.body.allowedJoinTypes, - defaultsPayload: req.body.defaultsPayload ?? null, - agentMessage: req.body.agentMessage ?? null - }); - await logActivity(db, { - companyId, - actorType: req.actor.type === "agent" ? "agent" : "user", - actorId: req.actor.type === "agent" ? req.actor.agentId ?? "unknown-agent" : req.actor.userId ?? "board", - action: "invite.created", - entityType: "invite", - entityId: created.id, - details: { - inviteType: created.inviteType, - allowedJoinTypes: created.allowedJoinTypes, - expiresAt: created.expiresAt.toISOString(), - hasAgentMessage: Boolean(normalizedAgentMessage) - } - }); - const companyName = await getInviteCompanyName(created.companyId); - const inviteSummary = toInviteSummaryResponse( - req, - token, - created, - companyName - ); - res.status(201).json({ - ...created, - token, - inviteUrl: `/invite/${token}`, - companyName, - onboardingTextPath: inviteSummary.onboardingTextPath, - onboardingTextUrl: inviteSummary.onboardingTextUrl, - inviteMessage: inviteSummary.inviteMessage - }); - } - ); - router2.post( - "/companies/:companyId/openclaw/invite-prompt", - validate(createOpenClawInvitePromptSchema), - async (req, res) => { - const companyId = req.params.companyId; - await assertCanGenerateOpenClawInvitePrompt(req, companyId); - const { token, created, normalizedAgentMessage } = await createCompanyInviteForCompany({ - req, - companyId, - allowedJoinTypes: "agent", - defaultsPayload: null, - agentMessage: req.body.agentMessage ?? null - }); - await logActivity(db, { - companyId, - actorType: req.actor.type === "agent" ? "agent" : "user", - actorId: req.actor.type === "agent" ? req.actor.agentId ?? "unknown-agent" : req.actor.userId ?? "board", - action: "invite.openclaw_prompt_created", - entityType: "invite", - entityId: created.id, - details: { - inviteType: created.inviteType, - allowedJoinTypes: created.allowedJoinTypes, - expiresAt: created.expiresAt.toISOString(), - hasAgentMessage: Boolean(normalizedAgentMessage) - } - }); - const companyName = await getInviteCompanyName(created.companyId); - const inviteSummary = toInviteSummaryResponse( - req, - token, - created, - companyName - ); - res.status(201).json({ - ...created, - token, - inviteUrl: `/invite/${token}`, - companyName, - onboardingTextPath: inviteSummary.onboardingTextPath, - onboardingTextUrl: inviteSummary.onboardingTextUrl, - inviteMessage: inviteSummary.inviteMessage - }); - } - ); - router2.get("/invites/:token", async (req, res) => { - const token = req.params.token.trim(); - if (!token) throw notFound("Invite not found"); - const invite = await db.select().from(invites).where(eq(invites.tokenHash, hashToken3(token))).then((rows) => rows[0] ?? null); - if (!invite || invite.revokedAt || invite.acceptedAt || inviteExpired(invite)) { - throw notFound("Invite not found"); - } - const companyName = await getInviteCompanyName(invite.companyId); - res.json(toInviteSummaryResponse(req, token, invite, companyName)); - }); - router2.get("/invites/:token/onboarding", async (req, res) => { - const token = req.params.token.trim(); - if (!token) throw notFound("Invite not found"); - const invite = await db.select().from(invites).where(eq(invites.tokenHash, hashToken3(token))).then((rows) => rows[0] ?? null); - if (!invite || invite.revokedAt || inviteExpired(invite)) { - throw notFound("Invite not found"); - } - const companyName = await getInviteCompanyName(invite.companyId); - res.json(buildInviteOnboardingManifest(req, token, invite, { - ...opts, - companyName - })); - }); - router2.get("/invites/:token/onboarding.txt", async (req, res) => { - const token = req.params.token.trim(); - if (!token) throw notFound("Invite not found"); - const invite = await db.select().from(invites).where(eq(invites.tokenHash, hashToken3(token))).then((rows) => rows[0] ?? null); - if (!invite || invite.revokedAt || inviteExpired(invite)) { - throw notFound("Invite not found"); - } - const companyName = await getInviteCompanyName(invite.companyId); - res.type("text/plain; charset=utf-8").send( - buildInviteOnboardingTextDocument(req, token, invite, { - ...opts, - companyName - }) - ); - }); - router2.get("/invites/:token/test-resolution", async (req, res) => { - const token = req.params.token.trim(); - if (!token) throw notFound("Invite not found"); - const invite = await db.select().from(invites).where(eq(invites.tokenHash, hashToken3(token))).then((rows) => rows[0] ?? null); - if (!invite || invite.revokedAt || inviteExpired(invite)) { - throw notFound("Invite not found"); - } - const rawUrl = typeof req.query.url === "string" ? req.query.url.trim() : ""; - if (!rawUrl) throw badRequest("url query parameter is required"); - let target; - try { - target = new URL(rawUrl); - } catch { - throw badRequest("url must be an absolute http(s) URL"); - } - if (target.protocol !== "http:" && target.protocol !== "https:") { - throw badRequest("url must use http or https"); - } - const parsedTimeoutMs = typeof req.query.timeoutMs === "string" ? Number(req.query.timeoutMs) : NaN; - const timeoutMs = Number.isFinite(parsedTimeoutMs) ? Math.max(1e3, Math.min(15e3, Math.floor(parsedTimeoutMs))) : 5e3; - const probe = await probeInviteResolutionTarget(target, timeoutMs); - res.json({ - inviteId: invite.id, - testResolutionPath: `/api/invites/${token}/test-resolution`, - requestedUrl: target.toString(), - timeoutMs, - ...probe - }); - }); - router2.post( - "/invites/:token/accept", - validate(acceptInviteSchema), - async (req, res) => { - const token = req.params.token.trim(); - if (!token) throw notFound("Invite not found"); - const invite = await db.select().from(invites).where(eq(invites.tokenHash, hashToken3(token))).then((rows) => rows[0] ?? null); - if (!invite || invite.revokedAt || inviteExpired(invite)) { - throw notFound("Invite not found"); - } - const inviteAlreadyAccepted = Boolean(invite.acceptedAt); - const existingJoinRequestForInvite = inviteAlreadyAccepted ? await db.select().from(joinRequests).where(eq(joinRequests.inviteId, invite.id)).then((rows) => rows[0] ?? null) : null; - if (invite.inviteType === "bootstrap_ceo") { - if (inviteAlreadyAccepted) throw notFound("Invite not found"); - if (req.body.requestType !== "human") { - throw badRequest("Bootstrap invite requires human request type"); - } - if (req.actor.type !== "board" || !req.actor.userId && !isLocalImplicit(req)) { - throw unauthorized( - "Authenticated user required for bootstrap acceptance" - ); - } - const userId = req.actor.userId ?? "local-board"; - const existingAdmin = await access.isInstanceAdmin(userId); - if (!existingAdmin) { - await access.promoteInstanceAdmin(userId); - } - const updatedInvite = await db.update(invites).set({ acceptedAt: /* @__PURE__ */ new Date(), updatedAt: /* @__PURE__ */ new Date() }).where(eq(invites.id, invite.id)).returning().then((rows) => rows[0] ?? invite); - res.status(202).json({ - inviteId: updatedInvite.id, - inviteType: updatedInvite.inviteType, - bootstrapAccepted: true, - userId - }); - return; - } - const requestType = req.body.requestType; - const companyId = invite.companyId; - if (!companyId) throw conflict("Invite is missing company scope"); - if (invite.allowedJoinTypes !== "both" && invite.allowedJoinTypes !== requestType) { - throw badRequest(`Invite does not allow ${requestType} joins`); - } - if (requestType === "human" && req.actor.type !== "board") { - throw unauthorized( - "Human invite acceptance requires authenticated user" - ); - } - if (requestType === "human" && !req.actor.userId && !isLocalImplicit(req)) { - throw unauthorized("Authenticated user is required"); - } - if (requestType === "agent" && !req.body.agentName) { - if (!inviteAlreadyAccepted || !existingJoinRequestForInvite?.agentName) { - throw badRequest("agentName is required for agent join requests"); - } - } - const adapterType = req.body.adapterType ?? null; - if (inviteAlreadyAccepted && !canReplayOpenClawGatewayInviteAccept({ - requestType, - adapterType, - existingJoinRequest: existingJoinRequestForInvite - })) { - throw notFound("Invite not found"); - } - const replayJoinRequestId = inviteAlreadyAccepted ? existingJoinRequestForInvite?.id ?? null : null; - if (inviteAlreadyAccepted && !replayJoinRequestId) { - throw conflict("Join request not found"); - } - const replayMergedDefaults = inviteAlreadyAccepted ? mergeJoinDefaultsPayloadForReplay( - existingJoinRequestForInvite?.agentDefaultsPayload ?? null, - req.body.agentDefaultsPayload ?? null - ) : req.body.agentDefaultsPayload ?? null; - const gatewayDefaultsPayload = requestType === "agent" ? buildJoinDefaultsPayloadForAccept({ - adapterType, - defaultsPayload: replayMergedDefaults, - taskcoreApiUrl: req.body.taskcoreApiUrl ?? null, - inboundOpenClawAuthHeader: req.header("x-openclaw-auth") ?? null, - inboundOpenClawTokenHeader: req.header("x-openclaw-token") ?? null - }) : null; - const joinDefaults = requestType === "agent" ? normalizeAgentDefaultsForJoin({ - adapterType, - defaultsPayload: gatewayDefaultsPayload, - deploymentMode: opts.deploymentMode, - deploymentExposure: opts.deploymentExposure, - bindHost: opts.bindHost, - allowedHostnames: opts.allowedHostnames - }) : { - normalized: null, - diagnostics: [], - fatalErrors: [] - }; - if (requestType === "agent" && joinDefaults.fatalErrors.length > 0) { - throw badRequest(joinDefaults.fatalErrors.join("; ")); - } - if (requestType === "agent" && adapterType === "openclaw_gateway") { - logger.info( - { - inviteId: invite.id, - joinRequestDiagnostics: joinDefaults.diagnostics.map((diag) => ({ - code: diag.code, - level: diag.level - })), - normalizedAgentDefaults: summarizeOpenClawGatewayDefaultsForLog( - joinDefaults.normalized - ) - }, - "invite accept normalized OpenClaw gateway defaults" - ); - } - const claimSecret = requestType === "agent" && !inviteAlreadyAccepted ? createClaimSecret() : null; - const claimSecretHash = claimSecret ? hashToken3(claimSecret) : null; - const claimSecretExpiresAt = claimSecret ? new Date(Date.now() + 7 * 24 * 60 * 60 * 1e3) : null; - const actorEmail = requestType === "human" ? await resolveActorEmail(db, req) : null; - const created = !inviteAlreadyAccepted ? await db.transaction(async (tx) => { - await tx.update(invites).set({ acceptedAt: /* @__PURE__ */ new Date(), updatedAt: /* @__PURE__ */ new Date() }).where( - and( - eq(invites.id, invite.id), - isNull(invites.acceptedAt), - isNull(invites.revokedAt) - ) - ); - const row = await tx.insert(joinRequests).values({ - inviteId: invite.id, - companyId, - requestType, - status: "pending_approval", - requestIp: requestIp(req), - requestingUserId: requestType === "human" ? req.actor.userId ?? "local-board" : null, - requestEmailSnapshot: requestType === "human" ? actorEmail : null, - agentName: requestType === "agent" ? req.body.agentName : null, - adapterType: requestType === "agent" ? adapterType : null, - capabilities: requestType === "agent" ? req.body.capabilities ?? null : null, - agentDefaultsPayload: requestType === "agent" ? joinDefaults.normalized : null, - claimSecretHash, - claimSecretExpiresAt - }).returning().then((rows) => rows[0]); - return row; - }) : await db.update(joinRequests).set({ - requestIp: requestIp(req), - agentName: requestType === "agent" ? req.body.agentName ?? existingJoinRequestForInvite?.agentName ?? null : null, - capabilities: requestType === "agent" ? req.body.capabilities ?? existingJoinRequestForInvite?.capabilities ?? null : null, - adapterType: requestType === "agent" ? adapterType : null, - agentDefaultsPayload: requestType === "agent" ? joinDefaults.normalized : null, - updatedAt: /* @__PURE__ */ new Date() - }).where(eq(joinRequests.id, replayJoinRequestId)).returning().then((rows) => rows[0]); - if (!created) { - throw conflict("Join request not found"); - } - if (inviteAlreadyAccepted && requestType === "agent" && adapterType === "openclaw_gateway" && created.status === "approved" && created.createdAgentId) { - const existingAgent = await agents2.getById(created.createdAgentId); - if (!existingAgent) { - throw conflict("Approved join request agent not found"); - } - const existingAdapterConfig = isPlainObject4(existingAgent.adapterConfig) ? existingAgent.adapterConfig : {}; - const nextAdapterConfig = { - ...existingAdapterConfig, - ...joinDefaults.normalized ?? {} - }; - const updatedAgent = await agents2.update(created.createdAgentId, { - adapterType, - adapterConfig: nextAdapterConfig - }); - if (!updatedAgent) { - throw conflict("Approved join request agent not found"); - } - await logActivity(db, { - companyId, - actorType: req.actor.type === "agent" ? "agent" : "user", - actorId: req.actor.type === "agent" ? req.actor.agentId ?? "invite-agent" : req.actor.userId ?? "board", - action: "agent.updated_from_join_replay", - entityType: "agent", - entityId: updatedAgent.id, - details: { inviteId: invite.id, joinRequestId: created.id } - }); - } - if (requestType === "agent" && adapterType === "openclaw_gateway") { - const expectedDefaults = summarizeOpenClawGatewayDefaultsForLog( - joinDefaults.normalized - ); - const persistedDefaults = summarizeOpenClawGatewayDefaultsForLog( - created.agentDefaultsPayload - ); - const missingPersistedFields = []; - if (expectedDefaults.url && !persistedDefaults.url) - missingPersistedFields.push("url"); - if (expectedDefaults.taskcoreApiUrl && !persistedDefaults.taskcoreApiUrl) { - missingPersistedFields.push("taskcoreApiUrl"); - } - if (expectedDefaults.gatewayToken && !persistedDefaults.gatewayToken) { - missingPersistedFields.push("headers.x-openclaw-token"); - } - if (expectedDefaults.devicePrivateKeyPem && !persistedDefaults.devicePrivateKeyPem) { - missingPersistedFields.push("devicePrivateKeyPem"); - } - if (expectedDefaults.headerKeys.length > 0 && persistedDefaults.headerKeys.length === 0) { - missingPersistedFields.push("headers"); - } - logger.info( - { - inviteId: invite.id, - joinRequestId: created.id, - joinRequestStatus: created.status, - expectedDefaults, - persistedDefaults, - diagnostics: joinDefaults.diagnostics.map((diag) => ({ - code: diag.code, - level: diag.level, - message: diag.message, - hint: diag.hint ?? null - })) - }, - "invite accept persisted OpenClaw gateway join request" - ); - if (missingPersistedFields.length > 0) { - logger.warn( - { - inviteId: invite.id, - joinRequestId: created.id, - missingPersistedFields - }, - "invite accept detected missing persisted OpenClaw gateway defaults" - ); - } - } - await logActivity(db, { - companyId, - actorType: req.actor.type === "agent" ? "agent" : "user", - actorId: req.actor.type === "agent" ? req.actor.agentId ?? "invite-agent" : req.actor.userId ?? (requestType === "agent" ? "invite-anon" : "board"), - action: inviteAlreadyAccepted ? "join.request_replayed" : "join.requested", - entityType: "join_request", - entityId: created.id, - details: { - requestType, - requestIp: created.requestIp, - inviteReplay: inviteAlreadyAccepted - } - }); - const response = toJoinRequestResponse(created); - if (claimSecret) { - const companyName = await getInviteCompanyName(invite.companyId); - const onboardingManifest = buildInviteOnboardingManifest( - req, - token, - invite, - { - ...opts, - companyName - } - ); - res.status(202).json({ - ...response, - claimSecret, - claimApiKeyPath: `/api/join-requests/${created.id}/claim-api-key`, - onboarding: onboardingManifest.onboarding, - diagnostics: joinDefaults.diagnostics - }); - return; - } - res.status(202).json({ - ...response, - ...joinDefaults.diagnostics.length > 0 ? { diagnostics: joinDefaults.diagnostics } : {} - }); - } - ); - router2.post("/invites/:inviteId/revoke", async (req, res) => { - const id = req.params.inviteId; - const invite = await db.select().from(invites).where(eq(invites.id, id)).then((rows) => rows[0] ?? null); - if (!invite) throw notFound("Invite not found"); - if (invite.inviteType === "bootstrap_ceo") { - await assertInstanceAdmin2(req); - } else { - if (!invite.companyId) throw conflict("Invite is missing company scope"); - await assertCompanyPermission(req, invite.companyId, "users:invite"); - } - if (invite.acceptedAt) throw conflict("Invite already consumed"); - if (invite.revokedAt) return res.json(invite); - const revoked = await db.update(invites).set({ revokedAt: /* @__PURE__ */ new Date(), updatedAt: /* @__PURE__ */ new Date() }).where(eq(invites.id, id)).returning().then((rows) => rows[0]); - if (invite.companyId) { - await logActivity(db, { - companyId: invite.companyId, - actorType: req.actor.type === "agent" ? "agent" : "user", - actorId: req.actor.type === "agent" ? req.actor.agentId ?? "unknown-agent" : req.actor.userId ?? "board", - action: "invite.revoked", - entityType: "invite", - entityId: id - }); - } - res.json(revoked); - }); - router2.get("/companies/:companyId/join-requests", async (req, res) => { - const companyId = req.params.companyId; - await assertCompanyPermission(req, companyId, "joins:approve"); - const query = listJoinRequestsQuerySchema.parse(req.query); - const all = await db.select().from(joinRequests).where(eq(joinRequests.companyId, companyId)).orderBy(desc(joinRequests.createdAt)); - const filtered = all.filter((row) => { - if (query.status && row.status !== query.status) return false; - if (query.requestType && row.requestType !== query.requestType) - return false; - return true; - }); - res.json(filtered.map(toJoinRequestResponse)); - }); - router2.post( - "/companies/:companyId/join-requests/:requestId/approve", - async (req, res) => { - const companyId = req.params.companyId; - const requestId = req.params.requestId; - await assertCompanyPermission(req, companyId, "joins:approve"); - const existing = await db.select().from(joinRequests).where( - and( - eq(joinRequests.companyId, companyId), - eq(joinRequests.id, requestId) - ) - ).then((rows) => rows[0] ?? null); - if (!existing) throw notFound("Join request not found"); - if (existing.status !== "pending_approval") - throw conflict("Join request is not pending"); - const invite = await db.select().from(invites).where(eq(invites.id, existing.inviteId)).then((rows) => rows[0] ?? null); - if (!invite) throw notFound("Invite not found"); - let createdAgentId = existing.createdAgentId ?? null; - if (existing.requestType === "human") { - if (!existing.requestingUserId) - throw conflict("Join request missing user identity"); - await access.ensureMembership( - companyId, - "user", - existing.requestingUserId, - "member", - "active" - ); - const grants = grantsFromDefaults( - invite.defaultsPayload, - "human" - ); - await access.setPrincipalGrants( - companyId, - "user", - existing.requestingUserId, - grants, - req.actor.userId ?? null - ); - } else { - const existingAgents = await agents2.list(companyId); - const managerId = resolveJoinRequestAgentManagerId(existingAgents); - if (!managerId) { - throw conflict( - "Join request cannot be approved because this company has no active CEO" - ); - } - const agentName = deduplicateAgentName( - existing.agentName ?? "New Agent", - existingAgents.map((a5) => ({ - id: a5.id, - name: a5.name, - status: a5.status - })) - ); - const created = await agents2.create(companyId, { - name: agentName, - role: "general", - title: null, - status: "idle", - reportsTo: managerId, - capabilities: existing.capabilities ?? null, - adapterType: existing.adapterType ?? "process", - adapterConfig: existing.agentDefaultsPayload && typeof existing.agentDefaultsPayload === "object" ? existing.agentDefaultsPayload : {}, - runtimeConfig: {}, - budgetMonthlyCents: 0, - spentMonthlyCents: 0, - permissions: {}, - lastHeartbeatAt: null, - metadata: null - }); - createdAgentId = created.id; - await access.ensureMembership( - companyId, - "agent", - created.id, - "member", - "active" - ); - const grants = agentJoinGrantsFromDefaults( - invite.defaultsPayload - ); - await access.setPrincipalGrants( - companyId, - "agent", - created.id, - grants, - req.actor.userId ?? null - ); - } - const approved = await db.update(joinRequests).set({ - status: "approved", - approvedByUserId: req.actor.userId ?? (isLocalImplicit(req) ? "local-board" : null), - approvedAt: /* @__PURE__ */ new Date(), - createdAgentId, - updatedAt: /* @__PURE__ */ new Date() - }).where(eq(joinRequests.id, requestId)).returning().then((rows) => rows[0]); - await logActivity(db, { - companyId, - actorType: "user", - actorId: req.actor.userId ?? "board", - action: "join.approved", - entityType: "join_request", - entityId: requestId, - details: { requestType: existing.requestType, createdAgentId } - }); - if (createdAgentId) { - void notifyHireApproved(db, { - companyId, - agentId: createdAgentId, - source: "join_request", - sourceId: requestId, - approvedAt: /* @__PURE__ */ new Date() - }).catch(() => { - }); - } - res.json(toJoinRequestResponse(approved)); - } - ); - router2.post( - "/companies/:companyId/join-requests/:requestId/reject", - async (req, res) => { - const companyId = req.params.companyId; - const requestId = req.params.requestId; - await assertCompanyPermission(req, companyId, "joins:approve"); - const existing = await db.select().from(joinRequests).where( - and( - eq(joinRequests.companyId, companyId), - eq(joinRequests.id, requestId) - ) - ).then((rows) => rows[0] ?? null); - if (!existing) throw notFound("Join request not found"); - if (existing.status !== "pending_approval") - throw conflict("Join request is not pending"); - const rejected = await db.update(joinRequests).set({ - status: "rejected", - rejectedByUserId: req.actor.userId ?? (isLocalImplicit(req) ? "local-board" : null), - rejectedAt: /* @__PURE__ */ new Date(), - updatedAt: /* @__PURE__ */ new Date() - }).where(eq(joinRequests.id, requestId)).returning().then((rows) => rows[0]); - await logActivity(db, { - companyId, - actorType: "user", - actorId: req.actor.userId ?? "board", - action: "join.rejected", - entityType: "join_request", - entityId: requestId, - details: { requestType: existing.requestType } - }); - res.json(toJoinRequestResponse(rejected)); - } - ); - router2.post( - "/join-requests/:requestId/claim-api-key", - validate(claimJoinRequestApiKeySchema), - async (req, res) => { - const requestId = req.params.requestId; - const presentedClaimSecretHash = hashToken3(req.body.claimSecret); - const joinRequest = await db.select().from(joinRequests).where(eq(joinRequests.id, requestId)).then((rows) => rows[0] ?? null); - if (!joinRequest) throw notFound("Join request not found"); - if (joinRequest.requestType !== "agent") - throw badRequest("Only agent join requests can claim API keys"); - if (joinRequest.status !== "approved") - throw conflict("Join request must be approved before key claim"); - if (!joinRequest.createdAgentId) - throw conflict("Join request has no created agent"); - if (!joinRequest.claimSecretHash) - throw conflict("Join request is missing claim secret metadata"); - if (!tokenHashesMatch2(joinRequest.claimSecretHash, presentedClaimSecretHash)) { - throw forbidden("Invalid claim secret"); - } - if (joinRequest.claimSecretExpiresAt && joinRequest.claimSecretExpiresAt.getTime() <= Date.now()) { - throw conflict("Claim secret expired"); - } - if (joinRequest.claimSecretConsumedAt) - throw conflict("Claim secret already used"); - const existingKey = await db.select({ id: agentApiKeys.id }).from(agentApiKeys).where(eq(agentApiKeys.agentId, joinRequest.createdAgentId)).then((rows) => rows[0] ?? null); - if (existingKey) throw conflict("API key already claimed"); - const consumed = await db.update(joinRequests).set({ claimSecretConsumedAt: /* @__PURE__ */ new Date(), updatedAt: /* @__PURE__ */ new Date() }).where( - and( - eq(joinRequests.id, requestId), - isNull(joinRequests.claimSecretConsumedAt) - ) - ).returning({ id: joinRequests.id }).then((rows) => rows[0] ?? null); - if (!consumed) throw conflict("Claim secret already used"); - const created = await agents2.createApiKey( - joinRequest.createdAgentId, - "initial-join-key" - ); - await logActivity(db, { - companyId: joinRequest.companyId, - actorType: "system", - actorId: "join-claim", - action: "agent_api_key.claimed", - entityType: "agent_api_key", - entityId: created.id, - details: { - agentId: joinRequest.createdAgentId, - joinRequestId: requestId - } - }); - res.status(201).json({ - keyId: created.id, - token: created.token, - agentId: joinRequest.createdAgentId, - createdAt: created.createdAt - }); - } - ); - router2.get("/companies/:companyId/members", async (req, res) => { - const companyId = req.params.companyId; - await assertCompanyPermission(req, companyId, "users:manage_permissions"); - const members = await access.listMembers(companyId); - res.json(members); - }); - router2.patch( - "/companies/:companyId/members/:memberId/permissions", - validate(updateMemberPermissionsSchema), - async (req, res) => { - const companyId = req.params.companyId; - const memberId = req.params.memberId; - await assertCompanyPermission(req, companyId, "users:manage_permissions"); - const updated = await access.setMemberPermissions( - companyId, - memberId, - req.body.grants ?? [], - req.actor.userId ?? null - ); - if (!updated) throw notFound("Member not found"); - res.json(updated); - } - ); - router2.post( - "/admin/users/:userId/promote-instance-admin", - async (req, res) => { - await assertInstanceAdmin2(req); - const userId = req.params.userId; - const result = await access.promoteInstanceAdmin(userId); - res.status(201).json(result); - } - ); - router2.post( - "/admin/users/:userId/demote-instance-admin", - async (req, res) => { - await assertInstanceAdmin2(req); - const userId = req.params.userId; - const removed = await access.demoteInstanceAdmin(userId); - if (!removed) throw notFound("Instance admin role not found"); - res.json(removed); - } - ); - router2.get("/admin/users/:userId/company-access", async (req, res) => { - await assertInstanceAdmin2(req); - const userId = req.params.userId; - const memberships = await access.listUserCompanyAccess(userId); - res.json(memberships); - }); - router2.put( - "/admin/users/:userId/company-access", - validate(updateUserCompanyAccessSchema), - async (req, res) => { - await assertInstanceAdmin2(req); - const userId = req.params.userId; - const memberships = await access.setUserCompanyAccess( - userId, - req.body.companyIds ?? [] - ); - res.json(memberships); - } - ); - return router2; -} - -// server/src/routes/plugins.ts -var import_express22 = __toESM(require_express2(), 1); -init_drizzle_orm(); -init_src2(); -import { existsSync as existsSync6 } from "node:fs"; -import path47 from "node:path"; -import { randomUUID as randomUUID10 } from "node:crypto"; -import { fileURLToPath as fileURLToPath18 } from "node:url"; - -// server/src/services/plugin-registry.ts -init_drizzle_orm(); -init_src2(); -function isPluginKeyConflict(error50) { - if (typeof error50 !== "object" || error50 === null) return false; - const err = error50; - const constraint = err.constraint ?? err.constraint_name; - return err.code === "23505" && constraint === "plugins_plugin_key_idx"; -} -function pluginRegistryService(db) { - async function getById(id) { - return db.select().from(plugins).where(eq(plugins.id, id)).then((rows) => rows[0] ?? null); - } - async function getByKey(pluginKey) { - return db.select().from(plugins).where(eq(plugins.pluginKey, pluginKey)).then((rows) => rows[0] ?? null); - } - async function nextInstallOrder() { - const result = await db.select({ maxOrder: sql`coalesce(max(${plugins.installOrder}), 0)` }).from(plugins); - return (result[0]?.maxOrder ?? 0) + 1; - } - return { - // ----- Read ----------------------------------------------------------- - /** List all registered plugins ordered by install order. */ - list: () => db.select().from(plugins).orderBy(asc(plugins.installOrder)), - /** - * List installed plugins (excludes soft-deleted/uninstalled). - * Use for Plugin Manager and default API list so uninstalled plugins do not appear. - */ - listInstalled: () => db.select().from(plugins).where(ne(plugins.status, "uninstalled")).orderBy(asc(plugins.installOrder)), - /** List plugins filtered by status. */ - listByStatus: (status) => db.select().from(plugins).where(eq(plugins.status, status)).orderBy(asc(plugins.installOrder)), - /** Get a single plugin by primary key. */ - getById, - /** Get a single plugin by its unique `pluginKey`. */ - getByKey, - // ----- Install / Register -------------------------------------------- - /** - * Register (install) a new plugin. - * - * The caller is expected to have already resolved and validated the - * manifest from the package. This method persists the plugin row and - * assigns the next install order. - */ - install: async (input, manifest) => { - const existing = await getByKey(manifest.id); - if (existing) { - if (existing.status !== "uninstalled") { - throw conflict(`Plugin already installed: ${manifest.id}`); - } - return db.update(plugins).set({ - packageName: input.packageName, - packagePath: input.packagePath ?? null, - version: manifest.version, - apiVersion: manifest.apiVersion, - categories: manifest.categories, - manifestJson: manifest, - status: "installed", - lastError: null, - updatedAt: /* @__PURE__ */ new Date() - }).where(eq(plugins.id, existing.id)).returning().then((rows) => rows[0] ?? null); - } - const installOrder = await nextInstallOrder(); - try { - const rows = await db.insert(plugins).values({ - pluginKey: manifest.id, - packageName: input.packageName, - version: manifest.version, - apiVersion: manifest.apiVersion, - categories: manifest.categories, - manifestJson: manifest, - status: "installed", - installOrder, - packagePath: input.packagePath ?? null - }).returning(); - return rows[0]; - } catch (error50) { - if (isPluginKeyConflict(error50)) { - throw conflict(`Plugin already installed: ${manifest.id}`); - } - throw error50; - } - }, - // ----- Update --------------------------------------------------------- - /** - * Update a plugin's manifest and version (e.g. on upgrade). - * The plugin must already exist. - */ - update: async (id, data2) => { - const plugin = await getById(id); - if (!plugin) throw notFound("Plugin not found"); - const setClause = { - updatedAt: /* @__PURE__ */ new Date() - }; - if (data2.packageName !== void 0) setClause.packageName = data2.packageName; - if (data2.version !== void 0) setClause.version = data2.version; - if (data2.manifest !== void 0) { - setClause.manifestJson = data2.manifest; - setClause.apiVersion = data2.manifest.apiVersion; - setClause.categories = data2.manifest.categories; - } - return db.update(plugins).set(setClause).where(eq(plugins.id, id)).returning().then((rows) => rows[0] ?? null); - }, - // ----- Status --------------------------------------------------------- - /** Update a plugin's lifecycle status and optional error message. */ - updateStatus: async (id, input) => { - const plugin = await getById(id); - if (!plugin) throw notFound("Plugin not found"); - return db.update(plugins).set({ - status: input.status, - lastError: input.lastError ?? null, - updatedAt: /* @__PURE__ */ new Date() - }).where(eq(plugins.id, id)).returning().then((rows) => rows[0] ?? null); - }, - // ----- Uninstall / Remove -------------------------------------------- - /** - * Uninstall a plugin. - * - * When `removeData` is true the plugin row (and cascaded config) is - * hard-deleted. Otherwise the status is set to `"uninstalled"` for - * a soft-delete that preserves the record. - */ - uninstall: async (id, removeData = false) => { - const plugin = await getById(id); - if (!plugin) throw notFound("Plugin not found"); - if (removeData) { - return db.delete(plugins).where(eq(plugins.id, id)).returning().then((rows) => rows[0] ?? null); - } - return db.update(plugins).set({ - status: "uninstalled", - updatedAt: /* @__PURE__ */ new Date() - }).where(eq(plugins.id, id)).returning().then((rows) => rows[0] ?? null); - }, - // ----- Config --------------------------------------------------------- - /** Retrieve a plugin's instance configuration. */ - getConfig: (pluginId) => db.select().from(pluginConfig).where(eq(pluginConfig.pluginId, pluginId)).then((rows) => rows[0] ?? null), - /** - * Create or fully replace a plugin's instance configuration. - * If a config row already exists for the plugin it is replaced; - * otherwise a new row is inserted. - */ - upsertConfig: async (pluginId, input) => { - const plugin = await getById(pluginId); - if (!plugin) throw notFound("Plugin not found"); - const existing = await db.select().from(pluginConfig).where(eq(pluginConfig.pluginId, pluginId)).then((rows) => rows[0] ?? null); - if (existing) { - return db.update(pluginConfig).set({ - configJson: input.configJson, - lastError: null, - updatedAt: /* @__PURE__ */ new Date() - }).where(eq(pluginConfig.pluginId, pluginId)).returning().then((rows) => rows[0]); - } - return db.insert(pluginConfig).values({ - pluginId, - configJson: input.configJson - }).returning().then((rows) => rows[0]); - }, - /** - * Partially update a plugin's instance configuration via shallow merge. - * If no config row exists yet one is created with the supplied values. - */ - patchConfig: async (pluginId, input) => { - const plugin = await getById(pluginId); - if (!plugin) throw notFound("Plugin not found"); - const existing = await db.select().from(pluginConfig).where(eq(pluginConfig.pluginId, pluginId)).then((rows) => rows[0] ?? null); - if (existing) { - const merged = { ...existing.configJson, ...input.configJson }; - return db.update(pluginConfig).set({ - configJson: merged, - lastError: null, - updatedAt: /* @__PURE__ */ new Date() - }).where(eq(pluginConfig.pluginId, pluginId)).returning().then((rows) => rows[0]); - } - return db.insert(pluginConfig).values({ - pluginId, - configJson: input.configJson - }).returning().then((rows) => rows[0]); - }, - /** - * Record an error against a plugin's config (e.g. validation failure - * against the plugin's instanceConfigSchema). - */ - setConfigError: async (pluginId, lastError) => { - const rows = await db.update(pluginConfig).set({ lastError, updatedAt: /* @__PURE__ */ new Date() }).where(eq(pluginConfig.pluginId, pluginId)).returning(); - if (rows.length === 0) throw notFound("Plugin config not found"); - return rows[0]; - }, - /** Delete a plugin's config row. */ - deleteConfig: async (pluginId) => { - const rows = await db.delete(pluginConfig).where(eq(pluginConfig.pluginId, pluginId)).returning(); - return rows[0] ?? null; - }, - // ----- Entities ------------------------------------------------------- - /** - * List persistent entity mappings owned by a specific plugin, with filtering and pagination. - * - * @param pluginId - The UUID of the plugin. - * @param query - Optional filters (type, externalId) and pagination (limit, offset). - * @returns A list of matching `PluginEntityRecord` objects. - */ - listEntities: (pluginId, query) => { - const conditions = [eq(pluginEntities.pluginId, pluginId)]; - if (query?.entityType) conditions.push(eq(pluginEntities.entityType, query.entityType)); - if (query?.externalId) conditions.push(eq(pluginEntities.externalId, query.externalId)); - return db.select().from(pluginEntities).where(and(...conditions)).orderBy(asc(pluginEntities.createdAt)).limit(query?.limit ?? 100).offset(query?.offset ?? 0); - }, - /** - * Look up a plugin-owned entity mapping by its external identifier. - * - * @param pluginId - The UUID of the plugin. - * @param entityType - The type of entity (e.g., 'project', 'issue'). - * @param externalId - The identifier in the external system. - * @returns The matching `PluginEntityRecord` or null. - */ - getEntityByExternalId: (pluginId, entityType, externalId) => db.select().from(pluginEntities).where( - and( - eq(pluginEntities.pluginId, pluginId), - eq(pluginEntities.entityType, entityType), - eq(pluginEntities.externalId, externalId) - ) - ).then((rows) => rows[0] ?? null), - /** - * Create or update a persistent mapping between a Taskcore object and an - * external entity. - * - * @param pluginId - The UUID of the plugin. - * @param input - The entity data to persist. - * @returns The newly created or updated `PluginEntityRecord`. - */ - upsertEntity: async (pluginId, input) => { - const existing = await db.select().from(pluginEntities).where( - and( - eq(pluginEntities.pluginId, pluginId), - eq(pluginEntities.entityType, input.entityType), - eq(pluginEntities.externalId, input.externalId ?? "") - ) - ).then((rows) => rows[0] ?? null); - if (existing) { - return db.update(pluginEntities).set({ - ...input, - updatedAt: /* @__PURE__ */ new Date() - }).where(eq(pluginEntities.id, existing.id)).returning().then((rows) => rows[0]); - } - return db.insert(pluginEntities).values({ - ...input, - pluginId - }).returning().then((rows) => rows[0]); - }, - /** - * Delete a specific plugin-owned entity mapping by its internal UUID. - * - * @param id - The UUID of the entity record. - * @returns The deleted record, or null if not found. - */ - deleteEntity: async (id) => { - const rows = await db.delete(pluginEntities).where(eq(pluginEntities.id, id)).returning(); - return rows[0] ?? null; - }, - // ----- Jobs ----------------------------------------------------------- - /** - * List all scheduled jobs registered for a specific plugin. - * - * @param pluginId - The UUID of the plugin. - * @returns A list of `PluginJobRecord` objects. - */ - listJobs: (pluginId) => db.select().from(pluginJobs).where(eq(pluginJobs.pluginId, pluginId)).orderBy(asc(pluginJobs.jobKey)), - /** - * Look up a plugin job by its unique job key. - * - * @param pluginId - The UUID of the plugin. - * @param jobKey - The key defined in the plugin manifest. - * @returns The matching `PluginJobRecord` or null. - */ - getJobByKey: (pluginId, jobKey) => db.select().from(pluginJobs).where(and(eq(pluginJobs.pluginId, pluginId), eq(pluginJobs.jobKey, jobKey))).then((rows) => rows[0] ?? null), - /** - * Register or update a scheduled job for a plugin. - * - * @param pluginId - The UUID of the plugin. - * @param jobKey - The unique key for the job. - * @param input - The schedule (cron) and optional status. - * @returns The updated or created `PluginJobRecord`. - */ - upsertJob: async (pluginId, jobKey, input) => { - const existing = await db.select().from(pluginJobs).where(and(eq(pluginJobs.pluginId, pluginId), eq(pluginJobs.jobKey, jobKey))).then((rows) => rows[0] ?? null); - if (existing) { - return db.update(pluginJobs).set({ - schedule: input.schedule, - status: input.status ?? existing.status, - updatedAt: /* @__PURE__ */ new Date() - }).where(eq(pluginJobs.id, existing.id)).returning().then((rows) => rows[0]); - } - return db.insert(pluginJobs).values({ - pluginId, - jobKey, - schedule: input.schedule, - status: input.status ?? "active" - }).returning().then((rows) => rows[0]); - }, - /** - * Record the start of a specific job execution. - * - * @param pluginId - The UUID of the plugin. - * @param jobId - The UUID of the parent job record. - * @param trigger - What triggered this run (e.g., 'schedule', 'manual'). - * @returns The newly created `PluginJobRunRecord` in 'pending' status. - */ - createJobRun: async (pluginId, jobId, trigger) => { - return db.insert(pluginJobRuns).values({ - pluginId, - jobId, - trigger, - status: "pending" - }).returning().then((rows) => rows[0]); - }, - /** - * Update the status, duration, and logs of a job execution record. - * - * @param runId - The UUID of the job run. - * @param input - The update fields (status, error, duration, etc.). - * @returns The updated `PluginJobRunRecord`. - */ - updateJobRun: async (runId, input) => { - return db.update(pluginJobRuns).set(input).where(eq(pluginJobRuns.id, runId)).returning().then((rows) => rows[0] ?? null); - }, - // ----- Webhooks ------------------------------------------------------- - /** - * Create a record for an incoming webhook delivery. - * - * @param pluginId - The UUID of the receiving plugin. - * @param webhookKey - The endpoint key defined in the manifest. - * @param input - The payload, headers, and optional external ID. - * @returns The newly created `PluginWebhookDeliveryRecord` in 'pending' status. - */ - createWebhookDelivery: async (pluginId, webhookKey, input) => { - return db.insert(pluginWebhookDeliveries).values({ - pluginId, - webhookKey, - externalId: input.externalId, - payload: input.payload, - headers: input.headers ?? {}, - status: "pending" - }).returning().then((rows) => rows[0]); - }, - /** - * Update the status and processing metrics of a webhook delivery. - * - * @param deliveryId - The UUID of the delivery record. - * @param input - The update fields (status, error, duration, etc.). - * @returns The updated `PluginWebhookDeliveryRecord`. - */ - updateWebhookDelivery: async (deliveryId, input) => { - return db.update(pluginWebhookDeliveries).set(input).where(eq(pluginWebhookDeliveries.id, deliveryId)).returning().then((rows) => rows[0] ?? null); - } - }; -} - -// server/src/services/plugin-lifecycle.ts -import { EventEmitter as EventEmitter2 } from "node:events"; - -// server/src/services/plugin-loader.ts -import { existsSync as existsSync5 } from "node:fs"; -import { readdir as readdir2, readFile as readFile3, rm, stat } from "node:fs/promises"; -import { execFile as execFile7 } from "node:child_process"; -import os23 from "node:os"; -import path46 from "node:path"; -import { fileURLToPath as fileURLToPath17 } from "node:url"; -import { promisify as promisify7 } from "node:util"; - -// server/src/services/plugin-manifest-validator.ts -var SUPPORTED_VERSIONS = [PLUGIN_API_VERSION]; -function pluginManifestValidator() { - return { - parse(input) { - const result = pluginManifestV1Schema.safeParse(input); - if (result.success) { - return { - success: true, - manifest: result.data - }; - } - const details = result.error.errors.map((issue2) => ({ - path: issue2.path, - message: issue2.message - })); - const errors = details.map( - ({ path: path53, message: message2 }) => path53.length > 0 ? `${path53.join(".")}: ${message2}` : message2 - ).join("; "); - return { - success: false, - errors, - details - }; - }, - parseOrThrow(input) { - const result = this.parse(input); - if (!result.success) { - throw badRequest(`Invalid plugin manifest: ${result.errors}`, result.details); - } - return result.manifest; - }, - getSupportedVersions() { - return SUPPORTED_VERSIONS; - } - }; -} - -// server/src/services/plugin-capability-validator.ts -var OPERATION_CAPABILITIES = { - // Data read operations - "companies.list": ["companies.read"], - "companies.get": ["companies.read"], - "projects.list": ["projects.read"], - "projects.get": ["projects.read"], - "project.workspaces.list": ["project.workspaces.read"], - "project.workspaces.get": ["project.workspaces.read"], - "issues.list": ["issues.read"], - "issues.get": ["issues.read"], - "issue.comments.list": ["issue.comments.read"], - "issue.comments.get": ["issue.comments.read"], - "agents.list": ["agents.read"], - "agents.get": ["agents.read"], - "goals.list": ["goals.read"], - "goals.get": ["goals.read"], - "activity.list": ["activity.read"], - "activity.get": ["activity.read"], - "costs.list": ["costs.read"], - "costs.get": ["costs.read"], - // Data write operations - "issues.create": ["issues.create"], - "issues.update": ["issues.update"], - "issue.comments.create": ["issue.comments.create"], - "activity.log": ["activity.log.write"], - "metrics.write": ["metrics.write"], - "telemetry.track": ["telemetry.track"], - // Plugin state operations - "plugin.state.get": ["plugin.state.read"], - "plugin.state.list": ["plugin.state.read"], - "plugin.state.set": ["plugin.state.write"], - "plugin.state.delete": ["plugin.state.write"], - // Runtime / Integration operations - "events.subscribe": ["events.subscribe"], - "events.emit": ["events.emit"], - "jobs.schedule": ["jobs.schedule"], - "jobs.cancel": ["jobs.schedule"], - "webhooks.receive": ["webhooks.receive"], - "http.request": ["http.outbound"], - "secrets.resolve": ["secrets.read-ref"], - // Agent tools - "agent.tools.register": ["agent.tools.register"], - "agent.tools.execute": ["agent.tools.register"] -}; -var UI_SLOT_CAPABILITIES = { - sidebar: "ui.sidebar.register", - sidebarPanel: "ui.sidebar.register", - projectSidebarItem: "ui.sidebar.register", - page: "ui.page.register", - detailTab: "ui.detailTab.register", - taskDetailView: "ui.detailTab.register", - dashboardWidget: "ui.dashboardWidget.register", - globalToolbarButton: "ui.action.register", - toolbarButton: "ui.action.register", - contextMenuItem: "ui.action.register", - commentAnnotation: "ui.commentAnnotation.register", - commentContextMenuItem: "ui.action.register", - settingsPage: "instance.settings.register" -}; -var LAUNCHER_PLACEMENT_CAPABILITIES = { - page: "ui.page.register", - detailTab: "ui.detailTab.register", - taskDetailView: "ui.detailTab.register", - dashboardWidget: "ui.dashboardWidget.register", - sidebar: "ui.sidebar.register", - sidebarPanel: "ui.sidebar.register", - projectSidebarItem: "ui.sidebar.register", - globalToolbarButton: "ui.action.register", - toolbarButton: "ui.action.register", - contextMenuItem: "ui.action.register", - commentAnnotation: "ui.commentAnnotation.register", - commentContextMenuItem: "ui.action.register", - settingsPage: "instance.settings.register" -}; -var FEATURE_CAPABILITIES = { - tools: "agent.tools.register", - jobs: "jobs.schedule", - webhooks: "webhooks.receive" -}; -function pluginCapabilityValidator() { - const log2 = logger.child({ service: "plugin-capability-validator" }); - function capabilitySet(manifest) { - return new Set(manifest.capabilities); - } - function buildForbiddenMessage(manifest, operation2, missing) { - return `Plugin '${manifest.id}' is not allowed to perform '${operation2}'. Missing required capabilities: ${missing.join(", ")}`; - } - return { - hasCapability(manifest, capability) { - return manifest.capabilities.includes(capability); - }, - hasAllCapabilities(manifest, capabilities) { - const declared = capabilitySet(manifest); - const missing = capabilities.filter((cap) => !declared.has(cap)); - return { - allowed: missing.length === 0, - missing, - pluginId: manifest.id - }; - }, - hasAnyCapability(manifest, capabilities) { - const declared = capabilitySet(manifest); - return capabilities.some((cap) => declared.has(cap)); - }, - checkOperation(manifest, operation2) { - const required2 = OPERATION_CAPABILITIES[operation2]; - if (!required2) { - log2.warn( - { pluginId: manifest.id, operation: operation2 }, - "capability check for unknown operation \u2013 rejecting by default" - ); - return { - allowed: false, - missing: [], - operation: operation2, - pluginId: manifest.id - }; - } - const declared = capabilitySet(manifest); - const missing = required2.filter((cap) => !declared.has(cap)); - if (missing.length > 0) { - log2.debug( - { pluginId: manifest.id, operation: operation2, missing }, - "capability check failed" - ); - } - return { - allowed: missing.length === 0, - missing, - operation: operation2, - pluginId: manifest.id - }; - }, - assertOperation(manifest, operation2) { - const result = this.checkOperation(manifest, operation2); - if (!result.allowed) { - const msg = result.missing.length > 0 ? buildForbiddenMessage(manifest, operation2, result.missing) : `Plugin '${manifest.id}' attempted unknown operation '${operation2}'`; - throw forbidden(msg); - } - }, - assertCapability(manifest, capability) { - if (!this.hasCapability(manifest, capability)) { - throw forbidden( - `Plugin '${manifest.id}' lacks required capability '${capability}'` - ); - } - }, - checkUiSlot(manifest, slotType) { - const required2 = UI_SLOT_CAPABILITIES[slotType]; - if (!required2) { - return { - allowed: false, - missing: [], - operation: `ui.${slotType}.register`, - pluginId: manifest.id - }; - } - const has = manifest.capabilities.includes(required2); - return { - allowed: has, - missing: has ? [] : [required2], - operation: `ui.${slotType}.register`, - pluginId: manifest.id - }; - }, - validateManifestCapabilities(manifest) { - const declared = capabilitySet(manifest); - const allMissing = []; - for (const [feature, requiredCap] of Object.entries(FEATURE_CAPABILITIES)) { - const featureValue = manifest[feature]; - if (Array.isArray(featureValue) && featureValue.length > 0) { - if (!declared.has(requiredCap)) { - allMissing.push(requiredCap); - } - } - } - const uiSlots = manifest.ui?.slots ?? []; - if (uiSlots.length > 0) { - for (const slot of uiSlots) { - const requiredCap = UI_SLOT_CAPABILITIES[slot.type]; - if (requiredCap && !declared.has(requiredCap)) { - if (!allMissing.includes(requiredCap)) { - allMissing.push(requiredCap); - } - } - } - } - const launchers = [ - ...manifest.launchers ?? [], - ...manifest.ui?.launchers ?? [] - ]; - if (launchers.length > 0) { - for (const launcher of launchers) { - const requiredCap = LAUNCHER_PLACEMENT_CAPABILITIES[launcher.placementZone]; - if (requiredCap && !declared.has(requiredCap) && !allMissing.includes(requiredCap)) { - allMissing.push(requiredCap); - } - } - } - return { - allowed: allMissing.length === 0, - missing: allMissing, - pluginId: manifest.id - }; - }, - getRequiredCapabilities(operation2) { - return OPERATION_CAPABILITIES[operation2] ?? []; - }, - getUiSlotCapability(slotType) { - return UI_SLOT_CAPABILITIES[slotType]; - } - }; -} - -// server/src/services/plugin-loader.ts -var execFileAsync6 = promisify7(execFile7); -var __dirname2 = path46.dirname(fileURLToPath17(import.meta.url)); -var NPM_PLUGIN_PACKAGE_PREFIX = "taskcore-plugin-"; -var DEFAULT_LOCAL_PLUGIN_DIR = path46.join( - os23.homedir(), - ".taskcore", - "plugins" -); -var DEV_TSX_LOADER_PATH = path46.resolve(__dirname2, "../../../cli/node_modules/tsx/dist/loader.mjs"); -function getDeclaredPageRoutePaths(manifest) { - return (manifest.ui?.slots ?? []).filter((slot) => slot.type === "page" && typeof slot.routePath === "string" && slot.routePath.length > 0).map((slot) => slot.routePath); -} -function isPluginPackageName(name) { - if (name.startsWith(NPM_PLUGIN_PACKAGE_PREFIX)) return true; - if (name.includes("/")) { - const localPart = name.split("/")[1] ?? ""; - return localPart.startsWith("plugin-"); - } - return false; -} -async function readPackageJson(dir) { - const pkgPath = path46.join(dir, "package.json"); - if (!existsSync5(pkgPath)) return null; - try { - const raw = await readFile3(pkgPath, "utf-8"); - return JSON.parse(raw); - } catch { - return null; - } -} -function resolveManifestPath(packageRoot, pkgJson) { - const taskcorePlugin = pkgJson["taskcorePlugin"]; - if (taskcorePlugin !== null && typeof taskcorePlugin === "object" && !Array.isArray(taskcorePlugin)) { - const manifestRelPath = taskcorePlugin["manifest"]; - if (typeof manifestRelPath === "string") { - return path46.resolve(packageRoot, manifestRelPath); - } - } - const conventionalPath = path46.join(packageRoot, "dist", "manifest.js"); - if (existsSync5(conventionalPath)) { - return conventionalPath; - } - const rootManifestPath = path46.join(packageRoot, "manifest.js"); - if (existsSync5(rootManifestPath)) { - return rootManifestPath; - } - return null; -} -function parseSemver(version3) { - const match = version3.match( - /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/ - ); - if (!match) return null; - return { - major: Number(match[1]), - minor: Number(match[2]), - patch: Number(match[3]), - prerelease: match[4] ? match[4].split(".") : [] - }; -} -function compareIdentifiers(left, right) { - const leftIsNumeric = /^\d+$/.test(left); - const rightIsNumeric = /^\d+$/.test(right); - if (leftIsNumeric && rightIsNumeric) { - return Number(left) - Number(right); - } - if (leftIsNumeric) return -1; - if (rightIsNumeric) return 1; - return left.localeCompare(right); -} -function compareSemver(left, right) { - const leftParsed = parseSemver(left); - const rightParsed = parseSemver(right); - if (!leftParsed || !rightParsed) { - throw new Error(`Invalid semver comparison: '${left}' vs '${right}'`); - } - const coreOrder = ["major", "minor", "patch"].map((key) => leftParsed[key] - rightParsed[key]).find((delta) => delta !== 0); - if (coreOrder) { - return coreOrder; - } - if (leftParsed.prerelease.length === 0 && rightParsed.prerelease.length === 0) { - return 0; - } - if (leftParsed.prerelease.length === 0) return 1; - if (rightParsed.prerelease.length === 0) return -1; - const maxLength = Math.max(leftParsed.prerelease.length, rightParsed.prerelease.length); - for (let index2 = 0; index2 < maxLength; index2 += 1) { - const leftId = leftParsed.prerelease[index2]; - const rightId = rightParsed.prerelease[index2]; - if (leftId === void 0) return -1; - if (rightId === void 0) return 1; - const diff = compareIdentifiers(leftId, rightId); - if (diff !== 0) return diff; - } - return 0; -} -function getMinimumHostVersion(manifest) { - return manifest.minimumHostVersion ?? manifest.minimumTaskcoreVersion; -} -function getPluginUiContributionMetadata(manifest) { - const slots = manifest.ui?.slots ?? []; - const launchers = [ - ...manifest.launchers ?? [], - ...manifest.ui?.launchers ?? [] - ]; - if (slots.length === 0 && launchers.length === 0) { - return null; - } - return { - uiEntryFile: "index.js", - slots, - launchers - }; -} -function pluginLoader(db, options = {}, runtimeServices) { - const { - localPluginDir = DEFAULT_LOCAL_PLUGIN_DIR, - enableLocalFilesystem = true, - enableNpmDiscovery = true - } = options; - const registry2 = pluginRegistryService(db); - const manifestValidator = pluginManifestValidator(); - const capabilityValidator = pluginCapabilityValidator(); - const log2 = logger.child({ service: "plugin-loader" }); - const hostVersion = runtimeServices?.instanceInfo.hostVersion; - async function assertPageRoutePathsAvailable(manifest) { - const requestedRoutePaths = getDeclaredPageRoutePaths(manifest); - if (requestedRoutePaths.length === 0) return; - const uniqueRequested = new Set(requestedRoutePaths); - if (uniqueRequested.size !== requestedRoutePaths.length) { - throw new Error(`Plugin ${manifest.id} declares duplicate page routePath values`); - } - const installedPlugins = await registry2.listInstalled(); - for (const plugin of installedPlugins) { - if (plugin.pluginKey === manifest.id) continue; - const installedManifest = plugin.manifestJson; - if (!installedManifest) continue; - const installedRoutePaths = new Set(getDeclaredPageRoutePaths(installedManifest)); - const conflictingRoute = requestedRoutePaths.find((routePath) => installedRoutePaths.has(routePath)); - if (conflictingRoute) { - throw new Error( - `Plugin ${manifest.id} routePath "${conflictingRoute}" conflicts with installed plugin ${plugin.pluginKey}` - ); - } - } - } - async function fetchAndValidate(installOptions) { - const { packageName, localPath, version: version3, installDir } = installOptions; - if (!packageName && !localPath) { - throw new Error("Either packageName or localPath must be provided"); - } - const targetInstallDir = installDir ?? localPluginDir; - let resolvedPackagePath; - let resolvedPackageName; - if (localPath) { - const absLocalPath = path46.resolve(localPath); - if (!existsSync5(absLocalPath)) { - throw new Error(`Local plugin path does not exist: ${absLocalPath}`); - } - resolvedPackagePath = absLocalPath; - const pkgJson2 = await readPackageJson(absLocalPath); - resolvedPackageName = typeof pkgJson2?.["name"] === "string" ? pkgJson2["name"] : path46.basename(absLocalPath); - log2.info( - { localPath: absLocalPath, packageName: resolvedPackageName }, - "plugin-loader: fetching plugin from local path" - ); - } else { - const spec = version3 ? `${packageName}@${version3}` : packageName; - log2.info( - { spec, installDir: targetInstallDir }, - "plugin-loader: fetching plugin from npm" - ); - try { - await execFileAsync6( - "npm", - ["install", spec, "--prefix", targetInstallDir, "--save", "--ignore-scripts"], - { timeout: 12e4 } - // 2 minute timeout for npm install - ); - } catch (err) { - throw new Error(`npm install failed for ${spec}: ${String(err)}`); - } - const nodeModulesPath = path46.join(targetInstallDir, "node_modules"); - resolvedPackageName = packageName; - if (resolvedPackageName.startsWith("@")) { - const [scope, name] = resolvedPackageName.split("/"); - resolvedPackagePath = path46.join(nodeModulesPath, scope, name); - } else { - resolvedPackagePath = path46.join(nodeModulesPath, resolvedPackageName); - } - if (!existsSync5(resolvedPackagePath)) { - throw new Error( - `Package directory not found after installation: ${resolvedPackagePath}` - ); - } - } - const pkgJson = await readPackageJson(resolvedPackagePath); - if (!pkgJson) throw new Error(`Missing package.json at ${resolvedPackagePath}`); - const manifestPath = resolveManifestPath(resolvedPackagePath, pkgJson); - if (!manifestPath || !existsSync5(manifestPath)) { - throw new Error( - `Package ${resolvedPackageName} at ${resolvedPackagePath} does not appear to be a Taskcore plugin (no manifest found).` - ); - } - const manifest = await loadManifestFromPath(manifestPath); - if (!manifestValidator.getSupportedVersions().includes(manifest.apiVersion)) { - throw new Error( - `Plugin ${manifest.id} declares apiVersion ${manifest.apiVersion} which is not supported by this host. Supported versions: ${manifestValidator.getSupportedVersions().join(", ")}` - ); - } - const capResult = capabilityValidator.validateManifestCapabilities(manifest); - if (!capResult.allowed) { - throw new Error( - `Plugin ${manifest.id} manifest has inconsistent capabilities. Missing required capabilities for declared features: ${capResult.missing.join(", ")}` - ); - } - await assertPageRoutePathsAvailable(manifest); - const minimumHostVersion = getMinimumHostVersion(manifest); - if (minimumHostVersion && hostVersion) { - if (compareSemver(hostVersion, minimumHostVersion) < 0) { - throw new Error( - `Plugin ${manifest.id} requires host version ${minimumHostVersion} or newer, but this server is running ${hostVersion}` - ); - } - } - const resolvedVersion = manifest.version; - return { - packagePath: resolvedPackagePath, - packageName: resolvedPackageName, - version: resolvedVersion, - source: localPath ? "local-filesystem" : "npm", - manifest - }; - } - async function loadManifestFromPath(manifestPath) { - let raw; - try { - const mod = await import(manifestPath); - raw = mod["default"] ?? mod; - } catch (err) { - throw new Error( - `Failed to load manifest module at ${manifestPath}: ${String(err)}` - ); - } - return manifestValidator.parseOrThrow(raw); - } - async function buildDiscoveredPlugin(packagePath, source) { - const pkgJson = await readPackageJson(packagePath); - if (!pkgJson) return null; - const packageName = typeof pkgJson["name"] === "string" ? pkgJson["name"] : ""; - const version3 = typeof pkgJson["version"] === "string" ? pkgJson["version"] : "0.0.0"; - const hasTaskcorePlugin = "taskcorePlugin" in pkgJson; - const nameMatchesConvention = isPluginPackageName(packageName); - if (!hasTaskcorePlugin && !nameMatchesConvention) { - return null; - } - const manifestPath = resolveManifestPath(packagePath, pkgJson); - if (!manifestPath || !existsSync5(manifestPath)) { - return { - packagePath, - packageName, - version: version3, - source, - manifest: null - }; - } - try { - const manifest = await loadManifestFromPath(manifestPath); - return { - packagePath, - packageName, - version: version3, - source, - manifest - }; - } catch (err) { - throw new Error( - `Plugin ${packageName}: ${String(err)}` - ); - } - } - return { - // ----------------------------------------------------------------------- - // discoverAll - // ----------------------------------------------------------------------- - async discoverAll(npmSearchDirs) { - const allDiscovered = []; - const allErrors = []; - const sources = []; - if (enableLocalFilesystem) { - sources.push("local-filesystem"); - const fsResult = await this.discoverFromLocalFilesystem(); - allDiscovered.push(...fsResult.discovered); - allErrors.push(...fsResult.errors); - } - if (enableNpmDiscovery) { - sources.push("npm"); - const npmResult = await this.discoverFromNpm(npmSearchDirs); - const existingPaths = new Set(allDiscovered.map((d5) => d5.packagePath)); - for (const plugin of npmResult.discovered) { - if (!existingPaths.has(plugin.packagePath)) { - allDiscovered.push(plugin); - } - } - allErrors.push(...npmResult.errors); - } - if (options.registryUrl) { - sources.push("registry"); - log2.warn( - { registryUrl: options.registryUrl }, - "plugin-loader: remote registry discovery is not yet implemented" - ); - } - log2.info( - { - discovered: allDiscovered.length, - errors: allErrors.length, - sources - }, - "plugin-loader: discovery complete" - ); - return { discovered: allDiscovered, errors: allErrors, sources }; - }, - // ----------------------------------------------------------------------- - // discoverFromLocalFilesystem - // ----------------------------------------------------------------------- - async discoverFromLocalFilesystem(dir) { - const scanDir = dir ?? localPluginDir; - const discovered = []; - const errors = []; - if (!existsSync5(scanDir)) { - log2.debug( - { dir: scanDir }, - "plugin-loader: local plugin directory does not exist, skipping" - ); - return { discovered, errors, sources: ["local-filesystem"] }; - } - let entries2; - try { - entries2 = await readdir2(scanDir); - } catch (err) { - log2.warn({ dir: scanDir, err }, "plugin-loader: failed to read local plugin directory"); - return { discovered, errors, sources: ["local-filesystem"] }; - } - for (const entry of entries2) { - const entryPath = path46.join(scanDir, entry); - let entryStat; - try { - entryStat = await stat(entryPath); - } catch { - continue; - } - if (!entryStat.isDirectory()) continue; - if (entry.startsWith("@")) { - let scopedEntries; - try { - scopedEntries = await readdir2(entryPath); - } catch { - continue; - } - for (const scopedEntry of scopedEntries) { - const scopedPath = path46.join(entryPath, scopedEntry); - try { - const scopedStat = await stat(scopedPath); - if (!scopedStat.isDirectory()) continue; - const plugin = await buildDiscoveredPlugin(scopedPath, "local-filesystem"); - if (plugin) discovered.push(plugin); - } catch (err) { - errors.push({ - packagePath: scopedPath, - packageName: `${entry}/${scopedEntry}`, - error: String(err) - }); - } - } - continue; - } - try { - const plugin = await buildDiscoveredPlugin(entryPath, "local-filesystem"); - if (plugin) discovered.push(plugin); - } catch (err) { - const pkgJson = await readPackageJson(entryPath); - const packageName = typeof pkgJson?.["name"] === "string" ? pkgJson["name"] : entry; - errors.push({ packagePath: entryPath, packageName, error: String(err) }); - } - } - log2.debug( - { dir: scanDir, discovered: discovered.length, errors: errors.length }, - "plugin-loader: local filesystem scan complete" - ); - return { discovered, errors, sources: ["local-filesystem"] }; - }, - // ----------------------------------------------------------------------- - // discoverFromNpm - // ----------------------------------------------------------------------- - async discoverFromNpm(searchDirs) { - const discovered = []; - const errors = []; - const dirsToSearch = searchDirs && searchDirs.length > 0 ? searchDirs : []; - if (dirsToSearch.length === 0) { - const cwdNodeModules = path46.join(process.cwd(), "node_modules"); - const localNodeModules = path46.join(localPluginDir, "node_modules"); - if (existsSync5(cwdNodeModules)) dirsToSearch.push(cwdNodeModules); - if (existsSync5(localNodeModules)) dirsToSearch.push(localNodeModules); - } - for (const nodeModulesDir of dirsToSearch) { - if (!existsSync5(nodeModulesDir)) continue; - let entries2; - try { - entries2 = await readdir2(nodeModulesDir); - } catch { - continue; - } - for (const entry of entries2) { - const entryPath = path46.join(nodeModulesDir, entry); - if (entry.startsWith("@")) { - let scopedEntries; - try { - scopedEntries = await readdir2(entryPath); - } catch { - continue; - } - for (const scopedEntry of scopedEntries) { - const fullName = `${entry}/${scopedEntry}`; - if (!isPluginPackageName(fullName)) continue; - const scopedPath = path46.join(entryPath, scopedEntry); - try { - const plugin = await buildDiscoveredPlugin(scopedPath, "npm"); - if (plugin) discovered.push(plugin); - } catch (err) { - errors.push({ - packagePath: scopedPath, - packageName: fullName, - error: String(err) - }); - } - } - continue; - } - if (!isPluginPackageName(entry)) continue; - let entryStat; - try { - entryStat = await stat(entryPath); - } catch { - continue; - } - if (!entryStat.isDirectory()) continue; - try { - const plugin = await buildDiscoveredPlugin(entryPath, "npm"); - if (plugin) discovered.push(plugin); - } catch (err) { - const pkgJson = await readPackageJson(entryPath); - const packageName = typeof pkgJson?.["name"] === "string" ? pkgJson["name"] : entry; - errors.push({ packagePath: entryPath, packageName, error: String(err) }); - } - } - } - log2.debug( - { searchDirs: dirsToSearch, discovered: discovered.length, errors: errors.length }, - "plugin-loader: npm discovery scan complete" - ); - return { discovered, errors, sources: ["npm"] }; - }, - // ----------------------------------------------------------------------- - // loadManifest - // ----------------------------------------------------------------------- - async loadManifest(packagePath) { - const pkgJson = await readPackageJson(packagePath); - if (!pkgJson) return null; - const hasTaskcorePlugin = "taskcorePlugin" in pkgJson; - const packageName = typeof pkgJson["name"] === "string" ? pkgJson["name"] : ""; - const nameMatchesConvention = isPluginPackageName(packageName); - if (!hasTaskcorePlugin && !nameMatchesConvention) { - return null; - } - const manifestPath = resolveManifestPath(packagePath, pkgJson); - if (!manifestPath || !existsSync5(manifestPath)) return null; - return loadManifestFromPath(manifestPath); - }, - // ----------------------------------------------------------------------- - // installPlugin - // ----------------------------------------------------------------------- - async installPlugin(installOptions) { - const discovered = await fetchAndValidate(installOptions); - await registry2.install( - { - packageName: discovered.packageName, - packagePath: discovered.source === "local-filesystem" ? discovered.packagePath : void 0 - }, - discovered.manifest - ); - log2.info( - { - pluginId: discovered.manifest.id, - packageName: discovered.packageName, - version: discovered.version, - capabilities: discovered.manifest.capabilities - }, - "plugin-loader: plugin installed successfully" - ); - return discovered; - }, - // ----------------------------------------------------------------------- - // upgradePlugin - // ----------------------------------------------------------------------- - /** - * Upgrade an already-installed plugin to a newer version. - * - * This method: - * 1. Fetches and validates the new plugin package using `fetchAndValidate`. - * 2. Ensures the new manifest ID matches the existing plugin ID for safety. - * 3. Updates the plugin record in the registry with the new version and manifest. - * - * @param pluginId - The UUID of the plugin to upgrade. - * @param upgradeOptions - Options for the upgrade (packageName, localPath, version). - * @returns The old and new manifests, along with the discovery metadata. - * @throws {Error} If the plugin is not found or if the new manifest ID differs. - */ - async upgradePlugin(pluginId, upgradeOptions) { - const plugin = await registry2.getById(pluginId); - if (!plugin) throw new Error(`Plugin not found: ${pluginId}`); - const oldManifest = plugin.manifestJson; - const { - packageName = plugin.packageName, - // For local-path installs, fall back to the stored packagePath so - // `upgradePlugin` can re-read the manifest from disk without needing - // the caller to re-supply the path every time. - localPath = plugin.packagePath ?? void 0, - version: version3 - } = upgradeOptions; - log2.info( - { pluginId, packageName, version: version3, localPath }, - "plugin-loader: upgrading plugin" - ); - const discovered = await fetchAndValidate({ - packageName, - localPath, - version: version3, - installDir: localPluginDir - }); - const newManifest = discovered.manifest; - if (newManifest.id !== oldManifest.id) { - throw new Error( - `Upgrade failed: new manifest ID '${newManifest.id}' does not match existing plugin ID '${oldManifest.id}'` - ); - } - const oldCaps = new Set(oldManifest.capabilities ?? []); - const newCaps = newManifest.capabilities ?? []; - const escalated = newCaps.filter((c5) => !oldCaps.has(c5)); - if (escalated.length > 0) { - log2.warn( - { pluginId, escalated, oldVersion: oldManifest.version, newVersion: newManifest.version }, - "plugin-loader: upgrade introduces new capabilities \u2014 requires admin approval" - ); - throw new Error( - `Upgrade for "${pluginId}" introduces new capabilities that require approval: ${escalated.join(", ")}. The previous version declared [${[...oldCaps].join(", ")}]. Please review and approve the capability escalation before upgrading.` - ); - } - await registry2.update(pluginId, { - packageName: discovered.packageName, - version: discovered.version, - manifest: newManifest - }); - return { - oldManifest, - newManifest, - discovered - }; - }, - // ----------------------------------------------------------------------- - // isSupportedApiVersion - // ----------------------------------------------------------------------- - isSupportedApiVersion(apiVersion) { - return manifestValidator.getSupportedVersions().includes(apiVersion); - }, - // ----------------------------------------------------------------------- - // cleanupInstallArtifacts - // ----------------------------------------------------------------------- - async cleanupInstallArtifacts(plugin) { - const managedTargets = /* @__PURE__ */ new Set(); - const managedNodeModulesDir = resolveManagedInstallPackageDir(localPluginDir, plugin.packageName); - const directManagedDir = path46.join(localPluginDir, plugin.packageName); - managedTargets.add(managedNodeModulesDir); - if (isPathInsideDir(directManagedDir, localPluginDir)) { - managedTargets.add(directManagedDir); - } - if (plugin.packagePath && isPathInsideDir(plugin.packagePath, localPluginDir)) { - managedTargets.add(path46.resolve(plugin.packagePath)); - } - const packageJsonPath = path46.join(localPluginDir, "package.json"); - if (existsSync5(packageJsonPath)) { - try { - await execFileAsync6( - "npm", - ["uninstall", plugin.packageName, "--prefix", localPluginDir, "--ignore-scripts"], - { timeout: 12e4 } - ); - } catch (err) { - log2.warn( - { - pluginId: plugin.id, - pluginKey: plugin.pluginKey, - packageName: plugin.packageName, - err: err instanceof Error ? err.message : String(err) - }, - "plugin-loader: npm uninstall failed during cleanup, falling back to direct removal" - ); - } - } - for (const target of managedTargets) { - if (!existsSync5(target)) continue; - await rm(target, { recursive: true, force: true }); - } - }, - // ----------------------------------------------------------------------- - // getLocalPluginDir - // ----------------------------------------------------------------------- - getLocalPluginDir() { - return localPluginDir; - }, - // ----------------------------------------------------------------------- - // hasRuntimeServices - // ----------------------------------------------------------------------- - hasRuntimeServices() { - return runtimeServices !== void 0; - }, - // ----------------------------------------------------------------------- - // ----------------------------------------------------------------------- - // loadAll - // ----------------------------------------------------------------------- - /** - * loadAll — Loads and activates all plugins that are currently in 'ready' status. - * - * This method is typically called during server startup. It fetches all ready - * plugins from the registry and attempts to activate them in parallel using - * Promise.allSettled. Failures in individual plugins do not prevent others from loading. - * - * @returns A promise that resolves with summary statistics of the load operation. - */ - async loadAll() { - if (!runtimeServices) { - throw new Error( - "Cannot loadAll: no PluginRuntimeServices provided. Pass runtime services as the third argument to pluginLoader()." - ); - } - log2.info("plugin-loader: loading all ready plugins"); - const readyPlugins = await registry2.listByStatus("ready"); - if (readyPlugins.length === 0) { - log2.info("plugin-loader: no ready plugins to load"); - return { total: 0, succeeded: 0, failed: 0, results: [] }; - } - log2.info( - { count: readyPlugins.length }, - "plugin-loader: found ready plugins to load" - ); - const results = await Promise.allSettled( - readyPlugins.map((plugin) => activatePlugin(plugin)) - ); - const loadResults = results.map((r5, i5) => { - if (r5.status === "fulfilled") return r5.value; - return { - plugin: readyPlugins[i5], - success: false, - error: String(r5.reason), - registered: { worker: false, eventSubscriptions: 0, jobs: 0, webhooks: 0, tools: 0 } - }; - }); - const succeeded = loadResults.filter((r5) => r5.success).length; - const failed = loadResults.filter((r5) => !r5.success).length; - log2.info( - { - total: readyPlugins.length, - succeeded, - failed - }, - "plugin-loader: loadAll complete" - ); - return { - total: readyPlugins.length, - succeeded, - failed, - results: loadResults - }; - }, - // ----------------------------------------------------------------------- - // loadSingle - // ----------------------------------------------------------------------- - /** - * loadSingle — Loads and activates a single plugin by its ID. - * - * This method retrieves the plugin from the registry, ensures it's in a valid - * state, and then calls activatePlugin to start its worker and register its - * capabilities (tools, jobs, etc.). - * - * @param pluginId - The UUID of the plugin to load. - * @returns A promise that resolves with the result of the activation. - */ - async loadSingle(pluginId) { - if (!runtimeServices) { - throw new Error( - "Cannot loadSingle: no PluginRuntimeServices provided. Pass runtime services as the third argument to pluginLoader()." - ); - } - const plugin = await registry2.getById(pluginId); - if (!plugin) { - throw new Error(`Plugin not found: ${pluginId}`); - } - if (plugin.status === "installed") { - await runtimeServices.lifecycleManager.load(pluginId); - const updated = await registry2.getById(pluginId); - if (!updated) throw new Error(`Plugin not found after status update: ${pluginId}`); - return { - plugin: updated, - success: true, - registered: { worker: true, eventSubscriptions: 0, jobs: 0, webhooks: 0, tools: 0 } - }; - } - if (plugin.status !== "ready") { - throw new Error( - `Cannot load plugin in status '${plugin.status}'. Plugin must be in 'installed' or 'ready' status.` - ); - } - return activatePlugin(plugin); - }, - // ----------------------------------------------------------------------- - // unloadSingle - // ----------------------------------------------------------------------- - async unloadSingle(pluginId, pluginKey) { - if (!runtimeServices) { - throw new Error( - "Cannot unloadSingle: no PluginRuntimeServices provided." - ); - } - log2.info( - { pluginId, pluginKey }, - "plugin-loader: unloading single plugin" - ); - const { - workerManager, - eventBus, - jobScheduler, - toolDispatcher - } = runtimeServices; - try { - await jobScheduler.unregisterPlugin(pluginId); - } catch (err) { - log2.warn( - { pluginId, err: err instanceof Error ? err.message : String(err) }, - "plugin-loader: failed to unregister from job scheduler (best-effort)" - ); - } - eventBus.clearPlugin(pluginKey); - toolDispatcher.unregisterPluginTools(pluginKey); - try { - if (workerManager.isRunning(pluginId)) { - await workerManager.stopWorker(pluginId); - } - } catch (err) { - log2.warn( - { pluginId, err: err instanceof Error ? err.message : String(err) }, - "plugin-loader: failed to stop worker during unload (best-effort)" - ); - } - log2.info( - { pluginId, pluginKey }, - "plugin-loader: plugin unloaded successfully" - ); - }, - // ----------------------------------------------------------------------- - // shutdownAll - // ----------------------------------------------------------------------- - async shutdownAll() { - if (!runtimeServices) { - throw new Error( - "Cannot shutdownAll: no PluginRuntimeServices provided." - ); - } - log2.info("plugin-loader: shutting down all plugins"); - const { workerManager, jobScheduler } = runtimeServices; - jobScheduler.stop(); - await workerManager.stopAll(); - log2.info("plugin-loader: all plugins shut down"); - } - }; - async function activatePlugin(plugin) { - const manifest = plugin.manifestJson; - const pluginId = plugin.id; - const pluginKey = plugin.pluginKey; - const registered = { - worker: false, - eventSubscriptions: 0, - jobs: 0, - webhooks: 0, - tools: 0 - }; - if (!runtimeServices) { - return { - plugin, - success: false, - error: "No runtime services available", - registered - }; - } - const { - workerManager, - eventBus, - jobScheduler, - jobStore, - toolDispatcher, - lifecycleManager, - buildHostHandlers, - instanceInfo - } = runtimeServices; - try { - log2.info( - { pluginId, pluginKey, version: plugin.version }, - "plugin-loader: activating plugin" - ); - const workerEntrypoint = resolveWorkerEntrypoint(plugin, localPluginDir); - const hostHandlers = buildHostHandlers(pluginId, manifest); - let config3 = {}; - try { - const configRow = await registry2.getConfig(pluginId); - if (configRow && typeof configRow === "object" && "configJson" in configRow) { - config3 = configRow.configJson ?? {}; - } - } catch { - log2.debug({ pluginId }, "plugin-loader: no config found, using empty config"); - } - const workerOptions = { - entrypointPath: workerEntrypoint, - manifest, - config: config3, - instanceInfo, - apiVersion: manifest.apiVersion, - hostHandlers, - autoRestart: true - }; - if (plugin.packagePath && existsSync5(DEV_TSX_LOADER_PATH)) { - workerOptions.execArgv = ["--import", DEV_TSX_LOADER_PATH]; - } - await workerManager.startWorker(pluginId, workerOptions); - registered.worker = true; - log2.info( - { pluginId, pluginKey }, - "plugin-loader: worker started" - ); - const jobDeclarations = manifest.jobs ?? []; - if (jobDeclarations.length > 0) { - await jobStore.syncJobDeclarations(pluginId, jobDeclarations); - await jobScheduler.registerPlugin(pluginId); - registered.jobs = jobDeclarations.length; - log2.info( - { pluginId, pluginKey, jobs: jobDeclarations.length }, - "plugin-loader: job declarations synced and plugin registered with scheduler" - ); - } - const _scopedBus = eventBus.forPlugin(pluginKey); - registered.eventSubscriptions = eventBus.subscriptionCount(pluginKey); - log2.debug( - { pluginId, pluginKey }, - "plugin-loader: event bus scoped handle ready" - ); - const webhookDeclarations = manifest.webhooks ?? []; - registered.webhooks = webhookDeclarations.length; - if (webhookDeclarations.length > 0) { - log2.info( - { pluginId, pluginKey, webhooks: webhookDeclarations.length }, - "plugin-loader: webhook endpoints declared in manifest" - ); - } - const toolDeclarations = manifest.tools ?? []; - if (toolDeclarations.length > 0) { - toolDispatcher.registerPluginTools(pluginKey, manifest); - registered.tools = toolDeclarations.length; - log2.info( - { pluginId, pluginKey, tools: toolDeclarations.length }, - "plugin-loader: agent tools registered" - ); - } - log2.info( - { - pluginId, - pluginKey, - version: plugin.version, - registered - }, - "plugin-loader: plugin activated successfully" - ); - return { plugin, success: true, registered }; - } catch (err) { - const errorMessage = err instanceof Error ? err.message : String(err); - log2.error( - { pluginId, pluginKey, err: errorMessage }, - "plugin-loader: failed to activate plugin" - ); - try { - await lifecycleManager.markError(pluginId, `Activation failed: ${errorMessage}`); - } catch (markErr) { - log2.error( - { - pluginId, - err: markErr instanceof Error ? markErr.message : String(markErr) - }, - "plugin-loader: failed to mark plugin as error after activation failure" - ); - } - return { - plugin, - success: false, - error: errorMessage, - registered - }; - } - } -} -function resolveWorkerEntrypoint(plugin, localPluginDir) { - const manifest = plugin.manifestJson; - const workerRelPath = manifest.entrypoints.worker; - if (plugin.packagePath && existsSync5(plugin.packagePath)) { - const entrypoint = path46.resolve(plugin.packagePath, workerRelPath); - if (entrypoint.startsWith(path46.resolve(plugin.packagePath)) && existsSync5(entrypoint)) { - return entrypoint; - } - } - const packageName = plugin.packageName; - let packageDir; - if (packageName.startsWith("@")) { - const [scope, name] = packageName.split("/"); - packageDir = path46.join(localPluginDir, "node_modules", scope, name); - } else { - packageDir = path46.join(localPluginDir, "node_modules", packageName); - } - const directDir = path46.join(localPluginDir, packageName); - for (const dir of [packageDir, directDir]) { - const entrypoint = path46.resolve(dir, workerRelPath); - if (!entrypoint.startsWith(path46.resolve(dir))) { - continue; - } - if (existsSync5(entrypoint)) { - return entrypoint; - } - } - if (path46.isAbsolute(workerRelPath) && existsSync5(workerRelPath)) { - return workerRelPath; - } - throw new Error( - `Worker entrypoint not found for plugin "${plugin.pluginKey}". Checked: ${path46.resolve(packageDir, workerRelPath)}, ${path46.resolve(directDir, workerRelPath)}` - ); -} -function resolveManagedInstallPackageDir(localPluginDir, packageName) { - if (packageName.startsWith("@")) { - return path46.join(localPluginDir, "node_modules", ...packageName.split("/")); - } - return path46.join(localPluginDir, "node_modules", packageName); -} -function isPathInsideDir(candidatePath, parentDir) { - const resolvedCandidate = path46.resolve(candidatePath); - const resolvedParent = path46.resolve(parentDir); - const relative3 = path46.relative(resolvedParent, resolvedCandidate); - return relative3 === "" || !relative3.startsWith("..") && !path46.isAbsolute(relative3); -} - -// server/src/services/plugin-lifecycle.ts -var VALID_TRANSITIONS = { - installed: ["ready", "error", "uninstalled"], - ready: ["ready", "disabled", "error", "upgrade_pending", "uninstalled"], - disabled: ["ready", "uninstalled"], - error: ["ready", "uninstalled"], - upgrade_pending: ["ready", "error", "uninstalled"], - uninstalled: ["installed"] - // reinstall -}; -function isValidTransition(from, to) { - return VALID_TRANSITIONS[from]?.includes(to) ?? false; -} -function pluginLifecycleManager(db, options) { - let loaderArg; - let workerManager; - if (options && typeof options === "object" && "discoverAll" in options) { - loaderArg = options; - } else if (options && typeof options === "object") { - const opts = options; - loaderArg = opts.loader; - workerManager = opts.workerManager; - } - const registry2 = pluginRegistryService(db); - const pluginLoaderInstance = loaderArg ?? pluginLoader(db); - const emitter2 = new EventEmitter2(); - emitter2.setMaxListeners(100); - const log2 = logger.child({ service: "plugin-lifecycle" }); - async function requirePlugin(pluginId) { - const plugin = await registry2.getById(pluginId); - if (!plugin) throw notFound(`Plugin not found: ${pluginId}`); - return plugin; - } - function assertTransition2(plugin, to) { - if (!isValidTransition(plugin.status, to)) { - throw badRequest( - `Invalid lifecycle transition: ${plugin.status} \u2192 ${to} for plugin ${plugin.pluginKey}` - ); - } - } - async function transition(pluginId, to, lastError = null, existingPlugin) { - const plugin = existingPlugin ?? await requirePlugin(pluginId); - assertTransition2(plugin, to); - const previousStatus = plugin.status; - const updated = await registry2.updateStatus(pluginId, { - status: to, - lastError - }); - if (!updated) throw notFound(`Plugin not found after status update: ${pluginId}`); - const result = updated; - log2.info( - { pluginId, pluginKey: result.pluginKey, from: previousStatus, to }, - `plugin lifecycle: ${previousStatus} \u2192 ${to}` - ); - emitter2.emit("plugin.status_changed", { - pluginId, - pluginKey: result.pluginKey, - previousStatus, - newStatus: to - }); - return result; - } - function emitDomain(event, payload2) { - emitter2.emit(event, payload2); - } - async function stopWorkerIfRunning(pluginId, pluginKey) { - if (!workerManager) return; - if (!workerManager.isRunning(pluginId) && !workerManager.getWorker(pluginId)) return; - try { - await workerManager.stopWorker(pluginId); - log2.info({ pluginId, pluginKey }, "plugin lifecycle: worker stopped"); - emitDomain("plugin.worker_stopped", { pluginId, pluginKey }); - } catch (err) { - log2.warn( - { pluginId, pluginKey, err: err instanceof Error ? err.message : String(err) }, - "plugin lifecycle: failed to stop worker (best-effort)" - ); - } - } - async function activateReadyPlugin(pluginId) { - const supportsRuntimeActivation = typeof pluginLoaderInstance.hasRuntimeServices === "function" && typeof pluginLoaderInstance.loadSingle === "function"; - if (!supportsRuntimeActivation || !pluginLoaderInstance.hasRuntimeServices()) { - return; - } - const loadResult = await pluginLoaderInstance.loadSingle(pluginId); - if (!loadResult.success) { - throw new Error( - loadResult.error ?? `Failed to activate plugin ${loadResult.plugin.pluginKey}` - ); - } - } - async function deactivatePluginRuntime(pluginId, pluginKey) { - const supportsRuntimeDeactivation = typeof pluginLoaderInstance.hasRuntimeServices === "function" && typeof pluginLoaderInstance.unloadSingle === "function"; - if (supportsRuntimeDeactivation && pluginLoaderInstance.hasRuntimeServices()) { - await pluginLoaderInstance.unloadSingle(pluginId, pluginKey); - return; - } - await stopWorkerIfRunning(pluginId, pluginKey); - } - return { - // -- load ------------------------------------------------------------- - /** - * load — Transitions a plugin to 'ready' status and starts its worker. - * - * This method is called after a plugin has been successfully installed and - * validated. It marks the plugin as ready in the database and immediately - * triggers the plugin loader to start the worker process. - * - * @param pluginId - The UUID of the plugin to load. - * @returns The updated plugin record. - */ - async load(pluginId) { - const result = await transition(pluginId, "ready"); - await activateReadyPlugin(pluginId); - emitDomain("plugin.loaded", { - pluginId, - pluginKey: result.pluginKey - }); - emitDomain("plugin.enabled", { - pluginId, - pluginKey: result.pluginKey - }); - return result; - }, - // -- enable ----------------------------------------------------------- - /** - * enable — Re-enables a plugin that was previously in an error or upgrade state. - * - * Similar to load(), this method transitions the plugin to 'ready' and starts - * its worker, but it specifically targets plugins that are currently disabled. - * - * @param pluginId - The UUID of the plugin to enable. - * @returns The updated plugin record. - */ - async enable(pluginId) { - const plugin = await requirePlugin(pluginId); - if (plugin.status !== "disabled" && plugin.status !== "error" && plugin.status !== "upgrade_pending") { - throw badRequest( - `Cannot enable plugin in status '${plugin.status}'. Plugin must be in 'disabled', 'error', or 'upgrade_pending' status to be enabled.` - ); - } - const result = await transition(pluginId, "ready", null, plugin); - await activateReadyPlugin(pluginId); - emitDomain("plugin.enabled", { - pluginId, - pluginKey: result.pluginKey - }); - return result; - }, - // -- disable ---------------------------------------------------------- - async disable(pluginId, reason) { - const plugin = await requirePlugin(pluginId); - if (plugin.status !== "ready") { - throw badRequest( - `Cannot disable plugin in status '${plugin.status}'. Plugin must be in 'ready' status to be disabled.` - ); - } - await deactivatePluginRuntime(pluginId, plugin.pluginKey); - const result = await transition(pluginId, "disabled", reason ?? null, plugin); - emitDomain("plugin.disabled", { - pluginId, - pluginKey: result.pluginKey, - reason - }); - return result; - }, - // -- unload ----------------------------------------------------------- - async unload(pluginId, removeData = false) { - const plugin = await requirePlugin(pluginId); - if (plugin.status === "uninstalled") { - if (removeData) { - await pluginLoaderInstance.cleanupInstallArtifacts(plugin); - const deleted = await registry2.uninstall(pluginId, true); - log2.info( - { pluginId, pluginKey: plugin.pluginKey }, - "plugin lifecycle: hard-deleted already-uninstalled plugin" - ); - emitDomain("plugin.unloaded", { - pluginId, - pluginKey: plugin.pluginKey, - removeData: true - }); - return deleted; - } - throw badRequest( - `Plugin ${plugin.pluginKey} is already uninstalled. Use removeData=true to permanently delete it.` - ); - } - await deactivatePluginRuntime(pluginId, plugin.pluginKey); - await pluginLoaderInstance.cleanupInstallArtifacts(plugin); - const result = await registry2.uninstall(pluginId, removeData); - log2.info( - { pluginId, pluginKey: plugin.pluginKey, removeData }, - `plugin lifecycle: ${plugin.status} \u2192 uninstalled${removeData ? " (hard delete)" : ""}` - ); - emitter2.emit("plugin.status_changed", { - pluginId, - pluginKey: plugin.pluginKey, - previousStatus: plugin.status, - newStatus: "uninstalled" - }); - emitDomain("plugin.unloaded", { - pluginId, - pluginKey: plugin.pluginKey, - removeData - }); - return result; - }, - // -- markError -------------------------------------------------------- - async markError(pluginId, error50) { - const plugin = await requirePlugin(pluginId); - await deactivatePluginRuntime(pluginId, plugin.pluginKey); - const result = await transition(pluginId, "error", error50, plugin); - emitDomain("plugin.error", { - pluginId, - pluginKey: result.pluginKey, - error: error50 - }); - return result; - }, - // -- markUpgradePending ----------------------------------------------- - async markUpgradePending(pluginId) { - const plugin = await requirePlugin(pluginId); - await deactivatePluginRuntime(pluginId, plugin.pluginKey); - const result = await transition(pluginId, "upgrade_pending", null, plugin); - emitDomain("plugin.upgrade_pending", { - pluginId, - pluginKey: result.pluginKey - }); - return result; - }, - // -- upgrade ---------------------------------------------------------- - /** - * Upgrade a plugin to a newer version by performing a package update and - * managing the lifecycle state transition. - * - * Following PLUGIN_SPEC.md §25.3, the upgrade process: - * 1. Stops the current worker process (if running). - * 2. Fetches and validates the new plugin package via the `PluginLoader`. - * 3. Compares the capabilities declared in the new manifest against the old one. - * 4. If new capabilities are added, transitions the plugin to `upgrade_pending` - * to await operator approval (worker stays stopped). - * 5. If no new capabilities are added, transitions the plugin back to `ready` - * with the updated version and manifest metadata. - * - * @param pluginId - The UUID of the plugin to upgrade. - * @param version - Optional target version specifier. - * @returns The updated `PluginRecord`. - * @throws {BadRequest} If the plugin is not in a ready or upgrade_pending state. - */ - async upgrade(pluginId, version3) { - const plugin = await requirePlugin(pluginId); - if (plugin.status !== "ready" && plugin.status !== "upgrade_pending") { - throw badRequest( - `Cannot upgrade plugin in status '${plugin.status}'. Plugin must be in 'ready' or 'upgrade_pending' status to be upgraded.` - ); - } - log2.info( - { pluginId, pluginKey: plugin.pluginKey, targetVersion: version3 }, - "plugin lifecycle: upgrade requested" - ); - await deactivatePluginRuntime(pluginId, plugin.pluginKey); - const { oldManifest, newManifest, discovered } = await pluginLoaderInstance.upgradePlugin(pluginId, { version: version3 }); - log2.info( - { - pluginId, - pluginKey: plugin.pluginKey, - oldVersion: oldManifest.version, - newVersion: newManifest.version - }, - "plugin lifecycle: package upgraded on disk" - ); - const addedCaps = newManifest.capabilities.filter( - (cap) => !oldManifest.capabilities.includes(cap) - ); - if (addedCaps.length > 0) { - log2.info( - { pluginId, pluginKey: plugin.pluginKey, addedCaps }, - "plugin lifecycle: new capabilities detected, transitioning to upgrade_pending" - ); - const result = await transition(pluginId, "upgrade_pending", null, plugin); - emitDomain("plugin.upgrade_pending", { - pluginId, - pluginKey: result.pluginKey - }); - return result; - } else { - const result = await transition(pluginId, "ready", null, { - ...plugin, - version: discovered.version, - manifestJson: newManifest - }); - await activateReadyPlugin(pluginId); - emitDomain("plugin.loaded", { - pluginId, - pluginKey: result.pluginKey - }); - emitDomain("plugin.enabled", { - pluginId, - pluginKey: result.pluginKey - }); - return result; - } - }, - // -- startWorker ------------------------------------------------------ - async startWorker(pluginId, options2) { - if (!workerManager) { - throw badRequest( - "Cannot start worker: no PluginWorkerManager is configured. Provide a workerManager option when constructing the lifecycle manager." - ); - } - const plugin = await requirePlugin(pluginId); - if (plugin.status !== "ready") { - throw badRequest( - `Cannot start worker for plugin in status '${plugin.status}'. Plugin must be in 'ready' status.` - ); - } - log2.info( - { pluginId, pluginKey: plugin.pluginKey }, - "plugin lifecycle: starting worker" - ); - await workerManager.startWorker(pluginId, options2); - emitDomain("plugin.worker_started", { - pluginId, - pluginKey: plugin.pluginKey - }); - log2.info( - { pluginId, pluginKey: plugin.pluginKey }, - "plugin lifecycle: worker started" - ); - }, - // -- stopWorker ------------------------------------------------------- - async stopWorker(pluginId) { - if (!workerManager) return; - const plugin = await requirePlugin(pluginId); - await stopWorkerIfRunning(pluginId, plugin.pluginKey); - }, - // -- restartWorker ---------------------------------------------------- - async restartWorker(pluginId) { - if (!workerManager) { - throw badRequest( - "Cannot restart worker: no PluginWorkerManager is configured." - ); - } - const plugin = await requirePlugin(pluginId); - if (plugin.status !== "ready") { - throw badRequest( - `Cannot restart worker for plugin in status '${plugin.status}'. Plugin must be in 'ready' status.` - ); - } - const handle = workerManager.getWorker(pluginId); - if (!handle) { - throw badRequest( - `Cannot restart worker for plugin "${plugin.pluginKey}": no worker is running.` - ); - } - log2.info( - { pluginId, pluginKey: plugin.pluginKey }, - "plugin lifecycle: restarting worker" - ); - await handle.restart(); - emitDomain("plugin.worker_stopped", { pluginId, pluginKey: plugin.pluginKey }); - emitDomain("plugin.worker_started", { pluginId, pluginKey: plugin.pluginKey }); - log2.info( - { pluginId, pluginKey: plugin.pluginKey }, - "plugin lifecycle: worker restarted" - ); - }, - // -- getStatus -------------------------------------------------------- - async getStatus(pluginId) { - const plugin = await registry2.getById(pluginId); - return plugin?.status ?? null; - }, - // -- canTransition ---------------------------------------------------- - async canTransition(pluginId, to) { - const plugin = await registry2.getById(pluginId); - if (!plugin) return false; - return isValidTransition(plugin.status, to); - }, - // -- Event subscriptions ---------------------------------------------- - on(event, listener) { - emitter2.on(event, listener); - }, - off(event, listener) { - emitter2.off(event, listener); - }, - once(event, listener) { - emitter2.once(event, listener); - } - }; -} - -// packages/plugins/sdk/dist/protocol.js -var JSONRPC_VERSION = "2.0"; -var JSONRPC_ERROR_CODES = { - /** Invalid JSON was received by the server. */ - PARSE_ERROR: -32700, - /** The JSON sent is not a valid Request object. */ - INVALID_REQUEST: -32600, - /** The method does not exist or is not available. */ - METHOD_NOT_FOUND: -32601, - /** Invalid method parameter(s). */ - INVALID_PARAMS: -32602, - /** Internal JSON-RPC error. */ - INTERNAL_ERROR: -32603 -}; -var PLUGIN_RPC_ERROR_CODES = { - /** The worker process is not running or not reachable. */ - WORKER_UNAVAILABLE: -32e3, - /** The plugin does not have the required capability for this operation. */ - CAPABILITY_DENIED: -32001, - /** The worker reported an unhandled error during method execution. */ - WORKER_ERROR: -32002, - /** The method call timed out waiting for the worker response. */ - TIMEOUT: -32003, - /** The worker does not implement the requested optional method. */ - METHOD_NOT_IMPLEMENTED: -32004, - /** A catch-all for errors that do not fit other categories. */ - UNKNOWN: -32099 -}; -var _nextId = 1; -var MAX_SAFE_RPC_ID = Number.MAX_SAFE_INTEGER - 1; -function createRequest(method, params, id) { - if (_nextId >= MAX_SAFE_RPC_ID) { - _nextId = 1; - } - return { - jsonrpc: JSONRPC_VERSION, - id: id ?? _nextId++, - method, - params - }; -} -function createErrorResponse(id, code, message2, data2) { - const response = { - jsonrpc: JSONRPC_VERSION, - id, - error: data2 !== void 0 ? { code, message: message2, data: data2 } : { code, message: message2 } - }; - return response; -} -function isJsonRpcRequest(value) { - if (typeof value !== "object" || value === null) - return false; - const obj = value; - return obj.jsonrpc === JSONRPC_VERSION && typeof obj.method === "string" && "id" in obj && obj.id !== void 0 && obj.id !== null; -} -function isJsonRpcNotification(value) { - if (typeof value !== "object" || value === null) - return false; - const obj = value; - return obj.jsonrpc === JSONRPC_VERSION && typeof obj.method === "string" && !("id" in obj); -} -function isJsonRpcResponse(value) { - if (typeof value !== "object" || value === null) - return false; - const obj = value; - return obj.jsonrpc === JSONRPC_VERSION && "id" in obj && ("result" in obj || "error" in obj); -} -function isJsonRpcSuccessResponse(response) { - return "result" in response && !("error" in response && response.error !== void 0); -} -var MESSAGE_DELIMITER = "\n"; -function serializeMessage(message2) { - return JSON.stringify(message2) + MESSAGE_DELIMITER; -} -function parseMessage(line3) { - const trimmed = line3.trim(); - if (trimmed.length === 0) { - throw new JsonRpcParseError("Empty message"); - } - let parsed; - try { - parsed = JSON.parse(trimmed); - } catch { - throw new JsonRpcParseError(`Invalid JSON: ${trimmed.slice(0, 200)}`); - } - if (typeof parsed !== "object" || parsed === null) { - throw new JsonRpcParseError("Message must be a JSON object"); - } - const obj = parsed; - if (obj.jsonrpc !== JSONRPC_VERSION) { - throw new JsonRpcParseError(`Invalid or missing jsonrpc version (expected "${JSONRPC_VERSION}", got ${JSON.stringify(obj.jsonrpc)})`); - } - return parsed; -} -var JsonRpcParseError = class extends Error { - name = "JsonRpcParseError"; - constructor(message2) { - super(message2); - } -}; -var JsonRpcCallError = class extends Error { - name = "JsonRpcCallError"; - /** The JSON-RPC error code. */ - code; - /** Optional structured error data from the response. */ - data; - constructor(error50) { - super(error50.message); - this.code = error50.code; - this.data = error50.data; - } -}; - -// packages/plugins/sdk/dist/host-client-factory.js -var CapabilityDeniedError = class extends Error { - name = "CapabilityDeniedError"; - code = PLUGIN_RPC_ERROR_CODES.CAPABILITY_DENIED; - constructor(pluginId, method, capability) { - super(`Plugin "${pluginId}" is missing required capability "${capability}" for method "${method}"`); - } -}; -var METHOD_CAPABILITY_MAP = { - // Config — always allowed - "config.get": null, - // State - "state.get": "plugin.state.read", - "state.set": "plugin.state.write", - "state.delete": "plugin.state.write", - // Entities — no specific capability required (plugin-scoped by design) - "entities.upsert": null, - "entities.list": null, - // Events - "events.emit": "events.emit", - "events.subscribe": "events.subscribe", - // HTTP - "http.fetch": "http.outbound", - // Secrets - "secrets.resolve": "secrets.read-ref", - // Activity - "activity.log": "activity.log.write", - // Metrics - "metrics.write": "metrics.write", - // Telemetry - "telemetry.track": "telemetry.track", - // Logger — always allowed - "log": null, - // Companies - "companies.list": "companies.read", - "companies.get": "companies.read", - // Projects - "projects.list": "projects.read", - "projects.get": "projects.read", - "projects.listWorkspaces": "project.workspaces.read", - "projects.getPrimaryWorkspace": "project.workspaces.read", - "projects.getWorkspaceForIssue": "project.workspaces.read", - // Issues - "issues.list": "issues.read", - "issues.get": "issues.read", - "issues.create": "issues.create", - "issues.update": "issues.update", - "issues.listComments": "issue.comments.read", - "issues.createComment": "issue.comments.create", - // Issue Documents - "issues.documents.list": "issue.documents.read", - "issues.documents.get": "issue.documents.read", - "issues.documents.upsert": "issue.documents.write", - "issues.documents.delete": "issue.documents.write", - // Agents - "agents.list": "agents.read", - "agents.get": "agents.read", - "agents.pause": "agents.pause", - "agents.resume": "agents.resume", - "agents.invoke": "agents.invoke", - // Agent Sessions - "agents.sessions.create": "agent.sessions.create", - "agents.sessions.list": "agent.sessions.list", - "agents.sessions.sendMessage": "agent.sessions.send", - "agents.sessions.close": "agent.sessions.close", - // Goals - "goals.list": "goals.read", - "goals.get": "goals.read", - "goals.create": "goals.create", - "goals.update": "goals.update" -}; -function createHostClientHandlers(options) { - const { pluginId, services } = options; - const capabilitySet = new Set(options.capabilities); - function requireCapability(method) { - const required2 = METHOD_CAPABILITY_MAP[method]; - if (required2 === null) - return; - if (capabilitySet.has(required2)) - return; - throw new CapabilityDeniedError(pluginId, method, required2); - } - function gated(method, handler) { - return async (params) => { - requireCapability(method); - return handler(params); - }; - } - return { - // Config - "config.get": gated("config.get", async () => { - return services.config.get(); - }), - // State - "state.get": gated("state.get", async (params) => { - return services.state.get(params); - }), - "state.set": gated("state.set", async (params) => { - return services.state.set(params); - }), - "state.delete": gated("state.delete", async (params) => { - return services.state.delete(params); - }), - // Entities - "entities.upsert": gated("entities.upsert", async (params) => { - return services.entities.upsert(params); - }), - "entities.list": gated("entities.list", async (params) => { - return services.entities.list(params); - }), - // Events - "events.emit": gated("events.emit", async (params) => { - return services.events.emit(params); - }), - "events.subscribe": gated("events.subscribe", async (params) => { - return services.events.subscribe(params); - }), - // HTTP - "http.fetch": gated("http.fetch", async (params) => { - return services.http.fetch(params); - }), - // Secrets - "secrets.resolve": gated("secrets.resolve", async (params) => { - return services.secrets.resolve(params); - }), - // Activity - "activity.log": gated("activity.log", async (params) => { - return services.activity.log(params); - }), - // Metrics - "metrics.write": gated("metrics.write", async (params) => { - return services.metrics.write(params); - }), - // Telemetry - "telemetry.track": gated("telemetry.track", async (params) => { - return services.telemetry.track(params); - }), - // Logger - "log": gated("log", async (params) => { - return services.logger.log(params); - }), - // Companies - "companies.list": gated("companies.list", async (params) => { - return services.companies.list(params); - }), - "companies.get": gated("companies.get", async (params) => { - return services.companies.get(params); - }), - // Projects - "projects.list": gated("projects.list", async (params) => { - return services.projects.list(params); - }), - "projects.get": gated("projects.get", async (params) => { - return services.projects.get(params); - }), - "projects.listWorkspaces": gated("projects.listWorkspaces", async (params) => { - return services.projects.listWorkspaces(params); - }), - "projects.getPrimaryWorkspace": gated("projects.getPrimaryWorkspace", async (params) => { - return services.projects.getPrimaryWorkspace(params); - }), - "projects.getWorkspaceForIssue": gated("projects.getWorkspaceForIssue", async (params) => { - return services.projects.getWorkspaceForIssue(params); - }), - // Issues - "issues.list": gated("issues.list", async (params) => { - return services.issues.list(params); - }), - "issues.get": gated("issues.get", async (params) => { - return services.issues.get(params); - }), - "issues.create": gated("issues.create", async (params) => { - return services.issues.create(params); - }), - "issues.update": gated("issues.update", async (params) => { - return services.issues.update(params); - }), - "issues.listComments": gated("issues.listComments", async (params) => { - return services.issues.listComments(params); - }), - "issues.createComment": gated("issues.createComment", async (params) => { - return services.issues.createComment(params); - }), - // Issue Documents - "issues.documents.list": gated("issues.documents.list", async (params) => { - return services.issueDocuments.list(params); - }), - "issues.documents.get": gated("issues.documents.get", async (params) => { - return services.issueDocuments.get(params); - }), - "issues.documents.upsert": gated("issues.documents.upsert", async (params) => { - return services.issueDocuments.upsert(params); - }), - "issues.documents.delete": gated("issues.documents.delete", async (params) => { - return services.issueDocuments.delete(params); - }), - // Agents - "agents.list": gated("agents.list", async (params) => { - return services.agents.list(params); - }), - "agents.get": gated("agents.get", async (params) => { - return services.agents.get(params); - }), - "agents.pause": gated("agents.pause", async (params) => { - return services.agents.pause(params); - }), - "agents.resume": gated("agents.resume", async (params) => { - return services.agents.resume(params); - }), - "agents.invoke": gated("agents.invoke", async (params) => { - return services.agents.invoke(params); - }), - // Agent Sessions - "agents.sessions.create": gated("agents.sessions.create", async (params) => { - return services.agentSessions.create(params); - }), - "agents.sessions.list": gated("agents.sessions.list", async (params) => { - return services.agentSessions.list(params); - }), - "agents.sessions.sendMessage": gated("agents.sessions.sendMessage", async (params) => { - return services.agentSessions.sendMessage(params); - }), - "agents.sessions.close": gated("agents.sessions.close", async (params) => { - return services.agentSessions.close(params); - }), - // Goals - "goals.list": gated("goals.list", async (params) => { - return services.goals.list(params); - }), - "goals.get": gated("goals.get", async (params) => { - return services.goals.get(params); - }), - "goals.create": gated("goals.create", async (params) => { - return services.goals.create(params); - }), - "goals.update": gated("goals.update", async (params) => { - return services.goals.update(params); - }) - }; -} - -// server/src/services/plugin-config-validator.ts -var import_ajv = __toESM(require_ajv(), 1); -var import_ajv_formats = __toESM(require_dist2(), 1); -function validateInstanceConfig(configJson, schema2) { - const AjvCtor = import_ajv.default.default ?? import_ajv.default; - const ajv = new AjvCtor({ allErrors: true }); - const applyFormats = import_ajv_formats.default.default ?? import_ajv_formats.default; - applyFormats(ajv); - ajv.addFormat("secret-ref", { validate: () => true }); - const validate2 = ajv.compile(schema2); - const valid = validate2(configJson); - if (valid) { - return { valid: true }; - } - const errors = (validate2.errors ?? []).map((err) => ({ - field: err.instancePath || "/", - message: err.message ?? "validation failed" - })); - return { valid: false, errors }; -} - -// server/src/routes/plugins.ts -var UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i; -var __dirname3 = path47.dirname(fileURLToPath18(import.meta.url)); -var REPO_ROOT = path47.resolve(__dirname3, "../../.."); -var BUNDLED_PLUGIN_EXAMPLES = [ - { - packageName: "@taskcore/plugin-hello-world-example", - pluginKey: "taskcore.hello-world-example", - displayName: "Hello World Widget (Example)", - description: "Reference UI plugin that adds a simple Hello World widget to the Taskcore dashboard.", - localPath: "packages/plugins/examples/plugin-hello-world-example", - tag: "example" - }, - { - packageName: "@taskcore/plugin-file-browser-example", - pluginKey: "taskcore-file-browser-example", - displayName: "File Browser (Example)", - description: "Example plugin that adds a Files link in project navigation plus a project detail file browser.", - localPath: "packages/plugins/examples/plugin-file-browser-example", - tag: "example" - }, - { - packageName: "@taskcore/plugin-kitchen-sink-example", - pluginKey: "taskcore-kitchen-sink-example", - displayName: "Kitchen Sink (Example)", - description: "Reference plugin that demonstrates the current Taskcore plugin API surface, bridge flows, UI extension surfaces, jobs, webhooks, tools, streams, and trusted local workspace/process demos.", - localPath: "packages/plugins/examples/plugin-kitchen-sink-example", - tag: "example" - } -]; -function listBundledPluginExamples() { - return BUNDLED_PLUGIN_EXAMPLES.flatMap((plugin) => { - const absoluteLocalPath = path47.resolve(REPO_ROOT, plugin.localPath); - if (!existsSync6(absoluteLocalPath)) return []; - return [{ ...plugin, localPath: absoluteLocalPath }]; - }); -} -async function resolvePlugin(registry2, pluginId) { - const isUuid2 = UUID_REGEX.test(pluginId); - const isScopedPackageKey = pluginId.startsWith("@") || pluginId.includes("/"); - if (isScopedPackageKey && !isUuid2) { - return registry2.getByKey(pluginId); - } - try { - const byId = await registry2.getById(pluginId); - if (byId) return byId; - } catch (error50) { - const maybeCode = typeof error50 === "object" && error50 !== null && "code" in error50 ? error50.code : void 0; - if (maybeCode !== "22P02") { - throw error50; - } - } - return registry2.getByKey(pluginId); -} -function pluginRoutes(db, loader, jobDeps, webhookDeps, toolDeps, bridgeDeps) { - const router2 = (0, import_express22.Router)(); - const registry2 = pluginRegistryService(db); - const lifecycle = pluginLifecycleManager(db, { - loader, - workerManager: bridgeDeps?.workerManager ?? webhookDeps?.workerManager - }); - async function resolvePluginAuditCompanyIds(req) { - if (typeof db.select === "function") { - const rows = await db.select({ id: companies.id }).from(companies); - return rows.map((row) => row.id); - } - if (req.actor.type === "agent" && req.actor.companyId) { - return [req.actor.companyId]; - } - if (req.actor.type === "board") { - return req.actor.companyIds ?? []; - } - return []; - } - async function logPluginMutationActivity(req, action, entityId, details) { - const companyIds = await resolvePluginAuditCompanyIds(req); - if (companyIds.length === 0) return; - const actor = getActorInfo(req); - await Promise.all(companyIds.map((companyId) => logActivity(db, { - companyId, - actorType: actor.actorType, - actorId: actor.actorId, - agentId: actor.agentId, - runId: actor.runId, - action, - entityType: "plugin", - entityId, - details - }))); - } - router2.get("/plugins", async (req, res) => { - assertBoard(req); - const rawStatus = req.query.status; - if (rawStatus !== void 0) { - if (typeof rawStatus !== "string" || !PLUGIN_STATUSES.includes(rawStatus)) { - res.status(400).json({ - error: `Invalid status '${String(rawStatus)}'. Must be one of: ${PLUGIN_STATUSES.join(", ")}` - }); - return; - } - } - const status = rawStatus; - const plugins2 = status ? await registry2.listByStatus(status) : await registry2.listInstalled(); - res.json(plugins2); - }); - router2.get("/plugins/examples", async (req, res) => { - assertBoard(req); - res.json(listBundledPluginExamples()); - }); - router2.get("/plugins/ui-contributions", async (req, res) => { - assertBoard(req); - const plugins2 = await registry2.listByStatus("ready"); - const contributions = plugins2.map((plugin) => { - const manifest = plugin.manifestJson; - if (!manifest) return null; - const uiMetadata = getPluginUiContributionMetadata(manifest); - if (!uiMetadata) return null; - return { - pluginId: plugin.id, - pluginKey: plugin.pluginKey, - displayName: manifest.displayName, - version: plugin.version, - updatedAt: plugin.updatedAt.toISOString(), - uiEntryFile: uiMetadata.uiEntryFile, - slots: uiMetadata.slots, - launchers: uiMetadata.launchers - }; - }).filter((item) => item !== null); - res.json(contributions); - }); - router2.get("/plugins/tools", async (req, res) => { - assertBoard(req); - if (!toolDeps) { - res.status(501).json({ error: "Plugin tool dispatch is not enabled" }); - return; - } - const pluginId = req.query.pluginId; - const filter = pluginId ? { pluginId } : void 0; - const tools = toolDeps.toolDispatcher.listToolsForAgent(filter); - res.json(tools); - }); - router2.post("/plugins/tools/execute", async (req, res) => { - assertBoard(req); - if (!toolDeps) { - res.status(501).json({ error: "Plugin tool dispatch is not enabled" }); - return; - } - const body = req.body; - if (!body) { - res.status(400).json({ error: "Request body is required" }); - return; - } - const { tool, parameters, runContext } = body; - if (!tool || typeof tool !== "string") { - res.status(400).json({ error: '"tool" is required and must be a string' }); - return; - } - if (!runContext || typeof runContext !== "object") { - res.status(400).json({ error: '"runContext" is required and must be an object' }); - return; - } - if (!runContext.agentId || !runContext.runId || !runContext.companyId || !runContext.projectId) { - res.status(400).json({ - error: '"runContext" must include agentId, runId, companyId, and projectId' - }); - return; - } - assertCompanyAccess(req, runContext.companyId); - const registeredTool = toolDeps.toolDispatcher.getTool(tool); - if (!registeredTool) { - res.status(404).json({ error: `Tool "${tool}" not found` }); - return; - } - try { - const result = await toolDeps.toolDispatcher.executeTool( - tool, - parameters ?? {}, - runContext - ); - res.json(result); - } catch (err) { - const message2 = err instanceof Error ? err.message : String(err); - if (message2.includes("not running") || message2.includes("worker")) { - res.status(502).json({ error: message2 }); - } else { - res.status(500).json({ error: message2 }); - } - } - }); - router2.post("/plugins/install", async (req, res) => { - assertBoard(req); - const { packageName, version: version3, isLocalPath } = req.body; - if (!packageName || typeof packageName !== "string") { - res.status(400).json({ error: "packageName is required and must be a string" }); - return; - } - if (version3 !== void 0 && typeof version3 !== "string") { - res.status(400).json({ error: "version must be a string if provided" }); - return; - } - if (isLocalPath !== void 0 && typeof isLocalPath !== "boolean") { - res.status(400).json({ error: "isLocalPath must be a boolean if provided" }); - return; - } - const trimmedPackage = packageName.trim(); - if (trimmedPackage.length === 0) { - res.status(400).json({ error: "packageName cannot be empty" }); - return; - } - if (!isLocalPath && /[<>:"|?*]/.test(trimmedPackage)) { - res.status(400).json({ error: "packageName contains invalid characters" }); - return; - } - try { - const installOptions = isLocalPath ? { localPath: trimmedPackage } : { packageName: trimmedPackage, version: version3?.trim() }; - const discovered = await loader.installPlugin(installOptions); - if (!discovered.manifest) { - res.status(500).json({ error: "Plugin installed but manifest is missing" }); - return; - } - const existingPlugin = await registry2.getByKey(discovered.manifest.id); - if (existingPlugin) { - await lifecycle.load(existingPlugin.id); - const updated = await registry2.getById(existingPlugin.id); - await logPluginMutationActivity(req, "plugin.installed", existingPlugin.id, { - pluginId: existingPlugin.id, - pluginKey: existingPlugin.pluginKey, - packageName: updated?.packageName ?? existingPlugin.packageName, - version: updated?.version ?? existingPlugin.version, - source: isLocalPath ? "local_path" : "npm" - }); - publishGlobalLiveEvent({ type: "plugin.ui.updated", payload: { pluginId: existingPlugin.id, action: "installed" } }); - res.json(updated); - } else { - res.status(500).json({ error: "Plugin installed but not found in registry" }); - } - } catch (err) { - const message2 = err instanceof Error ? err.message : String(err); - res.status(400).json({ error: message2 }); - } - }); - function mapRpcErrorToBridgeError(err) { - if (err instanceof JsonRpcCallError) { - switch (err.code) { - case PLUGIN_RPC_ERROR_CODES.WORKER_UNAVAILABLE: - return { - code: "WORKER_UNAVAILABLE", - message: err.message, - details: err.data - }; - case PLUGIN_RPC_ERROR_CODES.CAPABILITY_DENIED: - return { - code: "CAPABILITY_DENIED", - message: err.message, - details: err.data - }; - case PLUGIN_RPC_ERROR_CODES.TIMEOUT: - return { - code: "TIMEOUT", - message: err.message, - details: err.data - }; - case PLUGIN_RPC_ERROR_CODES.WORKER_ERROR: - return { - code: "WORKER_ERROR", - message: err.message, - details: err.data - }; - default: - return { - code: "UNKNOWN", - message: err.message, - details: err.data - }; - } - } - const message2 = err instanceof Error ? err.message : String(err); - if (message2.includes("not running") || message2.includes("not registered")) { - return { - code: "WORKER_UNAVAILABLE", - message: message2 - }; - } - return { - code: "UNKNOWN", - message: message2 - }; - } - router2.post("/plugins/:pluginId/bridge/data", async (req, res) => { - assertBoard(req); - if (!bridgeDeps) { - res.status(501).json({ error: "Plugin bridge is not enabled" }); - return; - } - const { pluginId } = req.params; - const plugin = await resolvePlugin(registry2, pluginId); - if (!plugin) { - res.status(404).json({ error: "Plugin not found" }); - return; - } - if (plugin.status !== "ready") { - const bridgeError = { - code: "WORKER_UNAVAILABLE", - message: `Plugin is not ready (current status: ${plugin.status})` - }; - res.status(502).json(bridgeError); - return; - } - const body = req.body; - if (!body || !body.key || typeof body.key !== "string") { - res.status(400).json({ error: '"key" is required and must be a string' }); - return; - } - if (body.companyId) { - assertCompanyAccess(req, body.companyId); - } - try { - const result = await bridgeDeps.workerManager.call( - plugin.id, - "getData", - { - key: body.key, - params: body.params ?? {}, - renderEnvironment: body.renderEnvironment ?? null - } - ); - res.json({ data: result }); - } catch (err) { - const bridgeError = mapRpcErrorToBridgeError(err); - res.status(502).json(bridgeError); - } - }); - router2.post("/plugins/:pluginId/bridge/action", async (req, res) => { - assertBoard(req); - if (!bridgeDeps) { - res.status(501).json({ error: "Plugin bridge is not enabled" }); - return; - } - const { pluginId } = req.params; - const plugin = await resolvePlugin(registry2, pluginId); - if (!plugin) { - res.status(404).json({ error: "Plugin not found" }); - return; - } - if (plugin.status !== "ready") { - const bridgeError = { - code: "WORKER_UNAVAILABLE", - message: `Plugin is not ready (current status: ${plugin.status})` - }; - res.status(502).json(bridgeError); - return; - } - const body = req.body; - if (!body || !body.key || typeof body.key !== "string") { - res.status(400).json({ error: '"key" is required and must be a string' }); - return; - } - if (body.companyId) { - assertCompanyAccess(req, body.companyId); - } - try { - const result = await bridgeDeps.workerManager.call( - plugin.id, - "performAction", - { - key: body.key, - params: body.params ?? {}, - renderEnvironment: body.renderEnvironment ?? null - } - ); - res.json({ data: result }); - } catch (err) { - const bridgeError = mapRpcErrorToBridgeError(err); - res.status(502).json(bridgeError); - } - }); - router2.post("/plugins/:pluginId/data/:key", async (req, res) => { - assertBoard(req); - if (!bridgeDeps) { - res.status(501).json({ error: "Plugin bridge is not enabled" }); - return; - } - const { pluginId, key } = req.params; - const plugin = await resolvePlugin(registry2, pluginId); - if (!plugin) { - res.status(404).json({ error: "Plugin not found" }); - return; - } - if (plugin.status !== "ready") { - const bridgeError = { - code: "WORKER_UNAVAILABLE", - message: `Plugin is not ready (current status: ${plugin.status})` - }; - res.status(502).json(bridgeError); - return; - } - const body = req.body; - if (body?.companyId) { - assertCompanyAccess(req, body.companyId); - } - try { - const result = await bridgeDeps.workerManager.call( - plugin.id, - "getData", - { - key, - params: body?.params ?? {}, - renderEnvironment: body?.renderEnvironment ?? null - } - ); - res.json({ data: result }); - } catch (err) { - const bridgeError = mapRpcErrorToBridgeError(err); - res.status(502).json(bridgeError); - } - }); - router2.post("/plugins/:pluginId/actions/:key", async (req, res) => { - assertBoard(req); - if (!bridgeDeps) { - res.status(501).json({ error: "Plugin bridge is not enabled" }); - return; - } - const { pluginId, key } = req.params; - const plugin = await resolvePlugin(registry2, pluginId); - if (!plugin) { - res.status(404).json({ error: "Plugin not found" }); - return; - } - if (plugin.status !== "ready") { - const bridgeError = { - code: "WORKER_UNAVAILABLE", - message: `Plugin is not ready (current status: ${plugin.status})` - }; - res.status(502).json(bridgeError); - return; - } - const body = req.body; - if (body?.companyId) { - assertCompanyAccess(req, body.companyId); - } - try { - const result = await bridgeDeps.workerManager.call( - plugin.id, - "performAction", - { - key, - params: body?.params ?? {}, - renderEnvironment: body?.renderEnvironment ?? null - } - ); - res.json({ data: result }); - } catch (err) { - const bridgeError = mapRpcErrorToBridgeError(err); - res.status(502).json(bridgeError); - } - }); - router2.get("/plugins/:pluginId/bridge/stream/:channel", async (req, res) => { - assertBoard(req); - if (!bridgeDeps?.streamBus) { - res.status(501).json({ error: "Plugin stream bridge is not enabled" }); - return; - } - const { pluginId, channel } = req.params; - const companyId = req.query.companyId; - if (!companyId) { - res.status(400).json({ error: '"companyId" query parameter is required' }); - return; - } - const plugin = await resolvePlugin(registry2, pluginId); - if (!plugin) { - res.status(404).json({ error: "Plugin not found" }); - return; - } - assertCompanyAccess(req, companyId); - res.writeHead(200, { - "Content-Type": "text/event-stream", - "Cache-Control": "no-cache", - "Connection": "keep-alive", - "X-Accel-Buffering": "no" - }); - res.flushHeaders(); - res.write(":ok\n\n"); - let unsubscribed = false; - const safeUnsubscribe = () => { - if (!unsubscribed) { - unsubscribed = true; - unsubscribe(); - } - }; - const unsubscribe = bridgeDeps.streamBus.subscribe( - plugin.id, - channel, - companyId, - (event, eventType) => { - if (unsubscribed || !res.writable) return; - try { - if (eventType !== "message") { - res.write(`event: ${eventType} -`); - } - res.write(`data: ${JSON.stringify(event)} - -`); - } catch { - safeUnsubscribe(); - } - } - ); - req.on("close", safeUnsubscribe); - res.on("error", safeUnsubscribe); - }); - router2.get("/plugins/:pluginId", async (req, res) => { - assertBoard(req); - const { pluginId } = req.params; - const plugin = await resolvePlugin(registry2, pluginId); - if (!plugin) { - res.status(404).json({ error: "Plugin not found" }); - return; - } - const worker = bridgeDeps?.workerManager.getWorker(plugin.id); - const supportsConfigTest = worker ? worker.supportedMethods.includes("validateConfig") : false; - res.json({ ...plugin, supportsConfigTest }); - }); - router2.delete("/plugins/:pluginId", async (req, res) => { - assertBoard(req); - const { pluginId } = req.params; - const purge = req.query.purge === "true"; - const plugin = await resolvePlugin(registry2, pluginId); - if (!plugin) { - res.status(404).json({ error: "Plugin not found" }); - return; - } - try { - const result = await lifecycle.unload(plugin.id, purge); - await logPluginMutationActivity(req, "plugin.uninstalled", plugin.id, { - pluginId: plugin.id, - pluginKey: plugin.pluginKey, - purge - }); - publishGlobalLiveEvent({ type: "plugin.ui.updated", payload: { pluginId: plugin.id, action: "uninstalled" } }); - res.json(result); - } catch (err) { - const message2 = err instanceof Error ? err.message : String(err); - res.status(400).json({ error: message2 }); - } - }); - router2.post("/plugins/:pluginId/enable", async (req, res) => { - assertBoard(req); - const { pluginId } = req.params; - const plugin = await resolvePlugin(registry2, pluginId); - if (!plugin) { - res.status(404).json({ error: "Plugin not found" }); - return; - } - try { - const result = await lifecycle.enable(plugin.id); - await logPluginMutationActivity(req, "plugin.enabled", plugin.id, { - pluginId: plugin.id, - pluginKey: plugin.pluginKey, - version: result?.version ?? plugin.version - }); - publishGlobalLiveEvent({ type: "plugin.ui.updated", payload: { pluginId: plugin.id, action: "enabled" } }); - res.json(result); - } catch (err) { - const message2 = err instanceof Error ? err.message : String(err); - res.status(400).json({ error: message2 }); - } - }); - router2.post("/plugins/:pluginId/disable", async (req, res) => { - assertBoard(req); - const { pluginId } = req.params; - const body = req.body; - const reason = body?.reason; - const plugin = await resolvePlugin(registry2, pluginId); - if (!plugin) { - res.status(404).json({ error: "Plugin not found" }); - return; - } - try { - const result = await lifecycle.disable(plugin.id, reason); - await logPluginMutationActivity(req, "plugin.disabled", plugin.id, { - pluginId: plugin.id, - pluginKey: plugin.pluginKey, - reason: reason ?? null - }); - publishGlobalLiveEvent({ type: "plugin.ui.updated", payload: { pluginId: plugin.id, action: "disabled" } }); - res.json(result); - } catch (err) { - const message2 = err instanceof Error ? err.message : String(err); - res.status(400).json({ error: message2 }); - } - }); - router2.get("/plugins/:pluginId/health", async (req, res) => { - assertBoard(req); - const { pluginId } = req.params; - const plugin = await resolvePlugin(registry2, pluginId); - if (!plugin) { - res.status(404).json({ error: "Plugin not found" }); - return; - } - const checks = []; - checks.push({ - name: "registry", - passed: true, - message: "Plugin found in registry" - }); - const hasValidManifest = Boolean(plugin.manifestJson?.id); - checks.push({ - name: "manifest", - passed: hasValidManifest, - message: hasValidManifest ? "Manifest is valid" : "Manifest is invalid or missing" - }); - const isHealthy = plugin.status === "ready"; - checks.push({ - name: "status", - passed: isHealthy, - message: `Current status: ${plugin.status}` - }); - const hasNoError = !plugin.lastError; - if (!hasNoError) { - checks.push({ - name: "error_state", - passed: false, - message: plugin.lastError ?? void 0 - }); - } - const result = { - pluginId: plugin.id, - status: plugin.status, - healthy: isHealthy && hasValidManifest && hasNoError, - checks, - lastError: plugin.lastError ?? void 0 - }; - res.json(result); - }); - router2.get("/plugins/:pluginId/logs", async (req, res) => { - assertBoard(req); - const { pluginId } = req.params; - const plugin = await resolvePlugin(registry2, pluginId); - if (!plugin) { - res.status(404).json({ error: "Plugin not found" }); - return; - } - const limit = Math.min(Math.max(parseInt(req.query.limit, 10) || 25, 1), 500); - const level = req.query.level; - const since = req.query.since; - const conditions = [eq(pluginLogs.pluginId, plugin.id)]; - if (level) { - conditions.push(eq(pluginLogs.level, level)); - } - if (since) { - const sinceDate = new Date(since); - if (!isNaN(sinceDate.getTime())) { - conditions.push(gte(pluginLogs.createdAt, sinceDate)); - } - } - const rows = await db.select().from(pluginLogs).where(and(...conditions)).orderBy(desc(pluginLogs.createdAt)).limit(limit); - res.json(rows); - }); - router2.post("/plugins/:pluginId/upgrade", async (req, res) => { - assertBoard(req); - const { pluginId } = req.params; - const body = req.body; - const version3 = body?.version; - const plugin = await resolvePlugin(registry2, pluginId); - if (!plugin) { - res.status(404).json({ error: "Plugin not found" }); - return; - } - try { - const result = await lifecycle.upgrade(plugin.id, version3); - await logPluginMutationActivity(req, "plugin.upgraded", plugin.id, { - pluginId: plugin.id, - pluginKey: plugin.pluginKey, - previousVersion: plugin.version, - version: result?.version ?? plugin.version, - targetVersion: version3 ?? null - }); - publishGlobalLiveEvent({ type: "plugin.ui.updated", payload: { pluginId: plugin.id, action: "upgraded" } }); - res.json(result); - } catch (err) { - const message2 = err instanceof Error ? err.message : String(err); - res.status(400).json({ error: message2 }); - } - }); - router2.get("/plugins/:pluginId/config", async (req, res) => { - assertBoard(req); - const { pluginId } = req.params; - const plugin = await resolvePlugin(registry2, pluginId); - if (!plugin) { - res.status(404).json({ error: "Plugin not found" }); - return; - } - const config3 = await registry2.getConfig(plugin.id); - res.json(config3); - }); - router2.post("/plugins/:pluginId/config", async (req, res) => { - assertBoard(req); - const { pluginId } = req.params; - const plugin = await resolvePlugin(registry2, pluginId); - if (!plugin) { - res.status(404).json({ error: "Plugin not found" }); - return; - } - const body = req.body; - if (!body?.configJson || typeof body.configJson !== "object") { - res.status(400).json({ error: '"configJson" is required and must be an object' }); - return; - } - if ("devUiUrl" in body.configJson && !(req.actor.type === "board" && req.actor.isInstanceAdmin)) { - delete body.configJson.devUiUrl; - } - const schema2 = plugin.manifestJson?.instanceConfigSchema; - if (schema2 && Object.keys(schema2).length > 0) { - const validation = validateInstanceConfig(body.configJson, schema2); - if (!validation.valid) { - res.status(400).json({ - error: "Configuration does not match the plugin's instanceConfigSchema", - fieldErrors: validation.errors - }); - return; - } - } - try { - const result = await registry2.upsertConfig(plugin.id, { - configJson: body.configJson - }); - await logPluginMutationActivity(req, "plugin.config.updated", plugin.id, { - pluginId: plugin.id, - pluginKey: plugin.pluginKey, - configKeyCount: Object.keys(body.configJson).length - }); - if (bridgeDeps?.workerManager.isRunning(plugin.id)) { - try { - await bridgeDeps.workerManager.call( - plugin.id, - "configChanged", - { config: body.configJson } - ); - } catch (rpcErr) { - if (rpcErr instanceof JsonRpcCallError && rpcErr.code === PLUGIN_RPC_ERROR_CODES.METHOD_NOT_IMPLEMENTED) { - try { - await lifecycle.restartWorker(plugin.id); - } catch { - } - } - } - } - res.json(result); - } catch (err) { - const message2 = err instanceof Error ? err.message : String(err); - res.status(400).json({ error: message2 }); - } - }); - router2.post("/plugins/:pluginId/config/test", async (req, res) => { - assertBoard(req); - if (!bridgeDeps) { - res.status(501).json({ error: "Plugin bridge is not enabled" }); - return; - } - const { pluginId } = req.params; - const plugin = await resolvePlugin(registry2, pluginId); - if (!plugin) { - res.status(404).json({ error: "Plugin not found" }); - return; - } - if (plugin.status !== "ready") { - res.status(400).json({ - error: `Plugin is not ready (current status: ${plugin.status})` - }); - return; - } - const body = req.body; - if (!body?.configJson || typeof body.configJson !== "object") { - res.status(400).json({ error: '"configJson" is required and must be an object' }); - return; - } - const schema2 = plugin.manifestJson?.instanceConfigSchema; - if (schema2 && Object.keys(schema2).length > 0) { - const validation = validateInstanceConfig(body.configJson, schema2); - if (!validation.valid) { - res.status(400).json({ - error: "Configuration does not match the plugin's instanceConfigSchema", - fieldErrors: validation.errors - }); - return; - } - } - try { - const result = await bridgeDeps.workerManager.call( - plugin.id, - "validateConfig", - { config: body.configJson } - ); - if (result.ok) { - const warningText = result.warnings?.length ? `Warnings: ${result.warnings.join("; ")}` : void 0; - res.json({ valid: true, message: warningText }); - } else { - const errorText2 = result.errors?.length ? result.errors.join("; ") : "Configuration validation failed."; - res.json({ valid: false, message: errorText2 }); - } - } catch (err) { - if (err instanceof JsonRpcCallError && err.code === PLUGIN_RPC_ERROR_CODES.METHOD_NOT_IMPLEMENTED) { - res.json({ - valid: false, - supported: false, - message: "This plugin does not support configuration testing." - }); - return; - } - const bridgeError = mapRpcErrorToBridgeError(err); - res.status(502).json(bridgeError); - } - }); - router2.get("/plugins/:pluginId/jobs", async (req, res) => { - assertBoard(req); - if (!jobDeps) { - res.status(501).json({ error: "Job scheduling is not enabled" }); - return; - } - const { pluginId } = req.params; - const plugin = await resolvePlugin(registry2, pluginId); - if (!plugin) { - res.status(404).json({ error: "Plugin not found" }); - return; - } - const rawStatus = req.query.status; - const validStatuses = ["active", "paused", "failed"]; - if (rawStatus !== void 0 && !validStatuses.includes(rawStatus)) { - res.status(400).json({ - error: `Invalid status '${rawStatus}'. Must be one of: ${validStatuses.join(", ")}` - }); - return; - } - try { - const jobs = await jobDeps.jobStore.listJobs( - plugin.id, - rawStatus - ); - res.json(jobs); - } catch (err) { - const message2 = err instanceof Error ? err.message : String(err); - res.status(500).json({ error: message2 }); - } - }); - router2.get("/plugins/:pluginId/jobs/:jobId/runs", async (req, res) => { - assertBoard(req); - if (!jobDeps) { - res.status(501).json({ error: "Job scheduling is not enabled" }); - return; - } - const { pluginId, jobId } = req.params; - const plugin = await resolvePlugin(registry2, pluginId); - if (!plugin) { - res.status(404).json({ error: "Plugin not found" }); - return; - } - const job = await jobDeps.jobStore.getJobByIdForPlugin(plugin.id, jobId); - if (!job) { - res.status(404).json({ error: "Job not found" }); - return; - } - const limit = req.query.limit ? parseInt(req.query.limit, 10) : 25; - if (isNaN(limit) || limit < 1 || limit > 500) { - res.status(400).json({ error: "limit must be a number between 1 and 500" }); - return; - } - try { - const runs = await jobDeps.jobStore.listRunsByJob(jobId, limit); - res.json(runs); - } catch (err) { - const message2 = err instanceof Error ? err.message : String(err); - res.status(500).json({ error: message2 }); - } - }); - router2.post("/plugins/:pluginId/jobs/:jobId/trigger", async (req, res) => { - assertBoard(req); - if (!jobDeps) { - res.status(501).json({ error: "Job scheduling is not enabled" }); - return; - } - const { pluginId, jobId } = req.params; - const plugin = await resolvePlugin(registry2, pluginId); - if (!plugin) { - res.status(404).json({ error: "Plugin not found" }); - return; - } - const job = await jobDeps.jobStore.getJobByIdForPlugin(plugin.id, jobId); - if (!job) { - res.status(404).json({ error: "Job not found" }); - return; - } - try { - const result = await jobDeps.scheduler.triggerJob(jobId, "manual"); - res.json(result); - } catch (err) { - const message2 = err instanceof Error ? err.message : String(err); - res.status(400).json({ error: message2 }); - } - }); - router2.post("/plugins/:pluginId/webhooks/:endpointKey", async (req, res) => { - if (!webhookDeps) { - res.status(501).json({ error: "Webhook ingestion is not enabled" }); - return; - } - const { pluginId, endpointKey } = req.params; - const plugin = await resolvePlugin(registry2, pluginId); - if (!plugin) { - res.status(404).json({ error: "Plugin not found" }); - return; - } - if (plugin.status !== "ready") { - res.status(400).json({ - error: `Plugin is not ready (current status: ${plugin.status})` - }); - return; - } - const manifest = plugin.manifestJson; - if (!manifest) { - res.status(400).json({ error: "Plugin manifest is missing" }); - return; - } - const capabilities = manifest.capabilities ?? []; - if (!capabilities.includes("webhooks.receive")) { - res.status(400).json({ - error: "Plugin does not have the webhooks.receive capability" - }); - return; - } - const declaredWebhooks = manifest.webhooks ?? []; - const webhookDecl = declaredWebhooks.find( - (w5) => w5.endpointKey === endpointKey - ); - if (!webhookDecl) { - res.status(404).json({ - error: `Webhook endpoint '${endpointKey}' is not declared by this plugin` - }); - return; - } - const requestId = randomUUID10(); - const rawHeaders = {}; - for (const [key, value] of Object.entries(req.headers)) { - if (typeof value === "string") { - rawHeaders[key] = value; - } else if (Array.isArray(value)) { - rawHeaders[key] = value.join(", "); - } - } - const stashedRaw = req.rawBody; - const rawBody = stashedRaw ? stashedRaw.toString("utf-8") : ""; - const parsedBody = req.body; - const payload2 = req.body ?? {}; - const startedAt = /* @__PURE__ */ new Date(); - const [delivery] = await db.insert(pluginWebhookDeliveries).values({ - pluginId: plugin.id, - webhookKey: endpointKey, - status: "pending", - payload: payload2, - headers: rawHeaders, - startedAt - }).returning({ id: pluginWebhookDeliveries.id }); - try { - await webhookDeps.workerManager.call(plugin.id, "handleWebhook", { - endpointKey, - headers: req.headers, - rawBody, - parsedBody, - requestId - }); - const finishedAt = /* @__PURE__ */ new Date(); - const durationMs = finishedAt.getTime() - startedAt.getTime(); - await db.update(pluginWebhookDeliveries).set({ - status: "success", - durationMs, - finishedAt - }).where(eq(pluginWebhookDeliveries.id, delivery.id)); - res.status(200).json({ - deliveryId: delivery.id, - status: "success" - }); - } catch (err) { - const finishedAt = /* @__PURE__ */ new Date(); - const durationMs = finishedAt.getTime() - startedAt.getTime(); - const errorMessage = err instanceof Error ? err.message : String(err); - await db.update(pluginWebhookDeliveries).set({ - status: "failed", - durationMs, - error: errorMessage, - finishedAt - }).where(eq(pluginWebhookDeliveries.id, delivery.id)); - res.status(502).json({ - deliveryId: delivery.id, - status: "failed", - error: errorMessage - }); - } - }); - router2.get("/plugins/:pluginId/dashboard", async (req, res) => { - assertBoard(req); - const { pluginId } = req.params; - const plugin = await resolvePlugin(registry2, pluginId); - if (!plugin) { - res.status(404).json({ error: "Plugin not found" }); - return; - } - let worker = null; - const wm = bridgeDeps?.workerManager ?? webhookDeps?.workerManager ?? null; - if (wm) { - const handle = wm.getWorker(plugin.id); - if (handle) { - const diag = handle.diagnostics(); - worker = { - status: diag.status, - pid: diag.pid, - uptime: diag.uptime, - consecutiveCrashes: diag.consecutiveCrashes, - totalCrashes: diag.totalCrashes, - pendingRequests: diag.pendingRequests, - lastCrashAt: diag.lastCrashAt, - nextRestartAt: diag.nextRestartAt - }; - } - } - let recentJobRuns = []; - if (jobDeps) { - try { - const runs = await jobDeps.jobStore.listRunsByPlugin(plugin.id, void 0, 10); - const jobs = await jobDeps.jobStore.listJobs(plugin.id); - const jobKeyMap = new Map(jobs.map((j5) => [j5.id, j5.jobKey])); - recentJobRuns = runs.sort((a5, b6) => new Date(b6.createdAt).getTime() - new Date(a5.createdAt).getTime()).map((r5) => ({ - id: r5.id, - jobId: r5.jobId, - jobKey: jobKeyMap.get(r5.jobId) ?? void 0, - trigger: r5.trigger, - status: r5.status, - durationMs: r5.durationMs, - error: r5.error, - startedAt: r5.startedAt ? new Date(r5.startedAt).toISOString() : null, - finishedAt: r5.finishedAt ? new Date(r5.finishedAt).toISOString() : null, - createdAt: new Date(r5.createdAt).toISOString() - })); - } catch { - } - } - let recentWebhookDeliveries = []; - try { - const deliveries = await db.select({ - id: pluginWebhookDeliveries.id, - webhookKey: pluginWebhookDeliveries.webhookKey, - status: pluginWebhookDeliveries.status, - durationMs: pluginWebhookDeliveries.durationMs, - error: pluginWebhookDeliveries.error, - startedAt: pluginWebhookDeliveries.startedAt, - finishedAt: pluginWebhookDeliveries.finishedAt, - createdAt: pluginWebhookDeliveries.createdAt - }).from(pluginWebhookDeliveries).where(eq(pluginWebhookDeliveries.pluginId, plugin.id)).orderBy(desc(pluginWebhookDeliveries.createdAt)).limit(10); - recentWebhookDeliveries = deliveries.map((d5) => ({ - id: d5.id, - webhookKey: d5.webhookKey, - status: d5.status, - durationMs: d5.durationMs, - error: d5.error, - startedAt: d5.startedAt ? d5.startedAt.toISOString() : null, - finishedAt: d5.finishedAt ? d5.finishedAt.toISOString() : null, - createdAt: d5.createdAt.toISOString() - })); - } catch { - } - const checks = []; - checks.push({ - name: "registry", - passed: true, - message: "Plugin found in registry" - }); - const hasValidManifest = Boolean(plugin.manifestJson?.id); - checks.push({ - name: "manifest", - passed: hasValidManifest, - message: hasValidManifest ? "Manifest is valid" : "Manifest is invalid or missing" - }); - const isHealthy = plugin.status === "ready"; - checks.push({ - name: "status", - passed: isHealthy, - message: `Current status: ${plugin.status}` - }); - const hasNoError = !plugin.lastError; - if (!hasNoError) { - checks.push({ - name: "error_state", - passed: false, - message: plugin.lastError ?? void 0 - }); - } - const health = { - pluginId: plugin.id, - status: plugin.status, - healthy: isHealthy && hasValidManifest && hasNoError, - checks, - lastError: plugin.lastError ?? void 0 - }; - res.json({ - pluginId: plugin.id, - worker, - recentJobRuns, - recentWebhookDeliveries, - health, - checkedAt: (/* @__PURE__ */ new Date()).toISOString() - }); - }); - return router2; -} - -// server/src/routes/adapters.ts -var import_express23 = __toESM(require_express2(), 1); -import { execFile as execFile8 } from "node:child_process"; -import fs37 from "node:fs"; -import { readFile as readFile4 } from "node:fs/promises"; -import path48 from "node:path"; -import { promisify as promisify8 } from "node:util"; -var execFileAsync7 = promisify8(execFile8); -function resolveAdapterPackageDir(record2) { - return record2.localPath ? path48.resolve(record2.localPath) : path48.resolve(getAdapterPluginsDir(), "node_modules", record2.packageName); -} -function readAdapterPackageVersionFromDisk(record2) { - try { - const pkgDir = resolveAdapterPackageDir(record2); - const raw = fs37.readFileSync(path48.join(pkgDir, "package.json"), "utf-8"); - const v5 = JSON.parse(raw).version; - return typeof v5 === "string" && v5.trim().length > 0 ? v5.trim() : void 0; - } catch { - return void 0; - } -} -function buildAdapterInfo(adapter, externalRecord, disabledSet) { - const fromDisk = externalRecord ? readAdapterPackageVersionFromDisk(externalRecord) : void 0; - return { - type: adapter.type, - label: adapter.type, - // ServerAdapterModule doesn't have a separate "label" field; type serves as label - source: externalRecord ? "external" : "builtin", - modelsCount: (adapter.models ?? []).length, - loaded: true, - // If it's in the registry, it's loaded - disabled: disabledSet.has(adapter.type), - overriddenBuiltin: externalRecord ? BUILTIN_ADAPTER_TYPES.has(adapter.type) : void 0, - overridePaused: BUILTIN_ADAPTER_TYPES.has(adapter.type) ? isOverridePaused(adapter.type) : void 0, - // Prefer on-disk package.json so the UI reflects bumps without relying on store-only fields. - version: fromDisk ?? externalRecord?.version, - packageName: externalRecord?.packageName, - isLocalPath: externalRecord?.localPath ? true : void 0 - }; -} -async function normalizeLocalPath(rawPath) { - if (rawPath.startsWith("/")) { - return rawPath; - } - if (/^[A-Za-z]:[\\/]/.test(rawPath)) { - try { - const { stdout } = await execFileAsync7("wslpath", ["-u", rawPath]); - return stdout.trim(); - } catch (err) { - logger.warn({ err, rawPath }, "wslpath conversion failed; using path as-is"); - return rawPath; - } - } - return rawPath; -} -function registerWithSessionManagement(adapter) { - const wrapped = { - ...adapter, - sessionManagement: getAdapterSessionManagement(adapter.type) ?? void 0 - }; - registerServerAdapter(wrapped); -} -function adapterRoutes() { - const router2 = (0, import_express23.Router)(); - router2.get("/adapters", async (_req, res) => { - assertBoard(_req); - const registeredAdapters = listServerAdapters(); - const externalRecords = new Map( - listAdapterPlugins().map((r5) => [r5.type, r5]) - ); - const disabledSet = new Set(getDisabledAdapterTypes()); - const result = registeredAdapters.map( - (adapter) => buildAdapterInfo(adapter, externalRecords.get(adapter.type), disabledSet) - ).sort((a5, b6) => a5.type.localeCompare(b6.type)); - res.json(result); - }); - router2.post("/adapters/install", async (req, res) => { - assertBoard(req); - const { packageName, isLocalPath = false, version: version3 } = req.body; - if (!packageName || typeof packageName !== "string") { - res.status(400).json({ error: "packageName is required and must be a string." }); - return; - } - let canonicalName = packageName; - let explicitVersion = version3; - const versionSuffix = packageName.match(/@(\d+\.\d+\.\d+.*)$/); - if (versionSuffix) { - const lastAtIndex = packageName.lastIndexOf("@"); - if (lastAtIndex > 0 && !explicitVersion) { - canonicalName = packageName.slice(0, lastAtIndex); - explicitVersion = versionSuffix[1]; - } - } - try { - let installedVersion; - let moduleLocalPath; - if (!isLocalPath) { - const pluginsDir = getAdapterPluginsDir(); - const spec = explicitVersion ? `${canonicalName}@${explicitVersion}` : canonicalName; - logger.info({ spec, pluginsDir }, "Installing adapter package via npm"); - await execFileAsync7("npm", ["install", "--no-save", spec], { - cwd: pluginsDir, - timeout: 12e4 - }); - try { - const pkgJsonPath = path48.join(pluginsDir, "node_modules", canonicalName, "package.json"); - const pkgContent = await import("node:fs/promises"); - const pkgRaw = await pkgContent.readFile(pkgJsonPath, "utf-8"); - const pkg2 = JSON.parse(pkgRaw); - const v5 = pkg2.version; - installedVersion = typeof v5 === "string" && v5.trim().length > 0 ? v5.trim() : explicitVersion; - } catch { - installedVersion = explicitVersion; - } - } else { - moduleLocalPath = path48.resolve(await normalizeLocalPath(packageName)); - try { - const pkgRaw = await readFile4(path48.join(moduleLocalPath, "package.json"), "utf-8"); - const v5 = JSON.parse(pkgRaw).version; - if (typeof v5 === "string" && v5.trim().length > 0) { - installedVersion = v5.trim(); - } - } catch { - } - } - const adapterModule = await loadExternalAdapterPackage(canonicalName, moduleLocalPath); - if (BUILTIN_ADAPTER_TYPES.has(adapterModule.type)) { - res.status(409).json({ - error: `Adapter type "${adapterModule.type}" is a built-in adapter and cannot be overwritten.` - }); - return; - } - const existing = findServerAdapter(adapterModule.type); - const isReinstall = existing !== null; - if (existing) { - unregisterServerAdapter(adapterModule.type); - logger.info({ type: adapterModule.type }, "Unregistered existing adapter for replacement"); - } - registerWithSessionManagement(adapterModule); - const record2 = { - packageName: canonicalName, - localPath: moduleLocalPath, - version: installedVersion ?? explicitVersion, - type: adapterModule.type, - installedAt: (/* @__PURE__ */ new Date()).toISOString() - }; - addAdapterPlugin(record2); - logger.info( - { type: adapterModule.type, packageName: canonicalName }, - "External adapter installed and registered" - ); - res.status(201).json({ - type: adapterModule.type, - packageName: canonicalName, - version: installedVersion ?? explicitVersion, - installedAt: record2.installedAt, - requiresRestart: isReinstall - }); - } catch (err) { - const message2 = err instanceof Error ? err.message : String(err); - logger.error({ err, packageName }, "Failed to install external adapter"); - if (message2.includes("npm") || message2.includes("ERR!")) { - res.status(500).json({ error: `npm install failed: ${message2}` }); - } else { - res.status(500).json({ error: `Failed to install adapter: ${message2}` }); - } - } - }); - router2.patch("/adapters/:type", async (req, res) => { - assertBoard(req); - const adapterType = req.params.type; - const { disabled } = req.body; - if (typeof disabled !== "boolean") { - res.status(400).json({ error: 'Request body must include { "disabled": true|false }.' }); - return; - } - const existing = findServerAdapter(adapterType); - if (!existing) { - res.status(404).json({ error: `Adapter "${adapterType}" is not registered.` }); - return; - } - const changed = setAdapterDisabled(adapterType, disabled); - if (changed) { - logger.info({ type: adapterType, disabled }, "Adapter enabled/disabled"); - } - res.json({ type: adapterType, disabled, changed }); - }); - router2.patch("/adapters/:type/override", async (req, res) => { - assertBoard(req); - const adapterType = req.params.type; - const { paused } = req.body; - if (typeof paused !== "boolean") { - res.status(400).json({ error: '"paused" (boolean) is required in request body.' }); - return; - } - if (!BUILTIN_ADAPTER_TYPES.has(adapterType)) { - res.status(400).json({ error: `Type "${adapterType}" is not a builtin adapter.` }); - return; - } - const changed = setOverridePaused(adapterType, paused); - logger.info({ type: adapterType, paused, changed }, "Adapter override toggle"); - res.json({ type: adapterType, paused, changed }); - }); - router2.delete("/adapters/:type", async (req, res) => { - assertBoard(req); - const adapterType = req.params.type; - if (!adapterType) { - res.status(400).json({ error: "Adapter type is required." }); - return; - } - if (BUILTIN_ADAPTER_TYPES.has(adapterType)) { - res.status(403).json({ - error: `Cannot remove built-in adapter "${adapterType}".` - }); - return; - } - const existing = findServerAdapter(adapterType); - if (!existing) { - res.status(404).json({ - error: `Adapter "${adapterType}" is not registered.` - }); - return; - } - const externalRecord = getAdapterPluginByType(adapterType); - if (!externalRecord) { - res.status(404).json({ - error: `Adapter "${adapterType}" is not an externally installed adapter.` - }); - return; - } - if (externalRecord.packageName && !externalRecord.localPath) { - try { - const pluginsDir = getAdapterPluginsDir(); - await execFileAsync7("npm", ["uninstall", externalRecord.packageName], { - cwd: pluginsDir, - timeout: 6e4 - }); - logger.info( - { type: adapterType, packageName: externalRecord.packageName }, - "npm uninstall completed for external adapter" - ); - } catch (err) { - logger.warn( - { err, type: adapterType, packageName: externalRecord.packageName }, - "npm uninstall failed for external adapter; continuing with unregister" - ); - } - } - unregisterServerAdapter(adapterType); - removeAdapterPlugin(adapterType); - logger.info({ type: adapterType }, "External adapter unregistered and removed"); - res.json({ type: adapterType, removed: true }); - }); - router2.post("/adapters/:type/reload", async (req, res) => { - assertBoard(req); - const type = req.params.type; - if (BUILTIN_ADAPTER_TYPES.has(type) && !getAdapterPluginByType(type)) { - res.status(400).json({ error: "Cannot reload built-in adapter." }); - return; - } - try { - const newModule = await reloadExternalAdapter(type); - if (!newModule) { - res.status(404).json({ error: `Adapter "${type}" is not an externally installed adapter.` }); - return; - } - unregisterServerAdapter(type); - registerWithSessionManagement(newModule); - configSchemaCache.delete(type); - const record2 = getAdapterPluginByType(type); - let newVersion; - if (record2) { - newVersion = readAdapterPackageVersionFromDisk(record2); - if (newVersion) { - addAdapterPlugin({ ...record2, version: newVersion }); - } - } - logger.info({ type, version: newVersion }, "External adapter reloaded at runtime"); - res.json({ type, version: newVersion, reloaded: true }); - } catch (err) { - const message2 = err instanceof Error ? err.message : String(err); - logger.error({ err, type }, "Failed to reload external adapter"); - res.status(500).json({ error: `Failed to reload adapter: ${message2}` }); - } - }); - router2.post("/adapters/:type/reinstall", async (req, res) => { - assertBoard(req); - const type = req.params.type; - if (BUILTIN_ADAPTER_TYPES.has(type) && !getAdapterPluginByType(type)) { - res.status(400).json({ error: "Cannot reinstall built-in adapter." }); - return; - } - const record2 = getAdapterPluginByType(type); - if (!record2) { - res.status(404).json({ error: `Adapter "${type}" is not an externally installed adapter.` }); - return; - } - if (record2.localPath) { - res.status(400).json({ error: "Local-path adapters cannot be reinstalled. Use Reload instead." }); - return; - } - try { - const pluginsDir = getAdapterPluginsDir(); - logger.info({ type, packageName: record2.packageName }, "Reinstalling adapter package via npm"); - await execFileAsync7("npm", ["install", "--no-save", record2.packageName], { - cwd: pluginsDir, - timeout: 12e4 - }); - const newModule = await reloadExternalAdapter(type); - if (!newModule) { - res.status(500).json({ error: "npm install succeeded but adapter reload failed." }); - return; - } - unregisterServerAdapter(type); - registerWithSessionManagement(newModule); - configSchemaCache.delete(type); - let newVersion; - const updatedRecord = getAdapterPluginByType(type); - if (updatedRecord) { - newVersion = readAdapterPackageVersionFromDisk(updatedRecord); - if (newVersion) { - addAdapterPlugin({ ...updatedRecord, version: newVersion }); - } - } - logger.info({ type, version: newVersion }, "Adapter reinstalled from npm"); - res.json({ type, version: newVersion, reinstalled: true }); - } catch (err) { - const message2 = err instanceof Error ? err.message : String(err); - logger.error({ err, type }, "Failed to reinstall adapter"); - res.status(500).json({ error: `Reinstall failed: ${message2}` }); - } - }); - const configSchemaCache = /* @__PURE__ */ new Map(); - const CONFIG_SCHEMA_TTL_MS = 3e4; - router2.get("/adapters/:type/config-schema", async (req, res) => { - assertBoard(req); - const { type } = req.params; - const adapter = findActiveServerAdapter(type); - if (!adapter) { - res.status(404).json({ error: `Adapter "${type}" is not registered.` }); - return; - } - if (!adapter.getConfigSchema) { - res.status(404).json({ error: `Adapter "${type}" does not provide a config schema.` }); - return; - } - const cached4 = configSchemaCache.get(type); - if (cached4 && cached4.adapter === adapter && Date.now() - cached4.fetchedAt < CONFIG_SCHEMA_TTL_MS) { - res.json(cached4.schema); - return; - } - try { - const schema2 = await adapter.getConfigSchema(); - configSchemaCache.set(type, { adapter, schema: schema2, fetchedAt: Date.now() }); - res.json(schema2); - } catch (err) { - const message2 = err instanceof Error ? err.message : String(err); - logger.error({ err, type }, "Failed to resolve config schema"); - res.status(500).json({ error: `Failed to resolve config schema: ${message2}` }); - } - }); - router2.get("/adapters/:type/ui-parser.js", (req, res) => { - assertBoard(req); - const { type } = req.params; - const source = getOrExtractUiParserSource(type); - if (!source) { - res.status(404).json({ error: `No UI parser available for adapter "${type}".` }); - return; - } - res.type("application/javascript").send(source); - }); - return router2; -} - -// server/src/routes/plugin-ui-static.ts -var import_express24 = __toESM(require_express2(), 1); -import path49 from "node:path"; -import fs38 from "node:fs"; -import crypto5 from "node:crypto"; -var CONTENT_HASH_PATTERN = /[.-][a-fA-F0-9]{8,}\.\w+$/; -var ONE_YEAR_SECONDS = 365 * 24 * 60 * 60; -var CACHE_CONTROL_IMMUTABLE = `public, max-age=${ONE_YEAR_SECONDS}, immutable`; -var CACHE_CONTROL_REVALIDATE = "public, max-age=0, must-revalidate"; -var MIME_TYPES = { - ".js": "application/javascript; charset=utf-8", - ".mjs": "application/javascript; charset=utf-8", - ".css": "text/css; charset=utf-8", - ".json": "application/json; charset=utf-8", - ".map": "application/json; charset=utf-8", - ".html": "text/html; charset=utf-8", - ".svg": "image/svg+xml", - ".png": "image/png", - ".jpg": "image/jpeg", - ".jpeg": "image/jpeg", - ".gif": "image/gif", - ".webp": "image/webp", - ".woff": "font/woff", - ".woff2": "font/woff2", - ".ttf": "font/ttf", - ".eot": "application/vnd.ms-fontobject", - ".ico": "image/x-icon", - ".txt": "text/plain; charset=utf-8" -}; -function resolvePluginUiDir(localPluginDir, packageName, entrypointsUi, packagePath) { - if (packagePath) { - const resolvedPackagePath = path49.resolve(packagePath); - if (fs38.existsSync(resolvedPackagePath)) { - const uiDirFromPackagePath = path49.resolve(resolvedPackagePath, entrypointsUi); - if (uiDirFromPackagePath.startsWith(resolvedPackagePath) && fs38.existsSync(uiDirFromPackagePath)) { - return uiDirFromPackagePath; - } - } - } - let packageRoot; - if (packageName.startsWith("@")) { - packageRoot = path49.join(localPluginDir, "node_modules", ...packageName.split("/")); - } else { - packageRoot = path49.join(localPluginDir, "node_modules", packageName); - } - if (!fs38.existsSync(packageRoot)) { - const directPath = path49.join(localPluginDir, packageName); - if (fs38.existsSync(directPath)) { - packageRoot = directPath; - } else { - return null; - } - } - const uiDir = path49.resolve(packageRoot, entrypointsUi); - if (!fs38.existsSync(uiDir)) { - return null; - } - return uiDir; -} -function computeETag(size2, mtimeMs) { - const ETAG_VERSION = "v2"; - const hash2 = crypto5.createHash("md5").update(`${ETAG_VERSION}:${size2}-${mtimeMs}`).digest("hex").slice(0, 16); - return `"${hash2}"`; -} -function pluginUiStaticRoutes(db, options) { - const router2 = (0, import_express24.Router)(); - const registry2 = pluginRegistryService(db); - const log2 = logger.child({ service: "plugin-ui-static" }); - router2.get("/_plugins/:pluginId/ui/*filePath", async (req, res) => { - const { pluginId } = req.params; - const rawParam = req.params.filePath; - const rawFilePath = Array.isArray(rawParam) ? rawParam.join("/") : rawParam; - if (!rawFilePath || rawFilePath.length === 0) { - res.status(400).json({ error: "File path is required" }); - return; - } - let plugin = null; - try { - plugin = await registry2.getById(pluginId); - } catch (error50) { - const maybeCode = typeof error50 === "object" && error50 !== null && "code" in error50 ? error50.code : void 0; - if (maybeCode !== "22P02") { - throw error50; - } - } - if (!plugin) { - plugin = await registry2.getByKey(pluginId); - } - if (!plugin) { - res.status(404).json({ error: "Plugin not found" }); - return; - } - if (plugin.status !== "ready") { - res.status(403).json({ - error: `Plugin UI is not available (status: ${plugin.status})` - }); - return; - } - const manifest = plugin.manifestJson; - if (!manifest?.entrypoints?.ui) { - res.status(404).json({ error: "Plugin does not declare a UI bundle" }); - return; - } - try { - const configRow = await registry2.getConfig(plugin.id); - const devUiUrl = configRow && typeof configRow === "object" && "configJson" in configRow && configRow.configJson?.devUiUrl; - if (typeof devUiUrl === "string" && devUiUrl.length > 0) { - if (true) { - log2.warn( - { pluginId: plugin.id }, - "plugin-ui-static: devUiUrl ignored in production" - ); - } else { - let decodedPath; - try { - decodedPath = decodeURIComponent(rawFilePath); - } catch { - res.status(400).json({ error: "Invalid file path" }); - return; - } - if (decodedPath.includes("://") || decodedPath.startsWith("//") || decodedPath.startsWith("\\\\")) { - res.status(400).json({ error: "Invalid file path" }); - return; - } - const targetUrl = new URL(rawFilePath, devUiUrl.endsWith("/") ? devUiUrl : devUiUrl + "/"); - if (targetUrl.protocol !== "http:" && targetUrl.protocol !== "https:") { - res.status(400).json({ error: "devUiUrl must use http or https protocol" }); - return; - } - const devHost = targetUrl.hostname; - const isLoopback = devHost === "localhost" || devHost === "127.0.0.1" || devHost === "::1" || devHost === "[::1]"; - if (!isLoopback) { - log2.warn( - { pluginId: plugin.id, devUiUrl, host: devHost }, - "plugin-ui-static: devUiUrl must target localhost, rejecting proxy" - ); - res.status(400).json({ error: "devUiUrl must target localhost" }); - return; - } - log2.debug( - { pluginId: plugin.id, devUiUrl, targetUrl: targetUrl.href }, - "plugin-ui-static: proxying to devUiUrl" - ); - try { - const controller = new AbortController(); - const timeout = setTimeout(() => controller.abort(), 1e4); - try { - const upstream = await fetch(targetUrl.href, { signal: controller.signal }); - if (!upstream.ok) { - res.status(upstream.status).json({ - error: `Dev server returned ${upstream.status}` - }); - return; - } - const contentType2 = upstream.headers.get("content-type"); - if (contentType2) res.set("Content-Type", contentType2); - res.set("Cache-Control", "no-cache, no-store, must-revalidate"); - const body = await upstream.arrayBuffer(); - res.send(Buffer.from(body)); - return; - } finally { - clearTimeout(timeout); - } - } catch (proxyErr) { - log2.warn( - { - pluginId: plugin.id, - devUiUrl, - err: proxyErr instanceof Error ? proxyErr.message : String(proxyErr) - }, - "plugin-ui-static: failed to proxy to devUiUrl, falling back to static" - ); - } - } - } - } catch { - } - const uiDir = resolvePluginUiDir( - options.localPluginDir, - plugin.packageName, - manifest.entrypoints.ui, - plugin.packagePath - ); - if (!uiDir) { - log2.warn( - { pluginId: plugin.id, pluginKey: plugin.pluginKey, packageName: plugin.packageName }, - "plugin-ui-static: UI directory not found on disk" - ); - res.status(404).json({ error: "Plugin UI directory not found" }); - return; - } - const resolvedFilePath = path49.resolve(uiDir, rawFilePath); - let fileStat; - try { - fileStat = fs38.statSync(resolvedFilePath); - } catch { - res.status(404).json({ error: "File not found" }); - return; - } - let realFilePath; - let realUiDir; - try { - realFilePath = fs38.realpathSync(resolvedFilePath); - realUiDir = fs38.realpathSync(uiDir); - } catch { - res.status(404).json({ error: "File not found" }); - return; - } - const relative3 = path49.relative(realUiDir, realFilePath); - if (relative3.startsWith("..") || path49.isAbsolute(relative3)) { - res.status(403).json({ error: "Access denied" }); - return; - } - if (!fileStat.isFile()) { - res.status(404).json({ error: "File not found" }); - return; - } - const basename3 = path49.basename(resolvedFilePath); - const isContentHashed = CONTENT_HASH_PATTERN.test(basename3); - if (isContentHashed) { - res.set("Cache-Control", CACHE_CONTROL_IMMUTABLE); - } else { - res.set("Cache-Control", CACHE_CONTROL_REVALIDATE); - const etag = computeETag(fileStat.size, fileStat.mtimeMs); - res.set("ETag", etag); - const ifNoneMatch = req.headers["if-none-match"]; - if (ifNoneMatch === etag) { - res.status(304).end(); - return; - } - } - const ext = path49.extname(resolvedFilePath).toLowerCase(); - const contentType = MIME_TYPES[ext]; - if (contentType) { - res.set("Content-Type", contentType); - } - res.set("Access-Control-Allow-Origin", "*"); - res.sendFile(resolvedFilePath, { dotfiles: "allow" }, (err) => { - if (err) { - log2.error( - { err, pluginId: plugin.id, filePath: resolvedFilePath }, - "plugin-ui-static: error sending file" - ); - if (!res.headersSent) { - res.status(500).json({ error: "Failed to serve file" }); - } - } - }); - }); - return router2; -} - -// server/src/ui-branding.ts -var FAVICON_BLOCK_START = ""; -var FAVICON_BLOCK_END = ""; -var RUNTIME_BRANDING_BLOCK_START = ""; -var RUNTIME_BRANDING_BLOCK_END = ""; -var DEFAULT_FAVICON_LINKS = [ - '', - '', - '', - '' -].join("\n"); -function isTruthyEnvValue(value) { - if (!value) return false; - const normalized = value.trim().toLowerCase(); - return normalized === "1" || normalized === "true" || normalized === "yes" || normalized === "on"; -} -function nonEmpty6(value) { - if (typeof value !== "string") return null; - const normalized = value.trim(); - return normalized.length > 0 ? normalized : null; -} -function normalizeHexColor2(value) { - const raw = nonEmpty6(value); - if (!raw) return null; - const hex4 = raw.startsWith("#") ? raw.slice(1) : raw; - if (/^[0-9a-fA-F]{3}$/.test(hex4)) { - return `#${hex4.split("").map((char2) => `${char2}${char2}`).join("").toLowerCase()}`; - } - if (/^[0-9a-fA-F]{6}$/.test(hex4)) { - return `#${hex4.toLowerCase()}`; - } - return null; -} -function hslComponentToHex(n5) { - return Math.round(Math.max(0, Math.min(255, n5))).toString(16).padStart(2, "0"); -} -function hslToHex(hue, saturation, lightness) { - const s5 = Math.max(0, Math.min(100, saturation)) / 100; - const l5 = Math.max(0, Math.min(100, lightness)) / 100; - const c5 = (1 - Math.abs(2 * l5 - 1)) * s5; - const h5 = (hue % 360 + 360) % 360; - const x5 = c5 * (1 - Math.abs(h5 / 60 % 2 - 1)); - const m5 = l5 - c5 / 2; - let r5 = 0; - let g5 = 0; - let b6 = 0; - if (h5 < 60) { - r5 = c5; - g5 = x5; - } else if (h5 < 120) { - r5 = x5; - g5 = c5; - } else if (h5 < 180) { - g5 = c5; - b6 = x5; - } else if (h5 < 240) { - g5 = x5; - b6 = c5; - } else if (h5 < 300) { - r5 = x5; - b6 = c5; - } else { - r5 = c5; - b6 = x5; - } - return `#${hslComponentToHex((r5 + m5) * 255)}${hslComponentToHex((g5 + m5) * 255)}${hslComponentToHex((b6 + m5) * 255)}`; -} -function deriveColorFromSeed(seed) { - let hash2 = 0; - for (const char2 of seed) { - hash2 = hash2 * 33 + char2.charCodeAt(0) >>> 0; - } - return hslToHex(hash2 % 360, 68, 56); -} -function hexToRgb(color) { - const normalized = normalizeHexColor2(color) ?? "#000000"; - return { - r: Number.parseInt(normalized.slice(1, 3), 16), - g: Number.parseInt(normalized.slice(3, 5), 16), - b: Number.parseInt(normalized.slice(5, 7), 16) - }; -} -function relativeLuminanceChannel(value) { - const normalized = value / 255; - return normalized <= 0.03928 ? normalized / 12.92 : ((normalized + 0.055) / 1.055) ** 2.4; -} -function relativeLuminance(color) { - const { r: r5, g: g5, b: b6 } = hexToRgb(color); - return 0.2126 * relativeLuminanceChannel(r5) + 0.7152 * relativeLuminanceChannel(g5) + 0.0722 * relativeLuminanceChannel(b6); -} -function pickReadableTextColor(background) { - const backgroundLuminance = relativeLuminance(background); - const whiteContrast = 1.05 / (backgroundLuminance + 0.05); - const blackContrast = (backgroundLuminance + 0.05) / 0.05; - return whiteContrast >= blackContrast ? "#f8fafc" : "#111827"; -} -function escapeHtmlAttribute(value) { - return value.replaceAll("&", "&").replaceAll('"', """).replaceAll("<", "<").replaceAll(">", ">"); -} -function createFaviconDataUrl(background, foreground) { - const svg2 = [ - '', - ``, - ``, - "" - ].join(""); - return `data:image/svg+xml,${encodeURIComponent(svg2)}`; -} -function isWorktreeUiBrandingEnabled(env2 = process.env) { - return isTruthyEnvValue(env2.TASKCORE_IN_WORKTREE); -} -function getWorktreeUiBranding(env2 = process.env) { - if (!isWorktreeUiBrandingEnabled(env2)) { - return { - enabled: false, - name: null, - color: null, - textColor: null, - faviconHref: null - }; - } - const name = nonEmpty6(env2.TASKCORE_WORKTREE_NAME) ?? nonEmpty6(env2.TASKCORE_INSTANCE_ID) ?? "worktree"; - const color = normalizeHexColor2(env2.TASKCORE_WORKTREE_COLOR) ?? deriveColorFromSeed(name); - const textColor = pickReadableTextColor(color); - return { - enabled: true, - name, - color, - textColor, - faviconHref: createFaviconDataUrl(color, textColor) - }; -} -function renderFaviconLinks(branding) { - if (!branding.enabled || !branding.faviconHref) return DEFAULT_FAVICON_LINKS; - const href = escapeHtmlAttribute(branding.faviconHref); - return [ - ``, - `` - ].join("\n"); -} -function renderRuntimeBrandingMeta(branding) { - if (!branding.enabled || !branding.name || !branding.color || !branding.textColor) return ""; - return [ - '', - ``, - ``, - `` - ].join("\n"); -} -function replaceMarkedBlock(html3, startMarker, endMarker, content) { - const start = html3.indexOf(startMarker); - const end = html3.indexOf(endMarker); - if (start === -1 || end === -1 || end < start) return html3; - const before = html3.slice(0, start + startMarker.length); - const after = html3.slice(end); - const indentedContent = content ? ` -${content.split("\n").map((line3) => ` ${line3}`).join("\n")} - ` : "\n "; - return `${before}${indentedContent}${after}`; -} -function applyUiBranding(html3, env2 = process.env) { - const branding = getWorktreeUiBranding(env2); - const withFavicon = replaceMarkedBlock(html3, FAVICON_BLOCK_START, FAVICON_BLOCK_END, renderFaviconLinks(branding)); - return replaceMarkedBlock( - withFavicon, - RUNTIME_BRANDING_BLOCK_START, - RUNTIME_BRANDING_BLOCK_END, - renderRuntimeBrandingMeta(branding) - ); -} - -// server/src/services/plugin-worker-manager.ts -import { fork } from "node:child_process"; -import { EventEmitter as EventEmitter3 } from "node:events"; -import { createInterface } from "node:readline"; -var DEFAULT_RPC_TIMEOUT_MS = 3e4; -var MAX_RPC_TIMEOUT_MS = 5 * 60 * 1e3; -var INITIALIZE_TIMEOUT_MS = 15e3; -var SHUTDOWN_DRAIN_MS = 1e4; -var SIGTERM_GRACE_MS = 5e3; -var MIN_BACKOFF_MS = 1e3; -var MAX_BACKOFF_MS = 5 * 60 * 1e3; -var BACKOFF_MULTIPLIER = 2; -var MAX_CONSECUTIVE_CRASHES = 10; -var CRASH_WINDOW_MS = 10 * 60 * 1e3; -var MAX_STDERR_EXCERPT_CHARS = 8e3; -function appendStderrExcerpt(current, chunk) { - const next = current ? `${current} -${chunk}` : chunk; - return next.length <= MAX_STDERR_EXCERPT_CHARS ? next : next.slice(-MAX_STDERR_EXCERPT_CHARS); -} -function formatWorkerFailureMessage(message2, stderrExcerpt) { - const excerpt = stderrExcerpt.trim(); - if (!excerpt) return message2; - if (message2.includes(excerpt)) return message2; - return `${message2} - -Worker stderr: -${excerpt}`; -} -function createPluginWorkerHandle(pluginId, options) { - const log2 = logger.child({ service: "plugin-worker", pluginId }); - const emitter2 = new EventEmitter3(); - emitter2.setMaxListeners(50); - let childProcess = null; - let readline = null; - let stderrReadline = null; - let status = "stopped"; - let startedAt = null; - let stderrExcerpt = ""; - const pendingRequests = /* @__PURE__ */ new Map(); - let nextRequestId = 1; - let supportedMethods = []; - let consecutiveCrashes = 0; - let totalCrashes = 0; - let lastCrashAt = null; - let backoffTimer = null; - let nextRestartAt = null; - const openStreamChannels = /* @__PURE__ */ new Map(); - let intentionalStop = false; - const rpcTimeoutMs = options.rpcTimeoutMs ?? DEFAULT_RPC_TIMEOUT_MS; - const autoRestart = options.autoRestart ?? true; - function setStatus(newStatus) { - const prev = status; - if (prev === newStatus) return; - status = newStatus; - log2.debug({ from: prev, to: newStatus }, "worker status change"); - emitter2.emit("status", { pluginId, status: newStatus, previousStatus: prev }); - } - function sendMessage(message2) { - if (!childProcess?.stdin?.writable) { - throw new Error(`Worker process for plugin "${pluginId}" is not writable`); - } - const serialized = serializeMessage(message2); - childProcess.stdin.write(serialized); - } - function handleLine(line3) { - if (!line3.trim()) return; - let message2; - try { - message2 = parseMessage(line3); - } catch (err) { - if (err instanceof JsonRpcParseError) { - log2.warn({ rawLine: line3.slice(0, 200) }, "unparseable message from worker"); - } else { - log2.warn({ err }, "error parsing worker message"); - } - return; - } - if (isJsonRpcResponse(message2)) { - handleResponse(message2); - } else if (isJsonRpcRequest(message2)) { - handleWorkerRequest(message2); - } else if (isJsonRpcNotification(message2)) { - handleWorkerNotification(message2); - } else { - log2.warn("unknown message type from worker"); - } - } - function handleResponse(response) { - const id = response.id; - if (id === null || id === void 0) { - log2.warn("received response with null/undefined id"); - return; - } - const pending = pendingRequests.get(id); - if (!pending) { - log2.warn({ id }, "received response for unknown request id"); - return; - } - clearTimeout(pending.timer); - pendingRequests.delete(id); - pending.resolve(response); - } - async function handleWorkerRequest(request) { - const method = request.method; - const handler = options.hostHandlers[method]; - if (!handler) { - log2.warn({ method }, "worker called unregistered host method"); - try { - sendMessage( - createErrorResponse( - request.id, - JSONRPC_ERROR_CODES.METHOD_NOT_FOUND, - `Host does not handle method "${method}"` - ) - ); - } catch { - } - return; - } - try { - const result = await handler(request.params); - sendMessage({ - jsonrpc: JSONRPC_VERSION, - id: request.id, - result: result ?? null - }); - } catch (err) { - const errorMessage = err instanceof Error ? err.message : String(err); - log2.error({ method, err: errorMessage }, "host handler error"); - try { - sendMessage( - createErrorResponse( - request.id, - JSONRPC_ERROR_CODES.INTERNAL_ERROR, - errorMessage - ) - ); - } catch { - } - } - } - function handleWorkerNotification(notification) { - if (notification.method === "log") { - const params = notification.params; - const level = params?.level ?? "info"; - const msg = params?.message ?? ""; - const meta3 = params?.meta; - const logFields = { - ...meta3, - pluginLogLevel: level, - pluginTimestamp: (/* @__PURE__ */ new Date()).toISOString() - }; - if (level === "error") { - log2.error(logFields, `[plugin] ${msg}`); - } else if (level === "warn") { - log2.warn(logFields, `[plugin] ${msg}`); - } else if (level === "debug") { - log2.debug(logFields, `[plugin] ${msg}`); - } else { - log2.info(logFields, `[plugin] ${msg}`); - } - return; - } - if (notification.method === "streams.open" || notification.method === "streams.emit" || notification.method === "streams.close") { - const params = notification.params ?? {}; - if (notification.method === "streams.open") { - const ch = String(params.channel ?? ""); - const co = String(params.companyId ?? ""); - if (ch) openStreamChannels.set(ch, co); - } else if (notification.method === "streams.close") { - openStreamChannels.delete(String(params.channel ?? "")); - } - if (options.onStreamNotification) { - try { - options.onStreamNotification(notification.method, params); - } catch (err) { - log2.error( - { - method: notification.method, - err: err instanceof Error ? err.message : String(err) - }, - "stream notification handler failed" - ); - } - } - return; - } - log2.debug({ method: notification.method }, "received notification from worker"); - } - function spawnProcess() { - const workerEnv = { - ...options.env, - PATH: process.env.PATH ?? "", - NODE_PATH: process.env.NODE_PATH ?? "", - TASKCORE_PLUGIN_ID: pluginId, - NODE_ENV: "production", - TZ: process.env.TZ ?? "UTC" - }; - const child = fork(options.entrypointPath, [], { - stdio: ["pipe", "pipe", "pipe", "ipc"], - execArgv: options.execArgv ?? [], - env: workerEnv, - // Don't let the child keep the parent alive - detached: false - }); - return child; - } - function attachStdioHandlers(child) { - if (child.stdout) { - readline = createInterface({ input: child.stdout }); - readline.on("line", handleLine); - } - if (child.stderr) { - stderrReadline = createInterface({ input: child.stderr }); - stderrReadline.on("line", (line3) => { - stderrExcerpt = appendStderrExcerpt(stderrExcerpt, line3); - log2.warn({ stream: "stderr" }, `[plugin stderr] ${line3}`); - }); - } - child.on("exit", (code, signal) => { - handleProcessExit(code, signal); - }); - child.on("error", (err) => { - log2.error({ err: err.message }, "worker process error"); - emitter2.emit("error", { pluginId, error: err }); - if (status === "starting") { - setStatus("crashed"); - rejectAllPending( - new Error(formatWorkerFailureMessage( - `Worker process failed to start: ${err.message}`, - stderrExcerpt - )) - ); - } - }); - } - function handleProcessExit(code, signal) { - const wasIntentional = intentionalStop; - if (readline) { - readline.close(); - readline = null; - } - if (stderrReadline) { - stderrReadline.close(); - stderrReadline = null; - } - childProcess = null; - startedAt = null; - rejectAllPending( - new Error(formatWorkerFailureMessage( - `Worker process exited (code=${code}, signal=${signal})`, - stderrExcerpt - )) - ); - if (openStreamChannels.size > 0 && options.onStreamNotification) { - for (const [channel, companyId] of openStreamChannels) { - try { - options.onStreamNotification("streams.close", { channel, companyId }); - } catch { - } - } - openStreamChannels.clear(); - } - emitter2.emit("exit", { pluginId, code, signal }); - if (wasIntentional) { - setStatus("stopped"); - log2.info({ code, signal }, "worker process stopped"); - return; - } - totalCrashes++; - const now2 = Date.now(); - if (lastCrashAt !== null && now2 - lastCrashAt > CRASH_WINDOW_MS) { - consecutiveCrashes = 0; - } - consecutiveCrashes++; - lastCrashAt = now2; - log2.error( - { code, signal, consecutiveCrashes, totalCrashes }, - "worker process crashed" - ); - const willRestart = autoRestart && consecutiveCrashes <= MAX_CONSECUTIVE_CRASHES; - setStatus("crashed"); - emitter2.emit("crash", { pluginId, code, signal, willRestart }); - if (willRestart) { - scheduleRestart(); - } else { - log2.error( - { consecutiveCrashes, maxCrashes: MAX_CONSECUTIVE_CRASHES }, - "max consecutive crashes reached, not restarting" - ); - } - } - function rejectAllPending(error50) { - for (const [id, pending] of pendingRequests) { - clearTimeout(pending.timer); - pending.resolve( - createErrorResponse( - pending.id, - PLUGIN_RPC_ERROR_CODES.WORKER_UNAVAILABLE, - error50.message - ) - ); - } - pendingRequests.clear(); - } - function computeBackoffMs() { - const delay3 = MIN_BACKOFF_MS * Math.pow(BACKOFF_MULTIPLIER, consecutiveCrashes - 1); - const jitter = delay3 * 0.25 * (Math.random() * 2 - 1); - return Math.min(Math.round(delay3 + jitter), MAX_BACKOFF_MS); - } - function scheduleRestart() { - const delay3 = computeBackoffMs(); - nextRestartAt = Date.now() + delay3; - setStatus("backoff"); - log2.info( - { delayMs: delay3, consecutiveCrashes }, - "scheduling restart with backoff" - ); - backoffTimer = setTimeout(async () => { - backoffTimer = null; - nextRestartAt = null; - try { - await startInternal(); - } catch (err) { - log2.error( - { err: err instanceof Error ? err.message : String(err) }, - "restart after backoff failed" - ); - } - }, delay3); - } - function cancelPendingRestart() { - if (backoffTimer !== null) { - clearTimeout(backoffTimer); - backoffTimer = null; - nextRestartAt = null; - } - } - async function startInternal() { - if (status === "running" || status === "starting") { - throw new Error(`Worker for plugin "${pluginId}" is already ${status}`); - } - intentionalStop = false; - setStatus("starting"); - stderrExcerpt = ""; - const child = spawnProcess(); - childProcess = child; - attachStdioHandlers(child); - startedAt = Date.now(); - const initParams = { - manifest: options.manifest, - config: options.config, - instanceInfo: options.instanceInfo, - apiVersion: options.apiVersion - }; - try { - const result = await callInternal( - "initialize", - initParams, - INITIALIZE_TIMEOUT_MS - ); - if (!result || !result.ok) { - throw new Error("Worker initialize returned ok=false"); - } - supportedMethods = result.supportedMethods ?? []; - } catch (err) { - const msg = err instanceof Error ? err.message : String(err); - log2.error({ err: msg }, "worker initialize failed"); - await killProcess(); - setStatus("crashed"); - throw new Error(`Worker initialize failed for "${pluginId}": ${msg}`); - } - consecutiveCrashes = 0; - setStatus("running"); - emitter2.emit("ready", { pluginId }); - log2.info({ pid: child.pid }, "worker process started and initialized"); - } - async function stopInternal() { - cancelPendingRestart(); - if (status === "stopped" || status === "stopping") { - return; - } - intentionalStop = true; - setStatus("stopping"); - if (!childProcess) { - setStatus("stopped"); - return; - } - try { - await Promise.race([ - callInternal("shutdown", {}, SHUTDOWN_DRAIN_MS), - waitForExit(SHUTDOWN_DRAIN_MS) - ]); - } catch { - log2.warn("shutdown RPC failed or timed out, escalating to SIGTERM"); - } - if (childProcess) { - await waitForExit(500); - } - if (!childProcess) { - setStatus("stopped"); - return; - } - log2.info("worker did not exit after shutdown RPC, sending SIGTERM"); - await killWithSignal("SIGTERM", SIGTERM_GRACE_MS); - if (!childProcess) { - setStatus("stopped"); - return; - } - log2.warn("worker did not exit after SIGTERM, sending SIGKILL"); - await killWithSignal("SIGKILL", 2e3); - if (childProcess) { - log2.error("worker process still alive after SIGKILL \u2014 this should not happen"); - } - setStatus("stopped"); - } - function waitForExit(timeoutMs) { - return new Promise((resolve4) => { - if (!childProcess) { - resolve4(); - return; - } - let settled = false; - const timer2 = setTimeout(() => { - if (settled) return; - settled = true; - resolve4(); - }, timeoutMs); - childProcess.once("exit", () => { - if (settled) return; - settled = true; - clearTimeout(timer2); - resolve4(); - }); - }); - } - function killWithSignal(signal, waitMs) { - return new Promise((resolve4) => { - if (!childProcess) { - resolve4(); - return; - } - const timer2 = setTimeout(() => { - resolve4(); - }, waitMs); - childProcess.once("exit", () => { - clearTimeout(timer2); - resolve4(); - }); - try { - childProcess.kill(signal); - } catch { - clearTimeout(timer2); - resolve4(); - } - }); - } - async function killProcess() { - if (!childProcess) return; - intentionalStop = true; - try { - childProcess.kill("SIGKILL"); - } catch { - } - await new Promise((resolve4) => { - if (!childProcess) { - resolve4(); - return; - } - const timer2 = setTimeout(() => { - resolve4(); - }, 1e3); - childProcess.once("exit", () => { - clearTimeout(timer2); - resolve4(); - }); - }); - } - function callInternal(method, params, timeoutMs) { - return new Promise((resolve4, reject) => { - if (!childProcess?.stdin?.writable) { - reject( - new Error( - `Cannot call "${method}" \u2014 worker for "${pluginId}" is not running` - ) - ); - return; - } - const id = nextRequestId++; - const timeout = Math.min(timeoutMs ?? rpcTimeoutMs, MAX_RPC_TIMEOUT_MS); - let settled = false; - const settle = (fn, value) => { - if (settled) return; - settled = true; - clearTimeout(timer2); - pendingRequests.delete(id); - fn(value); - }; - const timer2 = setTimeout(() => { - settle( - reject, - new JsonRpcCallError({ - code: PLUGIN_RPC_ERROR_CODES.TIMEOUT, - message: `RPC call "${method}" timed out after ${timeout}ms` - }) - ); - }, timeout); - const pending = { - id, - method, - resolve: (response) => { - if (isJsonRpcSuccessResponse(response)) { - settle(resolve4, response.result); - } else if ("error" in response && response.error) { - settle(reject, new JsonRpcCallError(response.error)); - } else { - settle(reject, new Error(`Unexpected response format for "${method}"`)); - } - }, - timer: timer2, - sentAt: Date.now() - }; - pendingRequests.set(id, pending); - try { - const request = createRequest(method, params, id); - sendMessage(request); - } catch (err) { - clearTimeout(timer2); - pendingRequests.delete(id); - reject( - new Error( - `Failed to send "${method}" to worker: ${err instanceof Error ? err.message : String(err)}` - ) - ); - } - }); - } - const handle = { - get pluginId() { - return pluginId; - }, - get status() { - return status; - }, - get supportedMethods() { - return supportedMethods; - }, - async start() { - await startInternal(); - }, - async stop() { - await stopInternal(); - }, - async restart() { - await stopInternal(); - await startInternal(); - }, - call(method, params, timeoutMs) { - if (status !== "running" && status !== "starting") { - return Promise.reject( - new Error( - `Cannot call "${method}" \u2014 worker for "${pluginId}" is ${status}` - ) - ); - } - return callInternal(method, params, timeoutMs); - }, - notify(method, params) { - if (status !== "running") return; - try { - sendMessage({ - jsonrpc: JSONRPC_VERSION, - method, - params - }); - } catch { - log2.warn({ method }, "failed to send notification to worker"); - } - }, - on(event, listener) { - emitter2.on(event, listener); - }, - off(event, listener) { - emitter2.off(event, listener); - }, - diagnostics() { - return { - pluginId, - status, - pid: childProcess?.pid ?? null, - uptime: startedAt !== null && status === "running" ? Date.now() - startedAt : null, - consecutiveCrashes, - totalCrashes, - pendingRequests: pendingRequests.size, - lastCrashAt, - nextRestartAt - }; - } - }; - return handle; -} -function createPluginWorkerManager(managerOptions) { - const log2 = logger.child({ service: "plugin-worker-manager" }); - const workers = /* @__PURE__ */ new Map(); - const startupLocks = /* @__PURE__ */ new Map(); - return { - async startWorker(pluginId, options) { - const inFlight = startupLocks.get(pluginId); - if (inFlight) { - log2.warn({ pluginId }, "concurrent startWorker call \u2014 waiting for in-flight start"); - return inFlight; - } - const existing = workers.get(pluginId); - if (existing && existing.status !== "stopped") { - throw new Error( - `Worker already registered for plugin "${pluginId}" (status: ${existing.status})` - ); - } - const handle = createPluginWorkerHandle(pluginId, options); - workers.set(pluginId, handle); - if (managerOptions?.onWorkerEvent) { - const notify = managerOptions.onWorkerEvent; - handle.on("crash", (payload2) => { - notify({ - type: "plugin.worker.crashed", - pluginId: payload2.pluginId, - code: payload2.code, - signal: payload2.signal, - willRestart: payload2.willRestart - }); - }); - handle.on("ready", (payload2) => { - const diag = handle.diagnostics(); - if (diag.totalCrashes > 0) { - notify({ - type: "plugin.worker.restarted", - pluginId: payload2.pluginId - }); - } - }); - } - log2.info({ pluginId }, "starting plugin worker"); - const startPromise = handle.start().then(() => handle).finally(() => { - startupLocks.delete(pluginId); - }); - startupLocks.set(pluginId, startPromise); - return startPromise; - }, - async stopWorker(pluginId) { - const handle = workers.get(pluginId); - if (!handle) { - log2.warn({ pluginId }, "no worker registered for plugin, nothing to stop"); - return; - } - log2.info({ pluginId }, "stopping plugin worker"); - await handle.stop(); - workers.delete(pluginId); - }, - getWorker(pluginId) { - return workers.get(pluginId); - }, - isRunning(pluginId) { - const handle = workers.get(pluginId); - return handle?.status === "running"; - }, - async stopAll() { - log2.info({ count: workers.size }, "stopping all plugin workers"); - const promises = Array.from(workers.values()).map(async (handle) => { - try { - await handle.stop(); - } catch (err) { - log2.error( - { - pluginId: handle.pluginId, - err: err instanceof Error ? err.message : String(err) - }, - "error stopping worker during shutdown" - ); - } - }); - await Promise.all(promises); - workers.clear(); - }, - diagnostics() { - return Array.from(workers.values()).map((h5) => h5.diagnostics()); - }, - call(pluginId, method, params, timeoutMs) { - const handle = workers.get(pluginId); - if (!handle) { - return Promise.reject( - new Error(`No worker registered for plugin "${pluginId}"`) - ); - } - return handle.call(method, params, timeoutMs); - } - }; -} - -// server/src/services/plugin-job-scheduler.ts -init_drizzle_orm(); -init_src2(); -var DEFAULT_TICK_INTERVAL_MS = 3e4; -var DEFAULT_JOB_TIMEOUT_MS = 5 * 60 * 1e3; -var DEFAULT_MAX_CONCURRENT_JOBS = 10; -function createPluginJobScheduler(options) { - const { - db, - jobStore, - workerManager, - tickIntervalMs = DEFAULT_TICK_INTERVAL_MS, - jobTimeoutMs = DEFAULT_JOB_TIMEOUT_MS, - maxConcurrentJobs = DEFAULT_MAX_CONCURRENT_JOBS - } = options; - const log2 = logger.child({ service: "plugin-job-scheduler" }); - let tickTimer = null; - let running = false; - const activeJobs = /* @__PURE__ */ new Set(); - let tickCount = 0; - let lastTickAt = null; - let tickInProgress = false; - async function tick() { - if (tickInProgress) { - log2.debug("skipping tick \u2014 previous tick still in progress"); - return; - } - tickInProgress = true; - tickCount++; - lastTickAt = /* @__PURE__ */ new Date(); - try { - const now2 = /* @__PURE__ */ new Date(); - const dueJobs = await db.select().from(pluginJobs).where( - and( - eq(pluginJobs.status, "active"), - lte(pluginJobs.nextRunAt, now2) - ) - ); - if (dueJobs.length === 0) { - return; - } - log2.debug({ count: dueJobs.length }, "found due jobs"); - const dispatches = []; - for (const job of dueJobs) { - if (activeJobs.size >= maxConcurrentJobs) { - log2.warn( - { maxConcurrentJobs, activeJobCount: activeJobs.size }, - "max concurrent jobs reached, deferring remaining jobs" - ); - break; - } - if (activeJobs.has(job.id)) { - log2.debug( - { jobId: job.id, jobKey: job.jobKey, pluginId: job.pluginId }, - "skipping job \u2014 already running (overlap prevention)" - ); - continue; - } - if (!workerManager.isRunning(job.pluginId)) { - log2.debug( - { jobId: job.id, pluginId: job.pluginId }, - "skipping job \u2014 worker not running" - ); - continue; - } - if (!job.schedule) { - log2.warn( - { jobId: job.id, jobKey: job.jobKey }, - "skipping job \u2014 no schedule defined" - ); - continue; - } - dispatches.push(dispatchJob(job)); - } - if (dispatches.length > 0) { - await Promise.allSettled(dispatches); - } - } catch (err) { - log2.error( - { err: err instanceof Error ? err.message : String(err) }, - "scheduler tick error" - ); - } finally { - tickInProgress = false; - } - } - async function dispatchJob(job) { - const { id: jobId, pluginId, jobKey, schedule } = job; - const jobLog = log2.child({ jobId, pluginId, jobKey }); - activeJobs.add(jobId); - let runId; - const startedAt = Date.now(); - try { - const run = await jobStore.createRun({ - jobId, - pluginId, - trigger: "schedule" - }); - runId = run.id; - jobLog.info({ runId }, "dispatching scheduled job"); - await jobStore.markRunning(runId); - await workerManager.call( - pluginId, - "runJob", - { - job: { - jobKey, - runId, - trigger: "schedule", - scheduledAt: (job.nextRunAt ?? /* @__PURE__ */ new Date()).toISOString() - } - }, - jobTimeoutMs - ); - const durationMs = Date.now() - startedAt; - await jobStore.completeRun(runId, { - status: "succeeded", - durationMs - }); - jobLog.info({ runId, durationMs }, "job completed successfully"); - } catch (err) { - const durationMs = Date.now() - startedAt; - const errorMessage = err instanceof Error ? err.message : String(err); - jobLog.error( - { runId, durationMs, err: errorMessage }, - "job execution failed" - ); - if (runId) { - try { - await jobStore.completeRun(runId, { - status: "failed", - error: errorMessage, - durationMs - }); - } catch (completeErr) { - jobLog.error( - { - runId, - err: completeErr instanceof Error ? completeErr.message : String(completeErr) - }, - "failed to record job failure" - ); - } - } - } finally { - activeJobs.delete(jobId); - try { - await advanceSchedulePointer(job); - } catch (err) { - jobLog.error( - { err: err instanceof Error ? err.message : String(err) }, - "failed to advance schedule pointer" - ); - } - } - } - async function triggerJob(jobId, trigger = "manual") { - const job = await jobStore.getJobById(jobId); - if (!job) { - throw new Error(`Job not found: ${jobId}`); - } - if (job.status !== "active") { - throw new Error( - `Job "${job.jobKey}" is not active (status: ${job.status})` - ); - } - if (activeJobs.has(jobId)) { - throw new Error( - `Job "${job.jobKey}" is already running \u2014 cannot trigger while in progress` - ); - } - const existingRuns = await db.select().from(pluginJobRuns).where( - and( - eq(pluginJobRuns.jobId, jobId), - eq(pluginJobRuns.status, "running") - ) - ); - if (existingRuns.length > 0) { - throw new Error( - `Job "${job.jobKey}" already has a running execution \u2014 cannot trigger while in progress` - ); - } - if (!workerManager.isRunning(job.pluginId)) { - throw new Error( - `Worker for plugin "${job.pluginId}" is not running \u2014 cannot trigger job` - ); - } - const run = await jobStore.createRun({ - jobId, - pluginId: job.pluginId, - trigger - }); - void dispatchManualRun(job, run.id, trigger); - return { runId: run.id, jobId }; - } - async function dispatchManualRun(job, runId, trigger) { - const { id: jobId, pluginId, jobKey } = job; - const jobLog = log2.child({ jobId, pluginId, jobKey, runId, trigger }); - activeJobs.add(jobId); - const startedAt = Date.now(); - try { - await jobStore.markRunning(runId); - await workerManager.call( - pluginId, - "runJob", - { - job: { - jobKey, - runId, - trigger, - scheduledAt: (/* @__PURE__ */ new Date()).toISOString() - } - }, - jobTimeoutMs - ); - const durationMs = Date.now() - startedAt; - await jobStore.completeRun(runId, { - status: "succeeded", - durationMs - }); - jobLog.info({ durationMs }, "manual job completed successfully"); - } catch (err) { - const durationMs = Date.now() - startedAt; - const errorMessage = err instanceof Error ? err.message : String(err); - jobLog.error({ durationMs, err: errorMessage }, "manual job failed"); - try { - await jobStore.completeRun(runId, { - status: "failed", - error: errorMessage, - durationMs - }); - } catch (completeErr) { - jobLog.error( - { - err: completeErr instanceof Error ? completeErr.message : String(completeErr) - }, - "failed to record manual job failure" - ); - } - } finally { - activeJobs.delete(jobId); - } - } - async function advanceSchedulePointer(job) { - const now2 = /* @__PURE__ */ new Date(); - let nextRunAt = null; - if (job.schedule) { - const validationError = validateCron(job.schedule); - if (validationError) { - log2.warn( - { jobId: job.id, schedule: job.schedule, error: validationError }, - "invalid cron schedule \u2014 cannot compute next run" - ); - } else { - const cron = parseCron(job.schedule); - nextRunAt = nextCronTick(cron, now2); - } - } - await jobStore.updateRunTimestamps(job.id, now2, nextRunAt); - } - async function ensureNextRunTimestamps(pluginId) { - const jobs = await jobStore.listJobs(pluginId, "active"); - for (const job of jobs) { - if (job.nextRunAt && job.nextRunAt.getTime() > Date.now()) { - continue; - } - if (!job.schedule) { - continue; - } - const validationError = validateCron(job.schedule); - if (validationError) { - log2.warn( - { jobId: job.id, jobKey: job.jobKey, schedule: job.schedule, error: validationError }, - "skipping job with invalid cron schedule" - ); - continue; - } - const cron = parseCron(job.schedule); - const nextRunAt = nextCronTick(cron, /* @__PURE__ */ new Date()); - if (nextRunAt) { - await jobStore.updateRunTimestamps( - job.id, - job.lastRunAt ?? /* @__PURE__ */ new Date(0), - nextRunAt - ); - log2.debug( - { jobId: job.id, jobKey: job.jobKey, nextRunAt: nextRunAt.toISOString() }, - "computed nextRunAt for job" - ); - } - } - } - async function registerPlugin(pluginId) { - log2.info({ pluginId }, "registering plugin with job scheduler"); - await ensureNextRunTimestamps(pluginId); - } - async function unregisterPlugin(pluginId) { - log2.info({ pluginId }, "unregistering plugin from job scheduler"); - try { - const runningRuns = await db.select().from(pluginJobRuns).where( - and( - eq(pluginJobRuns.pluginId, pluginId), - or( - eq(pluginJobRuns.status, "running"), - eq(pluginJobRuns.status, "queued") - ) - ) - ); - for (const run of runningRuns) { - await jobStore.completeRun(run.id, { - status: "cancelled", - error: "Plugin unregistered", - durationMs: run.startedAt ? Date.now() - run.startedAt.getTime() : null - }); - } - } catch (err) { - log2.error( - { - pluginId, - err: err instanceof Error ? err.message : String(err) - }, - "error cancelling in-flight runs during unregister" - ); - } - const jobs = await jobStore.listJobs(pluginId); - for (const job of jobs) { - activeJobs.delete(job.id); - } - } - function start() { - if (running) { - log2.debug("scheduler already running"); - return; - } - running = true; - tickTimer = setInterval(() => { - void tick(); - }, tickIntervalMs); - log2.info( - { tickIntervalMs, maxConcurrentJobs }, - "plugin job scheduler started" - ); - } - function stop() { - if (tickTimer !== null) { - clearInterval(tickTimer); - tickTimer = null; - } - if (!running) return; - running = false; - log2.info( - { activeJobCount: activeJobs.size }, - "plugin job scheduler stopped" - ); - } - function diagnostics() { - return { - running, - activeJobCount: activeJobs.size, - activeJobIds: [...activeJobs], - tickCount, - lastTickAt: lastTickAt?.toISOString() ?? null - }; - } - return { - start, - stop, - registerPlugin, - unregisterPlugin, - triggerJob, - tick, - diagnostics - }; -} - -// server/src/services/plugin-job-store.ts -init_drizzle_orm(); -init_src2(); -function pluginJobStore(db) { - async function assertPluginExists(pluginId) { - const rows = await db.select({ id: plugins.id }).from(plugins).where(eq(plugins.id, pluginId)); - if (rows.length === 0) { - throw notFound(`Plugin not found: ${pluginId}`); - } - } - return { - // ===================================================================== - // Job declarations (plugin_jobs) - // ===================================================================== - /** - * Sync declared jobs from a plugin manifest into the `plugin_jobs` table. - * - * This is called at plugin install and on each worker startup so the DB - * always reflects the manifest's declared jobs: - * - * - **New jobs** are inserted with status `active`. - * - **Existing jobs** have their `schedule` updated if it changed. - * - **Removed jobs** (present in DB but absent from the manifest) are - * set to `paused` so their history is preserved. - * - * The unique constraint `(pluginId, jobKey)` is used for conflict - * resolution. - * - * @param pluginId - UUID of the owning plugin - * @param declarations - Job declarations from the plugin manifest - */ - async syncJobDeclarations(pluginId, declarations) { - await assertPluginExists(pluginId); - const existingJobs = await db.select().from(pluginJobs).where(eq(pluginJobs.pluginId, pluginId)); - const existingByKey = new Map( - existingJobs.map((j5) => [j5.jobKey, j5]) - ); - const declaredKeys = /* @__PURE__ */ new Set(); - for (const decl of declarations) { - declaredKeys.add(decl.jobKey); - const existing = existingByKey.get(decl.jobKey); - const schedule = decl.schedule ?? ""; - if (existing) { - const updates = { - updatedAt: /* @__PURE__ */ new Date() - }; - if (existing.schedule !== schedule) { - updates.schedule = schedule; - } - if (existing.status === "paused") { - updates.status = "active"; - } - await db.update(pluginJobs).set(updates).where(eq(pluginJobs.id, existing.id)); - } else { - await db.insert(pluginJobs).values({ - pluginId, - jobKey: decl.jobKey, - schedule, - status: "active" - }); - } - } - for (const existing of existingJobs) { - if (!declaredKeys.has(existing.jobKey) && existing.status !== "paused") { - await db.update(pluginJobs).set({ status: "paused", updatedAt: /* @__PURE__ */ new Date() }).where(eq(pluginJobs.id, existing.id)); - } - } - }, - /** - * List all jobs for a plugin, optionally filtered by status. - * - * @param pluginId - UUID of the owning plugin - * @param status - Optional status filter - */ - async listJobs(pluginId, status) { - const conditions = [eq(pluginJobs.pluginId, pluginId)]; - if (status) { - conditions.push(eq(pluginJobs.status, status)); - } - return db.select().from(pluginJobs).where(and(...conditions)); - }, - /** - * Get a single job by its composite key `(pluginId, jobKey)`. - * - * @param pluginId - UUID of the owning plugin - * @param jobKey - Stable job identifier from the manifest - * @returns The job row, or `null` if not found - */ - async getJobByKey(pluginId, jobKey) { - const rows = await db.select().from(pluginJobs).where( - and( - eq(pluginJobs.pluginId, pluginId), - eq(pluginJobs.jobKey, jobKey) - ) - ); - return rows[0] ?? null; - }, - /** - * Get a single job by its primary key (UUID). - * - * @param jobId - UUID of the job row - * @returns The job row, or `null` if not found - */ - async getJobById(jobId) { - const rows = await db.select().from(pluginJobs).where(eq(pluginJobs.id, jobId)); - return rows[0] ?? null; - }, - /** - * Fetch a single job by ID, scoped to a specific plugin. - * - * Returns `null` if the job does not exist or does not belong to the - * given plugin — callers should treat both cases as "not found". - */ - async getJobByIdForPlugin(pluginId, jobId) { - const rows = await db.select().from(pluginJobs).where(and(eq(pluginJobs.id, jobId), eq(pluginJobs.pluginId, pluginId))); - return rows[0] ?? null; - }, - /** - * Update a job's status. - * - * @param jobId - UUID of the job row - * @param status - New status - */ - async updateJobStatus(jobId, status) { - await db.update(pluginJobs).set({ status, updatedAt: /* @__PURE__ */ new Date() }).where(eq(pluginJobs.id, jobId)); - }, - /** - * Update the `lastRunAt` and `nextRunAt` timestamps on a job. - * - * Called by the scheduler after a run completes to advance the - * scheduling pointer. - * - * @param jobId - UUID of the job row - * @param lastRunAt - When the last run started - * @param nextRunAt - When the next run should fire - */ - async updateRunTimestamps(jobId, lastRunAt, nextRunAt) { - await db.update(pluginJobs).set({ - lastRunAt, - nextRunAt, - updatedAt: /* @__PURE__ */ new Date() - }).where(eq(pluginJobs.id, jobId)); - }, - /** - * Delete all jobs (and cascaded runs) owned by a plugin. - * - * Called during plugin uninstall when `removeData = true`. - * - * @param pluginId - UUID of the owning plugin - */ - async deleteAllJobs(pluginId) { - await db.delete(pluginJobs).where(eq(pluginJobs.pluginId, pluginId)); - }, - // ===================================================================== - // Job runs (plugin_job_runs) - // ===================================================================== - /** - * Create a new job run record with status `queued`. - * - * The caller should create the run record *before* dispatching the - * `runJob` RPC to the worker, then update it to `running` once the - * worker begins execution. - * - * @param input - Job run input (jobId, pluginId, trigger) - * @returns The newly created run row - */ - async createRun(input) { - const rows = await db.insert(pluginJobRuns).values({ - jobId: input.jobId, - pluginId: input.pluginId, - trigger: input.trigger, - status: "queued" - }).returning(); - return rows[0]; - }, - /** - * Mark a run as `running` and set its `startedAt` timestamp. - * - * @param runId - UUID of the run row - */ - async markRunning(runId) { - await db.update(pluginJobRuns).set({ - status: "running", - startedAt: /* @__PURE__ */ new Date() - }).where(eq(pluginJobRuns.id, runId)); - }, - /** - * Complete a run — set its final status, error, duration, and - * `finishedAt` timestamp. - * - * @param runId - UUID of the run row - * @param input - Completion details - */ - async completeRun(runId, input) { - await db.update(pluginJobRuns).set({ - status: input.status, - error: input.error ?? null, - durationMs: input.durationMs ?? null, - finishedAt: /* @__PURE__ */ new Date() - }).where(eq(pluginJobRuns.id, runId)); - }, - /** - * Get a run by its primary key. - * - * @param runId - UUID of the run row - * @returns The run row, or `null` if not found - */ - async getRunById(runId) { - const rows = await db.select().from(pluginJobRuns).where(eq(pluginJobRuns.id, runId)); - return rows[0] ?? null; - }, - /** - * List runs for a specific job, ordered by creation time descending. - * - * @param jobId - UUID of the job - * @param limit - Maximum number of rows to return (default: 50) - */ - async listRunsByJob(jobId, limit = 50) { - return db.select().from(pluginJobRuns).where(eq(pluginJobRuns.jobId, jobId)).orderBy(desc(pluginJobRuns.createdAt)).limit(limit); - }, - /** - * List runs for a plugin, optionally filtered by status. - * - * @param pluginId - UUID of the owning plugin - * @param status - Optional status filter - * @param limit - Maximum number of rows to return (default: 50) - */ - async listRunsByPlugin(pluginId, status, limit = 50) { - const conditions = [eq(pluginJobRuns.pluginId, pluginId)]; - if (status) { - conditions.push(eq(pluginJobRuns.status, status)); - } - return db.select().from(pluginJobRuns).where(and(...conditions)).orderBy(desc(pluginJobRuns.createdAt)).limit(limit); - } - }; -} - -// server/src/services/plugin-tool-registry.ts -var TOOL_NAMESPACE_SEPARATOR = ":"; -function createPluginToolRegistry(workerManager) { - const log2 = logger.child({ service: "plugin-tool-registry" }); - const byNamespace = /* @__PURE__ */ new Map(); - const byPlugin = /* @__PURE__ */ new Map(); - function buildName(pluginId, toolName) { - return `${pluginId}${TOOL_NAMESPACE_SEPARATOR}${toolName}`; - } - function parseName(namespacedName) { - const sepIndex = namespacedName.lastIndexOf(TOOL_NAMESPACE_SEPARATOR); - if (sepIndex <= 0 || sepIndex >= namespacedName.length - 1) { - return null; - } - return { - pluginId: namespacedName.slice(0, sepIndex), - toolName: namespacedName.slice(sepIndex + 1) - }; - } - function addTool(pluginId, decl, pluginDbId) { - const namespacedName = buildName(pluginId, decl.name); - const entry = { - pluginId, - pluginDbId, - name: decl.name, - namespacedName, - displayName: decl.displayName, - description: decl.description, - parametersSchema: decl.parametersSchema - }; - byNamespace.set(namespacedName, entry); - let pluginTools = byPlugin.get(pluginId); - if (!pluginTools) { - pluginTools = /* @__PURE__ */ new Set(); - byPlugin.set(pluginId, pluginTools); - } - pluginTools.add(namespacedName); - } - function removePluginTools(pluginId) { - const pluginTools = byPlugin.get(pluginId); - if (!pluginTools) return 0; - const count2 = pluginTools.size; - for (const name of pluginTools) { - byNamespace.delete(name); - } - byPlugin.delete(pluginId); - return count2; - } - return { - registerPlugin(pluginId, manifest, pluginDbId) { - const dbId = pluginDbId ?? pluginId; - const previousCount = removePluginTools(pluginId); - if (previousCount > 0) { - log2.debug( - { pluginId, previousCount }, - "cleared previous tool registrations before re-registering" - ); - } - const tools = manifest.tools ?? []; - if (tools.length === 0) { - log2.debug({ pluginId }, "plugin declares no tools"); - return; - } - for (const decl of tools) { - addTool(pluginId, decl, dbId); - } - log2.info( - { - pluginId, - toolCount: tools.length, - tools: tools.map((t5) => buildName(pluginId, t5.name)) - }, - `registered ${tools.length} tool(s) for plugin` - ); - }, - unregisterPlugin(pluginId) { - const removed = removePluginTools(pluginId); - if (removed > 0) { - log2.info( - { pluginId, removedCount: removed }, - `unregistered ${removed} tool(s) for plugin` - ); - } - }, - getTool(namespacedName) { - return byNamespace.get(namespacedName) ?? null; - }, - getToolByPlugin(pluginId, toolName) { - const namespacedName = buildName(pluginId, toolName); - return byNamespace.get(namespacedName) ?? null; - }, - listTools(filter) { - if (filter?.pluginId) { - const pluginTools = byPlugin.get(filter.pluginId); - if (!pluginTools) return []; - const result = []; - for (const name of pluginTools) { - const tool = byNamespace.get(name); - if (tool) result.push(tool); - } - return result; - } - return Array.from(byNamespace.values()); - }, - parseNamespacedName(namespacedName) { - return parseName(namespacedName); - }, - buildNamespacedName(pluginId, toolName) { - return buildName(pluginId, toolName); - }, - async executeTool(namespacedName, parameters, runContext) { - const parsed = parseName(namespacedName); - if (!parsed) { - throw new Error( - `Invalid tool name "${namespacedName}". Expected format: "${TOOL_NAMESPACE_SEPARATOR}"` - ); - } - const { pluginId, toolName } = parsed; - const tool = byNamespace.get(namespacedName); - if (!tool) { - throw new Error( - `Tool "${namespacedName}" is not registered. The plugin may not be installed or its worker may not be running.` - ); - } - if (!workerManager) { - throw new Error( - `Cannot execute tool "${namespacedName}" \u2014 no worker manager configured. Tool execution requires a PluginWorkerManager.` - ); - } - const dbId = tool.pluginDbId; - if (!workerManager.isRunning(dbId)) { - throw new Error( - `Cannot execute tool "${namespacedName}" \u2014 worker for plugin "${pluginId}" is not running.` - ); - } - log2.debug( - { pluginId, pluginDbId: dbId, toolName, namespacedName, agentId: runContext.agentId, runId: runContext.runId }, - "executing tool via plugin worker" - ); - const rpcParams = { - toolName, - parameters, - runContext - }; - const result = await workerManager.call(dbId, "executeTool", rpcParams); - log2.debug( - { - pluginId, - toolName, - namespacedName, - hasContent: !!result.content, - hasData: result.data !== void 0, - hasError: !!result.error - }, - "tool execution completed" - ); - return { pluginId, toolName, result }; - }, - toolCount(pluginId) { - if (pluginId !== void 0) { - return byPlugin.get(pluginId)?.size ?? 0; - } - return byNamespace.size; - } - }; -} - -// server/src/services/plugin-tool-dispatcher.ts -function createPluginToolDispatcher(options = {}) { - const { workerManager, lifecycleManager, db } = options; - const log2 = logger.child({ service: "plugin-tool-dispatcher" }); - const registry2 = createPluginToolRegistry(workerManager); - let enabledListener = null; - let disabledListener = null; - let unloadedListener = null; - let initialized = false; - async function registerFromDb(pluginId) { - if (!db) { - log2.warn( - { pluginId }, - "cannot register tools from DB \u2014 no database connection configured" - ); - return; - } - const pluginRegistry = pluginRegistryService(db); - const plugin = await pluginRegistry.getById(pluginId); - if (!plugin) { - log2.warn({ pluginId }, "plugin not found in registry, cannot register tools"); - return; - } - const manifest = plugin.manifestJson; - if (!manifest) { - log2.warn({ pluginId }, "plugin has no manifest, cannot register tools"); - return; - } - registry2.registerPlugin(plugin.pluginKey, manifest, plugin.id); - } - function toAgentDescriptor(tool) { - return { - name: tool.namespacedName, - displayName: tool.displayName, - description: tool.description, - parametersSchema: tool.parametersSchema, - pluginId: tool.pluginDbId - }; - } - function handlePluginEnabled(payload2) { - log2.debug({ pluginId: payload2.pluginId, pluginKey: payload2.pluginKey }, "plugin enabled \u2014 registering tools"); - void registerFromDb(payload2.pluginId).catch((err) => { - log2.error( - { pluginId: payload2.pluginId, err: err instanceof Error ? err.message : String(err) }, - "failed to register tools after plugin enabled" - ); - }); - } - function handlePluginDisabled(payload2) { - log2.debug({ pluginId: payload2.pluginId, pluginKey: payload2.pluginKey }, "plugin disabled \u2014 unregistering tools"); - registry2.unregisterPlugin(payload2.pluginKey); - } - function handlePluginUnloaded(payload2) { - log2.debug({ pluginId: payload2.pluginId, pluginKey: payload2.pluginKey }, "plugin unloaded \u2014 unregistering tools"); - registry2.unregisterPlugin(payload2.pluginKey); - } - return { - async initialize() { - if (initialized) { - log2.warn("dispatcher already initialized, skipping"); - return; - } - log2.info("initializing plugin tool dispatcher"); - if (db) { - const pluginRegistry = pluginRegistryService(db); - const readyPlugins = await pluginRegistry.listByStatus("ready"); - let totalTools = 0; - for (const plugin of readyPlugins) { - const manifest = plugin.manifestJson; - if (manifest?.tools && manifest.tools.length > 0) { - registry2.registerPlugin(plugin.pluginKey, manifest, plugin.id); - totalTools += manifest.tools.length; - } - } - log2.info( - { readyPlugins: readyPlugins.length, registeredTools: totalTools }, - "loaded tools from ready plugins" - ); - } - if (lifecycleManager) { - enabledListener = handlePluginEnabled; - disabledListener = handlePluginDisabled; - unloadedListener = handlePluginUnloaded; - lifecycleManager.on("plugin.enabled", enabledListener); - lifecycleManager.on("plugin.disabled", disabledListener); - lifecycleManager.on("plugin.unloaded", unloadedListener); - log2.debug("subscribed to lifecycle events"); - } else { - log2.warn("no lifecycle manager provided \u2014 tools will not auto-update on plugin state changes"); - } - initialized = true; - log2.info( - { totalTools: registry2.toolCount() }, - "plugin tool dispatcher initialized" - ); - }, - teardown() { - if (!initialized) return; - if (lifecycleManager) { - if (enabledListener) lifecycleManager.off("plugin.enabled", enabledListener); - if (disabledListener) lifecycleManager.off("plugin.disabled", disabledListener); - if (unloadedListener) lifecycleManager.off("plugin.unloaded", unloadedListener); - enabledListener = null; - disabledListener = null; - unloadedListener = null; - } - initialized = false; - log2.info("plugin tool dispatcher torn down"); - }, - listToolsForAgent(filter) { - return registry2.listTools(filter).map(toAgentDescriptor); - }, - getTool(namespacedName) { - return registry2.getTool(namespacedName); - }, - async executeTool(namespacedName, parameters, runContext) { - log2.debug( - { - tool: namespacedName, - agentId: runContext.agentId, - runId: runContext.runId - }, - "dispatching tool execution" - ); - const result = await registry2.executeTool( - namespacedName, - parameters, - runContext - ); - log2.debug( - { - tool: namespacedName, - pluginId: result.pluginId, - hasContent: !!result.result.content, - hasError: !!result.result.error - }, - "tool execution completed" - ); - return result; - }, - registerPluginTools(pluginId, manifest) { - registry2.registerPlugin(pluginId, manifest); - }, - unregisterPluginTools(pluginId) { - registry2.unregisterPlugin(pluginId); - }, - toolCount(pluginId) { - return registry2.toolCount(pluginId); - }, - getRegistry() { - return registry2; - } - }; -} - -// server/src/services/plugin-job-coordinator.ts -function createPluginJobCoordinator(options) { - const { db, lifecycle, scheduler, jobStore } = options; - const log2 = logger.child({ service: "plugin-job-coordinator" }); - const registry2 = pluginRegistryService(db); - async function onPluginLoaded(payload2) { - const { pluginId, pluginKey } = payload2; - log2.info({ pluginId, pluginKey }, "plugin loaded \u2014 syncing jobs and registering with scheduler"); - try { - const plugin = await registry2.getById(pluginId); - if (!plugin?.manifestJson) { - log2.warn({ pluginId, pluginKey }, "plugin loaded but no manifest found \u2014 skipping job sync"); - return; - } - const manifest = plugin.manifestJson; - const jobDeclarations = manifest.jobs ?? []; - if (jobDeclarations.length > 0) { - log2.info( - { pluginId, pluginKey, jobCount: jobDeclarations.length }, - "syncing job declarations from manifest" - ); - await jobStore.syncJobDeclarations(pluginId, jobDeclarations); - } - await scheduler.registerPlugin(pluginId); - } catch (err) { - log2.error( - { - pluginId, - pluginKey, - err: err instanceof Error ? err.message : String(err) - }, - "failed to sync jobs or register plugin with scheduler" - ); - } - } - async function onPluginDisabled(payload2) { - const { pluginId, pluginKey, reason } = payload2; - log2.info( - { pluginId, pluginKey, reason }, - "plugin disabled \u2014 unregistering from scheduler" - ); - try { - await scheduler.unregisterPlugin(pluginId); - } catch (err) { - log2.error( - { - pluginId, - pluginKey, - err: err instanceof Error ? err.message : String(err) - }, - "failed to unregister plugin from scheduler" - ); - } - } - async function onPluginUnloaded(payload2) { - const { pluginId, pluginKey, removeData } = payload2; - log2.info( - { pluginId, pluginKey, removeData }, - "plugin unloaded \u2014 unregistering from scheduler" - ); - try { - await scheduler.unregisterPlugin(pluginId); - if (removeData) { - log2.info({ pluginId, pluginKey }, "purging job data for uninstalled plugin"); - await jobStore.deleteAllJobs(pluginId); - } - } catch (err) { - log2.error( - { - pluginId, - pluginKey, - err: err instanceof Error ? err.message : String(err) - }, - "failed to unregister plugin from scheduler during unload" - ); - } - } - let attached = false; - const boundOnLoaded = (payload2) => { - void onPluginLoaded(payload2); - }; - const boundOnDisabled = (payload2) => { - void onPluginDisabled(payload2); - }; - const boundOnUnloaded = (payload2) => { - void onPluginUnloaded(payload2); - }; - return { - start() { - if (attached) return; - attached = true; - lifecycle.on("plugin.loaded", boundOnLoaded); - lifecycle.on("plugin.disabled", boundOnDisabled); - lifecycle.on("plugin.unloaded", boundOnUnloaded); - log2.info("plugin job coordinator started \u2014 listening to lifecycle events"); - }, - stop() { - if (!attached) return; - attached = false; - lifecycle.off("plugin.loaded", boundOnLoaded); - lifecycle.off("plugin.disabled", boundOnDisabled); - lifecycle.off("plugin.unloaded", boundOnUnloaded); - log2.info("plugin job coordinator stopped"); - } - }; -} - -// server/src/services/plugin-host-services.ts -init_src2(); -init_drizzle_orm(); -import { randomUUID as randomUUID11 } from "node:crypto"; - -// server/src/services/plugin-state-store.ts -init_drizzle_orm(); -init_src2(); -var DEFAULT_NAMESPACE = "default"; -function scopeConditions(pluginId, scopeKind, scopeId, namespace, stateKey) { - const conditions = [ - eq(pluginState.pluginId, pluginId), - eq(pluginState.scopeKind, scopeKind), - eq(pluginState.namespace, namespace), - eq(pluginState.stateKey, stateKey) - ]; - if (scopeId != null && scopeId !== "") { - conditions.push(eq(pluginState.scopeId, scopeId)); - } else { - conditions.push(isNull(pluginState.scopeId)); - } - return and(...conditions); -} -function pluginStateStore(db) { - async function assertPluginExists(pluginId) { - const rows = await db.select({ id: plugins.id }).from(plugins).where(eq(plugins.id, pluginId)); - if (rows.length === 0) { - throw notFound(`Plugin not found: ${pluginId}`); - } - } - return { - /** - * Read a state value. - * - * Returns the stored JSON value, or `null` if no entry exists for the - * given scope and key. - * - * Requires `plugin.state.read` capability (enforced by the caller). - * - * @param pluginId - UUID of the owning plugin - * @param scopeKind - Granularity of the scope - * @param scopeId - Identifier for the scoped entity (null for `instance` scope) - * @param stateKey - The key to read - * @param namespace - Sub-namespace (defaults to `"default"`) - */ - get: async (pluginId, scopeKind, stateKey, { - scopeId, - namespace = DEFAULT_NAMESPACE - } = {}) => { - const rows = await db.select().from(pluginState).where(scopeConditions(pluginId, scopeKind, scopeId, namespace, stateKey)); - return rows[0]?.valueJson ?? null; - }, - /** - * Write (create or replace) a state value. - * - * Uses an upsert so the caller does not need to check for prior existence. - * On conflict (same composite key) the existing row's `value_json` and - * `updated_at` are overwritten. - * - * Requires `plugin.state.write` capability (enforced by the caller). - * - * @param pluginId - UUID of the owning plugin - * @param input - Scope key and value to store - */ - set: async (pluginId, input) => { - await assertPluginExists(pluginId); - const namespace = input.namespace ?? DEFAULT_NAMESPACE; - const scopeId = input.scopeId ?? null; - await db.insert(pluginState).values({ - pluginId, - scopeKind: input.scopeKind, - scopeId, - namespace, - stateKey: input.stateKey, - valueJson: input.value, - updatedAt: /* @__PURE__ */ new Date() - }).onConflictDoUpdate({ - target: [ - pluginState.pluginId, - pluginState.scopeKind, - pluginState.scopeId, - pluginState.namespace, - pluginState.stateKey - ], - set: { - valueJson: input.value, - updatedAt: /* @__PURE__ */ new Date() - } - }); - }, - /** - * Delete a state value. - * - * No-ops silently if the entry does not exist (idempotent by design). - * - * Requires `plugin.state.write` capability (enforced by the caller). - * - * @param pluginId - UUID of the owning plugin - * @param scopeKind - Granularity of the scope - * @param stateKey - The key to delete - * @param scopeId - Identifier for the scoped entity (null for `instance` scope) - * @param namespace - Sub-namespace (defaults to `"default"`) - */ - delete: async (pluginId, scopeKind, stateKey, { - scopeId, - namespace = DEFAULT_NAMESPACE - } = {}) => { - await db.delete(pluginState).where(scopeConditions(pluginId, scopeKind, scopeId, namespace, stateKey)); - }, - /** - * List all state entries for a plugin, optionally filtered by scope. - * - * Returns all matching rows as `PluginStateRecord`-shaped objects. - * The `valueJson` field contains the stored value. - * - * Requires `plugin.state.read` capability (enforced by the caller). - * - * @param pluginId - UUID of the owning plugin - * @param filter - Optional scope filters (scopeKind, scopeId, namespace) - */ - list: async (pluginId, filter = {}) => { - const conditions = [eq(pluginState.pluginId, pluginId)]; - if (filter.scopeKind !== void 0) { - conditions.push(eq(pluginState.scopeKind, filter.scopeKind)); - } - if (filter.scopeId !== void 0) { - conditions.push(eq(pluginState.scopeId, filter.scopeId)); - } - if (filter.namespace !== void 0) { - conditions.push(eq(pluginState.namespace, filter.namespace)); - } - return db.select().from(pluginState).where(and(...conditions)); - }, - /** - * Delete all state entries owned by a plugin. - * - * Called during plugin uninstall when `removeData = true`. Also useful - * for resetting a plugin's state during testing. - * - * @param pluginId - UUID of the owning plugin - */ - deleteAll: async (pluginId) => { - await db.delete(pluginState).where(eq(pluginState.pluginId, pluginId)); - } - }; -} - -// server/src/services/plugin-secrets-handler.ts -init_drizzle_orm(); -init_src2(); -function secretNotFound(secretRef) { - const err = new Error(`Secret not found: ${secretRef}`); - err.name = "SecretNotFoundError"; - return err; -} -function secretVersionNotFound(secretRef) { - const err = new Error(`No version found for secret: ${secretRef}`); - err.name = "SecretVersionNotFoundError"; - return err; -} -function invalidSecretRef(secretRef) { - const err = new Error(`Invalid secret reference: ${secretRef}`); - err.name = "InvalidSecretRefError"; - return err; -} -var UUID_RE3 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; -function isUuid(value) { - return UUID_RE3.test(value); -} -function collectSecretRefPaths(schema2) { - const paths2 = /* @__PURE__ */ new Set(); - if (!schema2 || typeof schema2 !== "object") return paths2; - function walk(node, prefix) { - const props = node.properties; - if (!props || typeof props !== "object") return; - for (const [key, propSchema] of Object.entries(props)) { - if (!propSchema || typeof propSchema !== "object") continue; - const path53 = prefix ? `${prefix}.${key}` : key; - if (propSchema.format === "secret-ref") { - paths2.add(path53); - } - if (propSchema.type === "object") { - walk(propSchema, path53); - } - } - } - walk(schema2, ""); - return paths2; -} -function extractSecretRefsFromConfig(configJson, schema2) { - const refs = /* @__PURE__ */ new Set(); - if (configJson == null || typeof configJson !== "object") return refs; - const secretPaths = collectSecretRefPaths(schema2); - if (secretPaths.size > 0) { - for (const dotPath of secretPaths) { - const keys = dotPath.split("."); - let current = configJson; - for (const k5 of keys) { - if (current == null || typeof current !== "object") { - current = void 0; - break; - } - current = current[k5]; - } - if (typeof current === "string" && isUuid(current)) { - refs.add(current); - } - } - return refs; - } - function walkAll(value) { - if (typeof value === "string") { - if (isUuid(value)) refs.add(value); - } else if (Array.isArray(value)) { - for (const item of value) walkAll(item); - } else if (value !== null && typeof value === "object") { - for (const v5 of Object.values(value)) walkAll(v5); - } - } - walkAll(configJson); - return refs; -} -function createRateLimiter(maxAttempts, windowMs) { - const attempts = /* @__PURE__ */ new Map(); - return { - check(key) { - const now2 = Date.now(); - const windowStart = now2 - windowMs; - const existing = (attempts.get(key) ?? []).filter((ts) => ts > windowStart); - if (existing.length >= maxAttempts) return false; - existing.push(now2); - attempts.set(key, existing); - return true; - } - }; -} -function createPluginSecretsHandler(options) { - const { db, pluginId } = options; - const registry2 = pluginRegistryService(db); - const rateLimiter = createRateLimiter(30, 6e4); - let cachedAllowedRefs = null; - let cachedAllowedRefsExpiry = 0; - const CONFIG_CACHE_TTL_MS = 3e4; - return { - async resolve(params) { - const { secretRef } = params; - if (!rateLimiter.check(pluginId)) { - const err = new Error("Rate limit exceeded for secret resolution"); - err.name = "RateLimitExceededError"; - throw err; - } - if (!secretRef || typeof secretRef !== "string" || secretRef.trim().length === 0) { - throw invalidSecretRef(secretRef ?? ""); - } - const trimmedRef = secretRef.trim(); - if (!isUuid(trimmedRef)) { - throw invalidSecretRef(trimmedRef); - } - const now2 = Date.now(); - if (!cachedAllowedRefs || now2 > cachedAllowedRefsExpiry) { - const [configRow, plugin] = await Promise.all([ - db.select().from(pluginConfig).where(eq(pluginConfig.pluginId, pluginId)).then((rows) => rows[0] ?? null), - registry2.getById(pluginId) - ]); - const schema2 = plugin?.manifestJson?.instanceConfigSchema; - cachedAllowedRefs = extractSecretRefsFromConfig(configRow?.configJson, schema2); - cachedAllowedRefsExpiry = now2 + CONFIG_CACHE_TTL_MS; - } - if (!cachedAllowedRefs.has(trimmedRef)) { - throw secretNotFound(trimmedRef); - } - const secret = await db.select().from(companySecrets).where(eq(companySecrets.id, trimmedRef)).then((rows) => rows[0] ?? null); - if (!secret) { - throw secretNotFound(trimmedRef); - } - const versionRow = await db.select().from(companySecretVersions).where( - and( - eq(companySecretVersions.secretId, secret.id), - eq(companySecretVersions.version, secret.latestVersion) - ) - ).then((rows) => rows[0] ?? null); - if (!versionRow) { - throw secretVersionNotFound(trimmedRef); - } - const provider = getSecretProvider(secret.provider); - const resolved = await provider.resolveVersion({ - material: versionRow.material, - externalRef: secret.externalRef - }); - return resolved; - } - }; -} - -// server/src/services/plugin-host-services.ts -import { lookup as dnsLookup } from "node:dns/promises"; -import { request as httpRequest } from "node:http"; -import { request as httpsRequest } from "node:https"; -import { isIP } from "node:net"; -var PLUGIN_FETCH_TIMEOUT_MS = 3e4; -var DNS_LOOKUP_TIMEOUT_MS = 5e3; -var ALLOWED_PROTOCOLS = /* @__PURE__ */ new Set(["http:", "https:"]); -var TELEMETRY_EVENT_NAME_REGEX = /^[a-z0-9][a-z0-9_-]*$/; -function isPrivateIP(ip) { - const lower = ip.toLowerCase(); - const v4MappedMatch = lower.match(/^::ffff:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/); - if (v4MappedMatch && v4MappedMatch[1]) return isPrivateIP(v4MappedMatch[1]); - if (ip.startsWith("10.")) return true; - if (ip.startsWith("172.")) { - const second = parseInt(ip.split(".")[1], 10); - if (second >= 16 && second <= 31) return true; - } - if (ip.startsWith("192.168.")) return true; - if (ip.startsWith("127.")) return true; - if (ip.startsWith("169.254.")) return true; - if (ip === "0.0.0.0") return true; - if (lower === "::1") return true; - if (lower.startsWith("fc") || lower.startsWith("fd")) return true; - if (lower.startsWith("fe80")) return true; - if (lower === "::") return true; - return false; -} -async function validateAndResolveFetchUrl(urlString) { - let parsed; - try { - parsed = new URL(urlString); - } catch { - throw new Error(`Invalid URL: ${urlString}`); - } - if (!ALLOWED_PROTOCOLS.has(parsed.protocol)) { - throw new Error( - `Disallowed protocol "${parsed.protocol}" \u2014 only http: and https: are permitted` - ); - } - const originalHostname = parsed.hostname.replace(/^\[|\]$/g, ""); - const hostHeader = parsed.host; - const dnsPromise = dnsLookup(originalHostname, { all: true }); - const timeoutPromise = new Promise((_, reject) => { - setTimeout( - () => reject(new Error(`DNS lookup timed out after ${DNS_LOOKUP_TIMEOUT_MS}ms for ${originalHostname}`)), - DNS_LOOKUP_TIMEOUT_MS - ); - }); - try { - const results = await Promise.race([dnsPromise, timeoutPromise]); - if (results.length === 0) { - throw new Error(`DNS resolution returned no results for ${originalHostname}`); - } - const safeResults = results.filter((entry) => !isPrivateIP(entry.address)); - if (safeResults.length === 0) { - throw new Error( - `All resolved IPs for ${originalHostname} are in private/reserved ranges` - ); - } - const resolved = safeResults[0]; - return { - parsedUrl: parsed, - resolvedAddress: resolved.address, - hostHeader, - tlsServername: parsed.protocol === "https:" && isIP(originalHostname) === 0 ? originalHostname : void 0, - useTls: parsed.protocol === "https:" - }; - } catch (err) { - if (err instanceof Error && (err.message.startsWith("All resolved IPs") || err.message.startsWith("DNS resolution returned") || err.message.startsWith("DNS lookup timed out"))) throw err; - throw new Error(`DNS resolution failed for ${originalHostname}: ${err.message}`); - } -} -function buildPinnedRequestOptions(target, init2) { - const headers = new Headers(init2?.headers); - const method = init2?.method ?? "GET"; - const body = init2?.body === void 0 || init2?.body === null ? void 0 : typeof init2.body === "string" ? init2.body : String(init2.body); - headers.set("Host", target.hostHeader); - if (body !== void 0 && !headers.has("content-length") && !headers.has("transfer-encoding")) { - headers.set("content-length", String(Buffer.byteLength(body))); - } - const pathname = `${target.parsedUrl.pathname}${target.parsedUrl.search}`; - const auth = target.parsedUrl.username || target.parsedUrl.password ? `${decodeURIComponent(target.parsedUrl.username)}:${decodeURIComponent(target.parsedUrl.password)}` : void 0; - return { - options: { - protocol: target.parsedUrl.protocol, - host: target.resolvedAddress, - port: target.parsedUrl.port ? Number(target.parsedUrl.port) : target.useTls ? 443 : 80, - path: pathname, - method, - headers: Object.fromEntries(headers.entries()), - auth, - servername: target.tlsServername - }, - body - }; -} -async function executePinnedHttpRequest(target, init2, signal) { - const { options, body } = buildPinnedRequestOptions(target, init2); - const response = await new Promise((resolve4, reject) => { - const requestFn = target.useTls ? httpsRequest : httpRequest; - const req = requestFn({ ...options, signal }, resolve4); - req.on("error", reject); - if (body !== void 0) { - req.write(body); - } - req.end(); - }); - const MAX_RESPONSE_BODY_BYTES = 200 * 1024 * 1024; - const chunks = []; - let totalBytes = 0; - await new Promise((resolve4, reject) => { - response.on("data", (chunk) => { - const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk); - totalBytes += buf.length; - if (totalBytes > MAX_RESPONSE_BODY_BYTES) { - chunks.length = 0; - response.destroy(new Error(`Response body exceeded ${MAX_RESPONSE_BODY_BYTES} bytes`)); - return; - } - chunks.push(buf); - }); - response.on("end", resolve4); - response.on("error", reject); - }); - const headers = {}; - for (const [key, value] of Object.entries(response.headers)) { - if (Array.isArray(value)) { - headers[key] = value.join(", "); - } else if (value !== void 0) { - headers[key] = value; - } - } - return { - status: response.statusCode ?? 500, - statusText: response.statusMessage ?? "", - headers, - body: Buffer.concat(chunks).toString("utf8") - }; -} -var UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i; -var PATH_LIKE_PATTERN = /[\\/]/; -var WINDOWS_DRIVE_PATH_PATTERN = /^[A-Za-z]:[\\/]/; -function looksLikePath(value) { - const normalized = value.trim(); - return (PATH_LIKE_PATTERN.test(normalized) || WINDOWS_DRIVE_PATH_PATTERN.test(normalized)) && !UUID_PATTERN.test(normalized); -} -function sanitizeWorkspaceText(value) { - const trimmed = value.trim(); - if (!trimmed || UUID_PATTERN.test(trimmed)) return ""; - return trimmed; -} -function sanitizeWorkspacePath(cwd) { - if (!cwd) return ""; - return looksLikePath(cwd) ? cwd.trim() : ""; -} -function sanitizeWorkspaceName(name, fallbackPath) { - const safeName = sanitizeWorkspaceText(name); - if (safeName && !looksLikePath(safeName)) { - return safeName; - } - const normalized = fallbackPath.trim().replace(/[\\/]+$/, ""); - const segments = normalized.split(/[\\/]/).filter(Boolean); - return segments[segments.length - 1] ?? "Workspace"; -} -var LOG_BUFFER_FLUSH_SIZE = 100; -var LOG_BUFFER_FLUSH_INTERVAL_MS = 5e3; -var MAX_LOG_MESSAGE_LENGTH = 1e4; -var MAX_LOG_META_JSON_LENGTH = 5e4; -var MAX_METRIC_NAME_LENGTH = 500; -var PINO_RESERVED_KEYS = /* @__PURE__ */ new Set([ - "level", - "time", - "pid", - "hostname", - "msg", - "v" -]); -function truncStr(s5, max) { - if (s5.length <= max) return s5; - return s5.slice(0, max) + "...[truncated]"; -} -function sanitiseMeta(meta3) { - if (meta3 == null) return null; - const cleaned = {}; - for (const [k5, v5] of Object.entries(meta3)) { - if (!PINO_RESERVED_KEYS.has(k5)) { - cleaned[k5] = v5; - } - } - let json3; - try { - json3 = JSON.stringify(cleaned); - } catch { - return { _sanitised: true, _error: "meta was not JSON-serialisable" }; - } - if (json3.length > MAX_LOG_META_JSON_LENGTH) { - return { _sanitised: true, _error: `meta exceeded ${MAX_LOG_META_JSON_LENGTH} chars` }; - } - return cleaned; -} -var _logBuffer = []; -async function flushPluginLogBuffer() { - if (_logBuffer.length === 0) return; - const entries2 = _logBuffer.splice(0, _logBuffer.length); - const byDb = /* @__PURE__ */ new Map(); - for (const entry of entries2) { - const group = byDb.get(entry.db); - if (group) { - group.push(entry); - } else { - byDb.set(entry.db, [entry]); - } - } - for (const [dbInstance, group] of byDb) { - const values2 = group.map((e5) => ({ - pluginId: e5.pluginId, - level: e5.level, - message: e5.message, - meta: e5.meta - })); - try { - await dbInstance.insert(pluginLogs).values(values2); - } catch (err) { - try { - logger.warn({ err, count: values2.length }, "Failed to batch-persist plugin logs to DB"); - } catch { - console.error("[plugin-host-services] Batch log flush failed:", err); - } - } - } -} -var _logFlushInterval = setInterval(() => { - flushPluginLogBuffer().catch((err) => { - console.error("[plugin-host-services] Periodic log flush error:", err); - }); -}, LOG_BUFFER_FLUSH_INTERVAL_MS); -if (_logFlushInterval.unref) _logFlushInterval.unref(); -var SESSION_EVENT_SUBSCRIPTION_TIMEOUT_MS = 30 * 60 * 1e3; -function buildHostServices(db, pluginId, pluginKey, eventBus, notifyWorker) { - const registry2 = pluginRegistryService(db); - const stateStore = pluginStateStore(db); - const secretsHandler = createPluginSecretsHandler({ db, pluginId }); - const companies2 = companyService(db); - const agents2 = agentService(db); - const heartbeat = heartbeatService(db); - const projects2 = projectService(db); - const issues2 = issueService(db); - const documents2 = documentService(db); - const goals2 = goalService(db); - const activity = activityService(db); - const costs = costService(db); - const assets2 = assetService(db); - const scopedBus = eventBus.forPlugin(pluginKey); - const activeSubscriptions = /* @__PURE__ */ new Set(); - let disposed = false; - const ensureCompanyId = (companyId) => { - if (!companyId) throw new Error("companyId is required for this operation"); - return companyId; - }; - const parseWindowValue = (value) => { - if (typeof value === "number" && Number.isFinite(value)) { - return Math.max(0, Math.floor(value)); - } - if (typeof value === "string" && value.trim().length > 0) { - const parsed = Number(value); - if (Number.isFinite(parsed)) { - return Math.max(0, Math.floor(parsed)); - } - } - return null; - }; - const applyWindow = (rows, params) => { - const offset = parseWindowValue(params?.offset) ?? 0; - const limit = parseWindowValue(params?.limit); - if (limit == null) return rows.slice(offset); - return rows.slice(offset, offset + limit); - }; - const ensurePluginAvailableForCompany = async (_companyId) => { - }; - const inCompany = (record2, companyId) => Boolean(record2 && record2.companyId === companyId); - const requireInCompany = (entityName, record2, companyId) => { - if (!inCompany(record2, companyId)) { - throw new Error(`${entityName} not found`); - } - return record2; - }; - return { - config: { - async get() { - const configRow = await registry2.getConfig(pluginId); - return configRow?.configJson ?? {}; - } - }, - state: { - async get(params) { - return stateStore.get(pluginId, params.scopeKind, params.stateKey, { - scopeId: params.scopeId, - namespace: params.namespace - }); - }, - async set(params) { - await stateStore.set(pluginId, { - scopeKind: params.scopeKind, - scopeId: params.scopeId, - namespace: params.namespace, - stateKey: params.stateKey, - value: params.value - }); - }, - async delete(params) { - await stateStore.delete(pluginId, params.scopeKind, params.stateKey, { - scopeId: params.scopeId, - namespace: params.namespace - }); - } - }, - entities: { - async upsert(params) { - return registry2.upsertEntity(pluginId, params); - }, - async list(params) { - return registry2.listEntities(pluginId, params); - } - }, - events: { - async emit(params) { - if (params.companyId) { - await ensurePluginAvailableForCompany(params.companyId); - } - await scopedBus.emit(params.name, params.companyId, params.payload); - }, - async subscribe(params) { - const handler = async (event) => { - if (notifyWorker) { - notifyWorker("onEvent", { event }); - } - }; - if (params.filter) { - scopedBus.subscribe(params.eventPattern, params.filter, handler); - } else { - scopedBus.subscribe(params.eventPattern, handler); - } - } - }, - http: { - async fetch(params) { - const target = await validateAndResolveFetchUrl(params.url); - const controller = new AbortController(); - const timeout = setTimeout(() => controller.abort(), PLUGIN_FETCH_TIMEOUT_MS); - try { - const init2 = params.init; - return await executePinnedHttpRequest(target, init2, controller.signal); - } finally { - clearTimeout(timeout); - } - } - }, - secrets: { - async resolve(params) { - return secretsHandler.resolve(params); - } - }, - activity: { - async log(params) { - const companyId = ensureCompanyId(params.companyId); - await ensurePluginAvailableForCompany(companyId); - await logActivity(db, { - companyId, - actorType: "system", - actorId: pluginId, - action: params.message, - entityType: params.entityType ?? "plugin", - entityId: params.entityId ?? pluginId, - details: params.metadata - }); - } - }, - metrics: { - async write(params) { - const safeName = truncStr(String(params.name ?? ""), MAX_METRIC_NAME_LENGTH); - logger.debug({ pluginId, name: safeName, value: params.value, tags: params.tags }, "Plugin metric write"); - _logBuffer.push({ - db, - pluginId, - level: "metric", - message: safeName, - meta: sanitiseMeta({ value: params.value, tags: params.tags ?? null }) - }); - if (_logBuffer.length >= LOG_BUFFER_FLUSH_SIZE) { - flushPluginLogBuffer().catch((err) => { - console.error("[plugin-host-services] Triggered metric flush failed:", err); - }); - } - } - }, - telemetry: { - async track(params) { - const eventName = String(params.eventName ?? "").trim(); - if (!TELEMETRY_EVENT_NAME_REGEX.test(eventName)) { - throw new Error( - 'Plugin telemetry event names must be lowercase slugs using letters, numbers, "_" or "-".' - ); - } - const telemetryClient = getTelemetryClient(); - if (!telemetryClient) return; - telemetryClient.track(`plugin.${pluginKey}.${eventName}`, params.dimensions); - } - }, - logger: { - async log(params) { - const { level, meta: meta3 } = params; - const safeMessage = truncStr(String(params.message ?? ""), MAX_LOG_MESSAGE_LENGTH); - const safeMeta = sanitiseMeta(meta3); - const pluginLogger = logger.child({ service: "plugin-worker", pluginId }); - const logFields = { - ...safeMeta, - pluginLogLevel: level, - pluginTimestamp: (/* @__PURE__ */ new Date()).toISOString() - }; - if (level === "error") pluginLogger.error(logFields, `[plugin] ${safeMessage}`); - else if (level === "warn") pluginLogger.warn(logFields, `[plugin] ${safeMessage}`); - else if (level === "debug") pluginLogger.debug(logFields, `[plugin] ${safeMessage}`); - else pluginLogger.info(logFields, `[plugin] ${safeMessage}`); - _logBuffer.push({ - db, - pluginId, - level: level ?? "info", - message: safeMessage, - meta: safeMeta - }); - if (_logBuffer.length >= LOG_BUFFER_FLUSH_SIZE) { - flushPluginLogBuffer().catch((err) => { - console.error("[plugin-host-services] Triggered log flush failed:", err); - }); - } - } - }, - companies: { - async list(params) { - return applyWindow(await companies2.list(), params); - }, - async get(params) { - await ensurePluginAvailableForCompany(params.companyId); - return await companies2.getById(params.companyId); - } - }, - projects: { - async list(params) { - const companyId = ensureCompanyId(params.companyId); - await ensurePluginAvailableForCompany(companyId); - return applyWindow(await projects2.list(companyId), params); - }, - async get(params) { - const companyId = ensureCompanyId(params.companyId); - await ensurePluginAvailableForCompany(companyId); - const project = await projects2.getById(params.projectId); - return inCompany(project, companyId) ? project : null; - }, - async listWorkspaces(params) { - const companyId = ensureCompanyId(params.companyId); - await ensurePluginAvailableForCompany(companyId); - const project = await projects2.getById(params.projectId); - if (!inCompany(project, companyId)) return []; - const rows = await projects2.listWorkspaces(params.projectId); - return rows.map((row) => { - const path53 = sanitizeWorkspacePath(row.cwd); - const name = sanitizeWorkspaceName(row.name, path53); - return { - id: row.id, - projectId: row.projectId, - name, - path: path53, - isPrimary: row.isPrimary, - createdAt: row.createdAt.toISOString(), - updatedAt: row.updatedAt.toISOString() - }; - }); - }, - async getPrimaryWorkspace(params) { - const companyId = ensureCompanyId(params.companyId); - await ensurePluginAvailableForCompany(companyId); - const project = await projects2.getById(params.projectId); - if (!inCompany(project, companyId)) return null; - const row = project.primaryWorkspace; - const path53 = sanitizeWorkspacePath(project.codebase.effectiveLocalFolder); - const name = sanitizeWorkspaceName(row?.name ?? project.name, path53); - return { - id: row?.id ?? `${project.id}:managed`, - projectId: project.id, - name, - path: path53, - isPrimary: true, - createdAt: (row?.createdAt ?? project.createdAt).toISOString(), - updatedAt: (row?.updatedAt ?? project.updatedAt).toISOString() - }; - }, - async getWorkspaceForIssue(params) { - const companyId = ensureCompanyId(params.companyId); - await ensurePluginAvailableForCompany(companyId); - const issue2 = await issues2.getById(params.issueId); - if (!inCompany(issue2, companyId)) return null; - const projectId = issue2.projectId; - if (!projectId) return null; - const project = await projects2.getById(projectId); - if (!inCompany(project, companyId)) return null; - const row = project.primaryWorkspace; - const path53 = sanitizeWorkspacePath(project.codebase.effectiveLocalFolder); - const name = sanitizeWorkspaceName(row?.name ?? project.name, path53); - return { - id: row?.id ?? `${project.id}:managed`, - projectId: project.id, - name, - path: path53, - isPrimary: true, - createdAt: (row?.createdAt ?? project.createdAt).toISOString(), - updatedAt: (row?.updatedAt ?? project.updatedAt).toISOString() - }; - } - }, - issues: { - async list(params) { - const companyId = ensureCompanyId(params.companyId); - await ensurePluginAvailableForCompany(companyId); - return applyWindow(await issues2.list(companyId, params), params); - }, - async get(params) { - const companyId = ensureCompanyId(params.companyId); - await ensurePluginAvailableForCompany(companyId); - const issue2 = await issues2.getById(params.issueId); - return inCompany(issue2, companyId) ? issue2 : null; - }, - async create(params) { - const companyId = ensureCompanyId(params.companyId); - await ensurePluginAvailableForCompany(companyId); - return await issues2.create(companyId, params); - }, - async update(params) { - const companyId = ensureCompanyId(params.companyId); - await ensurePluginAvailableForCompany(companyId); - requireInCompany("Issue", await issues2.getById(params.issueId), companyId); - return await issues2.update(params.issueId, params.patch); - }, - async listComments(params) { - const companyId = ensureCompanyId(params.companyId); - await ensurePluginAvailableForCompany(companyId); - if (!inCompany(await issues2.getById(params.issueId), companyId)) return []; - return await issues2.listComments(params.issueId); - }, - async createComment(params) { - const companyId = ensureCompanyId(params.companyId); - await ensurePluginAvailableForCompany(companyId); - requireInCompany("Issue", await issues2.getById(params.issueId), companyId); - return await issues2.addComment( - params.issueId, - params.body, - { agentId: params.authorAgentId } - ); - } - }, - issueDocuments: { - async list(params) { - const companyId = ensureCompanyId(params.companyId); - await ensurePluginAvailableForCompany(companyId); - requireInCompany("Issue", await issues2.getById(params.issueId), companyId); - const rows = await documents2.listIssueDocuments(params.issueId); - return rows; - }, - async get(params) { - const companyId = ensureCompanyId(params.companyId); - await ensurePluginAvailableForCompany(companyId); - requireInCompany("Issue", await issues2.getById(params.issueId), companyId); - const doc = await documents2.getIssueDocumentByKey(params.issueId, params.key); - return doc ?? null; - }, - async upsert(params) { - const companyId = ensureCompanyId(params.companyId); - await ensurePluginAvailableForCompany(companyId); - requireInCompany("Issue", await issues2.getById(params.issueId), companyId); - const result = await documents2.upsertIssueDocument({ - issueId: params.issueId, - key: params.key, - body: params.body, - title: params.title ?? null, - format: params.format ?? "markdown", - changeSummary: params.changeSummary ?? null - }); - return result.document; - }, - async delete(params) { - const companyId = ensureCompanyId(params.companyId); - await ensurePluginAvailableForCompany(companyId); - requireInCompany("Issue", await issues2.getById(params.issueId), companyId); - await documents2.deleteIssueDocument(params.issueId, params.key); - } - }, - agents: { - async list(params) { - const companyId = ensureCompanyId(params.companyId); - await ensurePluginAvailableForCompany(companyId); - const rows = await agents2.list(companyId); - return applyWindow( - rows.filter((agent) => !params.status || agent.status === params.status), - params - ); - }, - async get(params) { - const companyId = ensureCompanyId(params.companyId); - await ensurePluginAvailableForCompany(companyId); - const agent = await agents2.getById(params.agentId); - return inCompany(agent, companyId) ? agent : null; - }, - async pause(params) { - const companyId = ensureCompanyId(params.companyId); - await ensurePluginAvailableForCompany(companyId); - const agent = await agents2.getById(params.agentId); - requireInCompany("Agent", agent, companyId); - return await agents2.pause(params.agentId); - }, - async resume(params) { - const companyId = ensureCompanyId(params.companyId); - await ensurePluginAvailableForCompany(companyId); - const agent = await agents2.getById(params.agentId); - requireInCompany("Agent", agent, companyId); - return await agents2.resume(params.agentId); - }, - async invoke(params) { - const companyId = ensureCompanyId(params.companyId); - await ensurePluginAvailableForCompany(companyId); - const agent = await agents2.getById(params.agentId); - requireInCompany("Agent", agent, companyId); - const run = await heartbeat.wakeup(params.agentId, { - source: "automation", - triggerDetail: "system", - reason: params.reason ?? null, - payload: { prompt: params.prompt }, - requestedByActorType: "system", - requestedByActorId: pluginId - }); - if (!run) throw new Error("Agent wakeup was skipped by heartbeat policy"); - return { runId: run.id }; - } - }, - goals: { - async list(params) { - const companyId = ensureCompanyId(params.companyId); - await ensurePluginAvailableForCompany(companyId); - const rows = await goals2.list(companyId); - return applyWindow( - rows.filter( - (goal) => (!params.level || goal.level === params.level) && (!params.status || goal.status === params.status) - ), - params - ); - }, - async get(params) { - const companyId = ensureCompanyId(params.companyId); - await ensurePluginAvailableForCompany(companyId); - const goal = await goals2.getById(params.goalId); - return inCompany(goal, companyId) ? goal : null; - }, - async create(params) { - const companyId = ensureCompanyId(params.companyId); - await ensurePluginAvailableForCompany(companyId); - return await goals2.create(companyId, { - title: params.title, - description: params.description, - level: params.level, - status: params.status, - parentId: params.parentId, - ownerAgentId: params.ownerAgentId - }); - }, - async update(params) { - const companyId = ensureCompanyId(params.companyId); - await ensurePluginAvailableForCompany(companyId); - requireInCompany("Goal", await goals2.getById(params.goalId), companyId); - return await goals2.update(params.goalId, params.patch); - } - }, - agentSessions: { - async create(params) { - const companyId = ensureCompanyId(params.companyId); - await ensurePluginAvailableForCompany(companyId); - const agent = await agents2.getById(params.agentId); - requireInCompany("Agent", agent, companyId); - const taskKey = params.taskKey ?? `plugin:${pluginKey}:session:${randomUUID11()}`; - const row = await db.insert(agentTaskSessions).values({ - companyId, - agentId: params.agentId, - adapterType: agent.adapterType, - taskKey, - sessionParamsJson: null, - sessionDisplayId: null, - lastRunId: null, - lastError: null - }).returning().then((rows) => rows[0]); - return { - sessionId: row.id, - agentId: params.agentId, - companyId, - status: "active", - createdAt: row.createdAt.toISOString() - }; - }, - async list(params) { - const companyId = ensureCompanyId(params.companyId); - await ensurePluginAvailableForCompany(companyId); - const rows = await db.select().from(agentTaskSessions).where( - and( - eq(agentTaskSessions.agentId, params.agentId), - eq(agentTaskSessions.companyId, companyId), - like(agentTaskSessions.taskKey, `plugin:${pluginKey}:session:%`) - ) - ).orderBy(desc(agentTaskSessions.createdAt)); - return rows.map((row) => ({ - sessionId: row.id, - agentId: row.agentId, - companyId: row.companyId, - status: "active", - createdAt: row.createdAt.toISOString() - })); - }, - async sendMessage(params) { - if (disposed) { - throw new Error("Host services have been disposed"); - } - const companyId = ensureCompanyId(params.companyId); - await ensurePluginAvailableForCompany(companyId); - const session = await db.select().from(agentTaskSessions).where( - and( - eq(agentTaskSessions.id, params.sessionId), - eq(agentTaskSessions.companyId, companyId), - like(agentTaskSessions.taskKey, `plugin:${pluginKey}:session:%`) - ) - ).then((rows) => rows[0] ?? null); - if (!session) throw new Error(`Session not found: ${params.sessionId}`); - const run = await heartbeat.wakeup(session.agentId, { - source: "automation", - triggerDetail: "system", - reason: params.reason ?? null, - payload: { prompt: params.prompt }, - contextSnapshot: { - taskKey: session.taskKey, - wakeSource: "automation", - wakeTriggerDetail: "system" - }, - requestedByActorType: "system", - requestedByActorId: pluginId - }); - if (!run) throw new Error("Agent wakeup was skipped by heartbeat policy"); - if (notifyWorker) { - const TERMINAL_STATUSES = /* @__PURE__ */ new Set(["succeeded", "failed", "cancelled", "timed_out"]); - const cleanup = () => { - unsubscribe(); - clearTimeout(timeoutTimer); - activeSubscriptions.delete(entry); - }; - const unsubscribe = subscribeCompanyLiveEvents(companyId, (event) => { - const payload2 = event.payload; - if (!payload2 || payload2.runId !== run.id) return; - if (event.type === "heartbeat.run.log" || event.type === "heartbeat.run.event") { - notifyWorker("agents.sessions.event", { - sessionId: params.sessionId, - runId: run.id, - seq: payload2.seq ?? 0, - eventType: "chunk", - stream: payload2.stream ?? null, - message: payload2.chunk ?? payload2.message ?? null, - payload: payload2 - }); - } else if (event.type === "heartbeat.run.status") { - const status = payload2.status; - if (TERMINAL_STATUSES.has(status)) { - notifyWorker("agents.sessions.event", { - sessionId: params.sessionId, - runId: run.id, - seq: 0, - eventType: status === "succeeded" ? "done" : "error", - stream: "system", - message: status === "succeeded" ? "Run completed" : `Run ${status}`, - payload: payload2 - }); - cleanup(); - } else { - notifyWorker("agents.sessions.event", { - sessionId: params.sessionId, - runId: run.id, - seq: 0, - eventType: "status", - stream: "system", - message: `Run status: ${status}`, - payload: payload2 - }); - } - } - }); - const timeoutTimer = setTimeout(() => { - logger.warn( - { pluginId, pluginKey, runId: run.id }, - "session event subscription timed out \u2014 forcing cleanup" - ); - cleanup(); - }, SESSION_EVENT_SUBSCRIPTION_TIMEOUT_MS); - const entry = { unsubscribe, timer: timeoutTimer }; - activeSubscriptions.add(entry); - } - return { runId: run.id }; - }, - async close(params) { - const companyId = ensureCompanyId(params.companyId); - await ensurePluginAvailableForCompany(companyId); - const deleted = await db.delete(agentTaskSessions).where( - and( - eq(agentTaskSessions.id, params.sessionId), - eq(agentTaskSessions.companyId, companyId), - like(agentTaskSessions.taskKey, `plugin:${pluginKey}:session:%`) - ) - ).returning().then((rows) => rows.length); - if (deleted === 0) throw new Error(`Session not found: ${params.sessionId}`); - } - }, - /** - * Clean up all active session event subscriptions and flush any buffered - * log entries. Must be called when the plugin worker is stopped, crashed, - * or unloaded to prevent leaked listeners and lost log entries. - */ - dispose() { - disposed = true; - scopedBus.clear(); - const snapshot = Array.from(activeSubscriptions); - activeSubscriptions.clear(); - for (const entry of snapshot) { - clearTimeout(entry.timer); - entry.unsubscribe(); - } - flushPluginLogBuffer().catch((err) => { - console.error("[plugin-host-services] dispose() log flush failed:", err); - }); - } - }; -} - -// server/src/services/plugin-event-bus.ts -function matchesPattern(eventType, pattern) { - if (pattern === eventType) return true; - if (pattern.endsWith(".*")) { - const prefix = pattern.slice(0, -1); - return eventType.startsWith(prefix); - } - return false; -} -function passesFilter(event, filter) { - if (!filter) return true; - const payload2 = event.payload; - if (filter.projectId !== void 0) { - const projectId = event.entityType === "project" ? event.entityId : typeof payload2?.projectId === "string" ? payload2.projectId : void 0; - if (projectId !== filter.projectId) return false; - } - if (filter.companyId !== void 0) { - if (event.companyId !== filter.companyId) return false; - } - if (filter.agentId !== void 0) { - const agentId = event.entityType === "agent" ? event.entityId : typeof payload2?.agentId === "string" ? payload2.agentId : void 0; - if (agentId !== filter.agentId) return false; - } - return true; -} -function createPluginEventBus() { - const registry2 = /* @__PURE__ */ new Map(); - function subsFor(pluginId) { - let subs = registry2.get(pluginId); - if (!subs) { - subs = []; - registry2.set(pluginId, subs); - } - return subs; - } - async function emit(event) { - const errors = []; - const promises = []; - for (const [pluginId, subs] of registry2) { - for (const sub of subs) { - if (!matchesPattern(event.eventType, sub.eventPattern)) continue; - if (!passesFilter(event, sub.filter)) continue; - promises.push( - Promise.resolve().then(() => sub.handler(event)).catch((error50) => { - errors.push({ pluginId, error: error50 }); - }) - ); - } - } - await Promise.all(promises); - return { errors }; - } - function clearPlugin(pluginId) { - registry2.delete(pluginId); - } - function forPlugin(pluginId) { - return { - /** - * Subscribe to a core domain event or a plugin-namespaced event. - * - * For wildcard subscriptions use a trailing `.*` pattern, e.g. - * `"plugin.acme.linear.*"`. - * - * Requires the `events.subscribe` capability (capability enforcement is - * done by the host layer before calling this method). - */ - subscribe(eventPattern, fnOrFilter, maybeFn) { - let filter = null; - let handler; - if (typeof fnOrFilter === "function") { - handler = fnOrFilter; - } else { - filter = fnOrFilter; - if (!maybeFn) throw new Error("Handler function is required when a filter is provided"); - handler = maybeFn; - } - subsFor(pluginId).push({ eventPattern, filter, handler }); - }, - /** - * Emit a plugin-namespaced event. The event type is automatically - * prefixed with `plugin..` so: - * - `emit("sync-done", payload)` becomes `"plugin.acme.linear.sync-done"`. - * - * Requires the `events.emit` capability (enforced by the host layer). - * - * @throws {Error} if `name` already contains the `plugin.` prefix - * (prevents cross-namespace spoofing). - */ - async emit(name, companyId, payload2) { - if (!name || name.trim() === "") { - throw new Error(`Plugin "${pluginId}" must provide a non-empty event name.`); - } - if (!companyId || companyId.trim() === "") { - throw new Error(`Plugin "${pluginId}" must provide a companyId when emitting events.`); - } - if (name.startsWith("plugin.")) { - throw new Error( - `Plugin "${pluginId}" must not include the "plugin." prefix when emitting events. Emit the bare event name (e.g. "sync-done") and the bus will namespace it automatically.` - ); - } - const eventType = `plugin.${pluginId}.${name}`; - const event = { - eventId: crypto.randomUUID(), - eventType, - companyId, - occurredAt: (/* @__PURE__ */ new Date()).toISOString(), - actorType: "plugin", - actorId: pluginId, - payload: payload2 - }; - return emit(event); - }, - /** Remove all subscriptions registered by this plugin. */ - clear() { - clearPlugin(pluginId); - } - }; - } - return { - emit, - forPlugin, - clearPlugin, - /** Expose subscription count for a plugin (useful for tests and diagnostics). */ - subscriptionCount(pluginId) { - if (pluginId !== void 0) { - return registry2.get(pluginId)?.length ?? 0; - } - let total = 0; - for (const subs of registry2.values()) total += subs.length; - return total; - } - }; -} - -// node_modules/.pnpm/chokidar@4.0.3/node_modules/chokidar/esm/index.js -import { stat as statcb } from "fs"; -import { stat as stat4, readdir as readdir4 } from "fs/promises"; -import { EventEmitter as EventEmitter4 } from "events"; -import * as sysPath2 from "path"; - -// node_modules/.pnpm/readdirp@4.1.2/node_modules/readdirp/esm/index.js -import { stat as stat2, lstat, readdir as readdir3, realpath } from "node:fs/promises"; -import { Readable as Readable2 } from "node:stream"; -import { resolve as presolve, relative as prelative, join as pjoin, sep as psep } from "node:path"; -var EntryTypes = { - FILE_TYPE: "files", - DIR_TYPE: "directories", - FILE_DIR_TYPE: "files_directories", - EVERYTHING_TYPE: "all" -}; -var defaultOptions = { - root: ".", - fileFilter: (_entryInfo) => true, - directoryFilter: (_entryInfo) => true, - type: EntryTypes.FILE_TYPE, - lstat: false, - depth: 2147483648, - alwaysStat: false, - highWaterMark: 4096 -}; -Object.freeze(defaultOptions); -var RECURSIVE_ERROR_CODE = "READDIRP_RECURSIVE_ERROR"; -var NORMAL_FLOW_ERRORS = /* @__PURE__ */ new Set(["ENOENT", "EPERM", "EACCES", "ELOOP", RECURSIVE_ERROR_CODE]); -var ALL_TYPES = [ - EntryTypes.DIR_TYPE, - EntryTypes.EVERYTHING_TYPE, - EntryTypes.FILE_DIR_TYPE, - EntryTypes.FILE_TYPE -]; -var DIR_TYPES = /* @__PURE__ */ new Set([ - EntryTypes.DIR_TYPE, - EntryTypes.EVERYTHING_TYPE, - EntryTypes.FILE_DIR_TYPE -]); -var FILE_TYPES = /* @__PURE__ */ new Set([ - EntryTypes.EVERYTHING_TYPE, - EntryTypes.FILE_DIR_TYPE, - EntryTypes.FILE_TYPE -]); -var isNormalFlowError = (error50) => NORMAL_FLOW_ERRORS.has(error50.code); -var wantBigintFsStats = process.platform === "win32"; -var emptyFn = (_entryInfo) => true; -var normalizeFilter = (filter) => { - if (filter === void 0) - return emptyFn; - if (typeof filter === "function") - return filter; - if (typeof filter === "string") { - const fl = filter.trim(); - return (entry) => entry.basename === fl; - } - if (Array.isArray(filter)) { - const trItems = filter.map((item) => item.trim()); - return (entry) => trItems.some((f5) => entry.basename === f5); - } - return emptyFn; -}; -var ReaddirpStream = class extends Readable2 { - constructor(options = {}) { - super({ - objectMode: true, - autoDestroy: true, - highWaterMark: options.highWaterMark - }); - const opts = { ...defaultOptions, ...options }; - const { root, type } = opts; - this._fileFilter = normalizeFilter(opts.fileFilter); - this._directoryFilter = normalizeFilter(opts.directoryFilter); - const statMethod = opts.lstat ? lstat : stat2; - if (wantBigintFsStats) { - this._stat = (path53) => statMethod(path53, { bigint: true }); - } else { - this._stat = statMethod; - } - this._maxDepth = opts.depth ?? defaultOptions.depth; - this._wantsDir = type ? DIR_TYPES.has(type) : false; - this._wantsFile = type ? FILE_TYPES.has(type) : false; - this._wantsEverything = type === EntryTypes.EVERYTHING_TYPE; - this._root = presolve(root); - this._isDirent = !opts.alwaysStat; - this._statsProp = this._isDirent ? "dirent" : "stats"; - this._rdOptions = { encoding: "utf8", withFileTypes: this._isDirent }; - this.parents = [this._exploreDir(root, 1)]; - this.reading = false; - this.parent = void 0; - } - async _read(batch) { - if (this.reading) - return; - this.reading = true; - try { - while (!this.destroyed && batch > 0) { - const par = this.parent; - const fil = par && par.files; - if (fil && fil.length > 0) { - const { path: path53, depth } = par; - const slice = fil.splice(0, batch).map((dirent) => this._formatEntry(dirent, path53)); - const awaited = await Promise.all(slice); - for (const entry of awaited) { - if (!entry) - continue; - if (this.destroyed) - return; - const entryType = await this._getEntryType(entry); - if (entryType === "directory" && this._directoryFilter(entry)) { - if (depth <= this._maxDepth) { - this.parents.push(this._exploreDir(entry.fullPath, depth + 1)); - } - if (this._wantsDir) { - this.push(entry); - batch--; - } - } else if ((entryType === "file" || this._includeAsFile(entry)) && this._fileFilter(entry)) { - if (this._wantsFile) { - this.push(entry); - batch--; - } - } - } - } else { - const parent = this.parents.pop(); - if (!parent) { - this.push(null); - break; - } - this.parent = await parent; - if (this.destroyed) - return; - } - } - } catch (error50) { - this.destroy(error50); - } finally { - this.reading = false; - } - } - async _exploreDir(path53, depth) { - let files; - try { - files = await readdir3(path53, this._rdOptions); - } catch (error50) { - this._onError(error50); - } - return { files, depth, path: path53 }; - } - async _formatEntry(dirent, path53) { - let entry; - const basename3 = this._isDirent ? dirent.name : dirent; - try { - const fullPath = presolve(pjoin(path53, basename3)); - entry = { path: prelative(this._root, fullPath), fullPath, basename: basename3 }; - entry[this._statsProp] = this._isDirent ? dirent : await this._stat(fullPath); - } catch (err) { - this._onError(err); - return; - } - return entry; - } - _onError(err) { - if (isNormalFlowError(err) && !this.destroyed) { - this.emit("warn", err); - } else { - this.destroy(err); - } - } - async _getEntryType(entry) { - if (!entry && this._statsProp in entry) { - return ""; - } - const stats = entry[this._statsProp]; - if (stats.isFile()) - return "file"; - if (stats.isDirectory()) - return "directory"; - if (stats && stats.isSymbolicLink()) { - const full = entry.fullPath; - try { - const entryRealPath = await realpath(full); - const entryRealPathStats = await lstat(entryRealPath); - if (entryRealPathStats.isFile()) { - return "file"; - } - if (entryRealPathStats.isDirectory()) { - const len = entryRealPath.length; - if (full.startsWith(entryRealPath) && full.substr(len, 1) === psep) { - const recursiveError = new Error(`Circular symlink detected: "${full}" points to "${entryRealPath}"`); - recursiveError.code = RECURSIVE_ERROR_CODE; - return this._onError(recursiveError); - } - return "directory"; - } - } catch (error50) { - this._onError(error50); - return ""; - } - } - } - _includeAsFile(entry) { - const stats = entry && entry[this._statsProp]; - return stats && this._wantsEverything && !stats.isDirectory(); - } -}; -function readdirp(root, options = {}) { - let type = options.entryType || options.type; - if (type === "both") - type = EntryTypes.FILE_DIR_TYPE; - if (type) - options.type = type; - if (!root) { - throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)"); - } else if (typeof root !== "string") { - throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)"); - } else if (type && !ALL_TYPES.includes(type)) { - throw new Error(`readdirp: Invalid type passed. Use one of ${ALL_TYPES.join(", ")}`); - } - options.root = root; - return new ReaddirpStream(options); -} - -// node_modules/.pnpm/chokidar@4.0.3/node_modules/chokidar/esm/handler.js -import { watchFile, unwatchFile, watch as fs_watch } from "fs"; -import { open, stat as stat3, lstat as lstat2, realpath as fsrealpath } from "fs/promises"; -import * as sysPath from "path"; -import { type as osType } from "os"; -var STR_DATA = "data"; -var STR_END = "end"; -var STR_CLOSE = "close"; -var EMPTY_FN = () => { -}; -var pl = process.platform; -var isWindows = pl === "win32"; -var isMacos = pl === "darwin"; -var isLinux = pl === "linux"; -var isFreeBSD = pl === "freebsd"; -var isIBMi = osType() === "OS400"; -var EVENTS = { - ALL: "all", - READY: "ready", - ADD: "add", - CHANGE: "change", - ADD_DIR: "addDir", - UNLINK: "unlink", - UNLINK_DIR: "unlinkDir", - RAW: "raw", - ERROR: "error" -}; -var EV = EVENTS; -var THROTTLE_MODE_WATCH = "watch"; -var statMethods = { lstat: lstat2, stat: stat3 }; -var KEY_LISTENERS = "listeners"; -var KEY_ERR = "errHandlers"; -var KEY_RAW = "rawEmitters"; -var HANDLER_KEYS = [KEY_LISTENERS, KEY_ERR, KEY_RAW]; -var binaryExtensions = /* @__PURE__ */ new Set([ - "3dm", - "3ds", - "3g2", - "3gp", - "7z", - "a", - "aac", - "adp", - "afdesign", - "afphoto", - "afpub", - "ai", - "aif", - "aiff", - "alz", - "ape", - "apk", - "appimage", - "ar", - "arj", - "asf", - "au", - "avi", - "bak", - "baml", - "bh", - "bin", - "bk", - "bmp", - "btif", - "bz2", - "bzip2", - "cab", - "caf", - "cgm", - "class", - "cmx", - "cpio", - "cr2", - "cur", - "dat", - "dcm", - "deb", - "dex", - "djvu", - "dll", - "dmg", - "dng", - "doc", - "docm", - "docx", - "dot", - "dotm", - "dra", - "DS_Store", - "dsk", - "dts", - "dtshd", - "dvb", - "dwg", - "dxf", - "ecelp4800", - "ecelp7470", - "ecelp9600", - "egg", - "eol", - "eot", - "epub", - "exe", - "f4v", - "fbs", - "fh", - "fla", - "flac", - "flatpak", - "fli", - "flv", - "fpx", - "fst", - "fvt", - "g3", - "gh", - "gif", - "graffle", - "gz", - "gzip", - "h261", - "h263", - "h264", - "icns", - "ico", - "ief", - "img", - "ipa", - "iso", - "jar", - "jpeg", - "jpg", - "jpgv", - "jpm", - "jxr", - "key", - "ktx", - "lha", - "lib", - "lvp", - "lz", - "lzh", - "lzma", - "lzo", - "m3u", - "m4a", - "m4v", - "mar", - "mdi", - "mht", - "mid", - "midi", - "mj2", - "mka", - "mkv", - "mmr", - "mng", - "mobi", - "mov", - "movie", - "mp3", - "mp4", - "mp4a", - "mpeg", - "mpg", - "mpga", - "mxu", - "nef", - "npx", - "numbers", - "nupkg", - "o", - "odp", - "ods", - "odt", - "oga", - "ogg", - "ogv", - "otf", - "ott", - "pages", - "pbm", - "pcx", - "pdb", - "pdf", - "pea", - "pgm", - "pic", - "png", - "pnm", - "pot", - "potm", - "potx", - "ppa", - "ppam", - "ppm", - "pps", - "ppsm", - "ppsx", - "ppt", - "pptm", - "pptx", - "psd", - "pya", - "pyc", - "pyo", - "pyv", - "qt", - "rar", - "ras", - "raw", - "resources", - "rgb", - "rip", - "rlc", - "rmf", - "rmvb", - "rpm", - "rtf", - "rz", - "s3m", - "s7z", - "scpt", - "sgi", - "shar", - "snap", - "sil", - "sketch", - "slk", - "smv", - "snk", - "so", - "stl", - "suo", - "sub", - "swf", - "tar", - "tbz", - "tbz2", - "tga", - "tgz", - "thmx", - "tif", - "tiff", - "tlz", - "ttc", - "ttf", - "txz", - "udf", - "uvh", - "uvi", - "uvm", - "uvp", - "uvs", - "uvu", - "viv", - "vob", - "war", - "wav", - "wax", - "wbmp", - "wdp", - "weba", - "webm", - "webp", - "whl", - "wim", - "wm", - "wma", - "wmv", - "wmx", - "woff", - "woff2", - "wrm", - "wvx", - "xbm", - "xif", - "xla", - "xlam", - "xls", - "xlsb", - "xlsm", - "xlsx", - "xlt", - "xltm", - "xltx", - "xm", - "xmind", - "xpi", - "xpm", - "xwd", - "xz", - "z", - "zip", - "zipx" -]); -var isBinaryPath = (filePath) => binaryExtensions.has(sysPath.extname(filePath).slice(1).toLowerCase()); -var foreach = (val, fn) => { - if (val instanceof Set) { - val.forEach(fn); - } else { - fn(val); - } -}; -var addAndConvert = (main, prop, item) => { - let container = main[prop]; - if (!(container instanceof Set)) { - main[prop] = container = /* @__PURE__ */ new Set([container]); - } - container.add(item); -}; -var clearItem = (cont) => (key) => { - const set2 = cont[key]; - if (set2 instanceof Set) { - set2.clear(); - } else { - delete cont[key]; - } -}; -var delFromSet = (main, prop, item) => { - const container = main[prop]; - if (container instanceof Set) { - container.delete(item); - } else if (container === item) { - delete main[prop]; - } -}; -var isEmptySet = (val) => val instanceof Set ? val.size === 0 : !val; -var FsWatchInstances = /* @__PURE__ */ new Map(); -function createFsWatchInstance(path53, options, listener, errHandler, emitRaw) { - const handleEvent = (rawEvent, evPath) => { - listener(path53); - emitRaw(rawEvent, evPath, { watchedPath: path53 }); - if (evPath && path53 !== evPath) { - fsWatchBroadcast(sysPath.resolve(path53, evPath), KEY_LISTENERS, sysPath.join(path53, evPath)); - } - }; - try { - return fs_watch(path53, { - persistent: options.persistent - }, handleEvent); - } catch (error50) { - errHandler(error50); - return void 0; - } -} -var fsWatchBroadcast = (fullPath, listenerType, val1, val2, val3) => { - const cont = FsWatchInstances.get(fullPath); - if (!cont) - return; - foreach(cont[listenerType], (listener) => { - listener(val1, val2, val3); - }); -}; -var setFsWatchListener = (path53, fullPath, options, handlers) => { - const { listener, errHandler, rawEmitter } = handlers; - let cont = FsWatchInstances.get(fullPath); - let watcher; - if (!options.persistent) { - watcher = createFsWatchInstance(path53, options, listener, errHandler, rawEmitter); - if (!watcher) - return; - return watcher.close.bind(watcher); - } - if (cont) { - addAndConvert(cont, KEY_LISTENERS, listener); - addAndConvert(cont, KEY_ERR, errHandler); - addAndConvert(cont, KEY_RAW, rawEmitter); - } else { - watcher = createFsWatchInstance( - path53, - options, - fsWatchBroadcast.bind(null, fullPath, KEY_LISTENERS), - errHandler, - // no need to use broadcast here - fsWatchBroadcast.bind(null, fullPath, KEY_RAW) - ); - if (!watcher) - return; - watcher.on(EV.ERROR, async (error50) => { - const broadcastErr = fsWatchBroadcast.bind(null, fullPath, KEY_ERR); - if (cont) - cont.watcherUnusable = true; - if (isWindows && error50.code === "EPERM") { - try { - const fd = await open(path53, "r"); - await fd.close(); - broadcastErr(error50); - } catch (err) { - } - } else { - broadcastErr(error50); - } - }); - cont = { - listeners: listener, - errHandlers: errHandler, - rawEmitters: rawEmitter, - watcher - }; - FsWatchInstances.set(fullPath, cont); - } - return () => { - delFromSet(cont, KEY_LISTENERS, listener); - delFromSet(cont, KEY_ERR, errHandler); - delFromSet(cont, KEY_RAW, rawEmitter); - if (isEmptySet(cont.listeners)) { - cont.watcher.close(); - FsWatchInstances.delete(fullPath); - HANDLER_KEYS.forEach(clearItem(cont)); - cont.watcher = void 0; - Object.freeze(cont); - } - }; -}; -var FsWatchFileInstances = /* @__PURE__ */ new Map(); -var setFsWatchFileListener = (path53, fullPath, options, handlers) => { - const { listener, rawEmitter } = handlers; - let cont = FsWatchFileInstances.get(fullPath); - const copts = cont && cont.options; - if (copts && (copts.persistent < options.persistent || copts.interval > options.interval)) { - unwatchFile(fullPath); - cont = void 0; - } - if (cont) { - addAndConvert(cont, KEY_LISTENERS, listener); - addAndConvert(cont, KEY_RAW, rawEmitter); - } else { - cont = { - listeners: listener, - rawEmitters: rawEmitter, - options, - watcher: watchFile(fullPath, options, (curr, prev) => { - foreach(cont.rawEmitters, (rawEmitter2) => { - rawEmitter2(EV.CHANGE, fullPath, { curr, prev }); - }); - const currmtime = curr.mtimeMs; - if (curr.size !== prev.size || currmtime > prev.mtimeMs || currmtime === 0) { - foreach(cont.listeners, (listener2) => listener2(path53, curr)); - } - }) - }; - FsWatchFileInstances.set(fullPath, cont); - } - return () => { - delFromSet(cont, KEY_LISTENERS, listener); - delFromSet(cont, KEY_RAW, rawEmitter); - if (isEmptySet(cont.listeners)) { - FsWatchFileInstances.delete(fullPath); - unwatchFile(fullPath); - cont.options = cont.watcher = void 0; - Object.freeze(cont); - } - }; -}; -var NodeFsHandler = class { - constructor(fsW) { - this.fsw = fsW; - this._boundHandleError = (error50) => fsW._handleError(error50); - } - /** - * Watch file for changes with fs_watchFile or fs_watch. - * @param path to file or dir - * @param listener on fs change - * @returns closer for the watcher instance - */ - _watchWithNodeFs(path53, listener) { - const opts = this.fsw.options; - const directory = sysPath.dirname(path53); - const basename3 = sysPath.basename(path53); - const parent = this.fsw._getWatchedDir(directory); - parent.add(basename3); - const absolutePath = sysPath.resolve(path53); - const options = { - persistent: opts.persistent - }; - if (!listener) - listener = EMPTY_FN; - let closer; - if (opts.usePolling) { - const enableBin = opts.interval !== opts.binaryInterval; - options.interval = enableBin && isBinaryPath(basename3) ? opts.binaryInterval : opts.interval; - closer = setFsWatchFileListener(path53, absolutePath, options, { - listener, - rawEmitter: this.fsw._emitRaw - }); - } else { - closer = setFsWatchListener(path53, absolutePath, options, { - listener, - errHandler: this._boundHandleError, - rawEmitter: this.fsw._emitRaw - }); - } - return closer; - } - /** - * Watch a file and emit add event if warranted. - * @returns closer for the watcher instance - */ - _handleFile(file2, stats, initialAdd) { - if (this.fsw.closed) { - return; - } - const dirname3 = sysPath.dirname(file2); - const basename3 = sysPath.basename(file2); - const parent = this.fsw._getWatchedDir(dirname3); - let prevStats = stats; - if (parent.has(basename3)) - return; - const listener = async (path53, newStats) => { - if (!this.fsw._throttle(THROTTLE_MODE_WATCH, file2, 5)) - return; - if (!newStats || newStats.mtimeMs === 0) { - try { - const newStats2 = await stat3(file2); - if (this.fsw.closed) - return; - const at = newStats2.atimeMs; - const mt = newStats2.mtimeMs; - if (!at || at <= mt || mt !== prevStats.mtimeMs) { - this.fsw._emit(EV.CHANGE, file2, newStats2); - } - if ((isMacos || isLinux || isFreeBSD) && prevStats.ino !== newStats2.ino) { - this.fsw._closeFile(path53); - prevStats = newStats2; - const closer2 = this._watchWithNodeFs(file2, listener); - if (closer2) - this.fsw._addPathCloser(path53, closer2); - } else { - prevStats = newStats2; - } - } catch (error50) { - this.fsw._remove(dirname3, basename3); - } - } else if (parent.has(basename3)) { - const at = newStats.atimeMs; - const mt = newStats.mtimeMs; - if (!at || at <= mt || mt !== prevStats.mtimeMs) { - this.fsw._emit(EV.CHANGE, file2, newStats); - } - prevStats = newStats; - } - }; - const closer = this._watchWithNodeFs(file2, listener); - if (!(initialAdd && this.fsw.options.ignoreInitial) && this.fsw._isntIgnored(file2)) { - if (!this.fsw._throttle(EV.ADD, file2, 0)) - return; - this.fsw._emit(EV.ADD, file2, stats); - } - return closer; - } - /** - * Handle symlinks encountered while reading a dir. - * @param entry returned by readdirp - * @param directory path of dir being read - * @param path of this item - * @param item basename of this item - * @returns true if no more processing is needed for this entry. - */ - async _handleSymlink(entry, directory, path53, item) { - if (this.fsw.closed) { - return; - } - const full = entry.fullPath; - const dir = this.fsw._getWatchedDir(directory); - if (!this.fsw.options.followSymlinks) { - this.fsw._incrReadyCount(); - let linkPath; - try { - linkPath = await fsrealpath(path53); - } catch (e5) { - this.fsw._emitReady(); - return true; - } - if (this.fsw.closed) - return; - if (dir.has(item)) { - if (this.fsw._symlinkPaths.get(full) !== linkPath) { - this.fsw._symlinkPaths.set(full, linkPath); - this.fsw._emit(EV.CHANGE, path53, entry.stats); - } - } else { - dir.add(item); - this.fsw._symlinkPaths.set(full, linkPath); - this.fsw._emit(EV.ADD, path53, entry.stats); - } - this.fsw._emitReady(); - return true; - } - if (this.fsw._symlinkPaths.has(full)) { - return true; - } - this.fsw._symlinkPaths.set(full, true); - } - _handleRead(directory, initialAdd, wh, target, dir, depth, throttler) { - directory = sysPath.join(directory, ""); - throttler = this.fsw._throttle("readdir", directory, 1e3); - if (!throttler) - return; - const previous = this.fsw._getWatchedDir(wh.path); - const current = /* @__PURE__ */ new Set(); - let stream = this.fsw._readdirp(directory, { - fileFilter: (entry) => wh.filterPath(entry), - directoryFilter: (entry) => wh.filterDir(entry) - }); - if (!stream) - return; - stream.on(STR_DATA, async (entry) => { - if (this.fsw.closed) { - stream = void 0; - return; - } - const item = entry.path; - let path53 = sysPath.join(directory, item); - current.add(item); - if (entry.stats.isSymbolicLink() && await this._handleSymlink(entry, directory, path53, item)) { - return; - } - if (this.fsw.closed) { - stream = void 0; - return; - } - if (item === target || !target && !previous.has(item)) { - this.fsw._incrReadyCount(); - path53 = sysPath.join(dir, sysPath.relative(dir, path53)); - this._addToNodeFs(path53, initialAdd, wh, depth + 1); - } - }).on(EV.ERROR, this._boundHandleError); - return new Promise((resolve4, reject) => { - if (!stream) - return reject(); - stream.once(STR_END, () => { - if (this.fsw.closed) { - stream = void 0; - return; - } - const wasThrottled = throttler ? throttler.clear() : false; - resolve4(void 0); - previous.getChildren().filter((item) => { - return item !== directory && !current.has(item); - }).forEach((item) => { - this.fsw._remove(directory, item); - }); - stream = void 0; - if (wasThrottled) - this._handleRead(directory, false, wh, target, dir, depth, throttler); - }); - }); - } - /** - * Read directory to add / remove files from `@watched` list and re-read it on change. - * @param dir fs path - * @param stats - * @param initialAdd - * @param depth relative to user-supplied path - * @param target child path targeted for watch - * @param wh Common watch helpers for this path - * @param realpath - * @returns closer for the watcher instance. - */ - async _handleDir(dir, stats, initialAdd, depth, target, wh, realpath2) { - const parentDir = this.fsw._getWatchedDir(sysPath.dirname(dir)); - const tracked = parentDir.has(sysPath.basename(dir)); - if (!(initialAdd && this.fsw.options.ignoreInitial) && !target && !tracked) { - this.fsw._emit(EV.ADD_DIR, dir, stats); - } - parentDir.add(sysPath.basename(dir)); - this.fsw._getWatchedDir(dir); - let throttler; - let closer; - const oDepth = this.fsw.options.depth; - if ((oDepth == null || depth <= oDepth) && !this.fsw._symlinkPaths.has(realpath2)) { - if (!target) { - await this._handleRead(dir, initialAdd, wh, target, dir, depth, throttler); - if (this.fsw.closed) - return; - } - closer = this._watchWithNodeFs(dir, (dirPath, stats2) => { - if (stats2 && stats2.mtimeMs === 0) - return; - this._handleRead(dirPath, false, wh, target, dir, depth, throttler); - }); - } - return closer; - } - /** - * Handle added file, directory, or glob pattern. - * Delegates call to _handleFile / _handleDir after checks. - * @param path to file or ir - * @param initialAdd was the file added at watch instantiation? - * @param priorWh depth relative to user-supplied path - * @param depth Child path actually targeted for watch - * @param target Child path actually targeted for watch - */ - async _addToNodeFs(path53, initialAdd, priorWh, depth, target) { - const ready = this.fsw._emitReady; - if (this.fsw._isIgnored(path53) || this.fsw.closed) { - ready(); - return false; - } - const wh = this.fsw._getWatchHelpers(path53); - if (priorWh) { - wh.filterPath = (entry) => priorWh.filterPath(entry); - wh.filterDir = (entry) => priorWh.filterDir(entry); - } - try { - const stats = await statMethods[wh.statMethod](wh.watchPath); - if (this.fsw.closed) - return; - if (this.fsw._isIgnored(wh.watchPath, stats)) { - ready(); - return false; - } - const follow = this.fsw.options.followSymlinks; - let closer; - if (stats.isDirectory()) { - const absPath = sysPath.resolve(path53); - const targetPath = follow ? await fsrealpath(path53) : path53; - if (this.fsw.closed) - return; - closer = await this._handleDir(wh.watchPath, stats, initialAdd, depth, target, wh, targetPath); - if (this.fsw.closed) - return; - if (absPath !== targetPath && targetPath !== void 0) { - this.fsw._symlinkPaths.set(absPath, targetPath); - } - } else if (stats.isSymbolicLink()) { - const targetPath = follow ? await fsrealpath(path53) : path53; - if (this.fsw.closed) - return; - const parent = sysPath.dirname(wh.watchPath); - this.fsw._getWatchedDir(parent).add(wh.watchPath); - this.fsw._emit(EV.ADD, wh.watchPath, stats); - closer = await this._handleDir(parent, stats, initialAdd, depth, path53, wh, targetPath); - if (this.fsw.closed) - return; - if (targetPath !== void 0) { - this.fsw._symlinkPaths.set(sysPath.resolve(path53), targetPath); - } - } else { - closer = this._handleFile(wh.watchPath, stats, initialAdd); - } - ready(); - if (closer) - this.fsw._addPathCloser(path53, closer); - return false; - } catch (error50) { - if (this.fsw._handleError(error50)) { - ready(); - return path53; - } - } - } -}; - -// node_modules/.pnpm/chokidar@4.0.3/node_modules/chokidar/esm/index.js -var SLASH = "/"; -var SLASH_SLASH = "//"; -var ONE_DOT = "."; -var TWO_DOTS = ".."; -var STRING_TYPE = "string"; -var BACK_SLASH_RE = /\\/g; -var DOUBLE_SLASH_RE = /\/\//; -var DOT_RE = /\..*\.(sw[px])$|~$|\.subl.*\.tmp/; -var REPLACER_RE = /^\.[/\\]/; -function arrify(item) { - return Array.isArray(item) ? item : [item]; -} -var isMatcherObject = (matcher) => typeof matcher === "object" && matcher !== null && !(matcher instanceof RegExp); -function createPattern(matcher) { - if (typeof matcher === "function") - return matcher; - if (typeof matcher === "string") - return (string4) => matcher === string4; - if (matcher instanceof RegExp) - return (string4) => matcher.test(string4); - if (typeof matcher === "object" && matcher !== null) { - return (string4) => { - if (matcher.path === string4) - return true; - if (matcher.recursive) { - const relative3 = sysPath2.relative(matcher.path, string4); - if (!relative3) { - return false; - } - return !relative3.startsWith("..") && !sysPath2.isAbsolute(relative3); - } - return false; - }; - } - return () => false; -} -function normalizePath2(path53) { - if (typeof path53 !== "string") - throw new Error("string expected"); - path53 = sysPath2.normalize(path53); - path53 = path53.replace(/\\/g, "/"); - let prepend = false; - if (path53.startsWith("//")) - prepend = true; - const DOUBLE_SLASH_RE2 = /\/\//; - while (path53.match(DOUBLE_SLASH_RE2)) - path53 = path53.replace(DOUBLE_SLASH_RE2, "/"); - if (prepend) - path53 = "/" + path53; - return path53; -} -function matchPatterns(patterns, testString, stats) { - const path53 = normalizePath2(testString); - for (let index2 = 0; index2 < patterns.length; index2++) { - const pattern = patterns[index2]; - if (pattern(path53, stats)) { - return true; - } - } - return false; -} -function anymatch(matchers, testString) { - if (matchers == null) { - throw new TypeError("anymatch: specify first argument"); - } - const matchersArray = arrify(matchers); - const patterns = matchersArray.map((matcher) => createPattern(matcher)); - if (testString == null) { - return (testString2, stats) => { - return matchPatterns(patterns, testString2, stats); - }; - } - return matchPatterns(patterns, testString); -} -var unifyPaths = (paths_) => { - const paths2 = arrify(paths_).flat(); - if (!paths2.every((p5) => typeof p5 === STRING_TYPE)) { - throw new TypeError(`Non-string provided as watch path: ${paths2}`); - } - return paths2.map(normalizePathToUnix); -}; -var toUnix = (string4) => { - let str = string4.replace(BACK_SLASH_RE, SLASH); - let prepend = false; - if (str.startsWith(SLASH_SLASH)) { - prepend = true; - } - while (str.match(DOUBLE_SLASH_RE)) { - str = str.replace(DOUBLE_SLASH_RE, SLASH); - } - if (prepend) { - str = SLASH + str; - } - return str; -}; -var normalizePathToUnix = (path53) => toUnix(sysPath2.normalize(toUnix(path53))); -var normalizeIgnored = (cwd = "") => (path53) => { - if (typeof path53 === "string") { - return normalizePathToUnix(sysPath2.isAbsolute(path53) ? path53 : sysPath2.join(cwd, path53)); - } else { - return path53; - } -}; -var getAbsolutePath = (path53, cwd) => { - if (sysPath2.isAbsolute(path53)) { - return path53; - } - return sysPath2.join(cwd, path53); -}; -var EMPTY_SET = Object.freeze(/* @__PURE__ */ new Set()); -var DirEntry = class { - constructor(dir, removeWatcher) { - this.path = dir; - this._removeWatcher = removeWatcher; - this.items = /* @__PURE__ */ new Set(); - } - add(item) { - const { items } = this; - if (!items) - return; - if (item !== ONE_DOT && item !== TWO_DOTS) - items.add(item); - } - async remove(item) { - const { items } = this; - if (!items) - return; - items.delete(item); - if (items.size > 0) - return; - const dir = this.path; - try { - await readdir4(dir); - } catch (err) { - if (this._removeWatcher) { - this._removeWatcher(sysPath2.dirname(dir), sysPath2.basename(dir)); - } - } - } - has(item) { - const { items } = this; - if (!items) - return; - return items.has(item); - } - getChildren() { - const { items } = this; - if (!items) - return []; - return [...items.values()]; - } - dispose() { - this.items.clear(); - this.path = ""; - this._removeWatcher = EMPTY_FN; - this.items = EMPTY_SET; - Object.freeze(this); - } -}; -var STAT_METHOD_F = "stat"; -var STAT_METHOD_L = "lstat"; -var WatchHelper = class { - constructor(path53, follow, fsw) { - this.fsw = fsw; - const watchPath = path53; - this.path = path53 = path53.replace(REPLACER_RE, ""); - this.watchPath = watchPath; - this.fullWatchPath = sysPath2.resolve(watchPath); - this.dirParts = []; - this.dirParts.forEach((parts) => { - if (parts.length > 1) - parts.pop(); - }); - this.followSymlinks = follow; - this.statMethod = follow ? STAT_METHOD_F : STAT_METHOD_L; - } - entryPath(entry) { - return sysPath2.join(this.watchPath, sysPath2.relative(this.watchPath, entry.fullPath)); - } - filterPath(entry) { - const { stats } = entry; - if (stats && stats.isSymbolicLink()) - return this.filterDir(entry); - const resolvedPath2 = this.entryPath(entry); - return this.fsw._isntIgnored(resolvedPath2, stats) && this.fsw._hasReadPermissions(stats); - } - filterDir(entry) { - return this.fsw._isntIgnored(this.entryPath(entry), entry.stats); - } -}; -var FSWatcher = class extends EventEmitter4 { - // Not indenting methods for history sake; for now. - constructor(_opts = {}) { - super(); - this.closed = false; - this._closers = /* @__PURE__ */ new Map(); - this._ignoredPaths = /* @__PURE__ */ new Set(); - this._throttled = /* @__PURE__ */ new Map(); - this._streams = /* @__PURE__ */ new Set(); - this._symlinkPaths = /* @__PURE__ */ new Map(); - this._watched = /* @__PURE__ */ new Map(); - this._pendingWrites = /* @__PURE__ */ new Map(); - this._pendingUnlinks = /* @__PURE__ */ new Map(); - this._readyCount = 0; - this._readyEmitted = false; - const awf = _opts.awaitWriteFinish; - const DEF_AWF = { stabilityThreshold: 2e3, pollInterval: 100 }; - const opts = { - // Defaults - persistent: true, - ignoreInitial: false, - ignorePermissionErrors: false, - interval: 100, - binaryInterval: 300, - followSymlinks: true, - usePolling: false, - // useAsync: false, - atomic: true, - // NOTE: overwritten later (depends on usePolling) - ..._opts, - // Change format - ignored: _opts.ignored ? arrify(_opts.ignored) : arrify([]), - awaitWriteFinish: awf === true ? DEF_AWF : typeof awf === "object" ? { ...DEF_AWF, ...awf } : false - }; - if (isIBMi) - opts.usePolling = true; - if (opts.atomic === void 0) - opts.atomic = !opts.usePolling; - const envPoll = process.env.CHOKIDAR_USEPOLLING; - if (envPoll !== void 0) { - const envLower = envPoll.toLowerCase(); - if (envLower === "false" || envLower === "0") - opts.usePolling = false; - else if (envLower === "true" || envLower === "1") - opts.usePolling = true; - else - opts.usePolling = !!envLower; - } - const envInterval = process.env.CHOKIDAR_INTERVAL; - if (envInterval) - opts.interval = Number.parseInt(envInterval, 10); - let readyCalls = 0; - this._emitReady = () => { - readyCalls++; - if (readyCalls >= this._readyCount) { - this._emitReady = EMPTY_FN; - this._readyEmitted = true; - process.nextTick(() => this.emit(EVENTS.READY)); - } - }; - this._emitRaw = (...args) => this.emit(EVENTS.RAW, ...args); - this._boundRemove = this._remove.bind(this); - this.options = opts; - this._nodeFsHandler = new NodeFsHandler(this); - Object.freeze(opts); - } - _addIgnoredPath(matcher) { - if (isMatcherObject(matcher)) { - for (const ignored of this._ignoredPaths) { - if (isMatcherObject(ignored) && ignored.path === matcher.path && ignored.recursive === matcher.recursive) { - return; - } - } - } - this._ignoredPaths.add(matcher); - } - _removeIgnoredPath(matcher) { - this._ignoredPaths.delete(matcher); - if (typeof matcher === "string") { - for (const ignored of this._ignoredPaths) { - if (isMatcherObject(ignored) && ignored.path === matcher) { - this._ignoredPaths.delete(ignored); - } - } - } - } - // Public methods - /** - * Adds paths to be watched on an existing FSWatcher instance. - * @param paths_ file or file list. Other arguments are unused - */ - add(paths_, _origAdd, _internal) { - const { cwd } = this.options; - this.closed = false; - this._closePromise = void 0; - let paths2 = unifyPaths(paths_); - if (cwd) { - paths2 = paths2.map((path53) => { - const absPath = getAbsolutePath(path53, cwd); - return absPath; - }); - } - paths2.forEach((path53) => { - this._removeIgnoredPath(path53); - }); - this._userIgnored = void 0; - if (!this._readyCount) - this._readyCount = 0; - this._readyCount += paths2.length; - Promise.all(paths2.map(async (path53) => { - const res = await this._nodeFsHandler._addToNodeFs(path53, !_internal, void 0, 0, _origAdd); - if (res) - this._emitReady(); - return res; - })).then((results) => { - if (this.closed) - return; - results.forEach((item) => { - if (item) - this.add(sysPath2.dirname(item), sysPath2.basename(_origAdd || item)); - }); - }); - return this; - } - /** - * Close watchers or start ignoring events from specified paths. - */ - unwatch(paths_) { - if (this.closed) - return this; - const paths2 = unifyPaths(paths_); - const { cwd } = this.options; - paths2.forEach((path53) => { - if (!sysPath2.isAbsolute(path53) && !this._closers.has(path53)) { - if (cwd) - path53 = sysPath2.join(cwd, path53); - path53 = sysPath2.resolve(path53); - } - this._closePath(path53); - this._addIgnoredPath(path53); - if (this._watched.has(path53)) { - this._addIgnoredPath({ - path: path53, - recursive: true - }); - } - this._userIgnored = void 0; - }); - return this; - } - /** - * Close watchers and remove all listeners from watched paths. - */ - close() { - if (this._closePromise) { - return this._closePromise; - } - this.closed = true; - this.removeAllListeners(); - const closers = []; - this._closers.forEach((closerList) => closerList.forEach((closer) => { - const promise2 = closer(); - if (promise2 instanceof Promise) - closers.push(promise2); - })); - this._streams.forEach((stream) => stream.destroy()); - this._userIgnored = void 0; - this._readyCount = 0; - this._readyEmitted = false; - this._watched.forEach((dirent) => dirent.dispose()); - this._closers.clear(); - this._watched.clear(); - this._streams.clear(); - this._symlinkPaths.clear(); - this._throttled.clear(); - this._closePromise = closers.length ? Promise.all(closers).then(() => void 0) : Promise.resolve(); - return this._closePromise; - } - /** - * Expose list of watched paths - * @returns for chaining - */ - getWatched() { - const watchList = {}; - this._watched.forEach((entry, dir) => { - const key = this.options.cwd ? sysPath2.relative(this.options.cwd, dir) : dir; - const index2 = key || ONE_DOT; - watchList[index2] = entry.getChildren().sort(); - }); - return watchList; - } - emitWithAll(event, args) { - this.emit(event, ...args); - if (event !== EVENTS.ERROR) - this.emit(EVENTS.ALL, event, ...args); - } - // Common helpers - // -------------- - /** - * Normalize and emit events. - * Calling _emit DOES NOT MEAN emit() would be called! - * @param event Type of event - * @param path File or directory path - * @param stats arguments to be passed with event - * @returns the error if defined, otherwise the value of the FSWatcher instance's `closed` flag - */ - async _emit(event, path53, stats) { - if (this.closed) - return; - const opts = this.options; - if (isWindows) - path53 = sysPath2.normalize(path53); - if (opts.cwd) - path53 = sysPath2.relative(opts.cwd, path53); - const args = [path53]; - if (stats != null) - args.push(stats); - const awf = opts.awaitWriteFinish; - let pw; - if (awf && (pw = this._pendingWrites.get(path53))) { - pw.lastChange = /* @__PURE__ */ new Date(); - return this; - } - if (opts.atomic) { - if (event === EVENTS.UNLINK) { - this._pendingUnlinks.set(path53, [event, ...args]); - setTimeout(() => { - this._pendingUnlinks.forEach((entry, path54) => { - this.emit(...entry); - this.emit(EVENTS.ALL, ...entry); - this._pendingUnlinks.delete(path54); - }); - }, typeof opts.atomic === "number" ? opts.atomic : 100); - return this; - } - if (event === EVENTS.ADD && this._pendingUnlinks.has(path53)) { - event = EVENTS.CHANGE; - this._pendingUnlinks.delete(path53); - } - } - if (awf && (event === EVENTS.ADD || event === EVENTS.CHANGE) && this._readyEmitted) { - const awfEmit = (err, stats2) => { - if (err) { - event = EVENTS.ERROR; - args[0] = err; - this.emitWithAll(event, args); - } else if (stats2) { - if (args.length > 1) { - args[1] = stats2; - } else { - args.push(stats2); - } - this.emitWithAll(event, args); - } - }; - this._awaitWriteFinish(path53, awf.stabilityThreshold, event, awfEmit); - return this; - } - if (event === EVENTS.CHANGE) { - const isThrottled = !this._throttle(EVENTS.CHANGE, path53, 50); - if (isThrottled) - return this; - } - if (opts.alwaysStat && stats === void 0 && (event === EVENTS.ADD || event === EVENTS.ADD_DIR || event === EVENTS.CHANGE)) { - const fullPath = opts.cwd ? sysPath2.join(opts.cwd, path53) : path53; - let stats2; - try { - stats2 = await stat4(fullPath); - } catch (err) { - } - if (!stats2 || this.closed) - return; - args.push(stats2); - } - this.emitWithAll(event, args); - return this; - } - /** - * Common handler for errors - * @returns The error if defined, otherwise the value of the FSWatcher instance's `closed` flag - */ - _handleError(error50) { - const code = error50 && error50.code; - if (error50 && code !== "ENOENT" && code !== "ENOTDIR" && (!this.options.ignorePermissionErrors || code !== "EPERM" && code !== "EACCES")) { - this.emit(EVENTS.ERROR, error50); - } - return error50 || this.closed; - } - /** - * Helper utility for throttling - * @param actionType type being throttled - * @param path being acted upon - * @param timeout duration of time to suppress duplicate actions - * @returns tracking object or false if action should be suppressed - */ - _throttle(actionType, path53, timeout) { - if (!this._throttled.has(actionType)) { - this._throttled.set(actionType, /* @__PURE__ */ new Map()); - } - const action = this._throttled.get(actionType); - if (!action) - throw new Error("invalid throttle"); - const actionPath = action.get(path53); - if (actionPath) { - actionPath.count++; - return false; - } - let timeoutObject; - const clear = () => { - const item = action.get(path53); - const count2 = item ? item.count : 0; - action.delete(path53); - clearTimeout(timeoutObject); - if (item) - clearTimeout(item.timeoutObject); - return count2; - }; - timeoutObject = setTimeout(clear, timeout); - const thr = { timeoutObject, clear, count: 0 }; - action.set(path53, thr); - return thr; - } - _incrReadyCount() { - return this._readyCount++; - } - /** - * Awaits write operation to finish. - * Polls a newly created file for size variations. When files size does not change for 'threshold' milliseconds calls callback. - * @param path being acted upon - * @param threshold Time in milliseconds a file size must be fixed before acknowledging write OP is finished - * @param event - * @param awfEmit Callback to be called when ready for event to be emitted. - */ - _awaitWriteFinish(path53, threshold, event, awfEmit) { - const awf = this.options.awaitWriteFinish; - if (typeof awf !== "object") - return; - const pollInterval = awf.pollInterval; - let timeoutHandler; - let fullPath = path53; - if (this.options.cwd && !sysPath2.isAbsolute(path53)) { - fullPath = sysPath2.join(this.options.cwd, path53); - } - const now2 = /* @__PURE__ */ new Date(); - const writes = this._pendingWrites; - function awaitWriteFinishFn(prevStat) { - statcb(fullPath, (err, curStat) => { - if (err || !writes.has(path53)) { - if (err && err.code !== "ENOENT") - awfEmit(err); - return; - } - const now3 = Number(/* @__PURE__ */ new Date()); - if (prevStat && curStat.size !== prevStat.size) { - writes.get(path53).lastChange = now3; - } - const pw = writes.get(path53); - const df = now3 - pw.lastChange; - if (df >= threshold) { - writes.delete(path53); - awfEmit(void 0, curStat); - } else { - timeoutHandler = setTimeout(awaitWriteFinishFn, pollInterval, curStat); - } - }); - } - if (!writes.has(path53)) { - writes.set(path53, { - lastChange: now2, - cancelWait: () => { - writes.delete(path53); - clearTimeout(timeoutHandler); - return event; - } - }); - timeoutHandler = setTimeout(awaitWriteFinishFn, pollInterval); - } - } - /** - * Determines whether user has asked to ignore this path. - */ - _isIgnored(path53, stats) { - if (this.options.atomic && DOT_RE.test(path53)) - return true; - if (!this._userIgnored) { - const { cwd } = this.options; - const ign = this.options.ignored; - const ignored = (ign || []).map(normalizeIgnored(cwd)); - const ignoredPaths = [...this._ignoredPaths]; - const list2 = [...ignoredPaths.map(normalizeIgnored(cwd)), ...ignored]; - this._userIgnored = anymatch(list2, void 0); - } - return this._userIgnored(path53, stats); - } - _isntIgnored(path53, stat5) { - return !this._isIgnored(path53, stat5); - } - /** - * Provides a set of common helpers and properties relating to symlink handling. - * @param path file or directory pattern being watched - */ - _getWatchHelpers(path53) { - return new WatchHelper(path53, this.options.followSymlinks, this); - } - // Directory helpers - // ----------------- - /** - * Provides directory tracking objects - * @param directory path of the directory - */ - _getWatchedDir(directory) { - const dir = sysPath2.resolve(directory); - if (!this._watched.has(dir)) - this._watched.set(dir, new DirEntry(dir, this._boundRemove)); - return this._watched.get(dir); - } - // File helpers - // ------------ - /** - * Check for read permissions: https://stackoverflow.com/a/11781404/1358405 - */ - _hasReadPermissions(stats) { - if (this.options.ignorePermissionErrors) - return true; - return Boolean(Number(stats.mode) & 256); - } - /** - * Handles emitting unlink events for - * files and directories, and via recursion, for - * files and directories within directories that are unlinked - * @param directory within which the following item is located - * @param item base path of item/directory - */ - _remove(directory, item, isDirectory) { - const path53 = sysPath2.join(directory, item); - const fullPath = sysPath2.resolve(path53); - isDirectory = isDirectory != null ? isDirectory : this._watched.has(path53) || this._watched.has(fullPath); - if (!this._throttle("remove", path53, 100)) - return; - if (!isDirectory && this._watched.size === 1) { - this.add(directory, item, true); - } - const wp = this._getWatchedDir(path53); - const nestedDirectoryChildren = wp.getChildren(); - nestedDirectoryChildren.forEach((nested) => this._remove(path53, nested)); - const parent = this._getWatchedDir(directory); - const wasTracked = parent.has(item); - parent.remove(item); - if (this._symlinkPaths.has(fullPath)) { - this._symlinkPaths.delete(fullPath); - } - let relPath = path53; - if (this.options.cwd) - relPath = sysPath2.relative(this.options.cwd, path53); - if (this.options.awaitWriteFinish && this._pendingWrites.has(relPath)) { - const event = this._pendingWrites.get(relPath).cancelWait(); - if (event === EVENTS.ADD) - return; - } - this._watched.delete(path53); - this._watched.delete(fullPath); - const eventName = isDirectory ? EVENTS.UNLINK_DIR : EVENTS.UNLINK; - if (wasTracked && !this._isIgnored(path53)) - this._emit(eventName, path53); - this._closePath(path53); - } - /** - * Closes all watchers for a path - */ - _closePath(path53) { - this._closeFile(path53); - const dir = sysPath2.dirname(path53); - this._getWatchedDir(dir).remove(sysPath2.basename(path53)); - } - /** - * Closes only file-specific watchers - */ - _closeFile(path53) { - const closers = this._closers.get(path53); - if (!closers) - return; - closers.forEach((closer) => closer()); - this._closers.delete(path53); - } - _addPathCloser(path53, closer) { - if (!closer) - return; - let list2 = this._closers.get(path53); - if (!list2) { - list2 = []; - this._closers.set(path53, list2); - } - list2.push(closer); - } - _readdirp(root, opts) { - if (this.closed) - return; - const options = { type: EVENTS.ALL, alwaysStat: true, lstat: true, ...opts, depth: 0 }; - let stream = readdirp(root, options); - this._streams.add(stream); - stream.once(STR_CLOSE, () => { - stream = void 0; - }); - stream.once(STR_END, () => { - if (stream) { - this._streams.delete(stream); - stream = void 0; - } - }); - return stream; - } -}; -function watch(paths2, options = {}) { - const watcher = new FSWatcher(options); - watcher.add(paths2); - return watcher; -} -var esm_default = { watch, FSWatcher }; - -// server/src/services/plugin-dev-watcher.ts -import { existsSync as existsSync7, readFileSync as readFileSync4, readdirSync as readdirSync2, statSync as statSync2 } from "node:fs"; -import path50 from "node:path"; -var log = logger.child({ service: "plugin-dev-watcher" }); -var DEBOUNCE_MS = 500; -function shouldIgnorePath(filename) { - if (!filename) return false; - const normalized = filename.replace(/\\/g, "/"); - const segments = normalized.split("/").filter(Boolean); - return segments.some( - (segment) => segment === "node_modules" || segment === ".git" || segment === ".vite" || segment === ".taskcore-sdk" || segment.startsWith(".") - ); -} -function resolvePluginWatchTargets(packagePath, fsDeps) { - const fileExists = fsDeps?.existsSync ?? existsSync7; - const readFile5 = fsDeps?.readFileSync ?? readFileSync4; - const readDir = fsDeps?.readdirSync ?? readdirSync2; - const statFile = fsDeps?.statSync ?? statSync2; - const absPath = path50.resolve(packagePath); - const targets = /* @__PURE__ */ new Map(); - function addWatchTarget(targetPath, recursive, kind) { - const resolved = path50.resolve(targetPath); - if (!fileExists(resolved)) return; - const inferredKind = kind ?? (statFile(resolved).isDirectory() ? "dir" : "file"); - const existing = targets.get(resolved); - if (existing) { - existing.recursive = existing.recursive || recursive; - return; - } - targets.set(resolved, { path: resolved, recursive, kind: inferredKind }); - } - function addRuntimeFilesFromDir(dirPath) { - if (!fileExists(dirPath)) return; - for (const entry of readDir(dirPath, { withFileTypes: true })) { - const entryPath = path50.join(dirPath, entry.name); - if (entry.isDirectory()) { - addRuntimeFilesFromDir(entryPath); - continue; - } - if (!entry.isFile()) continue; - if (!entry.name.endsWith(".js") && !entry.name.endsWith(".css")) continue; - addWatchTarget(entryPath, false, "file"); - } - } - const packageJsonPath = path50.join(absPath, "package.json"); - addWatchTarget(packageJsonPath, false, "file"); - if (!fileExists(packageJsonPath)) { - return [...targets.values()]; - } - let packageJson = null; - try { - packageJson = JSON.parse(readFile5(packageJsonPath, "utf8")); - } catch { - packageJson = null; - } - const entrypointPaths = [ - packageJson?.taskcorePlugin?.manifest, - packageJson?.taskcorePlugin?.worker, - packageJson?.taskcorePlugin?.ui - ].filter((value) => typeof value === "string" && value.length > 0); - if (entrypointPaths.length === 0) { - addRuntimeFilesFromDir(path50.join(absPath, "dist")); - return [...targets.values()]; - } - for (const relativeEntrypoint of entrypointPaths) { - const resolvedEntrypoint = path50.resolve(absPath, relativeEntrypoint); - if (!fileExists(resolvedEntrypoint)) continue; - const stat5 = statFile(resolvedEntrypoint); - if (stat5.isDirectory()) { - addRuntimeFilesFromDir(resolvedEntrypoint); - } else { - addWatchTarget(resolvedEntrypoint, false, "file"); - } - } - return [...targets.values()].sort((a5, b6) => a5.path.localeCompare(b6.path)); -} -function createPluginDevWatcher(lifecycle, resolvePluginPackagePath, fsDeps) { - const watchers = /* @__PURE__ */ new Map(); - const debounceTimers = /* @__PURE__ */ new Map(); - const fileExists = fsDeps?.existsSync ?? existsSync7; - function watchPlugin(pluginId, packagePath) { - if (watchers.has(pluginId)) return; - const absPath = path50.resolve(packagePath); - if (!fileExists(absPath)) { - log.warn( - { pluginId, packagePath: absPath }, - "plugin-dev-watcher: package path does not exist, skipping watch" - ); - return; - } - try { - const watcherTargets = resolvePluginWatchTargets(absPath, fsDeps); - if (watcherTargets.length === 0) { - log.warn( - { pluginId, packagePath: absPath }, - "plugin-dev-watcher: no valid watch targets found, skipping watch" - ); - return; - } - const watcher = esm_default.watch( - watcherTargets.map((target) => target.path), - { - ignoreInitial: true, - awaitWriteFinish: { - stabilityThreshold: 200, - pollInterval: 100 - }, - ignored: (watchedPath) => { - const relativePath = path50.relative(absPath, watchedPath); - return shouldIgnorePath(relativePath); - } - } - ); - watcher.on("all", (_eventName, changedPath) => { - const relativePath = path50.relative(absPath, changedPath); - if (shouldIgnorePath(relativePath)) return; - const existing = debounceTimers.get(pluginId); - if (existing) clearTimeout(existing); - debounceTimers.set( - pluginId, - setTimeout(() => { - debounceTimers.delete(pluginId); - log.info( - { pluginId, changedFile: relativePath || path50.basename(changedPath) }, - "plugin-dev-watcher: file change detected, restarting worker" - ); - lifecycle.restartWorker(pluginId).catch((err) => { - log.warn( - { - pluginId, - err: err instanceof Error ? err.message : String(err) - }, - "plugin-dev-watcher: failed to restart worker after file change" - ); - }); - }, DEBOUNCE_MS) - ); - }); - watcher.on("error", (err) => { - log.warn( - { - pluginId, - packagePath: absPath, - err: err instanceof Error ? err.message : String(err) - }, - "plugin-dev-watcher: watcher error, stopping watch for this plugin" - ); - unwatchPlugin(pluginId); - }); - watchers.set(pluginId, watcher); - log.info( - { - pluginId, - packagePath: absPath, - watchTargets: watcherTargets.map((target) => ({ - path: target.path, - kind: target.kind - })) - }, - "plugin-dev-watcher: watching local plugin for changes" - ); - } catch (err) { - log.warn( - { - pluginId, - packagePath: absPath, - err: err instanceof Error ? err.message : String(err) - }, - "plugin-dev-watcher: failed to start file watcher" - ); - } - } - function unwatchPlugin(pluginId) { - const pluginWatcher = watchers.get(pluginId); - if (pluginWatcher) { - void pluginWatcher.close(); - watchers.delete(pluginId); - } - const timer2 = debounceTimers.get(pluginId); - if (timer2) { - clearTimeout(timer2); - debounceTimers.delete(pluginId); - } - } - function close() { - lifecycle.off("plugin.loaded", handlePluginLoaded); - lifecycle.off("plugin.enabled", handlePluginEnabled); - lifecycle.off("plugin.disabled", handlePluginDisabled); - lifecycle.off("plugin.unloaded", handlePluginUnloaded); - for (const [pluginId] of watchers) { - unwatchPlugin(pluginId); - } - } - async function watchLocalPluginById(pluginId) { - if (!resolvePluginPackagePath) return; - try { - const packagePath = await resolvePluginPackagePath(pluginId); - if (!packagePath) return; - watchPlugin(pluginId, packagePath); - } catch (err) { - log.warn( - { - pluginId, - err: err instanceof Error ? err.message : String(err) - }, - "plugin-dev-watcher: failed to resolve plugin package path" - ); - } - } - function handlePluginLoaded(payload2) { - void watchLocalPluginById(payload2.pluginId); - } - function handlePluginEnabled(payload2) { - void watchLocalPluginById(payload2.pluginId); - } - function handlePluginDisabled(payload2) { - unwatchPlugin(payload2.pluginId); - } - function handlePluginUnloaded(payload2) { - unwatchPlugin(payload2.pluginId); - } - lifecycle.on("plugin.loaded", handlePluginLoaded); - lifecycle.on("plugin.enabled", handlePluginEnabled); - lifecycle.on("plugin.disabled", handlePluginDisabled); - lifecycle.on("plugin.unloaded", handlePluginUnloaded); - return { - watch: watchPlugin, - unwatch: unwatchPlugin, - close - }; -} - -// server/src/services/plugin-host-service-cleanup.ts -function createPluginHostServiceCleanup(lifecycle, disposers) { - const runDispose = (pluginId, remove = false) => { - const dispose = disposers.get(pluginId); - if (!dispose) return; - dispose(); - if (remove) { - disposers.delete(pluginId); - } - }; - const handleWorkerStopped = ({ pluginId }) => { - runDispose(pluginId); - }; - const handlePluginUnloaded = ({ pluginId }) => { - runDispose(pluginId, true); - }; - lifecycle.on("plugin.worker_stopped", handleWorkerStopped); - lifecycle.on("plugin.unloaded", handlePluginUnloaded); - return { - handleWorkerEvent(event) { - if (event.type === "plugin.worker.crashed") { - runDispose(event.pluginId); - } - }, - disposeAll() { - for (const dispose of disposers.values()) { - dispose(); - } - disposers.clear(); - }, - teardown() { - lifecycle.off("plugin.worker_stopped", handleWorkerStopped); - lifecycle.off("plugin.unloaded", handlePluginUnloaded); - } - }; -} - -// server/src/vite-html-renderer.ts -import fs39 from "node:fs"; -import path51 from "node:path"; -var WATCHER_EVENTS = ["add", "change", "unlink"]; -var MAIN_ENTRY_TAG = ''; -var VITE_CLIENT_TAG = ''; -var REACT_REFRESH_PREAMBLE = ``; -function injectViteDevPreamble(html3) { - let injectedHtml = html3; - if (!injectedHtml.includes('"/@react-refresh"') && !injectedHtml.includes("'/@react-refresh'")) { - injectedHtml = injectedHtml.includes("") ? injectedHtml.replace("", ` ${REACT_REFRESH_PREAMBLE} - `) : `${REACT_REFRESH_PREAMBLE} -${injectedHtml}`; - } - if (injectedHtml.includes(VITE_CLIENT_TAG)) return injectedHtml; - if (injectedHtml.includes(MAIN_ENTRY_TAG)) { - return injectedHtml.replace(MAIN_ENTRY_TAG, `${VITE_CLIENT_TAG} - ${MAIN_ENTRY_TAG}`); - } - return injectedHtml.replace("", ` ${VITE_CLIENT_TAG} - `); -} -function createCachedViteHtmlRenderer(opts) { - const uiRoot = path51.resolve(opts.uiRoot); - const templatePath = path51.resolve(uiRoot, "index.html"); - const brandHtml = opts.brandHtml ?? ((html3) => html3); - let cachedHtml = null; - function loadHtml() { - if (cachedHtml === null) { - const rawTemplate = fs39.readFileSync(templatePath, "utf-8"); - cachedHtml = injectViteDevPreamble(brandHtml(rawTemplate)); - } - return cachedHtml; - } - function invalidate() { - cachedHtml = null; - } - function onWatchEvent(filePath) { - const resolvedPath2 = path51.resolve(filePath); - if (resolvedPath2 === templatePath || resolvedPath2.startsWith(`${uiRoot}${path51.sep}`)) { - invalidate(); - } - } - for (const eventName of WATCHER_EVENTS) { - opts.vite.watcher?.on?.(eventName, onWatchEvent); - } - return { - render() { - return Promise.resolve(loadHtml()); - }, - dispose() { - for (const eventName of WATCHER_EVENTS) { - opts.vite.watcher?.off?.(eventName, onWatchEvent); - } - } - }; -} - -// server/src/app.ts -var FEEDBACK_EXPORT_FLUSH_INTERVAL_MS = 5e3; -var VITE_DEV_ASSET_PREFIXES = [ - "/@fs/", - "/@id/", - "/@react-refresh", - "/@vite/", - "/assets/", - "/node_modules/", - "/src/" -]; -var VITE_DEV_STATIC_PATHS = /* @__PURE__ */ new Set([ - "/apple-touch-icon.png", - "/favicon-16x16.png", - "/favicon-32x32.png", - "/favicon.ico", - "/favicon.svg", - "/site.webmanifest" -]); -function resolveViteHmrPort(serverPort) { - if (serverPort <= 55535) { - return serverPort + 1e4; - } - return Math.max(1024, serverPort - 1e4); -} -function shouldServeViteDevHtml(req) { - const pathname = req.path; - if (VITE_DEV_STATIC_PATHS.has(pathname)) return false; - if (VITE_DEV_ASSET_PREFIXES.some((prefix) => pathname.startsWith(prefix))) return false; - return req.accepts(["html"]) === "html"; -} -async function createApp(db, opts) { - const app = (0, import_express25.default)(); - const pluginsEnabled = process.env.TASKCORE_PLUGINS_ENABLED !== "false"; - app.use(import_express25.default.json({ - // Company import/export payloads can inline full portable packages. - limit: "10mb", - verify: (req, _res, buf) => { - req.rawBody = buf; - } - })); - app.use(httpLogger); - const privateHostnameGateEnabled = opts.deploymentMode === "authenticated" && opts.deploymentExposure === "private"; - const privateHostnameAllowSet = resolvePrivateHostnameAllowSet({ - allowedHostnames: opts.allowedHostnames, - bindHost: opts.bindHost - }); - app.use( - privateHostnameGuard({ - enabled: privateHostnameGateEnabled, - allowedHostnames: opts.allowedHostnames, - bindHost: opts.bindHost - }) - ); - app.use( - actorMiddleware(db, { - deploymentMode: opts.deploymentMode, - resolveSession: opts.resolveSession - }) - ); - app.get("/api/auth/get-session", (req, res) => { - if (req.actor.type !== "board" || !req.actor.userId) { - res.status(401).json({ error: "Unauthorized" }); - return; - } - res.json({ - session: { - id: `taskcore:${req.actor.source}:${req.actor.userId}`, - userId: req.actor.userId - }, - user: { - id: req.actor.userId, - email: null, - name: req.actor.source === "local_implicit" ? "Local Board" : null - } - }); - }); - if (opts.betterAuthHandler) { - app.all("/api/auth/{*authPath}", opts.betterAuthHandler); - } - app.use(llmRoutes(db)); - const api = (0, import_express25.Router)(); - api.use(boardMutationGuard()); - api.use( - "/health", - healthRoutes(db, { - deploymentMode: opts.deploymentMode, - deploymentExposure: opts.deploymentExposure, - authReady: opts.authReady, - companyDeletionEnabled: opts.companyDeletionEnabled - }) - ); - api.use("/companies", companyRoutes(db, opts.storageService)); - api.use(companySkillRoutes(db)); - api.use(agentRoutes(db)); - api.use(assetRoutes(db, opts.storageService)); - api.use(projectRoutes(db)); - api.use(issueRoutes(db, opts.storageService, { - feedbackExportService: opts.feedbackExportService - })); - api.use(routineRoutes(db)); - api.use(executionWorkspaceRoutes(db)); - api.use(goalRoutes(db)); - api.use(approvalRoutes(db)); - api.use(secretRoutes(db)); - api.use(costRoutes(db)); - api.use(activityRoutes(db)); - api.use(dashboardRoutes(db)); - api.use(sidebarBadgeRoutes(db)); - api.use(sidebarPreferenceRoutes(db)); - api.use(inboxDismissalRoutes(db)); - api.use(instanceSettingsRoutes(db)); - const hostServicesDisposers = /* @__PURE__ */ new Map(); - const workerManager = createPluginWorkerManager(); - const pluginRegistry = pluginRegistryService(db); - const eventBus = createPluginEventBus(); - setPluginEventBus(eventBus); - const jobStore = pluginJobStore(db); - const lifecycle = pluginLifecycleManager(db, { workerManager }); - const scheduler = createPluginJobScheduler({ - db, - jobStore, - workerManager - }); - const toolDispatcher = createPluginToolDispatcher({ - workerManager, - lifecycleManager: lifecycle, - db - }); - const jobCoordinator = createPluginJobCoordinator({ - db, - lifecycle, - scheduler, - jobStore - }); - const hostServiceCleanup = createPluginHostServiceCleanup(lifecycle, hostServicesDisposers); - let viteHtmlRenderer = null; - const loader = pluginLoader( - db, - { localPluginDir: opts.localPluginDir ?? DEFAULT_LOCAL_PLUGIN_DIR }, - { - workerManager, - eventBus, - jobScheduler: scheduler, - jobStore, - toolDispatcher, - lifecycleManager: lifecycle, - instanceInfo: { - instanceId: opts.instanceId ?? "default", - hostVersion: opts.hostVersion ?? "0.0.0" - }, - buildHostHandlers: (pluginId, manifest) => { - const notifyWorker = (method, params) => { - const handle = workerManager.getWorker(pluginId); - if (handle) handle.notify(method, params); - }; - const services = buildHostServices(db, pluginId, manifest.id, eventBus, notifyWorker); - hostServicesDisposers.set(pluginId, () => services.dispose()); - return createHostClientHandlers({ - pluginId, - capabilities: manifest.capabilities, - services - }); - } - } - ); - api.use( - pluginRoutes( - db, - loader, - { scheduler, jobStore }, - { workerManager }, - { toolDispatcher }, - { workerManager } - ) - ); - api.use(adapterRoutes()); - api.use( - accessRoutes(db, { - deploymentMode: opts.deploymentMode, - deploymentExposure: opts.deploymentExposure, - bindHost: opts.bindHost, - allowedHostnames: opts.allowedHostnames - }) - ); - app.use("/api", api); - app.use("/api", (_req, res) => { - res.status(404).json({ error: "API route not found" }); - }); - app.use(pluginUiStaticRoutes(db, { - localPluginDir: opts.localPluginDir ?? DEFAULT_LOCAL_PLUGIN_DIR - })); - const __dirname4 = path52.dirname(fileURLToPath19(import.meta.url)); - if (opts.uiMode === "static") { - const candidates = [ - path52.resolve(__dirname4, "../ui-dist"), - path52.resolve(__dirname4, "../../ui/dist") - ]; - const uiDist = candidates.find((p5) => fs40.existsSync(path52.join(p5, "index.html"))); - if (uiDist) { - const indexHtml = applyUiBranding(fs40.readFileSync(path52.join(uiDist, "index.html"), "utf-8")); - app.use(import_express25.default.static(uiDist)); - app.get(/.*/, (_req, res) => { - res.status(200).set("Content-Type", "text/html").end(indexHtml); - }); - } else { - console.warn("[taskcore] UI dist not found; running in API-only mode"); - } - } - if (opts.uiMode === "vite-dev") { - const uiRoot = path52.resolve(__dirname4, "../../ui"); - const hmrPort = resolveViteHmrPort(opts.serverPort); - const { createServer: createViteServer } = await import("vite"); - const vite = await createViteServer({ - root: uiRoot, - appType: "custom", - server: { - middlewareMode: true, - hmr: { - host: opts.bindHost, - port: hmrPort, - clientPort: hmrPort - }, - allowedHosts: privateHostnameGateEnabled ? Array.from(privateHostnameAllowSet) : void 0 - } - }); - viteHtmlRenderer = createCachedViteHtmlRenderer({ - vite, - uiRoot, - brandHtml: applyUiBranding - }); - const renderViteHtml = viteHtmlRenderer; - app.get(/.*/, async (req, res, next) => { - if (!shouldServeViteDevHtml(req)) { - next(); - return; - } - try { - const html3 = await renderViteHtml.render(req.originalUrl); - res.status(200).set({ "Content-Type": "text/html" }).end(html3); - } catch (err) { - next(err); - } - }); - app.use(vite.middlewares); - } - app.use(errorHandler); - if (pluginsEnabled) { - jobCoordinator.start(); - scheduler.start(); - void toolDispatcher.initialize().catch((err) => { - logger.error({ err }, "Failed to initialize plugin tool dispatcher"); - }); - } - const feedbackExportTimer = opts.feedbackExportService ? setInterval(() => { - void opts.feedbackExportService?.flushPendingFeedbackTraces().catch((err) => { - logger.error({ err }, "Failed to flush pending feedback exports"); - }); - }, FEEDBACK_EXPORT_FLUSH_INTERVAL_MS) : null; - feedbackExportTimer?.unref?.(); - if (opts.feedbackExportService) { - void opts.feedbackExportService.flushPendingFeedbackTraces().catch((err) => { - logger.error({ err }, "Failed to flush pending feedback exports"); - }); - } - const devWatcher = pluginsEnabled && opts.uiMode === "vite-dev" ? createPluginDevWatcher( - lifecycle, - async (pluginId) => (await pluginRegistry.getById(pluginId))?.packagePath ?? null - ) : null; - if (pluginsEnabled) { - void loader.loadAll().then((result) => { - if (!result) return; - for (const loaded of result.results) { - if (devWatcher && loaded.success && loaded.plugin.packagePath) { - devWatcher.watch(loaded.plugin.id, loaded.plugin.packagePath); - } - } - }).catch((err) => { - logger.error({ err }, "Failed to load ready plugins on startup"); - }); - } - process.once("exit", () => { - if (feedbackExportTimer) clearInterval(feedbackExportTimer); - devWatcher?.close(); - viteHtmlRenderer?.dispose(); - hostServiceCleanup.disposeAll(); - hostServiceCleanup.teardown(); - }); - process.once("beforeExit", () => { - void flushPluginLogBuffer(); - }); - return app; -} - -// server/src/services/feedback-share-client.ts -import { gzipSync } from "node:zlib"; -var DEFAULT_FEEDBACK_EXPORT_BACKEND_URL = "https://telemetry.taskcore.ing"; -function buildFeedbackShareObjectKey(bundle, exportedAt) { - const year3 = String(exportedAt.getUTCFullYear()); - const month = String(exportedAt.getUTCMonth() + 1).padStart(2, "0"); - const day2 = String(exportedAt.getUTCDate()).padStart(2, "0"); - return `feedback-traces/${bundle.companyId}/${year3}/${month}/${day2}/${bundle.exportId ?? bundle.traceId}.json`; -} -function createFeedbackTraceShareClientFromConfig(config3) { - const baseUrl = config3.feedbackExportBackendUrl?.trim() || DEFAULT_FEEDBACK_EXPORT_BACKEND_URL; - const token = config3.feedbackExportBackendToken?.trim(); - const endpoint = new URL("/feedback-traces", baseUrl).toString(); - return { - async uploadTraceBundle(bundle) { - const exportedAt = /* @__PURE__ */ new Date(); - const objectKey = buildFeedbackShareObjectKey(bundle, exportedAt); - const requestBody = JSON.stringify({ - objectKey, - exportedAt: exportedAt.toISOString(), - bundle - }); - const response = await fetch(endpoint, { - method: "POST", - headers: { - "content-type": "application/json", - ...token ? { authorization: `Bearer ${token}` } : {} - }, - body: JSON.stringify({ - encoding: "gzip+base64+json", - payload: gzipSync(requestBody).toString("base64") - }) - }); - if (!response.ok) { - const detail = await response.text().catch(() => ""); - throw new Error(detail.trim() || `Feedback trace upload failed with HTTP ${response.status}`); - } - const payload2 = await response.json().catch(() => null); - return { - objectKey: typeof payload2?.objectKey === "string" && payload2.objectKey.trim().length > 0 ? payload2.objectKey : objectKey - }; - } - }; -} - -// server/src/vercel.ts -function isVercelRuntime() { - return process.env.VERCEL === "1" || process.env.NOW === "1"; -} -function applyVercelDefaults() { - if (!isVercelRuntime()) return; - const defaults = { - TASKCORE_DEPLOYMENT_MODE: "authenticated", - TASKCORE_DEPLOYMENT_EXPOSURE: "public", - SERVE_UI: "false", - TASKCORE_PLUGINS_ENABLED: "false", - TASKCORE_DB_BACKUP_ENABLED: "false", - HEARTBEAT_SCHEDULER_ENABLED: "false", - TASKCORE_STORAGE_LOCAL_DIR: "/tmp/taskcore-storage", - TASKCORE_LOG_DIR: "/tmp/taskcore-logs", - TASKCORE_PG_MAX_CONNECTIONS: "5" - }; - for (const [key, value] of Object.entries(defaults)) { - if (process.env[key] === void 0) { - process.env[key] = value; - } - } -} -function assertVercelConfig(config3) { - if (isVercelRuntime() && config3.deploymentMode !== "authenticated") { - throw new Error( - "Taskcore on Vercel requires TASKCORE_DEPLOYMENT_MODE=authenticated (a public, unauthenticated board is not allowed)." - ); - } - if (isVercelRuntime() && config3.deploymentExposure !== "public") { - throw new Error( - "Taskcore on Vercel requires TASKCORE_DEPLOYMENT_EXPOSURE=public." - ); - } - if (config3.deploymentMode === "authenticated" && config3.deploymentExposure === "public") { - if (config3.authBaseUrlMode !== "explicit" || !config3.authPublicBaseUrl) { - throw new Error( - "Authenticated public exposure requires auth.baseUrlMode=explicit and a public URL. Set TASKCORE_AUTH_PUBLIC_BASE_URL (or BETTER_AUTH_URL) to the deployment URL (e.g. https://taskcore-.vercel.app)." - ); - } - } -} -async function createAppForServerless(config3, db) { - let authReady = config3.deploymentMode === "local_trusted"; - let betterAuthHandler; - let resolveSession; - if (config3.deploymentMode === "authenticated") { - const { - createBetterAuthHandler: createBetterAuthHandler2, - createBetterAuthInstance: createBetterAuthInstance2, - deriveAuthTrustedOrigins: deriveAuthTrustedOrigins2, - resolveBetterAuthSession: resolveBetterAuthSession2 - } = await Promise.resolve().then(() => (init_better_auth(), better_auth_exports)); - const derivedTrustedOrigins = deriveAuthTrustedOrigins2(config3); - const envTrustedOrigins = (process.env.BETTER_AUTH_TRUSTED_ORIGINS ?? "").split(",").map((value) => value.trim()).filter((value) => value.length > 0); - const effectiveTrustedOrigins = Array.from(/* @__PURE__ */ new Set([...derivedTrustedOrigins, ...envTrustedOrigins])); - logger.info( - { - authBaseUrlMode: config3.authBaseUrlMode, - authPublicBaseUrl: config3.authPublicBaseUrl ?? null, - trustedOrigins: effectiveTrustedOrigins - }, - "Authenticated mode auth origin configuration (serverless)" - ); - const auth = createBetterAuthInstance2(db, config3, effectiveTrustedOrigins); - betterAuthHandler = createBetterAuthHandler2(auth); - resolveSession = (req) => resolveBetterAuthSession2(auth, req); - await initializeBoardClaimChallenge(db, { deploymentMode: config3.deploymentMode }); - authReady = true; - } - const storageService = createStorageServiceFromConfig(config3); - const feedback = feedbackService(db, { - shareClient: createFeedbackTraceShareClientFromConfig(config3) - }); - return createApp(db, { - uiMode: "none", - serverPort: 3e3, - storageService, - feedbackExportService: feedback, - deploymentMode: config3.deploymentMode, - deploymentExposure: config3.deploymentExposure, - allowedHostnames: config3.allowedHostnames, - bindHost: config3.host, - authReady, - companyDeletionEnabled: config3.companyDeletionEnabled, - betterAuthHandler, - resolveSession - }); -} -async function boot() { - applyVercelDefaults(); - const config3 = loadConfig(); - if (!config3.databaseUrl) { - throw new Error( - "Taskcore on Vercel requires an external PostgreSQL connection. Set DATABASE_URL (or the Vercel Postgres / RDS environment: POSTGRES_URL or PGHOST/PGDATABASE/PGUSER/PGPASSWORD)." - ); - } - assertVercelConfig(config3); - const maxConnections = Math.max(1, Number(process.env.TASKCORE_PG_MAX_CONNECTIONS) || 10); - const prepareDisabled = process.env.TASKCORE_PG_PREPARE !== void 0 ? process.env.TASKCORE_PG_PREPARE === "true" : isVercelRuntime(); - const db = createDb(config3.databaseUrl, { - max: maxConnections, - ...prepareDisabled ? { prepare: false } : {} - }); - logger.info( - { - deploymentMode: config3.deploymentMode, - deploymentExposure: config3.deploymentExposure, - storageProvider: config3.storageProvider, - databaseConfigured: true - }, - "Booting Taskcore serverless app" - ); - return createAppForServerless(config3, db); -} -var appPromise = null; -async function taskcoreVercelHandler(req, res) { - const app = await (appPromise ??= boot().catch((err) => { - appPromise = null; - throw err; - })); - app(req, res); -} -export { - taskcoreVercelHandler as default -}; diff --git a/doc/DEPLOYMENT-MODES.md b/doc/DEPLOYMENT-MODES.md index ada4973..c1137fb 100644 --- a/doc/DEPLOYMENT-MODES.md +++ b/doc/DEPLOYMENT-MODES.md @@ -142,3 +142,5 @@ This prevents lockout when a user migrates from long-running local trusted usage - implementation plan: `doc/plans/deployment-auth-mode-consolidation.md` - V1 contract: `doc/SPEC-implementation.md` - operator workflows: `doc/DEVELOPING.md` and `doc/CLI.md` +- Vercel deployment: `doc/VERCEL.md` + diff --git a/doc/VERCEL.md b/doc/VERCEL.md new file mode 100644 index 0000000..9fa2376 --- /dev/null +++ b/doc/VERCEL.md @@ -0,0 +1,97 @@ +# Deploying Taskcore to Vercel + +Status: Supported deployment target +Date: 2026-07-31 + +## 1. Overview + +Taskcore can run as a Vercel project with three deployable parts: + +| Part | What deploys | Where it comes from | +|---|---|---| +| **API** | A single Node serverless function at `api/index.js` | `server/src/vercel.ts` bundled by `scripts/build-vercel-function.mjs` (esbuild) | +| **UI** | Static SPA build in `ui/dist` | `pnpm --filter @taskcore/ui build` | +| **Database** | External PostgreSQL | Vercel Postgres, Neon, Supabase, or any reachable Postgres via `DATABASE_URL` | + +`vercel.json` wires the three together: + +- `buildCommand`: `pnpm vercel:build` — builds workspace packages, the UI, then the serverless bundle +- `outputDirectory`: `ui/dist` — static UI served from the build output +- `rewrites`: `/api/*` goes to the function; everything else falls back to `index.html` (SPA routing) +- `functions.api/index.js.maxDuration`: 60s so a cold boot (Express + better-auth + DB pool) completes before the first response + +The Express app serves the API only on Vercel (`SERVE_UI=false`, `uiMode: "none"`). All UI paths are served statically by the platform. + +## 2. What Works / What Does Not + +Works on Vercel: + +- Full `/api/*` surface (board routes, agent routes, better-auth `/api/auth/*`) +- Static board UI at the deployment root +- External PostgreSQL (`DATABASE_URL`, `POSTGRES_URL`/`POSTGRES_URL_NON_POOLING`, or `PGHOST`/`PGDATABASE`/`PGUSER`/`PGPASSWORD`) +- S3 storage via `TASKCORE_STORAGE_PROVIDER=s3` (see `doc/DATABASE.md`-adjacent storage docs) + +Not available in the serverless runtime (the Vercel handler disables these): + +- Embedded PostgreSQL / PGlite — `DATABASE_URL` is **required** (`server/src/vercel.ts` fails boot without it) +- Long-lived background work: heartbeat scheduler, routine scheduler, database backups, plugin workers +- Live events WebSocket channel (polling endpoints still work) +- Local-disk storage (`/tmp` is ephemeral — uploads/assets are lost between cold starts) +- Local/embedded agent adapters (Claude, Codex, etc. run as processes — they cannot run in a serverless function) + +## 3. Prerequisites + +- Repo pushed to GitHub, imported into a Vercel project +- An external PostgreSQL database (Vercel Postgres storage is the simplest path — it sets `POSTGRES_URL` automatically) +- Node.js 20+ and pnpm 9+ for local builds + +## 4. Required Environment Variables + +| Variable | Required | Purpose | +|---|---|---| +| `DATABASE_URL` (or `POSTGRES_URL` / `POSTGRES_URL_NON_POOLING` / `PGHOST`+`PGDATABASE`+`PGUSER`+`PGPASSWORD`) | Yes | External Postgres connection | +| `BETTER_AUTH_SECRET` (or `TASKCORE_AGENT_JWT_SECRET`) | Yes | Auth cookie/JWT signing secret | +| `TASKCORE_AUTH_PUBLIC_BASE_URL` (or `BETTER_AUTH_URL`) | Yes | Public deployment URL, e.g. `https://taskcore-.vercel.app` | + +Defaults applied automatically when `VERCEL=1` (see `applyVercelDefaults` in `server/src/vercel.ts`): + +| Variable | Default | Notes | +|---|---|---| +| `TASKCORE_DEPLOYMENT_MODE` | `authenticated` | Public unauthenticated boards are rejected | +| `TASKCORE_DEPLOYMENT_EXPOSURE` | `public` | | +| `SERVE_UI` | `false` | UI is served statically by Vercel | +| `TASKCORE_PLUGINS_ENABLED` | `false` | Plugin workers cannot run serverless | +| `TASKCORE_DB_BACKUP_ENABLED` | `false` | | +| `HEARTBEAT_SCHEDULER_ENABLED` | `false` | | +| `TASKCORE_STORAGE_LOCAL_DIR` | `/tmp/taskcore-storage` | Ephemeral — set S3 storage for durable uploads | +| `TASKCORE_PG_MAX_CONNECTIONS` | `5` | Keep bounded for serverless concurrency | + +Recommended: `TASKCORE_STORAGE_PROVIDER=s3` with `TASKCORE_STORAGE_S3_BUCKET`, `TASKCORE_STORAGE_S3_REGION`, and `AWS_ACCESS_KEY_ID`/`AWS_SECRET_ACCESS_KEY` so attachments and assets survive cold starts. + +## 5. Deploy Steps + +1. Import the repo into Vercel (framework preset: **Other**; the repo's `vercel.json` overrides settings). +2. Create an external Postgres (or attach Vercel Postgres) and set the env vars above, including the deployment URL in `TASKCORE_AUTH_PUBLIC_BASE_URL`. +3. Deploy. `pnpm vercel:build` runs on Vercel: workspace packages → UI (`ui/dist`) → serverless bundle (`api/index.js`). +4. Migrations are **not** applied by the serverless runtime. Before first use, apply the schema once: + ```sh + DATABASE_URL=... pnpm db:migrate + ``` +5. Sign in with a real user at `https:///api/auth/sign-in/email` (via the UI login page) — the first admin becomes the instance admin (board claim flow in `authenticated` mode). + +## 6. Local Verification + +```sh +pnpm vercel:build # full production build (workspace + UI + function bundle) +vercel dev # run the deployed layout locally (API function + static UI) +``` + +`vercel build` locally validates the exact layout (`ui/dist` static output + `api/index.js` function) that the platform will serve. + +## 7. Repository Files + +- `vercel.json` — platform config (build, routes, function limits) +- `server/src/vercel.ts` — serverless Express handler with Vercel runtime defaults and config guards +- `scripts/build-vercel-function.mjs` — esbuild bundler for `api/index.js` +- `packages/shared/src/vercel-postgres.ts` — `DATABASE_URL`/`POSTGRES_URL`/`PGHOST` connection resolution +- `api/index.js` — generated bundle (gitignored; built during `vercel:build`) diff --git a/package.json b/package.json index a8c8d40..c3280f3 100644 --- a/package.json +++ b/package.json @@ -12,6 +12,7 @@ "dev:server": "pnpm --filter @taskcore/server dev", "dev:ui": "pnpm --filter @taskcore/ui dev", "build": "pnpm run preflight:workspace-links && pnpm -r build", + "vercel:build": "pnpm run preflight:workspace-links && pnpm -r build && node scripts/build-vercel-function.mjs", "typecheck": "pnpm run preflight:workspace-links && pnpm -r typecheck", "test": "pnpm run test:run", "test:watch": "pnpm run preflight:workspace-links && vitest", diff --git a/scripts/build-vercel-function.mjs b/scripts/build-vercel-function.mjs index 74522a4..71e1d5f 100644 --- a/scripts/build-vercel-function.mjs +++ b/scripts/build-vercel-function.mjs @@ -31,7 +31,7 @@ await mkdir(path.dirname(outfile), { recursive: true }); const serverPkg = JSON.parse( readFileSync(path.join(repoRoot, "server/package.json"), "utf8"), -) as { version?: string }; +); const nativeExternal = [ "sharp", @@ -43,6 +43,45 @@ const nativeExternal = [ "jsdom", ]; +/** + * Keep every npm dependency external so the bundle stays ESM-clean (no + * esbuild CJS `require` shims that break in the Vercel Node runtime) and so + * Vercel's file tracer can include them from node_modules. Workspace + * packages (`@taskcore/*`) resolve to TypeScript source outside node_modules + * and stay bundled, which is the whole point of the single-file function. + */ +const externalizeNodeModules = { + name: "externalize-node-modules", + setup(build) { + // One shared verdict per package name so concurrent importers agree on + // external vs bundled (esbuild processes resolve callbacks in batches). + const verdicts = new Map(); + const resolveVerdict = (args) => { + const existing = verdicts.get(args.path); + if (existing) return existing; + const verdict = build + .resolve(args.path, { + importer: args.importer, + resolveDir: args.resolveDir, + kind: args.kind, + }) + .then((result) => { + if (result.errors.length > 0) { + return { errors: result.errors }; + } + if (result.path.includes("/node_modules/")) { + return { path: args.path, external: true }; + } + return null; + }) + .finally(() => verdicts.delete(args.path)); + verdicts.set(args.path, verdict); + return verdict; + }; + build.onResolve({ filter: /^[^./]/ }, (args) => resolveVerdict(args)); + }, +}; + try { await build({ entryPoints: [entry], @@ -52,6 +91,7 @@ try { format: "esm", target: "node20", external: nativeExternal, + plugins: [externalizeNodeModules], logLevel: "info", legalComments: "none", define: { diff --git a/vercel.json b/vercel.json new file mode 100644 index 0000000..aea0b21 --- /dev/null +++ b/vercel.json @@ -0,0 +1,17 @@ +{ + "$schema": "https://openapi.vercel.sh/vercel.json", + "framework": null, + "installCommand": "pnpm install --frozen-lockfile", + "buildCommand": "pnpm vercel:build", + "outputDirectory": "ui/dist", + "functions": { + "api/index.js": { + "maxDuration": 60 + } + }, + "rewrites": [ + { "source": "/api/(.*)", "destination": "/api/index.js" }, + { "source": "/api", "destination": "/api/index.js" }, + { "source": "/(.*)", "destination": "/index.html" } + ] +}